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 * $Id: class.ilObjFolderGUI.php 25134 2010-08-13 14:22:11Z smeyer $ * -* @ilCtrl_Calls ilBlogExerciseGUI: +* @ilCtrl_Calls ilBlogExerciseGUI: */ class ilBlogExerciseGUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - protected $node_id; // [int] - protected $ass_id; // [int] - protected $file; // [string] - - public function __construct($a_node_id) - { - global $DIC; + protected $node_id; // [int] + protected $ass_id; // [int] + protected $file; // [string] + + public function __construct($a_node_id) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->user = $DIC->user(); - $this->lng = $DIC->language(); - $this->node_id = $a_node_id; - $this->ass_id = (int)$_GET["ass"]; - $this->file = trim(ilUtil::stripSlashes($_GET["file"])); - } - - function executeCommand() - { - $ilCtrl = $this->ctrl; - - if(!$this->ass_id) - { - $this->ctrl->returnToParent($this); - } - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd(); - - switch($next_class) - { - default: - $this->$cmd(); - break; - } - - return true; - } - - public static function checkExercise($a_node_id) - { - global $DIC; + $this->ctrl = $DIC->ctrl(); + $this->user = $DIC->user(); + $this->lng = $DIC->language(); + $this->node_id = $a_node_id; + $this->ass_id = (int) $_GET["ass"]; + $this->file = trim(ilUtil::stripSlashes($_GET["file"])); + } + + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + if (!$this->ass_id) { + $this->ctrl->returnToParent($this); + } + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd(); + + switch ($next_class) { + default: + $this->$cmd(); + break; + } + + return true; + } + + public static function checkExercise($a_node_id) + { + global $DIC; - $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); - } - } - } + $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('

', "\n", $snippet); - $snippet = str_replace('', "\n", $snippet); - - return trim(strip_tags($snippet)); - } - - - // keywords - - public function getMDSection() - { - // general section available? - include_once 'Services/MetaData/classes/class.ilMD.php'; - $md_obj = new ilMD($this->getBlogId(), $this->getId(), "blp"); - if(!is_object($md_section = $md_obj->getGeneral())) - { - $md_section = $md_obj->addGeneral(); - $md_section->save(); - } - - return $md_section; - } - - public function updateKeywords(array $keywords) - { - $ilUser = $this->user; - - // language is not "used" anywhere - $ulang = $ilUser->getLanguage(); - $keywords = array($ulang=>$keywords); - - include_once("./Services/MetaData/classes/class.ilMDKeyword.php"); - ilMDKeyword::updateKeywords($this->getMDSection(), $keywords); - } - - public static function getKeywords($a_obj_id, $a_posting_id) - { - include_once("./Services/MetaData/classes/class.ilMDKeyword.php"); - return ilMDKeyword::lookupKeywords($a_obj_id, $a_posting_id); - } - - /** - * Handle news item - * - * @param bool $a_update - */ - public function handleNews($a_update = false) - { - $lng = $this->lng; - $ilUser = $this->user; - - // see ilWikiPage::updateNews() - - if (!$this->getActive()) - { - return; - } - - include_once("./Services/News/classes/class.ilNewsItem.php"); - $news_item = null; - - // try to re-use existing news item - if((bool)$a_update) - { - // get last news item of the day (if existing) - $news_id = ilNewsItem::getLastNewsIdForContext( - $this->getBlogId(), - "blog", - $this->getId(), - $this->getParentType(), - true - ); - if($news_id > 0) - { - $news_item = new ilNewsItem($news_id); - } - } - - // create new news item - if(!$news_item) - { - $news_set = new ilSetting("news"); - $default_visibility = $news_set->get("default_visibility", "users"); - - $news_item = new ilNewsItem(); - $news_item->setContext( - $this->getBlogId(), - "blog", - $this->getId(), - $this->getParentType() - ); - $news_item->setPriority(NEWS_NOTICE); - $news_item->setVisibility($default_visibility); - } - - // news author - $news_item->setUserId($ilUser->getId()); - - - // news title/content - - $news_item->setTitle($this->getTitle()); - - $content = $a_update - ? "blog_news_posting_updated" - : "blog_news_posting_published"; - - // news "author" - include_once "Services/User/classes/class.ilUserUtil.php"; - $content = sprintf($lng->txt($content), ilUserUtil::getNamePresentation($ilUser->getId())); - - // posting author[s] - $contributors = array(); - foreach(self::getPageContributors($this->getParentType(), $this->getId()) as $user) - { - $contributors[] = $user["user_id"]; - } - if(sizeof($contributors) > 1 || !in_array($this->getAuthor(), $contributors)) - { - // original author should come first? - $authors = array(ilUserUtil::getNamePresentation($this->getAuthor())); - foreach($contributors as $user_id) - { - if($user_id != $this->getAuthor()) - { - $authors[] = ilUserUtil::getNamePresentation($user_id); - } - } - $content .= "\n".sprintf($lng->txt("blog_news_posting_authors"), implode(", ", $authors)); - } - - $news_item->setContentTextIsLangVar(false); - $news_item->setContent($content); - - include_once "Modules/Blog/classes/class.ilBlogPostingGUI.php"; - $snippet = ilBlogPostingGUI::getSnippet($this->getId()); - $news_item->setContentLong($snippet); - - if(!$news_item->getId()) - { - $news_item->create(); - } - else - { - $news_item->update(true); - } - } - - /** - * Lookup posting property - * - * @param string $a_field field - * @param int $a_posting_id posting id - * @return mixed - */ - static protected function lookup($a_field, $a_posting_id) - { - global $DIC; - - $db = $DIC->database(); - - $set = $db->query("SELECT $a_field FROM il_blog_posting ". - " WHERE id = ".$db->quote($a_posting_id, "integer")); - $rec = $db->fetchAssoc($set); - - return $rec[$a_field]; - } - - /** - * Lookup title - * - * @param int $a_posting_id posting id - * @return string - */ - static function lookupTitle($a_posting_id) - { - $t = self::lookup("title", $a_posting_id); - return $t; - } - - +{ + 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 + */ + public function getParentType() + { + return "blp"; + } + + + /** + * Set title + * + * @param string $a_title + */ + public function setTitle($a_title) + { + $this->title = $a_title; + } + + /** + * Get title + * + * @return string + */ + public function getTitle() + { + return $this->title; + } + + /** + * Set blog object id + * + * @param int $a_id + */ + public function setBlogId($a_id) + { + $this->setParentId($a_id); + } + + /** + * Get blog object id + * + * @return int + */ + public function getBlogId() + { + return $this->getParentId(); + } + + /** + * Set creation date + * + * @param ilDateTime $a_date + */ + public function setCreated(ilDateTime $a_date) + { + $this->created = $a_date; + } + + /** + * Get creation date + * + * @return ilDateTime + */ + public function getCreated() + { + return $this->created; + } + + /** + * Set author user id + * + * @param int $a_id + */ + public function setAuthor($a_id) + { + $this->author = (int) $a_id; + } + + /** + * Get author user id + * + * @return int + */ + public function getAuthor() + { + return $this->author; + } + + /** + * Toggle approval status + */ + public function setApproved($a_status) + { + $this->approved = (bool) $a_status; + } + + /** + * Get approved status + * + * @return bool + */ + public function isApproved() + { + return (bool) $this->approved; + } + + /** + * Create new blog posting + */ + public 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 + */ + public 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 + */ + public 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(); + } + + public function checkApproval() + { + if (!$this->getActive() && $this->isApproved()) { + $this->approved = false; + $this->update(); + } + } + + /** + * Delete blog posting and all related data + * + * @return bool + */ + public 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 + */ + public 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 + */ + public 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 + */ + public 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 + */ + public 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 + */ + public 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('

', "\n", $snippet); + $snippet = str_replace('', "\n", $snippet); + + return trim(strip_tags($snippet)); + } + + + // keywords + + public function getMDSection() + { + // general section available? + include_once 'Services/MetaData/classes/class.ilMD.php'; + $md_obj = new ilMD($this->getBlogId(), $this->getId(), "blp"); + if (!is_object($md_section = $md_obj->getGeneral())) { + $md_section = $md_obj->addGeneral(); + $md_section->save(); + } + + return $md_section; + } + + public function updateKeywords(array $keywords) + { + $ilUser = $this->user; + + // language is not "used" anywhere + $ulang = $ilUser->getLanguage(); + $keywords = array($ulang=>$keywords); + + include_once("./Services/MetaData/classes/class.ilMDKeyword.php"); + ilMDKeyword::updateKeywords($this->getMDSection(), $keywords); + } + + public static function getKeywords($a_obj_id, $a_posting_id) + { + include_once("./Services/MetaData/classes/class.ilMDKeyword.php"); + return ilMDKeyword::lookupKeywords($a_obj_id, $a_posting_id); + } + + /** + * Handle news item + * + * @param bool $a_update + */ + public function handleNews($a_update = false) + { + $lng = $this->lng; + $ilUser = $this->user; + + // see ilWikiPage::updateNews() + + if (!$this->getActive()) { + return; + } + + include_once("./Services/News/classes/class.ilNewsItem.php"); + $news_item = null; + + // try to re-use existing news item + if ((bool) $a_update) { + // get last news item of the day (if existing) + $news_id = ilNewsItem::getLastNewsIdForContext( + $this->getBlogId(), + "blog", + $this->getId(), + $this->getParentType(), + true + ); + if ($news_id > 0) { + $news_item = new ilNewsItem($news_id); + } + } + + // create new news item + if (!$news_item) { + $news_set = new ilSetting("news"); + $default_visibility = $news_set->get("default_visibility", "users"); + + $news_item = new ilNewsItem(); + $news_item->setContext( + $this->getBlogId(), + "blog", + $this->getId(), + $this->getParentType() + ); + $news_item->setPriority(NEWS_NOTICE); + $news_item->setVisibility($default_visibility); + } + + // news author + $news_item->setUserId($ilUser->getId()); + + + // news title/content + + $news_item->setTitle($this->getTitle()); + + $content = $a_update + ? "blog_news_posting_updated" + : "blog_news_posting_published"; + + // news "author" + include_once "Services/User/classes/class.ilUserUtil.php"; + $content = sprintf($lng->txt($content), ilUserUtil::getNamePresentation($ilUser->getId())); + + // posting author[s] + $contributors = array(); + foreach (self::getPageContributors($this->getParentType(), $this->getId()) as $user) { + $contributors[] = $user["user_id"]; + } + if (sizeof($contributors) > 1 || !in_array($this->getAuthor(), $contributors)) { + // original author should come first? + $authors = array(ilUserUtil::getNamePresentation($this->getAuthor())); + foreach ($contributors as $user_id) { + if ($user_id != $this->getAuthor()) { + $authors[] = ilUserUtil::getNamePresentation($user_id); + } + } + $content .= "\n" . sprintf($lng->txt("blog_news_posting_authors"), implode(", ", $authors)); + } + + $news_item->setContentTextIsLangVar(false); + $news_item->setContent($content); + + include_once "Modules/Blog/classes/class.ilBlogPostingGUI.php"; + $snippet = ilBlogPostingGUI::getSnippet($this->getId()); + $news_item->setContentLong($snippet); + + if (!$news_item->getId()) { + $news_item->create(); + } else { + $news_item->update(true); + } + } + + /** + * Lookup posting property + * + * @param string $a_field field + * @param int $a_posting_id posting id + * @return mixed + */ + protected static function lookup($a_field, $a_posting_id) + { + global $DIC; + + $db = $DIC->database(); + + $set = $db->query("SELECT $a_field FROM il_blog_posting " . + " WHERE id = " . $db->quote($a_posting_id, "integer")); + $rec = $db->fetchAssoc($set); + + return $rec[$a_field]; + } + + /** + * Lookup title + * + * @param int $a_posting_id posting id + * @return string + */ + public static function lookupTitle($a_posting_id) + { + $t = self::lookup("title", $a_posting_id); + return $t; + } } - -?> \ No newline at end of file diff --git a/Modules/Blog/classes/class.ilBlogPostingConfig.php b/Modules/Blog/classes/class.ilBlogPostingConfig.php index 53c37889cbfc3cde05c36759877e5ea0ff8b7e74..358433d841997ce493b868146ebc9bcfc1ffdb56 100644 --- a/Modules/Blog/classes/class.ilBlogPostingConfig.php +++ b/Modules/Blog/classes/class.ilBlogPostingConfig.php @@ -5,7 +5,7 @@ include_once("./Services/COPage/classes/class.ilPageConfig.php"); /** - * Blog posting page configuration + * Blog posting page configuration * * @author Alex Killing * @version $Id$ @@ -13,20 +13,17 @@ include_once("./Services/COPage/classes/class.ilPageConfig.php"); */ class ilBlogPostingConfig extends ilPageConfig { - /** - * Init - */ - function init() - { - $this->setEnablePCType("Map", true); - $this->setEnableInternalLinks((bool)$_GET["ref_id"]); // #15668 - $this->setPreventHTMLUnmasking(false); - $this->setEnableActivation(true); - - $blga_set = new ilSetting("blga"); - $this->setPreventHTMLUnmasking(!(bool)$blga_set->get("mask", false)); - } - + /** + * Init + */ + public function init() + { + $this->setEnablePCType("Map", true); + $this->setEnableInternalLinks((bool) $_GET["ref_id"]); // #15668 + $this->setPreventHTMLUnmasking(false); + $this->setEnableActivation(true); + + $blga_set = new ilSetting("blga"); + $this->setPreventHTMLUnmasking(!(bool) $blga_set->get("mask", false)); + } } - -?> diff --git a/Modules/Blog/classes/class.ilBlogPostingGUI.php b/Modules/Blog/classes/class.ilBlogPostingGUI.php index a77cbaec12a2ccbfa6b3735767a2ef3dd5ce7c69..032fc01472256b5f5c5eca9c21659ded89d5e95c 100644 --- a/Modules/Blog/classes/class.ilBlogPostingGUI.php +++ b/Modules/Blog/classes/class.ilBlogPostingGUI.php @@ -17,947 +17,909 @@ include_once("./Modules/Blog/classes/class.ilBlogPosting.php"); */ class ilBlogPostingGUI extends ilPageObjectGUI { - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilLocatorGUI - */ - protected $locator; - - /** - * @var ilSetting - */ - protected $settings; - - /** - * @var int - */ - protected $node_id; - protected $access_handler; // [object] - - /** - * @var bool - */ - protected $enable_public_notes; - - /** - * @var bool - */ - protected $may_contribute; - - /** - * @var bool - */ - protected $fetchall; - - /** - * @var int - */ - protected $blpg; - - /** - * @var string - */ - protected $term; - - /** - * Constructor - * - * @param int $a_node - * @param object $a_access_handler - * @param int $a_id - * @param int $a_old_nr - * @param bool $a_enable_notes - * @param bool $a_may_contribute - */ - function __construct($a_node_id, $a_access_handler = null, $a_id = 0, $a_old_nr = 0, $a_enable_public_notes = true, $a_may_contribute = true, $a_style_sheet_id = 0) - { - global $DIC; - - $this->tabs = $DIC->tabs(); - $this->locator = $DIC["ilLocator"]; - $this->settings = $DIC->settings(); - $this->user = $DIC->user(); - $tpl = $DIC["tpl"]; - $lng = $DIC->language(); - - $lng->loadLanguageModule("blog"); - - $this->node_id = $a_node_id; - $this->access_handler = $a_access_handler; - $this->enable_public_notes = (bool)$a_enable_public_notes; - - parent::__construct("blp", $a_id, $a_old_nr); - - // needed for notification - $this->getBlogPosting()->setBlogNodeId($this->node_id, $this->isInWorkspace()); - $this->getBlogPosting()->getPageConfig()->setEditLockSupport(!$this->isInWorkspace()); - - // #11151 - $this->may_contribute = (bool)$a_may_contribute; - $this->setEnableEditing($a_may_contribute); - - // content style - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - - $tpl->setCurrentBlock("SyntaxStyle"); - $tpl->setVariable("LOCATION_SYNTAX_STYLESHEET", - ilObjStyleSheet::getSyntaxStylePath()); - $tpl->parseCurrentBlock(); - - // #17814 - $tpl->setCurrentBlock("ContentStyle"); - $tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($a_style_sheet_id)); - $tpl->parseCurrentBlock(); - - // needed for editor - $this->setStyleId($a_style_sheet_id); - - $this->blpg = (int) $_GET["blpg"]; - $this->fetchall = (bool) $_GET["fetchall"]; - $this->term = ilUtil::stripSlashes($_GET["term"]); - } - - /** - * execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - $ilLocator = $this->locator; - $tpl = $this->tpl; - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd(); - - $posting = $this->getBlogPosting(); - $ilCtrl->setParameter($this, "blpg", $posting->getId()); - - switch($next_class) - { - case "ilnotegui": - // $this->getTabs(); - // $ilTabs->setTabActive("pg"); - return $this->previewFullscreen(); - - default: - if($posting) - { - if($ilCtrl->getCmd() == "deactivatePageToList") - { - ilUtil::sendSuccess($this->lng->txt("blog_draft_info"), true); - } - else if($ilCtrl->getCmd() == "activatePageToList") - { - ilUtil::sendSuccess($this->lng->txt("blog_new_posting_info"), true); - } - $this->setPresentationTitle($posting->getTitle()); - - $tpl->setTitle(ilObject::_lookupTitle($this->getBlogPosting()->getBlogId()).": ". // #15017 - $posting->getTitle()); - $tpl->setTitleIcon(ilUtil::getImagePath("icon_blog.svg"), - $this->lng->txt("obj_blog")); // #12879 - - $ilLocator->addItem($posting->getTitle(), - $ilCtrl->getLinkTarget($this, "preview")); - } - return parent::executeCommand(); - } - } - - /** - * Set blog posting - * - * @param ilBlogPosting $a_posting - */ - function setBlogPosting(ilBlogPosting $a_posting) - { - $this->setPageObject($a_posting); - } - - /** - * Get blog posting - * - * @returnilBlogPosting - */ - function getBlogPosting() - { - return $this->getPageObject(); - } - - /** - * Centralized access management - * - * @param string $a_cmd - * @return bool - */ - protected function checkAccess($a_cmd) - { - if($a_cmd == "contribute") - { - return $this->may_contribute; - } - return $this->access_handler->checkAccess($a_cmd, "", $this->node_id); - } - - /** - * Preview blog posting - */ - function preview($a_mode = null) - { - global $DIC; - - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $ilSetting = $this->settings; - - $toolbar = $DIC->toolbar(); - - $this->getBlogPosting()->increaseViewCnt(); - - $wtpl = new ilTemplate("tpl.blog_page_view_main_column.html", - true, true, "Modules/Blog"); - - // page commands - if(!$a_mode) - { - if (!$this->getEnableEditing()) - { - $this->ctrl->redirect($this, "previewFullscreen"); - } - /* - // delete - $page_commands = false; - if ($this->checkAccess("write")) - { - $wtpl->setCurrentBlock("page_command"); - $wtpl->setVariable("HREF_PAGE_CMD", - $ilCtrl->getLinkTarget($this, "deleteBlogPostingConfirmationScreen")); - $wtpl->setVariable("TXT_PAGE_CMD", $lng->txt("delete")); - $wtpl->parseCurrentBlock(); - } - if ($page_commands) - { - $wtpl->setCurrentBlock("page_commands"); - $wtpl->parseCurrentBlock(); - } - */ - } - else - { - $callback = array($this, "observeNoteAction"); - - // notes - - $may_delete_comments = ($this->checkAccess("contribute") && - $ilSetting->get("comments_del_tutor", 1)); - - $wtpl->setVariable("TOOLBAR", $toolbar->getHTML()); - - $wtpl->setVariable("NOTES", $this->getNotesHTML($this->getBlogPosting(), - false, $this->enable_public_notes, $may_delete_comments, $callback)); - } - - // permanent link - if($a_mode != "embedded") - { - $append = ($this->blpg > 0) - ? "_".$this->blpg - : ""; - if($this->isInWorkspace()) - { - $append .= "_wsp"; - } - $tpl->setPermanentLink("blog", $this->node_id, $append); - } - - $wtpl->setVariable("PAGE", parent::preview()); - - $tpl->setLoginTargetPar("blog_".$this->node_id.$append); - - $ilCtrl->setParameter($this, "blpg", $this->getBlogPosting()->getId()); - - return $wtpl->get(); - } - - /** - * Needed for portfolio/blog handling - * - * @return string - */ - function previewEmbedded() - { - return $this->preview("embedded"); - } - - /** - * Needed for portfolio/blog handling - * - * @return string - */ - function previewFullscreen() - { - $this->add_date = true; - return $this->preview("fullscreen"); - } - - /** - * Embedded posting in portfolio - * - * @return string - */ - function showPage($a_title = "") - { - $this->setTemplateOutput(false); - - if (!$this->getAbstractOnly()) - { - if ($a_title != "") - { - $this->setPresentationTitle($a_title); - } - else - { - $this->setPresentationTitle($this->getBlogPosting()->getTitle()); - } - } - $this->getBlogPosting()->increaseViewCnt(); - - return parent::showPage(); - } - - /** - * Is current page part of personal workspace blog? - * - * @return bool - */ - protected function isInWorkspace() - { - $class = ''; - if (is_object($this->access_handler)) { - $class = get_class($this->access_handler); - } - - return stristr($class, "workspace"); - } - - /** - * Finalizing output processing - * - * @param string $a_output - * @return string - */ - function postOutputProcessing($a_output) - { - // #8626/#9370 - if(($this->getOutputMode() == "preview" || $this->getOutputMode() == "offline") - && !$this->getAbstractOnly() && $this->add_date) - { - $author = ""; - if(!$this->isInWorkspace()) - { - $authors = array(); - $author_id = $this->getBlogPosting()->getAuthor(); - if($author_id) - { - include_once "Services/User/classes/class.ilUserUtil.php"; - $authors[] = ilUserUtil::getNamePresentation($author_id); - } - - foreach(ilBlogPosting::getPageContributors("blp", $this->getBlogPosting()->getId()) as $editor) - { - if($editor["user_id"] != $author_id) - { - $authors[] = ilUserUtil::getNamePresentation($editor["user_id"]); - } - } - - if($authors) - { - $author = implode(", ", $authors)." - "; - } - } - - // prepend creation date - $rel = ilDatePresentation::useRelativeDates(); - ilDatePresentation::setUseRelativeDates(false); - $prefix = "
". - $author.ilDatePresentation::formatDate($this->getBlogPosting()->getCreated()). - "
"; - ilDatePresentation::setUseRelativeDates($rel); - - $a_output = $prefix.$a_output; - } - - return $a_output; - } - - /** - * Get tabs - * - * @param string $a_activate - */ - function getTabs($a_activate = "") - { - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameterByClass("ilobjbloggui", "blpg", $this->getBlogPosting()->getId()); - - parent::getTabs($a_activate); - } - - /** - * Delete blog posting confirmation screen - */ - function deleteBlogPostingConfirmationScreen() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if ($this->checkAccess("write") || $this->checkAccess("contribute")) - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $confirmation_gui = new ilConfirmationGUI(); - $confirmation_gui->setFormAction($ilCtrl->getFormAction($this)); - $confirmation_gui->setHeaderText($lng->txt("blog_posting_deletion_confirmation")); - $confirmation_gui->setCancel($lng->txt("cancel"), "cancelBlogPostingDeletion"); - $confirmation_gui->setConfirm($lng->txt("delete"), "confirmBlogPostingDeletion"); - - $dtpl = new ilTemplate("tpl.blog_posting_deletion_confirmation.html", true, - true, "Modules/Blog"); - - $dtpl->setVariable("PAGE_TITLE", $this->getBlogPosting()->getTitle()); - - // notes/comments - include_once("./Services/Notes/classes/class.ilNote.php"); - $cnt_note_users = ilNote::getUserCount($this->getBlogPosting()->getParentId(), - $this->getBlogPosting()->getId(), "wpg"); - $dtpl->setVariable("TXT_NUMBER_USERS_NOTES_OR_COMMENTS", - $lng->txt("blog_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 blog posting deletion - */ - function cancelBlogPostingDeletion() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirect($this, "preview"); - } - - /** - * Delete the blog posting - */ - function confirmBlogPostingDeletion() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if ($this->checkAccess("write") || $this->checkAccess("contribute")) - { - // delete all md keywords - $md_section = $this->getBlogPosting()->getMDSection(); - foreach($md_section->getKeywordIds() as $id) - { - $md_key = $md_section->getKeyword($id); - $md_key->delete(); - } - - $this->getBlogPosting()->delete(); - ilUtil::sendSuccess($lng->txt("blog_posting_deleted"), true); - } - - $ilCtrl->setParameterByClass("ilobjbloggui", "blpg", ""); // #14363 - $ilCtrl->redirectByClass("ilobjbloggui", "render"); - } - - function editTitle($a_form = null) - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilLocatorGUI + */ + protected $locator; + + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var int + */ + protected $node_id; + protected $access_handler; // [object] + + /** + * @var bool + */ + protected $enable_public_notes; + + /** + * @var bool + */ + protected $may_contribute; + + /** + * @var bool + */ + protected $fetchall; + + /** + * @var int + */ + protected $blpg; + + /** + * @var string + */ + protected $term; + + /** + * Constructor + * + * @param int $a_node + * @param object $a_access_handler + * @param int $a_id + * @param int $a_old_nr + * @param bool $a_enable_notes + * @param bool $a_may_contribute + */ + public function __construct($a_node_id, $a_access_handler = null, $a_id = 0, $a_old_nr = 0, $a_enable_public_notes = true, $a_may_contribute = true, $a_style_sheet_id = 0) + { + global $DIC; + + $this->tabs = $DIC->tabs(); + $this->locator = $DIC["ilLocator"]; + $this->settings = $DIC->settings(); + $this->user = $DIC->user(); + $tpl = $DIC["tpl"]; + $lng = $DIC->language(); + + $lng->loadLanguageModule("blog"); + + $this->node_id = $a_node_id; + $this->access_handler = $a_access_handler; + $this->enable_public_notes = (bool) $a_enable_public_notes; + + parent::__construct("blp", $a_id, $a_old_nr); + + // needed for notification + $this->getBlogPosting()->setBlogNodeId($this->node_id, $this->isInWorkspace()); + $this->getBlogPosting()->getPageConfig()->setEditLockSupport(!$this->isInWorkspace()); + + // #11151 + $this->may_contribute = (bool) $a_may_contribute; + $this->setEnableEditing($a_may_contribute); + + // content style + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + + $tpl->setCurrentBlock("SyntaxStyle"); + $tpl->setVariable( + "LOCATION_SYNTAX_STYLESHEET", + ilObjStyleSheet::getSyntaxStylePath() + ); + $tpl->parseCurrentBlock(); + + // #17814 + $tpl->setCurrentBlock("ContentStyle"); + $tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath($a_style_sheet_id) + ); + $tpl->parseCurrentBlock(); + + // needed for editor + $this->setStyleId($a_style_sheet_id); + + $this->blpg = (int) $_GET["blpg"]; + $this->fetchall = (bool) $_GET["fetchall"]; + $this->term = ilUtil::stripSlashes($_GET["term"]); + } + + /** + * execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + $ilLocator = $this->locator; + $tpl = $this->tpl; + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd(); + + $posting = $this->getBlogPosting(); + $ilCtrl->setParameter($this, "blpg", $posting->getId()); + + switch ($next_class) { + case "ilnotegui": + // $this->getTabs(); + // $ilTabs->setTabActive("pg"); + return $this->previewFullscreen(); + + default: + if ($posting) { + if ($ilCtrl->getCmd() == "deactivatePageToList") { + ilUtil::sendSuccess($this->lng->txt("blog_draft_info"), true); + } elseif ($ilCtrl->getCmd() == "activatePageToList") { + ilUtil::sendSuccess($this->lng->txt("blog_new_posting_info"), true); + } + $this->setPresentationTitle($posting->getTitle()); + + $tpl->setTitle(ilObject::_lookupTitle($this->getBlogPosting()->getBlogId()) . ": " . // #15017 + $posting->getTitle()); + $tpl->setTitleIcon( + ilUtil::getImagePath("icon_blog.svg"), + $this->lng->txt("obj_blog") + ); // #12879 + + $ilLocator->addItem( + $posting->getTitle(), + $ilCtrl->getLinkTarget($this, "preview") + ); + } + return parent::executeCommand(); + } + } + + /** + * Set blog posting + * + * @param ilBlogPosting $a_posting + */ + public function setBlogPosting(ilBlogPosting $a_posting) + { + $this->setPageObject($a_posting); + } + + /** + * Get blog posting + * + * @returnilBlogPosting + */ + public function getBlogPosting() + { + return $this->getPageObject(); + } + + /** + * Centralized access management + * + * @param string $a_cmd + * @return bool + */ + protected function checkAccess($a_cmd) + { + if ($a_cmd == "contribute") { + return $this->may_contribute; + } + return $this->access_handler->checkAccess($a_cmd, "", $this->node_id); + } + + /** + * Preview blog posting + */ + public function preview($a_mode = null) + { + global $DIC; + + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $ilSetting = $this->settings; + + $toolbar = $DIC->toolbar(); + + $this->getBlogPosting()->increaseViewCnt(); + + $wtpl = new ilTemplate( + "tpl.blog_page_view_main_column.html", + true, + true, + "Modules/Blog" + ); + + // page commands + if (!$a_mode) { + if (!$this->getEnableEditing()) { + $this->ctrl->redirect($this, "previewFullscreen"); + } + /* + // delete + $page_commands = false; + if ($this->checkAccess("write")) + { + $wtpl->setCurrentBlock("page_command"); + $wtpl->setVariable("HREF_PAGE_CMD", + $ilCtrl->getLinkTarget($this, "deleteBlogPostingConfirmationScreen")); + $wtpl->setVariable("TXT_PAGE_CMD", $lng->txt("delete")); + $wtpl->parseCurrentBlock(); + } + if ($page_commands) + { + $wtpl->setCurrentBlock("page_commands"); + $wtpl->parseCurrentBlock(); + } + */ + } else { + $callback = array($this, "observeNoteAction"); + + // notes + + $may_delete_comments = ($this->checkAccess("contribute") && + $ilSetting->get("comments_del_tutor", 1)); + + $wtpl->setVariable("TOOLBAR", $toolbar->getHTML()); + + $wtpl->setVariable("NOTES", $this->getNotesHTML( + $this->getBlogPosting(), + false, + $this->enable_public_notes, + $may_delete_comments, + $callback + )); + } + + // permanent link + if ($a_mode != "embedded") { + $append = ($this->blpg > 0) + ? "_" . $this->blpg + : ""; + if ($this->isInWorkspace()) { + $append .= "_wsp"; + } + $tpl->setPermanentLink("blog", $this->node_id, $append); + } + + $wtpl->setVariable("PAGE", parent::preview()); + + $tpl->setLoginTargetPar("blog_" . $this->node_id . $append); + + $ilCtrl->setParameter($this, "blpg", $this->getBlogPosting()->getId()); + + return $wtpl->get(); + } + + /** + * Needed for portfolio/blog handling + * + * @return string + */ + public function previewEmbedded() + { + return $this->preview("embedded"); + } + + /** + * Needed for portfolio/blog handling + * + * @return string + */ + public function previewFullscreen() + { + $this->add_date = true; + return $this->preview("fullscreen"); + } + + /** + * Embedded posting in portfolio + * + * @return string + */ + public function showPage($a_title = "") + { + $this->setTemplateOutput(false); + + if (!$this->getAbstractOnly()) { + if ($a_title != "") { + $this->setPresentationTitle($a_title); + } else { + $this->setPresentationTitle($this->getBlogPosting()->getTitle()); + } + } + $this->getBlogPosting()->increaseViewCnt(); + + return parent::showPage(); + } + + /** + * Is current page part of personal workspace blog? + * + * @return bool + */ + protected function isInWorkspace() + { + $class = ''; + if (is_object($this->access_handler)) { + $class = get_class($this->access_handler); + } + + return stristr($class, "workspace"); + } + + /** + * Finalizing output processing + * + * @param string $a_output + * @return string + */ + public function postOutputProcessing($a_output) + { + // #8626/#9370 + if (($this->getOutputMode() == "preview" || $this->getOutputMode() == "offline") + && !$this->getAbstractOnly() && $this->add_date) { + $author = ""; + if (!$this->isInWorkspace()) { + $authors = array(); + $author_id = $this->getBlogPosting()->getAuthor(); + if ($author_id) { + include_once "Services/User/classes/class.ilUserUtil.php"; + $authors[] = ilUserUtil::getNamePresentation($author_id); + } + + foreach (ilBlogPosting::getPageContributors("blp", $this->getBlogPosting()->getId()) as $editor) { + if ($editor["user_id"] != $author_id) { + $authors[] = ilUserUtil::getNamePresentation($editor["user_id"]); + } + } + + if ($authors) { + $author = implode(", ", $authors) . " - "; + } + } + + // prepend creation date + $rel = ilDatePresentation::useRelativeDates(); + ilDatePresentation::setUseRelativeDates(false); + $prefix = "
" . + $author . ilDatePresentation::formatDate($this->getBlogPosting()->getCreated()) . + "
"; + ilDatePresentation::setUseRelativeDates($rel); + + $a_output = $prefix . $a_output; + } + + return $a_output; + } + + /** + * Get tabs + * + * @param string $a_activate + */ + public function getTabs($a_activate = "") + { + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameterByClass("ilobjbloggui", "blpg", $this->getBlogPosting()->getId()); + + parent::getTabs($a_activate); + } + + /** + * Delete blog posting confirmation screen + */ + public function deleteBlogPostingConfirmationScreen() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if ($this->checkAccess("write") || $this->checkAccess("contribute")) { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $confirmation_gui = new ilConfirmationGUI(); + $confirmation_gui->setFormAction($ilCtrl->getFormAction($this)); + $confirmation_gui->setHeaderText($lng->txt("blog_posting_deletion_confirmation")); + $confirmation_gui->setCancel($lng->txt("cancel"), "cancelBlogPostingDeletion"); + $confirmation_gui->setConfirm($lng->txt("delete"), "confirmBlogPostingDeletion"); + + $dtpl = new ilTemplate( + "tpl.blog_posting_deletion_confirmation.html", + true, + true, + "Modules/Blog" + ); + + $dtpl->setVariable("PAGE_TITLE", $this->getBlogPosting()->getTitle()); + + // notes/comments + include_once("./Services/Notes/classes/class.ilNote.php"); + $cnt_note_users = ilNote::getUserCount( + $this->getBlogPosting()->getParentId(), + $this->getBlogPosting()->getId(), + "wpg" + ); + $dtpl->setVariable( + "TXT_NUMBER_USERS_NOTES_OR_COMMENTS", + $lng->txt("blog_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 blog posting deletion + */ + public function cancelBlogPostingDeletion() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirect($this, "preview"); + } + + /** + * Delete the blog posting + */ + public function confirmBlogPostingDeletion() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if ($this->checkAccess("write") || $this->checkAccess("contribute")) { + // delete all md keywords + $md_section = $this->getBlogPosting()->getMDSection(); + foreach ($md_section->getKeywordIds() as $id) { + $md_key = $md_section->getKeyword($id); + $md_key->delete(); + } + + $this->getBlogPosting()->delete(); + ilUtil::sendSuccess($lng->txt("blog_posting_deleted"), true); + } + + $ilCtrl->setParameterByClass("ilobjbloggui", "blpg", ""); // #14363 + $ilCtrl->redirectByClass("ilobjbloggui", "render"); + } + + public function editTitle($a_form = null) + { + $tpl = $this->tpl; + $ilTabs = $this->tabs; $ilTabs->clearTargets(); $ilTabs->setBackTarget($this->lng->txt("back"), $this->ctrl->getLinkTargetByClass("ilobjblogGUI")); $ilTabs->activateTab("edit"); - - if(!$a_form) - { - $a_form = $this->initTitleForm(); - } - - $tpl->setContent($a_form->getHTML()); - } - - function updateTitle() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $form = $this->initTitleForm(); - if($form->checkInput()) - { - if ($this->checkAccess("write") || $this->checkAccess("contribute")) - { - $page = $this->getPageObject(); - $page->setTitle($form->getInput("title")); - $page->update(); - - $page->handleNews(true); - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - //$ilCtrl->redirect($this, "preview"); + + if (!$a_form) { + $a_form = $this->initTitleForm(); + } + + $tpl->setContent($a_form->getHTML()); + } + + public function updateTitle() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $form = $this->initTitleForm(); + if ($form->checkInput()) { + if ($this->checkAccess("write") || $this->checkAccess("contribute")) { + $page = $this->getPageObject(); + $page->setTitle($form->getInput("title")); + $page->update(); + + $page->handleNews(true); + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + //$ilCtrl->redirect($this, "preview"); $this->ctrl->redirectByClass("ilObjBlogGUI", ""); - } - } - - $form->setValuesByPost(); - $this->editTitle($form); - } - - function initTitleForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once('Services/Form/classes/class.ilPropertyFormGUI.php'); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this)); - $form->setTitle($lng->txt('blog_rename_posting')); - - $title = new ilTextInputGUI($lng->txt("title"), "title"); - $title->setRequired(true); - $form->addItem($title); - - $title->setValue($this->getPageObject()->getTitle()); - - $form->addCommandButton('updateTitle', $lng->txt('save')); - $form->addCommandButton('cancelEdit', $lng->txt('cancel')); - - return $form; - } - - function editDate($a_form = null) - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($this->lng->txt("back"), $this->ctrl->getLinkTargetByClass("ilobjblogGUI")); - - $ilTabs->activateTab("edit"); - - if(!$a_form) - { - $a_form = $this->initDateForm(); - } - - $tpl->setContent($a_form->getHTML()); - } - - function updateDate() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $form = $this->initDateForm(); - if($form->checkInput()) - { - if ($this->checkAccess("write") || $this->checkAccess("contribute")) - { - $dt = $form->getItemByPostVar("date"); - $dt = $dt->getDate(); - - $page = $this->getPageObject(); - $page->setCreated($dt); - $page->update(); - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - //$ilCtrl->redirect($this, "preview"); + } + } + + $form->setValuesByPost(); + $this->editTitle($form); + } + + public function initTitleForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once('Services/Form/classes/class.ilPropertyFormGUI.php'); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this)); + $form->setTitle($lng->txt('blog_rename_posting')); + + $title = new ilTextInputGUI($lng->txt("title"), "title"); + $title->setRequired(true); + $form->addItem($title); + + $title->setValue($this->getPageObject()->getTitle()); + + $form->addCommandButton('updateTitle', $lng->txt('save')); + $form->addCommandButton('cancelEdit', $lng->txt('cancel')); + + return $form; + } + + public function editDate($a_form = null) + { + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + $ilTabs->clearTargets(); + $ilTabs->setBackTarget($this->lng->txt("back"), $this->ctrl->getLinkTargetByClass("ilobjblogGUI")); + + $ilTabs->activateTab("edit"); + + if (!$a_form) { + $a_form = $this->initDateForm(); + } + + $tpl->setContent($a_form->getHTML()); + } + + public function updateDate() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $form = $this->initDateForm(); + if ($form->checkInput()) { + if ($this->checkAccess("write") || $this->checkAccess("contribute")) { + $dt = $form->getItemByPostVar("date"); + $dt = $dt->getDate(); + + $page = $this->getPageObject(); + $page->setCreated($dt); + $page->update(); + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + //$ilCtrl->redirect($this, "preview"); $this->ctrl->redirectByClass("ilObjBlogGUI", ""); - } - } - - $form->setValuesByPost(); - $this->editTitle($form); - } - - function initDateForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once('Services/Form/classes/class.ilPropertyFormGUI.php'); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this)); - $form->setTitle($lng->txt('blog_edit_date')); - - $date = new ilDateTimeInputGUI($lng->txt("date"), "date"); - $date->setRequired(true); - $date->setShowTime(true); - $date->setInfo($lng->txt('blog_edit_date_info')); - $form->addItem($date); - - $date->setDate($this->getPageObject()->getCreated()); - - $form->addCommandButton('updateDate', $lng->txt('save')); - $form->addCommandButton('cancelEdit', $lng->txt('cancel')); - - return $form; - } - - /** - * Cancel editing - * - * @param - * @return - */ - protected function cancelEdit() - { + } + } + + $form->setValuesByPost(); + $this->editTitle($form); + } + + public function initDateForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once('Services/Form/classes/class.ilPropertyFormGUI.php'); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this)); + $form->setTitle($lng->txt('blog_edit_date')); + + $date = new ilDateTimeInputGUI($lng->txt("date"), "date"); + $date->setRequired(true); + $date->setShowTime(true); + $date->setInfo($lng->txt('blog_edit_date_info')); + $form->addItem($date); + + $date->setDate($this->getPageObject()->getCreated()); + + $form->addCommandButton('updateDate', $lng->txt('save')); + $form->addCommandButton('cancelEdit', $lng->txt('cancel')); + + return $form; + } + + /** + * Cancel editing + * + * @param + * @return + */ + protected function cancelEdit() + { $this->ctrl->redirectByClass("ilObjBlogGUI", ""); - } - - - function observeNoteAction($a_blog_id, $a_posting_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 "Modules/Blog/classes/class.ilObjBlog.php"; - ilObjBlog::sendNotification("comment", $this->isInWorkspace(), $this->node_id, $a_posting_id, $note); - } - - protected function getActivationCaptions() - { - $lng = $this->lng; - - return array("deactivatePage" => $lng->txt("blog_toggle_draft"), - "activatePage" => $lng->txt("blog_toggle_final")); - } - - function deactivatePageToList() - { - $this->deactivatePage(true); - } - - function deactivatePage($a_to_list = false) - { - if ($this->checkAccess("write") || $this->checkAccess("contribute")) - { - $this->getBlogPosting()->unpublish(); - } - - if(!$a_to_list) - { - $this->ctrl->redirect($this, "edit"); - } - else - { - $this->ctrl->setParameterByClass("ilobjbloggui", "blpg", ""); - $this->ctrl->redirectByClass("ilobjbloggui", ""); - } - } - - function activatePageToList() - { - $this->activatePage(true); - } - - function activatePage($a_to_list = false) - { - // send notifications - include_once "Modules/Blog/classes/class.ilObjBlog.php"; - ilObjBlog::sendNotification("new", $this->isInWorkspace(), $this->node_id, $this->getBlogPosting()->getId()); - - if ($this->checkAccess("write") || $this->checkAccess("contribute")) - { - $this->getBlogPosting()->setActive(true); - $this->getBlogPosting()->update(true, false, false); - } - if(!$a_to_list) - { - $this->ctrl->redirect($this, "edit"); - } - else - { - $this->ctrl->setParameterByClass("ilobjbloggui", "blpg", ""); - $this->ctrl->redirectByClass("ilobjbloggui", ""); - } - } - - /** - * Diplay the form - * @param ilPropertyFormGUI|null $a_form - */ - function editKeywords(ilPropertyFormGUI $a_form = null) - { - global $DIC; - - $renderer = $DIC->ui()->renderer(); - - $ilTabs = $this->tabs; - $tpl = $this->tpl; + } + + + public function observeNoteAction($a_blog_id, $a_posting_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 "Modules/Blog/classes/class.ilObjBlog.php"; + ilObjBlog::sendNotification("comment", $this->isInWorkspace(), $this->node_id, $a_posting_id, $note); + } + + protected function getActivationCaptions() + { + $lng = $this->lng; + + return array("deactivatePage" => $lng->txt("blog_toggle_draft"), + "activatePage" => $lng->txt("blog_toggle_final")); + } + + public function deactivatePageToList() + { + $this->deactivatePage(true); + } + + public function deactivatePage($a_to_list = false) + { + if ($this->checkAccess("write") || $this->checkAccess("contribute")) { + $this->getBlogPosting()->unpublish(); + } + + if (!$a_to_list) { + $this->ctrl->redirect($this, "edit"); + } else { + $this->ctrl->setParameterByClass("ilobjbloggui", "blpg", ""); + $this->ctrl->redirectByClass("ilobjbloggui", ""); + } + } + + public function activatePageToList() + { + $this->activatePage(true); + } + + public function activatePage($a_to_list = false) + { + // send notifications + include_once "Modules/Blog/classes/class.ilObjBlog.php"; + ilObjBlog::sendNotification("new", $this->isInWorkspace(), $this->node_id, $this->getBlogPosting()->getId()); + + if ($this->checkAccess("write") || $this->checkAccess("contribute")) { + $this->getBlogPosting()->setActive(true); + $this->getBlogPosting()->update(true, false, false); + } + if (!$a_to_list) { + $this->ctrl->redirect($this, "edit"); + } else { + $this->ctrl->setParameterByClass("ilobjbloggui", "blpg", ""); + $this->ctrl->redirectByClass("ilobjbloggui", ""); + } + } + + /** + * Diplay the form + * @param ilPropertyFormGUI|null $a_form + */ + public function editKeywords(ilPropertyFormGUI $a_form = null) + { + global $DIC; + + $renderer = $DIC->ui()->renderer(); + + $ilTabs = $this->tabs; + $tpl = $this->tpl; $ilTabs->clearTargets(); $ilTabs->setBackTarget($this->lng->txt("back"), $this->ctrl->getLinkTargetByClass("ilobjblogGUI")); - if (!$this->checkAccess("contribute")) - { - return; - } - - $ilTabs->activateTab("pg"); - - if(!$a_form) - { - $a_form = $this->initKeywordsForm(); - } - - $tpl->setContent($renderer->render($a_form)); - } - - protected function initKeywordsForm() - { - global $DIC; - - $ui_factory = $DIC->ui()->factory(); - //$ilUser = $this->user; - - $md_section = $this->getBlogPosting()->getMDSection(); - - $keywords = array(); - foreach($ids = $md_section->getKeywordIds() as $id) - { - $md_key = $md_section->getKeyword($id); - if (trim($md_key->getKeyword()) != "") - { - //$keywords[$md_key->getKeywordLanguageCode()][] - // = $md_key->getKeyword(); - $keywords[] = $md_key->getKeyword(); - } - } - - // language is not "used" anywhere - /*$ulang = $ilUser->getLanguage(); - if($keywords[$ulang]) - { - asort($keywords[$ulang]); - }*/ - - // other keywords in blog - $other = array(); - foreach(array_keys(ilBlogPosting::getAllPostings($this->getBlogPosting()->getBlogId())) as $posting_id) - { - if($posting_id != $this->getBlogPosting()->getId()) - { - $other = array_merge($other, ilBlogPosting::getKeywords($this->getBlogPosting()->getBlogId(), $posting_id)); - } - } - // #17414 - $other = array_unique($other); - sort($other, SORT_LOCALE_STRING); - if(is_array($keywords[$ulang])) - { - $other = array_diff($other, $keywords[$ulang]); - } - - $input_tag = $ui_factory->input()->field()->tag($this->lng->txt("blog_keywords"), $other, $this->lng->txt("blog_keyword_enter")); - $input_tag = $input_tag->withValue($keywords); - - $DIC->ctrl()->setParameter( - $this, - 'tags', - 'tags_processing' - ); - - $section = $ui_factory->input()->field()->section([$input_tag], $this->lng->txt("blog_edit_keywords"), ""); - - $form_action = $DIC->ctrl()->getFormAction($this, "saveKeywordsForm"); - $form = $ui_factory->input()->container()->form()->standard($form_action, ["tags" => $section]); - - return $form; - } - - protected function getParentObjId() - { - if($this->node_id) - { - if($this->isInWorkspace()) - { - return $this->access_handler->getTree()->lookupObjectId($this->node_id); - } - else - { - return ilObject::_lookupObjId($this->node_id); - } - } - } - - function saveKeywordsForm() - { - global $DIC; - - $request = $DIC->http()->request(); - $form = $this->initKeywordsForm(); - - if($request->getMethod() == "POST" - && $request->getQueryParams()['tags'] == 'tags_processing') - { - $form = $form->withRequest($request); - $result = $form->getData(); - - //TODO identify the input instead of use 0 - $keywords = $result["tags"][0]; - - if ($this->checkAccess("write") || $this->checkAccess("contribute")) - { - if (is_array($keywords)) - { - $this->getBlogPosting()->updateKeywords($keywords); - } - } - - $this->ctrl->redirectByClass("ilObjBlogGUI", ""); - } - } - - /** - * Get first text paragraph of page - * - * @param int $a_id - * @param bool $a_truncate - * @param int $a_truncate_length - * @param bool $a_include_picture - * @param int $a_picture_width - * @param int $a_picture_height - * @param string $a_export_directory - * @return string - */ - static function getSnippet($a_id, $a_truncate = false, $a_truncate_length = 500, $a_truncate_sign = "...", $a_include_picture = false, $a_picture_width = 144, $a_picture_height = 144, $a_export_directory = null) - { - $bpgui = new self(0, null, $a_id); - - // scan the full page for media objects - if($a_include_picture) - { - $img = $bpgui->getFirstMediaObjectAsTag($a_picture_width, $a_picture_height, $a_export_directory); - } - - $bpgui->setRawPageContent(true); - $bpgui->setAbstractOnly(true); - - // #8627: export won't work - should we set offline mode? - $bpgui->setFileDownloadLink("."); - $bpgui->setFullscreenLink("."); - $bpgui->setSourcecodeDownloadScript("."); - - // render without title - $page = $bpgui->showPage(); - - if($a_truncate) - { - $page = ilPageObject::truncateHTML($page, $a_truncate_length, $a_truncate_sign); - } - - if($img) - { - $page = '
'.$img.$page.'
'; - } - - return $page; - } - - protected function getFirstMediaObjectAsTag($a_width = 144, $a_height = 144, $a_export_directory = null) - { - $this->obj->buildDom(); - $mob_ids = $this->obj->collectMediaObjects(); - if($mob_ids) - { - require_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - foreach($mob_ids as $mob_id) - { - $mob_obj = new ilObjMediaObject($mob_id); - $mob_item = $mob_obj->getMediaItem("Standard"); - if(stristr($mob_item->getFormat(), "image")) - { - $mob_size = $mob_item->getOriginalSize(); - if($mob_size["width"] >= $a_width || - $mob_size["height"] >= $a_height) - { - if(!$a_export_directory) - { - $mob_dir = ilObjMediaObject::_getDirectory($mob_obj->getId()); - } - else - { - // see ilCOPageHTMLExport::exportHTMLMOB() - $mob_dir = "./mobs/mm_".$mob_obj->getId(); - } - $mob_res = self::parseImage($mob_size["width"], - $mob_size["height"], $a_width, $a_height); - - - $location = $mob_item->getLocationType() == "Reference" - ? $mob_item->getLocation() - : $mob_dir."/".$mob_item->getLocation(); - - return ''; - } - } - } - } - } - - protected static function parseImage($src_width, $src_height, $tgt_width, $tgt_height) - { - $ratio_width = $ratio_height = 1; - if($src_width > $tgt_width) - { - $ratio_width = $tgt_width / $src_width; - } - if($src_height > $tgt_height) - { - $ratio_height = $tgt_height / $src_height; - } - $shrink_ratio = min($ratio_width, $ratio_height); - - return array( - (int)round($src_width*$shrink_ratio), - (int)round($src_height*$shrink_ratio) - ); - } - - /** - * Get disabled text - * - * @param - * @return - */ - function getDisabledText() - { - return $this->lng->txt("blog_draft_text"); - } - + if (!$this->checkAccess("contribute")) { + return; + } + + $ilTabs->activateTab("pg"); + + if (!$a_form) { + $a_form = $this->initKeywordsForm(); + } + + $tpl->setContent($renderer->render($a_form)); + } + + protected function initKeywordsForm() + { + global $DIC; + + $ui_factory = $DIC->ui()->factory(); + //$ilUser = $this->user; + + $md_section = $this->getBlogPosting()->getMDSection(); + + $keywords = array(); + foreach ($ids = $md_section->getKeywordIds() as $id) { + $md_key = $md_section->getKeyword($id); + if (trim($md_key->getKeyword()) != "") { + //$keywords[$md_key->getKeywordLanguageCode()][] + // = $md_key->getKeyword(); + $keywords[] = $md_key->getKeyword(); + } + } + + // language is not "used" anywhere + /*$ulang = $ilUser->getLanguage(); + if($keywords[$ulang]) + { + asort($keywords[$ulang]); + }*/ + + // other keywords in blog + $other = array(); + foreach (array_keys(ilBlogPosting::getAllPostings($this->getBlogPosting()->getBlogId())) as $posting_id) { + if ($posting_id != $this->getBlogPosting()->getId()) { + $other = array_merge($other, ilBlogPosting::getKeywords($this->getBlogPosting()->getBlogId(), $posting_id)); + } + } + // #17414 + $other = array_unique($other); + sort($other, SORT_LOCALE_STRING); + if (is_array($keywords[$ulang])) { + $other = array_diff($other, $keywords[$ulang]); + } + + $input_tag = $ui_factory->input()->field()->tag($this->lng->txt("blog_keywords"), $other, $this->lng->txt("blog_keyword_enter")); + $input_tag = $input_tag->withValue($keywords); + + $DIC->ctrl()->setParameter( + $this, + 'tags', + 'tags_processing' + ); + + $section = $ui_factory->input()->field()->section([$input_tag], $this->lng->txt("blog_edit_keywords"), ""); + + $form_action = $DIC->ctrl()->getFormAction($this, "saveKeywordsForm"); + $form = $ui_factory->input()->container()->form()->standard($form_action, ["tags" => $section]); + + return $form; + } + + protected function getParentObjId() + { + if ($this->node_id) { + if ($this->isInWorkspace()) { + return $this->access_handler->getTree()->lookupObjectId($this->node_id); + } else { + return ilObject::_lookupObjId($this->node_id); + } + } + } + + public function saveKeywordsForm() + { + global $DIC; + + $request = $DIC->http()->request(); + $form = $this->initKeywordsForm(); + + if ($request->getMethod() == "POST" + && $request->getQueryParams()['tags'] == 'tags_processing') { + $form = $form->withRequest($request); + $result = $form->getData(); + + //TODO identify the input instead of use 0 + $keywords = $result["tags"][0]; + + if ($this->checkAccess("write") || $this->checkAccess("contribute")) { + if (is_array($keywords)) { + $this->getBlogPosting()->updateKeywords($keywords); + } + } + + $this->ctrl->redirectByClass("ilObjBlogGUI", ""); + } + } + + /** + * Get first text paragraph of page + * + * @param int $a_id + * @param bool $a_truncate + * @param int $a_truncate_length + * @param bool $a_include_picture + * @param int $a_picture_width + * @param int $a_picture_height + * @param string $a_export_directory + * @return string + */ + public static function getSnippet($a_id, $a_truncate = false, $a_truncate_length = 500, $a_truncate_sign = "...", $a_include_picture = false, $a_picture_width = 144, $a_picture_height = 144, $a_export_directory = null) + { + $bpgui = new self(0, null, $a_id); + + // scan the full page for media objects + if ($a_include_picture) { + $img = $bpgui->getFirstMediaObjectAsTag($a_picture_width, $a_picture_height, $a_export_directory); + } + + $bpgui->setRawPageContent(true); + $bpgui->setAbstractOnly(true); + + // #8627: export won't work - should we set offline mode? + $bpgui->setFileDownloadLink("."); + $bpgui->setFullscreenLink("."); + $bpgui->setSourcecodeDownloadScript("."); + + // render without title + $page = $bpgui->showPage(); + + if ($a_truncate) { + $page = ilPageObject::truncateHTML($page, $a_truncate_length, $a_truncate_sign); + } + + if ($img) { + $page = '
' . $img . $page . '
'; + } + + return $page; + } + + protected function getFirstMediaObjectAsTag($a_width = 144, $a_height = 144, $a_export_directory = null) + { + $this->obj->buildDom(); + $mob_ids = $this->obj->collectMediaObjects(); + if ($mob_ids) { + require_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + foreach ($mob_ids as $mob_id) { + $mob_obj = new ilObjMediaObject($mob_id); + $mob_item = $mob_obj->getMediaItem("Standard"); + if (stristr($mob_item->getFormat(), "image")) { + $mob_size = $mob_item->getOriginalSize(); + if ($mob_size["width"] >= $a_width || + $mob_size["height"] >= $a_height) { + if (!$a_export_directory) { + $mob_dir = ilObjMediaObject::_getDirectory($mob_obj->getId()); + } else { + // see ilCOPageHTMLExport::exportHTMLMOB() + $mob_dir = "./mobs/mm_" . $mob_obj->getId(); + } + $mob_res = self::parseImage( + $mob_size["width"], + $mob_size["height"], + $a_width, + $a_height + ); + + + $location = $mob_item->getLocationType() == "Reference" + ? $mob_item->getLocation() + : $mob_dir . "/" . $mob_item->getLocation(); + + return ''; + } + } + } + } + } + + protected static function parseImage($src_width, $src_height, $tgt_width, $tgt_height) + { + $ratio_width = $ratio_height = 1; + if ($src_width > $tgt_width) { + $ratio_width = $tgt_width / $src_width; + } + if ($src_height > $tgt_height) { + $ratio_height = $tgt_height / $src_height; + } + $shrink_ratio = min($ratio_width, $ratio_height); + + return array( + (int) round($src_width*$shrink_ratio), + (int) round($src_height*$shrink_ratio) + ); + } + + /** + * Get disabled text + * + * @param + * @return + */ + public function getDisabledText() + { + return $this->lng->txt("blog_draft_text"); + } } - -?> \ No newline at end of file diff --git a/Modules/Blog/classes/class.ilContributorTableGUI.php b/Modules/Blog/classes/class.ilContributorTableGUI.php index 42351b3f43cb2c51b75a7f1c0f2be04aa50c6fde..28e49f3b03e99b33b13ad2f1eff272e948a35d76 100644 --- a/Modules/Blog/classes/class.ilContributorTableGUI.php +++ b/Modules/Blog/classes/class.ilContributorTableGUI.php @@ -11,96 +11,88 @@ include_once './Services/Table/classes/class.ilTable2GUI.php'; */ class ilContributorTableGUI extends ilTable2GUI { - /** - * @var ilRbacReview - */ - protected $rbacreview; + /** + * @var ilRbacReview + */ + protected $rbacreview; - protected $local_roles; // [array] - - /** - * Constructor - * - * @param ilObject $a_parent_obj - * @param string $a_parent_cmd - * @param array $a_roles - */ - public function __construct($a_parent_obj, $a_parent_cmd, array $a_roles) - { - global $DIC; + protected $local_roles; // [array] + + /** + * Constructor + * + * @param ilObject $a_parent_obj + * @param string $a_parent_cmd + * @param array $a_roles + */ + public function __construct($a_parent_obj, $a_parent_cmd, array $a_roles) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->rbacreview = $DIC->rbac()->review(); - $ilCtrl = $DIC->ctrl(); - - $this->local_roles = $a_roles; - - parent::__construct($a_parent_obj, $a_parent_cmd); + $this->ctrl = $DIC->ctrl(); + $this->rbacreview = $DIC->rbac()->review(); + $ilCtrl = $DIC->ctrl(); + + $this->local_roles = $a_roles; + + parent::__construct($a_parent_obj, $a_parent_cmd); - $this->addColumn("", "", 1); - $this->addColumn($this->lng->txt("name"), "name"); - $this->addColumn($this->lng->txt("obj_role"), "role"); - - $this->setDefaultOrderField("name"); - - $this->setRowTemplate("tpl.contributor_row.html", "Modules/Blog"); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd)); - - $this->setSelectAllCheckbox("id"); // #16472 + $this->addColumn("", "", 1); + $this->addColumn($this->lng->txt("name"), "name"); + $this->addColumn($this->lng->txt("obj_role"), "role"); + + $this->setDefaultOrderField("name"); + + $this->setRowTemplate("tpl.contributor_row.html", "Modules/Blog"); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd)); + + $this->setSelectAllCheckbox("id"); // #16472 - if($this->contributor_ids) - { - $this->setTitle($this->lng->txt("blog_contributor_container_add")); - $this->addMultiCommand("addContributorContainerAction", $this->lng->txt("add")); - } - else - { - $this->setTitle($this->lng->txt("blog_contributors")); - $this->addMultiCommand("confirmRemoveContributor", $this->lng->txt("remove")); - } - - $this->getItems(); - } + if ($this->contributor_ids) { + $this->setTitle($this->lng->txt("blog_contributor_container_add")); + $this->addMultiCommand("addContributorContainerAction", $this->lng->txt("add")); + } else { + $this->setTitle($this->lng->txt("blog_contributors")); + $this->addMultiCommand("confirmRemoveContributor", $this->lng->txt("remove")); + } + + $this->getItems(); + } - protected function getItems() - { - $rbacreview = $this->rbacreview; - - $user_map = $assigned = array(); - foreach($this->local_roles as $id => $title) - { - $local = $rbacreview->assignedUsers($id); - $assigned = array_merge($assigned, $local); - foreach($local as $user_id) - { - $user_map[$user_id][] = $title; - } - } - - include_once "Services/User/classes/class.ilUserUtil.php"; - - $data = array(); - foreach(array_unique($assigned) as $id) - { - $data[] = array("id" => $id, - "name" => ilUserUtil::getNamePresentation($id, false, false, "", true), - "role" => $user_map[$id]); - } - - $this->setData($data); - } + protected function getItems() + { + $rbacreview = $this->rbacreview; + + $user_map = $assigned = array(); + foreach ($this->local_roles as $id => $title) { + $local = $rbacreview->assignedUsers($id); + $assigned = array_merge($assigned, $local); + foreach ($local as $user_id) { + $user_map[$user_id][] = $title; + } + } + + include_once "Services/User/classes/class.ilUserUtil.php"; + + $data = array(); + foreach (array_unique($assigned) as $id) { + $data[] = array("id" => $id, + "name" => ilUserUtil::getNamePresentation($id, false, false, "", true), + "role" => $user_map[$id]); + } + + $this->setData($data); + } - /** - * Fill template row - * - * @param array $a_set - */ - protected function fillRow($a_set) - { - $this->tpl->setVariable("VAL_ID", $a_set["id"]); - $this->tpl->setVariable("TXT_NAME", $a_set["name"]); - $this->tpl->setVariable("TXT_ROLES", implode(", " , $a_set["role"])); - } + /** + * Fill template row + * + * @param array $a_set + */ + protected function fillRow($a_set) + { + $this->tpl->setVariable("VAL_ID", $a_set["id"]); + $this->tpl->setVariable("TXT_NAME", $a_set["name"]); + $this->tpl->setVariable("TXT_ROLES", implode(", ", $a_set["role"])); + } } - -?> \ No newline at end of file diff --git a/Modules/Blog/classes/class.ilFSStorageBlog.php b/Modules/Blog/classes/class.ilFSStorageBlog.php index 4cd90f9ef28e5998226f9d4b1a8af6a78bd90ddc..7b76a262039d20381b30cf6739b88e9391249d24 100644 --- a/Modules/Blog/classes/class.ilFSStorageBlog.php +++ b/Modules/Blog/classes/class.ilFSStorageBlog.php @@ -1,50 +1,48 @@ - -* @version $Id$ -* -* @ingroup ModulesBlog -*/ -class ilFSStorageBlog extends ilFileSystemStorage -{ - public function __construct($a_container_id = 0) - { - parent::__construct(self::STORAGE_SECURED, true, $a_container_id); - } - - protected function getPathPostfix() - { - return 'blog'; - } - - protected function getPathPrefix() - { - return 'ilBlog'; - } -} - -?> \ No newline at end of file + +* @version $Id$ +* +* @ingroup ModulesBlog +*/ +class ilFSStorageBlog extends ilFileSystemStorage +{ + public function __construct($a_container_id = 0) + { + parent::__construct(self::STORAGE_SECURED, true, $a_container_id); + } + + protected function getPathPostfix() + { + return 'blog'; + } + + protected function getPathPrefix() + { + return 'ilBlog'; + } +} diff --git a/Modules/Blog/classes/class.ilObjBlog.php b/Modules/Blog/classes/class.ilObjBlog.php index ba23597c9b4027470a09e2de63e4cbb269722ba0..a85ff4f4bef8a7c0d09866a08ed75654565ab488 100644 --- a/Modules/Blog/classes/class.ilObjBlog.php +++ b/Modules/Blog/classes/class.ilObjBlog.php @@ -15,933 +15,890 @@ require_once "Services/Object/classes/class.ilObject2.php"; class ilObjBlog extends ilObject2 { - /** - * Constructor - */ - function __construct($a_id = 0, $a_reference = true) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_id = 0, $a_reference = true) + { + global $DIC; - parent::__construct($a_id, $a_reference); - $this->rbacreview = $DIC->rbac()->review(); - } + parent::__construct($a_id, $a_reference); + $this->rbacreview = $DIC->rbac()->review(); + } - protected $notes; // [bool] - protected $bg_color; // [string] - protected $font_color; // [string] - protected $img; // [string] - protected $ppic; // [string] - protected $rss; // [bool] - protected $approval; // [bool] - protected $style; // [bool] - protected $abstract_shorten = false; // [bool] - protected $abstract_shorten_length = self::ABSTRACT_DEFAULT_SHORTEN_LENGTH; // [int] - protected $abstract_image = false; // [bool] - protected $abstract_image_width = self::ABSTRACT_DEFAULT_IMAGE_WIDTH; // [int] - protected $abstract_image_height= self::ABSTRACT_DEFAULT_IMAGE_HEIGHT; // [int] - protected $keywords = true; // [bool] - protected $nav_mode = self::NAV_MODE_LIST; // [int] - protected $nav_mode_list_postings = self::NAV_MODE_LIST_DEFAULT_POSTINGS; // [int] - protected $nav_mode_list_months; // [int] - protected $overview_postings; // [int] - protected $authors = true; // [bool] - protected $order; - - const NAV_MODE_LIST = 1; - const NAV_MODE_MONTH = 2; - - const ABSTRACT_DEFAULT_SHORTEN_LENGTH = 500; - const ABSTRACT_DEFAULT_IMAGE_WIDTH = 144; - const ABSTRACT_DEFAULT_IMAGE_HEIGHT = 144; - const NAV_MODE_LIST_DEFAULT_POSTINGS = 10; - - function initType() - { - $this->type = "blog"; - } + protected $notes; // [bool] + protected $bg_color; // [string] + protected $font_color; // [string] + protected $img; // [string] + protected $ppic; // [string] + protected $rss; // [bool] + protected $approval; // [bool] + protected $style; // [bool] + protected $abstract_shorten = false; // [bool] + protected $abstract_shorten_length = self::ABSTRACT_DEFAULT_SHORTEN_LENGTH; // [int] + protected $abstract_image = false; // [bool] + protected $abstract_image_width = self::ABSTRACT_DEFAULT_IMAGE_WIDTH; // [int] + protected $abstract_image_height= self::ABSTRACT_DEFAULT_IMAGE_HEIGHT; // [int] + protected $keywords = true; // [bool] + protected $nav_mode = self::NAV_MODE_LIST; // [int] + protected $nav_mode_list_postings = self::NAV_MODE_LIST_DEFAULT_POSTINGS; // [int] + protected $nav_mode_list_months; // [int] + protected $overview_postings; // [int] + protected $authors = true; // [bool] + protected $order; + + const NAV_MODE_LIST = 1; + const NAV_MODE_MONTH = 2; + + const ABSTRACT_DEFAULT_SHORTEN_LENGTH = 500; + const ABSTRACT_DEFAULT_IMAGE_WIDTH = 144; + const ABSTRACT_DEFAULT_IMAGE_HEIGHT = 144; + const NAV_MODE_LIST_DEFAULT_POSTINGS = 10; + + public function initType() + { + $this->type = "blog"; + } - protected function doRead() - { - $ilDB = $this->db; + protected function doRead() + { + $ilDB = $this->db; - $set = $ilDB->query("SELECT * FROM il_blog". - " WHERE id = ".$ilDB->quote($this->id, "integer")); - $row = $ilDB->fetchAssoc($set); - $this->setProfilePicture((bool)$row["ppic"]); - $this->setBackgroundColor($row["bg_color"]); - $this->setFontColor($row["font_color"]); - $this->setImage($row["img"]); - $this->setRSS($row["rss_active"]); - $this->setApproval($row["approval"]); - $this->setAbstractShorten($row["abs_shorten"]); - $this->setAbstractShortenLength($row["abs_shorten_len"]); - $this->setAbstractImage($row["abs_image"]); - $this->setAbstractImageWidth($row["abs_img_width"]); - $this->setAbstractImageHeight($row["abs_img_height"]); - $this->setKeywords($row["keywords"]); - $this->setAuthors($row["authors"]); - $this->setNavMode($row["nav_mode"]); - $this->setNavModeListMonthsWithPostings($row["nav_list_mon_with_post"]); - $this->setNavModeListMonths($row["nav_list_mon"]); - $this->setOverviewPostings($row["ov_post"]); - if(trim($row["nav_order"])) - { - $this->setOrder(explode(";", $row["nav_order"])); - } - - // #14661 - include_once("./Services/Notes/classes/class.ilNote.php"); - $this->setNotesStatus(ilNote::commentsActivated($this->id, 0, "blog")); - - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $this->setStyleSheetId(ilObjStyleSheet::lookupObjectStyle($this->id)); - } + $set = $ilDB->query("SELECT * FROM il_blog" . + " WHERE id = " . $ilDB->quote($this->id, "integer")); + $row = $ilDB->fetchAssoc($set); + $this->setProfilePicture((bool) $row["ppic"]); + $this->setBackgroundColor($row["bg_color"]); + $this->setFontColor($row["font_color"]); + $this->setImage($row["img"]); + $this->setRSS($row["rss_active"]); + $this->setApproval($row["approval"]); + $this->setAbstractShorten($row["abs_shorten"]); + $this->setAbstractShortenLength($row["abs_shorten_len"]); + $this->setAbstractImage($row["abs_image"]); + $this->setAbstractImageWidth($row["abs_img_width"]); + $this->setAbstractImageHeight($row["abs_img_height"]); + $this->setKeywords($row["keywords"]); + $this->setAuthors($row["authors"]); + $this->setNavMode($row["nav_mode"]); + $this->setNavModeListMonthsWithPostings($row["nav_list_mon_with_post"]); + $this->setNavModeListMonths($row["nav_list_mon"]); + $this->setOverviewPostings($row["ov_post"]); + if (trim($row["nav_order"])) { + $this->setOrder(explode(";", $row["nav_order"])); + } + + // #14661 + include_once("./Services/Notes/classes/class.ilNote.php"); + $this->setNotesStatus(ilNote::commentsActivated($this->id, 0, "blog")); + + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $this->setStyleSheetId(ilObjStyleSheet::lookupObjectStyle($this->id)); + } - protected function doCreate() - { - $ilDB = $this->db; - - $ilDB->manipulate("INSERT INTO il_blog (id,ppic,rss_active,approval". - ",abs_shorten,abs_shorten_len,abs_image,abs_img_width,abs_img_height". - ",keywords,authors,nav_mode,nav_list_mon_with_post) VALUES (". - $ilDB->quote($this->id, "integer").",". - $ilDB->quote(true, "integer").",". - $ilDB->quote(true, "integer").",". - $ilDB->quote(false, "integer").",". - $ilDB->quote($this->hasAbstractShorten(), "integer").",". - $ilDB->quote($this->getAbstractShortenLength(), "integer").",". - $ilDB->quote($this->hasAbstractImage(), "integer").",". - $ilDB->quote($this->getAbstractImageWidth(), "integer").",". - $ilDB->quote($this->getAbstractImageHeight(), "integer").",". - $ilDB->quote($this->hasKeywords(), "integer").",". - $ilDB->quote($this->hasAuthors(), "integer").",". - $ilDB->quote($this->getNavMode(), "integer").",". - $ilDB->quote($this->getNavModeListMonthsWithPostings(), "integer"). - ")"); - - // #14661 - include_once("./Services/Notes/classes/class.ilNote.php"); - ilNote::activateComments($this->id, 0, "blog", true); - - /* - if ($this->getStyleSheetId() > 0) - { - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - ilObjStyleSheet::writeStyleUsage($this->id, $this->getStyleSheetId()); - } - */ - } - - protected function doDelete() - { - $ilDB = $this->db; - - $this->deleteImage(); + protected function doCreate() + { + $ilDB = $this->db; + + $ilDB->manipulate("INSERT INTO il_blog (id,ppic,rss_active,approval" . + ",abs_shorten,abs_shorten_len,abs_image,abs_img_width,abs_img_height" . + ",keywords,authors,nav_mode,nav_list_mon_with_post) VALUES (" . + $ilDB->quote($this->id, "integer") . "," . + $ilDB->quote(true, "integer") . "," . + $ilDB->quote(true, "integer") . "," . + $ilDB->quote(false, "integer") . "," . + $ilDB->quote($this->hasAbstractShorten(), "integer") . "," . + $ilDB->quote($this->getAbstractShortenLength(), "integer") . "," . + $ilDB->quote($this->hasAbstractImage(), "integer") . "," . + $ilDB->quote($this->getAbstractImageWidth(), "integer") . "," . + $ilDB->quote($this->getAbstractImageHeight(), "integer") . "," . + $ilDB->quote($this->hasKeywords(), "integer") . "," . + $ilDB->quote($this->hasAuthors(), "integer") . "," . + $ilDB->quote($this->getNavMode(), "integer") . "," . + $ilDB->quote($this->getNavModeListMonthsWithPostings(), "integer") . + ")"); + + // #14661 + include_once("./Services/Notes/classes/class.ilNote.php"); + ilNote::activateComments($this->id, 0, "blog", true); + + /* + if ($this->getStyleSheetId() > 0) + { + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + ilObjStyleSheet::writeStyleUsage($this->id, $this->getStyleSheetId()); + } + */ + } + + protected function doDelete() + { + $ilDB = $this->db; + + $this->deleteImage(); - include_once "Modules/Blog/classes/class.ilBlogPosting.php"; - ilBlogPosting::deleteAllBlogPostings($this->id); - - // remove all notifications - include_once "./Services/Notification/classes/class.ilNotification.php"; - ilNotification::removeForObject(ilNotification::TYPE_BLOG, $this->id); + include_once "Modules/Blog/classes/class.ilBlogPosting.php"; + ilBlogPosting::deleteAllBlogPostings($this->id); + + // remove all notifications + include_once "./Services/Notification/classes/class.ilNotification.php"; + ilNotification::removeForObject(ilNotification::TYPE_BLOG, $this->id); - $ilDB->manipulate("DELETE FROM il_blog". - " WHERE id = ".$ilDB->quote($this->id, "integer")); - } - - protected function doUpdate() - { - $ilDB = $this->db; - - if($this->id) - { - $ilDB->manipulate("UPDATE il_blog". - " SET ppic = ".$ilDB->quote($this->hasProfilePicture(), "integer"). - ",bg_color = ".$ilDB->quote($this->getBackgroundColor(), "text"). - ",font_color = ".$ilDB->quote($this->getFontcolor(), "text"). - ",img = ".$ilDB->quote($this->getImage(), "text"). - ",rss_active = ".$ilDB->quote($this->hasRSS(), "integer"). - ",approval = ".$ilDB->quote($this->hasApproval(), "integer"). - ",abs_shorten = ".$ilDB->quote($this->hasAbstractShorten(), "integer"). - ",abs_shorten_len = ".$ilDB->quote($this->getAbstractShortenLength(), "integer"). - ",abs_image = ".$ilDB->quote($this->hasAbstractImage(), "integer"). - ",abs_img_width = ".$ilDB->quote($this->getAbstractImageWidth(), "integer"). - ",abs_img_height = ".$ilDB->quote($this->getAbstractImageHeight(), "integer"). - ",keywords = ".$ilDB->quote($this->hasKeywords(), "integer"). - ",authors = ".$ilDB->quote($this->hasAuthors(), "integer"). - ",nav_mode = ".$ilDB->quote($this->getNavMode(), "integer"). - ",nav_list_mon_with_post = ".$ilDB->quote($this->getNavModeListMonthsWithPostings(), "integer"). - ",nav_list_mon = ".$ilDB->quote($this->getNavModeListMonths(), "integer"). - ",ov_post = ".$ilDB->quote($this->getOverviewPostings(), "integer"). - ",nav_order = ".$ilDB->quote(implode(";", $this->getOrder()), "text"). - " WHERE id = ".$ilDB->quote($this->id, "integer")); - - // #14661 - include_once("./Services/Notes/classes/class.ilNote.php"); - ilNote::activateComments($this->id, 0, "blog", $this->getNotesStatus()); - - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - ilObjStyleSheet::writeStyleUsage($this->id, $this->getStyleSheetId()); - } - } + $ilDB->manipulate("DELETE FROM il_blog" . + " WHERE id = " . $ilDB->quote($this->id, "integer")); + } + + protected function doUpdate() + { + $ilDB = $this->db; + + if ($this->id) { + $ilDB->manipulate("UPDATE il_blog" . + " SET ppic = " . $ilDB->quote($this->hasProfilePicture(), "integer") . + ",bg_color = " . $ilDB->quote($this->getBackgroundColor(), "text") . + ",font_color = " . $ilDB->quote($this->getFontcolor(), "text") . + ",img = " . $ilDB->quote($this->getImage(), "text") . + ",rss_active = " . $ilDB->quote($this->hasRSS(), "integer") . + ",approval = " . $ilDB->quote($this->hasApproval(), "integer") . + ",abs_shorten = " . $ilDB->quote($this->hasAbstractShorten(), "integer") . + ",abs_shorten_len = " . $ilDB->quote($this->getAbstractShortenLength(), "integer") . + ",abs_image = " . $ilDB->quote($this->hasAbstractImage(), "integer") . + ",abs_img_width = " . $ilDB->quote($this->getAbstractImageWidth(), "integer") . + ",abs_img_height = " . $ilDB->quote($this->getAbstractImageHeight(), "integer") . + ",keywords = " . $ilDB->quote($this->hasKeywords(), "integer") . + ",authors = " . $ilDB->quote($this->hasAuthors(), "integer") . + ",nav_mode = " . $ilDB->quote($this->getNavMode(), "integer") . + ",nav_list_mon_with_post = " . $ilDB->quote($this->getNavModeListMonthsWithPostings(), "integer") . + ",nav_list_mon = " . $ilDB->quote($this->getNavModeListMonths(), "integer") . + ",ov_post = " . $ilDB->quote($this->getOverviewPostings(), "integer") . + ",nav_order = " . $ilDB->quote(implode(";", $this->getOrder()), "text") . + " WHERE id = " . $ilDB->quote($this->id, "integer")); + + // #14661 + include_once("./Services/Notes/classes/class.ilNote.php"); + ilNote::activateComments($this->id, 0, "blog", $this->getNotesStatus()); + + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + ilObjStyleSheet::writeStyleUsage($this->id, $this->getStyleSheetId()); + } + } - protected function doCloneObject($new_obj, $a_target_id, $a_copy_id = null, $a_omit_tree = false) - { - // banner? - $img = $this->getImage(); - if($img) - { - $new_obj->setImage($img); - - $source = $this->initStorage($this->getId()); - $target = $new_obj->initStorage($new_obj->getId()); - - copy($source.$img, $target.$img); - } - - $new_obj->setNotesStatus($this->getNotesStatus()); - $new_obj->setProfilePicture($this->hasProfilePicture()); - $new_obj->setBackgroundColor($this->getBackgroundColor()); - $new_obj->setFontColor($this->getFontColor()); - $new_obj->setRSS($this->hasRSS()); - $new_obj->setApproval($this->hasApproval()); - $new_obj->setAbstractShorten($this->hasAbstractShorten()); - $new_obj->setAbstractShortenLength($this->getAbstractShortenLength()); - $new_obj->setAbstractImage($this->hasAbstractImage()); - $new_obj->setAbstractImageWidth($this->getAbstractImageWidth()); - $new_obj->setAbstractImageHeight($this->getAbstractImageHeight()); - $new_obj->update(); - - // set/copy stylesheet - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $style_id = $this->getStyleSheetId(); - if ($style_id > 0 && !ilObjStyleSheet::_lookupStandard($style_id)) - { - $style_obj = ilObjectFactory::getInstanceByObjId($style_id); - $new_id = $style_obj->ilClone(); - $new_obj->setStyleSheetId($new_id); - $new_obj->update(); - } - } - - /** - * Get notes status - * - * @return bool - */ - function getNotesStatus() - { - return $this->notes; - } + protected function doCloneObject($new_obj, $a_target_id, $a_copy_id = null, $a_omit_tree = false) + { + // banner? + $img = $this->getImage(); + if ($img) { + $new_obj->setImage($img); + + $source = $this->initStorage($this->getId()); + $target = $new_obj->initStorage($new_obj->getId()); + + copy($source . $img, $target . $img); + } + + $new_obj->setNotesStatus($this->getNotesStatus()); + $new_obj->setProfilePicture($this->hasProfilePicture()); + $new_obj->setBackgroundColor($this->getBackgroundColor()); + $new_obj->setFontColor($this->getFontColor()); + $new_obj->setRSS($this->hasRSS()); + $new_obj->setApproval($this->hasApproval()); + $new_obj->setAbstractShorten($this->hasAbstractShorten()); + $new_obj->setAbstractShortenLength($this->getAbstractShortenLength()); + $new_obj->setAbstractImage($this->hasAbstractImage()); + $new_obj->setAbstractImageWidth($this->getAbstractImageWidth()); + $new_obj->setAbstractImageHeight($this->getAbstractImageHeight()); + $new_obj->update(); + + // set/copy stylesheet + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $style_id = $this->getStyleSheetId(); + if ($style_id > 0 && !ilObjStyleSheet::_lookupStandard($style_id)) { + $style_obj = ilObjectFactory::getInstanceByObjId($style_id); + $new_id = $style_obj->ilClone(); + $new_obj->setStyleSheetId($new_id); + $new_obj->update(); + } + } + + /** + * Get notes status + * + * @return bool + */ + public function getNotesStatus() + { + return $this->notes; + } - /** - * Toggle notes status - * - * @param bool $a_status - */ - function setNotesStatus($a_status) - { - $this->notes = (bool)$a_status; - } - - /** - * Get profile picture status - * - * @return bool - */ - function hasProfilePicture() - { - return $this->ppic; - } + /** + * Toggle notes status + * + * @param bool $a_status + */ + public function setNotesStatus($a_status) + { + $this->notes = (bool) $a_status; + } + + /** + * Get profile picture status + * + * @return bool + */ + public function hasProfilePicture() + { + return $this->ppic; + } - /** - * Toggle profile picture status - * - * @param bool $a_status - */ - function setProfilePicture($a_status) - { - $this->ppic = (bool)$a_status; - } - - /** - * Get background color - * - * @return string - */ - function getBackgroundColor() - { - if(!$this->bg_color) - { - $this->bg_color = "ffffff"; - } - return $this->bg_color; - } + /** + * Toggle profile picture status + * + * @param bool $a_status + */ + public function setProfilePicture($a_status) + { + $this->ppic = (bool) $a_status; + } + + /** + * Get background color + * + * @return string + */ + public function getBackgroundColor() + { + if (!$this->bg_color) { + $this->bg_color = "ffffff"; + } + return $this->bg_color; + } - /** - * Set background color - * - * @param string $a_value - */ - function setBackgroundColor($a_value) - { - $this->bg_color = (string)$a_value; - } - - /** - * Get font color - * - * @return string - */ - function getFontColor() - { - if(!$this->font_color) - { - $this->font_color = "505050"; - } - return $this->font_color; - } + /** + * Set background color + * + * @param string $a_value + */ + public function setBackgroundColor($a_value) + { + $this->bg_color = (string) $a_value; + } + + /** + * Get font color + * + * @return string + */ + public function getFontColor() + { + if (!$this->font_color) { + $this->font_color = "505050"; + } + return $this->font_color; + } - /** - * Set font color - * - * @param string $a_value - */ - function setFontColor($a_value) - { - $this->font_color = (string)$a_value; - } - - /** - * Get banner image - * - * @return string - */ - function getImage() - { - return $this->img; - } + /** + * Set font color + * + * @param string $a_value + */ + public function setFontColor($a_value) + { + $this->font_color = (string) $a_value; + } + + /** + * Get banner image + * + * @return string + */ + public function getImage() + { + return $this->img; + } - /** - * Set banner image - * - * @param string $a_value - */ - function setImage($a_value) - { - $this->img = (string)$a_value; - } - - /** - * Get banner image incl. path - * - * @param bool $a_as_thumb - */ - function getImageFullPath($a_as_thumb = false) - { - if($this->img) - { - $path = $this->initStorage($this->id); - if(!$a_as_thumb) - { - return $path.$this->img; - } - else - { - return $path."thb_".$this->img; - } - } - } - - /** - * remove existing file - */ - public function deleteImage() - { - if($this->id) - { - include_once "Modules/Blog/classes/class.ilFSStorageBlog.php"; - $storage = new ilFSStorageBlog($this->id); - $storage->delete(); - - $this->setImage(null); - - $this->handleQuotaUpdate(); - } - } + /** + * Set banner image + * + * @param string $a_value + */ + public function setImage($a_value) + { + $this->img = (string) $a_value; + } + + /** + * Get banner image incl. path + * + * @param bool $a_as_thumb + */ + public function getImageFullPath($a_as_thumb = false) + { + if ($this->img) { + $path = $this->initStorage($this->id); + if (!$a_as_thumb) { + return $path . $this->img; + } else { + return $path . "thb_" . $this->img; + } + } + } + + /** + * remove existing file + */ + public function deleteImage() + { + if ($this->id) { + include_once "Modules/Blog/classes/class.ilFSStorageBlog.php"; + $storage = new ilFSStorageBlog($this->id); + $storage->delete(); + + $this->setImage(null); + + $this->handleQuotaUpdate(); + } + } - /** - * 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/Blog/classes/class.ilFSStorageBlog.php"; - $storage = new ilFSStorageBlog($a_id); - $storage->create(); - - $path = $storage->getAbsolutePath()."/"; - - if($a_subdir) - { - $path .= $a_subdir."/"; - - if(!is_dir($path)) - { - mkdir($path); - } - } - - return $path; - } - - /** - * Upload new image file - * - * @param array $a_upload - * @return bool - */ - function uploadImage(array $a_upload) - { - if(!$this->id) - { - return false; - } - - $this->deleteImage(); - - // #10074 - $clean_name = preg_replace("/[^a-zA-Z0-9\_\.\-]/", "", $a_upload["name"]); - - $path = $this->initStorage($this->id); - $original = "org_".$this->id."_".$clean_name; - $thumb = "thb_".$this->id."_".$clean_name; - $processed = $this->id."_".$clean_name; + /** + * 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/Blog/classes/class.ilFSStorageBlog.php"; + $storage = new ilFSStorageBlog($a_id); + $storage->create(); + + $path = $storage->getAbsolutePath() . "/"; + + if ($a_subdir) { + $path .= $a_subdir . "/"; + + if (!is_dir($path)) { + mkdir($path); + } + } + + return $path; + } + + /** + * Upload new image file + * + * @param array $a_upload + * @return bool + */ + public function uploadImage(array $a_upload) + { + if (!$this->id) { + return false; + } + + $this->deleteImage(); + + // #10074 + $clean_name = preg_replace("/[^a-zA-Z0-9\_\.\-]/", "", $a_upload["name"]); + + $path = $this->initStorage($this->id); + $original = "org_" . $this->id . "_" . $clean_name; + $thumb = "thb_" . $this->id . "_" . $clean_name; + $processed = $this->id . "_" . $clean_name; - if (ilUtil::moveUploadedFile($a_upload["tmp_name"], $original, $path.$original)) - { - chmod($path.$original, 0770); + if (ilUtil::moveUploadedFile($a_upload["tmp_name"], $original, $path . $original)) { + chmod($path . $original, 0770); - $blga_set = new ilSetting("blga"); - /* as banner height should overflow, we only handle width - $dimensions = $blga_set->get("banner_width")."x". - $blga_set->get("banner_height"); - */ - $dimensions = $blga_set->get("banner_width"); - - // take quality 100 to avoid jpeg artefacts when uploading jpeg files - // taking only frame [0] to avoid problems with animated gifs - $original_file = ilUtil::escapeShellArg($path.$original); - $thumb_file = ilUtil::escapeShellArg($path.$thumb); - $processed_file = ilUtil::escapeShellArg($path.$processed); - ilUtil::execConvert($original_file."[0] -geometry 100x100 -quality 100 JPEG:".$thumb_file); - ilUtil::execConvert($original_file."[0] -geometry ".$dimensions." -quality 100 JPEG:".$processed_file); - - $this->setImage($processed); - - $this->handleQuotaUpdate(); - - return true; - } - return false; - } - - /** - * Get RSS status - * - * @return bool - */ - function hasRSS() - { - return $this->rss; - } + $blga_set = new ilSetting("blga"); + /* as banner height should overflow, we only handle width + $dimensions = $blga_set->get("banner_width")."x". + $blga_set->get("banner_height"); + */ + $dimensions = $blga_set->get("banner_width"); + + // take quality 100 to avoid jpeg artefacts when uploading jpeg files + // taking only frame [0] to avoid problems with animated gifs + $original_file = ilUtil::escapeShellArg($path . $original); + $thumb_file = ilUtil::escapeShellArg($path . $thumb); + $processed_file = ilUtil::escapeShellArg($path . $processed); + ilUtil::execConvert($original_file . "[0] -geometry 100x100 -quality 100 JPEG:" . $thumb_file); + ilUtil::execConvert($original_file . "[0] -geometry " . $dimensions . " -quality 100 JPEG:" . $processed_file); + + $this->setImage($processed); + + $this->handleQuotaUpdate(); + + return true; + } + return false; + } + + /** + * Get RSS status + * + * @return bool + */ + public function hasRSS() + { + return $this->rss; + } - /** - * Toggle RSS status - * - * @param bool $a_status - */ - function setRSS($a_status) - { - $this->rss = (bool)$a_status; - } - - /** - * Get approval status - * - * @return bool - */ - function hasApproval() - { - return (bool)$this->approval; - } + /** + * Toggle RSS status + * + * @param bool $a_status + */ + public function setRSS($a_status) + { + $this->rss = (bool) $a_status; + } + + /** + * Get approval status + * + * @return bool + */ + public function hasApproval() + { + return (bool) $this->approval; + } - /** - * Toggle approval status - * - * @param bool $a_status - */ - function setApproval($a_status) - { - $this->approval = (bool)$a_status; - } - - /** - * Get style sheet id - * - * @return bool - */ - function getStyleSheetId() - { - return (int)$this->style; - } + /** + * Toggle approval status + * + * @param bool $a_status + */ + public function setApproval($a_status) + { + $this->approval = (bool) $a_status; + } + + /** + * Get style sheet id + * + * @return bool + */ + public function getStyleSheetId() + { + return (int) $this->style; + } - /** - * Set style sheet id - * - * @param int $a_style - */ - function setStyleSheetId($a_style) - { - $this->style = (int)$a_style; - } - - function hasAbstractShorten() - { - return $this->abstract_shorten; - } - - function setAbstractShorten($a_value) - { - $this->abstract_shorten = (bool)$a_value; - } - - function getAbstractShortenLength() - { - return $this->abstract_shorten_length; - } - - function setAbstractShortenLength($a_value) - { - $this->abstract_shorten_length = (int)$a_value; - } - - function hasAbstractImage() - { - return $this->abstract_image; - } - - function setAbstractImage($a_value) - { - $this->abstract_image = (bool)$a_value; - } - - function getAbstractImageWidth() - { - return $this->abstract_image_width; - } - - function setAbstractImageWidth($a_value) - { - $this->abstract_image_width = (int)$a_value; - } - - function getAbstractImageHeight() - { - return $this->abstract_image_height; - } - - function setAbstractImageHeight($a_value) - { - $this->abstract_image_height = (int)$a_value; - } - - function setKeywords($a_value) - { - $this->keywords = (bool)$a_value; - } - - function hasKeywords() - { - return $this->keywords; - } - - function setAuthors($a_value) - { - $this->authors = (bool)$a_value; - } - - function hasAuthors() - { - return $this->authors; - } - - function setNavMode($a_value) - { - $a_value = (int)$a_value; - if(in_array($a_value, array(self::NAV_MODE_LIST, self::NAV_MODE_MONTH))) - { - $this->nav_mode = $a_value; - } - } - - function getNavMode() - { - return $this->nav_mode; - } - - function setNavModeListMonthsWithPostings($a_value) - { - $this->nav_mode_list_months_with_post = (int)$a_value; - } - - function getNavModeListMonthsWithPostings() - { - return $this->nav_mode_list_months_with_post; - } - - function setNavModeListMonths($a_value) - { - if(!$a_value) - { - $a_value = null; - } - else - { - $a_value = (int)$a_value; - } - $this->nav_mode_list_months = $a_value; - } - - function getNavModeListMonths() - { - return $this->nav_mode_list_months; - } - - function setOverviewPostings($a_value) - { - if(!$a_value) - { - $a_value = null; - } - else - { - $a_value = (int)$a_value; - } - $this->overview_postings = $a_value; - } - - function getOverviewPostings() - { - return $this->overview_postings; - } - - function setOrder(array $a_values = null) - { - $this->order = $a_values; - } - - function getOrder() - { - return (array)$this->order; - } - - static function sendNotification($a_action, $a_in_wsp, $a_blog_node_id, $a_posting_id, $a_comment = null) - { - global $DIC; + /** + * Set style sheet id + * + * @param int $a_style + */ + public function setStyleSheetId($a_style) + { + $this->style = (int) $a_style; + } + + public function hasAbstractShorten() + { + return $this->abstract_shorten; + } + + public function setAbstractShorten($a_value) + { + $this->abstract_shorten = (bool) $a_value; + } + + public function getAbstractShortenLength() + { + return $this->abstract_shorten_length; + } + + public function setAbstractShortenLength($a_value) + { + $this->abstract_shorten_length = (int) $a_value; + } + + public function hasAbstractImage() + { + return $this->abstract_image; + } + + public function setAbstractImage($a_value) + { + $this->abstract_image = (bool) $a_value; + } + + public function getAbstractImageWidth() + { + return $this->abstract_image_width; + } + + public function setAbstractImageWidth($a_value) + { + $this->abstract_image_width = (int) $a_value; + } + + public function getAbstractImageHeight() + { + return $this->abstract_image_height; + } + + public function setAbstractImageHeight($a_value) + { + $this->abstract_image_height = (int) $a_value; + } + + public function setKeywords($a_value) + { + $this->keywords = (bool) $a_value; + } + + public function hasKeywords() + { + return $this->keywords; + } + + public function setAuthors($a_value) + { + $this->authors = (bool) $a_value; + } + + public function hasAuthors() + { + return $this->authors; + } + + public function setNavMode($a_value) + { + $a_value = (int) $a_value; + if (in_array($a_value, array(self::NAV_MODE_LIST, self::NAV_MODE_MONTH))) { + $this->nav_mode = $a_value; + } + } + + public function getNavMode() + { + return $this->nav_mode; + } + + public function setNavModeListMonthsWithPostings($a_value) + { + $this->nav_mode_list_months_with_post = (int) $a_value; + } + + public function getNavModeListMonthsWithPostings() + { + return $this->nav_mode_list_months_with_post; + } + + public function setNavModeListMonths($a_value) + { + if (!$a_value) { + $a_value = null; + } else { + $a_value = (int) $a_value; + } + $this->nav_mode_list_months = $a_value; + } + + public function getNavModeListMonths() + { + return $this->nav_mode_list_months; + } + + public function setOverviewPostings($a_value) + { + if (!$a_value) { + $a_value = null; + } else { + $a_value = (int) $a_value; + } + $this->overview_postings = $a_value; + } + + public function getOverviewPostings() + { + return $this->overview_postings; + } + + public function setOrder(array $a_values = null) + { + $this->order = $a_values; + } + + public function getOrder() + { + return (array) $this->order; + } + + public static function sendNotification($a_action, $a_in_wsp, $a_blog_node_id, $a_posting_id, $a_comment = null) + { + global $DIC; - $ilUser = $DIC->user(); - - // get blog object id (repository or workspace) - if($a_in_wsp) - { - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; - $tree = new ilWorkspaceTree($ilUser->getId()); // owner of tree is irrelevant - $blog_obj_id = $tree->lookupObjectId($a_blog_node_id); - $access_handler = new ilWorkspaceAccessHandler($tree); - } - else - { - $blog_obj_id = ilObject::_lookupObjId($a_blog_node_id); - $access_handler = null; - } - if(!$blog_obj_id) - { - return; - } - - include_once "./Modules/Blog/classes/class.ilBlogPosting.php"; - $posting = new ilBlogPosting($a_posting_id); - - // #11138 - $ignore_threshold = ($a_action == "comment"); - - $admin_only = false; - - // approval handling - if(!$posting->isApproved()) - { - $blog = new self($blog_obj_id, false); - if($blog->hasApproval()) - { - switch($a_action) - { - case "update": - // un-approved posting was updated - no notifications - return; + $ilUser = $DIC->user(); + + // get blog object id (repository or workspace) + if ($a_in_wsp) { + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; + $tree = new ilWorkspaceTree($ilUser->getId()); // owner of tree is irrelevant + $blog_obj_id = $tree->lookupObjectId($a_blog_node_id); + $access_handler = new ilWorkspaceAccessHandler($tree); + } else { + $blog_obj_id = ilObject::_lookupObjId($a_blog_node_id); + $access_handler = null; + } + if (!$blog_obj_id) { + return; + } + + include_once "./Modules/Blog/classes/class.ilBlogPosting.php"; + $posting = new ilBlogPosting($a_posting_id); + + // #11138 + $ignore_threshold = ($a_action == "comment"); + + $admin_only = false; + + // approval handling + if (!$posting->isApproved()) { + $blog = new self($blog_obj_id, false); + if ($blog->hasApproval()) { + switch ($a_action) { + case "update": + // un-approved posting was updated - no notifications + return; - case "new": - // un-approved posting was activated - admin-only notification - $admin_only = true; - $ignore_threshold = true; - $a_action = "approve"; - break; - } - } - } - - // create/update news item (only in repository) - if(!$a_in_wsp && - in_array($a_action, array("update", "new"))) - { - $posting->handleNews(($a_action == "update")); - } - - // recipients - include_once "./Services/Notification/classes/class.ilNotification.php"; - $users = ilNotification::getNotificationsForObject(ilNotification::TYPE_BLOG, - $blog_obj_id, $a_posting_id, $ignore_threshold); - if(!sizeof($users)) - { - return; - } + case "new": + // un-approved posting was activated - admin-only notification + $admin_only = true; + $ignore_threshold = true; + $a_action = "approve"; + break; + } + } + } + + // create/update news item (only in repository) + if (!$a_in_wsp && + in_array($a_action, array("update", "new"))) { + $posting->handleNews(($a_action == "update")); + } + + // recipients + include_once "./Services/Notification/classes/class.ilNotification.php"; + $users = ilNotification::getNotificationsForObject( + ilNotification::TYPE_BLOG, + $blog_obj_id, + $a_posting_id, + $ignore_threshold + ); + if (!sizeof($users)) { + return; + } - include_once "./Services/Notification/classes/class.ilSystemNotification.php"; - $ntf = new ilSystemNotification($a_in_wsp); - $ntf->setLangModules(array("blog")); - $ntf->setRefId($a_blog_node_id); - $ntf->setChangedByUserId($ilUser->getId()); - $ntf->setSubjectLangId('blog_change_notification_subject'); - $ntf->setIntroductionLangId('blog_change_notification_body_'.$a_action); - $ntf->addAdditionalInfo('blog_posting', $posting->getTitle()); - if($a_comment) - { - $ntf->addAdditionalInfo('comment', $a_comment, true); - } - $ntf->setGotoLangId('blog_change_notification_link'); - $ntf->setReasonLangId('blog_change_notification_reason'); - - $abstract = $posting->getNotificationAbstract(); - if($abstract) - { - $ntf->addAdditionalInfo('content', $abstract, true); - } - - $notified = $ntf->sendMail($users, "_".$a_posting_id, - ($admin_only ? "write" : "read")); - - // #14387 - if(sizeof($notified)) - { - ilNotification::updateNotificationTime(ilNotification::TYPE_BLOG, $blog_obj_id, $notified, $a_posting_id); - } - } - - /** - * Deliver blog as rss feed - * - * @param int $a_wsp_id - */ - static function deliverRSS($a_wsp_id) - { - global $DIC; + include_once "./Services/Notification/classes/class.ilSystemNotification.php"; + $ntf = new ilSystemNotification($a_in_wsp); + $ntf->setLangModules(array("blog")); + $ntf->setRefId($a_blog_node_id); + $ntf->setChangedByUserId($ilUser->getId()); + $ntf->setSubjectLangId('blog_change_notification_subject'); + $ntf->setIntroductionLangId('blog_change_notification_body_' . $a_action); + $ntf->addAdditionalInfo('blog_posting', $posting->getTitle()); + if ($a_comment) { + $ntf->addAdditionalInfo('comment', $a_comment, true); + } + $ntf->setGotoLangId('blog_change_notification_link'); + $ntf->setReasonLangId('blog_change_notification_reason'); + + $abstract = $posting->getNotificationAbstract(); + if ($abstract) { + $ntf->addAdditionalInfo('content', $abstract, true); + } + + $notified = $ntf->sendMail( + $users, + "_" . $a_posting_id, + ($admin_only ? "write" : "read") + ); + + // #14387 + if (sizeof($notified)) { + ilNotification::updateNotificationTime(ilNotification::TYPE_BLOG, $blog_obj_id, $notified, $a_posting_id); + } + } + + /** + * Deliver blog as rss feed + * + * @param int $a_wsp_id + */ + public static function deliverRSS($a_wsp_id) + { + global $DIC; - $tpl = $DIC["tpl"]; - $ilSetting = $DIC->settings(); - - if(!$ilSetting->get('enable_global_profiles')) - { - return; - } - - // #10827 - if(substr($a_wsp_id, -4) != "_cll") - { - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - $wsp_id = new ilWorkspaceTree(0); - $obj_id = $wsp_id->lookupObjectId($a_wsp_id); - $is_wsp = "_wsp"; - } - else - { - $a_wsp_id = substr($a_wsp_id, 0, -4); - $obj_id = ilObject::_lookupObjId($a_wsp_id); - $is_wsp = null; - } - if(!$obj_id) - { - return; - } - - $blog = new self($obj_id, false); - if(!$blog->hasRSS()) - { - return; - } - - include_once "Services/Feeds/classes/class.ilFeedWriter.php"; - $feed = new ilFeedWriter(); - - include_once "Services/Link/classes/class.ilLink.php"; - $url = ilLink::_getStaticLink($a_wsp_id, "blog", true, $is_wsp); - $url = str_replace("&", "&", $url); - - // #11870 - $feed->setChannelTitle(str_replace("&", "&", $blog->getTitle())); - $feed->setChannelDescription(str_replace("&", "&", $blog->getDescription())); - $feed->setChannelLink($url); - - // needed for blogpostinggui / pagegui - $tpl = new ilTemplate("tpl.main.html", true, true); - - include_once("./Modules/Blog/classes/class.ilBlogPosting.php"); - include_once("./Modules/Blog/classes/class.ilBlogPostingGUI.php"); - foreach(ilBlogPosting::getAllPostings($obj_id) as $item) - { - $id = $item["id"]; + $tpl = $DIC["tpl"]; + $ilSetting = $DIC->settings(); + + if (!$ilSetting->get('enable_global_profiles')) { + return; + } + + // #10827 + if (substr($a_wsp_id, -4) != "_cll") { + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + $wsp_id = new ilWorkspaceTree(0); + $obj_id = $wsp_id->lookupObjectId($a_wsp_id); + $is_wsp = "_wsp"; + } else { + $a_wsp_id = substr($a_wsp_id, 0, -4); + $obj_id = ilObject::_lookupObjId($a_wsp_id); + $is_wsp = null; + } + if (!$obj_id) { + return; + } + + $blog = new self($obj_id, false); + if (!$blog->hasRSS()) { + return; + } + + include_once "Services/Feeds/classes/class.ilFeedWriter.php"; + $feed = new ilFeedWriter(); + + include_once "Services/Link/classes/class.ilLink.php"; + $url = ilLink::_getStaticLink($a_wsp_id, "blog", true, $is_wsp); + $url = str_replace("&", "&", $url); + + // #11870 + $feed->setChannelTitle(str_replace("&", "&", $blog->getTitle())); + $feed->setChannelDescription(str_replace("&", "&", $blog->getDescription())); + $feed->setChannelLink($url); + + // needed for blogpostinggui / pagegui + $tpl = new ilTemplate("tpl.main.html", true, true); + + include_once("./Modules/Blog/classes/class.ilBlogPosting.php"); + include_once("./Modules/Blog/classes/class.ilBlogPostingGUI.php"); + foreach (ilBlogPosting::getAllPostings($obj_id) as $item) { + $id = $item["id"]; - // 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 = ""; + // 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 * @version $Id:$ * @@ -14,37 +14,34 @@ require_once "./Services/Object/classes/class.ilObject.php"; class ilObjBlogAdministration extends ilObject { - /** - * Constructor - * @access public - * @param integer reference_id or object_id - * @param boolean treat the id as reference_id (true) or object_id (false) - */ - public function __construct($a_id = 0,$a_call_by_reference = true) - { - $this->type = "blga"; - parent::__construct($a_id,$a_call_by_reference); - - $this->lng->loadLanguageModule("blog"); - } + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + $this->type = "blga"; + parent::__construct($a_id, $a_call_by_reference); - /** - * update object data - * - * @access public - * @return boolean - */ - public function update() - { - if (!parent::update()) - { - return false; - } + $this->lng->loadLanguageModule("blog"); + } - // put here object specific stuff - - return true; - } + /** + * update object data + * + * @access public + * @return boolean + */ + public function update() + { + if (!parent::update()) { + return false; + } -} -?> + // put here object specific stuff + + return true; + } +} diff --git a/Modules/Blog/classes/class.ilObjBlogAdministrationAccess.php b/Modules/Blog/classes/class.ilObjBlogAdministrationAccess.php index 395ef655bebc81d7dbd66058f7b633145c17b552..f35232c9566f411cb2ea6f885e875a03b9cff847 100644 --- a/Modules/Blog/classes/class.ilObjBlogAdministrationAccess.php +++ b/Modules/Blog/classes/class.ilObjBlogAdministrationAccess.php @@ -13,8 +13,4 @@ include_once("./Services/Object/classes/class.ilObjectAccess.php"); */ class ilObjBlogAdministrationAccess extends ilObjectAccess { - - } - -?> diff --git a/Modules/Blog/classes/class.ilObjBlogAdministrationGUI.php b/Modules/Blog/classes/class.ilObjBlogAdministrationGUI.php index 7e6c6fb4d9ab62b580053e307e12547ba30d8bc0..b13abd125e439a6c4fe2616c3f8ec0c07d1216f8 100644 --- a/Modules/Blog/classes/class.ilObjBlogAdministrationGUI.php +++ b/Modules/Blog/classes/class.ilObjBlogAdministrationGUI.php @@ -15,200 +15,191 @@ include_once("./Services/Object/classes/class.ilObjectGUI.php"); */ class ilObjBlogAdministrationGUI extends ilObjectGUI { - /** - * Contructor - * - * @access public - */ - public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) - { - global $DIC; + /** + * Contructor + * + * @access public + */ + public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) + { + global $DIC; - $this->lng = $DIC->language(); - $this->settings = $DIC->settings(); - $this->ctrl = $DIC->ctrl(); - $this->type = "blga"; - parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); + $this->lng = $DIC->language(); + $this->settings = $DIC->settings(); + $this->ctrl = $DIC->ctrl(); + $this->type = "blga"; + parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); - $this->lng->loadLanguageModule("blog"); - } + $this->lng->loadLanguageModule("blog"); + } - /** - * Execute command - * - * @access public - * - */ - public function executeCommand() - { - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); + /** + * Execute command + * + * @access public + * + */ + public function executeCommand() + { + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); - $this->prepareOutput(); + $this->prepareOutput(); - switch($next_class) - { - case 'ilpermissiongui': - $this->tabs_gui->setTabActive('perm_settings'); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $this->ctrl->forwardCommand($perm_gui); - break; + switch ($next_class) { + case 'ilpermissiongui': + $this->tabs_gui->setTabActive('perm_settings'); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $this->ctrl->forwardCommand($perm_gui); + break; - default: - if(!$cmd || $cmd == 'view') - { - $cmd = "editSettings"; - } + default: + if (!$cmd || $cmd == 'view') { + $cmd = "editSettings"; + } - $this->$cmd(); - break; - } - return true; - } + $this->$cmd(); + break; + } + return true; + } - /** - * Get tabs - * - * @access public - * - */ - public function getAdminTabs() - { - if ($this->checkPermissionBool("visible,read")) - { - $this->tabs_gui->addTarget("settings", - $this->ctrl->getLinkTarget($this, "editSettings"), - array("editSettings", "view")); - } + /** + * Get tabs + * + * @access public + * + */ + public function getAdminTabs() + { + if ($this->checkPermissionBool("visible,read")) { + $this->tabs_gui->addTarget( + "settings", + $this->ctrl->getLinkTarget($this, "editSettings"), + array("editSettings", "view") + ); + } - if ($this->checkPermissionBool('edit_permission')) - { - $this->tabs_gui->addTarget("perm_settings", - $this->ctrl->getLinkTargetByClass('ilpermissiongui',"perm"), - array(),'ilpermissiongui'); - } - } + if ($this->checkPermissionBool('edit_permission')) { + $this->tabs_gui->addTarget( + "perm_settings", + $this->ctrl->getLinkTargetByClass('ilpermissiongui', "perm"), + array(), + 'ilpermissiongui' + ); + } + } - - /** - * Edit settings. - */ - public function editSettings($a_form = null) - { - $lng = $this->lng; - $ilSetting = $this->settings; - - $this->tabs_gui->setTabActive('settings'); - - if (!$ilSetting->get("disable_wsp_blogs")) - { - ilUtil::sendInfo($lng->txt("blog_admin_toggle_info")); - } - else - { - ilUtil::sendInfo($lng->txt("blog_admin_inactive_info")); - } - - if(!$a_form) - { - $a_form = $this->initFormSettings(); - } - $this->tpl->setContent($a_form->getHTML()); - return true; - } + + /** + * Edit settings. + */ + public function editSettings($a_form = null) + { + $lng = $this->lng; + $ilSetting = $this->settings; + + $this->tabs_gui->setTabActive('settings'); + + if (!$ilSetting->get("disable_wsp_blogs")) { + ilUtil::sendInfo($lng->txt("blog_admin_toggle_info")); + } else { + ilUtil::sendInfo($lng->txt("blog_admin_inactive_info")); + } + + if (!$a_form) { + $a_form = $this->initFormSettings(); + } + $this->tpl->setContent($a_form->getHTML()); + return true; + } - /** - * Save settings - */ - public function saveSettings() - { - $ilCtrl = $this->ctrl; - - $this->checkPermission("write"); - - $form = $this->initFormSettings(); - if($form->checkInput()) - { - $banner = (bool)$form->getInput("banner"); - - $blga_set = new ilSetting("blga"); - $blga_set->set("banner", $banner); - $blga_set->set("banner_width", (int)$form->getInput("width")); - $blga_set->set("banner_height", (int)$form->getInput("height")); - $blga_set->set("mask", (bool)$form->getInput("mask")); - - ilUtil::sendSuccess($this->lng->txt("settings_saved"),true); - $ilCtrl->redirect($this, "editSettings"); - } - - $form->setValuesByPost(); - $this->editSettings($form); - } + /** + * Save settings + */ + public function saveSettings() + { + $ilCtrl = $this->ctrl; + + $this->checkPermission("write"); + + $form = $this->initFormSettings(); + if ($form->checkInput()) { + $banner = (bool) $form->getInput("banner"); + + $blga_set = new ilSetting("blga"); + $blga_set->set("banner", $banner); + $blga_set->set("banner_width", (int) $form->getInput("width")); + $blga_set->set("banner_height", (int) $form->getInput("height")); + $blga_set->set("mask", (bool) $form->getInput("mask")); + + ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "editSettings"); + } + + $form->setValuesByPost(); + $this->editSettings($form); + } - /** - * Save settings - */ - public function cancel() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirect($this, "view"); - } - - /** - * Init settings property form - * - * @access protected - */ - protected function initFormSettings() - { - $lng = $this->lng; - - include_once('Services/Form/classes/class.ilPropertyFormGUI.php'); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - $form->setTitle($this->lng->txt('blog_settings')); - - if ($this->checkPermissionBool("write")) - { - $form->addCommandButton('saveSettings',$this->lng->txt('save')); - $form->addCommandButton('cancel',$this->lng->txt('cancel')); - } + /** + * Save settings + */ + public function cancel() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirect($this, "view"); + } + + /** + * Init settings property form + * + * @access protected + */ + protected function initFormSettings() + { + $lng = $this->lng; + + include_once('Services/Form/classes/class.ilPropertyFormGUI.php'); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this)); + $form->setTitle($this->lng->txt('blog_settings')); + + if ($this->checkPermissionBool("write")) { + $form->addCommandButton('saveSettings', $this->lng->txt('save')); + $form->addCommandButton('cancel', $this->lng->txt('cancel')); + } - $banner = new ilCheckboxInputGUI($lng->txt("blog_preview_banner"), "banner"); - $banner->setInfo($lng->txt("blog_preview_banner_info")); - $form->addItem($banner); - - $width = new ilNumberInputGUI($lng->txt("blog_preview_banner_width"), "width"); - $width->setRequired(true); - $width->setSize(4); - $banner->addSubItem($width); - - $height = new ilNumberInputGUI($lng->txt("blog_preview_banner_height"), "height"); - $height->setRequired(true); - $height->setSize(4); - $banner->addSubItem($height); - - $blga_set = new ilSetting("blga"); - $banner->setChecked($blga_set->get("banner", false)); - if($blga_set->get("banner")) - { - $width->setValue($blga_set->get("banner_width")); - $height->setValue($blga_set->get("banner_height")); - } - else - { - $width->setValue(1370); - $height->setValue(100); - } - - $mask = new ilCheckboxInputGUI($lng->txt("blog_allow_html"), "mask"); - $mask->setInfo($lng->txt("blog_allow_html_info")); - $mask->setChecked($blga_set->get("mask", false)); - $form->addItem($mask); + $banner = new ilCheckboxInputGUI($lng->txt("blog_preview_banner"), "banner"); + $banner->setInfo($lng->txt("blog_preview_banner_info")); + $form->addItem($banner); + + $width = new ilNumberInputGUI($lng->txt("blog_preview_banner_width"), "width"); + $width->setRequired(true); + $width->setSize(4); + $banner->addSubItem($width); + + $height = new ilNumberInputGUI($lng->txt("blog_preview_banner_height"), "height"); + $height->setRequired(true); + $height->setSize(4); + $banner->addSubItem($height); + + $blga_set = new ilSetting("blga"); + $banner->setChecked($blga_set->get("banner", false)); + if ($blga_set->get("banner")) { + $width->setValue($blga_set->get("banner_width")); + $height->setValue($blga_set->get("banner_height")); + } else { + $width->setValue(1370); + $height->setValue(100); + } + + $mask = new ilCheckboxInputGUI($lng->txt("blog_allow_html"), "mask"); + $mask->setInfo($lng->txt("blog_allow_html_info")); + $mask->setChecked($blga_set->get("mask", false)); + $form->addItem($mask); - return $form; - } + return $form; + } } -?> \ No newline at end of file diff --git a/Modules/Blog/classes/class.ilObjBlogGUI.php b/Modules/Blog/classes/class.ilObjBlogGUI.php index b4bb61c83621624479d7e7edf28f441034c6026b..10c0c77b139e83c1da51eea490da77f9235e7d01 100644 --- a/Modules/Blog/classes/class.ilObjBlogGUI.php +++ b/Modules/Blog/classes/class.ilObjBlogGUI.php @@ -21,3596 +21,3330 @@ require_once "./Services/PersonalDesktop/interfaces/interface.ilDesktopItemHandl */ class ilObjBlogGUI extends ilObject2GUI implements ilDesktopItemHandling { - /** - * @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] - - 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"); - } - - 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"; - } - else if($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"]); - } - else if($banner->getDeletionFlag()) - { - $this->object->deleteImage(); - } - } - } - - 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(); - } - } - - 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 - */ - 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 + * @author Jörg Lützenkirchen * @version $Id$ * * @ingroup ModulesBookingManager */ class ilBookingObjectsTableGUI extends ilTable2GUI { - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - protected $ref_id; // [int] - protected $pool_id; // [int] - protected $has_schedule; // [bool] - protected $may_edit; // [bool] - protected $may_assign; // [bool] - protected $overall_limit; // [int] - protected $reservations = array(); // [array] - protected $current_bookings; // [int] - protected $advmd; // [array] - protected $filter; // [array] - protected $ui_factory; - protected $ui_renderer; - - /** - * Constructor - * @param object $a_parent_obj - * @param string $a_parent_cmd - * @param int $a_ref_id - * @param int $a_pool_id - * @param bool $a_pool_has_schedule - * @param int $a_pool_overall_limit - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_ref_id, $a_pool_id, $a_pool_has_schedule, $a_pool_overall_limit) - { - global $DIC; + protected $ref_id; // [int] + protected $pool_id; // [int] + protected $has_schedule; // [bool] + protected $may_edit; // [bool] + protected $may_assign; // [bool] + protected $overall_limit; // [int] + protected $reservations = array(); // [array] + protected $current_bookings; // [int] + protected $advmd; // [array] + protected $filter; // [array] + protected $ui_factory; + protected $ui_renderer; + + /** + * Constructor + * @param object $a_parent_obj + * @param string $a_parent_cmd + * @param int $a_ref_id + * @param int $a_pool_id + * @param bool $a_pool_has_schedule + * @param int $a_pool_overall_limit + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_ref_id, $a_pool_id, $a_pool_has_schedule, $a_pool_overall_limit) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $this->user = $DIC->user(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilAccess = $DIC->access(); - $this->ui_factory = $DIC->ui()->factory(); - $this->ui_renderer = $DIC->ui()->renderer(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->user = $DIC->user(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilAccess = $DIC->access(); + $this->ui_factory = $DIC->ui()->factory(); + $this->ui_renderer = $DIC->ui()->renderer(); - $this->ref_id = $a_ref_id; - $this->pool_id = $a_pool_id; - $this->has_schedule = $a_pool_has_schedule; - $this->overall_limit = $a_pool_overall_limit; - $this->may_edit = $ilAccess->checkAccess('write', '', $this->ref_id); - $this->may_assign = $ilAccess->checkAccess('edit_permission', '', $this->ref_id); - - $this->advmd = ilObjBookingPool::getAdvancedMDFields($this->ref_id); - - $this->setId("bkobj"); + $this->ref_id = $a_ref_id; + $this->pool_id = $a_pool_id; + $this->has_schedule = $a_pool_has_schedule; + $this->overall_limit = $a_pool_overall_limit; + $this->may_edit = $ilAccess->checkAccess('write', '', $this->ref_id); + $this->may_assign = $ilAccess->checkAccess('edit_permission', '', $this->ref_id); + + $this->advmd = ilObjBookingPool::getAdvancedMDFields($this->ref_id); + + $this->setId("bkobj"); - parent::__construct($a_parent_obj, $a_parent_cmd); + parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setTitle($lng->txt("book_objects_list")); + $this->setTitle($lng->txt("book_objects_list")); - // $this->setLimit(9999); - - $this->addColumn($this->lng->txt("title"), "title"); - - $cols = $this->getSelectableColumns(); - foreach($this->getSelectedColumns() as $col) - { - $this->addColumn($cols[$col]["txt"], $col); - } - - if(!$this->has_schedule) - { - $this->addColumn($this->lng->txt("available")); - } + // $this->setLimit(9999); + + $this->addColumn($this->lng->txt("title"), "title"); + + $cols = $this->getSelectableColumns(); + foreach ($this->getSelectedColumns() as $col) { + $this->addColumn($cols[$col]["txt"], $col); + } + + if (!$this->has_schedule) { + $this->addColumn($this->lng->txt("available")); + } - $this->addColumn($this->lng->txt("actions")); + $this->addColumn($this->lng->txt("actions")); - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd)); - $this->setRowTemplate("tpl.booking_object_row.html", "Modules/BookingManager"); - - $this->initFilter(); - $this->getItems(); - } - - /** - * needed for advmd filter handling - * - * @return ilAdvancedMDRecordGUI - */ - protected function getAdvMDRecordGUI() - { - // #16827 - return $this->record_gui; - } - - function initFilter() - { - $lng = $this->lng; - - // title/description - $title = $this->addFilterItemByMetaType( - "title", - ilTable2GUI::FILTER_TEXT, - false, - $lng->txt("title")."/".$lng->txt("description") - ); - $this->filter["title"] = $title->getValue(); - - // #18651 - if($this->has_schedule) - { - // booking period - $period = $this->addFilterItemByMetaType( - "period", - ilTable2GUI::FILTER_DATE_RANGE, - false, - $lng->txt("book_period") - ); - $this->filter["period"] = $period->getValue(); - } - } - - /** - * Gather data and build rows - */ - function getItems() - { - $ilUser = $this->user; - - include_once 'Modules/BookingManager/classes/class.ilBookingObject.php'; - $data = ilBookingObject::getList($this->pool_id, $this->filter["title"]); - - include_once 'Modules/BookingManager/classes/class.ilBookingSchedule.php'; - include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php'; - - // check schedule availability - if($this->has_schedule) - { - $now = time(); - $limit = strtotime("+1year"); - foreach($data as $idx => $item) - { - $schedule = new ilBookingSchedule($item["schedule_id"]); - $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 && $av_from > $limit)) - { - unset($data[$idx]); - } - if($av_from > $now) - { - $data[$idx]["not_yet"] = ilDatePresentation::formatDate(new ilDate($av_from, IL_CAL_UNIX)); - } - if($av_to) - { - // #18658 - if(!ilBookingReservation::isObjectAvailableInPeriod($item["booking_object_id"], $schedule, $av_from, $av_to)) - { - $this->lng->loadLanguageModule("dateplaner"); - $data[$idx]["full_up"] = $this->lng->txt("cal_booked_out"); - } - } - } - } - - foreach($data as $item) - { - $item_id = $item["booking_object_id"]; - - // available for given period? - if(is_object($this->filter["period"]["from"]) || - is_object($this->filter["period"]["to"])) - { - $from = is_object($this->filter["period"]["from"]) - ? strtotime($this->filter["period"]["from"]->get(IL_CAL_DATE)." 00:00:00") - : null; - $to = is_object($this->filter["period"]["to"]) - ? strtotime($this->filter["period"]["to"]->get(IL_CAL_DATE)." 23:59:59") - : null; - - $bobj = new ilBookingObject($item_id); - $schedule = new ilBookingSchedule($bobj->getScheduleId()); - - if(!ilBookingReservation::isObjectAvailableInPeriod($item_id, $schedule, $from, $to)) - { - unset($data[$idx]); - continue; - } - } - - // cache reservations - $item_rsv = ilBookingReservation::getList(array($item_id), 1000, 0, array()); - $this->reservations[$item_id] = $item_rsv["data"]; - } - - if(!$this->has_schedule && - $this->overall_limit) - { - $this->current_bookings = 0; - foreach($this->reservations as $obj_rsv) - { - foreach($obj_rsv as $item) - { - if($item["status"] != ilBookingReservation::STATUS_CANCELLED) - { - if($item["user_id"] == $ilUser->getId()) - { - $this->current_bookings++; - } - } - } - } - - if($this->current_bookings >= $this->overall_limit) - { - ilUtil::sendInfo($this->lng->txt("book_overall_limit_warning")); - } - } - - if($this->advmd) - { - // advanced metadata - include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecordGUI.php'); - $this->record_gui = new ilAdvancedMDRecordGUI(ilAdvancedMDRecordGUI::MODE_FILTER, "book", $this->pool_id, "bobj"); - $this->record_gui->setTableGUI($this); - $this->record_gui->parse(); - - include_once("./Services/AdvancedMetaData/classes/class.ilAdvancedMDValues.php"); - $data = ilAdvancedMDValues::queryForRecords( - $this->ref_id, "book", "bobj", - $this->pool_id, "bobj", $data, "pool_id", "booking_object_id", $this->record_gui->getFilterElements()); - } - - $this->setMaxCount(sizeof($data)); - $this->setData($data); - } - - function numericOrdering($a_field) - { - if (substr($a_field, 0, 3) == "md_") - { - $md_id = (int) substr($a_field, 3); - if ($this->advmd[$md_id]["type"] == ilAdvancedMDFieldDefinition::TYPE_DATE) - { - return true; - } - } - return false; - } - - function getSelectableColumns() - { - $cols = array(); - - $cols["description"] = array( - "txt" => $this->lng->txt("description"), - "default" => true - ); - - foreach($this->advmd as $field) - { - $cols["advmd".$field["id"]] = array( - "txt" => $field["title"], - "default" => false - ); - } - - return $cols; - } + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd)); + $this->setRowTemplate("tpl.booking_object_row.html", "Modules/BookingManager"); + + $this->initFilter(); + $this->getItems(); + } + + /** + * needed for advmd filter handling + * + * @return ilAdvancedMDRecordGUI + */ + protected function getAdvMDRecordGUI() + { + // #16827 + return $this->record_gui; + } + + public function initFilter() + { + $lng = $this->lng; + + // title/description + $title = $this->addFilterItemByMetaType( + "title", + ilTable2GUI::FILTER_TEXT, + false, + $lng->txt("title") . "/" . $lng->txt("description") + ); + $this->filter["title"] = $title->getValue(); + + // #18651 + if ($this->has_schedule) { + // booking period + $period = $this->addFilterItemByMetaType( + "period", + ilTable2GUI::FILTER_DATE_RANGE, + false, + $lng->txt("book_period") + ); + $this->filter["period"] = $period->getValue(); + } + } + + /** + * Gather data and build rows + */ + public function getItems() + { + $ilUser = $this->user; + + include_once 'Modules/BookingManager/classes/class.ilBookingObject.php'; + $data = ilBookingObject::getList($this->pool_id, $this->filter["title"]); + + include_once 'Modules/BookingManager/classes/class.ilBookingSchedule.php'; + include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php'; + + // check schedule availability + if ($this->has_schedule) { + $now = time(); + $limit = strtotime("+1year"); + foreach ($data as $idx => $item) { + $schedule = new ilBookingSchedule($item["schedule_id"]); + $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 && $av_from > $limit)) { + unset($data[$idx]); + } + if ($av_from > $now) { + $data[$idx]["not_yet"] = ilDatePresentation::formatDate(new ilDate($av_from, IL_CAL_UNIX)); + } + if ($av_to) { + // #18658 + if (!ilBookingReservation::isObjectAvailableInPeriod($item["booking_object_id"], $schedule, $av_from, $av_to)) { + $this->lng->loadLanguageModule("dateplaner"); + $data[$idx]["full_up"] = $this->lng->txt("cal_booked_out"); + } + } + } + } + + foreach ($data as $item) { + $item_id = $item["booking_object_id"]; + + // available for given period? + if (is_object($this->filter["period"]["from"]) || + is_object($this->filter["period"]["to"])) { + $from = is_object($this->filter["period"]["from"]) + ? strtotime($this->filter["period"]["from"]->get(IL_CAL_DATE) . " 00:00:00") + : null; + $to = is_object($this->filter["period"]["to"]) + ? strtotime($this->filter["period"]["to"]->get(IL_CAL_DATE) . " 23:59:59") + : null; + + $bobj = new ilBookingObject($item_id); + $schedule = new ilBookingSchedule($bobj->getScheduleId()); + + if (!ilBookingReservation::isObjectAvailableInPeriod($item_id, $schedule, $from, $to)) { + unset($data[$idx]); + continue; + } + } + + // cache reservations + $item_rsv = ilBookingReservation::getList(array($item_id), 1000, 0, array()); + $this->reservations[$item_id] = $item_rsv["data"]; + } + + if (!$this->has_schedule && + $this->overall_limit) { + $this->current_bookings = 0; + foreach ($this->reservations as $obj_rsv) { + foreach ($obj_rsv as $item) { + if ($item["status"] != ilBookingReservation::STATUS_CANCELLED) { + if ($item["user_id"] == $ilUser->getId()) { + $this->current_bookings++; + } + } + } + } + + if ($this->current_bookings >= $this->overall_limit) { + ilUtil::sendInfo($this->lng->txt("book_overall_limit_warning")); + } + } + + if ($this->advmd) { + // advanced metadata + include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecordGUI.php'); + $this->record_gui = new ilAdvancedMDRecordGUI(ilAdvancedMDRecordGUI::MODE_FILTER, "book", $this->pool_id, "bobj"); + $this->record_gui->setTableGUI($this); + $this->record_gui->parse(); + + include_once("./Services/AdvancedMetaData/classes/class.ilAdvancedMDValues.php"); + $data = ilAdvancedMDValues::queryForRecords( + $this->ref_id, + "book", + "bobj", + $this->pool_id, + "bobj", + $data, + "pool_id", + "booking_object_id", + $this->record_gui->getFilterElements() + ); + } + + $this->setMaxCount(sizeof($data)); + $this->setData($data); + } + + public function numericOrdering($a_field) + { + if (substr($a_field, 0, 3) == "md_") { + $md_id = (int) substr($a_field, 3); + if ($this->advmd[$md_id]["type"] == ilAdvancedMDFieldDefinition::TYPE_DATE) { + return true; + } + } + return false; + } + + public function getSelectableColumns() + { + $cols = array(); + + $cols["description"] = array( + "txt" => $this->lng->txt("description"), + "default" => true + ); + + foreach ($this->advmd as $field) { + $cols["advmd" . $field["id"]] = array( + "txt" => $field["title"], + "default" => false + ); + } + + return $cols; + } - /** - * Fill table row - * @param array $a_set - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - $has_booking = false; - $booking_possible = true; - $assign_possible = true; - $has_reservations = false; - - $selected = $this->getSelectedColumns(); + /** + * Fill table row + * @param array $a_set + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + $has_booking = false; + $booking_possible = true; + $assign_possible = true; + $has_reservations = false; + + $selected = $this->getSelectedColumns(); - $this->tpl->setVariable("TXT_TITLE", $a_set["title"]); - - if(in_array("description", $selected)) - { - $this->tpl->setVariable("TXT_DESC", nl2br($a_set["description"])); - } - - if($a_set["full_up"]) - { - $this->tpl->setVariable("NOT_YET", $a_set["full_up"]); - $booking_possible = false; - $assign_possible = false; - } - else if($a_set["not_yet"]) - { - $this->tpl->setVariable("NOT_YET", $a_set["not_yet"]); - } - - if(!$this->has_schedule) - { - $cnt = 0; - foreach($this->reservations[$a_set["booking_object_id"]] as $item) - { - if($item["status"] != ilBookingReservation::STATUS_CANCELLED) - { - $cnt++; - - if($item["user_id"] == $ilUser->getId()) - { - $has_booking = true; - } - - $has_reservations = true; - } - } - - $this->tpl->setVariable("VALUE_AVAIL", $a_set["nr_items"]-$cnt); - $this->tpl->setVariable("VALUE_AVAIL_ALL", $a_set["nr_items"]); + $this->tpl->setVariable("TXT_TITLE", $a_set["title"]); + + if (in_array("description", $selected)) { + $this->tpl->setVariable("TXT_DESC", nl2br($a_set["description"])); + } + + if ($a_set["full_up"]) { + $this->tpl->setVariable("NOT_YET", $a_set["full_up"]); + $booking_possible = false; + $assign_possible = false; + } elseif ($a_set["not_yet"]) { + $this->tpl->setVariable("NOT_YET", $a_set["not_yet"]); + } + + if (!$this->has_schedule) { + $cnt = 0; + foreach ($this->reservations[$a_set["booking_object_id"]] as $item) { + if ($item["status"] != ilBookingReservation::STATUS_CANCELLED) { + $cnt++; + + if ($item["user_id"] == $ilUser->getId()) { + $has_booking = true; + } + + $has_reservations = true; + } + } + + $this->tpl->setVariable("VALUE_AVAIL", $a_set["nr_items"]-$cnt); + $this->tpl->setVariable("VALUE_AVAIL_ALL", $a_set["nr_items"]); - if($a_set["nr_items"] <= $cnt || ($this->overall_limit && $this->current_bookings && $this->current_bookings >= $this->overall_limit)) - { - $booking_possible = false; - } - if($has_booking){ - $booking_possible = false; - } - if($a_set["nr_items"] <= $cnt - || empty(ilBookingParticipant::getAssignableParticipants($a_set["booking_object_id"]))) - { - $assign_possible = false; - } + if ($a_set["nr_items"] <= $cnt || ($this->overall_limit && $this->current_bookings && $this->current_bookings >= $this->overall_limit)) { + $booking_possible = false; + } + if ($has_booking) { + $booking_possible = false; + } + if ($a_set["nr_items"] <= $cnt + || empty(ilBookingParticipant::getAssignableParticipants($a_set["booking_object_id"]))) { + $assign_possible = false; + } + } elseif (!$this->may_edit) { + foreach ($this->reservations[$a_set["booking_object_id"]] as $item) { + if ($item["status"] != ilBookingReservation::STATUS_CANCELLED && + $item["user_id"] == $ilUser->getId()) { + $has_booking = true; + } + } + } - } - else if(!$this->may_edit) - { - foreach($this->reservations[$a_set["booking_object_id"]] as $item) - { - if($item["status"] != ilBookingReservation::STATUS_CANCELLED && - $item["user_id"] == $ilUser->getId()) - { - $has_booking = true; - } - } - } + //Actions + $items = array(); + + $ilCtrl->setParameter($this->parent_obj, 'object_id', $a_set['booking_object_id']); + + if ($booking_possible) { + if (is_object($this->filter['period']['from'])) { + $ilCtrl->setParameter($this->parent_obj, 'sseed', $this->filter['period']['from']->get(IL_CAL_DATE)); + } - //Actions - $items = array(); - - $ilCtrl->setParameter($this->parent_obj, 'object_id', $a_set['booking_object_id']); - - if($booking_possible) - { - if(is_object($this->filter['period']['from'])) - { - $ilCtrl->setParameter($this->parent_obj, 'sseed', $this->filter['period']['from']->get(IL_CAL_DATE)); - } + $items[] = $this->ui_factory->button()->shy($lng->txt('book_book'), $ilCtrl->getLinkTarget($this->parent_obj, 'book')); - $items[] = $this->ui_factory->button()->shy($lng->txt('book_book'),$ilCtrl->getLinkTarget($this->parent_obj, 'book')); + $ilCtrl->setParameter($this->parent_obj, 'sseed', ''); + } + + // #16663 + if (!$this->has_schedule && $has_booking) { + if (trim($a_set['post_text']) || $a_set['post_file']) { + $items[] = $this->ui_factory->button()->shy($lng->txt('book_post_booking_information'), $ilCtrl->getLinkTarget($this->parent_obj, 'displayPostInfo')); + } + $items[] = $this->ui_factory->button()->shy($lng->txt('book_set_cancel'), $ilCtrl->getLinkTarget($this->parent_obj, 'rsvConfirmCancelUser')); + } + + if ($this->may_edit || $has_booking) { + $ilCtrl->setParameterByClass('ilObjBookingPoolGUI', 'object_id', $a_set['booking_object_id']); + $items[] = $this->ui_factory->button()->shy($lng->txt('book_log'), $ilCtrl->getLinkTargetByClass('ilObjBookingPoolGUI', 'log')); + $ilCtrl->setParameterByClass('ilObjBookingPoolGUI', 'object_id', ''); + } - $ilCtrl->setParameter($this->parent_obj, 'sseed', ''); - } - - // #16663 - if(!$this->has_schedule && $has_booking) - { - if(trim($a_set['post_text']) || $a_set['post_file']) - { - $items[] = $this->ui_factory->button()->shy($lng->txt('book_post_booking_information'), $ilCtrl->getLinkTarget($this->parent_obj, 'displayPostInfo')); - } - $items[] = $this->ui_factory->button()->shy($lng->txt('book_set_cancel'), $ilCtrl->getLinkTarget($this->parent_obj, 'rsvConfirmCancelUser')); - } - - if($this->may_edit || $has_booking) - { - $ilCtrl->setParameterByClass('ilObjBookingPoolGUI', 'object_id', $a_set['booking_object_id']); - $items[] = $this->ui_factory->button()->shy($lng->txt('book_log'), $ilCtrl->getLinkTargetByClass('ilObjBookingPoolGUI', 'log')); - $ilCtrl->setParameterByClass('ilObjBookingPoolGUI', 'object_id', ''); - } + if ($this->may_assign && $assign_possible) { + if (is_object($this->filter['period']['from'])) { + $ilCtrl->setParameter($this->parent_obj, 'sseed', $this->filter['period']['from']->get(IL_CAL_DATE)); + } - if($this->may_assign && $assign_possible) - { - if(is_object($this->filter['period']['from'])) - { - $ilCtrl->setParameter($this->parent_obj, 'sseed', $this->filter['period']['from']->get(IL_CAL_DATE)); - } + $items[] = $this->ui_factory->button()->shy($lng->txt('book_assign_participant'), $ilCtrl->getLinkTarget($this->parent_obj, 'assignParticipants')); - $items[] = $this->ui_factory->button()->shy($lng->txt('book_assign_participant'), $ilCtrl->getLinkTarget($this->parent_obj, 'assignParticipants')); + $ilCtrl->setParameter($this->parent_obj, 'sseed', ''); + } - $ilCtrl->setParameter($this->parent_obj, 'sseed', ''); - } + if ($a_set['info_file']) { + $items[] = $this->ui_factory->button()->shy($lng->txt('book_download_info'), $ilCtrl->getLinkTarget($this->parent_obj, 'deliverInfo')); + } + + if ($this->may_edit) { + $items[] = $this->ui_factory->button()->shy($lng->txt('edit'), $ilCtrl->getLinkTarget($this->parent_obj, 'edit')); - if($a_set['info_file']) - { - $items[] = $this->ui_factory->button()->shy($lng->txt('book_download_info'), $ilCtrl->getLinkTarget($this->parent_obj, 'deliverInfo')); - } - - if ($this->may_edit) - { - $items[] = $this->ui_factory->button()->shy($lng->txt('edit'), $ilCtrl->getLinkTarget($this->parent_obj, 'edit')); + // #10890 + if (!$has_reservations) { + $items[] = $this->ui_factory->button()->shy($lng->txt('delete'), $ilCtrl->getLinkTarget($this->parent_obj, 'confirmDelete')); + } + } + + if ($this->advmd) { + foreach ($this->advmd as $item) { + $advmd_id = (int) $item["id"]; + + if (!in_array("advmd" . $advmd_id, $selected)) { + continue; + } + + $val = " "; + if (isset($a_set["md_" . $advmd_id . "_presentation"])) { + $pb = $a_set["md_" . $advmd_id . "_presentation"]->getList(); + if ($pb) { + $val = $pb; + } + } + + $this->tpl->setCurrentBlock("advmd_bl"); + $this->tpl->setVariable("ADVMD_VAL", $val); + $this->tpl->parseCurrentBlock(); + } + } - // #10890 - if(!$has_reservations) - { - $items[] = $this->ui_factory->button()->shy($lng->txt('delete'), $ilCtrl->getLinkTarget($this->parent_obj, 'confirmDelete')); - } - } - - if($this->advmd) - { - foreach ($this->advmd as $item) - { - $advmd_id = (int)$item["id"]; - - if(!in_array("advmd".$advmd_id, $selected)) - { - continue; - } - - $val = " "; - if(isset($a_set["md_".$advmd_id."_presentation"])) - { - $pb = $a_set["md_".$advmd_id."_presentation"]->getList(); - if($pb) - { - $val = $pb; - } - } - - $this->tpl->setCurrentBlock("advmd_bl"); - $this->tpl->setVariable("ADVMD_VAL", $val); - $this->tpl->parseCurrentBlock(); - } - } - - if(sizeof($items)) - { - $actions_dropdown = $this->ui_factory->dropdown()->standard($items)->withLabel($this->lng->txt('actions')); - $this->tpl->setVariable("ACTION_DROPDOWN", $this->ui_renderer->render($actions_dropdown)); - } - } + if (sizeof($items)) { + $actions_dropdown = $this->ui_factory->dropdown()->standard($items)->withLabel($this->lng->txt('actions')); + $this->tpl->setVariable("ACTION_DROPDOWN", $this->ui_renderer->render($actions_dropdown)); + } + } } - -?> \ No newline at end of file diff --git a/Modules/BookingManager/classes/class.ilBookingParticipant.php b/Modules/BookingManager/classes/class.ilBookingParticipant.php index ff212f046a3fed66cfb1bb410f7527f543359526..4f3a7063202160ac0de11d88e068704957ea89ad 100644 --- a/Modules/BookingManager/classes/class.ilBookingParticipant.php +++ b/Modules/BookingManager/classes/class.ilBookingParticipant.php @@ -8,319 +8,307 @@ */ class ilBookingParticipant { - 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. - */ - 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; - } - - 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', ''); - } - else if($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
-	 */
-	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  
+ * @author Jörg Lützenkirchen 
  * @version $Id$
  *
  * @ingroup ModulesBookingManager
  */
 class ilBookingReservationsTableGUI extends ilTable2GUI
 {
-	/**
-	 * @var ilObjUser
-	 */
-	protected $user;
-
-	/**
-	 * @var ilAccessHandler
-	 */
-	protected $access;
-
-	protected $ref_id;	// int
-	protected $filter;	// array
-	protected $pool_id;	// int
-	protected $show_all; // bool
-	protected $has_schedule; // bool
-	protected $objects; // array
-	protected $group_id; // int
-	protected $advmd; // [array]
-
-	/**
-	 * @var ilTree
-	 */
-	protected $tree;
-
-	/**
-	 * Constructor
-	 * @param	object	$a_parent_obj
-	 * @param	string	$a_parent_cmd
-	 * @param	int		$a_ref_id
-	 * @param	int		$a_pool_id
-	 * @param	bool	$a_show_all
-	 * @param	bool	$a_has_schedule
-	 * @param	array	$a_filter_pre
-	 * @param	array	$a_group_id
-	 */
-	function __construct($a_parent_obj, $a_parent_cmd, $a_ref_id, $a_pool_id, $a_show_all, $a_has_schedule, array $a_filter_pre = null, $a_group_id = null)
-	{
-		global $DIC;
-
-		$this->ctrl = $DIC->ctrl();
-		$this->lng = $DIC->language();
-		$this->user = $DIC->user();
-		$this->access = $DIC->access();
-		$ilCtrl = $DIC->ctrl();
-		$lng = $DIC->language();
-		$ilUser = $DIC->user();
-		$ilAccess = $DIC->access();
-		$this->tree = $DIC->repositoryTree();
-
-		$this->pool_id = $a_pool_id;
-		$this->ref_id = $a_ref_id;
-		$this->show_all = $a_show_all;
-		$this->has_schedule = (bool)$a_has_schedule;		
-		$this->group_id = $a_group_id;
-		
-		$this->advmd = ilObjBookingPool::getAdvancedMDFields($a_ref_id);
-		
-		$this->setId("bkrsv".$a_ref_id);
-		
-		parent::__construct($a_parent_obj, $a_parent_cmd);
-
-		$this->setTitle($lng->txt("book_reservations_list"));
-
-		$this->addColumn("", "", 1);
-		$this->addColumn($this->lng->txt("title"), "title");
-		
-		$selected = $this->getSelectedColumns();
-		$cols = $this->getSelectableColumns();
-		
-		if($this->has_schedule)
-		{
-			$this->lng->loadLanguageModule("dateplaner");
-			
-			$this->addColumn($this->lng->txt("date"), "date");
-			if(in_array("week", $selected))
-			{
-				$this->addColumn($this->lng->txt("wk_short"), "week");
-				unset($cols["week"]);
-			}
-			if(in_array("weekday", $selected))
-			{
-				$this->addColumn($this->lng->txt("cal_weekday"), "weekday");
-				unset($cols["weekday"]);
-			}
-			$this->addColumn($this->lng->txt("book_schedule_slot"), "slot");			
-			$this->addColumn($this->lng->txt("book_no_of_objects"), "counter");
-			
-			$this->setDefaultOrderField("date");
-			$this->setDefaultOrderDirection("asc");
-		}
-		else
-		{						
-			$this->addColumn($this->lng->txt("status"), "status");
-			
-			$this->setDefaultOrderField("title");
-			$this->setDefaultOrderDirection("asc");
-		}
-
-		// non-user columns
-		$user_cols = $this->getSelectableUserColumns();
-		foreach($this->getSelectedColumns() as $col)
-		{
-			if(array_key_exists($col, $cols))
-			{
-				if (!isset($user_cols[$col])) {
-					$this->addColumn($cols[$col]["txt"], $col);
-				}
-			}
-		}
-								
-		$this->addColumn($this->lng->txt("user"), "user_name");
-
-		// user columns
-		foreach($this->getSelectedColumns() as $col)
-		{
-			if(array_key_exists($col, $cols))
-			{
-				if (isset($user_cols[$col])) {
-					$this->addColumn($cols[$col]["txt"], $col);
-				}
-			}
-		}
-
-		$this->addColumn($this->lng->txt("actions"));
-		
-		$this->setEnableHeader(true);
-		$this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd));
-		$this->setRowTemplate("tpl.booking_reservation_row.html", "Modules/BookingManager");
-		$this->setResetCommand("resetLogFilter");
-		$this->setFilterCommand("applyLogFilter");
-		$this->setDisableFilterHiding(true);
-				
-		$this->initFilter($a_filter_pre);				
-
-		if($this->group_id)
-		{
-			$this->setLimit(9999);
-			$this->disable("numinfo");
-			$this->filters = array();
-		}
-		else
-		{
-			$this->setExportFormats(array(self::EXPORT_CSV, self::EXPORT_EXCEL));
-		}
-		
-		if($ilUser->getId() != ANONYMOUS_USER_ID)
-		{			
-			/*
-			if($ilAccess->checkAccess('write', '', $this->ref_id))
-			{
-				$this->addMultiCommand('rsvInUse', $lng->txt('book_set_in_use'));			
-				$this->addMultiCommand('rsvNotInUse', $lng->txt('book_set_not_in_use'));							
-			}
-			*/
-			
-			$this->addMultiCommand('rsvConfirmCancel', $lng->txt('book_set_cancel'));
-			// $this->addMultiCommand('rsvUncancel', $lng->txt('book_set_not_cancel'));			
-			$this->setSelectAllCheckbox('mrsv');
-		}
-		
-		$this->getItems($this->getCurrentFilter());
-		
-		ilDatePresentation::setUseRelativeDates(false);
-	}
-	
-	function getSelectableColumns($a_only_advmd = false, $a_include_user = true)
-	{
-		$cols = array();
-		
-		if($this->has_schedule &&
-			!(bool)$a_only_advmd)
-		{		
-			$this->lng->loadLanguageModule("dateplaner");			
-			
-			$cols["week"] = array(
-				"txt" => $this->lng->txt("wk_short"),
-				"default" => true
-			);
-			
-			$cols["weekday"] = array(
-				"txt" => $this->lng->txt("cal_weekday"),
-				"default" => true
-			);			
-		}
-
-		foreach($this->advmd as $field)
-		{
-			$cols["advmd".$field["id"]] = array(
-				"txt" => $field["title"],
-				"default" => false
-			);
-		}
-
-		if ($a_include_user)
-		{
-			$cols = array_merge($cols, $this->getSelectableUserColumns());
-		}
-
-		return $cols;
-	}
-
-	/**
-	 * Get selectable user fields
-	 *
-	 * @param
-	 * @return
-	 */
-	protected function getSelectableUserColumns()
-	{
-		$cols = [];
-		// additional user fields
-		if (($parent = $this->getParentGroupCourse()) !== false)	{
-
-			if ($this->access->checkAccess("manage_members", "", $parent["ref_id"]))
-			{
-				include_once './Services/PrivacySecurity/classes/class.ilExportFieldsInfo.php';
-				$ef = ilExportFieldsInfo::_getInstanceByType($parent["type"]);
-				foreach ($ef->getSelectableFieldsInfo(ilObject::_lookupObjectId($parent["ref_id"])) as $k => $v)
-				{
-					if (!in_array($k, ["login"]))
-					{
-						$cols[$k] = $v;
-					}
-				}
-			}
-		}
-		return $cols;
-	}
-
-	/**
-	 * Get selected user colimns
-	 *
-	 * @param
-	 * @return
-	 */
-	protected function getSelectedUserColumns()
-	{
-		$user_cols = $this->getSelectableUserColumns();
-		$sel = [];
-		foreach ($this->getSelectedColumns() as $col)
-		{
-			if (isset($user_cols[$col]))
-			{
-				$sel[] = $col;
-			}
-		}
-		return $sel;
-	}
-
-
-	/**
-	 * Get parent group or course
-	 *
-	 * @param
-	 * @return
-	 */
-	protected function getParentGroupCourse()
-	{
-		$tree = $this->tree;
-		if (($par_ref_id = $tree->checkForParentType($this->ref_id, "grp")) > 0)	{
-			return [
-				"ref_id" => $par_ref_id,
-				"type" => "grp"
-			];
-		}
-		if (($par_ref_id = $tree->checkForParentType($this->ref_id, "crs")) > 0)	{
-			return [
-				"ref_id" => $par_ref_id,
-				"type" => "crs"
-			];
-		}
-		return false;
-	}
-
-
-
-	/**
-	* Init filter
-	*/
-	function initFilter(array $a_filter_pre = null)
-	{									
-		if(is_array($a_filter_pre) && 
-			isset($a_filter_pre["object"]))
-		{			
-			$_SESSION["form_".$this->getId()]["object"] = serialize($a_filter_pre["object"]);						
-		}
-		
-		$this->objects = array();
-		include_once "Modules/BookingManager/classes/class.ilBookingObject.php";
-		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();
-
-		if($this->has_schedule)
-		{
-			// default period: from:today [ to:(today + n days) ]
-			if(!$_SESSION["form_".$this->getId()]["fromto"])
-			{
-				$from = new ilDateTime(date("Y-m-d"), IL_CAL_DATE); // today
-				$to = null;
-				
-				// add period end from pool settings?
-				include_once "Modules/BookingManager/classes/class.ilObjBookingPool.php";
-				$bpool = new ilObjBookingPool($this->pool_id, false);
-				$period = $bpool->getReservationFilterPeriod();
-				if($period !== null)
-				{
-					$to = clone $from;
-					if($period)
-					{
-						$to->increment(ilDateTime::DAY, $period);
-					}
-					$to = serialize($to);
-				}
-				
-				$_SESSION["form_".$this->getId()]["fromto"] = serialize(array(
-					"from" => serialize($from),
-					"to" => $to
-				));			
-			}
-			$item = $this->addFilterItemByMetaType("fromto", ilTable2GUI::FILTER_DATE_RANGE, false, $this->lng->txt('book_fromto'));
-			$this->filter["fromto"] = $item->getDate();
-			
-			// only needed for full log
-			if($this->show_all)
-			{
-				// see ilObjBookingPoolGUI::buildDatesBySchedule()
-				$map = array_flip(array('su', 'mo', 'tu', 'we', 'th', 'fr', 'sa'));
-				
-				$options = array(""=>$this->lng->txt('book_all'));
-				
-				// schedule to slot
-				require_once "Modules/BookingManager/classes/class.ilBookingSchedule.php";
-				foreach(ilBookingSchedule::getList($this->pool_id) as $def)
-				{
-					$schedule = new ilBookingSchedule($def["booking_schedule_id"]);
-					foreach($schedule->getDefinition() as $day => $slots)
-					{
-						$day_caption = ilCalendarUtil::_numericDayToString($map[$day], false);
-					
-						foreach($slots as $slot)
-						{
-							$idx = $map[$day]."_".$slot;
-							$options[$idx] = $day_caption.", ".$slot;
-						}
-					}
-				}
-				
-				ksort($options);
-				
-				$item = $this->addFilterItemByMetaType("book_schedule_slot", ilTable2GUI::FILTER_SELECT);
-				$item->setOptions($options);
-				$this->filter["slot"] = $item->getValue();		
-			}			
-		}
-		
-		$item = new ilCheckboxInputGUI($this->lng->txt("book_filter_past_reservations"), "past");
-		$this->addFilterItem($item);
-		$item->readFromSession();
-
-		// if period starts in the past we have to include past reservations
-		// :TODO: to be discussed
-		if(is_object($this->filter["fromto"]["from"]) &&
-			$this->filter["fromto"]["from"]->get(IL_CAL_DATE) < date("Y-m-d"))
-		{
-			$item->setChecked(true);
-		}			
-
-		$this->filter["past"] = $item->getChecked();	
-		
-		// status
-		$valid_status = array(-ilBookingReservation::STATUS_CANCELLED,
-			ilBookingReservation::STATUS_CANCELLED);		
-		if(!$this->has_schedule)
-		{
-			$options = array(""=>$this->lng->txt('book_all'));
-		}
-		else
-		{
-			$options = array();
-		}
-		foreach($valid_status as $loop)
-	    {
-			if($loop > 0)
-			{
-				$options[$loop] = $this->lng->txt('book_reservation_status_'.$loop);
-			}
-			else
-			{
-				$options[$loop] = $this->lng->txt('book_not').' '.$this->lng->txt('book_reservation_status_'.-$loop);
-			}
-		}
-		$item = $this->addFilterItemByMetaType("status", ilTable2GUI::FILTER_SELECT);
-		$item->setOptions($options);
-		$this->filter["status"] = $item->getValue();		
-							
-		// only needed for full log
-		if($this->show_all)
-		{											
-			$options = array(""=>$this->lng->txt('book_all'))+
-				ilBookingReservation::getUserFilter(array_keys($this->objects));
-			$item = $this->addFilterItemByMetaType("user", ilTable2GUI::FILTER_SELECT);
-			$item->setOptions($options);
-			if(is_array($a_filter_pre) && isset($a_filter_pre["user_id"]))
-			{
-				$item->setValue($a_filter_pre["user_id"]);
-				$this->filter["user_id"] = $a_filter_pre["user_id"];
-			}
-			else
-			{
-				$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["status"])
-		{
-			$filter["status"] = $this->filter["status"];
-		}
-		if($this->filter["user_id"])
-		{
-			$filter["user_id"] = $this->filter["user_id"];
-		}
-		
-		if($this->has_schedule)
-		{
-			if(!$filter["status"])
-			{
-				// needs distinct status because of aggregation
-				$filter["status"] = -ilBookingReservation::STATUS_CANCELLED;
-			}
-			if($this->filter["slot"])
-			{
-				$filter["slot"] = $this->filter["slot"];
-			}
-			
-			if($this->filter["fromto"]["from"] || $this->filter["fromto"]["to"])
-			{
-				if($this->filter["fromto"]["from"])
-				{
-					$filter["from"] = $this->filter["fromto"]["from"]->get(IL_CAL_UNIX);
-				}
-				if($this->filter["fromto"]["to"])
-				{
-					$day_end = new ilDateTime($this->filter["fromto"]["to"]->get(IL_CAL_DATE)." 23:59:59", IL_CAL_DATETIME);
-					$filter["to"] = $day_end->get(IL_CAL_UNIX);
-				}
-			}
-			
-			$filter["past"] = (bool)$this->filter["past"];	
-		}
-		
-		return $filter;
-	}
-	
-	function numericOrdering($a_field) 
-	{					
-		return in_array($a_field, array("counter", "date", "week", "weekday"));				
-	}
-	
-	/**
-	 * Gather data and build rows
-	 * @param	array	$filter
-	 */
-	function getItems(array $filter)
-	{		
-		$ilUser = $this->user;
-		
-		if(!$filter["object"])
-		{
-			$ids = array_keys($this->objects);
-		}
-		else
-		{
-			$ids = array($filter["object"]);
-		}
-		
-		if(!$this->show_all)
-		{
-			$filter["user_id"] = $ilUser->getId();
-		}
-	
-		include_once "Modules/BookingManager/classes/class.ilBookingReservation.php";
-		$data = ilBookingReservation::getListByDate($this->has_schedule, $ids, $filter);	
-		
-		if($this->advmd)
-		{			
-			// advanced metadata
-			include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecordGUI.php');
-			$this->record_gui = new ilAdvancedMDRecordGUI(ilAdvancedMDRecordGUI::MODE_FILTER, "book", $this->pool_id, "bobj");
-			$this->record_gui->setTableGUI($this);
-			$this->record_gui->parse();
-			
-			foreach(array_keys($data) as $idx)
-			{
-				$data[$idx]["pool_id"] = $this->pool_id;
-			}
-			
-			include_once("./Services/AdvancedMetaData/classes/class.ilAdvancedMDValues.php");
-			$data = ilAdvancedMDValues::queryForRecords(
-				$this->ref_id, "book", "bobj",
-				$this->pool_id, "bobj", $data, "pool_id", "object_id", $this->record_gui->getFilterElements());
-		}
-
-		if (count($this->getSelectedUserColumns()) > 0)
-		{
-			// get additional user data
-			$user_ids = array_unique(array_map(function ($d) {
-				return $d['user_id'];
-			}, $data));
-
-			// user data fields
-			$query = new ilUserQuery();
-			$query->setLimit(9999);
-			$query->setAdditionalFields($this->getSelectedUserColumns());
-			$query->setUserFilter($user_ids);
-			$ud = $query->query();
-			$usr_data = [];
-			foreach ($ud["set"] as $v)
-			{
-				foreach ($this->getSelectedUserColumns() as $c)
-				{
-					$usr_data[$v["usr_id"]][$c] = $v[$c];
-				}
-			}
-			foreach ($data as $key => $v)
-			{
-				$data[$key] = array_merge($v, $usr_data[$v["user_id"]]);
-			}
-		}
-
-		$this->setData($data);
-	}
-	
-	public function getAdvMDRecordGUI()
-	{
-		return $this->record_gui;
-	}
-	
-	public function getOrderField()
-	{
-		$field = parent::getOrderField();
-		
-		// #16560 - this will enable matchting slot sorting to date/week
-		if(in_array($field, array("date", "week")))
-		{
-			$field = "_sortdate";
-		}
-		
-		return $field;
-	}
-
-	/**
-	 * Fill table row
-	 * @param	array	$a_set
-	 */
-	protected function fillRow($a_set)
-	{
-		$lng = $this->lng;
-		$ilAccess = $this->access;
-		$ilCtrl = $this->ctrl;
-		$ilUser = $this->user;
-		
-		$selected = $this->getSelectedColumns();
-		
-	    $this->tpl->setVariable("TXT_TITLE", $a_set["title"]);
-		
-		$can_be_cancelled = (($ilAccess->checkAccess('write', '', $this->ref_id) || 
-			$a_set['user_id'] == $ilUser->getId()) &&
-			$a_set["can_be_cancelled"]);
-
-		if($can_be_cancelled)
-		{
-			$this->tpl->setVariable("MULTI_ID", $a_set["booking_reservation_id"]);
-		}
-
-		// #11995
-		$uname = $a_set["user_name"];
-		if(!trim($uname))
-		{
-			$uname = "[".$lng->txt("user_deleted")."]";
-		}
-		else
-		{			
-			//$ilCtrl->setParameter($this->parent_obj, 'user_id', $a_set['user_id']);
-			//$this->tpl->setVariable("HREF_PROFILE", $ilCtrl->getLinkTarget($this->parent_obj, 'showprofile'));
-			//$ilCtrl->setParameter($this->parent_obj, 'user_id', '');
-			include_once("./Services/User/classes/class.ilUserUtil.php");
-			$uname = ilUserUtil::getNamePresentation($a_set['user_id'], false, true, "", true);
-		}
-		$this->tpl->setVariable("TXT_CURRENT_USER", $uname);
-
-		if($this->has_schedule)
-		{			
-			$this->tpl->setVariable("VALUE_DATE", ilDatePresentation::formatDate(new ilDate($a_set["date"], IL_CAL_DATE)));
-			if(in_array("week", $selected))
-			{
-				$this->tpl->setVariable("VALUE_WEEK", $a_set["week"]);
-			}
-			if(in_array("weekday", $selected))
-			{
-				$this->tpl->setVariable("VALUE_WEEKDAY", ilCalendarUtil::_numericDayToString($a_set["weekday"], false));
-			}
-			$this->tpl->setVariable("VALUE_SLOT", $a_set["slot"]);
-			$this->tpl->setVariable("VALUE_COUNTER", $a_set["counter"]);			
-		}
-		else
-		{			
-			if(in_array($a_set['status'], array(ilBookingReservation::STATUS_CANCELLED, ilBookingReservation::STATUS_IN_USE)))
-			{
-				$this->tpl->setVariable("TXT_STATUS", $lng->txt('book_reservation_status_'.$a_set['status']));
-			}	
-			else
-			{
-				$this->tpl->setVariable("TXT_STATUS", " ");
-			}
-		}
-		
-		if($this->advmd)
-		{
-			foreach($this->advmd as $item)
-			{
-				$advmd_id = (int)$item["id"];
-				
-				if(!in_array("advmd".$advmd_id, $selected))						
-				{
-					continue;
-				}
-								
-				$val = " ";
-				if(isset($a_set["md_".$advmd_id."_presentation"]))
-				{
-					$pb = $a_set["md_".$advmd_id."_presentation"]->getList();
-					if($pb)
-					{
-						$val = $pb;
-					}
-				}		
-				
-				$this->tpl->setCurrentBlock("advmd_bl");										
-				$this->tpl->setVariable("VALUE_ADVMD", $val);
-				$this->tpl->parseCurrentBlock();
-			}
-		}
-
-		// additional user fields
-		$user_cols = $this->getSelectableUserColumns();
-		foreach($this->getSelectedColumns() as $col)
-		{
-			if (isset($user_cols[$col])) {
-				$this->tpl->setCurrentBlock("user_col");
-				$this->tpl->setVariable("VALUE_USER_COL", $a_set[$col]." ");
-				$this->tpl->parseCurrentBlock();
-			}
-		}
-
-		if($can_be_cancelled)
-		{			 
-			$ilCtrl->setParameter($this->parent_obj, 'reservation_id', $a_set['booking_reservation_id']);
-			$this->tpl->setVariable("URL_ACTION", $ilCtrl->getLinkTarget($this->parent_obj, 'rsvConfirmCancel'));
-			$ilCtrl->setParameter($this->parent_obj, 'reservation_id', "");
-			$this->tpl->setVariable("TXT_ACTION", $lng->txt('book_set_cancel'));
-		}	
-		
-		/* advsellist version
-		if (!$this->has_schedule || $date_to->get(IL_CAL_UNIX) > time())
-		{
-			include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php");
-			$alist = new ilAdvancedSelectionListGUI();
-			$alist->setId($a_set['booking_reservation_id']);
-			$alist->setListTitle($lng->txt("actions"));
-
-			$ilCtrl->setParameter($this->parent_obj, 'reservation_id', $a_set['booking_reservation_id']);
-
-			if(!$a_set['group_id'])
-			{
-				if($ilAccess->checkAccess('write', '', $this->ref_id))
-				{
-					if($a_set['status'] == ilBookingReservation::STATUS_CANCELLED)
-					{					
-						// can be uncancelled?
-						// if(ilBookingReservation::getAvailableObject(array($a_set['object_id']), $date_from->get(IL_CAL_UNIX), $date_to->get(IL_CAL_UNIX)))
-						// {
-						//	  $alist->addItem($lng->txt('book_set_not_cancel'), 'not_cancel', $ilCtrl->getLinkTarget($this->parent_obj, 'rsvUncancel'));
-						// }						
-					}
-					else if($a_set['status'] != ilBookingReservation::STATUS_IN_USE)
-					{
-						if($this->has_schedule)
-						{
-							$alist->addItem($lng->txt('book_set_in_use'), 'in_use', $ilCtrl->getLinkTarget($this->parent_obj, 'rsvInUse'));
-						}
-						$alist->addItem($lng->txt('book_set_cancel'), 'cancel', $ilCtrl->getLinkTarget($this->parent_obj, 'rsvConfirmCancel'));
-					}
-					else if($this->has_schedule)
-					{
-						$alist->addItem($lng->txt('book_set_not_in_use'), 'not_in_use', $ilCtrl->getLinkTarget($this->parent_obj, 'rsvNotInUse'));
-					}
-				}
-				else if($a_set['user_id'] == $ilUser->getId() && $a_set['status'] != ilBookingReservation::STATUS_CANCELLED)
-				{
-					$alist->addItem($lng->txt('book_set_cancel'), 'cancel', $ilCtrl->getLinkTarget($this->parent_obj, 'rsvConfirmCancel'));
-				}
-			}
-			else if($ilAccess->checkAccess('write', '', $this->ref_id) || $a_set['user_id'] == $ilUser->getId())
-			{				
-				$alist->addItem($lng->txt('details'), 'details', $ilCtrl->getLinkTarget($this->parent_obj, 'logDetails'));
-			}
-			
-			if(sizeof($alist->getItems()))
-			{
-				if(!$a_set['group_id'])
-				{
-					$this->tpl->setVariable('MULTI_ID', $a_set['booking_reservation_id']);
-				}
-				$this->tpl->setVariable('LAYER', $alist->getHTML());
-			}
-		}		
-		*/
-	}
-	
-	protected function fillHeaderExcel(ilExcel $a_excel, &$a_row)
-	{		
-		$a_excel->setCell($a_row, 0, $this->lng->txt("title"));					
-		$col = 0;
-		if($this->has_schedule)
-		{
-			$a_excel->setCell($a_row, ++$col, $this->lng->txt("date"));
-			$a_excel->setCell($a_row, ++$col, $this->lng->txt("wk_short"));
-			$a_excel->setCell($a_row, ++$col, $this->lng->txt("cal_weekday"));
-			$a_excel->setCell($a_row, ++$col, $this->lng->txt("book_schedule_slot"));
-			$a_excel->setCell($a_row, ++$col, $this->lng->txt("book_no_of_objects"));
-		}
-		else 
-		{
-			$a_excel->setCell($a_row, ++$col, $this->lng->txt("status"));		
-		}		
-		
-		foreach($this->getSelectableColumns(true) as $advmd_col)
-		{
-			$a_excel->setCell($a_row, ++$col, $advmd_col["txt"]);
-		}
-		
-		$a_excel->setCell($a_row, ++$col, $this->lng->txt("user"));			
-		
-		$a_excel->setBold("A".$a_row.":".$a_excel->getColumnCoord($col-1).$a_row);
-	}
-
-	protected function fillRowExcel(ilExcel $a_excel, &$a_row, $a_set)
-	{
-		$a_excel->setCell($a_row, 0, $a_set["title"]);
-		$col = 0;
-		if($this->has_schedule)
-		{			
-			$a_excel->setCell($a_row, ++$col, new ilDate($a_set["date"], IL_CAL_DATE));
-			$a_excel->setCell($a_row, ++$col, $a_set["week"]);
-			$a_excel->setCell($a_row, ++$col, ilCalendarUtil::_numericDayToString($a_set["weekday"], false));
-			$a_excel->setCell($a_row, ++$col, $a_set["slot"]);
-			$a_excel->setCell($a_row, ++$col, $a_set["counter"]);
-		}						
-		else
-		{		
-			$status = "";
-			if(in_array($a_set['status'], array(ilBookingReservation::STATUS_CANCELLED, ilBookingReservation::STATUS_IN_USE)))
-			{
-				$status = $this->lng->txt('book_reservation_status_'.$a_set['status']);			
-			}
-			$a_excel->setCell($a_row, ++$col, $status);
-		}
-		$a_excel->setCell($a_row, ++$col, $a_set['user_name']);		
-		
-		if($this->advmd)
-		{
-			foreach($this->advmd as $item)
-			{
-				$advmd_id = (int)$item["id"];						
-				$val = " ";
-				if(isset($a_set["md_".$advmd_id."_presentation"]))
-				{
-					$pb = $a_set["md_".$advmd_id."_presentation"]->getList();
-					if($pb)
-					{
-						$val = $pb;
-					}
-				}
-				$a_excel->setCell($a_row, ++$col, $val);
-			}
-		}
-	}
-
-	protected function fillHeaderCSV($a_csv)
-	{		
-		$a_csv->addColumn($this->lng->txt("title"));					
-		if($this->has_schedule)
-		{
-			$a_csv->addColumn($this->lng->txt("date"));
-			$a_csv->addColumn($this->lng->txt("wk_short"));
-			$a_csv->addColumn($this->lng->txt("cal_weekday"));
-			$a_csv->addColumn($this->lng->txt("book_schedule_slot"));
-			$a_csv->addColumn($this->lng->txt("book_no_of_objects"));			
-		}				
-		else
-		{
-			$a_csv->addColumn($this->lng->txt("status"));			
-		}
-				
-		foreach($this->getSelectableColumns(true) as $advmd_col)
-		{
-			$a_csv->addColumn($advmd_col["txt"]);
-		}
-		
-		$a_csv->addColumn($this->lng->txt("user"));				
-		$a_csv->addRow();		
-	}
-
-	protected function fillRowCSV($a_csv, $a_set)
-	{		
-		$a_csv->addColumn($a_set["title"]);		
-		if($this->has_schedule)
-		{
-			$a_csv->addColumn(ilDatePresentation::formatDate(new ilDate($a_set["date"], IL_CAL_DATE)));
-			$a_csv->addColumn($a_set["week"]);
-			$a_csv->addColumn(ilCalendarUtil::_numericDayToString($a_set["weekday"], false));
-			$a_csv->addColumn($a_set["slot"]);
-			$a_csv->addColumn($a_set["counter"]);			
-		}						
-		else
-		{
-			$status = "";
-			if(in_array($a_set['status'], array(ilBookingReservation::STATUS_CANCELLED, ilBookingReservation::STATUS_IN_USE)))
-			{
-				$status = $this->lng->txt('book_reservation_status_'.$a_set['status']);			
-			}
-			$a_csv->addColumn($status);
-		}
-		
-		if($this->advmd)
-		{
-			foreach($this->advmd as $item)
-			{
-				$advmd_id = (int)$item["id"];						
-				$val = " ";
-				if(isset($a_set["md_".$advmd_id."_presentation"]))
-				{
-					$pb = $a_set["md_".$advmd_id."_presentation"]->getList();
-					if($pb)
-					{
-						$val = $pb;
-					}
-				}
-				$a_csv->addColumn($val);
-			}
-		}
-		
-		$a_csv->addColumn($a_set['user_name']);		
-		$a_csv->addRow();
-	}
+    /**
+     * @var ilObjUser
+     */
+    protected $user;
+
+    /**
+     * @var ilAccessHandler
+     */
+    protected $access;
+
+    protected $ref_id;	// int
+    protected $filter;	// array
+    protected $pool_id;	// int
+    protected $show_all; // bool
+    protected $has_schedule; // bool
+    protected $objects; // array
+    protected $group_id; // int
+    protected $advmd; // [array]
+
+    /**
+     * @var ilTree
+     */
+    protected $tree;
+
+    /**
+     * Constructor
+     * @param	object	$a_parent_obj
+     * @param	string	$a_parent_cmd
+     * @param	int		$a_ref_id
+     * @param	int		$a_pool_id
+     * @param	bool	$a_show_all
+     * @param	bool	$a_has_schedule
+     * @param	array	$a_filter_pre
+     * @param	array	$a_group_id
+     */
+    public function __construct($a_parent_obj, $a_parent_cmd, $a_ref_id, $a_pool_id, $a_show_all, $a_has_schedule, array $a_filter_pre = null, $a_group_id = null)
+    {
+        global $DIC;
+
+        $this->ctrl = $DIC->ctrl();
+        $this->lng = $DIC->language();
+        $this->user = $DIC->user();
+        $this->access = $DIC->access();
+        $ilCtrl = $DIC->ctrl();
+        $lng = $DIC->language();
+        $ilUser = $DIC->user();
+        $ilAccess = $DIC->access();
+        $this->tree = $DIC->repositoryTree();
+
+        $this->pool_id = $a_pool_id;
+        $this->ref_id = $a_ref_id;
+        $this->show_all = $a_show_all;
+        $this->has_schedule = (bool) $a_has_schedule;
+        $this->group_id = $a_group_id;
+        
+        $this->advmd = ilObjBookingPool::getAdvancedMDFields($a_ref_id);
+        
+        $this->setId("bkrsv" . $a_ref_id);
+        
+        parent::__construct($a_parent_obj, $a_parent_cmd);
+
+        $this->setTitle($lng->txt("book_reservations_list"));
+
+        $this->addColumn("", "", 1);
+        $this->addColumn($this->lng->txt("title"), "title");
+        
+        $selected = $this->getSelectedColumns();
+        $cols = $this->getSelectableColumns();
+        
+        if ($this->has_schedule) {
+            $this->lng->loadLanguageModule("dateplaner");
+            
+            $this->addColumn($this->lng->txt("date"), "date");
+            if (in_array("week", $selected)) {
+                $this->addColumn($this->lng->txt("wk_short"), "week");
+                unset($cols["week"]);
+            }
+            if (in_array("weekday", $selected)) {
+                $this->addColumn($this->lng->txt("cal_weekday"), "weekday");
+                unset($cols["weekday"]);
+            }
+            $this->addColumn($this->lng->txt("book_schedule_slot"), "slot");
+            $this->addColumn($this->lng->txt("book_no_of_objects"), "counter");
+            
+            $this->setDefaultOrderField("date");
+            $this->setDefaultOrderDirection("asc");
+        } else {
+            $this->addColumn($this->lng->txt("status"), "status");
+            
+            $this->setDefaultOrderField("title");
+            $this->setDefaultOrderDirection("asc");
+        }
+
+        // non-user columns
+        $user_cols = $this->getSelectableUserColumns();
+        foreach ($this->getSelectedColumns() as $col) {
+            if (array_key_exists($col, $cols)) {
+                if (!isset($user_cols[$col])) {
+                    $this->addColumn($cols[$col]["txt"], $col);
+                }
+            }
+        }
+                                
+        $this->addColumn($this->lng->txt("user"), "user_name");
+
+        // user columns
+        foreach ($this->getSelectedColumns() as $col) {
+            if (array_key_exists($col, $cols)) {
+                if (isset($user_cols[$col])) {
+                    $this->addColumn($cols[$col]["txt"], $col);
+                }
+            }
+        }
+
+        $this->addColumn($this->lng->txt("actions"));
+        
+        $this->setEnableHeader(true);
+        $this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd));
+        $this->setRowTemplate("tpl.booking_reservation_row.html", "Modules/BookingManager");
+        $this->setResetCommand("resetLogFilter");
+        $this->setFilterCommand("applyLogFilter");
+        $this->setDisableFilterHiding(true);
+                
+        $this->initFilter($a_filter_pre);
+
+        if ($this->group_id) {
+            $this->setLimit(9999);
+            $this->disable("numinfo");
+            $this->filters = array();
+        } else {
+            $this->setExportFormats(array(self::EXPORT_CSV, self::EXPORT_EXCEL));
+        }
+        
+        if ($ilUser->getId() != ANONYMOUS_USER_ID) {
+            /*
+            if($ilAccess->checkAccess('write', '', $this->ref_id))
+            {
+                $this->addMultiCommand('rsvInUse', $lng->txt('book_set_in_use'));
+                $this->addMultiCommand('rsvNotInUse', $lng->txt('book_set_not_in_use'));
+            }
+            */
+            
+            $this->addMultiCommand('rsvConfirmCancel', $lng->txt('book_set_cancel'));
+            // $this->addMultiCommand('rsvUncancel', $lng->txt('book_set_not_cancel'));
+            $this->setSelectAllCheckbox('mrsv');
+        }
+        
+        $this->getItems($this->getCurrentFilter());
+        
+        ilDatePresentation::setUseRelativeDates(false);
+    }
+    
+    public function getSelectableColumns($a_only_advmd = false, $a_include_user = true)
+    {
+        $cols = array();
+        
+        if ($this->has_schedule &&
+            !(bool) $a_only_advmd) {
+            $this->lng->loadLanguageModule("dateplaner");
+            
+            $cols["week"] = array(
+                "txt" => $this->lng->txt("wk_short"),
+                "default" => true
+            );
+            
+            $cols["weekday"] = array(
+                "txt" => $this->lng->txt("cal_weekday"),
+                "default" => true
+            );
+        }
+
+        foreach ($this->advmd as $field) {
+            $cols["advmd" . $field["id"]] = array(
+                "txt" => $field["title"],
+                "default" => false
+            );
+        }
+
+        if ($a_include_user) {
+            $cols = array_merge($cols, $this->getSelectableUserColumns());
+        }
+
+        return $cols;
+    }
+
+    /**
+     * Get selectable user fields
+     *
+     * @param
+     * @return
+     */
+    protected function getSelectableUserColumns()
+    {
+        $cols = [];
+        // additional user fields
+        if (($parent = $this->getParentGroupCourse()) !== false) {
+            if ($this->access->checkAccess("manage_members", "", $parent["ref_id"])) {
+                include_once './Services/PrivacySecurity/classes/class.ilExportFieldsInfo.php';
+                $ef = ilExportFieldsInfo::_getInstanceByType($parent["type"]);
+                foreach ($ef->getSelectableFieldsInfo(ilObject::_lookupObjectId($parent["ref_id"])) as $k => $v) {
+                    if (!in_array($k, ["login"])) {
+                        $cols[$k] = $v;
+                    }
+                }
+            }
+        }
+        return $cols;
+    }
+
+    /**
+     * Get selected user colimns
+     *
+     * @param
+     * @return
+     */
+    protected function getSelectedUserColumns()
+    {
+        $user_cols = $this->getSelectableUserColumns();
+        $sel = [];
+        foreach ($this->getSelectedColumns() as $col) {
+            if (isset($user_cols[$col])) {
+                $sel[] = $col;
+            }
+        }
+        return $sel;
+    }
+
+
+    /**
+     * Get parent group or course
+     *
+     * @param
+     * @return
+     */
+    protected function getParentGroupCourse()
+    {
+        $tree = $this->tree;
+        if (($par_ref_id = $tree->checkForParentType($this->ref_id, "grp")) > 0) {
+            return [
+                "ref_id" => $par_ref_id,
+                "type" => "grp"
+            ];
+        }
+        if (($par_ref_id = $tree->checkForParentType($this->ref_id, "crs")) > 0) {
+            return [
+                "ref_id" => $par_ref_id,
+                "type" => "crs"
+            ];
+        }
+        return false;
+    }
+
+
+
+    /**
+    * Init filter
+    */
+    public function initFilter(array $a_filter_pre = null)
+    {
+        if (is_array($a_filter_pre) &&
+            isset($a_filter_pre["object"])) {
+            $_SESSION["form_" . $this->getId()]["object"] = serialize($a_filter_pre["object"]);
+        }
+        
+        $this->objects = array();
+        include_once "Modules/BookingManager/classes/class.ilBookingObject.php";
+        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();
+
+        if ($this->has_schedule) {
+            // default period: from:today [ to:(today + n days) ]
+            if (!$_SESSION["form_" . $this->getId()]["fromto"]) {
+                $from = new ilDateTime(date("Y-m-d"), IL_CAL_DATE); // today
+                $to = null;
+                
+                // add period end from pool settings?
+                include_once "Modules/BookingManager/classes/class.ilObjBookingPool.php";
+                $bpool = new ilObjBookingPool($this->pool_id, false);
+                $period = $bpool->getReservationFilterPeriod();
+                if ($period !== null) {
+                    $to = clone $from;
+                    if ($period) {
+                        $to->increment(ilDateTime::DAY, $period);
+                    }
+                    $to = serialize($to);
+                }
+                
+                $_SESSION["form_" . $this->getId()]["fromto"] = serialize(array(
+                    "from" => serialize($from),
+                    "to" => $to
+                ));
+            }
+            $item = $this->addFilterItemByMetaType("fromto", ilTable2GUI::FILTER_DATE_RANGE, false, $this->lng->txt('book_fromto'));
+            $this->filter["fromto"] = $item->getDate();
+            
+            // only needed for full log
+            if ($this->show_all) {
+                // see ilObjBookingPoolGUI::buildDatesBySchedule()
+                $map = array_flip(array('su', 'mo', 'tu', 'we', 'th', 'fr', 'sa'));
+                
+                $options = array(""=>$this->lng->txt('book_all'));
+                
+                // schedule to slot
+                require_once "Modules/BookingManager/classes/class.ilBookingSchedule.php";
+                foreach (ilBookingSchedule::getList($this->pool_id) as $def) {
+                    $schedule = new ilBookingSchedule($def["booking_schedule_id"]);
+                    foreach ($schedule->getDefinition() as $day => $slots) {
+                        $day_caption = ilCalendarUtil::_numericDayToString($map[$day], false);
+                    
+                        foreach ($slots as $slot) {
+                            $idx = $map[$day] . "_" . $slot;
+                            $options[$idx] = $day_caption . ", " . $slot;
+                        }
+                    }
+                }
+                
+                ksort($options);
+                
+                $item = $this->addFilterItemByMetaType("book_schedule_slot", ilTable2GUI::FILTER_SELECT);
+                $item->setOptions($options);
+                $this->filter["slot"] = $item->getValue();
+            }
+        }
+        
+        $item = new ilCheckboxInputGUI($this->lng->txt("book_filter_past_reservations"), "past");
+        $this->addFilterItem($item);
+        $item->readFromSession();
+
+        // if period starts in the past we have to include past reservations
+        // :TODO: to be discussed
+        if (is_object($this->filter["fromto"]["from"]) &&
+            $this->filter["fromto"]["from"]->get(IL_CAL_DATE) < date("Y-m-d")) {
+            $item->setChecked(true);
+        }
+
+        $this->filter["past"] = $item->getChecked();
+        
+        // status
+        $valid_status = array(-ilBookingReservation::STATUS_CANCELLED,
+            ilBookingReservation::STATUS_CANCELLED);
+        if (!$this->has_schedule) {
+            $options = array(""=>$this->lng->txt('book_all'));
+        } else {
+            $options = array();
+        }
+        foreach ($valid_status as $loop) {
+            if ($loop > 0) {
+                $options[$loop] = $this->lng->txt('book_reservation_status_' . $loop);
+            } else {
+                $options[$loop] = $this->lng->txt('book_not') . ' ' . $this->lng->txt('book_reservation_status_' . -$loop);
+            }
+        }
+        $item = $this->addFilterItemByMetaType("status", ilTable2GUI::FILTER_SELECT);
+        $item->setOptions($options);
+        $this->filter["status"] = $item->getValue();
+                            
+        // only needed for full log
+        if ($this->show_all) {
+            $options = array(""=>$this->lng->txt('book_all'))+
+                ilBookingReservation::getUserFilter(array_keys($this->objects));
+            $item = $this->addFilterItemByMetaType("user", ilTable2GUI::FILTER_SELECT);
+            $item->setOptions($options);
+            if (is_array($a_filter_pre) && isset($a_filter_pre["user_id"])) {
+                $item->setValue($a_filter_pre["user_id"]);
+                $this->filter["user_id"] = $a_filter_pre["user_id"];
+            } else {
+                $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["status"]) {
+            $filter["status"] = $this->filter["status"];
+        }
+        if ($this->filter["user_id"]) {
+            $filter["user_id"] = $this->filter["user_id"];
+        }
+        
+        if ($this->has_schedule) {
+            if (!$filter["status"]) {
+                // needs distinct status because of aggregation
+                $filter["status"] = -ilBookingReservation::STATUS_CANCELLED;
+            }
+            if ($this->filter["slot"]) {
+                $filter["slot"] = $this->filter["slot"];
+            }
+            
+            if ($this->filter["fromto"]["from"] || $this->filter["fromto"]["to"]) {
+                if ($this->filter["fromto"]["from"]) {
+                    $filter["from"] = $this->filter["fromto"]["from"]->get(IL_CAL_UNIX);
+                }
+                if ($this->filter["fromto"]["to"]) {
+                    $day_end = new ilDateTime($this->filter["fromto"]["to"]->get(IL_CAL_DATE) . " 23:59:59", IL_CAL_DATETIME);
+                    $filter["to"] = $day_end->get(IL_CAL_UNIX);
+                }
+            }
+            
+            $filter["past"] = (bool) $this->filter["past"];
+        }
+        
+        return $filter;
+    }
+    
+    public function numericOrdering($a_field)
+    {
+        return in_array($a_field, array("counter", "date", "week", "weekday"));
+    }
+    
+    /**
+     * Gather data and build rows
+     * @param	array	$filter
+     */
+    public function getItems(array $filter)
+    {
+        $ilUser = $this->user;
+        
+        if (!$filter["object"]) {
+            $ids = array_keys($this->objects);
+        } else {
+            $ids = array($filter["object"]);
+        }
+        
+        if (!$this->show_all) {
+            $filter["user_id"] = $ilUser->getId();
+        }
+    
+        include_once "Modules/BookingManager/classes/class.ilBookingReservation.php";
+        $data = ilBookingReservation::getListByDate($this->has_schedule, $ids, $filter);
+        
+        if ($this->advmd) {
+            // advanced metadata
+            include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecordGUI.php');
+            $this->record_gui = new ilAdvancedMDRecordGUI(ilAdvancedMDRecordGUI::MODE_FILTER, "book", $this->pool_id, "bobj");
+            $this->record_gui->setTableGUI($this);
+            $this->record_gui->parse();
+            
+            foreach (array_keys($data) as $idx) {
+                $data[$idx]["pool_id"] = $this->pool_id;
+            }
+            
+            include_once("./Services/AdvancedMetaData/classes/class.ilAdvancedMDValues.php");
+            $data = ilAdvancedMDValues::queryForRecords(
+                $this->ref_id,
+                "book",
+                "bobj",
+                $this->pool_id,
+                "bobj",
+                $data,
+                "pool_id",
+                "object_id",
+                $this->record_gui->getFilterElements()
+            );
+        }
+
+        if (count($this->getSelectedUserColumns()) > 0) {
+            // get additional user data
+            $user_ids = array_unique(array_map(function ($d) {
+                return $d['user_id'];
+            }, $data));
+
+            // user data fields
+            $query = new ilUserQuery();
+            $query->setLimit(9999);
+            $query->setAdditionalFields($this->getSelectedUserColumns());
+            $query->setUserFilter($user_ids);
+            $ud = $query->query();
+            $usr_data = [];
+            foreach ($ud["set"] as $v) {
+                foreach ($this->getSelectedUserColumns() as $c) {
+                    $usr_data[$v["usr_id"]][$c] = $v[$c];
+                }
+            }
+            foreach ($data as $key => $v) {
+                $data[$key] = array_merge($v, $usr_data[$v["user_id"]]);
+            }
+        }
+
+        $this->setData($data);
+    }
+    
+    public function getAdvMDRecordGUI()
+    {
+        return $this->record_gui;
+    }
+    
+    public function getOrderField()
+    {
+        $field = parent::getOrderField();
+        
+        // #16560 - this will enable matchting slot sorting to date/week
+        if (in_array($field, array("date", "week"))) {
+            $field = "_sortdate";
+        }
+        
+        return $field;
+    }
+
+    /**
+     * Fill table row
+     * @param	array	$a_set
+     */
+    protected function fillRow($a_set)
+    {
+        $lng = $this->lng;
+        $ilAccess = $this->access;
+        $ilCtrl = $this->ctrl;
+        $ilUser = $this->user;
+        
+        $selected = $this->getSelectedColumns();
+        
+        $this->tpl->setVariable("TXT_TITLE", $a_set["title"]);
+        
+        $can_be_cancelled = (($ilAccess->checkAccess('write', '', $this->ref_id) ||
+            $a_set['user_id'] == $ilUser->getId()) &&
+            $a_set["can_be_cancelled"]);
+
+        if ($can_be_cancelled) {
+            $this->tpl->setVariable("MULTI_ID", $a_set["booking_reservation_id"]);
+        }
+
+        // #11995
+        $uname = $a_set["user_name"];
+        if (!trim($uname)) {
+            $uname = "[" . $lng->txt("user_deleted") . "]";
+        } else {
+            //$ilCtrl->setParameter($this->parent_obj, 'user_id', $a_set['user_id']);
+            //$this->tpl->setVariable("HREF_PROFILE", $ilCtrl->getLinkTarget($this->parent_obj, 'showprofile'));
+            //$ilCtrl->setParameter($this->parent_obj, 'user_id', '');
+            include_once("./Services/User/classes/class.ilUserUtil.php");
+            $uname = ilUserUtil::getNamePresentation($a_set['user_id'], false, true, "", true);
+        }
+        $this->tpl->setVariable("TXT_CURRENT_USER", $uname);
+
+        if ($this->has_schedule) {
+            $this->tpl->setVariable("VALUE_DATE", ilDatePresentation::formatDate(new ilDate($a_set["date"], IL_CAL_DATE)));
+            if (in_array("week", $selected)) {
+                $this->tpl->setVariable("VALUE_WEEK", $a_set["week"]);
+            }
+            if (in_array("weekday", $selected)) {
+                $this->tpl->setVariable("VALUE_WEEKDAY", ilCalendarUtil::_numericDayToString($a_set["weekday"], false));
+            }
+            $this->tpl->setVariable("VALUE_SLOT", $a_set["slot"]);
+            $this->tpl->setVariable("VALUE_COUNTER", $a_set["counter"]);
+        } else {
+            if (in_array($a_set['status'], array(ilBookingReservation::STATUS_CANCELLED, ilBookingReservation::STATUS_IN_USE))) {
+                $this->tpl->setVariable("TXT_STATUS", $lng->txt('book_reservation_status_' . $a_set['status']));
+            } else {
+                $this->tpl->setVariable("TXT_STATUS", " ");
+            }
+        }
+        
+        if ($this->advmd) {
+            foreach ($this->advmd as $item) {
+                $advmd_id = (int) $item["id"];
+                
+                if (!in_array("advmd" . $advmd_id, $selected)) {
+                    continue;
+                }
+                                
+                $val = " ";
+                if (isset($a_set["md_" . $advmd_id . "_presentation"])) {
+                    $pb = $a_set["md_" . $advmd_id . "_presentation"]->getList();
+                    if ($pb) {
+                        $val = $pb;
+                    }
+                }
+                
+                $this->tpl->setCurrentBlock("advmd_bl");
+                $this->tpl->setVariable("VALUE_ADVMD", $val);
+                $this->tpl->parseCurrentBlock();
+            }
+        }
+
+        // additional user fields
+        $user_cols = $this->getSelectableUserColumns();
+        foreach ($this->getSelectedColumns() as $col) {
+            if (isset($user_cols[$col])) {
+                $this->tpl->setCurrentBlock("user_col");
+                $this->tpl->setVariable("VALUE_USER_COL", $a_set[$col] . " ");
+                $this->tpl->parseCurrentBlock();
+            }
+        }
+
+        if ($can_be_cancelled) {
+            $ilCtrl->setParameter($this->parent_obj, 'reservation_id', $a_set['booking_reservation_id']);
+            $this->tpl->setVariable("URL_ACTION", $ilCtrl->getLinkTarget($this->parent_obj, 'rsvConfirmCancel'));
+            $ilCtrl->setParameter($this->parent_obj, 'reservation_id', "");
+            $this->tpl->setVariable("TXT_ACTION", $lng->txt('book_set_cancel'));
+        }
+        
+        /* advsellist version
+        if (!$this->has_schedule || $date_to->get(IL_CAL_UNIX) > time())
+        {
+            include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php");
+            $alist = new ilAdvancedSelectionListGUI();
+            $alist->setId($a_set['booking_reservation_id']);
+            $alist->setListTitle($lng->txt("actions"));
+
+            $ilCtrl->setParameter($this->parent_obj, 'reservation_id', $a_set['booking_reservation_id']);
+
+            if(!$a_set['group_id'])
+            {
+                if($ilAccess->checkAccess('write', '', $this->ref_id))
+                {
+                    if($a_set['status'] == ilBookingReservation::STATUS_CANCELLED)
+                    {
+                        // can be uncancelled?
+                        // if(ilBookingReservation::getAvailableObject(array($a_set['object_id']), $date_from->get(IL_CAL_UNIX), $date_to->get(IL_CAL_UNIX)))
+                        // {
+                        //	  $alist->addItem($lng->txt('book_set_not_cancel'), 'not_cancel', $ilCtrl->getLinkTarget($this->parent_obj, 'rsvUncancel'));
+                        // }
+                    }
+                    else if($a_set['status'] != ilBookingReservation::STATUS_IN_USE)
+                    {
+                        if($this->has_schedule)
+                        {
+                            $alist->addItem($lng->txt('book_set_in_use'), 'in_use', $ilCtrl->getLinkTarget($this->parent_obj, 'rsvInUse'));
+                        }
+                        $alist->addItem($lng->txt('book_set_cancel'), 'cancel', $ilCtrl->getLinkTarget($this->parent_obj, 'rsvConfirmCancel'));
+                    }
+                    else if($this->has_schedule)
+                    {
+                        $alist->addItem($lng->txt('book_set_not_in_use'), 'not_in_use', $ilCtrl->getLinkTarget($this->parent_obj, 'rsvNotInUse'));
+                    }
+                }
+                else if($a_set['user_id'] == $ilUser->getId() && $a_set['status'] != ilBookingReservation::STATUS_CANCELLED)
+                {
+                    $alist->addItem($lng->txt('book_set_cancel'), 'cancel', $ilCtrl->getLinkTarget($this->parent_obj, 'rsvConfirmCancel'));
+                }
+            }
+            else if($ilAccess->checkAccess('write', '', $this->ref_id) || $a_set['user_id'] == $ilUser->getId())
+            {
+                $alist->addItem($lng->txt('details'), 'details', $ilCtrl->getLinkTarget($this->parent_obj, 'logDetails'));
+            }
+
+            if(sizeof($alist->getItems()))
+            {
+                if(!$a_set['group_id'])
+                {
+                    $this->tpl->setVariable('MULTI_ID', $a_set['booking_reservation_id']);
+                }
+                $this->tpl->setVariable('LAYER', $alist->getHTML());
+            }
+        }
+        */
+    }
+    
+    protected function fillHeaderExcel(ilExcel $a_excel, &$a_row)
+    {
+        $a_excel->setCell($a_row, 0, $this->lng->txt("title"));
+        $col = 0;
+        if ($this->has_schedule) {
+            $a_excel->setCell($a_row, ++$col, $this->lng->txt("date"));
+            $a_excel->setCell($a_row, ++$col, $this->lng->txt("wk_short"));
+            $a_excel->setCell($a_row, ++$col, $this->lng->txt("cal_weekday"));
+            $a_excel->setCell($a_row, ++$col, $this->lng->txt("book_schedule_slot"));
+            $a_excel->setCell($a_row, ++$col, $this->lng->txt("book_no_of_objects"));
+        } else {
+            $a_excel->setCell($a_row, ++$col, $this->lng->txt("status"));
+        }
+        
+        foreach ($this->getSelectableColumns(true) as $advmd_col) {
+            $a_excel->setCell($a_row, ++$col, $advmd_col["txt"]);
+        }
+        
+        $a_excel->setCell($a_row, ++$col, $this->lng->txt("user"));
+        
+        $a_excel->setBold("A" . $a_row . ":" . $a_excel->getColumnCoord($col-1) . $a_row);
+    }
+
+    protected function fillRowExcel(ilExcel $a_excel, &$a_row, $a_set)
+    {
+        $a_excel->setCell($a_row, 0, $a_set["title"]);
+        $col = 0;
+        if ($this->has_schedule) {
+            $a_excel->setCell($a_row, ++$col, new ilDate($a_set["date"], IL_CAL_DATE));
+            $a_excel->setCell($a_row, ++$col, $a_set["week"]);
+            $a_excel->setCell($a_row, ++$col, ilCalendarUtil::_numericDayToString($a_set["weekday"], false));
+            $a_excel->setCell($a_row, ++$col, $a_set["slot"]);
+            $a_excel->setCell($a_row, ++$col, $a_set["counter"]);
+        } else {
+            $status = "";
+            if (in_array($a_set['status'], array(ilBookingReservation::STATUS_CANCELLED, ilBookingReservation::STATUS_IN_USE))) {
+                $status = $this->lng->txt('book_reservation_status_' . $a_set['status']);
+            }
+            $a_excel->setCell($a_row, ++$col, $status);
+        }
+        $a_excel->setCell($a_row, ++$col, $a_set['user_name']);
+        
+        if ($this->advmd) {
+            foreach ($this->advmd as $item) {
+                $advmd_id = (int) $item["id"];
+                $val = " ";
+                if (isset($a_set["md_" . $advmd_id . "_presentation"])) {
+                    $pb = $a_set["md_" . $advmd_id . "_presentation"]->getList();
+                    if ($pb) {
+                        $val = $pb;
+                    }
+                }
+                $a_excel->setCell($a_row, ++$col, $val);
+            }
+        }
+    }
+
+    protected function fillHeaderCSV($a_csv)
+    {
+        $a_csv->addColumn($this->lng->txt("title"));
+        if ($this->has_schedule) {
+            $a_csv->addColumn($this->lng->txt("date"));
+            $a_csv->addColumn($this->lng->txt("wk_short"));
+            $a_csv->addColumn($this->lng->txt("cal_weekday"));
+            $a_csv->addColumn($this->lng->txt("book_schedule_slot"));
+            $a_csv->addColumn($this->lng->txt("book_no_of_objects"));
+        } else {
+            $a_csv->addColumn($this->lng->txt("status"));
+        }
+                
+        foreach ($this->getSelectableColumns(true) as $advmd_col) {
+            $a_csv->addColumn($advmd_col["txt"]);
+        }
+        
+        $a_csv->addColumn($this->lng->txt("user"));
+        $a_csv->addRow();
+    }
+
+    protected function fillRowCSV($a_csv, $a_set)
+    {
+        $a_csv->addColumn($a_set["title"]);
+        if ($this->has_schedule) {
+            $a_csv->addColumn(ilDatePresentation::formatDate(new ilDate($a_set["date"], IL_CAL_DATE)));
+            $a_csv->addColumn($a_set["week"]);
+            $a_csv->addColumn(ilCalendarUtil::_numericDayToString($a_set["weekday"], false));
+            $a_csv->addColumn($a_set["slot"]);
+            $a_csv->addColumn($a_set["counter"]);
+        } else {
+            $status = "";
+            if (in_array($a_set['status'], array(ilBookingReservation::STATUS_CANCELLED, ilBookingReservation::STATUS_IN_USE))) {
+                $status = $this->lng->txt('book_reservation_status_' . $a_set['status']);
+            }
+            $a_csv->addColumn($status);
+        }
+        
+        if ($this->advmd) {
+            foreach ($this->advmd as $item) {
+                $advmd_id = (int) $item["id"];
+                $val = " ";
+                if (isset($a_set["md_" . $advmd_id . "_presentation"])) {
+                    $pb = $a_set["md_" . $advmd_id . "_presentation"]->getList();
+                    if ($pb) {
+                        $val = $pb;
+                    }
+                }
+                $a_csv->addColumn($val);
+            }
+        }
+        
+        $a_csv->addColumn($a_set['user_name']);
+        $a_csv->addRow();
+    }
 }
-
-?>
\ No newline at end of file
diff --git a/Modules/BookingManager/classes/class.ilBookingSchedule.php b/Modules/BookingManager/classes/class.ilBookingSchedule.php
index 4da98c66ae566f76fedb67a7a597d90df0e7c885..cd88d0478690e91c8bfb399e50a8715501b02f0d 100644
--- a/Modules/BookingManager/classes/class.ilBookingSchedule.php
+++ b/Modules/BookingManager/classes/class.ilBookingSchedule.php
@@ -11,486 +11,464 @@
  */
 class ilBookingSchedule
 {
-	/**
-	 * @var ilDB
-	 */
-	protected $db;
-
-	protected $id;			// int
-	protected $title;		// string
-	protected $pool_id;		// int
-	protected $raster;		// int
-	protected $rent_min;	// int
-	protected $rent_max;	// int
-	protected $auto_break;	// int
-	protected $deadline;	// int
-	protected $definition;  // array
-	protected $av_from;		// ildatetime
-	protected $av_to;		// ildatetime
-
-	/**
-	 * 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();
-	}
-
-	/**
-	 * 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 booking pool id (aka parent obj ref 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 raster (in minutes)
-	 * @param	int	$a_raster
-	 */
-	function setRaster($a_raster)
-	{
-		$this->raster = (int)$a_raster;
-	}
-
-	/**
-	 * Get booking raster
-	 * @return	int
-	 */
-	function getRaster()
-	{
-		return $this->raster;
-	}
-
-	/**
-	 * Set minimum rental time
-	 * @param	int	$a_min
-	 */
-	function setMinRental($a_min)
-	{
-		$this->rent_min = (int)$a_min;
-	}
-
-	/**
-	 * Get minimum rental time
-	 * @return	int
-	 */
-	function getMinRental()
-	{
-		return $this->rent_min;
-	}
-
-	/**
-	 * Set maximum rental time
-	 * @param	int	$a_max
-	 */
-	function setMaxRental($a_max)
-	{
-		$this->rent_max = (int)$a_max;
-	}
-
-	/**
-	 * Get maximum rental time
-	 * @return	int
-	 */
-	function getMaxRental()
-	{
-		return $this->rent_max;
-	}
-
-	/**
-	 * Set break time
-	 * @param	int	$a_break
-	 */
-	function setAutoBreak($a_break)
-	{
-		$this->auto_break = (int)$a_break;
-	}
-
-	/**
-	 * Get break time
-	 * @return	int
-	 */
-	function getAutoBreak()
-	{
-		return $this->auto_break;
-	}
-
-	/**
-	 * Set deadline
-	 * @param	int	$a_deadline
-	 */
-	function setDeadline($a_deadline)
-	{
-		$this->deadline = (int)$a_deadline;
-	}
-
-	/**
-	 * Get deadline
-	 * @return	int
-	 */
-	function getDeadline()
-	{
-		return $this->deadline;
-	}
-
-	/**
-	 * Set definition
-	 * @param	array	$a_definition
-	 */
-	function setDefinition($a_definition)
-	{
-		$this->definition = $a_definition;
-	}
-
-	/**
-	 * Get definition
-	 * @return	array
-	 */
-	function getDefinition()
-	{
-		return $this->definition;
-	}
-	
-	/**
-	 * Set availability start
-	 * 
-	 * @param ilDateTime $a_date
-	 */
-	function setAvailabilityFrom(ilDateTime $a_date = null)
-	{
-		$this->av_from = $a_date;
-	}
-	
-	/**
-	 * Get availability start
-	 * 
-	 * @return ilDateTime 
-	 */
-	function getAvailabilityFrom()
-	{
-		return $this->av_from;
-	}
-	
-	/**
-	 * Set availability end
-	 * 
-	 * @param ilDateTime $a_date
-	 */
-	function setAvailabilityTo(ilDateTime $a_date = null)
-	{
-		$this->av_to = $a_date;
-	}
-	
-	/**
-	 * Get availability end
-	 * 
-	 * @return ilDateTime 
-	 */
-	function getAvailabilityTo()
-	{
-		return $this->av_to;
-	}
-
-	/**
-	 * Get dataset from db
-	 */
-	protected function read()
-	{
-		$ilDB = $this->db;
-		
-		if($this->id)
-		{
-			$set = $ilDB->query('SELECT title,raster,rent_min,rent_max,auto_break,'.
-				'deadline,av_from,av_to'.
-				' FROM booking_schedule'.
-				' WHERE booking_schedule_id = '.$ilDB->quote($this->id, 'integer'));
-			$row = $ilDB->fetchAssoc($set);
-			$this->setTitle($row['title']);
-			$this->setDeadline($row['deadline']);
-			$this->setAvailabilityFrom($row['av_from'] ? new ilDateTime($row['av_from'], IL_CAL_UNIX) : null);
-			$this->setAvailabilityTo($row['av_to'] ? new ilDateTime($row['av_to'], IL_CAL_UNIX) : null);
-			if($row['raster'])
-			{
-				$this->setRaster($row['raster']);
-				$this->setMinRental($row['rent_min']);
-				$this->setMaxRental($row['rent_max']);
-				$this->setAutoBreak($row['auto_break']);
-			}
-
-			// load definition
-			$definition = array();
-			$set = $ilDB->query('SELECT day_id,slot_id,times'.
-				' FROM booking_schedule_slot'.
-				' WHERE booking_schedule_id = '.$ilDB->quote($this->id, 'integer'));
-			while($row = $ilDB->fetchAssoc($set))
-			{
-				$definition[$row["day_id"]][$row["slot_id"]] = $row["times"];
-			}
-			$this->setDefinition($definition);
-		}
-	}
-
-	/**
-	 * Create new entry in db
-	 * @return	bool
-	 */
-	function save()
-	{
-		$ilDB = $this->db;
-
-		if($this->id)
-		{
-			return false;
-		}
-
-		$this->id = $ilDB->nextId('booking_schedule');
-
-		$av_from = ($this->getAvailabilityFrom() && !$this->getAvailabilityFrom()->isNull())
-			? $this->getAvailabilityFrom()->get(IL_CAL_UNIX)
-			: null;
-		$av_to = ($this->getAvailabilityTo() && !$this->getAvailabilityTo()->isNull())
-			? $this->getAvailabilityTo()->get(IL_CAL_UNIX)
-			: null;
-
-		$ilDB->manipulate('INSERT INTO booking_schedule'.
-			' (booking_schedule_id,title,pool_id,raster,rent_min,rent_max,auto_break,'.
-			'deadline,av_from,av_to)'.
-			' VALUES ('.$ilDB->quote($this->id, 'integer').','.$ilDB->quote($this->getTitle(), 'text').
-			','.$ilDB->quote($this->getPoolId(), 'integer').','.$ilDB->quote($this->getRaster(), 'integer').
-			','.$ilDB->quote($this->getMinRental(), 'integer').','.$ilDB->quote($this->getMaxRental(), 'integer').
-			','.$ilDB->quote($this->getAutoBreak(), 'integer').','.$ilDB->quote($this->getDeadline(), 'integer').
-			','.$ilDB->quote($av_from, 'integer').','.$ilDB->quote($av_to, 'integer').')');
-
-		$this->saveDefinition();
-		
-		return $this->id;
-	}
-
-	/**
-	 * Update entry in db
-	 * @return	bool
-	 */
-	function update()
-	{
-		$ilDB = $this->db;
-
-		if(!$this->id)
-		{
-			return false;
-		}
-
-		$av_from = ($this->getAvailabilityFrom() && !$this->getAvailabilityFrom()->isNull())
-			? $this->getAvailabilityFrom()->get(IL_CAL_UNIX)
-			: null;
-		$av_to = ($this->getAvailabilityTo() && !$this->getAvailabilityTo()->isNull())
-			? $this->getAvailabilityTo()->get(IL_CAL_UNIX)
-			: null;
-		
-		$ilDB->manipulate('UPDATE booking_schedule'.
-			' SET title = '.$ilDB->quote($this->getTitle(), 'text').
-			', pool_id = '.$ilDB->quote($this->getPoolId(), 'integer').
-			', raster = '.$ilDB->quote($this->getRaster(), 'integer').
-			', rent_min = '.$ilDB->quote($this->getMinRental(), 'integer').
-			', rent_max = '.$ilDB->quote($this->getMaxRental(), 'integer').
-			', auto_break = '.$ilDB->quote($this->getAutoBreak(), 'integer').
-			', deadline = '.$ilDB->quote($this->getDeadline(), 'integer').
-			', av_from = '.$ilDB->quote($av_from, 'integer').
-			', av_to = '.$ilDB->quote($av_to, 'integer').
-			' WHERE booking_schedule_id = '.$ilDB->quote($this->id, 'integer'));
-
-		$this->saveDefinition();
-	}
-	
-	public function doClone($a_pool_id)
-	{
-		$new_obj = new self();
-		$new_obj->setPoolId($a_pool_id);
-		$new_obj->setTitle($this->getTitle());
-		$new_obj->setRaster($this->getRaster());
-		$new_obj->setMinRental($this->getMinRental());
-		$new_obj->setMaxRental($this->getMaxRental());
-		$new_obj->setAutoBreak($this->getAutoBreak());
-		$new_obj->setDeadline($this->getDeadline());
-		$new_obj->setDefinition($this->getDefinition());
-		$new_obj->setAvailabilityFrom($this->getAvailabilityFrom());
-		$new_obj->setAvailabilityTo($this->getAvailabilityTo());
-		return $new_obj->save();	
-	}
-
-	/**
-	 * Save current definition
-	 */
-	protected function saveDefinition()
-	{
-		$ilDB = $this->db;
-
-		if(!$this->id)
-		{
-			return false;
-		}
-
-		$ilDB->manipulate('DELETE FROM booking_schedule_slot'.
-			' WHERE booking_schedule_id = '.$ilDB->quote($this->id, 'integer'));
-
-		$definition = $this->getDefinition();
-		if($definition)
-		{
-			foreach($definition as $day_id => $slots)
-			{
-				foreach($slots as $slot_id => $times)
-				{
-					$fields = array(
-						"booking_schedule_id" => array('integer', $this->id),
-						"day_id" => array('text', $day_id),
-						"slot_id" => array('integer', $slot_id),
-						"times" => array('text', $times)
-						);
-					$ilDB->insert('booking_schedule_slot', $fields);
-				}
-			}
-
-		}
-	}
-
-	/**
-	 * Check if given pool has any defined schedules
-	 * @param int $a_pool_id
-	 * @return bool
-	 */
-	static function hasExistingSchedules($a_pool_id)
-	{
-		global $DIC;
-
-		$ilDB = $DIC->database();
-
-		$set = $ilDB->query("SELECT booking_schedule_id".
-			" FROM booking_schedule".
-			" WHERE pool_id = ".$ilDB->quote($a_pool_id, 'integer'));
-		return (bool)$ilDB->numRows($set);
-	}
-
-	/**
-	 * Get list of booking objects for given pool
-	 * @param	int	$a_pool_id
-	 * @return	array
-	 */
-	static function getList($a_pool_id)
-	{
-		global $DIC;
-
-		$ilDB = $DIC->database();
-
-		$set = $ilDB->query('SELECT s.booking_schedule_id,s.title,'.
-			'MAX(o.schedule_id) AS object_has_schedule'.
-			' FROM booking_schedule s'.
-			' LEFT JOIN booking_object o ON (s.booking_schedule_id = o.schedule_id)'.
-			' WHERE s.pool_id = '.$ilDB->quote($a_pool_id, 'integer').
-			' GROUP BY s.booking_schedule_id,s.title'.
-			' ORDER BY s.title');
-		$res = array();
-		while($row = $ilDB->fetchAssoc($set))
-		{
-			if(!$row['object_has_schedule'])
-			{
-				$row['is_used'] = false;
-			}
-			else
-			{
-				$row['is_used'] = true;
-			}
-			$res[] = $row;
-		}
-		return $res;
-	}
-
-	/**
-	 * Delete single entry
-	 * @return bool
-	 */
-	function delete()
-	{
-		$ilDB = $this->db;
-
-		if($this->id)
-		{
-			return $ilDB->manipulate('DELETE FROM booking_schedule'.
-				' WHERE booking_schedule_id = '.$ilDB->quote($this->id, 'integer'));
-		}
-	}
-	
-	/**
-	 * Return definition grouped by slots (not days)
-	 * 
-	 * @return array
-	 */
-	function getDefinitionBySlots()
-	{
-		$def = $this->getDefinition();
-		$slots = array();
-		foreach($def as $day => $times)
-		{
-			foreach($times as $time)
-			{
-				$slots[$time][] = $day;
-			}
-		}
-		foreach($slots as $time => $days)
-		{
-			$slots[$time] = array_unique($days);		
-		}
-		ksort($slots);
-		return $slots;
-	}
-	
-	function setDefinitionBySlots(array $a_def)
-	{
-		$slots = array();
-		foreach($a_def as $time => $days)
-		{
-			foreach($days as $day)
-			{
-				$slots[$day][] = $time;
-			}
-		}
-		$this->setDefinition($slots);
-	}
+    /**
+     * @var ilDB
+     */
+    protected $db;
+
+    protected $id;			// int
+    protected $title;		// string
+    protected $pool_id;		// int
+    protected $raster;		// int
+    protected $rent_min;	// int
+    protected $rent_max;	// int
+    protected $auto_break;	// int
+    protected $deadline;	// int
+    protected $definition;  // array
+    protected $av_from;		// ildatetime
+    protected $av_to;		// ildatetime
+
+    /**
+     * 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();
+    }
+
+    /**
+     * 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 booking pool id (aka parent obj ref 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 raster (in minutes)
+     * @param	int	$a_raster
+     */
+    public function setRaster($a_raster)
+    {
+        $this->raster = (int) $a_raster;
+    }
+
+    /**
+     * Get booking raster
+     * @return	int
+     */
+    public function getRaster()
+    {
+        return $this->raster;
+    }
+
+    /**
+     * Set minimum rental time
+     * @param	int	$a_min
+     */
+    public function setMinRental($a_min)
+    {
+        $this->rent_min = (int) $a_min;
+    }
+
+    /**
+     * Get minimum rental time
+     * @return	int
+     */
+    public function getMinRental()
+    {
+        return $this->rent_min;
+    }
+
+    /**
+     * Set maximum rental time
+     * @param	int	$a_max
+     */
+    public function setMaxRental($a_max)
+    {
+        $this->rent_max = (int) $a_max;
+    }
+
+    /**
+     * Get maximum rental time
+     * @return	int
+     */
+    public function getMaxRental()
+    {
+        return $this->rent_max;
+    }
+
+    /**
+     * Set break time
+     * @param	int	$a_break
+     */
+    public function setAutoBreak($a_break)
+    {
+        $this->auto_break = (int) $a_break;
+    }
+
+    /**
+     * Get break time
+     * @return	int
+     */
+    public function getAutoBreak()
+    {
+        return $this->auto_break;
+    }
+
+    /**
+     * Set deadline
+     * @param	int	$a_deadline
+     */
+    public function setDeadline($a_deadline)
+    {
+        $this->deadline = (int) $a_deadline;
+    }
+
+    /**
+     * Get deadline
+     * @return	int
+     */
+    public function getDeadline()
+    {
+        return $this->deadline;
+    }
+
+    /**
+     * Set definition
+     * @param	array	$a_definition
+     */
+    public function setDefinition($a_definition)
+    {
+        $this->definition = $a_definition;
+    }
+
+    /**
+     * Get definition
+     * @return	array
+     */
+    public function getDefinition()
+    {
+        return $this->definition;
+    }
+    
+    /**
+     * Set availability start
+     *
+     * @param ilDateTime $a_date
+     */
+    public function setAvailabilityFrom(ilDateTime $a_date = null)
+    {
+        $this->av_from = $a_date;
+    }
+    
+    /**
+     * Get availability start
+     *
+     * @return ilDateTime
+     */
+    public function getAvailabilityFrom()
+    {
+        return $this->av_from;
+    }
+    
+    /**
+     * Set availability end
+     *
+     * @param ilDateTime $a_date
+     */
+    public function setAvailabilityTo(ilDateTime $a_date = null)
+    {
+        $this->av_to = $a_date;
+    }
+    
+    /**
+     * Get availability end
+     *
+     * @return ilDateTime
+     */
+    public function getAvailabilityTo()
+    {
+        return $this->av_to;
+    }
+
+    /**
+     * Get dataset from db
+     */
+    protected function read()
+    {
+        $ilDB = $this->db;
+        
+        if ($this->id) {
+            $set = $ilDB->query('SELECT title,raster,rent_min,rent_max,auto_break,' .
+                'deadline,av_from,av_to' .
+                ' FROM booking_schedule' .
+                ' WHERE booking_schedule_id = ' . $ilDB->quote($this->id, 'integer'));
+            $row = $ilDB->fetchAssoc($set);
+            $this->setTitle($row['title']);
+            $this->setDeadline($row['deadline']);
+            $this->setAvailabilityFrom($row['av_from'] ? new ilDateTime($row['av_from'], IL_CAL_UNIX) : null);
+            $this->setAvailabilityTo($row['av_to'] ? new ilDateTime($row['av_to'], IL_CAL_UNIX) : null);
+            if ($row['raster']) {
+                $this->setRaster($row['raster']);
+                $this->setMinRental($row['rent_min']);
+                $this->setMaxRental($row['rent_max']);
+                $this->setAutoBreak($row['auto_break']);
+            }
+
+            // load definition
+            $definition = array();
+            $set = $ilDB->query('SELECT day_id,slot_id,times' .
+                ' FROM booking_schedule_slot' .
+                ' WHERE booking_schedule_id = ' . $ilDB->quote($this->id, 'integer'));
+            while ($row = $ilDB->fetchAssoc($set)) {
+                $definition[$row["day_id"]][$row["slot_id"]] = $row["times"];
+            }
+            $this->setDefinition($definition);
+        }
+    }
+
+    /**
+     * Create new entry in db
+     * @return	bool
+     */
+    public function save()
+    {
+        $ilDB = $this->db;
+
+        if ($this->id) {
+            return false;
+        }
+
+        $this->id = $ilDB->nextId('booking_schedule');
+
+        $av_from = ($this->getAvailabilityFrom() && !$this->getAvailabilityFrom()->isNull())
+            ? $this->getAvailabilityFrom()->get(IL_CAL_UNIX)
+            : null;
+        $av_to = ($this->getAvailabilityTo() && !$this->getAvailabilityTo()->isNull())
+            ? $this->getAvailabilityTo()->get(IL_CAL_UNIX)
+            : null;
+
+        $ilDB->manipulate('INSERT INTO booking_schedule' .
+            ' (booking_schedule_id,title,pool_id,raster,rent_min,rent_max,auto_break,' .
+            'deadline,av_from,av_to)' .
+            ' VALUES (' . $ilDB->quote($this->id, 'integer') . ',' . $ilDB->quote($this->getTitle(), 'text') .
+            ',' . $ilDB->quote($this->getPoolId(), 'integer') . ',' . $ilDB->quote($this->getRaster(), 'integer') .
+            ',' . $ilDB->quote($this->getMinRental(), 'integer') . ',' . $ilDB->quote($this->getMaxRental(), 'integer') .
+            ',' . $ilDB->quote($this->getAutoBreak(), 'integer') . ',' . $ilDB->quote($this->getDeadline(), 'integer') .
+            ',' . $ilDB->quote($av_from, 'integer') . ',' . $ilDB->quote($av_to, 'integer') . ')');
+
+        $this->saveDefinition();
+        
+        return $this->id;
+    }
+
+    /**
+     * Update entry in db
+     * @return	bool
+     */
+    public function update()
+    {
+        $ilDB = $this->db;
+
+        if (!$this->id) {
+            return false;
+        }
+
+        $av_from = ($this->getAvailabilityFrom() && !$this->getAvailabilityFrom()->isNull())
+            ? $this->getAvailabilityFrom()->get(IL_CAL_UNIX)
+            : null;
+        $av_to = ($this->getAvailabilityTo() && !$this->getAvailabilityTo()->isNull())
+            ? $this->getAvailabilityTo()->get(IL_CAL_UNIX)
+            : null;
+        
+        $ilDB->manipulate('UPDATE booking_schedule' .
+            ' SET title = ' . $ilDB->quote($this->getTitle(), 'text') .
+            ', pool_id = ' . $ilDB->quote($this->getPoolId(), 'integer') .
+            ', raster = ' . $ilDB->quote($this->getRaster(), 'integer') .
+            ', rent_min = ' . $ilDB->quote($this->getMinRental(), 'integer') .
+            ', rent_max = ' . $ilDB->quote($this->getMaxRental(), 'integer') .
+            ', auto_break = ' . $ilDB->quote($this->getAutoBreak(), 'integer') .
+            ', deadline = ' . $ilDB->quote($this->getDeadline(), 'integer') .
+            ', av_from = ' . $ilDB->quote($av_from, 'integer') .
+            ', av_to = ' . $ilDB->quote($av_to, 'integer') .
+            ' WHERE booking_schedule_id = ' . $ilDB->quote($this->id, 'integer'));
+
+        $this->saveDefinition();
+    }
+    
+    public function doClone($a_pool_id)
+    {
+        $new_obj = new self();
+        $new_obj->setPoolId($a_pool_id);
+        $new_obj->setTitle($this->getTitle());
+        $new_obj->setRaster($this->getRaster());
+        $new_obj->setMinRental($this->getMinRental());
+        $new_obj->setMaxRental($this->getMaxRental());
+        $new_obj->setAutoBreak($this->getAutoBreak());
+        $new_obj->setDeadline($this->getDeadline());
+        $new_obj->setDefinition($this->getDefinition());
+        $new_obj->setAvailabilityFrom($this->getAvailabilityFrom());
+        $new_obj->setAvailabilityTo($this->getAvailabilityTo());
+        return $new_obj->save();
+    }
+
+    /**
+     * Save current definition
+     */
+    protected function saveDefinition()
+    {
+        $ilDB = $this->db;
+
+        if (!$this->id) {
+            return false;
+        }
+
+        $ilDB->manipulate('DELETE FROM booking_schedule_slot' .
+            ' WHERE booking_schedule_id = ' . $ilDB->quote($this->id, 'integer'));
+
+        $definition = $this->getDefinition();
+        if ($definition) {
+            foreach ($definition as $day_id => $slots) {
+                foreach ($slots as $slot_id => $times) {
+                    $fields = array(
+                        "booking_schedule_id" => array('integer', $this->id),
+                        "day_id" => array('text', $day_id),
+                        "slot_id" => array('integer', $slot_id),
+                        "times" => array('text', $times)
+                        );
+                    $ilDB->insert('booking_schedule_slot', $fields);
+                }
+            }
+        }
+    }
+
+    /**
+     * Check if given pool has any defined schedules
+     * @param int $a_pool_id
+     * @return bool
+     */
+    public static function hasExistingSchedules($a_pool_id)
+    {
+        global $DIC;
+
+        $ilDB = $DIC->database();
+
+        $set = $ilDB->query("SELECT booking_schedule_id" .
+            " FROM booking_schedule" .
+            " WHERE pool_id = " . $ilDB->quote($a_pool_id, 'integer'));
+        return (bool) $ilDB->numRows($set);
+    }
+
+    /**
+     * Get list of booking objects for given pool
+     * @param	int	$a_pool_id
+     * @return	array
+     */
+    public static function getList($a_pool_id)
+    {
+        global $DIC;
+
+        $ilDB = $DIC->database();
+
+        $set = $ilDB->query('SELECT s.booking_schedule_id,s.title,' .
+            'MAX(o.schedule_id) AS object_has_schedule' .
+            ' FROM booking_schedule s' .
+            ' LEFT JOIN booking_object o ON (s.booking_schedule_id = o.schedule_id)' .
+            ' WHERE s.pool_id = ' . $ilDB->quote($a_pool_id, 'integer') .
+            ' GROUP BY s.booking_schedule_id,s.title' .
+            ' ORDER BY s.title');
+        $res = array();
+        while ($row = $ilDB->fetchAssoc($set)) {
+            if (!$row['object_has_schedule']) {
+                $row['is_used'] = false;
+            } else {
+                $row['is_used'] = true;
+            }
+            $res[] = $row;
+        }
+        return $res;
+    }
+
+    /**
+     * Delete single entry
+     * @return bool
+     */
+    public function delete()
+    {
+        $ilDB = $this->db;
+
+        if ($this->id) {
+            return $ilDB->manipulate('DELETE FROM booking_schedule' .
+                ' WHERE booking_schedule_id = ' . $ilDB->quote($this->id, 'integer'));
+        }
+    }
+    
+    /**
+     * Return definition grouped by slots (not days)
+     *
+     * @return array
+     */
+    public function getDefinitionBySlots()
+    {
+        $def = $this->getDefinition();
+        $slots = array();
+        foreach ($def as $day => $times) {
+            foreach ($times as $time) {
+                $slots[$time][] = $day;
+            }
+        }
+        foreach ($slots as $time => $days) {
+            $slots[$time] = array_unique($days);
+        }
+        ksort($slots);
+        return $slots;
+    }
+    
+    public function setDefinitionBySlots(array $a_def)
+    {
+        $slots = array();
+        foreach ($a_def as $time => $days) {
+            foreach ($days as $day) {
+                $slots[$day][] = $time;
+            }
+        }
+        $this->setDefinition($slots);
+    }
 }
-
-?>
\ No newline at end of file
diff --git a/Modules/BookingManager/classes/class.ilBookingScheduleGUI.php b/Modules/BookingManager/classes/class.ilBookingScheduleGUI.php
index 8a4f9fff185a3d63468631746170ddb37fcfc30b..18ab685ba7dd5b9a7a282422516074d82f3800da 100644
--- a/Modules/BookingManager/classes/class.ilBookingScheduleGUI.php
+++ b/Modules/BookingManager/classes/class.ilBookingScheduleGUI.php
@@ -6,481 +6,454 @@
 *
 * @author Jörg Lützenkirchen 
 * @version $Id$
-* 
+*
 * @ilCtrl_Calls ilBookingScheduleGUI:
 */
 class ilBookingScheduleGUI
 {
-	/**
-	 * @var ilTemplate
-	 */
-	protected $tpl;
-
-	/**
-	 * @var ilTabsGUI
-	 */
-	protected $tabs;
-
-	/**
-	 * @var ilCtrl
-	 */
-	protected $ctrl;
-
-	/**
-	 * @var ilLanguage
-	 */
-	protected $lng;
-
-	/**
-	 * @var ilAccessHandler
-	 */
-	protected $access;
-
-	/**
-	 * @var ilHelpGUI
-	 */
-	protected $help;
-
-	/**
-	 * @var ilObjectDataCache
-	 */
-	protected $obj_data_cache;
-
-	/**
-	 * @var int
-	 */
-	protected $schedule_id;
-
-	/**
-	 * Constructor
-	 * @param	object	$a_parent_obj
-	 */
-	function __construct($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->help = $DIC["ilHelp"];
-		$this->obj_data_cache = $DIC["ilObjDataCache"];
-		$this->ref_id = $a_parent_obj->ref_id;
-		$this->schedule_id  = (int)$_REQUEST['schedule_id'];
-	}
-
-	/**
-	 * main switch
-	 */
-	function executeCommand()
-	{
-		$tpl = $this->tpl;
-		$ilTabs = $this->tabs;
-		$ilCtrl = $this->ctrl;
-
-		$next_class = $ilCtrl->getNextClass($this);
-
-		switch($next_class)
-		{
-			default:
-				$cmd = $ilCtrl->getCmd("render");
-				$this->$cmd();
-				break;
-		}
-		return true;
-	}
-
-	/**
-	 * Render list of booking schedules
-	 *
-	 * uses ilBookingSchedulesTableGUI
-	 */
-	function render()
-	{
-		$tpl = $this->tpl;
-		$lng = $this->lng;
-		$ilCtrl = $this->ctrl;
-		$ilAccess = $this->access;
-
-		include_once 'Modules/BookingManager/classes/class.ilBookingSchedulesTableGUI.php';
-		$table = new ilBookingSchedulesTableGUI($this, 'render', $this->ref_id);
-		
-		if ($ilAccess->checkAccess('write', '', $this->ref_id))
-		{
-			// if we have schedules but no objects - show info
-			if(sizeof($table->getData()))
-			{
-				include_once "Modules/BookingManager/classes/class.ilBookingObject.php";
-				if(!sizeof(ilBookingObject::getList(ilObject::_lookupObjId($this->ref_id))))
-				{
-					ilUtil::sendInfo($lng->txt("book_type_warning"));
-				}
-			}
-			
-			include_once 'Services/UIComponent/Toolbar/classes/class.ilToolbarGUI.php';
-			$bar = new ilToolbarGUI;
-			$bar->addButton($lng->txt('book_add_schedule'), $ilCtrl->getLinkTarget($this, 'create'));
-			$bar = $bar->getHTML();
-		}
-		
-		$tpl->setContent($bar.$table->getHTML());
-	}
-
-	/**
-	 * Render creation form
-	 */
-	function create()
+    /**
+     * @var ilTemplate
+     */
+    protected $tpl;
+
+    /**
+     * @var ilTabsGUI
+     */
+    protected $tabs;
+
+    /**
+     * @var ilCtrl
+     */
+    protected $ctrl;
+
+    /**
+     * @var ilLanguage
+     */
+    protected $lng;
+
+    /**
+     * @var ilAccessHandler
+     */
+    protected $access;
+
+    /**
+     * @var ilHelpGUI
+     */
+    protected $help;
+
+    /**
+     * @var ilObjectDataCache
+     */
+    protected $obj_data_cache;
+
+    /**
+     * @var int
+     */
+    protected $schedule_id;
+
+    /**
+     * Constructor
+     * @param	object	$a_parent_obj
+     */
+    public function __construct($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->help = $DIC["ilHelp"];
+        $this->obj_data_cache = $DIC["ilObjDataCache"];
+        $this->ref_id = $a_parent_obj->ref_id;
+        $this->schedule_id  = (int) $_REQUEST['schedule_id'];
+    }
+
+    /**
+     * main switch
+     */
+    public function executeCommand()
+    {
+        $tpl = $this->tpl;
+        $ilTabs = $this->tabs;
+        $ilCtrl = $this->ctrl;
+
+        $next_class = $ilCtrl->getNextClass($this);
+
+        switch ($next_class) {
+            default:
+                $cmd = $ilCtrl->getCmd("render");
+                $this->$cmd();
+                break;
+        }
+        return true;
+    }
+
+    /**
+     * Render list of booking schedules
+     *
+     * uses ilBookingSchedulesTableGUI
+     */
+    public function render()
     {
-		$tpl = $this->tpl;
-		$ilCtrl = $this->ctrl;
-		$ilTabs = $this->tabs;
-		$lng = $this->lng;
-		$ilHelp = $this->help;
-
-		$ilTabs->clearTargets();
-		$ilTabs->setBackTarget($lng->txt('book_back_to_list'), $ilCtrl->getLinkTarget($this, 'render'));
-		$ilHelp->setScreenIdComponent("book");
-		$ilHelp->setScreenId("schedules");
-		$ilHelp->setSubScreenId("create");
-
-		$form = $this->initForm();
-		$tpl->setContent($form->getHTML());
-	}
-
-	/**
-	 * Render edit form
-	 */
-	function edit()
+        $tpl = $this->tpl;
+        $lng = $this->lng;
+        $ilCtrl = $this->ctrl;
+        $ilAccess = $this->access;
+
+        include_once 'Modules/BookingManager/classes/class.ilBookingSchedulesTableGUI.php';
+        $table = new ilBookingSchedulesTableGUI($this, 'render', $this->ref_id);
+        
+        if ($ilAccess->checkAccess('write', '', $this->ref_id)) {
+            // if we have schedules but no objects - show info
+            if (sizeof($table->getData())) {
+                include_once "Modules/BookingManager/classes/class.ilBookingObject.php";
+                if (!sizeof(ilBookingObject::getList(ilObject::_lookupObjId($this->ref_id)))) {
+                    ilUtil::sendInfo($lng->txt("book_type_warning"));
+                }
+            }
+            
+            include_once 'Services/UIComponent/Toolbar/classes/class.ilToolbarGUI.php';
+            $bar = new ilToolbarGUI;
+            $bar->addButton($lng->txt('book_add_schedule'), $ilCtrl->getLinkTarget($this, 'create'));
+            $bar = $bar->getHTML();
+        }
+        
+        $tpl->setContent($bar . $table->getHTML());
+    }
+
+    /**
+     * Render creation form
+     */
+    public function create()
     {
-		$tpl = $this->tpl;
-		$ilCtrl = $this->ctrl;
-		$ilTabs = $this->tabs;
-		$lng = $this->lng;
-		$ilHelp = $this->help;
-
-		$ilTabs->clearTargets();
-		$ilTabs->setBackTarget($lng->txt('book_back_to_list'), $ilCtrl->getLinkTarget($this, 'render'));
-		$ilHelp->setScreenIdComponent("book");
-		$ilHelp->setScreenId("schedules");
-		$ilHelp->setSubScreenId("edit");
-
-		$form = $this->initForm('edit', $this->schedule_id);
-		$tpl->setContent($form->getHTML());
-	}
-
-	/**
-	 * 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;
-
-		$lng->loadLanguageModule("dateplaner");
-
-		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);
-
-		include_once "Modules/BookingManager/classes/class.ilScheduleInputGUI.php";
-		$definition = new ilScheduleInputGUI($lng->txt("book_schedule_days"), "days");
-		$definition->setInfo($lng->txt("book_schedule_days_info"));
-		$definition->setRequired(true);
-		$form_gui->addItem($definition);
-
-		$deadline_opts = new ilRadioGroupInputGUI($lng->txt("book_deadline_options"), "deadline_opts");
-		$deadline_opts->setRequired(true);
-		$form_gui->addItem($deadline_opts);
-
-		$deadline_time = new ilRadioOption($lng->txt("book_deadline_hours"), "hours");
-		$deadline_opts->addOption($deadline_time);
-
-		$deadline = new ilNumberInputGUI($lng->txt("book_deadline"), "deadline");
-		$deadline->setInfo($lng->txt("book_deadline_info"));
-		$deadline->setSuffix($lng->txt("book_hours"));
-		$deadline->setMinValue(1);
-		$deadline->setSize(3);
-		$deadline->setMaxLength(3);
-		$deadline_time->addSubItem($deadline);
-
-		$deadline_start = new ilRadioOption($lng->txt("book_deadline_slot_start"), "slot_start");
-		$deadline_opts->addOption($deadline_start);
-
-		$deadline_slot = new ilRadioOption($lng->txt("book_deadline_slot_end"), "slot_end");
-		$deadline_opts->addOption($deadline_slot);
-		
-		if ($a_mode == "edit")
-		{			
-			include_once 'Modules/BookingManager/classes/class.ilBookingSchedule.php';
-			$schedule = new ilBookingSchedule($id);
-		}		
-		
-		$av = new ilFormSectionHeaderGUI();
-		$av->setTitle($lng->txt("obj_activation_list_gui"));
-		$form_gui->addItem($av);
-				
-		// #18221
-		$lng->loadLanguageModule('rep');		
-		
-		$from = new ilDateTimeInputGUI($lng->txt("rep_activation_limited_start"), "from");		
-		$from->setShowTime(true);
-		$form_gui->addItem($from);
-		
-		$to = new ilDateTimeInputGUI($lng->txt("rep_activation_limited_end"), "to");		
-		$to->setShowTime(true);
-		$form_gui->addItem($to);
-	
-		if ($a_mode == "edit")
-		{
-			$form_gui->setTitle($lng->txt("book_edit_schedule"));
-
-			$item = new ilHiddenInputGUI('schedule_id');
-			$item->setValue($id);
-			$form_gui->addItem($item);
-
-			include_once 'Modules/BookingManager/classes/class.ilBookingSchedule.php';
-			$schedule = new ilBookingSchedule($id);
-			$title->setValue($schedule->getTitle());
-			$from->setDate($schedule->getAvailabilityFrom());
-			$to->setDate($schedule->getAvailabilityTo());
-			
-			if($schedule->getDeadline() == 0)
-			{				
-				$deadline_opts->setValue("slot_start");
-			}
-			else if($schedule->getDeadline() > 0)
-			{
-				$deadline->setValue($schedule->getDeadline());
-				$deadline_opts->setValue("hours");
-			}
-			else
-			{
-				$deadline->setValue(0);
-				$deadline_opts->setValue("slot_end");
-			}
-
-			/*
-			if($schedule->getRaster())
-			{
-				$type->setValue("flexible");
-				$raster->setValue($schedule->getRaster());
-				$rent_min->setValue($schedule->getMinRental());
-				$rent_max->setValue($schedule->getMaxRental());
-				$break->setValue($schedule->getAutoBreak());
-			}
-			else
-			{
-				$type->setValue("fix");
-			}
-			*/
-
-			$definition->setValue($schedule->getDefinitionBySlots());
-
-			$form_gui->addCommandButton("update", $lng->txt("save"));
-		}
-		else
-		{
-			$form_gui->setTitle($lng->txt("book_add_schedule"));
-			$form_gui->addCommandButton("save", $lng->txt("save"));
-			$form_gui->addCommandButton("render", $lng->txt("cancel"));
-		}
-		$form_gui->setFormAction($ilCtrl->getFormAction($this));
-
-		return $form_gui;
-	}
+        $tpl = $this->tpl;
+        $ilCtrl = $this->ctrl;
+        $ilTabs = $this->tabs;
+        $lng = $this->lng;
+        $ilHelp = $this->help;
+
+        $ilTabs->clearTargets();
+        $ilTabs->setBackTarget($lng->txt('book_back_to_list'), $ilCtrl->getLinkTarget($this, 'render'));
+        $ilHelp->setScreenIdComponent("book");
+        $ilHelp->setScreenId("schedules");
+        $ilHelp->setSubScreenId("create");
+
+        $form = $this->initForm();
+        $tpl->setContent($form->getHTML());
+    }
 
     /**
-	 * Create new dataset
-	 */
-	function save()
-	{
-		$tpl = $this->tpl;
-		$lng = $this->lng;
-
-		$form = $this->initForm();
-		if($form->checkInput())
-		{
-			include_once 'Modules/BookingManager/classes/class.ilBookingSchedule.php';
-			$obj = new ilBookingSchedule;
-			$this->formToObject($form, $obj);
-			$obj->save();
-
-			ilUtil::sendSuccess($lng->txt("book_schedule_added"));
-			$this->render();
-		}
-		else
-		{
-			$form->setValuesByPost();
-			$this->setDefinitionFromPost($form);
-			$tpl->setContent($form->getHTML());
-		}
-	}
-
-	/**
-	 * Update dataset
-	 */
-	function update()
-	{
-		$tpl = $this->tpl;
-		$lng = $this->lng;
-
-		$form = $this->initForm('edit', $this->schedule_id);
-		if($form->checkInput())
-		{
-			include_once 'Modules/BookingManager/classes/class.ilBookingSchedule.php';
-			$obj = new ilBookingSchedule($this->schedule_id);
-			$this->formToObject($form, $obj);
-			$obj->update();
-
-			ilUtil::sendSuccess($lng->txt("book_schedule_updated"));
-			$this->render();
-		}
-		else
-		{
-			$form->setValuesByPost();
-			$this->setDefinitionFromPost($form);
-			$tpl->setContent($form->getHTML());
-		}
-	}
-
-	/**
-	 * Reload definition values from post data
-	 *
-	 * @param ilPropertyFormGUI $form
-	 */
-	protected function setDefinitionFromPost(ilPropertyFormGUI $form)
-	{
-		$days = $form->getInput("days");
-		if($days)
-		{
-			$days_group = $form->getItemByPostVar("days");
-			foreach($days_group->getOptions() as $option)
-			{
-				$days_fields[$option->getValue()] = $option;
-			}
-			
-			foreach($days as $day)
-			{
-				$slot = $form->getInput($day."_slot");
-				$subs = $days_fields[$day]->getSubItems();
-				if($slot[0])
-				{
-					$subs[0]->setValue($slot[0]);
-				}
-				if($slot[1])
-				{
-					$subs[1]->setValue($slot[1]);
-				}
-			}
-		}
-	}
-
-	/**
-	 * Convert incoming form data to schedule object
-	 * @param	object	$form
-	 * @param	object	$schedule
-	 */
-	protected function formToObject($form, $schedule)
-	{
-		$ilObjDataCache = $this->obj_data_cache;
-		
-		$schedule->setTitle($form->getInput("title"));
-		$schedule->setPoolId($ilObjDataCache->lookupObjId($this->ref_id));
-		
-		$from = $form->getItemByPostVar("from");		
-		$schedule->setAvailabilityFrom($from->getDate());
-		
-		$to = $form->getItemByPostVar("to");
-		$schedule->setAvailabilityTo($to->getDate());
-		
-		switch($form->getInput("deadline_opts"))
-		{
-			case "slot_start":
-				$schedule->setDeadline(0);
-				break;
-			
-			case "hours":			
-				$schedule->setDeadline($form->getInput("deadline"));
-				break;
-			
-			case "slot_end":
-				$schedule->setDeadline(-1);
-				break;
-		}
-
-		/*
-		if($form->getInput("type") == "flexible")
-		{
-			$schedule->setRaster($form->getInput("raster"));
-			$schedule->setMinRental($form->getInput("rent_min"));
-			$schedule->setMaxRental($form->getInput("rent_max"));
-			$schedule->setAutoBreak($form->getInput("break"));
-		}
-		else
-		{
-			$schedule->setRaster(NULL);
-			$schedule->setMinRental(NULL);
-			$schedule->setMaxRental(NULL);
-			$schedule->setAutoBreak(NULL);
-		}
-		*/
-		
-		$schedule->setDefinitionBySlots(ilScheduleInputGUI::getPostData("days"));
-	}
-
-	/**
-	 * Confirm delete
-	 */
-	function confirmDelete()
-	{
-		$ilCtrl = $this->ctrl;
-		$lng = $this->lng;
-		$tpl = $this->tpl;
-		$ilTabs = $this->tabs;
-		$ilHelp = $this->help;
-
-		$ilHelp->setSubScreenId("delete");
-
-
-		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.ilBookingSchedule.php';
-		$type = new ilBookingSchedule($this->schedule_id);
-		$conf->addItem('schedule_id', $this->schedule_id, $type->getTitle());
-		$conf->setConfirm($lng->txt('delete'), 'delete');
-		$conf->setCancel($lng->txt('cancel'), 'render');
-
-		$tpl->setContent($conf->getHTML());
-	}
-
-	/**
-	 * Delete schedule
-	 */
-	function delete()
-	{
-		$ilCtrl = $this->ctrl;
-		$lng = $this->lng;
-
-		include_once 'Modules/BookingManager/classes/class.ilBookingSchedule.php';
-		$obj = new ilBookingSchedule($this->schedule_id);
-		$obj->delete();
-
-		ilUtil::sendSuccess($lng->txt('book_schedule_deleted'), true);
-		$ilCtrl->redirect($this, 'render');
-	}
-}
+     * Render edit form
+     */
+    public function edit()
+    {
+        $tpl = $this->tpl;
+        $ilCtrl = $this->ctrl;
+        $ilTabs = $this->tabs;
+        $lng = $this->lng;
+        $ilHelp = $this->help;
+
+        $ilTabs->clearTargets();
+        $ilTabs->setBackTarget($lng->txt('book_back_to_list'), $ilCtrl->getLinkTarget($this, 'render'));
+        $ilHelp->setScreenIdComponent("book");
+        $ilHelp->setScreenId("schedules");
+        $ilHelp->setSubScreenId("edit");
+
+        $form = $this->initForm('edit', $this->schedule_id);
+        $tpl->setContent($form->getHTML());
+    }
+
+    /**
+     * 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;
+
+        $lng->loadLanguageModule("dateplaner");
+
+        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);
+
+        include_once "Modules/BookingManager/classes/class.ilScheduleInputGUI.php";
+        $definition = new ilScheduleInputGUI($lng->txt("book_schedule_days"), "days");
+        $definition->setInfo($lng->txt("book_schedule_days_info"));
+        $definition->setRequired(true);
+        $form_gui->addItem($definition);
+
+        $deadline_opts = new ilRadioGroupInputGUI($lng->txt("book_deadline_options"), "deadline_opts");
+        $deadline_opts->setRequired(true);
+        $form_gui->addItem($deadline_opts);
+
+        $deadline_time = new ilRadioOption($lng->txt("book_deadline_hours"), "hours");
+        $deadline_opts->addOption($deadline_time);
+
+        $deadline = new ilNumberInputGUI($lng->txt("book_deadline"), "deadline");
+        $deadline->setInfo($lng->txt("book_deadline_info"));
+        $deadline->setSuffix($lng->txt("book_hours"));
+        $deadline->setMinValue(1);
+        $deadline->setSize(3);
+        $deadline->setMaxLength(3);
+        $deadline_time->addSubItem($deadline);
+
+        $deadline_start = new ilRadioOption($lng->txt("book_deadline_slot_start"), "slot_start");
+        $deadline_opts->addOption($deadline_start);
+
+        $deadline_slot = new ilRadioOption($lng->txt("book_deadline_slot_end"), "slot_end");
+        $deadline_opts->addOption($deadline_slot);
+        
+        if ($a_mode == "edit") {
+            include_once 'Modules/BookingManager/classes/class.ilBookingSchedule.php';
+            $schedule = new ilBookingSchedule($id);
+        }
+        
+        $av = new ilFormSectionHeaderGUI();
+        $av->setTitle($lng->txt("obj_activation_list_gui"));
+        $form_gui->addItem($av);
+                
+        // #18221
+        $lng->loadLanguageModule('rep');
+        
+        $from = new ilDateTimeInputGUI($lng->txt("rep_activation_limited_start"), "from");
+        $from->setShowTime(true);
+        $form_gui->addItem($from);
+        
+        $to = new ilDateTimeInputGUI($lng->txt("rep_activation_limited_end"), "to");
+        $to->setShowTime(true);
+        $form_gui->addItem($to);
+    
+        if ($a_mode == "edit") {
+            $form_gui->setTitle($lng->txt("book_edit_schedule"));
+
+            $item = new ilHiddenInputGUI('schedule_id');
+            $item->setValue($id);
+            $form_gui->addItem($item);
+
+            include_once 'Modules/BookingManager/classes/class.ilBookingSchedule.php';
+            $schedule = new ilBookingSchedule($id);
+            $title->setValue($schedule->getTitle());
+            $from->setDate($schedule->getAvailabilityFrom());
+            $to->setDate($schedule->getAvailabilityTo());
+            
+            if ($schedule->getDeadline() == 0) {
+                $deadline_opts->setValue("slot_start");
+            } elseif ($schedule->getDeadline() > 0) {
+                $deadline->setValue($schedule->getDeadline());
+                $deadline_opts->setValue("hours");
+            } else {
+                $deadline->setValue(0);
+                $deadline_opts->setValue("slot_end");
+            }
+
+            /*
+            if($schedule->getRaster())
+            {
+                $type->setValue("flexible");
+                $raster->setValue($schedule->getRaster());
+                $rent_min->setValue($schedule->getMinRental());
+                $rent_max->setValue($schedule->getMaxRental());
+                $break->setValue($schedule->getAutoBreak());
+            }
+            else
+            {
+                $type->setValue("fix");
+            }
+            */
+
+            $definition->setValue($schedule->getDefinitionBySlots());
+
+            $form_gui->addCommandButton("update", $lng->txt("save"));
+        } else {
+            $form_gui->setTitle($lng->txt("book_add_schedule"));
+            $form_gui->addCommandButton("save", $lng->txt("save"));
+            $form_gui->addCommandButton("render", $lng->txt("cancel"));
+        }
+        $form_gui->setFormAction($ilCtrl->getFormAction($this));
+
+        return $form_gui;
+    }
 
-?>
\ No newline at end of file
+    /**
+     * Create new dataset
+     */
+    public function save()
+    {
+        $tpl = $this->tpl;
+        $lng = $this->lng;
+
+        $form = $this->initForm();
+        if ($form->checkInput()) {
+            include_once 'Modules/BookingManager/classes/class.ilBookingSchedule.php';
+            $obj = new ilBookingSchedule;
+            $this->formToObject($form, $obj);
+            $obj->save();
+
+            ilUtil::sendSuccess($lng->txt("book_schedule_added"));
+            $this->render();
+        } else {
+            $form->setValuesByPost();
+            $this->setDefinitionFromPost($form);
+            $tpl->setContent($form->getHTML());
+        }
+    }
+
+    /**
+     * Update dataset
+     */
+    public function update()
+    {
+        $tpl = $this->tpl;
+        $lng = $this->lng;
+
+        $form = $this->initForm('edit', $this->schedule_id);
+        if ($form->checkInput()) {
+            include_once 'Modules/BookingManager/classes/class.ilBookingSchedule.php';
+            $obj = new ilBookingSchedule($this->schedule_id);
+            $this->formToObject($form, $obj);
+            $obj->update();
+
+            ilUtil::sendSuccess($lng->txt("book_schedule_updated"));
+            $this->render();
+        } else {
+            $form->setValuesByPost();
+            $this->setDefinitionFromPost($form);
+            $tpl->setContent($form->getHTML());
+        }
+    }
+
+    /**
+     * Reload definition values from post data
+     *
+     * @param ilPropertyFormGUI $form
+     */
+    protected function setDefinitionFromPost(ilPropertyFormGUI $form)
+    {
+        $days = $form->getInput("days");
+        if ($days) {
+            $days_group = $form->getItemByPostVar("days");
+            foreach ($days_group->getOptions() as $option) {
+                $days_fields[$option->getValue()] = $option;
+            }
+            
+            foreach ($days as $day) {
+                $slot = $form->getInput($day . "_slot");
+                $subs = $days_fields[$day]->getSubItems();
+                if ($slot[0]) {
+                    $subs[0]->setValue($slot[0]);
+                }
+                if ($slot[1]) {
+                    $subs[1]->setValue($slot[1]);
+                }
+            }
+        }
+    }
+
+    /**
+     * Convert incoming form data to schedule object
+     * @param	object	$form
+     * @param	object	$schedule
+     */
+    protected function formToObject($form, $schedule)
+    {
+        $ilObjDataCache = $this->obj_data_cache;
+        
+        $schedule->setTitle($form->getInput("title"));
+        $schedule->setPoolId($ilObjDataCache->lookupObjId($this->ref_id));
+        
+        $from = $form->getItemByPostVar("from");
+        $schedule->setAvailabilityFrom($from->getDate());
+        
+        $to = $form->getItemByPostVar("to");
+        $schedule->setAvailabilityTo($to->getDate());
+        
+        switch ($form->getInput("deadline_opts")) {
+            case "slot_start":
+                $schedule->setDeadline(0);
+                break;
+            
+            case "hours":
+                $schedule->setDeadline($form->getInput("deadline"));
+                break;
+            
+            case "slot_end":
+                $schedule->setDeadline(-1);
+                break;
+        }
+
+        /*
+        if($form->getInput("type") == "flexible")
+        {
+            $schedule->setRaster($form->getInput("raster"));
+            $schedule->setMinRental($form->getInput("rent_min"));
+            $schedule->setMaxRental($form->getInput("rent_max"));
+            $schedule->setAutoBreak($form->getInput("break"));
+        }
+        else
+        {
+            $schedule->setRaster(NULL);
+            $schedule->setMinRental(NULL);
+            $schedule->setMaxRental(NULL);
+            $schedule->setAutoBreak(NULL);
+        }
+        */
+        
+        $schedule->setDefinitionBySlots(ilScheduleInputGUI::getPostData("days"));
+    }
+
+    /**
+     * Confirm delete
+     */
+    public function confirmDelete()
+    {
+        $ilCtrl = $this->ctrl;
+        $lng = $this->lng;
+        $tpl = $this->tpl;
+        $ilTabs = $this->tabs;
+        $ilHelp = $this->help;
+
+        $ilHelp->setSubScreenId("delete");
+
+
+        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.ilBookingSchedule.php';
+        $type = new ilBookingSchedule($this->schedule_id);
+        $conf->addItem('schedule_id', $this->schedule_id, $type->getTitle());
+        $conf->setConfirm($lng->txt('delete'), 'delete');
+        $conf->setCancel($lng->txt('cancel'), 'render');
+
+        $tpl->setContent($conf->getHTML());
+    }
+
+    /**
+     * Delete schedule
+     */
+    public function delete()
+    {
+        $ilCtrl = $this->ctrl;
+        $lng = $this->lng;
+
+        include_once 'Modules/BookingManager/classes/class.ilBookingSchedule.php';
+        $obj = new ilBookingSchedule($this->schedule_id);
+        $obj->delete();
+
+        ilUtil::sendSuccess($lng->txt('book_schedule_deleted'), true);
+        $ilCtrl->redirect($this, 'render');
+    }
+}
diff --git a/Modules/BookingManager/classes/class.ilBookingSchedulesTableGUI.php b/Modules/BookingManager/classes/class.ilBookingSchedulesTableGUI.php
index 9645b7d68fe834d721ccd1ec2792d029e0a6fd32..a7064eb48988c7ac5c7b337fa4452ef29aff7129 100644
--- a/Modules/BookingManager/classes/class.ilBookingSchedulesTableGUI.php
+++ b/Modules/BookingManager/classes/class.ilBookingSchedulesTableGUI.php
@@ -6,112 +6,106 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php");
 /**
  * List booking schedules (for booking pool)
  *
- * @author Jörg Lützenkirchen  
+ * @author Jörg Lützenkirchen 
  * @version $Id$
  *
  * @ingroup ModulesBookingManager
  */
 class ilBookingSchedulesTableGUI extends ilTable2GUI
 {
-	/**
-	 * @var ilAccessHandler
-	 */
-	protected $access;
+    /**
+     * @var ilAccessHandler
+     */
+    protected $access;
 
-	/**
-	 * @var ilObjectDataCache
-	 */
-	protected $obj_data_cache;
+    /**
+     * @var ilObjectDataCache
+     */
+    protected $obj_data_cache;
 
-	/**
-	 * Constructor
-	 * @param	object	$a_parent_obj
-	 * @param	string	$a_parent_cmd
-	 * @param	int		$a_ref_id
-	 */
-	function __construct($a_parent_obj, $a_parent_cmd, $a_ref_id)
-	{
-		global $DIC;
+    /**
+     * Constructor
+     * @param	object	$a_parent_obj
+     * @param	string	$a_parent_cmd
+     * @param	int		$a_ref_id
+     */
+    public function __construct($a_parent_obj, $a_parent_cmd, $a_ref_id)
+    {
+        global $DIC;
 
-		$this->ctrl = $DIC->ctrl();
-		$this->lng = $DIC->language();
-		$this->access = $DIC->access();
-		$this->obj_data_cache = $DIC["ilObjDataCache"];
-		$ilCtrl = $DIC->ctrl();
-		$lng = $DIC->language();
-		$ilAccess = $DIC->access();
-		$lng = $DIC->language();
-		$ilObjDataCache = $DIC["ilObjDataCache"];
+        $this->ctrl = $DIC->ctrl();
+        $this->lng = $DIC->language();
+        $this->access = $DIC->access();
+        $this->obj_data_cache = $DIC["ilObjDataCache"];
+        $ilCtrl = $DIC->ctrl();
+        $lng = $DIC->language();
+        $ilAccess = $DIC->access();
+        $lng = $DIC->language();
+        $ilObjDataCache = $DIC["ilObjDataCache"];
 
-		$this->ref_id = $a_ref_id;
-		$this->setId("bksd");
+        $this->ref_id = $a_ref_id;
+        $this->setId("bksd");
 
-		parent::__construct($a_parent_obj, $a_parent_cmd);
-		
-		$this->addColumn($this->lng->txt("title"), "title");
-		$this->addColumn($this->lng->txt("book_is_used"));
-		$this->addColumn($this->lng->txt("actions"));
+        parent::__construct($a_parent_obj, $a_parent_cmd);
+        
+        $this->addColumn($this->lng->txt("title"), "title");
+        $this->addColumn($this->lng->txt("book_is_used"));
+        $this->addColumn($this->lng->txt("actions"));
 
-		$this->setEnableHeader(true);
-		$this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd));
-		$this->setRowTemplate("tpl.booking_schedule_row.html", "Modules/BookingManager");
-	
-		$this->getItems($ilObjDataCache->lookupObjId($this->ref_id));
-	}
+        $this->setEnableHeader(true);
+        $this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd));
+        $this->setRowTemplate("tpl.booking_schedule_row.html", "Modules/BookingManager");
+    
+        $this->getItems($ilObjDataCache->lookupObjId($this->ref_id));
+    }
 
-	/**
-	 * Build summary item rows for given object and filter(s)
-	 *
-	 * @param	int	$a_pool_id (aka parent obj id)
-	 */
-	function getItems($a_pool_id)
-	{
-		include_once 'Modules/BookingManager/classes/class.ilBookingSchedule.php';
-		$data = ilBookingSchedule::getList($a_pool_id);
-		
-		$this->setMaxCount(sizeof($data));
-		$this->setData($data);
-	}
+    /**
+     * Build summary item rows for given object and filter(s)
+     *
+     * @param	int	$a_pool_id (aka parent obj id)
+     */
+    public function getItems($a_pool_id)
+    {
+        include_once 'Modules/BookingManager/classes/class.ilBookingSchedule.php';
+        $data = ilBookingSchedule::getList($a_pool_id);
+        
+        $this->setMaxCount(sizeof($data));
+        $this->setData($data);
+    }
 
-	/**
-	 * Fill table row
-	 * @param	array	$a_set
-	 */
-	protected function fillRow($a_set)
-	{
-		$lng = $this->lng;
-		$ilAccess = $this->access;
-		$ilCtrl = $this->ctrl;
+    /**
+     * Fill table row
+     * @param	array	$a_set
+     */
+    protected function fillRow($a_set)
+    {
+        $lng = $this->lng;
+        $ilAccess = $this->access;
+        $ilCtrl = $this->ctrl;
 
-	    $this->tpl->setVariable("TXT_TITLE", $a_set["title"]);
+        $this->tpl->setVariable("TXT_TITLE", $a_set["title"]);
 
-		if($a_set["is_used"])
-		{
-			$this->tpl->setVariable("TXT_IS_USED", $lng->txt("yes"));
-		}
-		else
-		{
-			$this->tpl->setVariable("TXT_IS_USED", $lng->txt("no"));
-		}
+        if ($a_set["is_used"]) {
+            $this->tpl->setVariable("TXT_IS_USED", $lng->txt("yes"));
+        } else {
+            $this->tpl->setVariable("TXT_IS_USED", $lng->txt("no"));
+        }
 
-		$ilCtrl->setParameter($this->parent_obj, 'schedule_id', $a_set['booking_schedule_id']);
+        $ilCtrl->setParameter($this->parent_obj, 'schedule_id', $a_set['booking_schedule_id']);
 
-		include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php");
-		$alist = new ilAdvancedSelectionListGUI();
-		$alist->setId($a_set['booking_schedule_id']);
-		$alist->setListTitle($lng->txt("actions"));
-	
-		if ($ilAccess->checkAccess('write', '', $this->ref_id))
-		{
-			$alist->addItem($lng->txt('edit'), 'edit', $ilCtrl->getLinkTarget($this->parent_obj, 'edit')); // #12306
-			
-			if(!$a_set["is_used"])
-			{
-				$alist->addItem($lng->txt('delete'), 'delete', $ilCtrl->getLinkTarget($this->parent_obj, 'confirmDelete'));
-			}		
-		}
+        include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php");
+        $alist = new ilAdvancedSelectionListGUI();
+        $alist->setId($a_set['booking_schedule_id']);
+        $alist->setListTitle($lng->txt("actions"));
+    
+        if ($ilAccess->checkAccess('write', '', $this->ref_id)) {
+            $alist->addItem($lng->txt('edit'), 'edit', $ilCtrl->getLinkTarget($this->parent_obj, 'edit')); // #12306
+            
+            if (!$a_set["is_used"]) {
+                $alist->addItem($lng->txt('delete'), 'delete', $ilCtrl->getLinkTarget($this->parent_obj, 'confirmDelete'));
+            }
+        }
 
-		$this->tpl->setVariable("LAYER", $alist->getHTML());
-	}
+        $this->tpl->setVariable("LAYER", $alist->getHTML());
+    }
 }
-?>
diff --git a/Modules/BookingManager/classes/class.ilFSStorageBooking.php b/Modules/BookingManager/classes/class.ilFSStorageBooking.php
index ae1c3acd3e670b775e8b50db914b090588748004..12cca64f20f75a5a0a9245997faa1477114fe8b9 100644
--- a/Modules/BookingManager/classes/class.ilFSStorageBooking.php
+++ b/Modules/BookingManager/classes/class.ilFSStorageBooking.php
@@ -1,50 +1,48 @@
-
-* @version $Id$
-* 
-* @ingroup ModulesBookingManager
-*/
-class ilFSStorageBooking extends ilFileSystemStorage
-{
-	public function __construct($a_container_id = 0)
-	{
-		parent::__construct(self::STORAGE_WEB, true, $a_container_id);
-	}
-	
-	protected function getPathPostfix()
-	{
-	 	return 'book';
-	}
-	
-	protected function getPathPrefix()
-	{
-	 	return 'ilBookingManager';
-	}
-}
-
-?>
\ No newline at end of file
+
+* @version $Id$
+*
+* @ingroup ModulesBookingManager
+*/
+class ilFSStorageBooking extends ilFileSystemStorage
+{
+    public function __construct($a_container_id = 0)
+    {
+        parent::__construct(self::STORAGE_WEB, true, $a_container_id);
+    }
+    
+    protected function getPathPostfix()
+    {
+        return 'book';
+    }
+    
+    protected function getPathPrefix()
+    {
+        return 'ilBookingManager';
+    }
+}
diff --git a/Modules/BookingManager/classes/class.ilObjBookingPool.php b/Modules/BookingManager/classes/class.ilObjBookingPool.php
index 4b6b0eaa09e803247b539d431d0147804df31e0f..ce08830c9d0402329f8f0db9a5a7c9ce6fa8bce6 100644
--- a/Modules/BookingManager/classes/class.ilObjBookingPool.php
+++ b/Modules/BookingManager/classes/class.ilObjBookingPool.php
@@ -5,439 +5,426 @@ require_once "./Services/Object/classes/class.ilObject.php";
 
 /**
 * Class ilObjBookingPool
-* 
+*
 * @author Jörg Lützenkirchen 
 * @version $Id$
 *
 */
 class ilObjBookingPool extends ilObject
 {
-	//offline default should be true
-	protected $offline = true;			// [bool]
-	protected $public_log;		// [bool]
-	protected $schedule_type;	// [int]
-	protected $overall_limit;   // [int]
-	protected $reservation_period; // [int]
-	protected $reminder_status = 0; // [int]
-	protected $reminder_day = 1; // [int]
-
-	const TYPE_FIX_SCHEDULE = 1;
-	const TYPE_NO_SCHEDULE = 2;
-	
-	/**
-	* Constructor
-	* @param	int		$a_id					reference_id or object_id
-	* @param	bool	$a_call_by_reference	treat the id as reference_id (true) or object_id (false)
-	*/
-	function __construct($a_id = 0,$a_call_by_reference = true)
-	{
-		global $DIC;
-
-		$this->db = $DIC->database();
-		$this->type = "book";
-		$this->setScheduleType(self::TYPE_FIX_SCHEDULE);
-		parent::__construct($a_id,$a_call_by_reference);
-	}
-	
-	/**
-	 * Parse properties for sql statements 
-	 */
-	protected function getDBFields()
-	{
-		$fields = array(
-			"schedule_type" => array("integer", $this->getScheduleType()),
-			"pool_offline" => array("integer", $this->isOffline()),
-			"public_log" => array("integer", $this->hasPublicLog()),		
-			"ovlimit" => array("integer", $this->getOverallLimit()),
-			"reminder_status" => array("integer", $this->getReminderStatus()),
-			"reminder_day" => array("integer", $this->getReminderDay()),
-			"rsv_filter_period" => array("integer", $this->getReservationFilterPeriod())
-		);
-		
-		return $fields;
-	}
-
-	/**
-	* create object
-	* @return	integer
-	*/
-	function create()
-	{
-		$ilDB = $this->db;
-		
-		$new_id = parent::create();
-		
-		$fields = $this->getDBFields();
-		$fields["booking_pool_id"] = array("integer", $new_id);
-
-		$ilDB->insert("booking_settings", $fields);
-
-		return $new_id;
-	}
-
-	/**
-	* update object data
-	* @return	boolean
-	*/
-	function update()
-	{
-		$ilDB = $this->db;
-		
-		if (!parent::update())
-		{			
-			return false;
-		}
-
-		// put here object specific stuff
-		if($this->getId())
-		{			
-			$ilDB->update("booking_settings", $this->getDBFields(),
-				array("booking_pool_id" => array("integer", $this->getId())));			
-		}
-
-		return true;
-	}
-
-	function read()
-	{
-		$ilDB = $this->db;
-		
-		parent::read();
-
-		// put here object specific stuff
-		if($this->getId())
-		{
-			$set = $ilDB->query('SELECT * FROM booking_settings'.
-				' WHERE booking_pool_id = '.$ilDB->quote($this->getId(), 'integer'));
-			$row = $ilDB->fetchAssoc($set);
-			$this->setOffline($row['pool_offline']);
-			$this->setPublicLog($row['public_log']);
-			$this->setScheduleType($row['schedule_type']);
-			$this->setOverallLimit($row['ovlimit']);
-			$this->setReminderStatus($row['reminder_status']);
-			$this->setReminderDay($row['reminder_day']);
-			$this->setReservationFilterPeriod($row['rsv_filter_period']);
-		}
-	}
-
-	/**
-	 * Get poos with reminders
-	 *
-	 * @return array[]
-	 */
-	public static function getPoolsWithReminders()
-	{
-		global $DIC;
-
-		$db = $DIC->database();
-		$pools = [];
-		$set = $db->queryF("SELECT * FROM booking_settings ".
-			" WHERE reminder_status = %s ".
-			" AND reminder_day > %s ".
-			" AND pool_offline = %s ",
-			array("integer","integer","integer"),
-			array(1,0,0)
-			);
-		while ($rec = $db->fetchAssoc($set))
-		{
-			$pools[] = $rec;
-		}
-		return $pools;
-	}
-
-	/**
-	 * Write last reminder timestamp
-	 *
-	 * @param int pool id
-	 * @param int timestamp
-	 */
-	static public function writeLastReminderTimestamp($a_obj_id, $a_ts)
-	{
-		global $DIC;
-		$db = $DIC->database();
-		$db->update("booking_settings", array(
-				"last_remind_ts" => array("integer", $a_ts)
-			), array(	// where
-				"booking_pool_id" => array("integer", $a_obj_id)
-			));
-	}
-
-
-	/**
-	* delete object and all related data	
-	* @return	boolean	true if all object data were removed; false if only a references were removed
-	*/
-	function delete()
-	{
-		$ilDB = $this->db;
-
-		$id = $this->getId();
-
-		// always call parent delete function first!!
-		if (!parent::delete())
-		{
-			return false;
-		}
-
-		// put here your module specific stuff
-		
-		$ilDB->manipulate('DELETE FROM booking_settings'.
-				' WHERE booking_pool_id = '.$ilDB->quote($id, 'integer'));
-
-		$ilDB->manipulate('DELETE FROM booking_schedule'.
-				' WHERE pool_id = '.$ilDB->quote($id, 'integer'));
-		
-		$objects = array();
-		$set = $ilDB->query('SELECT booking_object_id FROM booking_object'.
-			' WHERE pool_id = '.$ilDB->quote($id, 'integer'));
-		while($row = $ilDB->fetchAssoc($set))
-		{
-			$objects[] = $row['booking_object_id'];
-		}
-
-		if(sizeof($objects))
-		{
-			$ilDB->manipulate('DELETE FROM booking_reservation'.
-					' WHERE '.$ilDB->in('object_id', $objects, '', 'integer'));
-		}
-
-		$ilDB->manipulate('DELETE FROM booking_object'.
-			' WHERE pool_id = '.$ilDB->quote($id, 'integer'));
-
-		return true;
-	}
-	
-	public function cloneObject($a_target_id,$a_copy_id = 0, $a_omit_tree = false)
-	{
-		$new_obj = parent::cloneObject($a_target_id, $a_copy_id, $a_omit_tree);
-
-		//copy online status if object is not the root copy object
-		$cp_options = ilCopyWizardOptions::_getInstance($a_copy_id);
-
-		if(!$cp_options->isRootNode($this->getRefId()))
-		{
-			$new_obj->setOffline($this->isOffline());
-		}
-
-		$new_obj->setScheduleType($this->getScheduleType());
-		$new_obj->setPublicLog($this->hasPublicLog());
-		$new_obj->setOverallLimit($this->getOverallLimit());
-		$new_obj->setReminderStatus($this->getReminderStatus());
-		$new_obj->setReminderDay($this->getReminderDay());
-
-		$smap = null;
-		if($this->getScheduleType() == self::TYPE_FIX_SCHEDULE)
-		{			
-			// schedules
-			include_once "Modules/BookingManager/classes/class.ilBookingSchedule.php";
-			foreach(ilBookingSchedule::getList($this->getId()) as $item)
-			{
-				$schedule = new ilBookingSchedule($item["booking_schedule_id"]);
-				$smap[$item["booking_schedule_id"]] = $schedule->doClone($new_obj->getId());				
-			}						
-		}
-		
-		// objects
-		include_once "Modules/BookingManager/classes/class.ilBookingObject.php";
-		foreach(ilBookingObject::getList($this->getId()) as $item)
-		{
-			$bobj = new ilBookingObject($item["booking_object_id"]);
-			$bobj->doClone($new_obj->getId(), $smap);
-		}		
-		
-		$new_obj->update();
-		
-		return $new_obj;
-	}
-	
-	/**
-	 * Toggle offline property
-	 * @param bool $a_value
-	 */
-	function setOffline($a_value = true)
+    //offline default should be true
+    protected $offline = true;			// [bool]
+    protected $public_log;		// [bool]
+    protected $schedule_type;	// [int]
+    protected $overall_limit;   // [int]
+    protected $reservation_period; // [int]
+    protected $reminder_status = 0; // [int]
+    protected $reminder_day = 1; // [int]
+
+    const TYPE_FIX_SCHEDULE = 1;
+    const TYPE_NO_SCHEDULE = 2;
+    
+    /**
+    * Constructor
+    * @param	int		$a_id					reference_id or object_id
+    * @param	bool	$a_call_by_reference	treat the id as reference_id (true) or object_id (false)
+    */
+    public function __construct($a_id = 0, $a_call_by_reference = true)
+    {
+        global $DIC;
+
+        $this->db = $DIC->database();
+        $this->type = "book";
+        $this->setScheduleType(self::TYPE_FIX_SCHEDULE);
+        parent::__construct($a_id, $a_call_by_reference);
+    }
+    
+    /**
+     * Parse properties for sql statements
+     */
+    protected function getDBFields()
+    {
+        $fields = array(
+            "schedule_type" => array("integer", $this->getScheduleType()),
+            "pool_offline" => array("integer", $this->isOffline()),
+            "public_log" => array("integer", $this->hasPublicLog()),
+            "ovlimit" => array("integer", $this->getOverallLimit()),
+            "reminder_status" => array("integer", $this->getReminderStatus()),
+            "reminder_day" => array("integer", $this->getReminderDay()),
+            "rsv_filter_period" => array("integer", $this->getReservationFilterPeriod())
+        );
+        
+        return $fields;
+    }
+
+    /**
+    * create object
+    * @return	integer
+    */
+    public function create()
+    {
+        $ilDB = $this->db;
+        
+        $new_id = parent::create();
+        
+        $fields = $this->getDBFields();
+        $fields["booking_pool_id"] = array("integer", $new_id);
+
+        $ilDB->insert("booking_settings", $fields);
+
+        return $new_id;
+    }
+
+    /**
+    * update object data
+    * @return	boolean
+    */
+    public function update()
+    {
+        $ilDB = $this->db;
+        
+        if (!parent::update()) {
+            return false;
+        }
+
+        // put here object specific stuff
+        if ($this->getId()) {
+            $ilDB->update(
+                "booking_settings",
+                $this->getDBFields(),
+                array("booking_pool_id" => array("integer", $this->getId()))
+            );
+        }
+
+        return true;
+    }
+
+    public function read()
+    {
+        $ilDB = $this->db;
+        
+        parent::read();
+
+        // put here object specific stuff
+        if ($this->getId()) {
+            $set = $ilDB->query('SELECT * FROM booking_settings' .
+                ' WHERE booking_pool_id = ' . $ilDB->quote($this->getId(), 'integer'));
+            $row = $ilDB->fetchAssoc($set);
+            $this->setOffline($row['pool_offline']);
+            $this->setPublicLog($row['public_log']);
+            $this->setScheduleType($row['schedule_type']);
+            $this->setOverallLimit($row['ovlimit']);
+            $this->setReminderStatus($row['reminder_status']);
+            $this->setReminderDay($row['reminder_day']);
+            $this->setReservationFilterPeriod($row['rsv_filter_period']);
+        }
+    }
+
+    /**
+     * Get poos with reminders
+     *
+     * @return array[]
+     */
+    public static function getPoolsWithReminders()
+    {
+        global $DIC;
+
+        $db = $DIC->database();
+        $pools = [];
+        $set = $db->queryF(
+            "SELECT * FROM booking_settings " .
+            " WHERE reminder_status = %s " .
+            " AND reminder_day > %s " .
+            " AND pool_offline = %s ",
+            array("integer","integer","integer"),
+            array(1,0,0)
+            );
+        while ($rec = $db->fetchAssoc($set)) {
+            $pools[] = $rec;
+        }
+        return $pools;
+    }
+
+    /**
+     * Write last reminder timestamp
+     *
+     * @param int pool id
+     * @param int timestamp
+     */
+    public static function writeLastReminderTimestamp($a_obj_id, $a_ts)
+    {
+        global $DIC;
+        $db = $DIC->database();
+        $db->update("booking_settings", array(
+                "last_remind_ts" => array("integer", $a_ts)
+            ), array(	// where
+                "booking_pool_id" => array("integer", $a_obj_id)
+            ));
+    }
+
+
+    /**
+    * delete object and all related data
+    * @return	boolean	true if all object data were removed; false if only a references were removed
+    */
+    public function delete()
+    {
+        $ilDB = $this->db;
+
+        $id = $this->getId();
+
+        // always call parent delete function first!!
+        if (!parent::delete()) {
+            return false;
+        }
+
+        // put here your module specific stuff
+        
+        $ilDB->manipulate('DELETE FROM booking_settings' .
+                ' WHERE booking_pool_id = ' . $ilDB->quote($id, 'integer'));
+
+        $ilDB->manipulate('DELETE FROM booking_schedule' .
+                ' WHERE pool_id = ' . $ilDB->quote($id, 'integer'));
+        
+        $objects = array();
+        $set = $ilDB->query('SELECT booking_object_id FROM booking_object' .
+            ' WHERE pool_id = ' . $ilDB->quote($id, 'integer'));
+        while ($row = $ilDB->fetchAssoc($set)) {
+            $objects[] = $row['booking_object_id'];
+        }
+
+        if (sizeof($objects)) {
+            $ilDB->manipulate('DELETE FROM booking_reservation' .
+                    ' WHERE ' . $ilDB->in('object_id', $objects, '', 'integer'));
+        }
+
+        $ilDB->manipulate('DELETE FROM booking_object' .
+            ' WHERE pool_id = ' . $ilDB->quote($id, 'integer'));
+
+        return true;
+    }
+    
+    public function cloneObject($a_target_id, $a_copy_id = 0, $a_omit_tree = false)
+    {
+        $new_obj = parent::cloneObject($a_target_id, $a_copy_id, $a_omit_tree);
+
+        //copy online status if object is not the root copy object
+        $cp_options = ilCopyWizardOptions::_getInstance($a_copy_id);
+
+        if (!$cp_options->isRootNode($this->getRefId())) {
+            $new_obj->setOffline($this->isOffline());
+        }
+
+        $new_obj->setScheduleType($this->getScheduleType());
+        $new_obj->setPublicLog($this->hasPublicLog());
+        $new_obj->setOverallLimit($this->getOverallLimit());
+        $new_obj->setReminderStatus($this->getReminderStatus());
+        $new_obj->setReminderDay($this->getReminderDay());
+
+        $smap = null;
+        if ($this->getScheduleType() == self::TYPE_FIX_SCHEDULE) {
+            // schedules
+            include_once "Modules/BookingManager/classes/class.ilBookingSchedule.php";
+            foreach (ilBookingSchedule::getList($this->getId()) as $item) {
+                $schedule = new ilBookingSchedule($item["booking_schedule_id"]);
+                $smap[$item["booking_schedule_id"]] = $schedule->doClone($new_obj->getId());
+            }
+        }
+        
+        // objects
+        include_once "Modules/BookingManager/classes/class.ilBookingObject.php";
+        foreach (ilBookingObject::getList($this->getId()) as $item) {
+            $bobj = new ilBookingObject($item["booking_object_id"]);
+            $bobj->doClone($new_obj->getId(), $smap);
+        }
+        
+        $new_obj->update();
+        
+        return $new_obj;
+    }
+    
+    /**
+     * Toggle offline property
+     * @param bool $a_value
+     */
+    public function setOffline($a_value = true)
+    {
+        $this->offline = (bool) $a_value;
+    }
+
+    /**
+     * Get offline property
+     * @return bool
+     */
+    public function isOffline()
+    {
+        return (bool) $this->offline;
+    }
+
+    /**
+     * Toggle public log property
+     * @param bool $a_value
+     */
+    public function setPublicLog($a_value = true)
     {
-		$this->offline = (bool)$a_value;
-	}
-
-	/**
-	 * Get offline property
-	 * @return bool
-	 */
-	function isOffline()
-	{
-		return (bool)$this->offline;
-	}
-
-	/**
-	 * Toggle public log property
-	 * @param bool $a_value
-	 */
-	function setPublicLog($a_value = true)
+        $this->public_log = (bool) $a_value;
+    }
+
+    /**
+     * Get public log property
+     * @return bool
+     */
+    public function hasPublicLog()
     {
-		$this->public_log = (bool)$a_value;
-	}
-
-	/**
-	 * Get public log property
-	 * @return bool
-	 */
-	function hasPublicLog()
-	{
-		return (bool)$this->public_log;
-	}
-
-	/**
-	 * Set schedule type
-	 * @param int $a_value
-	 */
-	function setScheduleType($a_value)
+        return (bool) $this->public_log;
+    }
+
+    /**
+     * Set schedule type
+     * @param int $a_value
+     */
+    public function setScheduleType($a_value)
     {
-		$this->schedule_type = (int)$a_value;
-	}
-
-	/**
-	 * Get schedule type
-	 * @return int
-	 */
-	function getScheduleType()
-	{
-		return $this->schedule_type;
-	}
-	
-	/**
-	 * Set reminder status
-	 *
-	 * @param int $a_val reminder status	
-	 */
-	function setReminderStatus($a_val)
-	{
-		$this->reminder_status = $a_val;
-	}
-	
-	/**
-	 * Get reminder status
-	 *
-	 * @return int reminder status
-	 */
-	function getReminderStatus()
-	{
-		return $this->reminder_status;
-	}
-
-	/**
-	 * Set reminder day
-	 *
-	 * @param int $a_val reminder day
-	 */
-	function setReminderDay($a_val)
-	{
-		$this->reminder_day = $a_val;
-	}
-
-	/**
-	 * Get reminder day
-	 *
-	 * @return int reminder day
-	 */
-	function getReminderDay()
-	{
-		return $this->reminder_day;
-	}
-	
-	/**
-	 * Check object status
-	 * 
-	 * @param int $a_obj_id
-	 * @return boolean
-	 */
-	public static function _lookupOnline($a_obj_id)
-	{
-		global $DIC;
-
-		$ilDB = $DIC->database();
-		
-		$set = $ilDB->query("SELECT pool_offline".
-			" FROM booking_settings".
-			" WHERE booking_pool_id = ".$ilDB->quote($a_obj_id, "integer"));
-		$row = $ilDB->fetchAssoc($set);				
-		return !(bool)$row["pool_offline"];
-	}
-	
-	/**
-	 * Set overall / global booking limit
-	 * 
-	 * @param int $a_value
-	 */
-	public function setOverallLimit($a_value = null)
-	{
-		if($a_value !== null)
-		{
-			$a_value = (int)$a_value;
-		}
-		$this->overall_limit = $a_value;
-	}
-	
-	/**
-	 * Get overall / global booking limit
-	 * 
-	 * @return int $a_value
-	 */
-	public function getOverallLimit()
-	{
-		return $this->overall_limit;
-	}
-	
-	/**
-	 * Set reservation filter period default
-	 * 
-	 * @param int $a_value
-	 */
-	public function setReservationFilterPeriod($a_value = null)
-	{		
-		if($a_value !== null)
-		{
-			$a_value = (int)$a_value;
-		}			
-		$this->reservation_period = $a_value;
-	}
-	
-	/**
-	 * Get reservation filter period default
-	 * 
-	 * @return int
-	 */
-	public function getReservationFilterPeriod()
-	{
-		return $this->reservation_period;
-	}
-	
-	
-	//
-	// advanced metadata
-	// 
-	
-	public static function getAdvancedMDFields($a_ref_id)
-	{	
-		$fields = array();
-		
-		include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecord.php');
-		$recs = ilAdvancedMDRecord::_getSelectedRecordsByObject("book", $a_ref_id, "bobj");
-
-		foreach($recs as $record_obj)
-		{
-			include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDFieldDefinition.php');
-			foreach (ilAdvancedMDFieldDefinition::getInstancesByRecordId($record_obj->getRecordId()) as $def)
-			{
-				$fields[$def->getFieldId()] = array(
-					"id" => $def->getFieldId(),
-					"title" => $def->getTitle(),
-					"type" => $def->getType()
-				);
-			}
-		}
-
-		return $fields;
-	}
+        $this->schedule_type = (int) $a_value;
+    }
+
+    /**
+     * Get schedule type
+     * @return int
+     */
+    public function getScheduleType()
+    {
+        return $this->schedule_type;
+    }
+    
+    /**
+     * Set reminder status
+     *
+     * @param int $a_val reminder status
+     */
+    public function setReminderStatus($a_val)
+    {
+        $this->reminder_status = $a_val;
+    }
+    
+    /**
+     * Get reminder status
+     *
+     * @return int reminder status
+     */
+    public function getReminderStatus()
+    {
+        return $this->reminder_status;
+    }
+
+    /**
+     * Set reminder day
+     *
+     * @param int $a_val reminder day
+     */
+    public function setReminderDay($a_val)
+    {
+        $this->reminder_day = $a_val;
+    }
+
+    /**
+     * Get reminder day
+     *
+     * @return int reminder day
+     */
+    public function getReminderDay()
+    {
+        return $this->reminder_day;
+    }
+    
+    /**
+     * Check object status
+     *
+     * @param int $a_obj_id
+     * @return boolean
+     */
+    public static function _lookupOnline($a_obj_id)
+    {
+        global $DIC;
+
+        $ilDB = $DIC->database();
+        
+        $set = $ilDB->query("SELECT pool_offline" .
+            " FROM booking_settings" .
+            " WHERE booking_pool_id = " . $ilDB->quote($a_obj_id, "integer"));
+        $row = $ilDB->fetchAssoc($set);
+        return !(bool) $row["pool_offline"];
+    }
+    
+    /**
+     * Set overall / global booking limit
+     *
+     * @param int $a_value
+     */
+    public function setOverallLimit($a_value = null)
+    {
+        if ($a_value !== null) {
+            $a_value = (int) $a_value;
+        }
+        $this->overall_limit = $a_value;
+    }
+    
+    /**
+     * Get overall / global booking limit
+     *
+     * @return int $a_value
+     */
+    public function getOverallLimit()
+    {
+        return $this->overall_limit;
+    }
+    
+    /**
+     * Set reservation filter period default
+     *
+     * @param int $a_value
+     */
+    public function setReservationFilterPeriod($a_value = null)
+    {
+        if ($a_value !== null) {
+            $a_value = (int) $a_value;
+        }
+        $this->reservation_period = $a_value;
+    }
+    
+    /**
+     * Get reservation filter period default
+     *
+     * @return int
+     */
+    public function getReservationFilterPeriod()
+    {
+        return $this->reservation_period;
+    }
+    
+    
+    //
+    // advanced metadata
+    //
+    
+    public static function getAdvancedMDFields($a_ref_id)
+    {
+        $fields = array();
+        
+        include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecord.php');
+        $recs = ilAdvancedMDRecord::_getSelectedRecordsByObject("book", $a_ref_id, "bobj");
+
+        foreach ($recs as $record_obj) {
+            include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDFieldDefinition.php');
+            foreach (ilAdvancedMDFieldDefinition::getInstancesByRecordId($record_obj->getRecordId()) as $def) {
+                $fields[$def->getFieldId()] = array(
+                    "id" => $def->getFieldId(),
+                    "title" => $def->getTitle(),
+                    "type" => $def->getType()
+                );
+            }
+        }
+
+        return $fields;
+    }
 }
-
-?>
\ No newline at end of file
diff --git a/Modules/BookingManager/classes/class.ilObjBookingPoolAccess.php b/Modules/BookingManager/classes/class.ilObjBookingPoolAccess.php
index 477fc46b80f3398dabe8786ce9679edb8cd90974..8993ae2caa5355f75e91c9af93c605b22ce28829 100644
--- a/Modules/BookingManager/classes/class.ilObjBookingPoolAccess.php
+++ b/Modules/BookingManager/classes/class.ilObjBookingPoolAccess.php
@@ -17,116 +17,110 @@ require_once('./Services/WebAccessChecker/interfaces/interface.ilWACCheckingClas
 */
 class ilObjBookingPoolAccess extends ilObjectAccess implements ilWACCheckingClass
 {
-	/**
-	 * @var ilObjUser
-	 */
-	protected $user;
-
-	/**
-	 * @var ilRbacSystem
-	 */
-	protected $rbacsystem;
-
-
-	/**
-	 * Constructor
-	 */
-	function __construct()
-	{
-		global $DIC;
-
-		$this->user = $DIC->user();
-		$this->rbacsystem = $DIC->rbac()->system();
-	}
-
-
-	/**
-	 * 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();
-		$commands[] = array("permission" => "read", "cmd" => "render", "lang_var" => "show", "default" => true);
-		$commands[] = array("permission" => "write", "cmd" => "render", "lang_var" => "edit_content");
-		$commands[] = array("permission" => "write", "cmd" => "edit", "lang_var" => "settings");
-		
-		return $commands;
-	}
-	
-	/**
-	* check whether goto script will succeed
-	*/
-	static function _checkGoto($a_target)
-	{
-		global $DIC;
-
-		$ilAccess = $DIC->access();
-		
-		$t_arr = explode("_", $a_target);
-
-		if ($t_arr[0] != "book" || ((int) $t_arr[1]) <= 0)
-		{
-			return false;
-		}
-
-		if ($ilAccess->checkAccess("read", "", $t_arr[1]))
-		{
-			return true;
-		}
-		return false;
-	}
-
-	function _checkAccess($a_cmd, $a_permission, $a_ref_id, $a_obj_id, $a_user_id = "")
-	{
-		$ilUser = $this->user;
-		$rbacsystem = $this->rbacsystem;
-
-		if ($a_user_id == "")
-		{
-			$a_user_id = $ilUser->getId();
-		}
-
-		// add no access info item and return false if access is not granted
-		// $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $a_text, $a_data = "");
-		//
-		// for all RBAC checks use checkAccessOfUser instead the normal checkAccess-method:
-		// $rbacsystem->checkAccessOfUser($a_user_id, $a_permission, $a_ref_id)
-
-		//TODO refactor this: first check if the object is online and then the permissions.
-		#22653
-		if(($a_permission == "visible" || $a_permission == "read") && !$rbacsystem->checkAccessOfUser($a_user_id,'write',$a_ref_id))
-		{
-			include_once "Modules/BookingManager/classes/class.ilObjBookingPool.php";
-			$pool = new ilObjBookingPool($a_ref_id);
-			if($pool->isOffline())
-			{
-				return false;
-			}
-		}
-
-		return true;
-	}
-
-	/**
-	 * @param ilWACPath $ilWACPath
-	 *
-	 * @return bool
-	 */
-	public function canBeDelivered(ilWACPath $ilWACPath) {
-
-		// we return always false, since the files in the file/ and post/ directoies
-		// are server by php (they could/should be moved to the data dir outside of the web doc root)
-		return false;
-	}
+    /**
+     * @var ilObjUser
+     */
+    protected $user;
+
+    /**
+     * @var ilRbacSystem
+     */
+    protected $rbacsystem;
+
+
+    /**
+     * Constructor
+     */
+    public function __construct()
+    {
+        global $DIC;
+
+        $this->user = $DIC->user();
+        $this->rbacsystem = $DIC->rbac()->system();
+    }
+
+
+    /**
+     * 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();
+        $commands[] = array("permission" => "read", "cmd" => "render", "lang_var" => "show", "default" => true);
+        $commands[] = array("permission" => "write", "cmd" => "render", "lang_var" => "edit_content");
+        $commands[] = array("permission" => "write", "cmd" => "edit", "lang_var" => "settings");
+        
+        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 ($t_arr[0] != "book" || ((int) $t_arr[1]) <= 0) {
+            return false;
+        }
+
+        if ($ilAccess->checkAccess("read", "", $t_arr[1])) {
+            return true;
+        }
+        return false;
+    }
+
+    public function _checkAccess($a_cmd, $a_permission, $a_ref_id, $a_obj_id, $a_user_id = "")
+    {
+        $ilUser = $this->user;
+        $rbacsystem = $this->rbacsystem;
+
+        if ($a_user_id == "") {
+            $a_user_id = $ilUser->getId();
+        }
+
+        // add no access info item and return false if access is not granted
+        // $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $a_text, $a_data = "");
+        //
+        // for all RBAC checks use checkAccessOfUser instead the normal checkAccess-method:
+        // $rbacsystem->checkAccessOfUser($a_user_id, $a_permission, $a_ref_id)
+
+        //TODO refactor this: first check if the object is online and then the permissions.
+        #22653
+        if (($a_permission == "visible" || $a_permission == "read") && !$rbacsystem->checkAccessOfUser($a_user_id, 'write', $a_ref_id)) {
+            include_once "Modules/BookingManager/classes/class.ilObjBookingPool.php";
+            $pool = new ilObjBookingPool($a_ref_id);
+            if ($pool->isOffline()) {
+                return false;
+            }
+        }
+
+        return true;
+    }
+
+    /**
+     * @param ilWACPath $ilWACPath
+     *
+     * @return bool
+     */
+    public function canBeDelivered(ilWACPath $ilWACPath)
+    {
+
+        // we return always false, since the files in the file/ and post/ directoies
+        // are server by php (they could/should be moved to the data dir outside of the web doc root)
+        return false;
+    }
 }
-
-?>
diff --git a/Modules/BookingManager/classes/class.ilObjBookingPoolGUI.php b/Modules/BookingManager/classes/class.ilObjBookingPoolGUI.php
index 0d3fd7a6aae13666384117634836942e9f8ab039..86e96b6b363d683ee96ae6b3395d25c25ac3e18a 100644
--- a/Modules/BookingManager/classes/class.ilObjBookingPoolGUI.php
+++ b/Modules/BookingManager/classes/class.ilObjBookingPoolGUI.php
@@ -8,7 +8,7 @@ require_once "./Services/Object/classes/class.ilObjectGUI.php";
 *
 * @author Jörg Lützenkirchen 
 * @version $Id$
-* 
+*
 * @ilCtrl_Calls ilObjBookingPoolGUI: ilPermissionGUI, ilBookingObjectGUI
 * @ilCtrl_Calls ilObjBookingPoolGUI: ilBookingScheduleGUI, ilInfoScreenGUI, ilPublicUserProfileGUI
 * @ilCtrl_Calls ilObjBookingPoolGUI: ilCommonActionDispatcherGUI, ilObjectCopyGUI, ilObjectMetaDataGUI
@@ -17,1987 +17,1851 @@ require_once "./Services/Object/classes/class.ilObjectGUI.php";
 */
 class ilObjBookingPoolGUI extends ilObjectGUI
 {
-	/**
-	 * @var ilTabsGUI
-	 */
-	protected $tabs;
-
-	/**
-	 * @var ilNavigationHistory
-	 */
-	protected $nav_history;
-
-	/**
-	 * @var ilHelpGUI
-	 */
-	protected $help;
-
-	/**
-	 * @var int
-	 */
-	protected $user_id_to_book;  // user who is getting the reservation
-
-	/**
-	 * @var int
-	 */
-	protected $user_id_assigner; // user who performs the reservation.(self/another)
-
-	/**
-	* Constructor
-	*
-	*/
-	function __construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output = true)
-	{
-		global $DIC;
-
-		$this->tpl = $DIC["tpl"];
-		$this->tabs = $DIC->tabs();
-		$this->nav_history = $DIC["ilNavigationHistory"];
-		$this->help = $DIC["ilHelp"];
-		$this->ctrl = $DIC->ctrl();
-		$this->lng = $DIC->language();
-		$this->type = "book";
-		parent::__construct($a_data,$a_id,$a_call_by_reference,$a_prepare_output);
-		$this->lng->loadLanguageModule("book");
-
-		$this->user_profile_id = (int)$_GET["user_id"];
-		$this->book_obj_id = (int)$_REQUEST['object_id'];
-		$this->seed = ilUtil::stripSlashes($_GET['seed']);
-		$this->sseed = ilUtil::stripSlashes($_GET['sseed']);
-		$this->reservation_id = ilUtil::stripSlashes($_GET["reservation_id"]);
-		$this->profile_user_id = (int) $_GET['user_id'];
-
-		$this->user_id_assigner = $this->user->getId();
-		if($_GET['bkusr']) {
-			$this->user_id_to_book = (int)$_GET['bkusr'];
-		} else {
-			$this->user_id_to_book = $this->user_id_assigner; // by default user books his own booking objects.
-		}
-
-		if ((int) $_REQUEST['object_id'] > 0 && ilBookingObject::lookupPoolId((int) $_REQUEST['object_id']) != $this->object->getId())
-		{
-			throw new ilException("Booking Object ID does not match Booking Pool.");
-		}
-	}
-
-	/**
+    /**
+     * @var ilTabsGUI
+     */
+    protected $tabs;
+
+    /**
+     * @var ilNavigationHistory
+     */
+    protected $nav_history;
+
+    /**
+     * @var ilHelpGUI
+     */
+    protected $help;
+
+    /**
+     * @var int
+     */
+    protected $user_id_to_book;  // user who is getting the reservation
+
+    /**
+     * @var int
+     */
+    protected $user_id_assigner; // user who performs the reservation.(self/another)
+
+    /**
+    * Constructor
+    *
+    */
+    public function __construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output = true)
+    {
+        global $DIC;
+
+        $this->tpl = $DIC["tpl"];
+        $this->tabs = $DIC->tabs();
+        $this->nav_history = $DIC["ilNavigationHistory"];
+        $this->help = $DIC["ilHelp"];
+        $this->ctrl = $DIC->ctrl();
+        $this->lng = $DIC->language();
+        $this->type = "book";
+        parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output);
+        $this->lng->loadLanguageModule("book");
+
+        $this->user_profile_id = (int) $_GET["user_id"];
+        $this->book_obj_id = (int) $_REQUEST['object_id'];
+        $this->seed = ilUtil::stripSlashes($_GET['seed']);
+        $this->sseed = ilUtil::stripSlashes($_GET['sseed']);
+        $this->reservation_id = ilUtil::stripSlashes($_GET["reservation_id"]);
+        $this->profile_user_id = (int) $_GET['user_id'];
+
+        $this->user_id_assigner = $this->user->getId();
+        if ($_GET['bkusr']) {
+            $this->user_id_to_book = (int) $_GET['bkusr'];
+        } else {
+            $this->user_id_to_book = $this->user_id_assigner; // by default user books his own booking objects.
+        }
+
+        if ((int) $_REQUEST['object_id'] > 0 && ilBookingObject::lookupPoolId((int) $_REQUEST['object_id']) != $this->object->getId()) {
+            throw new ilException("Booking Object ID does not match Booking Pool.");
+        }
+    }
+
+    /**
      * @return bool
      * @throws ilCtrlException
      * @throws ilObjectException
      */
-	function executeCommand()
-	{
-		$tpl = $this->tpl;
-		$ilTabs = $this->tabs;
-		$ilNavigationHistory = $this->nav_history;
-		$ilUser = $this->user;
-
-		$next_class = $this->ctrl->getNextClass($this);
-		$cmd = $this->ctrl->getCmd();
-		
-		if(!$next_class && $cmd == 'render')
-		{
-			if($ilUser->getId() != ANONYMOUS_USER_ID)
-			{
-				$this->ctrl->setCmdClass('ilBookingObjectGUI');
-				$next_class = $this->ctrl->getNextClass($this);
-			}
-			else
-			{
-				$this->ctrl->redirect($this, "infoscreen");
-			}
-		}
-
-		if(substr($cmd, 0, 4) == 'book')
-		{
-			$next_class = '';
-		}
-
-		$ilNavigationHistory->addItem($this->ref_id,
-				"./goto.php?target=book_".$this->ref_id, "book");
-
-		$this->prepareOutput();
-
-		switch($next_class)
-		{
-			case 'ilpermissiongui':
+    public function executeCommand()
+    {
+        $tpl = $this->tpl;
+        $ilTabs = $this->tabs;
+        $ilNavigationHistory = $this->nav_history;
+        $ilUser = $this->user;
+
+        $next_class = $this->ctrl->getNextClass($this);
+        $cmd = $this->ctrl->getCmd();
+        
+        if (!$next_class && $cmd == 'render') {
+            if ($ilUser->getId() != ANONYMOUS_USER_ID) {
+                $this->ctrl->setCmdClass('ilBookingObjectGUI');
+                $next_class = $this->ctrl->getNextClass($this);
+            } else {
+                $this->ctrl->redirect($this, "infoscreen");
+            }
+        }
+
+        if (substr($cmd, 0, 4) == 'book') {
+            $next_class = '';
+        }
+
+        $ilNavigationHistory->addItem(
+            $this->ref_id,
+            "./goto.php?target=book_" . $this->ref_id,
+            "book"
+        );
+
+        $this->prepareOutput();
+
+        switch ($next_class) {
+            case 'ilpermissiongui':
                 $this->checkPermission('edit_permission');
-				$this->tabs_gui->setTabActive('perm_settings');
-				include_once("Services/AccessControl/classes/class.ilPermissionGUI.php");
-				$perm_gui = new ilPermissionGUI($this);
-				$ret =& $this->ctrl->forwardCommand($perm_gui);
-				break;
-
-			case 'ilbookingobjectgui':
-			    if (!$this->checkPermissionBool('read') && $this->checkPermissionBool('visible')) {
+                $this->tabs_gui->setTabActive('perm_settings');
+                include_once("Services/AccessControl/classes/class.ilPermissionGUI.php");
+                $perm_gui = new ilPermissionGUI($this);
+                $ret =&$this->ctrl->forwardCommand($perm_gui);
+                break;
+
+            case 'ilbookingobjectgui':
+                if (!$this->checkPermissionBool('read') && $this->checkPermissionBool('visible')) {
                     $this->ctrl->redirect($this, "infoScreen");
                 }
                 $this->checkPermission('read');
-				$this->tabs_gui->setTabActive('render');
-				include_once("Modules/BookingManager/classes/class.ilBookingObjectGUI.php");
-				$object_gui = new ilBookingObjectGUI($this);
-				$ret =& $this->ctrl->forwardCommand($object_gui);
-				break;
+                $this->tabs_gui->setTabActive('render');
+                include_once("Modules/BookingManager/classes/class.ilBookingObjectGUI.php");
+                $object_gui = new ilBookingObjectGUI($this);
+                $ret =&$this->ctrl->forwardCommand($object_gui);
+                break;
 
-			case 'ilbookingschedulegui':
+            case 'ilbookingschedulegui':
                 $this->checkPermission('write');
-				$this->tabs_gui->setTabActive('schedules');
-				include_once("Modules/BookingManager/classes/class.ilBookingScheduleGUI.php");
-				$schedule_gui = new ilBookingScheduleGUI($this);
-				$ret =& $this->ctrl->forwardCommand($schedule_gui);
-				break;
+                $this->tabs_gui->setTabActive('schedules');
+                include_once("Modules/BookingManager/classes/class.ilBookingScheduleGUI.php");
+                $schedule_gui = new ilBookingScheduleGUI($this);
+                $ret =&$this->ctrl->forwardCommand($schedule_gui);
+                break;
 
-			case 'ilpublicuserprofilegui':
+            case 'ilpublicuserprofilegui':
                 $this->checkPermission('read');
-				$ilTabs->clearTargets();
-				include_once("Services/User/classes/class.ilPublicUserProfileGUI.php");
-				$profile = new ilPublicUserProfileGUI($this->user_profile_id);
-				$profile->setBackUrl($this->ctrl->getLinkTarget($this, 'log'));
-				$ret = $this->ctrl->forwardCommand($profile);
-				$tpl->setContent($ret);
-				break;
-
-			case 'ilinfoscreengui':
+                $ilTabs->clearTargets();
+                include_once("Services/User/classes/class.ilPublicUserProfileGUI.php");
+                $profile = new ilPublicUserProfileGUI($this->user_profile_id);
+                $profile->setBackUrl($this->ctrl->getLinkTarget($this, 'log'));
+                $ret = $this->ctrl->forwardCommand($profile);
+                $tpl->setContent($ret);
+                break;
+
+            case 'ilinfoscreengui':
                 $this->checkPermission('visible');
-				$this->infoScreen();
-				break;
-			
-			case "ilcommonactiondispatchergui":
+                $this->infoScreen();
+                break;
+            
+            case "ilcommonactiondispatchergui":
                 $this->checkPermission('read');
-				include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php");
-				$gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall();
-				$this->ctrl->forwardCommand($gui);
-				break;
-			
-			case "ilobjectcopygui":
+                include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php");
+                $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall();
+                $this->ctrl->forwardCommand($gui);
+                break;
+            
+            case "ilobjectcopygui":
                 $this->checkPermission('copy');
-				include_once "./Services/Object/classes/class.ilObjectCopyGUI.php";
-				$cp = new ilObjectCopyGUI($this);
-				$cp->setType("book");
-				$this->ctrl->forwardCommand($cp);
-				break;
-			
-			case 'ilobjectmetadatagui';
-				$this->checkPermission('write');
-				$this->tabs_gui->setTabActive('meta_data');
-				include_once 'Services/Object/classes/class.ilObjectMetaDataGUI.php';
-				$md_gui = new ilObjectMetaDataGUI($this->object, 'bobj');	
-				$this->ctrl->forwardCommand($md_gui);
-				break;
-
-			case 'ilbookingparticipantgui':
+                include_once "./Services/Object/classes/class.ilObjectCopyGUI.php";
+                $cp = new ilObjectCopyGUI($this);
+                $cp->setType("book");
+                $this->ctrl->forwardCommand($cp);
+                break;
+            
+            case 'ilobjectmetadatagui':
                 $this->checkPermission('write');
-				$this->tabs_gui->setTabActive('participants');
-				include_once("Modules/BookingManager/classes/class.ilBookingParticipantGUI.php");
-				$object_gui = new ilBookingParticipantGUI($this);
-				$this->ctrl->forwardCommand($object_gui);
-				break;
-			
-			default:
-			    if (!in_array($cmd, ["create", "save", "infoScreen"])) {
+                $this->tabs_gui->setTabActive('meta_data');
+                include_once 'Services/Object/classes/class.ilObjectMetaDataGUI.php';
+                $md_gui = new ilObjectMetaDataGUI($this->object, 'bobj');
+                $this->ctrl->forwardCommand($md_gui);
+                break;
+
+            case 'ilbookingparticipantgui':
+                $this->checkPermission('write');
+                $this->tabs_gui->setTabActive('participants');
+                include_once("Modules/BookingManager/classes/class.ilBookingParticipantGUI.php");
+                $object_gui = new ilBookingParticipantGUI($this);
+                $this->ctrl->forwardCommand($object_gui);
+                break;
+            
+            default:
+                if (!in_array($cmd, ["create", "save", "infoScreen"])) {
                     $this->checkPermission('read');
                 }
-				$cmd = $this->ctrl->getCmd();
-				$cmd .= 'Object';
-				$this->$cmd();
-				break;
-		}
-		
-		$this->addHeaderAction();
-		return true;
-	}
-
-	protected function initCreationForms($a_new_type)
-	{
-		$forms = parent::initCreationForms($a_new_type);
-		unset($forms[self::CFORM_IMPORT]);		
-		
-		return $forms;
-	}
-
-	protected function afterSave(ilObject $a_new_object)
-	{
-		$a_new_object->setOffline(true);
-		$a_new_object->update();
-
-		// always send a message
-		ilUtil::sendSuccess($this->lng->txt("book_pool_added"),true);
-		$this->ctrl->setParameter($this, "ref_id", $a_new_object->getRefId());
-		$this->ctrl->redirect($this, "edit");
-	}
-	
-	public function editObject()
-	{
-		$this->showNoScheduleMessage();
-		return parent::editObject();
-	}
-
-	/**
-	 * Show no schedule message
-	 *
-	 * @param
-	 * @return
-	 */
-	function showNoScheduleMessage()
-	{
-		// if we have no schedules yet - show info
-		include_once "Modules/BookingManager/classes/class.ilBookingSchedule.php";
-		if($this->object->getScheduleType() != ilObjBookingPool::TYPE_NO_SCHEDULE &&
-			!sizeof(ilBookingSchedule::getList($this->object->getId())))
-		{
-			ilUtil::sendInfo($this->lng->txt("book_schedule_warning_edit"));
-		}
-	}
-
-	
-	protected function initEditCustomForm(ilPropertyFormGUI $a_form)
-	{
-		$obj_service = $this->getObjectService();
-
-		$online = new ilCheckboxInputGUI($this->lng->txt("online"), "online");
-		$a_form->addItem($online);
-
-		$type = new ilRadioGroupInputGUI($this->lng->txt("book_schedule_type"), "stype");
-		$type->setRequired(true);
-		$a_form->addItem($type);
-		
-		// #14478
-		include_once "Modules/BookingManager/classes/class.ilBookingObject.php";
-		if(sizeof(ilBookingObject::getList($this->object->getId())))
-		{
-			$type->setDisabled(true);
-		}
-		
-		$fixed = new ilRadioOption($this->lng->txt("book_schedule_type_fixed"), ilObjBookingPool::TYPE_FIX_SCHEDULE);
-		$fixed->setInfo($this->lng->txt("book_schedule_type_fixed_info"));
-		$type->addOption($fixed);
-
-		#23637
-		//period
-		$period = new ilNumberInputGUI($this->lng->txt("book_reservation_filter_period"), "period");
-		$period->setInfo($this->lng->txt("book_reservation_filter_period_info"));
-		$period->setSuffix($this->lng->txt("days"));
-		$period->setSize(3);
-		$period->setMinValue(0);
-		$fixed->addSubItem($period);
-
-		// reminder
-		$rmd = new ilCheckboxInputGUI($this->lng->txt("book_reminder_setting"), "rmd");
-		$rmd->setChecked($this->object->getReminderStatus());
-		$fixed->addSubItem($rmd);
-
-		$rmd_day = new ilNumberInputGUI($this->lng->txt("book_reminder_day"), "rmd_day");
-		$rmd_day->setRequired(true);
-		$rmd_day->setInfo($this->lng->txt("book_reminder_day_info"));
-		$rmd_day->setSize(3);
-		$rmd_day->setSuffix($this->lng->txt("book_reminder_days"));
-		$rmd_day->setValue(max($this->object->getReminderDay(), 1));
-		$rmd_day->setMinValue(1);
-		$rmd->addSubItem($rmd_day);
-		
-		$none = new ilRadioOption($this->lng->txt("book_schedule_type_none"), ilObjBookingPool::TYPE_NO_SCHEDULE);
-		$none->setInfo($this->lng->txt("book_schedule_type_none_info"));
-		$type->addOption($none);
-		
-		$limit = new ilNumberInputGUI($this->lng->txt("book_overall_limit"), "limit");
-		$limit->setSize(4);
-		$limit->setMinValue(1);
-		$limit->setInfo($this->lng->txt("book_overall_limit_info"));
-		$none->addSubItem($limit);
-	
-		$public = new ilCheckboxInputGUI($this->lng->txt("book_public_log"), "public");
-		$public->setInfo($this->lng->txt("book_public_log_info"));
-		$a_form->addItem($public);
-
-		// presentation
-		$pres = new ilFormSectionHeaderGUI();
-		$pres->setTitle($this->lng->txt('obj_presentation'));
-		$a_form->addItem($pres);
-
-		// tile image
-		$obj_service->commonSettings()->legacyForm($a_form, $this->object)->addTileImage();
-
-		// additional features
-		$feat = new ilFormSectionHeaderGUI();
-		$feat->setTitle($this->lng->txt('obj_features'));
-		$a_form->addItem($feat);
-
-	}
-
-	protected function getEditFormCustomValues(array &$a_values)
-	{
-		$a_values["online"] = !$this->object->isOffline();
-		$a_values["public"] = $this->object->hasPublicLog();
-		$a_values["stype"] = $this->object->getScheduleType();
-		$a_values["limit"] = $this->object->getOverallLimit();		
-		$a_values["period"] = $this->object->getReservationFilterPeriod();
-		$a_values["rmd"] = $this->object->getReminderStatus();
-		$a_values["rmd_day"] = $this->object->getReminderDay();
-	}
-
-	protected function updateCustom(ilPropertyFormGUI $a_form)
-	{
-		$obj_service = $this->getObjectService();
-
-		$this->object->setOffline(!$a_form->getInput('online'));
-		$this->object->setReminderStatus($a_form->getInput('rmd'));
-		$this->object->setReminderDay($a_form->getInput('rmd_day'));
-		$this->object->setPublicLog($a_form->getInput('public'));
-		$this->object->setScheduleType($a_form->getInput('stype'));
-		$this->object->setOverallLimit($a_form->getInput('limit') ? $a_form->getInput('limit') : null);
-		$this->object->setReservationFilterPeriod(strlen($a_form->getInput('period')) ? (int)$a_form->getInput('period') : null);
-
-		// tile image
-		$obj_service->commonSettings()->legacyForm($a_form, $this->object)->saveTileImage();
-
-		include_once './Services/Container/classes/class.ilContainer.php';
-		include_once './Services/Object/classes/class.ilObjectServiceSettingsGUI.php';
-		ilObjectServiceSettingsGUI::updateServiceSettingsForm(
-			$this->object->getId(),
-			$a_form,
-			array(ilObjectServiceSettingsGUI::CUSTOM_METADATA)
-		);
-	}
-	
-	public function addExternalEditFormCustom(ilPropertyFormGUI $a_form)
-	{				
-		include_once './Services/Container/classes/class.ilContainer.php';
-		include_once './Services/Object/classes/class.ilObjectServiceSettingsGUI.php';
-		ilObjectServiceSettingsGUI::initServiceSettingsForm(
-				$this->object->getId(),
-				$a_form,
-				array(ilObjectServiceSettingsGUI::CUSTOM_METADATA)
-			);
-	}
-	
-	/**
-	* get tabs
-	*/
-	function setTabs()
-	{
-		$ilHelp = $this->help;
-		$ilUser = $this->user;
-		
-		if (in_array($this->ctrl->getCmd(), array("create", "save")) && !$this->ctrl->getNextClass())
-		{
-			return;
-		}
-		
-		$ilHelp->setScreenIdComponent("book");
-		
-		if ($this->checkPermissionBool('read'))
-		{
-			if($ilUser->getId() != ANONYMOUS_USER_ID)
-			{
-				$this->tabs_gui->addTab("render",
-						$this->lng->txt("book_booking_types"),
-						$this->ctrl->getLinkTarget($this, "render"));
-			}
-		
-			$this->tabs_gui->addTab("info",
-					$this->lng->txt("info_short"),
-					$this->ctrl->getLinkTarget($this, "infoscreen"));
-
-			if($ilUser->getId() != ANONYMOUS_USER_ID || $this->object->hasPublicLog())
-			{
-				$this->tabs_gui->addTab("log",
-					$this->lng->txt("book_log"),
-					$this->ctrl->getLinkTarget($this, "log"));		
-			}
-		}
-		
-		if ($this->checkPermissionBool('write'))
-		{
-			if($this->object->getScheduleType() != ilObjBookingPool::TYPE_NO_SCHEDULE)
-			{
-				$this->tabs_gui->addTab("schedules",
-					$this->lng->txt("book_schedules"),
-					$this->ctrl->getLinkTargetByClass("ilbookingschedulegui", "render"));
-			}
-			
-			$this->tabs_gui->addTab("settings",
-				$this->lng->txt("settings"),
-				$this->ctrl->getLinkTarget($this, "edit"));
-			
-			// meta data		
-			include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php";
-			$mdgui = new ilObjectMetaDataGUI($this->object, "bobj");					
-			$mdtab = $mdgui->getTab();
-			if($mdtab)
-			{
-				$this->tabs_gui->addTarget("meta_data",
-									 $mdtab,
-									 "",
-									 "ilobjectmetadatagui");
-			}	
-		}
-
-		if($this->checkPermissionBool('write')) {
-            $this->tabs_gui->addTab("participants",
+                $cmd = $this->ctrl->getCmd();
+                $cmd .= 'Object';
+                $this->$cmd();
+                break;
+        }
+        
+        $this->addHeaderAction();
+        return true;
+    }
+
+    protected function initCreationForms($a_new_type)
+    {
+        $forms = parent::initCreationForms($a_new_type);
+        unset($forms[self::CFORM_IMPORT]);
+        
+        return $forms;
+    }
+
+    protected function afterSave(ilObject $a_new_object)
+    {
+        $a_new_object->setOffline(true);
+        $a_new_object->update();
+
+        // always send a message
+        ilUtil::sendSuccess($this->lng->txt("book_pool_added"), true);
+        $this->ctrl->setParameter($this, "ref_id", $a_new_object->getRefId());
+        $this->ctrl->redirect($this, "edit");
+    }
+    
+    public function editObject()
+    {
+        $this->showNoScheduleMessage();
+        return parent::editObject();
+    }
+
+    /**
+     * Show no schedule message
+     *
+     * @param
+     * @return
+     */
+    public function showNoScheduleMessage()
+    {
+        // if we have no schedules yet - show info
+        include_once "Modules/BookingManager/classes/class.ilBookingSchedule.php";
+        if ($this->object->getScheduleType() != ilObjBookingPool::TYPE_NO_SCHEDULE &&
+            !sizeof(ilBookingSchedule::getList($this->object->getId()))) {
+            ilUtil::sendInfo($this->lng->txt("book_schedule_warning_edit"));
+        }
+    }
+
+    
+    protected function initEditCustomForm(ilPropertyFormGUI $a_form)
+    {
+        $obj_service = $this->getObjectService();
+
+        $online = new ilCheckboxInputGUI($this->lng->txt("online"), "online");
+        $a_form->addItem($online);
+
+        $type = new ilRadioGroupInputGUI($this->lng->txt("book_schedule_type"), "stype");
+        $type->setRequired(true);
+        $a_form->addItem($type);
+        
+        // #14478
+        include_once "Modules/BookingManager/classes/class.ilBookingObject.php";
+        if (sizeof(ilBookingObject::getList($this->object->getId()))) {
+            $type->setDisabled(true);
+        }
+        
+        $fixed = new ilRadioOption($this->lng->txt("book_schedule_type_fixed"), ilObjBookingPool::TYPE_FIX_SCHEDULE);
+        $fixed->setInfo($this->lng->txt("book_schedule_type_fixed_info"));
+        $type->addOption($fixed);
+
+        #23637
+        //period
+        $period = new ilNumberInputGUI($this->lng->txt("book_reservation_filter_period"), "period");
+        $period->setInfo($this->lng->txt("book_reservation_filter_period_info"));
+        $period->setSuffix($this->lng->txt("days"));
+        $period->setSize(3);
+        $period->setMinValue(0);
+        $fixed->addSubItem($period);
+
+        // reminder
+        $rmd = new ilCheckboxInputGUI($this->lng->txt("book_reminder_setting"), "rmd");
+        $rmd->setChecked($this->object->getReminderStatus());
+        $fixed->addSubItem($rmd);
+
+        $rmd_day = new ilNumberInputGUI($this->lng->txt("book_reminder_day"), "rmd_day");
+        $rmd_day->setRequired(true);
+        $rmd_day->setInfo($this->lng->txt("book_reminder_day_info"));
+        $rmd_day->setSize(3);
+        $rmd_day->setSuffix($this->lng->txt("book_reminder_days"));
+        $rmd_day->setValue(max($this->object->getReminderDay(), 1));
+        $rmd_day->setMinValue(1);
+        $rmd->addSubItem($rmd_day);
+        
+        $none = new ilRadioOption($this->lng->txt("book_schedule_type_none"), ilObjBookingPool::TYPE_NO_SCHEDULE);
+        $none->setInfo($this->lng->txt("book_schedule_type_none_info"));
+        $type->addOption($none);
+        
+        $limit = new ilNumberInputGUI($this->lng->txt("book_overall_limit"), "limit");
+        $limit->setSize(4);
+        $limit->setMinValue(1);
+        $limit->setInfo($this->lng->txt("book_overall_limit_info"));
+        $none->addSubItem($limit);
+    
+        $public = new ilCheckboxInputGUI($this->lng->txt("book_public_log"), "public");
+        $public->setInfo($this->lng->txt("book_public_log_info"));
+        $a_form->addItem($public);
+
+        // presentation
+        $pres = new ilFormSectionHeaderGUI();
+        $pres->setTitle($this->lng->txt('obj_presentation'));
+        $a_form->addItem($pres);
+
+        // tile image
+        $obj_service->commonSettings()->legacyForm($a_form, $this->object)->addTileImage();
+
+        // additional features
+        $feat = new ilFormSectionHeaderGUI();
+        $feat->setTitle($this->lng->txt('obj_features'));
+        $a_form->addItem($feat);
+    }
+
+    protected function getEditFormCustomValues(array &$a_values)
+    {
+        $a_values["online"] = !$this->object->isOffline();
+        $a_values["public"] = $this->object->hasPublicLog();
+        $a_values["stype"] = $this->object->getScheduleType();
+        $a_values["limit"] = $this->object->getOverallLimit();
+        $a_values["period"] = $this->object->getReservationFilterPeriod();
+        $a_values["rmd"] = $this->object->getReminderStatus();
+        $a_values["rmd_day"] = $this->object->getReminderDay();
+    }
+
+    protected function updateCustom(ilPropertyFormGUI $a_form)
+    {
+        $obj_service = $this->getObjectService();
+
+        $this->object->setOffline(!$a_form->getInput('online'));
+        $this->object->setReminderStatus($a_form->getInput('rmd'));
+        $this->object->setReminderDay($a_form->getInput('rmd_day'));
+        $this->object->setPublicLog($a_form->getInput('public'));
+        $this->object->setScheduleType($a_form->getInput('stype'));
+        $this->object->setOverallLimit($a_form->getInput('limit') ? $a_form->getInput('limit') : null);
+        $this->object->setReservationFilterPeriod(strlen($a_form->getInput('period')) ? (int) $a_form->getInput('period') : null);
+
+        // tile image
+        $obj_service->commonSettings()->legacyForm($a_form, $this->object)->saveTileImage();
+
+        include_once './Services/Container/classes/class.ilContainer.php';
+        include_once './Services/Object/classes/class.ilObjectServiceSettingsGUI.php';
+        ilObjectServiceSettingsGUI::updateServiceSettingsForm(
+            $this->object->getId(),
+            $a_form,
+            array(ilObjectServiceSettingsGUI::CUSTOM_METADATA)
+        );
+    }
+    
+    public function addExternalEditFormCustom(ilPropertyFormGUI $a_form)
+    {
+        include_once './Services/Container/classes/class.ilContainer.php';
+        include_once './Services/Object/classes/class.ilObjectServiceSettingsGUI.php';
+        ilObjectServiceSettingsGUI::initServiceSettingsForm(
+            $this->object->getId(),
+            $a_form,
+            array(ilObjectServiceSettingsGUI::CUSTOM_METADATA)
+            );
+    }
+    
+    /**
+    * get tabs
+    */
+    public function setTabs()
+    {
+        $ilHelp = $this->help;
+        $ilUser = $this->user;
+        
+        if (in_array($this->ctrl->getCmd(), array("create", "save")) && !$this->ctrl->getNextClass()) {
+            return;
+        }
+        
+        $ilHelp->setScreenIdComponent("book");
+        
+        if ($this->checkPermissionBool('read')) {
+            if ($ilUser->getId() != ANONYMOUS_USER_ID) {
+                $this->tabs_gui->addTab(
+                    "render",
+                    $this->lng->txt("book_booking_types"),
+                    $this->ctrl->getLinkTarget($this, "render")
+                );
+            }
+        
+            $this->tabs_gui->addTab(
+                "info",
+                $this->lng->txt("info_short"),
+                $this->ctrl->getLinkTarget($this, "infoscreen")
+            );
+
+            if ($ilUser->getId() != ANONYMOUS_USER_ID || $this->object->hasPublicLog()) {
+                $this->tabs_gui->addTab(
+                    "log",
+                    $this->lng->txt("book_log"),
+                    $this->ctrl->getLinkTarget($this, "log")
+                );
+            }
+        }
+        
+        if ($this->checkPermissionBool('write')) {
+            if ($this->object->getScheduleType() != ilObjBookingPool::TYPE_NO_SCHEDULE) {
+                $this->tabs_gui->addTab(
+                    "schedules",
+                    $this->lng->txt("book_schedules"),
+                    $this->ctrl->getLinkTargetByClass("ilbookingschedulegui", "render")
+                );
+            }
+            
+            $this->tabs_gui->addTab(
+                "settings",
+                $this->lng->txt("settings"),
+                $this->ctrl->getLinkTarget($this, "edit")
+            );
+            
+            // meta data
+            include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php";
+            $mdgui = new ilObjectMetaDataGUI($this->object, "bobj");
+            $mdtab = $mdgui->getTab();
+            if ($mdtab) {
+                $this->tabs_gui->addTarget(
+                    "meta_data",
+                    $mdtab,
+                    "",
+                    "ilobjectmetadatagui"
+                );
+            }
+        }
+
+        if ($this->checkPermissionBool('write')) {
+            $this->tabs_gui->addTab(
+                "participants",
                 $this->lng->txt("participants"),
-                $this->ctrl->getLinkTargetByClass("ilbookingparticipantgui", "render"));
+                $this->ctrl->getLinkTargetByClass("ilbookingparticipantgui", "render")
+            );
         }
 
-        if($this->checkPermissionBool('edit_permission'))
-        {
-                $this->tabs_gui->addTab("perm_settings",
-				$this->lng->txt("perm_settings"),
-				$this->ctrl->getLinkTargetByClass("ilpermissiongui", "perm"));
-		}
-	}
-	
-	protected function setHelpId($a_id)
-	{
-		$ilHelp = $this->help;
-		
-		$object_subtype = ($this->object->getScheduleType() == ilObjBookingPool::TYPE_FIX_SCHEDULE)
-			? '-schedule'
-			: '-nonschedule';
-		
-		$ilHelp->setScreenIdComponent('book');
-		$ilHelp->setScreenId('object'.$object_subtype);
-		$ilHelp->setSubScreenId($a_id);
-	}
-
-	/**
-	 * First step in booking process
-	 */
-	function bookObject()
-	{
-		$tpl = $this->tpl;
-		
-		$this->tabs_gui->clearTargets();
-		$this->tabs_gui->setBackTarget($this->lng->txt('book_back_to_list'), $this->ctrl->getLinkTarget($this, 'render'));
-		
-		$this->setHelpId("book");
-
-		include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
-		$obj = new ilBookingObject((int)$_GET['object_id']);
-				
-		$this->lng->loadLanguageModule("dateplaner");
-		$this->ctrl->setParameter($this, 'object_id', $obj->getId());
-
-		if($this->user_id_to_book != $this->user_id_assigner) {
-			$this->ctrl->setParameter($this, 'bkusr', $this->user_id_to_book);
-		}
-
-		if($this->object->getScheduleType() == ilObjBookingPool::TYPE_FIX_SCHEDULE)
-		{
-			include_once 'Modules/BookingManager/classes/class.ilBookingSchedule.php';		
-			$schedule = new ilBookingSchedule($obj->getScheduleId());
-
-			$tpl->setContent($this->renderSlots($schedule, array($obj->getId()), $obj->getTitle()));
-		}
-		else
-		{
-			include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php");
-			$cgui = new ilConfirmationGUI();
-			$cgui->setHeaderText($this->lng->txt("book_confirm_booking_no_schedule"));
-
-			$cgui->setFormAction($this->ctrl->getFormAction($this));
-			$cgui->setCancel($this->lng->txt("cancel"), "render");
-			$cgui->setConfirm($this->lng->txt("confirm"), "confirmedBooking");
-
-			$cgui->addItem("object_id", $obj->getId(), $obj->getTitle());
-
-			if($_GET['part_view'] == ilBookingParticipantGUI::PARTICIPANT_VIEW) {
-				$cgui->addHiddenItem("part_view", ilBookingParticipantGUI::PARTICIPANT_VIEW);
-			}
-
-			$tpl->setContent($cgui->getHTML());
-		}
-	}
-
-	protected function renderSlots(ilBookingSchedule $schedule, array $object_ids, $title)
-	{
-		$ilUser = $this->user;
-		
-		// fix
-		if(!$schedule->getRaster())
-		{
-			$mytpl = new ilTemplate('tpl.booking_reservation_fix.html', true, true, 'Modules/BookingManager');
-
-			$mytpl->setVariable('FORM_ACTION', $this->ctrl->getFormAction($this));
-			$mytpl->setVariable('TXT_TITLE', $this->lng->txt('book_reservation_title'));
-			$mytpl->setVariable('TXT_INFO', $this->lng->txt('book_reservation_fix_info'));
-			$mytpl->setVariable('TXT_OBJECT', $title);
-			$mytpl->setVariable('TXT_CMD_BOOK', $this->lng->txt('book_confirm_booking'));
-			$mytpl->setVariable('TXT_CMD_CANCEL', $this->lng->txt('cancel'));
-
-			include_once 'Services/Calendar/classes/class.ilCalendarUserSettings.php';
-			
-			$user_settings = ilCalendarUserSettings::_getInstanceByUserId($ilUser->getId());
-
-			$morning_aggr = $user_settings->getDayStart();
-			$evening_aggr = $user_settings->getDayEnd();
-			$hours = array();
-			for($i = $morning_aggr;$i <= $evening_aggr;$i++)
-			{
-				switch($user_settings->getTimeFormat())
-				{
-					case ilCalendarSettings::TIME_FORMAT_24:
-						if ($morning_aggr > 0 && $i == $morning_aggr)
-						{
-							$hours[$i] = sprintf('%02d:00',0)."-";
-						}
-						$hours[$i].= sprintf('%02d:00',$i);
-						if ($evening_aggr < 23 && $i == $evening_aggr)
-						{
-							$hours[$i].= "-".sprintf('%02d:00',23);
-						}
-						break;
-
-					case ilCalendarSettings::TIME_FORMAT_12:
-						if ($morning_aggr > 0 && $i == $morning_aggr)
-						{
-							$hours[$i] = date('h a',mktime(0,0,0,1,1,2000))."-";
-						}
-						$hours[$i].= date('h a',mktime($i,0,0,1,1,2000));
-						if ($evening_aggr < 23 && $i == $evening_aggr)
-						{
-							$hours[$i].= "-".date('h a',mktime(23,0,0,1,1,2000));
-						}
-						break;
-				}
-			}
-
-			if ($this->seed != "")
-			{
-				$find_first_open = false;
-				$seed = new ilDate($this->seed, IL_CAL_DATE);
-			}
-			else
-			{
-				$find_first_open = true;
-				$seed = ($this->sseed != "")
-					? new ilDate($this->sseed, IL_CAL_DATE)
-					: new ilDate(time(), IL_CAL_UNIX);
-			}
-			
-			include_once 'Services/Calendar/classes/class.ilCalendarUtil.php';
-			include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php';			
-			$week_start = $user_settings->getWeekStart();
-			
-			if(!$find_first_open)
-			{
-				$dates = array();
-				$this->buildDatesBySchedule($week_start, $hours, $schedule, $object_ids, $seed, $dates);
-			}
-			else
-			{
-				$dates = array();
-
-				//loop for 1 week
-				$has_open_slot = $this->buildDatesBySchedule($week_start, $hours, $schedule, $object_ids, $seed, $dates);
-				
-				// find first open slot
-				if(!$has_open_slot)
-				{
-					// 1 year is limit for search
-					$limit = clone($seed);
-					$limit->increment(ilDate::YEAR, 1);
-					$limit = $limit->get(IL_CAL_UNIX);
-					
-					while(!$has_open_slot && $seed->get(IL_CAL_UNIX) < $limit)
-					{
-						$seed->increment(ilDate::WEEK, 1);
-						
-						$dates = array();
-						$has_open_slot = $this->buildDatesBySchedule($week_start, $hours, $schedule, $object_ids, $seed, $dates);
-					}	
-				}
-			}			
-			
-			include_once 'Services/Calendar/classes/class.ilCalendarHeaderNavigationGUI.php';
-			$navigation = new ilCalendarHeaderNavigationGUI($this,$seed,ilDateTime::WEEK,'book');
-			$mytpl->setVariable('NAVIGATION', $navigation->getHTML());
-
-			foreach(ilCalendarUtil::_buildWeekDayList($seed,$week_start)->get() as $date)
-			{
-				$date_info = $date->get(IL_CAL_FKT_GETDATE,'','UTC');
-
-				$mytpl->setCurrentBlock('weekdays');
-				$mytpl->setVariable('TXT_WEEKDAY', ilCalendarUtil:: _numericDayToString($date_info['wday']));
-				$mytpl->setVariable('TXT_DATE', $date_info['mday'].' '.ilCalendarUtil:: _numericMonthToString($date_info['mon']));
-				$mytpl->parseCurrentBlock();
-			}
-			
-			include_once 'Services/Calendar/classes/class.ilCalendarAppointmentColors.php';
-			include_once 'Services/Calendar/classes/class.ilCalendarUtil.php';
-			$color = array();
-			$all = ilCalendarAppointmentColors::_getColorsByType('crs');
-			for($loop = 0; $loop < 7; $loop++)
-		    {
-				$col = $all[$loop];
-				$fnt = ilCalendarUtil::calculateFontColor($col);
-				$color[$loop+1] = 'border-bottom: 1px solid '.$col.'; background-color: '.$col.'; color: '.$fnt;
-			}
-			
-			$counter = 0;
-			foreach($dates as $hour => $days)
-			{
-				$caption = $days;
-				$caption = array_shift($caption);
-
-				for($loop = 1; $loop < 8; $loop++)
-			    {
-					if(!isset($days[$loop]))
-					{
-						$mytpl->setCurrentBlock('dates');
-						$mytpl->setVariable('DUMMY', ' ');
-						$mytpl->parseCurrentBlock();
-					}
-					else
-					{
-						if(isset($days[$loop]['captions']))
-						{
-							foreach($days[$loop]['captions'] as $slot_id => $slot_caption)
-							{								
-								$mytpl->setCurrentBlock('choice');
-								$mytpl->setVariable('TXT_DATE', $slot_caption);
-								$mytpl->setVariable('VALUE_DATE', $slot_id);
-								$mytpl->setVariable('DATE_COLOR', $color[$loop]);
-								$mytpl->setVariable('TXT_AVAILABLE', 
-									sprintf($this->lng->txt('book_reservation_available'), 
-									$days[$loop]['available'][$slot_id]));
-								$mytpl->parseCurrentBlock();
-							}
-
-							$mytpl->setCurrentBlock('dates');
-							$mytpl->setVariable('DUMMY', '');
-							$mytpl->parseCurrentBlock();
-						}
-						else if(isset($days[$loop]['in_slot']))
-						{
-							$mytpl->setCurrentBlock('dates');
-							$mytpl->setVariable('DATE_COLOR', $color[$loop]);
-							$mytpl->parseCurrentBlock();
-						}
-						else
-						{
-							$mytpl->setCurrentBlock('dates');
-							$mytpl->setVariable('DUMMY', ' ');
-							$mytpl->parseCurrentBlock();
-						}
-					}
-				}
-
-				$mytpl->setCurrentBlock('slots');
-				$mytpl->setVariable('TXT_HOUR', $caption);
-				if($counter%2)
-				{
-					$mytpl->setVariable('CSS_ROW', 'tblrow1');
-				}
-				else
-				{
-					$mytpl->setVariable('CSS_ROW', 'tblrow2');
-				}
-				$mytpl->parseCurrentBlock();
-
-				$counter++;
-			}
-		}
-		// flexible
-		else
-		{
-			// :TODO: inactive for now
-		}
-		
-		return $mytpl->get();
-	}
-	
-	protected function buildDatesBySchedule($week_start, array $hours, $schedule, array $object_ids, $seed, array &$dates)
-	{
-		$ilUser = $this->user;
-		
-		include_once 'Services/Calendar/classes/class.ilCalendarUserSettings.php';			
-		$user_settings = ilCalendarUserSettings::_getInstanceByUserId($ilUser->getId());		
-		
-		$map = array('mo', 'tu', 'we', 'th', 'fr', 'sa', 'su');
-		$definition = $schedule->getDefinition();
-		
-		$av_from = ($schedule->getAvailabilityFrom() && !$schedule->getAvailabilityFrom()->isNull())
-			? $schedule->getAvailabilityFrom()->get(IL_CAL_DATE)
-			: null;
-		$av_to = ($schedule->getAvailabilityTo() && !$schedule->getAvailabilityTo()->isNull())
-			? $schedule->getAvailabilityTo()->get(IL_CAL_DATE)
-			: null;
-		
-		$has_open_slot = false;
-		foreach(ilCalendarUtil::_buildWeekDayList($seed,$week_start)->get() as $date)
-		{
-			$date_info = $date->get(IL_CAL_FKT_GETDATE,'','UTC');
-
-			#24045 and #24936
-			if($av_from || $av_to)
-			{
-				$today = $date->get(IL_CAL_DATE);
-
-				if ($av_from && $av_from > $today)
-				{
-					continue;
-				}
-
-				if($av_to && $av_to < $today)
-				{
-					continue;
-				}
-			}
-
-			$slots = array();
-			if(isset($definition[$map[$date_info['isoday']-1]]))
-			{
-				$slots = array();
-				foreach($definition[$map[$date_info['isoday']-1]] as $slot)
-				{
-					$slot = explode('-', $slot);
-					$slots[] = array('from'=>str_replace(':', '', $slot[0]),
-						'to'=>str_replace(':', '', $slot[1]));
-				}
-			}
-
-			$last = array_pop(array_keys($hours));
-			$slot_captions = array();
-			foreach($hours as $hour => $period)
-			{
-				$dates[$hour][0] = $period;
-				
-				$period = explode("-", $period);
-				
-				// #13738
-				if($user_settings->getTimeFormat() == ilCalendarSettings::TIME_FORMAT_12)
-				{					
-					$period[0] = date("H", strtotime($period[0]));						
-					if(sizeof($period) == 2)
-					{
-						$period[1] = date("H", strtotime($period[1]));		
-					}							
-				}
-				
-				if(sizeof($period) == 1)
-				{
-					$period_from = (int)substr($period[0], 0, 2)."00";
-					$period_to = (int)substr($period[0], 0, 2)."59";
-				}
-				else
-				{
-					$period_from = (int)substr($period[0], 0, 2)."00";
-					$period_to = (int)substr($period[1], 0, 2)."59";
-				}		
-
-				$column = $date_info['isoday'];
-				if(!$week_start)
-				{
-					if($column < 7)
-					{
-						$column++;
-					}
-					else
-					{
-						$column = 1;
-					}
-				}
-
-				if(sizeof($slots))
-				{						
-					$in = false;
-					foreach($slots as $slot)
-					{
-						$slot_from = mktime(substr($slot['from'], 0, 2), substr($slot['from'], 2, 2), 0, $date_info["mon"], $date_info["mday"], $date_info["year"]);
-						$slot_to = mktime(substr($slot['to'], 0, 2), substr($slot['to'], 2, 2), 0, $date_info["mon"], $date_info["mday"], $date_info["year"]);
-
-						// always single object, we can sum up
-						$nr_available = (array)ilBookingReservation::getAvailableObject($object_ids, $slot_from, $slot_to-1, false, true);						
-						
-						// any objects available?
-						if(!array_sum($nr_available))
-						{
-							continue;
-						}					
-						
-						// check deadline
-						if($schedule->getDeadline() >= 0)
-						{
-							// 0-n hours before slots begins
-							if($slot_from < (time()+$schedule->getDeadline()*60*60))
-							{
-								continue;
-							}
-						}
-						else
-						{
-							// running slots can be booked, only ended slots are invalid
-							if($slot_to < time())
-							{
-								continue;
-							}							
-						}
-						
-						// is slot active in current hour?
-						if((int)$slot['from'] < $period_to && (int)$slot['to'] > $period_from)
-						{																					
-							$from = ilDatePresentation::formatDate(new ilDateTime($slot_from, IL_CAL_UNIX));
-							$from = array_pop(explode(' ', $from));
-							$to = ilDatePresentation::formatDate(new ilDateTime($slot_to, IL_CAL_UNIX));
-							$to = array_pop(explode(' ', $to));
-
-							// show caption (first hour) of slot
-							$id = $slot_from.'_'.$slot_to;
-							if(!in_array($id, $slot_captions))
-							{
-								$dates[$hour][$column]['captions'][$id] = $from.'-'.$to;
-								$dates[$hour][$column]['available'][$id] = array_sum($nr_available);
-								$slot_captions[] = $id;
-							}
-
-							$in = true;
-						}
-					}
-					// (any) active slot
-					if($in)
-					{
-						$has_open_slot = true;
-						$dates[$hour][$column]['in_slot'] = $in;
-					}
-				}
-			}
-		}
-
-		return $has_open_slot;
-	}
-
-	/**
-	 * Book object - either of type or specific - for given dates
-	 */
-	function confirmedBookingObject()
-	{				
-		$ilUser = $this->user;
-		
-		include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
-		include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php';		
-		
-		$success = false;
-		$rsv_ids = array();
-		
-		if($this->object->getScheduleType() == ilObjBookingPool::TYPE_NO_SCHEDULE)
-		{	
-			if($this->book_obj_id > 0)
-			{
-				$object_id = $this->book_obj_id;
-				if($object_id)
-				{
-					if(ilBookingReservation::isObjectAvailableNoSchedule($object_id) &&
-						!ilBookingReservation::getObjectReservationForUser($object_id, $this->user_id_to_book)) // #18304
-					{
-						$rsv_ids[] = $this->processBooking($object_id);
-						$success = $object_id;	
-					}
-					else
-					{
-						// #11852
-						ilUtil::sendFailure($this->lng->txt('book_reservation_failed_overbooked'), true);
-						$this->ctrl->redirect($this, 'render');						
-					}
-				}
-			}
-		}	
-		else
-		{												
-			if(!isset($_POST['date']))
-			{
-				ilUtil::sendFailure($this->lng->txt('select_one'));
-				return $this->bookObject();
-			}
-						
-			// single object reservation(s)
-			if($this->book_obj_id > 0)
-			{
-				$confirm = array();
-				
-				$object_id = $this->book_obj_id;
-				if($object_id)
-				{	
-					$group_id = null;
-					$nr = ilBookingObject::getNrOfItemsForObjects(array($object_id));
-					// needed for recurrence
-					$group_id = ilBookingReservation::getNewGroupId();
-					foreach($_POST['date'] as $date)
-					{										
-						$fromto = explode('_', $date);
-						$fromto[1]--;
-
-						$counter = ilBookingReservation::getAvailableObject(array($object_id), $fromto[0], $fromto[1], false, true);
-						$counter = $counter[$object_id];
-						if($counter)
-						{					
-							// needed for recurrence
-							$confirm[$object_id."_".$fromto[0]."_".($fromto[1]+1)] = $counter;
-						}
-					}
-				}
-				
-				if(sizeof($confirm))
-				{
-					return $this->confirmBookingNumbers($confirm, $group_id);					
-				}
-			}
-		}
-		
-		if($success)
-		{
-			$this->saveParticipant();
-			$this->handleBookingSuccess($success, $rsv_ids);
-		}
-		else
-		{
-			ilUtil::sendFailure($this->lng->txt('book_reservation_failed'), true);
-			$this->ctrl->redirect($this, 'book');
-		}
-	}
-	
-	protected function handleBookingSuccess($a_obj_id, array $a_rsv_ids = null)
-	{
-		ilUtil::sendSuccess($this->lng->txt('book_reservation_confirmed'), true);
-			
-		// show post booking information?
-		include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
-		$obj = new ilBookingObject($a_obj_id);
-		$pfile = $obj->getPostFile();
-		$ptext = $obj->getPostText();
-		if(trim($ptext) || $pfile)
-		{
-			if(sizeof($a_rsv_ids))
-			{
-				$this->ctrl->setParameterByClass('ilbookingobjectgui', 'rsv_ids', implode(";", $a_rsv_ids));		
-			}
-			$this->ctrl->setParameterByClass('ilbookingobjectgui', 'object_id', $obj->getId());				
-			$this->ctrl->redirectByClass('ilbookingobjectgui', 'displayPostInfo');
-		}
-		else
-		{
-			if($_POST['part_view'] == ilBookingParticipantGUI::PARTICIPANT_VIEW) {
-				$this->ctrl->redirectByClass('ilbookingparticipantgui','render');
-			} else {
-				$this->ctrl->redirect($this, 'render');
-			}
-		}
-	}
-	
-	protected function initBookingNumbersForm(array $a_objects_counter, $a_group_id, $a_reload = false)
-	{
-		include_once 'Services/Form/classes/class.ilPropertyFormGUI.php';
-		$form = new ilPropertyFormGUI();
-		$form->setFormAction($this->ctrl->getFormAction($this, "confirmedBooking"));
-		$form->setTitle($this->lng->txt("book_confirm_booking_schedule_number_of_objects"));
-		$form->setDescription($this->lng->txt("book_confirm_booking_schedule_number_of_objects_info"));
-		
-		include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
-		$section = false;
-		$min_date = null;
-		foreach($a_objects_counter as $id => $counter)
-		{			
-			$id = explode("_", $id);
-			$book_id = $id[0]."_".$id[1]."_".$id[2]."_".$counter;
-			
-			$obj = new ilBookingObject($id[0]);
-			
-			if(!$section)
-			{
-				$section = new ilFormSectionHeaderGUI();
-				$section->setTitle($obj->getTitle());
-				$form->addItem($section);
-				
-				$section = true;
-			}
-			
-			$period = /* $this->lng->txt("book_period").": ". */
-				ilDatePresentation::formatPeriod(
-					new ilDateTime($id[1], IL_CAL_UNIX),
-					new ilDateTime($id[2], IL_CAL_UNIX));
-			
-			$nr_field = new ilNumberInputGUI($period, "conf_nr__".$book_id);
-			$nr_field->setValue(1);
-			$nr_field->setSize(3);
-			$nr_field->setMaxValue($counter);
-			$nr_field->setMinValue($counter ? 1 : 0);
-			$nr_field->setRequired(true);
-			$form->addItem($nr_field);	
-			
-			if(!$min_date || $id[1] < $min_date)
-			{
-				$min_date = $id[1];
-			}
-		}
-		
-		// recurrence
-		$this->lng->loadLanguageModule("dateplaner");
-		$rec_mode = new ilSelectInputGUI($this->lng->txt("cal_recurrences"), "recm");
-		$rec_mode->setRequired(true);
-		$rec_mode->setOptions(array(			
-			"-1" => $this->lng->txt("cal_no_recurrence"),
-			1 => $this->lng->txt("cal_weekly"),
-			2 => $this->lng->txt("r_14"),
-			4 => $this->lng->txt("r_4_weeks")
-		));
-		$form->addItem($rec_mode);
-
-		$rec_end = new ilDateTimeInputGUI($this->lng->txt("cal_repeat_until"), "rece");		
-		$rec_end->setRequired(true);
-		$rec_mode->addSubItem($rec_end);	
-					
-		if(!$a_reload)
-		{
-			// show date only if active recurrence
-			$rec_mode->setHideSubForm(true, '>= 1');
-			
-			if($min_date)
-			{
-				$rec_end->setDate(new ilDateTime($min_date, IL_CAL_UNIX));
-			}
-		}
-		else
-		{
-			// recurrence may not be changed on reload
-			$rec_mode->setDisabled(true);
-			$rec_end->setDisabled(true);			
-		}
-		
-		if($a_group_id)
-		{
-			$grp = new ilHiddenInputGUI("grp_id");
-			$grp->setValue($a_group_id);
-			$form->addItem($grp);		
-		}
-
-		if($this->user_id_assigner != $this->user_id_to_book)
-		{
-			$usr = new ilHiddenInputGUI("bkusr");
-			$usr->setValue($this->user_id_to_book);
-			$form->addItem($usr);
-		}
-
-		$form->addCommandButton("confirmedBookingNumbers", $this->lng->txt("confirm"));
-		$form->addCommandButton("render", $this->lng->txt("cancel"));
-		
-		return $form;
-	}
-	
-	function confirmBookingNumbers(array $a_objects_counter, $a_group_id, ilPropertyFormGUI $a_form = null)
-	{
-		$tpl = $this->tpl;
-		
-		$this->tabs_gui->clearTargets();
-		$this->tabs_gui->setBackTarget($this->lng->txt('book_back_to_list'), $this->ctrl->getLinkTarget($this, 'render'));
-
-		if(!$a_form)
-		{
-			$a_form = $this->initBookingNumbersForm($a_objects_counter, $a_group_id);
-		}
-	
-		$tpl->setContent($a_form->getHTML());
-	}
-	
-	protected function addDaysDate($a_date, $a_days)
-	{
-		$date = date_parse($a_date);		
-		$stamp = mktime(0, 0, 1, $date["month"], $date["day"]+$a_days, $date["year"]);
-		return date("Y-m-d", $stamp);
-	}
-	
-	protected function addDaysStamp($a_stamp, $a_days)
-	{
-		$date = getDate($a_stamp);		
-		return mktime($date["hours"], $date["minutes"], $date["seconds"], 
-			$date["mon"], $date["mday"]+$a_days, $date["year"]);
-	}
-	
-	public function confirmedBookingNumbersObject()
-	{
-		include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php';								
-		include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
-
-		//get the user who will get the booking.
-		if($_POST['bkusr'])
-		{
-			$this->user_id_to_book = (int)$_POST['bkusr'];
-		}
-
-		// convert post data to initial form config
-		$counter = array();
-		$current_first = $obj_id = null;
-		foreach(array_keys($_POST) as $id)
-		{
-			if(substr($id, 0, 9) == "conf_nr__")
-			{
-				$id = explode("_", substr($id, 9));
-				$counter[$id[0]."_".$id[1]."_".$id[2]] = (int)$id[3];		
-				if(!$current_first)
-				{
-					$current_first = date("Y-m-d", $id[1]);
-				}
-			}
-		}
-		
-		// recurrence
-		
-		// checkInput() has not been called yet, so we have to improvise
-		include_once 'Services/Calendar/classes/class.ilCalendarUtil.php';
-		$end = ilCalendarUtil::parseIncomingDate($_POST["rece"], null);		
-		
-		if((int)$_POST["recm"] > 0 && $end && $current_first)
-		{
-			ksort($counter);			
-			$end = $end->get(IL_CAL_DATE);	
-			$cycle = (int)$_POST["recm"]*7;			
-			$cut = 0;		
-			$org = $counter;
-			while($cut < 1000 && $this->addDaysDate($current_first, $cycle) <= $end)
-			{
-				$cut++;
-				$current_first = null;
-				foreach($org as $item_id => $max)
-				{
-					$parts = explode("_", $item_id);
-					$obj_id = $parts[0];
-					
-					$from = $this->addDaysStamp($parts[1], $cycle*$cut);
-					$to = $this->addDaysStamp($parts[2], $cycle*$cut);
-					
-					$new_item_id = $obj_id."_".$from."_".$to;
-					
-					// form reload because of validation errors
-					if(!isset($counter[$new_item_id]) && date("Y-m-d", $to) <= $end)
-					{							
-						// get max available for added dates
-						$new_max = ilBookingReservation::getAvailableObject(array($obj_id), $from, $to-1, false, true);
-						$new_max = (int)$new_max[$obj_id];
-
-						$counter[$new_item_id] = $new_max;
-
-						if(!$current_first)
-						{
-							$current_first = date("Y-m-d", $from);
-						}
-										
-						// clone input 
-						$_POST["conf_nr__".$new_item_id."_".$new_max] = $_POST["conf_nr__".$item_id."_".$max];		
-					}
-				}							
-			}											
-		}			
-		
-		$group_id = $_POST["grp_id"];
-
-		$form = $this->initBookingNumbersForm($counter, $group_id, true);		
-		if($form->checkInput())
-		{					
-			$success = false;
-			$rsv_ids = array();
-			foreach($counter as $id => $all_nr)
-			{				
-				$book_nr = $form->getInput("conf_nr__".$id."_".$all_nr);
-				$parts = explode("_", $id);
-				$obj_id = $parts[0];
-				$from = $parts[1];
-				$to = $parts[2]-1;
-				
-				// get currently available slots
-				$counter = ilBookingReservation::getAvailableObject(array($obj_id), $from, $to, false, true);
-				$counter = $counter[$obj_id];
-				if($counter)
-				{	
-					// we can only book what is left
-					$book_nr = min($book_nr, $counter);							
-					for($loop = 0; $loop < $book_nr; $loop++)
-					{
-						$rsv_ids[] = $this->processBooking($obj_id, $from, $to, $group_id);
-						$success = $obj_id;									
-					}
-				}
-			}
-			if($success)
-			{
-				$this->saveParticipant();
-				$this->handleBookingSuccess($success, $rsv_ids);
-			}
-			else
-			{
-				ilUtil::sendFailure($this->lng->txt('book_reservation_failed'), true);
-				$this->ctrl->redirect($this, 'render');
-			}
-		}
-		else
-		{			
-			// ilDateTimeInputGUI does NOT add hidden values on disabled!
-
-			$rece_array = explode(".", $_POST['rece']);
-
-			$rece_day = str_pad($rece_array[0], 2, "0", STR_PAD_LEFT);
-			$rece_month = str_pad($rece_array[1], 2, "0", STR_PAD_LEFT);
-			$rece_year = $rece_array[2];
-
-			// ilDateTimeInputGUI will choke on POST array format
-			$_POST["rece"] = null;		
-			
-			$form->setValuesByPost();
-
-			$rece_date = new ilDate($rece_year."-".$rece_month."-".$rece_day, IL_CAL_DATE);
-
-			$form->getItemByPostVar("rece")->setDate($rece_date);
-			$form->getItemByPostVar("recm")->setHideSubForm($_POST["recm"] < 1);
-
-			$hidden_date = new ilHiddenInputGUI("rece");
-			$hidden_date->setValue($rece_date);
-			$form->addItem($hidden_date);
-			
-			return $this->confirmBookingNumbers($counter, $group_id, $form);				
-		}		
-	}
-	
-	/**
-	 * Book object for date
-	 * 
-	 * @param int $a_object_id
-	 * @param int $a_from timestamp
-	 * @param int $a_to timestamp
-	 * @param int $a_group_id 
-	 * @return int
-	 */
-	function processBooking($a_object_id, $a_from = null, $a_to = null, $a_group_id = null)
-	{
-		// #11995
-		$this->checkPermission('read');		
-		
-		include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php';
-		$reservation = new ilBookingReservation();
-		$reservation->setObjectId($a_object_id);
-		$reservation->setUserId($this->user_id_to_book);
-		$reservation->setAssignerId($this->user_id_assigner);
-		$reservation->setFrom($a_from);
-		$reservation->setTo($a_to);
-		$reservation->setGroupId($a_group_id);
-		$reservation->save();
-
-		if($a_from)
-		{
-			$this->lng->loadLanguageModule('dateplaner');
-			include_once 'Services/Calendar/classes/class.ilCalendarUtil.php';
-			include_once 'Services/Calendar/classes/class.ilCalendarCategory.php';
-			$def_cat = ilCalendarUtil::initDefaultCalendarByType(ilCalendarCategory::TYPE_BOOK,$this->user_id_to_book,$this->lng->txt('cal_ch_personal_book'),true);
-
-			include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
-			$object = new ilBookingObject($a_object_id);
-
-			include_once 'Services/Calendar/classes/class.ilCalendarEntry.php';
-			$entry = new ilCalendarEntry;
-			$entry->setStart(new ilDateTime($a_from, IL_CAL_UNIX));
-			$entry->setEnd(new ilDateTime($a_to, IL_CAL_UNIX));
-			$entry->setTitle($this->lng->txt('book_cal_entry').' '.$object->getTitle());
-			$entry->setContextId($reservation->getId());
-			$entry->save();
-
-			include_once 'Services/Calendar/classes/class.ilCalendarCategoryAssignments.php';
-			$assignment = new ilCalendarCategoryAssignments($entry->getEntryId());
-			$assignment->addAssignment($def_cat->getCategoryId());
-		}
-		
-		return $reservation->getId();
-	}
-
-	/**
-	 *  List reservations
-	 */
-	function logObject()
-	{
-		$tpl = $this->tpl;
-
-		$this->tabs_gui->setTabActive('log');
-				
-		$show_all = ($this->checkPermissionBool('write') || $this->object->hasPublicLog());
-		
-		$filter = null;
-		if ($this->book_obj_id > 0)
-		{
-			$filter["object"] = $this->book_obj_id;
-		}
-
-		// coming from participants tab to cancel reservations.
-		if($_GET['user_id'])
-		{
-			$filter["user_id"] = (int)$_GET['user_id'];
-		}
-
-		include_once 'Modules/BookingManager/classes/class.ilBookingReservationsTableGUI.php';
-		$table = new ilBookingReservationsTableGUI($this, 'log', $this->ref_id, 
-			$this->object->getId(), $show_all, 
-			($this->object->getScheduleType() != ilObjBookingPool::TYPE_NO_SCHEDULE),
-			$filter);
-		$tpl->setContent($table->getHTML());
-	}
-	
-	function logDetailsObject()
-	{
-		$tpl = $this->tpl;
-
-		$this->tabs_gui->clearTargets();
-		$this->tabs_gui->setBackTarget($this->lng->txt("back"),
-			$this->ctrl->getLinkTarget($this, "log"));
-				
-		$show_all = ($this->checkPermissionBool('write') ||	$this->object->hasPublicLog());
-		
-		$filter = null;
-		if ($this->book_obj_id > 0)
-		{
-			$filter["object"] = $this->book_obj_id;
-		}
-
-		include_once 'Modules/BookingManager/classes/class.ilBookingReservationsTableGUI.php';
-		$table = new ilBookingReservationsTableGUI($this, 'log', $this->ref_id, 
-			$this->object->getId(), $show_all, 
-			($this->object->getScheduleType() != ilObjBookingPool::TYPE_NO_SCHEDULE),
-			$filter, $this->reservation_id);
-		$tpl->setContent($table->getHTML());
-	}
-	
-	/**
-	 * Change status of given reservations
-	 */
-	function changeStatusObject()
-	{		
-		$this->tabs_gui->setTabActive('log');
-		
-		if(!$_POST['reservation_id'])
-		{
-			ilUtil::sendFailure($this->lng->txt('select_one'));
-			return $this->logObject();
-		}
-
-		if ($this->checkPermissionBool('write'))
-		{
-			include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php';
-			ilBookingReservation::changeStatus($_POST['reservation_id'], (int)$_POST['tstatus']);
-		}
-
-		ilUtil::sendSuccess($this->lng->txt('settings_saved'), true);
-		return $this->ctrl->redirect($this, 'log');
-	}
-
-	/**
-	 * Apply filter from reservations table gui
-	 */
-	function applyLogFilterObject()
-	{				
-		$show_all = ($this->checkPermissionBool('write') ||	$this->object->hasPublicLog());
-		
-		include_once 'Modules/BookingManager/classes/class.ilBookingReservationsTableGUI.php';
-		$table = new ilBookingReservationsTableGUI($this, 'log', $this->ref_id,
-			$this->object->getId(), $show_all,
-			($this->object->getScheduleType() != ilObjBookingPool::TYPE_NO_SCHEDULE));
-		$table->resetOffset();
-		$table->writeFilterToSession();
-		$this->logObject();
-	}
-
-	/**
-	 * Reset filter in reservations table gui
-	 */
-	function resetLogFilterObject()
-	{				
-		$show_all = ($this->checkPermissionBool('write') ||	$this->object->hasPublicLog());
-		
-		include_once 'Modules/BookingManager/classes/class.ilBookingReservationsTableGUI.php';
-		$table = new ilBookingReservationsTableGUI($this, 'log', $this->ref_id,
-			$this->object->getId(), $show_all,
-			($this->object->getScheduleType() != ilObjBookingPool::TYPE_NO_SCHEDULE));
-		$table->resetOffset();
-		$table->resetFilter();
-		$this->logObject();
-	}
-
-	public static function _goto($a_target)
-	{
-		global $DIC;
-
-		$ilAccess = $DIC->access();
-		$lng = $DIC->language();
-
-		if ($ilAccess->checkAccess("read", "", $a_target))
-		{
-			ilObjectGUI::_gotoRepositoryNode($a_target, "render");
-		}
-		else if ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID))
-		{
-			ilUtil::sendFailure(sprintf($lng->txt("msg_no_perm_read_item"),
-				ilObject::_lookupTitle(ilObject::_lookupObjId($a_target))), true);
-			ilObjectGUI::_gotoRepositoryRoot();
-		}	
-	}
-
-	/**
-	* 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 infoScreenObject()
-	{
-		$this->ctrl->setCmd("showSummary");
-		$this->ctrl->setCmdClass("ilinfoscreengui");
-		$this->infoScreen();
-	}
-
-	function infoScreen()
-	{
-		$ilCtrl = $this->ctrl;
-
-		$this->tabs_gui->setTabActive('info');
-		
-		$this->checkPermission("visible");
-
-		include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php");
-		$info = new ilInfoScreenGUI($this);
-
-		$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);
-			}
-		}
-
-		// forward the command
-		if ($ilCtrl->getNextClass() == "ilinfoscreengui")
-		{
-			$ilCtrl->forwardCommand($info);
-		}
-		else
-		{
-			return $ilCtrl->getHTML($info);
-		}
-	}
-	
-	protected function getLogReservationIds()
-	{		
-		if($_POST["mrsv"])
-		{
-			return $_POST["mrsv"];			
-		}
-		else if($this->reservation_id > 0)
-		{
-			return array($this->reservation_id);
-		}				
-	}
-	
-	function rsvConfirmCancelObject()
-	{
-		$ilCtrl = $this->ctrl;
-		$lng = $this->lng;
-		$tpl = $this->tpl;
-		$ilUser = $this->user;
-	
-		$ids = $this->getLogReservationIds();
-		if (!is_array($ids) || !sizeof($ids))
-		{
-			$this->ctrl->redirect($this, 'log');
-		}
-		
-		include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
-		include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php';
-		
-		$max = array();
-		foreach($ids as $idx => $id)
-		{
-			if(!is_numeric($id))
-			{
-				list($obj_id, $user_id, $from, $to) = explode("_", $id);
-				
-				$valid_ids = array();				
-				foreach(ilBookingObject::getList($this->object->getId()) as $item)
-				{
-					$valid_ids[$item["booking_object_id"]] = $item["title"];
-				}		
-						
-				if(($this->checkPermissionBool("write") || $user_id == $ilUser->getId()) &&
-					$from > time() &&
-					in_array($obj_id, array_keys($valid_ids)))
-				{				
-					$rsv_ids = ilBookingReservation::getCancelDetails($obj_id, $user_id, $from, $to);					
-					if(!sizeof($rsv_ids))
-					{
-						unset($ids[$idx]);
-					}
-					if(sizeof($rsv_ids) > 1)
-					{
-						$max[$id] = sizeof($rsv_ids);
-						$ids[$idx] = $rsv_ids;
-					}
-					else
-					{
-						// only 1 in group?  treat as normal reservation
-						$ids[$idx] = array_shift($rsv_ids);
-					}
-				}
-				else
-				{
-					unset($ids[$idx]);
-				}				
-			}
-		}
-
-        if (!is_array($ids) || !sizeof($ids))
-		{
-			$this->ctrl->redirect($this, 'log');
-		}
-		
-		// show form instead
-		if(sizeof($max) && max($max) > 1)
-		{
-			return $this->rsvConfirmCancelAggregationObject($ids);			
-		}
-		
-		$this->tabs_gui->clearTargets();
-		$this->tabs_gui->setBackTarget($lng->txt("back"),
-			$ilCtrl->getLinkTarget($this, "log"));
-			
-		$this->setHelpId("cancel_booking");		
-		
-		include_once 'Services/Utilities/classes/class.ilConfirmationGUI.php';
-		$conf = new ilConfirmationGUI();
-		$conf->setFormAction($ilCtrl->getFormAction($this, 'rsvCancel'));
-		$conf->setHeaderText($lng->txt('book_confirm_cancel'));
-		$conf->setConfirm($lng->txt('book_set_cancel'), 'rsvCancel');
-		$conf->setCancel($lng->txt('cancel'), 'log');
-
-		foreach($ids as $id)
-		{		
-			$rsv = new ilBookingReservation($id);
-			$obj = new ilBookingObject($rsv->getObjectId());
-			
-			$details = $obj->getTitle();
-			if($this->object->getScheduleType() != ilObjBookingPool::TYPE_NO_SCHEDULE)
-			{
-				$details .= ", ".ilDatePresentation::formatPeriod(
-					new ilDateTime($rsv->getFrom(), IL_CAL_UNIX),
-					new ilDateTime($rsv->getTo()+1, IL_CAL_UNIX));
-			}
-			
-			$conf->addItem('rsv_id[]', $id, $details);		
-		}
-	
-		$tpl->setContent($conf->getHTML());		
-	}
-	
-	function rsvConfirmCancelAggregationForm($a_ids)
-	{		
-		include_once 'Services/Form/classes/class.ilPropertyFormGUI.php';
-		$form = new ilPropertyFormGUI();
-		$form->setFormAction($this->ctrl->getFormAction($this, "rsvCancel"));
-		$form->setTitle($this->lng->txt("book_confirm_cancel_aggregation"));
-		
-		include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
-		include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php';	
-		
-		ilDatePresentation::setUseRelativeDates(false);
-		
-		foreach($a_ids as $idx => $ids)
-		{			
-			if(is_array($ids))
-			{
-				$first = $ids;
-				$first = array_shift($first);
-			}
-			else
-			{
-				$first = $ids;				
-			}
-			
-			$rsv = new ilBookingReservation($first);
-			$obj = new ilBookingObject($rsv->getObjectId());
-		
-			$caption = $obj->getTitle().", ".ilDatePresentation::formatPeriod(
-					new ilDateTime($rsv->getFrom(), IL_CAL_UNIX),
-					new ilDateTime($rsv->getTo()+1, IL_CAL_UNIX));
-			
-			// #17869
-			if(is_array($ids))
-			{
-				$caption .= " (".sizeof($ids).")";
-			}
-			
-			$item = new ilNumberInputGUI($caption, "rsv_id_".$idx);
-			$item->setRequired(true);
-			$item->setMinValue(0);
-			$item->setSize(4);			
-			$form->addItem($item);
-			
-			if(is_array($ids))
-			{
-				$item->setMaxValue(sizeof($ids));
-				
-				foreach($ids as $id)
-				{
-					$hidden = new ilHiddenInputGUI("rsv_aggr[".$idx."][]");
-					$hidden->setValue($id);
-					$form->addItem($hidden);
-				}
-			}
-			else 
-			{
-				$item->setMaxValue(1);
-				
-				$hidden = new ilHiddenInputGUI("rsv_aggr[".$idx."]");
-				$hidden->setValue($ids);
-				$form->addItem($hidden);
-			}	
-						
-			if($_POST["rsv_id_".$idx])
-			{
-				$item->setValue((int)$_POST["rsv_id_".$idx]);
-			}				
-		}
-				
-		$form->addCommandButton("rsvCancel", $this->lng->txt("confirm"));
-		$form->addCommandButton("log", $this->lng->txt("cancel"));	
-		
-		return $form;
-	}
-	
-	function rsvConfirmCancelAggregationObject(array $a_ids = null)
-	{
-		$tpl = $this->tpl;
-		$ilCtrl = $this->ctrl;
-		$lng = $this->lng;
-		
-		$this->tabs_gui->clearTargets();
-		$this->tabs_gui->setBackTarget($lng->txt("back"),
-			$ilCtrl->getLinkTarget($this, "log"));
-		
-		$this->setHelpId("cancel_booking");		
-		
-		// #13511
-		ilUtil::sendQuestion($lng->txt("book_confirm_cancel"));		
-		
-		$form = $this->rsvConfirmCancelAggregationForm($a_ids);
-		
-		$tpl->setContent($form->getHTML());		
-	}
-
-	function rsvCancelObject()
-	{
-		$ilUser = $this->user;
-		$tpl = $this->tpl;
-		$lng = $this->lng;
-		$ilCtrl = $this->ctrl;
-				
-		$ids = $_POST["rsv_id"];
-		
-		// parse aggregation form
-		if($_POST["rsv_aggr"])
-		{			
-			$form = $this->rsvConfirmCancelAggregationForm($_POST["rsv_aggr"]);
-			if(!$form->checkInput())
-			{
-				$this->tabs_gui->clearTargets();
-				$this->tabs_gui->setBackTarget($lng->txt("back"),
-					$ilCtrl->getLinkTarget($this, "log"));
-				
-				return $tpl->setContent($form->getHTML());		
-			}
-			
-			$ids = array();
-			foreach($_POST["rsv_aggr"] as $idx => $aggr_ids)
-			{
-				$max = (int)$_POST["rsv_id_".$idx];
-				if($max)
-				{
-					if(!is_array($aggr_ids))
-					{
-						$ids[] = $aggr_ids;
-					}
-					else
-					{
-						$aggr_ids = array_slice($aggr_ids, 0, $max);
-						$ids = array_merge($ids, $aggr_ids);
-					}						
-				}
-			}			
-		}
-		
-		if($ids)
-		{
-			include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php';
-			foreach($ids as $id)
-			{				
-				$obj = new ilBookingReservation($id);
-			
-				if (!$this->checkPermissionBool("write") && $obj->getUserId() != $ilUser->getId())
-				{
-					ilUtil::sendFailure($this->lng->txt('permission_denied'), true);
-					$this->ctrl->redirect($this, 'log');
-				}
-
-				$obj->setStatus(ilBookingReservation::STATUS_CANCELLED);
-				$obj->update();
-
-				if($this->object->getScheduleType() != ilObjBookingPool::TYPE_NO_SCHEDULE)
-				{
-					// remove user calendar entry (#11086)
-					$cal_entry_id = $obj->getCalendarEntry();		
-					if($cal_entry_id)
-					{
-						include_once 'Services/Calendar/classes/class.ilCalendarEntry.php';
-						$entry = new ilCalendarEntry($cal_entry_id);
-						$entry->delete();
-					}
-				}
-			}
-		}
-
-		ilUtil::sendSuccess($this->lng->txt('settings_saved'));
-		$this->logObject();
-	}
-
-	function rsvInUseObject()
-	{		
-		$this->checkPermission("write");
-
-		$ids = $this->getLogReservationIds();
-		if($ids)
-		{
-			include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php';		
-			foreach($ids as $id)
-			{		
-				$obj = new ilBookingReservation($id);
-				$obj->setStatus(ilBookingReservation::STATUS_IN_USE);
-				$obj->update();
-			}
-		}
-
-		ilUtil::sendSuccess($this->lng->txt('settings_saved'));
-		$this->logObject();
-	}
-
-	function rsvNotInUseObject()
-	{
-		$this->checkPermission("write");
-		
-		$ids = $this->getLogReservationIds();
-		if($ids)
-		{
-			include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php';		
-			foreach($ids as $id)
-			{	
-				$obj = new ilBookingReservation($id);
-				$obj->setStatus(NULL);
-				$obj->update();
-			}
-		}
-
-		ilUtil::sendSuccess($this->lng->txt('settings_saved'));
-		$this->logObject();
-	}
-
-	function showProfileObject()
-	{
-		$tpl = $this->tpl;
-		$ilCtrl = $this->ctrl;
-		
-		$this->tabs_gui->clearTargets();
-		
-		$user_id = $this->profile_user_id;
-		
-		include_once 'Services/User/classes/class.ilPublicUserProfileGUI.php';
-		$profile = new ilPublicUserProfileGUI($user_id);
-		$profile->setBackUrl($this->ctrl->getLinkTarget($this, 'log'));
-		$tpl->setContent($ilCtrl->getHTML($profile));
-	}
-	
-	public function addLocatorItems()
-	{
-		$ilLocator = $this->locator;
-		
-		if (is_object($this->object))
-		{
-			$ilLocator->addItem($this->object->getTitle(), $this->ctrl->getLinkTarget($this, "render"), "", $this->object->getRefId());
-		}
-	}
-
-	/**
-	 * @inheritdoc
-	 */
-	protected function initHeaderAction($a_sub_type = null, $a_sub_id = null)
-	{
-		$access = $this->access;
-		$user = $this->user;
-		$ctrl = $this->ctrl;
-		$lng = $this->lng;
-
-		$lng->loadLanguageModule("noti");
-
-		$lg = parent::initHeaderAction($a_sub_type, $a_sub_id);
-
-		if($lg && $access->checkAccess("read", "", $this->ref_id))
-		{
-			// notification
-			if(true)
-			{
-				if(!ilNotification::hasNotification(ilNotification::TYPE_BOOK, $user->getId(), $this->object->getId()))
-				{
-					$lg->addHeaderIcon("not_icon",
-						ilUtil::getImagePath("notification_off.svg"),
-						$lng->txt("noti_notification_deactivated"));
-
-					$ctrl->setParameter($this, "ntf", 1);
-					$caption = "noti_activate_notification";
-				}
-				else
-				{
-					$lg->addHeaderIcon("not_icon",
-						ilUtil::getImagePath("notification_on.svg"),
-						$lng->txt("noti_notification_activated"));
-
-					$ctrl->setParameter($this, "ntf", 0);
-					$caption = "noti_deactivate_notification";
-				}
-
-				$lg->addCustomCommand($ctrl->getLinkTarget($this, "saveNotification"),
-					$caption);
-
-				$ctrl->setParameter($this, "ntf", "");
-			}
-		}
-
-		return $lg;
-	}
-
-	/**
-	 * Save notification
-	 */
-	public function saveNotificationObject()
-	{
-		$ctrl = $this->ctrl;
-		$user = $this->user;
-
-
-		switch ($_GET["ntf"]) {
-			case 0:
-				ilNotification::setNotification(ilNotification::TYPE_BOOK, $user->getId(), $this->object->getId(), false);
-				break;
-
-			case 1:
-				ilNotification::setNotification(ilNotification::TYPE_BOOK, $user->getId(), $this->object->getId(), true);
-				break;
-		}
-		$ctrl->redirect($this, "render");
-	}
-	/*
-	 * save booking participant.
-	 */
-	protected function saveParticipant()
-	{
-		include_once ("./Modules/BookingManager/classes/class.ilBookingParticipant.php");
-		$participant = new ilBookingParticipant($this->user_id_to_book, $this->object->getId());
-	}
-
-	/**
-	 * Create reservations for a bunch of booking pool participants.
-	 */
-	function bookMultipleParticipantsObject()
-	{
-		if($_POST["mass"]) {
-			$participants = $_POST["mass"];
-		} else {
-			$this->ctrl->redirectByClass('ilbookingobjectgui', 'render');
-		}
-
-		$this->tabs->clearTargets();
-		$this->ctrl->setParameterByClass('ilbookingobjectgui','object_id',$this->book_obj_id);
-		$this->tabs->setBackTarget($this->lng->txt("back"),$this->ctrl->getLinkTargetByClass('ilbookingobjectgui','assignparticipants'));
-		$this->ctrl->setParameterByClass('ilbookingobjectgui', 'object_id','');
-
-		$conf = new ilConfirmationGUI();
-		$conf->setFormAction($this->ctrl->getFormAction($this));
-
-		//add user list as items.
-		foreach($participants as $id)
-		{
-			$name = ilObjUser::_lookupFullname($id);
-			$conf->addItem("participants[]", $id, $name);
-		}
-
-		$available = ilBookingReservation::numAvailableFromObjectNoSchedule($this->book_obj_id);
-		if(sizeof($participants) > $available)
-		{
-			$obj = new ilBookingObject($this->book_obj_id);
-			$conf->setHeaderText(
-				sprintf(
-					$this->lng->txt('book_limit_objects_available'),
-					sizeof($participants),
-					$obj->getTitle(),
-					$available
-				)
-			);
-		}
-		else
-		{
-			$conf->setHeaderText($this->lng->txt('book_confirm_booking_no_schedule'));
-			$conf->addHiddenItem("object_id", $this->book_obj_id);
-			$conf->setConfirm($this->lng->txt("assign"), "saveMultipleBookings");
-		}
-
-		$conf->setCancel($this->lng->txt("cancel"), 'redirectToList');
-		$this->tpl->setContent($conf->getHTML());
-	}
-
-	public function redirectToListObject()
-	{
-		$this->ctrl->setParameterByClass('ilbookingobjectgui','object_id',$this->book_obj_id);
-		$this->ctrl->redirectByClass('ilbookingobjectgui', 'assignParticipants');
-	}
-
-	/**
-	 * Save multiple users reservations for one booking pool object.
-	 * //TODO check if object/user exist in the DB,
-	 */
-	public function saveMultipleBookingsObject()
-	{
-		if($_POST["participants"] && $_POST['object_id']) {
-			$participants = $_POST["participants"];
-			$this->book_obj_id = $_POST['object_id'];
-		} else {
-			$this->ctrl->redirectByClass('ilbookingobjectgui', 'render');
-		}
-		$rsv_ids = array();
-		foreach($participants as $id)
-		{
-			$this->user_id_to_book = $id;
-			$rsv_ids[] = $this->processBooking($this->book_obj_id);
-		}
-
-		if(sizeof($rsv_ids))
-		{
-			ilUtil::sendSuccess("booking_multiple_succesfully");
-			$this->ctrl->redirectByClass('ilbookingobjectgui', 'render');
-		}
-		else
-		{
-			ilUtil::sendFailure($this->lng->txt('book_reservation_failed_overbooked'), true);
-			$this->ctrl->redirect($this, 'render');
-		}
-
-	}
-}
+        if ($this->checkPermissionBool('edit_permission')) {
+            $this->tabs_gui->addTab(
+                    "perm_settings",
+                    $this->lng->txt("perm_settings"),
+                    $this->ctrl->getLinkTargetByClass("ilpermissiongui", "perm")
+                );
+        }
+    }
+    
+    protected function setHelpId($a_id)
+    {
+        $ilHelp = $this->help;
+        
+        $object_subtype = ($this->object->getScheduleType() == ilObjBookingPool::TYPE_FIX_SCHEDULE)
+            ? '-schedule'
+            : '-nonschedule';
+        
+        $ilHelp->setScreenIdComponent('book');
+        $ilHelp->setScreenId('object' . $object_subtype);
+        $ilHelp->setSubScreenId($a_id);
+    }
+
+    /**
+     * First step in booking process
+     */
+    public function bookObject()
+    {
+        $tpl = $this->tpl;
+        
+        $this->tabs_gui->clearTargets();
+        $this->tabs_gui->setBackTarget($this->lng->txt('book_back_to_list'), $this->ctrl->getLinkTarget($this, 'render'));
+        
+        $this->setHelpId("book");
+
+        include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
+        $obj = new ilBookingObject((int) $_GET['object_id']);
+                
+        $this->lng->loadLanguageModule("dateplaner");
+        $this->ctrl->setParameter($this, 'object_id', $obj->getId());
+
+        if ($this->user_id_to_book != $this->user_id_assigner) {
+            $this->ctrl->setParameter($this, 'bkusr', $this->user_id_to_book);
+        }
+
+        if ($this->object->getScheduleType() == ilObjBookingPool::TYPE_FIX_SCHEDULE) {
+            include_once 'Modules/BookingManager/classes/class.ilBookingSchedule.php';
+            $schedule = new ilBookingSchedule($obj->getScheduleId());
+
+            $tpl->setContent($this->renderSlots($schedule, array($obj->getId()), $obj->getTitle()));
+        } else {
+            include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php");
+            $cgui = new ilConfirmationGUI();
+            $cgui->setHeaderText($this->lng->txt("book_confirm_booking_no_schedule"));
+
+            $cgui->setFormAction($this->ctrl->getFormAction($this));
+            $cgui->setCancel($this->lng->txt("cancel"), "render");
+            $cgui->setConfirm($this->lng->txt("confirm"), "confirmedBooking");
+
+            $cgui->addItem("object_id", $obj->getId(), $obj->getTitle());
+
+            if ($_GET['part_view'] == ilBookingParticipantGUI::PARTICIPANT_VIEW) {
+                $cgui->addHiddenItem("part_view", ilBookingParticipantGUI::PARTICIPANT_VIEW);
+            }
+
+            $tpl->setContent($cgui->getHTML());
+        }
+    }
+
+    protected function renderSlots(ilBookingSchedule $schedule, array $object_ids, $title)
+    {
+        $ilUser = $this->user;
+        
+        // fix
+        if (!$schedule->getRaster()) {
+            $mytpl = new ilTemplate('tpl.booking_reservation_fix.html', true, true, 'Modules/BookingManager');
+
+            $mytpl->setVariable('FORM_ACTION', $this->ctrl->getFormAction($this));
+            $mytpl->setVariable('TXT_TITLE', $this->lng->txt('book_reservation_title'));
+            $mytpl->setVariable('TXT_INFO', $this->lng->txt('book_reservation_fix_info'));
+            $mytpl->setVariable('TXT_OBJECT', $title);
+            $mytpl->setVariable('TXT_CMD_BOOK', $this->lng->txt('book_confirm_booking'));
+            $mytpl->setVariable('TXT_CMD_CANCEL', $this->lng->txt('cancel'));
+
+            include_once 'Services/Calendar/classes/class.ilCalendarUserSettings.php';
+            
+            $user_settings = ilCalendarUserSettings::_getInstanceByUserId($ilUser->getId());
+
+            $morning_aggr = $user_settings->getDayStart();
+            $evening_aggr = $user_settings->getDayEnd();
+            $hours = array();
+            for ($i = $morning_aggr;$i <= $evening_aggr;$i++) {
+                switch ($user_settings->getTimeFormat()) {
+                    case ilCalendarSettings::TIME_FORMAT_24:
+                        if ($morning_aggr > 0 && $i == $morning_aggr) {
+                            $hours[$i] = sprintf('%02d:00', 0) . "-";
+                        }
+                        $hours[$i].= sprintf('%02d:00', $i);
+                        if ($evening_aggr < 23 && $i == $evening_aggr) {
+                            $hours[$i].= "-" . sprintf('%02d:00', 23);
+                        }
+                        break;
+
+                    case ilCalendarSettings::TIME_FORMAT_12:
+                        if ($morning_aggr > 0 && $i == $morning_aggr) {
+                            $hours[$i] = date('h a', mktime(0, 0, 0, 1, 1, 2000)) . "-";
+                        }
+                        $hours[$i].= date('h a', mktime($i, 0, 0, 1, 1, 2000));
+                        if ($evening_aggr < 23 && $i == $evening_aggr) {
+                            $hours[$i].= "-" . date('h a', mktime(23, 0, 0, 1, 1, 2000));
+                        }
+                        break;
+                }
+            }
+
+            if ($this->seed != "") {
+                $find_first_open = false;
+                $seed = new ilDate($this->seed, IL_CAL_DATE);
+            } else {
+                $find_first_open = true;
+                $seed = ($this->sseed != "")
+                    ? new ilDate($this->sseed, IL_CAL_DATE)
+                    : new ilDate(time(), IL_CAL_UNIX);
+            }
+            
+            include_once 'Services/Calendar/classes/class.ilCalendarUtil.php';
+            include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php';
+            $week_start = $user_settings->getWeekStart();
+            
+            if (!$find_first_open) {
+                $dates = array();
+                $this->buildDatesBySchedule($week_start, $hours, $schedule, $object_ids, $seed, $dates);
+            } else {
+                $dates = array();
+
+                //loop for 1 week
+                $has_open_slot = $this->buildDatesBySchedule($week_start, $hours, $schedule, $object_ids, $seed, $dates);
+                
+                // find first open slot
+                if (!$has_open_slot) {
+                    // 1 year is limit for search
+                    $limit = clone($seed);
+                    $limit->increment(ilDate::YEAR, 1);
+                    $limit = $limit->get(IL_CAL_UNIX);
+                    
+                    while (!$has_open_slot && $seed->get(IL_CAL_UNIX) < $limit) {
+                        $seed->increment(ilDate::WEEK, 1);
+                        
+                        $dates = array();
+                        $has_open_slot = $this->buildDatesBySchedule($week_start, $hours, $schedule, $object_ids, $seed, $dates);
+                    }
+                }
+            }
+            
+            include_once 'Services/Calendar/classes/class.ilCalendarHeaderNavigationGUI.php';
+            $navigation = new ilCalendarHeaderNavigationGUI($this, $seed, ilDateTime::WEEK, 'book');
+            $mytpl->setVariable('NAVIGATION', $navigation->getHTML());
+
+            foreach (ilCalendarUtil::_buildWeekDayList($seed, $week_start)->get() as $date) {
+                $date_info = $date->get(IL_CAL_FKT_GETDATE, '', 'UTC');
+
+                $mytpl->setCurrentBlock('weekdays');
+                $mytpl->setVariable('TXT_WEEKDAY', ilCalendarUtil:: _numericDayToString($date_info['wday']));
+                $mytpl->setVariable('TXT_DATE', $date_info['mday'] . ' ' . ilCalendarUtil:: _numericMonthToString($date_info['mon']));
+                $mytpl->parseCurrentBlock();
+            }
+            
+            include_once 'Services/Calendar/classes/class.ilCalendarAppointmentColors.php';
+            include_once 'Services/Calendar/classes/class.ilCalendarUtil.php';
+            $color = array();
+            $all = ilCalendarAppointmentColors::_getColorsByType('crs');
+            for ($loop = 0; $loop < 7; $loop++) {
+                $col = $all[$loop];
+                $fnt = ilCalendarUtil::calculateFontColor($col);
+                $color[$loop+1] = 'border-bottom: 1px solid ' . $col . '; background-color: ' . $col . '; color: ' . $fnt;
+            }
+            
+            $counter = 0;
+            foreach ($dates as $hour => $days) {
+                $caption = $days;
+                $caption = array_shift($caption);
+
+                for ($loop = 1; $loop < 8; $loop++) {
+                    if (!isset($days[$loop])) {
+                        $mytpl->setCurrentBlock('dates');
+                        $mytpl->setVariable('DUMMY', ' ');
+                        $mytpl->parseCurrentBlock();
+                    } else {
+                        if (isset($days[$loop]['captions'])) {
+                            foreach ($days[$loop]['captions'] as $slot_id => $slot_caption) {
+                                $mytpl->setCurrentBlock('choice');
+                                $mytpl->setVariable('TXT_DATE', $slot_caption);
+                                $mytpl->setVariable('VALUE_DATE', $slot_id);
+                                $mytpl->setVariable('DATE_COLOR', $color[$loop]);
+                                $mytpl->setVariable(
+                                    'TXT_AVAILABLE',
+                                    sprintf(
+                                        $this->lng->txt('book_reservation_available'),
+                                        $days[$loop]['available'][$slot_id]
+                                    )
+                                );
+                                $mytpl->parseCurrentBlock();
+                            }
+
+                            $mytpl->setCurrentBlock('dates');
+                            $mytpl->setVariable('DUMMY', '');
+                            $mytpl->parseCurrentBlock();
+                        } elseif (isset($days[$loop]['in_slot'])) {
+                            $mytpl->setCurrentBlock('dates');
+                            $mytpl->setVariable('DATE_COLOR', $color[$loop]);
+                            $mytpl->parseCurrentBlock();
+                        } else {
+                            $mytpl->setCurrentBlock('dates');
+                            $mytpl->setVariable('DUMMY', ' ');
+                            $mytpl->parseCurrentBlock();
+                        }
+                    }
+                }
+
+                $mytpl->setCurrentBlock('slots');
+                $mytpl->setVariable('TXT_HOUR', $caption);
+                if ($counter%2) {
+                    $mytpl->setVariable('CSS_ROW', 'tblrow1');
+                } else {
+                    $mytpl->setVariable('CSS_ROW', 'tblrow2');
+                }
+                $mytpl->parseCurrentBlock();
+
+                $counter++;
+            }
+        }
+        // flexible
+        else {
+            // :TODO: inactive for now
+        }
+        
+        return $mytpl->get();
+    }
+    
+    protected function buildDatesBySchedule($week_start, array $hours, $schedule, array $object_ids, $seed, array &$dates)
+    {
+        $ilUser = $this->user;
+        
+        include_once 'Services/Calendar/classes/class.ilCalendarUserSettings.php';
+        $user_settings = ilCalendarUserSettings::_getInstanceByUserId($ilUser->getId());
+        
+        $map = array('mo', 'tu', 'we', 'th', 'fr', 'sa', 'su');
+        $definition = $schedule->getDefinition();
+        
+        $av_from = ($schedule->getAvailabilityFrom() && !$schedule->getAvailabilityFrom()->isNull())
+            ? $schedule->getAvailabilityFrom()->get(IL_CAL_DATE)
+            : null;
+        $av_to = ($schedule->getAvailabilityTo() && !$schedule->getAvailabilityTo()->isNull())
+            ? $schedule->getAvailabilityTo()->get(IL_CAL_DATE)
+            : null;
+        
+        $has_open_slot = false;
+        foreach (ilCalendarUtil::_buildWeekDayList($seed, $week_start)->get() as $date) {
+            $date_info = $date->get(IL_CAL_FKT_GETDATE, '', 'UTC');
+
+            #24045 and #24936
+            if ($av_from || $av_to) {
+                $today = $date->get(IL_CAL_DATE);
+
+                if ($av_from && $av_from > $today) {
+                    continue;
+                }
+
+                if ($av_to && $av_to < $today) {
+                    continue;
+                }
+            }
+
+            $slots = array();
+            if (isset($definition[$map[$date_info['isoday']-1]])) {
+                $slots = array();
+                foreach ($definition[$map[$date_info['isoday']-1]] as $slot) {
+                    $slot = explode('-', $slot);
+                    $slots[] = array('from'=>str_replace(':', '', $slot[0]),
+                        'to'=>str_replace(':', '', $slot[1]));
+                }
+            }
+
+            $last = array_pop(array_keys($hours));
+            $slot_captions = array();
+            foreach ($hours as $hour => $period) {
+                $dates[$hour][0] = $period;
+                
+                $period = explode("-", $period);
+                
+                // #13738
+                if ($user_settings->getTimeFormat() == ilCalendarSettings::TIME_FORMAT_12) {
+                    $period[0] = date("H", strtotime($period[0]));
+                    if (sizeof($period) == 2) {
+                        $period[1] = date("H", strtotime($period[1]));
+                    }
+                }
+                
+                if (sizeof($period) == 1) {
+                    $period_from = (int) substr($period[0], 0, 2) . "00";
+                    $period_to = (int) substr($period[0], 0, 2) . "59";
+                } else {
+                    $period_from = (int) substr($period[0], 0, 2) . "00";
+                    $period_to = (int) substr($period[1], 0, 2) . "59";
+                }
+
+                $column = $date_info['isoday'];
+                if (!$week_start) {
+                    if ($column < 7) {
+                        $column++;
+                    } else {
+                        $column = 1;
+                    }
+                }
+
+                if (sizeof($slots)) {
+                    $in = false;
+                    foreach ($slots as $slot) {
+                        $slot_from = mktime(substr($slot['from'], 0, 2), substr($slot['from'], 2, 2), 0, $date_info["mon"], $date_info["mday"], $date_info["year"]);
+                        $slot_to = mktime(substr($slot['to'], 0, 2), substr($slot['to'], 2, 2), 0, $date_info["mon"], $date_info["mday"], $date_info["year"]);
+
+                        // always single object, we can sum up
+                        $nr_available = (array) ilBookingReservation::getAvailableObject($object_ids, $slot_from, $slot_to-1, false, true);
+                        
+                        // any objects available?
+                        if (!array_sum($nr_available)) {
+                            continue;
+                        }
+                        
+                        // check deadline
+                        if ($schedule->getDeadline() >= 0) {
+                            // 0-n hours before slots begins
+                            if ($slot_from < (time()+$schedule->getDeadline()*60*60)) {
+                                continue;
+                            }
+                        } else {
+                            // running slots can be booked, only ended slots are invalid
+                            if ($slot_to < time()) {
+                                continue;
+                            }
+                        }
+                        
+                        // is slot active in current hour?
+                        if ((int) $slot['from'] < $period_to && (int) $slot['to'] > $period_from) {
+                            $from = ilDatePresentation::formatDate(new ilDateTime($slot_from, IL_CAL_UNIX));
+                            $from = array_pop(explode(' ', $from));
+                            $to = ilDatePresentation::formatDate(new ilDateTime($slot_to, IL_CAL_UNIX));
+                            $to = array_pop(explode(' ', $to));
+
+                            // show caption (first hour) of slot
+                            $id = $slot_from . '_' . $slot_to;
+                            if (!in_array($id, $slot_captions)) {
+                                $dates[$hour][$column]['captions'][$id] = $from . '-' . $to;
+                                $dates[$hour][$column]['available'][$id] = array_sum($nr_available);
+                                $slot_captions[] = $id;
+                            }
+
+                            $in = true;
+                        }
+                    }
+                    // (any) active slot
+                    if ($in) {
+                        $has_open_slot = true;
+                        $dates[$hour][$column]['in_slot'] = $in;
+                    }
+                }
+            }
+        }
+
+        return $has_open_slot;
+    }
+
+    /**
+     * Book object - either of type or specific - for given dates
+     */
+    public function confirmedBookingObject()
+    {
+        $ilUser = $this->user;
+        
+        include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
+        include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php';
+        
+        $success = false;
+        $rsv_ids = array();
+        
+        if ($this->object->getScheduleType() == ilObjBookingPool::TYPE_NO_SCHEDULE) {
+            if ($this->book_obj_id > 0) {
+                $object_id = $this->book_obj_id;
+                if ($object_id) {
+                    if (ilBookingReservation::isObjectAvailableNoSchedule($object_id) &&
+                        !ilBookingReservation::getObjectReservationForUser($object_id, $this->user_id_to_book)) { // #18304
+                        $rsv_ids[] = $this->processBooking($object_id);
+                        $success = $object_id;
+                    } else {
+                        // #11852
+                        ilUtil::sendFailure($this->lng->txt('book_reservation_failed_overbooked'), true);
+                        $this->ctrl->redirect($this, 'render');
+                    }
+                }
+            }
+        } else {
+            if (!isset($_POST['date'])) {
+                ilUtil::sendFailure($this->lng->txt('select_one'));
+                return $this->bookObject();
+            }
+                        
+            // single object reservation(s)
+            if ($this->book_obj_id > 0) {
+                $confirm = array();
+                
+                $object_id = $this->book_obj_id;
+                if ($object_id) {
+                    $group_id = null;
+                    $nr = ilBookingObject::getNrOfItemsForObjects(array($object_id));
+                    // needed for recurrence
+                    $group_id = ilBookingReservation::getNewGroupId();
+                    foreach ($_POST['date'] as $date) {
+                        $fromto = explode('_', $date);
+                        $fromto[1]--;
+
+                        $counter = ilBookingReservation::getAvailableObject(array($object_id), $fromto[0], $fromto[1], false, true);
+                        $counter = $counter[$object_id];
+                        if ($counter) {
+                            // needed for recurrence
+                            $confirm[$object_id . "_" . $fromto[0] . "_" . ($fromto[1]+1)] = $counter;
+                        }
+                    }
+                }
+                
+                if (sizeof($confirm)) {
+                    return $this->confirmBookingNumbers($confirm, $group_id);
+                }
+            }
+        }
+        
+        if ($success) {
+            $this->saveParticipant();
+            $this->handleBookingSuccess($success, $rsv_ids);
+        } else {
+            ilUtil::sendFailure($this->lng->txt('book_reservation_failed'), true);
+            $this->ctrl->redirect($this, 'book');
+        }
+    }
+    
+    protected function handleBookingSuccess($a_obj_id, array $a_rsv_ids = null)
+    {
+        ilUtil::sendSuccess($this->lng->txt('book_reservation_confirmed'), true);
+            
+        // show post booking information?
+        include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
+        $obj = new ilBookingObject($a_obj_id);
+        $pfile = $obj->getPostFile();
+        $ptext = $obj->getPostText();
+        if (trim($ptext) || $pfile) {
+            if (sizeof($a_rsv_ids)) {
+                $this->ctrl->setParameterByClass('ilbookingobjectgui', 'rsv_ids', implode(";", $a_rsv_ids));
+            }
+            $this->ctrl->setParameterByClass('ilbookingobjectgui', 'object_id', $obj->getId());
+            $this->ctrl->redirectByClass('ilbookingobjectgui', 'displayPostInfo');
+        } else {
+            if ($_POST['part_view'] == ilBookingParticipantGUI::PARTICIPANT_VIEW) {
+                $this->ctrl->redirectByClass('ilbookingparticipantgui', 'render');
+            } else {
+                $this->ctrl->redirect($this, 'render');
+            }
+        }
+    }
+    
+    protected function initBookingNumbersForm(array $a_objects_counter, $a_group_id, $a_reload = false)
+    {
+        include_once 'Services/Form/classes/class.ilPropertyFormGUI.php';
+        $form = new ilPropertyFormGUI();
+        $form->setFormAction($this->ctrl->getFormAction($this, "confirmedBooking"));
+        $form->setTitle($this->lng->txt("book_confirm_booking_schedule_number_of_objects"));
+        $form->setDescription($this->lng->txt("book_confirm_booking_schedule_number_of_objects_info"));
+        
+        include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
+        $section = false;
+        $min_date = null;
+        foreach ($a_objects_counter as $id => $counter) {
+            $id = explode("_", $id);
+            $book_id = $id[0] . "_" . $id[1] . "_" . $id[2] . "_" . $counter;
+            
+            $obj = new ilBookingObject($id[0]);
+            
+            if (!$section) {
+                $section = new ilFormSectionHeaderGUI();
+                $section->setTitle($obj->getTitle());
+                $form->addItem($section);
+                
+                $section = true;
+            }
+            
+            $period = /* $this->lng->txt("book_period").": ". */
+                ilDatePresentation::formatPeriod(
+                    new ilDateTime($id[1], IL_CAL_UNIX),
+                    new ilDateTime($id[2], IL_CAL_UNIX)
+                );
+            
+            $nr_field = new ilNumberInputGUI($period, "conf_nr__" . $book_id);
+            $nr_field->setValue(1);
+            $nr_field->setSize(3);
+            $nr_field->setMaxValue($counter);
+            $nr_field->setMinValue($counter ? 1 : 0);
+            $nr_field->setRequired(true);
+            $form->addItem($nr_field);
+            
+            if (!$min_date || $id[1] < $min_date) {
+                $min_date = $id[1];
+            }
+        }
+        
+        // recurrence
+        $this->lng->loadLanguageModule("dateplaner");
+        $rec_mode = new ilSelectInputGUI($this->lng->txt("cal_recurrences"), "recm");
+        $rec_mode->setRequired(true);
+        $rec_mode->setOptions(array(
+            "-1" => $this->lng->txt("cal_no_recurrence"),
+            1 => $this->lng->txt("cal_weekly"),
+            2 => $this->lng->txt("r_14"),
+            4 => $this->lng->txt("r_4_weeks")
+        ));
+        $form->addItem($rec_mode);
+
+        $rec_end = new ilDateTimeInputGUI($this->lng->txt("cal_repeat_until"), "rece");
+        $rec_end->setRequired(true);
+        $rec_mode->addSubItem($rec_end);
+                    
+        if (!$a_reload) {
+            // show date only if active recurrence
+            $rec_mode->setHideSubForm(true, '>= 1');
+            
+            if ($min_date) {
+                $rec_end->setDate(new ilDateTime($min_date, IL_CAL_UNIX));
+            }
+        } else {
+            // recurrence may not be changed on reload
+            $rec_mode->setDisabled(true);
+            $rec_end->setDisabled(true);
+        }
+        
+        if ($a_group_id) {
+            $grp = new ilHiddenInputGUI("grp_id");
+            $grp->setValue($a_group_id);
+            $form->addItem($grp);
+        }
+
+        if ($this->user_id_assigner != $this->user_id_to_book) {
+            $usr = new ilHiddenInputGUI("bkusr");
+            $usr->setValue($this->user_id_to_book);
+            $form->addItem($usr);
+        }
+
+        $form->addCommandButton("confirmedBookingNumbers", $this->lng->txt("confirm"));
+        $form->addCommandButton("render", $this->lng->txt("cancel"));
+        
+        return $form;
+    }
+    
+    public function confirmBookingNumbers(array $a_objects_counter, $a_group_id, ilPropertyFormGUI $a_form = null)
+    {
+        $tpl = $this->tpl;
+        
+        $this->tabs_gui->clearTargets();
+        $this->tabs_gui->setBackTarget($this->lng->txt('book_back_to_list'), $this->ctrl->getLinkTarget($this, 'render'));
+
+        if (!$a_form) {
+            $a_form = $this->initBookingNumbersForm($a_objects_counter, $a_group_id);
+        }
+    
+        $tpl->setContent($a_form->getHTML());
+    }
+    
+    protected function addDaysDate($a_date, $a_days)
+    {
+        $date = date_parse($a_date);
+        $stamp = mktime(0, 0, 1, $date["month"], $date["day"]+$a_days, $date["year"]);
+        return date("Y-m-d", $stamp);
+    }
+    
+    protected function addDaysStamp($a_stamp, $a_days)
+    {
+        $date = getDate($a_stamp);
+        return mktime(
+            $date["hours"],
+            $date["minutes"],
+            $date["seconds"],
+            $date["mon"],
+            $date["mday"]+$a_days,
+            $date["year"]
+        );
+    }
+    
+    public function confirmedBookingNumbersObject()
+    {
+        include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php';
+        include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
+
+        //get the user who will get the booking.
+        if ($_POST['bkusr']) {
+            $this->user_id_to_book = (int) $_POST['bkusr'];
+        }
+
+        // convert post data to initial form config
+        $counter = array();
+        $current_first = $obj_id = null;
+        foreach (array_keys($_POST) as $id) {
+            if (substr($id, 0, 9) == "conf_nr__") {
+                $id = explode("_", substr($id, 9));
+                $counter[$id[0] . "_" . $id[1] . "_" . $id[2]] = (int) $id[3];
+                if (!$current_first) {
+                    $current_first = date("Y-m-d", $id[1]);
+                }
+            }
+        }
+        
+        // recurrence
+        
+        // checkInput() has not been called yet, so we have to improvise
+        include_once 'Services/Calendar/classes/class.ilCalendarUtil.php';
+        $end = ilCalendarUtil::parseIncomingDate($_POST["rece"], null);
+        
+        if ((int) $_POST["recm"] > 0 && $end && $current_first) {
+            ksort($counter);
+            $end = $end->get(IL_CAL_DATE);
+            $cycle = (int) $_POST["recm"]*7;
+            $cut = 0;
+            $org = $counter;
+            while ($cut < 1000 && $this->addDaysDate($current_first, $cycle) <= $end) {
+                $cut++;
+                $current_first = null;
+                foreach ($org as $item_id => $max) {
+                    $parts = explode("_", $item_id);
+                    $obj_id = $parts[0];
+                    
+                    $from = $this->addDaysStamp($parts[1], $cycle*$cut);
+                    $to = $this->addDaysStamp($parts[2], $cycle*$cut);
+                    
+                    $new_item_id = $obj_id . "_" . $from . "_" . $to;
+                    
+                    // form reload because of validation errors
+                    if (!isset($counter[$new_item_id]) && date("Y-m-d", $to) <= $end) {
+                        // get max available for added dates
+                        $new_max = ilBookingReservation::getAvailableObject(array($obj_id), $from, $to-1, false, true);
+                        $new_max = (int) $new_max[$obj_id];
+
+                        $counter[$new_item_id] = $new_max;
+
+                        if (!$current_first) {
+                            $current_first = date("Y-m-d", $from);
+                        }
+                                        
+                        // clone input
+                        $_POST["conf_nr__" . $new_item_id . "_" . $new_max] = $_POST["conf_nr__" . $item_id . "_" . $max];
+                    }
+                }
+            }
+        }
+        
+        $group_id = $_POST["grp_id"];
+
+        $form = $this->initBookingNumbersForm($counter, $group_id, true);
+        if ($form->checkInput()) {
+            $success = false;
+            $rsv_ids = array();
+            foreach ($counter as $id => $all_nr) {
+                $book_nr = $form->getInput("conf_nr__" . $id . "_" . $all_nr);
+                $parts = explode("_", $id);
+                $obj_id = $parts[0];
+                $from = $parts[1];
+                $to = $parts[2]-1;
+                
+                // get currently available slots
+                $counter = ilBookingReservation::getAvailableObject(array($obj_id), $from, $to, false, true);
+                $counter = $counter[$obj_id];
+                if ($counter) {
+                    // we can only book what is left
+                    $book_nr = min($book_nr, $counter);
+                    for ($loop = 0; $loop < $book_nr; $loop++) {
+                        $rsv_ids[] = $this->processBooking($obj_id, $from, $to, $group_id);
+                        $success = $obj_id;
+                    }
+                }
+            }
+            if ($success) {
+                $this->saveParticipant();
+                $this->handleBookingSuccess($success, $rsv_ids);
+            } else {
+                ilUtil::sendFailure($this->lng->txt('book_reservation_failed'), true);
+                $this->ctrl->redirect($this, 'render');
+            }
+        } else {
+            // ilDateTimeInputGUI does NOT add hidden values on disabled!
+
+            $rece_array = explode(".", $_POST['rece']);
+
+            $rece_day = str_pad($rece_array[0], 2, "0", STR_PAD_LEFT);
+            $rece_month = str_pad($rece_array[1], 2, "0", STR_PAD_LEFT);
+            $rece_year = $rece_array[2];
+
+            // ilDateTimeInputGUI will choke on POST array format
+            $_POST["rece"] = null;
+            
+            $form->setValuesByPost();
+
+            $rece_date = new ilDate($rece_year . "-" . $rece_month . "-" . $rece_day, IL_CAL_DATE);
+
+            $form->getItemByPostVar("rece")->setDate($rece_date);
+            $form->getItemByPostVar("recm")->setHideSubForm($_POST["recm"] < 1);
+
+            $hidden_date = new ilHiddenInputGUI("rece");
+            $hidden_date->setValue($rece_date);
+            $form->addItem($hidden_date);
+            
+            return $this->confirmBookingNumbers($counter, $group_id, $form);
+        }
+    }
+    
+    /**
+     * Book object for date
+     *
+     * @param int $a_object_id
+     * @param int $a_from timestamp
+     * @param int $a_to timestamp
+     * @param int $a_group_id
+     * @return int
+     */
+    public function processBooking($a_object_id, $a_from = null, $a_to = null, $a_group_id = null)
+    {
+        // #11995
+        $this->checkPermission('read');
+        
+        include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php';
+        $reservation = new ilBookingReservation();
+        $reservation->setObjectId($a_object_id);
+        $reservation->setUserId($this->user_id_to_book);
+        $reservation->setAssignerId($this->user_id_assigner);
+        $reservation->setFrom($a_from);
+        $reservation->setTo($a_to);
+        $reservation->setGroupId($a_group_id);
+        $reservation->save();
+
+        if ($a_from) {
+            $this->lng->loadLanguageModule('dateplaner');
+            include_once 'Services/Calendar/classes/class.ilCalendarUtil.php';
+            include_once 'Services/Calendar/classes/class.ilCalendarCategory.php';
+            $def_cat = ilCalendarUtil::initDefaultCalendarByType(ilCalendarCategory::TYPE_BOOK, $this->user_id_to_book, $this->lng->txt('cal_ch_personal_book'), true);
+
+            include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
+            $object = new ilBookingObject($a_object_id);
+
+            include_once 'Services/Calendar/classes/class.ilCalendarEntry.php';
+            $entry = new ilCalendarEntry;
+            $entry->setStart(new ilDateTime($a_from, IL_CAL_UNIX));
+            $entry->setEnd(new ilDateTime($a_to, IL_CAL_UNIX));
+            $entry->setTitle($this->lng->txt('book_cal_entry') . ' ' . $object->getTitle());
+            $entry->setContextId($reservation->getId());
+            $entry->save();
+
+            include_once 'Services/Calendar/classes/class.ilCalendarCategoryAssignments.php';
+            $assignment = new ilCalendarCategoryAssignments($entry->getEntryId());
+            $assignment->addAssignment($def_cat->getCategoryId());
+        }
+        
+        return $reservation->getId();
+    }
 
-?>
\ No newline at end of file
+    /**
+     *  List reservations
+     */
+    public function logObject()
+    {
+        $tpl = $this->tpl;
+
+        $this->tabs_gui->setTabActive('log');
+                
+        $show_all = ($this->checkPermissionBool('write') || $this->object->hasPublicLog());
+        
+        $filter = null;
+        if ($this->book_obj_id > 0) {
+            $filter["object"] = $this->book_obj_id;
+        }
+
+        // coming from participants tab to cancel reservations.
+        if ($_GET['user_id']) {
+            $filter["user_id"] = (int) $_GET['user_id'];
+        }
+
+        include_once 'Modules/BookingManager/classes/class.ilBookingReservationsTableGUI.php';
+        $table = new ilBookingReservationsTableGUI(
+            $this,
+            'log',
+            $this->ref_id,
+            $this->object->getId(),
+            $show_all,
+            ($this->object->getScheduleType() != ilObjBookingPool::TYPE_NO_SCHEDULE),
+            $filter
+        );
+        $tpl->setContent($table->getHTML());
+    }
+    
+    public function logDetailsObject()
+    {
+        $tpl = $this->tpl;
+
+        $this->tabs_gui->clearTargets();
+        $this->tabs_gui->setBackTarget(
+            $this->lng->txt("back"),
+            $this->ctrl->getLinkTarget($this, "log")
+        );
+                
+        $show_all = ($this->checkPermissionBool('write') ||	$this->object->hasPublicLog());
+        
+        $filter = null;
+        if ($this->book_obj_id > 0) {
+            $filter["object"] = $this->book_obj_id;
+        }
+
+        include_once 'Modules/BookingManager/classes/class.ilBookingReservationsTableGUI.php';
+        $table = new ilBookingReservationsTableGUI(
+            $this,
+            'log',
+            $this->ref_id,
+            $this->object->getId(),
+            $show_all,
+            ($this->object->getScheduleType() != ilObjBookingPool::TYPE_NO_SCHEDULE),
+            $filter,
+            $this->reservation_id
+        );
+        $tpl->setContent($table->getHTML());
+    }
+    
+    /**
+     * Change status of given reservations
+     */
+    public function changeStatusObject()
+    {
+        $this->tabs_gui->setTabActive('log');
+        
+        if (!$_POST['reservation_id']) {
+            ilUtil::sendFailure($this->lng->txt('select_one'));
+            return $this->logObject();
+        }
+
+        if ($this->checkPermissionBool('write')) {
+            include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php';
+            ilBookingReservation::changeStatus($_POST['reservation_id'], (int) $_POST['tstatus']);
+        }
+
+        ilUtil::sendSuccess($this->lng->txt('settings_saved'), true);
+        return $this->ctrl->redirect($this, 'log');
+    }
+
+    /**
+     * Apply filter from reservations table gui
+     */
+    public function applyLogFilterObject()
+    {
+        $show_all = ($this->checkPermissionBool('write') ||	$this->object->hasPublicLog());
+        
+        include_once 'Modules/BookingManager/classes/class.ilBookingReservationsTableGUI.php';
+        $table = new ilBookingReservationsTableGUI(
+            $this,
+            'log',
+            $this->ref_id,
+            $this->object->getId(),
+            $show_all,
+            ($this->object->getScheduleType() != ilObjBookingPool::TYPE_NO_SCHEDULE)
+        );
+        $table->resetOffset();
+        $table->writeFilterToSession();
+        $this->logObject();
+    }
+
+    /**
+     * Reset filter in reservations table gui
+     */
+    public function resetLogFilterObject()
+    {
+        $show_all = ($this->checkPermissionBool('write') ||	$this->object->hasPublicLog());
+        
+        include_once 'Modules/BookingManager/classes/class.ilBookingReservationsTableGUI.php';
+        $table = new ilBookingReservationsTableGUI(
+            $this,
+            'log',
+            $this->ref_id,
+            $this->object->getId(),
+            $show_all,
+            ($this->object->getScheduleType() != ilObjBookingPool::TYPE_NO_SCHEDULE)
+        );
+        $table->resetOffset();
+        $table->resetFilter();
+        $this->logObject();
+    }
+
+    public static function _goto($a_target)
+    {
+        global $DIC;
+
+        $ilAccess = $DIC->access();
+        $lng = $DIC->language();
+
+        if ($ilAccess->checkAccess("read", "", $a_target)) {
+            ilObjectGUI::_gotoRepositoryNode($a_target, "render");
+        } elseif ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) {
+            ilUtil::sendFailure(sprintf(
+                $lng->txt("msg_no_perm_read_item"),
+                ilObject::_lookupTitle(ilObject::_lookupObjId($a_target))
+            ), true);
+            ilObjectGUI::_gotoRepositoryRoot();
+        }
+    }
+
+    /**
+    * 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 infoScreenObject()
+    {
+        $this->ctrl->setCmd("showSummary");
+        $this->ctrl->setCmdClass("ilinfoscreengui");
+        $this->infoScreen();
+    }
+
+    public function infoScreen()
+    {
+        $ilCtrl = $this->ctrl;
+
+        $this->tabs_gui->setTabActive('info');
+        
+        $this->checkPermission("visible");
+
+        include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php");
+        $info = new ilInfoScreenGUI($this);
+
+        $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);
+            }
+        }
+
+        // forward the command
+        if ($ilCtrl->getNextClass() == "ilinfoscreengui") {
+            $ilCtrl->forwardCommand($info);
+        } else {
+            return $ilCtrl->getHTML($info);
+        }
+    }
+    
+    protected function getLogReservationIds()
+    {
+        if ($_POST["mrsv"]) {
+            return $_POST["mrsv"];
+        } elseif ($this->reservation_id > 0) {
+            return array($this->reservation_id);
+        }
+    }
+    
+    public function rsvConfirmCancelObject()
+    {
+        $ilCtrl = $this->ctrl;
+        $lng = $this->lng;
+        $tpl = $this->tpl;
+        $ilUser = $this->user;
+    
+        $ids = $this->getLogReservationIds();
+        if (!is_array($ids) || !sizeof($ids)) {
+            $this->ctrl->redirect($this, 'log');
+        }
+        
+        include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
+        include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php';
+        
+        $max = array();
+        foreach ($ids as $idx => $id) {
+            if (!is_numeric($id)) {
+                list($obj_id, $user_id, $from, $to) = explode("_", $id);
+                
+                $valid_ids = array();
+                foreach (ilBookingObject::getList($this->object->getId()) as $item) {
+                    $valid_ids[$item["booking_object_id"]] = $item["title"];
+                }
+                        
+                if (($this->checkPermissionBool("write") || $user_id == $ilUser->getId()) &&
+                    $from > time() &&
+                    in_array($obj_id, array_keys($valid_ids))) {
+                    $rsv_ids = ilBookingReservation::getCancelDetails($obj_id, $user_id, $from, $to);
+                    if (!sizeof($rsv_ids)) {
+                        unset($ids[$idx]);
+                    }
+                    if (sizeof($rsv_ids) > 1) {
+                        $max[$id] = sizeof($rsv_ids);
+                        $ids[$idx] = $rsv_ids;
+                    } else {
+                        // only 1 in group?  treat as normal reservation
+                        $ids[$idx] = array_shift($rsv_ids);
+                    }
+                } else {
+                    unset($ids[$idx]);
+                }
+            }
+        }
+
+        if (!is_array($ids) || !sizeof($ids)) {
+            $this->ctrl->redirect($this, 'log');
+        }
+        
+        // show form instead
+        if (sizeof($max) && max($max) > 1) {
+            return $this->rsvConfirmCancelAggregationObject($ids);
+        }
+        
+        $this->tabs_gui->clearTargets();
+        $this->tabs_gui->setBackTarget(
+            $lng->txt("back"),
+            $ilCtrl->getLinkTarget($this, "log")
+        );
+            
+        $this->setHelpId("cancel_booking");
+        
+        include_once 'Services/Utilities/classes/class.ilConfirmationGUI.php';
+        $conf = new ilConfirmationGUI();
+        $conf->setFormAction($ilCtrl->getFormAction($this, 'rsvCancel'));
+        $conf->setHeaderText($lng->txt('book_confirm_cancel'));
+        $conf->setConfirm($lng->txt('book_set_cancel'), 'rsvCancel');
+        $conf->setCancel($lng->txt('cancel'), 'log');
+
+        foreach ($ids as $id) {
+            $rsv = new ilBookingReservation($id);
+            $obj = new ilBookingObject($rsv->getObjectId());
+            
+            $details = $obj->getTitle();
+            if ($this->object->getScheduleType() != ilObjBookingPool::TYPE_NO_SCHEDULE) {
+                $details .= ", " . ilDatePresentation::formatPeriod(
+                    new ilDateTime($rsv->getFrom(), IL_CAL_UNIX),
+                    new ilDateTime($rsv->getTo()+1, IL_CAL_UNIX)
+                );
+            }
+            
+            $conf->addItem('rsv_id[]', $id, $details);
+        }
+    
+        $tpl->setContent($conf->getHTML());
+    }
+    
+    public function rsvConfirmCancelAggregationForm($a_ids)
+    {
+        include_once 'Services/Form/classes/class.ilPropertyFormGUI.php';
+        $form = new ilPropertyFormGUI();
+        $form->setFormAction($this->ctrl->getFormAction($this, "rsvCancel"));
+        $form->setTitle($this->lng->txt("book_confirm_cancel_aggregation"));
+        
+        include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
+        include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php';
+        
+        ilDatePresentation::setUseRelativeDates(false);
+        
+        foreach ($a_ids as $idx => $ids) {
+            if (is_array($ids)) {
+                $first = $ids;
+                $first = array_shift($first);
+            } else {
+                $first = $ids;
+            }
+            
+            $rsv = new ilBookingReservation($first);
+            $obj = new ilBookingObject($rsv->getObjectId());
+        
+            $caption = $obj->getTitle() . ", " . ilDatePresentation::formatPeriod(
+                new ilDateTime($rsv->getFrom(), IL_CAL_UNIX),
+                new ilDateTime($rsv->getTo()+1, IL_CAL_UNIX)
+            );
+            
+            // #17869
+            if (is_array($ids)) {
+                $caption .= " (" . sizeof($ids) . ")";
+            }
+            
+            $item = new ilNumberInputGUI($caption, "rsv_id_" . $idx);
+            $item->setRequired(true);
+            $item->setMinValue(0);
+            $item->setSize(4);
+            $form->addItem($item);
+            
+            if (is_array($ids)) {
+                $item->setMaxValue(sizeof($ids));
+                
+                foreach ($ids as $id) {
+                    $hidden = new ilHiddenInputGUI("rsv_aggr[" . $idx . "][]");
+                    $hidden->setValue($id);
+                    $form->addItem($hidden);
+                }
+            } else {
+                $item->setMaxValue(1);
+                
+                $hidden = new ilHiddenInputGUI("rsv_aggr[" . $idx . "]");
+                $hidden->setValue($ids);
+                $form->addItem($hidden);
+            }
+                        
+            if ($_POST["rsv_id_" . $idx]) {
+                $item->setValue((int) $_POST["rsv_id_" . $idx]);
+            }
+        }
+                
+        $form->addCommandButton("rsvCancel", $this->lng->txt("confirm"));
+        $form->addCommandButton("log", $this->lng->txt("cancel"));
+        
+        return $form;
+    }
+    
+    public function rsvConfirmCancelAggregationObject(array $a_ids = null)
+    {
+        $tpl = $this->tpl;
+        $ilCtrl = $this->ctrl;
+        $lng = $this->lng;
+        
+        $this->tabs_gui->clearTargets();
+        $this->tabs_gui->setBackTarget(
+            $lng->txt("back"),
+            $ilCtrl->getLinkTarget($this, "log")
+        );
+        
+        $this->setHelpId("cancel_booking");
+        
+        // #13511
+        ilUtil::sendQuestion($lng->txt("book_confirm_cancel"));
+        
+        $form = $this->rsvConfirmCancelAggregationForm($a_ids);
+        
+        $tpl->setContent($form->getHTML());
+    }
+
+    public function rsvCancelObject()
+    {
+        $ilUser = $this->user;
+        $tpl = $this->tpl;
+        $lng = $this->lng;
+        $ilCtrl = $this->ctrl;
+                
+        $ids = $_POST["rsv_id"];
+        
+        // parse aggregation form
+        if ($_POST["rsv_aggr"]) {
+            $form = $this->rsvConfirmCancelAggregationForm($_POST["rsv_aggr"]);
+            if (!$form->checkInput()) {
+                $this->tabs_gui->clearTargets();
+                $this->tabs_gui->setBackTarget(
+                    $lng->txt("back"),
+                    $ilCtrl->getLinkTarget($this, "log")
+                );
+                
+                return $tpl->setContent($form->getHTML());
+            }
+            
+            $ids = array();
+            foreach ($_POST["rsv_aggr"] as $idx => $aggr_ids) {
+                $max = (int) $_POST["rsv_id_" . $idx];
+                if ($max) {
+                    if (!is_array($aggr_ids)) {
+                        $ids[] = $aggr_ids;
+                    } else {
+                        $aggr_ids = array_slice($aggr_ids, 0, $max);
+                        $ids = array_merge($ids, $aggr_ids);
+                    }
+                }
+            }
+        }
+        
+        if ($ids) {
+            include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php';
+            foreach ($ids as $id) {
+                $obj = new ilBookingReservation($id);
+            
+                if (!$this->checkPermissionBool("write") && $obj->getUserId() != $ilUser->getId()) {
+                    ilUtil::sendFailure($this->lng->txt('permission_denied'), true);
+                    $this->ctrl->redirect($this, 'log');
+                }
+
+                $obj->setStatus(ilBookingReservation::STATUS_CANCELLED);
+                $obj->update();
+
+                if ($this->object->getScheduleType() != ilObjBookingPool::TYPE_NO_SCHEDULE) {
+                    // remove user calendar entry (#11086)
+                    $cal_entry_id = $obj->getCalendarEntry();
+                    if ($cal_entry_id) {
+                        include_once 'Services/Calendar/classes/class.ilCalendarEntry.php';
+                        $entry = new ilCalendarEntry($cal_entry_id);
+                        $entry->delete();
+                    }
+                }
+            }
+        }
+
+        ilUtil::sendSuccess($this->lng->txt('settings_saved'));
+        $this->logObject();
+    }
+
+    public function rsvInUseObject()
+    {
+        $this->checkPermission("write");
+
+        $ids = $this->getLogReservationIds();
+        if ($ids) {
+            include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php';
+            foreach ($ids as $id) {
+                $obj = new ilBookingReservation($id);
+                $obj->setStatus(ilBookingReservation::STATUS_IN_USE);
+                $obj->update();
+            }
+        }
+
+        ilUtil::sendSuccess($this->lng->txt('settings_saved'));
+        $this->logObject();
+    }
+
+    public function rsvNotInUseObject()
+    {
+        $this->checkPermission("write");
+        
+        $ids = $this->getLogReservationIds();
+        if ($ids) {
+            include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php';
+            foreach ($ids as $id) {
+                $obj = new ilBookingReservation($id);
+                $obj->setStatus(null);
+                $obj->update();
+            }
+        }
+
+        ilUtil::sendSuccess($this->lng->txt('settings_saved'));
+        $this->logObject();
+    }
+
+    public function showProfileObject()
+    {
+        $tpl = $this->tpl;
+        $ilCtrl = $this->ctrl;
+        
+        $this->tabs_gui->clearTargets();
+        
+        $user_id = $this->profile_user_id;
+        
+        include_once 'Services/User/classes/class.ilPublicUserProfileGUI.php';
+        $profile = new ilPublicUserProfileGUI($user_id);
+        $profile->setBackUrl($this->ctrl->getLinkTarget($this, 'log'));
+        $tpl->setContent($ilCtrl->getHTML($profile));
+    }
+    
+    public function addLocatorItems()
+    {
+        $ilLocator = $this->locator;
+        
+        if (is_object($this->object)) {
+            $ilLocator->addItem($this->object->getTitle(), $this->ctrl->getLinkTarget($this, "render"), "", $this->object->getRefId());
+        }
+    }
+
+    /**
+     * @inheritdoc
+     */
+    protected function initHeaderAction($a_sub_type = null, $a_sub_id = null)
+    {
+        $access = $this->access;
+        $user = $this->user;
+        $ctrl = $this->ctrl;
+        $lng = $this->lng;
+
+        $lng->loadLanguageModule("noti");
+
+        $lg = parent::initHeaderAction($a_sub_type, $a_sub_id);
+
+        if ($lg && $access->checkAccess("read", "", $this->ref_id)) {
+            // notification
+            if (true) {
+                if (!ilNotification::hasNotification(ilNotification::TYPE_BOOK, $user->getId(), $this->object->getId())) {
+                    $lg->addHeaderIcon(
+                        "not_icon",
+                        ilUtil::getImagePath("notification_off.svg"),
+                        $lng->txt("noti_notification_deactivated")
+                    );
+
+                    $ctrl->setParameter($this, "ntf", 1);
+                    $caption = "noti_activate_notification";
+                } else {
+                    $lg->addHeaderIcon(
+                        "not_icon",
+                        ilUtil::getImagePath("notification_on.svg"),
+                        $lng->txt("noti_notification_activated")
+                    );
+
+                    $ctrl->setParameter($this, "ntf", 0);
+                    $caption = "noti_deactivate_notification";
+                }
+
+                $lg->addCustomCommand(
+                    $ctrl->getLinkTarget($this, "saveNotification"),
+                    $caption
+                );
+
+                $ctrl->setParameter($this, "ntf", "");
+            }
+        }
+
+        return $lg;
+    }
+
+    /**
+     * Save notification
+     */
+    public function saveNotificationObject()
+    {
+        $ctrl = $this->ctrl;
+        $user = $this->user;
+
+
+        switch ($_GET["ntf"]) {
+            case 0:
+                ilNotification::setNotification(ilNotification::TYPE_BOOK, $user->getId(), $this->object->getId(), false);
+                break;
+
+            case 1:
+                ilNotification::setNotification(ilNotification::TYPE_BOOK, $user->getId(), $this->object->getId(), true);
+                break;
+        }
+        $ctrl->redirect($this, "render");
+    }
+    /*
+     * save booking participant.
+     */
+    protected function saveParticipant()
+    {
+        include_once("./Modules/BookingManager/classes/class.ilBookingParticipant.php");
+        $participant = new ilBookingParticipant($this->user_id_to_book, $this->object->getId());
+    }
+
+    /**
+     * Create reservations for a bunch of booking pool participants.
+     */
+    public function bookMultipleParticipantsObject()
+    {
+        if ($_POST["mass"]) {
+            $participants = $_POST["mass"];
+        } else {
+            $this->ctrl->redirectByClass('ilbookingobjectgui', 'render');
+        }
+
+        $this->tabs->clearTargets();
+        $this->ctrl->setParameterByClass('ilbookingobjectgui', 'object_id', $this->book_obj_id);
+        $this->tabs->setBackTarget($this->lng->txt("back"), $this->ctrl->getLinkTargetByClass('ilbookingobjectgui', 'assignparticipants'));
+        $this->ctrl->setParameterByClass('ilbookingobjectgui', 'object_id', '');
+
+        $conf = new ilConfirmationGUI();
+        $conf->setFormAction($this->ctrl->getFormAction($this));
+
+        //add user list as items.
+        foreach ($participants as $id) {
+            $name = ilObjUser::_lookupFullname($id);
+            $conf->addItem("participants[]", $id, $name);
+        }
+
+        $available = ilBookingReservation::numAvailableFromObjectNoSchedule($this->book_obj_id);
+        if (sizeof($participants) > $available) {
+            $obj = new ilBookingObject($this->book_obj_id);
+            $conf->setHeaderText(
+                sprintf(
+                    $this->lng->txt('book_limit_objects_available'),
+                    sizeof($participants),
+                    $obj->getTitle(),
+                    $available
+                )
+            );
+        } else {
+            $conf->setHeaderText($this->lng->txt('book_confirm_booking_no_schedule'));
+            $conf->addHiddenItem("object_id", $this->book_obj_id);
+            $conf->setConfirm($this->lng->txt("assign"), "saveMultipleBookings");
+        }
+
+        $conf->setCancel($this->lng->txt("cancel"), 'redirectToList');
+        $this->tpl->setContent($conf->getHTML());
+    }
+
+    public function redirectToListObject()
+    {
+        $this->ctrl->setParameterByClass('ilbookingobjectgui', 'object_id', $this->book_obj_id);
+        $this->ctrl->redirectByClass('ilbookingobjectgui', 'assignParticipants');
+    }
+
+    /**
+     * Save multiple users reservations for one booking pool object.
+     * //TODO check if object/user exist in the DB,
+     */
+    public function saveMultipleBookingsObject()
+    {
+        if ($_POST["participants"] && $_POST['object_id']) {
+            $participants = $_POST["participants"];
+            $this->book_obj_id = $_POST['object_id'];
+        } else {
+            $this->ctrl->redirectByClass('ilbookingobjectgui', 'render');
+        }
+        $rsv_ids = array();
+        foreach ($participants as $id) {
+            $this->user_id_to_book = $id;
+            $rsv_ids[] = $this->processBooking($this->book_obj_id);
+        }
+
+        if (sizeof($rsv_ids)) {
+            ilUtil::sendSuccess("booking_multiple_succesfully");
+            $this->ctrl->redirectByClass('ilbookingobjectgui', 'render');
+        } else {
+            ilUtil::sendFailure($this->lng->txt('book_reservation_failed_overbooked'), true);
+            $this->ctrl->redirect($this, 'render');
+        }
+    }
+}
diff --git a/Modules/BookingManager/classes/class.ilObjBookingPoolListGUI.php b/Modules/BookingManager/classes/class.ilObjBookingPoolListGUI.php
index 46f083b1ab64494d2c640aa60c5ea16992f86dc0..67913c12bfb51e66c874ee5286f65fcd9a14e73d 100644
--- a/Modules/BookingManager/classes/class.ilObjBookingPoolListGUI.php
+++ b/Modules/BookingManager/classes/class.ilObjBookingPoolListGUI.php
@@ -14,98 +14,94 @@ include_once "Services/Object/classes/class.ilObjectListGUI.php";
  */
 class ilObjBookingPoolListGUI extends ilObjectListGUI
 {
-	/**
-	* constructor
-	*/
-	function __construct()
-	{
-		global $DIC;
+    /**
+    * constructor
+    */
+    public function __construct()
+    {
+        global $DIC;
 
-		$this->ctrl = $DIC->ctrl();
-		$this->lng = $DIC->language();
-		parent::__construct();
-	}
+        $this->ctrl = $DIC->ctrl();
+        $this->lng = $DIC->language();
+        parent::__construct();
+    }
 
-	/**
-	* initialisation
-	*/
-	function init()
-	{
-		$this->static_link_enabled = true;
-		$this->delete_enabled = true;
-		$this->cut_enabled = true;
-		$this->copy_enabled = true;
-		$this->subscribe_enabled = true;
-		$this->link_enabled = true;
-		$this->info_screen_enabled = true;
-		$this->type = "book";
-		$this->gui_class_name = "ilobjbookingpoolgui";
+    /**
+    * initialisation
+    */
+    public function init()
+    {
+        $this->static_link_enabled = true;
+        $this->delete_enabled = true;
+        $this->cut_enabled = true;
+        $this->copy_enabled = true;
+        $this->subscribe_enabled = true;
+        $this->link_enabled = true;
+        $this->info_screen_enabled = true;
+        $this->type = "book";
+        $this->gui_class_name = "ilobjbookingpoolgui";
 
-		/*
-		include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDSubstitution.php');
-		$this->substitutions = ilAdvancedMDSubstitution::_getInstanceByObjectType($this->type);
-		if($this->substitutions->isActive())
-		{
-			$this->substitutions_enabled = true;
-		}
-		 */
+        /*
+        include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDSubstitution.php');
+        $this->substitutions = ilAdvancedMDSubstitution::_getInstanceByObjectType($this->type);
+        if($this->substitutions->isActive())
+        {
+            $this->substitutions_enabled = true;
+        }
+         */
 
-		// general commands array
-		include_once('./Modules/BookingManager/classes/class.ilObjBookingPoolAccess.php');
-		$this->commands = ilObjBookingPoolAccess::_getCommands();
-	}
+        // general commands array
+        include_once('./Modules/BookingManager/classes/class.ilObjBookingPoolAccess.php');
+        $this->commands = ilObjBookingPoolAccess::_getCommands();
+    }
 
-	/**
-	* Get command target frame.
-	*
-	* Overwrite this method if link frame is not current frame
-	*
-	* @param	string		$a_cmd			command
-	* @return	string		command target frame
-	*/
-	function getCommandFrame($a_cmd)
-	{
-		return parent::getCommandFrame($a_cmd);
-	}
+    /**
+    * Get command target frame.
+    *
+    * Overwrite this method if link frame is not current frame
+    *
+    * @param	string		$a_cmd			command
+    * @return	string		command target frame
+    */
+    public function getCommandFrame($a_cmd)
+    {
+        return parent::getCommandFrame($a_cmd);
+    }
 
-	/**
-	* Get command link url.
-	*
-	* @param	int			$a_ref_id		reference id
-	* @param	string		$a_cmd			command
-	*/
-	function getCommandLink($a_cmd)
-	{
-		$ilCtrl = $this->ctrl;
-		
-		switch ($a_cmd) 
-		{
-			default :
-				$ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $this->ref_id);
-				$cmd_link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", $a_cmd);
-				$ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", (int) $_GET["ref_id"]);
-				break;
-		}
+    /**
+    * Get command link url.
+    *
+    * @param	int			$a_ref_id		reference id
+    * @param	string		$a_cmd			command
+    */
+    public function getCommandLink($a_cmd)
+    {
+        $ilCtrl = $this->ctrl;
+        
+        switch ($a_cmd) {
+            default:
+                $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $this->ref_id);
+                $cmd_link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", $a_cmd);
+                $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", (int) $_GET["ref_id"]);
+                break;
+        }
 
-		return $cmd_link;
-	}
-	
-	function getProperties()
-	{
-		$lng = $this->lng;
-		
-		// #11193
+        return $cmd_link;
+    }
+    
+    public function getProperties()
+    {
+        $lng = $this->lng;
+        
+        // #11193
 
-		$props = array();
+        $props = array();
 
-		include_once("./Modules/BookingManager/classes/class.ilObjBookingPool.php");
-		if (!ilObjBookingPool::_lookupOnline($this->obj_id))
-		{
-			$props[] = array("alert" => true, "property" => $lng->txt("status"),
-				"value" => $lng->txt("offline"));
-		}
-		return $props;
-	}
+        include_once("./Modules/BookingManager/classes/class.ilObjBookingPool.php");
+        if (!ilObjBookingPool::_lookupOnline($this->obj_id)) {
+            $props[] = array("alert" => true, "property" => $lng->txt("status"),
+                "value" => $lng->txt("offline"));
+        }
+        return $props;
+    }
 }
-
-?>
\ No newline at end of file
diff --git a/Modules/BookingManager/classes/class.ilScheduleInputGUI.php b/Modules/BookingManager/classes/class.ilScheduleInputGUI.php
index a30d72fe2571168ee6e297fb7fb04112063c1139..5faf4f52f46bf47f60004f39b94e7293ea1f15b6 100755
--- a/Modules/BookingManager/classes/class.ilScheduleInputGUI.php
+++ b/Modules/BookingManager/classes/class.ilScheduleInputGUI.php
@@ -12,294 +12,270 @@ include_once "Services/Form/classes/class.ilFormPropertyGUI.php";
 */
 class ilScheduleInputGUI extends ilFormPropertyGUI
 {
-	/**
-	 * @var ilTemplate
-	 */
-	protected $tpl;
+    /**
+     * @var ilTemplate
+     */
+    protected $tpl;
 
-	protected $value;
-	
-	/**
-	* Constructor
-	*
-	* @param	string	$a_title	Title
-	* @param	string	$a_postvar	Post Variable
-	*/
-	function __construct($a_title = "", $a_postvar = "")
-	{
-		global $DIC;
+    protected $value;
+    
+    /**
+    * Constructor
+    *
+    * @param	string	$a_title	Title
+    * @param	string	$a_postvar	Post Variable
+    */
+    public function __construct($a_title = "", $a_postvar = "")
+    {
+        global $DIC;
 
-		$this->lng = $DIC->language();
-		$this->tpl = $DIC["tpl"];
-		parent::__construct($a_title, $a_postvar);
-	}
+        $this->lng = $DIC->language();
+        $this->tpl = $DIC["tpl"];
+        parent::__construct($a_title, $a_postvar);
+    }
 
-	/**
-	* Set Value.
-	*
-	* @param	string	$a_value	Value
-	*/
-	function setValue($a_value)
-	{
-		$this->value = $a_value;
-	}
+    /**
+    * Set Value.
+    *
+    * @param	string	$a_value	Value
+    */
+    public function setValue($a_value)
+    {
+        $this->value = $a_value;
+    }
 
-	/**
-	* Get Value.
-	*
-	* @return	string	Value
-	*/
-	function getValue()
-	{
-		return $this->value;
-	}
+    /**
+    * Get Value.
+    *
+    * @return	string	Value
+    */
+    public function getValue()
+    {
+        return $this->value;
+    }
 
-	/**
-	 * Set message string for validation failure
-	 * @return 
-	 * @param string $a_msg
-	 */
-	public function setValidationFailureMessage($a_msg)
-	{
-		$this->validationFailureMessage = $a_msg;
-	}
-	
-	public function getValidationFailureMessage()
-	{
-		return $this->validationFailureMessage;
-	}
+    /**
+     * Set message string for validation failure
+     * @return
+     * @param string $a_msg
+     */
+    public function setValidationFailureMessage($a_msg)
+    {
+        $this->validationFailureMessage = $a_msg;
+    }
+    
+    public function getValidationFailureMessage()
+    {
+        return $this->validationFailureMessage;
+    }
 
-	/**
-	* Set value by array
-	*
-	* @param	array	$a_values	value array
-	*/
-	function setValueByArray($a_values)
-	{
-		$this->setValue(self::getPostData($this->getPostVar(), false));
-	}
+    /**
+    * Set value by array
+    *
+    * @param	array	$a_values	value array
+    */
+    public function setValueByArray($a_values)
+    {
+        $this->setValue(self::getPostData($this->getPostVar(), false));
+    }
 
-	/**
-	* Check input, strip slashes etc. set alert, if input is not ok.
-	*
-	* @return	boolean		Input ok, true/false
-	*/	
-	function checkInput()
-	{
-		$lng = $this->lng;
-		
-		$data = self::getPostData($this->getPostVar(), false);
-		if(sizeof($data))
-		{
-			// slots may not overlap
-			foreach($data as $slot => $days)
-			{
-				if(!$days)
-				{
-					$this->setAlert($lng->txt("msg_input_does_not_match_regexp"));
-					return false;
-				}
-				$parts = explode("-", $slot);
-				$from = str_replace(":", "", $parts[0]);
-				$to = str_replace(":", "", $parts[1]);
-				if($from > $to)
-				{
-					$this->setAlert($lng->txt("msg_input_does_not_match_regexp"));
-					return false;
-				}
-				
-				foreach($data as $rslot => $rdays)
-				{
-					if($slot != $rslot && $rdays && array_intersect($days, $rdays))
-					{
-						$rparts = explode("-", $rslot);
-						$rfrom = str_replace(":", "", $rparts[0]);
-						$rto = str_replace(":", "", $rparts[1]);
-						
-						if(($rfrom > $from && $rfrom < $to) || 
-							($rto > $from && $rto < $to) ||
-							($rfrom < $from && $rto > $to))
-						{
-							$this->setAlert($lng->txt("msg_input_does_not_match_regexp"));
-							return false;
-						}
-					}					
-				}				
-			}
+    /**
+    * Check input, strip slashes etc. set alert, if input is not ok.
+    *
+    * @return	boolean		Input ok, true/false
+    */
+    public function checkInput()
+    {
+        $lng = $this->lng;
+        
+        $data = self::getPostData($this->getPostVar(), false);
+        if (sizeof($data)) {
+            // slots may not overlap
+            foreach ($data as $slot => $days) {
+                if (!$days) {
+                    $this->setAlert($lng->txt("msg_input_does_not_match_regexp"));
+                    return false;
+                }
+                $parts = explode("-", $slot);
+                $from = str_replace(":", "", $parts[0]);
+                $to = str_replace(":", "", $parts[1]);
+                if ($from > $to) {
+                    $this->setAlert($lng->txt("msg_input_does_not_match_regexp"));
+                    return false;
+                }
+                
+                foreach ($data as $rslot => $rdays) {
+                    if ($slot != $rslot && $rdays && array_intersect($days, $rdays)) {
+                        $rparts = explode("-", $rslot);
+                        $rfrom = str_replace(":", "", $rparts[0]);
+                        $rto = str_replace(":", "", $rparts[1]);
+                        
+                        if (($rfrom > $from && $rfrom < $to) ||
+                            ($rto > $from && $rto < $to) ||
+                            ($rfrom < $from && $rto > $to)) {
+                            $this->setAlert($lng->txt("msg_input_does_not_match_regexp"));
+                            return false;
+                        }
+                    }
+                }
+            }
 
-			return true;
-		}
-		
-		if ($this->getRequired())
-		{
-			$this->setAlert($lng->txt("msg_input_is_required"));
-			return false;
-		}
+            return true;
+        }
+        
+        if ($this->getRequired()) {
+            $this->setAlert($lng->txt("msg_input_is_required"));
+            return false;
+        }
 
-		return true;
-	}
-	
-	static function getPostData($a_post_var, $a_remove_invalid = true)
-	{
-		$res = array();		
-		for($loop = 0; $loop < 24; $loop++)
-		{
-			$days = $_POST[$a_post_var."_days~".$loop];		
-			$from = self::parseTime($_POST[$a_post_var."_from_hh~".$loop],
-				$_POST[$a_post_var."_from_mm~".$loop]);
-			$to = self::parseTime($_POST[$a_post_var."_to_hh~".$loop],
-				$_POST[$a_post_var."_to_mm~".$loop]);
-			
-			// only if any part was edited (js based gui)
-			if($days || $from != "00:00" || $to != "00:00")
-			{				
-				$slot = $from."-".$to;				
-				if($days)
-				{
-					if(isset($res[$slot]))
-					{
-						$res[$slot] = array_unique(array_merge($res[$slot], $days));		
-					}
-					else
-					{
-						$res[$slot] = $days;
-					}
-				}
-				else
-				{
-					$res[$slot] = array();
-				}
-				
-				if($a_remove_invalid && !($days && $from && $to && $from != $to))
-				{						
-					unset($res[$slot]);
-				}
-			}
-		}
-		
-		return $res;		
-	}
-	
-	/**
-	* Render item
-	*/
-	protected function render($a_mode = "")
-	{
-		$lng = $this->lng;
-		
-		$tpl = new ilTemplate("tpl.schedule_input.html", true, true, "Modules/BookingManager");
-		
-		$lng->loadLanguageModule("dateplaner");
-		
-		$def = $this->getValue();
-		if(!$def)
-		{
-			$def = array(null=>null);
-		}
-			
-		$days = array("Mo", "Tu", "We", "Th", "Fr", "Sa", "Su");
-		$row = 0;
-		foreach($def as $slot => $days_select)
-		{
-			$tpl->setCurrentBlock("days");				
-			foreach($days as $day)
-			{
-				$day_value = strtolower($day);
-				
-				$tpl->setVariable("ROW", $row);
-				$tpl->setVariable("ID", $this->getFieldId());
-				$tpl->setVariable("POST_VAR", $this->getPostVar());
-				$tpl->setVariable("DAY", $day_value);
-				$tpl->setVariable("TXT_DAY", $lng->txt($day."_short"));
-				
-				if($days_select && in_array($day_value, $days_select))
-				{
-					$tpl->setVariable("DAY_STATUS", " checked=\"checked\"");
-				}				
-				
-				$tpl->parseCurrentBlock();
-			}
+        return true;
+    }
+    
+    public static function getPostData($a_post_var, $a_remove_invalid = true)
+    {
+        $res = array();
+        for ($loop = 0; $loop < 24; $loop++) {
+            $days = $_POST[$a_post_var . "_days~" . $loop];
+            $from = self::parseTime(
+                $_POST[$a_post_var . "_from_hh~" . $loop],
+                $_POST[$a_post_var . "_from_mm~" . $loop]
+            );
+            $to = self::parseTime(
+                $_POST[$a_post_var . "_to_hh~" . $loop],
+                $_POST[$a_post_var . "_to_mm~" . $loop]
+            );
+            
+            // only if any part was edited (js based gui)
+            if ($days || $from != "00:00" || $to != "00:00") {
+                $slot = $from . "-" . $to;
+                if ($days) {
+                    if (isset($res[$slot])) {
+                        $res[$slot] = array_unique(array_merge($res[$slot], $days));
+                    } else {
+                        $res[$slot] = $days;
+                    }
+                } else {
+                    $res[$slot] = array();
+                }
+                
+                if ($a_remove_invalid && !($days && $from && $to && $from != $to)) {
+                    unset($res[$slot]);
+                }
+            }
+        }
+        
+        return $res;
+    }
+    
+    /**
+    * Render item
+    */
+    protected function render($a_mode = "")
+    {
+        $lng = $this->lng;
+        
+        $tpl = new ilTemplate("tpl.schedule_input.html", true, true, "Modules/BookingManager");
+        
+        $lng->loadLanguageModule("dateplaner");
+        
+        $def = $this->getValue();
+        if (!$def) {
+            $def = array(null=>null);
+        }
+            
+        $days = array("Mo", "Tu", "We", "Th", "Fr", "Sa", "Su");
+        $row = 0;
+        foreach ($def as $slot => $days_select) {
+            $tpl->setCurrentBlock("days");
+            foreach ($days as $day) {
+                $day_value = strtolower($day);
+                
+                $tpl->setVariable("ROW", $row);
+                $tpl->setVariable("ID", $this->getFieldId());
+                $tpl->setVariable("POST_VAR", $this->getPostVar());
+                $tpl->setVariable("DAY", $day_value);
+                $tpl->setVariable("TXT_DAY", $lng->txt($day . "_short"));
+                
+                if ($days_select && in_array($day_value, $days_select)) {
+                    $tpl->setVariable("DAY_STATUS", " checked=\"checked\"");
+                }
+                
+                $tpl->parseCurrentBlock();
+            }
 
-			$tpl->setCurrentBlock("row");	
-			$tpl->setVariable("ROW", $row);
-			$tpl->setVariable("ID", $this->getFieldId());
-			$tpl->setVariable("POST_VAR", $this->getPostVar());
-			$tpl->setVariable("TXT_FROM", $lng->txt("cal_from"));
-			$tpl->setVariable("TXT_TO", $lng->txt("cal_until"));
-			include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php");
-			$tpl->setVariable("IMG_MULTI_ADD", ilGlyphGUI::get(ilGlyphGUI::ADD));
-			$tpl->setVariable("IMG_MULTI_REMOVE", ilGlyphGUI::get(ilGlyphGUI::REMOVE));
-			$tpl->setVariable("TXT_MULTI_ADD", $lng->txt("add"));
-			$tpl->setVariable("TXT_MULTI_REMOVE", $lng->txt("remove"));
-			
-			if($slot)
-			{
-				$parts = explode("-", $slot);
-				$from = explode(":", $parts[0]);
-				$to = explode(":", $parts[1]);
-				
-				$tpl->setVariable("FROM_HH_VALUE", $from[0]);
-				$tpl->setVariable("FROM_MM_VALUE", $from[1]);
-				$tpl->setVariable("TO_HH_VALUE", $to[0]);
-				$tpl->setVariable("TO_MM_VALUE", $to[1]);
-			}
-			
-			// manage hidden buttons
-			if($row > 0)
-			{
-				// inline needed because of JS
-				 $tpl->setVariable("ADD_STYLE", " style=\"display:none\""); 
-				// $tpl->setVariable("ADD_CLASS", "ilNoDisplay");				
-			}
-			else
-			{
-				// inline needed because of JS
-				$tpl->setVariable("RMV_STYLE", " style=\"display:none\""); 
-				// $tpl->setVariable("RMV_CLASS", "ilNoDisplay");		
-			}
-			
-			$tpl->parseCurrentBlock();
-			
-			$row++;
-		}
-		
-		return $tpl->get();
-	}
-	
-	/**
-	* Insert property html
-	*
-	* @return	int	Size
-	*/
-	function insert(&$a_tpl)
-	{
-		$tpl = $this->tpl;
-		
-		$tpl->addJavascript("Modules/BookingManager/js/ScheduleInput.js");
-		
-		$html = $this->render();
+            $tpl->setCurrentBlock("row");
+            $tpl->setVariable("ROW", $row);
+            $tpl->setVariable("ID", $this->getFieldId());
+            $tpl->setVariable("POST_VAR", $this->getPostVar());
+            $tpl->setVariable("TXT_FROM", $lng->txt("cal_from"));
+            $tpl->setVariable("TXT_TO", $lng->txt("cal_until"));
+            include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php");
+            $tpl->setVariable("IMG_MULTI_ADD", ilGlyphGUI::get(ilGlyphGUI::ADD));
+            $tpl->setVariable("IMG_MULTI_REMOVE", ilGlyphGUI::get(ilGlyphGUI::REMOVE));
+            $tpl->setVariable("TXT_MULTI_ADD", $lng->txt("add"));
+            $tpl->setVariable("TXT_MULTI_REMOVE", $lng->txt("remove"));
+            
+            if ($slot) {
+                $parts = explode("-", $slot);
+                $from = explode(":", $parts[0]);
+                $to = explode(":", $parts[1]);
+                
+                $tpl->setVariable("FROM_HH_VALUE", $from[0]);
+                $tpl->setVariable("FROM_MM_VALUE", $from[1]);
+                $tpl->setVariable("TO_HH_VALUE", $to[0]);
+                $tpl->setVariable("TO_MM_VALUE", $to[1]);
+            }
+            
+            // manage hidden buttons
+            if ($row > 0) {
+                // inline needed because of JS
+                $tpl->setVariable("ADD_STYLE", " style=\"display:none\"");
+            // $tpl->setVariable("ADD_CLASS", "ilNoDisplay");
+            } else {
+                // inline needed because of JS
+                $tpl->setVariable("RMV_STYLE", " style=\"display:none\"");
+                // $tpl->setVariable("RMV_CLASS", "ilNoDisplay");
+            }
+            
+            $tpl->parseCurrentBlock();
+            
+            $row++;
+        }
+        
+        return $tpl->get();
+    }
+    
+    /**
+    * Insert property html
+    *
+    * @return	int	Size
+    */
+    public function insert(&$a_tpl)
+    {
+        $tpl = $this->tpl;
+        
+        $tpl->addJavascript("Modules/BookingManager/js/ScheduleInput.js");
+        
+        $html = $this->render();
 
-		$a_tpl->setCurrentBlock("prop_generic");
-		$a_tpl->setVariable("PROP_GENERIC", $html);
-		$a_tpl->parseCurrentBlock();
-	}
-	
-	/**
-	 * Parse/normalize incoming time values
-	 * @param	string	$a_hours
-	 * @param	string	$a_minutes
-	 */
-	protected static function parseTime($a_hours, $a_minutes)
+        $a_tpl->setCurrentBlock("prop_generic");
+        $a_tpl->setVariable("PROP_GENERIC", $html);
+        $a_tpl->parseCurrentBlock();
+    }
+    
+    /**
+     * Parse/normalize incoming time values
+     * @param	string	$a_hours
+     * @param	string	$a_minutes
+     */
+    protected static function parseTime($a_hours, $a_minutes)
     {
-		$hours = (int)$a_hours;
-		$min = (int)$a_minutes;
-		if($hours > 23 || $min > 59)
-		{
-			return false;
-		}
-		return str_pad($hours, 2, "0", STR_PAD_LEFT).":".
-			str_pad($min, 2, "0", STR_PAD_LEFT);
-	}
+        $hours = (int) $a_hours;
+        $min = (int) $a_minutes;
+        if ($hours > 23 || $min > 59) {
+            return false;
+        }
+        return str_pad($hours, 2, "0", STR_PAD_LEFT) . ":" .
+            str_pad($min, 2, "0", STR_PAD_LEFT);
+    }
 }
-
-?>
\ No newline at end of file
diff --git a/Modules/Category/classes/class.ilCategoryAssignRoleTableGUI.php b/Modules/Category/classes/class.ilCategoryAssignRoleTableGUI.php
index 87b9a132a2c27ffc46a3c99c370a9f8829c29ccd..c0b24955ae35b746fcb851f3e259248681f2bab2 100644
--- a/Modules/Category/classes/class.ilCategoryAssignRoleTableGUI.php
+++ b/Modules/Category/classes/class.ilCategoryAssignRoleTableGUI.php
@@ -12,50 +12,48 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php");
  */
 class ilCategoryAssignRoleTableGUI extends ilTable2GUI
 {
-	/**
-	 * Constructor
-	 *
-	 * @param ilObjCategoryGUI $a_parent_obj
-	 * @param string $a_parent_cmd
-	 */
-	function __construct($a_parent_obj, $a_parent_cmd)
-	{
-		global $DIC;
+    /**
+     * Constructor
+     *
+     * @param ilObjCategoryGUI $a_parent_obj
+     * @param string $a_parent_cmd
+     */
+    public function __construct($a_parent_obj, $a_parent_cmd)
+    {
+        global $DIC;
 
-		$this->ctrl = $DIC->ctrl();
-		$this->lng = $DIC->language();
-		$ilCtrl = $DIC->ctrl();
-		$lng = $DIC->language();
-		
-		$this->setId("ilcatluaar");
-		
-		parent::__construct($a_parent_obj, $a_parent_cmd);
+        $this->ctrl = $DIC->ctrl();
+        $this->lng = $DIC->language();
+        $ilCtrl = $DIC->ctrl();
+        $lng = $DIC->language();
+        
+        $this->setId("ilcatluaar");
+        
+        parent::__construct($a_parent_obj, $a_parent_cmd);
 
-		$this->addColumn("", "", "", true,"4%");
-		$this->addColumn($lng->txt("title"), "title","35%");
-		$this->addColumn($lng->txt("description"), "desc","45%");
-		$this->addColumn($lng->txt("type"), "type","16%");
-		
-		$this->addMultiCommand('assignSave', $lng->txt("change_assignment"));
-	
-		$ilCtrl->saveParameter($a_parent_obj, 'obj_id');
-		$this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd));
-		$this->setRowTemplate("tpl.cat_role_assignment.html", "Modules/Category");
-		$this->setDefaultOrderDirection("asc");
-		$this->setShowRowsSelector(false);
-		$this->setLimit(999999);
-	}
+        $this->addColumn("", "", "", true, "4%");
+        $this->addColumn($lng->txt("title"), "title", "35%");
+        $this->addColumn($lng->txt("description"), "desc", "45%");
+        $this->addColumn($lng->txt("type"), "type", "16%");
+        
+        $this->addMultiCommand('assignSave', $lng->txt("change_assignment"));
+    
+        $ilCtrl->saveParameter($a_parent_obj, 'obj_id');
+        $this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd));
+        $this->setRowTemplate("tpl.cat_role_assignment.html", "Modules/Category");
+        $this->setDefaultOrderDirection("asc");
+        $this->setShowRowsSelector(false);
+        $this->setLimit(999999);
+    }
 
-	/**
-	 * @param array $a_set
-	 */
-	protected function fillRow($a_set)
-	{
-		$this->tpl->setVariable("INPUT_CHCKBX", $a_set["checkbox"]);
-		$this->tpl->setVariable("TXT_TITLE", $a_set["title"]);
-		$this->tpl->setVariable("TXT_DESCRIPTION", $a_set["desc"]);		
-		$this->tpl->setVariable("TXT_TYPE", $a_set["type"]);
-	}
+    /**
+     * @param array $a_set
+     */
+    protected function fillRow($a_set)
+    {
+        $this->tpl->setVariable("INPUT_CHCKBX", $a_set["checkbox"]);
+        $this->tpl->setVariable("TXT_TITLE", $a_set["title"]);
+        $this->tpl->setVariable("TXT_DESCRIPTION", $a_set["desc"]);
+        $this->tpl->setVariable("TXT_TYPE", $a_set["type"]);
+    }
 }
-
-?>
\ No newline at end of file
diff --git a/Modules/Category/classes/class.ilCategoryConditionController.php b/Modules/Category/classes/class.ilCategoryConditionController.php
index 41ca72e0189d988910df004c854f9f6cb0644ea3..e974660aa1374f4ed3849924ad526658bd0f2812 100644
--- a/Modules/Category/classes/class.ilCategoryConditionController.php
+++ b/Modules/Category/classes/class.ilCategoryConditionController.php
@@ -12,33 +12,31 @@ include_once("./Services/Conditions/interfaces/interface.ilConditionControllerIn
  */
 class ilCategoryConditionController implements ilConditionControllerInterface
 {
-	/**
-	 * @inheritdoc
-	 */
-	public function isContainerConditionController($container_ref_id): bool
-	{
-		return false;
-		return true;
-	}
-
-	/**
-	 * @inheritdoc
-	 */
-	public function getConditionSetForRepositoryObject($ref_id): ilConditionSet
-	{
-		global $DIC;
-
-		$f = $DIC->conditions()->factory();
-
-		$conditions = array();
-		if ($ref_id == 72)
-		{
-//			$conditions[] = $f->condition($f->repositoryTrigger(73), $f->operator()->passed());
-		}
-
-
-
-		return $f->set($conditions);
-	}
-
-}
\ No newline at end of file
+    /**
+     * @inheritdoc
+     */
+    public function isContainerConditionController($container_ref_id) : bool
+    {
+        return false;
+        return true;
+    }
+
+    /**
+     * @inheritdoc
+     */
+    public function getConditionSetForRepositoryObject($ref_id) : ilConditionSet
+    {
+        global $DIC;
+
+        $f = $DIC->conditions()->factory();
+
+        $conditions = array();
+        if ($ref_id == 72) {
+            //			$conditions[] = $f->condition($f->repositoryTrigger(73), $f->operator()->passed());
+        }
+
+
+
+        return $f->set($conditions);
+    }
+}
diff --git a/Modules/Category/classes/class.ilCategoryExporter.php b/Modules/Category/classes/class.ilCategoryExporter.php
index 7b995d908ff85777b8ebd8bb16a750b58ccca29f..0c2695666e9dc840815055d21b7074b1bcc7b7b4 100644
--- a/Modules/Category/classes/class.ilCategoryExporter.php
+++ b/Modules/Category/classes/class.ilCategoryExporter.php
@@ -5,142 +5,136 @@ include_once './Services/Export/classes/class.ilXmlExporter.php';
 
 /**
  * Class for category export
- * 
+ *
  * @author Stefan Meyer 
  * $Id$
  */
 class ilCategoryExporter extends ilXmlExporter
 {
-	/**
-	 * Get head dependencies
-	 *
-	 * @param		string		entity
-	 * @param		string		target release
-	 * @param		array		ids
-	 * @return		array		array of array with keys "component", entity", "ids"
-	 */
-	public function getXmlExportHeadDependencies($a_entity, $a_target_release, $a_ids)
-	{
-		// always trigger container because of co-page(s)
-		return array(
-			array(
-				'component'		=> 'Services/Container',
-				'entity'		=> 'struct',
-				'ids'			=> $a_ids
-			)
-		);
-		
-		/*
-		include_once './Services/Export/classes/class.ilExportOptions.php';
-		$eo = ilExportOptions::getInstance();
+    /**
+     * Get head dependencies
+     *
+     * @param		string		entity
+     * @param		string		target release
+     * @param		array		ids
+     * @return		array		array of array with keys "component", entity", "ids"
+     */
+    public function getXmlExportHeadDependencies($a_entity, $a_target_release, $a_ids)
+    {
+        // always trigger container because of co-page(s)
+        return array(
+            array(
+                'component'		=> 'Services/Container',
+                'entity'		=> 'struct',
+                'ids'			=> $a_ids
+            )
+        );
+        
+        /*
+        include_once './Services/Export/classes/class.ilExportOptions.php';
+        $eo = ilExportOptions::getInstance();
 
-		$obj_id = end($a_ids);
+        $obj_id = end($a_ids);
 
 
-		$GLOBALS['ilLog']->write(__METHOD__.': '.$obj_id);
-		if($eo->getOption(ilExportOptions::KEY_ROOT) != $obj_id)
-		{
-			return array();
-		}
-		
-		if(count(ilExportOptions::getInstance()->getSubitemsForExport()) > 1)
-		{
-			return array(
-				array(
-					'component'		=> 'Services/Container',
-					'entity'		=> 'struct',
-					'ids'			=> $a_ids
-				)
-			);
-		}
-		return array();		 
-		*/
-	}
-	
-	/**
-	 * Get tail dependencies
-	 *
-	 * @param		string		entity
-	 * @param		string		target release
-	 * @param		array		ids
-	 * @return		array		array of array with keys "component", entity", "ids"
-	 */
-	function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids)
-	{
-		if ($a_entity == "cat")
-		{
-			include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php");
-			$tax_ids = array();
-			foreach ($a_ids as $id)
-			{
-				$t_ids = ilObjTaxonomy::getUsageOfObject($id);
-				if (count($t_ids) > 0)
-				{
-					$tax_ids[$t_ids[0]] = $t_ids[0];
-				}
-			}
+        $GLOBALS['ilLog']->write(__METHOD__.': '.$obj_id);
+        if($eo->getOption(ilExportOptions::KEY_ROOT) != $obj_id)
+        {
+            return array();
+        }
 
-			return array (
-				array(
-					"component" => "Services/Taxonomy",
-					"entity" => "tax",
-					"ids" => $tax_ids)
-				);
-		}
-		return array();
-	}
+        if(count(ilExportOptions::getInstance()->getSubitemsForExport()) > 1)
+        {
+            return array(
+                array(
+                    'component'		=> 'Services/Container',
+                    'entity'		=> 'struct',
+                    'ids'			=> $a_ids
+                )
+            );
+        }
+        return array();
+        */
+    }
+    
+    /**
+     * Get tail dependencies
+     *
+     * @param		string		entity
+     * @param		string		target release
+     * @param		array		ids
+     * @return		array		array of array with keys "component", entity", "ids"
+     */
+    public function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids)
+    {
+        if ($a_entity == "cat") {
+            include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php");
+            $tax_ids = array();
+            foreach ($a_ids as $id) {
+                $t_ids = ilObjTaxonomy::getUsageOfObject($id);
+                if (count($t_ids) > 0) {
+                    $tax_ids[$t_ids[0]] = $t_ids[0];
+                }
+            }
 
-	/**
-	 * Get xml
-	 * @param object $a_entity
-	 * @param object $a_schema_version
-	 * @param object $a_id
-	 * @return
-	 */
-	public function getXmlRepresentation($a_entity, $a_schema_version, $a_id)
-	{
-		$cat_ref_id = end(ilObject::_getAllReferences($a_id));
-		$category = ilObjectFactory::getInstanceByRefId($cat_ref_id,false);
+            return array(
+                array(
+                    "component" => "Services/Taxonomy",
+                    "entity" => "tax",
+                    "ids" => $tax_ids)
+                );
+        }
+        return array();
+    }
 
-		if(!$category instanceof ilObjCategory)
-		{
-			$GLOBALS['ilLog']->write(__METHOD__. $a_id . ' is not instance of type category!');
-			return '';
-		}
+    /**
+     * Get xml
+     * @param object $a_entity
+     * @param object $a_schema_version
+     * @param object $a_id
+     * @return
+     */
+    public function getXmlRepresentation($a_entity, $a_schema_version, $a_id)
+    {
+        $cat_ref_id = end(ilObject::_getAllReferences($a_id));
+        $category = ilObjectFactory::getInstanceByRefId($cat_ref_id, false);
 
-		include_once './Modules/Category/classes/class.ilCategoryXmlWriter.php';
+        if (!$category instanceof ilObjCategory) {
+            $GLOBALS['ilLog']->write(__METHOD__ . $a_id . ' is not instance of type category!');
+            return '';
+        }
 
-		$writer = new ilCategoryXmlWriter($category);
-		$writer->setMode(ilCategoryXmlWriter::MODE_EXPORT);
-		$writer->export(false);
-		return $writer->getXml();
-	}
+        include_once './Modules/Category/classes/class.ilCategoryXmlWriter.php';
 
-	/**
-	 * Returns schema versions that the component can export to.
-	 * ILIAS chooses the first one, that has min/max constraints which
-	 * fit to the target release. Please put the newest on top.
-	 *
-	 * @return
-	 */
-	public function getValidSchemaVersions($a_entity)
-	{
-		return array (
-			"4.3.0" => array(
-				"namespace" => "http://www.ilias.de/Modules/Category/cat/4_3",
-				"xsd_file" => "ilias_cat_4_3.xsd",
-				"uses_dataset" => false,
-				"min" => "4.3.0",
-				"max" => "")
-		);
-	}
+        $writer = new ilCategoryXmlWriter($category);
+        $writer->setMode(ilCategoryXmlWriter::MODE_EXPORT);
+        $writer->export(false);
+        return $writer->getXml();
+    }
 
-	/**
-	 * Init method
-	 */
-	public function init() {
-		
-	}
+    /**
+     * Returns schema versions that the component can export to.
+     * ILIAS chooses the first one, that has min/max constraints which
+     * fit to the target release. Please put the newest on top.
+     *
+     * @return
+     */
+    public function getValidSchemaVersions($a_entity)
+    {
+        return array(
+            "4.3.0" => array(
+                "namespace" => "http://www.ilias.de/Modules/Category/cat/4_3",
+                "xsd_file" => "ilias_cat_4_3.xsd",
+                "uses_dataset" => false,
+                "min" => "4.3.0",
+                "max" => "")
+        );
+    }
 
+    /**
+     * Init method
+     */
+    public function init()
+    {
+    }
 }
-?>
diff --git a/Modules/Category/classes/class.ilCategoryImportParser.php b/Modules/Category/classes/class.ilCategoryImportParser.php
index 433c696c300cc0a83ffbfbbf5d63c1c49111cc89..22278dcbb57bb746199006908699d094622d8cc5 100755
--- a/Modules/Category/classes/class.ilCategoryImportParser.php
+++ b/Modules/Category/classes/class.ilCategoryImportParser.php
@@ -1,24 +1,24 @@
 rbacadmin = $DIC->rbac()->admin();
-		$this->rbacreview = $DIC->rbac()->review();
-		$this->rbacsystem = $DIC->rbac()->system();
-		$this->parent_cnt = 0;
-		$this->parent[$this->parent_cnt] = $a_parent;
-		$this->parent_cnt++;
-		$this->withrol = $withrol;
-		
-		parent::__construct($a_xml_file);
-	}
-
-
-	/**
-	* set event handler
-	* should be overwritten by inherited class
-	* @access	private
-	*/
-	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
-	*/
-	function startParsing()
-	{
-		parent::startParsing();
-	}
-
-	/**
-	* generate a tag with given name and attributes
-	*
-	* @param	string		"start" | "end" for starting or ending tag
-	* @param	string		element/tag name
-	* @param	array		array of attributes
-	*/
-	function buildTag ($type, $name, $attr="")
-	{
-		$tag = "<";
-
-		if ($type == "end")
-			$tag.= "/";
-
-		$tag.= $name;
-
-		if (is_array($attr))
-		{
-			foreach ($attr as $k => $v) {
-				$tag .= " " . $k . "=\"$v\"";
-			}
-		}
-
-		$tag.= ">";
-
-		return $tag;
-	}
-
-	/**
-	* handler for begin of element
-	*/
-	function handlerBeginTag($a_xml_parser, $a_name, $a_attribs)
-	  
- 	{
-	  
-		$rbacadmin = $this->rbacadmin;
-		$rbacreview = $this->rbacreview;
-		$rbacsystem = $this->rbacsystem;
-	  
-	  switch($a_name)
-		{
-			case "Category":
-				$cur_parent = $this->parent[$this->parent_cnt - 1];
-				require_once("Modules/Category/classes/class.ilObjCategory.php");
-				$this->category = new ilObjCategory;
-				$this->category->setImportId($a_attribs["Id"]." (#".$cur_parent.")");
-				$this->default_language = $a_attribs["DefaultLanguage"];
-				$this->category->setTitle($a_attribs["Id"]);
-				$this->category->create();
-				$this->category->createReference();
-				$this->category->putInTree($cur_parent);
-				$this->parent[$this->parent_cnt++] = $this->category->getRefId();
-				break;
-
-		case "CategorySpec":
-		  $this->cur_spec_lang = $a_attribs["Language"];
-		  break;
-
-		}
-
-	}
-
-
-	/**
-	* handler for end of element
-	*/
-	function handlerEndTag($a_xml_parser, $a_name)
-	{
-		switch($a_name)
-		{
-			case "Category":
-				unset($this->category);
-				unset($this->parent[$this->parent_cnt - 1]);
-				$this->parent_cnt--;
-				break;
-
-			case "CategorySpec":
-				$is_def = 0;
-				if ($this->cur_spec_lang == $this->default_language)
-				{
-					$this->category->setTitle($this->cur_title);
-					$this->category->setDescription($this->cur_description);
-					$this->category->update();
-					$is_def = 1;
-				}
-				$this->category->addTranslation($this->cur_title,
-					$this->cur_description, $this->cur_spec_lang, $is_def);
-				break;
-
-			case "Title":
-				$this->cur_title = $this->cdata;
-				break;
-
-			case "Description":
-				$this->cur_description = $this->cdata;
-				break;
-		}
-
-		$this->cdata = "";
-	}
-
-	/**
-	* handler for character data
-	*/
-	function handlerCharacterData($a_xml_parser, $a_data)
-	{
-		// i don't know why this is necessary, but
-		// the parser seems to convert ">" to ">" and "<" to "<"
-		// in character data, but we don't want that, because it's the
-		// way we mask user html in our content, so we convert back...
-		$a_data = str_replace("<","<",$a_data);
-		$a_data = str_replace(">",">",$a_data);
-
-		// DELETE WHITESPACES AND NEWLINES OF CHARACTER DATA
-		$a_data = preg_replace("/\n/","",$a_data);
-		$a_data = preg_replace("/\t+/","",$a_data);
-		if(!empty($a_data))
-		{
-			$this->cdata .= $a_data;
-		}
-	}
-
+    /**
+    * Constructor
+    *
+    * @param	string		$a_xml_file		xml file
+    *
+    * @access	public
+    */
+    public function __construct($a_xml_file, $a_parent, $withrol)
+    {
+        global $DIC;
+
+        $this->rbacadmin = $DIC->rbac()->admin();
+        $this->rbacreview = $DIC->rbac()->review();
+        $this->rbacsystem = $DIC->rbac()->system();
+        $this->parent_cnt = 0;
+        $this->parent[$this->parent_cnt] = $a_parent;
+        $this->parent_cnt++;
+        $this->withrol = $withrol;
+        
+        parent::__construct($a_xml_file);
+    }
+
+
+    /**
+    * 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();
+    }
+
+    /**
+    * generate a tag with given name and attributes
+    *
+    * @param	string		"start" | "end" for starting or ending tag
+    * @param	string		element/tag name
+    * @param	array		array of attributes
+    */
+    public function buildTag($type, $name, $attr="")
+    {
+        $tag = "<";
+
+        if ($type == "end") {
+            $tag.= "/";
+        }
+
+        $tag.= $name;
+
+        if (is_array($attr)) {
+            foreach ($attr as $k => $v) {
+                $tag .= " " . $k . "=\"$v\"";
+            }
+        }
+
+        $tag.= ">";
+
+        return $tag;
+    }
+
+    /**
+    * handler for begin of element
+    */
+    public function handlerBeginTag($a_xml_parser, $a_name, $a_attribs)
+    {
+        $rbacadmin = $this->rbacadmin;
+        $rbacreview = $this->rbacreview;
+        $rbacsystem = $this->rbacsystem;
+      
+        switch ($a_name) {
+            case "Category":
+                $cur_parent = $this->parent[$this->parent_cnt - 1];
+                require_once("Modules/Category/classes/class.ilObjCategory.php");
+                $this->category = new ilObjCategory;
+                $this->category->setImportId($a_attribs["Id"] . " (#" . $cur_parent . ")");
+                $this->default_language = $a_attribs["DefaultLanguage"];
+                $this->category->setTitle($a_attribs["Id"]);
+                $this->category->create();
+                $this->category->createReference();
+                $this->category->putInTree($cur_parent);
+                $this->parent[$this->parent_cnt++] = $this->category->getRefId();
+                break;
+
+        case "CategorySpec":
+          $this->cur_spec_lang = $a_attribs["Language"];
+          break;
+
+        }
+    }
+
+
+    /**
+    * handler for end of element
+    */
+    public function handlerEndTag($a_xml_parser, $a_name)
+    {
+        switch ($a_name) {
+            case "Category":
+                unset($this->category);
+                unset($this->parent[$this->parent_cnt - 1]);
+                $this->parent_cnt--;
+                break;
+
+            case "CategorySpec":
+                $is_def = 0;
+                if ($this->cur_spec_lang == $this->default_language) {
+                    $this->category->setTitle($this->cur_title);
+                    $this->category->setDescription($this->cur_description);
+                    $this->category->update();
+                    $is_def = 1;
+                }
+                $this->category->addTranslation(
+                    $this->cur_title,
+                    $this->cur_description,
+                    $this->cur_spec_lang,
+                    $is_def
+                );
+                break;
+
+            case "Title":
+                $this->cur_title = $this->cdata;
+                break;
+
+            case "Description":
+                $this->cur_description = $this->cdata;
+                break;
+        }
+
+        $this->cdata = "";
+    }
+
+    /**
+    * handler for character data
+    */
+    public function handlerCharacterData($a_xml_parser, $a_data)
+    {
+        // i don't know why this is necessary, but
+        // the parser seems to convert ">" to ">" and "<" to "<"
+        // in character data, but we don't want that, because it's the
+        // way we mask user html in our content, so we convert back...
+        $a_data = str_replace("<", "<", $a_data);
+        $a_data = str_replace(">", ">", $a_data);
+
+        // DELETE WHITESPACES AND NEWLINES OF CHARACTER DATA
+        $a_data = preg_replace("/\n/", "", $a_data);
+        $a_data = preg_replace("/\t+/", "", $a_data);
+        if (!empty($a_data)) {
+            $this->cdata .= $a_data;
+        }
+    }
 }
-?>
diff --git a/Modules/Category/classes/class.ilCategoryImporter.php b/Modules/Category/classes/class.ilCategoryImporter.php
index 9ff94ec0400ca0a62a25e91e9e9564c143969d3f..0669aa8b2e36b54209d1bcd816eb2f2d7079e9d5 100644
--- a/Modules/Category/classes/class.ilCategoryImporter.php
+++ b/Modules/Category/classes/class.ilCategoryImporter.php
@@ -14,100 +14,92 @@ include_once("./Services/Export/classes/class.ilXmlImporter.php");
 */
 class ilCategoryImporter extends ilXmlImporter
 {
-	private $category = null;
-	
+    private $category = null;
+    
 
-	public function init()
-	{
-	}
-	
-	/**
-	 * Import XML
-	 *
-	 * @param
-	 * @return
-	 */
-	function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping)
-	{
-		include_once './Modules/Category/classes/class.ilObjCategory.php';
-		if($new_id = $a_mapping->getMapping('Services/Container','objs',$a_id))
-		{
-			$refs = ilObject::_getAllReferences($new_id);
-			$this->category = ilObjectFactory::getInstanceByRefId(end($refs),false);
-		}
-		// Mapping for containers without subitems
-		elseif($new_id = $a_mapping->getMapping('Services/Container','refs',0))
-		{
-			$this->category = ilObjectFactory::getInstanceByRefId($new_id,false);
-		}
-		elseif(!$this->category instanceof ilObjCategory)
-		{
-			$this->category = new ilObjCategory();
-			$this->category->create(true);
-		}
+    public function init()
+    {
+    }
+    
+    /**
+     * Import XML
+     *
+     * @param
+     * @return
+     */
+    public function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping)
+    {
+        include_once './Modules/Category/classes/class.ilObjCategory.php';
+        if ($new_id = $a_mapping->getMapping('Services/Container', 'objs', $a_id)) {
+            $refs = ilObject::_getAllReferences($new_id);
+            $this->category = ilObjectFactory::getInstanceByRefId(end($refs), false);
+        }
+        // Mapping for containers without subitems
+        elseif ($new_id = $a_mapping->getMapping('Services/Container', 'refs', 0)) {
+            $this->category = ilObjectFactory::getInstanceByRefId($new_id, false);
+        } elseif (!$this->category instanceof ilObjCategory) {
+            $this->category = new ilObjCategory();
+            $this->category->create(true);
+        }
 
-		include_once './Modules/Category/classes/class.ilCategoryXmlParser.php';
+        include_once './Modules/Category/classes/class.ilCategoryXmlParser.php';
 
-		try 
-		{
-			$parser = new ilCategoryXmlParser($a_xml,0);
-			$parser->setCategory($this->category);
-			$parser->setMode(ilCategoryXmlParser::MODE_UPDATE);
-			$parser->startParsing();
-			$a_mapping->addMapping('Modules/Category','cat',$a_id,$this->category->getId());
-		}
-		catch(ilSaxParserException $e)
-		{
-			$GLOBALS['ilLog']->write(__METHOD__.': Parsing failed with message, "'.$e->getMessage().'".');
-		}
-		catch(Exception $e)
-		{
-			$GLOBALS['ilLog']->write(__METHOD__.': Parsing failed with message, "'.$e->getMessage().'".');
-		}
-							
-		foreach($a_mapping->getMappingsOfEntity('Services/Container', 'objs') as $old => $new)
-		{
-			$type = ilObject::_lookupType($new);
-			
-			// see ilGlossaryImporter::importXmlRepresentation()
-			// see ilTaxonomyDataSet::importRecord()
-			
-			$a_mapping->addMapping("Services/Taxonomy", "tax_item",
-				$type.":obj:".$old, $new);
+        try {
+            $parser = new ilCategoryXmlParser($a_xml, 0);
+            $parser->setCategory($this->category);
+            $parser->setMode(ilCategoryXmlParser::MODE_UPDATE);
+            $parser->startParsing();
+            $a_mapping->addMapping('Modules/Category', 'cat', $a_id, $this->category->getId());
+        } catch (ilSaxParserException $e) {
+            $GLOBALS['ilLog']->write(__METHOD__ . ': Parsing failed with message, "' . $e->getMessage() . '".');
+        } catch (Exception $e) {
+            $GLOBALS['ilLog']->write(__METHOD__ . ': Parsing failed with message, "' . $e->getMessage() . '".');
+        }
+                            
+        foreach ($a_mapping->getMappingsOfEntity('Services/Container', 'objs') as $old => $new) {
+            $type = ilObject::_lookupType($new);
+            
+            // see ilGlossaryImporter::importXmlRepresentation()
+            // see ilTaxonomyDataSet::importRecord()
+            
+            $a_mapping->addMapping(
+                "Services/Taxonomy",
+                "tax_item",
+                $type . ":obj:" . $old,
+                $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
-	 */
-	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); - } - } - } - } - + // 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 $ilSetting - * @return - */ - protected function buildHeader() - { - $ilSetting = $this->settings; - - $this->xmlSetDtdDef(""); - $this->xmlSetGenCmt("Export of ILIAS category ". $this->getCategory()->getId()." of installation ".$ilSetting->get('inst_id')."."); - $this->xmlHeader(); - - - return true; - } - - /** - * Build category xml - */ - protected function buildCategory() - { - $this->xmlStartTag('Category'); - } - - /** - * Add footer elements - */ - protected function buildFooter() - { - $this->xmlEndTag('Category'); - } - - /** - * Add Translations - */ - protected function buildTranslations() - { - $this->xmlStartTag('Translations'); - - $translations = $this->getCategory()->getObjectTranslation()->getLanguages(); - - - foreach((array) $translations as $translation) - { - $this->xmlStartTag('Translation', array( - 'default' => (int) $translation['lang_default'], - 'language' => $translation['lang']) - ); - $this->xmlElement('Title', array(),$translation['title']); - $this->xmlElement('Description',array(),$translation['desc']); - $this->xmlEndTag('Translation'); - } - $this->xmlEndTag('Translations'); - } + /** + * @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 $ilSetting + * @return + */ + protected function buildHeader() + { + $ilSetting = $this->settings; + + $this->xmlSetDtdDef(""); + $this->xmlSetGenCmt("Export of ILIAS category " . $this->getCategory()->getId() . " of installation " . $ilSetting->get('inst_id') . "."); + $this->xmlHeader(); + + + return true; + } + + /** + * Build category xml + */ + protected function buildCategory() + { + $this->xmlStartTag('Category'); + } + + /** + * Add footer elements + */ + protected function buildFooter() + { + $this->xmlEndTag('Category'); + } + + /** + * Add Translations + */ + protected function buildTranslations() + { + $this->xmlStartTag('Translations'); + + $translations = $this->getCategory()->getObjectTranslation()->getLanguages(); + + + foreach ((array) $translations as $translation) { + $this->xmlStartTag( + 'Translation', + array( + 'default' => (int) $translation['lang_default'], + 'language' => $translation['lang']) + ); + $this->xmlElement('Title', array(), $translation['title']); + $this->xmlElement('Description', array(), $translation['desc']); + $this->xmlEndTag('Translation'); + } + $this->xmlEndTag('Translations'); + } } -?> \ No newline at end of file diff --git a/Modules/Category/classes/class.ilECSCategorySettings.php b/Modules/Category/classes/class.ilECSCategorySettings.php index 469d4f4e78e49e8702b5a960deea7ad1e429437a..786f558d366ecb9ceebbe86ed62c7d354b2714c2 100644 --- a/Modules/Category/classes/class.ilECSCategorySettings.php +++ b/Modules/Category/classes/class.ilECSCategorySettings.php @@ -1,30 +1,28 @@ - -* $Id: class.ilObjCourseGUI.php 31646 2011-11-14 11:39:37Z jluetzen $ -* -* @ingroup Modules/Category -*/ -class ilECSCategorySettings extends ilECSObjectSettings -{ - protected function getECSObjectType() - { - return '/campusconnect/categories'; - } - - protected function buildJson(ilECSSetting $a_server) - { - $json = $this->getJsonCore('application/ecs-category'); - - return $json; - } -} - -?> \ No newline at end of file + +* $Id: class.ilObjCourseGUI.php 31646 2011-11-14 11:39:37Z jluetzen $ +* +* @ingroup Modules/Category +*/ +class ilECSCategorySettings extends ilECSObjectSettings +{ + protected function getECSObjectType() + { + return '/campusconnect/categories'; + } + + protected function buildJson(ilECSSetting $a_server) + { + $json = $this->getJsonCore('application/ecs-category'); + + return $json; + } +} diff --git a/Modules/Category/classes/class.ilObjCategory.php b/Modules/Category/classes/class.ilObjCategory.php index 56d36f5c85f1ccc3649cca07887b8c4c692c7c81..d435bc6ee76600b30458c6e7203cebba0c510a41 100755 --- a/Modules/Category/classes/class.ilObjCategory.php +++ b/Modules/Category/classes/class.ilObjCategory.php @@ -10,153 +10,142 @@ require_once "./Services/Container/classes/class.ilContainer.php"; /** * Class ilObjCategory -* -* @author Stefan Meyer +* +* @author Stefan Meyer * @version $Id$ * * @ingroup ModulesCategory */ class ilObjCategory extends ilContainer { - /** - * Constructor - * @access public - * @param integer reference_id or object_id - * @param boolean treat the id as reference_id (true) or object_id (false) - */ - function __construct($a_id = 0,$a_call_by_reference = true) - { - global $DIC; + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + global $DIC; - $this->db = $DIC->database(); - $this->app_event_handler = $DIC["ilAppEventHandler"]; - $this->log = $DIC["ilLog"]; - $this->user = $DIC->user(); - $this->type = "cat"; - parent::__construct($a_id,$a_call_by_reference); - } + $this->db = $DIC->database(); + $this->app_event_handler = $DIC["ilAppEventHandler"]; + $this->log = $DIC["ilLog"]; + $this->user = $DIC->user(); + $this->type = "cat"; + parent::__construct($a_id, $a_call_by_reference); + } - /** - * delete category and all related data - * - * @access public - * @return boolean true if all object data were removed; false if only a references were removed - */ - function delete() - { - $ilDB = $this->db; - $ilAppEventHandler = $this->app_event_handler; - - // always call parent delete function first!! - if (!parent::delete()) - { - return false; - } - - // put here category specific stuff - include_once('./Services/User/classes/class.ilObjUserFolder.php'); - ilObjUserFolder::_updateUserFolderAssignment($this->ref_id,USER_FOLDER_ID); + /** + * delete category and all related data + * + * @access public + * @return boolean true if all object data were removed; false if only a references were removed + */ + public function delete() + { + $ilDB = $this->db; + $ilAppEventHandler = $this->app_event_handler; + + // always call parent delete function first!! + if (!parent::delete()) { + return false; + } + + // put here category specific stuff + include_once('./Services/User/classes/class.ilObjUserFolder.php'); + ilObjUserFolder::_updateUserFolderAssignment($this->ref_id, USER_FOLDER_ID); - // taxonomies - include_once "Services/Taxonomy/classes/class.ilObjTaxonomy.php"; - foreach(ilObjTaxonomy::getUsageOfObject($this->getId()) as $tax_id) - { - if($tax_id) - { - $tax = new ilObjTaxonomy($tax_id); - $tax->delete(); - } - } - - $ilAppEventHandler->raise('Modules/Category', - 'delete', - array('object' => $this, - 'obj_id' => $this->getId())); - - return true; - } + // taxonomies + include_once "Services/Taxonomy/classes/class.ilObjTaxonomy.php"; + foreach (ilObjTaxonomy::getUsageOfObject($this->getId()) as $tax_id) { + if ($tax_id) { + $tax = new ilObjTaxonomy($tax_id); + $tax->delete(); + } + } + + $ilAppEventHandler->raise( + 'Modules/Category', + 'delete', + array('object' => $this, + 'obj_id' => $this->getId()) + ); + + return true; + } - /** - * Clone course (no member data) - * - * @access public - * @param int target ref_id - * @param int copy id - * - */ - public function cloneObject($a_target_id,$a_copy_id = 0, $a_omit_tree = false) - { - $new_obj = parent::cloneObject($a_target_id,$a_copy_id,$a_omit_tree); + /** + * Clone course (no member data) + * + * @access public + * @param int target ref_id + * @param int copy id + * + */ + public function cloneObject($a_target_id, $a_copy_id = 0, $a_omit_tree = false) + { + $new_obj = parent::cloneObject($a_target_id, $a_copy_id, $a_omit_tree); - return $new_obj; - } - - public function cloneDependencies($a_target_id,$a_copy_id) - { - parent::cloneDependencies($a_target_id,$a_copy_id); - - - // clone taxonomies - - include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php"); - $all_tax = ilObjTaxonomy::getUsageOfObject($this->getId()); - if(sizeof($all_tax)) - { - include_once("./Services/Taxonomy/classes/class.ilTaxNodeAssignment.php"); - - $cwo = ilCopyWizardOptions::_getInstance($a_copy_id); - $mappings = $cwo->getMappings(); - - foreach($all_tax as $old_tax_id) - { - if($old_tax_id) - { - // clone it - $old_tax = new ilObjTaxonomy($old_tax_id); - $new_tax = $old_tax->cloneObject(0,0,true); - $tax_map = $old_tax->getNodeMapping(); - - // assign new taxonomy to new category - ilObjTaxonomy::saveUsage($new_tax->getId(), ilObject::_lookupObjId($a_target_id)); - - // clone assignments (for all sub-items) - foreach($mappings as $old_ref_id => $new_ref_id) - { - if($old_ref_id != $new_ref_id) - { - $old_obj_id = ilObject::_lookupObjId($old_ref_id); - $new_obj_id = ilObject::_lookupObjId($new_ref_id); - $obj_type = ilObject::_lookupType($old_obj_id); - - $tax_ass = new ilTaxNodeAssignment($obj_type, $old_obj_id, "obj", $old_tax_id); - $assignmts = $tax_ass->getAssignmentsOfItem($old_obj_id); - if(sizeof($assignmts)) - { - $new_tax_ass = new ilTaxNodeAssignment($obj_type, $new_obj_id, "obj", $new_tax->getId()); - foreach($assignmts as $a) - { - if($tax_map[$a["node_id"]]) - { - $new_tax_ass->addAssignment($tax_map[$a["node_id"]], $new_obj_id); - } - } - } - } - } - } - } - } - } - - /** - * Add additional information to sub item, e.g. used in - * courses for timings information etc. - */ - function addAdditionalSubItemInformation(&$a_item_data) - { - include_once './Services/Object/classes/class.ilObjectActivation.php'; - ilObjectActivation::addAdditionalSubItemInformation($a_item_data); - } - + return $new_obj; + } + + public function cloneDependencies($a_target_id, $a_copy_id) + { + parent::cloneDependencies($a_target_id, $a_copy_id); + + + // clone taxonomies + + include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php"); + $all_tax = ilObjTaxonomy::getUsageOfObject($this->getId()); + if (sizeof($all_tax)) { + include_once("./Services/Taxonomy/classes/class.ilTaxNodeAssignment.php"); + + $cwo = ilCopyWizardOptions::_getInstance($a_copy_id); + $mappings = $cwo->getMappings(); + + foreach ($all_tax as $old_tax_id) { + if ($old_tax_id) { + // clone it + $old_tax = new ilObjTaxonomy($old_tax_id); + $new_tax = $old_tax->cloneObject(0, 0, true); + $tax_map = $old_tax->getNodeMapping(); + + // assign new taxonomy to new category + ilObjTaxonomy::saveUsage($new_tax->getId(), ilObject::_lookupObjId($a_target_id)); + + // clone assignments (for all sub-items) + foreach ($mappings as $old_ref_id => $new_ref_id) { + if ($old_ref_id != $new_ref_id) { + $old_obj_id = ilObject::_lookupObjId($old_ref_id); + $new_obj_id = ilObject::_lookupObjId($new_ref_id); + $obj_type = ilObject::_lookupType($old_obj_id); + + $tax_ass = new ilTaxNodeAssignment($obj_type, $old_obj_id, "obj", $old_tax_id); + $assignmts = $tax_ass->getAssignmentsOfItem($old_obj_id); + if (sizeof($assignmts)) { + $new_tax_ass = new ilTaxNodeAssignment($obj_type, $new_obj_id, "obj", $new_tax->getId()); + foreach ($assignmts as $a) { + if ($tax_map[$a["node_id"]]) { + $new_tax_ass->addAssignment($tax_map[$a["node_id"]], $new_obj_id); + } + } + } + } + } + } + } + } + } + + /** + * Add additional information to sub item, e.g. used in + * courses for timings information etc. + */ + public function addAdditionalSubItemInformation(&$a_item_data) + { + include_once './Services/Object/classes/class.ilObjectActivation.php'; + ilObjectActivation::addAdditionalSubItemInformation($a_item_data); + } } // END class.ilObjCategory -?> \ No newline at end of file diff --git a/Modules/Category/classes/class.ilObjCategoryAccess.php b/Modules/Category/classes/class.ilObjCategoryAccess.php index 70747fd0d702bb441c3b5775f5da9595ac6f1001..c998a1398d32b4cffbb85a4f92f321f38f3da391 100644 --- a/Modules/Category/classes/class.ilObjCategoryAccess.php +++ b/Modules/Category/classes/class.ilObjCategoryAccess.php @@ -16,80 +16,71 @@ include_once("./Services/Object/classes/class.ilObjectAccess.php"); class ilObjCategoryAccess extends ilObjectAccess { - /** - * 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(); - $commands[] = array("permission" => "read", "cmd" => "render", "lang_var" => "show", "default" => true); - + /** + * 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(); + $commands[] = array("permission" => "read", "cmd" => "render", "lang_var" => "show", "default" => true); + - // begin-patch fm - include_once './Services/WebServices/FileManager/classes/class.ilFMSettings.php'; - if(ilFMSettings::getInstance()->isEnabled()) - { - $commands[] = array( - 'permission' => 'read', - 'cmd' => 'fileManagerLaunch', - 'lang_var' => 'fm_start', - 'enable_anonymous' => false - ); - } - // end-patch fm + // begin-patch fm + include_once './Services/WebServices/FileManager/classes/class.ilFMSettings.php'; + if (ilFMSettings::getInstance()->isEnabled()) { + $commands[] = array( + 'permission' => 'read', + 'cmd' => 'fileManagerLaunch', + 'lang_var' => 'fm_start', + 'enable_anonymous' => false + ); + } + // end-patch fm - // BEGIN WebDAV - require_once ('Services/WebDAV/classes/class.ilDAVActivationChecker.php'); - if (ilDAVActivationChecker::_isActive()) - { - include_once './Services/WebDAV/classes/class.ilWebDAVUtil.php'; - if(ilWebDAVUtil::getInstance()->isLocalPasswordInstructionRequired()) - { - $commands[] = array('permission' => 'read', 'cmd' => 'showPasswordInstruction', 'lang_var' => 'mount_webfolder', 'enable_anonymous' => 'false'); - } - else - { - $commands[] = array("permission" => "read", "cmd" => "mount_webfolder", "lang_var" => "mount_webfolder", "enable_anonymous" => "false"); - } - } - // END WebDAV - $commands[] = array("permission" => "write", "cmd" => "enableAdministrationPanel", "lang_var" => "edit_content"); - $commands[] = array("permission" => "write", "cmd" => "edit", "lang_var" => "settings"); - - return $commands; - } - - /** - * check whether goto script will succeed - */ - static function _checkGoto($a_target) - { - global $DIC; + // BEGIN WebDAV + require_once('Services/WebDAV/classes/class.ilDAVActivationChecker.php'); + if (ilDAVActivationChecker::_isActive()) { + include_once './Services/WebDAV/classes/class.ilWebDAVUtil.php'; + if (ilWebDAVUtil::getInstance()->isLocalPasswordInstructionRequired()) { + $commands[] = array('permission' => 'read', 'cmd' => 'showPasswordInstruction', 'lang_var' => 'mount_webfolder', 'enable_anonymous' => 'false'); + } else { + $commands[] = array("permission" => "read", "cmd" => "mount_webfolder", "lang_var" => "mount_webfolder", "enable_anonymous" => "false"); + } + } + // END WebDAV + $commands[] = array("permission" => "write", "cmd" => "enableAdministrationPanel", "lang_var" => "edit_content"); + $commands[] = array("permission" => "write", "cmd" => "edit", "lang_var" => "settings"); + + return $commands; + } + + /** + * check whether goto script will succeed + */ + public static function _checkGoto($a_target) + { + global $DIC; - $ilAccess = $DIC->access(); - - $t_arr = explode("_", $a_target); + $ilAccess = $DIC->access(); + + $t_arr = explode("_", $a_target); - if ($t_arr[0] != "cat" || ((int) $t_arr[1]) <= 0) - { - return false; - } + if ($t_arr[0] != "cat" || ((int) $t_arr[1]) <= 0) { + return false; + } - if ($ilAccess->checkAccess("read", "", $t_arr[1])) - { - return true; - } - return false; - } + if ($ilAccess->checkAccess("read", "", $t_arr[1])) { + return true; + } + return false; + } } - -?> diff --git a/Modules/Category/classes/class.ilObjCategoryGUI.php b/Modules/Category/classes/class.ilObjCategoryGUI.php index 6b0094afbf394f3bda20f144aef1f1c2baa263de..cdfced1e680e151c96c3e936a1a30bb37361d283 100755 --- a/Modules/Category/classes/class.ilObjCategoryGUI.php +++ b/Modules/Category/classes/class.ilObjCategoryGUI.php @@ -20,1484 +20,1446 @@ require_once "./Services/Container/classes/class.ilContainerGUI.php"; */ class ilObjCategoryGUI extends ilContainerGUI { - /** - * @var ilNavigationHistory - */ - protected $nav_history; - - /** - * @var ilHelpGUI - */ - protected $help; - - var $ctrl; - - const CONTAINER_SETTING_TAXBLOCK = "tax_sblock_"; - - /** - * Constructor - * @access public - */ - function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) - { - global $DIC; - - $this->rbacsystem = $DIC->rbac()->system(); - $this->nav_history = $DIC["ilNavigationHistory"]; - $this->access = $DIC->access(); - $this->ctrl = $DIC->ctrl(); - $this->tabs = $DIC->tabs(); - $this->help = $DIC["ilHelp"]; - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - $this->tree = $DIC->repositoryTree(); - $this->error = $DIC["ilErr"]; - $this->settings = $DIC->settings(); - $this->tpl = $DIC["tpl"]; - $this->toolbar = $DIC->toolbar(); - $this->rbacreview = $DIC->rbac()->review(); - $this->rbacadmin = $DIC->rbac()->admin(); - //global $ilCtrl; - - // CONTROL OPTIONS - //$this->ctrl =& $ilCtrl; - //$this->ctrl->saveParameter($this,array("ref_id","cmdClass")); - $GLOBALS['lng']->loadLanguageModule('cat'); - $GLOBALS['lng']->loadLanguageModule('obj'); - - $this->type = "cat"; - parent::__construct($a_data,(int) $a_id,$a_call_by_reference,false); - - if (is_object($this->object)) - { - include_once("./Services/Container/classes/class.ilContainer.php"); - include_once("./Services/Object/classes/class.ilObjectServiceSettingsGUI.php"); - $this->info_screen_enabled = ilContainer::_lookupContainerSetting( - $this->object->getId(), - ilObjectServiceSettingsGUI::INFO_TAB_VISIBILITY, - true); - } - } - - function executeCommand() - { - $rbacsystem = $this->rbacsystem; - $ilNavigationHistory = $this->nav_history; - $ilAccess = $this->access; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - // show repository tree - $this->showRepTree(); - - switch($next_class) - { - case "ilobjusergui": - include_once('./Services/User/classes/class.ilObjUserGUI.php'); - - $this->tabs_gui->setTabActive('administrate_users'); - if(!$_GET['obj_id']) - { - $this->gui_obj = new ilObjUserGUI("",$_GET['ref_id'],true, false); - $this->gui_obj->setCreationMode($this->creation_mode); - $ret =& $this->ctrl->forwardCommand($this->gui_obj); - } - else - { - $this->gui_obj = new ilObjUserGUI("", $_GET['obj_id'],false, false); - $this->gui_obj->setCreationMode($this->creation_mode); - $ret =& $this->ctrl->forwardCommand($this->gui_obj); - } - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($this->lng->txt('backto_lua'), $this->ctrl->getLinkTarget($this,'listUsers')); - $ilHelp = $this->help; - $ilHelp->setScreenIdComponent("cat"); - $ilHelp->setScreenId("administrate_user"); - $ilHelp->setSubScreenId($ilCtrl->getCmd()); - break; - - case "ilobjuserfoldergui": - include_once('./Services/User/classes/class.ilObjUserFolderGUI.php'); - - $this->gui_obj = new ilObjUserFolderGUI("",(int) $_GET['ref_id'],true, false); - $this->gui_obj->setUserOwnerId((int) $_GET['ref_id']); - $this->gui_obj->setCreationMode($this->creation_mode); - $ret =& $this->ctrl->forwardCommand($this->gui_obj); - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($this->lng->txt('backto_lua'), $this->ctrl->getLinkTarget($this,'listUsers')); - $ilHelp = $this->help; - $ilHelp->setScreenIdComponent("cat"); - $ilHelp->setScreenId("administrate_user"); - $ilHelp->setSubScreenId($ilCtrl->getCmd()); - break; - - case "ilcolumngui": - $this->checkPermission("read"); - $this->prepareOutput(); - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->object->getStyleSheetId())); - $this->renderObject(); - break; - - case 'ilpermissiongui': - $this->prepareOutput(); - $this->tabs_gui->setTabActive('perm_settings'); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $ret =& $this->ctrl->forwardCommand($perm_gui); - break; - - case 'ilinfoscreengui': - if ($this->info_screen_enabled) - { - $this->prepareOutput(); - $this->infoScreen(); - } - break; - - case 'ilcontainerlinklistgui': - include_once("Services/Container/classes/class.ilContainerLinkListGUI.php"); - $link_list_gui = new ilContainerLinkListGUI(); - $ret =& $this->ctrl->forwardCommand($link_list_gui); - break; - - // container page editing - case "ilcontainerpagegui": - $this->prepareOutput(false); - $ret = $this->forwardToPageObject(); - if ($ret != "") - { - $this->tpl->setContent($ret); - } - break; - - case 'ilobjectcopygui': - $this->prepareOutput(); - - include_once './Services/Object/classes/class.ilObjectCopyGUI.php'; - $cp = new ilObjectCopyGUI($this); - $cp->setType('cat'); - $this->ctrl->forwardCommand($cp); - break; - - case "ilobjstylesheetgui": - $this->forwardToStyleSheet(); - break; - - case 'ilusertablegui': - include_once './Services/User/classes/class.ilUserTableGUI.php'; - $u_table = new ilUserTableGUI($this, "listUsers"); - $u_table->initFilter(); - $this->ctrl->setReturn($this,'listUsers'); - $this->ctrl->forwardCommand($u_table); - break; - - case "ilcommonactiondispatchergui": - $this->prepareOutput(); - include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); - $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); - $this->ctrl->forwardCommand($gui); - break; - - case 'ildidactictemplategui': - $this->ctrl->setReturn($this,'edit'); - include_once './Services/DidacticTemplate/classes/class.ilDidacticTemplateGUI.php'; - $did = new ilDidacticTemplateGUI($this); - $this->ctrl->forwardCommand($did); - break; - - case 'ilexportgui': - $this->prepareOutput(); - $this->tabs_gui->setTabActive('export'); - include_once './Services/Export/classes/class.ilExportGUI.php'; - $exp = new ilExportGUI($this); - $exp->addFormat('xml'); - $this->ctrl->forwardCommand($exp); - break; - - case 'ilobjecttranslationgui': - $this->checkPermissionBool("write"); - $this->prepareOutput(); - //$this->tabs_gui->setTabActive('export'); - $this->setEditTabs("settings_trans"); - include_once("./Services/Object/classes/class.ilObjectTranslationGUI.php"); - $transgui = new ilObjectTranslationGUI($this); - $this->ctrl->forwardCommand($transgui); - break; - - case 'ilobjtaxonomygui': - $this->checkPermissionBool("write"); - $this->prepareOutput(); - $this->initTaxSubTabs(); - include_once("./Services/Taxonomy/classes/class.ilObjTaxonomyGUI.php"); - $tax = new ilObjTaxonomyGUI(); - $tax->setAssignedObject($this->object->getId()); - $tax->setMultiple(true); - $tax->setListInfo($this->lng->txt("cntr_tax_list_info")); - $this->ctrl->forwardCommand($tax); - break; - - case 'ilobjectmetadatagui'; - $this->checkPermissionBool("write"); - $this->prepareOutput(); - $this->tabs_gui->activateTab('meta_data'); - $this->ctrl->forwardCommand($this->getObjectMetadataGUI()); - break; - - case "ilcontainernewssettingsgui": - $this->prepareOutput(); - $this->tabs_gui->setTabActive('settings'); - $this->setEditTabs(); - $this->tabs_gui->activateSubTab('obj_news_settings'); - $news_set_gui = new ilContainerNewsSettingsGUI($this); - $news_set_gui->setHideByDate(true); - $this->ctrl->forwardCommand($news_set_gui); - break; - - default: - if ($cmd == "infoScreen") - { - $this->checkPermission("visible"); - } - else - { - $this->checkPermission("read"); - } - - // add entry to navigation history - if (!$this->getCreationMode() && - $ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - include_once("./Services/Link/classes/class.ilLink.php"); - $ilNavigationHistory->addItem($_GET["ref_id"], - ilLink::_getLink($_GET["ref_id"], "cat"), "cat"); - } - - $this->prepareOutput(); - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - if (is_object($this->object)) - { - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->object->getStyleSheetId())); - } - - if(!$cmd) - { - $cmd = "render"; - } - $cmd .= "Object"; - $this->tabs_gui->activateTab("view_content"); // see #19868 - $this->$cmd(); - - break; - } - - $this->addHeaderAction(); - - return true; - } - - - /** - * @inheritDoc - */ - protected function addHeaderAction() { - ilPreviewGUI::initPreview(); - parent::addHeaderAction(); - } - - - /** - * Get object metadata gui - * - * @param - * @return - */ - function getObjectMetadataGUI() - { - include_once 'Services/Object/classes/class.ilObjectMetaDataGUI.php'; - $md_gui = new ilObjectMetaDataGUI($this->object); - include_once "Services/Object/classes/class.ilObjectServiceSettingsGUI.php"; - if(ilContainer::_lookupContainerSetting( - $this->object->getId(), - ilObjectServiceSettingsGUI::TAXONOMIES, - false - )) - { - $md_gui->enableTaxonomyDefinition(true); - $tax = $md_gui->getTaxonomyObjGUI(); - $tax->setMultiple(true); - $tax->setListInfo($this->lng->txt("cntr_tax_list_info")); - $taxonomies = $this->getTaxonomiesForRefId(); - if (sizeof($taxonomies)) - { - $md_gui->setTaxonomySettings(function ($form) - { - - $tax = $this->getTaxonomiesForRefId(); - $block = new ilCheckboxGroupInputGUI($this->lng->txt("cntr_taxonomy_show_sideblock"), "sblock"); - $form->addItem($block); - - $current = $this->getActiveBlocks(); - - foreach ($tax as $tax_id => $tax_item) - { - $option = new ilCheckboxOption($tax_item["title"], $tax_id, - ilObject::_lookupDescription($tax_id)); - - if ($tax_item["source"] != $this->object->getRefId()) - { - $loc = new ilLocatorGUI(); - $loc->setTextOnly(true); - $loc->addRepositoryItems($tax_item["source"]); - $option->setInfo($loc->getHTML()); - } - - $block->addOption($option); - - if (in_array($tax_id, $current)) - { - $value[] = $tax_id; - } - } - - $block->setValue($value); - - }, function ($form) - { - $taxonomies = $this->getTaxonomiesForRefId(); - if (sizeof($taxonomies)) - { - $sblock = $form->getInput("sblock"); - - $prefix = self::CONTAINER_SETTING_TAXBLOCK; - - ilContainer::_deleteContainerSettings($this->object->getId(), - $prefix . "%", true); - - if (is_array($sblock)) - { - foreach ($sblock as $tax_id) - { - ilContainer::_writeContainerSetting($this->object->getId(), - $prefix . $tax_id, 1); - } - } - } - }); - } - } - return $md_gui; - } - - - /** - * Get tabs - */ - function getTabs() - { - $rbacsystem = $this->rbacsystem; - $lng = $this->lng; - $ilHelp = $this->help; - $ilAccess = $this->access; - - if ($this->ctrl->getCmd() == "editPageContent") - { - return; - } - #$this->ctrl->setParameter($this,"ref_id",$this->ref_id); - - $ilHelp->setScreenIdComponent("cat"); - - if ($rbacsystem->checkAccess('read',$this->ref_id)) - { - $force_active = ($_GET["cmd"] == "" || $_GET["cmd"] == "render") - ? true - : false; - $this->tabs_gui->addTab("view_content", $lng->txt("content"), - $this->ctrl->getLinkTarget($this, "")); - - //BEGIN ChangeEvent add info tab to category object - if ($this->info_screen_enabled) - { - $force_active = ($this->ctrl->getNextClass() == "ilinfoscreengui" - || strtolower($_GET["cmdClass"]) == "ilnotegui") - ? true - : false; - $this->tabs_gui->addTarget("info_short", - $this->ctrl->getLinkTargetByClass( - array("ilobjcategorygui", "ilinfoscreengui"), "showSummary"), - array("showSummary","", "infoScreen"), - "", "", $force_active); - } - //END ChangeEvent add info tab to category object - } - - if ($rbacsystem->checkAccess('write',$this->ref_id)) - { - $force_active = ($_GET["cmd"] == "edit") - ? true - : false; - $this->tabs_gui->addTarget("settings", - $this->ctrl->getLinkTarget($this, "edit"), "edit", get_class($this) - , "", $force_active); - - - - // metadata / taxonomies - include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php"; - $mdgui = new ilObjectMetaDataGUI($this->object); - if (ilContainer::_lookupContainerSetting( - $this->object->getId(), - ilObjectServiceSettingsGUI::TAXONOMIES, - false - )) - { - $mdgui->enableTaxonomyDefinition(true); - } - $mdtab = $mdgui->getTab(); - if($mdtab) - { - $this->tabs_gui->addTab("meta_data", - $this->lng->txt("meta_data"), - $mdtab); - } - - } - - include_once './Services/User/classes/class.ilUserAccountSettings.php'; - if( - ilUserAccountSettings::getInstance()->isLocalUserAdministrationEnabled() and - $rbacsystem->checkAccess('cat_administrate_users',$this->ref_id)) - { - $this->tabs_gui->addTarget("administrate_users", - $this->ctrl->getLinkTarget($this, "listUsers"), "listUsers", get_class($this)); - } - - if($ilAccess->checkAccess('write','',$this->object->getRefId())) - { - $this->tabs_gui->addTarget( - 'export', - $this->ctrl->getLinkTargetByClass('ilexportgui',''), - 'export', - 'ilexportgui' - ); - } - - // parent tabs (all container: edit_permission, clipboard, trash - parent::getTabs(); - - } - - /** - * Render category - */ - function renderObject() - { - $ilTabs = $this->tabs; - - $ilTabs->activateTab("view_content"); - $ret = parent::renderObject(); - return $ret; - - } - - function viewObject() - { - if (strtolower($_GET["baseClass"]) == "iladministrationgui") - { - parent::viewObject(); - return true; - } - return $this->renderObject(); - } - - protected function initCreationForms($a_new_type) - { - $forms = parent::initCreationForms($a_new_type); - //unset($forms[self::CFORM_IMPORT]); - return $forms; - } - - protected function afterSave(ilObject $a_new_object) - { - $tree = $this->tree; - - // default: sort by title - include_once('Services/Container/classes/class.ilContainerSortingSettings.php'); - $settings = new ilContainerSortingSettings($a_new_object->getId()); - $settings->setSortMode(ilContainer::SORT_TITLE); - $settings->save(); - - // inherit parents content style, if not individual - $parent_ref_id = $tree->getParentId($a_new_object->getRefId()); - $parent_id = ilObject::_lookupObjId($parent_ref_id); - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $style_id = ilObjStyleSheet::lookupObjectStyle($parent_id); - if ($style_id > 0) - { - if (ilObjStyleSheet::_lookupStandard($style_id)) - { - ilObjStyleSheet::writeStyleUsage($a_new_object->getId(), $style_id); - } - } - - // always send a message - ilUtil::sendSuccess($this->lng->txt("cat_added"),true); - $this->ctrl->setParameter($this, "ref_id", $a_new_object->getRefId()); - $this->redirectToRefId($a_new_object->getRefId(), ""); - } - - /** - * 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 infoScreenObject() - { - $this->ctrl->setCmd("showSummary"); - $this->ctrl->setCmdClass("ilinfoscreengui"); - $this->infoScreen(); - } - - /** - * show information screen - */ - function infoScreen() - { - $ilAccess = $this->access; - $ilCtrl = $this->ctrl; - $ilErr = $this->error; - - if (!$ilAccess->checkAccess("visible", "", $this->ref_id)) - { - $ilErr->raiseError($this->lng->txt("msg_no_perm_read"), $ilErr->MESSAGE); - } - - if (!$this->info_screen_enabled) - { - return; - } - - // #10986 - $this->tabs_gui->setTabActive('info_short'); - - include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); - $info = new ilInfoScreenGUI($this); - - $info->enablePrivateNotes(); - - if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - $info->enableNews(); - } - - // no news editing for files, just notifications - $info->enableNewsEditing(false); - if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) - { - $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); - } - } - - include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecordGUI.php'); - $record_gui = new ilAdvancedMDRecordGUI(ilAdvancedMDRecordGUI::MODE_INFO,'cat',$this->object->getId()); - $record_gui->setInfoObject($info); - $record_gui->parse(); - - - // standard meta data - $info->addMetaDataSections($this->object->getId(),0, $this->object->getType()); - - // forward the command - if ($ilCtrl->getNextClass() == "ilinfoscreengui") - { - $ilCtrl->forwardCommand($info); - } - else - { - return $ilCtrl->getHTML($info); - } - } - - /** - * Edit extended category settings - * - * @access protected - */ - protected function editInfoObject() - { - $this->checkPermission("write"); - $this->setEditTabs(); - $this->tabs_gui->activateTab('settings'); - $this->tabs_gui->setSubTabActive('edit_cat_settings'); - - $this->initExtendedSettings(); - $this->tpl->setContent($this->form->getHTML()); - } - - /** - * Update info (extended meta data) - * - * @access protected - */ - protected function updateInfoObject() - { - $this->checkPermission("write"); - - // init form - $this->initExtendedSettings(); - - // still needed for date conversion and so on - $this->form->checkInput(); - - if($this->record_gui->importEditFormPostValues()) - { - $this->record_gui->writeEditForm(); - - ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); - $this->ctrl->redirect($this, "editInfo"); - } - - $this->editInfoObject(); - } - - - /** - * build property form for extended category settings - * - * @access protected - */ - protected function initExtendedSettings() - { - if(is_object($this->form)) - { - return true; - } - - include_once('Services/Form/classes/class.ilPropertyFormGUI.php'); - $this->form = new ilPropertyFormGUI(); - $this->form->setFormAction($this->ctrl->getFormAction($this)); - $this->form->setTitle($this->lng->txt('ext_cat_settings')); - $this->form->addCommandButton('updateInfo',$this->lng->txt('save')); - $this->form->addCommandButton('editInfo',$this->lng->txt('cancel')); - - include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecordGUI.php'); - $this->record_gui = new ilAdvancedMDRecordGUI(ilAdvancedMDRecordGUI::MODE_EDITOR,'cat',$this->object->getId()); - $this->record_gui->setPropertyForm($this->form); - $this->record_gui->parse(); - - return true; - } - - protected function setEditTabs($active_tab = "settings_misc") - { - $ilSetting = $this->settings; - $ilTabs = $this->tabs; - - $this->tabs_gui->addSubTab("settings_misc", - $this->lng->txt("settings"), - $this->ctrl->getLinkTarget($this, "edit")); - - $this->tabs_gui->addSubTab("settings_trans", - $this->lng->txt("obj_multilinguality"), - $this->ctrl->getLinkTargetByClass("ilobjecttranslationgui", "")); - - //news tab - $news_active = ilContainer::_lookupContainerSetting( - $this->object->getId(), - ilObjectServiceSettingsGUI::NEWS_VISIBILITY, - true); - - if($news_active) - { - $this->tabs_gui->addSubTab('obj_news_settings', - $this->lng->txt("cont_news_settings"), - $this->ctrl->getLinkTargetByClass('ilcontainernewssettingsgui')); - } - - $this->tabs_gui->activateTab("settings"); - $this->tabs_gui->activateSubTab($active_tab); - } - - function initEditForm() - { - $obj_service = $this->getObjectService(); - - $this->lng->loadLanguageModule($this->object->getType()); - $this->setEditTabs(); - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - $form->setTitle($this->lng->txt($this->object->getType()."_edit")); - - // title/description - $this->initFormTitleDescription($form); - - // Show didactic template type - $this->initDidacticTemplate($form); - - // presentation - $pres = new ilFormSectionHeaderGUI(); - $pres->setTitle($this->lng->txt('obj_presentation')); - $form->addItem($pres); - - // title and icon visibility - $form = $obj_service->commonSettings()->legacyForm($form, $this->object)->addTitleIconVisibility(); - - // top actions visibility - $form = $obj_service->commonSettings()->legacyForm($form, $this->object)->addTopActionsVisibility(); - - // custom icon - $form = $obj_service->commonSettings()->legacyForm($form, $this->object)->addIcon(); - - // tile image - $form = $obj_service->commonSettings()->legacyForm($form, $this->object)->addTileImage(); - - // list presentation - $form = $this->initListPresentationForm($form); - - // sorting - $form = $this->initSortingForm( - $form, - array( - ilContainer::SORT_TITLE, - ilContainer::SORT_CREATION, - ilContainer::SORT_MANUAL - ) - ); - - // block limit - $bl = new ilNumberInputGUI($this->lng->txt("cont_block_limit"), "block_limit"); - $bl->setInfo($this->lng->txt("cont_block_limit_info")); - $bl->setValue(ilContainer::_lookupContainerSetting($this->object->getId(), "block_limit")); - $form->addItem($bl); - - // icon settings - - // Edit ecs export settings - include_once 'Modules/Category/classes/class.ilECSCategorySettings.php'; - $ecs = new ilECSCategorySettings($this->object); - $ecs->addSettingsToForm($form, 'cat'); - - // services - $sh = new ilFormSectionHeaderGUI(); - $sh->setTitle($this->lng->txt('obj_features')); - $form->addItem($sh); - - include_once './Services/Object/classes/class.ilObjectServiceSettingsGUI.php'; - ilObjectServiceSettingsGUI::initServiceSettingsForm( - $this->object->getId(), - $form, - array( - ilObjectServiceSettingsGUI::INFO_TAB_VISIBILITY, - ilObjectServiceSettingsGUI::NEWS_VISIBILITY, - ilObjectServiceSettingsGUI::TAXONOMIES, - ilObjectServiceSettingsGUI::CUSTOM_METADATA - ) - ); - - $form->addCommandButton("update", $this->lng->txt("save")); - - return $form; - } - - function getEditFormValues() - { - // values are set in initEditForm() - } - - /** - * updates object entry in object_data - * - * @access public - */ - function updateObject() - { - $ilErr = $this->error; - $ilUser = $this->user; - $obj_service = $this->getObjectService(); - - if (!$this->checkPermissionBool("write")) - { - $ilErr->raiseError($this->lng->txt("msg_no_perm_write"), $ilErr->MESSAGE); - } - else - { - $form = $this->initEditForm(); - if($form->checkInput()) - { - $title = $form->getInput("title"); - $desc = $form->getInput("desc"); - - $this->object->setTitle($title); - $this->object->setDescription($desc); - $this->object->update(); - - $this->saveSortingSettings($form); - - // title icon visibility - $obj_service->commonSettings()->legacyForm($form, $this->object)->saveTitleIconVisibility(); - - // top actions visibility - $obj_service->commonSettings()->legacyForm($form, $this->object)->saveTopActionsVisibility(); - - // custom icon - $obj_service->commonSettings()->legacyForm($form, $this->object)->saveIcon(); - - // tile image - $obj_service->commonSettings()->legacyForm($form, $this->object)->saveTileImage(); - - // list presentation - $this->saveListPresentation($form); - - // BEGIN ChangeEvent: Record update - require_once('Services/Tracking/classes/class.ilChangeEvent.php'); - ilChangeEvent::_recordWriteEvent($this->object->getId(), $ilUser->getId(), 'update'); - ilChangeEvent::_catchupWriteEvents($this->object->getId(), $ilUser->getId()); - // END ChangeEvent: Record update - - // services - include_once './Services/Object/classes/class.ilObjectServiceSettingsGUI.php'; - ilObjectServiceSettingsGUI::updateServiceSettingsForm( - $this->object->getId(), - $form, - array( - ilObjectServiceSettingsGUI::INFO_TAB_VISIBILITY, - ilObjectServiceSettingsGUI::NEWS_VISIBILITY, - ilObjectServiceSettingsGUI::TAXONOMIES, - ilObjectServiceSettingsGUI::CUSTOM_METADATA - ) - ); - - // block limit - if ((int) $form->getInput("block_limit") > 0) - { - ilContainer::_writeContainerSetting($this->object->getId(), "block_limit", (int) $form->getInput("block_limit")); - } - else - { - ilContainer::_deleteContainerSettings($this->object->getId(), "block_limit"); - } - // Update ecs export settings - include_once 'Modules/Category/classes/class.ilECSCategorySettings.php'; - $ecs = new ilECSCategorySettings($this->object); - if($ecs->handleSettingsUpdate()) - { - return $this->afterUpdate(); - } - } - - // display form to correct errors - $this->setEditTabs(); - $form->setValuesByPost(); - $this->tpl->setContent($form->getHTML()); - } - } - - /** - * display form for category import - */ - function importCategoriesFormObject () - { - ilObjCategoryGUI::_importCategoriesForm($this->ref_id, $this->tpl); - } - - /** - * display form for category import (static, also called by RootFolderGUI) - */ - public static function _importCategoriesForm ($a_ref_id, &$a_tpl) - { - global $DIC; - - $lng = $DIC->language(); - $rbacreview = $DIC->rbac()->review(); - $ilCtrl = $DIC->ctrl(); - - $a_tpl->addBlockfile("ADM_CONTENT", "adm_content", "tpl.cat_import_form.html", - "Modules/Category"); - - $a_tpl->setVariable("FORMACTION", $ilCtrl->getFormActionByClass('ilObjCategoryGUI')); - - $a_tpl->setVariable("TXT_IMPORT_CATEGORIES", $lng->txt("import_categories")); - $a_tpl->setVariable("TXT_HIERARCHY_OPTION", $lng->txt("import_cat_localrol")); - $a_tpl->setVariable("TXT_IMPORT_FILE", $lng->txt("import_file")); - $a_tpl->setVariable("TXT_IMPORT_TABLE", $lng->txt("import_cat_table")); - - $a_tpl->setVariable("BTN_IMPORT", $lng->txt("import")); - $a_tpl->setVariable("BTN_CANCEL", $lng->txt("cancel")); - - // NEED TO FILL ADOPT_PERMISSIONS HTML FORM.... - $parent_role_ids = $rbacreview->getParentRoleIds($a_ref_id,true); - - // sort output for correct color changing - ksort($parent_role_ids); - - foreach ($parent_role_ids as $key => $par) - { - if ($par["obj_id"] != SYSTEM_ROLE_ID) - { - $check = ilUtil::formCheckbox(0,"adopt[]",$par["obj_id"],1); - $output["adopt"][$key]["css_row_adopt"] = ilUtil::switchColor($key, "tblrow1", "tblrow2"); - $output["adopt"][$key]["check_adopt"] = $check; - $output["adopt"][$key]["role_id"] = $par["obj_id"]; - $output["adopt"][$key]["type"] = ($par["type"] == 'role' ? 'Role' : 'Template'); - $output["adopt"][$key]["role_name"] = $par["title"]; - } - } - - //var_dump($output); - - // BEGIN ADOPT PERMISSIONS - foreach ($output["adopt"] as $key => $value) - { - $a_tpl->setCurrentBlock("ADOPT_PERM_ROW"); - $a_tpl->setVariable("CSS_ROW_ADOPT",$value["css_row_adopt"]); - $a_tpl->setVariable("CHECK_ADOPT",$value["check_adopt"]); - $a_tpl->setVariable("LABEL_ID",$value["role_id"]); - $a_tpl->setVariable("TYPE",$value["type"]); - $a_tpl->setVariable("ROLE_NAME",$value["role_name"]); - $a_tpl->parseCurrentBlock(); - } - } - - - /** - * import cancelled - * - * @access private - */ - function importCancelledObject() - { - $this->ctrl->redirect($this); - } - - /** - * get user import directory name - */ - static function _getImportDir() - { - return ilUtil::getDataDir()."/cat_import"; - } - - /** - * import categories - */ - function importCategoriesObject() - { - ilObjCategoryGUI::_importCategories($_GET["ref_id"]); - // call to importCategories with $withrol = 0 - ilObjCategoryGUI::_importCategories($_GET["ref_id"], 0); - } - - /** - * import categories with local rol - */ - function importCategoriesWithRolObject() - { - - //echo "entra aqui"; - // call to importCategories with $withrol = 1 - ilObjCategoryGUI::_importCategories($_GET["ref_id"], 1); - } - - /** - * import categories (static, also called by RootFolderGUI) - */ - - public static function _importCategories($a_ref_id, $withrol_tmp) - { - global $DIC; - - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - - require_once("./Modules/Category/classes/class.ilCategoryImportParser.php"); - - $import_dir = ilObjCategoryGUI::_getImportDir(); - - // create user import directory if necessary - if (!@is_dir($import_dir)) - { - ilUtil::createDirectory($import_dir); - } - - // move uploaded file to user import directory - - $file_name = $_FILES["importFile"]["name"]; - - // added to prevent empty file names - if (!strcmp($file_name,"")) { - ilUtil::sendFailure($lng->txt("no_import_file_found"), true); - $ilCtrl->redirectByClass('ilObjCategoryGUI'); - } - - $parts = pathinfo($file_name); - $full_path = $import_dir."/".$file_name; - ilUtil::moveUploadedFile($_FILES["importFile"]["tmp_name"], $file_name, $full_path); - - // unzip file - ilUtil::unzip($full_path); - - $subdir = basename($parts["basename"],".".$parts["extension"]); - $xml_file = $import_dir."/".$subdir."/".$subdir.".xml"; - // CategoryImportParser - //var_dump($_POST); - $importParser = new ilCategoryImportParser($xml_file, $a_ref_id, $withrol_tmp); - $importParser->startParsing(); - - ilUtil::sendSuccess($lng->txt("categories_imported"), true); - $ilCtrl->redirectByClass('ilObjCategoryGUI'); - } - - /** - * Reset filter - * (note: this function existed before data table filter has been introduced - */ - protected function resetFilterObject() - { - include_once("./Services/User/classes/class.ilUserTableGUI.php"); - $utab = new ilUserTableGUI($this, "listUsers",ilUserTableGUI::MODE_LOCAL_USER); - $utab->resetOffset(); - $utab->resetFilter(); - - // from "old" implementation - $this->listUsersObject(); - } - - /** - * Apply filter - * @return - */ - protected function applyFilterObject() - { - $ilTabs = $this->tabs; - - include_once("./Services/User/classes/class.ilUserTableGUI.php"); - $utab = new ilUserTableGUI($this, "listUsers", ilUserTableGUI::MODE_LOCAL_USER); - $utab->resetOffset(); - $utab->writeFilterToSession(); - $this->listUsersObject(); - } - - // METHODS for local user administration - function listUsersObject($show_delete = false) - { - $ilUser = $this->user; - $ilErr = $this->error; - $ilToolbar = $this->toolbar; - - include_once './Services/User/classes/class.ilLocalUser.php'; - include_once './Services/User/classes/class.ilObjUserGUI.php'; - - $rbacsystem = $this->rbacsystem; - $rbacreview = $this->rbacreview; - - if(!$rbacsystem->checkAccess("cat_administrate_users",$this->object->getRefId())) - { - $ilErr->raiseError($this->lng->txt("msg_no_perm_admin_users"), $ilErr->MESSAGE); - } - $this->tabs_gui->setTabActive('administrate_users'); - - - - $this->tpl->addBlockfile('ADM_CONTENT','adm_content','tpl.cat_admin_users.html', - "Modules/Category"); - - if(count($rbacreview->getGlobalAssignableRoles()) or in_array(SYSTEM_ROLE_ID,$rbacreview->assignedRoles($ilUser->getId()))) - { - $ilToolbar->addButton( - $this->lng->txt('add_user'), - $this->ctrl->getLinkTargetByClass('ilobjusergui','create') - ); - - $ilToolbar->addButton( - $this->lng->txt('import_users'), - $this->ctrl->getLinkTargetByClass('ilobjuserfoldergui','importUserForm') - ); - } - else - { - ilUtil::sendInfo($this->lng->txt('no_roles_user_can_be_assigned_to')); - } - - if($show_delete) - { - $this->tpl->setCurrentBlock("confirm_delete"); - $this->tpl->setVariable("CONFIRM_FORMACTION",$this->ctrl->getFormAction($this)); - $this->tpl->setVariable("TXT_CANCEL",$this->lng->txt('cancel')); - $this->tpl->setVariable("CONFIRM_CMD",'performDeleteUsers'); - $this->tpl->setVariable("TXT_CONFIRM",$this->lng->txt('delete')); - $this->tpl->parseCurrentBlock(); - } - - $this->lng->loadLanguageModule('user'); - - include_once("./Services/User/classes/class.ilUserTableGUI.php"); - $utab = new ilUserTableGUI($this, 'listUsers',ilUserTableGUI::MODE_LOCAL_USER); - $this->tpl->setVariable('USERS_TABLE',$utab->getHTML()); - - return true; - } - - /** - * Show auto complete results - */ - protected function addUserAutoCompleteObject() - { - include_once './Services/User/classes/class.ilUserAutoComplete.php'; - $auto = new ilUserAutoComplete(); - $auto->setSearchFields(array('login','firstname','lastname','email')); - $auto->enableFieldSearchableCheck(true); - $auto->isMoreLinkAvailable(true); - - if(($_REQUEST['fetchall'])) - { - $auto->setLimit(ilUserAutoComplete::MAX_ENTRIES); - } - - echo $auto->getList($_REQUEST['term']); - exit(); - } - - - function performDeleteUsersObject() - { - include_once './Services/User/classes/class.ilLocalUser.php'; - $this->checkPermission("cat_administrate_users"); - - foreach($_POST['user_ids'] as $user_id) - { - if(!in_array($user_id,ilLocalUser::_getAllUserIds($this->object->getRefId()))) - { - die('user id not valid'); - } - if(!$tmp_obj =& ilObjectFactory::getInstanceByObjId($user_id,false)) - { - continue; - } - $tmp_obj->delete(); - } - ilUtil::sendSuccess($this->lng->txt('deleted_users')); - $this->listUsersObject(); - - return true; - } - - function deleteUsersObject() - { - $this->checkPermission("cat_administrate_users"); - if(!count($_POST['id'])) - { - ilUtil::sendFailure($this->lng->txt('no_users_selected')); - $this->listUsersObject(); - - return true; - } - - include_once './Services/Utilities/classes/class.ilConfirmationGUI.php'; - $confirm = new ilConfirmationGUI(); - $confirm->setFormAction($this->ctrl->getFormAction($this)); - $confirm->setHeaderText($this->lng->txt('sure_delete_selected_users')); - $confirm->setConfirm($this->lng->txt('delete'), 'performDeleteUsers'); - $confirm->setCancel($this->lng->txt('cancel'), 'listUsers'); - - foreach($_POST['id'] as $user) - { - $name = ilObjUser::_lookupName($user); - - $confirm->addItem( - 'user_ids[]', - $user, - $name['lastname'].', '.$name['firstname'].' ['.$name['login'].']' - ); - } - $this->tpl->setContent($confirm->getHTML()); - } - - function assignRolesObject() - { - $rbacreview = $this->rbacreview; - $ilTabs = $this->tabs; - - $this->checkPermission("cat_administrate_users"); - - include_once './Services/User/classes/class.ilLocalUser.php'; - - if(!isset($_GET['obj_id'])) - { - ilUtil::sendFailure('no_user_selected'); - $this->listUsersObject(); - - return true; - } - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($this->lng->txt('backto_lua'), $this->ctrl->getLinkTarget($this,'listUsers')); - $ilHelp = $this->help; - $ilHelp->setScreenIdComponent("cat"); - $ilHelp->setScreenId("administrate_user"); - $ilHelp->setSubScreenId("assign_roles"); - - - $roles = $this->__getAssignableRoles(); - - if(!count($roles)) - { - #ilUtil::sendInfo($this->lng->txt('no_roles_user_can_be_assigned_to')); - #$this->listUsersObject(); - - #return true; - } - - $ass_roles = $rbacreview->assignedRoles($_GET['obj_id']); - - $counter = 0; - $f_result = array(); - - foreach($roles as $role) - { - $role_obj =& ilObjectFactory::getInstanceByObjId($role['obj_id']); - - $disabled = false; - $f_result[$counter]['checkbox'] = ilUtil::formCheckbox(in_array($role['obj_id'],$ass_roles) ? 1 : 0, - 'role_ids[]', - $role['obj_id'], - $disabled); - $f_result[$counter]['title'] = $role_obj->getTitle() ? $role_obj->getTitle() : ""; - $f_result[$counter]['desc'] = $role_obj->getDescription() ? $role_obj->getDescription() : ""; - $f_result[$counter]['type'] = $role['role_type'] == 'global' ? - $this->lng->txt('global') : - $this->lng->txt('local'); - - unset($role_obj); - ++$counter; - } - - include_once ('./Modules/Category/classes/class.ilCategoryAssignRoleTableGUI.php'); - $table = new ilCategoryAssignRoleTableGUI($this, "assignRoles"); - $tmp_obj =& ilObjectFactory::getInstanceByObjId($_GET['obj_id']); - $title = $this->lng->txt('role_assignment').' ('.$tmp_obj->getFullname().')'; - $table->setTitle($title,"icon_role.svg",$this->lng->txt("role_assignment")); - $table->setData($f_result); - $this->tpl->setContent($table->getHTML()); - } - - function assignSaveObject() - { - $rbacreview = $this->rbacreview; - $rbacadmin = $this->rbacadmin; - $this->checkPermission("cat_administrate_users"); - - include_once './Services/User/classes/class.ilLocalUser.php'; - // check hack - if(!isset($_GET['obj_id']) or !in_array($_REQUEST['obj_id'],ilLocalUser::_getAllUserIds())) - { - ilUtil::sendFailure('no_user_selected'); - $this->listUsersObject(); - - return true; - } - $roles = $this->__getAssignableRoles(); - - // check minimum one global role - if(!$this->__checkGlobalRoles($_POST['role_ids'])) - { - ilUtil::sendFailure($this->lng->txt('no_global_role_left')); - $this->assignRolesObject(); - - return false; - } - - $new_role_ids = $_POST['role_ids'] ? $_POST['role_ids'] : array(); - $assigned_roles = $rbacreview->assignedRoles((int) $_REQUEST['obj_id']); - foreach($roles as $role) - { - if(in_array($role['obj_id'],$new_role_ids) and !in_array($role['obj_id'],$assigned_roles)) - { - $rbacadmin->assignUser($role['obj_id'],(int) $_REQUEST['obj_id']); - } - if(in_array($role['obj_id'],$assigned_roles) and !in_array($role['obj_id'],$new_role_ids)) - { - $rbacadmin->deassignUser($role['obj_id'],(int) $_REQUEST['obj_id']); - } - } - ilUtil::sendSuccess($this->lng->txt('role_assignment_updated')); - $this->assignRolesObject(); - - return true; - } - - // PRIVATE - function __getAssignableRoles() - { - $rbacreview = $this->rbacreview; - $ilUser = $this->user; - - // check local user - $tmp_obj =& ilObjectFactory::getInstanceByObjId($_REQUEST['obj_id']); - // Admin => all roles - if(in_array(SYSTEM_ROLE_ID,$rbacreview->assignedRoles($ilUser->getId()))) - { - $global_roles = $rbacreview->getGlobalRolesArray(); - } - elseif($tmp_obj->getTimeLimitOwner() == $this->object->getRefId()) - { - $global_roles = $rbacreview->getGlobalAssignableRoles(); - } - else - { - $global_roles = array(); - } - return $roles = array_merge($global_roles, - $rbacreview->getAssignableChildRoles($this->object->getRefId())); - } - - function __checkGlobalRoles($new_assigned) - { - $rbacreview = $this->rbacreview; - $ilUser = $this->user; - - $this->checkPermission("cat_administrate_users"); - - // return true if it's not a local user - $tmp_obj =& ilObjectFactory::getInstanceByObjId($_REQUEST['obj_id']); - if($tmp_obj->getTimeLimitOwner() != $this->object->getRefId() and - !in_array(SYSTEM_ROLE_ID,$rbacreview->assignedRoles($ilUser->getId()))) - { - return true; - } - - // new assignment by form - $new_assigned = $new_assigned ? $new_assigned : array(); - $assigned = $rbacreview->assignedRoles((int) $_GET['obj_id']); - - // all assignable globals - if(!in_array(SYSTEM_ROLE_ID,$rbacreview->assignedRoles($ilUser->getId()))) - { - $ga = $rbacreview->getGlobalAssignableRoles(); - } - else - { - $ga = $rbacreview->getGlobalRolesArray(); - } - $global_assignable = array(); - foreach($ga as $role) - { - $global_assignable[] = $role['obj_id']; - } - - $new_visible_assigned_roles = array_intersect($new_assigned,$global_assignable); - $all_assigned_roles = array_intersect($assigned,$rbacreview->getGlobalRoles()); - $main_assigned_roles = array_diff($all_assigned_roles,$global_assignable); - - if(!count($new_visible_assigned_roles) and !count($main_assigned_roles)) - { - return false; - } - return true; - } - - public static function _goto($a_target) - { - global $DIC; - - $ilAccess = $DIC->access(); - $ilErr = $DIC["ilErr"]; - $lng = $DIC->language(); - - if ($ilAccess->checkAccess("read", "", $a_target)) - { - ilObjectGUI::_gotoRepositoryNode($a_target); - } - else if ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) - { - ilUtil::sendFailure(sprintf($lng->txt("msg_no_perm_read_item"), - ilObject::_lookupTitle(ilObject::_lookupObjId($a_target))), true); - ilObjectGUI::_gotoRepositoryRoot(); - } - - $ilErr->raiseError($lng->txt("msg_no_perm_read"), $ilErr->FATAL); - - } - - // - // taxonomy - // - - protected function initTaxSubTabs($a_active = "tax_list") - { - $this->tabs_gui->setTabActive("obj_tool_setting_taxonomies"); - $this->tabs_gui->addSubTab("tax_settings", $this->lng->txt("cntr_taxonomy_sideblock_settings"), - $this->ctrl->getLinkTarget($this, "editTaxonomySettings")); - $this->tabs_gui->addSubTab("tax_list", $this->lng->txt("cntr_taxonomy_definitions"), - $this->ctrl->getLinkTargetByClass("ilobjtaxonomygui", "")); - $this->tabs_gui->activateSubTab($a_active); - } - - protected function getTaxonomiesForRefId() - { - $tree = $this->tree; - - include_once "Services/Object/classes/class.ilObjectServiceSettingsGUI.php"; - include_once "Services/Taxonomy/classes/class.ilObjTaxonomy.php"; - - // see ilTaxMDGUI::getSelectableTaxonomies() - - $res = array(); - foreach($tree->getPathFull($this->object->getRefId()) as $node) - { - //if ($node["ref_id"] != $this->object->getRefId()) - { - // find all defined taxes for parent node, activation is not relevant - $node_taxes = ilObjTaxonomy::getUsageOfObject($node["obj_id"], true); - if (sizeof($node_taxes)) - { - foreach ($node_taxes as $node_tax) - { - $res[$node_tax["tax_id"]] = array( - "title" => $node_tax["title"] - , "source" => $node["child"] - ); - } - } - } - } - - asort($res); - return $res; - } - - - protected function getActiveBlocks() - { - $res = array(); - - $prefix = self::CONTAINER_SETTING_TAXBLOCK; - - foreach(ilContainer::_getContainerSettings($this->object->getId()) as $keyword => $value) - { - if(substr($keyword, 0, strlen($prefix)) == $prefix && (bool)$value) - { - $res[] = substr($keyword, strlen($prefix)); - } - } - - return $res; - } - + /** + * @var ilNavigationHistory + */ + protected $nav_history; + + /** + * @var ilHelpGUI + */ + protected $help; + + public $ctrl; + + const CONTAINER_SETTING_TAXBLOCK = "tax_sblock_"; + + /** + * Constructor + * @access public + */ + public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) + { + global $DIC; + + $this->rbacsystem = $DIC->rbac()->system(); + $this->nav_history = $DIC["ilNavigationHistory"]; + $this->access = $DIC->access(); + $this->ctrl = $DIC->ctrl(); + $this->tabs = $DIC->tabs(); + $this->help = $DIC["ilHelp"]; + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + $this->tree = $DIC->repositoryTree(); + $this->error = $DIC["ilErr"]; + $this->settings = $DIC->settings(); + $this->tpl = $DIC["tpl"]; + $this->toolbar = $DIC->toolbar(); + $this->rbacreview = $DIC->rbac()->review(); + $this->rbacadmin = $DIC->rbac()->admin(); + //global $ilCtrl; + + // CONTROL OPTIONS + //$this->ctrl =& $ilCtrl; + //$this->ctrl->saveParameter($this,array("ref_id","cmdClass")); + $GLOBALS['lng']->loadLanguageModule('cat'); + $GLOBALS['lng']->loadLanguageModule('obj'); + + $this->type = "cat"; + parent::__construct($a_data, (int) $a_id, $a_call_by_reference, false); + + if (is_object($this->object)) { + include_once("./Services/Container/classes/class.ilContainer.php"); + include_once("./Services/Object/classes/class.ilObjectServiceSettingsGUI.php"); + $this->info_screen_enabled = ilContainer::_lookupContainerSetting( + $this->object->getId(), + ilObjectServiceSettingsGUI::INFO_TAB_VISIBILITY, + true + ); + } + } + + public function executeCommand() + { + $rbacsystem = $this->rbacsystem; + $ilNavigationHistory = $this->nav_history; + $ilAccess = $this->access; + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + // show repository tree + $this->showRepTree(); + + switch ($next_class) { + case "ilobjusergui": + include_once('./Services/User/classes/class.ilObjUserGUI.php'); + + $this->tabs_gui->setTabActive('administrate_users'); + if (!$_GET['obj_id']) { + $this->gui_obj = new ilObjUserGUI("", $_GET['ref_id'], true, false); + $this->gui_obj->setCreationMode($this->creation_mode); + $ret =&$this->ctrl->forwardCommand($this->gui_obj); + } else { + $this->gui_obj = new ilObjUserGUI("", $_GET['obj_id'], false, false); + $this->gui_obj->setCreationMode($this->creation_mode); + $ret =&$this->ctrl->forwardCommand($this->gui_obj); + } + + $ilTabs->clearTargets(); + $ilTabs->setBackTarget($this->lng->txt('backto_lua'), $this->ctrl->getLinkTarget($this, 'listUsers')); + $ilHelp = $this->help; + $ilHelp->setScreenIdComponent("cat"); + $ilHelp->setScreenId("administrate_user"); + $ilHelp->setSubScreenId($ilCtrl->getCmd()); + break; + + case "ilobjuserfoldergui": + include_once('./Services/User/classes/class.ilObjUserFolderGUI.php'); + + $this->gui_obj = new ilObjUserFolderGUI("", (int) $_GET['ref_id'], true, false); + $this->gui_obj->setUserOwnerId((int) $_GET['ref_id']); + $this->gui_obj->setCreationMode($this->creation_mode); + $ret =&$this->ctrl->forwardCommand($this->gui_obj); + + $ilTabs->clearTargets(); + $ilTabs->setBackTarget($this->lng->txt('backto_lua'), $this->ctrl->getLinkTarget($this, 'listUsers')); + $ilHelp = $this->help; + $ilHelp->setScreenIdComponent("cat"); + $ilHelp->setScreenId("administrate_user"); + $ilHelp->setSubScreenId($ilCtrl->getCmd()); + break; + + case "ilcolumngui": + $this->checkPermission("read"); + $this->prepareOutput(); + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $this->tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath($this->object->getStyleSheetId()) + ); + $this->renderObject(); + break; + + case 'ilpermissiongui': + $this->prepareOutput(); + $this->tabs_gui->setTabActive('perm_settings'); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $ret =&$this->ctrl->forwardCommand($perm_gui); + break; + + case 'ilinfoscreengui': + if ($this->info_screen_enabled) { + $this->prepareOutput(); + $this->infoScreen(); + } + break; + + case 'ilcontainerlinklistgui': + include_once("Services/Container/classes/class.ilContainerLinkListGUI.php"); + $link_list_gui = new ilContainerLinkListGUI(); + $ret =&$this->ctrl->forwardCommand($link_list_gui); + break; + + // container page editing + case "ilcontainerpagegui": + $this->prepareOutput(false); + $ret = $this->forwardToPageObject(); + if ($ret != "") { + $this->tpl->setContent($ret); + } + break; + + case 'ilobjectcopygui': + $this->prepareOutput(); + + include_once './Services/Object/classes/class.ilObjectCopyGUI.php'; + $cp = new ilObjectCopyGUI($this); + $cp->setType('cat'); + $this->ctrl->forwardCommand($cp); + break; + + case "ilobjstylesheetgui": + $this->forwardToStyleSheet(); + break; + + case 'ilusertablegui': + include_once './Services/User/classes/class.ilUserTableGUI.php'; + $u_table = new ilUserTableGUI($this, "listUsers"); + $u_table->initFilter(); + $this->ctrl->setReturn($this, 'listUsers'); + $this->ctrl->forwardCommand($u_table); + break; + + case "ilcommonactiondispatchergui": + $this->prepareOutput(); + include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); + $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); + $this->ctrl->forwardCommand($gui); + break; + + case 'ildidactictemplategui': + $this->ctrl->setReturn($this, 'edit'); + include_once './Services/DidacticTemplate/classes/class.ilDidacticTemplateGUI.php'; + $did = new ilDidacticTemplateGUI($this); + $this->ctrl->forwardCommand($did); + break; + + case 'ilexportgui': + $this->prepareOutput(); + $this->tabs_gui->setTabActive('export'); + include_once './Services/Export/classes/class.ilExportGUI.php'; + $exp = new ilExportGUI($this); + $exp->addFormat('xml'); + $this->ctrl->forwardCommand($exp); + break; + + case 'ilobjecttranslationgui': + $this->checkPermissionBool("write"); + $this->prepareOutput(); + //$this->tabs_gui->setTabActive('export'); + $this->setEditTabs("settings_trans"); + include_once("./Services/Object/classes/class.ilObjectTranslationGUI.php"); + $transgui = new ilObjectTranslationGUI($this); + $this->ctrl->forwardCommand($transgui); + break; + + case 'ilobjtaxonomygui': + $this->checkPermissionBool("write"); + $this->prepareOutput(); + $this->initTaxSubTabs(); + include_once("./Services/Taxonomy/classes/class.ilObjTaxonomyGUI.php"); + $tax = new ilObjTaxonomyGUI(); + $tax->setAssignedObject($this->object->getId()); + $tax->setMultiple(true); + $tax->setListInfo($this->lng->txt("cntr_tax_list_info")); + $this->ctrl->forwardCommand($tax); + break; + + case 'ilobjectmetadatagui': + $this->checkPermissionBool("write"); + $this->prepareOutput(); + $this->tabs_gui->activateTab('meta_data'); + $this->ctrl->forwardCommand($this->getObjectMetadataGUI()); + break; + + case "ilcontainernewssettingsgui": + $this->prepareOutput(); + $this->tabs_gui->setTabActive('settings'); + $this->setEditTabs(); + $this->tabs_gui->activateSubTab('obj_news_settings'); + $news_set_gui = new ilContainerNewsSettingsGUI($this); + $news_set_gui->setHideByDate(true); + $this->ctrl->forwardCommand($news_set_gui); + break; + + default: + if ($cmd == "infoScreen") { + $this->checkPermission("visible"); + } else { + $this->checkPermission("read"); + } + + // add entry to navigation history + if (!$this->getCreationMode() && + $ilAccess->checkAccess("read", "", $_GET["ref_id"])) { + include_once("./Services/Link/classes/class.ilLink.php"); + $ilNavigationHistory->addItem( + $_GET["ref_id"], + ilLink::_getLink($_GET["ref_id"], "cat"), + "cat" + ); + } + + $this->prepareOutput(); + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + if (is_object($this->object)) { + $this->tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath($this->object->getStyleSheetId()) + ); + } + + if (!$cmd) { + $cmd = "render"; + } + $cmd .= "Object"; + $this->tabs_gui->activateTab("view_content"); // see #19868 + $this->$cmd(); + + break; + } + + $this->addHeaderAction(); + + return true; + } + + + /** + * @inheritDoc + */ + protected function addHeaderAction() + { + ilPreviewGUI::initPreview(); + parent::addHeaderAction(); + } + + + /** + * Get object metadata gui + * + * @param + * @return + */ + public function getObjectMetadataGUI() + { + include_once 'Services/Object/classes/class.ilObjectMetaDataGUI.php'; + $md_gui = new ilObjectMetaDataGUI($this->object); + include_once "Services/Object/classes/class.ilObjectServiceSettingsGUI.php"; + if (ilContainer::_lookupContainerSetting( + $this->object->getId(), + ilObjectServiceSettingsGUI::TAXONOMIES, + false + )) { + $md_gui->enableTaxonomyDefinition(true); + $tax = $md_gui->getTaxonomyObjGUI(); + $tax->setMultiple(true); + $tax->setListInfo($this->lng->txt("cntr_tax_list_info")); + $taxonomies = $this->getTaxonomiesForRefId(); + if (sizeof($taxonomies)) { + $md_gui->setTaxonomySettings(function ($form) { + $tax = $this->getTaxonomiesForRefId(); + $block = new ilCheckboxGroupInputGUI($this->lng->txt("cntr_taxonomy_show_sideblock"), "sblock"); + $form->addItem($block); + + $current = $this->getActiveBlocks(); + + foreach ($tax as $tax_id => $tax_item) { + $option = new ilCheckboxOption( + $tax_item["title"], + $tax_id, + ilObject::_lookupDescription($tax_id) + ); + + if ($tax_item["source"] != $this->object->getRefId()) { + $loc = new ilLocatorGUI(); + $loc->setTextOnly(true); + $loc->addRepositoryItems($tax_item["source"]); + $option->setInfo($loc->getHTML()); + } + + $block->addOption($option); + + if (in_array($tax_id, $current)) { + $value[] = $tax_id; + } + } + + $block->setValue($value); + }, function ($form) { + $taxonomies = $this->getTaxonomiesForRefId(); + if (sizeof($taxonomies)) { + $sblock = $form->getInput("sblock"); + + $prefix = self::CONTAINER_SETTING_TAXBLOCK; + + ilContainer::_deleteContainerSettings( + $this->object->getId(), + $prefix . "%", + true + ); + + if (is_array($sblock)) { + foreach ($sblock as $tax_id) { + ilContainer::_writeContainerSetting( + $this->object->getId(), + $prefix . $tax_id, + 1 + ); + } + } + } + }); + } + } + return $md_gui; + } + + + /** + * Get tabs + */ + public function getTabs() + { + $rbacsystem = $this->rbacsystem; + $lng = $this->lng; + $ilHelp = $this->help; + $ilAccess = $this->access; + + if ($this->ctrl->getCmd() == "editPageContent") { + return; + } + #$this->ctrl->setParameter($this,"ref_id",$this->ref_id); + + $ilHelp->setScreenIdComponent("cat"); + + if ($rbacsystem->checkAccess('read', $this->ref_id)) { + $force_active = ($_GET["cmd"] == "" || $_GET["cmd"] == "render") + ? true + : false; + $this->tabs_gui->addTab( + "view_content", + $lng->txt("content"), + $this->ctrl->getLinkTarget($this, "") + ); + + //BEGIN ChangeEvent add info tab to category object + if ($this->info_screen_enabled) { + $force_active = ($this->ctrl->getNextClass() == "ilinfoscreengui" + || strtolower($_GET["cmdClass"]) == "ilnotegui") + ? true + : false; + $this->tabs_gui->addTarget( + "info_short", + $this->ctrl->getLinkTargetByClass( + array("ilobjcategorygui", "ilinfoscreengui"), + "showSummary" + ), + array("showSummary","", "infoScreen"), + "", + "", + $force_active + ); + } + //END ChangeEvent add info tab to category object + } + + if ($rbacsystem->checkAccess('write', $this->ref_id)) { + $force_active = ($_GET["cmd"] == "edit") + ? true + : false; + $this->tabs_gui->addTarget( + "settings", + $this->ctrl->getLinkTarget($this, "edit"), + "edit", + get_class($this), + "", + $force_active + ); + + + + // metadata / taxonomies + include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php"; + $mdgui = new ilObjectMetaDataGUI($this->object); + if (ilContainer::_lookupContainerSetting( + $this->object->getId(), + ilObjectServiceSettingsGUI::TAXONOMIES, + false + )) { + $mdgui->enableTaxonomyDefinition(true); + } + $mdtab = $mdgui->getTab(); + if ($mdtab) { + $this->tabs_gui->addTab( + "meta_data", + $this->lng->txt("meta_data"), + $mdtab + ); + } + } + + include_once './Services/User/classes/class.ilUserAccountSettings.php'; + if ( + ilUserAccountSettings::getInstance()->isLocalUserAdministrationEnabled() and + $rbacsystem->checkAccess('cat_administrate_users', $this->ref_id)) { + $this->tabs_gui->addTarget( + "administrate_users", + $this->ctrl->getLinkTarget($this, "listUsers"), + "listUsers", + get_class($this) + ); + } + + if ($ilAccess->checkAccess('write', '', $this->object->getRefId())) { + $this->tabs_gui->addTarget( + 'export', + $this->ctrl->getLinkTargetByClass('ilexportgui', ''), + 'export', + 'ilexportgui' + ); + } + + // parent tabs (all container: edit_permission, clipboard, trash + parent::getTabs(); + } + + /** + * Render category + */ + public function renderObject() + { + $ilTabs = $this->tabs; + + $ilTabs->activateTab("view_content"); + $ret = parent::renderObject(); + return $ret; + } + + public function viewObject() + { + if (strtolower($_GET["baseClass"]) == "iladministrationgui") { + parent::viewObject(); + return true; + } + return $this->renderObject(); + } + + protected function initCreationForms($a_new_type) + { + $forms = parent::initCreationForms($a_new_type); + //unset($forms[self::CFORM_IMPORT]); + return $forms; + } + + protected function afterSave(ilObject $a_new_object) + { + $tree = $this->tree; + + // default: sort by title + include_once('Services/Container/classes/class.ilContainerSortingSettings.php'); + $settings = new ilContainerSortingSettings($a_new_object->getId()); + $settings->setSortMode(ilContainer::SORT_TITLE); + $settings->save(); + + // inherit parents content style, if not individual + $parent_ref_id = $tree->getParentId($a_new_object->getRefId()); + $parent_id = ilObject::_lookupObjId($parent_ref_id); + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $style_id = ilObjStyleSheet::lookupObjectStyle($parent_id); + if ($style_id > 0) { + if (ilObjStyleSheet::_lookupStandard($style_id)) { + ilObjStyleSheet::writeStyleUsage($a_new_object->getId(), $style_id); + } + } + + // always send a message + ilUtil::sendSuccess($this->lng->txt("cat_added"), true); + $this->ctrl->setParameter($this, "ref_id", $a_new_object->getRefId()); + $this->redirectToRefId($a_new_object->getRefId(), ""); + } + + /** + * 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 infoScreenObject() + { + $this->ctrl->setCmd("showSummary"); + $this->ctrl->setCmdClass("ilinfoscreengui"); + $this->infoScreen(); + } + + /** + * show information screen + */ + public function infoScreen() + { + $ilAccess = $this->access; + $ilCtrl = $this->ctrl; + $ilErr = $this->error; + + if (!$ilAccess->checkAccess("visible", "", $this->ref_id)) { + $ilErr->raiseError($this->lng->txt("msg_no_perm_read"), $ilErr->MESSAGE); + } + + if (!$this->info_screen_enabled) { + return; + } + + // #10986 + $this->tabs_gui->setTabActive('info_short'); + + include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); + $info = new ilInfoScreenGUI($this); + + $info->enablePrivateNotes(); + + if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) { + $info->enableNews(); + } + + // no news editing for files, just notifications + $info->enableNewsEditing(false); + if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) { + $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); + } + } + + include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecordGUI.php'); + $record_gui = new ilAdvancedMDRecordGUI(ilAdvancedMDRecordGUI::MODE_INFO, 'cat', $this->object->getId()); + $record_gui->setInfoObject($info); + $record_gui->parse(); + + + // standard meta data + $info->addMetaDataSections($this->object->getId(), 0, $this->object->getType()); + + // forward the command + if ($ilCtrl->getNextClass() == "ilinfoscreengui") { + $ilCtrl->forwardCommand($info); + } else { + return $ilCtrl->getHTML($info); + } + } + + /** + * Edit extended category settings + * + * @access protected + */ + protected function editInfoObject() + { + $this->checkPermission("write"); + $this->setEditTabs(); + $this->tabs_gui->activateTab('settings'); + $this->tabs_gui->setSubTabActive('edit_cat_settings'); + + $this->initExtendedSettings(); + $this->tpl->setContent($this->form->getHTML()); + } + + /** + * Update info (extended meta data) + * + * @access protected + */ + protected function updateInfoObject() + { + $this->checkPermission("write"); + + // init form + $this->initExtendedSettings(); + + // still needed for date conversion and so on + $this->form->checkInput(); + + if ($this->record_gui->importEditFormPostValues()) { + $this->record_gui->writeEditForm(); + + ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); + $this->ctrl->redirect($this, "editInfo"); + } + + $this->editInfoObject(); + } + + + /** + * build property form for extended category settings + * + * @access protected + */ + protected function initExtendedSettings() + { + if (is_object($this->form)) { + return true; + } + + include_once('Services/Form/classes/class.ilPropertyFormGUI.php'); + $this->form = new ilPropertyFormGUI(); + $this->form->setFormAction($this->ctrl->getFormAction($this)); + $this->form->setTitle($this->lng->txt('ext_cat_settings')); + $this->form->addCommandButton('updateInfo', $this->lng->txt('save')); + $this->form->addCommandButton('editInfo', $this->lng->txt('cancel')); + + include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecordGUI.php'); + $this->record_gui = new ilAdvancedMDRecordGUI(ilAdvancedMDRecordGUI::MODE_EDITOR, 'cat', $this->object->getId()); + $this->record_gui->setPropertyForm($this->form); + $this->record_gui->parse(); + + return true; + } + + protected function setEditTabs($active_tab = "settings_misc") + { + $ilSetting = $this->settings; + $ilTabs = $this->tabs; + + $this->tabs_gui->addSubTab( + "settings_misc", + $this->lng->txt("settings"), + $this->ctrl->getLinkTarget($this, "edit") + ); + + $this->tabs_gui->addSubTab( + "settings_trans", + $this->lng->txt("obj_multilinguality"), + $this->ctrl->getLinkTargetByClass("ilobjecttranslationgui", "") + ); + + //news tab + $news_active = ilContainer::_lookupContainerSetting( + $this->object->getId(), + ilObjectServiceSettingsGUI::NEWS_VISIBILITY, + true + ); + + if ($news_active) { + $this->tabs_gui->addSubTab( + 'obj_news_settings', + $this->lng->txt("cont_news_settings"), + $this->ctrl->getLinkTargetByClass('ilcontainernewssettingsgui') + ); + } + + $this->tabs_gui->activateTab("settings"); + $this->tabs_gui->activateSubTab($active_tab); + } + + public function initEditForm() + { + $obj_service = $this->getObjectService(); + + $this->lng->loadLanguageModule($this->object->getType()); + $this->setEditTabs(); + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this)); + $form->setTitle($this->lng->txt($this->object->getType() . "_edit")); + + // title/description + $this->initFormTitleDescription($form); + + // Show didactic template type + $this->initDidacticTemplate($form); + + // presentation + $pres = new ilFormSectionHeaderGUI(); + $pres->setTitle($this->lng->txt('obj_presentation')); + $form->addItem($pres); + + // title and icon visibility + $form = $obj_service->commonSettings()->legacyForm($form, $this->object)->addTitleIconVisibility(); + + // top actions visibility + $form = $obj_service->commonSettings()->legacyForm($form, $this->object)->addTopActionsVisibility(); + + // custom icon + $form = $obj_service->commonSettings()->legacyForm($form, $this->object)->addIcon(); + + // tile image + $form = $obj_service->commonSettings()->legacyForm($form, $this->object)->addTileImage(); + + // list presentation + $form = $this->initListPresentationForm($form); + + // sorting + $form = $this->initSortingForm( + $form, + array( + ilContainer::SORT_TITLE, + ilContainer::SORT_CREATION, + ilContainer::SORT_MANUAL + ) + ); + + // block limit + $bl = new ilNumberInputGUI($this->lng->txt("cont_block_limit"), "block_limit"); + $bl->setInfo($this->lng->txt("cont_block_limit_info")); + $bl->setValue(ilContainer::_lookupContainerSetting($this->object->getId(), "block_limit")); + $form->addItem($bl); + + // icon settings + + // Edit ecs export settings + include_once 'Modules/Category/classes/class.ilECSCategorySettings.php'; + $ecs = new ilECSCategorySettings($this->object); + $ecs->addSettingsToForm($form, 'cat'); + + // services + $sh = new ilFormSectionHeaderGUI(); + $sh->setTitle($this->lng->txt('obj_features')); + $form->addItem($sh); + + include_once './Services/Object/classes/class.ilObjectServiceSettingsGUI.php'; + ilObjectServiceSettingsGUI::initServiceSettingsForm( + $this->object->getId(), + $form, + array( + ilObjectServiceSettingsGUI::INFO_TAB_VISIBILITY, + ilObjectServiceSettingsGUI::NEWS_VISIBILITY, + ilObjectServiceSettingsGUI::TAXONOMIES, + ilObjectServiceSettingsGUI::CUSTOM_METADATA + ) + ); + + $form->addCommandButton("update", $this->lng->txt("save")); + + return $form; + } + + public function getEditFormValues() + { + // values are set in initEditForm() + } + + /** + * updates object entry in object_data + * + * @access public + */ + public function updateObject() + { + $ilErr = $this->error; + $ilUser = $this->user; + $obj_service = $this->getObjectService(); + + if (!$this->checkPermissionBool("write")) { + $ilErr->raiseError($this->lng->txt("msg_no_perm_write"), $ilErr->MESSAGE); + } else { + $form = $this->initEditForm(); + if ($form->checkInput()) { + $title = $form->getInput("title"); + $desc = $form->getInput("desc"); + + $this->object->setTitle($title); + $this->object->setDescription($desc); + $this->object->update(); + + $this->saveSortingSettings($form); + + // title icon visibility + $obj_service->commonSettings()->legacyForm($form, $this->object)->saveTitleIconVisibility(); + + // top actions visibility + $obj_service->commonSettings()->legacyForm($form, $this->object)->saveTopActionsVisibility(); + + // custom icon + $obj_service->commonSettings()->legacyForm($form, $this->object)->saveIcon(); + + // tile image + $obj_service->commonSettings()->legacyForm($form, $this->object)->saveTileImage(); + + // list presentation + $this->saveListPresentation($form); + + // BEGIN ChangeEvent: Record update + require_once('Services/Tracking/classes/class.ilChangeEvent.php'); + ilChangeEvent::_recordWriteEvent($this->object->getId(), $ilUser->getId(), 'update'); + ilChangeEvent::_catchupWriteEvents($this->object->getId(), $ilUser->getId()); + // END ChangeEvent: Record update + + // services + include_once './Services/Object/classes/class.ilObjectServiceSettingsGUI.php'; + ilObjectServiceSettingsGUI::updateServiceSettingsForm( + $this->object->getId(), + $form, + array( + ilObjectServiceSettingsGUI::INFO_TAB_VISIBILITY, + ilObjectServiceSettingsGUI::NEWS_VISIBILITY, + ilObjectServiceSettingsGUI::TAXONOMIES, + ilObjectServiceSettingsGUI::CUSTOM_METADATA + ) + ); + + // block limit + if ((int) $form->getInput("block_limit") > 0) { + ilContainer::_writeContainerSetting($this->object->getId(), "block_limit", (int) $form->getInput("block_limit")); + } else { + ilContainer::_deleteContainerSettings($this->object->getId(), "block_limit"); + } + // Update ecs export settings + include_once 'Modules/Category/classes/class.ilECSCategorySettings.php'; + $ecs = new ilECSCategorySettings($this->object); + if ($ecs->handleSettingsUpdate()) { + return $this->afterUpdate(); + } + } + + // display form to correct errors + $this->setEditTabs(); + $form->setValuesByPost(); + $this->tpl->setContent($form->getHTML()); + } + } + + /** + * display form for category import + */ + public function importCategoriesFormObject() + { + ilObjCategoryGUI::_importCategoriesForm($this->ref_id, $this->tpl); + } + + /** + * display form for category import (static, also called by RootFolderGUI) + */ + public static function _importCategoriesForm($a_ref_id, &$a_tpl) + { + global $DIC; + + $lng = $DIC->language(); + $rbacreview = $DIC->rbac()->review(); + $ilCtrl = $DIC->ctrl(); + + $a_tpl->addBlockfile( + "ADM_CONTENT", + "adm_content", + "tpl.cat_import_form.html", + "Modules/Category" + ); + + $a_tpl->setVariable("FORMACTION", $ilCtrl->getFormActionByClass('ilObjCategoryGUI')); + + $a_tpl->setVariable("TXT_IMPORT_CATEGORIES", $lng->txt("import_categories")); + $a_tpl->setVariable("TXT_HIERARCHY_OPTION", $lng->txt("import_cat_localrol")); + $a_tpl->setVariable("TXT_IMPORT_FILE", $lng->txt("import_file")); + $a_tpl->setVariable("TXT_IMPORT_TABLE", $lng->txt("import_cat_table")); + + $a_tpl->setVariable("BTN_IMPORT", $lng->txt("import")); + $a_tpl->setVariable("BTN_CANCEL", $lng->txt("cancel")); + + // NEED TO FILL ADOPT_PERMISSIONS HTML FORM.... + $parent_role_ids = $rbacreview->getParentRoleIds($a_ref_id, true); + + // sort output for correct color changing + ksort($parent_role_ids); + + foreach ($parent_role_ids as $key => $par) { + if ($par["obj_id"] != SYSTEM_ROLE_ID) { + $check = ilUtil::formCheckbox(0, "adopt[]", $par["obj_id"], 1); + $output["adopt"][$key]["css_row_adopt"] = ilUtil::switchColor($key, "tblrow1", "tblrow2"); + $output["adopt"][$key]["check_adopt"] = $check; + $output["adopt"][$key]["role_id"] = $par["obj_id"]; + $output["adopt"][$key]["type"] = ($par["type"] == 'role' ? 'Role' : 'Template'); + $output["adopt"][$key]["role_name"] = $par["title"]; + } + } + + //var_dump($output); + + // BEGIN ADOPT PERMISSIONS + foreach ($output["adopt"] as $key => $value) { + $a_tpl->setCurrentBlock("ADOPT_PERM_ROW"); + $a_tpl->setVariable("CSS_ROW_ADOPT", $value["css_row_adopt"]); + $a_tpl->setVariable("CHECK_ADOPT", $value["check_adopt"]); + $a_tpl->setVariable("LABEL_ID", $value["role_id"]); + $a_tpl->setVariable("TYPE", $value["type"]); + $a_tpl->setVariable("ROLE_NAME", $value["role_name"]); + $a_tpl->parseCurrentBlock(); + } + } + + + /** + * import cancelled + * + * @access private + */ + public function importCancelledObject() + { + $this->ctrl->redirect($this); + } + + /** + * get user import directory name + */ + public static function _getImportDir() + { + return ilUtil::getDataDir() . "/cat_import"; + } + + /** + * import categories + */ + public function importCategoriesObject() + { + ilObjCategoryGUI::_importCategories($_GET["ref_id"]); + // call to importCategories with $withrol = 0 + ilObjCategoryGUI::_importCategories($_GET["ref_id"], 0); + } + + /** + * import categories with local rol + */ + public function importCategoriesWithRolObject() + { + + //echo "entra aqui"; + // call to importCategories with $withrol = 1 + ilObjCategoryGUI::_importCategories($_GET["ref_id"], 1); + } + + /** + * import categories (static, also called by RootFolderGUI) + */ + + public static function _importCategories($a_ref_id, $withrol_tmp) + { + global $DIC; + + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + + require_once("./Modules/Category/classes/class.ilCategoryImportParser.php"); + + $import_dir = ilObjCategoryGUI::_getImportDir(); + + // create user import directory if necessary + if (!@is_dir($import_dir)) { + ilUtil::createDirectory($import_dir); + } + + // move uploaded file to user import directory + + $file_name = $_FILES["importFile"]["name"]; + + // added to prevent empty file names + if (!strcmp($file_name, "")) { + ilUtil::sendFailure($lng->txt("no_import_file_found"), true); + $ilCtrl->redirectByClass('ilObjCategoryGUI'); + } + + $parts = pathinfo($file_name); + $full_path = $import_dir . "/" . $file_name; + ilUtil::moveUploadedFile($_FILES["importFile"]["tmp_name"], $file_name, $full_path); + + // unzip file + ilUtil::unzip($full_path); + + $subdir = basename($parts["basename"], "." . $parts["extension"]); + $xml_file = $import_dir . "/" . $subdir . "/" . $subdir . ".xml"; + // CategoryImportParser + //var_dump($_POST); + $importParser = new ilCategoryImportParser($xml_file, $a_ref_id, $withrol_tmp); + $importParser->startParsing(); + + ilUtil::sendSuccess($lng->txt("categories_imported"), true); + $ilCtrl->redirectByClass('ilObjCategoryGUI'); + } + + /** + * Reset filter + * (note: this function existed before data table filter has been introduced + */ + protected function resetFilterObject() + { + include_once("./Services/User/classes/class.ilUserTableGUI.php"); + $utab = new ilUserTableGUI($this, "listUsers", ilUserTableGUI::MODE_LOCAL_USER); + $utab->resetOffset(); + $utab->resetFilter(); + + // from "old" implementation + $this->listUsersObject(); + } + + /** + * Apply filter + * @return + */ + protected function applyFilterObject() + { + $ilTabs = $this->tabs; + + include_once("./Services/User/classes/class.ilUserTableGUI.php"); + $utab = new ilUserTableGUI($this, "listUsers", ilUserTableGUI::MODE_LOCAL_USER); + $utab->resetOffset(); + $utab->writeFilterToSession(); + $this->listUsersObject(); + } + + // METHODS for local user administration + public function listUsersObject($show_delete = false) + { + $ilUser = $this->user; + $ilErr = $this->error; + $ilToolbar = $this->toolbar; + + include_once './Services/User/classes/class.ilLocalUser.php'; + include_once './Services/User/classes/class.ilObjUserGUI.php'; + + $rbacsystem = $this->rbacsystem; + $rbacreview = $this->rbacreview; + + if (!$rbacsystem->checkAccess("cat_administrate_users", $this->object->getRefId())) { + $ilErr->raiseError($this->lng->txt("msg_no_perm_admin_users"), $ilErr->MESSAGE); + } + $this->tabs_gui->setTabActive('administrate_users'); + + + + $this->tpl->addBlockfile( + 'ADM_CONTENT', + 'adm_content', + 'tpl.cat_admin_users.html', + "Modules/Category" + ); + + if (count($rbacreview->getGlobalAssignableRoles()) or in_array(SYSTEM_ROLE_ID, $rbacreview->assignedRoles($ilUser->getId()))) { + $ilToolbar->addButton( + $this->lng->txt('add_user'), + $this->ctrl->getLinkTargetByClass('ilobjusergui', 'create') + ); + + $ilToolbar->addButton( + $this->lng->txt('import_users'), + $this->ctrl->getLinkTargetByClass('ilobjuserfoldergui', 'importUserForm') + ); + } else { + ilUtil::sendInfo($this->lng->txt('no_roles_user_can_be_assigned_to')); + } + + if ($show_delete) { + $this->tpl->setCurrentBlock("confirm_delete"); + $this->tpl->setVariable("CONFIRM_FORMACTION", $this->ctrl->getFormAction($this)); + $this->tpl->setVariable("TXT_CANCEL", $this->lng->txt('cancel')); + $this->tpl->setVariable("CONFIRM_CMD", 'performDeleteUsers'); + $this->tpl->setVariable("TXT_CONFIRM", $this->lng->txt('delete')); + $this->tpl->parseCurrentBlock(); + } + + $this->lng->loadLanguageModule('user'); + + include_once("./Services/User/classes/class.ilUserTableGUI.php"); + $utab = new ilUserTableGUI($this, 'listUsers', ilUserTableGUI::MODE_LOCAL_USER); + $this->tpl->setVariable('USERS_TABLE', $utab->getHTML()); + + return true; + } + + /** + * Show auto complete results + */ + protected function addUserAutoCompleteObject() + { + include_once './Services/User/classes/class.ilUserAutoComplete.php'; + $auto = new ilUserAutoComplete(); + $auto->setSearchFields(array('login','firstname','lastname','email')); + $auto->enableFieldSearchableCheck(true); + $auto->isMoreLinkAvailable(true); + + if (($_REQUEST['fetchall'])) { + $auto->setLimit(ilUserAutoComplete::MAX_ENTRIES); + } + + echo $auto->getList($_REQUEST['term']); + exit(); + } + + + public function performDeleteUsersObject() + { + include_once './Services/User/classes/class.ilLocalUser.php'; + $this->checkPermission("cat_administrate_users"); + + foreach ($_POST['user_ids'] as $user_id) { + if (!in_array($user_id, ilLocalUser::_getAllUserIds($this->object->getRefId()))) { + die('user id not valid'); + } + if (!$tmp_obj =&ilObjectFactory::getInstanceByObjId($user_id, false)) { + continue; + } + $tmp_obj->delete(); + } + ilUtil::sendSuccess($this->lng->txt('deleted_users')); + $this->listUsersObject(); + + return true; + } + + public function deleteUsersObject() + { + $this->checkPermission("cat_administrate_users"); + if (!count($_POST['id'])) { + ilUtil::sendFailure($this->lng->txt('no_users_selected')); + $this->listUsersObject(); + + return true; + } + + include_once './Services/Utilities/classes/class.ilConfirmationGUI.php'; + $confirm = new ilConfirmationGUI(); + $confirm->setFormAction($this->ctrl->getFormAction($this)); + $confirm->setHeaderText($this->lng->txt('sure_delete_selected_users')); + $confirm->setConfirm($this->lng->txt('delete'), 'performDeleteUsers'); + $confirm->setCancel($this->lng->txt('cancel'), 'listUsers'); + + foreach ($_POST['id'] as $user) { + $name = ilObjUser::_lookupName($user); + + $confirm->addItem( + 'user_ids[]', + $user, + $name['lastname'] . ', ' . $name['firstname'] . ' [' . $name['login'] . ']' + ); + } + $this->tpl->setContent($confirm->getHTML()); + } + + public function assignRolesObject() + { + $rbacreview = $this->rbacreview; + $ilTabs = $this->tabs; + + $this->checkPermission("cat_administrate_users"); + + include_once './Services/User/classes/class.ilLocalUser.php'; + + if (!isset($_GET['obj_id'])) { + ilUtil::sendFailure('no_user_selected'); + $this->listUsersObject(); + + return true; + } + + $ilTabs->clearTargets(); + $ilTabs->setBackTarget($this->lng->txt('backto_lua'), $this->ctrl->getLinkTarget($this, 'listUsers')); + $ilHelp = $this->help; + $ilHelp->setScreenIdComponent("cat"); + $ilHelp->setScreenId("administrate_user"); + $ilHelp->setSubScreenId("assign_roles"); + + + $roles = $this->__getAssignableRoles(); + + if (!count($roles)) { + #ilUtil::sendInfo($this->lng->txt('no_roles_user_can_be_assigned_to')); + #$this->listUsersObject(); + + #return true; + } + + $ass_roles = $rbacreview->assignedRoles($_GET['obj_id']); + + $counter = 0; + $f_result = array(); + + foreach ($roles as $role) { + $role_obj =&ilObjectFactory::getInstanceByObjId($role['obj_id']); + + $disabled = false; + $f_result[$counter]['checkbox'] = ilUtil::formCheckbox( + in_array($role['obj_id'], $ass_roles) ? 1 : 0, + 'role_ids[]', + $role['obj_id'], + $disabled + ); + $f_result[$counter]['title'] = $role_obj->getTitle() ? $role_obj->getTitle() : ""; + $f_result[$counter]['desc'] = $role_obj->getDescription() ? $role_obj->getDescription() : ""; + $f_result[$counter]['type'] = $role['role_type'] == 'global' ? + $this->lng->txt('global') : + $this->lng->txt('local'); + + unset($role_obj); + ++$counter; + } + + include_once('./Modules/Category/classes/class.ilCategoryAssignRoleTableGUI.php'); + $table = new ilCategoryAssignRoleTableGUI($this, "assignRoles"); + $tmp_obj =&ilObjectFactory::getInstanceByObjId($_GET['obj_id']); + $title = $this->lng->txt('role_assignment') . ' (' . $tmp_obj->getFullname() . ')'; + $table->setTitle($title, "icon_role.svg", $this->lng->txt("role_assignment")); + $table->setData($f_result); + $this->tpl->setContent($table->getHTML()); + } + + public function assignSaveObject() + { + $rbacreview = $this->rbacreview; + $rbacadmin = $this->rbacadmin; + $this->checkPermission("cat_administrate_users"); + + include_once './Services/User/classes/class.ilLocalUser.php'; + // check hack + if (!isset($_GET['obj_id']) or !in_array($_REQUEST['obj_id'], ilLocalUser::_getAllUserIds())) { + ilUtil::sendFailure('no_user_selected'); + $this->listUsersObject(); + + return true; + } + $roles = $this->__getAssignableRoles(); + + // check minimum one global role + if (!$this->__checkGlobalRoles($_POST['role_ids'])) { + ilUtil::sendFailure($this->lng->txt('no_global_role_left')); + $this->assignRolesObject(); + + return false; + } + + $new_role_ids = $_POST['role_ids'] ? $_POST['role_ids'] : array(); + $assigned_roles = $rbacreview->assignedRoles((int) $_REQUEST['obj_id']); + foreach ($roles as $role) { + if (in_array($role['obj_id'], $new_role_ids) and !in_array($role['obj_id'], $assigned_roles)) { + $rbacadmin->assignUser($role['obj_id'], (int) $_REQUEST['obj_id']); + } + if (in_array($role['obj_id'], $assigned_roles) and !in_array($role['obj_id'], $new_role_ids)) { + $rbacadmin->deassignUser($role['obj_id'], (int) $_REQUEST['obj_id']); + } + } + ilUtil::sendSuccess($this->lng->txt('role_assignment_updated')); + $this->assignRolesObject(); + + return true; + } + + // PRIVATE + public function __getAssignableRoles() + { + $rbacreview = $this->rbacreview; + $ilUser = $this->user; + + // check local user + $tmp_obj =&ilObjectFactory::getInstanceByObjId($_REQUEST['obj_id']); + // Admin => all roles + if (in_array(SYSTEM_ROLE_ID, $rbacreview->assignedRoles($ilUser->getId()))) { + $global_roles = $rbacreview->getGlobalRolesArray(); + } elseif ($tmp_obj->getTimeLimitOwner() == $this->object->getRefId()) { + $global_roles = $rbacreview->getGlobalAssignableRoles(); + } else { + $global_roles = array(); + } + return $roles = array_merge( + $global_roles, + $rbacreview->getAssignableChildRoles($this->object->getRefId()) + ); + } + + public function __checkGlobalRoles($new_assigned) + { + $rbacreview = $this->rbacreview; + $ilUser = $this->user; + + $this->checkPermission("cat_administrate_users"); + + // return true if it's not a local user + $tmp_obj =&ilObjectFactory::getInstanceByObjId($_REQUEST['obj_id']); + if ($tmp_obj->getTimeLimitOwner() != $this->object->getRefId() and + !in_array(SYSTEM_ROLE_ID, $rbacreview->assignedRoles($ilUser->getId()))) { + return true; + } + + // new assignment by form + $new_assigned = $new_assigned ? $new_assigned : array(); + $assigned = $rbacreview->assignedRoles((int) $_GET['obj_id']); + + // all assignable globals + if (!in_array(SYSTEM_ROLE_ID, $rbacreview->assignedRoles($ilUser->getId()))) { + $ga = $rbacreview->getGlobalAssignableRoles(); + } else { + $ga = $rbacreview->getGlobalRolesArray(); + } + $global_assignable = array(); + foreach ($ga as $role) { + $global_assignable[] = $role['obj_id']; + } + + $new_visible_assigned_roles = array_intersect($new_assigned, $global_assignable); + $all_assigned_roles = array_intersect($assigned, $rbacreview->getGlobalRoles()); + $main_assigned_roles = array_diff($all_assigned_roles, $global_assignable); + + if (!count($new_visible_assigned_roles) and !count($main_assigned_roles)) { + return false; + } + return true; + } + + public static function _goto($a_target) + { + global $DIC; + + $ilAccess = $DIC->access(); + $ilErr = $DIC["ilErr"]; + $lng = $DIC->language(); + + if ($ilAccess->checkAccess("read", "", $a_target)) { + ilObjectGUI::_gotoRepositoryNode($a_target); + } elseif ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) { + ilUtil::sendFailure(sprintf( + $lng->txt("msg_no_perm_read_item"), + ilObject::_lookupTitle(ilObject::_lookupObjId($a_target)) + ), true); + ilObjectGUI::_gotoRepositoryRoot(); + } + + $ilErr->raiseError($lng->txt("msg_no_perm_read"), $ilErr->FATAL); + } + + // + // taxonomy + // + + protected function initTaxSubTabs($a_active = "tax_list") + { + $this->tabs_gui->setTabActive("obj_tool_setting_taxonomies"); + $this->tabs_gui->addSubTab( + "tax_settings", + $this->lng->txt("cntr_taxonomy_sideblock_settings"), + $this->ctrl->getLinkTarget($this, "editTaxonomySettings") + ); + $this->tabs_gui->addSubTab( + "tax_list", + $this->lng->txt("cntr_taxonomy_definitions"), + $this->ctrl->getLinkTargetByClass("ilobjtaxonomygui", "") + ); + $this->tabs_gui->activateSubTab($a_active); + } + + protected function getTaxonomiesForRefId() + { + $tree = $this->tree; + + include_once "Services/Object/classes/class.ilObjectServiceSettingsGUI.php"; + include_once "Services/Taxonomy/classes/class.ilObjTaxonomy.php"; + + // see ilTaxMDGUI::getSelectableTaxonomies() + + $res = array(); + foreach ($tree->getPathFull($this->object->getRefId()) as $node) { + //if ($node["ref_id"] != $this->object->getRefId()) + { + // find all defined taxes for parent node, activation is not relevant + $node_taxes = ilObjTaxonomy::getUsageOfObject($node["obj_id"], true); + if (sizeof($node_taxes)) { + foreach ($node_taxes as $node_tax) { + $res[$node_tax["tax_id"]] = array( + "title" => $node_tax["title"] + , "source" => $node["child"] + ); + } + } + } + } + + asort($res); + return $res; + } + + + protected function getActiveBlocks() + { + $res = array(); + + $prefix = self::CONTAINER_SETTING_TAXBLOCK; + + foreach (ilContainer::_getContainerSettings($this->object->getId()) as $keyword => $value) { + if (substr($keyword, 0, strlen($prefix)) == $prefix && (bool) $value) { + $res[] = substr($keyword, strlen($prefix)); + } + } + + return $res; + } } // END class.ilObjCategoryGUI -?> diff --git a/Modules/Category/classes/class.ilObjCategoryListGUI.php b/Modules/Category/classes/class.ilObjCategoryListGUI.php index b3de8951529f65bc0b77a1216b7933ceed16a154..d87ec0da0817367117d376eb861015a88945a411 100644 --- a/Modules/Category/classes/class.ilObjCategoryListGUI.php +++ b/Modules/Category/classes/class.ilObjCategoryListGUI.php @@ -1,24 +1,24 @@ ctrl = $DIC->ctrl(); - } + parent::__construct($a_context); + $this->ctrl = $DIC->ctrl(); + } - /** - * initialisation - */ - function init() - { - $this->static_link_enabled = true; - $this->delete_enabled = true; - $this->cut_enabled = true; - $this->copy_enabled = true; - $this->subscribe_enabled = true; - $this->link_enabled = false; - $this->info_screen_enabled = true; + /** + * initialisation + */ + public function init() + { + $this->static_link_enabled = true; + $this->delete_enabled = true; + $this->cut_enabled = true; + $this->copy_enabled = true; + $this->subscribe_enabled = true; + $this->link_enabled = false; + $this->info_screen_enabled = true; - $this->type = "cat"; - $this->gui_class_name = "ilobjcategorygui"; + $this->type = "cat"; + $this->gui_class_name = "ilobjcategorygui"; - include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDSubstitution.php'); - $this->substitutions = ilAdvancedMDSubstitution::_getInstanceByObjectType($this->type); - if($this->substitutions->isActive()) - { - $this->substitutions_enabled = true; - } + include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDSubstitution.php'); + $this->substitutions = ilAdvancedMDSubstitution::_getInstanceByObjectType($this->type); + if ($this->substitutions->isActive()) { + $this->substitutions_enabled = true; + } - // general commands array - include_once('./Modules/Category/classes/class.ilObjCategoryAccess.php'); - $this->commands = ilObjCategoryAccess::_getCommands(); - } + // general commands array + include_once('./Modules/Category/classes/class.ilObjCategoryAccess.php'); + $this->commands = ilObjCategoryAccess::_getCommands(); + } - /** - * - * @param bool - * @return bool - */ - function getInfoScreenStatus() - { - include_once("./Services/Container/classes/class.ilContainer.php"); - include_once("./Services/Object/classes/class.ilObjectServiceSettingsGUI.php"); - if (ilContainer::_lookupContainerSetting( - $this->obj_id, - ilObjectServiceSettingsGUI::INFO_TAB_VISIBILITY, - true - )) - { - return $this->info_screen_enabled; - } + /** + * + * @param bool + * @return bool + */ + public function getInfoScreenStatus() + { + include_once("./Services/Container/classes/class.ilContainer.php"); + include_once("./Services/Object/classes/class.ilObjectServiceSettingsGUI.php"); + if (ilContainer::_lookupContainerSetting( + $this->obj_id, + ilObjectServiceSettingsGUI::INFO_TAB_VISIBILITY, + true + )) { + return $this->info_screen_enabled; + } - return false; - } + return false; + } - /** - * Get command target frame. - * - * Overwrite this method if link frame is not current frame - * - * @param string $a_cmd command - * - * @return string command target frame - */ - function getCommandFrame($a_cmd) - { - // begin-patch fm - return parent::getCommandFrame($a_cmd); - // end-patch fm - } - /** - * Get command link url. - * - * @param int $a_ref_id reference id - * @param string $a_cmd command - * - */ - function getCommandLink($a_cmd) - { - $ilCtrl = $this->ctrl; - - // BEGIN WebDAV - switch ($a_cmd) - { - case 'mount_webfolder' : - require_once ('Services/WebDAV/classes/class.ilDAVActivationChecker.php'); - if (ilDAVActivationChecker::_isActive()) - { - require_once ('Services/WebDAV/classes/class.ilWebDAVUtil.php'); - $dav_util = ilWebDAVUtil::getInstance(); - - // FIXME: The following is a very dirty, ugly trick. - // To mount URI needs to be put into two attributes: - // href and folder. This hack returns both attributes - // like this: http://...mount_uri..." folder="http://...folder_uri... - $cmd_link = $dav_util->getMountURI($this->ref_id). - '" folder="'.$dav_util->getFolderURI($this->ref_id); - } - break; - default : - // separate method for this line - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $this->ref_id); - $cmd_link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", $a_cmd); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - break; - } - // END WebDAV + /** + * Get command target frame. + * + * Overwrite this method if link frame is not current frame + * + * @param string $a_cmd command + * + * @return string command target frame + */ + public function getCommandFrame($a_cmd) + { + // begin-patch fm + return parent::getCommandFrame($a_cmd); + // end-patch fm + } + /** + * Get command link url. + * + * @param int $a_ref_id reference id + * @param string $a_cmd command + * + */ + public function getCommandLink($a_cmd) + { + $ilCtrl = $this->ctrl; + + // BEGIN WebDAV + switch ($a_cmd) { + case 'mount_webfolder': + require_once('Services/WebDAV/classes/class.ilDAVActivationChecker.php'); + if (ilDAVActivationChecker::_isActive()) { + require_once('Services/WebDAV/classes/class.ilWebDAVUtil.php'); + $dav_util = ilWebDAVUtil::getInstance(); + + // FIXME: The following is a very dirty, ugly trick. + // To mount URI needs to be put into two attributes: + // href and folder. This hack returns both attributes + // like this: http://...mount_uri..." folder="http://...folder_uri... + $cmd_link = $dav_util->getMountURI($this->ref_id) . + '" folder="' . $dav_util->getFolderURI($this->ref_id); + } + break; + default: + // separate method for this line + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $this->ref_id); + $cmd_link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", $a_cmd); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + break; + } + // END WebDAV - return $cmd_link; - } - + return $cmd_link; + } } // END class.ilObjCategoryGUI -?> diff --git a/Modules/CategoryReference/classes/class.ilCategoryReferenceExporter.php b/Modules/CategoryReference/classes/class.ilCategoryReferenceExporter.php index c1cd566de1b356520069f6b82efecd06a40b1a79..07cde27d2315b3868bacbc4a13c7c51a52de4dde 100644 --- a/Modules/CategoryReference/classes/class.ilCategoryReferenceExporter.php +++ b/Modules/CategoryReference/classes/class.ilCategoryReferenceExporter.php @@ -6,22 +6,21 @@ include_once './Services/ContainerReference/classes/class.ilContainerReferenceEx /** * Class for category export - * + * * @author Stefan Meyer * $Id$ */ class ilCategoryReferenceExporter extends ilContainerReferenceExporter { - /** - * Init xml writer - * @param ilContainerReference $ref - * @return ilCategoryXmlWriter - */ - protected function initWriter(ilContainerReference $ref) - { - include_once './Modules/CategoryReference/classes/class.ilCategoryReferenceXmlWriter.php'; - return new ilCategoryReferenceXmlWriter($ref); - } + /** + * Init xml writer + * @param ilContainerReference $ref + * @return ilCategoryXmlWriter + */ + protected function initWriter(ilContainerReference $ref) + { + include_once './Modules/CategoryReference/classes/class.ilCategoryReferenceXmlWriter.php'; + return new ilCategoryReferenceXmlWriter($ref); + } } -?> diff --git a/Modules/CategoryReference/classes/class.ilCategoryReferenceImporter.php b/Modules/CategoryReference/classes/class.ilCategoryReferenceImporter.php index c9c568764f931b15a01ae0d6c616e15934eb0aed..08debf532528825fce369d21cf36ff3c4733463d 100644 --- a/Modules/CategoryReference/classes/class.ilCategoryReferenceImporter.php +++ b/Modules/CategoryReference/classes/class.ilCategoryReferenceImporter.php @@ -16,22 +16,21 @@ include_once './Services/ContainerReference/classes/class.ilContainerReferenceIm */ class ilCategoryReferenceImporter extends ilContainerReferenceImporter { - - /** - * Get reference type - */ - protected function getType() - { - return 'catr'; - } - - /** - * Init xml parser - */ - protected function initParser($a_xml) - { - include_once './Modules/CategoryReference/classes/class.ilCategoryReferenceXmlParser.php'; - return new ilCategoryReferenceXmlParser($a_xml); - } + + /** + * Get reference type + */ + protected function getType() + { + return 'catr'; + } + + /** + * Init xml parser + */ + protected function initParser($a_xml) + { + include_once './Modules/CategoryReference/classes/class.ilCategoryReferenceXmlParser.php'; + return new ilCategoryReferenceXmlParser($a_xml); + } } -?> \ No newline at end of file diff --git a/Modules/CategoryReference/classes/class.ilCategoryReferenceXmlParser.php b/Modules/CategoryReference/classes/class.ilCategoryReferenceXmlParser.php index eb21bbc4fc1ac29023fe2460eb409085e214b65f..9e5ba134be0a247b08f58440dfc3c052f5d43224 100644 --- a/Modules/CategoryReference/classes/class.ilCategoryReferenceXmlParser.php +++ b/Modules/CategoryReference/classes/class.ilCategoryReferenceXmlParser.php @@ -1,24 +1,24 @@ diff --git a/Modules/CategoryReference/classes/class.ilCategoryReferenceXmlWriter.php b/Modules/CategoryReference/classes/class.ilCategoryReferenceXmlWriter.php index 5ace4f87eef6ff874eb9549bf5be664b0bbeef4e..67a23c079ea5c0421d282dc648fb21a838dc90be 100644 --- a/Modules/CategoryReference/classes/class.ilCategoryReferenceXmlWriter.php +++ b/Modules/CategoryReference/classes/class.ilCategoryReferenceXmlWriter.php @@ -12,35 +12,34 @@ include_once './Services/ContainerReference/classes/class.ilContainerReferenceXm class ilCategoryReferenceXmlWriter extends ilContainerReferenceXmlWriter { - /** - * constructor - * @param string xml version - * @param string output encoding - * @param string input encoding - * @access public - */ - public function __construct(ilObjCategoryReference $ref = null) - { - global $DIC; + /** + * constructor + * @param string xml version + * @param string output encoding + * @param string input encoding + * @access public + */ + public function __construct(ilObjCategoryReference $ref = null) + { + global $DIC; - $this->settings = $DIC->settings(); - parent::__construct($ref); - } + $this->settings = $DIC->settings(); + parent::__construct($ref); + } - /** - * Build xml header - * @global $ilSetting - * @return - */ - protected function buildHeader() - { - $ilSetting = $this->settings; + /** + * Build xml header + * @global $ilSetting + * @return + */ + protected function buildHeader() + { + $ilSetting = $this->settings; - $this->xmlSetDtdDef(""); - $this->xmlSetGenCmt("Export of ILIAS category reference ". $this->getReference()->getId()." of installation ".$ilSetting->get('inst_id')."."); - $this->xmlHeader(); + $this->xmlSetDtdDef(""); + $this->xmlSetGenCmt("Export of ILIAS category reference " . $this->getReference()->getId() . " of installation " . $ilSetting->get('inst_id') . "."); + $this->xmlHeader(); - return true; - } + return true; + } } -?> \ No newline at end of file diff --git a/Modules/CategoryReference/classes/class.ilObjCategoryReference.php b/Modules/CategoryReference/classes/class.ilObjCategoryReference.php index 723dfdaf3b1f0ce02ca1a05a7fd91f0b736a1d97..01bd77d4012e836b01694deb87f447afeac579d2 100644 --- a/Modules/CategoryReference/classes/class.ilObjCategoryReference.php +++ b/Modules/CategoryReference/classes/class.ilObjCategoryReference.php @@ -1,54 +1,53 @@ * @version $Id$ -* +* * * @ingroup ModulesCategoryReference */ class ilObjCategoryReference extends ilContainerReference { - /** - * Constructor - * @param int $a_id reference id - * @param bool $a_call_by_reference - * @return void - */ - public function __construct($a_id = 0,$a_call_by_reference = true) - { - global $DIC; + /** + * Constructor + * @param int $a_id reference id + * @param bool $a_call_by_reference + * @return void + */ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + global $DIC; - $this->db = $DIC->database(); - $ilDB = $DIC->database(); + $this->db = $DIC->database(); + $ilDB = $DIC->database(); - $this->type = 'catr'; - parent::__construct($a_id,$a_call_by_reference); - } + $this->type = 'catr'; + parent::__construct($a_id, $a_call_by_reference); + } } -?> \ No newline at end of file diff --git a/Modules/CategoryReference/classes/class.ilObjCategoryReferenceAccess.php b/Modules/CategoryReference/classes/class.ilObjCategoryReferenceAccess.php index ed80a6fec4213bd8166e1b3b544b2087b8e7a2fe..6d369b7a7995d04d353e2a3f0b10ff098a4be51a 100644 --- a/Modules/CategoryReference/classes/class.ilObjCategoryReferenceAccess.php +++ b/Modules/CategoryReference/classes/class.ilObjCategoryReferenceAccess.php @@ -1,78 +1,72 @@ * @version $Id$ -* -* +* +* * @ingroup ModulesCategoryReference */ class ilObjCategoryReferenceAccess extends ilContainerReferenceAccess { - /** - * get commands - * - * Depends on permissions - * - * @param int $a_ref_id Reference id of course link - * - * 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($a_ref_id = null) - { - global $DIC; + /** + * get commands + * + * Depends on permissions + * + * @param int $a_ref_id Reference id of course link + * + * 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($a_ref_id = null) + { + global $DIC; - $ilAccess = $DIC->access(); + $ilAccess = $DIC->access(); - if($ilAccess->checkAccess('write','',$a_ref_id)) - { - // Only local (reference specific commands) - $commands = array - ( - array("permission" => "visible", "cmd" => "", "lang_var" => "show","default" => true), - array("permission" => "write", "cmd" => "editReference", "lang_var" => "edit") - ); - } - else - { - include_once('./Modules/Category/classes/class.ilObjCategoryAccess.php'); - $commands = ilObjCategoryAccess::_getCommands(); - } - return $commands; - } - -} -?> \ No newline at end of file + if ($ilAccess->checkAccess('write', '', $a_ref_id)) { + // Only local (reference specific commands) + $commands = array( + array("permission" => "visible", "cmd" => "", "lang_var" => "show","default" => true), + array("permission" => "write", "cmd" => "editReference", "lang_var" => "edit") + ); + } else { + include_once('./Modules/Category/classes/class.ilObjCategoryAccess.php'); + $commands = ilObjCategoryAccess::_getCommands(); + } + return $commands; + } +} diff --git a/Modules/CategoryReference/classes/class.ilObjCategoryReferenceGUI.php b/Modules/CategoryReference/classes/class.ilObjCategoryReferenceGUI.php index 883b28aae4d6d2f8344109a611b08c22e8e9de86..c3ec6ccdfa788a7d1cd02254ae6cbdd2931ff325 100644 --- a/Modules/CategoryReference/classes/class.ilObjCategoryReferenceGUI.php +++ b/Modules/CategoryReference/classes/class.ilObjCategoryReferenceGUI.php @@ -1,119 +1,121 @@ * @version $Id$ -* +* * @ilCtrl_Calls ilObjCategoryReferenceGUI: ilPermissionGUI, ilInfoScreenGUI, ilPropertyFormGUI * @ingroup ModulesCategoryReference */ class ilObjCategoryReferenceGUI extends ilContainerReferenceGUI { - /** - * @var ilHelpGUI - */ - protected $help; + /** + * @var ilHelpGUI + */ + protected $help; - protected $target_type = 'cat'; - protected $reference_type = 'catr'; + protected $target_type = 'cat'; + protected $reference_type = 'catr'; - /** - * Constructor - * @param - * @return - */ - public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) - { - global $DIC; + /** + * Constructor + * @param + * @return + */ + public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) + { + global $DIC; - $this->access = $DIC->access(); - $this->help = $DIC["ilHelp"]; - parent::__construct($a_data, $a_id,true,false); - } + $this->access = $DIC->access(); + $this->help = $DIC["ilHelp"]; + parent::__construct($a_data, $a_id, true, false); + } - /** - * Execute command - * - * @access public - * - */ - public function executeCommand() - { - parent::executeCommand(); - } - - - /** - * get tabs - * - * @access public + /** + * Execute command + * + * @access public + * + */ + public function executeCommand() + { + parent::executeCommand(); + } + + + /** + * get tabs + * + * @access public * @param object tabs gui object - */ - public function getTabs() - { - $ilAccess = $this->access; - $ilHelp = $this->help; + */ + public function getTabs() + { + $ilAccess = $this->access; + $ilHelp = $this->help; - $ilHelp->setScreenIdComponent("catr"); - - if($ilAccess->checkAccess('write','',$this->object->getRefId())) - { - $this->tabs_gui->addTarget("settings", - $this->ctrl->getLinkTarget($this, "edit"), - array(), - ""); - } - if ($ilAccess->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'); - } - } - - /** - * Support for goto php - * - * @return void - * @static - */ - public static function _goto($a_target) - { - global $DIC; + $ilHelp->setScreenIdComponent("catr"); + + if ($ilAccess->checkAccess('write', '', $this->object->getRefId())) { + $this->tabs_gui->addTarget( + "settings", + $this->ctrl->getLinkTarget($this, "edit"), + array(), + "" + ); + } + if ($ilAccess->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' + ); + } + } + + /** + * Support for goto php + * + * @return void + * @static + */ + public static function _goto($a_target) + { + global $DIC; - $ilAccess = $DIC->access(); - $ilErr = $DIC["ilErr"]; - $lng = $DIC->language(); - - include_once('./Services/ContainerReference/classes/class.ilContainerReference.php'); - $target_ref_id = ilContainerReference::_lookupTargetRefId(ilObject::_lookupObjId($a_target)); - - include_once('./Modules/Category/classes/class.ilObjCategoryGUI.php'); - ilObjCategoryGUI::_goto($target_ref_id); - } + $ilAccess = $DIC->access(); + $ilErr = $DIC["ilErr"]; + $lng = $DIC->language(); + + include_once('./Services/ContainerReference/classes/class.ilContainerReference.php'); + $target_ref_id = ilContainerReference::_lookupTargetRefId(ilObject::_lookupObjId($a_target)); + + include_once('./Modules/Category/classes/class.ilObjCategoryGUI.php'); + ilObjCategoryGUI::_goto($target_ref_id); + } } -?> \ No newline at end of file diff --git a/Modules/CategoryReference/classes/class.ilObjCategoryReferenceListGUI.php b/Modules/CategoryReference/classes/class.ilObjCategoryReferenceListGUI.php index 74ab61007f83876c706af0e0348a2e7aab99c08d..541a3f24eff6ede275f307f0e83458ee0121dcb7 100644 --- a/Modules/CategoryReference/classes/class.ilObjCategoryReferenceListGUI.php +++ b/Modules/CategoryReference/classes/class.ilObjCategoryReferenceListGUI.php @@ -1,245 +1,234 @@ * @version $Id$ -* -* +* +* * @ingroup ModulesCategoryReference */ class ilObjCategoryReferenceListGUI extends ilObjCategoryListGUI { - protected $reference_obj_id = null; - protected $reference_ref_id = null; - - protected $deleted = false; - - /** - * Constructor - * - * @access public - * - */ - public function __construct() - { - global $DIC; + protected $reference_obj_id = null; + protected $reference_ref_id = null; + + protected $deleted = false; + + /** + * Constructor + * + * @access public + * + */ + public function __construct() + { + global $DIC; - $this->access = $DIC->access(); - $this->tree = $DIC->repositoryTree(); - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - $this->ctrl = $DIC->ctrl(); - parent::__construct(); - } - - public function getIconImageType() - { - return 'catr'; - } + $this->access = $DIC->access(); + $this->tree = $DIC->repositoryTree(); + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + $this->ctrl = $DIC->ctrl(); + parent::__construct(); + } + + public function getIconImageType() + { + return 'catr'; + } - /** - * @inheritdoc - */ - public function getTypeIcon() - { - $reference_obj_id = ilObject::_lookupObjId($this->getCommandId()); - return ilObject::_getIcon( - $reference_obj_id, - 'small' - ); - } + /** + * @inheritdoc + */ + public function getTypeIcon() + { + $reference_obj_id = ilObject::_lookupObjId($this->getCommandId()); + return ilObject::_getIcon( + $reference_obj_id, + 'small' + ); + } - /** - * get command id - * - * @access public - * @param - * @return - */ - public function getCommandId() - { - return $this->reference_ref_id; - } - - /** - * no activation for links - * @return type - */ - public function insertTimingsCommand() - { - return; - } - - /** - * initialisation - */ - function init() - { - $this->copy_enabled = true; - $this->static_link_enabled = false; - $this->delete_enabled = true; - $this->cut_enabled = true; - $this->subscribe_enabled = true; - $this->link_enabled = false; - $this->info_screen_enabled = true; - $this->type = "cat"; - $this->gui_class_name = "ilobjcategorygui"; - - include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDSubstitution.php'); - $this->substitutions = ilAdvancedMDSubstitution::_getInstanceByObjectType($this->type); - if($this->substitutions->isActive()) - { - $this->substitutions_enabled = true; - } - } - - - - /** - * inititialize new item - * Course reference inits the course item - * - * @param int $a_ref_id reference id - * @param int $a_obj_id object id - * @param string $a_title title - * @param string $a_description description - */ - function initItem($a_ref_id, $a_obj_id, $a_title = "", $a_description = "") - { - $ilAccess = $this->access; - $tree = $this->tree; - - $this->reference_ref_id = $a_ref_id; - $this->reference_obj_id = $a_obj_id; - - include_once('./Services/ContainerReference/classes/class.ilContainerReference.php'); - $target_obj_id = ilContainerReference::_lookupTargetId($a_obj_id); - - $target_ref_ids = ilObject::_getAllReferences($target_obj_id); - $target_ref_id = current($target_ref_ids); - $target_title = ilContainerReference::_lookupTitle($a_obj_id); - $target_description = ilObject::_lookupDescription($target_obj_id); - - $this->deleted = $tree->isDeleted($target_ref_id); - - - - parent::initItem($target_ref_id, $target_obj_id,$target_title,$target_description); + /** + * get command id + * + * @access public + * @param + * @return + */ + public function getCommandId() + { + return $this->reference_ref_id; + } + + /** + * no activation for links + * @return type + */ + public function insertTimingsCommand() + { + return; + } + + /** + * initialisation + */ + public function init() + { + $this->copy_enabled = true; + $this->static_link_enabled = false; + $this->delete_enabled = true; + $this->cut_enabled = true; + $this->subscribe_enabled = true; + $this->link_enabled = false; + $this->info_screen_enabled = true; + $this->type = "cat"; + $this->gui_class_name = "ilobjcategorygui"; + + include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDSubstitution.php'); + $this->substitutions = ilAdvancedMDSubstitution::_getInstanceByObjectType($this->type); + if ($this->substitutions->isActive()) { + $this->substitutions_enabled = true; + } + } + + + + /** + * inititialize new item + * Course reference inits the course item + * + * @param int $a_ref_id reference id + * @param int $a_obj_id object id + * @param string $a_title title + * @param string $a_description description + */ + public function initItem($a_ref_id, $a_obj_id, $a_title = "", $a_description = "") + { + $ilAccess = $this->access; + $tree = $this->tree; + + $this->reference_ref_id = $a_ref_id; + $this->reference_obj_id = $a_obj_id; + + include_once('./Services/ContainerReference/classes/class.ilContainerReference.php'); + $target_obj_id = ilContainerReference::_lookupTargetId($a_obj_id); + + $target_ref_ids = ilObject::_getAllReferences($target_obj_id); + $target_ref_id = current($target_ref_ids); + $target_title = ilContainerReference::_lookupTitle($a_obj_id); + $target_description = ilObject::_lookupDescription($target_obj_id); + + $this->deleted = $tree->isDeleted($target_ref_id); + + + + parent::initItem($target_ref_id, $target_obj_id, $target_title, $target_description); - // general commands array - include_once('./Modules/CategoryReference/classes/class.ilObjCategoryReferenceAccess.php'); - $this->commands = ilObjCategoryReferenceAccess::_getCommands($this->reference_ref_id); + // general commands array + include_once('./Modules/CategoryReference/classes/class.ilObjCategoryReferenceAccess.php'); + $this->commands = ilObjCategoryReferenceAccess::_getCommands($this->reference_ref_id); - if($ilAccess->checkAccess('write','',$this->reference_ref_id) or $this->deleted) - { - $this->info_screen_enabled = false; - } - else - { - $this->info_screen_enabled = true; - } - } - - - function getProperties() - { - $lng = $this->lng; - $ilUser = $this->user; - $tree = $this->tree; + if ($ilAccess->checkAccess('write', '', $this->reference_ref_id) or $this->deleted) { + $this->info_screen_enabled = false; + } else { + $this->info_screen_enabled = true; + } + } + + + public function getProperties() + { + $lng = $this->lng; + $ilUser = $this->user; + $tree = $this->tree; - $props = parent::getProperties(); - - // offline - if($tree->isDeleted($this->ref_id)) - { - $props[] = array("alert" => true, "property" => $lng->txt("status"), - "value" => $lng->txt("reference_deleted")); - } + $props = parent::getProperties(); + + // offline + if ($tree->isDeleted($this->ref_id)) { + $props[] = array("alert" => true, "property" => $lng->txt("status"), + "value" => $lng->txt("reference_deleted")); + } - return $props ? $props : array(); - } - - /** - * - * @param - * @return - */ - public function checkCommandAccess($a_permission,$a_cmd,$a_ref_id,$a_type,$a_obj_id="") - { + return $props ? $props : array(); + } + + /** + * + * @param + * @return + */ + public function checkCommandAccess($a_permission, $a_cmd, $a_ref_id, $a_type, $a_obj_id="") + { - // Check edit reference against reference edit permission - switch($a_cmd) - { - case 'editReference': - return parent::checkCommandAccess($a_permission, $a_cmd, $this->getCommandId(), $a_type, $a_obj_id); - } + // Check edit reference against reference edit permission + switch ($a_cmd) { + case 'editReference': + return parent::checkCommandAccess($a_permission, $a_cmd, $this->getCommandId(), $a_type, $a_obj_id); + } - switch($a_permission) - { - case 'copy': - case 'delete': - // check against target ref_id - return parent::checkCommandAccess($a_permission, $a_cmd, $this->getCommandId(), $a_type, $a_obj_id); - - default: - // check against reference - return parent::checkCommandAccess($a_permission, $a_cmd, $a_ref_id, $a_type, $a_obj_id); - } - } - - /** - * get command link - * - * @access public - * @param string $a_cmd - * @return - */ - public function getCommandLink($a_cmd) - { - $ilCtrl = $this->ctrl; - - switch($a_cmd) - { - case 'editReference': - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $this->getCommandId()); - $cmd_link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", $a_cmd); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - return $cmd_link; - - default: - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $this->ref_id); - $cmd_link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", $a_cmd); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - return $cmd_link; - } - } - + switch ($a_permission) { + case 'copy': + case 'delete': + // check against target ref_id + return parent::checkCommandAccess($a_permission, $a_cmd, $this->getCommandId(), $a_type, $a_obj_id); + + default: + // check against reference + return parent::checkCommandAccess($a_permission, $a_cmd, $a_ref_id, $a_type, $a_obj_id); + } + } + + /** + * get command link + * + * @access public + * @param string $a_cmd + * @return + */ + public function getCommandLink($a_cmd) + { + $ilCtrl = $this->ctrl; + + switch ($a_cmd) { + case 'editReference': + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $this->getCommandId()); + $cmd_link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", $a_cmd); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + return $cmd_link; + default: + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $this->ref_id); + $cmd_link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", $a_cmd); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + return $cmd_link; + } + } } -?> \ No newline at end of file diff --git a/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeBlogGUI.php b/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeBlogGUI.php index b97cdbc791c339157f8c59f74a690fbe8c245a11..db3896774c6fac2ccaa922e822038cc9b3fc8fb4 100644 --- a/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeBlogGUI.php +++ b/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeBlogGUI.php @@ -12,38 +12,34 @@ include_once("./Modules/Exercise/AssignmentTypes/GUI/traits/trait.ilExAssignment */ class ilExAssTypeBlogGUI implements ilExAssignmentTypeGUIInterface { - use ilExAssignmentTypeGUIBase; - - /** - * @inheritdoc - */ - function addEditFormCustomProperties(ilPropertyFormGUI $form) - { - - } - - /** - * @inheritdoc - */ - function importFormToAssignment(ilExAssignment $ass , ilPropertyFormGUI $form) - { - - } - - /** - * @inheritdoc - */ - function getFormValuesArray(ilExAssignment $ass) - { - return []; - } - - /** - * @inheritdoc - */ - function getOverviewContent(ilInfoScreenGUI $a_info, ilExSubmission $a_submission) - { - - } - -} \ No newline at end of file + use ilExAssignmentTypeGUIBase; + + /** + * @inheritdoc + */ + public function addEditFormCustomProperties(ilPropertyFormGUI $form) + { + } + + /** + * @inheritdoc + */ + public function importFormToAssignment(ilExAssignment $ass, ilPropertyFormGUI $form) + { + } + + /** + * @inheritdoc + */ + public function getFormValuesArray(ilExAssignment $ass) + { + return []; + } + + /** + * @inheritdoc + */ + public function getOverviewContent(ilInfoScreenGUI $a_info, ilExSubmission $a_submission) + { + } +} diff --git a/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypePortfolioGUI.php b/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypePortfolioGUI.php index 11ef4e1c4835e0a514660814563d49b91fa5a6b1..c63b234be6dc87313fe0af328d0a0066e7cba1c6 100644 --- a/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypePortfolioGUI.php +++ b/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypePortfolioGUI.php @@ -12,81 +12,77 @@ include_once("./Modules/Exercise/AssignmentTypes/GUI/traits/trait.ilExAssignment */ class ilExAssTypePortfolioGUI implements ilExAssignmentTypeGUIInterface { - use ilExAssignmentTypeGUIBase; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - } - - /** - * @inheritdoc - */ - function addEditFormCustomProperties(ilPropertyFormGUI $form) - { - $lng = $this->lng; - - $rd_template = new ilRadioGroupInputGUI($lng->txt("exc_template"), "template"); - $rd_template->setRequired(true); - $radio_no_template = new ilRadioOption($lng->txt("exc_without_template"), 0, $lng->txt("exc_without_template_info", "without_template_info")); - $radio_with_template = new ilRadioOption($lng->txt("exc_with_template"), 1 , $lng->txt("exc_with_template_info", "with_template_info")); - - include_once "Services/Form/classes/class.ilRepositorySelector2InputGUI.php"; - $repo = new ilRepositorySelector2InputGUI($lng->txt("exc_portfolio_template"), "template_id"); - $repo->setRequired(true); - $repo->getExplorerGUI()->setSelectableTypes(array("prtt")); - $repo->getExplorerGUI()->setTypeWhiteList(array("root", "prtt", "cat", "crs", "grp")); - $radio_with_template->addSubItem($repo); - - $rd_template->addOption($radio_no_template); - $rd_template->addOption($radio_with_template); - $form->addItem($rd_template); - } - - /** - * @inheritdoc - */ - function importFormToAssignment(ilExAssignment $ass , ilPropertyFormGUI $form) - { - $ass->setPortfolioTemplateId(0); - if($form->getInput("template_id") && $form->getInput("template")) - { - $ass->setPortfolioTemplateId($form->getInput("template_id")); - } - } - - /** - * @inheritdoc - */ - function getFormValuesArray(ilExAssignment $ass) - { - $values = []; - - if ($ass->getPortfolioTemplateId() > 0) - { - $values["template_id"] = $ass->getPortfolioTemplateId(); - $values["template"] = 1; - } - - return $values; - } - - /** - * @inheritdoc - */ - function getOverviewContent(ilInfoScreenGUI $a_info, ilExSubmission $a_submission) - { - - } - -} \ No newline at end of file + use ilExAssignmentTypeGUIBase; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + } + + /** + * @inheritdoc + */ + public function addEditFormCustomProperties(ilPropertyFormGUI $form) + { + $lng = $this->lng; + + $rd_template = new ilRadioGroupInputGUI($lng->txt("exc_template"), "template"); + $rd_template->setRequired(true); + $radio_no_template = new ilRadioOption($lng->txt("exc_without_template"), 0, $lng->txt("exc_without_template_info", "without_template_info")); + $radio_with_template = new ilRadioOption($lng->txt("exc_with_template"), 1, $lng->txt("exc_with_template_info", "with_template_info")); + + include_once "Services/Form/classes/class.ilRepositorySelector2InputGUI.php"; + $repo = new ilRepositorySelector2InputGUI($lng->txt("exc_portfolio_template"), "template_id"); + $repo->setRequired(true); + $repo->getExplorerGUI()->setSelectableTypes(array("prtt")); + $repo->getExplorerGUI()->setTypeWhiteList(array("root", "prtt", "cat", "crs", "grp")); + $radio_with_template->addSubItem($repo); + + $rd_template->addOption($radio_no_template); + $rd_template->addOption($radio_with_template); + $form->addItem($rd_template); + } + + /** + * @inheritdoc + */ + public function importFormToAssignment(ilExAssignment $ass, ilPropertyFormGUI $form) + { + $ass->setPortfolioTemplateId(0); + if ($form->getInput("template_id") && $form->getInput("template")) { + $ass->setPortfolioTemplateId($form->getInput("template_id")); + } + } + + /** + * @inheritdoc + */ + public function getFormValuesArray(ilExAssignment $ass) + { + $values = []; + + if ($ass->getPortfolioTemplateId() > 0) { + $values["template_id"] = $ass->getPortfolioTemplateId(); + $values["template"] = 1; + } + + return $values; + } + + /** + * @inheritdoc + */ + public function getOverviewContent(ilInfoScreenGUI $a_info, ilExSubmission $a_submission) + { + } +} diff --git a/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeTextGUI.php b/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeTextGUI.php index 8942db7cd03b3bb5eb82ab8f791c0ea5f966ee38..5a05c0909b60e8b0495ee865ee0bfc3cc52aa3e8 100644 --- a/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeTextGUI.php +++ b/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeTextGUI.php @@ -12,92 +12,86 @@ include_once("./Modules/Exercise/AssignmentTypes/GUI/traits/trait.ilExAssignment */ class ilExAssTypeTextGUI implements ilExAssignmentTypeGUIInterface { - use ilExAssignmentTypeGUIBase; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - } - - /** - * @inheritdoc - */ - function addEditFormCustomProperties(ilPropertyFormGUI $form) - { - $lng = $this->lng; - - $rb_limit_chars = new ilCheckboxInputGUI($lng->txt("exc_limit_characters"),"limit_characters"); - - $min_char_limit = new ilNumberInputGUI($lng->txt("exc_min_char_limit"), "min_char_limit"); - $min_char_limit->allowDecimals(false); - $min_char_limit->setMinValue(0); - $min_char_limit->setSize(3); - - $max_char_limit = new ilNumberInputGUI($lng->txt("exc_max_char_limit"), "max_char_limit"); - $max_char_limit->allowDecimals(false); - $max_char_limit->setMinValue((int) $_POST['min_char_limit'] + 1); - - $max_char_limit->setSize(3); - - $rb_limit_chars->addSubItem($min_char_limit); - $rb_limit_chars->addSubItem($max_char_limit); - - $form->addItem($rb_limit_chars); - } - - /** - * @inheritdoc - */ - function importFormToAssignment(ilExAssignment $a_ass , ilPropertyFormGUI $a_form) - { - $a_ass->setMaxCharLimit(0); - $a_ass->setMinCharLimit(0); - if($a_form->getInput("limit_characters") && $a_form->getInput("max_char_limit")) - { - $a_ass->setMaxCharLimit($a_form->getInput("max_char_limit")); - } - if($a_form->getInput("limit_characters") && $a_form->getInput("min_char_limit")) - { - $a_ass->setMinCharLimit($a_form->getInput("min_char_limit")); - } - } - - /** - * @inheritdoc - */ - function getFormValuesArray(ilExAssignment $ass) - { - $values = []; - if($ass->getMinCharLimit()) - { - $values['limit_characters'] = 1; - $values['min_char_limit'] = $ass->getMinCharLimit(); - } - if($ass->getMaxCharLimit()) - { - $values['limit_characters'] = 1; - $values['max_char_limit'] = $ass->getMaxCharLimit(); - } - - return $values; - } - - /** - * @inheritdoc - */ - function getOverviewContent(ilInfoScreenGUI $a_info, ilExSubmission $a_submission) - { - - } - -} \ No newline at end of file + use ilExAssignmentTypeGUIBase; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + } + + /** + * @inheritdoc + */ + public function addEditFormCustomProperties(ilPropertyFormGUI $form) + { + $lng = $this->lng; + + $rb_limit_chars = new ilCheckboxInputGUI($lng->txt("exc_limit_characters"), "limit_characters"); + + $min_char_limit = new ilNumberInputGUI($lng->txt("exc_min_char_limit"), "min_char_limit"); + $min_char_limit->allowDecimals(false); + $min_char_limit->setMinValue(0); + $min_char_limit->setSize(3); + + $max_char_limit = new ilNumberInputGUI($lng->txt("exc_max_char_limit"), "max_char_limit"); + $max_char_limit->allowDecimals(false); + $max_char_limit->setMinValue((int) $_POST['min_char_limit'] + 1); + + $max_char_limit->setSize(3); + + $rb_limit_chars->addSubItem($min_char_limit); + $rb_limit_chars->addSubItem($max_char_limit); + + $form->addItem($rb_limit_chars); + } + + /** + * @inheritdoc + */ + public function importFormToAssignment(ilExAssignment $a_ass, ilPropertyFormGUI $a_form) + { + $a_ass->setMaxCharLimit(0); + $a_ass->setMinCharLimit(0); + if ($a_form->getInput("limit_characters") && $a_form->getInput("max_char_limit")) { + $a_ass->setMaxCharLimit($a_form->getInput("max_char_limit")); + } + if ($a_form->getInput("limit_characters") && $a_form->getInput("min_char_limit")) { + $a_ass->setMinCharLimit($a_form->getInput("min_char_limit")); + } + } + + /** + * @inheritdoc + */ + public function getFormValuesArray(ilExAssignment $ass) + { + $values = []; + if ($ass->getMinCharLimit()) { + $values['limit_characters'] = 1; + $values['min_char_limit'] = $ass->getMinCharLimit(); + } + if ($ass->getMaxCharLimit()) { + $values['limit_characters'] = 1; + $values['max_char_limit'] = $ass->getMaxCharLimit(); + } + + return $values; + } + + /** + * @inheritdoc + */ + public function getOverviewContent(ilInfoScreenGUI $a_info, ilExSubmission $a_submission) + { + } +} diff --git a/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeUploadGUI.php b/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeUploadGUI.php index 60e7bcb09d127e67c8299d7f637cb51a1ea45733..024ae0d871950fb0235bad3433337e24c1abaa1c 100644 --- a/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeUploadGUI.php +++ b/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeUploadGUI.php @@ -12,38 +12,34 @@ include_once("./Modules/Exercise/AssignmentTypes/GUI/traits/trait.ilExAssignment */ class ilExAssTypeUploadGUI implements ilExAssignmentTypeGUIInterface { - use ilExAssignmentTypeGUIBase; - - /** - * @inheritdoc - */ - function addEditFormCustomProperties(ilPropertyFormGUI $form) - { - - } - - /** - * @inheritdoc - */ - function importFormToAssignment(ilExAssignment $ass , ilPropertyFormGUI $form) - { - - } - - /** - * @inheritdoc - */ - function getFormValuesArray(ilExAssignment $ass) - { - return []; - } - - /** - * @inheritdoc - */ - function getOverviewContent(ilInfoScreenGUI $a_info, ilExSubmission $a_submission) - { - - } - -} \ No newline at end of file + use ilExAssignmentTypeGUIBase; + + /** + * @inheritdoc + */ + public function addEditFormCustomProperties(ilPropertyFormGUI $form) + { + } + + /** + * @inheritdoc + */ + public function importFormToAssignment(ilExAssignment $ass, ilPropertyFormGUI $form) + { + } + + /** + * @inheritdoc + */ + public function getFormValuesArray(ilExAssignment $ass) + { + return []; + } + + /** + * @inheritdoc + */ + public function getOverviewContent(ilInfoScreenGUI $a_info, ilExSubmission $a_submission) + { + } +} diff --git a/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeUploadTeamGUI.php b/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeUploadTeamGUI.php index 7d15b83a0012d2f206130b446586b26acbb0d864..d0c92d0d8718de6db0df6a7778b99cadb2d9f2f0 100644 --- a/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeUploadTeamGUI.php +++ b/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeUploadTeamGUI.php @@ -12,38 +12,34 @@ include_once("./Modules/Exercise/AssignmentTypes/GUI/traits/trait.ilExAssignment */ class ilExAssTypeUploadTeamGUI implements ilExAssignmentTypeGUIInterface { - use ilExAssignmentTypeGUIBase; - - /** - * @inheritdoc - */ - function addEditFormCustomProperties(ilPropertyFormGUI $form) - { - - } - - /** - * @inheritdoc - */ - function importFormToAssignment(ilExAssignment $ass , ilPropertyFormGUI $form) - { - - } - - /** - * @inheritdoc - */ - function getFormValuesArray(ilExAssignment $ass) - { - return []; - } - - /** - * @inheritdoc - */ - function getOverviewContent(ilInfoScreenGUI $a_info, ilExSubmission $a_submission) - { - - } - -} \ No newline at end of file + use ilExAssignmentTypeGUIBase; + + /** + * @inheritdoc + */ + public function addEditFormCustomProperties(ilPropertyFormGUI $form) + { + } + + /** + * @inheritdoc + */ + public function importFormToAssignment(ilExAssignment $ass, ilPropertyFormGUI $form) + { + } + + /** + * @inheritdoc + */ + public function getFormValuesArray(ilExAssignment $ass) + { + return []; + } + + /** + * @inheritdoc + */ + public function getOverviewContent(ilInfoScreenGUI $a_info, ilExSubmission $a_submission) + { + } +} diff --git a/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeWikiTeamGUI.php b/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeWikiTeamGUI.php index b89bd7cc581b7aa1e2c08135e93116922294c0f9..3f54a20e6ac331faaeb13a7cf5d4817339583710 100644 --- a/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeWikiTeamGUI.php +++ b/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeWikiTeamGUI.php @@ -13,304 +13,284 @@ include_once("./Modules/Exercise/AssignmentTypes/GUI/traits/trait.ilExAssignment */ class ilExAssTypeWikiTeamGUI implements ilExAssignmentTypeGUIInterface { - use ilExAssignmentTypeGUIBase; - - const MODE_OVERVIEW = "overview"; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTree - */ - protected $tree; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $this->tree = $DIC->repositoryTree(); - $this->access = $DIC->access(); - } - - /** - * Execute command - */ - function executeCommand() - { - $ctrl = $this->ctrl; - - $next_class = $ctrl->getNextClass($this); - $cmd = $ctrl->getCmd(); - - switch ($next_class) - { - default: - if (in_array($cmd, array("createWiki"))) - { - $this->$cmd(); - } - } - } - - /** - * @inheritdoc - */ - public function addEditFormCustomProperties(ilPropertyFormGUI $form) - { - $lng = $this->lng; - - // template - $rd_template = new ilRadioGroupInputGUI($lng->txt("exc_template"), "template"); - $rd_template->setRequired(true); - $radio_no_template = new ilRadioOption($lng->txt("exc_without_wiki_template"), 0, $lng->txt("exc_without_wiki_template_info")); - $radio_with_template = new ilRadioOption($lng->txt("exc_with_wiki_template"), 1 , $lng->txt("exc_with_wiki_template_info")); - - include_once "Services/Form/classes/class.ilRepositorySelector2InputGUI.php"; - $repo = new ilRepositorySelector2InputGUI($lng->txt("wiki_exc_template"), "template_ref_id"); - $repo->setRequired(true); - $repo->getExplorerGUI()->setSelectableTypes(array("wiki")); - $repo->getExplorerGUI()->setTypeWhiteList(array("root", "wiki", "cat", "crs", "grp", "fold")); - $radio_with_template->addSubItem($repo); - - $rd_template->addOption($radio_no_template); - $rd_template->addOption($radio_with_template); - $form->addItem($rd_template); - - // container - include_once "Services/Form/classes/class.ilRepositorySelector2InputGUI.php"; - $cont = new ilRepositorySelector2InputGUI($lng->txt("exc_wiki_container"), "container_ref_id"); - $cont->setRequired(true); - $cont->setInfo($lng->txt("exc_wiki_container_info")); - $cont->getExplorerGUI()->setSelectableTypes(array("cat", "crs", "grp", "fold")); - $cont->getExplorerGUI()->setTypeWhiteList(array("root", "cat", "crs", "grp", "fold")); - $form->addItem($cont); - } - - /** - * @inheritdoc - */ - public function importFormToAssignment(ilExAssignment $ass , ilPropertyFormGUI $form) - { - include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssWikiTeamAR.php"); - $ar = new ilExAssWikiTeamAR(); - $ar->setId($ass->getId()); - $ar->setTemplateRefId(0); - if($form->getInput("template_ref_id") && $form->getInput("template")) - { - $ar->setTemplateRefId($form->getInput("template_ref_id")); - } - $ar->setContainerRefId($form->getInput("container_ref_id")); - $ar->save(); - } - - /** - * @inheritdoc - */ - public function getFormValuesArray(ilExAssignment $ass) - { - $values = []; - - include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssWikiTeamAR.php"); - $ar = new ilExAssWikiTeamAR($ass->getId()); - - if ($ar->getTemplateRefId() > 0) - { - $values["template_ref_id"] = $ar->getTemplateRefId(); - $values["template"] = 1; - } - $values["container_ref_id"] = $ar->getContainerRefId(); - - return $values; - } - - /** - * @inheritdoc - */ - public function getOverviewContent(ilInfoScreenGUI $a_info, ilExSubmission $a_submission) - { - $this->ctrl->getHTML($this, array("mode" => self::MODE_OVERVIEW, "info" => $a_info, "submission" => $a_submission)); - } - - /** - * Get HTML - * - * @param array $par parameter - */ - public function getHTML($par) - { - switch ($par["mode"]) - { - case self::MODE_OVERVIEW: - $this->renderOverviewContent($par["info"], $par["submission"]); - break; - } - } - - /** - * Render overview content - * - * @param ilInfoScreenGUI $a_info - * @param ilExSubmission $a_submission - */ - protected function renderOverviewContent(ilInfoScreenGUI $a_info, ilExSubmission $a_submission) - { - $lng = $this->lng; - $ctrl = $this->ctrl; - - include_once "Modules/Wiki/classes/class.ilObjWiki.php"; - - $files_str = ""; - $valid_wiki = false; - - $team_members = $a_submission->getTeam()->getMembers(); - $team_available = (sizeof($team_members)); - - $selected_wiki = $a_submission->getSelectedObject(); - if($selected_wiki) - { - $wiki_ref_id = (int)$selected_wiki["filetitle"]; - - // #11746 - if(ilObject::_exists($wiki_ref_id, true, "wiki") && $this->tree->isInTree($wiki_ref_id)) - { - $wiki = new ilObjWiki($wiki_ref_id); - if($wiki->getTitle()) - { - // #10116 / #12791 - $ctrl->setParameterByClass("ilobjwikigui", "ref_id", $wiki_ref_id); - $wiki_link = ilLink::_getLink($wiki_ref_id); - $files_str = ''.$wiki->getTitle().''; - $valid_wiki = true; - } - } - // remove invalid resource if no upload yet (see download below) - else if(substr($selected_wiki["filename"], -1) == "/") - { - // #16887 - $a_submission->deleteResourceObject($selected_wiki["returned_id"]); - } - } - if($a_submission->canSubmit()) - { - if(!$valid_wiki && $team_available) - { - $button = ilLinkButton::getInstance(); - $button->setCaption("exc_create_wiki"); - $button->setUrl($ctrl->getLinkTarget($this,"createWiki")); - - $files_str .= "".$button->render(); - } - } - if($files_str) - { - $a_info->addProperty($lng->txt("exc_ass_team_wiki"), $files_str); - } - if($a_submission->hasSubmitted()) - { - $ctrl->setParameterByClass("ilExSubmissionFileGUI", "delivered", $selected_wiki["returned_id"]); - $dl_link =$ctrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExSubmissionFileGUI"), "download"); - $ctrl->setParameterByClass("ilExSubmissionFileGUI", "delivered", ""); - - $button = ilLinkButton::getInstance(); - $button->setCaption("download"); - $button->setUrl($dl_link); - - $a_info->addProperty($lng->txt("exc_files_returned"), $button->render()); - } - } - - - /** - * Create wiki for assignment - */ - protected function createWiki() - { - $access = $this->access; - $lng = $this->lng; - - include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssWikiTeamAR.php"); - $ar = new ilExAssWikiTeamAR($this->submission->getAssignment()->getId()); - $template_ref_id = $ar->getTemplateRefId(); - $container_ref_id = $ar->getContainerRefId(); - - // @todo: move checks to central place - // check if team exists - $team_members = $this->submission->getTeam()->getMembers(); - $team_available = (sizeof($team_members)); - if (!$team_available) - { - $lng->loadLanguageModule("exc"); - ilUtil::sendInfo($lng->txt("exc_team_needed_first"), true); - $this->ctrl->returnToParent($this); - } - - // check if submission is possible - if (!$this->submission->canSubmit()) - { - $lng->loadLanguageModule("exc"); - ilUtil::sendInfo($lng->txt("exercise_time_over"), true); - $this->ctrl->returnToParent($this); - } - - // check create permission of exercise owner - if (!$access->checkAccessOfUser($this->exercise->getOwner(),"create", "", $container_ref_id, "wiki")) - { - $lng->loadLanguageModule("exc"); - ilUtil::sendInfo($lng->txt("exc_owner_has_no_permission_to_create_wiki"), true); - $this->ctrl->returnToParent($this); - } - - if ($template_ref_id > 0 && ilObject::_exists($template_ref_id, true, "wiki")) - { - $template_wiki = new ilObjWiki($template_ref_id); - $wiki = $template_wiki->cloneObject($container_ref_id); - $wiki->setTitle($this->exercise->getTitle() . " - " . $this->submission->getAssignment()->getTitle()); - } - else - { - include_once "Modules/Wiki/classes/class.ilObjWiki.php"; - $wiki = new ilObjWiki(); - $wiki->setTitle($this->exercise->getTitle() . " - " . $this->submission->getAssignment()->getTitle()); - $wiki->create(); - $wiki->setStartPage($this->submission->getAssignment()->getTitle()); - - $wiki->createReference(); - $wiki->putInTree($container_ref_id); - $wiki->setPermissions($container_ref_id); - } - - $wiki->setOwner($this->exercise->getOwner()); - $wiki->setOnline(true); - $wiki->update(); - $wiki->updateOwner(); - - $this->submission->deleteAllFiles(); - //$this->handleRemovedUpload(); - - $this->submission->addResourceObject($wiki->getRefId()); - - $lng->loadLanguageModule("wiki"); - ilUtil::sendSuccess($lng->txt("wiki_exc_wiki_created"), true); - $this->ctrl->returnToParent($this); - } - -} \ No newline at end of file + use ilExAssignmentTypeGUIBase; + + const MODE_OVERVIEW = "overview"; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTree + */ + protected $tree; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->tree = $DIC->repositoryTree(); + $this->access = $DIC->access(); + } + + /** + * Execute command + */ + public function executeCommand() + { + $ctrl = $this->ctrl; + + $next_class = $ctrl->getNextClass($this); + $cmd = $ctrl->getCmd(); + + switch ($next_class) { + default: + if (in_array($cmd, array("createWiki"))) { + $this->$cmd(); + } + } + } + + /** + * @inheritdoc + */ + public function addEditFormCustomProperties(ilPropertyFormGUI $form) + { + $lng = $this->lng; + + // template + $rd_template = new ilRadioGroupInputGUI($lng->txt("exc_template"), "template"); + $rd_template->setRequired(true); + $radio_no_template = new ilRadioOption($lng->txt("exc_without_wiki_template"), 0, $lng->txt("exc_without_wiki_template_info")); + $radio_with_template = new ilRadioOption($lng->txt("exc_with_wiki_template"), 1, $lng->txt("exc_with_wiki_template_info")); + + include_once "Services/Form/classes/class.ilRepositorySelector2InputGUI.php"; + $repo = new ilRepositorySelector2InputGUI($lng->txt("wiki_exc_template"), "template_ref_id"); + $repo->setRequired(true); + $repo->getExplorerGUI()->setSelectableTypes(array("wiki")); + $repo->getExplorerGUI()->setTypeWhiteList(array("root", "wiki", "cat", "crs", "grp", "fold")); + $radio_with_template->addSubItem($repo); + + $rd_template->addOption($radio_no_template); + $rd_template->addOption($radio_with_template); + $form->addItem($rd_template); + + // container + include_once "Services/Form/classes/class.ilRepositorySelector2InputGUI.php"; + $cont = new ilRepositorySelector2InputGUI($lng->txt("exc_wiki_container"), "container_ref_id"); + $cont->setRequired(true); + $cont->setInfo($lng->txt("exc_wiki_container_info")); + $cont->getExplorerGUI()->setSelectableTypes(array("cat", "crs", "grp", "fold")); + $cont->getExplorerGUI()->setTypeWhiteList(array("root", "cat", "crs", "grp", "fold")); + $form->addItem($cont); + } + + /** + * @inheritdoc + */ + public function importFormToAssignment(ilExAssignment $ass, ilPropertyFormGUI $form) + { + include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssWikiTeamAR.php"); + $ar = new ilExAssWikiTeamAR(); + $ar->setId($ass->getId()); + $ar->setTemplateRefId(0); + if ($form->getInput("template_ref_id") && $form->getInput("template")) { + $ar->setTemplateRefId($form->getInput("template_ref_id")); + } + $ar->setContainerRefId($form->getInput("container_ref_id")); + $ar->save(); + } + + /** + * @inheritdoc + */ + public function getFormValuesArray(ilExAssignment $ass) + { + $values = []; + + include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssWikiTeamAR.php"); + $ar = new ilExAssWikiTeamAR($ass->getId()); + + if ($ar->getTemplateRefId() > 0) { + $values["template_ref_id"] = $ar->getTemplateRefId(); + $values["template"] = 1; + } + $values["container_ref_id"] = $ar->getContainerRefId(); + + return $values; + } + + /** + * @inheritdoc + */ + public function getOverviewContent(ilInfoScreenGUI $a_info, ilExSubmission $a_submission) + { + $this->ctrl->getHTML($this, array("mode" => self::MODE_OVERVIEW, "info" => $a_info, "submission" => $a_submission)); + } + + /** + * Get HTML + * + * @param array $par parameter + */ + public function getHTML($par) + { + switch ($par["mode"]) { + case self::MODE_OVERVIEW: + $this->renderOverviewContent($par["info"], $par["submission"]); + break; + } + } + + /** + * Render overview content + * + * @param ilInfoScreenGUI $a_info + * @param ilExSubmission $a_submission + */ + protected function renderOverviewContent(ilInfoScreenGUI $a_info, ilExSubmission $a_submission) + { + $lng = $this->lng; + $ctrl = $this->ctrl; + + include_once "Modules/Wiki/classes/class.ilObjWiki.php"; + + $files_str = ""; + $valid_wiki = false; + + $team_members = $a_submission->getTeam()->getMembers(); + $team_available = (sizeof($team_members)); + + $selected_wiki = $a_submission->getSelectedObject(); + if ($selected_wiki) { + $wiki_ref_id = (int) $selected_wiki["filetitle"]; + + // #11746 + if (ilObject::_exists($wiki_ref_id, true, "wiki") && $this->tree->isInTree($wiki_ref_id)) { + $wiki = new ilObjWiki($wiki_ref_id); + if ($wiki->getTitle()) { + // #10116 / #12791 + $ctrl->setParameterByClass("ilobjwikigui", "ref_id", $wiki_ref_id); + $wiki_link = ilLink::_getLink($wiki_ref_id); + $files_str = '' . $wiki->getTitle() . ''; + $valid_wiki = true; + } + } + // remove invalid resource if no upload yet (see download below) + elseif (substr($selected_wiki["filename"], -1) == "/") { + // #16887 + $a_submission->deleteResourceObject($selected_wiki["returned_id"]); + } + } + if ($a_submission->canSubmit()) { + if (!$valid_wiki && $team_available) { + $button = ilLinkButton::getInstance(); + $button->setCaption("exc_create_wiki"); + $button->setUrl($ctrl->getLinkTarget($this, "createWiki")); + + $files_str .= "" . $button->render(); + } + } + if ($files_str) { + $a_info->addProperty($lng->txt("exc_ass_team_wiki"), $files_str); + } + if ($a_submission->hasSubmitted()) { + $ctrl->setParameterByClass("ilExSubmissionFileGUI", "delivered", $selected_wiki["returned_id"]); + $dl_link =$ctrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExSubmissionFileGUI"), "download"); + $ctrl->setParameterByClass("ilExSubmissionFileGUI", "delivered", ""); + + $button = ilLinkButton::getInstance(); + $button->setCaption("download"); + $button->setUrl($dl_link); + + $a_info->addProperty($lng->txt("exc_files_returned"), $button->render()); + } + } + + + /** + * Create wiki for assignment + */ + protected function createWiki() + { + $access = $this->access; + $lng = $this->lng; + + include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssWikiTeamAR.php"); + $ar = new ilExAssWikiTeamAR($this->submission->getAssignment()->getId()); + $template_ref_id = $ar->getTemplateRefId(); + $container_ref_id = $ar->getContainerRefId(); + + // @todo: move checks to central place + // check if team exists + $team_members = $this->submission->getTeam()->getMembers(); + $team_available = (sizeof($team_members)); + if (!$team_available) { + $lng->loadLanguageModule("exc"); + ilUtil::sendInfo($lng->txt("exc_team_needed_first"), true); + $this->ctrl->returnToParent($this); + } + + // check if submission is possible + if (!$this->submission->canSubmit()) { + $lng->loadLanguageModule("exc"); + ilUtil::sendInfo($lng->txt("exercise_time_over"), true); + $this->ctrl->returnToParent($this); + } + + // check create permission of exercise owner + if (!$access->checkAccessOfUser($this->exercise->getOwner(), "create", "", $container_ref_id, "wiki")) { + $lng->loadLanguageModule("exc"); + ilUtil::sendInfo($lng->txt("exc_owner_has_no_permission_to_create_wiki"), true); + $this->ctrl->returnToParent($this); + } + + if ($template_ref_id > 0 && ilObject::_exists($template_ref_id, true, "wiki")) { + $template_wiki = new ilObjWiki($template_ref_id); + $wiki = $template_wiki->cloneObject($container_ref_id); + $wiki->setTitle($this->exercise->getTitle() . " - " . $this->submission->getAssignment()->getTitle()); + } else { + include_once "Modules/Wiki/classes/class.ilObjWiki.php"; + $wiki = new ilObjWiki(); + $wiki->setTitle($this->exercise->getTitle() . " - " . $this->submission->getAssignment()->getTitle()); + $wiki->create(); + $wiki->setStartPage($this->submission->getAssignment()->getTitle()); + + $wiki->createReference(); + $wiki->putInTree($container_ref_id); + $wiki->setPermissions($container_ref_id); + } + + $wiki->setOwner($this->exercise->getOwner()); + $wiki->setOnline(true); + $wiki->update(); + $wiki->updateOwner(); + + $this->submission->deleteAllFiles(); + //$this->handleRemovedUpload(); + + $this->submission->addResourceObject($wiki->getRefId()); + + $lng->loadLanguageModule("wiki"); + ilUtil::sendSuccess($lng->txt("wiki_exc_wiki_created"), true); + $this->ctrl->returnToParent($this); + } +} diff --git a/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssignmentTypesGUI.php b/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssignmentTypesGUI.php index 309f1ab72948c635ec700bd81ccc2f18acc924de..560b9e6deb7b6dd6ec2532b6f3ef9c65fc6736cc 100644 --- a/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssignmentTypesGUI.php +++ b/Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssignmentTypesGUI.php @@ -10,129 +10,123 @@ */ class ilExAssignmentTypesGUI { - protected $class_names = array( - ilExAssignment::TYPE_UPLOAD => "ilExAssTypeUploadGUI", - ilExAssignment::TYPE_BLOG => "ilExAssTypeBlogGUI", - ilExAssignment::TYPE_PORTFOLIO => "ilExAssTypePortfolioGUI", - ilExAssignment::TYPE_UPLOAD_TEAM => "ilExAssTypeUploadTeamGUI", - ilExAssignment::TYPE_TEXT => "ilExAssTypeTextGUI", - ilExAssignment::TYPE_WIKI_TEAM => "ilExAssTypeWikiTeamGUI" - ); - - /** - * Constructor - */ - protected function __construct() - { - } - - /** - * Get instance - * - * @return ilExAssignmentTypesGUI - */ - static public function getInstance() - { - return new self(); - } - - /** - * Get type gui object by id - * - * Centralized ID management is still an issue to be tackled in the future and caused - * by initial consts definition. - * - * @param int $a_id type id - * @return ilExAssignmentTypeGUIInterface - */ - public function getById($a_id) - { - // @todo: check id - - switch ($a_id) - { - case ilExAssignment::TYPE_UPLOAD: - include_once("./Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeUploadGUI.php"); - return new ilExAssTypeUploadGUI(); - break; - - case ilExAssignment::TYPE_BLOG: - include_once("./Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeBlogGUI.php"); - return new ilExAssTypeBlogGUI(); - break; - - case ilExAssignment::TYPE_PORTFOLIO: - include_once("./Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypePortfolioGUI.php"); - return new ilExAssTypePortfolioGUI(); - break; - - case ilExAssignment::TYPE_UPLOAD_TEAM: - include_once("./Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeUploadTeamGUI.php"); - return new ilExAssTypeUploadTeamGUI(); - break; - - case ilExAssignment::TYPE_TEXT: - include_once("./Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeTextGUI.php"); - return new ilExAssTypeTextGUI(); - break; - - case ilExAssignment::TYPE_WIKI_TEAM: - include_once("./Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeWikiTeamGUI.php"); - return new ilExAssTypeWikiTeamGUI(); - break; - } - - // we should throw some exception here - } - - /** - * Get type gui object by classname - * - * @param - * @return - */ - public function getByClassName($a_class_name) - { - $id = $this->getIdForClassName($a_class_name); - return $this->getById($id); - } - - - /** - * Checks if a class name is a valid exercise assignment type GUI class - * (case insensitive, since ilCtrl uses lower keys due to historic reasons) - * - * @param string - * @return bool - */ - public function isExAssTypeGUIClass($a_string) - { - foreach ($this->class_names as $cn) - { - if (strtolower($cn) == strtolower($a_string)) - { - return true; - } - } - return false; - } - - /** - * Get type id for class name - * - * @param $a_string - * @return null|int - */ - public function getIdForClassName($a_string) - { - foreach ($this->class_names as $k => $cn) - { - if (strtolower($cn) == strtolower($a_string)) - { - return $k; - } - } - return null; - } - -} \ No newline at end of file + protected $class_names = array( + ilExAssignment::TYPE_UPLOAD => "ilExAssTypeUploadGUI", + ilExAssignment::TYPE_BLOG => "ilExAssTypeBlogGUI", + ilExAssignment::TYPE_PORTFOLIO => "ilExAssTypePortfolioGUI", + ilExAssignment::TYPE_UPLOAD_TEAM => "ilExAssTypeUploadTeamGUI", + ilExAssignment::TYPE_TEXT => "ilExAssTypeTextGUI", + ilExAssignment::TYPE_WIKI_TEAM => "ilExAssTypeWikiTeamGUI" + ); + + /** + * Constructor + */ + protected function __construct() + { + } + + /** + * Get instance + * + * @return ilExAssignmentTypesGUI + */ + public static function getInstance() + { + return new self(); + } + + /** + * Get type gui object by id + * + * Centralized ID management is still an issue to be tackled in the future and caused + * by initial consts definition. + * + * @param int $a_id type id + * @return ilExAssignmentTypeGUIInterface + */ + public function getById($a_id) + { + // @todo: check id + + switch ($a_id) { + case ilExAssignment::TYPE_UPLOAD: + include_once("./Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeUploadGUI.php"); + return new ilExAssTypeUploadGUI(); + break; + + case ilExAssignment::TYPE_BLOG: + include_once("./Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeBlogGUI.php"); + return new ilExAssTypeBlogGUI(); + break; + + case ilExAssignment::TYPE_PORTFOLIO: + include_once("./Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypePortfolioGUI.php"); + return new ilExAssTypePortfolioGUI(); + break; + + case ilExAssignment::TYPE_UPLOAD_TEAM: + include_once("./Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeUploadTeamGUI.php"); + return new ilExAssTypeUploadTeamGUI(); + break; + + case ilExAssignment::TYPE_TEXT: + include_once("./Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeTextGUI.php"); + return new ilExAssTypeTextGUI(); + break; + + case ilExAssignment::TYPE_WIKI_TEAM: + include_once("./Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssTypeWikiTeamGUI.php"); + return new ilExAssTypeWikiTeamGUI(); + break; + } + + // we should throw some exception here + } + + /** + * Get type gui object by classname + * + * @param + * @return + */ + public function getByClassName($a_class_name) + { + $id = $this->getIdForClassName($a_class_name); + return $this->getById($id); + } + + + /** + * Checks if a class name is a valid exercise assignment type GUI class + * (case insensitive, since ilCtrl uses lower keys due to historic reasons) + * + * @param string + * @return bool + */ + public function isExAssTypeGUIClass($a_string) + { + foreach ($this->class_names as $cn) { + if (strtolower($cn) == strtolower($a_string)) { + return true; + } + } + return false; + } + + /** + * Get type id for class name + * + * @param $a_string + * @return null|int + */ + public function getIdForClassName($a_string) + { + foreach ($this->class_names as $k => $cn) { + if (strtolower($cn) == strtolower($a_string)) { + return $k; + } + } + return null; + } +} diff --git a/Modules/Exercise/AssignmentTypes/GUI/classes/interface.ilExAssignmentTypeGUIInterface.php b/Modules/Exercise/AssignmentTypes/GUI/classes/interface.ilExAssignmentTypeGUIInterface.php index a3a2277905a2545e1666ffaa69445993537ccb43..39de9fdfc2b8c86411353314b1f7b3fe0a9ae514 100644 --- a/Modules/Exercise/AssignmentTypes/GUI/classes/interface.ilExAssignmentTypeGUIInterface.php +++ b/Modules/Exercise/AssignmentTypes/GUI/classes/interface.ilExAssignmentTypeGUIInterface.php @@ -12,43 +12,42 @@ */ interface ilExAssignmentTypeGUIInterface { - /** - * Add custom form properties to edit form - * @param ilPropertyFormGUI $form - */ - function addEditFormCustomProperties(ilPropertyFormGUI $form); - - /** - * Get values from form and put them into assignment - * @param ilExAssignment $ass - * @param ilPropertyFormGUI $form - */ - function importFormToAssignment(ilExAssignment $ass , ilPropertyFormGUI $form); - - /** - * Get form values array from assignment - * @param ilExAssignment $ass - * @return array - */ - function getFormValuesArray(ilExAssignment $ass); - - /** - * Add overview content of submission to info screen object - * @param ilInfoScreenGUI $a_info - * @param ilExSubmission $a_submission - */ - function getOverviewContent(ilInfoScreenGUI $a_info, ilExSubmission $a_submission); - - /** - * Set submission - * @param ilExSubmission $a_submission - */ - function setSubmission(ilExSubmission $a_submission); - - /** - * Set exercise - * @param ilObjExercise $a_exercise - */ - function setExercise(ilObjExercise $a_exercise); - -} \ No newline at end of file + /** + * Add custom form properties to edit form + * @param ilPropertyFormGUI $form + */ + public function addEditFormCustomProperties(ilPropertyFormGUI $form); + + /** + * Get values from form and put them into assignment + * @param ilExAssignment $ass + * @param ilPropertyFormGUI $form + */ + public function importFormToAssignment(ilExAssignment $ass, ilPropertyFormGUI $form); + + /** + * Get form values array from assignment + * @param ilExAssignment $ass + * @return array + */ + public function getFormValuesArray(ilExAssignment $ass); + + /** + * Add overview content of submission to info screen object + * @param ilInfoScreenGUI $a_info + * @param ilExSubmission $a_submission + */ + public function getOverviewContent(ilInfoScreenGUI $a_info, ilExSubmission $a_submission); + + /** + * Set submission + * @param ilExSubmission $a_submission + */ + public function setSubmission(ilExSubmission $a_submission); + + /** + * Set exercise + * @param ilObjExercise $a_exercise + */ + public function setExercise(ilObjExercise $a_exercise); +} diff --git a/Modules/Exercise/AssignmentTypes/GUI/traits/trait.ilExAssignmentTypeGUIBase.php b/Modules/Exercise/AssignmentTypes/GUI/traits/trait.ilExAssignmentTypeGUIBase.php index 9faeb913e82233cac938136160cadf76afe8d1ea..f1e92aca775e3939dc86235525920801cf86e1c3 100644 --- a/Modules/Exercise/AssignmentTypes/GUI/traits/trait.ilExAssignmentTypeGUIBase.php +++ b/Modules/Exercise/AssignmentTypes/GUI/traits/trait.ilExAssignmentTypeGUIBase.php @@ -10,53 +10,53 @@ */ trait ilExAssignmentTypeGUIBase { - /** - * @var ilExSubmission - */ - protected $submission; + /** + * @var ilExSubmission + */ + protected $submission; - /** - * @var ilObjExercise - */ - protected $exercise; + /** + * @var ilObjExercise + */ + protected $exercise; - /** - * Set submission - * - * @param ilExSubmission $a_val submission - */ - function setSubmission(ilExSubmission $a_val) - { - $this->submission = $a_val; - } + /** + * Set submission + * + * @param ilExSubmission $a_val submission + */ + public function setSubmission(ilExSubmission $a_val) + { + $this->submission = $a_val; + } - /** - * Get submission - * - * @return ilExSubmission submission - */ - function getSubmission() - { - return $this->submission; - } + /** + * Get submission + * + * @return ilExSubmission submission + */ + public function getSubmission() + { + return $this->submission; + } - /** - * Set exercise - * - * @param ilObjExercise $a_val exercise - */ - function setExercise(ilObjExercise $a_val) - { - $this->exercise = $a_val; - } + /** + * Set exercise + * + * @param ilObjExercise $a_val exercise + */ + public function setExercise(ilObjExercise $a_val) + { + $this->exercise = $a_val; + } - /** - * Get exercise - * - * @return ilObjExercise exercise - */ - function getExercise() - { - return $this->exercise; - } -} \ No newline at end of file + /** + * Get exercise + * + * @return ilObjExercise exercise + */ + public function getExercise() + { + return $this->exercise; + } +} diff --git a/Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeBlog.php b/Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeBlog.php index 389cf11f126027c649c9370e5575ac73efc6e543..28b6f6744b3ca94b92ed10ea1087cacab917c930 100644 --- a/Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeBlog.php +++ b/Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeBlog.php @@ -11,96 +11,93 @@ include_once("./Modules/Exercise/AssignmentTypes/classes/interface.ilExAssignmen */ class ilExAssTypeBlog implements ilExAssignmentTypeInterface { - /** - * @var ilSetting - */ - protected $setting; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * Constructor - * - * @param ilSetting|null $a_setting - * @param ilLanguage|null $a_lng - */ - public function __construct(ilSetting $a_setting = null, ilLanguage $a_lng = null) - { - global $DIC; - - $this->setting = ($a_setting) - ? $a_setting - : $DIC["ilSetting"]; - - $this->lng = ($a_lng) - ? $a_lng - : $DIC->language(); - } - - /** - * @inheritdoc - */ - public function isActive() - { - if($this->setting->get('disable_wsp_blogs')) - { - return false; - } - return true; - } - - - /** - * @inheritdoc - */ - public function usesTeams() - { - return false; - } - - /** - * @inheritdoc - */ - public function usesFileUpload() - { - return false; - } - - /** - * @inheritdoc - */ - public function getTitle() - { - $lng = $this->lng; - - return $lng->txt("exc_type_blog"); - } - - /** - * @inheritdoc - */ - public function getSubmissionType() - { - return ilExSubmission::TYPE_OBJECT; - } - - /** - * @inheritdoc - */ - public function isSubmissionAssignedToTeam() - { - return false; - } - - /** - * @inheritdoc - */ - public function cloneSpecificProperties(ilExAssignment $source, ilExAssignment $target) - { - - } - -} \ No newline at end of file + /** + * @var ilSetting + */ + protected $setting; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * Constructor + * + * @param ilSetting|null $a_setting + * @param ilLanguage|null $a_lng + */ + public function __construct(ilSetting $a_setting = null, ilLanguage $a_lng = null) + { + global $DIC; + + $this->setting = ($a_setting) + ? $a_setting + : $DIC["ilSetting"]; + + $this->lng = ($a_lng) + ? $a_lng + : $DIC->language(); + } + + /** + * @inheritdoc + */ + public function isActive() + { + if ($this->setting->get('disable_wsp_blogs')) { + return false; + } + return true; + } + + + /** + * @inheritdoc + */ + public function usesTeams() + { + return false; + } + + /** + * @inheritdoc + */ + public function usesFileUpload() + { + return false; + } + + /** + * @inheritdoc + */ + public function getTitle() + { + $lng = $this->lng; + + return $lng->txt("exc_type_blog"); + } + + /** + * @inheritdoc + */ + public function getSubmissionType() + { + return ilExSubmission::TYPE_OBJECT; + } + + /** + * @inheritdoc + */ + public function isSubmissionAssignedToTeam() + { + return false; + } + + /** + * @inheritdoc + */ + public function cloneSpecificProperties(ilExAssignment $source, ilExAssignment $target) + { + } +} diff --git a/Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypePortfolio.php b/Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypePortfolio.php index 12d81f61a6623eee58f2c317f095cd12ed100f99..f482f589d343aca6451fb3406ce05928bb6dcd5b 100644 --- a/Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypePortfolio.php +++ b/Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypePortfolio.php @@ -11,95 +11,92 @@ include_once("./Modules/Exercise/AssignmentTypes/classes/interface.ilExAssignmen */ class ilExAssTypePortfolio implements ilExAssignmentTypeInterface { - /** - * @var ilSetting - */ - protected $setting; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * Constructor - * - * @param ilSetting|null $a_setting - * @param ilLanguage|null $a_lng - */ - public function __construct(ilSetting $a_setting = null, ilLanguage $a_lng = null) - { - global $DIC; - - $this->setting = ($a_setting) - ? $a_setting - : $DIC["ilSetting"]; - - $this->lng = ($a_lng) - ? $a_lng - : $DIC->language(); - } - - /** - * @inheritdoc - */ - public function isActive() - { - if($this->setting->get('user_portfolios')) - { - return true; - } - return false; - } - - /** - * @inheritdoc - */ - public function usesTeams() - { - return false; - } - - /** - * @inheritdoc - */ - public function usesFileUpload() - { - return false; - } - - /** - * @inheritdoc - */ - public function getTitle() - { - $lng = $this->lng; - - return $lng->txt("exc_type_portfolio"); - } - - /** - * @inheritdoc - */ - public function getSubmissionType() - { - return ilExSubmission::TYPE_OBJECT; - } - - /** - * @inheritdoc - */ - public function isSubmissionAssignedToTeam() - { - return false; - } - - /** - * @inheritdoc - */ - public function cloneSpecificProperties(ilExAssignment $source, ilExAssignment $target) - { - - } - -} \ No newline at end of file + /** + * @var ilSetting + */ + protected $setting; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * Constructor + * + * @param ilSetting|null $a_setting + * @param ilLanguage|null $a_lng + */ + public function __construct(ilSetting $a_setting = null, ilLanguage $a_lng = null) + { + global $DIC; + + $this->setting = ($a_setting) + ? $a_setting + : $DIC["ilSetting"]; + + $this->lng = ($a_lng) + ? $a_lng + : $DIC->language(); + } + + /** + * @inheritdoc + */ + public function isActive() + { + if ($this->setting->get('user_portfolios')) { + return true; + } + return false; + } + + /** + * @inheritdoc + */ + public function usesTeams() + { + return false; + } + + /** + * @inheritdoc + */ + public function usesFileUpload() + { + return false; + } + + /** + * @inheritdoc + */ + public function getTitle() + { + $lng = $this->lng; + + return $lng->txt("exc_type_portfolio"); + } + + /** + * @inheritdoc + */ + public function getSubmissionType() + { + return ilExSubmission::TYPE_OBJECT; + } + + /** + * @inheritdoc + */ + public function isSubmissionAssignedToTeam() + { + return false; + } + + /** + * @inheritdoc + */ + public function cloneSpecificProperties(ilExAssignment $source, ilExAssignment $target) + { + } +} diff --git a/Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeText.php b/Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeText.php index ccf0078eec23ff0845f8b113941ec803225238d7..fb568c0b6411611f10cdb850c3cd3211ef92f4cb 100644 --- a/Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeText.php +++ b/Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeText.php @@ -11,82 +11,79 @@ include_once("./Modules/Exercise/AssignmentTypes/classes/interface.ilExAssignmen */ class ilExAssTypeText implements ilExAssignmentTypeInterface { - /** - * @var ilLanguage - */ - protected $lng; - - /** - * Constructor - * - * @param ilLanguage|null $a_lng - */ - public function __construct(ilLanguage $a_lng = null) - { - global $DIC; - - $this->lng = ($a_lng) - ? $a_lng - : $DIC->language(); - } - - /** - * @inheritdoc - */ - public function isActive() - { - return true; - } - - /** - * @inheritdoc - */ - public function usesTeams() - { - return false; - } - - /** - * @inheritdoc - */ - public function usesFileUpload() - { - return false; - } - - /** - * @inheritdoc - */ - public function getTitle() - { - $lng = $this->lng; - - return $lng->txt("exc_type_text"); - } - - /** - * @inheritdoc - */ - public function getSubmissionType() - { - return ilExSubmission::TYPE_TEXT; - } - - /** - * @inheritdoc - */ - public function isSubmissionAssignedToTeam() - { - return false; - } - - /** - * @inheritdoc - */ - public function cloneSpecificProperties(ilExAssignment $source, ilExAssignment $target) - { - - } - - -} \ No newline at end of file + /** + * @var ilLanguage + */ + protected $lng; + + /** + * Constructor + * + * @param ilLanguage|null $a_lng + */ + public function __construct(ilLanguage $a_lng = null) + { + global $DIC; + + $this->lng = ($a_lng) + ? $a_lng + : $DIC->language(); + } + + /** + * @inheritdoc + */ + public function isActive() + { + return true; + } + + /** + * @inheritdoc + */ + public function usesTeams() + { + return false; + } + + /** + * @inheritdoc + */ + public function usesFileUpload() + { + return false; + } + + /** + * @inheritdoc + */ + public function getTitle() + { + $lng = $this->lng; + + return $lng->txt("exc_type_text"); + } + + /** + * @inheritdoc + */ + public function getSubmissionType() + { + return ilExSubmission::TYPE_TEXT; + } + + /** + * @inheritdoc + */ + public function isSubmissionAssignedToTeam() + { + return false; + } + + /** + * @inheritdoc + */ + public function cloneSpecificProperties(ilExAssignment $source, ilExAssignment $target) + { + } +} diff --git a/Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeUpload.php b/Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeUpload.php index 0ad616df9fe89de0a62aa567f1904837f164de5f..d20a9f8ebd489157fa73895853871daccae774af 100644 --- a/Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeUpload.php +++ b/Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeUpload.php @@ -11,82 +11,79 @@ include_once("./Modules/Exercise/AssignmentTypes/classes/interface.ilExAssignmen */ class ilExAssTypeUpload implements ilExAssignmentTypeInterface { - /** - * @var ilLanguage - */ - protected $lng; - - /** - * Constructor - * - * @param ilLanguage|null $a_lng - */ - public function __construct(ilLanguage $a_lng = null) - { - global $DIC; - - $this->lng = ($a_lng) - ? $a_lng - : $DIC->language(); - } - - /** - * @inheritdoc - */ - public function isActive() - { - return true; - } - - /** - * @inheritdoc - */ - public function usesTeams() - { - return false; - } - - /** - * @inheritdoc - */ - public function usesFileUpload() - { - return true; - } - - /** - * @inheritdoc - */ - public function getTitle() - { - $lng = $this->lng; - - return $lng->txt("exc_type_upload"); - } - - /** - * @inheritdoc - */ - public function getSubmissionType() - { - return ilExSubmission::TYPE_FILE; - } - - /** - * @inheritdoc - */ - public function isSubmissionAssignedToTeam() - { - return false; - } - - /** - * @inheritdoc - */ - public function cloneSpecificProperties(ilExAssignment $source, ilExAssignment $target) - { - - } - - -} \ No newline at end of file + /** + * @var ilLanguage + */ + protected $lng; + + /** + * Constructor + * + * @param ilLanguage|null $a_lng + */ + public function __construct(ilLanguage $a_lng = null) + { + global $DIC; + + $this->lng = ($a_lng) + ? $a_lng + : $DIC->language(); + } + + /** + * @inheritdoc + */ + public function isActive() + { + return true; + } + + /** + * @inheritdoc + */ + public function usesTeams() + { + return false; + } + + /** + * @inheritdoc + */ + public function usesFileUpload() + { + return true; + } + + /** + * @inheritdoc + */ + public function getTitle() + { + $lng = $this->lng; + + return $lng->txt("exc_type_upload"); + } + + /** + * @inheritdoc + */ + public function getSubmissionType() + { + return ilExSubmission::TYPE_FILE; + } + + /** + * @inheritdoc + */ + public function isSubmissionAssignedToTeam() + { + return false; + } + + /** + * @inheritdoc + */ + public function cloneSpecificProperties(ilExAssignment $source, ilExAssignment $target) + { + } +} diff --git a/Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeUploadTeam.php b/Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeUploadTeam.php index e9b52df10c8d5789d8b78c4d1fefa6f3f9a6c00f..57476ed2e043154c35f33bfb20cea8150caaf0c3 100644 --- a/Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeUploadTeam.php +++ b/Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeUploadTeam.php @@ -11,81 +11,79 @@ include_once("./Modules/Exercise/AssignmentTypes/classes/interface.ilExAssignmen */ class ilExAssTypeUploadTeam implements ilExAssignmentTypeInterface { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * Constructor - * - * @param ilLanguage|null $a_lng - */ - public function __construct(ilLanguage $a_lng = null) - { - global $DIC; + /** + * Constructor + * + * @param ilLanguage|null $a_lng + */ + public function __construct(ilLanguage $a_lng = null) + { + global $DIC; - $this->lng = ($a_lng) - ? $a_lng - : $DIC->language(); - } + $this->lng = ($a_lng) + ? $a_lng + : $DIC->language(); + } - /** - * @inheritdoc - */ - public function isActive() - { - return true; - } + /** + * @inheritdoc + */ + public function isActive() + { + return true; + } - /** - * @inheritdoc - */ - public function usesTeams() - { - return true; - } + /** + * @inheritdoc + */ + public function usesTeams() + { + return true; + } - /** - * @inheritdoc - */ - public function usesFileUpload() - { - return true; - } + /** + * @inheritdoc + */ + public function usesFileUpload() + { + return true; + } - /** - * @inheritdoc - */ - public function getTitle() - { - $lng = $this->lng; + /** + * @inheritdoc + */ + public function getTitle() + { + $lng = $this->lng; - return $lng->txt("exc_type_upload_team"); - } + return $lng->txt("exc_type_upload_team"); + } - /** - * @inheritdoc - */ - public function getSubmissionType() - { - return ilExSubmission::TYPE_FILE; - } + /** + * @inheritdoc + */ + public function getSubmissionType() + { + return ilExSubmission::TYPE_FILE; + } - /** - * @inheritdoc - */ - public function isSubmissionAssignedToTeam() - { - return false; - } + /** + * @inheritdoc + */ + public function isSubmissionAssignedToTeam() + { + return false; + } - /** - * @inheritdoc - */ - public function cloneSpecificProperties(ilExAssignment $source, ilExAssignment $target) - { - - } - -} \ No newline at end of file + /** + * @inheritdoc + */ + public function cloneSpecificProperties(ilExAssignment $source, ilExAssignment $target) + { + } +} diff --git a/Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeWikiTeam.php b/Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeWikiTeam.php index 23ba5795f518144c9e0db867ca53f43f1aa90264..086410441cbb4b580aad5f9156af0a9bcf13b6be 100644 --- a/Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeWikiTeam.php +++ b/Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeWikiTeam.php @@ -11,169 +11,169 @@ include_once("./Modules/Exercise/AssignmentTypes/classes/interface.ilExAssignmen */ class ilExAssTypeWikiTeam implements ilExAssignmentTypeInterface { - /** - * @var ilLanguage - */ - protected $lng; - - /** - * Constructor - * - * @param ilLanguage|null $a_lng - */ - public function __construct(ilLanguage $a_lng = null) - { - global $DIC; - - $this->lng = ($a_lng) - ? $a_lng - : $DIC->language(); - } - - /** - * @inheritdoc - */ - public function isActive() - { - return true; - } - - /** - * @inheritdoc - */ - public function usesTeams() - { - return true; - } - - /** - * @inheritdoc - */ - public function usesFileUpload() - { - return false; - } - - /** - * @inheritdoc - */ - public function getTitle() - { - $lng = $this->lng; - $lng->loadLanguageModule("wiki"); - return $lng->txt("wiki_type_wiki_team"); - } - - /** - * @inheritdoc - */ - public function getSubmissionType() - { - return ilExSubmission::TYPE_REPO_OBJECT; - } - - /** - * @inheritdoc - */ - public function isSubmissionAssignedToTeam() - { - return true; - } - - /** - * Submit wiki - * - * @param int $a_ass_id - * @param int $a_user_id - * @param int $a_wiki_ref_id - */ - public function submitWiki($a_ass_id, $a_user_id, $a_wiki_ref_id) - { - 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); - $submission = new ilExSubmission($ass, $a_user_id); - - if(!$submission->canSubmit()) - { - return; - } - - include_once "Modules/Wiki/classes/class.ilObjWiki.php"; - $wiki = new ilObjWiki((int) $a_wiki_ref_id); - include_once("./Modules/Wiki/classes/class.ilWikiHTMLExport.php"); - $exp = new ilWikiHTMLExport($wiki); - //$exp->setMode(ilWikiHTMLExport::MODE_USER); - $file = $exp->buildExportFile(); - - $size = filesize($file); - if($size) - { - $submission->deleteAllFiles(); - - $meta = array( - "name" => $a_wiki_ref_id, - "tmp_name" => $file, - "size" => $size - ); - $submission->uploadFile($meta, true); - - $this->handleNewUpload($ass, $submission); - return true; - } - return false; - } - - // @todo move to trait - protected function handleNewUpload(ilExAssignment $ass, - ilExSubmission $submission, $a_no_notifications = false) - { - $has_submitted = $submission->hasSubmitted(); - - // we need one ref id here - $exc_ref_ids = ilObject::_getAllReferences($ass->getExerciseId()); - $exc_ref_id = current($exc_ref_ids); - - $exc = new ilObjExercise($ass->getExerciseId(), false); - - $exc->processExerciseStatus( - $ass, - $submission->getUserIds(), - $has_submitted, - $submission->validatePeerReviews()); - - if($has_submitted && - !$a_no_notifications) - { - include_once "./Services/Notification/classes/class.ilNotification.php"; - $users = ilNotification::getNotificationsForObject(ilNotification::TYPE_EXERCISE_SUBMISSION, - $exc->getId()); - - include_once "./Modules/Exercise/classes/class.ilExerciseMailNotification.php"; - $not = new ilExerciseMailNotification(); - $not->setType(ilExerciseMailNotification::TYPE_SUBMISSION_UPLOAD); - $not->setAssignmentId($ass->getId()); - $not->setRefId($exc_ref_id); - $not->setRecipients($users); - $not->send(); - } - } - - /** - * @inheritdoc - */ - public function cloneSpecificProperties(ilExAssignment $source, ilExAssignment $target) - { - include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssWikiTeamAR.php"); - $source_ar = new ilExAssWikiTeamAR($source->getId()); - $target_ar = new ilExAssWikiTeamAR(); - $target_ar->setId($target->getId()); - $target_ar->setTemplateRefId($source_ar->getTemplateRefId()); - $target_ar->setContainerRefId($source_ar->getContainerRefId()); - $target_ar->save(); - } - - -} \ No newline at end of file + /** + * @var ilLanguage + */ + protected $lng; + + /** + * Constructor + * + * @param ilLanguage|null $a_lng + */ + public function __construct(ilLanguage $a_lng = null) + { + global $DIC; + + $this->lng = ($a_lng) + ? $a_lng + : $DIC->language(); + } + + /** + * @inheritdoc + */ + public function isActive() + { + return true; + } + + /** + * @inheritdoc + */ + public function usesTeams() + { + return true; + } + + /** + * @inheritdoc + */ + public function usesFileUpload() + { + return false; + } + + /** + * @inheritdoc + */ + public function getTitle() + { + $lng = $this->lng; + $lng->loadLanguageModule("wiki"); + return $lng->txt("wiki_type_wiki_team"); + } + + /** + * @inheritdoc + */ + public function getSubmissionType() + { + return ilExSubmission::TYPE_REPO_OBJECT; + } + + /** + * @inheritdoc + */ + public function isSubmissionAssignedToTeam() + { + return true; + } + + /** + * Submit wiki + * + * @param int $a_ass_id + * @param int $a_user_id + * @param int $a_wiki_ref_id + */ + public function submitWiki($a_ass_id, $a_user_id, $a_wiki_ref_id) + { + 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); + $submission = new ilExSubmission($ass, $a_user_id); + + if (!$submission->canSubmit()) { + return; + } + + include_once "Modules/Wiki/classes/class.ilObjWiki.php"; + $wiki = new ilObjWiki((int) $a_wiki_ref_id); + include_once("./Modules/Wiki/classes/class.ilWikiHTMLExport.php"); + $exp = new ilWikiHTMLExport($wiki); + //$exp->setMode(ilWikiHTMLExport::MODE_USER); + $file = $exp->buildExportFile(); + + $size = filesize($file); + if ($size) { + $submission->deleteAllFiles(); + + $meta = array( + "name" => $a_wiki_ref_id, + "tmp_name" => $file, + "size" => $size + ); + $submission->uploadFile($meta, true); + + $this->handleNewUpload($ass, $submission); + return true; + } + return false; + } + + // @todo move to trait + protected function handleNewUpload( + ilExAssignment $ass, + ilExSubmission $submission, + $a_no_notifications = false + ) { + $has_submitted = $submission->hasSubmitted(); + + // we need one ref id here + $exc_ref_ids = ilObject::_getAllReferences($ass->getExerciseId()); + $exc_ref_id = current($exc_ref_ids); + + $exc = new ilObjExercise($ass->getExerciseId(), false); + + $exc->processExerciseStatus( + $ass, + $submission->getUserIds(), + $has_submitted, + $submission->validatePeerReviews() + ); + + if ($has_submitted && + !$a_no_notifications) { + include_once "./Services/Notification/classes/class.ilNotification.php"; + $users = ilNotification::getNotificationsForObject( + ilNotification::TYPE_EXERCISE_SUBMISSION, + $exc->getId() + ); + + include_once "./Modules/Exercise/classes/class.ilExerciseMailNotification.php"; + $not = new ilExerciseMailNotification(); + $not->setType(ilExerciseMailNotification::TYPE_SUBMISSION_UPLOAD); + $not->setAssignmentId($ass->getId()); + $not->setRefId($exc_ref_id); + $not->setRecipients($users); + $not->send(); + } + } + + /** + * @inheritdoc + */ + public function cloneSpecificProperties(ilExAssignment $source, ilExAssignment $target) + { + include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssWikiTeamAR.php"); + $source_ar = new ilExAssWikiTeamAR($source->getId()); + $target_ar = new ilExAssWikiTeamAR(); + $target_ar->setId($target->getId()); + $target_ar->setTemplateRefId($source_ar->getTemplateRefId()); + $target_ar->setContainerRefId($source_ar->getContainerRefId()); + $target_ar->save(); + } +} diff --git a/Modules/Exercise/AssignmentTypes/classes/class.ilExAssWikiTeamAR.php b/Modules/Exercise/AssignmentTypes/classes/class.ilExAssWikiTeamAR.php index 1378ea479ee29e84591b0bd3b67dcb0ff1152ce3..6e38a81ec030063327d9be99ed5214713d184e5f 100644 --- a/Modules/Exercise/AssignmentTypes/classes/class.ilExAssWikiTeamAR.php +++ b/Modules/Exercise/AssignmentTypes/classes/class.ilExAssWikiTeamAR.php @@ -13,109 +13,110 @@ include_once("./Services/ActiveRecord/class.ActiveRecord.php"); */ class ilExAssWikiTeamAR extends ActiveRecord { - /** - * @return string - */ - static function returnDbTableName() { - return 'exc_ass_wiki_team'; - } - - /** - * @var int - * - * @con_is_primary true - * @con_is_unique true - * @con_has_field true - * @con_fieldtype integer - * @con_is_notnull true - * @con_length 4 - * @con_sequence false - */ - protected $id; - - /** - * @var int - * - * @con_has_field true - * @con_fieldtype integer - * @con_length 4 - * @con_is_notnull false - */ - protected $template_ref_id = 0; - - /** - * @var int - * - * @con_has_field true - * @con_fieldtype integer - * @con_length 4 - * @con_is_notnull false - */ - protected $container_ref_id = 0; - - - /** - * Get ID - * - * @return int ID - */ - public function getId() { - return $this->id; - } - - - /** - * Set ID - * - * @param int $id ID - */ - public function setId($id) { - $this->id = $id; - } - - - /** - * Set template ref id - * - * @param int $a_template_ref_id template ref id - */ - public function setTemplateRefId($a_template_ref_id) - { - $this->template_ref_id = $a_template_ref_id; - } - - - /** - * Get template ref id - * - * @return int - */ - public function getTemplateRefId() - { - return $this->template_ref_id; - } - - - /** - * Set container ref id - * - * @param int $a_container_ref_id container ref id - */ - public function setContainerRefId($a_container_ref_id) - { - $this->container_ref_id = $a_container_ref_id; - } - - - /** - * Get container ref id - * - * @return int - */ - public function getContainerRefId() - { - return $this->container_ref_id; - } + /** + * @return string + */ + public static function returnDbTableName() + { + return 'exc_ass_wiki_team'; + } + + /** + * @var int + * + * @con_is_primary true + * @con_is_unique true + * @con_has_field true + * @con_fieldtype integer + * @con_is_notnull true + * @con_length 4 + * @con_sequence false + */ + protected $id; + + /** + * @var int + * + * @con_has_field true + * @con_fieldtype integer + * @con_length 4 + * @con_is_notnull false + */ + protected $template_ref_id = 0; + + /** + * @var int + * + * @con_has_field true + * @con_fieldtype integer + * @con_length 4 + * @con_is_notnull false + */ + protected $container_ref_id = 0; + + + /** + * Get ID + * + * @return int ID + */ + public function getId() + { + return $this->id; + } + + + /** + * Set ID + * + * @param int $id ID + */ + public function setId($id) + { + $this->id = $id; + } + + + /** + * Set template ref id + * + * @param int $a_template_ref_id template ref id + */ + public function setTemplateRefId($a_template_ref_id) + { + $this->template_ref_id = $a_template_ref_id; + } + + + /** + * Get template ref id + * + * @return int + */ + public function getTemplateRefId() + { + return $this->template_ref_id; + } + + + /** + * Set container ref id + * + * @param int $a_container_ref_id container ref id + */ + public function setContainerRefId($a_container_ref_id) + { + $this->container_ref_id = $a_container_ref_id; + } + + + /** + * Get container ref id + * + * @return int + */ + public function getContainerRefId() + { + return $this->container_ref_id; + } } - -?> \ No newline at end of file diff --git a/Modules/Exercise/AssignmentTypes/classes/class.ilExAssignmentTypes.php b/Modules/Exercise/AssignmentTypes/classes/class.ilExAssignmentTypes.php index d43f46ba4754be4c8fa3b0d5dd1613dd17b90d02..27f435d772550a1f7a7ed50222d677c019070bdd 100644 --- a/Modules/Exercise/AssignmentTypes/classes/class.ilExAssignmentTypes.php +++ b/Modules/Exercise/AssignmentTypes/classes/class.ilExAssignmentTypes.php @@ -11,149 +11,148 @@ */ class ilExAssignmentTypes { - /** - * Constructor - */ - protected function __construct() - { - } - - /** - * Get instance - * - * @return ilExAssignmentTypes - */ - static public function getInstance() - { - return new self(); - } - - /** - * Get all ids - * - * @param - * @return - */ - public function getAllIds() - { - return [ - ilExAssignment::TYPE_UPLOAD, - ilExAssignment::TYPE_UPLOAD_TEAM, - ilExAssignment::TYPE_TEXT, - ilExAssignment::TYPE_BLOG, - ilExAssignment::TYPE_PORTFOLIO, - ilExAssignment::TYPE_WIKI_TEAM - ]; - } - - /** - * Is valid id - * - * @param int $a_id - * @return bool - */ - public function isValidId($a_id) - { - return in_array($a_id, $this->getAllIds()); - } - - - - /** - * Get all - * - * @param - * @return - */ - public function getAll() - { - return array_column( - array_map(function($id) { - return [$id, $this->getById($id)]; - }, $this->getAllIds() - ) - , 1, 0); - } - - /** - * Get all activated - * - * @param - * @return - */ - public function getAllActivated() - { - return array_filter($this->getAll(), function(ilExAssignmentTypeInterface $at) { - return $at->isActive(); - }); - } - - - /** - * Get type object by id - * - * Centralized ID management is still an issue to be tackled in the future and caused - * by initial consts definition. - * - * @param int $a_id type id - * @return ilExAssignmentTypeInterface - */ - public function getById($a_id) - { - switch ($a_id) - { - case ilExAssignment::TYPE_UPLOAD: - include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeUpload.php"); - return new ilExAssTypeUpload(); - break; - - case ilExAssignment::TYPE_BLOG: - include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeBlog.php"); - return new ilExAssTypeBlog(); - break; - - case ilExAssignment::TYPE_PORTFOLIO: - include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypePortfolio.php"); - return new ilExAssTypePortfolio(); - break; - - case ilExAssignment::TYPE_UPLOAD_TEAM: - include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeUploadTeam.php"); - return new ilExAssTypeUploadTeam(); - break; - - case ilExAssignment::TYPE_TEXT: - include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeText.php"); - return new ilExAssTypeText(); - break; - - case ilExAssignment::TYPE_WIKI_TEAM: - include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeWikiTeam.php"); - return new ilExAssTypeWikiTeam(); - break; - } - - // we should throw some exception here - } - - /** - * Get assignment type IDs for given submission type - * - * @param int $a_submission_type - * @return array - */ - public function getIdsForSubmissionType($a_submission_type) - { - $ids = []; - foreach ($this->getAllIds() as $id) - { - if ($this->getById($id)->getSubmissionType() == $a_submission_type) - { - $ids[] = $id; - } - } - return $ids; - } - - -} \ No newline at end of file + /** + * Constructor + */ + protected function __construct() + { + } + + /** + * Get instance + * + * @return ilExAssignmentTypes + */ + public static function getInstance() + { + return new self(); + } + + /** + * Get all ids + * + * @param + * @return + */ + public function getAllIds() + { + return [ + ilExAssignment::TYPE_UPLOAD, + ilExAssignment::TYPE_UPLOAD_TEAM, + ilExAssignment::TYPE_TEXT, + ilExAssignment::TYPE_BLOG, + ilExAssignment::TYPE_PORTFOLIO, + ilExAssignment::TYPE_WIKI_TEAM + ]; + } + + /** + * Is valid id + * + * @param int $a_id + * @return bool + */ + public function isValidId($a_id) + { + return in_array($a_id, $this->getAllIds()); + } + + + + /** + * Get all + * + * @param + * @return + */ + public function getAll() + { + return array_column( + array_map( + function ($id) { + return [$id, $this->getById($id)]; + }, + $this->getAllIds() + ), + 1, + 0 + ); + } + + /** + * Get all activated + * + * @param + * @return + */ + public function getAllActivated() + { + return array_filter($this->getAll(), function (ilExAssignmentTypeInterface $at) { + return $at->isActive(); + }); + } + + + /** + * Get type object by id + * + * Centralized ID management is still an issue to be tackled in the future and caused + * by initial consts definition. + * + * @param int $a_id type id + * @return ilExAssignmentTypeInterface + */ + public function getById($a_id) + { + switch ($a_id) { + case ilExAssignment::TYPE_UPLOAD: + include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeUpload.php"); + return new ilExAssTypeUpload(); + break; + + case ilExAssignment::TYPE_BLOG: + include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeBlog.php"); + return new ilExAssTypeBlog(); + break; + + case ilExAssignment::TYPE_PORTFOLIO: + include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypePortfolio.php"); + return new ilExAssTypePortfolio(); + break; + + case ilExAssignment::TYPE_UPLOAD_TEAM: + include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeUploadTeam.php"); + return new ilExAssTypeUploadTeam(); + break; + + case ilExAssignment::TYPE_TEXT: + include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeText.php"); + return new ilExAssTypeText(); + break; + + case ilExAssignment::TYPE_WIKI_TEAM: + include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssTypeWikiTeam.php"); + return new ilExAssTypeWikiTeam(); + break; + } + + // we should throw some exception here + } + + /** + * Get assignment type IDs for given submission type + * + * @param int $a_submission_type + * @return array + */ + public function getIdsForSubmissionType($a_submission_type) + { + $ids = []; + foreach ($this->getAllIds() as $id) { + if ($this->getById($id)->getSubmissionType() == $a_submission_type) { + $ids[] = $id; + } + } + return $ids; + } +} diff --git a/Modules/Exercise/AssignmentTypes/classes/interface.ilExAssignmentTypeInterface.php b/Modules/Exercise/AssignmentTypes/classes/interface.ilExAssignmentTypeInterface.php index bdf8c5e571f41abe906c029f4ae00bd253128583..ff5abef332be3f9c8f9c85a0d72c18a132ab5dfe 100644 --- a/Modules/Exercise/AssignmentTypes/classes/interface.ilExAssignmentTypeInterface.php +++ b/Modules/Exercise/AssignmentTypes/classes/interface.ilExAssignmentTypeInterface.php @@ -9,54 +9,53 @@ */ interface ilExAssignmentTypeInterface { - /** - * Is assignment type active? - * - * @return bool - */ - function isActive(); - - /** - * Uses teams - * - * @return bool - */ - function usesTeams(); - - /** - * Uses file upload - * - * @return bool - */ - function usesFileUpload(); - - /** - * Get title of type - * - * @return string - */ - public function getTitle(); - - /** - * Get submission type - * - * @return string - */ - public function getSubmissionType(); - - /** - * Get submission type - * - * @return string - */ - public function isSubmissionAssignedToTeam(); - - /** - * Clone type specific properties of an assignment - * - * @param ilExAssignment $source - * @param ilExAssignment $target - */ - public function cloneSpecificProperties(ilExAssignment $source, ilExAssignment $target); - -} \ No newline at end of file + /** + * Is assignment type active? + * + * @return bool + */ + public function isActive(); + + /** + * Uses teams + * + * @return bool + */ + public function usesTeams(); + + /** + * Uses file upload + * + * @return bool + */ + public function usesFileUpload(); + + /** + * Get title of type + * + * @return string + */ + public function getTitle(); + + /** + * Get submission type + * + * @return string + */ + public function getSubmissionType(); + + /** + * Get submission type + * + * @return string + */ + public function isSubmissionAssignedToTeam(); + + /** + * Clone type specific properties of an assignment + * + * @param ilExAssignment $source + * @param ilExAssignment $target + */ + public function cloneSpecificProperties(ilExAssignment $source, ilExAssignment $target); +} diff --git a/Modules/Exercise/RepoObjectAssignment/classes/class.ilExcRepoObjAssignment.php b/Modules/Exercise/RepoObjectAssignment/classes/class.ilExcRepoObjAssignment.php index ccd6fd492538060eeaf07d114b21c766ad2172a8..f946b094edbe303dd9ae9fd8ed04461fdbc4b49e 100644 --- a/Modules/Exercise/RepoObjectAssignment/classes/class.ilExcRepoObjAssignment.php +++ b/Modules/Exercise/RepoObjectAssignment/classes/class.ilExcRepoObjAssignment.php @@ -13,66 +13,62 @@ include_once("./Modules/Exercise/RepoObjectAssignment/interfaces/interface.ilExc class ilExcRepoObjAssignment implements ilExcRepoObjAssignmentInterface { - /** - * Constructor - * - */ - protected function __construct() - { - } + /** + * Constructor + * + */ + protected function __construct() + { + } - /** - * Get instance - * - * @param - * @return - */ - static public function getInstance() - { - return new self(); - } + /** + * Get instance + * + * @param + * @return + */ + public static function getInstance() + { + return new self(); + } - /** - * Get assignment(s) information of repository object - * - * @param int $a_ref_id ref id - * @param int $a_user_id if user id is provided, only readable links will be added - * @return ilExcRepoObjAssignmentInfoInterface[] - */ - function getAssignmentInfoOfObj($a_ref_id, $a_user_id) - { - include_once("./Modules/Exercise/RepoObjectAssignment/classes/class.ilExcRepoObjAssignmentInfo.php"); - return ilExcRepoObjAssignmentInfo::getInfo($a_ref_id, $a_user_id); - } + /** + * Get assignment(s) information of repository object + * + * @param int $a_ref_id ref id + * @param int $a_user_id if user id is provided, only readable links will be added + * @return ilExcRepoObjAssignmentInfoInterface[] + */ + public function getAssignmentInfoOfObj($a_ref_id, $a_user_id) + { + include_once("./Modules/Exercise/RepoObjectAssignment/classes/class.ilExcRepoObjAssignmentInfo.php"); + return ilExcRepoObjAssignmentInfo::getInfo($a_ref_id, $a_user_id); + } - /** - * Get assignment access info for a repository object - * - * @param int $a_ref_id ref id - * @param int $a_user_id user id - * @return ilExcRepoObjAssignmentAccessInfoInterface - */ - function getAccessInfo($a_ref_id, $a_user_id) - { - include_once("./Modules/Exercise/RepoObjectAssignment/classes/class.ilExcRepoObjAssignmentAccessInfo.php"); - return ilExcRepoObjAssignmentAccessInfo::getInfo($a_ref_id, $a_user_id); - } + /** + * Get assignment access info for a repository object + * + * @param int $a_ref_id ref id + * @param int $a_user_id user id + * @return ilExcRepoObjAssignmentAccessInfoInterface + */ + public function getAccessInfo($a_ref_id, $a_user_id) + { + include_once("./Modules/Exercise/RepoObjectAssignment/classes/class.ilExcRepoObjAssignmentAccessInfo.php"); + return ilExcRepoObjAssignmentAccessInfo::getInfo($a_ref_id, $a_user_id); + } - /** - * Is access denied - * - * @param int $a_ref_id ref id - * @param int $a_user_id user id - * @return bool - */ - function isGranted($a_ref_id, $a_user_id) - { - include_once("./Modules/Exercise/RepoObjectAssignment/classes/class.ilExcRepoObjAssignmentAccessInfo.php"); - $info = ilExcRepoObjAssignmentAccessInfo::getInfo($a_ref_id, $a_user_id); - return !$info->isGranted(); - } - - - - -} \ No newline at end of file + /** + * Is access denied + * + * @param int $a_ref_id ref id + * @param int $a_user_id user id + * @return bool + */ + public function isGranted($a_ref_id, $a_user_id) + { + include_once("./Modules/Exercise/RepoObjectAssignment/classes/class.ilExcRepoObjAssignmentAccessInfo.php"); + $info = ilExcRepoObjAssignmentAccessInfo::getInfo($a_ref_id, $a_user_id); + return !$info->isGranted(); + } +} diff --git a/Modules/Exercise/RepoObjectAssignment/classes/class.ilExcRepoObjAssignmentAccessInfo.php b/Modules/Exercise/RepoObjectAssignment/classes/class.ilExcRepoObjAssignmentAccessInfo.php index 567f3103edf97c0f889640a0115908c30402744f..caa23974b0494c576bda698e085b2018e29108b0 100644 --- a/Modules/Exercise/RepoObjectAssignment/classes/class.ilExcRepoObjAssignmentAccessInfo.php +++ b/Modules/Exercise/RepoObjectAssignment/classes/class.ilExcRepoObjAssignmentAccessInfo.php @@ -11,110 +11,102 @@ include_once("./Modules/Exercise/RepoObjectAssignment/interfaces/interface.ilExc */ class ilExcRepoObjAssignmentAccessInfo implements ilExcRepoObjAssignmentAccessInfoInterface { - /** - * @var bool - */ - protected $is_granted; - - /** - * @var string[] - */ - protected $not_granted_reasons; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * Constructor - * @param bool $a_is_granted - * @param string[] $a_not_granted_reasons - */ - protected function __construct($a_is_granted, array $a_not_granted_reasons) - { - global $DIC; - - $this->access = $DIC->access(); - $this->is_granted = $a_is_granted; - $this->not_granted_reasons = $a_not_granted_reasons; - - $this->lng = $DIC->language(); - } - - - /** - * Is access granted due to exercise assignment conditions? - * - * @return int assignment id - */ - public function isGranted() - { - return $this->is_granted; - } - - /** - * Get reasons why access is not granted. - * - * @return string[] - */ - public function getNotGrantedReasons() - { - return $this->not_granted_reasons; - } - - /** - * - * - * @param int $a_ref_id ref id - * @param int $a_user_id user id - * @return ilExcRepoObjAssignmentAccessInfo - */ - static public function getInfo($a_ref_id, $a_user_id) - { - global $DIC; - - include_once("./Modules/Exercise/RepoObjectAssignment/classes/class.ilExcRepoObjAssignment.php"); - $repo_obj_ass = ilExcRepoObjAssignment::getInstance(); - $lng = $DIC->language(); - $access = $DIC->access(); - - // if this object is not assigned to any assignment, we do not deny the access - $assignment_info = $repo_obj_ass->getAssignmentInfoOfObj($a_ref_id, $a_user_id); - if (count($assignment_info) == 0) - { - return new self(true, []); - } - - $granted = true; - $reasons = []; - foreach ($assignment_info as $i) - { - if (!$i->isUserSubmission()) - { - $has_write_permission = false; - foreach ($i->getReadableRefIds() as $exc_ref_id) - { - if ($access->checkAccessOfUser($a_user_id, "write", "", $exc_ref_id)) - { - $has_write_permission = true; - } - } - if (!$has_write_permission) - { - $granted = false; - $reasons[0] = $lng->txt("exc_obj_not_submitted_by_user"); - } - } - } - - return new self($granted, $reasons); - } - - -} \ No newline at end of file + /** + * @var bool + */ + protected $is_granted; + + /** + * @var string[] + */ + protected $not_granted_reasons; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * Constructor + * @param bool $a_is_granted + * @param string[] $a_not_granted_reasons + */ + protected function __construct($a_is_granted, array $a_not_granted_reasons) + { + global $DIC; + + $this->access = $DIC->access(); + $this->is_granted = $a_is_granted; + $this->not_granted_reasons = $a_not_granted_reasons; + + $this->lng = $DIC->language(); + } + + + /** + * Is access granted due to exercise assignment conditions? + * + * @return int assignment id + */ + public function isGranted() + { + return $this->is_granted; + } + + /** + * Get reasons why access is not granted. + * + * @return string[] + */ + public function getNotGrantedReasons() + { + return $this->not_granted_reasons; + } + + /** + * + * + * @param int $a_ref_id ref id + * @param int $a_user_id user id + * @return ilExcRepoObjAssignmentAccessInfo + */ + public static function getInfo($a_ref_id, $a_user_id) + { + global $DIC; + + include_once("./Modules/Exercise/RepoObjectAssignment/classes/class.ilExcRepoObjAssignment.php"); + $repo_obj_ass = ilExcRepoObjAssignment::getInstance(); + $lng = $DIC->language(); + $access = $DIC->access(); + + // if this object is not assigned to any assignment, we do not deny the access + $assignment_info = $repo_obj_ass->getAssignmentInfoOfObj($a_ref_id, $a_user_id); + if (count($assignment_info) == 0) { + return new self(true, []); + } + + $granted = true; + $reasons = []; + foreach ($assignment_info as $i) { + if (!$i->isUserSubmission()) { + $has_write_permission = false; + foreach ($i->getReadableRefIds() as $exc_ref_id) { + if ($access->checkAccessOfUser($a_user_id, "write", "", $exc_ref_id)) { + $has_write_permission = true; + } + } + if (!$has_write_permission) { + $granted = false; + $reasons[0] = $lng->txt("exc_obj_not_submitted_by_user"); + } + } + } + + return new self($granted, $reasons); + } +} diff --git a/Modules/Exercise/RepoObjectAssignment/classes/class.ilExcRepoObjAssignmentInfo.php b/Modules/Exercise/RepoObjectAssignment/classes/class.ilExcRepoObjAssignmentInfo.php index 0f3fc1ea689d095a0af5b5fd5a44d16539102c26..2854d9fb9654de93add9c72678311a4d023722e7 100644 --- a/Modules/Exercise/RepoObjectAssignment/classes/class.ilExcRepoObjAssignmentInfo.php +++ b/Modules/Exercise/RepoObjectAssignment/classes/class.ilExcRepoObjAssignmentInfo.php @@ -11,174 +11,178 @@ include_once("./Modules/Exercise/RepoObjectAssignment/interfaces/interface.ilExc */ class ilExcRepoObjAssignmentInfo implements ilExcRepoObjAssignmentInfoInterface { - /** - * @var int - */ - protected $id; - - /** - * @var int[] - */ - protected $ref_ids; - - /** - * @var string - */ - protected $title; - - /** - * @var ilExAssignmentTypes - */ - protected $ass_types; - - /** - * @var bool - */ - protected $is_user_submission; - - /** - * @var string - */ - protected $exc_title; - - /** - * @var int - */ - protected $exc_id; - - /** - * Constructor - * - * @param int $a_assignment_id - * @param int[] $a_ref_ids ref ids - */ - protected function __construct($a_assignment_id, $a_assignment_title, $a_ref_ids, $is_user_submission, - $a_exc_id, $a_exc_title) - { - $this->id = $a_assignment_id; - $this->title = $a_assignment_title; - $this->ref_ids = $a_ref_ids; - $this->ass_types = ilExAssignmentTypes::getInstance(); - $this->is_user_submission = $is_user_submission; - $this->exc_id = $a_exc_id; - $this->exc_title = $a_exc_title; - } - - - /** - * @inheritdoc - */ - public function getId() - { - return $this->id; - } - - /** - * @inheritdoc - */ - public function getTitle() - { - return $this->title; - } - - - /** - * @inheritdoc - */ - public function getLinks() - { - $links = []; - foreach ($this->ref_ids as $ref_id) - { - $links[$ref_id] = ilLink::_getLink($ref_id, "exc", array(), "_" . $this->id); - } - return $links; - } - - /** - * @inheritdoc - */ - public function isUserSubmission() - { - return $this->is_user_submission; - } - - /** - * @inheritdoc - */ - public function getExerciseId() - { - return $this->exc_id; - } - - /** - * @inheritdoc - */ - public function getExerciseTitle() - { - return $this->exc_title; - } - - /** - * @inheritdoc - */ - function getReadableRefIds() - { - return $this->ref_ids; - } - - - /** - * Get all info objects for a ref id of an repo object - * - * @param int $a_ref_id ref id - * @param int $a_user_id user id - * @return ilExcRepoObjAssignmentInfo[] - */ - static public function getInfo($a_ref_id, $a_user_id) - { - global $DIC; - - $access = $DIC->access(); - - include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssignmentTypes.php"); - $ass_types = ilExAssignmentTypes::getInstance(); - - $repos_ass_type_ids = $ass_types->getIdsForSubmissionType(ilExSubmission::TYPE_REPO_OBJECT); - include_once("./Modules/Exercise/classes/class.ilExSubmission.php"); - $submissions = ilExSubmission::getSubmissionsForFilename($a_ref_id, $repos_ass_type_ids); - - $ass_info = array(); - foreach ($submissions as $s) - { - $ass_type = $ass_types->getById($s["type"]); - - // @todo note: this currently only works, if submissions are assigned to the team (like team wikis) - // get team of user - include_once "Modules/Exercise/classes/class.ilExAssignmentTeam.php"; - $team = ilExAssignmentTeam::getInstanceByUserId($s["ass_id"], $a_user_id); - $is_user_submission = ($team->getId() > 0 && $team->getId() == $s["team_id"]) - ? true - : false; - - - // determine all readable ref ids of the exercise - $ref_ids = ilObject::_getAllReferences($s["exc_id"]); - $readable_ref_ids = array(); - foreach ($ref_ids as $ref_id) - { - if ($a_user_id > 0 && !$access->checkAccessOfUser($a_user_id, "read", "", $ref_id)) - { - continue; - } - $readable_ref_ids[] = $ref_id; - } - $ass_info[] = new self($s["ass_id"], $s["title"], $readable_ref_ids, $is_user_submission, - $s["exc_id"], ilObject::_lookupTitle($s["exc_id"])); - } - return $ass_info; - - } - - -} \ No newline at end of file + /** + * @var int + */ + protected $id; + + /** + * @var int[] + */ + protected $ref_ids; + + /** + * @var string + */ + protected $title; + + /** + * @var ilExAssignmentTypes + */ + protected $ass_types; + + /** + * @var bool + */ + protected $is_user_submission; + + /** + * @var string + */ + protected $exc_title; + + /** + * @var int + */ + protected $exc_id; + + /** + * Constructor + * + * @param int $a_assignment_id + * @param int[] $a_ref_ids ref ids + */ + protected function __construct( + $a_assignment_id, + $a_assignment_title, + $a_ref_ids, + $is_user_submission, + $a_exc_id, + $a_exc_title + ) { + $this->id = $a_assignment_id; + $this->title = $a_assignment_title; + $this->ref_ids = $a_ref_ids; + $this->ass_types = ilExAssignmentTypes::getInstance(); + $this->is_user_submission = $is_user_submission; + $this->exc_id = $a_exc_id; + $this->exc_title = $a_exc_title; + } + + + /** + * @inheritdoc + */ + public function getId() + { + return $this->id; + } + + /** + * @inheritdoc + */ + public function getTitle() + { + return $this->title; + } + + + /** + * @inheritdoc + */ + public function getLinks() + { + $links = []; + foreach ($this->ref_ids as $ref_id) { + $links[$ref_id] = ilLink::_getLink($ref_id, "exc", array(), "_" . $this->id); + } + return $links; + } + + /** + * @inheritdoc + */ + public function isUserSubmission() + { + return $this->is_user_submission; + } + + /** + * @inheritdoc + */ + public function getExerciseId() + { + return $this->exc_id; + } + + /** + * @inheritdoc + */ + public function getExerciseTitle() + { + return $this->exc_title; + } + + /** + * @inheritdoc + */ + public function getReadableRefIds() + { + return $this->ref_ids; + } + + + /** + * Get all info objects for a ref id of an repo object + * + * @param int $a_ref_id ref id + * @param int $a_user_id user id + * @return ilExcRepoObjAssignmentInfo[] + */ + public static function getInfo($a_ref_id, $a_user_id) + { + global $DIC; + + $access = $DIC->access(); + + include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssignmentTypes.php"); + $ass_types = ilExAssignmentTypes::getInstance(); + + $repos_ass_type_ids = $ass_types->getIdsForSubmissionType(ilExSubmission::TYPE_REPO_OBJECT); + include_once("./Modules/Exercise/classes/class.ilExSubmission.php"); + $submissions = ilExSubmission::getSubmissionsForFilename($a_ref_id, $repos_ass_type_ids); + + $ass_info = array(); + foreach ($submissions as $s) { + $ass_type = $ass_types->getById($s["type"]); + + // @todo note: this currently only works, if submissions are assigned to the team (like team wikis) + // get team of user + include_once "Modules/Exercise/classes/class.ilExAssignmentTeam.php"; + $team = ilExAssignmentTeam::getInstanceByUserId($s["ass_id"], $a_user_id); + $is_user_submission = ($team->getId() > 0 && $team->getId() == $s["team_id"]) + ? true + : false; + + + // determine all readable ref ids of the exercise + $ref_ids = ilObject::_getAllReferences($s["exc_id"]); + $readable_ref_ids = array(); + foreach ($ref_ids as $ref_id) { + if ($a_user_id > 0 && !$access->checkAccessOfUser($a_user_id, "read", "", $ref_id)) { + continue; + } + $readable_ref_ids[] = $ref_id; + } + $ass_info[] = new self( + $s["ass_id"], + $s["title"], + $readable_ref_ids, + $is_user_submission, + $s["exc_id"], + ilObject::_lookupTitle($s["exc_id"]) + ); + } + return $ass_info; + } +} diff --git a/Modules/Exercise/RepoObjectAssignment/interfaces/interface.ilExcRepoObjAssignmentAccessInfoInterface.php b/Modules/Exercise/RepoObjectAssignment/interfaces/interface.ilExcRepoObjAssignmentAccessInfoInterface.php index 1b81387f95a45228bd0f3d04faa52e1a5862d4fe..fd20e73e1ac4a4fe304e437d92ed5918366199b9 100644 --- a/Modules/Exercise/RepoObjectAssignment/interfaces/interface.ilExcRepoObjAssignmentAccessInfoInterface.php +++ b/Modules/Exercise/RepoObjectAssignment/interfaces/interface.ilExcRepoObjAssignmentAccessInfoInterface.php @@ -9,17 +9,17 @@ */ interface ilExcRepoObjAssignmentAccessInfoInterface { - /** - * Is access granted due to exercise assignment conditions? - * - * @return int assignment id - */ - function isGranted(); + /** + * Is access granted due to exercise assignment conditions? + * + * @return int assignment id + */ + public function isGranted(); - /** - * Get reasons why access is not granted. - * - * @return string[] - */ - function getNotGrantedReasons(); -} \ No newline at end of file + /** + * Get reasons why access is not granted. + * + * @return string[] + */ + public function getNotGrantedReasons(); +} diff --git a/Modules/Exercise/RepoObjectAssignment/interfaces/interface.ilExcRepoObjAssignmentInfoInterface.php b/Modules/Exercise/RepoObjectAssignment/interfaces/interface.ilExcRepoObjAssignmentInfoInterface.php index 23ef4d09591d9722ef193a6ef39e06eef519b252..724b6b334356145c0e1f370e7944036623cd0c70 100644 --- a/Modules/Exercise/RepoObjectAssignment/interfaces/interface.ilExcRepoObjAssignmentInfoInterface.php +++ b/Modules/Exercise/RepoObjectAssignment/interfaces/interface.ilExcRepoObjAssignmentInfoInterface.php @@ -9,54 +9,53 @@ */ interface ilExcRepoObjAssignmentInfoInterface { - /** - * Get assignment id - * - * @return int assignment id - */ - function getId(); - - /** - * Get assignment title - * - * @return int assignment id - */ - function getTitle(); - - /** - * Get readable link urls to the assignment (key is the ref id) - * - * @return string[] assignment link url - */ - function getLinks(); - - /** - * Check if this object has been submitted by the user provided or its team. If not, the - * repository object is related to an assignment, but has been submitted by another user/team. - * - * @return bool - */ - function isUserSubmission(); - - /** - * Get exercise id - * - * @return int - */ - function getExerciseId(); - - /** - * Get exercise title - * - * @return string - */ - function getExerciseTitle(); - - /** - * Get readable ref IDs - * - * @return int[] - */ - function getReadableRefIds(); - -} \ No newline at end of file + /** + * Get assignment id + * + * @return int assignment id + */ + public function getId(); + + /** + * Get assignment title + * + * @return int assignment id + */ + public function getTitle(); + + /** + * Get readable link urls to the assignment (key is the ref id) + * + * @return string[] assignment link url + */ + public function getLinks(); + + /** + * Check if this object has been submitted by the user provided or its team. If not, the + * repository object is related to an assignment, but has been submitted by another user/team. + * + * @return bool + */ + public function isUserSubmission(); + + /** + * Get exercise id + * + * @return int + */ + public function getExerciseId(); + + /** + * Get exercise title + * + * @return string + */ + public function getExerciseTitle(); + + /** + * Get readable ref IDs + * + * @return int[] + */ + public function getReadableRefIds(); +} diff --git a/Modules/Exercise/RepoObjectAssignment/interfaces/interface.ilExcRepoObjAssignmentInterface.php b/Modules/Exercise/RepoObjectAssignment/interfaces/interface.ilExcRepoObjAssignmentInterface.php index e137f81f0e4af076b476b7c2150717f370324af3..0e00266c86bb98aa41f67de5ae2a0c519c4ce27b 100644 --- a/Modules/Exercise/RepoObjectAssignment/interfaces/interface.ilExcRepoObjAssignmentInterface.php +++ b/Modules/Exercise/RepoObjectAssignment/interfaces/interface.ilExcRepoObjAssignmentInterface.php @@ -9,22 +9,21 @@ */ interface ilExcRepoObjAssignmentInterface { - /** - * Get assignment(s) info of repository object - * - * @param int $a_ref_id ref id - * @param int $a_user_id user id - * @return ilExcRepoObjAssignmentInfoInterface[] - */ - function getAssignmentInfoOfObj($a_ref_id, $a_user_id); + /** + * Get assignment(s) info of repository object + * + * @param int $a_ref_id ref id + * @param int $a_user_id user id + * @return ilExcRepoObjAssignmentInfoInterface[] + */ + public function getAssignmentInfoOfObj($a_ref_id, $a_user_id); - /** - * Get assignment access info for a repository object - * - * @param int $a_ref_id - * @param int $a_user_id - * @return ilExcRepoObjAssignmentAccessInfoInterface - */ - function isGranted($a_ref_id, $a_user_id); - -} \ No newline at end of file + /** + * Get assignment access info for a repository object + * + * @param int $a_ref_id + * @param int $a_user_id + * @return ilExcRepoObjAssignmentAccessInfoInterface + */ + public function isGranted($a_ref_id, $a_user_id); +} diff --git a/Modules/Exercise/classes/BackgroundTasks/class.ilDownloadSubmissionsBackgroundTask.php b/Modules/Exercise/classes/BackgroundTasks/class.ilDownloadSubmissionsBackgroundTask.php index 28dc2dd80b60e11d8c7a7e41edeb816a7105dde9..ed7eee0730b3cad2310c413f1d19d2464f568a56 100644 --- a/Modules/Exercise/classes/BackgroundTasks/class.ilDownloadSubmissionsBackgroundTask.php +++ b/Modules/Exercise/classes/BackgroundTasks/class.ilDownloadSubmissionsBackgroundTask.php @@ -3,133 +3,131 @@ use ILIAS\BackgroundTasks\Implementation\Bucket\BasicBucket; - /** * Download submissions and feedback for exercises. * @author Jesús López */ class ilDownloadSubmissionsBackgroundTask { - /** - * @var int - */ - protected $exc_ref_id; - - /** - * @var int - */ - protected $exc_id; - - /** - * @var int|null - */ - protected $ass_id; - - /** - * @var int|null - */ - protected $participant_id; - - /** - * @var int - */ - protected $user_id; - - /** - * @var \ILIAS\BackgroundTasks\Task\TaskFactory - */ - protected $task_factory = null; - - /** - * @var \ILIAS\BackgroundTasks\TaskManager - */ - protected $task_manager = null; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var - */ - private $logger = null; - - /** - * Constructor - * @param integer $a_usr_id - * @param integer $a_exc_ref_id - * @param integer $a_exc_id - * @param integer $a_ass_id - * @param integer $a_participant_id - */ - public function __construct($a_usr_id, $a_exc_ref_id, $a_exc_id, $a_ass_id, $a_participant_id) - { - global $DIC; - - $this->user_id = $a_usr_id; - $this->exc_ref_id = $a_exc_ref_id; - $this->exc_id = $a_exc_id; - $this->ass_id = $a_ass_id; - $this->participant_id = $a_participant_id; - - $this->task_factory = $DIC->backgroundTasks()->taskFactory(); - $this->task_manager = $DIC->backgroundTasks()->taskManager(); - $this->logger = $DIC->logger()->exc(); - - } - - public function run() - { - $bucket = new BasicBucket(); - $bucket->setUserId($this->user_id); - - $this->logger->debug("* Create task 'collect_data_job' using the following values:"); - $this->logger->debug("job class = ". ilExerciseManagementCollectFilesJob::class); - $this->logger->debug("exc_id = ".$this->exc_id.", exc_ref_id = ".$this->exc_ref_id.", ass_id = ".(int)$this->ass_id.", participant_id = ".(int)$this->participant_id.", user_id = ".(int)$this->user_id); - - $collect_data_job = $this->task_factory->createTask(ilExerciseManagementCollectFilesJob::class, - [ - (int)$this->exc_id, - (int)$this->exc_ref_id, - (int)$this->ass_id, - (int)$this->participant_id, - (int)$this->user_id - ] - ); - - $this->logger->debug("* Create task 'zip job' using the following values:"); - $this->logger->debug("job class = ". ilSubmissionsZipJob::class); - $this->logger->debug("sending as input the task called->collect_data_job"); - - $zip_job = $this->task_factory->createTask(ilSubmissionsZipJob::class, [$collect_data_job]); - - if($this->participant_id > 0) { - $download_name = ilExSubmission::getDirectoryNameFromUserData($this->participant_id); - $bucket->setTitle($this->getParticipantBucketTitle()); - } else { - $download_name = ilUtil::getASCIIFilename(ilExAssignment::lookupTitle($this->ass_id)); - $bucket->setTitle($download_name); - } - - - $this->logger->debug("* Create task 'download_interaction' using the following values:"); - $this->logger->debug("job class = ". ilExDownloadSubmissionsZipInteraction::class); - $this->logger->debug("download_name which is the same as bucket title = ".$download_name." + the zip_job task"); - // see comments here -> https://github.com/leifos-gmbh/ILIAS/commit/df6fc44a4c85da33bd8dd5b391a396349e7fa68f - $download_interaction = $this->task_factory->createTask(ilExDownloadSubmissionsZipInteraction::class,[$zip_job, $download_name]); - - //download name - $bucket->setTask($download_interaction); - $this->task_manager->run($bucket); - return true; - } - - protected function getParticipantBucketTitle() - { - $name = ilObjUser::_lookupName($this->participant_id); - $title = ucfirst($name['lastname']).", ".ucfirst($name['firstname']); - return $title; - } - -} \ No newline at end of file + /** + * @var int + */ + protected $exc_ref_id; + + /** + * @var int + */ + protected $exc_id; + + /** + * @var int|null + */ + protected $ass_id; + + /** + * @var int|null + */ + protected $participant_id; + + /** + * @var int + */ + protected $user_id; + + /** + * @var \ILIAS\BackgroundTasks\Task\TaskFactory + */ + protected $task_factory = null; + + /** + * @var \ILIAS\BackgroundTasks\TaskManager + */ + protected $task_manager = null; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var + */ + private $logger = null; + + /** + * Constructor + * @param integer $a_usr_id + * @param integer $a_exc_ref_id + * @param integer $a_exc_id + * @param integer $a_ass_id + * @param integer $a_participant_id + */ + public function __construct($a_usr_id, $a_exc_ref_id, $a_exc_id, $a_ass_id, $a_participant_id) + { + global $DIC; + + $this->user_id = $a_usr_id; + $this->exc_ref_id = $a_exc_ref_id; + $this->exc_id = $a_exc_id; + $this->ass_id = $a_ass_id; + $this->participant_id = $a_participant_id; + + $this->task_factory = $DIC->backgroundTasks()->taskFactory(); + $this->task_manager = $DIC->backgroundTasks()->taskManager(); + $this->logger = $DIC->logger()->exc(); + } + + public function run() + { + $bucket = new BasicBucket(); + $bucket->setUserId($this->user_id); + + $this->logger->debug("* Create task 'collect_data_job' using the following values:"); + $this->logger->debug("job class = " . ilExerciseManagementCollectFilesJob::class); + $this->logger->debug("exc_id = " . $this->exc_id . ", exc_ref_id = " . $this->exc_ref_id . ", ass_id = " . (int) $this->ass_id . ", participant_id = " . (int) $this->participant_id . ", user_id = " . (int) $this->user_id); + + $collect_data_job = $this->task_factory->createTask( + ilExerciseManagementCollectFilesJob::class, + [ + (int) $this->exc_id, + (int) $this->exc_ref_id, + (int) $this->ass_id, + (int) $this->participant_id, + (int) $this->user_id + ] + ); + + $this->logger->debug("* Create task 'zip job' using the following values:"); + $this->logger->debug("job class = " . ilSubmissionsZipJob::class); + $this->logger->debug("sending as input the task called->collect_data_job"); + + $zip_job = $this->task_factory->createTask(ilSubmissionsZipJob::class, [$collect_data_job]); + + if ($this->participant_id > 0) { + $download_name = ilExSubmission::getDirectoryNameFromUserData($this->participant_id); + $bucket->setTitle($this->getParticipantBucketTitle()); + } else { + $download_name = ilUtil::getASCIIFilename(ilExAssignment::lookupTitle($this->ass_id)); + $bucket->setTitle($download_name); + } + + + $this->logger->debug("* Create task 'download_interaction' using the following values:"); + $this->logger->debug("job class = " . ilExDownloadSubmissionsZipInteraction::class); + $this->logger->debug("download_name which is the same as bucket title = " . $download_name . " + the zip_job task"); + // see comments here -> https://github.com/leifos-gmbh/ILIAS/commit/df6fc44a4c85da33bd8dd5b391a396349e7fa68f + $download_interaction = $this->task_factory->createTask(ilExDownloadSubmissionsZipInteraction::class, [$zip_job, $download_name]); + + //download name + $bucket->setTask($download_interaction); + $this->task_manager->run($bucket); + return true; + } + + protected function getParticipantBucketTitle() + { + $name = ilObjUser::_lookupName($this->participant_id); + $title = ucfirst($name['lastname']) . ", " . ucfirst($name['firstname']); + return $title; + } +} diff --git a/Modules/Exercise/classes/BackgroundTasks/class.ilExDownloadSubmissionsZipInteraction.php b/Modules/Exercise/classes/BackgroundTasks/class.ilExDownloadSubmissionsZipInteraction.php index 48f1afbd8991d4a2f35b0c75d257eb6a0d052674..a9b235f5e499c0bbf68141774af4adf2f552ee41 100644 --- a/Modules/Exercise/classes/BackgroundTasks/class.ilExDownloadSubmissionsZipInteraction.php +++ b/Modules/Exercise/classes/BackgroundTasks/class.ilExDownloadSubmissionsZipInteraction.php @@ -12,101 +12,107 @@ use ILIAS\Filesystem\Util\LegacyPathHelper; /** * @author Jesús López */ -class ilExDownloadSubmissionsZipInteraction extends AbstractUserInteraction { - - const OPTION_DOWNLOAD = 'download'; - const OPTION_CANCEL = 'cancel'; - - /** - * @var \Monolog\Logger - */ - private $logger = null; - - - public function __construct() { - $this->logger = $GLOBALS['DIC']->logger()->exc(); - } - - - /** - * @inheritdoc - */ - public function getInputTypes() { - return [ - new SingleType(StringValue::class), - new SingleType(StringValue::class), - ]; - } - - - /** - * @inheritDoc - */ - public function getRemoveOption() { - return new UserInteractionOption('remove', self::OPTION_CANCEL); - } - - - /** - * @inheritDoc - */ - public function getOutputType() { - return new SingleType(StringValue::class); - } - - - /** - * @inheritDoc - */ - public function getOptions(array $input) { - return [ - new UserInteractionOption('download', self::OPTION_DOWNLOAD), - ]; - } - - - /** - * @inheritDoc - */ - public function interaction(array $input, Option $user_selected_option, Bucket $bucket) { - global $DIC; - $download_name = $input[0]; //directory name. - $zip_name = $input[1]; // zip job - - $this->logger->debug("Interaction -> input[0] download name MUST BE FULL PATH=> ".$download_name->getValue()); - $this->logger->debug("Interaction -> input[1] zip name MUST BE THE NAME WITHOUT EXTENSION. => ".$zip_name->getValue()); - - if ($user_selected_option->getValue() != self::OPTION_DOWNLOAD) { - $this->logger->info('Download canceled'); - // delete zip file - $filesystem = $DIC->filesystem()->temp(); - try { - $path = LegacyPathHelper::createRelativePath($zip_name->getValue()); - } catch (InvalidArgumentException $e) { - $path = null; - } - if (!is_null($path) && $filesystem->has($path)) { - $filesystem->deleteDir(dirname($path)); - } - - return $input; - } - - $this->logger->info("Delivering File."); - - - $zip_name = $zip_name->getValue(); - - $ending = substr($zip_name, -4); - if($ending != ".zip"){ - $zip_name .= ".zip"; - $this->logger->info("Add .zip extension"); - } - - //Download_name->getValue should return the complete path to the file - //Zip name is just an string - ilFileDelivery::deliverFileAttached($download_name->getValue(), $zip_name); - - return $input; - } +class ilExDownloadSubmissionsZipInteraction extends AbstractUserInteraction +{ + const OPTION_DOWNLOAD = 'download'; + const OPTION_CANCEL = 'cancel'; + + /** + * @var \Monolog\Logger + */ + private $logger = null; + + + public function __construct() + { + $this->logger = $GLOBALS['DIC']->logger()->exc(); + } + + + /** + * @inheritdoc + */ + public function getInputTypes() + { + return [ + new SingleType(StringValue::class), + new SingleType(StringValue::class), + ]; + } + + + /** + * @inheritDoc + */ + public function getRemoveOption() + { + return new UserInteractionOption('remove', self::OPTION_CANCEL); + } + + + /** + * @inheritDoc + */ + public function getOutputType() + { + return new SingleType(StringValue::class); + } + + + /** + * @inheritDoc + */ + public function getOptions(array $input) + { + return [ + new UserInteractionOption('download', self::OPTION_DOWNLOAD), + ]; + } + + + /** + * @inheritDoc + */ + public function interaction(array $input, Option $user_selected_option, Bucket $bucket) + { + global $DIC; + $download_name = $input[0]; //directory name. + $zip_name = $input[1]; // zip job + + $this->logger->debug("Interaction -> input[0] download name MUST BE FULL PATH=> " . $download_name->getValue()); + $this->logger->debug("Interaction -> input[1] zip name MUST BE THE NAME WITHOUT EXTENSION. => " . $zip_name->getValue()); + + if ($user_selected_option->getValue() != self::OPTION_DOWNLOAD) { + $this->logger->info('Download canceled'); + // delete zip file + $filesystem = $DIC->filesystem()->temp(); + try { + $path = LegacyPathHelper::createRelativePath($zip_name->getValue()); + } catch (InvalidArgumentException $e) { + $path = null; + } + if (!is_null($path) && $filesystem->has($path)) { + $filesystem->deleteDir(dirname($path)); + } + + return $input; + } + + $this->logger->info("Delivering File."); + + + $zip_name = $zip_name->getValue(); + + $ending = substr($zip_name, -4); + if ($ending != ".zip") { + $zip_name .= ".zip"; + $this->logger->info("Add .zip extension"); + } + + //Download_name->getValue should return the complete path to the file + //Zip name is just an string + ilFileDelivery::deliverFileAttached($download_name->getValue(), $zip_name); + + return $input; + } } diff --git a/Modules/Exercise/classes/BackgroundTasks/class.ilExerciseManagementCollectFilesJob.php b/Modules/Exercise/classes/BackgroundTasks/class.ilExerciseManagementCollectFilesJob.php index 035dad2ff81a51dafb07c2f35e63d5325a57c33b..2e630643bbf033aba25ce9937dbbad80688d0dea 100644 --- a/Modules/Exercise/classes/BackgroundTasks/class.ilExerciseManagementCollectFilesJob.php +++ b/Modules/Exercise/classes/BackgroundTasks/class.ilExerciseManagementCollectFilesJob.php @@ -16,644 +16,609 @@ use ILIAS\BackgroundTasks\Implementation\Values\ScalarValues\IntegerValue; */ class ilExerciseManagementCollectFilesJob extends AbstractJob { - /** - * @var ilLogger - */ - private $logger = null; - /** - * @var string - */ - protected $target_directory; - protected $submissions_directory; - protected $assignment; - protected $user_id; - protected $exercise_id; - protected $exercise_ref_id; - protected $temp_dir; - protected $lng; - protected $sanitized_title; //sanitized file name/sheet title - protected $excel; //ilExcel - protected $criteria_items; //array - protected $title_columns; - protected $ass_types_with_files; //TODO will be deprecated when use the new assignment type interface - protected $participant_id; - - const FBK_DIRECTORY = "Feedback_files"; - const LINK_COLOR = "0,0,255"; - const BG_COLOR = "255,255,255"; - //Column number incremented in ilExcel - const PARTICIPANT_LASTNAME_COLUMN = 0; - const PARTICIPANT_FIRSTNAME_COLUMN = 1; - const PARTICIPANT_LOGIN_COLUMN = 2; - const SUBMISSION_DATE_COLUMN = 3; - const FIRST_DEFAULT_SUBMIT_COLUMN = 4; - const FIRST_DEFAULT_REVIEW_COLUMN = 5; - - /** - * Constructor - */ - public function __construct() - { - global $DIC; - $this->lng = $DIC->language(); - $this->lng->loadLanguageModule('exc'); - //TODO will be deprecated when use the new assignment type interface - $this->ass_types_with_files = array( - ilExAssignment::TYPE_UPLOAD, - ilExAssignment::TYPE_UPLOAD_TEAM, - ilExAssignment::TYPE_BLOG, - ilExAssignment::TYPE_PORTFOLIO - ); - $this->logger = $DIC->logger()->exc(); - } - - /** - * @return array - */ - public function getInputTypes() - { - return - [ - new SingleType(IntegerValue::class), - new SingleType(IntegerValue::class), - new SingleType(IntegerValue::class), - new SingleType(IntegerValue::class), - new SingleType(IntegerValue::class) - ]; - } - - /** - * @return SingleType - */ - public function getOutputType() - { - return new SingleType(StringValue::class); - } - - public function isStateless() - { - return true; - } - - /** - * run the job - * @param array $input - * @param Observer $observer - * @return StringValue - */ - public function run(array $input, Observer $observer) - { - $this->exercise_id = $input[0]->getValue(); - $this->exercise_ref_id = $input[1]->getValue(); - $assignment_id = $input[2]->getValue(); - $participant_id = $input[3]->getValue(); - $this->user_id = $input[4]->getValue(); - - //if we have assignment - if($assignment_id > 0) - { - $this->collectAssignmentData($assignment_id); - $final_directory = $this->target_directory; - } - - if($participant_id > 0) - { - $this->participant_id = $participant_id; - $assignments = ilExAssignment::getInstancesByExercise($this->exercise_id); - foreach($assignments as $assignment) - { - $this->collectAssignmentData($assignment->getId()); - } - $final_directory = $this->temp_dir.DIRECTORY_SEPARATOR.ilExSubmission::getDirectoryNameFromUserData($participant_id); - - } - - $out = new StringValue(); - $out->setValue($final_directory); - return $out; - - } - - /** - * Copy a file in the Feedback_files directory - * TODO use the new filesystem. - * @param $a_directory string - * @param $a_file string - */ - public function copyFileToSubDirectory($a_directory, $a_file) - { - $dir = $this->target_directory."/".$a_directory; - - if(!is_dir($dir)) - { - ilUtil::createDirectory($dir); - } - - copy($a_file, $dir."/".basename($a_file)); - - /*global $DIC; - $fs = $DIC->filesystem(); - - $fs->storage()->copy($a_file, $this->temp_dir."/".basename($a_file));*/ - } - - /** - * @inheritdoc - */ - public function getExpectedTimeOfTaskInSeconds() - { - return 30; - } - - /** - * Set the Excel column titles. - */ - protected function addColumnTitles() - { - $col = 0; - foreach($this->title_columns as $title) - { - $this->excel->setCell(1, $col, $title); - $col++; - } - } - - /** - * @todo refactor to new file system access - * Create unique temp directory - */ - protected function createUniqueTempDirectory() - { - $this->temp_dir = ilUtil::ilTempnam(); - ilUtil::makeDirParents($this->temp_dir); - } - - /** - * Create the directory with the assignment title. - */ - protected function createTargetDirectory() - { - $path = $this->temp_dir.DIRECTORY_SEPARATOR; - if($this->participant_id > 0) { - $user_dir = ilExSubmission::getDirectoryNameFromUserData($this->participant_id); - $path .= $user_dir.DIRECTORY_SEPARATOR; - } - $this->target_directory = $path.$this->sanitized_title; - - ilUtil::makeDirParents($this->target_directory); - } - /** - * Create the directory with the assignment title. - */ - protected function createSubmissionsDirectory() - { - $this->logger->debug("lang key => ".$this->lng->getLangKey()); - $this->submissions_directory = $this->target_directory.DIRECTORY_SEPARATOR.$this->lng->txt("exc_ass_submission_zip"); - ilUtil::createDirectory($this->submissions_directory); - } - - /** - * Store the zip file which contains all submission files in the target directory. - * TODO -> put the reference of the original code. - * Possible TODO -> extract this to another BT job. - */ - function collectSubmissionFiles() - { - $members = array(); - - $exercise = new ilObjExercise($this->exercise_id, false); - - if($this->participant_id > 0) { - $exc_members_id = array($this->participant_id); - } else { - $exc_members_id = $exercise->members_obj->getMembers(); - } - - $filter = new ilExerciseMembersFilter($this->exercise_ref_id, $exc_members_id, $this->user_id); - $exc_members_id = $filter->filterParticipantsByAccess(); - - foreach( $exc_members_id as $member_id) - { - $submission = new ilExSubmission($this->assignment, $member_id); - $submission->updateTutorDownloadTime(); - - // get member object (ilObjUser) - if (ilObject::_exists($member_id)) - { - // adding file metadata - foreach($submission->getFiles() as $file) - { - $members[$file["user_id"]]["files"][$file["returned_id"]] = $file; - } - - $tmp_obj =& ilObjectFactory::getInstanceByObjId($member_id); - $members[$member_id]["name"] = $tmp_obj->getFirstname() . " " . $tmp_obj->getLastname(); - unset($tmp_obj); - } - } - - ilExSubmission::downloadAllAssignmentFiles($this->assignment, $members, $this->submissions_directory); - } - - /** - * @param $a_ass_type string - * @param $a_has_fbk bool - * @return bool - */ - protected function isExcelNeeded($a_ass_type, $a_has_fbk) - { - if($a_ass_type == ilExAssignment::TYPE_TEXT) { - return true; - } elseif($a_has_fbk && $a_ass_type != ilExAssignment::TYPE_UPLOAD_TEAM){ - return true; - } - return false; - } - - /** - * Add criteria data to the excel. - * @param $feedback_giver - * @param $participant_id - * @param $row - * @param $col - */ - protected function addCriteriaToExcel($feedback_giver,$participant_id, $row, $col) - { - $submission = new ilExSubmission($this->assignment,$participant_id); - - //Possible TODO: This getPeerReviewValues doesn't return always the same array structure then the client classes have - //to deal with this. Use only one data structure will avoid this extra work. - //values can be [19] => "blablablab" or ["text"] => "blablabla" - $values = $submission->getPeerReview()->getPeerReviewValues($feedback_giver, $participant_id); - - foreach($this->criteria_items as $item) - { - $col++; - - //Criteria without catalog doesn't have ID nor TITLE. The criteria instance is given via "type" ilExcCriteria::getInstanceByType - $crit_id = $item->getId(); - $crit_type = $item->getType(); - $crit_title = $item->getTitle(); - if($crit_title == ""){ - $crit_title = $item->getTranslatedType(); - } - - if(!in_array($crit_title, $this->title_columns)) { - $this->title_columns[] = $crit_title; - } - switch ($crit_type){ - case 'bool': - if($values[$crit_id] == 1){ - $this->excel->setCell($row,$col,$this->lng->txt("yes")); - } elseif($values[$crit_id] == -1){ - $this->excel->setCell($row,$col,$this->lng->txt("no")); - } - break; - case 'rating': - /* - * Get the rating data from the DB in the current less expensive way. - * assignment_id -> used in il_rating.obj_id - * object type as string -> used in il_rating.obj_type - * participant id -> il_rating.sub_obj_id - * "peer_" + criteria_id -> il_rating.sub_obj_type (peer or e.g. peer_12) - * peer id -> il_rating.user_id - */ - // Possible TODO: refactor ilExAssignment->getPeerReviewCriteriaCatalogueItems somehow to avoid client - // classes to deal with ilExCriteria instances with persistence (by id) or instances on the fly (by type) - $sub_obj_type = "peer"; - if($crit_id) { - $sub_obj_type .= "_".$crit_id; - } - $rating = ilRating::getRatingForUserAndObject( - $this->assignment->getId(), - 'ass', - $participant_id, - $sub_obj_type, - $feedback_giver - ); - if($rating_int = round((int)$rating)) - { - $this->excel->setCell($row,$col, $rating_int); - } - break; - case 'text': - //again another check for criteria id (if instantiated via type) - if($crit_id) { - $this->excel->setCell($row,$col, $values[$crit_id]); - } else { - $this->excel->setCell($row,$col, $values['text']); - } - break; - case 'file': - if($crit_id) { - $crit_file_obj = ilExcCriteriaFile::getInstanceById($crit_id); - } else { - $crit_file_obj = ilExcCriteriaFile::getInstanceByType($crit_type); - } - $crit_file_obj->setPeerReviewContext($this->assignment, $feedback_giver, $participant_id); - $files = $crit_file_obj->getFiles(); - - $extra_crit_column = 0; - foreach($files as $file) - { - if($extra_crit_column) { - $this->title_columns[] = $crit_title."_".$extra_crit_column; - } - $extra_crit_column++; - $this->copyFileToSubDirectory(self::FBK_DIRECTORY,$file); - $this->excel->setCell($row,$col, "./".self::FBK_DIRECTORY.DIRECTORY_SEPARATOR.basename($file)); - $this->excel->addLink($row, $col, './'.self::FBK_DIRECTORY.DIRECTORY_SEPARATOR.basename($file)); - $this->excel->setColors($this->excel->getCoordByColumnAndRow($col,$row), self::BG_COLOR,self::LINK_COLOR); - } - break; - } - } - } - - /** - * Get the number of max amount of files submitted by a single user in the assignment. - * Used to add columns to the excel. - * @param $a_obj_id - * @param $a_ass_id - * @return mixed - */ - public function getExtraColumnsForSubmissionFiles($a_obj_id, $a_ass_id) - { - global $DIC; - $ilDB = $DIC->database(); - - $and = ""; - if($this->participant_id > 0) { - $and = " AND user_id = ".$this->participant_id; - } - - $query = "SELECT MAX(max_num) AS max". - " FROM (SELECT COUNT(user_id) AS max_num FROM exc_returned". - " WHERE obj_id=".$a_obj_id.". AND ass_id=".$a_ass_id.$and." AND mimetype IS NOT NULL". - " GROUP BY user_id) AS COUNTS"; - - $set = $ilDB->query($query); - $row = $ilDB->fetchAssoc($set); - return $row['max']; - } - - /** - * Mapping the links to use them on the excel. - * @param $a_row int - * @param $a_col int - * @param $a_submission ilExSubmission - * @param $a_submission_file array - */ - public function addLink($a_row, $a_col, $a_submission_file) - { - $user_id = $a_submission_file['user_id']; - $targetdir = ilExSubmission::getDirectoryNameFromUserData($user_id); - - $filepath = './'.$this->lng->txt("exc_ass_submission_zip").DIRECTORY_SEPARATOR.$targetdir.DIRECTORY_SEPARATOR; - switch ($this->assignment->getType()) - { - case ilExAssignment::TYPE_UPLOAD: - $filepath .= $a_submission_file['filetitle']; - break; - - case ilExAssignment::TYPE_BLOG: - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - $wsp_tree = new ilWorkspaceTree($user_id); - // #12939 - if(!$wsp_tree->getRootId()) - { - $wsp_tree->createTreeForUser($user_id); - } - $node = $wsp_tree->getNodeData((int)$a_submission_file['filetitle']); - $filepath .= "blog_".$node['obj_id'].DIRECTORY_SEPARATOR."index.html"; - break; - - case ilExAssignment::TYPE_PORTFOLIO: - $filepath .= "prt_".$a_submission_file['filetitle'].DIRECTORY_SEPARATOR."index.html"; - break; - - default: - $filepath = ""; - } - $this->excel->addLink($a_row, $a_col, $filepath); - } - - protected function collectAssignmentData($assignment_id) - { - $ass_has_feedback = false; - $ass_has_criteria = false; - - //assignment object - $this->assignment = new ilExAssignment($assignment_id); - $assignment_type = $this->assignment->getType(); - - //Sanitized title for excel file and target directory. - $this->sanitized_title = ilUtil::getASCIIFilename($this->assignment->getTitle()); - - // directories - if(!isset($this->temp_dir)) { - $this->createUniqueTempDirectory(); - } - $this->createTargetDirectory(); - - //Collect submission files if needed by assignment type. - if(in_array($assignment_type,$this->ass_types_with_files)) { - $this->createSubmissionsDirectory(); - $this->collectSubmissionFiles(); - } - - if($this->assignment->getPeerReview()) { - $ass_has_feedback = true; - //obj to get the reviews in the foreach below. - $peer_review = new ilExPeerReview($this->assignment); - //default start column for revisions. - $first_excel_column_for_review = self::FIRST_DEFAULT_REVIEW_COLUMN; - } - - /** - * TODO refactor when 0 bugs: - * - extract the excel related code from this method. - * - incrementing/decrementing columns/rows management - */ - if($this->isExcelNeeded($assignment_type, $ass_has_feedback)) - { - // PhpSpreadsheet object - include_once "./Services/Excel/classes/class.ilExcel.php"; - $this->excel = new ilExcel(); - - //Excel sheet title - $this->excel->addSheet($this->sanitized_title); - - //add common excel Columns - #25585 - $this->title_columns = array( - $this->lng->txt('lastname'), - $this->lng->txt('firstname'), - $this->lng->txt('login'), - $this->lng->txt('exc_last_submission') - ); - switch($assignment_type) - { - case ilExAssignment::TYPE_TEXT: - $this->title_columns[] = $this->lng->txt("exc_submission_text"); - break; - case ilExAssignment::TYPE_UPLOAD: - $num_columns_submission = $this->getExtraColumnsForSubmissionFiles($this->exercise_id,$assignment_id); - if($num_columns_submission > 1){ - for($i = 1; $i <= $num_columns_submission; $i++) - { - $this->title_columns[] = $this->lng->txt("exc_submission_file")." ".$i; - } - } else { - $this->title_columns[] = $this->lng->txt("exc_submission_file"); - } - - $first_excel_column_for_review += $num_columns_submission -1; - break; - default: - $this->title_columns[] = $this->lng->txt("exc_submission"); - break; - } - if($ass_has_feedback) - { - $this->title_columns[] = $this->lng->txt("exc_peer_review_giver"); - $this->title_columns[] = $this->lng->txt('exc_last_submission'); - } - - //criteria - //Notice:getPeerReviewCriteriaCatalogueItems can return just an empty instance without data. - if($this->criteria_items = $this->assignment->getPeerReviewCriteriaCatalogueItems()){ - $ass_has_criteria = true; - } - - if($this->participant_id > 0) { - $participants = array($this->participant_id); - } else { - $participants = $this->getAssignmentMembersIds(); - } - - $filter = new ilExerciseMembersFilter($this->exercise_ref_id, $participants, $this->user_id); - $participants = $filter->filterParticipantsByAccess(); - - //SET THE ROW AT SECOND POSITION TO START ENTERING VALUES BELOW THE TITLE. - $row = 2; - // Fill the excel - foreach($participants as $participant_id) - { - $submission = new ilExSubmission($this->assignment,$participant_id); - $submission_files = $submission->getFiles(); - - if($submission_files) - { - $participant_name = ilObjUser::_lookupName($participant_id); - $this->excel->setCell($row, self::PARTICIPANT_LASTNAME_COLUMN, $participant_name['lastname']); - $this->excel->setCell($row, self::PARTICIPANT_FIRSTNAME_COLUMN, $participant_name['firstname']); - $this->excel->setCell($row, self::PARTICIPANT_LOGIN_COLUMN, $participant_name['login']); - - //Get the submission Text - if (!in_array($assignment_type, $this->ass_types_with_files)) - { - foreach($submission_files as $submission_file) - { - $this->excel->setCell($row, self::SUBMISSION_DATE_COLUMN, $submission_file['timestamp']); - $this->excel->setCell($row, self::FIRST_DEFAULT_SUBMIT_COLUMN, $submission_file['atext']); - } - } - else - { - $col = self::FIRST_DEFAULT_SUBMIT_COLUMN; - foreach ($submission_files as $submission_file) - { - $this->excel->setCell($row, self::SUBMISSION_DATE_COLUMN, $submission_file['timestamp']); - - if($assignment_type == ilExAssignment::TYPE_PORTFOLIO || $assignment_type == ilExAssignment::TYPE_BLOG) { - $this->excel->setCell($row, $col, $this->lng->txt("open")); - - } else{ - $this->excel->setCell($row, $col, $submission_file['filetitle']); - } - $this->excel->setColors($this->excel->getCoordByColumnAndRow($col+1, $row), self::BG_COLOR, self::LINK_COLOR); - $this->addLink($row, $col, $submission_file); - $col++; //does not affect blogs and portfolios. - } - } - - if($ass_has_feedback) - { - if($col < $first_excel_column_for_review) { - $col = $first_excel_column_for_review; - } - $reviews = $peer_review->getPeerReviewsByPeerId($participant_id); - - //extra lines - $current_review_row = 0; - foreach($reviews as $review) - { - //not all reviews are done, we check it via date of review. - if($review['tstamp']) - { - $current_review_row++; - if($current_review_row > 1) - { - for($i = 0; $i < $first_excel_column_for_review; $i++) - { - $cell_to_copy = $this->excel->getCell($row,$i); - // $i-1 because ilExcel setCell increments the column by 1 - $this->excel->setCell($row +1, $i-1, $cell_to_copy); - if($i > self::FIRST_DEFAULT_SUBMIT_COLUMN){ - $this->excel->setColors($this->excel->getCoordByColumnAndRow($i,$row+1), self::BG_COLOR,self::LINK_COLOR); - } - } - ++$row; - } - - $feedback_giver = $review['giver_id']; // user who made the review. - - $feedback_giver_name = ilObjUser::_lookupName($feedback_giver); - - $this->excel->setCell( - $row, - $col, - $feedback_giver_name['lastname'] . ", " . $feedback_giver_name['firstname'] . " [" . $feedback_giver_name['login'] . "]" - ); - - $this->excel->setCell($row, $col+1, $review['tstamp']); - - if($ass_has_criteria) - { - $this->addCriteriaToExcel($feedback_giver, $participant_id, $row, $col+1); - } - } - } - } - - $row++; - } - } - - $this->addColumnTitles(); - $this->excel->writeToFile($this->target_directory."/".$this->sanitized_title); - } - - } - - // get ONLY the members ids for this assignment - public function getAssignmentMembersIds() - { - global $DIC; - - $ilDB = $DIC->database(); - $members = array(); - - $set = $ilDB->query("SELECT usr_id". - " FROM exc_mem_ass_status". - " WHERE ass_id = ".$ilDB->quote($this->assignment->getId(), "integer")); - - while ($rec = $ilDB->fetchAssoc($set)) - { - $members[] = $rec['usr_id']; - } - - return $members; - } -} \ No newline at end of file + /** + * @var ilLogger + */ + private $logger = null; + /** + * @var string + */ + protected $target_directory; + protected $submissions_directory; + protected $assignment; + protected $user_id; + protected $exercise_id; + protected $exercise_ref_id; + protected $temp_dir; + protected $lng; + protected $sanitized_title; //sanitized file name/sheet title + protected $excel; //ilExcel + protected $criteria_items; //array + protected $title_columns; + protected $ass_types_with_files; //TODO will be deprecated when use the new assignment type interface + protected $participant_id; + + const FBK_DIRECTORY = "Feedback_files"; + const LINK_COLOR = "0,0,255"; + const BG_COLOR = "255,255,255"; + //Column number incremented in ilExcel + const PARTICIPANT_LASTNAME_COLUMN = 0; + const PARTICIPANT_FIRSTNAME_COLUMN = 1; + const PARTICIPANT_LOGIN_COLUMN = 2; + const SUBMISSION_DATE_COLUMN = 3; + const FIRST_DEFAULT_SUBMIT_COLUMN = 4; + const FIRST_DEFAULT_REVIEW_COLUMN = 5; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + $this->lng = $DIC->language(); + $this->lng->loadLanguageModule('exc'); + //TODO will be deprecated when use the new assignment type interface + $this->ass_types_with_files = array( + ilExAssignment::TYPE_UPLOAD, + ilExAssignment::TYPE_UPLOAD_TEAM, + ilExAssignment::TYPE_BLOG, + ilExAssignment::TYPE_PORTFOLIO + ); + $this->logger = $DIC->logger()->exc(); + } + + /** + * @return array + */ + public function getInputTypes() + { + return + [ + new SingleType(IntegerValue::class), + new SingleType(IntegerValue::class), + new SingleType(IntegerValue::class), + new SingleType(IntegerValue::class), + new SingleType(IntegerValue::class) + ]; + } + + /** + * @return SingleType + */ + public function getOutputType() + { + return new SingleType(StringValue::class); + } + + public function isStateless() + { + return true; + } + + /** + * run the job + * @param array $input + * @param Observer $observer + * @return StringValue + */ + public function run(array $input, Observer $observer) + { + $this->exercise_id = $input[0]->getValue(); + $this->exercise_ref_id = $input[1]->getValue(); + $assignment_id = $input[2]->getValue(); + $participant_id = $input[3]->getValue(); + $this->user_id = $input[4]->getValue(); + + //if we have assignment + if ($assignment_id > 0) { + $this->collectAssignmentData($assignment_id); + $final_directory = $this->target_directory; + } + + if ($participant_id > 0) { + $this->participant_id = $participant_id; + $assignments = ilExAssignment::getInstancesByExercise($this->exercise_id); + foreach ($assignments as $assignment) { + $this->collectAssignmentData($assignment->getId()); + } + $final_directory = $this->temp_dir . DIRECTORY_SEPARATOR . ilExSubmission::getDirectoryNameFromUserData($participant_id); + } + + $out = new StringValue(); + $out->setValue($final_directory); + return $out; + } + + /** + * Copy a file in the Feedback_files directory + * TODO use the new filesystem. + * @param $a_directory string + * @param $a_file string + */ + public function copyFileToSubDirectory($a_directory, $a_file) + { + $dir = $this->target_directory . "/" . $a_directory; + + if (!is_dir($dir)) { + ilUtil::createDirectory($dir); + } + + copy($a_file, $dir . "/" . basename($a_file)); + + /*global $DIC; + $fs = $DIC->filesystem(); + + $fs->storage()->copy($a_file, $this->temp_dir."/".basename($a_file));*/ + } + + /** + * @inheritdoc + */ + public function getExpectedTimeOfTaskInSeconds() + { + return 30; + } + + /** + * Set the Excel column titles. + */ + protected function addColumnTitles() + { + $col = 0; + foreach ($this->title_columns as $title) { + $this->excel->setCell(1, $col, $title); + $col++; + } + } + + /** + * @todo refactor to new file system access + * Create unique temp directory + */ + protected function createUniqueTempDirectory() + { + $this->temp_dir = ilUtil::ilTempnam(); + ilUtil::makeDirParents($this->temp_dir); + } + + /** + * Create the directory with the assignment title. + */ + protected function createTargetDirectory() + { + $path = $this->temp_dir . DIRECTORY_SEPARATOR; + if ($this->participant_id > 0) { + $user_dir = ilExSubmission::getDirectoryNameFromUserData($this->participant_id); + $path .= $user_dir . DIRECTORY_SEPARATOR; + } + $this->target_directory = $path . $this->sanitized_title; + + ilUtil::makeDirParents($this->target_directory); + } + /** + * Create the directory with the assignment title. + */ + protected function createSubmissionsDirectory() + { + $this->logger->debug("lang key => " . $this->lng->getLangKey()); + $this->submissions_directory = $this->target_directory . DIRECTORY_SEPARATOR . $this->lng->txt("exc_ass_submission_zip"); + ilUtil::createDirectory($this->submissions_directory); + } + + /** + * Store the zip file which contains all submission files in the target directory. + * TODO -> put the reference of the original code. + * Possible TODO -> extract this to another BT job. + */ + public function collectSubmissionFiles() + { + $members = array(); + + $exercise = new ilObjExercise($this->exercise_id, false); + + if ($this->participant_id > 0) { + $exc_members_id = array($this->participant_id); + } else { + $exc_members_id = $exercise->members_obj->getMembers(); + } + + $filter = new ilExerciseMembersFilter($this->exercise_ref_id, $exc_members_id, $this->user_id); + $exc_members_id = $filter->filterParticipantsByAccess(); + + foreach ($exc_members_id as $member_id) { + $submission = new ilExSubmission($this->assignment, $member_id); + $submission->updateTutorDownloadTime(); + + // get member object (ilObjUser) + if (ilObject::_exists($member_id)) { + // adding file metadata + foreach ($submission->getFiles() as $file) { + $members[$file["user_id"]]["files"][$file["returned_id"]] = $file; + } + + $tmp_obj =&ilObjectFactory::getInstanceByObjId($member_id); + $members[$member_id]["name"] = $tmp_obj->getFirstname() . " " . $tmp_obj->getLastname(); + unset($tmp_obj); + } + } + + ilExSubmission::downloadAllAssignmentFiles($this->assignment, $members, $this->submissions_directory); + } + + /** + * @param $a_ass_type string + * @param $a_has_fbk bool + * @return bool + */ + protected function isExcelNeeded($a_ass_type, $a_has_fbk) + { + if ($a_ass_type == ilExAssignment::TYPE_TEXT) { + return true; + } elseif ($a_has_fbk && $a_ass_type != ilExAssignment::TYPE_UPLOAD_TEAM) { + return true; + } + return false; + } + + /** + * Add criteria data to the excel. + * @param $feedback_giver + * @param $participant_id + * @param $row + * @param $col + */ + protected function addCriteriaToExcel($feedback_giver, $participant_id, $row, $col) + { + $submission = new ilExSubmission($this->assignment, $participant_id); + + //Possible TODO: This getPeerReviewValues doesn't return always the same array structure then the client classes have + //to deal with this. Use only one data structure will avoid this extra work. + //values can be [19] => "blablablab" or ["text"] => "blablabla" + $values = $submission->getPeerReview()->getPeerReviewValues($feedback_giver, $participant_id); + + foreach ($this->criteria_items as $item) { + $col++; + + //Criteria without catalog doesn't have ID nor TITLE. The criteria instance is given via "type" ilExcCriteria::getInstanceByType + $crit_id = $item->getId(); + $crit_type = $item->getType(); + $crit_title = $item->getTitle(); + if ($crit_title == "") { + $crit_title = $item->getTranslatedType(); + } + + if (!in_array($crit_title, $this->title_columns)) { + $this->title_columns[] = $crit_title; + } + switch ($crit_type) { + case 'bool': + if ($values[$crit_id] == 1) { + $this->excel->setCell($row, $col, $this->lng->txt("yes")); + } elseif ($values[$crit_id] == -1) { + $this->excel->setCell($row, $col, $this->lng->txt("no")); + } + break; + case 'rating': + /* + * Get the rating data from the DB in the current less expensive way. + * assignment_id -> used in il_rating.obj_id + * object type as string -> used in il_rating.obj_type + * participant id -> il_rating.sub_obj_id + * "peer_" + criteria_id -> il_rating.sub_obj_type (peer or e.g. peer_12) + * peer id -> il_rating.user_id + */ + // Possible TODO: refactor ilExAssignment->getPeerReviewCriteriaCatalogueItems somehow to avoid client + // classes to deal with ilExCriteria instances with persistence (by id) or instances on the fly (by type) + $sub_obj_type = "peer"; + if ($crit_id) { + $sub_obj_type .= "_" . $crit_id; + } + $rating = ilRating::getRatingForUserAndObject( + $this->assignment->getId(), + 'ass', + $participant_id, + $sub_obj_type, + $feedback_giver + ); + if ($rating_int = round((int) $rating)) { + $this->excel->setCell($row, $col, $rating_int); + } + break; + case 'text': + //again another check for criteria id (if instantiated via type) + if ($crit_id) { + $this->excel->setCell($row, $col, $values[$crit_id]); + } else { + $this->excel->setCell($row, $col, $values['text']); + } + break; + case 'file': + if ($crit_id) { + $crit_file_obj = ilExcCriteriaFile::getInstanceById($crit_id); + } else { + $crit_file_obj = ilExcCriteriaFile::getInstanceByType($crit_type); + } + $crit_file_obj->setPeerReviewContext($this->assignment, $feedback_giver, $participant_id); + $files = $crit_file_obj->getFiles(); + + $extra_crit_column = 0; + foreach ($files as $file) { + if ($extra_crit_column) { + $this->title_columns[] = $crit_title . "_" . $extra_crit_column; + } + $extra_crit_column++; + $this->copyFileToSubDirectory(self::FBK_DIRECTORY, $file); + $this->excel->setCell($row, $col, "./" . self::FBK_DIRECTORY . DIRECTORY_SEPARATOR . basename($file)); + $this->excel->addLink($row, $col, './' . self::FBK_DIRECTORY . DIRECTORY_SEPARATOR . basename($file)); + $this->excel->setColors($this->excel->getCoordByColumnAndRow($col, $row), self::BG_COLOR, self::LINK_COLOR); + } + break; + } + } + } + + /** + * Get the number of max amount of files submitted by a single user in the assignment. + * Used to add columns to the excel. + * @param $a_obj_id + * @param $a_ass_id + * @return mixed + */ + public function getExtraColumnsForSubmissionFiles($a_obj_id, $a_ass_id) + { + global $DIC; + $ilDB = $DIC->database(); + + $and = ""; + if ($this->participant_id > 0) { + $and = " AND user_id = " . $this->participant_id; + } + + $query = "SELECT MAX(max_num) AS max" . + " FROM (SELECT COUNT(user_id) AS max_num FROM exc_returned" . + " WHERE obj_id=" . $a_obj_id . ". AND ass_id=" . $a_ass_id . $and . " AND mimetype IS NOT NULL" . + " GROUP BY user_id) AS COUNTS"; + + $set = $ilDB->query($query); + $row = $ilDB->fetchAssoc($set); + return $row['max']; + } + + /** + * Mapping the links to use them on the excel. + * @param $a_row int + * @param $a_col int + * @param $a_submission ilExSubmission + * @param $a_submission_file array + */ + public function addLink($a_row, $a_col, $a_submission_file) + { + $user_id = $a_submission_file['user_id']; + $targetdir = ilExSubmission::getDirectoryNameFromUserData($user_id); + + $filepath = './' . $this->lng->txt("exc_ass_submission_zip") . DIRECTORY_SEPARATOR . $targetdir . DIRECTORY_SEPARATOR; + switch ($this->assignment->getType()) { + case ilExAssignment::TYPE_UPLOAD: + $filepath .= $a_submission_file['filetitle']; + break; + + case ilExAssignment::TYPE_BLOG: + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + $wsp_tree = new ilWorkspaceTree($user_id); + // #12939 + if (!$wsp_tree->getRootId()) { + $wsp_tree->createTreeForUser($user_id); + } + $node = $wsp_tree->getNodeData((int) $a_submission_file['filetitle']); + $filepath .= "blog_" . $node['obj_id'] . DIRECTORY_SEPARATOR . "index.html"; + break; + + case ilExAssignment::TYPE_PORTFOLIO: + $filepath .= "prt_" . $a_submission_file['filetitle'] . DIRECTORY_SEPARATOR . "index.html"; + break; + + default: + $filepath = ""; + } + $this->excel->addLink($a_row, $a_col, $filepath); + } + + protected function collectAssignmentData($assignment_id) + { + $ass_has_feedback = false; + $ass_has_criteria = false; + + //assignment object + $this->assignment = new ilExAssignment($assignment_id); + $assignment_type = $this->assignment->getType(); + + //Sanitized title for excel file and target directory. + $this->sanitized_title = ilUtil::getASCIIFilename($this->assignment->getTitle()); + + // directories + if (!isset($this->temp_dir)) { + $this->createUniqueTempDirectory(); + } + $this->createTargetDirectory(); + + //Collect submission files if needed by assignment type. + if (in_array($assignment_type, $this->ass_types_with_files)) { + $this->createSubmissionsDirectory(); + $this->collectSubmissionFiles(); + } + + if ($this->assignment->getPeerReview()) { + $ass_has_feedback = true; + //obj to get the reviews in the foreach below. + $peer_review = new ilExPeerReview($this->assignment); + //default start column for revisions. + $first_excel_column_for_review = self::FIRST_DEFAULT_REVIEW_COLUMN; + } + + /** + * TODO refactor when 0 bugs: + * - extract the excel related code from this method. + * - incrementing/decrementing columns/rows management + */ + if ($this->isExcelNeeded($assignment_type, $ass_has_feedback)) { + // PhpSpreadsheet object + include_once "./Services/Excel/classes/class.ilExcel.php"; + $this->excel = new ilExcel(); + + //Excel sheet title + $this->excel->addSheet($this->sanitized_title); + + //add common excel Columns + #25585 + $this->title_columns = array( + $this->lng->txt('lastname'), + $this->lng->txt('firstname'), + $this->lng->txt('login'), + $this->lng->txt('exc_last_submission') + ); + switch ($assignment_type) { + case ilExAssignment::TYPE_TEXT: + $this->title_columns[] = $this->lng->txt("exc_submission_text"); + break; + case ilExAssignment::TYPE_UPLOAD: + $num_columns_submission = $this->getExtraColumnsForSubmissionFiles($this->exercise_id, $assignment_id); + if ($num_columns_submission > 1) { + for ($i = 1; $i <= $num_columns_submission; $i++) { + $this->title_columns[] = $this->lng->txt("exc_submission_file") . " " . $i; + } + } else { + $this->title_columns[] = $this->lng->txt("exc_submission_file"); + } + + $first_excel_column_for_review += $num_columns_submission -1; + break; + default: + $this->title_columns[] = $this->lng->txt("exc_submission"); + break; + } + if ($ass_has_feedback) { + $this->title_columns[] = $this->lng->txt("exc_peer_review_giver"); + $this->title_columns[] = $this->lng->txt('exc_last_submission'); + } + + //criteria + //Notice:getPeerReviewCriteriaCatalogueItems can return just an empty instance without data. + if ($this->criteria_items = $this->assignment->getPeerReviewCriteriaCatalogueItems()) { + $ass_has_criteria = true; + } + + if ($this->participant_id > 0) { + $participants = array($this->participant_id); + } else { + $participants = $this->getAssignmentMembersIds(); + } + + $filter = new ilExerciseMembersFilter($this->exercise_ref_id, $participants, $this->user_id); + $participants = $filter->filterParticipantsByAccess(); + + //SET THE ROW AT SECOND POSITION TO START ENTERING VALUES BELOW THE TITLE. + $row = 2; + // Fill the excel + foreach ($participants as $participant_id) { + $submission = new ilExSubmission($this->assignment, $participant_id); + $submission_files = $submission->getFiles(); + + if ($submission_files) { + $participant_name = ilObjUser::_lookupName($participant_id); + $this->excel->setCell($row, self::PARTICIPANT_LASTNAME_COLUMN, $participant_name['lastname']); + $this->excel->setCell($row, self::PARTICIPANT_FIRSTNAME_COLUMN, $participant_name['firstname']); + $this->excel->setCell($row, self::PARTICIPANT_LOGIN_COLUMN, $participant_name['login']); + + //Get the submission Text + if (!in_array($assignment_type, $this->ass_types_with_files)) { + foreach ($submission_files as $submission_file) { + $this->excel->setCell($row, self::SUBMISSION_DATE_COLUMN, $submission_file['timestamp']); + $this->excel->setCell($row, self::FIRST_DEFAULT_SUBMIT_COLUMN, $submission_file['atext']); + } + } else { + $col = self::FIRST_DEFAULT_SUBMIT_COLUMN; + foreach ($submission_files as $submission_file) { + $this->excel->setCell($row, self::SUBMISSION_DATE_COLUMN, $submission_file['timestamp']); + + if ($assignment_type == ilExAssignment::TYPE_PORTFOLIO || $assignment_type == ilExAssignment::TYPE_BLOG) { + $this->excel->setCell($row, $col, $this->lng->txt("open")); + } else { + $this->excel->setCell($row, $col, $submission_file['filetitle']); + } + $this->excel->setColors($this->excel->getCoordByColumnAndRow($col+1, $row), self::BG_COLOR, self::LINK_COLOR); + $this->addLink($row, $col, $submission_file); + $col++; //does not affect blogs and portfolios. + } + } + + if ($ass_has_feedback) { + if ($col < $first_excel_column_for_review) { + $col = $first_excel_column_for_review; + } + $reviews = $peer_review->getPeerReviewsByPeerId($participant_id); + + //extra lines + $current_review_row = 0; + foreach ($reviews as $review) { + //not all reviews are done, we check it via date of review. + if ($review['tstamp']) { + $current_review_row++; + if ($current_review_row > 1) { + for ($i = 0; $i < $first_excel_column_for_review; $i++) { + $cell_to_copy = $this->excel->getCell($row, $i); + // $i-1 because ilExcel setCell increments the column by 1 + $this->excel->setCell($row +1, $i-1, $cell_to_copy); + if ($i > self::FIRST_DEFAULT_SUBMIT_COLUMN) { + $this->excel->setColors($this->excel->getCoordByColumnAndRow($i, $row+1), self::BG_COLOR, self::LINK_COLOR); + } + } + ++$row; + } + + $feedback_giver = $review['giver_id']; // user who made the review. + + $feedback_giver_name = ilObjUser::_lookupName($feedback_giver); + + $this->excel->setCell( + $row, + $col, + $feedback_giver_name['lastname'] . ", " . $feedback_giver_name['firstname'] . " [" . $feedback_giver_name['login'] . "]" + ); + + $this->excel->setCell($row, $col+1, $review['tstamp']); + + if ($ass_has_criteria) { + $this->addCriteriaToExcel($feedback_giver, $participant_id, $row, $col+1); + } + } + } + } + + $row++; + } + } + + $this->addColumnTitles(); + $this->excel->writeToFile($this->target_directory . "/" . $this->sanitized_title); + } + } + + // get ONLY the members ids for this assignment + public function getAssignmentMembersIds() + { + global $DIC; + + $ilDB = $DIC->database(); + $members = array(); + + $set = $ilDB->query("SELECT usr_id" . + " FROM exc_mem_ass_status" . + " WHERE ass_id = " . $ilDB->quote($this->assignment->getId(), "integer")); + + while ($rec = $ilDB->fetchAssoc($set)) { + $members[] = $rec['usr_id']; + } + + return $members; + } +} diff --git a/Modules/Exercise/classes/BackgroundTasks/class.ilSubmissionsZipJob.php b/Modules/Exercise/classes/BackgroundTasks/class.ilSubmissionsZipJob.php index e82e9484d9e14f0c0f54729ec956a036465d087a..64d7262da02df2d47c31c28f6071b48897d9032f 100644 --- a/Modules/Exercise/classes/BackgroundTasks/class.ilSubmissionsZipJob.php +++ b/Modules/Exercise/classes/BackgroundTasks/class.ilSubmissionsZipJob.php @@ -6,73 +6,74 @@ use ILIAS\BackgroundTasks\Implementation\Tasks\AbstractJob; use ILIAS\BackgroundTasks\Implementation\Values\ScalarValues\StringValue; /** - * Description of class class + * Description of class class * * @author Jesús López * */ class ilSubmissionsZipJob extends AbstractJob { - private $logger = null; - - - /** - * Construct - */ - public function __construct() - { - $this->logger = $GLOBALS['DIC']->logger()->exc(); - } - - /** - * @inheritDoc - */ - public function getInputTypes() - { - return - [ - new SingleType(StringValue::class) - ]; - } + private $logger = null; + + + /** + * Construct + */ + public function __construct() + { + $this->logger = $GLOBALS['DIC']->logger()->exc(); + } + + /** + * @inheritDoc + */ + public function getInputTypes() + { + return + [ + new SingleType(StringValue::class) + ]; + } - /** - * @inheritDoc - */ - public function getOutputType() - { - return new SingleType(StringValue::class); - } + /** + * @inheritDoc + */ + public function getOutputType() + { + return new SingleType(StringValue::class); + } - /** - * @inheritDoc - */ - public function isStateless() - { - return true; - } + /** + * @inheritDoc + */ + public function isStateless() + { + return true; + } - /** - * @inheritDoc - * @todo use filsystem service - */ - public function run(array $input, \ILIAS\BackgroundTasks\Observer $observer) - { - $tmpdir = $input[0]->getValue(); + /** + * @inheritDoc + * @todo use filsystem service + */ + public function run(array $input, \ILIAS\BackgroundTasks\Observer $observer) + { + $tmpdir = $input[0]->getValue(); - ilUtil::zip($tmpdir, $tmpdir.'.zip'); - - // delete temp directory - ilUtil::delDir($tmpdir); + ilUtil::zip($tmpdir, $tmpdir . '.zip'); + + // delete temp directory + ilUtil::delDir($tmpdir); - $zip_file_name = new StringValue(); - $zip_file_name->setValue($tmpdir.'.zip'); - return $zip_file_name; - } + $zip_file_name = new StringValue(); + $zip_file_name->setValue($tmpdir . '.zip'); + return $zip_file_name; + } - /** - * @inheritdoc - */ - public function getExpectedTimeOfTaskInSeconds() { - return 30; - } + /** + * @inheritdoc + */ + public function getExpectedTimeOfTaskInSeconds() + { + return 30; + } } diff --git a/Modules/Exercise/classes/class.ilAssignmentsTableGUI.php b/Modules/Exercise/classes/class.ilAssignmentsTableGUI.php index e2e9577efe0bce4cf5c6cdaf21a05167bf179f4e..5b2ed54732b9d9810efeed43f590fac36905208f 100644 --- a/Modules/Exercise/classes/class.ilAssignmentsTableGUI.php +++ b/Modules/Exercise/classes/class.ilAssignmentsTableGUI.php @@ -14,167 +14,159 @@ include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); */ class ilAssignmentsTableGUI extends ilTable2GUI { - /** - * @var ilExAssignmentTypes - */ - protected $types; + /** + * @var ilExAssignmentTypes + */ + protected $types; - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_exc_id) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_exc_id) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssignmentTypes.php"); - $this->types = ilExAssignmentTypes::getInstance(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssignmentTypes.php"); + $this->types = ilExAssignmentTypes::getInstance(); - $this->exc_id = $a_exc_id; - $this->setId("excass".$this->exc_id); - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setTitle($lng->txt("exc_assignments")); - $this->setTopCommands(true); - - // if you add pagination and disable the unlimited setting: - // fix saving of ordering of single pages! - $this->setLimit(9999); - - $this->addColumn("", "", "1", true); - $this->addColumn($this->lng->txt("title"), "title"); - $this->addColumn($this->lng->txt("exc_assignment_type"), "type"); - $this->addColumn($this->lng->txt("exc_presentation_order"), "order_val"); - $this->addColumn($this->lng->txt("exc_start_time"), "start_time"); - $this->addColumn($this->lng->txt("exc_deadline"), "deadline"); - $this->addColumn($this->lng->txt("exc_mandatory"), "mandatory"); - $this->addColumn($this->lng->txt("exc_peer_review"), "peer"); - $this->addColumn($this->lng->txt("exc_instruction"), "", "30%"); - $this->addColumn($this->lng->txt("actions")); - - $this->setDefaultOrderField("val_order"); - $this->setDefaultOrderDirection("asc"); - - //$this->setDefaultOrderField("name"); - //$this->setDefaultOrderDirection("asc"); - - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.exc_assignments_row.html", "Modules/Exercise"); - //$this->disable("footer"); - $this->setEnableTitle(true); - $this->setSelectAllCheckbox("id"); + $this->exc_id = $a_exc_id; + $this->setId("excass" . $this->exc_id); + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setTitle($lng->txt("exc_assignments")); + $this->setTopCommands(true); + + // if you add pagination and disable the unlimited setting: + // fix saving of ordering of single pages! + $this->setLimit(9999); + + $this->addColumn("", "", "1", true); + $this->addColumn($this->lng->txt("title"), "title"); + $this->addColumn($this->lng->txt("exc_assignment_type"), "type"); + $this->addColumn($this->lng->txt("exc_presentation_order"), "order_val"); + $this->addColumn($this->lng->txt("exc_start_time"), "start_time"); + $this->addColumn($this->lng->txt("exc_deadline"), "deadline"); + $this->addColumn($this->lng->txt("exc_mandatory"), "mandatory"); + $this->addColumn($this->lng->txt("exc_peer_review"), "peer"); + $this->addColumn($this->lng->txt("exc_instruction"), "", "30%"); + $this->addColumn($this->lng->txt("actions")); + + $this->setDefaultOrderField("val_order"); + $this->setDefaultOrderDirection("asc"); + + //$this->setDefaultOrderField("name"); + //$this->setDefaultOrderDirection("asc"); + + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.exc_assignments_row.html", "Modules/Exercise"); + //$this->disable("footer"); + $this->setEnableTitle(true); + $this->setSelectAllCheckbox("id"); - $this->addMultiCommand("confirmAssignmentsDeletion", $lng->txt("delete")); - - $this->addCommandButton("orderAssignmentsByDeadline", $lng->txt("exc_order_by_deadline")); - $this->addCommandButton("saveAssignmentOrder", $lng->txt("exc_save_order")); - //$this->addCommandButton("addAssignment", $lng->txt("exc_add_assignment")); - - include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); - include_once("./Modules/Exercise/classes/class.ilExPeerReview.php"); - $data = ilExAssignment::getAssignmentDataOfExercise($this->exc_id); - foreach($data as $idx => $row) - { - // #14450 - if($row["peer"]) - { - $data[$idx]["peer_invalid"] = true; - $peer_review = new ilExPeerReview(new ilExAssignment($row["id"])); - $peer_reviews = $peer_review->validatePeerReviewGroups(); - $data[$idx]["peer_invalid"] = $peer_reviews["invalid"]; - } - $data[$idx]["ass_type"] = $this->types->getById($row["type"]); - $data[$idx]["type"] = $data[$idx]["ass_type"]->getTitle(); - } - - $this->setData($data); - } - - function numericOrdering($a_field) - { - // #12000 - if(in_array($a_field, array("order_val", "deadline", "start_time"))) - { - return true; - } - return false; - } - - /** - * Fill table row - */ - protected function fillRow($d) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; + $this->addMultiCommand("confirmAssignmentsDeletion", $lng->txt("delete")); + + $this->addCommandButton("orderAssignmentsByDeadline", $lng->txt("exc_order_by_deadline")); + $this->addCommandButton("saveAssignmentOrder", $lng->txt("exc_save_order")); + //$this->addCommandButton("addAssignment", $lng->txt("exc_add_assignment")); + + include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); + include_once("./Modules/Exercise/classes/class.ilExPeerReview.php"); + $data = ilExAssignment::getAssignmentDataOfExercise($this->exc_id); + foreach ($data as $idx => $row) { + // #14450 + if ($row["peer"]) { + $data[$idx]["peer_invalid"] = true; + $peer_review = new ilExPeerReview(new ilExAssignment($row["id"])); + $peer_reviews = $peer_review->validatePeerReviewGroups(); + $data[$idx]["peer_invalid"] = $peer_reviews["invalid"]; + } + $data[$idx]["ass_type"] = $this->types->getById($row["type"]); + $data[$idx]["type"] = $data[$idx]["ass_type"]->getTitle(); + } + + $this->setData($data); + } + + public function numericOrdering($a_field) + { + // #12000 + if (in_array($a_field, array("order_val", "deadline", "start_time"))) { + return true; + } + return false; + } + + /** + * Fill table row + */ + protected function fillRow($d) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; - $this->tpl->setVariable("ID", $d["id"]); + $this->tpl->setVariable("ID", $d["id"]); - include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); - $ass = new ilExAssignment($d["id"]); + include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); + $ass = new ilExAssignment($d["id"]); - 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")); - } + 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 __ for each participant - include_once("./Modules/Exercise/classes/class.ilExerciseMembers.php"); - $exmem = new ilExerciseMembers($exc); - $mems = $exmem->getMembers(); - - $mems = $DIC->access()->filterUserIdsByRbacOrPositionOfCurrentUser( - 'edit_submissions_grades', - 'edit_submissions_grades', - $exercise->getRefId(), - $mems - ); - foreach ($mems as $mem) - { - $name = ilObjUser::_lookupName($mem); - $subdir = $name["lastname"]."_".$name["firstname"]."_".$name["login"]."_".$name["user_id"]; - $subdir = ilUtil::getASCIIFilename($subdir); - ilUtil::makeDir($mfdir."/".$subdir); - } - - // create the zip file - chdir($tmpdir); - $tmpzipfile = $tmpdir."/multi_feedback.zip"; - ilUtil::zip($tmpdir, $tmpzipfile, true); - chdir($cdir); - - - ilUtil::deliverFile($tmpzipfile, $deliverFilename.".zip", "", false, true); - } - - /** - * Upload multi feedback file - * - * @param array - * @return - */ - function uploadMultiFeedbackFile($a_file) - { - $lng = $this->lng; - $ilUser = $this->user; - - include_once("./Modules/Exercise/exceptions/class.ilExerciseException.php"); - if (!is_file($a_file["tmp_name"])) - { - throw new ilExerciseException($lng->txt("exc_feedback_file_could_not_be_uploaded")); - } - - include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); - $storage = new ilFSStorageExercise($this->getExerciseId(), $this->getId()); - $mfu = $storage->getMultiFeedbackUploadPath($ilUser->getId()); - ilUtil::delDir($mfu, true); - ilUtil::moveUploadedFile($a_file["tmp_name"], "multi_feedback.zip", $mfu."/"."multi_feedback.zip"); - ilUtil::unzip($mfu."/multi_feedback.zip", true); - $subdirs = ilUtil::getDir($mfu); - $subdir = "notfound"; - foreach ($subdirs as $s => $j) - { - if ($j["type"] == "dir" && substr($s, 0, 14) == "multi_feedback") - { - $subdir = $s; - } - } - - if (!is_dir($mfu."/".$subdir)) - { - throw new ilExerciseException($lng->txt("exc_no_feedback_dir_found_in_zip")); - } - - return true; - } - - /** - * Get multi feedback files (of uploader) - * - * @param int $a_user_id user id of uploader - * @return array array of user files (keys: lastname, firstname, user_id, login, file) - */ - function getMultiFeedbackFiles($a_user_id = 0) - { - $ilUser = $this->user; - - if ($a_user_id == 0) - { - $a_user_id = $ilUser->getId(); - } - - $mf_files = array(); - - // get members - $exc = new ilObjExercise($this->getExerciseId(), false); - include_once("./Modules/Exercise/classes/class.ilExerciseMembers.php"); - $exmem = new ilExerciseMembers($exc); - $mems = $exmem->getMembers(); - - // read mf directory - include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); - $storage = new ilFSStorageExercise($this->getExerciseId(), $this->getId()); - $mfu = $storage->getMultiFeedbackUploadPath($ilUser->getId()); - - // get subdir that starts with multi_feedback - $subdirs = ilUtil::getDir($mfu); - $subdir = "notfound"; - foreach ($subdirs as $s => $j) - { - if ($j["type"] == "dir" && substr($s, 0, 14) == "multi_feedback") - { - $subdir = $s; - } - } - - $items = ilUtil::getDir($mfu."/".$subdir); - foreach ($items as $k => $i) - { - // check directory - if ($i["type"] == "dir" && !in_array($k, array(".", ".."))) - { - // check if valid member id is given - $parts = explode("_", $i["entry"]); - $user_id = (int) $parts[count($parts) - 1]; - if (in_array($user_id, $mems)) - { - // read dir of user - $name = ilObjUser::_lookupName($user_id); - $files = ilUtil::getDir($mfu."/".$subdir."/".$k); - foreach ($files as $k2 => $f) - { - // append files to array - if ($f["type"] == "file" && substr($k2, 0, 1) != ".") - { - $mf_files[] = array( - "lastname" => $name["lastname"], - "firstname" => $name["firstname"], - "login" => $name["login"], - "user_id" => $name["user_id"], - "full_path" => $mfu."/".$subdir."/".$k."/".$k2, - "file" => $k2); - } - } - } - } - } - return $mf_files; - } - - /** - * Clear multi feedback directory - * - * @param array - * @return - */ - function clearMultiFeedbackDirectory() - { - $lng = $this->lng; - $ilUser = $this->user; - - include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); - $storage = new ilFSStorageExercise($this->getExerciseId(), $this->getId()); - $mfu = $storage->getMultiFeedbackUploadPath($ilUser->getId()); - ilUtil::delDir($mfu); - } - - /** - * Save multi feedback files - * - * @param - * @return - */ - function saveMultiFeedbackFiles($a_files, ilObjExercise $a_exc) - { - if($this->getExerciseId() != $a_exc->getId()) - { - return; - } - - include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); - $fstorage = new ilFSStorageExercise($this->getExerciseId(), $this->getId()); - $fstorage->create(); - - $team_map = array(); - - $mf_files = $this->getMultiFeedbackFiles(); - foreach ($mf_files as $f) - { - $user_id = $f["user_id"]; - $file_path = $f["full_path"]; - $file_name = $f["file"]; - - // if checked in confirmation gui - if ($a_files[$user_id][md5($file_name)] != "") - { - $submission = new ilExSubmission($this, $user_id); - $feedback_id = $submission->getFeedbackId(); - $noti_rec_ids = $submission->getUserIds(); - - if ($feedback_id) - { - $fb_path = $fstorage->getFeedbackPath($feedback_id); - $target = $fb_path."/".$file_name; - if (is_file($target)) - { - unlink($target); - } - // rename file - rename($file_path, $target); - - if ($noti_rec_ids) - { - foreach($noti_rec_ids as $user_id) - { - $member_status = $this->getMemberStatus($user_id); - $member_status->setFeedback(true); - $member_status->update(); - } - - $a_exc->sendFeedbackFileNotification($file_name, $noti_rec_ids, - (int) $this->getId()); - } - } - } - } - - $this->clearMultiFeedbackDirectory(); - } - - - - - /** - * Handle calendar entries for deadline(s) - * - * @param string $a_event - */ - protected function handleCalendarEntries($a_event) - { - $ilAppEventHandler = $this->app_event_handler; - - $dl_id = $this->getId()."0"; - $fbdl_id = $this->getId()."1"; - - $context_ids = array($dl_id, $fbdl_id); - $apps = array(); - - if($a_event != "delete") - { - include_once "Services/Calendar/classes/class.ilCalendarAppointmentTemplate.php"; - - // deadline or relative deadline given - if($this->getDeadline() || $this->getDeadlineMode() == ilExAssignment::DEADLINE_RELATIVE) - { - $app = new ilCalendarAppointmentTemplate($dl_id); - $app->setTranslationType(IL_CAL_TRANSLATION_SYSTEM); - $app->setSubtitle("cal_exc_deadline"); - $app->setTitle($this->getTitle()); - $app->setFullday(false); - // note: in the case of a relative deadline this will be set to 0 / 1970...) - // see ilCalendarScheduleFilterExercise for appointment modification - $app->setStart(new ilDateTime($this->getDeadline(), IL_CAL_UNIX)); - - $apps[] = $app; - } - - if($this->getPeerReview() && - $this->getPeerReviewDeadline()) - { - $app = new ilCalendarAppointmentTemplate($fbdl_id); - $app->setTranslationType(IL_CAL_TRANSLATION_SYSTEM); - $app->setSubtitle("cal_exc_peer_review_deadline"); - $app->setTitle($this->getTitle()); - $app->setFullday(false); - $app->setStart(new ilDateTime($this->getPeerReviewDeadline(), IL_CAL_UNIX)); - - $apps[] = $app; - } - - } - - include_once "Modules/Exercise/classes/class.ilObjExercise.php"; - $exc = new ilObjExercise($this->getExerciseId(), false); - - $ilAppEventHandler->raise('Modules/Exercise', - $a_event.'Assignment', - array( - 'object' => $exc, - 'obj_id' => $exc->getId(), - 'context_ids' => $context_ids, - 'appointments' => $apps)); - } - - - public static function getPendingFeedbackNotifications() - { - global $DIC; - - $ilDB = $DIC->database(); - - $res = array(); - - $set = $ilDB->query("SELECT id,fb_file,time_stamp,deadline2,fb_date FROM exc_assignment". - " WHERE fb_cron = ".$ilDB->quote(1, "integer"). - " AND (fb_date = ".$ilDB->quote(self::FEEDBACK_DATE_DEADLINE, "integer"). - " AND time_stamp IS NOT NULL". - " AND time_stamp > ".$ilDB->quote(0, "integer"). - " AND time_stamp < ".$ilDB->quote(time(), "integer"). - " AND fb_cron_done = ".$ilDB->quote(0, "integer"). - ") OR (fb_date = ".$ilDB->quote(self::FEEDBACK_DATE_CUSTOM, "integer"). - " AND fb_date_custom IS NOT NULL". - " AND fb_date_custom > ".$ilDB->quote(0, "integer"). - " AND fb_date_custom < ".$ilDB->quote(time(), "integer"). - " AND fb_cron_done = ".$ilDB->quote(0, "integer").")"); - - - - while($row = $ilDB->fetchAssoc($set)) - { - if($row['fb_date'] == self::FEEDBACK_DATE_DEADLINE) - { - $max = max($row['time_stamp'], $row['deadline2']); - if (trim($row["fb_file"]) && $max <= time()) - { - $res[] = $row["id"]; - } - } - elseif($row['fb_date'] == self::FEEDBACK_DATE_CUSTOM) - { - if(trim($row["fb_file"]) && $row['fb_date_custom'] <= time()) - { - $res[] = $row["id"]; - } - } - } - - return $res; - } - - public static function sendFeedbackNotifications($a_ass_id, $a_user_id = null) - { - global $DIC; - - $ilDB = $DIC->database(); - - $ass = new self($a_ass_id); - - // valid assignment? - if(!$ass->hasFeedbackCron() || !$ass->getFeedbackFile()) - { - return false; - } - - if(!$a_user_id) - { - // already done? - $set = $ilDB->query("SELECT fb_cron_done". - " FROM exc_assignment". - " WHERE id = ".$ilDB->quote($a_ass_id, "integer")); - $row = $ilDB->fetchAssoc($set); - if($row["fb_cron_done"]) - { - return false; - } - } - - include_once "./Services/Notification/classes/class.ilSystemNotification.php"; - $ntf = new ilSystemNotification(); - $ntf->setLangModules(array("exc")); - $ntf->setObjId($ass->getExerciseId()); - $ntf->setSubjectLangId("exc_feedback_notification_subject"); - $ntf->setIntroductionLangId("exc_feedback_notification_body"); - $ntf->addAdditionalInfo("exc_assignment", $ass->getTitle()); - $ntf->setGotoLangId("exc_feedback_notification_link"); - $ntf->setReasonLangId("exc_feedback_notification_reason"); - - if(!$a_user_id) - { - include_once "./Modules/Exercise/classes/class.ilExerciseMembers.php"; - $ntf->sendMail(ilExerciseMembers::_getMembers($ass->getExerciseId())); - - $ilDB->manipulate("UPDATE exc_assignment". - " SET fb_cron_done = ".$ilDB->quote(1, "integer"). - " WHERE id = ".$ilDB->quote($a_ass_id, "integer")); - } - else - { - $ntf->sendMail(array($a_user_id)); - } - - return true; - } - - - // status - - public function afterDeadline() // like: after effective deadline (for single user), no deadline: true - { - $ilUser = $this->user; - - // :TODO: always current user? - $idl = $this->getPersonalDeadline($ilUser->getId()); // official deadline - - // no deadline === true - $deadline = max($this->deadline, $this->deadline2, $idl); // includes grace period - return ($deadline - time() <= 0); - } - - public function afterDeadlineStrict($a_include_personal = true) - { - // :TODO: this means that peer feedback, global feedback is available - // after LAST personal deadline - // team management is currently ignoring personal deadlines - $idl = (bool)$a_include_personal - ? $this->getLastPersonalDeadline() - : null; - - // no deadline === false - $deadline = max($this->deadline, $this->deadline2, $idl); - - // #18271 - afterDeadline() does not handle last personal deadline - if($idl && $deadline == $idl) // after effective deadline of all users - { - return ($deadline - time() <= 0); - } - - return ($deadline > 0 && // like: after effective deadline (for single user), except: no deadline false - $this->afterDeadline()); - } - - /** - * @return bool return if sample solution is available using a custom date. - */ - public function afterCustomDate() - { - $date_custom = $this->getFeedbackDateCustom(); - - //if the solution will be displayed only after reach all the deadlines. - //$final_deadline = $this->afterDeadlineStrict(); - //$dl = max($final_deadline, time()); - //return ($date_custom - $dl <= 0); - return ($date_custom - time() <= 0); - } - - public function beforeDeadline() // like: before effective deadline (for all users), no deadline: true - { - // no deadline === true - return !$this->afterDeadlineStrict(); - } - - public function notStartedYet() - { - return (time() - $this->start_time <= 0); - } - - - // - // FEEDBACK FILES - // - - public function getGlobalFeedbackFileStoragePath() - { - include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); - $storage = new ilFSStorageExercise($this->getExerciseId(), $this->getId()); - return $storage->getGlobalFeedbackPath(); - } - - function deleteGlobalFeedbackFile() - { - ilUtil::delDir($this->getGlobalFeedbackFileStoragePath()); - } - - function handleGlobalFeedbackFileUpload(array $a_file) - { - $path = $this->getGlobalFeedbackFileStoragePath(); - ilUtil::delDir($path, true); - if (ilUtil::moveUploadedFile($a_file["tmp_name"], $a_file["name"], $path."/".$a_file["name"])) - { - $this->setFeedbackFile($a_file["name"]); - return true; - } - return false; - } - - function getGlobalFeedbackFilePath() - { - $file = $this->getFeedbackFile(); - if($file) - { - $path = $this->getGlobalFeedbackFileStoragePath(); - return $path."/".$file; - } - } - - /** - * @param int|null $a_user_id - * @return \ilExAssignmentMemberStatus - */ - public function getMemberStatus($a_user_id = null) - { - $ilUser = $this->user; - - if(!$a_user_id) - { - $a_user_id = $ilUser->getId(); - } - if(!array_key_exists($a_user_id, $this->member_status)) - { - include_once "Modules/Exercise/classes/class.ilExAssignmentMemberStatus.php"; - $this->member_status[$a_user_id] = new ilExAssignmentMemberStatus($this->getId(), $a_user_id); - } - return $this->member_status[$a_user_id]; - } - - public function recalculateLateSubmissions() - { - $ilDB = $this->db; - - // see JF, 2015-05-11 - - $ext_deadline = $this->getExtendedDeadline(); - - include_once "Modules/Exercise/classes/class.ilExSubmission.php"; - foreach(ilExSubmission::getAllAssignmentFiles($this->exc_id, $this->getId()) as $file) - { - $id = $file["returned_id"]; - $uploaded = new ilDateTime($file["ts"], IL_CAL_DATETIME); - $uploaded = $uploaded->get(IL_CAL_UNIX); - - $deadline = $this->getPersonalDeadline($file["user_id"]); - $last_deadline = max($deadline, $this->getExtendedDeadline()); - - $late = null; - - // upload is not late anymore - if($file["late"] && - (!$last_deadline || - !$ext_deadline || - $uploaded < $deadline)) - { - $late = false; - } - // upload is now late - else if(!$file["late"] && - $ext_deadline && - $deadline && - $uploaded > $deadline) - { - $late = true; - } - else if($last_deadline && $uploaded > $last_deadline) - { - // do nothing, we do not remove submissions? - } - - if($late !== null) - { - $ilDB->manipulate("UPDATE exc_returned". - " SET late = ".$ilDB->quote($late, "integer"). - " WHERE returned_id = ".$ilDB->quote($id, "integer")); - } - } - } - - - // - // individual deadlines - // - - public function setIndividualDeadline($id, ilDateTime $date) - { - $ilDB = $this->db; - - $is_team = false; - if(!is_numeric($id)) - { - $id = substr($id, 1); - $is_team = true; - } - - include_once("./Modules/Exercise/classes/class.ilExcIndividualDeadline.php"); - $idl = ilExcIndividualDeadline::getInstance($this->getId(), $id, $is_team); - $idl->setIndividualDeadline($date->get(IL_CAL_UNIX)); - $idl->save(); - - /* - $ilDB->replace("exc_idl", - array( - "ass_id" => array("integer", $this->getId()), - "member_id" => array("integer", $id), - "is_team" => array("integer", $is_team) - ), - array( - "tstamp" => array("integer", $date->get(IL_CAL_UNIX)) - ) - );*/ - } - - public function getIndividualDeadlines() - { - $ilDB = $this->db; - - $res = array(); - - $set = $ilDB->query("SELECT * FROM exc_idl". - " WHERE ass_id = ".$ilDB->quote($this->getId(), "integer")); - while($row = $ilDB->fetchAssoc($set)) - { - if($row["is_team"]) - { - $row["member_id"] = "t".$row["member_id"]; - } - - $res[$row["member_id"]] = $row["tstamp"]; - } - - return $res; - } - - public function hasActiveIDl() - { - return (bool)$this->getDeadline(); - } - - public function hasReadOnlyIDl() - { - if(!$this->ass_type->usesTeams() && - $this->getPeerReview()) - { - // all deadlines are read-only if we have peer feedback - include_once "Modules/Exercise/classes/class.ilExPeerReview.php"; - $peer_review = new ilExPeerReview($this); - if($peer_review->hasPeerReviewGroups()) - { - return true; - } - } - - return false; - } - - /** - * Save ordering of instruction files for an assignment - * @param int $a_ass_id assignment id - * @param int $a_order order - */ - static function saveInstructionFilesOrderOfAssignment($a_ass_id, $a_order) - { - global $DIC; - - $db = $DIC->database(); - - asort($a_order, SORT_NUMERIC); - - $nr = 10; - foreach ($a_order as $k => $v) - { - // the check for exc_id is for security reasons. ass ids are unique. - $db->manipulate($t = "UPDATE exc_ass_file_order SET ". - " order_nr = ".$db->quote($nr, "integer"). - " WHERE id = ".$db->quote((int) $k, "integer"). - " AND assignment_id = ".$db->quote((int) $a_ass_id, "integer") - ); - $nr+=10; - } - } - - /** - * Store the file order in the database - * @param string $a_filename previously sanitized. - * @param int $a_ass_id assignment id. - */ - static function instructionFileInsertOrder($a_filename, $a_ass_id, $a_order_nr = 0) - { - global $DIC; - - $db = $DIC->database(); - - $order = 0; - $order_val = 0; - - if($a_ass_id) - { - //first of all check the suffix and change if necessary - $filename = ilUtil::getSafeFilename($a_filename); - - if(!self::instructionFileExistsInDb($filename, $a_ass_id)) - { - if ($a_order_nr == 0) - { - $order_val = self::instructionFileOrderGetMax($a_ass_id); - $order = $order_val + 10; - } - else - { - $order = $a_order_nr; - } - - $id = $db->nextID('exc_ass_file_order'); - $db->manipulate("INSERT INTO exc_ass_file_order " . - "(id, assignment_id, filename, order_nr) VALUES (" . - $db->quote($id, "integer") . "," . - $db->quote($a_ass_id, "integer") . "," . - $db->quote($filename, "text") . "," . - $db->quote($order, "integer") . - ")"); - } - } - } - - static function instructionFileDeleteOrder($a_ass_id, $a_file) - { - global $DIC; - - $db = $DIC->database(); - - //now its done by filename. We need to figure how to get the order id in the confirmdelete method - foreach ($a_file as $k => $v) - { - $db->manipulate("DELETE FROM exc_ass_file_order " . - //"WHERE id = " . $ilDB->quote((int)$k, "integer") . - "WHERE filename = " . $db->quote($v, "string") . - " AND assignment_id = " . $db->quote($a_ass_id, 'integer') - ); - } - } - - /** - * @param string $a_old_name - * @param string $a_new_name - * @param int $a_ass_id assignment id - */ - static function renameInstructionFile($a_old_name, $a_new_name, $a_ass_id) - { - global $DIC; - - $db = $DIC->database(); - - if($a_ass_id) - { - $db->manipulate("DELETE FROM exc_ass_file_order". - " WHERE assignment_id = ".$db->quote((int)$a_ass_id, 'integer'). - " AND filename = ".$db->quote($a_new_name, 'string') - ); - - $db->manipulate("UPDATE exc_ass_file_order SET". - " filename = ".$db->quote($a_new_name, 'string'). - " WHERE assignment_id = ".$db->quote((int)$a_ass_id, 'integer'). - " AND filename = ".$db->quote($a_old_name, 'string') - ); - } - } - - /** - * @param $a_filename - * @param $a_ass_id assignment id - * @return int if the file exists or not in the DB - */ - static function instructionFileExistsInDb($a_filename, $a_ass_id) - { - global $DIC; - - $db = $DIC->database(); - - if($a_ass_id) - { - $result = $db->query("SELECT id FROM exc_ass_file_order" . - " WHERE assignment_id = " . $db->quote((int)$a_ass_id, 'integer') . - " AND filename = " . $db->quote($a_filename, 'string') - ); - - return $db->numRows($result); - } - } - - function fixInstructionFileOrdering() - { - global $DIC; - - $db = $DIC->database(); - - $files = array_map(function ($v) { - return $v["name"]; - }, $this->getFiles()); - - $set = $db->query("SELECT * FROM exc_ass_file_order ". - " WHERE assignment_id = ".$db->quote($this->getId(), "integer"). - " ORDER BY order_nr"); - $order_nr = 10; - $numbered_files = array(); - while ($rec = $db->fetchAssoc($set)) - { - // file exists, set correct order nr - if (in_array($rec["filename"], $files)) - { - $db->manipulate("UPDATE exc_ass_file_order SET ". - " order_nr = ".$db->quote($order_nr, "integer"). - " WHERE assignment_id = ".$db->quote($this->getId(), "integer"). - " AND id = ".$db->quote($rec["id"], "integer") - ); - $order_nr+=10; - $numbered_files[] = $rec["filename"]; - } - else // file does not exist, delete entry - { - $db->manipulate("DELETE FROM exc_ass_file_order ". - " WHERE assignment_id = ".$db->quote($this->getId(), "integer"). - " AND id = ".$db->quote($rec["id"], "integer") - ); - } - } - foreach ($files as $f) - { - if (!in_array($f, $numbered_files)) - { - self::instructionFileInsertOrder($f, $this->getId()); - } - } - } - - /** - * @param array $a_entries - * @param integer $a_ass_id assignment id - * @return array data items - */ - function fileAddOrder($a_entries = array()) - { - $this->fixInstructionFileOrdering(); - - $order = $this->getInstructionFilesOrder(); - foreach ($a_entries as $k => $e) - { - $a_entries[$k]["order_val"] = $order[$e["file"]]["order_nr"]; - $a_entries[$k]["order_id"] = $order[$e["file"]]["id"]; - } - - return $a_entries; - } - - /** - * @param int $a_ass_id assignment id - * @return int - */ - public static function instructionFileOrderGetMax($a_ass_id) - { - global $DIC; - - $db = $DIC->database(); - - //get max order number - $result = $db->queryF("SELECT max(order_nr) as max_order FROM exc_ass_file_order WHERE assignment_id = %s", - array('integer'), - array($db->quote($a_ass_id, 'integer')) - ); - - while ($row = $db->fetchAssoc($result)) { - $order_val = (int)$row['max_order']; - } - return $order_val; - } - - - /** - * Set limit minimum characters - * - * @param int minim limit - */ - function setMinCharLimit($a_val) - { - $this->min_char_limit = $a_val; - } - - /** - * Get limit minimum characters - * - * @return int minimum limit - */ - function getMinCharLimit() - { - return $this->min_char_limit; - } - - /** - * Set limit maximum characters - * @param int max limit - */ - function setMaxCharLimit($a_val) - { - $this->max_char_limit = $a_val; - } - - /** - * get limit maximum characters - * return int max limit - */ - function getMaxCharLimit() - { - return $this->max_char_limit; - } - - /** - * Get calculated deadlines for user/team members. These arrays will contain no entries, if team or user - * has not started the assignment yet. - * - * @return array[array] contains two arrays one with key "user", second with key "team", each one has - * member id as keys and calculated deadline as value - */ - public function getCalculatedDeadlines() - { - $calculated_deadlines = array( - "user" => array(), - "team" => array() - ); - - if ($this->getRelativeDeadline() && $this->getDeadlineMode() == self::DEADLINE_RELATIVE) - { - include_once("./Modules/Exercise/classes/class.ilExcIndividualDeadline.php"); - foreach (ilExcIndividualDeadline::getStartingTimestamps($this->getId()) as $ts) - { - $type = $ts["is_team"] - ? "team" - : "user"; - - $calculated_deadlines[$type][$ts["member_id"]] = array( - "calculated_deadline" => $ts["starting_ts"] + ($this->getRelativeDeadline() * 24 * 60 * 60) - ); - } - } - return $calculated_deadlines; - } + $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 + */ + public function setId($a_val) + { + $this->id = $a_val; + } + + /** + * Get assignment id + * + * @return int assignment id + */ + public function getId() + { + return $this->id; + } + + /** + * Set exercise id + * + * @param int exercise id + */ + public function setExerciseId($a_val) + { + $this->exc_id = $a_val; + } + + /** + * Get exercise id + * + * @return int exercise id + */ + public function getExerciseId() + { + return $this->exc_id; + } + + /** + * Set start time (timestamp) + * + * @param int start time (timestamp) + */ + public function setStartTime($a_val) + { + $this->start_time = $a_val; + } + + /** + * Get start time (timestamp) + * + * @return int start time (timestamp) + */ + public function getStartTime() + { + return $this->start_time; + } + + /** + * Set deadline (timestamp) + * + * @param int deadline (timestamp) + */ + public function setDeadline($a_val) + { + $this->deadline = $a_val; + } + + /** + * Get deadline (timestamp) + * + * @return int deadline (timestamp) + */ + public function getDeadline() + { + return $this->deadline; + } + + /** + * Set deadline mode + * + * @param int $a_val deadline mode + */ + public function setDeadlineMode($a_val) + { + $this->deadline_mode = $a_val; + } + + /** + * Get deadline mode + * + * @return int deadline mode + */ + public function getDeadlineMode() + { + return $this->deadline_mode; + } + + /** + * Set relative deadline + * + * @param int $a_val relative deadline + */ + public function setRelativeDeadline($a_val) + { + $this->relative_deadline = $a_val; + } + + /** + * Get relative deadline + * + * @return int relative deadline + */ + public 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 + */ + public 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 + */ + public function setExtendedDeadline($a_val) + { + if ($a_val !== null) { + $a_val = (int) $a_val; + } + $this->deadline2 = $a_val; + } + + /** + * Get extended deadline (timestamp) + * + * @return int + */ + public function getExtendedDeadline() + { + return $this->deadline2; + } + + /** + * Set instruction + * + * @param string instruction + */ + public function setInstruction($a_val) + { + $this->instruction = $a_val; + } + + /** + * Get instruction + * + * @return string instruction + */ + public function getInstruction() + { + return $this->instruction; + } + + /** + * Set title + * + * @param string title + */ + public function setTitle($a_val) + { + $this->title = $a_val; + } + + /** + * Get title + * + * @return string title + */ + public function getTitle() + { + return $this->title; + } + + /** + * Set mandatory + * + * @param int mandatory + */ + public function setMandatory($a_val) + { + $this->mandatory = $a_val; + } + + /** + * Get mandatory + * + * @return int mandatory + */ + public function getMandatory() + { + return $this->mandatory; + } + + /** + * Set order nr + * + * @param int order nr + */ + public function setOrderNr($a_val) + { + $this->order_nr = $a_val; + } + + /** + * Get order nr + * + * @return int order nr + */ + public 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) + */ + public 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) + */ + public function getType() + { + return $this->type; + } + + /** + * Is given type valid? + * + * @param int $a_value + * @return bool + */ + public function isValidType($a_value) + { + return $this->types->isValidId($a_value); + } + + /** + * Toggle peer review + * + * @param bool $a_value + */ + public function setPeerReview($a_value) + { + $this->peer = (bool) $a_value; + } + + /** + * Get peer review status + * + * @return bool + */ + public function getPeerReview() + { + return (bool) $this->peer; + } + + /** + * Set peer review minimum + * + * @param int $a_value + */ + public function setPeerReviewMin($a_value) + { + $this->peer_min = (int) $a_value; + } + + /** + * Get peer review minimum + * + * @return int + */ + public function getPeerReviewMin() + { + return (int) $this->peer_min; + } + + /** + * Set peer review simple unlock + * + * @param bool $a_value + */ + public function setPeerReviewSimpleUnlock($a_value) + { + $this->peer_unlock = (bool) $a_value; + } + + /** + * Get peer review simple unlock + * + * @return bool + */ + public function getPeerReviewSimpleUnlock() + { + return (bool) $this->peer_unlock; + } + + /** + * Set peer review deadline (timestamp) + * + * @param int deadline (timestamp) + */ + public function setPeerReviewDeadline($a_val) + { + $this->peer_dl = $a_val; + } + + /** + * Get peer review deadline (timestamp) + * + * @return int deadline (timestamp) + */ + public function getPeerReviewDeadline() + { + return $this->peer_dl; + } + + /** + * Set peer review validation + * + * @param int $a_value + */ + public function setPeerReviewValid($a_value) + { + $this->peer_valid = (int) $a_value; + } + + /** + * Get peer review validatiob + * + * @return int + */ + public function getPeerReviewValid() + { + return (int) $this->peer_valid; + } + + /** + * Set peer review rating + * + * @param bool + */ + public function setPeerReviewRating($a_val) + { + $this->peer_rating = (bool) $a_val; + } + + /** + * Get peer review rating status + * + * @return bool + */ + public function hasPeerReviewRating() + { + return $this->peer_rating; + } + + /** + * Set peer review text + * + * @param bool + */ + public function setPeerReviewText($a_val) + { + $this->peer_text = (bool) $a_val; + } + + /** + * Get peer review text status + * + * @return bool + */ + public function hasPeerReviewText() + { + return $this->peer_text; + } + + /** + * Set peer review file upload + * + * @param bool + */ + public function setPeerReviewFileUpload($a_val) + { + $this->peer_file = (bool) $a_val; + } + + /** + * Get peer review file upload status + * + * @return bool + */ + public function hasPeerReviewFileUpload() + { + return $this->peer_file; + } + + /** + * Set peer review personalized + * + * @param bool + */ + public function setPeerReviewPersonalized($a_val) + { + $this->peer_personal = (bool) $a_val; + } + + /** + * Get peer review personalized status + * + * @return bool + */ + public function hasPeerReviewPersonalized() + { + return $this->peer_personal; + } + + /** + * Set peer review minimum characters + * + * @param int $a_value + */ + public 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 + */ + public function getPeerReviewChars() + { + return $this->peer_char; + } + + /** + * Set peer review criteria catalogue id + * + * @param int $a_value + */ + public 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 + */ + public function getPeerReviewCriteriaCatalogue() + { + return $this->crit_cat; + } + + public 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 + */ + public function setFeedbackFile($a_value) + { + $this->feedback_file = (string) $a_value; + } + + /** + * Get (global) feedback file + * + * @return int + */ + public function getFeedbackFile() + { + return (string) $this->feedback_file; + } + + /** + * Toggle (global) feedback file cron + * + * @param bool $a_value + */ + public function setFeedbackCron($a_value) + { + $this->feedback_cron = (string) $a_value; + } + + /** + * Get (global) feedback file cron status + * + * @return int + */ + public function hasFeedbackCron() + { + return (bool) $this->feedback_cron; + } + + /** + * Set (global) feedback file availability date + * + * @param int $a_value + */ + public function setFeedbackDate($a_value) + { + $this->feedback_date = (int) $a_value; + } + + /** + * Get (global) feedback file availability date + * + * @return int + */ + public function getFeedbackDate() + { + return (int) $this->feedback_date; + } + + /** + * Set (global) feedback file availability using a custom date. + * @param int $a_value timestamp + */ + public function setFeedbackDateCustom($a_value) + { + $this->feedback_date_custom = $a_value; + } + + /** + * Get feedback file availability using custom date. + * @return string timestamp + */ + public function getFeedbackDateCustom() + { + return $this->feedback_date_custom; + } + + /** + * Set team management by tutor + * + * @param bool $a_value + */ + public function setTeamTutor($a_value) + { + $this->team_tutor = (bool) $a_value; + } + + /** + * Get team management by tutor + * + * @return bool + */ + public function getTeamTutor() + { + return $this->team_tutor; + } + + /** + * Set max number of uploads + * + * @param int $a_value + */ + public 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 + */ + public function getMaxFile() + { + return $this->max_file; + } + + /** + * Set portfolio template id + * + * @param int $a_val + */ + public function setPortfolioTemplateId($a_val) + { + $this->portfolio_template = $a_val; + } + + /** + * Get portfolio template id + * + * @return int portfolio template id + */ + public function getPortfolioTemplateId() + { + return $this->portfolio_template; + } + + + /** + * Read from db + */ + public 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 + */ + public 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 + */ + public 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 + */ + public 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 + */ + public 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 + */ + public 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 + */ + public 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 + */ + public static function lookupTitle($a_id) + { + return self::lookup($a_id, "title"); + } + + /** + * Lookup type + */ + public static function lookupType($a_id) + { + return self::lookup($a_id, "type"); + } + + /** + * Save ordering of all assignments of an exercise + */ + public 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 + */ + public 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 + */ + public 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. + */ + public 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 + */ + public 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 + */ + public 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 + */ + public 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) + */ + public 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 + */ + public 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 __ for each participant + include_once("./Modules/Exercise/classes/class.ilExerciseMembers.php"); + $exmem = new ilExerciseMembers($exc); + $mems = $exmem->getMembers(); + + $mems = $DIC->access()->filterUserIdsByRbacOrPositionOfCurrentUser( + 'edit_submissions_grades', + 'edit_submissions_grades', + $exercise->getRefId(), + $mems + ); + foreach ($mems as $mem) { + $name = ilObjUser::_lookupName($mem); + $subdir = $name["lastname"] . "_" . $name["firstname"] . "_" . $name["login"] . "_" . $name["user_id"]; + $subdir = ilUtil::getASCIIFilename($subdir); + ilUtil::makeDir($mfdir . "/" . $subdir); + } + + // create the zip file + chdir($tmpdir); + $tmpzipfile = $tmpdir . "/multi_feedback.zip"; + ilUtil::zip($tmpdir, $tmpzipfile, true); + chdir($cdir); + + + ilUtil::deliverFile($tmpzipfile, $deliverFilename . ".zip", "", false, true); + } + + /** + * Upload multi feedback file + * + * @param array + * @return + */ + public function uploadMultiFeedbackFile($a_file) + { + $lng = $this->lng; + $ilUser = $this->user; + + include_once("./Modules/Exercise/exceptions/class.ilExerciseException.php"); + if (!is_file($a_file["tmp_name"])) { + throw new ilExerciseException($lng->txt("exc_feedback_file_could_not_be_uploaded")); + } + + include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); + $storage = new ilFSStorageExercise($this->getExerciseId(), $this->getId()); + $mfu = $storage->getMultiFeedbackUploadPath($ilUser->getId()); + ilUtil::delDir($mfu, true); + ilUtil::moveUploadedFile($a_file["tmp_name"], "multi_feedback.zip", $mfu . "/" . "multi_feedback.zip"); + ilUtil::unzip($mfu . "/multi_feedback.zip", true); + $subdirs = ilUtil::getDir($mfu); + $subdir = "notfound"; + foreach ($subdirs as $s => $j) { + if ($j["type"] == "dir" && substr($s, 0, 14) == "multi_feedback") { + $subdir = $s; + } + } + + if (!is_dir($mfu . "/" . $subdir)) { + throw new ilExerciseException($lng->txt("exc_no_feedback_dir_found_in_zip")); + } + + return true; + } + + /** + * Get multi feedback files (of uploader) + * + * @param int $a_user_id user id of uploader + * @return array array of user files (keys: lastname, firstname, user_id, login, file) + */ + public function getMultiFeedbackFiles($a_user_id = 0) + { + $ilUser = $this->user; + + if ($a_user_id == 0) { + $a_user_id = $ilUser->getId(); + } + + $mf_files = array(); + + // get members + $exc = new ilObjExercise($this->getExerciseId(), false); + include_once("./Modules/Exercise/classes/class.ilExerciseMembers.php"); + $exmem = new ilExerciseMembers($exc); + $mems = $exmem->getMembers(); + + // read mf directory + include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); + $storage = new ilFSStorageExercise($this->getExerciseId(), $this->getId()); + $mfu = $storage->getMultiFeedbackUploadPath($ilUser->getId()); + + // get subdir that starts with multi_feedback + $subdirs = ilUtil::getDir($mfu); + $subdir = "notfound"; + foreach ($subdirs as $s => $j) { + if ($j["type"] == "dir" && substr($s, 0, 14) == "multi_feedback") { + $subdir = $s; + } + } + + $items = ilUtil::getDir($mfu . "/" . $subdir); + foreach ($items as $k => $i) { + // check directory + if ($i["type"] == "dir" && !in_array($k, array(".", ".."))) { + // check if valid member id is given + $parts = explode("_", $i["entry"]); + $user_id = (int) $parts[count($parts) - 1]; + if (in_array($user_id, $mems)) { + // read dir of user + $name = ilObjUser::_lookupName($user_id); + $files = ilUtil::getDir($mfu . "/" . $subdir . "/" . $k); + foreach ($files as $k2 => $f) { + // append files to array + if ($f["type"] == "file" && substr($k2, 0, 1) != ".") { + $mf_files[] = array( + "lastname" => $name["lastname"], + "firstname" => $name["firstname"], + "login" => $name["login"], + "user_id" => $name["user_id"], + "full_path" => $mfu . "/" . $subdir . "/" . $k . "/" . $k2, + "file" => $k2); + } + } + } + } + } + return $mf_files; + } + + /** + * Clear multi feedback directory + * + * @param array + * @return + */ + public function clearMultiFeedbackDirectory() + { + $lng = $this->lng; + $ilUser = $this->user; + + include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); + $storage = new ilFSStorageExercise($this->getExerciseId(), $this->getId()); + $mfu = $storage->getMultiFeedbackUploadPath($ilUser->getId()); + ilUtil::delDir($mfu); + } + + /** + * Save multi feedback files + * + * @param + * @return + */ + public function saveMultiFeedbackFiles($a_files, ilObjExercise $a_exc) + { + if ($this->getExerciseId() != $a_exc->getId()) { + return; + } + + include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); + $fstorage = new ilFSStorageExercise($this->getExerciseId(), $this->getId()); + $fstorage->create(); + + $team_map = array(); + + $mf_files = $this->getMultiFeedbackFiles(); + foreach ($mf_files as $f) { + $user_id = $f["user_id"]; + $file_path = $f["full_path"]; + $file_name = $f["file"]; + + // if checked in confirmation gui + if ($a_files[$user_id][md5($file_name)] != "") { + $submission = new ilExSubmission($this, $user_id); + $feedback_id = $submission->getFeedbackId(); + $noti_rec_ids = $submission->getUserIds(); + + if ($feedback_id) { + $fb_path = $fstorage->getFeedbackPath($feedback_id); + $target = $fb_path . "/" . $file_name; + if (is_file($target)) { + unlink($target); + } + // rename file + rename($file_path, $target); + + if ($noti_rec_ids) { + foreach ($noti_rec_ids as $user_id) { + $member_status = $this->getMemberStatus($user_id); + $member_status->setFeedback(true); + $member_status->update(); + } + + $a_exc->sendFeedbackFileNotification( + $file_name, + $noti_rec_ids, + (int) $this->getId() + ); + } + } + } + } + + $this->clearMultiFeedbackDirectory(); + } + + + + + /** + * Handle calendar entries for deadline(s) + * + * @param string $a_event + */ + protected function handleCalendarEntries($a_event) + { + $ilAppEventHandler = $this->app_event_handler; + + $dl_id = $this->getId() . "0"; + $fbdl_id = $this->getId() . "1"; + + $context_ids = array($dl_id, $fbdl_id); + $apps = array(); + + if ($a_event != "delete") { + include_once "Services/Calendar/classes/class.ilCalendarAppointmentTemplate.php"; + + // deadline or relative deadline given + if ($this->getDeadline() || $this->getDeadlineMode() == ilExAssignment::DEADLINE_RELATIVE) { + $app = new ilCalendarAppointmentTemplate($dl_id); + $app->setTranslationType(IL_CAL_TRANSLATION_SYSTEM); + $app->setSubtitle("cal_exc_deadline"); + $app->setTitle($this->getTitle()); + $app->setFullday(false); + // note: in the case of a relative deadline this will be set to 0 / 1970...) + // see ilCalendarScheduleFilterExercise for appointment modification + $app->setStart(new ilDateTime($this->getDeadline(), IL_CAL_UNIX)); + + $apps[] = $app; + } + + if ($this->getPeerReview() && + $this->getPeerReviewDeadline()) { + $app = new ilCalendarAppointmentTemplate($fbdl_id); + $app->setTranslationType(IL_CAL_TRANSLATION_SYSTEM); + $app->setSubtitle("cal_exc_peer_review_deadline"); + $app->setTitle($this->getTitle()); + $app->setFullday(false); + $app->setStart(new ilDateTime($this->getPeerReviewDeadline(), IL_CAL_UNIX)); + + $apps[] = $app; + } + } + + include_once "Modules/Exercise/classes/class.ilObjExercise.php"; + $exc = new ilObjExercise($this->getExerciseId(), false); + + $ilAppEventHandler->raise( + 'Modules/Exercise', + $a_event . 'Assignment', + array( + 'object' => $exc, + 'obj_id' => $exc->getId(), + 'context_ids' => $context_ids, + 'appointments' => $apps) + ); + } + + + public static function getPendingFeedbackNotifications() + { + global $DIC; + + $ilDB = $DIC->database(); + + $res = array(); + + $set = $ilDB->query("SELECT id,fb_file,time_stamp,deadline2,fb_date FROM exc_assignment" . + " WHERE fb_cron = " . $ilDB->quote(1, "integer") . + " AND (fb_date = " . $ilDB->quote(self::FEEDBACK_DATE_DEADLINE, "integer") . + " AND time_stamp IS NOT NULL" . + " AND time_stamp > " . $ilDB->quote(0, "integer") . + " AND time_stamp < " . $ilDB->quote(time(), "integer") . + " AND fb_cron_done = " . $ilDB->quote(0, "integer") . + ") OR (fb_date = " . $ilDB->quote(self::FEEDBACK_DATE_CUSTOM, "integer") . + " AND fb_date_custom IS NOT NULL" . + " AND fb_date_custom > " . $ilDB->quote(0, "integer") . + " AND fb_date_custom < " . $ilDB->quote(time(), "integer") . + " AND fb_cron_done = " . $ilDB->quote(0, "integer") . ")"); + + + + while ($row = $ilDB->fetchAssoc($set)) { + if ($row['fb_date'] == self::FEEDBACK_DATE_DEADLINE) { + $max = max($row['time_stamp'], $row['deadline2']); + if (trim($row["fb_file"]) && $max <= time()) { + $res[] = $row["id"]; + } + } elseif ($row['fb_date'] == self::FEEDBACK_DATE_CUSTOM) { + if (trim($row["fb_file"]) && $row['fb_date_custom'] <= time()) { + $res[] = $row["id"]; + } + } + } + + return $res; + } + + public static function sendFeedbackNotifications($a_ass_id, $a_user_id = null) + { + global $DIC; + + $ilDB = $DIC->database(); + + $ass = new self($a_ass_id); + + // valid assignment? + if (!$ass->hasFeedbackCron() || !$ass->getFeedbackFile()) { + return false; + } + + if (!$a_user_id) { + // already done? + $set = $ilDB->query("SELECT fb_cron_done" . + " FROM exc_assignment" . + " WHERE id = " . $ilDB->quote($a_ass_id, "integer")); + $row = $ilDB->fetchAssoc($set); + if ($row["fb_cron_done"]) { + return false; + } + } + + include_once "./Services/Notification/classes/class.ilSystemNotification.php"; + $ntf = new ilSystemNotification(); + $ntf->setLangModules(array("exc")); + $ntf->setObjId($ass->getExerciseId()); + $ntf->setSubjectLangId("exc_feedback_notification_subject"); + $ntf->setIntroductionLangId("exc_feedback_notification_body"); + $ntf->addAdditionalInfo("exc_assignment", $ass->getTitle()); + $ntf->setGotoLangId("exc_feedback_notification_link"); + $ntf->setReasonLangId("exc_feedback_notification_reason"); + + if (!$a_user_id) { + include_once "./Modules/Exercise/classes/class.ilExerciseMembers.php"; + $ntf->sendMail(ilExerciseMembers::_getMembers($ass->getExerciseId())); + + $ilDB->manipulate("UPDATE exc_assignment" . + " SET fb_cron_done = " . $ilDB->quote(1, "integer") . + " WHERE id = " . $ilDB->quote($a_ass_id, "integer")); + } else { + $ntf->sendMail(array($a_user_id)); + } + + return true; + } + + + // status + + public function afterDeadline() // like: after effective deadline (for single user), no deadline: true + { + $ilUser = $this->user; + + // :TODO: always current user? + $idl = $this->getPersonalDeadline($ilUser->getId()); // official deadline + + // no deadline === true + $deadline = max($this->deadline, $this->deadline2, $idl); // includes grace period + return ($deadline - time() <= 0); + } + + public function afterDeadlineStrict($a_include_personal = true) + { + // :TODO: this means that peer feedback, global feedback is available + // after LAST personal deadline + // team management is currently ignoring personal deadlines + $idl = (bool) $a_include_personal + ? $this->getLastPersonalDeadline() + : null; + + // no deadline === false + $deadline = max($this->deadline, $this->deadline2, $idl); + + // #18271 - afterDeadline() does not handle last personal deadline + if ($idl && $deadline == $idl) { // after effective deadline of all users + return ($deadline - time() <= 0); + } + + return ($deadline > 0 && // like: after effective deadline (for single user), except: no deadline false + $this->afterDeadline()); + } + + /** + * @return bool return if sample solution is available using a custom date. + */ + public function afterCustomDate() + { + $date_custom = $this->getFeedbackDateCustom(); + + //if the solution will be displayed only after reach all the deadlines. + //$final_deadline = $this->afterDeadlineStrict(); + //$dl = max($final_deadline, time()); + //return ($date_custom - $dl <= 0); + return ($date_custom - time() <= 0); + } + + public function beforeDeadline() // like: before effective deadline (for all users), no deadline: true + { + // no deadline === true + return !$this->afterDeadlineStrict(); + } + + public function notStartedYet() + { + return (time() - $this->start_time <= 0); + } + + + // + // FEEDBACK FILES + // + + public function getGlobalFeedbackFileStoragePath() + { + include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); + $storage = new ilFSStorageExercise($this->getExerciseId(), $this->getId()); + return $storage->getGlobalFeedbackPath(); + } + + public function deleteGlobalFeedbackFile() + { + ilUtil::delDir($this->getGlobalFeedbackFileStoragePath()); + } + + public function handleGlobalFeedbackFileUpload(array $a_file) + { + $path = $this->getGlobalFeedbackFileStoragePath(); + ilUtil::delDir($path, true); + if (ilUtil::moveUploadedFile($a_file["tmp_name"], $a_file["name"], $path . "/" . $a_file["name"])) { + $this->setFeedbackFile($a_file["name"]); + return true; + } + return false; + } + + public function getGlobalFeedbackFilePath() + { + $file = $this->getFeedbackFile(); + if ($file) { + $path = $this->getGlobalFeedbackFileStoragePath(); + return $path . "/" . $file; + } + } + + /** + * @param int|null $a_user_id + * @return \ilExAssignmentMemberStatus + */ + public function getMemberStatus($a_user_id = null) + { + $ilUser = $this->user; + + if (!$a_user_id) { + $a_user_id = $ilUser->getId(); + } + if (!array_key_exists($a_user_id, $this->member_status)) { + include_once "Modules/Exercise/classes/class.ilExAssignmentMemberStatus.php"; + $this->member_status[$a_user_id] = new ilExAssignmentMemberStatus($this->getId(), $a_user_id); + } + return $this->member_status[$a_user_id]; + } + + public function recalculateLateSubmissions() + { + $ilDB = $this->db; + + // see JF, 2015-05-11 + + $ext_deadline = $this->getExtendedDeadline(); + + include_once "Modules/Exercise/classes/class.ilExSubmission.php"; + foreach (ilExSubmission::getAllAssignmentFiles($this->exc_id, $this->getId()) as $file) { + $id = $file["returned_id"]; + $uploaded = new ilDateTime($file["ts"], IL_CAL_DATETIME); + $uploaded = $uploaded->get(IL_CAL_UNIX); + + $deadline = $this->getPersonalDeadline($file["user_id"]); + $last_deadline = max($deadline, $this->getExtendedDeadline()); + + $late = null; + + // upload is not late anymore + if ($file["late"] && + (!$last_deadline || + !$ext_deadline || + $uploaded < $deadline)) { + $late = false; + } + // upload is now late + elseif (!$file["late"] && + $ext_deadline && + $deadline && + $uploaded > $deadline) { + $late = true; + } elseif ($last_deadline && $uploaded > $last_deadline) { + // do nothing, we do not remove submissions? + } + + if ($late !== null) { + $ilDB->manipulate("UPDATE exc_returned" . + " SET late = " . $ilDB->quote($late, "integer") . + " WHERE returned_id = " . $ilDB->quote($id, "integer")); + } + } + } + + + // + // individual deadlines + // + + public function setIndividualDeadline($id, ilDateTime $date) + { + $ilDB = $this->db; + + $is_team = false; + if (!is_numeric($id)) { + $id = substr($id, 1); + $is_team = true; + } + + include_once("./Modules/Exercise/classes/class.ilExcIndividualDeadline.php"); + $idl = ilExcIndividualDeadline::getInstance($this->getId(), $id, $is_team); + $idl->setIndividualDeadline($date->get(IL_CAL_UNIX)); + $idl->save(); + + /* + $ilDB->replace("exc_idl", + array( + "ass_id" => array("integer", $this->getId()), + "member_id" => array("integer", $id), + "is_team" => array("integer", $is_team) + ), + array( + "tstamp" => array("integer", $date->get(IL_CAL_UNIX)) + ) + );*/ + } + + public function getIndividualDeadlines() + { + $ilDB = $this->db; + + $res = array(); + + $set = $ilDB->query("SELECT * FROM exc_idl" . + " WHERE ass_id = " . $ilDB->quote($this->getId(), "integer")); + while ($row = $ilDB->fetchAssoc($set)) { + if ($row["is_team"]) { + $row["member_id"] = "t" . $row["member_id"]; + } + + $res[$row["member_id"]] = $row["tstamp"]; + } + + return $res; + } + + public function hasActiveIDl() + { + return (bool) $this->getDeadline(); + } + + public function hasReadOnlyIDl() + { + if (!$this->ass_type->usesTeams() && + $this->getPeerReview()) { + // all deadlines are read-only if we have peer feedback + include_once "Modules/Exercise/classes/class.ilExPeerReview.php"; + $peer_review = new ilExPeerReview($this); + if ($peer_review->hasPeerReviewGroups()) { + return true; + } + } + + return false; + } + + /** + * Save ordering of instruction files for an assignment + * @param int $a_ass_id assignment id + * @param int $a_order order + */ + public static function saveInstructionFilesOrderOfAssignment($a_ass_id, $a_order) + { + global $DIC; + + $db = $DIC->database(); + + asort($a_order, SORT_NUMERIC); + + $nr = 10; + foreach ($a_order as $k => $v) { + // the check for exc_id is for security reasons. ass ids are unique. + $db->manipulate( + $t = "UPDATE exc_ass_file_order SET " . + " order_nr = " . $db->quote($nr, "integer") . + " WHERE id = " . $db->quote((int) $k, "integer") . + " AND assignment_id = " . $db->quote((int) $a_ass_id, "integer") + ); + $nr+=10; + } + } + + /** + * Store the file order in the database + * @param string $a_filename previously sanitized. + * @param int $a_ass_id assignment id. + */ + public static function instructionFileInsertOrder($a_filename, $a_ass_id, $a_order_nr = 0) + { + global $DIC; + + $db = $DIC->database(); + + $order = 0; + $order_val = 0; + + if ($a_ass_id) { + //first of all check the suffix and change if necessary + $filename = ilUtil::getSafeFilename($a_filename); + + if (!self::instructionFileExistsInDb($filename, $a_ass_id)) { + if ($a_order_nr == 0) { + $order_val = self::instructionFileOrderGetMax($a_ass_id); + $order = $order_val + 10; + } else { + $order = $a_order_nr; + } + + $id = $db->nextID('exc_ass_file_order'); + $db->manipulate("INSERT INTO exc_ass_file_order " . + "(id, assignment_id, filename, order_nr) VALUES (" . + $db->quote($id, "integer") . "," . + $db->quote($a_ass_id, "integer") . "," . + $db->quote($filename, "text") . "," . + $db->quote($order, "integer") . + ")"); + } + } + } + + public static function instructionFileDeleteOrder($a_ass_id, $a_file) + { + global $DIC; + + $db = $DIC->database(); + + //now its done by filename. We need to figure how to get the order id in the confirmdelete method + foreach ($a_file as $k => $v) { + $db->manipulate( + "DELETE FROM exc_ass_file_order " . + //"WHERE id = " . $ilDB->quote((int)$k, "integer") . + "WHERE filename = " . $db->quote($v, "string") . + " AND assignment_id = " . $db->quote($a_ass_id, 'integer') + ); + } + } + + /** + * @param string $a_old_name + * @param string $a_new_name + * @param int $a_ass_id assignment id + */ + public static function renameInstructionFile($a_old_name, $a_new_name, $a_ass_id) + { + global $DIC; + + $db = $DIC->database(); + + if ($a_ass_id) { + $db->manipulate( + "DELETE FROM exc_ass_file_order" . + " WHERE assignment_id = " . $db->quote((int) $a_ass_id, 'integer') . + " AND filename = " . $db->quote($a_new_name, 'string') + ); + + $db->manipulate( + "UPDATE exc_ass_file_order SET" . + " filename = " . $db->quote($a_new_name, 'string') . + " WHERE assignment_id = " . $db->quote((int) $a_ass_id, 'integer') . + " AND filename = " . $db->quote($a_old_name, 'string') + ); + } + } + + /** + * @param $a_filename + * @param $a_ass_id assignment id + * @return int if the file exists or not in the DB + */ + public static function instructionFileExistsInDb($a_filename, $a_ass_id) + { + global $DIC; + + $db = $DIC->database(); + + if ($a_ass_id) { + $result = $db->query( + "SELECT id FROM exc_ass_file_order" . + " WHERE assignment_id = " . $db->quote((int) $a_ass_id, 'integer') . + " AND filename = " . $db->quote($a_filename, 'string') + ); + + return $db->numRows($result); + } + } + + public function fixInstructionFileOrdering() + { + global $DIC; + + $db = $DIC->database(); + + $files = array_map(function ($v) { + return $v["name"]; + }, $this->getFiles()); + + $set = $db->query("SELECT * FROM exc_ass_file_order " . + " WHERE assignment_id = " . $db->quote($this->getId(), "integer") . + " ORDER BY order_nr"); + $order_nr = 10; + $numbered_files = array(); + while ($rec = $db->fetchAssoc($set)) { + // file exists, set correct order nr + if (in_array($rec["filename"], $files)) { + $db->manipulate( + "UPDATE exc_ass_file_order SET " . + " order_nr = " . $db->quote($order_nr, "integer") . + " WHERE assignment_id = " . $db->quote($this->getId(), "integer") . + " AND id = " . $db->quote($rec["id"], "integer") + ); + $order_nr+=10; + $numbered_files[] = $rec["filename"]; + } else { // file does not exist, delete entry + $db->manipulate( + "DELETE FROM exc_ass_file_order " . + " WHERE assignment_id = " . $db->quote($this->getId(), "integer") . + " AND id = " . $db->quote($rec["id"], "integer") + ); + } + } + foreach ($files as $f) { + if (!in_array($f, $numbered_files)) { + self::instructionFileInsertOrder($f, $this->getId()); + } + } + } + + /** + * @param array $a_entries + * @param integer $a_ass_id assignment id + * @return array data items + */ + public function fileAddOrder($a_entries = array()) + { + $this->fixInstructionFileOrdering(); + + $order = $this->getInstructionFilesOrder(); + foreach ($a_entries as $k => $e) { + $a_entries[$k]["order_val"] = $order[$e["file"]]["order_nr"]; + $a_entries[$k]["order_id"] = $order[$e["file"]]["id"]; + } + + return $a_entries; + } + + /** + * @param int $a_ass_id assignment id + * @return int + */ + public static function instructionFileOrderGetMax($a_ass_id) + { + global $DIC; + + $db = $DIC->database(); + + //get max order number + $result = $db->queryF( + "SELECT max(order_nr) as max_order FROM exc_ass_file_order WHERE assignment_id = %s", + array('integer'), + array($db->quote($a_ass_id, 'integer')) + ); + + while ($row = $db->fetchAssoc($result)) { + $order_val = (int) $row['max_order']; + } + return $order_val; + } + + + /** + * Set limit minimum characters + * + * @param int minim limit + */ + public function setMinCharLimit($a_val) + { + $this->min_char_limit = $a_val; + } + + /** + * Get limit minimum characters + * + * @return int minimum limit + */ + public function getMinCharLimit() + { + return $this->min_char_limit; + } + + /** + * Set limit maximum characters + * @param int max limit + */ + public function setMaxCharLimit($a_val) + { + $this->max_char_limit = $a_val; + } + + /** + * get limit maximum characters + * return int max limit + */ + public function getMaxCharLimit() + { + return $this->max_char_limit; + } + + /** + * Get calculated deadlines for user/team members. These arrays will contain no entries, if team or user + * has not started the assignment yet. + * + * @return array[array] contains two arrays one with key "user", second with key "team", each one has + * member id as keys and calculated deadline as value + */ + public function getCalculatedDeadlines() + { + $calculated_deadlines = array( + "user" => array(), + "team" => array() + ); + + if ($this->getRelativeDeadline() && $this->getDeadlineMode() == self::DEADLINE_RELATIVE) { + include_once("./Modules/Exercise/classes/class.ilExcIndividualDeadline.php"); + foreach (ilExcIndividualDeadline::getStartingTimestamps($this->getId()) as $ts) { + $type = $ts["is_team"] + ? "team" + : "user"; + + $calculated_deadlines[$type][$ts["member_id"]] = array( + "calculated_deadline" => $ts["starting_ts"] + ($this->getRelativeDeadline() * 24 * 60 * 60) + ); + } + } + return $calculated_deadlines; + } } - -?> \ No newline at end of file diff --git a/Modules/Exercise/classes/class.ilExAssignmentEditorGUI.php b/Modules/Exercise/classes/class.ilExAssignmentEditorGUI.php index 9fe4b3678f9117dd0bfc01730d069061b741071a..d5916ca7742d4ffcadd52bfc31c7fb2ec6132bd4 100644 --- a/Modules/Exercise/classes/class.ilExAssignmentEditorGUI.php +++ b/Modules/Exercise/classes/class.ilExAssignmentEditorGUI.php @@ -9,1919 +9,1795 @@ include_once("./Modules/Exercise/classes/class.ilExAssignmentReminder.php"); * Class ilExAssignmentEditorGUI * * @author Jörg Lützenkirchen -* +* * @ilCtrl_Calls ilExAssignmentEditorGUI: ilExAssignmentFileSystemGUI, ilExPeerReviewGUI, ilPropertyFormGUI * * @ingroup ModulesExercise */ -class ilExAssignmentEditorGUI +class ilExAssignmentEditorGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilSetting - */ - protected $settings; - - /** - * @var ilHelpGUI - */ - protected $help; - - /** - * @var int - */ - protected $exercise_id; - - /** - * @var ilExAssignment - */ - protected $assignment; - - /** - * @var bool - */ - protected $enable_peer_review_completion; - - /** - * @var ilExAssignmentTypes - */ - protected $types; - - /** - * Constructor - * - * @param int $a_exercise_id - * @param bool $a_enable_peer_review_completion_settings - * @param ilExAssignment $a_ass - * @return object - */ - public function __construct($a_exercise_id, $a_enable_peer_review_completion_settings, ilExAssignment $a_ass = null) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->tabs = $DIC->tabs(); - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - $this->toolbar = $DIC->toolbar(); - $this->settings = $DIC->settings(); - $this->help = $DIC["ilHelp"]; - $this->exercise_id = $a_exercise_id; - $this->assignment = $a_ass; - $this->enable_peer_review_completion = (bool)$a_enable_peer_review_completion_settings; - include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssignmentTypes.php"); - $this->types = ilExAssignmentTypes::getInstance(); - include_once("./Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssignmentTypesGUI.php"); - $this->type_guis = ilExAssignmentTypesGUI::getInstance(); - } - - public function executeCommand() - { - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - $lng = $this->lng; - - $class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd("listAssignments"); - - switch($class) - { - case "ilpropertyformgui": - $form = $this->initAssignmentForm($_GET["ass_type"]); - $ilCtrl->forwardCommand($form); - break; - - // instruction files - case "ilexassignmentfilesystemgui": - $this->setAssignmentHeader(); - $ilTabs->activateTab("ass_files"); - - include_once("./Modules/Exercise/classes/class.ilFSWebStorageExercise.php"); - $fstorage = new ilFSWebStorageExercise($this->exercise_id, $this->assignment->getId()); - $fstorage->create(); - - include_once("./Modules/Exercise/classes/class.ilExAssignmentFileSystemGUI.php"); - $fs_gui = new ilExAssignmentFileSystemGUI($fstorage->getPath()); - $fs_gui->setTitle($lng->txt("exc_instruction_files")); - $fs_gui->setTableId("excassfil".$this->assignment->getId()); - $fs_gui->setAllowDirectories(false); - $ilCtrl->forwardCommand($fs_gui); - break; - - case "ilexpeerreviewgui": - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTarget($this, "listAssignments")); - - include_once("./Modules/Exercise/classes/class.ilExPeerReviewGUI.php"); - $peer_gui = new ilExPeerReviewGUI($this->assignment); - $ilCtrl->forwardCommand($peer_gui); - break; - - default: - $this->{$cmd."Object"}(); - break; - } - } - - /** - * List assignments - */ - function listAssignmentsObject() - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $ilToolbar->setFormAction($ilCtrl->getFormAction($this, "addAssignment")); - - include_once "Services/Form/classes/class.ilSelectInputGUI.php"; - $ilToolbar->addStickyItem($this->getTypeDropdown()); - - include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; - $button = ilSubmitButton::getInstance(); - $button->setCaption("exc_add_assignment"); - $button->setCommand("addAssignment"); - $ilToolbar->addStickyItem($button); - - - include_once("./Modules/Exercise/classes/class.ilAssignmentsTableGUI.php"); - $t = new ilAssignmentsTableGUI($this, "listAssignments", $this->exercise_id); - $tpl->setContent($t->getHTML()); - } - - /** - * Create assignment - */ - function addAssignmentObject() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - - // #16163 - ignore ass id from request - $this->assignment = null; - - if(!(int)$_POST["type"]) - { - $ilCtrl->redirect($this, "listAssignments"); - } - - $form = $this->initAssignmentForm((int)$_POST["type"], "create"); - $tpl->setContent($form->getHTML()); - } - - /** - * Get type selection dropdown - * - * @return ilSelectInputGUI - */ - protected function getTypeDropdown() - { - $lng = $this->lng; - - $types = []; - foreach ($this->types->getAllActivated() as $k => $t) - { - $types[$k] = $t->getTitle(); - } - - $ty = new ilSelectInputGUI($lng->txt("exc_assignment_type"), "type"); - $ty->setOptions($types); - $ty->setRequired(true); - return $ty; - } - - /** - * Init assignment form. - * - * @param int $a_type - * @param int $a_mode "create"/"edit" - */ - protected function initAssignmentForm($a_type, $a_mode = "create") - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $ass_type = $this->types->getById($a_type); - $ass_type_gui = $this->type_guis->getById($a_type); - $ilCtrl->setParameter($this, "ass_type", $a_type); - - $lng->loadLanguageModule("form"); - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - if ($a_mode == "edit") - { - $form->setTitle($lng->txt("exc_edit_assignment")); - } - else - { - $form->setTitle($lng->txt("exc_new_assignment")); - } - $form->setFormAction($ilCtrl->getFormAction($this)); - - // title - $ti = new ilTextInputGUI($lng->txt("title"), "title"); - $ti->setMaxLength(200); - $ti->setRequired(true); - $form->addItem($ti); - - // type - $ty = $this->getTypeDropdown(); - $ty->setValue($a_type); - $ty->setDisabled(true); - $form->addItem($ty); - - // - // type specific start - // - - $ass_type_gui->addEditFormCustomProperties($form); - - // - // type specific end - // - - if($ass_type->usesTeams()) - { - if($a_mode == "edit") { - $has_teams = (bool)count(ilExAssignmentTeam::getAssignmentTeamMap($this->assignment->getId())); - } else { - $has_teams = false; - } - - // Radio for creators - $rd_team = new ilRadioGroupInputGUI($lng->txt("exc_team_formation"), "team_creator"); - - $radio_participants = new ilRadioOption( - $lng->txt("exc_team_by_participants"), - ilExAssignment::TEAMS_FORMED_BY_PARTICIPANTS, - $lng->txt("exc_team_by_participants_info") - ); - - $radio_tutors = new ilRadioOption( - $lng->txt("exc_team_by_tutors"), - ilExAssignment::TEAMS_FORMED_BY_TUTOR, - $lng->txt("exc_team_by_tutors_info") - ); - - #23679 - if(!$has_teams) - { - // Creation options - $rd_creation_method = new ilRadioGroupInputGUI($lng->txt("exc_team_creation"), "team_creation"); - $rd_creation_method->setRequired(true); - - //manual - $rd_creation_manual = new ilRadioOption( - $lng->txt("exc_team_by_tutors_manual"), - 0, - $lng->txt("exc_team_by_tutors_manual_info") - ); - $rd_creation_method->addOption($rd_creation_manual); - - //random options + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var int + */ + protected $exercise_id; + + /** + * @var ilExAssignment + */ + protected $assignment; + + /** + * @var bool + */ + protected $enable_peer_review_completion; + + /** + * @var ilExAssignmentTypes + */ + protected $types; + + /** + * Constructor + * + * @param int $a_exercise_id + * @param bool $a_enable_peer_review_completion_settings + * @param ilExAssignment $a_ass + * @return object + */ + public function __construct($a_exercise_id, $a_enable_peer_review_completion_settings, ilExAssignment $a_ass = null) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->tabs = $DIC->tabs(); + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + $this->toolbar = $DIC->toolbar(); + $this->settings = $DIC->settings(); + $this->help = $DIC["ilHelp"]; + $this->exercise_id = $a_exercise_id; + $this->assignment = $a_ass; + $this->enable_peer_review_completion = (bool) $a_enable_peer_review_completion_settings; + include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssignmentTypes.php"); + $this->types = ilExAssignmentTypes::getInstance(); + include_once("./Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssignmentTypesGUI.php"); + $this->type_guis = ilExAssignmentTypesGUI::getInstance(); + } + + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + $lng = $this->lng; + + $class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd("listAssignments"); + + switch ($class) { + case "ilpropertyformgui": + $form = $this->initAssignmentForm($_GET["ass_type"]); + $ilCtrl->forwardCommand($form); + break; + + // instruction files + case "ilexassignmentfilesystemgui": + $this->setAssignmentHeader(); + $ilTabs->activateTab("ass_files"); + + include_once("./Modules/Exercise/classes/class.ilFSWebStorageExercise.php"); + $fstorage = new ilFSWebStorageExercise($this->exercise_id, $this->assignment->getId()); + $fstorage->create(); + + include_once("./Modules/Exercise/classes/class.ilExAssignmentFileSystemGUI.php"); + $fs_gui = new ilExAssignmentFileSystemGUI($fstorage->getPath()); + $fs_gui->setTitle($lng->txt("exc_instruction_files")); + $fs_gui->setTableId("excassfil" . $this->assignment->getId()); + $fs_gui->setAllowDirectories(false); + $ilCtrl->forwardCommand($fs_gui); + break; + + case "ilexpeerreviewgui": + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, "listAssignments") + ); + + include_once("./Modules/Exercise/classes/class.ilExPeerReviewGUI.php"); + $peer_gui = new ilExPeerReviewGUI($this->assignment); + $ilCtrl->forwardCommand($peer_gui); + break; + + default: + $this->{$cmd . "Object"}(); + break; + } + } + + /** + * List assignments + */ + public function listAssignmentsObject() + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $ilToolbar->setFormAction($ilCtrl->getFormAction($this, "addAssignment")); + + include_once "Services/Form/classes/class.ilSelectInputGUI.php"; + $ilToolbar->addStickyItem($this->getTypeDropdown()); + + include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; + $button = ilSubmitButton::getInstance(); + $button->setCaption("exc_add_assignment"); + $button->setCommand("addAssignment"); + $ilToolbar->addStickyItem($button); + + + include_once("./Modules/Exercise/classes/class.ilAssignmentsTableGUI.php"); + $t = new ilAssignmentsTableGUI($this, "listAssignments", $this->exercise_id); + $tpl->setContent($t->getHTML()); + } + + /** + * Create assignment + */ + public function addAssignmentObject() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + + // #16163 - ignore ass id from request + $this->assignment = null; + + if (!(int) $_POST["type"]) { + $ilCtrl->redirect($this, "listAssignments"); + } + + $form = $this->initAssignmentForm((int) $_POST["type"], "create"); + $tpl->setContent($form->getHTML()); + } + + /** + * Get type selection dropdown + * + * @return ilSelectInputGUI + */ + protected function getTypeDropdown() + { + $lng = $this->lng; + + $types = []; + foreach ($this->types->getAllActivated() as $k => $t) { + $types[$k] = $t->getTitle(); + } + + $ty = new ilSelectInputGUI($lng->txt("exc_assignment_type"), "type"); + $ty->setOptions($types); + $ty->setRequired(true); + return $ty; + } + + /** + * Init assignment form. + * + * @param int $a_type + * @param int $a_mode "create"/"edit" + */ + protected function initAssignmentForm($a_type, $a_mode = "create") + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $ass_type = $this->types->getById($a_type); + $ass_type_gui = $this->type_guis->getById($a_type); + $ilCtrl->setParameter($this, "ass_type", $a_type); + + $lng->loadLanguageModule("form"); + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + if ($a_mode == "edit") { + $form->setTitle($lng->txt("exc_edit_assignment")); + } else { + $form->setTitle($lng->txt("exc_new_assignment")); + } + $form->setFormAction($ilCtrl->getFormAction($this)); + + // title + $ti = new ilTextInputGUI($lng->txt("title"), "title"); + $ti->setMaxLength(200); + $ti->setRequired(true); + $form->addItem($ti); + + // type + $ty = $this->getTypeDropdown(); + $ty->setValue($a_type); + $ty->setDisabled(true); + $form->addItem($ty); + + // + // type specific start + // + + $ass_type_gui->addEditFormCustomProperties($form); + + // + // type specific end + // + + if ($ass_type->usesTeams()) { + if ($a_mode == "edit") { + $has_teams = (bool) count(ilExAssignmentTeam::getAssignmentTeamMap($this->assignment->getId())); + } else { + $has_teams = false; + } + + // Radio for creators + $rd_team = new ilRadioGroupInputGUI($lng->txt("exc_team_formation"), "team_creator"); + + $radio_participants = new ilRadioOption( + $lng->txt("exc_team_by_participants"), + ilExAssignment::TEAMS_FORMED_BY_PARTICIPANTS, + $lng->txt("exc_team_by_participants_info") + ); + + $radio_tutors = new ilRadioOption( + $lng->txt("exc_team_by_tutors"), + ilExAssignment::TEAMS_FORMED_BY_TUTOR, + $lng->txt("exc_team_by_tutors_info") + ); + + #23679 + if (!$has_teams) { + // Creation options + $rd_creation_method = new ilRadioGroupInputGUI($lng->txt("exc_team_creation"), "team_creation"); + $rd_creation_method->setRequired(true); + + //manual + $rd_creation_manual = new ilRadioOption( + $lng->txt("exc_team_by_tutors_manual"), + 0, + $lng->txt("exc_team_by_tutors_manual_info") + ); + $rd_creation_method->addOption($rd_creation_manual); + + //random options $add_info = ""; if ($this->getExerciseTotalMembers() < 4) { - $add_info = " ".$lng->txt("exc_team_by_random_add_info").""; + $add_info = " " . $lng->txt("exc_team_by_random_add_info") . ""; + } + $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"); + } 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 @@ -10,579 +10,525 @@ */ class ilExAssignmentGUI { - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilCtrl - */ - protected $ctrl; - - protected $exc; // [ilObjExercise] - protected $current_ass_id; // [int] - - /** - * Constructor - */ - 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 - */ - 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(); - } - } - else if (!$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(); - } - else if ($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 - */ - 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); - } - 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 = ''.$lng->txt('; - $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 = '' . $lng->txt('; + $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[] = '

'. - '

'.$crit->getTitle().'
'. - '
'.$crit->getHTML($values[$crit_id]).'
'. - '

'; - } - - $acc->addItem( - ilUserUtil::getNamePresentation($peer_id, false, false, "", true), - '
'.implode("\n", $acc_html).'
' - ); - } - - $peer_data = $acc->getHTML(); - } - $this->tpl->setCurrentBlock("peer_bl"); - $this->tpl->setVariable("PEER_REVIEW", $peer_data); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setVariable("USER_NAME", $a_set["uname"]); - $this->tpl->setVariable("USER_DATE", - ilDatePresentation::formatDate(new ilDate($a_set["udate"], IL_CAL_DATETIME))); - $this->tpl->setVariable("USER_TEXT", nl2br($a_set["utext"])); - } -} - -?> \ No newline at end of file + +* @version $Id$ +* +* @ingroup ModulesExercise +*/ +class ilExAssignmentListTextTableGUI extends ilTable2GUI +{ + protected $ass; // [ilExAssignment] + protected $show_peer_review; // [bool] + protected $peer_review; // [ilExPeerReview] + + public 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[] = '

' . + '

' . $crit->getTitle() . '
' . + '
' . $crit->getHTML($values[$crit_id]) . '
' . + '

'; + } + + $acc->addItem( + ilUserUtil::getNamePresentation($peer_id, false, false, "", true), + '
' . implode("\n", $acc_html) . '
' + ); + } + + $peer_data = $acc->getHTML(); + } + $this->tpl->setCurrentBlock("peer_bl"); + $this->tpl->setVariable("PEER_REVIEW", $peer_data); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setVariable("USER_NAME", $a_set["uname"]); + $this->tpl->setVariable( + "USER_DATE", + ilDatePresentation::formatDate(new ilDate($a_set["udate"], IL_CAL_DATETIME)) + ); + $this->tpl->setVariable("USER_TEXT", nl2br($a_set["utext"])); + } +} diff --git a/Modules/Exercise/classes/class.ilExAssignmentMemberStatus.php b/Modules/Exercise/classes/class.ilExAssignmentMemberStatus.php index 0a9fcfb99bb905fa4b29ba464df631bfecbeb832..4c0527c12d9cbafbb5c1e66aa178eb579bd97a46 100644 --- a/Modules/Exercise/classes/class.ilExAssignmentMemberStatus.php +++ b/Modules/Exercise/classes/class.ilExAssignmentMemberStatus.php @@ -9,300 +9,287 @@ */ class ilExAssignmentMemberStatus { - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; - protected $ass_id; // [int] - protected $user_id; // [int] - protected $notice; // [string] - protected $returned; // [int] - protected $solved; // [int] - obsolete?! - protected $sent; // [int] - protected $sent_time; // [datetime] - protected $feedback; // [int] - protected $feedback_time; // [datetime] - protected $status = "notgraded"; // [string] - protected $status_time; // [datetime] - protected $mark; // [string] - protected $comment; // [string] - protected $db_exists; // [bool] - protected $returned_update; // [bool] - protected $status_update; // [bool] - - public function __construct($a_ass_id, $a_user_id) - { - global $DIC; + protected $ass_id; // [int] + protected $user_id; // [int] + protected $notice; // [string] + protected $returned; // [int] + protected $solved; // [int] - obsolete?! + protected $sent; // [int] + protected $sent_time; // [datetime] + protected $feedback; // [int] + protected $feedback_time; // [datetime] + protected $status = "notgraded"; // [string] + protected $status_time; // [datetime] + protected $mark; // [string] + protected $comment; // [string] + protected $db_exists; // [bool] + protected $returned_update; // [bool] + protected $status_update; // [bool] + + public function __construct($a_ass_id, $a_user_id) + { + global $DIC; - $this->db = $DIC->database(); - $this->ass_id = $a_ass_id; - $this->user_id = $a_user_id; - - $this->read(); - } - - public function setNotice($a_value) - { - $this->notice = $a_value; - } - - public function getNotice() - { - return $this->notice; - } - - public function setReturned($a_value) - { - if($a_value && - !$this->returned) - { - $this->returned_update = true; - } - $this->returned = $a_value; - } - - public function getReturned() - { - return $this->returned; - } - - public function setSolved($a_value) - { - $this->solved = $a_value; - } - - public function getSolved() - { - return $this->solved; - } - - protected function setStatusTime($a_value) - { - $this->status_time = $a_value; - } - - public function getStatusTime() - { - return $this->status_time; - } - - public function setSent($a_value) - { - if($a_value && $a_value != $this->sent) - { - $this->setSentTime(ilUtil::now()); - } - $this->sent = $a_value; - } - - public function getSent() - { - return $this->sent; - } - - protected function setSentTime($a_value) - { - $this->sent_time = $a_value; - } - - public function getSentTime() - { - return $this->sent_time; - } - - public function setFeedback($a_value) - { - if($a_value != $this->sent) - { - $this->setFeedbackTime(ilUtil::now()); - } - $this->feedback = $a_value; - } - - public function getFeedback() - { - return $this->feedback; - } - - protected function setFeedbackTime($a_value) - { - $this->feedback_time = $a_value; - } - - public function getFeedbackTime() - { - return $this->feedback_time; - } - - public function setStatus($a_value) - { - if($a_value != $this->status) - { - $this->setStatusTime(ilUtil::now()); - $this->status = $a_value; - $this->status_update = true; - } - } - - public function getStatus() - { - return $this->status; - } - - public function setMark($a_value) - { - if($a_value != $this->mark) - { - $this->setStatusTime(ilUtil::now()); - } - $this->mark = $a_value; - } - - public function getMark() - { - return $this->mark; - } - - public function setComment($a_value) - { - $this->comment = $a_value; - } - - public function getComment() - { - return $this->comment; - } - - protected function read() - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT * FROM exc_mem_ass_status". - " WHERE ass_id = ".$ilDB->quote($this->ass_id, "integer"). - " AND usr_id = ".$ilDB->quote($this->user_id, "integer")); - if($ilDB->numRows($set)) - { - $row = $ilDB->fetchAssoc($set); - - // not using setters to circumvent any datetime-logic/-magic - $this->notice = $row["notice"]; - $this->returned = $row["returned"]; - $this->solved = $row["solved"]; - $this->status_time = $row["status_time"]; - $this->sent = $row["sent"]; - $this->sent_time = $row["sent_time"]; - $this->feedback_time = $row["feedback_time"]; - $this->feedback = $row["feedback"]; - $this->status = $row["status"]; - $this->mark = $row["mark"]; - $this->comment = $row["u_comment"]; - $this->db_exists = true; - } - } - - protected function getFields() - { - return array( - "notice" => array("text", $this->getNotice()) - ,"returned" => array("integer", $this->getReturned()) - ,"solved" => array("integer", $this->getSolved()) - ,"status_time" => array("timestamp", $this->getStatusTime()) - ,"sent" => array("integer", $this->getSent()) - ,"sent_time" => array("timestamp", $this->getSentTime()) - ,"feedback_time" => array("timestamp", $this->getFeedbackTime()) - ,"feedback" => array("integer", $this->getFeedback()) - ,"status" => array("text", $this->getStatus()) - ,"mark" => array("text", $this->getMark()) - ,"u_comment" => array("text", $this->getComment()) - ); - } - - public function update() - { - $ilDB = $this->db; - - $keys = array( - "ass_id" => array("integer", $this->ass_id) - ,"usr_id" => array("integer", $this->user_id) - ); - $fields = $this->getFields(); - if(!$this->db_exists) - { - $fields = array_merge($keys, $fields); - $ilDB->insert("exc_mem_ass_status", $fields); - } - else - { - $ilDB->update("exc_mem_ass_status", $fields, $keys); - } - - if($this->returned_update) - { - $this->postUpdateReturned(); - } - if($this->status_update) - { - $this->postUpdateStatus(); - } - } - - protected function postUpdateReturned() - { - $ilDB = $this->db; - - // first upload => notification on submission? - $set = $ilDB->query("SELECT fb_cron, fb_date, fb_file". - " FROM exc_assignment". - " WHERE id = ".$ilDB->quote($this->ass_id, "integer")); - $row = $ilDB->fetchAssoc($set); - if($row["fb_cron"] && - $row["fb_file"] && - $row["fb_date"] == ilExAssignment::FEEDBACK_DATE_SUBMISSION) // #16200 - { - include_once "Modules/Exercise/classes/class.ilExAssignment.php"; - ilExAssignment::sendFeedbackNotifications($this->ass_id, $this->user_id); - } - } - - protected function postUpdateStatus() - { - include_once "Modules/Exercise/classes/class.ilExAssignment.php"; - $ass = new ilExAssignment($this->ass_id); - $exc = new ilObjExercise($ass->getExerciseId(), false); - $exc->updateUserStatus($this->user_id); - } - - public function getStatusIcon() - { - switch($this->getStatus()) - { - case "passed": - return "scorm/passed.svg"; - - case "failed": - return "scorm/failed.svg"; - - default: - return "scorm/not_attempted.svg"; - } - } - - /** - * Check whether exercise has been sent to any student per mail. - */ - public static function lookupAnyExerciseSent($a_ass_id) - { - global $DIC; + $this->db = $DIC->database(); + $this->ass_id = $a_ass_id; + $this->user_id = $a_user_id; + + $this->read(); + } + + public function setNotice($a_value) + { + $this->notice = $a_value; + } + + public function getNotice() + { + return $this->notice; + } + + public function setReturned($a_value) + { + if ($a_value && + !$this->returned) { + $this->returned_update = true; + } + $this->returned = $a_value; + } + + public function getReturned() + { + return $this->returned; + } + + public function setSolved($a_value) + { + $this->solved = $a_value; + } + + public function getSolved() + { + return $this->solved; + } + + protected function setStatusTime($a_value) + { + $this->status_time = $a_value; + } + + public function getStatusTime() + { + return $this->status_time; + } + + public function setSent($a_value) + { + if ($a_value && $a_value != $this->sent) { + $this->setSentTime(ilUtil::now()); + } + $this->sent = $a_value; + } + + public function getSent() + { + return $this->sent; + } + + protected function setSentTime($a_value) + { + $this->sent_time = $a_value; + } + + public function getSentTime() + { + return $this->sent_time; + } + + public function setFeedback($a_value) + { + if ($a_value != $this->sent) { + $this->setFeedbackTime(ilUtil::now()); + } + $this->feedback = $a_value; + } + + public function getFeedback() + { + return $this->feedback; + } + + protected function setFeedbackTime($a_value) + { + $this->feedback_time = $a_value; + } + + public function getFeedbackTime() + { + return $this->feedback_time; + } + + public function setStatus($a_value) + { + if ($a_value != $this->status) { + $this->setStatusTime(ilUtil::now()); + $this->status = $a_value; + $this->status_update = true; + } + } + + public function getStatus() + { + return $this->status; + } + + public function setMark($a_value) + { + if ($a_value != $this->mark) { + $this->setStatusTime(ilUtil::now()); + } + $this->mark = $a_value; + } + + public function getMark() + { + return $this->mark; + } + + public function setComment($a_value) + { + $this->comment = $a_value; + } + + public function getComment() + { + return $this->comment; + } + + protected function read() + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT * FROM exc_mem_ass_status" . + " WHERE ass_id = " . $ilDB->quote($this->ass_id, "integer") . + " AND usr_id = " . $ilDB->quote($this->user_id, "integer")); + if ($ilDB->numRows($set)) { + $row = $ilDB->fetchAssoc($set); + + // not using setters to circumvent any datetime-logic/-magic + $this->notice = $row["notice"]; + $this->returned = $row["returned"]; + $this->solved = $row["solved"]; + $this->status_time = $row["status_time"]; + $this->sent = $row["sent"]; + $this->sent_time = $row["sent_time"]; + $this->feedback_time = $row["feedback_time"]; + $this->feedback = $row["feedback"]; + $this->status = $row["status"]; + $this->mark = $row["mark"]; + $this->comment = $row["u_comment"]; + $this->db_exists = true; + } + } + + protected function getFields() + { + return array( + "notice" => array("text", $this->getNotice()) + ,"returned" => array("integer", $this->getReturned()) + ,"solved" => array("integer", $this->getSolved()) + ,"status_time" => array("timestamp", $this->getStatusTime()) + ,"sent" => array("integer", $this->getSent()) + ,"sent_time" => array("timestamp", $this->getSentTime()) + ,"feedback_time" => array("timestamp", $this->getFeedbackTime()) + ,"feedback" => array("integer", $this->getFeedback()) + ,"status" => array("text", $this->getStatus()) + ,"mark" => array("text", $this->getMark()) + ,"u_comment" => array("text", $this->getComment()) + ); + } + + public function update() + { + $ilDB = $this->db; + + $keys = array( + "ass_id" => array("integer", $this->ass_id) + ,"usr_id" => array("integer", $this->user_id) + ); + $fields = $this->getFields(); + if (!$this->db_exists) { + $fields = array_merge($keys, $fields); + $ilDB->insert("exc_mem_ass_status", $fields); + } else { + $ilDB->update("exc_mem_ass_status", $fields, $keys); + } + + if ($this->returned_update) { + $this->postUpdateReturned(); + } + if ($this->status_update) { + $this->postUpdateStatus(); + } + } + + protected function postUpdateReturned() + { + $ilDB = $this->db; + + // first upload => notification on submission? + $set = $ilDB->query("SELECT fb_cron, fb_date, fb_file" . + " FROM exc_assignment" . + " WHERE id = " . $ilDB->quote($this->ass_id, "integer")); + $row = $ilDB->fetchAssoc($set); + if ($row["fb_cron"] && + $row["fb_file"] && + $row["fb_date"] == ilExAssignment::FEEDBACK_DATE_SUBMISSION) { // #16200 + include_once "Modules/Exercise/classes/class.ilExAssignment.php"; + ilExAssignment::sendFeedbackNotifications($this->ass_id, $this->user_id); + } + } + + protected function postUpdateStatus() + { + include_once "Modules/Exercise/classes/class.ilExAssignment.php"; + $ass = new ilExAssignment($this->ass_id); + $exc = new ilObjExercise($ass->getExerciseId(), false); + $exc->updateUserStatus($this->user_id); + } + + public function getStatusIcon() + { + switch ($this->getStatus()) { + case "passed": + return "scorm/passed.svg"; + + case "failed": + return "scorm/failed.svg"; + + default: + return "scorm/not_attempted.svg"; + } + } + + /** + * Check whether exercise has been sent to any student per mail. + */ + public static function lookupAnyExerciseSent($a_ass_id) + { + global $DIC; - $ilDB = $DIC->database(); + $ilDB = $DIC->database(); - $q = "SELECT count(*) AS cnt". - " FROM exc_mem_ass_status". - " WHERE NOT sent_time IS NULL". - " AND ass_id = ".$ilDB->quote($a_ass_id, "integer"); - $set = $ilDB->query($q); - $rec = $ilDB->fetchAssoc($set); - return ($rec["cnt"] > 0); - } + $q = "SELECT count(*) AS cnt" . + " FROM exc_mem_ass_status" . + " WHERE NOT sent_time IS NULL" . + " AND ass_id = " . $ilDB->quote($a_ass_id, "integer"); + $set = $ilDB->query($q); + $rec = $ilDB->fetchAssoc($set); + return ($rec["cnt"] > 0); + } } diff --git a/Modules/Exercise/classes/class.ilExAssignmentPeerReviewOverviewTableGUI.php b/Modules/Exercise/classes/class.ilExAssignmentPeerReviewOverviewTableGUI.php index 8e2fbd255bb5aff3e5ec785cf4d1fb7fbe35b4f9..0dfdaefd416088d957ed8abd5ba5cf42c62134db 100644 --- a/Modules/Exercise/classes/class.ilExAssignmentPeerReviewOverviewTableGUI.php +++ b/Modules/Exercise/classes/class.ilExAssignmentPeerReviewOverviewTableGUI.php @@ -11,140 +11,128 @@ include_once './Services/Table/classes/class.ilTable2GUI.php'; */ class ilExAssignmentPeerReviewOverviewTableGUI extends ilTable2GUI { - protected $ass; // [ilExAssignment] - protected $panel_info; // [array] - - /** - * Constructor - * - * @param ilObject $a_parent_obj - * @param string $a_parent_cmd - * @param ilExAssignment $a_ass - */ - public function __construct($a_parent_obj, $a_parent_cmd, ilExAssignment $a_ass) - { - global $DIC; + protected $ass; // [ilExAssignment] + protected $panel_info; // [array] + + /** + * Constructor + * + * @param ilObject $a_parent_obj + * @param string $a_parent_cmd + * @param ilExAssignment $a_ass + */ + public function __construct($a_parent_obj, $a_parent_cmd, ilExAssignment $a_ass) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $ilCtrl = $DIC->ctrl(); - - $this->ass = $a_ass; - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setLimit(9999); - - $this->addColumn($this->lng->txt("exc_peer_review_recipient"), "recipient"); - $this->addColumn($this->lng->txt("exc_peer_review_giver"), "giver"); - $this->addColumn($this->lng->txt("status"), "status"); - - $this->setDefaultOrderField("recipient"); - - $this->setRowTemplate("tpl.exc_peer_review_overview_row.html", "Modules/Exercise"); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd)); + $this->ctrl = $DIC->ctrl(); + $ilCtrl = $DIC->ctrl(); + + $this->ass = $a_ass; + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setLimit(9999); + + $this->addColumn($this->lng->txt("exc_peer_review_recipient"), "recipient"); + $this->addColumn($this->lng->txt("exc_peer_review_giver"), "giver"); + $this->addColumn($this->lng->txt("status"), "status"); + + $this->setDefaultOrderField("recipient"); + + $this->setRowTemplate("tpl.exc_peer_review_overview_row.html", "Modules/Exercise"); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd)); - $this->setTitle($a_ass->getTitle().": ".$this->lng->txt("exc_peer_review_overview")); - - $this->disable("numinfo"); - - $this->getItems(); - - $this->addCommandButton("confirmResetPeerReview", $this->lng->txt("exc_peer_review_reset")); - } - - protected function translateUserIds($a_user_ids, $a_implode = false) - { - if(!is_array($a_user_ids) && is_numeric($a_user_ids)) - { - $a_user_ids = array($a_user_ids); - } - - $res = array(); - - include_once "Services/User/classes/class.ilUserUtil.php"; - foreach(array_unique($a_user_ids) as $user_id) - { - $res[] = ilUserUtil::getNamePresentation($user_id); - } - - if($a_implode) - { - $res = implode("
", $res); - } - return $res; - } - - public function getPanelInfo() - { - return $this->panel_info; - } - - protected function getItems() - { - $data = array(); - - include_once("./Modules/Exercise/classes/class.ilExPeerReview.php"); - $peer_review = new ilExPeerReview($this->ass); - $tmp = $peer_review->validatePeerReviewGroups(); - - if(!is_array($tmp)) - { - return; - } - - foreach($tmp["reviews"] as $peer_id => $reviews) - { - $peer = $this->translateUserIds($peer_id, true); - - foreach($reviews as $giver_id => $status) - { - $data[] = array("recipient" => $peer, - "giver" => $this->translateUserIds($giver_id, true), - "status" => ($status ? $this->lng->txt("valid") : "")); - } - } - - if($tmp["missing_user_ids"]) - { - $this->panel_info[] = array( - "title" => $this->lng->txt("exc_peer_review_missing_users"), - "value" => $this->translateUserIds($tmp["missing_user_ids"]) - ); - } - - if($tmp["not_returned_ids"]) - { - $this->panel_info[] = array( - "title" => $this->lng->txt("exc_peer_review_not_returned_users"), - "value" => $this->translateUserIds($tmp["not_returned_ids"]) - ); - } - - if($tmp["invalid_peer_ids"]) - { - $this->panel_info[] = array( - "title" => $this->lng->txt("exc_peer_review_invalid_peer_ids"), - "value" => $this->translateUserIds($tmp["invalid_peer_ids"]) - ); - } - - if($tmp["invalid_giver_ids"]) - { - $this->panel_info[] = array( - "title" => $this->lng->txt("exc_peer_review_invalid_giver_ids"), - "value" => $this->translateUserIds($tmp["invalid_giver_ids"]) - ); - } - - $this->setData($data); - } - - protected function fillRow($a_set) - { - $this->tpl->setVariable("PEER", $a_set["recipient"]); - $this->tpl->setVariable("GIVER", $a_set["giver"]); - $this->tpl->setVariable("STATUS", $a_set["status"]); - } + $this->setTitle($a_ass->getTitle() . ": " . $this->lng->txt("exc_peer_review_overview")); + + $this->disable("numinfo"); + + $this->getItems(); + + $this->addCommandButton("confirmResetPeerReview", $this->lng->txt("exc_peer_review_reset")); + } + + protected function translateUserIds($a_user_ids, $a_implode = false) + { + if (!is_array($a_user_ids) && is_numeric($a_user_ids)) { + $a_user_ids = array($a_user_ids); + } + + $res = array(); + + include_once "Services/User/classes/class.ilUserUtil.php"; + foreach (array_unique($a_user_ids) as $user_id) { + $res[] = ilUserUtil::getNamePresentation($user_id); + } + + if ($a_implode) { + $res = implode("
", $res); + } + return $res; + } + + public function getPanelInfo() + { + return $this->panel_info; + } + + protected function getItems() + { + $data = array(); + + include_once("./Modules/Exercise/classes/class.ilExPeerReview.php"); + $peer_review = new ilExPeerReview($this->ass); + $tmp = $peer_review->validatePeerReviewGroups(); + + if (!is_array($tmp)) { + return; + } + + foreach ($tmp["reviews"] as $peer_id => $reviews) { + $peer = $this->translateUserIds($peer_id, true); + + foreach ($reviews as $giver_id => $status) { + $data[] = array("recipient" => $peer, + "giver" => $this->translateUserIds($giver_id, true), + "status" => ($status ? $this->lng->txt("valid") : "")); + } + } + + if ($tmp["missing_user_ids"]) { + $this->panel_info[] = array( + "title" => $this->lng->txt("exc_peer_review_missing_users"), + "value" => $this->translateUserIds($tmp["missing_user_ids"]) + ); + } + + if ($tmp["not_returned_ids"]) { + $this->panel_info[] = array( + "title" => $this->lng->txt("exc_peer_review_not_returned_users"), + "value" => $this->translateUserIds($tmp["not_returned_ids"]) + ); + } + + if ($tmp["invalid_peer_ids"]) { + $this->panel_info[] = array( + "title" => $this->lng->txt("exc_peer_review_invalid_peer_ids"), + "value" => $this->translateUserIds($tmp["invalid_peer_ids"]) + ); + } + + if ($tmp["invalid_giver_ids"]) { + $this->panel_info[] = array( + "title" => $this->lng->txt("exc_peer_review_invalid_giver_ids"), + "value" => $this->translateUserIds($tmp["invalid_giver_ids"]) + ); + } + + $this->setData($data); + } + + protected function fillRow($a_set) + { + $this->tpl->setVariable("PEER", $a_set["recipient"]); + $this->tpl->setVariable("GIVER", $a_set["giver"]); + $this->tpl->setVariable("STATUS", $a_set["status"]); + } } - -?> \ No newline at end of file diff --git a/Modules/Exercise/classes/class.ilExAssignmentPeerReviewTableGUI.php b/Modules/Exercise/classes/class.ilExAssignmentPeerReviewTableGUI.php index 60c9aebcf33dcde0f64a25eeb9ce9ee4e3442713..bdaddac218c5d9031daf3ef5c3259eedf95db227 100644 --- a/Modules/Exercise/classes/class.ilExAssignmentPeerReviewTableGUI.php +++ b/Modules/Exercise/classes/class.ilExAssignmentPeerReviewTableGUI.php @@ -13,182 +13,163 @@ include_once './Services/Rating/classes/class.ilRatingGUI.php'; */ class ilExAssignmentPeerReviewTableGUI extends ilTable2GUI { - protected $ass; // [ilExAssignment] - protected $user_id; // [int] - protected $peer_data; // [array] - protected $fstorage; // [ilFSStorageExercise] - protected $invalid; // [int] - - /** - * Constructor - * - * @param ilObject $a_parent_obj - * @param string $a_parent_cmd - * @param ilExAssignment $a_ass - * @param int $a_user_id - * @param array $a_peer_data - */ - public function __construct($a_parent_obj, $a_parent_cmd, ilExAssignment $a_ass, $a_user_id, array $a_peer_data) - { - global $DIC; + protected $ass; // [ilExAssignment] + protected $user_id; // [int] + protected $peer_data; // [array] + protected $fstorage; // [ilFSStorageExercise] + protected $invalid; // [int] + + /** + * Constructor + * + * @param ilObject $a_parent_obj + * @param string $a_parent_cmd + * @param ilExAssignment $a_ass + * @param int $a_user_id + * @param array $a_peer_data + */ + public function __construct($a_parent_obj, $a_parent_cmd, ilExAssignment $a_ass, $a_user_id, array $a_peer_data) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $ilCtrl = $DIC->ctrl(); - - $this->ass = $a_ass; - $this->user_id = $a_user_id; - $this->peer_data = $a_peer_data; - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setLimit(9999); - - $this->setTitle($a_ass->getTitle().": ".$this->lng->txt("exc_peer_review"). - " - ".$this->lng->txt("exc_peer_review_give")); - - if(!$this->ass->hasPeerReviewPersonalized()) - { - $this->addColumn($this->lng->txt("id"), "seq"); - #21260 - $this->setDefaultOrderField("seq"); - } - else - { - $this->addColumn($this->lng->txt("exc_peer_review_recipient"), "name"); - #21260 - $this->setDefaultOrderField("name"); - } - $this->addColumn($this->lng->txt("last_update"), "tstamp"); - $this->addColumn($this->lng->txt("valid"), "valid"); - $this->addColumn($this->lng->txt("action"), ""); - - $this->setRowTemplate("tpl.exc_peer_review_row.html", "Modules/Exercise"); - - $this->disable("numinfo"); - - $this->getItems(); - - if($this->ass->hasPeerReviewFileUpload()) - { - include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); - $this->fstorage = new ilFSStorageExercise($this->ass->getExerciseId(), $this->ass->getId()); - $this->fstorage->create(); - } - } - - public function getInvalidItems() - { - return $this->invalid; - } - - protected function getItems() - { - $data = array(); - - $personal = $this->ass->hasPeerReviewPersonalized(); - - if($personal) - { - include_once "Services/User/classes/class.ilUserUtil.php"; - } - - $peer_review = new ilExPeerReview($this->ass); - - foreach($this->peer_data as $item) - { - $row = array(); - - $row["giver_id"] = $item["giver_id"]; - $row["peer_id"] = $item["peer_id"]; - $row["tstamp"] = $item["tstamp"]; - - if(!$personal) - { - $row["seq"] = $item["seq"]; - } - else - { - $row["name"] = ilUserUtil::getNamePresentation($item["peer_id"]); - } - - // validate - $row["valid"] = $all_empty = true; - $submission = new ilExSubmission($this->ass, $item["peer_id"]); - $values = $submission->getPeerReview()->getPeerReviewValues($item["giver_id"], $item["peer_id"]); - foreach($this->ass->getPeerReviewCriteriaCatalogueItems() as $crit) - { - $crit_id = $crit->getId() - ? $crit->getId() - : $crit->getType(); - $crit->setPeerReviewContext( - $this->ass, - $item["giver_id"], - $item["peer_id"] - ); - if(!$crit->validate($values[$crit_id])) - { - $row["valid"] = false; - } - if($crit->hasValue($values[$crit_id])) - { - $all_empty = false; - } - } - if($all_empty) - { - $row["valid"] = false; - } - if(!$row["valid"]) - { - $this->invalid++; - } - - $data[] = $row; - } - - $this->setData($data); - } - - public function numericOrdering($a_field) - { - if(in_array($a_field, array("seq"))) - { - return true; - } - return false; - } + $this->ctrl = $DIC->ctrl(); + $ilCtrl = $DIC->ctrl(); + + $this->ass = $a_ass; + $this->user_id = $a_user_id; + $this->peer_data = $a_peer_data; + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setLimit(9999); + + $this->setTitle($a_ass->getTitle() . ": " . $this->lng->txt("exc_peer_review") . + " - " . $this->lng->txt("exc_peer_review_give")); + + if (!$this->ass->hasPeerReviewPersonalized()) { + $this->addColumn($this->lng->txt("id"), "seq"); + #21260 + $this->setDefaultOrderField("seq"); + } else { + $this->addColumn($this->lng->txt("exc_peer_review_recipient"), "name"); + #21260 + $this->setDefaultOrderField("name"); + } + $this->addColumn($this->lng->txt("last_update"), "tstamp"); + $this->addColumn($this->lng->txt("valid"), "valid"); + $this->addColumn($this->lng->txt("action"), ""); + + $this->setRowTemplate("tpl.exc_peer_review_row.html", "Modules/Exercise"); + + $this->disable("numinfo"); + + $this->getItems(); + + if ($this->ass->hasPeerReviewFileUpload()) { + include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); + $this->fstorage = new ilFSStorageExercise($this->ass->getExerciseId(), $this->ass->getId()); + $this->fstorage->create(); + } + } + + public function getInvalidItems() + { + return $this->invalid; + } + + protected function getItems() + { + $data = array(); + + $personal = $this->ass->hasPeerReviewPersonalized(); + + if ($personal) { + include_once "Services/User/classes/class.ilUserUtil.php"; + } + + $peer_review = new ilExPeerReview($this->ass); + + foreach ($this->peer_data as $item) { + $row = array(); + + $row["giver_id"] = $item["giver_id"]; + $row["peer_id"] = $item["peer_id"]; + $row["tstamp"] = $item["tstamp"]; + + if (!$personal) { + $row["seq"] = $item["seq"]; + } else { + $row["name"] = ilUserUtil::getNamePresentation($item["peer_id"]); + } + + // validate + $row["valid"] = $all_empty = true; + $submission = new ilExSubmission($this->ass, $item["peer_id"]); + $values = $submission->getPeerReview()->getPeerReviewValues($item["giver_id"], $item["peer_id"]); + foreach ($this->ass->getPeerReviewCriteriaCatalogueItems() as $crit) { + $crit_id = $crit->getId() + ? $crit->getId() + : $crit->getType(); + $crit->setPeerReviewContext( + $this->ass, + $item["giver_id"], + $item["peer_id"] + ); + if (!$crit->validate($values[$crit_id])) { + $row["valid"] = false; + } + if ($crit->hasValue($values[$crit_id])) { + $all_empty = false; + } + } + if ($all_empty) { + $row["valid"] = false; + } + if (!$row["valid"]) { + $this->invalid++; + } + + $data[] = $row; + } + + $this->setData($data); + } + + public function numericOrdering($a_field) + { + if (in_array($a_field, array("seq"))) { + return true; + } + return false; + } - protected function fillRow($a_set) - { - $ilCtrl = $this->ctrl; - - if(isset($a_set["seq"])) - { - $this->tpl->setVariable("VAL_SEQ", $a_set["seq"]); - } - else - { - $this->tpl->setVariable("VAL_SEQ", $a_set["name"]); - } - - if($a_set["tstamp"]) - { - $a_set["tstamp"] = ilDatePresentation::formatDate(new ilDateTime($a_set["tstamp"], IL_CAL_DATETIME)); - } - $this->tpl->setVariable("VAL_TSTAMP", $a_set["tstamp"]); - - $this->tpl->setVariable("VAL_STATUS", $a_set["valid"] - ? $this->lng->txt("yes") - : $this->lng->txt("no") - ); - - $ilCtrl->setParameter($this->parent_obj, "peer_id", $a_set["peer_id"]); - $url = $ilCtrl->getLinkTarget($this->parent_obj, "editPeerReviewItem"); - $ilCtrl->setParameter($this->parent_obj, "pid", ""); - - $this->tpl->setVariable("TXT_ACTION", $this->lng->txt("edit")); - $this->tpl->setVariable("URL_ACTION", $url); - } + protected function fillRow($a_set) + { + $ilCtrl = $this->ctrl; + + if (isset($a_set["seq"])) { + $this->tpl->setVariable("VAL_SEQ", $a_set["seq"]); + } else { + $this->tpl->setVariable("VAL_SEQ", $a_set["name"]); + } + + if ($a_set["tstamp"]) { + $a_set["tstamp"] = ilDatePresentation::formatDate(new ilDateTime($a_set["tstamp"], IL_CAL_DATETIME)); + } + $this->tpl->setVariable("VAL_TSTAMP", $a_set["tstamp"]); + + $this->tpl->setVariable( + "VAL_STATUS", + $a_set["valid"] + ? $this->lng->txt("yes") + : $this->lng->txt("no") + ); + + $ilCtrl->setParameter($this->parent_obj, "peer_id", $a_set["peer_id"]); + $url = $ilCtrl->getLinkTarget($this->parent_obj, "editPeerReviewItem"); + $ilCtrl->setParameter($this->parent_obj, "pid", ""); + + $this->tpl->setVariable("TXT_ACTION", $this->lng->txt("edit")); + $this->tpl->setVariable("URL_ACTION", $url); + } } - -?> \ No newline at end of file diff --git a/Modules/Exercise/classes/class.ilExAssignmentReminder.php b/Modules/Exercise/classes/class.ilExAssignmentReminder.php index 87aebe5b8044e27e2c38fc636b830dfff176eb00..0925feb5aed55628445aa89376f52cb05c6cfff4 100644 --- a/Modules/Exercise/classes/class.ilExAssignmentReminder.php +++ b/Modules/Exercise/classes/class.ilExAssignmentReminder.php @@ -13,311 +13,306 @@ */ class ilExAssignmentReminder { - const SUBMIT_REMINDER = "submit"; - const GRADE_REMINDER = "grade"; - const FEEDBACK_REMINDER = "peer"; - - protected $db; - protected $tree; - protected $now; - - protected $rmd_status; - protected $rmd_start; - protected $rmd_end; - protected $rmd_frequency; - protected $rmd_last_send; - protected $rmd_tpl_id; - - protected $ass_id; - protected $exc_id; - protected $rmd_type; - - protected $log; - - //todo remove the params as soon as possible. - function __construct($a_exc_id = "", $a_ass_id = "", $a_type = "") - { - global $DIC; - $this->db = $DIC->database(); - $this->tree = $DIC->repositoryTree(); - $this->access = $DIC->access(); - $this->log = ilLoggerFactory::getLogger("exc"); - - if($a_ass_id) { - $this->ass_id = $a_ass_id; - } - if($a_exc_id) { - $this->exc_id = $a_exc_id; - } - if($a_type) { - $this->rmd_type = $a_type; - } - if($a_exc_id and $a_ass_id and $a_type) { - $this->read(); - } - } - - public function getReminderType() - { - return $this->rmd_type; - } - - /** - * Set reminder for users without submission. - * @param $a_status - */ - function setReminderStatus($a_status) - { - $this->rmd_status = $a_status; - } - - /** - * Get the reminder status - * @return mixed - */ - function getReminderStatus() - { - return $this->rmd_status; - } - - /** - * Set num days before the deadline to start sending notifications. - * @param $a_num_days - */ - function setReminderStart($a_num_days) - { - $this->rmd_start = $a_num_days; - } - - /** - * Get num days before the deadline to start sending notifications. - * @return mixed - */ - function getReminderStart() - { - return $this->rmd_start; - } - - /** - * Set the ending of the reminder - * @param $a_date - */ - function setReminderEnd($a_date) - { - $this->rmd_end = $a_date; - } - - /** - * get the ending of the reminder - * @return mixed - */ - function getReminderEnd() - { - return $this->rmd_end; - } - - /** - * Set frequency in days - * @param $a_num_days - */ - function setReminderFrequency($a_num_days) - { - $this->rmd_frequency = $a_num_days; - } - - /** - * get submit reminder frequency in days. - * @return mixed - */ - function getReminderFrequency() - { - return $this->rmd_frequency; - } - - function setReminderLastSend($a_timestamp) - { - $this->rmd_last_send = $a_timestamp; - } - - function getReminderLastSend() - { - return $this->rmd_last_send; - } - - function setReminderMailTemplate($a_tpl_id) - { - $this->rmd_tpl_id = $a_tpl_id; - } - - function getReminderMailTemplate() - { - return $this->rmd_tpl_id; - } - - public function save() - { - $this->db->insert("exc_ass_reminders", array( - "type" => array("text", $this->rmd_type), - "ass_id" => array("integer", $this->ass_id), - "exc_id" => array("integer", $this->exc_id), - "status" => array("integer", $this->getReminderStatus()), - "start" => array("integer", $this->getReminderStart()), - "end" => array("integer", $this->getReminderEnd()), - "freq" => array("integer", $this->getReminderFrequency()), - "last_send" => array("integer", $this->getReminderLastSend()), - "template_id" => array("integer", $this->getReminderMailTemplate()) - )); - } - - public function update() - { - $this->db->update("exc_ass_reminders", array( - "status" => array("integer", $this->getReminderStatus()), - "start" => array("integer", $this->getReminderStart()), - "end" => array("integer", $this->getReminderEnd()), - "freq" => array("integer", $this->getReminderFrequency()), - "last_send" => array("integer", $this->getReminderLastSend()), - "template_id" => array("integer", $this->getReminderMailTemplate()) - ), - array( - "type" => array("text", $this->rmd_type), - "exc_id" => array("integer", $this->exc_id), - "ass_id" => array("integer", $this->ass_id) - )); - } - - - public function read() - { - $set = $this->db->query("SELECT status, start, freq, end, last_send, template_id". - " FROM exc_ass_reminders". - " WHERE type ='".$this->rmd_type."'". - " AND ass_id = ".$this->ass_id. - " AND exc_id = ".$this->exc_id); - - $rec = $this->db->fetchAssoc($set); - if(is_array($rec)) - { - $this->initFromDB($rec); - } - } - - /** - * Import DB record - * @param array $a_set - */ - protected function initFromDB(array $a_set) - { - $this->setReminderStatus($a_set["status"]); - $this->setReminderStart($a_set["start"]); - $this->setReminderEnd($a_set["end"]); - $this->setReminderFrequency($a_set["freq"]); - $this->setReminderLastSend($a_set["last_send"]); - $this->setReminderMailTemplate($a_set["template_id"]); - } - - - // Specific Methods to be used via Cron Job. - /** - * Get reminders available by date/frequence. - * @param $a_type string reminder type - * @return mixed - */ - function getReminders($a_type = "") - { - $now = time(); - //remove time from the timestamp (86400 = 24h) - $now = floor($now/86400)*86400; - $and_type = ""; - if($a_type == self::SUBMIT_REMINDER || $a_type == self::GRADE_REMINDER || $a_type == self::FEEDBACK_REMINDER) - { - $and_type = " AND type = '".$a_type."'"; - } - - $query = "SELECT ass_id, exc_id, status, start, freq, end, type, last_send, template_id". - " FROM exc_ass_reminders". - " WHERE status = 1". - " AND start <= ".$now. - " AND end > ".$now. - $and_type; - - - $result = $this->db->query($query); - - $array_data = array(); - while($rec = $this->db->fetchAssoc($result)) - { - $rem = array( - "ass_id" => $rec["ass_id"], - "exc_id" => $rec["exc_id"], - "start" => $rec["start"], - "end" => $rec["end"], - "freq" => $rec["freq"], - "type" => $rec["type"], - "last_send" => $rec["last_send"], - "template_id" => $rec["template_id"] - ); - - //frequency - $next_send = strtotime("-".$rec["freq"]." day", $now); - if(!$rec["last_send"] || $next_send >= floor($rec["last_send"]/86400)*86400) - { - array_push($array_data,$rem); - } - } - - return $array_data; - } - - - /** - * Filter the reminders by object(crs,grp) by active status and if have members. - * @param $a_reminders - * @return array - */ - function parseSubmissionReminders($a_reminders) - { - $reminders = $a_reminders; - $users_to_remind = array(); - - foreach($reminders as $rem) - { - $ass_id = $rem["ass_id"]; - $ass_obj = new ilExAssignment($ass_id); - - $exc_id = $rem["exc_id"]; - - $exc_refs = ilObject::_getAllReferences($exc_id); - foreach($exc_refs as $exc_ref) - { - - //$this->log->debug("Reference => ".$exc_ref); - if($course_ref_id = $this->tree->checkForParentType($exc_ref, 'crs')) { - $obj = new ilObjCourse($course_ref_id); - $participants_class = "ilCourseParticipants"; - $parent_ref_id = $course_ref_id; - $parent_obj_type = 'crs'; - } else if ($group_ref_id = $parent_ref_id = $this->tree->checkForParentType($exc_ref, 'grp')) { - $obj = new ilObjGroup($group_ref_id); - $participants_class = "ilGroupParticipants"; - $parent_ref_id = $group_ref_id; - $parent_obj_type = 'grp'; - } else { - continue; - } - - $parent_obj_id = $obj->getId(); - $participants_ids = $participants_class::getInstance($parent_ref_id)->getMembers(); - - foreach($participants_ids as $member_id) - { + const SUBMIT_REMINDER = "submit"; + const GRADE_REMINDER = "grade"; + const FEEDBACK_REMINDER = "peer"; + + protected $db; + protected $tree; + protected $now; + + protected $rmd_status; + protected $rmd_start; + protected $rmd_end; + protected $rmd_frequency; + protected $rmd_last_send; + protected $rmd_tpl_id; + + protected $ass_id; + protected $exc_id; + protected $rmd_type; + + protected $log; + + //todo remove the params as soon as possible. + public function __construct($a_exc_id = "", $a_ass_id = "", $a_type = "") + { + global $DIC; + $this->db = $DIC->database(); + $this->tree = $DIC->repositoryTree(); + $this->access = $DIC->access(); + $this->log = ilLoggerFactory::getLogger("exc"); + + if ($a_ass_id) { + $this->ass_id = $a_ass_id; + } + if ($a_exc_id) { + $this->exc_id = $a_exc_id; + } + if ($a_type) { + $this->rmd_type = $a_type; + } + if ($a_exc_id and $a_ass_id and $a_type) { + $this->read(); + } + } + + public function getReminderType() + { + return $this->rmd_type; + } + + /** + * Set reminder for users without submission. + * @param $a_status + */ + public function setReminderStatus($a_status) + { + $this->rmd_status = $a_status; + } + + /** + * Get the reminder status + * @return mixed + */ + public function getReminderStatus() + { + return $this->rmd_status; + } + + /** + * Set num days before the deadline to start sending notifications. + * @param $a_num_days + */ + public function setReminderStart($a_num_days) + { + $this->rmd_start = $a_num_days; + } + + /** + * Get num days before the deadline to start sending notifications. + * @return mixed + */ + public function getReminderStart() + { + return $this->rmd_start; + } + + /** + * Set the ending of the reminder + * @param $a_date + */ + public function setReminderEnd($a_date) + { + $this->rmd_end = $a_date; + } + + /** + * get the ending of the reminder + * @return mixed + */ + public function getReminderEnd() + { + return $this->rmd_end; + } + + /** + * Set frequency in days + * @param $a_num_days + */ + public function setReminderFrequency($a_num_days) + { + $this->rmd_frequency = $a_num_days; + } + + /** + * get submit reminder frequency in days. + * @return mixed + */ + public function getReminderFrequency() + { + return $this->rmd_frequency; + } + + public function setReminderLastSend($a_timestamp) + { + $this->rmd_last_send = $a_timestamp; + } + + public function getReminderLastSend() + { + return $this->rmd_last_send; + } + + public function setReminderMailTemplate($a_tpl_id) + { + $this->rmd_tpl_id = $a_tpl_id; + } + + public function getReminderMailTemplate() + { + return $this->rmd_tpl_id; + } + + public function save() + { + $this->db->insert("exc_ass_reminders", array( + "type" => array("text", $this->rmd_type), + "ass_id" => array("integer", $this->ass_id), + "exc_id" => array("integer", $this->exc_id), + "status" => array("integer", $this->getReminderStatus()), + "start" => array("integer", $this->getReminderStart()), + "end" => array("integer", $this->getReminderEnd()), + "freq" => array("integer", $this->getReminderFrequency()), + "last_send" => array("integer", $this->getReminderLastSend()), + "template_id" => array("integer", $this->getReminderMailTemplate()) + )); + } + + public function update() + { + $this->db->update( + "exc_ass_reminders", + array( + "status" => array("integer", $this->getReminderStatus()), + "start" => array("integer", $this->getReminderStart()), + "end" => array("integer", $this->getReminderEnd()), + "freq" => array("integer", $this->getReminderFrequency()), + "last_send" => array("integer", $this->getReminderLastSend()), + "template_id" => array("integer", $this->getReminderMailTemplate()) + ), + array( + "type" => array("text", $this->rmd_type), + "exc_id" => array("integer", $this->exc_id), + "ass_id" => array("integer", $this->ass_id) + ) + ); + } + + + public function read() + { + $set = $this->db->query("SELECT status, start, freq, end, last_send, template_id" . + " FROM exc_ass_reminders" . + " WHERE type ='" . $this->rmd_type . "'" . + " AND ass_id = " . $this->ass_id . + " AND exc_id = " . $this->exc_id); + + $rec = $this->db->fetchAssoc($set); + if (is_array($rec)) { + $this->initFromDB($rec); + } + } + + /** + * Import DB record + * @param array $a_set + */ + protected function initFromDB(array $a_set) + { + $this->setReminderStatus($a_set["status"]); + $this->setReminderStart($a_set["start"]); + $this->setReminderEnd($a_set["end"]); + $this->setReminderFrequency($a_set["freq"]); + $this->setReminderLastSend($a_set["last_send"]); + $this->setReminderMailTemplate($a_set["template_id"]); + } + + + // Specific Methods to be used via Cron Job. + /** + * Get reminders available by date/frequence. + * @param $a_type string reminder type + * @return mixed + */ + public function getReminders($a_type = "") + { + $now = time(); + //remove time from the timestamp (86400 = 24h) + $now = floor($now/86400)*86400; + $and_type = ""; + if ($a_type == self::SUBMIT_REMINDER || $a_type == self::GRADE_REMINDER || $a_type == self::FEEDBACK_REMINDER) { + $and_type = " AND type = '" . $a_type . "'"; + } + + $query = "SELECT ass_id, exc_id, status, start, freq, end, type, last_send, template_id" . + " FROM exc_ass_reminders" . + " WHERE status = 1" . + " AND start <= " . $now . + " AND end > " . $now . + $and_type; + + + $result = $this->db->query($query); + + $array_data = array(); + while ($rec = $this->db->fetchAssoc($result)) { + $rem = array( + "ass_id" => $rec["ass_id"], + "exc_id" => $rec["exc_id"], + "start" => $rec["start"], + "end" => $rec["end"], + "freq" => $rec["freq"], + "type" => $rec["type"], + "last_send" => $rec["last_send"], + "template_id" => $rec["template_id"] + ); + + //frequency + $next_send = strtotime("-" . $rec["freq"] . " day", $now); + if (!$rec["last_send"] || $next_send >= floor($rec["last_send"]/86400)*86400) { + array_push($array_data, $rem); + } + } + + return $array_data; + } + + + /** + * Filter the reminders by object(crs,grp) by active status and if have members. + * @param $a_reminders + * @return array + */ + public function parseSubmissionReminders($a_reminders) + { + $reminders = $a_reminders; + $users_to_remind = array(); + + foreach ($reminders as $rem) { + $ass_id = $rem["ass_id"]; + $ass_obj = new ilExAssignment($ass_id); + + $exc_id = $rem["exc_id"]; + + $exc_refs = ilObject::_getAllReferences($exc_id); + foreach ($exc_refs as $exc_ref) { + + //$this->log->debug("Reference => ".$exc_ref); + if ($course_ref_id = $this->tree->checkForParentType($exc_ref, 'crs')) { + $obj = new ilObjCourse($course_ref_id); + $participants_class = "ilCourseParticipants"; + $parent_ref_id = $course_ref_id; + $parent_obj_type = 'crs'; + } elseif ($group_ref_id = $parent_ref_id = $this->tree->checkForParentType($exc_ref, 'grp')) { + $obj = new ilObjGroup($group_ref_id); + $participants_class = "ilGroupParticipants"; + $parent_ref_id = $group_ref_id; + $parent_obj_type = 'grp'; + } else { + continue; + } + + $parent_obj_id = $obj->getId(); + $participants_ids = $participants_class::getInstance($parent_ref_id)->getMembers(); + + foreach ($participants_ids as $member_id) { $this->log->debug("submission reminder: ass: $ass_id, member: $member_id."); - if($this->access->checkAccessOfUser($member_id, "read", "", $exc_ref)) - { - $state = ilExcAssMemberState::getInstanceByIds($ass_id, $member_id); - $days_diff = (($state->getOfficialDeadline() - time()) / (60*60*24)); - $this->log->debug("diff: ".$days_diff.", start: ".$rem["start"].", submission allowed: ".$state->isSubmissionAllowed()); - if ($state->isSubmissionAllowed() && $days_diff < $rem["start"]) { + if ($this->access->checkAccessOfUser($member_id, "read", "", $exc_ref)) { + $state = ilExcAssMemberState::getInstanceByIds($ass_id, $member_id); + $days_diff = (($state->getOfficialDeadline() - time()) / (60*60*24)); + $this->log->debug("diff: " . $days_diff . ", start: " . $rem["start"] . ", submission allowed: " . $state->isSubmissionAllowed()); + if ($state->isSubmissionAllowed() && $days_diff < $rem["start"]) { $submission = new ilExSubmission($ass_obj, $member_id); if (!$submission->getLastSubmission()) { @@ -334,88 +329,82 @@ class ilExAssignmentReminder array_push($users_to_remind, $member_data); } } - } - } - } - } - return $users_to_remind; - } - - function parseGradeReminders($a_reminders) - { - $reminders = $a_reminders; - $users_to_remind = array(); - - $has_pending_to_grade = false; - - foreach($reminders as $rem) - { - //$this->log->debug("---- parse grade reminder with values -> ",$rem); - $ass_obj = new ilExAssignment($rem["ass_id"]); - $members_data = $ass_obj->getMemberListData(); - - //$this->log->debug("--- get members list data => ",$members_data); - foreach($members_data as $member_id => $assignment_data) - { - if ($assignment_data["status"] == ilExerciseManagementGUI::GRADE_NOT_GRADED) - { - //at least there is one submission pending to grade. - $has_pending_to_grade = true; - continue; - } - } - - /* //DEBUG - if($has_pending_to_grade){ - $this->log->debug("SOMEONE HAS TO BE GRADED"); - } else { - $this->log->debug("There is nothing to Grade"); - } - */ - - if($has_pending_to_grade) - { - //get tutor of this exercise. - include_once "./Services/Notification/classes/class.ilNotification.php"; - - $users = ilNotification::getNotificationsForObject(ilNotification::TYPE_EXERCISE_SUBMISSION, $rem["exc_id"]); - - foreach ($users as $user_id) { - $exc_refs = ilObject::_getAllReferences($rem["exc_id"]); - $unike_usr_id = array(); - foreach ($exc_refs as $exc_ref) { - if ($this->access->checkAccessOfUser($user_id, "write", "", $exc_ref)) { - if (!in_array($user_id, $unike_usr_id)) { - $member_data = array( - "exc_id" => $rem["exc_id"], - "exc_ref" => $exc_ref, - "ass_id" => $rem["ass_id"], - "member_id" => $user_id, - "reminder_type" => $rem["type"], - "template_id" => $rem["template_id"] - ); - array_push($users_to_remind, $member_data); - array_push($unike_usr_id, $user_id); - } - } - } - } - } - } - - return $users_to_remind; - } - - function parsePeerReminders($a_reminders) - { - $reminders = $a_reminders; - $users_to_remind = array(); - - foreach($reminders as $reminder) - { - $giver_ids = array_unique(ilExPeerReview::lookupGiversWithPendingFeedback($reminder["ass_id"])); - foreach($giver_ids as $giver_id) - { + } + } + } + } + return $users_to_remind; + } + + public function parseGradeReminders($a_reminders) + { + $reminders = $a_reminders; + $users_to_remind = array(); + + $has_pending_to_grade = false; + + foreach ($reminders as $rem) { + //$this->log->debug("---- parse grade reminder with values -> ",$rem); + $ass_obj = new ilExAssignment($rem["ass_id"]); + $members_data = $ass_obj->getMemberListData(); + + //$this->log->debug("--- get members list data => ",$members_data); + foreach ($members_data as $member_id => $assignment_data) { + if ($assignment_data["status"] == ilExerciseManagementGUI::GRADE_NOT_GRADED) { + //at least there is one submission pending to grade. + $has_pending_to_grade = true; + continue; + } + } + + /* //DEBUG + if($has_pending_to_grade){ + $this->log->debug("SOMEONE HAS TO BE GRADED"); + } else { + $this->log->debug("There is nothing to Grade"); + } + */ + + if ($has_pending_to_grade) { + //get tutor of this exercise. + include_once "./Services/Notification/classes/class.ilNotification.php"; + + $users = ilNotification::getNotificationsForObject(ilNotification::TYPE_EXERCISE_SUBMISSION, $rem["exc_id"]); + + foreach ($users as $user_id) { + $exc_refs = ilObject::_getAllReferences($rem["exc_id"]); + $unike_usr_id = array(); + foreach ($exc_refs as $exc_ref) { + if ($this->access->checkAccessOfUser($user_id, "write", "", $exc_ref)) { + if (!in_array($user_id, $unike_usr_id)) { + $member_data = array( + "exc_id" => $rem["exc_id"], + "exc_ref" => $exc_ref, + "ass_id" => $rem["ass_id"], + "member_id" => $user_id, + "reminder_type" => $rem["type"], + "template_id" => $rem["template_id"] + ); + array_push($users_to_remind, $member_data); + array_push($unike_usr_id, $user_id); + } + } + } + } + } + } + + return $users_to_remind; + } + + public function parsePeerReminders($a_reminders) + { + $reminders = $a_reminders; + $users_to_remind = array(); + + foreach ($reminders as $reminder) { + $giver_ids = array_unique(ilExPeerReview::lookupGiversWithPendingFeedback($reminder["ass_id"])); + foreach ($giver_ids as $giver_id) { $state = ilExcAssMemberState::getInstanceByIds($reminder["ass_id"], $giver_id); $days_diff = (($state->getPeerReviewDeadline() - time()) / (60*60*24)); @@ -435,193 +424,193 @@ class ilExAssignmentReminder } } } - } - } - - return $users_to_remind; - } - - /** - * CRON send reminders - */ - public function checkReminders() - { - $submit_reminders = $this->getReminders(self::SUBMIT_REMINDER); - $parsed_submit_reminders = $this->parseSubmissionReminders($submit_reminders); - - $grade_reminders = $this->getReminders(self::GRADE_REMINDER); - $parsed_grade_reminders = $this->parseGradeReminders($grade_reminders); - - $peer_reminders = $this->getReminders(self::FEEDBACK_REMINDER); - $parsed_peer_reminders = $this->parsePeerReminders($peer_reminders); - - /* //DEBUG - $this->log->debug("ALL SUBMIT REMINDERS"); - $this->log->dump($submit_reminders); - $this->log->debug("PARSED SUBMIT REMINDERS"); - $this->log->dump($parsed_submit_reminders); - $this->log->debug("GRADE REMINDERS ARRAY"); - $this->log->dump($grade_reminders); - $this->log->debug("PARSED GRADE REMINDERS"); - $this->log->dump($parsed_grade_reminders); - $this->log->debug("PEER REMINDERS ARRAY"); - $this->log->dump($peer_reminders); - $this->log->debug("PARSED PEER REMINDERS"); - $this->log->dump($parsed_peer_reminders); - */ - - $reminders = array_merge($parsed_submit_reminders, $parsed_grade_reminders, $parsed_peer_reminders); - - $reminders_sent = $this->sendReminders($reminders); - - return $reminders_sent; - } - - /** - * @param $reminders array reminders data - * @return integer - */ - protected function sendReminders($reminders) - { - global $DIC; - - $tpl = null; - - foreach ($reminders as $reminder) - { - $template_id = $reminder['template_id']; - - $rmd_type = $reminder["reminder_type"]; - $this->log->debug("Sending reminder type = ".$rmd_type); - - //if the template exists (can be deleted via Administration/Mail) - if($template_id) - { - /** @var \ilMailTemplateService $templateService */ - $templateService = $DIC['mail.texttemplates.service']; - $tpl = $templateService->loadTemplateForId((int)$template_id); - } - - if($tpl) - { - $this->log->debug("** send reminder WITH template."); - $subject = $tpl->getSubject(); - - $placeholder_params = array( - "exc_id" => $reminder["exc_id"], - "exc_ref" => $reminder["exc_ref"], - "ass_id" => $reminder["ass_id"], - "member_id" => $reminder["member_id"] - ); - $message = $this->sentReminderPlaceholders($tpl->getMessage(), $placeholder_params, $rmd_type); - } - else - { - $this->log->debug("** send reminder WITHOUT template."); - - $ass_title = ilExAssignment::lookupTitle($reminder["ass_id"]); - $exc_title = ilObjExercise::_lookupTitle($reminder["exc_id"]); - - // use language of recipient to compose message - include_once "./Services/Language/classes/class.ilLanguageFactory.php"; - $ulng = ilLanguageFactory::_getLanguageOfUser($reminder["member_id"]); - $ulng->loadLanguageModule('exc'); - - $link = ilLink::_getLink($reminder["exc_ref"], "exc", array(), "_".$reminder["ass_id"]); - - $message = sprintf($ulng->txt('exc_reminder_salutation'), ilObjUser::_lookupFullname($reminder["member_id"]))."\n\n"; - - $this->log->debug("send: MAIL TYPE = ".$rmd_type.", user: ".$reminder["member_id"].", ass: ".$reminder["ass_id"]); - - switch($rmd_type) - { - case "submit": - $subject = sprintf($ulng->txt('exc_reminder_submit_subject'), $ass_title); - $message .= $ulng->txt('exc_reminder_submit_body').":\n\n"; - break; - - case "grade": - $subject = sprintf($ulng->txt('exc_reminder_grade_subject'), $ass_title); - $message .= $ulng->txt('exc_reminder_grade_body').":\n\n"; - break; - - case "peer": - $subject = sprintf($ulng->txt('exc_reminder_peer_subject'), $ass_title); - $message .= $ulng->txt('exc_reminder_peer_body').":\n\n"; - break; - } - - $message .= $ulng->txt('obj_exc').": ".$exc_title."\n"; - $message .= $ulng->txt('obj_ass').": ".$ass_title."\n"; - $message .= "\n".$ulng->txt('exc_reminder_link').": ".$link; - } - $mail_obj = new ilMail(ANONYMOUS_USER_ID); - $mail_obj->appendInstallationSignature(true); - $mail_obj->sendMail(ilObjUser::_lookupLogin($reminder["member_id"]), - "", "", $subject, $message, array(), array("system")); - } - - $this->updateRemindersLastDate($reminders); - return sizeof($reminders); - } - - //see ilObjSurvey. - protected function sentReminderPlaceholders($a_message, $a_reminder_data, $a_reminder_type) - { - // see ilMail::replacePlaceholders() - try { - switch ($a_reminder_type) { - case \ilExAssignmentReminder::SUBMIT_REMINDER: - $context = \ilMailTemplateContextService::getTemplateContextById(ilExcMailTemplateSubmitReminderContext::ID); - break; - case \ilExAssignmentReminder::GRADE_REMINDER: - $context = \ilMailTemplateContextService::getTemplateContextById(ilExcMailTemplateGradeReminderContext::ID); - break; - case \ilExAssignmentReminder::FEEDBACK_REMINDER: - $context = \ilMailTemplateContextService::getTemplateContextById(ilExcMailTemplatePeerReminderContext::ID); - break; - default: - exit(); - } - - $user = new \ilObjUser($a_reminder_data["member_id"]); - - $processor = new \ilMailTemplatePlaceholderResolver($context, $a_message); - $a_message = $processor->resolve($user, $a_reminder_data); - } catch (\Exception $e) { - \ilLoggerFactory::getLogger('mail')->error(__METHOD__ . ' has been called with invalid context.'); - } - - return $a_message; - } - - /** - * Update reminders last_send value with the current timestamp. - * @param $a_reminders - */ - protected function updateRemindersLastDate($a_reminders) - { - foreach($a_reminders as $reminder) - { - $sql = "UPDATE exc_ass_reminders". - " SET last_send = ".$this->db->quote(time(),'integer'). - " WHERE type = ".$this->db->quote($reminder["reminder_type"],'text'). - " AND ass_id = ".$this->db->quote($reminder["ass_id"],'integer'). - " AND exc_id = ".$this->db->quote($reminder["exc_id"],'integer'); - - $this->db->manipulate($sql); - } - } - - /** - * remove reminders from DB when the parent assignment is deleted. - * @param $a_ass_id - */ - function deleteReminders($a_ass_id) - { - $sql = "DELETE FROM exc_ass_reminders". - " WHERE ass_id = ".$a_ass_id; - - $this->db->manipulate($sql); - } -} \ No newline at end of file + } + } + + return $users_to_remind; + } + + /** + * CRON send reminders + */ + public function checkReminders() + { + $submit_reminders = $this->getReminders(self::SUBMIT_REMINDER); + $parsed_submit_reminders = $this->parseSubmissionReminders($submit_reminders); + + $grade_reminders = $this->getReminders(self::GRADE_REMINDER); + $parsed_grade_reminders = $this->parseGradeReminders($grade_reminders); + + $peer_reminders = $this->getReminders(self::FEEDBACK_REMINDER); + $parsed_peer_reminders = $this->parsePeerReminders($peer_reminders); + + /* //DEBUG + $this->log->debug("ALL SUBMIT REMINDERS"); + $this->log->dump($submit_reminders); + $this->log->debug("PARSED SUBMIT REMINDERS"); + $this->log->dump($parsed_submit_reminders); + $this->log->debug("GRADE REMINDERS ARRAY"); + $this->log->dump($grade_reminders); + $this->log->debug("PARSED GRADE REMINDERS"); + $this->log->dump($parsed_grade_reminders); + $this->log->debug("PEER REMINDERS ARRAY"); + $this->log->dump($peer_reminders); + $this->log->debug("PARSED PEER REMINDERS"); + $this->log->dump($parsed_peer_reminders); + */ + + $reminders = array_merge($parsed_submit_reminders, $parsed_grade_reminders, $parsed_peer_reminders); + + $reminders_sent = $this->sendReminders($reminders); + + return $reminders_sent; + } + + /** + * @param $reminders array reminders data + * @return integer + */ + protected function sendReminders($reminders) + { + global $DIC; + + $tpl = null; + + foreach ($reminders as $reminder) { + $template_id = $reminder['template_id']; + + $rmd_type = $reminder["reminder_type"]; + $this->log->debug("Sending reminder type = " . $rmd_type); + + //if the template exists (can be deleted via Administration/Mail) + if ($template_id) { + /** @var \ilMailTemplateService $templateService */ + $templateService = $DIC['mail.texttemplates.service']; + $tpl = $templateService->loadTemplateForId((int) $template_id); + } + + if ($tpl) { + $this->log->debug("** send reminder WITH template."); + $subject = $tpl->getSubject(); + + $placeholder_params = array( + "exc_id" => $reminder["exc_id"], + "exc_ref" => $reminder["exc_ref"], + "ass_id" => $reminder["ass_id"], + "member_id" => $reminder["member_id"] + ); + $message = $this->sentReminderPlaceholders($tpl->getMessage(), $placeholder_params, $rmd_type); + } else { + $this->log->debug("** send reminder WITHOUT template."); + + $ass_title = ilExAssignment::lookupTitle($reminder["ass_id"]); + $exc_title = ilObjExercise::_lookupTitle($reminder["exc_id"]); + + // use language of recipient to compose message + include_once "./Services/Language/classes/class.ilLanguageFactory.php"; + $ulng = ilLanguageFactory::_getLanguageOfUser($reminder["member_id"]); + $ulng->loadLanguageModule('exc'); + + $link = ilLink::_getLink($reminder["exc_ref"], "exc", array(), "_" . $reminder["ass_id"]); + + $message = sprintf($ulng->txt('exc_reminder_salutation'), ilObjUser::_lookupFullname($reminder["member_id"])) . "\n\n"; + + $this->log->debug("send: MAIL TYPE = " . $rmd_type . ", user: " . $reminder["member_id"] . ", ass: " . $reminder["ass_id"]); + + switch ($rmd_type) { + case "submit": + $subject = sprintf($ulng->txt('exc_reminder_submit_subject'), $ass_title); + $message .= $ulng->txt('exc_reminder_submit_body') . ":\n\n"; + break; + + case "grade": + $subject = sprintf($ulng->txt('exc_reminder_grade_subject'), $ass_title); + $message .= $ulng->txt('exc_reminder_grade_body') . ":\n\n"; + break; + + case "peer": + $subject = sprintf($ulng->txt('exc_reminder_peer_subject'), $ass_title); + $message .= $ulng->txt('exc_reminder_peer_body') . ":\n\n"; + break; + } + + $message .= $ulng->txt('obj_exc') . ": " . $exc_title . "\n"; + $message .= $ulng->txt('obj_ass') . ": " . $ass_title . "\n"; + $message .= "\n" . $ulng->txt('exc_reminder_link') . ": " . $link; + } + $mail_obj = new ilMail(ANONYMOUS_USER_ID); + $mail_obj->appendInstallationSignature(true); + $mail_obj->sendMail( + ilObjUser::_lookupLogin($reminder["member_id"]), + "", + "", + $subject, + $message, + array(), + array("system") + ); + } + + $this->updateRemindersLastDate($reminders); + return sizeof($reminders); + } + + //see ilObjSurvey. + protected function sentReminderPlaceholders($a_message, $a_reminder_data, $a_reminder_type) + { + // see ilMail::replacePlaceholders() + try { + switch ($a_reminder_type) { + case \ilExAssignmentReminder::SUBMIT_REMINDER: + $context = \ilMailTemplateContextService::getTemplateContextById(ilExcMailTemplateSubmitReminderContext::ID); + break; + case \ilExAssignmentReminder::GRADE_REMINDER: + $context = \ilMailTemplateContextService::getTemplateContextById(ilExcMailTemplateGradeReminderContext::ID); + break; + case \ilExAssignmentReminder::FEEDBACK_REMINDER: + $context = \ilMailTemplateContextService::getTemplateContextById(ilExcMailTemplatePeerReminderContext::ID); + break; + default: + exit(); + } + + $user = new \ilObjUser($a_reminder_data["member_id"]); + + $processor = new \ilMailTemplatePlaceholderResolver($context, $a_message); + $a_message = $processor->resolve($user, $a_reminder_data); + } catch (\Exception $e) { + \ilLoggerFactory::getLogger('mail')->error(__METHOD__ . ' has been called with invalid context.'); + } + + return $a_message; + } + + /** + * Update reminders last_send value with the current timestamp. + * @param $a_reminders + */ + protected function updateRemindersLastDate($a_reminders) + { + foreach ($a_reminders as $reminder) { + $sql = "UPDATE exc_ass_reminders" . + " SET last_send = " . $this->db->quote(time(), 'integer') . + " WHERE type = " . $this->db->quote($reminder["reminder_type"], 'text') . + " AND ass_id = " . $this->db->quote($reminder["ass_id"], 'integer') . + " AND exc_id = " . $this->db->quote($reminder["exc_id"], 'integer'); + + $this->db->manipulate($sql); + } + } + + /** + * remove reminders from DB when the parent assignment is deleted. + * @param $a_ass_id + */ + public function deleteReminders($a_ass_id) + { + $sql = "DELETE FROM exc_ass_reminders" . + " WHERE ass_id = " . $a_ass_id; + + $this->db->manipulate($sql); + } +} diff --git a/Modules/Exercise/classes/class.ilExAssignmentTeam.php b/Modules/Exercise/classes/class.ilExAssignmentTeam.php index e67a3a5f059af230cd605b15d71f278eb96e8922..c44f7ca19696e176254dbdc3b14bd5a523c04833 100644 --- a/Modules/Exercise/classes/class.ilExAssignmentTeam.php +++ b/Modules/Exercise/classes/class.ilExAssignmentTeam.php @@ -8,654 +8,611 @@ * @ingroup ModulesExercise */ class ilExAssignmentTeam -{ - /** - * @var ilDB - */ - protected $db; +{ + /** + * @var ilDB + */ + protected $db; - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - protected $id; // [int] - protected $assignment_id; // [int] - protected $members = array(); // [array] - - const TEAM_LOG_CREATE_TEAM = 1; - const TEAM_LOG_ADD_MEMBER = 2; - const TEAM_LOG_REMOVE_MEMBER = 3; - const TEAM_LOG_ADD_FILE = 4; - const TEAM_LOG_REMOVE_FILE = 5; - - public function __construct($a_id = null) - { - global $DIC; + protected $id; // [int] + protected $assignment_id; // [int] + protected $members = array(); // [array] + + const TEAM_LOG_CREATE_TEAM = 1; + const TEAM_LOG_ADD_MEMBER = 2; + const TEAM_LOG_REMOVE_MEMBER = 3; + const TEAM_LOG_ADD_FILE = 4; + const TEAM_LOG_REMOVE_FILE = 5; + + public function __construct($a_id = null) + { + global $DIC; - $this->db = $DIC->database(); - $this->user = $DIC->user(); - if($a_id) - { - $this->read($a_id); - } - } - - public static function getInstanceByUserId($a_assignment_id, $a_user_id, $a_create_on_demand = false) - { - $id = self::getTeamId($a_assignment_id, $a_user_id, $a_create_on_demand); - return new self($id); - } - - public static function getInstancesFromMap($a_assignment_id) - { - $teams = array(); - foreach(self::getAssignmentTeamMap($a_assignment_id) as $user_id => $team_id) - { - $teams[$team_id][] = $user_id; - } - - $res = array(); - foreach($teams as $team_id => $members) - { - $team = new self(); - $team->id = $team_id; - $team->assignment_id = $a_assignment_id; - $team->members = $members; - $res[$team_id] = $team; - } - - return $res; - } - - public function getId() - { - return $this->id; - } + $this->db = $DIC->database(); + $this->user = $DIC->user(); + if ($a_id) { + $this->read($a_id); + } + } + + public static function getInstanceByUserId($a_assignment_id, $a_user_id, $a_create_on_demand = false) + { + $id = self::getTeamId($a_assignment_id, $a_user_id, $a_create_on_demand); + return new self($id); + } + + public static function getInstancesFromMap($a_assignment_id) + { + $teams = array(); + foreach (self::getAssignmentTeamMap($a_assignment_id) as $user_id => $team_id) { + $teams[$team_id][] = $user_id; + } + + $res = array(); + foreach ($teams as $team_id => $members) { + $team = new self(); + $team->id = $team_id; + $team->assignment_id = $a_assignment_id; + $team->members = $members; + $res[$team_id] = $team; + } + + return $res; + } + + public function getId() + { + return $this->id; + } - private function setId($a_id) - { - $this->id = $a_id; - } - - protected function read($a_id) - { - $ilDB = $this->db; - - // #18094 - $this->members = array(); - - $sql = "SELECT * FROM il_exc_team". - " WHERE id = ".$ilDB->quote($a_id, "integer"); - $set = $ilDB->query($sql); - if($ilDB->numRows($set)) - { - $this->setId($a_id); - - while($row = $ilDB->fetchAssoc($set)) - { - $this->assignment_id = $row["ass_id"]; - $this->members[] = $row["user_id"]; - } - } - } - - /** - * Get team id for member id - * - * team will be created if no team yet - * - * @param int $a_user_id - * @param bool $a_create_on_demand - * @return int - */ - public static function getTeamId($a_assignment_id, $a_user_id, $a_create_on_demand = false) - { - global $DIC; + private function setId($a_id) + { + $this->id = $a_id; + } + + protected function read($a_id) + { + $ilDB = $this->db; + + // #18094 + $this->members = array(); + + $sql = "SELECT * FROM il_exc_team" . + " WHERE id = " . $ilDB->quote($a_id, "integer"); + $set = $ilDB->query($sql); + if ($ilDB->numRows($set)) { + $this->setId($a_id); + + while ($row = $ilDB->fetchAssoc($set)) { + $this->assignment_id = $row["ass_id"]; + $this->members[] = $row["user_id"]; + } + } + } + + /** + * Get team id for member id + * + * team will be created if no team yet + * + * @param int $a_user_id + * @param bool $a_create_on_demand + * @return int + */ + public static function getTeamId($a_assignment_id, $a_user_id, $a_create_on_demand = false) + { + global $DIC; - $ilDB = $DIC->database(); - - $sql = "SELECT id FROM il_exc_team". - " WHERE ass_id = ".$ilDB->quote($a_assignment_id, "integer"). - " AND user_id = ".$ilDB->quote($a_user_id, "integer"); - $set = $ilDB->query($sql); - $row = $ilDB->fetchAssoc($set); - $id = $row["id"]; - - if(!$id && $a_create_on_demand) - { - $id = $ilDB->nextId("il_exc_team"); + $ilDB = $DIC->database(); + + $sql = "SELECT id FROM il_exc_team" . + " WHERE ass_id = " . $ilDB->quote($a_assignment_id, "integer") . + " AND user_id = " . $ilDB->quote($a_user_id, "integer"); + $set = $ilDB->query($sql); + $row = $ilDB->fetchAssoc($set); + $id = $row["id"]; + + if (!$id && $a_create_on_demand) { + $id = $ilDB->nextId("il_exc_team"); - // get starting timestamp (relative deadlines) from individual deadline - include_once("./Modules/Exercise/classes/class.ilExcIndividualDeadline.php"); - $idl = ilExcIndividualDeadline::getInstance($a_assignment_id, $a_user_id); - - $fields = array("id" => array("integer", $id), - "ass_id" => array("integer", $a_assignment_id), - "user_id" => array("integer", $a_user_id)); - $ilDB->insert("il_exc_team", $fields); + // get starting timestamp (relative deadlines) from individual deadline + include_once("./Modules/Exercise/classes/class.ilExcIndividualDeadline.php"); + $idl = ilExcIndividualDeadline::getInstance($a_assignment_id, $a_user_id); + + $fields = array("id" => array("integer", $id), + "ass_id" => array("integer", $a_assignment_id), + "user_id" => array("integer", $a_user_id)); + $ilDB->insert("il_exc_team", $fields); - // set starting timestamp for created team - if ($idl->getStartingTimestamp() > 0) - { - $idl_team = ilExcIndividualDeadline::getInstance($a_assignment_id, $id, true); - $idl_team->setStartingTimestamp($idl->getStartingTimestamp()); - $idl_team->save(); - } - - self::writeTeamLog($id, self::TEAM_LOG_CREATE_TEAM); - self::writeTeamLog($id, self::TEAM_LOG_ADD_MEMBER, - ilObjUser::_lookupFullname($a_user_id)); - } - - return $id; - } + // set starting timestamp for created team + if ($idl->getStartingTimestamp() > 0) { + $idl_team = ilExcIndividualDeadline::getInstance($a_assignment_id, $id, true); + $idl_team->setStartingTimestamp($idl->getStartingTimestamp()); + $idl_team->save(); + } + + self::writeTeamLog($id, self::TEAM_LOG_CREATE_TEAM); + self::writeTeamLog( + $id, + self::TEAM_LOG_ADD_MEMBER, + ilObjUser::_lookupFullname($a_user_id) + ); + } + + return $id; + } - function createTeam($a_assignment_id, $a_user_id) - { - $ilDB = $this->db; - $id = $ilDB->nextId("il_exc_team"); - $fields = array("id" => array("integer", $id), - "ass_id" => array("integer", $a_assignment_id), - "user_id" => array("integer", $a_user_id)); - $ilDB->insert("il_exc_team", $fields); - self::writeTeamLog($id, self::TEAM_LOG_CREATE_TEAM); - self::writeTeamLog($id, self::TEAM_LOG_ADD_MEMBER, - ilObjUser::_lookupFullname($a_user_id)); - return $id; - } - - /** - * Get members of assignment team - * - * @return array - */ - public function getMembers() - { - return $this->members; - } - - /** - * Get members for all teams of assignment - * - * @return array - */ - function getMembersOfAllTeams() - { - $ilDB = $this->db; - - $ids = array(); - - $sql = "SELECT user_id". - " FROM il_exc_team". - " WHERE ass_id = ".$ilDB->quote($this->assignment_id, "integer"); - $set = $ilDB->query($sql); - while($row = $ilDB->fetchAssoc($set)) - { - $ids[] = $row["user_id"]; - } - - return $ids; - } - - /** - * Add new member to team - * - * @param int $a_user_id - * @param int $a_exc_ref_id - */ - function addTeamMember($a_user_id, $a_exc_ref_id = null) - { - $ilDB = $this->db; - - if(!$this->id) - { - return false; - } - - // must not be in any team already - if(!in_array($a_user_id, $this->getMembersOfAllTeams())) - { - $fields = array("id" => array("integer", $this->id), - "ass_id" => array("integer", $this->assignment_id), - "user_id" => array("integer", $a_user_id)); - $ilDB->insert("il_exc_team", $fields); - - if($a_exc_ref_id) - { - $this->sendNotification($a_exc_ref_id, $a_user_id, "add"); - } - - $this->writeLog(self::TEAM_LOG_ADD_MEMBER, - ilObjUser::_lookupFullname($a_user_id)); - - $this->read($this->id); - - return true; - } - - return false; - } - - /** - * Remove member from team - * - * @param int $a_user_id - * @param int $a_exc_ref_id - */ - function removeTeamMember($a_user_id, $a_exc_ref_id = null) - { - $ilDB = $this->db; - - if(!$this->id) - { - return; - } - - $sql = "DELETE FROM il_exc_team". - " WHERE ass_id = ".$ilDB->quote($this->assignment_id, "integer"). - " AND id = ".$ilDB->quote($this->id, "integer"). - " AND user_id = ".$ilDB->quote($a_user_id, "integer"); - $ilDB->manipulate($sql); - - if($a_exc_ref_id) - { - $this->sendNotification($a_exc_ref_id, $a_user_id, "rmv"); - } - - $this->writeLog(self::TEAM_LOG_REMOVE_MEMBER, - ilObjUser::_lookupFullname($a_user_id)); - - $this->read($this->id); - } - - /** - * Get team structure for assignment - * - * @param int $a_ass_id - * @return array - */ - public static function getAssignmentTeamMap($a_ass_id) - { - global $DIC; + public function createTeam($a_assignment_id, $a_user_id) + { + $ilDB = $this->db; + $id = $ilDB->nextId("il_exc_team"); + $fields = array("id" => array("integer", $id), + "ass_id" => array("integer", $a_assignment_id), + "user_id" => array("integer", $a_user_id)); + $ilDB->insert("il_exc_team", $fields); + self::writeTeamLog($id, self::TEAM_LOG_CREATE_TEAM); + self::writeTeamLog( + $id, + self::TEAM_LOG_ADD_MEMBER, + ilObjUser::_lookupFullname($a_user_id) + ); + return $id; + } + + /** + * Get members of assignment team + * + * @return array + */ + public function getMembers() + { + return $this->members; + } + + /** + * Get members for all teams of assignment + * + * @return array + */ + public function getMembersOfAllTeams() + { + $ilDB = $this->db; + + $ids = array(); + + $sql = "SELECT user_id" . + " FROM il_exc_team" . + " WHERE ass_id = " . $ilDB->quote($this->assignment_id, "integer"); + $set = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($set)) { + $ids[] = $row["user_id"]; + } + + return $ids; + } + + /** + * Add new member to team + * + * @param int $a_user_id + * @param int $a_exc_ref_id + */ + public function addTeamMember($a_user_id, $a_exc_ref_id = null) + { + $ilDB = $this->db; + + if (!$this->id) { + return false; + } + + // must not be in any team already + if (!in_array($a_user_id, $this->getMembersOfAllTeams())) { + $fields = array("id" => array("integer", $this->id), + "ass_id" => array("integer", $this->assignment_id), + "user_id" => array("integer", $a_user_id)); + $ilDB->insert("il_exc_team", $fields); + + if ($a_exc_ref_id) { + $this->sendNotification($a_exc_ref_id, $a_user_id, "add"); + } + + $this->writeLog( + self::TEAM_LOG_ADD_MEMBER, + ilObjUser::_lookupFullname($a_user_id) + ); + + $this->read($this->id); + + return true; + } + + return false; + } + + /** + * Remove member from team + * + * @param int $a_user_id + * @param int $a_exc_ref_id + */ + public function removeTeamMember($a_user_id, $a_exc_ref_id = null) + { + $ilDB = $this->db; + + if (!$this->id) { + return; + } + + $sql = "DELETE FROM il_exc_team" . + " WHERE ass_id = " . $ilDB->quote($this->assignment_id, "integer") . + " AND id = " . $ilDB->quote($this->id, "integer") . + " AND user_id = " . $ilDB->quote($a_user_id, "integer"); + $ilDB->manipulate($sql); + + if ($a_exc_ref_id) { + $this->sendNotification($a_exc_ref_id, $a_user_id, "rmv"); + } + + $this->writeLog( + self::TEAM_LOG_REMOVE_MEMBER, + ilObjUser::_lookupFullname($a_user_id) + ); + + $this->read($this->id); + } + + /** + * Get team structure for assignment + * + * @param int $a_ass_id + * @return array + */ + public static function getAssignmentTeamMap($a_ass_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $map = array(); - - $sql = "SELECT * FROM il_exc_team". - " WHERE ass_id = ".$ilDB->quote($a_ass_id, "integer"); - $set = $ilDB->query($sql); - while($row = $ilDB->fetchAssoc($set)) - { - $map[$row["user_id"]] = $row["id"]; - } - - return $map; - } - - public function writeLog($a_action, $a_details = null) - { - self::writeTeamLog($this->id, $a_action, $a_details); - } + $ilDB = $DIC->database(); + + $map = array(); + + $sql = "SELECT * FROM il_exc_team" . + " WHERE ass_id = " . $ilDB->quote($a_ass_id, "integer"); + $set = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($set)) { + $map[$row["user_id"]] = $row["id"]; + } + + return $map; + } + + public function writeLog($a_action, $a_details = null) + { + self::writeTeamLog($this->id, $a_action, $a_details); + } - /** - * Add entry to team log - * - * @param int $a_team_id - * @param int $a_action - * @param string $a_details - */ - public static function writeTeamLog($a_team_id, $a_action, $a_details = null) - { - global $DIC; + /** + * Add entry to team log + * + * @param int $a_team_id + * @param int $a_action + * @param string $a_details + */ + public static function writeTeamLog($a_team_id, $a_action, $a_details = null) + { + global $DIC; - $ilDB = $DIC->database(); - $ilUser = $DIC->user(); - $id = $ilDB->nextId('il_exc_team_log'); + $ilDB = $DIC->database(); + $ilUser = $DIC->user(); + $id = $ilDB->nextId('il_exc_team_log'); - $fields = array( - "log_id" => array("integer", $id), - "team_id" => array("integer", $a_team_id), - "user_id" => array("integer", $ilUser->getId()), - "action" => array("integer", $a_action), - "details" => array("text", $a_details), - "tstamp" => array("integer", time()) - ); + $fields = array( + "log_id" => array("integer", $id), + "team_id" => array("integer", $a_team_id), + "user_id" => array("integer", $ilUser->getId()), + "action" => array("integer", $a_action), + "details" => array("text", $a_details), + "tstamp" => array("integer", time()) + ); - $ilDB->insert("il_exc_team_log", $fields); - } - - /** - * Get all log entries for team - * - * @param int $a_team_id - * @return array - */ - public function getLog() - { - $ilDB = $this->db; - - $this->cleanLog(); - - $res = array(); - - $sql = "SELECT * FROM il_exc_team_log". - " WHERE team_id = ".$ilDB->quote($this->id, "integer"). - " ORDER BY tstamp DESC"; - $set = $ilDB->query($sql); - while($row = $ilDB->fetchAssoc($set)) - { - $res[] = $row; - } - return $res; - } - - /** - * Remove obsolete log entries - * - * As there is no proper team deletion event, we are doing it this way - */ - protected function cleanLog() - { - $ilDB = $this->db; - - // #18179 - - $teams = array(); - $set = $ilDB->query("SELECT DISTINCT(id)". - " FROM il_exc_team"); - while($row = $ilDB->fetchAssoc($set)) - { - $teams[] = $row["id"]; - } - - $set = $ilDB->query("SELECT DISTINCT(team_id)". - " FROM il_exc_team_log"); - while($row = $ilDB->fetchAssoc($set)) - { - $team_id = $row["team_id"]; - if(!in_array($team_id, $teams)) - { - $ilDB->manipulate("DELETE FROM il_exc_team_log". - " WHERE team_id = ".$ilDB->quote($team_id, "integer")); - } - } - } - - /** - * Send notification about team status - * - * @param int $a_exc_ref_id - * @param int $a_user_id - * @param string $a_action - */ - public function sendNotification($a_exc_ref_id, $a_user_id, $a_action) - { - $ilUser = $this->user; - - // no need to notify current user - if(!$a_exc_ref_id || - $ilUser->getId() == $a_user_id) - { - return; - } - - $ass = new ilExAssignment($this->assignment_id); - - include_once "./Services/Notification/classes/class.ilSystemNotification.php"; - $ntf = new ilSystemNotification(); - $ntf->setLangModules(array("exc")); - $ntf->setRefId($a_exc_ref_id); - $ntf->setChangedByUserId($ilUser->getId()); - $ntf->setSubjectLangId('exc_team_notification_subject_'.$a_action); - $ntf->setIntroductionLangId('exc_team_notification_body_'.$a_action); - $ntf->addAdditionalInfo("exc_assignment", $ass->getTitle()); - $ntf->setGotoLangId('exc_team_notification_link'); - $ntf->setReasonLangId('exc_team_notification_reason'); - $ntf->sendMail(array($a_user_id)); - } - - - public static function getAdoptableTeamAssignments($a_exercise_id, $a_exclude_ass_id = null, $a_user_id = null) - { - $res = array(); - - $data = ilExAssignment::getAssignmentDataOfExercise($a_exercise_id); - foreach($data as $row) - { - if($a_exclude_ass_id && $row["id"] == $a_exclude_ass_id) - { - continue; - } - - if($row["type"] == ilExAssignment::TYPE_UPLOAD_TEAM) - { - $map = self::getAssignmentTeamMap($row["id"]); - - if($a_user_id && !array_key_exists($a_user_id, $map)) - { - continue; - } - - if(sizeof($map)) - { - $user_team = null; - if($a_user_id) - { - $user_team_id = $map[$a_user_id]; - $user_team = array(); - foreach($map as $user_id => $team_id) - { - if($user_id != $a_user_id && - $user_team_id == $team_id) - { - $user_team[] = $user_id; - } - } - } - - if(!$a_user_id || - sizeof($user_team)) - { - $res[$row["id"]] = array( - "title" => $row["title"], - "teams" => sizeof(array_flip($map)), - ); - - if($a_user_id) - { - $res[$row["id"]]["user_team"] = $user_team; - } - } - } - } - } - - return ilUtil::sortArray($res, "title", "asc", false, true); - } - - public static function adoptTeams($a_source_ass_id, $a_target_ass_id, $a_user_id = null, $a_exc_ref_id = null) - { - $teams = array(); - - $old_team = null; - foreach(self::getAssignmentTeamMap($a_source_ass_id) as $user_id => $team_id) - { - $teams[$team_id][] = $user_id; - - if($a_user_id && $user_id == $a_user_id) - { - $old_team = $team_id; - } - } - - if($a_user_id) - { - // no existing team (in source) or user already in team (in current) - if(!$old_team || - self::getInstanceByUserId($a_target_ass_id, $a_user_id)->getId()) - { - return; - } - } - - $current_map = self::getAssignmentTeamMap($a_target_ass_id); - - foreach($teams as $team_id => $user_ids) - { - if(!$old_team || $team_id == $old_team) - { - // only not assigned users - $missing = array(); - foreach($user_ids as $user_id) - { - if(!array_key_exists($user_id, $current_map)) - { - $missing[] = $user_id; - } - } - - if(sizeof($missing)) - { - // create new team - $first = array_shift($missing); - $new_team = self::getInstanceByUserId($a_target_ass_id, $first, true); + $ilDB->insert("il_exc_team_log", $fields); + } + + /** + * Get all log entries for team + * + * @param int $a_team_id + * @return array + */ + public function getLog() + { + $ilDB = $this->db; + + $this->cleanLog(); + + $res = array(); + + $sql = "SELECT * FROM il_exc_team_log" . + " WHERE team_id = " . $ilDB->quote($this->id, "integer") . + " ORDER BY tstamp DESC"; + $set = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($set)) { + $res[] = $row; + } + return $res; + } + + /** + * Remove obsolete log entries + * + * As there is no proper team deletion event, we are doing it this way + */ + protected function cleanLog() + { + $ilDB = $this->db; + + // #18179 + + $teams = array(); + $set = $ilDB->query("SELECT DISTINCT(id)" . + " FROM il_exc_team"); + while ($row = $ilDB->fetchAssoc($set)) { + $teams[] = $row["id"]; + } + + $set = $ilDB->query("SELECT DISTINCT(team_id)" . + " FROM il_exc_team_log"); + while ($row = $ilDB->fetchAssoc($set)) { + $team_id = $row["team_id"]; + if (!in_array($team_id, $teams)) { + $ilDB->manipulate("DELETE FROM il_exc_team_log" . + " WHERE team_id = " . $ilDB->quote($team_id, "integer")); + } + } + } + + /** + * Send notification about team status + * + * @param int $a_exc_ref_id + * @param int $a_user_id + * @param string $a_action + */ + public function sendNotification($a_exc_ref_id, $a_user_id, $a_action) + { + $ilUser = $this->user; + + // no need to notify current user + if (!$a_exc_ref_id || + $ilUser->getId() == $a_user_id) { + return; + } + + $ass = new ilExAssignment($this->assignment_id); + + include_once "./Services/Notification/classes/class.ilSystemNotification.php"; + $ntf = new ilSystemNotification(); + $ntf->setLangModules(array("exc")); + $ntf->setRefId($a_exc_ref_id); + $ntf->setChangedByUserId($ilUser->getId()); + $ntf->setSubjectLangId('exc_team_notification_subject_' . $a_action); + $ntf->setIntroductionLangId('exc_team_notification_body_' . $a_action); + $ntf->addAdditionalInfo("exc_assignment", $ass->getTitle()); + $ntf->setGotoLangId('exc_team_notification_link'); + $ntf->setReasonLangId('exc_team_notification_reason'); + $ntf->sendMail(array($a_user_id)); + } + + + public static function getAdoptableTeamAssignments($a_exercise_id, $a_exclude_ass_id = null, $a_user_id = null) + { + $res = array(); + + $data = ilExAssignment::getAssignmentDataOfExercise($a_exercise_id); + foreach ($data as $row) { + if ($a_exclude_ass_id && $row["id"] == $a_exclude_ass_id) { + continue; + } + + if ($row["type"] == ilExAssignment::TYPE_UPLOAD_TEAM) { + $map = self::getAssignmentTeamMap($row["id"]); + + if ($a_user_id && !array_key_exists($a_user_id, $map)) { + continue; + } + + if (sizeof($map)) { + $user_team = null; + if ($a_user_id) { + $user_team_id = $map[$a_user_id]; + $user_team = array(); + foreach ($map as $user_id => $team_id) { + if ($user_id != $a_user_id && + $user_team_id == $team_id) { + $user_team[] = $user_id; + } + } + } + + if (!$a_user_id || + sizeof($user_team)) { + $res[$row["id"]] = array( + "title" => $row["title"], + "teams" => sizeof(array_flip($map)), + ); + + if ($a_user_id) { + $res[$row["id"]]["user_team"] = $user_team; + } + } + } + } + } + + return ilUtil::sortArray($res, "title", "asc", false, true); + } + + public static function adoptTeams($a_source_ass_id, $a_target_ass_id, $a_user_id = null, $a_exc_ref_id = null) + { + $teams = array(); + + $old_team = null; + foreach (self::getAssignmentTeamMap($a_source_ass_id) as $user_id => $team_id) { + $teams[$team_id][] = $user_id; + + if ($a_user_id && $user_id == $a_user_id) { + $old_team = $team_id; + } + } + + if ($a_user_id) { + // no existing team (in source) or user already in team (in current) + if (!$old_team || + self::getInstanceByUserId($a_target_ass_id, $a_user_id)->getId()) { + return; + } + } + + $current_map = self::getAssignmentTeamMap($a_target_ass_id); + + foreach ($teams as $team_id => $user_ids) { + if (!$old_team || $team_id == $old_team) { + // only not assigned users + $missing = array(); + foreach ($user_ids as $user_id) { + if (!array_key_exists($user_id, $current_map)) { + $missing[] = $user_id; + } + } + + if (sizeof($missing)) { + // create new team + $first = array_shift($missing); + $new_team = self::getInstanceByUserId($a_target_ass_id, $first, true); - // give new team starting time of original user - if ($a_user_id > 0 && $old_team > 0) - { - $idl = ilExcIndividualDeadline::getInstance($a_target_ass_id, $a_user_id); - if ($idl->getStartingTimestamp()) - { - $idl_team = ilExcIndividualDeadline::getInstance($a_target_ass_id, $new_team->getId(), true); - $idl_team->setStartingTimestamp($idl->getStartingTimestamp()); - $idl_team->save(); - } - } + // give new team starting time of original user + if ($a_user_id > 0 && $old_team > 0) { + $idl = ilExcIndividualDeadline::getInstance($a_target_ass_id, $a_user_id); + if ($idl->getStartingTimestamp()) { + $idl_team = ilExcIndividualDeadline::getInstance($a_target_ass_id, $new_team->getId(), true); + $idl_team->setStartingTimestamp($idl->getStartingTimestamp()); + $idl_team->save(); + } + } - if($a_exc_ref_id) - { - // getTeamId() does NOT send notification - $new_team->sendNotification($a_exc_ref_id, $first, "add"); - } - - foreach($missing as $user_id) - { - $new_team->addTeamMember($user_id, $a_exc_ref_id); - } - } - } - } - } - - // - // GROUPS - // - - public static function getAdoptableGroups($a_exc_ref_id) - { - global $DIC; + if ($a_exc_ref_id) { + // getTeamId() does NOT send notification + $new_team->sendNotification($a_exc_ref_id, $first, "add"); + } + + foreach ($missing as $user_id) { + $new_team->addTeamMember($user_id, $a_exc_ref_id); + } + } + } + } + } + + // + // GROUPS + // + + public static function getAdoptableGroups($a_exc_ref_id) + { + global $DIC; - $tree = $DIC->repositoryTree(); - - $res = array(); - - $parent_ref_id = $tree->getParentId($a_exc_ref_id); - if($parent_ref_id) - { - foreach($tree->getChildsByType($parent_ref_id, "grp") as $group) - { - $res[] = $group["obj_id"]; - } - } - - return $res; - } - - public static function getGroupMembersMap($a_exc_ref_id) - { - $res = array(); - - include_once "Modules/Group/classes/class.ilGroupParticipants.php"; - foreach(self::getAdoptableGroups($a_exc_ref_id) as $grp_obj_id) - { - $members_obj = new ilGroupParticipants($grp_obj_id); - - $res[$grp_obj_id] = array( - "title" => ilObject::_lookupTitle($grp_obj_id) - ,"members" => $members_obj->getMembers() - ); - } - - return ilUtil::sortArray($res, "title", "asc", false, true); - } + $tree = $DIC->repositoryTree(); + + $res = array(); + + $parent_ref_id = $tree->getParentId($a_exc_ref_id); + if ($parent_ref_id) { + foreach ($tree->getChildsByType($parent_ref_id, "grp") as $group) { + $res[] = $group["obj_id"]; + } + } + + return $res; + } + + public static function getGroupMembersMap($a_exc_ref_id) + { + $res = array(); + + include_once "Modules/Group/classes/class.ilGroupParticipants.php"; + foreach (self::getAdoptableGroups($a_exc_ref_id) as $grp_obj_id) { + $members_obj = new ilGroupParticipants($grp_obj_id); + + $res[$grp_obj_id] = array( + "title" => ilObject::_lookupTitle($grp_obj_id) + ,"members" => $members_obj->getMembers() + ); + } + + return ilUtil::sortArray($res, "title", "asc", false, true); + } - /** - * Create random teams for assignment type "team upload" following specific rules. - * example: - * - total exercise members : 9 members - * - total number of teams to create (defined via form): 4 groups - * - number of users per team --> 9 / 4 = 2 users - * - users to spread over groups --> 9 % 4 = 1 user - * - final teams: 3 teams of 2 users and 1 team of 3 users. - * @param $a_exercise_id integer - * @param $a_assignment_id integer - * @param $a_number_teams integer - * @param $a_min_participants integer - * @return bool - */ - public function createRandomTeams($a_exercise_id, $a_assignment_id, $a_number_teams, $a_min_participants) - { - //just in case... - if(count(self::getAssignmentTeamMap($a_assignment_id))) { - return false; - } - $exercise = new ilObjExercise($a_exercise_id, false); - $obj_exc_members = new ilExerciseMembers($exercise); - $members = $obj_exc_members->getMembers(); - $total_exc_members = count($members); - $number_of_teams = $a_number_teams; - if(!$number_of_teams) - { - if($a_min_participants) { - $number_of_teams = round($total_exc_members / $a_min_participants); - } else { - $number_of_teams = random_int(1, $total_exc_members); - } - } - $members_per_team = round($total_exc_members / $number_of_teams); - shuffle($members); - for($i=0;$i<$number_of_teams;$i++) - { - $members_counter = 0; - while(!empty($members) && $members_counter < $members_per_team) - { - $member_id = array_pop($members); - if($members_counter == 0) - { - $team_id = $this->createTeam($a_assignment_id, $member_id); - $this->setId($team_id); - $this->assignment_id = $a_assignment_id; - } - else - { - $this->addTeamMember($member_id); - } - $members_counter++; - } - } - //get the new teams, remove duplicates. - $teams = array_unique(array_values(self::getAssignmentTeamMap($a_assignment_id))); - shuffle($teams); - while(!empty($members)) - { - $member_id = array_pop($members); - $team_id = array_pop($teams); - $this->setId($team_id); - $this->addTeamMember($member_id); - } - return true; - } + /** + * Create random teams for assignment type "team upload" following specific rules. + * example: + * - total exercise members : 9 members + * - total number of teams to create (defined via form): 4 groups + * - number of users per team --> 9 / 4 = 2 users + * - users to spread over groups --> 9 % 4 = 1 user + * - final teams: 3 teams of 2 users and 1 team of 3 users. + * @param $a_exercise_id integer + * @param $a_assignment_id integer + * @param $a_number_teams integer + * @param $a_min_participants integer + * @return bool + */ + public function createRandomTeams($a_exercise_id, $a_assignment_id, $a_number_teams, $a_min_participants) + { + //just in case... + if (count(self::getAssignmentTeamMap($a_assignment_id))) { + return false; + } + $exercise = new ilObjExercise($a_exercise_id, false); + $obj_exc_members = new ilExerciseMembers($exercise); + $members = $obj_exc_members->getMembers(); + $total_exc_members = count($members); + $number_of_teams = $a_number_teams; + if (!$number_of_teams) { + if ($a_min_participants) { + $number_of_teams = round($total_exc_members / $a_min_participants); + } else { + $number_of_teams = random_int(1, $total_exc_members); + } + } + $members_per_team = round($total_exc_members / $number_of_teams); + shuffle($members); + for ($i=0;$i<$number_of_teams;$i++) { + $members_counter = 0; + while (!empty($members) && $members_counter < $members_per_team) { + $member_id = array_pop($members); + if ($members_counter == 0) { + $team_id = $this->createTeam($a_assignment_id, $member_id); + $this->setId($team_id); + $this->assignment_id = $a_assignment_id; + } else { + $this->addTeamMember($member_id); + } + $members_counter++; + } + } + //get the new teams, remove duplicates. + $teams = array_unique(array_values(self::getAssignmentTeamMap($a_assignment_id))); + shuffle($teams); + while (!empty($members)) { + $member_id = array_pop($members); + $team_id = array_pop($teams); + $this->setId($team_id); + $this->addTeamMember($member_id); + } + return true; + } } - diff --git a/Modules/Exercise/classes/class.ilExAssignmentTeamLogTableGUI.php b/Modules/Exercise/classes/class.ilExAssignmentTeamLogTableGUI.php index d686f75a7493e588bf43eeee55bf60356772e54b..3e80f43b73fd5bf54e4e596d75334385b16f61b1 100644 --- a/Modules/Exercise/classes/class.ilExAssignmentTeamLogTableGUI.php +++ b/Modules/Exercise/classes/class.ilExAssignmentTeamLogTableGUI.php @@ -4,109 +4,105 @@ include_once './Services/Table/classes/class.ilTable2GUI.php'; /** - * List all log entries of team + * List all log entries of team * * @author Jörg Lützenkirchen * @ingroup ModulesExercise */ class ilExAssignmentTeamLogTableGUI extends ilTable2GUI { - protected $team; // [ilExAssignmentTeam] - - /** - * Constructor - * - * @param ilObject $a_parent_obj - * @param string $a_parent_cmd - * @param int $a_team_id - */ - public function __construct($a_parent_obj, $a_parent_cmd, ilExAssignmentTeam $a_team) - { - global $DIC; + protected $team; // [ilExAssignmentTeam] + + /** + * Constructor + * + * @param ilObject $a_parent_obj + * @param string $a_parent_cmd + * @param int $a_team_id + */ + public function __construct($a_parent_obj, $a_parent_cmd, ilExAssignmentTeam $a_team) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $ilCtrl = $DIC->ctrl(); - - $this->team = $a_team; - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setTitle($this->lng->txt("exc_team_log")); + $this->ctrl = $DIC->ctrl(); + $ilCtrl = $DIC->ctrl(); + + $this->team = $a_team; + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setTitle($this->lng->txt("exc_team_log")); - $this->addColumn($this->lng->txt("date"), "tstamp"); - $this->addColumn($this->lng->txt("user"), "user"); - $this->addColumn($this->lng->txt("details"), "details"); - - $this->setDefaultOrderField("tstamp"); - $this->setDefaultOrderDirection("desc"); - - $this->setRowTemplate("tpl.exc_team_log_row.html", "Modules/Exercise"); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd)); + $this->addColumn($this->lng->txt("date"), "tstamp"); + $this->addColumn($this->lng->txt("user"), "user"); + $this->addColumn($this->lng->txt("details"), "details"); + + $this->setDefaultOrderField("tstamp"); + $this->setDefaultOrderDirection("desc"); + + $this->setRowTemplate("tpl.exc_team_log_row.html", "Modules/Exercise"); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd)); - $this->getItems(); - } + $this->getItems(); + } - /** - * Get all completed tests - */ - protected function getItems() - { - $data = array(); + /** + * Get all completed tests + */ + protected function getItems() + { + $data = array(); - foreach($this->team->getLog() as $item) - {; - switch($item["action"]) - { - case ilExAssignmentTeam::TEAM_LOG_CREATE_TEAM: - $mess = "create_team"; - break; - - case ilExAssignmentTeam::TEAM_LOG_ADD_MEMBER: - $mess = "add_member"; - break; - - case ilExAssignmentTeam::TEAM_LOG_REMOVE_MEMBER: - $mess = "remove_member"; - break; - - case ilExAssignmentTeam::TEAM_LOG_ADD_FILE: - $mess = "add_file"; - break; - - case ilExAssignmentTeam::TEAM_LOG_REMOVE_FILE: - $mess = "remove_file"; - break; - } - - $details = $this->lng->txt("exc_team_log_".$mess); - if($item["details"]) - { - $details = sprintf($details, $item["details"]); - } - - $data[] = array( - "tstamp" => $item["tstamp"], - "user" => ilObjUser::_lookupFullname($item["user_id"]), - "details" => $details - ); - } - - $this->setData($data); - } + foreach ($this->team->getLog() as $item) { + ; + switch ($item["action"]) { + case ilExAssignmentTeam::TEAM_LOG_CREATE_TEAM: + $mess = "create_team"; + break; + + case ilExAssignmentTeam::TEAM_LOG_ADD_MEMBER: + $mess = "add_member"; + break; + + case ilExAssignmentTeam::TEAM_LOG_REMOVE_MEMBER: + $mess = "remove_member"; + break; + + case ilExAssignmentTeam::TEAM_LOG_ADD_FILE: + $mess = "add_file"; + break; + + case ilExAssignmentTeam::TEAM_LOG_REMOVE_FILE: + $mess = "remove_file"; + break; + } + + $details = $this->lng->txt("exc_team_log_" . $mess); + if ($item["details"]) { + $details = sprintf($details, $item["details"]); + } + + $data[] = array( + "tstamp" => $item["tstamp"], + "user" => ilObjUser::_lookupFullname($item["user_id"]), + "details" => $details + ); + } + + $this->setData($data); + } - /** - * Fill template row - * - * @param array $a_set - */ - protected function fillRow($a_set) - { - $date = ilDatePresentation::formatDate(new ilDateTime($a_set["tstamp"], IL_CAL_UNIX)); - - $this->tpl->setVariable("TSTAMP", $date); - $this->tpl->setVariable("TXT_USER", $a_set["user"]); - $this->tpl->setVariable("TXT_DETAILS", $a_set["details"]); - } + /** + * Fill template row + * + * @param array $a_set + */ + protected function fillRow($a_set) + { + $date = ilDatePresentation::formatDate(new ilDateTime($a_set["tstamp"], IL_CAL_UNIX)); + + $this->tpl->setVariable("TSTAMP", $date); + $this->tpl->setVariable("TXT_USER", $a_set["user"]); + $this->tpl->setVariable("TXT_DETAILS", $a_set["details"]); + } } - -?> \ No newline at end of file diff --git a/Modules/Exercise/classes/class.ilExAssignmentTeamTableGUI.php b/Modules/Exercise/classes/class.ilExAssignmentTeamTableGUI.php index bc32454e5c0369d79edb27d0705ee7f9ece6c27f..d3c4aec9a7aa3c8a31c5f2bd5f3f7df15f2b3af6 100644 --- a/Modules/Exercise/classes/class.ilExAssignmentTeamTableGUI.php +++ b/Modules/Exercise/classes/class.ilExAssignmentTeamTableGUI.php @@ -11,137 +11,123 @@ include_once './Services/Table/classes/class.ilTable2GUI.php'; */ class ilExAssignmentTeamTableGUI extends ilTable2GUI { - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - protected $mode; // [int] - protected $team; // [ilExAssignmentTeam] - protected $read_only; // [bool] - protected $parent_ref_id; // [int] + protected $mode; // [int] + protected $team; // [ilExAssignmentTeam] + protected $read_only; // [bool] + protected $parent_ref_id; // [int] - /** - * @var bool - */ - protected $edit_permission; - - const MODE_ADD = 1; - const MODE_EDIT = 2; - - /** - * Constructor - * - * @param ilObject $a_parent_obj - * @param string $a_parent_cmd - * @param int $a_mode - * @param int $a_parent_ref_id - * @param ilExAssignmentTeam $a_team - * @param ilExAssignment $a_assignment - * @param array $a_member_ids - * @param bool $a_read_only - */ - public function __construct($a_parent_obj, $a_parent_cmd, $a_mode, $a_parent_ref_id, ilExAssignmentTeam $a_team, $a_read_only = false) - { - global $DIC; + /** + * @var bool + */ + protected $edit_permission; + + const MODE_ADD = 1; + const MODE_EDIT = 2; + + /** + * Constructor + * + * @param ilObject $a_parent_obj + * @param string $a_parent_cmd + * @param int $a_mode + * @param int $a_parent_ref_id + * @param ilExAssignmentTeam $a_team + * @param ilExAssignment $a_assignment + * @param array $a_member_ids + * @param bool $a_read_only + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_mode, $a_parent_ref_id, ilExAssignmentTeam $a_team, $a_read_only = false) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->access = $DIC->access(); - $ilCtrl = $DIC->ctrl(); + $this->ctrl = $DIC->ctrl(); + $this->access = $DIC->access(); + $ilCtrl = $DIC->ctrl(); - $access = $this->access; - $user = $DIC->user(); - $this->edit_permission = (bool) $access->checkAccessOfUser($user->getId(), "edit", "", $a_parent_ref_id); + $access = $this->access; + $user = $DIC->user(); + $this->edit_permission = (bool) $access->checkAccessOfUser($user->getId(), "edit", "", $a_parent_ref_id); - $this->mode = $a_mode; - $this->team = $a_team; - $this->read_only = (bool)$a_read_only; - $this->parent_ref_id = $a_parent_ref_id; - - parent::__construct($a_parent_obj, $a_parent_cmd); + $this->mode = $a_mode; + $this->team = $a_team; + $this->read_only = (bool) $a_read_only; + $this->parent_ref_id = $a_parent_ref_id; + + parent::__construct($a_parent_obj, $a_parent_cmd); - if(!$this->read_only) - { - $this->addColumn("", "", 1); - } - $this->addColumn($this->lng->txt("name"), "name"); - - $this->setDefaultOrderField("name"); - - $this->setRowTemplate("tpl.exc_team_member_row.html", "Modules/Exercise"); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd)); + if (!$this->read_only) { + $this->addColumn("", "", 1); + } + $this->addColumn($this->lng->txt("name"), "name"); + + $this->setDefaultOrderField("name"); + + $this->setRowTemplate("tpl.exc_team_member_row.html", "Modules/Exercise"); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd)); - if(!$this->read_only) - { - if($this->mode == self::MODE_ADD) - { - $this->setTitle($this->lng->txt("exc_team_member_container_add")); - $this->addMultiCommand("addTeamMemberContainerAction", $this->lng->txt("add")); - } - else - { - $this->setTitle($this->lng->txt("exc_team_members")); - $this->addMultiCommand("confirmRemoveTeamMember", $this->lng->txt("remove")); - } - } - - $this->getItems(); - } + if (!$this->read_only) { + if ($this->mode == self::MODE_ADD) { + $this->setTitle($this->lng->txt("exc_team_member_container_add")); + $this->addMultiCommand("addTeamMemberContainerAction", $this->lng->txt("add")); + } else { + $this->setTitle($this->lng->txt("exc_team_members")); + $this->addMultiCommand("confirmRemoveTeamMember", $this->lng->txt("remove")); + } + } + + $this->getItems(); + } - /** - * Get all completed tests - */ - protected function getItems() - { - if($this->mode == self::MODE_ADD) - { - $assigned = $this->team->getMembersOfAllTeams(); - } - else - { - $assigned = array(); - $this->member_ids = $this->team->getMembers(); - } - - include_once "Services/User/classes/class.ilUserUtil.php"; - - $data = array(); - foreach($this->member_ids as $id) - { - if(!in_array($id, $assigned)) - { - $data[] = array("id" => $id, - "name" => ilUserUtil::getNamePresentation($id, false, false, "", $this->edit_permission)); - } - } - - $this->setData($data); - } + /** + * Get all completed tests + */ + protected function getItems() + { + if ($this->mode == self::MODE_ADD) { + $assigned = $this->team->getMembersOfAllTeams(); + } else { + $assigned = array(); + $this->member_ids = $this->team->getMembers(); + } + + include_once "Services/User/classes/class.ilUserUtil.php"; + + $data = array(); + foreach ($this->member_ids as $id) { + if (!in_array($id, $assigned)) { + $data[] = array("id" => $id, + "name" => ilUserUtil::getNamePresentation($id, false, false, "", $this->edit_permission)); + } + } + + $this->setData($data); + } - /** - * Fill template row - * - * @param array $a_set - */ - protected function fillRow($a_set) - { - $ilAccess = $this->access; - - if(!$this->read_only) - { - $this->tpl->setVariable("VAL_ID", $a_set["id"]); - } - $this->tpl->setVariable("TXT_NAME", $a_set["name"]); - - // #18327 - if(!$ilAccess->checkAccessOfUser($a_set["id"], "read","", $this->parent_ref_id) && - is_array($info = $ilAccess->getInfo())) - { - $this->tpl->setCurrentBlock('access_warning'); - $this->tpl->setVariable('PARENT_ACCESS', $info[0]["text"]); - $this->tpl->parseCurrentBlock(); - } - } + /** + * Fill template row + * + * @param array $a_set + */ + protected function fillRow($a_set) + { + $ilAccess = $this->access; + + if (!$this->read_only) { + $this->tpl->setVariable("VAL_ID", $a_set["id"]); + } + $this->tpl->setVariable("TXT_NAME", $a_set["name"]); + + // #18327 + if (!$ilAccess->checkAccessOfUser($a_set["id"], "read", "", $this->parent_ref_id) && + is_array($info = $ilAccess->getInfo())) { + $this->tpl->setCurrentBlock('access_warning'); + $this->tpl->setVariable('PARENT_ACCESS', $info[0]["text"]); + $this->tpl->parseCurrentBlock(); + } + } } - -?> \ No newline at end of file diff --git a/Modules/Exercise/classes/class.ilExGradesTableGUI.php b/Modules/Exercise/classes/class.ilExGradesTableGUI.php index 8fdc03245ff0812ebe0dcf0899796cdd5599b4c9..3fc676bac6499c577f6f695903cc9a1a4998a7f9 100644 --- a/Modules/Exercise/classes/class.ilExGradesTableGUI.php +++ b/Modules/Exercise/classes/class.ilExGradesTableGUI.php @@ -15,195 +15,190 @@ include_once("./Modules/Exercise/classes/class.ilExAssignmentMemberStatus.php"); */ class ilExGradesTableGUI extends ilTable2GUI { - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_exc, $a_mem_obj) - { - global $DIC; + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_exc, $a_mem_obj) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->exc = $a_exc; - $this->exc_id = $this->exc->getId(); - - include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); - $this->setId("exc_grades_".$this->exc_id); - - $this->mem_obj = $a_mem_obj; - - $mems = $this->mem_obj->getMembers(); - $mems = $GLOBALS['DIC']->access()->filterUserIdsByRbacOrPositionOfCurrentUser( - 'edit_submissions_grades', - 'edit_submissions_grades', - $this->exc->getRefId(), - $mems - ); - - $data = array(); - foreach ($mems as $d) - { - $data[$d] = ilObjUser::_lookupName($d); - $data[$d]["user_id"] = $d; - } - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setData($data); - $this->ass_data = ilExAssignment::getInstancesByExercise($this->exc_id); - -//var_dump($data); - $this->setTitle($lng->txt("exc_grades")); - $this->setTopCommands(true); - //$this->setLimit(9999); - -// $this->addColumn("", "", "1", true); - $this->addColumn($this->lng->txt("name"), "lastname"); - $cnt = 1; - foreach ($this->ass_data as $ass) - { - $ilCtrl->setParameter($this->parent_obj, "ass_id", $ass->getId()); - $cnt_str = ''.$cnt.''; - if ($ass->getMandatory()) - { - $this->addColumn("".$cnt_str."", "", "", false, "", $ass->getTitle()." ". - "(".$lng->txt("exc_mandatory").")"); - } - else - { - $this->addColumn($cnt_str, "", "", false, "", $ass->getTitle()); - } - $cnt++; - } - $ilCtrl->setParameter($this->parent_obj, "ass_id", ""); - - $this->addColumn($this->lng->txt("exc_total_exc"), ""); - $this->lng->loadLanguageModule("trac"); - $this->addColumn($this->lng->txt("trac_comment")); - -// $this->addColumn($this->lng->txt("exc_grading"), "solved_time"); -// $this->addColumn($this->lng->txt("mail"), "feedback_time"); - - $this->setDefaultOrderField("lastname"); - $this->setDefaultOrderDirection("asc"); - - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.exc_grades_row.html", "Modules/Exercise"); - //$this->disable("footer"); - $this->setEnableTitle(true); -// $this->setSelectAllCheckbox("assid"); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->exc = $a_exc; + $this->exc_id = $this->exc->getId(); + + include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); + $this->setId("exc_grades_" . $this->exc_id); + + $this->mem_obj = $a_mem_obj; + + $mems = $this->mem_obj->getMembers(); + $mems = $GLOBALS['DIC']->access()->filterUserIdsByRbacOrPositionOfCurrentUser( + 'edit_submissions_grades', + 'edit_submissions_grades', + $this->exc->getRefId(), + $mems + ); + + $data = array(); + foreach ($mems as $d) { + $data[$d] = ilObjUser::_lookupName($d); + $data[$d]["user_id"] = $d; + } + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setData($data); + $this->ass_data = ilExAssignment::getInstancesByExercise($this->exc_id); + + //var_dump($data); + $this->setTitle($lng->txt("exc_grades")); + $this->setTopCommands(true); + //$this->setLimit(9999); + + // $this->addColumn("", "", "1", true); + $this->addColumn($this->lng->txt("name"), "lastname"); + $cnt = 1; + foreach ($this->ass_data as $ass) { + $ilCtrl->setParameter($this->parent_obj, "ass_id", $ass->getId()); + $cnt_str = '' . $cnt . ''; + if ($ass->getMandatory()) { + $this->addColumn("" . $cnt_str . "", "", "", false, "", $ass->getTitle() . " " . + "(" . $lng->txt("exc_mandatory") . ")"); + } else { + $this->addColumn($cnt_str, "", "", false, "", $ass->getTitle()); + } + $cnt++; + } + $ilCtrl->setParameter($this->parent_obj, "ass_id", ""); + + $this->addColumn($this->lng->txt("exc_total_exc"), ""); + $this->lng->loadLanguageModule("trac"); + $this->addColumn($this->lng->txt("trac_comment")); + + // $this->addColumn($this->lng->txt("exc_grading"), "solved_time"); + // $this->addColumn($this->lng->txt("mail"), "feedback_time"); + + $this->setDefaultOrderField("lastname"); + $this->setDefaultOrderDirection("asc"); + + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.exc_grades_row.html", "Modules/Exercise"); + //$this->disable("footer"); + $this->setEnableTitle(true); + // $this->setSelectAllCheckbox("assid"); - if (count($mems) > 0) - { - $this->addCommandButton("saveGrades", $lng->txt("exc_save_changes")); - } - } - - /** - * Check whether field is numeric - */ - function numericOrdering($a_f) - { - if (in_array($a_f, array("order_val"))) - { - return true; - } - return false; - } - - - /** - * Fill table row - */ - protected function fillRow($d) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; + if (count($mems) > 0) { + $this->addCommandButton("saveGrades", $lng->txt("exc_save_changes")); + } + } + + /** + * Check whether field is numeric + */ + public function numericOrdering($a_f) + { + if (in_array($a_f, array("order_val"))) { + return true; + } + return false; + } + + + /** + * Fill table row + */ + protected function fillRow($d) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; - $user_id = $d["user_id"]; - - foreach ($this->ass_data as $ass) - { - $member_status = new ilExAssignmentMemberStatus($ass->getId(), $user_id); - - // grade - $this->tpl->setCurrentBlock("grade"); - $status = $member_status->getStatus(); - $this->tpl->setVariable("SEL_".strtoupper($status), ' selected="selected" '); - $this->tpl->setVariable("TXT_NOTGRADED", $lng->txt("exc_notgraded")); - $this->tpl->setVariable("TXT_PASSED", $lng->txt("exc_passed")); - $this->tpl->setVariable("TXT_FAILED", $lng->txt("exc_failed")); - $pic = $member_status->getStatusIcon(); - $this->tpl->setVariable("IMG_STATUS", ilUtil::getImagePath($pic)); - $this->tpl->setVariable("ALT_STATUS", $lng->txt("exc_".$status)); - - // mark - $mark = $member_status->getMark(); - $this->tpl->setVariable("VAL_ONLY_MARK", $mark); - - $this->tpl->parseCurrentBlock(); - } - - // exercise total - - // mark input - $this->tpl->setCurrentBlock("mark_input"); - $this->tpl->setVariable("TXT_MARK", $lng->txt("exc_mark")); - $this->tpl->setVariable("NAME_MARK", - "mark[".$user_id."]"); - include_once 'Services/Tracking/classes/class.ilLPMarks.php'; - $mark = ilLPMarks::_lookupMark($user_id, $this->exc_id); - $this->tpl->setVariable("VAL_MARK", - ilUtil::prepareFormOutput($mark)); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setCurrentBlock("grade"); - $status = ilExerciseMembers::_lookupStatus($this->exc_id, $user_id); - $this->tpl->setVariable("SEL_".strtoupper($status), ' selected="selected" '); - switch($status) - { - case "passed": $pic = "scorm/passed.svg"; break; - case "failed": $pic = "scorm/failed.svg"; break; - default: $pic = "scorm/not_attempted.svg"; break; - } - $this->tpl->setVariable("IMG_STATUS", ilUtil::getImagePath($pic)); - $this->tpl->setVariable("ALT_STATUS", $lng->txt("exc_".$status)); - - // mark - /*$this->tpl->setVariable("TXT_MARK", $lng->txt("exc_mark")); - $this->tpl->setVariable("NAME_MARK", - "mark[".$d["id"]."]"); - $mark = ilExAssignment::lookupMarkOfUser($ass["id"], $user_id); - $this->tpl->setVariable("VAL_MARK", - ilUtil::prepareFormOutput($mark));*/ - - $this->tpl->parseCurrentBlock(); - - // name - $this->tpl->setVariable("TXT_NAME", - $d["lastname"].", ".$d["firstname"]." [".$d["login"]."]"); - $this->tpl->setVariable("VAL_ID", $user_id); - - // #17679 - $ilCtrl->setParameter($this->parent_obj, "part_id", $user_id); - $url = $ilCtrl->getLinkTarget($this->parent_obj, "showParticipant"); - $ilCtrl->setParameter($this->parent_obj, "part_id", ""); - - $this->tpl->setVariable("LINK_NAME", $url); - - // comment - $this->tpl->setVariable("ID_COMMENT", $user_id); - $c = ilLPMarks::_lookupComment($user_id, $this->exc_id); - $this->tpl->setVariable("VAL_COMMENT", - ilUtil::prepareFormOutput($c)); - - - } + $user_id = $d["user_id"]; + + foreach ($this->ass_data as $ass) { + $member_status = new ilExAssignmentMemberStatus($ass->getId(), $user_id); + + // grade + $this->tpl->setCurrentBlock("grade"); + $status = $member_status->getStatus(); + $this->tpl->setVariable("SEL_" . strtoupper($status), ' selected="selected" '); + $this->tpl->setVariable("TXT_NOTGRADED", $lng->txt("exc_notgraded")); + $this->tpl->setVariable("TXT_PASSED", $lng->txt("exc_passed")); + $this->tpl->setVariable("TXT_FAILED", $lng->txt("exc_failed")); + $pic = $member_status->getStatusIcon(); + $this->tpl->setVariable("IMG_STATUS", ilUtil::getImagePath($pic)); + $this->tpl->setVariable("ALT_STATUS", $lng->txt("exc_" . $status)); + + // mark + $mark = $member_status->getMark(); + $this->tpl->setVariable("VAL_ONLY_MARK", $mark); + + $this->tpl->parseCurrentBlock(); + } + + // exercise total + + // mark input + $this->tpl->setCurrentBlock("mark_input"); + $this->tpl->setVariable("TXT_MARK", $lng->txt("exc_mark")); + $this->tpl->setVariable( + "NAME_MARK", + "mark[" . $user_id . "]" + ); + include_once 'Services/Tracking/classes/class.ilLPMarks.php'; + $mark = ilLPMarks::_lookupMark($user_id, $this->exc_id); + $this->tpl->setVariable( + "VAL_MARK", + ilUtil::prepareFormOutput($mark) + ); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setCurrentBlock("grade"); + $status = ilExerciseMembers::_lookupStatus($this->exc_id, $user_id); + $this->tpl->setVariable("SEL_" . strtoupper($status), ' selected="selected" '); + switch ($status) { + case "passed": $pic = "scorm/passed.svg"; break; + case "failed": $pic = "scorm/failed.svg"; break; + default: $pic = "scorm/not_attempted.svg"; break; + } + $this->tpl->setVariable("IMG_STATUS", ilUtil::getImagePath($pic)); + $this->tpl->setVariable("ALT_STATUS", $lng->txt("exc_" . $status)); + + // mark + /*$this->tpl->setVariable("TXT_MARK", $lng->txt("exc_mark")); + $this->tpl->setVariable("NAME_MARK", + "mark[".$d["id"]."]"); + $mark = ilExAssignment::lookupMarkOfUser($ass["id"], $user_id); + $this->tpl->setVariable("VAL_MARK", + ilUtil::prepareFormOutput($mark));*/ + + $this->tpl->parseCurrentBlock(); + // name + $this->tpl->setVariable( + "TXT_NAME", + $d["lastname"] . ", " . $d["firstname"] . " [" . $d["login"] . "]" + ); + $this->tpl->setVariable("VAL_ID", $user_id); + + // #17679 + $ilCtrl->setParameter($this->parent_obj, "part_id", $user_id); + $url = $ilCtrl->getLinkTarget($this->parent_obj, "showParticipant"); + $ilCtrl->setParameter($this->parent_obj, "part_id", ""); + + $this->tpl->setVariable("LINK_NAME", $url); + + // comment + $this->tpl->setVariable("ID_COMMENT", $user_id); + $c = ilLPMarks::_lookupComment($user_id, $this->exc_id); + $this->tpl->setVariable( + "VAL_COMMENT", + ilUtil::prepareFormOutput($c) + ); + } } -?> \ No newline at end of file diff --git a/Modules/Exercise/classes/class.ilExParticipantTableGUI.php b/Modules/Exercise/classes/class.ilExParticipantTableGUI.php index c160b4c1444e491d853b2d588c0504e67c6d4f72..b65ff503d52333d6db765929fb2b2edd08e0509c 100644 --- a/Modules/Exercise/classes/class.ilExParticipantTableGUI.php +++ b/Modules/Exercise/classes/class.ilExParticipantTableGUI.php @@ -13,172 +13,153 @@ include_once("./Modules/Exercise/classes/class.ilExerciseSubmissionTableGUI.php" */ class ilExParticipantTableGUI extends ilExerciseSubmissionTableGUI { + protected $user; // [ilObjUser] + + protected function initMode($a_item_id) + { + $lng = $this->lng; + + $this->mode = self::MODE_BY_USER; + + // global id for all exercises + $this->setId("exc_part"); + + if ($a_item_id > 0) { + $name = ilObjUser::_lookupName($a_item_id); + if (trim($name["login"])) { + $this->user = new ilObjUser($a_item_id); + + $this->setTitle($lng->txt("exc_participant") . ": " . + $name["lastname"] . ", " . $name["firstname"] . " [" . $name["login"] . "]"); + } + } - protected $user; // [ilObjUser] - - protected function initMode($a_item_id) - { - $lng = $this->lng; - - $this->mode = self::MODE_BY_USER; - - // global id for all exercises - $this->setId("exc_part"); - - if($a_item_id > 0) - { - $name = ilObjUser::_lookupName($a_item_id); - if(trim($name["login"])) - { - $this->user = new ilObjUser($a_item_id); - - $this->setTitle($lng->txt("exc_participant").": ". - $name["lastname"].", ".$name["firstname"]." [".$name["login"]."]"); - } - } + $this->setSelectAllCheckbox("ass"); + } + + protected function parseData() + { + $ilAccess = $this->access; + $ilCtrl = $this->ctrl; + + $this->addCommandButton("saveStatusParticipant", $this->lng->txt("save")); + + // #14650 - invalid user + if (!$this->user) { + $ilCtrl->setParameter($this->getParentObject(), "member_id", ""); + $ilCtrl->setParameter($this->getParentObject(), "part_id", ""); // #20073 + $ilCtrl->redirect($this->getParentObject(), $this->getParentCmd()); + } + + // #18327 + if (!$ilAccess->checkAccessOfUser($this->user->getId(), "read", "", $this->exc->getRefId()) && + is_array($info = $ilAccess->getInfo())) { + $this->setDescription('' . $info[0]['text'] . ''); + } + + $data = array(); + /** @var ilExAssignment $ass */ + foreach (ilExAssignment::getInstancesByExercise($this->exc->getId()) as $ass) { + // ilExAssignment::getMemberListData() + $member_status = $ass->getMemberStatus($this->user->getId()); + + // filter + if ($this->filter["status"] && + $member_status->getStatus() != $this->filter["status"]) { + continue; + } + + $submission = new ilExSubmission($ass, $this->user->getId()); + $idl = $ass->getIndividualDeadlines(); + + if ($this->filter["subm"]) { + if ($this->filter["subm"] == "y" && + !$submission->getLastSubmission()) { + continue; + } elseif ($this->filter["subm"] == "n" && + $submission->getLastSubmission()) { + continue; + } + } + + $row = array( + "ass" => $ass, + "submission_obj" => $submission, + "name" => $ass->getTitle(), + "status" => $member_status->getStatus(), + "mark" => $member_status->getMark(), + "sent_time" => $member_status->getSentTime(), + "status_time" => $member_status->getStatusTime(), + "feedback_time" => $member_status->getFeedbackTime(), + "submission" => $submission->getLastSubmission(), + "notice" => $member_status->getNotice(), + "comment" => $member_status->getComment(), + "order_nr" => $ass->getOrderNr() + ); + + if ($ass->hasTeam()) { + $team_map = ilExAssignmentTeam::getAssignmentTeamMap($ass->getId()); + + $row["team"] = array(); + foreach ($submission->getTeam()->getMembers() as $user_id) { + $row["team"][$user_id] = ilObjUser::_lookupFullname($user_id); + } + asort($row["team"]); + + $team_id = $team_map[$this->user->getId()]; + if (is_numeric($team_id)) { + $idl_team_id = "t" . $team_id; + if (array_key_exists($idl_team_id, $idl)) { + $row["idl"] = $idl[$idl_team_id]; + } + } + } else { + if (array_key_exists($this->user->getId(), $idl)) { + $row["idl"] = $idl[$this->user->getId()]; + } + } + + $data[] = $row; + } + + return $data; + } + + protected function parseModeColumns() + { + $cols = array(); + + $cols["name"] = array($this->lng->txt("exc_assignment"), "order_nr"); + $cols["team_members"] = array($this->lng->txt("exc_tbl_team")); + $cols["idl"] = array($this->lng->txt("exc_tbl_individual_deadline"), "idl"); + + return $cols; + } + + protected function fillRow($a_item) + { + $ilCtrl = $this->ctrl; + $ilCtrl->setParameter($this->parent_obj, "member_id", $this->user->getId()); + $ilCtrl->setParameter($this->parent_obj, "ass_id", $a_item["ass"]->getId()); + + // multi-select id + $this->tpl->setVariable("NAME_ID", "ass"); + $this->tpl->setVariable("VAL_ID", $a_item["ass"]->getId()); + + $this->parseRow($this->user->getId(), $a_item["ass"], $a_item); + + $ilCtrl->setParameter($this->parent_obj, "ass_id", ""); + $ilCtrl->setParameter($this->parent_obj, "member_id", $this->user->getId()); + } - $this->setSelectAllCheckbox("ass"); - } - - protected function parseData() - { - $ilAccess = $this->access; - $ilCtrl = $this->ctrl; - - $this->addCommandButton("saveStatusParticipant", $this->lng->txt("save")); - - // #14650 - invalid user - if(!$this->user) - { - $ilCtrl->setParameter($this->getParentObject(), "member_id", ""); - $ilCtrl->setParameter($this->getParentObject(), "part_id", ""); // #20073 - $ilCtrl->redirect($this->getParentObject(), $this->getParentCmd()); - } - - // #18327 - if(!$ilAccess->checkAccessOfUser($this->user->getId(), "read","", $this->exc->getRefId()) && - is_array($info = $ilAccess->getInfo())) - { - $this->setDescription(''.$info[0]['text'].''); - } - - $data = array(); - /** @var ilExAssignment $ass */ - foreach(ilExAssignment::getInstancesByExercise($this->exc->getId()) as $ass) - { - // ilExAssignment::getMemberListData() - $member_status = $ass->getMemberStatus($this->user->getId()); - - // filter - if($this->filter["status"] && - $member_status->getStatus() != $this->filter["status"]) - { - continue; - } - - $submission = new ilExSubmission($ass, $this->user->getId()); - $idl = $ass->getIndividualDeadlines(); - - if($this->filter["subm"]) - { - if($this->filter["subm"] == "y" && - !$submission->getLastSubmission()) - { - continue; - } - else if($this->filter["subm"] == "n" && - $submission->getLastSubmission()) - { - continue; - } - } - - $row = array( - "ass" => $ass, - "submission_obj" => $submission, - "name" => $ass->getTitle(), - "status" => $member_status->getStatus(), - "mark" => $member_status->getMark(), - "sent_time" => $member_status->getSentTime(), - "status_time" => $member_status->getStatusTime(), - "feedback_time" => $member_status->getFeedbackTime(), - "submission" => $submission->getLastSubmission(), - "notice" => $member_status->getNotice(), - "comment" => $member_status->getComment(), - "order_nr" => $ass->getOrderNr() - ); - - if($ass->hasTeam()) - { - $team_map = ilExAssignmentTeam::getAssignmentTeamMap($ass->getId()); - - $row["team"] = array(); - foreach($submission->getTeam()->getMembers() as $user_id) - { - $row["team"][$user_id] = ilObjUser::_lookupFullname($user_id); - } - asort($row["team"]); - - $team_id = $team_map[$this->user->getId()]; - if(is_numeric($team_id)) - { - $idl_team_id = "t".$team_id; - if(array_key_exists($idl_team_id, $idl)) - { - $row["idl"] = $idl[$idl_team_id]; - } - } - } - else - { - if(array_key_exists($this->user->getId(), $idl)) - { - $row["idl"] = $idl[$this->user->getId()]; - } - } - - $data[] = $row; - } - - return $data; - } - - protected function parseModeColumns() - { - $cols = array(); - - $cols["name"] = array($this->lng->txt("exc_assignment"), "order_nr"); - $cols["team_members"] = array($this->lng->txt("exc_tbl_team")); - $cols["idl"] = array($this->lng->txt("exc_tbl_individual_deadline"), "idl"); - - return $cols; - } - - protected function fillRow($a_item) - { - $ilCtrl = $this->ctrl; - $ilCtrl->setParameter($this->parent_obj, "member_id", $this->user->getId()); - $ilCtrl->setParameter($this->parent_obj, "ass_id", $a_item["ass"]->getId()); - - // multi-select id - $this->tpl->setVariable("NAME_ID", "ass"); - $this->tpl->setVariable("VAL_ID", $a_item["ass"]->getId()); - - $this->parseRow($this->user->getId(), $a_item["ass"], $a_item); - - $ilCtrl->setParameter($this->parent_obj, "ass_id", ""); - $ilCtrl->setParameter($this->parent_obj, "member_id", $this->user->getId()); - } - - /** - * @inheritdoc - */ - function numericOrdering($a_field) - { - if (in_array($a_field, ["order_nr"])) - { - return true; - } - return false; - } -} \ No newline at end of file + /** + * @inheritdoc + */ + public function numericOrdering($a_field) + { + if (in_array($a_field, ["order_nr"])) { + return true; + } + return false; + } +} diff --git a/Modules/Exercise/classes/class.ilExPeerReview.php b/Modules/Exercise/classes/class.ilExPeerReview.php index cd0140cc07bb432f75de61553888431d462127f0..49e814f79f3222d8e0436ea313abeab17c599c20 100644 --- a/Modules/Exercise/classes/class.ilExPeerReview.php +++ b/Modules/Exercise/classes/class.ilExPeerReview.php @@ -9,567 +9,509 @@ */ class ilExPeerReview { - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - protected $assignment; // [$a_assignment] - protected $assignment_id; // [int] - - public function __construct(ilExAssignment $a_assignment) - { - global $DIC; + protected $assignment; // [$a_assignment] + protected $assignment_id; // [int] + + public function __construct(ilExAssignment $a_assignment) + { + global $DIC; - $this->db = $DIC->database(); - $this->user = $DIC->user(); - $this->assignment = $a_assignment; - $this->assignment_id = $a_assignment->getId(); - } - - public function hasPeerReviewGroups() - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT count(*) cnt". - " FROM exc_assignment_peer". - " WHERE ass_id = ".$ilDB->quote($this->assignment_id, "integer")); - $cnt = $ilDB->fetchAssoc($set); - return (bool)$cnt["cnt"]; - } - - protected function getValidPeerReviewUsers() - { - $ilDB = $this->db; - - $user_ids = array(); - - // returned / assigned ?! - $set = $ilDB->query("SELECT DISTINCT(user_id)". - " FROM exc_returned". - " WHERE ass_id = ".$ilDB->quote($this->assignment_id, "integer"). - " AND (filename IS NOT NULL OR atext IS NOT NULL)"); - while($row = $ilDB->fetchAssoc($set)) - { - $user_ids[] = $row["user_id"]; - } - - return $user_ids; - } - - protected function initPeerReviews() - { - $ilDB = $this->db; - - // see #22246 - if (!$this->assignment->afterDeadlineStrict()) - { - return false; - } + $this->db = $DIC->database(); + $this->user = $DIC->user(); + $this->assignment = $a_assignment; + $this->assignment_id = $a_assignment->getId(); + } + + public function hasPeerReviewGroups() + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT count(*) cnt" . + " FROM exc_assignment_peer" . + " WHERE ass_id = " . $ilDB->quote($this->assignment_id, "integer")); + $cnt = $ilDB->fetchAssoc($set); + return (bool) $cnt["cnt"]; + } + + protected function getValidPeerReviewUsers() + { + $ilDB = $this->db; + + $user_ids = array(); + + // returned / assigned ?! + $set = $ilDB->query("SELECT DISTINCT(user_id)" . + " FROM exc_returned" . + " WHERE ass_id = " . $ilDB->quote($this->assignment_id, "integer") . + " AND (filename IS NOT NULL OR atext IS NOT NULL)"); + while ($row = $ilDB->fetchAssoc($set)) { + $user_ids[] = $row["user_id"]; + } + + return $user_ids; + } + + protected function initPeerReviews() + { + $ilDB = $this->db; + + // see #22246 + if (!$this->assignment->afterDeadlineStrict()) { + return false; + } - if(!$this->hasPeerReviewGroups()) - { - $user_ids = $this->getValidPeerReviewUsers(); - - // forever alone - if(sizeof($user_ids) < 2) - { - return false; - } - - $rater_ids = $user_ids; - $matrix = array(); + if (!$this->hasPeerReviewGroups()) { + $user_ids = $this->getValidPeerReviewUsers(); + + // forever alone + if (sizeof($user_ids) < 2) { + return false; + } + + $rater_ids = $user_ids; + $matrix = array(); - $max = min(sizeof($user_ids)-1, $this->assignment->getPeerReviewMin()); - for($loop = 0; $loop < $max; $loop++) - { - $run_ids = array_combine($user_ids, $user_ids); - - foreach($rater_ids as $rater_id) - { - $possible_peer_ids = $run_ids; - - // may not rate himself - unset($possible_peer_ids[$rater_id]); - - // already has linked peers - if(array_key_exists($rater_id, $matrix)) - { - $possible_peer_ids = array_diff($possible_peer_ids, $matrix[$rater_id]); - } - - // #15665 / #15883 - if(!sizeof($possible_peer_ids)) - { - // no more possible peers left? start over with all valid users - $run_ids = array_combine($user_ids, $user_ids); - - // see above - $possible_peer_ids = $run_ids; - - // may not rate himself - unset($possible_peer_ids[$rater_id]); + $max = min(sizeof($user_ids)-1, $this->assignment->getPeerReviewMin()); + for ($loop = 0; $loop < $max; $loop++) { + $run_ids = array_combine($user_ids, $user_ids); + + foreach ($rater_ids as $rater_id) { + $possible_peer_ids = $run_ids; + + // may not rate himself + unset($possible_peer_ids[$rater_id]); + + // already has linked peers + if (array_key_exists($rater_id, $matrix)) { + $possible_peer_ids = array_diff($possible_peer_ids, $matrix[$rater_id]); + } + + // #15665 / #15883 + if (!sizeof($possible_peer_ids)) { + // no more possible peers left? start over with all valid users + $run_ids = array_combine($user_ids, $user_ids); + + // see above + $possible_peer_ids = $run_ids; + + // may not rate himself + unset($possible_peer_ids[$rater_id]); - // already has linked peers - if(array_key_exists($rater_id, $matrix)) - { - $possible_peer_ids = array_diff($possible_peer_ids, $matrix[$rater_id]); - } - } - - // #14947 - if(sizeof($possible_peer_ids)) - { - $peer_id = array_rand($possible_peer_ids); - if(!array_key_exists($rater_id, $matrix)) - { - $matrix[$rater_id] = array(); - } - $matrix[$rater_id][] = $peer_id; - } - - // remove peer_id from possible ids in this run - unset($run_ids[$peer_id]); - } - } - - foreach($matrix as $rater_id => $peer_ids) - { - foreach($peer_ids as $peer_id) - { - $ilDB->manipulate("INSERT INTO exc_assignment_peer". - " (ass_id, giver_id, peer_id)". - " VALUES (".$ilDB->quote($this->assignment_id, "integer"). - ", ".$ilDB->quote($rater_id, "integer"). - ", ".$ilDB->quote($peer_id, "integer").")"); - } - } - - } - return true; - } - - public function resetPeerReviews() - { - $ilDB = $this->db; - - $all = array(); - - if($this->hasPeerReviewGroups()) - { - foreach($this->getAllPeerReviews(false) as $peer_id => $reviews) - { - foreach(array_keys($reviews) as $giver_id) - { - $all[] = $giver_id; - - foreach($this->assignment->getPeerReviewCriteriaCatalogueItems() as $crit) - { - $crit->setPeerReviewContext($this->assignment, $giver_id, $peer_id); - $crit->resetReview(); - } - } - } - - // peer groups - $ilDB->manipulate("DELETE FROM exc_assignment_peer". - " WHERE ass_id = ".$ilDB->quote($this->assignment_id, "integer")); - } - - return $all; - } - - public function validatePeerReviewGroups() - { - if($this->hasPeerReviewGroups()) - { - include_once "./Modules/Exercise/classes/class.ilExerciseMembers.php"; - $all_exc = ilExerciseMembers::_getMembers($this->assignment->getExerciseId()); - $all_valid = $this->getValidPeerReviewUsers(); // only returned - - $peer_ids = $invalid_peer_ids = $invalid_giver_ids = $all_reviews = array(); - foreach($this->getAllPeerReviews(false) as $peer_id => $reviews) - { - $peer_ids[] = $peer_id; - - if(!in_array($peer_id, $all_valid) || - !in_array($peer_id, $all_exc)) - { - $invalid_peer_ids[] = $peer_id; - } - foreach($reviews as $giver_id => $valid) - { - if(!in_array($giver_id, $all_valid) || - !in_array($peer_id, $all_exc)) - { - $invalid_giver_ids[] = $giver_id; - } - else - { - $all_reviews[$peer_id][$giver_id] = $valid; - } - } - } - $invalid_giver_ids = array_unique($invalid_giver_ids); - - $missing_user_ids = array(); - foreach($all_valid as $user_id) - { - // a missing peer is also a missing giver - if(!in_array($user_id, $peer_ids)) - { - $missing_user_ids[] = $user_id; - } - } - - $not_returned_ids = array(); - foreach($all_exc as $user_id) - { - if(!in_array($user_id, $all_valid)) - { - $not_returned_ids[] = $user_id; - } - } - - return array( - "invalid" => (sizeof($missing_user_ids) || - sizeof($invalid_peer_ids) || - sizeof($invalid_giver_ids)), - "missing_user_ids" => $missing_user_ids, - "not_returned_ids" => $not_returned_ids, - "invalid_peer_ids" => $invalid_peer_ids, - "invalid_giver_ids" => $invalid_giver_ids, - "reviews" => $all_reviews); - } - } - - public function getPeerReviewValues($a_giver_id, $a_peer_id) - { - $peer = null; - foreach($this->getPeerReviewsByGiver($a_giver_id) as $item) - { - if($item["peer_id"] == $a_peer_id) - { - $peer = $item; - } - } - if(!$peer) - { - return; - } - $data = $peer["pcomment"]; - if($data) - { - $items = @unserialize($data); - if(!is_array($items)) - { - // v1 - pcomment == text - $items = array("text"=>$data); - } - return $items; - } - } - - public function getPeerReviewsByGiver($a_user_id) - { - $ilDB = $this->db; - - $res = array(); - - if($this->initPeerReviews()) - { - $idx = 0; - $set = $ilDB->query("SELECT *". - " FROM exc_assignment_peer". - " WHERE giver_id = ".$ilDB->quote($a_user_id, "integer"). - " AND ass_id = ".$ilDB->quote($this->assignment_id, "integer"). - " ORDER BY peer_id"); - while($row = $ilDB->fetchAssoc($set)) - { - $row["seq"] = ++$idx; - $res[] = $row; - } - } - - return $res; - } - - public function getPeerMaskedId($a_giver_id, $a_peer_id) - { - foreach($this->getPeerReviewsByGiver($a_giver_id) as $idx => $peer) - { - if($peer["peer_id"] == $a_peer_id) - { - return $peer["seq"]; - } - } - } - - protected function validatePeerReview(array $a_data) - { - $all_empty = true; - - // see getPeerReviewValues() - $values = null; - $data = $a_data["pcomment"]; - if($data) - { - $values = @unserialize($data); - if(!is_array($values)) - { - // v1 - pcomment == text - $values = array("text"=>$data); - } - } - - /* #18491 - values can be empty, text is optional (rating/file values are handled internally in criteria) - if(!$values) - { - return false; - } - */ - - foreach($this->assignment->getPeerReviewCriteriaCatalogueItems() as $crit) - { - $crit_id = $crit->getId() - ? $crit->getId() - : $crit->getType(); - $crit->setPeerReviewContext( - $this->assignment, - $a_data["giver_id"], - $a_data["peer_id"] - ); - if(!$crit->validate($values[$crit_id])) - { - return false; - } - if($crit->hasValue($values[$crit_id])) - { - $all_empty = false; - } - } - - return !$all_empty; - } - - public function getPeerReviewsByPeerId($a_user_id, $a_only_valid = false) - { - $ilDB = $this->db; - - $res = array(); - - $idx = 0; - $set = $ilDB->query("SELECT *". - " FROM exc_assignment_peer". - " WHERE peer_id = ".$ilDB->quote($a_user_id, "integer"). - " AND ass_id = ".$ilDB->quote($this->assignment_id, "integer"). - " ORDER BY peer_id"); - while($row = $ilDB->fetchAssoc($set)) - { - if(!$a_only_valid || - $this->validatePeerReview($row)) - { - // this would be correct but rather senseless - // $row["seq"] = $this->getPeerMaskedId($row["giver_id"], $a_user_id); - $row["seq"] = ++$idx; - $res[] = $row; - } - } - - return $res; - } - - public function getAllPeerReviews($a_only_valid = true) - { - $ilDB = $this->db; - - $res = array(); + // already has linked peers + if (array_key_exists($rater_id, $matrix)) { + $possible_peer_ids = array_diff($possible_peer_ids, $matrix[$rater_id]); + } + } + + // #14947 + if (sizeof($possible_peer_ids)) { + $peer_id = array_rand($possible_peer_ids); + if (!array_key_exists($rater_id, $matrix)) { + $matrix[$rater_id] = array(); + } + $matrix[$rater_id][] = $peer_id; + } + + // remove peer_id from possible ids in this run + unset($run_ids[$peer_id]); + } + } + + foreach ($matrix as $rater_id => $peer_ids) { + foreach ($peer_ids as $peer_id) { + $ilDB->manipulate("INSERT INTO exc_assignment_peer" . + " (ass_id, giver_id, peer_id)" . + " VALUES (" . $ilDB->quote($this->assignment_id, "integer") . + ", " . $ilDB->quote($rater_id, "integer") . + ", " . $ilDB->quote($peer_id, "integer") . ")"); + } + } + } + return true; + } + + public function resetPeerReviews() + { + $ilDB = $this->db; + + $all = array(); + + if ($this->hasPeerReviewGroups()) { + foreach ($this->getAllPeerReviews(false) as $peer_id => $reviews) { + foreach (array_keys($reviews) as $giver_id) { + $all[] = $giver_id; + + foreach ($this->assignment->getPeerReviewCriteriaCatalogueItems() as $crit) { + $crit->setPeerReviewContext($this->assignment, $giver_id, $peer_id); + $crit->resetReview(); + } + } + } + + // peer groups + $ilDB->manipulate("DELETE FROM exc_assignment_peer" . + " WHERE ass_id = " . $ilDB->quote($this->assignment_id, "integer")); + } + + return $all; + } + + public function validatePeerReviewGroups() + { + if ($this->hasPeerReviewGroups()) { + include_once "./Modules/Exercise/classes/class.ilExerciseMembers.php"; + $all_exc = ilExerciseMembers::_getMembers($this->assignment->getExerciseId()); + $all_valid = $this->getValidPeerReviewUsers(); // only returned + + $peer_ids = $invalid_peer_ids = $invalid_giver_ids = $all_reviews = array(); + foreach ($this->getAllPeerReviews(false) as $peer_id => $reviews) { + $peer_ids[] = $peer_id; + + if (!in_array($peer_id, $all_valid) || + !in_array($peer_id, $all_exc)) { + $invalid_peer_ids[] = $peer_id; + } + foreach ($reviews as $giver_id => $valid) { + if (!in_array($giver_id, $all_valid) || + !in_array($peer_id, $all_exc)) { + $invalid_giver_ids[] = $giver_id; + } else { + $all_reviews[$peer_id][$giver_id] = $valid; + } + } + } + $invalid_giver_ids = array_unique($invalid_giver_ids); + + $missing_user_ids = array(); + foreach ($all_valid as $user_id) { + // a missing peer is also a missing giver + if (!in_array($user_id, $peer_ids)) { + $missing_user_ids[] = $user_id; + } + } + + $not_returned_ids = array(); + foreach ($all_exc as $user_id) { + if (!in_array($user_id, $all_valid)) { + $not_returned_ids[] = $user_id; + } + } + + return array( + "invalid" => (sizeof($missing_user_ids) || + sizeof($invalid_peer_ids) || + sizeof($invalid_giver_ids)), + "missing_user_ids" => $missing_user_ids, + "not_returned_ids" => $not_returned_ids, + "invalid_peer_ids" => $invalid_peer_ids, + "invalid_giver_ids" => $invalid_giver_ids, + "reviews" => $all_reviews); + } + } + + public function getPeerReviewValues($a_giver_id, $a_peer_id) + { + $peer = null; + foreach ($this->getPeerReviewsByGiver($a_giver_id) as $item) { + if ($item["peer_id"] == $a_peer_id) { + $peer = $item; + } + } + if (!$peer) { + return; + } + $data = $peer["pcomment"]; + if ($data) { + $items = @unserialize($data); + if (!is_array($items)) { + // v1 - pcomment == text + $items = array("text"=>$data); + } + return $items; + } + } + + public function getPeerReviewsByGiver($a_user_id) + { + $ilDB = $this->db; + + $res = array(); + + if ($this->initPeerReviews()) { + $idx = 0; + $set = $ilDB->query("SELECT *" . + " FROM exc_assignment_peer" . + " WHERE giver_id = " . $ilDB->quote($a_user_id, "integer") . + " AND ass_id = " . $ilDB->quote($this->assignment_id, "integer") . + " ORDER BY peer_id"); + while ($row = $ilDB->fetchAssoc($set)) { + $row["seq"] = ++$idx; + $res[] = $row; + } + } + + return $res; + } + + public function getPeerMaskedId($a_giver_id, $a_peer_id) + { + foreach ($this->getPeerReviewsByGiver($a_giver_id) as $idx => $peer) { + if ($peer["peer_id"] == $a_peer_id) { + return $peer["seq"]; + } + } + } + + protected function validatePeerReview(array $a_data) + { + $all_empty = true; + + // see getPeerReviewValues() + $values = null; + $data = $a_data["pcomment"]; + if ($data) { + $values = @unserialize($data); + if (!is_array($values)) { + // v1 - pcomment == text + $values = array("text"=>$data); + } + } + + /* #18491 - values can be empty, text is optional (rating/file values are handled internally in criteria) + if(!$values) + { + return false; + } + */ + + foreach ($this->assignment->getPeerReviewCriteriaCatalogueItems() as $crit) { + $crit_id = $crit->getId() + ? $crit->getId() + : $crit->getType(); + $crit->setPeerReviewContext( + $this->assignment, + $a_data["giver_id"], + $a_data["peer_id"] + ); + if (!$crit->validate($values[$crit_id])) { + return false; + } + if ($crit->hasValue($values[$crit_id])) { + $all_empty = false; + } + } + + return !$all_empty; + } + + public function getPeerReviewsByPeerId($a_user_id, $a_only_valid = false) + { + $ilDB = $this->db; + + $res = array(); + + $idx = 0; + $set = $ilDB->query("SELECT *" . + " FROM exc_assignment_peer" . + " WHERE peer_id = " . $ilDB->quote($a_user_id, "integer") . + " AND ass_id = " . $ilDB->quote($this->assignment_id, "integer") . + " ORDER BY peer_id"); + while ($row = $ilDB->fetchAssoc($set)) { + if (!$a_only_valid || + $this->validatePeerReview($row)) { + // this would be correct but rather senseless + // $row["seq"] = $this->getPeerMaskedId($row["giver_id"], $a_user_id); + $row["seq"] = ++$idx; + $res[] = $row; + } + } + + return $res; + } + + public function getAllPeerReviews($a_only_valid = true) + { + $ilDB = $this->db; + + $res = array(); - $set = $ilDB->query("SELECT *". - " FROM exc_assignment_peer". - " WHERE ass_id = ".$ilDB->quote($this->assignment_id, "integer"). - " ORDER BY peer_id"); - while($row = $ilDB->fetchAssoc($set)) - { - $valid = $this->validatePeerReview($row); - if(!$a_only_valid || - $valid) - { - $res[$row["peer_id"]][$row["giver_id"]] = $valid; - } - } - - return $res; - } - - public function hasPeerReviewAccess($a_peer_id) - { - $ilDB = $this->db; - $ilUser = $this->user; - - $set = $ilDB->query("SELECT ass_id". - " FROM exc_assignment_peer". - " WHERE giver_id = ".$ilDB->quote($ilUser->getId(), "integer"). - " AND peer_id = ".$ilDB->quote($a_peer_id, "integer"). - " AND ass_id = ".$ilDB->quote($this->assignment_id, "integer")); - $row = $ilDB->fetchAssoc($set); - return (bool)$row["ass_id"]; - } - - public function updatePeerReviewTimestamp($a_peer_id) - { - $ilDB = $this->db; - $ilUser = $this->user; - - $ilDB->manipulate("UPDATE exc_assignment_peer". - " SET tstamp = ".$ilDB->quote(ilUtil::now(), "timestamp"). - " WHERE giver_id = ".$ilDB->quote($ilUser->getId(), "integer"). - " AND peer_id = ".$ilDB->quote($a_peer_id, "integer"). - " AND ass_id = ".$ilDB->quote($this->assignment_id, "integer")); - } - - public function updatePeerReview($a_peer_id, array $a_values) - { - $ilDB = $this->db; - $ilUser = $this->user; - - $sql = "UPDATE exc_assignment_peer". - " SET tstamp = ".$ilDB->quote(ilUtil::now(), "timestamp"). - ",pcomment = ".$ilDB->quote(serialize($a_values), "text"). - " WHERE giver_id = ".$ilDB->quote($ilUser->getId(), "integer"). - " AND peer_id = ".$ilDB->quote($a_peer_id, "integer"). - " AND ass_id = ".$ilDB->quote($this->assignment_id, "integer"); - - $ilDB->manipulate($sql); - } - - public function countGivenFeedback($a_validate = true, $a_user_id = null) - { - $ilDB = $this->db; - $ilUser = $this->user; - - if(!$a_user_id) - { - $a_user_id = $ilUser->getId(); - } - - $cnt = 0; - - include_once './Services/Rating/classes/class.ilRating.php'; - - $set = $ilDB->query("SELECT *". - " FROM exc_assignment_peer". - " WHERE ass_id = ".$ilDB->quote($this->assignment_id, "integer"). - " AND giver_id = ".$ilDB->quote($a_user_id, "integer")); - while($row = $ilDB->fetchAssoc($set)) - { - if(!(bool)$a_validate || - $this->validatePeerReview($row)) - { - $cnt++; - } - } - - return $cnt; - } - - protected function getMaxPossibleFeedbacks() - { - $ilDB = $this->db; - - // check if number of returned assignments is lower than assignment peer min - $set = $ilDB->query("SELECT COUNT(DISTINCT(user_id)) cnt". - " FROM exc_returned". - " WHERE ass_id = ".$ilDB->quote($this->assignment_id, "integer")); - $cnt = $ilDB->fetchAssoc($set); - $cnt = (int)$cnt["cnt"]; - return $cnt-1; - } - - public function getNumberOfMissingFeedbacksForReceived() - { - $max = $this->getMaxPossibleFeedbacks(); - - // #16160 - forever alone - if(!$max) - { - return; - } - - // are all required or just 1? - if(!$this->assignment->getPeerReviewSimpleUnlock()) - { - $needed = $this->assignment->getPeerReviewMin(); - } - else - { - $needed = 1; - } - - // there could be less participants than stated in the min required setting - $min = min($max, $needed); - - return max(0, $min-$this->countGivenFeedback()); - } - - public function isFeedbackValidForPassed($a_user_id) - { - // peer feedback is not required for passing - if($this->assignment->getPeerReviewValid() == ilExAssignment::PEER_REVIEW_VALID_NONE) - { - return true; - } - - // #16227 - no processing before reaching the peer review period - if(!$this->assignment->afterDeadlineStrict()) - { - return false; - } - - // forever alone - should be valid - $max = $this->getMaxPossibleFeedbacks(); - if(!$max) - { - return true; - } - - $no_of_feedbacks = $this->countGivenFeedback(true, $a_user_id); - - switch($this->assignment->getPeerReviewValid()) - { - case ilExAssignment::PEER_REVIEW_VALID_ONE: - return (bool)$no_of_feedbacks; - - case ilExAssignment::PEER_REVIEW_VALID_ALL: - // there could be less participants than stated in the min required setting - $min = min($max, $this->assignment->getPeerReviewMin()); - - return (($min-$no_of_feedbacks) < 1); - } - } + $set = $ilDB->query("SELECT *" . + " FROM exc_assignment_peer" . + " WHERE ass_id = " . $ilDB->quote($this->assignment_id, "integer") . + " ORDER BY peer_id"); + while ($row = $ilDB->fetchAssoc($set)) { + $valid = $this->validatePeerReview($row); + if (!$a_only_valid || + $valid) { + $res[$row["peer_id"]][$row["giver_id"]] = $valid; + } + } + + return $res; + } + + public function hasPeerReviewAccess($a_peer_id) + { + $ilDB = $this->db; + $ilUser = $this->user; + + $set = $ilDB->query("SELECT ass_id" . + " FROM exc_assignment_peer" . + " WHERE giver_id = " . $ilDB->quote($ilUser->getId(), "integer") . + " AND peer_id = " . $ilDB->quote($a_peer_id, "integer") . + " AND ass_id = " . $ilDB->quote($this->assignment_id, "integer")); + $row = $ilDB->fetchAssoc($set); + return (bool) $row["ass_id"]; + } + + public function updatePeerReviewTimestamp($a_peer_id) + { + $ilDB = $this->db; + $ilUser = $this->user; + + $ilDB->manipulate("UPDATE exc_assignment_peer" . + " SET tstamp = " . $ilDB->quote(ilUtil::now(), "timestamp") . + " WHERE giver_id = " . $ilDB->quote($ilUser->getId(), "integer") . + " AND peer_id = " . $ilDB->quote($a_peer_id, "integer") . + " AND ass_id = " . $ilDB->quote($this->assignment_id, "integer")); + } + + public function updatePeerReview($a_peer_id, array $a_values) + { + $ilDB = $this->db; + $ilUser = $this->user; + + $sql = "UPDATE exc_assignment_peer" . + " SET tstamp = " . $ilDB->quote(ilUtil::now(), "timestamp") . + ",pcomment = " . $ilDB->quote(serialize($a_values), "text") . + " WHERE giver_id = " . $ilDB->quote($ilUser->getId(), "integer") . + " AND peer_id = " . $ilDB->quote($a_peer_id, "integer") . + " AND ass_id = " . $ilDB->quote($this->assignment_id, "integer"); + + $ilDB->manipulate($sql); + } + + public function countGivenFeedback($a_validate = true, $a_user_id = null) + { + $ilDB = $this->db; + $ilUser = $this->user; + + if (!$a_user_id) { + $a_user_id = $ilUser->getId(); + } + + $cnt = 0; + + include_once './Services/Rating/classes/class.ilRating.php'; + + $set = $ilDB->query("SELECT *" . + " FROM exc_assignment_peer" . + " WHERE ass_id = " . $ilDB->quote($this->assignment_id, "integer") . + " AND giver_id = " . $ilDB->quote($a_user_id, "integer")); + while ($row = $ilDB->fetchAssoc($set)) { + if (!(bool) $a_validate || + $this->validatePeerReview($row)) { + $cnt++; + } + } + + return $cnt; + } + + protected function getMaxPossibleFeedbacks() + { + $ilDB = $this->db; + + // check if number of returned assignments is lower than assignment peer min + $set = $ilDB->query("SELECT COUNT(DISTINCT(user_id)) cnt" . + " FROM exc_returned" . + " WHERE ass_id = " . $ilDB->quote($this->assignment_id, "integer")); + $cnt = $ilDB->fetchAssoc($set); + $cnt = (int) $cnt["cnt"]; + return $cnt-1; + } + + public function getNumberOfMissingFeedbacksForReceived() + { + $max = $this->getMaxPossibleFeedbacks(); + + // #16160 - forever alone + if (!$max) { + return; + } + + // are all required or just 1? + if (!$this->assignment->getPeerReviewSimpleUnlock()) { + $needed = $this->assignment->getPeerReviewMin(); + } else { + $needed = 1; + } + + // there could be less participants than stated in the min required setting + $min = min($max, $needed); + + return max(0, $min-$this->countGivenFeedback()); + } + + public function isFeedbackValidForPassed($a_user_id) + { + // peer feedback is not required for passing + if ($this->assignment->getPeerReviewValid() == ilExAssignment::PEER_REVIEW_VALID_NONE) { + return true; + } + + // #16227 - no processing before reaching the peer review period + if (!$this->assignment->afterDeadlineStrict()) { + return false; + } + + // forever alone - should be valid + $max = $this->getMaxPossibleFeedbacks(); + if (!$max) { + return true; + } + + $no_of_feedbacks = $this->countGivenFeedback(true, $a_user_id); + + switch ($this->assignment->getPeerReviewValid()) { + case ilExAssignment::PEER_REVIEW_VALID_ONE: + return (bool) $no_of_feedbacks; + + case ilExAssignment::PEER_REVIEW_VALID_ALL: + // there could be less participants than stated in the min required setting + $min = min($max, $this->assignment->getPeerReviewMin()); + + return (($min-$no_of_feedbacks) < 1); + } + } - static function lookupGiversWithPendingFeedback($a_ass_id) - { - global $DIC; + public static function lookupGiversWithPendingFeedback($a_ass_id) + { + global $DIC; - $ilDB = $DIC->database(); - $user_ids = array(); + $ilDB = $DIC->database(); + $user_ids = array(); - $set = $ilDB->query("SELECT DISTINCT(giver_id) FROM exc_assignment_peer ". - " WHERE ass_id = ".$ilDB->quote($a_ass_id, "integer"). - " AND tstamp is NULL" - ); + $set = $ilDB->query( + "SELECT DISTINCT(giver_id) FROM exc_assignment_peer " . + " WHERE ass_id = " . $ilDB->quote($a_ass_id, "integer") . + " AND tstamp is NULL" + ); - while($row = $ilDB->fetchAssoc($set)) - { - array_push($user_ids, $row["giver_id"]); - } + while ($row = $ilDB->fetchAssoc($set)) { + array_push($user_ids, $row["giver_id"]); + } - return $user_ids; - } + return $user_ids; + } } diff --git a/Modules/Exercise/classes/class.ilExPeerReviewGUI.php b/Modules/Exercise/classes/class.ilExPeerReviewGUI.php index 62bd3cc3fedae870310d0db4b8fa61d0c852c926..70fc317e0a953434d015f220d09598a1f36fc5af 100644 --- a/Modules/Exercise/classes/class.ilExPeerReviewGUI.php +++ b/Modules/Exercise/classes/class.ilExPeerReviewGUI.php @@ -5,909 +5,850 @@ * Class ilExPeerReviewGUI * * @author Jörg Lützenkirchen -* +* * @ilCtrl_Calls ilExPeerReviewGUI: ilFileSystemGUI, ilRatingGUI, ilExSubmissionTextGUI, ilInfoScreenGUI -* +* * @ingroup ModulesExercise */ class ilExPeerReviewGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTabsGUI - */ - protected $tabs_gui; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilObjUser - */ - protected $user; - - protected $ass; // [ilExAssignment] - protected $submission; // [ilExSubmission] - - /** - * Constructor - * - * @param ilExAssignment $a_ass - * @param ilExSubmission $a_sub - * @return object - */ - public function __construct(ilExAssignment $a_ass, ilExSubmission $a_submission = null) - { - global $DIC; - - $this->user = $DIC->user(); - $ilCtrl = $DIC->ctrl(); - $ilTabs = $DIC->tabs(); - $lng = $DIC->language(); - $tpl = $DIC["tpl"]; - - $this->ass = $a_ass; - $this->submission = $a_submission; - - // :TODO: - $this->ctrl = $ilCtrl; - $this->tabs_gui = $ilTabs; - $this->lng = $lng; - $this->tpl = $tpl; - } - - public function executeCommand() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilTabs = $this->tabs_gui; - $ilUser = $this->user; - - if(!$this->ass->getPeerReview()) - { - $this->returnToParentObject(); - } - - $class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd("showpeerreviewoverview"); - - switch($class) - { - case "ilfilesystemgui": - $ilCtrl->saveParameter($this, array("fu")); - - // see self::downloadPeerReview() - $parts = explode("__", $_GET["fu"]); - $giver_id = $parts[0]; - $peer_id = $parts[1]; - - if(!$this->canGive()) - { - $this->returnToParentObject(); - } - - $valid = false; - $peer_items = $this->submission->getPeerReview()->getPeerReviewsByPeerId($peer_id, true); - if(sizeof($peer_items)) - { - foreach($peer_items as $item) - { - if($item["giver_id"] == $giver_id) - { - $valid = true; - } - } - } - if(!$valid) - { - $ilCtrl->redirect($this, "editPeerReview"); - } - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTarget($this, "editPeerReview")); - - include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); - $fstorage = new ilFSStorageExercise($this->ass->getExerciseId(), $this->ass->getId()); - $fstorage->create(); - - include_once("./Services/FileSystem/classes/class.ilFileSystemGUI.php"); - $fs_gui = new ilFileSystemGUI($fstorage->getPeerReviewUploadPath($peer_id, $giver_id)); - $fs_gui->setTableId("excfbpeer"); - $fs_gui->setAllowDirectories(false); - $fs_gui->setTitle($this->ass->getTitle().": ". - $lng->txt("exc_peer_review")." - ". - $lng->txt("exc_peer_review_give")); - $ret = $this->ctrl->forwardCommand($fs_gui); - break; - - case "ilratinggui": - $this->ass->updatePeerReviewTimestamp((int)$_REQUEST["peer_id"]); - - include_once("./Services/Rating/classes/class.ilRatingGUI.php"); - $rating_gui = new ilRatingGUI(); - $rating_gui->setObject($this->ass->getId(), "ass", - (int)$_REQUEST["peer_id"], "peer"); - $this->ctrl->forwardCommand($rating_gui); - $ilCtrl->redirect($this, "editPeerReview"); - break; - - case "ilexsubmissiontextgui": - if(!$this->submission->isTutor()) - { - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTarget($this, "editPeerReview")); - $this->ctrl->setReturn($this, "editPeerReview"); - } - else - { - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTarget($this, "showGivenPeerReview")); - $this->ctrl->setReturn($this, "showGivenPeerReview"); - } - include_once "Modules/Exercise/classes/class.ilExSubmissionTextGUI.php"; - $gui = new ilExSubmissionTextGUI(new ilObjExercise($this->ass->getExerciseId(), false), $this->submission); - $ilCtrl->forwardCommand($gui); - break; - - default: - $this->{$cmd."Object"}(); - break; - } - } - - function returnToParentObject() - { - $this->ctrl->returnToParent($this); - } - - public static function getOverviewContent(ilInfoScreenGUI $a_info, ilExSubmission $a_submission) - { - global $DIC; - - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - - include_once("./Modules/Exercise/classes/class.ilExcAssMemberState.php"); - $state = ilExcAssMemberState::getInstanceByIds($a_submission->getAssignment()->getId(), $a_submission->getUserId()); - - $ass = $a_submission->getAssignment(); - - - - - //if($ass->afterDeadlineStrict() && - // $ass->getPeerReview()) - if($state->hasSubmissionEndedForAllUsers() && - $ass->getPeerReview()) - { - $ilCtrl->setParameterByClass("ilExPeerReviewGUI", "ass_id", $a_submission->getAssignment()->getId()); - - $nr_missing_fb = $a_submission->getPeerReview()->getNumberOfMissingFeedbacksForReceived(); - - // before deadline (if any) - // if(!$ass->getPeerReviewDeadline() || - // $ass->getPeerReviewDeadline() > time()) - if($state->isPeerReviewAllowed()) - { - $dl_info = ""; - if($ass->getPeerReviewDeadline()) - { - $dl_info = " (".sprintf($lng->txt("exc_peer_review_deadline_info_button"), - $state->getPeerReviewDeadlinePresentation()).")"; - } - - $button = ilLinkButton::getInstance(); // edit peer review - $button->setPrimary($nr_missing_fb); - $button->setCaption($lng->txt("exc_peer_review_give").$dl_info, false); - $button->setUrl($ilCtrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExPeerReviewGUI"), "editPeerReview")); - $edit_pc = $button->render(); - } - else if($ass->getPeerReviewDeadline()) - { - $edit_pc = $lng->txt("exc_peer_review_deadline_reached"); - } - - // after deadline (if any) - if((!$ass->getPeerReviewDeadline() || - $ass->getPeerReviewDeadline() < time())) - { - // given peer review should be accessible at all times (read-only when not editable - see above) - if($ass->getPeerReviewDeadline() && - $a_submission->getPeerReview()->countGivenFeedback(false)) - { - $button = ilLinkButton::getInstance(); - $button->setCaption("exc_peer_review_given"); - $button->setUrl($ilCtrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExPeerReviewGUI"), "showGivenPeerReview")); - $view_pc = $button->render()." "; - } - - // did give enough feedback - if(!$nr_missing_fb) - { - // received any? - $received = (bool)sizeof($a_submission->getPeerReview()->getPeerReviewsByPeerId($a_submission->getUserId(), true)); - if($received) - { - $button = ilLinkButton::getInstance(); - $button->setCaption("exc_peer_review_show"); - $button->setUrl($ilCtrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExPeerReviewGUI"), "showReceivedPeerReview")); - $view_pc .= $button->render(); - } - // received none - else - { - $view_pc .= $lng->txt("exc_peer_review_show_received_none"); - } - } - // did not give enough - else - { - $view_pc .= $lng->txt("exc_peer_review_show_missing"); - } - } - /* must give before showing received - else - { - $view_pc = $lng->txt("exc_peer_review_show_not_rated_yet"); - } - */ - - $sep = ($edit_pc != "" && $view_pc != "") - ? "

" - : ""; - - $a_info->addProperty($lng->txt("exc_peer_review"), $edit_pc.$sep.$view_pc); - - $ilCtrl->setParameterByClass("ilExPeerReviewGUI", "ass_id", ""); - } - } - - protected function canGive() - { - return ($this->submission->isOwner() && - $this->ass->afterDeadlineStrict() && - (!$this->ass->getPeerReviewDeadline() || - $this->ass->getPeerReviewDeadline() > time())); - } - - protected function canView() - { - return ($this->submission->isTutor() || - ($this->submission->isOwner() && - $this->ass->afterDeadlineStrict() && - (!$this->ass->getPeerReviewDeadline() || - $this->ass->getPeerReviewDeadline() < time()))); - } - - function showGivenPeerReviewObject() - { - $tpl = $this->tpl; - $lng = $this->lng; - - if(!$this->canView()) - { - $this->returnToParentObject(); - } - - $peer_items = $this->submission->getPeerReview()->getPeerReviewsByGiver($this->submission->getUserId()); - if(!sizeof($peer_items)) - { - ilUtil::sendFailure($this->lng->txt("exc_peer_review_no_peers"), true); - $this->returnToParentObject(); - } - - $tpl->setTitle($this->ass->getTitle().": ".$lng->txt("exc_peer_review_given")); - - include_once "Services/InfoScreen/classes/class.ilInfoScreenGUI.php"; - $info_widget = new ilInfoScreenGUI($this); - - $this->renderInfoWidget($info_widget, $peer_items); - - $tpl->setContent($info_widget->getHTML()); - } - - function showReceivedPeerReviewObject() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - if(!$this->canView() || - (!$this->submission->isTutor() && - $this->submission->getPeerReview()->getNumberOfMissingFeedbacksForReceived())) - { - $this->returnToParentObject(); - } - - $this->tabs_gui->clearTargets(); - $this->tabs_gui->setBackTarget($this->lng->txt("back"), $this->ctrl->getLinkTarget($this, "returnToParent")); - - $peer_items = $this->submission->getPeerReview()->getPeerReviewsByPeerId($this->submission->getUserId(), !$this->submission->isTutor()); - if(!sizeof($peer_items)) - { - // #11373 - ilUtil::sendFailure($this->lng->txt("exc_peer_review_no_peers_reviewed_yet"), true); - $ilCtrl->redirect($this, "returnToParent"); - } - - $tpl->setTitle($this->ass->getTitle().": ".$lng->txt("exc_peer_review_show")); - - include_once "Services/InfoScreen/classes/class.ilInfoScreenGUI.php"; - $info_widget = new ilInfoScreenGUI($this); - - $this->renderInfoWidget($info_widget, $peer_items, true); - - $tpl->setContent($info_widget->getHTML()); - } - - protected function renderInfoWidget(ilInfoScreenGUI $a_info_widget, array $a_peer_items, $a_by_peer = false) - { - $lng = $this->lng; - - include_once "Services/User/classes/class.ilUserUtil.php"; - - if($this->submission->isTutor()) - { - $user_title = $a_by_peer - ? $lng->txt("exc_peer_review_recipient") - : $lng->txt("exc_peer_review_giver"); - $a_info_widget->addSection($user_title); - $a_info_widget->addProperty($lng->txt("name"), - ilUserUtil::getNamePresentation($this->submission->getUserId(), false, false, "", true)); - } - - if($a_by_peer) - { - // submission - - $a_info_widget->addSection($lng->txt("exc_submission")); - - $submission = new ilExSubmission($this->ass, $this->submission->getUserId()); - $file_info = $submission->getDownloadedFilesInfoForTableGUIS($this, "showReceivedPeerReview"); - - $a_info_widget->addProperty($file_info["last_submission"]["txt"], - $file_info["last_submission"]["value"]. - $this->getLateSubmissionInfo($submission)); - - $sub_data = $this->getSubmissionContent($submission); - if(!$sub_data) - { - $sub_data = ''.$lng->txt("download").''; - } - $a_info_widget->addProperty($lng->txt("exc_submission"), $sub_data); - } - - foreach($a_peer_items as $peer) - { - if(!$a_by_peer) - { - $giver_id = $this->submission->getUserId(); - $peer_id = $peer["peer_id"]; - $id_title = $lng->txt("exc_peer_review_recipient"); - $user_id = $peer_id; - } - else - { - $giver_id = $peer["giver_id"]; - $peer_id = $this->submission->getUserId(); - $id_title = $lng->txt("exc_peer_review_giver"); - $user_id = $giver_id; - } - - // peer info - if($this->submission->isTutor()) - { - $id_value = ilUserUtil::getNamePresentation($user_id, "", "", false, true); - } - else if(!$this->ass->hasPeerReviewPersonalized()) - { - $id_value = $peer["seq"]; - } - else - { - $id_value = ilUserUtil::getNamePresentation($user_id); - } - $a_info_widget->addSection($id_title.": ".$id_value); - - - // submission info - - if(!$a_by_peer) - { - $submission = new ilExSubmission($this->ass, $peer_id); - $file_info = $submission->getDownloadedFilesInfoForTableGUIS($this, "editPeerReviewItem"); - - $a_info_widget->addProperty($file_info["last_submission"]["txt"], - $file_info["last_submission"]["value"]. - $this->getLateSubmissionInfo($submission)); - - $sub_data = $this->getSubmissionContent($submission); - if(!$sub_data) - { - $sub_data = ''.$lng->txt("download").''; - } - $a_info_widget->addProperty($lng->txt("exc_submission"), $sub_data); - } - - - // peer review items - - $values = $this->submission->getPeerReview()->getPeerReviewValues($giver_id, $peer_id); - - foreach($this->ass->getPeerReviewCriteriaCatalogueItems() as $item) - { - $crit_id = $item->getId() - ? $item->getId() - : $item->getType(); - - $item->setPeerReviewContext( - $this->ass, - $giver_id, - $peer_id - ); - - $title = $item->getTitle(); - $html = $item->getHTML($values[$crit_id]); - $a_info_widget->addProperty($title ? $title : " ", $html ? $html : " "); - } - } - } - - protected function getLateSubmissionInfo(ilExSubmission $a_submission) - { - $lng = $this->lng; - - // #18966 - late files info - foreach($a_submission->getFiles() as $file) - { - if($file["late"]) - { - return '
'.$lng->txt("exc_late_submission").'
'; - } - } - } - - function editPeerReviewObject() - { - $tpl = $this->tpl; - - if(!$this->canGive()) - { - $this->returnToParentObject(); - } - - $peer_items = $this->submission->getPeerReview()->getPeerReviewsByGiver($this->submission->getUserId()); - if(!sizeof($peer_items)) - { - ilUtil::sendFailure($this->lng->txt("exc_peer_review_no_peers"), true); - $this->returnToParentObject(); - } - - $missing = $this->submission->getPeerReview()->getNumberOfMissingFeedbacksForReceived(); - if($missing) - { - $dl = $this->ass->getPeerReviewDeadline(); - if(!$dl || $dl < time()) - { - ilUtil::sendInfo(sprintf($this->lng->txt("exc_peer_review_missing_info"), $missing)); - } - else - { - ilUtil::sendInfo(sprintf($this->lng->txt("exc_peer_review_missing_info_deadline"), $missing, - ilDatePresentation::formatDate(new ilDateTime($dl, IL_CAL_UNIX)))); - } - } - - include_once "Modules/Exercise/classes/class.ilExAssignmentPeerReviewTableGUI.php"; - $tbl = new ilExAssignmentPeerReviewTableGUI($this, "editPeerReview", $this->ass, $this->submission->getUserId(), - $peer_items, "returnToParent"); - $tpl->setContent($tbl->getHTML()); - } - - function editPeerReviewItemObject(ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - - if(!$this->canGive() || - !$this->isValidPeer($_GET["peer_id"])) - { - $this->returnToParentObject(); - } - - if(!$a_form) - { - $a_form = $this->initPeerReviewItemForm($_GET["peer_id"]); - } - - $tpl->setContent($a_form->getHTML()); - } - - protected function isValidPeer($a_peer_id) - { - $peer_items = $this->submission->getPeerReview()->getPeerReviewsByGiver($this->submission->getUserId()); - foreach($peer_items as $item) - { - if($item["peer_id"] == $a_peer_id) - { - return true; - } - } - return false; - } - - protected function getSubmissionContent(ilExSubmission $a_submission) - { - if($this->ass->getType() != ilExAssignment::TYPE_TEXT) - { - return; - } - - $text = $a_submission->getFiles(); - if($text) - { - $text = array_shift($text); - if(trim($text["atext"])) - { - // mob id to mob src - include_once "Services/RTE/classes/class.ilRTE.php"; - return nl2br(ilRTE::_replaceMediaObjectImageSrc($text["atext"], 1)); - } - } - } - - protected function initPeerReviewItemForm($a_peer_id) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - // get peer data - $peer_items = $this->submission->getPeerReview()->getPeerReviewsByGiver($this->submission->getUserId()); - foreach($peer_items as $item) - { - if($item["peer_id"] == $a_peer_id) - { - $peer = $item; - break; - } - } - - $ilCtrl->saveParameter($this, "peer_id"); - - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this, "updatePeerReview")); - - $form->setTitle($this->ass->getTitle().": ".$lng->txt("exc_peer_review_give")); - - // peer info - if(!$this->ass->hasPeerReviewPersonalized()) - { - $id_title = $lng->txt("id"); - $id_value = $peer["seq"]; - } - else - { - include_once "Services/User/classes/class.ilUserUtil.php"; - $id_title = $lng->txt("exc_peer_review_recipient"); - $id_value = ilUserUtil::getNamePresentation($peer["peer_id"]); - } - $id = new ilNonEditableValueGUI($id_title); - $id->setValue($id_value); - $form->addItem($id); - - // submission info - - $submission = new ilExSubmission($this->ass, $peer["peer_id"]); - $file_info = $submission->getDownloadedFilesInfoForTableGUIS($this, "editPeerReviewItem"); - - $last_sub = new ilNonEditableValueGUI($file_info["last_submission"]["txt"], "", true); - $last_sub->setValue($file_info["last_submission"]["value"]. - $this->getLateSubmissionInfo($submission)); - $form->addItem($last_sub); - - $sub_data = $this->getSubmissionContent($submission); - if(!$sub_data) - { - $sub_data = ''.$lng->txt("download").''; - } - - $sub = new ilNonEditableValueGUI($lng->txt("exc_submission"), "", true); - $sub->setValue($sub_data); - $form->addItem($sub); - - // peer review items - - $input = new ilFormSectionHeaderGUI(); - $input->setTitle($lng->txt("exc_peer_review")); - $form->addItem($input); - - $values = $this->submission->getPeerReview()->getPeerReviewValues($this->submission->getUserId(), $a_peer_id); - - foreach($this->ass->getPeerReviewCriteriaCatalogueItems() as $item) - { - $crit_id = $item->getId() - ? $item->getId() - : $item->getType(); - - $item->setPeerReviewContext( - $this->ass, - $this->submission->getUserId(), - $peer["peer_id"], - $form - ); - $item->addToPeerReviewForm($values[$crit_id]); - } - - $form->addCommandButton("updatePeerReview", $lng->txt("save")); - $form->addCommandButton("editPeerReview", $lng->txt("cancel")); - - return $form; - } - - function updateCritAjaxObject() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - $tpl = $this->tpl; - - if(!$this->canGive() || - !$_POST["peer_id"] || - !$_POST["crit_id"] || - !$ilCtrl->isAsynch()) - { - exit(); - } - - $peer_id = (int)$_POST["peer_id"]; - $crit_id = $_POST["crit_id"]; - $giver_id = $ilUser->getId(); - - include_once "Modules/Exercise/classes/class.ilExcCriteria.php"; - if(!is_numeric($crit_id)) - { - $crit = ilExcCriteria::getInstanceByType($crit_id); - } - else - { - $crit = ilExcCriteria::getInstanceById($crit_id); - } - $crit->setPeerReviewContext($this->ass, $giver_id, $peer_id); - $html = $crit->updateFromAjax(); - - $this->handlePeerReviewChange(); - - echo $html; - echo $tpl->getOnLoadCodeForAsynch(); - exit(); - } - - function updatePeerReviewObject() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if(!$this->canGive() || - !$this->isValidPeer($_REQUEST["peer_id"])) - { - $this->returnToParentObject(); - } - - $peer_id = $_REQUEST["peer_id"]; - - $form = $this->initPeerReviewItemForm($peer_id); - if($form->checkInput()) - { - $valid = true; - - $values = array(); - foreach($this->ass->getPeerReviewCriteriaCatalogueItems() as $item) - { - $item->setPeerReviewContext( - $this->ass, - $this->submission->getUserId(), - $peer_id, - $form - ); - $value = $item->importFromPeerReviewForm(); - if($value !== null) - { - $crit_id = $item->getId() - ? $item->getId() - : $item->getType(); - $values[$crit_id] = $value; - } - if(!$item->validate($value)) - { - $valid = false; - } - } - - if($valid) - { - $this->submission->getPeerReview()->updatePeerReview($peer_id, $values); - - $this->handlePeerReviewChange(); - - ilUtil::sendSuccess($this->lng->txt("exc_peer_review_updated"), true); - $ilCtrl->redirect($this, "editPeerReview"); - } - else - { - ilUtil::sendFailure($lng->txt("form_input_not_valid")); - } - } - - $form->setValuesByPost(); - $this->editPeerReviewItemObject($form); - } - - protected function handlePeerReviewChange() - { - // (in)valid peer reviews could change assignment status - $exercise = new ilObjExercise($this->ass->getExerciseId(), false); - $exercise->processExerciseStatus($this->ass, - $this->submission->getUserIds(), - $this->submission->hasSubmitted(), - $this->submission->validatePeerReviews() - ); - } - - function downloadPeerReviewObject() - { - $ilCtrl = $this->ctrl; - - if(!$this->canView() && - !$this->canGive()) - { - $this->returnToParentObject(); - } - - $parts = explode("__", $_GET["fu"]); - $giver_id = $parts[0]; - $peer_id = $parts[1]; - $crit_id = $parts[2]; - - include_once "Modules/Exercise/classes/class.ilExcCriteria.php"; - if(!is_numeric($crit_id)) - { - $crit = ilExcCriteria::getInstanceByType($crit_id); - } - else - { - $crit = ilExcCriteria::getInstanceById($crit_id); - } - - $crit->setPeerReviewContext($this->ass, $giver_id, $peer_id); - $file = $crit->getFileByHash(); - if($file) - { - ilUtil::deliverFile($file, basename($file)); - } - - $ilCtrl->redirect($this, "returnToParent"); - } - - - - // - // ADMIN - // - - public function showPeerReviewOverviewObject() - { - $tpl = $this->tpl; - - if(!$this->ass || - !$this->ass->getPeerReview()) - { - $this->returnToParentObject(); - } - - include_once "Modules/Exercise/classes/class.ilExAssignmentPeerReviewOverviewTableGUI.php"; - $tbl = new ilExAssignmentPeerReviewOverviewTableGUI($this, "showPeerReviewOverview", - $this->ass); - - $panel = ""; - $panel_data = $tbl->getPanelInfo(); - if(sizeof($panel_data)) - { - $ptpl = new ilTemplate("tpl.exc_peer_review_overview_panel.html", true, true, "Modules/Exercise"); - foreach($panel_data as $item) - { - $ptpl->setCurrentBlock("user_bl"); - foreach($item["value"] as $user) - { - $ptpl->setVariable("USER", $user); - $ptpl->parseCurrentBlock(); - } - - $ptpl->setCurrentBlock("item_bl"); - $ptpl->setVariable("TITLE", $item["title"]); - $ptpl->parseCurrentBlock(); - } - - include_once "Services/UIComponent/Panel/classes/class.ilPanelGUI.php"; - $panel = ilPanelGUI::getInstance(); - $panel->setHeading($this->lng->txt("exc_peer_review_overview_invalid_users")); - $panel->setBody($ptpl->get()); - $panel = $panel->getHTML(); - } - - $tpl->setContent($tbl->getHTML().$panel); - } - - public function confirmResetPeerReviewObject() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $ilTabs = $this->tabs_gui; - - if(!$this->ass || - !$this->ass->getPeerReview()) - { - $this->returnToParentObject(); - } - - $ilTabs->clearTargets(); - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText(sprintf($this->lng->txt("exc_peer_review_reset_sure"), $this->ass->getTitle())); - $cgui->setCancel($this->lng->txt("cancel"), "showPeerReviewOverview"); - $cgui->setConfirm($this->lng->txt("delete"), "resetPeerReview"); - - $tpl->setContent($cgui->getHTML()); - } - - public function resetPeerReviewObject() - { - $ilCtrl = $this->ctrl; - - if(!$this->ass || - !$this->ass->getPeerReview()) - { - $this->returnToParentObject(); - } - - include_once "Modules/Exercise/classes/class.ilExPeerReview.php"; - $peer_review = new ilExPeerReview($this->ass); - $all_giver_ids = $peer_review->resetPeerReviews(); - - if(is_array($all_giver_ids)) - { - // if peer review is valid for completion, we have to re-calculate all assignment members - $exercise = new ilObjExercise($this->ass->getExerciseId(), false); - if($exercise->isCompletionBySubmissionEnabled() && - $this->ass->getPeerReviewValid() != ilExAssignment::PEER_REVIEW_VALID_NONE) - { - include_once "Modules/Exercise/classes/class.ilExSubmission.php"; - foreach($all_giver_ids as $user_id) - { - $submission = new ilExSubmission($this->ass, $user_id); - $pgui = new self($this->ass, $submission); - $pgui->handlePeerReviewChange(); - } - } - } - - ilUtil::sendSuccess($this->lng->txt("exc_peer_review_reset_done"), true); - $ilCtrl->redirect($this, "showPeerReviewOverview"); - } - - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTabsGUI + */ + protected $tabs_gui; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilObjUser + */ + protected $user; + + protected $ass; // [ilExAssignment] + protected $submission; // [ilExSubmission] + + /** + * Constructor + * + * @param ilExAssignment $a_ass + * @param ilExSubmission $a_sub + * @return object + */ + public function __construct(ilExAssignment $a_ass, ilExSubmission $a_submission = null) + { + global $DIC; + + $this->user = $DIC->user(); + $ilCtrl = $DIC->ctrl(); + $ilTabs = $DIC->tabs(); + $lng = $DIC->language(); + $tpl = $DIC["tpl"]; + + $this->ass = $a_ass; + $this->submission = $a_submission; + + // :TODO: + $this->ctrl = $ilCtrl; + $this->tabs_gui = $ilTabs; + $this->lng = $lng; + $this->tpl = $tpl; + } + + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilTabs = $this->tabs_gui; + $ilUser = $this->user; + + if (!$this->ass->getPeerReview()) { + $this->returnToParentObject(); + } + + $class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd("showpeerreviewoverview"); + + switch ($class) { + case "ilfilesystemgui": + $ilCtrl->saveParameter($this, array("fu")); + + // see self::downloadPeerReview() + $parts = explode("__", $_GET["fu"]); + $giver_id = $parts[0]; + $peer_id = $parts[1]; + + if (!$this->canGive()) { + $this->returnToParentObject(); + } + + $valid = false; + $peer_items = $this->submission->getPeerReview()->getPeerReviewsByPeerId($peer_id, true); + if (sizeof($peer_items)) { + foreach ($peer_items as $item) { + if ($item["giver_id"] == $giver_id) { + $valid = true; + } + } + } + if (!$valid) { + $ilCtrl->redirect($this, "editPeerReview"); + } + + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, "editPeerReview") + ); + + include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); + $fstorage = new ilFSStorageExercise($this->ass->getExerciseId(), $this->ass->getId()); + $fstorage->create(); + + include_once("./Services/FileSystem/classes/class.ilFileSystemGUI.php"); + $fs_gui = new ilFileSystemGUI($fstorage->getPeerReviewUploadPath($peer_id, $giver_id)); + $fs_gui->setTableId("excfbpeer"); + $fs_gui->setAllowDirectories(false); + $fs_gui->setTitle($this->ass->getTitle() . ": " . + $lng->txt("exc_peer_review") . " - " . + $lng->txt("exc_peer_review_give")); + $ret = $this->ctrl->forwardCommand($fs_gui); + break; + + case "ilratinggui": + $this->ass->updatePeerReviewTimestamp((int) $_REQUEST["peer_id"]); + + include_once("./Services/Rating/classes/class.ilRatingGUI.php"); + $rating_gui = new ilRatingGUI(); + $rating_gui->setObject( + $this->ass->getId(), + "ass", + (int) $_REQUEST["peer_id"], + "peer" + ); + $this->ctrl->forwardCommand($rating_gui); + $ilCtrl->redirect($this, "editPeerReview"); + break; + + case "ilexsubmissiontextgui": + if (!$this->submission->isTutor()) { + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, "editPeerReview") + ); + $this->ctrl->setReturn($this, "editPeerReview"); + } else { + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, "showGivenPeerReview") + ); + $this->ctrl->setReturn($this, "showGivenPeerReview"); + } + include_once "Modules/Exercise/classes/class.ilExSubmissionTextGUI.php"; + $gui = new ilExSubmissionTextGUI(new ilObjExercise($this->ass->getExerciseId(), false), $this->submission); + $ilCtrl->forwardCommand($gui); + break; + + default: + $this->{$cmd . "Object"}(); + break; + } + } + + public function returnToParentObject() + { + $this->ctrl->returnToParent($this); + } + + public static function getOverviewContent(ilInfoScreenGUI $a_info, ilExSubmission $a_submission) + { + global $DIC; + + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + + include_once("./Modules/Exercise/classes/class.ilExcAssMemberState.php"); + $state = ilExcAssMemberState::getInstanceByIds($a_submission->getAssignment()->getId(), $a_submission->getUserId()); + + $ass = $a_submission->getAssignment(); + + + + + //if($ass->afterDeadlineStrict() && + // $ass->getPeerReview()) + if ($state->hasSubmissionEndedForAllUsers() && + $ass->getPeerReview()) { + $ilCtrl->setParameterByClass("ilExPeerReviewGUI", "ass_id", $a_submission->getAssignment()->getId()); + + $nr_missing_fb = $a_submission->getPeerReview()->getNumberOfMissingFeedbacksForReceived(); + + // before deadline (if any) + // if(!$ass->getPeerReviewDeadline() || + // $ass->getPeerReviewDeadline() > time()) + if ($state->isPeerReviewAllowed()) { + $dl_info = ""; + if ($ass->getPeerReviewDeadline()) { + $dl_info = " (" . sprintf( + $lng->txt("exc_peer_review_deadline_info_button"), + $state->getPeerReviewDeadlinePresentation() + ) . ")"; + } + + $button = ilLinkButton::getInstance(); // edit peer review + $button->setPrimary($nr_missing_fb); + $button->setCaption($lng->txt("exc_peer_review_give") . $dl_info, false); + $button->setUrl($ilCtrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExPeerReviewGUI"), "editPeerReview")); + $edit_pc = $button->render(); + } elseif ($ass->getPeerReviewDeadline()) { + $edit_pc = $lng->txt("exc_peer_review_deadline_reached"); + } + + // after deadline (if any) + if ((!$ass->getPeerReviewDeadline() || + $ass->getPeerReviewDeadline() < time())) { + // given peer review should be accessible at all times (read-only when not editable - see above) + if ($ass->getPeerReviewDeadline() && + $a_submission->getPeerReview()->countGivenFeedback(false)) { + $button = ilLinkButton::getInstance(); + $button->setCaption("exc_peer_review_given"); + $button->setUrl($ilCtrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExPeerReviewGUI"), "showGivenPeerReview")); + $view_pc = $button->render() . " "; + } + + // did give enough feedback + if (!$nr_missing_fb) { + // received any? + $received = (bool) sizeof($a_submission->getPeerReview()->getPeerReviewsByPeerId($a_submission->getUserId(), true)); + if ($received) { + $button = ilLinkButton::getInstance(); + $button->setCaption("exc_peer_review_show"); + $button->setUrl($ilCtrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExPeerReviewGUI"), "showReceivedPeerReview")); + $view_pc .= $button->render(); + } + // received none + else { + $view_pc .= $lng->txt("exc_peer_review_show_received_none"); + } + } + // did not give enough + else { + $view_pc .= $lng->txt("exc_peer_review_show_missing"); + } + } + /* must give before showing received + else + { + $view_pc = $lng->txt("exc_peer_review_show_not_rated_yet"); + } + */ + + $sep = ($edit_pc != "" && $view_pc != "") + ? "

" + : ""; + + $a_info->addProperty($lng->txt("exc_peer_review"), $edit_pc . $sep . $view_pc); + + $ilCtrl->setParameterByClass("ilExPeerReviewGUI", "ass_id", ""); + } + } + + protected function canGive() + { + return ($this->submission->isOwner() && + $this->ass->afterDeadlineStrict() && + (!$this->ass->getPeerReviewDeadline() || + $this->ass->getPeerReviewDeadline() > time())); + } + + protected function canView() + { + return ($this->submission->isTutor() || + ($this->submission->isOwner() && + $this->ass->afterDeadlineStrict() && + (!$this->ass->getPeerReviewDeadline() || + $this->ass->getPeerReviewDeadline() < time()))); + } + + public function showGivenPeerReviewObject() + { + $tpl = $this->tpl; + $lng = $this->lng; + + if (!$this->canView()) { + $this->returnToParentObject(); + } + + $peer_items = $this->submission->getPeerReview()->getPeerReviewsByGiver($this->submission->getUserId()); + if (!sizeof($peer_items)) { + ilUtil::sendFailure($this->lng->txt("exc_peer_review_no_peers"), true); + $this->returnToParentObject(); + } + + $tpl->setTitle($this->ass->getTitle() . ": " . $lng->txt("exc_peer_review_given")); + + include_once "Services/InfoScreen/classes/class.ilInfoScreenGUI.php"; + $info_widget = new ilInfoScreenGUI($this); + + $this->renderInfoWidget($info_widget, $peer_items); + + $tpl->setContent($info_widget->getHTML()); + } + + public function showReceivedPeerReviewObject() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + if (!$this->canView() || + (!$this->submission->isTutor() && + $this->submission->getPeerReview()->getNumberOfMissingFeedbacksForReceived())) { + $this->returnToParentObject(); + } + + $this->tabs_gui->clearTargets(); + $this->tabs_gui->setBackTarget($this->lng->txt("back"), $this->ctrl->getLinkTarget($this, "returnToParent")); + + $peer_items = $this->submission->getPeerReview()->getPeerReviewsByPeerId($this->submission->getUserId(), !$this->submission->isTutor()); + if (!sizeof($peer_items)) { + // #11373 + ilUtil::sendFailure($this->lng->txt("exc_peer_review_no_peers_reviewed_yet"), true); + $ilCtrl->redirect($this, "returnToParent"); + } + + $tpl->setTitle($this->ass->getTitle() . ": " . $lng->txt("exc_peer_review_show")); + + include_once "Services/InfoScreen/classes/class.ilInfoScreenGUI.php"; + $info_widget = new ilInfoScreenGUI($this); + + $this->renderInfoWidget($info_widget, $peer_items, true); + + $tpl->setContent($info_widget->getHTML()); + } + + protected function renderInfoWidget(ilInfoScreenGUI $a_info_widget, array $a_peer_items, $a_by_peer = false) + { + $lng = $this->lng; + + include_once "Services/User/classes/class.ilUserUtil.php"; + + if ($this->submission->isTutor()) { + $user_title = $a_by_peer + ? $lng->txt("exc_peer_review_recipient") + : $lng->txt("exc_peer_review_giver"); + $a_info_widget->addSection($user_title); + $a_info_widget->addProperty( + $lng->txt("name"), + ilUserUtil::getNamePresentation($this->submission->getUserId(), false, false, "", true) + ); + } + + if ($a_by_peer) { + // submission + + $a_info_widget->addSection($lng->txt("exc_submission")); + + $submission = new ilExSubmission($this->ass, $this->submission->getUserId()); + $file_info = $submission->getDownloadedFilesInfoForTableGUIS($this, "showReceivedPeerReview"); + + $a_info_widget->addProperty( + $file_info["last_submission"]["txt"], + $file_info["last_submission"]["value"] . + $this->getLateSubmissionInfo($submission) + ); + + $sub_data = $this->getSubmissionContent($submission); + if (!$sub_data) { + $sub_data = '' . $lng->txt("download") . ''; + } + $a_info_widget->addProperty($lng->txt("exc_submission"), $sub_data); + } + + foreach ($a_peer_items as $peer) { + if (!$a_by_peer) { + $giver_id = $this->submission->getUserId(); + $peer_id = $peer["peer_id"]; + $id_title = $lng->txt("exc_peer_review_recipient"); + $user_id = $peer_id; + } else { + $giver_id = $peer["giver_id"]; + $peer_id = $this->submission->getUserId(); + $id_title = $lng->txt("exc_peer_review_giver"); + $user_id = $giver_id; + } + + // peer info + if ($this->submission->isTutor()) { + $id_value = ilUserUtil::getNamePresentation($user_id, "", "", false, true); + } elseif (!$this->ass->hasPeerReviewPersonalized()) { + $id_value = $peer["seq"]; + } else { + $id_value = ilUserUtil::getNamePresentation($user_id); + } + $a_info_widget->addSection($id_title . ": " . $id_value); + + + // submission info + + if (!$a_by_peer) { + $submission = new ilExSubmission($this->ass, $peer_id); + $file_info = $submission->getDownloadedFilesInfoForTableGUIS($this, "editPeerReviewItem"); + + $a_info_widget->addProperty( + $file_info["last_submission"]["txt"], + $file_info["last_submission"]["value"] . + $this->getLateSubmissionInfo($submission) + ); + + $sub_data = $this->getSubmissionContent($submission); + if (!$sub_data) { + $sub_data = '' . $lng->txt("download") . ''; + } + $a_info_widget->addProperty($lng->txt("exc_submission"), $sub_data); + } + + + // peer review items + + $values = $this->submission->getPeerReview()->getPeerReviewValues($giver_id, $peer_id); + + foreach ($this->ass->getPeerReviewCriteriaCatalogueItems() as $item) { + $crit_id = $item->getId() + ? $item->getId() + : $item->getType(); + + $item->setPeerReviewContext( + $this->ass, + $giver_id, + $peer_id + ); + + $title = $item->getTitle(); + $html = $item->getHTML($values[$crit_id]); + $a_info_widget->addProperty($title ? $title : " ", $html ? $html : " "); + } + } + } + + protected function getLateSubmissionInfo(ilExSubmission $a_submission) + { + $lng = $this->lng; + + // #18966 - late files info + foreach ($a_submission->getFiles() as $file) { + if ($file["late"]) { + return '
' . $lng->txt("exc_late_submission") . '
'; + } + } + } + + public function editPeerReviewObject() + { + $tpl = $this->tpl; + + if (!$this->canGive()) { + $this->returnToParentObject(); + } + + $peer_items = $this->submission->getPeerReview()->getPeerReviewsByGiver($this->submission->getUserId()); + if (!sizeof($peer_items)) { + ilUtil::sendFailure($this->lng->txt("exc_peer_review_no_peers"), true); + $this->returnToParentObject(); + } + + $missing = $this->submission->getPeerReview()->getNumberOfMissingFeedbacksForReceived(); + if ($missing) { + $dl = $this->ass->getPeerReviewDeadline(); + if (!$dl || $dl < time()) { + ilUtil::sendInfo(sprintf($this->lng->txt("exc_peer_review_missing_info"), $missing)); + } else { + ilUtil::sendInfo(sprintf( + $this->lng->txt("exc_peer_review_missing_info_deadline"), + $missing, + ilDatePresentation::formatDate(new ilDateTime($dl, IL_CAL_UNIX)) + )); + } + } + + include_once "Modules/Exercise/classes/class.ilExAssignmentPeerReviewTableGUI.php"; + $tbl = new ilExAssignmentPeerReviewTableGUI( + $this, + "editPeerReview", + $this->ass, + $this->submission->getUserId(), + $peer_items, + "returnToParent" + ); + $tpl->setContent($tbl->getHTML()); + } + + public function editPeerReviewItemObject(ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + + if (!$this->canGive() || + !$this->isValidPeer($_GET["peer_id"])) { + $this->returnToParentObject(); + } + + if (!$a_form) { + $a_form = $this->initPeerReviewItemForm($_GET["peer_id"]); + } + + $tpl->setContent($a_form->getHTML()); + } + + protected function isValidPeer($a_peer_id) + { + $peer_items = $this->submission->getPeerReview()->getPeerReviewsByGiver($this->submission->getUserId()); + foreach ($peer_items as $item) { + if ($item["peer_id"] == $a_peer_id) { + return true; + } + } + return false; + } + + protected function getSubmissionContent(ilExSubmission $a_submission) + { + if ($this->ass->getType() != ilExAssignment::TYPE_TEXT) { + return; + } + + $text = $a_submission->getFiles(); + if ($text) { + $text = array_shift($text); + if (trim($text["atext"])) { + // mob id to mob src + include_once "Services/RTE/classes/class.ilRTE.php"; + return nl2br(ilRTE::_replaceMediaObjectImageSrc($text["atext"], 1)); + } + } + } + + protected function initPeerReviewItemForm($a_peer_id) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + // get peer data + $peer_items = $this->submission->getPeerReview()->getPeerReviewsByGiver($this->submission->getUserId()); + foreach ($peer_items as $item) { + if ($item["peer_id"] == $a_peer_id) { + $peer = $item; + break; + } + } + + $ilCtrl->saveParameter($this, "peer_id"); + + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this, "updatePeerReview")); + + $form->setTitle($this->ass->getTitle() . ": " . $lng->txt("exc_peer_review_give")); + + // peer info + if (!$this->ass->hasPeerReviewPersonalized()) { + $id_title = $lng->txt("id"); + $id_value = $peer["seq"]; + } else { + include_once "Services/User/classes/class.ilUserUtil.php"; + $id_title = $lng->txt("exc_peer_review_recipient"); + $id_value = ilUserUtil::getNamePresentation($peer["peer_id"]); + } + $id = new ilNonEditableValueGUI($id_title); + $id->setValue($id_value); + $form->addItem($id); + + // submission info + + $submission = new ilExSubmission($this->ass, $peer["peer_id"]); + $file_info = $submission->getDownloadedFilesInfoForTableGUIS($this, "editPeerReviewItem"); + + $last_sub = new ilNonEditableValueGUI($file_info["last_submission"]["txt"], "", true); + $last_sub->setValue($file_info["last_submission"]["value"] . + $this->getLateSubmissionInfo($submission)); + $form->addItem($last_sub); + + $sub_data = $this->getSubmissionContent($submission); + if (!$sub_data) { + $sub_data = '' . $lng->txt("download") . ''; + } + + $sub = new ilNonEditableValueGUI($lng->txt("exc_submission"), "", true); + $sub->setValue($sub_data); + $form->addItem($sub); + + // peer review items + + $input = new ilFormSectionHeaderGUI(); + $input->setTitle($lng->txt("exc_peer_review")); + $form->addItem($input); + + $values = $this->submission->getPeerReview()->getPeerReviewValues($this->submission->getUserId(), $a_peer_id); + + foreach ($this->ass->getPeerReviewCriteriaCatalogueItems() as $item) { + $crit_id = $item->getId() + ? $item->getId() + : $item->getType(); + + $item->setPeerReviewContext( + $this->ass, + $this->submission->getUserId(), + $peer["peer_id"], + $form + ); + $item->addToPeerReviewForm($values[$crit_id]); + } + + $form->addCommandButton("updatePeerReview", $lng->txt("save")); + $form->addCommandButton("editPeerReview", $lng->txt("cancel")); + + return $form; + } + + public function updateCritAjaxObject() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + $tpl = $this->tpl; + + if (!$this->canGive() || + !$_POST["peer_id"] || + !$_POST["crit_id"] || + !$ilCtrl->isAsynch()) { + exit(); + } + + $peer_id = (int) $_POST["peer_id"]; + $crit_id = $_POST["crit_id"]; + $giver_id = $ilUser->getId(); + + include_once "Modules/Exercise/classes/class.ilExcCriteria.php"; + if (!is_numeric($crit_id)) { + $crit = ilExcCriteria::getInstanceByType($crit_id); + } else { + $crit = ilExcCriteria::getInstanceById($crit_id); + } + $crit->setPeerReviewContext($this->ass, $giver_id, $peer_id); + $html = $crit->updateFromAjax(); + + $this->handlePeerReviewChange(); + + echo $html; + echo $tpl->getOnLoadCodeForAsynch(); + exit(); + } + + public function updatePeerReviewObject() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if (!$this->canGive() || + !$this->isValidPeer($_REQUEST["peer_id"])) { + $this->returnToParentObject(); + } + + $peer_id = $_REQUEST["peer_id"]; + + $form = $this->initPeerReviewItemForm($peer_id); + if ($form->checkInput()) { + $valid = true; + + $values = array(); + foreach ($this->ass->getPeerReviewCriteriaCatalogueItems() as $item) { + $item->setPeerReviewContext( + $this->ass, + $this->submission->getUserId(), + $peer_id, + $form + ); + $value = $item->importFromPeerReviewForm(); + if ($value !== null) { + $crit_id = $item->getId() + ? $item->getId() + : $item->getType(); + $values[$crit_id] = $value; + } + if (!$item->validate($value)) { + $valid = false; + } + } + + if ($valid) { + $this->submission->getPeerReview()->updatePeerReview($peer_id, $values); + + $this->handlePeerReviewChange(); + + ilUtil::sendSuccess($this->lng->txt("exc_peer_review_updated"), true); + $ilCtrl->redirect($this, "editPeerReview"); + } else { + ilUtil::sendFailure($lng->txt("form_input_not_valid")); + } + } + + $form->setValuesByPost(); + $this->editPeerReviewItemObject($form); + } + + protected function handlePeerReviewChange() + { + // (in)valid peer reviews could change assignment status + $exercise = new ilObjExercise($this->ass->getExerciseId(), false); + $exercise->processExerciseStatus( + $this->ass, + $this->submission->getUserIds(), + $this->submission->hasSubmitted(), + $this->submission->validatePeerReviews() + ); + } + + public function downloadPeerReviewObject() + { + $ilCtrl = $this->ctrl; + + if (!$this->canView() && + !$this->canGive()) { + $this->returnToParentObject(); + } + + $parts = explode("__", $_GET["fu"]); + $giver_id = $parts[0]; + $peer_id = $parts[1]; + $crit_id = $parts[2]; + + include_once "Modules/Exercise/classes/class.ilExcCriteria.php"; + if (!is_numeric($crit_id)) { + $crit = ilExcCriteria::getInstanceByType($crit_id); + } else { + $crit = ilExcCriteria::getInstanceById($crit_id); + } + + $crit->setPeerReviewContext($this->ass, $giver_id, $peer_id); + $file = $crit->getFileByHash(); + if ($file) { + ilUtil::deliverFile($file, basename($file)); + } + + $ilCtrl->redirect($this, "returnToParent"); + } + + + + // + // ADMIN + // + + public function showPeerReviewOverviewObject() + { + $tpl = $this->tpl; + + if (!$this->ass || + !$this->ass->getPeerReview()) { + $this->returnToParentObject(); + } + + include_once "Modules/Exercise/classes/class.ilExAssignmentPeerReviewOverviewTableGUI.php"; + $tbl = new ilExAssignmentPeerReviewOverviewTableGUI( + $this, + "showPeerReviewOverview", + $this->ass + ); + + $panel = ""; + $panel_data = $tbl->getPanelInfo(); + if (sizeof($panel_data)) { + $ptpl = new ilTemplate("tpl.exc_peer_review_overview_panel.html", true, true, "Modules/Exercise"); + foreach ($panel_data as $item) { + $ptpl->setCurrentBlock("user_bl"); + foreach ($item["value"] as $user) { + $ptpl->setVariable("USER", $user); + $ptpl->parseCurrentBlock(); + } + + $ptpl->setCurrentBlock("item_bl"); + $ptpl->setVariable("TITLE", $item["title"]); + $ptpl->parseCurrentBlock(); + } + + include_once "Services/UIComponent/Panel/classes/class.ilPanelGUI.php"; + $panel = ilPanelGUI::getInstance(); + $panel->setHeading($this->lng->txt("exc_peer_review_overview_invalid_users")); + $panel->setBody($ptpl->get()); + $panel = $panel->getHTML(); + } + + $tpl->setContent($tbl->getHTML() . $panel); + } + + public function confirmResetPeerReviewObject() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $ilTabs = $this->tabs_gui; + + if (!$this->ass || + !$this->ass->getPeerReview()) { + $this->returnToParentObject(); + } + + $ilTabs->clearTargets(); + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText(sprintf($this->lng->txt("exc_peer_review_reset_sure"), $this->ass->getTitle())); + $cgui->setCancel($this->lng->txt("cancel"), "showPeerReviewOverview"); + $cgui->setConfirm($this->lng->txt("delete"), "resetPeerReview"); + + $tpl->setContent($cgui->getHTML()); + } + + public function resetPeerReviewObject() + { + $ilCtrl = $this->ctrl; + + if (!$this->ass || + !$this->ass->getPeerReview()) { + $this->returnToParentObject(); + } + + include_once "Modules/Exercise/classes/class.ilExPeerReview.php"; + $peer_review = new ilExPeerReview($this->ass); + $all_giver_ids = $peer_review->resetPeerReviews(); + + if (is_array($all_giver_ids)) { + // if peer review is valid for completion, we have to re-calculate all assignment members + $exercise = new ilObjExercise($this->ass->getExerciseId(), false); + if ($exercise->isCompletionBySubmissionEnabled() && + $this->ass->getPeerReviewValid() != ilExAssignment::PEER_REVIEW_VALID_NONE) { + include_once "Modules/Exercise/classes/class.ilExSubmission.php"; + foreach ($all_giver_ids as $user_id) { + $submission = new ilExSubmission($this->ass, $user_id); + $pgui = new self($this->ass, $submission); + $pgui->handlePeerReviewChange(); + } + } + } + + ilUtil::sendSuccess($this->lng->txt("exc_peer_review_reset_done"), true); + $ilCtrl->redirect($this, "showPeerReviewOverview"); + } } diff --git a/Modules/Exercise/classes/class.ilExSubmission.php b/Modules/Exercise/classes/class.ilExSubmission.php index fca703dc32b0f9aaed6aa06055895c1d63f74001..5f6b9b52dcc4516018adee4d5fe78d9996e64477 100644 --- a/Modules/Exercise/classes/class.ilExSubmission.php +++ b/Modules/Exercise/classes/class.ilExSubmission.php @@ -10,1728 +10,1554 @@ */ class ilExSubmission { - const TYPE_FILE = "File"; - const TYPE_OBJECT = "Object"; // Blogs in WSP/Portfolio - const TYPE_TEXT = "Text"; - const TYPE_REPO_OBJECT = "RepoObject"; // Wikis - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilDB - */ - protected $db; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilCtrl - */ - protected $ctrl; - - protected $assignment; // [ilExAssignment] - protected $user_id; // [int] - protected $team; // [ilExAssignmentTeam] - protected $peer_review; // [ilExPeerReview] - protected $is_tutor; // [bool] - protected $public_submissions; // [bool] - - /** - * @var ilExAssignmentTypeInterface - */ - protected $ass_type; - - /** - * @var ilExAssignmentTypes - */ - protected $ass_types; - - public function __construct(ilExAssignment $a_ass, $a_user_id, ilExAssignmentTeam $a_team = null, $a_is_tutor = false, $a_public_submissions = false) - { - global $DIC; - - $this->user = $DIC->user(); - $this->db = $DIC->database(); - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $ilUser = $DIC->user(); - - $this->assignment = $a_ass; - $this->ass_type = $this->assignment->getAssignmentType(); - $this->ass_types = ilExAssignmentTypes::getInstance(); - - $this->user_id = $a_user_id; - $this->is_tutor = (bool)$a_is_tutor; - $this->public_submissions = (bool)$a_public_submissions; - - include_once("./Modules/Exercise/classes/class.ilExcAssMemberState.php"); - $this->state = ilExcAssMemberState::getInstanceByIds($a_ass->getId(), $a_user_id); - - if($a_ass->hasTeam()) - { - if(!$a_team) - { - include_once "Modules/Exercise/classes/class.ilExAssignmentTeam.php"; - $this->team = ilExAssignmentTeam::getInstanceByUserId($this->assignment->getId(), $this->user_id); - } - else - { - $this->team = $a_team; - } - } - - if($this->assignment->getPeerReview()) - { - include_once "Modules/Exercise/classes/class.ilExPeerReview.php"; - $this->peer_review = new ilExPeerReview($this->assignment); - } - } - - public function getSubmissionType() - { - return $this->assignment->getAssignmentType()->getSubmissionType(); - /*switch($this->assignment->getType()) - { - case ilExAssignment::TYPE_UPLOAD_TEAM: - case ilExAssignment::TYPE_UPLOAD: - return "File"; - - case ilExAssignment::TYPE_BLOG: - case ilExAssignment::TYPE_PORTFOLIO: - return "Object"; - - case ilExAssignment::TYPE_TEXT: - return "Text"; - };*/ - } - - - /** - * @return \ilExAssignment - */ - public function getAssignment() - { - return $this->assignment; - } - - /** - * @return \ilExAssignmentTeam - */ - public function getTeam() - { - return $this->team; - } - - /** - * @return \ilExPeerReview - */ - public function getPeerReview() - { - return $this->peer_review; - } - - public function validatePeerReviews() - { - $res = array(); - foreach($this->getUserIds() as $user_id) - { - $valid = true; - - // no peer review == valid - if($this->peer_review) - { - $valid = $this->peer_review->isFeedbackValidForPassed($user_id); - } - - $res[$user_id] = $valid; - } - return $res; - } - - public function getUserId() - { - return $this->user_id; - } - - public function getUserIds() - { - if($this->team && - !$this->hasNoTeamYet()) - { - return $this->team->getMembers(); - } - - // if has no team currently there still might be uploads attached - return array($this->user_id); - } - - public function getFeedbackId() - { - if($this->team) - { - return "t".$this->team->getId(); - } - else - { - return $this->getUserId(); - } - } - - public function hasSubmitted() - { - return (bool)sizeof($this->getFiles(null, true)); - } - - public function getSelectedObject() - { - $files = $this->getFiles(); - if(sizeof($files)) - { - return array_pop($files); - } - } - - public function canSubmit() - { - return ($this->isOwner() && - $this->state->isSubmissionAllowed()); - } - - public function canView() - { - $ilUser = $this->user; - - if($this->canSubmit() || - $this->isTutor() || - $this->isInTeam() || - $this->public_submissions) - { - return true; - } - - // #16115 - if($this->peer_review) - { - // peer review givers may view peer submissions - foreach($this->peer_review->getPeerReviewsByPeerId($this->getUserId()) as $giver) - { - if($giver["giver_id"] == $ilUser->getId()) - { - return true; - } - } - } - - return false; - } - - public function isTutor() - { - return $this->is_tutor; - } - - public function hasNoTeamYet() - { - if($this->assignment->hasTeam() && - !$this->team->getId()) - { - return true; - } - return false; - } - - public function isInTeam($a_user_id = null) - { - $ilUser = $this->user; - - if(!$a_user_id) - { - $a_user_id = $ilUser->getId(); - } - return in_array($a_user_id, $this->getUserIds()); - } - - public function isOwner() - { - $ilUser = $this->user; - - return ($ilUser->getId() == $this->getUserId()); - } - - public function hasPeerReviewAccess() - { - return ($this->peer_review && - $this->peer_review->hasPeerReviewAccess($this->user_id)); - } - - public function canAddFile() - { - if(!$this->canSubmit()) - { - return false; - } - - $max = $this->getAssignment()->getMaxFile(); - if($max && - $max <= sizeof($this->getFiles())) - { - return false; - } - - return true; - } - - - // - // FILES - // - - protected function isLate() - { - $dl = $this->state->getOfficialDeadline(); - //$dl = $this->assignment->getPersonalDeadline($this->getUserId()); - return ($dl && $dl < time()); - } - - protected function initStorage() - { - include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); - return new ilFSStorageExercise($this->assignment->getExerciseId(), $this->assignment->getId()); - } - - /** - * Get storage id - * - * @return int - */ - protected function getStorageId() - { - if ($this->ass_type->isSubmissionAssignedToTeam()) - { - $storage_id = $this->getTeam()->getId(); - } - else - { - $storage_id = $this->getUserId(); - } - return $storage_id; - } - - - /** - * Save submitted file of user - */ - function uploadFile($a_http_post_files, $unzip = false) - { - $ilDB = $this->db; - - if(!$this->canAddFile()) - { - return false; - } - - if ($this->ass_type->isSubmissionAssignedToTeam()) - { - $team_id = $this->getTeam()->getId(); - $user_id = 0; - if ($team_id == 0) - { - return false; - } - } - else - { - $team_id = 0; - $user_id = $this->getUserId(); - } - $storage_id = $this->getStorageId(); - - $deliver_result = $this->initStorage()->uploadFile($a_http_post_files, $storage_id, $unzip); - - if ($deliver_result) - { - $next_id = $ilDB->nextId("exc_returned"); - $query = sprintf("INSERT INTO exc_returned ". - "(returned_id, obj_id, user_id, filename, filetitle, mimetype, ts, ass_id, late, team_id) ". - "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", - $ilDB->quote($next_id, "integer"), - $ilDB->quote($this->assignment->getExerciseId(), "integer"), - $ilDB->quote($user_id, "integer"), - $ilDB->quote($deliver_result["fullname"], "text"), - $ilDB->quote(ilFileUtils::getValidFilename($a_http_post_files["name"]), "text"), - $ilDB->quote($deliver_result["mimetype"], "text"), - $ilDB->quote(ilUtil::now(), "timestamp"), - $ilDB->quote($this->assignment->getId(), "integer"), - $ilDB->quote($this->isLate(), "integer"), - $ilDB->quote($team_id, "integer") - ); - $ilDB->manipulate($query); - - if($this->team) - { - $this->team->writeLog(ilExAssignmentTeam::TEAM_LOG_ADD_FILE, - $a_http_post_files["name"]); - } - - return true; - } - return false; - } - - /** - * processes errorhandling etc for uploaded archive - * @param string $tmpFile path and filename to uploaded file - */ - function processUploadedZipFile($fileTmp) - { - $lng = $this->lng; - - // Create unzip-directory - $newDir = ilUtil::ilTempnam(); - ilUtil::makeDir($newDir); - - include_once ("Services/Utilities/classes/class.ilFileUtils.php"); - - $success = true; - - try - { - ilFileUtils::processZipFile($newDir,$fileTmp, false); - ilFileUtils::recursive_dirscan($newDir, $filearray); - - // #18441 - check number of files in zip - $max_num = $this->assignment->getMaxFile(); - if($max_num) - { - $current_num = sizeof($this->getFiles()); - $zip_num = sizeof($filearray["file"]); - if($current_num + $zip_num > $max_num) - { - $success = false; - ilUtil::sendFailure($lng->txt("exc_upload_error")." [Zip1]", true); - } - } - - if($success) - { - foreach ($filearray["file"] as $key => $filename) - { - $a_http_post_files["name"] = ilFileUtils::utf8_encode($filename); - $a_http_post_files["type"] = "other"; - $a_http_post_files["tmp_name"] = $filearray["path"][$key]."/".$filename; - $a_http_post_files["error"] = 0; - $a_http_post_files["size"] = filesize($filearray["path"][$key]."/".$filename); - - if(!$this->uploadFile($a_http_post_files, true)) - { - $success = false; - ilUtil::sendFailure($lng->txt("exc_upload_error")." [Zip2]", true); - } - } - } - } - catch (ilFileUtilsException $e) - { - $success = false; - ilUtil::sendFailure($e->getMessage()); - } - - ilUtil::delDir($newDir); - return $success; - } - - public static function hasAnySubmissions($a_ass_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT * FROM exc_returned". - " WHERE ass_id = ".$ilDB->quote($a_ass_id, "integer"). - " AND (filename IS NOT NULL OR atext IS NOT NULL)". - " AND ts IS NOT NULL"; - $res = $ilDB->query($query); - return $res->numRows($res); - } - - public static function getAllAssignmentFiles($a_exc_id, $a_ass_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); - $storage = new ilFSStorageExercise($a_exc_id, $a_ass_id); - $path = $storage->getAbsoluteSubmissionPath(); - - include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssignmentTypes.php"); - $ass_type = ilExAssignmentTypes::getInstance()->getById(ilExAssignment::lookupType($a_ass_id)); - - $query = "SELECT * FROM exc_returned WHERE ass_id = ". - $ilDB->quote($a_ass_id, "integer"); - - $res = $ilDB->query($query); - while($row = $ilDB->fetchAssoc($res)) - { - if ($ass_type->isSubmissionAssignedToTeam()) - { - $storage_id = $row["team_id"]; - } - else - { - $storage_id = $row["user_id"]; - } - - $row["timestamp"] = $row["ts"]; - $row["filename"] = $path."/".$storage_id."/".basename($row["filename"]); - $delivered[] = $row; - } - - return $delivered ? $delivered : array(); - } - - public static function getAssignmentFilesByUsers(int $a_exc_id, int $a_ass_id, array $a_users) : array - { - global $DIC; - - $ilDB = $DIC->database(); - - $storage = new ilFSStorageExercise($a_exc_id, $a_ass_id); - $path = $storage->getAbsoluteSubmissionPath(); - - $ass_type = ilExAssignmentTypes::getInstance()->getById(ilExAssignment::lookupType($a_ass_id)); - - $query = "SELECT * FROM exc_returned WHERE ass_id = ". - $ilDB->quote($a_ass_id, "integer") . - " AND user_id IN (".implode(',',$a_users).")"; - - $res = $ilDB->query($query); - while($row = $ilDB->fetchAssoc($res)) - { - if ($ass_type->isSubmissionAssignedToTeam()) - { - $storage_id = $row["team_id"]; - } - else - { - $storage_id = $row["user_id"]; - } - - $row["timestamp"] = $row["ts"]; - $row["filename"] = $path."/".$storage_id."/".basename($row["filename"]); - $delivered[] = $row; - } - - return $delivered ? $delivered : array(); - } - - /** - * Get submission items (not only files) - * @todo this also returns non-file entries, rename this, see dev.txt.php - * @param array|null $a_file_ids - * @param bool $a_only_valid - * @param null $a_min_timestamp - * @return array - */ - function getFiles(array $a_file_ids = null, $a_only_valid = false, $a_min_timestamp = null) - { - $ilDB = $this->db; - - $sql = "SELECT * FROM exc_returned". - " WHERE ass_id = ".$ilDB->quote($this->getAssignment()->getId(), "integer"); - - $sql.= " AND ".$this->getTableUserWhere(true); - - - if($a_file_ids) - { - $sql .= " AND ".$ilDB->in("returned_id", $a_file_ids, false, "integer"); - } - - if($a_min_timestamp) - { - $sql .= " AND ts > ".$ilDB->quote($a_min_timestamp, "timestamp"); - } - - $result = $ilDB->query($sql); - - $delivered_files = array(); - if ($ilDB->numRows($result)) - { - $path = $this->initStorage()->getAbsoluteSubmissionPath(); - - while ($row = $ilDB->fetchAssoc($result)) - { - // blog/portfolio/text submissions - if($a_only_valid && - !$row["filename"] && - !(trim($row["atext"]))) - { - continue; - } - - $row["owner_id"] = $row["user_id"]; - $row["timestamp"] = $row["ts"]; - $row["timestamp14"] = substr($row["ts"], 0, 4). - substr($row["ts"], 5, 2).substr($row["ts"], 8, 2). - substr($row["ts"], 11, 2).substr($row["ts"], 14, 2). - substr($row["ts"], 17, 2); - - if ($this->getAssignment()->getAssignmentType()->isSubmissionAssignedToTeam()) - { - $storage_id = $row["team_id"]; - } - else - { - $storage_id = $row["user_id"]; - } - - - $row["filename"] = $path. - "/".$storage_id."/".basename($row["filename"]); - - // see 22301, 22719 - if (is_file($row["filename"]) || (!$this->assignment->getAssignmentType()->usesFileUpload())) - { - array_push($delivered_files, $row); - } - } - } - - return $delivered_files; - } - - /** - * Check how much files have been uploaded by the learner - * after the last download of the tutor. - * @param tutor integer - * @return array - */ - function lookupNewFiles($a_tutor = null) - { - $ilDB = $this->db; - $ilUser = $this->user; - - $tutor = ($a_tutor) - ? $a_tutor - : $ilUser->getId(); - - $where = " AND ".$this->getTableUserWhere(true); - - $q = "SELECT exc_returned.returned_id AS id ". - "FROM exc_usr_tutor, exc_returned ". - "WHERE exc_returned.ass_id = exc_usr_tutor.ass_id ". - " AND exc_returned.user_id = exc_usr_tutor.usr_id ". - " AND exc_returned.ass_id = ".$ilDB->quote($this->getAssignment()->getId(), "integer"). - $where. - " AND exc_usr_tutor.tutor_id = ".$ilDB->quote($tutor, "integer"). - " AND exc_usr_tutor.download_time < exc_returned.ts "; - - $new_up_set = $ilDB->query($q); - - $new_up = array(); - while ($new_up_rec = $ilDB->fetchAssoc($new_up_set)) - { - $new_up[] = $new_up_rec["id"]; - } - - return $new_up; - } - - /** - * Get exercise from submission id (used in ilObjMediaObject) - * - * @param int $a_returned_id - * @return int - */ - public static function lookupExerciseIdForReturnedId($a_returned_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT obj_id". - " FROM exc_returned". - " WHERE returned_id = ".$ilDB->quote($a_returned_id, "integer")); - $row = $ilDB->fetchAssoc($set); - return (int)$row["obj_id"]; - } - - /** - * Check if given file was assigned - * - * Used in Blog/Portfolio - * - * @param int $a_user_id - * @param string $a_filetitle - */ - public static function findUserFiles($a_user_id, $a_filetitle) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT obj_id, ass_id". - " FROM exc_returned". - " WHERE user_id = ".$ilDB->quote($a_user_id, "integer"). - " AND filetitle = ".$ilDB->quote($a_filetitle, "text")); - $res = array(); - while($row = $ilDB->fetchAssoc($set)) - { - $res[$row["ass_id"]] = $row; - } - return $res; - } - - function deleteAllFiles() - { - $files = array(); - foreach($this->getFiles() as $item) - { - $files[] = $item["returned_id"]; - } - if(sizeof($files)) - { - $this->deleteSelectedFiles($files); - } - } - - /** - * Deletes already delivered files - * @param array $file_id_array An array containing database ids of the delivered files - * @param numeric $user_id The database id of the user - * @access public - */ - function deleteSelectedFiles(array $file_id_array) - { - $ilDB = $this->db; - - - $where = " AND ".$this->getTableUserWhere(true); - - - if(!sizeof($file_id_array)) - { - return; - } - - if (count($file_id_array)) - { - $result = $ilDB->query("SELECT * FROM exc_returned". - " WHERE ".$ilDB->in("returned_id", $file_id_array, false, "integer"). - $where); - - if ($ilDB->numRows($result)) - { - $result_array = array(); - while ($row = $ilDB->fetchAssoc($result)) - { - $row["timestamp"] = $row["ts"]; - array_push($result_array, $row); - } - - // delete the entries in the database - $ilDB->manipulate("DELETE FROM exc_returned". - " WHERE ".$ilDB->in("returned_id", $file_id_array, false, "integer"). - $where); - - // delete the files - $path = $this->initStorage()->getAbsoluteSubmissionPath(); - foreach ($result_array as $key => $value) - { - if($value["filename"]) - { - if($this->team) - { - $this->team->writeLog(ilExAssignmentTeam::TEAM_LOG_REMOVE_FILE, - $value["filetitle"]); - } - - if ($this->getAssignment()->getAssignmentType()->isSubmissionAssignedToTeam()) - { - $storage_id = $value["team_id"]; - } - else - { - $storage_id = $value["user_id"]; - } - - $filename = $path."/".$storage_id."/".basename($value["filename"]); - unlink($filename); - } - } - } - } - } - - /** - * Delete all delivered files of user - * - * @param int $a_exc_id excercise id - * @param int $a_user_id user id - */ - public static function deleteUser($a_exc_id, $a_user_id) - { - - include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); - - foreach(ilExAssignment::getInstancesByExercise($a_exc_id) as $ass) - { - $submission = new self($ass, $a_user_id); - $submission->deleteAllFiles(); - - // remove from any team - $team = $submission->getTeam(); - if($team) - { - $team->removeTeamMember($a_user_id); - } - - // #14900 - $member_status = $ass->getMemberStatus($a_user_id); - $member_status->setStatus("notgraded"); - $member_status->update(); - } - } - - protected function getLastDownloadTime(array $a_user_ids) - { - $ilDB = $this->db; - $ilUser = $this->user; - - $q = "SELECT download_time FROM exc_usr_tutor WHERE ". - " ass_id = ".$ilDB->quote($this->getAssignment()->getId(), "integer")." AND ". - $ilDB->in("usr_id", $a_user_ids, "", "integer")." AND ". - " tutor_id = ".$ilDB->quote($ilUser->getId(), "integer"); - $lu_set = $ilDB->query($q); - $lu_rec = $ilDB->fetchAssoc($lu_set); - return $lu_rec["download_time"]; - } - - function downloadFiles(array $a_file_ids = null, $a_only_new = false, $a_peer_review_mask_filename = false) - { - $ilUser = $this->user; - $lng = $this->lng; - - $user_ids = $this->getUserIds(); - $is_team = $this->assignment->hasTeam(); - - // get last download time - $download_time = null; - if ($a_only_new) - { - $download_time = $this->getLastDownloadTime($user_ids); - } - - if($this->is_tutor) - { - $this->updateTutorDownloadTime(); - } - - if($a_peer_review_mask_filename) - { - // process peer review sequence id - $peer_id = null; - foreach($this->peer_review->getPeerReviewsByGiver($ilUser->getId()) as $idx => $item) - { - if($item["peer_id"] == $this->getUserId()) - { - $peer_id = $idx+1; - break; - } - } - - // this will remove personal info from zip-filename - $is_team = true; - } - - $files = $this->getFiles($a_file_ids, false, $download_time); - if($files) - { - if (sizeof($files) == 1) - { - $file = array_pop($files); - - switch($this->assignment->getType()) - { - case ilExAssignment::TYPE_BLOG: - case ilExAssignment::TYPE_PORTFOLIO: - $file["filetitle"] = ilObjUser::_lookupName($file["user_id"]); - $file["filetitle"] = ilObject::_lookupTitle($this->assignment->getExerciseId())." - ". - $this->assignment->getTitle()." - ". - $file["filetitle"]["firstname"]." ". - $file["filetitle"]["lastname"]." (". - $file["filetitle"]["login"].").zip"; - break; - - // @todo: generalize - case ilExAssignment::TYPE_WIKI_TEAM: - $file["filetitle"] = ilObject::_lookupTitle($this->assignment->getExerciseId())." - ". - $this->assignment->getTitle()." (Team ".$this->getTeam()->getId().").zip"; - break; - - default: - break; - } - - if($a_peer_review_mask_filename) - { - $suffix = array_pop(explode(".", $file["filetitle"])); - $file["filetitle"] = $this->assignment->getTitle()."_peer".$peer_id.".".$suffix; - } - else if($file["late"]) - { - $file["filetitle"] = $lng->txt("exc_late_submission")." - ". - $file["filetitle"]; - } - - $this->downloadSingleFile($file["user_id"], $file["filename"], $file["filetitle"], $file["team_id"]); - } - else - { - $array_files = array(); - foreach($files as $seq => $file) - { - if ($this->assignment->getAssignmentType()->isSubmissionAssignedToTeam()) - { - $storage_id = $file["team_id"]; - } - else - { - $storage_id = $file["user_id"]; - } - - $src = basename($file["filename"]); - if($a_peer_review_mask_filename) - { - $suffix = array_pop(explode(".", $src)); - $tgt = $this->assignment->getTitle()."_peer".$peer_id. - "_".(++$seq).".".$suffix; - - $array_files[$storage_id][] = array( - "src" => $src, - "tgt" => $tgt - ); - } - else - { - $array_files[$storage_id][] = array( - "src" => $src, - "late" => $file["late"] - ); - } - } - - $this->downloadMultipleFiles($array_files, - ($is_team ? null : $this->getUserId()), $is_team); - } - } - else - { - return false; - } - - return true; - } - - // Update the timestamp of the last download of current user (=tutor) - public function updateTutorDownloadTime() - { - $ilUser = $this->user; - $ilDB = $this->db; - - $exc_id = $this->assignment->getExerciseId(); - $ass_id = $this->assignment->getId(); - - foreach($this->getUserIds() as $user_id) - { - $ilDB->manipulateF("DELETE FROM exc_usr_tutor ". - "WHERE ass_id = %s AND usr_id = %s AND tutor_id = %s", - array("integer", "integer", "integer"), - array($ass_id, $user_id, $ilUser->getId())); - - $ilDB->manipulateF("INSERT INTO exc_usr_tutor (ass_id, obj_id, usr_id, tutor_id, download_time) VALUES ". - "(%s, %s, %s, %s, %s)", - array("integer", "integer", "integer", "integer", "timestamp"), - array($ass_id, $exc_id, $user_id, $ilUser->getId(), ilUtil::now())); - } - } - - protected function downloadSingleFile($a_user_id, $filename, $filetitle, $a_team_id) - { - if ($this->ass_type->isSubmissionAssignedToTeam()) - { - $storage_id = $a_team_id; - } - else - { - $storage_id = $a_user_id; - } - - $filename = $this->initStorage()->getAbsoluteSubmissionPath(). - "/".$storage_id."/".basename($filename); - - ilUtil::deliverFile($filename, $filetitle); - } - - protected function downloadMultipleFiles($a_filenames, $a_user_id, $a_multi_user = false) - { - $lng = $this->lng; - - $path = $this->initStorage()->getAbsoluteSubmissionPath(); - - $cdir = getcwd(); - - $zip = PATH_TO_ZIP; - $tmpdir = ilUtil::ilTempnam(); - $tmpfile = ilUtil::ilTempnam(); - $tmpzipfile = $tmpfile . ".zip"; - - ilUtil::makeDir($tmpdir); - chdir($tmpdir); - - $assTitle = ilExAssignment::lookupTitle($this->assignment->getId()); - $deliverFilename = str_replace(" ", "_", $assTitle); - if ($a_user_id > 0 && !$a_multi_user) - { - $userName = ilObjUser::_lookupName($a_user_id); - $deliverFilename .= "_".$userName["lastname"]."_".$userName["firstname"]; - } - else - { - $deliverFilename .= "_files"; - } - $orgDeliverFilename = trim($deliverFilename); - $deliverFilename = ilUtil::getASCIIFilename($orgDeliverFilename); - ilUtil::makeDir($tmpdir."/".$deliverFilename); - chdir($tmpdir."/".$deliverFilename); - - //copy all files to a temporary directory and remove them afterwards - $parsed_files = $duplicates = array(); - foreach ($a_filenames as $storage_id => $files) - { - $pathname = $path."/".$storage_id; - - foreach($files as $filename) - { - // peer review masked filenames, see deliverReturnedFiles() - if(isset($filename["tgt"])) - { - $newFilename = $filename["tgt"]; - $filename = $filename["src"]; - } - else - { - $late = $filename["late"]; - $filename = $filename["src"]; - - // remove timestamp - $newFilename = trim($filename); - $pos = strpos($newFilename , "_"); - if ($pos !== false) - { - $newFilename = substr($newFilename, $pos + 1); - } - // #11070 - $chkName = strtolower($newFilename); - if(array_key_exists($chkName, $duplicates)) - { - $suffix = strrpos($newFilename, "."); - $newFilename = substr($newFilename, 0, $suffix). - " (".(++$duplicates[$chkName]).")". - substr($newFilename, $suffix); - } - else - { - $duplicates[$chkName] = 1; - } - - if($late) - { - $newFilename = $lng->txt("exc_late_submission")." - ". - $newFilename; - } - } - - $newFilename = ilUtil::getASCIIFilename($newFilename); - $newFilename = $tmpdir.DIRECTORY_SEPARATOR.$deliverFilename.DIRECTORY_SEPARATOR.$newFilename; - // copy to temporal directory - $oldFilename = $pathname.DIRECTORY_SEPARATOR.$filename; - if (!copy ($oldFilename, $newFilename)) - { - echo 'Could not copy '.$oldFilename.' to '.$newFilename; - } - touch($newFilename, filectime($oldFilename)); - $parsed_files[] = ilUtil::escapeShellArg($deliverFilename.DIRECTORY_SEPARATOR.basename($newFilename)); - } - } - - chdir($tmpdir); - $zipcmd = $zip." ".ilUtil::escapeShellArg($tmpzipfile)." ".join($parsed_files, " "); - - exec($zipcmd); - ilUtil::delDir($tmpdir); - - chdir($cdir); - ilUtil::deliverFile($tmpzipfile, $orgDeliverFilename.".zip", "", false, true); - exit; - } - - /** - * Download all submitted files of an assignment (all user) - * @param $a_ass ilExAssignment - * @param $members array of user names, key is user id - * @param $to_path string - * @throws ilExerciseException - * @return void - */ - public static function downloadAllAssignmentFiles(ilExAssignment $a_ass, array $members, $to_path) - { - global $DIC; - - $lng = $DIC->language(); - - include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); - - $storage = new ilFSStorageExercise($a_ass->getExerciseId(), $a_ass->getId()); - $storage->create(); - - ksort($members); - //$savepath = $this->getExercisePath() . "/" . $this->obj_id . "/"; - $savepath = $storage->getAbsoluteSubmissionPath(); - $cdir = getcwd(); - - - // important check: if the directory does not exist - // ILIAS stays in the current directory (echoing only a warning) - // and the zip command below archives the whole ILIAS directory - // (including the data directory) and sends a mega file to the user :-o - if (!is_dir($savepath)) - { - return; - } - // Safe mode fix -// chdir($this->getExercisePath()); - - $tmpdir = $storage->getTempPath(); - chdir($tmpdir); - $zip = PATH_TO_ZIP; - - // check free diskspace - $dirsize = 0; - foreach (array_keys($members) as $id) - { - $directory = $savepath.DIRECTORY_SEPARATOR.$id; - $dirsize += ilUtil::dirsize($directory); - } - if ($dirsize > disk_free_space($tmpdir)) - { - return -1; - } - - $ass_type = $a_ass->getType(); - - // copy all member directories to the temporary folder - // switch from id to member name and append the login if the member name is double - // ensure that no illegal filenames will be created - // remove timestamp from filename - if($a_ass->hasTeam()) - { - $team_dirs = array(); - $team_map = ilExAssignmentTeam::getAssignmentTeamMap($a_ass->getId()); - } - foreach ($members as $id => $item) - { - $user = $item["name"]; - $user_files = $item["files"]; - $sourcedir = $savepath.DIRECTORY_SEPARATOR.$id; - if (!is_dir($sourcedir)) - { - continue; - } - - // group by teams - $team_dir= ""; - if(is_array($team_map) && - array_key_exists($id, $team_map)) - { - $team_id = $team_map[$id]; - if(!array_key_exists($team_id, $team_dirs)) - { - $team_dir = $lng->txt("exc_team")." ".$team_id; - ilUtil::makeDir($team_dir); - $team_dirs[$team_id] = $team_dir; - } - $team_dir = $team_dirs[$team_id].DIRECTORY_SEPARATOR; - } - - if ($a_ass->getAssignmentType()->isSubmissionAssignedToTeam()) - { - $targetdir = $team_dir . ilUtil::getASCIIFilename( - $item["name"] - ); - if ($targetdir == "") - { - continue; - } - - } - else - { - $targetdir = self::getDirectoryNameFromUserData($id); - if ($a_ass->getAssignmentType()->usesTeams()) { - $targetdir = $team_dir.$targetdir; + const TYPE_FILE = "File"; + const TYPE_OBJECT = "Object"; // Blogs in WSP/Portfolio + const TYPE_TEXT = "Text"; + const TYPE_REPO_OBJECT = "RepoObject"; // Wikis + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilDB + */ + protected $db; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilCtrl + */ + protected $ctrl; + + protected $assignment; // [ilExAssignment] + protected $user_id; // [int] + protected $team; // [ilExAssignmentTeam] + protected $peer_review; // [ilExPeerReview] + protected $is_tutor; // [bool] + protected $public_submissions; // [bool] + + /** + * @var ilExAssignmentTypeInterface + */ + protected $ass_type; + + /** + * @var ilExAssignmentTypes + */ + protected $ass_types; + + public function __construct(ilExAssignment $a_ass, $a_user_id, ilExAssignmentTeam $a_team = null, $a_is_tutor = false, $a_public_submissions = false) + { + global $DIC; + + $this->user = $DIC->user(); + $this->db = $DIC->database(); + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $ilUser = $DIC->user(); + + $this->assignment = $a_ass; + $this->ass_type = $this->assignment->getAssignmentType(); + $this->ass_types = ilExAssignmentTypes::getInstance(); + + $this->user_id = $a_user_id; + $this->is_tutor = (bool) $a_is_tutor; + $this->public_submissions = (bool) $a_public_submissions; + + include_once("./Modules/Exercise/classes/class.ilExcAssMemberState.php"); + $this->state = ilExcAssMemberState::getInstanceByIds($a_ass->getId(), $a_user_id); + + if ($a_ass->hasTeam()) { + if (!$a_team) { + include_once "Modules/Exercise/classes/class.ilExAssignmentTeam.php"; + $this->team = ilExAssignmentTeam::getInstanceByUserId($this->assignment->getId(), $this->user_id); + } else { + $this->team = $a_team; + } + } + + if ($this->assignment->getPeerReview()) { + include_once "Modules/Exercise/classes/class.ilExPeerReview.php"; + $this->peer_review = new ilExPeerReview($this->assignment); + } + } + + public function getSubmissionType() + { + return $this->assignment->getAssignmentType()->getSubmissionType(); + /*switch($this->assignment->getType()) + { + case ilExAssignment::TYPE_UPLOAD_TEAM: + case ilExAssignment::TYPE_UPLOAD: + return "File"; + + case ilExAssignment::TYPE_BLOG: + case ilExAssignment::TYPE_PORTFOLIO: + return "Object"; + + case ilExAssignment::TYPE_TEXT: + return "Text"; + };*/ + } + + + /** + * @return \ilExAssignment + */ + public function getAssignment() + { + return $this->assignment; + } + + /** + * @return \ilExAssignmentTeam + */ + public function getTeam() + { + return $this->team; + } + + /** + * @return \ilExPeerReview + */ + public function getPeerReview() + { + return $this->peer_review; + } + + public function validatePeerReviews() + { + $res = array(); + foreach ($this->getUserIds() as $user_id) { + $valid = true; + + // no peer review == valid + if ($this->peer_review) { + $valid = $this->peer_review->isFeedbackValidForPassed($user_id); + } + + $res[$user_id] = $valid; + } + return $res; + } + + public function getUserId() + { + return $this->user_id; + } + + public function getUserIds() + { + if ($this->team && + !$this->hasNoTeamYet()) { + return $this->team->getMembers(); + } + + // if has no team currently there still might be uploads attached + return array($this->user_id); + } + + public function getFeedbackId() + { + if ($this->team) { + return "t" . $this->team->getId(); + } else { + return $this->getUserId(); + } + } + + public function hasSubmitted() + { + return (bool) sizeof($this->getFiles(null, true)); + } + + public function getSelectedObject() + { + $files = $this->getFiles(); + if (sizeof($files)) { + return array_pop($files); + } + } + + public function canSubmit() + { + return ($this->isOwner() && + $this->state->isSubmissionAllowed()); + } + + public function canView() + { + $ilUser = $this->user; + + if ($this->canSubmit() || + $this->isTutor() || + $this->isInTeam() || + $this->public_submissions) { + return true; + } + + // #16115 + if ($this->peer_review) { + // peer review givers may view peer submissions + foreach ($this->peer_review->getPeerReviewsByPeerId($this->getUserId()) as $giver) { + if ($giver["giver_id"] == $ilUser->getId()) { + return true; + } + } + } + + return false; + } + + public function isTutor() + { + return $this->is_tutor; + } + + public function hasNoTeamYet() + { + if ($this->assignment->hasTeam() && + !$this->team->getId()) { + return true; + } + return false; + } + + public function isInTeam($a_user_id = null) + { + $ilUser = $this->user; + + if (!$a_user_id) { + $a_user_id = $ilUser->getId(); + } + return in_array($a_user_id, $this->getUserIds()); + } + + public function isOwner() + { + $ilUser = $this->user; + + return ($ilUser->getId() == $this->getUserId()); + } + + public function hasPeerReviewAccess() + { + return ($this->peer_review && + $this->peer_review->hasPeerReviewAccess($this->user_id)); + } + + public function canAddFile() + { + if (!$this->canSubmit()) { + return false; + } + + $max = $this->getAssignment()->getMaxFile(); + if ($max && + $max <= sizeof($this->getFiles())) { + return false; + } + + return true; + } + + + // + // FILES + // + + protected function isLate() + { + $dl = $this->state->getOfficialDeadline(); + //$dl = $this->assignment->getPersonalDeadline($this->getUserId()); + return ($dl && $dl < time()); + } + + protected function initStorage() + { + include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); + return new ilFSStorageExercise($this->assignment->getExerciseId(), $this->assignment->getId()); + } + + /** + * Get storage id + * + * @return int + */ + protected function getStorageId() + { + if ($this->ass_type->isSubmissionAssignedToTeam()) { + $storage_id = $this->getTeam()->getId(); + } else { + $storage_id = $this->getUserId(); + } + return $storage_id; + } + + + /** + * Save submitted file of user + */ + public function uploadFile($a_http_post_files, $unzip = false) + { + $ilDB = $this->db; + + if (!$this->canAddFile()) { + return false; + } + + if ($this->ass_type->isSubmissionAssignedToTeam()) { + $team_id = $this->getTeam()->getId(); + $user_id = 0; + if ($team_id == 0) { + return false; + } + } else { + $team_id = 0; + $user_id = $this->getUserId(); + } + $storage_id = $this->getStorageId(); + + $deliver_result = $this->initStorage()->uploadFile($a_http_post_files, $storage_id, $unzip); + + if ($deliver_result) { + $next_id = $ilDB->nextId("exc_returned"); + $query = sprintf( + "INSERT INTO exc_returned " . + "(returned_id, obj_id, user_id, filename, filetitle, mimetype, ts, ass_id, late, team_id) " . + "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", + $ilDB->quote($next_id, "integer"), + $ilDB->quote($this->assignment->getExerciseId(), "integer"), + $ilDB->quote($user_id, "integer"), + $ilDB->quote($deliver_result["fullname"], "text"), + $ilDB->quote(ilFileUtils::getValidFilename($a_http_post_files["name"]), "text"), + $ilDB->quote($deliver_result["mimetype"], "text"), + $ilDB->quote(ilUtil::now(), "timestamp"), + $ilDB->quote($this->assignment->getId(), "integer"), + $ilDB->quote($this->isLate(), "integer"), + $ilDB->quote($team_id, "integer") + ); + $ilDB->manipulate($query); + + if ($this->team) { + $this->team->writeLog( + ilExAssignmentTeam::TEAM_LOG_ADD_FILE, + $a_http_post_files["name"] + ); + } + + return true; + } + return false; + } + + /** + * processes errorhandling etc for uploaded archive + * @param string $tmpFile path and filename to uploaded file + */ + public function processUploadedZipFile($fileTmp) + { + $lng = $this->lng; + + // Create unzip-directory + $newDir = ilUtil::ilTempnam(); + ilUtil::makeDir($newDir); + + include_once("Services/Utilities/classes/class.ilFileUtils.php"); + + $success = true; + + try { + ilFileUtils::processZipFile($newDir, $fileTmp, false); + ilFileUtils::recursive_dirscan($newDir, $filearray); + + // #18441 - check number of files in zip + $max_num = $this->assignment->getMaxFile(); + if ($max_num) { + $current_num = sizeof($this->getFiles()); + $zip_num = sizeof($filearray["file"]); + if ($current_num + $zip_num > $max_num) { + $success = false; + ilUtil::sendFailure($lng->txt("exc_upload_error") . " [Zip1]", true); + } + } + + if ($success) { + foreach ($filearray["file"] as $key => $filename) { + $a_http_post_files["name"] = ilFileUtils::utf8_encode($filename); + $a_http_post_files["type"] = "other"; + $a_http_post_files["tmp_name"] = $filearray["path"][$key] . "/" . $filename; + $a_http_post_files["error"] = 0; + $a_http_post_files["size"] = filesize($filearray["path"][$key] . "/" . $filename); + + if (!$this->uploadFile($a_http_post_files, true)) { + $success = false; + ilUtil::sendFailure($lng->txt("exc_upload_error") . " [Zip2]", true); + } + } + } + } catch (ilFileUtilsException $e) { + $success = false; + ilUtil::sendFailure($e->getMessage()); + } + + ilUtil::delDir($newDir); + return $success; + } + + public static function hasAnySubmissions($a_ass_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT * FROM exc_returned" . + " WHERE ass_id = " . $ilDB->quote($a_ass_id, "integer") . + " AND (filename IS NOT NULL OR atext IS NOT NULL)" . + " AND ts IS NOT NULL"; + $res = $ilDB->query($query); + return $res->numRows($res); + } + + public static function getAllAssignmentFiles($a_exc_id, $a_ass_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); + $storage = new ilFSStorageExercise($a_exc_id, $a_ass_id); + $path = $storage->getAbsoluteSubmissionPath(); + + include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssignmentTypes.php"); + $ass_type = ilExAssignmentTypes::getInstance()->getById(ilExAssignment::lookupType($a_ass_id)); + + $query = "SELECT * FROM exc_returned WHERE ass_id = " . + $ilDB->quote($a_ass_id, "integer"); + + $res = $ilDB->query($query); + while ($row = $ilDB->fetchAssoc($res)) { + if ($ass_type->isSubmissionAssignedToTeam()) { + $storage_id = $row["team_id"]; + } else { + $storage_id = $row["user_id"]; + } + + $row["timestamp"] = $row["ts"]; + $row["filename"] = $path . "/" . $storage_id . "/" . basename($row["filename"]); + $delivered[] = $row; + } + + return $delivered ? $delivered : array(); + } + + public static function getAssignmentFilesByUsers(int $a_exc_id, int $a_ass_id, array $a_users) : array + { + global $DIC; + + $ilDB = $DIC->database(); + + $storage = new ilFSStorageExercise($a_exc_id, $a_ass_id); + $path = $storage->getAbsoluteSubmissionPath(); + + $ass_type = ilExAssignmentTypes::getInstance()->getById(ilExAssignment::lookupType($a_ass_id)); + + $query = "SELECT * FROM exc_returned WHERE ass_id = " . + $ilDB->quote($a_ass_id, "integer") . + " AND user_id IN (" . implode(',', $a_users) . ")"; + + $res = $ilDB->query($query); + while ($row = $ilDB->fetchAssoc($res)) { + if ($ass_type->isSubmissionAssignedToTeam()) { + $storage_id = $row["team_id"]; + } else { + $storage_id = $row["user_id"]; + } + + $row["timestamp"] = $row["ts"]; + $row["filename"] = $path . "/" . $storage_id . "/" . basename($row["filename"]); + $delivered[] = $row; + } + + return $delivered ? $delivered : array(); + } + + /** + * Get submission items (not only files) + * @todo this also returns non-file entries, rename this, see dev.txt.php + * @param array|null $a_file_ids + * @param bool $a_only_valid + * @param null $a_min_timestamp + * @return array + */ + public function getFiles(array $a_file_ids = null, $a_only_valid = false, $a_min_timestamp = null) + { + $ilDB = $this->db; + + $sql = "SELECT * FROM exc_returned" . + " WHERE ass_id = " . $ilDB->quote($this->getAssignment()->getId(), "integer"); + + $sql.= " AND " . $this->getTableUserWhere(true); + + + if ($a_file_ids) { + $sql .= " AND " . $ilDB->in("returned_id", $a_file_ids, false, "integer"); + } + + if ($a_min_timestamp) { + $sql .= " AND ts > " . $ilDB->quote($a_min_timestamp, "timestamp"); + } + + $result = $ilDB->query($sql); + + $delivered_files = array(); + if ($ilDB->numRows($result)) { + $path = $this->initStorage()->getAbsoluteSubmissionPath(); + + while ($row = $ilDB->fetchAssoc($result)) { + // blog/portfolio/text submissions + if ($a_only_valid && + !$row["filename"] && + !(trim($row["atext"]))) { + continue; + } + + $row["owner_id"] = $row["user_id"]; + $row["timestamp"] = $row["ts"]; + $row["timestamp14"] = substr($row["ts"], 0, 4) . + substr($row["ts"], 5, 2) . substr($row["ts"], 8, 2) . + substr($row["ts"], 11, 2) . substr($row["ts"], 14, 2) . + substr($row["ts"], 17, 2); + + if ($this->getAssignment()->getAssignmentType()->isSubmissionAssignedToTeam()) { + $storage_id = $row["team_id"]; + } else { + $storage_id = $row["user_id"]; + } + + + $row["filename"] = $path . + "/" . $storage_id . "/" . basename($row["filename"]); + + // see 22301, 22719 + if (is_file($row["filename"]) || (!$this->assignment->getAssignmentType()->usesFileUpload())) { + array_push($delivered_files, $row); + } + } + } + + return $delivered_files; + } + + /** + * Check how much files have been uploaded by the learner + * after the last download of the tutor. + * @param tutor integer + * @return array + */ + public function lookupNewFiles($a_tutor = null) + { + $ilDB = $this->db; + $ilUser = $this->user; + + $tutor = ($a_tutor) + ? $a_tutor + : $ilUser->getId(); + + $where = " AND " . $this->getTableUserWhere(true); + + $q = "SELECT exc_returned.returned_id AS id " . + "FROM exc_usr_tutor, exc_returned " . + "WHERE exc_returned.ass_id = exc_usr_tutor.ass_id " . + " AND exc_returned.user_id = exc_usr_tutor.usr_id " . + " AND exc_returned.ass_id = " . $ilDB->quote($this->getAssignment()->getId(), "integer") . + $where . + " AND exc_usr_tutor.tutor_id = " . $ilDB->quote($tutor, "integer") . + " AND exc_usr_tutor.download_time < exc_returned.ts "; + + $new_up_set = $ilDB->query($q); + + $new_up = array(); + while ($new_up_rec = $ilDB->fetchAssoc($new_up_set)) { + $new_up[] = $new_up_rec["id"]; + } + + return $new_up; + } + + /** + * Get exercise from submission id (used in ilObjMediaObject) + * + * @param int $a_returned_id + * @return int + */ + public static function lookupExerciseIdForReturnedId($a_returned_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query("SELECT obj_id" . + " FROM exc_returned" . + " WHERE returned_id = " . $ilDB->quote($a_returned_id, "integer")); + $row = $ilDB->fetchAssoc($set); + return (int) $row["obj_id"]; + } + + /** + * Check if given file was assigned + * + * Used in Blog/Portfolio + * + * @param int $a_user_id + * @param string $a_filetitle + */ + public static function findUserFiles($a_user_id, $a_filetitle) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query("SELECT obj_id, ass_id" . + " FROM exc_returned" . + " WHERE user_id = " . $ilDB->quote($a_user_id, "integer") . + " AND filetitle = " . $ilDB->quote($a_filetitle, "text")); + $res = array(); + while ($row = $ilDB->fetchAssoc($set)) { + $res[$row["ass_id"]] = $row; + } + return $res; + } + + public function deleteAllFiles() + { + $files = array(); + foreach ($this->getFiles() as $item) { + $files[] = $item["returned_id"]; + } + if (sizeof($files)) { + $this->deleteSelectedFiles($files); + } + } + + /** + * Deletes already delivered files + * @param array $file_id_array An array containing database ids of the delivered files + * @param numeric $user_id The database id of the user + * @access public + */ + public function deleteSelectedFiles(array $file_id_array) + { + $ilDB = $this->db; + + + $where = " AND " . $this->getTableUserWhere(true); + + + if (!sizeof($file_id_array)) { + return; + } + + if (count($file_id_array)) { + $result = $ilDB->query("SELECT * FROM exc_returned" . + " WHERE " . $ilDB->in("returned_id", $file_id_array, false, "integer") . + $where); + + if ($ilDB->numRows($result)) { + $result_array = array(); + while ($row = $ilDB->fetchAssoc($result)) { + $row["timestamp"] = $row["ts"]; + array_push($result_array, $row); + } + + // delete the entries in the database + $ilDB->manipulate("DELETE FROM exc_returned" . + " WHERE " . $ilDB->in("returned_id", $file_id_array, false, "integer") . + $where); + + // delete the files + $path = $this->initStorage()->getAbsoluteSubmissionPath(); + foreach ($result_array as $key => $value) { + if ($value["filename"]) { + if ($this->team) { + $this->team->writeLog( + ilExAssignmentTeam::TEAM_LOG_REMOVE_FILE, + $value["filetitle"] + ); + } + + if ($this->getAssignment()->getAssignmentType()->isSubmissionAssignedToTeam()) { + $storage_id = $value["team_id"]; + } else { + $storage_id = $value["user_id"]; + } + + $filename = $path . "/" . $storage_id . "/" . basename($value["filename"]); + unlink($filename); + } + } + } + } + } + + /** + * Delete all delivered files of user + * + * @param int $a_exc_id excercise id + * @param int $a_user_id user id + */ + public static function deleteUser($a_exc_id, $a_user_id) + { + include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); + + foreach (ilExAssignment::getInstancesByExercise($a_exc_id) as $ass) { + $submission = new self($ass, $a_user_id); + $submission->deleteAllFiles(); + + // remove from any team + $team = $submission->getTeam(); + if ($team) { + $team->removeTeamMember($a_user_id); + } + + // #14900 + $member_status = $ass->getMemberStatus($a_user_id); + $member_status->setStatus("notgraded"); + $member_status->update(); + } + } + + protected function getLastDownloadTime(array $a_user_ids) + { + $ilDB = $this->db; + $ilUser = $this->user; + + $q = "SELECT download_time FROM exc_usr_tutor WHERE " . + " ass_id = " . $ilDB->quote($this->getAssignment()->getId(), "integer") . " AND " . + $ilDB->in("usr_id", $a_user_ids, "", "integer") . " AND " . + " tutor_id = " . $ilDB->quote($ilUser->getId(), "integer"); + $lu_set = $ilDB->query($q); + $lu_rec = $ilDB->fetchAssoc($lu_set); + return $lu_rec["download_time"]; + } + + public function downloadFiles(array $a_file_ids = null, $a_only_new = false, $a_peer_review_mask_filename = false) + { + $ilUser = $this->user; + $lng = $this->lng; + + $user_ids = $this->getUserIds(); + $is_team = $this->assignment->hasTeam(); + + // get last download time + $download_time = null; + if ($a_only_new) { + $download_time = $this->getLastDownloadTime($user_ids); + } + + if ($this->is_tutor) { + $this->updateTutorDownloadTime(); + } + + if ($a_peer_review_mask_filename) { + // process peer review sequence id + $peer_id = null; + foreach ($this->peer_review->getPeerReviewsByGiver($ilUser->getId()) as $idx => $item) { + if ($item["peer_id"] == $this->getUserId()) { + $peer_id = $idx+1; + break; + } + } + + // this will remove personal info from zip-filename + $is_team = true; + } + + $files = $this->getFiles($a_file_ids, false, $download_time); + if ($files) { + if (sizeof($files) == 1) { + $file = array_pop($files); + + switch ($this->assignment->getType()) { + case ilExAssignment::TYPE_BLOG: + case ilExAssignment::TYPE_PORTFOLIO: + $file["filetitle"] = ilObjUser::_lookupName($file["user_id"]); + $file["filetitle"] = ilObject::_lookupTitle($this->assignment->getExerciseId()) . " - " . + $this->assignment->getTitle() . " - " . + $file["filetitle"]["firstname"] . " " . + $file["filetitle"]["lastname"] . " (" . + $file["filetitle"]["login"] . ").zip"; + break; + + // @todo: generalize + case ilExAssignment::TYPE_WIKI_TEAM: + $file["filetitle"] = ilObject::_lookupTitle($this->assignment->getExerciseId()) . " - " . + $this->assignment->getTitle() . " (Team " . $this->getTeam()->getId() . ").zip"; + break; + + default: + break; + } + + if ($a_peer_review_mask_filename) { + $suffix = array_pop(explode(".", $file["filetitle"])); + $file["filetitle"] = $this->assignment->getTitle() . "_peer" . $peer_id . "." . $suffix; + } elseif ($file["late"]) { + $file["filetitle"] = $lng->txt("exc_late_submission") . " - " . + $file["filetitle"]; + } + + $this->downloadSingleFile($file["user_id"], $file["filename"], $file["filetitle"], $file["team_id"]); + } else { + $array_files = array(); + foreach ($files as $seq => $file) { + if ($this->assignment->getAssignmentType()->isSubmissionAssignedToTeam()) { + $storage_id = $file["team_id"]; + } else { + $storage_id = $file["user_id"]; + } + + $src = basename($file["filename"]); + if ($a_peer_review_mask_filename) { + $suffix = array_pop(explode(".", $src)); + $tgt = $this->assignment->getTitle() . "_peer" . $peer_id . + "_" . (++$seq) . "." . $suffix; + + $array_files[$storage_id][] = array( + "src" => $src, + "tgt" => $tgt + ); + } else { + $array_files[$storage_id][] = array( + "src" => $src, + "late" => $file["late"] + ); + } + } + + $this->downloadMultipleFiles( + $array_files, + ($is_team ? null : $this->getUserId()), + $is_team + ); + } + } else { + return false; + } + + return true; + } + + // Update the timestamp of the last download of current user (=tutor) + public function updateTutorDownloadTime() + { + $ilUser = $this->user; + $ilDB = $this->db; + + $exc_id = $this->assignment->getExerciseId(); + $ass_id = $this->assignment->getId(); + + foreach ($this->getUserIds() as $user_id) { + $ilDB->manipulateF( + "DELETE FROM exc_usr_tutor " . + "WHERE ass_id = %s AND usr_id = %s AND tutor_id = %s", + array("integer", "integer", "integer"), + array($ass_id, $user_id, $ilUser->getId()) + ); + + $ilDB->manipulateF( + "INSERT INTO exc_usr_tutor (ass_id, obj_id, usr_id, tutor_id, download_time) VALUES " . + "(%s, %s, %s, %s, %s)", + array("integer", "integer", "integer", "integer", "timestamp"), + array($ass_id, $exc_id, $user_id, $ilUser->getId(), ilUtil::now()) + ); + } + } + + protected function downloadSingleFile($a_user_id, $filename, $filetitle, $a_team_id) + { + if ($this->ass_type->isSubmissionAssignedToTeam()) { + $storage_id = $a_team_id; + } else { + $storage_id = $a_user_id; + } + + $filename = $this->initStorage()->getAbsoluteSubmissionPath() . + "/" . $storage_id . "/" . basename($filename); + + ilUtil::deliverFile($filename, $filetitle); + } + + protected function downloadMultipleFiles($a_filenames, $a_user_id, $a_multi_user = false) + { + $lng = $this->lng; + + $path = $this->initStorage()->getAbsoluteSubmissionPath(); + + $cdir = getcwd(); + + $zip = PATH_TO_ZIP; + $tmpdir = ilUtil::ilTempnam(); + $tmpfile = ilUtil::ilTempnam(); + $tmpzipfile = $tmpfile . ".zip"; + + ilUtil::makeDir($tmpdir); + chdir($tmpdir); + + $assTitle = ilExAssignment::lookupTitle($this->assignment->getId()); + $deliverFilename = str_replace(" ", "_", $assTitle); + if ($a_user_id > 0 && !$a_multi_user) { + $userName = ilObjUser::_lookupName($a_user_id); + $deliverFilename .= "_" . $userName["lastname"] . "_" . $userName["firstname"]; + } else { + $deliverFilename .= "_files"; + } + $orgDeliverFilename = trim($deliverFilename); + $deliverFilename = ilUtil::getASCIIFilename($orgDeliverFilename); + ilUtil::makeDir($tmpdir . "/" . $deliverFilename); + chdir($tmpdir . "/" . $deliverFilename); + + //copy all files to a temporary directory and remove them afterwards + $parsed_files = $duplicates = array(); + foreach ($a_filenames as $storage_id => $files) { + $pathname = $path . "/" . $storage_id; + + foreach ($files as $filename) { + // peer review masked filenames, see deliverReturnedFiles() + if (isset($filename["tgt"])) { + $newFilename = $filename["tgt"]; + $filename = $filename["src"]; + } else { + $late = $filename["late"]; + $filename = $filename["src"]; + + // remove timestamp + $newFilename = trim($filename); + $pos = strpos($newFilename, "_"); + if ($pos !== false) { + $newFilename = substr($newFilename, $pos + 1); + } + // #11070 + $chkName = strtolower($newFilename); + if (array_key_exists($chkName, $duplicates)) { + $suffix = strrpos($newFilename, "."); + $newFilename = substr($newFilename, 0, $suffix) . + " (" . (++$duplicates[$chkName]) . ")" . + substr($newFilename, $suffix); + } else { + $duplicates[$chkName] = 1; + } + + if ($late) { + $newFilename = $lng->txt("exc_late_submission") . " - " . + $newFilename; + } + } + + $newFilename = ilUtil::getASCIIFilename($newFilename); + $newFilename = $tmpdir . DIRECTORY_SEPARATOR . $deliverFilename . DIRECTORY_SEPARATOR . $newFilename; + // copy to temporal directory + $oldFilename = $pathname . DIRECTORY_SEPARATOR . $filename; + if (!copy($oldFilename, $newFilename)) { + echo 'Could not copy ' . $oldFilename . ' to ' . $newFilename; + } + touch($newFilename, filectime($oldFilename)); + $parsed_files[] = ilUtil::escapeShellArg($deliverFilename . DIRECTORY_SEPARATOR . basename($newFilename)); + } + } + + chdir($tmpdir); + $zipcmd = $zip . " " . ilUtil::escapeShellArg($tmpzipfile) . " " . join($parsed_files, " "); + + exec($zipcmd); + ilUtil::delDir($tmpdir); + + chdir($cdir); + ilUtil::deliverFile($tmpzipfile, $orgDeliverFilename . ".zip", "", false, true); + exit; + } + + /** + * Download all submitted files of an assignment (all user) + * @param $a_ass ilExAssignment + * @param $members array of user names, key is user id + * @param $to_path string + * @throws ilExerciseException + * @return void + */ + public static function downloadAllAssignmentFiles(ilExAssignment $a_ass, array $members, $to_path) + { + global $DIC; + + $lng = $DIC->language(); + + include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); + + $storage = new ilFSStorageExercise($a_ass->getExerciseId(), $a_ass->getId()); + $storage->create(); + + ksort($members); + //$savepath = $this->getExercisePath() . "/" . $this->obj_id . "/"; + $savepath = $storage->getAbsoluteSubmissionPath(); + $cdir = getcwd(); + + + // important check: if the directory does not exist + // ILIAS stays in the current directory (echoing only a warning) + // and the zip command below archives the whole ILIAS directory + // (including the data directory) and sends a mega file to the user :-o + if (!is_dir($savepath)) { + return; + } + // Safe mode fix + // chdir($this->getExercisePath()); + + $tmpdir = $storage->getTempPath(); + chdir($tmpdir); + $zip = PATH_TO_ZIP; + + // check free diskspace + $dirsize = 0; + foreach (array_keys($members) as $id) { + $directory = $savepath . DIRECTORY_SEPARATOR . $id; + $dirsize += ilUtil::dirsize($directory); + } + if ($dirsize > disk_free_space($tmpdir)) { + return -1; + } + + $ass_type = $a_ass->getType(); + + // copy all member directories to the temporary folder + // switch from id to member name and append the login if the member name is double + // ensure that no illegal filenames will be created + // remove timestamp from filename + if ($a_ass->hasTeam()) { + $team_dirs = array(); + $team_map = ilExAssignmentTeam::getAssignmentTeamMap($a_ass->getId()); + } + foreach ($members as $id => $item) { + $user = $item["name"]; + $user_files = $item["files"]; + $sourcedir = $savepath . DIRECTORY_SEPARATOR . $id; + if (!is_dir($sourcedir)) { + continue; + } + + // group by teams + $team_dir= ""; + if (is_array($team_map) && + array_key_exists($id, $team_map)) { + $team_id = $team_map[$id]; + if (!array_key_exists($team_id, $team_dirs)) { + $team_dir = $lng->txt("exc_team") . " " . $team_id; + ilUtil::makeDir($team_dir); + $team_dirs[$team_id] = $team_dir; + } + $team_dir = $team_dirs[$team_id] . DIRECTORY_SEPARATOR; + } + + if ($a_ass->getAssignmentType()->isSubmissionAssignedToTeam()) { + $targetdir = $team_dir . ilUtil::getASCIIFilename( + $item["name"] + ); + if ($targetdir == "") { + continue; + } + } else { + $targetdir = self::getDirectoryNameFromUserData($id); + if ($a_ass->getAssignmentType()->usesTeams()) { + $targetdir = $team_dir . $targetdir; + } + } + ilUtil::makeDir($targetdir); + + $sourcefiles = scandir($sourcedir); + $duplicates = array(); + foreach ($sourcefiles as $sourcefile) { + if ($sourcefile == "." || $sourcefile == "..") { + continue; + } + + $targetfile = trim(basename($sourcefile)); + $pos = strpos($targetfile, "_"); + if ($pos !== false) { + $targetfile= substr($targetfile, $pos + 1); } - } - ilUtil::makeDir($targetdir); - - $sourcefiles = scandir($sourcedir); - $duplicates = array(); - foreach ($sourcefiles as $sourcefile) { - if ($sourcefile == "." || $sourcefile == "..") - { - continue; - } - - $targetfile = trim(basename($sourcefile)); - $pos = strpos($targetfile, "_"); - if ($pos !== false) - { - $targetfile= substr($targetfile, $pos + 1); - } - - if ($a_ass->getAssignmentType()->getSubmissionType() == self::TYPE_REPO_OBJECT) - { - $obj_id = ilObject::_lookupObjId($targetfile); - $obj_type = ilObject::_lookupType($obj_id); - $targetfile = $obj_type."_".$obj_id.".zip"; - } - - - // #14536 - if(array_key_exists($targetfile, $duplicates)) - { - $suffix = strrpos($targetfile, "."); - $targetfile = substr($targetfile, 0, $suffix). - " (".(++$duplicates[$targetfile]).")". - substr($targetfile, $suffix); - } - else - { - $duplicates[$targetfile] = 1; - } - - // late submission? - if (is_array($user_files)) // see #23900 - { - foreach ($user_files as $file) - { - if (basename($file["filename"]) == $sourcefile) - { - if ($file["late"]) - { - $targetfile = $lng->txt("exc_late_submission") . " - " . - $targetfile; - } - break; - } - } - } - - $targetfile = ilUtil::getASCIIFilename($targetfile); - $targetfile = $targetdir.DIRECTORY_SEPARATOR.$targetfile; - $sourcefile = $sourcedir.DIRECTORY_SEPARATOR.$sourcefile; - - if (!copy ($sourcefile, $targetfile)) - { - include_once "Modules/Exercise/exceptions/class.ilExerciseException.php"; - throw new ilExerciseException("Could not copy ".basename($sourcefile)." to '".$targetfile."'."); - } - else - { - // preserve time stamp - touch($targetfile, filectime($sourcefile)); - - // blogs and portfolios are stored as zip and have to be unzipped - if($ass_type == ilExAssignment::TYPE_PORTFOLIO || - $ass_type == ilExAssignment::TYPE_BLOG) - { - ilUtil::unzip($targetfile); - unlink($targetfile); - } - } - - } - } - $tmpzipfile = ilUtil::getASCIIFilename($lng->txt("exc_ass_submission_zip")).".zip"; - // Safe mode fix - $zipcmd = $zip." -r ".ilUtil::escapeShellArg($tmpzipfile)." ."; - exec($zipcmd); - //$path_final_zip_file = $to_path.DIRECTORY_SEPARATOR."Submissions/".$tmpzipfile; - $path_final_zip_file = $to_path.DIRECTORY_SEPARATOR.$tmpzipfile; - - if(file_exists($tmpdir.DIRECTORY_SEPARATOR.$tmpzipfile)) - { - copy($tmpzipfile,$path_final_zip_file); - ilUtil::delDir($tmpdir); - - //unzip the submissions zip file.(decided to unzip to allow the excel link the files more obvious when blog/portfolio) - chdir($to_path); - //TODO Bug in ilUtil -> if flat unzip fails. We can get rid of creating Submissions directory - //ilUtil::unzip($path_final_zip_file,FALSE, TRUE); - ilUtil::unzip($path_final_zip_file); - unlink($path_final_zip_file); - } - - chdir($cdir); - - } - - - /** - * Get user/team where clause - * - * @param - * @return - */ - protected function getTableUserWhere($a_team_mode = false) - { - $ilDB = $this->db; - - if ($this->getAssignment()->getAssignmentType()->isSubmissionAssignedToTeam()) - { - $team_id = $this->getTeam()->getId(); - $where = " team_id = ".$ilDB->quote($team_id, "integer")." "; - } - else - { - if ($a_team_mode) - { - $where = " " . $ilDB->in("user_id", $this->getUserIds(), "", "integer") . " "; - } - else - { - $where = " user_id = ".$ilDB->quote($this->getUserId(), "integer"); - } - } - return $where; - } - - - /** - * Get the date of the last submission of a user for the assignment - * - * @return mixed false or mysql timestamp of last submission - */ - function getLastSubmission() - { - $ilDB = $this->db; - - $ilDB->setLimit(1); - - $q = "SELECT obj_id,user_id,ts FROM exc_returned". - " WHERE ass_id = ".$ilDB->quote($this->assignment->getId(), "integer"). - " AND ".$this->getTableUserWhere(true). - " AND (filename IS NOT NULL OR atext IS NOT NULL)". - " AND ts IS NOT NULL". - " ORDER BY ts DESC"; - $usr_set = $ilDB->query($q); - $array = $ilDB->fetchAssoc($usr_set); - return ilUtil::getMySQLTimestamp($array["ts"]); - } - - - // - // OBJECTS - // - - /** - * Add personal resource or repository object (ref_id) to assigment - * - * @param int $a_wsp_id - * @param string $a_text - * @return int - * @throws ilExerciseException - */ - function addResourceObject($a_wsp_id, $a_text = null) - { - $ilDB = $this->db; - - if ($this->getAssignment()->getAssignmentType()->isSubmissionAssignedToTeam()) - { - $user_id = 0; - $team_id = $this->getTeam()->getId(); - } - else - { - $user_id = $this->getUserId(); - $team_id = 0; - } - - // repository objects must be unique in submissions - // the same repo object cannot be used in different submissions or even different assignment/exercises - // why? -> the access handling would fail, since the access depends e.g. on teams or even phase of the - // assignment - if ($this->getAssignment()->getAssignmentType()->getSubmissionType() == ilExSubmission::TYPE_REPO_OBJECT) - { - $repos_ass_type_ids = $this->ass_types->getIdsForSubmissionType(ilExSubmission::TYPE_REPO_OBJECT); - $subs = $this->getSubmissionsForFilename($a_wsp_id, $repos_ass_type_ids); - if (count($subs) > 0) - { - throw new ilExerciseException("Repository object $a_wsp_id is already assigned to another assignment."); - } - } - - $next_id = $ilDB->nextId("exc_returned"); - $query = sprintf("INSERT INTO exc_returned ". - "(returned_id, obj_id, user_id, filetitle, ass_id, ts, atext, late, team_id) ". - "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)", - $ilDB->quote($next_id, "integer"), - $ilDB->quote($this->assignment->getExerciseId(), "integer"), - $ilDB->quote($user_id, "integer"), - $ilDB->quote($a_wsp_id, "text"), - $ilDB->quote($this->assignment->getId(), "integer"), - $ilDB->quote(ilUtil::now(), "timestamp"), - $ilDB->quote($a_text, "text"), - $ilDB->quote($this->isLate(), "integer"), - $ilDB->quote($team_id, "integer") - ); - $ilDB->manipulate($query); - - return $next_id; - } - - /** - * Remove personal resource to assigment - * - * @param int $a_returned_id - */ - public function deleteResourceObject($a_returned_id) - { - $ilDB = $this->db; - - $ilDB->manipulate("DELETE FROM exc_returned". - " WHERE obj_id = ".$ilDB->quote($this->assignment->getExerciseId(), "integer"). - " AND ".$this->getTableUserWhere(false). - " AND ass_id = ".$ilDB->quote($this->assignment->getId(), "integer"). - " AND returned_id = ".$ilDB->quote($a_returned_id, "integer")); - } - - /** - * Handle text assignment submissions - * - * @param string $a_text - * @return int - */ - function updateTextSubmission($a_text) - { - $ilDB = $this->db; - - $files = $this->getFiles(); - - // no text = remove submission - if(!trim($a_text)) - { - $this->deleteAllFiles(); - return; - } - - if(!$files) - { - return $this->addResourceObject("TEXT", $a_text); - } - else - { - $files = array_shift($files); - $id = $files["returned_id"]; - if($id) - { - $ilDB->manipulate("UPDATE exc_returned". - " SET atext = ".$ilDB->quote($a_text, "text"). - ", ts = ".$ilDB->quote(ilUtil::now(), "timestamp"). - ", late = ".$ilDB->quote($this->isLate(), "integer"). - " WHERE returned_id = ".$ilDB->quote($id, "integer")); - return $id; - } - } - } - - - // - // GUI helper - // - - // :TODO: - - public function getDownloadedFilesInfoForTableGUIS($a_parent_obj, $a_parent_cmd = null) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $result = array(); - $result["files"]["count"] = "---"; - - // submission: - // see if files have been resubmmited after solved - $last_sub = $this->getLastSubmission(); - if ($last_sub) - { - $last_sub = ilDatePresentation::formatDate(new ilDateTime($last_sub,IL_CAL_DATETIME)); - } - else - { - $last_sub = "---"; - } - /* #13741 - status_time has been reduced to grading (mark/status) - if (self::lookupUpdatedSubmission($a_ass_id, $a_user_id) == 1) - { - $last_sub = "".$last_sub.""; - } - */ - $result["last_submission"]["txt"] = $lng->txt("exc_last_submission"); - $result["last_submission"]["value"] = $last_sub; - - // #16994 - $ilCtrl->setParameterByClass("ilexsubmissionfilegui", "member_id", $this->getUserId()); - - // assignment type specific - switch($this->assignment->getType()) - { - case ilExAssignment::TYPE_UPLOAD_TEAM: - // data is merged by team - see above - // fallthrough - - case ilExAssignment::TYPE_UPLOAD: - $all_files = $this->getFiles(); - $late_files = 0; - foreach($all_files as $file) - { - if($file["late"]) - { - $late_files++; - } - } - - // nr of submitted files - $result["files"]["txt"] = $lng->txt("exc_files_returned"); - if ($late_files) - { - $result["files"]["txt"].= ' - '.$lng->txt("exc_late_submission")." (".$late_files.")"; - } - $sub_cnt = count($all_files); - $new = $this->lookupNewFiles(); - if (count($new) > 0) - { - $sub_cnt.= " ".sprintf($lng->txt("cnt_new"),count($new)); - } - - $result["files"]["count"] = $sub_cnt; - - // download command - if ($sub_cnt > 0) - { - $result["files"]["download_url"] = - $ilCtrl->getLinkTargetByClass("ilexsubmissionfilegui", "downloadReturned"); - - if (count($new) <= 0) - { - $result["files"]["download_txt"] = $lng->txt("exc_tbl_action_download_files"); - } - else - { - $result["files"]["download_txt"] = $lng->txt("exc_tbl_action_download_all_files"); - } - - // download new files only - if (count($new) > 0) - { - $result["files"]["download_new_url"] = - $ilCtrl->getLinkTargetByClass("ilexsubmissionfilegui", "downloadNewReturned"); - - $result["files"]["download_new_txt"] = $lng->txt("exc_tbl_action_download_new_files"); - } - } - break; - - case ilExAssignment::TYPE_BLOG: - $result["files"]["txt"] =$lng->txt("exc_blog_returned"); - $blogs = $this->getFiles(); - if($blogs) - { - $blogs = array_pop($blogs); - if($blogs && substr($blogs["filename"], -1) != "/") - { - if($blogs["late"]) - { - $result["files"]["txt"].= ' - '.$lng->txt("exc_late_submission").""; - } - - $result["files"]["count"] = 1; - - $result["files"]["download_url"] = - $ilCtrl->getLinkTargetByClass("ilexsubmissionfilegui", "downloadReturned"); - - $result["files"]["download_txt"] = $lng->txt("exc_tbl_action_download_files"); - } - } - break; - - case ilExAssignment::TYPE_PORTFOLIO: - $result["files"]["txt"] = $lng->txt("exc_portfolio_returned"); - $portfolios = $this->getFiles(); - if($portfolios) - { - $portfolios = array_pop($portfolios); - if($portfolios && substr($portfolios["filename"], -1) != "/") - { - if($portfolios["late"]) - { - $result["files"]["txt"].= ' - '.$lng->txt("exc_late_submission").""; - } - - $result["files"]["count"] = 1; - - $result["files"]["download_url"] = - $ilCtrl->getLinkTargetByClass("ilexsubmissionfilegui", "downloadReturned"); - - $result["files"]["download_txt"] = $lng->txt("exc_tbl_action_download_files"); - } - } - break; - - case ilExAssignment::TYPE_TEXT: - $result["files"]["txt"] = $lng->txt("exc_files_returned_text"); - $files = $this->getFiles(); - if($files) - { - $result["files"]["count"] = 1; - - $files = array_shift($files); - if(trim($files["atext"])) - { - if($files["late"]) - { - $result["files"]["txt"].= ' - '.$lng->txt("exc_late_submission").""; - } - - $result["files"]["download_url"] = - $ilCtrl->getLinkTargetByClass("ilexsubmissiontextgui", "showAssignmentText"); - - $result["files"]["download_txt"] = $lng->txt("exc_tbl_action_text_assignment_show"); - } - } - break; - - case ilExAssignment::TYPE_WIKI_TEAM: - $result["files"]["txt"] = $lng->txt("exc_wiki_returned"); - $objs = $this->getFiles(); - if($objs) - { - $objs = array_pop($objs); - if($objs && substr($objs["filename"], -1) != "/") - { - if($objs["late"]) - { - $result["files"]["txt"].= ' - '.$lng->txt("exc_late_submission").""; - } - - $result["files"]["count"] = 1; - - $result["files"]["download_url"] = - $ilCtrl->getLinkTargetByClass("ilexsubmissionfilegui", "downloadReturned"); - - $result["files"]["download_txt"] = $lng->txt("exc_tbl_action_download_files"); - } - } - break; - } - - $ilCtrl->setParameterByClass("ilexsubmissionfilegui", "member_id", ""); - - return $result; - } - - /** - * Get assignment return entries for a filename - * - * @param string $a_filename - * @param int[] $a_assignment_types - * @return array - */ - public static function getSubmissionsForFilename($a_filename, $a_assignment_types = array()) - { - global $DIC; - - $db = $DIC->database(); - - $query = "SELECT * FROM exc_returned r LEFT JOIN exc_assignment a". - " ON (r.ass_id = a.id) ". - " WHERE r.filetitle = ".$db->quote($a_filename, "string"); - - if (is_array($a_assignment_types) && count($a_assignment_types) > 0) - { - $query.= " AND ".$db->in("a.type", $a_assignment_types, false, "integer"); - } - - $set = $db->query($query); - $rets = array(); - while ($rec = $db->fetchAssoc($set)) - { - $rets[] = $rec; - } - - - return $rets; - } - - /* - * @param $a_user_id - * @return string - */ - static function getDirectoryNameFromUserData($a_user_id) - { - $userName = ilObjUser::_lookupName($a_user_id); - $targetdir = ilUtil::getASCIIFilename( - trim($userName["lastname"])."_". - trim($userName["firstname"])."_". - trim($userName["login"])."_". - $userName["user_id"] - ); - - return $targetdir; - } - - /** - * @param $a_exercise_id - * @param $a_ass_id - * @return array - */ - public static function getAssignmentParticipants(int $a_exercise_id, int $a_ass_id) : array - { - global $DIC; - - $ilDB = $DIC->database(); - - $participants = array(); - $query = "SELECT user_id FROM exc_returned WHERE ass_id = ". - $ilDB->quote($a_ass_id, "integer") . - " AND obj_id = ". - $ilDB->quote($a_exercise_id, "integer"); - - $res = $ilDB->query($query); - - while($row = $ilDB->fetchAssoc($res)) - { - $participants[] = $row['user_id']; - } - - return $participants; - } -} + if ($a_ass->getAssignmentType()->getSubmissionType() == self::TYPE_REPO_OBJECT) { + $obj_id = ilObject::_lookupObjId($targetfile); + $obj_type = ilObject::_lookupType($obj_id); + $targetfile = $obj_type . "_" . $obj_id . ".zip"; + } + + + // #14536 + if (array_key_exists($targetfile, $duplicates)) { + $suffix = strrpos($targetfile, "."); + $targetfile = substr($targetfile, 0, $suffix) . + " (" . (++$duplicates[$targetfile]) . ")" . + substr($targetfile, $suffix); + } else { + $duplicates[$targetfile] = 1; + } + + // late submission? + if (is_array($user_files)) { // see #23900 + foreach ($user_files as $file) { + if (basename($file["filename"]) == $sourcefile) { + if ($file["late"]) { + $targetfile = $lng->txt("exc_late_submission") . " - " . + $targetfile; + } + break; + } + } + } + + $targetfile = ilUtil::getASCIIFilename($targetfile); + $targetfile = $targetdir . DIRECTORY_SEPARATOR . $targetfile; + $sourcefile = $sourcedir . DIRECTORY_SEPARATOR . $sourcefile; + + if (!copy($sourcefile, $targetfile)) { + include_once "Modules/Exercise/exceptions/class.ilExerciseException.php"; + throw new ilExerciseException("Could not copy " . basename($sourcefile) . " to '" . $targetfile . "'."); + } else { + // preserve time stamp + touch($targetfile, filectime($sourcefile)); + + // blogs and portfolios are stored as zip and have to be unzipped + if ($ass_type == ilExAssignment::TYPE_PORTFOLIO || + $ass_type == ilExAssignment::TYPE_BLOG) { + ilUtil::unzip($targetfile); + unlink($targetfile); + } + } + } + } + $tmpzipfile = ilUtil::getASCIIFilename($lng->txt("exc_ass_submission_zip")) . ".zip"; + // Safe mode fix + $zipcmd = $zip . " -r " . ilUtil::escapeShellArg($tmpzipfile) . " ."; + exec($zipcmd); + //$path_final_zip_file = $to_path.DIRECTORY_SEPARATOR."Submissions/".$tmpzipfile; + $path_final_zip_file = $to_path . DIRECTORY_SEPARATOR . $tmpzipfile; + + if (file_exists($tmpdir . DIRECTORY_SEPARATOR . $tmpzipfile)) { + copy($tmpzipfile, $path_final_zip_file); + ilUtil::delDir($tmpdir); + + //unzip the submissions zip file.(decided to unzip to allow the excel link the files more obvious when blog/portfolio) + chdir($to_path); + //TODO Bug in ilUtil -> if flat unzip fails. We can get rid of creating Submissions directory + //ilUtil::unzip($path_final_zip_file,FALSE, TRUE); + ilUtil::unzip($path_final_zip_file); + unlink($path_final_zip_file); + } + + chdir($cdir); + } + + + /** + * Get user/team where clause + * + * @param + * @return + */ + protected function getTableUserWhere($a_team_mode = false) + { + $ilDB = $this->db; + + if ($this->getAssignment()->getAssignmentType()->isSubmissionAssignedToTeam()) { + $team_id = $this->getTeam()->getId(); + $where = " team_id = " . $ilDB->quote($team_id, "integer") . " "; + } else { + if ($a_team_mode) { + $where = " " . $ilDB->in("user_id", $this->getUserIds(), "", "integer") . " "; + } else { + $where = " user_id = " . $ilDB->quote($this->getUserId(), "integer"); + } + } + return $where; + } + + + /** + * Get the date of the last submission of a user for the assignment + * + * @return mixed false or mysql timestamp of last submission + */ + public function getLastSubmission() + { + $ilDB = $this->db; + + $ilDB->setLimit(1); + + $q = "SELECT obj_id,user_id,ts FROM exc_returned" . + " WHERE ass_id = " . $ilDB->quote($this->assignment->getId(), "integer") . + " AND " . $this->getTableUserWhere(true) . + " AND (filename IS NOT NULL OR atext IS NOT NULL)" . + " AND ts IS NOT NULL" . + " ORDER BY ts DESC"; + $usr_set = $ilDB->query($q); + $array = $ilDB->fetchAssoc($usr_set); + return ilUtil::getMySQLTimestamp($array["ts"]); + } + + + // + // OBJECTS + // + + /** + * Add personal resource or repository object (ref_id) to assigment + * + * @param int $a_wsp_id + * @param string $a_text + * @return int + * @throws ilExerciseException + */ + public function addResourceObject($a_wsp_id, $a_text = null) + { + $ilDB = $this->db; + + if ($this->getAssignment()->getAssignmentType()->isSubmissionAssignedToTeam()) { + $user_id = 0; + $team_id = $this->getTeam()->getId(); + } else { + $user_id = $this->getUserId(); + $team_id = 0; + } + + // repository objects must be unique in submissions + // the same repo object cannot be used in different submissions or even different assignment/exercises + // why? -> the access handling would fail, since the access depends e.g. on teams or even phase of the + // assignment + if ($this->getAssignment()->getAssignmentType()->getSubmissionType() == ilExSubmission::TYPE_REPO_OBJECT) { + $repos_ass_type_ids = $this->ass_types->getIdsForSubmissionType(ilExSubmission::TYPE_REPO_OBJECT); + $subs = $this->getSubmissionsForFilename($a_wsp_id, $repos_ass_type_ids); + if (count($subs) > 0) { + throw new ilExerciseException("Repository object $a_wsp_id is already assigned to another assignment."); + } + } + + $next_id = $ilDB->nextId("exc_returned"); + $query = sprintf( + "INSERT INTO exc_returned " . + "(returned_id, obj_id, user_id, filetitle, ass_id, ts, atext, late, team_id) " . + "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)", + $ilDB->quote($next_id, "integer"), + $ilDB->quote($this->assignment->getExerciseId(), "integer"), + $ilDB->quote($user_id, "integer"), + $ilDB->quote($a_wsp_id, "text"), + $ilDB->quote($this->assignment->getId(), "integer"), + $ilDB->quote(ilUtil::now(), "timestamp"), + $ilDB->quote($a_text, "text"), + $ilDB->quote($this->isLate(), "integer"), + $ilDB->quote($team_id, "integer") + ); + $ilDB->manipulate($query); + + return $next_id; + } + + /** + * Remove personal resource to assigment + * + * @param int $a_returned_id + */ + public function deleteResourceObject($a_returned_id) + { + $ilDB = $this->db; + + $ilDB->manipulate("DELETE FROM exc_returned" . + " WHERE obj_id = " . $ilDB->quote($this->assignment->getExerciseId(), "integer") . + " AND " . $this->getTableUserWhere(false) . + " AND ass_id = " . $ilDB->quote($this->assignment->getId(), "integer") . + " AND returned_id = " . $ilDB->quote($a_returned_id, "integer")); + } + + /** + * Handle text assignment submissions + * + * @param string $a_text + * @return int + */ + public function updateTextSubmission($a_text) + { + $ilDB = $this->db; + + $files = $this->getFiles(); + + // no text = remove submission + if (!trim($a_text)) { + $this->deleteAllFiles(); + return; + } + + if (!$files) { + return $this->addResourceObject("TEXT", $a_text); + } else { + $files = array_shift($files); + $id = $files["returned_id"]; + if ($id) { + $ilDB->manipulate("UPDATE exc_returned" . + " SET atext = " . $ilDB->quote($a_text, "text") . + ", ts = " . $ilDB->quote(ilUtil::now(), "timestamp") . + ", late = " . $ilDB->quote($this->isLate(), "integer") . + " WHERE returned_id = " . $ilDB->quote($id, "integer")); + return $id; + } + } + } + + + // + // GUI helper + // + + // :TODO: + + public function getDownloadedFilesInfoForTableGUIS($a_parent_obj, $a_parent_cmd = null) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $result = array(); + $result["files"]["count"] = "---"; + + // submission: + // see if files have been resubmmited after solved + $last_sub = $this->getLastSubmission(); + if ($last_sub) { + $last_sub = ilDatePresentation::formatDate(new ilDateTime($last_sub, IL_CAL_DATETIME)); + } else { + $last_sub = "---"; + } + /* #13741 - status_time has been reduced to grading (mark/status) + if (self::lookupUpdatedSubmission($a_ass_id, $a_user_id) == 1) + { + $last_sub = "".$last_sub.""; + } + */ + $result["last_submission"]["txt"] = $lng->txt("exc_last_submission"); + $result["last_submission"]["value"] = $last_sub; + + // #16994 + $ilCtrl->setParameterByClass("ilexsubmissionfilegui", "member_id", $this->getUserId()); + + // assignment type specific + switch ($this->assignment->getType()) { + case ilExAssignment::TYPE_UPLOAD_TEAM: + // data is merged by team - see above + // fallthrough + + case ilExAssignment::TYPE_UPLOAD: + $all_files = $this->getFiles(); + $late_files = 0; + foreach ($all_files as $file) { + if ($file["late"]) { + $late_files++; + } + } + + // nr of submitted files + $result["files"]["txt"] = $lng->txt("exc_files_returned"); + if ($late_files) { + $result["files"]["txt"].= ' - ' . $lng->txt("exc_late_submission") . " (" . $late_files . ")"; + } + $sub_cnt = count($all_files); + $new = $this->lookupNewFiles(); + if (count($new) > 0) { + $sub_cnt.= " " . sprintf($lng->txt("cnt_new"), count($new)); + } + + $result["files"]["count"] = $sub_cnt; + + // download command + if ($sub_cnt > 0) { + $result["files"]["download_url"] = + $ilCtrl->getLinkTargetByClass("ilexsubmissionfilegui", "downloadReturned"); + + if (count($new) <= 0) { + $result["files"]["download_txt"] = $lng->txt("exc_tbl_action_download_files"); + } else { + $result["files"]["download_txt"] = $lng->txt("exc_tbl_action_download_all_files"); + } + + // download new files only + if (count($new) > 0) { + $result["files"]["download_new_url"] = + $ilCtrl->getLinkTargetByClass("ilexsubmissionfilegui", "downloadNewReturned"); + + $result["files"]["download_new_txt"] = $lng->txt("exc_tbl_action_download_new_files"); + } + } + break; + + case ilExAssignment::TYPE_BLOG: + $result["files"]["txt"] =$lng->txt("exc_blog_returned"); + $blogs = $this->getFiles(); + if ($blogs) { + $blogs = array_pop($blogs); + if ($blogs && substr($blogs["filename"], -1) != "/") { + if ($blogs["late"]) { + $result["files"]["txt"].= ' - ' . $lng->txt("exc_late_submission") . ""; + } + + $result["files"]["count"] = 1; + + $result["files"]["download_url"] = + $ilCtrl->getLinkTargetByClass("ilexsubmissionfilegui", "downloadReturned"); + + $result["files"]["download_txt"] = $lng->txt("exc_tbl_action_download_files"); + } + } + break; + + case ilExAssignment::TYPE_PORTFOLIO: + $result["files"]["txt"] = $lng->txt("exc_portfolio_returned"); + $portfolios = $this->getFiles(); + if ($portfolios) { + $portfolios = array_pop($portfolios); + if ($portfolios && substr($portfolios["filename"], -1) != "/") { + if ($portfolios["late"]) { + $result["files"]["txt"].= ' - ' . $lng->txt("exc_late_submission") . ""; + } + + $result["files"]["count"] = 1; + + $result["files"]["download_url"] = + $ilCtrl->getLinkTargetByClass("ilexsubmissionfilegui", "downloadReturned"); + + $result["files"]["download_txt"] = $lng->txt("exc_tbl_action_download_files"); + } + } + break; + + case ilExAssignment::TYPE_TEXT: + $result["files"]["txt"] = $lng->txt("exc_files_returned_text"); + $files = $this->getFiles(); + if ($files) { + $result["files"]["count"] = 1; + + $files = array_shift($files); + if (trim($files["atext"])) { + if ($files["late"]) { + $result["files"]["txt"].= ' - ' . $lng->txt("exc_late_submission") . ""; + } + + $result["files"]["download_url"] = + $ilCtrl->getLinkTargetByClass("ilexsubmissiontextgui", "showAssignmentText"); + + $result["files"]["download_txt"] = $lng->txt("exc_tbl_action_text_assignment_show"); + } + } + break; + + case ilExAssignment::TYPE_WIKI_TEAM: + $result["files"]["txt"] = $lng->txt("exc_wiki_returned"); + $objs = $this->getFiles(); + if ($objs) { + $objs = array_pop($objs); + if ($objs && substr($objs["filename"], -1) != "/") { + if ($objs["late"]) { + $result["files"]["txt"].= ' - ' . $lng->txt("exc_late_submission") . ""; + } + + $result["files"]["count"] = 1; + + $result["files"]["download_url"] = + $ilCtrl->getLinkTargetByClass("ilexsubmissionfilegui", "downloadReturned"); + + $result["files"]["download_txt"] = $lng->txt("exc_tbl_action_download_files"); + } + } + break; + } + + $ilCtrl->setParameterByClass("ilexsubmissionfilegui", "member_id", ""); + + return $result; + } + + /** + * Get assignment return entries for a filename + * + * @param string $a_filename + * @param int[] $a_assignment_types + * @return array + */ + public static function getSubmissionsForFilename($a_filename, $a_assignment_types = array()) + { + global $DIC; + + $db = $DIC->database(); + + $query = "SELECT * FROM exc_returned r LEFT JOIN exc_assignment a" . + " ON (r.ass_id = a.id) " . + " WHERE r.filetitle = " . $db->quote($a_filename, "string"); + + if (is_array($a_assignment_types) && count($a_assignment_types) > 0) { + $query.= " AND " . $db->in("a.type", $a_assignment_types, false, "integer"); + } + + $set = $db->query($query); + $rets = array(); + while ($rec = $db->fetchAssoc($set)) { + $rets[] = $rec; + } + + + return $rets; + } + + /* + * @param $a_user_id + * @return string + */ + public static function getDirectoryNameFromUserData($a_user_id) + { + $userName = ilObjUser::_lookupName($a_user_id); + $targetdir = ilUtil::getASCIIFilename( + trim($userName["lastname"]) . "_" . + trim($userName["firstname"]) . "_" . + trim($userName["login"]) . "_" . + $userName["user_id"] + ); + + return $targetdir; + } + + /** + * @param $a_exercise_id + * @param $a_ass_id + * @return array + */ + public static function getAssignmentParticipants(int $a_exercise_id, int $a_ass_id) : array + { + global $DIC; + + $ilDB = $DIC->database(); + + $participants = array(); + $query = "SELECT user_id FROM exc_returned WHERE ass_id = " . + $ilDB->quote($a_ass_id, "integer") . + " AND obj_id = " . + $ilDB->quote($a_exercise_id, "integer"); + + $res = $ilDB->query($query); + + while ($row = $ilDB->fetchAssoc($res)) { + $participants[] = $row['user_id']; + } + + return $participants; + } +} diff --git a/Modules/Exercise/classes/class.ilExSubmissionBaseGUI.php b/Modules/Exercise/classes/class.ilExSubmissionBaseGUI.php index 24f9e8f7087cdcea0c61688561470fdfb49e47a7..3a73ac70e6bb25fbce20ec6a180b1e53b7b77876 100644 --- a/Modules/Exercise/classes/class.ilExSubmissionBaseGUI.php +++ b/Modules/Exercise/classes/class.ilExSubmissionBaseGUI.php @@ -3,7 +3,7 @@ /** * Exercise submission base gui - * + * * This is an abstract base class for all types of submissions * * @author Jörg Lützenkirchen @@ -11,117 +11,120 @@ */ abstract class ilExSubmissionBaseGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTabsGUI - */ - protected $tabs_gui; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilTabsGUI + */ + protected $tabs_gui; - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilLanguage + */ + protected $lng; - protected $exercise; // [ilObjExercise] - protected $submission; // [ilExSubmission] - protected $assignment; // [ilExAssignment] + /** + * @var ilTemplate + */ + protected $tpl; - /** - * @var ilExAssignmentTypesGUI - */ - protected $type_guis; - - public function __construct(ilObjExercise $a_exercise, ilExSubmission $a_submission) - { - global $DIC; + protected $exercise; // [ilObjExercise] + protected $submission; // [ilExSubmission] + protected $assignment; // [ilExAssignment] - $ilCtrl = $DIC->ctrl(); - $ilTabs = $DIC->tabs(); - $lng = $DIC->language(); - $tpl = $DIC["tpl"]; - - $this->exercise = $a_exercise; - $this->submission = $a_submission; - $this->assignment = $a_submission->getAssignment(); - - // :TODO: - $this->ctrl = $ilCtrl; - $this->tabs_gui = $ilTabs; - $this->lng = $lng; - $this->tpl = $tpl; + /** + * @var ilExAssignmentTypesGUI + */ + protected $type_guis; + + public function __construct(ilObjExercise $a_exercise, ilExSubmission $a_submission) + { + global $DIC; - include_once("./Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssignmentTypesGUI.php"); - $this->type_guis = ilExAssignmentTypesGUI::getInstance(); + $ilCtrl = $DIC->ctrl(); + $ilTabs = $DIC->tabs(); + $lng = $DIC->language(); + $tpl = $DIC["tpl"]; + + $this->exercise = $a_exercise; + $this->submission = $a_submission; + $this->assignment = $a_submission->getAssignment(); + + // :TODO: + $this->ctrl = $ilCtrl; + $this->tabs_gui = $ilTabs; + $this->lng = $lng; + $this->tpl = $tpl; - } - - abstract public static function getOverviewContent(ilInfoScreenGUI $a_info, ilExSubmission $a_submission); - - protected function handleTabs() - { - $this->tabs_gui->clearTargets(); - $this->tabs_gui->setBackTarget($this->lng->txt("back"), - $this->ctrl->getLinkTarget($this, "returnToParent")); - - $this->tabs_gui->addTab("submission", $this->lng->txt("exc_submission"), - $this->ctrl->getLinkTarget($this, "")); - $this->tabs_gui->activateTab("submission"); - - if($this->assignment->hasTeam()) - { - include_once "Modules/Exercise/classes/class.ilExSubmissionTeamGUI.php"; - ilExSubmissionTeamGUI::handleTabs(); - } - } - - function returnToParentObject() - { - $this->ctrl->returnToParent($this); - } - - - // - // RETURNED/EXERCISE STATUS - // - - protected function handleNewUpload($a_no_notifications = false) - { - $has_submitted = $this->submission->hasSubmitted(); - - $this->exercise->processExerciseStatus( - $this->assignment, - $this->submission->getUserIds(), - $has_submitted, - $this->submission->validatePeerReviews()); - - if($has_submitted && - !$a_no_notifications) - { - include_once "./Services/Notification/classes/class.ilNotification.php"; - $users = ilNotification::getNotificationsForObject(ilNotification::TYPE_EXERCISE_SUBMISSION, $this->exercise->getId()); + include_once("./Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssignmentTypesGUI.php"); + $this->type_guis = ilExAssignmentTypesGUI::getInstance(); + } + + abstract public static function getOverviewContent(ilInfoScreenGUI $a_info, ilExSubmission $a_submission); + + protected function handleTabs() + { + $this->tabs_gui->clearTargets(); + $this->tabs_gui->setBackTarget( + $this->lng->txt("back"), + $this->ctrl->getLinkTarget($this, "returnToParent") + ); + + $this->tabs_gui->addTab( + "submission", + $this->lng->txt("exc_submission"), + $this->ctrl->getLinkTarget($this, "") + ); + $this->tabs_gui->activateTab("submission"); + + if ($this->assignment->hasTeam()) { + include_once "Modules/Exercise/classes/class.ilExSubmissionTeamGUI.php"; + ilExSubmissionTeamGUI::handleTabs(); + } + } + + public function returnToParentObject() + { + $this->ctrl->returnToParent($this); + } + + + // + // RETURNED/EXERCISE STATUS + // + + protected function handleNewUpload($a_no_notifications = false) + { + $has_submitted = $this->submission->hasSubmitted(); + + $this->exercise->processExerciseStatus( + $this->assignment, + $this->submission->getUserIds(), + $has_submitted, + $this->submission->validatePeerReviews() + ); + + if ($has_submitted && + !$a_no_notifications) { + include_once "./Services/Notification/classes/class.ilNotification.php"; + $users = ilNotification::getNotificationsForObject(ilNotification::TYPE_EXERCISE_SUBMISSION, $this->exercise->getId()); - include_once "./Modules/Exercise/classes/class.ilExerciseMailNotification.php"; - $not = new ilExerciseMailNotification(); - $not->setType(ilExerciseMailNotification::TYPE_SUBMISSION_UPLOAD); - $not->setAssignmentId($this->assignment->getId()); - $not->setRefId($this->exercise->getRefId()); - $not->setRecipients($users); - $not->send(); - } - } - - protected function handleRemovedUpload() - { - // #16532 - always send notifications - $this->handleNewUpload(); - } + include_once "./Modules/Exercise/classes/class.ilExerciseMailNotification.php"; + $not = new ilExerciseMailNotification(); + $not->setType(ilExerciseMailNotification::TYPE_SUBMISSION_UPLOAD); + $not->setAssignmentId($this->assignment->getId()); + $not->setRefId($this->exercise->getRefId()); + $not->setRecipients($users); + $not->send(); + } + } + + protected function handleRemovedUpload() + { + // #16532 - always send notifications + $this->handleNewUpload(); + } } diff --git a/Modules/Exercise/classes/class.ilExSubmissionFileGUI.php b/Modules/Exercise/classes/class.ilExSubmissionFileGUI.php index 1f9f888d25623e95cbd06d8aca51ccd4e329bc84..61f219b54a0a4d5d491b42ea564f4fc25c909176 100644 --- a/Modules/Exercise/classes/class.ilExSubmissionFileGUI.php +++ b/Modules/Exercise/classes/class.ilExSubmissionFileGUI.php @@ -5,499 +5,453 @@ * File-based submissions * * @author Jörg Lützenkirchen - * - * @ilCtrl_Calls ilExSubmissionFileGUI: + * + * @ilCtrl_Calls ilExSubmissionFileGUI: * @ingroup ModulesExercise */ class ilExSubmissionFileGUI extends ilExSubmissionBaseGUI -{ - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilHelpGUI - */ - protected $help; - - /** - * @var ilObjUser - */ - protected $user; - - - /** - * Constructor - */ - function __construct(ilObjExercise $a_exercise, ilExSubmission $a_submission) - { - global $DIC; - - parent::__construct($a_exercise, $a_submission); - - $this->toolbar = $DIC->toolbar(); - $this->help = $DIC["ilHelp"]; - $this->user = $DIC->user(); - } - - public function executeCommand() - { - $ilCtrl = $this->ctrl; - - if(!$this->submission->canView()) - { - $this->returnToParentObject(); - } - - $class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd("submissionScreen"); - - switch($class) - { - default: - $this->{$cmd."Object"}(); - break; - } - } - - public static function getOverviewContent(ilInfoScreenGUI $a_info, ilExSubmission $a_submission) - { - global $DIC; - - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - - $titles = array(); - foreach($a_submission->getFiles() as $file) - { - $titles[] = $file["filetitle"]; - } - $files_str = implode($titles, "
"); - if ($files_str == "") - { - $files_str = $lng->txt("message_no_delivered_files"); - } - - // no team == no submission - if(!$a_submission->hasNoTeamYet()) - { - if ($a_submission->canSubmit()) - { - $title = (count($titles) == 0 - ? $lng->txt("exc_hand_in") - : $lng->txt("exc_edit_submission")); - - $button = ilLinkButton::getInstance(); - $button->setPrimary(true); - $button->setCaption($title, false); - $button->setUrl($ilCtrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExSubmissionFileGUI"), "submissionScreen")); - $files_str.= "

".$button->render(); - } - else - { - if (count($titles) > 0) - { - $button = ilLinkButton::getInstance(); - $button->setCaption("already_delivered_files"); - $button->setUrl($ilCtrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExSubmissionFileGUI"), "submissionScreen")); - $files_str.= "

".$button->render(); - } - } - } - - $a_info->addProperty($lng->txt("exc_files_returned"), $files_str); - } - - /** - * Displays a form which allows members to deliver their solutions - * - * @access public - */ - function submissionScreenObject() - { - $ilToolbar = $this->toolbar; - $ilHelp = $this->help; - $ilUser = $this->user; - - - $this->handleTabs(); - - $ilHelp->setScreenIdComponent("exc"); - $ilHelp->setScreenId("submissions"); - - if (!$this->submission->canSubmit()) - { - ilUtil::sendInfo($this->lng->txt("exercise_time_over")); - } - else - { - $max_files = $this->submission->getAssignment()->getMaxFile(); - - if($this->submission->canAddFile()) - { - // #15883 - extended deadline warning - $deadline = $this->assignment->getPersonalDeadline($ilUser->getId()); - if($deadline && - time() > $deadline) - { - $dl = ilDatePresentation::formatDate(new ilDateTime($deadline, IL_CAL_UNIX)); - $dl = sprintf($this->lng->txt("exc_late_submission_warning"), $dl); - $dl = ''.$dl.''; - $ilToolbar->addText($dl); - } - - $ilToolbar->addButton($this->lng->txt("file_add"), - $this->ctrl->getLinkTarget($this, "uploadForm")); - - if(!$max_files || - $max_files > 1) - { - $ilToolbar->addButton($this->lng->txt("header_zip"), - $this->ctrl->getLinkTarget($this, "uploadZipForm")); - } - } - - if($max_files) - { - ilUtil::sendInfo(sprintf($this->lng->txt("exc_max_file_reached"), $max_files)); - } - } - - include_once("./Modules/Exercise/classes/class.ilExcDeliveredFilesTableGUI.php"); - $tab = new ilExcDeliveredFilesTableGUI($this, "submissionScreen", $this->submission); - $this->tpl->setContent($tab->getHTML()); - } - - /** - * Display form for single file upload - */ - public function uploadFormObject(ilPropertyFormGUI $a_form = null) - { - if (!$this->submission->canSubmit()) - { - $this->ctrl->redirect($this, "submissionScreen"); - } - - $this->tabs_gui->clearTargets(); - $this->tabs_gui->setBackTarget($this->lng->txt("back"), - $this->ctrl->getLinkTarget($this, "submissionScreen")); - - $ilHelp = $this->help; - $ilHelp->setScreenIdComponent("exc"); - $ilHelp->setScreenId("upload_submission"); - - if(!$a_form) - { - $a_form = $this->initUploadForm(); - } - $this->tpl->setContent($a_form->getHTML()); - } - - /** - * Display form for zip file upload - */ - public function uploadZipFormObject(ilPropertyFormGUI $a_form = null) - { - if (!$this->submission->canSubmit()) - { - $this->ctrl->redirect($this, "submissionScreen"); - } - - $this->tabs_gui->clearTargets(); - $this->tabs_gui->setBackTarget($this->lng->txt("back"), - $this->ctrl->getLinkTarget($this, "submissionScreen")); - - if(!$a_form) - { - $a_form = $this->initZipUploadForm(); - } - $this->tpl->setContent($a_form->getHTML()); - } +{ + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var ilObjUser + */ + protected $user; + + + /** + * Constructor + */ + public function __construct(ilObjExercise $a_exercise, ilExSubmission $a_submission) + { + global $DIC; + + parent::__construct($a_exercise, $a_submission); + + $this->toolbar = $DIC->toolbar(); + $this->help = $DIC["ilHelp"]; + $this->user = $DIC->user(); + } + + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + if (!$this->submission->canView()) { + $this->returnToParentObject(); + } + + $class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd("submissionScreen"); + + switch ($class) { + default: + $this->{$cmd . "Object"}(); + break; + } + } + + public static function getOverviewContent(ilInfoScreenGUI $a_info, ilExSubmission $a_submission) + { + global $DIC; + + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + + $titles = array(); + foreach ($a_submission->getFiles() as $file) { + $titles[] = $file["filetitle"]; + } + $files_str = implode($titles, "
"); + if ($files_str == "") { + $files_str = $lng->txt("message_no_delivered_files"); + } + + // no team == no submission + if (!$a_submission->hasNoTeamYet()) { + if ($a_submission->canSubmit()) { + $title = (count($titles) == 0 + ? $lng->txt("exc_hand_in") + : $lng->txt("exc_edit_submission")); + + $button = ilLinkButton::getInstance(); + $button->setPrimary(true); + $button->setCaption($title, false); + $button->setUrl($ilCtrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExSubmissionFileGUI"), "submissionScreen")); + $files_str.= "

" . $button->render(); + } else { + if (count($titles) > 0) { + $button = ilLinkButton::getInstance(); + $button->setCaption("already_delivered_files"); + $button->setUrl($ilCtrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExSubmissionFileGUI"), "submissionScreen")); + $files_str.= "

" . $button->render(); + } + } + } + + $a_info->addProperty($lng->txt("exc_files_returned"), $files_str); + } + + /** + * Displays a form which allows members to deliver their solutions + * + * @access public + */ + public function submissionScreenObject() + { + $ilToolbar = $this->toolbar; + $ilHelp = $this->help; + $ilUser = $this->user; + + + $this->handleTabs(); + + $ilHelp->setScreenIdComponent("exc"); + $ilHelp->setScreenId("submissions"); + + if (!$this->submission->canSubmit()) { + ilUtil::sendInfo($this->lng->txt("exercise_time_over")); + } else { + $max_files = $this->submission->getAssignment()->getMaxFile(); + + if ($this->submission->canAddFile()) { + // #15883 - extended deadline warning + $deadline = $this->assignment->getPersonalDeadline($ilUser->getId()); + if ($deadline && + time() > $deadline) { + $dl = ilDatePresentation::formatDate(new ilDateTime($deadline, IL_CAL_UNIX)); + $dl = sprintf($this->lng->txt("exc_late_submission_warning"), $dl); + $dl = '' . $dl . ''; + $ilToolbar->addText($dl); + } + + $ilToolbar->addButton( + $this->lng->txt("file_add"), + $this->ctrl->getLinkTarget($this, "uploadForm") + ); + + if (!$max_files || + $max_files > 1) { + $ilToolbar->addButton( + $this->lng->txt("header_zip"), + $this->ctrl->getLinkTarget($this, "uploadZipForm") + ); + } + } + + if ($max_files) { + ilUtil::sendInfo(sprintf($this->lng->txt("exc_max_file_reached"), $max_files)); + } + } + + include_once("./Modules/Exercise/classes/class.ilExcDeliveredFilesTableGUI.php"); + $tab = new ilExcDeliveredFilesTableGUI($this, "submissionScreen", $this->submission); + $this->tpl->setContent($tab->getHTML()); + } + + /** + * Display form for single file upload + */ + public function uploadFormObject(ilPropertyFormGUI $a_form = null) + { + if (!$this->submission->canSubmit()) { + $this->ctrl->redirect($this, "submissionScreen"); + } + + $this->tabs_gui->clearTargets(); + $this->tabs_gui->setBackTarget( + $this->lng->txt("back"), + $this->ctrl->getLinkTarget($this, "submissionScreen") + ); + + $ilHelp = $this->help; + $ilHelp->setScreenIdComponent("exc"); + $ilHelp->setScreenId("upload_submission"); + + if (!$a_form) { + $a_form = $this->initUploadForm(); + } + $this->tpl->setContent($a_form->getHTML()); + } + + /** + * Display form for zip file upload + */ + public function uploadZipFormObject(ilPropertyFormGUI $a_form = null) + { + if (!$this->submission->canSubmit()) { + $this->ctrl->redirect($this, "submissionScreen"); + } + + $this->tabs_gui->clearTargets(); + $this->tabs_gui->setBackTarget( + $this->lng->txt("back"), + $this->ctrl->getLinkTarget($this, "submissionScreen") + ); + + if (!$a_form) { + $a_form = $this->initZipUploadForm(); + } + $this->tpl->setContent($a_form->getHTML()); + } - /** - * Init upload form form. - */ - protected function initUploadForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - - // file input - include_once("./Services/Form/classes/class.ilFileWizardInputGUI.php"); - $fi = new ilFileWizardInputGUI($lng->txt("file"), "deliver"); - $fi->setFilenames(array(0 => '')); - $fi->setRequired(true); - $form->addItem($fi); - - $form->addCommandButton("uploadFile", $lng->txt("upload")); - $form->addCommandButton("submissionScreen", $lng->txt("cancel")); - - $form->setTitle($lng->txt("file_add")); - $form->setFormAction($ilCtrl->getFormAction($this, "uploadFile")); - - return $form; - } - - /** - * Init upload form form. - */ - protected function initZipUploadForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - - include_once("./Services/Form/classes/class.ilFileInputGUI.php"); - $fi = new ilFileInputGUI($lng->txt("file"), "deliver"); - $fi->setSuffixes(array("zip")); - $fi->setRequired(true); - $form->addItem($fi); - - $form->addCommandButton("uploadZip", $lng->txt("upload")); - $form->addCommandButton("submissionScreen", $lng->txt("cancel")); - - $form->setTitle($lng->txt("header_zip")); - $form->setFormAction($ilCtrl->getFormAction($this, "uploadZip")); - - return $form; - } + /** + * Init upload form form. + */ + protected function initUploadForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + + // file input + include_once("./Services/Form/classes/class.ilFileWizardInputGUI.php"); + $fi = new ilFileWizardInputGUI($lng->txt("file"), "deliver"); + $fi->setFilenames(array(0 => '')); + $fi->setRequired(true); + $form->addItem($fi); + + $form->addCommandButton("uploadFile", $lng->txt("upload")); + $form->addCommandButton("submissionScreen", $lng->txt("cancel")); + + $form->setTitle($lng->txt("file_add")); + $form->setFormAction($ilCtrl->getFormAction($this, "uploadFile")); + + return $form; + } + + /** + * Init upload form form. + */ + protected function initZipUploadForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + + include_once("./Services/Form/classes/class.ilFileInputGUI.php"); + $fi = new ilFileInputGUI($lng->txt("file"), "deliver"); + $fi->setSuffixes(array("zip")); + $fi->setRequired(true); + $form->addItem($fi); + + $form->addCommandButton("uploadZip", $lng->txt("upload")); + $form->addCommandButton("submissionScreen", $lng->txt("cancel")); + + $form->setTitle($lng->txt("header_zip")); + $form->setFormAction($ilCtrl->getFormAction($this, "uploadZip")); + + return $form; + } - /** - * Upload files - */ - function uploadFileObject() - { - $ilCtrl = $this->ctrl; - - // #15322 - if (!$this->submission->canSubmit()) - { - ilUtil::sendInfo($this->lng->txt("exercise_time_over"), true); - } - else - { - $form = $this->initUploadForm(); - if(!$form->checkInput()) - { - return $this->uploadFormObject($form); - } - - $success = false; - foreach ($_FILES["deliver"]["name"] as $k => $v) - { - $file = array( - "name" => $_FILES["deliver"]["name"][$k], - "type" => $_FILES["deliver"]["type"][$k], - "tmp_name" => $_FILES["deliver"]["tmp_name"][$k], - "error" => $_FILES["deliver"]["error"][$k], - "size" => $_FILES["deliver"]["size"][$k], - ); - if(!$this->submission->uploadFile($file)) - { - ilUtil::sendFailure($this->lng->txt("exc_upload_error")." [Single File]", true); - } - else - { - $success = true; - } - } - - if($success) - { - ilUtil::sendSuccess($this->lng->txt("file_added"), true); - $this->handleNewUpload(); - } - } - - $ilCtrl->redirect($this, "submissionScreen"); - } - - /** - * Upload zip file - */ - function uploadZipObject() - { - $ilCtrl = $this->ctrl; - - // #15322 - if (!$this->submission->canSubmit()) - { - ilUtil::sendInfo($this->lng->txt("exercise_time_over"), true); - } - else - { - $form = $this->initZipUploadForm(); - if(!$form->checkInput()) - { - return $this->uploadZipFormObject($form); - } - - if (preg_match("/zip/",$_FILES["deliver"]["type"]) == 1) - { - if($this->submission->processUploadedZipFile($_FILES["deliver"]["tmp_name"])) - { - ilUtil::sendSuccess($this->lng->txt("file_added"), true); - $this->handleNewUpload(); - } - } - } - - $ilCtrl->redirect($this, "submissionScreen"); - } - - /** - * Confirm deletion of delivered files - */ - function confirmDeleteDeliveredObject() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - if (!$this->submission->canSubmit()) - { - ilUtil::sendFailure($this->lng->txt("exercise_time_over"), true); - $ilCtrl->redirect($this, "submissionScreen"); - } - - if (!is_array($_POST["delivered"]) || count($_POST["delivered"]) == 0) - { - ilUtil::sendFailure($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "submissionScreen"); - } - else - { - $this->tabs_gui->clearTargets(); - $this->tabs_gui->setBackTarget($this->lng->txt("back"), - $this->ctrl->getLinkTarget($this, "submissionScreen")); - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("info_delete_sure")); - $cgui->setCancel($lng->txt("cancel"), "submissionScreen"); - $cgui->setConfirm($lng->txt("delete"), "deleteDelivered"); - - $files = $this->submission->getFiles(); - - foreach ($_POST["delivered"] as $i) - { - reset ($files); - $title = ""; - foreach ($files as $f) - { - if ($f["returned_id"] == $i) - { - $title = $f["filetitle"]; - } - } - $cgui->addItem("delivered[]", $i, $title); - } - - $tpl->setContent($cgui->getHTML()); - } - } - - /** - * Delete file(s) submitted by user - * - * @param - * @return - */ - function deleteDeliveredObject() - { - $ilCtrl = $this->ctrl; - - if (!$this->submission->canSubmit()) - { - ilUtil::sendFailure($this->lng->txt("exercise_time_over"), true); - } - else if (!count($_POST["delivered"])) - { - ilUtil::sendFailure($this->lng->txt("please_select_a_delivered_file_to_delete"), true); - } - else - { - $this->submission->deleteSelectedFiles($_POST["delivered"]); - $this->handleRemovedUpload(); - - ilUtil::sendSuccess($this->lng->txt("exc_submitted_files_deleted"), true); - } - $ilCtrl->redirect($this, "submissionScreen"); - } - - /** - * Download submitted files of user. - */ - function downloadReturnedObject($a_only_new = false) - { - $lng = $this->lng; - - $peer_review_mask_filename = false; - - if($this->submission->canView()) - { - $peer_review_mask_filename = $this->submission->hasPeerReviewAccess(); - } - else - { - // no access - return; - } - - $this->submission->downloadFiles(null, $a_only_new, $peer_review_mask_filename); - // we only get here, if no files have been found for download - if ($a_only_new) - { - ilUtil::sendInfo($lng->txt("exc_all_new_files_offered_already"), true); - } - $this->returnToParentObject(); - } - - /** - * Download newly submitted files of user. - */ - function downloadNewReturnedObject() - { - $this->downloadReturnedObject(true); - } - - /** - * User downloads (own) submitted files - * - * @param - * @return - */ - function downloadObject() - { - $ilCtrl = $this->ctrl; - - $delivered_id = $_REQUEST["delivered"]; - - if(!$this->submission->canView()) - { - $this->returnToParentObject(); - } - - if(!is_array($delivered_id) && $delivered_id > 0) - { - $delivered_id = [$delivered_id]; - } - if (is_array($delivered_id) && count($delivered_id) > 0) - { - $this->submission->downloadFiles($delivered_id); - exit; - } - else - { - ilUtil::sendFailure($this->lng->txt("please_select_a_delivered_file_to_download"), true); - $ilCtrl->redirect($this, "submissionScreen"); - } - } + /** + * Upload files + */ + public function uploadFileObject() + { + $ilCtrl = $this->ctrl; + + // #15322 + if (!$this->submission->canSubmit()) { + ilUtil::sendInfo($this->lng->txt("exercise_time_over"), true); + } else { + $form = $this->initUploadForm(); + if (!$form->checkInput()) { + return $this->uploadFormObject($form); + } + + $success = false; + foreach ($_FILES["deliver"]["name"] as $k => $v) { + $file = array( + "name" => $_FILES["deliver"]["name"][$k], + "type" => $_FILES["deliver"]["type"][$k], + "tmp_name" => $_FILES["deliver"]["tmp_name"][$k], + "error" => $_FILES["deliver"]["error"][$k], + "size" => $_FILES["deliver"]["size"][$k], + ); + if (!$this->submission->uploadFile($file)) { + ilUtil::sendFailure($this->lng->txt("exc_upload_error") . " [Single File]", true); + } else { + $success = true; + } + } + + if ($success) { + ilUtil::sendSuccess($this->lng->txt("file_added"), true); + $this->handleNewUpload(); + } + } + + $ilCtrl->redirect($this, "submissionScreen"); + } + + /** + * Upload zip file + */ + public function uploadZipObject() + { + $ilCtrl = $this->ctrl; + + // #15322 + if (!$this->submission->canSubmit()) { + ilUtil::sendInfo($this->lng->txt("exercise_time_over"), true); + } else { + $form = $this->initZipUploadForm(); + if (!$form->checkInput()) { + return $this->uploadZipFormObject($form); + } + + if (preg_match("/zip/", $_FILES["deliver"]["type"]) == 1) { + if ($this->submission->processUploadedZipFile($_FILES["deliver"]["tmp_name"])) { + ilUtil::sendSuccess($this->lng->txt("file_added"), true); + $this->handleNewUpload(); + } + } + } + + $ilCtrl->redirect($this, "submissionScreen"); + } + + /** + * Confirm deletion of delivered files + */ + public function confirmDeleteDeliveredObject() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + if (!$this->submission->canSubmit()) { + ilUtil::sendFailure($this->lng->txt("exercise_time_over"), true); + $ilCtrl->redirect($this, "submissionScreen"); + } + + if (!is_array($_POST["delivered"]) || count($_POST["delivered"]) == 0) { + ilUtil::sendFailure($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "submissionScreen"); + } else { + $this->tabs_gui->clearTargets(); + $this->tabs_gui->setBackTarget( + $this->lng->txt("back"), + $this->ctrl->getLinkTarget($this, "submissionScreen") + ); + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("info_delete_sure")); + $cgui->setCancel($lng->txt("cancel"), "submissionScreen"); + $cgui->setConfirm($lng->txt("delete"), "deleteDelivered"); + + $files = $this->submission->getFiles(); + + foreach ($_POST["delivered"] as $i) { + reset($files); + $title = ""; + foreach ($files as $f) { + if ($f["returned_id"] == $i) { + $title = $f["filetitle"]; + } + } + $cgui->addItem("delivered[]", $i, $title); + } + + $tpl->setContent($cgui->getHTML()); + } + } + + /** + * Delete file(s) submitted by user + * + * @param + * @return + */ + public function deleteDeliveredObject() + { + $ilCtrl = $this->ctrl; + + if (!$this->submission->canSubmit()) { + ilUtil::sendFailure($this->lng->txt("exercise_time_over"), true); + } elseif (!count($_POST["delivered"])) { + ilUtil::sendFailure($this->lng->txt("please_select_a_delivered_file_to_delete"), true); + } else { + $this->submission->deleteSelectedFiles($_POST["delivered"]); + $this->handleRemovedUpload(); + + ilUtil::sendSuccess($this->lng->txt("exc_submitted_files_deleted"), true); + } + $ilCtrl->redirect($this, "submissionScreen"); + } + + /** + * Download submitted files of user. + */ + public function downloadReturnedObject($a_only_new = false) + { + $lng = $this->lng; + + $peer_review_mask_filename = false; + + if ($this->submission->canView()) { + $peer_review_mask_filename = $this->submission->hasPeerReviewAccess(); + } else { + // no access + return; + } + + $this->submission->downloadFiles(null, $a_only_new, $peer_review_mask_filename); + // we only get here, if no files have been found for download + if ($a_only_new) { + ilUtil::sendInfo($lng->txt("exc_all_new_files_offered_already"), true); + } + $this->returnToParentObject(); + } + + /** + * Download newly submitted files of user. + */ + public function downloadNewReturnedObject() + { + $this->downloadReturnedObject(true); + } + + /** + * User downloads (own) submitted files + * + * @param + * @return + */ + public function downloadObject() + { + $ilCtrl = $this->ctrl; + + $delivered_id = $_REQUEST["delivered"]; + + if (!$this->submission->canView()) { + $this->returnToParentObject(); + } + + if (!is_array($delivered_id) && $delivered_id > 0) { + $delivered_id = [$delivered_id]; + } + if (is_array($delivered_id) && count($delivered_id) > 0) { + $this->submission->downloadFiles($delivered_id); + exit; + } else { + ilUtil::sendFailure($this->lng->txt("please_select_a_delivered_file_to_download"), true); + $ilCtrl->redirect($this, "submissionScreen"); + } + } } diff --git a/Modules/Exercise/classes/class.ilExSubmissionGUI.php b/Modules/Exercise/classes/class.ilExSubmissionGUI.php index 00a35b3cbaa5033dd3306f472f9990b7b3ff174e..844fb875ddaecc1ebc8b694bfb9fd0b4e46a0bbe 100644 --- a/Modules/Exercise/classes/class.ilExSubmissionGUI.php +++ b/Modules/Exercise/classes/class.ilExSubmissionGUI.php @@ -8,383 +8,365 @@ include_once "Modules/Exercise/classes/class.ilExSubmission.php"; * Class ilExSubmissionGUI * * @author Jörg Lützenkirchen -* -* @ilCtrl_Calls ilExSubmissionGUI: ilExSubmissionTeamGUI, ilExSubmissionFileGUI -* @ilCtrl_Calls ilExSubmissionGUI: ilExSubmissionTextGUI, ilExSubmissionObjectGUI +* +* @ilCtrl_Calls ilExSubmissionGUI: ilExSubmissionTeamGUI, ilExSubmissionFileGUI +* @ilCtrl_Calls ilExSubmissionGUI: ilExSubmissionTextGUI, ilExSubmissionObjectGUI * @ilCtrl_Calls ilExSubmissionGUI: ilExPeerReviewGUI * @ingroup ModulesExercise */ class ilExSubmissionGUI { - const MODE_OVERVIEW_CONTENT = 1; + const MODE_OVERVIEW_CONTENT = 1; - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilTabsGUI - */ - protected $tabs_gui; + /** + * @var ilTabsGUI + */ + protected $tabs_gui; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilTemplate + */ + protected $tpl; - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - protected $exercise; // [ilObjExercise] - protected $submission; // [ilExSubmission] - protected $assignment; // [ilExAssignment] + protected $exercise; // [ilObjExercise] + protected $submission; // [ilExSubmission] + protected $assignment; // [ilExAssignment] - /** - * @var ilExAssignmentTypesGUI - */ - protected $type_guis; - - /** - * Constructor - * - * @param ilObjExercise $a_exercise - * @param ilExAssignment $a_ass - * @param int $a_user_id - * @return object - */ - public function __construct(ilObjExercise $a_exercise, ilExAssignment $a_ass, $a_user_id = null) - { - global $DIC; + /** + * @var ilExAssignmentTypesGUI + */ + protected $type_guis; + + /** + * Constructor + * + * @param ilObjExercise $a_exercise + * @param ilExAssignment $a_ass + * @param int $a_user_id + * @return object + */ + public function __construct(ilObjExercise $a_exercise, ilExAssignment $a_ass, $a_user_id = null) + { + global $DIC; - $this->user = $DIC->user(); - $ilCtrl = $DIC->ctrl(); - $ilTabs = $DIC->tabs(); - $lng = $DIC->language(); - $tpl = $DIC["tpl"]; - $ilUser = $DIC->user(); - - if(!$a_user_id) - { - $a_user_id = $ilUser->getId(); - } - - $this->assignment = $a_ass; - $this->exercise = $a_exercise; + $this->user = $DIC->user(); + $ilCtrl = $DIC->ctrl(); + $ilTabs = $DIC->tabs(); + $lng = $DIC->language(); + $tpl = $DIC["tpl"]; + $ilUser = $DIC->user(); + + if (!$a_user_id) { + $a_user_id = $ilUser->getId(); + } + + $this->assignment = $a_ass; + $this->exercise = $a_exercise; - include_once("./Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssignmentTypesGUI.php"); - $this->type_guis = ilExAssignmentTypesGUI::getInstance(); + include_once("./Modules/Exercise/AssignmentTypes/GUI/classes/class.ilExAssignmentTypesGUI.php"); + $this->type_guis = ilExAssignmentTypesGUI::getInstance(); - // #12337 - if (!$this->exercise->members_obj->isAssigned($a_user_id)) - { - $this->exercise->members_obj->assignMember($a_user_id); - } - - // public submissions ??? - $public_submissions = false; - if ($this->exercise->getShowSubmissions() && - $this->exercise->getTimestamp() - time() <= 0) // ??? - { - $public_submissions = true; - } - $this->submission = new ilExSubmission($a_ass, $a_user_id, null, false, $public_submissions); - - // :TODO: - $this->ctrl = $ilCtrl; - $this->tabs_gui = $ilTabs; - $this->lng = $lng; - $this->tpl = $tpl; - } - - public function executeCommand() - { - $ilCtrl = $this->ctrl; - - $class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd("listPublicSubmissions"); - - switch($class) - { - case "ilexsubmissionteamgui": - // team gui has no base gui - see we have to handle tabs here - - $this->tabs_gui->clearTargets(); - $this->tabs_gui->setBackTarget($this->lng->txt("back"), - $this->ctrl->getLinkTarget($this, "returnToParent")); + // #12337 + if (!$this->exercise->members_obj->isAssigned($a_user_id)) { + $this->exercise->members_obj->assignMember($a_user_id); + } + + // public submissions ??? + $public_submissions = false; + if ($this->exercise->getShowSubmissions() && + $this->exercise->getTimestamp() - time() <= 0) { // ??? + $public_submissions = true; + } + $this->submission = new ilExSubmission($a_ass, $a_user_id, null, false, $public_submissions); + + // :TODO: + $this->ctrl = $ilCtrl; + $this->tabs_gui = $ilTabs; + $this->lng = $lng; + $this->tpl = $tpl; + } + + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd("listPublicSubmissions"); + + switch ($class) { + case "ilexsubmissionteamgui": + // team gui has no base gui - see we have to handle tabs here + + $this->tabs_gui->clearTargets(); + $this->tabs_gui->setBackTarget( + $this->lng->txt("back"), + $this->ctrl->getLinkTarget($this, "returnToParent") + ); - // forward to type gui - if ($this->submission->getSubmissionType() != ilExSubmission::TYPE_REPO_OBJECT) - { - $this->tabs_gui->addTab("submission", $this->lng->txt("exc_submission"), - $this->ctrl->getLinkTargetByClass("ilexsubmission" . $this->submission->getSubmissionType() . "gui", "")); - } + // forward to type gui + if ($this->submission->getSubmissionType() != ilExSubmission::TYPE_REPO_OBJECT) { + $this->tabs_gui->addTab( + "submission", + $this->lng->txt("exc_submission"), + $this->ctrl->getLinkTargetByClass("ilexsubmission" . $this->submission->getSubmissionType() . "gui", "") + ); + } - include_once "Modules/Exercise/classes/class.ilExSubmissionTeamGUI.php"; - $gui = new ilExSubmissionTeamGUI($this->exercise, $this->submission); - $ilCtrl->forwardCommand($gui); - break; - - case "ilexsubmissiontextgui": - include_once "Modules/Exercise/classes/class.ilExSubmissionTextGUI.php"; - $gui = new ilExSubmissionTextGUI($this->exercise, $this->submission); - $ilCtrl->forwardCommand($gui); - break; - - case "ilexsubmissionfilegui": - include_once "Modules/Exercise/classes/class.ilExSubmissionFileGUI.php"; - $gui = new ilExSubmissionFileGUI($this->exercise, $this->submission); - $ilCtrl->forwardCommand($gui); - break; - - case "ilexsubmissionobjectgui": - include_once "Modules/Exercise/classes/class.ilExSubmissionObjectGUI.php"; - $gui = new ilExSubmissionObjectGUI($this->exercise, $this->submission); - $ilCtrl->forwardCommand($gui); - break; - - case "ilexpeerreviewgui": - $this->tabs_gui->clearTargets(); - $this->tabs_gui->setBackTarget($this->lng->txt("back"), - $this->ctrl->getLinkTarget($this, "returnToParent")); - - include_once("./Modules/Exercise/classes/class.ilExPeerReviewGUI.php"); - $peer_gui = new ilExPeerReviewGUI($this->assignment, $this->submission); - $this->ctrl->forwardCommand($peer_gui); - break; - - default: + include_once "Modules/Exercise/classes/class.ilExSubmissionTeamGUI.php"; + $gui = new ilExSubmissionTeamGUI($this->exercise, $this->submission); + $ilCtrl->forwardCommand($gui); + break; + + case "ilexsubmissiontextgui": + include_once "Modules/Exercise/classes/class.ilExSubmissionTextGUI.php"; + $gui = new ilExSubmissionTextGUI($this->exercise, $this->submission); + $ilCtrl->forwardCommand($gui); + break; + + case "ilexsubmissionfilegui": + include_once "Modules/Exercise/classes/class.ilExSubmissionFileGUI.php"; + $gui = new ilExSubmissionFileGUI($this->exercise, $this->submission); + $ilCtrl->forwardCommand($gui); + break; + + case "ilexsubmissionobjectgui": + include_once "Modules/Exercise/classes/class.ilExSubmissionObjectGUI.php"; + $gui = new ilExSubmissionObjectGUI($this->exercise, $this->submission); + $ilCtrl->forwardCommand($gui); + break; + + case "ilexpeerreviewgui": + $this->tabs_gui->clearTargets(); + $this->tabs_gui->setBackTarget( + $this->lng->txt("back"), + $this->ctrl->getLinkTarget($this, "returnToParent") + ); + + include_once("./Modules/Exercise/classes/class.ilExPeerReviewGUI.php"); + $peer_gui = new ilExPeerReviewGUI($this->assignment, $this->submission); + $this->ctrl->forwardCommand($peer_gui); + break; + + default: - // forward to type gui - if ($this->type_guis->isExAssTypeGUIClass($class)) - { - $type_gui = $this->type_guis->getByClassName($class); - $type_gui->setSubmission($this->submission); - $type_gui->setExercise($this->exercise); - return $ilCtrl->forwardCommand($type_gui); - } + // forward to type gui + if ($this->type_guis->isExAssTypeGUIClass($class)) { + $type_gui = $this->type_guis->getByClassName($class); + $type_gui->setSubmission($this->submission); + $type_gui->setExercise($this->exercise); + return $ilCtrl->forwardCommand($type_gui); + } - $this->{$cmd."Object"}(); - break; - } - } + $this->{$cmd . "Object"}(); + break; + } + } - /** - * @param ilInfoScreenGUI $a_info - * @param ilExSubmission $a_submission - * @param ilObjExercise $a_exc - * @return string - * @throws ilCtrlException - */ - public static function getOverviewContent(ilInfoScreenGUI $a_info, ilExSubmission $a_submission, ilObjExercise $a_exc) - { - global $DIC; + /** + * @param ilInfoScreenGUI $a_info + * @param ilExSubmission $a_submission + * @param ilObjExercise $a_exc + * @return string + * @throws ilCtrlException + */ + public static function getOverviewContent(ilInfoScreenGUI $a_info, ilExSubmission $a_submission, ilObjExercise $a_exc) + { + global $DIC; - $ilCtrl = $DIC->ctrl(); - - if(!$a_submission->canView()) - { - return; - } - - $ilCtrl->setParameterByClass("ilExSubmissionGUI", "ass_id", $a_submission->getAssignment()->getId()); - - if($a_submission->getAssignment()->hasTeam()) - { - include_once "Modules/Exercise/classes/class.ilExSubmissionTeamGUI.php"; - ilExSubmissionTeamGUI::getOverviewContent($a_info, $a_submission); - } - - $submission_type = $a_submission->getSubmissionType(); - // old handling -> forward to submission type gui class - // @todo migrate everything to new concept - if ($submission_type != ilExSubmission::TYPE_REPO_OBJECT) - { - $class = "ilExSubmission" . $submission_type . "GUI"; - include_once "Modules/Exercise/classes/class." . $class . ".php"; - $class::getOverviewContent($a_info, $a_submission); - } - else // new: get HTML from assignemt type gui class - { - include_once("./Modules/Exercise/classes/class.ilExSubmissionGUI.php"); - $sub_gui = new ilExSubmissionGUI($a_exc, $a_submission->getAssignment()); - $ilCtrl->getHTML($sub_gui, array( - "mode" => self::MODE_OVERVIEW_CONTENT, - "info" => $a_info, - "submission" => $a_submission - )); - } - - $ilCtrl->setParameterByClass("ilExSubmissionGUI", "ass_id", ""); - } + $ilCtrl = $DIC->ctrl(); + + if (!$a_submission->canView()) { + return; + } + + $ilCtrl->setParameterByClass("ilExSubmissionGUI", "ass_id", $a_submission->getAssignment()->getId()); + + if ($a_submission->getAssignment()->hasTeam()) { + include_once "Modules/Exercise/classes/class.ilExSubmissionTeamGUI.php"; + ilExSubmissionTeamGUI::getOverviewContent($a_info, $a_submission); + } + + $submission_type = $a_submission->getSubmissionType(); + // old handling -> forward to submission type gui class + // @todo migrate everything to new concept + if ($submission_type != ilExSubmission::TYPE_REPO_OBJECT) { + $class = "ilExSubmission" . $submission_type . "GUI"; + include_once "Modules/Exercise/classes/class." . $class . ".php"; + $class::getOverviewContent($a_info, $a_submission); + } else { // new: get HTML from assignemt type gui class + include_once("./Modules/Exercise/classes/class.ilExSubmissionGUI.php"); + $sub_gui = new ilExSubmissionGUI($a_exc, $a_submission->getAssignment()); + $ilCtrl->getHTML($sub_gui, array( + "mode" => self::MODE_OVERVIEW_CONTENT, + "info" => $a_info, + "submission" => $a_submission + )); + } + + $ilCtrl->setParameterByClass("ilExSubmissionGUI", "ass_id", ""); + } - /** - * Get HTML - * - * @param - * @return - */ - public function getHTML($par) - { - switch ($par["mode"]) - { - // get overview content from ass type gui - case self::MODE_OVERVIEW_CONTENT: - $type_gui = $this->type_guis->getById($par["submission"]->getAssignment()->getType()); - return $type_gui->getOverviewContent($par["info"], $par["submission"]); - break; - } - } + /** + * Get HTML + * + * @param + * @return + */ + public function getHTML($par) + { + switch ($par["mode"]) { + // get overview content from ass type gui + case self::MODE_OVERVIEW_CONTENT: + $type_gui = $this->type_guis->getById($par["submission"]->getAssignment()->getType()); + return $type_gui->getOverviewContent($par["info"], $par["submission"]); + break; + } + } - - /** - * List all submissions - */ - function listPublicSubmissionsObject() - { - $ilTabs = $this->tabs_gui; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if(!$this->exercise->getShowSubmissions()) - { - $this->returnToParentObject(); - } - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTarget($this, "returnToParent")); - - if($this->assignment->getType() != ilExAssignment::TYPE_TEXT) - { - include_once("./Modules/Exercise/classes/class.ilPublicSubmissionsTableGUI.php"); - $tab = new ilPublicSubmissionsTableGUI($this, "listPublicSubmissions", $this->assignment); - $this->tpl->setContent($tab->getHTML()); - } - else - { - // #13271 - include_once "Modules/Exercise/classes/class.ilExAssignmentListTextTableGUI.php"; - $tbl = new ilExAssignmentListTextTableGUI($this, "listPublicSubmissions", $this->assignment, false, true); - $this->tpl->setContent($tbl->getHTML()); - } - } - - /** - * Download feedback file - */ - function downloadFeedbackFileObject() - { - $ilUser = $this->user; - - $file = $_REQUEST["file"]; + + /** + * List all submissions + */ + public function listPublicSubmissionsObject() + { + $ilTabs = $this->tabs_gui; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if (!$this->exercise->getShowSubmissions()) { + $this->returnToParentObject(); + } + + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, "returnToParent") + ); + + if ($this->assignment->getType() != ilExAssignment::TYPE_TEXT) { + include_once("./Modules/Exercise/classes/class.ilPublicSubmissionsTableGUI.php"); + $tab = new ilPublicSubmissionsTableGUI($this, "listPublicSubmissions", $this->assignment); + $this->tpl->setContent($tab->getHTML()); + } else { + // #13271 + include_once "Modules/Exercise/classes/class.ilExAssignmentListTextTableGUI.php"; + $tbl = new ilExAssignmentListTextTableGUI($this, "listPublicSubmissions", $this->assignment, false, true); + $this->tpl->setContent($tbl->getHTML()); + } + } + + /** + * Download feedback file + */ + public function downloadFeedbackFileObject() + { + $ilUser = $this->user; + + $file = $_REQUEST["file"]; - if (!isset($file)) - { - ilUtil::sendFailure($this->lng->txt("exc_select_one_file"),true); - $this->ctrl->redirect($this, "view"); - } - - // check, whether file belongs to assignment - include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); - $storage = new ilFSStorageExercise($this->exercise->getId(), $this->assignment->getId()); - $files = $storage->getFeedbackFiles($this->submission->getFeedbackId()); - $file_exist = false; - foreach($files as $fb_file) - { - if($fb_file == $file) - { - $file_exist = true; - break; - } - } - if(!$file_exist) - { - echo "FILE DOES NOT EXIST"; - exit; - } - - // check whether assignment has already started - if (!$this->assignment->notStartedYet()) - { - // deliver file - $p = $storage->getFeedbackFilePath($this->submission->getFeedbackId(), $file); - ilUtil::deliverFile($p, $file); - } - - return true; - } - - public function downloadGlobalFeedbackFileObject() - { - $ilCtrl = $this->ctrl; - - $needs_dl = ($this->assignment->getFeedbackDate() == ilExAssignment::FEEDBACK_DATE_DEADLINE); - - if(!$this->assignment || - !$this->assignment->getFeedbackFile() || - ($needs_dl && !$this->assignment->afterDeadlineStrict()) || - (!$needs_dl && !$this->submission->hasSubmitted())) - { - $ilCtrl->redirect($this, "returnToParent"); - } + if (!isset($file)) { + ilUtil::sendFailure($this->lng->txt("exc_select_one_file"), true); + $this->ctrl->redirect($this, "view"); + } + + // check, whether file belongs to assignment + include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); + $storage = new ilFSStorageExercise($this->exercise->getId(), $this->assignment->getId()); + $files = $storage->getFeedbackFiles($this->submission->getFeedbackId()); + $file_exist = false; + foreach ($files as $fb_file) { + if ($fb_file == $file) { + $file_exist = true; + break; + } + } + if (!$file_exist) { + echo "FILE DOES NOT EXIST"; + exit; + } + + // check whether assignment has already started + if (!$this->assignment->notStartedYet()) { + // deliver file + $p = $storage->getFeedbackFilePath($this->submission->getFeedbackId(), $file); + ilUtil::deliverFile($p, $file); + } + + return true; + } + + public function downloadGlobalFeedbackFileObject() + { + $ilCtrl = $this->ctrl; + + $needs_dl = ($this->assignment->getFeedbackDate() == ilExAssignment::FEEDBACK_DATE_DEADLINE); + + if (!$this->assignment || + !$this->assignment->getFeedbackFile() || + ($needs_dl && !$this->assignment->afterDeadlineStrict()) || + (!$needs_dl && !$this->submission->hasSubmitted())) { + $ilCtrl->redirect($this, "returnToParent"); + } - // this is due to temporary bug in handleGlobalFeedbackFileUpload that missed the last "/" - $file = (is_file($this->assignment->getGlobalFeedbackFilePath())) - ? $this->assignment->getGlobalFeedbackFilePath() - : $this->assignment->getGlobalFeedbackFileStoragePath().$this->assignment->getFeedbackFile(); + // this is due to temporary bug in handleGlobalFeedbackFileUpload that missed the last "/" + $file = (is_file($this->assignment->getGlobalFeedbackFilePath())) + ? $this->assignment->getGlobalFeedbackFilePath() + : $this->assignment->getGlobalFeedbackFileStoragePath() . $this->assignment->getFeedbackFile(); - ilUtil::deliverFile($file, $this->assignment->getFeedbackFile()); - } - - /** - * Download assignment file - */ - function downloadFileObject() - { - $file = $_REQUEST["file"]; + ilUtil::deliverFile($file, $this->assignment->getFeedbackFile()); + } + + /** + * Download assignment file + */ + public function downloadFileObject() + { + $file = $_REQUEST["file"]; - if (!isset($file)) - { - ilUtil::sendFailure($this->lng->txt("exc_select_one_file"),true); - $this->ctrl->redirect($this, "view"); - } - - // check whether assignment as already started - if (!$this->assignment->notStartedYet()) - { - // check, whether file belongs to assignment - $files = $this->assignment->getFiles(); - $file_exist = false; - foreach($files as $lfile) - { - if($lfile["name"] == $file) - { - // deliver file - ilUtil::deliverFile($lfile["fullpath"], $file); - exit(); - } - } - if(!$file_exist) - { - echo "FILE DOES NOT EXIST"; - exit; - } - } - - return true; - } - - function returnToParentObject() - { - $this->ctrl->returnToParent($this); - } + if (!isset($file)) { + ilUtil::sendFailure($this->lng->txt("exc_select_one_file"), true); + $this->ctrl->redirect($this, "view"); + } + + // check whether assignment as already started + if (!$this->assignment->notStartedYet()) { + // check, whether file belongs to assignment + $files = $this->assignment->getFiles(); + $file_exist = false; + foreach ($files as $lfile) { + if ($lfile["name"] == $file) { + // deliver file + ilUtil::deliverFile($lfile["fullpath"], $file); + exit(); + } + } + if (!$file_exist) { + echo "FILE DOES NOT EXIST"; + exit; + } + } + + return true; + } + + public function returnToParentObject() + { + $this->ctrl->returnToParent($this); + } } diff --git a/Modules/Exercise/classes/class.ilExSubmissionObjectGUI.php b/Modules/Exercise/classes/class.ilExSubmissionObjectGUI.php index ad91d0ca0554484efe690294b1cbddd1d2c0f569..509bf5facd6b76b78ad6679ffd1232d5ad9c1bea 100644 --- a/Modules/Exercise/classes/class.ilExSubmissionObjectGUI.php +++ b/Modules/Exercise/classes/class.ilExSubmissionObjectGUI.php @@ -5,815 +5,744 @@ * Object-based submissions (ends up as static file) * * @author Jörg Lützenkirchen - * - * @ilCtrl_Calls ilExSubmissionObjectGUI: + * + * @ilCtrl_Calls ilExSubmissionObjectGUI: * @ingroup ModulesExercise */ class ilExSubmissionObjectGUI extends ilExSubmissionBaseGUI { - /** - * 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) - else if(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) - 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 - * - * @ilCtrl_Calls ilExSubmissionTextGUI: - * @ingroup ModulesExercise + * + * @ilCtrl_Calls ilExSubmissionTextGUI: + * @ingroup ModulesExercise */ class ilExSubmissionTextGUI extends ilExSubmissionBaseGUI -{ - /** - * @var ilObjUser - */ - protected $user; +{ + /** + * @var ilObjUser + */ + protected $user; - /** - * @var ilHelpGUI - */ - protected $help; + /** + * @var ilHelpGUI + */ + protected $help; - /** - * Constructor - */ - function __construct(ilObjExercise $a_exercise, ilExSubmission $a_submission) - { - global $DIC; + /** + * Constructor + */ + public function __construct(ilObjExercise $a_exercise, ilExSubmission $a_submission) + { + global $DIC; - parent::__construct($a_exercise, $a_submission); - $this->user = $DIC->user(); - $this->help = $DIC["ilHelp"]; - } + parent::__construct($a_exercise, $a_submission); + $this->user = $DIC->user(); + $this->help = $DIC["ilHelp"]; + } - public function executeCommand() - { - $ilCtrl = $this->ctrl; - - if(!$this->assignment || - $this->assignment->getType() != ilExAssignment::TYPE_TEXT || - !$this->submission->canView()) - { - return; - } - - $class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd("showassignmenttext"); - - switch($class) - { - default: - $this->{$cmd."Object"}(); - break; - } - } - - public static function getOverviewContent(ilInfoScreenGUI $a_info, ilExSubmission $a_submission) - { - global $DIC; + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + if (!$this->assignment || + $this->assignment->getType() != ilExAssignment::TYPE_TEXT || + !$this->submission->canView()) { + return; + } + + $class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd("showassignmenttext"); + + switch ($class) { + default: + $this->{$cmd . "Object"}(); + break; + } + } + + public static function getOverviewContent(ilInfoScreenGUI $a_info, ilExSubmission $a_submission) + { + global $DIC; - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - - if($a_submission->canSubmit()) - { - $button = ilLinkButton::getInstance(); - $button->setPrimary(true); - $button->setCaption("exc_text_assignment_edit"); - $button->setUrl($ilCtrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExSubmissionTextGUI"), "editAssignmentText")); - $files_str = $button->render(); - } - else - { - $button = ilLinkButton::getInstance(); - $button->setCaption("exc_text_assignment_show"); - $button->setUrl($ilCtrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExSubmissionTextGUI"), "showAssignmentText")); - $files_str = $button->render(); - } + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + + if ($a_submission->canSubmit()) { + $button = ilLinkButton::getInstance(); + $button->setPrimary(true); + $button->setCaption("exc_text_assignment_edit"); + $button->setUrl($ilCtrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExSubmissionTextGUI"), "editAssignmentText")); + $files_str = $button->render(); + } else { + $button = ilLinkButton::getInstance(); + $button->setCaption("exc_text_assignment_show"); + $button->setUrl($ilCtrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExSubmissionTextGUI"), "showAssignmentText")); + $files_str = $button->render(); + } - $a_info->addProperty($lng->txt("exc_files_returned_text"), $files_str); - } - - - // - // TEXT ASSIGNMENT (EDIT) - // - - protected function initAssignmentTextForm($a_read_only = false) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; + $a_info->addProperty($lng->txt("exc_files_returned_text"), $files_str); + } + + + // + // TEXT ASSIGNMENT (EDIT) + // + + protected function initAssignmentTextForm($a_read_only = false) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $form = new ilPropertyFormGUI(); - $form->setTitle($this->lng->txt("exc_assignment")." \"".$this->assignment->getTitle()."\""); - - if(!$a_read_only) - { - $text = new ilTextAreaInputGUI($this->lng->txt("exc_your_text"), "atxt"); - $text->setRequired((bool)$this->submission->getAssignment()->getMandatory()); - $text->setRows(40); - $text->setMaxNumOfChars($this->assignment->getMaxCharLimit()); - $text->setMinNumOfChars($this->assignment->getMinCharLimit()); + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $form = new ilPropertyFormGUI(); + $form->setTitle($this->lng->txt("exc_assignment") . " \"" . $this->assignment->getTitle() . "\""); + + if (!$a_read_only) { + $text = new ilTextAreaInputGUI($this->lng->txt("exc_your_text"), "atxt"); + $text->setRequired((bool) $this->submission->getAssignment()->getMandatory()); + $text->setRows(40); + $text->setMaxNumOfChars($this->assignment->getMaxCharLimit()); + $text->setMinNumOfChars($this->assignment->getMinCharLimit()); - if ($text->isCharLimited()) - { - $char_msg = ""; - if($this->assignment->getMinCharLimit()) - { - $char_msg .= $lng->txt("exc_min_char_limit").": ".$this->assignment->getMinCharLimit(); - } - if($this->assignment->getMaxCharLimit()) - { - $char_msg .= " ".$lng->txt("exc_max_char_limit").": ".$this->assignment->getMaxCharLimit(); - } - $text->setInfo($char_msg); - } + if ($text->isCharLimited()) { + $char_msg = ""; + if ($this->assignment->getMinCharLimit()) { + $char_msg .= $lng->txt("exc_min_char_limit") . ": " . $this->assignment->getMinCharLimit(); + } + if ($this->assignment->getMaxCharLimit()) { + $char_msg .= " " . $lng->txt("exc_max_char_limit") . ": " . $this->assignment->getMaxCharLimit(); + } + $text->setInfo($char_msg); + } - $form->addItem($text); - - // custom rte tags - $text->setUseRte(true); - $text->setRTESupport($this->submission->getUserId(), "exca~", "exc_ass"); - - // see ilObjForumGUI - $text->disableButtons(array( - 'charmap', - 'undo', - 'redo', - 'justifyleft', - 'justifycenter', - 'justifyright', - 'justifyfull', - 'anchor', - 'fullscreen', - 'cut', - 'copy', - 'paste', - 'pastetext', - 'code', - // 'formatselect' #13234 - )); - - $form->setFormAction($ilCtrl->getFormAction($this, "updateAssignmentText")); - $form->addCommandButton("updateAssignmentTextAndReturn", $this->lng->txt("save_return")); - $form->addCommandButton("updateAssignmentText", $this->lng->txt("save")); - $form->addCommandButton("returnToParent", $this->lng->txt("cancel")); - } - else - { - $form->setFormAction($ilCtrl->getFormAction($this, "returnToParent")); - $text = new ilNonEditableValueGUI($this->lng->txt("exc_files_returned_text"), "atxt", true); - $form->addItem($text); - } - - return $form; - } - - function editAssignmentTextObject(ilPropertyFormGUI $a_form = null) - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; + $form->addItem($text); + + // custom rte tags + $text->setUseRte(true); + $text->setRTESupport($this->submission->getUserId(), "exca~", "exc_ass"); + + // see ilObjForumGUI + $text->disableButtons(array( + 'charmap', + 'undo', + 'redo', + 'justifyleft', + 'justifycenter', + 'justifyright', + 'justifyfull', + 'anchor', + 'fullscreen', + 'cut', + 'copy', + 'paste', + 'pastetext', + 'code', + // 'formatselect' #13234 + )); + + $form->setFormAction($ilCtrl->getFormAction($this, "updateAssignmentText")); + $form->addCommandButton("updateAssignmentTextAndReturn", $this->lng->txt("save_return")); + $form->addCommandButton("updateAssignmentText", $this->lng->txt("save")); + $form->addCommandButton("returnToParent", $this->lng->txt("cancel")); + } else { + $form->setFormAction($ilCtrl->getFormAction($this, "returnToParent")); + $text = new ilNonEditableValueGUI($this->lng->txt("exc_files_returned_text"), "atxt", true); + $form->addItem($text); + } + + return $form; + } + + public function editAssignmentTextObject(ilPropertyFormGUI $a_form = null) + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; - if(!$this->submission->canSubmit()) - { - ilUtil::sendFailure($this->lng->txt("exercise_time_over"), true); - $ilCtrl->redirect($this, "returnToParent"); - } - - $deadline = max($this->assignment->getDeadline(), $this->assignment->getExtendedDeadline()); - if($deadline) - { - $deadline = $this->assignment->getPersonalDeadline($ilUser->getId()); - - // extended deadline date should not be presented anywhere - // see ilExAssignmentGUI::addSchedule() - $dl_info = ilDatePresentation::formatDate(new ilDateTime($deadline, IL_CAL_UNIX)); - - // #16151 - extended deadline warning (only after deadline passed) - if($deadline < time()) - { - $dl = ilDatePresentation::formatDate(new ilDateTime($deadline, IL_CAL_UNIX)); - $dl = '
'.sprintf($this->lng->txt("exc_late_submission_warning"), $dl).''; - $dl_info .= $dl; - } - - ilUtil::sendInfo($this->lng->txt("exc_edit_until").": ".$dl_info); - } - - $this->handleTabs(); + if (!$this->submission->canSubmit()) { + ilUtil::sendFailure($this->lng->txt("exercise_time_over"), true); + $ilCtrl->redirect($this, "returnToParent"); + } + + $deadline = max($this->assignment->getDeadline(), $this->assignment->getExtendedDeadline()); + if ($deadline) { + $deadline = $this->assignment->getPersonalDeadline($ilUser->getId()); + + // extended deadline date should not be presented anywhere + // see ilExAssignmentGUI::addSchedule() + $dl_info = ilDatePresentation::formatDate(new ilDateTime($deadline, IL_CAL_UNIX)); + + // #16151 - extended deadline warning (only after deadline passed) + if ($deadline < time()) { + $dl = ilDatePresentation::formatDate(new ilDateTime($deadline, IL_CAL_UNIX)); + $dl = '
' . sprintf($this->lng->txt("exc_late_submission_warning"), $dl) . ''; + $dl_info .= $dl; + } + + ilUtil::sendInfo($this->lng->txt("exc_edit_until") . ": " . $dl_info); + } + + $this->handleTabs(); - $ilHelp = $this->help; - $ilHelp->setScreenIdComponent("exc"); - $ilHelp->setScreenId("text_submission"); + $ilHelp = $this->help; + $ilHelp->setScreenIdComponent("exc"); + $ilHelp->setScreenId("text_submission"); - if(!$a_form) - { - $a_form = $this->initAssignmentTextForm(); + if (!$a_form) { + $a_form = $this->initAssignmentTextForm(); - $files = $this->submission->getFiles(); - if($files) - { - $files = array_shift($files); - if(trim($files["atext"])) - { - $text = $a_form->getItemByPostVar("atxt"); - // mob id to mob src - $text->setValue(ilRTE::_replaceMediaObjectImageSrc($files["atext"], 1)); - } - } - } - - $this->tpl->setContent($a_form->getHTML()); - } - - function updateAssignmentTextAndReturnObject() - { - $this->updateAssignmentTextObject(true); - } - - function updateAssignmentTextObject($a_return = false) - { - $ilCtrl = $this->ctrl; - - if(!$this->submission->canSubmit()) - { - ilUtil::sendFailure($this->lng->txt("exercise_time_over"), true); - $ilCtrl->redirect($this, "returnToParent"); - } - - $form = $this->initAssignmentTextForm(); - - // we are not using a purifier, so we have to set the valid RTE tags - // :TODO: - include_once("./Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php"); - $rte = $form->getItemByPostVar("atxt"); - $rte->setRteTags(ilObjAdvancedEditing::_getUsedHTMLTags("exc_ass")); - - if($form->checkInput()) - { - $text = trim($form->getInput("atxt")); - - $existing = $this->submission->getFiles(); - - $returned_id = $this->submission->updateTextSubmission( - // mob src to mob id - ilRTE::_replaceMediaObjectImageSrc($text, 0)); - - // no empty text - if($returned_id) - { - // #16532 - always send notifications - $this->handleNewUpload(); - - // mob usage - include_once "Services/MediaObjects/classes/class.ilObjMediaObject.php"; - $mobs = ilRTE::_getMediaObjects($text, 0); - foreach($mobs as $mob) - { - if(ilObjMediaObject::_exists($mob)) - { - ilObjMediaObject::_removeUsage($mob, 'exca~:html', $this->submission->getUserId()); - ilObjMediaObject::_saveUsage($mob, 'exca:html', $returned_id); - } - } - } - else - { - $this->handleRemovedUpload(); - } - - ilUtil::sendSuccess($this->lng->txt("exc_text_saved"), true); - if($a_return) - { - $ilCtrl->redirect($this, "returnToParent"); - } - else - { - $ilCtrl->redirect($this, "editAssignmentText"); - } - } - - $form->setValuesByPost(); - $this->editAssignmentTextObject($form); - } - - function showAssignmentTextObject() - { - if(!$this->submission->isTutor()) - { - $this->handleTabs(); - } - - $a_form = $this->initAssignmentTextForm(true); - - $files = $this->submission->getFiles(); - if($files) - { - $files = array_shift($files); - if(trim($files["atext"])) - { - if($files["late"] && - !$this->submission->hasPeerReviewAccess()) - { - ilUtil::sendFailure($this->lng->txt("exc_late_submission")); - } - - $text = $a_form->getItemByPostVar("atxt"); - // mob id to mob src - $text->setValue(nl2br(ilRTE::_replaceMediaObjectImageSrc($files["atext"], 1))); - } - } - - $this->tpl->setContent($a_form->getHTML()); - } + $files = $this->submission->getFiles(); + if ($files) { + $files = array_shift($files); + if (trim($files["atext"])) { + $text = $a_form->getItemByPostVar("atxt"); + // mob id to mob src + $text->setValue(ilRTE::_replaceMediaObjectImageSrc($files["atext"], 1)); + } + } + } + + $this->tpl->setContent($a_form->getHTML()); + } + + public function updateAssignmentTextAndReturnObject() + { + $this->updateAssignmentTextObject(true); + } + + public function updateAssignmentTextObject($a_return = false) + { + $ilCtrl = $this->ctrl; + + if (!$this->submission->canSubmit()) { + ilUtil::sendFailure($this->lng->txt("exercise_time_over"), true); + $ilCtrl->redirect($this, "returnToParent"); + } + + $form = $this->initAssignmentTextForm(); + + // we are not using a purifier, so we have to set the valid RTE tags + // :TODO: + include_once("./Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php"); + $rte = $form->getItemByPostVar("atxt"); + $rte->setRteTags(ilObjAdvancedEditing::_getUsedHTMLTags("exc_ass")); + + if ($form->checkInput()) { + $text = trim($form->getInput("atxt")); + + $existing = $this->submission->getFiles(); + + $returned_id = $this->submission->updateTextSubmission( + // mob src to mob id + ilRTE::_replaceMediaObjectImageSrc($text, 0) + ); + + // no empty text + if ($returned_id) { + // #16532 - always send notifications + $this->handleNewUpload(); + + // mob usage + include_once "Services/MediaObjects/classes/class.ilObjMediaObject.php"; + $mobs = ilRTE::_getMediaObjects($text, 0); + foreach ($mobs as $mob) { + if (ilObjMediaObject::_exists($mob)) { + ilObjMediaObject::_removeUsage($mob, 'exca~:html', $this->submission->getUserId()); + ilObjMediaObject::_saveUsage($mob, 'exca:html', $returned_id); + } + } + } else { + $this->handleRemovedUpload(); + } + + ilUtil::sendSuccess($this->lng->txt("exc_text_saved"), true); + if ($a_return) { + $ilCtrl->redirect($this, "returnToParent"); + } else { + $ilCtrl->redirect($this, "editAssignmentText"); + } + } + + $form->setValuesByPost(); + $this->editAssignmentTextObject($form); + } + + public function showAssignmentTextObject() + { + if (!$this->submission->isTutor()) { + $this->handleTabs(); + } + + $a_form = $this->initAssignmentTextForm(true); + + $files = $this->submission->getFiles(); + if ($files) { + $files = array_shift($files); + if (trim($files["atext"])) { + if ($files["late"] && + !$this->submission->hasPeerReviewAccess()) { + ilUtil::sendFailure($this->lng->txt("exc_late_submission")); + } + + $text = $a_form->getItemByPostVar("atxt"); + // mob id to mob src + $text->setValue(nl2br(ilRTE::_replaceMediaObjectImageSrc($files["atext"], 1))); + } + } + + $this->tpl->setContent($a_form->getHTML()); + } } diff --git a/Modules/Exercise/classes/class.ilExcAssMemberState.php b/Modules/Exercise/classes/class.ilExcAssMemberState.php index 0cacae3c5576f7e90414f15de06dd98e90675e91..a80aae272195c14766d47d93e7c7e7bc2b9738f3 100644 --- a/Modules/Exercise/classes/class.ilExcAssMemberState.php +++ b/Modules/Exercise/classes/class.ilExcAssMemberState.php @@ -31,560 +31,524 @@ */ class ilExcAssMemberState { - /** - * @var int - */ - protected $ass_id; - - /** - * @var int - */ - protected $user_id; - - /** - * @var ilExAssignment - */ - protected $assignment; - - /** - * @var int either user id or team id, if this is a team assignment and the user is member of a team, in this case is_team is true - */ - protected $member_id; - - /** - * @var int - */ - protected $team_id = 0; - - /** - * @var bool - */ - protected $is_team = false; - - /** - * ilExcAssMemberState constructor. - * @param int $a_ass_id assignment id - * @param int $a_user_id user id - */ - protected function __construct(ilExAssignment $a_ass, ilObjUser $a_user, ilExcIndividualDeadline $a_idl, $a_time, ilLanguage $lng, ilExAssignmentTeam $a_team = null) - { - $this->time = $a_time; - $this->ass_id = $a_ass->getId(); - $this->user_id = $a_user->getId(); - $this->member_id = $a_user->getId(); - $this->lng = $lng; - - $this->assignment = $a_ass; - - // check team status - $this->is_team = false; - if($this->assignment->getType() == ilExAssignment::TYPE_UPLOAD_TEAM) - { - if($a_team->getId()) - { - $this->member_id = $a_team->getId(); - $this->team_id = $a_team->getId(); - $this->is_team = true; - } - } - - $this->idl = $a_idl; - } - - /** - * Get instance by IDs (recommended for consumer code) - * - * @param int $a_ass_id assignment id - * @param int $a_user_id user id - * @return ilExcAssMemberState - */ - public static function getInstanceByIds($a_ass_id, $a_user_id = 0) - { - global $DIC; - - $lng = $DIC->language(); - $user = ($a_user_id > 0) - ? new ilObjUser($a_user_id) - : $DIC->user(); - - include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); - $ass = new ilExAssignment($a_ass_id); - - $member_id = $user->getId(); - $is_team = false; - $team = null; - if($ass->getType() == ilExAssignment::TYPE_UPLOAD_TEAM) // better move this to ilExcIndividualDeadline - { - include_once("./Modules/Exercise/classes/class.ilExAssignmentTeam.php"); - $team = ilExAssignmentTeam::getInstanceByUserId($a_ass_id, $user->getId()); - if ($team->getId()) - { - $member_id = $team->getId(); - $is_team = true; - } - } - - // note: team may be not null, but is_team still false - include_once("./Modules/Exercise/classes/class.ilExcIndividualDeadline.php"); - $idl = ilExcIndividualDeadline::getInstance($a_ass_id, $member_id, $is_team); - - return self::getInstance($ass, $user, $idl, time(), $lng, $team); - } - - /** - * Get instance by dependencies. - * - * Usually you should prefer to use getInstanceByIds. If you use getInstance you need to ensure consistency (e.g. deadline needs to match user) - */ - public static function getInstance(ilExAssignment $a_ass, ilObjUser $a_user, ilExcIndividualDeadline $a_idl, $a_time, ilLanguage $lng, ilExAssignmentTeam $a_team = null) - { - return new self($a_ass, $a_user, $a_idl, $a_time, $lng, $a_team); - } - - /** - * Get individual deadline object - * - * @return ilExcIndividualDeadline - */ - function getIndividualDeadlineObject() - { - return $this->idl; - } - - - /** - * Get general start - * - * @param - * @return - */ - function getGeneralStart() - { - return $this->assignment->getStartTime(); - } - - /** - * Get start presentation - * - * @return string - */ - function getGeneralStartPresentation() - { - if ($this->getGeneralStart()) - { - return $this->getTimePresentation($this->getGeneralStart()); - } - return ""; - } - - /** - * Get individual start - * - * @return int - */ - function getIndividualStart() - { - if ($this->assignment->getDeadlineMode() == ilExAssignment::DEADLINE_RELATIVE) - { - return $this->idl->getStartingTimestamp(); - } - return 0; - } - - - /** - * Has started - * - * @return bool - */ - function hasGenerallyStarted() - { - return !$this->assignment->notStartedYet(); - } - - /** - * Calculated deadline is only given, if a relative deadline is given and the user started the assignment - * - * @return int - */ - function getCalculatedDeadline() - { - $calculated_deadline = 0; - if ($this->assignment->getDeadlineMode() == ilExAssignment::DEADLINE_RELATIVE) - { - if ($this->idl->getStartingTimestamp() && $this->assignment->getRelativeDeadline()) - { - $calculated_deadline = $this->idl->getStartingTimestamp() + ($this->assignment->getRelativeDeadline() * 24 * 60 * 60); - } - } - return $calculated_deadline; - } - - /** - * Get relative deadline - * - * @return int - */ - function getRelativeDeadline() - { - if ($this->assignment->getDeadlineMode() == ilExAssignment::DEADLINE_RELATIVE) - { - return $this->assignment->getRelativeDeadline(); - } - return 0; - } - - /** - * Get relative deadline presentation - * - * @return string - */ - function getRelativeDeadlinePresentation() - { - if ($this->assignment->getDeadlineMode() == ilExAssignment::DEADLINE_RELATIVE) - { - return $this->getRelativeDeadline()." ".$this->lng->txt("days"); - } - return ""; - } - - /** - * Get official deadline (individual deadline, fixed deadline or calculated deadline (using relative deadline and starting ts)) - * - * Grace period is not taken into account here. - * - * @return int - */ - function getOfficialDeadline() - { - $dl = $this->idl->getIndividualDeadline(); // team or user individual deadline - - if ($this->assignment->getDeadlineMode() == ilExAssignment::DEADLINE_ABSOLUTE) // absolute deadline - { - return max($this->assignment->getDeadline(), $dl); // take what's greater: idl or abs deadline - } - - // relative deadline: take max idl or calculated deadline - return max($this->getCalculatedDeadline(), $dl); - } - - - /** - * Get official deadline presentation - * - * @return string - */ - function getOfficialDeadlinePresentation() - { - if ($this->getOfficialDeadline() > 0) - { - return $this->getTimePresentation($this->getOfficialDeadline()); - } - - return ""; - } - - /** - * Check if official deadline exists and has ended - * - * @return bool - */ - function exceededOfficialDeadline() - { - $od = $this->getOfficialDeadline(); - if ($od && $od < time()) - { - return true; - } - return false; - } - - /** - * Remaining time presentation (based on official deadline) - * - * @param - * @return string - */ - function getRemainingTimePresentation() - { - $lng = $this->lng; - $official_deadline = $this->getOfficialDeadline(); - if ($official_deadline == 0) - { - return $lng->txt("exc_no_deadline_specified"); - } - if ($official_deadline - $this->time <= 0) - { - $time_str = $lng->txt("exc_time_over_short"); - } - else - { - $time_str = ilUtil::period2String(new ilDateTime($official_deadline, IL_CAL_UNIX)); - } - - return $time_str; - } - - /** - * Get individual deadline - * - * @return int - */ - function getIndividualDeadline() - { - if ($this->idl->getIndividualDeadline() > $this->getCommonDeadline()) - { - return $this->idl->getIndividualDeadline(); - } - return 0; - } - - - /** - * Get common deadline presentation - * - * @return string - */ - function getIndividualDeadlinePresentation() - { - if ($this->getIndividualDeadline() > 0) - { - return $this->getTimePresentation($this->getIndividualDeadline()); - } - - return ""; - } - - /** - * Get common deadline (no individual deadline or grace period included) - * - * @return int - */ - function getCommonDeadline() - { - if ($this->assignment->getDeadlineMode() == ilExAssignment::DEADLINE_ABSOLUTE) // absolute deadline - { - return $this->assignment->getDeadline(); - } - - return $this->getCalculatedDeadline(); - } - - /** - * Get common deadline presentation - * - * @return string - */ - function getCommonDeadlinePresentation() - { - if ($this->getCommonDeadline() > 0) - { - return $this->getTimePresentation($this->getCommonDeadline()); - } - - return "no deadline"; - } - - /** - * Get effective deadline (max of official deadline and grace end period) for the user - * - * @return int - */ - function getEffectiveDeadline() - { - return max($this->getOfficialDeadline(), $this->assignment->getExtendedDeadline()); - } - - /** - * Get peer review deadline - * - * @return int - */ - function getPeerReviewDeadline() - { - if ($this->assignment->getPeerReview() && - $this->assignment->getPeerReviewDeadline()) - { - return $this->assignment->getPeerReviewDeadline(); - } - return 0; - } - - /** - * Get common deadline presentation - * - * @return string - */ - function getPeerReviewDeadlinePresentation() - { - if ($this->getPeerReviewDeadline() > 0) - { - return $this->getTimePresentation($this->getPeerReviewDeadline()); - } - - return "no peer review deadline"; - } - - /** - * Is submission currently allowed - * - * @return bool - */ - function isPeerReviewAllowed() - { - if ($this->assignment->getPeerReview() && $this->hasSubmissionEndedForAllUsers() - && ($this->getPeerReviewDeadline() == 0 || $this->getPeerReviewDeadline() > $this->time)) - { - return true; - } - - return false; - } - - /** - * Get common deadline presentation - * - * @return string - */ - protected function getTimePresentation($a_timestamp) - { - if ($a_timestamp > 0) - { - return ilDatePresentation::formatDate(new ilDateTime($a_timestamp, IL_CAL_UNIX)); - } - - return ""; - } - - /** - * Instructions visible - * - * @return bool - */ - function areInstructionsVisible() - { - return $this->hasSubmissionStarted(); - } - - /** - * Get late submission warning - * - * @param - * @return - */ - /* - function getLateSubmissionWarning() - { - $lng = $this->lng; - $late_dl = ""; - - // official deadline is done, but submission still allowed - if ($this->inLateSubmissionPhase()) - { - // extended deadline date should not be presented anywhere - $late_dl = $this->getTimePresentation($this->getOfficialDeadline()); - $late_dl = "
".sprintf($lng->txt("exc_late_submission_warning"), $late_dl); - $late_dl = ''.$late_dl.''; - } - - return $late_dl; - }*/ - - /** - * In late submission phase - * - * @param - * @return - */ - function inLateSubmissionPhase() - { - // official deadline is done, but submission still allowed - if ($this->getOfficialDeadline() && - $this->getOfficialDeadline() < $this->time && - $this->isSubmissionAllowed()) - { - return true; - } - return false; - } - - - /** - * Check if the submission phase has started for the current user - * - * (if the assignment is generally started and for relative deadlines, if the user started the assignment) - * - * @return bool - */ - function hasSubmissionStarted() - { - if ($this->hasGenerallyStarted() && ($this->assignment->getDeadlineMode() == ilExAssignment::DEADLINE_ABSOLUTE || - $this->getIndividualStart() > 0)) - { - return true; - } - return false; - } - - /** - * Check if the submission phase has ended for the current user - * - * @return bool - */ - function hasSubmissionEnded() - { - if ($this->getEffectiveDeadline() == 0) - { - return false; - } - - if ($this->time > $this->getEffectiveDeadline()) - { - return true; - } - return false; - } - - /** - * Has submission ended for all users - * - * @param - * @return - */ - function hasSubmissionEndedForAllUsers() - { - $global_subm_end = max($this->getEffectiveDeadline(), $this->assignment->getLastPersonalDeadline()); - - if ($global_subm_end == 0) - { - return false; - } - - if ($this->time > $global_subm_end) - { - return true; - } - return false; - } - - - - /** - * Is submission currently allowed - * - * @param - * @return - */ - function isSubmissionAllowed() - { - if ($this->hasSubmissionStarted() && !$this->hasSubmissionEnded()) - { - return true; - } - return false; - } - - - - -} \ No newline at end of file + /** + * @var int + */ + protected $ass_id; + + /** + * @var int + */ + protected $user_id; + + /** + * @var ilExAssignment + */ + protected $assignment; + + /** + * @var int either user id or team id, if this is a team assignment and the user is member of a team, in this case is_team is true + */ + protected $member_id; + + /** + * @var int + */ + protected $team_id = 0; + + /** + * @var bool + */ + protected $is_team = false; + + /** + * ilExcAssMemberState constructor. + * @param int $a_ass_id assignment id + * @param int $a_user_id user id + */ + protected function __construct(ilExAssignment $a_ass, ilObjUser $a_user, ilExcIndividualDeadline $a_idl, $a_time, ilLanguage $lng, ilExAssignmentTeam $a_team = null) + { + $this->time = $a_time; + $this->ass_id = $a_ass->getId(); + $this->user_id = $a_user->getId(); + $this->member_id = $a_user->getId(); + $this->lng = $lng; + + $this->assignment = $a_ass; + + // check team status + $this->is_team = false; + if ($this->assignment->getType() == ilExAssignment::TYPE_UPLOAD_TEAM) { + if ($a_team->getId()) { + $this->member_id = $a_team->getId(); + $this->team_id = $a_team->getId(); + $this->is_team = true; + } + } + + $this->idl = $a_idl; + } + + /** + * Get instance by IDs (recommended for consumer code) + * + * @param int $a_ass_id assignment id + * @param int $a_user_id user id + * @return ilExcAssMemberState + */ + public static function getInstanceByIds($a_ass_id, $a_user_id = 0) + { + global $DIC; + + $lng = $DIC->language(); + $user = ($a_user_id > 0) + ? new ilObjUser($a_user_id) + : $DIC->user(); + + include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); + $ass = new ilExAssignment($a_ass_id); + + $member_id = $user->getId(); + $is_team = false; + $team = null; + if ($ass->getType() == ilExAssignment::TYPE_UPLOAD_TEAM) { // better move this to ilExcIndividualDeadline + include_once("./Modules/Exercise/classes/class.ilExAssignmentTeam.php"); + $team = ilExAssignmentTeam::getInstanceByUserId($a_ass_id, $user->getId()); + if ($team->getId()) { + $member_id = $team->getId(); + $is_team = true; + } + } + + // note: team may be not null, but is_team still false + include_once("./Modules/Exercise/classes/class.ilExcIndividualDeadline.php"); + $idl = ilExcIndividualDeadline::getInstance($a_ass_id, $member_id, $is_team); + + return self::getInstance($ass, $user, $idl, time(), $lng, $team); + } + + /** + * Get instance by dependencies. + * + * Usually you should prefer to use getInstanceByIds. If you use getInstance you need to ensure consistency (e.g. deadline needs to match user) + */ + public static function getInstance(ilExAssignment $a_ass, ilObjUser $a_user, ilExcIndividualDeadline $a_idl, $a_time, ilLanguage $lng, ilExAssignmentTeam $a_team = null) + { + return new self($a_ass, $a_user, $a_idl, $a_time, $lng, $a_team); + } + + /** + * Get individual deadline object + * + * @return ilExcIndividualDeadline + */ + public function getIndividualDeadlineObject() + { + return $this->idl; + } + + + /** + * Get general start + * + * @param + * @return + */ + public function getGeneralStart() + { + return $this->assignment->getStartTime(); + } + + /** + * Get start presentation + * + * @return string + */ + public function getGeneralStartPresentation() + { + if ($this->getGeneralStart()) { + return $this->getTimePresentation($this->getGeneralStart()); + } + return ""; + } + + /** + * Get individual start + * + * @return int + */ + public function getIndividualStart() + { + if ($this->assignment->getDeadlineMode() == ilExAssignment::DEADLINE_RELATIVE) { + return $this->idl->getStartingTimestamp(); + } + return 0; + } + + + /** + * Has started + * + * @return bool + */ + public function hasGenerallyStarted() + { + return !$this->assignment->notStartedYet(); + } + + /** + * Calculated deadline is only given, if a relative deadline is given and the user started the assignment + * + * @return int + */ + public function getCalculatedDeadline() + { + $calculated_deadline = 0; + if ($this->assignment->getDeadlineMode() == ilExAssignment::DEADLINE_RELATIVE) { + if ($this->idl->getStartingTimestamp() && $this->assignment->getRelativeDeadline()) { + $calculated_deadline = $this->idl->getStartingTimestamp() + ($this->assignment->getRelativeDeadline() * 24 * 60 * 60); + } + } + return $calculated_deadline; + } + + /** + * Get relative deadline + * + * @return int + */ + public function getRelativeDeadline() + { + if ($this->assignment->getDeadlineMode() == ilExAssignment::DEADLINE_RELATIVE) { + return $this->assignment->getRelativeDeadline(); + } + return 0; + } + + /** + * Get relative deadline presentation + * + * @return string + */ + public function getRelativeDeadlinePresentation() + { + if ($this->assignment->getDeadlineMode() == ilExAssignment::DEADLINE_RELATIVE) { + return $this->getRelativeDeadline() . " " . $this->lng->txt("days"); + } + return ""; + } + + /** + * Get official deadline (individual deadline, fixed deadline or calculated deadline (using relative deadline and starting ts)) + * + * Grace period is not taken into account here. + * + * @return int + */ + public function getOfficialDeadline() + { + $dl = $this->idl->getIndividualDeadline(); // team or user individual deadline + + if ($this->assignment->getDeadlineMode() == ilExAssignment::DEADLINE_ABSOLUTE) { // absolute deadline + return max($this->assignment->getDeadline(), $dl); // take what's greater: idl or abs deadline + } + + // relative deadline: take max idl or calculated deadline + return max($this->getCalculatedDeadline(), $dl); + } + + + /** + * Get official deadline presentation + * + * @return string + */ + public function getOfficialDeadlinePresentation() + { + if ($this->getOfficialDeadline() > 0) { + return $this->getTimePresentation($this->getOfficialDeadline()); + } + + return ""; + } + + /** + * Check if official deadline exists and has ended + * + * @return bool + */ + public function exceededOfficialDeadline() + { + $od = $this->getOfficialDeadline(); + if ($od && $od < time()) { + return true; + } + return false; + } + + /** + * Remaining time presentation (based on official deadline) + * + * @param + * @return string + */ + public function getRemainingTimePresentation() + { + $lng = $this->lng; + $official_deadline = $this->getOfficialDeadline(); + if ($official_deadline == 0) { + return $lng->txt("exc_no_deadline_specified"); + } + if ($official_deadline - $this->time <= 0) { + $time_str = $lng->txt("exc_time_over_short"); + } else { + $time_str = ilUtil::period2String(new ilDateTime($official_deadline, IL_CAL_UNIX)); + } + + return $time_str; + } + + /** + * Get individual deadline + * + * @return int + */ + public function getIndividualDeadline() + { + if ($this->idl->getIndividualDeadline() > $this->getCommonDeadline()) { + return $this->idl->getIndividualDeadline(); + } + return 0; + } + + + /** + * Get common deadline presentation + * + * @return string + */ + public function getIndividualDeadlinePresentation() + { + if ($this->getIndividualDeadline() > 0) { + return $this->getTimePresentation($this->getIndividualDeadline()); + } + + return ""; + } + + /** + * Get common deadline (no individual deadline or grace period included) + * + * @return int + */ + public function getCommonDeadline() + { + if ($this->assignment->getDeadlineMode() == ilExAssignment::DEADLINE_ABSOLUTE) { // absolute deadline + return $this->assignment->getDeadline(); + } + + return $this->getCalculatedDeadline(); + } + + /** + * Get common deadline presentation + * + * @return string + */ + public function getCommonDeadlinePresentation() + { + if ($this->getCommonDeadline() > 0) { + return $this->getTimePresentation($this->getCommonDeadline()); + } + + return "no deadline"; + } + + /** + * Get effective deadline (max of official deadline and grace end period) for the user + * + * @return int + */ + public function getEffectiveDeadline() + { + return max($this->getOfficialDeadline(), $this->assignment->getExtendedDeadline()); + } + + /** + * Get peer review deadline + * + * @return int + */ + public function getPeerReviewDeadline() + { + if ($this->assignment->getPeerReview() && + $this->assignment->getPeerReviewDeadline()) { + return $this->assignment->getPeerReviewDeadline(); + } + return 0; + } + + /** + * Get common deadline presentation + * + * @return string + */ + public function getPeerReviewDeadlinePresentation() + { + if ($this->getPeerReviewDeadline() > 0) { + return $this->getTimePresentation($this->getPeerReviewDeadline()); + } + + return "no peer review deadline"; + } + + /** + * Is submission currently allowed + * + * @return bool + */ + public function isPeerReviewAllowed() + { + if ($this->assignment->getPeerReview() && $this->hasSubmissionEndedForAllUsers() + && ($this->getPeerReviewDeadline() == 0 || $this->getPeerReviewDeadline() > $this->time)) { + return true; + } + + return false; + } + + /** + * Get common deadline presentation + * + * @return string + */ + protected function getTimePresentation($a_timestamp) + { + if ($a_timestamp > 0) { + return ilDatePresentation::formatDate(new ilDateTime($a_timestamp, IL_CAL_UNIX)); + } + + return ""; + } + + /** + * Instructions visible + * + * @return bool + */ + public function areInstructionsVisible() + { + return $this->hasSubmissionStarted(); + } + + /** + * Get late submission warning + * + * @param + * @return + */ + /* + function getLateSubmissionWarning() + { + $lng = $this->lng; + $late_dl = ""; + + // official deadline is done, but submission still allowed + if ($this->inLateSubmissionPhase()) + { + // extended deadline date should not be presented anywhere + $late_dl = $this->getTimePresentation($this->getOfficialDeadline()); + $late_dl = "
".sprintf($lng->txt("exc_late_submission_warning"), $late_dl); + $late_dl = ''.$late_dl.''; + } + + return $late_dl; + }*/ + + /** + * In late submission phase + * + * @param + * @return + */ + public function inLateSubmissionPhase() + { + // official deadline is done, but submission still allowed + if ($this->getOfficialDeadline() && + $this->getOfficialDeadline() < $this->time && + $this->isSubmissionAllowed()) { + return true; + } + return false; + } + + + /** + * Check if the submission phase has started for the current user + * + * (if the assignment is generally started and for relative deadlines, if the user started the assignment) + * + * @return bool + */ + public function hasSubmissionStarted() + { + if ($this->hasGenerallyStarted() && ($this->assignment->getDeadlineMode() == ilExAssignment::DEADLINE_ABSOLUTE || + $this->getIndividualStart() > 0)) { + return true; + } + return false; + } + + /** + * Check if the submission phase has ended for the current user + * + * @return bool + */ + public function hasSubmissionEnded() + { + if ($this->getEffectiveDeadline() == 0) { + return false; + } + + if ($this->time > $this->getEffectiveDeadline()) { + return true; + } + return false; + } + + /** + * Has submission ended for all users + * + * @param + * @return + */ + public function hasSubmissionEndedForAllUsers() + { + $global_subm_end = max($this->getEffectiveDeadline(), $this->assignment->getLastPersonalDeadline()); + + if ($global_subm_end == 0) { + return false; + } + + if ($this->time > $global_subm_end) { + return true; + } + return false; + } + + + + /** + * Is submission currently allowed + * + * @param + * @return + */ + public function isSubmissionAllowed() + { + if ($this->hasSubmissionStarted() && !$this->hasSubmissionEnded()) { + return true; + } + return false; + } +} diff --git a/Modules/Exercise/classes/class.ilExcCriteria.php b/Modules/Exercise/classes/class.ilExcCriteria.php index ebe4ab29434a61b1470df5e445cd4c8e79fc5172..51d9bce724c72793601ea658eb8c635dbcf2effb 100644 --- a/Modules/Exercise/classes/class.ilExcCriteria.php +++ b/Modules/Exercise/classes/class.ilExcCriteria.php @@ -10,387 +10,374 @@ */ abstract class ilExcCriteria { - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; - protected $id; // [int] - protected $parent; // [int] - protected $title; // [string] - protected $desc; // [string] - protected $required; // [bool] - protected $pos; // [int] - protected $def; // [string] - - protected $form; // [ilPropertyFormGUI] - protected $ass; // [ilExAssignment] - protected $giver_id; // [int] - protected $peer_id; // [int] - - protected function __construct() - { - global $DIC; + protected $id; // [int] + protected $parent; // [int] + protected $title; // [string] + protected $desc; // [string] + protected $required; // [bool] + protected $pos; // [int] + protected $def; // [string] + + protected $form; // [ilPropertyFormGUI] + protected $ass; // [ilExAssignment] + protected $giver_id; // [int] + protected $peer_id; // [int] + + protected function __construct() + { + global $DIC; - $this->db = $DIC->database(); - - } - - public static function getInstanceById($a_id) - { - global $DIC; + $this->db = $DIC->database(); + } + + public static function getInstanceById($a_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT *". - " FROM exc_crit". - " WHERE id = ".$ilDB->quote($a_id, "integer")); - if($ilDB->numRows($set)) - { - $row = $ilDB->fetchAssoc($set); - $obj = self::getInstanceByType($row["type"]); - $obj->importFromDB($row); - return $obj; - } - } - - public static function getInstancesByParentId($a_parent_id) - { - global $DIC; + $ilDB = $DIC->database(); + + $set = $ilDB->query("SELECT *" . + " FROM exc_crit" . + " WHERE id = " . $ilDB->quote($a_id, "integer")); + if ($ilDB->numRows($set)) { + $row = $ilDB->fetchAssoc($set); + $obj = self::getInstanceByType($row["type"]); + $obj->importFromDB($row); + return $obj; + } + } + + public static function getInstancesByParentId($a_parent_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $res = array(); - - $set = $ilDB->query("SELECT *". - " FROM exc_crit". - " WHERE parent = ".$ilDB->quote($a_parent_id, "integer"). - " ORDER BY pos"); - while($row = $ilDB->fetchAssoc($set)) - { - $obj = self::getInstanceByType($row["type"]); - $obj->importFromDB($row); - $res[$obj->getId()] = $obj; - } - - return $res; - } - - - // - // type(s) - // - - public static function getTypesMap() - { - global $DIC; + $ilDB = $DIC->database(); + + $res = array(); + + $set = $ilDB->query("SELECT *" . + " FROM exc_crit" . + " WHERE parent = " . $ilDB->quote($a_parent_id, "integer") . + " ORDER BY pos"); + while ($row = $ilDB->fetchAssoc($set)) { + $obj = self::getInstanceByType($row["type"]); + $obj->importFromDB($row); + $res[$obj->getId()] = $obj; + } + + return $res; + } + + + // + // type(s) + // + + public static function getTypesMap() + { + global $DIC; - $lng = $DIC->language(); - - return array( - "bool" => $lng->txt("exc_criteria_type_bool") - ,"rating" => $lng->txt("exc_criteria_type_rating") - ,"text" => $lng->txt("exc_criteria_type_text") - ,"file" => $lng->txt("exc_criteria_type_file") - ); - } - - public function getTranslatedType() - { - $map = $this->getTypesMap(); - return $map[$this->getType()]; - } - - public static function getInstanceByType($a_type) - { - $class = "ilExcCriteria".ucfirst($a_type); - include_once "Modules/Exercise/classes/class.".$class.".php"; - return new $class; - } - - - // - // properties - // - - public function getId() - { - return $this->id; - } - - protected function setId($a_id) - { - $this->id = (int)$a_id; - } - - abstract public function getType(); - - public function setParent($a_value) - { - $this->parent = ($a_value !== null) - ? (int)$a_value - : null; - } - - public function getParent() - { - return $this->parent; - } - - public function setTitle($a_value) - { - $this->title = ($a_value !== null) - ? trim($a_value) - : null; - } - - public function getTitle() - { - return $this->title; - } - - public function setDescription($a_value) - { - $this->desc = ($a_value !== null) - ? trim($a_value) - : null; - } - - public function getDescription() - { - return $this->desc; - } - - public function setRequired($a_value) - { - $this->required = (bool)$a_value; - } - - public function isRequired() - { - return $this->required; - } + $lng = $DIC->language(); + + return array( + "bool" => $lng->txt("exc_criteria_type_bool") + ,"rating" => $lng->txt("exc_criteria_type_rating") + ,"text" => $lng->txt("exc_criteria_type_text") + ,"file" => $lng->txt("exc_criteria_type_file") + ); + } + + public function getTranslatedType() + { + $map = $this->getTypesMap(); + return $map[$this->getType()]; + } + + public static function getInstanceByType($a_type) + { + $class = "ilExcCriteria" . ucfirst($a_type); + include_once "Modules/Exercise/classes/class." . $class . ".php"; + return new $class; + } + + + // + // properties + // + + public function getId() + { + return $this->id; + } + + protected function setId($a_id) + { + $this->id = (int) $a_id; + } + + abstract public function getType(); + + public function setParent($a_value) + { + $this->parent = ($a_value !== null) + ? (int) $a_value + : null; + } + + public function getParent() + { + return $this->parent; + } + + public function setTitle($a_value) + { + $this->title = ($a_value !== null) + ? trim($a_value) + : null; + } + + public function getTitle() + { + return $this->title; + } + + public function setDescription($a_value) + { + $this->desc = ($a_value !== null) + ? trim($a_value) + : null; + } + + public function getDescription() + { + return $this->desc; + } + + public function setRequired($a_value) + { + $this->required = (bool) $a_value; + } + + public function isRequired() + { + return $this->required; + } - public function setPosition($a_value) - { - $this->pos = (int)$a_value; - } - - public function getPosition() - { - return $this->pos; - } - - protected function setDefinition(array $a_value = null) - { - $this->def = $a_value; - } - - protected function getDefinition() - { - return $this->def; - } - - public function importDefinition($a_def, $a_def_json) - { - // see #23711 - // use json, if given - if ($a_def_json != "") - { - $def = json_decode($a_def_json, true); - if (is_array($def)) - { - $this->setDefinition($def); - } - return; - } + public function setPosition($a_value) + { + $this->pos = (int) $a_value; + } + + public function getPosition() + { + return $this->pos; + } + + protected function setDefinition(array $a_value = null) + { + $this->def = $a_value; + } + + protected function getDefinition() + { + return $this->def; + } + + public function importDefinition($a_def, $a_def_json) + { + // see #23711 + // use json, if given + if ($a_def_json != "") { + $def = json_decode($a_def_json, true); + if (is_array($def)) { + $this->setDefinition($def); + } + return; + } - // use unserialize only if php > 7 - if ($a_def != "" && version_compare(PHP_VERSION, '7.0.0') >= 0) - { - $a_def = @unserialize($a_def, false); - if(is_array($a_def)) - { - $this->setDefinition($a_def); - } - } - } - - - // - // CRUD - // - - protected function importFromDB(array $a_row) - { - $this->setId($a_row["id"]); - $this->setParent($a_row["parent"]); - $this->setTitle($a_row["title"]); - $this->setDescription($a_row["descr"]); - $this->setRequired($a_row["required"]); - $this->setPosition($a_row["pos"]); - $this->setDefinition($a_row["def"] - ? unserialize($a_row["def"]) - : null); - } - - protected function getDBProperties() - { - return array( - "type" => array("text", $this->getType()) - ,"title" => array("text", $this->getTitle()) - ,"descr" => array("text", $this->getDescription()) - ,"required" => array("integer", $this->isRequired()) - ,"pos" => array("integer", $this->getPosition()) - ,"def" => array("text", is_array($this->getDefinition()) - ? serialize($this->getDefinition()) - : null) - ); - } - protected function getLastPosition() - { - $ilDB = $this->db; - - if(!$this->getParent()) - { - return; - } - - $set = $ilDB->query("SELECT MAX(pos) pos". - " FROM exc_crit". - " WHERE parent = ".$ilDB->quote($this->getParent(), "integer")); - $row = $ilDB->fetchAssoc($set); - return (int)$row["pos"]; - } - - public function save() - { - $ilDB = $this->db; - - if($this->id) - { - return $this->update(); - } - - $this->id = $ilDB->nextId("exc_crit"); - - $fields = $this->getDBProperties(); - - $fields["id"] = array("integer", $this->id); - $fields["type"] = array("text", $this->getType()); - $fields["parent"] = array("integer", $this->getParent()); - $fields["pos"] = array("integer", $this->getLastPosition()+10); - - $ilDB->insert("exc_crit", $fields); - } - - public function update() - { - $ilDB = $this->db; - - if(!$this->id) - { - return $this->save(); - } - - $primary = array("id"=>array("integer", $this->id)); - $ilDB->update("exc_crit", $this->getDBProperties(), $primary); - } - - public function delete() - { - $ilDB = $this->db; - - if(!$this->id) - { - return; - } - - $ilDB->manipulate("DELETE FROM exc_crit". - " WHERE id = ".$ilDB->quote($this->id, "integer")); - } - - public static function deleteByParent($a_parent_id) - { - global $DIC; + // use unserialize only if php > 7 + if ($a_def != "" && version_compare(PHP_VERSION, '7.0.0') >= 0) { + $a_def = @unserialize($a_def, false); + if (is_array($a_def)) { + $this->setDefinition($a_def); + } + } + } + + + // + // CRUD + // + + protected function importFromDB(array $a_row) + { + $this->setId($a_row["id"]); + $this->setParent($a_row["parent"]); + $this->setTitle($a_row["title"]); + $this->setDescription($a_row["descr"]); + $this->setRequired($a_row["required"]); + $this->setPosition($a_row["pos"]); + $this->setDefinition($a_row["def"] + ? unserialize($a_row["def"]) + : null); + } + + protected function getDBProperties() + { + return array( + "type" => array("text", $this->getType()) + ,"title" => array("text", $this->getTitle()) + ,"descr" => array("text", $this->getDescription()) + ,"required" => array("integer", $this->isRequired()) + ,"pos" => array("integer", $this->getPosition()) + ,"def" => array("text", is_array($this->getDefinition()) + ? serialize($this->getDefinition()) + : null) + ); + } + protected function getLastPosition() + { + $ilDB = $this->db; + + if (!$this->getParent()) { + return; + } + + $set = $ilDB->query("SELECT MAX(pos) pos" . + " FROM exc_crit" . + " WHERE parent = " . $ilDB->quote($this->getParent(), "integer")); + $row = $ilDB->fetchAssoc($set); + return (int) $row["pos"]; + } + + public function save() + { + $ilDB = $this->db; + + if ($this->id) { + return $this->update(); + } + + $this->id = $ilDB->nextId("exc_crit"); + + $fields = $this->getDBProperties(); + + $fields["id"] = array("integer", $this->id); + $fields["type"] = array("text", $this->getType()); + $fields["parent"] = array("integer", $this->getParent()); + $fields["pos"] = array("integer", $this->getLastPosition()+10); + + $ilDB->insert("exc_crit", $fields); + } + + public function update() + { + $ilDB = $this->db; + + if (!$this->id) { + return $this->save(); + } + + $primary = array("id"=>array("integer", $this->id)); + $ilDB->update("exc_crit", $this->getDBProperties(), $primary); + } + + public function delete() + { + $ilDB = $this->db; + + if (!$this->id) { + return; + } + + $ilDB->manipulate("DELETE FROM exc_crit" . + " WHERE id = " . $ilDB->quote($this->id, "integer")); + } + + public static function deleteByParent($a_parent_id) + { + global $DIC; - $ilDB = $DIC->database(); - - if(!(int)$a_parent_id) - { - return; - } - - $ilDB->manipulate("DELETE FROM exc_crit". - " WHERE parent = ".$ilDB->quote($a_parent_id, "integer")); - } - - public function cloneObject($a_target_parent_id) - { - $new_obj = ilExcCriteria::getInstanceByType($this->getType()); - $new_obj->setParent($a_target_parent_id); - $new_obj->setTitle($this->getTitle()); - $new_obj->setDescription($this->getDescription()); - $new_obj->setRequired($this->isRequired()); - $new_obj->setPosition($this->getPosition()); - $new_obj->setDefinition($this->getDefinition()); - $new_obj->save(); - - return $new_obj->getId(); - } - - - // - // ASSIGNMENT EDITOR - // - - public function initCustomForm(ilPropertyFormGUI $a_form) - { - // type-specific - } - - public function exportCustomForm(ilPropertyFormGUI $a_form) - { - // type-specific - } - - public function importCustomForm(ilPropertyFormGUI $a_form) - { - // type-specific - } - - - // PEER REVIEW - - public function setPeerReviewContext(ilExAssignment $a_ass, $a_giver_id, $a_peer_id, ilPropertyFormGUI $a_form = null) - { - $this->form = $a_form; - $this->ass = $a_ass; - $this->giver_id = $a_giver_id; - $this->peer_id = $a_peer_id; - } - - abstract public function addToPeerReviewForm($a_value = null); - - abstract public function importFromPeerReviewForm(); - - public function updateFromAjax() - { - // type-specific - } - - public function validate($a_value) - { - return true; - } - - abstract public function hasValue($a_value); - - abstract public function getHTML($a_value); - - public function resetReview() - { - // type-specific (only needed for data not kept in exc_assignment_peer) - } - -} \ No newline at end of file + $ilDB = $DIC->database(); + + if (!(int) $a_parent_id) { + return; + } + + $ilDB->manipulate("DELETE FROM exc_crit" . + " WHERE parent = " . $ilDB->quote($a_parent_id, "integer")); + } + + public function cloneObject($a_target_parent_id) + { + $new_obj = ilExcCriteria::getInstanceByType($this->getType()); + $new_obj->setParent($a_target_parent_id); + $new_obj->setTitle($this->getTitle()); + $new_obj->setDescription($this->getDescription()); + $new_obj->setRequired($this->isRequired()); + $new_obj->setPosition($this->getPosition()); + $new_obj->setDefinition($this->getDefinition()); + $new_obj->save(); + + return $new_obj->getId(); + } + + + // + // ASSIGNMENT EDITOR + // + + public function initCustomForm(ilPropertyFormGUI $a_form) + { + // type-specific + } + + public function exportCustomForm(ilPropertyFormGUI $a_form) + { + // type-specific + } + + public function importCustomForm(ilPropertyFormGUI $a_form) + { + // type-specific + } + + + // PEER REVIEW + + public function setPeerReviewContext(ilExAssignment $a_ass, $a_giver_id, $a_peer_id, ilPropertyFormGUI $a_form = null) + { + $this->form = $a_form; + $this->ass = $a_ass; + $this->giver_id = $a_giver_id; + $this->peer_id = $a_peer_id; + } + + abstract public function addToPeerReviewForm($a_value = null); + + abstract public function importFromPeerReviewForm(); + + public function updateFromAjax() + { + // type-specific + } + + public function validate($a_value) + { + return true; + } + + abstract public function hasValue($a_value); + + abstract public function getHTML($a_value); + + public function resetReview() + { + // type-specific (only needed for data not kept in exc_assignment_peer) + } +} diff --git a/Modules/Exercise/classes/class.ilExcCriteriaBool.php b/Modules/Exercise/classes/class.ilExcCriteriaBool.php index c3de03d94f8f16a2aee6292587951f8047a21e56..670ed0ee9432172215c79778ac5c08014bae9d97 100644 --- a/Modules/Exercise/classes/class.ilExcCriteriaBool.php +++ b/Modules/Exercise/classes/class.ilExcCriteriaBool.php @@ -12,83 +12,76 @@ include_once "Modules/Exercise/classes/class.ilExcCriteria.php"; */ class ilExcCriteriaBool extends ilExcCriteria { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * Constructor - */ - function __construct() - { - global $DIC; + /** + * Constructor + */ + public function __construct() + { + global $DIC; - parent::__construct(); - $this->lng = $DIC->language(); - } + parent::__construct(); + $this->lng = $DIC->language(); + } - public function getType() - { - return "bool"; - } - - - // PEER REVIEW - - public function addToPeerReviewForm($a_value = null) - { - $lng = $this->lng; - - if(!$this->isRequired()) - { - $input = new ilCheckboxInputGUI($this->getTitle(), "prccc_bool_".$this->getId()); - $input->setInfo($this->getDescription()); - $input->setRequired($this->isRequired()); - $input->setChecked($a_value > 0); - } - else - { - $input = new ilSelectInputGUI($this->getTitle(), "prccc_bool_".$this->getId()); - $input->setInfo($this->getDescription()); - $input->setRequired($this->isRequired()); - $input->setValue($a_value); - $options = array(); - if(!$a_value) - { - $options[""] = $lng->txt("please_select"); - } - $options[1] = $lng->txt("yes"); - $options[-1] = $lng->txt("no"); - $input->setOptions($options); - } - $this->form->addItem($input); - } - - public function importFromPeerReviewForm() - { - return (int)$this->form->getInput("prccc_bool_".$this->getId()); - } - - public function hasValue($a_value) - { - return (int)$a_value; - } - - public function getHTML($a_value) - { - $lng = $this->lng; - - $caption = null; - if($this->isRequired() && $a_value < 0) - { - $caption = $lng->txt("no"); - } - else if($a_value == 1) - { - $caption = $lng->txt("yes"); - } - return $caption; - } + public function getType() + { + return "bool"; + } + + + // PEER REVIEW + + public function addToPeerReviewForm($a_value = null) + { + $lng = $this->lng; + + if (!$this->isRequired()) { + $input = new ilCheckboxInputGUI($this->getTitle(), "prccc_bool_" . $this->getId()); + $input->setInfo($this->getDescription()); + $input->setRequired($this->isRequired()); + $input->setChecked($a_value > 0); + } else { + $input = new ilSelectInputGUI($this->getTitle(), "prccc_bool_" . $this->getId()); + $input->setInfo($this->getDescription()); + $input->setRequired($this->isRequired()); + $input->setValue($a_value); + $options = array(); + if (!$a_value) { + $options[""] = $lng->txt("please_select"); + } + $options[1] = $lng->txt("yes"); + $options[-1] = $lng->txt("no"); + $input->setOptions($options); + } + $this->form->addItem($input); + } + + public function importFromPeerReviewForm() + { + return (int) $this->form->getInput("prccc_bool_" . $this->getId()); + } + + public function hasValue($a_value) + { + return (int) $a_value; + } + + public function getHTML($a_value) + { + $lng = $this->lng; + + $caption = null; + if ($this->isRequired() && $a_value < 0) { + $caption = $lng->txt("no"); + } elseif ($a_value == 1) { + $caption = $lng->txt("yes"); + } + return $caption; + } } diff --git a/Modules/Exercise/classes/class.ilExcCriteriaCatalogue.php b/Modules/Exercise/classes/class.ilExcCriteriaCatalogue.php index b6b1bd9f15ca1bdcc9003d70f07319a66a9eb61a..a25c83efc170f0b220ce334ad5d84d1c3d75edb6 100644 --- a/Modules/Exercise/classes/class.ilExcCriteriaCatalogue.php +++ b/Modules/Exercise/classes/class.ilExcCriteriaCatalogue.php @@ -10,226 +10,217 @@ */ class ilExcCriteriaCatalogue { - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; - protected $id; // [int] - protected $parent; // [int] - protected $title; // [string] - protected $pos; // [int] - - public function __construct($a_id = null) - { - global $DIC; + protected $id; // [int] + protected $parent; // [int] + protected $title; // [string] + protected $pos; // [int] + + public function __construct($a_id = null) + { + global $DIC; - $this->db = $DIC->database(); - $this->read($a_id); - } - - public static function getInstancesByParentId($a_parent_id) - { - global $DIC; + $this->db = $DIC->database(); + $this->read($a_id); + } + + public static function getInstancesByParentId($a_parent_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $res = array(); - - $set = $ilDB->query("SELECT *". - " FROM exc_crit_cat". - " WHERE parent = ".$ilDB->quote($a_parent_id, "integer"). - " ORDER BY pos"); - while($row = $ilDB->fetchAssoc($set)) - { - $obj = new self(); - $obj->importFromDB($row); - $res[$obj->getId()] = $obj; - } - - return $res; - } - - - // - // properties - // - - public function getId() - { - return $this->id; - } - - protected function setId($a_id) - { - $this->id = (int)$a_id; - } - - public function setParent($a_value) - { - $this->parent = ($a_value !== null) - ? (int)$a_value - : null; - } - - public function getParent() - { - return $this->parent; - } - - public function setTitle($a_value) - { - $this->title = ($a_value !== null) - ? trim($a_value) - : null; - } - - public function getTitle() - { - return $this->title; - } + $ilDB = $DIC->database(); + + $res = array(); + + $set = $ilDB->query("SELECT *" . + " FROM exc_crit_cat" . + " WHERE parent = " . $ilDB->quote($a_parent_id, "integer") . + " ORDER BY pos"); + while ($row = $ilDB->fetchAssoc($set)) { + $obj = new self(); + $obj->importFromDB($row); + $res[$obj->getId()] = $obj; + } + + return $res; + } + + + // + // properties + // + + public function getId() + { + return $this->id; + } + + protected function setId($a_id) + { + $this->id = (int) $a_id; + } + + public function setParent($a_value) + { + $this->parent = ($a_value !== null) + ? (int) $a_value + : null; + } + + public function getParent() + { + return $this->parent; + } + + public function setTitle($a_value) + { + $this->title = ($a_value !== null) + ? trim($a_value) + : null; + } + + public function getTitle() + { + return $this->title; + } - public function setPosition($a_value) - { - $this->pos = (int)$a_value; - } - - public function getPosition() - { - return $this->pos; - } - - - // - // CRUD - // - - protected function importFromDB(array $a_row) - { - $this->setId($a_row["id"]); - $this->setParent($a_row["parent"]); - $this->setTitle($a_row["title"]); - $this->setPosition($a_row["pos"]); - } - - protected function getDBProperties() - { - return array( - "title" => array("text", $this->getTitle()) - ,"pos" => array("integer", $this->getPosition()) - ); - } - protected function getLastPosition() - { - $ilDB = $this->db; - - if(!$this->getParent()) - { - return; - } - - $set = $ilDB->query("SELECT MAX(pos) pos". - " FROM exc_crit_cat". - " WHERE parent = ".$ilDB->quote($this->getParent(), "integer")); - $row = $ilDB->fetchAssoc($set); - return (int)$row["pos"]; - } - - protected function read($a_id) - { - $ilDB = $this->db; - - $a_id = (int)$a_id; - if($a_id) - { - $set = $ilDB->query("SELECT *". - " FROM exc_crit_cat". - " WHERE id = ".$ilDB->quote($a_id, "integer")); - if($ilDB->numRows($set)) - { - $row = $ilDB->fetchAssoc($set); - $this->importFromDB($row); - } - } - } - - public function save() - { - $ilDB = $this->db; - - if($this->id) - { - return $this->update(); - } - - $this->id = $ilDB->nextId("exc_crit_cat"); - - $fields = $this->getDBProperties(); - $fields["parent"] = array("integer", $this->getParent()); - $fields["pos"] = array("integer", $this->getLastPosition()+10); - $fields["id"] = array("integer", $this->id); - - $ilDB->insert("exc_crit_cat", $fields); - } - - public function update() - { - $ilDB = $this->db; - - if(!$this->id) - { - return $this->save(); - } - - $primary = array("id"=>array("integer", $this->id)); - $ilDB->update("exc_crit_cat", $this->getDBProperties(), $primary); - } - - public function delete() - { - $ilDB = $this->db; - - if(!$this->id) - { - return; - } - - include_once "Modules/Exercise/classes/class.ilExcCriteria.php"; - ilExcCriteria::deleteByParent($this->id); - - $ilDB->manipulate("DELETE FROM exc_crit_cat". - " WHERE id = ".$ilDB->quote($this->id, "integer")); - } - - public static function deleteByParent($a_parent_id) - { - global $DIC; + public function setPosition($a_value) + { + $this->pos = (int) $a_value; + } + + public function getPosition() + { + return $this->pos; + } + + + // + // CRUD + // + + protected function importFromDB(array $a_row) + { + $this->setId($a_row["id"]); + $this->setParent($a_row["parent"]); + $this->setTitle($a_row["title"]); + $this->setPosition($a_row["pos"]); + } + + protected function getDBProperties() + { + return array( + "title" => array("text", $this->getTitle()) + ,"pos" => array("integer", $this->getPosition()) + ); + } + protected function getLastPosition() + { + $ilDB = $this->db; + + if (!$this->getParent()) { + return; + } + + $set = $ilDB->query("SELECT MAX(pos) pos" . + " FROM exc_crit_cat" . + " WHERE parent = " . $ilDB->quote($this->getParent(), "integer")); + $row = $ilDB->fetchAssoc($set); + return (int) $row["pos"]; + } + + protected function read($a_id) + { + $ilDB = $this->db; + + $a_id = (int) $a_id; + if ($a_id) { + $set = $ilDB->query("SELECT *" . + " FROM exc_crit_cat" . + " WHERE id = " . $ilDB->quote($a_id, "integer")); + if ($ilDB->numRows($set)) { + $row = $ilDB->fetchAssoc($set); + $this->importFromDB($row); + } + } + } + + public function save() + { + $ilDB = $this->db; + + if ($this->id) { + return $this->update(); + } + + $this->id = $ilDB->nextId("exc_crit_cat"); + + $fields = $this->getDBProperties(); + $fields["parent"] = array("integer", $this->getParent()); + $fields["pos"] = array("integer", $this->getLastPosition()+10); + $fields["id"] = array("integer", $this->id); + + $ilDB->insert("exc_crit_cat", $fields); + } + + public function update() + { + $ilDB = $this->db; + + if (!$this->id) { + return $this->save(); + } + + $primary = array("id"=>array("integer", $this->id)); + $ilDB->update("exc_crit_cat", $this->getDBProperties(), $primary); + } + + public function delete() + { + $ilDB = $this->db; + + if (!$this->id) { + return; + } + + include_once "Modules/Exercise/classes/class.ilExcCriteria.php"; + ilExcCriteria::deleteByParent($this->id); + + $ilDB->manipulate("DELETE FROM exc_crit_cat" . + " WHERE id = " . $ilDB->quote($this->id, "integer")); + } + + public static function deleteByParent($a_parent_id) + { + global $DIC; - $ilDB = $DIC->database(); - - if(!(int)$a_parent_id) - { - return; - } - - $ilDB->manipulate("DELETE FROM exc_crit". - " WHERE parent = ".$ilDB->quote($a_parent_id, "integer")); - } - - public function cloneObject($a_target_parent_id) - { - $new_obj = new self(); - $new_obj->setParent($a_target_parent_id); - $new_obj->setTitle($this->getTitle()); - $new_obj->setPosition($this->getPosition()); - $new_obj->save(); - - include_once "Modules/Exercise/classes/class.ilExcCriteria.php"; - foreach(ilExcCriteria::getInstancesByParentId($this->getId()) as $crit) - { - $crit->cloneObject($new_obj->getId()); - } - - return $new_obj->getId(); - } + $ilDB = $DIC->database(); + + if (!(int) $a_parent_id) { + return; + } + + $ilDB->manipulate("DELETE FROM exc_crit" . + " WHERE parent = " . $ilDB->quote($a_parent_id, "integer")); + } + + public function cloneObject($a_target_parent_id) + { + $new_obj = new self(); + $new_obj->setParent($a_target_parent_id); + $new_obj->setTitle($this->getTitle()); + $new_obj->setPosition($this->getPosition()); + $new_obj->save(); + + include_once "Modules/Exercise/classes/class.ilExcCriteria.php"; + foreach (ilExcCriteria::getInstancesByParentId($this->getId()) as $crit) { + $crit->cloneObject($new_obj->getId()); + } + + return $new_obj->getId(); + } } diff --git a/Modules/Exercise/classes/class.ilExcCriteriaCatalogueGUI.php b/Modules/Exercise/classes/class.ilExcCriteriaCatalogueGUI.php index 4a36fec70476b40fa23eb99b1a3b636dff279a5e..565cf61b95674e194f46a68df7b47a62b19e24f5 100644 --- a/Modules/Exercise/classes/class.ilExcCriteriaCatalogueGUI.php +++ b/Modules/Exercise/classes/class.ilExcCriteriaCatalogueGUI.php @@ -12,301 +12,279 @@ include_once "Modules/Exercise/classes/class.ilExcCriteriaCatalogue.php"; * @ingroup ModulesExercise */ class ilExcCriteriaCatalogueGUI -{ - /** - * @var ilCtrl - */ - protected $ctrl; +{ + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilTabsGUI - */ - protected $tabs; + /** + * @var ilTabsGUI + */ + protected $tabs; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilToolbarGUI - */ - protected $toolbar; + /** + * @var ilToolbarGUI + */ + protected $toolbar; - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilTemplate + */ + protected $tpl; - protected $exc_obj; // [ilObjExercise] - - public function __construct(ilObjExercise $a_exc_obj) - { - global $DIC; + protected $exc_obj; // [ilObjExercise] + + public function __construct(ilObjExercise $a_exc_obj) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->tabs = $DIC->tabs(); - $this->lng = $DIC->language(); - $this->toolbar = $DIC->toolbar(); - $this->tpl = $DIC["tpl"]; - $this->exc_obj = $a_exc_obj; - } - - public function executeCommand() - { - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - $lng = $this->lng; - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd("view"); - - switch($next_class) - { - case "ilexccriteriagui": - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($lng->txt("back"), $ilCtrl->getLinkTarget($this, "")); - $ilCtrl->saveParameter($this, "cat_id"); - include_once "Modules/Exercise/classes/class.ilExcCriteriaGUI.php"; - $crit_gui = new ilExcCriteriaGUI($_REQUEST["cat_id"]); - $ilCtrl->forwardCommand($crit_gui); - break; - - default: - $this->$cmd(); - break; - } - } - - - // - // LIST/TABLE - // - - protected function view() - { - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - - $ilToolbar->addButton($lng->txt("exc_add_criteria_catalogue"), - $ilCtrl->getLinkTarget($this, "add")); - - include_once "Modules/Exercise/classes/class.ilExcCriteriaCatalogueTableGUI.php"; - $tbl = new ilExcCriteriaCatalogueTableGUI($this, "view", $this->exc_obj->getId()); - $tpl->setContent($tbl->getHTML()); - } - - protected function saveOrder() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $all_cat = ilExcCriteriaCatalogue::getInstancesByParentId($this->exc_obj->getId()); - - $pos = 0; - asort($_POST["pos"]); - foreach(array_keys($_POST["pos"]) as $id) - { - if(array_key_exists($id, $all_cat)) - { - $pos += 10; - $all_cat[$id]->setPosition($pos); - $all_cat[$id]->update(); - } - } - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - $ilCtrl->redirect($this, "view"); - } - - protected function confirmDeletion() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - - $ids = $_POST["id"]; - if(!sizeof($ids)) - { - ilUtil::sendInfo($lng->txt("select_one"), true); - $ilCtrl->redirect($this, "view"); - } - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $confirmation_gui = new ilConfirmationGUI(); - $confirmation_gui->setFormAction($ilCtrl->getFormAction($this, "delete")); - $confirmation_gui->setHeaderText($lng->txt("exc_criteria_catalogue_deletion_confirmation")); - $confirmation_gui->setCancel($lng->txt("cancel"), "view"); - $confirmation_gui->setConfirm($lng->txt("delete"), "delete"); + $this->ctrl = $DIC->ctrl(); + $this->tabs = $DIC->tabs(); + $this->lng = $DIC->language(); + $this->toolbar = $DIC->toolbar(); + $this->tpl = $DIC["tpl"]; + $this->exc_obj = $a_exc_obj; + } + + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + $lng = $this->lng; + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd("view"); + + switch ($next_class) { + case "ilexccriteriagui": + $ilTabs->clearTargets(); + $ilTabs->setBackTarget($lng->txt("back"), $ilCtrl->getLinkTarget($this, "")); + $ilCtrl->saveParameter($this, "cat_id"); + include_once "Modules/Exercise/classes/class.ilExcCriteriaGUI.php"; + $crit_gui = new ilExcCriteriaGUI($_REQUEST["cat_id"]); + $ilCtrl->forwardCommand($crit_gui); + break; + + default: + $this->$cmd(); + break; + } + } + + + // + // LIST/TABLE + // + + protected function view() + { + $ilToolbar = $this->toolbar; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + + $ilToolbar->addButton( + $lng->txt("exc_add_criteria_catalogue"), + $ilCtrl->getLinkTarget($this, "add") + ); + + include_once "Modules/Exercise/classes/class.ilExcCriteriaCatalogueTableGUI.php"; + $tbl = new ilExcCriteriaCatalogueTableGUI($this, "view", $this->exc_obj->getId()); + $tpl->setContent($tbl->getHTML()); + } + + protected function saveOrder() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $all_cat = ilExcCriteriaCatalogue::getInstancesByParentId($this->exc_obj->getId()); + + $pos = 0; + asort($_POST["pos"]); + foreach (array_keys($_POST["pos"]) as $id) { + if (array_key_exists($id, $all_cat)) { + $pos += 10; + $all_cat[$id]->setPosition($pos); + $all_cat[$id]->update(); + } + } + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "view"); + } + + protected function confirmDeletion() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + + $ids = $_POST["id"]; + if (!sizeof($ids)) { + ilUtil::sendInfo($lng->txt("select_one"), true); + $ilCtrl->redirect($this, "view"); + } + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $confirmation_gui = new ilConfirmationGUI(); + $confirmation_gui->setFormAction($ilCtrl->getFormAction($this, "delete")); + $confirmation_gui->setHeaderText($lng->txt("exc_criteria_catalogue_deletion_confirmation")); + $confirmation_gui->setCancel($lng->txt("cancel"), "view"); + $confirmation_gui->setConfirm($lng->txt("delete"), "delete"); - foreach(ilExcCriteriaCatalogue::getInstancesByParentId($this->exc_obj->getId()) as $item) - { - if(in_array($item->getId(), $ids)) - { - $confirmation_gui->addItem("id[]", $item->getId(), $item->getTitle()); - } - } - - $tpl->setContent($confirmation_gui->getHTML()); - } - - protected function delete() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $ids = $_POST["id"]; - if(!sizeof($ids)) - { - $ilCtrl->redirect($this, "view"); - } - - foreach(ilExcCriteriaCatalogue::getInstancesByParentId($this->exc_obj->getId()) as $item) - { - if(in_array($item->getId(), $ids)) - { - $item->delete(); - } - } - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - $ilCtrl->redirect($this, "view"); - } - - - // - // EDIT - // - - protected function initForm(ilExcCriteriaCatalogue $a_cat_obj = null) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $form = new ilPropertyFormGUI(); - - $is_edit = ($a_cat_obj !== null); - if(!$is_edit) - { - $form->setFormAction($ilCtrl->getFormAction($this, "create")); - $form->setTitle($lng->txt("exc_criteria_catalogue_create_form")); - $form->addCommandButton("create", $lng->txt("create")); - } - else - { - $form->setFormAction($ilCtrl->getFormAction($this, "update")); - $form->setTitle($lng->txt("exc_criteria_catalogue_update_form")); - $form->addCommandButton("update", $lng->txt("save")); - } - - $form->addCommandButton("view", $lng->txt("cancel")); - - $title = new ilTextInputGUI($lng->txt("title"), "title"); - $title->setRequired(true); - $form->addItem($title); - - return $form; - } - - protected function add(ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - - if(!$a_form) - { - $a_form = $this->initForm(); - } - - $tpl->setContent($a_form->getHTML()); - } - - protected function exportForm(ilExcCriteriaCatalogue $a_cat_obj, ilPropertyFormGUI $a_form) - { - $a_form->getItemByPostVar("title")->setValue($a_cat_obj->getTitle()); - } - - protected function importForm(ilExcCriteriaCatalogue $a_cat_obj = null) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $is_edit = ($a_cat_obj !== null); - - $form = $this->initForm($a_cat_obj); - if($form->checkInput()) - { - if(!$is_edit) - { - $a_cat_obj = new ilExcCriteriaCatalogue(); - $a_cat_obj->setParent($this->exc_obj->getId()); - } - - $a_cat_obj->setTitle($form->getInput("title")); - - if(!$is_edit) - { - $a_cat_obj->save(); - } - else - { - $a_cat_obj->update(); - } - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - $ilCtrl->redirect($this, "view"); - } - - $form->setValuesByPost(); - $this->{$is_edit ? "edit" : "add"}($form); - } - - protected function create() - { - $this->importForm(); - } - - protected function getCurrentCatalogue() - { - $ilCtrl = $this->ctrl; - - $id = (int)$_REQUEST["cat_id"]; - if($id) - { - $cat_obj = new ilExcCriteriaCatalogue($id); - if($cat_obj->getParent() == $this->exc_obj->getId()) - { - $ilCtrl->setParameter($this, "cat_id", $id); - return $cat_obj; - } - } - - $ilCtrl->redirect($this, "view"); - } - - protected function edit(ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - - $cat_obj = $this->getCurrentCatalogue(); - - if(!$a_form) - { - $a_form = $this->initForm($cat_obj); - $this->exportForm($cat_obj, $a_form); - } - - $tpl->setContent($a_form->getHTML()); - } - - protected function update() - { - $cat_obj = $this->getCurrentCatalogue(); - $this->importForm($cat_obj); - } - - - + foreach (ilExcCriteriaCatalogue::getInstancesByParentId($this->exc_obj->getId()) as $item) { + if (in_array($item->getId(), $ids)) { + $confirmation_gui->addItem("id[]", $item->getId(), $item->getTitle()); + } + } + + $tpl->setContent($confirmation_gui->getHTML()); + } + + protected function delete() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $ids = $_POST["id"]; + if (!sizeof($ids)) { + $ilCtrl->redirect($this, "view"); + } + + foreach (ilExcCriteriaCatalogue::getInstancesByParentId($this->exc_obj->getId()) as $item) { + if (in_array($item->getId(), $ids)) { + $item->delete(); + } + } + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "view"); + } + + + // + // EDIT + // + + protected function initForm(ilExcCriteriaCatalogue $a_cat_obj = null) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $form = new ilPropertyFormGUI(); + + $is_edit = ($a_cat_obj !== null); + if (!$is_edit) { + $form->setFormAction($ilCtrl->getFormAction($this, "create")); + $form->setTitle($lng->txt("exc_criteria_catalogue_create_form")); + $form->addCommandButton("create", $lng->txt("create")); + } else { + $form->setFormAction($ilCtrl->getFormAction($this, "update")); + $form->setTitle($lng->txt("exc_criteria_catalogue_update_form")); + $form->addCommandButton("update", $lng->txt("save")); + } + + $form->addCommandButton("view", $lng->txt("cancel")); + + $title = new ilTextInputGUI($lng->txt("title"), "title"); + $title->setRequired(true); + $form->addItem($title); + + return $form; + } + + protected function add(ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + + if (!$a_form) { + $a_form = $this->initForm(); + } + + $tpl->setContent($a_form->getHTML()); + } + + protected function exportForm(ilExcCriteriaCatalogue $a_cat_obj, ilPropertyFormGUI $a_form) + { + $a_form->getItemByPostVar("title")->setValue($a_cat_obj->getTitle()); + } + + protected function importForm(ilExcCriteriaCatalogue $a_cat_obj = null) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $is_edit = ($a_cat_obj !== null); + + $form = $this->initForm($a_cat_obj); + if ($form->checkInput()) { + if (!$is_edit) { + $a_cat_obj = new ilExcCriteriaCatalogue(); + $a_cat_obj->setParent($this->exc_obj->getId()); + } + + $a_cat_obj->setTitle($form->getInput("title")); + + if (!$is_edit) { + $a_cat_obj->save(); + } else { + $a_cat_obj->update(); + } + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "view"); + } + + $form->setValuesByPost(); + $this->{$is_edit ? "edit" : "add"}($form); + } + + protected function create() + { + $this->importForm(); + } + + protected function getCurrentCatalogue() + { + $ilCtrl = $this->ctrl; + + $id = (int) $_REQUEST["cat_id"]; + if ($id) { + $cat_obj = new ilExcCriteriaCatalogue($id); + if ($cat_obj->getParent() == $this->exc_obj->getId()) { + $ilCtrl->setParameter($this, "cat_id", $id); + return $cat_obj; + } + } + + $ilCtrl->redirect($this, "view"); + } + + protected function edit(ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + + $cat_obj = $this->getCurrentCatalogue(); + + if (!$a_form) { + $a_form = $this->initForm($cat_obj); + $this->exportForm($cat_obj, $a_form); + } + + $tpl->setContent($a_form->getHTML()); + } + + protected function update() + { + $cat_obj = $this->getCurrentCatalogue(); + $this->importForm($cat_obj); + } } diff --git a/Modules/Exercise/classes/class.ilExcCriteriaCatalogueTableGUI.php b/Modules/Exercise/classes/class.ilExcCriteriaCatalogueTableGUI.php index 1e629adc4925e50d12fcdd22bcca6e1ac1289af5..cc2b1c7cf3269176d7d811db5dd03a892b5fbecb 100644 --- a/Modules/Exercise/classes/class.ilExcCriteriaCatalogueTableGUI.php +++ b/Modules/Exercise/classes/class.ilExcCriteriaCatalogueTableGUI.php @@ -12,170 +12,157 @@ include_once "Services/Table/classes/class.ilTable2GUI.php"; */ class ilExcCriteriaCatalogueTableGUI extends ilTable2GUI { - protected $exc_id; // [int] + protected $exc_id; // [int] - public function __construct($a_parent_obj, $a_parent_cmd, $a_exc_id) - { - global $DIC; + public function __construct($a_parent_obj, $a_parent_cmd, $a_exc_id) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->exc_id = $a_exc_id; - $this->setId("exccritcat".$this->exc_id); - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setLimit(9999); // because of manual order - - $this->setTitle($lng->txt("exc_criteria_catalogues")); - - $this->addColumn("", "", "1", true); - $this->addColumn($this->lng->txt("position"), "pos", "10%"); - $this->addColumn($this->lng->txt("title"), "title"); - $this->addColumn($this->lng->txt("exc_criterias")); - $this->addColumn($this->lng->txt("exc_assignments")); - $this->addColumn($this->lng->txt("actions")); - - $this->setDefaultOrderField("pos"); - $this->setDefaultOrderDirection("asc"); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.exc_crit_cat_row.html", "Modules/Exercise"); - $this->setSelectAllCheckbox("id"); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->exc_id = $a_exc_id; + $this->setId("exccritcat" . $this->exc_id); + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setLimit(9999); // because of manual order + + $this->setTitle($lng->txt("exc_criteria_catalogues")); + + $this->addColumn("", "", "1", true); + $this->addColumn($this->lng->txt("position"), "pos", "10%"); + $this->addColumn($this->lng->txt("title"), "title"); + $this->addColumn($this->lng->txt("exc_criterias")); + $this->addColumn($this->lng->txt("exc_assignments")); + $this->addColumn($this->lng->txt("actions")); + + $this->setDefaultOrderField("pos"); + $this->setDefaultOrderDirection("asc"); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.exc_crit_cat_row.html", "Modules/Exercise"); + $this->setSelectAllCheckbox("id"); - $this->addMultiCommand("confirmDeletion", $lng->txt("delete")); - - if($this->getItems()) - { - $this->addCommandButton("saveOrder", $lng->txt("exc_save_order")); - } - } - - protected function getItems() - { - $lng = $this->lng; - - $data = array(); - - include_once "Modules/Exercise/classes/class.ilExAssignment.php"; - include_once "Modules/Exercise/classes/class.ilExcCriteria.php"; - include_once "Modules/Exercise/classes/class.ilExPeerReview.php"; - - $protected = $assigned = array(); - foreach(ilExAssignment::getInstancesByExercise($this->exc_id) as $ass) - { - if($ass->getPeerReviewCriteriaCatalogue()) - { - $assigned[$ass->getPeerReviewCriteriaCatalogue()][$ass->getId()] = $ass->getTitle(); - - $peer_review = new ilExPeerReview($ass); - if($peer_review->hasPeerReviewGroups()) - { - $protected[$ass->getPeerReviewCriteriaCatalogue()][] = $ass->getId(); - } - } - } - - if(sizeof($protected)) - { - ilUtil::sendInfo($lng->txt("exc_crit_cat_protected_assignment_info")); - } - - $pos = 0; - foreach(ilExcCriteriaCatalogue::getInstancesByParentId($this->exc_id) as $item) - { - $pos += 10; - - $crits = array(); - foreach(ilExcCriteria::getInstancesByParentId($item->getId()) as $crit) - { - $crits[] = array($crit->getTranslatedType(), $crit->getTitle()); - } - - $data[] = array( - "id" => $item->getId() - ,"pos" => $pos - ,"title" => $item->getTitle() - ,"criterias" => $crits - ,"protected" => array_key_exists($item->getId(), $protected) - ? $protected[$item->getId()] - : null - ,"assigned" => array_key_exists($item->getId(), $assigned) - ? $assigned[$item->getId()] - : null - ); - } - - $this->setData($data); - - return (bool)sizeof($data); - } - - public function numericOrdering($a_field) - { - return in_array($a_field, array("pos")); - } - - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; + $this->addMultiCommand("confirmDeletion", $lng->txt("delete")); + + if ($this->getItems()) { + $this->addCommandButton("saveOrder", $lng->txt("exc_save_order")); + } + } + + protected function getItems() + { + $lng = $this->lng; + + $data = array(); + + include_once "Modules/Exercise/classes/class.ilExAssignment.php"; + include_once "Modules/Exercise/classes/class.ilExcCriteria.php"; + include_once "Modules/Exercise/classes/class.ilExPeerReview.php"; + + $protected = $assigned = array(); + foreach (ilExAssignment::getInstancesByExercise($this->exc_id) as $ass) { + if ($ass->getPeerReviewCriteriaCatalogue()) { + $assigned[$ass->getPeerReviewCriteriaCatalogue()][$ass->getId()] = $ass->getTitle(); + + $peer_review = new ilExPeerReview($ass); + if ($peer_review->hasPeerReviewGroups()) { + $protected[$ass->getPeerReviewCriteriaCatalogue()][] = $ass->getId(); + } + } + } + + if (sizeof($protected)) { + ilUtil::sendInfo($lng->txt("exc_crit_cat_protected_assignment_info")); + } + + $pos = 0; + foreach (ilExcCriteriaCatalogue::getInstancesByParentId($this->exc_id) as $item) { + $pos += 10; + + $crits = array(); + foreach (ilExcCriteria::getInstancesByParentId($item->getId()) as $crit) { + $crits[] = array($crit->getTranslatedType(), $crit->getTitle()); + } + + $data[] = array( + "id" => $item->getId() + ,"pos" => $pos + ,"title" => $item->getTitle() + ,"criterias" => $crits + ,"protected" => array_key_exists($item->getId(), $protected) + ? $protected[$item->getId()] + : null + ,"assigned" => array_key_exists($item->getId(), $assigned) + ? $assigned[$item->getId()] + : null + ); + } + + $this->setData($data); + + return (bool) sizeof($data); + } + + public function numericOrdering($a_field) + { + return in_array($a_field, array("pos")); + } + + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; - $this->tpl->setVariable("ID", $a_set["id"]); - $this->tpl->setVariable("POS", $a_set["pos"]); - $this->tpl->setVariable("TITLE", $a_set["title"]); - - $ilCtrl->setParameter($this->getParentObject(), "cat_id", $a_set["id"]); - $url = $ilCtrl->getLinkTarget($this->getParentObject(), "edit"); - - if(sizeof($a_set["criterias"])) - { - $this->tpl->setCurrentBlock("crit_bl"); - foreach($a_set["criterias"] as $crit) - { - $this->tpl->setVariable("CRIT_TYPE", $crit[0]); - $this->tpl->setVariable("CRIT_TITLE", $crit[1]); - $this->tpl->parseCurrentBlock(); - } - } - - $this->tpl->setCurrentBlock("action_bl"); - $this->tpl->setVariable("ACTION_URL", $url); - $this->tpl->setVariable("ACTION_TXT", $lng->txt("edit")); - $this->tpl->parseCurrentBlock(); - - if(is_array($a_set["assigned"])) - { - foreach($a_set["assigned"] as $ass_id => $ass_title) - { - if(is_array($a_set["protected"]) && - in_array($ass_id, $a_set["protected"])) - { - $this->tpl->setCurrentBlock("ass_protected_bl"); - $this->tpl->setVariable("ASS_PROTECTED", $lng->txt("exc_crit_cat_protected_assignment")); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setCurrentBlock("ass_bl"); - $this->tpl->setVariable("ASS_TITLE", $ass_title); - $this->tpl->parseCurrentBlock(); - } - } - - - if(!is_array($a_set["protected"])) - { - $url = $ilCtrl->getLinkTargetByClass("ilExcCriteriaGUI", ""); + $this->tpl->setVariable("ID", $a_set["id"]); + $this->tpl->setVariable("POS", $a_set["pos"]); + $this->tpl->setVariable("TITLE", $a_set["title"]); + + $ilCtrl->setParameter($this->getParentObject(), "cat_id", $a_set["id"]); + $url = $ilCtrl->getLinkTarget($this->getParentObject(), "edit"); + + if (sizeof($a_set["criterias"])) { + $this->tpl->setCurrentBlock("crit_bl"); + foreach ($a_set["criterias"] as $crit) { + $this->tpl->setVariable("CRIT_TYPE", $crit[0]); + $this->tpl->setVariable("CRIT_TITLE", $crit[1]); + $this->tpl->parseCurrentBlock(); + } + } + + $this->tpl->setCurrentBlock("action_bl"); + $this->tpl->setVariable("ACTION_URL", $url); + $this->tpl->setVariable("ACTION_TXT", $lng->txt("edit")); + $this->tpl->parseCurrentBlock(); + + if (is_array($a_set["assigned"])) { + foreach ($a_set["assigned"] as $ass_id => $ass_title) { + if (is_array($a_set["protected"]) && + in_array($ass_id, $a_set["protected"])) { + $this->tpl->setCurrentBlock("ass_protected_bl"); + $this->tpl->setVariable("ASS_PROTECTED", $lng->txt("exc_crit_cat_protected_assignment")); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setCurrentBlock("ass_bl"); + $this->tpl->setVariable("ASS_TITLE", $ass_title); + $this->tpl->parseCurrentBlock(); + } + } + + + if (!is_array($a_set["protected"])) { + $url = $ilCtrl->getLinkTargetByClass("ilExcCriteriaGUI", ""); - $this->tpl->setCurrentBlock("action_bl"); - $this->tpl->setVariable("ACTION_URL", $url); - $this->tpl->setVariable("ACTION_TXT", $lng->txt("exc_edit_criterias")); - $this->tpl->parseCurrentBlock(); + $this->tpl->setCurrentBlock("action_bl"); + $this->tpl->setVariable("ACTION_URL", $url); + $this->tpl->setVariable("ACTION_TXT", $lng->txt("exc_edit_criterias")); + $this->tpl->parseCurrentBlock(); - $ilCtrl->setParameter($this->getParentObject(), "cat_id", ""); - } - } -} \ No newline at end of file + $ilCtrl->setParameter($this->getParentObject(), "cat_id", ""); + } + } +} diff --git a/Modules/Exercise/classes/class.ilExcCriteriaFile.php b/Modules/Exercise/classes/class.ilExcCriteriaFile.php index a9e82ca53c205c73423e7861c31bba1f86a2032c..8091e8f24ca00655b5f0268f521b0053aeba41a1 100644 --- a/Modules/Exercise/classes/class.ilExcCriteriaFile.php +++ b/Modules/Exercise/classes/class.ilExcCriteriaFile.php @@ -12,155 +12,147 @@ include_once "Modules/Exercise/classes/class.ilExcCriteria.php"; */ class ilExcCriteriaFile extends ilExcCriteria { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * Constructor - */ - function __construct() - { - global $DIC; - parent::__construct(); + /** + * Constructor + */ + public function __construct() + { + global $DIC; + parent::__construct(); - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - } + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + } - public function getType() - { - return "file"; - } - - protected function initStorage() - { - include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); - $storage = new ilFSStorageExercise($this->ass->getExerciseId(), $this->ass->getId()); - return $storage->getPeerReviewUploadPath($this->peer_id, $this->giver_id, $this->getId()); - } - - public function getFiles() - { - $path = $this->initStorage(); - return (array)glob($path."*.*"); - } - - public function resetReview() - { - include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); - $storage = new ilFSStorageExercise($this->ass->getExerciseId(), $this->ass->getId()); - $storage->deleteDirectory($storage->getPeerReviewUploadPath($this->peer_id, $this->giver_id, $this->getId())); - } - - - // PEER REVIEW - - public function addToPeerReviewForm($a_value = null) - { - $existing = array(); - foreach($this->getFiles() as $file) - { - $existing[] = basename($file); - } - - $files = new ilFileInputGUI($this->getTitle(), "prccc_file_".$this->getId()); - $files->setInfo($this->getDescription()); - $files->setRequired($this->isRequired()); - $files->setValue(implode("
", $existing)); - $files->setALlowDeletion(true); - $this->form->addItem($files); - } - - public function importFromPeerReviewForm() - { - $path = $this->initStorage(); - - if($this->form->getItemByPostVar("prccc_file_".$this->getId())->getDeletionFlag()) - { - ilUtil::delDir($path); - $this->form->getItemByPostVar("prccc_file_".$this->getId())->setValue(null); - } - - $incoming = $_FILES["prccc_file_".$this->getId()]; - if($incoming["tmp_name"]) - { - $org_name = basename($incoming["name"]); - - ilUtil::moveUploadedFile($incoming["tmp_name"], - $org_name, - $path.$org_name, - false); - } - } - - public function hasValue($a_value) - { - return (bool)sizeof($this->getFiles()); - } - - public function validate($a_value) - { - $lng = $this->lng; - - // because of deletion flag we have to also check ourselves - if($this->isRequired()) - { - if(!$this->hasValue($a_value)) - { - if($this->form) - { - $this->form->getItemByPostVar("prccc_file_".$this->getId())->setAlert($lng->txt("msg_input_is_required")); - } - return false; - } - } - return true; - } - - public function getFileByHash() - { - $hash = trim($_GET["fuf"]); - if($hash) - { - foreach($this->getFiles() as $file) - { - if(md5($file) == $hash) - { - return $file; - } - } - } - } - - public function getHTML($a_value) - { - $ilCtrl = $this->ctrl; - - $crit_id = $this->getId() - ? $this->getId() - : "file"; - $ilCtrl->setParameterByClass("ilExPeerReviewGUI", "fu", $this->giver_id."__".$this->peer_id."__".$crit_id); - - $files = array(); - foreach($this->getFiles() as $file) - { - $ilCtrl->setParameterByClass("ilExPeerReviewGUI", "fuf", md5($file)); - $dl = $ilCtrl->getLinkTargetByClass("ilExPeerReviewGUI", "downloadPeerReview"); - $ilCtrl->setParameterByClass("ilExPeerReviewGUI", "fuf", ""); - - $files[] = ''.basename($file).''; - } - - $ilCtrl->setParameterByClass("ilExPeerReviewGUI", "fu", ""); - - return implode("
", $files); - } + public function getType() + { + return "file"; + } + + protected function initStorage() + { + include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); + $storage = new ilFSStorageExercise($this->ass->getExerciseId(), $this->ass->getId()); + return $storage->getPeerReviewUploadPath($this->peer_id, $this->giver_id, $this->getId()); + } + + public function getFiles() + { + $path = $this->initStorage(); + return (array) glob($path . "*.*"); + } + + public function resetReview() + { + include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); + $storage = new ilFSStorageExercise($this->ass->getExerciseId(), $this->ass->getId()); + $storage->deleteDirectory($storage->getPeerReviewUploadPath($this->peer_id, $this->giver_id, $this->getId())); + } + + + // PEER REVIEW + + public function addToPeerReviewForm($a_value = null) + { + $existing = array(); + foreach ($this->getFiles() as $file) { + $existing[] = basename($file); + } + + $files = new ilFileInputGUI($this->getTitle(), "prccc_file_" . $this->getId()); + $files->setInfo($this->getDescription()); + $files->setRequired($this->isRequired()); + $files->setValue(implode("
", $existing)); + $files->setALlowDeletion(true); + $this->form->addItem($files); + } + + public function importFromPeerReviewForm() + { + $path = $this->initStorage(); + + if ($this->form->getItemByPostVar("prccc_file_" . $this->getId())->getDeletionFlag()) { + ilUtil::delDir($path); + $this->form->getItemByPostVar("prccc_file_" . $this->getId())->setValue(null); + } + + $incoming = $_FILES["prccc_file_" . $this->getId()]; + if ($incoming["tmp_name"]) { + $org_name = basename($incoming["name"]); + + ilUtil::moveUploadedFile( + $incoming["tmp_name"], + $org_name, + $path . $org_name, + false + ); + } + } + + public function hasValue($a_value) + { + return (bool) sizeof($this->getFiles()); + } + + public function validate($a_value) + { + $lng = $this->lng; + + // because of deletion flag we have to also check ourselves + if ($this->isRequired()) { + if (!$this->hasValue($a_value)) { + if ($this->form) { + $this->form->getItemByPostVar("prccc_file_" . $this->getId())->setAlert($lng->txt("msg_input_is_required")); + } + return false; + } + } + return true; + } + + public function getFileByHash() + { + $hash = trim($_GET["fuf"]); + if ($hash) { + foreach ($this->getFiles() as $file) { + if (md5($file) == $hash) { + return $file; + } + } + } + } + + public function getHTML($a_value) + { + $ilCtrl = $this->ctrl; + + $crit_id = $this->getId() + ? $this->getId() + : "file"; + $ilCtrl->setParameterByClass("ilExPeerReviewGUI", "fu", $this->giver_id . "__" . $this->peer_id . "__" . $crit_id); + + $files = array(); + foreach ($this->getFiles() as $file) { + $ilCtrl->setParameterByClass("ilExPeerReviewGUI", "fuf", md5($file)); + $dl = $ilCtrl->getLinkTargetByClass("ilExPeerReviewGUI", "downloadPeerReview"); + $ilCtrl->setParameterByClass("ilExPeerReviewGUI", "fuf", ""); + + $files[] = '' . basename($file) . ''; + } + + $ilCtrl->setParameterByClass("ilExPeerReviewGUI", "fu", ""); + + return implode("
", $files); + } } diff --git a/Modules/Exercise/classes/class.ilExcCriteriaGUI.php b/Modules/Exercise/classes/class.ilExcCriteriaGUI.php index 225f5b264365829c06d900f515913a2b223a398f..a81e745b87899aea6732f2b9f14e3320c23ed31e 100644 --- a/Modules/Exercise/classes/class.ilExcCriteriaGUI.php +++ b/Modules/Exercise/classes/class.ilExcCriteriaGUI.php @@ -8,330 +8,307 @@ include_once "Modules/Exercise/classes/class.ilExcCriteria.php"; * Class ilExcCriteriaGUI * * @author Jörg Lützenkirchen - * @ilCtrl_Calls ilExcCriteriaGUI: + * @ilCtrl_Calls ilExcCriteriaGUI: * @ingroup ModulesExercise */ class ilExcCriteriaGUI -{ - /** - * @var ilCtrl - */ - protected $ctrl; +{ + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilToolbarGUI - */ - protected $toolbar; + /** + * @var ilToolbarGUI + */ + protected $toolbar; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilTemplate + */ + protected $tpl; - protected $cat_id; // [int] - - public function __construct($a_cat_id) - { - global $DIC; + protected $cat_id; // [int] + + public function __construct($a_cat_id) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->toolbar = $DIC->toolbar(); - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - $this->cat_id = $a_cat_id; - } - - public function executeCommand() - { - $ilCtrl = $this->ctrl; - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd("view"); - - switch($next_class) - { - default: - $this->$cmd(); - break; - } - } - - - // - // LIST/TABLE - // - - protected function view() - { - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - - $ilToolbar->setFormAction($ilCtrl->getFormAction($this, "add")); - - include_once "Services/Form/classes/class.ilSelectInputGUI.php"; - $types = new ilSelectInputGUI($lng->txt("type"), "type"); - $types->setOptions(ilExcCriteria::getTypesMap()); - $ilToolbar->addStickyItem($types); - - include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; - $button = ilSubmitButton::getInstance(); - $button->setCaption("exc_add_criteria"); - $button->setCommand("add"); - $ilToolbar->addStickyItem($button); - - include_once "Modules/Exercise/classes/class.ilExcCriteriaTableGUI.php"; - $tbl = new ilExcCriteriaTableGUI($this, "view", $this->cat_id); - $tpl->setContent($tbl->getHTML()); - } - - protected function saveOrder() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $all_cat = ilExcCriteria::getInstancesByParentId($this->cat_id); - - $pos = 0; - asort($_POST["pos"]); - foreach(array_keys($_POST["pos"]) as $id) - { - if(array_key_exists($id, $all_cat)) - { - $pos += 10; - $all_cat[$id]->setPosition($pos); - $all_cat[$id]->update(); - } - } - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - $ilCtrl->redirect($this, "view"); - } - - protected function confirmDeletion() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - - $ids = $_POST["id"]; - if(!sizeof($ids)) - { - ilUtil::sendInfo($lng->txt("select_one"), true); - $ilCtrl->redirect($this, "view"); - } - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $confirmation_gui = new ilConfirmationGUI(); - $confirmation_gui->setFormAction($ilCtrl->getFormAction($this, "delete")); - $confirmation_gui->setHeaderText($lng->txt("exc_criteria_deletion_confirmation")); - $confirmation_gui->setCancel($lng->txt("cancel"), "view"); - $confirmation_gui->setConfirm($lng->txt("delete"), "delete"); + $this->ctrl = $DIC->ctrl(); + $this->toolbar = $DIC->toolbar(); + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + $this->cat_id = $a_cat_id; + } + + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd("view"); + + switch ($next_class) { + default: + $this->$cmd(); + break; + } + } + + + // + // LIST/TABLE + // + + protected function view() + { + $ilToolbar = $this->toolbar; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + + $ilToolbar->setFormAction($ilCtrl->getFormAction($this, "add")); + + include_once "Services/Form/classes/class.ilSelectInputGUI.php"; + $types = new ilSelectInputGUI($lng->txt("type"), "type"); + $types->setOptions(ilExcCriteria::getTypesMap()); + $ilToolbar->addStickyItem($types); + + include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; + $button = ilSubmitButton::getInstance(); + $button->setCaption("exc_add_criteria"); + $button->setCommand("add"); + $ilToolbar->addStickyItem($button); + + include_once "Modules/Exercise/classes/class.ilExcCriteriaTableGUI.php"; + $tbl = new ilExcCriteriaTableGUI($this, "view", $this->cat_id); + $tpl->setContent($tbl->getHTML()); + } + + protected function saveOrder() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $all_cat = ilExcCriteria::getInstancesByParentId($this->cat_id); + + $pos = 0; + asort($_POST["pos"]); + foreach (array_keys($_POST["pos"]) as $id) { + if (array_key_exists($id, $all_cat)) { + $pos += 10; + $all_cat[$id]->setPosition($pos); + $all_cat[$id]->update(); + } + } + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "view"); + } + + protected function confirmDeletion() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + + $ids = $_POST["id"]; + if (!sizeof($ids)) { + ilUtil::sendInfo($lng->txt("select_one"), true); + $ilCtrl->redirect($this, "view"); + } + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $confirmation_gui = new ilConfirmationGUI(); + $confirmation_gui->setFormAction($ilCtrl->getFormAction($this, "delete")); + $confirmation_gui->setHeaderText($lng->txt("exc_criteria_deletion_confirmation")); + $confirmation_gui->setCancel($lng->txt("cancel"), "view"); + $confirmation_gui->setConfirm($lng->txt("delete"), "delete"); - foreach(ilExcCriteria::getInstancesByParentId($this->cat_id) as $item) - { - if(in_array($item->getId(), $ids)) - { - $confirmation_gui->addItem("id[]", $item->getId(), $item->getTitle()); - } - } - - $tpl->setContent($confirmation_gui->getHTML()); - } - - protected function delete() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $ids = $_POST["id"]; - if(!sizeof($ids)) - { - $ilCtrl->redirect($this, "view"); - } - - foreach(ilExcCriteria::getInstancesByParentId($this->cat_id) as $item) - { - if(in_array($item->getId(), $ids)) - { - $item->delete(); - } - } - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - $ilCtrl->redirect($this, "view"); - } - - - // - // EDIT - // - - protected function initForm(ilExcCriteria $a_crit_obj) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $form = new ilPropertyFormGUI(); - - $is_edit = (bool)$a_crit_obj->getId(); - if(!$is_edit) - { - $form->setFormAction($ilCtrl->getFormAction($this, "create")); - $form->setTitle($lng->txt("exc_criteria_create_form")); - $form->addCommandButton("create", $lng->txt("create")); - } - else - { - $form->setFormAction($ilCtrl->getFormAction($this, "update")); - $form->setTitle($lng->txt("exc_criteria_update_form")); - $form->addCommandButton("update", $lng->txt("save")); - } - - $form->addCommandButton("view", $lng->txt("cancel")); - - $type = new ilNonEditableValueGUI($lng->txt("type")); - $type->setValue($a_crit_obj->getTranslatedType()); - $form->addItem($type); - - $title = new ilTextInputGUI($lng->txt("title"), "title"); - $title->setRequired(true); - $form->addItem($title); - - $desc = new ilTextAreaInputGUI($lng->txt("description"), "desc"); - $form->addItem($desc); - - $req = new ilCheckboxInputGUI($lng->txt("required_field"), "req"); - $form->addItem($req); - - $a_crit_obj->initCustomForm($form); - - return $form; - } - - protected function add(ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - - $new_type = trim($_REQUEST["type"]); - if(!$new_type) - { - $ilCtrl->redirect($this, "view"); - } - - $ilCtrl->setParameter($this, "type", $new_type); - - if(!$a_form) - { - $crit_obj = ilExcCriteria::getInstanceByType($new_type); - $a_form = $this->initForm($crit_obj); - } - - $tpl->setContent($a_form->getHTML()); - } - - protected function exportForm(ilExcCriteria $a_crit_obj, ilPropertyFormGUI $a_form) - { - $a_form->getItemByPostVar("title")->setValue($a_crit_obj->getTitle()); - $a_form->getItemByPostVar("desc")->setValue($a_crit_obj->getDescription()); - $a_form->getItemByPostVar("req")->setChecked($a_crit_obj->isRequired()); - - $a_crit_obj->exportCustomForm($a_form); - } - - protected function importForm(ilExcCriteria $a_crit_obj) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $is_edit = (bool)$a_crit_obj->getId(); - - $form = $this->initForm($a_crit_obj); - if($form->checkInput()) - { - $a_crit_obj->setTitle($form->getInput("title")); - $a_crit_obj->setDescription($form->getInput("desc")); - $a_crit_obj->setRequired($form->getInput("req")); - - $a_crit_obj->importCustomForm($form); - - if(!$is_edit) - { - $a_crit_obj->setParent($this->cat_id); - $a_crit_obj->save(); - } - else - { - $a_crit_obj->update(); - } - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - $ilCtrl->redirect($this, "view"); - } - - $form->setValuesByPost(); - $this->{$is_edit ? "edit" : "add"}($form); - } - - protected function create() - { - $ilCtrl = $this->ctrl; - - $new_type = trim($_REQUEST["type"]); - if(!$new_type) - { - $ilCtrl->redirect($this, "view"); - } - - $crit_obj = ilExcCriteria::getInstanceByType($new_type); - $this->importForm($crit_obj); - } - - protected function getCurrentCritera() - { - $ilCtrl = $this->ctrl; - - $id = (int)$_REQUEST["crit_id"]; - if($id) - { - $crit_obj = ilExcCriteria::getInstanceById($id); - if($crit_obj->getParent() == $this->cat_id) - { - $ilCtrl->setParameter($this, "crit_id", $id); - return $crit_obj; - } - } - - $ilCtrl->redirect($this, "view"); - } - - protected function edit(ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - - $crit_obj = $this->getCurrentCritera(); - - if(!$a_form) - { - $a_form = $this->initForm($crit_obj); - $this->exportForm($crit_obj, $a_form); - } - - $tpl->setContent($a_form->getHTML()); - } - - protected function update() - { - $crit_obj = $this->getCurrentCritera(); - $this->importForm($crit_obj); - } - + foreach (ilExcCriteria::getInstancesByParentId($this->cat_id) as $item) { + if (in_array($item->getId(), $ids)) { + $confirmation_gui->addItem("id[]", $item->getId(), $item->getTitle()); + } + } + + $tpl->setContent($confirmation_gui->getHTML()); + } + + protected function delete() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $ids = $_POST["id"]; + if (!sizeof($ids)) { + $ilCtrl->redirect($this, "view"); + } + + foreach (ilExcCriteria::getInstancesByParentId($this->cat_id) as $item) { + if (in_array($item->getId(), $ids)) { + $item->delete(); + } + } + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "view"); + } + + + // + // EDIT + // + + protected function initForm(ilExcCriteria $a_crit_obj) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $form = new ilPropertyFormGUI(); + + $is_edit = (bool) $a_crit_obj->getId(); + if (!$is_edit) { + $form->setFormAction($ilCtrl->getFormAction($this, "create")); + $form->setTitle($lng->txt("exc_criteria_create_form")); + $form->addCommandButton("create", $lng->txt("create")); + } else { + $form->setFormAction($ilCtrl->getFormAction($this, "update")); + $form->setTitle($lng->txt("exc_criteria_update_form")); + $form->addCommandButton("update", $lng->txt("save")); + } + + $form->addCommandButton("view", $lng->txt("cancel")); + + $type = new ilNonEditableValueGUI($lng->txt("type")); + $type->setValue($a_crit_obj->getTranslatedType()); + $form->addItem($type); + + $title = new ilTextInputGUI($lng->txt("title"), "title"); + $title->setRequired(true); + $form->addItem($title); + + $desc = new ilTextAreaInputGUI($lng->txt("description"), "desc"); + $form->addItem($desc); + + $req = new ilCheckboxInputGUI($lng->txt("required_field"), "req"); + $form->addItem($req); + + $a_crit_obj->initCustomForm($form); + + return $form; + } + + protected function add(ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + + $new_type = trim($_REQUEST["type"]); + if (!$new_type) { + $ilCtrl->redirect($this, "view"); + } + + $ilCtrl->setParameter($this, "type", $new_type); + + if (!$a_form) { + $crit_obj = ilExcCriteria::getInstanceByType($new_type); + $a_form = $this->initForm($crit_obj); + } + + $tpl->setContent($a_form->getHTML()); + } + + protected function exportForm(ilExcCriteria $a_crit_obj, ilPropertyFormGUI $a_form) + { + $a_form->getItemByPostVar("title")->setValue($a_crit_obj->getTitle()); + $a_form->getItemByPostVar("desc")->setValue($a_crit_obj->getDescription()); + $a_form->getItemByPostVar("req")->setChecked($a_crit_obj->isRequired()); + + $a_crit_obj->exportCustomForm($a_form); + } + + protected function importForm(ilExcCriteria $a_crit_obj) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $is_edit = (bool) $a_crit_obj->getId(); + + $form = $this->initForm($a_crit_obj); + if ($form->checkInput()) { + $a_crit_obj->setTitle($form->getInput("title")); + $a_crit_obj->setDescription($form->getInput("desc")); + $a_crit_obj->setRequired($form->getInput("req")); + + $a_crit_obj->importCustomForm($form); + + if (!$is_edit) { + $a_crit_obj->setParent($this->cat_id); + $a_crit_obj->save(); + } else { + $a_crit_obj->update(); + } + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "view"); + } + + $form->setValuesByPost(); + $this->{$is_edit ? "edit" : "add"}($form); + } + + protected function create() + { + $ilCtrl = $this->ctrl; + + $new_type = trim($_REQUEST["type"]); + if (!$new_type) { + $ilCtrl->redirect($this, "view"); + } + + $crit_obj = ilExcCriteria::getInstanceByType($new_type); + $this->importForm($crit_obj); + } + + protected function getCurrentCritera() + { + $ilCtrl = $this->ctrl; + + $id = (int) $_REQUEST["crit_id"]; + if ($id) { + $crit_obj = ilExcCriteria::getInstanceById($id); + if ($crit_obj->getParent() == $this->cat_id) { + $ilCtrl->setParameter($this, "crit_id", $id); + return $crit_obj; + } + } + + $ilCtrl->redirect($this, "view"); + } + + protected function edit(ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + + $crit_obj = $this->getCurrentCritera(); + + if (!$a_form) { + $a_form = $this->initForm($crit_obj); + $this->exportForm($crit_obj, $a_form); + } + + $tpl->setContent($a_form->getHTML()); + } + + protected function update() + { + $crit_obj = $this->getCurrentCritera(); + $this->importForm($crit_obj); + } } diff --git a/Modules/Exercise/classes/class.ilExcCriteriaRating.php b/Modules/Exercise/classes/class.ilExcCriteriaRating.php index 4f620f7365b2b5a505f3e1542ed1f0c53f420744..71aa65b7142394fb6f9e24a2000ad1962b78729a 100644 --- a/Modules/Exercise/classes/class.ilExcCriteriaRating.php +++ b/Modules/Exercise/classes/class.ilExcCriteriaRating.php @@ -12,176 +12,168 @@ include_once "Modules/Exercise/classes/class.ilExcCriteria.php"; */ class ilExcCriteriaRating extends ilExcCriteria { - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilTemplate + */ + protected $tpl; - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * Constructor - */ - function __construct() - { - global $DIC; + /** + * Constructor + */ + public function __construct() + { + global $DIC; - parent::__construct(); - $this->tpl = $DIC["tpl"]; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - } + parent::__construct(); + $this->tpl = $DIC["tpl"]; + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + } - public function getType() - { - return "rating"; - } - - - // PEER REVIEW - - public function addToPeerReviewForm($a_value = null) - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - - $tpl->addJavaScript("Modules/Exercise/js/ilExcPeerReview.js"); - $tpl->addOnLoadCode("il.ExcPeerReview.setAjax('". - $ilCtrl->getLinkTargetByClass("ilExPeerReviewGUI", "updateCritAjax", "", true, false). - "')"); - - $field_id = "prccc_rating_".$this->getId(); - - $input = new ilCustomInputGUI($this->getTitle(), $field_id); - $input->setInfo($this->getDescription()); - $input->setRequired($this->isRequired()); - $input->setHtml($this->renderWidget()); - $this->form->addItem($input); - - // #16993 - making form checkInput() work - if(is_array($_POST) && - array_key_exists("cmd", $_POST)) - { - $_POST[$field_id] = $this->hasValue($a_value); - } - - $this->form_item = $input; - } - - protected function getRatingSubType() - { - return $this->getId() - ? "peer_".(int)$this->getId() - : "peer"; // no catalogue / v1 - } - - protected function renderWidget($a_read_only = false) - { - include_once './Services/Rating/classes/class.ilRatingGUI.php'; - $rating = new ilRatingGUI(); - $rating->setObject( - $this->ass->getId(), - "ass", - $this->peer_id, - $this->getRatingSubType() - ); - $rating->setUserId($this->giver_id); - - $ajax_id = $this->getId() - ? (int)$this->getId() - : "'rating'"; - - if(!(bool)$a_read_only) - { - $html = '
'. - $rating->getHTML(false, true, "il.ExcPeerReview.saveCrit(this, ".$this->peer_id.", ".$ajax_id.", %rating%)"). - '
'; - } - else - { - $html = $rating->getHTML(false, false); - } - - return $html; - } - - public function importFromPeerReviewForm() - { - // see updateFromAjax() - } - - public function updateFromAjax() - { - // save rating - include_once './Services/Rating/classes/class.ilRating.php'; - ilRating::writeRatingForUserAndObject( - $this->ass->getId(), - "ass", - $this->peer_id, - $this->getRatingSubType(), - $this->giver_id, - $_POST["value"] - ); - - // render current rating - // $ilCtrl->setParameter($this->parent_obj, "peer_id", $peer_id); - return $this->renderWidget($a_ass, $a_giver_id, $a_peer_id); - } - - public function validate($a_value) - { - $lng = $this->lng; - - if($this->isRequired()) - { - if(!$this->hasValue($a_value)) - { - if($this->form) - { - $this->form->getItemByPostVar("prccc_rating_".$this->getId())->setAlert($lng->txt("msg_input_is_required")); - } - return false; - } - } - return true; - } - - public function hasValue($a_value) - { - include_once './Services/Rating/classes/class.ilRating.php'; - return (bool)ilRating::getRatingForUserAndObject( - $this->ass->getId(), - "ass", - $this->peer_id, - $this->getRatingSubType(), - $this->giver_id - ); - } - - public function getHTML($a_value) - { - return $this->renderWidget($this->ass, $this->giver_id, $this->peer_id, true); - } - - public function resetReview() - { - include_once './Services/Rating/classes/class.ilRating.php'; - ilRating::resetRatingForUserAndObject( - $this->ass->getId(), - "ass", - $this->peer_id, - $this->getRatingSubType(), - $this->giver_id - ); - } - + public function getType() + { + return "rating"; + } + + + // PEER REVIEW + + public function addToPeerReviewForm($a_value = null) + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + + $tpl->addJavaScript("Modules/Exercise/js/ilExcPeerReview.js"); + $tpl->addOnLoadCode("il.ExcPeerReview.setAjax('" . + $ilCtrl->getLinkTargetByClass("ilExPeerReviewGUI", "updateCritAjax", "", true, false) . + "')"); + + $field_id = "prccc_rating_" . $this->getId(); + + $input = new ilCustomInputGUI($this->getTitle(), $field_id); + $input->setInfo($this->getDescription()); + $input->setRequired($this->isRequired()); + $input->setHtml($this->renderWidget()); + $this->form->addItem($input); + + // #16993 - making form checkInput() work + if (is_array($_POST) && + array_key_exists("cmd", $_POST)) { + $_POST[$field_id] = $this->hasValue($a_value); + } + + $this->form_item = $input; + } + + protected function getRatingSubType() + { + return $this->getId() + ? "peer_" . (int) $this->getId() + : "peer"; // no catalogue / v1 + } + + protected function renderWidget($a_read_only = false) + { + include_once './Services/Rating/classes/class.ilRatingGUI.php'; + $rating = new ilRatingGUI(); + $rating->setObject( + $this->ass->getId(), + "ass", + $this->peer_id, + $this->getRatingSubType() + ); + $rating->setUserId($this->giver_id); + + $ajax_id = $this->getId() + ? (int) $this->getId() + : "'rating'"; + + if (!(bool) $a_read_only) { + $html = '
' . + $rating->getHTML(false, true, "il.ExcPeerReview.saveCrit(this, " . $this->peer_id . ", " . $ajax_id . ", %rating%)") . + '
'; + } else { + $html = $rating->getHTML(false, false); + } + + return $html; + } + + public function importFromPeerReviewForm() + { + // see updateFromAjax() + } + + public function updateFromAjax() + { + // save rating + include_once './Services/Rating/classes/class.ilRating.php'; + ilRating::writeRatingForUserAndObject( + $this->ass->getId(), + "ass", + $this->peer_id, + $this->getRatingSubType(), + $this->giver_id, + $_POST["value"] + ); + + // render current rating + // $ilCtrl->setParameter($this->parent_obj, "peer_id", $peer_id); + return $this->renderWidget($a_ass, $a_giver_id, $a_peer_id); + } + + public function validate($a_value) + { + $lng = $this->lng; + + if ($this->isRequired()) { + if (!$this->hasValue($a_value)) { + if ($this->form) { + $this->form->getItemByPostVar("prccc_rating_" . $this->getId())->setAlert($lng->txt("msg_input_is_required")); + } + return false; + } + } + return true; + } + + public function hasValue($a_value) + { + include_once './Services/Rating/classes/class.ilRating.php'; + return (bool) ilRating::getRatingForUserAndObject( + $this->ass->getId(), + "ass", + $this->peer_id, + $this->getRatingSubType(), + $this->giver_id + ); + } + + public function getHTML($a_value) + { + return $this->renderWidget($this->ass, $this->giver_id, $this->peer_id, true); + } + + public function resetReview() + { + include_once './Services/Rating/classes/class.ilRating.php'; + ilRating::resetRatingForUserAndObject( + $this->ass->getId(), + "ass", + $this->peer_id, + $this->getRatingSubType(), + $this->giver_id + ); + } } diff --git a/Modules/Exercise/classes/class.ilExcCriteriaTableGUI.php b/Modules/Exercise/classes/class.ilExcCriteriaTableGUI.php index acc424ec7d7addb896037eaf7a54f662703aa3e9..54bd3c9d592d608bb321b01058983ab303fe2b38 100644 --- a/Modules/Exercise/classes/class.ilExcCriteriaTableGUI.php +++ b/Modules/Exercise/classes/class.ilExcCriteriaTableGUI.php @@ -12,91 +12,89 @@ include_once "Services/Table/classes/class.ilTable2GUI.php"; */ class ilExcCriteriaTableGUI extends ilTable2GUI { - protected $cat_id; // [int] + protected $cat_id; // [int] - public function __construct($a_parent_obj, $a_parent_cmd, $a_cat_id) - { - global $DIC; + public function __construct($a_parent_obj, $a_parent_cmd, $a_cat_id) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->cat_id = $a_cat_id; - $this->setId("exccrit".$this->cat_id); - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setLimit(9999); // because of manual order - - $this->setTitle($lng->txt("exc_criterias")); - - $this->addColumn("", "", "1", true); - $this->addColumn($this->lng->txt("position"), "pos", "10%"); - $this->addColumn($this->lng->txt("title"), "title"); - $this->addColumn($this->lng->txt("type"), "type"); - $this->addColumn($this->lng->txt("actions")); - - $this->setDefaultOrderField("pos"); - $this->setDefaultOrderDirection("asc"); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.exc_crit_row.html", "Modules/Exercise"); - $this->setSelectAllCheckbox("id"); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->cat_id = $a_cat_id; + $this->setId("exccrit" . $this->cat_id); + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setLimit(9999); // because of manual order + + $this->setTitle($lng->txt("exc_criterias")); + + $this->addColumn("", "", "1", true); + $this->addColumn($this->lng->txt("position"), "pos", "10%"); + $this->addColumn($this->lng->txt("title"), "title"); + $this->addColumn($this->lng->txt("type"), "type"); + $this->addColumn($this->lng->txt("actions")); + + $this->setDefaultOrderField("pos"); + $this->setDefaultOrderDirection("asc"); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.exc_crit_row.html", "Modules/Exercise"); + $this->setSelectAllCheckbox("id"); - $this->addMultiCommand("confirmDeletion", $lng->txt("delete")); - - if($this->getItems()) - { - $this->addCommandButton("saveOrder", $lng->txt("exc_save_order")); - } - } - - protected function getItems() - { - $data = array(); - - $pos = 0; - foreach(ilExcCriteria::getInstancesByParentId($this->cat_id) as $item) - { - $pos += 10; - - $data[] = array( - "id" => $item->getId() - ,"type" => $item->getTranslatedType() - ,"pos" => $pos - ,"title" => $item->getTitle() - ); - } - - $this->setData($data); - - return (bool)sizeof($data); - } - - public function numericOrdering($a_field) - { - return in_array($a_field, array("pos")); - } - - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; + $this->addMultiCommand("confirmDeletion", $lng->txt("delete")); + + if ($this->getItems()) { + $this->addCommandButton("saveOrder", $lng->txt("exc_save_order")); + } + } + + protected function getItems() + { + $data = array(); + + $pos = 0; + foreach (ilExcCriteria::getInstancesByParentId($this->cat_id) as $item) { + $pos += 10; + + $data[] = array( + "id" => $item->getId() + ,"type" => $item->getTranslatedType() + ,"pos" => $pos + ,"title" => $item->getTitle() + ); + } + + $this->setData($data); + + return (bool) sizeof($data); + } + + public function numericOrdering($a_field) + { + return in_array($a_field, array("pos")); + } + + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; - $this->tpl->setVariable("ID", $a_set["id"]); - $this->tpl->setVariable("POS", $a_set["pos"]); - $this->tpl->setVariable("TYPE", $a_set["type"]); - $this->tpl->setVariable("TITLE", $a_set["title"]); - - $ilCtrl->setParameter($this->getParentObject(), "crit_id", $a_set["id"]); - $url = $ilCtrl->getLinkTarget($this->getParentObject(), "edit"); - $ilCtrl->setParameter($this->getParentObject(), "crit_id", ""); - - $this->tpl->setCurrentBlock("action_bl"); - $this->tpl->setVariable("ACTION_URL", $url); - $this->tpl->setVariable("ACTION_TXT", $lng->txt("edit")); - $this->tpl->parseCurrentBlock(); - } -} \ No newline at end of file + $this->tpl->setVariable("ID", $a_set["id"]); + $this->tpl->setVariable("POS", $a_set["pos"]); + $this->tpl->setVariable("TYPE", $a_set["type"]); + $this->tpl->setVariable("TITLE", $a_set["title"]); + + $ilCtrl->setParameter($this->getParentObject(), "crit_id", $a_set["id"]); + $url = $ilCtrl->getLinkTarget($this->getParentObject(), "edit"); + $ilCtrl->setParameter($this->getParentObject(), "crit_id", ""); + + $this->tpl->setCurrentBlock("action_bl"); + $this->tpl->setVariable("ACTION_URL", $url); + $this->tpl->setVariable("ACTION_TXT", $lng->txt("edit")); + $this->tpl->parseCurrentBlock(); + } +} diff --git a/Modules/Exercise/classes/class.ilExcCriteriaText.php b/Modules/Exercise/classes/class.ilExcCriteriaText.php index 7a50b6c865f77020cca94e8594876370e498c057..141fc8a832a79c6abdc8b5bb52151f3e42e1de5e 100644 --- a/Modules/Exercise/classes/class.ilExcCriteriaText.php +++ b/Modules/Exercise/classes/class.ilExcCriteriaText.php @@ -12,146 +12,137 @@ include_once "Modules/Exercise/classes/class.ilExcCriteria.php"; */ class ilExcCriteriaText extends ilExcCriteria { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * Constructor - */ - function __construct() - { - global $DIC; - parent::__construct(); + /** + * Constructor + */ + public function __construct() + { + global $DIC; + parent::__construct(); - $this->lng = $DIC->language(); - } + $this->lng = $DIC->language(); + } - public function getType() - { - return "text"; - } - - public function setMinChars($a_value) - { - $this->setDefinition(array("chars" => (int)$a_value)); - } - - public function getMinChars() - { - $def = $this->getDefinition(); - if(is_array($def)) - { - return $def["chars"]; - } - } - - // - // ASSIGNMENT EDITOR - // - - public function initCustomForm(ilPropertyFormGUI $a_form) - { - $lng = $this->lng; - - $peer_char_tgl = new ilCheckboxInputGUI($lng->txt("exc_peer_review_min_chars_tgl"), "peer_char_tgl"); - $a_form->addItem($peer_char_tgl); - - $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->setRequired(true); - $peer_char->setSize(3); - $peer_char_tgl->addSubItem($peer_char); - } - - public function exportCustomForm(ilPropertyFormGUI $a_form) - { - $min = $this->getMinChars(); - if($min) - { - $a_form->getItemByPostVar("peer_char_tgl")->setChecked(true); - $a_form->getItemByPostVar("peer_char")->setValue($min); - } - } - - public function importCustomForm(ilPropertyFormGUI $a_form) - { - $this->setDefinition(null); - - if($a_form->getInput("peer_char_tgl")) - { - $this->setMinChars($a_form->getInput("peer_char")); - } - } - - - // PEER REVIEW - - public function addToPeerReviewForm($a_value = null) - { - $lng = $this->lng; - - $info = array(); - if($this->getDescription()) - { - $info[] = $this->getDescription(); - } - if($this->getMinChars()) - { - $info[] = $lng->txt("exc_peer_review_min_chars").": ".$this->getMinChars(); - } - $info = implode("
", $info); - - $input = new ilTextAreaInputGUI($this->getTitle(), "prccc_text_".$this->getId()); - $input->setRows(10); - $input->setInfo($info); - $input->setRequired($this->isRequired()); - $input->setValue($a_value); - - $this->form->addItem($input); - } - - public function importFromPeerReviewForm() - { - return trim($this->form->getInput("prccc_text_".$this->getId())); - } - - public function validate($a_value) - { - $lng = $this->lng; - - if(!$this->hasValue($a_value) && - !$this->isRequired()) - { - return true; - } - - $min = $this->getMinChars(); - if($min) - { - include_once "Services/Utilities/classes/class.ilStr.php"; - if(ilStr::strLen($a_value) < $min) - { - if($this->form) - { - $mess = sprintf($lng->txt("exc_peer_review_chars_invalid"), $min); - $this->form->getItemByPostVar("prccc_text_".$this->getId())->setAlert($mess); - } - return false; - } - } - return true; - } - - public function hasValue($a_value) - { - return (bool)strlen($a_value); - } - - public function getHTML($a_value) - { - return nl2br($a_value); - } + public function getType() + { + return "text"; + } + + public function setMinChars($a_value) + { + $this->setDefinition(array("chars" => (int) $a_value)); + } + + public function getMinChars() + { + $def = $this->getDefinition(); + if (is_array($def)) { + return $def["chars"]; + } + } + + // + // ASSIGNMENT EDITOR + // + + public function initCustomForm(ilPropertyFormGUI $a_form) + { + $lng = $this->lng; + + $peer_char_tgl = new ilCheckboxInputGUI($lng->txt("exc_peer_review_min_chars_tgl"), "peer_char_tgl"); + $a_form->addItem($peer_char_tgl); + + $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->setRequired(true); + $peer_char->setSize(3); + $peer_char_tgl->addSubItem($peer_char); + } + + public function exportCustomForm(ilPropertyFormGUI $a_form) + { + $min = $this->getMinChars(); + if ($min) { + $a_form->getItemByPostVar("peer_char_tgl")->setChecked(true); + $a_form->getItemByPostVar("peer_char")->setValue($min); + } + } + + public function importCustomForm(ilPropertyFormGUI $a_form) + { + $this->setDefinition(null); + + if ($a_form->getInput("peer_char_tgl")) { + $this->setMinChars($a_form->getInput("peer_char")); + } + } + + + // PEER REVIEW + + public function addToPeerReviewForm($a_value = null) + { + $lng = $this->lng; + + $info = array(); + if ($this->getDescription()) { + $info[] = $this->getDescription(); + } + if ($this->getMinChars()) { + $info[] = $lng->txt("exc_peer_review_min_chars") . ": " . $this->getMinChars(); + } + $info = implode("
", $info); + + $input = new ilTextAreaInputGUI($this->getTitle(), "prccc_text_" . $this->getId()); + $input->setRows(10); + $input->setInfo($info); + $input->setRequired($this->isRequired()); + $input->setValue($a_value); + + $this->form->addItem($input); + } + + public function importFromPeerReviewForm() + { + return trim($this->form->getInput("prccc_text_" . $this->getId())); + } + + public function validate($a_value) + { + $lng = $this->lng; + + if (!$this->hasValue($a_value) && + !$this->isRequired()) { + return true; + } + + $min = $this->getMinChars(); + if ($min) { + include_once "Services/Utilities/classes/class.ilStr.php"; + if (ilStr::strLen($a_value) < $min) { + if ($this->form) { + $mess = sprintf($lng->txt("exc_peer_review_chars_invalid"), $min); + $this->form->getItemByPostVar("prccc_text_" . $this->getId())->setAlert($mess); + } + return false; + } + } + return true; + } + + public function hasValue($a_value) + { + return (bool) strlen($a_value); + } + + public function getHTML($a_value) + { + return nl2br($a_value); + } } diff --git a/Modules/Exercise/classes/class.ilExcCronFeedbackNotification.php b/Modules/Exercise/classes/class.ilExcCronFeedbackNotification.php index d83fde471fdeaf4ba3c0c7a11a1c5345b677980e..e26f2131bf2fb9c83ef8ce95109f659d819ac5da 100644 --- a/Modules/Exercise/classes/class.ilExcCronFeedbackNotification.php +++ b/Modules/Exercise/classes/class.ilExcCronFeedbackNotification.php @@ -1,100 +1,95 @@ - - * @ingroup ModulesExercise - */ -class ilExcCronFeedbackNotification extends ilCronJob -{ - /** - * @var ilLanguage - */ - protected $lng; - - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - } - - public function getId() - { - return "exc_feedback_notification"; - } - - public function getTitle() - { - $lng = $this->lng; - - $lng->loadLanguageModule("exc"); - return $lng->txt("exc_global_feedback_file_cron"); - } - - public function getDescription() - { - $lng = $this->lng; - - $lng->loadLanguageModule("exc"); - return $lng->txt("exc_global_feedback_file_cron_info"); - } - - public function getDefaultScheduleType() - { - return self::SCHEDULE_TYPE_DAILY; - } - - public function getDefaultScheduleValue() - { - return; - } - - public function hasAutoActivation() - { - return true; - } - - public function hasFlexibleSchedule() - { - return false; - } - - public function run() - { - $status = ilCronJobResult::STATUS_NO_ACTION; - $message = array(); - - $count = 0; - - include_once "Modules/Exercise/classes/class.ilExAssignment.php"; - foreach(ilExAssignment::getPendingFeedbackNotifications() as $ass_id) - { - if(ilExAssignment::sendFeedbackNotifications($ass_id)) - { - $count++; - } - } - - if($count) - { - $status = ilCronJobResult::STATUS_OK; - } - - $result = new ilCronJobResult(); - $result->setStatus($status); - - return $result; - } -} - -?> \ No newline at end of file + + * @ingroup ModulesExercise + */ +class ilExcCronFeedbackNotification extends ilCronJob +{ + /** + * @var ilLanguage + */ + protected $lng; + + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + } + + public function getId() + { + return "exc_feedback_notification"; + } + + public function getTitle() + { + $lng = $this->lng; + + $lng->loadLanguageModule("exc"); + return $lng->txt("exc_global_feedback_file_cron"); + } + + public function getDescription() + { + $lng = $this->lng; + + $lng->loadLanguageModule("exc"); + return $lng->txt("exc_global_feedback_file_cron_info"); + } + + public function getDefaultScheduleType() + { + return self::SCHEDULE_TYPE_DAILY; + } + + public function getDefaultScheduleValue() + { + return; + } + + public function hasAutoActivation() + { + return true; + } + + public function hasFlexibleSchedule() + { + return false; + } + + public function run() + { + $status = ilCronJobResult::STATUS_NO_ACTION; + $message = array(); + + $count = 0; + + include_once "Modules/Exercise/classes/class.ilExAssignment.php"; + foreach (ilExAssignment::getPendingFeedbackNotifications() as $ass_id) { + if (ilExAssignment::sendFeedbackNotifications($ass_id)) { + $count++; + } + } + + if ($count) { + $status = ilCronJobResult::STATUS_OK; + } + + $result = new ilCronJobResult(); + $result->setStatus($status); + + return $result; + } +} diff --git a/Modules/Exercise/classes/class.ilExcCronReminders.php b/Modules/Exercise/classes/class.ilExcCronReminders.php index bd5a5d8fd923f8056f50c29d2cfd21cc0e81e31e..ba5c9194c56d8f8f37ca411f05a38442a1a30140 100644 --- a/Modules/Exercise/classes/class.ilExcCronReminders.php +++ b/Modules/Exercise/classes/class.ilExcCronReminders.php @@ -12,91 +12,87 @@ include_once "Services/Cron/classes/class.ilCronJob.php"; */ class ilExcCronReminders extends ilCronJob { - /** - * @var ilLanguage - */ - protected $lng; - - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - } - - public function getId() - { - return "exc_reminders"; - } - - public function getTitle() - { - $lng = $this->lng; - - $lng->loadLanguageModule("exc"); - - return $lng->txt("exc_reminders_cron"); - } - - public function getDescription() - { - $lng = $this->lng; - - $lng->loadLanguageModule("exc"); - - return $lng->txt("exc_reminders_cron_info"); - } - - public function getDefaultScheduleType() - { - return self::SCHEDULE_TYPE_DAILY; - } - - public function getDefaultScheduleValue() - { - return; - } - - public function hasAutoActivation() - { - return true; - } - - public function hasFlexibleSchedule() - { - return true; - } - - public function run() - { - include_once "Modules/Exercise/classes/class.ilExAssignmentReminder.php"; - - $cron_status = ilCronJobResult::STATUS_NO_ACTION; - $message = ""; - $reminder = new ilExAssignmentReminder(); - $num_reminders = $reminder->checkReminders(); - - if($num_reminders) - { - $cron_status = ilCronJobResult::STATUS_OK; - $message = $this->lng->txt('exc_reminder_cron_ok'); - } - - $cron_result = new ilCronJobResult(); - $cron_result->setStatus($cron_status); - - if($message != "") - { - $cron_result->setMessage($message." ".$num_reminders); - $cron_result->setCode("#".$num_reminders); - } - - return $cron_result; - } -} + /** + * @var ilLanguage + */ + protected $lng; + + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + } + + public function getId() + { + return "exc_reminders"; + } + + public function getTitle() + { + $lng = $this->lng; + + $lng->loadLanguageModule("exc"); + + return $lng->txt("exc_reminders_cron"); + } + + public function getDescription() + { + $lng = $this->lng; + + $lng->loadLanguageModule("exc"); + + return $lng->txt("exc_reminders_cron_info"); + } -?> \ No newline at end of file + public function getDefaultScheduleType() + { + return self::SCHEDULE_TYPE_DAILY; + } + + public function getDefaultScheduleValue() + { + return; + } + + public function hasAutoActivation() + { + return true; + } + + public function hasFlexibleSchedule() + { + return true; + } + + public function run() + { + include_once "Modules/Exercise/classes/class.ilExAssignmentReminder.php"; + + $cron_status = ilCronJobResult::STATUS_NO_ACTION; + $message = ""; + $reminder = new ilExAssignmentReminder(); + $num_reminders = $reminder->checkReminders(); + + if ($num_reminders) { + $cron_status = ilCronJobResult::STATUS_OK; + $message = $this->lng->txt('exc_reminder_cron_ok'); + } + + $cron_result = new ilCronJobResult(); + $cron_result->setStatus($cron_status); + + if ($message != "") { + $cron_result->setMessage($message . " " . $num_reminders); + $cron_result->setCode("#" . $num_reminders); + } + + return $cron_result; + } +} diff --git a/Modules/Exercise/classes/class.ilExcDeliveredFilesTableGUI.php b/Modules/Exercise/classes/class.ilExcDeliveredFilesTableGUI.php index 34b79659c730db8b4cf58d27eee3b07cebcb3566..297294efeeda008568b2f666fc8cfa3faf1bca4e 100644 --- a/Modules/Exercise/classes/class.ilExcDeliveredFilesTableGUI.php +++ b/Modules/Exercise/classes/class.ilExcDeliveredFilesTableGUI.php @@ -13,98 +13,91 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilExcDeliveredFilesTableGUI extends ilTable2GUI { - protected $submission; // [ilExSubmission] - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, ilExSubmission $a_submission) - { - global $DIC; + protected $submission; // [ilExSubmission] + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, ilExSubmission $a_submission) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->submission = $a_submission; - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setData($this->submission->getFiles()); - $this->setTitle($this->lng->txt("already_delivered_files")." - ". - $this->submission->getAssignment()->getTitle()); - $this->setLimit(9999); - - $this->addColumn($this->lng->txt(""), "", "1", 1); - $this->addColumn($this->lng->txt("filename"), "filetitle"); - - if ($this->submission->getAssignment()->getAssignmentType()->usesTeams() && - $this->submission->getAssignment()->getAssignmentType()->usesFileUpload()) - { - // #11957 - $this->lng->loadLanguageModule("file"); - $this->addColumn($this->lng->txt("file_uploaded_by")); - include_once "Services/User/classes/class.ilUserUtil.php"; - } - - $this->addColumn($this->lng->txt("date"), "timestamp14"); - - if($this->submission->getAssignment()->getExtendedDeadline()) - { - $this->addColumn($this->lng->txt("exc_late_submission"), "late"); - } - - $this->addColumn($this->lng->txt("action")); - $this->setDefaultOrderField("filetitle"); - - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.delivered_file_row.html", "Modules/Exercise"); - $this->disable("footer"); - $this->setEnableTitle(true); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->submission = $a_submission; + + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setData($this->submission->getFiles()); + $this->setTitle($this->lng->txt("already_delivered_files") . " - " . + $this->submission->getAssignment()->getTitle()); + $this->setLimit(9999); + + $this->addColumn($this->lng->txt(""), "", "1", 1); + $this->addColumn($this->lng->txt("filename"), "filetitle"); + + if ($this->submission->getAssignment()->getAssignmentType()->usesTeams() && + $this->submission->getAssignment()->getAssignmentType()->usesFileUpload()) { + // #11957 + $this->lng->loadLanguageModule("file"); + $this->addColumn($this->lng->txt("file_uploaded_by")); + include_once "Services/User/classes/class.ilUserUtil.php"; + } + + $this->addColumn($this->lng->txt("date"), "timestamp14"); + + if ($this->submission->getAssignment()->getExtendedDeadline()) { + $this->addColumn($this->lng->txt("exc_late_submission"), "late"); + } + + $this->addColumn($this->lng->txt("action")); + $this->setDefaultOrderField("filetitle"); + + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.delivered_file_row.html", "Modules/Exercise"); + $this->disable("footer"); + $this->setEnableTitle(true); - if ($this->submission->canSubmit()) - { - $this->addMultiCommand("confirmDeleteDelivered", $lng->txt("delete")); - } - } + if ($this->submission->canSubmit()) { + $this->addMultiCommand("confirmDeleteDelivered", $lng->txt("delete")); + } + } - /** - * Fill table row - */ - protected function fillRow($file) - { - $ilCtrl = $this->ctrl; - - $this->tpl->setVariable("FILE_ID", $file["returned_id"]); - $this->tpl->setVariable("DELIVERED_FILE", $file["filetitle"]); - - $date = new ilDateTime($file['timestamp14'],IL_CAL_TIMESTAMP); - $this->tpl->setVariable("DELIVERED_DATE", ilDatePresentation::formatDate($date)); - - if ($this->submission->getAssignment()->getAssignmentType()->usesTeams() && - $this->submission->getAssignment()->getAssignmentType()->usesFileUpload()) - { - $this->tpl->setVariable("DELIVERED_OWNER", - ilUserUtil::getNamePresentation($file["owner_id"])); - } - - if($this->submission->getAssignment()->getExtendedDeadline()) - { - $this->tpl->setVariable("DELIVERED_LATE", ($file["late"]) - ? ''.$this->lng->txt("yes").'' - : $this->lng->txt("no")); - } - - // #16164 - download - $ilCtrl->setParameter($this->getParentObject(), "delivered", $file["returned_id"]); - $url = $ilCtrl->getLinkTarget($this->getParentObject(), "download"); - $ilCtrl->setParameter($this->getParentObject(), "delivered", ""); - $this->tpl->setVariable("ACTION_TXT", $this->lng->txt("download")); - $this->tpl->setVariable("ACTION_URL", $url); - - } + /** + * Fill table row + */ + protected function fillRow($file) + { + $ilCtrl = $this->ctrl; + $this->tpl->setVariable("FILE_ID", $file["returned_id"]); + $this->tpl->setVariable("DELIVERED_FILE", $file["filetitle"]); + + $date = new ilDateTime($file['timestamp14'], IL_CAL_TIMESTAMP); + $this->tpl->setVariable("DELIVERED_DATE", ilDatePresentation::formatDate($date)); + + if ($this->submission->getAssignment()->getAssignmentType()->usesTeams() && + $this->submission->getAssignment()->getAssignmentType()->usesFileUpload()) { + $this->tpl->setVariable( + "DELIVERED_OWNER", + ilUserUtil::getNamePresentation($file["owner_id"]) + ); + } + + if ($this->submission->getAssignment()->getExtendedDeadline()) { + $this->tpl->setVariable("DELIVERED_LATE", ($file["late"]) + ? '' . $this->lng->txt("yes") . '' + : $this->lng->txt("no")); + } + + // #16164 - download + $ilCtrl->setParameter($this->getParentObject(), "delivered", $file["returned_id"]); + $url = $ilCtrl->getLinkTarget($this->getParentObject(), "download"); + $ilCtrl->setParameter($this->getParentObject(), "delivered", ""); + $this->tpl->setVariable("ACTION_TXT", $this->lng->txt("download")); + $this->tpl->setVariable("ACTION_URL", $url); + } } - -?> \ No newline at end of file diff --git a/Modules/Exercise/classes/class.ilExcIndividualDeadline.php b/Modules/Exercise/classes/class.ilExcIndividualDeadline.php index 2d803fb62c22b7de0edecb12667df306834df064..49deb6466d7fbbd26443cb13b8591244038ae63d 100644 --- a/Modules/Exercise/classes/class.ilExcIndividualDeadline.php +++ b/Modules/Exercise/classes/class.ilExcIndividualDeadline.php @@ -10,188 +10,185 @@ */ class ilExcIndividualDeadline { - /** - * @var int - */ - protected $participant_id; - - /** - * @var bool - */ - protected $is_team; - - /** - * @var int - */ - protected $ass_id; - - /** - * @var ilDB - */ - protected $db; - - /** - * @var int - */ - protected $starting_timestamp = 0; - - /** - * @var int - */ - protected $individual_deadline; - - /** - * ilExcIndividualDeadline constructor. - * - * @param int $a_ass_id - * @param int $a_participant_id - * @param bool $a_is_team - */ - protected function __construct($a_ass_id, $a_participant_id, $a_is_team) - { - global $DIC; - $this->participant_id = $a_participant_id; - $this->is_team = $a_is_team; - $this->ass_id = $a_ass_id; - $this->db = $DIC->database(); - $this->read(); - } - - /** - * Get instance - * - * @param int $a_ass_id - * @param int $a_participant_id - * @param bool $a_is_team - * @return ilExcIndividualDeadline - */ - public static function getInstance($a_ass_id, $a_participant_id, $a_is_team = false) - { - return new self($a_ass_id, $a_participant_id, $a_is_team); - } - - /** - * Set starting timestamp - * - * @param int $a_val starting timestamp - */ - function setStartingTimestamp($a_val) - { - $this->starting_timestamp = $a_val; - } - - /** - * Get starting timestamp - * - * @return int starting timestamp - */ - function getStartingTimestamp() - { - return $this->starting_timestamp; - } - - /** - * Set Individual Deadline - * - * @param int $a_val - */ - function setIndividualDeadline($a_val) - { - $this->individual_deadline = $a_val; - } - - /** - * Get Individual Deadline - * - * @return int - */ - function getIndividualDeadline() - { - return $this->individual_deadline; - } - - /** - * Read - */ - function read() - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT * FROM exc_idl ". - " WHERE ass_id = ".$this->db->quote($this->ass_id, "integer"). - " AND member_id = ".$this->db->quote($this->participant_id, "integer"). - " AND is_team = ".$this->db->quote($this->is_team, "integer") - ); - $rec = $this->db->fetchAssoc($set); - - $this->setIndividualDeadline((int) $rec["tstamp"]); - $this->setStartingTimestamp((int) $rec["starting_ts"]); - } - - /** - * Save - */ - function save() - { - $ilDB = $this->db; - - $ilDB->replace("exc_idl", - array( - "ass_id" => array("integer", $this->ass_id), - "member_id" => array("integer", $this->participant_id), - "is_team" => array("integer", $this->is_team) - ), - array( - "tstamp" => array("integer", $this->getIndividualDeadline()), - "starting_ts" => array("integer", $this->getStartingTimestamp()) - ) - ); - } - - /** - * Delete - */ - function delete() - { - $ilDB = $this->db; - - $ilDB->manipulate("DELETE FROM exc_idl ". - " WHERE ass_id = ".$this->db->quote($this->ass_id, "integer"). - " AND member_id = ".$this->db->quote($this->participant_id, "integer"). - " AND is_team = ".$this->db->quote($this->is_team, "integer") - ); - - } - - - /** - * Get starting timestamp data for an assignment. - * - * This is mainly used by ilExAssignment to determine the calculated deadlines - * - * @param $a_ass_id - * @return array - */ - static public function getStartingTimestamps($a_ass_id) - { - global $DIC; - - $ilDB = $DIC->database(); - $res = array(); - - $set = $ilDB->query("SELECT * FROM exc_idl". - " WHERE ass_id = ".$ilDB->quote($a_ass_id, "integer")); - while ($row = $ilDB->fetchAssoc($set)) - { - $res[] = array("member_id" => $row["member_id"], - "is_team" => $row["is_team"], - "starting_ts" => $row["starting_ts"]); - } - - return $res; - } - - + /** + * @var int + */ + protected $participant_id; + + /** + * @var bool + */ + protected $is_team; + + /** + * @var int + */ + protected $ass_id; + + /** + * @var ilDB + */ + protected $db; + + /** + * @var int + */ + protected $starting_timestamp = 0; + + /** + * @var int + */ + protected $individual_deadline; + + /** + * ilExcIndividualDeadline constructor. + * + * @param int $a_ass_id + * @param int $a_participant_id + * @param bool $a_is_team + */ + protected function __construct($a_ass_id, $a_participant_id, $a_is_team) + { + global $DIC; + $this->participant_id = $a_participant_id; + $this->is_team = $a_is_team; + $this->ass_id = $a_ass_id; + $this->db = $DIC->database(); + $this->read(); + } + + /** + * Get instance + * + * @param int $a_ass_id + * @param int $a_participant_id + * @param bool $a_is_team + * @return ilExcIndividualDeadline + */ + public static function getInstance($a_ass_id, $a_participant_id, $a_is_team = false) + { + return new self($a_ass_id, $a_participant_id, $a_is_team); + } + + /** + * Set starting timestamp + * + * @param int $a_val starting timestamp + */ + public function setStartingTimestamp($a_val) + { + $this->starting_timestamp = $a_val; + } + + /** + * Get starting timestamp + * + * @return int starting timestamp + */ + public function getStartingTimestamp() + { + return $this->starting_timestamp; + } + + /** + * Set Individual Deadline + * + * @param int $a_val + */ + public function setIndividualDeadline($a_val) + { + $this->individual_deadline = $a_val; + } + + /** + * Get Individual Deadline + * + * @return int + */ + public function getIndividualDeadline() + { + return $this->individual_deadline; + } + + /** + * Read + */ + public function read() + { + $ilDB = $this->db; + + $set = $ilDB->query( + "SELECT * FROM exc_idl " . + " WHERE ass_id = " . $this->db->quote($this->ass_id, "integer") . + " AND member_id = " . $this->db->quote($this->participant_id, "integer") . + " AND is_team = " . $this->db->quote($this->is_team, "integer") + ); + $rec = $this->db->fetchAssoc($set); + + $this->setIndividualDeadline((int) $rec["tstamp"]); + $this->setStartingTimestamp((int) $rec["starting_ts"]); + } + + /** + * Save + */ + public function save() + { + $ilDB = $this->db; + + $ilDB->replace( + "exc_idl", + array( + "ass_id" => array("integer", $this->ass_id), + "member_id" => array("integer", $this->participant_id), + "is_team" => array("integer", $this->is_team) + ), + array( + "tstamp" => array("integer", $this->getIndividualDeadline()), + "starting_ts" => array("integer", $this->getStartingTimestamp()) + ) + ); + } + + /** + * Delete + */ + public function delete() + { + $ilDB = $this->db; + + $ilDB->manipulate( + "DELETE FROM exc_idl " . + " WHERE ass_id = " . $this->db->quote($this->ass_id, "integer") . + " AND member_id = " . $this->db->quote($this->participant_id, "integer") . + " AND is_team = " . $this->db->quote($this->is_team, "integer") + ); + } + + + /** + * Get starting timestamp data for an assignment. + * + * This is mainly used by ilExAssignment to determine the calculated deadlines + * + * @param $a_ass_id + * @return array + */ + public static function getStartingTimestamps($a_ass_id) + { + global $DIC; + + $ilDB = $DIC->database(); + $res = array(); + + $set = $ilDB->query("SELECT * FROM exc_idl" . + " WHERE ass_id = " . $ilDB->quote($a_ass_id, "integer")); + while ($row = $ilDB->fetchAssoc($set)) { + $res[] = array("member_id" => $row["member_id"], + "is_team" => $row["is_team"], + "starting_ts" => $row["starting_ts"]); + } + + return $res; + } } - -?> \ No newline at end of file diff --git a/Modules/Exercise/classes/class.ilExcMailTemplateGradeReminderContext.php b/Modules/Exercise/classes/class.ilExcMailTemplateGradeReminderContext.php index e509718b7a8dda059af55011dd4eb5db5adea49c..682f162ba54ce0919e3bbe77f4b92d981054c476 100644 --- a/Modules/Exercise/classes/class.ilExcMailTemplateGradeReminderContext.php +++ b/Modules/Exercise/classes/class.ilExcMailTemplateGradeReminderContext.php @@ -6,121 +6,114 @@ include_once './Services/Mail/classes/class.ilMailTemplateContext.php'; /** * Handles exercise Grade reminder mail placeholders * If all contexts are using the same placeholders,constructor etc. todo: create base class. - * + * * @author Jesús López * @package ModulesExercise */ class ilExcMailTemplateGradeReminderContext extends ilMailTemplateContext { - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilObjectDataCache - */ - protected $obj_data_cache; - - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - if (isset($DIC["ilObjDataCache"])) - { - $this->obj_data_cache = $DIC["ilObjDataCache"]; - } - } - - const ID = 'exc_context_grade_rmd'; - - /** - * @return string - */ - public function getId() - { - return self::ID; - } - - /** - * @return string - */ - public function getTitle() - { - $lng = $this->lng; - - $lng->loadLanguageModule('exc'); - - return $lng->txt('exc_mail_context_grade_reminder_title'); - } - - /** - * @return string - */ - public function getDescription() - { - $lng = $this->lng; - - $lng->loadLanguageModule('exc'); - - return $lng->txt('exc_mail_context_grade_reminder_info'); - } - - /** - * Return an array of placeholders - * @return array - */ - public function getSpecificPlaceholders() - { - $lng = $this->lng; - $lng->loadLanguageModule('exc'); - - $placeholders = array(); - - $placeholders['ass_title'] = array( - 'placeholder' => 'ASSIGNMENT_TITLE', - 'label' => $lng->txt('exc_mail_context_reminder_assignment_title') - ); - $placeholders['exc_title'] = array( - 'placeholder' => 'EXERCISE_TITLE', - 'label' => $lng->txt('exc_mail_context_reminder_exercise_title') - ); - - $placeholders['ass_link'] = array( - 'placeholder' => 'ASSIGNMENT_LINK', - 'label' => $lng->txt('perma_link') - ); - - return $placeholders; - } - - /** - * {@inheritdoc} - */ - public function resolveSpecificPlaceholder($placeholder_id, array $context_parameters, ilObjUser $recipient = null, $html_markup = false) - { - $ilObjDataCache = $this->obj_data_cache; - - if($placeholder_id == 'ass_title') - { - return ilExAssignment::lookupTitle($context_parameters["ass_id"]); - } - else if($placeholder_id == 'exc_title') - { - return $ilObjDataCache->lookupTitle($context_parameters["exc_id"]); - - } - else if($placeholder_id == 'ass_link') - { - require_once './Services/Link/classes/class.ilLink.php'; - return ilLink::_getLink($context_parameters["exc_ref"], "exc", array(), "_".$context_parameters["ass_id"]); - } - - return ''; - } -} \ No newline at end of file + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilObjectDataCache + */ + protected $obj_data_cache; + + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + if (isset($DIC["ilObjDataCache"])) { + $this->obj_data_cache = $DIC["ilObjDataCache"]; + } + } + + const ID = 'exc_context_grade_rmd'; + + /** + * @return string + */ + public function getId() + { + return self::ID; + } + + /** + * @return string + */ + public function getTitle() + { + $lng = $this->lng; + + $lng->loadLanguageModule('exc'); + + return $lng->txt('exc_mail_context_grade_reminder_title'); + } + + /** + * @return string + */ + public function getDescription() + { + $lng = $this->lng; + + $lng->loadLanguageModule('exc'); + + return $lng->txt('exc_mail_context_grade_reminder_info'); + } + + /** + * Return an array of placeholders + * @return array + */ + public function getSpecificPlaceholders() + { + $lng = $this->lng; + $lng->loadLanguageModule('exc'); + + $placeholders = array(); + + $placeholders['ass_title'] = array( + 'placeholder' => 'ASSIGNMENT_TITLE', + 'label' => $lng->txt('exc_mail_context_reminder_assignment_title') + ); + $placeholders['exc_title'] = array( + 'placeholder' => 'EXERCISE_TITLE', + 'label' => $lng->txt('exc_mail_context_reminder_exercise_title') + ); + + $placeholders['ass_link'] = array( + 'placeholder' => 'ASSIGNMENT_LINK', + 'label' => $lng->txt('perma_link') + ); + + return $placeholders; + } + + /** + * {@inheritdoc} + */ + public function resolveSpecificPlaceholder($placeholder_id, array $context_parameters, ilObjUser $recipient = null, $html_markup = false) + { + $ilObjDataCache = $this->obj_data_cache; + + if ($placeholder_id == 'ass_title') { + return ilExAssignment::lookupTitle($context_parameters["ass_id"]); + } elseif ($placeholder_id == 'exc_title') { + return $ilObjDataCache->lookupTitle($context_parameters["exc_id"]); + } elseif ($placeholder_id == 'ass_link') { + require_once './Services/Link/classes/class.ilLink.php'; + return ilLink::_getLink($context_parameters["exc_ref"], "exc", array(), "_" . $context_parameters["ass_id"]); + } + + return ''; + } +} diff --git a/Modules/Exercise/classes/class.ilExcMailTemplatePeerReminderContext.php b/Modules/Exercise/classes/class.ilExcMailTemplatePeerReminderContext.php index fb0515c6de48b4b3054cdf9f6347f490aa9fdf56..5d8bc99ece9d56ae5bcb303893aae621a84f631d 100644 --- a/Modules/Exercise/classes/class.ilExcMailTemplatePeerReminderContext.php +++ b/Modules/Exercise/classes/class.ilExcMailTemplatePeerReminderContext.php @@ -6,121 +6,114 @@ include_once './Services/Mail/classes/class.ilMailTemplateContext.php'; /** * Handles exercise Peer reminder mail placeholders * If all contexts are using the same placeholders,constructor etc. todo: create base class. - * + * * @author Jesús López * @package ModulesExercise */ class ilExcMailTemplatePeerReminderContext extends ilMailTemplateContext { - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilObjectDataCache - */ - protected $obj_data_cache; - - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - if (isset($DIC["ilObjDataCache"])) - { - $this->obj_data_cache = $DIC["ilObjDataCache"]; - } - } - - const ID = 'exc_context_peer_rmd'; - - /** - * @return string - */ - public function getId() - { - return self::ID; - } - - /** - * @return string - */ - public function getTitle() - { - $lng = $this->lng; - - $lng->loadLanguageModule('exc'); - - return $lng->txt('exc_mail_context_peer_reminder_title'); - } - - /** - * @return string - */ - public function getDescription() - { - $lng = $this->lng; - - $lng->loadLanguageModule('exc'); - - return $lng->txt('exc_mail_context_peer_reminder_info'); - } - - /** - * Return an array of placeholders - * @return array - */ - public function getSpecificPlaceholders() - { - $lng = $this->lng; - $lng->loadLanguageModule('exc'); - - $placeholders = array(); - - $placeholders['ass_title'] = array( - 'placeholder' => 'ASSIGNMENT_TITLE', - 'label' => $lng->txt('exc_mail_context_reminder_assignment_title') - ); - $placeholders['exc_title'] = array( - 'placeholder' => 'EXERCISE_TITLE', - 'label' => $lng->txt('exc_mail_context_reminder_exercise_title') - ); - - $placeholders['ass_link'] = array( - 'placeholder' => 'ASSIGNMENT_LINK', - 'label' => $lng->txt('perma_link') - ); - - return $placeholders; - } - - /** - * {@inheritdoc} - */ - public function resolveSpecificPlaceholder($placeholder_id, array $context_parameters, ilObjUser $recipient = null, $html_markup = false) - { - $ilObjDataCache = $this->obj_data_cache; - - if($placeholder_id == 'ass_title') - { - return ilExAssignment::lookupTitle($context_parameters["ass_id"]); - } - else if($placeholder_id == 'exc_title') - { - return $ilObjDataCache->lookupTitle($context_parameters["exc_id"]); - - } - else if($placeholder_id == 'ass_link') - { - require_once './Services/Link/classes/class.ilLink.php'; - return ilLink::_getLink($context_parameters["exc_ref"], "exc", array(), "_".$context_parameters["ass_id"]); - } - - return ''; - } -} \ No newline at end of file + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilObjectDataCache + */ + protected $obj_data_cache; + + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + if (isset($DIC["ilObjDataCache"])) { + $this->obj_data_cache = $DIC["ilObjDataCache"]; + } + } + + const ID = 'exc_context_peer_rmd'; + + /** + * @return string + */ + public function getId() + { + return self::ID; + } + + /** + * @return string + */ + public function getTitle() + { + $lng = $this->lng; + + $lng->loadLanguageModule('exc'); + + return $lng->txt('exc_mail_context_peer_reminder_title'); + } + + /** + * @return string + */ + public function getDescription() + { + $lng = $this->lng; + + $lng->loadLanguageModule('exc'); + + return $lng->txt('exc_mail_context_peer_reminder_info'); + } + + /** + * Return an array of placeholders + * @return array + */ + public function getSpecificPlaceholders() + { + $lng = $this->lng; + $lng->loadLanguageModule('exc'); + + $placeholders = array(); + + $placeholders['ass_title'] = array( + 'placeholder' => 'ASSIGNMENT_TITLE', + 'label' => $lng->txt('exc_mail_context_reminder_assignment_title') + ); + $placeholders['exc_title'] = array( + 'placeholder' => 'EXERCISE_TITLE', + 'label' => $lng->txt('exc_mail_context_reminder_exercise_title') + ); + + $placeholders['ass_link'] = array( + 'placeholder' => 'ASSIGNMENT_LINK', + 'label' => $lng->txt('perma_link') + ); + + return $placeholders; + } + + /** + * {@inheritdoc} + */ + public function resolveSpecificPlaceholder($placeholder_id, array $context_parameters, ilObjUser $recipient = null, $html_markup = false) + { + $ilObjDataCache = $this->obj_data_cache; + + if ($placeholder_id == 'ass_title') { + return ilExAssignment::lookupTitle($context_parameters["ass_id"]); + } elseif ($placeholder_id == 'exc_title') { + return $ilObjDataCache->lookupTitle($context_parameters["exc_id"]); + } elseif ($placeholder_id == 'ass_link') { + require_once './Services/Link/classes/class.ilLink.php'; + return ilLink::_getLink($context_parameters["exc_ref"], "exc", array(), "_" . $context_parameters["ass_id"]); + } + + return ''; + } +} diff --git a/Modules/Exercise/classes/class.ilExcMailTemplateSubmitReminderContext.php b/Modules/Exercise/classes/class.ilExcMailTemplateSubmitReminderContext.php index 0d68f98c65dd1b5700e4b1c1a892ed427372dd72..af4624710df6827aac984c4eca29bc7713543fda 100644 --- a/Modules/Exercise/classes/class.ilExcMailTemplateSubmitReminderContext.php +++ b/Modules/Exercise/classes/class.ilExcMailTemplateSubmitReminderContext.php @@ -6,121 +6,114 @@ include_once './Services/Mail/classes/class.ilMailTemplateContext.php'; /** * Handles exercise Submit reminder mail placeholders * If all contexts are using the same placeholders,constructor etc. todo: create base class. - * + * * @author Jesús López * @package ModulesExercise */ class ilExcMailTemplateSubmitReminderContext extends ilMailTemplateContext { - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilObjectDataCache - */ - protected $obj_data_cache; - - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - if (isset($DIC["ilObjDataCache"])) - { - $this->obj_data_cache = $DIC["ilObjDataCache"]; - } - } - - const ID = 'exc_context_submit_rmd'; - - /** - * @return string - */ - public function getId() - { - return self::ID; - } - - /** - * @return string - */ - public function getTitle() - { - $lng = $this->lng; - - $lng->loadLanguageModule('exc'); - - return $lng->txt('exc_mail_context_submit_reminder_title'); - } - - /** - * @return string - */ - public function getDescription() - { - $lng = $this->lng; - - $lng->loadLanguageModule('exc'); - - return $lng->txt('exc_mail_context_submit_reminder_info'); - } - - /** - * Return an array of placeholders - * @return array - */ - public function getSpecificPlaceholders() - { - $lng = $this->lng; - $lng->loadLanguageModule('exc'); - - $placeholders = array(); - - $placeholders['ass_title'] = array( - 'placeholder' => 'ASSIGNMENT_TITLE', - 'label' => $lng->txt('exc_mail_context_reminder_assignment_title') - ); - $placeholders['exc_title'] = array( - 'placeholder' => 'EXERCISE_TITLE', - 'label' => $lng->txt('exc_mail_context_reminder_exercise_title') - ); - - $placeholders['ass_link'] = array( - 'placeholder' => 'ASSIGNMENT_LINK', - 'label' => $lng->txt('perma_link') - ); - - return $placeholders; - } - - /** - * {@inheritdoc} - */ - public function resolveSpecificPlaceholder($placeholder_id, array $context_parameters, ilObjUser $recipient = null, $html_markup = false) - { - $ilObjDataCache = $this->obj_data_cache; - - if($placeholder_id == 'ass_title') - { - return ilExAssignment::lookupTitle($context_parameters["ass_id"]); - } - else if($placeholder_id == 'exc_title') - { - return $ilObjDataCache->lookupTitle($context_parameters["exc_id"]); - - } - else if($placeholder_id == 'ass_link') - { - require_once './Services/Link/classes/class.ilLink.php'; - return ilLink::_getLink($context_parameters["exc_ref"], "exc", array(), "_".$context_parameters["ass_id"]); - } - - return ''; - } -} \ No newline at end of file + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilObjectDataCache + */ + protected $obj_data_cache; + + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + if (isset($DIC["ilObjDataCache"])) { + $this->obj_data_cache = $DIC["ilObjDataCache"]; + } + } + + const ID = 'exc_context_submit_rmd'; + + /** + * @return string + */ + public function getId() + { + return self::ID; + } + + /** + * @return string + */ + public function getTitle() + { + $lng = $this->lng; + + $lng->loadLanguageModule('exc'); + + return $lng->txt('exc_mail_context_submit_reminder_title'); + } + + /** + * @return string + */ + public function getDescription() + { + $lng = $this->lng; + + $lng->loadLanguageModule('exc'); + + return $lng->txt('exc_mail_context_submit_reminder_info'); + } + + /** + * Return an array of placeholders + * @return array + */ + public function getSpecificPlaceholders() + { + $lng = $this->lng; + $lng->loadLanguageModule('exc'); + + $placeholders = array(); + + $placeholders['ass_title'] = array( + 'placeholder' => 'ASSIGNMENT_TITLE', + 'label' => $lng->txt('exc_mail_context_reminder_assignment_title') + ); + $placeholders['exc_title'] = array( + 'placeholder' => 'EXERCISE_TITLE', + 'label' => $lng->txt('exc_mail_context_reminder_exercise_title') + ); + + $placeholders['ass_link'] = array( + 'placeholder' => 'ASSIGNMENT_LINK', + 'label' => $lng->txt('perma_link') + ); + + return $placeholders; + } + + /** + * {@inheritdoc} + */ + public function resolveSpecificPlaceholder($placeholder_id, array $context_parameters, ilObjUser $recipient = null, $html_markup = false) + { + $ilObjDataCache = $this->obj_data_cache; + + if ($placeholder_id == 'ass_title') { + return ilExAssignment::lookupTitle($context_parameters["ass_id"]); + } elseif ($placeholder_id == 'exc_title') { + return $ilObjDataCache->lookupTitle($context_parameters["exc_id"]); + } elseif ($placeholder_id == 'ass_link') { + require_once './Services/Link/classes/class.ilLink.php'; + return ilLink::_getLink($context_parameters["exc_ref"], "exc", array(), "_" . $context_parameters["ass_id"]); + } + + return ''; + } +} diff --git a/Modules/Exercise/classes/class.ilExerciseCertificateAdapter.php b/Modules/Exercise/classes/class.ilExerciseCertificateAdapter.php index 0ae8317b8bf5af33104643c1fc11be401c3552e4..5531bb9f9cbd137dc45506944d6f44ac1fac100f 100644 --- a/Modules/Exercise/classes/class.ilExerciseCertificateAdapter.php +++ b/Modules/Exercise/classes/class.ilExerciseCertificateAdapter.php @@ -32,187 +32,184 @@ include_once "./Services/Certificate/classes/class.ilCertificateAdapter.php"; */ class ilExerciseCertificateAdapter extends ilCertificateAdapter { - protected $object; - - /** - * ilTestCertificateAdapter contructor - * - * @param object $object A reference to a test object - */ - function __construct($object) - { - $this->object = $object; - parent::__construct(); - } + protected $object; + + /** + * ilTestCertificateAdapter contructor + * + * @param object $object A reference to a test object + */ + public function __construct($object) + { + $this->object = $object; + parent::__construct(); + } - /** - * Returns the certificate path (with a trailing path separator) - * - * @return string The certificate path - */ - public function getCertificatePath() - { - return CLIENT_WEB_DIR . "/exercise/certificates/" . $this->object->getId() . "/"; - } - - /** - * Returns an array containing all variables and values which can be exchanged in the certificate. - * The values will be taken for the certificate preview. - * - * @return array The certificate variables - */ - public function getCertificateVariablesForPreview() - { - $vars = $this->getBaseVariablesForPreview(false); - $vars["RESULT_PASSED"] = ilUtil::prepareFormOutput($this->lng->txt("certificate_var_result_passed")); - $vars["RESULT_MARK"] = ilUtil::prepareFormOutput($this->lng->txt("certificate_var_result_mark_short")); - $vars["EXERCISE_TITLE"] = ilUtil::prepareFormOutput($this->object->getTitle()); - - $insert_tags = array(); - foreach($vars as $id => $caption) - { - $insert_tags["[".$id."]"] = $caption; - } - return $insert_tags; - } + /** + * Returns the certificate path (with a trailing path separator) + * + * @return string The certificate path + */ + public function getCertificatePath() + { + return CLIENT_WEB_DIR . "/exercise/certificates/" . $this->object->getId() . "/"; + } + + /** + * Returns an array containing all variables and values which can be exchanged in the certificate. + * The values will be taken for the certificate preview. + * + * @return array The certificate variables + */ + public function getCertificateVariablesForPreview() + { + $vars = $this->getBaseVariablesForPreview(false); + $vars["RESULT_PASSED"] = ilUtil::prepareFormOutput($this->lng->txt("certificate_var_result_passed")); + $vars["RESULT_MARK"] = ilUtil::prepareFormOutput($this->lng->txt("certificate_var_result_mark_short")); + $vars["EXERCISE_TITLE"] = ilUtil::prepareFormOutput($this->object->getTitle()); + + $insert_tags = array(); + foreach ($vars as $id => $caption) { + $insert_tags["[" . $id . "]"] = $caption; + } + return $insert_tags; + } - /** - * Returns an array containing all variables and values which can be exchanged in the certificate - * The values should be calculated from real data. The $params parameter array should contain all - * necessary information to calculate the values. - * - * @param array $params An array of parameters to calculate the certificate parameter values - * @return array The certificate variables - */ - public function getCertificateVariablesForPresentation($params = array()) - { - $user_id = $params["user_id"]; - - include_once 'Services/Tracking/classes/class.ilLPMarks.php'; - $mark = ilLPMarks::_lookupMark($user_id, $this->object->getId()); - include_once 'Modules/Exercise/classes/class.ilExerciseMembers.php'; - $status = ilExerciseMembers::_lookupStatus($this->object->getId(), $user_id); - - $user_data = ilObjUser::_lookupFields($user_id); - $completion_date = $this->getUserCompletionDate($user_id); - - $vars = $this->getBaseVariablesForPresentation($user_data, null, $completion_date); - $vars["RESULT_PASSED"] = ilUtil::prepareFormOutput($this->lng->txt("exc_".$status)); - $vars["RESULT_MARK"] = ilUtil::prepareFormOutput($mark); - $vars["EXERCISE_TITLE"] = ilUtil::prepareFormOutput($this->object->getTitle()); - - foreach($vars as $id => $caption) - { - $insert_tags["[".$id."]"] = $caption; - } - return $insert_tags; - } - - /** - * Returns a description of the available certificate parameters. The description will be shown at - * the bottom of the certificate editor text area. - * - * @return string The certificate parameters description - */ - public function getCertificateVariablesDescription() - { - $vars = $this->getBaseVariablesDescription(false); - $vars["RESULT_PASSED"] = $this->lng->txt("certificate_ph_passed_exercise"); - $vars["RESULT_MARK"] = $this->lng->txt("certificate_ph_mark"); - $vars["EXERCISE_TITLE"] = $this->lng->txt("certificate_ph_exercisetitle"); - - $template = new ilTemplate("tpl.certificate_edit.html", TRUE, TRUE, "Modules/Exercise"); - $template->setCurrentBlock("items"); - foreach($vars as $id => $caption) - { - $template->setVariable("ID", $id); - $template->setVariable("TXT", $caption); - $template->parseCurrentBlock(); - } + /** + * Returns an array containing all variables and values which can be exchanged in the certificate + * The values should be calculated from real data. The $params parameter array should contain all + * necessary information to calculate the values. + * + * @param array $params An array of parameters to calculate the certificate parameter values + * @return array The certificate variables + */ + public function getCertificateVariablesForPresentation($params = array()) + { + $user_id = $params["user_id"]; + + include_once 'Services/Tracking/classes/class.ilLPMarks.php'; + $mark = ilLPMarks::_lookupMark($user_id, $this->object->getId()); + include_once 'Modules/Exercise/classes/class.ilExerciseMembers.php'; + $status = ilExerciseMembers::_lookupStatus($this->object->getId(), $user_id); + + $user_data = ilObjUser::_lookupFields($user_id); + $completion_date = $this->getUserCompletionDate($user_id); + + $vars = $this->getBaseVariablesForPresentation($user_data, null, $completion_date); + $vars["RESULT_PASSED"] = ilUtil::prepareFormOutput($this->lng->txt("exc_" . $status)); + $vars["RESULT_MARK"] = ilUtil::prepareFormOutput($mark); + $vars["EXERCISE_TITLE"] = ilUtil::prepareFormOutput($this->object->getTitle()); + + foreach ($vars as $id => $caption) { + $insert_tags["[" . $id . "]"] = $caption; + } + return $insert_tags; + } + + /** + * Returns a description of the available certificate parameters. The description will be shown at + * the bottom of the certificate editor text area. + * + * @return string The certificate parameters description + */ + public function getCertificateVariablesDescription() + { + $vars = $this->getBaseVariablesDescription(false); + $vars["RESULT_PASSED"] = $this->lng->txt("certificate_ph_passed_exercise"); + $vars["RESULT_MARK"] = $this->lng->txt("certificate_ph_mark"); + $vars["EXERCISE_TITLE"] = $this->lng->txt("certificate_ph_exercisetitle"); + + $template = new ilTemplate("tpl.certificate_edit.html", true, true, "Modules/Exercise"); + $template->setCurrentBlock("items"); + foreach ($vars as $id => $caption) { + $template->setVariable("ID", $id); + $template->setVariable("TXT", $caption); + $template->parseCurrentBlock(); + } - $template->setVariable("PH_INTRODUCTION", $this->lng->txt("certificate_ph_introduction")); + $template->setVariable("PH_INTRODUCTION", $this->lng->txt("certificate_ph_introduction")); - return $template->get(); - } - - public function addAdditionalFormElements(&$form, $form_fields) - { - $visibility = new ilRadioGroupInputGUI($this->lng->txt("certificate_visibility"), "certificate_visibility"); - $visibility->addOption(new ilRadioOption($this->lng->txt("certificate_visibility_always"), 0)); - $visibility->addOption(new ilRadioOption($this->lng->txt("certificate_visibility_passed_exercise"), 1)); - $visibility->addOption(new ilRadioOption($this->lng->txt("certificate_visibility_never"), 2)); - $visibility->setValue($form_fields["certificate_visibility"]); - if (count($_POST)) $visibility->checkInput(); - $form->addItem($visibility); - } + return $template->get(); + } + + public function addAdditionalFormElements(&$form, $form_fields) + { + $visibility = new ilRadioGroupInputGUI($this->lng->txt("certificate_visibility"), "certificate_visibility"); + $visibility->addOption(new ilRadioOption($this->lng->txt("certificate_visibility_always"), 0)); + $visibility->addOption(new ilRadioOption($this->lng->txt("certificate_visibility_passed_exercise"), 1)); + $visibility->addOption(new ilRadioOption($this->lng->txt("certificate_visibility_never"), 2)); + $visibility->setValue($form_fields["certificate_visibility"]); + if (count($_POST)) { + $visibility->checkInput(); + } + $form->addItem($visibility); + } - public function addFormFieldsFromPOST(&$form_fields) - { - $form_fields["certificate_visibility"] = $_POST["certificate_visibility"]; - } + public function addFormFieldsFromPOST(&$form_fields) + { + $form_fields["certificate_visibility"] = $_POST["certificate_visibility"]; + } - public function addFormFieldsFromObject(&$form_fields) - { - $form_fields["certificate_visibility"] = $this->object->getCertificateVisibility(); - } + public function addFormFieldsFromObject(&$form_fields) + { + $form_fields["certificate_visibility"] = $this->object->getCertificateVisibility(); + } - public function saveFormFields(&$form_fields) - { - $this->object->saveCertificateVisibility($form_fields["certificate_visibility"]); - } + public function saveFormFields(&$form_fields) + { + $this->object->saveCertificateVisibility($form_fields["certificate_visibility"]); + } - /** - * Returns the adapter type - * This value will be used to generate file names for the certificates - * - * @return string A string value to represent the adapter type - */ - public function getAdapterType() - { - return "exc"; - } + /** + * Returns the adapter type + * This value will be used to generate file names for the certificates + * + * @return string A string value to represent the adapter type + */ + public function getAdapterType() + { + return "exc"; + } - /** - * Returns a certificate ID - * This value will be used to generate unique file names for the certificates - * - * @return mixed A unique ID which represents a certificate - */ - public function getCertificateID() - { - return $this->object->getId(); - } + /** + * Returns a certificate ID + * This value will be used to generate unique file names for the certificates + * + * @return mixed A unique ID which represents a certificate + */ + public function getCertificateID() + { + return $this->object->getId(); + } - /** - * This code was orignaly located in `ilObjExercise` and has been moved - * here for `ilCertificateMigrationJob` - * - * @param int $objectId - * @param int $userId - * @return bool - */ - public function hasUserCertificate(int $userId) - { - // show certificate? - if(ilCertificate::isActive() && ilCertificate::isObjectActive($this->object->getId())) { - $certificate_visible = $this->object->getCertificateVisibility(); - // if not never - if($certificate_visible != 2) { - // if passed only - $status = ilExerciseMembers::_lookupStatus($this->object->getId(), $userId); - if($certificate_visible == 1 && $status == "passed") { - return true; - } + /** + * This code was orignaly located in `ilObjExercise` and has been moved + * here for `ilCertificateMigrationJob` + * + * @param int $objectId + * @param int $userId + * @return bool + */ + public function hasUserCertificate(int $userId) + { + // show certificate? + if (ilCertificate::isActive() && ilCertificate::isObjectActive($this->object->getId())) { + $certificate_visible = $this->object->getCertificateVisibility(); + // if not never + if ($certificate_visible != 2) { + // if passed only + $status = ilExerciseMembers::_lookupStatus($this->object->getId(), $userId); + if ($certificate_visible == 1 && $status == "passed") { + return true; + } - // always (excluding notgraded) - else if($certificate_visible == 0 && $status != "notgraded") { - return true; - } - } - } + // always (excluding notgraded) + elseif ($certificate_visible == 0 && $status != "notgraded") { + return true; + } + } + } - return false; - } + return false; + } } - -?> diff --git a/Modules/Exercise/classes/class.ilExerciseDataSet.php b/Modules/Exercise/classes/class.ilExerciseDataSet.php index 6fed268e49c554134469cc3bd1bfdebb0d1b3073..410f5d8a77d3bbf0ec38362c757171020a0e66c5 100644 --- a/Modules/Exercise/classes/class.ilExerciseDataSet.php +++ b/Modules/Exercise/classes/class.ilExerciseDataSet.php @@ -21,753 +21,694 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); */ class ilExerciseDataSet extends ilDataSet { - /** - * Get supported versions - * - * @param - * @return - */ - public function getSupportedVersions() - { - return array("4.1.0", "4.4.0", "5.0.0", "5.1.0", "5.2.0", "5.3.0"); - } - - /** - * Get xml namespace - * - * @param - * @return - */ - function getXmlNamespace($a_entity, $a_schema_version) - { - return "http://www.ilias.de/xml/Modules/Exercise/".$a_entity; - } - - /** - * Get field types for entity - * - * @param - * @return - */ - protected function getTypes($a_entity, $a_version) - { - if ($a_entity == "exc") - { - switch ($a_version) - { - case "4.1.0": - return array( - "Id" => "integer", - "Title" => "text", - "Description" => "text", - "PassMode" => "text", - "PassNr" => "integer", - "ShowSubmissions" => "integer" - ); - - case "4.4.0": - case "5.0.0": - case "5.1.0": - return array( - "Id" => "integer", - "Title" => "text", - "Description" => "text", - "PassMode" => "text", - "PassNr" => "integer", - "ShowSubmissions" => "integer", - "ComplBySubmission" => "integer" - ); - - case "5.2.0": - case "5.3.0": - return array( - "Id" => "integer", - "Title" => "text", - "Description" => "text", - "PassMode" => "text", - "PassNr" => "integer", - "ShowSubmissions" => "integer", - "ComplBySubmission" => "integer", - "Tfeedback" => "integer" - ); - } - } - - if ($a_entity == "exc_assignment") - { - switch ($a_version) - { - case "4.1.0": - return array( - "Id" => "integer", - "ExerciseId" => "integer", - "Deadline" => "text", - "Instruction" => "text", - "Title" => "text", - "Mandatory" => "integer", - "OrderNr" => "integer", - "Dir" => "directory"); - - case "4.4.0": - return array( - "Id" => "integer", - "ExerciseId" => "integer", - "Type" => "integer", - "Deadline" => "integer", - "Instruction" => "text", - "Title" => "text", - "Mandatory" => "integer", - "OrderNr" => "integer", - "Dir" => "directory" - // peer - ,"Peer" => "integer" - ,"PeerMin" => "integer" - ,"PeerDeadline" => "integer" - // global feedback - ,"FeedbackFile" => "integer" - ,"FeedbackCron" => "integer" - ,"FeedbackDate" => "integer" - ,"FeedbackDir" => "directory" - ); - - case "5.0.0": - return array( - "Id" => "integer", - "ExerciseId" => "integer", - "Type" => "integer", - "Deadline" => "integer", - "Instruction" => "text", - "Title" => "text", - "Mandatory" => "integer", - "OrderNr" => "integer", - "Dir" => "directory" - // peer - ,"Peer" => "integer" - ,"PeerMin" => "integer" - ,"PeerDeadline" => "integer" - ,"PeerFile" => "integer" - ,"PeerPersonal" => "integer" - // global feedback - ,"FeedbackFile" => "integer" - ,"FeedbackCron" => "integer" - ,"FeedbackDate" => "integer" - ,"FeedbackDir" => "directory" - ); - - case "5.1.0": - case "5.2.0": - return array( - "Id" => "integer", - "ExerciseId" => "integer", - "Type" => "integer", - "Deadline" => "integer", - "Deadline2" => "integer", - "Instruction" => "text", - "Title" => "text", - "Mandatory" => "integer", - "OrderNr" => "integer", - "TeamTutor" => "integer", - "MaxFile" => "integer", - "Dir" => "directory" - // peer - ,"Peer" => "integer" - ,"PeerMin" => "integer" - ,"PeerDeadline" => "integer" - ,"PeerFile" => "integer" - ,"PeerPersonal" => "integer" - ,"PeerChar" => "integer" - ,"PeerUnlock" => "integer" - ,"PeerValid" => "integer" - ,"PeerText" => "integer" - ,"PeerRating" => "integer" - ,"PeerCritCat" => "integer" - // global feedback - ,"FeedbackFile" => "integer" - ,"FeedbackCron" => "integer" - ,"FeedbackDate" => "integer" - ,"FeedbackDir" => "directory" - ); - case "5.3.0": - return array( - "Id" => "integer", - "ExerciseId" => "integer", - "Type" => "integer", - "Deadline" => "integer", - "Deadline2" => "integer", - "Instruction" => "text", - "Title" => "text", - "Mandatory" => "integer", - "OrderNr" => "integer", - "TeamTutor" => "integer", - "MaxFile" => "integer", - "Dir" => "directory", - //web data directory - "WebDataDir" => "directory" - // peer - ,"Peer" => "integer" - ,"PeerMin" => "integer" - ,"PeerDeadline" => "integer" - ,"PeerFile" => "integer" - ,"PeerPersonal" => "integer" - ,"PeerChar" => "integer" - ,"PeerUnlock" => "integer" - ,"PeerValid" => "integer" - ,"PeerText" => "integer" - ,"PeerRating" => "integer" - ,"PeerCritCat" => "integer" - // global feedback - ,"FeedbackFile" => "integer" - ,"FeedbackCron" => "integer" - ,"FeedbackDate" => "integer" - ,"FeedbackDir" => "directory" - ,"FbDateCustom" => "integer" - ); - } - } - - if ($a_entity == "exc_cit_cat") - { - switch ($a_version) - { - case "5.1.0": - case "5.2.0": - case "5.3.0": - return array( - "Id" => "integer" - ,"Parent" => "integer" - ,"Title" => "text" - ,"Pos" => "integer" - ); - } - } - - if ($a_entity == "exc_cit") - { - switch ($a_version) - { - case "5.1.0": - case "5.2.0": - case "5.3.0": - return array( - "Id" => "integer" - ,"Parent" => "integer" - ,"Type" => "text" - ,"Title" => "text" - ,"Descr" => "text" - ,"Pos" => "integer" - ,"Required" => "integer" - ,"Def" => "text" - ,"DefJson" => "text" - ); - } - } - - if ($a_entity == "exc_ass_file_order") - { - switch ($a_version) - { - case "5.3.0": - return array( - "Id" => "integer" - , "AssignmentId" => "integer" - , "Filename" => "text" - , "OrderNr" => "integer" - ); - } - } - - if ($a_entity == "exc_ass_reminders") - { - switch($a_version) - { - case "5.3.0": - return array( - "Type" => "text", - "AssignmentId" => "integer", - "ExerciseId" => "integer", - "Status" => "integer", - "Start" => "integer", - "End" => "integer", - "Frequency" => "integer", - "LastSend" => "integer", - "TemplateId" => "integer" - ); - } - } - return false; - } - - /** - * Read data - * - * @param - * @return - */ - 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 == "exc") - { - switch ($a_version) - { - case "4.1.0": - $this->getDirectDataFromQuery("SELECT exc_data.obj_id id, title, description,". - " pass_mode, pass_nr, show_submissions". - " FROM exc_data JOIN object_data ON (exc_data.obj_id = object_data.obj_id)". - " WHERE ".$ilDB->in("exc_data.obj_id", $a_ids, false, "integer")); - break; - - case "4.4.0": - case "5.0.0": - case "5.1.0": - $this->getDirectDataFromQuery("SELECT exc_data.obj_id id, title, description,". - " pass_mode, pass_nr, show_submissions, compl_by_submission". - " FROM exc_data JOIN object_data ON (exc_data.obj_id = object_data.obj_id)". - " WHERE ".$ilDB->in("exc_data.obj_id", $a_ids, false, "integer")); - break; - - case "5.2.0": - case "5.3.0": - $this->getDirectDataFromQuery("SELECT exc_data.obj_id id, title, description,". - " pass_mode, pass_nr, show_submissions, compl_by_submission, tfeedback". - " FROM exc_data JOIN object_data ON (exc_data.obj_id = object_data.obj_id)". - " WHERE ".$ilDB->in("exc_data.obj_id", $a_ids, false, "integer")); - break; - } - } - - if ($a_entity == "exc_assignment") - { - switch ($a_version) - { - case "4.1.0": - $this->getDirectDataFromQuery("SELECT id, exc_id exercise_id, time_stamp deadline, ". - " instruction, title, start_time, mandatory, order_nr". - " FROM exc_assignment". - " WHERE ".$ilDB->in("exc_id", $a_ids, false, "integer")); - break; - - case "4.4.0": - $this->getDirectDataFromQuery("SELECT id, exc_id exercise_id, type, time_stamp deadline,". - " instruction, title, start_time, mandatory, order_nr, peer, peer_min, peer_dl peer_deadline,". - " fb_file feedback_file, fb_cron feedback_cron, fb_date feedback_date". - " FROM exc_assignment". - " WHERE ".$ilDB->in("exc_id", $a_ids, false, "integer")); - break; - - case "5.0.0": - $this->getDirectDataFromQuery("SELECT id, exc_id exercise_id, type, time_stamp deadline,". - " instruction, title, start_time, mandatory, order_nr, peer, peer_min, peer_dl peer_deadline,". - " peer_file, peer_prsl peer_personal, fb_file feedback_file, fb_cron feedback_cron, fb_date feedback_date". - " FROM exc_assignment". - " WHERE ".$ilDB->in("exc_id", $a_ids, false, "integer")); - break; - - case "5.1.0": - case "5.2.0": - case "5.3.0": - $this->getDirectDataFromQuery("SELECT id, exc_id exercise_id, type, time_stamp deadline, deadline2,". - " instruction, title, start_time, mandatory, order_nr, team_tutor, max_file, peer, peer_min,". - " peer_dl peer_deadline, peer_file, peer_prsl peer_personal, peer_char, peer_unlock, peer_valid,". - " peer_text, peer_rating, peer_crit_cat, fb_file feedback_file, fb_cron feedback_cron, fb_date feedback_date,". - " fb_date_custom". - " FROM exc_assignment". - " WHERE ".$ilDB->in("exc_id", $a_ids, false, "integer")); - break; - } - } - - if ($a_entity == "exc_crit_cat") - { - switch ($a_version) - { - case "5.1.0": - case "5.2.0": - case "5.3.0": - $this->getDirectDataFromQuery("SELECT id, parent, title, pos". - " FROM exc_crit_cat". - " WHERE ".$ilDB->in("parent", $a_ids, false, "integer")); - break; - } - } - - if ($a_entity == "exc_crit") - { - switch ($a_version) - { - case "5.1.0": - case "5.2.0": - case "5.3.0": - $this->getDirectDataFromQuery("SELECT id, parent, type, title". - ", descr, pos, required, def". - " FROM exc_crit". - " WHERE ".$ilDB->in("parent", $a_ids, false, "integer")); - foreach ($this->data as $k => $v) - { - $this->data[$k]["DefJson"] = ""; - if ($v["Def"] != "") - { - $this->data[$k]["DefJson"] = json_encode(unserialize($v["Def"])); - } - } - break; - } - } - - if ($a_entity == "exc_ass_file_order") - { - switch ($a_version) - { - case "5.3.0": - $this->getDirectDataFromQuery("SELECT id, assignment_id, filename, order_nr". - " FROM exc_ass_file_order". - " WHERE ".$ilDB->in("assignment_id", $a_ids, false, "integer")); - break; - } - - } - - if($a_entity == "exc_ass_reminders") - { - switch ($a_version) - { - case "5.3.0": - $this->getDirectDataFromQuery("SELECT type, ass_id, exc_id, status, start, end, freq, last_send, template_id". - " FROM exc_ass_reminders". - " WHERE ".$ilDB->in("ass_id", $a_ids, false, "integer")); - break; - } - } - } - - /** - * Get xml record (export) - * - * @param array abstract data record - * @return array xml record - */ - function getXmlRecord($a_entity, $a_version, $a_set) - { - if ($a_entity == "exc_assignment") - { - // convert server dates to utc - if($a_set["StartTime"] != "") - { - $start = new ilDateTime($a_set["StartTime"], IL_CAL_UNIX); - $a_set["StartTime"] = $start->get(IL_CAL_DATETIME,'','UTC'); - } - if($a_set["Deadline"] != "") - { - $deadline = new ilDateTime($a_set["Deadline"], IL_CAL_UNIX); - $a_set["Deadline"] = $deadline->get(IL_CAL_DATETIME,'','UTC'); - } - if($a_set["Deadline2"] != "") - { - $deadline = new ilDateTime($a_set["Deadline2"], IL_CAL_UNIX); - $a_set["Deadline2"] = $deadline->get(IL_CAL_DATETIME,'','UTC'); - } - - include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); - $fstorage = new ilFSStorageExercise($a_set["ExerciseId"], $a_set["Id"]); - $a_set["Dir"] = $fstorage->getPath(); - - include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); - $fstorage = new ilFSStorageExercise($a_set["ExerciseId"], $a_set["Id"]); - $a_set["FeedbackDir"] = $fstorage->getGlobalFeedbackPath(); - - //now the instruction files inside the root directory - include_once("./Modules/Exercise/classes/class.ilFSWebStorageExercise.php"); - $fswebstorage = new ilFSWebStorageExercise($a_set['ExerciseId'], $a_set['Id']); - $a_set['WebDataDir'] = $fswebstorage->getPath(); - } - - //Discuss if necessary when working with timestamps. - if($a_entity == "exc_ass_reminders") - { - - if($a_set["End"] != "") - { - $end = new ilDateTime($a_set["End"], IL_CAL_UNIX); - $a_set["End"] = $end->get(IL_CAL_DATETIME,'','UTC'); - } - if($a_set["LastSend"] != "") - { - $last = new ilDateTime($a_set["LastSend"], IL_CAL_UNIX); - $a_set["LastSend"] = $last->get(IL_CAL_DATETIME,'','UTC'); - } - } - - return $a_set; - } - - - /** - * Determine the dependent sets of data - */ - protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) - { - switch ($a_entity) - { - case "exc": - switch ($a_version) - { - case "4.1.0": - case "4.4.0": - case "5.0.0": - return array( - "exc_assignment" => array("ids" => $a_rec["Id"]) - ); - - case "5.1.0": - case "5.2.0": - case "5.3.0": - return array( - "exc_crit_cat" => array("ids" => $a_rec["Id"]), - "exc_assignment" => array("ids" => $a_rec["Id"]) - ); - } - break; - - case "exc_crit_cat": - return array( - "exc_crit" => array("ids" => $a_rec["Id"]) - ); - - case "exc_assignment": - switch ($a_version) - { - case "5.3.0": - return array( - "exc_ass_file_order" => array("ids" => $a_rec["Id"]), - "exc_ass_reminders" => array("ids" => $a_rec["Id"]) - ); - - } - break; - } - return false; - } - - - /** - * Import record - * - * @param - * @return - */ - function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) - { -//echo $a_entity; -//var_dump($a_rec); - - switch ($a_entity) - { - case "exc": - include_once("./Modules/Exercise/classes/class.ilObjExercise.php"); - - if($new_id = $a_mapping->getMapping('Services/Container','objs',$a_rec['Id'])) - { - $newObj = ilObjectFactory::getInstanceByObjId($new_id,false); - } - else - { - $newObj = new ilObjExercise(); - $newObj->setType("exc"); - $newObj->create(true); - } - - $newObj->setTitle($a_rec["Title"]); - $newObj->setDescription($a_rec["Description"]); - $newObj->setPassMode($a_rec["PassMode"]); - $newObj->setPassNr($a_rec["PassNr"]); - $newObj->setShowSubmissions($a_rec["ShowSubmissions"]); - $newObj->setCompletionBySubmission($a_rec["ComplBySubmission"]); - $newObj->setTutorFeedback($a_rec["Tfeedback"]); - $newObj->update(); - $newObj->saveData(); - $this->current_exc = $newObj; - - $a_mapping->addMapping("Modules/Exercise", "exc", $a_rec["Id"], $newObj->getId()); - break; - - case "exc_assignment": - $exc_id = $a_mapping->getMapping("Modules/Exercise", "exc", $a_rec["ExerciseId"]); - if ($exc_id > 0) - { - if (is_object($this->current_exc) && $this->current_exc->getId() == $exc_id) - { - $exc = $this->current_exc; - } - else - { - include_once("./Modules/Exercise/classes/class.ilObjExercise.php"); - $exc = new ilObjExercise($exc_id, false); - } - - include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); - - $ass = new ilExAssignment(); - $ass->setExerciseId($exc_id); - - if ($a_rec["StartTime"] != "") - { - $start = new ilDateTime($a_rec["StartTime"], IL_CAL_DATETIME, "UTC"); - $ass->setStartTime($start->get(IL_CAL_UNIX)); - } - - if ($a_rec["Deadline"] != "") - { - $deadline = new ilDateTime($a_rec["Deadline"], IL_CAL_DATETIME, "UTC"); - $ass->setDeadline($deadline->get(IL_CAL_UNIX)); - } - - $ass->setInstruction($a_rec["Instruction"]); - $ass->setTitle($a_rec["Title"]); - $ass->setMandatory($a_rec["Mandatory"]); - $ass->setOrderNr($a_rec["OrderNr"]); - - // 4.2 - $ass->setType($a_rec["Type"]); - - // 4.4 - $ass->setPeerReview($a_rec["Peer"]); - $ass->setPeerReviewMin($a_rec["PeerMin"]); - $ass->setPeerReviewDeadline($a_rec["PeerDeadline"]); - $ass->setFeedbackFile($a_rec["FeedbackFile"]); - $ass->setFeedbackCron($a_rec["FeedbackCron"]); - $ass->setFeedbackDate($a_rec["FeedbackDate"]); - - // 5.0 - $ass->setPeerReviewFileUpload($a_rec["PeerFile"]); - $ass->setPeerReviewPersonalized($a_rec["PeerPersonal"]); - - // 5.1 - if ($a_rec["Deadline2"] != "") - { - $deadline = new ilDateTime($a_rec["Deadline2"], IL_CAL_DATETIME, "UTC"); - $ass->setExtendedDeadline($deadline->get(IL_CAL_UNIX)); - } - $ass->setMaxFile($a_rec["MaxFile"]); - $ass->setTeamTutor($a_rec["TeamTutor"]); - $ass->setPeerReviewChars($a_rec["PeerChar"]); - $ass->setPeerReviewSimpleUnlock($a_rec["PeerUnlock"]); - $ass->setPeerReviewValid($a_rec["PeerValid"]); - $ass->setPeerReviewText($a_rec["PeerText"]); - $ass->setPeerReviewRating($a_rec["PeerRating"]); - - // 5.3 - $ass->setFeedbackDateCustom($a_rec["FbDateCustom"]); - - // criteria catalogue - if($a_rec["PeerCritCat"]) - { - $ass->setPeerReviewCriteriaCatalogue($a_mapping->getMapping("Modules/Exercise", "exc_crit_cat", $a_rec["PeerCritCat"])); - } - - $ass->save(); - - include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); - $fstorage = new ilFSStorageExercise($exc_id, $ass->getId()); - $fstorage->create(); - - // assignment files - $dir = str_replace("..", "", $a_rec["Dir"]); - if ($dir != "" && $this->getImportDirectory() != "") - { - $source_dir = $this->getImportDirectory()."/".$dir; - $target_dir = $fstorage->getPath(); - ilUtil::rCopy($source_dir, $target_dir); - } - - // (4.4) global feedback file - $dir = str_replace("..", "", $a_rec["FeedbackDir"]); - if ($dir != "" && $this->getImportDirectory() != "") - { - $source_dir = $this->getImportDirectory()."/".$dir; - $target_dir = $fstorage->getGlobalFeedbackPath(); - ilUtil::rCopy($source_dir, $target_dir); - } - - // (5.3) assignment files inside ILIAS - include_once("./Modules/Exercise/classes/class.ilFSWebStorageExercise.php"); - $fwebstorage = new ilFSWebStorageExercise($exc_id, $ass->getId()); - $fwebstorage->create(); - $dir = str_replace("..", "", $a_rec["WebDataDir"]); - if ($dir != "" && $this->getImportDirectory() != "") - { - $source_dir = $this->getImportDirectory()."/".$dir; - $target_dir = $fwebstorage->getPath(); - ilUtil::rCopy($source_dir, $target_dir); - } - - $a_mapping->addMapping("Modules/Exercise", "exc_assignment", $a_rec["Id"], $ass->getId()); - - } - - break; - - case "exc_crit_cat": - $exc_id = $a_mapping->getMapping("Modules/Exercise", "exc", $a_rec["Parent"]); - if ($exc_id > 0) - { - include_once("./Modules/Exercise/classes/class.ilExcCriteriaCatalogue.php"); - $crit_cat = new ilExcCriteriaCatalogue(); - $crit_cat->setParent($exc_id); - $crit_cat->setTitle($a_rec["Title"]); - $crit_cat->setPosition($a_rec["Pos"]); - $crit_cat->save(); - - $a_mapping->addMapping("Modules/Exercise", "exc_crit_cat", $a_rec["Id"], $crit_cat->getId()); - } - break; - - case "exc_crit": - $crit_cat_id = $a_mapping->getMapping("Modules/Exercise", "exc_crit_cat", $a_rec["Parent"]); - if ($crit_cat_id > 0) - { - include_once("./Modules/Exercise/classes/class.ilExcCriteria.php"); - $crit = ilExcCriteria::getInstanceByType($a_rec["Type"]); - $crit->setParent($crit_cat_id); - $crit->setTitle($a_rec["Title"]); - $crit->setDescription($a_rec["Descr"]); - $crit->setPosition($a_rec["Pos"]); - $crit->setRequired($a_rec["Required"]); - $crit->importDefinition($a_rec["Def"], $a_rec["DefJson"]); - $crit->save(); - } - break; - - case "exc_ass_file_order": - - $ass_id = $a_mapping->getMapping("Modules/Exercise", "exc_assignment", $a_rec["AssignmentId"]); - if ($ass_id > 0) - { - ilExAssignment::instructionFileInsertOrder($a_rec["Filename"], $ass_id, $a_rec["OrderNr"]); - } - break; - - case "exc_ass_reminders": - // (5.3) reminders - include_once("./Modules/Exercise/classes/class.ilExAssignmentReminder.php"); - $new_ass_id = $a_mapping->getMapping("Modules/Exercise", "exc_assignment", $a_rec["AssId"]); - $new_exc_id = $a_mapping->getMapping('Modules/Exercise','exc',$a_rec['ExcId']); - //always UTC timestamp in db. - $end = new ilDateTime($a_rec["End"], IL_CAL_DATETIME, "UTC"); - $rmd = new ilExAssignmentReminder($new_exc_id, $new_ass_id,$a_rec["Type"]); - $rmd->setReminderStatus($a_rec["Status"]); - $rmd->setReminderStart($a_rec["Start"]); - $rmd->setReminderEnd($end->get(IL_CAL_UNIX)); - $rmd->setReminderFrequency($a_rec["Freq"]); - $rmd->setReminderLastSend($a_rec["LastSend"]); - $rmd->setReminderMailTemplate($a_rec["TemplateId"]); - $rmd->save(); - } - } + /** + * Get supported versions + * + * @param + * @return + */ + public function getSupportedVersions() + { + return array("4.1.0", "4.4.0", "5.0.0", "5.1.0", "5.2.0", "5.3.0"); + } + + /** + * Get xml namespace + * + * @param + * @return + */ + public function getXmlNamespace($a_entity, $a_schema_version) + { + return "http://www.ilias.de/xml/Modules/Exercise/" . $a_entity; + } + + /** + * Get field types for entity + * + * @param + * @return + */ + protected function getTypes($a_entity, $a_version) + { + if ($a_entity == "exc") { + switch ($a_version) { + case "4.1.0": + return array( + "Id" => "integer", + "Title" => "text", + "Description" => "text", + "PassMode" => "text", + "PassNr" => "integer", + "ShowSubmissions" => "integer" + ); + + case "4.4.0": + case "5.0.0": + case "5.1.0": + return array( + "Id" => "integer", + "Title" => "text", + "Description" => "text", + "PassMode" => "text", + "PassNr" => "integer", + "ShowSubmissions" => "integer", + "ComplBySubmission" => "integer" + ); + + case "5.2.0": + case "5.3.0": + return array( + "Id" => "integer", + "Title" => "text", + "Description" => "text", + "PassMode" => "text", + "PassNr" => "integer", + "ShowSubmissions" => "integer", + "ComplBySubmission" => "integer", + "Tfeedback" => "integer" + ); + } + } + + if ($a_entity == "exc_assignment") { + switch ($a_version) { + case "4.1.0": + return array( + "Id" => "integer", + "ExerciseId" => "integer", + "Deadline" => "text", + "Instruction" => "text", + "Title" => "text", + "Mandatory" => "integer", + "OrderNr" => "integer", + "Dir" => "directory"); + + case "4.4.0": + return array( + "Id" => "integer", + "ExerciseId" => "integer", + "Type" => "integer", + "Deadline" => "integer", + "Instruction" => "text", + "Title" => "text", + "Mandatory" => "integer", + "OrderNr" => "integer", + "Dir" => "directory" + // peer + ,"Peer" => "integer" + ,"PeerMin" => "integer" + ,"PeerDeadline" => "integer" + // global feedback + ,"FeedbackFile" => "integer" + ,"FeedbackCron" => "integer" + ,"FeedbackDate" => "integer" + ,"FeedbackDir" => "directory" + ); + + case "5.0.0": + return array( + "Id" => "integer", + "ExerciseId" => "integer", + "Type" => "integer", + "Deadline" => "integer", + "Instruction" => "text", + "Title" => "text", + "Mandatory" => "integer", + "OrderNr" => "integer", + "Dir" => "directory" + // peer + ,"Peer" => "integer" + ,"PeerMin" => "integer" + ,"PeerDeadline" => "integer" + ,"PeerFile" => "integer" + ,"PeerPersonal" => "integer" + // global feedback + ,"FeedbackFile" => "integer" + ,"FeedbackCron" => "integer" + ,"FeedbackDate" => "integer" + ,"FeedbackDir" => "directory" + ); + + case "5.1.0": + case "5.2.0": + return array( + "Id" => "integer", + "ExerciseId" => "integer", + "Type" => "integer", + "Deadline" => "integer", + "Deadline2" => "integer", + "Instruction" => "text", + "Title" => "text", + "Mandatory" => "integer", + "OrderNr" => "integer", + "TeamTutor" => "integer", + "MaxFile" => "integer", + "Dir" => "directory" + // peer + ,"Peer" => "integer" + ,"PeerMin" => "integer" + ,"PeerDeadline" => "integer" + ,"PeerFile" => "integer" + ,"PeerPersonal" => "integer" + ,"PeerChar" => "integer" + ,"PeerUnlock" => "integer" + ,"PeerValid" => "integer" + ,"PeerText" => "integer" + ,"PeerRating" => "integer" + ,"PeerCritCat" => "integer" + // global feedback + ,"FeedbackFile" => "integer" + ,"FeedbackCron" => "integer" + ,"FeedbackDate" => "integer" + ,"FeedbackDir" => "directory" + ); + case "5.3.0": + return array( + "Id" => "integer", + "ExerciseId" => "integer", + "Type" => "integer", + "Deadline" => "integer", + "Deadline2" => "integer", + "Instruction" => "text", + "Title" => "text", + "Mandatory" => "integer", + "OrderNr" => "integer", + "TeamTutor" => "integer", + "MaxFile" => "integer", + "Dir" => "directory", + //web data directory + "WebDataDir" => "directory" + // peer + ,"Peer" => "integer" + ,"PeerMin" => "integer" + ,"PeerDeadline" => "integer" + ,"PeerFile" => "integer" + ,"PeerPersonal" => "integer" + ,"PeerChar" => "integer" + ,"PeerUnlock" => "integer" + ,"PeerValid" => "integer" + ,"PeerText" => "integer" + ,"PeerRating" => "integer" + ,"PeerCritCat" => "integer" + // global feedback + ,"FeedbackFile" => "integer" + ,"FeedbackCron" => "integer" + ,"FeedbackDate" => "integer" + ,"FeedbackDir" => "directory" + ,"FbDateCustom" => "integer" + ); + } + } + + if ($a_entity == "exc_cit_cat") { + switch ($a_version) { + case "5.1.0": + case "5.2.0": + case "5.3.0": + return array( + "Id" => "integer" + ,"Parent" => "integer" + ,"Title" => "text" + ,"Pos" => "integer" + ); + } + } + + if ($a_entity == "exc_cit") { + switch ($a_version) { + case "5.1.0": + case "5.2.0": + case "5.3.0": + return array( + "Id" => "integer" + ,"Parent" => "integer" + ,"Type" => "text" + ,"Title" => "text" + ,"Descr" => "text" + ,"Pos" => "integer" + ,"Required" => "integer" + ,"Def" => "text" + ,"DefJson" => "text" + ); + } + } + + if ($a_entity == "exc_ass_file_order") { + switch ($a_version) { + case "5.3.0": + return array( + "Id" => "integer" + , "AssignmentId" => "integer" + , "Filename" => "text" + , "OrderNr" => "integer" + ); + } + } + + if ($a_entity == "exc_ass_reminders") { + switch ($a_version) { + case "5.3.0": + return array( + "Type" => "text", + "AssignmentId" => "integer", + "ExerciseId" => "integer", + "Status" => "integer", + "Start" => "integer", + "End" => "integer", + "Frequency" => "integer", + "LastSend" => "integer", + "TemplateId" => "integer" + ); + } + } + return false; + } + + /** + * 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 == "exc") { + switch ($a_version) { + case "4.1.0": + $this->getDirectDataFromQuery("SELECT exc_data.obj_id id, title, description," . + " pass_mode, pass_nr, show_submissions" . + " FROM exc_data JOIN object_data ON (exc_data.obj_id = object_data.obj_id)" . + " WHERE " . $ilDB->in("exc_data.obj_id", $a_ids, false, "integer")); + break; + + case "4.4.0": + case "5.0.0": + case "5.1.0": + $this->getDirectDataFromQuery("SELECT exc_data.obj_id id, title, description," . + " pass_mode, pass_nr, show_submissions, compl_by_submission" . + " FROM exc_data JOIN object_data ON (exc_data.obj_id = object_data.obj_id)" . + " WHERE " . $ilDB->in("exc_data.obj_id", $a_ids, false, "integer")); + break; + + case "5.2.0": + case "5.3.0": + $this->getDirectDataFromQuery("SELECT exc_data.obj_id id, title, description," . + " pass_mode, pass_nr, show_submissions, compl_by_submission, tfeedback" . + " FROM exc_data JOIN object_data ON (exc_data.obj_id = object_data.obj_id)" . + " WHERE " . $ilDB->in("exc_data.obj_id", $a_ids, false, "integer")); + break; + } + } + + if ($a_entity == "exc_assignment") { + switch ($a_version) { + case "4.1.0": + $this->getDirectDataFromQuery("SELECT id, exc_id exercise_id, time_stamp deadline, " . + " instruction, title, start_time, mandatory, order_nr" . + " FROM exc_assignment" . + " WHERE " . $ilDB->in("exc_id", $a_ids, false, "integer")); + break; + + case "4.4.0": + $this->getDirectDataFromQuery("SELECT id, exc_id exercise_id, type, time_stamp deadline," . + " instruction, title, start_time, mandatory, order_nr, peer, peer_min, peer_dl peer_deadline," . + " fb_file feedback_file, fb_cron feedback_cron, fb_date feedback_date" . + " FROM exc_assignment" . + " WHERE " . $ilDB->in("exc_id", $a_ids, false, "integer")); + break; + + case "5.0.0": + $this->getDirectDataFromQuery("SELECT id, exc_id exercise_id, type, time_stamp deadline," . + " instruction, title, start_time, mandatory, order_nr, peer, peer_min, peer_dl peer_deadline," . + " peer_file, peer_prsl peer_personal, fb_file feedback_file, fb_cron feedback_cron, fb_date feedback_date" . + " FROM exc_assignment" . + " WHERE " . $ilDB->in("exc_id", $a_ids, false, "integer")); + break; + + case "5.1.0": + case "5.2.0": + case "5.3.0": + $this->getDirectDataFromQuery("SELECT id, exc_id exercise_id, type, time_stamp deadline, deadline2," . + " instruction, title, start_time, mandatory, order_nr, team_tutor, max_file, peer, peer_min," . + " peer_dl peer_deadline, peer_file, peer_prsl peer_personal, peer_char, peer_unlock, peer_valid," . + " peer_text, peer_rating, peer_crit_cat, fb_file feedback_file, fb_cron feedback_cron, fb_date feedback_date," . + " fb_date_custom" . + " FROM exc_assignment" . + " WHERE " . $ilDB->in("exc_id", $a_ids, false, "integer")); + break; + } + } + + if ($a_entity == "exc_crit_cat") { + switch ($a_version) { + case "5.1.0": + case "5.2.0": + case "5.3.0": + $this->getDirectDataFromQuery("SELECT id, parent, title, pos" . + " FROM exc_crit_cat" . + " WHERE " . $ilDB->in("parent", $a_ids, false, "integer")); + break; + } + } + + if ($a_entity == "exc_crit") { + switch ($a_version) { + case "5.1.0": + case "5.2.0": + case "5.3.0": + $this->getDirectDataFromQuery("SELECT id, parent, type, title" . + ", descr, pos, required, def" . + " FROM exc_crit" . + " WHERE " . $ilDB->in("parent", $a_ids, false, "integer")); + foreach ($this->data as $k => $v) { + $this->data[$k]["DefJson"] = ""; + if ($v["Def"] != "") { + $this->data[$k]["DefJson"] = json_encode(unserialize($v["Def"])); + } + } + break; + } + } + + if ($a_entity == "exc_ass_file_order") { + switch ($a_version) { + case "5.3.0": + $this->getDirectDataFromQuery("SELECT id, assignment_id, filename, order_nr" . + " FROM exc_ass_file_order" . + " WHERE " . $ilDB->in("assignment_id", $a_ids, false, "integer")); + break; + } + } + + if ($a_entity == "exc_ass_reminders") { + switch ($a_version) { + case "5.3.0": + $this->getDirectDataFromQuery("SELECT type, ass_id, exc_id, status, start, end, freq, last_send, template_id" . + " FROM exc_ass_reminders" . + " WHERE " . $ilDB->in("ass_id", $a_ids, false, "integer")); + break; + } + } + } + + /** + * Get xml record (export) + * + * @param array abstract data record + * @return array xml record + */ + public function getXmlRecord($a_entity, $a_version, $a_set) + { + if ($a_entity == "exc_assignment") { + // convert server dates to utc + if ($a_set["StartTime"] != "") { + $start = new ilDateTime($a_set["StartTime"], IL_CAL_UNIX); + $a_set["StartTime"] = $start->get(IL_CAL_DATETIME, '', 'UTC'); + } + if ($a_set["Deadline"] != "") { + $deadline = new ilDateTime($a_set["Deadline"], IL_CAL_UNIX); + $a_set["Deadline"] = $deadline->get(IL_CAL_DATETIME, '', 'UTC'); + } + if ($a_set["Deadline2"] != "") { + $deadline = new ilDateTime($a_set["Deadline2"], IL_CAL_UNIX); + $a_set["Deadline2"] = $deadline->get(IL_CAL_DATETIME, '', 'UTC'); + } + + include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); + $fstorage = new ilFSStorageExercise($a_set["ExerciseId"], $a_set["Id"]); + $a_set["Dir"] = $fstorage->getPath(); + + include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); + $fstorage = new ilFSStorageExercise($a_set["ExerciseId"], $a_set["Id"]); + $a_set["FeedbackDir"] = $fstorage->getGlobalFeedbackPath(); + + //now the instruction files inside the root directory + include_once("./Modules/Exercise/classes/class.ilFSWebStorageExercise.php"); + $fswebstorage = new ilFSWebStorageExercise($a_set['ExerciseId'], $a_set['Id']); + $a_set['WebDataDir'] = $fswebstorage->getPath(); + } + + //Discuss if necessary when working with timestamps. + if ($a_entity == "exc_ass_reminders") { + if ($a_set["End"] != "") { + $end = new ilDateTime($a_set["End"], IL_CAL_UNIX); + $a_set["End"] = $end->get(IL_CAL_DATETIME, '', 'UTC'); + } + if ($a_set["LastSend"] != "") { + $last = new ilDateTime($a_set["LastSend"], IL_CAL_UNIX); + $a_set["LastSend"] = $last->get(IL_CAL_DATETIME, '', 'UTC'); + } + } + + return $a_set; + } + + + /** + * Determine the dependent sets of data + */ + protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) + { + switch ($a_entity) { + case "exc": + switch ($a_version) { + case "4.1.0": + case "4.4.0": + case "5.0.0": + return array( + "exc_assignment" => array("ids" => $a_rec["Id"]) + ); + + case "5.1.0": + case "5.2.0": + case "5.3.0": + return array( + "exc_crit_cat" => array("ids" => $a_rec["Id"]), + "exc_assignment" => array("ids" => $a_rec["Id"]) + ); + } + break; + + case "exc_crit_cat": + return array( + "exc_crit" => array("ids" => $a_rec["Id"]) + ); + + case "exc_assignment": + switch ($a_version) { + case "5.3.0": + return array( + "exc_ass_file_order" => array("ids" => $a_rec["Id"]), + "exc_ass_reminders" => array("ids" => $a_rec["Id"]) + ); + + } + break; + } + return false; + } + + + /** + * Import record + * + * @param + * @return + */ + public function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) + { + //echo $a_entity; + //var_dump($a_rec); + + switch ($a_entity) { + case "exc": + include_once("./Modules/Exercise/classes/class.ilObjExercise.php"); + + if ($new_id = $a_mapping->getMapping('Services/Container', 'objs', $a_rec['Id'])) { + $newObj = ilObjectFactory::getInstanceByObjId($new_id, false); + } else { + $newObj = new ilObjExercise(); + $newObj->setType("exc"); + $newObj->create(true); + } + + $newObj->setTitle($a_rec["Title"]); + $newObj->setDescription($a_rec["Description"]); + $newObj->setPassMode($a_rec["PassMode"]); + $newObj->setPassNr($a_rec["PassNr"]); + $newObj->setShowSubmissions($a_rec["ShowSubmissions"]); + $newObj->setCompletionBySubmission($a_rec["ComplBySubmission"]); + $newObj->setTutorFeedback($a_rec["Tfeedback"]); + $newObj->update(); + $newObj->saveData(); + $this->current_exc = $newObj; + + $a_mapping->addMapping("Modules/Exercise", "exc", $a_rec["Id"], $newObj->getId()); + break; + + case "exc_assignment": + $exc_id = $a_mapping->getMapping("Modules/Exercise", "exc", $a_rec["ExerciseId"]); + if ($exc_id > 0) { + if (is_object($this->current_exc) && $this->current_exc->getId() == $exc_id) { + $exc = $this->current_exc; + } else { + include_once("./Modules/Exercise/classes/class.ilObjExercise.php"); + $exc = new ilObjExercise($exc_id, false); + } + + include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); + + $ass = new ilExAssignment(); + $ass->setExerciseId($exc_id); + + if ($a_rec["StartTime"] != "") { + $start = new ilDateTime($a_rec["StartTime"], IL_CAL_DATETIME, "UTC"); + $ass->setStartTime($start->get(IL_CAL_UNIX)); + } + + if ($a_rec["Deadline"] != "") { + $deadline = new ilDateTime($a_rec["Deadline"], IL_CAL_DATETIME, "UTC"); + $ass->setDeadline($deadline->get(IL_CAL_UNIX)); + } + + $ass->setInstruction($a_rec["Instruction"]); + $ass->setTitle($a_rec["Title"]); + $ass->setMandatory($a_rec["Mandatory"]); + $ass->setOrderNr($a_rec["OrderNr"]); + + // 4.2 + $ass->setType($a_rec["Type"]); + + // 4.4 + $ass->setPeerReview($a_rec["Peer"]); + $ass->setPeerReviewMin($a_rec["PeerMin"]); + $ass->setPeerReviewDeadline($a_rec["PeerDeadline"]); + $ass->setFeedbackFile($a_rec["FeedbackFile"]); + $ass->setFeedbackCron($a_rec["FeedbackCron"]); + $ass->setFeedbackDate($a_rec["FeedbackDate"]); + + // 5.0 + $ass->setPeerReviewFileUpload($a_rec["PeerFile"]); + $ass->setPeerReviewPersonalized($a_rec["PeerPersonal"]); + + // 5.1 + if ($a_rec["Deadline2"] != "") { + $deadline = new ilDateTime($a_rec["Deadline2"], IL_CAL_DATETIME, "UTC"); + $ass->setExtendedDeadline($deadline->get(IL_CAL_UNIX)); + } + $ass->setMaxFile($a_rec["MaxFile"]); + $ass->setTeamTutor($a_rec["TeamTutor"]); + $ass->setPeerReviewChars($a_rec["PeerChar"]); + $ass->setPeerReviewSimpleUnlock($a_rec["PeerUnlock"]); + $ass->setPeerReviewValid($a_rec["PeerValid"]); + $ass->setPeerReviewText($a_rec["PeerText"]); + $ass->setPeerReviewRating($a_rec["PeerRating"]); + + // 5.3 + $ass->setFeedbackDateCustom($a_rec["FbDateCustom"]); + + // criteria catalogue + if ($a_rec["PeerCritCat"]) { + $ass->setPeerReviewCriteriaCatalogue($a_mapping->getMapping("Modules/Exercise", "exc_crit_cat", $a_rec["PeerCritCat"])); + } + + $ass->save(); + + include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); + $fstorage = new ilFSStorageExercise($exc_id, $ass->getId()); + $fstorage->create(); + + // assignment files + $dir = str_replace("..", "", $a_rec["Dir"]); + if ($dir != "" && $this->getImportDirectory() != "") { + $source_dir = $this->getImportDirectory() . "/" . $dir; + $target_dir = $fstorage->getPath(); + ilUtil::rCopy($source_dir, $target_dir); + } + + // (4.4) global feedback file + $dir = str_replace("..", "", $a_rec["FeedbackDir"]); + if ($dir != "" && $this->getImportDirectory() != "") { + $source_dir = $this->getImportDirectory() . "/" . $dir; + $target_dir = $fstorage->getGlobalFeedbackPath(); + ilUtil::rCopy($source_dir, $target_dir); + } + + // (5.3) assignment files inside ILIAS + include_once("./Modules/Exercise/classes/class.ilFSWebStorageExercise.php"); + $fwebstorage = new ilFSWebStorageExercise($exc_id, $ass->getId()); + $fwebstorage->create(); + $dir = str_replace("..", "", $a_rec["WebDataDir"]); + if ($dir != "" && $this->getImportDirectory() != "") { + $source_dir = $this->getImportDirectory() . "/" . $dir; + $target_dir = $fwebstorage->getPath(); + ilUtil::rCopy($source_dir, $target_dir); + } + + $a_mapping->addMapping("Modules/Exercise", "exc_assignment", $a_rec["Id"], $ass->getId()); + } + + break; + + case "exc_crit_cat": + $exc_id = $a_mapping->getMapping("Modules/Exercise", "exc", $a_rec["Parent"]); + if ($exc_id > 0) { + include_once("./Modules/Exercise/classes/class.ilExcCriteriaCatalogue.php"); + $crit_cat = new ilExcCriteriaCatalogue(); + $crit_cat->setParent($exc_id); + $crit_cat->setTitle($a_rec["Title"]); + $crit_cat->setPosition($a_rec["Pos"]); + $crit_cat->save(); + + $a_mapping->addMapping("Modules/Exercise", "exc_crit_cat", $a_rec["Id"], $crit_cat->getId()); + } + break; + + case "exc_crit": + $crit_cat_id = $a_mapping->getMapping("Modules/Exercise", "exc_crit_cat", $a_rec["Parent"]); + if ($crit_cat_id > 0) { + include_once("./Modules/Exercise/classes/class.ilExcCriteria.php"); + $crit = ilExcCriteria::getInstanceByType($a_rec["Type"]); + $crit->setParent($crit_cat_id); + $crit->setTitle($a_rec["Title"]); + $crit->setDescription($a_rec["Descr"]); + $crit->setPosition($a_rec["Pos"]); + $crit->setRequired($a_rec["Required"]); + $crit->importDefinition($a_rec["Def"], $a_rec["DefJson"]); + $crit->save(); + } + break; + + case "exc_ass_file_order": + + $ass_id = $a_mapping->getMapping("Modules/Exercise", "exc_assignment", $a_rec["AssignmentId"]); + if ($ass_id > 0) { + ilExAssignment::instructionFileInsertOrder($a_rec["Filename"], $ass_id, $a_rec["OrderNr"]); + } + break; + + case "exc_ass_reminders": + // (5.3) reminders + include_once("./Modules/Exercise/classes/class.ilExAssignmentReminder.php"); + $new_ass_id = $a_mapping->getMapping("Modules/Exercise", "exc_assignment", $a_rec["AssId"]); + $new_exc_id = $a_mapping->getMapping('Modules/Exercise', 'exc', $a_rec['ExcId']); + //always UTC timestamp in db. + $end = new ilDateTime($a_rec["End"], IL_CAL_DATETIME, "UTC"); + $rmd = new ilExAssignmentReminder($new_exc_id, $new_ass_id, $a_rec["Type"]); + $rmd->setReminderStatus($a_rec["Status"]); + $rmd->setReminderStart($a_rec["Start"]); + $rmd->setReminderEnd($end->get(IL_CAL_UNIX)); + $rmd->setReminderFrequency($a_rec["Freq"]); + $rmd->setReminderLastSend($a_rec["LastSend"]); + $rmd->setReminderMailTemplate($a_rec["TemplateId"]); + $rmd->save(); + } + } } -?> \ No newline at end of file diff --git a/Modules/Exercise/classes/class.ilExerciseExporter.php b/Modules/Exercise/classes/class.ilExerciseExporter.php index 570ad3491124fb6092a9b91d428007fa135452da..75bda493bab9a9b441637f49bcf7e5a4c87a3b35 100644 --- a/Modules/Exercise/classes/class.ilExerciseExporter.php +++ b/Modules/Exercise/classes/class.ilExerciseExporter.php @@ -12,32 +12,32 @@ include_once("./Services/Export/classes/class.ilXmlExporter.php"); */ class ilExerciseExporter extends ilXmlExporter { - private $ds; + private $ds; - /** - * Initialisation - */ - function init() - { - include_once("./Modules/Exercise/classes/class.ilExerciseDataSet.php"); - $this->ds = new ilExerciseDataSet(); - $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); - $this->ds->setDSPrefix("ds"); - } + /** + * Initialisation + */ + public function init() + { + include_once("./Modules/Exercise/classes/class.ilExerciseDataSet.php"); + $this->ds = new ilExerciseDataSet(); + $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); + $this->ds->setDSPrefix("ds"); + } - /** - * Get xml representation - * - * @param string entity - * @param string target release - * @param string id - * @return string xml string - */ - 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); - } + /** + * Get xml representation + * + * @param string entity + * @param string target release + * @param string id + * @return string xml string + */ + 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 getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) { @@ -56,54 +56,51 @@ class ilExerciseExporter extends ilXmlExporter } /** - * Returns schema versions that the component can export to. - * ILIAS chooses the first one, that has min/max constraints which - * fit to the target release. Please put the newest on top. - * - * @return - */ - function getValidSchemaVersions($a_entity) - { - return array ( - "4.1.0" => array( - "namespace" => "http://www.ilias.de/Modules/Exercise/exc/4_1", - "xsd_file" => "ilias_exc_4_1.xsd", - "uses_dataset" => true, - "min" => "4.1.0", - "max" => "4.3.99"), - "4.4.0" => array( - "namespace" => "http://www.ilias.de/Modules/Exercise/exc/4_4", - "xsd_file" => "ilias_exc_4_4.xsd", - "uses_dataset" => true, - "min" => "4.4.0", - "max" => "4.4.99"), - "5.0.0" => array( - "namespace" => "http://www.ilias.de/Modules/Exercise/exc/5_0", - "xsd_file" => "ilias_exc_5_0.xsd", - "uses_dataset" => true, - "min" => "5.0.0", - "max" => "5.0.99"), - "5.1.0" => array( - "namespace" => "http://www.ilias.de/Modules/Exercise/exc/5_1", - "xsd_file" => "ilias_exc_5_1.xsd", - "uses_dataset" => true, - "min" => "5.1.0", - "max" => "5.1.99"), - "5.2.0" => array( - "namespace" => "http://www.ilias.de/Modules/Exercise/exc/5_2", - "xsd_file" => "ilias_exc_5_2.xsd", - "uses_dataset" => true, - "min" => "5.2.0", - "max" => "5.2.99"), - "5.3.0" => array( - "namespace" => "http://www.ilias.de/Modules/Exercise/exc/5_3", - "xsd_file" => "ilias_exc_5_3.xsd", - "uses_dataset" => true, - "min" => "5.3.0", - "max" => "") - ); - } - + * Returns schema versions that the component can export to. + * ILIAS chooses the first one, that has min/max constraints which + * fit to the target release. Please put the newest on top. + * + * @return + */ + public function getValidSchemaVersions($a_entity) + { + return array( + "4.1.0" => array( + "namespace" => "http://www.ilias.de/Modules/Exercise/exc/4_1", + "xsd_file" => "ilias_exc_4_1.xsd", + "uses_dataset" => true, + "min" => "4.1.0", + "max" => "4.3.99"), + "4.4.0" => array( + "namespace" => "http://www.ilias.de/Modules/Exercise/exc/4_4", + "xsd_file" => "ilias_exc_4_4.xsd", + "uses_dataset" => true, + "min" => "4.4.0", + "max" => "4.4.99"), + "5.0.0" => array( + "namespace" => "http://www.ilias.de/Modules/Exercise/exc/5_0", + "xsd_file" => "ilias_exc_5_0.xsd", + "uses_dataset" => true, + "min" => "5.0.0", + "max" => "5.0.99"), + "5.1.0" => array( + "namespace" => "http://www.ilias.de/Modules/Exercise/exc/5_1", + "xsd_file" => "ilias_exc_5_1.xsd", + "uses_dataset" => true, + "min" => "5.1.0", + "max" => "5.1.99"), + "5.2.0" => array( + "namespace" => "http://www.ilias.de/Modules/Exercise/exc/5_2", + "xsd_file" => "ilias_exc_5_2.xsd", + "uses_dataset" => true, + "min" => "5.2.0", + "max" => "5.2.99"), + "5.3.0" => array( + "namespace" => "http://www.ilias.de/Modules/Exercise/exc/5_3", + "xsd_file" => "ilias_exc_5_3.xsd", + "uses_dataset" => true, + "min" => "5.3.0", + "max" => "") + ); + } } - -?> \ No newline at end of file diff --git a/Modules/Exercise/classes/class.ilExerciseHandlerGUI.php b/Modules/Exercise/classes/class.ilExerciseHandlerGUI.php index 9476b7110eb819bfe5418bcffdbbed7ea574199f..c39ecb5c99c725c495b40b64378e58e516b03396 100644 --- a/Modules/Exercise/classes/class.ilExerciseHandlerGUI.php +++ b/Modules/Exercise/classes/class.ilExerciseHandlerGUI.php @@ -13,85 +13,82 @@ */ class ilExerciseHandlerGUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilTemplate + */ + protected $tpl; - /** - * @var ilNavigationHistory - */ - protected $nav_history; + /** + * @var ilNavigationHistory + */ + protected $nav_history; - function __construct() - { - global $DIC; + public function __construct() + { + global $DIC; - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $this->tpl = $DIC["tpl"]; - $this->nav_history = $DIC["ilNavigationHistory"]; - $ilCtrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->tpl = $DIC["tpl"]; + $this->nav_history = $DIC["ilNavigationHistory"]; + $ilCtrl = $DIC->ctrl(); - // initialisation stuff - $this->ctrl = $ilCtrl; - - //$ilNavigationHistory->addItem($_GET["ref_id"], - // "ilias.php?baseClass=ilGlossaryEditorGUI&ref_id=".$_GET["ref_id"]); + // initialisation stuff + $this->ctrl = $ilCtrl; + + //$ilNavigationHistory->addItem($_GET["ref_id"], + // "ilias.php?baseClass=ilGlossaryEditorGUI&ref_id=".$_GET["ref_id"]); + } + + /** + * execute command + */ + public function executeCommand() + { + $lng = $this->lng; + $ilAccess = $this->access; + $tpl = $this->tpl; + $ilNavigationHistory = $this->nav_history; + + $cmd = $this->ctrl->getCmd(); + $next_class = $this->ctrl->getNextClass($this); + if ($next_class == "") { + $this->ctrl->setCmdClass("ilobjexercisegui"); + $next_class = $this->ctrl->getNextClass($this); + } - } - - /** - * execute command - */ - function executeCommand() - { - $lng = $this->lng; - $ilAccess = $this->access; - $tpl = $this->tpl; - $ilNavigationHistory = $this->nav_history; - - $cmd = $this->ctrl->getCmd(); - $next_class = $this->ctrl->getNextClass($this); - if ($next_class == "") - { - $this->ctrl->setCmdClass("ilobjexercisegui"); - $next_class = $this->ctrl->getNextClass($this); - } + // add entry to navigation history + if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) { + $ilNavigationHistory->addItem( + $_GET["ref_id"], + "ilias.php?baseClass=ilExerciseHandlerGUI&cmd=showOverview&ref_id=" . $_GET["ref_id"], + "exc" + ); + } - // add entry to navigation history - if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - $ilNavigationHistory->addItem($_GET["ref_id"], - "ilias.php?baseClass=ilExerciseHandlerGUI&cmd=showOverview&ref_id=".$_GET["ref_id"], "exc"); - } - - switch ($next_class) - { - case 'ilobjexercisegui': - require_once "./Modules/Exercise/classes/class.ilObjExerciseGUI.php"; - $ex_gui = new ilObjExerciseGUI("", (int) $_GET["ref_id"], true, false); - $this->ctrl->forwardCommand($ex_gui); - break; - } - - $tpl->show(); - } + switch ($next_class) { + case 'ilobjexercisegui': + require_once "./Modules/Exercise/classes/class.ilObjExerciseGUI.php"; + $ex_gui = new ilObjExerciseGUI("", (int) $_GET["ref_id"], true, false); + $this->ctrl->forwardCommand($ex_gui); + break; + } + $tpl->show(); + } } -?> \ No newline at end of file diff --git a/Modules/Exercise/classes/class.ilExerciseImporter.php b/Modules/Exercise/classes/class.ilExerciseImporter.php index c90db406b947ecd5b33529f246c0c6b88371b1ea..14cdcc64ce49afd456fc4ca99877c187dfa8c603 100644 --- a/Modules/Exercise/classes/class.ilExerciseImporter.php +++ b/Modules/Exercise/classes/class.ilExerciseImporter.php @@ -13,29 +13,32 @@ include_once("./Services/Export/classes/class.ilXmlImporter.php"); class ilExerciseImporter extends ilXmlImporter { - /** - * Initialisation - */ - function init() - { - include_once("./Modules/Exercise/classes/class.ilExerciseDataSet.php"); - $this->ds = new ilExerciseDataSet(); - $this->ds->setDSPrefix("ds"); - $this->ds->setImportDirectory($this->getImportDirectory()); - } + /** + * Initialisation + */ + public function init() + { + include_once("./Modules/Exercise/classes/class.ilExerciseDataSet.php"); + $this->ds = new ilExerciseDataSet(); + $this->ds->setDSPrefix("ds"); + $this->ds->setImportDirectory($this->getImportDirectory()); + } - /** - * Import XML - * - * @param - * @return - */ - function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) - { - include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); - $parser = new ilDataSetImportParser($a_entity, $this->getSchemaVersion(), - $a_xml, $this->ds, $a_mapping); - } + /** + * Import XML + * + * @param + * @return + */ + public function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) + { + include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); + $parser = new ilDataSetImportParser( + $a_entity, + $this->getSchemaVersion(), + $a_xml, + $this->ds, + $a_mapping + ); + } } - -?> \ No newline at end of file diff --git a/Modules/Exercise/classes/class.ilExerciseLP.php b/Modules/Exercise/classes/class.ilExerciseLP.php index de5a323f88b7c1e55538e6df3c05d4979eafbeb8..34cd80a4d026613e2e8e62c783b88b327870eefa 100644 --- a/Modules/Exercise/classes/class.ilExerciseLP.php +++ b/Modules/Exercise/classes/class.ilExerciseLP.php @@ -1,56 +1,53 @@ - - * @version $Id: class.ilLPStatusPlugin.php 43734 2013-07-29 15:27:58Z jluetzen $ - * @package ModulesExercise - */ -class ilExerciseLP extends ilObjectLP -{ - public static function getDefaultModes($a_lp_active) - { - return array( - ilLPObjSettings::LP_MODE_DEACTIVATED, - ilLPObjSettings::LP_MODE_EXERCISE_RETURNED - ); - } - - public function getDefaultMode() - { - return ilLPObjSettings::LP_MODE_EXERCISE_RETURNED; - } - - public function getValidModes() - { - return array( - ilLPObjSettings::LP_MODE_DEACTIVATED, - ilLPObjSettings::LP_MODE_EXERCISE_RETURNED - ); - } - - protected static function isLPMember(array &$a_res, $a_usr_id, $a_obj_ids) - { - global $DIC; +database(); - - $set = $ilDB->query("SELECT obj_id". - " FROM exc_members". - " WHERE ".$ilDB->in("obj_id", $a_obj_ids, "", "integer"). - " AND usr_id = ".$ilDB->quote($a_usr_id, "integer")); - while($row = $ilDB->fetchAssoc($set)) - { - $a_res[$row["obj_id"]] = true; - } - - return true; - } -} - -?> \ No newline at end of file +/* Copyright (c) 1998-2009 ILIAS open source, Extended GPL, see docs/LICENSE */ + +include_once "Services/Object/classes/class.ilObjectLP.php"; + +/** + * Exercise to lp connector + * + * @author Jörg Lützenkirchen + * @version $Id: class.ilLPStatusPlugin.php 43734 2013-07-29 15:27:58Z jluetzen $ + * @package ModulesExercise + */ +class ilExerciseLP extends ilObjectLP +{ + public static function getDefaultModes($a_lp_active) + { + return array( + ilLPObjSettings::LP_MODE_DEACTIVATED, + ilLPObjSettings::LP_MODE_EXERCISE_RETURNED + ); + } + + public function getDefaultMode() + { + return ilLPObjSettings::LP_MODE_EXERCISE_RETURNED; + } + + public function getValidModes() + { + return array( + ilLPObjSettings::LP_MODE_DEACTIVATED, + ilLPObjSettings::LP_MODE_EXERCISE_RETURNED + ); + } + + protected static function isLPMember(array &$a_res, $a_usr_id, $a_obj_ids) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query("SELECT obj_id" . + " FROM exc_members" . + " WHERE " . $ilDB->in("obj_id", $a_obj_ids, "", "integer") . + " AND usr_id = " . $ilDB->quote($a_usr_id, "integer")); + while ($row = $ilDB->fetchAssoc($set)) { + $a_res[$row["obj_id"]] = true; + } + + return true; + } +} diff --git a/Modules/Exercise/classes/class.ilExerciseMailNotification.php b/Modules/Exercise/classes/class.ilExerciseMailNotification.php index e9aaf443c15c96b7f27b0e9c10b7361fada1ed1e..78d266d9ac309319444b0359068201eeba87a732 100644 --- a/Modules/Exercise/classes/class.ilExerciseMailNotification.php +++ b/Modules/Exercise/classes/class.ilExerciseMailNotification.php @@ -6,197 +6,212 @@ include_once './Services/Mail/classes/class.ilMailNotification.php'; /** * @author Alex Killing * @version $Id$ - * + * * @ingroup ModulesExercise */ class ilExerciseMailNotification extends ilMailNotification { - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - const TYPE_FEEDBACK_FILE_ADDED = 20; - const TYPE_SUBMISSION_UPLOAD = 30; - const TYPE_FEEDBACK_TEXT_ADDED = 40; + const TYPE_FEEDBACK_FILE_ADDED = 20; + const TYPE_SUBMISSION_UPLOAD = 30; + const TYPE_FEEDBACK_TEXT_ADDED = 40; - /** - * - */ - public function __construct() - { - global $DIC; + /** + * + */ + public function __construct() + { + global $DIC; - $this->user = $DIC->user(); - parent::__construct(); - } - - /** - * Set assignment id - * - * @param int assignment id - */ - function setAssignmentId($a_val) - { - $this->ass_id = $a_val; - } - - /** - * Get assignment id - * - * @return int assignment id - */ - function getAssignmentId() - { - return $this->ass_id; - } - - /** - * Send notifications - * @return - */ - public function send() - { - $ilUser = $this->user; - // parent::send(); - - include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); - - switch($this->getType()) - { - case self::TYPE_FEEDBACK_FILE_ADDED: - - foreach($this->getRecipients() as $rcp) - { - $this->initLanguage($rcp); - $this->initMail(); - $this->setSubject( - sprintf($this->getLanguageText('exc_msg_new_feedback_file_uploaded'), - $this->getObjectTitle(true)) - ); - $this->setBody(ilMail::getSalutation($rcp,$this->getLanguage())); - $this->appendBody("\n\n"); - $this->appendBody( - $this->getLanguageText('exc_msg_new_feedback_file_uploaded2')); - $this->appendBody("\n"); - $this->appendBody( - $this->getLanguageText('obj_exc').": ".$this->getObjectTitle(true)); - $this->appendBody("\n"); - $this->appendBody( - $this->getLanguageText('exc_assignment').": ". - ilExAssignment::lookupTitle($this->getAssignmentId())); - $this->appendBody("\n\n"); - $this->appendBody($this->getLanguageText('exc_mail_permanent_link')); - $this->appendBody("\n"); - $this->appendBody($this->createPermanentLink(array(), '_'.$this->getAssignmentId()). - '#fb'.$this->getAssignmentId()); - $this->getMail()->appendInstallationSignature(true); - - $this->sendMail(array($rcp),array('system')); - } - break; + $this->user = $DIC->user(); + parent::__construct(); + } + + /** + * Set assignment id + * + * @param int assignment id + */ + public function setAssignmentId($a_val) + { + $this->ass_id = $a_val; + } + + /** + * Get assignment id + * + * @return int assignment id + */ + public function getAssignmentId() + { + return $this->ass_id; + } + + /** + * Send notifications + * @return + */ + public function send() + { + $ilUser = $this->user; + // parent::send(); + + include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); + + switch ($this->getType()) { + case self::TYPE_FEEDBACK_FILE_ADDED: + + foreach ($this->getRecipients() as $rcp) { + $this->initLanguage($rcp); + $this->initMail(); + $this->setSubject( + sprintf( + $this->getLanguageText('exc_msg_new_feedback_file_uploaded'), + $this->getObjectTitle(true) + ) + ); + $this->setBody(ilMail::getSalutation($rcp, $this->getLanguage())); + $this->appendBody("\n\n"); + $this->appendBody( + $this->getLanguageText('exc_msg_new_feedback_file_uploaded2') + ); + $this->appendBody("\n"); + $this->appendBody( + $this->getLanguageText('obj_exc') . ": " . $this->getObjectTitle(true) + ); + $this->appendBody("\n"); + $this->appendBody( + $this->getLanguageText('exc_assignment') . ": " . + ilExAssignment::lookupTitle($this->getAssignmentId()) + ); + $this->appendBody("\n\n"); + $this->appendBody($this->getLanguageText('exc_mail_permanent_link')); + $this->appendBody("\n"); + $this->appendBody($this->createPermanentLink(array(), '_' . $this->getAssignmentId()) . + '#fb' . $this->getAssignmentId()); + $this->getMail()->appendInstallationSignature(true); + + $this->sendMail(array($rcp), array('system')); + } + break; - case self::TYPE_SUBMISSION_UPLOAD: + case self::TYPE_SUBMISSION_UPLOAD: - foreach($this->getRecipients() as $rcp) - { - $this->initLanguage($rcp); - $this->initMail(); - $this->setSubject( - sprintf($this->getLanguageText('exc_submission_notification_subject'), - $this->getObjectTitle(true)) - ); - $this->setBody(ilMail::getSalutation($rcp,$this->getLanguage())); - $this->appendBody("\n\n"); - $this->appendBody( - sprintf($this->getLanguageText('exc_submission_notification_body'), $this->getObjectTitle(true))); - $this->appendBody("\n"); - $this->appendBody( - $this->getLanguageText('exc_assignment').": ". - ilExAssignment::lookupTitle($this->getAssignmentId())); - $this->appendBody("\n"); - $this->appendBody( - $this->getLanguageText('user').": ". - $ilUser->getFullName()); - $this->appendBody("\n\n"); - $this->appendBody(sprintf($this->getLanguageText('exc_submission_notification_link'), - $this->createPermanentLink())); + foreach ($this->getRecipients() as $rcp) { + $this->initLanguage($rcp); + $this->initMail(); + $this->setSubject( + sprintf( + $this->getLanguageText('exc_submission_notification_subject'), + $this->getObjectTitle(true) + ) + ); + $this->setBody(ilMail::getSalutation($rcp, $this->getLanguage())); + $this->appendBody("\n\n"); + $this->appendBody( + sprintf($this->getLanguageText('exc_submission_notification_body'), $this->getObjectTitle(true)) + ); + $this->appendBody("\n"); + $this->appendBody( + $this->getLanguageText('exc_assignment') . ": " . + ilExAssignment::lookupTitle($this->getAssignmentId()) + ); + $this->appendBody("\n"); + $this->appendBody( + $this->getLanguageText('user') . ": " . + $ilUser->getFullName() + ); + $this->appendBody("\n\n"); + $this->appendBody(sprintf( + $this->getLanguageText('exc_submission_notification_link'), + $this->createPermanentLink() + )); - if (ilExAssignment::lookupType($this->getAssignmentId()) == ilExAssignment::TYPE_UPLOAD) - { - $this->appendBody("\n\n"); + if (ilExAssignment::lookupType($this->getAssignmentId()) == ilExAssignment::TYPE_UPLOAD) { + $this->appendBody("\n\n"); - //new files uploaded - $assignment = new ilExAssignment($this->getAssignmentId()); - $submission = new ilExSubmission($assignment,$ilUser->getId()); + //new files uploaded + $assignment = new ilExAssignment($this->getAssignmentId()); + $submission = new ilExSubmission($assignment, $ilUser->getId()); - // since mails are sent immediately after upload the files should always be new - //if($submission->lookupNewFiles($submission->getTutor())) - //{ - $this->appendBody(sprintf($this->getLanguageText('exc_submission_downloads_notification_link'), - $this->createPermanentLink(array(),"_".$this->getAssignmentId()."_".$ilUser->getId()."_setdownload"))); - //} - //else - //{ - // $this->appendBody(sprintf($this->getLanguageText('exc_submission_downloads_notification_link'), - // $this->getLanguageText("exc_submission_no_new_files"))); - //} - } + // since mails are sent immediately after upload the files should always be new + //if($submission->lookupNewFiles($submission->getTutor())) + //{ + $this->appendBody(sprintf( + $this->getLanguageText('exc_submission_downloads_notification_link'), + $this->createPermanentLink(array(), "_" . $this->getAssignmentId() . "_" . $ilUser->getId() . "_setdownload") + )); + //} + //else + //{ + // $this->appendBody(sprintf($this->getLanguageText('exc_submission_downloads_notification_link'), + // $this->getLanguageText("exc_submission_no_new_files"))); + //} + } - $this->appendBody("\n\n"); - $this->appendBody(sprintf($this->getLanguageText('exc_submission_and_grades_notification_link'), - $this->createPermanentLink(array(), "_".$this->getAssignmentId()."_grades"))); + $this->appendBody("\n\n"); + $this->appendBody(sprintf( + $this->getLanguageText('exc_submission_and_grades_notification_link'), + $this->createPermanentLink(array(), "_" . $this->getAssignmentId() . "_grades") + )); - $this->getMail()->appendInstallationSignature(true); + $this->getMail()->appendInstallationSignature(true); - $this->sendMail(array($rcp),array('system')); - } - break; - - case self::TYPE_FEEDBACK_TEXT_ADDED: - - foreach($this->getRecipients() as $rcp) - { - $this->initLanguage($rcp); - $this->initMail(); - $this->setSubject( - sprintf($this->getLanguageText('exc_msg_new_feedback_text_uploaded'), - $this->getObjectTitle(true)) - ); - $this->setBody(ilMail::getSalutation($rcp,$this->getLanguage())); - $this->appendBody("\n\n"); - $this->appendBody( - $this->getLanguageText('exc_msg_new_feedback_text_uploaded2')); - $this->appendBody("\n"); - $this->appendBody( - $this->getLanguageText('obj_exc').": ".$this->getObjectTitle(true)); - $this->appendBody("\n"); - $this->appendBody( - $this->getLanguageText('exc_assignment').": ". - ilExAssignment::lookupTitle($this->getAssignmentId())); - $this->appendBody("\n\n"); - $this->appendBody($this->getLanguageText('exc_mail_permanent_link')); - $this->appendBody("\n"); - $this->appendBody($this->createPermanentLink(array(), '_'.$this->getAssignmentId()). - '#fb'.$this->getAssignmentId()); - $this->getMail()->appendInstallationSignature(true); - - $this->sendMail(array($rcp),array('system')); - } - break; - } - return true; - } - - /** - * Add language module exc - * @param object $a_usr_id - * @return - */ - protected function initLanguage($a_usr_id) - { - parent::initLanguage($a_usr_id); - $this->getLanguage()->loadLanguageModule('exc'); - } + $this->sendMail(array($rcp), array('system')); + } + break; + + case self::TYPE_FEEDBACK_TEXT_ADDED: + + foreach ($this->getRecipients() as $rcp) { + $this->initLanguage($rcp); + $this->initMail(); + $this->setSubject( + sprintf( + $this->getLanguageText('exc_msg_new_feedback_text_uploaded'), + $this->getObjectTitle(true) + ) + ); + $this->setBody(ilMail::getSalutation($rcp, $this->getLanguage())); + $this->appendBody("\n\n"); + $this->appendBody( + $this->getLanguageText('exc_msg_new_feedback_text_uploaded2') + ); + $this->appendBody("\n"); + $this->appendBody( + $this->getLanguageText('obj_exc') . ": " . $this->getObjectTitle(true) + ); + $this->appendBody("\n"); + $this->appendBody( + $this->getLanguageText('exc_assignment') . ": " . + ilExAssignment::lookupTitle($this->getAssignmentId()) + ); + $this->appendBody("\n\n"); + $this->appendBody($this->getLanguageText('exc_mail_permanent_link')); + $this->appendBody("\n"); + $this->appendBody($this->createPermanentLink(array(), '_' . $this->getAssignmentId()) . + '#fb' . $this->getAssignmentId()); + $this->getMail()->appendInstallationSignature(true); + + $this->sendMail(array($rcp), array('system')); + } + break; + } + return true; + } + + /** + * Add language module exc + * @param object $a_usr_id + * @return + */ + protected function initLanguage($a_usr_id) + { + parent::initLanguage($a_usr_id); + $this->getLanguage()->loadLanguageModule('exc'); + } } -?> \ No newline at end of file diff --git a/Modules/Exercise/classes/class.ilExerciseManagementGUI.php b/Modules/Exercise/classes/class.ilExerciseManagementGUI.php index 1f01ec129ae2466cb2b6bbd0a9765fff6a32117c..878b6cf6e2d4b27d7a0a430b5cfd1f72a389e76e 100644 --- a/Modules/Exercise/classes/class.ilExerciseManagementGUI.php +++ b/Modules/Exercise/classes/class.ilExerciseManagementGUI.php @@ -8,2225 +8,2056 @@ include_once "Modules/Exercise/classes/class.ilExSubmissionBaseGUI.php"; * Class ilExerciseManagementGUI * * @author Jörg Lützenkirchen -* +* * @ilCtrl_Calls ilExerciseManagementGUI: ilFileSystemGUI, ilRepositorySearchGUI * @ilCtrl_Calls ilExerciseManagementGUI: ilExSubmissionTeamGUI, ilExSubmissionFileGUI * @ilCtrl_Calls ilExerciseManagementGUI: ilExSubmissionTextGUI, ilExPeerReviewGUI -* +* * @ingroup ModulesExercise */ class ilExerciseManagementGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTabsGUI - */ - protected $tabs_gui; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var \ILIAS\UI\Factory - */ - protected $ui_factory; - - /** - * @var \ILIAS\UI\Renderer - */ - protected $ui_renderer; - - /** - * @var array - */ - protected $filter; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - protected $exercise; // [ilObjExercise] - protected $assignment; // [ilExAssignment] - - protected $task_factory; - - /** - * @var ilObjUser - */ - protected $user; - - const VIEW_ASSIGNMENT = 1; - const VIEW_PARTICIPANT = 2; - const VIEW_GRADES = 3; - - const FEEDBACK_ONLY_SUBMISSION = "submission_feedback"; - const FEEDBACK_FULL_SUBMISSION = "submission_only"; - - const GRADE_NOT_GRADED = "notgraded"; - const GRADE_PASSED = "passed"; - const GRADE_FAILED = "failed"; - - /** - * Constructor - * - * @param int $a_exercise_id - * @return object - */ - public function __construct(ilObjExercise $a_exercise, ilExAssignment $a_ass = null) - { - global $DIC; - - $this->ui_factory = $DIC->ui()->factory(); - $this->ui_renderer = $DIC->ui()->renderer(); - $this->user = $DIC->user(); - $this->toolbar = $DIC->toolbar(); - - $this->ctrl = $DIC->ctrl(); - $this->tabs_gui = $DIC->tabs(); - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - - $this->task_factory = $DIC->backgroundTasks()->taskFactory(); - - - $this->exercise = $a_exercise; - if($a_ass) - { - $this->assignment = $a_ass; - $this->ass_id = $this->assignment->getId(); - } - - $this->ctrl->saveParameter($this, array("vw", "member_id")); - - } - - public function executeCommand() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilTabs = $this->tabs_gui; - - $class = $ilCtrl->getNextClass($this); - //$cmd = $ilCtrl->getCmd("listPublicSubmissions"); - - switch($class) - { - case "ilfilesystemgui": - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTarget($this, $this->getViewBack())); - - ilUtil::sendInfo($lng->txt("exc_fb_tutor_info")); - - include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); - $fstorage = new ilFSStorageExercise($this->exercise->getId(), $this->assignment->getId()); - $fstorage->create(); - - $submission = new ilExSubmission($this->assignment, (int)$_GET["member_id"]); - $feedback_id = $submission->getFeedbackId(); - $noti_rec_ids = $submission->getUserIds(); - - include_once("./Services/User/classes/class.ilUserUtil.php"); - $fs_title = array(); - foreach($noti_rec_ids as $rec_id) - { - $fs_title[] = ilUserUtil::getNamePresentation($rec_id, false, false, "", true); - } - $fs_title = implode(" / ", $fs_title); - - include_once("./Services/FileSystem/classes/class.ilFileSystemGUI.php"); - $fs_gui = new ilFileSystemGUI($fstorage->getFeedbackPath($feedback_id)); - $fs_gui->setTableId("excfbfil".$this->assignment->getId()."_".$feedback_id); - $fs_gui->setAllowDirectories(false); - $fs_gui->setTitle($lng->txt("exc_fb_files")." - ". - $this->assignment->getTitle()." - ". - $fs_title); - $pcommand = $fs_gui->getLastPerformedCommand(); - if (is_array($pcommand) && $pcommand["cmd"] == "create_file") - { - foreach($noti_rec_ids as $user_id) - { - $member_status = $this->assignment->getMemberStatus($user_id); - $member_status->setFeedback(true); - $member_status->update(); - } - - $this->exercise->sendFeedbackFileNotification($pcommand["name"], - $noti_rec_ids, $this->assignment->getId()); - } - $this->ctrl->forwardCommand($fs_gui); - break; - - case 'ilrepositorysearchgui': - include_once('./Services/Search/classes/class.ilRepositorySearchGUI.php'); - $rep_search = new ilRepositorySearchGUI(); - $ref_id = $this->exercise->getRefId(); - $rep_search->addUserAccessFilterCallable(function ($a_user_ids) use ($ref_id) - { - - return $GLOBALS['DIC']->access()->filterUserIdsByRbacOrPositionOfCurrentUser( - 'edit_submissions_grades', - 'edit_submissions_grades', - $ref_id, - $a_user_ids - ); - }); - $rep_search->setTitle($this->lng->txt("exc_add_participant")); - $rep_search->setCallback($this,'addMembersObject'); - - // Set tabs - $this->addSubTabs("assignment"); - $this->ctrl->setReturn($this,'members'); - - $this->ctrl->forwardCommand($rep_search); - break; - - case "ilexsubmissionteamgui": - include_once "Modules/Exercise/classes/class.ilExSubmissionTeamGUI.php"; - $gui = new ilExSubmissionTeamGUI($this->exercise, $this->initSubmission()); - $ilCtrl->forwardCommand($gui); - break; - - case "ilexsubmissionfilegui": - include_once "Modules/Exercise/classes/class.ilExSubmissionFileGUI.php"; - $gui = new ilExSubmissionFileGUI($this->exercise, $this->initSubmission()); - $ilCtrl->forwardCommand($gui); - break; - - case "ilexsubmissiontextgui": - $ilCtrl->saveParameter($this, array("part_id")); - include_once "Modules/Exercise/classes/class.ilExSubmissionTextGUI.php"; - $gui = new ilExSubmissionTextGUI($this->exercise, $this->initSubmission()); - $ilCtrl->forwardCommand($gui); - break; - - case "ilexpeerreviewgui": - include_once "Modules/Exercise/classes/class.ilExPeerReviewGUI.php"; - $gui = new ilExPeerReviewGUI($this->assignment, $this->initSubmission()); - $ilCtrl->forwardCommand($gui); - break; - - default: - $cmd = $ilCtrl->getCmd(); - switch($cmd) - { - case 'downloadSubmissions': - $cmd = $ilCtrl->getCmd("downloadSubmissions"); - break; - default: - $cmd = $ilCtrl->getCmd("listPublicSubmissions"); - break; - } - $this->{$cmd."Object"}(); - break; - } - } - - protected function getViewBack() - { - switch($_REQUEST["vw"]) - { - case self::VIEW_PARTICIPANT: - $back_cmd = "showParticipant"; - break; - - case self::VIEW_GRADES: - $back_cmd = "showGradesOverview"; - break; - - default: - // case self::VIEW_ASSIGNMENT: - $back_cmd = "members"; - break; - } - return $back_cmd; - } - - protected function initSubmission() - { - $back_cmd = $this->getViewBack(); - $this->ctrl->setReturn($this, $back_cmd); - - $this->tabs_gui->clearTargets(); - $this->tabs_gui->setBackTarget($this->lng->txt("back"), - $this->ctrl->getLinkTarget($this, $back_cmd)); - - include_once "Modules/Exercise/classes/class.ilExSubmission.php"; - return new ilExSubmission($this->assignment, $_REQUEST["member_id"], null, true); - } - - /** - * adds tabs to tab gui object - * - * @param object $tabs_gui ilTabsGUI object - */ - function addSubTabs($a_activate) - { - $ilTabs = $this->tabs_gui; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $ass_id = $_GET["ass_id"]; - $part_id = $_GET["part_id"]; - - $ilCtrl->setParameter($this, "vw", ""); - $ilCtrl->setParameter($this, "member_id", ""); - $ilCtrl->setParameter($this, "ass_id", ""); - $ilCtrl->setParameter($this, "part_id", ""); - - $ilTabs->addSubTab("assignment", $lng->txt("exc_assignment_view"), - $ilCtrl->getLinkTarget($this, "members")); - $ilTabs->addSubTab("participant", $lng->txt("exc_participant_view"), - $ilCtrl->getLinkTarget($this, "showParticipant")); - $ilTabs->addSubTab("grades", $lng->txt("exc_grades_overview"), - $ilCtrl->getLinkTarget($this, "showGradesOverview")); - $ilTabs->activateSubTab($a_activate); - - $ilCtrl->setParameter($this, "ass_id", $ass_id); - $ilCtrl->setParameter($this, "part_id", $part_id); - } - - public function waitingDownloadObject() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameterByClass("ilExSubmissionFileGUI", "member_id", (int) $_GET["member_id"]); - $url = $ilCtrl->getLinkTargetByClass(array("ilRepositoryGUI", "ilExerciseHandlerGUI", "ilObjExerciseGUI", "ilExerciseManagementGUI", "ilExSubmissionFileGUI"),"downloadNewReturned"); - $js_url = $ilCtrl->getLinkTargetByClass(array("ilRepositoryGUI", "ilExerciseHandlerGUI", "ilObjExerciseGUI", "ilExerciseManagementGUI", "ilExSubmissionFileGUI"),"downloadNewReturned", "", "", false); - ilUtil::sendInfo($lng->txt("exc_wait_for_files")." ".$lng->txt('exc_download_files').""); - $this->membersObject(); - } - - /** - * All participants and submission of one assignment - */ - function membersObject() - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - include_once 'Services/Tracking/classes/class.ilLPMarks.php'; - - $this->addSubTabs("assignment"); - - // assignment selection - include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); - $ass = ilExAssignment::getInstancesByExercise($this->exercise->getId()); - - if (!$this->assignment) - { - $this->assignment = current($ass); - } - - reset($ass); - if (count($ass) > 1) - { - $options = array(); - foreach ($ass as $a) - { - $options[$a->getId()] = $a->getTitle(); - } - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $si = new ilSelectInputGUI($this->lng->txt(""), "ass_id"); - $si->setOptions($options); - $si->setValue($this->assignment->getId()); - $ilToolbar->addStickyItem($si); - - include_once("./Services/UIComponent/Button/classes/class.ilSubmitButton.php"); - $button = ilSubmitButton::getInstance(); - $button->setCaption("exc_select_ass"); - $button->setCommand("selectAssignment"); - $ilToolbar->addStickyItem($button); - - $ilToolbar->addSeparator(); - } - // #16165 - if only 1 assignment dropdown is not displayed; - else if($this->assignment) - { - $ilCtrl->setParameter($this, "ass_id", $this->assignment->getId()); - } - - // add member - // is only shown if 'edit_submissions_grades' is granted by rbac. positions - // access is not sufficient. - $has_rbac_access = $GLOBALS['DIC']->access()->checkAccess( - 'edit_submissions_grades', - '', - $this->exercise->getRefId() - ); - if($has_rbac_access) - { - 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->exercise->getRefId() - ) - ); - } - - // #16168 - no assignments - if (count($ass) > 0) - { - if($has_rbac_access) - { - $ilToolbar->addSeparator(); - } - - // we do not want the ilRepositorySearchGUI form action - $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); - - $ilCtrl->setParameter($this, "ass_id", $this->assignment->getId()); - - if($this->assignment->getType() == ilExAssignment::TYPE_UPLOAD_TEAM) - { - include_once("./Modules/Exercise/classes/class.ilExAssignmentTeam.php"); - if(ilExAssignmentTeam::getAdoptableGroups($this->exercise->getRefId())) - { - $ilToolbar->addButton($this->lng->txt("exc_adopt_group_teams"), - $this->ctrl->getLinkTarget($this, "adoptTeamsFromGroup")); - - $ilToolbar->addSeparator(); - } - } - else if($this->exercise->hasTutorFeedbackFile()) - { - if (!$this->assignment->getAssignmentType()->usesTeams()) - { - // multi-feedback - $ilToolbar->addButton($this->lng->txt("exc_multi_feedback"), - $this->ctrl->getLinkTarget($this, "showMultiFeedback")); - - $ilToolbar->addSeparator(); - } - } - - if(ilExSubmission::hasAnySubmissions($this->assignment->getId())) - { - $ass_type = $this->assignment->getType(); - //todo change addFormButton for addButtonInstance - if($ass_type == ilExAssignment::TYPE_TEXT) { - $ilToolbar->addFormButton($lng->txt("exc_list_text_assignment"), "listTextAssignment"); - } - $ilToolbar->addFormButton($lng->txt("download_all_returned_files"), "downloadSubmissions"); - } - $this->ctrl->setParameter($this, "vw", self::VIEW_ASSIGNMENT); - - include_once("./Modules/Exercise/classes/class.ilExerciseMemberTableGUI.php"); - $exc_tab = new ilExerciseMemberTableGUI($this, "members", $this->exercise, $this->assignment->getId()); - $tpl->setContent( - $exc_tab->getHTML(). - $this->initIndividualDeadlineModal() - ); - } - else - { - ilUtil::sendInfo($lng->txt("exc_no_assignments_available")); - } - - $ilCtrl->setParameter($this, "ass_id", ""); - - return; - } - - function downloadSubmissionsObject() - { - include_once './Modules/Exercise/classes/BackgroundTasks/class.ilDownloadSubmissionsBackgroundTask.php'; - - $participant_id = $_REQUEST['part_id']; - - $download_task = new ilDownloadSubmissionsBackgroundTask( - (int)$GLOBALS['DIC']->user()->getId(), - (int)$this->exercise->getRefId(), - (int)$this->exercise->getId(), - (int)$this->ass_id, - (int)$participant_id); - - if($download_task->run()) { - ilUtil::sendSuccess($this->lng->txt('exc_down_files_started_bg'),true); - } - - if($this->assignment) { - $this->ctrl->redirect($this, "members"); - } else{ - $this->ctrl->redirect($this, "showParticipant"); - } - } - - function membersApplyObject() - { - $this->saveStatusAllObject(null, false); - include_once("./Modules/Exercise/classes/class.ilExerciseMemberTableGUI.php"); - $exc_tab = new ilExerciseMemberTableGUI($this, "members", $this->exercise, $this->assignment->getId()); - $exc_tab->resetOffset(); - $exc_tab->writeFilterToSession(); - - $this->membersObject(); - } - - function membersResetObject() - { - include_once("./Modules/Exercise/classes/class.ilExerciseMemberTableGUI.php"); - $exc_tab = new ilExerciseMemberTableGUI($this, "members", $this->exercise, $this->assignment->getId()); - $exc_tab->resetOffset(); - $exc_tab->resetFilter(); - - $this->membersObject(); - } - - /** - * Save grades - */ - function saveGradesObject() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - include_once 'Services/Tracking/classes/class.ilLPMarks.php'; - - if (is_array($_POST["lcomment"])) - { - foreach ($_POST["lcomment"] as $k => $v) - { - $marks_obj = new ilLPMarks($this->exercise->getId(), (int) $k); - $marks_obj->setComment(ilUtil::stripSlashes($v)); - $marks_obj->setMark(ilUtil::stripSlashes($_POST["mark"][$k])); - $marks_obj->update(); - } - } - ilUtil::sendSuccess($lng->txt("exc_msg_saved_grades"), true); - $ilCtrl->redirect($this, "showGradesOverview"); - } - - - // TEXT ASSIGNMENT ?! - - /** - * todo: Pagination. - */ - function listTextAssignmentObject() - { - $this->initFilter(); - - //tabs - $this->tabs_gui->clearTargets(); - $this->tabs_gui->setBackTarget($this->lng->txt("back"), - $this->ctrl->getLinkTarget($this, "members")); - - $button_print = $this->ui_factory->button()->standard($this->lng->txt('print'), "#") - ->withOnLoadCode(function($id) { - return "$('#{$id}').click(function() { window.print(); return false; });"; - }); - $this->toolbar->addSeparator(); - $this->toolbar->addComponent($button_print); - - //retrieve data - $peer_review = new ilExPeerReview($this->assignment); - $peer_data = $peer_review->getAllPeerReviews(); - - include_once "Services/User/classes/class.ilUserUtil.php"; - include_once "Services/RTE/classes/class.ilRTE.php"; - - $report_html = ""; - //TODO create proper title. - $report_title = $this->lng->txt("exc_list_text_assignment").": ".$this->assignment->getTitle(); - $report_html .= "

".$report_title."

"; - $total_reports = 0; - - $members = ilExSubmission::getAssignmentParticipants($this->exercise->getId(), $this->ass_id); - $members_filter = new ilExerciseMembersFilter($this->exercise->getRefId(), $members, $this->user->getId()); - $members = $members_filter->filterParticipantsByAccess(); - - foreach(ilExSubmission::getAssignmentFilesByUsers($this->exercise->getId(), $this->assignment->getId(), $members) as $file) - { - if(trim($file["atext"]) && ilObjUser::_exists($file["user_id"])) - { - $user = new ilObjUser($file["user_id"]); - $uname = $user->getFirstname()." ".$user->getLastname(); - $data = array( - "uid" => $file["user_id"], - "uname" => $uname, - "udate" => $file["ts"], - "utext" => ilRTE::_replaceMediaObjectImageSrc($file["atext"], 1) // mob id to mob src - ); - - if(isset($peer_data[$file["user_id"]])) - { - $data["peer"] = array_keys($peer_data[$file["user_id"]]); - } - - $data["fb_received"] = count($data["peer"]); - $data["fb_given"] = $peer_review->countGivenFeedback(true, $file["user_id"]); - - $submission_data = $this->assignment->getExerciseMemberAssignmentData($file["user_id"], $this->filter["status"]); - - if(is_array($submission_data)) - { - $data = array_merge($data, $submission_data); - $report_html .= $this->getReportPanel($data); - $total_reports++; - - } - } - } - if($total_reports == 0) - { - $mtpl = new ilTemplate("tpl.message.html", true, true, "Services/Utilities"); - $mtpl->setCurrentBlock("info_message"); - $mtpl->setVariable("TEXT", $this->lng->txt("fiter_no_results")); - $mtpl->parseCurrentBlock(); - $report_html .= $mtpl->get(); - } - - $this->tpl->setContent($report_html); - } - - public function getReportPanel($a_data) - { - $modal = $this->getEvaluationModal($a_data); - - $this->ctrl->setParameter($this,"member_id", $a_data['uid']); - - $actions = array( - $this->ui_factory->button()->shy($this->lng->txt("grade_evaluate"), "#")->withOnClick($modal->getShowSignal()) - ); - if($this->exercise->hasTutorFeedbackMail()) - { - $actions[] = $this->ui_factory->button()->shy( - $this->lng->txt("exc_tbl_action_feedback_mail"), - $this->ctrl->getLinkTarget($this,"redirectFeedbackMail") - ); - } - if($this->exercise->hasTutorFeedbackFile()) - { - $actions[] = $this->ui_factory->button()->shy( - $this->lng->txt("exc_tbl_action_feedback_file"), - $this->ctrl->getLinkTargetByClass("ilFileSystemGUI", "listFiles") - ); - } - - $this->ctrl->setParameter($this,"member_id", ""); - - $actions_dropdown = $this->ui_factory->dropdown()->standard($actions); - - if($a_data['status'] == self::GRADE_NOT_GRADED) { - $str_status_key = $this->lng->txt('exc_tbl_status'); - $str_status_value = $this->lng->txt('not_yet'); - } else { - $str_status_key = $this->lng->txt('exc_tbl_status_time'); - $str_status_value = ilDatePresentation::formatDate(new ilDateTime($a_data["status_time"], IL_CAL_DATETIME)); - } - - $str_mark_key = $this->lng->txt("exc_tbl_mark"); - $str_mark_value = $this->lng->txt('not_yet'); - - if(($a_data['mark'] != "")){ - $str_mark_value = $a_data['mark']; - } - - if($a_data['feedback_time']) { - $str_evaluation_key = $this->lng->txt('exc_tbl_feedback_time'); - $str_evaluation_value = ilDatePresentation::formatDate(new ilDateTime($a_data["feedback_time"], IL_CAL_DATETIME)); - } else { - $str_evaluation_key = $this->lng->txt('exc_settings_feedback'); - $str_evaluation_value = $this->lng->txt('not_yet'); - } - - $card_content = array( - $this->lng->txt("exc_tbl_submission_date") => ilDatePresentation::formatDate(new ilDateTime($a_data["udate"], IL_CAL_DATETIME)), - $str_status_key => $str_status_value, - $str_mark_key => $str_mark_value, - $str_evaluation_key => $str_evaluation_value, - $this->lng->txt('feedback_given') => $a_data['fb_given'], - $this->lng->txt('feedback_received') => $a_data['fb_received'] - ); - $card_tpl = new ilTemplate("tpl.exc_report_details_card.html", true, true, "Modules/Exercise"); - foreach($card_content as $key => $value) - { - $card_tpl->setCurrentBlock("assingment_card"); - $card_tpl->setVariable("ROW_KEY", $key); - $card_tpl->setVariable("ROW_VALUE", $value); - $card_tpl->parseCurrentBlock(); - } - - $main_panel = $this->ui_factory->panel()->sub($a_data['uname'], $this->ui_factory->legacy($a_data['utext'])) - ->withCard($this->ui_factory->card()->standard($this->lng->txt('text_assignment'))->withSections(array($this->ui_factory->legacy($card_tpl->get()))))->withActions($actions_dropdown); - - $feedback_tpl = new ilTemplate("tpl.exc_report_feedback.html", true, true, "Modules/Exercise"); - if(array_key_exists("peer", $a_data) && $this->filter["feedback"] == "submission_feedback") - { - $feedback_tpl->setCurrentBlock("feedback"); - foreach($a_data["peer"] as $peer_id) - { - $user = new ilObjUser($peer_id); - $peer_name = $user->getFirstname()." ".$user->getLastname(); - - $feedback_tpl->setCurrentBlock("peer_feedback"); - $feedback_tpl->setVariable("PEER_NAME", $peer_name); - - $submission = new ilExSubmission($this->assignment, $a_data["uid"]); - $values = $submission->getPeerReview()->getPeerReviewValues($peer_id, $a_data["uid"]); - - $review_html = ""; - foreach($this->assignment->getPeerReviewCriteriaCatalogueItems() as $crit) - { - $crit_id = $crit->getId() - ? $crit->getId() - : $crit->getType(); - $crit->setPeerReviewContext($this->assignment, $peer_id, $a_data["uid"]); - - $review_html .= - '
'.$crit->getTitle().'
'. - '
'.$crit->getHTML($values[$crit_id]).'
'; - - } - $feedback_tpl->setVariable("PEER_FEEDBACK", $review_html); - $feedback_tpl->parseCurrentBlock(); - } - $feedback_tpl->parseCurrentBlock(); - } - $feedback_tpl->setVariable("GRADE", $this->lng->txt('grade').": ".$this->lng->txt('exc_'.$a_data['status'])); - $feedback_tpl->setVariable("COMMENT", $this->lng->txt('exc_comment')."
".$a_data['comment']); - - $feedback_panel = $this->ui_factory->panel()->sub("",$this->ui_factory->legacy($feedback_tpl->get())); - - $report = $this->ui_factory->panel()->report("", array($main_panel, $feedback_panel)); - - return $this->ui_renderer->render([$modal,$report]); - } - - public function getEvaluationModal($a_data) - { - $modal_tpl = new ilTemplate("tpl.exc_report_evaluation_modal.html", true, true, "Modules/Exercise"); - $modal_tpl->setVariable("USER_NAME",$a_data['uname']); - - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this, "saveEvaluationFromModal")); - $form->setId(uniqid('form')); - - //Grade - $options = array( - self::GRADE_NOT_GRADED => $this->lng->txt("exc_notgraded"), - self::GRADE_PASSED => $this->lng->txt("exc_passed"), - self::GRADE_FAILED => $this->lng->txt("exc_failed") - ); - $si = new ilSelectInputGUI($this->lng->txt("exc_tbl_status"), "grade"); - $si->setOptions($options); - $si->setValue($a_data['status']); - $form->addItem($si); - - //Mark - $mark_input = new ilTextInputGUI($this->lng->txt("exc_tbl_mark"), "mark"); - $mark_input->setValue($a_data['mark']); - $mark_input->setMaxLength(32); - $mark_input->setSize(4); - $form->addItem($mark_input); - - $item = new ilHiddenInputGUI('mem_id'); - $item->setValue($a_data['uid']); - $form->addItem($item); - - //TODO: CHECK ilias string utils. ilUtil shortenText with net blank. - if($this->exercise->hasTutorFeedbackText()) - { - $max_chars = 500; - - $u_text = strip_tags($a_data["utext"]); //otherwise will get open P - $text = $u_text; - //show more - if(strlen($u_text) > $max_chars) - { - $text = ""; - $text .= "
"; - $text .= mb_substr($u_text, 0, $max_chars); - $text .= ""; - $text .= mb_substr($u_text, $max_chars); - $text .= "
"; - $text .= ""; - } - $modal_tpl->setVariable("USER_TEXT",$text); - - $ta = new ilTextAreaInputGUI($this->lng->txt("exc_comment"), 'comment'); - $ta->setInfo($this->lng->txt("exc_comment_for_learner_info")); - $ta->setValue($a_data['comment']); - $ta->setRows(10); - $form->addItem($ta); - } - - $modal_tpl->setVariable("FORM",$form->getHTML()); - - $form_id = 'form_' . $form->getId(); - $submit_btn = $this->ui_factory->button()->primary($this->lng->txt("save"), '#') - ->withOnLoadCode(function($id) use ($form_id) { - return "$('#{$id}').click(function() { $('#{$form_id}').submit(); return false; });"; - }); - - return $this->ui_factory->modal()->roundtrip(strtoupper($this->lng->txt("grade_evaluate")), $this->ui_factory->legacy($modal_tpl->get()))->withActionButtons([$submit_btn]); - } - - /** - * Save assignment submission grade(status) and comment from the roundtrip modal. - */ - public function saveEvaluationFromModalObject() - { - $comment = trim($_POST['comment']); - $user_id = (int)$_POST['mem_id']; - $grade = trim($_POST["grade"]); - $mark = trim($_POST['mark']); - - if($this->assignment->getId() && $user_id) { - $member_status = $this->assignment->getMemberStatus($user_id); - $member_status->setComment(ilUtil::stripSlashes($comment)); - $member_status->setStatus($grade); - $member_status->setMark($mark); - if($comment != "") { - $member_status->setFeedback(true); - } - $member_status->update(); - } - ilUtil::sendSuccess($this->lng->txt("exc_status_saved"), true); - $this->ctrl->redirect($this, "listTextAssignment"); - } - - /** - * Add user as member - */ - public function addUserFromAutoCompleteObject() - { - if(!strlen(trim($_POST['user_login']))) - { - ilUtil::sendFailure($this->lng->txt('msg_no_search_string')); - $this->membersObject(); - 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')); - return $this->membersObject(); - } - - $user_ids[] = $user_id; - } - - if(!$this->addMembersObject($user_ids)) - { - $this->membersObject(); - return false; - } - return true; - } - - /** - * Add new partipant - */ - function addMembersObject($a_user_ids = array()) - { - if(!count($a_user_ids)) - { - ilUtil::sendFailure($this->lng->txt("no_checkbox")); - return false; - } - - if(!$this->exercise->members_obj->assignMembers($a_user_ids)) - { - ilUtil::sendFailure($this->lng->txt("exc_members_already_assigned")); - return false; - } - else - { - /* #16921 - // #9946 - create team for new user(s) for each team upload assignment - foreach(ilExAssignment::getInstancesByExercise($this->exercise->getId()) as $ass) - { - if($ass->hasTeam()) - { - include_once "Modules/Exercise/classes/class.ilExAssignmentTeam.php"; - foreach($a_user_ids as $user_id) - { - // #15915 - ilExAssignmentTeam::getTeamId($ass->getId(), $user_id, true); - } - } - } - */ - - ilUtil::sendSuccess($this->lng->txt("exc_members_assigned"),true); - } - - $this->ctrl->redirect($this, "members"); - return true; - } - - - /** - * Select assignment - */ - function selectAssignmentObject() - { - $_GET["ass_id"] = ilUtil::stripSlashes($_POST["ass_id"]); - $this->membersObject(); - } - - /** - * Show Participant - */ - function showParticipantObject() - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->addSubTabs("participant"); - $this->ctrl->setParameter($this, "ass_id", ""); - - // participant selection - include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); - $ass = ilExAssignment::getAssignmentDataOfExercise($this->exercise->getId()); - $members = $this->exercise->members_obj->getMembers(); - - $members = $GLOBALS['DIC']->access()->filterUserIdsByRbacOrPositionOfCurrentUser( - 'edit_submissions_grades', - 'edit_submissions_grades', - $this->exercise->getRefId(), - $members - ); - - - if (count($members) == 0) - { - ilUtil::sendInfo($lng->txt("exc_no_participants")); - return; - } - - $mems = array(); - foreach ($members as $mem_id) - { - if (ilObject::_lookupType($mem_id) == "usr") - { - include_once("./Services/User/classes/class.ilObjUser.php"); - $name = ilObjUser::_lookupName($mem_id); - if (trim($name["login"]) != "") // #20073 - { - $mems[$mem_id] = $name; - } - } - } - - $mems = ilUtil::sortArray($mems, "lastname", "asc", false, true); - - if ($_GET["part_id"] == "" && count($mems) > 0) - { - $_GET["part_id"] = key($mems); - } - - $current_participant = $_GET["part_id"]; - - reset($mems); - if (count($mems) > 1) - { - $options = array(); - foreach ($mems as $k => $m) - { - $options[$k] = - $m["lastname"].", ".$m["firstname"]." [".$m["login"]."]"; - } - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $si = new ilSelectInputGUI($this->lng->txt(""), "part_id"); - $si->setOptions($options); - $si->setValue($current_participant); - $ilToolbar->addStickyItem($si); - - include_once("./Services/UIComponent/Button/classes/class.ilSubmitButton.php"); - $button = ilSubmitButton::getInstance(); - $button->setCaption("exc_select_part"); - $button->setCommand("selectParticipant"); - $ilToolbar->addStickyItem($button); - } - - if (count($mems) > 0) - { - $this->ctrl->setParameter($this, "vw", self::VIEW_PARTICIPANT); - $this->ctrl->setParameter($this, "part_id", $current_participant); - - $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); - $ilToolbar->addFormButton($lng->txt("download_all_returned_files"), "downloadSubmissions"); - - include_once("./Modules/Exercise/classes/class.ilExParticipantTableGUI.php"); - $part_tab = new ilExParticipantTableGUI($this, "showParticipant", - $this->exercise, $current_participant); - $tpl->setContent($part_tab->getHTML(). - $this->initIndividualDeadlineModal()); - } - else - { - ilUtil::sendInfo($this->lng->txt("exc_no_assignments_available")); - } - } - - function showParticipantApplyObject() - { - include_once("./Modules/Exercise/classes/class.ilExParticipantTableGUI.php"); - $exc_tab = new ilExParticipantTableGUI($this, "showParticipant", $this->exercise, $_GET["part_id"]); - $exc_tab->resetOffset(); - $exc_tab->writeFilterToSession(); - - $this->showParticipantObject(); - } - - function showParticipantResetObject() - { - include_once("./Modules/Exercise/classes/class.ilExParticipantTableGUI.php"); - $exc_tab = new ilExParticipantTableGUI($this, "showParticipant", $this->exercise, $_GET["part_id"]); - $exc_tab->resetOffset(); - $exc_tab->resetFilter(); - - $this->showParticipantObject(); - } - - /** - * Select participant - */ - function selectParticipantObject() - { - $_GET["part_id"] = ilUtil::stripSlashes($_POST["part_id"]); - $this->showParticipantObject(); - } - - /** - * Show grades overview - */ - function showGradesOverviewObject() - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->addSubTabs("grades"); - - include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); - $mem_obj = new ilExerciseMembers($this->exercise); - $mems = $mem_obj->getMembers(); - - $mems = $GLOBALS['DIC']->access()->filterUserIdsByRbacOrPositionOfCurrentUser( - 'edit_submissions_grades', - 'edit_submissions_grades', - $this->exercise->getRefId(), - $mems - ); - if (count($mems) > 0) - { - $ilToolbar->addButton($lng->txt("exc_export_excel"), - $ilCtrl->getLinkTarget($this, "exportExcel")); - } - - $this->ctrl->setParameter($this, "vw", self::VIEW_GRADES); - - include_once("./Modules/Exercise/classes/class.ilExGradesTableGUI.php"); - $grades_tab = new ilExGradesTableGUI($this, "showGradesOverview", - $this->exercise, $mem_obj); - $tpl->setContent($grades_tab->getHTML()); - } - - /** - * set feedback status for member and redirect to mail screen - */ - function redirectFeedbackMailObject() - { - $members = array(); - - if ($_GET["member_id"] != "") - { - $submission = new ilExSubmission($this->assignment, $_GET["member_id"]); - $members = $submission->getUserIds(); - } - else if($members = $this->getMultiActionUserIds()) - { - $members = array_keys($members); - } - - if($members) - { - $logins = array(); - foreach($members as $user_id) - { - $member_status = $this->assignment->getMemberStatus($user_id); - $member_status->setFeedback(true); - $member_status->update(); - - $logins[] = ilObjUser::_lookupLogin($user_id); - } - $logins = implode($logins, ","); - - // #16530 - see ilObjCourseGUI::createMailSignature - $sig = chr(13).chr(10).chr(13).chr(10); - $sig .= $this->lng->txt('exc_mail_permanent_link'); - $sig .= chr(13).chr(10).chr(13).chr(10); - include_once './Services/Link/classes/class.ilLink.php'; - $sig .= ilLink::_getLink($this->exercise->getRefId()); - $sig = rawurlencode(base64_encode($sig)); - - require_once 'Services/Mail/classes/class.ilMailFormCall.php'; - ilUtil::redirect(ilMailFormCall::getRedirectTarget( - $this, - $this->getViewBack(), - array(), - array( - 'type' => 'new', - 'rcp_to' => $logins, - ilMailFormCall::SIGNATURE_KEY => $sig - ) - )); - } - } - - /** - * Download all submitted files (of all members). - */ - function downloadAllObject() - { - $members = array(); - - foreach($this->exercise->members_obj->getMembers() as $member_id) - { - $submission = new ilExSubmission($this->assignment, $member_id); - $submission->updateTutorDownloadTime(); - - // get member object (ilObjUser) - if (ilObject::_exists($member_id)) - { - $storage_id = ""; - // adding file metadata - foreach($submission->getFiles() as $file) - { - if ($this->assignment->getAssignmentType()->isSubmissionAssignedToTeam()) - { - $storage_id = $file["team_id"]; - } - else - { - $storage_id = $file["user_id"]; - } - - $members[$storage_id]["files"][$file["returned_id"]] = $file; - } - if ($this->assignment->getAssignmentType()->isSubmissionAssignedToTeam()) - { - $name = "Team ".$submission->getTeam()->getId(); - } - else - { - $tmp_obj = ilObjectFactory::getInstanceByObjId($member_id); - $name = $tmp_obj->getFirstname() . " " . $tmp_obj->getLastname(); - } - if ($storage_id > 0) - { - $members[$storage_id]["name"] = $name; - } - unset($tmp_obj); - } - } - - ilExSubmission::downloadAllAssignmentFiles($this->assignment, $members); - } - - protected function getMultiActionUserIds($a_keep_teams = false) - { - // multi-user - if($this->assignment) - { - if(!$_POST["member"]) - { - ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); - $this->ctrl->redirect($this, "members"); - } - - foreach(array_keys($_POST["member"]) as $user_id) - { - $submission = new ilExSubmission($this->assignment, $user_id); - $tmembers = $submission->getUserIds(); - if(!(bool)$a_keep_teams) - { - foreach($tmembers as $tuser_id) - { - $members[$tuser_id] = 1; - } - } - else - { - if($tmembers) - { - $members[] = $tmembers; - } - else - { - // no team yet - $members[] = $user_id; - } - } - } - } - // multi-ass - else - { - if(!$_POST["ass"]) - { - ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); - $this->ctrl->redirect($this, "showParticipant"); - } - - $user_id = $_GET["part_id"]; - - include_once "Modules/Exercise/classes/class.ilExAssignment.php"; - foreach(array_keys($_POST["ass"]) as $ass_id) - { - $submission = new ilExSubmission(new ilExAssignment($ass_id), $user_id); - $tmembers = $submission->getUserIds(); - if(!(bool)$a_keep_teams) - { - foreach($tmembers as $tuser_id) - { - $members[$ass_id][] = $tuser_id; - } - } - else - { - if($tmembers) - { - $members[$ass_id][] = $tmembers; - } - else - { - // no team yet - $members[$ass_id][] = $user_id; - } - } - } - } - - return $members; - } - - /** - * Send assignment per mail to participants - */ - function sendMembersObject() - { - $members = $this->getMultiActionUserIds(); - - ilUtil::sendSuccess($this->lng->txt("exc_sent"),true); - if($this->assignment) - { - $this->exercise->sendAssignment($this->assignment, array_keys($members)); - $this->ctrl->redirect($this, "members"); - } - else - { - foreach($members as $ass_id => $users) - { - $this->exercise->sendAssignment(new ilExAssignment($ass_id), $users); - } - $this->ctrl->setParameter($this, "part_id", $_GET["part_id"]); // #17629 - $this->ctrl->redirect($this, "showParticipant"); - } - } - - /** - * Confirm deassigning members - */ - function confirmDeassignMembersObject() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - $members = $this->getMultiActionUserIds(); - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("exc_msg_sure_to_deassign_participant")); - $cgui->setCancel($lng->txt("cancel"), "members"); - $cgui->setConfirm($lng->txt("remove"), "deassignMembers"); - - include_once("./Services/User/classes/class.ilUserUtil.php"); - foreach ($members as $k => $m) - { - $cgui->addItem("member[$k]", $m, - ilUserUtil::getNamePresentation((int) $k, false, false, "", true)); - } - - $tpl->setContent($cgui->getHTML()); - } - - /** - * Deassign members from exercise - */ - function deassignMembersObject() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $members = $this->getMultiActionUserIds(); - - foreach(array_keys($members) as $usr_id) - { - $this->exercise->members_obj->deassignMember((int) $usr_id); - } - ilUtil::sendSuccess($lng->txt("exc_msg_participants_removed"), true); - $ilCtrl->redirect($this, "members"); - } - - function saveCommentsObject() - { - if(!isset($_POST['comments_value'])) - { - return; - } + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTabsGUI + */ + protected $tabs_gui; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var \ILIAS\UI\Factory + */ + protected $ui_factory; + + /** + * @var \ILIAS\UI\Renderer + */ + protected $ui_renderer; + + /** + * @var array + */ + protected $filter; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + protected $exercise; // [ilObjExercise] + protected $assignment; // [ilExAssignment] + + protected $task_factory; + + /** + * @var ilObjUser + */ + protected $user; + + const VIEW_ASSIGNMENT = 1; + const VIEW_PARTICIPANT = 2; + const VIEW_GRADES = 3; + + const FEEDBACK_ONLY_SUBMISSION = "submission_feedback"; + const FEEDBACK_FULL_SUBMISSION = "submission_only"; + + const GRADE_NOT_GRADED = "notgraded"; + const GRADE_PASSED = "passed"; + const GRADE_FAILED = "failed"; + + /** + * Constructor + * + * @param int $a_exercise_id + * @return object + */ + public function __construct(ilObjExercise $a_exercise, ilExAssignment $a_ass = null) + { + global $DIC; + + $this->ui_factory = $DIC->ui()->factory(); + $this->ui_renderer = $DIC->ui()->renderer(); + $this->user = $DIC->user(); + $this->toolbar = $DIC->toolbar(); + + $this->ctrl = $DIC->ctrl(); + $this->tabs_gui = $DIC->tabs(); + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + + $this->task_factory = $DIC->backgroundTasks()->taskFactory(); + + + $this->exercise = $a_exercise; + if ($a_ass) { + $this->assignment = $a_ass; + $this->ass_id = $this->assignment->getId(); + } + + $this->ctrl->saveParameter($this, array("vw", "member_id")); + } + + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilTabs = $this->tabs_gui; + + $class = $ilCtrl->getNextClass($this); + //$cmd = $ilCtrl->getCmd("listPublicSubmissions"); + + switch ($class) { + case "ilfilesystemgui": + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, $this->getViewBack()) + ); + + ilUtil::sendInfo($lng->txt("exc_fb_tutor_info")); + + include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); + $fstorage = new ilFSStorageExercise($this->exercise->getId(), $this->assignment->getId()); + $fstorage->create(); + + $submission = new ilExSubmission($this->assignment, (int) $_GET["member_id"]); + $feedback_id = $submission->getFeedbackId(); + $noti_rec_ids = $submission->getUserIds(); + + include_once("./Services/User/classes/class.ilUserUtil.php"); + $fs_title = array(); + foreach ($noti_rec_ids as $rec_id) { + $fs_title[] = ilUserUtil::getNamePresentation($rec_id, false, false, "", true); + } + $fs_title = implode(" / ", $fs_title); + + include_once("./Services/FileSystem/classes/class.ilFileSystemGUI.php"); + $fs_gui = new ilFileSystemGUI($fstorage->getFeedbackPath($feedback_id)); + $fs_gui->setTableId("excfbfil" . $this->assignment->getId() . "_" . $feedback_id); + $fs_gui->setAllowDirectories(false); + $fs_gui->setTitle($lng->txt("exc_fb_files") . " - " . + $this->assignment->getTitle() . " - " . + $fs_title); + $pcommand = $fs_gui->getLastPerformedCommand(); + if (is_array($pcommand) && $pcommand["cmd"] == "create_file") { + foreach ($noti_rec_ids as $user_id) { + $member_status = $this->assignment->getMemberStatus($user_id); + $member_status->setFeedback(true); + $member_status->update(); + } + + $this->exercise->sendFeedbackFileNotification( + $pcommand["name"], + $noti_rec_ids, + $this->assignment->getId() + ); + } + $this->ctrl->forwardCommand($fs_gui); + break; + + case 'ilrepositorysearchgui': + include_once('./Services/Search/classes/class.ilRepositorySearchGUI.php'); + $rep_search = new ilRepositorySearchGUI(); + $ref_id = $this->exercise->getRefId(); + $rep_search->addUserAccessFilterCallable(function ($a_user_ids) use ($ref_id) { + return $GLOBALS['DIC']->access()->filterUserIdsByRbacOrPositionOfCurrentUser( + 'edit_submissions_grades', + 'edit_submissions_grades', + $ref_id, + $a_user_ids + ); + }); + $rep_search->setTitle($this->lng->txt("exc_add_participant")); + $rep_search->setCallback($this, 'addMembersObject'); + + // Set tabs + $this->addSubTabs("assignment"); + $this->ctrl->setReturn($this, 'members'); + + $this->ctrl->forwardCommand($rep_search); + break; + + case "ilexsubmissionteamgui": + include_once "Modules/Exercise/classes/class.ilExSubmissionTeamGUI.php"; + $gui = new ilExSubmissionTeamGUI($this->exercise, $this->initSubmission()); + $ilCtrl->forwardCommand($gui); + break; + + case "ilexsubmissionfilegui": + include_once "Modules/Exercise/classes/class.ilExSubmissionFileGUI.php"; + $gui = new ilExSubmissionFileGUI($this->exercise, $this->initSubmission()); + $ilCtrl->forwardCommand($gui); + break; + + case "ilexsubmissiontextgui": + $ilCtrl->saveParameter($this, array("part_id")); + include_once "Modules/Exercise/classes/class.ilExSubmissionTextGUI.php"; + $gui = new ilExSubmissionTextGUI($this->exercise, $this->initSubmission()); + $ilCtrl->forwardCommand($gui); + break; + + case "ilexpeerreviewgui": + include_once "Modules/Exercise/classes/class.ilExPeerReviewGUI.php"; + $gui = new ilExPeerReviewGUI($this->assignment, $this->initSubmission()); + $ilCtrl->forwardCommand($gui); + break; + + default: + $cmd = $ilCtrl->getCmd(); + switch ($cmd) { + case 'downloadSubmissions': + $cmd = $ilCtrl->getCmd("downloadSubmissions"); + break; + default: + $cmd = $ilCtrl->getCmd("listPublicSubmissions"); + break; + } + $this->{$cmd . "Object"}(); + break; + } + } + + protected function getViewBack() + { + switch ($_REQUEST["vw"]) { + case self::VIEW_PARTICIPANT: + $back_cmd = "showParticipant"; + break; + + case self::VIEW_GRADES: + $back_cmd = "showGradesOverview"; + break; + + default: + // case self::VIEW_ASSIGNMENT: + $back_cmd = "members"; + break; + } + return $back_cmd; + } + + protected function initSubmission() + { + $back_cmd = $this->getViewBack(); + $this->ctrl->setReturn($this, $back_cmd); + + $this->tabs_gui->clearTargets(); + $this->tabs_gui->setBackTarget( + $this->lng->txt("back"), + $this->ctrl->getLinkTarget($this, $back_cmd) + ); + + include_once "Modules/Exercise/classes/class.ilExSubmission.php"; + return new ilExSubmission($this->assignment, $_REQUEST["member_id"], null, true); + } + + /** + * adds tabs to tab gui object + * + * @param object $tabs_gui ilTabsGUI object + */ + public function addSubTabs($a_activate) + { + $ilTabs = $this->tabs_gui; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $ass_id = $_GET["ass_id"]; + $part_id = $_GET["part_id"]; + + $ilCtrl->setParameter($this, "vw", ""); + $ilCtrl->setParameter($this, "member_id", ""); + $ilCtrl->setParameter($this, "ass_id", ""); + $ilCtrl->setParameter($this, "part_id", ""); + + $ilTabs->addSubTab( + "assignment", + $lng->txt("exc_assignment_view"), + $ilCtrl->getLinkTarget($this, "members") + ); + $ilTabs->addSubTab( + "participant", + $lng->txt("exc_participant_view"), + $ilCtrl->getLinkTarget($this, "showParticipant") + ); + $ilTabs->addSubTab( + "grades", + $lng->txt("exc_grades_overview"), + $ilCtrl->getLinkTarget($this, "showGradesOverview") + ); + $ilTabs->activateSubTab($a_activate); + + $ilCtrl->setParameter($this, "ass_id", $ass_id); + $ilCtrl->setParameter($this, "part_id", $part_id); + } + + public function waitingDownloadObject() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameterByClass("ilExSubmissionFileGUI", "member_id", (int) $_GET["member_id"]); + $url = $ilCtrl->getLinkTargetByClass(array("ilRepositoryGUI", "ilExerciseHandlerGUI", "ilObjExerciseGUI", "ilExerciseManagementGUI", "ilExSubmissionFileGUI"), "downloadNewReturned"); + $js_url = $ilCtrl->getLinkTargetByClass(array("ilRepositoryGUI", "ilExerciseHandlerGUI", "ilObjExerciseGUI", "ilExerciseManagementGUI", "ilExSubmissionFileGUI"), "downloadNewReturned", "", "", false); + ilUtil::sendInfo($lng->txt("exc_wait_for_files") . " " . $lng->txt('exc_download_files') . ""); + $this->membersObject(); + } + + /** + * All participants and submission of one assignment + */ + public function membersObject() + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + include_once 'Services/Tracking/classes/class.ilLPMarks.php'; + + $this->addSubTabs("assignment"); + + // assignment selection + include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); + $ass = ilExAssignment::getInstancesByExercise($this->exercise->getId()); + + if (!$this->assignment) { + $this->assignment = current($ass); + } + + reset($ass); + if (count($ass) > 1) { + $options = array(); + foreach ($ass as $a) { + $options[$a->getId()] = $a->getTitle(); + } + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $si = new ilSelectInputGUI($this->lng->txt(""), "ass_id"); + $si->setOptions($options); + $si->setValue($this->assignment->getId()); + $ilToolbar->addStickyItem($si); + + include_once("./Services/UIComponent/Button/classes/class.ilSubmitButton.php"); + $button = ilSubmitButton::getInstance(); + $button->setCaption("exc_select_ass"); + $button->setCommand("selectAssignment"); + $ilToolbar->addStickyItem($button); + + $ilToolbar->addSeparator(); + } + // #16165 - if only 1 assignment dropdown is not displayed; + elseif ($this->assignment) { + $ilCtrl->setParameter($this, "ass_id", $this->assignment->getId()); + } + + // add member + // is only shown if 'edit_submissions_grades' is granted by rbac. positions + // access is not sufficient. + $has_rbac_access = $GLOBALS['DIC']->access()->checkAccess( + 'edit_submissions_grades', + '', + $this->exercise->getRefId() + ); + if ($has_rbac_access) { + 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->exercise->getRefId() + ) + ); + } + + // #16168 - no assignments + if (count($ass) > 0) { + if ($has_rbac_access) { + $ilToolbar->addSeparator(); + } + + // we do not want the ilRepositorySearchGUI form action + $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); + + $ilCtrl->setParameter($this, "ass_id", $this->assignment->getId()); + + if ($this->assignment->getType() == ilExAssignment::TYPE_UPLOAD_TEAM) { + include_once("./Modules/Exercise/classes/class.ilExAssignmentTeam.php"); + if (ilExAssignmentTeam::getAdoptableGroups($this->exercise->getRefId())) { + $ilToolbar->addButton( + $this->lng->txt("exc_adopt_group_teams"), + $this->ctrl->getLinkTarget($this, "adoptTeamsFromGroup") + ); + + $ilToolbar->addSeparator(); + } + } elseif ($this->exercise->hasTutorFeedbackFile()) { + if (!$this->assignment->getAssignmentType()->usesTeams()) { + // multi-feedback + $ilToolbar->addButton( + $this->lng->txt("exc_multi_feedback"), + $this->ctrl->getLinkTarget($this, "showMultiFeedback") + ); + + $ilToolbar->addSeparator(); + } + } + + if (ilExSubmission::hasAnySubmissions($this->assignment->getId())) { + $ass_type = $this->assignment->getType(); + //todo change addFormButton for addButtonInstance + if ($ass_type == ilExAssignment::TYPE_TEXT) { + $ilToolbar->addFormButton($lng->txt("exc_list_text_assignment"), "listTextAssignment"); + } + $ilToolbar->addFormButton($lng->txt("download_all_returned_files"), "downloadSubmissions"); + } + $this->ctrl->setParameter($this, "vw", self::VIEW_ASSIGNMENT); + + include_once("./Modules/Exercise/classes/class.ilExerciseMemberTableGUI.php"); + $exc_tab = new ilExerciseMemberTableGUI($this, "members", $this->exercise, $this->assignment->getId()); + $tpl->setContent( + $exc_tab->getHTML() . + $this->initIndividualDeadlineModal() + ); + } else { + ilUtil::sendInfo($lng->txt("exc_no_assignments_available")); + } + + $ilCtrl->setParameter($this, "ass_id", ""); + + return; + } + + public function downloadSubmissionsObject() + { + include_once './Modules/Exercise/classes/BackgroundTasks/class.ilDownloadSubmissionsBackgroundTask.php'; + + $participant_id = $_REQUEST['part_id']; + + $download_task = new ilDownloadSubmissionsBackgroundTask( + (int) $GLOBALS['DIC']->user()->getId(), + (int) $this->exercise->getRefId(), + (int) $this->exercise->getId(), + (int) $this->ass_id, + (int) $participant_id + ); + + if ($download_task->run()) { + ilUtil::sendSuccess($this->lng->txt('exc_down_files_started_bg'), true); + } + + if ($this->assignment) { + $this->ctrl->redirect($this, "members"); + } else { + $this->ctrl->redirect($this, "showParticipant"); + } + } + + public function membersApplyObject() + { + $this->saveStatusAllObject(null, false); + include_once("./Modules/Exercise/classes/class.ilExerciseMemberTableGUI.php"); + $exc_tab = new ilExerciseMemberTableGUI($this, "members", $this->exercise, $this->assignment->getId()); + $exc_tab->resetOffset(); + $exc_tab->writeFilterToSession(); + + $this->membersObject(); + } + + public function membersResetObject() + { + include_once("./Modules/Exercise/classes/class.ilExerciseMemberTableGUI.php"); + $exc_tab = new ilExerciseMemberTableGUI($this, "members", $this->exercise, $this->assignment->getId()); + $exc_tab->resetOffset(); + $exc_tab->resetFilter(); + + $this->membersObject(); + } + + /** + * Save grades + */ + public function saveGradesObject() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + include_once 'Services/Tracking/classes/class.ilLPMarks.php'; + + if (is_array($_POST["lcomment"])) { + foreach ($_POST["lcomment"] as $k => $v) { + $marks_obj = new ilLPMarks($this->exercise->getId(), (int) $k); + $marks_obj->setComment(ilUtil::stripSlashes($v)); + $marks_obj->setMark(ilUtil::stripSlashes($_POST["mark"][$k])); + $marks_obj->update(); + } + } + ilUtil::sendSuccess($lng->txt("exc_msg_saved_grades"), true); + $ilCtrl->redirect($this, "showGradesOverview"); + } + + + // TEXT ASSIGNMENT ?! + + /** + * todo: Pagination. + */ + public function listTextAssignmentObject() + { + $this->initFilter(); + + //tabs + $this->tabs_gui->clearTargets(); + $this->tabs_gui->setBackTarget( + $this->lng->txt("back"), + $this->ctrl->getLinkTarget($this, "members") + ); + + $button_print = $this->ui_factory->button()->standard($this->lng->txt('print'), "#") + ->withOnLoadCode(function ($id) { + return "$('#{$id}').click(function() { window.print(); return false; });"; + }); + $this->toolbar->addSeparator(); + $this->toolbar->addComponent($button_print); + + //retrieve data + $peer_review = new ilExPeerReview($this->assignment); + $peer_data = $peer_review->getAllPeerReviews(); + + include_once "Services/User/classes/class.ilUserUtil.php"; + include_once "Services/RTE/classes/class.ilRTE.php"; + + $report_html = ""; + //TODO create proper title. + $report_title = $this->lng->txt("exc_list_text_assignment") . ": " . $this->assignment->getTitle(); + $report_html .= "

" . $report_title . "

"; + $total_reports = 0; + + $members = ilExSubmission::getAssignmentParticipants($this->exercise->getId(), $this->ass_id); + $members_filter = new ilExerciseMembersFilter($this->exercise->getRefId(), $members, $this->user->getId()); + $members = $members_filter->filterParticipantsByAccess(); + + foreach (ilExSubmission::getAssignmentFilesByUsers($this->exercise->getId(), $this->assignment->getId(), $members) as $file) { + if (trim($file["atext"]) && ilObjUser::_exists($file["user_id"])) { + $user = new ilObjUser($file["user_id"]); + $uname = $user->getFirstname() . " " . $user->getLastname(); + $data = array( + "uid" => $file["user_id"], + "uname" => $uname, + "udate" => $file["ts"], + "utext" => ilRTE::_replaceMediaObjectImageSrc($file["atext"], 1) // mob id to mob src + ); + + if (isset($peer_data[$file["user_id"]])) { + $data["peer"] = array_keys($peer_data[$file["user_id"]]); + } + + $data["fb_received"] = count($data["peer"]); + $data["fb_given"] = $peer_review->countGivenFeedback(true, $file["user_id"]); + + $submission_data = $this->assignment->getExerciseMemberAssignmentData($file["user_id"], $this->filter["status"]); + + if (is_array($submission_data)) { + $data = array_merge($data, $submission_data); + $report_html .= $this->getReportPanel($data); + $total_reports++; + } + } + } + if ($total_reports == 0) { + $mtpl = new ilTemplate("tpl.message.html", true, true, "Services/Utilities"); + $mtpl->setCurrentBlock("info_message"); + $mtpl->setVariable("TEXT", $this->lng->txt("fiter_no_results")); + $mtpl->parseCurrentBlock(); + $report_html .= $mtpl->get(); + } + + $this->tpl->setContent($report_html); + } + + public function getReportPanel($a_data) + { + $modal = $this->getEvaluationModal($a_data); + + $this->ctrl->setParameter($this, "member_id", $a_data['uid']); + + $actions = array( + $this->ui_factory->button()->shy($this->lng->txt("grade_evaluate"), "#")->withOnClick($modal->getShowSignal()) + ); + if ($this->exercise->hasTutorFeedbackMail()) { + $actions[] = $this->ui_factory->button()->shy( + $this->lng->txt("exc_tbl_action_feedback_mail"), + $this->ctrl->getLinkTarget($this, "redirectFeedbackMail") + ); + } + if ($this->exercise->hasTutorFeedbackFile()) { + $actions[] = $this->ui_factory->button()->shy( + $this->lng->txt("exc_tbl_action_feedback_file"), + $this->ctrl->getLinkTargetByClass("ilFileSystemGUI", "listFiles") + ); + } + + $this->ctrl->setParameter($this, "member_id", ""); + + $actions_dropdown = $this->ui_factory->dropdown()->standard($actions); + + if ($a_data['status'] == self::GRADE_NOT_GRADED) { + $str_status_key = $this->lng->txt('exc_tbl_status'); + $str_status_value = $this->lng->txt('not_yet'); + } else { + $str_status_key = $this->lng->txt('exc_tbl_status_time'); + $str_status_value = ilDatePresentation::formatDate(new ilDateTime($a_data["status_time"], IL_CAL_DATETIME)); + } + + $str_mark_key = $this->lng->txt("exc_tbl_mark"); + $str_mark_value = $this->lng->txt('not_yet'); + + if (($a_data['mark'] != "")) { + $str_mark_value = $a_data['mark']; + } + + if ($a_data['feedback_time']) { + $str_evaluation_key = $this->lng->txt('exc_tbl_feedback_time'); + $str_evaluation_value = ilDatePresentation::formatDate(new ilDateTime($a_data["feedback_time"], IL_CAL_DATETIME)); + } else { + $str_evaluation_key = $this->lng->txt('exc_settings_feedback'); + $str_evaluation_value = $this->lng->txt('not_yet'); + } + + $card_content = array( + $this->lng->txt("exc_tbl_submission_date") => ilDatePresentation::formatDate(new ilDateTime($a_data["udate"], IL_CAL_DATETIME)), + $str_status_key => $str_status_value, + $str_mark_key => $str_mark_value, + $str_evaluation_key => $str_evaluation_value, + $this->lng->txt('feedback_given') => $a_data['fb_given'], + $this->lng->txt('feedback_received') => $a_data['fb_received'] + ); + $card_tpl = new ilTemplate("tpl.exc_report_details_card.html", true, true, "Modules/Exercise"); + foreach ($card_content as $key => $value) { + $card_tpl->setCurrentBlock("assingment_card"); + $card_tpl->setVariable("ROW_KEY", $key); + $card_tpl->setVariable("ROW_VALUE", $value); + $card_tpl->parseCurrentBlock(); + } + + $main_panel = $this->ui_factory->panel()->sub($a_data['uname'], $this->ui_factory->legacy($a_data['utext'])) + ->withCard($this->ui_factory->card()->standard($this->lng->txt('text_assignment'))->withSections(array($this->ui_factory->legacy($card_tpl->get()))))->withActions($actions_dropdown); + + $feedback_tpl = new ilTemplate("tpl.exc_report_feedback.html", true, true, "Modules/Exercise"); + if (array_key_exists("peer", $a_data) && $this->filter["feedback"] == "submission_feedback") { + $feedback_tpl->setCurrentBlock("feedback"); + foreach ($a_data["peer"] as $peer_id) { + $user = new ilObjUser($peer_id); + $peer_name = $user->getFirstname() . " " . $user->getLastname(); + + $feedback_tpl->setCurrentBlock("peer_feedback"); + $feedback_tpl->setVariable("PEER_NAME", $peer_name); + + $submission = new ilExSubmission($this->assignment, $a_data["uid"]); + $values = $submission->getPeerReview()->getPeerReviewValues($peer_id, $a_data["uid"]); + + $review_html = ""; + foreach ($this->assignment->getPeerReviewCriteriaCatalogueItems() as $crit) { + $crit_id = $crit->getId() + ? $crit->getId() + : $crit->getType(); + $crit->setPeerReviewContext($this->assignment, $peer_id, $a_data["uid"]); + + $review_html .= + '
' . $crit->getTitle() . '
' . + '
' . $crit->getHTML($values[$crit_id]) . '
'; + } + $feedback_tpl->setVariable("PEER_FEEDBACK", $review_html); + $feedback_tpl->parseCurrentBlock(); + } + $feedback_tpl->parseCurrentBlock(); + } + $feedback_tpl->setVariable("GRADE", $this->lng->txt('grade') . ": " . $this->lng->txt('exc_' . $a_data['status'])); + $feedback_tpl->setVariable("COMMENT", $this->lng->txt('exc_comment') . "
" . $a_data['comment']); + + $feedback_panel = $this->ui_factory->panel()->sub("", $this->ui_factory->legacy($feedback_tpl->get())); + + $report = $this->ui_factory->panel()->report("", array($main_panel, $feedback_panel)); + + return $this->ui_renderer->render([$modal,$report]); + } + + public function getEvaluationModal($a_data) + { + $modal_tpl = new ilTemplate("tpl.exc_report_evaluation_modal.html", true, true, "Modules/Exercise"); + $modal_tpl->setVariable("USER_NAME", $a_data['uname']); + + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this, "saveEvaluationFromModal")); + $form->setId(uniqid('form')); + + //Grade + $options = array( + self::GRADE_NOT_GRADED => $this->lng->txt("exc_notgraded"), + self::GRADE_PASSED => $this->lng->txt("exc_passed"), + self::GRADE_FAILED => $this->lng->txt("exc_failed") + ); + $si = new ilSelectInputGUI($this->lng->txt("exc_tbl_status"), "grade"); + $si->setOptions($options); + $si->setValue($a_data['status']); + $form->addItem($si); + + //Mark + $mark_input = new ilTextInputGUI($this->lng->txt("exc_tbl_mark"), "mark"); + $mark_input->setValue($a_data['mark']); + $mark_input->setMaxLength(32); + $mark_input->setSize(4); + $form->addItem($mark_input); + + $item = new ilHiddenInputGUI('mem_id'); + $item->setValue($a_data['uid']); + $form->addItem($item); + + //TODO: CHECK ilias string utils. ilUtil shortenText with net blank. + if ($this->exercise->hasTutorFeedbackText()) { + $max_chars = 500; + + $u_text = strip_tags($a_data["utext"]); //otherwise will get open P + $text = $u_text; + //show more + if (strlen($u_text) > $max_chars) { + $text = ""; + $text .= "
"; + $text .= mb_substr($u_text, 0, $max_chars); + $text .= ""; + $text .= mb_substr($u_text, $max_chars); + $text .= "
"; + $text .= ""; + } + $modal_tpl->setVariable("USER_TEXT", $text); + + $ta = new ilTextAreaInputGUI($this->lng->txt("exc_comment"), 'comment'); + $ta->setInfo($this->lng->txt("exc_comment_for_learner_info")); + $ta->setValue($a_data['comment']); + $ta->setRows(10); + $form->addItem($ta); + } + + $modal_tpl->setVariable("FORM", $form->getHTML()); + + $form_id = 'form_' . $form->getId(); + $submit_btn = $this->ui_factory->button()->primary($this->lng->txt("save"), '#') + ->withOnLoadCode(function ($id) use ($form_id) { + return "$('#{$id}').click(function() { $('#{$form_id}').submit(); return false; });"; + }); + + return $this->ui_factory->modal()->roundtrip(strtoupper($this->lng->txt("grade_evaluate")), $this->ui_factory->legacy($modal_tpl->get()))->withActionButtons([$submit_btn]); + } + + /** + * Save assignment submission grade(status) and comment from the roundtrip modal. + */ + public function saveEvaluationFromModalObject() + { + $comment = trim($_POST['comment']); + $user_id = (int) $_POST['mem_id']; + $grade = trim($_POST["grade"]); + $mark = trim($_POST['mark']); + + if ($this->assignment->getId() && $user_id) { + $member_status = $this->assignment->getMemberStatus($user_id); + $member_status->setComment(ilUtil::stripSlashes($comment)); + $member_status->setStatus($grade); + $member_status->setMark($mark); + if ($comment != "") { + $member_status->setFeedback(true); + } + $member_status->update(); + } + ilUtil::sendSuccess($this->lng->txt("exc_status_saved"), true); + $this->ctrl->redirect($this, "listTextAssignment"); + } + + /** + * Add user as member + */ + public function addUserFromAutoCompleteObject() + { + if (!strlen(trim($_POST['user_login']))) { + ilUtil::sendFailure($this->lng->txt('msg_no_search_string')); + $this->membersObject(); + 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')); + return $this->membersObject(); + } + + $user_ids[] = $user_id; + } + + if (!$this->addMembersObject($user_ids)) { + $this->membersObject(); + return false; + } + return true; + } + + /** + * Add new partipant + */ + public function addMembersObject($a_user_ids = array()) + { + if (!count($a_user_ids)) { + ilUtil::sendFailure($this->lng->txt("no_checkbox")); + return false; + } + + if (!$this->exercise->members_obj->assignMembers($a_user_ids)) { + ilUtil::sendFailure($this->lng->txt("exc_members_already_assigned")); + return false; + } else { + /* #16921 + // #9946 - create team for new user(s) for each team upload assignment + foreach(ilExAssignment::getInstancesByExercise($this->exercise->getId()) as $ass) + { + if($ass->hasTeam()) + { + include_once "Modules/Exercise/classes/class.ilExAssignmentTeam.php"; + foreach($a_user_ids as $user_id) + { + // #15915 + ilExAssignmentTeam::getTeamId($ass->getId(), $user_id, true); + } + } + } + */ + + ilUtil::sendSuccess($this->lng->txt("exc_members_assigned"), true); + } + + $this->ctrl->redirect($this, "members"); + return true; + } + + + /** + * Select assignment + */ + public function selectAssignmentObject() + { + $_GET["ass_id"] = ilUtil::stripSlashes($_POST["ass_id"]); + $this->membersObject(); + } + + /** + * Show Participant + */ + public function showParticipantObject() + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->addSubTabs("participant"); + $this->ctrl->setParameter($this, "ass_id", ""); + + // participant selection + include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); + $ass = ilExAssignment::getAssignmentDataOfExercise($this->exercise->getId()); + $members = $this->exercise->members_obj->getMembers(); + + $members = $GLOBALS['DIC']->access()->filterUserIdsByRbacOrPositionOfCurrentUser( + 'edit_submissions_grades', + 'edit_submissions_grades', + $this->exercise->getRefId(), + $members + ); + + + if (count($members) == 0) { + ilUtil::sendInfo($lng->txt("exc_no_participants")); + return; + } + + $mems = array(); + foreach ($members as $mem_id) { + if (ilObject::_lookupType($mem_id) == "usr") { + include_once("./Services/User/classes/class.ilObjUser.php"); + $name = ilObjUser::_lookupName($mem_id); + if (trim($name["login"]) != "") { // #20073 + $mems[$mem_id] = $name; + } + } + } + + $mems = ilUtil::sortArray($mems, "lastname", "asc", false, true); + + if ($_GET["part_id"] == "" && count($mems) > 0) { + $_GET["part_id"] = key($mems); + } + + $current_participant = $_GET["part_id"]; + + reset($mems); + if (count($mems) > 1) { + $options = array(); + foreach ($mems as $k => $m) { + $options[$k] = + $m["lastname"] . ", " . $m["firstname"] . " [" . $m["login"] . "]"; + } + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $si = new ilSelectInputGUI($this->lng->txt(""), "part_id"); + $si->setOptions($options); + $si->setValue($current_participant); + $ilToolbar->addStickyItem($si); + + include_once("./Services/UIComponent/Button/classes/class.ilSubmitButton.php"); + $button = ilSubmitButton::getInstance(); + $button->setCaption("exc_select_part"); + $button->setCommand("selectParticipant"); + $ilToolbar->addStickyItem($button); + } + + if (count($mems) > 0) { + $this->ctrl->setParameter($this, "vw", self::VIEW_PARTICIPANT); + $this->ctrl->setParameter($this, "part_id", $current_participant); + + $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); + $ilToolbar->addFormButton($lng->txt("download_all_returned_files"), "downloadSubmissions"); + + include_once("./Modules/Exercise/classes/class.ilExParticipantTableGUI.php"); + $part_tab = new ilExParticipantTableGUI( + $this, + "showParticipant", + $this->exercise, + $current_participant + ); + $tpl->setContent($part_tab->getHTML() . + $this->initIndividualDeadlineModal()); + } else { + ilUtil::sendInfo($this->lng->txt("exc_no_assignments_available")); + } + } + + public function showParticipantApplyObject() + { + include_once("./Modules/Exercise/classes/class.ilExParticipantTableGUI.php"); + $exc_tab = new ilExParticipantTableGUI($this, "showParticipant", $this->exercise, $_GET["part_id"]); + $exc_tab->resetOffset(); + $exc_tab->writeFilterToSession(); + + $this->showParticipantObject(); + } + + public function showParticipantResetObject() + { + include_once("./Modules/Exercise/classes/class.ilExParticipantTableGUI.php"); + $exc_tab = new ilExParticipantTableGUI($this, "showParticipant", $this->exercise, $_GET["part_id"]); + $exc_tab->resetOffset(); + $exc_tab->resetFilter(); + + $this->showParticipantObject(); + } + + /** + * Select participant + */ + public function selectParticipantObject() + { + $_GET["part_id"] = ilUtil::stripSlashes($_POST["part_id"]); + $this->showParticipantObject(); + } + + /** + * Show grades overview + */ + public function showGradesOverviewObject() + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->addSubTabs("grades"); + + include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); + $mem_obj = new ilExerciseMembers($this->exercise); + $mems = $mem_obj->getMembers(); + + $mems = $GLOBALS['DIC']->access()->filterUserIdsByRbacOrPositionOfCurrentUser( + 'edit_submissions_grades', + 'edit_submissions_grades', + $this->exercise->getRefId(), + $mems + ); + if (count($mems) > 0) { + $ilToolbar->addButton( + $lng->txt("exc_export_excel"), + $ilCtrl->getLinkTarget($this, "exportExcel") + ); + } + + $this->ctrl->setParameter($this, "vw", self::VIEW_GRADES); + + include_once("./Modules/Exercise/classes/class.ilExGradesTableGUI.php"); + $grades_tab = new ilExGradesTableGUI( + $this, + "showGradesOverview", + $this->exercise, + $mem_obj + ); + $tpl->setContent($grades_tab->getHTML()); + } + + /** + * set feedback status for member and redirect to mail screen + */ + public function redirectFeedbackMailObject() + { + $members = array(); + + if ($_GET["member_id"] != "") { + $submission = new ilExSubmission($this->assignment, $_GET["member_id"]); + $members = $submission->getUserIds(); + } elseif ($members = $this->getMultiActionUserIds()) { + $members = array_keys($members); + } + + if ($members) { + $logins = array(); + foreach ($members as $user_id) { + $member_status = $this->assignment->getMemberStatus($user_id); + $member_status->setFeedback(true); + $member_status->update(); + + $logins[] = ilObjUser::_lookupLogin($user_id); + } + $logins = implode($logins, ","); + + // #16530 - see ilObjCourseGUI::createMailSignature + $sig = chr(13) . chr(10) . chr(13) . chr(10); + $sig .= $this->lng->txt('exc_mail_permanent_link'); + $sig .= chr(13) . chr(10) . chr(13) . chr(10); + include_once './Services/Link/classes/class.ilLink.php'; + $sig .= ilLink::_getLink($this->exercise->getRefId()); + $sig = rawurlencode(base64_encode($sig)); + + require_once 'Services/Mail/classes/class.ilMailFormCall.php'; + ilUtil::redirect(ilMailFormCall::getRedirectTarget( + $this, + $this->getViewBack(), + array(), + array( + 'type' => 'new', + 'rcp_to' => $logins, + ilMailFormCall::SIGNATURE_KEY => $sig + ) + )); + } + } + + /** + * Download all submitted files (of all members). + */ + public function downloadAllObject() + { + $members = array(); + + foreach ($this->exercise->members_obj->getMembers() as $member_id) { + $submission = new ilExSubmission($this->assignment, $member_id); + $submission->updateTutorDownloadTime(); + + // get member object (ilObjUser) + if (ilObject::_exists($member_id)) { + $storage_id = ""; + // adding file metadata + foreach ($submission->getFiles() as $file) { + if ($this->assignment->getAssignmentType()->isSubmissionAssignedToTeam()) { + $storage_id = $file["team_id"]; + } else { + $storage_id = $file["user_id"]; + } + + $members[$storage_id]["files"][$file["returned_id"]] = $file; + } + if ($this->assignment->getAssignmentType()->isSubmissionAssignedToTeam()) { + $name = "Team " . $submission->getTeam()->getId(); + } else { + $tmp_obj = ilObjectFactory::getInstanceByObjId($member_id); + $name = $tmp_obj->getFirstname() . " " . $tmp_obj->getLastname(); + } + if ($storage_id > 0) { + $members[$storage_id]["name"] = $name; + } + unset($tmp_obj); + } + } + + ilExSubmission::downloadAllAssignmentFiles($this->assignment, $members); + } + + protected function getMultiActionUserIds($a_keep_teams = false) + { + // multi-user + if ($this->assignment) { + if (!$_POST["member"]) { + ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); + $this->ctrl->redirect($this, "members"); + } + + foreach (array_keys($_POST["member"]) as $user_id) { + $submission = new ilExSubmission($this->assignment, $user_id); + $tmembers = $submission->getUserIds(); + if (!(bool) $a_keep_teams) { + foreach ($tmembers as $tuser_id) { + $members[$tuser_id] = 1; + } + } else { + if ($tmembers) { + $members[] = $tmembers; + } else { + // no team yet + $members[] = $user_id; + } + } + } + } + // multi-ass + else { + if (!$_POST["ass"]) { + ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); + $this->ctrl->redirect($this, "showParticipant"); + } + + $user_id = $_GET["part_id"]; + + include_once "Modules/Exercise/classes/class.ilExAssignment.php"; + foreach (array_keys($_POST["ass"]) as $ass_id) { + $submission = new ilExSubmission(new ilExAssignment($ass_id), $user_id); + $tmembers = $submission->getUserIds(); + if (!(bool) $a_keep_teams) { + foreach ($tmembers as $tuser_id) { + $members[$ass_id][] = $tuser_id; + } + } else { + if ($tmembers) { + $members[$ass_id][] = $tmembers; + } else { + // no team yet + $members[$ass_id][] = $user_id; + } + } + } + } + + return $members; + } + + /** + * Send assignment per mail to participants + */ + public function sendMembersObject() + { + $members = $this->getMultiActionUserIds(); + + ilUtil::sendSuccess($this->lng->txt("exc_sent"), true); + if ($this->assignment) { + $this->exercise->sendAssignment($this->assignment, array_keys($members)); + $this->ctrl->redirect($this, "members"); + } else { + foreach ($members as $ass_id => $users) { + $this->exercise->sendAssignment(new ilExAssignment($ass_id), $users); + } + $this->ctrl->setParameter($this, "part_id", $_GET["part_id"]); // #17629 + $this->ctrl->redirect($this, "showParticipant"); + } + } + + /** + * Confirm deassigning members + */ + public function confirmDeassignMembersObject() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + $members = $this->getMultiActionUserIds(); + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("exc_msg_sure_to_deassign_participant")); + $cgui->setCancel($lng->txt("cancel"), "members"); + $cgui->setConfirm($lng->txt("remove"), "deassignMembers"); + + include_once("./Services/User/classes/class.ilUserUtil.php"); + foreach ($members as $k => $m) { + $cgui->addItem( + "member[$k]", + $m, + ilUserUtil::getNamePresentation((int) $k, false, false, "", true) + ); + } + + $tpl->setContent($cgui->getHTML()); + } + + /** + * Deassign members from exercise + */ + public function deassignMembersObject() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $members = $this->getMultiActionUserIds(); + + foreach (array_keys($members) as $usr_id) { + $this->exercise->members_obj->deassignMember((int) $usr_id); + } + ilUtil::sendSuccess($lng->txt("exc_msg_participants_removed"), true); + $ilCtrl->redirect($this, "members"); + } + + public function saveCommentsObject() + { + if (!isset($_POST['comments_value'])) { + return; + } - $this->exercise->members_obj->setNoticeForMember($_GET["member_id"], - ilUtil::stripSlashes($_POST["comments_value"])); - ilUtil::sendSuccess($this->lng->txt("exc_members_comments_saved")); - $this->membersObject(); - } - -/** - * Save assignment status (participant view) - */ - function saveStatusParticipantObject(array $a_selected = null) - { - $ilCtrl = $this->ctrl; - - $member_id = (int)$_GET["part_id"]; - $data = array(); - foreach(array_keys($_POST["id"]) as $ass_id) - { - if(is_array($a_selected) && - !in_array($ass_id, $a_selected)) - { - continue; - } - - $data[$ass_id][$member_id] = array( - "status" => ilUtil::stripSlashes($_POST["status"][$ass_id]) - ); - - if(array_key_exists("mark", $_POST)) - { - $data[$ass_id][$member_id]["mark"] = ilUtil::stripSlashes($_POST["mark"][$ass_id]); - } - if(array_key_exists("notice", $_POST)) - { - $data[$ass_id][$member_id]["notice"] = ilUtil::stripSlashes($_POST["notice"][$ass_id]); - } - } - - $ilCtrl->setParameter($this, "part_id", $member_id); // #17629 - $this->saveStatus($data); - } - - - function saveStatusAllObject(array $a_selected = null, $a_redirect = true) - { - $user_ids = (array) array_keys((array) $_POST['id']); - $filtered_user_ids = $GLOBALS['DIC']->access()->filterUserIdsByRbacOrPositionOfCurrentUser( - 'edit_submissions_grades', - 'edit_submissions_grades', - $this->exercise->getRefId(), - $user_ids - ); - - $data = array(); - foreach($filtered_user_ids as $user_id) - { - if (is_array($a_selected) && - !in_array($user_id, $a_selected)) - { - continue; - } - - $data[-1][$user_id] = array( - "status" => ilUtil::stripSlashes($_POST["status"][$user_id]) - ); - - if (array_key_exists("mark", $_POST)) - { - $data[-1][$user_id]["mark"] = ilUtil::stripSlashes($_POST["mark"][$user_id]); - } - if (array_key_exists("notice", $_POST)) - { - $data[-1][$user_id]["notice"] = ilUtil::stripSlashes($_POST["notice"][$user_id]); - } - } - $this->saveStatus($data, $a_redirect); - } - - function saveStatusSelectedObject() - { - $members = $this->getMultiActionUserIds(); - - if($this->assignment) - { - $this->saveStatusAllObject(array_keys($members)); - } - else - { - $this->saveStatusParticipantObject(array_keys($members)); - } - } - - /** - * Save status of selecte members - */ - protected function saveStatus(array $a_data, $a_redirect = true) - { - $ilCtrl = $this->ctrl; - - include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); - - $saved_for = array(); - foreach($a_data as $ass_id => $users) - { - $ass = ($ass_id < 0) - ? $this->assignment - : new ilExAssignment($ass_id); - foreach($users as $user_id => $values) - { - // this will add team members if available - $submission = new ilExSubmission($ass, $user_id); - foreach($submission->getUserIds() as $sub_user_id) - { - $uname = ilObjUser::_lookupName($sub_user_id); - $saved_for[$sub_user_id] = $uname["lastname"].", ".$uname["firstname"]; - - $member_status = $ass->getMemberStatus($sub_user_id); - - // see bug #22566 - $status = $values["status"]; - if ($status == "") - { - $status = self::GRADE_NOT_GRADED; - } - $member_status->setStatus($status); - if(array_key_exists("mark", $values)) - { - $member_status->setMark($values["mark"]); - } - if(array_key_exists("notice", $values)) - { - $member_status->setNotice($values["notice"]); - } - $member_status->update(); - } - } - } - - if (count($saved_for) > 0) - { - $save_for_str = "(".implode($saved_for, " - ").")"; - } - - if ($a_redirect) - { - ilUtil::sendSuccess($this->lng->txt("exc_status_saved") . " " . $save_for_str, true); - $ilCtrl->redirect($this, $this->getViewBack()); - } - } - - /** - * Save comment for learner (asynch) - */ - function saveCommentForLearnersObject() - { - $res = array("result"=>false); - - if($this->ctrl->isAsynch()) - { - $ass_id = (int)$_POST["ass_id"]; - $user_id = (int)$_POST["mem_id"]; - $comment = trim($_POST["comm"]); - - if($ass_id && $user_id) - { - $submission = new ilExSubmission($this->assignment, $user_id); - $user_ids = $submission->getUserIds(); - - $all_members = new ilExerciseMembers($this->exercise); - $all_members = $all_members->getMembers(); - - $reci_ids = array(); - foreach($user_ids as $user_id) - { - if(in_array($user_id, $all_members)) - { - $member_status = $this->assignment->getMemberStatus($user_id); - $member_status->setComment(ilUtil::stripSlashes($comment)); - $member_status->setFeedback(true); - $member_status->update(); - - if(trim($comment)) - { - $reci_ids[] = $user_id; - } - } - } - - if(sizeof($reci_ids)) - { - // send notification - $this->exercise->sendFeedbackFileNotification(null, $reci_ids, - $ass_id, true); - } - - $res = array("result"=>true, "snippet"=>nl2br($comment)); - } - } - - echo(json_encode($res)); - exit(); - } - - /** - * Export as excel - */ - function exportExcelObject() - { - $this->exercise->exportGradesExcel(); - exit; - } - - - // - // TEAM - // - - function createTeamsObject() - { - $ilCtrl = $this->ctrl; - - $members = $this->getMultiActionUserIds(true); - - $new_members = array(); - - include_once "Modules/Exercise/classes/class.ilExAssignmentTeam.php"; - foreach($members as $group) - { - if(is_array($group)) - { - $new_members = array_merge($new_members, $group); - - $first_user = $group; - $first_user = array_shift($first_user); - $team = ilExAssignmentTeam::getInstanceByUserId($this->assignment->getId(), $first_user); - foreach($group as $user_id) - { - $team->removeTeamMember($user_id); - } - } - else - { - $new_members[] = $group; - } - } - - if(sizeof($new_members)) - { - // see ilExSubmissionTeamGUI::addTeamMemberActionObject() - - $first_user = array_shift($new_members); - $team = ilExAssignmentTeam::getInstanceByUserId($this->assignment->getId(), $first_user, true); - if(sizeof($new_members)) - { - foreach($new_members as $user_id) - { - $team->addTeamMember($user_id); - } - } - - // re-evaluate complete team, as some members might have had submitted - $submission = new ilExSubmission($this->assignment, $first_user); - $this->exercise->processExerciseStatus( - $this->assignment, - $team->getMembers(), - $submission->hasSubmitted(), - $submission->validatePeerReviews() - ); - } - - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "members"); - } - - function dissolveTeamsObject() - { - $ilCtrl = $this->ctrl; - - $members = $this->getMultiActionUserIds(true); - - include_once "Modules/Exercise/classes/class.ilExAssignmentTeam.php"; - foreach($members as $group) - { - // if single member - nothing to do - if(is_array($group)) - { - // see ilExSubmissionTeamGUI::removeTeamMemberObject() - - $first_user = $group; - $first_user = array_shift($first_user); - $team = ilExAssignmentTeam::getInstanceByUserId($this->assignment->getId(), $first_user); - foreach($group as $user_id) - { - $team->removeTeamMember($user_id); - } - - // reset ex team members, as any submission is not valid without team - $this->exercise->processExerciseStatus( - $this->assignment, - $group, - false - ); - } - } - - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "members"); - } - - function adoptTeamsFromGroupObject(ilPropertyFormGUI $a_form = null) - { - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs_gui; - $lng = $this->lng; - $tpl = $this->tpl; - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTarget($this, $this->getViewBack())); - - if(!$a_form) - { - $a_form = $this->initGroupForm(); - } - $tpl->setContent($a_form->getHTML()); - } - - protected function initGroupForm() - { - $lng = $this->lng; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setTitle($lng->txt("exc_adopt_group_teams")." - ".$this->assignment->getTitle()); - $form->setFormAction($this->ctrl->getFormAction($this, "createTeamsFromGroups")); - - include_once "Modules/Exercise/classes/class.ilExAssignmentTeam.php"; - include_once "Services/User/classes/class.ilUserUtil.php"; - $all_members = array(); - foreach(ilExAssignmentTeam::getGroupMembersMap($this->exercise->getRefId()) as $grp_id => $group) - { - if(sizeof($group["members"])) - { - $grp_team = new ilCheckboxGroupInputGUI($lng->txt("obj_grp")." \"".$group["title"]."\"", "grpt_".$grp_id); - $grp_value = $options = array(); - foreach($group["members"] as $user_id) - { - $user_name = ilUserUtil::getNamePresentation($user_id, false, false, "", true); - $options[$user_id] = $user_name; - if(!in_array($user_id, $all_members)) - { - $grp_value[] = $user_id; - $all_members[] = $user_id; - } - } - asort($options); - foreach($options as $user_id => $user_name) - { - $grp_team->addOption(new ilCheckboxOption($user_name, $user_id)); - } - $grp_team->setValue($grp_value); - $form->addItem($grp_team); - } - else - { - $grp_team = new ilNonEditableValueGUI($group["title"]); - $grp_team->setValue($lng->txt("exc_adopt_group_teams_no_members")); - $form->addItem($grp_team); - } - } - - if(sizeof($all_members)) - { - $form->addCommandButton("createTeamsFromGroups", $lng->txt("save")); - } - $form->addCommandButton("members", $lng->txt("cancel")); - - return $form; - } - - function createTeamsFromGroupsObject() - { - $lng = $this->lng; - - $form = $this->initGroupForm(); - if($form->checkInput()) - { - include_once "Services/User/classes/class.ilUserUtil.php"; - $map = ilExAssignmentTeam::getGroupMembersMap($this->exercise->getRefId()); - $all_members = $teams = array(); - $valid = true; - foreach(array_keys($map) as $grp_id) - { - $postvar = "grpt_".$grp_id; - $members = $_POST[$postvar]; - if(is_array($members)) - { - $teams[] = $members; - $invalid_team_members = array(); - - foreach($members as $user_id) - { - if(!array_key_exists($user_id, $all_members)) - { - $all_members[$user_id] = $grp_id; - } - else - { - // user is selected in multiple groups - $invalid_team_members[] = $user_id; - } - } - - if(sizeof($invalid_team_members)) - { - $valid = false; - - $alert = array(); - foreach($invalid_team_members as $user_id) - { - $user_name = ilUserUtil::getNamePresentation($user_id, false, false, "", true); - $grp_title = $map[$all_members[$user_id]]["title"]; - $alert[] = sprintf($lng->txt("exc_adopt_group_teams_conflict"), $user_name, $grp_title); - } - $input = $form->getItemByPostVar($postvar); - $input->setAlert(implode("
", $alert)); - } - } - } - if($valid) - { - if(sizeof($teams)) - { - $existing_users = array_keys(ilExAssignmentTeam::getAssignmentTeamMap($this->assignment->getId())); - - // create teams from group selections - $sum = array("added"=>0, "blocked"=>0); - foreach($teams as $members) - { - foreach($members as $user_id) - { - if(!$this->exercise->members_obj->isAssigned($user_id)) - { - $this->exercise->members_obj->assignMember($user_id); - } - - if(!in_array($user_id, $existing_users)) - { - $sum["added"]++; - } - else - { - $sum["blocked"]++; - } - } - - $first = array_shift($members); - $team = ilExAssignmentTeam::getInstanceByUserId($this->assignment->getId(), $first, true); - - // getTeamId() does NOT send notification - // $team->sendNotification($this->exercise->getRefId(), $first, "add"); - - if(sizeof($members)) - { - foreach($members as $user_id) - { - $team->addTeamMember($user_id); - } - } - } - - $mess = array(); - if($sum["added"]) - { - $mess[] = sprintf($lng->txt("exc_adopt_group_teams_added"), $sum["added"]); - } - if($sum["blocked"]) - { - $mess[] = sprintf($lng->txt("exc_adopt_group_teams_blocked"), $sum["blocked"]); - } - if($sum["added"]) - { - ilUtil::sendSuccess(implode(" ", $mess), true); - } - else - { - ilUtil::sendFailure(implode(" ", $mess), true); - } - } - $this->ctrl->redirect($this, "members"); - } - else - { - ilUtil::sendFailure($lng->txt("form_input_not_valid")); - } - } - - $form->setValuesByPost(); - $this->adoptTeamsFromGroupObject($form); - } - - - //// - //// Multi Feedback - //// - - function initMultiFeedbackForm($a_ass_id) - { - $lng = $this->lng; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->addCommandButton("uploadMultiFeedback", $lng->txt("upload")); - $form->addCommandButton("members", $lng->txt("cancel")); - - // multi feedback file - $fi = new ilFileInputGUI($lng->txt("exc_multi_feedback_file"), "mfzip"); - $fi->setSuffixes(array("zip")); - $fi->setRequired(true); - $form->addItem($fi); - - $form->setTitle(ilExAssignment::lookupTitle($a_ass_id)); - $form->setFormAction($this->ctrl->getFormAction($this, "uploadMultiFeedback")); - - return $form; - } - - /** - * Show multi-feedback screen - * - * @param - * @return - */ - function showMultiFeedbackObject(ilPropertyFormGUI $a_form = null) - { - $ilToolbar = $this->toolbar; - $lng = $this->lng; - $tpl = $this->tpl; - - ilUtil::sendInfo($lng->txt("exc_multi_feedb_info")); - - $this->addSubTabs("assignment"); - - // #13719 - include_once("./Services/UIComponent/Button/classes/class.ilLinkButton.php"); - $button = ilLinkButton::getInstance(); - $button->setCaption("exc_download_zip_structure"); - $button->setUrl($this->ctrl->getLinkTarget($this, "downloadMultiFeedbackZip")); - $button->setOmitPreventDoubleSubmission(true); - $ilToolbar->addButtonInstance($button); - - if(!$a_form) - { - $a_form = $this->initMultiFeedbackForm($this->assignment->getId()); - } - - $tpl->setContent($a_form->getHTML()); - } - - /** - * Download multi-feedback structrue file - */ - function downloadMultiFeedbackZipObject() - { - $this->assignment->sendMultiFeedbackStructureFile($this->exercise); - } - - /** - * Upload multi feedback file - */ - function uploadMultiFeedbackObject() - { - // #11983 - $form = $this->initMultiFeedbackForm($this->assignment->getId()); - if($form->checkInput()) - { - try - { - $this->assignment->uploadMultiFeedbackFile(ilUtil::stripSlashesArray($_FILES["mfzip"])); - $this->ctrl->redirect($this, "showMultiFeedbackConfirmationTable"); - } - catch (ilExerciseException $e) - { - ilUtil::sendFailure($e->getMessage(), true); - $this->ctrl->redirect($this, "showMultiFeedback"); - } - } - - $form->setValuesByPost(); - $this->showMultiFeedbackObject($form); - } - - /** - * Show multi feedback confirmation table - * - * @param - * @return - */ - function showMultiFeedbackConfirmationTableObject() - { - $tpl = $this->tpl; - - $this->addSubTabs("assignment"); - - include_once("./Modules/Exercise/classes/class.ilFeedbackConfirmationTable2GUI.php"); - $tab = new ilFeedbackConfirmationTable2GUI($this, "showMultiFeedbackConfirmationTable", $this->assignment); - $tpl->setContent($tab->getHTML()); - } - - /** - * Cancel Multi Feedback - */ - function cancelMultiFeedbackObject() - { - $this->assignment->clearMultiFeedbackDirectory(); - $this->ctrl->redirect($this, "members"); - } - - /** - * Save multi feedback - */ - function saveMultiFeedbackObject() - { - $this->assignment->saveMultiFeedbackFiles($_POST["file"], $this->exercise); - - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "members"); - } - - - // - // individual deadlines - // - - protected function initIndividualDeadlineModal() - { - $lng = $this->lng; - $tpl = $this->tpl; - - // prepare modal+ - include_once "./Services/UIComponent/Modal/classes/class.ilModalGUI.php"; - $modal = ilModalGUI::getInstance(); - $modal->setHeading($lng->txt("exc_individual_deadline")); - $modal->setId("ilExcIDl"); - $modal->setBody('
'); - $modal = $modal->getHTML(); - - $ajax_url = $this->ctrl->getLinkTarget($this, "handleIndividualDeadlineCalls", "", true, false); - - $tpl->addJavaScript("./Modules/Exercise/js/ilExcIDl.js", true, 3); - $tpl->addOnloadCode('il.ExcIDl.init("'.$ajax_url.'");'); - - include_once "Services/Calendar/classes/class.ilCalendarUtil.php"; - ilCalendarUtil::initDateTimePicker(); - - return $modal; - } - - protected function parseIndividualDeadlineData(array $a_data) - { - if($a_data) - { - $map = array(); - $ass_tmp = array(); - foreach($a_data as $item) - { - $item = explode("_", $item); - $ass_id = $item[0]; - $user_id = $item[1]; - - if(!array_key_exists($ass_id, $ass_tmp)) - { - if($this->assignment && - $ass_id == $this->assignment->getId()) - { - $ass_tmp[$ass_id] = $this->assignment; - } - else - { - $ass_tmp[$ass_id] = new ilExAssignment($ass_id); - } - } - - $map[$ass_id][] = $user_id; - } - - return array($map, $ass_tmp); - } - } - - protected function handleIndividualDeadlineCallsObject() - { - $tpl = $this->tpl; - - $this->ctrl->saveParameter($this, "part_id"); - - // we are done - if((bool)$_GET["dn"]) - { - ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); - $this->ctrl->redirect($this, $this->assignment - ? "members" - : "showParticipant"); - } - - include_once "Modules/Exercise/classes/class.ilExAssignment.php"; - - // initial form call - if($_GET["idlid"]) - { - $tmp = $this->parseIndividualDeadlineData(explode(",", $_GET["idlid"])); - if(is_array($tmp)) - { - $form = $this->initIndividualDeadlineForm($tmp[1], $tmp[0]); - echo $form->getHTML(). - $tpl->getOnLoadCodeForAsynch(); - } - } - // form "submit" - else - { - $tmp = array(); - foreach(array_keys($_POST) as $id) - { - if(substr($id, 0, 3) == "dl_") - { - $tmp[] = substr($id, 3); - } - } - $tmp = $this->parseIndividualDeadlineData($tmp); - $ass_map = $tmp[1]; - $users = $tmp[0]; - unset($tmp); - - $form = $this->initIndividualDeadlineForm($ass_map, $users); - $res = array(); - if($valid = $form->checkInput()) - { - foreach($users as $ass_id => $users) - { - $ass = $ass_map[$ass_id]; - - // :TODO: should individual deadlines BEFORE extended be possible? - $dl = new ilDateTime($ass->getDeadline(), IL_CAL_UNIX); - - foreach($users as $user_id) - { - $date_field = $form->getItemByPostVar("dl_".$ass_id."_".$user_id); - if(ilDate::_before($date_field->getDate(), $dl)) - { - $date_field->setAlert(sprintf($this->lng->txt("exc_individual_deadline_before_global"), ilDatePresentation::formatDate($dl))); - $valid = false; - } - else - { - $res[$ass_id][$user_id] = $date_field->getDate(); - } - } - } - } - - if(!$valid) - { - $form->setValuesByPost(); - echo $form->getHTML(). - $tpl->getOnLoadCodeForAsynch(); - } - else - { - foreach($res as $ass_id => $users) - { - $ass = $ass_map[$ass_id]; - - foreach($users as $id => $date) - { - $ass->setIndividualDeadline($id, $date); - } - - $ass->recalculateLateSubmissions(); - } - - echo "ok"; - } - } - - exit(); - } - - protected function initIndividualDeadlineForm(array $a_ass_map, array $ids) - { - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - $form->setName("ilExcIDlForm"); - - include_once "Services/User/classes/class.ilUserUtil.php"; - foreach($ids as $ass_id => $users) - { - $ass = $a_ass_map[$ass_id]; - - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($ass->getTitle()); - $form->addItem($section); - - include_once("./Modules/Exercise/classes/class.ilExAssignmentTeam.php"); - $teams = ilExAssignmentTeam::getInstancesFromMap($ass->getId()); - - $values = $ass->getIndividualDeadlines(); - - foreach($users as $id) - { - // single user - if(is_numeric($id)) - { - $name = ilObjUser::_lookupName($id); - $name = $name["lastname"].", ".$name["firstname"]; - } - // team - else - { - $name = ""; - $team_id = (int)substr($id, 1); - if(array_key_exists($team_id, $teams)) - { - $name = array(); - foreach($teams[$team_id]->getMembers() as $member_id) - { - $uname = ilObjUser::_lookupName($member_id); - $name[] = $uname["lastname"].", ".$uname["firstname"]; - } - asort($name); - $name = implode("
", $name); - } - } - - $dl = new ilDateTimeInputGUI($name, "dl_".$ass_id."_".$id); - $dl->setShowTime(true); - $dl->setRequired(true); - $form->addItem($dl); - - if(array_key_exists($id, $values)) - { - $dl->setDate(new ilDateTime($values[$id], IL_CAL_UNIX)); - } - } - } - - $form->addCommandButton("", $this->lng->txt("save")); - - return $form; - } - - protected function setIndividualDeadlineObject() - { - // this will only get called if no selection - ilUtil::sendFailure($this->lng->txt("select_one")); - - if($this->assignment) - { - $this->membersObject(); - } - else - { - $this->showParticipantObject(); - } - } - - function initFilter() - { - $this->lng->loadLanguageModule("search"); - - $this->toolbar->setFormAction($this->ctrl->getFormAction($this, "listTextAssignment")); - - // Status - - if($_POST["filter_status"]) { - $this->filter["status"] = trim(ilUtil::stripSlashes($_POST["filter_status"])); - } - - $si_status = new ilSelectInputGUI($this->lng->txt("exc_tbl_status"), "filter_status"); - $options = array( - "" => $this->lng->txt("search_any"), - self::GRADE_NOT_GRADED => $this->lng->txt("exc_notgraded"), - self::GRADE_PASSED => $this->lng->txt("exc_passed"), - self::GRADE_FAILED => $this->lng->txt("exc_failed") - ); - $si_status->setOptions($options); - $si_status->setValue($this->filter["status"]); - - $this->toolbar->addInputItem($si_status, true); - - // Submissions and Feedback - #24713 - if($this->assignment->getPeerReview()) { - if ($_POST["filter_feedback"]) { - $this->filter["feedback"] = trim(ilUtil::stripSlashes($_POST["filter_feedback"])); - } else { - $this->filter["feedback"] = "submission_feedback"; - } - - $si_feedback = new ilSelectInputGUI($this->lng->txt("feedback"), "filter_feedback"); - $options = array( - "submission_feedback" => $this->lng->txt("submissions_feedback"), - "submission_only" => $this->lng->txt("submissions_only") - ); - $si_feedback->setOptions($options); - $si_feedback->setValue($this->filter["feedback"]); - - $this->toolbar->addInputItem($si_feedback, true); - } - - //todo: old school here. - include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; - $submit = ilSubmitButton::getInstance(); - $submit->setCaption("filter"); - $submit->setCommand("listTextAssignment"); - $this->toolbar->addButtonInstance($submit); - } + $this->exercise->members_obj->setNoticeForMember( + $_GET["member_id"], + ilUtil::stripSlashes($_POST["comments_value"]) + ); + ilUtil::sendSuccess($this->lng->txt("exc_members_comments_saved")); + $this->membersObject(); + } + + /** + * Save assignment status (participant view) + */ + public function saveStatusParticipantObject(array $a_selected = null) + { + $ilCtrl = $this->ctrl; + + $member_id = (int) $_GET["part_id"]; + $data = array(); + foreach (array_keys($_POST["id"]) as $ass_id) { + if (is_array($a_selected) && + !in_array($ass_id, $a_selected)) { + continue; + } + + $data[$ass_id][$member_id] = array( + "status" => ilUtil::stripSlashes($_POST["status"][$ass_id]) + ); + + if (array_key_exists("mark", $_POST)) { + $data[$ass_id][$member_id]["mark"] = ilUtil::stripSlashes($_POST["mark"][$ass_id]); + } + if (array_key_exists("notice", $_POST)) { + $data[$ass_id][$member_id]["notice"] = ilUtil::stripSlashes($_POST["notice"][$ass_id]); + } + } + + $ilCtrl->setParameter($this, "part_id", $member_id); // #17629 + $this->saveStatus($data); + } + + + public function saveStatusAllObject(array $a_selected = null, $a_redirect = true) + { + $user_ids = (array) array_keys((array) $_POST['id']); + $filtered_user_ids = $GLOBALS['DIC']->access()->filterUserIdsByRbacOrPositionOfCurrentUser( + 'edit_submissions_grades', + 'edit_submissions_grades', + $this->exercise->getRefId(), + $user_ids + ); + + $data = array(); + foreach ($filtered_user_ids as $user_id) { + if (is_array($a_selected) && + !in_array($user_id, $a_selected)) { + continue; + } + + $data[-1][$user_id] = array( + "status" => ilUtil::stripSlashes($_POST["status"][$user_id]) + ); + + if (array_key_exists("mark", $_POST)) { + $data[-1][$user_id]["mark"] = ilUtil::stripSlashes($_POST["mark"][$user_id]); + } + if (array_key_exists("notice", $_POST)) { + $data[-1][$user_id]["notice"] = ilUtil::stripSlashes($_POST["notice"][$user_id]); + } + } + $this->saveStatus($data, $a_redirect); + } + + public function saveStatusSelectedObject() + { + $members = $this->getMultiActionUserIds(); + + if ($this->assignment) { + $this->saveStatusAllObject(array_keys($members)); + } else { + $this->saveStatusParticipantObject(array_keys($members)); + } + } + + /** + * Save status of selecte members + */ + protected function saveStatus(array $a_data, $a_redirect = true) + { + $ilCtrl = $this->ctrl; + + include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); + + $saved_for = array(); + foreach ($a_data as $ass_id => $users) { + $ass = ($ass_id < 0) + ? $this->assignment + : new ilExAssignment($ass_id); + foreach ($users as $user_id => $values) { + // this will add team members if available + $submission = new ilExSubmission($ass, $user_id); + foreach ($submission->getUserIds() as $sub_user_id) { + $uname = ilObjUser::_lookupName($sub_user_id); + $saved_for[$sub_user_id] = $uname["lastname"] . ", " . $uname["firstname"]; + + $member_status = $ass->getMemberStatus($sub_user_id); + + // see bug #22566 + $status = $values["status"]; + if ($status == "") { + $status = self::GRADE_NOT_GRADED; + } + $member_status->setStatus($status); + if (array_key_exists("mark", $values)) { + $member_status->setMark($values["mark"]); + } + if (array_key_exists("notice", $values)) { + $member_status->setNotice($values["notice"]); + } + $member_status->update(); + } + } + } + + if (count($saved_for) > 0) { + $save_for_str = "(" . implode($saved_for, " - ") . ")"; + } + + if ($a_redirect) { + ilUtil::sendSuccess($this->lng->txt("exc_status_saved") . " " . $save_for_str, true); + $ilCtrl->redirect($this, $this->getViewBack()); + } + } + + /** + * Save comment for learner (asynch) + */ + public function saveCommentForLearnersObject() + { + $res = array("result"=>false); + + if ($this->ctrl->isAsynch()) { + $ass_id = (int) $_POST["ass_id"]; + $user_id = (int) $_POST["mem_id"]; + $comment = trim($_POST["comm"]); + + if ($ass_id && $user_id) { + $submission = new ilExSubmission($this->assignment, $user_id); + $user_ids = $submission->getUserIds(); + + $all_members = new ilExerciseMembers($this->exercise); + $all_members = $all_members->getMembers(); + + $reci_ids = array(); + foreach ($user_ids as $user_id) { + if (in_array($user_id, $all_members)) { + $member_status = $this->assignment->getMemberStatus($user_id); + $member_status->setComment(ilUtil::stripSlashes($comment)); + $member_status->setFeedback(true); + $member_status->update(); + + if (trim($comment)) { + $reci_ids[] = $user_id; + } + } + } + + if (sizeof($reci_ids)) { + // send notification + $this->exercise->sendFeedbackFileNotification( + null, + $reci_ids, + $ass_id, + true + ); + } + + $res = array("result"=>true, "snippet"=>nl2br($comment)); + } + } + + echo(json_encode($res)); + exit(); + } + + /** + * Export as excel + */ + public function exportExcelObject() + { + $this->exercise->exportGradesExcel(); + exit; + } + + + // + // TEAM + // + + public function createTeamsObject() + { + $ilCtrl = $this->ctrl; + + $members = $this->getMultiActionUserIds(true); + + $new_members = array(); + + include_once "Modules/Exercise/classes/class.ilExAssignmentTeam.php"; + foreach ($members as $group) { + if (is_array($group)) { + $new_members = array_merge($new_members, $group); + + $first_user = $group; + $first_user = array_shift($first_user); + $team = ilExAssignmentTeam::getInstanceByUserId($this->assignment->getId(), $first_user); + foreach ($group as $user_id) { + $team->removeTeamMember($user_id); + } + } else { + $new_members[] = $group; + } + } + + if (sizeof($new_members)) { + // see ilExSubmissionTeamGUI::addTeamMemberActionObject() + + $first_user = array_shift($new_members); + $team = ilExAssignmentTeam::getInstanceByUserId($this->assignment->getId(), $first_user, true); + if (sizeof($new_members)) { + foreach ($new_members as $user_id) { + $team->addTeamMember($user_id); + } + } + + // re-evaluate complete team, as some members might have had submitted + $submission = new ilExSubmission($this->assignment, $first_user); + $this->exercise->processExerciseStatus( + $this->assignment, + $team->getMembers(), + $submission->hasSubmitted(), + $submission->validatePeerReviews() + ); + } + + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "members"); + } + + public function dissolveTeamsObject() + { + $ilCtrl = $this->ctrl; + + $members = $this->getMultiActionUserIds(true); + + include_once "Modules/Exercise/classes/class.ilExAssignmentTeam.php"; + foreach ($members as $group) { + // if single member - nothing to do + if (is_array($group)) { + // see ilExSubmissionTeamGUI::removeTeamMemberObject() + + $first_user = $group; + $first_user = array_shift($first_user); + $team = ilExAssignmentTeam::getInstanceByUserId($this->assignment->getId(), $first_user); + foreach ($group as $user_id) { + $team->removeTeamMember($user_id); + } + + // reset ex team members, as any submission is not valid without team + $this->exercise->processExerciseStatus( + $this->assignment, + $group, + false + ); + } + } + + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "members"); + } + + public function adoptTeamsFromGroupObject(ilPropertyFormGUI $a_form = null) + { + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs_gui; + $lng = $this->lng; + $tpl = $this->tpl; + + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, $this->getViewBack()) + ); + + if (!$a_form) { + $a_form = $this->initGroupForm(); + } + $tpl->setContent($a_form->getHTML()); + } + + protected function initGroupForm() + { + $lng = $this->lng; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setTitle($lng->txt("exc_adopt_group_teams") . " - " . $this->assignment->getTitle()); + $form->setFormAction($this->ctrl->getFormAction($this, "createTeamsFromGroups")); + + include_once "Modules/Exercise/classes/class.ilExAssignmentTeam.php"; + include_once "Services/User/classes/class.ilUserUtil.php"; + $all_members = array(); + foreach (ilExAssignmentTeam::getGroupMembersMap($this->exercise->getRefId()) as $grp_id => $group) { + if (sizeof($group["members"])) { + $grp_team = new ilCheckboxGroupInputGUI($lng->txt("obj_grp") . " \"" . $group["title"] . "\"", "grpt_" . $grp_id); + $grp_value = $options = array(); + foreach ($group["members"] as $user_id) { + $user_name = ilUserUtil::getNamePresentation($user_id, false, false, "", true); + $options[$user_id] = $user_name; + if (!in_array($user_id, $all_members)) { + $grp_value[] = $user_id; + $all_members[] = $user_id; + } + } + asort($options); + foreach ($options as $user_id => $user_name) { + $grp_team->addOption(new ilCheckboxOption($user_name, $user_id)); + } + $grp_team->setValue($grp_value); + $form->addItem($grp_team); + } else { + $grp_team = new ilNonEditableValueGUI($group["title"]); + $grp_team->setValue($lng->txt("exc_adopt_group_teams_no_members")); + $form->addItem($grp_team); + } + } + + if (sizeof($all_members)) { + $form->addCommandButton("createTeamsFromGroups", $lng->txt("save")); + } + $form->addCommandButton("members", $lng->txt("cancel")); + + return $form; + } + + public function createTeamsFromGroupsObject() + { + $lng = $this->lng; + + $form = $this->initGroupForm(); + if ($form->checkInput()) { + include_once "Services/User/classes/class.ilUserUtil.php"; + $map = ilExAssignmentTeam::getGroupMembersMap($this->exercise->getRefId()); + $all_members = $teams = array(); + $valid = true; + foreach (array_keys($map) as $grp_id) { + $postvar = "grpt_" . $grp_id; + $members = $_POST[$postvar]; + if (is_array($members)) { + $teams[] = $members; + $invalid_team_members = array(); + + foreach ($members as $user_id) { + if (!array_key_exists($user_id, $all_members)) { + $all_members[$user_id] = $grp_id; + } else { + // user is selected in multiple groups + $invalid_team_members[] = $user_id; + } + } + + if (sizeof($invalid_team_members)) { + $valid = false; + + $alert = array(); + foreach ($invalid_team_members as $user_id) { + $user_name = ilUserUtil::getNamePresentation($user_id, false, false, "", true); + $grp_title = $map[$all_members[$user_id]]["title"]; + $alert[] = sprintf($lng->txt("exc_adopt_group_teams_conflict"), $user_name, $grp_title); + } + $input = $form->getItemByPostVar($postvar); + $input->setAlert(implode("
", $alert)); + } + } + } + if ($valid) { + if (sizeof($teams)) { + $existing_users = array_keys(ilExAssignmentTeam::getAssignmentTeamMap($this->assignment->getId())); + + // create teams from group selections + $sum = array("added"=>0, "blocked"=>0); + foreach ($teams as $members) { + foreach ($members as $user_id) { + if (!$this->exercise->members_obj->isAssigned($user_id)) { + $this->exercise->members_obj->assignMember($user_id); + } + + if (!in_array($user_id, $existing_users)) { + $sum["added"]++; + } else { + $sum["blocked"]++; + } + } + + $first = array_shift($members); + $team = ilExAssignmentTeam::getInstanceByUserId($this->assignment->getId(), $first, true); + + // getTeamId() does NOT send notification + // $team->sendNotification($this->exercise->getRefId(), $first, "add"); + + if (sizeof($members)) { + foreach ($members as $user_id) { + $team->addTeamMember($user_id); + } + } + } + + $mess = array(); + if ($sum["added"]) { + $mess[] = sprintf($lng->txt("exc_adopt_group_teams_added"), $sum["added"]); + } + if ($sum["blocked"]) { + $mess[] = sprintf($lng->txt("exc_adopt_group_teams_blocked"), $sum["blocked"]); + } + if ($sum["added"]) { + ilUtil::sendSuccess(implode(" ", $mess), true); + } else { + ilUtil::sendFailure(implode(" ", $mess), true); + } + } + $this->ctrl->redirect($this, "members"); + } else { + ilUtil::sendFailure($lng->txt("form_input_not_valid")); + } + } + + $form->setValuesByPost(); + $this->adoptTeamsFromGroupObject($form); + } + + + //// + //// Multi Feedback + //// + + public function initMultiFeedbackForm($a_ass_id) + { + $lng = $this->lng; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->addCommandButton("uploadMultiFeedback", $lng->txt("upload")); + $form->addCommandButton("members", $lng->txt("cancel")); + + // multi feedback file + $fi = new ilFileInputGUI($lng->txt("exc_multi_feedback_file"), "mfzip"); + $fi->setSuffixes(array("zip")); + $fi->setRequired(true); + $form->addItem($fi); + + $form->setTitle(ilExAssignment::lookupTitle($a_ass_id)); + $form->setFormAction($this->ctrl->getFormAction($this, "uploadMultiFeedback")); + + return $form; + } + + /** + * Show multi-feedback screen + * + * @param + * @return + */ + public function showMultiFeedbackObject(ilPropertyFormGUI $a_form = null) + { + $ilToolbar = $this->toolbar; + $lng = $this->lng; + $tpl = $this->tpl; + + ilUtil::sendInfo($lng->txt("exc_multi_feedb_info")); + + $this->addSubTabs("assignment"); + + // #13719 + include_once("./Services/UIComponent/Button/classes/class.ilLinkButton.php"); + $button = ilLinkButton::getInstance(); + $button->setCaption("exc_download_zip_structure"); + $button->setUrl($this->ctrl->getLinkTarget($this, "downloadMultiFeedbackZip")); + $button->setOmitPreventDoubleSubmission(true); + $ilToolbar->addButtonInstance($button); + + if (!$a_form) { + $a_form = $this->initMultiFeedbackForm($this->assignment->getId()); + } + + $tpl->setContent($a_form->getHTML()); + } + + /** + * Download multi-feedback structrue file + */ + public function downloadMultiFeedbackZipObject() + { + $this->assignment->sendMultiFeedbackStructureFile($this->exercise); + } + + /** + * Upload multi feedback file + */ + public function uploadMultiFeedbackObject() + { + // #11983 + $form = $this->initMultiFeedbackForm($this->assignment->getId()); + if ($form->checkInput()) { + try { + $this->assignment->uploadMultiFeedbackFile(ilUtil::stripSlashesArray($_FILES["mfzip"])); + $this->ctrl->redirect($this, "showMultiFeedbackConfirmationTable"); + } catch (ilExerciseException $e) { + ilUtil::sendFailure($e->getMessage(), true); + $this->ctrl->redirect($this, "showMultiFeedback"); + } + } + + $form->setValuesByPost(); + $this->showMultiFeedbackObject($form); + } + + /** + * Show multi feedback confirmation table + * + * @param + * @return + */ + public function showMultiFeedbackConfirmationTableObject() + { + $tpl = $this->tpl; + + $this->addSubTabs("assignment"); + + include_once("./Modules/Exercise/classes/class.ilFeedbackConfirmationTable2GUI.php"); + $tab = new ilFeedbackConfirmationTable2GUI($this, "showMultiFeedbackConfirmationTable", $this->assignment); + $tpl->setContent($tab->getHTML()); + } + + /** + * Cancel Multi Feedback + */ + public function cancelMultiFeedbackObject() + { + $this->assignment->clearMultiFeedbackDirectory(); + $this->ctrl->redirect($this, "members"); + } + + /** + * Save multi feedback + */ + public function saveMultiFeedbackObject() + { + $this->assignment->saveMultiFeedbackFiles($_POST["file"], $this->exercise); + + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "members"); + } + + + // + // individual deadlines + // + + protected function initIndividualDeadlineModal() + { + $lng = $this->lng; + $tpl = $this->tpl; + + // prepare modal+ + include_once "./Services/UIComponent/Modal/classes/class.ilModalGUI.php"; + $modal = ilModalGUI::getInstance(); + $modal->setHeading($lng->txt("exc_individual_deadline")); + $modal->setId("ilExcIDl"); + $modal->setBody('
'); + $modal = $modal->getHTML(); + + $ajax_url = $this->ctrl->getLinkTarget($this, "handleIndividualDeadlineCalls", "", true, false); + + $tpl->addJavaScript("./Modules/Exercise/js/ilExcIDl.js", true, 3); + $tpl->addOnloadCode('il.ExcIDl.init("' . $ajax_url . '");'); + + include_once "Services/Calendar/classes/class.ilCalendarUtil.php"; + ilCalendarUtil::initDateTimePicker(); + + return $modal; + } + + protected function parseIndividualDeadlineData(array $a_data) + { + if ($a_data) { + $map = array(); + $ass_tmp = array(); + foreach ($a_data as $item) { + $item = explode("_", $item); + $ass_id = $item[0]; + $user_id = $item[1]; + + if (!array_key_exists($ass_id, $ass_tmp)) { + if ($this->assignment && + $ass_id == $this->assignment->getId()) { + $ass_tmp[$ass_id] = $this->assignment; + } else { + $ass_tmp[$ass_id] = new ilExAssignment($ass_id); + } + } + + $map[$ass_id][] = $user_id; + } + + return array($map, $ass_tmp); + } + } + + protected function handleIndividualDeadlineCallsObject() + { + $tpl = $this->tpl; + + $this->ctrl->saveParameter($this, "part_id"); + + // we are done + if ((bool) $_GET["dn"]) { + ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); + $this->ctrl->redirect($this, $this->assignment + ? "members" + : "showParticipant"); + } + + include_once "Modules/Exercise/classes/class.ilExAssignment.php"; + + // initial form call + if ($_GET["idlid"]) { + $tmp = $this->parseIndividualDeadlineData(explode(",", $_GET["idlid"])); + if (is_array($tmp)) { + $form = $this->initIndividualDeadlineForm($tmp[1], $tmp[0]); + echo $form->getHTML() . + $tpl->getOnLoadCodeForAsynch(); + } + } + // form "submit" + else { + $tmp = array(); + foreach (array_keys($_POST) as $id) { + if (substr($id, 0, 3) == "dl_") { + $tmp[] = substr($id, 3); + } + } + $tmp = $this->parseIndividualDeadlineData($tmp); + $ass_map = $tmp[1]; + $users = $tmp[0]; + unset($tmp); + + $form = $this->initIndividualDeadlineForm($ass_map, $users); + $res = array(); + if ($valid = $form->checkInput()) { + foreach ($users as $ass_id => $users) { + $ass = $ass_map[$ass_id]; + + // :TODO: should individual deadlines BEFORE extended be possible? + $dl = new ilDateTime($ass->getDeadline(), IL_CAL_UNIX); + + foreach ($users as $user_id) { + $date_field = $form->getItemByPostVar("dl_" . $ass_id . "_" . $user_id); + if (ilDate::_before($date_field->getDate(), $dl)) { + $date_field->setAlert(sprintf($this->lng->txt("exc_individual_deadline_before_global"), ilDatePresentation::formatDate($dl))); + $valid = false; + } else { + $res[$ass_id][$user_id] = $date_field->getDate(); + } + } + } + } + + if (!$valid) { + $form->setValuesByPost(); + echo $form->getHTML() . + $tpl->getOnLoadCodeForAsynch(); + } else { + foreach ($res as $ass_id => $users) { + $ass = $ass_map[$ass_id]; + + foreach ($users as $id => $date) { + $ass->setIndividualDeadline($id, $date); + } + + $ass->recalculateLateSubmissions(); + } + + echo "ok"; + } + } + + exit(); + } + + protected function initIndividualDeadlineForm(array $a_ass_map, array $ids) + { + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this)); + $form->setName("ilExcIDlForm"); + + include_once "Services/User/classes/class.ilUserUtil.php"; + foreach ($ids as $ass_id => $users) { + $ass = $a_ass_map[$ass_id]; + + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($ass->getTitle()); + $form->addItem($section); + + include_once("./Modules/Exercise/classes/class.ilExAssignmentTeam.php"); + $teams = ilExAssignmentTeam::getInstancesFromMap($ass->getId()); + + $values = $ass->getIndividualDeadlines(); + + foreach ($users as $id) { + // single user + if (is_numeric($id)) { + $name = ilObjUser::_lookupName($id); + $name = $name["lastname"] . ", " . $name["firstname"]; + } + // team + else { + $name = ""; + $team_id = (int) substr($id, 1); + if (array_key_exists($team_id, $teams)) { + $name = array(); + foreach ($teams[$team_id]->getMembers() as $member_id) { + $uname = ilObjUser::_lookupName($member_id); + $name[] = $uname["lastname"] . ", " . $uname["firstname"]; + } + asort($name); + $name = implode("
", $name); + } + } + + $dl = new ilDateTimeInputGUI($name, "dl_" . $ass_id . "_" . $id); + $dl->setShowTime(true); + $dl->setRequired(true); + $form->addItem($dl); + + if (array_key_exists($id, $values)) { + $dl->setDate(new ilDateTime($values[$id], IL_CAL_UNIX)); + } + } + } + + $form->addCommandButton("", $this->lng->txt("save")); + + return $form; + } + + protected function setIndividualDeadlineObject() + { + // this will only get called if no selection + ilUtil::sendFailure($this->lng->txt("select_one")); + + if ($this->assignment) { + $this->membersObject(); + } else { + $this->showParticipantObject(); + } + } + + public function initFilter() + { + $this->lng->loadLanguageModule("search"); + + $this->toolbar->setFormAction($this->ctrl->getFormAction($this, "listTextAssignment")); + + // Status + + if ($_POST["filter_status"]) { + $this->filter["status"] = trim(ilUtil::stripSlashes($_POST["filter_status"])); + } + + $si_status = new ilSelectInputGUI($this->lng->txt("exc_tbl_status"), "filter_status"); + $options = array( + "" => $this->lng->txt("search_any"), + self::GRADE_NOT_GRADED => $this->lng->txt("exc_notgraded"), + self::GRADE_PASSED => $this->lng->txt("exc_passed"), + self::GRADE_FAILED => $this->lng->txt("exc_failed") + ); + $si_status->setOptions($options); + $si_status->setValue($this->filter["status"]); + + $this->toolbar->addInputItem($si_status, true); + + // Submissions and Feedback + #24713 + if ($this->assignment->getPeerReview()) { + if ($_POST["filter_feedback"]) { + $this->filter["feedback"] = trim(ilUtil::stripSlashes($_POST["filter_feedback"])); + } else { + $this->filter["feedback"] = "submission_feedback"; + } + + $si_feedback = new ilSelectInputGUI($this->lng->txt("feedback"), "filter_feedback"); + $options = array( + "submission_feedback" => $this->lng->txt("submissions_feedback"), + "submission_only" => $this->lng->txt("submissions_only") + ); + $si_feedback->setOptions($options); + $si_feedback->setValue($this->filter["feedback"]); + + $this->toolbar->addInputItem($si_feedback, true); + } + + //todo: old school here. + include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; + $submit = ilSubmitButton::getInstance(); + $submit->setCaption("filter"); + $submit->setCommand("listTextAssignment"); + $this->toolbar->addButtonInstance($submit); + } } - diff --git a/Modules/Exercise/classes/class.ilExerciseMemberTableGUI.php b/Modules/Exercise/classes/class.ilExerciseMemberTableGUI.php index 17a3e8b9214ff2c985f773ee67b0f83aa23f774d..06421b47753f6f2d149eb0e52749a6894c5f0f98 100644 --- a/Modules/Exercise/classes/class.ilExerciseMemberTableGUI.php +++ b/Modules/Exercise/classes/class.ilExerciseMemberTableGUI.php @@ -14,287 +14,240 @@ include_once("./Modules/Exercise/classes/class.ilExerciseSubmissionTableGUI.php" */ class ilExerciseMemberTableGUI extends ilExerciseSubmissionTableGUI { - /** - * @var ilExAssignment - */ - protected $ass; + /** + * @var ilExAssignment + */ + protected $ass; - protected $teams = array(); + protected $teams = array(); - function __construct($a_parent_obj, $a_parent_cmd, ilObjExercise $a_exc, $a_item_id) - { - /** @var ilCtrl $ilCtrl */ - global $ilCtrl; - //var_dump($ilCtrl->getCmd()); exit; - parent::__construct($a_parent_obj, $a_parent_cmd, $a_exc, $a_item_id); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj, "saveStatusAll")); - } + public function __construct($a_parent_obj, $a_parent_cmd, ilObjExercise $a_exc, $a_item_id) + { + /** @var ilCtrl $ilCtrl */ + global $ilCtrl; + //var_dump($ilCtrl->getCmd()); exit; + parent::__construct($a_parent_obj, $a_parent_cmd, $a_exc, $a_item_id); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj, "saveStatusAll")); + } - protected function initMode($a_item_id) - { - $lng = $this->lng; - - $this->mode = self::MODE_BY_ASSIGNMENT; - - // global id for all exercises - $this->setId("exc_mem"); - - include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); - $this->ass = new ilExAssignment($a_item_id); - - $this->setTitle($lng->txt("exc_assignment").": ".$this->ass->getTitle()); - $this->setSelectAllCheckbox("member"); - } - - protected function parseData() - { - $this->addCommandButton("saveStatusAll", $this->lng->txt("exc_save_all")); - - $tmp_data = $this->ass->getMemberListData(); - - // filter user access - $usr_ids = array_keys($tmp_data); - $filtered_usr_ids = $GLOBALS['DIC']->access()->filterUserIdsByRbacOrPositionOfCurrentUser( - 'etit_submissions_grades', - 'edit_submissions_grades', - $this->exc->getRefId(), - $usr_ids - ); - $data = []; - foreach($filtered_usr_ids as $usr_id) - { - $data[$usr_id] = $tmp_data[$usr_id]; - } - - - $idl = $this->ass->getIndividualDeadlines(); - $calc_deadline = $this->ass->getCalculatedDeadlines(); - - // team upload? (1 row == 1 team) - if($this->ass->hasTeam()) - { - $teams = ilExAssignmentTeam::getInstancesFromMap($this->ass->getId()); - $team_map = ilExAssignmentTeam::getAssignmentTeamMap($this->ass->getId()); - - $tmp = array(); - - foreach($data as $item) - { - // filter - if($this->filter["status"] && - $item["status"] != $this->filter["status"]) - { - continue; - } - - $team_id = $team_map[$item["usr_id"]]; - - if(!$team_id) - { - // #11957 - $team_id = "nty".$item["usr_id"]; - } - - if(!isset($tmp[$team_id])) - { - $tmp[$team_id] = $item; - - if(is_numeric($team_id)) - { - $tmp[$team_id]["submission_obj"] = new ilExSubmission($this->ass, $item["usr_id"], $teams[$team_id]); - } - else - { - // ilExSubmission should not try to auto-load - $tmp[$team_id]["submission_obj"] = new ilExSubmission($this->ass, $item["usr_id"], new ilExAssignmentTeam()); - } - } - - $tmp[$team_id]["team"][$item["usr_id"]] = $item["name"]; - - if(is_numeric($team_id)) - { - $idl_team_id = "t".$team_id; - if(array_key_exists($idl_team_id, $idl)) - { - $tmp[$team_id]["idl"] = $idl[$idl_team_id]; - } + protected function initMode($a_item_id) + { + $lng = $this->lng; + + $this->mode = self::MODE_BY_ASSIGNMENT; + + // global id for all exercises + $this->setId("exc_mem"); + + include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); + $this->ass = new ilExAssignment($a_item_id); + + $this->setTitle($lng->txt("exc_assignment") . ": " . $this->ass->getTitle()); + $this->setSelectAllCheckbox("member"); + } + + protected function parseData() + { + $this->addCommandButton("saveStatusAll", $this->lng->txt("exc_save_all")); + + $tmp_data = $this->ass->getMemberListData(); + + // filter user access + $usr_ids = array_keys($tmp_data); + $filtered_usr_ids = $GLOBALS['DIC']->access()->filterUserIdsByRbacOrPositionOfCurrentUser( + 'etit_submissions_grades', + 'edit_submissions_grades', + $this->exc->getRefId(), + $usr_ids + ); + $data = []; + foreach ($filtered_usr_ids as $usr_id) { + $data[$usr_id] = $tmp_data[$usr_id]; + } + + + $idl = $this->ass->getIndividualDeadlines(); + $calc_deadline = $this->ass->getCalculatedDeadlines(); + + // team upload? (1 row == 1 team) + if ($this->ass->hasTeam()) { + $teams = ilExAssignmentTeam::getInstancesFromMap($this->ass->getId()); + $team_map = ilExAssignmentTeam::getAssignmentTeamMap($this->ass->getId()); + + $tmp = array(); + + foreach ($data as $item) { + // filter + if ($this->filter["status"] && + $item["status"] != $this->filter["status"]) { + continue; + } + + $team_id = $team_map[$item["usr_id"]]; + + if (!$team_id) { + // #11957 + $team_id = "nty" . $item["usr_id"]; + } + + if (!isset($tmp[$team_id])) { + $tmp[$team_id] = $item; + + if (is_numeric($team_id)) { + $tmp[$team_id]["submission_obj"] = new ilExSubmission($this->ass, $item["usr_id"], $teams[$team_id]); + } else { + // ilExSubmission should not try to auto-load + $tmp[$team_id]["submission_obj"] = new ilExSubmission($this->ass, $item["usr_id"], new ilExAssignmentTeam()); + } + } + + $tmp[$team_id]["team"][$item["usr_id"]] = $item["name"]; + + if (is_numeric($team_id)) { + $idl_team_id = "t" . $team_id; + if (array_key_exists($idl_team_id, $idl)) { + $tmp[$team_id]["idl"] = $idl[$idl_team_id]; + } - if (isset($calc_deadline["team"][$team_id])) - { - $tmp[$team_id]["calc_deadline"] = $calc_deadline["team"][$team_id]["calculated_deadline"]; - } - } - else - { - if (isset($calc_deadline["user"][$item["usr_id"]])) - { - $tmp["nty".$item["usr_id"]]["calc_deadline"] = $calc_deadline["user"][$item["usr_id"]]["calculated_deadline"]; - } - } - } - - // filter (team-wide) - if($this->filter["name"]) - { - foreach($tmp as $idx => $item) - { - if(!stristr(implode("", $item["team"]), $this->filter["name"])) - { - unset($tmp[$idx]); - } - } - } - if($this->filter["subm"]) - { - foreach($tmp as $idx => $item) - { - $submission = $item["submission_obj"]; - if($this->filter["subm"] == "y" && - !$submission->getLastSubmission()) - { - unset($tmp[$idx]); - } - else if($this->filter["subm"] == "n" && - $submission->getLastSubmission()) - { - unset($tmp[$idx]); - } - } - - - } - - $data = $tmp; - unset($tmp); - } - else - { - foreach($data as $idx => $item) - { - // filter - if($this->filter["status"] && - $item["status"] != $this->filter["status"]) - { - unset($data[$idx]); - continue; - } - if($this->filter["name"] && - !stristr($item["name"], $this->filter["name"]) && - !stristr($item["login"], $this->filter["name"])) - { - unset($data[$idx]); - continue; - } - - $data[$idx]["submission_obj"] = new ilExSubmission($this->ass, $item["usr_id"]); - - // filter - if($this->filter["subm"]) - { - $submission = $data[$idx]["submission_obj"]; - if($this->filter["subm"] == "y" && - !$submission->getLastSubmission()) - { - unset($data[$idx]); - continue; - } - else if($this->filter["subm"] == "n" && - $submission->getLastSubmission()) - { - unset($data[$idx]); - continue; - } - } - - if(array_key_exists($item["usr_id"], $idl)) - { - $data[$idx]["idl"] = $idl[$item["usr_id"]]; - } + if (isset($calc_deadline["team"][$team_id])) { + $tmp[$team_id]["calc_deadline"] = $calc_deadline["team"][$team_id]["calculated_deadline"]; + } + } else { + if (isset($calc_deadline["user"][$item["usr_id"]])) { + $tmp["nty" . $item["usr_id"]]["calc_deadline"] = $calc_deadline["user"][$item["usr_id"]]["calculated_deadline"]; + } + } + } + + // filter (team-wide) + if ($this->filter["name"]) { + foreach ($tmp as $idx => $item) { + if (!stristr(implode("", $item["team"]), $this->filter["name"])) { + unset($tmp[$idx]); + } + } + } + if ($this->filter["subm"]) { + foreach ($tmp as $idx => $item) { + $submission = $item["submission_obj"]; + if ($this->filter["subm"] == "y" && + !$submission->getLastSubmission()) { + unset($tmp[$idx]); + } elseif ($this->filter["subm"] == "n" && + $submission->getLastSubmission()) { + unset($tmp[$idx]); + } + } + } + + $data = $tmp; + unset($tmp); + } else { + foreach ($data as $idx => $item) { + // filter + if ($this->filter["status"] && + $item["status"] != $this->filter["status"]) { + unset($data[$idx]); + continue; + } + if ($this->filter["name"] && + !stristr($item["name"], $this->filter["name"]) && + !stristr($item["login"], $this->filter["name"])) { + unset($data[$idx]); + continue; + } + + $data[$idx]["submission_obj"] = new ilExSubmission($this->ass, $item["usr_id"]); + + // filter + if ($this->filter["subm"]) { + $submission = $data[$idx]["submission_obj"]; + if ($this->filter["subm"] == "y" && + !$submission->getLastSubmission()) { + unset($data[$idx]); + continue; + } elseif ($this->filter["subm"] == "n" && + $submission->getLastSubmission()) { + unset($data[$idx]); + continue; + } + } + + if (array_key_exists($item["usr_id"], $idl)) { + $data[$idx]["idl"] = $idl[$item["usr_id"]]; + } - if (isset($calc_deadline["user"][$item["usr_id"]])) - { - $data[$idx]["calc_deadline"] = $calc_deadline["user"][$item["usr_id"]]["calculated_deadline"]; - } + if (isset($calc_deadline["user"][$item["usr_id"]])) { + $data[$idx]["calc_deadline"] = $calc_deadline["user"][$item["usr_id"]]["calculated_deadline"]; + } + } + } + + return $data; + } + + protected function getModeColumns() + { + $cols = array(); + + if (!$this->ass->hasTeam()) { + $selected = $this->getSelectedColumns(); + + if (in_array("image", $selected)) { + $cols["image"] = array($this->lng->txt("image")); + } + + $cols["name"] = array($this->lng->txt("name"), "name"); + + if (in_array("login", $selected)) { + $cols["login"] = array($this->lng->txt("login"), "login"); + } + } else { + $cols["name"] = array($this->lng->txt("exc_team")); + } + + return $cols; + } + + protected function parseModeColumns() + { + $cols = array(); - } - } - - return $data; - } - - protected function getModeColumns() - { - $cols = array(); - - if(!$this->ass->hasTeam()) - { - $selected = $this->getSelectedColumns(); - - if(in_array("image", $selected)) - { - $cols["image"] = array($this->lng->txt("image")); - } - - $cols["name"] = array($this->lng->txt("name"), "name"); - - if(in_array("login", $selected)) - { - $cols["login"] = array($this->lng->txt("login"), "login"); - } - } - else - { - $cols["name"] = array($this->lng->txt("exc_team")); - } - - return $cols; - } - - protected function parseModeColumns() - { - $cols = array(); + if (!$this->ass->hasTeam()) { + $cols["image"] = array($this->lng->txt("image")); + $cols["name"] = array($this->lng->txt("name"), "name"); + $cols["login"] = array($this->lng->txt("login"), "login"); + } else { + $cols["name"] = array($this->lng->txt("exc_tbl_team")); + } + + if ($this->ass->hasActiveIDl()) { + $cols["idl"] = array($this->lng->txt("exc_tbl_individual_deadline"), "idl"); + } - if(!$this->ass->hasTeam()) - { - $cols["image"] = array($this->lng->txt("image")); - $cols["name"] = array($this->lng->txt("name"), "name"); - $cols["login"] = array($this->lng->txt("login"), "login"); - } - else - { - $cols["name"] = array($this->lng->txt("exc_tbl_team")); - } - - if($this->ass->hasActiveIDl()) - { - $cols["idl"] = array($this->lng->txt("exc_tbl_individual_deadline"), "idl"); - } + if ($this->ass->getDeadlineMode() == ilExAssignment::DEADLINE_RELATIVE && $this->ass->getRelativeDeadline()) { + $cols["calc_deadline"] = array($this->lng->txt("exc_tbl_calculated_deadline"), "calc_deadline"); + } - if($this->ass->getDeadlineMode() == ilExAssignment::DEADLINE_RELATIVE && $this->ass->getRelativeDeadline()) - { - $cols["calc_deadline"] = array($this->lng->txt("exc_tbl_calculated_deadline"), "calc_deadline"); - } + return $cols; + } + + protected function fillRow($member) + { + $ilCtrl = $this->ctrl; - return $cols; - } - - protected function fillRow($member) - { - $ilCtrl = $this->ctrl; + $member_id = $member["usr_id"]; + + $ilCtrl->setParameter($this->parent_obj, "ass_id", $this->ass->getId()); + $ilCtrl->setParameter($this->parent_obj, "member_id", $member_id); + + // multi-select id + $this->tpl->setVariable("NAME_ID", "member"); + $this->tpl->setVariable("VAL_ID", $member_id); - $member_id = $member["usr_id"]; - - $ilCtrl->setParameter($this->parent_obj, "ass_id", $this->ass->getId()); - $ilCtrl->setParameter($this->parent_obj, "member_id", $member_id); - - // multi-select id - $this->tpl->setVariable("NAME_ID", "member"); - $this->tpl->setVariable("VAL_ID", $member_id); - - $this->parseRow($member_id, $this->ass, $member); - - $ilCtrl->setParameter($this->parent_obj, "ass_id", $this->ass->getId()); // #17140 - $ilCtrl->setParameter($this->parent_obj, "member_id", ""); - } -} \ No newline at end of file + $this->parseRow($member_id, $this->ass, $member); + + $ilCtrl->setParameter($this->parent_obj, "ass_id", $this->ass->getId()); // #17140 + $ilCtrl->setParameter($this->parent_obj, "member_id", ""); + } +} diff --git a/Modules/Exercise/classes/class.ilExerciseMembers.php b/Modules/Exercise/classes/class.ilExerciseMembers.php index 25bb92c190c2ef46505da746c0af4c829437c6aa..aae5100f9262a69735fbc22c202c8f57d07abc88 100755 --- a/Modules/Exercise/classes/class.ilExerciseMembers.php +++ b/Modules/Exercise/classes/class.ilExerciseMembers.php @@ -11,469 +11,451 @@ */ class ilExerciseMembers { - /** - * @var ilDB - */ - protected $db; - - var $ref_id; - var $obj_id; - var $members; - var $status; -// var $status_feedback; -// var $status_sent; -// var $status_returned; -// var $notice; - - function __construct($a_exc) - { - global $DIC; - - $this->db = $DIC->database(); - $this->exc = $a_exc; - $this->obj_id = $a_exc->getId(); - $this->ref_id = $a_exc->getRefId(); - $this->read(); - } - - /** - * Get exercise ref id - */ - function getRefId() - { - return $this->ref_id; - } - - /** - * Get exercise id - */ - function getObjId() - { - return $this->obj_id; - } - - /** - * Set exercise id - */ - function setObjId($a_obj_id) - { - $this->obj_id = $a_obj_id; - } - - /** - * Get members array - */ - function getMembers() - { - return $this->members ? $this->members : array(); - } - - /** - * Set members array - */ - function setMembers($a_members) - { - $this->members = $a_members; - } - - /** - * Assign a user to the exercise - * - * @param int $a_usr_id user id - */ - function assignMember($a_usr_id) - { - $ilDB = $this->db; - - if($this->exc->hasAddToDesktop()) - { - $tmp_user = ilObjectFactory::getInstanceByObjId($a_usr_id); - $tmp_user->addDesktopItem($this->getRefId(),"exc"); - } - - $ilDB->manipulate("DELETE FROM exc_members ". - "WHERE obj_id = ".$ilDB->quote($this->getObjId(), "integer")." ". - "AND usr_id = ".$ilDB->quote($a_usr_id, "integer")." "); - -// @todo: some of this fields may not be needed anymore - $ilDB->manipulateF("INSERT INTO exc_members (obj_id, usr_id, status, sent, feedback) ". - " VALUES (%s,%s,%s,%s,%s)", - array("integer", "integer", "text", "integer", "integer"), - array($this->getObjId(), $a_usr_id, 'notgraded', 0, 0)); - - include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); - ilExAssignment::createNewUserRecords($a_usr_id, $this->getObjId()); - - $this->read(); - - include_once("./Services/Tracking/classes/class.ilLPStatusWrapper.php"); - ilLPStatusWrapper::_updateStatus($this->getObjId(), $a_usr_id); - - return true; - } - - /** - * Is user assigned to exercise? - */ - function isAssigned($a_id) - { - return in_array($a_id,$this->getMembers()); - } - - /** - * Assign members to exercise - */ - function assignMembers($a_members) - { - $assigned = 0; - if(is_array($a_members)) - { - foreach($a_members as $member) - { - if(!$this->isAssigned($member)) - { - $this->assignMember($member); - } - else - { - ++$assigned; - } - } - } - if($assigned == count($a_members)) - { - return false; - } - else - { - return true; - } - } - - /** - * Detaches a user from an exercise - * - * @param int $a_usr_id user id - */ - function deassignMember($a_usr_id) - { - $ilDB = $this->db; - - $tmp_user = ilObjectFactory::getInstanceByObjId($a_usr_id); - $tmp_user->dropDesktopItem($this->getRefId(),"exc"); - - $query = "DELETE FROM exc_members ". - "WHERE obj_id = ".$ilDB->quote($this->getObjId(), "integer")." ". - "AND usr_id = ".$ilDB->quote($a_usr_id, "integer")." "; - - $ilDB->manipulate($query); - - $this->read(); - - include_once("./Services/Tracking/classes/class.ilLPStatusWrapper.php"); - ilLPStatusWrapper::_updateStatus($this->getObjId(), $a_usr_id); - - // delete all delivered files of the member - include_once("./Modules/Exercise/classes/class.ilExSubmission.php"); - ilExSubmission::deleteUser($this->exc->getId(), $a_usr_id); - -// @todo: delete all assignment associations (and their files) - - return false; - } - - /** - * Deassign members - */ - function deassignMembers($a_members) - { - if(is_array($a_members)) - { - foreach($a_members as $member) - { - $this->deassignMember($member); - } - } - else - { - return false; - } - } - - /** - * Read all members - */ - function read() - { - $ilDB = $this->db; - - $tmp_arr_members = array(); - - $query = "SELECT * FROM exc_members ". - "WHERE obj_id = ".$ilDB->quote($this->getObjId(), "integer"); - - $res = $ilDB->query($query); - while($row = $ilDB->fetchObject($res)) - { - if (ilObject::_lookupType($row->usr_id) == "usr") { + /** + * @var ilDB + */ + protected $db; + + public $ref_id; + public $obj_id; + public $members; + public $status; + // var $status_feedback; + // var $status_sent; + // var $status_returned; + // var $notice; + + public function __construct($a_exc) + { + global $DIC; + + $this->db = $DIC->database(); + $this->exc = $a_exc; + $this->obj_id = $a_exc->getId(); + $this->ref_id = $a_exc->getRefId(); + $this->read(); + } + + /** + * Get exercise ref id + */ + public function getRefId() + { + return $this->ref_id; + } + + /** + * Get exercise id + */ + public function getObjId() + { + return $this->obj_id; + } + + /** + * Set exercise id + */ + public function setObjId($a_obj_id) + { + $this->obj_id = $a_obj_id; + } + + /** + * Get members array + */ + public function getMembers() + { + return $this->members ? $this->members : array(); + } + + /** + * Set members array + */ + public function setMembers($a_members) + { + $this->members = $a_members; + } + + /** + * Assign a user to the exercise + * + * @param int $a_usr_id user id + */ + public function assignMember($a_usr_id) + { + $ilDB = $this->db; + + if ($this->exc->hasAddToDesktop()) { + $tmp_user = ilObjectFactory::getInstanceByObjId($a_usr_id); + $tmp_user->addDesktopItem($this->getRefId(), "exc"); + } + + $ilDB->manipulate("DELETE FROM exc_members " . + "WHERE obj_id = " . $ilDB->quote($this->getObjId(), "integer") . " " . + "AND usr_id = " . $ilDB->quote($a_usr_id, "integer") . " "); + + // @todo: some of this fields may not be needed anymore + $ilDB->manipulateF( + "INSERT INTO exc_members (obj_id, usr_id, status, sent, feedback) " . + " VALUES (%s,%s,%s,%s,%s)", + array("integer", "integer", "text", "integer", "integer"), + array($this->getObjId(), $a_usr_id, 'notgraded', 0, 0) + ); + + include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); + ilExAssignment::createNewUserRecords($a_usr_id, $this->getObjId()); + + $this->read(); + + include_once("./Services/Tracking/classes/class.ilLPStatusWrapper.php"); + ilLPStatusWrapper::_updateStatus($this->getObjId(), $a_usr_id); + + return true; + } + + /** + * Is user assigned to exercise? + */ + public function isAssigned($a_id) + { + return in_array($a_id, $this->getMembers()); + } + + /** + * Assign members to exercise + */ + public function assignMembers($a_members) + { + $assigned = 0; + if (is_array($a_members)) { + foreach ($a_members as $member) { + if (!$this->isAssigned($member)) { + $this->assignMember($member); + } else { + ++$assigned; + } + } + } + if ($assigned == count($a_members)) { + return false; + } else { + return true; + } + } + + /** + * Detaches a user from an exercise + * + * @param int $a_usr_id user id + */ + public function deassignMember($a_usr_id) + { + $ilDB = $this->db; + + $tmp_user = ilObjectFactory::getInstanceByObjId($a_usr_id); + $tmp_user->dropDesktopItem($this->getRefId(), "exc"); + + $query = "DELETE FROM exc_members " . + "WHERE obj_id = " . $ilDB->quote($this->getObjId(), "integer") . " " . + "AND usr_id = " . $ilDB->quote($a_usr_id, "integer") . " "; + + $ilDB->manipulate($query); + + $this->read(); + + include_once("./Services/Tracking/classes/class.ilLPStatusWrapper.php"); + ilLPStatusWrapper::_updateStatus($this->getObjId(), $a_usr_id); + + // delete all delivered files of the member + include_once("./Modules/Exercise/classes/class.ilExSubmission.php"); + ilExSubmission::deleteUser($this->exc->getId(), $a_usr_id); + + // @todo: delete all assignment associations (and their files) + + return false; + } + + /** + * Deassign members + */ + public function deassignMembers($a_members) + { + if (is_array($a_members)) { + foreach ($a_members as $member) { + $this->deassignMember($member); + } + } else { + return false; + } + } + + /** + * Read all members + */ + public function read() + { + $ilDB = $this->db; + + $tmp_arr_members = array(); + + $query = "SELECT * FROM exc_members " . + "WHERE obj_id = " . $ilDB->quote($this->getObjId(), "integer"); + + $res = $ilDB->query($query); + while ($row = $ilDB->fetchObject($res)) { + if (ilObject::_lookupType($row->usr_id) == "usr") { $tmp_arr_members[] = $row->usr_id; } - } - $this->setMembers($tmp_arr_members); - - return true; - } - -// @todo: clone also assignments - function ilClone($a_new_id) - { - $ilDB = $this->db; - - $data = array(); - - $query = "SELECT * FROM exc_members ". - "WHERE obj_id = ".$ilDB->quote($this->getObjId(), "integer"); - - $res = $ilDB->query($query); - while($row = $ilDB->fetchObject($res)) - { - $data[] = array("usr_id" => $row->usr_id, - "notice" => $row->notice, - "returned" => $row->returned, - "status" => $row->status, - "sent" => $row->sent, - "feedback" => $row->feedback - ); - } - foreach($data as $row) - { - $ilDB->manipulateF("INSERT INTO exc_members ". - " (obj_id, usr_id, notice, returned, status, feedback, sent) VALUES ". - " (%s,%s,%s,%s,%s,%s,%s)", - array ("integer", "integer", "text", "integer", "text", "integer", "integer"), - array ($a_new_id, $row["usr_id"], $row["notice"], (int) $row["returned"], - $row["status"], (int) $row["feedback"], (int) $row["sent"]) - ); - - include_once("./Services/Tracking/classes/class.ilLPStatusWrapper.php"); - ilLPStatusWrapper::_updateStatus($a_new_id, $row["usr_id"]); - } - return true; - } - -// @todo: delete also assignments - function delete() - { - $ilDB = $this->db; - - $query = "DELETE FROM exc_members WHERE obj_id = ". - $ilDB->quote($this->getObjId(), "integer"); - $ilDB->manipulate($query); - - include_once("./Services/Tracking/classes/class.ilLPStatusWrapper.php"); - ilLPStatusWrapper::_refreshStatus($this->getObjId()); - - return true; - } - - static function _getMembers($a_obj_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - // #14963 - see ilExAssignment::getMemberListData() - $query = "SELECT DISTINCT(excm.usr_id) ud". - " FROM exc_members excm". - " JOIN object_data od ON (od.obj_id = excm.usr_id)". - " WHERE excm.obj_id = ".$ilDB->quote($a_obj_id, "integer"). - " AND od.type = ".$ilDB->quote("usr", "text"); - - $res = $ilDB->query($query); - while($row = $ilDB->fetchObject($res)) - { - $usr_ids[] = $row->ud; - } - - return $usr_ids ? $usr_ids : array(); - } - - /** - * Lookup current status (notgraded|passed|failed) - * - * This information is determined by the assignment status and saved - * redundtantly in this table for performance reasons. - * - * @param int $a_obj_id exercise id - * @param int $a_user_id member id - * @return mixed false (if user is no member) or notgraded|passed|failed - */ - static function _lookupStatus($a_obj_id, $a_user_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT status FROM exc_members ". - "WHERE obj_id = ".$ilDB->quote($a_obj_id, "integer"). - " AND usr_id = ".$ilDB->quote($a_user_id, "integer"); - - $res = $ilDB->query($query); - if($row = $ilDB->fetchAssoc($res)) - { - return $row["status"]; - } - - return false; - } - - /** - * Write user status - * - * This information is determined by the assignment status and saved - * redundtantly in this table for performance reasons. - * See ilObjExercise->updateUserStatus(). - * - * @param int exercise id - * @param int user id - * @param text status - */ - static function _writeStatus($a_obj_id, $a_user_id, $a_status) - { - global $DIC; - - $ilDB = $DIC->database(); - - $ilDB->manipulate("UPDATE exc_members SET ". - " status = ".$ilDB->quote($a_status, "text"). - " WHERE obj_id = ".$ilDB->quote($a_obj_id, "integer"). - " AND usr_id = ".$ilDB->quote($a_user_id, "integer") - ); - - include_once("./Services/Tracking/classes/class.ilLPStatusWrapper.php"); - ilLPStatusWrapper::_updateStatus($a_obj_id, $a_user_id); - } - - /** - * Write returned status - * - * The returned status is initially 0. If the first file is returned - * by a user for any assignment of the exercise, the returned status - * is set to 1 and it will stay that way, even if this file is deleted again. - * -> learning progress uses this to determine "in progress" status - * - * @param int exercise id - * @param int user id - * @param text status - */ - static function _writeReturned($a_obj_id, $a_user_id, $a_status) - { - global $DIC; - - $ilDB = $DIC->database(); - - $ilDB->manipulate("UPDATE exc_members SET ". - " returned = ".$ilDB->quote($a_status, "integer"). - " WHERE obj_id = ".$ilDB->quote($a_obj_id, "integer"). - " AND usr_id = ".$ilDB->quote($a_user_id, "integer") - ); - - include_once("./Services/Tracking/classes/class.ilLPStatusWrapper.php"); - ilLPStatusWrapper::_updateStatus($a_obj_id, $a_user_id); - } - - - // - // LP - // - - /** - * Get returned status for all members (if they have anything returned for - * any assignment) - */ - static function _getReturned($a_obj_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT DISTINCT(usr_id) as ud FROM exc_members ". - "WHERE obj_id = ".$ilDB->quote($a_obj_id, "integer")." ". - "AND returned = 1"; - - $res = $ilDB->query($query); - while($row = $ilDB->fetchObject($res)) - { - $usr_ids[] = $row->ud; - } - - return $usr_ids ? $usr_ids : array(); - } - - /** - * Has user returned anything in any assignment? - * - * @param integer object id - * @param integer user id - * @return boolean true/false - */ - static function _hasReturned($a_obj_id, $a_user_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT DISTINCT(usr_id) FROM exc_members WHERE ". - " obj_id = ".$ilDB->quote($a_obj_id, "integer")." AND ". - " returned = ".$ilDB->quote(1, "integer")." AND ". - " usr_id = ".$ilDB->quote($a_user_id, "integer") - ); - if ($rec = $ilDB->fetchAssoc($set)) - { - return true; - } - return false; - } - - /** - * Get all users that passed the exercise - */ - static function _getPassedUsers($a_obj_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT DISTINCT(usr_id) FROM exc_members ". - "WHERE obj_id = ".$ilDB->quote($a_obj_id, "integer")." ". - "AND status = ".$ilDB->quote("passed", "text"); - $res = $ilDB->query($query); - while($row = $ilDB->fetchObject($res)) - { - $usr_ids[] = $row->usr_id; - } - return $usr_ids ? $usr_ids : array(); - } - - /** - * Get all users that failed the exercise - */ - static function _getFailedUsers($a_obj_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT DISTINCT(usr_id) FROM exc_members ". - "WHERE obj_id = ".$ilDB->quote($a_obj_id, "integer")." ". - "AND status = ".$ilDB->quote("failed", "text"); - $res = $ilDB->query($query); - while($row = $ilDB->fetchObject($res)) - { - $usr_ids[] = $row->usr_id; - } - return $usr_ids ? $usr_ids : array(); - } - + } + $this->setMembers($tmp_arr_members); + + return true; + } + + // @todo: clone also assignments + public function ilClone($a_new_id) + { + $ilDB = $this->db; + + $data = array(); + + $query = "SELECT * FROM exc_members " . + "WHERE obj_id = " . $ilDB->quote($this->getObjId(), "integer"); + + $res = $ilDB->query($query); + while ($row = $ilDB->fetchObject($res)) { + $data[] = array("usr_id" => $row->usr_id, + "notice" => $row->notice, + "returned" => $row->returned, + "status" => $row->status, + "sent" => $row->sent, + "feedback" => $row->feedback + ); + } + foreach ($data as $row) { + $ilDB->manipulateF( + "INSERT INTO exc_members " . + " (obj_id, usr_id, notice, returned, status, feedback, sent) VALUES " . + " (%s,%s,%s,%s,%s,%s,%s)", + array("integer", "integer", "text", "integer", "text", "integer", "integer"), + array($a_new_id, $row["usr_id"], $row["notice"], (int) $row["returned"], + $row["status"], (int) $row["feedback"], (int) $row["sent"]) + ); + + include_once("./Services/Tracking/classes/class.ilLPStatusWrapper.php"); + ilLPStatusWrapper::_updateStatus($a_new_id, $row["usr_id"]); + } + return true; + } + + // @todo: delete also assignments + public function delete() + { + $ilDB = $this->db; + + $query = "DELETE FROM exc_members WHERE obj_id = " . + $ilDB->quote($this->getObjId(), "integer"); + $ilDB->manipulate($query); + + include_once("./Services/Tracking/classes/class.ilLPStatusWrapper.php"); + ilLPStatusWrapper::_refreshStatus($this->getObjId()); + + return true; + } + + public static function _getMembers($a_obj_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + // #14963 - see ilExAssignment::getMemberListData() + $query = "SELECT DISTINCT(excm.usr_id) ud" . + " FROM exc_members excm" . + " JOIN object_data od ON (od.obj_id = excm.usr_id)" . + " WHERE excm.obj_id = " . $ilDB->quote($a_obj_id, "integer") . + " AND od.type = " . $ilDB->quote("usr", "text"); + + $res = $ilDB->query($query); + while ($row = $ilDB->fetchObject($res)) { + $usr_ids[] = $row->ud; + } + + return $usr_ids ? $usr_ids : array(); + } + + /** + * Lookup current status (notgraded|passed|failed) + * + * This information is determined by the assignment status and saved + * redundtantly in this table for performance reasons. + * + * @param int $a_obj_id exercise id + * @param int $a_user_id member id + * @return mixed false (if user is no member) or notgraded|passed|failed + */ + public static function _lookupStatus($a_obj_id, $a_user_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT status FROM exc_members " . + "WHERE obj_id = " . $ilDB->quote($a_obj_id, "integer") . + " AND usr_id = " . $ilDB->quote($a_user_id, "integer"); + + $res = $ilDB->query($query); + if ($row = $ilDB->fetchAssoc($res)) { + return $row["status"]; + } + + return false; + } + + /** + * Write user status + * + * This information is determined by the assignment status and saved + * redundtantly in this table for performance reasons. + * See ilObjExercise->updateUserStatus(). + * + * @param int exercise id + * @param int user id + * @param text status + */ + public static function _writeStatus($a_obj_id, $a_user_id, $a_status) + { + global $DIC; + + $ilDB = $DIC->database(); + + $ilDB->manipulate( + "UPDATE exc_members SET " . + " status = " . $ilDB->quote($a_status, "text") . + " WHERE obj_id = " . $ilDB->quote($a_obj_id, "integer") . + " AND usr_id = " . $ilDB->quote($a_user_id, "integer") + ); + + include_once("./Services/Tracking/classes/class.ilLPStatusWrapper.php"); + ilLPStatusWrapper::_updateStatus($a_obj_id, $a_user_id); + } + + /** + * Write returned status + * + * The returned status is initially 0. If the first file is returned + * by a user for any assignment of the exercise, the returned status + * is set to 1 and it will stay that way, even if this file is deleted again. + * -> learning progress uses this to determine "in progress" status + * + * @param int exercise id + * @param int user id + * @param text status + */ + public static function _writeReturned($a_obj_id, $a_user_id, $a_status) + { + global $DIC; + + $ilDB = $DIC->database(); + + $ilDB->manipulate( + "UPDATE exc_members SET " . + " returned = " . $ilDB->quote($a_status, "integer") . + " WHERE obj_id = " . $ilDB->quote($a_obj_id, "integer") . + " AND usr_id = " . $ilDB->quote($a_user_id, "integer") + ); + + include_once("./Services/Tracking/classes/class.ilLPStatusWrapper.php"); + ilLPStatusWrapper::_updateStatus($a_obj_id, $a_user_id); + } + + + // + // LP + // + + /** + * Get returned status for all members (if they have anything returned for + * any assignment) + */ + public static function _getReturned($a_obj_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT DISTINCT(usr_id) as ud FROM exc_members " . + "WHERE obj_id = " . $ilDB->quote($a_obj_id, "integer") . " " . + "AND returned = 1"; + + $res = $ilDB->query($query); + while ($row = $ilDB->fetchObject($res)) { + $usr_ids[] = $row->ud; + } + + return $usr_ids ? $usr_ids : array(); + } + + /** + * Has user returned anything in any assignment? + * + * @param integer object id + * @param integer user id + * @return boolean true/false + */ + public static function _hasReturned($a_obj_id, $a_user_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT DISTINCT(usr_id) FROM exc_members WHERE " . + " obj_id = " . $ilDB->quote($a_obj_id, "integer") . " AND " . + " returned = " . $ilDB->quote(1, "integer") . " AND " . + " usr_id = " . $ilDB->quote($a_user_id, "integer") + ); + if ($rec = $ilDB->fetchAssoc($set)) { + return true; + } + return false; + } + + /** + * Get all users that passed the exercise + */ + public static function _getPassedUsers($a_obj_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT DISTINCT(usr_id) FROM exc_members " . + "WHERE obj_id = " . $ilDB->quote($a_obj_id, "integer") . " " . + "AND status = " . $ilDB->quote("passed", "text"); + $res = $ilDB->query($query); + while ($row = $ilDB->fetchObject($res)) { + $usr_ids[] = $row->usr_id; + } + return $usr_ids ? $usr_ids : array(); + } + + /** + * Get all users that failed the exercise + */ + public static function _getFailedUsers($a_obj_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT DISTINCT(usr_id) FROM exc_members " . + "WHERE obj_id = " . $ilDB->quote($a_obj_id, "integer") . " " . + "AND status = " . $ilDB->quote("failed", "text"); + $res = $ilDB->query($query); + while ($row = $ilDB->fetchObject($res)) { + $usr_ids[] = $row->usr_id; + } + return $usr_ids ? $usr_ids : array(); + } } //END class.ilObjExercise -?> diff --git a/Modules/Exercise/classes/class.ilExerciseMembersFilter.php b/Modules/Exercise/classes/class.ilExerciseMembersFilter.php index 589ce51a512fddf83f427be73b55005a01926825..e8808316ea1a569b91b2d16640e1d71fde944170 100644 --- a/Modules/Exercise/classes/class.ilExerciseMembersFilter.php +++ b/Modules/Exercise/classes/class.ilExerciseMembersFilter.php @@ -11,70 +11,68 @@ */ class ilExerciseMembersFilter { - /** - * @var \ilAccessHandler - */ - protected $members; + /** + * @var \ilAccessHandler + */ + protected $members; - /** - * @var \ILIAS\DI\RBACServices - */ - private $access; + /** + * @var \ILIAS\DI\RBACServices + */ + private $access; - /** - * @var int - */ - protected $exercise_ref_id; + /** + * @var int + */ + protected $exercise_ref_id; - /** - * @var int - */ - protected $user_id; + /** + * @var int + */ + protected $user_id; - /** - * Constructor - * - * @param int $a_user_id User id of the executioner, can come from CRON JOBS - * @param int $a_exc_ref_id - * @param array $a_participants_ids - */ - public function __construct(int $a_exc_ref_id, array $a_participants_ids, int $a_user_id) - { - global $DIC; + /** + * Constructor + * + * @param int $a_user_id User id of the executioner, can come from CRON JOBS + * @param int $a_exc_ref_id + * @param array $a_participants_ids + */ + public function __construct(int $a_exc_ref_id, array $a_participants_ids, int $a_user_id) + { + global $DIC; - $this->access = $DIC->access(); - if($a_user_id) { - $this->user_id = $a_user_id; - } - else{ - $this->user_id = $DIC->user()->getId(); - } + $this->access = $DIC->access(); + if ($a_user_id) { + $this->user_id = $a_user_id; + } else { + $this->user_id = $DIC->user()->getId(); + } - $this->exercise_ref_id = $a_exc_ref_id; - $this->members = $a_participants_ids; - } + $this->exercise_ref_id = $a_exc_ref_id; + $this->members = $a_participants_ids; + } - /** - * Filter manageable members by position or rbac access - * @return int[] - */ - public function filterParticipantsByAccess() : array - { - if($this->access->checkAccessOfUser( - $this->user_id, - 'edit_submissions_grades', - '', - $this->exercise_ref_id - )) - { - // if access by rbac granted => return all - return $this->members; - } - return $this->access->filterUserIdsByPositionOfUser( - $this->user_id, - 'edit_submissions_grades', - $this->exercise_ref_id, - $this->members - ); - } -} \ No newline at end of file + /** + * Filter manageable members by position or rbac access + * @return int[] + */ + public function filterParticipantsByAccess() : array + { + if ($this->access->checkAccessOfUser( + $this->user_id, + 'edit_submissions_grades', + '', + $this->exercise_ref_id + )) { + // if access by rbac granted => return all + return $this->members; + } + return $this->access->filterUserIdsByPositionOfUser( + $this->user_id, + 'edit_submissions_grades', + $this->exercise_ref_id, + $this->members + ); + } +} diff --git a/Modules/Exercise/classes/class.ilExerciseSubmissionTableGUI.php b/Modules/Exercise/classes/class.ilExerciseSubmissionTableGUI.php index 46f8c30b6e2f2cad4e82557ec4f4381c09349f6c..27e503b79b17f109b1a9f6486c5e0482528567a1 100644 --- a/Modules/Exercise/classes/class.ilExerciseSubmissionTableGUI.php +++ b/Modules/Exercise/classes/class.ilExerciseSubmissionTableGUI.php @@ -7,7 +7,7 @@ include_once("./Modules/Exercise/classes/class.ilExAssignmentTeam.php"); include_once("./Services/UIComponent/Modal/classes/class.ilModalGUI.php"); /** - * Exercise submission table + * Exercise submission table * * @author Jörg Lützenkirchen * @version $Id$ @@ -15,619 +15,573 @@ include_once("./Services/UIComponent/Modal/classes/class.ilModalGUI.php"); * @ingroup ModulesExercise */ abstract class ilExerciseSubmissionTableGUI extends ilTable2GUI -{ - /** - * @var ilAccessHandler - */ - protected $access; +{ + /** + * @var ilAccessHandler + */ + protected $access; - protected $exc; // [ilObjExercise] - protected $mode; // [int] - protected $filter; // [array] - protected $comment_modals = array(); // [array] - - const MODE_BY_ASSIGNMENT = 1; - const MODE_BY_USER = 2; - - // needs PH P5.6 for array support - protected $cols_mandatory = array("name", "status"); - protected $cols_default = array("login", "submission_date", "idl", "calc_deadline"); - protected $cols_order = array("image", "name", "login", "team_members", - "sent_time", "submission", "calc_deadline", "idl", "status", "mark", "status_time", - "feedback_time", "comment", "notice"); - - /** - * Constructor - * - * @param string $a_parent_obj - * @param string $a_parent_cmd - * @param ilObjExercise $a_exc - * @param int $a_item_id - * @return self - */ - function __construct($a_parent_obj, $a_parent_cmd, ilObjExercise $a_exc, $a_item_id) - { - global $DIC; + protected $exc; // [ilObjExercise] + protected $mode; // [int] + protected $filter; // [array] + protected $comment_modals = array(); // [array] + + const MODE_BY_ASSIGNMENT = 1; + const MODE_BY_USER = 2; + + // needs PH P5.6 for array support + protected $cols_mandatory = array("name", "status"); + protected $cols_default = array("login", "submission_date", "idl", "calc_deadline"); + protected $cols_order = array("image", "name", "login", "team_members", + "sent_time", "submission", "calc_deadline", "idl", "status", "mark", "status_time", + "feedback_time", "comment", "notice"); + + /** + * Constructor + * + * @param string $a_parent_obj + * @param string $a_parent_cmd + * @param ilObjExercise $a_exc + * @param int $a_item_id + * @return self + */ + public function __construct($a_parent_obj, $a_parent_cmd, ilObjExercise $a_exc, $a_item_id) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->access = $DIC->access(); - $this->tpl = $DIC["tpl"]; - $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->access = $DIC->access(); + $this->tpl = $DIC["tpl"]; + $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - - $this->exc = $a_exc; - - $this->initMode($a_item_id); - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setShowTemplates(true); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.exc_members_row.html", "Modules/Exercise"); + $ilCtrl = $DIC->ctrl(); + + $this->exc = $a_exc; + + $this->initMode($a_item_id); + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setShowTemplates(true); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.exc_members_row.html", "Modules/Exercise"); - #25100 - if($this->mode == self::MODE_BY_ASSIGNMENT) { - $this->setDefaultOrderField("name"); - $this->setDefaultOrderDirection("asc"); - } - - - // columns - - $this->addColumn("", "", "1", true); - - $selected = $this->getSelectedColumns(); - $columns = $this->parseColumns(); - foreach($this->cols_order as $id) - { - if(in_array($id, $this->cols_mandatory) || - in_array($id, $selected)) - { - if(array_key_exists($id, $columns)) - { - $col = $columns[$id]; - $this->addColumn($col[0], $col[1]); - } - } - } - - $this->addColumn($this->lng->txt("actions")); - - - // multi actions - - $this->addMultiCommand("saveStatusSelected", $this->lng->txt("exc_save_selected")); - - $this->setFormName("ilExcIDlForm"); + #25100 + if ($this->mode == self::MODE_BY_ASSIGNMENT) { + $this->setDefaultOrderField("name"); + $this->setDefaultOrderDirection("asc"); + } + + + // columns + + $this->addColumn("", "", "1", true); + + $selected = $this->getSelectedColumns(); + $columns = $this->parseColumns(); + foreach ($this->cols_order as $id) { + if (in_array($id, $this->cols_mandatory) || + in_array($id, $selected)) { + if (array_key_exists($id, $columns)) { + $col = $columns[$id]; + $this->addColumn($col[0], $col[1]); + } + } + } + + $this->addColumn($this->lng->txt("actions")); + + + // multi actions + + $this->addMultiCommand("saveStatusSelected", $this->lng->txt("exc_save_selected")); + + $this->setFormName("ilExcIDlForm"); - // see 0021530 and parseRow here with similar action per user - if ($this->mode == self::MODE_BY_ASSIGNMENT && - $this->ass->hasActiveIDl() && - !$this->ass->hasReadOnlyIDl()) - { - $this->addMultiCommand("setIndividualDeadline", $this->lng->txt("exc_individual_deadline_action")); - } - - if($this->exc->hasTutorFeedbackMail() && - $this->mode == self::MODE_BY_ASSIGNMENT) - { - $this->addMultiCommand("redirectFeedbackMail", $this->lng->txt("exc_tbl_action_feedback_mail")); - } - - $this->addMultiCommand("sendMembers", $this->lng->txt("exc_send_assignment")); - - if($this->mode == self::MODE_BY_ASSIGNMENT && - $this->ass && - $this->ass->hasTeam()) - { - $this->addMultiCommand("createTeams", $this->lng->txt("exc_team_multi_create")); - $this->addMultiCommand("dissolveTeams", $this->lng->txt("exc_team_multi_dissolve")); - } - - if($this->mode == self::MODE_BY_ASSIGNMENT) - { - $this->addMultiCommand("confirmDeassignMembers", $this->lng->txt("exc_deassign_members")); - } - - $this->setFilterCommand($this->getParentCmd()."Apply"); - $this->setResetCommand($this->getParentCmd()."Reset"); - - $this->initFilter(); - $this->setData($this->parseData()); - - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - } - - function initFilter() - { - if($this->mode == self::MODE_BY_ASSIGNMENT) - { - $item = $this->addFilterItemByMetaType("flt_name", self::FILTER_TEXT, false, $this->lng->txt("name")." / ".$this->lng->txt("login")); - $this->filter["name"] = $item->getValue(); - } - - $this->lng->loadLanguageModule("search"); - $options = array( - "" => $this->lng->txt("search_any"), - "notgraded" => $this->lng->txt("exc_notgraded"), - "passed" => $this->lng->txt("exc_passed"), - "failed" => $this->lng->txt("exc_failed") - ); - $item = $this->addFilterItemByMetaType("flt_status", self::FILTER_SELECT, false, $this->lng->txt("exc_tbl_status")); - $item->setOptions($options); - $this->filter["status"] = $item->getValue(); - - $options = array( - "" => $this->lng->txt("search_any"), - "y" => $this->lng->txt("exc_tbl_filter_has_submission"), - "n" => $this->lng->txt("exc_tbl_filter_has_no_submission") - ); - $item = $this->addFilterItemByMetaType("flt_subm", self::FILTER_SELECT, false, $this->lng->txt("exc_tbl_filter_submission")); - $item->setOptions($options); - $this->filter["subm"] = $item->getValue(); - } - - abstract protected function initMode($a_item_id); - - abstract protected function parseData(); - - abstract protected function parseModeColumns(); - - function getSelectableColumns() - { - $cols = array(); - - $columns = $this->parseColumns(); - foreach($this->cols_order as $id) - { - if(in_array($id, $this->cols_mandatory)) - { - continue; - } - - if(array_key_exists($id, $columns)) - { - $col = $columns[$id]; - - $cols[$id] = array( - "txt" => $col[0], - "default" => in_array($id, $this->cols_default) - ); - } - } - - return $cols; - } - - protected function parseColumns() - { - $cols = $this->parseModeColumns(); - - $cols["submission"] = array($this->lng->txt("exc_tbl_submission_date"), "submission"); - - $cols["status"] = array($this->lng->txt("exc_tbl_status"), "status"); - $cols["mark"] = array($this->lng->txt("exc_tbl_mark"), "mark"); - $cols["status_time"] = array($this->lng->txt("exc_tbl_status_time"), "status_time"); - - $cols["sent_time"] = array($this->lng->txt("exc_tbl_sent_time"), "sent_time"); - - if($this->exc->hasTutorFeedbackText() || - $this->exc->hasTutorFeedbackMail() || - $this->exc->hasTutorFeedbackFile()) - { - $cols["feedback_time"] = array($this->lng->txt("exc_tbl_feedback_time"), "feedback_time"); - } - - if($this->exc->hasTutorFeedbackText()) - { - $cols["comment"] = array($this->lng->txt("exc_tbl_comment"), "comment"); - } - - $cols["notice"] = array($this->lng->txt("exc_tbl_notice"), "note"); - - return $cols; - } - - protected function parseRow($a_user_id, ilExAssignment $a_ass, array $a_row) - { - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - - $has_no_team_yet = ($a_ass->hasTeam() && - !ilExAssignmentTeam::getTeamId($a_ass->getId(), $a_user_id)); - - - // static columns + // see 0021530 and parseRow here with similar action per user + if ($this->mode == self::MODE_BY_ASSIGNMENT && + $this->ass->hasActiveIDl() && + !$this->ass->hasReadOnlyIDl()) { + $this->addMultiCommand("setIndividualDeadline", $this->lng->txt("exc_individual_deadline_action")); + } + + if ($this->exc->hasTutorFeedbackMail() && + $this->mode == self::MODE_BY_ASSIGNMENT) { + $this->addMultiCommand("redirectFeedbackMail", $this->lng->txt("exc_tbl_action_feedback_mail")); + } + + $this->addMultiCommand("sendMembers", $this->lng->txt("exc_send_assignment")); + + if ($this->mode == self::MODE_BY_ASSIGNMENT && + $this->ass && + $this->ass->hasTeam()) { + $this->addMultiCommand("createTeams", $this->lng->txt("exc_team_multi_create")); + $this->addMultiCommand("dissolveTeams", $this->lng->txt("exc_team_multi_dissolve")); + } + + if ($this->mode == self::MODE_BY_ASSIGNMENT) { + $this->addMultiCommand("confirmDeassignMembers", $this->lng->txt("exc_deassign_members")); + } + + $this->setFilterCommand($this->getParentCmd() . "Apply"); + $this->setResetCommand($this->getParentCmd() . "Reset"); + + $this->initFilter(); + $this->setData($this->parseData()); + + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + } + + public function initFilter() + { + if ($this->mode == self::MODE_BY_ASSIGNMENT) { + $item = $this->addFilterItemByMetaType("flt_name", self::FILTER_TEXT, false, $this->lng->txt("name") . " / " . $this->lng->txt("login")); + $this->filter["name"] = $item->getValue(); + } + + $this->lng->loadLanguageModule("search"); + $options = array( + "" => $this->lng->txt("search_any"), + "notgraded" => $this->lng->txt("exc_notgraded"), + "passed" => $this->lng->txt("exc_passed"), + "failed" => $this->lng->txt("exc_failed") + ); + $item = $this->addFilterItemByMetaType("flt_status", self::FILTER_SELECT, false, $this->lng->txt("exc_tbl_status")); + $item->setOptions($options); + $this->filter["status"] = $item->getValue(); + + $options = array( + "" => $this->lng->txt("search_any"), + "y" => $this->lng->txt("exc_tbl_filter_has_submission"), + "n" => $this->lng->txt("exc_tbl_filter_has_no_submission") + ); + $item = $this->addFilterItemByMetaType("flt_subm", self::FILTER_SELECT, false, $this->lng->txt("exc_tbl_filter_submission")); + $item->setOptions($options); + $this->filter["subm"] = $item->getValue(); + } + + abstract protected function initMode($a_item_id); + + abstract protected function parseData(); + + abstract protected function parseModeColumns(); + + public function getSelectableColumns() + { + $cols = array(); + + $columns = $this->parseColumns(); + foreach ($this->cols_order as $id) { + if (in_array($id, $this->cols_mandatory)) { + continue; + } + + if (array_key_exists($id, $columns)) { + $col = $columns[$id]; + + $cols[$id] = array( + "txt" => $col[0], + "default" => in_array($id, $this->cols_default) + ); + } + } + + return $cols; + } + + protected function parseColumns() + { + $cols = $this->parseModeColumns(); + + $cols["submission"] = array($this->lng->txt("exc_tbl_submission_date"), "submission"); + + $cols["status"] = array($this->lng->txt("exc_tbl_status"), "status"); + $cols["mark"] = array($this->lng->txt("exc_tbl_mark"), "mark"); + $cols["status_time"] = array($this->lng->txt("exc_tbl_status_time"), "status_time"); + + $cols["sent_time"] = array($this->lng->txt("exc_tbl_sent_time"), "sent_time"); + + if ($this->exc->hasTutorFeedbackText() || + $this->exc->hasTutorFeedbackMail() || + $this->exc->hasTutorFeedbackFile()) { + $cols["feedback_time"] = array($this->lng->txt("exc_tbl_feedback_time"), "feedback_time"); + } + + if ($this->exc->hasTutorFeedbackText()) { + $cols["comment"] = array($this->lng->txt("exc_tbl_comment"), "comment"); + } + + $cols["notice"] = array($this->lng->txt("exc_tbl_notice"), "note"); + + return $cols; + } + + protected function parseRow($a_user_id, ilExAssignment $a_ass, array $a_row) + { + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + + $has_no_team_yet = ($a_ass->hasTeam() && + !ilExAssignmentTeam::getTeamId($a_ass->getId(), $a_user_id)); + + + // static columns - if($this->mode == self::MODE_BY_ASSIGNMENT) - { - if(!$a_ass->hasTeam()) - { - $this->tpl->setVariable("VAL_NAME", $a_row["name"]); + if ($this->mode == self::MODE_BY_ASSIGNMENT) { + if (!$a_ass->hasTeam()) { + $this->tpl->setVariable("VAL_NAME", $a_row["name"]); - // #18327 - if(!$ilAccess->checkAccessOfUser($a_user_id, "read","", $this->exc->getRefId()) && - is_array($info = $ilAccess->getInfo())) - { - $this->tpl->setCurrentBlock('access_warning'); - $this->tpl->setVariable('PARENT_ACCESS', $info[0]["text"]); - $this->tpl->parseCurrentBlock(); - } - } - else - { - asort($a_row["team"]); - foreach($a_row["team"] as $team_member_id => $team_member_name) // #10749 - { - if(sizeof($a_row["team"]) > 1) - { - $ilCtrl->setParameterByClass("ilExSubmissionTeamGUI", "id", $team_member_id); - $url = $ilCtrl->getLinkTargetByClass("ilExSubmissionTeamGUI", "confirmRemoveTeamMember"); - $ilCtrl->setParameterByClass("ilExSubmissionTeamGUI", "id", ""); + // #18327 + if (!$ilAccess->checkAccessOfUser($a_user_id, "read", "", $this->exc->getRefId()) && + is_array($info = $ilAccess->getInfo())) { + $this->tpl->setCurrentBlock('access_warning'); + $this->tpl->setVariable('PARENT_ACCESS', $info[0]["text"]); + $this->tpl->parseCurrentBlock(); + } + } else { + asort($a_row["team"]); + foreach ($a_row["team"] as $team_member_id => $team_member_name) { // #10749 + if (sizeof($a_row["team"]) > 1) { + $ilCtrl->setParameterByClass("ilExSubmissionTeamGUI", "id", $team_member_id); + $url = $ilCtrl->getLinkTargetByClass("ilExSubmissionTeamGUI", "confirmRemoveTeamMember"); + $ilCtrl->setParameterByClass("ilExSubmissionTeamGUI", "id", ""); - include_once "Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"; + include_once "Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"; - $this->tpl->setCurrentBlock("team_member_removal_bl"); - $this->tpl->setVariable("URL_TEAM_MEMBER_REMOVAL", $url); - $this->tpl->setVariable("TXT_TEAM_MEMBER_REMOVAL", - ilGlyphGUI::get(ilGlyphGUI::CLOSE, $this->lng->txt("remove"))); - $this->tpl->parseCurrentBlock(); - } + $this->tpl->setCurrentBlock("team_member_removal_bl"); + $this->tpl->setVariable("URL_TEAM_MEMBER_REMOVAL", $url); + $this->tpl->setVariable( + "TXT_TEAM_MEMBER_REMOVAL", + ilGlyphGUI::get(ilGlyphGUI::CLOSE, $this->lng->txt("remove")) + ); + $this->tpl->parseCurrentBlock(); + } - // #18327 - if(!$ilAccess->checkAccessOfUser($team_member_id, "read","", $this->exc->getRefId()) && - is_array($info = $ilAccess->getInfo())) - { - $this->tpl->setCurrentBlock('team_access_warning'); - $this->tpl->setVariable('TEAM_PARENT_ACCESS', $info[0]["text"]); - $this->tpl->parseCurrentBlock(); - } + // #18327 + if (!$ilAccess->checkAccessOfUser($team_member_id, "read", "", $this->exc->getRefId()) && + is_array($info = $ilAccess->getInfo())) { + $this->tpl->setCurrentBlock('team_access_warning'); + $this->tpl->setVariable('TEAM_PARENT_ACCESS', $info[0]["text"]); + $this->tpl->parseCurrentBlock(); + } - $this->tpl->setCurrentBlock("team_member"); - $this->tpl->setVariable("TXT_MEMBER_NAME", $team_member_name); - $this->tpl->parseCurrentBlock(); - } + $this->tpl->setCurrentBlock("team_member"); + $this->tpl->setVariable("TXT_MEMBER_NAME", $team_member_name); + $this->tpl->parseCurrentBlock(); + } - if($has_no_team_yet) - { - // #11957 - $this->tpl->setCurrentBlock("team_info"); - $this->tpl->setVariable("TXT_TEAM_INFO", $this->lng->txt("exc_no_team_yet")); - } - else - { - $this->tpl->setCurrentBlock("team_info"); - $this->tpl->setVariable("TXT_TEAM_INFO", "(".$a_row["submission_obj"]->getTeam()->getId().")"); - } - } - } - else - { - $this->tpl->setVariable("VAL_NAME", $a_row["name"]); - } - - // do not grade or mark if no team yet - if(!$has_no_team_yet) - { - // status - $this->tpl->setVariable("SEL_".strtoupper($a_row["status"]), ' selected="selected" '); - $this->tpl->setVariable("TXT_NOTGRADED", $this->lng->txt("exc_notgraded")); - $this->tpl->setVariable("TXT_PASSED", $this->lng->txt("exc_passed")); - $this->tpl->setVariable("TXT_FAILED", $this->lng->txt("exc_failed")); - } - else - { - $nt_colspan = in_array("mark", $this->getSelectedColumns()) - ? 2 - : 1; - - $this->tpl->setVariable("NO_TEAM_COLSPAN", $nt_colspan); - } - - - // comment modal - - if($this->exc->hasTutorFeedbackText()) - { - $comment_id = "excasscomm_".$a_ass->getId()."_".$a_user_id; + if ($has_no_team_yet) { + // #11957 + $this->tpl->setCurrentBlock("team_info"); + $this->tpl->setVariable("TXT_TEAM_INFO", $this->lng->txt("exc_no_team_yet")); + } else { + $this->tpl->setCurrentBlock("team_info"); + $this->tpl->setVariable("TXT_TEAM_INFO", "(" . $a_row["submission_obj"]->getTeam()->getId() . ")"); + } + } + } else { + $this->tpl->setVariable("VAL_NAME", $a_row["name"]); + } + + // do not grade or mark if no team yet + if (!$has_no_team_yet) { + // status + $this->tpl->setVariable("SEL_" . strtoupper($a_row["status"]), ' selected="selected" '); + $this->tpl->setVariable("TXT_NOTGRADED", $this->lng->txt("exc_notgraded")); + $this->tpl->setVariable("TXT_PASSED", $this->lng->txt("exc_passed")); + $this->tpl->setVariable("TXT_FAILED", $this->lng->txt("exc_failed")); + } else { + $nt_colspan = in_array("mark", $this->getSelectedColumns()) + ? 2 + : 1; + + $this->tpl->setVariable("NO_TEAM_COLSPAN", $nt_colspan); + } + + + // comment modal + + if ($this->exc->hasTutorFeedbackText()) { + $comment_id = "excasscomm_" . $a_ass->getId() . "_" . $a_user_id; - $modal = ilModalGUI::getInstance(); - $modal->setId($comment_id); - $modal->setHeading($this->lng->txt("exc_tbl_action_feedback_text")); + $modal = ilModalGUI::getInstance(); + $modal->setId($comment_id); + $modal->setHeading($this->lng->txt("exc_tbl_action_feedback_text")); - $lcomment_form = new ilPropertyFormGUI(); - $lcomment_form->setId($comment_id); - $lcomment_form->setPreventDoubleSubmission(false); + $lcomment_form = new ilPropertyFormGUI(); + $lcomment_form->setId($comment_id); + $lcomment_form->setPreventDoubleSubmission(false); - $lcomment = new ilTextAreaInputGUI($this->lng->txt("exc_comment_for_learner"), "lcomment_".$a_ass->getId()."_".$a_user_id); - $lcomment->setInfo($this->lng->txt("exc_comment_for_learner_info")); - $lcomment->setValue($a_row["comment"]); - $lcomment->setCols(45); - $lcomment->setRows(10); - $lcomment_form->addItem($lcomment); + $lcomment = new ilTextAreaInputGUI($this->lng->txt("exc_comment_for_learner"), "lcomment_" . $a_ass->getId() . "_" . $a_user_id); + $lcomment->setInfo($this->lng->txt("exc_comment_for_learner_info")); + $lcomment->setValue($a_row["comment"]); + $lcomment->setCols(45); + $lcomment->setRows(10); + $lcomment_form->addItem($lcomment); - $lcomment_form->addCommandButton("save", $this->lng->txt("save")); - // $lcomment_form->addCommandButton("cancel", $lng->txt("cancel")); + $lcomment_form->addCommandButton("save", $this->lng->txt("save")); + // $lcomment_form->addCommandButton("cancel", $lng->txt("cancel")); - $modal->setBody($lcomment_form->getHTML()); + $modal->setBody($lcomment_form->getHTML()); - $this->comment_modals[] = $modal->getHTML(); - unset($modal); - } - - - // selectable columns - - foreach($this->getSelectedColumns() as $col) - { - switch($col) - { - case "image": - if(!$a_ass->hasTeam()) - { - include_once "./Services/Object/classes/class.ilObjectFactory.php"; - if($usr_obj = ilObjectFactory::getInstanceByObjId($a_user_id, false)) - { - $this->tpl->setVariable("VAL_IMAGE", $usr_obj->getPersonalPicturePath("xxsmall")); - $this->tpl->setVariable("TXT_IMAGE", $this->lng->txt("personal_picture")); - } - } - break; - - case "team_members": - if($a_ass->hasTeam()) - { - if(!sizeof($a_row["team"])) - { - $this->tpl->setVariable("VAL_TEAM_MEMBER", $this->lng->txt("exc_no_team_yet")); - } - else - { - foreach($a_row["team"] as $name) - { - $this->tpl->setCurrentBlock("team_member_bl"); - $this->tpl->setVariable("VAL_TEAM_MEMBER", $name); - $this->tpl->parseCurrentBlock(); - } - } - } - else - { - $this->tpl->setVariable("VAL_TEAM_MEMBER", " "); - } - break; - - case "idl": - $this->tpl->setVariable("VAL_".strtoupper($col), - $a_row[$col] - ? ilDatePresentation::formatDate(new ilDateTime($a_row[$col], IL_CAL_UNIX)) - : " "); - break; + $this->comment_modals[] = $modal->getHTML(); + unset($modal); + } + + + // selectable columns + + foreach ($this->getSelectedColumns() as $col) { + switch ($col) { + case "image": + if (!$a_ass->hasTeam()) { + include_once "./Services/Object/classes/class.ilObjectFactory.php"; + if ($usr_obj = ilObjectFactory::getInstanceByObjId($a_user_id, false)) { + $this->tpl->setVariable("VAL_IMAGE", $usr_obj->getPersonalPicturePath("xxsmall")); + $this->tpl->setVariable("TXT_IMAGE", $this->lng->txt("personal_picture")); + } + } + break; + + case "team_members": + if ($a_ass->hasTeam()) { + if (!sizeof($a_row["team"])) { + $this->tpl->setVariable("VAL_TEAM_MEMBER", $this->lng->txt("exc_no_team_yet")); + } else { + foreach ($a_row["team"] as $name) { + $this->tpl->setCurrentBlock("team_member_bl"); + $this->tpl->setVariable("VAL_TEAM_MEMBER", $name); + $this->tpl->parseCurrentBlock(); + } + } + } else { + $this->tpl->setVariable("VAL_TEAM_MEMBER", " "); + } + break; + + case "idl": + $this->tpl->setVariable( + "VAL_" . strtoupper($col), + $a_row[$col] + ? ilDatePresentation::formatDate(new ilDateTime($a_row[$col], IL_CAL_UNIX)) + : " " + ); + break; - case "calc_deadline": - $this->tpl->setVariable("VAL_".strtoupper($col), - $a_row[$col] - ? ilDatePresentation::formatDate(new ilDateTime($a_row[$col], IL_CAL_UNIX)) - : " "); - break; + case "calc_deadline": + $this->tpl->setVariable( + "VAL_" . strtoupper($col), + $a_row[$col] + ? ilDatePresentation::formatDate(new ilDateTime($a_row[$col], IL_CAL_UNIX)) + : " " + ); + break; - case "mark": - if($has_no_team_yet) - { - break; - } - // fallthrough - - case "notice": - // see #22076 - $this->tpl->setVariable("VAL_".strtoupper($col), ilUtil::prepareFormOutput(trim($a_row[$col]))); - break; - - case "comment": - // for js-updating - $this->tpl->setVariable("LCOMMENT_ID", $comment_id."_snip"); + case "mark": + if ($has_no_team_yet) { + break; + } + // fallthrough + + // no break + case "notice": + // see #22076 + $this->tpl->setVariable("VAL_" . strtoupper($col), ilUtil::prepareFormOutput(trim($a_row[$col]))); + break; + + case "comment": + // for js-updating + $this->tpl->setVariable("LCOMMENT_ID", $comment_id . "_snip"); - // see #22076 - $this->tpl->setVariable("VAL_".strtoupper($col), (trim($a_row[$col]) !== "") - ? nl2br(trim($a_row[$col])) - : " "); - break; - - case "submission": - if($a_row["submission_obj"]) - { - foreach($a_row["submission_obj"]->getFiles() as $file) - { - if($file["late"]) - { - $this->tpl->setVariable("TXT_LATE", $this->lng->txt("exc_late_submission")); - break; - } - } - } - // fallthrough - - case "feedback_time": - case "status_time": - case "sent_time": - $this->tpl->setVariable("VAL_".strtoupper($col), - $a_row[$col] - ? ilDatePresentation::formatDate(new ilDateTime($a_row[$col], IL_CAL_DATETIME)) - : " "); - break; - - case "login": - if($a_ass->hasTeam()) - { - break; - } - // fallthrough - - default: - $this->tpl->setVariable("VAL_".strtoupper($col), $a_row[$col] - ? trim($a_row[$col]) - : " "); - break; - } - } - - - // actions - - include_once "Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"; - $actions = new ilAdvancedSelectionListGUI(); - $actions->setId($a_ass->getId()."_".$a_user_id); - $actions->setListTitle($this->lng->txt("actions")); - - $file_info = $a_row["submission_obj"]->getDownloadedFilesInfoForTableGUIS($this->getParentObject(), $this->getParentCmd()); - - $counter = $file_info["files"]["count"]; - if($counter) - { - if($file_info["files"]["download_url"]) - { - $actions->addItem( - $file_info["files"]["download_txt"]." (".$counter.")", - "", - $file_info["files"]["download_url"] - ); - } - - if($file_info["files"]["download_new_url"]) - { - $actions->addItem( - $file_info["files"]["download_new_txt"], - "", - $file_info["files"]["download_new_url"] - ); - } - } - - if(!$has_no_team_yet && - $a_ass->hasActiveIDl() && - !$a_ass->hasReadOnlyIDl()) - { - $idl_id = $a_ass->hasTeam() - ? "t".ilExAssignmentTeam::getTeamId($a_ass->getId(), $a_user_id) - : $a_user_id; - - $this->tpl->setVariable("VAL_IDL_ID", $a_ass->getId()."_".$idl_id); - - $actions->addItem( - $this->lng->txt("exc_individual_deadline_action"), - "", - "#", - "", - "", - "", - "", - false, - "il.ExcIDl.trigger('".$idl_id."',".$a_ass->getId().")" - ); - } - - // feedback mail - if($this->exc->hasTutorFeedbackMail()) - { - $actions->addItem( - $this->lng->txt("exc_tbl_action_feedback_mail"), - "", - $ilCtrl->getLinkTarget($this->parent_obj, "redirectFeedbackMail") - ); - } - - // feedback files - if($this->exc->hasTutorFeedbackFile()) - { - include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); - $storage = new ilFSStorageExercise($this->exc->getId(), $a_ass->getId()); - $counter = $storage->countFeedbackFiles($a_row["submission_obj"]->getFeedbackId()); - $counter = $counter - ? " (".$counter.")" - : ""; - $actions->addItem( - $this->lng->txt("exc_tbl_action_feedback_file").$counter, - "", - $ilCtrl->getLinkTargetByClass("ilfilesystemgui", "listFiles") - ); - } + // see #22076 + $this->tpl->setVariable("VAL_" . strtoupper($col), (trim($a_row[$col]) !== "") + ? nl2br(trim($a_row[$col])) + : " "); + break; + + case "submission": + if ($a_row["submission_obj"]) { + foreach ($a_row["submission_obj"]->getFiles() as $file) { + if ($file["late"]) { + $this->tpl->setVariable("TXT_LATE", $this->lng->txt("exc_late_submission")); + break; + } + } + } + // fallthrough + + // no break + case "feedback_time": + case "status_time": + case "sent_time": + $this->tpl->setVariable( + "VAL_" . strtoupper($col), + $a_row[$col] + ? ilDatePresentation::formatDate(new ilDateTime($a_row[$col], IL_CAL_DATETIME)) + : " " + ); + break; + + case "login": + if ($a_ass->hasTeam()) { + break; + } + // fallthrough + + // no break + default: + $this->tpl->setVariable("VAL_" . strtoupper($col), $a_row[$col] + ? trim($a_row[$col]) + : " "); + break; + } + } + + + // actions + + include_once "Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"; + $actions = new ilAdvancedSelectionListGUI(); + $actions->setId($a_ass->getId() . "_" . $a_user_id); + $actions->setListTitle($this->lng->txt("actions")); + + $file_info = $a_row["submission_obj"]->getDownloadedFilesInfoForTableGUIS($this->getParentObject(), $this->getParentCmd()); + + $counter = $file_info["files"]["count"]; + if ($counter) { + if ($file_info["files"]["download_url"]) { + $actions->addItem( + $file_info["files"]["download_txt"] . " (" . $counter . ")", + "", + $file_info["files"]["download_url"] + ); + } + + if ($file_info["files"]["download_new_url"]) { + $actions->addItem( + $file_info["files"]["download_new_txt"], + "", + $file_info["files"]["download_new_url"] + ); + } + } + + if (!$has_no_team_yet && + $a_ass->hasActiveIDl() && + !$a_ass->hasReadOnlyIDl()) { + $idl_id = $a_ass->hasTeam() + ? "t" . ilExAssignmentTeam::getTeamId($a_ass->getId(), $a_user_id) + : $a_user_id; + + $this->tpl->setVariable("VAL_IDL_ID", $a_ass->getId() . "_" . $idl_id); + + $actions->addItem( + $this->lng->txt("exc_individual_deadline_action"), + "", + "#", + "", + "", + "", + "", + false, + "il.ExcIDl.trigger('" . $idl_id . "'," . $a_ass->getId() . ")" + ); + } + + // feedback mail + if ($this->exc->hasTutorFeedbackMail()) { + $actions->addItem( + $this->lng->txt("exc_tbl_action_feedback_mail"), + "", + $ilCtrl->getLinkTarget($this->parent_obj, "redirectFeedbackMail") + ); + } + + // feedback files + if ($this->exc->hasTutorFeedbackFile()) { + include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); + $storage = new ilFSStorageExercise($this->exc->getId(), $a_ass->getId()); + $counter = $storage->countFeedbackFiles($a_row["submission_obj"]->getFeedbackId()); + $counter = $counter + ? " (" . $counter . ")" + : ""; + $actions->addItem( + $this->lng->txt("exc_tbl_action_feedback_file") . $counter, + "", + $ilCtrl->getLinkTargetByClass("ilfilesystemgui", "listFiles") + ); + } - // comment (modal - see above) - if($this->exc->hasTutorFeedbackText()) - { - $actions->addItem( - $this->lng->txt("exc_tbl_action_feedback_text"), - "", - "#", - "", - "", - "", - "", - false, - "il.ExcManagement.showComment('".$comment_id."')" - ); - } - - // peer review - if(($peer_review = $a_row["submission_obj"]->getPeerReview()) && $a_ass->afterDeadlineStrict()) // see #22246 - { - $counter = $peer_review->countGivenFeedback(true, $a_user_id); - $counter = $counter - ? " (".$counter.")" - : ""; - $actions->addItem( - $this->lng->txt("exc_tbl_action_peer_review_given").$counter, - "", - $ilCtrl->getLinkTargetByClass("ilexpeerreviewgui", "showGivenPeerReview") - ); - - $counter = sizeof($peer_review->getPeerReviewsByPeerId($a_user_id, true)); - $counter = $counter - ? " (".$counter.")" - : ""; - $actions->addItem( - $this->lng->txt("exc_tbl_action_peer_review_received").$counter, - "", - $ilCtrl->getLinkTargetByClass("ilexpeerreviewgui", "showReceivedPeerReview") - ); - } - - // team - if($has_no_team_yet) - { - $actions->addItem( - $this->lng->txt("exc_create_team"), - "", - $ilCtrl->getLinkTargetByClass("ilExSubmissionTeamGUI", "createSingleMemberTeam") - ); - } - else if($a_ass->hasTeam()) - { - $actions->addItem( - $this->lng->txt("exc_tbl_action_team_log"), - "", - $ilCtrl->getLinkTargetByClass("ilExSubmissionTeamGUI", "showTeamLog") - ); - } - - $this->tpl->setVariable("ACTIONS", $actions->getHTML()); - } - - public function render() - { - global $DIC; - $ilCtrl = $this->ctrl; - $tpl = $DIC->ui()->mainTemplate(); - - $url = $ilCtrl->getLinkTarget($this->getParentObject(), "saveCommentForLearners", "", true, false); - - $tpl->addJavaScript("Modules/Exercise/js/ilExcManagement.js"); - $tpl->addOnLoadCode('il.ExcManagement.init("'.$url.'");'); - - return parent::render(). - implode("\n", $this->comment_modals); - } -} \ No newline at end of file + // comment (modal - see above) + if ($this->exc->hasTutorFeedbackText()) { + $actions->addItem( + $this->lng->txt("exc_tbl_action_feedback_text"), + "", + "#", + "", + "", + "", + "", + false, + "il.ExcManagement.showComment('" . $comment_id . "')" + ); + } + + // peer review + if (($peer_review = $a_row["submission_obj"]->getPeerReview()) && $a_ass->afterDeadlineStrict()) { // see #22246 + $counter = $peer_review->countGivenFeedback(true, $a_user_id); + $counter = $counter + ? " (" . $counter . ")" + : ""; + $actions->addItem( + $this->lng->txt("exc_tbl_action_peer_review_given") . $counter, + "", + $ilCtrl->getLinkTargetByClass("ilexpeerreviewgui", "showGivenPeerReview") + ); + + $counter = sizeof($peer_review->getPeerReviewsByPeerId($a_user_id, true)); + $counter = $counter + ? " (" . $counter . ")" + : ""; + $actions->addItem( + $this->lng->txt("exc_tbl_action_peer_review_received") . $counter, + "", + $ilCtrl->getLinkTargetByClass("ilexpeerreviewgui", "showReceivedPeerReview") + ); + } + + // team + if ($has_no_team_yet) { + $actions->addItem( + $this->lng->txt("exc_create_team"), + "", + $ilCtrl->getLinkTargetByClass("ilExSubmissionTeamGUI", "createSingleMemberTeam") + ); + } elseif ($a_ass->hasTeam()) { + $actions->addItem( + $this->lng->txt("exc_tbl_action_team_log"), + "", + $ilCtrl->getLinkTargetByClass("ilExSubmissionTeamGUI", "showTeamLog") + ); + } + + $this->tpl->setVariable("ACTIONS", $actions->getHTML()); + } + + public function render() + { + global $DIC; + $ilCtrl = $this->ctrl; + $tpl = $DIC->ui()->mainTemplate(); + + $url = $ilCtrl->getLinkTarget($this->getParentObject(), "saveCommentForLearners", "", true, false); + + $tpl->addJavaScript("Modules/Exercise/js/ilExcManagement.js"); + $tpl->addOnLoadCode('il.ExcManagement.init("' . $url . '");'); + + return parent::render() . + implode("\n", $this->comment_modals); + } +} diff --git a/Modules/Exercise/classes/class.ilExerciseVerificationTableGUI.php b/Modules/Exercise/classes/class.ilExerciseVerificationTableGUI.php index c741b3aaac5166d0b85715330937e6472a8ef6bd..e88c913f3d0d706ed553b9c48787747a576c8213 100644 --- a/Modules/Exercise/classes/class.ilExerciseVerificationTableGUI.php +++ b/Modules/Exercise/classes/class.ilExerciseVerificationTableGUI.php @@ -12,99 +12,96 @@ include_once './Services/Table/classes/class.ilTable2GUI.php'; class ilExerciseVerificationTableGUI extends ilTable2GUI { - /** - * @var ilUserCertificateRepository - */ - private $userCertificateRepository; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @param ilObject $a_parent_obj - * @param string $a_parent_cmd - * @param ilUserCertificateRepository|null $userCertificateRepository - */ - public function __construct( - $a_parent_obj, - $a_parent_cmd = "", - ilUserCertificateRepository $userCertificateRepository = null - ) { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->user = $DIC->user(); - $database = $DIC->database(); - $logger = $DIC->logger()->root(); - $ilCtrl = $DIC->ctrl(); - - if (null === $userCertificateRepository) { - $userCertificateRepository = new ilUserCertificateRepository($database, $logger); - } - $this->userCertificateRepository = $userCertificateRepository; - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->addColumn($this->lng->txt("title"), "title"); - $this->addColumn($this->lng->txt("passed"), "passed"); - $this->addColumn($this->lng->txt("action"), ""); - - $this->setTitle($this->lng->txt("excv_create")); - $this->setDescription($this->lng->txt("excv_create_info")); - - $this->setRowTemplate("tpl.exc_verification_row.html", "Modules/Exercise"); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd)); - - $this->getItems(); - } - - /** - * Get all achieved test certificates for the current user - */ - protected function getItems() - { - $ilUser = $this->user; - $userId = $ilUser->getId(); - - $certificateArray = $this->userCertificateRepository - ->fetchActiveCertificatesByTypeForPresentation($userId, 'exc'); - - $data = array(); - - foreach ($certificateArray as $certificate) { - $data[] = array( - 'id' => $certificate->getUserCertificate()->getObjId(), - 'title' => $certificate->getObjectTitle(), - 'passed' => true - ); - } - - $this->setData($data); - } - - /** - * Fill template row - * - * @param array $a_set - */ - protected function fillRow($a_set) - { - $ilCtrl = $this->ctrl; - - $this->tpl->setVariable("TITLE", $a_set["title"]); - $this->tpl->setVariable("PASSED", ($a_set["passed"]) ? $this->lng->txt("yes") : - $this->lng->txt("no")); - - if($a_set["passed"]) - { - $ilCtrl->setParameter($this->parent_obj, "exc_id", $a_set["id"]); - $action = $ilCtrl->getLinkTarget($this->parent_obj, "save"); - $this->tpl->setVariable("URL_SELECT", $action); - $this->tpl->setVariable("TXT_SELECT", $this->lng->txt("select")); - } - } + /** + * @var ilUserCertificateRepository + */ + private $userCertificateRepository; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @param ilObject $a_parent_obj + * @param string $a_parent_cmd + * @param ilUserCertificateRepository|null $userCertificateRepository + */ + public function __construct( + $a_parent_obj, + $a_parent_cmd = "", + ilUserCertificateRepository $userCertificateRepository = null + ) { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->user = $DIC->user(); + $database = $DIC->database(); + $logger = $DIC->logger()->root(); + $ilCtrl = $DIC->ctrl(); + + if (null === $userCertificateRepository) { + $userCertificateRepository = new ilUserCertificateRepository($database, $logger); + } + $this->userCertificateRepository = $userCertificateRepository; + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->addColumn($this->lng->txt("title"), "title"); + $this->addColumn($this->lng->txt("passed"), "passed"); + $this->addColumn($this->lng->txt("action"), ""); + + $this->setTitle($this->lng->txt("excv_create")); + $this->setDescription($this->lng->txt("excv_create_info")); + + $this->setRowTemplate("tpl.exc_verification_row.html", "Modules/Exercise"); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd)); + + $this->getItems(); + } + + /** + * Get all achieved test certificates for the current user + */ + protected function getItems() + { + $ilUser = $this->user; + $userId = $ilUser->getId(); + + $certificateArray = $this->userCertificateRepository + ->fetchActiveCertificatesByTypeForPresentation($userId, 'exc'); + + $data = array(); + + foreach ($certificateArray as $certificate) { + $data[] = array( + 'id' => $certificate->getUserCertificate()->getObjId(), + 'title' => $certificate->getObjectTitle(), + 'passed' => true + ); + } + + $this->setData($data); + } + + /** + * Fill template row + * + * @param array $a_set + */ + protected function fillRow($a_set) + { + $ilCtrl = $this->ctrl; + + $this->tpl->setVariable("TITLE", $a_set["title"]); + $this->tpl->setVariable("PASSED", ($a_set["passed"]) ? $this->lng->txt("yes") : + $this->lng->txt("no")); + + if ($a_set["passed"]) { + $ilCtrl->setParameter($this->parent_obj, "exc_id", $a_set["id"]); + $action = $ilCtrl->getLinkTarget($this->parent_obj, "save"); + $this->tpl->setVariable("URL_SELECT", $action); + $this->tpl->setVariable("TXT_SELECT", $this->lng->txt("select")); + } + } } - -?> diff --git a/Modules/Exercise/classes/class.ilExerciseXMLParser.php b/Modules/Exercise/classes/class.ilExerciseXMLParser.php index d90bb724c5c4cbf56112c66edea286728bad402e..cf0673f1a8ef44813bec22e6f6caffdaddf399cf 100644 --- a/Modules/Exercise/classes/class.ilExerciseXMLParser.php +++ b/Modules/Exercise/classes/class.ilExerciseXMLParser.php @@ -17,17 +17,16 @@ include_once './Services/Xml/classes/class.ilSaxParser.php'; */ class ilExerciseXMLParser extends ilSaxParser { - - static $CONTENT_NOT_COMPRESSED = 0; - static $CONTENT_GZ_COMPRESSED = 1; - static $CONTENT_ZLIB_COMPRESSED = 2; + public static $CONTENT_NOT_COMPRESSED = 0; + public static $CONTENT_GZ_COMPRESSED = 1; + public static $CONTENT_ZLIB_COMPRESSED = 2; /** - * Exercise object which has been parsed - * - * @var ilObjExercise - */ - var $exercise; + * Exercise object which has been parsed + * + * @var ilObjExercise + */ + public $exercise; /** * this will be matched against the id in the xml @@ -35,7 +34,7 @@ class ilExerciseXMLParser extends ilSaxParser * * @var int */ - var $obj_id; + public $obj_id; /** @@ -43,315 +42,303 @@ class ilExerciseXMLParser extends ilSaxParser * * @var boolean */ - var $result; + public $result; /** * Content compression mode, defaults to no compression * * @var int */ - var $mode; + public $mode; /** * Current Exercise Assignment * @var ilExAssignment */ - var $assignment; + public $assignment; /** * Storage for exercise related files * @var ilFSStorageExercise */ - var $storage; + public $storage; /** - * Constructor - * - * @param ilExercise $exercise existing exercise object - * @param string $a_xml_file xml data - * @param int $obj_id obj id of exercise which is to be updated - * @access public - */ - function __construct($exercise, $a_xml_data, $obj_id = -1) - { -// @todo: needs to be revised for multiple assignments per exercise + * Constructor + * + * @param ilExercise $exercise existing exercise object + * @param string $a_xml_file xml data + * @param int $obj_id obj id of exercise which is to be updated + * @access public + */ + public function __construct($exercise, $a_xml_data, $obj_id = -1) + { + // @todo: needs to be revised for multiple assignments per exercise - parent::__construct(); - - $this->exercise = $exercise; - // get all assignments and choose first one if exists, otherwise create - $assignments = ilExAssignment::getAssignmentDataOfExercise($exercise->getId()); - if (count ($assignments) > 0) { - $this->assignment = new ilExAssignment($assignments [0]["id"]); - } else { - $this->assignment = new ilExAssignment(); - $this->assignment->setExerciseId($exercise->getId()); - $this->assignment->save(); - } - - include_once ("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); - $this->storage = new ilFSStorageExercise ( $this->exercise->getId(), $this->assignment->getId()); - $this->storage->create(); - $this->storage->init(); - - $this->setXMLContent($a_xml_data); - $this->obj_id = $obj_id; - $this->result = false; - } + parent::__construct(); + + $this->exercise = $exercise; + // get all assignments and choose first one if exists, otherwise create + $assignments = ilExAssignment::getAssignmentDataOfExercise($exercise->getId()); + if (count($assignments) > 0) { + $this->assignment = new ilExAssignment($assignments [0]["id"]); + } else { + $this->assignment = new ilExAssignment(); + $this->assignment->setExerciseId($exercise->getId()); + $this->assignment->save(); + } + + include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); + $this->storage = new ilFSStorageExercise($this->exercise->getId(), $this->assignment->getId()); + $this->storage->create(); + $this->storage->init(); + + $this->setXMLContent($a_xml_data); + $this->obj_id = $obj_id; + $this->result = false; + } - /** - * set event handlers - * - * @param resource reference to the xml parser - * @access private - */ - 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'); - } + /** + * set event handlers + * + * @param resource reference to the xml parser + * @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'); + } - /** - * handler for begin of element - * - * @param resource $a_xml_parser xml parser - * @param string $a_name element name - * @param array $a_attribs element attributes array - * @throws ilExerciseException when obj id != - 1 and if it it does not match the id in the xml - */ - function handlerBeginTag($a_xml_parser,$a_name,$a_attribs) - { - switch($a_name) - { - case 'Exercise': - if (isset($a_attribs["obj_id"])) - { - $read_obj_id = ilUtil::__extractId($a_attribs["obj_id"], IL_INST_ID); - if ($this->obj_id != -1 && (int) $read_obj_id != -1 && (int) $this->obj_id != (int) $read_obj_id) - { - throw new ilExerciseException ("Object IDs (xml $read_obj_id and argument ".$this->obj_id.") do not match!", ilExerciseException::$ID_MISMATCH); - } - } - break; - case 'Member': - $this->usr_action = $a_attribs["action"]; - $this->usr_id = ilUtil::__extractId($a_attribs["usr_id"], IL_INST_ID); - break; + /** + * handler for begin of element + * + * @param resource $a_xml_parser xml parser + * @param string $a_name element name + * @param array $a_attribs element attributes array + * @throws ilExerciseException when obj id != - 1 and if it it does not match the id in the xml + */ + public function handlerBeginTag($a_xml_parser, $a_name, $a_attribs) + { + switch ($a_name) { + case 'Exercise': + if (isset($a_attribs["obj_id"])) { + $read_obj_id = ilUtil::__extractId($a_attribs["obj_id"], IL_INST_ID); + if ($this->obj_id != -1 && (int) $read_obj_id != -1 && (int) $this->obj_id != (int) $read_obj_id) { + throw new ilExerciseException("Object IDs (xml $read_obj_id and argument " . $this->obj_id . ") do not match!", ilExerciseException::$ID_MISMATCH); + } + } + break; + case 'Member': + $this->usr_action = $a_attribs["action"]; + $this->usr_id = ilUtil::__extractId($a_attribs["usr_id"], IL_INST_ID); + break; - case 'File': + case 'File': $this->file_action = $a_attribs["action"]; - break; - case 'Content': + break; + case 'Content': $this->mode = ilExerciseXMLParser::$CONTENT_NOT_COMPRESSED; - if ($a_attribs["mode"] == "GZIP") - { - if (!function_exists("gzdecode")) - throw new ilExerciseException ("Deflating with gzip is not supported", ilExerciseException::$ID_DEFLATE_METHOD_MISMATCH); + if ($a_attribs["mode"] == "GZIP") { + if (!function_exists("gzdecode")) { + throw new ilExerciseException("Deflating with gzip is not supported", ilExerciseException::$ID_DEFLATE_METHOD_MISMATCH); + } - $this->mode = ilExerciseXMLParser::$CONTENT_GZ_COMPRESSED; - } elseif ($a_attribs["mode"] == "ZLIB") - { - if (!function_exists("gzuncompress")) - throw new ilExerciseException ("Deflating with zlib (compress/uncompress) is not supported", ilExerciseException::$ID_DEFLATE_METHOD_MISMATCH); + $this->mode = ilExerciseXMLParser::$CONTENT_GZ_COMPRESSED; + } elseif ($a_attribs["mode"] == "ZLIB") { + if (!function_exists("gzuncompress")) { + throw new ilExerciseException("Deflating with zlib (compress/uncompress) is not supported", ilExerciseException::$ID_DEFLATE_METHOD_MISMATCH); + } - $this->mode = ilExerciseXMLParser::$CONTENT_ZLIB_COMPRESSED; - } - break; - case 'Marking': - $this->status = $a_attribs["status"]; - if ($this->status == ilExerciseXMLWriter::$STATUS_NOT_GRADED) - $this->status = "notgraded"; - elseif ($this->status == ilExerciseXMLWriter::$STATUS_PASSED) - $this->status = "passed"; - else - $this->status = "failed"; - break; + $this->mode = ilExerciseXMLParser::$CONTENT_ZLIB_COMPRESSED; + } + break; + case 'Marking': + $this->status = $a_attribs["status"]; + if ($this->status == ilExerciseXMLWriter::$STATUS_NOT_GRADED) { + $this->status = "notgraded"; + } elseif ($this->status == ilExerciseXMLWriter::$STATUS_PASSED) { + $this->status = "passed"; + } else { + $this->status = "failed"; + } + break; - } - } + } + } - /** - * handler for end of element - * - * @param resource $a_xml_parser xml parser - * @param string $a_name element name - */ - function handlerEndTag($a_xml_parser,$a_name) - { - switch($a_name) - { - case 'Exercise': + /** + * handler for end of element + * + * @param resource $a_xml_parser xml parser + * @param string $a_name element name + */ + public function handlerEndTag($a_xml_parser, $a_name) + { + switch ($a_name) { + case 'Exercise': $this->result = true; - break; - case 'Title': - $this->exercise->setTitle(trim($this->cdata)); - $this->assignment->setTitle(trim($this->cdata)); - break; - case 'Description': - $this->exercise->setDescription(trim($this->cdata)); - break; - case 'Instruction': - $this->assignment->setInstruction(trim($this->cdata)); - break; - case 'DueDate': - $this->assignment->setDeadLine(trim($this->cdata)); - break; - case 'Member': - $this->updateMember($this->usr_id, $this->usr_action); - // update marking after update member. - $this->updateMarking($this->usr_id); - break; - case 'Filename': - $this->file_name = trim($this->cdata); - break; - case 'Content': - $this->file_content = trim($this->cdata); - break; - case 'File': - $this->updateFile($this->file_name, $this->file_content, $this->file_action); - break; - case 'Comment': - $this->comment = trim($this->cdata); - break; - case 'Notice': - $this->notice = trim($this->cdata); - break; - case 'Mark': - $this->mark = trim($this->cdata); - break; - case 'Marking': - // see Member end tag - break; - } + break; + case 'Title': + $this->exercise->setTitle(trim($this->cdata)); + $this->assignment->setTitle(trim($this->cdata)); + break; + case 'Description': + $this->exercise->setDescription(trim($this->cdata)); + break; + case 'Instruction': + $this->assignment->setInstruction(trim($this->cdata)); + break; + case 'DueDate': + $this->assignment->setDeadLine(trim($this->cdata)); + break; + case 'Member': + $this->updateMember($this->usr_id, $this->usr_action); + // update marking after update member. + $this->updateMarking($this->usr_id); + break; + case 'Filename': + $this->file_name = trim($this->cdata); + break; + case 'Content': + $this->file_content = trim($this->cdata); + break; + case 'File': + $this->updateFile($this->file_name, $this->file_content, $this->file_action); + break; + case 'Comment': + $this->comment = trim($this->cdata); + break; + case 'Notice': + $this->notice = trim($this->cdata); + break; + case 'Mark': + $this->mark = trim($this->cdata); + break; + case 'Marking': + // see Member end tag + break; + } - $this->cdata = ''; + $this->cdata = ''; - return; - } + return; + } - /** - * handler for character data - * - * @param resource $a_xml_parser xml parser - * @param string $a_data character data - */ - function handlerCharacterData($a_xml_parser,$a_data) - { - if($a_data != "\n") - { - $this->cdata .= $a_data; - } - } + /** + * handler for character data + * + * @param resource $a_xml_parser xml parser + * @param string $a_data character data + */ + public function handlerCharacterData($a_xml_parser, $a_data) + { + if ($a_data != "\n") { + $this->cdata .= $a_data; + } + } - /** - * update member object according to given action - * - * @param int $user_id - * @param string $action can be Attach or Detach - */ - private function updateMember ($user_id, $action) { - if (!is_int($user_id) || $user_id <= 0) { - return; - } - $memberObject = new ilExerciseMembers($this->exercise); + /** + * update member object according to given action + * + * @param int $user_id + * @param string $action can be Attach or Detach + */ + private function updateMember($user_id, $action) + { + if (!is_int($user_id) || $user_id <= 0) { + return; + } + $memberObject = new ilExerciseMembers($this->exercise); - if ($action == "Attach" && !$memberObject->isAssigned($user_id)) - { - $memberObject->assignMember ($user_id); - } + if ($action == "Attach" && !$memberObject->isAssigned($user_id)) { + $memberObject->assignMember($user_id); + } - if ($action == "Detach" && $memberObject->isAssigned($user_id)) - { - $memberObject->deassignMember ($user_id); - } - } + if ($action == "Detach" && $memberObject->isAssigned($user_id)) { + $memberObject->deassignMember($user_id); + } + } - /** - * update file according to filename - * - * @param string $filename - * @param string $content base 64 encoded string - * @param string $action can be Attach or Detach - */ - private function updateFile ($filename, $b64encodedContent, $action) - { - if (strlen($filename) == 0) { - return; - } - $filename= $this->storage->getAbsolutePath()."/".$filename; - - if ($action == "Attach") - { - $content = base64_decode((string) $b64encodedContent); - if ($this->mode == ilExerciseXMLParser::$CONTENT_GZ_COMPRESSED) { + /** + * update file according to filename + * + * @param string $filename + * @param string $content base 64 encoded string + * @param string $action can be Attach or Detach + */ + private function updateFile($filename, $b64encodedContent, $action) + { + if (strlen($filename) == 0) { + return; + } + $filename= $this->storage->getAbsolutePath() . "/" . $filename; + + if ($action == "Attach") { + $content = base64_decode((string) $b64encodedContent); + if ($this->mode == ilExerciseXMLParser::$CONTENT_GZ_COMPRESSED) { $content = gzdecode($content); - }elseif ($this->mode ==ilExerciseXMLParser::$CONTENT_ZLIB_COMPRESSED) { + } elseif ($this->mode ==ilExerciseXMLParser::$CONTENT_ZLIB_COMPRESSED) { $content = gzuncompress($content); - } - - //echo $filename; - $this->storage->writeToFile($content, $filename); - + } + + //echo $filename; + $this->storage->writeToFile($content, $filename); } - if ($action == "Detach") - { + if ($action == "Detach") { $this->storage->deleteFile($filename); } - } - - /** - * starts parsing an changes object by side effect. - * - * @throws ilExerciseException when obj id != - 1 and if it it does not match the id in the xml - * @return boolean true, if no errors happend. - * - */ - public function start () { - $this->startParsing(); - return $this->result > 0; - } - - /** - * update marking of member - * - * @param int $usr_id - */ - private function updateMarking($usr_id) { - - $member_status = $this->assignment->getMemberStatus($usr_id); - if (isset($this->mark)) - { - $member_status->setMark(ilUtil::stripSlashes($this->mark)); - } - if (isset($this->comment)) - { - $member_status->setComment(ilUtil::stripSlashes($this->comment)); - } - if (isset($this->status)) - { - $member_status->setStatus(ilUtil::stripSlashes($this->status)); - } - if (isset($this->notice)) - { - $member_status->setNotice(ilUtil::stripSlashes($this->notice)); - } - $member_status->update(); - - // reset variables - $this->mark = null; - $this->status = null; - $this->notice = null; - $this->comment = null; - } - - public function getAssignment () { - return $this->assignment; - } + } + /** + * starts parsing an changes object by side effect. + * + * @throws ilExerciseException when obj id != - 1 and if it it does not match the id in the xml + * @return boolean true, if no errors happend. + * + */ + public function start() + { + $this->startParsing(); + return $this->result > 0; + } + + /** + * update marking of member + * + * @param int $usr_id + */ + private function updateMarking($usr_id) + { + $member_status = $this->assignment->getMemberStatus($usr_id); + if (isset($this->mark)) { + $member_status->setMark(ilUtil::stripSlashes($this->mark)); + } + if (isset($this->comment)) { + $member_status->setComment(ilUtil::stripSlashes($this->comment)); + } + if (isset($this->status)) { + $member_status->setStatus(ilUtil::stripSlashes($this->status)); + } + if (isset($this->notice)) { + $member_status->setNotice(ilUtil::stripSlashes($this->notice)); + } + $member_status->update(); + + // reset variables + $this->mark = null; + $this->status = null; + $this->notice = null; + $this->comment = null; + } + + public function getAssignment() + { + return $this->assignment; + } } -?> \ No newline at end of file diff --git a/Modules/Exercise/classes/class.ilExerciseXMLWriter.php b/Modules/Exercise/classes/class.ilExerciseXMLWriter.php index 2cc6b1ae3fc8b9f724bddc8527cc9e9d97efaeb8..ab0bf78ecc0f6903dce0a12e40fc3e1cd0c8794b 100644 --- a/Modules/Exercise/classes/class.ilExerciseXMLWriter.php +++ b/Modules/Exercise/classes/class.ilExerciseXMLWriter.php @@ -18,233 +18,240 @@ include_once "./Modules/Exercise/classes/class.ilExAssignment.php"; * * @ingroup ModulesExercise */ -class ilExerciseXMLWriter extends ilXmlWriter { - - static $CONTENT_ATTACH_NO = 0; - static $CONTENT_ATTACH_ENCODED = 1; - static $CONTENT_ATTACH_ZLIB_ENCODED = 2; - static $CONTENT_ATTACH_GZIP_ENCODED = 3; - - static $STATUS_NOT_GRADED = "NOT_GRADED"; - static $STATUS_PASSED = "PASSED"; - static $STATUS_FAILED = "FAILED"; - /** - * if true, file contents will be attached as base64 - * - * @var boolean - */ - var $attachFileContents; - - /** - * if true, members will be attach to xml - * - * @var boolean - */ - var $attachMembers; - - /** - * Exercise Object - * - * @var ilObjExercise - */ - var $exercise; - - /** - * constructor - * @param string xml version - * @param string output encoding - * @param string input encoding - * @access public - */ - function __construct() { - // @todo: needs to be revised for multiple assignments per exercise - //die ("Needs revision for ILIAS 4.1"); - parent::__construct(); - $this->attachFileContents = ilExerciseXMLWriter::$CONTENT_ATTACH_NO; - } - - /** - * - * set exercise object - * @param ilObjExercise $exercise - */ - - function setExercise($exercise) { - $this->exercise = $exercise; - } - - /** - * set attachment content mode - * - * @param int $attachFileContents - * @throws ilExerciseException if mode is not supported - */ - function setAttachFileContents($attachFileContents) { - if ($attachFileContents == ilExerciseXMLWriter::$CONTENT_ATTACH_GZIP_ENCODED && ! function_exists ( "gzencode" )) { - throw new ilExerciseException ( "Inflating with gzip is not supported", ilExerciseException::$ID_DEFLATE_METHOD_MISMATCH ); - } - if ($attachFileContents == ilExerciseXMLWriter::$CONTENT_ATTACH_ZLIB_ENCODED && ! function_exists ( "gzcompress" )) { - throw new ilExerciseException ( "Inflating with zlib (compress/uncompress) is not supported", ilExerciseException::$ID_DEFLATE_METHOD_MISMATCH ); - } - - $this->attachFileContents = $attachFileContents; - } - - function start() { - $this->__buildHeader (); - - $attribs = array ("obj_id" => "il_" . IL_INST_ID . "_exc_" . $this->exercise->getId () ); - - if ($this->exercise->getOwner ()) - $attribs ["owner"] = "il_" . IL_INST_ID . "_usr_" . $this->exercise->getOwner (); - - $this->xmlStartTag ( "Exercise", $attribs ); - - //todo: create new dtd for new assignment structure - $this->xmlElement("Title", null,$this->exercise->getTitle()); - $this->xmlElement("Description", null,$this->exercise->getDescription()); - //$this->xmlElement("Instruction", null,$this->exercise->getInstruction()); - //$this->xmlElement("DueDate", null,$this->exercise->getTimestamp()); - +class ilExerciseXMLWriter extends ilXmlWriter +{ + public static $CONTENT_ATTACH_NO = 0; + public static $CONTENT_ATTACH_ENCODED = 1; + public static $CONTENT_ATTACH_ZLIB_ENCODED = 2; + public static $CONTENT_ATTACH_GZIP_ENCODED = 3; + + public static $STATUS_NOT_GRADED = "NOT_GRADED"; + public static $STATUS_PASSED = "PASSED"; + public static $STATUS_FAILED = "FAILED"; + /** + * if true, file contents will be attached as base64 + * + * @var boolean + */ + public $attachFileContents; + + /** + * if true, members will be attach to xml + * + * @var boolean + */ + public $attachMembers; + + /** + * Exercise Object + * + * @var ilObjExercise + */ + public $exercise; + + /** + * constructor + * @param string xml version + * @param string output encoding + * @param string input encoding + * @access public + */ + public function __construct() + { + // @todo: needs to be revised for multiple assignments per exercise + //die ("Needs revision for ILIAS 4.1"); + parent::__construct(); + $this->attachFileContents = ilExerciseXMLWriter::$CONTENT_ATTACH_NO; + } + + /** + * + * set exercise object + * @param ilObjExercise $exercise + */ + + public function setExercise($exercise) + { + $this->exercise = $exercise; + } + + /** + * set attachment content mode + * + * @param int $attachFileContents + * @throws ilExerciseException if mode is not supported + */ + public function setAttachFileContents($attachFileContents) + { + if ($attachFileContents == ilExerciseXMLWriter::$CONTENT_ATTACH_GZIP_ENCODED && !function_exists("gzencode")) { + throw new ilExerciseException("Inflating with gzip is not supported", ilExerciseException::$ID_DEFLATE_METHOD_MISMATCH); + } + if ($attachFileContents == ilExerciseXMLWriter::$CONTENT_ATTACH_ZLIB_ENCODED && !function_exists("gzcompress")) { + throw new ilExerciseException("Inflating with zlib (compress/uncompress) is not supported", ilExerciseException::$ID_DEFLATE_METHOD_MISMATCH); + } + + $this->attachFileContents = $attachFileContents; + } + + public function start() + { + $this->__buildHeader(); + + $attribs = array("obj_id" => "il_" . IL_INST_ID . "_exc_" . $this->exercise->getId() ); + + if ($this->exercise->getOwner()) { + $attribs ["owner"] = "il_" . IL_INST_ID . "_usr_" . $this->exercise->getOwner(); + } + + $this->xmlStartTag("Exercise", $attribs); + + //todo: create new dtd for new assignment structure + $this->xmlElement("Title", null, $this->exercise->getTitle()); + $this->xmlElement("Description", null, $this->exercise->getDescription()); + //$this->xmlElement("Instruction", null,$this->exercise->getInstruction()); + //$this->xmlElement("DueDate", null,$this->exercise->getTimestamp()); + - //todo: as a workaround use first assignment for compatibility with old exercise dtd - $assignments = ilExAssignment::getAssignmentDataOfExercise ( $this->exercise->getId () ); - - if (count ( $assignments ) > 0) { - foreach ( $assignments as $assignment ) { - $this->xmlStartTag ("Assignment"); - $this->xmlElement ( "Instruction", null, $assignment ["instruction"] ); - $this->xmlElement ( "DueDate", null, $assignment ["deadline"] ); - - $this->handleAssignmentFiles ( $this->exercise->getId (), $assignment ["id"] ); - if ($this->attachMembers) - { - $this->handleAssignmentMembers ($this->exercise->getId (), $assignment ["id"]); - } - $this->xmlEndTag ( "Assignment" ); - } - } - + //todo: as a workaround use first assignment for compatibility with old exercise dtd + $assignments = ilExAssignment::getAssignmentDataOfExercise($this->exercise->getId()); + + if (count($assignments) > 0) { + foreach ($assignments as $assignment) { + $this->xmlStartTag("Assignment"); + $this->xmlElement("Instruction", null, $assignment ["instruction"]); + $this->xmlElement("DueDate", null, $assignment ["deadline"]); + + $this->handleAssignmentFiles($this->exercise->getId(), $assignment ["id"]); + if ($this->attachMembers) { + $this->handleAssignmentMembers($this->exercise->getId(), $assignment ["id"]); + } + $this->xmlEndTag("Assignment"); + } + } + - $this->xmlEndTag ( "Exercise" ); - $this->__buildFooter (); - - return true; - } - - function getXML() { - return $this->xmlDumpMem ( FALSE ); - } - - function __buildHeader() { - $this->xmlSetDtdDef ( "" ); - $this->xmlSetGenCmt ( "Exercise Object" ); - $this->xmlHeader (); - - return true; - } - - function __buildFooter() { - - } - - /** - * write access to property attchMarkings - * - * @param boolean $value - */ - public function setAttachMembers($value) { - $this->attachMembers = $value ? true : false; - } - - /** - * attach marking tag to member for given assignment - * - * @param int $user_id - * @param int $assignment_id - */ - private function attachMarking($user_id, $assignment_id) { + $this->xmlEndTag("Exercise"); + $this->__buildFooter(); + + return true; + } + + public function getXML() + { + return $this->xmlDumpMem(false); + } + + public function __buildHeader() + { + $this->xmlSetDtdDef(""); + $this->xmlSetGenCmt("Exercise Object"); + $this->xmlHeader(); + + return true; + } + + public function __buildFooter() + { + } + + /** + * write access to property attchMarkings + * + * @param boolean $value + */ + public function setAttachMembers($value) + { + $this->attachMembers = $value ? true : false; + } + + /** + * attach marking tag to member for given assignment + * + * @param int $user_id + * @param int $assignment_id + */ + private function attachMarking($user_id, $assignment_id) + { + $ass = new ilExAssignment($assignment_id); - $ass = new ilExAssignment($assignment_id); - - $amark = $ass->getMemberStatus($user_id)->getMark(); - $astatus = $ass->getMemberStatus($user_id)->getStatus(); - $acomment = $ass->getMemberStatus($user_id)->getComment(); - $anotice = $ass->getMemberStatus($user_id)->getNotice(); - - - if ($astatus == "notgraded") { - $status = ilExerciseXMLWriter::$STATUS_NOT_GRADED; - } elseif ($astatus == "failed") { - $status = ilExerciseXMLWriter::$STATUS_FAILED; - } else { - $status = ilExerciseXMLWriter::$STATUS_PASSED; - } - - $this->xmlStartTag ( "Marking", array ("status" => $status ) ); - $this->xmlElement ( "Mark", null, $amark); - $this->xmlElement ( "Notice", null, $anotice ); - $this->xmlElement ( "Comment", null, $acomment ); - $this->xmlEndTag ( "Marking" ); - } - - private function handleAssignmentFiles($ex_id, $as_id) { - $this->xmlStartTag ( "Files" ); - include_once ("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); - $storage = new ilFSStorageExercise ( $ex_id, $as_id ); - $files = $storage->getFiles (); - - if (count ( $files )) { - foreach ( $files as $file ) { - $this->xmlStartTag ( "File", array ("size" => $file ["size"] ) ); - $this->xmlElement ( "Filename", null, $file ["name"] ); - if ($this->attachFileContents) { - $filename = $file ["fullpath"]; - if (@is_file ( $filename )) { - $content = @file_get_contents ( $filename ); - $attribs = array ("mode" => "PLAIN" ); - if ($this->attachFileContents == ilExerciseXMLWriter::$CONTENT_ATTACH_ZLIB_ENCODED) { - $attribs = array ("mode" => "ZLIB" ); - $content = gzcompress ( $content, 9 ); - } elseif ($this->attachFileContents == ilExerciseXMLWriter::$CONTENT_ATTACH_GZIP_ENCODED) { - $attribs = array ("mode" => "GZIP" ); - $content = gzencode ( $content, 9 ); - } - $content = base64_encode ( $content ); - $this->xmlElement ( "Content", $attribs, $content ); - } - } - $this->xmlEndTag ( "File" ); - } - } - $this->xmlEndTag ( "Files" ); - } - - /** - * create xml for files per assignment - * - * @param integer $ex_id exercise id - * @param array $assignments assignment id - */ - private function handleAssignmentMembers($ex_id, $assignment_id) { - $this->xmlStartTag ( "Members" ); - include_once ("./Modules/Exercise/classes/class.ilExerciseMembers.php"); - $members = ilExerciseMembers::_getMembers($ex_id); - if (count ( $members )) { - foreach ( $members as $member_id ) { - $this->xmlStartTag ( "Member", array ("usr_id" => "il_" . IL_INST_ID . "_usr_" . $member_id ) ); - - $name = ilObjUser::_lookupName($member_id); - - $this->xmlElement("Firstname", array(), $name['firstname']); - $this->xmlElement("Lastname", array(), $name['lastname']); - $this->xmlElement("Login", array(), $name['login']); - $this->attachMarking ( $member_id, $assignment_id); - $this->xmlEndTag ( "Member" ); - } - } - $this->xmlEndTag ( "Members" ); - } + $amark = $ass->getMemberStatus($user_id)->getMark(); + $astatus = $ass->getMemberStatus($user_id)->getStatus(); + $acomment = $ass->getMemberStatus($user_id)->getComment(); + $anotice = $ass->getMemberStatus($user_id)->getNotice(); + + + if ($astatus == "notgraded") { + $status = ilExerciseXMLWriter::$STATUS_NOT_GRADED; + } elseif ($astatus == "failed") { + $status = ilExerciseXMLWriter::$STATUS_FAILED; + } else { + $status = ilExerciseXMLWriter::$STATUS_PASSED; + } + + $this->xmlStartTag("Marking", array("status" => $status )); + $this->xmlElement("Mark", null, $amark); + $this->xmlElement("Notice", null, $anotice); + $this->xmlElement("Comment", null, $acomment); + $this->xmlEndTag("Marking"); + } + + private function handleAssignmentFiles($ex_id, $as_id) + { + $this->xmlStartTag("Files"); + include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); + $storage = new ilFSStorageExercise($ex_id, $as_id); + $files = $storage->getFiles(); + + if (count($files)) { + foreach ($files as $file) { + $this->xmlStartTag("File", array("size" => $file ["size"] )); + $this->xmlElement("Filename", null, $file ["name"]); + if ($this->attachFileContents) { + $filename = $file ["fullpath"]; + if (@is_file($filename)) { + $content = @file_get_contents($filename); + $attribs = array("mode" => "PLAIN" ); + if ($this->attachFileContents == ilExerciseXMLWriter::$CONTENT_ATTACH_ZLIB_ENCODED) { + $attribs = array("mode" => "ZLIB" ); + $content = gzcompress($content, 9); + } elseif ($this->attachFileContents == ilExerciseXMLWriter::$CONTENT_ATTACH_GZIP_ENCODED) { + $attribs = array("mode" => "GZIP" ); + $content = gzencode($content, 9); + } + $content = base64_encode($content); + $this->xmlElement("Content", $attribs, $content); + } + } + $this->xmlEndTag("File"); + } + } + $this->xmlEndTag("Files"); + } + + /** + * create xml for files per assignment + * + * @param integer $ex_id exercise id + * @param array $assignments assignment id + */ + private function handleAssignmentMembers($ex_id, $assignment_id) + { + $this->xmlStartTag("Members"); + include_once("./Modules/Exercise/classes/class.ilExerciseMembers.php"); + $members = ilExerciseMembers::_getMembers($ex_id); + if (count($members)) { + foreach ($members as $member_id) { + $this->xmlStartTag("Member", array("usr_id" => "il_" . IL_INST_ID . "_usr_" . $member_id )); + + $name = ilObjUser::_lookupName($member_id); + + $this->xmlElement("Firstname", array(), $name['firstname']); + $this->xmlElement("Lastname", array(), $name['lastname']); + $this->xmlElement("Login", array(), $name['login']); + $this->attachMarking($member_id, $assignment_id); + $this->xmlEndTag("Member"); + } + } + $this->xmlEndTag("Members"); + } } - -?> diff --git a/Modules/Exercise/classes/class.ilFSStorageExercise.php b/Modules/Exercise/classes/class.ilFSStorageExercise.php index 14ac0b12c7eda70e56897ba6dd7302c182f77a74..52fa18d45791db8d306614bf03a65817a599720d 100644 --- a/Modules/Exercise/classes/class.ilFSStorageExercise.php +++ b/Modules/Exercise/classes/class.ilFSStorageExercise.php @@ -1,366 +1,349 @@ * @version $Id$ -* -* @ingroup ModulesExercise +* +* @ingroup ModulesExercise */ class ilFSStorageExercise extends ilFileSystemStorage { - /** - * Constructor - * - * @param int exercise id - */ - public function __construct($a_container_id = 0, $a_ass_id = 0) - { - $this->ass_id = $a_ass_id; - parent::__construct(self::STORAGE_DATA,true,$a_container_id); - } - - /** - * Append ass_ to path (assignment id) - */ - function init() - { - if (parent::init()) - { - if ($this->ass_id > 0) - { - $this->submission_path = $this->path."/subm_".$this->ass_id; - $this->tmp_path = $this->path."/tmp_".$this->ass_id; - $this->feedb_path = $this->path."/feedb_".$this->ass_id; - $this->multi_feedback_upload_path = $this->path."/mfb_up_".$this->ass_id; - $this->peer_review_upload_path = $this->path."/peer_up_".$this->ass_id; - $this->path.= "/ass_".$this->ass_id; - } - } - else - { - return false; - } - return true; - } - - - /** - * Implementation of abstract method - * - * @access protected - * - */ - protected function getPathPostfix() - { - return 'exc'; - } - - /** - * Implementation of abstract method - * - * @access protected - * - */ - protected function getPathPrefix() - { - return 'ilExercise'; - } - - /** - * Get submission path - */ - function getAbsoluteSubmissionPath() - { - return $this->submission_path; - } - - /** - * Get submission path - */ - function getTempPath() - { - return $this->tmp_path; - } + /** + * Constructor + * + * @param int exercise id + */ + public function __construct($a_container_id = 0, $a_ass_id = 0) + { + $this->ass_id = $a_ass_id; + parent::__construct(self::STORAGE_DATA, true, $a_container_id); + } + + /** + * Append ass_ to path (assignment id) + */ + public function init() + { + if (parent::init()) { + if ($this->ass_id > 0) { + $this->submission_path = $this->path . "/subm_" . $this->ass_id; + $this->tmp_path = $this->path . "/tmp_" . $this->ass_id; + $this->feedb_path = $this->path . "/feedb_" . $this->ass_id; + $this->multi_feedback_upload_path = $this->path . "/mfb_up_" . $this->ass_id; + $this->peer_review_upload_path = $this->path . "/peer_up_" . $this->ass_id; + $this->path.= "/ass_" . $this->ass_id; + } + } else { + return false; + } + return true; + } + + + /** + * Implementation of abstract method + * + * @access protected + * + */ + protected function getPathPostfix() + { + return 'exc'; + } + + /** + * Implementation of abstract method + * + * @access protected + * + */ + protected function getPathPrefix() + { + return 'ilExercise'; + } + + /** + * Get submission path + */ + public function getAbsoluteSubmissionPath() + { + return $this->submission_path; + } + + /** + * Get submission path + */ + public function getTempPath() + { + return $this->tmp_path; + } - /** - * Get feedback path - */ - function getFeedbackPath($a_user_id) - { - $path = $this->feedb_path."/".$a_user_id; - if(!file_exists($path)) - { - ilUtil::makeDirParents($path); - } - return $path; - } - - function getGlobalFeedbackPath() - { - $path = $this->feedb_path."/0"; - if(!file_exists($path)) - { - ilUtil::makeDirParents($path); - } - return $path; - } + /** + * Get feedback path + */ + public function getFeedbackPath($a_user_id) + { + $path = $this->feedb_path . "/" . $a_user_id; + if (!file_exists($path)) { + ilUtil::makeDirParents($path); + } + return $path; + } + + public function getGlobalFeedbackPath() + { + $path = $this->feedb_path . "/0"; + if (!file_exists($path)) { + ilUtil::makeDirParents($path); + } + return $path; + } - /** - * Get multi feedback upload path - * (each uploader handled in a separate path) - */ - function getMultiFeedbackUploadPath($a_user_id) - { - $path = $this->multi_feedback_upload_path."/".$a_user_id; - if(!file_exists($path)) - { - ilUtil::makeDirParents($path); - } - return $path; - } - - /** - * Get pear review upload path - * (each peer handled in a separate path) - */ - function getPeerReviewUploadPath($a_peer_id, $a_giver_id, $a_crit_id) - { - $path = $this->peer_review_upload_path."/".$a_peer_id."/".$a_giver_id."/"; + /** + * Get multi feedback upload path + * (each uploader handled in a separate path) + */ + public function getMultiFeedbackUploadPath($a_user_id) + { + $path = $this->multi_feedback_upload_path . "/" . $a_user_id; + if (!file_exists($path)) { + ilUtil::makeDirParents($path); + } + return $path; + } + + /** + * Get pear review upload path + * (each peer handled in a separate path) + */ + public function getPeerReviewUploadPath($a_peer_id, $a_giver_id, $a_crit_id) + { + $path = $this->peer_review_upload_path . "/" . $a_peer_id . "/" . $a_giver_id . "/"; - if((int)$a_crit_id) - { - $path .= (int)$a_crit_id."/"; - } - if(!file_exists($path)) - { - ilUtil::makeDirParents($path); - } - return $path; - } - - /** - * Create directory - * - * @access public - * - */ - public function create() - { - parent::create(); - if(!file_exists($this->submission_path)) - { - ilUtil::makeDirParents($this->submission_path); - } - if(!file_exists($this->tmp_path)) - { - ilUtil::makeDirParents($this->tmp_path); - } - if(!file_exists($this->feedb_path)) - { - ilUtil::makeDirParents($this->feedb_path); - } - return true; - } + if ((int) $a_crit_id) { + $path .= (int) $a_crit_id . "/"; + } + if (!file_exists($path)) { + ilUtil::makeDirParents($path); + } + return $path; + } + + /** + * Create directory + * + * @access public + * + */ + public function create() + { + parent::create(); + if (!file_exists($this->submission_path)) { + ilUtil::makeDirParents($this->submission_path); + } + if (!file_exists($this->tmp_path)) { + ilUtil::makeDirParents($this->tmp_path); + } + if (!file_exists($this->feedb_path)) { + ilUtil::makeDirParents($this->feedb_path); + } + return true; + } - /** - * Get assignment files - */ - function getFiles() - { - $files = array(); - if (!is_dir($this->path)) - { - return $files; - } + /** + * Get assignment files + */ + public function getFiles() + { + $files = array(); + if (!is_dir($this->path)) { + return $files; + } - $dp = opendir($this->path); - while($file = readdir($dp)) - { - if(!is_dir($this->path.'/'.$file)) - { - $files[] = array( - 'name' => $file, - 'size' => filesize($this->path.'/'.$file), - 'ctime' => filectime($this->path.'/'.$file), - 'fullpath' => $this->path.'/'.$file); - } - } - closedir($dp); - $files = ilUtil::sortArray($files, "name", "asc"); - return $files; - } - - - //// - //// Handle submitted files - //// - - /** - * store delivered file in filesystem - * @param array HTTP_POST_FILES - * @param numeric database id of the user who delivered the file - * @access public - * @return mixed Returns a result array with filename and mime type of the saved file, otherwise false - */ - function uploadFile($a_http_post_file, $user_id, $is_unziped = false) - { - $this->create(); - // TODO: - // CHECK UPLOAD LIMIT + $dp = opendir($this->path); + while ($file = readdir($dp)) { + if (!is_dir($this->path . '/' . $file)) { + $files[] = array( + 'name' => $file, + 'size' => filesize($this->path . '/' . $file), + 'ctime' => filectime($this->path . '/' . $file), + 'fullpath' => $this->path . '/' . $file); + } + } + closedir($dp); + $files = ilUtil::sortArray($files, "name", "asc"); + return $files; + } + + + //// + //// Handle submitted files + //// + + /** + * store delivered file in filesystem + * @param array HTTP_POST_FILES + * @param numeric database id of the user who delivered the file + * @access public + * @return mixed Returns a result array with filename and mime type of the saved file, otherwise false + */ + public function uploadFile($a_http_post_file, $user_id, $is_unziped = false) + { + $this->create(); + // TODO: + // CHECK UPLOAD LIMIT - // - $result = false; - if(isset($a_http_post_file) && $a_http_post_file['size']) - { - $filename = $a_http_post_file['name']; + // + $result = false; + if (isset($a_http_post_file) && $a_http_post_file['size']) { + $filename = $a_http_post_file['name']; - include_once("./Services/Utilities/classes/class.ilFileUtils.php"); - $filename = ilFileUtils::getValidFilename($filename); + include_once("./Services/Utilities/classes/class.ilFileUtils.php"); + $filename = ilFileUtils::getValidFilename($filename); - // replace whitespaces with underscores - $filename = preg_replace("/\s/", "_", $filename); - // remove all special characters - $filename = preg_replace("/[^_a-zA-Z0-9\.]/", "", $filename); + // replace whitespaces with underscores + $filename = preg_replace("/\s/", "_", $filename); + // remove all special characters + $filename = preg_replace("/[^_a-zA-Z0-9\.]/", "", $filename); - if(!is_dir($savepath = $this->getAbsoluteSubmissionPath())) - { - ilUtil::makeDir($savepath); - } - $savepath .= '/' .$user_id; - if(!is_dir($savepath)) - { - ilUtil::makeDir($savepath); - } + if (!is_dir($savepath = $this->getAbsoluteSubmissionPath())) { + ilUtil::makeDir($savepath); + } + $savepath .= '/' . $user_id; + if (!is_dir($savepath)) { + ilUtil::makeDir($savepath); + } - // CHECK IF FILE PATH EXISTS - if (!is_dir($savepath)) - { - ilUtil::makeDir($savepath); - } - $now = getdate(); - $prefix = sprintf("%04d%02d%02d%02d%02d%02d", $now["year"], $now["mon"], $now["mday"], $now["hours"], - $now["minutes"], $now["seconds"]); + // CHECK IF FILE PATH EXISTS + if (!is_dir($savepath)) { + ilUtil::makeDir($savepath); + } + $now = getdate(); + $prefix = sprintf( + "%04d%02d%02d%02d%02d%02d", + $now["year"], + $now["mon"], + $now["mday"], + $now["hours"], + $now["minutes"], + $now["seconds"] + ); - if (!$is_unziped) - { - ilUtil::moveUploadedFile($a_http_post_file["tmp_name"], $prefix . "_" . $filename, - $savepath . "/" . $prefix . "_" . $filename); - } - else - { + if (!$is_unziped) { + ilUtil::moveUploadedFile( + $a_http_post_file["tmp_name"], + $prefix . "_" . $filename, + $savepath . "/" . $prefix . "_" . $filename + ); + } else { + rename( + $a_http_post_file['tmp_name'], + $savepath . "/" . $prefix . "_" . $filename + ); + } - rename($a_http_post_file['tmp_name'], - $savepath . "/" . $prefix . "_" . $filename); - } + require_once "./Services/MediaObjects/classes/class.ilObjMediaObject.php"; + if (is_file($savepath . "/" . $prefix . "_" . $filename)) { + $result = array( + "filename" => $prefix . "_" . $filename, + "fullname" => $savepath . "/" . $prefix . "_" . $filename, + "mimetype" => ilObjMediaObject::getMimeType($savepath . "/" . $prefix . "_" . $filename) + ); + } + } + return $result; + } - require_once "./Services/MediaObjects/classes/class.ilObjMediaObject.php"; - if (is_file($savepath . "/" . $prefix . "_" . $filename)) - { - $result = array( - "filename" => $prefix . "_" . $filename, - "fullname" => $savepath . "/" . $prefix . "_" . $filename, - "mimetype" => ilObjMediaObject::getMimeType($savepath . "/" . $prefix . "_" . $filename) - ); - } - } - return $result; - } + /** + * Get number of feedback files + */ + public function getFeedbackFiles($a_user_id) + { + $files = array(); + + $dir = $this->getFeedbackPath($a_user_id); + if (@is_dir($dir)) { + $dp = opendir($dir); + while ($file = readdir($dp)) { + if (!is_dir($this->path . '/' . $file) && substr($file, 0, 1) != ".") { + $files[] = $file; + } + } + } + + return $files; + } + + /** + * Count number of feedback files for a user + */ + public function countFeedbackFiles($a_user_id) + { + $fbf = $this->getFeedbackFiles($a_user_id); + return count($fbf); + } + + /** + * Get path for assignment file + */ + public function getAssignmentFilePath($a_file) + { + return $this->getAbsolutePath() . "/" . $a_file; + } + + /** + * Get path for feedback file + */ + public function getFeedbackFilePath($a_user_id, $a_file) + { + $dir = $this->getFeedbackPath($a_user_id); + return $dir . "/" . $a_file; + } - /** - * Get number of feedback files - */ - function getFeedbackFiles($a_user_id) - { - $files = array(); - - $dir = $this->getFeedbackPath($a_user_id); - if (@is_dir($dir)) - { - $dp = opendir($dir); - while($file = readdir($dp)) - { - if(!is_dir($this->path.'/'.$file) && substr($file, 0, 1) != ".") - { - $files[] = $file; - } - } - } - - return $files; - } - - /** - * Count number of feedback files for a user - */ - function countFeedbackFiles($a_user_id) - { - $fbf = $this->getFeedbackFiles($a_user_id); - return count($fbf); - } - - /** - * Get path for assignment file - */ - function getAssignmentFilePath($a_file) - { - return $this->getAbsolutePath()."/".$a_file; - } - - /** - * Get path for feedback file - */ - function getFeedbackFilePath($a_user_id, $a_file) - { - $dir = $this->getFeedbackPath($a_user_id); - return $dir."/".$a_file; - } - - /** - * Upload assignment files - * (e.g. from assignment creation form) - */ - function uploadAssignmentFiles($a_files) - { - if (is_array($a_files["name"])) - { - foreach ($a_files["name"] as $k => $name) - { - if ($name != "") - { - $type = $a_files["type"][$k]; - $tmp_name = $a_files["tmp_name"][$k]; - $size = $a_files["size"][$k]; - ilUtil::moveUploadedFile($tmp_name, - basename($name), - $this->path.DIRECTORY_SEPARATOR.basename($name), - false); - } - } - } - } + /** + * Upload assignment files + * (e.g. from assignment creation form) + */ + public function uploadAssignmentFiles($a_files) + { + if (is_array($a_files["name"])) { + foreach ($a_files["name"] as $k => $name) { + if ($name != "") { + $type = $a_files["type"][$k]; + $tmp_name = $a_files["tmp_name"][$k]; + $size = $a_files["size"][$k]; + ilUtil::moveUploadedFile( + $tmp_name, + basename($name), + $this->path . DIRECTORY_SEPARATOR . basename($name), + false + ); + } + } + } + } } -?> \ No newline at end of file diff --git a/Modules/Exercise/classes/class.ilFSWebStorageExercise.php b/Modules/Exercise/classes/class.ilFSWebStorageExercise.php index 8c52b02b1a598bb0d31466776e139c686cc25a74..6de51ca76a6066443772782569d656a116163ab4 100644 --- a/Modules/Exercise/classes/class.ilFSWebStorageExercise.php +++ b/Modules/Exercise/classes/class.ilFSWebStorageExercise.php @@ -11,148 +11,138 @@ require_once('./Services/FileSystem/classes/class.ilFileSystemStorage.php'); */ class ilFSWebStorageExercise extends ilFileSystemStorage { - protected $log; - protected $ass_id; - - /** - * Constructor - * - * @param int assingment id - */ - public function __construct($a_container_id = 0, $a_ass_id = 0) - { - $this->ass_id = $a_ass_id; - $this->log = ilLoggerFactory::getLogger("exc"); - $this->log->debug("ilFSWebStorageExercise construct with a_container_id = ".$a_container_id." and ass_id =".$a_ass_id); - parent::__construct(self::STORAGE_WEB,true,$a_container_id); - } - - /** - * Append ass_ to path (assignment id) - */ - function init() - { - if (parent::init()) - { - if ($this->ass_id > 0) - { - $this->log->debug("parent init() with ass_id =".$this->ass_id); - $this->path.= "/ass_".$this->ass_id; - } - } - else - { - $this->log->debug("no parent init() without ass_id"); - return false; - } - return true; - } - - - /** - * Implementation of abstract method - * - * @access protected - * - */ - protected function getPathPostfix() - { - return 'exc'; - } - - /** - * Implementation of abstract method - * - * @access protected - * - */ - protected function getPathPrefix() - { - return 'ilExercise'; - } - - /** - * Create directory - * - * @access public - * - */ - public function create() - { - $this->log->debug("parent create"); - - parent::create(); - - return true; - - } - - /** - * Get assignment files - */ - function getFiles() - { - require_once "./Modules/Exercise/classes/class.ilExAssignment.php"; - - $ass = new ilExAssignment($this->ass_id); - $files_order = $ass->getInstructionFilesOrder(); - - $files = array(); - if (!is_dir($this->path)) - { - return $files; - } - - $dp = opendir($this->path); - while($file = readdir($dp)) - { - if(!is_dir($this->path.'/'.$file)) - { - $files[] = array( - 'name' => $file, - 'size' => filesize($this->path.'/'.$file), - 'ctime' => filectime($this->path.'/'.$file), - 'fullpath' => $this->path.'/'.$file, - 'order' => $files_order[$file]["order_nr"] ? $files_order[$file]["order_nr"] : 0 - ); - } - } - closedir($dp); - $files = ilUtil::sortArray($files, "order", "asc", true); - return $files; - } - - /** - * Get path for assignment file - */ - function getAssignmentFilePath($a_file) - { - return $this->getAbsolutePath()."/".$a_file; - } - - /** - * Upload assignment files - * (e.g. from assignment creation form) - */ - - function uploadAssignmentFiles($a_files) - { - if (is_array($a_files["name"])) - { - foreach ($a_files["name"] as $k => $name) - { - if ($name != "") - { - $type = $a_files["type"][$k]; - $tmp_name = $a_files["tmp_name"][$k]; - $size = $a_files["size"][$k]; - ilUtil::moveUploadedFile($tmp_name, - basename($name), - $this->path.DIRECTORY_SEPARATOR.basename($name), - false); - } - } - } - } - -} \ No newline at end of file + protected $log; + protected $ass_id; + + /** + * Constructor + * + * @param int assingment id + */ + public function __construct($a_container_id = 0, $a_ass_id = 0) + { + $this->ass_id = $a_ass_id; + $this->log = ilLoggerFactory::getLogger("exc"); + $this->log->debug("ilFSWebStorageExercise construct with a_container_id = " . $a_container_id . " and ass_id =" . $a_ass_id); + parent::__construct(self::STORAGE_WEB, true, $a_container_id); + } + + /** + * Append ass_ to path (assignment id) + */ + public function init() + { + if (parent::init()) { + if ($this->ass_id > 0) { + $this->log->debug("parent init() with ass_id =" . $this->ass_id); + $this->path.= "/ass_" . $this->ass_id; + } + } else { + $this->log->debug("no parent init() without ass_id"); + return false; + } + return true; + } + + + /** + * Implementation of abstract method + * + * @access protected + * + */ + protected function getPathPostfix() + { + return 'exc'; + } + + /** + * Implementation of abstract method + * + * @access protected + * + */ + protected function getPathPrefix() + { + return 'ilExercise'; + } + + /** + * Create directory + * + * @access public + * + */ + public function create() + { + $this->log->debug("parent create"); + + parent::create(); + + return true; + } + + /** + * Get assignment files + */ + public function getFiles() + { + require_once "./Modules/Exercise/classes/class.ilExAssignment.php"; + + $ass = new ilExAssignment($this->ass_id); + $files_order = $ass->getInstructionFilesOrder(); + + $files = array(); + if (!is_dir($this->path)) { + return $files; + } + + $dp = opendir($this->path); + while ($file = readdir($dp)) { + if (!is_dir($this->path . '/' . $file)) { + $files[] = array( + 'name' => $file, + 'size' => filesize($this->path . '/' . $file), + 'ctime' => filectime($this->path . '/' . $file), + 'fullpath' => $this->path . '/' . $file, + 'order' => $files_order[$file]["order_nr"] ? $files_order[$file]["order_nr"] : 0 + ); + } + } + closedir($dp); + $files = ilUtil::sortArray($files, "order", "asc", true); + return $files; + } + + /** + * Get path for assignment file + */ + public function getAssignmentFilePath($a_file) + { + return $this->getAbsolutePath() . "/" . $a_file; + } + + /** + * Upload assignment files + * (e.g. from assignment creation form) + */ + + public function uploadAssignmentFiles($a_files) + { + if (is_array($a_files["name"])) { + foreach ($a_files["name"] as $k => $name) { + if ($name != "") { + $type = $a_files["type"][$k]; + $tmp_name = $a_files["tmp_name"][$k]; + $size = $a_files["size"][$k]; + ilUtil::moveUploadedFile( + $tmp_name, + basename($name), + $this->path . DIRECTORY_SEPARATOR . basename($name), + false + ); + } + } + } + } +} diff --git a/Modules/Exercise/classes/class.ilFeedbackConfirmationTable2GUI.php b/Modules/Exercise/classes/class.ilFeedbackConfirmationTable2GUI.php index 0909e5b42db23cae26635fecdec7b13e8c4b990a..00e1b9efd6279d5c0baff3e568e6b9ded4c1308a 100644 --- a/Modules/Exercise/classes/class.ilFeedbackConfirmationTable2GUI.php +++ b/Modules/Exercise/classes/class.ilFeedbackConfirmationTable2GUI.php @@ -5,7 +5,7 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); /** - * TableGUI class for + * TableGUI class for * * @author Alex Killing * @version $Id$ @@ -14,68 +14,66 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilFeedbackConfirmationTable2GUI extends ilTable2GUI { - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_ass) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_ass) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $this->user = $DIC->user(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilAccess = $DIC->access(); - $lng = $DIC->language(); - $ilUser = $DIC->user(); - - $this->ass = $a_ass; - $this->setId("exc_mdf_upload"); - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setLimit(9999); - $this->setData($this->ass->getMultiFeedbackFiles($ilUser->getId())); - $this->setTitle($lng->txt("exc_multi_feedback_files")); - $this->setSelectAllCheckbox("file[]"); - - $this->addColumn("", "", "1px", true); - $this->addColumn($this->lng->txt("lastname"), "lastname"); - $this->addColumn($this->lng->txt("firstname"), "firstname"); - $this->addColumn($this->lng->txt("login"), "login"); - $this->addColumn($this->lng->txt("file"), "file"); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.multi_feedback_confirmation_row.html", "Modules/Exercise"); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->user = $DIC->user(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilAccess = $DIC->access(); + $lng = $DIC->language(); + $ilUser = $DIC->user(); + + $this->ass = $a_ass; + $this->setId("exc_mdf_upload"); + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setLimit(9999); + $this->setData($this->ass->getMultiFeedbackFiles($ilUser->getId())); + $this->setTitle($lng->txt("exc_multi_feedback_files")); + $this->setSelectAllCheckbox("file[]"); + + $this->addColumn("", "", "1px", true); + $this->addColumn($this->lng->txt("lastname"), "lastname"); + $this->addColumn($this->lng->txt("firstname"), "firstname"); + $this->addColumn($this->lng->txt("login"), "login"); + $this->addColumn($this->lng->txt("file"), "file"); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.multi_feedback_confirmation_row.html", "Modules/Exercise"); - $this->addCommandButton("saveMultiFeedback", $lng->txt("save")); - $this->addCommandButton("cancelMultiFeedback", $lng->txt("cancel")); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - - $this->tpl->setVariable("FIRSTNAME", $a_set["firstname"]); - $this->tpl->setVariable("LASTNAME", $a_set["lastname"]); - $this->tpl->setVariable("LOGIN", $a_set["login"]); - $this->tpl->setVariable("FILE", $a_set["file"]); - $this->tpl->setVariable("POST_FILE", md5($a_set["file"])); - $this->tpl->setVariable("USER_ID", $a_set["user_id"]); - } + $this->addCommandButton("saveMultiFeedback", $lng->txt("save")); + $this->addCommandButton("cancelMultiFeedback", $lng->txt("cancel")); + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $this->tpl->setVariable("FIRSTNAME", $a_set["firstname"]); + $this->tpl->setVariable("LASTNAME", $a_set["lastname"]); + $this->tpl->setVariable("LOGIN", $a_set["login"]); + $this->tpl->setVariable("FILE", $a_set["file"]); + $this->tpl->setVariable("POST_FILE", md5($a_set["file"])); + $this->tpl->setVariable("USER_ID", $a_set["user_id"]); + } } -?> diff --git a/Modules/Exercise/classes/class.ilObjExercise.php b/Modules/Exercise/classes/class.ilObjExercise.php index 0fd6048e2a72c417f7b9d4c9a1a3fc01d20a24e9..88d892975f6152aede0aa042e1863266216c8803 100755 --- a/Modules/Exercise/classes/class.ilObjExercise.php +++ b/Modules/Exercise/classes/class.ilObjExercise.php @@ -18,866 +18,823 @@ require_once "./Modules/Exercise/classes/class.ilExerciseMembers.php"; */ class ilObjExercise extends ilObject { - /** - * @var ilObjUser - */ - protected $user; - - var $file_obj; - var $members_obj; - var $files; - - var $timestamp; - var $hour; - var $minutes; - var $day; - var $month; - var $year; - var $instruction; - var $certificate_visibility; - - var $tutor_feedback = 7; // [int] - - const TUTOR_FEEDBACK_MAIL = 1; - const TUTOR_FEEDBACK_TEXT = 2; - const TUTOR_FEEDBACK_FILE = 4; - - /** - * - * Indicates whether completion by submission is enabled or not - * - * @var boolean - * @access protected - * - */ - protected $completion_by_submission = false; - - /** - * @var \ILIAS\Filesystem\Filesystem - */ - private $webFilesystem; - - /** - * Constructor - * @access public - * @param integer reference_id or object_id - * @param boolean treat the id as reference_id (true) or object_id (false) - */ - function __construct($a_id = 0,$a_call_by_reference = true) - { - global $DIC; - - $this->db = $DIC->database(); - $this->app_event_handler = $DIC["ilAppEventHandler"]; - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - $this->setPassMode("all"); - $this->type = "exc"; - $this->webFilesystem = $DIC->filesystem()->web(); - - parent::__construct($a_id,$a_call_by_reference); - } - - // SET, GET METHODS - function setDate($a_hour,$a_minutes,$a_day,$a_month,$a_year) - { - $this->hour = (int) $a_hour; - $this->minutes = (int) $a_minutes; - $this->day = (int) $a_day; - $this->month = (int) $a_month; - $this->year = (int) $a_year; - $this->timestamp = mktime($this->hour,$this->minutes,0,$this->month,$this->day,$this->year); - return true; - } - function getTimestamp() - { - return $this->timestamp; - } - function setTimestamp($a_timestamp) - { - $this->timestamp = $a_timestamp; - } - function setInstruction($a_instruction) - { - $this->instruction = $a_instruction; - } - function getInstruction() - { - return $this->instruction; - } - - /** - * Set pass mode (all | nr) - * - * @param string pass mode - */ - function setPassMode($a_val) - { - $this->pass_mode = $a_val; - } - - /** - * Get pass mode (all | nr) - * - * @return string pass mode - */ - function getPassMode() - { - return $this->pass_mode; - } - - /** - * Set number of assignments that must be passed to pass the exercise - * - * @param integer pass nr - */ - function setPassNr($a_val) - { - $this->pass_nr = $a_val; - } - - /** - * Get number of assignments that must be passed to pass the exercise - * - * @return integer pass nr - */ - function getPassNr() - { - return $this->pass_nr; - } - - /** - * Set whether submissions of learners should be shown to other learners after deadline - * - * @param boolean show submissions - */ - function setShowSubmissions($a_val) - { - $this->show_submissions = $a_val; - } - - /** - * Get whether submissions of learners should be shown to other learners after deadline - * - * @return integer show submissions - */ - function getShowSubmissions() - { - return $this->show_submissions; - } - - -/* function getFiles() - { - return $this->files; - }*/ - - function checkDate() - { - return $this->hour == (int) date("H",$this->timestamp) and - $this->minutes == (int) date("i",$this->timestamp) and - $this->day == (int) date("d",$this->timestamp) and - $this->month == (int) date("m",$this->timestamp) and - $this->year == (int) date("Y",$this->timestamp); - - } - - function hasTutorFeedbackText() - { - return $this->tutor_feedback & self::TUTOR_FEEDBACK_TEXT; - } - - function hasTutorFeedbackMail() - { - return $this->tutor_feedback & self::TUTOR_FEEDBACK_MAIL; - } - - function hasTutorFeedbackFile() - { - return $this->tutor_feedback & self::TUTOR_FEEDBACK_FILE; - } - - protected function getTutorFeedback() - { - return $this->tutor_feedback; - } - - public function setTutorFeedback($a_value) - { - $this->tutor_feedback = $a_value; - } - - function saveData() - { - $ilDB = $this->db; - - $ilDB->insert("exc_data", array( - "obj_id" => array("integer", $this->getId()), - "instruction" => array("clob", $this->getInstruction()), - "time_stamp" => array("integer", $this->getTimestamp()), - "pass_mode" => array("text", $this->getPassMode()), - "pass_nr" => array("text", $this->getPassNr()), - "show_submissions" => array("integer", (int) $this->getShowSubmissions()), - 'compl_by_submission' => array('integer', (int)$this->isCompletionBySubmissionEnabled()), - "certificate_visibility" => array("integer", (int)$this->getCertificateVisibility()), - "tfeedback" => array("integer", (int)$this->getTutorFeedback()) - )); - return true; - } - - /** - * Clone exercise (no member data) - * - * @access public - * @param int target ref_id - * @param int copy id - */ - public function cloneObject($a_target_id,$a_copy_id = 0, $a_omit_tree = false) - { - $ilDB = $this->db; - - // Copy settings - $new_obj = parent::cloneObject($a_target_id,$a_copy_id, $a_omit_tree); - $new_obj->setInstruction($this->getInstruction()); - $new_obj->setTimestamp($this->getTimestamp()); - $new_obj->setPassMode($this->getPassMode()); - $new_obj->saveData(); - $new_obj->setPassNr($this->getPassNr()); - $new_obj->setShowSubmissions($this->getShowSubmissions()); - $new_obj->setCompletionBySubmission($this->isCompletionBySubmissionEnabled()); - $new_obj->setTutorFeedback($this->getTutorFeedback()); - $new_obj->setCertificateVisibility($this->getCertificateVisibility()); - $new_obj->update(); - - $new_obj->saveCertificateVisibility($this->getCertificateVisibility()); - - // Copy criteria catalogues - $crit_cat_map = array(); - include_once("./Modules/Exercise/classes/class.ilExcCriteriaCatalogue.php"); - foreach(ilExcCriteriaCatalogue::getInstancesByParentId($this->getId()) as $crit_cat) - { - $new_id = $crit_cat->cloneObject($new_obj->getId()); - $crit_cat_map[$crit_cat->getId()] = $new_id; - } - - // Copy assignments - include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); - ilExAssignment::cloneAssignmentsOfExercise($this->getId(), $new_obj->getId(), $crit_cat_map); - - // Copy learning progress settings - include_once('Services/Tracking/classes/class.ilLPObjSettings.php'); - $obj_settings = new ilLPObjSettings($this->getId()); - $obj_settings->cloneSettings($new_obj->getId()); - unset($obj_settings); - - $factory = new ilCertificateFactory(); - $templateRepository = new ilCertificateTemplateRepository($ilDB); - - $cloneAction = new ilCertificateCloneAction( - $ilDB, - $factory, - $templateRepository, - $this->webFilesystem, - $this->log, - new ilCertificateObjectHelper() - ); - - $cloneAction->cloneCertificate($this, $new_obj); - - return $new_obj; - } - - /** - * delete course and all related data - * - * @access public - * @return boolean true if all object data were removed; false if only a references were removed - */ - function delete() - { - $ilDB = $this->db; - $ilAppEventHandler = $this->app_event_handler; - - // always call parent delete function first!! - if (!parent::delete()) - { - return false; - } - // put here course specific stuff - $ilDB->manipulate("DELETE FROM exc_data ". - "WHERE obj_id = ".$ilDB->quote($this->getId(), "integer")); - - include_once "Modules/Exercise/classes/class.ilExcCriteriaCatalogue.php"; - ilExcCriteriaCatalogue::deleteByParent($this->getId()); - - // remove all notifications - include_once "./Services/Notification/classes/class.ilNotification.php"; - ilNotification::removeForObject(ilNotification::TYPE_EXERCISE_SUBMISSION, $this->getId()); - - $ilAppEventHandler->raise('Modules/Exercise', - 'delete', - array('obj_id'=>$this->getId())); - - return true; - } - - function read() - { - $ilDB = $this->db; - - parent::read(); - - $query = "SELECT * FROM exc_data ". - "WHERE obj_id = ".$ilDB->quote($this->getId(), "integer"); - - $res = $ilDB->query($query); - while($row = $ilDB->fetchObject($res)) - { - $this->setInstruction($row->instruction); - $this->setTimestamp($row->time_stamp); - $pm = ($row->pass_mode == "") - ? "all" - : $row->pass_mode; - $this->setPassMode($pm); - $this->setShowSubmissions($row->show_submissions); - if ($row->pass_mode == "nr") - { - $this->setPassNr($row->pass_nr); - } - $this->setCompletionBySubmission($row->compl_by_submission == 1 ? true : false); - $this->setCertificateVisibility($row->certificate_visibility); - $this->setTutorFeedback($row->tfeedback); - } - - $this->members_obj = new ilExerciseMembers($this); - - return true; - } - - function update() - { - $ilDB = $this->db; - - parent::update(); - - if ($this->getPassMode() == "all") - { - $pass_nr = null; - } - else - { - $pass_nr = $this->getPassNr(); - } - - $ilDB->update("exc_data", array( - "instruction" => array("clob", $this->getInstruction()), - "time_stamp" => array("integer", $this->getTimestamp()), - "pass_mode" => array("text", $this->getPassMode()), - "pass_nr" => array("integer", $this->getPassNr()), - "show_submissions" => array("integer", (int) $this->getShowSubmissions()), - 'compl_by_submission' => array('integer', (int)$this->isCompletionBySubmissionEnabled()), - 'tfeedback' => array('integer', (int)$this->getTutorFeedback()), - ), array( - "obj_id" => array("integer", $this->getId()) - )); - - $this->updateAllUsersStatus(); - - return true; - } - - /** - * send exercise per mail to members - */ - function sendAssignment(ilExAssignment $a_ass, $a_members) - { - $lng = $this->lng; - $ilUser = $this->user; - - $lng->loadLanguageModule("exc"); - - // subject - $subject = $a_ass->getTitle() - ? $this->getTitle().": ".$a_ass->getTitle() - : $this->getTitle(); - - - // body - - $body = $a_ass->getInstruction(); - $body .= "\n\n"; - - $body .= $lng->txt("exc_edit_until").": "; - $body .= (!$a_ass->getDeadline()) - ? $lng->txt("exc_no_deadline_specified") - : ilDatePresentation::formatDate(new ilDateTime($a_ass->getDeadline(), IL_CAL_UNIX)); - $body .= "\n\n"; - - include_once "Services/Link/classes/class.ilLink.php"; - $body .= ilLink::_getLink($this->getRefId(), "exc"); - - - // files - $file_names = array(); - include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); - $storage = new ilFSStorageExercise($a_ass->getExerciseId(), $a_ass->getId()); - $files = $storage->getFiles(); - if(count($files)) - { - include_once "./Services/Mail/classes/class.ilFileDataMail.php"; - $mfile_obj = new ilFileDataMail($GLOBALS['DIC']['ilUser']->getId()); - foreach($files as $file) - { - $mfile_obj->copyAttachmentFile($file["fullpath"], $file["name"]); - $file_names[] = $file["name"]; - } - } - - // recipients - $recipients = array(); - foreach($a_members as $member_id) - { - $tmp_obj = ilObjectFactory::getInstanceByObjId($member_id); - $recipients[] = $tmp_obj->getLogin(); - unset($tmp_obj); - } - $recipients = implode("," ,$recipients); - - // send mail - include_once "Services/Mail/classes/class.ilMail.php"; - $tmp_mail_obj = new ilMail($ilUser->getId()); - $errors = $tmp_mail_obj->sendMail( - $recipients, - "", - "", - $subject, - $body, - $file_names, - array("normal") - ); - unset($tmp_mail_obj); - - // remove tmp files - if(sizeof($file_names)) - { - $mfile_obj->unlinkFiles($file_names); - unset($mfile_obj); - } - - // set recipients mail status - foreach($a_members as $member_id) - { - $member_status = $a_ass->getMemberStatus($member_id); - $member_status->setSent(true); - $member_status->update(); - } - - return true; - } - - /** - * Determine status of user - */ - function determinStatusOfUser($a_user_id = 0) - { - $ilUser = $this->user; - - if ($a_user_id == 0) - { - $a_user_id = $ilUser->getId(); - } - - include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); - $ass = ilExAssignment::getInstancesByExercise($this->getId()); - - $passed_all_mandatory = true; - $failed_a_mandatory = false; - $cnt_passed = 0; - $cnt_notgraded = 0; - $passed_at_least_one = false; - - foreach ($ass as $a) - { - $stat = $a->getMemberStatus($a_user_id)->getStatus(); - if ($a->getMandatory() && ($stat == "failed" || $stat == "notgraded")) - { - $passed_all_mandatory = false; - } - if ($a->getMandatory() && ($stat == "failed")) - { - $failed_a_mandatory = true; - } - if ($stat == "passed") - { - $cnt_passed++; - } - if ($stat == "notgraded") - { - $cnt_notgraded++; - } - } - - if (count($ass) == 0) - { - $passed_all_mandatory = false; - } - - if ($this->getPassMode() != "nr") - { -//echo "5"; - $overall_stat = "notgraded"; - if ($failed_a_mandatory) - { -//echo "6"; - $overall_stat = "failed"; - } - else if ($passed_all_mandatory && $cnt_passed > 0) - { -//echo "7"; - $overall_stat = "passed"; - } - } - else - { -//echo "8"; - $min_nr = $this->getPassNr(); - $overall_stat = "notgraded"; -//echo "*".$cnt_passed."*".$cnt_notgraded."*".$min_nr."*"; - if ($failed_a_mandatory || ($cnt_passed + $cnt_notgraded < $min_nr)) - { -//echo "9"; - $overall_stat = "failed"; - } - else if ($passed_all_mandatory && $cnt_passed >= $min_nr) - { -//echo "A"; - $overall_stat = "passed"; - } - } - - $ret = array( - "overall_status" => $overall_stat, - "failed_a_mandatory" => $failed_a_mandatory); -//echo "
p:".$cnt_passed.":ng:".$cnt_notgraded; -//var_dump($ret); - return $ret; - } - - /** - * Update exercise status of user - */ - function updateUserStatus($a_user_id = 0) - { - $ilUser = $this->user; - - if ($a_user_id == 0) - { - $a_user_id = $ilUser->getId(); - } - - $st = $this->determinStatusOfUser($a_user_id); - - include_once("./Modules/Exercise/classes/class.ilExerciseMembers.php"); - ilExerciseMembers::_writeStatus($this->getId(), $a_user_id, - $st["overall_status"]); - } - - /** - * Update status of all users - */ - function updateAllUsersStatus() - { - if (!is_object($this->members_obj)) - { - $this->members_obj = new ilExerciseMembers($this); - } - - $mems = $this->members_obj->getMembers(); - foreach ($mems as $mem) - { - $this->updateUserStatus($mem); - } - } - - /** - * Exports grades as excel - */ - function exportGradesExcel() - { - include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); - $ass_data = ilExAssignment::getInstancesByExercise($this->getId()); - - include_once "./Services/Excel/classes/class.ilExcel.php"; - $excel = new ilExcel(); - $excel->addSheet($this->lng->txt("exc_status")); - - - // - // status - // - - // header row - $row = $cnt = 1; - $excel->setCell($row, 0, $this->lng->txt("name")); - foreach ($ass_data as $ass) - { - $excel->setCell($row, $cnt++, $cnt-1); - } - $excel->setCell($row, $cnt++, $this->lng->txt("exc_total_exc")); - $excel->setCell($row, $cnt++, $this->lng->txt("exc_mark")); - $excel->setCell($row++, $cnt, $this->lng->txt("exc_comment_for_learner")); - $excel->setBold("A1:".$excel->getColumnCoord($cnt)."1"); - - // data rows - $mem_obj = new ilExerciseMembers($this); - - $filtered_members = $GLOBALS['DIC']->access()->filterUserIdsByRbacOrPositionOfCurrentUser( - 'etit_submissions_grades', - 'edit_submissions_grades', - $this->getRefId(), - (array) $mem_obj->getMembers() - ); - - foreach((array) $filtered_members as $user_id) - { - $mems[$user_id] = ilObjUser::_lookupName($user_id); - } - $mems = ilUtil::sortArray($mems, "lastname", "asc", false, true); - - include_once 'Services/Tracking/classes/class.ilLPMarks.php'; - foreach ($mems as $user_id => $d) - { - $col = 0; - - // name - $excel->setCell($row, $col++, $d["lastname"].", ".$d["firstname"]." [".$d["login"]."]"); - - reset($ass_data); - foreach ($ass_data as $ass) - { - $status = $ass->getMemberStatus($user_id)->getStatus(); - $excel->setCell($row, $col++, $this->lng->txt("exc_".$status)); - } - - // total status - $status = ilExerciseMembers::_lookupStatus($this->getId(), $user_id); - $excel->setCell($row, $col++, $this->lng->txt("exc_".$status)); - - // #18096 - $marks_obj = new ilLPMarks($this->getId(), $user_id); - $excel->setCell($row, $col++, $marks_obj->getMark()); - $excel->setCell($row++, $col, $marks_obj->getComment()); - } - - - // - // mark - // - - $excel->addSheet($this->lng->txt("exc_mark")); - - // header row - $row = $cnt = 1; - $excel->setCell($row, 0, $this->lng->txt("name")); - foreach ($ass_data as $ass) - { - $excel->setCell($row, $cnt++, $cnt-1); - } - $excel->setCell($row++, $cnt++, $this->lng->txt("exc_total_exc")); - $excel->setBold("A1:".$excel->getColumnCoord($cnt)."1"); - - // data rows - reset($mems); - foreach ($mems as $user_id => $d) - { - $col = 0; - - // name - $d = ilObjUser::_lookupName($user_id); - $excel->setCell($row, $col++, $d["lastname"].", ".$d["firstname"]." [".$d["login"]."]"); - - reset($ass_data); - foreach ($ass_data as $ass) - { - $excel->setCell($row, $col++, $ass->getMemberStatus($user_id)->getMark()); - } - - // total mark - $excel->setCell($row++, $col, ilLPMarks::_lookupMark($user_id, $this->getId())); - } - - $exc_name = ilUtil::getASCIIFilename(preg_replace("/\s/", "_", $this->getTitle())); - $excel->sendToClient($exc_name); - } - - /** - * Send feedback file notification to user - */ - function sendFeedbackFileNotification($a_feedback_file, $a_user_id, $a_ass_id, $a_is_text_feedback = false) - { - $user_ids = $a_user_id; - if(!is_array($user_ids)) - { - $user_ids = array($user_ids); - } - - include_once("./Modules/Exercise/classes/class.ilExerciseMailNotification.php"); - - $type = (bool)$a_is_text_feedback - ? ilExerciseMailNotification::TYPE_FEEDBACK_TEXT_ADDED - : ilExerciseMailNotification::TYPE_FEEDBACK_FILE_ADDED; - - $not = new ilExerciseMailNotification(); - $not->setType($type); - $not->setAssignmentId($a_ass_id); - $not->setObjId($this->getId()); - if ($this->getRefId() > 0) - { - $not->setRefId($this->getRefId()); - } - $not->setRecipients($user_ids); - $not->send(); - } - - /** - * - * Checks whether completion by submission is enabled or not - * - * @return boolean - * @access public - * - */ - public function isCompletionBySubmissionEnabled() - { - return $this->completion_by_submission; - } - - /** - * - * Enabled/Disable completion by submission - * - * @param boolean - * @return ilObjExercise - * @access public - * - */ - public function setCompletionBySubmission($bool) - { - $this->completion_by_submission = (bool)$bool; - - return $this; - } - - public function processExerciseStatus(ilExAssignment $a_ass, array $a_user_ids, $a_has_submitted, array $a_valid_submissions = null) - { - $a_has_submitted = (bool)$a_has_submitted; - - include_once("./Modules/Exercise/classes/class.ilExerciseMembers.php"); - foreach($a_user_ids as $user_id) - { - $member_status = $a_ass->getMemberStatus($user_id); - $member_status->setReturned($a_has_submitted); - $member_status->update(); - - ilExerciseMembers::_writeReturned($this->getId(), $user_id, $a_has_submitted); - } - - // re-evaluate exercise status - if($this->isCompletionBySubmissionEnabled()) - { - foreach($a_user_ids as $user_id) - { - $status = 'notgraded'; - if($a_has_submitted) - { - if(!is_array($a_valid_submissions) || - $a_valid_submissions[$user_id]) - { - $status = 'passed'; - } - } - - $member_status = $a_ass->getMemberStatus($user_id); - $member_status->setStatus($status); - $member_status->update(); - } - } - } - - /** - * Get all exercises for user - * - * @param $a_user_id - * @return array (exercise id => passed) - */ - public static function _lookupFinishedUserExercises($a_user_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT obj_id, status FROM exc_members". - " WHERE usr_id = ".$ilDB->quote($a_user_id, "integer"). - " AND (status = ".$ilDB->quote("passed", "text"). - " OR status = ".$ilDB->quote("failed", "text").")"); - - $all = array(); - while($row = $ilDB->fetchAssoc($set)) - { - $all[$row["obj_id"]] = ($row["status"] == "passed"); - } - return $all; - } - - - /** - * Returns the visibility settings of the certificate - * - * @return integer The value for the visibility settings (0 = always, 1 = only passed, 2 = never) - * @access public - */ - function getCertificateVisibility() - { - return (strlen($this->certificate_visibility)) ? $this->certificate_visibility : 0; - } - - /** - * Sets the visibility settings of the certificate - * - * @param integer $a_value The value for the visibility settings (0 = always, 1 = only passed, 2 = never) - * @access public - */ - function setCertificateVisibility($a_value) - { - $this->certificate_visibility = $a_value; - } - - /** - * Saves the visibility settings of the certificate - * - * @param integer $a_value The value for the visibility settings (0 = always, 1 = only passed, 2 = never) - * @access private - */ - function saveCertificateVisibility($a_value) - { - $ilDB = $this->db; - - $affectedRows = $ilDB->manipulateF("UPDATE exc_data SET certificate_visibility = %s WHERE obj_id = %s", - array('integer', 'integer'), - array($a_value, $this->getId()) - ); - } - - /** - * Add to desktop after hand-in - * - * @return bool - */ - function hasAddToDesktop() - { - $exc_set = new ilSetting("excs"); - return (bool)$exc_set->get("add_to_pd", true); - } + /** + * @var ilObjUser + */ + protected $user; + + public $file_obj; + public $members_obj; + public $files; + + public $timestamp; + public $hour; + public $minutes; + public $day; + public $month; + public $year; + public $instruction; + public $certificate_visibility; + + public $tutor_feedback = 7; // [int] + + const TUTOR_FEEDBACK_MAIL = 1; + const TUTOR_FEEDBACK_TEXT = 2; + const TUTOR_FEEDBACK_FILE = 4; + + /** + * + * Indicates whether completion by submission is enabled or not + * + * @var boolean + * @access protected + * + */ + protected $completion_by_submission = false; + + /** + * @var \ILIAS\Filesystem\Filesystem + */ + private $webFilesystem; + + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + global $DIC; + + $this->db = $DIC->database(); + $this->app_event_handler = $DIC["ilAppEventHandler"]; + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + $this->setPassMode("all"); + $this->type = "exc"; + $this->webFilesystem = $DIC->filesystem()->web(); + + parent::__construct($a_id, $a_call_by_reference); + } + + // SET, GET METHODS + public function setDate($a_hour, $a_minutes, $a_day, $a_month, $a_year) + { + $this->hour = (int) $a_hour; + $this->minutes = (int) $a_minutes; + $this->day = (int) $a_day; + $this->month = (int) $a_month; + $this->year = (int) $a_year; + $this->timestamp = mktime($this->hour, $this->minutes, 0, $this->month, $this->day, $this->year); + return true; + } + public function getTimestamp() + { + return $this->timestamp; + } + public function setTimestamp($a_timestamp) + { + $this->timestamp = $a_timestamp; + } + public function setInstruction($a_instruction) + { + $this->instruction = $a_instruction; + } + public function getInstruction() + { + return $this->instruction; + } + + /** + * Set pass mode (all | nr) + * + * @param string pass mode + */ + public function setPassMode($a_val) + { + $this->pass_mode = $a_val; + } + + /** + * Get pass mode (all | nr) + * + * @return string pass mode + */ + public function getPassMode() + { + return $this->pass_mode; + } + + /** + * Set number of assignments that must be passed to pass the exercise + * + * @param integer pass nr + */ + public function setPassNr($a_val) + { + $this->pass_nr = $a_val; + } + + /** + * Get number of assignments that must be passed to pass the exercise + * + * @return integer pass nr + */ + public function getPassNr() + { + return $this->pass_nr; + } + + /** + * Set whether submissions of learners should be shown to other learners after deadline + * + * @param boolean show submissions + */ + public function setShowSubmissions($a_val) + { + $this->show_submissions = $a_val; + } + + /** + * Get whether submissions of learners should be shown to other learners after deadline + * + * @return integer show submissions + */ + public function getShowSubmissions() + { + return $this->show_submissions; + } + + + /* function getFiles() + { + return $this->files; + }*/ + + public function checkDate() + { + return $this->hour == (int) date("H", $this->timestamp) and + $this->minutes == (int) date("i", $this->timestamp) and + $this->day == (int) date("d", $this->timestamp) and + $this->month == (int) date("m", $this->timestamp) and + $this->year == (int) date("Y", $this->timestamp); + } + + public function hasTutorFeedbackText() + { + return $this->tutor_feedback & self::TUTOR_FEEDBACK_TEXT; + } + + public function hasTutorFeedbackMail() + { + return $this->tutor_feedback & self::TUTOR_FEEDBACK_MAIL; + } + + public function hasTutorFeedbackFile() + { + return $this->tutor_feedback & self::TUTOR_FEEDBACK_FILE; + } + + protected function getTutorFeedback() + { + return $this->tutor_feedback; + } + + public function setTutorFeedback($a_value) + { + $this->tutor_feedback = $a_value; + } + + public function saveData() + { + $ilDB = $this->db; + + $ilDB->insert("exc_data", array( + "obj_id" => array("integer", $this->getId()), + "instruction" => array("clob", $this->getInstruction()), + "time_stamp" => array("integer", $this->getTimestamp()), + "pass_mode" => array("text", $this->getPassMode()), + "pass_nr" => array("text", $this->getPassNr()), + "show_submissions" => array("integer", (int) $this->getShowSubmissions()), + 'compl_by_submission' => array('integer', (int) $this->isCompletionBySubmissionEnabled()), + "certificate_visibility" => array("integer", (int) $this->getCertificateVisibility()), + "tfeedback" => array("integer", (int) $this->getTutorFeedback()) + )); + return true; + } + + /** + * Clone exercise (no member data) + * + * @access public + * @param int target ref_id + * @param int copy id + */ + public function cloneObject($a_target_id, $a_copy_id = 0, $a_omit_tree = false) + { + $ilDB = $this->db; + + // Copy settings + $new_obj = parent::cloneObject($a_target_id, $a_copy_id, $a_omit_tree); + $new_obj->setInstruction($this->getInstruction()); + $new_obj->setTimestamp($this->getTimestamp()); + $new_obj->setPassMode($this->getPassMode()); + $new_obj->saveData(); + $new_obj->setPassNr($this->getPassNr()); + $new_obj->setShowSubmissions($this->getShowSubmissions()); + $new_obj->setCompletionBySubmission($this->isCompletionBySubmissionEnabled()); + $new_obj->setTutorFeedback($this->getTutorFeedback()); + $new_obj->setCertificateVisibility($this->getCertificateVisibility()); + $new_obj->update(); + + $new_obj->saveCertificateVisibility($this->getCertificateVisibility()); + + // Copy criteria catalogues + $crit_cat_map = array(); + include_once("./Modules/Exercise/classes/class.ilExcCriteriaCatalogue.php"); + foreach (ilExcCriteriaCatalogue::getInstancesByParentId($this->getId()) as $crit_cat) { + $new_id = $crit_cat->cloneObject($new_obj->getId()); + $crit_cat_map[$crit_cat->getId()] = $new_id; + } + + // Copy assignments + include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); + ilExAssignment::cloneAssignmentsOfExercise($this->getId(), $new_obj->getId(), $crit_cat_map); + + // Copy learning progress settings + include_once('Services/Tracking/classes/class.ilLPObjSettings.php'); + $obj_settings = new ilLPObjSettings($this->getId()); + $obj_settings->cloneSettings($new_obj->getId()); + unset($obj_settings); + + $factory = new ilCertificateFactory(); + $templateRepository = new ilCertificateTemplateRepository($ilDB); + + $cloneAction = new ilCertificateCloneAction( + $ilDB, + $factory, + $templateRepository, + $this->webFilesystem, + $this->log, + new ilCertificateObjectHelper() + ); + + $cloneAction->cloneCertificate($this, $new_obj); + + return $new_obj; + } + + /** + * delete course and all related data + * + * @access public + * @return boolean true if all object data were removed; false if only a references were removed + */ + public function delete() + { + $ilDB = $this->db; + $ilAppEventHandler = $this->app_event_handler; + + // always call parent delete function first!! + if (!parent::delete()) { + return false; + } + // put here course specific stuff + $ilDB->manipulate("DELETE FROM exc_data " . + "WHERE obj_id = " . $ilDB->quote($this->getId(), "integer")); + + include_once "Modules/Exercise/classes/class.ilExcCriteriaCatalogue.php"; + ilExcCriteriaCatalogue::deleteByParent($this->getId()); + + // remove all notifications + include_once "./Services/Notification/classes/class.ilNotification.php"; + ilNotification::removeForObject(ilNotification::TYPE_EXERCISE_SUBMISSION, $this->getId()); + + $ilAppEventHandler->raise( + 'Modules/Exercise', + 'delete', + array('obj_id'=>$this->getId()) + ); + + return true; + } + + public function read() + { + $ilDB = $this->db; + + parent::read(); + + $query = "SELECT * FROM exc_data " . + "WHERE obj_id = " . $ilDB->quote($this->getId(), "integer"); + + $res = $ilDB->query($query); + while ($row = $ilDB->fetchObject($res)) { + $this->setInstruction($row->instruction); + $this->setTimestamp($row->time_stamp); + $pm = ($row->pass_mode == "") + ? "all" + : $row->pass_mode; + $this->setPassMode($pm); + $this->setShowSubmissions($row->show_submissions); + if ($row->pass_mode == "nr") { + $this->setPassNr($row->pass_nr); + } + $this->setCompletionBySubmission($row->compl_by_submission == 1 ? true : false); + $this->setCertificateVisibility($row->certificate_visibility); + $this->setTutorFeedback($row->tfeedback); + } + + $this->members_obj = new ilExerciseMembers($this); + + return true; + } + + public function update() + { + $ilDB = $this->db; + + parent::update(); + + if ($this->getPassMode() == "all") { + $pass_nr = null; + } else { + $pass_nr = $this->getPassNr(); + } + + $ilDB->update("exc_data", array( + "instruction" => array("clob", $this->getInstruction()), + "time_stamp" => array("integer", $this->getTimestamp()), + "pass_mode" => array("text", $this->getPassMode()), + "pass_nr" => array("integer", $this->getPassNr()), + "show_submissions" => array("integer", (int) $this->getShowSubmissions()), + 'compl_by_submission' => array('integer', (int) $this->isCompletionBySubmissionEnabled()), + 'tfeedback' => array('integer', (int) $this->getTutorFeedback()), + ), array( + "obj_id" => array("integer", $this->getId()) + )); + + $this->updateAllUsersStatus(); + + return true; + } + + /** + * send exercise per mail to members + */ + public function sendAssignment(ilExAssignment $a_ass, $a_members) + { + $lng = $this->lng; + $ilUser = $this->user; + + $lng->loadLanguageModule("exc"); + + // subject + $subject = $a_ass->getTitle() + ? $this->getTitle() . ": " . $a_ass->getTitle() + : $this->getTitle(); + + + // body + + $body = $a_ass->getInstruction(); + $body .= "\n\n"; + + $body .= $lng->txt("exc_edit_until") . ": "; + $body .= (!$a_ass->getDeadline()) + ? $lng->txt("exc_no_deadline_specified") + : ilDatePresentation::formatDate(new ilDateTime($a_ass->getDeadline(), IL_CAL_UNIX)); + $body .= "\n\n"; + + include_once "Services/Link/classes/class.ilLink.php"; + $body .= ilLink::_getLink($this->getRefId(), "exc"); + + + // files + $file_names = array(); + include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php"); + $storage = new ilFSStorageExercise($a_ass->getExerciseId(), $a_ass->getId()); + $files = $storage->getFiles(); + if (count($files)) { + include_once "./Services/Mail/classes/class.ilFileDataMail.php"; + $mfile_obj = new ilFileDataMail($GLOBALS['DIC']['ilUser']->getId()); + foreach ($files as $file) { + $mfile_obj->copyAttachmentFile($file["fullpath"], $file["name"]); + $file_names[] = $file["name"]; + } + } + + // recipients + $recipients = array(); + foreach ($a_members as $member_id) { + $tmp_obj = ilObjectFactory::getInstanceByObjId($member_id); + $recipients[] = $tmp_obj->getLogin(); + unset($tmp_obj); + } + $recipients = implode(",", $recipients); + + // send mail + include_once "Services/Mail/classes/class.ilMail.php"; + $tmp_mail_obj = new ilMail($ilUser->getId()); + $errors = $tmp_mail_obj->sendMail( + $recipients, + "", + "", + $subject, + $body, + $file_names, + array("normal") + ); + unset($tmp_mail_obj); + + // remove tmp files + if (sizeof($file_names)) { + $mfile_obj->unlinkFiles($file_names); + unset($mfile_obj); + } + + // set recipients mail status + foreach ($a_members as $member_id) { + $member_status = $a_ass->getMemberStatus($member_id); + $member_status->setSent(true); + $member_status->update(); + } + + return true; + } + + /** + * Determine status of user + */ + public function determinStatusOfUser($a_user_id = 0) + { + $ilUser = $this->user; + + if ($a_user_id == 0) { + $a_user_id = $ilUser->getId(); + } + + include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); + $ass = ilExAssignment::getInstancesByExercise($this->getId()); + + $passed_all_mandatory = true; + $failed_a_mandatory = false; + $cnt_passed = 0; + $cnt_notgraded = 0; + $passed_at_least_one = false; + + foreach ($ass as $a) { + $stat = $a->getMemberStatus($a_user_id)->getStatus(); + if ($a->getMandatory() && ($stat == "failed" || $stat == "notgraded")) { + $passed_all_mandatory = false; + } + if ($a->getMandatory() && ($stat == "failed")) { + $failed_a_mandatory = true; + } + if ($stat == "passed") { + $cnt_passed++; + } + if ($stat == "notgraded") { + $cnt_notgraded++; + } + } + + if (count($ass) == 0) { + $passed_all_mandatory = false; + } + + if ($this->getPassMode() != "nr") { + //echo "5"; + $overall_stat = "notgraded"; + if ($failed_a_mandatory) { + //echo "6"; + $overall_stat = "failed"; + } elseif ($passed_all_mandatory && $cnt_passed > 0) { + //echo "7"; + $overall_stat = "passed"; + } + } else { + //echo "8"; + $min_nr = $this->getPassNr(); + $overall_stat = "notgraded"; + //echo "*".$cnt_passed."*".$cnt_notgraded."*".$min_nr."*"; + if ($failed_a_mandatory || ($cnt_passed + $cnt_notgraded < $min_nr)) { + //echo "9"; + $overall_stat = "failed"; + } elseif ($passed_all_mandatory && $cnt_passed >= $min_nr) { + //echo "A"; + $overall_stat = "passed"; + } + } + + $ret = array( + "overall_status" => $overall_stat, + "failed_a_mandatory" => $failed_a_mandatory); + //echo "
p:".$cnt_passed.":ng:".$cnt_notgraded; + //var_dump($ret); + return $ret; + } + + /** + * Update exercise status of user + */ + public function updateUserStatus($a_user_id = 0) + { + $ilUser = $this->user; + + if ($a_user_id == 0) { + $a_user_id = $ilUser->getId(); + } + + $st = $this->determinStatusOfUser($a_user_id); + + include_once("./Modules/Exercise/classes/class.ilExerciseMembers.php"); + ilExerciseMembers::_writeStatus( + $this->getId(), + $a_user_id, + $st["overall_status"] + ); + } + + /** + * Update status of all users + */ + public function updateAllUsersStatus() + { + if (!is_object($this->members_obj)) { + $this->members_obj = new ilExerciseMembers($this); + } + + $mems = $this->members_obj->getMembers(); + foreach ($mems as $mem) { + $this->updateUserStatus($mem); + } + } + + /** + * Exports grades as excel + */ + public function exportGradesExcel() + { + include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); + $ass_data = ilExAssignment::getInstancesByExercise($this->getId()); + + include_once "./Services/Excel/classes/class.ilExcel.php"; + $excel = new ilExcel(); + $excel->addSheet($this->lng->txt("exc_status")); + + + // + // status + // + + // header row + $row = $cnt = 1; + $excel->setCell($row, 0, $this->lng->txt("name")); + foreach ($ass_data as $ass) { + $excel->setCell($row, $cnt++, $cnt-1); + } + $excel->setCell($row, $cnt++, $this->lng->txt("exc_total_exc")); + $excel->setCell($row, $cnt++, $this->lng->txt("exc_mark")); + $excel->setCell($row++, $cnt, $this->lng->txt("exc_comment_for_learner")); + $excel->setBold("A1:" . $excel->getColumnCoord($cnt) . "1"); + + // data rows + $mem_obj = new ilExerciseMembers($this); + + $filtered_members = $GLOBALS['DIC']->access()->filterUserIdsByRbacOrPositionOfCurrentUser( + 'etit_submissions_grades', + 'edit_submissions_grades', + $this->getRefId(), + (array) $mem_obj->getMembers() + ); + + foreach ((array) $filtered_members as $user_id) { + $mems[$user_id] = ilObjUser::_lookupName($user_id); + } + $mems = ilUtil::sortArray($mems, "lastname", "asc", false, true); + + include_once 'Services/Tracking/classes/class.ilLPMarks.php'; + foreach ($mems as $user_id => $d) { + $col = 0; + + // name + $excel->setCell($row, $col++, $d["lastname"] . ", " . $d["firstname"] . " [" . $d["login"] . "]"); + + reset($ass_data); + foreach ($ass_data as $ass) { + $status = $ass->getMemberStatus($user_id)->getStatus(); + $excel->setCell($row, $col++, $this->lng->txt("exc_" . $status)); + } + + // total status + $status = ilExerciseMembers::_lookupStatus($this->getId(), $user_id); + $excel->setCell($row, $col++, $this->lng->txt("exc_" . $status)); + + // #18096 + $marks_obj = new ilLPMarks($this->getId(), $user_id); + $excel->setCell($row, $col++, $marks_obj->getMark()); + $excel->setCell($row++, $col, $marks_obj->getComment()); + } + + + // + // mark + // + + $excel->addSheet($this->lng->txt("exc_mark")); + + // header row + $row = $cnt = 1; + $excel->setCell($row, 0, $this->lng->txt("name")); + foreach ($ass_data as $ass) { + $excel->setCell($row, $cnt++, $cnt-1); + } + $excel->setCell($row++, $cnt++, $this->lng->txt("exc_total_exc")); + $excel->setBold("A1:" . $excel->getColumnCoord($cnt) . "1"); + + // data rows + reset($mems); + foreach ($mems as $user_id => $d) { + $col = 0; + + // name + $d = ilObjUser::_lookupName($user_id); + $excel->setCell($row, $col++, $d["lastname"] . ", " . $d["firstname"] . " [" . $d["login"] . "]"); + + reset($ass_data); + foreach ($ass_data as $ass) { + $excel->setCell($row, $col++, $ass->getMemberStatus($user_id)->getMark()); + } + + // total mark + $excel->setCell($row++, $col, ilLPMarks::_lookupMark($user_id, $this->getId())); + } + + $exc_name = ilUtil::getASCIIFilename(preg_replace("/\s/", "_", $this->getTitle())); + $excel->sendToClient($exc_name); + } + + /** + * Send feedback file notification to user + */ + public function sendFeedbackFileNotification($a_feedback_file, $a_user_id, $a_ass_id, $a_is_text_feedback = false) + { + $user_ids = $a_user_id; + if (!is_array($user_ids)) { + $user_ids = array($user_ids); + } + + include_once("./Modules/Exercise/classes/class.ilExerciseMailNotification.php"); + + $type = (bool) $a_is_text_feedback + ? ilExerciseMailNotification::TYPE_FEEDBACK_TEXT_ADDED + : ilExerciseMailNotification::TYPE_FEEDBACK_FILE_ADDED; + + $not = new ilExerciseMailNotification(); + $not->setType($type); + $not->setAssignmentId($a_ass_id); + $not->setObjId($this->getId()); + if ($this->getRefId() > 0) { + $not->setRefId($this->getRefId()); + } + $not->setRecipients($user_ids); + $not->send(); + } + + /** + * + * Checks whether completion by submission is enabled or not + * + * @return boolean + * @access public + * + */ + public function isCompletionBySubmissionEnabled() + { + return $this->completion_by_submission; + } + + /** + * + * Enabled/Disable completion by submission + * + * @param boolean + * @return ilObjExercise + * @access public + * + */ + public function setCompletionBySubmission($bool) + { + $this->completion_by_submission = (bool) $bool; + + return $this; + } + + public function processExerciseStatus(ilExAssignment $a_ass, array $a_user_ids, $a_has_submitted, array $a_valid_submissions = null) + { + $a_has_submitted = (bool) $a_has_submitted; + + include_once("./Modules/Exercise/classes/class.ilExerciseMembers.php"); + foreach ($a_user_ids as $user_id) { + $member_status = $a_ass->getMemberStatus($user_id); + $member_status->setReturned($a_has_submitted); + $member_status->update(); + + ilExerciseMembers::_writeReturned($this->getId(), $user_id, $a_has_submitted); + } + + // re-evaluate exercise status + if ($this->isCompletionBySubmissionEnabled()) { + foreach ($a_user_ids as $user_id) { + $status = 'notgraded'; + if ($a_has_submitted) { + if (!is_array($a_valid_submissions) || + $a_valid_submissions[$user_id]) { + $status = 'passed'; + } + } + + $member_status = $a_ass->getMemberStatus($user_id); + $member_status->setStatus($status); + $member_status->update(); + } + } + } + + /** + * Get all exercises for user + * + * @param $a_user_id + * @return array (exercise id => passed) + */ + public static function _lookupFinishedUserExercises($a_user_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query("SELECT obj_id, status FROM exc_members" . + " WHERE usr_id = " . $ilDB->quote($a_user_id, "integer") . + " AND (status = " . $ilDB->quote("passed", "text") . + " OR status = " . $ilDB->quote("failed", "text") . ")"); + + $all = array(); + while ($row = $ilDB->fetchAssoc($set)) { + $all[$row["obj_id"]] = ($row["status"] == "passed"); + } + return $all; + } + + + /** + * Returns the visibility settings of the certificate + * + * @return integer The value for the visibility settings (0 = always, 1 = only passed, 2 = never) + * @access public + */ + public function getCertificateVisibility() + { + return (strlen($this->certificate_visibility)) ? $this->certificate_visibility : 0; + } + + /** + * Sets the visibility settings of the certificate + * + * @param integer $a_value The value for the visibility settings (0 = always, 1 = only passed, 2 = never) + * @access public + */ + public function setCertificateVisibility($a_value) + { + $this->certificate_visibility = $a_value; + } + + /** + * Saves the visibility settings of the certificate + * + * @param integer $a_value The value for the visibility settings (0 = always, 1 = only passed, 2 = never) + * @access private + */ + public function saveCertificateVisibility($a_value) + { + $ilDB = $this->db; + + $affectedRows = $ilDB->manipulateF( + "UPDATE exc_data SET certificate_visibility = %s WHERE obj_id = %s", + array('integer', 'integer'), + array($a_value, $this->getId()) + ); + } + + /** + * Add to desktop after hand-in + * + * @return bool + */ + public function hasAddToDesktop() + { + $exc_set = new ilSetting("excs"); + return (bool) $exc_set->get("add_to_pd", true); + } } - -?> diff --git a/Modules/Exercise/classes/class.ilObjExerciseAccess.php b/Modules/Exercise/classes/class.ilObjExerciseAccess.php index 261733293e7e60fe7bc843180e9d9b03a1bca1d4..b70559296c00a664a35bc4f9195bd756640a89e3 100644 --- a/Modules/Exercise/classes/class.ilObjExerciseAccess.php +++ b/Modules/Exercise/classes/class.ilObjExerciseAccess.php @@ -15,181 +15,169 @@ include_once './Services/Conditions/interfaces/interface.ilConditionHandling.php */ class ilObjExerciseAccess extends ilObjectAccess implements ilConditionHandling { - - /** - * Get possible conditions operators - */ - public static function getConditionOperators() - { - include_once './Services/Conditions/classes/class.ilConditionHandler.php'; - return array( - ilConditionHandler::OPERATOR_PASSED, - ilConditionHandler::OPERATOR_FAILED - ); - } - - - /** - * check condition - * @param type $a_exc_id - * @param type $a_operator - * @param type $a_value - * @param type $a_usr_id - * @return boolean - */ - public static function checkCondition($a_exc_id,$a_operator,$a_value,$a_usr_id) - { - include_once './Services/Conditions/classes/class.ilConditionHandler.php'; - include_once './Modules/Exercise/classes/class.ilExerciseMembers.php'; - - switch($a_operator) - { - case ilConditionHandler::OPERATOR_PASSED: - if (ilExerciseMembers::_lookupStatus($a_exc_id, $a_usr_id) == "passed") - { - return true; - } - else - { - return false; - } - break; - - case ilConditionHandler::OPERATOR_FAILED: - return ilExerciseMembers::_lookupStatus($a_exc_id,$a_usr_id) == 'failed'; + + /** + * Get possible conditions operators + */ + public static function getConditionOperators() + { + include_once './Services/Conditions/classes/class.ilConditionHandler.php'; + return array( + ilConditionHandler::OPERATOR_PASSED, + ilConditionHandler::OPERATOR_FAILED + ); + } + + + /** + * check condition + * @param type $a_exc_id + * @param type $a_operator + * @param type $a_value + * @param type $a_usr_id + * @return boolean + */ + public static function checkCondition($a_exc_id, $a_operator, $a_value, $a_usr_id) + { + include_once './Services/Conditions/classes/class.ilConditionHandler.php'; + include_once './Modules/Exercise/classes/class.ilExerciseMembers.php'; + + switch ($a_operator) { + case ilConditionHandler::OPERATOR_PASSED: + if (ilExerciseMembers::_lookupStatus($a_exc_id, $a_usr_id) == "passed") { + return true; + } else { + return false; + } + break; + + case ilConditionHandler::OPERATOR_FAILED: + return ilExerciseMembers::_lookupStatus($a_exc_id, $a_usr_id) == 'failed'; - default: - return true; - } - return true; - } - + default: + return true; + } + return true; + } + - /** - * 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" => "showOverview", "lang_var" => "show", - "default" => true), - array("permission" => "write", "cmd" => "listAssignments", "lang_var" => "edit_assignments"), - array("permission" => "write", "cmd" => "edit", "lang_var" => "settings") - ); - - return $commands; - } - - static function _lookupRemainingWorkingTimeString($a_obj_id) - { - 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" => "showOverview", "lang_var" => "show", + "default" => true), + array("permission" => "write", "cmd" => "listAssignments", "lang_var" => "edit_assignments"), + array("permission" => "write", "cmd" => "edit", "lang_var" => "settings") + ); + + return $commands; + } + + public static function _lookupRemainingWorkingTimeString($a_obj_id) + { + global $DIC; - $ilDB = $DIC->database(); - - // #14077 - mind peer deadline, too - - $dl = null; - $cnt = array(); - - $q = "SELECT id, time_stamp, deadline2, peer_dl". - " FROM exc_assignment WHERE exc_id = ".$ilDB->quote($a_obj_id, "integer"). - " AND (time_stamp > ".$ilDB->quote(time(), "integer"). - " OR (peer_dl > ".$ilDB->quote(time(), "integer"). - " AND peer > ".$ilDB->quote(0, "integer")."))"; - $set = $ilDB->query($q); - while($row = $ilDB->fetchAssoc($set)) - { - if($row["time_stamp"] > time() && - ($row["time_stamp"] < $dl || !$dl)) - { - $dl = $row["time_stamp"]; - } - /* extended deadline should not be presented anywhere - if($row["deadline2"] > time() && - ($row["deadline2"] < $dl || !$dl)) - { - $dl = $row["deadline2"]; - } - */ - if($row["peer_dl"] > time() && - ($row["peer_dl"] < $dl || !$dl)) - { - $dl = $row["peer_dl"]; - } - $cnt[$row["id"]] = true; - } - - // :TODO: mind personal deadline? - - if($dl) - { - $dl = ilUtil::period2String(new ilDateTime($dl, IL_CAL_UNIX)); - } - - return array( - "mtime" => $dl, - "cnt" => sizeof($cnt) - ); - } - - /** - * check whether goto script will succeed - */ - static function _checkGoto($a_target) - { - global $DIC; + $ilDB = $DIC->database(); + + // #14077 - mind peer deadline, too + + $dl = null; + $cnt = array(); + + $q = "SELECT id, time_stamp, deadline2, peer_dl" . + " FROM exc_assignment WHERE exc_id = " . $ilDB->quote($a_obj_id, "integer") . + " AND (time_stamp > " . $ilDB->quote(time(), "integer") . + " OR (peer_dl > " . $ilDB->quote(time(), "integer") . + " AND peer > " . $ilDB->quote(0, "integer") . "))"; + $set = $ilDB->query($q); + while ($row = $ilDB->fetchAssoc($set)) { + if ($row["time_stamp"] > time() && + ($row["time_stamp"] < $dl || !$dl)) { + $dl = $row["time_stamp"]; + } + /* extended deadline should not be presented anywhere + if($row["deadline2"] > time() && + ($row["deadline2"] < $dl || !$dl)) + { + $dl = $row["deadline2"]; + } + */ + if ($row["peer_dl"] > time() && + ($row["peer_dl"] < $dl || !$dl)) { + $dl = $row["peer_dl"]; + } + $cnt[$row["id"]] = true; + } + + // :TODO: mind personal deadline? + + if ($dl) { + $dl = ilUtil::period2String(new ilDateTime($dl, IL_CAL_UNIX)); + } + + return array( + "mtime" => $dl, + "cnt" => sizeof($cnt) + ); + } + + /** + * check whether goto script will succeed + */ + public static function _checkGoto($a_target) + { + global $DIC; - $ilAccess = $DIC->access(); - - $t_arr = explode("_", $a_target); + $ilAccess = $DIC->access(); + + $t_arr = explode("_", $a_target); - if ($t_arr[0] != "exc" || ((int) $t_arr[1]) <= 0) - { - return false; - } + if ($t_arr[0] != "exc" || ((int) $t_arr[1]) <= 0) { + return false; + } - if ($ilAccess->checkAccess("read", "", $t_arr[1])) - { - return true; - } - return false; - } + if ($ilAccess->checkAccess("read", "", $t_arr[1])) { + return true; + } + return false; + } - /** - * @param ilWACPath $ilWACPath - * - * @return bool - */ - public function canBeDelivered(ilWACPath $ilWACPath) { - global $ilAccess; + /** + * @param ilWACPath $ilWACPath + * + * @return bool + */ + public function canBeDelivered(ilWACPath $ilWACPath) + { + global $ilAccess; - return true; + return true; - // to do: check the path, extract the IDs from the path - // determine the object ID of the corresponding exercise - // get all ref IDs of the exercise from the object id and check if use - // has read access to any of these ref ids (if yes, return true) + // to do: check the path, extract the IDs from the path + // determine the object ID of the corresponding exercise + // get all ref IDs of the exercise from the object id and check if use + // has read access to any of these ref ids (if yes, return true) - preg_match("/\\/poll_([\\d]*)\\//uism", $ilWACPath->getPath(), $results); + preg_match("/\\/poll_([\\d]*)\\//uism", $ilWACPath->getPath(), $results); - foreach (ilObject2::_getAllReferences($results[1]) as $ref_id) { - if ($ilAccess->checkAccess('read', '', $ref_id)) { - return true; - } - } + foreach (ilObject2::_getAllReferences($results[1]) as $ref_id) { + if ($ilAccess->checkAccess('read', '', $ref_id)) { + return true; + } + } - return false; - } + return false; + } } - -?> diff --git a/Modules/Exercise/classes/class.ilObjExerciseAdministration.php b/Modules/Exercise/classes/class.ilObjExerciseAdministration.php index 2981397fe8d07a25f40bd09bc2374ee7da7519ea..ee40ebde66a56f84aa56b3b6900409aa468cec47 100644 --- a/Modules/Exercise/classes/class.ilObjExerciseAdministration.php +++ b/Modules/Exercise/classes/class.ilObjExerciseAdministration.php @@ -1,29 +1,27 @@ - - * @version $Id:$ - * - * @package ModulesExercise - */ -class ilObjExerciseAdministration extends ilObject -{ - public function __construct($a_id = 0, $a_call_by_reference = true) - { - $this->type = "excs"; - parent::__construct($a_id,$a_call_by_reference); - } - - public function delete() - { - // DISABLED - return false; - } -} - -?> \ No newline at end of file + + * @version $Id:$ + * + * @package ModulesExercise + */ +class ilObjExerciseAdministration extends ilObject +{ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + $this->type = "excs"; + parent::__construct($a_id, $a_call_by_reference); + } + + public function delete() + { + // DISABLED + return false; + } +} diff --git a/Modules/Exercise/classes/class.ilObjExerciseAdministrationAccess.php b/Modules/Exercise/classes/class.ilObjExerciseAdministrationAccess.php index a3959a38dc523b97a6bdfa3ef9cc72345f40d931..c885892b1eedd091d556c3586f7569e9adf82d22 100644 --- a/Modules/Exercise/classes/class.ilObjExerciseAdministrationAccess.php +++ b/Modules/Exercise/classes/class.ilObjExerciseAdministrationAccess.php @@ -1,19 +1,16 @@ - - * @version $Id$ - * - * @ingroup ModulesExercise - */ -class ilObjExerciseAdministrationAccess extends ilObjectAccess -{ - -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @ingroup ModulesExercise + */ +class ilObjExerciseAdministrationAccess extends ilObjectAccess +{ +} diff --git a/Modules/Exercise/classes/class.ilObjExerciseAdministrationGUI.php b/Modules/Exercise/classes/class.ilObjExerciseAdministrationGUI.php index 75735f321255fdca695ee90e68d52c130370688b..951268eea0d33b837c9b098a391168d54da4b4ef 100644 --- a/Modules/Exercise/classes/class.ilObjExerciseAdministrationGUI.php +++ b/Modules/Exercise/classes/class.ilObjExerciseAdministrationGUI.php @@ -1,178 +1,174 @@ - - * @version $Id:$ - * - * @ilCtrl_Calls ilObjExerciseAdministrationGUI: ilPermissionGUI - * - * @ingroup ModulesExercise - */ -class ilObjExerciseAdministrationGUI extends ilObjectGUI -{ - /** - * Contructor - * - * @access public - */ - public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) - { - global $DIC; - - $this->lng = $DIC->language(); - $this->settings = $DIC->settings(); - $this->ctrl = $DIC->ctrl(); - $this->access = $DIC->access(); - $this->type = "excs"; - parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); - - $this->lng->loadLanguageModule("exercise"); - } - - /** - * Execute command - * - * @access public - * - */ - public function executeCommand() - { - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - $this->prepareOutput(); - - switch($next_class) - { - case 'ilpermissiongui': - $this->tabs_gui->setTabActive('perm_settings'); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $this->ctrl->forwardCommand($perm_gui); - break; - - default: - if(!$cmd || $cmd == 'view') - { - $cmd = "editSettings"; - } - - $this->$cmd(); - break; - } - return true; - } - - /** - * Get tabs - * - * @access public - * - */ - public function getAdminTabs() - { - if ($this->checkPermissionBool("visible,read")) - { - $this->tabs_gui->addTarget("settings", - $this->ctrl->getLinkTarget($this, "editSettings"), - array("editSettings", "view")); - } - - if ($this->checkPermissionBool('edit_permission')) - { - $this->tabs_gui->addTarget("perm_settings", - $this->ctrl->getLinkTargetByClass('ilpermissiongui',"perm"), - array(),'ilpermissiongui'); - } - } - - - /** - * Edit settings. - */ - public function editSettings($a_form = null) - { - $lng = $this->lng; - $ilSetting = $this->settings; - - $this->tabs_gui->setTabActive('settings'); - - if(!$a_form) - { - $a_form = $this->initFormSettings(); - } - $this->tpl->setContent($a_form->getHTML()); - return true; - } - - /** - * Save settings - */ - public function saveSettings() - { - $ilCtrl = $this->ctrl; - - $this->checkPermission("write"); - - $form = $this->initFormSettings(); - if($form->checkInput()) - { - $exc_set = new ilSetting("excs"); - $exc_set->set("add_to_pd", (bool)$form->getInput("pd")); - - ilUtil::sendSuccess($this->lng->txt("settings_saved"),true); - $ilCtrl->redirect($this, "editSettings"); - } - - $form->setValuesByPost(); - $this->editSettings($form); - } - - /** - * Save settings - */ - public function cancel() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirect($this, "view"); - } - - /** - * Init settings property form - * - * @access protected - */ - protected function initFormSettings() - { - $lng = $this->lng; - $ilAccess = $this->access; - - include_once('Services/Form/classes/class.ilPropertyFormGUI.php'); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - $form->setTitle($this->lng->txt('exc_admin_settings')); - - if ($this->checkPermissionBool("write")) - { - $form->addCommandButton('saveSettings',$this->lng->txt('save')); - $form->addCommandButton('cancel',$this->lng->txt('cancel')); - } - - $exc_set = new ilSetting("excs"); - - $pd = new ilCheckboxInputGUI($lng->txt("to_desktop"), "pd"); - $pd->setInfo($lng->txt("exc_to_desktop_info")); - $pd->setChecked($exc_set->get("add_to_pd", true)); - $form->addItem($pd); - - return $form; - } -} - -?> \ No newline at end of file + + * @version $Id:$ + * + * @ilCtrl_Calls ilObjExerciseAdministrationGUI: ilPermissionGUI + * + * @ingroup ModulesExercise + */ +class ilObjExerciseAdministrationGUI extends ilObjectGUI +{ + /** + * Contructor + * + * @access public + */ + public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) + { + global $DIC; + + $this->lng = $DIC->language(); + $this->settings = $DIC->settings(); + $this->ctrl = $DIC->ctrl(); + $this->access = $DIC->access(); + $this->type = "excs"; + parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); + + $this->lng->loadLanguageModule("exercise"); + } + + /** + * Execute command + * + * @access public + * + */ + public function executeCommand() + { + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + $this->prepareOutput(); + + switch ($next_class) { + case 'ilpermissiongui': + $this->tabs_gui->setTabActive('perm_settings'); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $this->ctrl->forwardCommand($perm_gui); + break; + + default: + if (!$cmd || $cmd == 'view') { + $cmd = "editSettings"; + } + + $this->$cmd(); + break; + } + return true; + } + + /** + * Get tabs + * + * @access public + * + */ + public function getAdminTabs() + { + if ($this->checkPermissionBool("visible,read")) { + $this->tabs_gui->addTarget( + "settings", + $this->ctrl->getLinkTarget($this, "editSettings"), + array("editSettings", "view") + ); + } + + if ($this->checkPermissionBool('edit_permission')) { + $this->tabs_gui->addTarget( + "perm_settings", + $this->ctrl->getLinkTargetByClass('ilpermissiongui', "perm"), + array(), + 'ilpermissiongui' + ); + } + } + + + /** + * Edit settings. + */ + public function editSettings($a_form = null) + { + $lng = $this->lng; + $ilSetting = $this->settings; + + $this->tabs_gui->setTabActive('settings'); + + if (!$a_form) { + $a_form = $this->initFormSettings(); + } + $this->tpl->setContent($a_form->getHTML()); + return true; + } + + /** + * Save settings + */ + public function saveSettings() + { + $ilCtrl = $this->ctrl; + + $this->checkPermission("write"); + + $form = $this->initFormSettings(); + if ($form->checkInput()) { + $exc_set = new ilSetting("excs"); + $exc_set->set("add_to_pd", (bool) $form->getInput("pd")); + + ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "editSettings"); + } + + $form->setValuesByPost(); + $this->editSettings($form); + } + + /** + * Save settings + */ + public function cancel() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirect($this, "view"); + } + + /** + * Init settings property form + * + * @access protected + */ + protected function initFormSettings() + { + $lng = $this->lng; + $ilAccess = $this->access; + + include_once('Services/Form/classes/class.ilPropertyFormGUI.php'); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this)); + $form->setTitle($this->lng->txt('exc_admin_settings')); + + if ($this->checkPermissionBool("write")) { + $form->addCommandButton('saveSettings', $this->lng->txt('save')); + $form->addCommandButton('cancel', $this->lng->txt('cancel')); + } + + $exc_set = new ilSetting("excs"); + + $pd = new ilCheckboxInputGUI($lng->txt("to_desktop"), "pd"); + $pd->setInfo($lng->txt("exc_to_desktop_info")); + $pd->setChecked($exc_set->get("add_to_pd", true)); + $form->addItem($pd); + + return $form; + } +} diff --git a/Modules/Exercise/classes/class.ilObjExerciseGUI.php b/Modules/Exercise/classes/class.ilObjExerciseGUI.php index a073c6a32a5e431e6ff5bc0a435d3ff8d41b42ed..c815f1fa10367eed6614f277b2a4850f056c3590 100755 --- a/Modules/Exercise/classes/class.ilObjExerciseGUI.php +++ b/Modules/Exercise/classes/class.ilObjExerciseGUI.php @@ -11,944 +11,942 @@ require_once "./Services/Object/classes/class.ilObjectGUI.php"; * @author Alex Killing * @author Michael Jansen * $Id$ -* +* * @ilCtrl_Calls ilObjExerciseGUI: ilPermissionGUI, ilLearningProgressGUI, ilInfoScreenGUI * @ilCtrl_Calls ilObjExerciseGUI: ilObjectCopyGUI, ilExportGUI -* @ilCtrl_Calls ilObjExerciseGUI: ilCommonActionDispatcherGUI, ilCertificateGUI +* @ilCtrl_Calls ilObjExerciseGUI: ilCommonActionDispatcherGUI, ilCertificateGUI * @ilCtrl_Calls ilObjExerciseGUI: ilExAssignmentEditorGUI, ilExSubmissionGUI * @ilCtrl_Calls ilObjExerciseGUI: ilExerciseManagementGUI, ilExcCriteriaCatalogueGUI -* +* * @ingroup ModulesExercise */ class ilObjExerciseGUI extends ilObjectGUI { - /** - * @var - */ - private $certificateDownloadValidator; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilHelpGUI - */ - protected $help; - - /** - * @var ilExAssignment - */ - protected $ass = null; - - /** - * Constructor - * @access public - */ - function __construct($a_data,$a_id,$a_call_by_reference,$a_prepare_output = true) - { - global $DIC; - - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - $this->ctrl = $DIC->ctrl(); - $this->tabs = $DIC->tabs(); - $this->help = $DIC["ilHelp"]; - $this->locator = $DIC["ilLocator"]; - $this->tpl = $DIC["tpl"]; - $this->toolbar = $DIC->toolbar(); - $lng = $DIC->language(); - - $this->lng->loadLanguageModule('cert'); - - $this->type = "exc"; - parent::__construct($a_data,$a_id,$a_call_by_reference,false); - - $lng->loadLanguageModule("exercise"); - $lng->loadLanguageModule("exc"); - $this->ctrl->saveParameter($this, "ass_id"); - - include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); - if ($_REQUEST["ass_id"] > 0 && is_object($this->object) && ilExAssignment::lookupExerciseId($_REQUEST["ass_id"]) == $this->object->getId()) - { - $this->ass = new ilExAssignment((int) $_REQUEST["ass_id"]); - } - else if ($_REQUEST["ass_id"] > 0) - { - throw new ilExerciseException("Assignment ID does not match Exercise."); - } - - - $this->certificateDownloadValidator = new ilCertificateDownloadValidator(); - } - - function executeCommand() - { - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - $lng = $this->lng; + /** + * @var + */ + private $certificateDownloadValidator; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var ilExAssignment + */ + protected $ass = null; + + /** + * Constructor + * @access public + */ + public function __construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output = true) + { + global $DIC; + + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + $this->ctrl = $DIC->ctrl(); + $this->tabs = $DIC->tabs(); + $this->help = $DIC["ilHelp"]; + $this->locator = $DIC["ilLocator"]; + $this->tpl = $DIC["tpl"]; + $this->toolbar = $DIC->toolbar(); + $lng = $DIC->language(); + + $this->lng->loadLanguageModule('cert'); + + $this->type = "exc"; + parent::__construct($a_data, $a_id, $a_call_by_reference, false); + + $lng->loadLanguageModule("exercise"); + $lng->loadLanguageModule("exc"); + $this->ctrl->saveParameter($this, "ass_id"); + + include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); + if ($_REQUEST["ass_id"] > 0 && is_object($this->object) && ilExAssignment::lookupExerciseId($_REQUEST["ass_id"]) == $this->object->getId()) { + $this->ass = new ilExAssignment((int) $_REQUEST["ass_id"]); + } elseif ($_REQUEST["ass_id"] > 0) { + throw new ilExerciseException("Assignment ID does not match Exercise."); + } + + + $this->certificateDownloadValidator = new ilCertificateDownloadValidator(); + } + + public function executeCommand() + { + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + $lng = $this->lng; - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - $this->prepareOutput(); + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + $this->prepareOutput(); -//echo "-".$next_class."-".$cmd."-"; exit; - switch($next_class) - { - case "ilinfoscreengui": - $ilTabs->activateTab("info"); - $this->infoScreen(); // forwards command - break; - - case 'ilpermissiongui': - $ilTabs->activateTab("permissions"); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $ret =& $this->ctrl->forwardCommand($perm_gui); - break; - - case "illearningprogressgui": - $ilTabs->activateTab("learning_progress"); - include_once './Services/Tracking/classes/class.ilLearningProgressGUI.php'; - - $new_gui = new ilLearningProgressGUI(ilLearningProgressGUI::LP_CONTEXT_REPOSITORY, - $this->object->getRefId(), - $_GET['user_id'] ? $_GET['user_id'] : $ilUser->getId()); - $this->ctrl->forwardCommand($new_gui); - $this->tabs_gui->setTabActive('learning_progress'); - break; - - case 'ilobjectcopygui': - $ilCtrl->saveParameter($this, 'new_type'); - $ilCtrl->setReturnByClass(get_class($this),'create'); - - include_once './Services/Object/classes/class.ilObjectCopyGUI.php'; - $cp = new ilObjectCopyGUI($this); - $cp->setType('exc'); - $this->ctrl->forwardCommand($cp); - break; - - case "ilexportgui": - $ilTabs->activateTab("export"); - include_once("./Services/Export/classes/class.ilExportGUI.php"); - $exp_gui = new ilExportGUI($this); - $exp_gui->addFormat("xml"); - $ret = $this->ctrl->forwardCommand($exp_gui); + //echo "-".$next_class."-".$cmd."-"; exit; + switch ($next_class) { + case "ilinfoscreengui": + $ilTabs->activateTab("info"); + $this->infoScreen(); // forwards command + break; + + case 'ilpermissiongui': + $ilTabs->activateTab("permissions"); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $ret =&$this->ctrl->forwardCommand($perm_gui); + break; + + case "illearningprogressgui": + $ilTabs->activateTab("learning_progress"); + include_once './Services/Tracking/classes/class.ilLearningProgressGUI.php'; + + $new_gui = new ilLearningProgressGUI( + ilLearningProgressGUI::LP_CONTEXT_REPOSITORY, + $this->object->getRefId(), + $_GET['user_id'] ? $_GET['user_id'] : $ilUser->getId() + ); + $this->ctrl->forwardCommand($new_gui); + $this->tabs_gui->setTabActive('learning_progress'); + break; + + case 'ilobjectcopygui': + $ilCtrl->saveParameter($this, 'new_type'); + $ilCtrl->setReturnByClass(get_class($this), 'create'); + + include_once './Services/Object/classes/class.ilObjectCopyGUI.php'; + $cp = new ilObjectCopyGUI($this); + $cp->setType('exc'); + $this->ctrl->forwardCommand($cp); + break; + + case "ilexportgui": + $ilTabs->activateTab("export"); + include_once("./Services/Export/classes/class.ilExportGUI.php"); + $exp_gui = new ilExportGUI($this); + $exp_gui->addFormat("xml"); + $ret = $this->ctrl->forwardCommand($exp_gui); // $this->tpl->show(); - break; - - case "ilcommonactiondispatchergui": - include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); - $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); - $this->ctrl->forwardCommand($gui); - break; - - case "ilcertificategui": - $this->setSettingsSubTabs(); - $this->tabs_gui->activateTab("settings"); - $this->tabs_gui->activateSubTab("certificate"); - - $guiFactory = new ilCertificateGUIFactory(); - $output_gui = $guiFactory->create($this->object); - - $this->ctrl->forwardCommand($output_gui); - break; - - case "ilexassignmenteditorgui": - $this->checkPermission("write"); - $ilTabs->activateTab("content"); - $this->addContentSubTabs("list_assignments"); - include_once("./Modules/Exercise/classes/class.ilExAssignmentEditorGUI.php"); - $ass_gui = new ilExAssignmentEditorGUI($this->object->getId(), $this->object->isCompletionBySubmissionEnabled(), $this->ass); - $this->ctrl->forwardCommand($ass_gui); - break; - - case "ilexsubmissiongui": - $this->checkPermission("read"); - $ilTabs->activateTab("content"); - $this->addContentSubTabs("content"); - $this->ctrl->setReturn($this, "showOverview"); - include_once("./Modules/Exercise/classes/class.ilExSubmissionGUI.php"); - $sub_gui = new ilExSubmissionGUI($this->object, $this->ass, (int)$_REQUEST["member_id"]); - $this->ctrl->forwardCommand($sub_gui); - break; - - case "ilexercisemanagementgui": - // rbac or position access - if ($GLOBALS['DIC']->access()->checkRbacOrPositionPermissionAccess( - 'edit_submissions_grades', - 'edit_submissions_grades', - $this->object->getRefId() - )) - { - $ilTabs->activateTab("grades"); - include_once("./Modules/Exercise/classes/class.ilExerciseManagementGUI.php"); - $mgmt_gui = new ilExerciseManagementGUI($this->object, $this->ass); - $this->ctrl->forwardCommand($mgmt_gui); - } - else - { - $this->checkPermission("edit_submissions_grades"); // throw error by standard procedure - } - break; - - case "ilexccriteriacataloguegui": - $this->checkPermission("write"); - $ilTabs->activateTab("settings"); - $this->setSettingsSubTabs(); - $ilTabs->activateSubTab("crit"); - include_once("./Modules/Exercise/classes/class.ilExcCriteriaCatalogueGUI.php"); - $crit_gui = new ilExcCriteriaCatalogueGUI($this->object); - $this->ctrl->forwardCommand($crit_gui); - break; - - default: - if(!$cmd) - { - $cmd = "infoScreen"; - } - - $cmd .= "Object"; - - $this->$cmd(); - - break; - } - - $this->addHeaderAction(); + break; + + case "ilcommonactiondispatchergui": + include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); + $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); + $this->ctrl->forwardCommand($gui); + break; + + case "ilcertificategui": + $this->setSettingsSubTabs(); + $this->tabs_gui->activateTab("settings"); + $this->tabs_gui->activateSubTab("certificate"); + + $guiFactory = new ilCertificateGUIFactory(); + $output_gui = $guiFactory->create($this->object); + + $this->ctrl->forwardCommand($output_gui); + break; + + case "ilexassignmenteditorgui": + $this->checkPermission("write"); + $ilTabs->activateTab("content"); + $this->addContentSubTabs("list_assignments"); + include_once("./Modules/Exercise/classes/class.ilExAssignmentEditorGUI.php"); + $ass_gui = new ilExAssignmentEditorGUI($this->object->getId(), $this->object->isCompletionBySubmissionEnabled(), $this->ass); + $this->ctrl->forwardCommand($ass_gui); + break; + + case "ilexsubmissiongui": + $this->checkPermission("read"); + $ilTabs->activateTab("content"); + $this->addContentSubTabs("content"); + $this->ctrl->setReturn($this, "showOverview"); + include_once("./Modules/Exercise/classes/class.ilExSubmissionGUI.php"); + $sub_gui = new ilExSubmissionGUI($this->object, $this->ass, (int) $_REQUEST["member_id"]); + $this->ctrl->forwardCommand($sub_gui); + break; + + case "ilexercisemanagementgui": + // rbac or position access + if ($GLOBALS['DIC']->access()->checkRbacOrPositionPermissionAccess( + 'edit_submissions_grades', + 'edit_submissions_grades', + $this->object->getRefId() + )) { + $ilTabs->activateTab("grades"); + include_once("./Modules/Exercise/classes/class.ilExerciseManagementGUI.php"); + $mgmt_gui = new ilExerciseManagementGUI($this->object, $this->ass); + $this->ctrl->forwardCommand($mgmt_gui); + } else { + $this->checkPermission("edit_submissions_grades"); // throw error by standard procedure + } + break; + + case "ilexccriteriacataloguegui": + $this->checkPermission("write"); + $ilTabs->activateTab("settings"); + $this->setSettingsSubTabs(); + $ilTabs->activateSubTab("crit"); + include_once("./Modules/Exercise/classes/class.ilExcCriteriaCatalogueGUI.php"); + $crit_gui = new ilExcCriteriaCatalogueGUI($this->object); + $this->ctrl->forwardCommand($crit_gui); + break; + + default: + if (!$cmd) { + $cmd = "infoScreen"; + } + + $cmd .= "Object"; + + $this->$cmd(); + + break; + } + + $this->addHeaderAction(); - return true; - } - - function viewObject() - { - $this->infoScreenObject(); - } - - protected function afterSave(ilObject $a_new_object) - { - $ilCtrl = $this->ctrl; - - $a_new_object->saveData(); - - ilUtil::sendSuccess($this->lng->txt("exc_added"), true); - - $ilCtrl->setParameterByClass("ilExAssignmentEditorGUI", "ref_id", $a_new_object->getRefId()); - $ilCtrl->redirectByClass("ilExAssignmentEditorGUI", "addAssignment"); - } - - protected function listAssignmentsObject() - { - $ilCtrl = $this->ctrl; - - $this->checkPermissionBool("write"); - - // #16587 - $ilCtrl->redirectByClass("ilExAssignmentEditorGUI", "listAssignments"); - } - - /** - * Init properties form. - */ - protected function initEditCustomForm(ilPropertyFormGUI $a_form) - { - $obj_service = $this->getObjectService(); - - $a_form->setTitle($this->lng->txt("exc_edit_exercise")); - - $pres = new ilFormSectionHeaderGUI(); - $pres->setTitle($this->lng->txt('obj_presentation')); - $a_form->addItem($pres); - - // tile image - $a_form = $obj_service->commonSettings()->legacyForm($a_form, $this->object)->addTileImage(); - - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($this->lng->txt('exc_passing_exc')); - $a_form->addItem($section); - - // pass mode - $radg = new ilRadioGroupInputGUI($this->lng->txt("exc_pass_mode"), "pass_mode"); - - $op1 = new ilRadioOption($this->lng->txt("exc_pass_all"), "all", - $this->lng->txt("exc_pass_all_info")); - $radg->addOption($op1); - $op2 = new ilRadioOption($this->lng->txt("exc_pass_minimum_nr"), "nr", - $this->lng->txt("exc_pass_minimum_nr_info")); - $radg->addOption($op2); - - // minimum number of assignments to pass - $ni = new ilNumberInputGUI($this->lng->txt("exc_min_nr"), "pass_nr"); - $ni->setSize(4); - $ni->setMaxLength(4); - $ni->setRequired(true); - include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); - $mand = ilExAssignment::countMandatory($this->object->getId()); - $min = max($mand, 1); - $ni->setMinValue($min, true); - $ni->setInfo($this->lng->txt("exc_min_nr_info")); - $op2->addSubItem($ni); - - $a_form->addItem($radg); - - // completion by submission - $subcompl = new ilRadioGroupInputGUI($this->lng->txt("exc_passed_status_determination"), "completion_by_submission"); - $op1 = new ilRadioOption($this->lng->txt("exc_completion_by_tutor"), 0, ""); - $subcompl->addOption($op1); - $op2 = new ilRadioOption($this->lng->txt("exc_completion_by_submission"), 1,$this->lng->txt("exc_completion_by_submission_info")); - $subcompl->addOption($op2); - $a_form->addItem($subcompl); - - /*$subcompl = new ilCheckboxInputGUI($this->lng->txt('exc_completion_by_submission'), 'completion_by_submission'); - $subcompl->setInfo($this->lng->txt('exc_completion_by_submission_info')); - $subcompl->setValue(1); - $a_form->addItem($subcompl);*/ - - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($this->lng->txt('exc_publishing')); - $a_form->addItem($section); - - // show submissions - $cb = new ilCheckboxInputGUI($this->lng->txt("exc_show_submissions"), "show_submissions"); - $cb->setInfo($this->lng->txt("exc_show_submissions_info")); - $a_form->addItem($cb); - - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($this->lng->txt('exc_notification')); - $a_form->addItem($section); - - // submission notifications - $cbox = new ilCheckboxInputGUI($this->lng->txt("exc_submission_notification"), "notification"); - $cbox->setInfo($this->lng->txt("exc_submission_notification_info")); - $a_form->addItem($cbox); - - - // feedback settings - - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($this->lng->txt('exc_feedback')); - $a_form->addItem($section); - - $fdb = new ilCheckboxGroupInputGUI($this->lng->txt("exc_settings_feedback"), "tfeedback"); - $a_form->addItem($fdb); - - $option = new ilCheckboxOption($this->lng->txt("exc_settings_feedback_mail"), ilObjExercise::TUTOR_FEEDBACK_MAIL); - $option->setInfo($this->lng->txt("exc_settings_feedback_mail_info")); - $fdb->addOption($option); - $option = new ilCheckboxOption($this->lng->txt("exc_settings_feedback_file"), ilObjExercise::TUTOR_FEEDBACK_FILE); - $option->setInfo($this->lng->txt("exc_settings_feedback_file_info")); - $fdb->addOption($option); - $option = new ilCheckboxOption($this->lng->txt("exc_settings_feedback_text"), ilObjExercise::TUTOR_FEEDBACK_TEXT); - $option->setInfo($this->lng->txt("exc_settings_feedback_text_info")); - $fdb->addOption($option); - - $position_settings = ilOrgUnitGlobalSettings::getInstance() - ->getObjectPositionSettingsByType($this->object->getType()); - - if($position_settings->isActive()) - { - // add additional feature section - $feat = new ilFormSectionHeaderGUI(); - $feat->setTitle($this->lng->txt('obj_features')); - $a_form->addItem($feat); - - // add orgunit settings - ilObjectServiceSettingsGUI::initServiceSettingsForm( - $this->object->getId(), - $a_form, - array( - ilObjectServiceSettingsGUI::ORGU_POSITION_ACCESS - ) - ); - - } - } - - /** - * Get values for properties form - */ - protected function getEditFormCustomValues(array &$a_values) - { - $ilUser = $this->user; - - $a_values["desc"] = $this->object->getLongDescription(); - $a_values["show_submissions"] = $this->object->getShowSubmissions(); - $a_values["pass_mode"] = $this->object->getPassMode(); - if ($a_values["pass_mode"] == "nr") - { - $a_values["pass_nr"] = $this->object->getPassNr(); - } - - include_once "./Services/Notification/classes/class.ilNotification.php"; - $a_values["notification"] = ilNotification::hasNotification( - ilNotification::TYPE_EXERCISE_SUBMISSION, $ilUser->getId(), - $this->object->getId()); - - $a_values['completion_by_submission'] = (int) $this->object->isCompletionBySubmissionEnabled(); - - $tfeedback = array(); - if($this->object->hasTutorFeedbackMail()) - { - $tfeedback[] = ilObjExercise::TUTOR_FEEDBACK_MAIL; - } - if($this->object->hasTutorFeedbackText()) - { - $tfeedback[] = ilObjExercise::TUTOR_FEEDBACK_TEXT; - } - if($this->object->hasTutorFeedbackFile()) - { - $tfeedback[] = ilObjExercise::TUTOR_FEEDBACK_FILE; - } - $a_values['tfeedback'] = $tfeedback; - - // orgunit position setting enabled - $a_values['obj_orgunit_positions'] = (bool) ilOrgUnitGlobalSettings::getInstance() - ->isPositionAccessActiveForObject($this->object->getId()); - - } - - protected function updateCustom(ilPropertyFormGUI $a_form) - { - $obj_service = $this->getObjectService(); - - $ilUser = $this->user; - $this->object->setShowSubmissions($a_form->getInput("show_submissions")); - $this->object->setPassMode($a_form->getInput("pass_mode")); - if ($this->object->getPassMode() == "nr") - { - $this->object->setPassNr($a_form->getInput("pass_nr")); - } - - $this->object->setCompletionBySubmission($a_form->getInput('completion_by_submission') == 1 ? true : false); - - $feedback = $a_form->getInput("tfeedback"); - $this->object->setTutorFeedback(is_array($feedback) - ? array_sum($feedback) - : null); - - include_once "./Services/Notification/classes/class.ilNotification.php"; - ilNotification::setNotification(ilNotification::TYPE_EXERCISE_SUBMISSION, - $ilUser->getId(), $this->object->getId(), - (bool)$a_form->getInput("notification")); - - // tile image - $obj_service->commonSettings()->legacyForm($a_form, $this->object)->saveTileImage(); - - ilObjectServiceSettingsGUI::updateServiceSettingsForm( - $this->object->getId(), - $a_form, - array( - ilObjectServiceSettingsGUI::ORGU_POSITION_ACCESS - ) - ); - - } + return true; + } + + public function viewObject() + { + $this->infoScreenObject(); + } + + protected function afterSave(ilObject $a_new_object) + { + $ilCtrl = $this->ctrl; + + $a_new_object->saveData(); + + ilUtil::sendSuccess($this->lng->txt("exc_added"), true); + + $ilCtrl->setParameterByClass("ilExAssignmentEditorGUI", "ref_id", $a_new_object->getRefId()); + $ilCtrl->redirectByClass("ilExAssignmentEditorGUI", "addAssignment"); + } + + protected function listAssignmentsObject() + { + $ilCtrl = $this->ctrl; + + $this->checkPermissionBool("write"); + + // #16587 + $ilCtrl->redirectByClass("ilExAssignmentEditorGUI", "listAssignments"); + } + + /** + * Init properties form. + */ + protected function initEditCustomForm(ilPropertyFormGUI $a_form) + { + $obj_service = $this->getObjectService(); + + $a_form->setTitle($this->lng->txt("exc_edit_exercise")); + + $pres = new ilFormSectionHeaderGUI(); + $pres->setTitle($this->lng->txt('obj_presentation')); + $a_form->addItem($pres); + + // tile image + $a_form = $obj_service->commonSettings()->legacyForm($a_form, $this->object)->addTileImage(); + + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($this->lng->txt('exc_passing_exc')); + $a_form->addItem($section); + + // pass mode + $radg = new ilRadioGroupInputGUI($this->lng->txt("exc_pass_mode"), "pass_mode"); + + $op1 = new ilRadioOption( + $this->lng->txt("exc_pass_all"), + "all", + $this->lng->txt("exc_pass_all_info") + ); + $radg->addOption($op1); + $op2 = new ilRadioOption( + $this->lng->txt("exc_pass_minimum_nr"), + "nr", + $this->lng->txt("exc_pass_minimum_nr_info") + ); + $radg->addOption($op2); + + // minimum number of assignments to pass + $ni = new ilNumberInputGUI($this->lng->txt("exc_min_nr"), "pass_nr"); + $ni->setSize(4); + $ni->setMaxLength(4); + $ni->setRequired(true); + include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); + $mand = ilExAssignment::countMandatory($this->object->getId()); + $min = max($mand, 1); + $ni->setMinValue($min, true); + $ni->setInfo($this->lng->txt("exc_min_nr_info")); + $op2->addSubItem($ni); + + $a_form->addItem($radg); + + // completion by submission + $subcompl = new ilRadioGroupInputGUI($this->lng->txt("exc_passed_status_determination"), "completion_by_submission"); + $op1 = new ilRadioOption($this->lng->txt("exc_completion_by_tutor"), 0, ""); + $subcompl->addOption($op1); + $op2 = new ilRadioOption($this->lng->txt("exc_completion_by_submission"), 1, $this->lng->txt("exc_completion_by_submission_info")); + $subcompl->addOption($op2); + $a_form->addItem($subcompl); + + /*$subcompl = new ilCheckboxInputGUI($this->lng->txt('exc_completion_by_submission'), 'completion_by_submission'); + $subcompl->setInfo($this->lng->txt('exc_completion_by_submission_info')); + $subcompl->setValue(1); + $a_form->addItem($subcompl);*/ + + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($this->lng->txt('exc_publishing')); + $a_form->addItem($section); + + // show submissions + $cb = new ilCheckboxInputGUI($this->lng->txt("exc_show_submissions"), "show_submissions"); + $cb->setInfo($this->lng->txt("exc_show_submissions_info")); + $a_form->addItem($cb); + + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($this->lng->txt('exc_notification')); + $a_form->addItem($section); + + // submission notifications + $cbox = new ilCheckboxInputGUI($this->lng->txt("exc_submission_notification"), "notification"); + $cbox->setInfo($this->lng->txt("exc_submission_notification_info")); + $a_form->addItem($cbox); + + + // feedback settings + + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($this->lng->txt('exc_feedback')); + $a_form->addItem($section); + + $fdb = new ilCheckboxGroupInputGUI($this->lng->txt("exc_settings_feedback"), "tfeedback"); + $a_form->addItem($fdb); + + $option = new ilCheckboxOption($this->lng->txt("exc_settings_feedback_mail"), ilObjExercise::TUTOR_FEEDBACK_MAIL); + $option->setInfo($this->lng->txt("exc_settings_feedback_mail_info")); + $fdb->addOption($option); + $option = new ilCheckboxOption($this->lng->txt("exc_settings_feedback_file"), ilObjExercise::TUTOR_FEEDBACK_FILE); + $option->setInfo($this->lng->txt("exc_settings_feedback_file_info")); + $fdb->addOption($option); + $option = new ilCheckboxOption($this->lng->txt("exc_settings_feedback_text"), ilObjExercise::TUTOR_FEEDBACK_TEXT); + $option->setInfo($this->lng->txt("exc_settings_feedback_text_info")); + $fdb->addOption($option); + + $position_settings = ilOrgUnitGlobalSettings::getInstance() + ->getObjectPositionSettingsByType($this->object->getType()); + + if ($position_settings->isActive()) { + // add additional feature section + $feat = new ilFormSectionHeaderGUI(); + $feat->setTitle($this->lng->txt('obj_features')); + $a_form->addItem($feat); + + // add orgunit settings + ilObjectServiceSettingsGUI::initServiceSettingsForm( + $this->object->getId(), + $a_form, + array( + ilObjectServiceSettingsGUI::ORGU_POSITION_ACCESS + ) + ); + } + } + + /** + * Get values for properties form + */ + protected function getEditFormCustomValues(array &$a_values) + { + $ilUser = $this->user; + + $a_values["desc"] = $this->object->getLongDescription(); + $a_values["show_submissions"] = $this->object->getShowSubmissions(); + $a_values["pass_mode"] = $this->object->getPassMode(); + if ($a_values["pass_mode"] == "nr") { + $a_values["pass_nr"] = $this->object->getPassNr(); + } + + include_once "./Services/Notification/classes/class.ilNotification.php"; + $a_values["notification"] = ilNotification::hasNotification( + ilNotification::TYPE_EXERCISE_SUBMISSION, + $ilUser->getId(), + $this->object->getId() + ); + + $a_values['completion_by_submission'] = (int) $this->object->isCompletionBySubmissionEnabled(); + + $tfeedback = array(); + if ($this->object->hasTutorFeedbackMail()) { + $tfeedback[] = ilObjExercise::TUTOR_FEEDBACK_MAIL; + } + if ($this->object->hasTutorFeedbackText()) { + $tfeedback[] = ilObjExercise::TUTOR_FEEDBACK_TEXT; + } + if ($this->object->hasTutorFeedbackFile()) { + $tfeedback[] = ilObjExercise::TUTOR_FEEDBACK_FILE; + } + $a_values['tfeedback'] = $tfeedback; + + // orgunit position setting enabled + $a_values['obj_orgunit_positions'] = (bool) ilOrgUnitGlobalSettings::getInstance() + ->isPositionAccessActiveForObject($this->object->getId()); + } + + protected function updateCustom(ilPropertyFormGUI $a_form) + { + $obj_service = $this->getObjectService(); + + $ilUser = $this->user; + $this->object->setShowSubmissions($a_form->getInput("show_submissions")); + $this->object->setPassMode($a_form->getInput("pass_mode")); + if ($this->object->getPassMode() == "nr") { + $this->object->setPassNr($a_form->getInput("pass_nr")); + } + + $this->object->setCompletionBySubmission($a_form->getInput('completion_by_submission') == 1 ? true : false); + + $feedback = $a_form->getInput("tfeedback"); + $this->object->setTutorFeedback(is_array($feedback) + ? array_sum($feedback) + : null); + + include_once "./Services/Notification/classes/class.ilNotification.php"; + ilNotification::setNotification( + ilNotification::TYPE_EXERCISE_SUBMISSION, + $ilUser->getId(), + $this->object->getId(), + (bool) $a_form->getInput("notification") + ); + + // tile image + $obj_service->commonSettings()->legacyForm($a_form, $this->object)->saveTileImage(); + + ilObjectServiceSettingsGUI::updateServiceSettingsForm( + $this->object->getId(), + $a_form, + array( + ilObjectServiceSettingsGUI::ORGU_POSITION_ACCESS + ) + ); + } - /** - * Add subtabs of content view - * - * @param object $tabs_gui ilTabsGUI object - */ - function addContentSubTabs($a_activate) - { - $ilTabs = $this->tabs; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $ilTabs->addSubTab("content", $lng->txt("view"), - $ilCtrl->getLinkTarget($this, "showOverview")); - if ($this->checkPermissionBool("write")) - { - $ilTabs->addSubTab("list_assignments", $lng->txt("edit"), - $ilCtrl->getLinkTargetByClass("ilExAssignmentEditorGUI", "listAssignments")); - } - $ilTabs->activateSubTab($a_activate); - } - - /** - * adds tabs to tab gui object - * - * @param object $tabs_gui ilTabsGUI object - */ - function getTabs() - { - $lng = $this->lng; - $ilHelp = $this->help; + /** + * Add subtabs of content view + * + * @param object $tabs_gui ilTabsGUI object + */ + public function addContentSubTabs($a_activate) + { + $ilTabs = $this->tabs; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $ilTabs->addSubTab( + "content", + $lng->txt("view"), + $ilCtrl->getLinkTarget($this, "showOverview") + ); + if ($this->checkPermissionBool("write")) { + $ilTabs->addSubTab( + "list_assignments", + $lng->txt("edit"), + $ilCtrl->getLinkTargetByClass("ilExAssignmentEditorGUI", "listAssignments") + ); + } + $ilTabs->activateSubTab($a_activate); + } + + /** + * adds tabs to tab gui object + * + * @param object $tabs_gui ilTabsGUI object + */ + public function getTabs() + { + $lng = $this->lng; + $ilHelp = $this->help; - $ilHelp->setScreenIdComponent("exc"); - - if ($this->checkPermissionBool("read")) - { - $this->tabs_gui->addTab("content", - $lng->txt("exc_assignments"), - $this->ctrl->getLinkTarget($this, "showOverview")); - } - - $next_class = strtolower($this->ctrl->getNextClass()); - if ($this->checkPermissionBool("visible") || $this->checkPermissionBool("read")) - { - $this->tabs_gui->addTab("info", - $lng->txt("info_short"), - $this->ctrl->getLinkTargetByClass("ilinfoscreengui", "showSummary")); - } - - // edit properties - if ($this->checkPermissionBool("write")) - { - /*$tabs_gui->addTab("assignments", - $lng->txt("exc_edit_assignments"), - $this->ctrl->getLinkTarget($this, 'listAssignments'));*/ - - $this->tabs_gui->addTab("settings", - $lng->txt("settings"), - $this->ctrl->getLinkTarget($this, 'edit')); - - } - if($this->access->checkRbacOrPositionPermissionAccess( - 'edit_submissions_grades', - 'edit_submissions_grades', - $this->object->getRefId())) - { - $this->tabs_gui->addTab("grades", - $lng->txt("exc_submissions_and_grades"), - $this->ctrl->getLinkTargetByClass("ilexercisemanagementgui", "members")); - } - - // learning progress - $save_sort_order = $_GET["sort_order"]; // hack, because exercise sort parameters - $save_sort_by = $_GET["sort_by"]; // must not be forwarded to learning progress - $save_offset = $_GET["offset"]; - $_GET["offset"] = $_GET["sort_by"] = $_GET["sort_order"] = ""; - - include_once './Services/Tracking/classes/class.ilLearningProgressAccess.php'; - if(ilLearningProgressAccess::checkAccess($this->object->getRefId())) - { - $this->tabs_gui->addTab('learning_progress', - $lng->txt('learning_progress'), - $this->ctrl->getLinkTargetByClass(array('ilobjexercisegui','illearningprogressgui'),'')); - } - - $_GET["sort_order"] = $save_sort_order; // hack, part ii - $_GET["sort_by"] = $save_sort_by; - $_GET["offset"] = $save_offset; - - // export - if ($this->checkPermissionBool("write")) - { - $this->tabs_gui->addTab("export", - $lng->txt("export"), - $this->ctrl->getLinkTargetByClass("ilexportgui", "")); - } - - - // permissions - if ($this->checkPermissionBool("edit_permission")) - { - $this->tabs_gui->addTab('permissions', - $lng->txt("perm_settings"), - $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm")); - } - } - - /** - * 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 infoScreenObject() - { - $this->ctrl->setCmd("showSummary"); - $this->ctrl->setCmdClass("ilinfoscreengui"); - $this->infoScreen(); - } - - /** - * show information screen - */ - function infoScreen() - { - $ilUser = $this->user; - $ilTabs = $this->tabs; - $lng = $this->lng; - - $ilTabs->activateTab("info"); - - if (!$this->checkPermissionBool("read")) - { - $this->checkPermission("visible"); - } - - include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); - $info = new ilInfoScreenGUI($this); - - $info->enablePrivateNotes(); - - $info->enableNews(); - if ($this->checkPermissionBool("write")) - { - $info->enableNewsEditing(); - $info->setBlockProperty("news", "settings", true); - } - - // standard meta data - //$info->addMetaDataSections($this->object->getId(),0, $this->object->getType()); - - // instructions - $info->addSection($this->lng->txt("exc_overview")); - include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); - $ass = ilExAssignment::getAssignmentDataOfExercise($this->object->getId()); - $cnt = 0; - $mcnt = 0; - foreach ($ass as $a) - { - $cnt++; - if ($a["mandatory"]) - { - $mcnt++; - } - } - $info->addProperty($lng->txt("exc_assignments"), $cnt); - $info->addProperty($lng->txt("exc_mandatory"), $mcnt); - if ($this->object->getPassMode() != "nr") - { - $info->addProperty($lng->txt("exc_pass_mode"), - $lng->txt("exc_msg_all_mandatory_ass")); - } - else - { - $info->addProperty($lng->txt("exc_pass_mode"), - sprintf($lng->txt("exc_msg_min_number_ass"), $this->object->getPassNr())); - } - - // feedback from tutor - include_once("Services/Tracking/classes/class.ilLPMarks.php"); - if ($this->checkPermissionBool("read")) - { - $lpcomment = ilLPMarks::_lookupComment($ilUser->getId(), $this->object->getId()); - $mark = ilLPMarks::_lookupMark($ilUser->getId(), $this->object->getId()); - //$status = ilExerciseMembers::_lookupStatus($this->object->getId(), $ilUser->getId()); - $st = $this->object->determinStatusOfUser($ilUser->getId()); - $status = $st["overall_status"]; - if ($lpcomment != "" || $mark != "" || $status != "notgraded") - { - $info->addSection($this->lng->txt("exc_feedback_from_tutor")); - if ($lpcomment != "") - { - $info->addProperty($this->lng->txt("exc_comment"), - $lpcomment); - } - if ($mark != "") - { - $info->addProperty($this->lng->txt("exc_mark"), - $mark); - } - - //if ($status == "") - //{ - // $info->addProperty($this->lng->txt("status"), - // $this->lng->txt("message_no_delivered_files")); - //} - //else - if ($status != "notgraded") - { - $img = ''.$lng->txt('; - - $add = ""; - if ($st["failed_a_mandatory"]) - { - $add = " (".$lng->txt("exc_msg_failed_mandatory").")"; - } - else if ($status == "failed") - { - $add = " (".$lng->txt("exc_msg_missed_minimum_number").")"; - } - $info->addProperty($this->lng->txt("status"), - $img." ".$this->lng->txt("exc_".$status).$add); - } - } - } - - // forward the command - $this->ctrl->forwardCommand($info); - } - - function editObject() - { - $this->setSettingsSubTabs(); - $this->tabs_gui->activateSubTab("edit"); - return parent::editObject(); - } - - protected function setSettingsSubTabs() - { - $this->tabs_gui->addSubTab("edit", - $this->lng->txt("general_settings"), - $this->ctrl->getLinkTarget($this, "edit")); - - $this->tabs_gui->addSubTab("crit", - $this->lng->txt("exc_criteria_catalogues"), - $this->ctrl->getLinkTargetByClass("ilexccriteriacataloguegui", "")); - - include_once "Services/Certificate/classes/class.ilCertificate.php"; - if(ilCertificate::isActive()) - { - $this->tabs_gui->addSubTab("certificate", - $this->lng->txt("certificate"), - $this->ctrl->getLinkTarget($this, "certificate")); - } - } - - /** - * redirect script - * - * @param string $a_target - */ - public static function _goto($a_target, $a_raw) - { - global $DIC; - - $ilErr = $DIC["ilErr"]; - $lng = $DIC->language(); - $ilAccess = $DIC->access(); - $ilCtrl = $DIC->ctrl(); - - //we don't have baseClass here... - $ilCtrl->setTargetScript("ilias.php"); - $ilCtrl->initBaseClass("ilRepositoryGUI"); - - //ilExerciseMailNotification has links to: - // "Assignments", "Submission and Grades" and Downnoad the NEW files if the assignment type is "File Upload". - $ass_id = $_GET['ass_id']; - $parts = explode("_", $a_raw); - if(!$ass_id) - { - $ass_id = null; - $action = null; - - switch(end($parts)) - { - case "download": - $action = $parts[3]; - $member = $parts[2]; - $ass_id = $parts[1]; - break; - - case "setdownload": - $action = $parts[3]; - $member = $parts[2]; - $ass_id = $parts[1]; - break; - - case "grades": - $action= $parts[2]; - $ass_id = $parts[1]; - break; - } - } - - $ilCtrl->setParameterByClass("ilExerciseHandlerGUI", "ref_id", $a_target); - - if ($ilAccess->checkAccess("read", "", $a_target)) - { - $ilCtrl->setParameterByClass("ilExerciseHandlerGUI", "target", $a_raw); - - if($ass_id){ - $ilCtrl->setParameterByClass("ilExerciseManagementGUI", "ass_id", $ass_id); - } - - switch($action) - { - case "grades": - $ilCtrl->redirectByClass(array("ilRepositoryGUI", "ilExerciseHandlerGUI", "ilObjExerciseGUI", "ilExerciseManagementGUI"), "members"); - break; - - /*case "download": - $ilCtrl->setParameterByClass("ilExerciseHandlerGUI", "member_id", $member); - $ilCtrl->redirectByClass(array("ilRepositoryGUI", "ilExerciseHandlerGUI", "ilObjExerciseGUI", "ilExerciseManagementGUI", "ilExSubmissionFileGUI"),"downloadNewReturned"); - break;*/ - - case "setdownload": - $ilCtrl->setParameterByClass("ilExerciseHandlerGUI", "member_id", $member); - $ilCtrl->redirectByClass(array("ilRepositoryGUI", "ilExerciseHandlerGUI", "ilObjExerciseGUI", "ilExerciseManagementGUI"),"waitingDownload"); - break; - - default: - if ($parts[1] != "") - { - $ilCtrl->setParameterByClass("ilExerciseHandlerGUI", "ass_id", $parts[1]); - $ilCtrl->setParameterByClass("ilExerciseHandlerGUI", "ass_id_goto", $parts[1]); - } - $ilCtrl->redirectByClass(array("ilRepositoryGUI", "ilExerciseHandlerGUI", "ilObjExerciseGUI"), "showOverview"); - break; - - } - - } - else if ($ilAccess->checkAccess("visible", "", $a_target)) - { - $ilCtrl->redirectByClass(array("ilRepositoryGUI", "ilExerciseHandlerGUI", "ilObjExerciseGUI"), "infoScreen"); - } - else if ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) - { - ilUtil::sendFailure(sprintf($lng->txt("msg_no_perm_read_item"), - ilObject::_lookupTitle(ilObject::_lookupObjId($a_target))), true); - ilObjectGUI::_gotoRepositoryRoot(); - } - } - - /** - * Add locator item - */ - function addLocatorItems() - { - $ilLocator = $this->locator; - - if (is_object($this->object)) - { - // #17955 - $ilLocator->addItem($this->object->getTitle(), $this->ctrl->getLinkTarget($this, "showOverview"), "", $_GET["ref_id"]); - } - } - - - //// - //// Assignments, Learner's View - //// - - /** - * Show overview of assignments - */ - function showOverviewObject() - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; - $ilUser = $this->user; - $ilToolbar = $this->toolbar; - - $this->checkPermission("read"); - - $tpl->addJavaScript("./Modules/Exercise/js/ilExcPresentation.js"); - - include_once("./Services/Tracking/classes/class.ilLearningProgress.php"); - ilLearningProgress::_tracProgress($ilUser->getId(),$this->object->getId(), - $this->object->getRefId(), 'exc'); - - $ilTabs->activateTab("content"); - $this->addContentSubTabs("content"); - - if($this->certificateDownloadValidator->isCertificateDownloadable((int) $ilUser->getId(), (int) $this->object->getId())) { - $ilToolbar->addButton($this->lng->txt("certificate"), - $this->ctrl->getLinkTarget($this, "outCertificate")); - } - - include_once("./Modules/Exercise/classes/class.ilExAssignmentGUI.php"); - $ass_gui = new ilExAssignmentGUI($this->object); - - include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); - include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); - $acc = new ilAccordionGUI(); - $acc->setId("exc_ow_".$this->object->getId()); - - $ass_data = ilExAssignment::getInstancesByExercise($this->object->getId()); - foreach ($ass_data as $ass) - { - // incoming assignment deeplink - $force_open = false; - if(isset($_GET["ass_id_goto"]) && - (int)$_GET["ass_id_goto"] == $ass->getId()) - { - $force_open = true; - } - - $acc->addItem($ass_gui->getOverviewHeader($ass), - $ass_gui->getOverviewBody($ass), - $force_open); - } - - if (count($ass_data) < 2) - { - $acc->setBehaviour("FirstOpen"); - } - else - { - $acc->setUseSessionStorage(true); - } - - $mtpl = new ilTemplate("tpl.exc_ass_overview.html", true, true, "Modules/Exercise"); - $mtpl->setVariable("CONTENT", $acc->getHTML()); - - $tpl->setContent($mtpl->get()); - } - - function certificateObject() - { - $this->setSettingsSubTabs(); - $this->tabs_gui->activateTab("settings"); - $this->tabs_gui->activateSubTab("certificate"); - - $guiFactory = new ilCertificateGUIFactory(); - $output_gui = $guiFactory->create($this->object); - - $output_gui->certificateEditor(); - } - - function outCertificateObject() - { - global $DIC; - - $database = $DIC->database(); - $logger = $DIC->logger()->root(); - - $ilUser = $this->user; - - $objectId = (int) $this->object->getId(); - - if(false === $this->certificateDownloadValidator->isCertificateDownloadable($ilUser->getId(), $objectId)) { - ilUtil::sendFailure($this->lng->txt("permission_denied"), true); - $this->ctrl->redirect($this); - } - - $ilUserCertificateRepository = new ilUserCertificateRepository($database, $logger); - $pdfGenerator = new ilPdfGenerator($ilUserCertificateRepository, $logger); - - $pdfAction = new ilCertificatePdfAction( - $logger, - $pdfGenerator, - new ilCertificateUtilHelper(), - $this->lng->txt('error_creating_certificate_pdf') - ); - - $pdfAction->downloadPdf((int) $ilUser->getId(), (int) $objectId); - } - - /** - * Start assignment with relative deadline - */ - function startAssignmentObject() - { - global $DIC; - - $ilCtrl = $DIC->ctrl(); - $ilUser = $DIC->user(); - - if ($this->ass) - { - include_once("./Modules/Exercise/classes/class.ilExcAssMemberState.php"); - $state = ilExcAssMemberState::getInstanceByIds($this->ass->getId(), $ilUser->getId()); - if (!$state->getCommonDeadline() && $state->getRelativeDeadline()) - { - $idl = $state->getIndividualDeadlineObject(); - $idl->setStartingTimestamp(time()); - $idl->save(); - } - } - - $ilCtrl->redirect($this, "showOverview"); - } + $ilHelp->setScreenIdComponent("exc"); + + if ($this->checkPermissionBool("read")) { + $this->tabs_gui->addTab( + "content", + $lng->txt("exc_assignments"), + $this->ctrl->getLinkTarget($this, "showOverview") + ); + } + + $next_class = strtolower($this->ctrl->getNextClass()); + if ($this->checkPermissionBool("visible") || $this->checkPermissionBool("read")) { + $this->tabs_gui->addTab( + "info", + $lng->txt("info_short"), + $this->ctrl->getLinkTargetByClass("ilinfoscreengui", "showSummary") + ); + } + + // edit properties + if ($this->checkPermissionBool("write")) { + /*$tabs_gui->addTab("assignments", + $lng->txt("exc_edit_assignments"), + $this->ctrl->getLinkTarget($this, 'listAssignments'));*/ + + $this->tabs_gui->addTab( + "settings", + $lng->txt("settings"), + $this->ctrl->getLinkTarget($this, 'edit') + ); + } + if ($this->access->checkRbacOrPositionPermissionAccess( + 'edit_submissions_grades', + 'edit_submissions_grades', + $this->object->getRefId() + )) { + $this->tabs_gui->addTab( + "grades", + $lng->txt("exc_submissions_and_grades"), + $this->ctrl->getLinkTargetByClass("ilexercisemanagementgui", "members") + ); + } + + // learning progress + $save_sort_order = $_GET["sort_order"]; // hack, because exercise sort parameters + $save_sort_by = $_GET["sort_by"]; // must not be forwarded to learning progress + $save_offset = $_GET["offset"]; + $_GET["offset"] = $_GET["sort_by"] = $_GET["sort_order"] = ""; + + include_once './Services/Tracking/classes/class.ilLearningProgressAccess.php'; + if (ilLearningProgressAccess::checkAccess($this->object->getRefId())) { + $this->tabs_gui->addTab( + 'learning_progress', + $lng->txt('learning_progress'), + $this->ctrl->getLinkTargetByClass(array('ilobjexercisegui','illearningprogressgui'), '') + ); + } + + $_GET["sort_order"] = $save_sort_order; // hack, part ii + $_GET["sort_by"] = $save_sort_by; + $_GET["offset"] = $save_offset; + + // export + if ($this->checkPermissionBool("write")) { + $this->tabs_gui->addTab( + "export", + $lng->txt("export"), + $this->ctrl->getLinkTargetByClass("ilexportgui", "") + ); + } + + + // permissions + if ($this->checkPermissionBool("edit_permission")) { + $this->tabs_gui->addTab( + 'permissions', + $lng->txt("perm_settings"), + $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm") + ); + } + } + + /** + * 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 infoScreenObject() + { + $this->ctrl->setCmd("showSummary"); + $this->ctrl->setCmdClass("ilinfoscreengui"); + $this->infoScreen(); + } + + /** + * show information screen + */ + public function infoScreen() + { + $ilUser = $this->user; + $ilTabs = $this->tabs; + $lng = $this->lng; + + $ilTabs->activateTab("info"); + + if (!$this->checkPermissionBool("read")) { + $this->checkPermission("visible"); + } + + include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); + $info = new ilInfoScreenGUI($this); + + $info->enablePrivateNotes(); + + $info->enableNews(); + if ($this->checkPermissionBool("write")) { + $info->enableNewsEditing(); + $info->setBlockProperty("news", "settings", true); + } + + // standard meta data + //$info->addMetaDataSections($this->object->getId(),0, $this->object->getType()); + + // instructions + $info->addSection($this->lng->txt("exc_overview")); + include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); + $ass = ilExAssignment::getAssignmentDataOfExercise($this->object->getId()); + $cnt = 0; + $mcnt = 0; + foreach ($ass as $a) { + $cnt++; + if ($a["mandatory"]) { + $mcnt++; + } + } + $info->addProperty($lng->txt("exc_assignments"), $cnt); + $info->addProperty($lng->txt("exc_mandatory"), $mcnt); + if ($this->object->getPassMode() != "nr") { + $info->addProperty( + $lng->txt("exc_pass_mode"), + $lng->txt("exc_msg_all_mandatory_ass") + ); + } else { + $info->addProperty( + $lng->txt("exc_pass_mode"), + sprintf($lng->txt("exc_msg_min_number_ass"), $this->object->getPassNr()) + ); + } + + // feedback from tutor + include_once("Services/Tracking/classes/class.ilLPMarks.php"); + if ($this->checkPermissionBool("read")) { + $lpcomment = ilLPMarks::_lookupComment($ilUser->getId(), $this->object->getId()); + $mark = ilLPMarks::_lookupMark($ilUser->getId(), $this->object->getId()); + //$status = ilExerciseMembers::_lookupStatus($this->object->getId(), $ilUser->getId()); + $st = $this->object->determinStatusOfUser($ilUser->getId()); + $status = $st["overall_status"]; + if ($lpcomment != "" || $mark != "" || $status != "notgraded") { + $info->addSection($this->lng->txt("exc_feedback_from_tutor")); + if ($lpcomment != "") { + $info->addProperty( + $this->lng->txt("exc_comment"), + $lpcomment + ); + } + if ($mark != "") { + $info->addProperty( + $this->lng->txt("exc_mark"), + $mark + ); + } + + //if ($status == "") + //{ + // $info->addProperty($this->lng->txt("status"), + // $this->lng->txt("message_no_delivered_files")); + //} + //else + if ($status != "notgraded") { + $img = '' . $lng->txt('; + + $add = ""; + if ($st["failed_a_mandatory"]) { + $add = " (" . $lng->txt("exc_msg_failed_mandatory") . ")"; + } elseif ($status == "failed") { + $add = " (" . $lng->txt("exc_msg_missed_minimum_number") . ")"; + } + $info->addProperty( + $this->lng->txt("status"), + $img . " " . $this->lng->txt("exc_" . $status) . $add + ); + } + } + } + + // forward the command + $this->ctrl->forwardCommand($info); + } + + public function editObject() + { + $this->setSettingsSubTabs(); + $this->tabs_gui->activateSubTab("edit"); + return parent::editObject(); + } + + protected function setSettingsSubTabs() + { + $this->tabs_gui->addSubTab( + "edit", + $this->lng->txt("general_settings"), + $this->ctrl->getLinkTarget($this, "edit") + ); + + $this->tabs_gui->addSubTab( + "crit", + $this->lng->txt("exc_criteria_catalogues"), + $this->ctrl->getLinkTargetByClass("ilexccriteriacataloguegui", "") + ); + + include_once "Services/Certificate/classes/class.ilCertificate.php"; + if (ilCertificate::isActive()) { + $this->tabs_gui->addSubTab( + "certificate", + $this->lng->txt("certificate"), + $this->ctrl->getLinkTarget($this, "certificate") + ); + } + } + + /** + * redirect script + * + * @param string $a_target + */ + public static function _goto($a_target, $a_raw) + { + global $DIC; + + $ilErr = $DIC["ilErr"]; + $lng = $DIC->language(); + $ilAccess = $DIC->access(); + $ilCtrl = $DIC->ctrl(); + + //we don't have baseClass here... + $ilCtrl->setTargetScript("ilias.php"); + $ilCtrl->initBaseClass("ilRepositoryGUI"); + + //ilExerciseMailNotification has links to: + // "Assignments", "Submission and Grades" and Downnoad the NEW files if the assignment type is "File Upload". + $ass_id = $_GET['ass_id']; + $parts = explode("_", $a_raw); + if (!$ass_id) { + $ass_id = null; + $action = null; + + switch (end($parts)) { + case "download": + $action = $parts[3]; + $member = $parts[2]; + $ass_id = $parts[1]; + break; + + case "setdownload": + $action = $parts[3]; + $member = $parts[2]; + $ass_id = $parts[1]; + break; + + case "grades": + $action= $parts[2]; + $ass_id = $parts[1]; + break; + } + } + + $ilCtrl->setParameterByClass("ilExerciseHandlerGUI", "ref_id", $a_target); + + if ($ilAccess->checkAccess("read", "", $a_target)) { + $ilCtrl->setParameterByClass("ilExerciseHandlerGUI", "target", $a_raw); + + if ($ass_id) { + $ilCtrl->setParameterByClass("ilExerciseManagementGUI", "ass_id", $ass_id); + } + + switch ($action) { + case "grades": + $ilCtrl->redirectByClass(array("ilRepositoryGUI", "ilExerciseHandlerGUI", "ilObjExerciseGUI", "ilExerciseManagementGUI"), "members"); + break; + + /*case "download": + $ilCtrl->setParameterByClass("ilExerciseHandlerGUI", "member_id", $member); + $ilCtrl->redirectByClass(array("ilRepositoryGUI", "ilExerciseHandlerGUI", "ilObjExerciseGUI", "ilExerciseManagementGUI", "ilExSubmissionFileGUI"),"downloadNewReturned"); + break;*/ + + case "setdownload": + $ilCtrl->setParameterByClass("ilExerciseHandlerGUI", "member_id", $member); + $ilCtrl->redirectByClass(array("ilRepositoryGUI", "ilExerciseHandlerGUI", "ilObjExerciseGUI", "ilExerciseManagementGUI"), "waitingDownload"); + break; + + default: + if ($parts[1] != "") { + $ilCtrl->setParameterByClass("ilExerciseHandlerGUI", "ass_id", $parts[1]); + $ilCtrl->setParameterByClass("ilExerciseHandlerGUI", "ass_id_goto", $parts[1]); + } + $ilCtrl->redirectByClass(array("ilRepositoryGUI", "ilExerciseHandlerGUI", "ilObjExerciseGUI"), "showOverview"); + break; + + } + } elseif ($ilAccess->checkAccess("visible", "", $a_target)) { + $ilCtrl->redirectByClass(array("ilRepositoryGUI", "ilExerciseHandlerGUI", "ilObjExerciseGUI"), "infoScreen"); + } elseif ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) { + ilUtil::sendFailure(sprintf( + $lng->txt("msg_no_perm_read_item"), + ilObject::_lookupTitle(ilObject::_lookupObjId($a_target)) + ), true); + ilObjectGUI::_gotoRepositoryRoot(); + } + } + + /** + * Add locator item + */ + public function addLocatorItems() + { + $ilLocator = $this->locator; + + if (is_object($this->object)) { + // #17955 + $ilLocator->addItem($this->object->getTitle(), $this->ctrl->getLinkTarget($this, "showOverview"), "", $_GET["ref_id"]); + } + } + + + //// + //// Assignments, Learner's View + //// + + /** + * Show overview of assignments + */ + public function showOverviewObject() + { + $tpl = $this->tpl; + $ilTabs = $this->tabs; + $ilUser = $this->user; + $ilToolbar = $this->toolbar; + + $this->checkPermission("read"); + + $tpl->addJavaScript("./Modules/Exercise/js/ilExcPresentation.js"); + + include_once("./Services/Tracking/classes/class.ilLearningProgress.php"); + ilLearningProgress::_tracProgress( + $ilUser->getId(), + $this->object->getId(), + $this->object->getRefId(), + 'exc' + ); + + $ilTabs->activateTab("content"); + $this->addContentSubTabs("content"); + + if ($this->certificateDownloadValidator->isCertificateDownloadable((int) $ilUser->getId(), (int) $this->object->getId())) { + $ilToolbar->addButton( + $this->lng->txt("certificate"), + $this->ctrl->getLinkTarget($this, "outCertificate") + ); + } + + include_once("./Modules/Exercise/classes/class.ilExAssignmentGUI.php"); + $ass_gui = new ilExAssignmentGUI($this->object); + + include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); + include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); + $acc = new ilAccordionGUI(); + $acc->setId("exc_ow_" . $this->object->getId()); + + $ass_data = ilExAssignment::getInstancesByExercise($this->object->getId()); + foreach ($ass_data as $ass) { + // incoming assignment deeplink + $force_open = false; + if (isset($_GET["ass_id_goto"]) && + (int) $_GET["ass_id_goto"] == $ass->getId()) { + $force_open = true; + } + + $acc->addItem( + $ass_gui->getOverviewHeader($ass), + $ass_gui->getOverviewBody($ass), + $force_open + ); + } + + if (count($ass_data) < 2) { + $acc->setBehaviour("FirstOpen"); + } else { + $acc->setUseSessionStorage(true); + } + + $mtpl = new ilTemplate("tpl.exc_ass_overview.html", true, true, "Modules/Exercise"); + $mtpl->setVariable("CONTENT", $acc->getHTML()); + + $tpl->setContent($mtpl->get()); + } + + public function certificateObject() + { + $this->setSettingsSubTabs(); + $this->tabs_gui->activateTab("settings"); + $this->tabs_gui->activateSubTab("certificate"); + + $guiFactory = new ilCertificateGUIFactory(); + $output_gui = $guiFactory->create($this->object); + + $output_gui->certificateEditor(); + } + + public function outCertificateObject() + { + global $DIC; + + $database = $DIC->database(); + $logger = $DIC->logger()->root(); + + $ilUser = $this->user; + + $objectId = (int) $this->object->getId(); + + if (false === $this->certificateDownloadValidator->isCertificateDownloadable($ilUser->getId(), $objectId)) { + ilUtil::sendFailure($this->lng->txt("permission_denied"), true); + $this->ctrl->redirect($this); + } + + $ilUserCertificateRepository = new ilUserCertificateRepository($database, $logger); + $pdfGenerator = new ilPdfGenerator($ilUserCertificateRepository, $logger); + + $pdfAction = new ilCertificatePdfAction( + $logger, + $pdfGenerator, + new ilCertificateUtilHelper(), + $this->lng->txt('error_creating_certificate_pdf') + ); + + $pdfAction->downloadPdf((int) $ilUser->getId(), (int) $objectId); + } + + /** + * Start assignment with relative deadline + */ + public function startAssignmentObject() + { + global $DIC; + + $ilCtrl = $DIC->ctrl(); + $ilUser = $DIC->user(); + + if ($this->ass) { + include_once("./Modules/Exercise/classes/class.ilExcAssMemberState.php"); + $state = ilExcAssMemberState::getInstanceByIds($this->ass->getId(), $ilUser->getId()); + if (!$state->getCommonDeadline() && $state->getRelativeDeadline()) { + $idl = $state->getIndividualDeadlineObject(); + $idl->setStartingTimestamp(time()); + $idl->save(); + } + } + + $ilCtrl->redirect($this, "showOverview"); + } } - -?> diff --git a/Modules/Exercise/classes/class.ilObjExerciseListGUI.php b/Modules/Exercise/classes/class.ilObjExerciseListGUI.php index ef476f42af3cab0639fc6a753e88bbc6e8fa1bed..12770906602ab9c7719b6abed1a57cbbf4cf206e 100644 --- a/Modules/Exercise/classes/class.ilObjExerciseListGUI.php +++ b/Modules/Exercise/classes/class.ilObjExerciseListGUI.php @@ -13,107 +13,101 @@ include_once "Services/Object/classes/class.ilObjectListGUI.php"; */ class ilObjExerciseListGUI extends ilObjectListGUI { - /** - * initialisation - */ - function init() - { - $this->static_link_enabled = true; - $this->delete_enabled = true; - $this->cut_enabled = true; - $this->copy_enabled = true; - $this->subscribe_enabled = true; - $this->link_enabled = true; - $this->info_screen_enabled = true; - $this->type = "exc"; - $this->gui_class_name = "ilobjexercisegui"; - - // general commands array - include_once('./Modules/Exercise/classes/class.ilObjExerciseAccess.php'); - $this->commands = ilObjExerciseAccess::_getCommands(); - } - - - /** - * inititialize new item - * - * @param int $a_ref_id reference id - * @param int $a_obj_id object id - * @param string $a_title title - * @param string $a_description description - */ - function initItem($a_ref_id, $a_obj_id, $a_title = "", $a_description = "") - { - parent::initItem($a_ref_id, $a_obj_id, $a_title, $a_description); - } - - - /** - * Get command target frame - * - * @param string $a_cmd command - * - * @return string command target frame - */ - function getCommandFrame($a_cmd) - { - switch($a_cmd) - { - default: - $frame = ilFrameTargetInfo::_getFrame("MainContent"); - break; - } - - return $frame; - } - - - - /** - * Get item properties - * - * @return array array of property arrays: - * "alert" (boolean) => display as an alert property (usually in red) - * "property" (string) => property name - * "value" (string) => property value - */ - function getProperties() - { - $lng = $this->lng; - $ilUser = $this->user; - - $props = array(); - $rem = ilObjExerciseAccess::_lookupRemainingWorkingTimeString($this->obj_id); - if ($rem["mtime"] != "") - { - $props[] = array( - "property" => ($rem["cnt"] > 1) - ? $this->lng->txt("exc_next_deadline") - : $this->lng->txt("exc_next_deadline_single"), - "value" => $rem["mtime"] - ); - } - - return $props; - } - - - /** - * Get command link url. - * - * @param int $a_ref_id reference id - * @param string $a_cmd command - * - */ - function getCommandLink($a_cmd) - { - // separate method for this line - $cmd_link = "ilias.php?baseClass=ilExerciseHandlerGUI&ref_id=".$this->ref_id."&cmd=$a_cmd"; - - return $cmd_link; - } - - - + /** + * initialisation + */ + public function init() + { + $this->static_link_enabled = true; + $this->delete_enabled = true; + $this->cut_enabled = true; + $this->copy_enabled = true; + $this->subscribe_enabled = true; + $this->link_enabled = true; + $this->info_screen_enabled = true; + $this->type = "exc"; + $this->gui_class_name = "ilobjexercisegui"; + + // general commands array + include_once('./Modules/Exercise/classes/class.ilObjExerciseAccess.php'); + $this->commands = ilObjExerciseAccess::_getCommands(); + } + + + /** + * inititialize new item + * + * @param int $a_ref_id reference id + * @param int $a_obj_id object id + * @param string $a_title title + * @param string $a_description description + */ + public function initItem($a_ref_id, $a_obj_id, $a_title = "", $a_description = "") + { + parent::initItem($a_ref_id, $a_obj_id, $a_title, $a_description); + } + + + /** + * Get command target frame + * + * @param string $a_cmd command + * + * @return string command target frame + */ + public function getCommandFrame($a_cmd) + { + switch ($a_cmd) { + default: + $frame = ilFrameTargetInfo::_getFrame("MainContent"); + break; + } + + return $frame; + } + + + + /** + * Get item properties + * + * @return array array of property arrays: + * "alert" (boolean) => display as an alert property (usually in red) + * "property" (string) => property name + * "value" (string) => property value + */ + public function getProperties() + { + $lng = $this->lng; + $ilUser = $this->user; + + $props = array(); + $rem = ilObjExerciseAccess::_lookupRemainingWorkingTimeString($this->obj_id); + if ($rem["mtime"] != "") { + $props[] = array( + "property" => ($rem["cnt"] > 1) + ? $this->lng->txt("exc_next_deadline") + : $this->lng->txt("exc_next_deadline_single"), + "value" => $rem["mtime"] + ); + } + + return $props; + } + + + /** + * Get command link url. + * + * @param int $a_ref_id reference id + * @param string $a_cmd command + * + */ + public function getCommandLink($a_cmd) + { + // separate method for this line + $cmd_link = "ilias.php?baseClass=ilExerciseHandlerGUI&ref_id=" . $this->ref_id . "&cmd=$a_cmd"; + + return $cmd_link; + } } // END class.ilObjTestListGUI -?> diff --git a/Modules/Exercise/classes/class.ilObjExerciseSubItemListGUI.php b/Modules/Exercise/classes/class.ilObjExerciseSubItemListGUI.php index fc88e13f588e6cf2d99203ae8f1a4cfe25c11500..d71b6067156c0cbcfc8b25f6b4028fb5c6524f77 100644 --- a/Modules/Exercise/classes/class.ilObjExerciseSubItemListGUI.php +++ b/Modules/Exercise/classes/class.ilObjExerciseSubItemListGUI.php @@ -6,7 +6,7 @@ include_once './Services/Object/classes/class.ilSubItemListGUI.php'; include_once './Modules/Exercise/classes/class.ilExAssignment.php'; /** -* Represents search sub item lists +* Represents search sub item lists * * @author Stefan Meyer * @version $Id$ @@ -15,89 +15,81 @@ include_once './Modules/Exercise/classes/class.ilExAssignment.php'; */ class ilObjExerciseSubItemListGUI extends ilSubItemListGUI { - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * Constructor - */ - function __construct($a_cmd_class) - { - global $DIC; - parent::__construct($a_cmd_class); + /** + * Constructor + */ + public function __construct($a_cmd_class) + { + global $DIC; + parent::__construct($a_cmd_class); - $this->access = $DIC->access(); - } + $this->access = $DIC->access(); + } - /** - * Check if read access to assignments is granted - * @param int assignment id - * @return - */ - protected function isAssignmentVisible($a_ass_id) - { - $ilAccess = $this->access; - - if($ilAccess->checkAccess('write','',$this->getRefId())) - { - return true; - } - - return ilExAssignment::lookupAssignmentOnline($a_ass_id); - } + /** + * Check if read access to assignments is granted + * @param int assignment id + * @return + */ + protected function isAssignmentVisible($a_ass_id) + { + $ilAccess = $this->access; + + if ($ilAccess->checkAccess('write', '', $this->getRefId())) { + return true; + } + + return ilExAssignment::lookupAssignmentOnline($a_ass_id); + } - /** - * @see ilSubItemListGUI::getHTML() - */ - public function getHTML() - { - $lng = $this->lng; - - $lng->loadLanguageModule('exc'); - - $valid = false; - foreach($this->getSubItemIds(true) as $sub_item) - { - if(!$this->isAssignmentVisible($sub_item)) - { - continue; - } - $valid = true; + /** + * @see ilSubItemListGUI::getHTML() + */ + public function getHTML() + { + $lng = $this->lng; + + $lng->loadLanguageModule('exc'); + + $valid = false; + foreach ($this->getSubItemIds(true) as $sub_item) { + if (!$this->isAssignmentVisible($sub_item)) { + continue; + } + $valid = true; - if(is_object($this->getHighlighter()) and strlen($this->getHighlighter()->getContent($this->getObjId(),$sub_item))) - { - $this->tpl->setCurrentBlock('sea_fragment'); - $this->tpl->setVariable('TXT_FRAGMENT',$this->getHighlighter()->getContent($this->getObjId(),$sub_item)); - $this->tpl->parseCurrentBlock(); - } - $this->tpl->setCurrentBlock('subitem'); - $this->tpl->setVariable('SUBITEM_TYPE',$lng->txt('exc_assignment')); - $this->tpl->setVariable('SEPERATOR',':'); - - #$link_data = ilLinkResourceItems::lookupItem($this->getObjId(),$sub_item); - #$link_data = ilParameterAppender::_append($link_data); + if (is_object($this->getHighlighter()) and strlen($this->getHighlighter()->getContent($this->getObjId(), $sub_item))) { + $this->tpl->setCurrentBlock('sea_fragment'); + $this->tpl->setVariable('TXT_FRAGMENT', $this->getHighlighter()->getContent($this->getObjId(), $sub_item)); + $this->tpl->parseCurrentBlock(); + } + $this->tpl->setCurrentBlock('subitem'); + $this->tpl->setVariable('SUBITEM_TYPE', $lng->txt('exc_assignment')); + $this->tpl->setVariable('SEPERATOR', ':'); + + #$link_data = ilLinkResourceItems::lookupItem($this->getObjId(),$sub_item); + #$link_data = ilParameterAppender::_append($link_data); - #$this->getItemListGUI()->setChildId($sub_item); - $this->tpl->setVariable('LINK','ilias.php?baseClass=ilExerciseHandlerGUI&cmd=showOverview&ref_id='.$this->getRefId().'&ass_id='.$sub_item); - $this->tpl->setVariable('TITLE',ilExAssignment::lookupTitle($sub_item)); + #$this->getItemListGUI()->setChildId($sub_item); + $this->tpl->setVariable('LINK', 'ilias.php?baseClass=ilExerciseHandlerGUI&cmd=showOverview&ref_id=' . $this->getRefId() . '&ass_id=' . $sub_item); + $this->tpl->setVariable('TITLE', ilExAssignment::lookupTitle($sub_item)); - if(count($this->getSubItemIds(true)) > 1) - { - $this->parseRelevance($sub_item); - } - - $this->tpl->parseCurrentBlock(); - } - - $this->showDetailsLink(); - - return $valid ? $this->tpl->get() : ''; - - - } + if (count($this->getSubItemIds(true)) > 1) { + $this->parseRelevance($sub_item); + } + + $this->tpl->parseCurrentBlock(); + } + + $this->showDetailsLink(); + + return $valid ? $this->tpl->get() : ''; + } } -?> \ No newline at end of file diff --git a/Modules/Exercise/classes/class.ilObjExerciseVerification.php b/Modules/Exercise/classes/class.ilObjExerciseVerification.php index 23ceb9172c7c7c7f8839a8e3d48adc7a5710dc15..618b8a5ed930ac8f3923d915a39edf8f8993905a 100644 --- a/Modules/Exercise/classes/class.ilObjExerciseVerification.php +++ b/Modules/Exercise/classes/class.ilObjExerciseVerification.php @@ -1,35 +1,33 @@ - -* -* @version $Id$ -* -* @ingroup ModulesExercise -*/ -class ilObjExerciseVerification extends ilVerificationObject -{ - protected function initType() - { - $this->type = "excv"; - } - - protected function getPropertyMap() - { - return array("issued_on" => self::TYPE_DATE, - "file" => self::TYPE_STRING - /* - "success" => self::TYPE_BOOL, - "mark" => self::TYPE_STRING, - "comment" => self::TYPE_STRING - */ - ); - } -} - -?> + +* +* @version $Id$ +* +* @ingroup ModulesExercise +*/ +class ilObjExerciseVerification extends ilVerificationObject +{ + protected function initType() + { + $this->type = "excv"; + } + + protected function getPropertyMap() + { + return array("issued_on" => self::TYPE_DATE, + "file" => self::TYPE_STRING + /* + "success" => self::TYPE_BOOL, + "mark" => self::TYPE_STRING, + "comment" => self::TYPE_STRING + */ + ); + } +} diff --git a/Modules/Exercise/classes/class.ilObjExerciseVerificationAccess.php b/Modules/Exercise/classes/class.ilObjExerciseVerificationAccess.php index 94ba6d33927ce4fd8e087779630d005cb8d73467..1012ff6bfe29194dee71a6efcd0a5ebddbd9998d 100644 --- a/Modules/Exercise/classes/class.ilObjExerciseVerificationAccess.php +++ b/Modules/Exercise/classes/class.ilObjExerciseVerificationAccess.php @@ -1,60 +1,56 @@ - -* @version $Id: class.ilObjFolderAccess.php 26739 2010-11-28 20:33:51Z smeyer $ -* -*/ -class ilObjExerciseVerificationAccess extends ilObjectAccess -{ - /** - * 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(); - $commands[] = array("permission" => "read", "cmd" => "view", "lang_var" => "show", "default" => true); - return $commands; - } - - static function _checkGoto($a_target) - { - global $DIC; +access(); - - $t_arr = explode("_", $a_target); - - // #11021 - // personal workspace context: do not force normal login - if(isset($t_arr[2]) && $t_arr[2] == "wsp") - { - include_once "Services/PersonalWorkspace/classes/class.ilSharedResourceGUI.php"; - return ilSharedResourceGUI::hasAccess($t_arr[1]); - } - - if ($ilAccess->checkAccess("read", "", $t_arr[1])) - { - return true; - } - return false; - } -} - -?> +/* Copyright (c) 1998-2009 ILIAS open source, Extended GPL, see docs/LICENSE */ + +include_once("./Services/Object/classes/class.ilObjectAccess.php"); + +/** +* Class ilObjExerciseVerificationAccess +* +* +* @author Jörg Lützenkirchen +* @version $Id: class.ilObjFolderAccess.php 26739 2010-11-28 20:33:51Z smeyer $ +* +*/ +class ilObjExerciseVerificationAccess extends ilObjectAccess +{ + /** + * 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(); + $commands[] = array("permission" => "read", "cmd" => "view", "lang_var" => "show", "default" => true); + return $commands; + } + + public static function _checkGoto($a_target) + { + global $DIC; + + $ilAccess = $DIC->access(); + + $t_arr = explode("_", $a_target); + + // #11021 + // personal workspace context: do not force normal login + if (isset($t_arr[2]) && $t_arr[2] == "wsp") { + include_once "Services/PersonalWorkspace/classes/class.ilSharedResourceGUI.php"; + return ilSharedResourceGUI::hasAccess($t_arr[1]); + } + + if ($ilAccess->checkAccess("read", "", $t_arr[1])) { + return true; + } + return false; + } +} diff --git a/Modules/Exercise/classes/class.ilObjExerciseVerificationGUI.php b/Modules/Exercise/classes/class.ilObjExerciseVerificationGUI.php index 79593047c02091fa21d4223d5645a1b2c0cd89f9..ec8e5ed647689fa292c4dd995227fed28f708659 100644 --- a/Modules/Exercise/classes/class.ilObjExerciseVerificationGUI.php +++ b/Modules/Exercise/classes/class.ilObjExerciseVerificationGUI.php @@ -1,191 +1,170 @@ - -* @version $Id: class.ilPersonalDesktopGUI.php 26976 2010-12-16 13:24:38Z akill $ -* -* @ilCtrl_Calls ilObjExerciseVerificationGUI: ilWorkspaceAccessGUI -* -* @ingroup ModulesExercise -*/ -class ilObjExerciseVerificationGUI extends ilObject2GUI -{ - public function getType() - { - return "excv"; - } - - /** - * List all exercises in which current user participated - */ - public function create() - { - $ilTabs = $this->tabs_gui; - - if($this->id_type == self::WORKSPACE_NODE_ID) - { - include_once "Services/DiskQuota/classes/class.ilDiskQuotaHandler.php"; - if(!ilDiskQuotaHandler::isUploadPossible()) - { - $this->lng->loadLanguageModule("file"); - ilUtil::sendFailure($this->lng->txt("personal_workspace_quota_exceeded_warning"), true); - $this->ctrl->redirect($this, "cancel"); - } - } - - $this->lng->loadLanguageModule("excv"); - - $ilTabs->setBackTarget($this->lng->txt("back"), - $this->ctrl->getLinkTarget($this, "cancel")); - - include_once "Modules/Exercise/classes/class.ilExerciseVerificationTableGUI.php"; - $table = new ilExerciseVerificationTableGUI($this, "create"); - $this->tpl->setContent($table->getHTML()); - } - - /** - * create new instance and save it - */ - public function save() - { - global $DIC; - - $ilUser = $this->user; - - $objectId = $_REQUEST["exc_id"]; - if($objectId) - { - $certificateVerificationFileService = new ilCertificateVerificationFileService( - $DIC->language(), - $DIC->database(), - $DIC->logger()->root(), - new ilCertificateVerificationClassMap() - ); - - $userCertificateRepository = new ilUserCertificateRepository(); - - $userCertificatePresentation = $userCertificateRepository->fetchActiveCertificateForPresentation( - (int) $ilUser->getId(), - (int) $objectId - ); - - try { - $newObj = $certificateVerificationFileService->createFile($userCertificatePresentation); - } catch (\Exception $exception) { - ilUtil::sendFailure($this->lng->txt('error_creating_certificate_pdf')); - return $this->create(); - } - - if($newObj) - { - $parent_id = $this->node_id; - $this->node_id = null; - $this->putObjectInTree($newObj, $parent_id); - - $this->afterSave($newObj); - } - else - { - ilUtil::sendFailure($this->lng->txt("msg_failed")); - } - } - else - { - ilUtil::sendFailure($this->lng->txt("select_one")); - } - $this->create(); - } - - public function deliver() - { - $file = $this->object->getFilePath(); - if($file) - { - ilUtil::deliverFile($file, $this->object->getTitle().".pdf"); - } - } - - /** - * Render content - * - * @param bool $a_return - * @param string $a_url - */ - public function render($a_return = false, $a_url = false) - { - $ilUser = $this->user; - $lng = $this->lng; - - if(!$a_return) - { - $this->deliver(); - } - else - { - $tree = new ilWorkspaceTree($ilUser->getId()); - $wsp_id = $tree->lookupNodeId($this->object->getId()); - - $caption = $lng->txt("wsp_type_excv").' "'.$this->object->getTitle().'"'; - - $valid = true; - if(!file_exists($this->object->getFilePath())) - { - $valid = false; - $message = $lng->txt("url_not_found"); - } - else if(!$a_url) - { - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; - $access_handler = new ilWorkspaceAccessHandler($tree); - if(!$access_handler->checkAccess("read", "", $wsp_id)) - { - $valid = false; - $message = $lng->txt("permission_denied"); - } - } - - if($valid) - { - if(!$a_url) - { - $a_url = $this->getAccessHandler()->getGotoLink($wsp_id, $this->object->getId()); - } - return ''; - } - else - { - return '
'.$caption.' ('.$message.')
'; - } - } - } - - function downloadFromPortfolioPage(ilPortfolioPage $a_page) - { - include_once "Services/COPage/classes/class.ilPCVerification.php"; - if(ilPCVerification::isInPortfolioPage($a_page, $this->object->getType(), $this->object->getId())) - { - $this->deliver(); - } - - include_once "Modules/Exercise/exceptions/class.ilExerciseException.php"; - throw new ilExerciseException($this->lng->txt('permission_denied')); - } - - public static function _goto($a_target) - { - $id = explode("_", $a_target); - - $_GET["baseClass"] = "ilsharedresourceGUI"; - $_GET["wsp_id"] = $id[0]; - include("ilias.php"); - exit; - } -} - -?> + +* @version $Id: class.ilPersonalDesktopGUI.php 26976 2010-12-16 13:24:38Z akill $ +* +* @ilCtrl_Calls ilObjExerciseVerificationGUI: ilWorkspaceAccessGUI +* +* @ingroup ModulesExercise +*/ +class ilObjExerciseVerificationGUI extends ilObject2GUI +{ + public function getType() + { + return "excv"; + } + + /** + * List all exercises in which current user participated + */ + public function create() + { + $ilTabs = $this->tabs_gui; + + if ($this->id_type == self::WORKSPACE_NODE_ID) { + include_once "Services/DiskQuota/classes/class.ilDiskQuotaHandler.php"; + if (!ilDiskQuotaHandler::isUploadPossible()) { + $this->lng->loadLanguageModule("file"); + ilUtil::sendFailure($this->lng->txt("personal_workspace_quota_exceeded_warning"), true); + $this->ctrl->redirect($this, "cancel"); + } + } + + $this->lng->loadLanguageModule("excv"); + + $ilTabs->setBackTarget( + $this->lng->txt("back"), + $this->ctrl->getLinkTarget($this, "cancel") + ); + + include_once "Modules/Exercise/classes/class.ilExerciseVerificationTableGUI.php"; + $table = new ilExerciseVerificationTableGUI($this, "create"); + $this->tpl->setContent($table->getHTML()); + } + + /** + * create new instance and save it + */ + public function save() + { + global $DIC; + + $ilUser = $this->user; + + $objectId = $_REQUEST["exc_id"]; + if ($objectId) { + $certificateVerificationFileService = new ilCertificateVerificationFileService( + $DIC->language(), + $DIC->database(), + $DIC->logger()->root(), + new ilCertificateVerificationClassMap() + ); + + $userCertificateRepository = new ilUserCertificateRepository(); + + $userCertificatePresentation = $userCertificateRepository->fetchActiveCertificateForPresentation( + (int) $ilUser->getId(), + (int) $objectId + ); + + try { + $newObj = $certificateVerificationFileService->createFile($userCertificatePresentation); + } catch (\Exception $exception) { + ilUtil::sendFailure($this->lng->txt('error_creating_certificate_pdf')); + return $this->create(); + } + + if ($newObj) { + $parent_id = $this->node_id; + $this->node_id = null; + $this->putObjectInTree($newObj, $parent_id); + + $this->afterSave($newObj); + } else { + ilUtil::sendFailure($this->lng->txt("msg_failed")); + } + } else { + ilUtil::sendFailure($this->lng->txt("select_one")); + } + $this->create(); + } + + public function deliver() + { + $file = $this->object->getFilePath(); + if ($file) { + ilUtil::deliverFile($file, $this->object->getTitle() . ".pdf"); + } + } + + /** + * Render content + * + * @param bool $a_return + * @param string $a_url + */ + public function render($a_return = false, $a_url = false) + { + $ilUser = $this->user; + $lng = $this->lng; + + if (!$a_return) { + $this->deliver(); + } else { + $tree = new ilWorkspaceTree($ilUser->getId()); + $wsp_id = $tree->lookupNodeId($this->object->getId()); + + $caption = $lng->txt("wsp_type_excv") . ' "' . $this->object->getTitle() . '"'; + + $valid = true; + if (!file_exists($this->object->getFilePath())) { + $valid = false; + $message = $lng->txt("url_not_found"); + } elseif (!$a_url) { + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; + $access_handler = new ilWorkspaceAccessHandler($tree); + if (!$access_handler->checkAccess("read", "", $wsp_id)) { + $valid = false; + $message = $lng->txt("permission_denied"); + } + } + + if ($valid) { + if (!$a_url) { + $a_url = $this->getAccessHandler()->getGotoLink($wsp_id, $this->object->getId()); + } + return ''; + } else { + return '
' . $caption . ' (' . $message . ')
'; + } + } + } + + public function downloadFromPortfolioPage(ilPortfolioPage $a_page) + { + include_once "Services/COPage/classes/class.ilPCVerification.php"; + if (ilPCVerification::isInPortfolioPage($a_page, $this->object->getType(), $this->object->getId())) { + $this->deliver(); + } + + include_once "Modules/Exercise/exceptions/class.ilExerciseException.php"; + throw new ilExerciseException($this->lng->txt('permission_denied')); + } + + public static function _goto($a_target) + { + $id = explode("_", $a_target); + + $_GET["baseClass"] = "ilsharedresourceGUI"; + $_GET["wsp_id"] = $id[0]; + include("ilias.php"); + exit; + } +} diff --git a/Modules/Exercise/classes/class.ilObjExerciseVerificationListGUI.php b/Modules/Exercise/classes/class.ilObjExerciseVerificationListGUI.php index 7afbdc3792ba4adc71158572cdfb4da871322bd6..acf727ba33cf834595a6a73e38fb2d9a351806ab 100644 --- a/Modules/Exercise/classes/class.ilObjExerciseVerificationListGUI.php +++ b/Modules/Exercise/classes/class.ilObjExerciseVerificationListGUI.php @@ -1,49 +1,46 @@ - -* $Id: class.ilObjFolderListGUI.php 26089 2010-10-20 08:08:05Z smeyer $ -* -* @extends ilObjectListGUI -*/ - -include_once "Services/Object/classes/class.ilObjectListGUI.php"; - -class ilObjExerciseVerificationListGUI extends ilObjectListGUI -{ - /** - * initialisation - */ - function init() - { - $this->delete_enabled = true; - $this->cut_enabled = true; - $this->copy_enabled = true; - $this->subscribe_enabled = false; - $this->link_enabled = false; - $this->info_screen_enabled = false; - $this->type = "excv"; - $this->gui_class_name = "ilobjexerciseverificationgui"; - - // general commands array - include_once('./Modules/Exercise/classes/class.ilObjExerciseVerificationAccess.php'); - $this->commands = ilObjExerciseVerificationAccess::_getCommands(); - } - - function getProperties() - { - $lng = $this->lng; - - return array( - array("alert" => false, "property" => $lng->txt("type"), - "value" => $lng->txt("wsp_list_excv")) - ); - } - -} - -?> \ No newline at end of file + +* $Id: class.ilObjFolderListGUI.php 26089 2010-10-20 08:08:05Z smeyer $ +* +* @extends ilObjectListGUI +*/ + +include_once "Services/Object/classes/class.ilObjectListGUI.php"; + +class ilObjExerciseVerificationListGUI extends ilObjectListGUI +{ + /** + * initialisation + */ + public function init() + { + $this->delete_enabled = true; + $this->cut_enabled = true; + $this->copy_enabled = true; + $this->subscribe_enabled = false; + $this->link_enabled = false; + $this->info_screen_enabled = false; + $this->type = "excv"; + $this->gui_class_name = "ilobjexerciseverificationgui"; + + // general commands array + include_once('./Modules/Exercise/classes/class.ilObjExerciseVerificationAccess.php'); + $this->commands = ilObjExerciseVerificationAccess::_getCommands(); + } + + public function getProperties() + { + $lng = $this->lng; + + return array( + array("alert" => false, "property" => $lng->txt("type"), + "value" => $lng->txt("wsp_list_excv")) + ); + } +} diff --git a/Modules/Exercise/classes/class.ilPublicSubmissionsTableGUI.php b/Modules/Exercise/classes/class.ilPublicSubmissionsTableGUI.php index fcd273d7005ad965703972ad2a0fe9e968659f0d..7f825564f4d559d496a235a9ff47c3a385512ee2 100644 --- a/Modules/Exercise/classes/class.ilPublicSubmissionsTableGUI.php +++ b/Modules/Exercise/classes/class.ilPublicSubmissionsTableGUI.php @@ -14,107 +14,106 @@ include_once "Modules/Exercise/classes/class.ilExSubmission.php"; */ class ilPublicSubmissionsTableGUI extends ilTable2GUI { - protected $ass; // [ilExAssignment] - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, ilExAssignment $a_ass) - { - global $DIC; + protected $ass; // [ilExAssignment] + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, ilExAssignment $a_ass) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->ass = $a_ass; - - include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setData($this->ass->getMemberListData()); - $this->setTitle($lng->txt("exc_assignment").": ".$this->ass->getTitle()); - $this->setTopCommands(true); - //$this->setLimit(9999); - - $this->addColumn($this->lng->txt("name"), "name"); - $this->addColumn($this->lng->txt("exc_submission"), ""); - - $this->setDefaultOrderField("name"); - $this->setDefaultOrderDirection("asc"); - - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.exc_public_submissions_row.html", "Modules/Exercise"); - //$this->disable("footer"); - $this->setEnableTitle(true); - } - - /** - * Fill table row - */ - protected function fillRow($member) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->ass = $a_ass; + + include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); + + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setData($this->ass->getMemberListData()); + $this->setTitle($lng->txt("exc_assignment") . ": " . $this->ass->getTitle()); + $this->setTopCommands(true); + //$this->setLimit(9999); + + $this->addColumn($this->lng->txt("name"), "name"); + $this->addColumn($this->lng->txt("exc_submission"), ""); + + $this->setDefaultOrderField("name"); + $this->setDefaultOrderDirection("asc"); + + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.exc_public_submissions_row.html", "Modules/Exercise"); + //$this->disable("footer"); + $this->setEnableTitle(true); + } + + /** + * Fill table row + */ + protected function fillRow($member) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; - include_once "./Services/Object/classes/class.ilObjectFactory.php"; - $member_id = $member["usr_id"]; - if(!($mem_obj = ilObjectFactory::getInstanceByObjId($member_id,false))) - { - return; - } + include_once "./Services/Object/classes/class.ilObjectFactory.php"; + $member_id = $member["usr_id"]; + if (!($mem_obj = ilObjectFactory::getInstanceByObjId($member_id, false))) { + return; + } - // name and login - $this->tpl->setVariable("TXT_NAME", - $member["name"]); - $this->tpl->setVariable("TXT_LOGIN", - "[".$member["login"]."]"); - - // image - $this->tpl->setVariable("USR_IMAGE", - $mem_obj->getPersonalPicturePath("xxsmall")); - $this->tpl->setVariable("USR_ALT", $lng->txt("personal_picture")); - - $sub = new ilExSubmission($this->ass, $member_id); + // name and login + $this->tpl->setVariable( + "TXT_NAME", + $member["name"] + ); + $this->tpl->setVariable( + "TXT_LOGIN", + "[" . $member["login"] . "]" + ); + + // image + $this->tpl->setVariable( + "USR_IMAGE", + $mem_obj->getPersonalPicturePath("xxsmall") + ); + $this->tpl->setVariable("USR_ALT", $lng->txt("personal_picture")); + + $sub = new ilExSubmission($this->ass, $member_id); - // submission: - // see if files have been resubmmited after solved - $last_sub = $sub->getLastSubmission(); - if ($last_sub) - { - $last_sub = ilDatePresentation::formatDate(new ilDateTime($last_sub,IL_CAL_DATETIME)); - } - else - { - $last_sub = "---"; - } + // submission: + // see if files have been resubmmited after solved + $last_sub = $sub->getLastSubmission(); + if ($last_sub) { + $last_sub = ilDatePresentation::formatDate(new ilDateTime($last_sub, IL_CAL_DATETIME)); + } else { + $last_sub = "---"; + } - // nr of submitted files - $sub_cnt = count($sub->getFiles()); - - $this->tpl->setVariable("TXT_SUBMITTED_FILES", $lng->txt("exc_files_returned")); - $this->tpl->setVariable("VAL_SUBMITTED_FILES", $sub_cnt); - - // download command - if ($sub_cnt > 0) - { - $ilCtrl->setParameterByClass("ilExSubmissionFileGUI", "member_id", $member_id); - $url = $ilCtrl->getLinkTargetByClass("ilExSubmissionFileGUI", "downloadReturned"); - $ilCtrl->setParameterByClass("ilExSubmissionFileGUI", "member_id", ""); - - // #15126 - include_once("./Services/UIComponent/Button/classes/class.ilLinkButton.php"); - $button = ilLinkButton::getInstance(); - $button->setCaption("exc_download_files"); - $button->setUrl($url); - $button->setOmitPreventDoubleSubmission(true); - $this->tpl->setVariable("BTN_DOWNLOAD", $button->render()); - } - - $this->tpl->parseCurrentBlock(); - } + // nr of submitted files + $sub_cnt = count($sub->getFiles()); + + $this->tpl->setVariable("TXT_SUBMITTED_FILES", $lng->txt("exc_files_returned")); + $this->tpl->setVariable("VAL_SUBMITTED_FILES", $sub_cnt); + + // download command + if ($sub_cnt > 0) { + $ilCtrl->setParameterByClass("ilExSubmissionFileGUI", "member_id", $member_id); + $url = $ilCtrl->getLinkTargetByClass("ilExSubmissionFileGUI", "downloadReturned"); + $ilCtrl->setParameterByClass("ilExSubmissionFileGUI", "member_id", ""); + + // #15126 + include_once("./Services/UIComponent/Button/classes/class.ilLinkButton.php"); + $button = ilLinkButton::getInstance(); + $button->setCaption("exc_download_files"); + $button->setUrl($url); + $button->setOmitPreventDoubleSubmission(true); + $this->tpl->setVariable("BTN_DOWNLOAD", $button->render()); + } + $this->tpl->parseCurrentBlock(); + } } -?> \ No newline at end of file diff --git a/Modules/Exercise/exceptions/class.ilExerciseException.php b/Modules/Exercise/exceptions/class.ilExerciseException.php index ea7f6a879eefb721bcaa54711d1cba50d2a6ef7b..6e5904107a0344966b6fe27c183829a70db079e5 100644 --- a/Modules/Exercise/exceptions/class.ilExerciseException.php +++ b/Modules/Exercise/exceptions/class.ilExerciseException.php @@ -1,27 +1,26 @@ , Roland Küstermann - * @version $Id$ - * + * @version $Id$ + * */ class ilExerciseException extends ilException { public static $ID_MISMATCH = 0; public static $ID_DEFLATE_METHOD_MISMATCH = 1; - /** - * Constructor - * - * @param string $a_message message - */ - public function __construct($a_message, $a_code = 0) - { - parent::__construct($a_message, $a_code); - } + /** + * Constructor + * + * @param string $a_message message + */ + public function __construct($a_message, $a_code = 0) + { + parent::__construct($a_message, $a_code); + } } -?> diff --git a/Modules/ExternalFeed/classes/class.ilExternalFeedDataSet.php b/Modules/ExternalFeed/classes/class.ilExternalFeedDataSet.php index 49b284f92ae165bcba2dc81025022899cc2ee650..7789446b99cecbf0aa0d6471ab40332f489a15d6 100644 --- a/Modules/ExternalFeed/classes/class.ilExternalFeedDataSet.php +++ b/Modules/ExternalFeed/classes/class.ilExternalFeedDataSet.php @@ -5,141 +5,129 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); /** * External feed data set class - * + * * @author Alex Killing * @version $Id$ * @ingroup ingroup ModulesExternalFeed */ class ilExternalFeedDataSet extends ilDataSet { - /** - * Get supported versions - * - * @param - * @return - */ - public function getSupportedVersions() - { - return array("4.1.0"); - } - - /** - * Get xml namespace - * - * @param - * @return - */ - function getXmlNamespace($a_entity, $a_schema_version) - { - return "http://www.ilias.de/xml/Modules/ExternalFeed/".$a_entity; - } - - /** - * Get field types for entity - * - * @param - * @return - */ - protected function getTypes($a_entity, $a_version) - { - if ($a_entity == "feed") - { - switch ($a_version) - { - case "4.1.0": - return array( - "Id" => "integer", - "Title" => "text", - "Url" => "text"); - } - } + /** + * Get supported versions + * + * @param + * @return + */ + public function getSupportedVersions() + { + return array("4.1.0"); + } + + /** + * Get xml namespace + * + * @param + * @return + */ + public function getXmlNamespace($a_entity, $a_schema_version) + { + return "http://www.ilias.de/xml/Modules/ExternalFeed/" . $a_entity; + } + + /** + * Get field types for entity + * + * @param + * @return + */ + protected function getTypes($a_entity, $a_version) + { + if ($a_entity == "feed") { + switch ($a_version) { + case "4.1.0": + return array( + "Id" => "integer", + "Title" => "text", + "Url" => "text"); + } + } + } - } + /** + * Read data + * + * @param + * @return + */ + public function readData($a_entity, $a_version, $a_ids) + { + $ilDB = $this->db; - /** - * Read data - * - * @param - * @return - */ - function readData($a_entity, $a_version, $a_ids) - { - $ilDB = $this->db; + if (!is_array($a_ids)) { + $a_ids = array($a_ids); + } + + if ($a_entity == "feed") { + switch ($a_version) { + case "4.1.0": + $this->getDirectDataFromQuery("SELECT obj_id id, title, description url " . + " FROM object_data " . + "WHERE " . + $ilDB->in("obj_id", $a_ids, false, "integer")); + break; + } + } + } + + /** + * Determine the dependent sets of data + */ + protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) + { + return false; + } + + + /** + * Import record + * + * @param + * @return + */ + public function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) + { + //echo $a_entity; + //var_dump($a_rec); - if (!is_array($a_ids)) - { - $a_ids = array($a_ids); - } - - if ($a_entity == "feed") - { - switch ($a_version) - { - case "4.1.0": - $this->getDirectDataFromQuery("SELECT obj_id id, title, description url ". - " FROM object_data ". - "WHERE ". - $ilDB->in("obj_id", $a_ids, false, "integer")); - break; - } - } + switch ($a_entity) { + case "feed": - } - - /** - * Determine the dependent sets of data - */ - protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) - { - return false; - } - - - /** - * Import record - * - * @param - * @return - */ - function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) - { -//echo $a_entity; -//var_dump($a_rec); + include_once("./Modules/ExternalFeed/classes/class.ilObjExternalFeed.php"); - switch ($a_entity) - { - case "feed": + if ($new_id = $a_mapping->getMapping('Services/Container', 'objs', $a_rec['Id'])) { + $newObj = ilObjectFactory::getInstanceByObjId($new_id, false); + } else { + $newObj = new ilObjExternalFeed(); + $newObj->setType("feed"); + $newObj->create(true); + } - include_once("./Modules/ExternalFeed/classes/class.ilObjExternalFeed.php"); + $newObj->setTitle($a_rec["Title"]); + $newObj->setDescription($a_rec["Url"]); + $newObj->update(); + $this->current_obj = $newObj; + $a_mapping->addMapping("Modules/ExternalFeed", "feed", $a_rec["Id"], $newObj->getId()); - if($new_id = $a_mapping->getMapping('Services/Container','objs',$a_rec['Id'])) - { - $newObj = ilObjectFactory::getInstanceByObjId($new_id,false); - } - else - { - $newObj = new ilObjExternalFeed(); - $newObj->setType("feed"); - $newObj->create(true); - } + // create the feed block + include_once("./Services/Block/classes/class.ilExternalFeedBlock.php"); + $fb = new ilExternalFeedBlock(); + $fb->setTitle($a_rec["Title"]); + $fb->setFeedUrl($a_rec["Url"]); + $fb->setContextObjId($newObj->getId()); + $fb->setContextObjType("feed"); + $fb->create(); - $newObj->setTitle($a_rec["Title"]); - $newObj->setDescription($a_rec["Url"]); - $newObj->update(); - $this->current_obj = $newObj; - $a_mapping->addMapping("Modules/ExternalFeed", "feed", $a_rec["Id"], $newObj->getId()); - - // create the feed block - include_once("./Services/Block/classes/class.ilExternalFeedBlock.php"); - $fb = new ilExternalFeedBlock(); - $fb->setTitle($a_rec["Title"]); - $fb->setFeedUrl($a_rec["Url"]); - $fb->setContextObjId($newObj->getId()); - $fb->setContextObjType("feed"); - $fb->create(); - - break; - } - } + break; + } + } } -?> \ No newline at end of file diff --git a/Modules/ExternalFeed/classes/class.ilExternalFeedExporter.php b/Modules/ExternalFeed/classes/class.ilExternalFeedExporter.php index ff73896f1679f5c1fdb93af606ffd2fd68d5e8ac..829ab4401dc7e91223d320d69546b8d87982e7e4 100644 --- a/Modules/ExternalFeed/classes/class.ilExternalFeedExporter.php +++ b/Modules/ExternalFeed/classes/class.ilExternalFeedExporter.php @@ -12,52 +12,49 @@ include_once("./Services/Export/classes/class.ilXmlExporter.php"); */ class ilExternalFeedExporter extends ilXmlExporter { - private $ds; - - /** - * Initialisation - */ - function init() - { - include_once("./Modules/ExternalFeed/classes/class.ilExternalFeedDataSet.php"); - $this->ds = new ilExternalFeedDataSet(); - $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); - $this->ds->setDSPrefix("ds"); - } - - - /** - * Get xml representation - * - * @param string entity - * @param string target release - * @param string id - * @return string xml string - */ - public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) - { - return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); - } - - /** - * Returns schema versions that the component can export to. - * ILIAS chooses the first one, that has min/max constraints which - * fit to the target release. Please put the newest on top. - * - * @return - */ - function getValidSchemaVersions($a_entity) - { - return array ( - "4.1.0" => array( - "namespace" => "http://www.ilias.de/Modules/ExternalFeed/feed/4_1", - "xsd_file" => "ilias_feed_4_1.xsd", - "uses_dataset" => true, - "min" => "4.1.0", - "max" => "") - ); - } - + private $ds; + + /** + * Initialisation + */ + public function init() + { + include_once("./Modules/ExternalFeed/classes/class.ilExternalFeedDataSet.php"); + $this->ds = new ilExternalFeedDataSet(); + $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); + $this->ds->setDSPrefix("ds"); + } + + + /** + * Get xml representation + * + * @param string entity + * @param string target release + * @param string id + * @return string xml string + */ + public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) + { + return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); + } + + /** + * Returns schema versions that the component can export to. + * ILIAS chooses the first one, that has min/max constraints which + * fit to the target release. Please put the newest on top. + * + * @return + */ + public function getValidSchemaVersions($a_entity) + { + return array( + "4.1.0" => array( + "namespace" => "http://www.ilias.de/Modules/ExternalFeed/feed/4_1", + "xsd_file" => "ilias_feed_4_1.xsd", + "uses_dataset" => true, + "min" => "4.1.0", + "max" => "") + ); + } } - -?> \ No newline at end of file diff --git a/Modules/ExternalFeed/classes/class.ilExternalFeedHandlerGUI.php b/Modules/ExternalFeed/classes/class.ilExternalFeedHandlerGUI.php index 9f83400733a944b00174698ae8a9b5d91302f7ce..c61a387922873f49986a2b50a0d0c86b25a52752 100755 --- a/Modules/ExternalFeed/classes/class.ilExternalFeedHandlerGUI.php +++ b/Modules/ExternalFeed/classes/class.ilExternalFeedHandlerGUI.php @@ -1,24 +1,24 @@ lng = $DIC->language(); - $this->access = $DIC->access(); - $this->tpl = $DIC["tpl"]; - $ilCtrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->tpl = $DIC["tpl"]; + $ilCtrl = $DIC->ctrl(); - // initialisation stuff - $this->ctrl = $ilCtrl; - - } - - /** - * execute command - */ - function executeCommand() - { - $lng = $this->lng; - $ilAccess = $this->access; - $tpl = $this->tpl; - - $cmd = $this->ctrl->getCmd(); - $next_class = $this->ctrl->getNextClass($this); - if ($next_class == "") - { - $this->ctrl->setCmdClass("ilobjexternalfeedgui"); - $next_class = $this->ctrl->getNextClass($this); - } + // initialisation stuff + $this->ctrl = $ilCtrl; + } + + /** + * execute command + */ + public function executeCommand() + { + $lng = $this->lng; + $ilAccess = $this->access; + $tpl = $this->tpl; + + $cmd = $this->ctrl->getCmd(); + $next_class = $this->ctrl->getNextClass($this); + if ($next_class == "") { + $this->ctrl->setCmdClass("ilobjexternalfeedgui"); + $next_class = $this->ctrl->getNextClass($this); + } - switch ($next_class) - { - case 'ilobjexternalfeedgui': - require_once "./Modules/ExternalFeed/classes/class.ilObjExternalFeedGUI.php"; - $ef_gui = new ilObjExternalFeedGUI("", (int) $_GET["ref_id"], true, false); - $this->ctrl->forwardCommand($mc_gui); - break; - } - - $tpl->show(); - } + switch ($next_class) { + case 'ilobjexternalfeedgui': + require_once "./Modules/ExternalFeed/classes/class.ilObjExternalFeedGUI.php"; + $ef_gui = new ilObjExternalFeedGUI("", (int) $_GET["ref_id"], true, false); + $this->ctrl->forwardCommand($mc_gui); + break; + } + $tpl->show(); + } } diff --git a/Modules/ExternalFeed/classes/class.ilExternalFeedImporter.php b/Modules/ExternalFeed/classes/class.ilExternalFeedImporter.php index 666727a36fcb4fdf6bdddd7f5c3b345ec28c11df..88cd287cfdf0bedac69d7518feb27a6905e06ca3 100644 --- a/Modules/ExternalFeed/classes/class.ilExternalFeedImporter.php +++ b/Modules/ExternalFeed/classes/class.ilExternalFeedImporter.php @@ -13,29 +13,32 @@ include_once("./Services/Export/classes/class.ilXmlImporter.php"); class ilExternalFeedImporter extends ilXmlImporter { - /** - * Initialisation - */ - function init() - { - include_once("./Modules/ExternalFeed/classes/class.ilExternalFeedDataSet.php"); - $this->ds = new ilExternalFeedDataSet(); - $this->ds->setDSPrefix("ds"); - } + /** + * Initialisation + */ + public function init() + { + include_once("./Modules/ExternalFeed/classes/class.ilExternalFeedDataSet.php"); + $this->ds = new ilExternalFeedDataSet(); + $this->ds->setDSPrefix("ds"); + } - /** - * Import XML - * - * @param - * @return - */ - function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) - { - include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); - $parser = new ilDataSetImportParser($a_entity, $this->getSchemaVersion(), - $a_xml, $this->ds, $a_mapping); - } + /** + * Import XML + * + * @param + * @return + */ + public function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) + { + include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); + $parser = new ilDataSetImportParser( + $a_entity, + $this->getSchemaVersion(), + $a_xml, + $this->ds, + $a_mapping + ); + } } - -?> \ No newline at end of file diff --git a/Modules/ExternalFeed/classes/class.ilObjExternalFeed.php b/Modules/ExternalFeed/classes/class.ilObjExternalFeed.php index d56e3af70edb71df6f393ee4fb4beee3a473f67f..f61f0e0821132605c5e7c94710e2a22c9b116cfc 100755 --- a/Modules/ExternalFeed/classes/class.ilObjExternalFeed.php +++ b/Modules/ExternalFeed/classes/class.ilObjExternalFeed.php @@ -5,141 +5,132 @@ require_once "./Services/Object/classes/class.ilObject.php"; /** * Class ilObjExternalFeed -* -* @author Alex Killing +* +* @author Alex Killing * @version $Id$ * */ class ilObjExternalFeed extends ilObject { - /** - * Constructor - * @access public - * @param integer reference_id or object_id - * @param boolean treat the id as reference_id (true) or object_id (false) - */ - function __construct($a_id = 0,$a_call_by_reference = true) - { - global $DIC; + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + global $DIC; - $this->db = $DIC->database(); - $this->log = $DIC["ilLog"]; - $this->type = "feed"; - parent::__construct($a_id,$a_call_by_reference); - } + $this->db = $DIC->database(); + $this->log = $DIC["ilLog"]; + $this->type = "feed"; + parent::__construct($a_id, $a_call_by_reference); + } - /** - * update object data - * - * @access public - * @return boolean - */ - function update() - { - if (!parent::update()) - { - return false; - } + /** + * update object data + * + * @access public + * @return boolean + */ + public function update() + { + if (!parent::update()) { + return false; + } - // put here object specific stuff + // put here object specific stuff - return true; - } + return true; + } - /** - * Clone - * - * @access public - * @param int target id - * @param int copy id - * - */ - public function cloneObject($a_target_id,$a_copy_id = 0, $a_omit_tree = false) - { - $ilDB = $this->db; - $ilLog = $this->log; - - $new_obj = parent::cloneObject($a_target_id,$a_copy_id, $a_omit_tree); - $fb = $this->getFeedBlock(); - - include_once("./Services/Block/classes/class.ilExternalFeedBlock.php"); - $new_feed_block = new ilExternalFeedBlock(); - $new_feed_block->setContextObjId($new_obj->getId()); - $new_feed_block->setContextObjType("feed"); + /** + * Clone + * + * @access public + * @param int target id + * @param int copy id + * + */ + public function cloneObject($a_target_id, $a_copy_id = 0, $a_omit_tree = false) + { + $ilDB = $this->db; + $ilLog = $this->log; + + $new_obj = parent::cloneObject($a_target_id, $a_copy_id, $a_omit_tree); + $fb = $this->getFeedBlock(); + + include_once("./Services/Block/classes/class.ilExternalFeedBlock.php"); + $new_feed_block = new ilExternalFeedBlock(); + $new_feed_block->setContextObjId($new_obj->getId()); + $new_feed_block->setContextObjType("feed"); - if (is_object($fb)) - { - $new_feed_block->setFeedUrl($fb->getFeedUrl()); - $new_feed_block->setTitle($fb->getTitle()); - } - $new_feed_block->create(); + if (is_object($fb)) { + $new_feed_block->setFeedUrl($fb->getFeedUrl()); + $new_feed_block->setTitle($fb->getTitle()); + } + $new_feed_block->create(); - return $new_obj; - } + return $new_obj; + } - /** - * delete object and all related data - * - * @access public - * @return boolean true if all object data were removed; false if only a references were removed - */ - function delete() - { - // always call parent delete function first!! - if (!parent::delete()) - { - return false; - } - - //put here your module specific stuff - - // delete feed block - include_once("./Services/Block/classes/class.ilCustomBlock.php"); - $costum_block = new ilCustomBlock(); - $costum_block->setContextObjId($this->getId()); - $costum_block->setContextObjType($this->getType()); - $c_blocks = $costum_block->queryBlocksForContext(); - - include_once("./Services/Block/classes/class.ilExternalFeedBlock.php"); - foreach($c_blocks as $c_block) // should be usually only one - { - if ($c_block["type"] == "feed") - { - $fb = new ilExternalFeedBlock($c_block["id"]); - $fb->delete(); - include_once("./Services/Block/classes/class.ilBlockSetting.php"); - ilBlockSetting::_deleteSettingsOfBlock($c_block["id"], "feed"); - } - } + /** + * delete object and all related data + * + * @access public + * @return boolean true if all object data were removed; false if only a references were removed + */ + public function delete() + { + // always call parent delete function first!! + if (!parent::delete()) { + return false; + } + + //put here your module specific stuff + + // delete feed block + include_once("./Services/Block/classes/class.ilCustomBlock.php"); + $costum_block = new ilCustomBlock(); + $costum_block->setContextObjId($this->getId()); + $costum_block->setContextObjType($this->getType()); + $c_blocks = $costum_block->queryBlocksForContext(); + + include_once("./Services/Block/classes/class.ilExternalFeedBlock.php"); + foreach ($c_blocks as $c_block) { // should be usually only one + if ($c_block["type"] == "feed") { + $fb = new ilExternalFeedBlock($c_block["id"]); + $fb->delete(); + include_once("./Services/Block/classes/class.ilBlockSetting.php"); + ilBlockSetting::_deleteSettingsOfBlock($c_block["id"], "feed"); + } + } - //ilBlockSetting::_lookupSide($type, $user_id, $c_block["id"]); - - return true; - } + //ilBlockSetting::_lookupSide($type, $user_id, $c_block["id"]); + + return true; + } - function getFeedBlock() - { - $ilLog = $this->log; - - // delete feed block - include_once("./Services/Block/classes/class.ilCustomBlock.php"); - $costum_block = new ilCustomBlock(); - $costum_block->setContextObjId($this->getId()); - $costum_block->setContextObjType($this->getType()); - $c_blocks = $costum_block->queryBlocksForContext(); - - include_once("./Services/Block/classes/class.ilExternalFeedBlock.php"); - foreach($c_blocks as $c_block) // should be usually only one - { - if ($c_block["type"] == "feed") - { - $fb = new ilExternalFeedBlock($c_block["id"]); - return $fb; - } - } + public function getFeedBlock() + { + $ilLog = $this->log; + + // delete feed block + include_once("./Services/Block/classes/class.ilCustomBlock.php"); + $costum_block = new ilCustomBlock(); + $costum_block->setContextObjId($this->getId()); + $costum_block->setContextObjType($this->getType()); + $c_blocks = $costum_block->queryBlocksForContext(); + + include_once("./Services/Block/classes/class.ilExternalFeedBlock.php"); + foreach ($c_blocks as $c_block) { // should be usually only one + if ($c_block["type"] == "feed") { + $fb = new ilExternalFeedBlock($c_block["id"]); + return $fb; + } + } - return false; - } - + return false; + } } // END class.ilObjExternalFeed -?> diff --git a/Modules/ExternalFeed/classes/class.ilObjExternalFeedAccess.php b/Modules/ExternalFeed/classes/class.ilObjExternalFeedAccess.php index 617618c3de00d170cdc86b980997ed79815e140b..50ac5e789f92d6ac8cc683a9cfce01a0eafad29d 100755 --- a/Modules/ExternalFeed/classes/class.ilObjExternalFeedAccess.php +++ b/Modules/ExternalFeed/classes/class.ilObjExternalFeedAccess.php @@ -17,53 +17,48 @@ include_once("./Services/Object/classes/class.ilObjectAccess.php"); class ilObjExternalFeedAccess extends ilObjectAccess { - /** - * 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" => "write", "cmd" => "edit", "lang_var" => "settings") - ); - - 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" => "write", "cmd" => "edit", "lang_var" => "settings") + ); + + return $commands; + } + + + /** + * check whether goto script will succeed + */ + public static function _checkGoto($a_target) + { + global $DIC; - $ilAccess = $DIC->access(); - - // #14870 - used for redirect after copy - - $t_arr = explode("_", $a_target); + $ilAccess = $DIC->access(); + + // #14870 - used for redirect after copy + + $t_arr = explode("_", $a_target); - if ($t_arr[0] != "feed" || ((int) $t_arr[1]) <= 0) - { - return false; - } + if ($t_arr[0] != "feed" || ((int) $t_arr[1]) <= 0) { + return false; + } - if ($ilAccess->checkAccess("read", "", $t_arr[1])) - { - return true; - } - return false; - } + if ($ilAccess->checkAccess("read", "", $t_arr[1])) { + return true; + } + return false; + } } - -?> \ No newline at end of file diff --git a/Modules/ExternalFeed/classes/class.ilObjExternalFeedGUI.php b/Modules/ExternalFeed/classes/class.ilObjExternalFeedGUI.php index 014ce0278f7e2d26a73cd15bccaaa1639e5f2409..88094705064203afe24853f0b0e9ddd6ded8d3b0 100755 --- a/Modules/ExternalFeed/classes/class.ilObjExternalFeedGUI.php +++ b/Modules/ExternalFeed/classes/class.ilObjExternalFeedGUI.php @@ -6,242 +6,242 @@ require_once "./Services/Object/classes/class.ilObjectGUI.php"; /** * Class ilObjExternalFeedGUI * -* @author Alex Killing +* @author Alex Killing * @version $Id$ -* +* * @ilCtrl_Calls ilObjExternalFeedGUI: ilExternalFeedBlockGUI, ilPermissionGUI, ilExportGUI * @ilCtrl_IsCalledBy ilObjExternalFeedGUI: ilRepositoryGUI, ilAdministrationGUI */ class ilObjExternalFeedGUI extends ilObjectGUI { - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilHelpGUI - */ - protected $help; - - /** - * Constructor - * @access public - */ - function __construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output = true) - { - global $DIC; - - $this->tpl = $DIC["tpl"]; - $this->tabs = $DIC->tabs(); - $this->ctrl = $DIC->ctrl(); - $this->tree = $DIC->repositoryTree(); - $this->access = $DIC->access(); - $this->lng = $DIC->language(); - $this->help = $DIC["ilHelp"]; - $this->type = "feed"; - parent::__construct($a_data,$a_id,$a_call_by_reference,$a_prepare_output); - } - - - function executeCommand() - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - $next_class = $this->ctrl->getNextClass($this); - - switch($next_class) - { - case 'ilpermissiongui': - $this->prepareOutput(); - $ilTabs->activateTab("id_permissions"); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $ret = $this->ctrl->forwardCommand($perm_gui); - break; - - case "ilexternalfeedblockgui": - $this->prepareOutput(); - $ilTabs->activateTab("id_settings"); - include_once("./Services/Block/classes/class.ilExternalFeedBlockGUI.php"); - $fb_gui = new ilExternalFeedBlockGUI(); - $fb_gui->setGuiObject($this); - if (is_object($this->object)) - { - $fb_gui->setRefId($this->object->getRefId()); - } - $ret = $this->ctrl->forwardCommand($fb_gui); - $tpl->setContent($ret); - 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"); - $ret = $this->ctrl->forwardCommand($exp_gui); + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * Constructor + * @access public + */ + public function __construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output = true) + { + global $DIC; + + $this->tpl = $DIC["tpl"]; + $this->tabs = $DIC->tabs(); + $this->ctrl = $DIC->ctrl(); + $this->tree = $DIC->repositoryTree(); + $this->access = $DIC->access(); + $this->lng = $DIC->language(); + $this->help = $DIC["ilHelp"]; + $this->type = "feed"; + parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); + } + + + public function executeCommand() + { + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + $next_class = $this->ctrl->getNextClass($this); + + switch ($next_class) { + case 'ilpermissiongui': + $this->prepareOutput(); + $ilTabs->activateTab("id_permissions"); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $ret = $this->ctrl->forwardCommand($perm_gui); + break; + + case "ilexternalfeedblockgui": + $this->prepareOutput(); + $ilTabs->activateTab("id_settings"); + include_once("./Services/Block/classes/class.ilExternalFeedBlockGUI.php"); + $fb_gui = new ilExternalFeedBlockGUI(); + $fb_gui->setGuiObject($this); + if (is_object($this->object)) { + $fb_gui->setRefId($this->object->getRefId()); + } + $ret = $this->ctrl->forwardCommand($fb_gui); + $tpl->setContent($ret); + 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"); + $ret = $this->ctrl->forwardCommand($exp_gui); // $this->tpl->show(); - break; - - default: - $cmd = $this->ctrl->getCmd("view"); - if ($cmd != "create") - { - $this->prepareOutput(); - } - $cmd .= "Object"; - $this->$cmd(); - break; - } - return true; - } - - function createObject() - { - $ilCtrl = $this->ctrl; - $ilCtrl->setCmdClass("ilexternalfeedblockgui"); - $ilCtrl->setCmd("create"); - return $this->executeCommand(); - } - - /** - * save object - * @access public - */ - function save($a_feed_block) - { - // create and insert forum in objecttree - $_REQUEST["new_type"] = "feed"; - $_POST["title"] = $a_feed_block->getTitle(); - $_POST["desc"] = $a_feed_block->getFeedUrl(); - parent::saveObject($a_feed_block); - } - - function afterSave(ilObject $a_new_object, $a_feed_block = null) - { - if ($a_feed_block != null) - { - // saveObject() parameters are sent as array - $a_feed_block = $a_feed_block[0]; - - $a_feed_block->setContextObjId($a_new_object->getId()); - $a_feed_block->setContextObjType("feed"); - } - } - - /** - * Exit save. - * - */ - public function exitSave() - { - $ilCtrl = $this->ctrl; - - // always send a message - ilUtil::sendSuccess($this->lng->txt("object_added"), true); - $this->ctrl->returnToParent($this); - } - - /** - * update object - * @access public - */ - function update($a_feed_block) - { - $_POST["title"] = $a_feed_block->getTitle(); - $_POST["desc"] = $a_feed_block->getFeedUrl(); - parent::updateObject(); - } - - /** - * Cancel update. - * - */ - public function cancelUpdate() - { - $tree = $this->tree; - - $par = $tree->getParentId($_GET["ref_id"]); - $_GET["ref_id"] = $par; - $this->redirectToRefId($par); - } - - /** - * After update - * - */ - public function afterUpdate() - { - $tree = $this->tree; - - $par = $tree->getParentId($_GET["ref_id"]); - $_GET["ref_id"] = $par; - $this->redirectToRefId($par); - } - - /** - * get tabs - * @access public - */ - function setTabs() - { - $ilAccess = $this->access; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - $lng = $this->lng; - $ilHelp = $this->help; - - if (in_array($ilCtrl->getCmd(), array("create", "saveFeedBlock"))) - { - return; - } - $ilHelp->setScreenIdComponent("feed"); - - $ilCtrl->setParameterByClass("ilexternalfeedblockgui", "external_feed_block_id", - $_GET["external_feed_block_id"]); - $ilCtrl->saveParameter($this, "external_feed_block_id"); - - if ($ilAccess->checkAccess('write', '', $this->object->getRefId())) - { - $ilTabs->addTab("id_settings", - $lng->txt("settings"), - $this->ctrl->getLinkTargetByClass("ilexternalfeedblockgui", "editFeedBlock")); - } - - // export - if ($ilAccess->checkAccess("write", "", $this->object->getRefId()) && DEVMODE == 1) - { - $ilTabs->addTab("export", - $lng->txt("export"), - $this->ctrl->getLinkTargetByClass("ilexportgui", "")); - } - - - if($ilAccess->checkAccess('edit_permission', '', $this->object->getRefId())) - { - $ilTabs->addTab("id_permissions", - $lng->txt("perm_settings"), - $this->ctrl->getLinkTargetByClass("ilpermissiongui", "perm")); - } - } - - public static function _goto($a_target) - { - global $DIC; - - $tree = $DIC->repositoryTree(); - - $id = explode("_", $a_target); - $ref_id = $id[0]; - - // is sideblock: so show parent instead - $container_id = $tree->getParentId($ref_id); - - // #14870 - include_once "Services/Link/classes/class.ilLink.php"; - ilUtil::redirect(ilLink::_getLink($container_id)); - } + break; + + default: + $cmd = $this->ctrl->getCmd("view"); + if ($cmd != "create") { + $this->prepareOutput(); + } + $cmd .= "Object"; + $this->$cmd(); + break; + } + return true; + } + + public function createObject() + { + $ilCtrl = $this->ctrl; + $ilCtrl->setCmdClass("ilexternalfeedblockgui"); + $ilCtrl->setCmd("create"); + return $this->executeCommand(); + } + + /** + * save object + * @access public + */ + public function save($a_feed_block) + { + // create and insert forum in objecttree + $_REQUEST["new_type"] = "feed"; + $_POST["title"] = $a_feed_block->getTitle(); + $_POST["desc"] = $a_feed_block->getFeedUrl(); + parent::saveObject($a_feed_block); + } + + public function afterSave(ilObject $a_new_object, $a_feed_block = null) + { + if ($a_feed_block != null) { + // saveObject() parameters are sent as array + $a_feed_block = $a_feed_block[0]; + + $a_feed_block->setContextObjId($a_new_object->getId()); + $a_feed_block->setContextObjType("feed"); + } + } + + /** + * Exit save. + * + */ + public function exitSave() + { + $ilCtrl = $this->ctrl; + + // always send a message + ilUtil::sendSuccess($this->lng->txt("object_added"), true); + $this->ctrl->returnToParent($this); + } + + /** + * update object + * @access public + */ + public function update($a_feed_block) + { + $_POST["title"] = $a_feed_block->getTitle(); + $_POST["desc"] = $a_feed_block->getFeedUrl(); + parent::updateObject(); + } + + /** + * Cancel update. + * + */ + public function cancelUpdate() + { + $tree = $this->tree; + + $par = $tree->getParentId($_GET["ref_id"]); + $_GET["ref_id"] = $par; + $this->redirectToRefId($par); + } + + /** + * After update + * + */ + public function afterUpdate() + { + $tree = $this->tree; + + $par = $tree->getParentId($_GET["ref_id"]); + $_GET["ref_id"] = $par; + $this->redirectToRefId($par); + } + + /** + * get tabs + * @access public + */ + public function setTabs() + { + $ilAccess = $this->access; + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + $lng = $this->lng; + $ilHelp = $this->help; + + if (in_array($ilCtrl->getCmd(), array("create", "saveFeedBlock"))) { + return; + } + $ilHelp->setScreenIdComponent("feed"); + + $ilCtrl->setParameterByClass( + "ilexternalfeedblockgui", + "external_feed_block_id", + $_GET["external_feed_block_id"] + ); + $ilCtrl->saveParameter($this, "external_feed_block_id"); + + if ($ilAccess->checkAccess('write', '', $this->object->getRefId())) { + $ilTabs->addTab( + "id_settings", + $lng->txt("settings"), + $this->ctrl->getLinkTargetByClass("ilexternalfeedblockgui", "editFeedBlock") + ); + } + + // export + if ($ilAccess->checkAccess("write", "", $this->object->getRefId()) && DEVMODE == 1) { + $ilTabs->addTab( + "export", + $lng->txt("export"), + $this->ctrl->getLinkTargetByClass("ilexportgui", "") + ); + } + + + if ($ilAccess->checkAccess('edit_permission', '', $this->object->getRefId())) { + $ilTabs->addTab( + "id_permissions", + $lng->txt("perm_settings"), + $this->ctrl->getLinkTargetByClass("ilpermissiongui", "perm") + ); + } + } + + public static function _goto($a_target) + { + global $DIC; + + $tree = $DIC->repositoryTree(); + + $id = explode("_", $a_target); + $ref_id = $id[0]; + + // is sideblock: so show parent instead + $container_id = $tree->getParentId($ref_id); + + // #14870 + include_once "Services/Link/classes/class.ilLink.php"; + ilUtil::redirect(ilLink::_getLink($container_id)); + } } // END class.ilObjExternalFeed -?> \ No newline at end of file diff --git a/Modules/ExternalFeed/classes/class.ilObjExternalFeedListGUI.php b/Modules/ExternalFeed/classes/class.ilObjExternalFeedListGUI.php index 111a980c8923db5b260a48620ef23e73a2fe14e1..04bd98b41e66c06d6ffb7440c72afd63085fb221 100755 --- a/Modules/ExternalFeed/classes/class.ilObjExternalFeedListGUI.php +++ b/Modules/ExternalFeed/classes/class.ilObjExternalFeedListGUI.php @@ -1,24 +1,24 @@ copy_enabled = false; - $this->delete_enabled = true; - $this->cut_enabled = true; - $this->subscribe_enabled = true; - $this->link_enabled = true; - $this->info_screen_enabled = true; - $this->type = "mcst"; - $this->gui_class_name = "ilobjexternalfeedgui"; - - // general commands array - include_once('./Modules/ExternalFeed/classes/class.ilObjExternalFeedAccess.php'); - $this->commands = ilObjExternalFeedAccess::_getCommands(); - } - - - /** - * inititialize new item - * - * @param int $a_ref_id reference id - * @param int $a_obj_id object id - * @param string $a_title title - * @param string $a_description description - */ - function initItem($a_ref_id, $a_obj_id, $a_title = "", $a_description = "") - { - parent::initItem($a_ref_id, $a_obj_id, $a_title, $a_description); - } - - - /** - * Get command target frame - * - * @param string $a_cmd command - * - * @return string command target frame - */ - function getCommandFrame($a_cmd) - { - switch($a_cmd) - { - default: - $frame = ilFrameTargetInfo::_getFrame("MainContent"); - break; - } - - return $frame; - } - - - - /** - * Get item properties - * - * @return array array of property arrays: - * "alert" (boolean) => display as an alert property (usually in red) - * "property" (string) => property name - * "value" (string) => property value - */ - function getProperties() - { - $lng = $this->lng; - $ilUser = $this->user; - - $props = array(); - //$props[] = array( - // "property" => $this->lng->txt("exc_time_to_send"), - // "value" => ilObjExerciseAccess::_lookupRemainingWorkingTimeString($this->obj_id) - //); - - return $props; - } - - - /** - * Get command link url. - * - * @param int $a_ref_id reference id - * @param string $a_cmd command - * - */ - function getCommandLink($a_cmd) - { - // separate method for this line - $cmd_link = "ilias.php?baseClass=ilExternalFeedHandlerGUI&ref_id=".$this->ref_id."&cmd=$a_cmd"; - - return $cmd_link; - } - - /** - * Returns whether current item is a block in a side column or not - */ - function isSideBlock() - { - return true; - } - - + /** + * initialisation + */ + public function init() + { + $this->copy_enabled = false; + $this->delete_enabled = true; + $this->cut_enabled = true; + $this->subscribe_enabled = true; + $this->link_enabled = true; + $this->info_screen_enabled = true; + $this->type = "mcst"; + $this->gui_class_name = "ilobjexternalfeedgui"; + + // general commands array + include_once('./Modules/ExternalFeed/classes/class.ilObjExternalFeedAccess.php'); + $this->commands = ilObjExternalFeedAccess::_getCommands(); + } + + + /** + * inititialize new item + * + * @param int $a_ref_id reference id + * @param int $a_obj_id object id + * @param string $a_title title + * @param string $a_description description + */ + public function initItem($a_ref_id, $a_obj_id, $a_title = "", $a_description = "") + { + parent::initItem($a_ref_id, $a_obj_id, $a_title, $a_description); + } + + + /** + * Get command target frame + * + * @param string $a_cmd command + * + * @return string command target frame + */ + public function getCommandFrame($a_cmd) + { + switch ($a_cmd) { + default: + $frame = ilFrameTargetInfo::_getFrame("MainContent"); + break; + } + + return $frame; + } + + + + /** + * Get item properties + * + * @return array array of property arrays: + * "alert" (boolean) => display as an alert property (usually in red) + * "property" (string) => property name + * "value" (string) => property value + */ + public function getProperties() + { + $lng = $this->lng; + $ilUser = $this->user; + + $props = array(); + //$props[] = array( + // "property" => $this->lng->txt("exc_time_to_send"), + // "value" => ilObjExerciseAccess::_lookupRemainingWorkingTimeString($this->obj_id) + //); + + return $props; + } + + + /** + * Get command link url. + * + * @param int $a_ref_id reference id + * @param string $a_cmd command + * + */ + public function getCommandLink($a_cmd) + { + // separate method for this line + $cmd_link = "ilias.php?baseClass=ilExternalFeedHandlerGUI&ref_id=" . $this->ref_id . "&cmd=$a_cmd"; + + return $cmd_link; + } + + /** + * Returns whether current item is a block in a side column or not + */ + public function isSideBlock() + { + return true; + } } // END class.ilObjExternalFeedListGUI -?> diff --git a/Modules/File/classes/class.ilObjFileAccessSettingsGUI.php b/Modules/File/classes/class.ilObjFileAccessSettingsGUI.php index fa621c376604c2ff273fe8a1f013cdb2531d3ba9..1eba174cebe522b520e3b7c97283c2057eb3e3c5 100644 --- a/Modules/File/classes/class.ilObjFileAccessSettingsGUI.php +++ b/Modules/File/classes/class.ilObjFileAccessSettingsGUI.php @@ -630,6 +630,7 @@ class ilObjFileAccessSettingsGUI extends ilObjectGUI // create table require_once './Services/Table/classes/class.ilTableGUI.php'; $tbl = new ilTableGUI(0, false); + $tbl->setTitle(''); // title & header columns $header_vars = array('login', 'firstname', 'lastname', 'email', 'access_until', 'last_login', 'disk_quota', 'disk_usage', 'last_reminder'); @@ -728,25 +729,17 @@ class ilObjFileAccessSettingsGUI extends ilObjectGUI default : $tbl_content_cell = htmlspecialchars($row[$key]); } - /* - if (is_array($tbl_content_cell)) - { - $tbl->tpl->setCurrentBlock("tbl_cell_subtitle"); - $tbl->tpl->setVariable("TBL_CELL_SUBTITLE",$tbl_content_cell[1]); - $tbl->tpl->parseCurrentBlock(); - $tbl_content_cell = "".$tbl_content_cell[0].""; - }*/ - - $tbl->tpl->setCurrentBlock("tbl_content_cell"); - $tbl->tpl->setVariable("TBL_CONTENT_CELL", $tbl_content_cell); - - $tbl->tpl->parseCurrentBlock(); + + $tbl->getTemplateObject()->setCurrentBlock("tbl_content_cell"); + $tbl->getTemplateObject()->setVariable("TBL_CONTENT_CELL", $tbl_content_cell); + + $tbl->getTemplateObject()->parseCurrentBlock(); } - $tbl->tpl->setCurrentBlock("tbl_content_row"); + $tbl->getTemplateObject()->setCurrentBlock("tbl_content_row"); $rowcolor = ilUtil::switchColor($count, "tblrow1", "tblrow2"); - $tbl->tpl->setVariable("ROWCOLOR", $rowcolor); - $tbl->tpl->parseCurrentBlock(); + $tbl->getTemplateObject()->setVariable("ROWCOLOR", $rowcolor); + $tbl->getTemplateObject()->parseCurrentBlock(); $count++; } diff --git a/Modules/Folder/classes/class.ilFolderExporter.php b/Modules/Folder/classes/class.ilFolderExporter.php index 32afac62be63fbed080b1e0dfeabc115e3d9ab87..f8c6b6af1684cfa549f81d8daf8bddc5f2bb8e14 100644 --- a/Modules/Folder/classes/class.ilFolderExporter.php +++ b/Modules/Folder/classes/class.ilFolderExporter.php @@ -16,109 +16,103 @@ include_once './Services/Export/classes/class.ilXmlExporter.php'; */ class ilFolderExporter extends ilXmlExporter { - private $writer = null; + private $writer = null; - /** - * Constructor - */ - public function __construct() - { - - } - - /** - * Init export - * @return - */ - public function init() - { - } - - /** - * Get head dependencies - * - * @param string entity - * @param string target release - * @param array ids - * @return array array of array with keys "component", entity", "ids" - */ - public function getXmlExportHeadDependencies($a_entity, $a_target_release, $a_ids) - { - // always trigger container because of co-page(s) - return array( - array( - 'component' => 'Services/Container', - 'entity' => 'struct', - 'ids' => $a_ids - ) - ); - - /* - include_once './Services/Export/classes/class.ilExportOptions.php'; - $eo = ilExportOptions::getInstance(); - - $obj_id = end($a_ids); - - if($eo->getOption(ilExportOptions::KEY_ROOT) != $obj_id) - { - return array(); - } - if(count(ilExportOptions::getInstance()->getSubitemsForExport()) > 1) - { - return array( - array( - 'component' => 'Services/Container', - 'entity' => 'struct', - 'ids' => $a_ids - ) - ); - } - return array(); - */ - } - - - /** - * Get xml - * @param object $a_entity - * @param object $a_schema_version - * @param object $a_id - * @return - */ - public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) - { - try - { - $this->writer = new ilFolderXmlWriter(false); - $this->writer->setObjId($a_id); - $this->writer->write(); - return $this->writer->xmlDumpMem(false); - - } - catch(UnexpectedValueException $e) - { - $GLOBALS['ilLog']->write("Caught error: ".$e->getMessage()); - return ''; - } - } - - /** - * Returns schema versions that the component can export to. - * ILIAS chooses the first one, that has min/max constraints which - * fit to the target release. Please put the newest on top. - * - * @return - */ - public function getValidSchemaVersions($a_entity) - { - return array ( - "4.1.0" => array( - "namespace" => "http://www.ilias.de/Modules/Folder/fold/4_1", - "xsd_file" => "ilias_fold_4_1.xsd", - "uses_dataset" => false, - "min" => "4.1.0", - "max" => "") - ); - } + /** + * Constructor + */ + public function __construct() + { + } + + /** + * Init export + * @return + */ + public function init() + { + } + + /** + * Get head dependencies + * + * @param string entity + * @param string target release + * @param array ids + * @return array array of array with keys "component", entity", "ids" + */ + public function getXmlExportHeadDependencies($a_entity, $a_target_release, $a_ids) + { + // always trigger container because of co-page(s) + return array( + array( + 'component' => 'Services/Container', + 'entity' => 'struct', + 'ids' => $a_ids + ) + ); + + /* + include_once './Services/Export/classes/class.ilExportOptions.php'; + $eo = ilExportOptions::getInstance(); + + $obj_id = end($a_ids); + + if($eo->getOption(ilExportOptions::KEY_ROOT) != $obj_id) + { + return array(); + } + if(count(ilExportOptions::getInstance()->getSubitemsForExport()) > 1) + { + return array( + array( + 'component' => 'Services/Container', + 'entity' => 'struct', + 'ids' => $a_ids + ) + ); + } + return array(); + */ + } + + + /** + * Get xml + * @param object $a_entity + * @param object $a_schema_version + * @param object $a_id + * @return + */ + public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) + { + try { + $this->writer = new ilFolderXmlWriter(false); + $this->writer->setObjId($a_id); + $this->writer->write(); + return $this->writer->xmlDumpMem(false); + } catch (UnexpectedValueException $e) { + $GLOBALS['ilLog']->write("Caught error: " . $e->getMessage()); + return ''; + } + } + + /** + * Returns schema versions that the component can export to. + * ILIAS chooses the first one, that has min/max constraints which + * fit to the target release. Please put the newest on top. + * + * @return + */ + public function getValidSchemaVersions($a_entity) + { + return array( + "4.1.0" => array( + "namespace" => "http://www.ilias.de/Modules/Folder/fold/4_1", + "xsd_file" => "ilias_fold_4_1.xsd", + "uses_dataset" => false, + "min" => "4.1.0", + "max" => "") + ); + } } -?> \ No newline at end of file diff --git a/Modules/Folder/classes/class.ilFolderImporter.php b/Modules/Folder/classes/class.ilFolderImporter.php index 7614e749ba61d2691a161bfd9c554ab4f3564bf9..525d915ac6c5a00fde32ab8e975cac1dfe642926 100644 --- a/Modules/Folder/classes/class.ilFolderImporter.php +++ b/Modules/Folder/classes/class.ilFolderImporter.php @@ -14,52 +14,41 @@ include_once("./Services/Export/classes/class.ilXmlImporter.php"); */ class ilFolderImporter extends ilXmlImporter { - private $folder = null; - + private $folder = null; + - public function init() - { - } - - /** - * Import XML - * - * @param - * @return - */ - function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) - { - include_once './Modules/Folder/classes/class.ilObjFolder.php'; - if($new_id = $a_mapping->getMapping('Services/Container','objs',$a_id)) - { - $this->folder = ilObjectFactory::getInstanceByObjId($new_id,false); - } - elseif($new_id = $a_mapping->getMapping('Services/Container','refs',0)) - { - $this->folder = ilObjectFactory::getInstanceByRefId($new_id,false); - } - elseif(!$this->folder instanceof ilObjFolder) - { - $this->folder = new ilObjFolder(); - $this->folder->create(true); - } + public function init() + { + } + + /** + * Import XML + * + * @param + * @return + */ + public function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) + { + include_once './Modules/Folder/classes/class.ilObjFolder.php'; + if ($new_id = $a_mapping->getMapping('Services/Container', 'objs', $a_id)) { + $this->folder = ilObjectFactory::getInstanceByObjId($new_id, false); + } elseif ($new_id = $a_mapping->getMapping('Services/Container', 'refs', 0)) { + $this->folder = ilObjectFactory::getInstanceByRefId($new_id, false); + } elseif (!$this->folder instanceof ilObjFolder) { + $this->folder = new ilObjFolder(); + $this->folder->create(true); + } - include_once './Modules/Folder/classes/class.ilFolderXmlParser.php'; + include_once './Modules/Folder/classes/class.ilFolderXmlParser.php'; - try - { - $parser = new ilFolderXmlParser($this->folder,$a_xml); - $parser->start(); - $a_mapping->addMapping('Modules/Folder','fold',$a_id,$this->folder->getId()); - } - catch(ilSaxParserException $e) - { - $GLOBALS['ilLog']->write(__METHOD__.': Parsing failed with message, "'.$e->getMessage().'".'); - } - catch(ilWebLinkXMLParserException $e) - { - $GLOBALS['ilLog']->write(__METHOD__.': Parsing failed with message, "'.$e->getMessage().'".'); - } - } + try { + $parser = new ilFolderXmlParser($this->folder, $a_xml); + $parser->start(); + $a_mapping->addMapping('Modules/Folder', 'fold', $a_id, $this->folder->getId()); + } catch (ilSaxParserException $e) { + $GLOBALS['ilLog']->write(__METHOD__ . ': Parsing failed with message, "' . $e->getMessage() . '".'); + } catch (ilWebLinkXMLParserException $e) { + $GLOBALS['ilLog']->write(__METHOD__ . ': Parsing failed with message, "' . $e->getMessage() . '".'); + } + } } -?> \ No newline at end of file diff --git a/Modules/Folder/classes/class.ilFolderLP.php b/Modules/Folder/classes/class.ilFolderLP.php index 11c7fdd8f62610db38b4e3fdf4760049d1c6066b..3137b20d9f3938986da49445f495cb5fda97e4b3 100644 --- a/Modules/Folder/classes/class.ilFolderLP.php +++ b/Modules/Folder/classes/class.ilFolderLP.php @@ -1,37 +1,35 @@ - - * @version $Id: class.ilLPStatusPlugin.php 43734 2013-07-29 15:27:58Z jluetzen $ - * @package ModulesFolder - */ -class ilFolderLP extends ilObjectLP -{ - public static function getDefaultModes($a_lp_active) - { - return array( - ilLPObjSettings::LP_MODE_DEACTIVATED - ); - } - - public function getDefaultMode() - { - return ilLPObjSettings::LP_MODE_DEACTIVATED; - } - - public function getValidModes() - { - return array( - ilLPObjSettings::LP_MODE_DEACTIVATED, - ilLPObjSettings::LP_MODE_COLLECTION - ); - } -} - -?> \ No newline at end of file + + * @version $Id: class.ilLPStatusPlugin.php 43734 2013-07-29 15:27:58Z jluetzen $ + * @package ModulesFolder + */ +class ilFolderLP extends ilObjectLP +{ + public static function getDefaultModes($a_lp_active) + { + return array( + ilLPObjSettings::LP_MODE_DEACTIVATED + ); + } + + public function getDefaultMode() + { + return ilLPObjSettings::LP_MODE_DEACTIVATED; + } + + public function getValidModes() + { + return array( + ilLPObjSettings::LP_MODE_DEACTIVATED, + ilLPObjSettings::LP_MODE_COLLECTION + ); + } +} diff --git a/Modules/Folder/classes/class.ilFolderXmlParser.php b/Modules/Folder/classes/class.ilFolderXmlParser.php index 7c938ab2c6294576e22e3af0d42363bacd60a5f4..fa812f413b4dd690345e822884549a397a615ccb 100644 --- a/Modules/Folder/classes/class.ilFolderXmlParser.php +++ b/Modules/Folder/classes/class.ilFolderXmlParser.php @@ -14,154 +14,148 @@ include_once './Services/Xml/classes/class.ilSaxParser.php'; */ class ilFolderXmlParser extends ilSaxParser { - /** - * @var ilErrorHandling - */ - protected $error; + /** + * @var ilErrorHandling + */ + protected $error; - private $folder = null; - + private $folder = null; + - /** - * Constructor - */ - public function __construct($folder,$xml) - { - global $DIC; + /** + * Constructor + */ + public function __construct($folder, $xml) + { + global $DIC; - $this->error = $DIC["ilErr"]; - parent::__construct(); - $this->setXMLContent($xml); - $this->setFolder($folder); - $this->setThrowException(true); - } - - /** - * set weblink - * @param ilObject $webl - * @return - */ - public function setFolder(ilObject $folder) - { - $this->folder = $folder; - } - - /** - * Get folder object - * @return ilObject - */ - public function getFolder() - { - return $this->folder; - } - - - /** - * - * @return - * @throws ilSaxParserException if invalid xml structure is given - * @throws ilWebLinkXMLParserException missing elements - */ - - public function start() - { - return $this->startParsing(); - } - - /** - * set event handlers - * - * @param resource reference to the xml parser - * @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'); - } - - /** - * handler for begin of element - * - * @param resource $a_xml_parser xml parser - * @param string $a_name element name - * @param array $a_attribs element attributes array - */ - public function handlerBeginTag($a_xml_parser,$a_name,$a_attribs) - { - $ilErr = $this->error; + $this->error = $DIC["ilErr"]; + parent::__construct(); + $this->setXMLContent($xml); + $this->setFolder($folder); + $this->setThrowException(true); + } + + /** + * set weblink + * @param ilObject $webl + * @return + */ + public function setFolder(ilObject $folder) + { + $this->folder = $folder; + } + + /** + * Get folder object + * @return ilObject + */ + public function getFolder() + { + return $this->folder; + } + + + /** + * + * @return + * @throws ilSaxParserException if invalid xml structure is given + * @throws ilWebLinkXMLParserException missing elements + */ + + public function start() + { + return $this->startParsing(); + } + + /** + * set event handlers + * + * @param resource reference to the xml parser + * @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'); + } + + /** + * handler for begin of element + * + * @param resource $a_xml_parser xml parser + * @param string $a_name element name + * @param array $a_attribs element attributes array + */ + public function handlerBeginTag($a_xml_parser, $a_name, $a_attribs) + { + $ilErr = $this->error; - switch($a_name) - { + switch ($a_name) { - case 'Folder': - break; + case 'Folder': + break; - case 'Sorting': - case 'Sort': - include_once './Services/Container/classes/class.ilContainerSortingSettings.php'; - ilContainerSortingSettings::_importContainerSortingSettings($a_attribs, $this->getFolder()->getId()); - break; - - case 'Title': - case 'Description': - break; - } - - } - - /** - * handler for end of element - * - * @param resource $a_xml_parser xml parser - * @param string $a_name element name - * @throws ilSaxParserException if invalid xml structure is given - * @throws ilWebLinkXMLParserException missing elements - */ - public function handlerEndTag($a_xml_parser,$a_name) - { - - $GLOBALS['ilLog']->write(__METHOD__.': Called '.$a_name); + case 'Sorting': + case 'Sort': + include_once './Services/Container/classes/class.ilContainerSortingSettings.php'; + ilContainerSortingSettings::_importContainerSortingSettings($a_attribs, $this->getFolder()->getId()); + break; + + case 'Title': + case 'Description': + break; + } + } + + /** + * handler for end of element + * + * @param resource $a_xml_parser xml parser + * @param string $a_name element name + * @throws ilSaxParserException if invalid xml structure is given + * @throws ilWebLinkXMLParserException missing elements + */ + public function handlerEndTag($a_xml_parser, $a_name) + { + $GLOBALS['ilLog']->write(__METHOD__ . ': Called ' . $a_name); - switch($a_name) - { - - case 'Folder': - $this->getFolder()->update(); - break; - - case 'Title': - $this->getFolder()->setTitle(trim($this->cdata)); - break; - - case 'Description': - $this->getFolder()->setDescription(trim($this->cdata)); - break; - - } - - // Reset cdata - $this->cdata = ''; - } - + switch ($a_name) { + + case 'Folder': + $this->getFolder()->update(); + break; + + case 'Title': + $this->getFolder()->setTitle(trim($this->cdata)); + break; + + case 'Description': + $this->getFolder()->setDescription(trim($this->cdata)); + break; + + } + + // Reset cdata + $this->cdata = ''; + } + - - /** - * handler for character data - * - * @param resource $a_xml_parser xml parser - * @param string $a_data character data - */ - public function handlerCharacterData($a_xml_parser,$a_data) - { - if($a_data != "\n") - { - // Replace multiple tabs with one space - $a_data = preg_replace("/\t+/"," ",$a_data); - $this->cdata .= $a_data; - } - } + + /** + * handler for character data + * + * @param resource $a_xml_parser xml parser + * @param string $a_data character data + */ + public function handlerCharacterData($a_xml_parser, $a_data) + { + if ($a_data != "\n") { + // Replace multiple tabs with one space + $a_data = preg_replace("/\t+/", " ", $a_data); + $this->cdata .= $a_data; + } + } } -?> \ No newline at end of file diff --git a/Modules/Folder/classes/class.ilFolderXmlWriter.php b/Modules/Folder/classes/class.ilFolderXmlWriter.php index 968a10e9e0275c9fa4f2750721ba6dbeb2e3145f..15c720534b32cf190e8dbd0c6ae56e4603bfcb33 100644 --- a/Modules/Folder/classes/class.ilFolderXmlWriter.php +++ b/Modules/Folder/classes/class.ilFolderXmlWriter.php @@ -13,86 +13,81 @@ include_once "./Services/Xml/classes/class.ilXmlWriter.php"; */ class ilFolderXmlWriter extends ilXmlWriter { - private $add_header = true; - - private $obj_id = 0; - private $folder = null; + private $add_header = true; + + private $obj_id = 0; + private $folder = null; - /** - * Constructor - */ - public function __construct($a_add_header) - { - $this->add_header = $a_add_header; - parent::__construct(); - } - - /** - * Set obj_id of weblink object - * @param int obj_id - * @return bool - */ - public function setObjId($a_obj_id) - { - $this->obj_id = $a_obj_id; - } - - /** - * Write XML - * @return - * @throws UnexpectedValueException Thrown if obj_id is not of type webr or no obj_id is given - */ - public function write() - { - $this->init(); - if($this->add_header) - { - $this->buildHeader(); - } - $this->xmlStartTag('Folder',array('Id' => $this->folder->getId())); - $this->xmlElement('Title',array(),$this->folder->getTitle()); - $this->xmlElement('Description',array(),$this->folder->getDescription()); - include_once './Services/Container/classes/class.ilContainerSortingSettings.php'; - ilContainerSortingSettings::_exportContainerSortingSettings($this,$this->obj_id); - $this->xmlEndTag('Folder'); - } - - /** - * Build XML header - * @return - */ - protected function buildHeader() - { - $this->xmlSetDtdDef(""); - $this->xmlSetGenCmt("Export of a ILIAS Folder"); - $this->xmlHeader(); + /** + * Constructor + */ + public function __construct($a_add_header) + { + $this->add_header = $a_add_header; + parent::__construct(); + } + + /** + * Set obj_id of weblink object + * @param int obj_id + * @return bool + */ + public function setObjId($a_obj_id) + { + $this->obj_id = $a_obj_id; + } + + /** + * Write XML + * @return + * @throws UnexpectedValueException Thrown if obj_id is not of type webr or no obj_id is given + */ + public function write() + { + $this->init(); + if ($this->add_header) { + $this->buildHeader(); + } + $this->xmlStartTag('Folder', array('Id' => $this->folder->getId())); + $this->xmlElement('Title', array(), $this->folder->getTitle()); + $this->xmlElement('Description', array(), $this->folder->getDescription()); + include_once './Services/Container/classes/class.ilContainerSortingSettings.php'; + ilContainerSortingSettings::_exportContainerSortingSettings($this, $this->obj_id); + $this->xmlEndTag('Folder'); + } + + /** + * Build XML header + * @return + */ + protected function buildHeader() + { + $this->xmlSetDtdDef(""); + $this->xmlSetGenCmt("Export of a ILIAS Folder"); + $this->xmlHeader(); - return true; - } - - - /** - * Init xml writer - * @return bool - * @throws UnexpectedValueException Thrown if obj_id is not of type webr - */ - protected function init() - { - $this->xmlClear(); - - if(!$this->obj_id) - { - throw new UnexpectedValueException('No obj_id given: '); - } - include_once './Services/Object/classes/class.ilObjectFactory.php'; - if(!$this->folder = ilObjectFactory::getInstanceByObjId($this->obj_id,false)) - { - throw new UnexpectedValueException('Invalid obj_id given: '.$this->obj_id); - } - if($this->folder->getType() != 'fold') - { - throw new UnexpectedValueException('Invalid obj_id given. Object is not of type folder'); - } - } + return true; + } + + + /** + * Init xml writer + * @return bool + * @throws UnexpectedValueException Thrown if obj_id is not of type webr + */ + protected function init() + { + $this->xmlClear(); + + if (!$this->obj_id) { + throw new UnexpectedValueException('No obj_id given: '); + } + include_once './Services/Object/classes/class.ilObjectFactory.php'; + if (!$this->folder = ilObjectFactory::getInstanceByObjId($this->obj_id, false)) { + throw new UnexpectedValueException('Invalid obj_id given: ' . $this->obj_id); + } + if ($this->folder->getType() != 'fold') { + throw new UnexpectedValueException('Invalid obj_id given. Object is not of type folder'); + } + } } -?> \ No newline at end of file diff --git a/Modules/Folder/classes/class.ilObjFolder.php b/Modules/Folder/classes/class.ilObjFolder.php index 62dc4180097592fe540b8ef80a6a940f4e2b4362..41e2de9d3984e569d6f06eb6ee84c2d41acb8d9b 100755 --- a/Modules/Folder/classes/class.ilObjFolder.php +++ b/Modules/Folder/classes/class.ilObjFolder.php @@ -1,24 +1,24 @@ tree = $DIC->repositoryTree(); - $this->lng = $DIC->language(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->access = $DIC->access(); - $this->type = "fold"; - parent::__construct($a_id,$a_call_by_reference); - $this->lng->loadLanguageModule('fold'); - } + $this->tree = $DIC->repositoryTree(); + $this->lng = $DIC->language(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->access = $DIC->access(); + $this->type = "fold"; + parent::__construct($a_id, $a_call_by_reference); + $this->lng->loadLanguageModule('fold'); + } - function setFolderTree($a_tree) - { - $this->folder_tree =& $a_tree; - } - - /** - * Clone folder - * - * @access public - * @param int target id - * @param int copy id - * - */ - public function cloneObject($a_target_id,$a_copy_id = 0, $a_omit_tree = false) - { - $new_obj = parent::cloneObject($a_target_id,$a_copy_id, $a_omit_tree); - - // Copy learning progress settings - include_once('Services/Tracking/classes/class.ilLPObjSettings.php'); - $obj_settings = new ilLPObjSettings($this->getId()); - $obj_settings->cloneSettings($new_obj->getId()); - unset($obj_settings); - - return $new_obj; - } + public function setFolderTree($a_tree) + { + $this->folder_tree =&$a_tree; + } + + /** + * Clone folder + * + * @access public + * @param int target id + * @param int copy id + * + */ + public function cloneObject($a_target_id, $a_copy_id = 0, $a_omit_tree = false) + { + $new_obj = parent::cloneObject($a_target_id, $a_copy_id, $a_omit_tree); + + // Copy learning progress settings + include_once('Services/Tracking/classes/class.ilLPObjSettings.php'); + $obj_settings = new ilLPObjSettings($this->getId()); + $obj_settings->cloneSettings($new_obj->getId()); + unset($obj_settings); + + return $new_obj; + } - /** - * insert folder into grp_tree - * - */ - function putInTree($a_parent) - { - $tree = $this->tree; - - if (!is_object($this->folder_tree)) - { - $this->folder_tree =& $tree; - } + /** + * insert folder into grp_tree + * + */ + public function putInTree($a_parent) + { + $tree = $this->tree; + + if (!is_object($this->folder_tree)) { + $this->folder_tree =&$tree; + } - if ($this->withReferences()) - { - // put reference id into tree - $this->folder_tree->insertNode($this->getRefId(), $a_parent); - } - else - { - // put object id into tree - $this->folder_tree->insertNode($this->getId(), $a_parent); - } - } - - /** - * Clone object dependencies (crs items, preconditions) - * - * @access public - * @param int target ref id of new course - * @param int copy id - * - */ - public function cloneDependencies($a_target_id,$a_copy_id) - { - parent::cloneDependencies($a_target_id,$a_copy_id); + if ($this->withReferences()) { + // put reference id into tree + $this->folder_tree->insertNode($this->getRefId(), $a_parent); + } else { + // put object id into tree + $this->folder_tree->insertNode($this->getId(), $a_parent); + } + } + + /** + * Clone object dependencies (crs items, preconditions) + * + * @access public + * @param int target ref id of new course + * @param int copy id + * + */ + public function cloneDependencies($a_target_id, $a_copy_id) + { + parent::cloneDependencies($a_target_id, $a_copy_id); - include_once('Services/Object/classes/class.ilObjectActivation.php'); - ilObjectActivation::cloneDependencies($this->getRefId(), $a_target_id, $a_copy_id); - - return true; - } + include_once('Services/Object/classes/class.ilObjectActivation.php'); + ilObjectActivation::cloneDependencies($this->getRefId(), $a_target_id, $a_copy_id); + + return true; + } - /** - * private functions which iterates through all folders and files - * and create an according file structure in a temporary directory. This function works recursive. - * - * @param int $ref_id Reference-ID of Folder - * @param string $title of Folder - * @param string $tmpdir (MUST be already relative due to filesystem-service) - * - * @return string returns first created directory - * @throws \ILIAS\Filesystem\Exception\FileNotFoundException - * @throws \ILIAS\Filesystem\Exception\IOException - * @throws ilFileException - * @throws ilFileUtilsException - */ - private static function recurseFolder($ref_id, $title, $tmpdir) { - global $DIC; + /** + * private functions which iterates through all folders and files + * and create an according file structure in a temporary directory. This function works recursive. + * + * @param int $ref_id Reference-ID of Folder + * @param string $title of Folder + * @param string $tmpdir (MUST be already relative due to filesystem-service) + * + * @return string returns first created directory + * @throws \ILIAS\Filesystem\Exception\FileNotFoundException + * @throws \ILIAS\Filesystem\Exception\IOException + * @throws ilFileException + * @throws ilFileUtilsException + */ + private static function recurseFolder($ref_id, $title, $tmpdir) + { + global $DIC; - $tree = $DIC->repositoryTree(); - $ilAccess = $DIC->access(); + $tree = $DIC->repositoryTree(); + $ilAccess = $DIC->access(); - $tmpdir = $tmpdir . DIRECTORY_SEPARATOR . ilUtil::getASCIIFilename($title); + $tmpdir = $tmpdir . DIRECTORY_SEPARATOR . ilUtil::getASCIIFilename($title); - $temp_fs = $DIC->filesystem()->temp(); - $storage_fs = $DIC->filesystem()->storage(); - $temp_fs->createDir($tmpdir); + $temp_fs = $DIC->filesystem()->temp(); + $storage_fs = $DIC->filesystem()->storage(); + $temp_fs->createDir($tmpdir); - $subtree = $tree->getChildsByTypeFilter($ref_id, array("fold", "file")); + $subtree = $tree->getChildsByTypeFilter($ref_id, array("fold", "file")); - foreach ($subtree as $child) { - if (!$ilAccess->checkAccess("read", "", $child["ref_id"])) { - continue; - } - if (ilObject::_isInTrash($child["ref_id"])) { - continue; - } - if ($child["type"] == "fold") { - ilObjFolder::recurseFolder($child["ref_id"], $child["title"], $tmpdir); - } else { - $newFilename = $tmpdir . DIRECTORY_SEPARATOR . ilUtil::getASCIIFilename($child["title"]); - // copy to temporal directory - $relative_path_of_file = LegacyPathHelper::createRelativePath(ilObjFile::_lookupAbsolutePath($child["obj_id"])); - if ($storage_fs->has($relative_path_of_file)) { - $s = $storage_fs->readStream($relative_path_of_file); - } else { - throw new ilFileException("Could not copy " . $relative_path_of_file . " to " . $newFilename); - } - $temp_fs->writeStream($newFilename, $s); - } - } - } - - public function downloadFolder() { - $ilAccess = $this->access; + foreach ($subtree as $child) { + if (!$ilAccess->checkAccess("read", "", $child["ref_id"])) { + continue; + } + if (ilObject::_isInTrash($child["ref_id"])) { + continue; + } + if ($child["type"] == "fold") { + ilObjFolder::recurseFolder($child["ref_id"], $child["title"], $tmpdir); + } else { + $newFilename = $tmpdir . DIRECTORY_SEPARATOR . ilUtil::getASCIIFilename($child["title"]); + // copy to temporal directory + $relative_path_of_file = LegacyPathHelper::createRelativePath(ilObjFile::_lookupAbsolutePath($child["obj_id"])); + if ($storage_fs->has($relative_path_of_file)) { + $s = $storage_fs->readStream($relative_path_of_file); + } else { + throw new ilFileException("Could not copy " . $relative_path_of_file . " to " . $newFilename); + } + $temp_fs->writeStream($newFilename, $s); + } + } + } + + public function downloadFolder() + { + $ilAccess = $this->access; - if (!$ilAccess->checkAccess("read", "", $this->getRefId())) - { - $this->ilErr->raiseError(get_class($this)."::downloadFolder(): missing read permission!",$this->ilErr->WARNING); - } - if (ilObject::_isInTrash($this->getRefId())) - { - $this->ilErr->raiseError(get_class($this)."::downloadFolder(): object is trashed!",$this->ilErr->WARNING); - } + if (!$ilAccess->checkAccess("read", "", $this->getRefId())) { + $this->ilErr->raiseError(get_class($this) . "::downloadFolder(): missing read permission!", $this->ilErr->WARNING); + } + if (ilObject::_isInTrash($this->getRefId())) { + $this->ilErr->raiseError(get_class($this) . "::downloadFolder(): object is trashed!", $this->ilErr->WARNING); + } - $tmpdir = ilUtil::ilTempnam(); - ilUtil::makeDir($tmpdir); - $basename = ilUtil::getAsciiFilename($this->getTitle()); - $deliverFilename = $basename.".zip"; - $zipbasedir = $tmpdir.DIRECTORY_SEPARATOR.$basename; - $tmpzipfile = $tmpdir.DIRECTORY_SEPARATOR.$deliverFilename; - - try { - ilObjFolder::recurseFolder ($this->getRefId(), $this->getTitle(), LegacyPathHelper::createRelativePath($tmpdir)); - ilUtil::zip($zipbasedir, $tmpzipfile); - rename($tmpzipfile,$zipfile = ilUtil::ilTempnam()); - ilUtil::delDir($tmpdir); - ilUtil::deliverFile($zipfile,$deliverFilename,'',false,true); - } catch (ilFileException $e) { - ilUtil::sendInfo($e->getMessage(), true); - } - } - - /** - * Get container view mode - */ - function getViewMode() - { - $tree = $this->tree; - - // default: by type - $view = ilContainer::VIEW_BY_TYPE; + $tmpdir = ilUtil::ilTempnam(); + ilUtil::makeDir($tmpdir); + $basename = ilUtil::getAsciiFilename($this->getTitle()); + $deliverFilename = $basename . ".zip"; + $zipbasedir = $tmpdir . DIRECTORY_SEPARATOR . $basename; + $tmpzipfile = $tmpdir . DIRECTORY_SEPARATOR . $deliverFilename; + + try { + ilObjFolder::recurseFolder($this->getRefId(), $this->getTitle(), LegacyPathHelper::createRelativePath($tmpdir)); + ilUtil::zip($zipbasedir, $tmpzipfile); + rename($tmpzipfile, $zipfile = ilUtil::ilTempnam()); + ilUtil::delDir($tmpdir); + ilUtil::deliverFile($zipfile, $deliverFilename, '', false, true); + } catch (ilFileException $e) { + ilUtil::sendInfo($e->getMessage(), true); + } + } + + /** + * Get container view mode + */ + public function getViewMode() + { + $tree = $this->tree; + + // default: by type + $view = ilContainer::VIEW_BY_TYPE; - // always inherit from - $container_ref_id = $tree->checkForParentType($this->ref_id, 'grp'); - if(!$container_ref_id) - { - $container_ref_id = $tree->checkForParentType($this->ref_id, 'crs'); - } - if($container_ref_id) - { - include_once("./Modules/Course/classes/class.ilObjCourseAccess.php"); - $view_mode = ilObjCourseAccess::_lookupViewMode(ilObject::_lookupObjId($container_ref_id)); - if ($view_mode == ilContainer::VIEW_SESSIONS || - $view_mode == ilContainer::VIEW_BY_TYPE || - $view_mode == ilContainer::VIEW_SIMPLE) - { - $view = $view_mode; - } - } - - return $view; - } - - /** - * Add additional information to sub item, e.g. used in - * courses for timings information etc. - */ - function addAdditionalSubItemInformation(&$a_item_data) - { - include_once './Services/Object/classes/class.ilObjectActivation.php'; - ilObjectActivation::addAdditionalSubItemInformation($a_item_data); - } - - /** - * Overwritten read method - * - * @access public - * @param - * @return - */ - public function read() - { - $tree = $this->tree; - - parent::read(); - - // Inherit order type from parent course (if exists) - include_once('./Services/Container/classes/class.ilContainerSortingSettings.php'); - $this->setOrderType(ilContainerSortingSettings::_lookupSortMode($this->getId())); - } + // always inherit from + $container_ref_id = $tree->checkForParentType($this->ref_id, 'grp'); + if (!$container_ref_id) { + $container_ref_id = $tree->checkForParentType($this->ref_id, 'crs'); + } + if ($container_ref_id) { + include_once("./Modules/Course/classes/class.ilObjCourseAccess.php"); + $view_mode = ilObjCourseAccess::_lookupViewMode(ilObject::_lookupObjId($container_ref_id)); + if ($view_mode == ilContainer::VIEW_SESSIONS || + $view_mode == ilContainer::VIEW_BY_TYPE || + $view_mode == ilContainer::VIEW_SIMPLE) { + $view = $view_mode; + } + } + + return $view; + } + /** + * Add additional information to sub item, e.g. used in + * courses for timings information etc. + */ + public function addAdditionalSubItemInformation(&$a_item_data) + { + include_once './Services/Object/classes/class.ilObjectActivation.php'; + ilObjectActivation::addAdditionalSubItemInformation($a_item_data); + } + + /** + * Overwritten read method + * + * @access public + * @param + * @return + */ + public function read() + { + $tree = $this->tree; + + parent::read(); + + // Inherit order type from parent course (if exists) + include_once('./Services/Container/classes/class.ilContainerSortingSettings.php'); + $this->setOrderType(ilContainerSortingSettings::_lookupSortMode($this->getId())); + } } // END class.ilObjFolder -?> diff --git a/Modules/Folder/classes/class.ilObjFolderAccess.php b/Modules/Folder/classes/class.ilObjFolderAccess.php index f2ae8d09b312cc89a613331e5c6630366b87bf10..6425c8615f9ff7e1695d9e013a0f8da964400808 100644 --- a/Modules/Folder/classes/class.ilObjFolderAccess.php +++ b/Modules/Folder/classes/class.ilObjFolderAccess.php @@ -14,104 +14,96 @@ include_once("./Services/Object/classes/class.ilObjectAccess.php"); */ class ilObjFolderAccess extends ilObjectAccess { - private static $folderSettings; + private static $folderSettings; - private static function getFolderSettings() { - if (is_null (ilObjFolderAccess::$folderSettings)) - { - ilObjFolderAccess::$folderSettings = new ilSetting('fold'); + private static function getFolderSettings() + { + if (is_null(ilObjFolderAccess::$folderSettings)) { + ilObjFolderAccess::$folderSettings = new ilSetting('fold'); } return ilObjFolderAccess::$folderSettings; } - /** - * 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(); - $commands[] = array("permission" => "read", "cmd" => "view", "lang_var" => "show", "default" => true); + /** + * 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(); + $commands[] = array("permission" => "read", "cmd" => "view", "lang_var" => "show", "default" => true); - include_once './Services/WebServices/FileManager/classes/class.ilFMSettings.php'; - if(ilFMSettings::getInstance()->isEnabled()) - { - $commands[] = array( - 'permission' => 'read', - 'cmd' => 'fileManagerLaunch', - 'lang_var' => 'fm_start', - 'enable_anonymous' => false - ); - } + include_once './Services/WebServices/FileManager/classes/class.ilFMSettings.php'; + if (ilFMSettings::getInstance()->isEnabled()) { + $commands[] = array( + 'permission' => 'read', + 'cmd' => 'fileManagerLaunch', + 'lang_var' => 'fm_start', + 'enable_anonymous' => false + ); + } - // why here, why read permission? it just needs info_screen_enabled = true in ilObjCategoryListGUI (alex, 30.7.2008) - // this is not consistent, with all other objects... - //$commands[] = array("permission" => "read", "cmd" => "showSummary", "lang_var" => "info_short", "enable_anonymous" => "false"); - if (ilObjFolderAccess::hasDownloadAction($_GET["ref_id"])) - { - $commands[] = array("permission" => "read", "cmd" => "downloadFolder", "lang_var" => "download"); // #18805 - } - // BEGIN WebDAV: Mount Webfolder. - include_once ('Services/WebDAV/classes/class.ilDAVActivationChecker.php'); - if (ilDAVActivationChecker::_isActive()) - { - include_once './Services/WebDAV/classes/class.ilWebDAVUtil.php'; - if(ilWebDAVUtil::getInstance()->isLocalPasswordInstructionRequired()) - { - $commands[] = array('permission' => 'read', 'cmd' => 'showPasswordInstruction', 'lang_var' => 'mount_webfolder', 'enable_anonymous' => 'false'); - } - else - { - $commands[] = array("permission" => "read", "cmd" => "mount_webfolder", "lang_var" => "mount_webfolder", "enable_anonymous" => "false"); - } - } - $commands[] = array("permission" => "write", "cmd" => "enableAdministrationPanel", "lang_var" => "edit_content"); - $commands[] = array("permission" => "write", "cmd" => "edit", "lang_var" => "settings"); - - return $commands; - } + // why here, why read permission? it just needs info_screen_enabled = true in ilObjCategoryListGUI (alex, 30.7.2008) + // this is not consistent, with all other objects... + //$commands[] = array("permission" => "read", "cmd" => "showSummary", "lang_var" => "info_short", "enable_anonymous" => "false"); + if (ilObjFolderAccess::hasDownloadAction($_GET["ref_id"])) { + $commands[] = array("permission" => "read", "cmd" => "downloadFolder", "lang_var" => "download"); // #18805 + } + // BEGIN WebDAV: Mount Webfolder. + include_once('Services/WebDAV/classes/class.ilDAVActivationChecker.php'); + if (ilDAVActivationChecker::_isActive()) { + include_once './Services/WebDAV/classes/class.ilWebDAVUtil.php'; + if (ilWebDAVUtil::getInstance()->isLocalPasswordInstructionRequired()) { + $commands[] = array('permission' => 'read', 'cmd' => 'showPasswordInstruction', 'lang_var' => 'mount_webfolder', 'enable_anonymous' => 'false'); + } else { + $commands[] = array("permission" => "read", "cmd" => "mount_webfolder", "lang_var" => "mount_webfolder", "enable_anonymous" => "false"); + } + } + $commands[] = array("permission" => "write", "cmd" => "enableAdministrationPanel", "lang_var" => "edit_content"); + $commands[] = array("permission" => "write", "cmd" => "edit", "lang_var" => "settings"); + + return $commands; + } - - private static function hasDownloadAction ($ref_id) - { - global $DIC; + + private static function hasDownloadAction($ref_id) + { + global $DIC; - $tree = $DIC->repositoryTree(); - $ilUser = $DIC->user(); - $settings = ilObjFolderAccess::getFolderSettings(); - // default value should reflect previous behaviour (-> 0) - if ($settings->get("enable_download_folder", 0) != 1) - return false; - - /* - * deactivated check for now, because wrong ref_id here! - - * - $children = $tree->getChildsByTypeFilter($ref_id, array("file","fold")); + $tree = $DIC->repositoryTree(); + $ilUser = $DIC->user(); + $settings = ilObjFolderAccess::getFolderSettings(); + // default value should reflect previous behaviour (-> 0) + if ($settings->get("enable_download_folder", 0) != 1) { + return false; + } + + /* + * deactivated check for now, because wrong ref_id here! - // no children at all, so no download button - if (count ($children) == 0) - return false; - // check if at least one of the children has a read permission - foreach ($children as $child) - { - if ($rbacsystem->checkAccessOfUser($ilUser->getId(), "read", $child["ref_id"])) - return true; - } - return false; - */ - return true; - } + * + $children = $tree->getChildsByTypeFilter($ref_id, array("file","fold")); + // no children at all, so no download button + if (count ($children) == 0) + return false; + // check if at least one of the children has a read permission + foreach ($children as $child) + { + if ($rbacsystem->checkAccessOfUser($ilUser->getId(), "read", $child["ref_id"])) + return true; + } + return false; + */ + return true; + } } - -?> diff --git a/Modules/Folder/classes/class.ilObjFolderGUI.php b/Modules/Folder/classes/class.ilObjFolderGUI.php index e717eb4ae237f2fe3dc49dc657b06dcce6828a32..04c6887d99e1fd058a1a5eb0022456b8a40aa78d 100755 --- a/Modules/Folder/classes/class.ilObjFolderGUI.php +++ b/Modules/Folder/classes/class.ilObjFolderGUI.php @@ -22,215 +22,217 @@ require_once "./Services/Container/classes/class.ilContainerGUI.php"; class ilObjFolderGUI extends ilContainerGUI { - /** - * @var ilHelpGUI - */ - protected $help; - - var $folder_tree; // folder tree - - /** - * Constructor - * @access public - */ - public function __construct($a_data, $a_id = 0, $a_call_by_reference = true, $a_prepare_output = false) - { - global $DIC; - - $this->tree = $DIC->repositoryTree(); - $this->tabs = $DIC->tabs(); - $this->user = $DIC->user(); - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->help = $DIC["ilHelp"]; - $this->error = $DIC["ilErr"]; - $this->tpl = $DIC["tpl"]; - $this->settings = $DIC->settings(); - $this->type = "fold"; - parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output, false); - - $this->lng->loadLanguageModule("obj"); - } - - - /** - * View folder - */ - function viewObject() - { - $tree = $this->tree; - - $this->checkPermission('read'); - - if (strtolower($_GET["baseClass"]) == "iladministrationgui") - { - parent::viewObject(); - return true; - } - - // Trac access - see ilObjCourseGUI - include_once 'Services/Tracking/classes/class.ilLearningProgress.php'; - ilLearningProgress::_tracProgress($GLOBALS["ilUser"]->getId(),$this->object->getId(), - $this->object->getRefId(),'fold'); - - $this->renderObject(); - $this->tabs_gui->setTabActive('view_content'); - return true; - } - - /** - * Render folder - */ - function renderObject() - { - $ilTabs = $this->tabs; - - $this->checkPermission('read'); - - $ilTabs->activateTab("view_content"); - $ret = parent::renderObject(); - return $ret; - } - - function executeCommand() - { - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - // show repository tree - $this->showRepTree(); - - switch ($next_class) - { - case 'ilpermissiongui': - $this->prepareOutput(); - $this->tabs_gui->setTabActive('perm_settings'); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $ret =& $this->ctrl->forwardCommand($perm_gui); - break; - - - case 'ilcoursecontentgui': - $this->prepareOutput(); - include_once './Modules/Course/classes/class.ilCourseContentGUI.php'; - $course_content_obj = new ilCourseContentGUI($this); - $this->ctrl->forwardCommand($course_content_obj); - break; - - case "illearningprogressgui": - $this->prepareOutput(); - include_once './Services/Tracking/classes/class.ilLearningProgressGUI.php'; - - $new_gui = new ilLearningProgressGUI(ilLearningProgressGUI::LP_CONTEXT_REPOSITORY, - $this->object->getRefId(), - $_GET['user_id'] ? $_GET['user_id'] : $ilUser->getId()); - $this->ctrl->forwardCommand($new_gui); - $this->tabs_gui->setTabActive('learning_progress'); - break; - - // container page editing - case "ilcontainerpagegui": - $this->prepareOutput(false); - $ret = $this->forwardToPageObject(); - if ($ret != "") - { - $this->tpl->setContent($ret); - } - break; - - case 'ilinfoscreengui': - $this->prepareOutput(); - $this->infoScreen(); - break; - - case 'ilobjectcopygui': - $this->prepareOutput(); - - include_once './Services/Object/classes/class.ilObjectCopyGUI.php'; - $cp = new ilObjectCopyGUI($this); - $cp->setType('fold'); - $this->ctrl->forwardCommand($cp); - break; - - case "ilobjstylesheetgui": - $this->forwardToStyleSheet(); - break; - - case 'ilexportgui': - $this->prepareOutput(); - - $this->tabs_gui->setTabActive('export'); - include_once './Services/Export/classes/class.ilExportGUI.php'; - $exp = new ilExportGUI($this); - $exp->addFormat('xml'); - $this->ctrl->forwardCommand($exp); - break; - - case "ilcommonactiondispatchergui": - include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); - $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); - $this->ctrl->forwardCommand($gui); - break; - - case 'ildidactictemplategui': - $this->ctrl->setReturn($this,'edit'); - include_once './Services/DidacticTemplate/classes/class.ilDidacticTemplateGUI.php'; - $did = new ilDidacticTemplateGUI($this); - $this->ctrl->forwardCommand($did); - break; - case 'ilcolumngui': - $this->tabs_gui->setTabActive('none'); - $this->checkPermission("read"); - $this->viewObject(); - break; - - case 'ilbackgroundtaskhub': - include_once './Services/BackgroundTask/classes/class.ilBackgroundTaskHub.php'; - $bggui = new ilBackgroundTaskHub(); - $this->ctrl->forwardCommand($bggui); - break; - - case 'ilobjecttranslationgui': - $this->checkPermissionBool("write"); - $this->prepareOutput(); - $this->setSubTabs("settings_trans"); - include_once("./Services/Object/classes/class.ilObjectTranslationGUI.php"); - $transgui = new ilObjectTranslationGUI($this); - $this->ctrl->forwardCommand($transgui); - break; - - default: - - $this->prepareOutput(); - // cognos-blu-patch: begin - // removed timings forward - // cognos-blu-patch: end - - if (empty($cmd)) - { - $cmd = "view"; - } - $cmd .= "Object"; - $this->$cmd(); - break; - } - - $this->addHeaderAction(); - } - - /** - * set tree - */ - function setFolderTree($a_tree) - { - $this->folder_tree =& $a_tree; - } + /** + * @var ilHelpGUI + */ + protected $help; + + public $folder_tree; // folder tree + + /** + * Constructor + * @access public + */ + public function __construct($a_data, $a_id = 0, $a_call_by_reference = true, $a_prepare_output = false) + { + global $DIC; + + $this->tree = $DIC->repositoryTree(); + $this->tabs = $DIC->tabs(); + $this->user = $DIC->user(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->help = $DIC["ilHelp"]; + $this->error = $DIC["ilErr"]; + $this->tpl = $DIC["tpl"]; + $this->settings = $DIC->settings(); + $this->type = "fold"; + parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output, false); + + $this->lng->loadLanguageModule("obj"); + } + + + /** + * View folder + */ + public function viewObject() + { + $tree = $this->tree; + + $this->checkPermission('read'); + + if (strtolower($_GET["baseClass"]) == "iladministrationgui") { + parent::viewObject(); + return true; + } + + // Trac access - see ilObjCourseGUI + include_once 'Services/Tracking/classes/class.ilLearningProgress.php'; + ilLearningProgress::_tracProgress( + $GLOBALS["ilUser"]->getId(), + $this->object->getId(), + $this->object->getRefId(), + 'fold' + ); + + $this->renderObject(); + $this->tabs_gui->setTabActive('view_content'); + return true; + } + + /** + * Render folder + */ + public function renderObject() + { + $ilTabs = $this->tabs; + + $this->checkPermission('read'); + + $ilTabs->activateTab("view_content"); + $ret = parent::renderObject(); + return $ret; + } + + public function executeCommand() + { + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + // show repository tree + $this->showRepTree(); + + switch ($next_class) { + case 'ilpermissiongui': + $this->prepareOutput(); + $this->tabs_gui->setTabActive('perm_settings'); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $ret =&$this->ctrl->forwardCommand($perm_gui); + break; + + + case 'ilcoursecontentgui': + $this->prepareOutput(); + include_once './Modules/Course/classes/class.ilCourseContentGUI.php'; + $course_content_obj = new ilCourseContentGUI($this); + $this->ctrl->forwardCommand($course_content_obj); + break; + + case "illearningprogressgui": + $this->prepareOutput(); + include_once './Services/Tracking/classes/class.ilLearningProgressGUI.php'; + + $new_gui = new ilLearningProgressGUI( + ilLearningProgressGUI::LP_CONTEXT_REPOSITORY, + $this->object->getRefId(), + $_GET['user_id'] ? $_GET['user_id'] : $ilUser->getId() + ); + $this->ctrl->forwardCommand($new_gui); + $this->tabs_gui->setTabActive('learning_progress'); + break; + + // container page editing + case "ilcontainerpagegui": + $this->prepareOutput(false); + $ret = $this->forwardToPageObject(); + if ($ret != "") { + $this->tpl->setContent($ret); + } + break; + + case 'ilinfoscreengui': + $this->prepareOutput(); + $this->infoScreen(); + break; + + case 'ilobjectcopygui': + $this->prepareOutput(); + + include_once './Services/Object/classes/class.ilObjectCopyGUI.php'; + $cp = new ilObjectCopyGUI($this); + $cp->setType('fold'); + $this->ctrl->forwardCommand($cp); + break; + + case "ilobjstylesheetgui": + $this->forwardToStyleSheet(); + break; + + case 'ilexportgui': + $this->prepareOutput(); + + $this->tabs_gui->setTabActive('export'); + include_once './Services/Export/classes/class.ilExportGUI.php'; + $exp = new ilExportGUI($this); + $exp->addFormat('xml'); + $this->ctrl->forwardCommand($exp); + break; + + case "ilcommonactiondispatchergui": + include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); + $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); + $this->ctrl->forwardCommand($gui); + break; + + case 'ildidactictemplategui': + $this->ctrl->setReturn($this, 'edit'); + include_once './Services/DidacticTemplate/classes/class.ilDidacticTemplateGUI.php'; + $did = new ilDidacticTemplateGUI($this); + $this->ctrl->forwardCommand($did); + break; + case 'ilcolumngui': + $this->tabs_gui->setTabActive('none'); + $this->checkPermission("read"); + $this->viewObject(); + break; + + case 'ilbackgroundtaskhub': + include_once './Services/BackgroundTask/classes/class.ilBackgroundTaskHub.php'; + $bggui = new ilBackgroundTaskHub(); + $this->ctrl->forwardCommand($bggui); + break; + + case 'ilobjecttranslationgui': + $this->checkPermissionBool("write"); + $this->prepareOutput(); + $this->setSubTabs("settings_trans"); + include_once("./Services/Object/classes/class.ilObjectTranslationGUI.php"); + $transgui = new ilObjectTranslationGUI($this); + $this->ctrl->forwardCommand($transgui); + break; + + default: + + $this->prepareOutput(); + // cognos-blu-patch: begin + // removed timings forward + // cognos-blu-patch: end + + if (empty($cmd)) { + $cmd = "view"; + } + $cmd .= "Object"; + $this->$cmd(); + break; + } + + $this->addHeaderAction(); + } + + /** + * set tree + */ + public function setFolderTree($a_tree) + { + $this->folder_tree =&$a_tree; + } /** * Import file object @@ -238,415 +240,425 @@ class ilObjFolderGUI extends ilContainerGUI * @param type $parent_id * @param type $a_catch_errors */ - public function importFileObject($parent_id = null, $a_catch_errors = true) - { - $lng = $this->lng; - - if(parent::importFileObject($parent_id, $a_catch_errors)) - { - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $this->ctrl->returnToParent($this); - } - } - - /** - * Init object edit form - * - * @return ilPropertyFormGUI - */ - protected function initEditForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $obj_service = $this->getObjectService(); - - $lng->loadLanguageModule($this->object->getType()); - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this, "update")); - $form->setTitle($this->lng->txt($this->object->getType()."_edit")); - - // title - $ti = new ilTextInputGUI($this->lng->txt("title"), "title"); - $ti->setSize(min(40, ilObject::TITLE_LENGTH)); - $ti->setMaxLength(ilObject::TITLE_LENGTH); - $ti->setRequired(true); - $form->addItem($ti); - - // description - $ta = new ilTextAreaInputGUI($this->lng->txt("description"), "desc"); - $ta->setCols(40); - $ta->setRows(2); - $form->addItem($ta); - - // Show didactic template type - $this->initDidacticTemplate($form); - - $pres = new ilFormSectionHeaderGUI(); - $pres->setTitle($this->lng->txt('fold_presentation')); - $form->addItem($pres); - - // title and icon visibility - $form = $obj_service->commonSettings()->legacyForm($form, $this->object)->addTitleIconVisibility(); - - // top actions visibility - $form = $obj_service->commonSettings()->legacyForm($form, $this->object)->addTopActionsVisibility(); - - // custom icon - $form = $obj_service->commonSettings()->legacyForm($form, $this->object)->addIcon(); - - // tile image - $form = $obj_service->commonSettings()->legacyForm($form, $this->object)->addTileImage(); - - // list presentation - $form = $this->initListPresentationForm($form); - - $this->initSortingForm( - $form, - array( - ilContainer::SORT_INHERIT, - ilContainer::SORT_TITLE, - ilContainer::SORT_CREATION, - ilContainer::SORT_MANUAL - ) - ); - - $form->addCommandButton("update", $this->lng->txt("save")); - //$this->form->addCommandButton("cancelUpdate", $lng->txt("cancel")); - - return $form; - } - - protected function getEditFormCustomValues(array &$a_values) - { - // we cannot use $this->object->getOrderType() - // if set to inherit it will be translated to parent setting - include_once './Services/Container/classes/class.ilContainerSortingSettings.php'; - $sort = new ilContainerSortingSettings($this->object->getId()); - $a_values["sor"] = $sort->getSortMode(); - } - - protected function updateCustom(ilPropertyFormGUI $a_form) - { - $obj_service = $this->getObjectService(); - - // title icon visibility - $obj_service->commonSettings()->legacyForm($a_form, $this->object)->saveTitleIconVisibility(); - - // top actions visibility - $obj_service->commonSettings()->legacyForm($a_form, $this->object)->saveTopActionsVisibility(); - - // custom icon - $obj_service->commonSettings()->legacyForm($a_form, $this->object)->saveIcon(); - - // tile image - $obj_service->commonSettings()->legacyForm($a_form, $this->object)->saveTileImage(); - - // list presentation - $this->saveListPresentation($a_form); - - $this->saveSortingSettings($a_form); - } - - // BEGIN ChangeEvent show info screen on folder object - /** - * 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 showSummaryObject() - { - $this->ctrl->setCmd("showSummary"); - $this->ctrl->setCmdClass("ilinfoscreengui"); - $this->infoScreen(); - } - - protected function afterSave(ilObject $a_new_object) - { - include_once './Services/Container/classes/class.ilContainerSortingSettings.php'; - $sort = new ilContainerSortingSettings($a_new_object->getId()); - $sort->setSortMode(ilContainer::SORT_INHERIT); - $sort->update(); - - // always send a message - ilUtil::sendSuccess($this->lng->txt("fold_added"),true); - $this->ctrl->setParameter($this, "ref_id", $a_new_object->getRefId()); - $this->redirectToRefId($a_new_object->getRefId(), ""); - } - - /** - * 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 infoScreenObject() - { - $this->ctrl->setCmd("showSummary"); - $this->ctrl->setCmdClass("ilinfoscreengui"); - $this->infoScreen(); - } - - /** - * show information screen - */ - function infoScreen() - { - $ilAccess = $this->access; - - if (!$ilAccess->checkAccess("visible", "", $this->ref_id)) - { - $this->ilias->raiseError($this->lng->txt("msg_no_perm_read"),$this->ilias->error_obj->MESSAGE); - } - - include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); - $info = new ilInfoScreenGUI($this); - - $GLOBALS['ilTabs']->activateTab('info_short'); - - $info->enablePrivateNotes(); - - if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - $info->enableNews(); - } - - // no news editing for files, just notifications - $info->enableNewsEditing(false); - if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) - { - $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()); - - // forward the command - $this->ctrl->forwardCommand($info); - } - // END ChangeEvent show info screen on folder object - - /** - * Get tabs - */ - function getTabs() - { - $rbacsystem = $this->rbacsystem; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - $ilHelp = $this->help; - - $this->ctrl->setParameter($this,"ref_id",$this->ref_id); - - $ilHelp->setScreenIdComponent("fold"); - - $this->tabs_gui->setTabActive(""); - if ($rbacsystem->checkAccess('read',$this->ref_id)) - { - $this->tabs_gui->addTab("view_content", $lng->txt("content"), - $this->ctrl->getLinkTarget($this, "")); - - //BEGIN ChangeEvent add info tab to category object - $force_active = ($this->ctrl->getNextClass() == "ilinfoscreengui" - || strtolower($_GET["cmdClass"]) == "ilnotegui") - ? true - : false; - $this->tabs_gui->addTarget("info_short", - $this->ctrl->getLinkTargetByClass( - array("ilobjfoldergui", "ilinfoscreengui"), "showSummary"), - array("showSummary","", "infoScreen"), - "", "", $force_active); - //END ChangeEvent add info tab to category object - } - - if ($rbacsystem->checkAccess('write',$this->ref_id)) - { - $this->tabs_gui->addTarget("settings", - $this->ctrl->getLinkTarget($this, "edit"), "edit", "", "", ($ilCtrl->getCmd() == "edit")); - } - - // learning progress - include_once './Services/Tracking/classes/class.ilLearningProgressAccess.php'; - if(ilLearningProgressAccess::checkAccess($this->object->getRefId())) - { - $this->tabs_gui->addTarget('learning_progress', - $this->ctrl->getLinkTargetByClass(array('ilobjfoldergui','illearningprogressgui'),''), - '', - array('illplistofobjectsgui','illplistofsettingsgui','illearningprogressgui','illplistofprogressgui')); - } - - if($ilAccess->checkAccess('write','',$this->object->getRefId())) - { - $this->tabs_gui->addTarget( - 'export', - $this->ctrl->getLinkTargetByClass('ilexportgui',''), - 'export', - 'ilexportgui' - ); - } - - - if ($rbacsystem->checkAccess('edit_permission',$this->ref_id)) - { - $this->tabs_gui->addTarget("perm_settings", - $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm"), array("perm","info","owner"), 'ilpermissiongui'); - } - - // show clipboard in repository - if ($_GET["baseClass"] == "ilRepositoryGUI" and !empty($_SESSION['il_rep_clipboard'])) - { - $this->tabs_gui->addTarget("clipboard", - $this->ctrl->getLinkTarget($this, "clipboard"), "clipboard", get_class($this)); - } - - } - - /** - * goto target group - */ - public static function _goto($a_target) - { - global $DIC; - - $ilAccess = $DIC->access(); - $ilErr = $DIC["ilErr"]; - $lng = $DIC->language(); - - if ($ilAccess->checkAccess("read", "", $a_target)) - { - ilObjectGUI::_gotoRepositoryNode($a_target); - } - $ilErr->raiseError($lng->txt("msg_no_perm_read"), $ilErr->FATAL); - } - - - public function downloadFolderObject () { - $ilAccess = $this->access; - $ilErr = $this->error; - $lng = $this->lng; - - if (!$ilAccess->checkAccess("read", "", $this->ref_id)) - { - $this->ilias->raiseError($this->lng->txt("msg_no_perm_read"),$this->ilias->error_obj->MESSAGE); - } - $filename = $this->object->downloadFolder(); - ilUtil::deliverFile($filename, ilUtil::getASCIIFilename($this->object->getTitle().".zip")); - } - - /** - * Modify Item ListGUI for presentation in container - * @global type $tree - * @param type $a_item_list_gui - * @param type $a_item_data - * @param type $a_show_path - */ - public function modifyItemGUI($a_item_list_gui, $a_item_data, $a_show_path) - { - $tree = $this->tree; - - // if folder is in a course, modify item list gui according to course requirements - if ($course_ref_id = $tree->checkForParentType($this->object->getRefId(),'crs')) - { - include_once("./Modules/Course/classes/class.ilObjCourse.php"); - include_once("./Modules/Course/classes/class.ilObjCourseGUI.php"); - $course_obj_id = ilObject::_lookupObjId($course_ref_id); - ilObjCourseGUI::_modifyItemGUI( - $a_item_list_gui, - 'ilcoursecontentgui', - $a_item_data, - $a_show_path, - ilObjCourse::_lookupAboStatus($course_obj_id), - $course_ref_id, - $course_obj_id, - $this->object->getRefId() - ); - } - } - - protected function forwardToTimingsView() - { - $tree = $this->tree; - - if(!$crs_ref = $tree->checkForParentType($this->ref_id, 'crs')) - { - return false; - } - include_once './Modules/Course/classes/class.ilObjCourse.php'; - if(!$this->ctrl->getCmd() and ilObjCourse::_lookupViewMode(ilObject::_lookupObjId($crs_ref)) == ilContainer::VIEW_TIMING) - { - if(!isset($_SESSION['crs_timings'])) { - $_SESSION['crs_timings'] = true; - } - - if($_SESSION['crs_timings'] == true) { - include_once './Modules/Course/classes/class.ilCourseContentGUI.php'; - $course_content_obj = new ilCourseContentGUI($this); - $this->ctrl->setCmdClass(get_class($course_content_obj)); - $this->ctrl->setCmd('editUserTimings'); - $this->ctrl->forwardCommand($course_content_obj); - return true; - } - } - $_SESSION['crs_timings'] = false; - return false; - } - - /** - * Edit - * - * @param - * @return - */ - public function editObject() - { - $ilTabs = $this->tabs; - $ilErr = $this->error; - - $this->setSubTabs("settings"); - $ilTabs->activateTab("settings"); - - if (!$this->checkPermissionBool("write")) - { - $ilErr->raiseError($this->lng->txt("msg_no_perm_write"),$ilErr->MESSAGE); - } - - $form = $this->initEditForm(); - $values = $this->getEditFormValues(); - if($values) - { - $form->setValuesByArray($values,TRUE); - } - $GLOBALS['tpl']->setContent($form->getHTML()); - } - - - /** - * Set sub tabs - */ - function setSubTabs($a_tab) - { - $ilTabs = $this->tabs; - $lng = $this->lng; - - $ilTabs->addSubTab("settings", - $lng->txt("fold_settings"), - $this->ctrl->getLinkTarget($this,'edit')); - - $this->tabs_gui->addSubTab("settings_trans", - $this->lng->txt("obj_multilinguality"), - $this->ctrl->getLinkTargetByClass("ilobjecttranslationgui", "")); - - $ilTabs->activateSubTab($a_tab); - $ilTabs->activateTab("settings"); - } + public function importFileObject($parent_id = null, $a_catch_errors = true) + { + $lng = $this->lng; + + if (parent::importFileObject($parent_id, $a_catch_errors)) { + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $this->ctrl->returnToParent($this); + } + } + + /** + * Init object edit form + * + * @return ilPropertyFormGUI + */ + protected function initEditForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $obj_service = $this->getObjectService(); + + $lng->loadLanguageModule($this->object->getType()); + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this, "update")); + $form->setTitle($this->lng->txt($this->object->getType() . "_edit")); + + // title + $ti = new ilTextInputGUI($this->lng->txt("title"), "title"); + $ti->setSize(min(40, ilObject::TITLE_LENGTH)); + $ti->setMaxLength(ilObject::TITLE_LENGTH); + $ti->setRequired(true); + $form->addItem($ti); + + // description + $ta = new ilTextAreaInputGUI($this->lng->txt("description"), "desc"); + $ta->setCols(40); + $ta->setRows(2); + $form->addItem($ta); + + // Show didactic template type + $this->initDidacticTemplate($form); + + $pres = new ilFormSectionHeaderGUI(); + $pres->setTitle($this->lng->txt('fold_presentation')); + $form->addItem($pres); + + // title and icon visibility + $form = $obj_service->commonSettings()->legacyForm($form, $this->object)->addTitleIconVisibility(); + + // top actions visibility + $form = $obj_service->commonSettings()->legacyForm($form, $this->object)->addTopActionsVisibility(); + + // custom icon + $form = $obj_service->commonSettings()->legacyForm($form, $this->object)->addIcon(); + + // tile image + $form = $obj_service->commonSettings()->legacyForm($form, $this->object)->addTileImage(); + + // list presentation + $form = $this->initListPresentationForm($form); + + $this->initSortingForm( + $form, + array( + ilContainer::SORT_INHERIT, + ilContainer::SORT_TITLE, + ilContainer::SORT_CREATION, + ilContainer::SORT_MANUAL + ) + ); + + $form->addCommandButton("update", $this->lng->txt("save")); + //$this->form->addCommandButton("cancelUpdate", $lng->txt("cancel")); + + return $form; + } + + protected function getEditFormCustomValues(array &$a_values) + { + // we cannot use $this->object->getOrderType() + // if set to inherit it will be translated to parent setting + include_once './Services/Container/classes/class.ilContainerSortingSettings.php'; + $sort = new ilContainerSortingSettings($this->object->getId()); + $a_values["sor"] = $sort->getSortMode(); + } + + protected function updateCustom(ilPropertyFormGUI $a_form) + { + $obj_service = $this->getObjectService(); + + // title icon visibility + $obj_service->commonSettings()->legacyForm($a_form, $this->object)->saveTitleIconVisibility(); + + // top actions visibility + $obj_service->commonSettings()->legacyForm($a_form, $this->object)->saveTopActionsVisibility(); + + // custom icon + $obj_service->commonSettings()->legacyForm($a_form, $this->object)->saveIcon(); + + // tile image + $obj_service->commonSettings()->legacyForm($a_form, $this->object)->saveTileImage(); + + // list presentation + $this->saveListPresentation($a_form); + + $this->saveSortingSettings($a_form); + } + + // BEGIN ChangeEvent show info screen on folder object + /** + * 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 showSummaryObject() + { + $this->ctrl->setCmd("showSummary"); + $this->ctrl->setCmdClass("ilinfoscreengui"); + $this->infoScreen(); + } + + protected function afterSave(ilObject $a_new_object) + { + include_once './Services/Container/classes/class.ilContainerSortingSettings.php'; + $sort = new ilContainerSortingSettings($a_new_object->getId()); + $sort->setSortMode(ilContainer::SORT_INHERIT); + $sort->update(); + + // always send a message + ilUtil::sendSuccess($this->lng->txt("fold_added"), true); + $this->ctrl->setParameter($this, "ref_id", $a_new_object->getRefId()); + $this->redirectToRefId($a_new_object->getRefId(), ""); + } + + /** + * 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 infoScreenObject() + { + $this->ctrl->setCmd("showSummary"); + $this->ctrl->setCmdClass("ilinfoscreengui"); + $this->infoScreen(); + } + + /** + * show information screen + */ + public function infoScreen() + { + $ilAccess = $this->access; + + if (!$ilAccess->checkAccess("visible", "", $this->ref_id)) { + $this->ilias->raiseError($this->lng->txt("msg_no_perm_read"), $this->ilias->error_obj->MESSAGE); + } + + include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); + $info = new ilInfoScreenGUI($this); + + $GLOBALS['ilTabs']->activateTab('info_short'); + + $info->enablePrivateNotes(); + + if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) { + $info->enableNews(); + } + + // no news editing for files, just notifications + $info->enableNewsEditing(false); + if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) { + $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()); + + // forward the command + $this->ctrl->forwardCommand($info); + } + // END ChangeEvent show info screen on folder object + + /** + * Get tabs + */ + public function getTabs() + { + $rbacsystem = $this->rbacsystem; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + $ilHelp = $this->help; + + $this->ctrl->setParameter($this, "ref_id", $this->ref_id); + + $ilHelp->setScreenIdComponent("fold"); + + $this->tabs_gui->setTabActive(""); + if ($rbacsystem->checkAccess('read', $this->ref_id)) { + $this->tabs_gui->addTab( + "view_content", + $lng->txt("content"), + $this->ctrl->getLinkTarget($this, "") + ); + + //BEGIN ChangeEvent add info tab to category object + $force_active = ($this->ctrl->getNextClass() == "ilinfoscreengui" + || strtolower($_GET["cmdClass"]) == "ilnotegui") + ? true + : false; + $this->tabs_gui->addTarget( + "info_short", + $this->ctrl->getLinkTargetByClass( + array("ilobjfoldergui", "ilinfoscreengui"), + "showSummary" + ), + array("showSummary","", "infoScreen"), + "", + "", + $force_active + ); + //END ChangeEvent add info tab to category object + } + + if ($rbacsystem->checkAccess('write', $this->ref_id)) { + $this->tabs_gui->addTarget( + "settings", + $this->ctrl->getLinkTarget($this, "edit"), + "edit", + "", + "", + ($ilCtrl->getCmd() == "edit") + ); + } + + // learning progress + include_once './Services/Tracking/classes/class.ilLearningProgressAccess.php'; + if (ilLearningProgressAccess::checkAccess($this->object->getRefId())) { + $this->tabs_gui->addTarget( + 'learning_progress', + $this->ctrl->getLinkTargetByClass(array('ilobjfoldergui','illearningprogressgui'), ''), + '', + array('illplistofobjectsgui','illplistofsettingsgui','illearningprogressgui','illplistofprogressgui') + ); + } + + if ($ilAccess->checkAccess('write', '', $this->object->getRefId())) { + $this->tabs_gui->addTarget( + 'export', + $this->ctrl->getLinkTargetByClass('ilexportgui', ''), + 'export', + 'ilexportgui' + ); + } + + + if ($rbacsystem->checkAccess('edit_permission', $this->ref_id)) { + $this->tabs_gui->addTarget( + "perm_settings", + $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm"), + array("perm","info","owner"), + 'ilpermissiongui' + ); + } + + // show clipboard in repository + if ($_GET["baseClass"] == "ilRepositoryGUI" and !empty($_SESSION['il_rep_clipboard'])) { + $this->tabs_gui->addTarget( + "clipboard", + $this->ctrl->getLinkTarget($this, "clipboard"), + "clipboard", + get_class($this) + ); + } + } + + /** + * goto target group + */ + public static function _goto($a_target) + { + global $DIC; + + $ilAccess = $DIC->access(); + $ilErr = $DIC["ilErr"]; + $lng = $DIC->language(); + + if ($ilAccess->checkAccess("read", "", $a_target)) { + ilObjectGUI::_gotoRepositoryNode($a_target); + } + $ilErr->raiseError($lng->txt("msg_no_perm_read"), $ilErr->FATAL); + } + + + public function downloadFolderObject() + { + $ilAccess = $this->access; + $ilErr = $this->error; + $lng = $this->lng; + + if (!$ilAccess->checkAccess("read", "", $this->ref_id)) { + $this->ilias->raiseError($this->lng->txt("msg_no_perm_read"), $this->ilias->error_obj->MESSAGE); + } + $filename = $this->object->downloadFolder(); + ilUtil::deliverFile($filename, ilUtil::getASCIIFilename($this->object->getTitle() . ".zip")); + } + + /** + * Modify Item ListGUI for presentation in container + * @global type $tree + * @param type $a_item_list_gui + * @param type $a_item_data + * @param type $a_show_path + */ + public function modifyItemGUI($a_item_list_gui, $a_item_data, $a_show_path) + { + $tree = $this->tree; + + // if folder is in a course, modify item list gui according to course requirements + if ($course_ref_id = $tree->checkForParentType($this->object->getRefId(), 'crs')) { + include_once("./Modules/Course/classes/class.ilObjCourse.php"); + include_once("./Modules/Course/classes/class.ilObjCourseGUI.php"); + $course_obj_id = ilObject::_lookupObjId($course_ref_id); + ilObjCourseGUI::_modifyItemGUI( + $a_item_list_gui, + 'ilcoursecontentgui', + $a_item_data, + $a_show_path, + ilObjCourse::_lookupAboStatus($course_obj_id), + $course_ref_id, + $course_obj_id, + $this->object->getRefId() + ); + } + } + + protected function forwardToTimingsView() + { + $tree = $this->tree; + + if (!$crs_ref = $tree->checkForParentType($this->ref_id, 'crs')) { + return false; + } + include_once './Modules/Course/classes/class.ilObjCourse.php'; + if (!$this->ctrl->getCmd() and ilObjCourse::_lookupViewMode(ilObject::_lookupObjId($crs_ref)) == ilContainer::VIEW_TIMING) { + if (!isset($_SESSION['crs_timings'])) { + $_SESSION['crs_timings'] = true; + } + + if ($_SESSION['crs_timings'] == true) { + include_once './Modules/Course/classes/class.ilCourseContentGUI.php'; + $course_content_obj = new ilCourseContentGUI($this); + $this->ctrl->setCmdClass(get_class($course_content_obj)); + $this->ctrl->setCmd('editUserTimings'); + $this->ctrl->forwardCommand($course_content_obj); + return true; + } + } + $_SESSION['crs_timings'] = false; + return false; + } + + /** + * Edit + * + * @param + * @return + */ + public function editObject() + { + $ilTabs = $this->tabs; + $ilErr = $this->error; + + $this->setSubTabs("settings"); + $ilTabs->activateTab("settings"); + + if (!$this->checkPermissionBool("write")) { + $ilErr->raiseError($this->lng->txt("msg_no_perm_write"), $ilErr->MESSAGE); + } + + $form = $this->initEditForm(); + $values = $this->getEditFormValues(); + if ($values) { + $form->setValuesByArray($values, true); + } + $GLOBALS['tpl']->setContent($form->getHTML()); + } + + + /** + * Set sub tabs + */ + public function setSubTabs($a_tab) + { + $ilTabs = $this->tabs; + $lng = $this->lng; + + $ilTabs->addSubTab( + "settings", + $lng->txt("fold_settings"), + $this->ctrl->getLinkTarget($this, 'edit') + ); + + $this->tabs_gui->addSubTab( + "settings_trans", + $this->lng->txt("obj_multilinguality"), + $this->ctrl->getLinkTargetByClass("ilobjecttranslationgui", "") + ); + + $ilTabs->activateSubTab($a_tab); + $ilTabs->activateTab("settings"); + } } // END class.ilObjFolderGUI -?> diff --git a/Modules/Folder/classes/class.ilObjFolderListGUI.php b/Modules/Folder/classes/class.ilObjFolderListGUI.php index e8947f15cffcb2ec6c305ef98a103726633485f0..772e0cb6320d7a17ada601c4ab21426815550a6b 100644 --- a/Modules/Folder/classes/class.ilObjFolderListGUI.php +++ b/Modules/Folder/classes/class.ilObjFolderListGUI.php @@ -1,24 +1,24 @@ static_link_enabled = true; - $this->delete_enabled = true; - $this->cut_enabled = true; - $this->copy_enabled = true; - $this->subscribe_enabled = true; - $this->link_enabled = false; - $this->info_screen_enabled = true; - $this->type = "fold"; - $this->gui_class_name = "ilobjfoldergui"; + /** + * initialisation + */ + public function init() + { + $this->static_link_enabled = true; + $this->delete_enabled = true; + $this->cut_enabled = true; + $this->copy_enabled = true; + $this->subscribe_enabled = true; + $this->link_enabled = false; + $this->info_screen_enabled = true; + $this->type = "fold"; + $this->gui_class_name = "ilobjfoldergui"; - // general commands array - include_once('./Modules/Folder/classes/class.ilObjFolderAccess.php'); - $this->commands = ilObjFolderAccess::_getCommands(); - } + // general commands array + include_once('./Modules/Folder/classes/class.ilObjFolderAccess.php'); + $this->commands = ilObjFolderAccess::_getCommands(); + } - /** - * Get item properties - * - * @return array array of property arrays: - * "alert" (boolean) => display as an alert property (usually in red) - * "property" (string) => property name - * "value" (string) => property value - */ - function getProperties() - { - $props = parent::getProperties(); + /** + * Get item properties + * + * @return array array of property arrays: + * "alert" (boolean) => display as an alert property (usually in red) + * "property" (string) => property name + * "value" (string) => property value + */ + public function getProperties() + { + $props = parent::getProperties(); - return $props; - } - - /** - * Get command link url. - * - * @param int $a_ref_id reference id - * @param string $a_cmd command - * - */ - function getCommandLink($a_cmd) - { - $ilCtrl = $this->ctrl; - - // BEGIN WebDAV: Mount webfolder. - switch ($a_cmd) - { - case 'mount_webfolder' : - require_once ('Services/WebDAV/classes/class.ilDAVActivationChecker.php'); - if (ilDAVActivationChecker::_isActive()) - { - require_once ('Services/WebDAV/classes/class.ilWebDAVUtil.php'); - $dav_util = ilWebDAVUtil::getInstance(); - - // XXX: The following is a very dirty, ugly trick. - // To mount URI needs to be put into two attributes: - // href and folder. This hack returns both attributes - // like this: http://...mount_uri..." folder="http://...folder_uri... - $cmd_link = $dav_util->getMountURI($this->ref_id, $this->title, $this->parent). - '" folder="'.$dav_util->getFolderURI($this->ref_id, $this->title, $this->parent); - break; - } // Fall through, when plugin is inactive. - default : - // separate method for this line - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $this->ref_id); - $cmd_link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", $a_cmd); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - break; - } - - return $cmd_link; - // END WebDAV: Mount Webfolder - } - - // BEGIN WebDAV: mount_webfolder in _blank frame - /** - * Get command target frame. - * - * Overwrite this method if link frame is not current frame - * - * @param string $a_cmd command - * - * @return string command target frame - */ - function getCommandFrame($a_cmd) - { - // begin-patch fm - return parent::getCommandFrame($a_cmd); - // end-patch fm - } - // END WebDAV: mount_webfolder in _blank frame + return $props; + } + /** + * Get command link url. + * + * @param int $a_ref_id reference id + * @param string $a_cmd command + * + */ + public function getCommandLink($a_cmd) + { + $ilCtrl = $this->ctrl; + + // BEGIN WebDAV: Mount webfolder. + switch ($a_cmd) { + case 'mount_webfolder': + require_once('Services/WebDAV/classes/class.ilDAVActivationChecker.php'); + if (ilDAVActivationChecker::_isActive()) { + require_once('Services/WebDAV/classes/class.ilWebDAVUtil.php'); + $dav_util = ilWebDAVUtil::getInstance(); + + // XXX: The following is a very dirty, ugly trick. + // To mount URI needs to be put into two attributes: + // href and folder. This hack returns both attributes + // like this: http://...mount_uri..." folder="http://...folder_uri... + $cmd_link = $dav_util->getMountURI($this->ref_id, $this->title, $this->parent) . + '" folder="' . $dav_util->getFolderURI($this->ref_id, $this->title, $this->parent); + break; + } // Fall through, when plugin is inactive. + // no break + default: + // separate method for this line + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $this->ref_id); + $cmd_link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", $a_cmd); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + break; + } + + return $cmd_link; + // END WebDAV: Mount Webfolder + } + // BEGIN WebDAV: mount_webfolder in _blank frame + /** + * Get command target frame. + * + * Overwrite this method if link frame is not current frame + * + * @param string $a_cmd command + * + * @return string command target frame + */ + public function getCommandFrame($a_cmd) + { + // begin-patch fm + return parent::getCommandFrame($a_cmd); + // end-patch fm + } + // END WebDAV: mount_webfolder in _blank frame } // END class.ilObjFolderListGUI -?> diff --git a/Modules/Glossary/classes/class.ilECSGlossarySettings.php b/Modules/Glossary/classes/class.ilECSGlossarySettings.php index 03fe762e63aa0256dcd6a7a4edce11fa3f01b378..faf77e7fe88accfa4d60013c8702438925a5f003 100644 --- a/Modules/Glossary/classes/class.ilECSGlossarySettings.php +++ b/Modules/Glossary/classes/class.ilECSGlossarySettings.php @@ -1,32 +1,30 @@ - -* $Id: class.ilObjCourseGUI.php 31646 2011-11-14 11:39:37Z jluetzen $ -* -* @ingroup Modules/Glossary -*/ -class ilECSGlossarySettings extends ilECSObjectSettings -{ - protected function getECSObjectType() - { - return '/campusconnect/glossaries'; - } - - protected function buildJson(ilECSSetting $a_server) - { - $json = $this->getJsonCore('application/ecs-glossary'); - - $json->availability = $this->content_obj->getOnline() ? 'online' : 'offline'; - - return $json; - } -} - -?> \ No newline at end of file + +* $Id: class.ilObjCourseGUI.php 31646 2011-11-14 11:39:37Z jluetzen $ +* +* @ingroup Modules/Glossary +*/ +class ilECSGlossarySettings extends ilECSObjectSettings +{ + protected function getECSObjectType() + { + return '/campusconnect/glossaries'; + } + + protected function buildJson(ilECSSetting $a_server) + { + $json = $this->getJsonCore('application/ecs-glossary'); + + $json->availability = $this->content_obj->getOnline() ? 'online' : 'offline'; + + return $json; + } +} diff --git a/Modules/Glossary/classes/class.ilGloAdvColSortInputGUI.php b/Modules/Glossary/classes/class.ilGloAdvColSortInputGUI.php index 5ce03bcfbe33b4f17f57dc1e0b90f4a284dad563..c3123df3da7395b585677b5760283ed4c74d5771 100644 --- a/Modules/Glossary/classes/class.ilGloAdvColSortInputGUI.php +++ b/Modules/Glossary/classes/class.ilGloAdvColSortInputGUI.php @@ -8,131 +8,125 @@ include_once 'Services/Form/classes/class.ilFormPropertyGUI.php'; * Please note, that data us already an array, we do not use the MultipleValues * interface here. * - * @author Alex Killing + * @author Alex Killing * @version $Id$ * @ingroup ModulesGlossary */ class ilGloAdvColSortInputGUI extends ilFormPropertyGUI { - - /** - * Constructor - * - * @param - */ - function __construct($a_title = "", $a_id = "") - { - global $DIC; + + /** + * Constructor + * + * @param + */ + public function __construct($a_title = "", $a_id = "") + { + global $DIC; - $this->lng = $DIC->language(); - parent::__construct($a_title, $a_id); - $this->setType("glo_adv_col_sort"); - } - - /** - * Set Value. - * - * @param string $a_value Value - */ - function setValue($a_value) - { - $this->value = $a_value; - } + $this->lng = $DIC->language(); + parent::__construct($a_title, $a_id); + $this->setType("glo_adv_col_sort"); + } + + /** + * Set Value. + * + * @param string $a_value Value + */ + public function setValue($a_value) + { + $this->value = $a_value; + } - /** - * Get Value. - * - * @return string Value - */ - function getValue() - { - return $this->value; - } + /** + * Get Value. + * + * @return string Value + */ + public function getValue() + { + return $this->value; + } - - /** - * Input should always be valid, since we sort only - * - * @return boolean - */ - function checkInput() - { - if (is_array($_POST[$this->getPostVar()])) { - foreach ($_POST[$this->getPostVar()] as $k => $v) - { - $_POST[$this->getPostVar()][$k]["id"] = ilUtil::stripSlashes($_POST[$this->getPostVar()][$k]["id"]); - $_POST[$this->getPostVar()][$k]["text"] = ilUtil::stripSlashes($_POST[$this->getPostVar()][$k]["text"]); - } - } - else - { - $_POST[$this->getPostVar()] = array(); - } + + /** + * Input should always be valid, since we sort only + * + * @return boolean + */ + public function checkInput() + { + if (is_array($_POST[$this->getPostVar()])) { + foreach ($_POST[$this->getPostVar()] as $k => $v) { + $_POST[$this->getPostVar()][$k]["id"] = ilUtil::stripSlashes($_POST[$this->getPostVar()][$k]["id"]); + $_POST[$this->getPostVar()][$k]["text"] = ilUtil::stripSlashes($_POST[$this->getPostVar()][$k]["text"]); + } + } else { + $_POST[$this->getPostVar()] = array(); + } - return true; - } + return true; + } - /** - * render - */ - function render() - { - $lng = $this->lng; - - $tpl = new ilTemplate("tpl.adv_col_sort_input.html", true, true, "Modules/Glossary"); - include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); - if (is_array($this->getValue())) - { - foreach ($this->getValue() as $k => $v) - { - $tpl->setCurrentBlock("item"); - $tpl->setVariable("TEXT", $v["text"]); - $tpl->setVariable("ID", $this->getFieldId()."~".$k); - $tpl->setVariable("DOWN", ilGlyphGUI::get(ilGlyphGUI::DOWN)); - $tpl->setVariable("TXT_DOWN", $lng->txt("down")); - $tpl->setVariable("UP", ilGlyphGUI::get(ilGlyphGUI::UP)); - $tpl->setVariable("TXT_UP", $lng->txt("up")); - $tpl->setVariable('NAME', $this->getPostVar()."[".$k."][id]"); - $tpl->setVariable('TNAME', $this->getPostVar()."[".$k."][text]"); - $tpl->setVariable('VAL', ilUtil::prepareFormOutput($v["id"])); - $tpl->setVariable('TVAL', ilUtil::prepareFormOutput($v["text"])); - $tpl->parseCurrentBlock(); - } - } - - return $tpl->get(); - } - - /** - * Insert property html - * - */ - function insert(&$a_tpl) - { - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $this->render()); - $a_tpl->parseCurrentBlock(); - } - - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - if ($this->getPostVar() && isset($a_values[$this->getPostVar()])) - { - $this->setValue($a_values[$this->getPostVar()]); - } - } - - /** - * Get HTML for table filter - */ - function getTableFilterHTML() - { - $html = $this->render(); - return $html; - } + /** + * render + */ + public function render() + { + $lng = $this->lng; + + $tpl = new ilTemplate("tpl.adv_col_sort_input.html", true, true, "Modules/Glossary"); + include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); + if (is_array($this->getValue())) { + foreach ($this->getValue() as $k => $v) { + $tpl->setCurrentBlock("item"); + $tpl->setVariable("TEXT", $v["text"]); + $tpl->setVariable("ID", $this->getFieldId() . "~" . $k); + $tpl->setVariable("DOWN", ilGlyphGUI::get(ilGlyphGUI::DOWN)); + $tpl->setVariable("TXT_DOWN", $lng->txt("down")); + $tpl->setVariable("UP", ilGlyphGUI::get(ilGlyphGUI::UP)); + $tpl->setVariable("TXT_UP", $lng->txt("up")); + $tpl->setVariable('NAME', $this->getPostVar() . "[" . $k . "][id]"); + $tpl->setVariable('TNAME', $this->getPostVar() . "[" . $k . "][text]"); + $tpl->setVariable('VAL', ilUtil::prepareFormOutput($v["id"])); + $tpl->setVariable('TVAL', ilUtil::prepareFormOutput($v["text"])); + $tpl->parseCurrentBlock(); + } + } + + return $tpl->get(); + } + + /** + * Insert property html + * + */ + public function insert(&$a_tpl) + { + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $this->render()); + $a_tpl->parseCurrentBlock(); + } + + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + if ($this->getPostVar() && isset($a_values[$this->getPostVar()])) { + $this->setValue($a_values[$this->getPostVar()]); + } + } + + /** + * Get HTML for table filter + */ + public function getTableFilterHTML() + { + $html = $this->render(); + return $html; + } } diff --git a/Modules/Glossary/classes/class.ilGlossaryAct.php b/Modules/Glossary/classes/class.ilGlossaryAct.php index 4521b57f158597a13d7f12331fe085463fffd7a9..112c29976ee6893c151dc6bde3d086bbbc94c06f 100644 --- a/Modules/Glossary/classes/class.ilGlossaryAct.php +++ b/Modules/Glossary/classes/class.ilGlossaryAct.php @@ -11,112 +11,100 @@ */ class ilGlossaryAct { - /** - * @var ilObjGlossary - */ - protected $glossary; - - /** - * @var ilObjUser acting user - */ - protected $user; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * ilGlossaryAct constructor. - * @param ilObjGlossary $a_glossary - * @param ilObjUser $a_user - */ - protected function __construct(ilObjGlossary $a_glossary, ilObjUser $a_user) - { - global $DIC; - - $this->access = $DIC->access(); - $this->glossary = $a_glossary; - $this->user = $a_user; - } - - /** - * Get instance - * @param ilObjGlossary $a_glossary - * @param ilObjUser $a_user - * @return ilGlossaryAct - */ - static function getInstance(ilObjGlossary $a_glossary, ilObjUser $a_user) - { - return new self($a_glossary, $a_user); - } - - /** - * Copy term - * - * @param ilObjGlossary $a_source_glossary - * @param int $a_term_id term id - */ - function copyTerm(ilObjGlossary $a_source_glossary, $a_term_id) - { - if (!$this->access->checkAccessOfUser($this->user->getId(), "write", "", $this->glossary->getRefId())) - { - return; - } - - if (!$this->access->checkAccessOfUser($this->user->getId(), "read", "", $a_source_glossary->getRefId())) - { - return; - } - - include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - if (ilGlossaryTerm::_lookGlossaryID($a_term_id) != $a_source_glossary->getId()) - { - return; - } - - ilGlossaryTerm::_copyTerm($a_term_id, $this->glossary->getId()); - } - - - /** - * Reference a term of another glossary in current glossary - * - * @param ilObjGlossary $a_source_glossary - * @param int[] $a_term_ids - */ - function referenceTerms(ilObjGlossary $a_source_glossary, $a_term_ids) - { - if (!$this->access->checkAccessOfUser($this->user->getId(), "write", "", $this->glossary->getRefId())) - { - return; - } - - if (!$this->access->checkAccessOfUser($this->user->getId(), "read", "", $a_source_glossary->getRefId())) - { - return; - } - - include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - include_once("./Modules/Glossary/classes/class.ilGlossaryTermReferences.php"); - $refs = new ilGlossaryTermReferences($this->glossary->getId()); - foreach ($a_term_ids as $term_id) - { - if (ilGlossaryTerm::_lookGlossaryID($term_id) != $a_source_glossary->getId()) - { - continue; - } - - if ($this->glossary->getId() == $a_source_glossary->getId()) - { - continue; - } - $refs->addTerm($term_id); - } - $refs->update(); - } - - + /** + * @var ilObjGlossary + */ + protected $glossary; + + /** + * @var ilObjUser acting user + */ + protected $user; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * ilGlossaryAct constructor. + * @param ilObjGlossary $a_glossary + * @param ilObjUser $a_user + */ + protected function __construct(ilObjGlossary $a_glossary, ilObjUser $a_user) + { + global $DIC; + + $this->access = $DIC->access(); + $this->glossary = $a_glossary; + $this->user = $a_user; + } + + /** + * Get instance + * @param ilObjGlossary $a_glossary + * @param ilObjUser $a_user + * @return ilGlossaryAct + */ + public static function getInstance(ilObjGlossary $a_glossary, ilObjUser $a_user) + { + return new self($a_glossary, $a_user); + } + + /** + * Copy term + * + * @param ilObjGlossary $a_source_glossary + * @param int $a_term_id term id + */ + public function copyTerm(ilObjGlossary $a_source_glossary, $a_term_id) + { + if (!$this->access->checkAccessOfUser($this->user->getId(), "write", "", $this->glossary->getRefId())) { + return; + } + + if (!$this->access->checkAccessOfUser($this->user->getId(), "read", "", $a_source_glossary->getRefId())) { + return; + } + + include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + if (ilGlossaryTerm::_lookGlossaryID($a_term_id) != $a_source_glossary->getId()) { + return; + } + + ilGlossaryTerm::_copyTerm($a_term_id, $this->glossary->getId()); + } + + + /** + * Reference a term of another glossary in current glossary + * + * @param ilObjGlossary $a_source_glossary + * @param int[] $a_term_ids + */ + public function referenceTerms(ilObjGlossary $a_source_glossary, $a_term_ids) + { + if (!$this->access->checkAccessOfUser($this->user->getId(), "write", "", $this->glossary->getRefId())) { + return; + } + + if (!$this->access->checkAccessOfUser($this->user->getId(), "read", "", $a_source_glossary->getRefId())) { + return; + } + + include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + include_once("./Modules/Glossary/classes/class.ilGlossaryTermReferences.php"); + $refs = new ilGlossaryTermReferences($this->glossary->getId()); + foreach ($a_term_ids as $term_id) { + if (ilGlossaryTerm::_lookGlossaryID($term_id) != $a_source_glossary->getId()) { + continue; + } + + if ($this->glossary->getId() == $a_source_glossary->getId()) { + continue; + } + $refs->addTerm($term_id); + } + $refs->update(); + } } - -?> \ No newline at end of file diff --git a/Modules/Glossary/classes/class.ilGlossaryAdvMetaDataAdapter.php b/Modules/Glossary/classes/class.ilGlossaryAdvMetaDataAdapter.php index ee7c599e1873e0c2fd50e0a108ca376ec4322f1e..e791c1d69fd45a4525989e4964f9dc0b7c12349d 100644 --- a/Modules/Glossary/classes/class.ilGlossaryAdvMetaDataAdapter.php +++ b/Modules/Glossary/classes/class.ilGlossaryAdvMetaDataAdapter.php @@ -3,171 +3,161 @@ /* Copyright (c) 1998-2012 ILIAS open source, Extended GPL, see docs/LICENSE */ /** - * Advanced meta data adapter + * Advanced meta data adapter * * @author Alex Killing * @version $Id$ - * @ingroup + * @ingroup */ class ilGlossaryAdvMetaDataAdapter { - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * Constructor - */ - function __construct($a_glo_ref_id) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_glo_ref_id) + { + global $DIC; - $this->db = $DIC->database(); - $this->lng = $DIC->language(); - $this->glo_id = ilObject::_lookupObjectId($a_glo_ref_id); - $this->glo_ref_id = $a_glo_ref_id; - } - + $this->db = $DIC->database(); + $this->lng = $DIC->language(); + $this->glo_id = ilObject::_lookupObjectId($a_glo_ref_id); + $this->glo_ref_id = $a_glo_ref_id; + } + - /** - * Get all advanced metadata fields - */ - function getAllFields() - { - $fields = array(); - include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecord.php'); - $recs = ilAdvancedMDRecord::_getSelectedRecordsByObject("glo", $this->glo_ref_id, "term"); + /** + * Get all advanced metadata fields + */ + public function getAllFields() + { + $fields = array(); + include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecord.php'); + $recs = ilAdvancedMDRecord::_getSelectedRecordsByObject("glo", $this->glo_ref_id, "term"); - foreach($recs as $record_obj) - { - include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDFieldDefinition.php'); - foreach (ilAdvancedMDFieldDefinition::getInstancesByRecordId($record_obj->getRecordId()) as $def) - { - $fields[$def->getFieldId()] = array( - "id" => $def->getFieldId(), - "title" => $def->getTitle(), - "type" => $def->getType() - ); - } - } + foreach ($recs as $record_obj) { + include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDFieldDefinition.php'); + foreach (ilAdvancedMDFieldDefinition::getInstancesByRecordId($record_obj->getRecordId()) as $def) { + $fields[$def->getFieldId()] = array( + "id" => $def->getFieldId(), + "title" => $def->getTitle(), + "type" => $def->getType() + ); + } + } - return $fields; - } - - /** - * Get column order - * - * @param - * @return - */ - function getColumnOrder() - { - $ilDB = $this->db; - $lng = $this->lng; - - $columns = array(); - - $set = $ilDB->query("SELECT * FROM glo_advmd_col_order ". - " WHERE glo_id = ".$ilDB->quote($this->glo_id, "integer"). - " ORDER BY order_nr" - ); - $order = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $order[$rec["field_id"]] = $rec["order_nr"]; - } -//var_dump($order); - // add term at beginning, if not included - if (!isset($order[0])) - { - $columns[] = array("id" => 0, - "text" => $lng->txt("cont_term")); - } + return $fields; + } + + /** + * Get column order + * + * @param + * @return + */ + public function getColumnOrder() + { + $ilDB = $this->db; + $lng = $this->lng; + + $columns = array(); + + $set = $ilDB->query( + "SELECT * FROM glo_advmd_col_order " . + " WHERE glo_id = " . $ilDB->quote($this->glo_id, "integer") . + " ORDER BY order_nr" + ); + $order = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $order[$rec["field_id"]] = $rec["order_nr"]; + } + //var_dump($order); + // add term at beginning, if not included + if (!isset($order[0])) { + $columns[] = array("id" => 0, + "text" => $lng->txt("cont_term")); + } - $fields = $this->getAllFields(); - - // add all fields that have been already sorted - foreach ($order as $id => $order_nr) - { - if (isset($fields[$id])) - { - $columns[] = array("id" => $id, - "text" => $fields[$id]["title"]); - unset($fields[$id]); - } - else if ($id == 0) - { - $columns[] = array("id" => 0, - "text" => $lng->txt("cont_term")); - } - } - - // add all fields that have not been sorted - foreach ($fields as $f) - { - $columns[] = array("id" => $f["id"], - "text" => $f["title"]); - } - - return $columns; - } + $fields = $this->getAllFields(); + + // add all fields that have been already sorted + foreach ($order as $id => $order_nr) { + if (isset($fields[$id])) { + $columns[] = array("id" => $id, + "text" => $fields[$id]["title"]); + unset($fields[$id]); + } elseif ($id == 0) { + $columns[] = array("id" => 0, + "text" => $lng->txt("cont_term")); + } + } + + // add all fields that have not been sorted + foreach ($fields as $f) { + $columns[] = array("id" => $f["id"], + "text" => $f["title"]); + } + + return $columns; + } - /** - * Save column order - * - * @param - * @return - */ - function saveColumnOrder($a_cols) - { - $ilDB = $this->db; - - $ilDB->manipulate("DELETE FROM glo_advmd_col_order WHERE ". - " glo_id = ".$ilDB->quote($this->glo_id, "integer") - ); + /** + * Save column order + * + * @param + * @return + */ + public function saveColumnOrder($a_cols) + { + $ilDB = $this->db; + + $ilDB->manipulate( + "DELETE FROM glo_advmd_col_order WHERE " . + " glo_id = " . $ilDB->quote($this->glo_id, "integer") + ); - $nr = 10; - $set = array(); - foreach ($a_cols as $c) - { -//var_dump($c); - if (!isset($set[$c["id"]])) - { - $ilDB->manipulate("INSERT INTO glo_advmd_col_order ". - "(glo_id, field_id, order_nr) VALUES (". - $ilDB->quote($this->glo_id, "integer").",". - $ilDB->quote($c["id"], "integer").",". - $ilDB->quote($nr+=10, "integer"). - ")"); - $set[$c["id"]] = $c["id"]; - } - } - } + $nr = 10; + $set = array(); + foreach ($a_cols as $c) { + //var_dump($c); + if (!isset($set[$c["id"]])) { + $ilDB->manipulate("INSERT INTO glo_advmd_col_order " . + "(glo_id, field_id, order_nr) VALUES (" . + $ilDB->quote($this->glo_id, "integer") . "," . + $ilDB->quote($c["id"], "integer") . "," . + $ilDB->quote($nr+=10, "integer") . + ")"); + $set[$c["id"]] = $c["id"]; + } + } + } - /** - * Write single column order - * - * @param - * @return - */ - static function writeColumnOrder($a_glo_id, $a_field_id, $a_order_nr) - { - global $DIC; + /** + * Write single column order + * + * @param + * @return + */ + public static function writeColumnOrder($a_glo_id, $a_field_id, $a_order_nr) + { + global $DIC; - $ilDB = $DIC->database(); + $ilDB = $DIC->database(); - $ilDB->replace("glo_advmd_col_order", - array("glo_id" => array("integer", $a_glo_id), - "field_id" => array("integer", $a_field_id)), - array("order_nr" => array("integer", $a_order_nr)) - ); - } + $ilDB->replace( + "glo_advmd_col_order", + array("glo_id" => array("integer", $a_glo_id), + "field_id" => array("integer", $a_field_id)), + array("order_nr" => array("integer", $a_order_nr)) + ); + } } - -?> diff --git a/Modules/Glossary/classes/class.ilGlossaryAutoLinkTableGUI.php b/Modules/Glossary/classes/class.ilGlossaryAutoLinkTableGUI.php index 7ff8a96c6f823669d870d2a85b6598c89c261b20..956b44a8b176873977378321397a700dcc3e3ee2 100644 --- a/Modules/Glossary/classes/class.ilGlossaryAutoLinkTableGUI.php +++ b/Modules/Glossary/classes/class.ilGlossaryAutoLinkTableGUI.php @@ -14,66 +14,62 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilGlossaryAutoLinkTableGUI extends ilTable2GUI { - /** - * @var ilObjGlossary - */ - protected $glossary; + /** + * @var ilObjGlossary + */ + protected $glossary; - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * Constructor - */ - function __construct(ilObjGlossary $a_glossary, $a_parent_obj, $a_parent_cmd) - { - global $DIC; - - $this->glossary = $a_glossary; - $this->id = "glo_glo"; - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - $data = array(); - foreach ($a_glossary->getAutoGlossaries() as $glo_id) - { - $data[] = array("glo_id" => $glo_id, "title" => ilObject::_lookupTitle($glo_id)); - } - $this->setData($data); - $this->setTitle($this->lng->txt("cont_auto_glossaries")); - - $this->addColumn($this->lng->txt("title"), "title"); - $this->addColumn($this->lng->txt("actions")); - - $this->setFormAction($this->ctrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.glo_glossary_auto_link_row.html", "Modules/Glossary"); + /** + * Constructor + */ + public function __construct(ilObjGlossary $a_glossary, $a_parent_obj, $a_parent_cmd) + { + global $DIC; + + $this->glossary = $a_glossary; + $this->id = "glo_glo"; + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + $data = array(); + foreach ($a_glossary->getAutoGlossaries() as $glo_id) { + $data[] = array("glo_id" => $glo_id, "title" => ilObject::_lookupTitle($glo_id)); + } + $this->setData($data); + $this->setTitle($this->lng->txt("cont_auto_glossaries")); + + $this->addColumn($this->lng->txt("title"), "title"); + $this->addColumn($this->lng->txt("actions")); + + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.glo_glossary_auto_link_row.html", "Modules/Glossary"); -// $this->addMultiCommand("", $lng->txt("")); + // $this->addMultiCommand("", $lng->txt("")); // $this->addCommandButton("", $lng->txt("")); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $this->ctrl->setParameter($this->parent_obj, "glo_id", $a_set["glo_id"]); - $this->tpl->setCurrentBlock("cmd"); - $this->tpl->setVariable("CMD_HREF", $this->ctrl->getLinkTarget($this->parent_obj, "removeGlossary")); - $this->tpl->setVariable("CMD_TXT", $this->lng->txt("remove")); - $this->tpl->parseCurrentBlock(); - $this->tpl->setVariable("TITLE", ilObject::_lookupTitle($a_set["glo_id"])); - } - - + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $this->ctrl->setParameter($this->parent_obj, "glo_id", $a_set["glo_id"]); + $this->tpl->setCurrentBlock("cmd"); + $this->tpl->setVariable("CMD_HREF", $this->ctrl->getLinkTarget($this->parent_obj, "removeGlossary")); + $this->tpl->setVariable("CMD_TXT", $this->lng->txt("remove")); + $this->tpl->parseCurrentBlock(); + $this->tpl->setVariable("TITLE", ilObject::_lookupTitle($a_set["glo_id"])); + } } -?> diff --git a/Modules/Glossary/classes/class.ilGlossaryDataSet.php b/Modules/Glossary/classes/class.ilGlossaryDataSet.php index 239e1bd42acd27c5f9792d6028c61a7f55e5a832..16387df5a7307e8d378f78edb9e623a2961a1bcf 100644 --- a/Modules/Glossary/classes/class.ilGlossaryDataSet.php +++ b/Modules/Glossary/classes/class.ilGlossaryDataSet.php @@ -5,7 +5,7 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); /** * Glossary Data set class - * + * * This class implements the following entities: * - glo: data from glossary * - glo_term: data from glossary_term @@ -18,312 +18,312 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); */ class ilGlossaryDataSet extends ilDataSet { - /** - * @var ilLogger - */ - protected $log; - - /** - * Constructor - */ - function __construct() - { - global $DIC; + /** + * @var ilLogger + */ + protected $log; - $this->db = $DIC->database(); - $this->log = ilLoggerFactory::getLogger('glo'); - parent::__construct(); - } + /** + * Constructor + */ + public function __construct() + { + global $DIC; - /** - * Get supported versions - * - * @return string version - */ - public function getSupportedVersions() - { - return array("5.1.0"); - } - - /** - * Get xml namespace - * - * @param - * @return - */ - function getXmlNamespace($a_entity, $a_schema_version) - { - return "http://www.ilias.de/xml/Modules/Glossary/".$a_entity; - } - - /** - * Get field types for entity - * - * @param string $a_entity entity - * @param string $a_version version number - * @return array types array - */ - protected function getTypes($a_entity, $a_version) - { - if ($a_entity == "glo") - { - switch ($a_version) - { - case "5.1.0": - return array( - "Id" => "integer", - "Title" => "text", - "Description" => "text", - "Virtual" => "text", - "PresMode" => "text", - "SnippetLength" => "integer", - "GloMenuActive" => "text", - "ShowTax" => "integer" - ); - } - } + $this->db = $DIC->database(); + $this->log = ilLoggerFactory::getLogger('glo'); + parent::__construct(); + } - if ($a_entity == "glo_term") - { - switch ($a_version) - { - case "5.1.0": - return array( - "Id" => "integer", - "GloId" => "integer", - "Term" => "text", - "Language" => "text", - "ImportId" => "text" - ); - } - } + /** + * Get supported versions + * + * @return string version + */ + public function getSupportedVersions() + { + return array("5.1.0"); + } + + /** + * Get xml namespace + * + * @param + * @return + */ + public function getXmlNamespace($a_entity, $a_schema_version) + { + return "http://www.ilias.de/xml/Modules/Glossary/" . $a_entity; + } + + /** + * Get field types for entity + * + * @param string $a_entity entity + * @param string $a_version version number + * @return array types array + */ + protected function getTypes($a_entity, $a_version) + { + if ($a_entity == "glo") { + switch ($a_version) { + case "5.1.0": + return array( + "Id" => "integer", + "Title" => "text", + "Description" => "text", + "Virtual" => "text", + "PresMode" => "text", + "SnippetLength" => "integer", + "GloMenuActive" => "text", + "ShowTax" => "integer" + ); + } + } - if ($a_entity == "glo_definition") - { - switch ($a_version) - { - case "5.1.0": - return array( - "Id" => "integer", - "TermId" => "integer", - "ShortText" => "text", - "Nr" => "integer", - "ShortTextDirty" => "integer" - ); - } - } + if ($a_entity == "glo_term") { + switch ($a_version) { + case "5.1.0": + return array( + "Id" => "integer", + "GloId" => "integer", + "Term" => "text", + "Language" => "text", + "ImportId" => "text" + ); + } + } - if ($a_entity == "glo_advmd_col_order") - { - switch ($a_version) - { - case "5.1.0": - return array( - "GloId" => "integer", - "FieldId" => "text", - "OrderNr" => "integer" - ); - } - } + if ($a_entity == "glo_definition") { + switch ($a_version) { + case "5.1.0": + return array( + "Id" => "integer", + "TermId" => "integer", + "ShortText" => "text", + "Nr" => "integer", + "ShortTextDirty" => "integer" + ); + } + } - } + if ($a_entity == "glo_advmd_col_order") { + switch ($a_version) { + case "5.1.0": + return array( + "GloId" => "integer", + "FieldId" => "text", + "OrderNr" => "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 == "glo") - { - switch ($a_version) - { - case "5.1.0": - $this->getDirectDataFromQuery("SELECT o.title, o.description, g.id, g.virtual, pres_mode, snippet_length, show_tax, glo_menu_active". - " FROM glossary g JOIN object_data o ". - " ON (g.id = o.obj_id) ". - " WHERE ".$ilDB->in("g.id", $a_ids, false, "integer")); - break; - } - } + if (!is_array($a_ids)) { + $a_ids = array($a_ids); + } + + if ($a_entity == "glo") { + switch ($a_version) { + case "5.1.0": + $this->getDirectDataFromQuery("SELECT o.title, o.description, g.id, g.virtual, pres_mode, snippet_length, show_tax, glo_menu_active" . + " FROM glossary g JOIN object_data o " . + " ON (g.id = o.obj_id) " . + " WHERE " . $ilDB->in("g.id", $a_ids, false, "integer")); + break; + } + } - if ($a_entity == "glo_term") - { - switch ($a_version) - { - case "5.1.0": - // todo: how does import id needs to be set? - $this->getDirectDataFromQuery("SELECT id, glo_id, term, language". - " FROM glossary_term ". - " WHERE ".$ilDB->in("glo_id", $a_ids, false, "integer")); - break; - } - } + if ($a_entity == "glo_term") { + switch ($a_version) { + case "5.1.0": + // todo: how does import id needs to be set? + $this->getDirectDataFromQuery("SELECT id, glo_id, term, language" . + " FROM glossary_term " . + " WHERE " . $ilDB->in("glo_id", $a_ids, false, "integer")); + break; + } + } - if ($a_entity == "glo_definition") - { - switch ($a_version) - { - case "5.1.0": - $this->getDirectDataFromQuery("SELECT id, term_id, short_text, nr, short_text_dirty". - " FROM glossary_definition ". - " WHERE ".$ilDB->in("term_id", $a_ids, false, "integer")); - break; - } - } + if ($a_entity == "glo_definition") { + switch ($a_version) { + case "5.1.0": + $this->getDirectDataFromQuery("SELECT id, term_id, short_text, nr, short_text_dirty" . + " FROM glossary_definition " . + " WHERE " . $ilDB->in("term_id", $a_ids, false, "integer")); + break; + } + } - if ($a_entity == "glo_advmd_col_order") - { - switch ($a_version) - { - case "5.1.0": - $this->getDirectDataFromQuery("SELECT glo_id, field_id, order_nr". - " FROM glo_advmd_col_order ". - " WHERE ".$ilDB->in("glo_id", $a_ids, false, "integer")); - break; - } - } - } - - /** - * Determine the dependent sets of data - */ - protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) - { - switch ($a_entity) - { - case "glo": - return array ( - "glo_term" => array("ids" => $a_rec["Id"]), - "glo_advmd_col_order" => array("ids" => $a_rec["Id"]) - ); + if ($a_entity == "glo_advmd_col_order") { + switch ($a_version) { + case "5.1.0": + $this->getDirectDataFromQuery("SELECT glo_id, field_id, order_nr" . + " FROM glo_advmd_col_order " . + " WHERE " . $ilDB->in("glo_id", $a_ids, false, "integer")); + break; + } + } + } + + /** + * Determine the dependent sets of data + */ + protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) + { + switch ($a_entity) { + case "glo": + return array( + "glo_term" => array("ids" => $a_rec["Id"]), + "glo_advmd_col_order" => array("ids" => $a_rec["Id"]) + ); - case "glo_term": - return array ( - "glo_definition" => array("ids" => $a_rec["Id"]) - ); - } + case "glo_term": + return array( + "glo_definition" => array("ids" => $a_rec["Id"]) + ); + } - return false; - } - - - /** - * Import record - * - * @param - * @return - */ - function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) - { - switch ($a_entity) - { - case "glo": + return false; + } + + + /** + * Import record + * + * @param + * @return + */ + public function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) + { + switch ($a_entity) { + case "glo": - include_once("./Modules/Glossary/classes/class.ilObjGlossary.php"); - if($new_id = $a_mapping->getMapping('Services/Container','objs',$a_rec['Id'])) - { - $newObj = ilObjectFactory::getInstanceByObjId($new_id,false); - } - else - { - $newObj = new ilObjGlossary(); - $newObj->create(true); - } - - $newObj->setTitle($a_rec["Title"]); - $newObj->setDescription($a_rec["Description"]); - $newObj->setVirtualMode($a_rec["Virtual"]); - $newObj->setPresentationMode($a_rec["PresMode"]); - $newObj->setSnippetLength($a_rec["SnippetLength"]); - $newObj->setActiveGlossaryMenu($a_rec["GloMenuActive"]); - $newObj->setShowTaxonomy($a_rec["ShowTax"]); - $newObj->update(true); + include_once("./Modules/Glossary/classes/class.ilObjGlossary.php"); + if ($new_id = $a_mapping->getMapping('Services/Container', 'objs', $a_rec['Id'])) { + $newObj = ilObjectFactory::getInstanceByObjId($new_id, false); + } else { + $newObj = new ilObjGlossary(); + $newObj->create(true); + } + + $newObj->setTitle($a_rec["Title"]); + $newObj->setDescription($a_rec["Description"]); + $newObj->setVirtualMode($a_rec["Virtual"]); + $newObj->setPresentationMode($a_rec["PresMode"]); + $newObj->setSnippetLength($a_rec["SnippetLength"]); + $newObj->setActiveGlossaryMenu($a_rec["GloMenuActive"]); + $newObj->setShowTaxonomy($a_rec["ShowTax"]); + $newObj->update(true); - $this->current_obj = $newObj; - $this->old_glo_id = $a_rec["Id"]; - $a_mapping->addMapping("Modules/Glossary", "glo", $a_rec["Id"], $newObj->getId()); - $a_mapping->addMapping("Services/Object", "obj", $a_rec["Id"], $newObj->getId()); - $a_mapping->addMapping("Services/MetaData", "md", - $a_rec["Id"].":0:glo", $newObj->getId().":0:glo"); - $a_mapping->addMapping("Services/AdvancedMetaData", "parent", $a_rec["Id"], $newObj->getId()); - break; + $this->current_obj = $newObj; + $this->old_glo_id = $a_rec["Id"]; + $a_mapping->addMapping("Modules/Glossary", "glo", $a_rec["Id"], $newObj->getId()); + $a_mapping->addMapping("Services/Object", "obj", $a_rec["Id"], $newObj->getId()); + $a_mapping->addMapping( + "Services/MetaData", + "md", + $a_rec["Id"] . ":0:glo", + $newObj->getId() . ":0:glo" + ); + $a_mapping->addMapping("Services/AdvancedMetaData", "parent", $a_rec["Id"], $newObj->getId()); + break; - case "glo_term": + case "glo_term": - // id, glo_id, term, language, import_id + // id, glo_id, term, language, import_id - include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - $glo_id = (int) $a_mapping->getMapping("Modules/Glossary", "glo", $a_rec["GloId"]); - $term = new ilGlossaryTerm(); - $term->setGlossaryId($glo_id); - $term->setTerm($a_rec["Term"]); - $term->setLanguage($a_rec["Language"]); - if ($this->getCurrentInstallationId() > 0) - { - $term->setImportId("il_".$this->getCurrentInstallationId()."_git_".$a_rec["Id"]); - } - $term->create(); - $term_id = $term->getId(); - $this->log->debug("glo_term, import id: ".$term->getImportId().", term id: ".$term_id); + include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + $glo_id = (int) $a_mapping->getMapping("Modules/Glossary", "glo", $a_rec["GloId"]); + $term = new ilGlossaryTerm(); + $term->setGlossaryId($glo_id); + $term->setTerm($a_rec["Term"]); + $term->setLanguage($a_rec["Language"]); + if ($this->getCurrentInstallationId() > 0) { + $term->setImportId("il_" . $this->getCurrentInstallationId() . "_git_" . $a_rec["Id"]); + } + $term->create(); + $term_id = $term->getId(); + $this->log->debug("glo_term, import id: " . $term->getImportId() . ", term id: " . $term_id); - $a_mapping->addMapping("Modules/Glossary", "term", - $a_rec["Id"], $term_id); + $a_mapping->addMapping( + "Modules/Glossary", + "term", + $a_rec["Id"], + $term_id + ); - $a_mapping->addMapping("Services/Taxonomy", "tax_item", - "glo:term:".$a_rec["Id"], $term_id); + $a_mapping->addMapping( + "Services/Taxonomy", + "tax_item", + "glo:term:" . $a_rec["Id"], + $term_id + ); - $a_mapping->addMapping("Services/Taxonomy", "tax_item_obj_id", - "glo:term:".$a_rec["Id"], $glo_id); + $a_mapping->addMapping( + "Services/Taxonomy", + "tax_item_obj_id", + "glo:term:" . $a_rec["Id"], + $glo_id + ); - $a_mapping->addMapping("Services/AdvancedMetaData", "advmd_sub_item", - "advmd:term:".$a_rec["Id"], $term_id); - break; + $a_mapping->addMapping( + "Services/AdvancedMetaData", + "advmd_sub_item", + "advmd:term:" . $a_rec["Id"], + $term_id + ); + break; - case "glo_definition": + case "glo_definition": - // id, term_id, short_text, nr, short_text_dirty + // id, term_id, short_text, nr, short_text_dirty - include_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); - $term_id = (int) $a_mapping->getMapping("Modules/Glossary", "term", $a_rec["TermId"]); - if ((int) $term_id == 0) - { - $this->log->debug("ERROR: Did not find glossary term glo_term id '".$a_rec["TermId"]."' for definition id '".$a_rec["Id"]."'."); - } - else - { - $def = new ilGlossaryDefinition(); - $def->setTermId($term_id); - $def->setShortText($a_rec["ShortText"]); - $def->setNr($a_rec["Nr"]); - $def->setShortTextDirty($a_rec["ShortTextDirty"]); - // no metadata, no page creation - $def->create(true, true); + include_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); + $term_id = (int) $a_mapping->getMapping("Modules/Glossary", "term", $a_rec["TermId"]); + if ((int) $term_id == 0) { + $this->log->debug("ERROR: Did not find glossary term glo_term id '" . $a_rec["TermId"] . "' for definition id '" . $a_rec["Id"] . "'."); + } else { + $def = new ilGlossaryDefinition(); + $def->setTermId($term_id); + $def->setShortText($a_rec["ShortText"]); + $def->setNr($a_rec["Nr"]); + $def->setShortTextDirty($a_rec["ShortTextDirty"]); + // no metadata, no page creation + $def->create(true, true); - $a_mapping->addMapping("Modules/Glossary", "def", $a_rec["Id"], $def->getId()); - $a_mapping->addMapping("Services/COPage", "pg", "gdf:" . $a_rec["Id"], - "gdf:" . $def->getId()); - $a_mapping->addMapping("Services/MetaData", "md", - $this->old_glo_id . ":" . $a_rec["Id"] . ":gdf", $this->current_obj->getId() . ":" . $def->getId() . ":gdf"); - } - break; + $a_mapping->addMapping("Modules/Glossary", "def", $a_rec["Id"], $def->getId()); + $a_mapping->addMapping( + "Services/COPage", + "pg", + "gdf:" . $a_rec["Id"], + "gdf:" . $def->getId() + ); + $a_mapping->addMapping( + "Services/MetaData", + "md", + $this->old_glo_id . ":" . $a_rec["Id"] . ":gdf", + $this->current_obj->getId() . ":" . $def->getId() . ":gdf" + ); + } + break; - case "glo_advmd_col_order": - // glo_id, field_id, order_nr - // we save the ordering in the mapping, the glossary importer needs to fix this in the final - // processing - $a_mapping->addMapping("Modules/Glossary", "advmd_col_order", $a_rec["GloId"].":".$a_rec["FieldId"], $a_rec["OrderNr"]); - break; - } - } + case "glo_advmd_col_order": + // glo_id, field_id, order_nr + // we save the ordering in the mapping, the glossary importer needs to fix this in the final + // processing + $a_mapping->addMapping("Modules/Glossary", "advmd_col_order", $a_rec["GloId"] . ":" . $a_rec["FieldId"], $a_rec["OrderNr"]); + break; + } + } } -?> \ No newline at end of file diff --git a/Modules/Glossary/classes/class.ilGlossaryDefPage.php b/Modules/Glossary/classes/class.ilGlossaryDefPage.php index 57a40a97394360226750d09701d1f6f557538b84..98b2e3f4125ca301d9b7ae282c3ccc7993f6d145 100755 --- a/Modules/Glossary/classes/class.ilGlossaryDefPage.php +++ b/Modules/Glossary/classes/class.ilGlossaryDefPage.php @@ -5,43 +5,40 @@ include_once("./Services/COPage/classes/class.ilPageObject.php"); /** * Glossary definition page object - * - * @author Alex Killing + * + * @author Alex Killing * @version $Id$ * * @ingroup ModulesGlossary */ class ilGlossaryDefPage extends ilPageObject { - /** - * Get parent type - * - * @return string parent type - */ - function getParentType() - { - return "gdf"; - } - - /** - * Before page content update - * - * Note: This one is "work in progress", currently only text paragraphs call this hook - * It is called before the page content object invokes the update procedure of - * ilPageObject - * - * @param - * @return - */ - function beforePageContentUpdate($a_page_content) - { - if ($a_page_content->getType() == "par") - { - include_once("./Modules/Glossary/classes/class.ilObjGlossary.php"); - $glos = ilObjGlossary::lookupAutoGlossaries($this->getParentId()); - $a_page_content->autoLinkGlossaries($glos); - } - } + /** + * Get parent type + * + * @return string parent type + */ + public function getParentType() + { + return "gdf"; + } + /** + * Before page content update + * + * Note: This one is "work in progress", currently only text paragraphs call this hook + * It is called before the page content object invokes the update procedure of + * ilPageObject + * + * @param + * @return + */ + public function beforePageContentUpdate($a_page_content) + { + if ($a_page_content->getType() == "par") { + include_once("./Modules/Glossary/classes/class.ilObjGlossary.php"); + $glos = ilObjGlossary::lookupAutoGlossaries($this->getParentId()); + $a_page_content->autoLinkGlossaries($glos); + } + } } -?> diff --git a/Modules/Glossary/classes/class.ilGlossaryDefPageConfig.php b/Modules/Glossary/classes/class.ilGlossaryDefPageConfig.php index d1d6c207addab0e3231d97da02afe43378e500fa..84e6df5add256c2acf75326ed5f05719dfc8556e 100644 --- a/Modules/Glossary/classes/class.ilGlossaryDefPageConfig.php +++ b/Modules/Glossary/classes/class.ilGlossaryDefPageConfig.php @@ -5,7 +5,7 @@ include_once("./Services/COPage/classes/class.ilPageConfig.php"); /** - * Glossary definition page configuration + * Glossary definition page configuration * * @author Alex Killing * @version $Id$ @@ -13,17 +13,14 @@ include_once("./Services/COPage/classes/class.ilPageConfig.php"); */ class ilGlossaryDefPageConfig extends ilPageConfig { - /** - * Init - */ - function init() - { - $this->setEnableKeywords(true); - $this->setEnableInternalLinks(true); - $this->setIntLinkHelpDefaultType("GlossaryItem"); - $this->setIntLinkHelpDefaultId($_GET["ref_id"]); - } - + /** + * Init + */ + public function init() + { + $this->setEnableKeywords(true); + $this->setEnableInternalLinks(true); + $this->setIntLinkHelpDefaultType("GlossaryItem"); + $this->setIntLinkHelpDefaultId($_GET["ref_id"]); + } } - -?> diff --git a/Modules/Glossary/classes/class.ilGlossaryDefPageGUI.php b/Modules/Glossary/classes/class.ilGlossaryDefPageGUI.php index a257e15928c949ad3dca227dae28b8adb32c1590..eb77eac3234f9acdc68dd25dcdad2c2031dcad01 100755 --- a/Modules/Glossary/classes/class.ilGlossaryDefPageGUI.php +++ b/Modules/Glossary/classes/class.ilGlossaryDefPageGUI.php @@ -7,8 +7,8 @@ include_once("./Modules/Glossary/classes/class.ilGlossaryDefPage.php"); /** * Glossary definition page GUI class - * - * @author Alex Killing + * + * @author Alex Killing * * @ilCtrl_Calls ilGlossaryDefPageGUI: ilPageEditorGUI, ilEditClipboardGUI, ilObjectMetaDataGUI * @ilCtrl_Calls ilGlossaryDefPageGUI: ilPublicUserProfileGUI, ilNoteGUI @@ -18,65 +18,60 @@ include_once("./Modules/Glossary/classes/class.ilGlossaryDefPage.php"); */ class ilGlossaryDefPageGUI extends ilPageObjectGUI { - /** - * @var ilObjGlossary - */ - protected $glossary; - - /** - * Constructor - */ - function __construct($a_id = 0, $a_old_nr = 0) - { - global $DIC; - - $this->tpl = $DIC["tpl"]; - $tpl = $DIC["tpl"]; - - parent::__construct("gdf", $a_id, $a_old_nr); - } - - /** - * Set glossary - * - * @param ilObjGlossary $a_val glossary - */ - function setGlossary($a_val) - { - $this->glossary = $a_val; - } - - /** - * Get glossary - * - * @return ilObjGlossary glossary - */ - function getGlossary() - { - return $this->glossary; - } + /** + * @var ilObjGlossary + */ + protected $glossary; + + /** + * Constructor + */ + public function __construct($a_id = 0, $a_old_nr = 0) + { + global $DIC; - /** - * Output metadata - */ - 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); - } - } + $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("
", "
", $text); - $text = strip_tags($text, "
"); - if (is_int(strpos(substr($text, $a_length - 16 - 5, 10), "[tex]"))) - { - $offset = 5; - } - $short = ilUtil::shortenText($text, $a_length - 16 + $offset, true); - - // make short text longer, if tex end tag is missing - $ltexs = strrpos($short, "[tex]"); - $ltexe = strrpos($short, "[/tex]"); - if ($ltexs > $ltexe) - { - $ltexe = strpos($text, "[/tex]", $ltexs); - if ($ltexe > 0) - { - $short = ilUtil::shortenText($text, $ltexe+6, true); - } - } - - $short = ilUtil::shortenText($text, $a_length, true); - - return $short; - } - - function updateShortText() - { - $this->page_object->buildDom(); - $text = $this->page_object->getFirstParagraphText(); - - $short = $this->shortenShortText($text); - - $this->setShortText($short); - $this->setShortTextDirty(false); - $this->update(); - } - - /** - * static - */ - static function getDefinitionList($a_term_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $defs = array(); - $q = "SELECT * FROM glossary_definition WHERE term_id = ". - $ilDB->quote($a_term_id, "integer"). - " ORDER BY nr"; - $def_set = $ilDB->query($q); - while ($def_rec = $ilDB->fetchAssoc($def_set)) - { - $defs[] = array("term_id" => $def_rec["term_id"], - "page_id" => $def_rec["page_id"], "id" => $def_rec["id"], - "short_text" => strip_tags($def_rec["short_text"], "
"), - "nr" => $def_rec["nr"], - "short_text_dirty" => $def_rec["short_text_dirty"]); - } - return $defs; - } - - /** - * export xml - */ - function exportXML(&$a_xml_writer, $a_inst) - { - $attrs = array(); - $a_xml_writer->xmlStartTag("Definition", $attrs); - - $this->exportXMLMetaData($a_xml_writer); - $this->exportXMLDefinition($a_xml_writer, $a_inst); - - $a_xml_writer->xmlEndTag("Definition"); - } - - - /** - * export content objects meta data to xml (see ilias_co.dtd) - * - * @param object $a_xml_writer ilXmlWriter object that receives the - * xml data - */ - function exportXMLMetaData(&$a_xml_writer) - { - $glo_id = ilGlossaryTerm::_lookGlossaryID($this->getTermId()); - include_once("Services/MetaData/classes/class.ilMD2XML.php"); - $md2xml = new ilMD2XML($glo_id, $this->getId(), $this->getType()); - $md2xml->setExportMode(true); - $md2xml->startExport(); - $a_xml_writer->appendXML($md2xml->getXML()); - } - - /** - * - */ - function modifyExportIdentifier($a_tag, $a_param, $a_value) - { - if ($a_tag == "Identifier" && $a_param == "Entry") - { - $a_value = "il_".IL_INST_ID."_gdf_".$this->getId(); - } - - return $a_value; - } - - - /** - * export page objects meta data to xml (see ilias_co.dtd) - * - * @param object $a_xml_writer ilXmlWriter object that receives the - * xml data - */ - function exportXMLDefinition(&$a_xml_writer, $a_inst = 0) - { - - $this->page_object->buildDom(); - $this->page_object->insertInstIntoIDs($a_inst); - $this->mobs_contained = $this->page_object->collectMediaObjects(false); - include_once("./Services/COPage/classes/class.ilPCFileList.php"); - $this->files_contained = ilPCFileList::collectFileItems($this->page_object, $this->page_object->getDomDoc()); - $xml = $this->page_object->getXMLFromDom(false, false, false, "", true); - $xml = str_replace("&","&", $xml); - $a_xml_writer->appendXML($xml); - - $this->page_object->freeDom(); - } - - /** - * create meta data entry - */ - function createMetaData() - { - include_once 'Services/MetaData/classes/class.ilMDCreator.php'; - - $ilUser = $this->user; - - $glo_id = ilGlossaryTerm::_lookGlossaryID($this->getTermId()); - $lang = ilGlossaryTerm::_lookLanguage($this->getTermId()); - $md_creator = new ilMDCreator($glo_id,$this->getId(),$this->getType()); - $md_creator->setTitle($this->getTitle()); - $md_creator->setTitleLanguage($lang); - $md_creator->setDescription($this->getDescription()); - $md_creator->setDescriptionLanguage($lang); - $md_creator->setKeywordLanguage($lang); - $md_creator->setLanguage($lang); -//echo "-".$this->getTitle()."-"; exit; - $md_creator->create(); - - return true; - } - - /** - * update meta data entry - */ - function updateMetaData() - { - include_once("Services/MetaData/classes/class.ilMD.php"); - include_once("Services/MetaData/classes/class.ilMDGeneral.php"); - include_once("Services/MetaData/classes/class.ilMDDescription.php"); - - $glo_id = ilGlossaryTerm::_lookGlossaryID($this->getTermId()); - $md = new ilMD($glo_id, $this->getId(), $this->getType()); - $md_gen = $md->getGeneral(); - $md_gen->setTitle($this->getTitle()); - - // sets first description (maybe not appropriate) - $md_des_ids = $md_gen->getDescriptionIds(); - if (count($md_des_ids) > 0) - { - $md_des = $md_gen->getDescription($md_des_ids[0]); - $md_des->setDescription($this->getDescription()); - $md_des->update(); - } - $md_gen->update(); - } - - /** - * delete meta data entry - */ - function deleteMetaData() - { - // Delete meta data - include_once('Services/MetaData/classes/class.ilMD.php'); - $glo_id = ilGlossaryTerm::_lookGlossaryID($this->getTermId()); - $md = new ilMD($glo_id, $this->getId(), $this->getType()); - $md->deleteAll(); - } - - /** - * Meta data update listener - * - * Important note: Do never call create() or update() - * method of ilObject here. It would result in an - * endless loop: update object -> update meta -> update - * object -> ... - * Use static _writeTitle() ... methods instead. - * - * Even if this is not stored to db, it should be stored to the object - * e.g. for during import parsing - * - * @param string $a_element - */ - function MDUpdateListener($a_element) - { - include_once 'Services/MetaData/classes/class.ilMD.php'; - - switch($a_element) - { - case 'General': - - // Update Title and description - $glo_id = ilGlossaryTerm::_lookGlossaryID($this->getTermId()); - $md = new ilMD($glo_id, $this->getId(), $this->getType()); - $md_gen = $md->getGeneral(); - - //ilObject::_writeTitle($this->getId(),$md_gen->getTitle()); - $this->setTitle($md_gen->getTitle()); - - foreach($md_gen->getDescriptionIds() as $id) - { - $md_des = $md_gen->getDescription($id); - //ilObject::_writeDescription($this->getId(),$md_des->getDescription()); - $this->setDescription($md_des->getDescription()); - break; - } - - break; - - default: - } - return true; - } - - /** - * Looks up term id for a definition id - * - * @param int $a_def_id definition id - */ - static function _lookupTermId($a_def_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "SELECT * FROM glossary_definition WHERE id = ". - $ilDB->quote($a_def_id, "integer"); - $def_set = $ilDB->query($q); - $def_rec = $ilDB->fetchAssoc($def_set); - - return $def_rec["term_id"]; - } - - /** - * Set short texts dirty - * - * @param - * @return - */ - static function setShortTextsDirty($a_glo_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - $term_ids = ilGlossaryTerm::getTermsOfGlossary($a_glo_id); - - foreach ($term_ids as $term_id) - { - $ilDB->manipulate("UPDATE glossary_definition SET ". - " short_text_dirty = ".$ilDB->quote(1, "integer"). - " WHERE term_id = ".$ilDB->quote($term_id, "integer") - ); - } - } + /** + * @var ilDB + */ + protected $db; + + /** + * @var ilObjUser + */ + protected $user; + + public $lng; + public $tpl; + + public $id; + public $term_id; + public $glo_id; + public $page_object; + public $short_text; + public $nr; + public $short_text_dirty = false; + + /** + * Constructor + * @access public + */ + 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 + */ + public 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); + } + + public function setId($a_id) + { + $this->id = $a_id; + } + + public function getId() + { + return $this->id; + } + + public function getType() + { + return "gdf"; + } + + public function setTermId($a_term_id) + { + $this->term_id = $a_term_id; + } + + public function getTermId() + { + return $this->term_id; + } + + public function setShortText($a_text) + { + $this->short_text = $this->shortenShortText($a_text); + } + + public function getShortText() + { + return $this->short_text; + } + + public function setNr($a_nr) + { + $this->nr = $a_nr; + } + + public function getNr() + { + return $this->nr; + } + + public function assignPageObject(&$a_page_object) + { + $this->page_object = $a_page_object; + } + + public function &getPageObject() + { + return $this->page_object; + } + + /** + * get title of content object + * + * @return string title + */ + public function getTitle() + { + return $this->title; + } + + /** + * set title of content object + */ + public function setTitle($a_title) + { + $this->title = $a_title; + } + + /** + * Get description + * + * @return string description + */ + public function getDescription() + { + return $this->description; + } + + /** + * Set description + * + * @param string description + */ + public function setDescription($a_description) + { + $this->description = $a_description; + } + + /** + * Set short text dirty + * + * @param boolean short text dirty + */ + public function setShortTextDirty($a_val) + { + $this->short_text_dirty = $a_val; + } + + /** + * Get short text dirty + * + * @return boolean short text dirty + */ + public function getShortTextDirty() + { + return $this->short_text_dirty; + } + /** + * Create definition + * + * @param boolean upload true/false + */ + public 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(); + } + } + + public 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(); + } + + + public 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(); + } + + public 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(); + } + + + public 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 + */ + public 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("
", "
", $text); + $text = strip_tags($text, "
"); + if (is_int(strpos(substr($text, $a_length - 16 - 5, 10), "[tex]"))) { + $offset = 5; + } + $short = ilUtil::shortenText($text, $a_length - 16 + $offset, true); + + // make short text longer, if tex end tag is missing + $ltexs = strrpos($short, "[tex]"); + $ltexe = strrpos($short, "[/tex]"); + if ($ltexs > $ltexe) { + $ltexe = strpos($text, "[/tex]", $ltexs); + if ($ltexe > 0) { + $short = ilUtil::shortenText($text, $ltexe+6, true); + } + } + + $short = ilUtil::shortenText($text, $a_length, true); + + return $short; + } + + public function updateShortText() + { + $this->page_object->buildDom(); + $text = $this->page_object->getFirstParagraphText(); + + $short = $this->shortenShortText($text); + + $this->setShortText($short); + $this->setShortTextDirty(false); + $this->update(); + } + + /** + * static + */ + public static function getDefinitionList($a_term_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $defs = array(); + $q = "SELECT * FROM glossary_definition WHERE term_id = " . + $ilDB->quote($a_term_id, "integer") . + " ORDER BY nr"; + $def_set = $ilDB->query($q); + while ($def_rec = $ilDB->fetchAssoc($def_set)) { + $defs[] = array("term_id" => $def_rec["term_id"], + "page_id" => $def_rec["page_id"], "id" => $def_rec["id"], + "short_text" => strip_tags($def_rec["short_text"], "
"), + "nr" => $def_rec["nr"], + "short_text_dirty" => $def_rec["short_text_dirty"]); + } + return $defs; + } + + /** + * export xml + */ + public function exportXML(&$a_xml_writer, $a_inst) + { + $attrs = array(); + $a_xml_writer->xmlStartTag("Definition", $attrs); + + $this->exportXMLMetaData($a_xml_writer); + $this->exportXMLDefinition($a_xml_writer, $a_inst); + + $a_xml_writer->xmlEndTag("Definition"); + } + + + /** + * export content objects meta data to xml (see ilias_co.dtd) + * + * @param object $a_xml_writer ilXmlWriter object that receives the + * xml data + */ + public function exportXMLMetaData(&$a_xml_writer) + { + $glo_id = ilGlossaryTerm::_lookGlossaryID($this->getTermId()); + include_once("Services/MetaData/classes/class.ilMD2XML.php"); + $md2xml = new ilMD2XML($glo_id, $this->getId(), $this->getType()); + $md2xml->setExportMode(true); + $md2xml->startExport(); + $a_xml_writer->appendXML($md2xml->getXML()); + } + + /** + * + */ + public function modifyExportIdentifier($a_tag, $a_param, $a_value) + { + if ($a_tag == "Identifier" && $a_param == "Entry") { + $a_value = "il_" . IL_INST_ID . "_gdf_" . $this->getId(); + } + + return $a_value; + } + + + /** + * export page objects meta data to xml (see ilias_co.dtd) + * + * @param object $a_xml_writer ilXmlWriter object that receives the + * xml data + */ + public function exportXMLDefinition(&$a_xml_writer, $a_inst = 0) + { + $this->page_object->buildDom(); + $this->page_object->insertInstIntoIDs($a_inst); + $this->mobs_contained = $this->page_object->collectMediaObjects(false); + include_once("./Services/COPage/classes/class.ilPCFileList.php"); + $this->files_contained = ilPCFileList::collectFileItems($this->page_object, $this->page_object->getDomDoc()); + $xml = $this->page_object->getXMLFromDom(false, false, false, "", true); + $xml = str_replace("&", "&", $xml); + $a_xml_writer->appendXML($xml); + + $this->page_object->freeDom(); + } + + /** + * create meta data entry + */ + public function createMetaData() + { + include_once 'Services/MetaData/classes/class.ilMDCreator.php'; + + $ilUser = $this->user; + + $glo_id = ilGlossaryTerm::_lookGlossaryID($this->getTermId()); + $lang = ilGlossaryTerm::_lookLanguage($this->getTermId()); + $md_creator = new ilMDCreator($glo_id, $this->getId(), $this->getType()); + $md_creator->setTitle($this->getTitle()); + $md_creator->setTitleLanguage($lang); + $md_creator->setDescription($this->getDescription()); + $md_creator->setDescriptionLanguage($lang); + $md_creator->setKeywordLanguage($lang); + $md_creator->setLanguage($lang); + //echo "-".$this->getTitle()."-"; exit; + $md_creator->create(); + + return true; + } + + /** + * update meta data entry + */ + public function updateMetaData() + { + include_once("Services/MetaData/classes/class.ilMD.php"); + include_once("Services/MetaData/classes/class.ilMDGeneral.php"); + include_once("Services/MetaData/classes/class.ilMDDescription.php"); + + $glo_id = ilGlossaryTerm::_lookGlossaryID($this->getTermId()); + $md = new ilMD($glo_id, $this->getId(), $this->getType()); + $md_gen = $md->getGeneral(); + $md_gen->setTitle($this->getTitle()); + + // sets first description (maybe not appropriate) + $md_des_ids = $md_gen->getDescriptionIds(); + if (count($md_des_ids) > 0) { + $md_des = $md_gen->getDescription($md_des_ids[0]); + $md_des->setDescription($this->getDescription()); + $md_des->update(); + } + $md_gen->update(); + } + + /** + * delete meta data entry + */ + public function deleteMetaData() + { + // Delete meta data + include_once('Services/MetaData/classes/class.ilMD.php'); + $glo_id = ilGlossaryTerm::_lookGlossaryID($this->getTermId()); + $md = new ilMD($glo_id, $this->getId(), $this->getType()); + $md->deleteAll(); + } + + /** + * Meta data update listener + * + * Important note: Do never call create() or update() + * method of ilObject here. It would result in an + * endless loop: update object -> update meta -> update + * object -> ... + * Use static _writeTitle() ... methods instead. + * + * Even if this is not stored to db, it should be stored to the object + * e.g. for during import parsing + * + * @param string $a_element + */ + public function MDUpdateListener($a_element) + { + include_once 'Services/MetaData/classes/class.ilMD.php'; + + switch ($a_element) { + case 'General': + + // Update Title and description + $glo_id = ilGlossaryTerm::_lookGlossaryID($this->getTermId()); + $md = new ilMD($glo_id, $this->getId(), $this->getType()); + $md_gen = $md->getGeneral(); + + //ilObject::_writeTitle($this->getId(),$md_gen->getTitle()); + $this->setTitle($md_gen->getTitle()); + + foreach ($md_gen->getDescriptionIds() as $id) { + $md_des = $md_gen->getDescription($id); + //ilObject::_writeDescription($this->getId(),$md_des->getDescription()); + $this->setDescription($md_des->getDescription()); + break; + } + + break; + + default: + } + return true; + } + + /** + * Looks up term id for a definition id + * + * @param int $a_def_id definition id + */ + public static function _lookupTermId($a_def_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "SELECT * FROM glossary_definition WHERE id = " . + $ilDB->quote($a_def_id, "integer"); + $def_set = $ilDB->query($q); + $def_rec = $ilDB->fetchAssoc($def_set); + + return $def_rec["term_id"]; + } + + /** + * Set short texts dirty + * + * @param + * @return + */ + public static function setShortTextsDirty($a_glo_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + $term_ids = ilGlossaryTerm::getTermsOfGlossary($a_glo_id); + + foreach ($term_ids as $term_id) { + $ilDB->manipulate( + "UPDATE glossary_definition SET " . + " short_text_dirty = " . $ilDB->quote(1, "integer") . + " WHERE term_id = " . $ilDB->quote($term_id, "integer") + ); + } + } } - -?> \ No newline at end of file diff --git a/Modules/Glossary/classes/class.ilGlossaryEditorGUI.php b/Modules/Glossary/classes/class.ilGlossaryEditorGUI.php index 48d15719b7ed1a52876473b921ef5640c108e177..2291a5e46bc8ec24ec1437235bf8730d9f1bd550 100644 --- a/Modules/Glossary/classes/class.ilGlossaryEditorGUI.php +++ b/Modules/Glossary/classes/class.ilGlossaryEditorGUI.php @@ -16,87 +16,84 @@ */ class ilGlossaryEditorGUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * @var ilNavigationHistory - */ - protected $nav_history; + /** + * @var ilNavigationHistory + */ + protected $nav_history; - /** - * @var ilErrorHandling - */ - protected $error; + /** + * @var ilErrorHandling + */ + protected $error; - function __construct() - { - global $DIC; + public function __construct() + { + global $DIC; - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $this->nav_history = $DIC["ilNavigationHistory"]; - $this->error = $DIC["ilErr"]; - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilAccess = $DIC->access(); - $ilNavigationHistory = $DIC["ilNavigationHistory"]; - $ilErr = $DIC["ilErr"]; - - // initialisation stuff - $this->ctrl = $ilCtrl; - $lng->loadLanguageModule("content"); - - // check write permission - if (!$ilAccess->checkAccess("write", "", $_GET["ref_id"]) && - !$ilAccess->checkAccess("edit_content", "", $_GET["ref_id"])) - { - $ilErr->raiseError($lng->txt("permission_denied"), $ilErr->MESSAGE); - } - - $ilNavigationHistory->addItem($_GET["ref_id"], - "ilias.php?baseClass=ilGlossaryEditorGUI&ref_id=".$_GET["ref_id"], - "glo"); - - } - - /** - * execute command - */ - function executeCommand() - { - $lng = $this->lng; - $ilAccess = $this->access; - - $cmd = $this->ctrl->getCmd(); - $next_class = $this->ctrl->getNextClass($this); - if ($next_class == "") - { - $this->ctrl->setCmdClass("ilobjglossarygui"); - $this->ctrl->setCmd(""); - } - - switch ($next_class) - { - case 'ilobjglossarygui': - default: - require_once "./Modules/Glossary/classes/class.ilObjGlossaryGUI.php"; - $glossary_gui = new ilObjGlossaryGUI("", $_GET["ref_id"], true, false); - $this->ctrl->forwardCommand($glossary_gui); - break; - } - } + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->nav_history = $DIC["ilNavigationHistory"]; + $this->error = $DIC["ilErr"]; + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilAccess = $DIC->access(); + $ilNavigationHistory = $DIC["ilNavigationHistory"]; + $ilErr = $DIC["ilErr"]; + + // initialisation stuff + $this->ctrl = $ilCtrl; + $lng->loadLanguageModule("content"); + + // check write permission + if (!$ilAccess->checkAccess("write", "", $_GET["ref_id"]) && + !$ilAccess->checkAccess("edit_content", "", $_GET["ref_id"])) { + $ilErr->raiseError($lng->txt("permission_denied"), $ilErr->MESSAGE); + } + + $ilNavigationHistory->addItem( + $_GET["ref_id"], + "ilias.php?baseClass=ilGlossaryEditorGUI&ref_id=" . $_GET["ref_id"], + "glo" + ); + } + + /** + * execute command + */ + public function executeCommand() + { + $lng = $this->lng; + $ilAccess = $this->access; + + $cmd = $this->ctrl->getCmd(); + $next_class = $this->ctrl->getNextClass($this); + if ($next_class == "") { + $this->ctrl->setCmdClass("ilobjglossarygui"); + $this->ctrl->setCmd(""); + } + switch ($next_class) { + case 'ilobjglossarygui': + default: + require_once "./Modules/Glossary/classes/class.ilObjGlossaryGUI.php"; + $glossary_gui = new ilObjGlossaryGUI("", $_GET["ref_id"], true, false); + $this->ctrl->forwardCommand($glossary_gui); + break; + } + } } diff --git a/Modules/Glossary/classes/class.ilGlossaryExport.php b/Modules/Glossary/classes/class.ilGlossaryExport.php index 052e35f1620d3e93b90cb1f6ee2e17df1704abda..759e88ce028879e0ce240fc3d358437b86ade3e7 100755 --- a/Modules/Glossary/classes/class.ilGlossaryExport.php +++ b/Modules/Glossary/classes/class.ilGlossaryExport.php @@ -1,24 +1,24 @@ settings = $DIC->settings(); - $ilErr = $DIC["ilErr"]; - $ilDB = $DIC->database(); - $ilSetting = $DIC->settings(); - - $this->glo_obj = $a_glo_obj; - - $this->err = $ilErr; - $this->db = $ilDB; - $this->mode = $a_mode; - - $settings = $ilSetting->getAll(); - // The default '0' is required for the directory structure (smeyer) - $this->inst_id = $settings["inst_id"] ? $settings['inst_id'] : 0; - - $date = time(); - switch($this->mode) - { - case "xml": - $this->export_dir = $this->glo_obj->getExportDirectory(); - $this->subdir = $date."__".$this->inst_id."__". - $this->glo_obj->getType()."_".$this->glo_obj->getId(); - $this->filename = $this->subdir.".xml"; - break; - - case "html": - $this->export_dir = $this->glo_obj->getExportDirectory("html"); - $this->subdir = $this->glo_obj->getType()."_".$this->glo_obj->getId(); - $this->filename = $this->subdir.".zip"; - break; - - } - - } - - function getInstId() - { - return $this->inst_id; - } - - /** - * build export file (complete zip file) - * - * @access public - * @return - */ - function buildExportFile() - { - switch ($this->mode) - { - case "html": - return $this->buildExportFileHTML(); - break; - - default: - return $this->buildExportFileXML(); - break; - } - } - - /** - * build export file (complete zip file) - */ - function buildExportFileXML() - { - - 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 Glossary ". - $this->glo_obj->getId()." of installation ".$this->inst."."); - - // set xml header - $this->xml->xmlHeader(); - - // create directories - $this->glo_obj->createExportDirectory(); - ilUtil::makeDir($this->export_dir."/".$this->subdir); - ilUtil::makeDir($this->export_dir."/".$this->subdir."/objects"); - - // get Log File - $expDir = $this->glo_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->glo_obj->exportXML($this->xml, $this->inst_id, - $this->export_dir."/".$this->subdir, $expLog); - - - - // dump xml document to file - $this->xml->xmlDumpFile($this->export_dir."/".$this->subdir."/".$this->filename - , false); - - // 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 html export file - */ - function buildExportFileHTML() - { - // create directories - $this->glo_obj->createExportDirectory("html"); - - // get Log File - $expDir = $this->glo_obj->getExportDirectory(); - - // get xml content - $this->glo_obj->exportHTML($this->export_dir."/".$this->subdir, $expLog); - } - + /** + * @var ilSetting + */ + protected $settings; + + public $err; // error object + public $db; // database object + public $glo_obj; // glossary + public $inst_id; // installation id + + /** + * Constructor + * @access public + */ + public function __construct(&$a_glo_obj, $a_mode = "xml") + { + global $DIC; + + $this->settings = $DIC->settings(); + $ilErr = $DIC["ilErr"]; + $ilDB = $DIC->database(); + $ilSetting = $DIC->settings(); + + $this->glo_obj = $a_glo_obj; + + $this->err = $ilErr; + $this->db = $ilDB; + $this->mode = $a_mode; + + $settings = $ilSetting->getAll(); + // The default '0' is required for the directory structure (smeyer) + $this->inst_id = $settings["inst_id"] ? $settings['inst_id'] : 0; + + $date = time(); + switch ($this->mode) { + case "xml": + $this->export_dir = $this->glo_obj->getExportDirectory(); + $this->subdir = $date . "__" . $this->inst_id . "__" . + $this->glo_obj->getType() . "_" . $this->glo_obj->getId(); + $this->filename = $this->subdir . ".xml"; + break; + + case "html": + $this->export_dir = $this->glo_obj->getExportDirectory("html"); + $this->subdir = $this->glo_obj->getType() . "_" . $this->glo_obj->getId(); + $this->filename = $this->subdir . ".zip"; + break; + + } + } + + public function getInstId() + { + return $this->inst_id; + } + + /** + * build export file (complete zip file) + * + * @access public + * @return + */ + public function buildExportFile() + { + switch ($this->mode) { + case "html": + return $this->buildExportFileHTML(); + break; + + default: + return $this->buildExportFileXML(); + break; + } + } + + /** + * build export file (complete zip file) + */ + public function buildExportFileXML() + { + 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 Glossary " . + $this->glo_obj->getId() . " of installation " . $this->inst . "."); + + // set xml header + $this->xml->xmlHeader(); + + // create directories + $this->glo_obj->createExportDirectory(); + ilUtil::makeDir($this->export_dir . "/" . $this->subdir); + ilUtil::makeDir($this->export_dir . "/" . $this->subdir . "/objects"); + + // get Log File + $expDir = $this->glo_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->glo_obj->exportXML( + $this->xml, + $this->inst_id, + $this->export_dir . "/" . $this->subdir, + $expLog + ); + + + + // dump xml document to file + $this->xml->xmlDumpFile($this->export_dir . "/" . $this->subdir . "/" . $this->filename, false); + + // 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 html export file + */ + public function buildExportFileHTML() + { + // create directories + $this->glo_obj->createExportDirectory("html"); + + // get Log File + $expDir = $this->glo_obj->getExportDirectory(); + + // get xml content + $this->glo_obj->exportHTML($this->export_dir . "/" . $this->subdir, $expLog); + } } - -?> diff --git a/Modules/Glossary/classes/class.ilGlossaryExporter.php b/Modules/Glossary/classes/class.ilGlossaryExporter.php index 04626dff9dcc646e572be402687436887253f332..4e4cf1f027658aa2fee42c29319b59800db4ad38 100644 --- a/Modules/Glossary/classes/class.ilGlossaryExporter.php +++ b/Modules/Glossary/classes/class.ilGlossaryExporter.php @@ -12,199 +12,182 @@ include_once("./Services/Export/classes/class.ilXmlExporter.php"); */ class ilGlossaryExporter extends ilXmlExporter { - private $ds; - - /** - * Initialisation - */ - function init() - { - include_once("./Modules/Glossary/classes/class.ilGlossaryDataSet.php"); - $this->ds = new ilGlossaryDataSet(); - $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); - $this->ds->setDSPrefix("ds"); - } - - /** - * Get tail dependencies - * - * @param string entity - * @param string target release - * @param array ids - * @return array array of array with keys "component", entity", "ids" - */ - function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) - { - if ($a_entity == "glo") - { - include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - include_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); - - $md_ids = array(); - - // glo related ids - foreach ($a_ids as $id) - { - $md_ids[] = $id.":0:glo"; - } - - // definition related ids - $page_ids = array(); - foreach ($a_ids as $id) - { - // workaround for #0023923 - $all_refs = ilObject::_getAllReferences($id); - $ref_id = current($all_refs); - $terms = ilGlossaryTerm::getTermList($ref_id); - foreach ($terms as $t) - { - $defs = ilGlossaryDefinition::getDefinitionList($t["id"]); - foreach ($defs as $d) - { - $page_ids[] = "gdf:".$d["id"]; - $md_ids[] = $id.":".$d["id"].":gdf"; - } - } - } - // definition pages and their metadat - $deps = array ( - array( - "component" => "Services/COPage", - "entity" => "pg", - "ids" => $page_ids), - array( - "component" => "Services/MetaData", - "entity" => "md", - "ids" => $md_ids), - ); - - // taxonomy - include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php"); - $tax_ids = array(); - foreach ($a_ids as $id) - { - $t_ids = ilObjTaxonomy::getUsageOfObject($id); - if (count($t_ids) > 0) - { - $tax_ids[$t_ids[0]] = $t_ids[0]; - } - } - if(sizeof($tax_ids)) - { - $deps[] = array( - "component" => "Services/Taxonomy", - "entity" => "tax", - "ids" => $tax_ids - ); - } - - // advanced metadata - $advmd_ids = array(); - foreach($a_ids as $id) - { - $rec_ids = $this->getActiveAdvMDRecords($id); - if(sizeof($rec_ids)) - { - foreach($rec_ids as $rec_id) - { - $advmd_ids[] = $id.":".$rec_id; - } - } - } - if(sizeof($advmd_ids)) - { - $deps[] = array( - "component" => "Services/AdvancedMetaData", - "entity" => "advmd", - "ids" => $advmd_ids - ); - } - - // style - $obj_ids = (is_array($a_ids)) - ? $a_ids - : array($a_ids); - $deps[] = array( - "component" => "Services/Style", - "entity" => "object_style", - "ids" => $obj_ids - ); - - // service settings - $deps[] = array( - "component" => "Services/Object", - "entity" => "common", - "ids" => $a_ids); - - return $deps; - } - return array(); - } - - protected function getActiveAdvMDRecords($a_id) - { - include_once('./Services/AdvancedMetaData/classes/class.ilAdvancedMDRecord.php'); - $active = array(); - // selected globals - $sel_globals = ilAdvancedMDRecord::getObjRecSelection($a_id, "term"); - - foreach(ilAdvancedMDRecord::_getActivatedRecordsByObjectType("glo", "term") as $record_obj) - { - // local ones and globally activated for the object - if ($record_obj->getParentObject() == $a_id || in_array($record_obj->getRecordId(), $sel_globals)) - { - $active[] = $record_obj->getRecordId(); - } - } - - return $active; - } - - /** - * Get xml representation - * - * @param string entity - * @param string target release - * @param string id - * @return string xml string - */ - public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) - { - return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); - - /*include_once './Modules/Glossary/classes/class.ilObjGlossary.php'; - $glo = new ilObjGlossary($a_id,false); - - include_once './Modules/Glossary/classes/class.ilGlossaryExport.php'; - $exp = new ilGlossaryExport($glo,'xml'); - $zip = $exp->buildExportFile();*/ - } - - /** - * Returns schema versions that the component can export to. - * ILIAS chooses the first one, that has min/max constraints which - * fit to the target release. Please put the newest on top. - * - * @return - */ - function getValidSchemaVersions($a_entity) - { - return array ( - "5.1.0" => array( - "namespace" => "http://www.ilias.de/Modules/Glossary/htlm/4_1", - "xsd_file" => "ilias_glo_5_1.xsd", - "uses_dataset" => true, - "min" => "5.1.0", - "max" => ""), - "4.1.0" => array( - "namespace" => "http://www.ilias.de/Modules/Glossary/htlm/4_1", - "xsd_file" => "ilias_glo_4_1.xsd", - "uses_dataset" => false, - "min" => "4.1.0", - "max" => "") - ); - } - + private $ds; + + /** + * Initialisation + */ + public function init() + { + include_once("./Modules/Glossary/classes/class.ilGlossaryDataSet.php"); + $this->ds = new ilGlossaryDataSet(); + $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); + $this->ds->setDSPrefix("ds"); + } + + /** + * Get tail dependencies + * + * @param string entity + * @param string target release + * @param array ids + * @return array array of array with keys "component", entity", "ids" + */ + public function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) + { + if ($a_entity == "glo") { + include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + include_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); + + $md_ids = array(); + + // glo related ids + foreach ($a_ids as $id) { + $md_ids[] = $id . ":0:glo"; + } + + // definition related ids + $page_ids = array(); + foreach ($a_ids as $id) { + // workaround for #0023923 + $all_refs = ilObject::_getAllReferences($id); + $ref_id = current($all_refs); + $terms = ilGlossaryTerm::getTermList($ref_id); + foreach ($terms as $t) { + $defs = ilGlossaryDefinition::getDefinitionList($t["id"]); + foreach ($defs as $d) { + $page_ids[] = "gdf:" . $d["id"]; + $md_ids[] = $id . ":" . $d["id"] . ":gdf"; + } + } + } + // definition pages and their metadat + $deps = array( + array( + "component" => "Services/COPage", + "entity" => "pg", + "ids" => $page_ids), + array( + "component" => "Services/MetaData", + "entity" => "md", + "ids" => $md_ids), + ); + + // taxonomy + include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php"); + $tax_ids = array(); + foreach ($a_ids as $id) { + $t_ids = ilObjTaxonomy::getUsageOfObject($id); + if (count($t_ids) > 0) { + $tax_ids[$t_ids[0]] = $t_ids[0]; + } + } + if (sizeof($tax_ids)) { + $deps[] = array( + "component" => "Services/Taxonomy", + "entity" => "tax", + "ids" => $tax_ids + ); + } + + // advanced metadata + $advmd_ids = array(); + foreach ($a_ids as $id) { + $rec_ids = $this->getActiveAdvMDRecords($id); + if (sizeof($rec_ids)) { + foreach ($rec_ids as $rec_id) { + $advmd_ids[] = $id . ":" . $rec_id; + } + } + } + if (sizeof($advmd_ids)) { + $deps[] = array( + "component" => "Services/AdvancedMetaData", + "entity" => "advmd", + "ids" => $advmd_ids + ); + } + + // style + $obj_ids = (is_array($a_ids)) + ? $a_ids + : array($a_ids); + $deps[] = array( + "component" => "Services/Style", + "entity" => "object_style", + "ids" => $obj_ids + ); + + // service settings + $deps[] = array( + "component" => "Services/Object", + "entity" => "common", + "ids" => $a_ids); + + return $deps; + } + return array(); + } + + protected function getActiveAdvMDRecords($a_id) + { + include_once('./Services/AdvancedMetaData/classes/class.ilAdvancedMDRecord.php'); + $active = array(); + // selected globals + $sel_globals = ilAdvancedMDRecord::getObjRecSelection($a_id, "term"); + + foreach (ilAdvancedMDRecord::_getActivatedRecordsByObjectType("glo", "term") as $record_obj) { + // local ones and globally activated for the object + if ($record_obj->getParentObject() == $a_id || in_array($record_obj->getRecordId(), $sel_globals)) { + $active[] = $record_obj->getRecordId(); + } + } + + return $active; + } + + /** + * Get xml representation + * + * @param string entity + * @param string target release + * @param string id + * @return string xml string + */ + public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) + { + return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); + + /*include_once './Modules/Glossary/classes/class.ilObjGlossary.php'; + $glo = new ilObjGlossary($a_id,false); + + include_once './Modules/Glossary/classes/class.ilGlossaryExport.php'; + $exp = new ilGlossaryExport($glo,'xml'); + $zip = $exp->buildExportFile();*/ + } + + /** + * Returns schema versions that the component can export to. + * ILIAS chooses the first one, that has min/max constraints which + * fit to the target release. Please put the newest on top. + * + * @return + */ + public function getValidSchemaVersions($a_entity) + { + return array( + "5.1.0" => array( + "namespace" => "http://www.ilias.de/Modules/Glossary/htlm/4_1", + "xsd_file" => "ilias_glo_5_1.xsd", + "uses_dataset" => true, + "min" => "5.1.0", + "max" => ""), + "4.1.0" => array( + "namespace" => "http://www.ilias.de/Modules/Glossary/htlm/4_1", + "xsd_file" => "ilias_glo_4_1.xsd", + "uses_dataset" => false, + "min" => "4.1.0", + "max" => "") + ); + } } - -?> \ No newline at end of file diff --git a/Modules/Glossary/classes/class.ilGlossaryForeignTermCollectorGUI.php b/Modules/Glossary/classes/class.ilGlossaryForeignTermCollectorGUI.php index 6c934b0b85305b72fbc0c197bd4a3c1446c1f925..7e0c3da92c9f596580d7964f8c7d04717097363e 100644 --- a/Modules/Glossary/classes/class.ilGlossaryForeignTermCollectorGUI.php +++ b/Modules/Glossary/classes/class.ilGlossaryForeignTermCollectorGUI.php @@ -11,196 +11,188 @@ */ class ilGlossaryForeignTermCollectorGUI { - /** - * @var ilObjGlossaryGUI - */ - protected $glossary_gui; - - /** - * @var ilObjGlossary - */ - protected $glossary; - - /** - * @var int ref id of foreign glossary - */ - protected $fglo_ref_id; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * Constructor - * - * @param ilObjGlossaryGUI $a_glossary_gui - */ - protected function __construct(ilObjGlossaryGUI $a_glossary_gui) - { - global $DIC; - - $this->tpl = $DIC["tpl"]; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - - $this->glossary_gui = $a_glossary_gui; - $this->glossary = $a_glossary_gui->object; - - $this->fglo_ref_id = (int) $_GET["fglo_ref_id"]; - if ($this->fglo_ref_id > 0 && ilObject::_lookupType($this->fglo_ref_id, true) == "glo") - { - $this->foreign_glossary = new ilObjGlossary($this->fglo_ref_id, true); - } - - $this->ctrl->saveParameter($this, "fglo_ref_id"); - } - - /** - * Get instance - * - * @param ilObjGlossaryGUI $a_glossary_gui - * @return ilGlossaryForeignTermCollectorGUI - */ - public static function getInstance(ilObjGlossaryGUI $a_glossary_gui) - { - return new self($a_glossary_gui); - } - - /** - * Execute command - */ - function executeCommand() - { - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd("showGlossarySelector"); - - switch ($next_class) - { - default: - if (in_array($cmd, array("showGlossarySelector", "setForeignGlossary", "showTerms", "copyTerms", "referenceTerms"))) - { - $this->$cmd(); - } - } - } - - /** - * Add level resource - */ - function showGlossarySelector() - { - ilUtil::sendInfo($this->lng->txt("glo_select_source_glo")); - include_once("./Services/Repository/classes/class.ilRepositorySelectorExplorerGUI.php"); - $exp = new ilRepositorySelectorExplorerGUI($this, "showGlossarySelector", - $this, "setForeignGlossary", "fglo_ref_id"); - $exp->setTypeWhiteList(array("root", "cat", "grp", "crs", "glo", "fold")); - $exp->setClickableTypes(array("glo")); - if (!$exp->handleCommand()) - { - $this->tpl->setContent($exp->getHTML()); - } - } - - /** - * Save level resource - */ - function setForeignGlossary() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $ref_id = (int) $_GET["fglo_ref_id"]; - - if ($ref_id == $this->glossary->getRefId()) - { - ilUtil::sendFailure($lng->txt("glo_please_select_other_glo"), true); - $ilCtrl->redirect($this, "showGlossarySelector"); - } - - $ilCtrl->redirect($this, "showTerms"); - } - - /** - * Show Terms - * - * @param - * @return - */ - function showTerms() - { - include_once("./Modules/Glossary/classes/class.ilGlossaryForeignTermTableGUI.php"); - $t = new ilGlossaryForeignTermTableGUI($this, "showTerms", $this->foreign_glossary); - - $this->tpl->setContent($t->getHTML()); - } - - /** - * Copy terms - * - * @param - * @return - */ - function copyTerms() - { - if(!is_array($_POST["term_id"])) - { - ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); - $this->ctrl->redirect($this, "showTerms"); - } - include_once("./Modules/Glossary/classes/class.ilGlossaryAct.php"); - $act = ilGlossaryAct::getInstance($this->glossary, $this->user); - foreach ($_POST["term_id"] as $id) - { - $act->copyTerm($this->foreign_glossary, (int) $id); - } - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->returnToParent($this); - } - - /** - * Reference terms - * - * @param - * @return - */ - function referenceTerms() - { - if(!is_array($_POST["term_id"])) - { - ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); - $this->ctrl->redirect($this, "showTerms"); - } - include_once("./Modules/Glossary/classes/class.ilGlossaryAct.php"); - $act = ilGlossaryAct::getInstance($this->glossary, $this->user); - $terms = array(); - foreach ($_POST["term_id"] as $id) - { - $terms[] = (int) $id; - - } - $act->referenceTerms($this->foreign_glossary, $terms); - - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->returnToParent($this); - } - + /** + * @var ilObjGlossaryGUI + */ + protected $glossary_gui; + + /** + * @var ilObjGlossary + */ + protected $glossary; + + /** + * @var int ref id of foreign glossary + */ + protected $fglo_ref_id; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * Constructor + * + * @param ilObjGlossaryGUI $a_glossary_gui + */ + protected function __construct(ilObjGlossaryGUI $a_glossary_gui) + { + global $DIC; + + $this->tpl = $DIC["tpl"]; + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + + $this->glossary_gui = $a_glossary_gui; + $this->glossary = $a_glossary_gui->object; + + $this->fglo_ref_id = (int) $_GET["fglo_ref_id"]; + if ($this->fglo_ref_id > 0 && ilObject::_lookupType($this->fglo_ref_id, true) == "glo") { + $this->foreign_glossary = new ilObjGlossary($this->fglo_ref_id, true); + } + + $this->ctrl->saveParameter($this, "fglo_ref_id"); + } + + /** + * Get instance + * + * @param ilObjGlossaryGUI $a_glossary_gui + * @return ilGlossaryForeignTermCollectorGUI + */ + public static function getInstance(ilObjGlossaryGUI $a_glossary_gui) + { + return new self($a_glossary_gui); + } + + /** + * Execute command + */ + public function executeCommand() + { + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd("showGlossarySelector"); + + switch ($next_class) { + default: + if (in_array($cmd, array("showGlossarySelector", "setForeignGlossary", "showTerms", "copyTerms", "referenceTerms"))) { + $this->$cmd(); + } + } + } + + /** + * Add level resource + */ + public function showGlossarySelector() + { + ilUtil::sendInfo($this->lng->txt("glo_select_source_glo")); + include_once("./Services/Repository/classes/class.ilRepositorySelectorExplorerGUI.php"); + $exp = new ilRepositorySelectorExplorerGUI( + $this, + "showGlossarySelector", + $this, + "setForeignGlossary", + "fglo_ref_id" + ); + $exp->setTypeWhiteList(array("root", "cat", "grp", "crs", "glo", "fold")); + $exp->setClickableTypes(array("glo")); + if (!$exp->handleCommand()) { + $this->tpl->setContent($exp->getHTML()); + } + } + + /** + * Save level resource + */ + public function setForeignGlossary() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $ref_id = (int) $_GET["fglo_ref_id"]; + + if ($ref_id == $this->glossary->getRefId()) { + ilUtil::sendFailure($lng->txt("glo_please_select_other_glo"), true); + $ilCtrl->redirect($this, "showGlossarySelector"); + } + + $ilCtrl->redirect($this, "showTerms"); + } + + /** + * Show Terms + * + * @param + * @return + */ + public function showTerms() + { + include_once("./Modules/Glossary/classes/class.ilGlossaryForeignTermTableGUI.php"); + $t = new ilGlossaryForeignTermTableGUI($this, "showTerms", $this->foreign_glossary); + + $this->tpl->setContent($t->getHTML()); + } + + /** + * Copy terms + * + * @param + * @return + */ + public function copyTerms() + { + if (!is_array($_POST["term_id"])) { + ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); + $this->ctrl->redirect($this, "showTerms"); + } + include_once("./Modules/Glossary/classes/class.ilGlossaryAct.php"); + $act = ilGlossaryAct::getInstance($this->glossary, $this->user); + foreach ($_POST["term_id"] as $id) { + $act->copyTerm($this->foreign_glossary, (int) $id); + } + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->returnToParent($this); + } + + /** + * Reference terms + * + * @param + * @return + */ + public function referenceTerms() + { + if (!is_array($_POST["term_id"])) { + ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); + $this->ctrl->redirect($this, "showTerms"); + } + include_once("./Modules/Glossary/classes/class.ilGlossaryAct.php"); + $act = ilGlossaryAct::getInstance($this->glossary, $this->user); + $terms = array(); + foreach ($_POST["term_id"] as $id) { + $terms[] = (int) $id; + } + $act->referenceTerms($this->foreign_glossary, $terms); + + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->returnToParent($this); + } } - -?> \ No newline at end of file diff --git a/Modules/Glossary/classes/class.ilGlossaryForeignTermTableGUI.php b/Modules/Glossary/classes/class.ilGlossaryForeignTermTableGUI.php index e79be50e8081a32c7f557506cefd6e583e009abe..608fbd49286cc869f6bde41bcc5b1833bf8a9056 100644 --- a/Modules/Glossary/classes/class.ilGlossaryForeignTermTableGUI.php +++ b/Modules/Glossary/classes/class.ilGlossaryForeignTermTableGUI.php @@ -14,62 +14,60 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilGlossaryForeignTermTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilObjGlossary - */ - protected $glossary; + /** + * @var ilObjGlossary + */ + protected $glossary; - /** - * ilGlossaryForeignTermTableGUI constructor. - * - * @param object $a_parent_obj - * @param string $a_parent_cmd - * @param ilObjGlossary $a_glossary - */ - function __construct($a_parent_obj, $a_parent_cmd, ilObjGlossary $a_glossary) - { - global $DIC; + /** + * ilGlossaryForeignTermTableGUI constructor. + * + * @param object $a_parent_obj + * @param string $a_parent_cmd + * @param ilObjGlossary $a_glossary + */ + public function __construct($a_parent_obj, $a_parent_cmd, ilObjGlossary $a_glossary) + { + global $DIC; - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $this->glossary = $a_glossary; - - parent::__construct($a_parent_obj, $a_parent_cmd); - $terms = $this->glossary->getTermList(); + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->glossary = $a_glossary; + + parent::__construct($a_parent_obj, $a_parent_cmd); + $terms = $this->glossary->getTermList(); - $this->setData($terms); - $this->setTitle($this->glossary->getTitle().": ".$this->lng->txt("glo_select_terms")); - - $this->addColumn("", "", "1"); - $this->addColumn($this->lng->txt("glo_term")); - - $this->setFormAction($this->ctrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.glo_foreign_term_row.html", "Modules/Glossary"); + $this->setData($terms); + $this->setTitle($this->glossary->getTitle() . ": " . $this->lng->txt("glo_select_terms")); + + $this->addColumn("", "", "1"); + $this->addColumn($this->lng->txt("glo_term")); + + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.glo_foreign_term_row.html", "Modules/Glossary"); - $this->addMultiCommand("copyTerms", $this->lng->txt("glo_copy_terms")); - $this->addMultiCommand("referenceTerms", $this->lng->txt("glo_reference_terms")); - - //$this->addCommandButton("", $lng->txt("")); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $this->tpl->setVariable("TERM", $a_set["term"]); - $this->tpl->setVariable("TERM_ID", $a_set["id"]); - } + $this->addMultiCommand("copyTerms", $this->lng->txt("glo_copy_terms")); + $this->addMultiCommand("referenceTerms", $this->lng->txt("glo_reference_terms")); + //$this->addCommandButton("", $lng->txt("")); + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $this->tpl->setVariable("TERM", $a_set["term"]); + $this->tpl->setVariable("TERM_ID", $a_set["id"]); + } } -?> \ No newline at end of file diff --git a/Modules/Glossary/classes/class.ilGlossaryImportConfig.php b/Modules/Glossary/classes/class.ilGlossaryImportConfig.php index 44e2670b8dc84871465999610adc3997be1cf552..eda7ba5b26638c2ed8dda37c2179f6c1675f7643 100644 --- a/Modules/Glossary/classes/class.ilGlossaryImportConfig.php +++ b/Modules/Glossary/classes/class.ilGlossaryImportConfig.php @@ -12,7 +12,4 @@ include_once("./Services/Export/classes/class.ilImportConfig.php"); */ class ilGlossaryImportConfig extends ilImportConfig { - } - -?> \ No newline at end of file diff --git a/Modules/Glossary/classes/class.ilGlossaryImporter.php b/Modules/Glossary/classes/class.ilGlossaryImporter.php index 867409509763ecc59dcef6c668b91766180edd8c..5687d61eb3da8b09021b8e9afd2e62890407d902 100644 --- a/Modules/Glossary/classes/class.ilGlossaryImporter.php +++ b/Modules/Glossary/classes/class.ilGlossaryImporter.php @@ -12,149 +12,147 @@ include_once("./Services/Export/classes/class.ilXmlImporter.php"); */ class ilGlossaryImporter extends ilXmlImporter { - /** - * Initialisation - */ - 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 - */ - 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 - */ - 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); - } - } - } - } - } - } - + /** + * 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; $jsetGlossary($this->glossary); - $page_gui->setOutputMode($a_page_mode); - $page_gui->setStyleId($this->glossary->getStyleSheetId()); - $page = $page_gui->getPageObject(); - - // internal links - $page->buildDom(); - $int_links = $page->getInternalLinks(); - $link_xml = $this->getLinkXML($int_links); - $page_gui->setLinkXML($link_xml); - - if ($this->offlineMode()) - { - $page_gui->setOutputMode("offline"); - $page_gui->setOfflineDirectory($this->getOfflineDirectory()); - } - $page_gui->setSourcecodeDownloadScript($this->getLink($ref_id)); - $page_gui->setFullscreenLink($this->getLink($ref_id, "fullscreen", $term_id, $def["id"])); - - $page_gui->setTemplateOutput(false); - $page_gui->setRawPageContent(true); - $page_gui->setFileDownloadLink($this->getLink($ref_id, "downloadFile")); - if (!$this->offlineMode()) - { - $output = $page_gui->showPage(); - } - else - { - $output = $page_gui->presentation($page_gui->getOutputMode()); - } - - if (count($defs) > 1) - { - $tpl->setCurrentBlock("definition_header"); - $tpl->setVariable("TXT_DEFINITION", - $this->lng->txt("cont_definition")." ".($j+1)); - $tpl->setVariable("DEF_NR", ($j+1)); - $tpl->parseCurrentBlock(); - } - - $tpl->setCurrentBlock("definition"); - $tpl->setVariable("PAGE_CONTENT", $output); - $tpl->parseCurrentBlock(); - } - - // display possible backlinks - $sources = ilInternalLink::_getSourcesOfTarget('git',$_GET['term_id'],0); - - if ($sources) - { - $backlist_shown = false; - foreach ($sources as $src) - { - $type = explode(':',$src['type']); - - if ($type[0] == 'lm') - { - if ($type[1] == 'pg') - { - $title = ilLMPageObject::_getPresentationTitle($src['id']); - $lm_id = ilLMObject::_lookupContObjID($src['id']); - $lm_title = ilObject::_lookupTitle($lm_id); - $tpl->setCurrentBlock('backlink_item'); - $ref_ids = ilObject::_getAllReferences($lm_id); - $access = false; - foreach($ref_ids as $rid) - { - if ($ilAccess->checkAccess("read", "", $rid)) - { - $access = true; - } - } - if ($access) - { - $tpl->setCurrentBlock("backlink_item"); - $tpl->setVariable("BACKLINK_LINK",ILIAS_HTTP_PATH."/goto.php?target=".$type[1]."_".$src['id']); - $tpl->setVariable("BACKLINK_ITEM",$lm_title.": ".$title); - $tpl->parseCurrentBlock(); - $backlist_shown = true; - } - } - } - } - if ($backlist_shown) - { - $tpl->setCurrentBlock("backlink_list"); - $tpl->setVariable("BACKLINK_TITLE",$this->lng->txt('glo_term_used_in')); - $tpl->parseCurrentBlock(); - } - } - - if (!$a_get_html) - { - $tpl->setCurrentBlock("perma_link"); - $tpl->setVariable("PERMA_LINK", ILIAS_HTTP_PATH. - "/goto.php?target=". - "git". - "_".$term_id."_".$ref_id."&client_id=".CLIENT_ID); - $tpl->setVariable("TXT_PERMA_LINK", $this->lng->txt("perma_link")); - $tpl->setVariable("PERMA_TARGET", "_top"); - $tpl->parseCurrentBlock(); - - // show taxonomy - $this->showTaxonomy(); - } - - // highlighting? - if ($_GET["srcstring"] != "" && !$this->offlineMode()) - { - include_once './Services/Search/classes/class.ilUserSearchCache.php'; - $cache = ilUserSearchCache::_getInstance($ilUser->getId()); - $cache->switchSearchType(ilUserSearchCache::LAST_QUERY); - $search_string = $cache->getQuery(); - - include_once("./Services/UIComponent/TextHighlighter/classes/class.ilTextHighlighterGUI.php"); - include_once("./Services/Search/classes/class.ilQueryParser.php"); - $p = new ilQueryParser($search_string); - $p->parse(); - - $words = $p->getQuotedWords(); - if (is_array($words)) - { - foreach ($words as $w) - { - ilTextHighlighterGUI::highlight("ilGloContent", $w, $tpl); - } - } - $this->fill_on_load_code = true; - } - - if ($this->offlineMode() || $a_get_html) - { - return $tpl->get(); - } - } - - /** - * Definitions tabs - * - * @param - * @return - */ - function showDefinitionTabs($a_act) - { - $ilTabs = $this->tabs_gui; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilHelp = $this->help; - - if (!$this->offlineMode()) - { - $ilHelp->setScreenIdComponent("glo"); - - $ilCtrl->setParameter($this, "term_id", ""); - $this->ctrl->setParameter($this, "offset", $_GET["offset"]); - if (!empty ($_REQUEST["term"])) - { - $this->ctrl->setParameter($this, "term", $_REQUEST["term"]); - $this->ctrl->setParameter($this, "oldoffset", $_GET["oldoffset"]); - $back = $ilCtrl->getLinkTarget($this, "searchTerms"); - } - else - { - $back = $ilCtrl->getLinkTarget($this, "listTerms"); - } - $ilCtrl->setParameter($this, "term_id", $this->term_id); - $ilCtrl->saveParameter($this, "term_id"); - - $ilTabs->setBackTarget($this->lng->txt("obj_glo"), $back); - - $ilTabs->addTab("term_content", - $lng->txt("content"), - $ilCtrl->getLinkTarget($this, "listDefinitions")); - - $ilTabs->addTab("print_view", - $lng->txt("print_view"), - $ilCtrl->getLinkTarget($this, "printViewSelection")); - - $ilCtrl->setParameterByClass("ilglossarytermgui", "term_id", $this->term_id); - include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - if (ilGlossaryTerm::_lookGlossaryID($this->term_id) == $this->glossary->getId()) - { - $ilTabs->addNonTabbedLink("editing_view", - $lng->txt("glo_editing_view"), - $ilCtrl->getLinkTargetByClass(array("ilglossaryeditorgui", "ilobjglossarygui", "ilglossarytermgui"), "listDefinitions")); - //"ilias.php?baseClass=ilGlossaryEditorGUI&ref_id=".$_GET["ref_id"]."&edit_term=".$this->term_id); - } - $ilTabs->activateTab($a_act); - } - } - - - /** - * show fullscreen view - */ - function fullscreen() - { - $html = $this->media("fullscreen"); - return $html; - } - - /** - * show media object - */ - function media($a_mode = "media") - { - $this->tpl = new ilTemplate("tpl.fullscreen.html", true, true, "Services/COPage"); - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $this->tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->glossary->getStyleSheetId())); - - //$int_links = $page_object->getInternalLinks(); - $med_links = ilMediaItem::_getMapAreasIntLinks($_GET["mob_id"]); - - // later - //$link_xml = $this->getLinkXML($med_links, $this->getLayoutLinkTargets()); - - $link_xlm = ""; - - require_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $media_obj = new ilObjMediaObject($_GET["mob_id"]); - - $xml = ""; - // todo: we get always the first alias now (problem if mob is used multiple - // times in page) - $xml.= $media_obj->getXML(IL_MODE_ALIAS); - $xml.= $media_obj->getXML(IL_MODE_OUTPUT); - $xml.= $link_xml; - $xml.=""; - - $xsl = file_get_contents("./Services/COPage/xsl/page.xsl"); - $args = array( '/_xml' => $xml, '/_xsl' => $xsl ); - $xh = xslt_create(); - - if (!$this->offlineMode()) - { - $enlarge_path = ilUtil::getImagePath("enlarge.svg", false, "output"); - $wb_path = ilUtil::getWebspaceDir("output")."/"; - } - else - { - $enlarge_path = "images/enlarge.svg"; - $wb_path = ""; - } - - $mode = $a_mode; - - $this->ctrl->setParameter($this, "obj_type", "MediaObject"); - $fullscreen_link = - $this->getLink($_GET["ref_id"], "fullscreen"); - $this->ctrl->clearParameters($this); - - $params = array ('mode' => $mode, 'enlarge_path' => $enlarge_path, - 'link_params' => "ref_id=".$_GET["ref_id"],'fullscreen_link' => $fullscreen_link, - 'ref_id' => $_GET["ref_id"], 'pg_frame' => $pg_frame, 'webspace_path' => $wb_path); - $output = xslt_process($xh,"arg:/_xml","arg:/_xsl",NULL,$args, $params); - echo xslt_error($xh); - xslt_free($xh); - - // unmask user html - $this->tpl->setVariable("MEDIA_CONTENT", $output); - - $this->tpl->parseCurrentBlock(); - if ($this->offlineMode()) - { - $html = $this->tpl->get(); - return $html; - } - - } - - /** - * show download list - */ - function showDownloadList() - { - $ilAccess = $this->access; - $lng = $this->lng; - $ilTabs = $this->tabs_gui; - - if (!$ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - $ilErr->raiseError($lng->txt("permission_denied"), $ilErr->MESSAGE); - } - - $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.glo_download_list.html", "Modules/Glossary"); - - $this->setTabs(); - $ilTabs->activateTab("download"); - - // set title header - $this->tpl->setTitle($this->glossary->getTitle()); - $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_glo.svg")); - - // create table - require_once("./Services/Table/classes/class.ilTableGUI.php"); - $tbl = new ilTableGUI(); - - // load files templates - $this->tpl->addBlockfile("DOWNLOAD_TABLE", "download_table", "tpl.table.html"); - - // load template for table content data - $this->tpl->addBlockfile("TBL_CONTENT", "tbl_content", "tpl.download_file_row.html", "Modules/Glossary"); - - $export_files = array(); - $types = array("xml", "html"); - foreach($types as $type) - { - if ($this->glossary->getPublicExportFile($type) != "") - { - $dir = $this->glossary->getExportDirectory($type); - if (is_file($this->glossary->getExportDirectory($type)."/". - $this->glossary->getPublicExportFile($type))) - { - $size = filesize($this->glossary->getExportDirectory($type)."/". - $this->glossary->getPublicExportFile($type)); - $export_files[] = array("type" => $type, - "file" => $this->glossary->getPublicExportFile($type), - "size" => $size); - } - } - } - - $num = 0; - - $tbl->setTitle($this->lng->txt("download")); - - $tbl->setHeaderNames(array($this->lng->txt("cont_format"), - $this->lng->txt("cont_file"), - $this->lng->txt("size"), $this->lng->txt("date"), - "")); - - $cols = array("format", "file", "size", "date", "download"); - $header_params = array("ref_id" => $_GET["ref_id"], "obj_id" => $_GET["obj_id"], - "cmd" => "showDownloadList", "cmdClass" => strtolower(get_class($this))); - $tbl->setHeaderVars($cols, $header_params); - $tbl->setColumnWidth(array("10%", "30%", "20%", "20%","20%")); - $tbl->disable("sort"); - - // control - $tbl->setOrderColumn($_GET["sort_by"]); - $tbl->setOrderDirection($_GET["sort_order"]); - $tbl->setLimit($_GET["limit"]); - $tbl->setOffset($_GET["offset"]); - $tbl->setMaxCount($this->maxcount); // ??? - - // $this->tpl->setVariable("COLUMN_COUNTS", 5); - - // footer - //$tbl->setFooter("tblfooter",$this->lng->txt("previous"),$this->lng->txt("next")); - $tbl->disable("footer"); - - $tbl->setMaxCount(count($export_files)); - $export_files = array_slice($export_files, $_GET["offset"], $_GET["limit"]); - - $tbl->render(); - if(count($export_files) > 0) - { - $i=0; - foreach($export_files as $exp_file) - { - $this->tpl->setCurrentBlock("tbl_content"); - $this->tpl->setVariable("TXT_FILENAME", $exp_file["file"]); - - $css_row = ilUtil::switchColor($i++, "tblrow1", "tblrow2"); - $this->tpl->setVariable("CSS_ROW", $css_row); - - $this->tpl->setVariable("TXT_SIZE", $exp_file["size"]); - $this->tpl->setVariable("TXT_FORMAT", strtoupper($exp_file["type"])); - $this->tpl->setVariable("CHECKBOX_ID", $exp_file["type"].":".$exp_file["file"]); - - $file_arr = explode("__", $exp_file["file"]); - $this->tpl->setVariable("TXT_DATE", date("Y-m-d H:i:s",$file_arr[0])); - - $this->tpl->setVariable("TXT_DOWNLOAD", $this->lng->txt("download")); - $this->ctrl->setParameter($this, "type", $exp_file["type"]); - $this->tpl->setVariable("LINK_DOWNLOAD", - $this->ctrl->getLinkTarget($this, "downloadExportFile")); - - $this->tpl->parseCurrentBlock(); - } - } //if is_array - else - { - $this->tpl->setVariable("TXT_OBJECT_NOT_FOUND", $this->lng->txt("obj_not_found")); - $this->tpl->setVariable("NUM_COLS", 5); - $this->tpl->parseCurrentBlock(); - } - - //$this->tpl->show(); - } - - /** - * send download file (xml/html) - */ - function downloadExportFile() - { - $ilAccess = $this->access; - $ilErr = $this->error; - $lng = $this->lng; - - if (!$ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - $ilErr->raiseError($lng->txt("permission_denied"), $ilErr->error_obj->MESSAGE); - } - - $file = $this->glossary->getPublicExportFile($_GET["type"]); - if ($this->glossary->getPublicExportFile($_GET["type"]) != "") - { - $dir = $this->glossary->getExportDirectory($_GET["type"]); - if (is_file($dir."/".$file)) - { - ilUtil::deliverFile($dir."/".$file, $file); - exit; - } - } - $ilErr->raiseError($this->lng->txt("file_not_found"),$ilErr->MESSAGE); - } - - /** - * set Locator - * - * @param object tree object - * @param integer reference id - * @access public - */ - function setLocator($a_tree = "", $a_id = "") - { - //$this->tpl->addBlockFile("LOCATOR", "locator", "tpl.locator.html", "Services/Locator"); - require_once ("./Modules/Glossary/classes/class.ilGlossaryLocatorGUI.php"); - $gloss_loc = new ilGlossaryLocatorGUI(); - $gloss_loc->setMode("presentation"); - if (!empty($this->term_id)) - { - $term = new ilGlossaryTerm($this->term_id); - $gloss_loc->setTerm($term); - } - $gloss_loc->setGlossary($this->glossary); - //$gloss_loc->setDefinition($this->definition); - $gloss_loc->display(); - } - - /** - * download file of file lists - */ - function downloadFile() - { - $ilAccess = $this->access; - $ilErr = $this->error; - $lng = $this->lng; - - if (!$ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - $ilErr->raiseError($lng->txt("permission_denied"), $ilErr->MESSAGE); - } - - $file = explode("_", $_GET["file_id"]); - include_once("./Modules/File/classes/class.ilObjFile.php"); - $fileObj = new ilObjFile($file[count($file) - 1], false); - $fileObj->sendFile(); - exit; - } - - /** - * output tabs - */ - function setTabs() - { - $this->getTabs(); - } - - /** - * get link targets - */ - function getLinkXML($a_int_links) - { - - if ($a_layoutframes == "") - { - $a_layoutframes = array(); - } - $link_info = ""; - foreach ($a_int_links as $int_link) - { -//echo "
+".$int_link["Type"]."+".$int_link["TargetFrame"]."+".$int_link["Target"]."+"; - $target = $int_link["Target"]; - if (substr($target, 0, 4) == "il__") - { - $target_arr = explode("_", $target); - $target_id = $target_arr[count($target_arr) - 1]; - $type = $int_link["Type"]; - $targetframe = ($int_link["TargetFrame"] != "") - ? $int_link["TargetFrame"] - : "None"; - - // anchor - $anc = $anc_add = ""; - if ($int_link["Anchor"] != "") - { - $anc = $int_link["Anchor"]; - $anc_add = "_".rawurlencode($int_link["Anchor"]); - } - - if ($targetframe == "New") - { - $ltarget = "_blank"; - } - else - { - $ltarget = ""; - } - $lcontent = ""; - switch($type) - { - case "PageObject": - case "StructureObject": - $lm_id = ilLMObject::_lookupContObjID($target_id); - $cont_obj = $this->content_object; - if ($type == "PageObject") - { - $href = "./goto.php?target=pg_".$target_id.$anc_add; - } - else - { - $href = "./goto.php?target=st_".$target_id; - } - //$ltarget = "ilContObj".$lm_id; - break; - - case "GlossaryItem": - if (ilGlossaryTerm::_lookGlossaryID($target_id) == $this->glossary->getId()) - { - if ($this->offlineMode()) - { - $href = "term_".$target_id.".html"; - } - else - { - $this->ctrl->setParameter($this, "term_id", $target_id); - $href = $this->ctrl->getLinkTarget($this, "listDefinitions"); - $href = str_replace("&", "&", $href); - } - } - else - { - $href = "./goto.php?target=git_".$target_id; - } - break; - - case "MediaObject": - if ($this->offlineMode()) - { - $href = "media_".$target_id.".html"; - } - else - { - $this->ctrl->setParameter($this, "obj_type", $type); - $this->ctrl->setParameter($this, "mob_id", $target_id); - $href = $this->ctrl->getLinkTarget($this, "media"); - $href = str_replace("&", "&", $href); - } - break; - - case "RepositoryItem": - $obj_type = ilObject::_lookupType($target_id, true); - $obj_id = ilObject::_lookupObjId($target_id); - $href = "./goto.php?target=".$obj_type."_".$target_id; - $t_frame = ilFrameTargetInfo::_getFrame("MainContent", $obj_type); - $ltarget = $t_frame; - break; - - case "WikiPage": - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $href = ilWikiPage::getGotoForWikiPageTarget($target_id); - break; - - case "User": - $obj_type = ilObject::_lookupType($target_id); - if ($obj_type == "usr") - { - include_once("./Services/User/classes/class.ilUserUtil.php"); - $back = $this->ctrl->getLinkTarget($this, "listDefinitions"); - //var_dump($back); exit; - $this->ctrl->setParameterByClass("ilpublicuserprofilegui", "user_id", $target_id); - $this->ctrl->setParameterByClass("ilpublicuserprofilegui", "back_url", - rawurlencode($back)); - $href = ""; - include_once("./Services/User/classes/class.ilUserUtil.php"); - if (ilUserUtil::hasPublicProfile($target_id)) - { - $href = $this->ctrl->getLinkTargetByClass("ilpublicuserprofilegui", "getHTML"); - } - $this->ctrl->setParameterByClass("ilpublicuserprofilegui", "user_id", ""); - $lcontent = ilUserUtil::getNamePresentation($target_id, false, false); - } - break; - - } - - $anc_par = 'Anchor="'.$anc.'"'; - - $link_info.=""; - - $this->ctrl->clearParameters($this); - } - } - $link_info.= "
"; - - return $link_info; - } - - - /** - * handles links for learning module presentation - */ - function getLink($a_ref_id, $a_cmd = "", $a_term_id = "", $a_def_id = "", - $a_frame = "", $a_type = "") - { - if ($a_cmd == "") - { - $a_cmd = "layout"; - } - //$script = "glossary_presentation.php"; - - // handle online links - if (!$this->offlineMode()) - { - //$link = $script."?ref_id=".$a_ref_id; - switch ($a_cmd) - { - case "fullscreen": - $this->ctrl->setParameter($this, "def_id", $a_def_id); - $link = $this->ctrl->getLinkTarget($this, "fullscreen"); - break; - - default: - $link.= "&cmd=".$a_cmd; - if ($a_frame != "") - { - $this->ctrl->setParameter($this, "frame", $a_frame); - } - if ($a_obj_id != "") - { - switch ($a_type) - { - case "MediaObject": - $this->ctrl->setParameter($this, "mob_id", $a_obj_id); - break; - - default: - $this->ctrl->setParameter($this, "def_id", $a_def_id); - break; - } - } - if ($a_type != "") - { - $this->ctrl->setParameter($this, "obj_type", $a_type); - } - $link = $this->ctrl->getLinkTarget($this, $a_cmd); + /** + * @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; + + public $admin_tabs; + public $glossary; + public $tpl; + public $lng; + + /** + * Constructor + * @access public + */ + 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) + */ + public function setOfflineMode($a_offline = true) + { + $this->offline = $a_offline; + } + + /** + * checks wether offline content generation is activated + */ + public function offlineMode() + { + return $this->offline; + } + + /** + * Set offline directory. + */ + public function setOfflineDirectory($a_dir) + { + $this->offline_dir = $a_dir; + } + + + /** + * Get offline directory. + */ + public function getOfflineDirectory() + { + return $this->offline_dir; + } + + + /** + * execute command + */ + public 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(); + } + + public 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 + */ + public 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 + */ + public 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 + */ + public 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 + */ + public 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 + */ + public function resetFilter() + { + $prtab = $this->getPresentationTable(); + $prtab->resetOffset(); + $prtab->resetFilter(); + $this->listTerms(); + } + + /** + * list definitions of a term + */ + public 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; $jsetGlossary($this->glossary); + $page_gui->setOutputMode($a_page_mode); + $page_gui->setStyleId($this->glossary->getStyleSheetId()); + $page = $page_gui->getPageObject(); + + // internal links + $page->buildDom(); + $int_links = $page->getInternalLinks(); + $link_xml = $this->getLinkXML($int_links); + $page_gui->setLinkXML($link_xml); + + if ($this->offlineMode()) { + $page_gui->setOutputMode("offline"); + $page_gui->setOfflineDirectory($this->getOfflineDirectory()); + } + $page_gui->setSourcecodeDownloadScript($this->getLink($ref_id)); + $page_gui->setFullscreenLink($this->getLink($ref_id, "fullscreen", $term_id, $def["id"])); + + $page_gui->setTemplateOutput(false); + $page_gui->setRawPageContent(true); + $page_gui->setFileDownloadLink($this->getLink($ref_id, "downloadFile")); + if (!$this->offlineMode()) { + $output = $page_gui->showPage(); + } else { + $output = $page_gui->presentation($page_gui->getOutputMode()); + } + + if (count($defs) > 1) { + $tpl->setCurrentBlock("definition_header"); + $tpl->setVariable( + "TXT_DEFINITION", + $this->lng->txt("cont_definition") . " " . ($j+1) + ); + $tpl->setVariable("DEF_NR", ($j+1)); + $tpl->parseCurrentBlock(); + } + + $tpl->setCurrentBlock("definition"); + $tpl->setVariable("PAGE_CONTENT", $output); + $tpl->parseCurrentBlock(); + } + + // display possible backlinks + $sources = ilInternalLink::_getSourcesOfTarget('git', $_GET['term_id'], 0); + + if ($sources) { + $backlist_shown = false; + foreach ($sources as $src) { + $type = explode(':', $src['type']); + + if ($type[0] == 'lm') { + if ($type[1] == 'pg') { + $title = ilLMPageObject::_getPresentationTitle($src['id']); + $lm_id = ilLMObject::_lookupContObjID($src['id']); + $lm_title = ilObject::_lookupTitle($lm_id); + $tpl->setCurrentBlock('backlink_item'); + $ref_ids = ilObject::_getAllReferences($lm_id); + $access = false; + foreach ($ref_ids as $rid) { + if ($ilAccess->checkAccess("read", "", $rid)) { + $access = true; + } + } + if ($access) { + $tpl->setCurrentBlock("backlink_item"); + $tpl->setVariable("BACKLINK_LINK", ILIAS_HTTP_PATH . "/goto.php?target=" . $type[1] . "_" . $src['id']); + $tpl->setVariable("BACKLINK_ITEM", $lm_title . ": " . $title); + $tpl->parseCurrentBlock(); + $backlist_shown = true; + } + } + } + } + if ($backlist_shown) { + $tpl->setCurrentBlock("backlink_list"); + $tpl->setVariable("BACKLINK_TITLE", $this->lng->txt('glo_term_used_in')); + $tpl->parseCurrentBlock(); + } + } + + if (!$a_get_html) { + $tpl->setCurrentBlock("perma_link"); + $tpl->setVariable("PERMA_LINK", ILIAS_HTTP_PATH . + "/goto.php?target=" . + "git" . + "_" . $term_id . "_" . $ref_id . "&client_id=" . CLIENT_ID); + $tpl->setVariable("TXT_PERMA_LINK", $this->lng->txt("perma_link")); + $tpl->setVariable("PERMA_TARGET", "_top"); + $tpl->parseCurrentBlock(); + + // show taxonomy + $this->showTaxonomy(); + } + + // highlighting? + if ($_GET["srcstring"] != "" && !$this->offlineMode()) { + include_once './Services/Search/classes/class.ilUserSearchCache.php'; + $cache = ilUserSearchCache::_getInstance($ilUser->getId()); + $cache->switchSearchType(ilUserSearchCache::LAST_QUERY); + $search_string = $cache->getQuery(); + + include_once("./Services/UIComponent/TextHighlighter/classes/class.ilTextHighlighterGUI.php"); + include_once("./Services/Search/classes/class.ilQueryParser.php"); + $p = new ilQueryParser($search_string); + $p->parse(); + + $words = $p->getQuotedWords(); + if (is_array($words)) { + foreach ($words as $w) { + ilTextHighlighterGUI::highlight("ilGloContent", $w, $tpl); + } + } + $this->fill_on_load_code = true; + } + + if ($this->offlineMode() || $a_get_html) { + return $tpl->get(); + } + } + + /** + * Definitions tabs + * + * @param + * @return + */ + public function showDefinitionTabs($a_act) + { + $ilTabs = $this->tabs_gui; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilHelp = $this->help; + + if (!$this->offlineMode()) { + $ilHelp->setScreenIdComponent("glo"); + + $ilCtrl->setParameter($this, "term_id", ""); + $this->ctrl->setParameter($this, "offset", $_GET["offset"]); + if (!empty($_REQUEST["term"])) { + $this->ctrl->setParameter($this, "term", $_REQUEST["term"]); + $this->ctrl->setParameter($this, "oldoffset", $_GET["oldoffset"]); + $back = $ilCtrl->getLinkTarget($this, "searchTerms"); + } else { + $back = $ilCtrl->getLinkTarget($this, "listTerms"); + } + $ilCtrl->setParameter($this, "term_id", $this->term_id); + $ilCtrl->saveParameter($this, "term_id"); + + $ilTabs->setBackTarget($this->lng->txt("obj_glo"), $back); + + $ilTabs->addTab( + "term_content", + $lng->txt("content"), + $ilCtrl->getLinkTarget($this, "listDefinitions") + ); + + $ilTabs->addTab( + "print_view", + $lng->txt("print_view"), + $ilCtrl->getLinkTarget($this, "printViewSelection") + ); + + $ilCtrl->setParameterByClass("ilglossarytermgui", "term_id", $this->term_id); + include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + if (ilGlossaryTerm::_lookGlossaryID($this->term_id) == $this->glossary->getId()) { + $ilTabs->addNonTabbedLink( + "editing_view", + $lng->txt("glo_editing_view"), + $ilCtrl->getLinkTargetByClass(array("ilglossaryeditorgui", "ilobjglossarygui", "ilglossarytermgui"), "listDefinitions") + ); + //"ilias.php?baseClass=ilGlossaryEditorGUI&ref_id=".$_GET["ref_id"]."&edit_term=".$this->term_id); + } + $ilTabs->activateTab($a_act); + } + } + + + /** + * show fullscreen view + */ + public function fullscreen() + { + $html = $this->media("fullscreen"); + return $html; + } + + /** + * show media object + */ + public function media($a_mode = "media") + { + $this->tpl = new ilTemplate("tpl.fullscreen.html", true, true, "Services/COPage"); + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $this->tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); + $this->tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath($this->glossary->getStyleSheetId()) + ); + + //$int_links = $page_object->getInternalLinks(); + $med_links = ilMediaItem::_getMapAreasIntLinks($_GET["mob_id"]); + + // later + //$link_xml = $this->getLinkXML($med_links, $this->getLayoutLinkTargets()); + + $link_xlm = ""; + + require_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $media_obj = new ilObjMediaObject($_GET["mob_id"]); + + $xml = ""; + // todo: we get always the first alias now (problem if mob is used multiple + // times in page) + $xml.= $media_obj->getXML(IL_MODE_ALIAS); + $xml.= $media_obj->getXML(IL_MODE_OUTPUT); + $xml.= $link_xml; + $xml.=""; + + $xsl = file_get_contents("./Services/COPage/xsl/page.xsl"); + $args = array( '/_xml' => $xml, '/_xsl' => $xsl ); + $xh = xslt_create(); + + if (!$this->offlineMode()) { + $enlarge_path = ilUtil::getImagePath("enlarge.svg", false, "output"); + $wb_path = ilUtil::getWebspaceDir("output") . "/"; + } else { + $enlarge_path = "images/enlarge.svg"; + $wb_path = ""; + } + + $mode = $a_mode; + + $this->ctrl->setParameter($this, "obj_type", "MediaObject"); + $fullscreen_link = + $this->getLink($_GET["ref_id"], "fullscreen"); + $this->ctrl->clearParameters($this); + + $params = array('mode' => $mode, 'enlarge_path' => $enlarge_path, + 'link_params' => "ref_id=" . $_GET["ref_id"],'fullscreen_link' => $fullscreen_link, + 'ref_id' => $_GET["ref_id"], 'pg_frame' => $pg_frame, 'webspace_path' => $wb_path); + $output = xslt_process($xh, "arg:/_xml", "arg:/_xsl", null, $args, $params); + echo xslt_error($xh); + xslt_free($xh); + + // unmask user html + $this->tpl->setVariable("MEDIA_CONTENT", $output); + + $this->tpl->parseCurrentBlock(); + if ($this->offlineMode()) { + $html = $this->tpl->get(); + return $html; + } + } + + /** + * show download list + */ + public function showDownloadList() + { + $ilAccess = $this->access; + $lng = $this->lng; + $ilTabs = $this->tabs_gui; + + if (!$ilAccess->checkAccess("read", "", $_GET["ref_id"])) { + $ilErr->raiseError($lng->txt("permission_denied"), $ilErr->MESSAGE); + } + + $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.glo_download_list.html", "Modules/Glossary"); + + $this->setTabs(); + $ilTabs->activateTab("download"); + + // set title header + $this->tpl->setTitle($this->glossary->getTitle()); + $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_glo.svg")); + + // create table + require_once("./Services/Table/classes/class.ilTableGUI.php"); + $tbl = new ilTableGUI(); + + // load files templates + $this->tpl->addBlockfile("DOWNLOAD_TABLE", "download_table", "tpl.table.html"); + + // load template for table content data + $this->tpl->addBlockfile("TBL_CONTENT", "tbl_content", "tpl.download_file_row.html", "Modules/Glossary"); + + $export_files = array(); + $types = array("xml", "html"); + foreach ($types as $type) { + if ($this->glossary->getPublicExportFile($type) != "") { + $dir = $this->glossary->getExportDirectory($type); + if (is_file($this->glossary->getExportDirectory($type) . "/" . + $this->glossary->getPublicExportFile($type))) { + $size = filesize($this->glossary->getExportDirectory($type) . "/" . + $this->glossary->getPublicExportFile($type)); + $export_files[] = array("type" => $type, + "file" => $this->glossary->getPublicExportFile($type), + "size" => $size); + } + } + } + + $num = 0; + + $tbl->setTitle($this->lng->txt("download")); + + $tbl->setHeaderNames(array($this->lng->txt("cont_format"), + $this->lng->txt("cont_file"), + $this->lng->txt("size"), $this->lng->txt("date"), + "")); + + $cols = array("format", "file", "size", "date", "download"); + $header_params = array("ref_id" => $_GET["ref_id"], "obj_id" => $_GET["obj_id"], + "cmd" => "showDownloadList", "cmdClass" => strtolower(get_class($this))); + $tbl->setHeaderVars($cols, $header_params); + $tbl->setColumnWidth(array("10%", "30%", "20%", "20%","20%")); + $tbl->disable("sort"); + + // control + $tbl->setOrderColumn($_GET["sort_by"]); + $tbl->setOrderDirection($_GET["sort_order"]); + $tbl->setLimit($_GET["limit"]); + $tbl->setOffset($_GET["offset"]); + $tbl->setMaxCount($this->maxcount); // ??? + + // $this->tpl->setVariable("COLUMN_COUNTS", 5); + + // footer + //$tbl->setFooter("tblfooter",$this->lng->txt("previous"),$this->lng->txt("next")); + $tbl->disable("footer"); + + $tbl->setMaxCount(count($export_files)); + $export_files = array_slice($export_files, $_GET["offset"], $_GET["limit"]); + + $tbl->render(); + if (count($export_files) > 0) { + $i=0; + foreach ($export_files as $exp_file) { + $this->tpl->setCurrentBlock("tbl_content"); + $this->tpl->setVariable("TXT_FILENAME", $exp_file["file"]); + + $css_row = ilUtil::switchColor($i++, "tblrow1", "tblrow2"); + $this->tpl->setVariable("CSS_ROW", $css_row); + + $this->tpl->setVariable("TXT_SIZE", $exp_file["size"]); + $this->tpl->setVariable("TXT_FORMAT", strtoupper($exp_file["type"])); + $this->tpl->setVariable("CHECKBOX_ID", $exp_file["type"] . ":" . $exp_file["file"]); + + $file_arr = explode("__", $exp_file["file"]); + $this->tpl->setVariable("TXT_DATE", date("Y-m-d H:i:s", $file_arr[0])); + + $this->tpl->setVariable("TXT_DOWNLOAD", $this->lng->txt("download")); + $this->ctrl->setParameter($this, "type", $exp_file["type"]); + $this->tpl->setVariable( + "LINK_DOWNLOAD", + $this->ctrl->getLinkTarget($this, "downloadExportFile") + ); + + $this->tpl->parseCurrentBlock(); + } + } //if is_array + else { + $this->tpl->setVariable("TXT_OBJECT_NOT_FOUND", $this->lng->txt("obj_not_found")); + $this->tpl->setVariable("NUM_COLS", 5); + $this->tpl->parseCurrentBlock(); + } + + //$this->tpl->show(); + } + + /** + * send download file (xml/html) + */ + public function downloadExportFile() + { + $ilAccess = $this->access; + $ilErr = $this->error; + $lng = $this->lng; + + if (!$ilAccess->checkAccess("read", "", $_GET["ref_id"])) { + $ilErr->raiseError($lng->txt("permission_denied"), $ilErr->error_obj->MESSAGE); + } + + $file = $this->glossary->getPublicExportFile($_GET["type"]); + if ($this->glossary->getPublicExportFile($_GET["type"]) != "") { + $dir = $this->glossary->getExportDirectory($_GET["type"]); + if (is_file($dir . "/" . $file)) { + ilUtil::deliverFile($dir . "/" . $file, $file); + exit; + } + } + $ilErr->raiseError($this->lng->txt("file_not_found"), $ilErr->MESSAGE); + } + + /** + * set Locator + * + * @param object tree object + * @param integer reference id + * @access public + */ + public function setLocator($a_tree = "", $a_id = "") + { + //$this->tpl->addBlockFile("LOCATOR", "locator", "tpl.locator.html", "Services/Locator"); + require_once("./Modules/Glossary/classes/class.ilGlossaryLocatorGUI.php"); + $gloss_loc = new ilGlossaryLocatorGUI(); + $gloss_loc->setMode("presentation"); + if (!empty($this->term_id)) { + $term = new ilGlossaryTerm($this->term_id); + $gloss_loc->setTerm($term); + } + $gloss_loc->setGlossary($this->glossary); + //$gloss_loc->setDefinition($this->definition); + $gloss_loc->display(); + } + + /** + * download file of file lists + */ + public function downloadFile() + { + $ilAccess = $this->access; + $ilErr = $this->error; + $lng = $this->lng; + + if (!$ilAccess->checkAccess("read", "", $_GET["ref_id"])) { + $ilErr->raiseError($lng->txt("permission_denied"), $ilErr->MESSAGE); + } + + $file = explode("_", $_GET["file_id"]); + include_once("./Modules/File/classes/class.ilObjFile.php"); + $fileObj = new ilObjFile($file[count($file) - 1], false); + $fileObj->sendFile(); + exit; + } + + /** + * output tabs + */ + public function setTabs() + { + $this->getTabs(); + } + + /** + * get link targets + */ + public function getLinkXML($a_int_links) + { + if ($a_layoutframes == "") { + $a_layoutframes = array(); + } + $link_info = ""; + foreach ($a_int_links as $int_link) { + //echo "
+".$int_link["Type"]."+".$int_link["TargetFrame"]."+".$int_link["Target"]."+"; + $target = $int_link["Target"]; + if (substr($target, 0, 4) == "il__") { + $target_arr = explode("_", $target); + $target_id = $target_arr[count($target_arr) - 1]; + $type = $int_link["Type"]; + $targetframe = ($int_link["TargetFrame"] != "") + ? $int_link["TargetFrame"] + : "None"; + + // anchor + $anc = $anc_add = ""; + if ($int_link["Anchor"] != "") { + $anc = $int_link["Anchor"]; + $anc_add = "_" . rawurlencode($int_link["Anchor"]); + } + + if ($targetframe == "New") { + $ltarget = "_blank"; + } else { + $ltarget = ""; + } + $lcontent = ""; + switch ($type) { + case "PageObject": + case "StructureObject": + $lm_id = ilLMObject::_lookupContObjID($target_id); + $cont_obj = $this->content_object; + if ($type == "PageObject") { + $href = "./goto.php?target=pg_" . $target_id . $anc_add; + } else { + $href = "./goto.php?target=st_" . $target_id; + } + //$ltarget = "ilContObj".$lm_id; + break; + + case "GlossaryItem": + if (ilGlossaryTerm::_lookGlossaryID($target_id) == $this->glossary->getId()) { + if ($this->offlineMode()) { + $href = "term_" . $target_id . ".html"; + } else { + $this->ctrl->setParameter($this, "term_id", $target_id); + $href = $this->ctrl->getLinkTarget($this, "listDefinitions"); + $href = str_replace("&", "&", $href); + } + } else { + $href = "./goto.php?target=git_" . $target_id; + } + break; + + case "MediaObject": + if ($this->offlineMode()) { + $href = "media_" . $target_id . ".html"; + } else { + $this->ctrl->setParameter($this, "obj_type", $type); + $this->ctrl->setParameter($this, "mob_id", $target_id); + $href = $this->ctrl->getLinkTarget($this, "media"); + $href = str_replace("&", "&", $href); + } + break; + + case "RepositoryItem": + $obj_type = ilObject::_lookupType($target_id, true); + $obj_id = ilObject::_lookupObjId($target_id); + $href = "./goto.php?target=" . $obj_type . "_" . $target_id; + $t_frame = ilFrameTargetInfo::_getFrame("MainContent", $obj_type); + $ltarget = $t_frame; + break; + + case "WikiPage": + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + $href = ilWikiPage::getGotoForWikiPageTarget($target_id); + break; + + case "User": + $obj_type = ilObject::_lookupType($target_id); + if ($obj_type == "usr") { + include_once("./Services/User/classes/class.ilUserUtil.php"); + $back = $this->ctrl->getLinkTarget($this, "listDefinitions"); + //var_dump($back); exit; + $this->ctrl->setParameterByClass("ilpublicuserprofilegui", "user_id", $target_id); + $this->ctrl->setParameterByClass( + "ilpublicuserprofilegui", + "back_url", + rawurlencode($back) + ); + $href = ""; + include_once("./Services/User/classes/class.ilUserUtil.php"); + if (ilUserUtil::hasPublicProfile($target_id)) { + $href = $this->ctrl->getLinkTargetByClass("ilpublicuserprofilegui", "getHTML"); + } + $this->ctrl->setParameterByClass("ilpublicuserprofilegui", "user_id", ""); + $lcontent = ilUserUtil::getNamePresentation($target_id, false, false); + } + break; + + } + + $anc_par = 'Anchor="' . $anc . '"'; + + $link_info.=""; + + $this->ctrl->clearParameters($this); + } + } + $link_info.= "
"; + + return $link_info; + } + + + /** + * handles links for learning module presentation + */ + public function getLink( + $a_ref_id, + $a_cmd = "", + $a_term_id = "", + $a_def_id = "", + $a_frame = "", + $a_type = "" + ) { + if ($a_cmd == "") { + $a_cmd = "layout"; + } + //$script = "glossary_presentation.php"; + + // handle online links + if (!$this->offlineMode()) { + //$link = $script."?ref_id=".$a_ref_id; + switch ($a_cmd) { + case "fullscreen": + $this->ctrl->setParameter($this, "def_id", $a_def_id); + $link = $this->ctrl->getLinkTarget($this, "fullscreen"); + break; + + default: + $link.= "&cmd=" . $a_cmd; + if ($a_frame != "") { + $this->ctrl->setParameter($this, "frame", $a_frame); + } + if ($a_obj_id != "") { + switch ($a_type) { + case "MediaObject": + $this->ctrl->setParameter($this, "mob_id", $a_obj_id); + break; + + default: + $this->ctrl->setParameter($this, "def_id", $a_def_id); + break; + } + } + if ($a_type != "") { + $this->ctrl->setParameter($this, "obj_type", $a_type); + } + $link = $this->ctrl->getLinkTarget($this, $a_cmd); // $link = str_replace("&", "&", $link); - break; - } - } - else // handle offline links - { - switch ($a_cmd) - { - case "downloadFile": - break; - - case "fullscreen": - $link = "fullscreen.html"; // id is handled by xslt - break; - - case "layout": - break; - - case "glossary": - $link = "term_".$a_obj_id.".html"; - break; - - case "media": - $link = "media_".$a_obj_id.".html"; - break; - - default: - break; - } - } - $this->ctrl->clearParameters($this); - return $link; - } - - /** - * Print view selection - * - * @param - * @return - */ - function printViewSelection() - { - $ilUser = $this->user; - $lng = $this->lng; - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $ilTabs = $this->tabs_gui; - - $ilCtrl->saveParameter($this, "term_id"); - - if ((int) $this->term_id == 0) - { - $this->setTabs(); - $ilTabs->activateTab("print_view"); - } - else - { - $tpl->setTitleIcon(ilUtil::getImagePath("icon_glo.svg")); - $term = new ilGlossaryTerm((int) $this->term_id); - $tpl->setTitle($this->lng->txt("cont_term").": ".$term->getTerm()); - $this->showDefinitionTabs("print_view"); - } - - $this->initPrintViewSelectionForm(); - - $tpl->setContent($this->form->getHTML()); - } - - /** - * Init print view selection form. - */ - public function initPrintViewSelectionForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $terms = $this->glossary->getTermList(); - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - $this->form->setTarget("print_view"); - $this->form->setFormAction($ilCtrl->getFormAction($this)); - - // selection type - $radg = new ilRadioGroupInputGUI($lng->txt("cont_selection"), "sel_type"); - $radg->setValue("glossary"); - - // current term - if ((int) $this->term_id > 0) - { - $op1 = new ilRadioOption($lng->txt("cont_current_term"), "term"); - $radg->addOption($op1); - $radg->setValue("term"); - } - - // whole glossary - $op2 = new ilRadioOption($lng->txt("cont_whole_glossary") - ." (".$lng->txt("cont_terms").": ".count($terms).")", "glossary"); - $radg->addOption($op2); - - // selected topic - if (($t_id = $this->glossary->getTaxonomyId()) > 0 && $this->glossary->getShowTaxonomy()) - { - $op4 = new ilRadioOption($lng->txt("cont_selected_topic"), "sel_topic"); - $radg->addOption($op4); - - // topic drop down - include_once("./Services/Taxonomy/classes/class.ilTaxAssignInputGUI.php"); - $si = new ilTaxAssignInputGUI($t_id, false, $lng->txt("cont_topic"), "topic", - false); - if ($this->tax_node > 0) - { - $si->setValue((int) $this->tax_node); - } - $op4->addSubItem($si); - - } - - // selected terms - $op3= new ilRadioOption($lng->txt("cont_selected_terms"), "selection"); - $radg->addOption($op3); - - include_once("./Services/Form/classes/class.ilNestedListInputGUI.php"); - $nl = new ilNestedListInputGUI("", "obj_id"); - $op3->addSubItem($nl); -//var_dump($terms); - foreach ($terms as $t) - { - $nl->addListNode($t["id"], $t["term"], 0, false, false); - } - - $this->form->addItem($radg); - - $this->form->addCommandButton("printView", $lng->txt("cont_show_print_view")); - $this->form->setPreventDoubleSubmission(false); - - $this->form->setTitle($lng->txt("cont_print_selection")); - } - - /** - * Print View - * - * @param - * @return - */ - function printView() - { - $ilAccess = $this->access; - $tpl = $this->tpl; - - if (!$ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - return; - } - - $terms = array(); - switch ($_POST["sel_type"]) - { - case "glossary": - $ts = $this->glossary->getTermList(); - foreach ($ts as $t) - { - $terms[] = $t["id"]; - } - break; - - case "sel_topic": - include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php"); - $t_id = $this->glossary->getTaxonomyId(); - $items = ilObjTaxonomy::getSubTreeItems("glo", $this->glossary->getId(), "term", $t_id, (int) $_POST["topic"]); - foreach ($items as $i) - { - if ($i["item_type"] == "term") - { - $terms[] = $i["item_id"]; - } - } - break; - - case "selection": - if (is_array($_POST["obj_id"])) - { - $terms = $_POST["obj_id"]; - } - else - { - $terms = array(); - } - break; - - case "term": - $terms = array($this->term_id); - break; - } - - $tpl = new ilTemplate("tpl.main.html", true, true); - $tpl->setVariable("LOCATION_STYLESHEET", ilObjStyleSheet::getContentPrintStyle()); - -/* - // syntax style - $this->tpl->setCurrentBlock("SyntaxStyle"); - $this->tpl->setVariable("LOCATION_SYNTAX_STYLESHEET", - ilObjStyleSheet::getSyntaxStylePath()); - $this->tpl->parseCurrentBlock(); - - // content style - $this->tpl->setCurrentBlock("ContentStyle"); - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->glossary->getStyleSheetId())); - $this->tpl->parseCurrentBlock();*/ - - include_once("./Services/jQuery/classes/class.iljQueryUtil.php"); - iljQueryUtil::initjQuery($tpl); - - // determine target frames for internal links - - foreach ($terms as $t_id) - { - $page_content.= $this->listDefinitions($_GET["ref_id"], $t_id, true, IL_PAGE_PRINT); - } - $tpl->setVariable("CONTENT", $page_content. - ''); - $tpl->show(false); - exit; - } - - /** - * get tabs - */ - function getTabs() - { - $ilAccess = $this->access; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilHelp = $this->help; - - $ilHelp->setScreenIdComponent("glo"); - - $oldoffset = (is_numeric ($_GET["oldoffset"]))?$_GET["oldoffset"]:$_GET["offset"]; - - if (!$this->offlineMode()) - { - if ($this->ctrl->getCmd() != "listDefinitions") - { - if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - $this->tabs_gui->addTab("terms", - $lng->txt("cont_terms"), - $ilCtrl->getLinkTarget($this, "listTerms")); - } - - $this->tabs_gui->addTab("info", - $lng->txt("info_short"), - $ilCtrl->getLinkTarget($this, "infoScreen")); - - $this->tabs_gui->addTab("print_view", - $lng->txt("cont_print_view"), - $ilCtrl->getLinkTarget($this, "printViewSelection")); - - // glossary menu - if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - //if ($this->glossary->isActiveGlossaryMenu()) - //{ - // download links - if ($this->glossary->isActiveDownloads()) - { - $this->tabs_gui->addTab("download", - $lng->txt("download"), - $ilCtrl->getLinkTarget($this, "showDownloadList")); - } - //} - } - - if ($ilAccess->checkAccess("write", "", (int) $_GET["ref_id"]) || - $ilAccess->checkAccess("edit_content", "", (int) $_GET["ref_id"])) - { - include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - $this->tabs_gui->addNonTabbedLink("editing_view", - $lng->txt("glo_editing_view"), - "ilias.php?baseClass=ilGlossaryEditorGUI&ref_id=".(int) $_GET["ref_id"], - "_top"); - } - - } - } - else - { - $this->tabs_gui->addTarget("cont_back", - "index.html#term_".$this->term_id, "", - ""); - } - } - - function download_paragraph () { - include_once("./Modules/Glossary/classes/class.ilGlossaryDefPage.php"); - $pg_obj = new ilGlossaryDefPage($_GET["pg_id"]); - $pg_obj->send_paragraph ($_GET["par_id"], $_GET["downloadtitle"]); - } - - - /** - * 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->outputInfoScreen(); - } - - /** - * info screen call from inside learning module - */ - /* - function showInfoScreen() - { - $this->outputInfoScreen(true); - }*/ - - /** - * info screen - */ - function outputInfoScreen() - { - $ilAccess = $this->access; - $ilTabs = $this->tabs_gui; - - $this->setTabs(); - $ilTabs->activateTab("info"); - $this->lng->loadLanguageModule("meta"); - - include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); - - $info = new ilInfoScreenGUI($this->glossary_gui); - $info->enablePrivateNotes(); - //$info->enableLearningProgress(); - - $info->enableNews(); - if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) - { - $info->enableNewsEditing(); - $news_set = new ilSetting("news"); - $enable_internal_rss = $news_set->get("enable_rss_for_internal"); - if ($enable_internal_rss) - { - $info->setBlockProperty("news", "settings", true); - } - } - - // add read / back button - if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - /* - if ($_GET["obj_id"] > 0) - { - $this->ctrl->setParameter($this, "obj_id", $_GET["obj_id"]); - $info->addButton($this->lng->txt("back"), - $this->ctrl->getLinkTarget($this, "layout")); - } - else - { - $info->addButton($this->lng->txt("view"), - $this->ctrl->getLinkTarget($this, "layout")); - }*/ - } - - // show standard meta data section - $info->addMetaDataSections($this->glossary->getId(),0, $this->glossary->getType()); - - include_once("./Modules/Glossary/classes/class.ilObjGlossaryGUI.php"); - ilObjGlossaryGUI::addUsagesToInfo($info, $this->glossary->getId()); - - if ($this->offlineMode()) - { - $this->tpl->setContent($info->getHTML()); - return $this->tpl->get(); - } - else - { - // forward the command - $this->ctrl->forwardCommand($info); - } - } - - /** - * Choose first letter - * - * @param - * @return - */ - function chooseLetter() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirect($this, "listTerms"); - } - - /** - * Show taxonomy - * - * @param - * @return - */ - function showTaxonomy() - { - $tpl = $this->tpl; - $lng = $this->lng; - if (!$this->offlineMode() && $this->glossary->getShowTaxonomy()) - { - include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php"); - $tax_ids = ilObjTaxonomy::getUsageOfObject($this->glossary->getId()); - if (count($tax_ids) > 0) - { - include_once("./Services/Taxonomy/classes/class.ilTaxonomyExplorerGUI.php"); - $tax_exp = new ilTaxonomyExplorerGUI($this, "showTaxonomy", $tax_ids[0], - "ilglossarypresentationgui", "listTerms"); - if (!$tax_exp->handleCommand()) - { - //$tpl->setLeftNavContent($tax_exp->getHTML()); - $tpl->setLeftContent($tax_exp->getHTML()." "); - } - return; - - - include_once("./Services/Taxonomy/classes/class.ilObjTaxonomyGUI.php"); - $tpl->setLeftNavContent(ilObjTaxonomyGUI::getTreeHTML($tax_ids[0], - "ilglossarypresentationgui", "listTerms", $lng->txt("cont_all_topics"))); - } - } - - } - - + $tpl->show(false); + exit; + } + + /** + * get tabs + */ + public function getTabs() + { + $ilAccess = $this->access; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilHelp = $this->help; + + $ilHelp->setScreenIdComponent("glo"); + + $oldoffset = (is_numeric($_GET["oldoffset"]))?$_GET["oldoffset"]:$_GET["offset"]; + + if (!$this->offlineMode()) { + if ($this->ctrl->getCmd() != "listDefinitions") { + if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) { + $this->tabs_gui->addTab( + "terms", + $lng->txt("cont_terms"), + $ilCtrl->getLinkTarget($this, "listTerms") + ); + } + + $this->tabs_gui->addTab( + "info", + $lng->txt("info_short"), + $ilCtrl->getLinkTarget($this, "infoScreen") + ); + + $this->tabs_gui->addTab( + "print_view", + $lng->txt("cont_print_view"), + $ilCtrl->getLinkTarget($this, "printViewSelection") + ); + + // glossary menu + if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) { + //if ($this->glossary->isActiveGlossaryMenu()) + //{ + // download links + if ($this->glossary->isActiveDownloads()) { + $this->tabs_gui->addTab( + "download", + $lng->txt("download"), + $ilCtrl->getLinkTarget($this, "showDownloadList") + ); + } + //} + } + + if ($ilAccess->checkAccess("write", "", (int) $_GET["ref_id"]) || + $ilAccess->checkAccess("edit_content", "", (int) $_GET["ref_id"])) { + include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + $this->tabs_gui->addNonTabbedLink( + "editing_view", + $lng->txt("glo_editing_view"), + "ilias.php?baseClass=ilGlossaryEditorGUI&ref_id=" . (int) $_GET["ref_id"], + "_top" + ); + } + } + } else { + $this->tabs_gui->addTarget( + "cont_back", + "index.html#term_" . $this->term_id, + "", + "" + ); + } + } + + public function download_paragraph() + { + include_once("./Modules/Glossary/classes/class.ilGlossaryDefPage.php"); + $pg_obj = new ilGlossaryDefPage($_GET["pg_id"]); + $pg_obj->send_paragraph($_GET["par_id"], $_GET["downloadtitle"]); + } + + + /** + * 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->outputInfoScreen(); + } + + /** + * info screen call from inside learning module + */ + /* + function showInfoScreen() + { + $this->outputInfoScreen(true); + }*/ + + /** + * info screen + */ + public function outputInfoScreen() + { + $ilAccess = $this->access; + $ilTabs = $this->tabs_gui; + + $this->setTabs(); + $ilTabs->activateTab("info"); + $this->lng->loadLanguageModule("meta"); + + include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); + + $info = new ilInfoScreenGUI($this->glossary_gui); + $info->enablePrivateNotes(); + //$info->enableLearningProgress(); + + $info->enableNews(); + if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) { + $info->enableNewsEditing(); + $news_set = new ilSetting("news"); + $enable_internal_rss = $news_set->get("enable_rss_for_internal"); + if ($enable_internal_rss) { + $info->setBlockProperty("news", "settings", true); + } + } + + // add read / back button + if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) { + /* + if ($_GET["obj_id"] > 0) + { + $this->ctrl->setParameter($this, "obj_id", $_GET["obj_id"]); + $info->addButton($this->lng->txt("back"), + $this->ctrl->getLinkTarget($this, "layout")); + } + else + { + $info->addButton($this->lng->txt("view"), + $this->ctrl->getLinkTarget($this, "layout")); + }*/ + } + + // show standard meta data section + $info->addMetaDataSections($this->glossary->getId(), 0, $this->glossary->getType()); + + include_once("./Modules/Glossary/classes/class.ilObjGlossaryGUI.php"); + ilObjGlossaryGUI::addUsagesToInfo($info, $this->glossary->getId()); + + if ($this->offlineMode()) { + $this->tpl->setContent($info->getHTML()); + return $this->tpl->get(); + } else { + // forward the command + $this->ctrl->forwardCommand($info); + } + } + + /** + * Choose first letter + * + * @param + * @return + */ + public function chooseLetter() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirect($this, "listTerms"); + } + + /** + * Show taxonomy + * + * @param + * @return + */ + public function showTaxonomy() + { + $tpl = $this->tpl; + $lng = $this->lng; + if (!$this->offlineMode() && $this->glossary->getShowTaxonomy()) { + include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php"); + $tax_ids = ilObjTaxonomy::getUsageOfObject($this->glossary->getId()); + if (count($tax_ids) > 0) { + include_once("./Services/Taxonomy/classes/class.ilTaxonomyExplorerGUI.php"); + $tax_exp = new ilTaxonomyExplorerGUI( + $this, + "showTaxonomy", + $tax_ids[0], + "ilglossarypresentationgui", + "listTerms" + ); + if (!$tax_exp->handleCommand()) { + //$tpl->setLeftNavContent($tax_exp->getHTML()); + $tpl->setLeftContent($tax_exp->getHTML() . " "); + } + return; + + + include_once("./Services/Taxonomy/classes/class.ilObjTaxonomyGUI.php"); + $tpl->setLeftNavContent(ilObjTaxonomyGUI::getTreeHTML( + $tax_ids[0], + "ilglossarypresentationgui", + "listTerms", + $lng->txt("cont_all_topics") + )); + } + } + } } - -?> diff --git a/Modules/Glossary/classes/class.ilGlossaryTerm.php b/Modules/Glossary/classes/class.ilGlossaryTerm.php index 668891938ba589ca8b6540ff84d30b2112f19959..471e999007148f5eb16a2f50a775867d0e7a8ec1 100755 --- a/Modules/Glossary/classes/class.ilGlossaryTerm.php +++ b/Modules/Glossary/classes/class.ilGlossaryTerm.php @@ -11,723 +11,685 @@ */ class ilGlossaryTerm { - /** - * @var ilDB - */ - protected $db; - - var $lng; - var $tpl; - - var $id; - var $glossary; - var $term; - var $language; - var $glo_id; - var $import_id; - - /** - * Constructor - * @access public - */ - function __construct($a_id = 0) - { - global $DIC; - - $this->db = $DIC->database(); - $lng = $DIC->language(); - $tpl = $DIC["tpl"]; - - $this->lng = $lng; - $this->tpl = $tpl; - - $this->id = $a_id; - $this->type = "term"; - if ($a_id != 0) - { - $this->read(); - } - } - - /** - * read glossary term data - */ - function read() - { - $ilDB = $this->db; - - $q = "SELECT * FROM glossary_term WHERE id = ". - $ilDB->quote($this->id, "integer"); - $term_set = $ilDB->query($q); - $term_rec = $ilDB->fetchAssoc($term_set); - - $this->setTerm($term_rec["term"]); - $this->setImportId($term_rec["import_id"]); - $this->setLanguage($term_rec["language"]); - $this->setGlossaryId($term_rec["glo_id"]); - - } - - /** - * get current term id for import id (static) - * - * @param int $a_import_id import id - * - * @return int id - */ - static function _getIdForImportId($a_import_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - if ($a_import_id == "") - { - return 0; - } - - $q = "SELECT * FROM glossary_term WHERE import_id = ". - $ilDB->quote($a_import_id, "text"). - " ORDER BY create_date DESC"; - $term_set = $ilDB->query($q); - while ($term_rec = $ilDB->fetchAssoc($term_set)) - { - $glo_id = ilGlossaryTerm::_lookGlossaryID($term_rec["id"]); - - $ref_ids = ilObject::_getAllReferences($glo_id); // will be 0 if import of lm is in progress (new import) - if (count($ref_ids) == 0 || ilObject::_hasUntrashedReference($glo_id)) - { - return $term_rec["id"]; - } - } - - return 0; - } - - - /** - * checks wether a glossary term with specified id exists or not - * - * @param int $id id - * - * @return boolean true, if glossary term exists - */ - static function _exists($a_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - include_once("./Services/Link/classes/class.ilInternalLink.php"); - if (is_int(strpos($a_id, "_"))) - { - $a_id = ilInternalLink::_extractObjIdOfTarget($a_id); - } - - $q = "SELECT * FROM glossary_term WHERE id = ". - $ilDB->quote($a_id, "integer"); - $obj_set = $ilDB->query($q); - if ($obj_rec = $ilDB->fetchAssoc($obj_set)) - { - return true; - } - else - { - return false; - } - - } - - - /** - * set glossary term id (= glossary item id) - * - * @param int $a_id glossary term id - */ - function setId($a_id) - { - $this->id = $a_id; - } - - - /** - * get term id (= glossary item id) - * - * @return int glossary term id - */ - function getId() - { - return $this->id; - } - - /** - * set glossary object - * - * @param object $a_glossary glossary object - */ - function setGlossary(&$a_glossary) - { - $this->glossary = $a_glossary; - $this->setGlossaryId($a_glossary->getId()); - } - - - /** - * set glossary id - * - * @param int $a_glo_id glossary id - */ - function setGlossaryId($a_glo_id) - { - $this->glo_id = $a_glo_id; - } - - - /** - * get glossary id - * - * @return int glossary id - */ - function getGlossaryId() - { - return $this->glo_id; - } - - - /** - * set term - * - * @param string $a_term term - */ - function setTerm($a_term) - { - $this->term = $a_term; - } - - - /** - * get term - * - * @return string term - */ - function getTerm() - { - return $this->term; - } - - - /** - * set language - * - * @param string $a_language two letter language code - */ - function setLanguage($a_language) - { - $this->language = $a_language; - } - - /** - * get language - * @return string two letter language code - */ - function getLanguage() - { - return $this->language; - } - - - /** - * set import id - */ - function setImportId($a_import_id) - { - $this->import_id = $a_import_id; - } - - - /** - * get import id - */ - function getImportId() - { - return $this->import_id; - } - - - /** - * create new glossary term - */ - function create() - { - $ilDB = $this->db; - - $this->setId($ilDB->nextId("glossary_term")); - $ilDB->manipulate("INSERT INTO glossary_term (id, glo_id, term, language, import_id, create_date, last_update)". - " VALUES (". - $ilDB->quote($this->getId(), "integer").", ". - $ilDB->quote($this->getGlossaryId(), "integer").", ". - $ilDB->quote($this->term, "text").", ". - $ilDB->quote($this->language, "text").",". - $ilDB->quote($this->getImportId(), "text").",". - $ilDB->now().", ". - $ilDB->now().")"); - } - - - /** - * delete glossary term (and all its definition objects) - */ - function delete() - { - $ilDB = $this->db; - - require_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); - $defs = ilGlossaryDefinition::getDefinitionList($this->getId()); - foreach($defs as $def) - { - $def_obj = new ilGlossaryDefinition($def["id"]); - $def_obj->delete(); - } - - // delete term references - include_once("./Modules/Glossary/classes/class.ilGlossaryTermReferences.php"); - ilGlossaryTermReferences::deleteReferencesOfTerm($this->getId()); - - // delete glossary_term record - $ilDB->manipulate("DELETE FROM glossary_term ". - " WHERE id = ".$ilDB->quote($this->getId(), "integer")); - } - - - /** - * update glossary term - */ - function update() - { - $ilDB = $this->db; - - $ilDB->manipulate("UPDATE glossary_term SET ". - " glo_id = ".$ilDB->quote($this->getGlossaryId(), "integer").", ". - " term = ".$ilDB->quote($this->getTerm(), "text").", ". - " import_id = ".$ilDB->quote($this->getImportId(), "text").", ". - " language = ".$ilDB->quote($this->getLanguage(), "text").", ". - " last_update = ".$ilDB->now()." ". - " WHERE id = ".$ilDB->quote($this->getId(), "integer")); - } - - /** - * get glossary id form term id - */ - static function _lookGlossaryID($term_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT * FROM glossary_term WHERE id = ". - $ilDB->quote($term_id, "integer"); - $obj_set = $ilDB->query($query); - $obj_rec = $ilDB->fetchAssoc($obj_set); - - return $obj_rec["glo_id"]; - } - - /** - * get glossary term - */ - static function _lookGlossaryTerm($term_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT * FROM glossary_term WHERE id = ". - $ilDB->quote($term_id, "integer"); - $obj_set = $ilDB->query($query); - $obj_rec = $ilDB->fetchAssoc($obj_set); - - return $obj_rec["term"]; - } - - /** - * lookup term language - */ - static function _lookLanguage($term_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT * FROM glossary_term WHERE id = ". - $ilDB->quote($term_id, "integer"); - $obj_set = $ilDB->query($query); - $obj_rec = $ilDB->fetchAssoc($obj_set); - - return $obj_rec["language"]; - } - - /** - * Get all terms for given set of glossary ids. - * - * @param integer/array array of glossary ids for meta glossaries - * @param string searchstring - * @param string first letter - * @return array array of terms - */ - static function getTermList($a_glo_ref_id, $searchterm = "", $a_first_letter = "", $a_def = "", - $a_tax_node = 0, $a_add_amet_fields = false, array $a_amet_filter = null, $a_include_references = false) - { - global $DIC; - - if (is_array($a_glo_ref_id)) - { - $a_glo_id = array_map(function($id) { - return ilObject::_lookupObjectId($id); - },$a_glo_ref_id); - } - else - { - $a_glo_id = ilObject::_lookupObjectId($a_glo_ref_id); - } - $ilDB = $DIC->database(); - - $join = $in = ""; - - $terms = array(); - - // get all term ids under taxonomy node (if given) - if ($a_tax_node > 1) - { - include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php"); - $tax_ids = ilObjTaxonomy::getUsageOfObject($a_glo_id); - if (count($tax_ids) > 0) - { - $items = ilObjTaxonomy::getSubTreeItems("glo", $a_glo_id, "term", $tax_ids[0], $a_tax_node); - $sub_tree_ids = array(); - foreach ($items as $i) - { - $sub_tree_ids[] = $i["item_id"]; - } - $in = " AND ".$ilDB->in("gt.id", $sub_tree_ids, false, "integer"); - } - } - - if ($a_def != "") - { - // meta glossary? - if (is_array($a_glo_id)) - { - $glo_where = $ilDB->in("page_object.parent_id", $a_glo_id, false, "integer"); - } - else - { - $glo_where = " page_object.parent_id = ".$ilDB->quote($a_glo_id, "integer"); - } - - $join = " JOIN glossary_definition gd ON (gd.term_id = gt.id)". - " JOIN page_object ON (". - $glo_where. - " AND page_object.parent_type = ".$ilDB->quote("gdf", "text"). - " AND page_object.page_id = gd.id". - " AND ".$ilDB->like("page_object.content", "text", "%".$a_def."%"). - ")"; - } - - $searchterm = (!empty ($searchterm)) - ? " AND ".$ilDB->like("term", "text", "%".$searchterm."%")." " - : ""; - - if ($a_first_letter != "") - { - $searchterm.= " AND ".$ilDB->upper($ilDB->substr("term", 1, 1))." = ".$ilDB->upper($ilDB->quote($a_first_letter, "text"))." "; - } - - // include references - $where_glo_id_or = ""; - if ($a_include_references) - { - $join.= " LEFT JOIN glo_term_reference tr ON (gt.id = tr.term_id) "; - if (is_array($a_glo_id)) - { - $where_glo_id_or = " OR ".$ilDB->in("tr.glo_id", $a_glo_id, false, "integer"); - } - else - { - $where_glo_id_or = " OR tr.glo_id = ".$ilDB->quote($a_glo_id, "integer"); - } - } - - // meta glossary - if (is_array($a_glo_id)) - { - $where = "(".$ilDB->in("gt.glo_id", $a_glo_id, false, "integer").$where_glo_id_or.")"; - } - else - { - $where = "(gt.glo_id = ".$ilDB->quote($a_glo_id, "integer").$where_glo_id_or.")"; - } - - $where.= $in; - - - $q = "SELECT DISTINCT(gt.term), gt.id, gt.glo_id, gt.language FROM glossary_term gt ".$join." WHERE ".$where.$searchterm." ORDER BY term"; - - //echo $q; exit; - - $term_set = $ilDB->query($q); - $glo_ids = array(); - while ($term_rec = $ilDB->fetchAssoc($term_set)) - { - $terms[] = array("term" => $term_rec["term"], - "language" => $term_rec["language"], "id" => $term_rec["id"], "glo_id" => $term_rec["glo_id"]); - $glo_ids[] = $term_rec["glo_id"]; - } - - // add advanced metadata - if (($a_add_amet_fields || is_array($a_amet_filter)) && !is_array($a_glo_ref_id)) - { - include_once("./Services/AdvancedMetaData/classes/class.ilAdvancedMDValues.php"); - $terms = ilAdvancedMDValues::queryForRecords($a_glo_ref_id, "glo", "term", $glo_ids, "term", $terms, "glo_id", "id", $a_amet_filter); - } - return $terms; - } - - /** - * Get all terms for given set of glossary ids. - * - * @param integer/array array of glossary ids for meta glossaries - * @param string searchstring - * @param string first letter - * @return array array of terms - */ - static function getFirstLetters($a_glo_id, $a_tax_node = 0) - { - global $DIC; - - $ilDB = $DIC->database(); - - $terms = array(); - - // meta glossary - if (is_array($a_glo_id)) - { - $where = $ilDB->in("glo_id", $a_glo_id, false, "integer"); - } - else - { - $where = " glo_id = ".$ilDB->quote($a_glo_id, "integer")." "; - - // get all term ids under taxonomy node (if given) - if ($a_tax_node > 1) - { - include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php"); - $tax_ids = ilObjTaxonomy::getUsageOfObject($a_glo_id); - if (count($tax_ids) > 0) - { - $items = ilObjTaxonomy::getSubTreeItems("glo", $a_glo_id, "term", $tax_ids[0], $a_tax_node); - $sub_tree_ids = array(); - foreach ($items as $i) - { - $sub_tree_ids[] = $i["item_id"]; - } - $in = " AND ".$ilDB->in("id", $sub_tree_ids, false, "integer"); - } - } - - $where.= $in; - } - - $q = "SELECT DISTINCT ".$ilDB->upper($ilDB->substr("term", 1, 1))." let FROM glossary_term WHERE ".$where." ORDER BY let"; - $let_set = $ilDB->query($q); - - $lets = array(); - while ($let_rec = $ilDB->fetchAssoc($let_set)) - { - $let[$let_rec["let"]] = $let_rec["let"]; - } - return $let; - } - - /** - * export xml - */ - function exportXML(&$a_xml_writer, $a_inst) - { - - $attrs = array(); - $attrs["Language"] = $this->getLanguage(); - $attrs["Id"] = "il_".IL_INST_ID."_git_".$this->getId(); - $a_xml_writer->xmlStartTag("GlossaryItem", $attrs); - - $attrs = array(); - $a_xml_writer->xmlElement("GlossaryTerm", $attrs, $this->getTerm()); - - $defs = ilGlossaryDefinition::getDefinitionList($this->getId()); - - foreach($defs as $def) - { - $definition = new ilGlossaryDefinition($def["id"]); - $definition->exportXML($a_xml_writer, $a_inst); - } - - $a_xml_writer->xmlEndTag("GlossaryItem"); - } - - /** - * Get number of usages - * - * @param int term id - * @return int number of usages - */ - static function getNumberOfUsages($a_term_id) - { - return count(ilGlossaryTerm::getUsages($a_term_id)); - } - - /** - * Get number of usages - * - * @param int term id - * @return int number of usages - */ - static function getUsages($a_term_id) - { - include_once("./Services/Link/classes/class.ilInternalLink.php"); - $usages = (ilInternalLink::_getSourcesOfTarget("git", $a_term_id, 0)); - - include_once("./Modules/Glossary/classes/class.ilGlossaryTermReferences.php"); - foreach (ilGlossaryTermReferences::lookupReferencesOfTerm($a_term_id) as $glo_id) - { - $usages["glo:termref:".$glo_id.":-"] = array( - "type" => "glo:termref", - "id" => $glo_id, - "lang" => "-" - ); - } - - return $usages; - } - - /** - * Copy a term to a glossary - * - * @param - * @return - */ - static function _copyTerm($a_term_id, $a_glossary_id) - { - $old_term = new ilGlossaryTerm($a_term_id); - - // copy the term - $new_term = new ilGlossaryTerm(); - $new_term->setTerm($old_term->getTerm()); - $new_term->setLanguage($old_term->getLanguage()); - $new_term->setGlossaryId($a_glossary_id); - $new_term->create(); - - // copy the definitions - include_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); - $def_list = ilGlossaryDefinition::getDefinitionList($a_term_id); - foreach ($def_list as $def) - { - $old_def = new ilGlossaryDefinition($def["id"]); - - $new_def = new ilGlossaryDefinition(); - $new_def->setShortText($old_def->getShortText()); - $new_def->setNr($old_def->getNr()); - $new_def->setTermId($new_term->getId()); - $new_def->create(); - - // copy meta data - include_once("Services/MetaData/classes/class.ilMD.php"); - $md = new ilMD($old_term->getGlossaryId(), - $old_def->getPageObject()->getId(), - $old_def->getPageObject()->getParentType()); - $new_md = $md->cloneMD($a_glossary_id, - $new_def->getPageObject()->getId(), - $old_def->getPageObject()->getParentType()); - - - $new_page = $new_def->getPageObject(); - $old_def->getPageObject()->copy($new_page->getId(), $new_page->getParentType(), $new_page->getParentId(), true); - - // page content - //$new_def->getPageObject()->setXMLContent($old_def->getPageObject()->copyXmlContent(true)); - //$new_def->getPageObject()->buildDom(); - //$new_def->getPageObject()->update(); - - } - - // adv metadata - include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecord.php'); - include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDFieldDefinition.php'); - $old_recs = ilAdvancedMDRecord::_getSelectedRecordsByObject("glo", $old_term->getGlossaryId(), "term"); - $new_recs = ilAdvancedMDRecord::_getSelectedRecordsByObject("glo", $a_glossary_id, "term"); - foreach($old_recs as $old_record_obj) - { - reset($new_recs); - foreach ($new_recs as $new_record_obj) - { - if ($old_record_obj->getRecordId() == $new_record_obj->getRecordId()) - { - foreach (ilAdvancedMDFieldDefinition::getInstancesByRecordId($old_record_obj->getRecordId()) as $def) - { - // now we need to copy $def->getFieldId() values from old term to new term - // how? - // clone values - - $source_primary = array("obj_id"=>array("integer", $old_term->getGlossaryId())); - $source_primary["sub_type"] = array("text", "term"); - $source_primary["sub_id"] = array("integer", $old_term->getId()); - $source_primary["field_id"] = array("integer", $def->getFieldId()); - $target_primary = array("obj_id"=>array("integer", $new_term->getGlossaryId())); - $target_primary["sub_type"] = array("text", "term"); - $target_primary["sub_id"] = array("integer", $new_term->getId()); - - ilADTFactory::getInstance()->initActiveRecordByType(); - $has_cloned = ilADTActiveRecordByType::cloneByPrimary( - "adv_md_values", - array( - "obj_id" => "integer", - "sub_type" => "text", - "sub_id" => "integer", - "field_id" => "integer" - ), - $source_primary, - $target_primary, - array("disabled"=>"integer")); - - } - } - } - } - - - return $new_term->getId(); - } - - /** - * Get terms of glossary - * - * @param - * @return - */ - static function getTermsOfGlossary($a_glo_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT id FROM glossary_term WHERE ". - " glo_id = ".$ilDB->quote($a_glo_id, "integer") - ); - $ids = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $ids[] = $rec["id"]; - } - return $ids; - } + /** + * @var ilDB + */ + protected $db; + + public $lng; + public $tpl; + + public $id; + public $glossary; + public $term; + public $language; + public $glo_id; + public $import_id; + + /** + * Constructor + * @access public + */ + public function __construct($a_id = 0) + { + global $DIC; + + $this->db = $DIC->database(); + $lng = $DIC->language(); + $tpl = $DIC["tpl"]; + + $this->lng = $lng; + $this->tpl = $tpl; + + $this->id = $a_id; + $this->type = "term"; + if ($a_id != 0) { + $this->read(); + } + } + + /** + * read glossary term data + */ + public function read() + { + $ilDB = $this->db; + + $q = "SELECT * FROM glossary_term WHERE id = " . + $ilDB->quote($this->id, "integer"); + $term_set = $ilDB->query($q); + $term_rec = $ilDB->fetchAssoc($term_set); + + $this->setTerm($term_rec["term"]); + $this->setImportId($term_rec["import_id"]); + $this->setLanguage($term_rec["language"]); + $this->setGlossaryId($term_rec["glo_id"]); + } + + /** + * get current term id for import id (static) + * + * @param int $a_import_id import id + * + * @return int id + */ + public static function _getIdForImportId($a_import_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + if ($a_import_id == "") { + return 0; + } + + $q = "SELECT * FROM glossary_term WHERE import_id = " . + $ilDB->quote($a_import_id, "text") . + " ORDER BY create_date DESC"; + $term_set = $ilDB->query($q); + while ($term_rec = $ilDB->fetchAssoc($term_set)) { + $glo_id = ilGlossaryTerm::_lookGlossaryID($term_rec["id"]); + + $ref_ids = ilObject::_getAllReferences($glo_id); // will be 0 if import of lm is in progress (new import) + if (count($ref_ids) == 0 || ilObject::_hasUntrashedReference($glo_id)) { + return $term_rec["id"]; + } + } + + return 0; + } + + + /** + * checks wether a glossary term with specified id exists or not + * + * @param int $id id + * + * @return boolean true, if glossary term exists + */ + public static function _exists($a_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + include_once("./Services/Link/classes/class.ilInternalLink.php"); + if (is_int(strpos($a_id, "_"))) { + $a_id = ilInternalLink::_extractObjIdOfTarget($a_id); + } + + $q = "SELECT * FROM glossary_term WHERE id = " . + $ilDB->quote($a_id, "integer"); + $obj_set = $ilDB->query($q); + if ($obj_rec = $ilDB->fetchAssoc($obj_set)) { + return true; + } else { + return false; + } + } + + + /** + * set glossary term id (= glossary item id) + * + * @param int $a_id glossary term id + */ + public function setId($a_id) + { + $this->id = $a_id; + } + + + /** + * get term id (= glossary item id) + * + * @return int glossary term id + */ + public function getId() + { + return $this->id; + } + + /** + * set glossary object + * + * @param object $a_glossary glossary object + */ + public function setGlossary(&$a_glossary) + { + $this->glossary = $a_glossary; + $this->setGlossaryId($a_glossary->getId()); + } + + + /** + * set glossary id + * + * @param int $a_glo_id glossary id + */ + public function setGlossaryId($a_glo_id) + { + $this->glo_id = $a_glo_id; + } + + + /** + * get glossary id + * + * @return int glossary id + */ + public function getGlossaryId() + { + return $this->glo_id; + } + + + /** + * set term + * + * @param string $a_term term + */ + public function setTerm($a_term) + { + $this->term = $a_term; + } + + + /** + * get term + * + * @return string term + */ + public function getTerm() + { + return $this->term; + } + + + /** + * set language + * + * @param string $a_language two letter language code + */ + public function setLanguage($a_language) + { + $this->language = $a_language; + } + + /** + * get language + * @return string two letter language code + */ + public function getLanguage() + { + return $this->language; + } + + + /** + * set import id + */ + public function setImportId($a_import_id) + { + $this->import_id = $a_import_id; + } + + + /** + * get import id + */ + public function getImportId() + { + return $this->import_id; + } + + + /** + * create new glossary term + */ + public function create() + { + $ilDB = $this->db; + + $this->setId($ilDB->nextId("glossary_term")); + $ilDB->manipulate("INSERT INTO glossary_term (id, glo_id, term, language, import_id, create_date, last_update)" . + " VALUES (" . + $ilDB->quote($this->getId(), "integer") . ", " . + $ilDB->quote($this->getGlossaryId(), "integer") . ", " . + $ilDB->quote($this->term, "text") . ", " . + $ilDB->quote($this->language, "text") . "," . + $ilDB->quote($this->getImportId(), "text") . "," . + $ilDB->now() . ", " . + $ilDB->now() . ")"); + } + + + /** + * delete glossary term (and all its definition objects) + */ + public function delete() + { + $ilDB = $this->db; + + require_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); + $defs = ilGlossaryDefinition::getDefinitionList($this->getId()); + foreach ($defs as $def) { + $def_obj = new ilGlossaryDefinition($def["id"]); + $def_obj->delete(); + } + + // delete term references + include_once("./Modules/Glossary/classes/class.ilGlossaryTermReferences.php"); + ilGlossaryTermReferences::deleteReferencesOfTerm($this->getId()); + + // delete glossary_term record + $ilDB->manipulate("DELETE FROM glossary_term " . + " WHERE id = " . $ilDB->quote($this->getId(), "integer")); + } + + + /** + * update glossary term + */ + public function update() + { + $ilDB = $this->db; + + $ilDB->manipulate("UPDATE glossary_term SET " . + " glo_id = " . $ilDB->quote($this->getGlossaryId(), "integer") . ", " . + " term = " . $ilDB->quote($this->getTerm(), "text") . ", " . + " import_id = " . $ilDB->quote($this->getImportId(), "text") . ", " . + " language = " . $ilDB->quote($this->getLanguage(), "text") . ", " . + " last_update = " . $ilDB->now() . " " . + " WHERE id = " . $ilDB->quote($this->getId(), "integer")); + } + + /** + * get glossary id form term id + */ + public static function _lookGlossaryID($term_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT * FROM glossary_term WHERE id = " . + $ilDB->quote($term_id, "integer"); + $obj_set = $ilDB->query($query); + $obj_rec = $ilDB->fetchAssoc($obj_set); + + return $obj_rec["glo_id"]; + } + + /** + * get glossary term + */ + public static function _lookGlossaryTerm($term_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT * FROM glossary_term WHERE id = " . + $ilDB->quote($term_id, "integer"); + $obj_set = $ilDB->query($query); + $obj_rec = $ilDB->fetchAssoc($obj_set); + + return $obj_rec["term"]; + } + + /** + * lookup term language + */ + public static function _lookLanguage($term_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT * FROM glossary_term WHERE id = " . + $ilDB->quote($term_id, "integer"); + $obj_set = $ilDB->query($query); + $obj_rec = $ilDB->fetchAssoc($obj_set); + + return $obj_rec["language"]; + } + + /** + * Get all terms for given set of glossary ids. + * + * @param integer/array array of glossary ids for meta glossaries + * @param string searchstring + * @param string first letter + * @return array array of terms + */ + public static function getTermList( + $a_glo_ref_id, + $searchterm = "", + $a_first_letter = "", + $a_def = "", + $a_tax_node = 0, + $a_add_amet_fields = false, + array $a_amet_filter = null, + $a_include_references = false + ) { + global $DIC; + + if (is_array($a_glo_ref_id)) { + $a_glo_id = array_map(function ($id) { + return ilObject::_lookupObjectId($id); + }, $a_glo_ref_id); + } else { + $a_glo_id = ilObject::_lookupObjectId($a_glo_ref_id); + } + $ilDB = $DIC->database(); + + $join = $in = ""; + + $terms = array(); + + // get all term ids under taxonomy node (if given) + if ($a_tax_node > 1) { + include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php"); + $tax_ids = ilObjTaxonomy::getUsageOfObject($a_glo_id); + if (count($tax_ids) > 0) { + $items = ilObjTaxonomy::getSubTreeItems("glo", $a_glo_id, "term", $tax_ids[0], $a_tax_node); + $sub_tree_ids = array(); + foreach ($items as $i) { + $sub_tree_ids[] = $i["item_id"]; + } + $in = " AND " . $ilDB->in("gt.id", $sub_tree_ids, false, "integer"); + } + } + + if ($a_def != "") { + // meta glossary? + if (is_array($a_glo_id)) { + $glo_where = $ilDB->in("page_object.parent_id", $a_glo_id, false, "integer"); + } else { + $glo_where = " page_object.parent_id = " . $ilDB->quote($a_glo_id, "integer"); + } + + $join = " JOIN glossary_definition gd ON (gd.term_id = gt.id)" . + " JOIN page_object ON (" . + $glo_where . + " AND page_object.parent_type = " . $ilDB->quote("gdf", "text") . + " AND page_object.page_id = gd.id" . + " AND " . $ilDB->like("page_object.content", "text", "%" . $a_def . "%") . + ")"; + } + + $searchterm = (!empty($searchterm)) + ? " AND " . $ilDB->like("term", "text", "%" . $searchterm . "%") . " " + : ""; + + if ($a_first_letter != "") { + $searchterm.= " AND " . $ilDB->upper($ilDB->substr("term", 1, 1)) . " = " . $ilDB->upper($ilDB->quote($a_first_letter, "text")) . " "; + } + + // include references + $where_glo_id_or = ""; + if ($a_include_references) { + $join.= " LEFT JOIN glo_term_reference tr ON (gt.id = tr.term_id) "; + if (is_array($a_glo_id)) { + $where_glo_id_or = " OR " . $ilDB->in("tr.glo_id", $a_glo_id, false, "integer"); + } else { + $where_glo_id_or = " OR tr.glo_id = " . $ilDB->quote($a_glo_id, "integer"); + } + } + + // meta glossary + if (is_array($a_glo_id)) { + $where = "(" . $ilDB->in("gt.glo_id", $a_glo_id, false, "integer") . $where_glo_id_or . ")"; + } else { + $where = "(gt.glo_id = " . $ilDB->quote($a_glo_id, "integer") . $where_glo_id_or . ")"; + } + + $where.= $in; + + + $q = "SELECT DISTINCT(gt.term), gt.id, gt.glo_id, gt.language FROM glossary_term gt " . $join . " WHERE " . $where . $searchterm . " ORDER BY term"; + + //echo $q; exit; + + $term_set = $ilDB->query($q); + $glo_ids = array(); + while ($term_rec = $ilDB->fetchAssoc($term_set)) { + $terms[] = array("term" => $term_rec["term"], + "language" => $term_rec["language"], "id" => $term_rec["id"], "glo_id" => $term_rec["glo_id"]); + $glo_ids[] = $term_rec["glo_id"]; + } + + // add advanced metadata + if (($a_add_amet_fields || is_array($a_amet_filter)) && !is_array($a_glo_ref_id)) { + include_once("./Services/AdvancedMetaData/classes/class.ilAdvancedMDValues.php"); + $terms = ilAdvancedMDValues::queryForRecords($a_glo_ref_id, "glo", "term", $glo_ids, "term", $terms, "glo_id", "id", $a_amet_filter); + } + return $terms; + } + + /** + * Get all terms for given set of glossary ids. + * + * @param integer/array array of glossary ids for meta glossaries + * @param string searchstring + * @param string first letter + * @return array array of terms + */ + public static function getFirstLetters($a_glo_id, $a_tax_node = 0) + { + global $DIC; + + $ilDB = $DIC->database(); + + $terms = array(); + + // meta glossary + if (is_array($a_glo_id)) { + $where = $ilDB->in("glo_id", $a_glo_id, false, "integer"); + } else { + $where = " glo_id = " . $ilDB->quote($a_glo_id, "integer") . " "; + + // get all term ids under taxonomy node (if given) + if ($a_tax_node > 1) { + include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php"); + $tax_ids = ilObjTaxonomy::getUsageOfObject($a_glo_id); + if (count($tax_ids) > 0) { + $items = ilObjTaxonomy::getSubTreeItems("glo", $a_glo_id, "term", $tax_ids[0], $a_tax_node); + $sub_tree_ids = array(); + foreach ($items as $i) { + $sub_tree_ids[] = $i["item_id"]; + } + $in = " AND " . $ilDB->in("id", $sub_tree_ids, false, "integer"); + } + } + + $where.= $in; + } + + $q = "SELECT DISTINCT " . $ilDB->upper($ilDB->substr("term", 1, 1)) . " let FROM glossary_term WHERE " . $where . " ORDER BY let"; + $let_set = $ilDB->query($q); + + $lets = array(); + while ($let_rec = $ilDB->fetchAssoc($let_set)) { + $let[$let_rec["let"]] = $let_rec["let"]; + } + return $let; + } + + /** + * export xml + */ + public function exportXML(&$a_xml_writer, $a_inst) + { + $attrs = array(); + $attrs["Language"] = $this->getLanguage(); + $attrs["Id"] = "il_" . IL_INST_ID . "_git_" . $this->getId(); + $a_xml_writer->xmlStartTag("GlossaryItem", $attrs); + + $attrs = array(); + $a_xml_writer->xmlElement("GlossaryTerm", $attrs, $this->getTerm()); + + $defs = ilGlossaryDefinition::getDefinitionList($this->getId()); + + foreach ($defs as $def) { + $definition = new ilGlossaryDefinition($def["id"]); + $definition->exportXML($a_xml_writer, $a_inst); + } + + $a_xml_writer->xmlEndTag("GlossaryItem"); + } + + /** + * Get number of usages + * + * @param int term id + * @return int number of usages + */ + public static function getNumberOfUsages($a_term_id) + { + return count(ilGlossaryTerm::getUsages($a_term_id)); + } + + /** + * Get number of usages + * + * @param int term id + * @return int number of usages + */ + public static function getUsages($a_term_id) + { + include_once("./Services/Link/classes/class.ilInternalLink.php"); + $usages = (ilInternalLink::_getSourcesOfTarget("git", $a_term_id, 0)); + + include_once("./Modules/Glossary/classes/class.ilGlossaryTermReferences.php"); + foreach (ilGlossaryTermReferences::lookupReferencesOfTerm($a_term_id) as $glo_id) { + $usages["glo:termref:" . $glo_id . ":-"] = array( + "type" => "glo:termref", + "id" => $glo_id, + "lang" => "-" + ); + } + + return $usages; + } + + /** + * Copy a term to a glossary + * + * @param + * @return + */ + public static function _copyTerm($a_term_id, $a_glossary_id) + { + $old_term = new ilGlossaryTerm($a_term_id); + + // copy the term + $new_term = new ilGlossaryTerm(); + $new_term->setTerm($old_term->getTerm()); + $new_term->setLanguage($old_term->getLanguage()); + $new_term->setGlossaryId($a_glossary_id); + $new_term->create(); + + // copy the definitions + include_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); + $def_list = ilGlossaryDefinition::getDefinitionList($a_term_id); + foreach ($def_list as $def) { + $old_def = new ilGlossaryDefinition($def["id"]); + + $new_def = new ilGlossaryDefinition(); + $new_def->setShortText($old_def->getShortText()); + $new_def->setNr($old_def->getNr()); + $new_def->setTermId($new_term->getId()); + $new_def->create(); + + // copy meta data + include_once("Services/MetaData/classes/class.ilMD.php"); + $md = new ilMD( + $old_term->getGlossaryId(), + $old_def->getPageObject()->getId(), + $old_def->getPageObject()->getParentType() + ); + $new_md = $md->cloneMD( + $a_glossary_id, + $new_def->getPageObject()->getId(), + $old_def->getPageObject()->getParentType() + ); + + + $new_page = $new_def->getPageObject(); + $old_def->getPageObject()->copy($new_page->getId(), $new_page->getParentType(), $new_page->getParentId(), true); + + // page content + //$new_def->getPageObject()->setXMLContent($old_def->getPageObject()->copyXmlContent(true)); + //$new_def->getPageObject()->buildDom(); + //$new_def->getPageObject()->update(); + } + + // adv metadata + include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecord.php'); + include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDFieldDefinition.php'); + $old_recs = ilAdvancedMDRecord::_getSelectedRecordsByObject("glo", $old_term->getGlossaryId(), "term"); + $new_recs = ilAdvancedMDRecord::_getSelectedRecordsByObject("glo", $a_glossary_id, "term"); + foreach ($old_recs as $old_record_obj) { + reset($new_recs); + foreach ($new_recs as $new_record_obj) { + if ($old_record_obj->getRecordId() == $new_record_obj->getRecordId()) { + foreach (ilAdvancedMDFieldDefinition::getInstancesByRecordId($old_record_obj->getRecordId()) as $def) { + // now we need to copy $def->getFieldId() values from old term to new term + // how? + // clone values + + $source_primary = array("obj_id"=>array("integer", $old_term->getGlossaryId())); + $source_primary["sub_type"] = array("text", "term"); + $source_primary["sub_id"] = array("integer", $old_term->getId()); + $source_primary["field_id"] = array("integer", $def->getFieldId()); + $target_primary = array("obj_id"=>array("integer", $new_term->getGlossaryId())); + $target_primary["sub_type"] = array("text", "term"); + $target_primary["sub_id"] = array("integer", $new_term->getId()); + + ilADTFactory::getInstance()->initActiveRecordByType(); + $has_cloned = ilADTActiveRecordByType::cloneByPrimary( + "adv_md_values", + array( + "obj_id" => "integer", + "sub_type" => "text", + "sub_id" => "integer", + "field_id" => "integer" + ), + $source_primary, + $target_primary, + array("disabled"=>"integer") + ); + } + } + } + } + + + return $new_term->getId(); + } + + /** + * Get terms of glossary + * + * @param + * @return + */ + public static function getTermsOfGlossary($a_glo_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT id FROM glossary_term WHERE " . + " glo_id = " . $ilDB->quote($a_glo_id, "integer") + ); + $ids = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $ids[] = $rec["id"]; + } + return $ids; + } } - -?> diff --git a/Modules/Glossary/classes/class.ilGlossaryTermGUI.php b/Modules/Glossary/classes/class.ilGlossaryTermGUI.php index 4b0738c617df958cce13f205f6bc8ea8dc8027b0..d272696fdaa5806f027b780848b496aceca18fda 100755 --- a/Modules/Glossary/classes/class.ilGlossaryTermGUI.php +++ b/Modules/Glossary/classes/class.ilGlossaryTermGUI.php @@ -17,833 +17,837 @@ require_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); */ class ilGlossaryTermGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTabsGUI - */ - protected $tabs_gui; - - /** - * @var ilHelpGUI - */ - protected $help; - - var $lng; - var $tpl; - var $glossary; - var $term; - var $link_xml; - - /** - * @var ilLogger - */ - protected $log; - - /** - * @var ilObjGlossary|null - */ - protected $term_glossary = null; - - /** - * Constructor - * @access public - */ - function __construct($a_id = 0) - { - global $DIC; - - $this->help = $DIC["ilHelp"]; - $lng = $DIC->language(); - $tpl = $DIC["tpl"]; - $ilCtrl = $DIC->ctrl(); - $ilTabs = $DIC->tabs(); - - $this->lng = $lng; - $this->tpl = $tpl; - $this->ctrl = $ilCtrl; - $this->ctrl->saveParameter($this, array("term_id")); - $this->tabs_gui = $ilTabs; - - $this->log = ilLoggerFactory::getLogger('glo'); - - $this->ref_id = $_GET["ref_id"]; - - if($a_id != 0) - { - $this->term = new ilGlossaryTerm($a_id); - require_once("./Modules/Glossary/classes/class.ilObjGlossary.php"); - if (ilObject::_lookupObjectId($this->ref_id) == ilGlossaryTerm::_lookGlossaryID($a_id)) - { - $this->term_glossary = new ilObjGlossary($this->ref_id, true); - } - else - { - $this->term_glossary = new ilObjGlossary(ilGlossaryTerm::_lookGlossaryID($a_id), false); - } - } - } - - /** - * execute command - */ - function executeCommand() - { - $ilTabs = $this->tabs_gui; - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - $this->log->debug("glossary term, next class ".$next_class.", cmd: ".$cmd); - - switch ($next_class) - { - case "iltermdefinitioneditorgui": - //$this->ctrl->setReturn($this, "listDefinitions"); - $def_edit = new ilTermDefinitionEditorGUI(); - //$ret = $def_edit->executeCommand(); - $ret = $this->ctrl->forwardCommand($def_edit); - $this->quickList("edit", $def_edit); - break; - - case "ilpropertyformgui"; - $form = $this->getEditTermForm(); - $this->ctrl->forwardCommand($form); - break; - - case "ilobjectmetadatagui"; - $this->setTabs(); - $ilTabs->activateTab('meta_data'); - include_once 'Services/Object/classes/class.ilObjectMetaDataGUI.php'; - $md_gui = new ilObjectMetaDataGUI($this->term_glossary, - 'term', $this->term->getId()); - $this->ctrl->forwardCommand($md_gui); - $this->quickList(); - break; - - default: - $ret = $this->$cmd(); - break; - } - } - - /** - * set offline directory to offdir - * - * @param offdir contains diretory where to store files - */ - function setOfflineDirectory ($offdir) { - $this->offline_directory = $offdir; - } - - - /** - * get offline directory - * @return directory where to store offline files - */ - function getOfflineDirectory () { - return $this->offline_directory; - } - - - function setGlossary($a_glossary) - { - $this->glossary = $a_glossary; - if (!is_object($this->term_glossary)) - { - $this->term_glossary = $a_glossary; - } - } - - function setLinkXML($a_link_xml) - { - $this->link_xml = $a_link_xml; - } - - function getLinkXML() - { - return $this->link_xml; - } - - /** - * form for new content object creation - */ - function create() - { - // deprecated - } - - /** - * save term - */ - function saveTerm() - { - // deprecated - } - - - /** - * Edit term - */ - function editTerm(ilPropertyFormGUI $a_form = null) - { - $ilTabs = $this->tabs_gui; - $ilCtrl = $this->ctrl; - -// $this->getTemplate(); - $this->displayLocator(); - $this->setTabs(); - $ilTabs->activateTab("properties"); - - $this->tpl->setTitle($this->lng->txt("cont_term").": ".$this->term->getTerm()); - $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_glo.svg")); - - if(!$a_form) - { - $a_form = $this->getEditTermForm(); - } - - $this->tpl->setContent($ilCtrl->getHTML($a_form)); - - $this->quickList(); - } - - /** - * Get edit term form - * - * @param - * @return - */ - function getEditTermForm() - { - $ilTabs = $this->tabs_gui; - $ilCtrl = $this->ctrl; - - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this, "updateTerm")); - $form->setTitle($this->lng->txt("cont_edit_term")); - - $term = new ilTextInputGUI($this->lng->txt("cont_term"), "term"); - $term->setRequired(true); - $term->setValue($this->term->getTerm()); - $form->addItem($term); - - $lang = new ilSelectInputGUI($this->lng->txt("language"), "term_language"); - $lang->setRequired(true); - $lang->setOptions(ilMDLanguageItem::_getLanguages()); - $lang->setValue($this->term->getLanguage()); - $form->addItem($lang); - - // taxonomy - if ($this->term_glossary->getTaxonomyId() > 0) - { - include_once("./Services/Taxonomy/classes/class.ilTaxSelectInputGUI.php"); - $tax_node_assign = new ilTaxSelectInputGUI($this->term_glossary->getTaxonomyId(), "tax_node", true); - - include_once("./Services/Taxonomy/classes/class.ilTaxNodeAssignment.php"); - $ta = new ilTaxNodeAssignment("glo", $this->term_glossary->getId(), "term", $this->term_glossary->getTaxonomyId()); - $assgnmts = $ta->getAssignmentsOfItem($this->term->getId()); - $node_ids = array(); - foreach ($assgnmts as $a) - { - $node_ids[] = $a["node_id"]; - } - $tax_node_assign->setValue($node_ids); - - $form->addItem($tax_node_assign); - - } - - // advanced metadata - include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecordGUI.php'); - $this->record_gui = new ilAdvancedMDRecordGUI(ilAdvancedMDRecordGUI::MODE_EDITOR,'glo',$this->term_glossary->getId(),'term', - $this->term->getId()); - $this->record_gui->setPropertyForm($form); - $this->record_gui->parse(); - - $form->addCommandButton("updateTerm", $this->lng->txt("save")); - - return $form; - } - - - - /** - * update term - */ - function updateTerm() - { - $form = $this->getEditTermForm(); - if($form->checkInput() && - $this->record_gui->importEditFormPostValues()) - { - // update term - $this->term->setTerm(ilUtil::stripSlashes($_POST["term"])); - $this->term->setLanguage($_POST["term_language"]); - $this->term->update(); - - // update taxonomy assignment - if ($this->term_glossary->getTaxonomyId() > 0) - { - include_once("./Services/Taxonomy/classes/class.ilTaxNodeAssignment.php"); - $ta = new ilTaxNodeAssignment("glo", $this->term_glossary->getId(), "term", $this->term_glossary->getTaxonomyId()); - $ta->deleteAssignmentsOfItem($this->term->getId()); - if (is_array($_POST["tax_node"])) - { - foreach ($_POST["tax_node"] as $node_id) - { - $ta->addAssignment($node_id, $this->term->getId()); - } - } - - } - - $this->record_gui->writeEditForm(); - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"),true); - $this->ctrl->redirect($this, "editTerm"); - } - - $form->setValuesByPost(); - $this->editTerm($form); - } - - /** - * Get overlay html - * - * @param - * @return - */ - function getOverlayHTML($a_close_el_id, $a_glo_ov_id = "", $a_lang = "", $a_outputmode = "offline") - { - $lng = $this->lng; - - if ($a_lang == "") - { - $a_lang = $lng->getLangKey(); - } - - $tpl = new ilTemplate("tpl.glossary_overlay.html", true, true, "Modules/Glossary"); -// $this->output(true, $tpl); - if ($a_outputmode == "preview") - { - $a_outputmode = "presentation"; - } - if ($a_outputmode == "offline") - { - $this->output(true, $tpl, $a_outputmode); - } - else - { - $this->output(false, $tpl, $a_outputmode); - } - if ($a_glo_ov_id != "") - { - $tpl->setCurrentBlock("glovlink"); - $tpl->setVariable("TXT_LINK", $lng->txtlng("content", "cont_sco_glossary", $a_lang)); - $tpl->setVariable("ID_LINK", $a_glo_ov_id); - $tpl->parseCurrentBlock(); - } - $tpl->setVariable("TXT_CLOSE", $lng->txtlng("common", "close", $a_lang)); - $tpl->setVariable("ID_CLOSE", $a_close_el_id); - return $tpl->get(); - } - - /** - * output glossary term definitions - * - * used in ilLMPresentationGUI->ilGlossary() - */ - function output($a_offline = false, $a_tpl = "", $a_outputmode = "presentation") - { - if ($a_tpl != "") - { - $tpl = $a_tpl; - } - else - { - $tpl = $this->tpl; - } - - require_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); - require_once("./Modules/Glossary/classes/class.ilGlossaryDefPageGUI.php"); - - $defs = ilGlossaryDefinition::getDefinitionList($this->term->getId()); - - $tpl->setVariable("TXT_TERM", $this->term->getTerm()); - - for($j=0; $jsetSourcecodeDownloadScript("ilias.php?baseClass=ilGlossaryPresentationGUI&ref_id=".$_GET["ref_id"]); - if (!$a_offline) - { - //$page_gui->setFullscreenLink( - // "ilias.php?baseClass=ilGlossaryPresentationGUI&cmd=fullscreen&ref_id=".$_GET["ref_id"]); - } - else - { - $page_gui->setFullscreenLink("fullscreen.html"); // id is set by xslt - } - $page_gui->setFileDownloadLink("ilias.php?baseClass=ilGlossaryPresentationGUI&cmd=downloadFile&ref_id=".$_GET["ref_id"]); - - if (!$a_offline) - { - $page_gui->setOutputMode($a_outputmode); - } - else - { - $page_gui->setOutputMode("offline"); - $page_gui->setOfflineDirectory($this->getOfflineDirectory()); - } - - //$page_gui->setOutputMode("edit"); - //$page_gui->setPresentationTitle($this->term->getTerm()); - $page_gui->setLinkXML($this->getLinkXML()); - $page_gui->setTemplateOutput(false); - $output = $page_gui->presentation($page_gui->getOutputMode()); - - if (count($defs) > 1) - { - $tpl->setCurrentBlock("definition_header"); - $tpl->setVariable("TXT_DEFINITION", - $this->lng->txt("cont_definition")." ".($j+1)); - $tpl->parseCurrentBlock(); - } - - include_once './Services/MathJax/classes/class.ilMathJax.php'; - ilMathJax::getInstance()->includeMathJax($tpl); - - $tpl->setCurrentBlock("definition"); - $tpl->setVariable("PAGE_CONTENT", $output); - $tpl->parseCurrentBlock(); - } - } - - /** - * get internal links - */ - function getInternalLinks() - { - require_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); - require_once("./Modules/Glossary/classes/class.ilGlossaryDefPageGUI.php"); - - $defs = ilGlossaryDefinition::getDefinitionList($this->term->getId()); - - $term_links = array(); - for($j=0; $jbuildDom(); - $page_links = $page->getInternalLinks(); - foreach($page_links as $key => $page_link) - { - $term_links[$key] = $page_link; - } - } - - return $term_links; - } - - /** - * list definitions - */ - function listDefinitions() - { - $ilTabs = $this->tabs_gui; - -// $this->getTemplate(); - $this->displayLocator(); - $this->setTabs(); - $ilTabs->activateTab("definitions"); - require_once("./Modules/Glossary/classes/class.ilGlossaryDefPageGUI.php"); - - // content style - $this->tpl->setCurrentBlock("ContentStyle"); - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->term_glossary->getStyleSheetId())); - $this->tpl->parseCurrentBlock(); - - // syntax style - $this->tpl->setCurrentBlock("SyntaxStyle"); - $this->tpl->setVariable("LOCATION_SYNTAX_STYLESHEET", - ilObjStyleSheet::getSyntaxStylePath()); - $this->tpl->parseCurrentBlock(); - - // load template for table - $this->tpl->addBlockfile("ADM_CONTENT", "def_list", "tpl.glossary_definition_list.html", true); - //$this->tpl->addBlockfile("CONTENT", "def_list", "tpl.glossary_definition_list.html", true); - //ilUtil::sendInfo(); -// $this->tpl->addBlockfile("STATUSLINE", "statusline", "tpl.statusline.html"); - $this->tpl->setTitle( - $this->lng->txt("cont_term").": ".$this->term->getTerm()); - $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_glo.svg")); - - $this->tpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this)); - - $this->tpl->setCurrentBlock("add_def"); - $this->tpl->setVariable("TXT_ADD_DEFINITION", - $this->lng->txt("cont_add_definition")); - $this->tpl->setVariable("BTN_ADD", "addDefinition"); - $this->tpl->parseCurrentBlock(); - $this->tpl->setCurrentBlock("def_list"); - - $defs = ilGlossaryDefinition::getDefinitionList($_GET["term_id"]); - - $this->tpl->setVariable("TXT_TERM", $this->term->getTerm()); - - for($j=0; $jsetStyleId($this->term_glossary->getStyleSheetId()); - $page_gui->setSourcecodeDownloadScript("ilias.php?baseClass=ilGlossaryPresentationGUI&ref_id=".$_GET["ref_id"]); - $page_gui->setTemplateOutput(false); - $output = $page_gui->preview(); - - if (count($defs) > 1) - { - $this->tpl->setCurrentBlock("definition_header"); - $this->tpl->setVariable("TXT_DEFINITION", - $this->lng->txt("cont_definition")." ".($j+1)); - $this->tpl->parseCurrentBlock(); - } - - if ($j > 0) - { - $this->tpl->setCurrentBlock("up"); - $this->tpl->setVariable("TXT_UP", $this->lng->txt("up")); - $this->ctrl->setParameter($this, "def", $def["id"]); - $this->tpl->setVariable("LINK_UP", - $this->ctrl->getLinkTarget($this, "moveUp")); - $this->tpl->parseCurrentBlock(); - } - - if ($j+1 < count($defs)) - { - $this->tpl->setCurrentBlock("down"); - $this->tpl->setVariable("TXT_DOWN", $this->lng->txt("down")); - $this->ctrl->setParameter($this, "def", $def["id"]); - $this->tpl->setVariable("LINK_DOWN", - $this->ctrl->getLinkTarget($this, "moveDown")); - $this->tpl->parseCurrentBlock(); - } - $this->tpl->setCurrentBlock("submit_btns"); - $this->tpl->setVariable("TXT_EDIT", $this->lng->txt("edit")); - $this->ctrl->setParameter($this, "def", $def["id"]); - $this->ctrl->setParameterByClass("ilTermDefinitionEditorGUI", "def", $def["id"]); - $this->tpl->setVariable("LINK_EDIT", - $this->ctrl->getLinkTargetByClass(array("ilTermDefinitionEditorGUI", "ilGlossaryDefPageGUI"), "edit")); - $this->tpl->setVariable("TXT_DELETE", $this->lng->txt("delete")); - $this->tpl->setVariable("LINK_DELETE", - $this->ctrl->getLinkTarget($this, "confirmDefinitionDeletion")); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setCurrentBlock("definition"); - $this->tpl->setVariable("PAGE_CONTENT", $output); - $this->tpl->parseCurrentBlock(); - } - //$this->tpl->setCurrentBlock("def_list"); - //$this->tpl->parseCurrentBlock(); - - $this->quickList(); - } - - - /** - * deletion confirmation screen - */ - function confirmDefinitionDeletion() - { - $ilTabs = $this->tabs_gui; - - //$this->getTemplate(); - $this->displayLocator(); - $this->setTabs(); - $ilTabs->activateTab("definitions"); - - // content style - $this->tpl->setCurrentBlock("ContentStyle"); - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->term_glossary->getStyleSheetId())); - $this->tpl->parseCurrentBlock(); - - // syntax style - $this->tpl->setCurrentBlock("SyntaxStyle"); - $this->tpl->setVariable("LOCATION_SYNTAX_STYLESHEET", - ilObjStyleSheet::getSyntaxStylePath()); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setTitle( - $this->lng->txt("cont_term").": ".$this->term->getTerm()); - $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_glo.svg")); - - $this->tpl->addBlockfile("ADM_CONTENT", "def_list", "tpl.glossary_definition_delete.html", true); - ilUtil::sendQuestion($this->lng->txt("info_delete_sure")); - - $this->tpl->setVariable("TXT_TERM", $this->term->getTerm()); - - $definition = new ilGlossaryDefinition($_GET["def"]); - $page_gui = new ilGlossaryDefPageGUI($definition->getId()); - $page_gui->setTemplateOutput(false); - $page_gui->setStyleId($this->term_glossary->getStyleSheetId()); - $page_gui->setSourcecodeDownloadScript("ilias.php?baseClass=ilGlossaryPresentationGUI&ref_id=".$_GET["ref_id"]); - $page_gui->setFileDownloadLink("ilias.php?baseClass=ilGlossaryPresentationGUI&ref_id=".$_GET["ref_id"]); - $page_gui->setFullscreenLink("ilias.php?baseClass=ilGlossaryPresentationGUI&ref_id=".$_GET["ref_id"]); - $output = $page_gui->preview(); - - $this->tpl->setCurrentBlock("definition"); - $this->tpl->setVariable("PAGE_CONTENT", $output); - $this->tpl->setVariable("TXT_CANCEL", $this->lng->txt("cancel")); - $this->tpl->setVariable("LINK_CANCEL", - $this->ctrl->getLinkTarget($this, "cancelDefinitionDeletion")); - $this->tpl->setVariable("TXT_CONFIRM", $this->lng->txt("confirm")); - $this->ctrl->setParameter($this, "def", $definition->getId()); - $this->tpl->setVariable("LINK_CONFIRM", - $this->ctrl->getLinkTarget($this, "deleteDefinition")); - $this->tpl->parseCurrentBlock(); - } - - function cancelDefinitionDeletion() - { - $this->ctrl->redirect($this, "listDefinitions"); - } - - - function deleteDefinition() - { - $definition = new ilGlossaryDefinition($_GET["def"]); - $definition->delete(); - $this->ctrl->redirect($this, "listDefinitions"); - } - - - /** - * move definition upwards - */ - function moveUp() - { - $definition = new ilGlossaryDefinition($_GET["def"]); - $definition->moveUp(); - $this->ctrl->redirect($this, "listDefinitions"); - } - - - /** - * move definition downwards - */ - function moveDown() - { - $definition = new ilGlossaryDefinition($_GET["def"]); - $definition->moveDown(); - $this->ctrl->redirect($this, "listDefinitions"); - } - - - /** - * add definition - */ - function addDefinition() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameterByClass("ilobjglossarygui", "term_id", $this->term->getId()); - $ilCtrl->redirectByClass("ilobjglossarygui", "addDefinition"); - } - - /** - * cancel adding definition - */ - function cancel() - { - $this->ctrl->redirect($this, "listDefinitions"); - } - - /** - * save definition - */ - function saveDefinition() - { - $def = new ilGlossaryDefinition(); - $def->setTermId($_GET["term_id"]); - $def->setTitle(ilUtil::stripSlashes($_POST["title"]));#"content object ".$newObj->getId()); // set by meta_gui->save - $def->setDescription(ilUtil::stripSlashes($_POST["desc"])); // set by meta_gui->save - $def->create(); - - $this->ctrl->redirect($this, "listDefinitions"); - } - - /** - * output tabs - */ - function setTabs() - { - $this->getTabs(); - } - - /** - * display locator - */ - function displayLocator() - { - require_once ("./Modules/Glossary/classes/class.ilGlossaryLocatorGUI.php"); - $gloss_loc = new ilGlossaryLocatorGUI(); - $gloss_loc->setTerm($this->term); - $gloss_loc->setGlossary($this->glossary); - //$gloss_loc->setDefinition($this->definition); - $gloss_loc->display(); - } - - - /** - * get tabs - */ - function getTabs() - { - $lng = $this->lng; - $ilHelp = $this->help; - - - $ilHelp->setScreenIdComponent("glo_term"); - -//echo ":".$_GET["term_id"].":"; - if ($_GET["term_id"] != "") - { - $this->tabs_gui->addTab("properties", - $lng->txt("term"), - $this->ctrl->getLinkTarget($this, "editTerm")); - - $this->tabs_gui->addTab("definitions", - $lng->txt("cont_definitions"), - $this->ctrl->getLinkTarget($this, "listDefinitions")); - - $this->tabs_gui->addTab("usage", - $lng->txt("cont_usage")." (".ilGlossaryTerm::getNumberOfUsages($_GET["term_id"]).")", - $this->ctrl->getLinkTarget($this, "listUsages")); - - include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php"; - $mdgui = new ilObjectMetaDataGUI($this->term_glossary, - "term", $this->term->getId()); - $mdtab = $mdgui->getTab(); - if($mdtab) - { - $this->tabs_gui->addTab("meta_data", - $lng->txt("meta_data"), - $mdtab); - } - - $this->tabs_gui->addNonTabbedLink("presentation_view", - $this->lng->txt("glo_presentation_view"), - ILIAS_HTTP_PATH. - "/goto.php?target=". - "git". - "_".$_GET["term_id"]."_".$_GET["ref_id"]."&client_id=".CLIENT_ID, - "_top" - ); - - } - - // back to glossary - $this->tabs_gui->setBackTarget($this->lng->txt("glossary"), - $this->ctrl->getLinkTargetByClass("ilobjglossarygui", "listTerms")); - - } - - /** - * redirect script - * - * @param string $a_target - */ - public static function _goto($a_target, $a_ref_id = "") - { - global $DIC; - - $rbacsystem = $DIC->rbac()->system(); - $ilErr = $DIC["ilErr"]; - $lng = $DIC->language(); - $ilAccess = $DIC->access(); - - $glo_id = ilGlossaryTerm::_lookGlossaryID($a_target);//::_lookupContObjID($a_target); - - // get all references - if ($a_ref_id > 0) - { - $ref_ids = array($a_ref_id); - } - else - { - $ref_ids = ilObject::_getAllReferences($glo_id); - } - - // check read permissions - foreach ($ref_ids as $ref_id) - { - // Permission check - if ($ilAccess->checkAccess("read", "", $ref_id)) - { - $_GET["baseClass"] = "ilGlossaryPresentationGUI"; - $_GET["term_id"] = $a_target; - $_GET["ref_id"] = $ref_id; - $_GET["cmd"] = "listDefinitions"; - include_once("ilias.php"); - exit; - } - } - if ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) - { - ilUtil::sendFailure(sprintf($lng->txt("msg_no_perm_read_item"), - ilObject::_lookupTitle($glo_id)), true); - ilObjectGUI::_gotoRepositoryRoot(); - } - - - $ilErr->raiseError($lng->txt("msg_no_perm_read_lm"), $ilErr->FATAL); - } - - /** - * List usage - */ - function listUsages() - { - $ilTabs = $this->tabs_gui; - $tpl = $this->tpl; - - //$this->displayLocator(); -// $this->getTemplate(); - $this->displayLocator(); - $this->setTabs(); - $ilTabs->activateTab("usage"); - - $this->tpl->setTitle($this->lng->txt("cont_term").": ".$this->term->getTerm()); - $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_glo.svg")); - - include_once("./Modules/Glossary/classes/class.ilTermUsagesTableGUI.php"); - $tab = new ilTermUsagesTableGUI($this, "listUsages", $_GET["term_id"]); - - $tpl->setContent($tab->getHTML()); - - $this->quickList(); - } - - /** - * Set quick term list cmd into left navigation URL - */ - function quickList() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - - //$tpl->setLeftNavUrl($ilCtrl->getLinkTarget($this, "showQuickList")); - - include_once("./Modules/Glossary/classes/class.ilTermQuickListTableGUI.php"); - $tab = new ilTermQuickListTableGUI($this, "editTerm"); - $tpl->setLeftNavContent($tab->getHTML()); - } + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTabsGUI + */ + protected $tabs_gui; + + /** + * @var ilHelpGUI + */ + protected $help; + + public $lng; + public $tpl; + public $glossary; + public $term; + public $link_xml; + + /** + * @var ilLogger + */ + protected $log; + + /** + * @var ilObjGlossary|null + */ + protected $term_glossary = null; + + /** + * Constructor + * @access public + */ + public function __construct($a_id = 0) + { + global $DIC; + + $this->help = $DIC["ilHelp"]; + $lng = $DIC->language(); + $tpl = $DIC["tpl"]; + $ilCtrl = $DIC->ctrl(); + $ilTabs = $DIC->tabs(); + + $this->lng = $lng; + $this->tpl = $tpl; + $this->ctrl = $ilCtrl; + $this->ctrl->saveParameter($this, array("term_id")); + $this->tabs_gui = $ilTabs; + + $this->log = ilLoggerFactory::getLogger('glo'); + + $this->ref_id = $_GET["ref_id"]; + + if ($a_id != 0) { + $this->term = new ilGlossaryTerm($a_id); + require_once("./Modules/Glossary/classes/class.ilObjGlossary.php"); + if (ilObject::_lookupObjectId($this->ref_id) == ilGlossaryTerm::_lookGlossaryID($a_id)) { + $this->term_glossary = new ilObjGlossary($this->ref_id, true); + } else { + $this->term_glossary = new ilObjGlossary(ilGlossaryTerm::_lookGlossaryID($a_id), false); + } + } + } + + /** + * execute command + */ + public function executeCommand() + { + $ilTabs = $this->tabs_gui; + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + $this->log->debug("glossary term, next class " . $next_class . ", cmd: " . $cmd); + + switch ($next_class) { + case "iltermdefinitioneditorgui": + //$this->ctrl->setReturn($this, "listDefinitions"); + $def_edit = new ilTermDefinitionEditorGUI(); + //$ret = $def_edit->executeCommand(); + $ret = $this->ctrl->forwardCommand($def_edit); + $this->quickList("edit", $def_edit); + break; + + case "ilpropertyformgui": + $form = $this->getEditTermForm(); + $this->ctrl->forwardCommand($form); + break; + + case "ilobjectmetadatagui": + $this->setTabs(); + $ilTabs->activateTab('meta_data'); + include_once 'Services/Object/classes/class.ilObjectMetaDataGUI.php'; + $md_gui = new ilObjectMetaDataGUI( + $this->term_glossary, + 'term', + $this->term->getId() + ); + $this->ctrl->forwardCommand($md_gui); + $this->quickList(); + break; + + default: + $ret = $this->$cmd(); + break; + } + } + + /** + * set offline directory to offdir + * + * @param offdir contains diretory where to store files + */ + public function setOfflineDirectory($offdir) + { + $this->offline_directory = $offdir; + } + + + /** + * get offline directory + * @return directory where to store offline files + */ + public function getOfflineDirectory() + { + return $this->offline_directory; + } + + + public function setGlossary($a_glossary) + { + $this->glossary = $a_glossary; + if (!is_object($this->term_glossary)) { + $this->term_glossary = $a_glossary; + } + } + + public function setLinkXML($a_link_xml) + { + $this->link_xml = $a_link_xml; + } + + public function getLinkXML() + { + return $this->link_xml; + } + + /** + * form for new content object creation + */ + public function create() + { + // deprecated + } + + /** + * save term + */ + public function saveTerm() + { + // deprecated + } + + + /** + * Edit term + */ + public function editTerm(ilPropertyFormGUI $a_form = null) + { + $ilTabs = $this->tabs_gui; + $ilCtrl = $this->ctrl; + + // $this->getTemplate(); + $this->displayLocator(); + $this->setTabs(); + $ilTabs->activateTab("properties"); + + $this->tpl->setTitle($this->lng->txt("cont_term") . ": " . $this->term->getTerm()); + $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_glo.svg")); + + if (!$a_form) { + $a_form = $this->getEditTermForm(); + } + + $this->tpl->setContent($ilCtrl->getHTML($a_form)); + + $this->quickList(); + } + + /** + * Get edit term form + * + * @param + * @return + */ + public function getEditTermForm() + { + $ilTabs = $this->tabs_gui; + $ilCtrl = $this->ctrl; + + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this, "updateTerm")); + $form->setTitle($this->lng->txt("cont_edit_term")); + + $term = new ilTextInputGUI($this->lng->txt("cont_term"), "term"); + $term->setRequired(true); + $term->setValue($this->term->getTerm()); + $form->addItem($term); + + $lang = new ilSelectInputGUI($this->lng->txt("language"), "term_language"); + $lang->setRequired(true); + $lang->setOptions(ilMDLanguageItem::_getLanguages()); + $lang->setValue($this->term->getLanguage()); + $form->addItem($lang); + + // taxonomy + if ($this->term_glossary->getTaxonomyId() > 0) { + include_once("./Services/Taxonomy/classes/class.ilTaxSelectInputGUI.php"); + $tax_node_assign = new ilTaxSelectInputGUI($this->term_glossary->getTaxonomyId(), "tax_node", true); + + include_once("./Services/Taxonomy/classes/class.ilTaxNodeAssignment.php"); + $ta = new ilTaxNodeAssignment("glo", $this->term_glossary->getId(), "term", $this->term_glossary->getTaxonomyId()); + $assgnmts = $ta->getAssignmentsOfItem($this->term->getId()); + $node_ids = array(); + foreach ($assgnmts as $a) { + $node_ids[] = $a["node_id"]; + } + $tax_node_assign->setValue($node_ids); + + $form->addItem($tax_node_assign); + } + + // advanced metadata + include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecordGUI.php'); + $this->record_gui = new ilAdvancedMDRecordGUI( + ilAdvancedMDRecordGUI::MODE_EDITOR, + 'glo', + $this->term_glossary->getId(), + 'term', + $this->term->getId() + ); + $this->record_gui->setPropertyForm($form); + $this->record_gui->parse(); + + $form->addCommandButton("updateTerm", $this->lng->txt("save")); + + return $form; + } + + + + /** + * update term + */ + public function updateTerm() + { + $form = $this->getEditTermForm(); + if ($form->checkInput() && + $this->record_gui->importEditFormPostValues()) { + // update term + $this->term->setTerm(ilUtil::stripSlashes($_POST["term"])); + $this->term->setLanguage($_POST["term_language"]); + $this->term->update(); + + // update taxonomy assignment + if ($this->term_glossary->getTaxonomyId() > 0) { + include_once("./Services/Taxonomy/classes/class.ilTaxNodeAssignment.php"); + $ta = new ilTaxNodeAssignment("glo", $this->term_glossary->getId(), "term", $this->term_glossary->getTaxonomyId()); + $ta->deleteAssignmentsOfItem($this->term->getId()); + if (is_array($_POST["tax_node"])) { + foreach ($_POST["tax_node"] as $node_id) { + $ta->addAssignment($node_id, $this->term->getId()); + } + } + } + + $this->record_gui->writeEditForm(); + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "editTerm"); + } + + $form->setValuesByPost(); + $this->editTerm($form); + } + + /** + * Get overlay html + * + * @param + * @return + */ + public function getOverlayHTML($a_close_el_id, $a_glo_ov_id = "", $a_lang = "", $a_outputmode = "offline") + { + $lng = $this->lng; + + if ($a_lang == "") { + $a_lang = $lng->getLangKey(); + } + + $tpl = new ilTemplate("tpl.glossary_overlay.html", true, true, "Modules/Glossary"); + // $this->output(true, $tpl); + if ($a_outputmode == "preview") { + $a_outputmode = "presentation"; + } + if ($a_outputmode == "offline") { + $this->output(true, $tpl, $a_outputmode); + } else { + $this->output(false, $tpl, $a_outputmode); + } + if ($a_glo_ov_id != "") { + $tpl->setCurrentBlock("glovlink"); + $tpl->setVariable("TXT_LINK", $lng->txtlng("content", "cont_sco_glossary", $a_lang)); + $tpl->setVariable("ID_LINK", $a_glo_ov_id); + $tpl->parseCurrentBlock(); + } + $tpl->setVariable("TXT_CLOSE", $lng->txtlng("common", "close", $a_lang)); + $tpl->setVariable("ID_CLOSE", $a_close_el_id); + return $tpl->get(); + } + + /** + * output glossary term definitions + * + * used in ilLMPresentationGUI->ilGlossary() + */ + public function output($a_offline = false, $a_tpl = "", $a_outputmode = "presentation") + { + if ($a_tpl != "") { + $tpl = $a_tpl; + } else { + $tpl = $this->tpl; + } + + require_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); + require_once("./Modules/Glossary/classes/class.ilGlossaryDefPageGUI.php"); + + $defs = ilGlossaryDefinition::getDefinitionList($this->term->getId()); + + $tpl->setVariable("TXT_TERM", $this->term->getTerm()); + + for ($j=0; $jsetSourcecodeDownloadScript("ilias.php?baseClass=ilGlossaryPresentationGUI&ref_id=" . $_GET["ref_id"]); + if (!$a_offline) { + //$page_gui->setFullscreenLink( + // "ilias.php?baseClass=ilGlossaryPresentationGUI&cmd=fullscreen&ref_id=".$_GET["ref_id"]); + } else { + $page_gui->setFullscreenLink("fullscreen.html"); // id is set by xslt + } + $page_gui->setFileDownloadLink("ilias.php?baseClass=ilGlossaryPresentationGUI&cmd=downloadFile&ref_id=" . $_GET["ref_id"]); + + if (!$a_offline) { + $page_gui->setOutputMode($a_outputmode); + } else { + $page_gui->setOutputMode("offline"); + $page_gui->setOfflineDirectory($this->getOfflineDirectory()); + } + + //$page_gui->setOutputMode("edit"); + //$page_gui->setPresentationTitle($this->term->getTerm()); + $page_gui->setLinkXML($this->getLinkXML()); + $page_gui->setTemplateOutput(false); + $output = $page_gui->presentation($page_gui->getOutputMode()); + + if (count($defs) > 1) { + $tpl->setCurrentBlock("definition_header"); + $tpl->setVariable( + "TXT_DEFINITION", + $this->lng->txt("cont_definition") . " " . ($j+1) + ); + $tpl->parseCurrentBlock(); + } + + include_once './Services/MathJax/classes/class.ilMathJax.php'; + ilMathJax::getInstance()->includeMathJax($tpl); + + $tpl->setCurrentBlock("definition"); + $tpl->setVariable("PAGE_CONTENT", $output); + $tpl->parseCurrentBlock(); + } + } + + /** + * get internal links + */ + public function getInternalLinks() + { + require_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); + require_once("./Modules/Glossary/classes/class.ilGlossaryDefPageGUI.php"); + + $defs = ilGlossaryDefinition::getDefinitionList($this->term->getId()); + + $term_links = array(); + for ($j=0; $jbuildDom(); + $page_links = $page->getInternalLinks(); + foreach ($page_links as $key => $page_link) { + $term_links[$key] = $page_link; + } + } + + return $term_links; + } + + /** + * list definitions + */ + public function listDefinitions() + { + $ilTabs = $this->tabs_gui; + + // $this->getTemplate(); + $this->displayLocator(); + $this->setTabs(); + $ilTabs->activateTab("definitions"); + require_once("./Modules/Glossary/classes/class.ilGlossaryDefPageGUI.php"); + + // content style + $this->tpl->setCurrentBlock("ContentStyle"); + $this->tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath($this->term_glossary->getStyleSheetId()) + ); + $this->tpl->parseCurrentBlock(); + + // syntax style + $this->tpl->setCurrentBlock("SyntaxStyle"); + $this->tpl->setVariable( + "LOCATION_SYNTAX_STYLESHEET", + ilObjStyleSheet::getSyntaxStylePath() + ); + $this->tpl->parseCurrentBlock(); + + // load template for table + $this->tpl->addBlockfile("ADM_CONTENT", "def_list", "tpl.glossary_definition_list.html", true); + //$this->tpl->addBlockfile("CONTENT", "def_list", "tpl.glossary_definition_list.html", true); + //ilUtil::sendInfo(); + // $this->tpl->addBlockfile("STATUSLINE", "statusline", "tpl.statusline.html"); + $this->tpl->setTitle( + $this->lng->txt("cont_term") . ": " . $this->term->getTerm() + ); + $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_glo.svg")); + + $this->tpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this)); + + $this->tpl->setCurrentBlock("add_def"); + $this->tpl->setVariable( + "TXT_ADD_DEFINITION", + $this->lng->txt("cont_add_definition") + ); + $this->tpl->setVariable("BTN_ADD", "addDefinition"); + $this->tpl->parseCurrentBlock(); + $this->tpl->setCurrentBlock("def_list"); + + $defs = ilGlossaryDefinition::getDefinitionList($_GET["term_id"]); + + $this->tpl->setVariable("TXT_TERM", $this->term->getTerm()); + + for ($j=0; $jsetStyleId($this->term_glossary->getStyleSheetId()); + $page_gui->setSourcecodeDownloadScript("ilias.php?baseClass=ilGlossaryPresentationGUI&ref_id=" . $_GET["ref_id"]); + $page_gui->setTemplateOutput(false); + $output = $page_gui->preview(); + + if (count($defs) > 1) { + $this->tpl->setCurrentBlock("definition_header"); + $this->tpl->setVariable( + "TXT_DEFINITION", + $this->lng->txt("cont_definition") . " " . ($j+1) + ); + $this->tpl->parseCurrentBlock(); + } + + if ($j > 0) { + $this->tpl->setCurrentBlock("up"); + $this->tpl->setVariable("TXT_UP", $this->lng->txt("up")); + $this->ctrl->setParameter($this, "def", $def["id"]); + $this->tpl->setVariable( + "LINK_UP", + $this->ctrl->getLinkTarget($this, "moveUp") + ); + $this->tpl->parseCurrentBlock(); + } + + if ($j+1 < count($defs)) { + $this->tpl->setCurrentBlock("down"); + $this->tpl->setVariable("TXT_DOWN", $this->lng->txt("down")); + $this->ctrl->setParameter($this, "def", $def["id"]); + $this->tpl->setVariable( + "LINK_DOWN", + $this->ctrl->getLinkTarget($this, "moveDown") + ); + $this->tpl->parseCurrentBlock(); + } + $this->tpl->setCurrentBlock("submit_btns"); + $this->tpl->setVariable("TXT_EDIT", $this->lng->txt("edit")); + $this->ctrl->setParameter($this, "def", $def["id"]); + $this->ctrl->setParameterByClass("ilTermDefinitionEditorGUI", "def", $def["id"]); + $this->tpl->setVariable( + "LINK_EDIT", + $this->ctrl->getLinkTargetByClass(array("ilTermDefinitionEditorGUI", "ilGlossaryDefPageGUI"), "edit") + ); + $this->tpl->setVariable("TXT_DELETE", $this->lng->txt("delete")); + $this->tpl->setVariable( + "LINK_DELETE", + $this->ctrl->getLinkTarget($this, "confirmDefinitionDeletion") + ); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setCurrentBlock("definition"); + $this->tpl->setVariable("PAGE_CONTENT", $output); + $this->tpl->parseCurrentBlock(); + } + //$this->tpl->setCurrentBlock("def_list"); + //$this->tpl->parseCurrentBlock(); + + $this->quickList(); + } + + + /** + * deletion confirmation screen + */ + public function confirmDefinitionDeletion() + { + $ilTabs = $this->tabs_gui; + + //$this->getTemplate(); + $this->displayLocator(); + $this->setTabs(); + $ilTabs->activateTab("definitions"); + + // content style + $this->tpl->setCurrentBlock("ContentStyle"); + $this->tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath($this->term_glossary->getStyleSheetId()) + ); + $this->tpl->parseCurrentBlock(); + + // syntax style + $this->tpl->setCurrentBlock("SyntaxStyle"); + $this->tpl->setVariable( + "LOCATION_SYNTAX_STYLESHEET", + ilObjStyleSheet::getSyntaxStylePath() + ); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setTitle( + $this->lng->txt("cont_term") . ": " . $this->term->getTerm() + ); + $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_glo.svg")); + + $this->tpl->addBlockfile("ADM_CONTENT", "def_list", "tpl.glossary_definition_delete.html", true); + ilUtil::sendQuestion($this->lng->txt("info_delete_sure")); + + $this->tpl->setVariable("TXT_TERM", $this->term->getTerm()); + + $definition = new ilGlossaryDefinition($_GET["def"]); + $page_gui = new ilGlossaryDefPageGUI($definition->getId()); + $page_gui->setTemplateOutput(false); + $page_gui->setStyleId($this->term_glossary->getStyleSheetId()); + $page_gui->setSourcecodeDownloadScript("ilias.php?baseClass=ilGlossaryPresentationGUI&ref_id=" . $_GET["ref_id"]); + $page_gui->setFileDownloadLink("ilias.php?baseClass=ilGlossaryPresentationGUI&ref_id=" . $_GET["ref_id"]); + $page_gui->setFullscreenLink("ilias.php?baseClass=ilGlossaryPresentationGUI&ref_id=" . $_GET["ref_id"]); + $output = $page_gui->preview(); + + $this->tpl->setCurrentBlock("definition"); + $this->tpl->setVariable("PAGE_CONTENT", $output); + $this->tpl->setVariable("TXT_CANCEL", $this->lng->txt("cancel")); + $this->tpl->setVariable( + "LINK_CANCEL", + $this->ctrl->getLinkTarget($this, "cancelDefinitionDeletion") + ); + $this->tpl->setVariable("TXT_CONFIRM", $this->lng->txt("confirm")); + $this->ctrl->setParameter($this, "def", $definition->getId()); + $this->tpl->setVariable( + "LINK_CONFIRM", + $this->ctrl->getLinkTarget($this, "deleteDefinition") + ); + $this->tpl->parseCurrentBlock(); + } + + public function cancelDefinitionDeletion() + { + $this->ctrl->redirect($this, "listDefinitions"); + } + + + public function deleteDefinition() + { + $definition = new ilGlossaryDefinition($_GET["def"]); + $definition->delete(); + $this->ctrl->redirect($this, "listDefinitions"); + } + + + /** + * move definition upwards + */ + public function moveUp() + { + $definition = new ilGlossaryDefinition($_GET["def"]); + $definition->moveUp(); + $this->ctrl->redirect($this, "listDefinitions"); + } + + + /** + * move definition downwards + */ + public function moveDown() + { + $definition = new ilGlossaryDefinition($_GET["def"]); + $definition->moveDown(); + $this->ctrl->redirect($this, "listDefinitions"); + } + + + /** + * add definition + */ + public function addDefinition() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameterByClass("ilobjglossarygui", "term_id", $this->term->getId()); + $ilCtrl->redirectByClass("ilobjglossarygui", "addDefinition"); + } + + /** + * cancel adding definition + */ + public function cancel() + { + $this->ctrl->redirect($this, "listDefinitions"); + } + + /** + * save definition + */ + public function saveDefinition() + { + $def = new ilGlossaryDefinition(); + $def->setTermId($_GET["term_id"]); + $def->setTitle(ilUtil::stripSlashes($_POST["title"]));#"content object ".$newObj->getId()); // set by meta_gui->save + $def->setDescription(ilUtil::stripSlashes($_POST["desc"])); // set by meta_gui->save + $def->create(); + + $this->ctrl->redirect($this, "listDefinitions"); + } + + /** + * output tabs + */ + public function setTabs() + { + $this->getTabs(); + } + + /** + * display locator + */ + public function displayLocator() + { + require_once("./Modules/Glossary/classes/class.ilGlossaryLocatorGUI.php"); + $gloss_loc = new ilGlossaryLocatorGUI(); + $gloss_loc->setTerm($this->term); + $gloss_loc->setGlossary($this->glossary); + //$gloss_loc->setDefinition($this->definition); + $gloss_loc->display(); + } + + + /** + * get tabs + */ + public function getTabs() + { + $lng = $this->lng; + $ilHelp = $this->help; + + + $ilHelp->setScreenIdComponent("glo_term"); + + //echo ":".$_GET["term_id"].":"; + if ($_GET["term_id"] != "") { + $this->tabs_gui->addTab( + "properties", + $lng->txt("term"), + $this->ctrl->getLinkTarget($this, "editTerm") + ); + + $this->tabs_gui->addTab( + "definitions", + $lng->txt("cont_definitions"), + $this->ctrl->getLinkTarget($this, "listDefinitions") + ); + + $this->tabs_gui->addTab( + "usage", + $lng->txt("cont_usage") . " (" . ilGlossaryTerm::getNumberOfUsages($_GET["term_id"]) . ")", + $this->ctrl->getLinkTarget($this, "listUsages") + ); + + include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php"; + $mdgui = new ilObjectMetaDataGUI( + $this->term_glossary, + "term", + $this->term->getId() + ); + $mdtab = $mdgui->getTab(); + if ($mdtab) { + $this->tabs_gui->addTab( + "meta_data", + $lng->txt("meta_data"), + $mdtab + ); + } + + $this->tabs_gui->addNonTabbedLink( + "presentation_view", + $this->lng->txt("glo_presentation_view"), + ILIAS_HTTP_PATH . + "/goto.php?target=" . + "git" . + "_" . $_GET["term_id"] . "_" . $_GET["ref_id"] . "&client_id=" . CLIENT_ID, + "_top" + ); + } + + // back to glossary + $this->tabs_gui->setBackTarget( + $this->lng->txt("glossary"), + $this->ctrl->getLinkTargetByClass("ilobjglossarygui", "listTerms") + ); + } + + /** + * redirect script + * + * @param string $a_target + */ + public static function _goto($a_target, $a_ref_id = "") + { + global $DIC; + + $rbacsystem = $DIC->rbac()->system(); + $ilErr = $DIC["ilErr"]; + $lng = $DIC->language(); + $ilAccess = $DIC->access(); + + $glo_id = ilGlossaryTerm::_lookGlossaryID($a_target);//::_lookupContObjID($a_target); + + // get all references + if ($a_ref_id > 0) { + $ref_ids = array($a_ref_id); + } else { + $ref_ids = ilObject::_getAllReferences($glo_id); + } + + // check read permissions + foreach ($ref_ids as $ref_id) { + // Permission check + if ($ilAccess->checkAccess("read", "", $ref_id)) { + $_GET["baseClass"] = "ilGlossaryPresentationGUI"; + $_GET["term_id"] = $a_target; + $_GET["ref_id"] = $ref_id; + $_GET["cmd"] = "listDefinitions"; + include_once("ilias.php"); + exit; + } + } + if ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) { + ilUtil::sendFailure(sprintf( + $lng->txt("msg_no_perm_read_item"), + ilObject::_lookupTitle($glo_id) + ), true); + ilObjectGUI::_gotoRepositoryRoot(); + } + + + $ilErr->raiseError($lng->txt("msg_no_perm_read_lm"), $ilErr->FATAL); + } + + /** + * List usage + */ + public function listUsages() + { + $ilTabs = $this->tabs_gui; + $tpl = $this->tpl; + + //$this->displayLocator(); + // $this->getTemplate(); + $this->displayLocator(); + $this->setTabs(); + $ilTabs->activateTab("usage"); + + $this->tpl->setTitle($this->lng->txt("cont_term") . ": " . $this->term->getTerm()); + $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_glo.svg")); + + include_once("./Modules/Glossary/classes/class.ilTermUsagesTableGUI.php"); + $tab = new ilTermUsagesTableGUI($this, "listUsages", $_GET["term_id"]); + + $tpl->setContent($tab->getHTML()); + + $this->quickList(); + } + + /** + * Set quick term list cmd into left navigation URL + */ + public function quickList() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + + //$tpl->setLeftNavUrl($ilCtrl->getLinkTarget($this, "showQuickList")); + + include_once("./Modules/Glossary/classes/class.ilTermQuickListTableGUI.php"); + $tab = new ilTermQuickListTableGUI($this, "editTerm"); + $tpl->setLeftNavContent($tab->getHTML()); + } } - -?> diff --git a/Modules/Glossary/classes/class.ilGlossaryTermPermission.php b/Modules/Glossary/classes/class.ilGlossaryTermPermission.php index 7a5e0db1eed55ac62318f21d7eead4b6e780eb2c..adf26d2d86ead74ec1bd96f7e9dce10da04f23f8 100644 --- a/Modules/Glossary/classes/class.ilGlossaryTermPermission.php +++ b/Modules/Glossary/classes/class.ilGlossaryTermPermission.php @@ -11,102 +11,93 @@ */ class ilGlossaryTermPermission { - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * @var int[] - */ - protected $glossary_id = array(); + /** + * @var int[] + */ + protected $glossary_id = array(); - /** - * @var array - */ - protected $permission = array(); + /** + * @var array + */ + protected $permission = array(); - /** - * @var ilLogger - */ - protected $log; + /** + * @var ilLogger + */ + protected $log; - /** - * ilGlossaryTermPermission constructor. - */ - private function __construct() - { - global $DIC; + /** + * ilGlossaryTermPermission constructor. + */ + private function __construct() + { + global $DIC; - $this->user = $DIC->user(); - $this->access = $DIC->access(); + $this->user = $DIC->user(); + $this->access = $DIC->access(); - $this->log = ilLoggerFactory::getLogger('glo'); - } + $this->log = ilLoggerFactory::getLogger('glo'); + } - /** - * Get instance - * @return ilGlossaryTermPermission - */ - static public function getInstance() - { - return new self(); - } - - /** - * Check permission - * - * @param string $a_perm - * @param int $a_term_id - * @return bool - */ - public function checkPermission($a_perm, $a_term_id) - { - $this->log->debug("check permission ".$a_perm." for ".$a_term_id."."); - $glo_id = $this->getGlossaryIdForTerm($a_term_id); - if (!isset($this->permission[$a_perm][$glo_id])) - { - $this->permission[$a_perm][$glo_id] = false; - $this->log->debug("...checking references"); - foreach (ilObject::_getAllReferences($glo_id) as $ref_id) - { - $this->log->debug("...".$ref_id); - if ($this->permission[$a_perm][$glo_id] == true) - { - continue; - } - if ($this->access->checkAccess($a_perm, "", $ref_id)) - { - $this->permission[$a_perm][$glo_id] = true; - } - } - } - $this->log->debug("...return ".((int) $this->permission[$a_perm][$glo_id])); - return $this->permission[$a_perm][$glo_id]; - } - - /** - * Get glossary for term - * - * @param int $a_term_id - * @return int - */ - protected function getGlossaryIdForTerm($a_term_id) - { - if (!isset($this->glossary_id[$a_term_id])) - { - include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - $this->glossary_id[$a_term_id] = ilGlossaryTerm::_lookGlossaryID($a_term_id); - } - return $this->glossary_id[$a_term_id]; - } + /** + * Get instance + * @return ilGlossaryTermPermission + */ + public static function getInstance() + { + return new self(); + } + /** + * Check permission + * + * @param string $a_perm + * @param int $a_term_id + * @return bool + */ + public function checkPermission($a_perm, $a_term_id) + { + $this->log->debug("check permission " . $a_perm . " for " . $a_term_id . "."); + $glo_id = $this->getGlossaryIdForTerm($a_term_id); + if (!isset($this->permission[$a_perm][$glo_id])) { + $this->permission[$a_perm][$glo_id] = false; + $this->log->debug("...checking references"); + foreach (ilObject::_getAllReferences($glo_id) as $ref_id) { + $this->log->debug("..." . $ref_id); + if ($this->permission[$a_perm][$glo_id] == true) { + continue; + } + if ($this->access->checkAccess($a_perm, "", $ref_id)) { + $this->permission[$a_perm][$glo_id] = true; + } + } + } + $this->log->debug("...return " . ((int) $this->permission[$a_perm][$glo_id])); + return $this->permission[$a_perm][$glo_id]; + } + /** + * Get glossary for term + * + * @param int $a_term_id + * @return int + */ + protected function getGlossaryIdForTerm($a_term_id) + { + if (!isset($this->glossary_id[$a_term_id])) { + include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + $this->glossary_id[$a_term_id] = ilGlossaryTerm::_lookGlossaryID($a_term_id); + } + return $this->glossary_id[$a_term_id]; + } } - -?> \ No newline at end of file diff --git a/Modules/Glossary/classes/class.ilGlossaryTermReferences.php b/Modules/Glossary/classes/class.ilGlossaryTermReferences.php index 7947d9c9bc760dba4539904791082f76cedc0139..9efe424395ac9e3bac4fd5f39f64c39beb078956 100644 --- a/Modules/Glossary/classes/class.ilGlossaryTermReferences.php +++ b/Modules/Glossary/classes/class.ilGlossaryTermReferences.php @@ -11,237 +11,228 @@ */ class ilGlossaryTermReferences { - /** - * @var int glossary id - */ - protected $glo_id; - - /** - * @var int[] (term ids) - */ - protected $terms = array(); - - /** - * @var ilDB - */ - protected $db; - - /** - * __construct - * - * @param int $a_glo_id glossary id - */ - function __construct($a_glo_id = 0) - { - global $DIC; - - $this->db = $DIC->database(); - - $this->setGlossaryId($a_glo_id); - if ($a_glo_id > 0) - { - $this->read(); - } - } - - /** - * Set glossary id - * - * @param int $a_val glossary id - */ - function setGlossaryId($a_val) - { - $this->glo_id = $a_val; - } - - /** - * Get glossary id - * - * @return int glossary id - */ - function getGlossaryId() - { - return $this->glo_id; - } - - /** - * Set terms - * - * @param int[] $a_val term ids - */ - function setTerms($a_val) - { - $this->terms = $a_val; - } - - /** - * Get terms - * - * @return int[] term ids - */ - function getTerms() - { - return $this->terms; - } - - /** - * Add term - * - * @param int term id - */ - function addTerm($a_term_id) - { - if (!in_array($a_term_id, $this->terms)) - { - $this->terms[] = $a_term_id; - } - } - - /** - * Delete term - * - * @param $a_term_id - */ - function deleteTerm($a_term_id) - { - foreach ($this->terms as $k => $v) - { - if ($v == $a_term_id) - { - unset($this->terms[$k]); - } - } - } - - - /** - * Read - */ - function read() - { - $set = $this->db->query("SELECT term_id FROM glo_term_reference ". - " WHERE glo_id = ".$this->db->quote($this->getGlossaryId(), "integer")); - while ($rec = $this->db->fetchAssoc($set)) - { - $this->addTerm($rec["term_id"]); - } - } - - /** - * Update - */ - function update() - { - $this->delete(); - foreach ($this->getTerms() as $t) - { - $this->db->replace("glo_term_reference", - array( - "glo_id" => array("integer", $this->getGlossaryId()), - "term_id" => array("integer", $t), - ), - array() - ); - } - } - - /** - * Delete references (of glossary) - */ - function delete() - { - $this->db->manipulate("DELETE FROM glo_term_reference WHERE ". - " glo_id = ".$this->db->quote($this->getGlossaryId(), "integer") - ); - } - - /** - * Delete all references of a term - * - * @param int $a_term_id term id - */ - static function deleteReferencesOfTerm($a_term_id) - { - global $DIC; - - $db = $DIC->database(); - $db->manipulate("DELETE FROM glo_term_reference WHERE ". - " term_id = ".$db->quote($a_term_id, "integer") - ); - } - - - /** - * Check if a glossary uses references - * - * @param int $a_glossary_id - * @return bool - */ - static function hasReferences($a_glossary_id) - { - global $DIC; - - $db = $DIC->database(); - $set = $db->query("SELECT * FROM glo_term_reference ". - " WHERE glo_id = ".$db->quote($a_glossary_id, "integer") - ); - if ($rec = $db->fetchAssoc($set)) - { - return true; - } - return false; - } - - /** - * Is a term referenced by one or multiple glossaries - * @param int|int[] $a_glo_id - * @param int $a_term_id - * @return bool - */ - static function isReferenced($a_glo_id, $a_term_id) - { - global $DIC; - - $db = $DIC->database(); - if (!is_array($a_glo_id)) - { - $a_glo_id = array($a_glo_id); - } - $set = $db->query($q = "SELECT * FROM glo_term_reference ". - " WHERE ".$db->in("glo_id", $a_glo_id, false, "integer"). - " AND term_id = ".$db->quote($a_term_id, "integer") - ); - if ($rec = $db->fetchAssoc($set)) - { - return true; - } - return false; - } - - /** - * Lookup references of a term - * - * @param int $a_term_id term id - * @return int[] glossary ids - */ - static function lookupReferencesOfTerm($a_term_id) - { - global $DIC; - - $db = $DIC->database(); - $set = $db->query($q = "SELECT DISTINCT glo_id FROM glo_term_reference ". - " WHERE term_id = ".$db->quote($a_term_id, "integer") - ); - $glos = array(); - while ($rec = $db->fetchAssoc($set)) - { - $glos[] = $rec["glo_id"]; - } - return $glos; - } - - - + /** + * @var int glossary id + */ + protected $glo_id; + + /** + * @var int[] (term ids) + */ + protected $terms = array(); + + /** + * @var ilDB + */ + protected $db; + + /** + * __construct + * + * @param int $a_glo_id glossary id + */ + public function __construct($a_glo_id = 0) + { + global $DIC; + + $this->db = $DIC->database(); + + $this->setGlossaryId($a_glo_id); + if ($a_glo_id > 0) { + $this->read(); + } + } + + /** + * Set glossary id + * + * @param int $a_val glossary id + */ + public function setGlossaryId($a_val) + { + $this->glo_id = $a_val; + } + + /** + * Get glossary id + * + * @return int glossary id + */ + public function getGlossaryId() + { + return $this->glo_id; + } + + /** + * Set terms + * + * @param int[] $a_val term ids + */ + public function setTerms($a_val) + { + $this->terms = $a_val; + } + + /** + * Get terms + * + * @return int[] term ids + */ + public function getTerms() + { + return $this->terms; + } + + /** + * Add term + * + * @param int term id + */ + public function addTerm($a_term_id) + { + if (!in_array($a_term_id, $this->terms)) { + $this->terms[] = $a_term_id; + } + } + + /** + * Delete term + * + * @param $a_term_id + */ + public function deleteTerm($a_term_id) + { + foreach ($this->terms as $k => $v) { + if ($v == $a_term_id) { + unset($this->terms[$k]); + } + } + } + + + /** + * Read + */ + public function read() + { + $set = $this->db->query("SELECT term_id FROM glo_term_reference " . + " WHERE glo_id = " . $this->db->quote($this->getGlossaryId(), "integer")); + while ($rec = $this->db->fetchAssoc($set)) { + $this->addTerm($rec["term_id"]); + } + } + + /** + * Update + */ + public function update() + { + $this->delete(); + foreach ($this->getTerms() as $t) { + $this->db->replace( + "glo_term_reference", + array( + "glo_id" => array("integer", $this->getGlossaryId()), + "term_id" => array("integer", $t), + ), + array() + ); + } + } + + /** + * Delete references (of glossary) + */ + public function delete() + { + $this->db->manipulate( + "DELETE FROM glo_term_reference WHERE " . + " glo_id = " . $this->db->quote($this->getGlossaryId(), "integer") + ); + } + + /** + * Delete all references of a term + * + * @param int $a_term_id term id + */ + public static function deleteReferencesOfTerm($a_term_id) + { + global $DIC; + + $db = $DIC->database(); + $db->manipulate( + "DELETE FROM glo_term_reference WHERE " . + " term_id = " . $db->quote($a_term_id, "integer") + ); + } + + + /** + * Check if a glossary uses references + * + * @param int $a_glossary_id + * @return bool + */ + public static function hasReferences($a_glossary_id) + { + global $DIC; + + $db = $DIC->database(); + $set = $db->query( + "SELECT * FROM glo_term_reference " . + " WHERE glo_id = " . $db->quote($a_glossary_id, "integer") + ); + if ($rec = $db->fetchAssoc($set)) { + return true; + } + return false; + } + + /** + * Is a term referenced by one or multiple glossaries + * @param int|int[] $a_glo_id + * @param int $a_term_id + * @return bool + */ + public static function isReferenced($a_glo_id, $a_term_id) + { + global $DIC; + + $db = $DIC->database(); + if (!is_array($a_glo_id)) { + $a_glo_id = array($a_glo_id); + } + $set = $db->query( + $q = "SELECT * FROM glo_term_reference " . + " WHERE " . $db->in("glo_id", $a_glo_id, false, "integer") . + " AND term_id = " . $db->quote($a_term_id, "integer") + ); + if ($rec = $db->fetchAssoc($set)) { + return true; + } + return false; + } + + /** + * Lookup references of a term + * + * @param int $a_term_id term id + * @return int[] glossary ids + */ + public static function lookupReferencesOfTerm($a_term_id) + { + global $DIC; + + $db = $DIC->database(); + $set = $db->query( + $q = "SELECT DISTINCT glo_id FROM glo_term_reference " . + " WHERE term_id = " . $db->quote($a_term_id, "integer") + ); + $glos = array(); + while ($rec = $db->fetchAssoc($set)) { + $glos[] = $rec["glo_id"]; + } + return $glos; + } } - -?> \ No newline at end of file diff --git a/Modules/Glossary/classes/class.ilObjGlossary.php b/Modules/Glossary/classes/class.ilObjGlossary.php index 8158e5a397382cc8503037f2ed0bb2bfa37e0cba..617bc63ef678ce3423e223caef84c2c597cf9d33 100755 --- a/Modules/Glossary/classes/class.ilObjGlossary.php +++ b/Modules/Glossary/classes/class.ilObjGlossary.php @@ -19,1427 +19,1372 @@ include_once("./Services/AdvancedMetaData/interfaces/interface.ilAdvancedMetaDat */ class ilObjGlossary extends ilObject implements ilAdvancedMetaDataSubItems { - /** - * @var ilTemplate - */ - protected $tpl; - - - /** - * @var ilDB - */ - protected $db; - - /** - * @var array - */ - var $auto_glossaries = array(); - - /** - * @var ilObjUser - */ - protected $user; - - /** - * Constructor - * @access public - */ - function __construct($a_id = 0,$a_call_by_reference = true) - { - global $DIC; - $this->error = $DIC["ilErr"]; - $this->tpl = $DIC["tpl"]; - - $this->db = $DIC->database(); - $this->user = $DIC->user(); - $this->type = "glo"; - parent::__construct($a_id,$a_call_by_reference); - } - - /** - * create glossary object - */ - function create($a_upload = false) - { - parent::create(); - - // meta data will be created by - // import parser - if (!$a_upload) - { - $this->createMetaData(); - } - $this->db->insert('glossary', - array( - 'id' => array('integer', $this->getId()), - 'is_online' => array('text', 'n'), - 'virtual' => array('text', $this->getVirtualMode()), - 'pres_mode' => array('text', 'table'), - 'snippet_length' => array('integer', 200) - ) - ); - - $this->setPresentationMode("table"); - $this->setSnippetLength(200); - - $this->updateAutoGlossaries(); - - if (((int) $this->getStyleSheetId()) > 0) - { - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - ilObjStyleSheet::writeStyleUsage($this->getId(), $this->getStyleSheetId()); - } - - } - - /** - * read data of content object - */ - function read() - { - parent::read(); -# echo "Glossary
\n"; - - $q = "SELECT * FROM glossary WHERE id = ". - $this->db->quote($this->getId(), "integer"); - $gl_set = $this->db->query($q); - $gl_rec = $this->db->fetchAssoc($gl_set); - $this->setOnline(ilUtil::yn2tf($gl_rec["is_online"])); - $this->setVirtualMode($gl_rec["virtual"]); - $this->setPublicExportFile("xml", $gl_rec["public_xml_file"]); - $this->setPublicExportFile("html", $gl_rec["public_html_file"]); - $this->setActiveGlossaryMenu(ilUtil::yn2tf($gl_rec["glo_menu_active"])); - $this->setActiveDownloads(ilUtil::yn2tf($gl_rec["downloads_active"])); - $this->setPresentationMode($gl_rec["pres_mode"]); - $this->setSnippetLength($gl_rec["snippet_length"]); - $this->setShowTaxonomy($gl_rec["show_tax"]); - - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $this->setStyleSheetId((int) ilObjStyleSheet::lookupObjectStyle($this->getId())); - - // read auto glossaries - $set = $this->db->query("SELECT * FROM glo_glossaries ". - " WHERE id = ".$this->db->quote($this->getId(), "integer") - ); - $glos = array(); - while ($rec = $this->db->fetchAssoc($set)) - { - $glos[] = $rec["glo_id"]; - } - $this->setAutoGlossaries($glos); - - - } - - /** - * get description of glossary object - * - * @return string description - */ - function getDescription() - { - return parent::getDescription(); - } - - /** - * set description of glossary object - */ - function setDescription($a_description) - { - parent::setDescription($a_description); - } - - - /** - * set glossary type (virtual: fixed/level/subtree, normal:none) - */ - function setVirtualMode($a_mode) - { - switch ($a_mode) - { - case "level": - case "subtree": - // case "fixed": - $this->virtual_mode = $a_mode; - $this->virtual = true; - break; - - default: - $this->virtual_mode = "none"; - $this->virtual = false; - break; - } - } - - /** - * get glossary type (normal or virtual) - */ - function getVirtualMode() - { - return $this->virtual_mode; - } - - /** - * returns true if glossary type is virtual (any mode) - */ - function isVirtual() - { - return $this->virtual; - } - - /** - * get title of glossary object - * - * @return string title - */ - function getTitle() - { - return parent::getTitle(); - } - - /** - * set title of glossary object - */ - function setTitle($a_title) - { - parent::setTitle($a_title); -// $this->meta_data->setTitle($a_title); - } - - /** - * Set presentation mode - * - * @param string presentation mode - */ - function setPresentationMode($a_val) - { - $this->pres_mode = $a_val; - } - - /** - * Get presentation mode - * - * @return string presentation mode - */ - function getPresentationMode() - { - return $this->pres_mode; - } - - /** - * Set snippet length - * - * @param int snippet length - */ - function setSnippetLength($a_val) - { - $this->snippet_length = $a_val; - } - - /** - * Get snippet length - * - * @return int snippet length - */ - function getSnippetLength() - { - return ($this->snippet_length > 0) - ? $this->snippet_length - : null; - } - - function setOnline($a_online) - { - $this->online = $a_online; - } - - function getOnline() - { - return $this->online; - } - - /** - * check wether content object is online - */ - static function _lookupOnline($a_id) - { - global $DIC; - - $db = $DIC->database(); - - $q = "SELECT is_online FROM glossary WHERE id = ". - $db->quote($a_id, "integer"); - $lm_set = $db->query($q); - $lm_rec = $db->fetchAssoc($lm_set); - - return ilUtil::yn2tf($lm_rec["is_online"]); - } - - /** - * Lookup glossary property - * - * @param int glossary id - * @param string property - */ - static protected function lookup($a_id, $a_property) - { - global $DIC; - - $db = $DIC->database(); - - $set = $db->query("SELECT $a_property FROM glossary WHERE id = ". - $db->quote($a_id, "integer")); - $rec = $db->fetchAssoc($set); - - return $rec[$a_property]; - } - - /** - * Lookup snippet length - * - * @param int glossary id - * @return int snippet length - */ - static function lookupSnippetLength($a_id) - { - return ilObjGlossary::lookup($a_id, "snippet_length"); - } - - - function setActiveGlossaryMenu($a_act_glo_menu) - { - $this->glo_menu_active = $a_act_glo_menu; - } - - function isActiveGlossaryMenu() - { - return $this->glo_menu_active; - } - - function setActiveDownloads($a_down) - { - $this->downloads_active = $a_down; - } - - function isActiveDownloads() - { - return $this->downloads_active; - } - - /** - * Get ID of assigned style sheet object - */ - function getStyleSheetId() - { - return $this->style_id; - } - - /** - * Set ID of assigned style sheet object - */ - function setStyleSheetId($a_style_id) - { - $this->style_id = $a_style_id; - } - - - /** - * Set show taxonomy - * - * @param bool $a_val show taxonomy - */ - function setShowTaxonomy($a_val) - { - $this->show_tax = $a_val; - } - - /** - * Get show taxonomy - * - * @return bool show taxonomy - */ - function getShowTaxonomy() - { - return $this->show_tax; - } - - /** - * Set auto glossaries - * - * @param array $a_val int - */ - function setAutoGlossaries($a_val) - { - $this->auto_glossaries = array(); - if (is_array($a_val)) - { - foreach ($a_val as $v) - { - $v = (int) $v; - if ($v > 0 && ilObject::_lookupType($v) == "glo" && - !in_array($v, $this->auto_glossaries)) - { - $this->auto_glossaries[] = $v; - } - } - } - } - - /** - * Get auto glossaries - * - * @return array int - */ - function getAutoGlossaries() - { - return $this->auto_glossaries; - } - - /** - * Remove auto glossary - * - * @param - * @return - */ - function removeAutoGlossary($a_glo_id) - { - $glo_ids = array(); - foreach($this->getAutoGlossaries() as $g) - { - if ($g != $a_glo_id) - { - $glo_ids[] = $g; - } - } - $this->setAutoGlossaries($glo_ids); - } - - /** - * Update object - */ - function update() - { - $this->updateMetaData(); - - $this->db->update('glossary', - array( - 'is_online' => array('text', ilUtil::tf2yn($this->getOnline())), - 'virtual' => array('text', $this->getVirtualMode()), - 'public_xml_file' => array('text', $this->getPublicExportFile("xml")), - 'public_html_file' => array('text', $this->getPublicExportFile("html")), - 'glo_menu_active' => array('text', ilUtil::tf2yn($this->isActiveGlossaryMenu())), - 'downloads_active' => array('text', ilUtil::tf2yn($this->isActiveDownloads())), - 'pres_mode' => array('text', $this->getPresentationMode()), - 'show_tax' => array('integer', $this->getShowTaxonomy()), - 'snippet_length' => array('integer', $this->getSnippetLength()) - ), - array( - 'id' => array('integer', $this->getId()) - ) - ); - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - ilObjStyleSheet::writeStyleUsage($this->getId(), $this->getStyleSheetId()); - - $this->updateAutoGlossaries(); - parent::update(); - } - - - /** - * Update auto glossaries - * - * @param - * @return - */ - function updateAutoGlossaries() - { - // update auto glossaries - $this->db->manipulate("DELETE FROM glo_glossaries WHERE ". - " id = ".$this->db->quote($this->getId(), "integer") - ); - foreach ($this->getAutoGlossaries() as $glo_id) - { - $this->db->insert('glo_glossaries', - array( - 'id' => array('integer', $this->getId()), - 'glo_id' => array('integer', $glo_id) - ) - ); - } - } - - /** - * Lookup auto glossaries - * - * @param - * @return - */ - static function lookupAutoGlossaries($a_id) - { - global $DIC; - - $db = $DIC->database(); - - // read auto glossaries - $set = $db->query("SELECT * FROM glo_glossaries ". - " WHERE id = ".$db->quote($a_id, "integer") - ); - $glos = array(); - while ($rec = $db->fetchAssoc($set)) - { - $glos[] = $rec["glo_id"]; - } - return $glos; - } - - /** - * Get term list - */ - function getTermList($searchterm = "", $a_letter = "", $a_def = "", $a_tax_node = 0, $a_include_offline_childs = false, - $a_add_amet_fields = false, array $a_amet_filter = null, $a_omit_virtual = false, $a_include_references = false) - { - if ($a_omit_virtual) - { - $glo_ref_ids[] = $this->getRefId(); - } - else - { - $glo_ref_ids = $this->getAllGlossaryIds($a_include_offline_childs, true); - } - $list = ilGlossaryTerm::getTermList($glo_ref_ids, $searchterm, $a_letter, $a_def, $a_tax_node, - $a_add_amet_fields, $a_amet_filter, $a_include_references); - return $list; - } - - /** - * Get term list - */ - function getFirstLetters($a_tax_node = 0) - { - $glo_ids = $this->getAllGlossaryIds(); - $first_letters = ilGlossaryTerm::getFirstLetters($glo_ids, $a_tax_node); - return $first_letters; - } - - /** - * Get all glossary ids - * - * @param - * @return - */ - function getAllGlossaryIds($a_include_offline_childs = false, $ids_are_ref_ids = false) - { - global $DIC; - - $tree = $DIC->repositoryTree(); - - if ($this->isVirtual()) - { - $glo_ids = array(); - - $virtual_mode = $this->getRefId() ? $this->getVirtualMode() : ''; - switch ($virtual_mode) - { - case "level": - $glo_arr = $tree->getChildsByType($tree->getParentId($this->getRefId()),"glo"); - foreach ($glo_arr as $glo) - { - { - if ($ids_are_ref_ids) - { - $glo_ids[] = $glo['child']; - } - else - { - $glo_ids[] = $glo['obj_id']; - } - } - } - break; - - case "subtree": - $subtree_nodes = $tree->getSubTree($tree->getNodeData($tree->getParentId($this->getRefId()))); - - foreach ($subtree_nodes as $node) - { - if ($node['type'] == 'glo') - { - if ($ids_are_ref_ids) - { - $glo_ids[] = $node['child']; - } - else - { - $glo_ids[] = $node['obj_id']; - } - } - } - break; - } - if (!$a_include_offline_childs) - { - $glo_ids = ilObjGlossary::removeOfflineGlossaries($glo_ids, $ids_are_ref_ids); - } - // always show entries of current glossary (if no permission is given, user will not come to the presentation screen) - // see bug #14477 - if ($ids_are_ref_ids) - { - if (!in_array($this->getRefId(), $glo_ids)) - { - $glo_ids[] = $this->getRefId(); - } - } - else - { - if (!in_array($this->getId(), $glo_ids)) - { - $glo_ids[] = $this->getId(); - } - } - } - else - { - if ($ids_are_ref_ids) - { - $glo_ids = $this->getRefId(); - } - else - { - $glo_ids = $this->getId(); - } - } - - return $glo_ids; - } - - /** - * creates data directory for import files - * (data_dir/glo_data/glo_/import, depending on data - * directory that is set in ILIAS setup/ini) - */ - function createImportDirectory() - { - $ilErr = $this->error; - - $glo_data_dir = ilUtil::getDataDir()."/glo_data"; - ilUtil::makeDir($glo_data_dir); - if(!is_writable($glo_data_dir)) - { - $ilErr->raiseError("Glossary Data Directory (".$glo_data_dir - .") not writeable.",$ilErr->error_obj->FATAL); - } - - // create glossary directory (data_dir/glo_data/glo_) - $glo_dir = $glo_data_dir."/glo_".$this->getId(); - ilUtil::makeDir($glo_dir); - if(!@is_dir($glo_dir)) - { - $ilErr->raiseError("Creation of Glossary Directory failed.",$ilErr->FATAL); - } - // create Import subdirectory (data_dir/glo_data/glo_/import) - $import_dir = $glo_dir."/import"; - ilUtil::makeDir($import_dir); - if(!@is_dir($import_dir)) - { - $ilErr->raiseError("Creation of Export Directory failed.",$ilErr->FATAL); - } - } - - /** - * get import directory of glossary - */ - function getImportDirectory() - { - $export_dir = ilUtil::getDataDir()."/glo_data"."/glo_".$this->getId()."/import"; - - return $export_dir; - } - - /** - * Creates export directory - */ - function createExportDirectory($a_type = "xml") - { - include_once("./Services/Export/classes/class.ilExport.php"); - return ilExport::_createExportDirectory($this->getId(), $a_type, $this->getType()); - } - - /** - * Get export directory of glossary - */ - function getExportDirectory($a_type = "xml") - { - include_once("./Services/Export/classes/class.ilExport.php"); - return ilExport::_getExportDirectory($this->getId(), $a_type, $this->getType()); - } - - /** - * Get export files - */ - function getExportFiles() - { - include_once("./Services/Export/classes/class.ilExport.php"); - return ilExport::_getExportFiles($this->getId(), array("xml", "html"), $this->getType()); - } - - /** - * specify public export file for type - * - * @param string $a_type type ("xml" / "html") - * @param string $a_file file name - */ - function setPublicExportFile($a_type, $a_file) - { - $this->public_export_file[$a_type] = $a_file; - } - - /** - * get public export file - * - * @param string $a_type type ("xml" / "html") - * - * @return string $a_file file name - */ - function getPublicExportFile($a_type) - { - return $this->public_export_file[$a_type]; - } - - /** - * export html package - */ - function exportHTML($a_target_dir, $log) - { - $tpl = $this->tpl; - - // initialize temporary target directory - ilUtil::delDir($a_target_dir); - ilUtil::makeDir($a_target_dir); - + /** + * @var ilTemplate + */ + protected $tpl; + + + /** + * @var ilDB + */ + protected $db; + + /** + * @var array + */ + public $auto_glossaries = array(); + + /** + * @var ilObjUser + */ + protected $user; + + /** + * Constructor + * @access public + */ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + global $DIC; + $this->error = $DIC["ilErr"]; + $this->tpl = $DIC["tpl"]; + + $this->db = $DIC->database(); + $this->user = $DIC->user(); + $this->type = "glo"; + parent::__construct($a_id, $a_call_by_reference); + } + + /** + * create glossary object + */ + public function create($a_upload = false) + { + parent::create(); + + // meta data will be created by + // import parser + if (!$a_upload) { + $this->createMetaData(); + } + $this->db->insert( + 'glossary', + array( + 'id' => array('integer', $this->getId()), + 'is_online' => array('text', 'n'), + 'virtual' => array('text', $this->getVirtualMode()), + 'pres_mode' => array('text', 'table'), + 'snippet_length' => array('integer', 200) + ) + ); + + $this->setPresentationMode("table"); + $this->setSnippetLength(200); + + $this->updateAutoGlossaries(); + + if (((int) $this->getStyleSheetId()) > 0) { + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + ilObjStyleSheet::writeStyleUsage($this->getId(), $this->getStyleSheetId()); + } + } + + /** + * read data of content object + */ + public function read() + { + parent::read(); + # echo "Glossary
\n"; + + $q = "SELECT * FROM glossary WHERE id = " . + $this->db->quote($this->getId(), "integer"); + $gl_set = $this->db->query($q); + $gl_rec = $this->db->fetchAssoc($gl_set); + $this->setOnline(ilUtil::yn2tf($gl_rec["is_online"])); + $this->setVirtualMode($gl_rec["virtual"]); + $this->setPublicExportFile("xml", $gl_rec["public_xml_file"]); + $this->setPublicExportFile("html", $gl_rec["public_html_file"]); + $this->setActiveGlossaryMenu(ilUtil::yn2tf($gl_rec["glo_menu_active"])); + $this->setActiveDownloads(ilUtil::yn2tf($gl_rec["downloads_active"])); + $this->setPresentationMode($gl_rec["pres_mode"]); + $this->setSnippetLength($gl_rec["snippet_length"]); + $this->setShowTaxonomy($gl_rec["show_tax"]); + + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $this->setStyleSheetId((int) ilObjStyleSheet::lookupObjectStyle($this->getId())); + + // read auto glossaries + $set = $this->db->query( + "SELECT * FROM glo_glossaries " . + " WHERE id = " . $this->db->quote($this->getId(), "integer") + ); + $glos = array(); + while ($rec = $this->db->fetchAssoc($set)) { + $glos[] = $rec["glo_id"]; + } + $this->setAutoGlossaries($glos); + } + + /** + * get description of glossary object + * + * @return string description + */ + public function getDescription() + { + return parent::getDescription(); + } + + /** + * set description of glossary object + */ + public function setDescription($a_description) + { + parent::setDescription($a_description); + } + + + /** + * set glossary type (virtual: fixed/level/subtree, normal:none) + */ + public function setVirtualMode($a_mode) + { + switch ($a_mode) { + case "level": + case "subtree": + // case "fixed": + $this->virtual_mode = $a_mode; + $this->virtual = true; + break; + + default: + $this->virtual_mode = "none"; + $this->virtual = false; + break; + } + } + + /** + * get glossary type (normal or virtual) + */ + public function getVirtualMode() + { + return $this->virtual_mode; + } + + /** + * returns true if glossary type is virtual (any mode) + */ + public function isVirtual() + { + return $this->virtual; + } + + /** + * get title of glossary object + * + * @return string title + */ + public function getTitle() + { + return parent::getTitle(); + } + + /** + * set title of glossary object + */ + public function setTitle($a_title) + { + parent::setTitle($a_title); + // $this->meta_data->setTitle($a_title); + } + + /** + * Set presentation mode + * + * @param string presentation mode + */ + public function setPresentationMode($a_val) + { + $this->pres_mode = $a_val; + } + + /** + * Get presentation mode + * + * @return string presentation mode + */ + public function getPresentationMode() + { + return $this->pres_mode; + } + + /** + * Set snippet length + * + * @param int snippet length + */ + public function setSnippetLength($a_val) + { + $this->snippet_length = $a_val; + } + + /** + * Get snippet length + * + * @return int snippet length + */ + public function getSnippetLength() + { + return ($this->snippet_length > 0) + ? $this->snippet_length + : null; + } + + public function setOnline($a_online) + { + $this->online = $a_online; + } + + public function getOnline() + { + return $this->online; + } + + /** + * check wether content object is online + */ + public static function _lookupOnline($a_id) + { + global $DIC; + + $db = $DIC->database(); + + $q = "SELECT is_online FROM glossary WHERE id = " . + $db->quote($a_id, "integer"); + $lm_set = $db->query($q); + $lm_rec = $db->fetchAssoc($lm_set); + + return ilUtil::yn2tf($lm_rec["is_online"]); + } + + /** + * Lookup glossary property + * + * @param int glossary id + * @param string property + */ + protected static function lookup($a_id, $a_property) + { + global $DIC; + + $db = $DIC->database(); + + $set = $db->query("SELECT $a_property FROM glossary WHERE id = " . + $db->quote($a_id, "integer")); + $rec = $db->fetchAssoc($set); + + return $rec[$a_property]; + } + + /** + * Lookup snippet length + * + * @param int glossary id + * @return int snippet length + */ + public static function lookupSnippetLength($a_id) + { + return ilObjGlossary::lookup($a_id, "snippet_length"); + } + + + public function setActiveGlossaryMenu($a_act_glo_menu) + { + $this->glo_menu_active = $a_act_glo_menu; + } + + public function isActiveGlossaryMenu() + { + return $this->glo_menu_active; + } + + public function setActiveDownloads($a_down) + { + $this->downloads_active = $a_down; + } + + public function isActiveDownloads() + { + return $this->downloads_active; + } + + /** + * Get ID of assigned style sheet object + */ + public function getStyleSheetId() + { + return $this->style_id; + } + + /** + * Set ID of assigned style sheet object + */ + public function setStyleSheetId($a_style_id) + { + $this->style_id = $a_style_id; + } + + + /** + * Set show taxonomy + * + * @param bool $a_val show taxonomy + */ + public function setShowTaxonomy($a_val) + { + $this->show_tax = $a_val; + } + + /** + * Get show taxonomy + * + * @return bool show taxonomy + */ + public function getShowTaxonomy() + { + return $this->show_tax; + } + + /** + * Set auto glossaries + * + * @param array $a_val int + */ + public function setAutoGlossaries($a_val) + { + $this->auto_glossaries = array(); + if (is_array($a_val)) { + foreach ($a_val as $v) { + $v = (int) $v; + if ($v > 0 && ilObject::_lookupType($v) == "glo" && + !in_array($v, $this->auto_glossaries)) { + $this->auto_glossaries[] = $v; + } + } + } + } + + /** + * Get auto glossaries + * + * @return array int + */ + public function getAutoGlossaries() + { + return $this->auto_glossaries; + } + + /** + * Remove auto glossary + * + * @param + * @return + */ + public function removeAutoGlossary($a_glo_id) + { + $glo_ids = array(); + foreach ($this->getAutoGlossaries() as $g) { + if ($g != $a_glo_id) { + $glo_ids[] = $g; + } + } + $this->setAutoGlossaries($glo_ids); + } + + /** + * Update object + */ + public function update() + { + $this->updateMetaData(); + + $this->db->update( + 'glossary', + array( + 'is_online' => array('text', ilUtil::tf2yn($this->getOnline())), + 'virtual' => array('text', $this->getVirtualMode()), + 'public_xml_file' => array('text', $this->getPublicExportFile("xml")), + 'public_html_file' => array('text', $this->getPublicExportFile("html")), + 'glo_menu_active' => array('text', ilUtil::tf2yn($this->isActiveGlossaryMenu())), + 'downloads_active' => array('text', ilUtil::tf2yn($this->isActiveDownloads())), + 'pres_mode' => array('text', $this->getPresentationMode()), + 'show_tax' => array('integer', $this->getShowTaxonomy()), + 'snippet_length' => array('integer', $this->getSnippetLength()) + ), + array( + 'id' => array('integer', $this->getId()) + ) + ); + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + ilObjStyleSheet::writeStyleUsage($this->getId(), $this->getStyleSheetId()); + + $this->updateAutoGlossaries(); + parent::update(); + } + + + /** + * Update auto glossaries + * + * @param + * @return + */ + public function updateAutoGlossaries() + { + // update auto glossaries + $this->db->manipulate( + "DELETE FROM glo_glossaries WHERE " . + " id = " . $this->db->quote($this->getId(), "integer") + ); + foreach ($this->getAutoGlossaries() as $glo_id) { + $this->db->insert( + 'glo_glossaries', + array( + 'id' => array('integer', $this->getId()), + 'glo_id' => array('integer', $glo_id) + ) + ); + } + } + + /** + * Lookup auto glossaries + * + * @param + * @return + */ + public static function lookupAutoGlossaries($a_id) + { + global $DIC; + + $db = $DIC->database(); + + // read auto glossaries + $set = $db->query( + "SELECT * FROM glo_glossaries " . + " WHERE id = " . $db->quote($a_id, "integer") + ); + $glos = array(); + while ($rec = $db->fetchAssoc($set)) { + $glos[] = $rec["glo_id"]; + } + return $glos; + } + + /** + * Get term list + */ + public function getTermList( + $searchterm = "", + $a_letter = "", + $a_def = "", + $a_tax_node = 0, + $a_include_offline_childs = false, + $a_add_amet_fields = false, + array $a_amet_filter = null, + $a_omit_virtual = false, + $a_include_references = false + ) { + if ($a_omit_virtual) { + $glo_ref_ids[] = $this->getRefId(); + } else { + $glo_ref_ids = $this->getAllGlossaryIds($a_include_offline_childs, true); + } + $list = ilGlossaryTerm::getTermList( + $glo_ref_ids, + $searchterm, + $a_letter, + $a_def, + $a_tax_node, + $a_add_amet_fields, + $a_amet_filter, + $a_include_references + ); + return $list; + } + + /** + * Get term list + */ + public function getFirstLetters($a_tax_node = 0) + { + $glo_ids = $this->getAllGlossaryIds(); + $first_letters = ilGlossaryTerm::getFirstLetters($glo_ids, $a_tax_node); + return $first_letters; + } + + /** + * Get all glossary ids + * + * @param + * @return + */ + public function getAllGlossaryIds($a_include_offline_childs = false, $ids_are_ref_ids = false) + { + global $DIC; + + $tree = $DIC->repositoryTree(); + + if ($this->isVirtual()) { + $glo_ids = array(); + + $virtual_mode = $this->getRefId() ? $this->getVirtualMode() : ''; + switch ($virtual_mode) { + case "level": + $glo_arr = $tree->getChildsByType($tree->getParentId($this->getRefId()), "glo"); + foreach ($glo_arr as $glo) { + { + if ($ids_are_ref_ids) { + $glo_ids[] = $glo['child']; + } else { + $glo_ids[] = $glo['obj_id']; + } + } + } + break; + + case "subtree": + $subtree_nodes = $tree->getSubTree($tree->getNodeData($tree->getParentId($this->getRefId()))); + + foreach ($subtree_nodes as $node) { + if ($node['type'] == 'glo') { + if ($ids_are_ref_ids) { + $glo_ids[] = $node['child']; + } else { + $glo_ids[] = $node['obj_id']; + } + } + } + break; + } + if (!$a_include_offline_childs) { + $glo_ids = ilObjGlossary::removeOfflineGlossaries($glo_ids, $ids_are_ref_ids); + } + // always show entries of current glossary (if no permission is given, user will not come to the presentation screen) + // see bug #14477 + if ($ids_are_ref_ids) { + if (!in_array($this->getRefId(), $glo_ids)) { + $glo_ids[] = $this->getRefId(); + } + } else { + if (!in_array($this->getId(), $glo_ids)) { + $glo_ids[] = $this->getId(); + } + } + } else { + if ($ids_are_ref_ids) { + $glo_ids = $this->getRefId(); + } else { + $glo_ids = $this->getId(); + } + } + + return $glo_ids; + } + + /** + * creates data directory for import files + * (data_dir/glo_data/glo_/import, depending on data + * directory that is set in ILIAS setup/ini) + */ + public function createImportDirectory() + { + $ilErr = $this->error; + + $glo_data_dir = ilUtil::getDataDir() . "/glo_data"; + ilUtil::makeDir($glo_data_dir); + if (!is_writable($glo_data_dir)) { + $ilErr->raiseError("Glossary Data Directory (" . $glo_data_dir + . ") not writeable.", $ilErr->error_obj->FATAL); + } + + // create glossary directory (data_dir/glo_data/glo_) + $glo_dir = $glo_data_dir . "/glo_" . $this->getId(); + ilUtil::makeDir($glo_dir); + if (!@is_dir($glo_dir)) { + $ilErr->raiseError("Creation of Glossary Directory failed.", $ilErr->FATAL); + } + // create Import subdirectory (data_dir/glo_data/glo_/import) + $import_dir = $glo_dir . "/import"; + ilUtil::makeDir($import_dir); + if (!@is_dir($import_dir)) { + $ilErr->raiseError("Creation of Export Directory failed.", $ilErr->FATAL); + } + } + + /** + * get import directory of glossary + */ + public function getImportDirectory() + { + $export_dir = ilUtil::getDataDir() . "/glo_data" . "/glo_" . $this->getId() . "/import"; + + return $export_dir; + } + + /** + * Creates export directory + */ + public function createExportDirectory($a_type = "xml") + { + include_once("./Services/Export/classes/class.ilExport.php"); + return ilExport::_createExportDirectory($this->getId(), $a_type, $this->getType()); + } + + /** + * Get export directory of glossary + */ + public function getExportDirectory($a_type = "xml") + { + include_once("./Services/Export/classes/class.ilExport.php"); + return ilExport::_getExportDirectory($this->getId(), $a_type, $this->getType()); + } + + /** + * Get export files + */ + public function getExportFiles() + { + include_once("./Services/Export/classes/class.ilExport.php"); + return ilExport::_getExportFiles($this->getId(), array("xml", "html"), $this->getType()); + } + + /** + * specify public export file for type + * + * @param string $a_type type ("xml" / "html") + * @param string $a_file file name + */ + public function setPublicExportFile($a_type, $a_file) + { + $this->public_export_file[$a_type] = $a_file; + } + + /** + * get public export file + * + * @param string $a_type type ("xml" / "html") + * + * @return string $a_file file name + */ + public function getPublicExportFile($a_type) + { + return $this->public_export_file[$a_type]; + } + + /** + * export html package + */ + public function exportHTML($a_target_dir, $log) + { + $tpl = $this->tpl; + + // initialize temporary target directory + ilUtil::delDir($a_target_dir); + ilUtil::makeDir($a_target_dir); + // init mathjax rendering for export - include_once './Services/MathJax/classes/class.ilMathJax.php'; - ilMathJax::getInstance()->init(ilMathJax::PURPOSE_EXPORT); - - include_once("./Services/COPage/classes/class.ilCOPageHTMLExport.php"); - $this->co_page_html_export = new ilCOPageHTMLExport($a_target_dir); - $this->co_page_html_export->createDirectories(); - - // export system style sheet - $location_stylesheet = ilUtil::getStyleSheetLocation("filesystem"); - $style_name = $this->user->prefs["style"].".css"; - copy($location_stylesheet, $a_target_dir."/".$style_name); - $location_stylesheet = ilUtil::getStyleSheetLocation(); - - if ($this->getStyleSheetId() < 1) - { - $cont_stylesheet = "Services/COPage/css/content.css"; - copy($cont_stylesheet, $a_target_dir."/content.css"); - } - else - { - $content_style_img_dir = $a_target_dir."/images"; - ilUtil::makeDir($content_style_img_dir); - $style = new ilObjStyleSheet($this->getStyleSheetId()); - $style->writeCSSFile($a_target_dir."/content.css", "images"); - $style->copyImagesToDir($content_style_img_dir); - } - - // export syntax highlighting style - $syn_stylesheet = ilObjStyleSheet::getSyntaxStylePath(); - copy($syn_stylesheet, $a_target_dir."/syntaxhighlight.css"); - - // get glossary presentation gui class - include_once("./Modules/Glossary/classes/class.ilGlossaryPresentationGUI.php"); - $_GET["cmd"] = "nop"; - $glo_gui = new ilGlossaryPresentationGUI(); - $glo_gui->setOfflineMode(true); - $glo_gui->setOfflineDirectory($a_target_dir); - - // could be implemented in the future if other export - // formats are supported (e.g. scorm) - //$glo_gui->setExportFormat($a_export_format); - - // export terms - $this->exportHTMLGlossaryTerms($glo_gui, $a_target_dir); - - // export all media objects - foreach ($this->offline_mobs as $mob) - { - $this->exportHTMLMOB($a_target_dir, $glo_gui, $mob, "_blank"); - } - $_GET["obj_type"] = "MediaObject"; - $_GET["obj_id"] = $a_mob_id; - $_GET["cmd"] = ""; - - // export all file objects - foreach ($this->offline_files as $file) - { - $this->exportHTMLFile($a_target_dir, $file); - } - - // export images - $image_dir = $a_target_dir."/images"; - ilUtil::makeDir($image_dir); - ilUtil::makeDir($image_dir."/browser"); - copy(ilUtil::getImagePath("enlarge.svg", false, "filesystem"), - $image_dir."/enlarge.svg"); - copy(ilUtil::getImagePath("browser/blank.png", false, "filesystem"), - $image_dir."/browser/plus.png"); - copy(ilUtil::getImagePath("browser/blank.png", false, "filesystem"), - $image_dir."/browser/minus.png"); - copy(ilUtil::getImagePath("browser/blank.png", false, "filesystem"), - $image_dir."/browser/blank.png"); - copy(ilUtil::getImagePath("icon_st.svg", false, "filesystem"), - $image_dir."/icon_st.svg"); - copy(ilUtil::getImagePath("icon_pg.svg", false, "filesystem"), - $image_dir."/icon_pg.svg"); - copy(ilUtil::getImagePath("nav_arr_L.png", false, "filesystem"), - $image_dir."/nav_arr_L.png"); - copy(ilUtil::getImagePath("nav_arr_R.png", false, "filesystem"), - $image_dir."/nav_arr_R.png"); - - // template workaround: reset of template - $tpl = new ilTemplate("tpl.main.html", true, true); - $tpl->setVariable("LOCATION_STYLESHEET",$location_stylesheet); - $tpl->addBlockFile("CONTENT", "content", "tpl.adm_content.html"); - - // zip everything - if (true) - { - // zip it all - $date = time(); - $zip_file = $this->getExportDirectory("html")."/".$date."__".IL_INST_ID."__". - $this->getType()."_".$this->getId().".zip"; -//echo "zip-".$a_target_dir."-to-".$zip_file; - ilUtil::zip($a_target_dir, $zip_file); - ilUtil::delDir($a_target_dir); - } - } - - - /** - * export glossary terms - */ - function exportHTMLGlossaryTerms(&$a_glo_gui, $a_target_dir) - { - include_once("./Services/COPage/classes/class.ilCOPageHTMLExport.php"); - $copage_export = new ilCOPageHTMLExport($a_target_dir); - $copage_export->exportSupportScripts(); - - // index.html file - $a_glo_gui->tpl = new ilTemplate("tpl.main.html", true, true); - $style_name = $this->user->prefs["style"].".css";; - $a_glo_gui->tpl->setVariable("LOCATION_STYLESHEET","./".$style_name); - $a_glo_gui->tpl->addBlockFile("CONTENT", "content", "tpl.adm_content.html"); - $a_glo_gui->tpl->setTitle($this->getTitle()); - - $content = $a_glo_gui->listTerms(); - $file = $a_target_dir."/index.html"; - - // open file - if (!($fp = @fopen($file,"w+"))) - { - die ("Error: Could not open \"".$file."\" for writing". - " in ".__FILE__." on line ".__LINE__."
"); - } - chmod($file, 0770); - fwrite($fp, $content); - fclose($fp); - - $terms = $this->getTermList(); - - $this->offline_mobs = array(); - $this->offline_files = array(); - - foreach($terms as $term) - { - $a_glo_gui->tpl = new ilTemplate("tpl.main.html", true, true); - $a_glo_gui->tpl = $copage_export->getPreparedMainTemplate(); - //$tpl->addBlockFile("CONTENT", "content", "tpl.adm_content.html"); - - // set style - $style_name = $this->user->prefs["style"].".css";; - $a_glo_gui->tpl->setVariable("LOCATION_STYLESHEET","./".$style_name); - - $_GET["term_id"] = $term["id"]; - $_GET["frame"] = "_blank"; - $content = $a_glo_gui->listDefinitions($_GET["ref_id"],$term["id"],false); - $file = $a_target_dir."/term_".$term["id"].".html"; - - // open file - if (!($fp = @fopen($file,"w+"))) - { - die ("Error: Could not open \"".$file."\" for writing". - " in ".__FILE__." on line ".__LINE__."
"); - } - chmod($file, 0770); - fwrite($fp, $content); - fclose($fp); - - // store linked/embedded media objects of glosssary term - include_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); - $defs = ilGlossaryDefinition::getDefinitionList($term["id"]); - foreach($defs as $def) - { - $def_mobs = ilObjMediaObject::_getMobsOfObject("gdf:pg", $def["id"]); - foreach($def_mobs as $def_mob) - { - $this->offline_mobs[$def_mob] = $def_mob; - } - - // get all files of page - include_once("./Modules/File/classes/class.ilObjFile.php"); - $def_files = ilObjFile::_getFilesOfObject("gdf:pg", $def["id"]); - $this->offline_files = array_merge($this->offline_files, $def_files); - - } - } - } - - /** - * export media object to html - */ - function exportHTMLMOB($a_target_dir, &$a_glo_gui, $a_mob_id) - { - $tpl = $this->tpl; - - $mob_dir = $a_target_dir."/mobs"; - - $source_dir = ilUtil::getWebspaceDir()."/mobs/mm_".$a_mob_id; - if (@is_dir($source_dir)) - { - ilUtil::makeDir($mob_dir."/mm_".$a_mob_id); - ilUtil::rCopy($source_dir, $mob_dir."/mm_".$a_mob_id); - } - - $tpl = new ilTemplate("tpl.main.html", true, true); - $tpl->addBlockFile("CONTENT", "content", "tpl.adm_content.html"); - $_GET["obj_type"] = "MediaObject"; - $_GET["mob_id"] = $a_mob_id; - $_GET["cmd"] = ""; - $content = $a_glo_gui->media(); - $file = $a_target_dir."/media_".$a_mob_id.".html"; - - // open file - if (!($fp = @fopen($file,"w+"))) - { - die ("Error: Could not open \"".$file."\" for writing". - " in ".__FILE__." on line ".__LINE__."
"); - } - chmod($file, 0770); - fwrite($fp, $content); - fclose($fp); - - // fullscreen - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $mob_obj = new ilObjMediaObject($a_mob_id); - if ($mob_obj->hasFullscreenItem()) - { - $tpl = new ilTemplate("tpl.main.html", true, true); - $tpl->addBlockFile("CONTENT", "content", "tpl.adm_content.html"); - $_GET["mob_id"] = $a_mob_id; - $_GET["cmd"] = "fullscreen"; - $content = $a_glo_gui->fullscreen(); - $file = $a_target_dir."/fullscreen_".$a_mob_id.".html"; - - // open file - if (!($fp = @fopen($file,"w+"))) - { - die ("Error: Could not open \"".$file."\" for writing". - " in ".__FILE__." on line ".__LINE__."
"); - } - chmod($file, 0770); - fwrite($fp, $content); - fclose($fp); - } - } - - /** - * export file object - */ - function exportHTMLFile($a_target_dir, $a_file_id) - { - $file_dir = $a_target_dir."/files/file_".$a_file_id; - ilUtil::makeDir($file_dir); - include_once("./Modules/File/classes/class.ilObjFile.php"); - $file_obj = new ilObjFile($a_file_id, false); - $source_file = $file_obj->getDirectory($file_obj->getVersion())."/".$file_obj->getFileName(); - if (!is_file($source_file)) - { - $source_file = $file_obj->getDirectory()."/".$file_obj->getFileName(); - } - copy($source_file, $file_dir."/".$file_obj->getFileName()); - } - - - /** - * export object to xml (see ilias_co.dtd) - * - * @param object $a_xml_writer ilXmlWriter object that receives the - * xml data - */ - function exportXML(&$a_xml_writer, $a_inst, $a_target_dir, &$expLog) - { - // export glossary - $attrs = array(); - $attrs["Type"] = "Glossary"; - $a_xml_writer->xmlStartTag("ContentObject", $attrs); - - // MetaData - $this->exportXMLMetaData($a_xml_writer); - - // collect media objects - $terms = $this->getTermList(); - $this->mob_ids = array(); - $this->file_ids = array(); - foreach ($terms as $term) - { - include_once "./Modules/Glossary/classes/class.ilGlossaryDefinition.php"; - - $defs = ilGlossaryDefinition::getDefinitionList($term[id]); - - foreach($defs as $def) - { - $this->page_object = new ilGlossaryDefPage($def["id"]); - $this->page_object->buildDom(); - $this->page_object->insertInstIntoIDs(IL_INST_ID); - $mob_ids = $this->page_object->collectMediaObjects(false); - include_once("./Services/COPage/classes/class.ilPCFileList.php"); - $file_ids = ilPCFileList::collectFileItems($this->page_object, $this->page_object->getDomDoc()); - foreach($mob_ids as $mob_id) - { - $this->mob_ids[$mob_id] = $mob_id; - } - foreach($file_ids as $file_id) - { - $this->file_ids[$file_id] = $file_id; - } - } - } - - // export media objects - $expLog->write(date("[y-m-d H:i:s] ")."Start Export Media Objects"); - $this->exportXMLMediaObjects($a_xml_writer, $a_inst, $a_target_dir, $expLog); - $expLog->write(date("[y-m-d H:i:s] ")."Finished Export Media Objects"); - - // FileItems - $expLog->write(date("[y-m-d H:i:s] ")."Start Export File Items"); - $this->exportFileItems($a_target_dir, $expLog); - $expLog->write(date("[y-m-d H:i:s] ")."Finished Export File Items"); - - // Glossary - $expLog->write(date("[y-m-d H:i:s] ")."Start Export Glossary Items"); - $this->exportXMLGlossaryItems($a_xml_writer, $a_inst, $expLog); - $expLog->write(date("[y-m-d H:i:s] ")."Finished Export Glossary Items"); - - $a_xml_writer->xmlEndTag("ContentObject"); - } - - /** - * export page objects to xml (see ilias_co.dtd) - * - * @param object $a_xml_writer ilXmlWriter object that receives the - * xml data - */ - function exportXMLGlossaryItems(&$a_xml_writer, $a_inst, &$expLog) - { - $attrs = array(); - $a_xml_writer->xmlStartTag("Glossary", $attrs); - - // MetaData - $this->exportXMLMetaData($a_xml_writer); - - $terms = $this->getTermList(); - - // export glossary terms - reset($terms); - foreach ($terms as $term) - { - $expLog->write(date("[y-m-d H:i:s] ")."Page Object ".$page["obj_id"]); - - // export xml to writer object - $glo_term = new ilGlossaryTerm($term["id"]); - $glo_term->exportXML($a_xml_writer, $a_inst); - - unset($glo_term); - - } - - $a_xml_writer->xmlEndTag("Glossary"); - } - - /** - * export content objects meta data to xml (see ilias_co.dtd) - * - * @param object $a_xml_writer ilXmlWriter object that receives the - * xml data - */ - function exportXMLMetaData(&$a_xml_writer) - { - include_once("Services/MetaData/classes/class.ilMD2XML.php"); - $md2xml = new ilMD2XML($this->getId(), 0, $this->getType()); - $md2xml->setExportMode(true); - $md2xml->startExport(); - $a_xml_writer->appendXML($md2xml->getXML()); - } - - /** - * export media objects to xml (see ilias_co.dtd) - * - * @param object $a_xml_writer ilXmlWriter object that receives the - * xml data - */ - function exportXMLMediaObjects(&$a_xml_writer, $a_inst, $a_target_dir, &$expLog) - { - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - - foreach ($this->mob_ids as $mob_id) - { - $expLog->write(date("[y-m-d H:i:s] ")."Media Object ".$mob_id); - $media_obj = new ilObjMediaObject($mob_id); - $media_obj->exportXML($a_xml_writer, $a_inst); - $media_obj->exportFiles($a_target_dir); - unset($media_obj); - } - } - - /** - * export files of file itmes - * - */ - function exportFileItems($a_target_dir, &$expLog) - { - include_once("./Modules/File/classes/class.ilObjFile.php"); - - foreach ($this->file_ids as $file_id) - { - $expLog->write(date("[y-m-d H:i:s] ")."File Item ".$file_id); - $file_obj = new ilObjFile($file_id, false); - $file_obj->export($a_target_dir); - unset($file_obj); - } - } - - - - /** - * - */ - function modifyExportIdentifier($a_tag, $a_param, $a_value) - { - if ($a_tag == "Identifier" && $a_param == "Entry") - { - $a_value = "il_".IL_INST_ID."_glo_".$this->getId(); - } - - return $a_value; - } - - - - - /** - * delete glossary and all related data - * - * this method has been tested on may 9th 2004 - * meta data, terms, definitions, definition meta data - * and definition pages have been deleted correctly as desired - * - * @access public - * @return boolean true if all object data were removed; false if only a references were removed - */ - function delete() - { - // always call parent delete function first!! - if (!parent::delete()) - { - return false; - } - - // delete terms - if (!$this->isVirtual()) - { - $terms = $this->getTermList(); - foreach ($terms as $term) - { - $term_obj = new ilGlossaryTerm($term["id"]); - $term_obj->delete(); - } - } - - // delete term references - include_once("./Modules/Glossary/classes/class.ilGlossaryTermReferences.php"); - $refs = new ilGlossaryTermReferences($this->getId()); - $refs->delete(); - - // delete glossary data entry - $q = "DELETE FROM glossary WHERE id = ".$this->db->quote($this->getId()); - $this->db->query($q); - - // delete meta data - $this->deleteMetaData(); - - return true; - } - - /** - * Get zipped xml file for glossary. - */ - function getXMLZip() - { - include_once("./Modules/Glossary/classes/class.ilGlossaryExport.php"); - $glo_exp = new ilGlossaryExport($this); - return $glo_exp->buildExportFile(); - } - - /** - * Get deletion dependencies - * - */ - static function getDeletionDependencies($a_obj_id) - { - global $DIC; - - $lng = $DIC->language(); - - $dep = array(); - include_once("./Modules/ScormAicc/classes/class.ilObjSAHSLearningModule.php"); - $sms = ilObjSAHSLearningModule::getScormModulesForGlossary($a_obj_id); - foreach ($sms as $sm) - { - $lng->loadLanguageModule("content"); - $dep[$sm] = $lng->txt("glo_used_in_scorm"); - } -//echo "-".$a_obj_id."-"; -//var_dump($dep); - return $dep; - } - - /** - * Get taxonomy - * - * @return int taxononmy ID - */ - function getTaxonomyId() - { - include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php"); - $tax_ids = ilObjTaxonomy::getUsageOfObject($this->getId()); - if (count($tax_ids) > 0) - { - // glossaries handle max. one taxonomy - return $tax_ids[0]; - } - return 0; - } - - - /** - * Clone glossary - * - * @param int target ref_id - * @param int copy id - */ - public function cloneObject($a_target_id,$a_copy_id = 0, $a_omit_tree = false) - { - $new_obj = parent::cloneObject($a_target_id,$a_copy_id, $a_omit_tree); - $this->cloneMetaData($new_obj); - - //copy online status if object is not the root copy object - $cp_options = ilCopyWizardOptions::_getInstance($a_copy_id); - - if(!$cp_options->isRootNode($this->getRefId())) - { - $new_obj->setOnline($this->getOnline()); - } - -// $new_obj->setTitle($this->getTitle()); - $new_obj->setDescription($this->getDescription()); - $new_obj->setVirtualMode($this->getVirtualMode()); - $new_obj->setPresentationMode($this->getPresentationMode()); - $new_obj->setSnippetLength($this->getSnippetLength()); - $new_obj->setAutoGlossaries($this->getAutoGlossaries()); - $new_obj->update(); - - // set/copy stylesheet - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $style_id = $this->getStyleSheetId(); - if ($style_id > 0 && !ilObjStyleSheet::_lookupStandard($style_id)) - { - include_once("./Services/Object/classes/class.ilObjectFactory.php"); - $style_obj = ilObjectFactory::getInstanceByObjId($style_id); - $new_id = $style_obj->ilClone(); - $new_obj->setStyleSheetId($new_id); - $new_obj->update(); - } - - // copy taxonomy - if (($tax_id = $this->getTaxonomyId()) > 0) - { - // clone it - include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php"); - $tax = new ilObjTaxonomy($tax_id); - $new_tax = $tax->cloneObject(0,0,true); - $map = $tax->getNodeMapping(); - - // assign new taxonomy to new glossary - ilObjTaxonomy::saveUsage($new_tax->getId(), $new_obj->getId()); - } - - // assign new tax/new glossary - // handle mapping - - // prepare tax node assignments objects - include_once("./Services/Taxonomy/classes/class.ilTaxNodeAssignment.php"); - if ($tax_id > 0) - { - $tax_ass = new ilTaxNodeAssignment("glo", $this->getId(), "term", $tax_id); - $new_tax_ass = new ilTaxNodeAssignment("glo", $new_obj->getId(), "term", $new_tax->getId()); - } - - // copy terms - $term_mappings = array(); - foreach (ilGlossaryTerm::getTermList($this->getRefId()) as $term) - { - $new_term_id = ilGlossaryTerm::_copyTerm($term["id"], $new_obj->getId()); - $term_mappings[$term["id"]] = $new_term_id; - - // copy tax node assignments - if ($tax_id > 0) - { - $assignmts = $tax_ass->getAssignmentsOfItem($term["id"]); - foreach ($assignmts as $a) - { - if ($map[$a["node_id"]] > 0) - { - $new_tax_ass->addAssignment($map[$a["node_id"]] ,$new_term_id); - } - } - } - } - - // add mapping of term_ids to copy wizard options - if (!empty($term_mappings)) - { - $cp_options->appendMapping($this->getRefId().'_glo_terms', (array) $term_mappings); - } - - - return $new_obj; - } - - /** - * Remove offline glossaries from obj id array - * - * @param - * @return - */ - function removeOfflineGlossaries($a_glo_ids, $ids_are_ref_ids = false) - { - $glo_ids = $a_glo_ids; - if ($ids_are_ref_ids) - { - $glo_ids = array_map(function($id) { - return ilObject::_lookupObjectId($id); - }, $a_glo_ids); - } - - $set = $this->db->query("SELECT id FROM glossary ". - " WHERE ".$this->db->in("id", $glo_ids, false, "integer"). - " AND is_online = ".$this->db->quote("y", "text") - ); - $online_glo_ids = array(); - while ($rec = $this->db->fetchAssoc($set)) - { - $online_glo_ids[] = $rec["id"]; - } - - if (!$ids_are_ref_ids) - { - return $online_glo_ids; - } - - $online_ref_ids = array_filter($a_glo_ids, function($ref_id) use ($online_glo_ids) { - return in_array(ilObject::_lookupObjectId($ref_id), $online_glo_ids); - }); - - - return $online_ref_ids; - } - - public static function getAdvMDSubItemTitle($a_obj_id, $a_sub_type, $a_sub_id) - { - global $DIC; - - $lng = $DIC->language(); - - if($a_sub_type == "term") - { - $lng->loadLanguageModule("glo"); - - include_once "Modules/Glossary/classes/class.ilGlossaryTerm.php"; - return $lng->txt("glo_term").' "'. ilGlossaryTerm::_lookGlossaryTerm($a_sub_id).'"'; - } - } - - /** - * Auto link glossary terms - * - * @param - * @return - */ - function autoLinkGlossaryTerms($a_glo_ref_id) - { - // get terms of target glossary - include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - $terms = ilGlossaryTerm::getTermList($a_glo_ref_id); - - // for each get page: get content - $source_terms = ilGlossaryTerm::getTermList($this->getRefId()); - $found_pages = array(); - foreach($source_terms as $source_term) - { - $source_defs = ilGlossaryDefinition::getDefinitionList($source_term["id"]); - - for ($j = 0; $j < count($source_defs); $j++) - { - $def = $source_defs[$j]; - $pg = new ilGlossaryDefPage($def["id"]); - - $c = $pg->getXMLContent(); - foreach ($terms as $t) - { - if (is_int(stripos($c, $t["term"]))) - { - $found_pages[$def["id"]]["terms"][] = $t; - if (!is_object($found_pages[$def["id"]]["page"])) - { - $found_pages[$def["id"]]["page"] = $pg; - } - } - } - reset($terms); - } - } - - // ilPCParagraph autoLinkGlossariesPage with page and terms - include_once("./Services/COPage/classes/class.ilPCParagraph.php"); - foreach ($found_pages as $id => $fp) - { - ilPCParagraph::autoLinkGlossariesPage($fp["page"], $fp["terms"]); - } - - - } - - /** - * Is long text search supported - * - * @return bool - */ - function supportsLongTextQuery() - { - return true; - } + include_once './Services/MathJax/classes/class.ilMathJax.php'; + ilMathJax::getInstance()->init(ilMathJax::PURPOSE_EXPORT); + + include_once("./Services/COPage/classes/class.ilCOPageHTMLExport.php"); + $this->co_page_html_export = new ilCOPageHTMLExport($a_target_dir); + $this->co_page_html_export->createDirectories(); + + // export system style sheet + $location_stylesheet = ilUtil::getStyleSheetLocation("filesystem"); + $style_name = $this->user->prefs["style"] . ".css"; + copy($location_stylesheet, $a_target_dir . "/" . $style_name); + $location_stylesheet = ilUtil::getStyleSheetLocation(); + + if ($this->getStyleSheetId() < 1) { + $cont_stylesheet = "Services/COPage/css/content.css"; + copy($cont_stylesheet, $a_target_dir . "/content.css"); + } else { + $content_style_img_dir = $a_target_dir . "/images"; + ilUtil::makeDir($content_style_img_dir); + $style = new ilObjStyleSheet($this->getStyleSheetId()); + $style->writeCSSFile($a_target_dir . "/content.css", "images"); + $style->copyImagesToDir($content_style_img_dir); + } + + // export syntax highlighting style + $syn_stylesheet = ilObjStyleSheet::getSyntaxStylePath(); + copy($syn_stylesheet, $a_target_dir . "/syntaxhighlight.css"); + + // get glossary presentation gui class + include_once("./Modules/Glossary/classes/class.ilGlossaryPresentationGUI.php"); + $_GET["cmd"] = "nop"; + $glo_gui = new ilGlossaryPresentationGUI(); + $glo_gui->setOfflineMode(true); + $glo_gui->setOfflineDirectory($a_target_dir); + + // could be implemented in the future if other export + // formats are supported (e.g. scorm) + //$glo_gui->setExportFormat($a_export_format); + + // export terms + $this->exportHTMLGlossaryTerms($glo_gui, $a_target_dir); + + // export all media objects + foreach ($this->offline_mobs as $mob) { + $this->exportHTMLMOB($a_target_dir, $glo_gui, $mob, "_blank"); + } + $_GET["obj_type"] = "MediaObject"; + $_GET["obj_id"] = $a_mob_id; + $_GET["cmd"] = ""; + + // export all file objects + foreach ($this->offline_files as $file) { + $this->exportHTMLFile($a_target_dir, $file); + } + + // export images + $image_dir = $a_target_dir . "/images"; + ilUtil::makeDir($image_dir); + ilUtil::makeDir($image_dir . "/browser"); + copy( + ilUtil::getImagePath("enlarge.svg", false, "filesystem"), + $image_dir . "/enlarge.svg" + ); + copy( + ilUtil::getImagePath("browser/blank.png", false, "filesystem"), + $image_dir . "/browser/plus.png" + ); + copy( + ilUtil::getImagePath("browser/blank.png", false, "filesystem"), + $image_dir . "/browser/minus.png" + ); + copy( + ilUtil::getImagePath("browser/blank.png", false, "filesystem"), + $image_dir . "/browser/blank.png" + ); + copy( + ilUtil::getImagePath("icon_st.svg", false, "filesystem"), + $image_dir . "/icon_st.svg" + ); + copy( + ilUtil::getImagePath("icon_pg.svg", false, "filesystem"), + $image_dir . "/icon_pg.svg" + ); + copy( + ilUtil::getImagePath("nav_arr_L.png", false, "filesystem"), + $image_dir . "/nav_arr_L.png" + ); + copy( + ilUtil::getImagePath("nav_arr_R.png", false, "filesystem"), + $image_dir . "/nav_arr_R.png" + ); + + // template workaround: reset of template + $tpl = new ilTemplate("tpl.main.html", true, true); + $tpl->setVariable("LOCATION_STYLESHEET", $location_stylesheet); + $tpl->addBlockFile("CONTENT", "content", "tpl.adm_content.html"); + + // zip everything + if (true) { + // zip it all + $date = time(); + $zip_file = $this->getExportDirectory("html") . "/" . $date . "__" . IL_INST_ID . "__" . + $this->getType() . "_" . $this->getId() . ".zip"; + //echo "zip-".$a_target_dir."-to-".$zip_file; + ilUtil::zip($a_target_dir, $zip_file); + ilUtil::delDir($a_target_dir); + } + } + + + /** + * export glossary terms + */ + public function exportHTMLGlossaryTerms(&$a_glo_gui, $a_target_dir) + { + include_once("./Services/COPage/classes/class.ilCOPageHTMLExport.php"); + $copage_export = new ilCOPageHTMLExport($a_target_dir); + $copage_export->exportSupportScripts(); + + // index.html file + $a_glo_gui->tpl = new ilTemplate("tpl.main.html", true, true); + $style_name = $this->user->prefs["style"] . ".css"; + ; + $a_glo_gui->tpl->setVariable("LOCATION_STYLESHEET", "./" . $style_name); + $a_glo_gui->tpl->addBlockFile("CONTENT", "content", "tpl.adm_content.html"); + $a_glo_gui->tpl->setTitle($this->getTitle()); + + $content = $a_glo_gui->listTerms(); + $file = $a_target_dir . "/index.html"; + + // open file + if (!($fp = @fopen($file, "w+"))) { + die("Error: Could not open \"" . $file . "\" for writing" . + " in " . __FILE__ . " on line " . __LINE__ . "
"); + } + chmod($file, 0770); + fwrite($fp, $content); + fclose($fp); + + $terms = $this->getTermList(); + + $this->offline_mobs = array(); + $this->offline_files = array(); + + foreach ($terms as $term) { + $a_glo_gui->tpl = new ilTemplate("tpl.main.html", true, true); + $a_glo_gui->tpl = $copage_export->getPreparedMainTemplate(); + //$tpl->addBlockFile("CONTENT", "content", "tpl.adm_content.html"); + + // set style + $style_name = $this->user->prefs["style"] . ".css"; + ; + $a_glo_gui->tpl->setVariable("LOCATION_STYLESHEET", "./" . $style_name); + + $_GET["term_id"] = $term["id"]; + $_GET["frame"] = "_blank"; + $content = $a_glo_gui->listDefinitions($_GET["ref_id"], $term["id"], false); + $file = $a_target_dir . "/term_" . $term["id"] . ".html"; + + // open file + if (!($fp = @fopen($file, "w+"))) { + die("Error: Could not open \"" . $file . "\" for writing" . + " in " . __FILE__ . " on line " . __LINE__ . "
"); + } + chmod($file, 0770); + fwrite($fp, $content); + fclose($fp); + + // store linked/embedded media objects of glosssary term + include_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); + $defs = ilGlossaryDefinition::getDefinitionList($term["id"]); + foreach ($defs as $def) { + $def_mobs = ilObjMediaObject::_getMobsOfObject("gdf:pg", $def["id"]); + foreach ($def_mobs as $def_mob) { + $this->offline_mobs[$def_mob] = $def_mob; + } + + // get all files of page + include_once("./Modules/File/classes/class.ilObjFile.php"); + $def_files = ilObjFile::_getFilesOfObject("gdf:pg", $def["id"]); + $this->offline_files = array_merge($this->offline_files, $def_files); + } + } + } + + /** + * export media object to html + */ + public function exportHTMLMOB($a_target_dir, &$a_glo_gui, $a_mob_id) + { + $tpl = $this->tpl; + + $mob_dir = $a_target_dir . "/mobs"; + + $source_dir = ilUtil::getWebspaceDir() . "/mobs/mm_" . $a_mob_id; + if (@is_dir($source_dir)) { + ilUtil::makeDir($mob_dir . "/mm_" . $a_mob_id); + ilUtil::rCopy($source_dir, $mob_dir . "/mm_" . $a_mob_id); + } + + $tpl = new ilTemplate("tpl.main.html", true, true); + $tpl->addBlockFile("CONTENT", "content", "tpl.adm_content.html"); + $_GET["obj_type"] = "MediaObject"; + $_GET["mob_id"] = $a_mob_id; + $_GET["cmd"] = ""; + $content = $a_glo_gui->media(); + $file = $a_target_dir . "/media_" . $a_mob_id . ".html"; + + // open file + if (!($fp = @fopen($file, "w+"))) { + die("Error: Could not open \"" . $file . "\" for writing" . + " in " . __FILE__ . " on line " . __LINE__ . "
"); + } + chmod($file, 0770); + fwrite($fp, $content); + fclose($fp); + + // fullscreen + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $mob_obj = new ilObjMediaObject($a_mob_id); + if ($mob_obj->hasFullscreenItem()) { + $tpl = new ilTemplate("tpl.main.html", true, true); + $tpl->addBlockFile("CONTENT", "content", "tpl.adm_content.html"); + $_GET["mob_id"] = $a_mob_id; + $_GET["cmd"] = "fullscreen"; + $content = $a_glo_gui->fullscreen(); + $file = $a_target_dir . "/fullscreen_" . $a_mob_id . ".html"; + + // open file + if (!($fp = @fopen($file, "w+"))) { + die("Error: Could not open \"" . $file . "\" for writing" . + " in " . __FILE__ . " on line " . __LINE__ . "
"); + } + chmod($file, 0770); + fwrite($fp, $content); + fclose($fp); + } + } + + /** + * export file object + */ + public function exportHTMLFile($a_target_dir, $a_file_id) + { + $file_dir = $a_target_dir . "/files/file_" . $a_file_id; + ilUtil::makeDir($file_dir); + include_once("./Modules/File/classes/class.ilObjFile.php"); + $file_obj = new ilObjFile($a_file_id, false); + $source_file = $file_obj->getDirectory($file_obj->getVersion()) . "/" . $file_obj->getFileName(); + if (!is_file($source_file)) { + $source_file = $file_obj->getDirectory() . "/" . $file_obj->getFileName(); + } + copy($source_file, $file_dir . "/" . $file_obj->getFileName()); + } + + + /** + * export object to xml (see ilias_co.dtd) + * + * @param object $a_xml_writer ilXmlWriter object that receives the + * xml data + */ + public function exportXML(&$a_xml_writer, $a_inst, $a_target_dir, &$expLog) + { + // export glossary + $attrs = array(); + $attrs["Type"] = "Glossary"; + $a_xml_writer->xmlStartTag("ContentObject", $attrs); + + // MetaData + $this->exportXMLMetaData($a_xml_writer); + + // collect media objects + $terms = $this->getTermList(); + $this->mob_ids = array(); + $this->file_ids = array(); + foreach ($terms as $term) { + include_once "./Modules/Glossary/classes/class.ilGlossaryDefinition.php"; + + $defs = ilGlossaryDefinition::getDefinitionList($term[id]); + + foreach ($defs as $def) { + $this->page_object = new ilGlossaryDefPage($def["id"]); + $this->page_object->buildDom(); + $this->page_object->insertInstIntoIDs(IL_INST_ID); + $mob_ids = $this->page_object->collectMediaObjects(false); + include_once("./Services/COPage/classes/class.ilPCFileList.php"); + $file_ids = ilPCFileList::collectFileItems($this->page_object, $this->page_object->getDomDoc()); + foreach ($mob_ids as $mob_id) { + $this->mob_ids[$mob_id] = $mob_id; + } + foreach ($file_ids as $file_id) { + $this->file_ids[$file_id] = $file_id; + } + } + } + + // export media objects + $expLog->write(date("[y-m-d H:i:s] ") . "Start Export Media Objects"); + $this->exportXMLMediaObjects($a_xml_writer, $a_inst, $a_target_dir, $expLog); + $expLog->write(date("[y-m-d H:i:s] ") . "Finished Export Media Objects"); + + // FileItems + $expLog->write(date("[y-m-d H:i:s] ") . "Start Export File Items"); + $this->exportFileItems($a_target_dir, $expLog); + $expLog->write(date("[y-m-d H:i:s] ") . "Finished Export File Items"); + + // Glossary + $expLog->write(date("[y-m-d H:i:s] ") . "Start Export Glossary Items"); + $this->exportXMLGlossaryItems($a_xml_writer, $a_inst, $expLog); + $expLog->write(date("[y-m-d H:i:s] ") . "Finished Export Glossary Items"); + + $a_xml_writer->xmlEndTag("ContentObject"); + } + + /** + * export page objects to xml (see ilias_co.dtd) + * + * @param object $a_xml_writer ilXmlWriter object that receives the + * xml data + */ + public function exportXMLGlossaryItems(&$a_xml_writer, $a_inst, &$expLog) + { + $attrs = array(); + $a_xml_writer->xmlStartTag("Glossary", $attrs); + + // MetaData + $this->exportXMLMetaData($a_xml_writer); + + $terms = $this->getTermList(); + + // export glossary terms + reset($terms); + foreach ($terms as $term) { + $expLog->write(date("[y-m-d H:i:s] ") . "Page Object " . $page["obj_id"]); + + // export xml to writer object + $glo_term = new ilGlossaryTerm($term["id"]); + $glo_term->exportXML($a_xml_writer, $a_inst); + + unset($glo_term); + } + + $a_xml_writer->xmlEndTag("Glossary"); + } + + /** + * export content objects meta data to xml (see ilias_co.dtd) + * + * @param object $a_xml_writer ilXmlWriter object that receives the + * xml data + */ + public function exportXMLMetaData(&$a_xml_writer) + { + include_once("Services/MetaData/classes/class.ilMD2XML.php"); + $md2xml = new ilMD2XML($this->getId(), 0, $this->getType()); + $md2xml->setExportMode(true); + $md2xml->startExport(); + $a_xml_writer->appendXML($md2xml->getXML()); + } + + /** + * export media objects to xml (see ilias_co.dtd) + * + * @param object $a_xml_writer ilXmlWriter object that receives the + * xml data + */ + public function exportXMLMediaObjects(&$a_xml_writer, $a_inst, $a_target_dir, &$expLog) + { + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + + foreach ($this->mob_ids as $mob_id) { + $expLog->write(date("[y-m-d H:i:s] ") . "Media Object " . $mob_id); + $media_obj = new ilObjMediaObject($mob_id); + $media_obj->exportXML($a_xml_writer, $a_inst); + $media_obj->exportFiles($a_target_dir); + unset($media_obj); + } + } + + /** + * export files of file itmes + * + */ + public function exportFileItems($a_target_dir, &$expLog) + { + include_once("./Modules/File/classes/class.ilObjFile.php"); + + foreach ($this->file_ids as $file_id) { + $expLog->write(date("[y-m-d H:i:s] ") . "File Item " . $file_id); + $file_obj = new ilObjFile($file_id, false); + $file_obj->export($a_target_dir); + unset($file_obj); + } + } + + + + /** + * + */ + public function modifyExportIdentifier($a_tag, $a_param, $a_value) + { + if ($a_tag == "Identifier" && $a_param == "Entry") { + $a_value = "il_" . IL_INST_ID . "_glo_" . $this->getId(); + } + + return $a_value; + } + + + + + /** + * delete glossary and all related data + * + * this method has been tested on may 9th 2004 + * meta data, terms, definitions, definition meta data + * and definition pages have been deleted correctly as desired + * + * @access public + * @return boolean true if all object data were removed; false if only a references were removed + */ + public function delete() + { + // always call parent delete function first!! + if (!parent::delete()) { + return false; + } + + // delete terms + if (!$this->isVirtual()) { + $terms = $this->getTermList(); + foreach ($terms as $term) { + $term_obj = new ilGlossaryTerm($term["id"]); + $term_obj->delete(); + } + } + + // delete term references + include_once("./Modules/Glossary/classes/class.ilGlossaryTermReferences.php"); + $refs = new ilGlossaryTermReferences($this->getId()); + $refs->delete(); + + // delete glossary data entry + $q = "DELETE FROM glossary WHERE id = " . $this->db->quote($this->getId()); + $this->db->query($q); + + // delete meta data + $this->deleteMetaData(); + + return true; + } + + /** + * Get zipped xml file for glossary. + */ + public function getXMLZip() + { + include_once("./Modules/Glossary/classes/class.ilGlossaryExport.php"); + $glo_exp = new ilGlossaryExport($this); + return $glo_exp->buildExportFile(); + } + + /** + * Get deletion dependencies + * + */ + public static function getDeletionDependencies($a_obj_id) + { + global $DIC; + + $lng = $DIC->language(); + + $dep = array(); + include_once("./Modules/ScormAicc/classes/class.ilObjSAHSLearningModule.php"); + $sms = ilObjSAHSLearningModule::getScormModulesForGlossary($a_obj_id); + foreach ($sms as $sm) { + $lng->loadLanguageModule("content"); + $dep[$sm] = $lng->txt("glo_used_in_scorm"); + } + //echo "-".$a_obj_id."-"; + //var_dump($dep); + return $dep; + } + + /** + * Get taxonomy + * + * @return int taxononmy ID + */ + public function getTaxonomyId() + { + include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php"); + $tax_ids = ilObjTaxonomy::getUsageOfObject($this->getId()); + if (count($tax_ids) > 0) { + // glossaries handle max. one taxonomy + return $tax_ids[0]; + } + return 0; + } + + + /** + * Clone glossary + * + * @param int target ref_id + * @param int copy id + */ + public function cloneObject($a_target_id, $a_copy_id = 0, $a_omit_tree = false) + { + $new_obj = parent::cloneObject($a_target_id, $a_copy_id, $a_omit_tree); + $this->cloneMetaData($new_obj); + + //copy online status if object is not the root copy object + $cp_options = ilCopyWizardOptions::_getInstance($a_copy_id); + + if (!$cp_options->isRootNode($this->getRefId())) { + $new_obj->setOnline($this->getOnline()); + } + + // $new_obj->setTitle($this->getTitle()); + $new_obj->setDescription($this->getDescription()); + $new_obj->setVirtualMode($this->getVirtualMode()); + $new_obj->setPresentationMode($this->getPresentationMode()); + $new_obj->setSnippetLength($this->getSnippetLength()); + $new_obj->setAutoGlossaries($this->getAutoGlossaries()); + $new_obj->update(); + + // set/copy stylesheet + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $style_id = $this->getStyleSheetId(); + if ($style_id > 0 && !ilObjStyleSheet::_lookupStandard($style_id)) { + include_once("./Services/Object/classes/class.ilObjectFactory.php"); + $style_obj = ilObjectFactory::getInstanceByObjId($style_id); + $new_id = $style_obj->ilClone(); + $new_obj->setStyleSheetId($new_id); + $new_obj->update(); + } + + // copy taxonomy + if (($tax_id = $this->getTaxonomyId()) > 0) { + // clone it + include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php"); + $tax = new ilObjTaxonomy($tax_id); + $new_tax = $tax->cloneObject(0, 0, true); + $map = $tax->getNodeMapping(); + + // assign new taxonomy to new glossary + ilObjTaxonomy::saveUsage($new_tax->getId(), $new_obj->getId()); + } + + // assign new tax/new glossary + // handle mapping + + // prepare tax node assignments objects + include_once("./Services/Taxonomy/classes/class.ilTaxNodeAssignment.php"); + if ($tax_id > 0) { + $tax_ass = new ilTaxNodeAssignment("glo", $this->getId(), "term", $tax_id); + $new_tax_ass = new ilTaxNodeAssignment("glo", $new_obj->getId(), "term", $new_tax->getId()); + } + + // copy terms + $term_mappings = array(); + foreach (ilGlossaryTerm::getTermList($this->getRefId()) as $term) { + $new_term_id = ilGlossaryTerm::_copyTerm($term["id"], $new_obj->getId()); + $term_mappings[$term["id"]] = $new_term_id; + + // copy tax node assignments + if ($tax_id > 0) { + $assignmts = $tax_ass->getAssignmentsOfItem($term["id"]); + foreach ($assignmts as $a) { + if ($map[$a["node_id"]] > 0) { + $new_tax_ass->addAssignment($map[$a["node_id"]], $new_term_id); + } + } + } + } + + // add mapping of term_ids to copy wizard options + if (!empty($term_mappings)) { + $cp_options->appendMapping($this->getRefId() . '_glo_terms', (array) $term_mappings); + } + + + return $new_obj; + } + + /** + * Remove offline glossaries from obj id array + * + * @param + * @return + */ + public function removeOfflineGlossaries($a_glo_ids, $ids_are_ref_ids = false) + { + $glo_ids = $a_glo_ids; + if ($ids_are_ref_ids) { + $glo_ids = array_map(function ($id) { + return ilObject::_lookupObjectId($id); + }, $a_glo_ids); + } + + $set = $this->db->query( + "SELECT id FROM glossary " . + " WHERE " . $this->db->in("id", $glo_ids, false, "integer") . + " AND is_online = " . $this->db->quote("y", "text") + ); + $online_glo_ids = array(); + while ($rec = $this->db->fetchAssoc($set)) { + $online_glo_ids[] = $rec["id"]; + } + + if (!$ids_are_ref_ids) { + return $online_glo_ids; + } + + $online_ref_ids = array_filter($a_glo_ids, function ($ref_id) use ($online_glo_ids) { + return in_array(ilObject::_lookupObjectId($ref_id), $online_glo_ids); + }); + + + return $online_ref_ids; + } + + public static function getAdvMDSubItemTitle($a_obj_id, $a_sub_type, $a_sub_id) + { + global $DIC; + + $lng = $DIC->language(); + + if ($a_sub_type == "term") { + $lng->loadLanguageModule("glo"); + + include_once "Modules/Glossary/classes/class.ilGlossaryTerm.php"; + return $lng->txt("glo_term") . ' "' . ilGlossaryTerm::_lookGlossaryTerm($a_sub_id) . '"'; + } + } + + /** + * Auto link glossary terms + * + * @param + * @return + */ + public function autoLinkGlossaryTerms($a_glo_ref_id) + { + // get terms of target glossary + include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + $terms = ilGlossaryTerm::getTermList($a_glo_ref_id); + + // for each get page: get content + $source_terms = ilGlossaryTerm::getTermList($this->getRefId()); + $found_pages = array(); + foreach ($source_terms as $source_term) { + $source_defs = ilGlossaryDefinition::getDefinitionList($source_term["id"]); + + for ($j = 0; $j < count($source_defs); $j++) { + $def = $source_defs[$j]; + $pg = new ilGlossaryDefPage($def["id"]); + + $c = $pg->getXMLContent(); + foreach ($terms as $t) { + if (is_int(stripos($c, $t["term"]))) { + $found_pages[$def["id"]]["terms"][] = $t; + if (!is_object($found_pages[$def["id"]]["page"])) { + $found_pages[$def["id"]]["page"] = $pg; + } + } + } + reset($terms); + } + } + + // ilPCParagraph autoLinkGlossariesPage with page and terms + include_once("./Services/COPage/classes/class.ilPCParagraph.php"); + foreach ($found_pages as $id => $fp) { + ilPCParagraph::autoLinkGlossariesPage($fp["page"], $fp["terms"]); + } + } + + /** + * Is long text search supported + * + * @return bool + */ + public function supportsLongTextQuery() + { + return true; + } } - -?> diff --git a/Modules/Glossary/classes/class.ilObjGlossaryAccess.php b/Modules/Glossary/classes/class.ilObjGlossaryAccess.php index 141edb8b86cc79ff080dc2d3a21bd79d7724e39e..558e784cad157cc79bbd75f3518282e957823599 100644 --- a/Modules/Glossary/classes/class.ilObjGlossaryAccess.php +++ b/Modules/Glossary/classes/class.ilObjGlossaryAccess.php @@ -16,190 +16,172 @@ include_once("./Services/Object/classes/class.ilObjectAccess.php"); */ class ilObjGlossaryAccess extends ilObjectAccess { - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilAccessHandler - */ - protected $access; - - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->user = $DIC->user(); - $this->lng = $DIC->language(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->access = $DIC->access(); - } - - /** - * checks wether a user may invoke a command or not - * (this method is called by ilAccessHandler::checkAccess) - * - * @param string $a_cmd command (not permission!) - * @param string $a_permission permission - * @param int $a_ref_id reference id - * @param int $a_obj_id object id - * @param int $a_user_id user id (if not provided, current user is taken) - * - * @return mixed true, if everything is ok, message (string) when - * access is not granted - */ - function _checkAccess($a_cmd, $a_permission, $a_ref_id, $a_obj_id, $a_user_id = "") - { - $ilUser = $this->user; - $lng = $this->lng; - $rbacsystem = $this->rbacsystem; - $ilAccess = $this->access; - - if ($a_user_id == "") - { - $a_user_id = $ilUser->getId(); - } - - switch ($a_permission) - { - case "read": - if(!ilObjGlossaryAccess::_lookupOnline($a_obj_id) - && !$rbacsystem->checkAccessOfUser($a_user_id,'write',$a_ref_id)) - { - $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("offline")); - return false; - } - break; - - case "visible": - if (!ilObjGlossaryAccess::_lookupOnline($a_obj_id) && - (!$rbacsystem->checkAccessOfUser($a_user_id,'write', $a_ref_id))) - { - $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("offline")); - return false; - } - break; - } - - - return true; - } - - /** - * 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" => "view", "lang_var" => "show", - "default" => true), - array("permission" => "write", "cmd" => "edit", "lang_var" => "edit_content"), - array("permission" => "edit_content", "cmd" => "edit", "lang_var" => "edit_content"), // #11099 - array("permission" => "write", "cmd" => "properties", "lang_var" => "settings") - ); - - return $commands; - } - - // - // access relevant methods - // - - /** - * check wether learning module is online - */ - static function _lookupOnline($a_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "SELECT * FROM glossary WHERE id = ". - $ilDB->quote($a_id, "integer"); - $lm_set = $ilDB->query($q); - $lm_rec = $ilDB->fetchAssoc($lm_set); - - return ilUtil::yn2tf($lm_rec["is_online"]); - } - - /** - * check whether goto script will succeed - */ - static function _checkGoto($a_target) - { - global $DIC; - - $ilAccess = $DIC->access(); - - $t_arr = explode("_", $a_target); - - if (($t_arr[0] != "glo" && $t_arr[0] != "git") || ((int) $t_arr[1]) <= 0) - { - return false; - } - - if ($t_arr[0] == "glo") - { - if ($ilAccess->checkAccess("read", "", $t_arr[1]) || - $ilAccess->checkAccess("visible", "", $t_arr[1])) - { - return true; - } - } - - if ($t_arr[0] == "git") - { - if ($t_arr[2] > 0) - { - $ref_ids = array($t_arr[2]); - } - else - { - // determine learning object - require_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - $glo_id = ilGlossaryTerm::_lookGlossaryID($t_arr[1]); - $ref_ids = ilObject::_getAllReferences($glo_id); - } - // check read permissions - foreach ($ref_ids as $ref_id) - { - // Permission check - if ($ilAccess->checkAccess("read", "", $ref_id)) - { - return true; - } - } - } - - return false; - } - - + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilAccessHandler + */ + protected $access; + + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->user = $DIC->user(); + $this->lng = $DIC->language(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->access = $DIC->access(); + } + + /** + * checks wether a user may invoke a command or not + * (this method is called by ilAccessHandler::checkAccess) + * + * @param string $a_cmd command (not permission!) + * @param string $a_permission permission + * @param int $a_ref_id reference id + * @param int $a_obj_id object id + * @param int $a_user_id user id (if not provided, current user is taken) + * + * @return mixed true, if everything is ok, message (string) when + * access is not granted + */ + public function _checkAccess($a_cmd, $a_permission, $a_ref_id, $a_obj_id, $a_user_id = "") + { + $ilUser = $this->user; + $lng = $this->lng; + $rbacsystem = $this->rbacsystem; + $ilAccess = $this->access; + + if ($a_user_id == "") { + $a_user_id = $ilUser->getId(); + } + + switch ($a_permission) { + case "read": + if (!ilObjGlossaryAccess::_lookupOnline($a_obj_id) + && !$rbacsystem->checkAccessOfUser($a_user_id, 'write', $a_ref_id)) { + $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("offline")); + return false; + } + break; + + case "visible": + if (!ilObjGlossaryAccess::_lookupOnline($a_obj_id) && + (!$rbacsystem->checkAccessOfUser($a_user_id, 'write', $a_ref_id))) { + $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("offline")); + return false; + } + break; + } + + + return true; + } + + /** + * 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" => "view", "lang_var" => "show", + "default" => true), + array("permission" => "write", "cmd" => "edit", "lang_var" => "edit_content"), + array("permission" => "edit_content", "cmd" => "edit", "lang_var" => "edit_content"), // #11099 + array("permission" => "write", "cmd" => "properties", "lang_var" => "settings") + ); + + return $commands; + } + + // + // access relevant methods + // + + /** + * check wether learning module is online + */ + public static function _lookupOnline($a_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "SELECT * FROM glossary WHERE id = " . + $ilDB->quote($a_id, "integer"); + $lm_set = $ilDB->query($q); + $lm_rec = $ilDB->fetchAssoc($lm_set); + + return ilUtil::yn2tf($lm_rec["is_online"]); + } + + /** + * check whether goto script will succeed + */ + public static function _checkGoto($a_target) + { + global $DIC; + + $ilAccess = $DIC->access(); + + $t_arr = explode("_", $a_target); + + if (($t_arr[0] != "glo" && $t_arr[0] != "git") || ((int) $t_arr[1]) <= 0) { + return false; + } + + if ($t_arr[0] == "glo") { + if ($ilAccess->checkAccess("read", "", $t_arr[1]) || + $ilAccess->checkAccess("visible", "", $t_arr[1])) { + return true; + } + } + + if ($t_arr[0] == "git") { + if ($t_arr[2] > 0) { + $ref_ids = array($t_arr[2]); + } else { + // determine learning object + require_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + $glo_id = ilGlossaryTerm::_lookGlossaryID($t_arr[1]); + $ref_ids = ilObject::_getAllReferences($glo_id); + } + // check read permissions + foreach ($ref_ids as $ref_id) { + // Permission check + if ($ilAccess->checkAccess("read", "", $ref_id)) { + return true; + } + } + } + + return false; + } } - -?> diff --git a/Modules/Glossary/classes/class.ilObjGlossaryGUI.php b/Modules/Glossary/classes/class.ilObjGlossaryGUI.php index 82fd89e25e3d0c3d2f5654b79be228abb59854ed..851ea327acd4d708f9537e1a45de63b87ef3bda9 100755 --- a/Modules/Glossary/classes/class.ilObjGlossaryGUI.php +++ b/Modules/Glossary/classes/class.ilObjGlossaryGUI.php @@ -21,1928 +21,1896 @@ require_once("./Services/COPage/classes/class.ilPCParagraph.php"); * @ilCtrl_Calls ilObjGlossaryGUI: ilInfoScreenGUI, ilCommonActionDispatcherGUI, ilObjStyleSheetGUI * @ilCtrl_Calls ilObjGlossaryGUI: ilObjTaxonomyGUI, ilExportGUI, ilObjectCopyGUI * @ilCtrl_Calls ilObjGlossaryGUI: ilObjectMetaDataGUI, ilGlossaryForeignTermCollectorGUI -* +* * @ingroup ModulesGlossary */ class ilObjGlossaryGUI extends ilObjectGUI { - /** - * @var ilErrorHandling - */ - protected $error; - - var $admin_tabs; - var $mode; - var $term; - - /** - * @var int - */ - protected $term_id; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilSetting - */ - protected $setting; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilHelp - */ - protected $help; - - /** - * @var ilGlossaryTermPermission - */ - protected $term_perm; - - /** - * @var ilLogger - */ - protected $log; - - /** - * Constructor - * @access public - */ - function __construct($a_data,$a_id = 0,$a_call_by_reference = true, $a_prepare_output = true) - { - $this->error = $DIC["ilErr"]; - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - $this->toolbar = $DIC->toolbar(); - $this->tabs = $DIC->tabs(); - $this->setting = $DIC["ilSetting"]; - $this->access = $DIC->access(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->help = $DIC["ilHelp"]; - - $this->log = ilLoggerFactory::getLogger('glo'); - - include_once("./Modules/Glossary/classes/class.ilGlossaryTermPermission.php"); - $this->term_perm = ilGlossaryTermPermission::getInstance(); - - $this->ctrl->saveParameter($this, array("ref_id", "offset")); - - $this->lng->loadLanguageModule("content"); - $this->lng->loadLanguageModule("glo"); - - $this->type = "glo"; - parent::__construct($a_data, $a_id, $a_call_by_reference, false); - - // determine term id and check whether it is valid (belongs to - // current glossary) - $this->term_id = (int) $_GET["term_id"]; - $term_glo_id = ilGlossaryTerm::_lookGlossaryID($this->term_id); - include_once("./Modules/Glossary/classes/class.ilGlossaryTermReferences.php"); - if ($this->term_id > 0 && $term_glo_id != $this->object->getId() - && !ilGlossaryTermReferences::isReferenced($this->object->getId(), $this->term_id)) - { - $this->term_id = ""; - } - - $this->tax_id = $this->object->getTaxonomyId(); - if ($this->tax_id > 0) - { - $this->ctrl->saveParameter($this, array("show_tax", "tax_node")); - - 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"]; - } - } - - /** - * execute command - */ - function executeCommand() - { - $cmd = $this->ctrl->getCmd(); - $next_class = $this->ctrl->getNextClass($this); - - $this->log->debug("glossary term, next class ".$next_class.", cmd: ".$cmd); - - switch ($next_class) - { - case 'ilobjectmetadatagui'; - $this->checkPermission("write"); - - $this->getTemplate(); - $this->setTabs(); - $this->setLocator(); - $this->addHeaderAction(); - - $this->tabs_gui->activateTab('meta_data'); - include_once 'Services/Object/classes/class.ilObjectMetaDataGUI.php'; - $md_gui = new ilObjectMetaDataGUI($this->object, 'term'); - $this->ctrl->forwardCommand($md_gui); - break; - - case "ilglossarytermgui": - if (!$this->term_perm->checkPermission("edit_content", $this->term_id) && - !$this->term_perm->checkPermission("write", $this->term_id)) - { - include_once("./Modules/Glossary/exceptions/class.ilGlossaryException.php"); - throw new ilGlossaryException("No permission."); - } - $this->getTemplate(); + /** + * @var ilErrorHandling + */ + protected $error; + + public $admin_tabs; + public $mode; + public $term; + + /** + * @var int + */ + protected $term_id; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilSetting + */ + protected $setting; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilHelp + */ + protected $help; + + /** + * @var ilGlossaryTermPermission + */ + protected $term_perm; + + /** + * @var ilLogger + */ + protected $log; + + /** + * Constructor + * @access public + */ + public function __construct($a_data, $a_id = 0, $a_call_by_reference = true, $a_prepare_output = true) + { + $this->error = $DIC["ilErr"]; + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + $this->toolbar = $DIC->toolbar(); + $this->tabs = $DIC->tabs(); + $this->setting = $DIC["ilSetting"]; + $this->access = $DIC->access(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->help = $DIC["ilHelp"]; + + $this->log = ilLoggerFactory::getLogger('glo'); + + include_once("./Modules/Glossary/classes/class.ilGlossaryTermPermission.php"); + $this->term_perm = ilGlossaryTermPermission::getInstance(); + + $this->ctrl->saveParameter($this, array("ref_id", "offset")); + + $this->lng->loadLanguageModule("content"); + $this->lng->loadLanguageModule("glo"); + + $this->type = "glo"; + parent::__construct($a_data, $a_id, $a_call_by_reference, false); + + // determine term id and check whether it is valid (belongs to + // current glossary) + $this->term_id = (int) $_GET["term_id"]; + $term_glo_id = ilGlossaryTerm::_lookGlossaryID($this->term_id); + include_once("./Modules/Glossary/classes/class.ilGlossaryTermReferences.php"); + if ($this->term_id > 0 && $term_glo_id != $this->object->getId() + && !ilGlossaryTermReferences::isReferenced($this->object->getId(), $this->term_id)) { + $this->term_id = ""; + } + + $this->tax_id = $this->object->getTaxonomyId(); + if ($this->tax_id > 0) { + $this->ctrl->saveParameter($this, array("show_tax", "tax_node")); + + 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"]; + } + } + + /** + * execute command + */ + public function executeCommand() + { + $cmd = $this->ctrl->getCmd(); + $next_class = $this->ctrl->getNextClass($this); + + $this->log->debug("glossary term, next class " . $next_class . ", cmd: " . $cmd); + + switch ($next_class) { + case 'ilobjectmetadatagui': + $this->checkPermission("write"); + + $this->getTemplate(); + $this->setTabs(); + $this->setLocator(); + $this->addHeaderAction(); + + $this->tabs_gui->activateTab('meta_data'); + include_once 'Services/Object/classes/class.ilObjectMetaDataGUI.php'; + $md_gui = new ilObjectMetaDataGUI($this->object, 'term'); + $this->ctrl->forwardCommand($md_gui); + break; + + case "ilglossarytermgui": + if (!$this->term_perm->checkPermission("edit_content", $this->term_id) && + !$this->term_perm->checkPermission("write", $this->term_id)) { + include_once("./Modules/Glossary/exceptions/class.ilGlossaryException.php"); + throw new ilGlossaryException("No permission."); + } + $this->getTemplate(); // $this->quickList(); - $this->ctrl->setReturn($this, "listTerms"); - $term_gui = new ilGlossaryTermGUI($this->term_id); - $term_gui->setGlossary($this->object); - //$ret = $term_gui->executeCommand(); - $ret = $this->ctrl->forwardCommand($term_gui); - break; - - case "ilinfoscreengui": - $this->addHeaderAction(); - $this->showInfoScreen(); - 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" || $_GET["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 'ilpermissiongui': - if (strtolower($_GET["baseClass"]) == "iladministrationgui") - { - $this->prepareOutput(); - } - else - { - $this->getTemplate(); - $this->setTabs(); - $this->setLocator(); - $this->addHeaderAction(); - } - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $ret = $this->ctrl->forwardCommand($perm_gui); - break; - - case "ilcommonactiondispatchergui": - include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); - $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); - $this->ctrl->forwardCommand($gui); - break; - - case "ilobjtaxonomygui": - $this->getTemplate(); - $this->setTabs(); - $this->setLocator(); - $this->addHeaderAction(); - $this->tabs->activateTab("settings"); - $this->setSettingsSubTabs("taxonomy"); - - include_once("./Services/Taxonomy/classes/class.ilObjTaxonomyGUI.php"); - $this->ctrl->setReturn($this, "properties"); - $tax_gui = new ilObjTaxonomyGUI(); - $tax_gui->setMultiple(false); - - /*include_once("./Modules/Glossary/classes/class.ilTermTaxInfo.php"); - $term_info = new ilTermTaxInfo();*/ - //$tax_gui->activateAssignedItemSorting($term_info, "glo", "term"); - - $tax_gui->setAssignedObject($this->object->getId()); - $ret = $this->ctrl->forwardCommand($tax_gui); - break; - - case "ilexportgui": - $this->getTemplate(); - $this->setTabs(); - $this->tabs->activateTab("export"); - $this->setLocator(); - include_once("./Services/Export/classes/class.ilExportGUI.php"); - $exp_gui = new ilExportGUI($this); - //$exp_gui->addFormat("xml", "", $this, "export"); - $exp_gui->addFormat("xml"); - $exp_gui->addFormat("html", "", $this, "exportHTML"); - $exp_gui->addCustomColumn($this->lng->txt("cont_public_access"), - $this, "getPublicAccessColValue"); - $exp_gui->addCustomMultiCommand($this->lng->txt("cont_public_access"), - $this, "publishExportFile"); - $ret = $this->ctrl->forwardCommand($exp_gui); - break; - - case 'ilobjectcopygui': - $this->prepareOutput(); - include_once './Services/Object/classes/class.ilObjectCopyGUI.php'; - $cp = new ilObjectCopyGUI($this); - $cp->setType('glo'); - $this->ctrl->forwardCommand($cp); - break; - - case "ilglossaryforeigntermcollectorgui": - $this->ctrl->setReturn($this, ""); - $this->getTemplate(); - $this->setTabs(); - $this->setLocator(); - $this->addHeaderAction(); - include_once("./Modules/Glossary/classes/class.ilGlossaryForeignTermCollectorGUI.php"); - $coll = ilGlossaryForeignTermCollectorGUI::getInstance($this); - $this->ctrl->forwardCommand($coll); - break; - - default: - $cmd = $this->ctrl->getCmd("listTerms"); - - if (($cmd == "create") && ($_POST["new_type"] == "term")) - { - $this->ctrl->setCmd("create"); - $this->ctrl->setCmdClass("ilGlossaryTermGUI"); - $ret = $this->executeCommand(); - return; - } - else - { - if (!in_array($cmd, array("quickList"))) - { - if (strtolower($_GET["baseClass"]) == "iladministrationgui" || - $this->getCreationMode() == true) - { - $this->prepareOutput(); - $cmd.= "Object"; - } - else - { - $this->getTemplate(); - $this->setTabs(); - $this->setLocator(); - $this->addHeaderAction(); - - if($cmd == "redrawHeaderAction") - { - $cmd = "redrawHeaderActionObject"; - } - } - } - $ret = $this->$cmd(); - } - break; - } - - if (!in_array($cmd, array("quickList"))) - { - if (strtolower($_GET["baseClass"]) != "iladministrationgui") - { - if (!$this->getCreationMode()) - { - $this->tpl->show(); - } - } - } - else - { - $this->tpl->show(false); - } - } - - function assignObject() - { - include_once("./Modules/Glossary/classes/class.ilObjGlossary.php"); - - $this->object = new ilObjGlossary($this->id, true); - } - - /*protected function initCreationForms($a_new_type) - { - $forms = array( - self::CFORM_NEW => $this->initCreateForm($a_new_type), - self::CFORM_IMPORT => $this->initImportForm($a_new_type) - ); - - return $forms; - }*/ - - function initCreateForm($a_new_type) - { - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setTarget("_top"); - $form->setFormAction($this->ctrl->getFormAction($this)); - $form->setTitle($this->lng->txt($a_new_type."_new")); - - // title - $ti = new ilTextInputGUI($this->lng->txt("title"), "title"); - $ti->setSize(min(40, ilObject::TITLE_LENGTH)); - $ti->setMaxLength(ilObject::TITLE_LENGTH); - $ti->setRequired(true); - $form->addItem($ti); - - // description - $ta = new ilTextAreaInputGUI($this->lng->txt("description"), "desc"); - $ta->setCols(40); - $ta->setRows(2); - $form->addItem($ta); - - // mode - $stati = array( - "none"=>$this->lng->txt("glo_mode_normal"), - "level"=>$this->lng->txt("glo_mode_level"), - "subtree"=>$this->lng->txt("glo_mode_subtree") - ); - $tm = new ilSelectInputGUI($this->lng->txt("glo_mode"), "glo_mode"); - $tm->setOptions($stati); - $tm->setInfo($this->lng->txt("glo_mode_desc")); - $tm->setRequired(true); - $form->addItem($tm); - - $form->addCommandButton("save", $this->lng->txt($a_new_type."_add")); - $form->addCommandButton("cancel", $this->lng->txt("cancel")); - - return $form; - } - - function importObject() - { - $this->createObject(); - } - - /** - * save new content object to db - */ - function saveObject() - { - $ilErr = $this->error; - - $new_type = $_REQUEST["new_type"]; - - // create permission is already checked in createObject. This check here is done to prevent hacking attempts - if (!$this->checkPermissionBool("create", "", $new_type)) - { - $ilErr->raiseError($this->lng->txt("no_create_permission"), $ilErr->MESSAGE); - } - - $this->lng->loadLanguageModule($new_type); - $this->ctrl->setParameter($this, "new_type", $new_type); - - $form = $this->initCreateForm($new_type); - if ($form->checkInput()) - { - $this->ctrl->setParameter($this, "new_type", ""); - - include_once("./Modules/Glossary/classes/class.ilObjGlossary.php"); - $newObj = new ilObjGlossary(); - $newObj->setType($new_type); - $newObj->setTitle($form->getInput("title")); - $newObj->setDescription($form->getInput("desc")); - $newObj->setVirtualMode($form->getInput("glo_mode")); - $newObj->create(); - - $this->putObjectInTree($newObj); - - // always send a message - ilUtil::sendSuccess($this->lng->txt("glo_added"),true); - ilUtil::redirect("ilias.php?baseClass=ilGlossaryEditorGUI&ref_id=".$newObj->getRefId()); - } - - // display only this form to correct input - $form->setValuesByPost(); - $this->tpl->setContent($form->getHtml()); - } - - /** - * Show info screen - * - * @param - * @return - */ - function showInfoScreen() - { - $this->getTemplate(); - $this->setTabs(); - $this->setLocator(); - $this->lng->loadLanguageModule("meta"); - include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); - - $info = new ilInfoScreenGUI($this); - $info->enablePrivateNotes(); - $info->enableNews(); - if ($this->access->checkAccess("write", "", $_GET["ref_id"])) - { - $info->enableNewsEditing(); - $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->addMetaDataSections($this->object->getId(),0, $this->object->getType()); - - ilObjGlossaryGUI::addUsagesToInfo($info, $this->object->getId()); - - $this->ctrl->forwardCommand($info); - } - - /** - * Add usages to info - * - * @param - * @return - */ - static function addUsagesToInfo($info, $glo_id) - { - global $DIC; - - $lng = $DIC->language(); - $ilAccess = $DIC->access(); - - $info->addSection($lng->txt("glo_usages")); - include_once("./Modules/ScormAicc/classes/class.ilObjSAHSLearningModule.php"); - $sms = ilObjSAHSLearningModule::getScormModulesForGlossary($glo_id); - foreach ($sms as $sm) - { - $link = false; - $refs = ilObject::_getAllReferences($sm); - foreach ($refs as $ref) - { - if ($link === false) - { - if ($ilAccess->checkAccess("write", "", $ref)) - { - include_once("./Services/Link/classes/class.ilLink.php"); - $link = ilLink::_getLink($ref,'sahs'); - } - } - } - - $entry = ilObject::_lookupTitle($sm); - if ($link !== false) - { - $entry = "".$entry.""; - } - - $info->addProperty($lng->txt("obj_sahs"), $entry); - } - } - - - function viewObject() - { - $ilErr = $this->error; - - if (strtolower($_GET["baseClass"]) == "iladministrationgui") - { - parent::viewObject(); - return; - } - - if (!$this->rbacsystem->checkAccess("visible,read",$this->object->getRefId())) - { - $ilErr->raiseError($this->lng->txt("permission_denied"), $ilErr->MESSAGE); - } - - } - - /** - * edit properties of object (admin form) - * - * @access public - */ - function properties() - { - $this->checkPermission("write"); - - $this->setSettingsSubTabs("general_settings"); - - $this->initSettingsForm(); - - // Edit ecs export settings - include_once 'Modules/Glossary/classes/class.ilECSGlossarySettings.php'; - $ecs = new ilECSGlossarySettings($this->object); - $ecs->addSettingsToForm($this->form, 'glo'); - - $this->tpl->setContent($this->form->getHTML()); - } - - /** - * Init settings form. - * - * @param int $a_mode Edit Mode - */ - public function initSettingsForm($a_mode = "edit") - { - $obj_service = $this->getObjectService(); - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - // title - $title = new ilTextInputGUI($this->lng->txt("title"), "title"); - $title->setRequired(true); - $this->form->addItem($title); - - // description - $desc = new ilTextAreaInputGUI($this->lng->txt("desc"), "description"); - $this->form->addItem($desc); - - $this->lng->loadLanguageModule("rep"); - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($this->lng->txt('rep_activation_availability')); - $this->form->addItem($section); - - // online - $online = new ilCheckboxInputGUI($this->lng->txt("cont_online"), "cobj_online"); - $online->setValue("y"); - $online->setInfo($this->lng->txt("glo_online_info")); - $this->form->addItem($online); - - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($this->lng->txt('glo_content_settings')); - $this->form->addItem($section); - - // glossary mode - $glo_mode = new ilRadioGroupInputGUI($this->lng->txt("glo_mode"), "glo_mode"); - //$glo_mode->setInfo($this->lng->txt("glo_mode_desc")); - $op1 = new ilRadioOption($this->lng->txt("glo_mode_normal"), "none",$this->lng->txt("glo_mode_normal_info")); - $glo_mode->addOption($op1); - $op2 = new ilRadioOption($this->lng->txt("glo_mode_level"), "level",$this->lng->txt("glo_mode_level_info")); - $glo_mode->addOption($op2); - $op3 = new ilRadioOption($this->lng->txt("glo_mode_subtree"), "subtree",$this->lng->txt("glo_mode_subtree_info")); - $glo_mode->addOption($op3); - $this->form->addItem($glo_mode); - - // glossary mode - /*$options = array( - "none"=>$this->lng->txt("glo_mode_normal"), - "level"=>$this->lng->txt("glo_mode_level"), - "subtree"=>$this->lng->txt("glo_mode_subtree") - ); - $glo_mode = new ilSelectInputGUI($this->lng->txt("glo_mode"), "glo_mode"); - $glo_mode->setOptions($options); - $glo_mode->setInfo($this->lng->txt("glo_mode_desc")); - $this->form->addItem($glo_mode);*/ - - - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($this->lng->txt('cont_presentation')); - $this->form->addItem($section); - - // tile image - $obj_service->commonSettings()->legacyForm($this->form, $this->object)->addTileImage(); - - // presentation mode - $pres_mode = new ilRadioGroupInputGUI($this->lng->txt("glo_presentation_mode"), "pres_mode"); - $pres_mode->setValue("table"); - $op1 = new ilRadioOption($this->lng->txt("glo_table_form"), "table", $this->lng->txt("glo_table_form_info")); - - // short text length - $snl = new ilNumberInputGUI($this->lng->txt("glo_text_snippet_length"), "snippet_length"); - $snl->setMaxValue(3000); - $snl->setMinValue(100); - $snl->setMaxLength(4); - $snl->setSize(4); - $snl->setInfo($this->lng->txt("glo_text_snippet_length_info")); - $snl->setValue(200); - $op1->addSubItem($snl); - - $pres_mode->addOption($op1); - $op2 = new ilRadioOption($this->lng->txt("glo_full_definitions"), "full_def", $this->lng->txt("glo_full_definitions_info")); - $pres_mode->addOption($op2); - $this->form->addItem($pres_mode); - - // show taxonomy - include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php"); - $tax_ids = ilObjTaxonomy::getUsageOfObject($this->object->getId()); - if (count($tax_ids) > 0) - { - $show_tax = new ilCheckboxInputGUI($this->lng->txt("glo_show_taxonomy"), "show_tax"); - $show_tax->setInfo($this->lng->txt("glo_show_taxonomy_info")); - $this->form->addItem($show_tax); - } - - // downloads - $down = new ilCheckboxInputGUI($this->lng->txt("cont_downloads"), "glo_act_downloads"); - $down->setValue("y"); - $down->setInfo($this->lng->txt("cont_downloads_desc")); - $this->form->addItem($down); - - if ($a_mode == "edit") - { - $title->setValue($this->object->getTitle()); - $desc->setValue($this->object->getDescription()); - $online->setChecked($this->object->getOnline()); - $glo_mode->setValue($this->object->getVirtualMode()); - $pres_mode->setValue($this->object->getPresentationMode()); - $snl->setValue($this->object->getSnippetLength()); - if (count($tax_ids) > 0) - { - $show_tax->setChecked($this->object->getShowTaxonomy()); - } - - $down->setChecked($this->object->isActiveDownloads()); - - // additional features - $feat = new ilFormSectionHeaderGUI(); - $feat->setTitle($this->lng->txt('obj_features')); - $this->form->addItem($feat); - - include_once './Services/Container/classes/class.ilContainer.php'; - include_once './Services/Object/classes/class.ilObjectServiceSettingsGUI.php'; - ilObjectServiceSettingsGUI::initServiceSettingsForm( - $this->object->getId(), - $this->form, - array( - ilObjectServiceSettingsGUI::CUSTOM_METADATA - ) - ); - } - - // sort columns, if adv fields are given - include_once("./Modules/Glossary/classes/class.ilGlossaryAdvMetaDataAdapter.php"); - $adv_ap = new ilGlossaryAdvMetaDataAdapter($this->object->getRefId()); - $cols = $adv_ap->getColumnOrder(); - if (count($cols) > 1) - { - include_once './Modules/Glossary/classes/class.ilGloAdvColSortInputGUI.php'; - $ti = new ilGloAdvColSortInputGUI($this->lng->txt("cont_col_ordering"), "field_order"); - $this->form->addItem($ti); - $ti->setValue($cols); - } - - // save and cancel commands - $this->form->addCommandButton("saveProperties", $this->lng->txt("save")); - - $this->form->setTitle($this->lng->txt("cont_glo_properties")); - $this->form->setFormAction($this->ctrl->getFormAction($this)); - } - - - /** - * save properties - */ - function saveProperties() - { - $obj_service = $this->getObjectService(); - - $this->initSettingsForm(); - if ($this->form->checkInput()) - { - $this->object->setTitle($_POST['title']); - $this->object->setDescription($_POST['description']); - $this->object->setOnline(ilUtil::yn2tf($_POST["cobj_online"])); - $this->object->setVirtualMode($_POST["glo_mode"]); -// $this->object->setActiveGlossaryMenu(ilUtil::yn2tf($_POST["glo_act_menu"])); - $this->object->setActiveDownloads(ilUtil::yn2tf($_POST["glo_act_downloads"])); - $this->object->setPresentationMode($_POST["pres_mode"]); - $this->object->setSnippetLength($_POST["snippet_length"]); - $this->object->setShowTaxonomy($_POST["show_tax"]); - $this->object->update(); - - // tile image - $obj_service->commonSettings()->legacyForm($this->form, $this->object)->saveTileImage(); - - // field order of advanced metadata - include_once("./Modules/Glossary/classes/class.ilGlossaryAdvMetaDataAdapter.php"); - $adv_ap = new ilGlossaryAdvMetaDataAdapter($this->object->getRefId()); - $cols = $adv_ap->getColumnOrder(); - if (count($cols) > 1) - { - $adv_ap->saveColumnOrder($_POST["field_order"]); - } - - // set definition short texts dirty - include_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); - ilGlossaryDefinition::setShortTextsDirty($this->object->getId()); - - include_once './Services/Object/classes/class.ilObjectServiceSettingsGUI.php'; - ilObjectServiceSettingsGUI::updateServiceSettingsForm( - $this->object->getId(), - $this->form, - array( - ilObjectServiceSettingsGUI::CUSTOM_METADATA - ) - ); - - // Update ecs export settings - include_once 'Modules/Glossary/classes/class.ilECSGlossarySettings.php'; - $ecs = new ilECSGlossarySettings($this->object); - if($ecs->handleSettingsUpdate()) - { - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "properties"); - } - - } - $this->form->setValuesByPost(); - $this->tpl->setContent($this->form->getHTML()); - } - - - /** - * list terms - */ - function listTerms() - { - if ($_GET["show_tax"]) - { - $this->showTaxonomy(); - } - - // term - include_once("./Services/Form/classes/class.ilTextInputGUI.php"); - $ti = new ilTextInputGUI($this->lng->txt("cont_new_term"), "new_term"); - $ti->setMaxLength(80); - $ti->setSize(20); - $this->toolbar->addInputItem($ti, true); - - // language - $this->lng->loadLanguageModule("meta"); - $lang = ilMDLanguageItem::_getLanguages(); - if ($_SESSION["il_text_lang_".$_GET["ref_id"]] != "") - { - $s_lang = $_SESSION["il_text_lang_".$_GET["ref_id"]]; - } - else - { - $s_lang = $this->user->getLanguage(); - } - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $si = new ilSelectInputGUI($this->lng->txt("language"), "term_language"); - $si->setOptions($lang); - $si->setValue($s_lang); - $this->toolbar->addInputItem($si, true); - - $this->toolbar->setFormAction($this->ctrl->getFormAction($this)); - $this->toolbar->addFormButton($this->lng->txt("glo_add_new_term"), "addTerm"); - - $this->toolbar->addSeparator(); - - //ilEditClipboard::getAction() == "copy" - include_once("./Modules/LearningModule/classes/class.ilEditClipboard.php"); - if ($this->user->clipboardHasObjectsOfType("term")) - { - $this->toolbar->addButton($this->lng->txt("paste"), - $this->ctrl->getLinkTarget($this, "pasteTerms")); - $this->toolbar->addButton($this->lng->txt("clear_clipboard"), - $this->ctrl->getLinkTarget($this, "clearClipboard")); - } - else - { - $this->toolbar->addButton($this->lng->txt("glo_add_from_other"), - $this->ctrl->getLinkTargetByClass("ilglossaryforeigntermcollectorgui", "")); - } - - if (is_object($this->tax)) - { - $this->toolbar->addSeparator(); - if ($_GET["show_tax"]) - { - $this->toolbar->addButton($this->lng->txt("glo_hide_taxonomy"), - $this->ctrl->getLinkTarget($this, "deactTaxonomy")); - } - else - { - $this->toolbar->addButton($this->lng->txt("glo_show_taxonomy"), - $this->ctrl->getLinkTarget($this, "actTaxonomy")); - } - } - - include_once("./Modules/Glossary/classes/class.ilTermListTableGUI.php"); - $tab = new ilTermListTableGUI($this, "listTerms", $this->tax_node); - $this->tpl->setContent($tab->getHTML()); - } - - /** - * Show Taxonomy - * - * @param - * @return - */ - function actTaxonomy() - { - $this->ctrl->setParameter($this, "show_tax", 1); - $this->ctrl->redirect($this, "listTerms"); - } - - /** - * Hide Taxonomy - * - * @param - * @return - */ - function deactTaxonomy() - { - $this->ctrl->setParameter($this, "show_tax", ""); - $this->ctrl->redirect($this, "listTerms"); - } - - - /** - * show possible action (form buttons) - * - * @access public - */ - function showActions($a_actions) - { - foreach ($a_actions as $name => $lng) - { - $d[$name] = array("name" => $name, "lng" => $lng); - } - - $notoperations = array(); - $operations = array(); - - $operations = $d; - - if (count($operations) > 0) - { - foreach ($operations as $val) - { - $this->tpl->setCurrentBlock("tbl_action_btn"); - $this->tpl->setVariable("BTN_NAME", $val["name"]); - $this->tpl->setVariable("BTN_VALUE", $this->lng->txt($val["lng"])); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setCurrentBlock("tbl_action_row"); - $this->tpl->setVariable("IMG_ARROW",ilUtil::getImagePath("arrow_downright.svg")); - $this->tpl->parseCurrentBlock(); - } - } - - /** - * add term - */ - function addTerm() - { - if (trim($_POST["new_term"]) == "") - { - ilUtil::sendFailure($this->lng->txt("cont_please_enter_a_term"), true); - $this->ctrl->redirect($this, "listTerms"); - } - - // add term - include_once ("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - $term = new ilGlossaryTerm(); - $term->setGlossary($this->object); - $term->setTerm(ilUtil::stripSlashes($_POST["new_term"])); - $term->setLanguage($_POST["term_language"]); - $_SESSION["il_text_lang_".$_GET["ref_id"]] = $_POST["term_language"]; - $term->create(); - - // add first definition - $def = new ilGlossaryDefinition(); - $def->setTermId($term->getId()); - $def->setTitle(ilUtil::stripSlashes($_POST["new_term"])); - $def->create(); - - $this->ctrl->setParameterByClass("ilglossarydefpagegui", "term_id", $term->getId()); - $this->ctrl->setParameterByClass("ilglossarydefpagegui", "def", $def->getId()); - $this->ctrl->redirectByClass(array("ilglossarytermgui", - "iltermdefinitioneditorgui", "ilglossarydefpagegui"), "edit"); - } - - /** - * move a definiton up - */ - function moveDefinitionUp() - { - include_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); - - $definition = new ilGlossaryDefinition($_GET["def"]); - $definition->moveUp(); - - $this->ctrl->redirect($this, "listTerms"); - } - - /** - * move a definiton down - */ - function moveDefinitionDown() - { - include_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); - - $definition = new ilGlossaryDefinition($_GET["def"]); - $definition->moveDown(); - - $this->ctrl->redirect($this, "listTerms"); - } - - /** - * deletion confirmation screen - */ - function confirmDefinitionDeletion() - { - //$this->getTemplate(); - //$this->displayLocator(); - //$this->setTabs(); - - $term = new ilGlossaryTerm($this->term_id); - - $add = ""; - $nr = ilGlossaryTerm::getNumberOfUsages($this->term_id); - if ($nr > 0) - { - $this->ctrl->setParameterByClass("ilglossarytermgui", - "term_id", $this->term_id); - $link = "[".$this->lng->txt("glo_list_usages")."]"; - $add = "
".sprintf($this->lng->txt("glo_term_is_used_n_times"), $nr)." ".$link; - } - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setHeaderText($this->lng->txt("info_delete_sure").$add); - - $cgui->setFormAction($this->ctrl->getFormAction($this)); - $cgui->setCancel($this->lng->txt("cancel"), "cancelDefinitionDeletion"); - $cgui->setConfirm($this->lng->txt("confirm"), "deleteDefinition"); - - // content style - $this->setContentStyleSheet($this->tpl); - - // syntax style - $this->tpl->setCurrentBlock("SyntaxStyle"); - $this->tpl->setVariable("LOCATION_SYNTAX_STYLESHEET", - ilObjStyleSheet::getSyntaxStylePath()); - $this->tpl->parseCurrentBlock(); - - $definition = new ilGlossaryDefinition($_GET["def"]); - $page_gui = new ilGlossaryDefPageGUI($definition->getId()); - $page_gui->setTemplateOutput(false); - $page_gui->setStyleId($this->object->getStyleSheetId()); - $page_gui->setSourcecodeDownloadScript("ilias.php?baseClass=ilGlossaryPresentationGUI&ref_id=".$_GET["ref_id"]); - $page_gui->setFileDownloadLink("ilias.php?baseClass=ilGlossaryPresentationGUI&ref_id=".$_GET["ref_id"]); - $page_gui->setFullscreenLink("ilias.php?baseClass=ilGlossaryPresentationGUI&ref_id=".$_GET["ref_id"]); - $output = $page_gui->preview(); - - $cgui->addItem("def", $_GET["def"], $term->getTerm().$output); - - $this->tpl->setContent($cgui->getHTML()); - } - - function cancelDefinitionDeletion() - { - $this->ctrl->redirect($this, "listTerms"); - } - - - function deleteDefinition() - { - $definition = new ilGlossaryDefinition($_REQUEST["def"]); - $definition->delete(); - $this->ctrl->redirect($this, "listTerms"); - } - - /** - * edit term - */ - function editTerm() - { - // deprecated - } - - - /** - * update term - */ - function updateTerm() - { - $term = new ilGlossaryTerm($this->term_id); - - $term->setTerm(ilUtil::stripSlashes($_POST["term"])); - $term->setLanguage($_POST["term_language"]); - $term->update(); - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"),true); - $this->ctrl->redirect($this, "listTerms"); - } - - - - /** - * export content object - */ - function export() - { - $this->checkPermission("write"); - - require_once("./Modules/Glossary/classes/class.ilGlossaryExport.php"); - $glo_exp = new ilGlossaryExport($this->object); - $glo_exp->buildExportFile(); - $this->ctrl->redirectByClass("ilexportgui", ""); - } - - /** - * create html package - */ - function exportHTML() - { - require_once("./Modules/Glossary/classes/class.ilGlossaryExport.php"); - $glo_exp = new ilGlossaryExport($this->object, "html"); - $glo_exp->buildExportFile(); -//echo $this->tpl->get(); - $this->ctrl->redirectByClass("ilexportgui", ""); - } - - /** - * download export file - */ - function publishExportFile() - { - $ilErr = $this->error; - - if(!isset($_POST["file"])) - { - $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); - } - if (count($_POST["file"]) > 1) - { - $ilErr->raiseError($this->lng->txt("cont_select_max_one_item"), $ilErr->MESSAGE); - } - - $file = explode(":", $_POST["file"][0]); - $export_dir = $this->object->getExportDirectory($file[0]); - - if ($this->object->getPublicExportFile($file[0]) == - $file[1]) - { - $this->object->setPublicExportFile($file[0], ""); - } - else - { - $this->object->setPublicExportFile($file[0], $file[1]); - } - $this->object->update(); - $this->ctrl->redirectByClass("ilexportgui", ""); - } - - /* - * list all export files - */ - function viewExportLog() - { - } - - /** - * confirm term deletion - */ - function confirmTermDeletion() - { - //$this->prepareOutput(); - if (!isset($_POST["id"])) - { - ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); - $this->ctrl->redirect($this, "listTerms"); - } - - // check ids - include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - include_once("./Modules/Glossary/classes/class.ilGlossaryTermReferences.php"); - foreach ($_POST["id"] as $term_id) - { - $term_glo_id = ilGlossaryTerm::_lookGlossaryID((int) $term_id); - if ($term_glo_id != $this->object->getId() && !ilGlossaryTermReferences::isReferenced($this->object->getId(), $term_id)) - { - ilUtil::sendFailure($this->lng->txt("glo_term_must_belong_to_glo"), true); - $this->ctrl->redirect($this, "listTerms"); - } - } - - // display confirmation message - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($this->ctrl->getFormAction($this)); - $cgui->setHeaderText($this->lng->txt("info_delete_sure")); - $cgui->setCancel($this->lng->txt("cancel"), "cancelTermDeletion"); - $cgui->setConfirm($this->lng->txt("confirm"), "deleteTerms"); - - include_once("./Modules/Glossary/classes/class.ilGlossaryTermReferences.php"); - - foreach($_POST["id"] as $id) - { - $term = new ilGlossaryTerm($id); - - $add = ""; - $nr = ilGlossaryTerm::getNumberOfUsages($id); - if ($nr > 0) - { - $this->ctrl->setParameterByClass("ilglossarytermgui", - "term_id", $id); - - if (ilGlossaryTermReferences::isReferenced($this->object->getId(), $id)) - { - $add = " (".$this->lng->txt("glo_term_reference").")"; - } - else - { - $link = "[".$this->lng->txt("glo_list_usages")."]"; - $add = "
". - sprintf($this->lng->txt("glo_term_is_used_n_times"), $nr)." ".$link."
"; - - } - } - - $cgui->addItem("id[]", $id, $term->getTerm().$add); - } - - $this->tpl->setContent($cgui->getHTML()); - } - - /** - * cancel deletion of object - * - * @access public - */ - function cancelTermDeletion() - { - $this->ctrl->redirect($this, "listTerms"); - } - - /** - * delete selected terms - */ - function deleteTerms() - { - include_once("./Modules/Glossary/classes/class.ilGlossaryTermReferences.php"); - foreach($_POST["id"] as $id) - { - if (ilGlossaryTermReferences::isReferenced($this->object->getId(), $id)) - { - $refs = new ilGlossaryTermReferences($this->object->getId()); - $refs->deleteTerm($id); - $refs->update(); - } - else - { - $term = new ilGlossaryTerm($id); - $term->delete(); - } - } - $this->ctrl->redirect($this, "listTerms"); - } - - /** - * set Locator - * - * @param object tree object - * @param integer reference id - * @access public - */ - function setLocator($a_tree = "", $a_id = "") - { - if(strtolower($_GET["baseClass"]) != "ilglossaryeditorgui") - { - parent::setLocator($a_tree, $a_id); - } - else - { - if(is_object($this->object)) - { - require_once("./Modules/Glossary/classes/class.ilGlossaryLocatorGUI.php"); - $gloss_loc = new ilGlossaryLocatorGUI(); - if (is_object($this->term)) - { - $gloss_loc->setTerm($this->term); - } - $gloss_loc->setGlossary($this->object); - //$gloss_loc->setDefinition($this->definition); - $gloss_loc->display(); - } - } - - } - - /** - * view content - */ - function view() - { - //$this->prepareOutput(); - $this->viewObject(); - } - - /** - * create new (subobject) in glossary - */ - function create() - { - switch($_POST["new_type"]) - { - case "term": - $term_gui = new ilGlossaryTermGUI(); - $term_gui->create(); - break; - } - } - - function saveTerm() - { - $term_gui = new ilGlossaryTermGUI(); - $term_gui->setGlossary($this->object); - $term_gui->save(); - - ilUtil::sendSuccess($this->lng->txt("cont_added_term"),true); - - //ilUtil::redirect("glossary_edit.php?ref_id=".$_GET["ref_id"]."&cmd=listTerms"); - $this->ctrl->redirect($this, "listTerms"); - } - - - /** - * add definition - */ - function addDefinition() - { - $term_id = (int) $_GET["term_id"]; - - include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - $term_glo_id = ilGlossaryTerm::_lookGlossaryID((int) $term_id); - if ($term_glo_id != $this->object->getId()) - { - ilUtil::sendFailure($this->lng->txt("glo_term_must_belong_to_glo"), true); - $this->ctrl->redirect($this, "listTerms"); - } - - // add term - include_once ("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - $term = new ilGlossaryTerm($term_id); - - // add first definition - $def = new ilGlossaryDefinition(); - $def->setTermId($term->getId()); - $def->setTitle(ilUtil::stripSlashes($term->getTerm())); - $def->create(); - - $this->ctrl->setParameterByClass("ilglossarydefpagegui", "term_id", $term->getId()); - $this->ctrl->setParameterByClass("ilglossarydefpagegui", "def", $def->getId()); - $this->ctrl->redirectByClass(array("ilglossarytermgui", - "iltermdefinitioneditorgui", "ilglossarydefpagegui"), "edit"); - - } - - function getTemplate() - { - $this->tpl->getStandardTemplate(); - - $title = $this->object->getTitle(); - - - if ($this->term_id > 0) - { - $this->tpl->setTitle($this->lng->txt("term").": ". - ilGlossaryTerm::_lookGlossaryTerm($this->term_id)); - } - else - { - parent::setTitleAndDescription(); - $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_glo.svg")); - $this->tpl->setTitle($this->lng->txt("glo").": ".$title); - } - } - - /** - * output tabs - */ - function setTabs() - { - $this->getTabs(); - } - - /** - * get tabs - */ - function getTabs() - { - $this->help->setScreenIdComponent("glo"); - - // list terms - $force_active = ($_GET["cmd"] == "" || $_GET["cmd"] == "listTerms") - ? true - : false; - $this->tabs_gui->addTarget("cont_terms", - $this->ctrl->getLinkTarget($this, "listTerms"), array("listTerms", ""), - get_class($this), "", $force_active); - - $force_active = false; - if ($this->ctrl->getCmd() == "showSummary" || - strtolower($this->ctrl->getNextClass()) == "ilinfoscreengui") - { - $force_active = true; - } - $this->tabs_gui->addTarget("info_short", - $this->ctrl->getLinkTargetByClass("ilinfoscreengui", "showSummary"), "", - "ilInfoScreenGUI", "", $force_active); - - // properties - if ($this->rbacsystem->checkAccess('write',$this->object->getRefId())) - { - $this->tabs_gui->addTarget("settings", - $this->ctrl->getLinkTarget($this, "properties"), "properties", - get_class($this)); - - // meta data - include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php"; - $mdgui = new ilObjectMetaDataGUI($this->object, "term"); - $mdtab = $mdgui->getTab(); - if($mdtab) - { - $this->tabs_gui->addTarget("meta_data", $mdtab, - "", "ilobjectmetadatagui"); - } - - // export - /*$tabs_gui->addTarget("export", - $this->ctrl->getLinkTarget($this, "exportList"), - array("exportList", "viewExportLog"), get_class($this));*/ - - // export - $this->tabs_gui->addTarget("export", - $this->ctrl->getLinkTargetByClass("ilexportgui", ""), - "", "ilexportgui"); - } - - // permissions - if ($this->rbacsystem->checkAccess('edit_permission',$this->object->getRefId())) - { - /*$tabs_gui->addTarget("permission_settings", - $this->ctrl->getLinkTarget($this, "perm"), - array("perm", "info"), - get_class($this)); - */ - $this->tabs_gui->addTarget("perm_settings", - $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm"), array("perm","info","owner"), 'ilpermissiongui'); - - } - - $this->tabs_gui->addNonTabbedLink("presentation_view", - $this->lng->txt("glo_presentation_view"), - "ilias.php?baseClass=ilGlossaryPresentationGUI&ref_id=".$this->object->getRefID(), - "_top" - ); - - } - - /** - * Set sub tabs - */ - function setSettingsSubTabs($a_active) - { - if (in_array($a_active, - array("general_settings", "style", "taxonomy", "glossaries"))) - { - // general properties - $this->tabs->addSubTab("general_settings", - $this->lng->txt("settings"), - $this->ctrl->getLinkTarget($this, 'properties')); - - // style properties - $this->tabs->addSubTab("style", - $this->lng->txt("obj_sty"), - $this->ctrl->getLinkTarget($this, 'editStyleProperties')); - - // taxonomy - include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php"); - ilObjTaxonomy::loadLanguageModule(); - $this->tabs->addSubTab("taxonomy", - $this->lng->txt("tax_taxonomy"), - $this->ctrl->getLinkTargetByClass("ilobjtaxonomygui", '')); - - // style properties - $this->tabs->addSubTab("glossaries", - $this->lng->txt("cont_auto_glossaries"), - $this->ctrl->getLinkTarget($this, 'editGlossaries')); - - $this->tabs->activateSubTab($a_active); - } - } - - - /** - * redirect script - * - * @param string $a_target - */ - public static function _goto($a_target) - { - global $DIC; - - $lng = $DIC->language(); - $ilAccess = $DIC->access(); - $ilErr = $DIC["ilErr"]; - - if ($ilAccess->checkAccess("read", "", $a_target)) - { - $_GET["ref_id"] = $a_target; - $_GET["baseClass"] = "ilGlossaryPresentationGUI"; - include("ilias.php"); - exit; - } - else if ($ilAccess->checkAccess("visible", "", $a_target)) - { - $_GET["ref_id"] = $a_target; - $_GET["cmd"] = "infoScreen"; - $_GET["baseClass"] = "ilGlossaryPresentationGUI"; - include("ilias.php"); - exit; - } - else if ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) - { - ilUtil::sendFailure(sprintf($lng->txt("msg_no_perm_read_item"), - ilObject::_lookupTitle(ilObject::_lookupObjId($a_target))), true); - ilObjectGUI::_gotoRepositoryRoot(); - } - - $ilErr->raiseError($lng->txt("msg_no_perm_read_lm"), $ilErr->FATAL); - } - - /** - * Apply filter - */ - function applyFilter() - { - include_once("./Modules/Glossary/classes/class.ilTermListTableGUI.php"); - $prtab = new ilTermListTableGUI($this, "listTerms", $this->tax_node); - $prtab->resetOffset(); - $prtab->writeFilterToSession(); - $this->listTerms(); - } - - /** - * Reset filter - * (note: this function existed before data table filter has been introduced - */ - function resetFilter() - { - include_once("./Modules/Glossary/classes/class.ilTermListTableGUI.php"); - $prtab = new ilTermListTableGUI($this, "listTerms", $this->tax_node); - $prtab->resetOffset(); - $prtab->resetFilter(); - $this->listTerms(); - } - - - //// - //// Style related functions - //// - - /** - * Set content style sheet - */ - function setContentStyleSheet($a_tpl = null) - { - if ($a_tpl != null) - { - $ctpl = $a_tpl; - } - else - { - $ctpl = $this->tpl; - } - - $ctpl->setCurrentBlock("ContentStyle"); - $ctpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->object->getStyleSheetId())); - $ctpl->parseCurrentBlock(); - } - - - /** - * Edit style properties - */ - function editStyleProperties() - { - $this->checkPermission("write"); - - $this->initStylePropertiesForm(); - $this->tpl->setContent($this->form->getHTML()); - - $this->tabs->activateTab("settings"); - $this->setSettingsSubTabs("style"); - } - - /** - * Init style properties form - */ - function initStylePropertiesForm() - { - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $this->lng->loadLanguageModule("style"); - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - $fixed_style = $this->setting->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").")"); - $this->form->addItem($st); - } - else - { - $st_styles = ilObjStyleSheet::_getStandardStyles(true, false, - $_GET["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)); - $this->form->addItem($st); - -//$this->ctrl->getLinkTargetByClass("ilObjStyleSheetGUI", "edit")); - - // delete command - $this->form->addCommandButton("editStyle", - $this->lng->txt("style_edit_style")); - $this->form->addCommandButton("deleteStyle", - $this->lng->txt("style_delete_style")); -//$this->ctrl->getLinkTargetByClass("ilObjStyleSheetGUI", "delete")); - } - } - - if ($style_id <= 0 || ilObjStyleSheet::_lookupStandard($style_id)) - { - $style_sel = ilUtil::formSelect ($style_id, "style_id", - $st_styles, false, true); - $style_sel = new ilSelectInputGUI($this->lng->txt("style_current_style"), "style_id"); - $style_sel->setOptions($st_styles); - $style_sel->setValue($style_id); - $this->form->addItem($style_sel); -//$this->ctrl->getLinkTargetByClass("ilObjStyleSheetGUI", "create")); - $this->form->addCommandButton("saveStyleSettings", - $this->lng->txt("save")); - $this->form->addCommandButton("createStyle", - $this->lng->txt("sty_create_ind_style")); - } - } - $this->form->setTitle($this->lng->txt("glo_style")); - $this->form->setFormAction($this->ctrl->getFormAction($this)); - } - - /** - * Create Style - */ - function createStyle() - { - $this->ctrl->redirectByClass("ilobjstylesheetgui", "create"); - } - - /** - * Edit Style - */ - function editStyle() - { - $this->ctrl->redirectByClass("ilobjstylesheetgui", "edit"); - } - - /** - * Delete Style - */ - function deleteStyle() - { - $this->ctrl->redirectByClass("ilobjstylesheetgui", "delete"); - } - - /** - * Save style settings - */ - function saveStyleSettings() - { - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - if ($this->setting->get("fixed_content_style_id") <= 0 && - (ilObjStyleSheet::_lookupStandard($this->object->getStyleSheetId()) - || $this->object->getStyleSheetId() == 0)) - { - $this->object->setStyleSheetId(ilUtil::stripSlashes($_POST["style_id"])); - $this->object->update(); - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - } - $this->ctrl->redirect($this, "editStyleProperties"); - } - - /** - * Get public access value for export table - */ - function getPublicAccessColValue($a_type, $a_file) - { - if ($this->object->getPublicExportFile($a_type) == $a_file) - { - return $this->lng->txt("yes"); - } - - return " "; - } - - /** - * Show taxonomy - * - * @param - * @return - */ - function showTaxonomy() - { - include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php"); - $tax_ids = ilObjTaxonomy::getUsageOfObject($this->object->getId()); - if (count($tax_ids) > 0) - { - include_once("./Services/Taxonomy/classes/class.ilTaxonomyExplorerGUI.php"); - $tax_exp = new ilTaxonomyExplorerGUI($this, "showTaxonomy", $tax_ids[0], - "ilobjglossarygui", "listTerms"); - if (!$tax_exp->handleCommand()) - { - //$this->tpl->setLeftNavContent($tax_exp->getHTML()); - $this->tpl->setLeftNavContent($tax_exp->getHTML()." "); - } - } - - } - - // - // Auto glossaries - // - - /** - * Edit automatically linked glossaries - * - * @param - * @return - */ - function editGlossaries() - { - $this->tabs->setTabActive("settings"); - $this->setSettingsSubTabs("glossaries"); - - $this->toolbar->addButton($this->lng->txt("add"), - $this->ctrl->getLinkTarget($this, "showGlossarySelector")); - - include_once("./Modules/Glossary/classes/class.ilGlossaryAutoLinkTableGUI.php"); - $tab = new ilGlossaryAutoLinkTableGUI($this->object, $this, "editGlossaries"); - - $this->tpl->setContent($tab->getHTML()); - } - - /** - * Select LM Glossary - * - * @param - * @return - */ - function showGlossarySelector() - { - $this->tabs->setTabActive("settings"); - $this->setSettingsSubTabs("glossaries"); - - include_once 'Services/Search/classes/class.ilSearchRootSelector.php'; - - $exp = new ilSearchRootSelector($this->ctrl->getLinkTarget($this,'showGlossarySelector')); - $exp->setExpand($_GET["search_root_expand"] ? $_GET["search_root_expand"] : $this->tree->readRootId()); - $exp->setExpandTarget($this->ctrl->getLinkTarget($this,'showGlossarySelector')); - $exp->setTargetClass(get_class($this)); - $exp->setCmd('confirmGlossarySelection'); - $exp->setClickableTypes(array("glo")); - $exp->addFilter("glo"); - - // build html-output - $exp->setOutput(0); - $this->tpl->setContent($exp->getOutput()); - - } - - /** - * Confirm glossary selection - */ - function confirmGlossarySelection() - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $this->ctrl->setParameter($this, "glo_ref_id", $_GET["root_id"]); - $cgui->setFormAction($this->ctrl->getFormAction($this)); - $cgui->setHeaderText($this->lng->txt("glo_link_glo_in_glo")); - $cgui->setCancel($this->lng->txt("no"), "selectGlossary"); - $cgui->setConfirm($this->lng->txt("yes"), "selectGlossaryLink"); - $this->tpl->setContent($cgui->getHTML()); - } - - /** - * Select a glossary and link all its terms - * - * @param - * @return - */ - function selectGlossaryLink() - { - $glo_ref_id = (int) $_GET["glo_ref_id"]; - $glo_id = ilObject::_lookupObjId($glo_ref_id); - $this->object->autoLinkGlossaryTerms($glo_ref_id); - $this->selectGlossary(); - } - - - /** - * Select lm glossary - * - * @param - * @return - */ - function selectGlossary() - { - $glos = $this->object->getAutoGlossaries(); - $glo_ref_id = (int) $_GET["glo_ref_id"]; - $glo_id = ilObject::_lookupObjId($glo_ref_id); - if (!in_array($glo_id, $glos)) - { - $glos[] = $glo_id; - } - $this->object->setAutoGlossaries($glos); - $this->object->update(); - - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "editGlossaries"); - } - - /** - * Remove lm glossary - * - * @param - * @return - */ - function removeGlossary() - { - $this->object->removeAutoGlossary((int) $_GET["glo_id"]); - $this->object->update(); - - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "editGlossaries"); - } - - /** - * Copy terms - * - * @param - * @return - */ - function copyTerms() - { - $items = ilUtil::stripSlashesArray($_POST["id"]); - if (!is_array($items)) - { - ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); - $this->ctrl->redirect($this, "listTerms"); - } - - include_once("./Modules/LearningModule/classes/class.ilEditClipboard.php"); - $this->user->clipboardDeleteObjectsOfType("term"); - - // put them into the clipboard - $time = date("Y-m-d H:i:s", time()); - $order = 0; - foreach ($items as $id) - { - $this->user->addObjectToClipboard($id, - "term", ilGlossaryTerm::_lookGlossaryTerm($id), 0, $time, $order); - } - - ilEditClipboard::setAction("copy"); - ilUtil::sendInfo($this->lng->txt("glo_selected_terms_have_been_copied"), true); - $this->ctrl->redirect($this, "listTerms"); - } - - /** - * Reference terms - * - * @param - * @return - */ - function referenceTerms() - { - $items = ilUtil::stripSlashesArray($_POST["id"]); - if (!is_array($items)) - { - ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); - $this->ctrl->redirect($this, "listTerms"); - } - - include_once("./Modules/LearningModule/classes/class.ilEditClipboard.php"); - $this->user->clipboardDeleteObjectsOfType("term"); - - // put them into the clipboard - $time = date("Y-m-d H:i:s", time()); - $order = 0; - foreach ($items as $id) - { - $this->user->addObjectToClipboard($id, - "term", ilGlossaryTerm::_lookGlossaryTerm($id), 0, $time, $order); - } - - ilEditClipboard::setAction("link"); - ilUtil::sendInfo($this->lng->txt("glo_selected_terms_have_been_copied"), true); - $this->ctrl->redirect($this, "listTerms"); - } - - - /** - * Clear clipboard - * - * @param - * @return - */ - function clearClipboard() - { - $this->user->clipboardDeleteObjectsOfType("term"); - $this->ctrl->redirect($this, "listTerms"); - } - - /** - * Paste Terms - */ - function pasteTerms() - { - include_once("./Modules/LearningModule/classes/class.ilEditClipboard.php"); - if (ilEditClipboard::getAction() == "copy") - { - foreach ($this->user->getClipboardObjects("term") as $item) - { - ilGlossaryTerm::_copyTerm($item["id"], $this->object->getId()); - } - } - if (ilEditClipboard::getAction() == "link") - { - include_once("./Modules/Glossary/classes/class.ilGlossaryTermReferences.php"); - $refs = new ilGlossaryTermReferences($this->object->getId()); - foreach ($this->user->getClipboardObjects("term") as $item) - { - $refs->addTerm($item["id"]); - } - $refs->update(); - } - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "listTerms"); - } - - + $this->ctrl->setReturn($this, "listTerms"); + $term_gui = new ilGlossaryTermGUI($this->term_id); + $term_gui->setGlossary($this->object); + //$ret = $term_gui->executeCommand(); + $ret = $this->ctrl->forwardCommand($term_gui); + break; + + case "ilinfoscreengui": + $this->addHeaderAction(); + $this->showInfoScreen(); + 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" || $_GET["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 'ilpermissiongui': + if (strtolower($_GET["baseClass"]) == "iladministrationgui") { + $this->prepareOutput(); + } else { + $this->getTemplate(); + $this->setTabs(); + $this->setLocator(); + $this->addHeaderAction(); + } + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $ret = $this->ctrl->forwardCommand($perm_gui); + break; + + case "ilcommonactiondispatchergui": + include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); + $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); + $this->ctrl->forwardCommand($gui); + break; + + case "ilobjtaxonomygui": + $this->getTemplate(); + $this->setTabs(); + $this->setLocator(); + $this->addHeaderAction(); + $this->tabs->activateTab("settings"); + $this->setSettingsSubTabs("taxonomy"); + + include_once("./Services/Taxonomy/classes/class.ilObjTaxonomyGUI.php"); + $this->ctrl->setReturn($this, "properties"); + $tax_gui = new ilObjTaxonomyGUI(); + $tax_gui->setMultiple(false); + + /*include_once("./Modules/Glossary/classes/class.ilTermTaxInfo.php"); + $term_info = new ilTermTaxInfo();*/ + //$tax_gui->activateAssignedItemSorting($term_info, "glo", "term"); + + $tax_gui->setAssignedObject($this->object->getId()); + $ret = $this->ctrl->forwardCommand($tax_gui); + break; + + case "ilexportgui": + $this->getTemplate(); + $this->setTabs(); + $this->tabs->activateTab("export"); + $this->setLocator(); + include_once("./Services/Export/classes/class.ilExportGUI.php"); + $exp_gui = new ilExportGUI($this); + //$exp_gui->addFormat("xml", "", $this, "export"); + $exp_gui->addFormat("xml"); + $exp_gui->addFormat("html", "", $this, "exportHTML"); + $exp_gui->addCustomColumn( + $this->lng->txt("cont_public_access"), + $this, + "getPublicAccessColValue" + ); + $exp_gui->addCustomMultiCommand( + $this->lng->txt("cont_public_access"), + $this, + "publishExportFile" + ); + $ret = $this->ctrl->forwardCommand($exp_gui); + break; + + case 'ilobjectcopygui': + $this->prepareOutput(); + include_once './Services/Object/classes/class.ilObjectCopyGUI.php'; + $cp = new ilObjectCopyGUI($this); + $cp->setType('glo'); + $this->ctrl->forwardCommand($cp); + break; + + case "ilglossaryforeigntermcollectorgui": + $this->ctrl->setReturn($this, ""); + $this->getTemplate(); + $this->setTabs(); + $this->setLocator(); + $this->addHeaderAction(); + include_once("./Modules/Glossary/classes/class.ilGlossaryForeignTermCollectorGUI.php"); + $coll = ilGlossaryForeignTermCollectorGUI::getInstance($this); + $this->ctrl->forwardCommand($coll); + break; + + default: + $cmd = $this->ctrl->getCmd("listTerms"); + + if (($cmd == "create") && ($_POST["new_type"] == "term")) { + $this->ctrl->setCmd("create"); + $this->ctrl->setCmdClass("ilGlossaryTermGUI"); + $ret = $this->executeCommand(); + return; + } else { + if (!in_array($cmd, array("quickList"))) { + if (strtolower($_GET["baseClass"]) == "iladministrationgui" || + $this->getCreationMode() == true) { + $this->prepareOutput(); + $cmd.= "Object"; + } else { + $this->getTemplate(); + $this->setTabs(); + $this->setLocator(); + $this->addHeaderAction(); + + if ($cmd == "redrawHeaderAction") { + $cmd = "redrawHeaderActionObject"; + } + } + } + $ret = $this->$cmd(); + } + break; + } + + if (!in_array($cmd, array("quickList"))) { + if (strtolower($_GET["baseClass"]) != "iladministrationgui") { + if (!$this->getCreationMode()) { + $this->tpl->show(); + } + } + } else { + $this->tpl->show(false); + } + } + + public function assignObject() + { + include_once("./Modules/Glossary/classes/class.ilObjGlossary.php"); + + $this->object = new ilObjGlossary($this->id, true); + } + + /*protected function initCreationForms($a_new_type) + { + $forms = array( + self::CFORM_NEW => $this->initCreateForm($a_new_type), + self::CFORM_IMPORT => $this->initImportForm($a_new_type) + ); + + return $forms; + }*/ + + public function initCreateForm($a_new_type) + { + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setTarget("_top"); + $form->setFormAction($this->ctrl->getFormAction($this)); + $form->setTitle($this->lng->txt($a_new_type . "_new")); + + // title + $ti = new ilTextInputGUI($this->lng->txt("title"), "title"); + $ti->setSize(min(40, ilObject::TITLE_LENGTH)); + $ti->setMaxLength(ilObject::TITLE_LENGTH); + $ti->setRequired(true); + $form->addItem($ti); + + // description + $ta = new ilTextAreaInputGUI($this->lng->txt("description"), "desc"); + $ta->setCols(40); + $ta->setRows(2); + $form->addItem($ta); + + // mode + $stati = array( + "none"=>$this->lng->txt("glo_mode_normal"), + "level"=>$this->lng->txt("glo_mode_level"), + "subtree"=>$this->lng->txt("glo_mode_subtree") + ); + $tm = new ilSelectInputGUI($this->lng->txt("glo_mode"), "glo_mode"); + $tm->setOptions($stati); + $tm->setInfo($this->lng->txt("glo_mode_desc")); + $tm->setRequired(true); + $form->addItem($tm); + + $form->addCommandButton("save", $this->lng->txt($a_new_type . "_add")); + $form->addCommandButton("cancel", $this->lng->txt("cancel")); + + return $form; + } + + public function importObject() + { + $this->createObject(); + } + + /** + * save new content object to db + */ + public function saveObject() + { + $ilErr = $this->error; + + $new_type = $_REQUEST["new_type"]; + + // create permission is already checked in createObject. This check here is done to prevent hacking attempts + if (!$this->checkPermissionBool("create", "", $new_type)) { + $ilErr->raiseError($this->lng->txt("no_create_permission"), $ilErr->MESSAGE); + } + + $this->lng->loadLanguageModule($new_type); + $this->ctrl->setParameter($this, "new_type", $new_type); + + $form = $this->initCreateForm($new_type); + if ($form->checkInput()) { + $this->ctrl->setParameter($this, "new_type", ""); + + include_once("./Modules/Glossary/classes/class.ilObjGlossary.php"); + $newObj = new ilObjGlossary(); + $newObj->setType($new_type); + $newObj->setTitle($form->getInput("title")); + $newObj->setDescription($form->getInput("desc")); + $newObj->setVirtualMode($form->getInput("glo_mode")); + $newObj->create(); + + $this->putObjectInTree($newObj); + + // always send a message + ilUtil::sendSuccess($this->lng->txt("glo_added"), true); + ilUtil::redirect("ilias.php?baseClass=ilGlossaryEditorGUI&ref_id=" . $newObj->getRefId()); + } + + // display only this form to correct input + $form->setValuesByPost(); + $this->tpl->setContent($form->getHtml()); + } + + /** + * Show info screen + * + * @param + * @return + */ + public function showInfoScreen() + { + $this->getTemplate(); + $this->setTabs(); + $this->setLocator(); + $this->lng->loadLanguageModule("meta"); + include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); + + $info = new ilInfoScreenGUI($this); + $info->enablePrivateNotes(); + $info->enableNews(); + if ($this->access->checkAccess("write", "", $_GET["ref_id"])) { + $info->enableNewsEditing(); + $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->addMetaDataSections($this->object->getId(), 0, $this->object->getType()); + + ilObjGlossaryGUI::addUsagesToInfo($info, $this->object->getId()); + + $this->ctrl->forwardCommand($info); + } + + /** + * Add usages to info + * + * @param + * @return + */ + public static function addUsagesToInfo($info, $glo_id) + { + global $DIC; + + $lng = $DIC->language(); + $ilAccess = $DIC->access(); + + $info->addSection($lng->txt("glo_usages")); + include_once("./Modules/ScormAicc/classes/class.ilObjSAHSLearningModule.php"); + $sms = ilObjSAHSLearningModule::getScormModulesForGlossary($glo_id); + foreach ($sms as $sm) { + $link = false; + $refs = ilObject::_getAllReferences($sm); + foreach ($refs as $ref) { + if ($link === false) { + if ($ilAccess->checkAccess("write", "", $ref)) { + include_once("./Services/Link/classes/class.ilLink.php"); + $link = ilLink::_getLink($ref, 'sahs'); + } + } + } + + $entry = ilObject::_lookupTitle($sm); + if ($link !== false) { + $entry = "" . $entry . ""; + } + + $info->addProperty($lng->txt("obj_sahs"), $entry); + } + } + + + public function viewObject() + { + $ilErr = $this->error; + + if (strtolower($_GET["baseClass"]) == "iladministrationgui") { + parent::viewObject(); + return; + } + + if (!$this->rbacsystem->checkAccess("visible,read", $this->object->getRefId())) { + $ilErr->raiseError($this->lng->txt("permission_denied"), $ilErr->MESSAGE); + } + } + + /** + * edit properties of object (admin form) + * + * @access public + */ + public function properties() + { + $this->checkPermission("write"); + + $this->setSettingsSubTabs("general_settings"); + + $this->initSettingsForm(); + + // Edit ecs export settings + include_once 'Modules/Glossary/classes/class.ilECSGlossarySettings.php'; + $ecs = new ilECSGlossarySettings($this->object); + $ecs->addSettingsToForm($this->form, 'glo'); + + $this->tpl->setContent($this->form->getHTML()); + } + + /** + * Init settings form. + * + * @param int $a_mode Edit Mode + */ + public function initSettingsForm($a_mode = "edit") + { + $obj_service = $this->getObjectService(); + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + // title + $title = new ilTextInputGUI($this->lng->txt("title"), "title"); + $title->setRequired(true); + $this->form->addItem($title); + + // description + $desc = new ilTextAreaInputGUI($this->lng->txt("desc"), "description"); + $this->form->addItem($desc); + + $this->lng->loadLanguageModule("rep"); + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($this->lng->txt('rep_activation_availability')); + $this->form->addItem($section); + + // online + $online = new ilCheckboxInputGUI($this->lng->txt("cont_online"), "cobj_online"); + $online->setValue("y"); + $online->setInfo($this->lng->txt("glo_online_info")); + $this->form->addItem($online); + + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($this->lng->txt('glo_content_settings')); + $this->form->addItem($section); + + // glossary mode + $glo_mode = new ilRadioGroupInputGUI($this->lng->txt("glo_mode"), "glo_mode"); + //$glo_mode->setInfo($this->lng->txt("glo_mode_desc")); + $op1 = new ilRadioOption($this->lng->txt("glo_mode_normal"), "none", $this->lng->txt("glo_mode_normal_info")); + $glo_mode->addOption($op1); + $op2 = new ilRadioOption($this->lng->txt("glo_mode_level"), "level", $this->lng->txt("glo_mode_level_info")); + $glo_mode->addOption($op2); + $op3 = new ilRadioOption($this->lng->txt("glo_mode_subtree"), "subtree", $this->lng->txt("glo_mode_subtree_info")); + $glo_mode->addOption($op3); + $this->form->addItem($glo_mode); + + // glossary mode + /*$options = array( + "none"=>$this->lng->txt("glo_mode_normal"), + "level"=>$this->lng->txt("glo_mode_level"), + "subtree"=>$this->lng->txt("glo_mode_subtree") + ); + $glo_mode = new ilSelectInputGUI($this->lng->txt("glo_mode"), "glo_mode"); + $glo_mode->setOptions($options); + $glo_mode->setInfo($this->lng->txt("glo_mode_desc")); + $this->form->addItem($glo_mode);*/ + + + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($this->lng->txt('cont_presentation')); + $this->form->addItem($section); + + // tile image + $obj_service->commonSettings()->legacyForm($this->form, $this->object)->addTileImage(); + + // presentation mode + $pres_mode = new ilRadioGroupInputGUI($this->lng->txt("glo_presentation_mode"), "pres_mode"); + $pres_mode->setValue("table"); + $op1 = new ilRadioOption($this->lng->txt("glo_table_form"), "table", $this->lng->txt("glo_table_form_info")); + + // short text length + $snl = new ilNumberInputGUI($this->lng->txt("glo_text_snippet_length"), "snippet_length"); + $snl->setMaxValue(3000); + $snl->setMinValue(100); + $snl->setMaxLength(4); + $snl->setSize(4); + $snl->setInfo($this->lng->txt("glo_text_snippet_length_info")); + $snl->setValue(200); + $op1->addSubItem($snl); + + $pres_mode->addOption($op1); + $op2 = new ilRadioOption($this->lng->txt("glo_full_definitions"), "full_def", $this->lng->txt("glo_full_definitions_info")); + $pres_mode->addOption($op2); + $this->form->addItem($pres_mode); + + // show taxonomy + include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php"); + $tax_ids = ilObjTaxonomy::getUsageOfObject($this->object->getId()); + if (count($tax_ids) > 0) { + $show_tax = new ilCheckboxInputGUI($this->lng->txt("glo_show_taxonomy"), "show_tax"); + $show_tax->setInfo($this->lng->txt("glo_show_taxonomy_info")); + $this->form->addItem($show_tax); + } + + // downloads + $down = new ilCheckboxInputGUI($this->lng->txt("cont_downloads"), "glo_act_downloads"); + $down->setValue("y"); + $down->setInfo($this->lng->txt("cont_downloads_desc")); + $this->form->addItem($down); + + if ($a_mode == "edit") { + $title->setValue($this->object->getTitle()); + $desc->setValue($this->object->getDescription()); + $online->setChecked($this->object->getOnline()); + $glo_mode->setValue($this->object->getVirtualMode()); + $pres_mode->setValue($this->object->getPresentationMode()); + $snl->setValue($this->object->getSnippetLength()); + if (count($tax_ids) > 0) { + $show_tax->setChecked($this->object->getShowTaxonomy()); + } + + $down->setChecked($this->object->isActiveDownloads()); + + // additional features + $feat = new ilFormSectionHeaderGUI(); + $feat->setTitle($this->lng->txt('obj_features')); + $this->form->addItem($feat); + + include_once './Services/Container/classes/class.ilContainer.php'; + include_once './Services/Object/classes/class.ilObjectServiceSettingsGUI.php'; + ilObjectServiceSettingsGUI::initServiceSettingsForm( + $this->object->getId(), + $this->form, + array( + ilObjectServiceSettingsGUI::CUSTOM_METADATA + ) + ); + } + + // sort columns, if adv fields are given + include_once("./Modules/Glossary/classes/class.ilGlossaryAdvMetaDataAdapter.php"); + $adv_ap = new ilGlossaryAdvMetaDataAdapter($this->object->getRefId()); + $cols = $adv_ap->getColumnOrder(); + if (count($cols) > 1) { + include_once './Modules/Glossary/classes/class.ilGloAdvColSortInputGUI.php'; + $ti = new ilGloAdvColSortInputGUI($this->lng->txt("cont_col_ordering"), "field_order"); + $this->form->addItem($ti); + $ti->setValue($cols); + } + + // save and cancel commands + $this->form->addCommandButton("saveProperties", $this->lng->txt("save")); + + $this->form->setTitle($this->lng->txt("cont_glo_properties")); + $this->form->setFormAction($this->ctrl->getFormAction($this)); + } + + + /** + * save properties + */ + public function saveProperties() + { + $obj_service = $this->getObjectService(); + + $this->initSettingsForm(); + if ($this->form->checkInput()) { + $this->object->setTitle($_POST['title']); + $this->object->setDescription($_POST['description']); + $this->object->setOnline(ilUtil::yn2tf($_POST["cobj_online"])); + $this->object->setVirtualMode($_POST["glo_mode"]); + // $this->object->setActiveGlossaryMenu(ilUtil::yn2tf($_POST["glo_act_menu"])); + $this->object->setActiveDownloads(ilUtil::yn2tf($_POST["glo_act_downloads"])); + $this->object->setPresentationMode($_POST["pres_mode"]); + $this->object->setSnippetLength($_POST["snippet_length"]); + $this->object->setShowTaxonomy($_POST["show_tax"]); + $this->object->update(); + + // tile image + $obj_service->commonSettings()->legacyForm($this->form, $this->object)->saveTileImage(); + + // field order of advanced metadata + include_once("./Modules/Glossary/classes/class.ilGlossaryAdvMetaDataAdapter.php"); + $adv_ap = new ilGlossaryAdvMetaDataAdapter($this->object->getRefId()); + $cols = $adv_ap->getColumnOrder(); + if (count($cols) > 1) { + $adv_ap->saveColumnOrder($_POST["field_order"]); + } + + // set definition short texts dirty + include_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); + ilGlossaryDefinition::setShortTextsDirty($this->object->getId()); + + include_once './Services/Object/classes/class.ilObjectServiceSettingsGUI.php'; + ilObjectServiceSettingsGUI::updateServiceSettingsForm( + $this->object->getId(), + $this->form, + array( + ilObjectServiceSettingsGUI::CUSTOM_METADATA + ) + ); + + // Update ecs export settings + include_once 'Modules/Glossary/classes/class.ilECSGlossarySettings.php'; + $ecs = new ilECSGlossarySettings($this->object); + if ($ecs->handleSettingsUpdate()) { + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "properties"); + } + } + $this->form->setValuesByPost(); + $this->tpl->setContent($this->form->getHTML()); + } + + + /** + * list terms + */ + public function listTerms() + { + if ($_GET["show_tax"]) { + $this->showTaxonomy(); + } + + // term + include_once("./Services/Form/classes/class.ilTextInputGUI.php"); + $ti = new ilTextInputGUI($this->lng->txt("cont_new_term"), "new_term"); + $ti->setMaxLength(80); + $ti->setSize(20); + $this->toolbar->addInputItem($ti, true); + + // language + $this->lng->loadLanguageModule("meta"); + $lang = ilMDLanguageItem::_getLanguages(); + if ($_SESSION["il_text_lang_" . $_GET["ref_id"]] != "") { + $s_lang = $_SESSION["il_text_lang_" . $_GET["ref_id"]]; + } else { + $s_lang = $this->user->getLanguage(); + } + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $si = new ilSelectInputGUI($this->lng->txt("language"), "term_language"); + $si->setOptions($lang); + $si->setValue($s_lang); + $this->toolbar->addInputItem($si, true); + + $this->toolbar->setFormAction($this->ctrl->getFormAction($this)); + $this->toolbar->addFormButton($this->lng->txt("glo_add_new_term"), "addTerm"); + + $this->toolbar->addSeparator(); + + //ilEditClipboard::getAction() == "copy" + include_once("./Modules/LearningModule/classes/class.ilEditClipboard.php"); + if ($this->user->clipboardHasObjectsOfType("term")) { + $this->toolbar->addButton( + $this->lng->txt("paste"), + $this->ctrl->getLinkTarget($this, "pasteTerms") + ); + $this->toolbar->addButton( + $this->lng->txt("clear_clipboard"), + $this->ctrl->getLinkTarget($this, "clearClipboard") + ); + } else { + $this->toolbar->addButton( + $this->lng->txt("glo_add_from_other"), + $this->ctrl->getLinkTargetByClass("ilglossaryforeigntermcollectorgui", "") + ); + } + + if (is_object($this->tax)) { + $this->toolbar->addSeparator(); + if ($_GET["show_tax"]) { + $this->toolbar->addButton( + $this->lng->txt("glo_hide_taxonomy"), + $this->ctrl->getLinkTarget($this, "deactTaxonomy") + ); + } else { + $this->toolbar->addButton( + $this->lng->txt("glo_show_taxonomy"), + $this->ctrl->getLinkTarget($this, "actTaxonomy") + ); + } + } + + include_once("./Modules/Glossary/classes/class.ilTermListTableGUI.php"); + $tab = new ilTermListTableGUI($this, "listTerms", $this->tax_node); + $this->tpl->setContent($tab->getHTML()); + } + + /** + * Show Taxonomy + * + * @param + * @return + */ + public function actTaxonomy() + { + $this->ctrl->setParameter($this, "show_tax", 1); + $this->ctrl->redirect($this, "listTerms"); + } + + /** + * Hide Taxonomy + * + * @param + * @return + */ + public function deactTaxonomy() + { + $this->ctrl->setParameter($this, "show_tax", ""); + $this->ctrl->redirect($this, "listTerms"); + } + + + /** + * show possible action (form buttons) + * + * @access public + */ + public function showActions($a_actions) + { + foreach ($a_actions as $name => $lng) { + $d[$name] = array("name" => $name, "lng" => $lng); + } + + $notoperations = array(); + $operations = array(); + + $operations = $d; + + if (count($operations) > 0) { + foreach ($operations as $val) { + $this->tpl->setCurrentBlock("tbl_action_btn"); + $this->tpl->setVariable("BTN_NAME", $val["name"]); + $this->tpl->setVariable("BTN_VALUE", $this->lng->txt($val["lng"])); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setCurrentBlock("tbl_action_row"); + $this->tpl->setVariable("IMG_ARROW", ilUtil::getImagePath("arrow_downright.svg")); + $this->tpl->parseCurrentBlock(); + } + } + + /** + * add term + */ + public function addTerm() + { + if (trim($_POST["new_term"]) == "") { + ilUtil::sendFailure($this->lng->txt("cont_please_enter_a_term"), true); + $this->ctrl->redirect($this, "listTerms"); + } + + // add term + include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + $term = new ilGlossaryTerm(); + $term->setGlossary($this->object); + $term->setTerm(ilUtil::stripSlashes($_POST["new_term"])); + $term->setLanguage($_POST["term_language"]); + $_SESSION["il_text_lang_" . $_GET["ref_id"]] = $_POST["term_language"]; + $term->create(); + + // add first definition + $def = new ilGlossaryDefinition(); + $def->setTermId($term->getId()); + $def->setTitle(ilUtil::stripSlashes($_POST["new_term"])); + $def->create(); + + $this->ctrl->setParameterByClass("ilglossarydefpagegui", "term_id", $term->getId()); + $this->ctrl->setParameterByClass("ilglossarydefpagegui", "def", $def->getId()); + $this->ctrl->redirectByClass(array("ilglossarytermgui", + "iltermdefinitioneditorgui", "ilglossarydefpagegui"), "edit"); + } + + /** + * move a definiton up + */ + public function moveDefinitionUp() + { + include_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); + + $definition = new ilGlossaryDefinition($_GET["def"]); + $definition->moveUp(); + + $this->ctrl->redirect($this, "listTerms"); + } + + /** + * move a definiton down + */ + public function moveDefinitionDown() + { + include_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); + + $definition = new ilGlossaryDefinition($_GET["def"]); + $definition->moveDown(); + + $this->ctrl->redirect($this, "listTerms"); + } + + /** + * deletion confirmation screen + */ + public function confirmDefinitionDeletion() + { + //$this->getTemplate(); + //$this->displayLocator(); + //$this->setTabs(); + + $term = new ilGlossaryTerm($this->term_id); + + $add = ""; + $nr = ilGlossaryTerm::getNumberOfUsages($this->term_id); + if ($nr > 0) { + $this->ctrl->setParameterByClass( + "ilglossarytermgui", + "term_id", + $this->term_id + ); + $link = "[" . $this->lng->txt("glo_list_usages") . "]"; + $add = "
" . sprintf($this->lng->txt("glo_term_is_used_n_times"), $nr) . " " . $link; + } + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setHeaderText($this->lng->txt("info_delete_sure") . $add); + + $cgui->setFormAction($this->ctrl->getFormAction($this)); + $cgui->setCancel($this->lng->txt("cancel"), "cancelDefinitionDeletion"); + $cgui->setConfirm($this->lng->txt("confirm"), "deleteDefinition"); + + // content style + $this->setContentStyleSheet($this->tpl); + + // syntax style + $this->tpl->setCurrentBlock("SyntaxStyle"); + $this->tpl->setVariable( + "LOCATION_SYNTAX_STYLESHEET", + ilObjStyleSheet::getSyntaxStylePath() + ); + $this->tpl->parseCurrentBlock(); + + $definition = new ilGlossaryDefinition($_GET["def"]); + $page_gui = new ilGlossaryDefPageGUI($definition->getId()); + $page_gui->setTemplateOutput(false); + $page_gui->setStyleId($this->object->getStyleSheetId()); + $page_gui->setSourcecodeDownloadScript("ilias.php?baseClass=ilGlossaryPresentationGUI&ref_id=" . $_GET["ref_id"]); + $page_gui->setFileDownloadLink("ilias.php?baseClass=ilGlossaryPresentationGUI&ref_id=" . $_GET["ref_id"]); + $page_gui->setFullscreenLink("ilias.php?baseClass=ilGlossaryPresentationGUI&ref_id=" . $_GET["ref_id"]); + $output = $page_gui->preview(); + + $cgui->addItem("def", $_GET["def"], $term->getTerm() . $output); + + $this->tpl->setContent($cgui->getHTML()); + } + + public function cancelDefinitionDeletion() + { + $this->ctrl->redirect($this, "listTerms"); + } + + + public function deleteDefinition() + { + $definition = new ilGlossaryDefinition($_REQUEST["def"]); + $definition->delete(); + $this->ctrl->redirect($this, "listTerms"); + } + + /** + * edit term + */ + public function editTerm() + { + // deprecated + } + + + /** + * update term + */ + public function updateTerm() + { + $term = new ilGlossaryTerm($this->term_id); + + $term->setTerm(ilUtil::stripSlashes($_POST["term"])); + $term->setLanguage($_POST["term_language"]); + $term->update(); + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "listTerms"); + } + + + + /** + * export content object + */ + public function export() + { + $this->checkPermission("write"); + + require_once("./Modules/Glossary/classes/class.ilGlossaryExport.php"); + $glo_exp = new ilGlossaryExport($this->object); + $glo_exp->buildExportFile(); + $this->ctrl->redirectByClass("ilexportgui", ""); + } + + /** + * create html package + */ + public function exportHTML() + { + require_once("./Modules/Glossary/classes/class.ilGlossaryExport.php"); + $glo_exp = new ilGlossaryExport($this->object, "html"); + $glo_exp->buildExportFile(); + //echo $this->tpl->get(); + $this->ctrl->redirectByClass("ilexportgui", ""); + } + + /** + * download export file + */ + public function publishExportFile() + { + $ilErr = $this->error; + + if (!isset($_POST["file"])) { + $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); + } + if (count($_POST["file"]) > 1) { + $ilErr->raiseError($this->lng->txt("cont_select_max_one_item"), $ilErr->MESSAGE); + } + + $file = explode(":", $_POST["file"][0]); + $export_dir = $this->object->getExportDirectory($file[0]); + + if ($this->object->getPublicExportFile($file[0]) == + $file[1]) { + $this->object->setPublicExportFile($file[0], ""); + } else { + $this->object->setPublicExportFile($file[0], $file[1]); + } + $this->object->update(); + $this->ctrl->redirectByClass("ilexportgui", ""); + } + + /* + * list all export files + */ + public function viewExportLog() + { + } + + /** + * confirm term deletion + */ + public function confirmTermDeletion() + { + //$this->prepareOutput(); + if (!isset($_POST["id"])) { + ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); + $this->ctrl->redirect($this, "listTerms"); + } + + // check ids + include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + include_once("./Modules/Glossary/classes/class.ilGlossaryTermReferences.php"); + foreach ($_POST["id"] as $term_id) { + $term_glo_id = ilGlossaryTerm::_lookGlossaryID((int) $term_id); + if ($term_glo_id != $this->object->getId() && !ilGlossaryTermReferences::isReferenced($this->object->getId(), $term_id)) { + ilUtil::sendFailure($this->lng->txt("glo_term_must_belong_to_glo"), true); + $this->ctrl->redirect($this, "listTerms"); + } + } + + // display confirmation message + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($this->ctrl->getFormAction($this)); + $cgui->setHeaderText($this->lng->txt("info_delete_sure")); + $cgui->setCancel($this->lng->txt("cancel"), "cancelTermDeletion"); + $cgui->setConfirm($this->lng->txt("confirm"), "deleteTerms"); + + include_once("./Modules/Glossary/classes/class.ilGlossaryTermReferences.php"); + + foreach ($_POST["id"] as $id) { + $term = new ilGlossaryTerm($id); + + $add = ""; + $nr = ilGlossaryTerm::getNumberOfUsages($id); + if ($nr > 0) { + $this->ctrl->setParameterByClass( + "ilglossarytermgui", + "term_id", + $id + ); + + if (ilGlossaryTermReferences::isReferenced($this->object->getId(), $id)) { + $add = " (" . $this->lng->txt("glo_term_reference") . ")"; + } else { + $link = "[" . $this->lng->txt("glo_list_usages") . "]"; + $add = "
" . + sprintf($this->lng->txt("glo_term_is_used_n_times"), $nr) . " " . $link . "
"; + } + } + + $cgui->addItem("id[]", $id, $term->getTerm() . $add); + } + + $this->tpl->setContent($cgui->getHTML()); + } + + /** + * cancel deletion of object + * + * @access public + */ + public function cancelTermDeletion() + { + $this->ctrl->redirect($this, "listTerms"); + } + + /** + * delete selected terms + */ + public function deleteTerms() + { + include_once("./Modules/Glossary/classes/class.ilGlossaryTermReferences.php"); + foreach ($_POST["id"] as $id) { + if (ilGlossaryTermReferences::isReferenced($this->object->getId(), $id)) { + $refs = new ilGlossaryTermReferences($this->object->getId()); + $refs->deleteTerm($id); + $refs->update(); + } else { + $term = new ilGlossaryTerm($id); + $term->delete(); + } + } + $this->ctrl->redirect($this, "listTerms"); + } + + /** + * set Locator + * + * @param object tree object + * @param integer reference id + * @access public + */ + public function setLocator($a_tree = "", $a_id = "") + { + if (strtolower($_GET["baseClass"]) != "ilglossaryeditorgui") { + parent::setLocator($a_tree, $a_id); + } else { + if (is_object($this->object)) { + require_once("./Modules/Glossary/classes/class.ilGlossaryLocatorGUI.php"); + $gloss_loc = new ilGlossaryLocatorGUI(); + if (is_object($this->term)) { + $gloss_loc->setTerm($this->term); + } + $gloss_loc->setGlossary($this->object); + //$gloss_loc->setDefinition($this->definition); + $gloss_loc->display(); + } + } + } + + /** + * view content + */ + public function view() + { + //$this->prepareOutput(); + $this->viewObject(); + } + + /** + * create new (subobject) in glossary + */ + public function create() + { + switch ($_POST["new_type"]) { + case "term": + $term_gui = new ilGlossaryTermGUI(); + $term_gui->create(); + break; + } + } + + public function saveTerm() + { + $term_gui = new ilGlossaryTermGUI(); + $term_gui->setGlossary($this->object); + $term_gui->save(); + + ilUtil::sendSuccess($this->lng->txt("cont_added_term"), true); + + //ilUtil::redirect("glossary_edit.php?ref_id=".$_GET["ref_id"]."&cmd=listTerms"); + $this->ctrl->redirect($this, "listTerms"); + } + + + /** + * add definition + */ + public function addDefinition() + { + $term_id = (int) $_GET["term_id"]; + + include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + $term_glo_id = ilGlossaryTerm::_lookGlossaryID((int) $term_id); + if ($term_glo_id != $this->object->getId()) { + ilUtil::sendFailure($this->lng->txt("glo_term_must_belong_to_glo"), true); + $this->ctrl->redirect($this, "listTerms"); + } + + // add term + include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + $term = new ilGlossaryTerm($term_id); + + // add first definition + $def = new ilGlossaryDefinition(); + $def->setTermId($term->getId()); + $def->setTitle(ilUtil::stripSlashes($term->getTerm())); + $def->create(); + + $this->ctrl->setParameterByClass("ilglossarydefpagegui", "term_id", $term->getId()); + $this->ctrl->setParameterByClass("ilglossarydefpagegui", "def", $def->getId()); + $this->ctrl->redirectByClass(array("ilglossarytermgui", + "iltermdefinitioneditorgui", "ilglossarydefpagegui"), "edit"); + } + + public function getTemplate() + { + $this->tpl->getStandardTemplate(); + + $title = $this->object->getTitle(); + + + if ($this->term_id > 0) { + $this->tpl->setTitle($this->lng->txt("term") . ": " . + ilGlossaryTerm::_lookGlossaryTerm($this->term_id)); + } else { + parent::setTitleAndDescription(); + $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_glo.svg")); + $this->tpl->setTitle($this->lng->txt("glo") . ": " . $title); + } + } + + /** + * output tabs + */ + public function setTabs() + { + $this->getTabs(); + } + + /** + * get tabs + */ + public function getTabs() + { + $this->help->setScreenIdComponent("glo"); + + // list terms + $force_active = ($_GET["cmd"] == "" || $_GET["cmd"] == "listTerms") + ? true + : false; + $this->tabs_gui->addTarget( + "cont_terms", + $this->ctrl->getLinkTarget($this, "listTerms"), + array("listTerms", ""), + get_class($this), + "", + $force_active + ); + + $force_active = false; + if ($this->ctrl->getCmd() == "showSummary" || + strtolower($this->ctrl->getNextClass()) == "ilinfoscreengui") { + $force_active = true; + } + $this->tabs_gui->addTarget( + "info_short", + $this->ctrl->getLinkTargetByClass("ilinfoscreengui", "showSummary"), + "", + "ilInfoScreenGUI", + "", + $force_active + ); + + // properties + if ($this->rbacsystem->checkAccess('write', $this->object->getRefId())) { + $this->tabs_gui->addTarget( + "settings", + $this->ctrl->getLinkTarget($this, "properties"), + "properties", + get_class($this) + ); + + // meta data + include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php"; + $mdgui = new ilObjectMetaDataGUI($this->object, "term"); + $mdtab = $mdgui->getTab(); + if ($mdtab) { + $this->tabs_gui->addTarget( + "meta_data", + $mdtab, + "", + "ilobjectmetadatagui" + ); + } + + // export + /*$tabs_gui->addTarget("export", + $this->ctrl->getLinkTarget($this, "exportList"), + array("exportList", "viewExportLog"), get_class($this));*/ + + // export + $this->tabs_gui->addTarget( + "export", + $this->ctrl->getLinkTargetByClass("ilexportgui", ""), + "", + "ilexportgui" + ); + } + + // permissions + if ($this->rbacsystem->checkAccess('edit_permission', $this->object->getRefId())) { + /*$tabs_gui->addTarget("permission_settings", + $this->ctrl->getLinkTarget($this, "perm"), + array("perm", "info"), + get_class($this)); + */ + $this->tabs_gui->addTarget( + "perm_settings", + $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm"), + array("perm","info","owner"), + 'ilpermissiongui' + ); + } + + $this->tabs_gui->addNonTabbedLink( + "presentation_view", + $this->lng->txt("glo_presentation_view"), + "ilias.php?baseClass=ilGlossaryPresentationGUI&ref_id=" . $this->object->getRefID(), + "_top" + ); + } + + /** + * Set sub tabs + */ + public function setSettingsSubTabs($a_active) + { + if (in_array( + $a_active, + array("general_settings", "style", "taxonomy", "glossaries") + )) { + // general properties + $this->tabs->addSubTab( + "general_settings", + $this->lng->txt("settings"), + $this->ctrl->getLinkTarget($this, 'properties') + ); + + // style properties + $this->tabs->addSubTab( + "style", + $this->lng->txt("obj_sty"), + $this->ctrl->getLinkTarget($this, 'editStyleProperties') + ); + + // taxonomy + include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php"); + ilObjTaxonomy::loadLanguageModule(); + $this->tabs->addSubTab( + "taxonomy", + $this->lng->txt("tax_taxonomy"), + $this->ctrl->getLinkTargetByClass("ilobjtaxonomygui", '') + ); + + // style properties + $this->tabs->addSubTab( + "glossaries", + $this->lng->txt("cont_auto_glossaries"), + $this->ctrl->getLinkTarget($this, 'editGlossaries') + ); + + $this->tabs->activateSubTab($a_active); + } + } + + + /** + * redirect script + * + * @param string $a_target + */ + public static function _goto($a_target) + { + global $DIC; + + $lng = $DIC->language(); + $ilAccess = $DIC->access(); + $ilErr = $DIC["ilErr"]; + + if ($ilAccess->checkAccess("read", "", $a_target)) { + $_GET["ref_id"] = $a_target; + $_GET["baseClass"] = "ilGlossaryPresentationGUI"; + include("ilias.php"); + exit; + } elseif ($ilAccess->checkAccess("visible", "", $a_target)) { + $_GET["ref_id"] = $a_target; + $_GET["cmd"] = "infoScreen"; + $_GET["baseClass"] = "ilGlossaryPresentationGUI"; + include("ilias.php"); + exit; + } elseif ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) { + ilUtil::sendFailure(sprintf( + $lng->txt("msg_no_perm_read_item"), + ilObject::_lookupTitle(ilObject::_lookupObjId($a_target)) + ), true); + ilObjectGUI::_gotoRepositoryRoot(); + } + + $ilErr->raiseError($lng->txt("msg_no_perm_read_lm"), $ilErr->FATAL); + } + + /** + * Apply filter + */ + public function applyFilter() + { + include_once("./Modules/Glossary/classes/class.ilTermListTableGUI.php"); + $prtab = new ilTermListTableGUI($this, "listTerms", $this->tax_node); + $prtab->resetOffset(); + $prtab->writeFilterToSession(); + $this->listTerms(); + } + + /** + * Reset filter + * (note: this function existed before data table filter has been introduced + */ + public function resetFilter() + { + include_once("./Modules/Glossary/classes/class.ilTermListTableGUI.php"); + $prtab = new ilTermListTableGUI($this, "listTerms", $this->tax_node); + $prtab->resetOffset(); + $prtab->resetFilter(); + $this->listTerms(); + } + + + //// + //// Style related functions + //// + + /** + * Set content style sheet + */ + public function setContentStyleSheet($a_tpl = null) + { + if ($a_tpl != null) { + $ctpl = $a_tpl; + } else { + $ctpl = $this->tpl; + } + + $ctpl->setCurrentBlock("ContentStyle"); + $ctpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath($this->object->getStyleSheetId()) + ); + $ctpl->parseCurrentBlock(); + } + + + /** + * Edit style properties + */ + public function editStyleProperties() + { + $this->checkPermission("write"); + + $this->initStylePropertiesForm(); + $this->tpl->setContent($this->form->getHTML()); + + $this->tabs->activateTab("settings"); + $this->setSettingsSubTabs("style"); + } + + /** + * Init style properties form + */ + public function initStylePropertiesForm() + { + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $this->lng->loadLanguageModule("style"); + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + $fixed_style = $this->setting->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") . ")"); + $this->form->addItem($st); + } else { + $st_styles = ilObjStyleSheet::_getStandardStyles( + true, + false, + $_GET["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)); + $this->form->addItem($st); + + //$this->ctrl->getLinkTargetByClass("ilObjStyleSheetGUI", "edit")); + + // delete command + $this->form->addCommandButton( + "editStyle", + $this->lng->txt("style_edit_style") + ); + $this->form->addCommandButton( + "deleteStyle", + $this->lng->txt("style_delete_style") + ); + //$this->ctrl->getLinkTargetByClass("ilObjStyleSheetGUI", "delete")); + } + } + + if ($style_id <= 0 || ilObjStyleSheet::_lookupStandard($style_id)) { + $style_sel = ilUtil::formSelect( + $style_id, + "style_id", + $st_styles, + false, + true + ); + $style_sel = new ilSelectInputGUI($this->lng->txt("style_current_style"), "style_id"); + $style_sel->setOptions($st_styles); + $style_sel->setValue($style_id); + $this->form->addItem($style_sel); + //$this->ctrl->getLinkTargetByClass("ilObjStyleSheetGUI", "create")); + $this->form->addCommandButton( + "saveStyleSettings", + $this->lng->txt("save") + ); + $this->form->addCommandButton( + "createStyle", + $this->lng->txt("sty_create_ind_style") + ); + } + } + $this->form->setTitle($this->lng->txt("glo_style")); + $this->form->setFormAction($this->ctrl->getFormAction($this)); + } + + /** + * Create Style + */ + public function createStyle() + { + $this->ctrl->redirectByClass("ilobjstylesheetgui", "create"); + } + + /** + * Edit Style + */ + public function editStyle() + { + $this->ctrl->redirectByClass("ilobjstylesheetgui", "edit"); + } + + /** + * Delete Style + */ + public function deleteStyle() + { + $this->ctrl->redirectByClass("ilobjstylesheetgui", "delete"); + } + + /** + * Save style settings + */ + public function saveStyleSettings() + { + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + if ($this->setting->get("fixed_content_style_id") <= 0 && + (ilObjStyleSheet::_lookupStandard($this->object->getStyleSheetId()) + || $this->object->getStyleSheetId() == 0)) { + $this->object->setStyleSheetId(ilUtil::stripSlashes($_POST["style_id"])); + $this->object->update(); + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + } + $this->ctrl->redirect($this, "editStyleProperties"); + } + + /** + * Get public access value for export table + */ + public function getPublicAccessColValue($a_type, $a_file) + { + if ($this->object->getPublicExportFile($a_type) == $a_file) { + return $this->lng->txt("yes"); + } + + return " "; + } + + /** + * Show taxonomy + * + * @param + * @return + */ + public function showTaxonomy() + { + include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php"); + $tax_ids = ilObjTaxonomy::getUsageOfObject($this->object->getId()); + if (count($tax_ids) > 0) { + include_once("./Services/Taxonomy/classes/class.ilTaxonomyExplorerGUI.php"); + $tax_exp = new ilTaxonomyExplorerGUI( + $this, + "showTaxonomy", + $tax_ids[0], + "ilobjglossarygui", + "listTerms" + ); + if (!$tax_exp->handleCommand()) { + //$this->tpl->setLeftNavContent($tax_exp->getHTML()); + $this->tpl->setLeftNavContent($tax_exp->getHTML() . " "); + } + } + } + + // + // Auto glossaries + // + + /** + * Edit automatically linked glossaries + * + * @param + * @return + */ + public function editGlossaries() + { + $this->tabs->setTabActive("settings"); + $this->setSettingsSubTabs("glossaries"); + + $this->toolbar->addButton( + $this->lng->txt("add"), + $this->ctrl->getLinkTarget($this, "showGlossarySelector") + ); + + include_once("./Modules/Glossary/classes/class.ilGlossaryAutoLinkTableGUI.php"); + $tab = new ilGlossaryAutoLinkTableGUI($this->object, $this, "editGlossaries"); + + $this->tpl->setContent($tab->getHTML()); + } + + /** + * Select LM Glossary + * + * @param + * @return + */ + public function showGlossarySelector() + { + $this->tabs->setTabActive("settings"); + $this->setSettingsSubTabs("glossaries"); + + include_once 'Services/Search/classes/class.ilSearchRootSelector.php'; + + $exp = new ilSearchRootSelector($this->ctrl->getLinkTarget($this, 'showGlossarySelector')); + $exp->setExpand($_GET["search_root_expand"] ? $_GET["search_root_expand"] : $this->tree->readRootId()); + $exp->setExpandTarget($this->ctrl->getLinkTarget($this, 'showGlossarySelector')); + $exp->setTargetClass(get_class($this)); + $exp->setCmd('confirmGlossarySelection'); + $exp->setClickableTypes(array("glo")); + $exp->addFilter("glo"); + + // build html-output + $exp->setOutput(0); + $this->tpl->setContent($exp->getOutput()); + } + + /** + * Confirm glossary selection + */ + public function confirmGlossarySelection() + { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $this->ctrl->setParameter($this, "glo_ref_id", $_GET["root_id"]); + $cgui->setFormAction($this->ctrl->getFormAction($this)); + $cgui->setHeaderText($this->lng->txt("glo_link_glo_in_glo")); + $cgui->setCancel($this->lng->txt("no"), "selectGlossary"); + $cgui->setConfirm($this->lng->txt("yes"), "selectGlossaryLink"); + $this->tpl->setContent($cgui->getHTML()); + } + + /** + * Select a glossary and link all its terms + * + * @param + * @return + */ + public function selectGlossaryLink() + { + $glo_ref_id = (int) $_GET["glo_ref_id"]; + $glo_id = ilObject::_lookupObjId($glo_ref_id); + $this->object->autoLinkGlossaryTerms($glo_ref_id); + $this->selectGlossary(); + } + + + /** + * Select lm glossary + * + * @param + * @return + */ + public function selectGlossary() + { + $glos = $this->object->getAutoGlossaries(); + $glo_ref_id = (int) $_GET["glo_ref_id"]; + $glo_id = ilObject::_lookupObjId($glo_ref_id); + if (!in_array($glo_id, $glos)) { + $glos[] = $glo_id; + } + $this->object->setAutoGlossaries($glos); + $this->object->update(); + + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "editGlossaries"); + } + + /** + * Remove lm glossary + * + * @param + * @return + */ + public function removeGlossary() + { + $this->object->removeAutoGlossary((int) $_GET["glo_id"]); + $this->object->update(); + + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "editGlossaries"); + } + + /** + * Copy terms + * + * @param + * @return + */ + public function copyTerms() + { + $items = ilUtil::stripSlashesArray($_POST["id"]); + if (!is_array($items)) { + ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); + $this->ctrl->redirect($this, "listTerms"); + } + + include_once("./Modules/LearningModule/classes/class.ilEditClipboard.php"); + $this->user->clipboardDeleteObjectsOfType("term"); + + // put them into the clipboard + $time = date("Y-m-d H:i:s", time()); + $order = 0; + foreach ($items as $id) { + $this->user->addObjectToClipboard( + $id, + "term", + ilGlossaryTerm::_lookGlossaryTerm($id), + 0, + $time, + $order + ); + } + + ilEditClipboard::setAction("copy"); + ilUtil::sendInfo($this->lng->txt("glo_selected_terms_have_been_copied"), true); + $this->ctrl->redirect($this, "listTerms"); + } + + /** + * Reference terms + * + * @param + * @return + */ + public function referenceTerms() + { + $items = ilUtil::stripSlashesArray($_POST["id"]); + if (!is_array($items)) { + ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); + $this->ctrl->redirect($this, "listTerms"); + } + + include_once("./Modules/LearningModule/classes/class.ilEditClipboard.php"); + $this->user->clipboardDeleteObjectsOfType("term"); + + // put them into the clipboard + $time = date("Y-m-d H:i:s", time()); + $order = 0; + foreach ($items as $id) { + $this->user->addObjectToClipboard( + $id, + "term", + ilGlossaryTerm::_lookGlossaryTerm($id), + 0, + $time, + $order + ); + } + + ilEditClipboard::setAction("link"); + ilUtil::sendInfo($this->lng->txt("glo_selected_terms_have_been_copied"), true); + $this->ctrl->redirect($this, "listTerms"); + } + + + /** + * Clear clipboard + * + * @param + * @return + */ + public function clearClipboard() + { + $this->user->clipboardDeleteObjectsOfType("term"); + $this->ctrl->redirect($this, "listTerms"); + } + + /** + * Paste Terms + */ + public function pasteTerms() + { + include_once("./Modules/LearningModule/classes/class.ilEditClipboard.php"); + if (ilEditClipboard::getAction() == "copy") { + foreach ($this->user->getClipboardObjects("term") as $item) { + ilGlossaryTerm::_copyTerm($item["id"], $this->object->getId()); + } + } + if (ilEditClipboard::getAction() == "link") { + include_once("./Modules/Glossary/classes/class.ilGlossaryTermReferences.php"); + $refs = new ilGlossaryTermReferences($this->object->getId()); + foreach ($this->user->getClipboardObjects("term") as $item) { + $refs->addTerm($item["id"]); + } + $refs->update(); + } + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "listTerms"); + } } - -?> \ No newline at end of file diff --git a/Modules/Glossary/classes/class.ilObjGlossaryListGUI.php b/Modules/Glossary/classes/class.ilObjGlossaryListGUI.php index 3f55e1d50cf617643398df462efcfe5d245443cf..b6813dd0e78457527a23f9f98b74b8f712bab792 100644 --- a/Modules/Glossary/classes/class.ilObjGlossaryListGUI.php +++ b/Modules/Glossary/classes/class.ilObjGlossaryListGUI.php @@ -15,119 +15,113 @@ include_once "Services/Object/classes/class.ilObjectListGUI.php"; class ilObjGlossaryListGUI extends ilObjectListGUI { - /** - * initialisation - * - * this method should be overwritten by derived classes - */ - function init() - { - $this->static_link_enabled = true; - $this->delete_enabled = true; - $this->cut_enabled = true; - $this->copy_enabled = true; - $this->subscribe_enabled = true; - $this->link_enabled = true; - $this->info_screen_enabled = true; - $this->type = "glo"; - $this->gui_class_name = "ilobjglossarygui"; - - // general commands array - include_once("./Modules/Glossary/classes/class.ilObjGlossaryAccess.php"); - $this->commands = ilObjGlossaryAccess::_getCommands(); - } - - /** - * Overwrite this method, if link target is not build by ctrl class - * (e.g. "lm_presentation.php", "forum.php"). This is the case - * for all links now, but bringing everything to ilCtrl should - * be realised in the future. - * - * @param string $a_cmd command - * - */ - function getCommandLink($a_cmd) - { - switch($a_cmd) - { - case "view": - $cmd_link = "ilias.php?baseClass=ilGlossaryPresentationGUI&ref_id=".$this->ref_id; - break; - - case "edit": - $cmd_link = "ilias.php?baseClass=ilGlossaryEditorGUI&ref_id=".$this->ref_id; - break; - - case "properties": - $this->ctrl->setParameterByClass("ilobjglossarygui", "ref_id", $this->ref_id); - $cmd_link = $this->ctrl->getLinkTargetByClass(array("ilglossaryeditorgui", "ilobjglossarygui"), $a_cmd); - break; - - case "infoScreen": - $cmd_link = "ilias.php?baseClass=ilGlossaryPresentationGUI&cmd=infoScreen&ref_id=".$this->ref_id; - break; - - default: - $this->ctrl->setParameterByClass("ilrepositorygui", "ref_id", $this->ref_id); - $cmd_link = $this->ctrl->getLinkTargetByClass("ilrepositorygui", $a_cmd); - $this->ctrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - break; - } - - return $cmd_link; - } - - /** - * Get command target frame - * - * @param string $a_cmd command - * - * @return string command target frame - */ - function getCommandFrame($a_cmd) - { - switch($a_cmd) - { - case "view": - case "edit": - case "properties": - $frame = ilFrameTargetInfo::_getFrame("MainContent"); - break; - - default: - $frame = ""; - break; - } - - return $frame; - } - - - /** - * Get item properties - * - * @return array array of property arrays: - * "alert" (boolean) => display as an alert property (usually in red) - * "property" (string) => property name - * "value" (string) => property value - */ - function getProperties() - { - $lng = $this->lng; - $rbacsystem = $this->rbacsystem; - - $props = array(); - - include_once("./Modules/Glossary/classes/class.ilObjGlossaryAccess.php"); - - if (!ilObjGlossaryAccess::_lookupOnline($this->obj_id)) - { - $props[] = array("alert" => true, "property" => $lng->txt("status"), - "value" => $lng->txt("offline")); - } - return $props; - } - - + /** + * initialisation + * + * this method should be overwritten by derived classes + */ + public function init() + { + $this->static_link_enabled = true; + $this->delete_enabled = true; + $this->cut_enabled = true; + $this->copy_enabled = true; + $this->subscribe_enabled = true; + $this->link_enabled = true; + $this->info_screen_enabled = true; + $this->type = "glo"; + $this->gui_class_name = "ilobjglossarygui"; + + // general commands array + include_once("./Modules/Glossary/classes/class.ilObjGlossaryAccess.php"); + $this->commands = ilObjGlossaryAccess::_getCommands(); + } + + /** + * Overwrite this method, if link target is not build by ctrl class + * (e.g. "lm_presentation.php", "forum.php"). This is the case + * for all links now, but bringing everything to ilCtrl should + * be realised in the future. + * + * @param string $a_cmd command + * + */ + public function getCommandLink($a_cmd) + { + switch ($a_cmd) { + case "view": + $cmd_link = "ilias.php?baseClass=ilGlossaryPresentationGUI&ref_id=" . $this->ref_id; + break; + + case "edit": + $cmd_link = "ilias.php?baseClass=ilGlossaryEditorGUI&ref_id=" . $this->ref_id; + break; + + case "properties": + $this->ctrl->setParameterByClass("ilobjglossarygui", "ref_id", $this->ref_id); + $cmd_link = $this->ctrl->getLinkTargetByClass(array("ilglossaryeditorgui", "ilobjglossarygui"), $a_cmd); + break; + + case "infoScreen": + $cmd_link = "ilias.php?baseClass=ilGlossaryPresentationGUI&cmd=infoScreen&ref_id=" . $this->ref_id; + break; + + default: + $this->ctrl->setParameterByClass("ilrepositorygui", "ref_id", $this->ref_id); + $cmd_link = $this->ctrl->getLinkTargetByClass("ilrepositorygui", $a_cmd); + $this->ctrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + break; + } + + return $cmd_link; + } + + /** + * Get command target frame + * + * @param string $a_cmd command + * + * @return string command target frame + */ + public function getCommandFrame($a_cmd) + { + switch ($a_cmd) { + case "view": + case "edit": + case "properties": + $frame = ilFrameTargetInfo::_getFrame("MainContent"); + break; + + default: + $frame = ""; + break; + } + + return $frame; + } + + + /** + * Get item properties + * + * @return array array of property arrays: + * "alert" (boolean) => display as an alert property (usually in red) + * "property" (string) => property name + * "value" (string) => property value + */ + public function getProperties() + { + $lng = $this->lng; + $rbacsystem = $this->rbacsystem; + + $props = array(); + + include_once("./Modules/Glossary/classes/class.ilObjGlossaryAccess.php"); + + if (!ilObjGlossaryAccess::_lookupOnline($this->obj_id)) { + $props[] = array("alert" => true, "property" => $lng->txt("status"), + "value" => $lng->txt("offline")); + } + return $props; + } } // END class.ilObjCategoryGUI -?> diff --git a/Modules/Glossary/classes/class.ilObjGlossarySubItemListGUI.php b/Modules/Glossary/classes/class.ilObjGlossarySubItemListGUI.php index 5f0c26ee1a69af2ec9117bec79e0ba5be73f648f..e849ec2033467032c1a20abe3805c98c368bb874 100644 --- a/Modules/Glossary/classes/class.ilObjGlossarySubItemListGUI.php +++ b/Modules/Glossary/classes/class.ilObjGlossarySubItemListGUI.php @@ -1,110 +1,106 @@ * @version $Id$ -* +* * * @ingroup ModulesGlossary */ class ilObjGlossarySubItemListGUI extends ilSubItemListGUI { - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - /** - * Constructor - */ - function __construct($a_cmd_class) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_cmd_class) + { + global $DIC; - parent::__construct($a_cmd_class); - $this->user = $DIC->user(); - } + parent::__construct($a_cmd_class); + $this->user = $DIC->user(); + } - /** - * get html - * @return - */ - public function getHTML() - { - $lng = $this->lng; - $ilUser = $this->user; - - $lng->loadLanguageModule('content'); - foreach($this->getSubItemIds(true) as $sub_item) - { - if(is_object($this->getHighlighter()) and strlen($this->getHighlighter()->getContent($this->getObjId(),$sub_item))) - { - $this->tpl->setCurrentBlock('sea_fragment'); - $this->tpl->setVariable('TXT_FRAGMENT',$this->getHighlighter()->getContent($this->getObjId(),$sub_item)); - $this->tpl->parseCurrentBlock(); - } - $this->tpl->setCurrentBlock('subitem'); - $this->tpl->setVariable('SUBITEM_TYPE',$lng->txt('cont_term')); - $this->tpl->setVariable('SEPERATOR',':'); - - #$this->getItemListGUI()->setChildId($sub_item); - - include_once './Services/Search/classes/class.ilUserSearchCache.php'; - $src_string = ilUserSearchCache::_getInstance($ilUser->getId())->getUrlEncodedQuery(); - - $this->tpl->setVariable('LINK',ilLink::_getLink( - $this->getRefId(), - 'git', - array( - 'target' => 'git_'.$sub_item.'_'.$this->getRefId(), - 'srcstring' => 1 - ) - )); - - $this->tpl->setVariable('TARGET',$this->getItemListGUI()->getCommandFrame('')); - $this->tpl->setVariable('TITLE',ilGlossaryTerm::_lookGlossaryTerm($sub_item)); + /** + * get html + * @return + */ + public function getHTML() + { + $lng = $this->lng; + $ilUser = $this->user; + + $lng->loadLanguageModule('content'); + foreach ($this->getSubItemIds(true) as $sub_item) { + if (is_object($this->getHighlighter()) and strlen($this->getHighlighter()->getContent($this->getObjId(), $sub_item))) { + $this->tpl->setCurrentBlock('sea_fragment'); + $this->tpl->setVariable('TXT_FRAGMENT', $this->getHighlighter()->getContent($this->getObjId(), $sub_item)); + $this->tpl->parseCurrentBlock(); + } + $this->tpl->setCurrentBlock('subitem'); + $this->tpl->setVariable('SUBITEM_TYPE', $lng->txt('cont_term')); + $this->tpl->setVariable('SEPERATOR', ':'); + + #$this->getItemListGUI()->setChildId($sub_item); + + include_once './Services/Search/classes/class.ilUserSearchCache.php'; + $src_string = ilUserSearchCache::_getInstance($ilUser->getId())->getUrlEncodedQuery(); + + $this->tpl->setVariable('LINK', ilLink::_getLink( + $this->getRefId(), + 'git', + array( + 'target' => 'git_' . $sub_item . '_' . $this->getRefId(), + 'srcstring' => 1 + ) + )); + + $this->tpl->setVariable('TARGET', $this->getItemListGUI()->getCommandFrame('')); + $this->tpl->setVariable('TITLE', ilGlossaryTerm::_lookGlossaryTerm($sub_item)); - // begin-patch mime_filter - if(count($this->getSubItemIds(true)) > 1) - { - $this->parseRelevance($sub_item); - } - // end-patch mime_filter - - $this->tpl->parseCurrentBlock(); - } - - $this->showDetailsLink(); - - return $this->tpl->get(); - } + // begin-patch mime_filter + if (count($this->getSubItemIds(true)) > 1) { + $this->parseRelevance($sub_item); + } + // end-patch mime_filter + + $this->tpl->parseCurrentBlock(); + } + + $this->showDetailsLink(); + + return $this->tpl->get(); + } } -?> \ No newline at end of file diff --git a/Modules/Glossary/classes/class.ilPresentationListTableGUI.php b/Modules/Glossary/classes/class.ilPresentationListTableGUI.php index 861c749744b39059ad05543baf8a36b9e03b1f9f..601221f503191bfc67a63bea661276c41ff08f62 100644 --- a/Modules/Glossary/classes/class.ilPresentationListTableGUI.php +++ b/Modules/Glossary/classes/class.ilPresentationListTableGUI.php @@ -1,4 +1,4 @@ -lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); - $this->glossary = $a_glossary; - $this->offline = $a_offline; - $this->tax_node = $a_tax_node; - $this->tax_id = $a_tax_id; - $this->setId("glopr".$this->glossary->getId()); - - include_once("./Modules/Glossary/classes/class.ilGlossaryAdvMetaDataAdapter.php"); - $adv_ad = new ilGlossaryAdvMetaDataAdapter($this->glossary->getRefId()); - $this->adv_fields = $adv_ad->getAllFields(); + $this->glossary = $a_glossary; + $this->offline = $a_offline; + $this->tax_node = $a_tax_node; + $this->tax_id = $a_tax_id; + $this->setId("glopr" . $this->glossary->getId()); + + include_once("./Modules/Glossary/classes/class.ilGlossaryAdvMetaDataAdapter.php"); + $adv_ad = new ilGlossaryAdvMetaDataAdapter($this->glossary->getRefId()); + $this->adv_fields = $adv_ad->getAllFields(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - //$this->setTitle($this->lng->txt("cont_terms")); + + parent::__construct($a_parent_obj, $a_parent_cmd); + //$this->setTitle($this->lng->txt("cont_terms")); - if ($this->glossary->getPresentationMode() == "full_def") - { - $this->addColumn($this->lng->txt("cont_terms")); - } - else - { - include_once("./Modules/Glossary/classes/class.ilGlossaryAdvMetaDataAdapter.php"); - $adv_ap = new ilGlossaryAdvMetaDataAdapter($this->glossary->getRefId()); - $this->adv_cols_order = $adv_ap->getColumnOrder(); - foreach ($this->adv_cols_order as $c) - { - if ($c["id"] == 0) - { - $this->addColumn($this->lng->txt("cont_term"), "term"); - } - else - { - $this->addColumn($c["text"], "md_".$c["id"]); - } - } - + if ($this->glossary->getPresentationMode() == "full_def") { + $this->addColumn($this->lng->txt("cont_terms")); + } else { + include_once("./Modules/Glossary/classes/class.ilGlossaryAdvMetaDataAdapter.php"); + $adv_ap = new ilGlossaryAdvMetaDataAdapter($this->glossary->getRefId()); + $this->adv_cols_order = $adv_ap->getColumnOrder(); + foreach ($this->adv_cols_order as $c) { + if ($c["id"] == 0) { + $this->addColumn($this->lng->txt("cont_term"), "term"); + } else { + $this->addColumn($c["text"], "md_" . $c["id"]); + } + } + - $this->addColumn($this->lng->txt("cont_definitions")); - if ($this->glossary->isVirtual()) - { - $this->addColumn($this->lng->txt("obj_glo")); - } - } - - $this->setEnableHeader(true); - if (!$this->offline) - { - $this->setFormAction($this->ctrl->getFormAction($this->parent_obj)); - } - else - { - $this->disable("footer"); - } - $this->setRowTemplate("tpl.term_tbl_pres_row.html", "Modules/Glossary"); - $this->setEnableTitle(true); - - if (!$this->offline) - { - $this->initFilter(); - $this->setFilterCommand("applyFilter"); - - $this->setShowRowsSelector(true); - } - - // advanced metadata - include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecordGUI.php'); - $this->record_gui = new ilAdvancedMDRecordGUI(ilAdvancedMDRecordGUI::MODE_FILTER,'glo',$this->glossary->getId(),'term'); - $this->record_gui->setTableGUI($this); - $this->record_gui->parse(); - //$this->setDefaultOrderField("login"); - //$this->setDefaultOrderDirection("asc"); - $this->setData($this->glossary->getTermList($this->filter["term"], $_GET["letter"], - $this->filter["definition"], $this->tax_node, false, true, $this->record_gui->getFilterElements(), false, true)); -// $this->setData(array()); - } - - /** - * needed for advmd filter handling - * - * @return ilAdvancedMDRecordGUI - */ - protected function getAdvMDRecordGUI() - { - return $this->record_gui; - } - - /** - * Init filter - */ - function initFilter() - { - // term - include_once("./Services/Form/classes/class.ilTextInputGUI.php"); - $ti = new ilTextInputGUI($this->lng->txt("cont_term"), "term"); - $ti->setMaxLength(64); - $ti->setSize(20); - $ti->setSubmitFormOnEnter(true); - $this->addFilterItem($ti); - $ti->readFromSession(); - $this->filter["term"] = $ti->getValue(); - - // definition - if ($this->glossary->supportsLongTextQuery()) - { - include_once("./Services/Form/classes/class.ilTextInputGUI.php"); - $ti = new ilTextInputGUI($this->lng->txt("cont_definition"), "defintion"); - $ti->setMaxLength(64); - $ti->setSize(20); - $ti->setSubmitFormOnEnter(true); - $this->addFilterItem($ti); - $ti->readFromSession(); - $this->filter["definition"] = $ti->getValue(); - } - } - - /** - * Should this field be sorted numeric? - * - * @return boolean numeric ordering; default is false - */ - function numericOrdering($a_field) - { - if (substr($a_field, 0, 3) == "md_") - { - $md_id = (int) substr($a_field, 3); - if ($this->adv_fields[$md_id]["type"] == ilAdvancedMDFieldDefinition::TYPE_DATE) - { - return true; - } - } - return false; - } + $this->addColumn($this->lng->txt("cont_definitions")); + if ($this->glossary->isVirtual()) { + $this->addColumn($this->lng->txt("obj_glo")); + } + } + + $this->setEnableHeader(true); + if (!$this->offline) { + $this->setFormAction($this->ctrl->getFormAction($this->parent_obj)); + } else { + $this->disable("footer"); + } + $this->setRowTemplate("tpl.term_tbl_pres_row.html", "Modules/Glossary"); + $this->setEnableTitle(true); + + if (!$this->offline) { + $this->initFilter(); + $this->setFilterCommand("applyFilter"); + + $this->setShowRowsSelector(true); + } + + // advanced metadata + include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecordGUI.php'); + $this->record_gui = new ilAdvancedMDRecordGUI(ilAdvancedMDRecordGUI::MODE_FILTER, 'glo', $this->glossary->getId(), 'term'); + $this->record_gui->setTableGUI($this); + $this->record_gui->parse(); + //$this->setDefaultOrderField("login"); + //$this->setDefaultOrderDirection("asc"); + $this->setData($this->glossary->getTermList( + $this->filter["term"], + $_GET["letter"], + $this->filter["definition"], + $this->tax_node, + false, + true, + $this->record_gui->getFilterElements(), + false, + true + )); + // $this->setData(array()); + } + + /** + * needed for advmd filter handling + * + * @return ilAdvancedMDRecordGUI + */ + protected function getAdvMDRecordGUI() + { + return $this->record_gui; + } + + /** + * Init filter + */ + public function initFilter() + { + // term + include_once("./Services/Form/classes/class.ilTextInputGUI.php"); + $ti = new ilTextInputGUI($this->lng->txt("cont_term"), "term"); + $ti->setMaxLength(64); + $ti->setSize(20); + $ti->setSubmitFormOnEnter(true); + $this->addFilterItem($ti); + $ti->readFromSession(); + $this->filter["term"] = $ti->getValue(); + + // definition + if ($this->glossary->supportsLongTextQuery()) { + include_once("./Services/Form/classes/class.ilTextInputGUI.php"); + $ti = new ilTextInputGUI($this->lng->txt("cont_definition"), "defintion"); + $ti->setMaxLength(64); + $ti->setSize(20); + $ti->setSubmitFormOnEnter(true); + $this->addFilterItem($ti); + $ti->readFromSession(); + $this->filter["definition"] = $ti->getValue(); + } + } + + /** + * Should this field be sorted numeric? + * + * @return boolean numeric ordering; default is false + */ + public function numericOrdering($a_field) + { + if (substr($a_field, 0, 3) == "md_") { + $md_id = (int) substr($a_field, 3); + if ($this->adv_fields[$md_id]["type"] == ilAdvancedMDFieldDefinition::TYPE_DATE) { + return true; + } + } + return false; + } - /** - * Fill table row - */ - protected function fillRow($term) - { - $defs = ilGlossaryDefinition::getDefinitionList($term["id"]); - $this->ctrl->setParameter($this->parent_obj, "term_id", $term["id"]); + /** + * Fill table row + */ + protected function fillRow($term) + { + $defs = ilGlossaryDefinition::getDefinitionList($term["id"]); + $this->ctrl->setParameter($this->parent_obj, "term_id", $term["id"]); - if ($this->glossary->getPresentationMode() == "full_def") - { - $this->tpl->setCurrentBlock("fd_td"); - $this->tpl->setVariable("FULL_DEF", - $this->parent_obj->listDefinitions($_GET["ref_id"], $term["id"], true)); - $this->tpl->parseCurrentBlock(); - } - else - { - if(sizeof($defs)) - { - for ($j=0; $j < count($defs); $j++) - { - $def = $defs[$j]; - if (count($defs) > 1) - { - if (!$this->offline) - { - if (!empty ($filter)) - { - $this->ctrl->setParameter($this->parent_obj, "term", $filter); - $this->ctrl->setParameter($this->parent_obj, "oldoffset", $_GET["oldoffset"]); - } - $this->ctrl->setParameter($this->parent_obj, "term_id", $term["id"]); - $this->ctrl->setParameter($this->parent_obj, "offset", $_GET["offset"]); - $def_href = $this->ctrl->getLinkTarget($this->parent_obj, "listDefinitions"); - $this->ctrl->clearParameters($this->parent_obj); - } - else - { - $def_href = "term_".$term["id"].".html"; - } - $this->tpl->parseCurrentBlock(); + if ($this->glossary->getPresentationMode() == "full_def") { + $this->tpl->setCurrentBlock("fd_td"); + $this->tpl->setVariable( + "FULL_DEF", + $this->parent_obj->listDefinitions($_GET["ref_id"], $term["id"], true) + ); + $this->tpl->parseCurrentBlock(); + } else { + if (sizeof($defs)) { + for ($j=0; $j < count($defs); $j++) { + $def = $defs[$j]; + if (count($defs) > 1) { + if (!$this->offline) { + if (!empty($filter)) { + $this->ctrl->setParameter($this->parent_obj, "term", $filter); + $this->ctrl->setParameter($this->parent_obj, "oldoffset", $_GET["oldoffset"]); + } + $this->ctrl->setParameter($this->parent_obj, "term_id", $term["id"]); + $this->ctrl->setParameter($this->parent_obj, "offset", $_GET["offset"]); + $def_href = $this->ctrl->getLinkTarget($this->parent_obj, "listDefinitions"); + $this->ctrl->clearParameters($this->parent_obj); + } else { + $def_href = "term_" . $term["id"] . ".html"; + } + $this->tpl->parseCurrentBlock(); - $this->tpl->setCurrentBlock("definition"); - $this->tpl->setVariable("DEF_TEXT", $this->lng->txt("cont_definition")." ".($j + 1)); - $this->tpl->setVariable("HREF_DEF", $def_href."#ilPageTocDef".($j + 1)); - $this->tpl->parseCurrentBlock(); - } + $this->tpl->setCurrentBlock("definition"); + $this->tpl->setVariable("DEF_TEXT", $this->lng->txt("cont_definition") . " " . ($j + 1)); + $this->tpl->setVariable("HREF_DEF", $def_href . "#ilPageTocDef" . ($j + 1)); + $this->tpl->parseCurrentBlock(); + } - // check dirty short texts - $this->tpl->setCurrentBlock("definition"); - if ($def["short_text_dirty"]) - { - // #18022 - $def_obj = new ilGlossaryDefinition($def["id"]); - $def_obj->updateShortText(); - $short_str = $def_obj->getShortText(); - } - else - { - $short_str = $def["short_text"]; - } - // replace tex - // if a tex end tag is missing a tex end tag - $ltexs = strrpos($short_str, "[tex]"); - $ltexe = strrpos($short_str, "[/tex]"); - if ($ltexs > $ltexe) - { - $page = new ilGlossaryDefPage($def["id"]); - $page->buildDom(); - $short_str = $page->getFirstParagraphText(); - $short_str = strip_tags($short_str, "
"); - $ltexe = strpos($short_str, "[/tex]", $ltexs); - $short_str = ilUtil::shortenText($short_str, $ltexe+6, true); - } + // check dirty short texts + $this->tpl->setCurrentBlock("definition"); + if ($def["short_text_dirty"]) { + // #18022 + $def_obj = new ilGlossaryDefinition($def["id"]); + $def_obj->updateShortText(); + $short_str = $def_obj->getShortText(); + } else { + $short_str = $def["short_text"]; + } + // replace tex + // if a tex end tag is missing a tex end tag + $ltexs = strrpos($short_str, "[tex]"); + $ltexe = strrpos($short_str, "[/tex]"); + if ($ltexs > $ltexe) { + $page = new ilGlossaryDefPage($def["id"]); + $page->buildDom(); + $short_str = $page->getFirstParagraphText(); + $short_str = strip_tags($short_str, "
"); + $ltexe = strpos($short_str, "[/tex]", $ltexs); + $short_str = ilUtil::shortenText($short_str, $ltexe+6, true); + } - include_once './Services/MathJax/classes/class.ilMathJax.php'; - if (!$this->offline) - { - $short_str = ilMathJax::getInstance()->insertLatexImages($short_str); - } - else - { - $short_str = ilMathJax::getInstance()->insertLatexImages($short_str, '[tex]', '[/tex]', - $this->parent_obj->getOfflineDirectory().'/teximg','./teximg'); - } + include_once './Services/MathJax/classes/class.ilMathJax.php'; + if (!$this->offline) { + $short_str = ilMathJax::getInstance()->insertLatexImages($short_str); + } else { + $short_str = ilMathJax::getInstance()->insertLatexImages( + $short_str, + '[tex]', + '[/tex]', + $this->parent_obj->getOfflineDirectory() . '/teximg', + './teximg' + ); + } - $short_str = ilPCParagraph::xml2output($short_str); + $short_str = ilPCParagraph::xml2output($short_str); - $this->tpl->setVariable("DEF_SHORT", $short_str); - $this->tpl->parseCurrentBlock(); + $this->tpl->setVariable("DEF_SHORT", $short_str); + $this->tpl->parseCurrentBlock(); - $this->tpl->setCurrentBlock("definition_row"); - $this->tpl->parseCurrentBlock(); - } - } - else - { - $this->tpl->touchBlock("def_td"); - } + $this->tpl->setCurrentBlock("definition_row"); + $this->tpl->parseCurrentBlock(); + } + } else { + $this->tpl->touchBlock("def_td"); + } - // display additional column 'glossary' for meta glossaries - if ($this->glossary->isVirtual()) - { - $this->tpl->setCurrentBlock("glossary_row"); - $glo_title = ilObject::_lookupTitle($term["glo_id"]); - $this->tpl->setVariable("GLO_TITLE", $glo_title); - $this->tpl->parseCurrentBlock(); - } + // display additional column 'glossary' for meta glossaries + if ($this->glossary->isVirtual()) { + $this->tpl->setCurrentBlock("glossary_row"); + $glo_title = ilObject::_lookupTitle($term["glo_id"]); + $this->tpl->setVariable("GLO_TITLE", $glo_title); + $this->tpl->parseCurrentBlock(); + } + } - } - - $this->ctrl->clearParameters($this->parent_obj); - - // advanced metadata - foreach ($this->adv_cols_order as $c) - { - if ($c["id"] == 0) - { - $this->tpl->setCurrentBlock("link_start"); - if (!$this->offline) - { - if (!empty ($filter)) - { - $this->ctrl->setParameter($this->parent_obj, "term", $filter); - $this->ctrl->setParameter($this->parent_obj, "oldoffset", $_GET["oldoffset"]); - } - $this->ctrl->setParameter($this->parent_obj, "term_id", $term["id"]); - $this->ctrl->setParameter($this->parent_obj, "offset", $_GET["offset"]); - $this->tpl->setVariable("LINK_VIEW_TERM", - $this->ctrl->getLinkTarget($this->parent_obj, "listDefinitions")); - $this->ctrl->clearParameters($this->parent_obj); - } - else - { - $this->tpl->setVariable("LINK_VIEW_TERM", "term_".$term["id"].".html"); - } - $this->tpl->parseCurrentBlock(); - - $this->tpl->setCurrentBlock("link_end"); - $this->tpl->setVariable("ANCHOR_TERM", "term_".$term["id"]); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setCurrentBlock("td"); - $this->tpl->setVariable("TEXT", $term["term"]); - $this->tpl->parseCurrentBlock(); - } - else - { - $id = $c["id"]; - - $val = " "; - if(isset($term["md_".$id."_presentation"])) - { - $pb = $term["md_".$id."_presentation"]->getList(); - if($pb) - { - $val = $pb; - } - } - - $this->tpl->setCurrentBlock("td"); - $this->tpl->setVariable("TEXT", $val); - $this->tpl->parseCurrentBlock(); - } - } - } + $this->ctrl->clearParameters($this->parent_obj); + // advanced metadata + foreach ($this->adv_cols_order as $c) { + if ($c["id"] == 0) { + $this->tpl->setCurrentBlock("link_start"); + if (!$this->offline) { + if (!empty($filter)) { + $this->ctrl->setParameter($this->parent_obj, "term", $filter); + $this->ctrl->setParameter($this->parent_obj, "oldoffset", $_GET["oldoffset"]); + } + $this->ctrl->setParameter($this->parent_obj, "term_id", $term["id"]); + $this->ctrl->setParameter($this->parent_obj, "offset", $_GET["offset"]); + $this->tpl->setVariable( + "LINK_VIEW_TERM", + $this->ctrl->getLinkTarget($this->parent_obj, "listDefinitions") + ); + $this->ctrl->clearParameters($this->parent_obj); + } else { + $this->tpl->setVariable("LINK_VIEW_TERM", "term_" . $term["id"] . ".html"); + } + $this->tpl->parseCurrentBlock(); + + $this->tpl->setCurrentBlock("link_end"); + $this->tpl->setVariable("ANCHOR_TERM", "term_" . $term["id"]); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setCurrentBlock("td"); + $this->tpl->setVariable("TEXT", $term["term"]); + $this->tpl->parseCurrentBlock(); + } else { + $id = $c["id"]; + + $val = " "; + if (isset($term["md_" . $id . "_presentation"])) { + $pb = $term["md_" . $id . "_presentation"]->getList(); + if ($pb) { + $val = $pb; + } + } + + $this->tpl->setCurrentBlock("td"); + $this->tpl->setVariable("TEXT", $val); + $this->tpl->parseCurrentBlock(); + } + } + } } -?> \ No newline at end of file diff --git a/Modules/Glossary/classes/class.ilTermDefinitionEditorGUI.php b/Modules/Glossary/classes/class.ilTermDefinitionEditorGUI.php index 5ccd73989f8e5e265117a2ca7e44e643461479e4..b869c4d793deabd094976dcdbb777c6f06f1bb1f 100755 --- a/Modules/Glossary/classes/class.ilTermDefinitionEditorGUI.php +++ b/Modules/Glossary/classes/class.ilTermDefinitionEditorGUI.php @@ -4,7 +4,7 @@ require_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); -require_once ("./Modules/Glossary/classes/class.ilGlossaryDefPageGUI.php"); +require_once("./Modules/Glossary/classes/class.ilGlossaryDefPageGUI.php"); /** * GUI class for glossary term definition editor @@ -18,203 +18,212 @@ require_once ("./Modules/Glossary/classes/class.ilGlossaryDefPageGUI.php"); */ class ilTermDefinitionEditorGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTabsGUI - */ - protected $tabs_gui; - - var $tpl; - var $lng; - var $glossary; - var $definition; - var $term; - - /** - * Constructor - * @access public - */ - function __construct() - { - global $DIC; - - $tpl = $DIC["tpl"]; - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $ilTabs = $DIC->tabs(); - - // initiate variables - $this->tpl = $tpl; - $this->lng = $lng; - $this->ctrl = $ilCtrl; - $this->glossary = new ilObjGlossary($_GET["ref_id"], true); - $this->definition = new ilGlossaryDefinition($_GET["def"]); - $this->term = new ilGlossaryTerm($this->definition->getTermId()); - $this->term_glossary = new ilObjGlossary(ilGlossaryTerm::_lookGlossaryID($this->definition->getTermId()), false); - $this->tabs_gui = $ilTabs; - - $this->ctrl->saveParameter($this, array("def")); - } - - - function executeCommand() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - // content style - $this->tpl->setCurrentBlock("ContentStyle"); - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->term_glossary->getStyleSheetId())); - $this->tpl->parseCurrentBlock(); - - // syntax style - $this->tpl->setCurrentBlock("SyntaxStyle"); - $this->tpl->setVariable("LOCATION_SYNTAX_STYLESHEET", - ilObjStyleSheet::getSyntaxStylePath()); - $this->tpl->parseCurrentBlock(); - - require_once ("./Modules/Glossary/classes/class.ilGlossaryLocatorGUI.php"); - $gloss_loc = new ilGlossaryLocatorGUI(); - $gloss_loc->setTerm($this->term); - $gloss_loc->setGlossary($this->glossary); - $gloss_loc->setDefinition($this->definition); - -// $this->tpl->getStandardTemplate(); - $this->tpl->setTitle($this->term->getTerm()." - ". - $this->lng->txt("cont_definition")." ". - $this->definition->getNr()); - if ($this->ctrl->getNextClass() == "ilglossarydefpagegui") - { - $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_glo.svg")); - } - - switch ($next_class) - { - - case "ilglossarydefpagegui": - - // output number of usages - if ($ilCtrl->getCmd() == "edit" && - $ilCtrl->getCmdClass() == "ilglossarydefpagegui") - { - $nr = ilGlossaryTerm::getNumberOfUsages($_GET["term_id"]); - if ($nr > 0) - { - $link = "[".$lng->txt("glo_list_usages")."]"; - ilUtil::sendInfo(sprintf($lng->txt("glo_term_is_used_n_times"), - $nr)." ".$link); - } - } - - // not so nice, to do: revise locator handling - if ($this->ctrl->getNextClass() == "ilglossarydefpagegui" - || $this->ctrl->getCmdClass() == "ileditclipboardgui") - { - $gloss_loc->display(); - } - $this->setTabs(); - $this->ctrl->setReturnByClass("ilGlossaryDefPageGUI", "edit"); - $this->ctrl->setReturn($this, "listDefinitions"); - $page_gui = new ilGlossaryDefPageGUI($this->definition->getId()); - $page = $page_gui->getPageObject(); - $this->definition->assignPageObject($page); - $page->addUpdateListener($this, "saveShortText"); - $page_gui->setEditPreview(true); - - // metadata - // ... set title to term, if no title is given - include_once("./Services/MetaData/classes/class.ilMD.php"); - $md = new ilMD($this->term_glossary->getId(), $this->definition->getId(), "gdf"); - $md_gen = $md->getGeneral(); - if ($md_gen->getTitle() == "") - { - $md_gen->setTitle($this->term->getTerm()); - $md_gen->update(); - } - - $page_gui->activateMetaDataEditor($this->term_glossary, "gdf", $this->definition->getId()); - - $page_gui->setSourcecodeDownloadScript("ilias.php?baseClass=ilGlossaryPresentationGUI&ref_id=".$_GET["ref_id"]); - $page_gui->setFullscreenLink("ilias.php?baseClass=ilGlossaryPresentationGUI&cmd=fullscreen&ref_id=".$_GET["ref_id"]); - $page_gui->setTemplateTargetVar("ADM_CONTENT"); - $page_gui->setOutputMode("edit"); - - $page_gui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId( - $this->term_glossary->getStyleSheetId(), "glo")); - $page_gui->setLocator($gloss_loc); - $page_gui->setIntLinkReturn($this->ctrl->getLinkTargetByClass("ilobjglossarygui", "quickList", - "", false, false)); - $page_gui->setPageBackTitle($this->lng->txt("cont_definition")); - $page_gui->setLinkParams("ref_id=".$_GET["ref_id"]); - $page_gui->setHeader($this->term->getTerm()); - $page_gui->setFileDownloadLink("ilias.php?baseClass=ilGlossaryPresentationGUI&cmd=downloadFile&ref_id=".$_GET["ref_id"]); - $page_gui->setPresentationTitle($this->term->getTerm()); - $ret = $this->ctrl->forwardCommand($page_gui); - $tpl->setContent($ret); - break; - - default: - $this->setTabs(); - $gloss_loc->display(); - $ret = $this->$cmd(); - break; - - } - } - - - /** - * output main header (title and locator) - */ - function main_header($a_header_title) - { - $lng = $this->lng; - - $this->tpl->getStandardTemplate(); - $this->tpl->setTitle($a_header_title); - $this->displayLocator(); - //$this->setAdminTabs($a_type); - } - - /** - * output tabs - */ - function setTabs() - { - // catch feedback message - $this->getTabs(); - } - - /** - * get tabs - */ - function getTabs() - { - // back to glossary - $this->tabs_gui->setBack2Target($this->lng->txt("glossary"), - $this->ctrl->getParentReturn($this)); - - // back to upper context - $this->tabs_gui->setBackTarget($this->lng->txt("term"), - $this->ctrl->getLinkTargetByClass("ilglossarytermgui", "editTerm")); - - } - - - function saveShortText() - { - $this->definition->updateShortText(); - } + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTabsGUI + */ + protected $tabs_gui; + + public $tpl; + public $lng; + public $glossary; + public $definition; + public $term; + + /** + * Constructor + * @access public + */ + public function __construct() + { + global $DIC; + + $tpl = $DIC["tpl"]; + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $ilTabs = $DIC->tabs(); + + // initiate variables + $this->tpl = $tpl; + $this->lng = $lng; + $this->ctrl = $ilCtrl; + $this->glossary = new ilObjGlossary($_GET["ref_id"], true); + $this->definition = new ilGlossaryDefinition($_GET["def"]); + $this->term = new ilGlossaryTerm($this->definition->getTermId()); + $this->term_glossary = new ilObjGlossary(ilGlossaryTerm::_lookGlossaryID($this->definition->getTermId()), false); + $this->tabs_gui = $ilTabs; + + $this->ctrl->saveParameter($this, array("def")); + } + + + public function executeCommand() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + // content style + $this->tpl->setCurrentBlock("ContentStyle"); + $this->tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath($this->term_glossary->getStyleSheetId()) + ); + $this->tpl->parseCurrentBlock(); + + // syntax style + $this->tpl->setCurrentBlock("SyntaxStyle"); + $this->tpl->setVariable( + "LOCATION_SYNTAX_STYLESHEET", + ilObjStyleSheet::getSyntaxStylePath() + ); + $this->tpl->parseCurrentBlock(); + + require_once("./Modules/Glossary/classes/class.ilGlossaryLocatorGUI.php"); + $gloss_loc = new ilGlossaryLocatorGUI(); + $gloss_loc->setTerm($this->term); + $gloss_loc->setGlossary($this->glossary); + $gloss_loc->setDefinition($this->definition); + + // $this->tpl->getStandardTemplate(); + $this->tpl->setTitle($this->term->getTerm() . " - " . + $this->lng->txt("cont_definition") . " " . + $this->definition->getNr()); + if ($this->ctrl->getNextClass() == "ilglossarydefpagegui") { + $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_glo.svg")); + } + + switch ($next_class) { + + case "ilglossarydefpagegui": + + // output number of usages + if ($ilCtrl->getCmd() == "edit" && + $ilCtrl->getCmdClass() == "ilglossarydefpagegui") { + $nr = ilGlossaryTerm::getNumberOfUsages($_GET["term_id"]); + if ($nr > 0) { + $link = "[" . $lng->txt("glo_list_usages") . "]"; + ilUtil::sendInfo(sprintf( + $lng->txt("glo_term_is_used_n_times"), + $nr + ) . " " . $link); + } + } + + // not so nice, to do: revise locator handling + if ($this->ctrl->getNextClass() == "ilglossarydefpagegui" + || $this->ctrl->getCmdClass() == "ileditclipboardgui") { + $gloss_loc->display(); + } + $this->setTabs(); + $this->ctrl->setReturnByClass("ilGlossaryDefPageGUI", "edit"); + $this->ctrl->setReturn($this, "listDefinitions"); + $page_gui = new ilGlossaryDefPageGUI($this->definition->getId()); + $page = $page_gui->getPageObject(); + $this->definition->assignPageObject($page); + $page->addUpdateListener($this, "saveShortText"); + $page_gui->setEditPreview(true); + + // metadata + // ... set title to term, if no title is given + include_once("./Services/MetaData/classes/class.ilMD.php"); + $md = new ilMD($this->term_glossary->getId(), $this->definition->getId(), "gdf"); + $md_gen = $md->getGeneral(); + if ($md_gen->getTitle() == "") { + $md_gen->setTitle($this->term->getTerm()); + $md_gen->update(); + } + + $page_gui->activateMetaDataEditor($this->term_glossary, "gdf", $this->definition->getId()); + + $page_gui->setSourcecodeDownloadScript("ilias.php?baseClass=ilGlossaryPresentationGUI&ref_id=" . $_GET["ref_id"]); + $page_gui->setFullscreenLink("ilias.php?baseClass=ilGlossaryPresentationGUI&cmd=fullscreen&ref_id=" . $_GET["ref_id"]); + $page_gui->setTemplateTargetVar("ADM_CONTENT"); + $page_gui->setOutputMode("edit"); + + $page_gui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId( + $this->term_glossary->getStyleSheetId(), + "glo" + )); + $page_gui->setLocator($gloss_loc); + $page_gui->setIntLinkReturn($this->ctrl->getLinkTargetByClass( + "ilobjglossarygui", + "quickList", + "", + false, + false + )); + $page_gui->setPageBackTitle($this->lng->txt("cont_definition")); + $page_gui->setLinkParams("ref_id=" . $_GET["ref_id"]); + $page_gui->setHeader($this->term->getTerm()); + $page_gui->setFileDownloadLink("ilias.php?baseClass=ilGlossaryPresentationGUI&cmd=downloadFile&ref_id=" . $_GET["ref_id"]); + $page_gui->setPresentationTitle($this->term->getTerm()); + $ret = $this->ctrl->forwardCommand($page_gui); + $tpl->setContent($ret); + break; + + default: + $this->setTabs(); + $gloss_loc->display(); + $ret = $this->$cmd(); + break; + + } + } + + + /** + * output main header (title and locator) + */ + public function main_header($a_header_title) + { + $lng = $this->lng; + + $this->tpl->getStandardTemplate(); + $this->tpl->setTitle($a_header_title); + $this->displayLocator(); + //$this->setAdminTabs($a_type); + } + + /** + * output tabs + */ + public function setTabs() + { + // catch feedback message + $this->getTabs(); + } + + /** + * get tabs + */ + public function getTabs() + { + // back to glossary + $this->tabs_gui->setBack2Target( + $this->lng->txt("glossary"), + $this->ctrl->getParentReturn($this) + ); + + // back to upper context + $this->tabs_gui->setBackTarget( + $this->lng->txt("term"), + $this->ctrl->getLinkTargetByClass("ilglossarytermgui", "editTerm") + ); + } + + + public function saveShortText() + { + $this->definition->updateShortText(); + } } -?> diff --git a/Modules/Glossary/classes/class.ilTermListTableGUI.php b/Modules/Glossary/classes/class.ilTermListTableGUI.php index 0a93863a6fb3df24442311f0fdf9be8a5247a64b..3bbe5cedd6ebb581683208443c3ef5046216b3d3 100644 --- a/Modules/Glossary/classes/class.ilTermListTableGUI.php +++ b/Modules/Glossary/classes/class.ilTermListTableGUI.php @@ -1,4 +1,4 @@ -glossary = $a_parent_obj->object; - $this->setId("glotl".$this->glossary->getId()); - $this->tax_node = $a_tax_node; - - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - - $this->selectable_cols = array(); - - include_once("./Modules/Glossary/classes/class.ilGlossaryTermPermission.php"); - $this->term_perm = ilGlossaryTermPermission::getInstance(); - - include_once("./Modules/Glossary/classes/class.ilGlossaryAdvMetaDataAdapter.php"); - $adv_ad = new ilGlossaryAdvMetaDataAdapter($this->glossary->getRefId()); - $this->adv_fields = $adv_ad->getAllFields(); - foreach ($this->adv_fields as $f) - { - $this->selectable_cols["md_".$f["id"]] = array( - "txt" => $f["title"], - "default" => false - ); - } - - // selectable columns - $this->selectable_cols["language"] = array( - "txt" => $this->lng->txt("language"), - "default" => true); - $this->selectable_cols["usage"] = array( - "txt" => $this->lng->txt("cont_usage"), - "default" => true); - - // selectable columns of advanced metadata - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setTitle($this->lng->txt("cont_terms")); - - $this->addColumn("", "", "1", true); - //$this->addColumn($this->lng->txt("cont_term")); - - include_once("./Modules/Glossary/classes/class.ilGlossaryAdvMetaDataAdapter.php"); - $adv_ap = new ilGlossaryAdvMetaDataAdapter($this->glossary->getRefId()); - $this->adv_cols_order = $adv_ap->getColumnOrder(); - $this->selected_cols = $this->getSelectedColumns(); - foreach ($this->adv_cols_order as $c) - { - if ($c["id"] == 0) - { - $this->addColumn($this->lng->txt("cont_term"), "term"); - } - else - { - if (in_array("md_".$c["id"], $this->selected_cols)) - { - $this->addColumn($c["text"], "md_".$c["id"]); - } - } - } - - foreach (array ("language", "usage") as $c) - { - if (in_array($c, $this->selected_cols)) - { - $this->addColumn($this->selectable_cols[$c]["txt"]); - } - } - - $this->setDefaultOrderDirection("asc"); - $this->setDefaultOrderField("term"); - $this->addColumn($this->lng->txt("cont_definitions")); - - if ($this->showGlossaryColumn()) - { - $this->addColumn($this->lng->txt("obj_glo")); - } - - $this->addColumn("", "", "1"); - - $this->setEnableHeader(true); - $this->setFormAction($this->ctrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.term_tbl_row.html", "Modules/Glossary"); - $this->setEnableTitle(true); - - $this->addMultiCommand("copyTerms", $this->lng->txt("copy")); - $this->addMultiCommand("referenceTerms", $this->lng->txt("glo_reference")); - $this->addMultiCommand("confirmTermDeletion", $this->lng->txt("delete")); - //$this->addMultiCommand("addDefinition", $this->lng->txt("cont_add_definition")); - - $this->setShowRowsSelector(true); - - $this->initFilter(); - $this->setData($this->glossary->getTermList($this->filter["term"], "", - $this->filter["definition"], $this->tax_node, true, true, null, false, true)); - } - - /** - * Show glossary column - * - * @param - * @return - */ - function showGlossaryColumn() - { - include_once("./Modules/Glossary/classes/class.ilGlossaryTermReferences.php"); - return (in_array($this->glossary->getVirtualMode(), - array("level", "subtree")) || ilGlossaryTermReferences::hasReferences($this->glossary->getId())); - } - - - /** - * Get selectable columns - * - * @param - * @return - */ - function getSelectableColumns() - { - return $this->selectable_cols; - } - - /** - * Should this field be sorted numeric? - * - * @return boolean numeric ordering; default is false - */ - function numericOrdering($a_field) - { - if (substr($a_field, 0, 3) == "md_") - { - $md_id = (int) substr($a_field, 3); - if ($this->adv_fields[$md_id]["type"] == ilAdvancedMDFieldDefinition::TYPE_DATE) - { - return true; - } - } - return false; - } - - /** - * Init filter - */ - function initFilter() - { - // term - include_once("./Services/Form/classes/class.ilTextInputGUI.php"); - $ti = new ilTextInputGUI($this->lng->txt("cont_term"), "term"); - $ti->setMaxLength(64); - $ti->setSize(20); - $ti->setSubmitFormOnEnter(true); - $this->addFilterItem($ti); - $ti->readFromSession(); - $this->filter["term"] = $ti->getValue(); - - // definition - if ($this->glossary->supportsLongTextQuery()) - { - include_once("./Services/Form/classes/class.ilTextInputGUI.php"); - $ti = new ilTextInputGUI($this->lng->txt("cont_definition"), "defintion"); - $ti->setMaxLength(64); - $ti->setSize(20); - $ti->setSubmitFormOnEnter(true); - $this->addFilterItem($ti); - $ti->readFromSession(); - $this->filter["definition"] = $ti->getValue(); - } - } - - /** - * Fill table row - */ - protected function fillRow($term) - { - include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"); - - $defs = ilGlossaryDefinition::getDefinitionList($term["id"]); - $this->ctrl->setParameterByClass("ilobjglossarygui", "term_id", $term["id"]); - $this->ctrl->setParameterByClass("ilglossarytermgui", "term_id", $term["id"]); - $this->ctrl->setParameterByClass("ilglossarydefpagegui", "term_id", $term["id"]); - - // actions drop down - //if ($this->glossary->getId() == $term["glo_id"]) - - if ($this->term_perm->checkPermission("write", $term["id"]) || - $this->term_perm->checkPermission("edit_content", $term["id"])) - { - include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - include_once("./Modules/Glossary/classes/class.ilGlossaryTermReferences.php"); - if (ilGlossaryTerm::_lookGlossaryID($term["id"]) == $this->glossary->getId() || - ilGlossaryTermReferences::isReferenced($this->glossary->getId(), $term["id"])) - { - $list = new ilAdvancedSelectionListGUI(); - $list->addItem($this->lng->txt("cont_edit_term"), "", $this->ctrl->getLinkTargetByClass("ilglossarytermgui", "editTerm")); - if (count($defs) > 1) - { - $list->addItem($this->lng->txt("cont_edit_definitions"), "", $this->ctrl->getLinkTargetByClass("ilglossarytermgui", "listDefinitions")); - } else if (count($defs) == 1) - { - $this->ctrl->setParameterByClass("ilglossarydefpagegui", "def", $defs[0]["id"]); - $list->addItem($this->lng->txt("cont_edit_definition"), "", $this->ctrl->getLinkTargetByClass(array("ilglossarytermgui", - "iltermdefinitioneditorgui", - "ilglossarydefpagegui"), "edit")); - } - $list->addItem($this->lng->txt("cont_add_definition"), "", $this->ctrl->getLinkTargetByClass("ilobjglossarygui", "addDefinition")); - $this->ctrl->setParameterByClass("ilglossarydefpagegui", "def", ""); - - $list->setId("act_term_" . $term["id"]); - $list->setListTitle($this->lng->txt("actions")); - $this->tpl->setVariable("ACTIONS", $list->getHTML()); - } - } - - - for($j=0; $jtpl->setCurrentBlock("definition"); - $short_str = $def["short_text"]; - - if ($def["short_text_dirty"]) - { - // #18022 - $def_obj = new ilGlossaryDefinition($def["id"]); - $def_obj->updateShortText(); - $short_str = $def_obj->getShortText(); - } - - // replace tex - // if a tex end tag is missing a tex end tag - $ltexs = strrpos($short_str, "[tex]"); - $ltexe = strrpos($short_str, "[/tex]"); - if ($ltexs > $ltexe) - { - $page = new ilGlossaryDefPage($def["id"]); - $page->buildDom(); - $short_str = $page->getFirstParagraphText(); - $short_str = strip_tags($short_str, "
"); - $ltexe = strpos($short_str, "[/tex]", $ltexs); - $short_str = ilUtil::shortenText($short_str, $ltexe+6, true); - } - - include_once './Services/MathJax/classes/class.ilMathJax.php'; - $short_str = ilMathJax::getInstance()->insertLatexImages($short_str); - - $short_str = ilPCParagraph::xml2output($short_str); - $this->tpl->setVariable("DEF_SHORT", $short_str); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setCurrentBlock("definition_row"); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setCurrentBlock("check_col"); - $this->tpl->setVariable("CHECKBOX_ID", $term["id"]); - $this->tpl->parseCurrentBlock(); - - $this->ctrl->setParameter($this->parent_obj, "term_id", $term["id"]); - - - // usage - if (in_array("usage", $this->getSelectedColumns())) - { - $nr_usage = ilGlossaryTerm::getNumberOfUsages($term["id"]); - if ($nr_usage > 0 && $this->glossary->getId() == $term["glo_id"]) - { - $this->tpl->setCurrentBlock("link_usage"); - $this->ctrl->setParameterByClass("ilglossarytermgui", "term_id", $term["id"]); - $this->tpl->setVariable("LUSAGE", ilGlossaryTerm::getNumberOfUsages($term["id"])); - $this->tpl->setVariable("LINK_USAGE", - $this->ctrl->getLinkTargetByClass("ilglossarytermgui", "listUsages")); - $this->ctrl->setParameterByClass("ilglossarytermgui", "term_id", ""); - $this->tpl->parseCurrentBlock(); - } - else - { - $this->tpl->setCurrentBlock("usage"); - $this->tpl->setVariable("USAGE", ilGlossaryTerm::getNumberOfUsages($term["id"])); - $this->tpl->parseCurrentBlock(); - } - $this->tpl->setCurrentBlock("td_usage"); - $this->tpl->parseCurrentBlock(); - } - - // glossary title - if ($this->showGlossaryColumn()) - { - $this->tpl->setCurrentBlock("glossary"); - $this->tpl->setVariable("GLO_TITLE", ilObject::_lookupTitle($term["glo_id"])); - $this->tpl->parseCurrentBlock(); - } - - // output language - if (in_array("language", $this->getSelectedColumns())) - { - $this->tpl->setCurrentBlock("td_lang"); - $this->tpl->setVariable("TEXT_LANGUAGE", $this->lng->txt("meta_l_".$term["language"])); - $this->tpl->parseCurrentBlock(); - } - - - foreach ($this->adv_cols_order as $c) - { - if ($c["id"] == 0) - { - $this->tpl->setCurrentBlock("td"); - $this->tpl->setVariable("TD_VAL", $term["term"]); - $this->tpl->parseCurrentBlock(); - } - else - { - if (in_array("md_".$c["id"], $this->selected_cols)) - { - $id = (int) $c["id"]; - - $val = " "; - if(isset($term["md_".$id."_presentation"])) - { - $pb = $term["md_".$id."_presentation"]->getHTML(); - if($pb) - { - $val = $pb; - } - } - - $this->tpl->setCurrentBlock("td"); - $this->tpl->setVariable("TD_VAL", $val); - $this->tpl->parseCurrentBlock(); - } - } - } - } - + /** + * @var ilObjGlossary + */ + protected $glossary; + + /** + * @var ilGlossaryTermPermission + */ + protected $term_perm; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_tax_node) + { + global $DIC; + + $this->glossary = $a_parent_obj->object; + $this->setId("glotl" . $this->glossary->getId()); + $this->tax_node = $a_tax_node; + + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + + $this->selectable_cols = array(); + + include_once("./Modules/Glossary/classes/class.ilGlossaryTermPermission.php"); + $this->term_perm = ilGlossaryTermPermission::getInstance(); + + include_once("./Modules/Glossary/classes/class.ilGlossaryAdvMetaDataAdapter.php"); + $adv_ad = new ilGlossaryAdvMetaDataAdapter($this->glossary->getRefId()); + $this->adv_fields = $adv_ad->getAllFields(); + foreach ($this->adv_fields as $f) { + $this->selectable_cols["md_" . $f["id"]] = array( + "txt" => $f["title"], + "default" => false + ); + } + + // selectable columns + $this->selectable_cols["language"] = array( + "txt" => $this->lng->txt("language"), + "default" => true); + $this->selectable_cols["usage"] = array( + "txt" => $this->lng->txt("cont_usage"), + "default" => true); + + // selectable columns of advanced metadata + + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setTitle($this->lng->txt("cont_terms")); + + $this->addColumn("", "", "1", true); + //$this->addColumn($this->lng->txt("cont_term")); + + include_once("./Modules/Glossary/classes/class.ilGlossaryAdvMetaDataAdapter.php"); + $adv_ap = new ilGlossaryAdvMetaDataAdapter($this->glossary->getRefId()); + $this->adv_cols_order = $adv_ap->getColumnOrder(); + $this->selected_cols = $this->getSelectedColumns(); + foreach ($this->adv_cols_order as $c) { + if ($c["id"] == 0) { + $this->addColumn($this->lng->txt("cont_term"), "term"); + } else { + if (in_array("md_" . $c["id"], $this->selected_cols)) { + $this->addColumn($c["text"], "md_" . $c["id"]); + } + } + } + + foreach (array("language", "usage") as $c) { + if (in_array($c, $this->selected_cols)) { + $this->addColumn($this->selectable_cols[$c]["txt"]); + } + } + + $this->setDefaultOrderDirection("asc"); + $this->setDefaultOrderField("term"); + $this->addColumn($this->lng->txt("cont_definitions")); + + if ($this->showGlossaryColumn()) { + $this->addColumn($this->lng->txt("obj_glo")); + } + + $this->addColumn("", "", "1"); + + $this->setEnableHeader(true); + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.term_tbl_row.html", "Modules/Glossary"); + $this->setEnableTitle(true); + + $this->addMultiCommand("copyTerms", $this->lng->txt("copy")); + $this->addMultiCommand("referenceTerms", $this->lng->txt("glo_reference")); + $this->addMultiCommand("confirmTermDeletion", $this->lng->txt("delete")); + //$this->addMultiCommand("addDefinition", $this->lng->txt("cont_add_definition")); + + $this->setShowRowsSelector(true); + + $this->initFilter(); + $this->setData($this->glossary->getTermList( + $this->filter["term"], + "", + $this->filter["definition"], + $this->tax_node, + true, + true, + null, + false, + true + )); + } + + /** + * Show glossary column + * + * @param + * @return + */ + public function showGlossaryColumn() + { + include_once("./Modules/Glossary/classes/class.ilGlossaryTermReferences.php"); + return (in_array( + $this->glossary->getVirtualMode(), + array("level", "subtree") + ) || ilGlossaryTermReferences::hasReferences($this->glossary->getId())); + } + + + /** + * Get selectable columns + * + * @param + * @return + */ + public function getSelectableColumns() + { + return $this->selectable_cols; + } + + /** + * Should this field be sorted numeric? + * + * @return boolean numeric ordering; default is false + */ + public function numericOrdering($a_field) + { + if (substr($a_field, 0, 3) == "md_") { + $md_id = (int) substr($a_field, 3); + if ($this->adv_fields[$md_id]["type"] == ilAdvancedMDFieldDefinition::TYPE_DATE) { + return true; + } + } + return false; + } + + /** + * Init filter + */ + public function initFilter() + { + // term + include_once("./Services/Form/classes/class.ilTextInputGUI.php"); + $ti = new ilTextInputGUI($this->lng->txt("cont_term"), "term"); + $ti->setMaxLength(64); + $ti->setSize(20); + $ti->setSubmitFormOnEnter(true); + $this->addFilterItem($ti); + $ti->readFromSession(); + $this->filter["term"] = $ti->getValue(); + + // definition + if ($this->glossary->supportsLongTextQuery()) { + include_once("./Services/Form/classes/class.ilTextInputGUI.php"); + $ti = new ilTextInputGUI($this->lng->txt("cont_definition"), "defintion"); + $ti->setMaxLength(64); + $ti->setSize(20); + $ti->setSubmitFormOnEnter(true); + $this->addFilterItem($ti); + $ti->readFromSession(); + $this->filter["definition"] = $ti->getValue(); + } + } + + /** + * Fill table row + */ + protected function fillRow($term) + { + include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"); + + $defs = ilGlossaryDefinition::getDefinitionList($term["id"]); + $this->ctrl->setParameterByClass("ilobjglossarygui", "term_id", $term["id"]); + $this->ctrl->setParameterByClass("ilglossarytermgui", "term_id", $term["id"]); + $this->ctrl->setParameterByClass("ilglossarydefpagegui", "term_id", $term["id"]); + + // actions drop down + //if ($this->glossary->getId() == $term["glo_id"]) + + if ($this->term_perm->checkPermission("write", $term["id"]) || + $this->term_perm->checkPermission("edit_content", $term["id"])) { + include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + include_once("./Modules/Glossary/classes/class.ilGlossaryTermReferences.php"); + if (ilGlossaryTerm::_lookGlossaryID($term["id"]) == $this->glossary->getId() || + ilGlossaryTermReferences::isReferenced($this->glossary->getId(), $term["id"])) { + $list = new ilAdvancedSelectionListGUI(); + $list->addItem($this->lng->txt("cont_edit_term"), "", $this->ctrl->getLinkTargetByClass("ilglossarytermgui", "editTerm")); + if (count($defs) > 1) { + $list->addItem($this->lng->txt("cont_edit_definitions"), "", $this->ctrl->getLinkTargetByClass("ilglossarytermgui", "listDefinitions")); + } elseif (count($defs) == 1) { + $this->ctrl->setParameterByClass("ilglossarydefpagegui", "def", $defs[0]["id"]); + $list->addItem($this->lng->txt("cont_edit_definition"), "", $this->ctrl->getLinkTargetByClass(array("ilglossarytermgui", + "iltermdefinitioneditorgui", + "ilglossarydefpagegui"), "edit")); + } + $list->addItem($this->lng->txt("cont_add_definition"), "", $this->ctrl->getLinkTargetByClass("ilobjglossarygui", "addDefinition")); + $this->ctrl->setParameterByClass("ilglossarydefpagegui", "def", ""); + + $list->setId("act_term_" . $term["id"]); + $list->setListTitle($this->lng->txt("actions")); + $this->tpl->setVariable("ACTIONS", $list->getHTML()); + } + } + + + for ($j=0; $jtpl->setCurrentBlock("definition"); + $short_str = $def["short_text"]; + + if ($def["short_text_dirty"]) { + // #18022 + $def_obj = new ilGlossaryDefinition($def["id"]); + $def_obj->updateShortText(); + $short_str = $def_obj->getShortText(); + } + + // replace tex + // if a tex end tag is missing a tex end tag + $ltexs = strrpos($short_str, "[tex]"); + $ltexe = strrpos($short_str, "[/tex]"); + if ($ltexs > $ltexe) { + $page = new ilGlossaryDefPage($def["id"]); + $page->buildDom(); + $short_str = $page->getFirstParagraphText(); + $short_str = strip_tags($short_str, "
"); + $ltexe = strpos($short_str, "[/tex]", $ltexs); + $short_str = ilUtil::shortenText($short_str, $ltexe+6, true); + } + + include_once './Services/MathJax/classes/class.ilMathJax.php'; + $short_str = ilMathJax::getInstance()->insertLatexImages($short_str); + + $short_str = ilPCParagraph::xml2output($short_str); + $this->tpl->setVariable("DEF_SHORT", $short_str); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setCurrentBlock("definition_row"); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setCurrentBlock("check_col"); + $this->tpl->setVariable("CHECKBOX_ID", $term["id"]); + $this->tpl->parseCurrentBlock(); + + $this->ctrl->setParameter($this->parent_obj, "term_id", $term["id"]); + + + // usage + if (in_array("usage", $this->getSelectedColumns())) { + $nr_usage = ilGlossaryTerm::getNumberOfUsages($term["id"]); + if ($nr_usage > 0 && $this->glossary->getId() == $term["glo_id"]) { + $this->tpl->setCurrentBlock("link_usage"); + $this->ctrl->setParameterByClass("ilglossarytermgui", "term_id", $term["id"]); + $this->tpl->setVariable("LUSAGE", ilGlossaryTerm::getNumberOfUsages($term["id"])); + $this->tpl->setVariable( + "LINK_USAGE", + $this->ctrl->getLinkTargetByClass("ilglossarytermgui", "listUsages") + ); + $this->ctrl->setParameterByClass("ilglossarytermgui", "term_id", ""); + $this->tpl->parseCurrentBlock(); + } else { + $this->tpl->setCurrentBlock("usage"); + $this->tpl->setVariable("USAGE", ilGlossaryTerm::getNumberOfUsages($term["id"])); + $this->tpl->parseCurrentBlock(); + } + $this->tpl->setCurrentBlock("td_usage"); + $this->tpl->parseCurrentBlock(); + } + + // glossary title + if ($this->showGlossaryColumn()) { + $this->tpl->setCurrentBlock("glossary"); + $this->tpl->setVariable("GLO_TITLE", ilObject::_lookupTitle($term["glo_id"])); + $this->tpl->parseCurrentBlock(); + } + + // output language + if (in_array("language", $this->getSelectedColumns())) { + $this->tpl->setCurrentBlock("td_lang"); + $this->tpl->setVariable("TEXT_LANGUAGE", $this->lng->txt("meta_l_" . $term["language"])); + $this->tpl->parseCurrentBlock(); + } + + + foreach ($this->adv_cols_order as $c) { + if ($c["id"] == 0) { + $this->tpl->setCurrentBlock("td"); + $this->tpl->setVariable("TD_VAL", $term["term"]); + $this->tpl->parseCurrentBlock(); + } else { + if (in_array("md_" . $c["id"], $this->selected_cols)) { + $id = (int) $c["id"]; + + $val = " "; + if (isset($term["md_" . $id . "_presentation"])) { + $pb = $term["md_" . $id . "_presentation"]->getHTML(); + if ($pb) { + $val = $pb; + } + } + + $this->tpl->setCurrentBlock("td"); + $this->tpl->setVariable("TD_VAL", $val); + $this->tpl->parseCurrentBlock(); + } + } + } + } } -?> \ No newline at end of file diff --git a/Modules/Glossary/classes/class.ilTermQuickListTableGUI.php b/Modules/Glossary/classes/class.ilTermQuickListTableGUI.php index 34280ddd8f813136e51d14754d445fddfc1bd268..550d0fec6fadb64f5e8c737682ede2e69c7446ab 100644 --- a/Modules/Glossary/classes/class.ilTermQuickListTableGUI.php +++ b/Modules/Glossary/classes/class.ilTermQuickListTableGUI.php @@ -1,4 +1,4 @@ -ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilAccess = $DIC->access(); - $lng = $DIC->language(); - - $this->glossary = $a_parent_obj->glossary; - $this->setId("gloqtl".$this->glossary->getId()); - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setTitle($lng->txt("cont_terms")); - - $this->addColumn("", ""); - $this->setEnableHeader(false); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.term_quick_list_row.html", "Modules/Glossary"); - $this->setEnableTitle(false); + $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->glossary = $a_parent_obj->glossary; + $this->setId("gloqtl" . $this->glossary->getId()); + + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setTitle($lng->txt("cont_terms")); + + $this->addColumn("", ""); + $this->setEnableHeader(false); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.term_quick_list_row.html", "Modules/Glossary"); + $this->setEnableTitle(false); - //$this->setData($this->glossary->getTermList($this->filter["term"], "", - // $this->filter["definition"])); - $this->setData($this->glossary->getTermList("", "", "", 0, false, false, null, true)); - } - - /** - * Fill table row - */ - protected function fillRow($term) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; + //$this->setData($this->glossary->getTermList($this->filter["term"], "", + // $this->filter["definition"])); + $this->setData($this->glossary->getTermList("", "", "", 0, false, false, null, true)); + } + + /** + * Fill table row + */ + protected function fillRow($term) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; - $defs = ilGlossaryDefinition::getDefinitionList($term["id"]); - $ilCtrl->setParameterByClass("ilglossarytermgui", "term_id", $term["id"]); - - $sep = ": "; - for($j=0; $j < count($defs); $j++) - { - $def = $defs[$j]; + $defs = ilGlossaryDefinition::getDefinitionList($term["id"]); + $ilCtrl->setParameterByClass("ilglossarytermgui", "term_id", $term["id"]); + + $sep = ": "; + for ($j=0; $j < count($defs); $j++) { + $def = $defs[$j]; - $this->tpl->setCurrentBlock("definition"); - $this->tpl->setVariable("SEP", $sep); - $ilCtrl->setParameterByClass("ilglossarydefpagegui", "def", $def["id"]); - $this->tpl->setVariable("LINK_EDIT_DEF", - $ilCtrl->getLinkTargetByClass(array("ilglossarytermgui", - "iltermdefinitioneditorgui", - "ilglossarydefpagegui"), "edit")); - $this->tpl->setVariable("TEXT_DEF", $this->lng->txt("glo_definition_abbr").($j+1)); - $this->tpl->parseCurrentBlock(); - $sep = ", "; - } - $ilCtrl->setParameterByClass("ilglossarydefpagegui", "def", $_GET["def"]); - - if ($term["id"] == $_GET["term_id"]) - { - $this->tpl->touchBlock("hl"); - } - - $this->tpl->setVariable("TEXT_TERM", $term["term"]); - $this->tpl->setVariable("LINK_EDIT_TERM", - $ilCtrl->getLinkTargetByClass("ilglossarytermgui", "editTerm")); - - $ilCtrl->setParameterByClass("ilglossarytermgui", "term_id", $_GET["term_id"]); - } + $this->tpl->setCurrentBlock("definition"); + $this->tpl->setVariable("SEP", $sep); + $ilCtrl->setParameterByClass("ilglossarydefpagegui", "def", $def["id"]); + $this->tpl->setVariable( + "LINK_EDIT_DEF", + $ilCtrl->getLinkTargetByClass(array("ilglossarytermgui", + "iltermdefinitioneditorgui", + "ilglossarydefpagegui"), "edit") + ); + $this->tpl->setVariable("TEXT_DEF", $this->lng->txt("glo_definition_abbr") . ($j+1)); + $this->tpl->parseCurrentBlock(); + $sep = ", "; + } + $ilCtrl->setParameterByClass("ilglossarydefpagegui", "def", $_GET["def"]); + if ($term["id"] == $_GET["term_id"]) { + $this->tpl->touchBlock("hl"); + } + + $this->tpl->setVariable("TEXT_TERM", $term["term"]); + $this->tpl->setVariable( + "LINK_EDIT_TERM", + $ilCtrl->getLinkTargetByClass("ilglossarytermgui", "editTerm") + ); + + $ilCtrl->setParameterByClass("ilglossarytermgui", "term_id", $_GET["term_id"]); + } } -?> \ No newline at end of file diff --git a/Modules/Glossary/classes/class.ilTermUsagesTableGUI.php b/Modules/Glossary/classes/class.ilTermUsagesTableGUI.php index 8dcf942beb32064e24bd887ecfbe7f175b47de3d..f81a3035ed16aff670671868bfde477513d377f3 100644 --- a/Modules/Glossary/classes/class.ilTermUsagesTableGUI.php +++ b/Modules/Glossary/classes/class.ilTermUsagesTableGUI.php @@ -13,316 +13,281 @@ include_once("Services/Table/classes/class.ilTable2GUI.php"); */ class ilTermUsagesTableGUI extends ilTable2GUI { - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_term_id) - { - global $DIC; + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_term_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(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->term_id = $a_term_id; - - $this->addColumn("", "", "1"); // checkbox - $this->setEnableHeader(false); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.term_usage_row.html", "Modules/Glossary"); - $this->getItems(); - $this->setTitle($lng->txt("cont_usage")); - } + $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); + $this->term_id = $a_term_id; + + $this->addColumn("", "", "1"); // checkbox + $this->setEnableHeader(false); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.term_usage_row.html", "Modules/Glossary"); + $this->getItems(); + $this->setTitle($lng->txt("cont_usage")); + } - /** - * Get items of current folder - */ - function getItems() - { - $usages = ilGlossaryTerm::getUsages($this->term_id); - - $clip_cnt = 0; - $to_del = array(); - $agg_usages = array(); - foreach($usages as $k => $usage) - { - if (empty($agg_usages[$usage["type"].":".$usage["id"]])) - { - $usage["hist_nr"] = array($usage["hist_nr"]); - $agg_usages[$usage["type"].":".$usage["id"]] = $usage; - } - else - { - $agg_usages[$usage["type"].":".$usage["id"]]["hist_nr"][] = - $usage["hist_nr"]; - } - } + /** + * Get items of current folder + */ + public function getItems() + { + $usages = ilGlossaryTerm::getUsages($this->term_id); + + $clip_cnt = 0; + $to_del = array(); + $agg_usages = array(); + foreach ($usages as $k => $usage) { + if (empty($agg_usages[$usage["type"] . ":" . $usage["id"]])) { + $usage["hist_nr"] = array($usage["hist_nr"]); + $agg_usages[$usage["type"] . ":" . $usage["id"]] = $usage; + } else { + $agg_usages[$usage["type"] . ":" . $usage["id"]]["hist_nr"][] = + $usage["hist_nr"]; + } + } - $this->setData($agg_usages); - } - - /** - * Standard Version of Fill Row. Most likely to - * be overwritten by derived class. - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; + $this->setData($agg_usages); + } + + /** + * Standard Version of Fill Row. Most likely to + * be overwritten by derived class. + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; - $usage = $a_set; - - if(is_int(strpos($usage["type"], ":"))) - { - $us_arr = explode(":", $usage["type"]); - $usage["type"] = $us_arr[1]; - $cont_type = $us_arr[0]; - } + $usage = $a_set; + + if (is_int(strpos($usage["type"], ":"))) { + $us_arr = explode(":", $usage["type"]); + $usage["type"] = $us_arr[1]; + $cont_type = $us_arr[0]; + } - include_once('./Services/Link/classes/class.ilLink.php'); + include_once('./Services/Link/classes/class.ilLink.php'); - switch($usage["type"]) - { - case "pg": - $item = array(); + switch ($usage["type"]) { + case "pg": + $item = array(); - //$this->tpl->setVariable("TXT_OBJECT", $usage["type"].":".$usage["id"]); - switch ($cont_type) - { - case "sahs": - require_once("./Modules/Scorm2004/classes/class.ilSCORM2004Page.php"); - $page_obj = new ilSCORM2004Page($usage["id"]); + //$this->tpl->setVariable("TXT_OBJECT", $usage["type"].":".$usage["id"]); + switch ($cont_type) { + case "sahs": + require_once("./Modules/Scorm2004/classes/class.ilSCORM2004Page.php"); + $page_obj = new ilSCORM2004Page($usage["id"]); - require_once("./Modules/ScormAicc/classes/class.ilObjSAHSLearningModule.php"); - require_once("./Modules/Scorm2004/classes/class.ilSCORM2004PageNode.php"); - $lm_obj = new ilObjSAHSLearningModule($page_obj->getParentId(), false); - $item["obj_type_txt"] = $this->lng->txt("obj_".$cont_type); - $item["obj_title"] = $lm_obj->getTitle(); - $item["sub_txt"] = $this->lng->txt("pg"); - $item["sub_title"] = ilSCORM2004PageNode::_lookupTitle($page_obj->getId()); - $ref_id = $this->getFirstWritableRefId($lm_obj->getId()); - if ($ref_id > 0) - { - $item["obj_link"] = ilLink::_getStaticLink($ref_id, "sahs"); - } - break; - - case "lm": - require_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - $page_obj = new ilLMPage($usage["id"]); + require_once("./Modules/ScormAicc/classes/class.ilObjSAHSLearningModule.php"); + require_once("./Modules/Scorm2004/classes/class.ilSCORM2004PageNode.php"); + $lm_obj = new ilObjSAHSLearningModule($page_obj->getParentId(), false); + $item["obj_type_txt"] = $this->lng->txt("obj_" . $cont_type); + $item["obj_title"] = $lm_obj->getTitle(); + $item["sub_txt"] = $this->lng->txt("pg"); + $item["sub_title"] = ilSCORM2004PageNode::_lookupTitle($page_obj->getId()); + $ref_id = $this->getFirstWritableRefId($lm_obj->getId()); + if ($ref_id > 0) { + $item["obj_link"] = ilLink::_getStaticLink($ref_id, "sahs"); + } + break; + + case "lm": + require_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + $page_obj = new ilLMPage($usage["id"]); - require_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); - require_once("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); - require_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - $lm_obj = new ilObjLearningModule($page_obj->getParentId(), false); - $item["obj_type_txt"] = $this->lng->txt("obj_".$cont_type); - $item["obj_title"] = $lm_obj->getTitle(); - $item["sub_txt"] = $this->lng->txt("pg"); - $item["sub_title"] = ilLMObject::_lookupTitle($page_obj->getId()); - $ref_id = $this->getFirstWritableRefId($lm_obj->getId()); - if ($ref_id > 0) - { - $item["obj_link"] = ilLink::_getStaticLink($ref_id, "lm"); - } - break; - - case "wpg": - require_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $page_obj = new ilWikiPage($usage["id"]); - $item["obj_type_txt"] = $this->lng->txt("obj_wiki"); - $item["obj_title"] = ilObject::_lookupTitle($page_obj->getParentId()); - $item["sub_txt"] = $this->lng->txt("pg"); - $item["sub_title"] = ilWikiPage::lookupTitle($page_obj->getId()); - $ref_id = $this->getFirstWritableRefId($page_obj->getParentId()); - if ($ref_id > 0) - { - $item["obj_link"] = ilLink::_getStaticLink($ref_id, "wiki"); - } - break; + require_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); + require_once("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); + require_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + $lm_obj = new ilObjLearningModule($page_obj->getParentId(), false); + $item["obj_type_txt"] = $this->lng->txt("obj_" . $cont_type); + $item["obj_title"] = $lm_obj->getTitle(); + $item["sub_txt"] = $this->lng->txt("pg"); + $item["sub_title"] = ilLMObject::_lookupTitle($page_obj->getId()); + $ref_id = $this->getFirstWritableRefId($lm_obj->getId()); + if ($ref_id > 0) { + $item["obj_link"] = ilLink::_getStaticLink($ref_id, "lm"); + } + break; + + case "wpg": + require_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + $page_obj = new ilWikiPage($usage["id"]); + $item["obj_type_txt"] = $this->lng->txt("obj_wiki"); + $item["obj_title"] = ilObject::_lookupTitle($page_obj->getParentId()); + $item["sub_txt"] = $this->lng->txt("pg"); + $item["sub_title"] = ilWikiPage::lookupTitle($page_obj->getId()); + $ref_id = $this->getFirstWritableRefId($page_obj->getParentId()); + if ($ref_id > 0) { + $item["obj_link"] = ilLink::_getStaticLink($ref_id, "wiki"); + } + break; - case "gdf": - require_once("./Modules/Glossary/classes/class.ilGlossaryDefPage.php"); - $page_obj = new ilGlossaryDefPage($usage["id"]); - require_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - require_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); - $term_id = ilGlossaryDefinition::_lookupTermId($page_obj->getId()); - $glo_id = ilGlossaryTerm::_lookGlossaryId($term_id); - $item["obj_type_txt"] = $this->lng->txt("obj_glo"); - $item["obj_title"] = ilObject::_lookupTitle($glo_id); - $item["sub_txt"] = $this->lng->txt("cont_term"); - $item["sub_title"] = ilGlossaryTerm::_lookGlossaryTerm($term_id); - $ref_id = $this->getFirstWritableRefId($page_obj->getParentId()); - if ($ref_id > 0) - { - $item["obj_link"] = ilLink::_getStaticLink($ref_id, "glo"); - } - break; + case "gdf": + require_once("./Modules/Glossary/classes/class.ilGlossaryDefPage.php"); + $page_obj = new ilGlossaryDefPage($usage["id"]); + require_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + require_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); + $term_id = ilGlossaryDefinition::_lookupTermId($page_obj->getId()); + $glo_id = ilGlossaryTerm::_lookGlossaryId($term_id); + $item["obj_type_txt"] = $this->lng->txt("obj_glo"); + $item["obj_title"] = ilObject::_lookupTitle($glo_id); + $item["sub_txt"] = $this->lng->txt("cont_term"); + $item["sub_title"] = ilGlossaryTerm::_lookGlossaryTerm($term_id); + $ref_id = $this->getFirstWritableRefId($page_obj->getParentId()); + if ($ref_id > 0) { + $item["obj_link"] = ilLink::_getStaticLink($ref_id, "glo"); + } + break; - case "fold": - case "root": - case "crs": - case "grp": - case "cat": - case "cont": - $item["obj_type_txt"] = $this->lng->txt("obj_".$cont_type); - $item["obj_title"] = ilObject::_lookupTitle($usage["id"]); - $ref_id = $this->getFirstWritableRefId($usage["id"]); - if ($ref_id > 0) - { - $item["obj_link"] = ilLink::_getStaticLink($ref_id, $cont_type); - } - break; + case "fold": + case "root": + case "crs": + case "grp": + case "cat": + case "cont": + $item["obj_type_txt"] = $this->lng->txt("obj_" . $cont_type); + $item["obj_title"] = ilObject::_lookupTitle($usage["id"]); + $ref_id = $this->getFirstWritableRefId($usage["id"]); + if ($ref_id > 0) { + $item["obj_link"] = ilLink::_getStaticLink($ref_id, $cont_type); + } + break; - default: - $item["obj_title"] = "Page ".$cont_type.", ".$usage["id"]; - break; - } - break; + default: + $item["obj_title"] = "Page " . $cont_type . ", " . $usage["id"]; + break; + } + break; - case "mep": - $item["obj_type_txt"] = $this->lng->txt("obj_mep"); - $item["obj_title"] = ilObject::_lookupTitle($usage["id"]); - $ref_id = $this->getFirstWritableRefId($usage["id"]); - if ($ref_id > 0) - { - $item["obj_link"] = ilLink::_getStaticLink($ref_id, "mep"); - } - break; + case "mep": + $item["obj_type_txt"] = $this->lng->txt("obj_mep"); + $item["obj_title"] = ilObject::_lookupTitle($usage["id"]); + $ref_id = $this->getFirstWritableRefId($usage["id"]); + if ($ref_id > 0) { + $item["obj_link"] = ilLink::_getStaticLink($ref_id, "mep"); + } + break; - case "map": - $item["obj_type_txt"] = $this->lng->txt("obj_mob"); - $item["obj_title"] = ilObject::_lookupTitle($usage["id"]); - $item["sub_txt"] = $this->lng->txt("cont_link_area"); - break; + case "map": + $item["obj_type_txt"] = $this->lng->txt("obj_mob"); + $item["obj_title"] = ilObject::_lookupTitle($usage["id"]); + $item["sub_txt"] = $this->lng->txt("cont_link_area"); + break; - case "sqst": - $item["obj_type_txt"] = $this->lng->txt("cont_sqst"); - include_once("./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"); - $obj_id = SurveyQuestion::lookupObjFi($usage["id"]); - $item["obj_title"] = ilObject::_lookupTitle($obj_id); - $item["sub_txt"] = $this->lng->txt("question"); - $item["sub_title"] = SurveyQuestion::_getTitle($usage["id"]); - $ref_id = $this->getFirstWritableRefId($obj_id); - if ($ref_id > 0) - { - $item["obj_link"] = ilLink::_getStaticLink($ref_id); - } + case "sqst": + $item["obj_type_txt"] = $this->lng->txt("cont_sqst"); + include_once("./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"); + $obj_id = SurveyQuestion::lookupObjFi($usage["id"]); + $item["obj_title"] = ilObject::_lookupTitle($obj_id); + $item["sub_txt"] = $this->lng->txt("question"); + $item["sub_title"] = SurveyQuestion::_getTitle($usage["id"]); + $ref_id = $this->getFirstWritableRefId($obj_id); + if ($ref_id > 0) { + $item["obj_link"] = ilLink::_getStaticLink($ref_id); + } - break; + break; - case "termref": - $item["obj_type_txt"] = $this->lng->txt("obj_glo"); - $item["obj_title"] = ilObject::_lookupTitle($usage["id"]); - $item["sub_txt"] = $this->lng->txt("glo_referenced_term"); - $ref_id = $this->getFirstWritableRefId($usage["id"]); - if ($ref_id > 0) - { - $item["obj_link"] = ilLink::_getStaticLink($ref_id); - } - break; + case "termref": + $item["obj_type_txt"] = $this->lng->txt("obj_glo"); + $item["obj_title"] = ilObject::_lookupTitle($usage["id"]); + $item["sub_txt"] = $this->lng->txt("glo_referenced_term"); + $ref_id = $this->getFirstWritableRefId($usage["id"]); + if ($ref_id > 0) { + $item["obj_link"] = ilLink::_getStaticLink($ref_id); + } + break; - default: - $item["obj_title"] = "Type ".$usage["type"].", ".$usage["id"]; - break; - } - - // show versions - if (is_array($usage["hist_nr"]) && - (count($usage["hist_nr"]) > 1 || $usage["hist_nr"][0] > 0)) - { - asort($usage["hist_nr"]); - $ver = $sep = ""; - if ($usage["hist_nr"][0] == 0) - { - array_shift($usage["hist_nr"]); - $usage["hist_nr"][] = 0; - } - foreach ($usage["hist_nr"] as $nr) - { - if ($nr > 0) - { - $ver.= $sep.$nr; - } - else - { - $ver.= $sep.$this->lng->txt("cont_current_version"); - } - $sep = ", "; - } + default: + $item["obj_title"] = "Type " . $usage["type"] . ", " . $usage["id"]; + break; + } + + // show versions + if (is_array($usage["hist_nr"]) && + (count($usage["hist_nr"]) > 1 || $usage["hist_nr"][0] > 0)) { + asort($usage["hist_nr"]); + $ver = $sep = ""; + if ($usage["hist_nr"][0] == 0) { + array_shift($usage["hist_nr"]); + $usage["hist_nr"][] = 0; + } + foreach ($usage["hist_nr"] as $nr) { + if ($nr > 0) { + $ver.= $sep . $nr; + } else { + $ver.= $sep . $this->lng->txt("cont_current_version"); + } + $sep = ", "; + } - $this->tpl->setCurrentBlock("versions"); - $this->tpl->setVariable("TXT_VERSIONS", $this->lng->txt("cont_versions")); - $this->tpl->setVariable("VAL_VERSIONS", $ver); - $this->tpl->parseCurrentBlock(); - } + $this->tpl->setCurrentBlock("versions"); + $this->tpl->setVariable("TXT_VERSIONS", $this->lng->txt("cont_versions")); + $this->tpl->setVariable("VAL_VERSIONS", $ver); + $this->tpl->parseCurrentBlock(); + } - if ($item["obj_type_txt"] != "") - { - $this->tpl->setCurrentBlock("type"); - $this->tpl->setVariable("TXT_TYPE", $this->lng->txt("type")); - $this->tpl->setVariable("VAL_TYPE", $item["obj_type_txt"]); - $this->tpl->parseCurrentBlock(); - } + if ($item["obj_type_txt"] != "") { + $this->tpl->setCurrentBlock("type"); + $this->tpl->setVariable("TXT_TYPE", $this->lng->txt("type")); + $this->tpl->setVariable("VAL_TYPE", $item["obj_type_txt"]); + $this->tpl->parseCurrentBlock(); + } - if ($usage["type"] != "clip") - { - if ($item["obj_link"]) - { - $this->tpl->setCurrentBlock("linked_item"); - $this->tpl->setVariable("TXT_OBJECT", $item["obj_title"]); - $this->tpl->setVariable("HREF_LINK", $item["obj_link"]); - $this->tpl->parseCurrentBlock(); - } - else - { - $this->tpl->setVariable("TXT_OBJECT_NO_LINK", $item["obj_title"]); - } - - if ($item["sub_txt"] != "") - { - $this->tpl->setVariable("SEP", ", "); - $this->tpl->setVariable("SUB_TXT", $item["sub_txt"]); - if ($item["sub_title"] != "") - { - $this->tpl->setVariable("SEP2", ": "); - $this->tpl->setVariable("SUB_TITLE", $item["sub_title"]); - } - } - - } - else - { - $this->tpl->setVariable("TXT_OBJECT_NO_LINK", $this->lng->txt("cont_users_have_mob_in_clip1"). - " ".$usage["cnt"]." ".$this->lng->txt("cont_users_have_mob_in_clip2")); + if ($usage["type"] != "clip") { + if ($item["obj_link"]) { + $this->tpl->setCurrentBlock("linked_item"); + $this->tpl->setVariable("TXT_OBJECT", $item["obj_title"]); + $this->tpl->setVariable("HREF_LINK", $item["obj_link"]); + $this->tpl->parseCurrentBlock(); + } else { + $this->tpl->setVariable("TXT_OBJECT_NO_LINK", $item["obj_title"]); + } + + if ($item["sub_txt"] != "") { + $this->tpl->setVariable("SEP", ", "); + $this->tpl->setVariable("SUB_TXT", $item["sub_txt"]); + if ($item["sub_title"] != "") { + $this->tpl->setVariable("SEP2", ": "); + $this->tpl->setVariable("SUB_TITLE", $item["sub_title"]); + } + } + } else { + $this->tpl->setVariable("TXT_OBJECT_NO_LINK", $this->lng->txt("cont_users_have_mob_in_clip1") . + " " . $usage["cnt"] . " " . $this->lng->txt("cont_users_have_mob_in_clip2")); + } + } - } - } - - function getFirstWritableRefId($a_obj_id) - { - $ilAccess = $this->access; - - $ref_ids = ilObject::_getAllReferences($a_obj_id); - foreach ($ref_ids as $ref_id) - { - if ($ilAccess->checkAccess("write", "", $ref_id)) - { - return $ref_id; - } - } - return 0; - } + public function getFirstWritableRefId($a_obj_id) + { + $ilAccess = $this->access; + + $ref_ids = ilObject::_getAllReferences($a_obj_id); + foreach ($ref_ids as $ref_id) { + if ($ilAccess->checkAccess("write", "", $ref_id)) { + return $ref_id; + } + } + return 0; + } } -?> diff --git a/Modules/Glossary/exceptions/class.ilGlossaryException.php b/Modules/Glossary/exceptions/class.ilGlossaryException.php index 1620cb53a82c1ddde0fe4853666b0706e2d6cadc..fced76cbe3e369c449cfdf1dd388a4f52867ea65 100644 --- a/Modules/Glossary/exceptions/class.ilGlossaryException.php +++ b/Modules/Glossary/exceptions/class.ilGlossaryException.php @@ -13,4 +13,3 @@ require_once 'Services/Exceptions/classes/class.ilException.php'; class ilGlossaryException extends ilException { } -?> diff --git a/Modules/Glossary/exceptions/class.ilGlossaryOldImportException.php b/Modules/Glossary/exceptions/class.ilGlossaryOldImportException.php index d237ad2b1c31210a349b80c678935d93b31532c7..1d20c146c29c8bda5e79e0edf61aa7fa2df67cda 100644 --- a/Modules/Glossary/exceptions/class.ilGlossaryOldImportException.php +++ b/Modules/Glossary/exceptions/class.ilGlossaryOldImportException.php @@ -13,4 +13,3 @@ require_once 'Services/Exceptions/classes/class.ilException.php'; class ilGlossaryOldImportException extends ilException { } -?> diff --git a/Modules/HTMLLearningModule/classes/class.ilHTLMEditorGUI.php b/Modules/HTMLLearningModule/classes/class.ilHTLMEditorGUI.php index 348e4249bd634e2f3a58184113e42239c919a79a..7d737825fffffac0fba51f27aa3c2db2c81be766 100755 --- a/Modules/HTMLLearningModule/classes/class.ilHTLMEditorGUI.php +++ b/Modules/HTMLLearningModule/classes/class.ilHTLMEditorGUI.php @@ -1,24 +1,24 @@ rbacsystem = $DIC->rbac()->system(); - $this->error = $DIC["ilErr"]; - $this->access = $DIC->access(); - $this->nav_history = $DIC["ilNavigationHistory"]; - $tpl = $DIC["tpl"]; - $lng = $DIC->language(); - $objDefinition = $DIC["objDefinition"]; - $ilCtrl = $DIC->ctrl(); - $rbacsystem = $DIC->rbac()->system(); - $ilErr = $DIC["ilErr"]; - - $lng->loadLanguageModule("content"); - - // check write permission - if (!$rbacsystem->checkAccess("write", $_GET["ref_id"])) - { - $ilErr->raiseError($lng->txt("permission_denied"), $ilErr->MESSAGE); - } - - $this->ctrl = $ilCtrl; - - //$this->ctrl->saveParameter($this, array("ref_id", "obj_id")); - $this->ctrl->saveParameter($this, array("ref_id")); - - // initiate variables - $this->tpl = $tpl; - $this->lng = $lng; - $this->objDefinition = $objDefinition; - $this->ref_id = $_GET["ref_id"]; - - } - - /** - * execute command - */ - function executeCommand() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - $ilNavigationHistory = $this->nav_history; - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(""); - - // add entry to navigation history - if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - $ilCtrl->setParameterByClass("ilobjfilebasedlmgui", "ref_id", $_GET["ref_id"]); - $ilNavigationHistory->addItem($_GET["ref_id"], - $ilCtrl->getLinkTargetByClass(array("ilrepositorygui", "ilobjfilebasedlmgui"), "infoScreen"), "htlm"); - } - - switch($next_class) - { - case "ilobjfilebasedlmgui": - require_once ("./Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMGUI.php"); - $fblm_gui = new ilObjFileBasedLMGUI("", $_GET["ref_id"],true, false); - $ilCtrl->forwardCommand($fblm_gui); - $tpl->show(); - break; - - default: - $this->ctrl->setCmdClass("ilobjfilebasedlmgui"); - $this->ctrl->setCmd(""); - return $this->executeCommand(); - break; - } - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilNavigationHistory + */ + protected $nav_history; + + public $tpl; + public $lng; + public $objDefinition; + public $ref_id; + + /** + * Constructor + * @access public + */ + public function __construct() + { + global $DIC; + + $this->rbacsystem = $DIC->rbac()->system(); + $this->error = $DIC["ilErr"]; + $this->access = $DIC->access(); + $this->nav_history = $DIC["ilNavigationHistory"]; + $tpl = $DIC["tpl"]; + $lng = $DIC->language(); + $objDefinition = $DIC["objDefinition"]; + $ilCtrl = $DIC->ctrl(); + $rbacsystem = $DIC->rbac()->system(); + $ilErr = $DIC["ilErr"]; + + $lng->loadLanguageModule("content"); + + // check write permission + if (!$rbacsystem->checkAccess("write", $_GET["ref_id"])) { + $ilErr->raiseError($lng->txt("permission_denied"), $ilErr->MESSAGE); + } + + $this->ctrl = $ilCtrl; + + //$this->ctrl->saveParameter($this, array("ref_id", "obj_id")); + $this->ctrl->saveParameter($this, array("ref_id")); + + // initiate variables + $this->tpl = $tpl; + $this->lng = $lng; + $this->objDefinition = $objDefinition; + $this->ref_id = $_GET["ref_id"]; + } + + /** + * execute command + */ + public function executeCommand() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + $ilNavigationHistory = $this->nav_history; + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(""); + + // add entry to navigation history + if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) { + $ilCtrl->setParameterByClass("ilobjfilebasedlmgui", "ref_id", $_GET["ref_id"]); + $ilNavigationHistory->addItem( + $_GET["ref_id"], + $ilCtrl->getLinkTargetByClass(array("ilrepositorygui", "ilobjfilebasedlmgui"), "infoScreen"), + "htlm" + ); + } + + switch ($next_class) { + case "ilobjfilebasedlmgui": + require_once("./Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMGUI.php"); + $fblm_gui = new ilObjFileBasedLMGUI("", $_GET["ref_id"], true, false); + $ilCtrl->forwardCommand($fblm_gui); + $tpl->show(); + break; + + default: + $this->ctrl->setCmdClass("ilobjfilebasedlmgui"); + $this->ctrl->setCmd(""); + return $this->executeCommand(); + break; + } + } } -?> diff --git a/Modules/HTMLLearningModule/classes/class.ilHTLMPresentationGUI.php b/Modules/HTMLLearningModule/classes/class.ilHTLMPresentationGUI.php index 4992d664af0bb50447b1dac9846c26789f8ee944..deeea494c73e9ccab485a598dd998e42304027e9 100755 --- a/Modules/HTMLLearningModule/classes/class.ilHTLMPresentationGUI.php +++ b/Modules/HTMLLearningModule/classes/class.ilHTLMPresentationGUI.php @@ -1,24 +1,24 @@ access = $DIC->access(); - $this->error = $DIC["ilErr"]; - $this->nav_history = $DIC["ilNavigationHistory"]; - $tpl = $DIC["tpl"]; - $lng = $DIC->language(); - $objDefinition = $DIC["objDefinition"]; - $ilCtrl = $DIC->ctrl(); - $ilAccess = $DIC->access(); - $ilErr = $DIC["ilErr"]; - - $lng->loadLanguageModule("content"); - - // check write permission - if (!$ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - $ilErr->raiseError($lng->txt("permission_denied"), $ilErr->MESSAGE); - } - - - $this->ctrl = $ilCtrl; - - //$this->ctrl->saveParameter($this, array("ref_id", "obj_id")); - $this->ctrl->saveParameter($this, array("ref_id")); - - // initiate variables - $this->tpl = $tpl; - $this->lng = $lng; - $this->objDefinition = $objDefinition; - $this->ref_id = $_GET["ref_id"]; - - } - - /** - * execute command - */ - function executeCommand() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - $ilNavigationHistory = $this->nav_history; - - // add entry to navigation history - if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - $ilCtrl->setParameterByClass("ilobjfilebasedlmgui", "ref_id", $_GET["ref_id"]); - $ilNavigationHistory->addItem($_GET["ref_id"], - $ilCtrl->getLinkTargetByClass(array("ilrepositorygui", "ilobjfilebasedlmgui"), "infoScreen"), "htlm"); - - } - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(""); - - switch($next_class) - { - case "ilobjfilebasedlmgui": - require_once ("./Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMGUI.php"); - $fblm_gui = new ilObjFileBasedLMGUI("", $_GET["ref_id"],true, false); - $ilCtrl->forwardCommand($fblm_gui); - $tpl->show(); - break; - - default: - $this->ctrl->setCmdClass("ilobjfilebasedlmgui"); - $this->ctrl->setCmd("showLearningModule"); - return $this->executeCommand(); - break; - } - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilNavigationHistory + */ + protected $nav_history; + + public $tpl; + public $lng; + public $objDefinition; + public $ref_id; + + /** + * Constructor + * @access public + */ + public function __construct() + { + global $DIC; + + $this->access = $DIC->access(); + $this->error = $DIC["ilErr"]; + $this->nav_history = $DIC["ilNavigationHistory"]; + $tpl = $DIC["tpl"]; + $lng = $DIC->language(); + $objDefinition = $DIC["objDefinition"]; + $ilCtrl = $DIC->ctrl(); + $ilAccess = $DIC->access(); + $ilErr = $DIC["ilErr"]; + + $lng->loadLanguageModule("content"); + + // check write permission + if (!$ilAccess->checkAccess("read", "", $_GET["ref_id"])) { + $ilErr->raiseError($lng->txt("permission_denied"), $ilErr->MESSAGE); + } + + + $this->ctrl = $ilCtrl; + + //$this->ctrl->saveParameter($this, array("ref_id", "obj_id")); + $this->ctrl->saveParameter($this, array("ref_id")); + + // initiate variables + $this->tpl = $tpl; + $this->lng = $lng; + $this->objDefinition = $objDefinition; + $this->ref_id = $_GET["ref_id"]; + } + + /** + * execute command + */ + public function executeCommand() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + $ilNavigationHistory = $this->nav_history; + + // add entry to navigation history + if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) { + $ilCtrl->setParameterByClass("ilobjfilebasedlmgui", "ref_id", $_GET["ref_id"]); + $ilNavigationHistory->addItem( + $_GET["ref_id"], + $ilCtrl->getLinkTargetByClass(array("ilrepositorygui", "ilobjfilebasedlmgui"), "infoScreen"), + "htlm" + ); + } + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(""); + + switch ($next_class) { + case "ilobjfilebasedlmgui": + require_once("./Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMGUI.php"); + $fblm_gui = new ilObjFileBasedLMGUI("", $_GET["ref_id"], true, false); + $ilCtrl->forwardCommand($fblm_gui); + $tpl->show(); + break; + + default: + $this->ctrl->setCmdClass("ilobjfilebasedlmgui"); + $this->ctrl->setCmd("showLearningModule"); + return $this->executeCommand(); + break; + } + } } -?> diff --git a/Modules/HTMLLearningModule/classes/class.ilHTMLLearningModuleDataSet.php b/Modules/HTMLLearningModule/classes/class.ilHTMLLearningModuleDataSet.php index 2e720e3133ae4136b7edeb33937e677a6d811ecb..295e498095caefa147e5b988a8cd8f0c22ac62eb 100644 --- a/Modules/HTMLLearningModule/classes/class.ilHTMLLearningModuleDataSet.php +++ b/Modules/HTMLLearningModule/classes/class.ilHTMLLearningModuleDataSet.php @@ -5,161 +5,152 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); /** * HTML learning module data set class - * + * * @author Alex Killing * @version $Id$ * @ingroup ingroup ModulesHTMLLearningModule */ class ilHTMLLearningModuleDataSet extends ilDataSet { - /** - * Get supported versions - * - * @param - * @return - */ - public function getSupportedVersions() - { - return array("4.1.0"); - } - - /** - * Get xml namespace - * - * @param - * @return - */ - function getXmlNamespace($a_entity, $a_schema_version) - { - return "http://www.ilias.de/xml/Modules/HTMLLearningModule/".$a_entity; - } - - /** - * Get field types for entity - * - * @param - * @return - */ - protected function getTypes($a_entity, $a_version) - { - if ($a_entity == "htlm") - { - switch ($a_version) - { - case "4.1.0": - return array( - "Id" => "integer", - "Title" => "text", - "Description" => "text", - "StartFile" => "text", - "Dir" => "directory"); - } - } + /** + * Get supported versions + * + * @param + * @return + */ + public function getSupportedVersions() + { + return array("4.1.0"); + } + + /** + * Get xml namespace + * + * @param + * @return + */ + public function getXmlNamespace($a_entity, $a_schema_version) + { + return "http://www.ilias.de/xml/Modules/HTMLLearningModule/" . $a_entity; + } + + /** + * Get field types for entity + * + * @param + * @return + */ + protected function getTypes($a_entity, $a_version) + { + if ($a_entity == "htlm") { + switch ($a_version) { + case "4.1.0": + return array( + "Id" => "integer", + "Title" => "text", + "Description" => "text", + "StartFile" => "text", + "Dir" => "directory"); + } + } + } - } + /** + * Read data + * + * @param + * @return + */ + public function readData($a_entity, $a_version, $a_ids, $a_field = "") + { + $ilDB = $this->db; - /** - * Read data - * - * @param - * @return - */ - 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 == "htlm") { + switch ($a_version) { + case "4.1.0": + $this->getDirectDataFromQuery("SELECT id, title, description, " . + " startfile start_file " . + " FROM file_based_lm JOIN object_data ON (file_based_lm.id = object_data.obj_id) " . + "WHERE " . + $ilDB->in("id", $a_ids, false, "integer")); + break; + } + } + } + + /** + * Determine the dependent sets of data + */ + protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) + { + return false; + } + - if (!is_array($a_ids)) - { - $a_ids = array($a_ids); - } - - if ($a_entity == "htlm") - { - switch ($a_version) - { - case "4.1.0": - $this->getDirectDataFromQuery("SELECT id, title, description, ". - " startfile start_file ". - " FROM file_based_lm JOIN object_data ON (file_based_lm.id = object_data.obj_id) ". - "WHERE ". - $ilDB->in("id", $a_ids, false, "integer")); - break; - } - } + /** + * Get xml record + * + * @param + * @return + */ + public function getXmlRecord($a_entity, $a_version, $a_set) + { + include_once("./Modules/HTMLLearningModule/classes/class.ilObjFileBasedLM.php"); + $lm = new ilObjFileBasedLM($a_set["Id"], false); + $dir = $lm->getDataDirectory(); + $a_set["Dir"] = $dir; - } - - /** - * Determine the dependent sets of data - */ - protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) - { - return false; - } - + return $a_set; + } - /** - * Get xml record - * - * @param - * @return - */ - function getXmlRecord($a_entity, $a_version, $a_set) - { - include_once("./Modules/HTMLLearningModule/classes/class.ilObjFileBasedLM.php"); - $lm = new ilObjFileBasedLM($a_set["Id"], false); - $dir = $lm->getDataDirectory(); - $a_set["Dir"] = $dir; + /** + * Import record + * + * @param + * @return + */ + public function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) + { + //echo $a_entity; + //var_dump($a_rec); - return $a_set; - } + switch ($a_entity) { + case "htlm": + + include_once("./Modules/HTMLLearningModule/classes/class.ilObjFileBasedLM.php"); + if ($new_id = $a_mapping->getMapping('Services/Container', 'objs', $a_rec['Id'])) { + $newObj = ilObjectFactory::getInstanceByObjId($new_id, false); + } else { + $newObj = new ilObjFileBasedLM(); + $newObj->setType("htlm"); + $newObj->create(true); + } - /** - * Import record - * - * @param - * @return - */ - function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) - { -//echo $a_entity; -//var_dump($a_rec); + $newObj->setTitle($a_rec["Title"]); + $newObj->setDescription($a_rec["Description"]); + $newObj->setStartFile($a_rec["StartFile"], true); + $newObj->update(true); + $this->current_obj = $newObj; - switch ($a_entity) - { - case "htlm": - - include_once("./Modules/HTMLLearningModule/classes/class.ilObjFileBasedLM.php"); - if($new_id = $a_mapping->getMapping('Services/Container','objs',$a_rec['Id'])) - { - $newObj = ilObjectFactory::getInstanceByObjId($new_id,false); - } - else - { - $newObj = new ilObjFileBasedLM(); - $newObj->setType("htlm"); - $newObj->create(true); - } + $dir = str_replace("..", "", $a_rec["Dir"]); + if ($dir != "" && $this->getImportDirectory() != "") { + $source_dir = $this->getImportDirectory() . "/" . $dir; + $target_dir = $newObj->getDataDirectory(); + ilUtil::rCopy($source_dir, $target_dir); + } - $newObj->setTitle($a_rec["Title"]); - $newObj->setDescription($a_rec["Description"]); - $newObj->setStartFile($a_rec["StartFile"], true); - $newObj->update(true); - $this->current_obj = $newObj; - - $dir = str_replace("..", "", $a_rec["Dir"]); - if ($dir != "" && $this->getImportDirectory() != "") - { - $source_dir = $this->getImportDirectory()."/".$dir; - $target_dir = $newObj->getDataDirectory(); - ilUtil::rCopy($source_dir, $target_dir); - } - - $a_mapping->addMapping("Modules/HTMLLearningModule", "htlm", $a_rec["Id"], $newObj->getId()); - $a_mapping->addMapping("Services/MetaData", "md", - $a_rec["Id"].":0:htlm", $newObj->getId().":0:htlm"); - break; - } - } + $a_mapping->addMapping("Modules/HTMLLearningModule", "htlm", $a_rec["Id"], $newObj->getId()); + $a_mapping->addMapping( + "Services/MetaData", + "md", + $a_rec["Id"] . ":0:htlm", + $newObj->getId() . ":0:htlm" + ); + break; + } + } } -?> \ No newline at end of file diff --git a/Modules/HTMLLearningModule/classes/class.ilHTMLLearningModuleExporter.php b/Modules/HTMLLearningModule/classes/class.ilHTMLLearningModuleExporter.php index 5577754f6561188919a91ac2cb0b50122dd5c674..c9e0d4d140479227ce958f828acdcea8d1da0cd9 100644 --- a/Modules/HTMLLearningModule/classes/class.ilHTMLLearningModuleExporter.php +++ b/Modules/HTMLLearningModule/classes/class.ilHTMLLearningModuleExporter.php @@ -12,18 +12,18 @@ include_once("./Services/Export/classes/class.ilXmlExporter.php"); */ class ilHTMLLearningModuleExporter extends ilXmlExporter { - private $ds; + private $ds; - /** - * Initialisation - */ - function init() - { - include_once("./Modules/HTMLLearningModule/classes/class.ilHTMLLearningModuleDataSet.php"); - $this->ds = new ilHTMLLearningModuleDataSet(); - $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); - $this->ds->setDSPrefix("ds"); - } + /** + * Initialisation + */ + public function init() + { + include_once("./Modules/HTMLLearningModule/classes/class.ilHTMLLearningModuleDataSet.php"); + $this->ds = new ilHTMLLearningModuleDataSet(); + $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); + $this->ds->setDSPrefix("ds"); + } /** @@ -34,12 +34,12 @@ class ilHTMLLearningModuleExporter extends ilXmlExporter * @param array ids * @return array array of array with keys "component", entity", "ids" */ - function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) + public function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) { $deps = []; $md_ids = []; foreach ($a_ids as $id) { - $md_ids[] = $id.":0:htlm"; + $md_ids[] = $id . ":0:htlm"; } $deps[] = [ @@ -58,39 +58,36 @@ class ilHTMLLearningModuleExporter extends ilXmlExporter return $deps; } - /** - * Get xml representation - * - * @param string entity - * @param string target release - * @param string id - * @return string xml string - */ - 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); - } - - /** - * Returns schema versions that the component can export to. - * ILIAS chooses the first one, that has min/max constraints which - * fit to the target release. Please put the newest on top. - * - * @return - */ - function getValidSchemaVersions($a_entity) - { - return array ( - "4.1.0" => array( - "namespace" => "http://www.ilias.de/Modules/HTMLLearningModule/htlm/4_1", - "xsd_file" => "ilias_htlm_4_1.xsd", - "uses_dataset" => true, - "min" => "4.1.0", - "max" => "") - ); - } + /** + * Get xml representation + * + * @param string entity + * @param string target release + * @param string id + * @return string xml string + */ + 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); + } + /** + * Returns schema versions that the component can export to. + * ILIAS chooses the first one, that has min/max constraints which + * fit to the target release. Please put the newest on top. + * + * @return + */ + public function getValidSchemaVersions($a_entity) + { + return array( + "4.1.0" => array( + "namespace" => "http://www.ilias.de/Modules/HTMLLearningModule/htlm/4_1", + "xsd_file" => "ilias_htlm_4_1.xsd", + "uses_dataset" => true, + "min" => "4.1.0", + "max" => "") + ); + } } - -?> \ No newline at end of file diff --git a/Modules/HTMLLearningModule/classes/class.ilHTMLLearningModuleImporter.php b/Modules/HTMLLearningModule/classes/class.ilHTMLLearningModuleImporter.php index b92fb69974b524645e7f6adb973bb60c55a27f76..1142823b2267883cfe8406c570ede489428f2d7d 100644 --- a/Modules/HTMLLearningModule/classes/class.ilHTMLLearningModuleImporter.php +++ b/Modules/HTMLLearningModule/classes/class.ilHTMLLearningModuleImporter.php @@ -13,30 +13,33 @@ include_once("./Services/Export/classes/class.ilXmlImporter.php"); class ilHTMLLearningModuleImporter extends ilXmlImporter { - /** - * Initialisation - */ - function init() - { - include_once("./Modules/HTMLLearningModule/classes/class.ilHTMLLearningModuleDataSet.php"); - $this->ds = new ilHTMLLearningModuleDataSet(); - $this->ds->setDSPrefix("ds"); - $this->ds->setImportDirectory($this->getImportDirectory()); - } + /** + * Initialisation + */ + public function init() + { + include_once("./Modules/HTMLLearningModule/classes/class.ilHTMLLearningModuleDataSet.php"); + $this->ds = new ilHTMLLearningModuleDataSet(); + $this->ds->setDSPrefix("ds"); + $this->ds->setImportDirectory($this->getImportDirectory()); + } - /** - * Import XML - * - * @param - * @return - */ - function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) - { - include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); - $parser = new ilDataSetImportParser($a_entity, $this->getSchemaVersion(), - $a_xml, $this->ds, $a_mapping); - } + /** + * Import XML + * + * @param + * @return + */ + public function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) + { + include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); + $parser = new ilDataSetImportParser( + $a_entity, + $this->getSchemaVersion(), + $a_xml, + $this->ds, + $a_mapping + ); + } } - -?> \ No newline at end of file diff --git a/Modules/HTMLLearningModule/classes/class.ilHTMLLearningModuleLP.php b/Modules/HTMLLearningModule/classes/class.ilHTMLLearningModuleLP.php index 591c2184074c554542cbc27e9fbd248d907d5029..3a914c646e9c47919166251f9788219c2f8a7ca9 100644 --- a/Modules/HTMLLearningModule/classes/class.ilHTMLLearningModuleLP.php +++ b/Modules/HTMLLearningModule/classes/class.ilHTMLLearningModuleLP.php @@ -1,47 +1,42 @@ - - * @version $Id: class.ilLPStatusPlugin.php 43734 2013-07-29 15:27:58Z jluetzen $ - * @package ModulesHTMLLearningModule - */ -class ilHTMLLearningModuleLP extends ilObjectLP -{ - public static function getDefaultModes($a_lp_active) - { - if(!$a_lp_active) - { - return array( - ilLPObjSettings::LP_MODE_DEACTIVATED - ); - } - else - { - return array( - ilLPObjSettings::LP_MODE_DEACTIVATED, - ilLPObjSettings::LP_MODE_MANUAL - ); - } - } - - public function getDefaultMode() - { - return ilLPObjSettings::LP_MODE_MANUAL; - } - - public function getValidModes() - { - return array( - ilLPObjSettings::LP_MODE_DEACTIVATED, - ilLPObjSettings::LP_MODE_MANUAL - ); - } -} - -?> \ No newline at end of file + + * @version $Id: class.ilLPStatusPlugin.php 43734 2013-07-29 15:27:58Z jluetzen $ + * @package ModulesHTMLLearningModule + */ +class ilHTMLLearningModuleLP extends ilObjectLP +{ + public static function getDefaultModes($a_lp_active) + { + if (!$a_lp_active) { + return array( + ilLPObjSettings::LP_MODE_DEACTIVATED + ); + } else { + return array( + ilLPObjSettings::LP_MODE_DEACTIVATED, + ilLPObjSettings::LP_MODE_MANUAL + ); + } + } + + public function getDefaultMode() + { + return ilLPObjSettings::LP_MODE_MANUAL; + } + + public function getValidModes() + { + return array( + ilLPObjSettings::LP_MODE_DEACTIVATED, + ilLPObjSettings::LP_MODE_MANUAL + ); + } +} diff --git a/Modules/HTMLLearningModule/classes/class.ilObjFileBasedLM.php b/Modules/HTMLLearningModule/classes/class.ilObjFileBasedLM.php index 840ce9dc0171acf1c6a91ca8970c60877d672847..cccc25c14d703eeff5125b4aa695e02238d1e59c 100755 --- a/Modules/HTMLLearningModule/classes/class.ilObjFileBasedLM.php +++ b/Modules/HTMLLearningModule/classes/class.ilObjFileBasedLM.php @@ -19,210 +19,201 @@ require_once "./Services/Object/classes/class.ilObject.php"; */ class ilObjFileBasedLM extends ilObject { - var $tree; - - protected $online; // [bool] - - /** - * Constructor - * @access public - * @param integer reference_id or object_id - * @param boolean treat the id as reference_id (true) or object_id (false) - */ - function __construct($a_id = 0,$a_call_by_reference = true) - { - global $DIC; - - // default is offline - $this->setOfflineStatus(true); - - $this->db = $DIC->database(); - // this also calls read() method! (if $a_id is set) - $this->type = "htlm"; - parent::__construct($a_id,$a_call_by_reference); - - } - - - /** - * update object data - * - * @access public - * @return boolean - */ - function update($a_skip_meta = false) - { - $ilDB = $this->db; - - if (!$a_skip_meta) - { - $this->updateMetaData(); - } - parent::update(); - - $ilDB->manipulate($q = "UPDATE file_based_lm SET ". - " startfile = ".$ilDB->quote($this->getStartFile(), "text")." ". - " WHERE id = ".$ilDB->quote($this->getId(), "integer")); - return true; - } - - /** - * read object - */ - function read() - { - $ilDB = $this->db; - - parent::read(); - - $q = "SELECT * FROM file_based_lm WHERE id = ".$ilDB->quote($this->getId(), "integer"); - $lm_set = $ilDB->query($q); - $lm_rec = $ilDB->fetchAssoc($lm_set); - $this->setStartFile((string) $lm_rec["startfile"]); - } - - - - /** - * create file based lm - */ - function create($a_skip_meta = false) - { - $ilDB = $this->db; - - parent::create(); - $this->createDataDirectory(); - - $ilDB->manipulate("INSERT INTO file_based_lm (id, startfile) VALUES ". - " (".$ilDB->quote($this->getID(), "integer").",". - $ilDB->quote($this->getStartfile(), "text").")"); - if (!$a_skip_meta) - { - $this->createMetaData(); - } - } - - function getDataDirectory($mode = "filesystem") - { - $lm_data_dir = ilUtil::getWebspaceDir($mode)."/lm_data"; - $lm_dir = $lm_data_dir."/lm_".$this->getId(); - - return $lm_dir; - } - - function createDataDirectory() - { - ilUtil::makeDir($this->getDataDirectory()); - } - - function getStartFile() - { - return $this->start_file; - } - - function setStartFile($a_file, $a_omit_file_check = false) - { - if($a_file && - (file_exists($this->getDataDirectory()."/".$a_file) || $a_omit_file_check)) - { - $this->start_file = $a_file; - } - } - - /** - * Gets the disk usage of the object in bytes. + public $tree; + + protected $online; // [bool] + + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + global $DIC; + + // default is offline + $this->setOfflineStatus(true); + + $this->db = $DIC->database(); + // this also calls read() method! (if $a_id is set) + $this->type = "htlm"; + parent::__construct($a_id, $a_call_by_reference); + } + + + /** + * update object data * - * @access public - * @return integer the disk usage in bytes - */ - function getDiskUsage() - { - require_once("./Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMAccess.php"); - return ilObjFileBasedLMAccess::_lookupDiskUsage($this->id); - } - - - - /** - * delete object and all related data - * - * this method has been tested on may 9th 2004 - * data directory, meta data, file based lm data - * have been deleted correctly as desired - * - * @access public - * @return boolean true if all object data were removed; false if only a references were removed - */ - function delete() - { - $ilDB = $this->db; - - // always call parent delete function first!! - if (!parent::delete()) - { - return false; - } - - // Delete meta data - $this->deleteMetaData(); - - // delete file_based_lm record - $ilDB->manipulate("DELETE FROM file_based_lm WHERE id = ". - $ilDB->quote($this->getID(), "integer")); - - // delete data directory - ilUtil::delDir($this->getDataDirectory()); - - return true; - } - - /** - * Populate by directory. Add a filename to do a special check for - * ILIAS HTML export files. If the corresponding directory is found - * within the passed directory path (i.e. "htlm_") this - * subdirectory is used instead. - * - * @param - * @return - */ - function populateByDirectoy($a_dir, $a_filename = "") - { - preg_match("/.*htlm_([0-9]*)\.zip/", $a_filename, $match); - if (is_dir($a_dir."/htlm_".$match[1])) - { - $a_dir = $a_dir."/htlm_".$match[1]; - } - ilUtil::rCopy($a_dir, $this->getDataDirectory()); - ilUtil::renameExecutables($this->getDataDirectory()); - } - - /** - * Clone HTML learning module - * - * @param int target ref_id - * @param int copy id - */ - public function cloneObject($a_target_id,$a_copy_id = 0, $a_omit_tree = false) - { - $new_obj = parent::cloneObject($a_target_id,$a_copy_id, $a_omit_tree); - $this->cloneMetaData($new_obj); - - //copy online status if object is not the root copy object - $cp_options = ilCopyWizardOptions::_getInstance($a_copy_id); - - if(!$cp_options->isRootNode($this->getRefId())) - { - $new_obj->setOfflineStatus($this->getOfflineStatus()); - } - - // copy content - $new_obj->populateByDirectoy($this->getDataDirectory()); - - $new_obj->setStartFile($this->getStartFile()); - $new_obj->update(); - - return $new_obj; - } + * @access public + * @return boolean + */ + public function update($a_skip_meta = false) + { + $ilDB = $this->db; + + if (!$a_skip_meta) { + $this->updateMetaData(); + } + parent::update(); + + $ilDB->manipulate($q = "UPDATE file_based_lm SET " . + " startfile = " . $ilDB->quote($this->getStartFile(), "text") . " " . + " WHERE id = " . $ilDB->quote($this->getId(), "integer")); + return true; + } + + /** + * read object + */ + public function read() + { + $ilDB = $this->db; + + parent::read(); + + $q = "SELECT * FROM file_based_lm WHERE id = " . $ilDB->quote($this->getId(), "integer"); + $lm_set = $ilDB->query($q); + $lm_rec = $ilDB->fetchAssoc($lm_set); + $this->setStartFile((string) $lm_rec["startfile"]); + } + + + + /** + * create file based lm + */ + public function create($a_skip_meta = false) + { + $ilDB = $this->db; + + parent::create(); + $this->createDataDirectory(); + + $ilDB->manipulate("INSERT INTO file_based_lm (id, startfile) VALUES " . + " (" . $ilDB->quote($this->getID(), "integer") . "," . + $ilDB->quote($this->getStartfile(), "text") . ")"); + if (!$a_skip_meta) { + $this->createMetaData(); + } + } + + public function getDataDirectory($mode = "filesystem") + { + $lm_data_dir = ilUtil::getWebspaceDir($mode) . "/lm_data"; + $lm_dir = $lm_data_dir . "/lm_" . $this->getId(); + + return $lm_dir; + } + + public function createDataDirectory() + { + ilUtil::makeDir($this->getDataDirectory()); + } + + public function getStartFile() + { + return $this->start_file; + } + + public function setStartFile($a_file, $a_omit_file_check = false) + { + if ($a_file && + (file_exists($this->getDataDirectory() . "/" . $a_file) || $a_omit_file_check)) { + $this->start_file = $a_file; + } + } + + /** + * Gets the disk usage of the object in bytes. + * + * @access public + * @return integer the disk usage in bytes + */ + public function getDiskUsage() + { + require_once("./Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMAccess.php"); + return ilObjFileBasedLMAccess::_lookupDiskUsage($this->id); + } + + + /** + * delete object and all related data + * + * this method has been tested on may 9th 2004 + * data directory, meta data, file based lm data + * have been deleted correctly as desired + * + * @access public + * @return boolean true if all object data were removed; false if only a references were removed + */ + public function delete() + { + $ilDB = $this->db; + + // always call parent delete function first!! + if (!parent::delete()) { + return false; + } + + // Delete meta data + $this->deleteMetaData(); + + // delete file_based_lm record + $ilDB->manipulate("DELETE FROM file_based_lm WHERE id = " . + $ilDB->quote($this->getID(), "integer")); + + // delete data directory + ilUtil::delDir($this->getDataDirectory()); + + return true; + } + + /** + * Populate by directory. Add a filename to do a special check for + * ILIAS HTML export files. If the corresponding directory is found + * within the passed directory path (i.e. "htlm_") this + * subdirectory is used instead. + * + * @param + * @return + */ + public function populateByDirectoy($a_dir, $a_filename = "") + { + preg_match("/.*htlm_([0-9]*)\.zip/", $a_filename, $match); + if (is_dir($a_dir . "/htlm_" . $match[1])) { + $a_dir = $a_dir . "/htlm_" . $match[1]; + } + ilUtil::rCopy($a_dir, $this->getDataDirectory()); + ilUtil::renameExecutables($this->getDataDirectory()); + } + + /** + * Clone HTML learning module + * + * @param int target ref_id + * @param int copy id + */ + public function cloneObject($a_target_id, $a_copy_id = 0, $a_omit_tree = false) + { + $new_obj = parent::cloneObject($a_target_id, $a_copy_id, $a_omit_tree); + $this->cloneMetaData($new_obj); + + //copy online status if object is not the root copy object + $cp_options = ilCopyWizardOptions::_getInstance($a_copy_id); + + if (!$cp_options->isRootNode($this->getRefId())) { + $new_obj->setOfflineStatus($this->getOfflineStatus()); + } + + // copy content + $new_obj->populateByDirectoy($this->getDataDirectory()); + + $new_obj->setStartFile($this->getStartFile()); + $new_obj->update(); + + return $new_obj; + } } -?> diff --git a/Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMAccess.php b/Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMAccess.php index 9d2d20a538a6f441dc11ee85fa2f22d154dc8dfb..053f8177f47809c9508d691e606959cdcdffe3f0 100644 --- a/Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMAccess.php +++ b/Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMAccess.php @@ -15,208 +15,190 @@ include_once("./Services/Object/classes/class.ilObjectAccess.php"); */ class ilObjFileBasedLMAccess extends ilObjectAccess { - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilAccessHandler - */ - protected $access; - - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->user = $DIC->user(); - $this->lng = $DIC->language(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->access = $DIC->access(); - } - - static $startfile; - - /** - * checks wether a user may invoke a command or not - * (this method is called by ilAccessHandler::checkAccess) - * - * @param string $a_cmd command (not permission!) - * @param string $a_permission permission - * @param int $a_ref_id reference id - * @param int $a_obj_id object id - * @param int $a_user_id user id (if not provided, current user is taken) - * - * @return boolean true, if everything is ok - */ - function _checkAccess($a_cmd, $a_permission, $a_ref_id, $a_obj_id, $a_user_id = "") - { - $ilUser = $this->user; - $lng = $this->lng; - $ilAccess = $this->access; - - if ($a_user_id == "") - { - $a_user_id = $ilUser->getId(); - } - - switch ($a_permission) - { - case "read": - - if (ilObjFileBasedLMAccess::_determineStartUrl($a_obj_id) == "") - { - $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("offline")); - return false; - } - break; - } - return true; - } - - /** - * 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" => "view", "lang_var" => "show", - "default" => true), - array("permission" => "write", "cmd" => "edit", "lang_var" => "edit_content"), - array("permission" => "write", "cmd" => "properties", "lang_var" => "settings") - ); - - return $commands; - } - - // - // access relevant methods - // - - /** - * determine start url - */ - static function _determineStartUrl($a_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - if (isset(self::$startfile[$a_id])) - { - $start_file = self::$startfile[$a_id]; - } - else - { - $q = "SELECT startfile FROM file_based_lm WHERE id = ".$ilDB->quote($a_id, "integer"); - $set = $ilDB->query($q); - $rec = $ilDB->fetchAssoc($set); - $start_file = $rec["startfile"]; - self::$startfile[$a_id] = $start_file.""; - } - - $dir = ilUtil::getWebspaceDir()."/lm_data/lm_".$a_id; - - if (($start_file != "") && - (@is_file($dir."/".$start_file))) - { - return "./".$dir."/".$start_file; - } - else if (@is_file($dir."/index.html")) - { - return "./".$dir."/index.html"; - } - else if (@is_file($dir."/index.htm")) - { - return "./".$dir."/index.htm"; - } - - return ""; - } - - /** - * check whether goto script will succeed - */ - static function _checkGoto($a_target) - { - global $DIC; - - $ilAccess = $DIC->access(); - - $t_arr = explode("_", $a_target); - - if ($t_arr[0] != "htlm" || ((int) $t_arr[1]) <= 0) - { - return false; - } - - if ($ilAccess->checkAccess("visible", "", $t_arr[1]) || - $ilAccess->checkAccess("read", "", $t_arr[1])) - { - return true; - } - return false; - } - - /** - * Returns the number of bytes used on the harddisk by the learning module - * with the specified object id. - * @param int object id of a file object. - */ - static function _lookupDiskUsage($a_id) - { - $lm_data_dir = ilUtil::getWebspaceDir('filesystem')."/lm_data"; - $lm_dir = $lm_data_dir.DIRECTORY_SEPARATOR."lm_".$a_id; - - return file_exists($lm_dir) ? ilUtil::dirsize($lm_dir) : 0; - } - - - /** - * Preload data - * - * @param array $a_obj_ids array of object ids - */ - static function _preloadData($a_obj_ids, $a_ref_ids) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "SELECT id, startfile FROM file_based_lm WHERE ". - $ilDB->in("id", $a_obj_ids, false, "integer"); - - $lm_set = $ilDB->query($q); - while ($rec = $ilDB->fetchAssoc($lm_set)) - { - self::$startfile[$rec["id"]] = $rec["startfile"].""; - } - } - + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilAccessHandler + */ + protected $access; + + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->user = $DIC->user(); + $this->lng = $DIC->language(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->access = $DIC->access(); + } + + public static $startfile; + + /** + * checks wether a user may invoke a command or not + * (this method is called by ilAccessHandler::checkAccess) + * + * @param string $a_cmd command (not permission!) + * @param string $a_permission permission + * @param int $a_ref_id reference id + * @param int $a_obj_id object id + * @param int $a_user_id user id (if not provided, current user is taken) + * + * @return boolean true, if everything is ok + */ + public function _checkAccess($a_cmd, $a_permission, $a_ref_id, $a_obj_id, $a_user_id = "") + { + $ilUser = $this->user; + $lng = $this->lng; + $ilAccess = $this->access; + + if ($a_user_id == "") { + $a_user_id = $ilUser->getId(); + } + + switch ($a_permission) { + case "read": + + if (ilObjFileBasedLMAccess::_determineStartUrl($a_obj_id) == "") { + $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("offline")); + return false; + } + break; + } + return true; + } + + /** + * 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" => "view", "lang_var" => "show", + "default" => true), + array("permission" => "write", "cmd" => "edit", "lang_var" => "edit_content"), + array("permission" => "write", "cmd" => "properties", "lang_var" => "settings") + ); + + return $commands; + } + + // + // access relevant methods + // + + /** + * determine start url + */ + public static function _determineStartUrl($a_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + if (isset(self::$startfile[$a_id])) { + $start_file = self::$startfile[$a_id]; + } else { + $q = "SELECT startfile FROM file_based_lm WHERE id = " . $ilDB->quote($a_id, "integer"); + $set = $ilDB->query($q); + $rec = $ilDB->fetchAssoc($set); + $start_file = $rec["startfile"]; + self::$startfile[$a_id] = $start_file . ""; + } + + $dir = ilUtil::getWebspaceDir() . "/lm_data/lm_" . $a_id; + + if (($start_file != "") && + (@is_file($dir . "/" . $start_file))) { + return "./" . $dir . "/" . $start_file; + } elseif (@is_file($dir . "/index.html")) { + return "./" . $dir . "/index.html"; + } elseif (@is_file($dir . "/index.htm")) { + return "./" . $dir . "/index.htm"; + } + + return ""; + } + + /** + * check whether goto script will succeed + */ + public static function _checkGoto($a_target) + { + global $DIC; + + $ilAccess = $DIC->access(); + + $t_arr = explode("_", $a_target); + + if ($t_arr[0] != "htlm" || ((int) $t_arr[1]) <= 0) { + return false; + } + + if ($ilAccess->checkAccess("visible", "", $t_arr[1]) || + $ilAccess->checkAccess("read", "", $t_arr[1])) { + return true; + } + return false; + } + + /** + * Returns the number of bytes used on the harddisk by the learning module + * with the specified object id. + * @param int object id of a file object. + */ + public static function _lookupDiskUsage($a_id) + { + $lm_data_dir = ilUtil::getWebspaceDir('filesystem') . "/lm_data"; + $lm_dir = $lm_data_dir . DIRECTORY_SEPARATOR . "lm_" . $a_id; + + return file_exists($lm_dir) ? ilUtil::dirsize($lm_dir) : 0; + } + + + /** + * Preload data + * + * @param array $a_obj_ids array of object ids + */ + public static function _preloadData($a_obj_ids, $a_ref_ids) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "SELECT id, startfile FROM file_based_lm WHERE " . + $ilDB->in("id", $a_obj_ids, false, "integer"); + + $lm_set = $ilDB->query($q); + while ($rec = $ilDB->fetchAssoc($lm_set)) { + self::$startfile[$rec["id"]] = $rec["startfile"] . ""; + } + } } - -?> diff --git a/Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMGUI.php b/Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMGUI.php index db5220635331e590d0802a7e3790b368d2977cf6..9b1d220a2268de57a47eaede0a8227e3078e7ae2 100755 --- a/Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMGUI.php +++ b/Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMGUI.php @@ -23,875 +23,846 @@ require_once("./Services/FileSystem/classes/class.ilFileSystemGUI.php"); class ilObjFileBasedLMGUI extends ilObjectGUI { - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * @var ilHelpGUI - */ - protected $help; - - var $output_prepared; - - /** - * Constructor - * - * @access public - */ - function __construct($a_data,$a_id = 0,$a_call_by_reference = true, $a_prepare_output = true) - { - global $DIC; - - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - $this->locator = $DIC["ilLocator"]; - $this->tabs = $DIC->tabs(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->tree = $DIC->repositoryTree(); - $this->tpl = $DIC["tpl"]; - $this->access = $DIC->access(); - $this->error = $DIC["ilErr"]; - $this->toolbar = $DIC->toolbar(); - $this->help = $DIC["ilHelp"]; - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - - $this->ctrl = $ilCtrl; - $this->ctrl->saveParameter($this, array("ref_id")); - - $this->type = "htlm"; - $lng->loadLanguageModule("content"); - $lng->loadLanguageModule("obj"); - - parent::__construct($a_data, $a_id, $a_call_by_reference, false); - //$this->actions = $this->objDefinition->getActions("mep"); - $this->output_prepared = $a_prepare_output; - - } - - /** - * execute command - */ - function executeCommand() - { - $ilUser = $this->user; - $ilLocator = $this->locator; - $ilTabs = $this->tabs; - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - if (strtolower($_GET["baseClass"]) == "iladministrationgui" || - $this->getCreationMode() == true) - { - $this->prepareOutput(); - } - else - { - if (!in_array($cmd, array("", "framset")) || $next_class != "") - { - $this->getTemplate(); - $this->setLocator(); - $this->setTabs(); - } - } - - switch($next_class) - { - case 'ilobjectmetadatagui': - $this->checkPermission("write"); - $ilTabs->activateTab('id_meta_data'); - include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php"; - $md_gui = new ilObjectMetaDataGUI($this->object); - $this->ctrl->forwardCommand($md_gui); - break; - - case "ilfilesystemgui": - $this->checkPermission("write"); - $ilTabs->activateTab('id_list_files'); - $fs_gui = new ilFileSystemGUI($this->object->getDataDirectory()); - $fs_gui->activateLabels(true, $this->lng->txt("cont_purpose")); - $fs_gui->setUseUploadDirectory(true); - $fs_gui->setTableId("htlmfs".$this->object->getId()); - if ($this->object->getStartFile() != "") - { - $fs_gui->labelFile($this->object->getStartFile(), - $this->lng->txt("cont_startfile")); - } - $fs_gui->addCommand($this, "setStartFile", $this->lng->txt("cont_set_start_file")); - - $this->ctrl->forwardCommand($fs_gui); - - // try to set start file automatically - require_once("./Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMAccess.php"); - if (!ilObjFileBasedLMAccess::_determineStartUrl($this->object->getId())) - { - $do_update = false; - - $pcommand = $fs_gui->getLastPerformedCommand(); - if (is_array($pcommand)) - { - $valid = array("index.htm", "index.html", "start.htm", "start.html"); - if($pcommand["cmd"] == "create_file") - { - $file = strtolower(basename($pcommand["name"])); - if(in_array($file, $valid)) - { - $this->object->setStartFile($pcommand["name"]); - $do_update = $pcommand["name"]; - } - } - else if($pcommand["cmd"] == "unzip_file") - { - $zip_file = strtolower(basename($pcommand["name"])); - $suffix = strrpos($zip_file, "."); - if($suffix) - { - $zip_file = substr($zip_file, 0, $suffix); - } - foreach($pcommand["added"] as $file) - { - $chk_file = null; - if(stristr($file, ".htm")) - { - $chk_file = strtolower(basename($file)); - $suffix = strrpos($chk_file, "."); - if($suffix) - { - $chk_file = substr($chk_file, 0, $suffix); - } - } - if(in_array(basename($file), $valid) || - ($zip_file && $chk_file && $chk_file == $zip_file)) - { - $this->object->setStartFile($file); - $do_update = $file; - break; - } - } - } - } - - if($do_update) - { - ilUtil::sendInfo(sprintf($this->lng->txt("cont_start_file_set_to"), $do_update), true); - - $this->object->update(); - $this->ctrl->redirectByClass("ilfilesystemgui", "listFiles"); - } - } - break; - - case "ilinfoscreengui": - $ret = $this->outputInfoScreen(); - break; - - case "illearningprogressgui": - $ilTabs->activateTab('id_learning_progress'); - include_once './Services/Tracking/classes/class.ilLearningProgressGUI.php'; - $new_gui = new ilLearningProgressGUI(ilLearningProgressGUI::LP_CONTEXT_REPOSITORY, - $this->object->getRefId(), - $_GET['user_id'] ? $_GET['user_id'] : $ilUser->getId()); - $this->ctrl->forwardCommand($new_gui); - break; - - case 'ilpermissiongui': - $ilTabs->activateTab('id_permissions'); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $ret = $this->ctrl->forwardCommand($perm_gui); - break; - - case "ilexportgui": - $ilTabs->activateTab("export"); - include_once("./Services/Export/classes/class.ilExportGUI.php"); - $exp_gui = new ilExportGUI($this); - $exp_gui->addFormat("xml"); - $exp_gui->addFormat("html", "", $this, "exportHTML"); - $ret = $this->ctrl->forwardCommand($exp_gui); + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilHelpGUI + */ + protected $help; + + public $output_prepared; + + /** + * Constructor + * + * @access public + */ + public function __construct($a_data, $a_id = 0, $a_call_by_reference = true, $a_prepare_output = true) + { + global $DIC; + + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + $this->locator = $DIC["ilLocator"]; + $this->tabs = $DIC->tabs(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->tree = $DIC->repositoryTree(); + $this->tpl = $DIC["tpl"]; + $this->access = $DIC->access(); + $this->error = $DIC["ilErr"]; + $this->toolbar = $DIC->toolbar(); + $this->help = $DIC["ilHelp"]; + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + + $this->ctrl = $ilCtrl; + $this->ctrl->saveParameter($this, array("ref_id")); + + $this->type = "htlm"; + $lng->loadLanguageModule("content"); + $lng->loadLanguageModule("obj"); + + parent::__construct($a_data, $a_id, $a_call_by_reference, false); + //$this->actions = $this->objDefinition->getActions("mep"); + $this->output_prepared = $a_prepare_output; + } + + /** + * execute command + */ + public function executeCommand() + { + $ilUser = $this->user; + $ilLocator = $this->locator; + $ilTabs = $this->tabs; + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + if (strtolower($_GET["baseClass"]) == "iladministrationgui" || + $this->getCreationMode() == true) { + $this->prepareOutput(); + } else { + if (!in_array($cmd, array("", "framset")) || $next_class != "") { + $this->getTemplate(); + $this->setLocator(); + $this->setTabs(); + } + } + + switch ($next_class) { + case 'ilobjectmetadatagui': + $this->checkPermission("write"); + $ilTabs->activateTab('id_meta_data'); + include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php"; + $md_gui = new ilObjectMetaDataGUI($this->object); + $this->ctrl->forwardCommand($md_gui); + break; + + case "ilfilesystemgui": + $this->checkPermission("write"); + $ilTabs->activateTab('id_list_files'); + $fs_gui = new ilFileSystemGUI($this->object->getDataDirectory()); + $fs_gui->activateLabels(true, $this->lng->txt("cont_purpose")); + $fs_gui->setUseUploadDirectory(true); + $fs_gui->setTableId("htlmfs" . $this->object->getId()); + if ($this->object->getStartFile() != "") { + $fs_gui->labelFile( + $this->object->getStartFile(), + $this->lng->txt("cont_startfile") + ); + } + $fs_gui->addCommand($this, "setStartFile", $this->lng->txt("cont_set_start_file")); + + $this->ctrl->forwardCommand($fs_gui); + + // try to set start file automatically + require_once("./Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMAccess.php"); + if (!ilObjFileBasedLMAccess::_determineStartUrl($this->object->getId())) { + $do_update = false; + + $pcommand = $fs_gui->getLastPerformedCommand(); + if (is_array($pcommand)) { + $valid = array("index.htm", "index.html", "start.htm", "start.html"); + if ($pcommand["cmd"] == "create_file") { + $file = strtolower(basename($pcommand["name"])); + if (in_array($file, $valid)) { + $this->object->setStartFile($pcommand["name"]); + $do_update = $pcommand["name"]; + } + } elseif ($pcommand["cmd"] == "unzip_file") { + $zip_file = strtolower(basename($pcommand["name"])); + $suffix = strrpos($zip_file, "."); + if ($suffix) { + $zip_file = substr($zip_file, 0, $suffix); + } + foreach ($pcommand["added"] as $file) { + $chk_file = null; + if (stristr($file, ".htm")) { + $chk_file = strtolower(basename($file)); + $suffix = strrpos($chk_file, "."); + if ($suffix) { + $chk_file = substr($chk_file, 0, $suffix); + } + } + if (in_array(basename($file), $valid) || + ($zip_file && $chk_file && $chk_file == $zip_file)) { + $this->object->setStartFile($file); + $do_update = $file; + break; + } + } + } + } + + if ($do_update) { + ilUtil::sendInfo(sprintf($this->lng->txt("cont_start_file_set_to"), $do_update), true); + + $this->object->update(); + $this->ctrl->redirectByClass("ilfilesystemgui", "listFiles"); + } + } + break; + + case "ilinfoscreengui": + $ret = $this->outputInfoScreen(); + break; + + case "illearningprogressgui": + $ilTabs->activateTab('id_learning_progress'); + include_once './Services/Tracking/classes/class.ilLearningProgressGUI.php'; + $new_gui = new ilLearningProgressGUI( + ilLearningProgressGUI::LP_CONTEXT_REPOSITORY, + $this->object->getRefId(), + $_GET['user_id'] ? $_GET['user_id'] : $ilUser->getId() + ); + $this->ctrl->forwardCommand($new_gui); + break; + + case 'ilpermissiongui': + $ilTabs->activateTab('id_permissions'); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $ret = $this->ctrl->forwardCommand($perm_gui); + break; + + case "ilexportgui": + $ilTabs->activateTab("export"); + include_once("./Services/Export/classes/class.ilExportGUI.php"); + $exp_gui = new ilExportGUI($this); + $exp_gui->addFormat("xml"); + $exp_gui->addFormat("html", "", $this, "exportHTML"); + $ret = $this->ctrl->forwardCommand($exp_gui); // $this->tpl->show(); - break; - - case "ilcommonactiondispatchergui": - include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); - $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); - $this->ctrl->forwardCommand($gui); - break; - - default: - $cmd = $this->ctrl->getCmd("frameset"); - if (strtolower($_GET["baseClass"]) == "iladministrationgui" || - $this->getCreationMode() == true) - { - $cmd.= "Object"; - } - $ret = $this->$cmd(); - break; - } - - $this->addHeaderAction(); - } - - protected function initCreationForms($a_new_type) - { - $forms = array(self::CFORM_NEW => $this->initCreateForm($a_new_type), - self::CFORM_IMPORT => $this->initImportForm($a_new_type)); - - return $forms; - } - - /** - * cancel action and go back to previous page - * @access public - * - */ - final function cancelCreationObject($in_rep = false) - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirectByClass("ilrepositorygui", "frameset"); - } - - /** - * edit properties of object (admin form) - * - * @access public - */ - function properties() - { - $rbacsystem = $this->rbacsystem; - $tree = $this->tree; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - $ilTabs->activateTab("id_settings"); - - $this->initSettingsForm(); - $this->getSettingsFormValues(); - $tpl->setContent($this->form->getHTML()); - } - - /** - * Init settings form. - */ - public function initSettingsForm() - { - $obj_service = $this->getObjectService(); - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - // title - $ti = new ilTextInputGUI($this->lng->txt("title"), "title"); - $ti->setSize(min(40, ilObject::TITLE_LENGTH)); - $ti->setMaxLength(ilObject::TITLE_LENGTH); - $ti->setRequired(true); - $this->form->addItem($ti); - - // description - $ta = new ilTextAreaInputGUI($this->lng->txt("description"), "desc"); - $ta->setCols(40); - $ta->setRows(2); - $this->form->addItem($ta); - - // online - $cb = new ilCheckboxInputGUI($lng->txt("cont_online"), "cobj_online"); - $cb->setOptionTitle($lng->txt("")); - $cb->setValue("y"); - $this->form->addItem($cb); - - // startfile - require_once("./Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMAccess.php"); - $startfile = ilObjFileBasedLMAccess::_determineStartUrl($this->object->getId()); - - $ne = new ilNonEditableValueGUI($lng->txt("cont_startfile"), ""); - if ($startfile != "") - { - $ne->setValue(basename($startfile)); - } - else - { - $ne->setValue(basename($this->lng->txt("no_start_file"))); - } - $this->form->addItem($ne); - - $pres = new ilFormSectionHeaderGUI(); - $pres->setTitle($this->lng->txt('obj_presentation')); - $this->form->addItem($pres); - - // tile image - $obj_service->commonSettings()->legacyForm($this->form, $this->object)->addTileImage(); - - $this->form->addCommandButton("saveProperties", $lng->txt("save")); - $this->form->addCommandButton("toFilesystem", $lng->txt("cont_set_start_file")); - - $this->form->setTitle($lng->txt("cont_lm_properties")); - $this->form->setFormAction($ilCtrl->getFormAction($this, "saveProperties")); - } - - /** - * Get current values for settings from - */ - public function getSettingsFormValues() - { - require_once("./Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMAccess.php"); - $startfile = ilObjFileBasedLMAccess::_determineStartUrl($this->object->getId()); - - $values = array(); - $values['cobj_online'] = !$this->object->getOfflineStatus(); - if ($startfile != "") - { - $startfile = basename($startfile); - } - else - { - $startfile = $this->lng->txt("no_start_file"); - } - - $values["startfile"] = $startfile; - $values["title"] = $this->object->getTitle(); - $values["desc"] = $this->object->getDescription(); - //$values["lic"] = $this->object->getShowLicense(); - - $this->form->setValuesByArray($values); - } - - /** - * Set start file - * - * @param - * @return - */ - function toFilesystem() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirectByClass("ilfilesystemgui", "listFiles"); - } - - /** - * Save properties form - */ - public function saveProperties() - { - $tpl = $this->tpl; - $ilAccess = $this->access; - $ilTabs = $this->tabs; - $obj_service = $this->getObjectService(); - - $this->initSettingsForm(""); - if ($this->form->checkInput()) - { - $this->object->setTitle($this->form->getInput("title")); - $this->object->setDescription($this->form->getInput("desc")); - $this->object->setOfflineStatus(! (bool) $_POST['cobj_online']); - - $this->object->update(); - - // tile image - $obj_service->commonSettings()->legacyForm($this->form, $this->object)->saveTileImage(); - - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "properties"); - } - - $ilTabs->activateTab("id_settings"); - $this->form->setValuesByPost(); - $tpl->setContent($this->form->getHtml()); - } - - /** - * edit properties of object (admin form) - * - * @access public - */ - function editObject() - { - $rbacsystem = $this->rbacsystem; - $ilErr = $this->error; - - if (!$rbacsystem->checkAccess("visible,write",$this->object->getRefId())) - { - $ilErr->raiseError($this->lng->txt("permission_denied"), $ilErr->MESSAGE); - } - - } - - /** - * edit properties of object (module form) - */ - function edit() - { - $this->prepareOutput(); - $this->editObject(); - } - - /** - * cancel editing - */ - function cancel() - { - //$this->setReturnLocation("cancel","fblm_edit.php?cmd=listFiles&ref_id=".$_GET["ref_id"]); - $this->cancelObject(); - } - - /** - * save object - * @access public - */ - function afterSave(ilObject $newObj) - { - if(!$newObj->getStartFile()) - { - // try to set start file automatically - $files = array(); - include_once "Services/Utilities/classes/class.ilFileUtils.php"; - ilFileUtils::recursive_dirscan($newObj->getDataDirectory(), $files); - if(is_array($files["file"])) - { - $zip_file = null; - if(stristr($newObj->getTitle(), ".zip")) - { - $zip_file = strtolower($newObj->getTitle()); - $suffix = strrpos($zip_file, "."); - if($suffix) - { - $zip_file = substr($zip_file, 0, $suffix); - } - } - $valid = array("index.htm", "index.html", "start.htm", "start.html"); - foreach($files["file"] as $idx => $file) - { - $chk_file = null; - if(stristr($file, ".htm")) - { - $chk_file = strtolower($file); - $suffix = strrpos($chk_file, "."); - if($suffix) - { - $chk_file = substr($chk_file, 0, $suffix); - } - } - if(in_array($file, $valid) || - ($chk_file && $zip_file && $chk_file == $zip_file)) - { - $newObj->setStartFile(str_replace($newObj->getDataDirectory()."/", "", $files["path"][$idx]).$file); - $newObj->update(); - break; - } - } - } - } - - // always send a message - ilUtil::sendSuccess($this->lng->txt("object_added"),true); - $this->object = $newObj; - $this->redirectAfterCreation(); - } - - - /** - * update properties - */ - function update() - { - //$this->setReturnLocation("update", "fblm_edit.php?cmd=listFiles&ref_id=".$_GET["ref_id"]. - // "&obj_id=".$_GET["obj_id"]); - $this->updateObject(); - } - - - function setStartFile($a_file) - { - $this->object->setStartFile($a_file); - $this->object->update(); - $this->ctrl->redirectByClass("ilfilesystemgui", "listFiles"); - } - - /** - * permission form - */ - function perm() - { - $this->setFormAction("permSave", "fblm_edit.php?cmd=permSave&ref_id=".$_GET["ref_id"]. - "&obj_id=".$_GET["obj_id"]); - $this->setFormAction("addRole", "fblm_edit.php?ref_id=".$_GET["ref_id"]. - "&obj_id=".$_GET["obj_id"]."&cmd=addRole"); - $this->permObject(); - } - - - /** - * Frameset -> Output list of files - */ - function frameset() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->setCmdClass("ilfilesystemgui"); - $ilCtrl->setCmd("listFiles"); - return $this->executeCommand(); - } - - /** - * output main header (title and locator) - */ - function getTemplate() - { - $lng = $this->lng; - - $this->tpl->getStandardTemplate(); - } - - function showLearningModule() - { - $ilUser = $this->user; - - // #9483 - if ($ilUser->getId() != ANONYMOUS_USER_ID) - { - include_once "Services/Tracking/classes/class.ilLearningProgress.php"; - ilLearningProgress::_tracProgress($ilUser->getId(), $this->object->getId(), - $this->object->getRefId(), "htlm"); - } - - require_once("./Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMAccess.php"); - require_once('./Services/WebAccessChecker/classes/class.ilWACSignedPath.php'); - - $startfile = ilObjFileBasedLMAccess::_determineStartUrl($this->object->getId()); - ilWACSignedPath::signFolderOfStartFile($startfile); - if ($startfile != "") - { - ilUtil::redirect($startfile); - } - } - - // InfoScreen methods - /** - * 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->outputInfoScreen(); - } - - /** - * info screen call from inside learning module - */ - function showInfoScreen() - { - $this->outputInfoScreen(true); - } - - /** - * info screen - */ - function outputInfoScreen($a_standard_locator = true) - { - $ilToolbar = $this->toolbar; - $ilAccess = $this->access; - $ilTabs = $this->tabs; - - $ilTabs->activateTab('id_info'); - - $this->lng->loadLanguageModule("meta"); - include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); - - $info = new ilInfoScreenGUI($this); - $info->enablePrivateNotes(); - $info->enableLearningProgress(); - - $info->enableNews(); - if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) - { - $info->enableNewsEditing(); - - $news_set = new ilSetting("news"); - $enable_internal_rss = $news_set->get("enable_rss_for_internal"); - if ($enable_internal_rss) - { - $info->setBlockProperty("news", "settings", true); - } - } - - // add read / back button - if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - // #15127 - include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; - $button = ilLinkButton::getInstance(); - $button->setCaption("view"); - $button->setPrimary(true); - $button->setUrl("ilias.php?baseClass=ilHTLMPresentationGUI&ref_id=".$this->object->getRefID()); - $button->setTarget("ilContObj".$this->object->getId()); - $ilToolbar->addButtonInstance($button); - } - - // show standard meta data section - $info->addMetaDataSections($this->object->getId(),0, $this->object->getType()); - - // forward the command - $this->ctrl->forwardCommand($info); - } - - - - /** - * output tabs - */ - function setTabs() - { - $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_lm.svg")); - - $this->getTabs(); - $this->tpl->setTitle($this->object->getTitle()); - } - - /** - * adds tabs to tab gui object - */ - function getTabs() - { - $ilUser = $this->user; - $ilAccess = $this->access; - $ilTabs = $this->tabs; - $lng = $this->lng; - $ilHelp = $this->help; - - $ilHelp->setScreenIdComponent("htlm"); - - if($ilAccess->checkAccess('write', '', $this->ref_id)) - { - $ilTabs->addTab("id_list_files", - $lng->txt("cont_list_files"), - $this->ctrl->getLinkTargetByClass("ilfilesystemgui", "listFiles")); - } - - if($ilAccess->checkAccess('visible', '', $this->ref_id)) - { - $ilTabs->addTab("id_info", - $lng->txt("info_short"), - $this->ctrl->getLinkTargetByClass(array("ilobjfilebasedlmgui", "ilinfoscreengui"), "showSummary")); - } - - if($ilAccess->checkAccess('write', '', $this->ref_id)) - { - $ilTabs->addTab("id_settings", - $lng->txt("settings"), - $this->ctrl->getLinkTarget($this, "properties")); - } - - include_once './Services/Tracking/classes/class.ilLearningProgressAccess.php'; - if(ilLearningProgressAccess::checkAccess($this->object->getRefId())) - { - $ilTabs->addTab("id_learning_progress", - $lng->txt("learning_progress"), - $this->ctrl->getLinkTargetByClass(array('ilobjfilebasedlmgui','illearningprogressgui'), '')); - } - - if($ilAccess->checkAccess('write', '', $this->ref_id)) - { - include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php"; - $mdgui = new ilObjectMetaDataGUI($this->object); - $mdtab = $mdgui->getTab(); - if($mdtab) - { - $ilTabs->addTab("id_meta_data", - $lng->txt("meta_data"), - $mdtab); - } - - } - - - // export - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - $ilTabs->addTab("export", - $lng->txt("export"), - $this->ctrl->getLinkTargetByClass("ilexportgui", "")); - } - - if ($ilAccess->checkAccess('edit_permission', '', $this->object->getRefId())) - { - $ilTabs->addTab("id_permissions", - $lng->txt("perm_settings"), - $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm")); - } - - require_once("./Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMAccess.php"); - $startfile = ilObjFileBasedLMAccess::_determineStartUrl($this->object->getId()); - - if ($startfile != "") - { - $ilTabs->addNonTabbedLink("presentation_view", - $this->lng->txt("glo_presentation_view"), - "ilias.php?baseClass=ilHTLMPresentationGUI&ref_id=".$this->object->getRefID(), - "_blank" - ); - } - - } - - /** - * redirect script - * - * @param string $a_target - */ - public static function _goto($a_target) - { - global $DIC; - - $rbacsystem = $DIC->rbac()->system(); - $ilErr = $DIC["ilErr"]; - $lng = $DIC->language(); - $ilAccess = $DIC->access(); - - if ($ilAccess->checkAccess("read", "", $a_target) || - $ilAccess->checkAccess("visible", "", $a_target)) - { - ilObjectGUI::_gotoRepositoryNode($a_target, "infoScreen"); - } - else if ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) - { - ilUtil::sendFailure(sprintf($lng->txt("msg_no_perm_read_item"), - ilObject::_lookupTitle(ilObject::_lookupObjId($a_target))), true); - ilObjectGUI::_gotoRepositoryRoot(); - } - - $ilErr->raiseError($lng->txt("msg_no_perm_read_lm"), $ilErr->FATAL); - } - - function addLocatorItems() - { - $ilLocator = $this->locator; - - if (is_object($this->object)) - { - $ilLocator->addItem($this->object->getTitle(), - $this->ctrl->getLinkTargetByClass("ilinfoscreengui", "showSummary"), "", $_GET["ref_id"]); - } - } - - - /** - * Import file - * - * @param - * @return - */ - function importFileObject($parent_id = null, $a_catch_errors = true) - { - try - { - return parent::importFileObject(); - } - catch (ilManifestFileNotFoundImportException $e) - { - // since there is no manifest xml we assume that this is an HTML export file - $this->createFromDirectory($e->getTmpDir()); - } - } - - /** - * Create new object from a html zip file - * - * @param - * @return - */ - function createFromDirectory($a_dir) - { - $ilErr = $this->error; - - if (!$this->checkPermissionBool("create", "", "htlm") || $a_dir == "") - { - $ilErr->raiseError($this->lng->txt("no_create_permission")); - } - - // create instance - $newObj = new ilObjFileBasedLM(); - $filename = ilUtil::stripSlashes($_FILES["importfile"]["name"]); - $newObj->setTitle($filename); - $newObj->setDescription(""); - $newObj->create(); - $newObj->populateByDirectoy($a_dir, $filename); - $this->putObjectInTree($newObj); - - $this->afterSave($newObj); - } - - - - - //// - //// Export to HTML - //// - - - /** - * create html package - */ - function exportHTML() - { - $inst_id = IL_INST_ID; - - include_once("./Services/Export/classes/class.ilExport.php"); - - ilExport::_createExportDirectory($this->object->getId(), "html", - $this->object->getType()); - $export_dir = ilExport::_getExportDirectory($this->object->getId(), "html", - $this->object->getType()); - - $subdir = $this->object->getType()."_".$this->object->getId(); - $filename = $this->subdir.".zip"; - - $target_dir = $export_dir."/".$subdir; - - ilUtil::delDir($target_dir); - ilUtil::makeDir($target_dir); - - $source_dir = $this->object->getDataDirectory(); - - ilUtil::rCopy($source_dir, $target_dir); - - // zip it all - $date = time(); - $zip_file = $export_dir."/".$date."__".IL_INST_ID."__". - $this->object->getType()."_".$this->object->getId().".zip"; - ilUtil::zip($target_dir, $zip_file); - - ilUtil::delDir($target_dir); - } - - /** - * @inheritdoc - */ - public function redirectAfterCreation() - { - $ctrl = $this->ctrl; - $ctrl->setParameterByClass("ilObjFileBasedLMGUI", "ref_id", $this->object->getRefId()); - $ctrl->redirectByClass(["ilrepositorygui", "ilObjFileBasedLMGUI"], "properties"); - } - - + break; + + case "ilcommonactiondispatchergui": + include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); + $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); + $this->ctrl->forwardCommand($gui); + break; + + default: + $cmd = $this->ctrl->getCmd("frameset"); + if (strtolower($_GET["baseClass"]) == "iladministrationgui" || + $this->getCreationMode() == true) { + $cmd.= "Object"; + } + $ret = $this->$cmd(); + break; + } + + $this->addHeaderAction(); + } + + protected function initCreationForms($a_new_type) + { + $forms = array(self::CFORM_NEW => $this->initCreateForm($a_new_type), + self::CFORM_IMPORT => $this->initImportForm($a_new_type)); + + return $forms; + } + + /** + * cancel action and go back to previous page + * @access public + * + */ + final public function cancelCreationObject($in_rep = false) + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirectByClass("ilrepositorygui", "frameset"); + } + + /** + * edit properties of object (admin form) + * + * @access public + */ + public function properties() + { + $rbacsystem = $this->rbacsystem; + $tree = $this->tree; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + $ilTabs->activateTab("id_settings"); + + $this->initSettingsForm(); + $this->getSettingsFormValues(); + $tpl->setContent($this->form->getHTML()); + } + + /** + * Init settings form. + */ + public function initSettingsForm() + { + $obj_service = $this->getObjectService(); + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + // title + $ti = new ilTextInputGUI($this->lng->txt("title"), "title"); + $ti->setSize(min(40, ilObject::TITLE_LENGTH)); + $ti->setMaxLength(ilObject::TITLE_LENGTH); + $ti->setRequired(true); + $this->form->addItem($ti); + + // description + $ta = new ilTextAreaInputGUI($this->lng->txt("description"), "desc"); + $ta->setCols(40); + $ta->setRows(2); + $this->form->addItem($ta); + + // online + $cb = new ilCheckboxInputGUI($lng->txt("cont_online"), "cobj_online"); + $cb->setOptionTitle($lng->txt("")); + $cb->setValue("y"); + $this->form->addItem($cb); + + // startfile + require_once("./Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMAccess.php"); + $startfile = ilObjFileBasedLMAccess::_determineStartUrl($this->object->getId()); + + $ne = new ilNonEditableValueGUI($lng->txt("cont_startfile"), ""); + if ($startfile != "") { + $ne->setValue(basename($startfile)); + } else { + $ne->setValue(basename($this->lng->txt("no_start_file"))); + } + $this->form->addItem($ne); + + $pres = new ilFormSectionHeaderGUI(); + $pres->setTitle($this->lng->txt('obj_presentation')); + $this->form->addItem($pres); + + // tile image + $obj_service->commonSettings()->legacyForm($this->form, $this->object)->addTileImage(); + + $this->form->addCommandButton("saveProperties", $lng->txt("save")); + $this->form->addCommandButton("toFilesystem", $lng->txt("cont_set_start_file")); + + $this->form->setTitle($lng->txt("cont_lm_properties")); + $this->form->setFormAction($ilCtrl->getFormAction($this, "saveProperties")); + } + + /** + * Get current values for settings from + */ + public function getSettingsFormValues() + { + require_once("./Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMAccess.php"); + $startfile = ilObjFileBasedLMAccess::_determineStartUrl($this->object->getId()); + + $values = array(); + $values['cobj_online'] = !$this->object->getOfflineStatus(); + if ($startfile != "") { + $startfile = basename($startfile); + } else { + $startfile = $this->lng->txt("no_start_file"); + } + + $values["startfile"] = $startfile; + $values["title"] = $this->object->getTitle(); + $values["desc"] = $this->object->getDescription(); + //$values["lic"] = $this->object->getShowLicense(); + + $this->form->setValuesByArray($values); + } + + /** + * Set start file + * + * @param + * @return + */ + public function toFilesystem() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirectByClass("ilfilesystemgui", "listFiles"); + } + + /** + * Save properties form + */ + public function saveProperties() + { + $tpl = $this->tpl; + $ilAccess = $this->access; + $ilTabs = $this->tabs; + $obj_service = $this->getObjectService(); + + $this->initSettingsForm(""); + if ($this->form->checkInput()) { + $this->object->setTitle($this->form->getInput("title")); + $this->object->setDescription($this->form->getInput("desc")); + $this->object->setOfflineStatus(!(bool) $_POST['cobj_online']); + + $this->object->update(); + + // tile image + $obj_service->commonSettings()->legacyForm($this->form, $this->object)->saveTileImage(); + + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "properties"); + } + + $ilTabs->activateTab("id_settings"); + $this->form->setValuesByPost(); + $tpl->setContent($this->form->getHtml()); + } + + /** + * edit properties of object (admin form) + * + * @access public + */ + public function editObject() + { + $rbacsystem = $this->rbacsystem; + $ilErr = $this->error; + + if (!$rbacsystem->checkAccess("visible,write", $this->object->getRefId())) { + $ilErr->raiseError($this->lng->txt("permission_denied"), $ilErr->MESSAGE); + } + } + + /** + * edit properties of object (module form) + */ + public function edit() + { + $this->prepareOutput(); + $this->editObject(); + } + + /** + * cancel editing + */ + public function cancel() + { + //$this->setReturnLocation("cancel","fblm_edit.php?cmd=listFiles&ref_id=".$_GET["ref_id"]); + $this->cancelObject(); + } + + /** + * save object + * @access public + */ + public function afterSave(ilObject $newObj) + { + if (!$newObj->getStartFile()) { + // try to set start file automatically + $files = array(); + include_once "Services/Utilities/classes/class.ilFileUtils.php"; + ilFileUtils::recursive_dirscan($newObj->getDataDirectory(), $files); + if (is_array($files["file"])) { + $zip_file = null; + if (stristr($newObj->getTitle(), ".zip")) { + $zip_file = strtolower($newObj->getTitle()); + $suffix = strrpos($zip_file, "."); + if ($suffix) { + $zip_file = substr($zip_file, 0, $suffix); + } + } + $valid = array("index.htm", "index.html", "start.htm", "start.html"); + foreach ($files["file"] as $idx => $file) { + $chk_file = null; + if (stristr($file, ".htm")) { + $chk_file = strtolower($file); + $suffix = strrpos($chk_file, "."); + if ($suffix) { + $chk_file = substr($chk_file, 0, $suffix); + } + } + if (in_array($file, $valid) || + ($chk_file && $zip_file && $chk_file == $zip_file)) { + $newObj->setStartFile(str_replace($newObj->getDataDirectory() . "/", "", $files["path"][$idx]) . $file); + $newObj->update(); + break; + } + } + } + } + + // always send a message + ilUtil::sendSuccess($this->lng->txt("object_added"), true); + $this->object = $newObj; + $this->redirectAfterCreation(); + } + + + /** + * update properties + */ + public function update() + { + //$this->setReturnLocation("update", "fblm_edit.php?cmd=listFiles&ref_id=".$_GET["ref_id"]. + // "&obj_id=".$_GET["obj_id"]); + $this->updateObject(); + } + + + public function setStartFile($a_file) + { + $this->object->setStartFile($a_file); + $this->object->update(); + $this->ctrl->redirectByClass("ilfilesystemgui", "listFiles"); + } + + /** + * permission form + */ + public function perm() + { + $this->setFormAction("permSave", "fblm_edit.php?cmd=permSave&ref_id=" . $_GET["ref_id"] . + "&obj_id=" . $_GET["obj_id"]); + $this->setFormAction("addRole", "fblm_edit.php?ref_id=" . $_GET["ref_id"] . + "&obj_id=" . $_GET["obj_id"] . "&cmd=addRole"); + $this->permObject(); + } + + + /** + * Frameset -> Output list of files + */ + public function frameset() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->setCmdClass("ilfilesystemgui"); + $ilCtrl->setCmd("listFiles"); + return $this->executeCommand(); + } + + /** + * output main header (title and locator) + */ + public function getTemplate() + { + $lng = $this->lng; + + $this->tpl->getStandardTemplate(); + } + + public function showLearningModule() + { + $ilUser = $this->user; + + // #9483 + if ($ilUser->getId() != ANONYMOUS_USER_ID) { + include_once "Services/Tracking/classes/class.ilLearningProgress.php"; + ilLearningProgress::_tracProgress( + $ilUser->getId(), + $this->object->getId(), + $this->object->getRefId(), + "htlm" + ); + } + + require_once("./Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMAccess.php"); + require_once('./Services/WebAccessChecker/classes/class.ilWACSignedPath.php'); + + $startfile = ilObjFileBasedLMAccess::_determineStartUrl($this->object->getId()); + ilWACSignedPath::signFolderOfStartFile($startfile); + if ($startfile != "") { + ilUtil::redirect($startfile); + } + } + + // InfoScreen methods + /** + * 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->outputInfoScreen(); + } + + /** + * info screen call from inside learning module + */ + public function showInfoScreen() + { + $this->outputInfoScreen(true); + } + + /** + * info screen + */ + public function outputInfoScreen($a_standard_locator = true) + { + $ilToolbar = $this->toolbar; + $ilAccess = $this->access; + $ilTabs = $this->tabs; + + $ilTabs->activateTab('id_info'); + + $this->lng->loadLanguageModule("meta"); + include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); + + $info = new ilInfoScreenGUI($this); + $info->enablePrivateNotes(); + $info->enableLearningProgress(); + + $info->enableNews(); + if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) { + $info->enableNewsEditing(); + + $news_set = new ilSetting("news"); + $enable_internal_rss = $news_set->get("enable_rss_for_internal"); + if ($enable_internal_rss) { + $info->setBlockProperty("news", "settings", true); + } + } + + // add read / back button + if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) { + // #15127 + include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; + $button = ilLinkButton::getInstance(); + $button->setCaption("view"); + $button->setPrimary(true); + $button->setUrl("ilias.php?baseClass=ilHTLMPresentationGUI&ref_id=" . $this->object->getRefID()); + $button->setTarget("ilContObj" . $this->object->getId()); + $ilToolbar->addButtonInstance($button); + } + + // show standard meta data section + $info->addMetaDataSections($this->object->getId(), 0, $this->object->getType()); + + // forward the command + $this->ctrl->forwardCommand($info); + } + + + + /** + * output tabs + */ + public function setTabs() + { + $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_lm.svg")); + + $this->getTabs(); + $this->tpl->setTitle($this->object->getTitle()); + } + + /** + * adds tabs to tab gui object + */ + public function getTabs() + { + $ilUser = $this->user; + $ilAccess = $this->access; + $ilTabs = $this->tabs; + $lng = $this->lng; + $ilHelp = $this->help; + + $ilHelp->setScreenIdComponent("htlm"); + + if ($ilAccess->checkAccess('write', '', $this->ref_id)) { + $ilTabs->addTab( + "id_list_files", + $lng->txt("cont_list_files"), + $this->ctrl->getLinkTargetByClass("ilfilesystemgui", "listFiles") + ); + } + + if ($ilAccess->checkAccess('visible', '', $this->ref_id)) { + $ilTabs->addTab( + "id_info", + $lng->txt("info_short"), + $this->ctrl->getLinkTargetByClass(array("ilobjfilebasedlmgui", "ilinfoscreengui"), "showSummary") + ); + } + + if ($ilAccess->checkAccess('write', '', $this->ref_id)) { + $ilTabs->addTab( + "id_settings", + $lng->txt("settings"), + $this->ctrl->getLinkTarget($this, "properties") + ); + } + + include_once './Services/Tracking/classes/class.ilLearningProgressAccess.php'; + if (ilLearningProgressAccess::checkAccess($this->object->getRefId())) { + $ilTabs->addTab( + "id_learning_progress", + $lng->txt("learning_progress"), + $this->ctrl->getLinkTargetByClass(array('ilobjfilebasedlmgui','illearningprogressgui'), '') + ); + } + + if ($ilAccess->checkAccess('write', '', $this->ref_id)) { + include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php"; + $mdgui = new ilObjectMetaDataGUI($this->object); + $mdtab = $mdgui->getTab(); + if ($mdtab) { + $ilTabs->addTab( + "id_meta_data", + $lng->txt("meta_data"), + $mdtab + ); + } + } + + + // export + if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) { + $ilTabs->addTab( + "export", + $lng->txt("export"), + $this->ctrl->getLinkTargetByClass("ilexportgui", "") + ); + } + + if ($ilAccess->checkAccess('edit_permission', '', $this->object->getRefId())) { + $ilTabs->addTab( + "id_permissions", + $lng->txt("perm_settings"), + $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm") + ); + } + + require_once("./Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMAccess.php"); + $startfile = ilObjFileBasedLMAccess::_determineStartUrl($this->object->getId()); + + if ($startfile != "") { + $ilTabs->addNonTabbedLink( + "presentation_view", + $this->lng->txt("glo_presentation_view"), + "ilias.php?baseClass=ilHTLMPresentationGUI&ref_id=" . $this->object->getRefID(), + "_blank" + ); + } + } + + /** + * redirect script + * + * @param string $a_target + */ + public static function _goto($a_target) + { + global $DIC; + + $rbacsystem = $DIC->rbac()->system(); + $ilErr = $DIC["ilErr"]; + $lng = $DIC->language(); + $ilAccess = $DIC->access(); + + if ($ilAccess->checkAccess("read", "", $a_target) || + $ilAccess->checkAccess("visible", "", $a_target)) { + ilObjectGUI::_gotoRepositoryNode($a_target, "infoScreen"); + } elseif ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) { + ilUtil::sendFailure(sprintf( + $lng->txt("msg_no_perm_read_item"), + ilObject::_lookupTitle(ilObject::_lookupObjId($a_target)) + ), true); + ilObjectGUI::_gotoRepositoryRoot(); + } + + $ilErr->raiseError($lng->txt("msg_no_perm_read_lm"), $ilErr->FATAL); + } + + public function addLocatorItems() + { + $ilLocator = $this->locator; + + if (is_object($this->object)) { + $ilLocator->addItem( + $this->object->getTitle(), + $this->ctrl->getLinkTargetByClass("ilinfoscreengui", "showSummary"), + "", + $_GET["ref_id"] + ); + } + } + + + /** + * Import file + * + * @param + * @return + */ + public function importFileObject($parent_id = null, $a_catch_errors = true) + { + try { + return parent::importFileObject(); + } catch (ilManifestFileNotFoundImportException $e) { + // since there is no manifest xml we assume that this is an HTML export file + $this->createFromDirectory($e->getTmpDir()); + } + } + + /** + * Create new object from a html zip file + * + * @param + * @return + */ + public function createFromDirectory($a_dir) + { + $ilErr = $this->error; + + if (!$this->checkPermissionBool("create", "", "htlm") || $a_dir == "") { + $ilErr->raiseError($this->lng->txt("no_create_permission")); + } + + // create instance + $newObj = new ilObjFileBasedLM(); + $filename = ilUtil::stripSlashes($_FILES["importfile"]["name"]); + $newObj->setTitle($filename); + $newObj->setDescription(""); + $newObj->create(); + $newObj->populateByDirectoy($a_dir, $filename); + $this->putObjectInTree($newObj); + + $this->afterSave($newObj); + } + + + + + //// + //// Export to HTML + //// + + + /** + * create html package + */ + public function exportHTML() + { + $inst_id = IL_INST_ID; + + include_once("./Services/Export/classes/class.ilExport.php"); + + ilExport::_createExportDirectory( + $this->object->getId(), + "html", + $this->object->getType() + ); + $export_dir = ilExport::_getExportDirectory( + $this->object->getId(), + "html", + $this->object->getType() + ); + + $subdir = $this->object->getType() . "_" . $this->object->getId(); + $filename = $this->subdir . ".zip"; + + $target_dir = $export_dir . "/" . $subdir; + + ilUtil::delDir($target_dir); + ilUtil::makeDir($target_dir); + + $source_dir = $this->object->getDataDirectory(); + + ilUtil::rCopy($source_dir, $target_dir); + + // zip it all + $date = time(); + $zip_file = $export_dir . "/" . $date . "__" . IL_INST_ID . "__" . + $this->object->getType() . "_" . $this->object->getId() . ".zip"; + ilUtil::zip($target_dir, $zip_file); + + ilUtil::delDir($target_dir); + } + + /** + * @inheritdoc + */ + public function redirectAfterCreation() + { + $ctrl = $this->ctrl; + $ctrl->setParameterByClass("ilObjFileBasedLMGUI", "ref_id", $this->object->getRefId()); + $ctrl->redirectByClass(["ilrepositorygui", "ilObjFileBasedLMGUI"], "properties"); + } } -?> diff --git a/Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMListGUI.php b/Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMListGUI.php index 3d1cbdbd207c1bc12f672a9cf1232fa318f810cf..b74b4180587f51576f6b54f34a56eb7224015c99 100644 --- a/Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMListGUI.php +++ b/Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMListGUI.php @@ -14,120 +14,113 @@ include_once "Services/Object/classes/class.ilObjectListGUI.php"; */ class ilObjFileBasedLMListGUI extends ilObjectListGUI { - /** - * initialisation - * - * this method should be overwritten by derived classes - */ - function init() - { - $this->copy_enabled = true; - $this->delete_enabled = true; - $this->cut_enabled = true; - $this->subscribe_enabled = true; - $this->link_enabled = true; - $this->info_screen_enabled = true; - $this->type = "htlm"; - $this->gui_class_name = "ilobjfilebasedlmgui"; - - // general commands array - include_once('Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMAccess.php'); - $this->commands = ilObjFileBasedLMAccess::_getCommands(); - } - - /** - * Overwrite this method, if link target is not build by ctrl class - * (e.g. "forum.php"). This is the case - * for all links now, but bringing everything to ilCtrl should - * be realised in the future. - * - * @param string $a_cmd command - * - */ - function getCommandLink($a_cmd) - { - $ilCtrl = $this->ctrl; - - switch($a_cmd) - { - case "view": - $cmd_link = "ilias.php?baseClass=ilHTLMPresentationGUI&ref_id=".$this->ref_id; - break; - - case "edit": - $cmd_link = "ilias.php?baseClass=ilHTLMEditorGUI&ref_id=".$this->ref_id; - break; - - default: - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $this->ref_id); - $cmd_link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", $a_cmd); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - break; - } - - return $cmd_link; - } - - - /** - * Get command target frame - * - * @param string $a_cmd command - * - * @return string command target frame - */ - function getCommandFrame($a_cmd) - { - switch($a_cmd) - { - case "view": - $frame = "ilContObj".$this->obj_id; - break; - - case "edit": - $frame = ilFrameTargetInfo::_getFrame("MainContent"); - break; - - default: - $frame = ""; - break; - } - - return $frame; - } - - - /** - * Get item properties - * - * @return array array of property arrays: - * "alert" (boolean) => display as an alert property (usually in red) - * "property" (string) => property name - * "value" (string) => property value - */ - function getProperties() - { - $lng = $this->lng; - $rbacsystem = $this->rbacsystem; - - // centralized offline status - $props = parent::getProperties(); - - if (!ilObjFileBasedLMAccess::_determineStartUrl($this->obj_id)) - { - $props[] = array("alert" => true, "property" => $lng->txt("status"), - "value" => $lng->txt("no_start_file")); - } - - if ($rbacsystem->checkAccess("write",$this->ref_id)) - { - $props[] = array("alert" => false, "property" => $lng->txt("type"), - "value" => $lng->txt("htlm")); - } - - return $props; - } - - + /** + * initialisation + * + * this method should be overwritten by derived classes + */ + public function init() + { + $this->copy_enabled = true; + $this->delete_enabled = true; + $this->cut_enabled = true; + $this->subscribe_enabled = true; + $this->link_enabled = true; + $this->info_screen_enabled = true; + $this->type = "htlm"; + $this->gui_class_name = "ilobjfilebasedlmgui"; + + // general commands array + include_once('Modules/HTMLLearningModule/classes/class.ilObjFileBasedLMAccess.php'); + $this->commands = ilObjFileBasedLMAccess::_getCommands(); + } + + /** + * Overwrite this method, if link target is not build by ctrl class + * (e.g. "forum.php"). This is the case + * for all links now, but bringing everything to ilCtrl should + * be realised in the future. + * + * @param string $a_cmd command + * + */ + public function getCommandLink($a_cmd) + { + $ilCtrl = $this->ctrl; + + switch ($a_cmd) { + case "view": + $cmd_link = "ilias.php?baseClass=ilHTLMPresentationGUI&ref_id=" . $this->ref_id; + break; + + case "edit": + $cmd_link = "ilias.php?baseClass=ilHTLMEditorGUI&ref_id=" . $this->ref_id; + break; + + default: + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $this->ref_id); + $cmd_link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", $a_cmd); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + break; + } + + return $cmd_link; + } + + + /** + * Get command target frame + * + * @param string $a_cmd command + * + * @return string command target frame + */ + public function getCommandFrame($a_cmd) + { + switch ($a_cmd) { + case "view": + $frame = "ilContObj" . $this->obj_id; + break; + + case "edit": + $frame = ilFrameTargetInfo::_getFrame("MainContent"); + break; + + default: + $frame = ""; + break; + } + + return $frame; + } + + + /** + * Get item properties + * + * @return array array of property arrays: + * "alert" (boolean) => display as an alert property (usually in red) + * "property" (string) => property name + * "value" (string) => property value + */ + public function getProperties() + { + $lng = $this->lng; + $rbacsystem = $this->rbacsystem; + + // centralized offline status + $props = parent::getProperties(); + + if (!ilObjFileBasedLMAccess::_determineStartUrl($this->obj_id)) { + $props[] = array("alert" => true, "property" => $lng->txt("status"), + "value" => $lng->txt("no_start_file")); + } + + if ($rbacsystem->checkAccess("write", $this->ref_id)) { + $props[] = array("alert" => false, "property" => $lng->txt("type"), + "value" => $lng->txt("htlm")); + } + + return $props; + } } // END class.ilObjCategoryGUI -?> diff --git a/Modules/ItemGroup/classes/class.ilItemGroupAR.php b/Modules/ItemGroup/classes/class.ilItemGroupAR.php index 4561dc399e5846349b1c6a341843d2335770b0ee..16961c58235c05df4abc608647431e5eae80954d 100644 --- a/Modules/ItemGroup/classes/class.ilItemGroupAR.php +++ b/Modules/ItemGroup/classes/class.ilItemGroupAR.php @@ -9,110 +9,111 @@ include_once("./Services/ActiveRecord/class.ActiveRecord.php"); * * @author Alex Killing * @version $Id$ - * @ingroup + * @ingroup */ class ilItemGroupAR extends ActiveRecord { - /** - * @return string - */ - static function returnDbTableName() { - return 'itgr_data'; - } - - /** - * @var int - * - * @con_is_primary true - * @con_is_unique true - * @con_has_field true - * @con_fieldtype integer - * @con_is_notnull true - * @con_length 4 - * @con_sequence false - */ - protected $id; - - /** - * @var string - * - * @con_has_field true - * @con_fieldtype integer - * @con_length 1 - * @con_is_notnull false - */ - protected $hide_title = ''; - - /** - * @var int - * - * @con_has_field true - * @con_fieldtype integer - * @con_length 1 - * @con_is_notnull false - */ - protected $behaviour = 0; - - /** - * Get ID - * - * @return int ID - */ - public function getId() { - return $this->id; - } - - - /** - * Set ID - * - * @param int $id ID - */ - public function setId($id) { - $this->id = $id; - } - - /** - * Set hide title - * - * @param bool $a_hide_title hide title - */ - public function setHideTitle($a_hide_title) - { - $this->hide_title = $a_hide_title; - } - - - /** - * Get hide title - * - * @return bool hide title - */ - public function getHideTitle() - { - return $this->hide_title; - } - - /** - * Set behaviour - * - * @param int $a_val behaviour - */ - public function setBehaviour($a_val) - { - $this->behaviour = $a_val; - } - - - /** - * Get behaviour - * - * @return int behaviour - */ - public function getBehaviour() - { - return $this->behaviour; - } + /** + * @return string + */ + public static function returnDbTableName() + { + return 'itgr_data'; + } + + /** + * @var int + * + * @con_is_primary true + * @con_is_unique true + * @con_has_field true + * @con_fieldtype integer + * @con_is_notnull true + * @con_length 4 + * @con_sequence false + */ + protected $id; + + /** + * @var string + * + * @con_has_field true + * @con_fieldtype integer + * @con_length 1 + * @con_is_notnull false + */ + protected $hide_title = ''; + + /** + * @var int + * + * @con_has_field true + * @con_fieldtype integer + * @con_length 1 + * @con_is_notnull false + */ + protected $behaviour = 0; + + /** + * Get ID + * + * @return int ID + */ + public function getId() + { + return $this->id; + } + + + /** + * Set ID + * + * @param int $id ID + */ + public function setId($id) + { + $this->id = $id; + } + + /** + * Set hide title + * + * @param bool $a_hide_title hide title + */ + public function setHideTitle($a_hide_title) + { + $this->hide_title = $a_hide_title; + } + + + /** + * Get hide title + * + * @return bool hide title + */ + public function getHideTitle() + { + return $this->hide_title; + } + + /** + * Set behaviour + * + * @param int $a_val behaviour + */ + public function setBehaviour($a_val) + { + $this->behaviour = $a_val; + } + + + /** + * Get behaviour + * + * @return int behaviour + */ + public function getBehaviour() + { + return $this->behaviour; + } } - -?> \ No newline at end of file diff --git a/Modules/ItemGroup/classes/class.ilItemGroupBehaviour.php b/Modules/ItemGroup/classes/class.ilItemGroupBehaviour.php index 069e260bf7d63f7e7b456336dd7a5e3808881e58..255137778d2689a6a991920eca06a0818f292362 100644 --- a/Modules/ItemGroup/classes/class.ilItemGroupBehaviour.php +++ b/Modules/ItemGroup/classes/class.ilItemGroupBehaviour.php @@ -11,29 +11,25 @@ */ class ilItemGroupBehaviour { - const ALWAYS_OPEN = 0; - const EXPANDABLE_CLOSED = 1; - const EXPANDABLE_OPEN = 2; - - /** - * Get all behaviours - * - * @return array - */ - static function getAll() - { - global $DIC; - - $lng = $DIC->language(); - - return array( - self::ALWAYS_OPEN => $lng->txt("itgr_always_open"), - self::EXPANDABLE_CLOSED => $lng->txt("itgr_expandable_closed"), - self::EXPANDABLE_OPEN => $lng->txt("itgr_expandable_open") - ); - - } - + const ALWAYS_OPEN = 0; + const EXPANDABLE_CLOSED = 1; + const EXPANDABLE_OPEN = 2; + + /** + * Get all behaviours + * + * @return array + */ + public static function getAll() + { + global $DIC; + + $lng = $DIC->language(); + + return array( + self::ALWAYS_OPEN => $lng->txt("itgr_always_open"), + self::EXPANDABLE_CLOSED => $lng->txt("itgr_expandable_closed"), + self::EXPANDABLE_OPEN => $lng->txt("itgr_expandable_open") + ); + } } - -?> \ No newline at end of file diff --git a/Modules/ItemGroup/classes/class.ilItemGroupDataSet.php b/Modules/ItemGroup/classes/class.ilItemGroupDataSet.php index dd47257c2a8b91d5e98116564f5112326b9e797f..454773da753a94c5f0db30ee88f73df07a1e756c 100644 --- a/Modules/ItemGroup/classes/class.ilItemGroupDataSet.php +++ b/Modules/ItemGroup/classes/class.ilItemGroupDataSet.php @@ -5,209 +5,189 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); /** * Item group data set class - * + * * @author Alex Killing * @version $Id$ * @ingroup ingroup ModulesItemGroup */ class ilItemGroupDataSet extends ilDataSet -{ - /** - * Get supported versions - * - * @param - * @return - */ - public function getSupportedVersions() - { - return array("4.3.0", "5.3.0"); - } - - /** - * Get xml namespace - * - * @param - * @return - */ - function getXmlNamespace($a_entity, $a_schema_version) - { - return "http://www.ilias.de/xml/Modules/ItemGroup/".$a_entity; - } - - /** - * Get field types for entity - * - * @param - * @return - */ - protected function getTypes($a_entity, $a_version) - { - if ($a_entity == "itgr") - { - switch ($a_version) - { - case "4.3.0": - return array( - "Id" => "integer", - "Title" => "text", - "Description" => "text"); - case "5.3.0": - return array( - "Id" => "integer", - "HideTitle" => "integer", - "Behaviour" => "integer", - "Title" => "text", - "Description" => "text"); - } - } +{ + /** + * Get supported versions + * + * @param + * @return + */ + public function getSupportedVersions() + { + return array("4.3.0", "5.3.0"); + } + + /** + * Get xml namespace + * + * @param + * @return + */ + public function getXmlNamespace($a_entity, $a_schema_version) + { + return "http://www.ilias.de/xml/Modules/ItemGroup/" . $a_entity; + } + + /** + * Get field types for entity + * + * @param + * @return + */ + protected function getTypes($a_entity, $a_version) + { + if ($a_entity == "itgr") { + switch ($a_version) { + case "4.3.0": + return array( + "Id" => "integer", + "Title" => "text", + "Description" => "text"); + case "5.3.0": + return array( + "Id" => "integer", + "HideTitle" => "integer", + "Behaviour" => "integer", + "Title" => "text", + "Description" => "text"); + } + } - if ($a_entity == "itgr_item") - { - switch ($a_version) - { - case "4.3.0": - case "5.3.0": - return array( - "ItemGroupId" => "integer", - "ItemId" => "text" - ); - } - } + if ($a_entity == "itgr_item") { + switch ($a_version) { + case "4.3.0": + case "5.3.0": + return array( + "ItemGroupId" => "integer", + "ItemId" => "text" + ); + } + } + } - } + /** + * Read data + * + * @param + * @return + */ + public function readData($a_entity, $a_version, $a_ids, $a_field = "") + { + $ilDB = $this->db; - /** - * Read data - * - * @param - * @return - */ - 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 == "itgr") { + switch ($a_version) { + case "4.3.0": + $this->getDirectDataFromQuery("SELECT obj_id id, title, description " . + " FROM object_data " . + "WHERE " . + $ilDB->in("obj_id", $a_ids, false, "integer")); + break; + case "5.3.0": + $this->getDirectDataFromQuery("SELECT obj_id id, title, description, hide_title, behaviour " . + " FROM object_data JOIN itgr_data ON (object_data.obj_id = itgr_data.id)" . + "WHERE " . + $ilDB->in("obj_id", $a_ids, false, "integer")); + break; - if (!is_array($a_ids)) - { - $a_ids = array($a_ids); - } - - if ($a_entity == "itgr") - { - switch ($a_version) - { - case "4.3.0": - $this->getDirectDataFromQuery("SELECT obj_id id, title, description ". - " FROM object_data ". - "WHERE ". - $ilDB->in("obj_id", $a_ids, false, "integer")); - break; - case "5.3.0": - $this->getDirectDataFromQuery("SELECT obj_id id, title, description, hide_title, behaviour ". - " FROM object_data JOIN itgr_data ON (object_data.obj_id = itgr_data.id)". - "WHERE ". - $ilDB->in("obj_id", $a_ids, false, "integer")); - break; + } + } - } - } + if ($a_entity == "itgr_item") { + switch ($a_version) { + case "4.3.0": + case "5.3.0": + $this->getDirectDataFromQuery($q = "SELECT item_group_id itgr_id, item_ref_id item_id" . + " FROM item_group_item " . + "WHERE " . + $ilDB->in("item_group_id", $a_ids, false, "integer")); + break; + } + } + } + + /** + * Get xml record (export) + * + * @param array abstract data record + * @return array xml record + */ + public function getXmlRecord($a_entity, $a_version, $a_set) + { + if ($a_entity == "itgr_item") { + // make ref id an object id + $a_set["ItemId"] = ilObject::_lookupObjId($a_set["ItemId"]); + } + return $a_set; + } - if ($a_entity == "itgr_item") - { - switch ($a_version) - { - case "4.3.0": - case "5.3.0": - $this->getDirectDataFromQuery($q = "SELECT item_group_id itgr_id, item_ref_id item_id". - " FROM item_group_item ". - "WHERE ". - $ilDB->in("item_group_id", $a_ids, false, "integer")); - break; - } - } + /** + * Determine the dependent sets of data + */ + protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) + { + switch ($a_entity) { + case "itgr": + return array( + "itgr_item" => array("ids" => $a_rec["Id"]) + ); + } - } - - /** - * Get xml record (export) - * - * @param array abstract data record - * @return array xml record - */ - function getXmlRecord($a_entity, $a_version, $a_set) - { - if ($a_entity == "itgr_item") - { - // make ref id an object id - $a_set["ItemId"] = ilObject::_lookupObjId($a_set["ItemId"]); - } - return $a_set; - } + return false; + } - /** - * Determine the dependent sets of data - */ - protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) - { - switch ($a_entity) - { - case "itgr": - return array ( - "itgr_item" => array("ids" => $a_rec["Id"]) - ); - } + /** + * Import record + * + * @param + * @return + */ + public function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) + { + switch ($a_entity) { + case "itgr": + include_once("./Modules/ItemGroup/classes/class.ilObjItemGroup.php"); + + if ($new_id = $a_mapping->getMapping('Services/Container', 'objs', $a_rec['Id'])) { + $newObj = ilObjectFactory::getInstanceByObjId($new_id, false); + } else { + $newObj = new ilObjItemGroup(); + $newObj->setType("itgr"); + $newObj->create(true); + } + + $newObj->setTitle($a_rec["Title"]); + $newObj->setDescription($a_rec["Description"]); + $newObj->setBehaviour($a_rec["Behaviour"]); + $newObj->setHideTitle($a_rec["HideTitle"]); + $newObj->update(true); + $this->current_obj = $newObj; + $a_mapping->addMapping("Modules/ItemGroup", "itgr", $a_rec["Id"], $newObj->getId()); + + break; + + case "itgr_item": + if ($obj_id = $a_mapping->getMapping('Services/Container', 'objs', $a_rec['ItemId'])) { + $ref_id = current(ilObject::_getAllReferences($obj_id)); + include_once './Modules/ItemGroup/classes/class.ilItemGroupItems.php'; + $itgri = new ilItemGroupItems(); + $itgri->setItemGroupId($this->current_obj->getId()); + $itgri->read(); + $itgri->addItem($ref_id); + $itgri->update(); + } + break; - return false; - } - - /** - * Import record - * - * @param - * @return - */ - function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) - { - - switch ($a_entity) - { - case "itgr": - include_once("./Modules/ItemGroup/classes/class.ilObjItemGroup.php"); - - if ($new_id = $a_mapping->getMapping('Services/Container','objs',$a_rec['Id'])) - { - $newObj = ilObjectFactory::getInstanceByObjId($new_id,false); - } - else - { - $newObj = new ilObjItemGroup(); - $newObj->setType("itgr"); - $newObj->create(true); - } - - $newObj->setTitle($a_rec["Title"]); - $newObj->setDescription($a_rec["Description"]); - $newObj->setBehaviour($a_rec["Behaviour"]); - $newObj->setHideTitle($a_rec["HideTitle"]); - $newObj->update(true); - $this->current_obj = $newObj; - $a_mapping->addMapping("Modules/ItemGroup", "itgr", $a_rec["Id"], $newObj->getId()); - - break; - - case "itgr_item": - if($obj_id = $a_mapping->getMapping('Services/Container','objs',$a_rec['ItemId'])) - { - $ref_id = current(ilObject::_getAllReferences($obj_id)); - include_once './Modules/ItemGroup/classes/class.ilItemGroupItems.php'; - $itgri = new ilItemGroupItems(); - $itgri->setItemGroupId($this->current_obj->getId()); - $itgri->read(); - $itgri->addItem($ref_id); - $itgri->update(); - } - break; - - } - } + } + } } -?> \ No newline at end of file diff --git a/Modules/ItemGroup/classes/class.ilItemGroupExporter.php b/Modules/ItemGroup/classes/class.ilItemGroupExporter.php index d67318fb9ec79f7e09af6438ae82ad79a17457de..c2d12518e62c1579e6755947759ab2124d55366f 100644 --- a/Modules/ItemGroup/classes/class.ilItemGroupExporter.php +++ b/Modules/ItemGroup/classes/class.ilItemGroupExporter.php @@ -12,57 +12,54 @@ include_once("./Services/Export/classes/class.ilXmlExporter.php"); */ class ilItemGroupExporter extends ilXmlExporter { - private $ds; + private $ds; - /** - * Initialisation - */ - function init() - { - include_once("./Modules/ItemGroup/classes/class.ilItemGroupDataSet.php"); - $this->ds = new ilItemGroupDataSet(); - $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); - $this->ds->setDSPrefix("ds"); - } + /** + * Initialisation + */ + public function init() + { + include_once("./Modules/ItemGroup/classes/class.ilItemGroupDataSet.php"); + $this->ds = new ilItemGroupDataSet(); + $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); + $this->ds->setDSPrefix("ds"); + } - /** - * Get xml representation - * - * @param string entity - * @param string target release - * @param string id - * @return string xml string - */ - public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) - { - return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); - } - - /** - * Returns schema versions that the component can export to. - * ILIAS chooses the first one, that has min/max constraints which - * fit to the target release. Please put the newest on top. - * - * @return - */ - function getValidSchemaVersions($a_entity) - { - return array ( - "5.3.0" => array( - "namespace" => "http://www.ilias.de/Modules/ItemGroup/itgr/5_3", - "xsd_file" => "ilias_itgr_5_3.xsd", - "uses_dataset" => true, - "min" => "5.3.0", - "max" => ""), - "4.3.0" => array( - "namespace" => "http://www.ilias.de/Modules/ItemGroup/itgr/4_3", - "xsd_file" => "ilias_itgr_4_3.xsd", - "uses_dataset" => true, - "min" => "4.3.0", - "max" => "") - ); - } + /** + * Get xml representation + * + * @param string entity + * @param string target release + * @param string id + * @return string xml string + */ + public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) + { + return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); + } + /** + * Returns schema versions that the component can export to. + * ILIAS chooses the first one, that has min/max constraints which + * fit to the target release. Please put the newest on top. + * + * @return + */ + public function getValidSchemaVersions($a_entity) + { + return array( + "5.3.0" => array( + "namespace" => "http://www.ilias.de/Modules/ItemGroup/itgr/5_3", + "xsd_file" => "ilias_itgr_5_3.xsd", + "uses_dataset" => true, + "min" => "5.3.0", + "max" => ""), + "4.3.0" => array( + "namespace" => "http://www.ilias.de/Modules/ItemGroup/itgr/4_3", + "xsd_file" => "ilias_itgr_4_3.xsd", + "uses_dataset" => true, + "min" => "4.3.0", + "max" => "") + ); + } } - -?> \ No newline at end of file diff --git a/Modules/ItemGroup/classes/class.ilItemGroupImporter.php b/Modules/ItemGroup/classes/class.ilItemGroupImporter.php index 37f43f8ed099d6d5d983aac79ed0844a0f397234..b7260b5bea88265f154f4338c5b363375c57c8f1 100644 --- a/Modules/ItemGroup/classes/class.ilItemGroupImporter.php +++ b/Modules/ItemGroup/classes/class.ilItemGroupImporter.php @@ -13,29 +13,32 @@ include_once("./Services/Export/classes/class.ilXmlImporter.php"); class ilItemGroupImporter extends ilXmlImporter { - /** - * Initialisation - */ - function init() - { - include_once("./Modules/ItemGroup/classes/class.ilItemGroupDataSet.php"); - $this->ds = new ilItemGroupDataSet(); - $this->ds->setDSPrefix("ds"); - } + /** + * Initialisation + */ + public function init() + { + include_once("./Modules/ItemGroup/classes/class.ilItemGroupDataSet.php"); + $this->ds = new ilItemGroupDataSet(); + $this->ds->setDSPrefix("ds"); + } - /** - * Import XML - * - * @param - * @return - */ - function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) - { - include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); - $parser = new ilDataSetImportParser($a_entity, $this->getSchemaVersion(), - $a_xml, $this->ds, $a_mapping); - } + /** + * Import XML + * + * @param + * @return + */ + public function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) + { + include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); + $parser = new ilDataSetImportParser( + $a_entity, + $this->getSchemaVersion(), + $a_xml, + $this->ds, + $a_mapping + ); + } } - -?> \ No newline at end of file diff --git a/Modules/ItemGroup/classes/class.ilItemGroupItems.php b/Modules/ItemGroup/classes/class.ilItemGroupItems.php index a02d609dcac94b19314797d6e4e92b464d2d882c..02c8db4dda7e28c95fd137ce3c62edd20ba9424e 100644 --- a/Modules/ItemGroup/classes/class.ilItemGroupItems.php +++ b/Modules/ItemGroup/classes/class.ilItemGroupItems.php @@ -8,327 +8,309 @@ * This class is used to store the materials (items) that are assigned * to an item group. Main table used is item_group_item * - * @author Alex Killing + * @author Alex Killing * @version $Id$ - * + * */ class ilItemGroupItems { - /** - * @var ilDB - */ - protected $db; - - /** - * @var ilObjectDefinition - */ - protected $obj_def; + /** + * @var ilDB + */ + protected $db; - /** - * @var ilObjectDataCache - */ - protected $obj_data_cache; + /** + * @var ilObjectDefinition + */ + protected $obj_def; - /** - * @var Logger - */ - protected $log; + /** + * @var ilObjectDataCache + */ + protected $obj_data_cache; - var $ilDB; - var $tree; - var $lng; + /** + * @var Logger + */ + protected $log; - var $item_group_id = 0; - var $item_group_ref_id = 0; - var $items = array(); + public $ilDB; + public $tree; + public $lng; - /** - * Constructor - * - * @param int $a_item_group_ref_id ref id of item group - */ - function __construct($a_item_group_ref_id = 0) - { - global $DIC; + public $item_group_id = 0; + public $item_group_ref_id = 0; + public $items = array(); - $this->obj_data_cache = $DIC["ilObjDataCache"]; - $this->log = $DIC["ilLog"]; - $ilDB = $DIC->database(); - $lng = $DIC->language(); - $tree = $DIC->repositoryTree(); - $objDefinition = $DIC["objDefinition"]; + /** + * Constructor + * + * @param int $a_item_group_ref_id ref id of item group + */ + public function __construct($a_item_group_ref_id = 0) + { + global $DIC; - $this->db = $ilDB; - $this->lng = $lng; - $this->tree = $tree; - $this->obj_def = $objDefinition; + $this->obj_data_cache = $DIC["ilObjDataCache"]; + $this->log = $DIC["ilLog"]; + $ilDB = $DIC->database(); + $lng = $DIC->language(); + $tree = $DIC->repositoryTree(); + $objDefinition = $DIC["objDefinition"]; - $this->setItemGroupRefId((int) $a_item_group_ref_id); - if ($this->getItemGroupRefId() > 0) - { - $this->setItemGroupId((int) ilObject::_lookupObjId($a_item_group_ref_id)); - } + $this->db = $ilDB; + $this->lng = $lng; + $this->tree = $tree; + $this->obj_def = $objDefinition; - if ($this->getItemGroupId() > 0) - { - $this->read(); - } - } + $this->setItemGroupRefId((int) $a_item_group_ref_id); + if ($this->getItemGroupRefId() > 0) { + $this->setItemGroupId((int) ilObject::_lookupObjId($a_item_group_ref_id)); + } - /** - * Set item group id - * - * @param int $a_val item group id - */ - function setItemGroupId($a_val) - { - $this->item_group_id = $a_val; - } - - /** - * Get item group id - * - * @return int item group id - */ - function getItemGroupId() - { - return $this->item_group_id; - } - - /** - * Set item group ref id - * - * @param int $a_val item group ref id - */ - function setItemGroupRefId($a_val) - { - $this->item_group_ref_id = $a_val; - } - - /** - * Get item group ref id - * - * @return int item group ref id - */ - function getItemGroupRefId() - { - return $this->item_group_ref_id; - } - - /** - * Set items - * - * @param array $a_val items (array of ref ids) - */ - function setItems($a_val) - { - $this->items = $a_val; - } - - /** - * Get items - * - * @return array items (array of ref ids) - */ - function getItems() - { - return $this->items; - } - - /** - * Add one item - * - * @param int $a_item_ref_id item ref id - */ - public function addItem($a_item_ref_id) - { - if (!in_array($a_item_ref_id, $this->items)) - { - $this->items[] = (int) $a_item_ref_id; - } - } - - /** - * Delete items of item group - */ - function delete() - { - $query = "DELETE FROM item_group_item ". - "WHERE item_group_id = ".$this->db->quote($this->getItemGroupId(), 'integer'); - $this->db->manipulate($query); - } + if ($this->getItemGroupId() > 0) { + $this->read(); + } + } - /** - * Update item group items - */ - function update() - { - $this->delete(); - - foreach($this->items as $item) - { - $query = "INSERT INTO item_group_item (item_group_id,item_ref_id) ". - "VALUES( ". - $this->db->quote($this->getItemGroupId() ,'integer').", ". - $this->db->quote($item ,'integer')." ". - ")"; - $this->db->manipulate($query); - } - } + /** + * Set item group id + * + * @param int $a_val item group id + */ + public function setItemGroupId($a_val) + { + $this->item_group_id = $a_val; + } + + /** + * Get item group id + * + * @return int item group id + */ + public function getItemGroupId() + { + return $this->item_group_id; + } + + /** + * Set item group ref id + * + * @param int $a_val item group ref id + */ + public function setItemGroupRefId($a_val) + { + $this->item_group_ref_id = $a_val; + } + + /** + * Get item group ref id + * + * @return int item group ref id + */ + public function getItemGroupRefId() + { + return $this->item_group_ref_id; + } + + /** + * Set items + * + * @param array $a_val items (array of ref ids) + */ + public function setItems($a_val) + { + $this->items = $a_val; + } + + /** + * Get items + * + * @return array items (array of ref ids) + */ + public function getItems() + { + return $this->items; + } + + /** + * Add one item + * + * @param int $a_item_ref_id item ref id + */ + public function addItem($a_item_ref_id) + { + if (!in_array($a_item_ref_id, $this->items)) { + $this->items[] = (int) $a_item_ref_id; + } + } + + /** + * Delete items of item group + */ + public function delete() + { + $query = "DELETE FROM item_group_item " . + "WHERE item_group_id = " . $this->db->quote($this->getItemGroupId(), 'integer'); + $this->db->manipulate($query); + } - /** - * Read item group items - */ - public function read() - { - $this->items = array(); - $set = $this->db->query("SELECT * FROM item_group_item ". - " WHERE item_group_id = ".$this->db->quote($this->getItemGroupId(), "integer") - ); - while ($rec = $this->db->fetchAssoc($set)) - { - $this->items[] = $rec["item_ref_id"]; - } - } + /** + * Update item group items + */ + public function update() + { + $this->delete(); + + foreach ($this->items as $item) { + $query = "INSERT INTO item_group_item (item_group_id,item_ref_id) " . + "VALUES( " . + $this->db->quote($this->getItemGroupId(), 'integer') . ", " . + $this->db->quote($item, 'integer') . " " . + ")"; + $this->db->manipulate($query); + } + } - /** - * Get assignable items - * - * @param - * @return - */ - function getAssignableItems() - { - $objDefinition = $this->obj_def; - - if ($this->getItemGroupRefId() <= 0) - { - return array(); - } - - $parent_node = $this->tree->getNodeData( - $this->tree->getParentId($this->getItemGroupRefId())); - - $materials = array(); - $nodes = $this->tree->getChilds($parent_node["child"]); + /** + * Read item group items + */ + public function read() + { + $this->items = array(); + $set = $this->db->query( + "SELECT * FROM item_group_item " . + " WHERE item_group_id = " . $this->db->quote($this->getItemGroupId(), "integer") + ); + while ($rec = $this->db->fetchAssoc($set)) { + $this->items[] = $rec["item_ref_id"]; + } + } - include_once("./Modules/File/classes/class.ilObjFileAccess.php"); - foreach($nodes as $node) - { - // filter side blocks and session, item groups and role folder - if ($node['child'] == $parent_node["child"] || - $this->obj_def->isSideBlock($node['type']) || - in_array($node['type'], array('sess', 'itgr', 'rolf', 'adm'))) - { - continue; - } - - // filter hidden files - // see http://www.ilias.de/mantis/view.php?id=10269 - if ($node['type'] == "file" && - ilObjFileAccess::_isFileHidden($node['title'])) - { - continue; - } - - if ($objDefinition->isInactivePlugin($node['type'])) - { - continue; - } + /** + * Get assignable items + * + * @param + * @return + */ + public function getAssignableItems() + { + $objDefinition = $this->obj_def; + + if ($this->getItemGroupRefId() <= 0) { + return array(); + } + + $parent_node = $this->tree->getNodeData( + $this->tree->getParentId($this->getItemGroupRefId()) + ); + + $materials = array(); + $nodes = $this->tree->getChilds($parent_node["child"]); - $materials[] = $node; - } - - $materials = ilUtil::sortArray($materials, "title", "asc"); - - return $materials; - } + include_once("./Modules/File/classes/class.ilObjFileAccess.php"); + foreach ($nodes as $node) { + // filter side blocks and session, item groups and role folder + if ($node['child'] == $parent_node["child"] || + $this->obj_def->isSideBlock($node['type']) || + in_array($node['type'], array('sess', 'itgr', 'rolf', 'adm'))) { + continue; + } + + // filter hidden files + // see http://www.ilias.de/mantis/view.php?id=10269 + if ($node['type'] == "file" && + ilObjFileAccess::_isFileHidden($node['title'])) { + continue; + } + + if ($objDefinition->isInactivePlugin($node['type'])) { + continue; + } - - /** - * Get valid items - * - * @param - * @return - */ - function getValidItems() - { - $items = $this->getItems(); - $ass_items = $this->getAssignableItems(); - $valid_items = array(); - foreach ($ass_items as $aitem) - { - if (in_array($aitem["ref_id"], $items)) - { - $valid_items[] = $aitem["ref_id"]; - } - } - return $valid_items; - } + $materials[] = $node; + } + + $materials = ilUtil::sortArray($materials, "title", "asc"); + + return $materials; + } - /** - * Clone items - * - * @access public - * - * @param int source event id - * @param int copy id - */ - public function cloneItems($a_source_id,$a_copy_id) - { - $ilObjDataCache = $this->obj_data_cache; - $ilLog = $this->log; - - $ilLog->write(__METHOD__.': Begin cloning item group materials ... -'.$a_source_id.'-'); - - include_once('Services/CopyWizard/classes/class.ilCopyWizardOptions.php'); - $cwo = ilCopyWizardOptions::_getInstance($a_copy_id); - $mappings = $cwo->getMappings(); - - $new_items = array(); -// check: is this a ref id!? - $source_ig = new ilItemGroupItems($a_source_id); - foreach($source_ig->getItems() as $item_ref_id) - { - if(isset($mappings[$item_ref_id]) and $mappings[$item_ref_id]) - { - $ilLog->write(__METHOD__.': Clone item group item nr. '.$item_ref_id); - $new_items[] = $mappings[$item_ref_id]; - } - else - { - $ilLog->write(__METHOD__.': No mapping found for item group item nr. '.$item_ref_id); - } - } - $this->setItems($new_items); - $this->update(); - $ilLog->write(__METHOD__.': Finished cloning item group items ...'); - return true; - } - - static function _getItemsOfContainer($a_ref_id) - { - global $DIC; + + /** + * Get valid items + * + * @param + * @return + */ + public function getValidItems() + { + $items = $this->getItems(); + $ass_items = $this->getAssignableItems(); + $valid_items = array(); + foreach ($ass_items as $aitem) { + if (in_array($aitem["ref_id"], $items)) { + $valid_items[] = $aitem["ref_id"]; + } + } + return $valid_items; + } - $ilDB = $DIC->database(); - $tree = $DIC->repositoryTree(); - - $itgr_nodes = $tree->getChildsByType($a_ref_id,'itgr'); - foreach ($itgr_nodes as $node) - { - $itgr_ids[] = $node['obj_id']; - } - $query = "SELECT item_ref_id FROM item_group_item ". - "WHERE ".$ilDB->in('item_group_id', $itgr_ids,false,'integer'); - + /** + * Clone items + * + * @access public + * + * @param int source event id + * @param int copy id + */ + public function cloneItems($a_source_id, $a_copy_id) + { + $ilObjDataCache = $this->obj_data_cache; + $ilLog = $this->log; + + $ilLog->write(__METHOD__ . ': Begin cloning item group materials ... -' . $a_source_id . '-'); + + include_once('Services/CopyWizard/classes/class.ilCopyWizardOptions.php'); + $cwo = ilCopyWizardOptions::_getInstance($a_copy_id); + $mappings = $cwo->getMappings(); + + $new_items = array(); + // check: is this a ref id!? + $source_ig = new ilItemGroupItems($a_source_id); + foreach ($source_ig->getItems() as $item_ref_id) { + if (isset($mappings[$item_ref_id]) and $mappings[$item_ref_id]) { + $ilLog->write(__METHOD__ . ': Clone item group item nr. ' . $item_ref_id); + $new_items[] = $mappings[$item_ref_id]; + } else { + $ilLog->write(__METHOD__ . ': No mapping found for item group item nr. ' . $item_ref_id); + } + } + $this->setItems($new_items); + $this->update(); + $ilLog->write(__METHOD__ . ': Finished cloning item group items ...'); + return true; + } + + public static function _getItemsOfContainer($a_ref_id) + { + global $DIC; - $res = $ilDB->query($query); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - $items[] = $row->item_ref_id; - } - return $items ? $items : array(); - } + $ilDB = $DIC->database(); + $tree = $DIC->repositoryTree(); + + $itgr_nodes = $tree->getChildsByType($a_ref_id, 'itgr'); + foreach ($itgr_nodes as $node) { + $itgr_ids[] = $node['obj_id']; + } + $query = "SELECT item_ref_id FROM item_group_item " . + "WHERE " . $ilDB->in('item_group_id', $itgr_ids, false, 'integer'); + + $res = $ilDB->query($query); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + $items[] = $row->item_ref_id; + } + return $items ? $items : array(); + } } -?> \ No newline at end of file diff --git a/Modules/ItemGroup/classes/class.ilItemGroupItemsTableGUI.php b/Modules/ItemGroup/classes/class.ilItemGroupItemsTableGUI.php index b72baa1f0d23fbcc433bf96b78e39dee3358ec0f..335dd5696c544954ada40e83e2e81c7afc7cc9eb 100644 --- a/Modules/ItemGroup/classes/class.ilItemGroupItemsTableGUI.php +++ b/Modules/ItemGroup/classes/class.ilItemGroupItemsTableGUI.php @@ -14,99 +14,102 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilItemGroupItemsTableGUI extends ilTable2GUI { - /** - * @var ilTree - */ - protected $tree; + /** + * @var ilTree + */ + protected $tree; - /** - * @var ilObjectDefinition - */ - protected $obj_def; + /** + * @var ilObjectDefinition + */ + protected $obj_def; - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd) + { + global $DIC; - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $tree = $DIC->repositoryTree(); - $objDefinition = $DIC["objDefinition"]; - - $this->lng = $lng; - $this->ctrl = $ilCtrl; - $this->tree = $tree; - $this->obj_def = $objDefinition; - - include_once 'Modules/ItemGroup/classes/class.ilItemGroupItems.php'; - $this->item_group_items = new ilItemGroupItems($a_parent_obj->object->getRefId()); - $this->items = $this->item_group_items->getItems(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setLimit(9999); - - $this->getMaterials(); - $this->setTitle($lng->txt("itgr_assigned_materials")); - - $this->addColumn("", "", "1px", true); - $this->addColumn($this->lng->txt("itgr_item")); - $this->addColumn($this->lng->txt("itgr_assignment")); - $this->setSelectAllCheckbox("items[]"); - - $this->setFormAction($this->ctrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.item_group_items_row.html", "Modules/ItemGroup"); + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $tree = $DIC->repositoryTree(); + $objDefinition = $DIC["objDefinition"]; + + $this->lng = $lng; + $this->ctrl = $ilCtrl; + $this->tree = $tree; + $this->obj_def = $objDefinition; + + include_once 'Modules/ItemGroup/classes/class.ilItemGroupItems.php'; + $this->item_group_items = new ilItemGroupItems($a_parent_obj->object->getRefId()); + $this->items = $this->item_group_items->getItems(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setLimit(9999); + + $this->getMaterials(); + $this->setTitle($lng->txt("itgr_assigned_materials")); + + $this->addColumn("", "", "1px", true); + $this->addColumn($this->lng->txt("itgr_item")); + $this->addColumn($this->lng->txt("itgr_assignment")); + $this->setSelectAllCheckbox("items[]"); + + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.item_group_items_row.html", "Modules/ItemGroup"); - $this->addCommandButton("saveItemAssignment", $lng->txt("save")); - } - - /** - * Get materials - * - * @param - * @return - */ - function getMaterials() - { - $materials = array(); - $items = $this->item_group_items->getAssignableItems(); - - foreach($items as $item) - { - $item["sorthash"] = (int)(!in_array($item['ref_id'], $this->items)).$item["title"]; - $materials[] = $item; - } - - $materials = ilUtil::sortArray($materials, "sorthash", "asc"); - $this->setData($materials); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - - $this->tpl->setVariable("ITEM_REF_ID", $a_set["child"]); - $this->tpl->setVariable("TITLE", $a_set["title"]); - $this->tpl->setVariable("IMG", ilUtil::img( - ilObject::_getIcon($a_set["obj_id"], "tiny"), "", "", "", "", "", "ilIcon")); - - if (in_array($a_set["child"], $this->items)) - { - $this->tpl->setVariable("IMG_ASSIGNED", ilUtil::img( - ilUtil::getImagePath("icon_ok.svg"))); - $this->tpl->setVariable("CHECKED", "checked='checked'"); - } - else - { - $this->tpl->setVariable("IMG_ASSIGNED", ilUtil::img( - ilUtil::getImagePath("icon_not_ok.svg"))); - } - } + $this->addCommandButton("saveItemAssignment", $lng->txt("save")); + } + + /** + * Get materials + * + * @param + * @return + */ + public function getMaterials() + { + $materials = array(); + $items = $this->item_group_items->getAssignableItems(); + + foreach ($items as $item) { + $item["sorthash"] = (int) (!in_array($item['ref_id'], $this->items)) . $item["title"]; + $materials[] = $item; + } + + $materials = ilUtil::sortArray($materials, "sorthash", "asc"); + $this->setData($materials); + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $this->tpl->setVariable("ITEM_REF_ID", $a_set["child"]); + $this->tpl->setVariable("TITLE", $a_set["title"]); + $this->tpl->setVariable("IMG", ilUtil::img( + ilObject::_getIcon($a_set["obj_id"], "tiny"), + "", + "", + "", + "", + "", + "ilIcon" + )); + + if (in_array($a_set["child"], $this->items)) { + $this->tpl->setVariable("IMG_ASSIGNED", ilUtil::img( + ilUtil::getImagePath("icon_ok.svg") + )); + $this->tpl->setVariable("CHECKED", "checked='checked'"); + } else { + $this->tpl->setVariable("IMG_ASSIGNED", ilUtil::img( + ilUtil::getImagePath("icon_not_ok.svg") + )); + } + } } -?> diff --git a/Modules/ItemGroup/classes/class.ilObjItemGroup.php b/Modules/ItemGroup/classes/class.ilObjItemGroup.php index d24f8fd747e77e5cdbdbde80bcefe71782c0368d..efad62c543f60dc3fdd27752a53c1ecee97ba382 100644 --- a/Modules/ItemGroup/classes/class.ilObjItemGroup.php +++ b/Modules/ItemGroup/classes/class.ilObjItemGroup.php @@ -18,257 +18,250 @@ include_once("./Modules/ItemGroup/classes/class.ilItemGroupAR.php"); */ class ilObjItemGroup extends ilObject2 { - /** - * @var ilObjectDefinition - */ - protected $obj_def; + /** + * @var ilObjectDefinition + */ + protected $obj_def; - protected $access_type; // [int] - protected $access_begin; // [timestamp] - protected $access_end; // [timestamp] - protected $access_visibility; // [bool] - protected $item_data_ar = null; // active record - - /** - * Constructor - * - * @param int $a_id id - * @param bool $a_reference ref id? - * @return - */ - function __construct($a_id = 0, $a_reference = true) - { - global $DIC; + protected $access_type; // [int] + protected $access_begin; // [timestamp] + protected $access_end; // [timestamp] + protected $access_visibility; // [bool] + protected $item_data_ar = null; // active record + + /** + * Constructor + * + * @param int $a_id id + * @param bool $a_reference ref id? + * @return + */ + public function __construct($a_id = 0, $a_reference = true) + { + global $DIC; - $this->log = $DIC["ilLog"]; - $tree = $DIC->repositoryTree(); - $objDefinition = $DIC["objDefinition"]; - $ilDB = $DIC->database(); - - $this->tree = $tree; - $this->obj_def = $objDefinition; - $this->db = $ilDB; + $this->log = $DIC["ilLog"]; + $tree = $DIC->repositoryTree(); + $objDefinition = $DIC["objDefinition"]; + $ilDB = $DIC->database(); + + $this->tree = $tree; + $this->obj_def = $objDefinition; + $this->db = $ilDB; - $this->item_data_ar = new ilItemGroupAR(); + $this->item_data_ar = new ilItemGroupAR(); - parent::__construct($a_id, $a_reference); - } + parent::__construct($a_id, $a_reference); + } - /** - * Set ID - * - * @param int $a_val ID - */ - function setId($a_val) - { - parent::setId($a_val); - $this->item_data_ar->setId($a_val); - } + /** + * Set ID + * + * @param int $a_val ID + */ + public function setId($a_val) + { + parent::setId($a_val); + $this->item_data_ar->setId($a_val); + } - /** - * Init type - */ - function initType() - { - $this->type = "itgr"; - } + /** + * Init type + */ + public function initType() + { + $this->type = "itgr"; + } - /** - * Set hide title - * - * @param bool $a_val hide title - */ - function setHideTitle($a_val) - { - $this->item_data_ar->setHideTitle($a_val); - } + /** + * Set hide title + * + * @param bool $a_val hide title + */ + public function setHideTitle($a_val) + { + $this->item_data_ar->setHideTitle($a_val); + } - /** - * Get hide title - * - * @return bool hide title - */ - function getHideTitle() - { - return $this->item_data_ar->getHideTitle(); - } + /** + * Get hide title + * + * @return bool hide title + */ + public function getHideTitle() + { + return $this->item_data_ar->getHideTitle(); + } - /** - * Set behaviour (see ilItemGroupBehaviour) - * - * @param int $a_val behaviour - */ - function setBehaviour($a_val) - { - $this->item_data_ar->setBehaviour($a_val); - } + /** + * Set behaviour (see ilItemGroupBehaviour) + * + * @param int $a_val behaviour + */ + public function setBehaviour($a_val) + { + $this->item_data_ar->setBehaviour($a_val); + } - /** - * Get hide title - * - * @return int behaviour - */ - function getBehaviour() - { - return $this->item_data_ar->getBehaviour(); - } + /** + * Get hide title + * + * @return int behaviour + */ + public function getBehaviour() + { + return $this->item_data_ar->getBehaviour(); + } - /** - * Read - */ - protected function doRead() - { - $this->item_data_ar = new ilItemGroupAR($this->getId()); - } + /** + * Read + */ + protected function doRead() + { + $this->item_data_ar = new ilItemGroupAR($this->getId()); + } - /** - * Creation - */ - protected function doCreate() - { - if($this->getId()) - { - $this->item_data_ar->setId($this->getId()); - $this->item_data_ar->create(); - } - } - - /** - * Update - */ - protected function doUpdate() - { - if($this->getId()) - { - $this->item_data_ar->update(); - } - } + /** + * Creation + */ + protected function doCreate() + { + if ($this->getId()) { + $this->item_data_ar->setId($this->getId()); + $this->item_data_ar->create(); + } + } + + /** + * Update + */ + protected function doUpdate() + { + if ($this->getId()) { + $this->item_data_ar->update(); + } + } - /** - * Deletion - */ - protected function doDelete() - { - if($this->getId()) - { - $this->item_data_ar->delete(); - } - } - - /** - * Clone obj item group - * @param ilObjItemGroup $new_obj - * @param int $a_target_id - * @param string $a_copy_id - * @param bool $a_omit_tree - */ - protected function doCloneObject($new_obj, $a_target_id, $a_copy_id = null, $a_omit_tree = false) - { - $new_obj->setHideTitle($this->getHideTitle()); - $new_obj->setBehaviour($this->getBehaviour()); - $new_obj->update(); - } + /** + * Deletion + */ + protected function doDelete() + { + if ($this->getId()) { + $this->item_data_ar->delete(); + } + } + + /** + * Clone obj item group + * @param ilObjItemGroup $new_obj + * @param int $a_target_id + * @param string $a_copy_id + * @param bool $a_omit_tree + */ + protected function doCloneObject($new_obj, $a_target_id, $a_copy_id = null, $a_omit_tree = false) + { + $new_obj->setHideTitle($this->getHideTitle()); + $new_obj->setBehaviour($this->getBehaviour()); + $new_obj->update(); + } - /** - * Clone dependencies - * - * @param - * @return - */ - function cloneDependencies($a_target_id,$a_copy_id) - { - $ilLog = $this->log; - - $ilLog->write(__METHOD__.': Cloning item group dependencies -'.$a_source_id.'-'); - - parent::cloneDependencies($a_target_id,$a_copy_id); + /** + * Clone dependencies + * + * @param + * @return + */ + public function cloneDependencies($a_target_id, $a_copy_id) + { + $ilLog = $this->log; + + $ilLog->write(__METHOD__ . ': Cloning item group dependencies -' . $a_source_id . '-'); + + parent::cloneDependencies($a_target_id, $a_copy_id); - include_once('./Modules/ItemGroup/classes/class.ilItemGroupItems.php'); - $ig_items = new ilItemGroupItems($a_target_id); - $ig_items->cloneItems($this->getRefId(), $a_copy_id); + include_once('./Modules/ItemGroup/classes/class.ilItemGroupItems.php'); + $ig_items = new ilItemGroupItems($a_target_id); + $ig_items->cloneItems($this->getRefId(), $a_copy_id); - return true; - } + return true; + } - /** - * Fix container item group references after a container has been cloned - * - * @param - * @return - */ - static function fixContainerItemGroupRefsAfterCloning($a_source_container, $a_copy_id) - { - global $DIC; + /** + * Fix container item group references after a container has been cloned + * + * @param + * @return + */ + public static function fixContainerItemGroupRefsAfterCloning($a_source_container, $a_copy_id) + { + global $DIC; - $ilLog = $DIC["ilLog"]; - - $ilLog->write(__METHOD__.': Fix item group references in '.$a_source_container->getType()); - - include_once('Services/CopyWizard/classes/class.ilCopyWizardOptions.php'); - $cwo = ilCopyWizardOptions::_getInstance($a_copy_id); - $mappings = $cwo->getMappings(); - - $new_container_ref_id = $mappings[$a_source_container->getRefId()]; - $ilLog->write(__METHOD__.': 2-'.$new_container_ref_id.'-'); - $new_container_obj_id = ilObject::_lookupObjId($new_container_ref_id); - - include_once("./Services/COPage/classes/class.ilPageObject.php"); - include_once("./Services/Container/classes/class.ilContainerPage.php"); - $ilLog->write(__METHOD__.': 3'.$new_container_obj_id.'-'); - if (ilPageObject::_exists("cont", $new_container_obj_id)) - { - $ilLog->write(__METHOD__.': 4'); - $new_page = new ilContainerPage($new_container_obj_id); - $new_page->buildDom(); - include_once("./Services/COPage/classes/class.ilPCResources.php"); - ilPCResources::modifyItemGroupRefIdsByMapping($new_page, $mappings); - $new_page->update(); - } - $ilLog->write(__METHOD__.': 5'); - } + $ilLog = $DIC["ilLog"]; + + $ilLog->write(__METHOD__ . ': Fix item group references in ' . $a_source_container->getType()); + + include_once('Services/CopyWizard/classes/class.ilCopyWizardOptions.php'); + $cwo = ilCopyWizardOptions::_getInstance($a_copy_id); + $mappings = $cwo->getMappings(); + + $new_container_ref_id = $mappings[$a_source_container->getRefId()]; + $ilLog->write(__METHOD__ . ': 2-' . $new_container_ref_id . '-'); + $new_container_obj_id = ilObject::_lookupObjId($new_container_ref_id); + + include_once("./Services/COPage/classes/class.ilPageObject.php"); + include_once("./Services/Container/classes/class.ilContainerPage.php"); + $ilLog->write(__METHOD__ . ': 3' . $new_container_obj_id . '-'); + if (ilPageObject::_exists("cont", $new_container_obj_id)) { + $ilLog->write(__METHOD__ . ': 4'); + $new_page = new ilContainerPage($new_container_obj_id); + $new_page->buildDom(); + include_once("./Services/COPage/classes/class.ilPCResources.php"); + ilPCResources::modifyItemGroupRefIdsByMapping($new_page, $mappings); + $new_page->update(); + } + $ilLog->write(__METHOD__ . ': 5'); + } - /** - * Lookup hide title - * - * @param int $a_id ID - * @return bool - */ - static function lookupHideTitle($a_id) - { - return self::lookup($a_id, "hide_title"); - } + /** + * Lookup hide title + * + * @param int $a_id ID + * @return bool + */ + public static function lookupHideTitle($a_id) + { + return self::lookup($a_id, "hide_title"); + } - /** - * Lookup behaviour - * - * @param int $a_id ID - * @return int - */ - static function lookupBehaviour($a_id) - { - return self::lookup($a_id, "behaviour"); - } + /** + * Lookup behaviour + * + * @param int $a_id ID + * @return int + */ + public static function lookupBehaviour($a_id) + { + return self::lookup($a_id, "behaviour"); + } - /** - * Lookup hide title - * - * @param int $a_id ID - * @return bool - */ - protected static function lookup($a_id, $a_key) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT ".$a_key." FROM itgr_data ". - " WHERE id = ".$ilDB->quote($a_id, "integer") - ); - $rec = $ilDB->fetchAssoc($set); - return $rec[$a_key]; - } + /** + * Lookup hide title + * + * @param int $a_id ID + * @return bool + */ + protected static function lookup($a_id, $a_key) + { + global $DIC; + $ilDB = $DIC->database(); + $set = $ilDB->query( + "SELECT " . $a_key . " FROM itgr_data " . + " WHERE id = " . $ilDB->quote($a_id, "integer") + ); + $rec = $ilDB->fetchAssoc($set); + return $rec[$a_key]; + } } - -?> \ No newline at end of file diff --git a/Modules/ItemGroup/classes/class.ilObjItemGroupAccess.php b/Modules/ItemGroup/classes/class.ilObjItemGroupAccess.php index 0379c3d028bd2c61f97331039b9228199e047bae..02ab5d1ebcac1f760d75648a60f2c9a0375b144c 100644 --- a/Modules/ItemGroup/classes/class.ilObjItemGroupAccess.php +++ b/Modules/ItemGroup/classes/class.ilObjItemGroupAccess.php @@ -14,106 +14,101 @@ include_once './Services/Object/classes/class.ilObjectAccess.php'; */ class ilObjItemGroupAccess extends ilObjectAccess { - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilRbacSystem - */ - protected $rbacsystem; + /** + * @var ilRbacSystem + */ + protected $rbacsystem; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * Constructor - */ - function __construct() - { - global $DIC; + /** + * Constructor + */ + public function __construct() + { + global $DIC; - $this->user = $DIC->user(); - $this->lng = $DIC->language(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->access = $DIC->access(); - } + $this->user = $DIC->user(); + $this->lng = $DIC->language(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->access = $DIC->access(); + } - /** - * get list of command/permission combinations - * - * @access public - * @return array - * @static - */ - public static function _getCommands() - { - $commands = array - ( - array("permission" => "read", "cmd" => "gotoParent", "lang_var" => "", "default" => true), - array("permission" => "write", "cmd" => "listMaterials", "lang_var" => "edit_content", "default" => false), - array("permission" => "write", "cmd" => "edit", "lang_var" => "settings", "default" => false) - ); - - return $commands; - } + /** + * get list of command/permission combinations + * + * @access public + * @return array + * @static + */ + public static function _getCommands() + { + $commands = array( + array("permission" => "read", "cmd" => "gotoParent", "lang_var" => "", "default" => true), + array("permission" => "write", "cmd" => "listMaterials", "lang_var" => "edit_content", "default" => false), + array("permission" => "write", "cmd" => "edit", "lang_var" => "settings", "default" => false) + ); + + return $commands; + } - /** - * checks wether a user may invoke a command or not + /** + * checks wether a user may invoke a command or not * (this method is called by ilAccessHandler::checkAccess) - * - * @param string $a_cmd command (not permission!) - * @param string $a_permission permission - * @param int $a_ref_id reference id - * @param int $a_obj_id object id - * @param int $a_user_id user id (if not provided, current user is taken) - * - * @return boolean true, if everything is ok - */ - public function _checkAccess($a_cmd, $a_permission, $a_ref_id, $a_obj_id, $a_user_id = "") - { - $ilUser = $this->user; - $lng = $this->lng; - $rbacsystem = $this->rbacsystem; - $ilAccess = $this->access; - - $a_user_id = $a_user_id ? $a_user_id : $ilUser->getId(); - return true; - } - - - /** - * check whether goto script will succeed - */ - public static function _checkGoto($a_target) - { - global $DIC; + * + * @param string $a_cmd command (not permission!) + * @param string $a_permission permission + * @param int $a_ref_id reference id + * @param int $a_obj_id object id + * @param int $a_user_id user id (if not provided, current user is taken) + * + * @return boolean true, if everything is ok + */ + public function _checkAccess($a_cmd, $a_permission, $a_ref_id, $a_obj_id, $a_user_id = "") + { + $ilUser = $this->user; + $lng = $this->lng; + $rbacsystem = $this->rbacsystem; + $ilAccess = $this->access; + + $a_user_id = $a_user_id ? $a_user_id : $ilUser->getId(); + return true; + } + + + /** + * check whether goto script will succeed + */ + public static function _checkGoto($a_target) + { + global $DIC; - $ilAccess = $DIC->access(); - - $t_arr = explode("_", $a_target); + $ilAccess = $DIC->access(); + + $t_arr = explode("_", $a_target); - if ($t_arr[0] != "itgr" || ((int) $t_arr[1]) <= 0) - { - return false; - } + if ($t_arr[0] != "itgr" || ((int) $t_arr[1]) <= 0) { + return false; + } - if($ilAccess->checkAccess("read", "", $t_arr[1])) - { - return true; - } - return false; - } - + if ($ilAccess->checkAccess("read", "", $t_arr[1])) { + return true; + } + return false; + } } -?> \ No newline at end of file diff --git a/Modules/ItemGroup/classes/class.ilObjItemGroupGUI.php b/Modules/ItemGroup/classes/class.ilObjItemGroupGUI.php index 650be2fd671ff43558cf35c4177f81ecb04fcd18..7506ee58e20b7e4b3d1dd00ef97fe8e4d18481a7 100755 --- a/Modules/ItemGroup/classes/class.ilObjItemGroupGUI.php +++ b/Modules/ItemGroup/classes/class.ilObjItemGroupGUI.php @@ -19,389 +19,386 @@ include_once("./Modules/ItemGroup/classes/class.ilObjItemGroup.php"); */ class ilObjItemGroupGUI extends ilObject2GUI { - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilHelpGUI - */ - protected $help; - - /** - * @var ilErrorHandling - */ - protected $error; - - - /** - * Constructor - */ - function __construct($a_id = 0, $a_id_type = self::REPOSITORY_NODE_ID, $a_parent_node_id = 0) - { - global $DIC; - parent::__construct($a_id, $a_id_type, $a_parent_node_id); - - $this->lng = $DIC->language(); - $this->tabs = $DIC->tabs(); - $this->access = $DIC->access(); - $this->tpl = $DIC["tpl"]; - $this->ctrl = $DIC->ctrl(); - $this->locator = $DIC["ilLocator"]; - $this->tree = $DIC->repositoryTree(); - $this->help = $DIC["ilHelp"]; - $this->error = $DIC["ilErr"]; - } - - /** - * Initialisation - */ - protected function afterConstructor() - { - $lng = $this->lng; - - $lng->loadLanguageModule("itgr"); - - $this->ctrl->saveParameter($this, array("ref_id")); - } - - /** - * Get type - */ - final function getType() - { - return "itgr"; - } - - /** - * execute command - */ - function executeCommand() - { - $ilTabs = $this->tabs; - $lng = $this->lng; - $ilAccess = $this->access; - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $ilLocator = $this->locator; - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - switch($next_class) - { - case 'ilinfoscreengui': - $this->prepareOutput(); - $this->addHeaderAction(); - $this->infoScreen(); - break; - - case 'ilpermissiongui': - $this->prepareOutput(); - $ilTabs->activateTab("perm_settings"); - $this->addHeaderAction(); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $ret = $this->ctrl->forwardCommand($perm_gui); - break; - - case "ilcommonactiondispatchergui": - include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); - $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); - $this->ctrl->forwardCommand($gui); - break; - - default: - $cmd = $this->ctrl->getCmd("listMaterials"); - $this->prepareOutput(); - $this->addHeaderAction(); - $this->$cmd(); - break; - } - } - - /** - * Add session locator - * - * @access public - * - */ - public function addLocatorItems() - { - $ilLocator = $this->locator; - $ilAccess = $this->access; - - if (is_object($this->object) && $ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - $ilLocator->addItem($this->object->getTitle(), $this->ctrl->getLinkTarget($this, "listMaterials"), "", $_GET["ref_id"]); - } - } - - protected function initCreationForms($a_new_type) - { - $forms = array(self::CFORM_NEW => $this->initCreateForm($a_new_type) - ); - - return $forms; - } - - /** - * Init edit form, custom part - * - * @param ilPropertyFormGUI $a_form form object - */ - function initEditCustomForm(ilPropertyFormGUI $a_form) - { - $a_form->removeItemByPostVar("desc"); - - // description - $ta = new ilTextAreaInputGUI($this->lng->txt("description"), "desc"); - $ta->setRows(2); - $ta->setInfo($this->lng->txt("itgr_desc_info")); - $a_form->addItem($ta); - - // show title - $cb = new ilCheckboxInputGUI($this->lng->txt("itgr_show_title"), "show_title"); - $cb->setInfo($this->lng->txt("itgr_show_title_info")); - $a_form->addItem($cb); - - // behaviour - include_once("./Modules/ItemGroup/classes/class.ilItemGroupBehaviour.php"); - $options = ilItemGroupBehaviour::getAll(); - $si = new ilSelectInputGUI($this->lng->txt("itgr_behaviour"), "behaviour"); - $si->setInfo($this->lng->txt("itgr_behaviour_info")); - $si->setOptions($options); - $cb->addSubItem($si); - - } - - - /** - * After save - */ - protected function afterSave(ilObject $a_new_object) - { - $ilCtrl = $this->ctrl; - - ilUtil::sendSuccess($this->lng->txt("object_added"), true); - $ilCtrl->redirect($this, "listMaterials"); - } - - /** - * show material assignment - * - * @access protected - * @param - * @return - */ - public function listMaterials() - { - $tree = $this->tree; - $ilTabs = $this->tabs; - $tpl = $this->tpl; - - $this->checkPermission("write"); - - $ilTabs->activateTab("materials"); - - $parent_ref_id = $tree->getParentId($this->object->getRefId()); - - include_once "Services/Object/classes/class.ilObjectAddNewItemGUI.php"; - $gui = new ilObjectAddNewItemGUI($parent_ref_id); - $gui->setDisabledObjectTypes(array("itgr", "sess")); - $gui->setAfterCreationCallback($this->object->getRefId()); - $gui->render(); - - include_once("./Modules/ItemGroup/classes/class.ilItemGroupItemsTableGUI.php"); - $tab = new ilItemGroupItemsTableGUI($this, "listMaterials"); - $tpl->setContent($tab->getHTML()); - } - - /** - * Save material assignment - */ - public function saveItemAssignment() - { - $ilCtrl = $this->ctrl; - - $this->checkPermission("write"); - - include_once './Modules/ItemGroup/classes/class.ilItemGroupItems.php'; - - $item_group_items = new ilItemGroupItems($this->object->getRefId()); - $items = is_array($_POST['items']) - ? $_POST['items'] - : array(); - $items = ilUtil::stripSlashesArray($items); - $item_group_items->setItems($items); - $item_group_items->update(); - - ilUtil::sendSuccess($this->lng->txt('msg_obj_modified'), true); - $ilCtrl->redirect($this, "listMaterials"); - } - - - /** - * Get standard template - */ - function getTemplate() - { - $this->tpl->getStandardTemplate(); - } - - - /** - * Set tabs - */ - function setTabs() - { - $ilAccess = $this->access; - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $ilHelp = $this->help; - $lng = $this->lng; - $tree = $this->tree; - - $ilHelp->setScreenIdComponent("itgr"); - - $parent_ref_id = $tree->getParentId($this->object->getRefId()); - $parent_obj_id = ilObject::_lookupObjId($parent_ref_id); - $parent_type = ilObject::_lookupType($parent_obj_id); - - include_once("./Services/Link/classes/class.ilLink.php"); - $ilTabs->setBackTarget( - $lng->txt('obj_'.$parent_type), - ilLink::_getLink($parent_ref_id), "_top"); - - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - $ilTabs->addTab('materials', - $lng->txt('itgr_materials'), - $this->ctrl->getLinkTarget($this, 'listMaterials')); - - $ilTabs->addTab('settings', - $lng->txt('settings'), - $this->ctrl->getLinkTarget($this, 'edit')); - } - - if ($ilAccess->checkAccess("edit_permission", "", $this->object->getRefId())) - { - $ilTabs->addTab("perm_settings", - $lng->txt('perm_settings'), - $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm") - ); - } - } - - - /** - * Goto item group - */ - public static function _goto($a_target) - { - global $DIC; - - $ilAccess = $DIC->access(); - $ilErr = $DIC["ilErr"]; - $lng = $DIC->language(); - $tree = $DIC->repositoryTree(); - - $targets = explode('_',$a_target); - $ref_id = $targets[0]; - $par_id = $tree->getParentId($ref_id); - - if ($ilAccess->checkAccess("read", "", $par_id)) - { - include_once("./Services/Link/classes/class.ilLink.php"); - ilUtil::redirect(ilLink::_getLink($par_id)); - exit; - } - else if ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) - { - ilUtil::sendFailure(sprintf($lng->txt("msg_no_perm_read_item"), - ilObject::_lookupTitle(ilObject::_lookupObjId($a_target))), true); - ilObjectGUI::_gotoRepositoryRoot(); - } - - $ilErr->raiseError($lng->txt("msg_no_perm_read"), $ilErr->FATAL); - } - - /** - * Goto item group - */ - function gotoParent() - { - $ilAccess = $this->access; - $ilErr = $this->error; - $lng = $this->lng; - $tree = $this->tree; - - $ref_id = $this->object->getRefId(); - $par_id = $tree->getParentId($ref_id); - - if ($ilAccess->checkAccess("read", "", $par_id)) - { - include_once("./Services/Link/classes/class.ilLink.php"); - ilUtil::redirect(ilLink::_getLink($par_id)); - exit; - } - } - - /** - * Custom callback after object is created (in parent containert - * - * @param ilObject $a_obj - */ - public function afterSaveCallback(ilObject $a_obj) - { - // add new object to materials - include_once './Modules/ItemGroup/classes/class.ilItemGroupItems.php'; - $items = new ilItemGroupItems($this->object->getRefId()); - $items->addItem($a_obj->getRefId()); - $items->update(); - } - - /** - * Get edit form values (custom part) - * - * @param array $a_values form values - */ - function getEditFormCustomValues(array &$a_values) - { - $a_values["show_title"] = !$this->object->getHideTitle(); - $a_values["behaviour"] = $this->object->getBehaviour(); - } - - /** - * Update (custom part) - * - * @param ilPropertyFormGUI $a_form form - */ - function updateCustom(ilPropertyFormGUI $a_form) - { - $this->object->setHideTitle(!$a_form->getInput("show_title")); - include_once("./Modules/ItemGroup/classes/class.ilItemGroupBehaviour.php"); - $behaviour = ($a_form->getInput("show_title")) - ? $a_form->getInput("behaviour") - : ilItemGroupBehaviour::ALWAYS_OPEN; - $this->object->setBehaviour($behaviour); - } - - /** - * Init object creation form - * - * @param string $a_new_type - * @return ilPropertyFormGUI - */ - protected function initCreateForm($a_new_type) - { - $form = parent::initCreateForm($a_new_type); - $ta = $form->getItemByPostVar("desc"); - $ta->setInfo($this->lng->txt("itgr_desc_info")); - return $form; - } - - + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var ilErrorHandling + */ + protected $error; + + + /** + * Constructor + */ + public function __construct($a_id = 0, $a_id_type = self::REPOSITORY_NODE_ID, $a_parent_node_id = 0) + { + global $DIC; + parent::__construct($a_id, $a_id_type, $a_parent_node_id); + + $this->lng = $DIC->language(); + $this->tabs = $DIC->tabs(); + $this->access = $DIC->access(); + $this->tpl = $DIC["tpl"]; + $this->ctrl = $DIC->ctrl(); + $this->locator = $DIC["ilLocator"]; + $this->tree = $DIC->repositoryTree(); + $this->help = $DIC["ilHelp"]; + $this->error = $DIC["ilErr"]; + } + + /** + * Initialisation + */ + protected function afterConstructor() + { + $lng = $this->lng; + + $lng->loadLanguageModule("itgr"); + + $this->ctrl->saveParameter($this, array("ref_id")); + } + + /** + * Get type + */ + final public function getType() + { + return "itgr"; + } + + /** + * execute command + */ + public function executeCommand() + { + $ilTabs = $this->tabs; + $lng = $this->lng; + $ilAccess = $this->access; + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $ilLocator = $this->locator; + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + switch ($next_class) { + case 'ilinfoscreengui': + $this->prepareOutput(); + $this->addHeaderAction(); + $this->infoScreen(); + break; + + case 'ilpermissiongui': + $this->prepareOutput(); + $ilTabs->activateTab("perm_settings"); + $this->addHeaderAction(); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $ret = $this->ctrl->forwardCommand($perm_gui); + break; + + case "ilcommonactiondispatchergui": + include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); + $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); + $this->ctrl->forwardCommand($gui); + break; + + default: + $cmd = $this->ctrl->getCmd("listMaterials"); + $this->prepareOutput(); + $this->addHeaderAction(); + $this->$cmd(); + break; + } + } + + /** + * Add session locator + * + * @access public + * + */ + public function addLocatorItems() + { + $ilLocator = $this->locator; + $ilAccess = $this->access; + + if (is_object($this->object) && $ilAccess->checkAccess("write", "", $this->object->getRefId())) { + $ilLocator->addItem($this->object->getTitle(), $this->ctrl->getLinkTarget($this, "listMaterials"), "", $_GET["ref_id"]); + } + } + + protected function initCreationForms($a_new_type) + { + $forms = array(self::CFORM_NEW => $this->initCreateForm($a_new_type) + ); + + return $forms; + } + + /** + * Init edit form, custom part + * + * @param ilPropertyFormGUI $a_form form object + */ + public function initEditCustomForm(ilPropertyFormGUI $a_form) + { + $a_form->removeItemByPostVar("desc"); + + // description + $ta = new ilTextAreaInputGUI($this->lng->txt("description"), "desc"); + $ta->setRows(2); + $ta->setInfo($this->lng->txt("itgr_desc_info")); + $a_form->addItem($ta); + + // show title + $cb = new ilCheckboxInputGUI($this->lng->txt("itgr_show_title"), "show_title"); + $cb->setInfo($this->lng->txt("itgr_show_title_info")); + $a_form->addItem($cb); + + // behaviour + include_once("./Modules/ItemGroup/classes/class.ilItemGroupBehaviour.php"); + $options = ilItemGroupBehaviour::getAll(); + $si = new ilSelectInputGUI($this->lng->txt("itgr_behaviour"), "behaviour"); + $si->setInfo($this->lng->txt("itgr_behaviour_info")); + $si->setOptions($options); + $cb->addSubItem($si); + } + + + /** + * After save + */ + protected function afterSave(ilObject $a_new_object) + { + $ilCtrl = $this->ctrl; + + ilUtil::sendSuccess($this->lng->txt("object_added"), true); + $ilCtrl->redirect($this, "listMaterials"); + } + + /** + * show material assignment + * + * @access protected + * @param + * @return + */ + public function listMaterials() + { + $tree = $this->tree; + $ilTabs = $this->tabs; + $tpl = $this->tpl; + + $this->checkPermission("write"); + + $ilTabs->activateTab("materials"); + + $parent_ref_id = $tree->getParentId($this->object->getRefId()); + + include_once "Services/Object/classes/class.ilObjectAddNewItemGUI.php"; + $gui = new ilObjectAddNewItemGUI($parent_ref_id); + $gui->setDisabledObjectTypes(array("itgr", "sess")); + $gui->setAfterCreationCallback($this->object->getRefId()); + $gui->render(); + + include_once("./Modules/ItemGroup/classes/class.ilItemGroupItemsTableGUI.php"); + $tab = new ilItemGroupItemsTableGUI($this, "listMaterials"); + $tpl->setContent($tab->getHTML()); + } + + /** + * Save material assignment + */ + public function saveItemAssignment() + { + $ilCtrl = $this->ctrl; + + $this->checkPermission("write"); + + include_once './Modules/ItemGroup/classes/class.ilItemGroupItems.php'; + + $item_group_items = new ilItemGroupItems($this->object->getRefId()); + $items = is_array($_POST['items']) + ? $_POST['items'] + : array(); + $items = ilUtil::stripSlashesArray($items); + $item_group_items->setItems($items); + $item_group_items->update(); + + ilUtil::sendSuccess($this->lng->txt('msg_obj_modified'), true); + $ilCtrl->redirect($this, "listMaterials"); + } + + + /** + * Get standard template + */ + public function getTemplate() + { + $this->tpl->getStandardTemplate(); + } + + + /** + * Set tabs + */ + public function setTabs() + { + $ilAccess = $this->access; + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $ilHelp = $this->help; + $lng = $this->lng; + $tree = $this->tree; + + $ilHelp->setScreenIdComponent("itgr"); + + $parent_ref_id = $tree->getParentId($this->object->getRefId()); + $parent_obj_id = ilObject::_lookupObjId($parent_ref_id); + $parent_type = ilObject::_lookupType($parent_obj_id); + + include_once("./Services/Link/classes/class.ilLink.php"); + $ilTabs->setBackTarget( + $lng->txt('obj_' . $parent_type), + ilLink::_getLink($parent_ref_id), + "_top" + ); + + if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) { + $ilTabs->addTab( + 'materials', + $lng->txt('itgr_materials'), + $this->ctrl->getLinkTarget($this, 'listMaterials') + ); + + $ilTabs->addTab( + 'settings', + $lng->txt('settings'), + $this->ctrl->getLinkTarget($this, 'edit') + ); + } + + if ($ilAccess->checkAccess("edit_permission", "", $this->object->getRefId())) { + $ilTabs->addTab( + "perm_settings", + $lng->txt('perm_settings'), + $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm") + ); + } + } + + + /** + * Goto item group + */ + public static function _goto($a_target) + { + global $DIC; + + $ilAccess = $DIC->access(); + $ilErr = $DIC["ilErr"]; + $lng = $DIC->language(); + $tree = $DIC->repositoryTree(); + + $targets = explode('_', $a_target); + $ref_id = $targets[0]; + $par_id = $tree->getParentId($ref_id); + + if ($ilAccess->checkAccess("read", "", $par_id)) { + include_once("./Services/Link/classes/class.ilLink.php"); + ilUtil::redirect(ilLink::_getLink($par_id)); + exit; + } elseif ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) { + ilUtil::sendFailure(sprintf( + $lng->txt("msg_no_perm_read_item"), + ilObject::_lookupTitle(ilObject::_lookupObjId($a_target)) + ), true); + ilObjectGUI::_gotoRepositoryRoot(); + } + + $ilErr->raiseError($lng->txt("msg_no_perm_read"), $ilErr->FATAL); + } + + /** + * Goto item group + */ + public function gotoParent() + { + $ilAccess = $this->access; + $ilErr = $this->error; + $lng = $this->lng; + $tree = $this->tree; + + $ref_id = $this->object->getRefId(); + $par_id = $tree->getParentId($ref_id); + + if ($ilAccess->checkAccess("read", "", $par_id)) { + include_once("./Services/Link/classes/class.ilLink.php"); + ilUtil::redirect(ilLink::_getLink($par_id)); + exit; + } + } + + /** + * Custom callback after object is created (in parent containert + * + * @param ilObject $a_obj + */ + public function afterSaveCallback(ilObject $a_obj) + { + // add new object to materials + include_once './Modules/ItemGroup/classes/class.ilItemGroupItems.php'; + $items = new ilItemGroupItems($this->object->getRefId()); + $items->addItem($a_obj->getRefId()); + $items->update(); + } + + /** + * Get edit form values (custom part) + * + * @param array $a_values form values + */ + public function getEditFormCustomValues(array &$a_values) + { + $a_values["show_title"] = !$this->object->getHideTitle(); + $a_values["behaviour"] = $this->object->getBehaviour(); + } + + /** + * Update (custom part) + * + * @param ilPropertyFormGUI $a_form form + */ + public function updateCustom(ilPropertyFormGUI $a_form) + { + $this->object->setHideTitle(!$a_form->getInput("show_title")); + include_once("./Modules/ItemGroup/classes/class.ilItemGroupBehaviour.php"); + $behaviour = ($a_form->getInput("show_title")) + ? $a_form->getInput("behaviour") + : ilItemGroupBehaviour::ALWAYS_OPEN; + $this->object->setBehaviour($behaviour); + } + + /** + * Init object creation form + * + * @param string $a_new_type + * @return ilPropertyFormGUI + */ + protected function initCreateForm($a_new_type) + { + $form = parent::initCreateForm($a_new_type); + $ta = $form->getItemByPostVar("desc"); + $ta->setInfo($this->lng->txt("itgr_desc_info")); + return $form; + } } -?> \ No newline at end of file diff --git a/Modules/ItemGroup/classes/class.ilObjItemGroupListGUI.php b/Modules/ItemGroup/classes/class.ilObjItemGroupListGUI.php index 1ed31416ea75aa5713ecf586cde89cc442b6fe8f..8a881b7022e49964c25ba9d383163d202c327587 100644 --- a/Modules/ItemGroup/classes/class.ilObjItemGroupListGUI.php +++ b/Modules/ItemGroup/classes/class.ilObjItemGroupListGUI.php @@ -6,7 +6,7 @@ include_once('Services/Object/classes/class.ilObjectListGUI.php'); /** * Item group list gui class - * + * * @author Alex Killing * @version $Id$ * @@ -14,123 +14,121 @@ include_once('Services/Object/classes/class.ilObjectListGUI.php'); */ class ilObjItemGroupListGUI extends ilObjectListGUI { - /** - * Constructor - */ - public function __construct() - { - global $DIC; + /** + * Constructor + */ + public function __construct() + { + global $DIC; - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $lng->loadLanguageModule('itgr'); - parent::__construct(); - } - - /** - * Initialisation - * - * @access public - * @return void - */ - public function init() - { - $this->delete_enabled = true; - $this->cut_enabled = false; - $this->copy_enabled = false; - $this->subscribe_enabled = false; - $this->link_enabled = false; - $this->info_screen_enabled = false; - $this->subitems_enabled = true; - $this->type = "itgr"; - $this->gui_class_name = "ilobjitemgroupgui"; - - // general commands array - include_once('./Modules/ItemGroup/classes/class.ilObjItemGroupAccess.php'); - $this->commands = ilObjItemGroupAccess::_getCommands(); - } + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $lng->loadLanguageModule('itgr'); + parent::__construct(); + } + + /** + * Initialisation + * + * @access public + * @return void + */ + public function init() + { + $this->delete_enabled = true; + $this->cut_enabled = false; + $this->copy_enabled = false; + $this->subscribe_enabled = false; + $this->link_enabled = false; + $this->info_screen_enabled = false; + $this->subitems_enabled = true; + $this->type = "itgr"; + $this->gui_class_name = "ilobjitemgroupgui"; + + // general commands array + include_once('./Modules/ItemGroup/classes/class.ilObjItemGroupAccess.php'); + $this->commands = ilObjItemGroupAccess::_getCommands(); + } - /** - * Enable subscribtion (deactivated) - * necessary due to bug 11509 - * - * @param - * @return - */ - function enableSubscribe($a_val) - { - $this->subscribe_enabled = false; - } - - /** - * Prevent enabling info - * necessary due to bug 11509 - * - * @param bool - * @return void - */ - function enableInfoScreen($a_info_screen) - { - $this->info_screen_enabled = false; - } + /** + * Enable subscribtion (deactivated) + * necessary due to bug 11509 + * + * @param + * @return + */ + public function enableSubscribe($a_val) + { + $this->subscribe_enabled = false; + } + + /** + * Prevent enabling info + * necessary due to bug 11509 + * + * @param bool + * @return void + */ + public function enableInfoScreen($a_info_screen) + { + $this->info_screen_enabled = false; + } - /** - * Get command link url. - * - * @param int $a_ref_id reference id - * @param string $a_cmd command - * - */ - public function getCommandLink($a_cmd) - { - $ilCtrl = $this->ctrl; - - // separate method for this line - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $this->ref_id); - $cmd_link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", $a_cmd); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - return $cmd_link; - } - - - /** - * Fet properties - * - * @return array properties array - */ - public function getProperties() - { - $props = array(); - return $props; - } + /** + * Get command link url. + * + * @param int $a_ref_id reference id + * @param string $a_cmd command + * + */ + public function getCommandLink($a_cmd) + { + $ilCtrl = $this->ctrl; + + // separate method for this line + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $this->ref_id); + $cmd_link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", $a_cmd); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + return $cmd_link; + } + + + /** + * Fet properties + * + * @return array properties array + */ + public function getProperties() + { + $props = array(); + return $props; + } - - - /** - * Get assigned items of event. - * @return - * @param object $a_sess_id - */ - protected static function lookupAssignedMaterials($a_sess_id) - { - global $DIC; + + + /** + * Get assigned items of event. + * @return + * @param object $a_sess_id + */ + protected static function lookupAssignedMaterials($a_sess_id) + { + global $DIC; - $ilDB = $DIC->database(); - -return array(); -/* - $query = 'SELECT * FROM event_items '. - 'WHERE event_id = '.$ilDB->quote($a_sess_id).' '; - $res = $ilDB->query($query); - while($row = $res->fetchRow(FETCHMODE_OBJECT)) - { - $items[] = $row['item_id']; - } - return $items ? $items : array();*/ - } - + $ilDB = $DIC->database(); + + return array(); + /* + $query = 'SELECT * FROM event_items '. + 'WHERE event_id = '.$ilDB->quote($a_sess_id).' '; + $res = $ilDB->query($query); + while($row = $res->fetchRow(FETCHMODE_OBJECT)) + { + $items[] = $row['item_id']; + } + return $items ? $items : array();*/ + } } -?> \ No newline at end of file diff --git a/Modules/LearningModule/classes/class.ilChapterHierarchyFormGUI.php b/Modules/LearningModule/classes/class.ilChapterHierarchyFormGUI.php index f4bbc7f2d85bccedff437fcda93da9022c16af84..506bcf61beed634c55932fdff5d8fb877f47a683 100644 --- a/Modules/LearningModule/classes/class.ilChapterHierarchyFormGUI.php +++ b/Modules/LearningModule/classes/class.ilChapterHierarchyFormGUI.php @@ -9,342 +9,338 @@ include_once("./Modules/LearningModule/classes/class.ilLMObjTranslation.php"); * This class represents a hierarchical form. These forms are used for * quick editing, where each node is represented by it's title. * -* @author Alex Killing +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilChapterHierarchyFormGUI extends ilHierarchyFormGUI { - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - /** - * Constructor - * - * @param - */ - function __construct($a_lm_type, $a_lang = "-") - { - global $DIC; + /** + * Constructor + * + * @param + */ + public function __construct($a_lm_type, $a_lang = "-") + { + global $DIC; - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - $this->ctrl = $DIC->ctrl(); - $this->lm_type = $a_lm_type; + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + $this->ctrl = $DIC->ctrl(); + $this->lm_type = $a_lm_type; - $this->lang = ($a_lang == "") - ? "-" - : $a_lang; - parent::__construct(); - $this->setCheckboxName("id"); - } - - /** - * Get child title - * - * @param - * @return - */ - function getChildTitle($a_child) - { - if ($this->lang != "-") - { - $lmobjtrans = new ilLMObjTranslation($a_child["node_id"], $this->lang); - return $lmobjtrans->getTitle(); - } - return $a_child["title"]; - } + $this->lang = ($a_lang == "") + ? "-" + : $a_lang; + parent::__construct(); + $this->setCheckboxName("id"); + } + + /** + * Get child title + * + * @param + * @return + */ + public function getChildTitle($a_child) + { + if ($this->lang != "-") { + $lmobjtrans = new ilLMObjTranslation($a_child["node_id"], $this->lang); + return $lmobjtrans->getTitle(); + } + return $a_child["title"]; + } - /** - * Get child info - * - * @param array $a_child node array - * @return string node title - */ - function getChildInfo($a_child) - { - if ($this->lang != "-") - { - return $a_child["title"]; - } - return ""; - } + /** + * Get child info + * + * @param array $a_child node array + * @return string node title + */ + public function getChildInfo($a_child) + { + if ($this->lang != "-") { + return $a_child["title"]; + } + return ""; + } - /** - * Get menu items - */ - function getMenuItems($a_node, $a_depth, $a_first_child = false, $a_next_sibling = null, $a_childs = null) - { - $lng = $this->lng; - $ilUser = $this->user; - - $cmds = array(); + /** + * Get menu items + */ + public function getMenuItems($a_node, $a_depth, $a_first_child = false, $a_next_sibling = null, $a_childs = null) + { + $lng = $this->lng; + $ilUser = $this->user; + + $cmds = array(); - if ($a_childs == null) - { - $a_childs = []; - } - - if (!$a_first_child) // drop area of node - { - if ($a_node["type"] == "pg" || ($a_node["type"] == "st" && count($a_childs) == 0 && $this->getMaxDepth() != 0)) - { - if ($a_node["type"] == "st") - { - $cmds[] = array("text" => $lng->txt("cont_insert_page"), "cmd" => "insertPage", "multi" => 10, - "as_subitem" => true); - if ($ilUser->clipboardHasObjectsOfType("pg")) - { - $cmds[] = array("text" => $lng->txt("cont_insert_page_from_clip"), - "cmd" => "insertPageClip", "as_subitem" => true); - } - } - else - { - $cmds[] = array("text" => $lng->txt("cont_insert_page"), "cmd" => "insertPage", "multi" => 10); - if ($ilUser->clipboardHasObjectsOfType("pg")) - { - $cmds[] = array("text" => $lng->txt("cont_insert_page_from_clip"), - "cmd" => "insertPageClip"); - } - } - } - if ($a_node["type"] != "pg" && $this->getMaxDepth() != 0) - { - $cmds[] = array("text" => $lng->txt("cont_insert_subchapter"), - "cmd" => "insertSubchapter", "multi" => 10); - if ($ilUser->clipboardHasObjectsOfType("st")) - { - $cmds[] = array("text" => $lng->txt("cont_insert_subchapter_from_clip"), - "cmd" => "insertSubchapterClip"); - } - } - - if (($a_next_sibling["type"] != "pg" && ($a_depth == 0 || $a_next_sibling["type"] == "st")) - || $a_node["type"] == "st") - { - $cmds[] = array("text" => $lng->txt("cont_insert_chapter"), - "cmd" => "insertChapter", "multi" => 10); - if ($ilUser->clipboardHasObjectsOfType("st")) - { - $cmds[] = array("text" => $lng->txt("cont_insert_chapter_from_clip"), - "cmd" => "insertChapterClip"); - } - } - } - else // drop area before first child of node - { - if ($a_node["type"] == "st" && $this->getMaxDepth() != 0) - { - $cmds[] = array("text" => $lng->txt("cont_insert_page"), - "cmd" => "insertPage", "multi" => 10); - if ($ilUser->clipboardHasObjectsOfType("pg")) - { - $cmds[] = array("text" => $lng->txt("cont_insert_page_from_clip"), - "cmd" => "insertPageClip"); - } - } - if ($a_childs[0]["type"] != "pg") - { - $cmds[] = array("text" => $lng->txt("cont_insert_chapter"), - "cmd" => "insertChapter", "multi" => 10); - if ($ilUser->clipboardHasObjectsOfType("st")) - { - $cmds[] = array("text" => $lng->txt("cont_insert_chapter_from_clip"), - "cmd" => "insertChapterClip"); - } - } - } + if ($a_childs == null) { + $a_childs = []; + } + + if (!$a_first_child) { // drop area of node + if ($a_node["type"] == "pg" || ($a_node["type"] == "st" && count($a_childs) == 0 && $this->getMaxDepth() != 0)) { + if ($a_node["type"] == "st") { + $cmds[] = array("text" => $lng->txt("cont_insert_page"), "cmd" => "insertPage", "multi" => 10, + "as_subitem" => true); + if ($ilUser->clipboardHasObjectsOfType("pg")) { + $cmds[] = array("text" => $lng->txt("cont_insert_page_from_clip"), + "cmd" => "insertPageClip", "as_subitem" => true); + } + } else { + $cmds[] = array("text" => $lng->txt("cont_insert_page"), "cmd" => "insertPage", "multi" => 10); + if ($ilUser->clipboardHasObjectsOfType("pg")) { + $cmds[] = array("text" => $lng->txt("cont_insert_page_from_clip"), + "cmd" => "insertPageClip"); + } + } + } + if ($a_node["type"] != "pg" && $this->getMaxDepth() != 0) { + $cmds[] = array("text" => $lng->txt("cont_insert_subchapter"), + "cmd" => "insertSubchapter", "multi" => 10); + if ($ilUser->clipboardHasObjectsOfType("st")) { + $cmds[] = array("text" => $lng->txt("cont_insert_subchapter_from_clip"), + "cmd" => "insertSubchapterClip"); + } + } + + if (($a_next_sibling["type"] != "pg" && ($a_depth == 0 || $a_next_sibling["type"] == "st")) + || $a_node["type"] == "st") { + $cmds[] = array("text" => $lng->txt("cont_insert_chapter"), + "cmd" => "insertChapter", "multi" => 10); + if ($ilUser->clipboardHasObjectsOfType("st")) { + $cmds[] = array("text" => $lng->txt("cont_insert_chapter_from_clip"), + "cmd" => "insertChapterClip"); + } + } + } else { // drop area before first child of node + if ($a_node["type"] == "st" && $this->getMaxDepth() != 0) { + $cmds[] = array("text" => $lng->txt("cont_insert_page"), + "cmd" => "insertPage", "multi" => 10); + if ($ilUser->clipboardHasObjectsOfType("pg")) { + $cmds[] = array("text" => $lng->txt("cont_insert_page_from_clip"), + "cmd" => "insertPageClip"); + } + } + if ($a_childs[0]["type"] != "pg") { + $cmds[] = array("text" => $lng->txt("cont_insert_chapter"), + "cmd" => "insertChapter", "multi" => 10); + if ($ilUser->clipboardHasObjectsOfType("st")) { + $cmds[] = array("text" => $lng->txt("cont_insert_chapter_from_clip"), + "cmd" => "insertChapterClip"); + } + } + } - return $cmds; - } + return $cmds; + } - /** - * Which nodes allow child nodes? - */ - function nodeAllowsChilds($a_node) - { - if ($a_node["type"] == "pg") - { - return false; - } - return true; - } + /** + * Which nodes allow child nodes? + */ + public function nodeAllowsChilds($a_node) + { + if ($a_node["type"] == "pg") { + return false; + } + return true; + } - /** - * Makes nodes drag and drop content and targets. - * - * @param object $a_node node array - */ - function manageDragAndDrop($a_node, $a_depth, $a_first_child_drop_area = false, $a_next_sibling = null, $a_childs = null) - { - $lng = $this->lng; - - $this->makeDragContent($a_node["node_id"], "grp_".$a_node["type"]); + /** + * Makes nodes drag and drop content and targets. + * + * @param object $a_node node array + */ + public function manageDragAndDrop($a_node, $a_depth, $a_first_child_drop_area = false, $a_next_sibling = null, $a_childs = null) + { + $lng = $this->lng; + + $this->makeDragContent($a_node["node_id"], "grp_" . $a_node["type"]); - if ($a_childs == null) - { - $a_childs = []; - } + if ($a_childs == null) { + $a_childs = []; + } - if (!$a_first_child_drop_area) - { - if ($a_node["type"] == "pg" || ($a_node["type"] == "st" && count($a_childs) == 0 && $this->getMaxDepth() != 0)) - { - if ($a_node["type"] == "st") - { - $this->makeDragTarget($a_node["node_id"], "grp_pg", $a_first_child_drop_area, - true, ""); - } - else - { - $this->makeDragTarget($a_node["node_id"], "grp_pg", $a_first_child_drop_area, - false, ""); - } - } - - if ($a_node["type"] != "pg" && $this->getMaxDepth() != 0) - { - $this->makeDragTarget($a_node["node_id"], "grp_st", $a_first_child_drop_area, - true, $lng->txt("cont_insert_as_subchapter")); - } - - if (($a_next_sibling["type"] != "pg" && ($a_depth == 0 || $a_next_sibling["type"] == "st")) - || $a_node["type"] == "st") - { - $this->makeDragTarget($a_node["node_id"], "grp_st", $a_first_child_drop_area, - false, $lng->txt("cont_insert_as_chapter")); - } - } - else - { - if ($a_node["type"] == "st" && $this->getMaxDepth() != 0) - { - $this->makeDragTarget($a_node["node_id"], "grp_pg", $a_first_child_drop_area, - true); - } - if ($a_childs[0]["type"] != "pg") - { - $this->makeDragTarget($a_node["node_id"], "grp_st", $a_first_child_drop_area, - true); - } - } - } + if (!$a_first_child_drop_area) { + if ($a_node["type"] == "pg" || ($a_node["type"] == "st" && count($a_childs) == 0 && $this->getMaxDepth() != 0)) { + if ($a_node["type"] == "st") { + $this->makeDragTarget( + $a_node["node_id"], + "grp_pg", + $a_first_child_drop_area, + true, + "" + ); + } else { + $this->makeDragTarget( + $a_node["node_id"], + "grp_pg", + $a_first_child_drop_area, + false, + "" + ); + } + } + + if ($a_node["type"] != "pg" && $this->getMaxDepth() != 0) { + $this->makeDragTarget( + $a_node["node_id"], + "grp_st", + $a_first_child_drop_area, + true, + $lng->txt("cont_insert_as_subchapter") + ); + } + + if (($a_next_sibling["type"] != "pg" && ($a_depth == 0 || $a_next_sibling["type"] == "st")) + || $a_node["type"] == "st") { + $this->makeDragTarget( + $a_node["node_id"], + "grp_st", + $a_first_child_drop_area, + false, + $lng->txt("cont_insert_as_chapter") + ); + } + } else { + if ($a_node["type"] == "st" && $this->getMaxDepth() != 0) { + $this->makeDragTarget( + $a_node["node_id"], + "grp_pg", + $a_first_child_drop_area, + true + ); + } + if ($a_childs[0]["type"] != "pg") { + $this->makeDragTarget( + $a_node["node_id"], + "grp_st", + $a_first_child_drop_area, + true + ); + } + } + } - /** - * Get icon path for an item. - * - * @param array itema array - * @return string icon path - */ - function getChildIcon($a_item) - { - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - - $img = "icon_".$a_item["type"].".svg"; - - if ($a_item["type"] == "pg") - { - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - $lm_set = new ilSetting("lm"); - $active = ilLMPage::_lookupActive($a_item["node_id"], $this->lm_type, - $lm_set->get("time_scheduled_page_activation")); - - // is page scheduled? - $img_sc = ($lm_set->get("time_scheduled_page_activation") && - ilLMPage::_isScheduledActivation($a_item["node_id"], $this->lm_type)) - ? "_sc" - : ""; - - $img = "icon_pg".$img_sc.".svg"; + /** + * Get icon path for an item. + * + * @param array itema array + * @return string icon path + */ + public function getChildIcon($a_item) + { + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + + $img = "icon_" . $a_item["type"] . ".svg"; + + if ($a_item["type"] == "pg") { + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + $lm_set = new ilSetting("lm"); + $active = ilLMPage::_lookupActive( + $a_item["node_id"], + $this->lm_type, + $lm_set->get("time_scheduled_page_activation") + ); + + // is page scheduled? + $img_sc = ($lm_set->get("time_scheduled_page_activation") && + ilLMPage::_isScheduledActivation($a_item["node_id"], $this->lm_type)) + ? "_sc" + : ""; + + $img = "icon_pg" . $img_sc . ".svg"; - if (!$active) - { - $img = "icon_pg_d".$img_sc.".svg"; - } - else - { - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - $contains_dis = ilLMPage::_lookupContainsDeactivatedElements($a_item["node_id"], - $this->lm_type); - if ($contains_dis) - { - $img = "icon_pg_del".$img_sc.".svg"; - } - } - } - return ilUtil::getImagePath($img); - } + if (!$active) { + $img = "icon_pg_d" . $img_sc . ".svg"; + } else { + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + $contains_dis = ilLMPage::_lookupContainsDeactivatedElements( + $a_item["node_id"], + $this->lm_type + ); + if ($contains_dis) { + $img = "icon_pg_del" . $img_sc . ".svg"; + } + } + } + return ilUtil::getImagePath($img); + } - /** - * Get icon alt text - * - * @param array itema array - * @return string icon alt text - */ - function getChildIconAlt($a_item) - { - $lng = $this->lng; - - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - - if ($a_item["type"] == "pg") - { - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - $active = ilLMPage::_lookupActive($a_item["node_id"], $this->lm_type); + /** + * Get icon alt text + * + * @param array itema array + * @return string icon alt text + */ + public function getChildIconAlt($a_item) + { + $lng = $this->lng; + + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + + if ($a_item["type"] == "pg") { + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + $active = ilLMPage::_lookupActive($a_item["node_id"], $this->lm_type); - if (!$active) - { - return $lng->txt("cont_page_deactivated"); - } - else - { - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - $contains_dis = ilLMPage::_lookupContainsDeactivatedElements($a_item["node_id"], - $this->lm_type); - if ($contains_dis) - { - return $lng->txt("cont_page_deactivated_elements"); - } - } - } - return ilUtil::getImagePath("icon_".$a_item["type"].".svg"); - } + if (!$active) { + return $lng->txt("cont_page_deactivated"); + } else { + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + $contains_dis = ilLMPage::_lookupContainsDeactivatedElements( + $a_item["node_id"], + $this->lm_type + ); + if ($contains_dis) { + return $lng->txt("cont_page_deactivated_elements"); + } + } + } + return ilUtil::getImagePath("icon_" . $a_item["type"] . ".svg"); + } - /** - * Get item commands - * - * @param array item array - * @return array array of arrays("text", "link") - */ - function getChildCommands($a_item) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $lm_class = "ilobjlearningmodulegui"; - - $commands = array(); - switch ($a_item["type"]) - { - case "pg": - $ilCtrl->setParameterByClass("illmpageobjectgui", "obj_id", - $a_item["node_id"]); - $commands[] = array("text" => $lng->txt("edit"), - "link" => $ilCtrl->getLinkTargetByClass(array($lm_class, "illmpageobjectgui"), "edit")); - break; - - case "st": - $ilCtrl->setParameterByClass("ilstructureobjectgui", "obj_id", - $a_item["node_id"]); - $commands[] = array("text" => $lng->txt("edit"), - "link" => $ilCtrl->getLinkTargetByClass(array($lm_class, "ilstructureobjectgui"), "view")); - break; - } - - return $commands; - } + /** + * Get item commands + * + * @param array item array + * @return array array of arrays("text", "link") + */ + public function getChildCommands($a_item) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $lm_class = "ilobjlearningmodulegui"; + + $commands = array(); + switch ($a_item["type"]) { + case "pg": + $ilCtrl->setParameterByClass( + "illmpageobjectgui", + "obj_id", + $a_item["node_id"] + ); + $commands[] = array("text" => $lng->txt("edit"), + "link" => $ilCtrl->getLinkTargetByClass(array($lm_class, "illmpageobjectgui"), "edit")); + break; + case "st": + $ilCtrl->setParameterByClass( + "ilstructureobjectgui", + "obj_id", + $a_item["node_id"] + ); + $commands[] = array("text" => $lng->txt("edit"), + "link" => $ilCtrl->getLinkTargetByClass(array($lm_class, "ilstructureobjectgui"), "view")); + break; + } + + return $commands; + } } diff --git a/Modules/LearningModule/classes/class.ilContObjLocatorGUI.php b/Modules/LearningModule/classes/class.ilContObjLocatorGUI.php index fae490bde31f68e64ffdbd56e566b32055c58d82..0de8bf4543ebc5976a2715ea65e9c65991492448 100755 --- a/Modules/LearningModule/classes/class.ilContObjLocatorGUI.php +++ b/Modules/LearningModule/classes/class.ilContObjLocatorGUI.php @@ -1,24 +1,24 @@ language(); - $tpl = $DIC["tpl"]; - $ilCtrl = $DIC->ctrl(); - - $this->ctrl = $ilCtrl; - $this->tree = $a_tree; - $this->mode = "std"; - $this->temp_var = "LOCATOR"; - $this->lng = $lng; - $this->tpl = $tpl; - $this->show_user = false; - } - - function setTemplateVariable($a_temp_var) - { - $this->temp_var = $a_temp_var; - } - - function setObjectID($a_obj_id) - { - $this->obj_id = $a_obj_id; - } - - function setContentObject($a_cont_obj) - { - $this->cont_obj = $a_cont_obj; - } - - /** - * display locator - */ - function display($a_gui_class) - { - $lng = $this->lng; - - $this->tpl->addBlockFile($this->temp_var, "locator", "tpl.locator.html", "Services/Locator"); - - if (($this->obj_id != 0) && $this->tree->isInTree($this->obj_id)) - { - $path = $this->tree->getPathFull($this->obj_id); - } - else - { - $path = $this->tree->getPathFull($this->tree->getRootId()); - if ($this->obj_id != 0) - { - $path[] = array("type" => "pg", "child" => $this->obj_id, - "title" => ilLMPageObject::_getPresentationTitle($this->obj_id)); - } - } - - $modifier = 1; - - foreach ($path as $key => $row) - { - if ($key < count($path)-$modifier) - { - $this->tpl->touchBlock("locator_separator"); - } - - $this->tpl->setCurrentBlock("locator_item"); - $transit = ""; - if ($row["child"] == 1) - { - $title = $this->cont_obj->getTitle(); - $cmd = "properties"; - $cmdClass = $a_gui_class; - } - else - { - $title = $row["title"]; - switch($row["type"]) - { - case "st": - $cmdClass = "ilStructureObjectGUI"; - $cmd = "view"; - if ($this->ctrl->getCmdClass() != "ilstructureobjectgui") - { - $transit = array($a_gui_class); - } - break; - - case "pg": - $cmdClass = "ilLMPageObjectGUI"; - $cmd = "view"; - if ($this->ctrl->getCmdClass() != "illmpageobjectgui") - { - $transit = array($a_gui_class); - } - break; - } - } - $this->tpl->setVariable("ITEM", $title); - $obj_str = ($row["child"] == 1) - ? "" - : "&obj_id=".$row["child"]; - - $this->ctrl->setParameterByClass($cmdClass, "obj_id", $row["child"]); - $link = $this->ctrl->getLinkTargetByClass($cmdClass, $cmd, $transit); - $this->ctrl->setParameterByClass($cmdClass, "obj_id", $_GET["obj_id"]); - $this->tpl->setVariable("LINK_ITEM", $link); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setCurrentBlock("locator"); - $this->tpl->parseCurrentBlock(); - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + public $mode; + public $temp_var; + public $tree; + public $lng; + public $tpl; + + + public function __construct($a_tree) + { + global $DIC; + + $lng = $DIC->language(); + $tpl = $DIC["tpl"]; + $ilCtrl = $DIC->ctrl(); + + $this->ctrl = $ilCtrl; + $this->tree = $a_tree; + $this->mode = "std"; + $this->temp_var = "LOCATOR"; + $this->lng = $lng; + $this->tpl = $tpl; + $this->show_user = false; + } + + public function setTemplateVariable($a_temp_var) + { + $this->temp_var = $a_temp_var; + } + + public function setObjectID($a_obj_id) + { + $this->obj_id = $a_obj_id; + } + + public function setContentObject($a_cont_obj) + { + $this->cont_obj = $a_cont_obj; + } + + /** + * display locator + */ + public function display($a_gui_class) + { + $lng = $this->lng; + + $this->tpl->addBlockFile($this->temp_var, "locator", "tpl.locator.html", "Services/Locator"); + + if (($this->obj_id != 0) && $this->tree->isInTree($this->obj_id)) { + $path = $this->tree->getPathFull($this->obj_id); + } else { + $path = $this->tree->getPathFull($this->tree->getRootId()); + if ($this->obj_id != 0) { + $path[] = array("type" => "pg", "child" => $this->obj_id, + "title" => ilLMPageObject::_getPresentationTitle($this->obj_id)); + } + } + + $modifier = 1; + + foreach ($path as $key => $row) { + if ($key < count($path)-$modifier) { + $this->tpl->touchBlock("locator_separator"); + } + + $this->tpl->setCurrentBlock("locator_item"); + $transit = ""; + if ($row["child"] == 1) { + $title = $this->cont_obj->getTitle(); + $cmd = "properties"; + $cmdClass = $a_gui_class; + } else { + $title = $row["title"]; + switch ($row["type"]) { + case "st": + $cmdClass = "ilStructureObjectGUI"; + $cmd = "view"; + if ($this->ctrl->getCmdClass() != "ilstructureobjectgui") { + $transit = array($a_gui_class); + } + break; + + case "pg": + $cmdClass = "ilLMPageObjectGUI"; + $cmd = "view"; + if ($this->ctrl->getCmdClass() != "illmpageobjectgui") { + $transit = array($a_gui_class); + } + break; + } + } + $this->tpl->setVariable("ITEM", $title); + $obj_str = ($row["child"] == 1) + ? "" + : "&obj_id=" . $row["child"]; + + $this->ctrl->setParameterByClass($cmdClass, "obj_id", $row["child"]); + $link = $this->ctrl->getLinkTargetByClass($cmdClass, $cmd, $transit); + $this->ctrl->setParameterByClass($cmdClass, "obj_id", $_GET["obj_id"]); + $this->tpl->setVariable("LINK_ITEM", $link); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setCurrentBlock("locator"); + $this->tpl->parseCurrentBlock(); + } } -?> diff --git a/Modules/LearningModule/classes/class.ilContObjParser.php b/Modules/LearningModule/classes/class.ilContObjParser.php index 41c80563efb885e14c575b8959934e4fbae3adde..8d52e61a3babe2a96fff964d0596015139c41add 100755 --- a/Modules/LearningModule/classes/class.ilContObjParser.php +++ b/Modules/LearningModule/classes/class.ilContObjParser.php @@ -30,1673 +30,1530 @@ include_once("Services/MetaData/classes/class.ilMD.php"); */ class ilContObjParser extends ilMDSaxParser { - var $lng; - var $tree; - var $cnt; // counts open elements - var $current_element; // store current element type - var $learning_module; // current learning module - var $page_object; // current page object - var $lm_page_object; - var $structure_objects; // array of current structure objects - var $media_object; - var $current_object; // at the time a LearningModule, PageObject or StructureObject - var $meta_data; // current meta data object - var $paragraph; - var $table; - var $lm_tree; - var $pg_into_tree; - var $st_into_tree; - var $container = []; - var $in_page_object; // are we currently within a PageObject? true/false - var $in_meta_data; // are we currently within MetaData? true/false - var $in_media_object; - var $in_file_item; - var $in_glossary; - var $in_map_area; - var $content_object; - var $glossary_object; - var $file_item; - var $keyword_language; - var $pages_to_parse; - var $mob_mapping; - var $file_item_mapping; - var $subdir; - var $media_item; // current media item - var $loc_type; // current location type - var $map_area; // current map area - var $link_targets; // stores all objects by import id - var $qst_mapping; - var $metadata_parsing_disabled; - var $in_meta_meta_data = false; - protected $glossary_term_map = array(); - - /** - * @var ilLogger - */ - protected $log; - - /** - * Constructor - * - * @param object $a_content_object must be of type ilObjContentObject - * ilObjTest or ilObjQuestionPool - * @param string $a_xml_file xml file - * @param string $a_subdir subdirectory in import directory - * @access public - */ - function __construct(&$a_content_object, $a_xml_file, $a_subdir, $a_import_dir = "") - { - global $DIC; - - $this->log = $DIC["ilLog"]; - $lng = $DIC->language(); - $tree = $DIC->repositoryTree(); - - $this->log = ilLoggerFactory::getLogger('lm'); - - $this->import_dir = ($a_import_dir != "") - ? $a_import_dir - : $a_content_object->getImportDirectory(); - - parent::__construct($a_xml_file); - $this->cnt = array(); - $this->current_element = array(); - $this->structure_objects = array(); - $this->content_object = $a_content_object; - //$this->lm_id = $a_lm_id; - $this->st_into_tree = array(); - $this->pg_into_tree = array(); - $this->pages_to_parse = array(); - $this->mobs_with_int_links = array(); - $this->mob_mapping = array(); - $this->file_item_mapping = array(); - $this->pg_mapping = array(); - $this->link_targets = array(); - $this->subdir = $a_subdir; - $this->lng = $lng; - $this->tree = $tree; - $this->inside_code = false; - $this->qst_mapping = array(); - $this->coType = $this->content_object->getType(); - $this->metadata_parsing_disabled = false; - - if (($this->coType != "tst") and ($this->coType != "qpl")) - { - $this->lm_tree = new ilTree($this->content_object->getId()); - $this->lm_tree->setTreeTablePK("lm_id"); - $this->lm_tree->setTableNames('lm_tree','lm_data'); - } - //$this->lm_tree->addTree($a_lm_id, 1); happens in ilObjLearningModuleGUI - - } - - /** - * set event handlers - * - * @param resource reference to the xml parser - * @access private - */ - 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'); - } - - /** - * Set import mapping - * @param ilImportMapping $mapping - */ - public function setImportMapping(ilImportMapping $mapping = null) - { - $this->mapping = $mapping; - } - - - /** - * start parser - */ - function startParsing() - { - $this->log->debug("start"); - -//echo "start parsing
"; - parent::startParsing(); -//echo "storeTree
"; - $this->storeTree(); -//echo "processPagesToParse
"; - $this->processPagesToParse(); -//echo "copyMobFiles
"; - $this->copyMobFiles(); -//echo "copyFileItems
"; - $this->copyFileItems(); -//echo "
END Parsing"; exit; - } - - - /** - * insert StructureObjects and PageObjects into tree - */ - function storeTree() - { - $ilLog = $this->log; - -//echo "Storing the tree
"; - foreach($this->st_into_tree as $st) - { -//echo "insert st id: ".$st["id"].", parent:".$st["parent"]."
"; - $this->lm_tree->insertNode($st["id"], $st["parent"]); -//echo "done
"; -//var_dump($this->pg_into_tree[$st["id"]]); -//echo "
"; - if (is_array($this->pg_into_tree[$st["id"]])) - { - foreach($this->pg_into_tree[$st["id"]] as $pg) - { - switch ($pg["type"]) - { - case "pg_alias": - if ($this->pg_mapping[$pg["id"]] == "") - { - $ilLog->write("LM Import: No PageObject for PageAlias ". - $pg["id"]." found! (Please update export installation to ILIAS 3.3.0)"); - - // Jump two levels up. First level is switch - continue 2; - } - $pg_id = $this->pg_mapping[$pg["id"]]; - break; - - case "pg": - $pg_id = $pg["id"]; - break; - } - if (!$this->lm_tree->isInTree($pg_id)) - { - $this->lm_tree->insertNode($pg_id, $st["id"]); - } - } - } - } -//echo "END: storing the tree"; + public $lng; + public $tree; + public $cnt; // counts open elements + public $current_element; // store current element type + public $learning_module; // current learning module + public $page_object; // current page object + public $lm_page_object; + public $structure_objects; // array of current structure objects + public $media_object; + public $current_object; // at the time a LearningModule, PageObject or StructureObject + public $meta_data; // current meta data object + public $paragraph; + public $table; + public $lm_tree; + public $pg_into_tree; + public $st_into_tree; + public $container = []; + public $in_page_object; // are we currently within a PageObject? true/false + public $in_meta_data; // are we currently within MetaData? true/false + public $in_media_object; + public $in_file_item; + public $in_glossary; + public $in_map_area; + public $content_object; + public $glossary_object; + public $file_item; + public $keyword_language; + public $pages_to_parse; + public $mob_mapping; + public $file_item_mapping; + public $subdir; + public $media_item; // current media item + public $loc_type; // current location type + public $map_area; // current map area + public $link_targets; // stores all objects by import id + public $qst_mapping; + public $metadata_parsing_disabled; + public $in_meta_meta_data = false; + protected $glossary_term_map = array(); + + /** + * @var ilLogger + */ + protected $log; + + /** + * Constructor + * + * @param object $a_content_object must be of type ilObjContentObject + * ilObjTest or ilObjQuestionPool + * @param string $a_xml_file xml file + * @param string $a_subdir subdirectory in import directory + * @access public + */ + public function __construct(&$a_content_object, $a_xml_file, $a_subdir, $a_import_dir = "") + { + global $DIC; + + $this->log = $DIC["ilLog"]; + $lng = $DIC->language(); + $tree = $DIC->repositoryTree(); + + $this->log = ilLoggerFactory::getLogger('lm'); + + $this->import_dir = ($a_import_dir != "") + ? $a_import_dir + : $a_content_object->getImportDirectory(); + + parent::__construct($a_xml_file); + $this->cnt = array(); + $this->current_element = array(); + $this->structure_objects = array(); + $this->content_object = $a_content_object; + //$this->lm_id = $a_lm_id; + $this->st_into_tree = array(); + $this->pg_into_tree = array(); + $this->pages_to_parse = array(); + $this->mobs_with_int_links = array(); + $this->mob_mapping = array(); + $this->file_item_mapping = array(); + $this->pg_mapping = array(); + $this->link_targets = array(); + $this->subdir = $a_subdir; + $this->lng = $lng; + $this->tree = $tree; + $this->inside_code = false; + $this->qst_mapping = array(); + $this->coType = $this->content_object->getType(); + $this->metadata_parsing_disabled = false; + + if (($this->coType != "tst") and ($this->coType != "qpl")) { + $this->lm_tree = new ilTree($this->content_object->getId()); + $this->lm_tree->setTreeTablePK("lm_id"); + $this->lm_tree->setTableNames('lm_tree', 'lm_data'); + } + //$this->lm_tree->addTree($a_lm_id, 1); happens in ilObjLearningModuleGUI + } + + /** + * set event handlers + * + * @param resource reference to the xml parser + * @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'); + } + + /** + * Set import mapping + * @param ilImportMapping $mapping + */ + public function setImportMapping(ilImportMapping $mapping = null) + { + $this->mapping = $mapping; + } + + + /** + * start parser + */ + public function startParsing() + { + $this->log->debug("start"); + + //echo "start parsing
"; + parent::startParsing(); + //echo "storeTree
"; + $this->storeTree(); + //echo "processPagesToParse
"; + $this->processPagesToParse(); + //echo "copyMobFiles
"; + $this->copyMobFiles(); + //echo "copyFileItems
"; + $this->copyFileItems(); + //echo "
END Parsing"; exit; + } + + + /** + * insert StructureObjects and PageObjects into tree + */ + public function storeTree() + { + $ilLog = $this->log; + + //echo "Storing the tree
"; + foreach ($this->st_into_tree as $st) { + //echo "insert st id: ".$st["id"].", parent:".$st["parent"]."
"; + $this->lm_tree->insertNode($st["id"], $st["parent"]); + //echo "done
"; + //var_dump($this->pg_into_tree[$st["id"]]); + //echo "
"; + if (is_array($this->pg_into_tree[$st["id"]])) { + foreach ($this->pg_into_tree[$st["id"]] as $pg) { + switch ($pg["type"]) { + case "pg_alias": + if ($this->pg_mapping[$pg["id"]] == "") { + $ilLog->write("LM Import: No PageObject for PageAlias " . + $pg["id"] . " found! (Please update export installation to ILIAS 3.3.0)"); + + // Jump two levels up. First level is switch + continue 2; + } + $pg_id = $this->pg_mapping[$pg["id"]]; + break; + + case "pg": + $pg_id = $pg["id"]; + break; + } + if (!$this->lm_tree->isInTree($pg_id)) { + $this->lm_tree->insertNode($pg_id, $st["id"]); + } + } + } + } + //echo "END: storing the tree"; //exit; - } - - - /** - * parse pages that contain files, mobs and/or internal links - */ - function processPagesToParse() - { - /* - $pg_mapping = array(); - foreach($this->pg_mapping as $key => $value) - { - $pg_mapping[$key] = "il__pg_".$value; - }*/ -//echo "
processIntLinks"; flush(); - - // outgoin internal links - foreach($this->pages_to_parse as $page_id) - { - $page_arr = explode(":", $page_id); -//echo "
resolve:".$this->content_object->getType().":".$page_id; flush(); - switch($page_arr[0]) - { - case "lm": - switch ($this->content_object->getType()) - { - case "lm": - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - $page_obj = new ilLMPage($page_arr[1]); - break; - - default: - die("Unknown content type ".$this->content_object->getType()); - } - - break; - - case "gdf": - include_once("./Modules/Glossary/classes/class.ilGlossaryDefPage.php"); - $page_obj = new ilGlossaryDefPage($page_arr[1]); - break; - - case "qpl": - $page_obj = new ilAssQuestionPage($page_arr[1]); - break; - } - $page_obj->buildDom(); - $page_obj->resolveIntLinks(); - $page_obj->resolveIIMMediaAliases($this->mob_mapping); - if (in_array($this->coType, array("lm"))) - { - $page_obj->resolveQuestionReferences($this->qst_mapping); - } - $page_obj->update(false); - - if ($page_arr[0] == "gdf") - { - $def = new ilGlossaryDefinition($page_arr[1]); - $def->updateShortText(); - } - - unset($page_obj); - } - -//echo "
map area internal links"; flush(); - // outgoins map area (mob) internal links - foreach($this->mobs_with_int_links as $mob_id) - { - ilMediaItem::_resolveMapAreaLinks($mob_id); - } - -//echo "
incoming interna links"; flush(); - // incoming internal links - $done = array(); - foreach ($this->link_targets as $link_target) - { -//echo "doin link target:".$link_target.":
"; - $link_arr = explode("_", $link_target); - $target_inst = $link_arr[1]; - $target_type = $link_arr[2]; - $target_id = $link_arr[3]; -//echo "
-".$target_type."-".$target_id."-".$target_inst."-"; - $sources = ilInternalLink::_getSourcesOfTarget($target_type, $target_id, $target_inst); - foreach($sources as $key => $source) - { -//echo "got source:".$key.":
"; - if(in_array($key, $done)) - { - continue; - } - $type_arr = explode(":", $source["type"]); - - // content object pages - if ($type_arr[1] == "pg") - { - if (ilPageObject::_exists($type_arr[0],$source["id"])) - { - include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); - $page_object = ilPageObjectFactory::getInstance($type_arr[0], $source["id"]); - $page_object->buildDom(); - $page_object->resolveIntLinks(); - $page_object->update(); - unset($page_object); - } - } - - // eventually correct links in questions to learning modules - if ($type_arr[0] == "qst") - { - require_once "./Modules/TestQuestionPool/classes/class.assQuestion.php"; - assQuestion::_resolveIntLinks($source["id"]); - } - // eventually correct links in survey questions to learning modules - if ($type_arr[0] == "sqst") - { - require_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - SurveyQuestion::_resolveIntLinks($source["id"]); - } - $done[$key] = $key; - } - } - } - - - /** - * copy multimedia object files from import zip file to mob directory - */ - function copyMobFiles() - { - $imp_dir = $this->import_dir; - foreach ($this->mob_mapping as $origin_id => $mob_id) - { - if(empty($origin_id)) - { - continue; - } - - /* - $origin_arr = explode("_", $origin_id); - if ($origin_arr[2] == "el") // imagemap - { - $obj_dir = "imagemap".$origin_arr[3]; - } - else // normal media object - { - $obj_dir = "mm".$origin_arr[3]; - }*/ - - $obj_dir = $origin_id; - $source_dir = $imp_dir."/".$this->subdir."/objects/".$obj_dir; - $target_dir = ilUtil::getWebspaceDir()."/mobs/mm_".$mob_id; - - if (@is_dir($source_dir)) - { - // make target directory - ilUtil::makeDir($target_dir); - //@mkdir($target_dir); - //@chmod($target_dir, 0755); - - if (@is_dir($target_dir)) - { - ilLoggerFactory::getLogger("mob")->debug("s:-$source_dir-,t:-$target_dir-"); - ilUtil::rCopy(realpath($source_dir), realpath($target_dir)); - } - } - } - } - - /** - * copy files of file items - */ - function copyFileItems() - { - $imp_dir = $this->import_dir; - foreach ($this->file_item_mapping as $origin_id => $file_id) - { - if(empty($origin_id)) - { - continue; - } - $obj_dir = $origin_id; - $source_dir = $imp_dir."/".$this->subdir."/objects/".$obj_dir; - - include_once("./Modules/File/classes/class.ilObjFile.php"); - $file_obj = new ilObjFile($file_id, false); - //$target_dir = ilUtil::getDataDir()."/files/file_".$file_id; - $target_dir = $file_obj->getDirectory(); - if (@is_dir($source_dir)) - { - // make target directory - ilUtil::makeDir($target_dir); - //@mkdir($target_dir); - //@chmod($target_dir, 0755); - - if (@is_dir($target_dir)) - { - ilUtil::rCopy(realpath($source_dir), realpath($target_dir)); - } - } - $test = $file_obj->determineFilesize(); - $file_obj->update(); - } - } - - /** - * set question import ident to pool/test question id mapping - */ - function setQuestionMapping($a_map) - { - $this->qst_mapping = $a_map; - } - - - /* - * update parsing status for a element begin - */ - function beginElement($a_name) - { - if(!isset($this->status["$a_name"])) - { - $this->cnt[$a_name] == 1; - } - else - { - $this->cnt[$a_name]++; - } - $this->current_element[count($this->current_element)] = $a_name; - } - - /* - * update parsing status for an element ending - * - * @param string $a_name element name - */ - function endElement($a_name) - { - $this->cnt[$a_name]--; - unset ($this->current_element[count($this->current_element) - 1]); - } - - /* - * returns current element - */ - function getCurrentElement() - { - return ($this->current_element[count($this->current_element) - 1]); - } - - /* - * returns number of current open elements of type $a_name - * - * @param string $a_name element name - */ - function getOpenCount($a_name) - { - if (isset($this->cnt[$a_name])) - { - return $this->cnt[$a_name]; - } - else - { - return 0; - } - - } - - /** - * generate a tag with given name and attributes - * - * @param string "start" | "end" for starting or ending tag - * @param string element/tag name - * @param array array of attributes - */ - function buildTag ($type, $name, $attr="") - { - $tag = "<"; - - if ($type == "end") - $tag.= "/"; - - $tag.= $name; - - if (is_array($attr)) - { - foreach ($attr as $k => $v) { - $tag .= " " . $k . "=\"$v\""; - } - } - - $tag.= ">"; - - return $tag; - } - - /** - * handler for begin of element - * - * @param resource $a_xml_parser xml parser - * @param string $a_name element name - * @param array $a_attribs element attributes array - */ - function handlerBeginTag($a_xml_parser,$a_name,$a_attribs) - { -//echo "BEGIN TAG: $a_name
"; flush(); - switch($a_name) - { - case "ContentObject": - $this->current_object = $this->content_object; + } + + + /** + * parse pages that contain files, mobs and/or internal links + */ + public function processPagesToParse() + { + /* + $pg_mapping = array(); + foreach($this->pg_mapping as $key => $value) + { + $pg_mapping[$key] = "il__pg_".$value; + }*/ + //echo "
processIntLinks"; flush(); + + // outgoin internal links + foreach ($this->pages_to_parse as $page_id) { + $page_arr = explode(":", $page_id); + //echo "
resolve:".$this->content_object->getType().":".$page_id; flush(); + switch ($page_arr[0]) { + case "lm": + switch ($this->content_object->getType()) { + case "lm": + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + $page_obj = new ilLMPage($page_arr[1]); + break; + + default: + die("Unknown content type " . $this->content_object->getType()); + } + + break; + + case "gdf": + include_once("./Modules/Glossary/classes/class.ilGlossaryDefPage.php"); + $page_obj = new ilGlossaryDefPage($page_arr[1]); + break; + + case "qpl": + $page_obj = new ilAssQuestionPage($page_arr[1]); + break; + } + $page_obj->buildDom(); + $page_obj->resolveIntLinks(); + $page_obj->resolveIIMMediaAliases($this->mob_mapping); + if (in_array($this->coType, array("lm"))) { + $page_obj->resolveQuestionReferences($this->qst_mapping); + } + $page_obj->update(false); + + if ($page_arr[0] == "gdf") { + $def = new ilGlossaryDefinition($page_arr[1]); + $def->updateShortText(); + } + + unset($page_obj); + } + + //echo "
map area internal links"; flush(); + // outgoins map area (mob) internal links + foreach ($this->mobs_with_int_links as $mob_id) { + ilMediaItem::_resolveMapAreaLinks($mob_id); + } + + //echo "
incoming interna links"; flush(); + // incoming internal links + $done = array(); + foreach ($this->link_targets as $link_target) { + //echo "doin link target:".$link_target.":
"; + $link_arr = explode("_", $link_target); + $target_inst = $link_arr[1]; + $target_type = $link_arr[2]; + $target_id = $link_arr[3]; + //echo "
-".$target_type."-".$target_id."-".$target_inst."-"; + $sources = ilInternalLink::_getSourcesOfTarget($target_type, $target_id, $target_inst); + foreach ($sources as $key => $source) { + //echo "got source:".$key.":
"; + if (in_array($key, $done)) { + continue; + } + $type_arr = explode(":", $source["type"]); + + // content object pages + if ($type_arr[1] == "pg") { + if (ilPageObject::_exists($type_arr[0], $source["id"])) { + include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); + $page_object = ilPageObjectFactory::getInstance($type_arr[0], $source["id"]); + $page_object->buildDom(); + $page_object->resolveIntLinks(); + $page_object->update(); + unset($page_object); + } + } + + // eventually correct links in questions to learning modules + if ($type_arr[0] == "qst") { + require_once "./Modules/TestQuestionPool/classes/class.assQuestion.php"; + assQuestion::_resolveIntLinks($source["id"]); + } + // eventually correct links in survey questions to learning modules + if ($type_arr[0] == "sqst") { + require_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + SurveyQuestion::_resolveIntLinks($source["id"]); + } + $done[$key] = $key; + } + } + } + + + /** + * copy multimedia object files from import zip file to mob directory + */ + public function copyMobFiles() + { + $imp_dir = $this->import_dir; + foreach ($this->mob_mapping as $origin_id => $mob_id) { + if (empty($origin_id)) { + continue; + } + + /* + $origin_arr = explode("_", $origin_id); + if ($origin_arr[2] == "el") // imagemap + { + $obj_dir = "imagemap".$origin_arr[3]; + } + else // normal media object + { + $obj_dir = "mm".$origin_arr[3]; + }*/ + + $obj_dir = $origin_id; + $source_dir = $imp_dir . "/" . $this->subdir . "/objects/" . $obj_dir; + $target_dir = ilUtil::getWebspaceDir() . "/mobs/mm_" . $mob_id; + + if (@is_dir($source_dir)) { + // make target directory + ilUtil::makeDir($target_dir); + //@mkdir($target_dir); + //@chmod($target_dir, 0755); + + if (@is_dir($target_dir)) { + ilLoggerFactory::getLogger("mob")->debug("s:-$source_dir-,t:-$target_dir-"); + ilUtil::rCopy(realpath($source_dir), realpath($target_dir)); + } + } + } + } + + /** + * copy files of file items + */ + public function copyFileItems() + { + $imp_dir = $this->import_dir; + foreach ($this->file_item_mapping as $origin_id => $file_id) { + if (empty($origin_id)) { + continue; + } + $obj_dir = $origin_id; + $source_dir = $imp_dir . "/" . $this->subdir . "/objects/" . $obj_dir; + + include_once("./Modules/File/classes/class.ilObjFile.php"); + $file_obj = new ilObjFile($file_id, false); + //$target_dir = ilUtil::getDataDir()."/files/file_".$file_id; + $target_dir = $file_obj->getDirectory(); + if (@is_dir($source_dir)) { + // make target directory + ilUtil::makeDir($target_dir); + //@mkdir($target_dir); + //@chmod($target_dir, 0755); + + if (@is_dir($target_dir)) { + ilUtil::rCopy(realpath($source_dir), realpath($target_dir)); + } + } + $test = $file_obj->determineFilesize(); + $file_obj->update(); + } + } + + /** + * set question import ident to pool/test question id mapping + */ + public function setQuestionMapping($a_map) + { + $this->qst_mapping = $a_map; + } + + + /* + * update parsing status for a element begin + */ + public function beginElement($a_name) + { + if (!isset($this->status["$a_name"])) { + $this->cnt[$a_name] == 1; + } else { + $this->cnt[$a_name]++; + } + $this->current_element[count($this->current_element)] = $a_name; + } + + /* + * update parsing status for an element ending + * + * @param string $a_name element name + */ + public function endElement($a_name) + { + $this->cnt[$a_name]--; + unset($this->current_element[count($this->current_element) - 1]); + } + + /* + * returns current element + */ + public function getCurrentElement() + { + return ($this->current_element[count($this->current_element) - 1]); + } + + /* + * returns number of current open elements of type $a_name + * + * @param string $a_name element name + */ + public function getOpenCount($a_name) + { + if (isset($this->cnt[$a_name])) { + return $this->cnt[$a_name]; + } else { + return 0; + } + } + + /** + * generate a tag with given name and attributes + * + * @param string "start" | "end" for starting or ending tag + * @param string element/tag name + * @param array array of attributes + */ + public function buildTag($type, $name, $attr="") + { + $tag = "<"; + + if ($type == "end") { + $tag.= "/"; + } + + $tag.= $name; + + if (is_array($attr)) { + foreach ($attr as $k => $v) { + $tag .= " " . $k . "=\"$v\""; + } + } + + $tag.= ">"; + + return $tag; + } + + /** + * handler for begin of element + * + * @param resource $a_xml_parser xml parser + * @param string $a_name element name + * @param array $a_attribs element attributes array + */ + public function handlerBeginTag($a_xml_parser, $a_name, $a_attribs) + { + //echo "BEGIN TAG: $a_name
"; flush(); + switch ($a_name) { + case "ContentObject": + $this->current_object = $this->content_object; //echo "
Parser:CObjType:".$a_attribs["Type"]; - if ($a_attribs["Type"] == "Glossary") - { - $this->glossary_object = $this->content_object; - } - break; + if ($a_attribs["Type"] == "Glossary") { + $this->glossary_object = $this->content_object; + } + break; - case "StructureObject": + case "StructureObject": //echo "

StructureOB-SET-".count($this->structure_objects)."
"; - $this->structure_objects[count($this->structure_objects)] - = new ilStructureObject($this->content_object); - $this->current_object = $this->structure_objects[count($this->structure_objects) - 1]; - $this->current_object->setLMId($this->content_object->getId()); - // new meta data handling: we create the structure - // object already here, this should also create a - // md entry - $this->current_object->create(true); - break; - - case "PageObject": - $this->in_page_object = true; - $this->cur_qid = ""; - if (($this->coType != "tst") and ($this->coType != "qpl")) - { - $this->lm_page_object = new ilLMPageObject($this->content_object); - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - $this->page_object = new ilLMPage(); - $this->lm_page_object->setLMId($this->content_object->getId()); - $this->lm_page_object->assignPageObject($this->page_object); - $this->current_object = $this->lm_page_object; - } - else - { - include_once("./Modules/TestQuestionPool/classes/class.ilAssQuestionPage.php"); - $this->page_object = new ilAssQuestionPage(); - } - break; - - case "PageAlias": - if (($this->coType != "tst") and ($this->coType != "qpl")) - { - $this->lm_page_object->setAlias(true); - $this->lm_page_object->setOriginID($a_attribs["OriginId"]); - } - break; - - case "MediaObject": - $this->in_media_object = true; + $this->structure_objects[count($this->structure_objects)] + = new ilStructureObject($this->content_object); + $this->current_object = $this->structure_objects[count($this->structure_objects) - 1]; + $this->current_object->setLMId($this->content_object->getId()); + // new meta data handling: we create the structure + // object already here, this should also create a + // md entry + $this->current_object->create(true); + break; + + case "PageObject": + $this->in_page_object = true; + $this->cur_qid = ""; + if (($this->coType != "tst") and ($this->coType != "qpl")) { + $this->lm_page_object = new ilLMPageObject($this->content_object); + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + $this->page_object = new ilLMPage(); + $this->lm_page_object->setLMId($this->content_object->getId()); + $this->lm_page_object->assignPageObject($this->page_object); + $this->current_object = $this->lm_page_object; + } else { + include_once("./Modules/TestQuestionPool/classes/class.ilAssQuestionPage.php"); + $this->page_object = new ilAssQuestionPage(); + } + break; + + case "PageAlias": + if (($this->coType != "tst") and ($this->coType != "qpl")) { + $this->lm_page_object->setAlias(true); + $this->lm_page_object->setOriginID($a_attribs["OriginId"]); + } + break; + + case "MediaObject": + $this->in_media_object = true; + // no break case "InteractiveImage": - $this->media_meta_start = true; - $this->media_meta_cache = array(); - $this->media_object = new ilObjMediaObject(); - break; + $this->media_meta_start = true; + $this->media_meta_cache = array(); + $this->media_object = new ilObjMediaObject(); + break; - case "MediaAlias": + case "MediaAlias": //echo "
---NEW MEDIAALIAS---
"; - $this->media_object->setAlias(true); - $this->media_object->setImportId($a_attribs["OriginId"]); - if (is_object($this->page_object)) - { - $this->page_object->needsImportParsing(true); - } - break; - - case "MediaItem": - case "MediaAliasItem": - $this->in_media_item = true; - $this->media_item = new ilMediaItem(); - $this->media_item->setPurpose($a_attribs["Purpose"]); - /*if ($a_name == "MediaItem") - { - $this->media_item->setHighlightMode($a_attribs["MapHighlightMode"]); - $this->media_item->setHighlightClass($a_attribs["MapHighlightClass"]); - }*/ - break; - - case "Layout": - if (is_object($this->media_object) && $this->in_media_object) - { - $this->media_item->setWidth($a_attribs["Width"]); - $this->media_item->setHeight($a_attribs["Height"]); - $this->media_item->setHAlign($a_attribs["HorizontalAlign"]); - } - break; - - case "Parameter": - if (is_object($this->media_object) && $this->in_media_object) - { - $this->media_item->setParameter($a_attribs["Name"], $a_attribs["Value"]); - } - break; - - case "MapArea": - $this->in_map_area = true; - $this->map_area = new ilMapArea(); - $this->map_area->setShape($a_attribs["Shape"]); - $this->map_area->setCoords($a_attribs["Coords"]); - $this->map_area->setHighlightMode($a_attribs["HighlightMode"]); - $this->map_area->setHighlightClass($a_attribs["HighlightClass"]); - break; - - case "Glossary": - $this->in_glossary = true; - if ($this->content_object->getType() != "glo") - { - $this->glossary_object = new ilObjGlossary(); - $this->glossary_object->setTitle(""); - $this->glossary_object->setDescription(""); - $this->glossary_object->create(true); - $this->glossary_object->createReference(); - $parent = $this->tree->getParentNodeData($this->content_object->getRefId()); - $this->glossary_object->putInTree($parent["child"]); - $this->glossary_object->setPermissions($parent["child"]); - } - $this->current_object = $this->glossary_object; - break; - - case "GlossaryItem": - $this->glossary_term = new ilGlossaryTerm(); - $this->glossary_term->setGlossaryId($this->glossary_object->getId()); - $this->glossary_term->setLanguage($a_attribs["Language"]); - $this->glossary_term->setImportId($a_attribs["Id"]); - $this->link_targets[$a_attribs["Id"]] = $a_attribs["Id"]; - break; - - case "Definition": - $this->in_glossary_definition = true; - $this->glossary_definition = new ilGlossaryDefinition(); - include_once("./Modules/Glossary/classes/class.ilGlossaryDefPage.php"); - $this->page_object = new ilGlossaryDefPage(); - $this->page_object->setParentId($this->glossary_term->getGlossaryId()); - $this->glossary_definition->setTermId($this->glossary_term->getId()); - $this->glossary_definition->assignPageObject($this->page_object); - $this->current_object = $this->glossary_definition; - $this->glossary_definition->create(true); - // see bug #12465, we need to clear xml after creation, since it will be - // otherwise, and appendXML calls will lead to "...." - $this->page_object->setXMLContent(""); - break; - - case "FileItem": - $this->in_file_item = true; - $this->file_item = new ilObjFile(); - $this->file_item->setTitle("dummy"); - $this->file_item->setMode("filelist"); - if (is_object($this->page_object)) - { - $this->page_object->needsImportParsing(true); - } - break; - - case "Paragraph": - if ($a_attribs["Characteristic"] == "Code") - { - $this->inside_code = true; - } - break; - - case "Properties": - $this->in_properties = true; - break; - - case "Property": - if ($this->content_object->getType() == "lm") - { - switch($a_attribs["Name"]) - { - case "Layout": - $this->content_object->setLayout($a_attribs["Value"]); - break; - - case "PageHeader": - $this->content_object->setPageHeader($a_attribs["Value"]); - break; - - case "TOCMode": - $this->content_object->setTOCMode($a_attribs["Value"]); - break; - - case "ActiveLMMenu": - $this->content_object->setActiveLMMenu( - ilUtil::yn2tf($a_attribs["Value"])); - break; - - case "ActiveNumbering": - $this->content_object->setActiveNumbering( - ilUtil::yn2tf($a_attribs["Value"])); - break; - - case "ActiveTOC": - $this->content_object->setActiveTOC( - ilUtil::yn2tf($a_attribs["Value"])); - break; - - case "ActivePrintView": - $this->content_object->setActivePrintView( - ilUtil::yn2tf($a_attribs["Value"])); - break; - - case "CleanFrames": - $this->content_object->setCleanFrames( - ilUtil::yn2tf($a_attribs["Value"])); - break; - - case "PublicNotes": - $this->content_object->setPublicNotes( - ilUtil::yn2tf($a_attribs["Value"])); - break; - - case "HistoryUserComments": - $this->content_object->setHistoryUserComments( - ilUtil::yn2tf($a_attribs["Value"])); - break; - - case "Rating": - $this->content_object->setRating( - ilUtil::yn2tf($a_attribs["Value"])); - break; - - case "RatingPages": - $this->content_object->setRatingPages( - ilUtil::yn2tf($a_attribs["Value"])); - break; - - case "HeaderPage": - if ($a_attribs["Value"] != "") - { - if ($this->pg_mapping[$a_attribs["Value"]] > 0) - { - $this->content_object->setHeaderPage( - $this->pg_mapping[$a_attribs["Value"]]); - } - } - break; - - case "FooterPage": - if ($a_attribs["Value"] != "") - { - if ($this->pg_mapping[$a_attribs["Value"]] > 0) - { - $this->content_object->setFooterPage( - $this->pg_mapping[$a_attribs["Value"]]); - } - } - break; - - case "LayoutPerPage": - $this->content_object->setLayoutPerPage($a_attribs["Value"]); - break; - - case "ProgressIcons": - $this->content_object->setProgressIcons($a_attribs["Value"]); - break; - - case "StoreTries": - $this->content_object->setStoreTries($a_attribs["Value"]); - break; - - case "RestrictForwardNavigation": - $this->content_object->setRestrictForwardNavigation($a_attribs["Value"]); - break; - - case "DisableDefaultFeedback": - $this->content_object->setDisableDefaultFeedback($a_attribs["Value"]); - break; - - } - //echo "
+".$a_attribs["Name"]."+"; - } - break; - - //////////////////////////////////////////////// - /// Meta Data Section - //////////////////////////////////////////////// - case "MetaData": - $this->in_meta_data = true; + $this->media_object->setAlias(true); + $this->media_object->setImportId($a_attribs["OriginId"]); + if (is_object($this->page_object)) { + $this->page_object->needsImportParsing(true); + } + break; + + case "MediaItem": + case "MediaAliasItem": + $this->in_media_item = true; + $this->media_item = new ilMediaItem(); + $this->media_item->setPurpose($a_attribs["Purpose"]); + /*if ($a_name == "MediaItem") + { + $this->media_item->setHighlightMode($a_attribs["MapHighlightMode"]); + $this->media_item->setHighlightClass($a_attribs["MapHighlightClass"]); + }*/ + break; + + case "Layout": + if (is_object($this->media_object) && $this->in_media_object) { + $this->media_item->setWidth($a_attribs["Width"]); + $this->media_item->setHeight($a_attribs["Height"]); + $this->media_item->setHAlign($a_attribs["HorizontalAlign"]); + } + break; + + case "Parameter": + if (is_object($this->media_object) && $this->in_media_object) { + $this->media_item->setParameter($a_attribs["Name"], $a_attribs["Value"]); + } + break; + + case "MapArea": + $this->in_map_area = true; + $this->map_area = new ilMapArea(); + $this->map_area->setShape($a_attribs["Shape"]); + $this->map_area->setCoords($a_attribs["Coords"]); + $this->map_area->setHighlightMode($a_attribs["HighlightMode"]); + $this->map_area->setHighlightClass($a_attribs["HighlightClass"]); + break; + + case "Glossary": + $this->in_glossary = true; + if ($this->content_object->getType() != "glo") { + $this->glossary_object = new ilObjGlossary(); + $this->glossary_object->setTitle(""); + $this->glossary_object->setDescription(""); + $this->glossary_object->create(true); + $this->glossary_object->createReference(); + $parent = $this->tree->getParentNodeData($this->content_object->getRefId()); + $this->glossary_object->putInTree($parent["child"]); + $this->glossary_object->setPermissions($parent["child"]); + } + $this->current_object = $this->glossary_object; + break; + + case "GlossaryItem": + $this->glossary_term = new ilGlossaryTerm(); + $this->glossary_term->setGlossaryId($this->glossary_object->getId()); + $this->glossary_term->setLanguage($a_attribs["Language"]); + $this->glossary_term->setImportId($a_attribs["Id"]); + $this->link_targets[$a_attribs["Id"]] = $a_attribs["Id"]; + break; + + case "Definition": + $this->in_glossary_definition = true; + $this->glossary_definition = new ilGlossaryDefinition(); + include_once("./Modules/Glossary/classes/class.ilGlossaryDefPage.php"); + $this->page_object = new ilGlossaryDefPage(); + $this->page_object->setParentId($this->glossary_term->getGlossaryId()); + $this->glossary_definition->setTermId($this->glossary_term->getId()); + $this->glossary_definition->assignPageObject($this->page_object); + $this->current_object = $this->glossary_definition; + $this->glossary_definition->create(true); + // see bug #12465, we need to clear xml after creation, since it will be + // otherwise, and appendXML calls will lead to "...." + $this->page_object->setXMLContent(""); + break; + + case "FileItem": + $this->in_file_item = true; + $this->file_item = new ilObjFile(); + $this->file_item->setTitle("dummy"); + $this->file_item->setMode("filelist"); + if (is_object($this->page_object)) { + $this->page_object->needsImportParsing(true); + } + break; + + case "Paragraph": + if ($a_attribs["Characteristic"] == "Code") { + $this->inside_code = true; + } + break; + + case "Properties": + $this->in_properties = true; + break; + + case "Property": + if ($this->content_object->getType() == "lm") { + switch ($a_attribs["Name"]) { + case "Layout": + $this->content_object->setLayout($a_attribs["Value"]); + break; + + case "PageHeader": + $this->content_object->setPageHeader($a_attribs["Value"]); + break; + + case "TOCMode": + $this->content_object->setTOCMode($a_attribs["Value"]); + break; + + case "ActiveLMMenu": + $this->content_object->setActiveLMMenu( + ilUtil::yn2tf($a_attribs["Value"]) + ); + break; + + case "ActiveNumbering": + $this->content_object->setActiveNumbering( + ilUtil::yn2tf($a_attribs["Value"]) + ); + break; + + case "ActiveTOC": + $this->content_object->setActiveTOC( + ilUtil::yn2tf($a_attribs["Value"]) + ); + break; + + case "ActivePrintView": + $this->content_object->setActivePrintView( + ilUtil::yn2tf($a_attribs["Value"]) + ); + break; + + case "CleanFrames": + $this->content_object->setCleanFrames( + ilUtil::yn2tf($a_attribs["Value"]) + ); + break; + + case "PublicNotes": + $this->content_object->setPublicNotes( + ilUtil::yn2tf($a_attribs["Value"]) + ); + break; + + case "HistoryUserComments": + $this->content_object->setHistoryUserComments( + ilUtil::yn2tf($a_attribs["Value"]) + ); + break; + + case "Rating": + $this->content_object->setRating( + ilUtil::yn2tf($a_attribs["Value"]) + ); + break; + + case "RatingPages": + $this->content_object->setRatingPages( + ilUtil::yn2tf($a_attribs["Value"]) + ); + break; + + case "HeaderPage": + if ($a_attribs["Value"] != "") { + if ($this->pg_mapping[$a_attribs["Value"]] > 0) { + $this->content_object->setHeaderPage( + $this->pg_mapping[$a_attribs["Value"]] + ); + } + } + break; + + case "FooterPage": + if ($a_attribs["Value"] != "") { + if ($this->pg_mapping[$a_attribs["Value"]] > 0) { + $this->content_object->setFooterPage( + $this->pg_mapping[$a_attribs["Value"]] + ); + } + } + break; + + case "LayoutPerPage": + $this->content_object->setLayoutPerPage($a_attribs["Value"]); + break; + + case "ProgressIcons": + $this->content_object->setProgressIcons($a_attribs["Value"]); + break; + + case "StoreTries": + $this->content_object->setStoreTries($a_attribs["Value"]); + break; + + case "RestrictForwardNavigation": + $this->content_object->setRestrictForwardNavigation($a_attribs["Value"]); + break; + + case "DisableDefaultFeedback": + $this->content_object->setDisableDefaultFeedback($a_attribs["Value"]); + break; + + } + //echo "
+".$a_attribs["Name"]."+"; + } + break; + + //////////////////////////////////////////////// + /// Meta Data Section + //////////////////////////////////////////////// + case "MetaData": + $this->in_meta_data = true; //echo "
begin meta data section -".$this->current_object->getType()."-"; - // media obejct meta data handling - // is done in the "Identifier" begin tag processing - // the rest is done here - if(!$this->in_media_object) - { - if (($this->coType != "tst") and ($this->coType != "qpl")) - { - // type pg/st - if ($this->current_object->getType() == "st" || - $this->current_object->getType() == "pg") - { - // late creation of page object - if ($this->current_object->getType() == "pg") - { - $this->lm_page_object->create(true); - } - $this->md = new ilMD($this->content_object->getId() , - $this->current_object->getId(), - $this->current_object->getType()); - } - // type gdf - else if ($this->current_object->getType() == "gdf") - { - $this->md = new ilMD($this->glossary_object->getId() , - $this->current_object->getId(), - $this->current_object->getType()); - } - // type lm, dbk, glo - else - { - if ($this->processMeta()) - { - $this->md = new ilMD($this->current_object->getId() , - 0, - $this->current_object->getType()); - } - } - } - else - { - // type qpl or tst - $this->md = new ilMD($this->content_object->getId() , - 0, - $this->current_object->getType() - ); - if ($this->md->getGeneral() != false) - { - $this->metadata_parsing_disabled = true; - $this->enableMDParsing(false); - } - } - } - break; - - // Identifier - case "Identifier": - - // begin-patch optes_lok_export - if($this->in_meta_data && $this->current_object instanceof ilStructureObject) - { - if($this->mapping instanceof ilImportMapping) - { - $import_id_parsed = ilUtil::parseImportId($a_attribs['Entry']); - if($import_id_parsed['type'] == 'st') - { - $this->mapping->addMapping( - 'Modules/LearningModule', - 'lm_tree', - $import_id_parsed['id'], - $this->current_object->getId() - ); - } - } - } - // end-patch optes_lok_export - - // please note: Meta-Metadata and MetaData are different tags! - if (!$this->in_meta_meta_data) - { - if ($this->in_meta_data && !$this->in_glossary_definition) - { - if (!$this->in_media_object) - { - $this->current_object->setImportId($a_attribs["Entry"]); - } - $this->link_targets[$a_attribs["Entry"]] = $a_attribs["Entry"]; - } - if ($this->in_file_item) - { - if ($this->file_item_mapping[$a_attribs["Entry"]] == "") - { - $this->file_item->create(); - $this->file_item->setImportId($a_attribs["Entry"]); - $this->file_item_mapping[$a_attribs["Entry"]] = $this->file_item->getId(); - } - } - if ($this->in_meta_data && $this->in_media_object) - { -//echo "looking for -".$a_attribs["Entry"]."-
"; - - $mob_id = $this->mob_mapping[$a_attribs["Entry"]]; - - // within learning module import, usually a media object - // has already been created with a media alias tag - if ($mob_id > 0) - { - $this->media_object = new ilObjMediaObject($mob_id); - } - else // in glossaries the media objects precede the definitions - // so we don't have an object already - { - $this->media_object = new ilObjMediaObject(); - $this->media_object->create(true, false); - $this->mob_mapping[$a_attribs["Entry"]] - = $this->media_object->getId(); - } - $this->media_object->setImportId($a_attribs["Entry"]); - $this->md = new ilMD(0 , - $this->media_object->getId(), - "mob"); - $this->emptyMediaMetaCache($a_xml_parser); - } - } - break; - - case "Meta-Metadata": - $this->in_meta_meta_data = true; - break; - - // Internal Link - case "IntLink": - if (is_object($this->page_object)) - { - $this->page_object->setContainsIntLink(true); - } - if ($this->in_map_area) - { -//echo "intlink:maparea:
"; - $this->map_area->setLinkType(IL_INT_LINK); - $this->map_area->setTarget($a_attribs["Target"]); - $this->map_area->setType($a_attribs["Type"]); - $this->map_area->setTargetFrame($a_attribs["TargetFrame"]); - if (is_object($this->media_object)) - { -//echo ":setContainsLink:
"; - $this->media_object->setContainsIntLink(true); - } - } - break; - - // External Link - case "ExtLink": - if ($this->in_map_area) - { - $this->map_area->setLinkType(IL_EXT_LINK); - $this->map_area->setHref($a_attribs["Href"]); - $this->map_area->setExtTitle($a_attribs["Title"]); - } - break; - - // Question - case "Question": - $this->cur_qid = $a_attribs["QRef"]; - $this->page_object->setContainsQuestion(true); - break; - - case "Location": - $this->loc_type = $a_attribs["Type"]; - break; - - } - $this->beginElement($a_name); - - // append content to page xml content - if(($this->in_page_object || $this->in_glossary_definition) - && !$this->in_meta_data && !$this->in_media_object) - { - if ($a_name == "Definition") - { - $app_name = "PageObject"; - $app_attribs = array(); - } - else - { - $app_name = $a_name; - $app_attribs = $a_attribs; - } - - // change identifier entry of file items to new local file id - if ($this->in_file_item && $app_name == "Identifier") - { - $app_attribs["Entry"] = "il__file_".$this->file_item_mapping[$a_attribs["Entry"]]; - //$app_attribs["Entry"] = "il__file_".$this->file_item->getId(); - } - - $this->page_object->appendXMLContent($this->buildTag("start", $app_name, $app_attribs)); -//echo "  after append, xml:".$this->page_object->getXMLContent().":
"; - } - - - // call meta data handler - if ($this->in_meta_data && $this->processMeta()) - { - // cache beginning of meta data within media object tags - // (we need to know the id at the begin of meta elements within - // media objects, after the "Identifier" tag has been processed - // we send the cached data to the meta xml handler) - if ($this->in_media_object && $this->media_meta_start) - { - $this->media_meta_cache[] = - array("type" => "handlerBeginTag", "par1" => $a_name, "par2" => $a_attribs); - } - else - { - if ($a_name == "Identifier") - { - if (!$this->in_media_object) - { - $a_attribs["Entry"] = "il__".$this->current_object->getType(). - "_".$this->current_object->getId(); - } - else - { - $a_attribs["Entry"] = "il__mob". - "_".$this->media_object->getId(); - } - $a_attribs["Catalog"] = "ILIAS"; - } - - parent::handlerBeginTag($a_xml_parser,$a_name,$a_attribs); - } - } - } - - /** - * check whether meta data should be processed - */ - function processMeta() - { - // do not process second meta block in (ilias3) glossaries - // which comes right after the "Glossary" tag - if ($this->content_object->getType() == "glo" && - $this->in_glossary && !$this->in_media_object - && !$this->in_glossary_definition) - { - return false; - } - - return true; - } - - - /** - * handler for end of element - * - * @param resource $a_xml_parser xml parser - * @param string $a_name element name - */ - function handlerEndTag($a_xml_parser,$a_name) - { - // call meta data handler - if ($this->in_meta_data && $this->processMeta()) - { - // cache beginning of meta data within media object tags - // (we need to know the id, after that we send the cached data - // to the meta xml handler) - if ($this->in_media_object && $this->media_meta_start) - { - $this->media_meta_cache[] = - array("type" => "handlerEndTag", "par1" => $a_name); - } - else - { - parent::handlerEndTag($a_xml_parser,$a_name); - } - } - -//echo "END TAG: $a_name
"; flush(); - // append content to page xml content - if (($this->in_page_object || $this->in_glossary_definition) - && !$this->in_meta_data && !$this->in_media_object) - { - $app_name = ($a_name == "Definition") - ? "PageObject" - : $a_name; - $this->page_object->appendXMLContent($this->buildTag("end", $app_name)); - } - - switch($a_name) - { - case "StructureObject": - //unset($this->meta_data); - unset($this->structure_objects[count($this->structure_objects) - 1]); - break; - - case "PageObject": - - $this->in_page_object = false; - if (($this->coType != "tst") and ($this->coType != "qpl")) - { - if (!$this->lm_page_object->isAlias()) - { - //$this->page_object->createFromXML(); - $this->page_object->updateFromXML(); - $this->pg_mapping[$this->lm_page_object->getImportId()] - = $this->lm_page_object->getId(); - - if($this->mapping instanceof ilImportMapping) - { - $import_id_parsed = ilUtil::parseImportId($this->lm_page_object->getImportId()); - if($import_id_parsed['type'] == 'pg') - { - $this->mapping->addMapping( - 'Modules/LearningModule', - 'pg', - $import_id_parsed['id'], - $this->lm_page_object->getId() - ); - } - - } - - // collect pages with internal links - if ($this->page_object->containsIntLink()) - { - $this->pages_to_parse["lm:".$this->page_object->getId()] = "lm:".$this->page_object->getId(); - } - - // collect pages with mobs or files - if ($this->page_object->needsImportParsing()) - { - $this->pages_to_parse["lm:".$this->page_object->getId()] = "lm:".$this->page_object->getId(); - } - - // collect pages with questions - if ($this->page_object->getContainsQuestion()) - { - $this->pages_to_parse["lm:".$this->page_object->getId()] = "lm:".$this->page_object->getId(); - } - - } - } - else - { - $xml = $this->page_object->getXMLContent(); - if ($this->cur_qid != "") - { - $ids = $this->qst_mapping[$this->cur_qid]; - if ($ids["pool"] > 0) - { - // question pool question - include_once("./Modules/TestQuestionPool/classes/class.ilAssQuestionPage.php"); - $page = new ilAssQuestionPage($ids["pool"]); - $xmlcontent = str_replace($this->cur_qid, - "il__qst_".$ids["pool"], $xml); - $page->setXMLContent($xmlcontent); - $page->updateFromXML(); - if( $this->page_object->needsImportParsing() ) - { - $this->pages_to_parse["qpl:".$page->getId()] = "qpl:".$page->getId(); - } - unset($page); - } - if ($ids["test"] > 0) - { - // test question - include_once("./Modules/TestQuestionPool/classes/class.ilAssQuestionPage.php"); - $page = new ilAssQuestionPage($ids["test"]); - $xmlcontent = str_replace($this->cur_qid, - "il__qst_".$ids["test"], $xml); - $page->setXMLContent($xmlcontent); - $page->updateFromXML(); - if( $this->page_object->needsImportParsing() ) - { - $this->pages_to_parse["qpl:".$page->getId()] = "qpl:".$page->getId(); - } - unset($page); - } - } - } - - // if we are within a structure object: put page in tree - $cnt = count($this->structure_objects); + // media obejct meta data handling + // is done in the "Identifier" begin tag processing + // the rest is done here + if (!$this->in_media_object) { + if (($this->coType != "tst") and ($this->coType != "qpl")) { + // type pg/st + if ($this->current_object->getType() == "st" || + $this->current_object->getType() == "pg") { + // late creation of page object + if ($this->current_object->getType() == "pg") { + $this->lm_page_object->create(true); + } + $this->md = new ilMD( + $this->content_object->getId() , + $this->current_object->getId(), + $this->current_object->getType() + ); + } + // type gdf + elseif ($this->current_object->getType() == "gdf") { + $this->md = new ilMD( + $this->glossary_object->getId() , + $this->current_object->getId(), + $this->current_object->getType() + ); + } + // type lm, dbk, glo + else { + if ($this->processMeta()) { + $this->md = new ilMD( + $this->current_object->getId() , + 0, + $this->current_object->getType() + ); + } + } + } else { + // type qpl or tst + $this->md = new ilMD( + $this->content_object->getId(), + 0, + $this->current_object->getType() + ); + if ($this->md->getGeneral() != false) { + $this->metadata_parsing_disabled = true; + $this->enableMDParsing(false); + } + } + } + break; + + // Identifier + case "Identifier": + + // begin-patch optes_lok_export + if ($this->in_meta_data && $this->current_object instanceof ilStructureObject) { + if ($this->mapping instanceof ilImportMapping) { + $import_id_parsed = ilUtil::parseImportId($a_attribs['Entry']); + if ($import_id_parsed['type'] == 'st') { + $this->mapping->addMapping( + 'Modules/LearningModule', + 'lm_tree', + $import_id_parsed['id'], + $this->current_object->getId() + ); + } + } + } + // end-patch optes_lok_export + + // please note: Meta-Metadata and MetaData are different tags! + if (!$this->in_meta_meta_data) { + if ($this->in_meta_data && !$this->in_glossary_definition) { + if (!$this->in_media_object) { + $this->current_object->setImportId($a_attribs["Entry"]); + } + $this->link_targets[$a_attribs["Entry"]] = $a_attribs["Entry"]; + } + if ($this->in_file_item) { + if ($this->file_item_mapping[$a_attribs["Entry"]] == "") { + $this->file_item->create(); + $this->file_item->setImportId($a_attribs["Entry"]); + $this->file_item_mapping[$a_attribs["Entry"]] = $this->file_item->getId(); + } + } + if ($this->in_meta_data && $this->in_media_object) { + //echo "looking for -".$a_attribs["Entry"]."-
"; + + $mob_id = $this->mob_mapping[$a_attribs["Entry"]]; + + // within learning module import, usually a media object + // has already been created with a media alias tag + if ($mob_id > 0) { + $this->media_object = new ilObjMediaObject($mob_id); + } else { // in glossaries the media objects precede the definitions + // so we don't have an object already + $this->media_object = new ilObjMediaObject(); + $this->media_object->create(true, false); + $this->mob_mapping[$a_attribs["Entry"]] + = $this->media_object->getId(); + } + $this->media_object->setImportId($a_attribs["Entry"]); + $this->md = new ilMD( + 0 , + $this->media_object->getId(), + "mob" + ); + $this->emptyMediaMetaCache($a_xml_parser); + } + } + break; + + case "Meta-Metadata": + $this->in_meta_meta_data = true; + break; + + // Internal Link + case "IntLink": + if (is_object($this->page_object)) { + $this->page_object->setContainsIntLink(true); + } + if ($this->in_map_area) { + //echo "intlink:maparea:
"; + $this->map_area->setLinkType(IL_INT_LINK); + $this->map_area->setTarget($a_attribs["Target"]); + $this->map_area->setType($a_attribs["Type"]); + $this->map_area->setTargetFrame($a_attribs["TargetFrame"]); + if (is_object($this->media_object)) { + //echo ":setContainsLink:
"; + $this->media_object->setContainsIntLink(true); + } + } + break; + + // External Link + case "ExtLink": + if ($this->in_map_area) { + $this->map_area->setLinkType(IL_EXT_LINK); + $this->map_area->setHref($a_attribs["Href"]); + $this->map_area->setExtTitle($a_attribs["Title"]); + } + break; + + // Question + case "Question": + $this->cur_qid = $a_attribs["QRef"]; + $this->page_object->setContainsQuestion(true); + break; + + case "Location": + $this->loc_type = $a_attribs["Type"]; + break; + + } + $this->beginElement($a_name); + + // append content to page xml content + if (($this->in_page_object || $this->in_glossary_definition) + && !$this->in_meta_data && !$this->in_media_object) { + if ($a_name == "Definition") { + $app_name = "PageObject"; + $app_attribs = array(); + } else { + $app_name = $a_name; + $app_attribs = $a_attribs; + } + + // change identifier entry of file items to new local file id + if ($this->in_file_item && $app_name == "Identifier") { + $app_attribs["Entry"] = "il__file_" . $this->file_item_mapping[$a_attribs["Entry"]]; + //$app_attribs["Entry"] = "il__file_".$this->file_item->getId(); + } + + $this->page_object->appendXMLContent($this->buildTag("start", $app_name, $app_attribs)); + //echo "  after append, xml:".$this->page_object->getXMLContent().":
"; + } + + + // call meta data handler + if ($this->in_meta_data && $this->processMeta()) { + // cache beginning of meta data within media object tags + // (we need to know the id at the begin of meta elements within + // media objects, after the "Identifier" tag has been processed + // we send the cached data to the meta xml handler) + if ($this->in_media_object && $this->media_meta_start) { + $this->media_meta_cache[] = + array("type" => "handlerBeginTag", "par1" => $a_name, "par2" => $a_attribs); + } else { + if ($a_name == "Identifier") { + if (!$this->in_media_object) { + $a_attribs["Entry"] = "il__" . $this->current_object->getType() . + "_" . $this->current_object->getId(); + } else { + $a_attribs["Entry"] = "il__mob" . + "_" . $this->media_object->getId(); + } + $a_attribs["Catalog"] = "ILIAS"; + } + + parent::handlerBeginTag($a_xml_parser, $a_name, $a_attribs); + } + } + } + + /** + * check whether meta data should be processed + */ + public function processMeta() + { + // do not process second meta block in (ilias3) glossaries + // which comes right after the "Glossary" tag + if ($this->content_object->getType() == "glo" && + $this->in_glossary && !$this->in_media_object + && !$this->in_glossary_definition) { + return false; + } + + return true; + } + + + /** + * handler for end of element + * + * @param resource $a_xml_parser xml parser + * @param string $a_name element name + */ + public function handlerEndTag($a_xml_parser, $a_name) + { + // call meta data handler + if ($this->in_meta_data && $this->processMeta()) { + // cache beginning of meta data within media object tags + // (we need to know the id, after that we send the cached data + // to the meta xml handler) + if ($this->in_media_object && $this->media_meta_start) { + $this->media_meta_cache[] = + array("type" => "handlerEndTag", "par1" => $a_name); + } else { + parent::handlerEndTag($a_xml_parser, $a_name); + } + } + + //echo "END TAG: $a_name
"; flush(); + // append content to page xml content + if (($this->in_page_object || $this->in_glossary_definition) + && !$this->in_meta_data && !$this->in_media_object) { + $app_name = ($a_name == "Definition") + ? "PageObject" + : $a_name; + $this->page_object->appendXMLContent($this->buildTag("end", $app_name)); + } + + switch ($a_name) { + case "StructureObject": + //unset($this->meta_data); + unset($this->structure_objects[count($this->structure_objects) - 1]); + break; + + case "PageObject": + + $this->in_page_object = false; + if (($this->coType != "tst") and ($this->coType != "qpl")) { + if (!$this->lm_page_object->isAlias()) { + //$this->page_object->createFromXML(); + $this->page_object->updateFromXML(); + $this->pg_mapping[$this->lm_page_object->getImportId()] + = $this->lm_page_object->getId(); + + if ($this->mapping instanceof ilImportMapping) { + $import_id_parsed = ilUtil::parseImportId($this->lm_page_object->getImportId()); + if ($import_id_parsed['type'] == 'pg') { + $this->mapping->addMapping( + 'Modules/LearningModule', + 'pg', + $import_id_parsed['id'], + $this->lm_page_object->getId() + ); + } + } + + // collect pages with internal links + if ($this->page_object->containsIntLink()) { + $this->pages_to_parse["lm:" . $this->page_object->getId()] = "lm:" . $this->page_object->getId(); + } + + // collect pages with mobs or files + if ($this->page_object->needsImportParsing()) { + $this->pages_to_parse["lm:" . $this->page_object->getId()] = "lm:" . $this->page_object->getId(); + } + + // collect pages with questions + if ($this->page_object->getContainsQuestion()) { + $this->pages_to_parse["lm:" . $this->page_object->getId()] = "lm:" . $this->page_object->getId(); + } + } + } else { + $xml = $this->page_object->getXMLContent(); + if ($this->cur_qid != "") { + $ids = $this->qst_mapping[$this->cur_qid]; + if ($ids["pool"] > 0) { + // question pool question + include_once("./Modules/TestQuestionPool/classes/class.ilAssQuestionPage.php"); + $page = new ilAssQuestionPage($ids["pool"]); + $xmlcontent = str_replace( + $this->cur_qid, + "il__qst_" . $ids["pool"], + $xml + ); + $page->setXMLContent($xmlcontent); + $page->updateFromXML(); + if ($this->page_object->needsImportParsing()) { + $this->pages_to_parse["qpl:" . $page->getId()] = "qpl:" . $page->getId(); + } + unset($page); + } + if ($ids["test"] > 0) { + // test question + include_once("./Modules/TestQuestionPool/classes/class.ilAssQuestionPage.php"); + $page = new ilAssQuestionPage($ids["test"]); + $xmlcontent = str_replace( + $this->cur_qid, + "il__qst_" . $ids["test"], + $xml + ); + $page->setXMLContent($xmlcontent); + $page->updateFromXML(); + if ($this->page_object->needsImportParsing()) { + $this->pages_to_parse["qpl:" . $page->getId()] = "qpl:" . $page->getId(); + } + unset($page); + } + } + } + + // if we are within a structure object: put page in tree + $cnt = count($this->structure_objects); //echo "1"; - if ($cnt > 0) - { -//echo "B-$cnt-
"; -//echo "
"; var_dump($this->structure_objects); echo "
"; - $parent_id = $this->structure_objects[$cnt - 1]->getId(); - if ($this->lm_page_object->isAlias()) - { -//echo "3"; - $this->pg_into_tree[$parent_id][] = array("type" => "pg_alias", "id" => $this->lm_page_object->getOriginId()); -//echo "
"; var_dump($this->pg_into_tree); echo "
"; - } - else - { -//echo "4"; - $this->pg_into_tree[$parent_id][] = array("type" => "pg", "id" => $this->lm_page_object->getId()); - } - } - - unset($this->page_object); - unset($this->lm_page_object); - unset ($this->container[count($this->container) - 1]); - break; - - case "MediaObject": - $this->in_media_object = false; + if ($cnt > 0) { + //echo "B-$cnt-
"; + //echo "
"; var_dump($this->structure_objects); echo "
"; + $parent_id = $this->structure_objects[$cnt - 1]->getId(); + if ($this->lm_page_object->isAlias()) { + //echo "3"; + $this->pg_into_tree[$parent_id][] = array("type" => "pg_alias", "id" => $this->lm_page_object->getOriginId()); + //echo "
"; var_dump($this->pg_into_tree); echo "
"; + } else { + //echo "4"; + $this->pg_into_tree[$parent_id][] = array("type" => "pg", "id" => $this->lm_page_object->getId()); + } + } + + unset($this->page_object); + unset($this->lm_page_object); + unset($this->container[count($this->container) - 1]); + break; + + case "MediaObject": + $this->in_media_object = false; + // no break case "InteractiveImage": //echo "ENDMediaObject:ImportId:".$this->media_object->getImportId()."
"; - // create media object on first occurence of an Id - - - if(empty($this->mob_mapping[$this->media_object->getImportId()])) - { -//echo "No mapping found --creating media object:title:".$this->media_object->getTitle().":
"; - - // create media object - // media items are saves for mobs outside of - // pages only - $this->media_object->create(true, false); - -//echo "
creating mob ".$this->media_object->getId().":".$this->media_object->getTitle().":"; - - // collect mobs with internal links - if ($this->media_object->containsIntLink()) - { -//echo "got int link :".$this->media_object->getId().":
"; - $this->mobs_with_int_links[] = $this->media_object->getId(); - } - - $this->mob_mapping[$this->media_object->getImportId()] - = $this->media_object->getId(); -//echo "create:import_id:".$this->media_object->getImportId().":ID:".$this->mob_mapping[$this->media_object->getImportId()]."
"; - } - else - { -//echo "Mapping found
"; - // get the id from mapping - $this->media_object->setId($this->mob_mapping[$this->media_object->getImportId()]); - - // update "real" (no alias) media object - // (note: we overwrite any data from the media object - // created by an MediaAlias, only the data of the real - // object is stored in db separately; data of the - // MediaAliases are within the page XML - if (!$this->media_object->isAlias()) - { - // now the media items are saved within the db - $this->media_object->update(); - -//echo "
update media object :".$this->media_object->getId().":"; - - // collect mobs with internal links - if ($this->media_object->containsIntLink()) - { -//echo "got int link :".$this->media_object->getId().":
"; - $this->mobs_with_int_links[] = $this->media_object->getId(); - } - } - } - - // append media alias to page, if we are in a page - if ($this->in_page_object || $this->in_glossary_definition) - { - if ($a_name != "InteractiveImage") - { - $this->page_object->appendXMLContent($this->media_object->getXML(IL_MODE_ALIAS)); -//echo "Appending:".htmlentities($this->media_object->getXML(IL_MODE_ALIAS))."
"; - } - } - - break; - - case "MediaItem": - case "MediaAliasItem": - $this->in_media_item = false; - $this->media_object->addMediaItem($this->media_item); + // create media object on first occurence of an Id + + + if (empty($this->mob_mapping[$this->media_object->getImportId()])) { + //echo "No mapping found --creating media object:title:".$this->media_object->getTitle().":
"; + + // create media object + // media items are saves for mobs outside of + // pages only + $this->media_object->create(true, false); + + //echo "
creating mob ".$this->media_object->getId().":".$this->media_object->getTitle().":"; + + // collect mobs with internal links + if ($this->media_object->containsIntLink()) { + //echo "got int link :".$this->media_object->getId().":
"; + $this->mobs_with_int_links[] = $this->media_object->getId(); + } + + $this->mob_mapping[$this->media_object->getImportId()] + = $this->media_object->getId(); + //echo "create:import_id:".$this->media_object->getImportId().":ID:".$this->mob_mapping[$this->media_object->getImportId()]."
"; + } else { + //echo "Mapping found
"; + // get the id from mapping + $this->media_object->setId($this->mob_mapping[$this->media_object->getImportId()]); + + // update "real" (no alias) media object + // (note: we overwrite any data from the media object + // created by an MediaAlias, only the data of the real + // object is stored in db separately; data of the + // MediaAliases are within the page XML + if (!$this->media_object->isAlias()) { + // now the media items are saved within the db + $this->media_object->update(); + + //echo "
update media object :".$this->media_object->getId().":"; + + // collect mobs with internal links + if ($this->media_object->containsIntLink()) { + //echo "got int link :".$this->media_object->getId().":
"; + $this->mobs_with_int_links[] = $this->media_object->getId(); + } + } + } + + // append media alias to page, if we are in a page + if ($this->in_page_object || $this->in_glossary_definition) { + if ($a_name != "InteractiveImage") { + $this->page_object->appendXMLContent($this->media_object->getXML(IL_MODE_ALIAS)); + //echo "Appending:".htmlentities($this->media_object->getXML(IL_MODE_ALIAS))."
"; + } + } + + break; + + case "MediaItem": + case "MediaAliasItem": + $this->in_media_item = false; + $this->media_object->addMediaItem($this->media_item); //echo "adding media item -".$this->media_item->getId()."-".$this->media_item->getLocation()."- to object -".$this->media_object->getId()."-"; - break; - - case "MapArea": - $this->in_map_area = false; - $this->media_item->addMapArea($this->map_area); - break; - - case "Properties": - $this->in_properties = false; - if ($this->content_object->getType() == "lm") - { - $this->content_object->update(); - } - break; - - case "MetaData": - $this->in_meta_data = false; - if(strtolower(get_class($this->current_object)) == "illmpageobject" && !$this->in_media_object) - { - // Metadaten eines PageObjects sichern in NestedSet - if (is_object($this->lm_page_object)) - { - // update title/description of page object - $this->current_object->MDUpdateListener('General'); - ilLMObject::_writeImportId($this->current_object->getId(), - $this->current_object->getImportId()); - } - } - else if((strtolower(get_class($this->current_object)) == "ilobjquestionpool" || - strtolower(get_class($this->current_object)) == "ilobjtest") && - !$this->in_media_object) -// !$this->in_media_object && !$this->in_page_object) -// changed for imports of ILIAS 2 Tests where PageObjects could have -// Metadata sections (Helmut Schottmüller, 2005-12-02) - { - if ($this->metadata_parsing_disabled) - { - $this->enableMDParsing(true); - } - else - { - if ($this->in_page_object) - { - $this->page_object->MDUpdateListener('General'); - ilLMObject::_writeImportId($this->page_object->getId(), - $this->page_object->getImportId()); - } - else - { - $this->current_object->MDUpdateListener('General'); - ilLMObject::_writeImportId($this->current_object->getId(), - $this->current_object->getImportId()); - } - } - } - else if(strtolower(get_class($this->current_object)) == "ilstructureobject") - { // save structure object at the end of its meta block - // determine parent - $cnt = count($this->structure_objects); - if ($cnt > 1) - { - $parent_id = $this->structure_objects[$cnt - 2]->getId(); - } - else - { - $parent_id = $this->lm_tree->getRootId(); - } - - // create structure object and put it in tree - //$this->current_object->create(true); // now on top - $this->st_into_tree[] = array ("id" => $this->current_object->getId(), - "parent" => $parent_id); - - // update title/description of structure object - $this->current_object->MDUpdateListener('General'); - ilLMObject::_writeImportId($this->current_object->getId(), - $this->current_object->getImportId()); - } - else if(strtolower(get_class($this->current_object)) == "ilobjlearningmodule" || - strtolower(get_class($this->current_object)) == "ilobjcontentobject" || - (strtolower(get_class($this->current_object)) == "ilobjglossary" && $this->in_glossary)) - { - // todo: saving of md? getting title/descr and - // set it for current object - } - else if(strtolower(get_class($this->current_object)) == "ilglossarydefinition" && !$this->in_media_object) - { - // now on top - //$this->glossary_definition->create(); - - $this->page_object->setId($this->glossary_definition->getId()); - $this->page_object->updateFromXML(); - - // todo: saving of md? getting title/descr and - // set it for current object - } - - - if(strtolower(get_class($this->current_object)) == "ilobjlearningmodule" || - strtolower(get_class($this->current_object)) == "ilobjglossary") - { - if (strtolower(get_class($this->current_object)) == "ilobjglossary" && - $this->content_object->getType() != "glo") - { -//echo "
getting2: ".$this->content_object->getTitle().""; - $this->current_object->setTitle($this->content_object->getTitle()." - ". - $this->lng->txt("glossary")); - } - - $this->current_object->MDUpdateListener('General'); - /* - if (!$this->in_media_object && $this->processMeta()) - { - $this->current_object->update(); - } - */ - } - - if ($this->in_media_object) - { -//echo "
call media object update listener"; - $this->media_object->MDUpdateListener('General'); - } - - if ($this->in_glossary_definition) - { - $this->glossary_definition->MDUpdateListener('General'); - } - - break; - - case "Meta-Metadata": - $this->in_meta_meta_data = false; - break; - - case "FileItem": - $this->in_file_item = false; - // only update new file items - if ($this->file_item->getImportId($a_attribs["Entry"] != "")) - { - $this->file_item->update(); - } - break; - - - case "Table": - unset ($this->container[count($this->container) - 1]); - break; - - case "Glossary": - $this->in_glossary = false; - break; - - case "GlossaryTerm": - $term = trim($this->chr_data); - $term = str_replace("<", "<", $term); - $term = str_replace(">", ">", $term); - $this->glossary_term->setTerm($term); - $this->glossary_term->create(); - $iia = explode("_", $this->glossary_term->getImportId()); - $this->glossary_term_map[(int) $iia[count($iia) - 1]] = $this->glossary_term->getId(); - break; - - case "Paragraph": - $this->inside_code = false; - break; - - case "Definition": - $this->in_glossary_definition = false; - $this->page_object->updateFromXML(); + break; + + case "MapArea": + $this->in_map_area = false; + $this->media_item->addMapArea($this->map_area); + break; + + case "Properties": + $this->in_properties = false; + if ($this->content_object->getType() == "lm") { + $this->content_object->update(); + } + break; + + case "MetaData": + $this->in_meta_data = false; + if (strtolower(get_class($this->current_object)) == "illmpageobject" && !$this->in_media_object) { + // Metadaten eines PageObjects sichern in NestedSet + if (is_object($this->lm_page_object)) { + // update title/description of page object + $this->current_object->MDUpdateListener('General'); + ilLMObject::_writeImportId( + $this->current_object->getId(), + $this->current_object->getImportId() + ); + } + } elseif ((strtolower(get_class($this->current_object)) == "ilobjquestionpool" || + strtolower(get_class($this->current_object)) == "ilobjtest") && + !$this->in_media_object) { + // !$this->in_media_object && !$this->in_page_object) + // changed for imports of ILIAS 2 Tests where PageObjects could have + // Metadata sections (Helmut Schottmüller, 2005-12-02) + if ($this->metadata_parsing_disabled) { + $this->enableMDParsing(true); + } else { + if ($this->in_page_object) { + $this->page_object->MDUpdateListener('General'); + ilLMObject::_writeImportId( + $this->page_object->getId(), + $this->page_object->getImportId() + ); + } else { + $this->current_object->MDUpdateListener('General'); + ilLMObject::_writeImportId( + $this->current_object->getId(), + $this->current_object->getImportId() + ); + } + } + } elseif (strtolower(get_class($this->current_object)) == "ilstructureobject") { // save structure object at the end of its meta block + // determine parent + $cnt = count($this->structure_objects); + if ($cnt > 1) { + $parent_id = $this->structure_objects[$cnt - 2]->getId(); + } else { + $parent_id = $this->lm_tree->getRootId(); + } + + // create structure object and put it in tree + //$this->current_object->create(true); // now on top + $this->st_into_tree[] = array("id" => $this->current_object->getId(), + "parent" => $parent_id); + + // update title/description of structure object + $this->current_object->MDUpdateListener('General'); + ilLMObject::_writeImportId( + $this->current_object->getId(), + $this->current_object->getImportId() + ); + } elseif (strtolower(get_class($this->current_object)) == "ilobjlearningmodule" || + strtolower(get_class($this->current_object)) == "ilobjcontentobject" || + (strtolower(get_class($this->current_object)) == "ilobjglossary" && $this->in_glossary)) { + // todo: saving of md? getting title/descr and + // set it for current object + } elseif (strtolower(get_class($this->current_object)) == "ilglossarydefinition" && !$this->in_media_object) { + // now on top + //$this->glossary_definition->create(); + + $this->page_object->setId($this->glossary_definition->getId()); + $this->page_object->updateFromXML(); + + // todo: saving of md? getting title/descr and + // set it for current object + } + + + if (strtolower(get_class($this->current_object)) == "ilobjlearningmodule" || + strtolower(get_class($this->current_object)) == "ilobjglossary") { + if (strtolower(get_class($this->current_object)) == "ilobjglossary" && + $this->content_object->getType() != "glo") { + //echo "
getting2: ".$this->content_object->getTitle().""; + $this->current_object->setTitle($this->content_object->getTitle() . " - " . + $this->lng->txt("glossary")); + } + + $this->current_object->MDUpdateListener('General'); + /* + if (!$this->in_media_object && $this->processMeta()) + { + $this->current_object->update(); + } + */ + } + + if ($this->in_media_object) { + //echo "
call media object update listener"; + $this->media_object->MDUpdateListener('General'); + } + + if ($this->in_glossary_definition) { + $this->glossary_definition->MDUpdateListener('General'); + } + + break; + + case "Meta-Metadata": + $this->in_meta_meta_data = false; + break; + + case "FileItem": + $this->in_file_item = false; + // only update new file items + if ($this->file_item->getImportId($a_attribs["Entry"] != "")) { + $this->file_item->update(); + } + break; + + + case "Table": + unset($this->container[count($this->container) - 1]); + break; + + case "Glossary": + $this->in_glossary = false; + break; + + case "GlossaryTerm": + $term = trim($this->chr_data); + $term = str_replace("<", "<", $term); + $term = str_replace(">", ">", $term); + $this->glossary_term->setTerm($term); + $this->glossary_term->create(); + $iia = explode("_", $this->glossary_term->getImportId()); + $this->glossary_term_map[(int) $iia[count($iia) - 1]] = $this->glossary_term->getId(); + break; + + case "Paragraph": + $this->inside_code = false; + break; + + case "Definition": + $this->in_glossary_definition = false; + $this->page_object->updateFromXML(); //echo "  after def update, xml:".htmlentities($this->page_object->getXMLContent()).":
"; //echo "
".$this->page_object->getId()."-".$this->page_object->getParentType()."-"; - $this->page_object->buildDom(); - $this->glossary_definition->setShortText($this->page_object->getFirstParagraphText()); - $this->glossary_definition->update(); - //$this->pg_mapping[$this->lm_page_object->getImportId()] - // = $this->lm_page_object->getId(); - if ($this->page_object->containsIntLink()) - { -//echo "
Definition contains Int Link:".$this->page_object->getId(); - $this->pages_to_parse["gdf:".$this->page_object->getId()] = "gdf:".$this->page_object->getId(); - } - if ($this->page_object->needsImportParsing()) - { - $this->pages_to_parse["gdf:".$this->page_object->getId()] = "gdf:".$this->page_object->getId(); - } - break; - - case "Format": - if ($this->in_media_item) - { - $this->media_item->setFormat(trim($this->chr_data)); - } - if ($this->in_file_item) - { - $this->file_item->setFileType(trim($this->chr_data)); - } - break; - - case "Title": - if (!$this->in_media_object) - { - $this->current_object->setTitle(trim($this->chr_data)); - //$this->meta_data->setTitle(trim($this->chr_data)); - } - else - { - $this->media_object->setTitle(trim($this->chr_data)); - //$this->meta_data->setTitle(trim($this->chr_data)); - } - break; - - case "Language": - /* - if (is_object($this->meta_data)) - { - $this->meta_data->setLanguage(trim($this->chr_data)); - }*/ - - break; - - case "Description": - //$this->meta_data->setDescription(trim($this->chr_data)); - break; - - case "Caption": - if ($this->in_media_object) - { - $this->media_item->setCaption(trim($this->chr_data)); - } - break; - - case "TextRepresentation": - if ($this->in_media_object) - { - $this->media_item->setTextRepresentation(trim($this->chr_data)); - } - break; - - // Location - case "Location": - // TODO: adapt for files in "real" subdirectories - if ($this->in_media_item) - { - $this->media_item->setLocationType($this->loc_type); - if ($this->loc_type == "Reference") - { - $this->media_item->setLocation(str_replace("&", "&", trim($this->chr_data))); - } - else - { - $this->media_item->setLocation(trim($this->chr_data)); - } - //echo "-".$this->media_item->getLocation()."-"; - } - if ($this->in_file_item) - { - // set file name from xml file - $this->file_item->setFileName(trim($this->chr_data)); - - // special handling for file names with special characters - // (e.g. ">") - if ($this->file_item->getType() == "file" && - is_int(strpos($this->chr_data, "&")) && - is_int(strpos($this->chr_data, ";"))) - { - $imp_dir = $this->import_dir; - $source_dir = $imp_dir."/".$this->subdir."/objects/". - $this->file_item->getImportId(); - - // read "physical" file name from directory - if ($dir = opendir($source_dir)) - { - while (false !== ($file = readdir($dir))) - { - if ($file != "." && $file != "..") - { - $this->file_item->setFileName($file); - } - } - closedir($dir); - } - } - - // set file item title - $this->file_item->setTitle(trim($this->chr_data)); - } - break; - - } - $this->endElement($a_name); - $this->chr_data = ""; - } - - /** - * handler for character data - * - * @param resource $a_xml_parser xml parser - * @param string $a_data character data - */ - function handlerCharacterData($a_xml_parser,$a_data) - { - // call meta data handler - if ($this->in_meta_data && $this->processMeta()) - { - // cache beginning of meta data within media object tags - // (we need to know the id, after that we send the cached data - // to the meta xml handler) - if ($this->in_media_object && $this->media_meta_start) - { - $this->media_meta_cache[] = - array("type" => "handlerCharacterData", "par1" => $a_data); - } - else - { - parent::handlerCharacterData($a_xml_parser,$a_data); - } - } - - // the parser converts ">" to ">" and "<" to "<" - // in character data, but we don't want that, because it's the - // way we mask user html in our content, so we convert back... - - $a_data = str_replace("<","<",$a_data); - $a_data = str_replace(">",">",$a_data); - - - // DELETE WHITESPACES AND NEWLINES OF CHARACTER DATA - $a_data = preg_replace("/\n/","",$a_data); - if (!$this->inside_code) - { - $a_data = preg_replace("/\t+/","",$a_data); - } - - $this->chr_data .= $a_data; - - if(!empty($a_data) || $a_data === "0") - { - // append all data to page, if we are within PageObject, - // but not within MetaData or MediaObject - if (($this->in_page_object || $this->in_glossary_definition) - && !$this->in_meta_data && !$this->in_media_object) - { - $this->page_object->appendXMLContent($a_data); - } - - if ($this->in_meta_data) - { - //$this->meta_data->appendXMLContent($a_data); + $this->page_object->buildDom(); + $this->glossary_definition->setShortText($this->page_object->getFirstParagraphText()); + $this->glossary_definition->update(); + //$this->pg_mapping[$this->lm_page_object->getImportId()] + // = $this->lm_page_object->getId(); + if ($this->page_object->containsIntLink()) { + //echo "
Definition contains Int Link:".$this->page_object->getId(); + $this->pages_to_parse["gdf:" . $this->page_object->getId()] = "gdf:" . $this->page_object->getId(); + } + if ($this->page_object->needsImportParsing()) { + $this->pages_to_parse["gdf:" . $this->page_object->getId()] = "gdf:" . $this->page_object->getId(); + } + break; + + case "Format": + if ($this->in_media_item) { + $this->media_item->setFormat(trim($this->chr_data)); + } + if ($this->in_file_item) { + $this->file_item->setFileType(trim($this->chr_data)); + } + break; + + case "Title": + if (!$this->in_media_object) { + $this->current_object->setTitle(trim($this->chr_data)); + //$this->meta_data->setTitle(trim($this->chr_data)); + } else { + $this->media_object->setTitle(trim($this->chr_data)); + //$this->meta_data->setTitle(trim($this->chr_data)); + } + break; + + case "Language": + /* + if (is_object($this->meta_data)) + { + $this->meta_data->setLanguage(trim($this->chr_data)); + }*/ + + break; + + case "Description": + //$this->meta_data->setDescription(trim($this->chr_data)); + break; + + case "Caption": + if ($this->in_media_object) { + $this->media_item->setCaption(trim($this->chr_data)); + } + break; + + case "TextRepresentation": + if ($this->in_media_object) { + $this->media_item->setTextRepresentation(trim($this->chr_data)); + } + break; + + // Location + case "Location": + // TODO: adapt for files in "real" subdirectories + if ($this->in_media_item) { + $this->media_item->setLocationType($this->loc_type); + if ($this->loc_type == "Reference") { + $this->media_item->setLocation(str_replace("&", "&", trim($this->chr_data))); + } else { + $this->media_item->setLocation(trim($this->chr_data)); + } + //echo "-".$this->media_item->getLocation()."-"; + } + if ($this->in_file_item) { + // set file name from xml file + $this->file_item->setFileName(trim($this->chr_data)); + + // special handling for file names with special characters + // (e.g. ">") + if ($this->file_item->getType() == "file" && + is_int(strpos($this->chr_data, "&")) && + is_int(strpos($this->chr_data, ";"))) { + $imp_dir = $this->import_dir; + $source_dir = $imp_dir . "/" . $this->subdir . "/objects/" . + $this->file_item->getImportId(); + + // read "physical" file name from directory + if ($dir = opendir($source_dir)) { + while (false !== ($file = readdir($dir))) { + if ($file != "." && $file != "..") { + $this->file_item->setFileName($file); + } + } + closedir($dir); + } + } + + // set file item title + $this->file_item->setTitle(trim($this->chr_data)); + } + break; + + } + $this->endElement($a_name); + $this->chr_data = ""; + } + + /** + * handler for character data + * + * @param resource $a_xml_parser xml parser + * @param string $a_data character data + */ + public function handlerCharacterData($a_xml_parser, $a_data) + { + // call meta data handler + if ($this->in_meta_data && $this->processMeta()) { + // cache beginning of meta data within media object tags + // (we need to know the id, after that we send the cached data + // to the meta xml handler) + if ($this->in_media_object && $this->media_meta_start) { + $this->media_meta_cache[] = + array("type" => "handlerCharacterData", "par1" => $a_data); + } else { + parent::handlerCharacterData($a_xml_parser, $a_data); + } + } + + // the parser converts ">" to ">" and "<" to "<" + // in character data, but we don't want that, because it's the + // way we mask user html in our content, so we convert back... + + $a_data = str_replace("<", "<", $a_data); + $a_data = str_replace(">", ">", $a_data); + + + // DELETE WHITESPACES AND NEWLINES OF CHARACTER DATA + $a_data = preg_replace("/\n/", "", $a_data); + if (!$this->inside_code) { + $a_data = preg_replace("/\t+/", "", $a_data); + } + + $this->chr_data .= $a_data; + + if (!empty($a_data) || $a_data === "0") { + // append all data to page, if we are within PageObject, + // but not within MetaData or MediaObject + if (($this->in_page_object || $this->in_glossary_definition) + && !$this->in_meta_data && !$this->in_media_object) { + $this->page_object->appendXMLContent($a_data); + } + + if ($this->in_meta_data) { + //$this->meta_data->appendXMLContent($a_data); //echo "
".$a_data; - } - - switch($this->getCurrentElement()) - { - - case "IntLink": - case "ExtLink": - if($this->in_map_area) - { - $this->map_area->appendTitle($a_data); - } - break; - - } - } - - } - - - /** - * send all cached tags to the meta data parser and - * clear the cache - */ - function emptyMediaMetaCache(&$a_xml_parser) - { - foreach ($this->media_meta_cache as $cache_entry) - { - switch($cache_entry["type"]) - { - case "handlerBeginTag": - parent::handlerBeginTag($a_xml_parser, - $cache_entry["par1"], $cache_entry["par2"]); - break; - - case "handlerEndTag": - parent::handlerEndTag($a_xml_parser, - $cache_entry["par1"]); - break; - - case "handlerCharacterData": - parent::handlerCharacterData($a_xml_parser, - $cache_entry["par1"]); - break; - } - } - - $this->media_meta_start = false; - $this->media_meta_cache[] = array(); - } - - /** - * Get glossary term map (imported ids to new ids) - * - * @param - * @return - */ - function getGlossaryTermMap() - { - return $this->glossary_term_map; - } - + } + + switch ($this->getCurrentElement()) { + + case "IntLink": + case "ExtLink": + if ($this->in_map_area) { + $this->map_area->appendTitle($a_data); + } + break; + + } + } + } + + + /** + * send all cached tags to the meta data parser and + * clear the cache + */ + public function emptyMediaMetaCache(&$a_xml_parser) + { + foreach ($this->media_meta_cache as $cache_entry) { + switch ($cache_entry["type"]) { + case "handlerBeginTag": + parent::handlerBeginTag( + $a_xml_parser, + $cache_entry["par1"], + $cache_entry["par2"] + ); + break; + + case "handlerEndTag": + parent::handlerEndTag( + $a_xml_parser, + $cache_entry["par1"] + ); + break; + + case "handlerCharacterData": + parent::handlerCharacterData( + $a_xml_parser, + $cache_entry["par1"] + ); + break; + } + } + + $this->media_meta_start = false; + $this->media_meta_cache[] = array(); + } + + /** + * Get glossary term map (imported ids to new ids) + * + * @param + * @return + */ + public function getGlossaryTermMap() + { + return $this->glossary_term_map; + } } -?> diff --git a/Modules/LearningModule/classes/class.ilContObjectExport.php b/Modules/LearningModule/classes/class.ilContObjectExport.php index 18a5c610695a14170da5e9912be52e5ed70b73e8..475a50eb1ccd697be25c27414629a3a7d624b5b3 100755 --- a/Modules/LearningModule/classes/class.ilContObjectExport.php +++ b/Modules/LearningModule/classes/class.ilContObjectExport.php @@ -15,235 +15,231 @@ require_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); */ class ilContObjectExport { - var $err; // error object - var $db; // database object - var $cont_obj; // content object (learning module | digilib book) - var $inst_id; // installation id - var $mode; - - /** - * Constructor - * @access 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; - } - } - - function getInstId() - { - return $this->inst_id; - } - - /** - * build export file (complete zip file) - * - * @access public - * @return - */ - 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 - */ - 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 - */ - 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 * @version $Id$ @@ -14,76 +14,74 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilLMBlockedUsersTableGUI extends ilTable2GUI { - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_lm) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_lm) + { + 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->lm = $a_lm; + $this->lm = $a_lm; - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setData($this->getBlockedUsers()); - $this->setTitle($lng->txt("")); - - $this->addColumn("", "", "1px"); - $this->addColumn($this->lng->txt("user"), "user"); - $this->addColumn($this->lng->txt("question"), ""); - $this->addColumn($this->lng->txt("page"), "page_title"); - $this->addColumn($this->lng->txt("cont_last_try"), "last_try"); - $this->addColumn($this->lng->txt("cont_unlocked")); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.blocked_users.html", "Modules/LearningModule"); + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setData($this->getBlockedUsers()); + $this->setTitle($lng->txt("")); + + $this->addColumn("", "", "1px"); + $this->addColumn($this->lng->txt("user"), "user"); + $this->addColumn($this->lng->txt("question"), ""); + $this->addColumn($this->lng->txt("page"), "page_title"); + $this->addColumn($this->lng->txt("cont_last_try"), "last_try"); + $this->addColumn($this->lng->txt("cont_unlocked")); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.blocked_users.html", "Modules/LearningModule"); - $this->addMultiCommand("sendMailToBlockedUsers", $lng->txt("send_mail")); - $this->addMultiCommand("resetNumberOfTries", $lng->txt("cont_reset_nr_of_tries")); - $this->addMultiCommand("unlockQuestion", $lng->txt("cont_unlock_allow_continue")); - //$this->addCommandButton("", $lng->txt("")); - } + $this->addMultiCommand("sendMailToBlockedUsers", $lng->txt("send_mail")); + $this->addMultiCommand("resetNumberOfTries", $lng->txt("cont_reset_nr_of_tries")); + $this->addMultiCommand("unlockQuestion", $lng->txt("cont_unlock_allow_continue")); + //$this->addCommandButton("", $lng->txt("")); + } - /** - * Get blocked users - * - * @return array array of blocked user information - */ - protected function getBlockedUsers() - { - include_once("./Modules/LearningModule/classes/class.ilLMTracker.php"); - /** @var ilLMTracker $track */ - $track = ilLMTracker::getInstance($this->lm->getRefId()); + /** + * Get blocked users + * + * @return array array of blocked user information + */ + protected function getBlockedUsers() + { + include_once("./Modules/LearningModule/classes/class.ilLMTracker.php"); + /** @var ilLMTracker $track */ + $track = ilLMTracker::getInstance($this->lm->getRefId()); - return $bl_users = $track->getBlockedUsersInformation(); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - - $this->tpl->setVariable("USER_QUEST_ID", $a_set["qst_id"].":".$a_set["user_id"]); - $this->tpl->setVariable("USER_NAME", $a_set["user_name"]); - $this->tpl->setVariable("QUESTION", $a_set["question_text"]); - $this->tpl->setVariable("PAGE", $a_set["page_title"]); - $this->tpl->setVariable("LAST_TRY", $a_set["last_try"]); - $this->tpl->setVariable("IGNORE_FAIL", ($a_set["unlocked"] ? $lng->txt("yes") : $lng->txt("no"))); - } + return $bl_users = $track->getBlockedUsersInformation(); + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $this->tpl->setVariable("USER_QUEST_ID", $a_set["qst_id"] . ":" . $a_set["user_id"]); + $this->tpl->setVariable("USER_NAME", $a_set["user_name"]); + $this->tpl->setVariable("QUESTION", $a_set["question_text"]); + $this->tpl->setVariable("PAGE", $a_set["page_title"]); + $this->tpl->setVariable("LAST_TRY", $a_set["last_try"]); + $this->tpl->setVariable("IGNORE_FAIL", ($a_set["unlocked"] ? $lng->txt("yes") : $lng->txt("no"))); + } } -?> \ No newline at end of file diff --git a/Modules/LearningModule/classes/class.ilLMContObjectManifestBuilder.php b/Modules/LearningModule/classes/class.ilLMContObjectManifestBuilder.php index c3368f8fe29f492bb2dbaf76e877c220dcba4c14..de607b3fefd1d65c11f1216bc79402058fa0b51f 100755 --- a/Modules/LearningModule/classes/class.ilLMContObjectManifestBuilder.php +++ b/Modules/LearningModule/classes/class.ilLMContObjectManifestBuilder.php @@ -15,147 +15,143 @@ require_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); */ class ilLMContObjectManifestBuilder { - var $db; // database object - var $cont_obj; // content object (learning module | digilib book) - var $inst_id; // installation id - - /** - * Constructor - * @access public - */ - function __construct($a_cont_obj) - { - global $DIC; - - $ilDB = $DIC->database(); - - $this->cont_obj = $a_cont_obj; - - $this->db = $ilDB; - - $this->inst_id = IL_INST_ID; - - } - - /** - * build manifest structure - */ - function buildManifest() - { - require_once("./Services/Xml/classes/class.ilXmlWriter.php"); - - $this->writer = new ilXmlWriter; - - // set xml header - $this->writer->xmlHeader(); - - // manifest start tag - $attrs = array(); - $attrs["identifier"] = "il_".IL_INST_ID."_"."man". - "_".$this->cont_obj->getId(); - $attrs["version"] = ""; - $attrs["xmlns:xsi"] = "http://www.w3.org/2001/XMLSchema-instance"; - $attrs["xsi:schemaLocation"] = "http://www.imsproject.org/xsd/imscp_rootv1p1p2". - " imscp_rootv1p1p2.xsd". - " http://www.imsglobal.org/xsd/imsmd_rootv1p2p1". - " imsmd_rootv1p2p1.xsd". - " http://www.adlnet.org/xsd/adlcp_rootv1p2". - " adlcp_rootv1p2.xsd"; - $attrs["xmlns:imsmd"] = "http://www.imsproject.org/xsd/imsmd_rootv1p2p1"; - $attrs["xmlns:adlcp"] = "http://www.adlnet.org/xsd/adlcp_rootv1p2"; - $attrs["xmlns"] = "http://www.imsproject.org/xsd/imscp_rootv1p1p2"; - $this->writer->xmlStartTag("manifest", $attrs); - - // organizations start tag - $attrs = array(); - $this->writer->xmlStartTag("organizations", $attrs); - - // organization start tag - $attrs = array(); - $attrs["identifier"] = "il_".IL_INST_ID."_".$this->cont_obj->getType(). - "_".$this->cont_obj->getId(); - $attrs["structure"] = "hierarchical"; - $this->writer->xmlStartTag("organization", $attrs); - - // title element - $attrs = array(); - $this->writer->xmlElement("title", $attrs, $this->cont_obj->getTitle()); - - // write item hierarchy - $this->writeItemHierarchy(); - - // organization end tag - $this->writer->xmlEndTag("organization"); - - // organizations end tag - $this->writer->xmlEndTag("organizations"); - - // resources start tag - $attrs = array(); - $this->writer->xmlStartTag("resources", $attrs); - - // write resources - $this->writeResources(); - - // resources end tag - $this->writer->xmlEndTag("resources"); - - // manifest end tag - $this->writer->xmlEndTag("manifest"); - - // write manifest file - //$this->xml->xmlDumpFile($this->export_dir."/".$this->subdir."/".$this->filename - // , false); - - // destroy writer object - $this->writer->_XmlWriter; - } - - /** - * dump manifest file into directory - */ - function dump($a_target_dir) - { - $this->writer->xmlDumpFile($a_target_dir."/imsmanifest.xml", false); - } - - /** - * write item hierarchy - * - * this first version only writes one item for the whole learning module - */ - function writeItemHierarchy() - { - // start item - $attrs = array(); - $attrs["identifier"] = "INDEX"; - $attrs["identifierref"] = "RINDEX"; - $this->writer->xmlStartTag("item", $attrs); - - // title element - $attrs = array(); - $this->writer->xmlElement("title", $attrs, $this->cont_obj->getTitle()); - - // end item - $this->writer->xmlEndTag("item"); - } - - - /** - * write resources - * - * this first version only writes one resource for the whole learning module - */ - function writeResources() - { - $attrs = array(); - $attrs["identifier"] = "RINDEX"; - $attrs["type"] = "webcontent"; - $attrs["adlcp:scormtype"] = "asset"; - $attrs["href"] = "res/index.html"; - $this->writer->xmlElement("resource", $attrs, ""); - } - + public $db; // database object + public $cont_obj; // content object (learning module | digilib book) + public $inst_id; // installation id + + /** + * Constructor + * @access public + */ + public function __construct($a_cont_obj) + { + global $DIC; + + $ilDB = $DIC->database(); + + $this->cont_obj = $a_cont_obj; + + $this->db = $ilDB; + + $this->inst_id = IL_INST_ID; + } + + /** + * build manifest structure + */ + public function buildManifest() + { + require_once("./Services/Xml/classes/class.ilXmlWriter.php"); + + $this->writer = new ilXmlWriter; + + // set xml header + $this->writer->xmlHeader(); + + // manifest start tag + $attrs = array(); + $attrs["identifier"] = "il_" . IL_INST_ID . "_" . "man" . + "_" . $this->cont_obj->getId(); + $attrs["version"] = ""; + $attrs["xmlns:xsi"] = "http://www.w3.org/2001/XMLSchema-instance"; + $attrs["xsi:schemaLocation"] = "http://www.imsproject.org/xsd/imscp_rootv1p1p2" . + " imscp_rootv1p1p2.xsd" . + " http://www.imsglobal.org/xsd/imsmd_rootv1p2p1" . + " imsmd_rootv1p2p1.xsd" . + " http://www.adlnet.org/xsd/adlcp_rootv1p2" . + " adlcp_rootv1p2.xsd"; + $attrs["xmlns:imsmd"] = "http://www.imsproject.org/xsd/imsmd_rootv1p2p1"; + $attrs["xmlns:adlcp"] = "http://www.adlnet.org/xsd/adlcp_rootv1p2"; + $attrs["xmlns"] = "http://www.imsproject.org/xsd/imscp_rootv1p1p2"; + $this->writer->xmlStartTag("manifest", $attrs); + + // organizations start tag + $attrs = array(); + $this->writer->xmlStartTag("organizations", $attrs); + + // organization start tag + $attrs = array(); + $attrs["identifier"] = "il_" . IL_INST_ID . "_" . $this->cont_obj->getType() . + "_" . $this->cont_obj->getId(); + $attrs["structure"] = "hierarchical"; + $this->writer->xmlStartTag("organization", $attrs); + + // title element + $attrs = array(); + $this->writer->xmlElement("title", $attrs, $this->cont_obj->getTitle()); + + // write item hierarchy + $this->writeItemHierarchy(); + + // organization end tag + $this->writer->xmlEndTag("organization"); + + // organizations end tag + $this->writer->xmlEndTag("organizations"); + + // resources start tag + $attrs = array(); + $this->writer->xmlStartTag("resources", $attrs); + + // write resources + $this->writeResources(); + + // resources end tag + $this->writer->xmlEndTag("resources"); + + // manifest end tag + $this->writer->xmlEndTag("manifest"); + + // write manifest file + //$this->xml->xmlDumpFile($this->export_dir."/".$this->subdir."/".$this->filename + // , false); + + // destroy writer object + $this->writer->_XmlWriter; + } + + /** + * dump manifest file into directory + */ + public function dump($a_target_dir) + { + $this->writer->xmlDumpFile($a_target_dir . "/imsmanifest.xml", false); + } + + /** + * write item hierarchy + * + * this first version only writes one item for the whole learning module + */ + public function writeItemHierarchy() + { + // start item + $attrs = array(); + $attrs["identifier"] = "INDEX"; + $attrs["identifierref"] = "RINDEX"; + $this->writer->xmlStartTag("item", $attrs); + + // title element + $attrs = array(); + $this->writer->xmlElement("title", $attrs, $this->cont_obj->getTitle()); + + // end item + $this->writer->xmlEndTag("item"); + } + + + /** + * write resources + * + * this first version only writes one resource for the whole learning module + */ + public function writeResources() + { + $attrs = array(); + $attrs["identifier"] = "RINDEX"; + $attrs["type"] = "webcontent"; + $attrs["adlcp:scormtype"] = "asset"; + $attrs["href"] = "res/index.html"; + $this->writer->xmlElement("resource", $attrs, ""); + } } - -?> diff --git a/Modules/LearningModule/classes/class.ilLMDownloadTableGUI.php b/Modules/LearningModule/classes/class.ilLMDownloadTableGUI.php index 1ff4370c6f9f2753a396e37fb9d79a92fab26bff..bb838dbc498dcc7a5f555356e386f76faff698ad 100644 --- a/Modules/LearningModule/classes/class.ilLMDownloadTableGUI.php +++ b/Modules/LearningModule/classes/class.ilLMDownloadTableGUI.php @@ -14,85 +14,85 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilLMDownloadTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilObjLearningModule - */ - protected $lm; - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, ilObjLearningModule $a_lm) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - $this->lm = $a_lm; - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setData($this->lm->getPublicExportFiles()); - $this->setTitle($this->lng->txt("download")); - - $this->addColumn($this->lng->txt("cont_format")); - $this->addColumn($this->lng->txt("cont_file")); - $this->addColumn($this->lng->txt("size")); - $this->addColumn($this->lng->txt("date")); - $this->addColumn($this->lng->txt("action")); - $this->disable("footer"); - $this->setMaxCount(9999); - - $this->setFormAction($this->ctrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.download_file_row.html", "Modules/LearningModule"); - } - - /** - * Get download files - */ - function getDownloadFiles() - { - $this->setData($this->lm->getPublicExportFiles()); - } - - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $this->tpl->setVariable("TXT_FILENAME", $a_set["file"]); - - $this->tpl->setVariable("TXT_SIZE", ilUtil::formatSize($a_set["size"])); - $this->tpl->setVariable("TXT_FORMAT", strtoupper($a_set["type"])); - $this->tpl->setVariable("CHECKBOX_ID", $a_set["type"].":".$a_set["file"]); - - $file_arr = explode("__", $a_set["file"]); - ilDatePresentation::setUseRelativeDates(false); - $this->tpl->setVariable("TXT_DATE", ilDatePresentation::formatDate(new ilDateTime($file_arr[0], IL_CAL_UNIX))); - - $this->tpl->setVariable("TXT_DOWNLOAD", $this->lng->txt("download")); - $this->ctrl->setParameter($this->parent_obj, "type", $a_set["dir_type"]); - $this->tpl->setVariable("LINK_DOWNLOAD", - $this->ctrl->getLinkTarget($this->parent_obj, "downloadExportFile")); - - $this->tpl->parseCurrentBlock(); - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilObjLearningModule + */ + protected $lm; + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, ilObjLearningModule $a_lm) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + $this->lm = $a_lm; + + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setData($this->lm->getPublicExportFiles()); + $this->setTitle($this->lng->txt("download")); + + $this->addColumn($this->lng->txt("cont_format")); + $this->addColumn($this->lng->txt("cont_file")); + $this->addColumn($this->lng->txt("size")); + $this->addColumn($this->lng->txt("date")); + $this->addColumn($this->lng->txt("action")); + $this->disable("footer"); + $this->setMaxCount(9999); + + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.download_file_row.html", "Modules/LearningModule"); + } + + /** + * Get download files + */ + public function getDownloadFiles() + { + $this->setData($this->lm->getPublicExportFiles()); + } + + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $this->tpl->setVariable("TXT_FILENAME", $a_set["file"]); + + $this->tpl->setVariable("TXT_SIZE", ilUtil::formatSize($a_set["size"])); + $this->tpl->setVariable("TXT_FORMAT", strtoupper($a_set["type"])); + $this->tpl->setVariable("CHECKBOX_ID", $a_set["type"] . ":" . $a_set["file"]); + + $file_arr = explode("__", $a_set["file"]); + ilDatePresentation::setUseRelativeDates(false); + $this->tpl->setVariable("TXT_DATE", ilDatePresentation::formatDate(new ilDateTime($file_arr[0], IL_CAL_UNIX))); + + $this->tpl->setVariable("TXT_DOWNLOAD", $this->lng->txt("download")); + $this->ctrl->setParameter($this->parent_obj, "type", $a_set["dir_type"]); + $this->tpl->setVariable( + "LINK_DOWNLOAD", + $this->ctrl->getLinkTarget($this->parent_obj, "downloadExportFile") + ); + + $this->tpl->parseCurrentBlock(); + } } -?> \ No newline at end of file diff --git a/Modules/LearningModule/classes/class.ilLMEditShortTitlesGUI.php b/Modules/LearningModule/classes/class.ilLMEditShortTitlesGUI.php index 07e8226cabb3362c08900e25d4456a89eecd1f17..67623de40afc90847629db9df2c68eb6cbf3897f 100644 --- a/Modules/LearningModule/classes/class.ilLMEditShortTitlesGUI.php +++ b/Modules/LearningModule/classes/class.ilLMEditShortTitlesGUI.php @@ -4,98 +4,92 @@ class ilLMEditShortTitlesGUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilObjLearningModule - */ - protected $lm; + /** + * @var ilObjLearningModule + */ + protected $lm; - /** - * @var ilObjLearningModuleGUI - */ - protected $lm_gui; + /** + * @var ilObjLearningModuleGUI + */ + protected $lm_gui; - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilTemplate + */ + protected $tpl; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * Learning module - * - * @param ilObjLearningModule $a_lm learning module - */ - function __construct(ilObjLearningModuleGUI $a_lm_gui) - { - global $DIC; + /** + * Learning module + * + * @param ilObjLearningModule $a_lm learning module + */ + public function __construct(ilObjLearningModuleGUI $a_lm_gui) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lm = $a_lm_gui->object; - $this->lm_gui = $a_lm_gui; - $this->tpl = $DIC["tpl"]; - $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->lm = $a_lm_gui->object; + $this->lm_gui = $a_lm_gui; + $this->tpl = $DIC["tpl"]; + $this->lng = $DIC->language(); - $this->lang = ($_GET["transl"] == "") - ? "-" - : $_GET["transl"]; + $this->lang = ($_GET["transl"] == "") + ? "-" + : $_GET["transl"]; + } - } + /** + * Execute command + */ + public function executeCommand() + { + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd("listShortTitles"); - /** - * Execute command - */ - function executeCommand() - { - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd("listShortTitles"); + switch ($next_class) { + default: + if (in_array($cmd, array("listShortTitles", "save"))) { + $this->$cmd(); + } + } + } - switch ($next_class) - { - default: - if (in_array($cmd, array("listShortTitles", "save"))) - { - $this->$cmd(); - } - } - } + /** + * List short titles + */ + public function listShortTitles() + { + ilUtil::sendInfo($this->lng->txt("cont_short_title_info")); + $ml_head = ilObjContentObjectGUI::getMultiLangHeader($this->lm->getId(), $this->lm_gui, "short_titles"); + include_once("./Modules/LearningModule/classes/class.ilLMEditShortTitlesTableGUI.php"); + $tab = new ilLMEditShortTitlesTableGUI($this, "listShortTitles", $this->lm, $this->lang); + $this->tpl->setContent($ml_head . $tab->getHTML()); + } - /** - * List short titles - */ - function listShortTitles() - { - ilUtil::sendInfo($this->lng->txt("cont_short_title_info")); - $ml_head = ilObjContentObjectGUI::getMultiLangHeader($this->lm->getId(), $this->lm_gui, "short_titles"); - include_once("./Modules/LearningModule/classes/class.ilLMEditShortTitlesTableGUI.php"); - $tab = new ilLMEditShortTitlesTableGUI($this, "listShortTitles", $this->lm, $this->lang); - $this->tpl->setContent($ml_head.$tab->getHTML()); - } - - /** - * Save short titles - */ - function save() - { - if (is_array($_POST["short_title"])) - { - foreach ($_POST["short_title"] as $id => $title) - { - if (ilLMObject::_lookupContObjID($id) == $this->lm->getId()) - { - ilLMObject::writeShortTitle($id, ilUtil::stripSlashes($title), $this->lang); - } - } - } - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "listShortTitles"); - } -} \ No newline at end of file + /** + * Save short titles + */ + public function save() + { + if (is_array($_POST["short_title"])) { + foreach ($_POST["short_title"] as $id => $title) { + if (ilLMObject::_lookupContObjID($id) == $this->lm->getId()) { + ilLMObject::writeShortTitle($id, ilUtil::stripSlashes($title), $this->lang); + } + } + } + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "listShortTitles"); + } +} diff --git a/Modules/LearningModule/classes/class.ilLMEditShortTitlesTableGUI.php b/Modules/LearningModule/classes/class.ilLMEditShortTitlesTableGUI.php index 4db2fbc502b4b0c01adea6cae1195ca19ac92fe9..20a8168ab732419f381c80fb9fbced950e2c0842 100644 --- a/Modules/LearningModule/classes/class.ilLMEditShortTitlesTableGUI.php +++ b/Modules/LearningModule/classes/class.ilLMEditShortTitlesTableGUI.php @@ -13,67 +13,65 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilLMEditShortTitlesTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilObjLearningModule - */ - protected $lm; + /** + * @var ilObjLearningModule + */ + protected $lm; - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilTemplate + */ + protected $tpl; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_lm, $a_lang) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_lm, $a_lang) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lm = $a_lm; - $this->tpl = $DIC["tpl"]; - $this->lng = $DIC->language(); - $this->lang = $a_lang; + $this->ctrl = $DIC->ctrl(); + $this->lm = $a_lm; + $this->tpl = $DIC["tpl"]; + $this->lng = $DIC->language(); + $this->lang = $a_lang; - $this->setId("lm_short_title"); + $this->setId("lm_short_title"); - parent::__construct($a_parent_obj, $a_parent_cmd); - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - $this->setData(ilLMObject::getShortTitles($this->lm->getId(), $this->lang)); - $this->setTitle($this->lng->txt("cont_short_titles")); - - $this->addColumn($this->lng->txt("title")); - $this->addColumn($this->lng->txt("cont_short_title")); - - $this->setFormAction($this->ctrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.short_title_row.html", "Modules/LearningModule"); - - $this->addCommandButton("save", $this->lng->txt("save")); - //$this->setMaxCount(9999); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $this->tpl->setVariable("TITLE", $a_set["title"]); - $this->tpl->setVariable("DEFAULT_TITLE", $a_set["default_title"]); - $this->tpl->setVariable("DEFAULT_SHORT_TITLE", $a_set["default_short_title"]); - $this->tpl->setVariable("ID", $a_set["obj_id"]); - $this->tpl->setVariable("SHORT_TITLE", ilUtil::prepareFormOutput($a_set["short_title"])); - } + parent::__construct($a_parent_obj, $a_parent_cmd); + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + $this->setData(ilLMObject::getShortTitles($this->lm->getId(), $this->lang)); + $this->setTitle($this->lng->txt("cont_short_titles")); + + $this->addColumn($this->lng->txt("title")); + $this->addColumn($this->lng->txt("cont_short_title")); + + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.short_title_row.html", "Modules/LearningModule"); + $this->addCommandButton("save", $this->lng->txt("save")); + //$this->setMaxCount(9999); + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $this->tpl->setVariable("TITLE", $a_set["title"]); + $this->tpl->setVariable("DEFAULT_TITLE", $a_set["default_title"]); + $this->tpl->setVariable("DEFAULT_SHORT_TITLE", $a_set["default_short_title"]); + $this->tpl->setVariable("ID", $a_set["obj_id"]); + $this->tpl->setVariable("SHORT_TITLE", ilUtil::prepareFormOutput($a_set["short_title"])); + } } -?> \ No newline at end of file diff --git a/Modules/LearningModule/classes/class.ilLMEditorExplorerGUI.php b/Modules/LearningModule/classes/class.ilLMEditorExplorerGUI.php index f4631614ee5ea57f360169d088148f902beb81af..63e1b1933581ec290c93322c0cd05f5d7d88266d 100644 --- a/Modules/LearningModule/classes/class.ilLMEditorExplorerGUI.php +++ b/Modules/LearningModule/classes/class.ilLMEditorExplorerGUI.php @@ -14,146 +14,138 @@ include_once("./Modules/LearningModule/classes/class.ilLMExplorerGUI.php"); class ilLMEditorExplorerGUI extends ilLMExplorerGUI { - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, ilObjContentObject $a_lm, $a_id = "") - { - global $DIC; - parent::__construct($a_parent_obj, $a_parent_cmd, $a_lm, $a_id); + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, ilObjContentObject $a_lm, $a_id = "") + { + global $DIC; + parent::__construct($a_parent_obj, $a_parent_cmd, $a_lm, $a_id); - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - } + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + } - /** - * Get node icon - * - * @param array $a_node node array - * @return string icon path - */ - function getNodeIcon($a_node) - { - if ($a_node["child"] == $this->getNodeId($this->getRootNode())) - { - $icon = ilUtil::getImagePath("icon_lm.svg"); - } - else - { - $a_name = "icon_".$a_node["type"].".svg"; - if ($a_node["type"] == "pg") - { - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - $lm_set = new ilSetting("lm"); - $active = ilLMPage::_lookupActive($a_node["child"], $this->lm->getType(), - $lm_set->get("time_scheduled_page_activation")); - - // is page scheduled? - $img_sc = ($lm_set->get("time_scheduled_page_activation") && - ilLMPage::_isScheduledActivation($a_node["child"], $this->lm->getType())) - ? "_sc" - : ""; - - $a_name = "icon_pg".$img_sc.".svg"; - - if (!$active) - { - $a_name = "icon_pg_d".$img_sc.".svg"; - } - else - { - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - $contains_dis = ilLMPage::_lookupContainsDeactivatedElements($a_node["child"], - $this->lm->getType()); - if ($contains_dis) - { - $a_name = "icon_pg_del".$img_sc.".svg"; - } - } - } - $icon = ilUtil::getImagePath($a_name); - } - - return $icon; - } + /** + * Get node icon + * + * @param array $a_node node array + * @return string icon path + */ + public function getNodeIcon($a_node) + { + if ($a_node["child"] == $this->getNodeId($this->getRootNode())) { + $icon = ilUtil::getImagePath("icon_lm.svg"); + } else { + $a_name = "icon_" . $a_node["type"] . ".svg"; + if ($a_node["type"] == "pg") { + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + $lm_set = new ilSetting("lm"); + $active = ilLMPage::_lookupActive( + $a_node["child"], + $this->lm->getType(), + $lm_set->get("time_scheduled_page_activation") + ); + + // is page scheduled? + $img_sc = ($lm_set->get("time_scheduled_page_activation") && + ilLMPage::_isScheduledActivation($a_node["child"], $this->lm->getType())) + ? "_sc" + : ""; + + $a_name = "icon_pg" . $img_sc . ".svg"; + + if (!$active) { + $a_name = "icon_pg_d" . $img_sc . ".svg"; + } else { + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + $contains_dis = ilLMPage::_lookupContainsDeactivatedElements( + $a_node["child"], + $this->lm->getType() + ); + if ($contains_dis) { + $a_name = "icon_pg_del" . $img_sc . ".svg"; + } + } + } + $icon = ilUtil::getImagePath($a_name); + } + + return $icon; + } - /** - * Get node icon alt text - * - * @param array $a_node node array - * @return string alt text - */ - function getNodeIconAlt($a_node) - { - $lng = $this->lng; - - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + /** + * Get node icon alt text + * + * @param array $a_node node array + * @return string alt text + */ + public function getNodeIconAlt($a_node) + { + $lng = $this->lng; + + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - if ($a_node["type"] == "du") - { - $a_node["type"] = "lm"; - } + if ($a_node["type"] == "du") { + $a_node["type"] = "lm"; + } - if ($a_node["type"] == "pg") - { - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - $lm_set = new ilSetting("lm"); - $active = ilLMPage::_lookupActive($a_node["child"], $this->lm->getType(), - $lm_set->get("time_scheduled_page_activation")); + if ($a_node["type"] == "pg") { + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + $lm_set = new ilSetting("lm"); + $active = ilLMPage::_lookupActive( + $a_node["child"], + $this->lm->getType(), + $lm_set->get("time_scheduled_page_activation") + ); - if (!$active) - { - return $lng->txt("cont_page_deactivated"); - } - else - { - $contains_dis = ilLMPage::_lookupContainsDeactivatedElements($a_node["child"], - $this->lm->getType()); - if ($contains_dis) - { - return $lng->txt("cont_page_deactivated_elements"); - } - } - } - return parent::getNodeIconAlt($a_node); - } - - /** - * Get href for node - * - * @param mixed $a_node node object/array - * @return string href attribute - */ - function getNodeHref($a_node) - { - $ilCtrl = $this->ctrl; - - switch($a_node["type"]) - { - case "du": + if (!$active) { + return $lng->txt("cont_page_deactivated"); + } else { + $contains_dis = ilLMPage::_lookupContainsDeactivatedElements( + $a_node["child"], + $this->lm->getType() + ); + if ($contains_dis) { + return $lng->txt("cont_page_deactivated_elements"); + } + } + } + return parent::getNodeIconAlt($a_node); + } + + /** + * Get href for node + * + * @param mixed $a_node node object/array + * @return string href attribute + */ + public function getNodeHref($a_node) + { + $ilCtrl = $this->ctrl; + + switch ($a_node["type"]) { + case "du": // $ilCtrl->setParameterByClass("ilobjlearningmodulegui", "obj_id", $a_node["child"]); - $ret = $ilCtrl->getLinkTargetByClass("ilobjlearningmodulegui", "chapters"); + $ret = $ilCtrl->getLinkTargetByClass("ilobjlearningmodulegui", "chapters"); // $ilCtrl->setParameterByClass("ilobjlearningmodulegui", "obj_id", $_GET["obj_id"]); - return $ret; - break; + return $ret; + break; - case "pg": - $ilCtrl->setParameterByClass("illmpageobjectgui", "obj_id", $a_node["child"]); - $ret = $ilCtrl->getLinkTargetByClass(array("ilobjlearningmodulegui", "illmpageobjectgui"), "edit"); - $ilCtrl->setParameterByClass("illmpageobjectgui", "obj_id", $_GET["obj_id"]); - return $ret; - break; - - case "st": - $ilCtrl->setParameterByClass("ilstructureobjectgui", "obj_id", $a_node["child"]); - $ret = $ilCtrl->getLinkTargetByClass(array("ilobjlearningmodulegui", "ilstructureobjectgui"), "view"); - $ilCtrl->setParameterByClass("ilstructureobjectgui", "obj_id", $_GET["obj_id"]); - return $ret; - break; - } - } + case "pg": + $ilCtrl->setParameterByClass("illmpageobjectgui", "obj_id", $a_node["child"]); + $ret = $ilCtrl->getLinkTargetByClass(array("ilobjlearningmodulegui", "illmpageobjectgui"), "edit"); + $ilCtrl->setParameterByClass("illmpageobjectgui", "obj_id", $_GET["obj_id"]); + return $ret; + break; + case "st": + $ilCtrl->setParameterByClass("ilstructureobjectgui", "obj_id", $a_node["child"]); + $ret = $ilCtrl->getLinkTargetByClass(array("ilobjlearningmodulegui", "ilstructureobjectgui"), "view"); + $ilCtrl->setParameterByClass("ilstructureobjectgui", "obj_id", $_GET["obj_id"]); + return $ret; + break; + } + } } - -?> diff --git a/Modules/LearningModule/classes/class.ilLMExplorerGUI.php b/Modules/LearningModule/classes/class.ilLMExplorerGUI.php index 67e93bb39751fd0a960d352f4118c8a8e243245e..85a9ab21fc72797a9eaec73344d92ef416a9087f 100644 --- a/Modules/LearningModule/classes/class.ilLMExplorerGUI.php +++ b/Modules/LearningModule/classes/class.ilLMExplorerGUI.php @@ -15,179 +15,168 @@ include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); */ class ilLMExplorerGUI extends ilTreeExplorerGUI { - /** - * @var ilObjUser - */ - protected $user; - - protected $lp_cache; // [array] - protected $cnt_lmobj; // number of items (chapters and pages) in the explorer - - /** - * Constructor - * - * @param object $a_parent_obj parent gui object - * @param string $a_parent_cmd parent cmd - * @param ilObjContentObject $a_lm learning module - */ - public function __construct($a_parent_obj, $a_parent_cmd, ilObjContentObject $a_lm, $a_id = "") - { - global $DIC; - - $this->user = $DIC->user(); - $this->lm = $a_lm; - - include_once("./Modules/LearningModule/classes/class.ilLMTree.php"); - $tree = ilLMTree::getInstance($this->lm->getId()); - -//echo "+".$tree->isCacheUsed()."+"; - -// $tree = new ilTree($this->lm->getId()); -// $tree->setTableNames('lm_tree','lm_data'); -// $tree->setTreeTablePK("lm_id"); - - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - $this->cnt_lmobj = ilLMObject::preloadDataByLM($this->lm->getId()); - - include_once("./Services/COPage/classes/class.ilPageObject.php"); - ilPageObject::preloadActivationDataByParentId($this->lm->getId()); - - if ($a_id == "") - { - $a_id = "lm_exp"; - - // this does not work, since it is not set yet - if ($this->getOfflineMode()) - { - $a_id = "lm_exp_off"; - } - } - - parent::__construct($a_id, $a_parent_obj, $a_parent_cmd, $tree); - - $this->setSkipRootNode(false); - $this->setAjax(false); - $this->setPreloadChilds(true); - - $this->setPathOpen($tree->readRootId()); - - if ((int) $_GET["obj_id"] > 0) - { - $this->setPathOpen((int) $_GET["obj_id"]); - } - } - - /** - * Before rendering - */ - function beforeRendering() - { - if ($this->cnt_lmobj > 200 && !$this->getOfflineMode()) - { - $this->setAjax(true); - } - } - - - /** - * Get node content - * - * @param array $a_node node array - * @return string node content - */ - function getNodeContent($a_node) - { - if ($a_node["child"] == $this->getNodeId($this->getRootNode())) - { - return $this->lm->getTitle(); - } - - $lang = ($_GET["transl"] != "") - ? $_GET["transl"] - : "-"; - return ilLMObject::_getPresentationTitle($a_node, IL_PAGE_TITLE, - $this->lm->isActiveNumbering(), false, false, $this->lm->getId(), $lang); - } - - /** - * Is node highlighted? - * - * @param mixed $a_node node object/array - * @return boolean node visible true/false - */ - function isNodeHighlighted($a_node) - { - if ($a_node["child"] == $_GET["obj_id"] || - ($_GET["obj_id"] == "" && $a_node["child"] == $this->getNodeId($this->getRootNode()))) - { - return true; - } - return false; - } - - /** - * Check learning progress icon - * - * @param int $a_id lm tree node id - * @return string image path - */ - protected function checkLPIcon($a_id) - { - $ilUser = $this->user; - - // do it once for all chapters - if($this->lp_cache[$this->lm->getId()] === null) - { - $this->lp_cache[$this->lm->getId()] = false; - - include_once './Services/Tracking/classes/class.ilLearningProgressAccess.php'; - if(ilLearningProgressAccess::checkAccess($this->lm->getRefId())) - { - $info = null; - - include_once './Services/Object/classes/class.ilObjectLP.php'; - $olp = ilObjectLP::getInstance($this->lm->getId()); - if($olp->getCurrentMode() == ilLPObjSettings::LP_MODE_COLLECTION_MANUAL || - $olp->getCurrentMode() == ilLPObjSettings::LP_MODE_COLLECTION_TLT) - { - include_once "Services/Tracking/classes/class.ilLPStatusFactory.php"; - $class = ilLPStatusFactory::_getClassById($this->lm->getId(), $olp->getCurrentMode()); - $info = $class::_getStatusInfo($this->lm->getId()); - } - - // parse collection items - if(is_array($info["items"])) - { - foreach($info["items"] as $item_id) - { - $status = ilLPStatus::LP_STATUS_NOT_ATTEMPTED_NUM; - if(is_array($info["in_progress"][$item_id]) && - in_array($ilUser->getId(), $info["in_progress"][$item_id])) - { - $status = ilLPStatus::LP_STATUS_IN_PROGRESS_NUM; - } - else if(is_array($info["completed"][$item_id]) && - in_array($ilUser->getId(), $info["completed"][$item_id])) - { - $status = ilLPStatus::LP_STATUS_COMPLETED_NUM; - } - $this->lp_cache[$this->lm->getId()][$item_id] =$status; - } - } - } - - include_once './Services/Tracking/classes/class.ilLearningProgressBaseGUI.php'; - } - - if(is_array($this->lp_cache[$this->lm->getId()]) && - isset($this->lp_cache[$this->lm->getId()][$a_id])) - { - return ilLearningProgressBaseGUI::_getImagePathForStatus($this->lp_cache[$this->lm->getId()][$a_id]); - } - - return ""; - } - + /** + * @var ilObjUser + */ + protected $user; + + protected $lp_cache; // [array] + protected $cnt_lmobj; // number of items (chapters and pages) in the explorer + + /** + * Constructor + * + * @param object $a_parent_obj parent gui object + * @param string $a_parent_cmd parent cmd + * @param ilObjContentObject $a_lm learning module + */ + public function __construct($a_parent_obj, $a_parent_cmd, ilObjContentObject $a_lm, $a_id = "") + { + global $DIC; + + $this->user = $DIC->user(); + $this->lm = $a_lm; + + include_once("./Modules/LearningModule/classes/class.ilLMTree.php"); + $tree = ilLMTree::getInstance($this->lm->getId()); + + //echo "+".$tree->isCacheUsed()."+"; + + // $tree = new ilTree($this->lm->getId()); + // $tree->setTableNames('lm_tree','lm_data'); + // $tree->setTreeTablePK("lm_id"); + + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + $this->cnt_lmobj = ilLMObject::preloadDataByLM($this->lm->getId()); + + include_once("./Services/COPage/classes/class.ilPageObject.php"); + ilPageObject::preloadActivationDataByParentId($this->lm->getId()); + + if ($a_id == "") { + $a_id = "lm_exp"; + + // this does not work, since it is not set yet + if ($this->getOfflineMode()) { + $a_id = "lm_exp_off"; + } + } + + parent::__construct($a_id, $a_parent_obj, $a_parent_cmd, $tree); + + $this->setSkipRootNode(false); + $this->setAjax(false); + $this->setPreloadChilds(true); + + $this->setPathOpen($tree->readRootId()); + + if ((int) $_GET["obj_id"] > 0) { + $this->setPathOpen((int) $_GET["obj_id"]); + } + } + + /** + * Before rendering + */ + public function beforeRendering() + { + if ($this->cnt_lmobj > 200 && !$this->getOfflineMode()) { + $this->setAjax(true); + } + } + + + /** + * Get node content + * + * @param array $a_node node array + * @return string node content + */ + public function getNodeContent($a_node) + { + if ($a_node["child"] == $this->getNodeId($this->getRootNode())) { + return $this->lm->getTitle(); + } + + $lang = ($_GET["transl"] != "") + ? $_GET["transl"] + : "-"; + return ilLMObject::_getPresentationTitle( + $a_node, + IL_PAGE_TITLE, + $this->lm->isActiveNumbering(), + false, + false, + $this->lm->getId(), + $lang + ); + } + + /** + * Is node highlighted? + * + * @param mixed $a_node node object/array + * @return boolean node visible true/false + */ + public function isNodeHighlighted($a_node) + { + if ($a_node["child"] == $_GET["obj_id"] || + ($_GET["obj_id"] == "" && $a_node["child"] == $this->getNodeId($this->getRootNode()))) { + return true; + } + return false; + } + + /** + * Check learning progress icon + * + * @param int $a_id lm tree node id + * @return string image path + */ + protected function checkLPIcon($a_id) + { + $ilUser = $this->user; + + // do it once for all chapters + if ($this->lp_cache[$this->lm->getId()] === null) { + $this->lp_cache[$this->lm->getId()] = false; + + include_once './Services/Tracking/classes/class.ilLearningProgressAccess.php'; + if (ilLearningProgressAccess::checkAccess($this->lm->getRefId())) { + $info = null; + + include_once './Services/Object/classes/class.ilObjectLP.php'; + $olp = ilObjectLP::getInstance($this->lm->getId()); + if ($olp->getCurrentMode() == ilLPObjSettings::LP_MODE_COLLECTION_MANUAL || + $olp->getCurrentMode() == ilLPObjSettings::LP_MODE_COLLECTION_TLT) { + include_once "Services/Tracking/classes/class.ilLPStatusFactory.php"; + $class = ilLPStatusFactory::_getClassById($this->lm->getId(), $olp->getCurrentMode()); + $info = $class::_getStatusInfo($this->lm->getId()); + } + + // parse collection items + if (is_array($info["items"])) { + foreach ($info["items"] as $item_id) { + $status = ilLPStatus::LP_STATUS_NOT_ATTEMPTED_NUM; + if (is_array($info["in_progress"][$item_id]) && + in_array($ilUser->getId(), $info["in_progress"][$item_id])) { + $status = ilLPStatus::LP_STATUS_IN_PROGRESS_NUM; + } elseif (is_array($info["completed"][$item_id]) && + in_array($ilUser->getId(), $info["completed"][$item_id])) { + $status = ilLPStatus::LP_STATUS_COMPLETED_NUM; + } + $this->lp_cache[$this->lm->getId()][$item_id] =$status; + } + } + } + + include_once './Services/Tracking/classes/class.ilLearningProgressBaseGUI.php'; + } + + if (is_array($this->lp_cache[$this->lm->getId()]) && + isset($this->lp_cache[$this->lm->getId()][$a_id])) { + return ilLearningProgressBaseGUI::_getImagePathForStatus($this->lp_cache[$this->lm->getId()][$a_id]); + } + + return ""; + } } - -?> diff --git a/Modules/LearningModule/classes/class.ilLMGlossaryTableGUI.php b/Modules/LearningModule/classes/class.ilLMGlossaryTableGUI.php index a63be681cf2a3a5a0f7d3fb7ce8ef8ca737a08dc..ce98fc4ed04aced8fdde2efdf0047e986fc000b6 100644 --- a/Modules/LearningModule/classes/class.ilLMGlossaryTableGUI.php +++ b/Modules/LearningModule/classes/class.ilLMGlossaryTableGUI.php @@ -14,65 +14,61 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilLMGlossaryTableGUI extends ilTable2GUI { - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * Constructor - */ - function __construct($a_lm, $a_parent_obj, $a_parent_cmd) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_lm, $a_parent_obj, $a_parent_cmd) + { + 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->lm = $a_lm; - $this->id = "lm_glo"; - - parent::__construct($a_parent_obj, $a_parent_cmd); - $data = array(); - foreach ($a_lm->getAutoGlossaries() as $glo_id) - { - $data[] = array("glo_id" => $glo_id, "title" => ilObject::_lookupTitle($glo_id)); - } - $this->setData($data); - $this->setTitle($lng->txt("cont_auto_glossaries")); - - $this->addColumn($this->lng->txt("title"), "title"); - $this->addColumn($this->lng->txt("actions")); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.lm_glossary_row.html", "Modules/LearningModule"); + $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->lm = $a_lm; + $this->id = "lm_glo"; + + parent::__construct($a_parent_obj, $a_parent_cmd); + $data = array(); + foreach ($a_lm->getAutoGlossaries() as $glo_id) { + $data[] = array("glo_id" => $glo_id, "title" => ilObject::_lookupTitle($glo_id)); + } + $this->setData($data); + $this->setTitle($lng->txt("cont_auto_glossaries")); + + $this->addColumn($this->lng->txt("title"), "title"); + $this->addColumn($this->lng->txt("actions")); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.lm_glossary_row.html", "Modules/LearningModule"); -// $this->addMultiCommand("", $lng->txt("")); + // $this->addMultiCommand("", $lng->txt("")); // $this->addCommandButton("", $lng->txt("")); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; - $ilCtrl->setParameter($this->parent_obj, "glo_id", $a_set["glo_id"]); - $this->tpl->setCurrentBlock("cmd"); - $this->tpl->setVariable("CMD_HREF", $ilCtrl->getLinkTarget($this->parent_obj, "removeLMGlossary")); - $this->tpl->setVariable("CMD_TXT", $lng->txt("remove")); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setVariable("TITLE", ilObject::_lookupTitle($a_set["glo_id"])); - } - - + $ilCtrl->setParameter($this->parent_obj, "glo_id", $a_set["glo_id"]); + $this->tpl->setCurrentBlock("cmd"); + $this->tpl->setVariable("CMD_HREF", $ilCtrl->getLinkTarget($this->parent_obj, "removeLMGlossary")); + $this->tpl->setVariable("CMD_TXT", $lng->txt("remove")); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setVariable("TITLE", ilObject::_lookupTitle($a_set["glo_id"])); + } } -?> diff --git a/Modules/LearningModule/classes/class.ilLMImportGUI.php b/Modules/LearningModule/classes/class.ilLMImportGUI.php index ab0a9443a1e2946bde432ff48c3e7dfdf686ed38..7a41e98f3c7b2af7b06fb264f3e4cbf6597c82de 100644 --- a/Modules/LearningModule/classes/class.ilLMImportGUI.php +++ b/Modules/LearningModule/classes/class.ilLMImportGUI.php @@ -11,138 +11,135 @@ */ class ilLMImportGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTemplate - */ - protected $tpl; - - protected $lm; - - /** - * Constructor - */ - function __construct($a_lm) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - $this->lm = $a_lm; - } - - /** - * Execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - - $cmd = $ilCtrl->getCmd("showTranslationImportForm"); - - if (in_array($cmd, array("showTranslationImportForm", "importTranslation"))) - { - $this->$cmd(); - } - } - - /** - * Translation import - * - * @param - * @return - */ - function showTranslationImportForm() - { - $lng = $this->lng; - $tpl = $this->tpl; - - ilUtil::sendInfo($lng->txt("cont_trans_import_info")); - $form = $this->initTranslationImportForm(); - $tpl->setContent($form->getHTML()); - } - - /** - * Init translation input form. - */ - public function initTranslationImportForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $lng->loadLanguageModule("meta"); - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - - // import file - $fi = new ilFileInputGUI($lng->txt("file"), "importfile"); - $fi->setSuffixes(array("zip")); - $fi->setRequired(true); - $fi->setSize(30); - $form->addItem($fi); - - include_once("./Services/MetaData/classes/class.ilMDLanguageItem.php"); - include_once("./Services/Object/classes/class.ilObjectTranslation.php"); - $ot = ilObjectTranslation::getInstance($this->lm->getId()); - foreach ($ot->getLanguages() as $l) - { - if ($l["lang_code"] != $ot->getMasterLanguage()) - { - $options[$l["lang_code"]] = $lng->txt("meta_l_".$l["lang_code"]); - } - } - $si = new ilSelectInputGUI($lng->txt("cont_import_lang"), "import_lang"); - $si->setOptions($options); - $form->addItem($si); - - $form->addCommandButton("importTranslation", $lng->txt("import")); - $form->setTitle($lng->txt("cont_import_trans")); - $form->setFormAction($ilCtrl->getFormAction($this)); - - return $form; - } - - /** - * Import translation - */ - function importTranslation() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - include_once("./Services/Export/classes/class.ilImport.php"); - $imp = new ilImport(); - $conf = $imp->getConfig("Modules/LearningModule"); - - $target_lang = ilUtil::stripSlashes($_POST["import_lang"]); - include_once("./Services/Object/classes/class.ilObjectTranslation.php"); - $ot = ilObjectTranslation::getInstance($this->lm->getId()); - if ($target_lang == $ot->getMasterLanguage() || $target_lang == "") - { - ilUtil::sendFailure($lng->txt("cont_transl_master_language_not_allowed"), true); - $ilCtrl->redirect($this, "showTranslationImportForm"); - } - - $conf->setTranslationImportMode($this->lm, $target_lang); - $imp->importObject(null, $_FILES["importfile"]["tmp_name"], - $_FILES["importfile"]["name"], "lm", "Modules/LearningModule"); -//echo "h"; exit; - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "showTranslationImportForm"); - } - - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTemplate + */ + protected $tpl; + + protected $lm; + + /** + * Constructor + */ + public function __construct($a_lm) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + $this->lm = $a_lm; + } + + /** + * Execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $cmd = $ilCtrl->getCmd("showTranslationImportForm"); + + if (in_array($cmd, array("showTranslationImportForm", "importTranslation"))) { + $this->$cmd(); + } + } + + /** + * Translation import + * + * @param + * @return + */ + public function showTranslationImportForm() + { + $lng = $this->lng; + $tpl = $this->tpl; + + ilUtil::sendInfo($lng->txt("cont_trans_import_info")); + $form = $this->initTranslationImportForm(); + $tpl->setContent($form->getHTML()); + } + + /** + * Init translation input form. + */ + public function initTranslationImportForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $lng->loadLanguageModule("meta"); + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + + // import file + $fi = new ilFileInputGUI($lng->txt("file"), "importfile"); + $fi->setSuffixes(array("zip")); + $fi->setRequired(true); + $fi->setSize(30); + $form->addItem($fi); + + include_once("./Services/MetaData/classes/class.ilMDLanguageItem.php"); + include_once("./Services/Object/classes/class.ilObjectTranslation.php"); + $ot = ilObjectTranslation::getInstance($this->lm->getId()); + foreach ($ot->getLanguages() as $l) { + if ($l["lang_code"] != $ot->getMasterLanguage()) { + $options[$l["lang_code"]] = $lng->txt("meta_l_" . $l["lang_code"]); + } + } + $si = new ilSelectInputGUI($lng->txt("cont_import_lang"), "import_lang"); + $si->setOptions($options); + $form->addItem($si); + + $form->addCommandButton("importTranslation", $lng->txt("import")); + $form->setTitle($lng->txt("cont_import_trans")); + $form->setFormAction($ilCtrl->getFormAction($this)); + + return $form; + } + + /** + * Import translation + */ + public function importTranslation() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + include_once("./Services/Export/classes/class.ilImport.php"); + $imp = new ilImport(); + $conf = $imp->getConfig("Modules/LearningModule"); + + $target_lang = ilUtil::stripSlashes($_POST["import_lang"]); + include_once("./Services/Object/classes/class.ilObjectTranslation.php"); + $ot = ilObjectTranslation::getInstance($this->lm->getId()); + if ($target_lang == $ot->getMasterLanguage() || $target_lang == "") { + ilUtil::sendFailure($lng->txt("cont_transl_master_language_not_allowed"), true); + $ilCtrl->redirect($this, "showTranslationImportForm"); + } + + $conf->setTranslationImportMode($this->lm, $target_lang); + $imp->importObject( + null, + $_FILES["importfile"]["tmp_name"], + $_FILES["importfile"]["name"], + "lm", + "Modules/LearningModule" + ); + //echo "h"; exit; + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "showTranslationImportForm"); + } } - -?> \ No newline at end of file diff --git a/Modules/LearningModule/classes/class.ilLMLayout.php b/Modules/LearningModule/classes/class.ilLMLayout.php index 2d05ac78b8776724af659a166779ec9b583730cf..acd2c7e2e05e93ea6b39254be667e76ac618f278 100755 --- a/Modules/LearningModule/classes/class.ilLMLayout.php +++ b/Modules/LearningModule/classes/class.ilLMLayout.php @@ -1,24 +1,24 @@ keep_with_previous = $a_keep; - } - - - /** - * get keep with previous - */ - function getKeepWithPrevious () - { - return $this->keep_with_previous; - } - - - /** - * set keep with next - * - * @param boolean $a_keep - */ - function setKeepWithNext ($a_keep) - { - $this->keep_with_next = $a_keep; - } - - - /** - * get keep with next - */ - function getKeepWithNext () - { - return $this->keep_with_next; - } - - - /** - * set css url - * - * @param string $a_url CSS URL - */ - function setCssUrl ($a_url) - { - $this->css_url = $a_url; - } - - - /** - * get css url - */ - function getCssUrl () - { - return $this->css_url; - } - - /** - * set horizontal align - * - * @param string $a_align left | center | right - */ - function setHorizontalAlign ($a_align) - { - $this->hor_align = $a_align; - } - - /** - * get horizontal align - */ - function getHorizontalAlign () - { - return $this->hor_align; - } - - /** - * set vertical align - * - * @param string $a_align top | middle | bottom - */ - function setVerticalAlign ($a_align) - { - $this->ver_align = $a_align; - } - - /** - * get vertical align - */ - function getVerticalAlign () - { - return $this->ver_align; - } - - - /** - * set target frame ????? - * - * @param string $a_align Media | FAQ | Glossary - */ - function setTargetFrame ($a_frame) - { - $this->target_frame = $a_frame; - } - - /** - * get target frame ????? - */ - function getTargetFrame () - { - return $this->target_frame; - } - - /** - * set width - * - * @param string $a_width width - */ - function setWidth ($a_width) - { - $this->width = $a_width; - } - - /** - * get width - */ - function getWidth () - { - return $this->width; - } - - /** - * set height - * - * @param string $a_height height - */ - function setHeight ($a_height) - { - $this->height = $a_height; - } - - /** - * get height - */ - function getHeight () - { - return $this->height; - } - + public $keep_with_previous; + public $keep_with_next; + public $css_url; + public $ver_align; + public $hor_align; + public $target_frame; + public $width; + public $height; + + /** + * Constructor + * @access public + */ + public function __construct() + { + } + + /** + * set keep with previous + * + * @param boolean $a_keep + */ + public function setKeepWithPrevious($a_keep) + { + $this->keep_with_previous = $a_keep; + } + + + /** + * get keep with previous + */ + public function getKeepWithPrevious() + { + return $this->keep_with_previous; + } + + + /** + * set keep with next + * + * @param boolean $a_keep + */ + public function setKeepWithNext($a_keep) + { + $this->keep_with_next = $a_keep; + } + + + /** + * get keep with next + */ + public function getKeepWithNext() + { + return $this->keep_with_next; + } + + + /** + * set css url + * + * @param string $a_url CSS URL + */ + public function setCssUrl($a_url) + { + $this->css_url = $a_url; + } + + + /** + * get css url + */ + public function getCssUrl() + { + return $this->css_url; + } + + /** + * set horizontal align + * + * @param string $a_align left | center | right + */ + public function setHorizontalAlign($a_align) + { + $this->hor_align = $a_align; + } + + /** + * get horizontal align + */ + public function getHorizontalAlign() + { + return $this->hor_align; + } + + /** + * set vertical align + * + * @param string $a_align top | middle | bottom + */ + public function setVerticalAlign($a_align) + { + $this->ver_align = $a_align; + } + + /** + * get vertical align + */ + public function getVerticalAlign() + { + return $this->ver_align; + } + + + /** + * set target frame ????? + * + * @param string $a_align Media | FAQ | Glossary + */ + public function setTargetFrame($a_frame) + { + $this->target_frame = $a_frame; + } + + /** + * get target frame ????? + */ + public function getTargetFrame() + { + return $this->target_frame; + } + + /** + * set width + * + * @param string $a_width width + */ + public function setWidth($a_width) + { + $this->width = $a_width; + } + + /** + * get width + */ + public function getWidth() + { + return $this->width; + } + + /** + * set height + * + * @param string $a_height height + */ + public function setHeight($a_height) + { + $this->height = $a_height; + } + + /** + * get height + */ + public function getHeight() + { + return $this->height; + } } -?> diff --git a/Modules/LearningModule/classes/class.ilLMMailNotification.php b/Modules/LearningModule/classes/class.ilLMMailNotification.php index d8d7602259b4a451cc5097ea2ce1abe7ae39b9eb..84af8c4c4d93f20102366b614c7422731874cc43 100644 --- a/Modules/LearningModule/classes/class.ilLMMailNotification.php +++ b/Modules/LearningModule/classes/class.ilLMMailNotification.php @@ -6,112 +6,116 @@ include_once './Services/Mail/classes/class.ilMailNotification.php'; /** * @author Alex Killing * @version $Id$ - * + * * @ingroup ModulesLearningModule */ class ilLMMailNotification extends ilMailNotification { - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - /** - * Constructor - */ - function __construct($a_is_personal_workspace = false) - { - global $DIC; - parent::__construct($a_is_personal_workspace); + /** + * Constructor + */ + public function __construct($a_is_personal_workspace = false) + { + global $DIC; + parent::__construct($a_is_personal_workspace); - $this->user = $DIC->user(); - } + $this->user = $DIC->user(); + } - const TYPE_USER_BLOCKED = 10; + const TYPE_USER_BLOCKED = 10; - /** - * Set question id - * - * @param int $a_val question id - */ - function setQuestionId($a_val) - { - $this->question_id = $a_val; - } + /** + * Set question id + * + * @param int $a_val question id + */ + public function setQuestionId($a_val) + { + $this->question_id = $a_val; + } - /** - * Get question id - * - * @return int question id - */ - function getQuestionId() - { - return $this->question_id; - } + /** + * Get question id + * + * @return int question id + */ + public function getQuestionId() + { + return $this->question_id; + } - /** - * Send notifications - * @return - */ - public function send() - { - $ilUser = $this->user; - - switch($this->getType()) - { - case self::TYPE_USER_BLOCKED: - - foreach($this->getRecipients() as $rcp) - { - $this->initLanguage($rcp); - $this->initMail(); - $this->setSubject( - sprintf($this->getLanguageText('cont_user_blocked'), - $this->getObjectTitle(true)) - ); - $this->setBody(ilMail::getSalutation($rcp,$this->getLanguage())); - $this->appendBody("\n\n"); - $this->appendBody( - $this->getLanguageText('cont_user_blocked2')); - $this->appendBody("\n"); - $this->appendBody( - $this->getLanguageText('cont_user_blocked3')." '".$this->getLanguageText('objs_qst')."' > '".$this->getLanguageText('cont_blocked_users')."'"); - $this->appendBody("\n"); - $this->appendBody( - $this->getLanguageText('obj_lm').": ".$this->getObjectTitle(true)); - $this->appendBody("\n"); - include_once("./Services/User/classes/class.ilUserUtil.php"); - $this->appendBody( - $this->getLanguageText('user').": ".ilUserUtil::getNamePresentation($ilUser->getId(), false, false, "")); - $this->appendBody("\n"); + /** + * Send notifications + * @return + */ + public function send() + { + $ilUser = $this->user; + + switch ($this->getType()) { + case self::TYPE_USER_BLOCKED: + + foreach ($this->getRecipients() as $rcp) { + $this->initLanguage($rcp); + $this->initMail(); + $this->setSubject( + sprintf( + $this->getLanguageText('cont_user_blocked'), + $this->getObjectTitle(true) + ) + ); + $this->setBody(ilMail::getSalutation($rcp, $this->getLanguage())); + $this->appendBody("\n\n"); + $this->appendBody( + $this->getLanguageText('cont_user_blocked2') + ); + $this->appendBody("\n"); + $this->appendBody( + $this->getLanguageText('cont_user_blocked3') . " '" . $this->getLanguageText('objs_qst') . "' > '" . $this->getLanguageText('cont_blocked_users') . "'" + ); + $this->appendBody("\n"); + $this->appendBody( + $this->getLanguageText('obj_lm') . ": " . $this->getObjectTitle(true) + ); + $this->appendBody("\n"); + include_once("./Services/User/classes/class.ilUserUtil.php"); + $this->appendBody( + $this->getLanguageText('user') . ": " . ilUserUtil::getNamePresentation($ilUser->getId(), false, false, "") + ); + $this->appendBody("\n"); - include_once("./Modules/TestQuestionPool/classes/class.assQuestion.php"); - $this->appendBody( - $this->getLanguageText('question').": ".assQuestion::_getTitle($this->getQuestionId())); - $this->appendBody("\n"); - $this->appendBody("\n\n"); - $this->appendBody($this->getLanguageText('cont_lm_mail_permanent_link')); - $this->appendBody("\n"); - $this->appendBody($this->createPermanentLink(array(), "")); - $this->getMail()->appendInstallationSignature(true); - $this->sendMail(array($rcp),array('system')); - } - break; + include_once("./Modules/TestQuestionPool/classes/class.assQuestion.php"); + $this->appendBody( + $this->getLanguageText('question') . ": " . assQuestion::_getTitle($this->getQuestionId()) + ); + $this->appendBody("\n"); + $this->appendBody("\n\n"); + $this->appendBody($this->getLanguageText('cont_lm_mail_permanent_link')); + $this->appendBody("\n"); + $this->appendBody($this->createPermanentLink(array(), "")); + $this->getMail()->appendInstallationSignature(true); + $this->sendMail(array($rcp), array('system')); + } + break; - } - return true; - } - - /** - * Init language - * - * @param int $a_usr_id user id - */ - protected function initLanguage($a_usr_id) - { - parent::initLanguage($a_usr_id); - $this->getLanguage()->loadLanguageModule('content'); - } + } + return true; + } + + /** + * Init language + * + * @param int $a_usr_id user id + */ + protected function initLanguage($a_usr_id) + { + parent::initLanguage($a_usr_id); + $this->getLanguage()->loadLanguageModule('content'); + } } -?> \ No newline at end of file diff --git a/Modules/LearningModule/classes/class.ilLMMenuEditor.php b/Modules/LearningModule/classes/class.ilLMMenuEditor.php index c09c915d0886d91fc005a4ddc3a69c86d60fb5a6..c882c1e069c39900744fe80bc005482454091f14 100644 --- a/Modules/LearningModule/classes/class.ilLMMenuEditor.php +++ b/Modules/LearningModule/classes/class.ilLMMenuEditor.php @@ -1,24 +1,24 @@ database(); + $ilDB = $DIC->database(); - $this->db = $ilDB; - $this->link_type = "extern"; - $this->link_ref_id = null; - } + $this->db = $ilDB; + $this->link_type = "extern"; + $this->link_ref_id = null; + } - function setObjId($a_obj_id) - { - $this->lm_id = $a_obj_id; - } + public function setObjId($a_obj_id) + { + $this->lm_id = $a_obj_id; + } - function getObjId() - { - return $this->lm_id; - } + public function getObjId() + { + return $this->lm_id; + } - function setEntryId($a_id) - { - $this->entry_id = $a_id; - } + public function setEntryId($a_id) + { + $this->entry_id = $a_id; + } - function getEntryId() - { - return $this->entry_id; - } + public function getEntryId() + { + return $this->entry_id; + } - function setLinkType($a_link_type) - { - $this->link_type = $a_link_type; - } - - function getLinkType() - { - return $this->link_type; - } - - function setTitle($a_title) - { - $this->title = $a_title; - } + public function setLinkType($a_link_type) + { + $this->link_type = $a_link_type; + } + + public function getLinkType() + { + return $this->link_type; + } + + public function setTitle($a_title) + { + $this->title = $a_title; + } - function getTitle() - { - return $this->title; - } - - function setTarget($a_target) - { - $this->target = $a_target; - } - - function getTarget() - { - return $this->target; - } - - function setLinkRefId($a_link_ref_id) - { - $this->link_ref_id = $a_link_ref_id; - } + public function getTitle() + { + return $this->title; + } + + public function setTarget($a_target) + { + $this->target = $a_target; + } + + public function getTarget() + { + return $this->target; + } + + public function setLinkRefId($a_link_ref_id) + { + $this->link_ref_id = $a_link_ref_id; + } - function getLinkRefId() - { - return $this->link_ref_id; - } - - /** - * Set active - * - * @param string $a_val - */ - function setActive($a_val) - { - $this->active = $a_val; - } - - /** - * Get active - * - * @return string - */ - function getActive() - { - return $this->active; - } - + public function getLinkRefId() + { + return $this->link_ref_id; + } + + /** + * Set active + * + * @param string $a_val + */ + public function setActive($a_val) + { + $this->active = $a_val; + } + + /** + * Get active + * + * @return string + */ + public function getActive() + { + return $this->active; + } + - function create() - { - $ilDB = $this->db; - - $id = $ilDB->nextId("lm_menu"); - $q = "INSERT INTO lm_menu (id, lm_id,link_type,title,target,link_ref_id, active) ". - "VALUES ". - "(". - $ilDB->quote($id, "integer").",". - $ilDB->quote((int) $this->getObjId(), "integer").",". - $ilDB->quote($this->getLinkType(), "text").",". - $ilDB->quote($this->getTitle(), "text").",". - $ilDB->quote($this->getTarget(), "text").",". - $ilDB->quote((int) $this->getLinkRefId(), "integer").",". - $ilDB->quote($this->getActive(), "text"). - ")"; - $r = $ilDB->manipulate($q); + public function create() + { + $ilDB = $this->db; + + $id = $ilDB->nextId("lm_menu"); + $q = "INSERT INTO lm_menu (id, lm_id,link_type,title,target,link_ref_id, active) " . + "VALUES " . + "(" . + $ilDB->quote($id, "integer") . "," . + $ilDB->quote((int) $this->getObjId(), "integer") . "," . + $ilDB->quote($this->getLinkType(), "text") . "," . + $ilDB->quote($this->getTitle(), "text") . "," . + $ilDB->quote($this->getTarget(), "text") . "," . + $ilDB->quote((int) $this->getLinkRefId(), "integer") . "," . + $ilDB->quote($this->getActive(), "text") . + ")"; + $r = $ilDB->manipulate($q); - $this->entry_id = $id; + $this->entry_id = $id; - return true; - } - - function getMenuEntries($a_only_active = false) - { - $ilDB = $this->db; - - $entries = array(); - - if ($a_only_active === true) - { - $and = " AND active = ".$ilDB->quote("y", "text"); - } - - $q = "SELECT * FROM lm_menu ". - "WHERE lm_id = ".$ilDB->quote($this->lm_id, "integer"). - $and; - - $r = $ilDB->query($q); + return true; + } + + public function getMenuEntries($a_only_active = false) + { + $ilDB = $this->db; + + $entries = array(); + + if ($a_only_active === true) { + $and = " AND active = " . $ilDB->quote("y", "text"); + } + + $q = "SELECT * FROM lm_menu " . + "WHERE lm_id = " . $ilDB->quote($this->lm_id, "integer") . + $and; + + $r = $ilDB->query($q); - while($row = $ilDB->fetchObject($r)) - { - $entries[] = array('id' => $row->id, - 'title' => $row->title, - 'link' => $row->target, - 'type' => $row->link_type, - 'ref_id' => $row->link_ref_id, - 'active' => $row->active - ); - } + while ($row = $ilDB->fetchObject($r)) { + $entries[] = array('id' => $row->id, + 'title' => $row->title, + 'link' => $row->target, + 'type' => $row->link_type, + 'ref_id' => $row->link_ref_id, + 'active' => $row->active + ); + } - return $entries; - } - - /** - * delete menu entry - * - */ - function delete($a_id) - { - $ilDB = $this->db; - - if (!$a_id) - { - return false; - } - - $q = "DELETE FROM lm_menu WHERE id = ". - $ilDB->quote($a_id, "integer"); - $ilDB->manipulate($q); - - return true; - } - - /** - * update menu entry - * - */ - function update() - { - $ilDB = $this->db; - - $q = "UPDATE lm_menu SET ". - " link_type = ".$ilDB->quote($this->getLinkType(), "text").",". - " title = ".$ilDB->quote($this->getTitle(), "text").",". - " target = ".$ilDB->quote($this->getTarget(), "text").",". - " link_ref_id = ".$ilDB->quote((int) $this->getLinkRefId(), "integer"). - " WHERE id = ".$ilDB->quote($this->getEntryId(), "integer"); - $r = $ilDB->manipulate($q); - - return true; - } - - function readEntry($a_id) - { - $ilDB = $this->db; - - if (!$a_id) - { - return false; - } - - $q = "SELECT * FROM lm_menu WHERE id = ". - $ilDB->quote($a_id, "integer"); - $r = $ilDB->query($q); + return $entries; + } + + /** + * delete menu entry + * + */ + public function delete($a_id) + { + $ilDB = $this->db; + + if (!$a_id) { + return false; + } + + $q = "DELETE FROM lm_menu WHERE id = " . + $ilDB->quote($a_id, "integer"); + $ilDB->manipulate($q); + + return true; + } + + /** + * update menu entry + * + */ + public function update() + { + $ilDB = $this->db; + + $q = "UPDATE lm_menu SET " . + " link_type = " . $ilDB->quote($this->getLinkType(), "text") . "," . + " title = " . $ilDB->quote($this->getTitle(), "text") . "," . + " target = " . $ilDB->quote($this->getTarget(), "text") . "," . + " link_ref_id = " . $ilDB->quote((int) $this->getLinkRefId(), "integer") . + " WHERE id = " . $ilDB->quote($this->getEntryId(), "integer"); + $r = $ilDB->manipulate($q); + + return true; + } + + public function readEntry($a_id) + { + $ilDB = $this->db; + + if (!$a_id) { + return false; + } + + $q = "SELECT * FROM lm_menu WHERE id = " . + $ilDB->quote($a_id, "integer"); + $r = $ilDB->query($q); - $row = $ilDB->fetchObject($r); - - $this->setTitle($row->title); - $this->setTarget($row->target); - $this->setLinkType($row->link_type); - $this->setLinkRefId($row->link_ref_id); - $this->setEntryid($a_id); - $this->setActive($row->active); - } - - /** - * update active status of all menu entries of lm - * @param array entry ids - * - */ - function updateActiveStatus($a_entries) - { - $ilDB = $this->db; - - // update active status - $q = "UPDATE lm_menu SET " . - "active = CASE " . - "WHEN ".$ilDB->in("id", $a_entries, false, "integer")." ". - "THEN ".$ilDB->quote("y", "text")." ". - "ELSE ".$ilDB->quote("n", "text")." ". - "END " . - "WHERE lm_id = ".$ilDB->quote($this->lm_id, "integer"); + $row = $ilDB->fetchObject($r); + + $this->setTitle($row->title); + $this->setTarget($row->target); + $this->setLinkType($row->link_type); + $this->setLinkRefId($row->link_ref_id); + $this->setEntryid($a_id); + $this->setActive($row->active); + } + + /** + * update active status of all menu entries of lm + * @param array entry ids + * + */ + public function updateActiveStatus($a_entries) + { + $ilDB = $this->db; + + // update active status + $q = "UPDATE lm_menu SET " . + "active = CASE " . + "WHEN " . $ilDB->in("id", $a_entries, false, "integer") . " " . + "THEN " . $ilDB->quote("y", "text") . " " . + "ELSE " . $ilDB->quote("n", "text") . " " . + "END " . + "WHERE lm_id = " . $ilDB->quote($this->lm_id, "integer"); - $ilDB->manipulate($q); - } + $ilDB->manipulate($q); + } - /** - * Fix ref ids on import - * - * @param int $new_lm_id - * @param array $ref_mapping - */ - public static function fixImportMenuItems(int $new_lm_id, array $ref_mapping) - { - global $DIC; + /** + * Fix ref ids on import + * + * @param int $new_lm_id + * @param array $ref_mapping + */ + public static function fixImportMenuItems(int $new_lm_id, array $ref_mapping) + { + global $DIC; - $db = $DIC->database(); + $db = $DIC->database(); - $set = $db->queryF("SELECT * FROM lm_menu ". - " WHERE lm_id = %s ", - array("integer"), - array($new_lm_id) - ); - while ($rec = $db->fetchAssoc($set)) - { - // ... only check internal links - if ($rec["link_type"] == "intern") - { - $link = explode("_", $rec["link_ref_id"]); - $ref_id = (int) $link[count($link)-1]; - $new_ref_id = $ref_mapping[$ref_id]; - // if ref id has been imported, update it - if ($new_ref_id > 0) - { - $new_target = str_replace((string) $ref_id, (string) $new_ref_id, $rec["target"]); - $db->update("lm_menu", array( - "link_ref_id" => array("integer", $new_ref_id), - "target" => array("text", $new_target) - ), array( // where - "id" => array("integer", $rec["id"]) - )); - } - else // if not, delete the menu item - { - $db->manipulateF("DELETE FROM lm_menu WHERE ". - " id = %s", - array("integer"), - array($rec["id"])); - } - } - } - } + $set = $db->queryF( + "SELECT * FROM lm_menu " . + " WHERE lm_id = %s ", + array("integer"), + array($new_lm_id) + ); + while ($rec = $db->fetchAssoc($set)) { + // ... only check internal links + if ($rec["link_type"] == "intern") { + $link = explode("_", $rec["link_ref_id"]); + $ref_id = (int) $link[count($link)-1]; + $new_ref_id = $ref_mapping[$ref_id]; + // if ref id has been imported, update it + if ($new_ref_id > 0) { + $new_target = str_replace((string) $ref_id, (string) $new_ref_id, $rec["target"]); + $db->update("lm_menu", array( + "link_ref_id" => array("integer", $new_ref_id), + "target" => array("text", $new_target) + ), array( // where + "id" => array("integer", $rec["id"]) + )); + } else { // if not, delete the menu item + $db->manipulateF( + "DELETE FROM lm_menu WHERE " . + " id = %s", + array("integer"), + array($rec["id"]) + ); + } + } + } + } - /** - * Write status for entry id - * - * @param $entry_id - * @param $active - */ - static public function writeActive($entry_id, $active) - { - global $DIC; + /** + * Write status for entry id + * + * @param $entry_id + * @param $active + */ + public static function writeActive($entry_id, $active) + { + global $DIC; - $db = $DIC->database(); + $db = $DIC->database(); - $db->update("lm_menu", array( - "active" => array("text", ($active ? "y" : "n")) - ), array( // where - "id" => array("", $entry_id) - )); - } - + $db->update("lm_menu", array( + "active" => array("text", ($active ? "y" : "n")) + ), array( // where + "id" => array("", $entry_id) + )); + } } -?> diff --git a/Modules/LearningModule/classes/class.ilLMMenuItemsTableGUI.php b/Modules/LearningModule/classes/class.ilLMMenuItemsTableGUI.php index bb662778a210dc239f7a4f463840c9f60337971f..a53b7d5e3f313166f796ccdd74a9456875cbb38d 100644 --- a/Modules/LearningModule/classes/class.ilLMMenuItemsTableGUI.php +++ b/Modules/LearningModule/classes/class.ilLMMenuItemsTableGUI.php @@ -14,92 +14,85 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilLMMenuItemsTableGUI extends ilTable2GUI { - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_lmme) - { - 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(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->lmme = $a_lmme; - $entries = $this->lmme->getMenuEntries(); - - $this->setData($entries); - $this->setTitle($lng->txt("cont_custom_menu_entries")); - $this->disable("footer"); - -// $this->addColumn("", "", "1px", true); - $this->addColumn($this->lng->txt("link")); - $this->addColumn($this->lng->txt("active")); - $this->addColumn($this->lng->txt("actions")); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.lm_menu_entry_row.html", "Modules/LearningModule"); - -// $this->addMultiCommand("deleteMenuEntry", $lng->txt("delete")); - $this->addCommandButton("saveMenuProperties", $lng->txt("save")); - } - - /** - * Fill table row - */ - protected function fillRow($entry) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameter($this->parent_obj, "menu_entry", $entry["id"]); - - $this->tpl->setCurrentBlock("cmd"); - $this->tpl->setVariable("HREF_CMD", $ilCtrl->getLinkTarget($this->parent_obj,"editMenuEntry")); - $this->tpl->setVariable("CMD", $this->lng->txt("edit")); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setCurrentBlock("cmd"); - $this->tpl->setVariable("HREF_CMD", $ilCtrl->getLinkTarget($this->parent_obj,"deleteMenuEntry")); - $this->tpl->setVariable("CMD", $this->lng->txt("delete")); - $this->tpl->parseCurrentBlock(); - - $ilCtrl->setParameter($this, "menu_entry", ""); - - $this->tpl->setVariable("LINK_ID", $entry["id"]); - - if ($entry["type"] == "intern") - { - $entry["link"] = ILIAS_HTTP_PATH."/goto.php?target=".$entry["link"]; - } - - // add http:// prefix if not exist - if (!strstr($entry["link"],'://') && !strstr($entry["link"],'mailto:')) - { - $entry["link"] = "http://".$entry["link"]; - } - - $this->tpl->setVariable("HREF_LINK", $entry["link"]); - $this->tpl->setVariable("LINK", $entry["title"]); - - if (ilUtil::yn2tf($entry["active"])) - { - $this->tpl->setVariable("ACTIVE_CHECK", "checked=\"checked\""); - } - - - } - + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_lmme) + { + 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(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->lmme = $a_lmme; + $entries = $this->lmme->getMenuEntries(); + + $this->setData($entries); + $this->setTitle($lng->txt("cont_custom_menu_entries")); + $this->disable("footer"); + + // $this->addColumn("", "", "1px", true); + $this->addColumn($this->lng->txt("link")); + $this->addColumn($this->lng->txt("active")); + $this->addColumn($this->lng->txt("actions")); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.lm_menu_entry_row.html", "Modules/LearningModule"); + + // $this->addMultiCommand("deleteMenuEntry", $lng->txt("delete")); + $this->addCommandButton("saveMenuProperties", $lng->txt("save")); + } + + /** + * Fill table row + */ + protected function fillRow($entry) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameter($this->parent_obj, "menu_entry", $entry["id"]); + + $this->tpl->setCurrentBlock("cmd"); + $this->tpl->setVariable("HREF_CMD", $ilCtrl->getLinkTarget($this->parent_obj, "editMenuEntry")); + $this->tpl->setVariable("CMD", $this->lng->txt("edit")); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setCurrentBlock("cmd"); + $this->tpl->setVariable("HREF_CMD", $ilCtrl->getLinkTarget($this->parent_obj, "deleteMenuEntry")); + $this->tpl->setVariable("CMD", $this->lng->txt("delete")); + $this->tpl->parseCurrentBlock(); + + $ilCtrl->setParameter($this, "menu_entry", ""); + + $this->tpl->setVariable("LINK_ID", $entry["id"]); + + if ($entry["type"] == "intern") { + $entry["link"] = ILIAS_HTTP_PATH . "/goto.php?target=" . $entry["link"]; + } + + // add http:// prefix if not exist + if (!strstr($entry["link"], '://') && !strstr($entry["link"], 'mailto:')) { + $entry["link"] = "http://" . $entry["link"]; + } + + $this->tpl->setVariable("HREF_LINK", $entry["link"]); + $this->tpl->setVariable("LINK", $entry["title"]); + + if (ilUtil::yn2tf($entry["active"])) { + $this->tpl->setVariable("ACTIVE_CHECK", "checked=\"checked\""); + } + } } -?> diff --git a/Modules/LearningModule/classes/class.ilLMMenuObjectSelector.php b/Modules/LearningModule/classes/class.ilLMMenuObjectSelector.php index 4f996b5c2d4a3fbc920d3fd59ba0e2a906159c79..419260aaeeab169740f27c22ea57bdebb3973f18 100644 --- a/Modules/LearningModule/classes/class.ilLMMenuObjectSelector.php +++ b/Modules/LearningModule/classes/class.ilLMMenuObjectSelector.php @@ -15,119 +15,110 @@ require_once("./Services/UIComponent/Explorer/classes/class.ilExplorer.php"); class ilLMMenuObjectSelector extends ilExplorer { - /** - * id of root folder - * @var int root folder id - * @access private - */ - var $root_id; - var $output; - var $ctrl; - var $selectable_type; - var $ref_id; - - /** - * Constructor - * @access public - * @param string scriptname - * @param int user_id - */ - function __construct($a_target,&$a_gui_obj) - { - global $DIC; - - $this->rbacsystem = $DIC->rbac()->system(); - $this->lng = $DIC->language(); - $tree = $DIC->repositoryTree(); - $ilCtrl = $DIC->ctrl(); - - $this->ctrl = $ilCtrl; - - $this->gui_obj = $a_gui_obj; - - parent::__construct($a_target); - $this->tree = $tree; - $this->root_id = $this->tree->readRootId(); - $this->order_column = "title"; - $this->setSessionExpandVariable("lm_menu_expand"); - $this->addFilter("rolf"); - $this->addFilter("adm"); - } - - function setSelectableTypes($a_types) - { - $this->selectable_types = $a_types; - } - - function setRefId($a_ref_id) - { - $this->ref_id = $a_ref_id; - } - - - function buildLinkTarget($a_node_id, $a_type) - { - if(in_array($a_type,$this->selectable_types)) - { - $this->ctrl->setParameter($this->gui_obj,'link_ref_id',$a_node_id); - if ($_GET["menu_entry"] > 0) - { - return $this->ctrl->getLinkTarget($this->gui_obj,'editMenuEntry'); - } - else - { - return $this->ctrl->getLinkTarget($this->gui_obj,'addMenuEntry'); - } - } - } - - function buildFrameTarget($a_type, $a_child = 0, $a_obj_id = 0) - { - return ''; - } - - function isClickable($a_type, $a_ref_id = 0) - {//return true; - return in_array($a_type,$this->selectable_types) and $a_ref_id != $this->ref_id; - } - - function showChilds($a_ref_id) - { - $rbacsystem = $this->rbacsystem; - - if ($a_ref_id == 0) - { - return true; - } - - if ($rbacsystem->checkAccess("read", $a_ref_id)) - { - return true; - } - else - { - return false; - } - } - - - /** - * overwritten method from base class - * @access public - * @param integer obj_id - * @param integer array options - * @return string - */ - function formatHeader($a_tpl, $a_obj_id,$a_option) - { - $lng = $this->lng; - - $tpl = new ilTemplate("tpl.tree.html", true, true, "Services/UIComponent/Explorer"); - - $tpl->setCurrentBlock("text"); - $tpl->setVariable("OBJ_TITLE", $lng->txt("repository")); - $tpl->parseCurrentBlock(); - $this->output[] = $tpl->get(); - } + /** + * id of root folder + * @var int root folder id + * @access private + */ + public $root_id; + public $output; + public $ctrl; + public $selectable_type; + public $ref_id; + + /** + * Constructor + * @access public + * @param string scriptname + * @param int user_id + */ + public function __construct($a_target, &$a_gui_obj) + { + global $DIC; + + $this->rbacsystem = $DIC->rbac()->system(); + $this->lng = $DIC->language(); + $tree = $DIC->repositoryTree(); + $ilCtrl = $DIC->ctrl(); + + $this->ctrl = $ilCtrl; + + $this->gui_obj = $a_gui_obj; + + parent::__construct($a_target); + $this->tree = $tree; + $this->root_id = $this->tree->readRootId(); + $this->order_column = "title"; + $this->setSessionExpandVariable("lm_menu_expand"); + $this->addFilter("rolf"); + $this->addFilter("adm"); + } + + public function setSelectableTypes($a_types) + { + $this->selectable_types = $a_types; + } + + public function setRefId($a_ref_id) + { + $this->ref_id = $a_ref_id; + } + + + public function buildLinkTarget($a_node_id, $a_type) + { + if (in_array($a_type, $this->selectable_types)) { + $this->ctrl->setParameter($this->gui_obj, 'link_ref_id', $a_node_id); + if ($_GET["menu_entry"] > 0) { + return $this->ctrl->getLinkTarget($this->gui_obj, 'editMenuEntry'); + } else { + return $this->ctrl->getLinkTarget($this->gui_obj, 'addMenuEntry'); + } + } + } + + public function buildFrameTarget($a_type, $a_child = 0, $a_obj_id = 0) + { + return ''; + } + + public function isClickable($a_type, $a_ref_id = 0) + {//return true; + return in_array($a_type, $this->selectable_types) and $a_ref_id != $this->ref_id; + } + + public function showChilds($a_ref_id) + { + $rbacsystem = $this->rbacsystem; + + if ($a_ref_id == 0) { + return true; + } + + if ($rbacsystem->checkAccess("read", $a_ref_id)) { + return true; + } else { + return false; + } + } + + + /** + * overwritten method from base class + * @access public + * @param integer obj_id + * @param integer array options + * @return string + */ + public function formatHeader($a_tpl, $a_obj_id, $a_option) + { + $lng = $this->lng; + + $tpl = new ilTemplate("tpl.tree.html", true, true, "Services/UIComponent/Explorer"); + + $tpl->setCurrentBlock("text"); + $tpl->setVariable("OBJ_TITLE", $lng->txt("repository")); + $tpl->parseCurrentBlock(); + $this->output[] = $tpl->get(); + } } -?> diff --git a/Modules/LearningModule/classes/class.ilLMMultiSrt.php b/Modules/LearningModule/classes/class.ilLMMultiSrt.php index edb655581a9b58e743659fd196b0d71b801b89cb..7c8d146b7523b6c961ea0793576ab26cf4c87d37 100644 --- a/Modules/LearningModule/classes/class.ilLMMultiSrt.php +++ b/Modules/LearningModule/classes/class.ilLMMultiSrt.php @@ -13,46 +13,43 @@ include_once("./Services/MediaObjects/interfaces/interface.ilMobMultiSrtInt.php" */ class ilLMMultiSrt implements ilMobMultiSrtInt { + public function __construct($a_lm) + { + $this->lm = $a_lm; + } - function __construct($a_lm) - { - $this->lm = $a_lm; - } + /** + * Get directory for multi srt upload + * + * @return string diretory + */ + public function getUploadDir() + { + return ilUtil::getDataDir() . "/lm_data" . + "/lm_" . $this->lm->getId() . "/srt_tmp"; + } - /** - * Get directory for multi srt upload - * - * @return string diretory - */ - function getUploadDir() - { - return ilUtil::getDataDir()."/lm_data". - "/lm_".$this->lm->getId()."/srt_tmp"; - } - - /** - * - * - * @param - * @return - */ - function getMobIds() - { - // add mob information to items - // all pages - include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $pages = ilLMPageObject::getPageList($this->lm->getId()); - $mobs = array(); - foreach ($pages as $page) - { - // all media objects - $pg_mobs = ilObjMediaObject::_getMobsOfObject("lm:pg", $page["obj_id"], 0, ""); - foreach ($pg_mobs as $k => $pg_mob) - { - $mobs[$k] = $pg_mob; - } - } - return $mobs; - } -} \ No newline at end of file + /** + * + * + * @param + * @return + */ + public function getMobIds() + { + // add mob information to items + // all pages + include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $pages = ilLMPageObject::getPageList($this->lm->getId()); + $mobs = array(); + foreach ($pages as $page) { + // all media objects + $pg_mobs = ilObjMediaObject::_getMobsOfObject("lm:pg", $page["obj_id"], 0, ""); + foreach ($pg_mobs as $k => $pg_mob) { + $mobs[$k] = $pg_mob; + } + } + return $mobs; + } +} diff --git a/Modules/LearningModule/classes/class.ilLMObjTranslation.php b/Modules/LearningModule/classes/class.ilLMObjTranslation.php index b0f0f8a9ad66a710281423452fc4474566150cb3..44b2bed97fbf5fffdced33c0adca31563758ecfd 100644 --- a/Modules/LearningModule/classes/class.ilLMObjTranslation.php +++ b/Modules/LearningModule/classes/class.ilLMObjTranslation.php @@ -3,7 +3,7 @@ /* Copyright (c) 1998-2012 ILIAS open source, Extended GPL, see docs/LICENSE */ /** - * Translation information on lm object + * Translation information on lm object * * @author Alex Killing * @version $Id$ @@ -11,233 +11,228 @@ */ class ilLMObjTranslation { - /** - * @var ilDB - */ - protected $db; - - protected $lang; - protected $title; - protected $short_title; - protected $create_date; - protected $last_update; - - /** - * Constructor - * - * @param int $a_id object id (page, chapter) - * @param string $a_lang language code - */ - function __construct($a_id = 0, $a_lang = "") - { - global $DIC; - - $this->db = $DIC->database(); - if ($a_id > 0 && $a_lang != "") - { - $this->setId($a_id); - $this->setLang($a_lang); - $this->read(); - } - } - - /** - * Set Id - * - * @param int $a_val id - */ - function setId($a_val) - { - $this->id = $a_val; - } - - /** - * Get Id - * - * @return int id - */ - function getId() - { - return $this->id; - } - - /** - * Set lang - * - * @param string $a_val language - */ - function setLang($a_val) - { - $this->lang = $a_val; - } - - /** - * Get lang - * - * @return string language - */ - function getLang() - { - return $this->lang; - } - - /** - * Set title - * - * @param string $a_val title - */ - function setTitle($a_val) - { - $this->title = $a_val; - } - - /** - * Get title - * - * @return string title - */ - function getTitle() - { - return $this->title; - } - - /** - * Set short title - * - * @param string $a_val short title - */ - function setShortTitle($a_val) - { - $this->short_title = $a_val; - } - - /** - * Get short title - * - * @return string short title - */ - function getShortTitle() - { - return $this->short_title; - } - - /** - * Get create date - * - * @return string create date - */ - function getCreateDate() - { - return $this->create_date; - } - - /** - * Get update date - * - * @return string update date - */ - function getLastUpdate() - { - return $this->last_update; - } - - /** - * Read - */ - function read() - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT * FROM lm_data_transl ". - " WHERE id = ".$ilDB->quote($this->getId(), "integer"). - " AND lang = ".$ilDB->quote($this->getLang(), "text") - ); - $rec = $ilDB->fetchAssoc($set); - $this->setTitle($rec["title"]); - $this->setShortTitle($rec["short_title"]); - $this->create_date = $rec["create_date"]; - $this->last_update = $rec["last_update"]; - } - - /** - * Save (inserts if not existing, otherwise updates) - */ - function save() - { - $ilDB = $this->db; - - if (!self::exists($this->getId(), $this->getLang())) - { - $ilDB->manipulate("INSERT INTO lm_data_transl ". - "(id, lang, title, short_title, create_date, last_update) VALUES (". - $ilDB->quote($this->getId(), "integer").",". - $ilDB->quote($this->getLang(), "text").",". - $ilDB->quote($this->getTitle(), "text").",". - $ilDB->quote($this->getShortTitle(), "text").",". - $ilDB->now().",". - $ilDB->now(). - ")"); - } - else - { - $ilDB->manipulate("UPDATE lm_data_transl SET ". - " title = ".$ilDB->quote($this->getTitle(), "text").",". - " short_title = ".$ilDB->quote($this->getShortTitle(), "text").",". - " last_update = ".$ilDB->now(). - " WHERE id = ".$ilDB->quote($this->getId(), "integer"). - " AND lang = ".$ilDB->quote($this->getLang(), "text") - ); - } - } - - /** - * Check for existence - * - * @param int $a_id object id (page, chapter) - * @param string $a_lang language code - * @return bool true/false - */ - static function exists($a_id, $a_lang) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT * FROM lm_data_transl ". - " WHERE id = ".$ilDB->quote($a_id, "integer"). - " AND lang = ".$ilDB->quote($a_lang, "text") - ); - if($rec = $ilDB->fetchAssoc($set)) - { - return true; - } - return false; - } - - /** - * Copy all translations of an object - * - * @param int $a_source_id source id - * @param int $a_target_id target - */ - static function copy($a_source_id, $a_target_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT * FROM lm_data_transl ". - " WHERE id = ".$ilDB->quote($a_source_id, "integer") - ); - while ($rec = $ilDB->fetchAssoc($set)) - { - $lmobjtrans = new ilLMObjTranslation($a_target_id, $rec["lang"]); - $lmobjtrans->setTitle($rec["title"]); - $lmobjtrans->setShortTitle($rec["short_title"]); - $lmobjtrans->save(); - } - } - + /** + * @var ilDB + */ + protected $db; + + protected $lang; + protected $title; + protected $short_title; + protected $create_date; + protected $last_update; + + /** + * Constructor + * + * @param int $a_id object id (page, chapter) + * @param string $a_lang language code + */ + public function __construct($a_id = 0, $a_lang = "") + { + global $DIC; + + $this->db = $DIC->database(); + if ($a_id > 0 && $a_lang != "") { + $this->setId($a_id); + $this->setLang($a_lang); + $this->read(); + } + } + + /** + * Set Id + * + * @param int $a_val id + */ + public function setId($a_val) + { + $this->id = $a_val; + } + + /** + * Get Id + * + * @return int id + */ + public function getId() + { + return $this->id; + } + + /** + * Set lang + * + * @param string $a_val language + */ + public function setLang($a_val) + { + $this->lang = $a_val; + } + + /** + * Get lang + * + * @return string language + */ + public function getLang() + { + return $this->lang; + } + + /** + * Set title + * + * @param string $a_val title + */ + public function setTitle($a_val) + { + $this->title = $a_val; + } + + /** + * Get title + * + * @return string title + */ + public function getTitle() + { + return $this->title; + } + + /** + * Set short title + * + * @param string $a_val short title + */ + public function setShortTitle($a_val) + { + $this->short_title = $a_val; + } + + /** + * Get short title + * + * @return string short title + */ + public function getShortTitle() + { + return $this->short_title; + } + + /** + * Get create date + * + * @return string create date + */ + public function getCreateDate() + { + return $this->create_date; + } + + /** + * Get update date + * + * @return string update date + */ + public function getLastUpdate() + { + return $this->last_update; + } + + /** + * Read + */ + public function read() + { + $ilDB = $this->db; + + $set = $ilDB->query( + "SELECT * FROM lm_data_transl " . + " WHERE id = " . $ilDB->quote($this->getId(), "integer") . + " AND lang = " . $ilDB->quote($this->getLang(), "text") + ); + $rec = $ilDB->fetchAssoc($set); + $this->setTitle($rec["title"]); + $this->setShortTitle($rec["short_title"]); + $this->create_date = $rec["create_date"]; + $this->last_update = $rec["last_update"]; + } + + /** + * Save (inserts if not existing, otherwise updates) + */ + public function save() + { + $ilDB = $this->db; + + if (!self::exists($this->getId(), $this->getLang())) { + $ilDB->manipulate("INSERT INTO lm_data_transl " . + "(id, lang, title, short_title, create_date, last_update) VALUES (" . + $ilDB->quote($this->getId(), "integer") . "," . + $ilDB->quote($this->getLang(), "text") . "," . + $ilDB->quote($this->getTitle(), "text") . "," . + $ilDB->quote($this->getShortTitle(), "text") . "," . + $ilDB->now() . "," . + $ilDB->now() . + ")"); + } else { + $ilDB->manipulate( + "UPDATE lm_data_transl SET " . + " title = " . $ilDB->quote($this->getTitle(), "text") . "," . + " short_title = " . $ilDB->quote($this->getShortTitle(), "text") . "," . + " last_update = " . $ilDB->now() . + " WHERE id = " . $ilDB->quote($this->getId(), "integer") . + " AND lang = " . $ilDB->quote($this->getLang(), "text") + ); + } + } + + /** + * Check for existence + * + * @param int $a_id object id (page, chapter) + * @param string $a_lang language code + * @return bool true/false + */ + public static function exists($a_id, $a_lang) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT * FROM lm_data_transl " . + " WHERE id = " . $ilDB->quote($a_id, "integer") . + " AND lang = " . $ilDB->quote($a_lang, "text") + ); + if ($rec = $ilDB->fetchAssoc($set)) { + return true; + } + return false; + } + + /** + * Copy all translations of an object + * + * @param int $a_source_id source id + * @param int $a_target_id target + */ + public static function copy($a_source_id, $a_target_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT * FROM lm_data_transl " . + " WHERE id = " . $ilDB->quote($a_source_id, "integer") + ); + while ($rec = $ilDB->fetchAssoc($set)) { + $lmobjtrans = new ilLMObjTranslation($a_target_id, $rec["lang"]); + $lmobjtrans->setTitle($rec["title"]); + $lmobjtrans->setShortTitle($rec["short_title"]); + $lmobjtrans->save(); + } + } } - -?> diff --git a/Modules/LearningModule/classes/class.ilLMObject.php b/Modules/LearningModule/classes/class.ilLMObject.php index 47245a91004f9df2abf6db485517a475134b922e..f9bcbcabc3d99e33d3db9712b1c06a13d47c6657 100755 --- a/Modules/LearningModule/classes/class.ilLMObject.php +++ b/Modules/LearningModule/classes/class.ilLMObject.php @@ -16,1687 +16,1598 @@ require_once("Services/MetaData/classes/class.ilMDLanguageItem.php"); */ class ilLMObject { - /** - * @var ilObjUser - */ - protected $user; - - var $lm_id; - var $type; - var $id; - var $meta_data; - var $data_record; // assoc array of lm_data record - var $content_object; - var $title; - var $short_title; - var $description; - var $active = true; - static protected $data_records = array(); - - /** - * @var ilDB - */ - protected $db; - - /** - * @param object $a_content_obj content object (digi book or learning module) - */ - function __construct($a_content_obj, $a_id = 0) - { - global $DIC; - $this->user = $DIC->user(); - - $this->db = $DIC->database(); - - $this->id = $a_id; - $this->setContentObject($a_content_obj); - $this->setLMId($a_content_obj->getId()); - if($a_id != 0) - { - $this->read(); - } - } - - /** - * Meta data update listener - * - * Important note: Do never call create() or update() - * method of ilObject here. It would result in an - * endless loop: update object -> update meta -> update - * object -> ... - * Use static _writeTitle() ... methods instead. - * - * @param string $a_element md element - * @return boolean success - */ - function MDUpdateListener($a_element) - { - include_once 'Services/MetaData/classes/class.ilMD.php'; - - switch($a_element) - { - case 'General': - - // Update Title and description - $md = new ilMD($this->getLMId(), $this->getId(), $this->getType()); - $md_gen = $md->getGeneral(); - - ilLMObject::_writeTitle($this->getId(),$md_gen->getTitle()); - - foreach($md_gen->getDescriptionIds() as $id) - { - $md_des = $md_gen->getDescription($id); -// ilLMObject::_writeDescription($this->getId(),$md_des->getDescription()); - break; - } - break; - - case 'Educational': - include_once("./Services/Object/classes/class.ilObjectLP.php"); - $obj_lp = ilObjectLP::getInstance($this->getLMId()); - if(in_array($obj_lp->getCurrentMode(), - array(ilLPObjSettings::LP_MODE_TLT, ilLPObjSettings::LP_MODE_COLLECTION_TLT))) - { - include_once("./Services/Tracking/classes/class.ilLPStatusWrapper.php"); - ilLPStatusWrapper::_refreshStatus($this->getLMId()); - } - break; - - default: - } - return true; - } - - - /** - * lookup named identifier (ILIAS_NID) - */ - static function _lookupNID($a_lm_id, $a_lm_obj_id, $a_type) - { - include_once 'Services/MetaData/classes/class.ilMD.php'; -//echo "-".$a_lm_id."-".$a_lm_obj_id."-".$a_type."-"; - $md = new ilMD($a_lm_id, $a_lm_obj_id, $a_type); - $md_gen = $md->getGeneral(); - if (is_object($md_gen)) - { - foreach($md_gen->getIdentifierIds() as $id) - { - $md_id = $md_gen->getIdentifier($id); - if ($md_id->getCatalog() == "ILIAS_NID") - { - return $md_id->getEntry(); - } - } - } - - return false; - } - - - /** - * create meta data entry - */ - function createMetaData() - { - include_once 'Services/MetaData/classes/class.ilMDCreator.php'; - - $ilUser = $this->user; - - $md_creator = new ilMDCreator($this->getLMId(), $this->getId(), $this->getType()); - $md_creator->setTitle($this->getTitle()); - $md_creator->setTitleLanguage($ilUser->getPref('language')); - $md_creator->setDescription($this->getDescription()); - $md_creator->setDescriptionLanguage($ilUser->getPref('language')); - $md_creator->setKeywordLanguage($ilUser->getPref('language')); - $md_creator->setLanguage($ilUser->getPref('language')); - $md_creator->create(); - - return true; - } - - /** - * update meta data entry - */ - function updateMetaData() - { - include_once("Services/MetaData/classes/class.ilMD.php"); - include_once("Services/MetaData/classes/class.ilMDGeneral.php"); - include_once("Services/MetaData/classes/class.ilMDDescription.php"); - - $md = new ilMD($this->getLMId(), $this->getId(), $this->getType()); - $md_gen = $md->getGeneral(); - $md_gen->setTitle($this->getTitle()); - - // sets first description (maybe not appropriate) - $md_des_ids = $md_gen->getDescriptionIds(); - if (count($md_des_ids) > 0) - { - $md_des = $md_gen->getDescription($md_des_ids[0]); -// $md_des->setDescription($this->getDescription()); - $md_des->update(); - } - $md_gen->update(); - - } - - - /** - * delete meta data entry - */ - function deleteMetaData() - { - // Delete meta data - include_once('Services/MetaData/classes/class.ilMD.php'); - $md = new ilMD($this->getLMId(), $this->getId(), $this->getType()); - $md->deleteAll(); - } - - - - /** - * this method should only be called by class ilLMObjectFactory - */ - function setDataRecord($a_record) - { - $this->data_record = $a_record; - } - - function read() - { - $ilDB = $this->db; - - if(!isset($this->data_record)) - { - $query = "SELECT * FROM lm_data WHERE obj_id = ". - $ilDB->quote($this->id, "integer"); - $obj_set = $ilDB->query($query); - $this->data_record = $ilDB->fetchAssoc($obj_set); - } - - $this->type = $this->data_record["type"]; - $this->setImportId($this->data_record["import_id"]); - $this->setTitle($this->data_record["title"]); - $this->setShortTitle($this->data_record["short_title"]); - $this->setLayout($this->data_record["layout"]); - } - - - /** - * Preload data records by lm - * - * @param integer $a_lm_id lm id - * @return int number of preloaded records - */ - static function preloadDataByLM($a_lm_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT * FROM lm_data ". - " WHERE lm_id = ".$ilDB->quote($a_lm_id, "integer") - ); - while ($rec = $ilDB->fetchAssoc($set)) - { - self::$data_records[$rec["obj_id"]] = $rec; - } - return count(self::$data_records); - } - - - /** - * set title of lm object - * - * @param string $a_title title of chapter or page - */ - function setTitle($a_title) - { - $this->title = $a_title; - } - - /** - * get title of lm object - * - * @return string title of chapter or page - */ - function getTitle() - { - return $this->title; - } - - /** - * set short title of lm object - * - * @param string $a_title short title of chapter or page - */ - function setShortTitle($a_title) - { - $this->short_title = $a_title; - } - - /** - * get short title of lm object - * - * @return string short title of chapter or page - */ - function getShortTitle() - { - return $this->short_title; - } - - - /** - * Lookup title - * - * @param int lm object id - */ - protected static function _lookup($a_obj_id, $a_field) - { - global $DIC; - - $ilDB = $DIC->database(); - - if (isset(self::$data_records[$a_obj_id])) - { - return self::$data_records[$a_obj_id][$a_field]; - } - - $query = "SELECT ".$a_field." FROM lm_data WHERE obj_id = ". - $ilDB->quote($a_obj_id, "integer"); - $obj_set = $ilDB->query($query); - $obj_rec = $ilDB->fetchAssoc($obj_set); - - return $obj_rec[$a_field]; - } - - /** - * Lookup title - * - * @param int $a_obj_id object id - * @return string - */ - static function _lookupTitle($a_obj_id) - { - return self::_lookup($a_obj_id, "title"); - } - - /** - * Lookup short title - * - * @param int $a_obj_id object id - * @return string - */ - static function _lookupShortTitle($a_obj_id) - { - return self::_lookup($a_obj_id, "short_title"); - } - - /** - * Lookup type - * - * @param int id of pg st - * @param int id of lm object [optional] - */ - static function _lookupType($a_obj_id, $a_lm_id = 0) - { - global $DIC; - - $ilDB = $DIC->database(); - - if (isset(self::$data_records[$a_obj_id])) - { - if ($a_lm_id == 0 || self::$data_records[$a_obj_id]["lm_id"] == $a_lm_id) - { - return self::$data_records[$a_obj_id]["type"]; - } - } - - if($a_lm_id) - { - $and = ' AND lm_id = '.$ilDB->quote($a_lm_id,'integer'); - } - - $query = "SELECT type FROM lm_data WHERE obj_id = ".$ilDB->quote($a_obj_id, "integer").$and; - $obj_set = $ilDB->query($query); - $obj_rec = $ilDB->fetchAssoc($obj_set); - - return $obj_rec["type"]; - } - - - static function _writeTitle($a_obj_id, $a_title) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "UPDATE lm_data SET ". - " title = ".$ilDB->quote($a_title, "text"). - " WHERE obj_id = ".$ilDB->quote($a_obj_id, "integer"); - $ilDB->manipulate($query); - } - - - function setDescription($a_description) - { - $this->description = $a_description; - } - - function getDescription() - { - return $this->description; - } - - function setType($a_type) - { - $this->type = $a_type; - } - - function getType() - { - return $this->type; - } - - function setLMId($a_lm_id) - { - $this->lm_id = $a_lm_id; - - } - - function getLMId() - { - return $this->lm_id; - } - - function setContentObject(&$a_content_obj) - { - $this->content_object = $a_content_obj; - } - - function &getContentObject() - { - return $this->content_object; - } - - function setId($a_id) - { - $this->id = $a_id; - } - - function getId() - { - return $this->id; - } - - function getImportId() - { - return $this->import_id; - } - - function setImportId($a_id) - { - $this->import_id = $a_id; - } - - /** - * Set layout - * - * @param string layout - */ - function setLayout($a_val) - { - $this->layout = $a_val; - } - - /** - * Get layout - * - * @return string layout - */ - function getLayout() - { - return $this->layout; - } - - /** - * write import id to db (static) - * - * @param int $a_id lm object id - * @param string $a_import_id import id - * @access public - */ - static function _writeImportId($a_id, $a_import_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "UPDATE lm_data ". - "SET ". - "import_id = ".$ilDB->quote($a_import_id, "text").",". - "last_update = ".$ilDB->now()." ". - "WHERE obj_id = ".$ilDB->quote($a_id, "integer"); - - $ilDB->manipulate($q); - } - - function create($a_upload = false) - { - $ilDB = $this->db; - - // insert object data - $this->setId($ilDB->nextId("lm_data")); - $query = "INSERT INTO lm_data (obj_id, title, type, layout, lm_id, import_id, short_title, create_date) ". - "VALUES (". - $ilDB->quote($this->getId(), "integer").",". - $ilDB->quote($this->getTitle(), "text").",". - $ilDB->quote($this->getType(), "text").", ". - $ilDB->quote($this->getLayout(), "text").", ". - $ilDB->quote($this->getLMId(), "integer").",". - $ilDB->quote($this->getImportId(), "text").",". - $ilDB->quote($this->getShortTitle(), "text"). - ", ".$ilDB->now().")"; - $ilDB->manipulate($query); - - // create history entry - include_once("./Services/History/classes/class.ilHistory.php"); - ilHistory::_createEntry($this->getId(), "create", "", - $this->content_object->getType().":".$this->getType()); - - if (!$a_upload) - { - $this->createMetaData(); - } - - } - - /** - * update complete object - */ - function update() - { - $ilDB = $this->db; - - $this->updateMetaData(); - - $query = "UPDATE lm_data SET ". - " lm_id = ".$ilDB->quote($this->getLMId(), "integer"). - " ,title = ".$ilDB->quote($this->getTitle(), "text"). - " ,short_title = ".$ilDB->quote($this->getShortTitle(), "text"). - " ,layout = ".$ilDB->quote($this->getLayout(), "text"). - " WHERE obj_id = ".$ilDB->quote($this->getId(), "integer"); - - $ilDB->manipulate($query); - } - - - /** - * update public access flags in lm_data for all pages of a content object - * @static - * @access public - * @param array page ids - * @param integer content object id - * @return of the jedi - */ - static function _writePublicAccessStatus($a_pages,$a_cont_obj_id) - { - global $DIC; - - $ilDB = $DIC->database(); - $ilLog = $DIC["ilLog"]; - $ilErr = $DIC["ilErr"]; - - if (!is_array($a_pages)) - {$a_pages = array(0); - /*$message = sprintf('ilLMObject::_writePublicAccessStatus(): Invalid parameter! $a_pages must be an array'); - $ilLog->write($message,$ilLog->WARNING); - $ilErr->raiseError($message,$ilErr->MESSAGE); - return false;*/ - } - - if (empty($a_cont_obj_id)) - { - $message = sprintf('ilLMObject::_writePublicAccessStatus(): Invalid parameter! $a_cont_obj_id is empty'); - $ilLog->write($message,$ilLog->WARNING); - $ilErr->raiseError($message,$ilErr->MESSAGE); - return false; - } - - // update structure entries: if at least one page of a chapter is public set chapter to public too - $lm_tree = new ilTree($a_cont_obj_id); - $lm_tree->setTableNames('lm_tree','lm_data'); - $lm_tree->setTreeTablePK("lm_id"); - $lm_tree->readRootId(); - - // get all st entries of cont_obj - $q = "SELECT obj_id FROM lm_data " . - "WHERE lm_id = ".$ilDB->quote($a_cont_obj_id, "integer")." " . - "AND type = 'st'"; - $r = $ilDB->query($q); - - // add chapters with a public page to a_pages - while ($row = $ilDB->fetchAssoc($r)) - { - $childs = $lm_tree->getChilds($row["obj_id"]); - - foreach ($childs as $page) - { - if ($page["type"] == "pg" and in_array($page["obj_id"],$a_pages)) - { - array_push($a_pages, $row["obj_id"]); - break; - } - } - } - - // update public access status of all pages of cont_obj - $q = "UPDATE lm_data SET " . - "public_access = CASE " . - "WHEN ".$ilDB->in("obj_id", $a_pages, false, "integer")." ". - "THEN ".$ilDB->quote("y", "text"). - "ELSE ".$ilDB->quote("n", "text"). - "END " . - "WHERE lm_id = ".$ilDB->quote($a_cont_obj_id, "integer")." " . - "AND ".$ilDB->in("type", array("pg", "st"), false, "text"); - $ilDB->manipulate($q); - - return true; - } - - static function _isPagePublic($a_node_id,$a_check_public_mode = false) - { - global $DIC; - - $ilDB = $DIC->database(); - $ilLog = $DIC["ilLog"]; - - if (empty($a_node_id)) - { - $message = sprintf('ilLMObject::_isPagePublic(): Invalid parameter! $a_node_id is empty'); - $ilLog->write($message,$ilLog->WARNING); - return false; - } - - if ($a_check_public_mode === true) - { - $lm_id = ilLMObject::_lookupContObjId($a_node_id); - - $q = "SELECT public_access_mode FROM content_object WHERE id = ". - $ilDB->quote($lm_id, "integer"); - $r = $ilDB->query($q); - $row = $ilDB->fetchAssoc($r); - - if ($row["public_access_mode"] == "complete") - { - return true; - } - } - - $q = "SELECT public_access FROM lm_data WHERE obj_id=". - $ilDB->quote($a_node_id, "integer"); - $r = $ilDB->query($q); - $row = $ilDB->fetchAssoc($r); - - return ilUtil::yn2tf($row["public_access"]); - } - - /** - * delete lm object data - */ - function delete($a_delete_meta_data = true) - { - $ilDB = $this->db; - - $query = "DELETE FROM lm_data WHERE obj_id = ". - $ilDB->quote($this->getId(), "integer"); - $ilDB->manipulate($query); - - $this->deleteMetaData(); - } - - /** - * get current object id for import id (static) - * - * import ids can exist multiple times (if the same learning module - * has been imported multiple times). we get the object id of - * the last imported object, that is not in trash - * - * @param int $a_import_id import id - * - * @return int id - */ - static function _getIdForImportId($a_import_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "SELECT obj_id FROM lm_data WHERE import_id = ". - $ilDB->quote($a_import_id, "text")." ". - " ORDER BY create_date DESC"; - $obj_set = $ilDB->query($q); - while ($obj_rec = $ilDB->fetchAssoc($obj_set)) - { - $lm_id = ilLMObject::_lookupContObjID($obj_rec["obj_id"]); - - // link only in learning module, that is not trashed - include_once("./Services/Help/classes/class.ilObjHelpSettings.php"); - $ref_ids = ilObject::_getAllReferences($lm_id); // will be 0 if import of lm is in progress (new import) - if (count($ref_ids) == 0 || ilObject::_hasUntrashedReference($lm_id) || - ilObjHelpSettings::isHelpLM($lm_id)) - { - return $obj_rec["obj_id"]; - } - } - - return 0; - } - - /** - * Get all items for an import ID - * - * (only for items notnot in trash) - * - * @param int $a_import_id import id - * - * @return int id - */ - static function _getAllObjectsForImportId($a_import_id, $a_in_lm = 0) - { - global $DIC; - - $ilDB = $DIC->database(); - - $where = ($a_in_lm > 0) - ? " AND lm_id = ".$ilDB->quote($a_in_lm, "integer")." " - : ""; - - $q = "SELECT * FROM lm_data WHERE import_id = ". - $ilDB->quote($a_import_id, "text")." ". - $where. - " ORDER BY create_date DESC"; - $obj_set = $ilDB->query($q); - - $items = array(); - while ($obj_rec = $ilDB->fetchAssoc($obj_set)) - { - // check, whether lm is not trashed - if (ilObject::_hasUntrashedReference($obj_rec["lm_id"])) - { - $items[] = $obj_rec; - } - } - - return $items; - } - - /** - * checks wether a lm content object with specified id exists or not - * - * @param int $id id - * - * @return boolean true, if lm content object exists - */ - static function _exists($a_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - include_once("./Services/Link/classes/class.ilInternalLink.php"); - if (is_int(strpos($a_id, "_"))) - { - $a_id = ilInternalLink::_extractObjIdOfTarget($a_id); - } - - $q = "SELECT * FROM lm_data WHERE obj_id = ". - $ilDB->quote($a_id, "integer"); - $obj_set = $ilDB->query($q); - if ($obj_rec = $ilDB->fetchAssoc($obj_set)) - { - return true; - } - else - { - return false; - } - - } - - /** - * static - */ - static function getObjectList($lm_id, $type = "") - { - global $DIC; - - $ilDB = $DIC->database(); - - $type_str = ($type != "") - ? "AND type = ".$ilDB->quote($type, "text")." " - : ""; - - $query = "SELECT * FROM lm_data ". - "WHERE lm_id= ".$ilDB->quote($lm_id, "integer")." ". - $type_str." ". - "ORDER BY title"; - $obj_set = $ilDB->query($query); - $obj_list = array(); - while($obj_rec = $ilDB->fetchAssoc($obj_set)) - { - $obj_list[] = array("obj_id" => $obj_rec["obj_id"], - "title" => $obj_rec["title"], - "import_id" => $obj_rec["import_id"], - "type" => $obj_rec["type"]); - } - return $obj_list; - } - - - /** - * delete all objects of content object (digi book / learning module) - */ - static function _deleteAllObjectData(&$a_cobj) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT * FROM lm_data ". - "WHERE lm_id= ".$ilDB->quote($a_cobj->getId(), "integer"); - $obj_set = $ilDB->query($query); - - require_once("./Modules/LearningModule/classes/class.ilLMObjectFactory.php"); - while ($obj_rec = $ilDB->fetchAssoc($obj_set)) - { - $lm_obj = ilLMObjectFactory::getInstance($a_cobj, $obj_rec["obj_id"],false); - - if (is_object($lm_obj)) - { - $lm_obj->delete(true); - } - } - - return true; - } - - /** - * get learning module / digibook id for lm object - */ - static function _lookupContObjID($a_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - if (isset(self::$data_records[$a_id])) - { - return self::$data_records[$a_id]["lm_id"]; - } - - $query = "SELECT lm_id FROM lm_data WHERE obj_id = ". - $ilDB->quote($a_id, "integer"); - $obj_set = $ilDB->query($query); - $obj_rec = $ilDB->fetchAssoc($obj_set); - - return $obj_rec["lm_id"]; - } - - /** - * put this object into content object tree - */ - static function putInTree($a_obj, $a_parent_id = "", $a_target_node_id = "") - { - global $DIC; - - $ilLog = $DIC["ilLog"]; - - $tree = new ilTree($a_obj->getContentObject()->getId()); - $tree->setTableNames('lm_tree', 'lm_data'); - $tree->setTreeTablePK("lm_id"); - - // determine parent - $parent_id = ($a_parent_id != "") - ? $a_parent_id - : $tree->getRootId(); - - // determine target - if ($a_target_node_id != "") - { - $target = $a_target_node_id; - } - else - { - // determine last child that serves as predecessor - if ($a_obj->getType() == "st") - { - $s_types = array("st", "pg"); - $childs = $tree->getChildsByTypeFilter($parent_id, $s_types); - } - else - { - $s_types = "pg"; - $childs = $tree->getChildsByType($parent_id, $s_types); - } - - if (count($childs) == 0) - { - $target = IL_FIRST_NODE; - } - else - { - $target = $childs[count($childs) - 1]["obj_id"]; - } - } - - if ($tree->isInTree($parent_id) && !$tree->isInTree($a_obj->getId())) - { - $ilLog->write("LMObject::putInTree: insertNode, ID: ".$a_obj->getId(). - "Parent ID: ".$parent_id.", Target: ".$target); - - $tree->insertNode($a_obj->getId(), $parent_id, $target); - } - } - - /** - * Get learningmodule tree - * - * @param int learning module object id - * - * @return object tree object - */ - static function getTree($a_cont_obj_id) - { - $tree = new ilTree($a_cont_obj_id); - $tree->setTableNames('lm_tree', 'lm_data'); - $tree->setTreeTablePK("lm_id"); - $tree->readRootId(); - - return $tree; - } - - /** - * Copy a set of chapters/pages into the clipboard - */ - static function clipboardCut($a_cont_obj_id, $a_ids) - { - $tree = ilLMObject::getTree($a_cont_obj_id); - - if (!is_array($a_ids)) - { - return false; - } - else - { - // get all "top" ids, i.e. remove ids, that have a selected parent - foreach($a_ids as $id) - { - $path = $tree->getPathId($id); - $take = true; - foreach($path as $path_id) - { - if ($path_id != $id && in_array($path_id, $a_ids)) - { - $take = false; - } - } - if ($take) - { - $cut_ids[] = $id; - } - } - } - - ilLMObject::clipboardCopy($a_cont_obj_id, $cut_ids); - - // remove the objects from the tree - // note: we are getting chapters which are *not* in the tree - // we do not delete any pages/chapters here - foreach ($cut_ids as $id) - { - $curnode = $tree->getNodeData($id); - if ($tree->isInTree($id)) - { - $tree->deleteTree($curnode); - } - } - - } - - /** - * Copy a set of chapters/pages into the clipboard - */ - static function clipboardCopy($a_cont_obj_id, $a_ids) - { - global $DIC; - - $ilUser = $DIC->user(); - - $tree = ilLMObject::getTree($a_cont_obj_id); - - $ilUser->clipboardDeleteObjectsOfType("pg"); - $ilUser->clipboardDeleteObjectsOfType("st"); - - // put them into the clipboard - $time = date("Y-m-d H:i:s", time()); - $order = 0; - foreach ($a_ids as $id) - { - $curnode = array(); - if ($tree->isInTree($id)) - { - $curnode = $tree->getNodeData($id); - $subnodes = $tree->getSubTree($curnode); - foreach($subnodes as $subnode) - { - if ($subnode["child"] != $id) - { - $ilUser->addObjectToClipboard($subnode["child"], - $subnode["type"], $subnode["title"], - $subnode["parent"], $time, $subnode["lft"]); - } - } - } - $order = ($curnode["lft"] > 0) - ? $curnode["lft"] - : (int) ($order + 1); - $ilUser->addObjectToClipboard($id, - ilLMObject::_lookupType($id), ilLMObject::_lookupTitle($id), 0, $time, - $order); - } - } - - /** - * Paste item (tree) from clipboard to current lm - */ - static function pasteTree($a_target_lm, $a_item_id, $a_parent_id, $a_target, $a_insert_time, - &$a_copied_nodes, $a_as_copy = false, $a_source_lm = null) - { - global $DIC; - - $ilUser = $DIC->user(); - $ilLog = $DIC["ilLog"]; - - include_once("./Modules/LearningModule/classes/class.ilStructureObject.php"); - include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); - - $item_lm_id = ilLMObject::_lookupContObjID($a_item_id); - $item_type = ilLMObject::_lookupType($a_item_id); - $lm_obj = ilObjectFactory::getInstanceByObjId($item_lm_id); - if ($item_type == "st") - { - $item = new ilStructureObject($lm_obj, $a_item_id); - } - else if ($item_type == "pg") - { - $item = new ilLMPageObject($lm_obj, $a_item_id); - } - - $ilLog->write("Getting from clipboard type ".$item_type.", ". - "Item ID: ".$a_item_id.", of original LM: ".$item_lm_id); - - if ($item_lm_id != $a_target_lm->getId() && !$a_as_copy) - { - // @todo: check whether st is NOT in tree - - // "move" metadata to new lm - include_once("Services/MetaData/classes/class.ilMD.php"); - $md = new ilMD($item_lm_id, $item->getId(), $item->getType()); - $new_md = $md->cloneMD($a_target_lm->getId(), $item->getId(), $item->getType()); - - // update lm object - $item->setLMId($a_target_lm->getId()); - $item->setContentObject($a_target_lm); - $item->update(); - - // delete old meta data set - $md->deleteAll(); - - if ($item_type == "pg") - { - $page = $item->getPageObject(); - $page->buildDom(); - $page->setParentId($a_target_lm->getId()); - $page->update(); - } - } - - if ($a_as_copy) - { - $target_item = $item->copy($a_target_lm); - $a_copied_nodes[$item->getId()] = $target_item->getId(); - } - else - { - $target_item = $item; - } - - $ilLog->write("Putting into tree type ".$target_item->getType(). - "Item ID: ".$target_item->getId().", Parent: ".$a_parent_id.", ". - "Target: ".$a_target.", Item LM:".$target_item->getContentObject()->getId()); - - ilLMObject::putInTree($target_item, $a_parent_id, $a_target); - - if ($a_source_lm == null) - { - $childs = $ilUser->getClipboardChilds($item->getId(), $a_insert_time); - } - else - { - $childs = $a_source_lm->lm_tree->getChilds($item->getId()); - foreach ($childs as $k => $child) - { - $childs[$k]["id"] = $childs[$k]["child"]; - } - } - - foreach($childs as $child) - { - ilLMObject::pasteTree($a_target_lm, $child["id"], $target_item->getId(), - IL_LAST_NODE, $a_insert_time, $a_copied_nodes, $a_as_copy, $a_source_lm); - } - - return $target_item->getId(); - // @todo: write history (see pastePage) - } - - /** - * Save titles for lm objects - * - * @param array titles (key is ID, value is title) - */ - static function saveTitles($a_lm, $a_titles, $a_lang = "-") - { - include_once("./Modules/LearningModule/classes/class.ilLMObjTranslation.php"); - - if ($a_lang == "") - { - $a_lang = "-"; - } - if (is_array($a_titles)) - { - include_once("./Services/Form/classes/class.ilFormPropertyGUI.php"); - include_once("./Services/MetaData/classes/class.ilMD.php"); - foreach($a_titles as $id => $title) - { - // see #20375 - $title = ilFormPropertyGUI::removeProhibitedCharacters($title); - if ($a_lang == "-") - { - $lmobj = ilLMObjectFactory::getInstance($a_lm, $id, false); - if (is_object($lmobj)) - { - // Update Title and description - $md = new ilMD($a_lm->getId(), $id, $lmobj->getType()); - $md_gen = $md->getGeneral(); - if (is_object($md_gen)) // see bug #0015843 - { - $md_gen->setTitle($title); - $md_gen->update(); - $md->update(); - } - ilLMObject::_writeTitle($id, $title); - } - } - else - { - $lmobjtrans = new ilLMObjTranslation($id, $a_lang); - $lmobjtrans->setTitle($title); - $lmobjtrans->save(); - } - } - } - } - - /** - * Update internal links, after multiple pages have been copied - */ - static function updateInternalLinks($a_copied_nodes, $a_parent_type = "lm") - { - $all_fixes = array(); - foreach($a_copied_nodes as $original_id => $copied_id) - { - $copied_type = ilLMObject::_lookupType($copied_id); - $copy_lm = ilLMObject::_lookupContObjID($copied_id); - - if ($copied_type == "pg") - { - foreach (ilPageObject::lookupTranslations($a_parent_type, $copied_id) as $l) - { - // - // 1. Outgoing links from the copied page. - // - //$targets = ilInternalLink::_getTargetsOfSource($a_parent_type.":pg", $copied_id); - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - $tpg = new ilLMPage($copied_id, 0, $l); - $tpg->buildDom(); - $il = $tpg->getInternalLinks(); - $targets = array(); - foreach ($il as $l) - { - $targets[] = array("type" => ilInternalLink::_extractTypeOfTarget($l["Target"]), - "id" => (int)ilInternalLink::_extractObjIdOfTarget($l["Target"]), - "inst" => (int)ilInternalLink::_extractInstOfTarget($l["Target"])); - } - $fix = array(); - foreach ($targets as $target) - { - if (($target["inst"] == 0 || $target["inst"] = IL_INST_ID) && - ($target["type"] == "pg" || $target["type"] == "st")) - { - // first check, whether target is also within the copied set - if ($a_copied_nodes[$target["id"]] > 0) - { - $fix[$target["id"]] = $a_copied_nodes[$target["id"]]; - } else - { - // now check, if a copy if the target is already in the same lm - - // only if target is not already in the same lm! - $trg_lm = ilLMObject::_lookupContObjID($target["id"]); - if ($trg_lm != $copy_lm) - { - $lm_data = ilLMObject::_getAllObjectsForImportId("il__" . $target["type"] . "_" . $target["id"]); - $found = false; - - foreach ($lm_data as $item) - { - if (!$found && ($item["lm_id"] == $copy_lm)) - { - $fix[$target["id"]] = $item["obj_id"]; - $found = true; - } - } - } - } - } - } - - // outgoing links to be fixed - if (count($fix) > 0) - { - //echo "
--".$copied_id; - //var_dump($fix); - $t = ilObject::_lookupType($copy_lm); - if (is_array($all_fixes[$t . ":" . $copied_id])) - { - $all_fixes[$t . ":" . $copied_id] += $fix; - } else - { - $all_fixes[$t . ":" . $copied_id] = $fix; - } - } - } - } - - if ($copied_type == "pg" || - $copied_type == "st") - { - - // - // 2. Incoming links to the original pages - // - // A->B A2 (A+B currently copied) - // A->C B2 - // B->A - // C->A C2->A (C already copied) - $original_lm = ilLMObject::_lookupContObjID($original_id); - $original_type = ilObject::_lookupType($original_lm); - - if ($original_lm != $copy_lm) - { - - // This gets sources that link to A+B (so we have C here) - // (this also does already the trick when instance map areas are given in C) - // int_link, where target_type, target_id, target_inst -> ok - $sources = ilInternalLink::_getSourcesOfTarget($copied_type, - $original_id, 0); - - // mobs linking to $original_id - // map_area, where link_type, target -> ok - $mobs = ilMapArea::_getMobsForTarget("int", "il__".$copied_type. - "_".$original_id); - - // pages using these mobs - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - foreach($mobs as $mob) - { - // mob_usage, where id -> ok - // mep_item, where foreign_id, type -> ok - // mep_tree, where child -> already existed - // il_news_item, where mob_id -> ok - // map_area, where link_type, target -> aready existed - // media_item, where id -> already existed - // personal_clipboard, where item_id, type -> ok - $usages = ilObjMediaObject::lookupUsages($mob); - foreach($usages as $usage) - { - if ($usage["type"] == "lm:pg" | $usage["type"] == "lm:st") - { - $sources[] = $usage; - } - } - } - $fix = array(); - foreach($sources as $source) - { - $stype = explode(":", $source["type"]); - $source_type = $stype[1]; - - if ($source_type == "pg" || $source_type == "st") - { - // first of all: source must be in original lm - $src_lm = ilLMObject::_lookupContObjID($source["id"]); - - if ($src_lm == $original_lm) - { - // check, if a copy if the source is already in the same lm - // now we look for the latest copy of C in LM2 - $lm_data = ilLMObject::_getAllObjectsForImportId("il__".$source_type."_".$source["id"], - $copy_lm); - $found = false; - foreach ($lm_data as $item) - { - if (!$found) - { - $fix[$item["obj_id"]][$original_id] = $copied_id; - $found = true; - } - } - } - } - } - // outgoing links to be fixed - if (count($fix) > 0) - { - foreach ($fix as $page_id => $fix_array) - { - $t = ilObject::_lookupType($copy_lm); - if (is_array($all_fixes[$t.":".$page_id])) - { - $all_fixes[$t.":".$page_id] += $fix_array; - } - else - { - $all_fixes[$t.":".$page_id] = $fix_array; - } - - } - } - } - } - } - - foreach ($all_fixes as $pg => $fixes) - { - $pg = explode(":", $pg); - include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); - foreach (ilPageObject::lookupTranslations($pg[0], $pg[1]) as $l) - { - $page = ilPageObjectFactory::getInstance($pg[0], $pg[1], 0, $l); - if ($page->moveIntLinks($fixes)) - { - $page->update(true, true); - } - } - } - } - - /** - * Check for unique types (all pages or all chapters) - */ - static function uniqueTypesCheck($a_items) - { - $types = array(); - if (is_array($a_items)) - { - foreach($a_items as $item) - { - $type = ilLMObject::_lookupType($item); - $types[$type] = $type; - } - } - - if (count($types) > 1) - { - return false; - } - return true; - } - - /** - * Write layout setting - * - * @param int lm object id - * @param string layout - */ - static function writeLayout($a_obj_id, $a_layout, $a_lm = null) - { - global $DIC; - - $ilDB = $DIC->database(); - - $t = ilLMObject::_lookupType($a_obj_id); - - if ($t == "pg") - { - $query = "UPDATE lm_data SET ". - " layout = ".$ilDB->quote($a_layout, "text"). - " WHERE obj_id = ".$ilDB->quote($a_obj_id, "integer"); - $ilDB->manipulate($query); - } - else if ($t == "st" && is_object($a_lm)) - { - $node = $a_lm->getLMTree()->getNodeData($a_obj_id); - $child_nodes = $a_lm->getLMTree()->getSubTree($node); - if (is_array($child_nodes) && count($child_nodes) > 0) - { - foreach ($child_nodes as $c) - { - if ($c["type"] == "pg") - { - $query = "UPDATE lm_data SET ". - " layout = ".$ilDB->quote($a_layout, "text"). - " WHERE obj_id = ".$ilDB->quote($c["child"], "integer"); - $ilDB->manipulate($query); - } - } - } - } - } - - /** - * Lookup type - * - * @param int lm object id - */ - static function lookupLayout($a_obj_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT layout FROM lm_data WHERE obj_id = ". - $ilDB->quote($a_obj_id, "integer"); - $obj_set = $ilDB->query($query); - $obj_rec = $ilDB->fetchAssoc($obj_set); - - return $obj_rec["layout"]; - } - - /** - * Get pages of chapter - * - * @param - * @return - */ - static function getPagesOfChapter($a_lm_id, $a_chap_id) - { - // update structure entries: if at least one page of a chapter is public set chapter to public too - $lm_tree = new ilTree($a_lm_id); - $lm_tree->setTableNames('lm_tree','lm_data'); - $lm_tree->setTreeTablePK("lm_id"); - $lm_tree->readRootId(); - - $childs = $lm_tree->getChildsByType($a_chap_id, "pg"); - - return $childs; - } - - /** - * Get all objects of learning module - * - * @param - * @return - */ - static function _getAllLMObjectsOfLM($a_lm_id, $a_type = "") - { - global $DIC; - - $ilDB = $DIC->database(); - - $and = ($a_type != "") - ? " AND type = ".$ilDB->quote($a_type, "text") - : ""; - - $set = $ilDB->query("SELECT obj_id FROM lm_data ". - " WHERE lm_id = ".$ilDB->quote($a_lm_id, "integer").$and); - $obj_ids = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $obj_ids[] = $rec["obj_id"]; - } - - return $obj_ids; - } - - - //// - //// Export ID handling - //// - - /** - * Save export id - * - * @param - * @return - */ - public static function saveExportId($a_lm_id, $a_lmobj_id, $a_exp_id, $a_type = "pg") - { - global $DIC; - - $ilDB = $DIC->database(); - - include_once("Services/MetaData/classes/class.ilMDIdentifier.php"); - - if (trim($a_exp_id) == "") - { - // delete export ids, if existing - $entries = ilMDIdentifier::_getEntriesForObj( - $a_lm_id, $a_lmobj_id, $a_type); - - foreach ($entries as $id => $e) - { - if ($e["catalog"] == "ILIAS_NID") - { - $identifier = new ilMDIdentifier(); - $identifier->setMetaId($id); - $identifier->delete(); - } - } - } - else - { - // update existing entry - $entries = ilMDIdentifier::_getEntriesForObj( - $a_lm_id, $a_lmobj_id, $a_type); - - $updated = false; - foreach ($entries as $id => $e) - { - if ($e["catalog"] == "ILIAS_NID") - { - $identifier = new ilMDIdentifier(); - $identifier->setMetaId($id); - $identifier->read(); - $identifier->setEntry($a_exp_id); - $identifier->update(); - $updated = true; - } - } - - // nothing updated? create a new one - if (!$updated) - { - include_once("./Services/MetaData/classes/class.ilMD.php"); - $md = new ilMD($a_lm_id, $a_lmobj_id, $a_type); - $md_gen = $md->getGeneral(); - $identifier = $md_gen->addIdentifier(); - $identifier->setEntry($a_exp_id); - $identifier->setCatalog("ILIAS_NID"); - $identifier->save(); - } - } - - } - - /** - * Get export ID - * - * @param - * @return - */ - public static function getExportId($a_lm_id, $a_lmobj_id, $a_type = "pg") - { - // look for export id - include_once("./Services/MetaData/classes/class.ilMDIdentifier.php"); - $entries = ilMDIdentifier::_getEntriesForObj( - $a_lm_id, $a_lmobj_id, $a_type); - - foreach ($entries as $e) - { - if ($e["catalog"] == "ILIAS_NID") - { - return $e["entry"]; - } - } - } - - /** - * Does export ID exist in lm? - * - * @param - * @return - */ - function existsExportID($a_lm_id, $a_exp_id, $a_type = "pg") - { - include_once("./Services/MetaData/classes/class.ilMDIdentifier.php"); - return ilMDIdentifier::existsIdInRbacObject($a_lm_id, $a_type, "ILIAS_NID", $a_exp_id); - } - - /** - * Get duplicate export IDs (count export ID usages) - */ - public static function getDuplicateExportIDs($a_lm_id, $a_type = "pg") - { - include_once("./Services/MetaData/classes/class.ilMDIdentifier.php"); - $entries = ilMDIdentifier::_getEntriesForRbacObj($a_lm_id, $a_type); - $res = array(); - foreach ($entries as $e) - { - if ($e["catalog"] == "ILIAS_NID") - { - if (ilLMObject::_exists($e["obj_id"])) - { - $res[trim($e["entry"])]++; - } - } - } - return $res; - } - - /** - * Does export ID exist in lm? - * - * @param - * @return - */ - function getExportIDInfo($a_lm_id, $a_exp_id, $a_type = "pg") - { - include_once("./Services/MetaData/classes/class.ilMDIdentifier.php"); - $data = ilMDIdentifier::readIdData($a_lm_id, $a_type, "ILIAS_NID", $a_exp_id); - return $data; - } - - /** - * Get affective title - * - * @param - * @return - */ - static function _getPresentationTitle($a_node, $a_mode = IL_PAGE_TITLE, - $a_include_numbers = false, $a_time_scheduled_activation = false, - $a_force_content = false, $a_lm_id = 0, $a_lang = "-") - { - if ($a_lang == "") - { - $a_lang = "-"; - } - - if ($a_node["type"] == "st") - { - include_once './Modules/LearningModule/classes/class.ilStructureObject.php'; - return ilStructureObject::_getPresentationTitle($a_node["child"], IL_CHAPTER_TITLE, - $a_include_numbers, $a_time_scheduled_activation, $a_force_content, $a_lm_id, $a_lang); - } - else - { - include_once './Modules/LearningModule/classes/class.ilLMPageObject.php'; - return ilLMPageObject::_getPresentationTitle($a_node["child"], - $a_mode, $a_include_numbers, $a_time_scheduled_activation, - $a_force_content, $a_lm_id, $a_lang); - } - } - - /** - * Get short titles - * - * @param - * @return array - */ - static function getShortTitles($a_lm_id, $a_lang = "-") - { - global $DIC; - - $db = $DIC->database(); - - $title_data = array(); - if ($a_lang == "-") - { - $set = $db->query("SELECT t.child, d.obj_id, d.title, d.short_title FROM lm_data d LEFT JOIN lm_tree t ON (d.obj_id = t.child) WHERE d.lm_id = " . - $db->quote($a_lm_id, "integer") . " ORDER BY t.lft, d.title"); - } - else - { - $set = $db->query("SELECT t.child, d.obj_id, tr.title, tr.short_title, d.title default_title, d.short_title default_short_title FROM lm_data d ". - " LEFT JOIN lm_tree t ON (d.obj_id = t.child) ". - " LEFT JOIN lm_data_transl tr ON (tr.id = d.obj_id AND tr.lang=".$db->quote($a_lang, "text").") WHERE d.lm_id = " . - $db->quote($a_lm_id, "integer") . " ORDER BY t.lft, d.title"); - } - while ($rec = $db->fetchAssoc($set)) - { - $title_data[] = $rec; - } - return $title_data; - } - - /** - * Write short title - * - * @param integer $a_id object id - * @param string $a_short_title short title - */ - static function writeShortTitle($a_id, $a_short_title, $a_lang = "-") - { - global $DIC; - - $db = $DIC->database(); - - if ($a_lang != "-" && $a_lang != "") - { - $trans = new ilLMObjTranslation($a_id, $a_lang); - $trans->setShortTitle($a_short_title); - $trans->save(); - } - else - { - $db->manipulate("UPDATE lm_data SET " . - " short_title = " . $db->quote($a_short_title, "text") . - " WHERE obj_id = " . $db->quote($a_id, "integer") - ); - } - } - - + /** + * @var ilObjUser + */ + protected $user; + + public $lm_id; + public $type; + public $id; + public $meta_data; + public $data_record; // assoc array of lm_data record + public $content_object; + public $title; + public $short_title; + public $description; + public $active = true; + protected static $data_records = array(); + + /** + * @var ilDB + */ + protected $db; + + /** + * @param object $a_content_obj content object (digi book or learning module) + */ + public function __construct($a_content_obj, $a_id = 0) + { + global $DIC; + $this->user = $DIC->user(); + + $this->db = $DIC->database(); + + $this->id = $a_id; + $this->setContentObject($a_content_obj); + $this->setLMId($a_content_obj->getId()); + if ($a_id != 0) { + $this->read(); + } + } + + /** + * Meta data update listener + * + * Important note: Do never call create() or update() + * method of ilObject here. It would result in an + * endless loop: update object -> update meta -> update + * object -> ... + * Use static _writeTitle() ... methods instead. + * + * @param string $a_element md element + * @return boolean success + */ + public function MDUpdateListener($a_element) + { + include_once 'Services/MetaData/classes/class.ilMD.php'; + + switch ($a_element) { + case 'General': + + // Update Title and description + $md = new ilMD($this->getLMId(), $this->getId(), $this->getType()); + $md_gen = $md->getGeneral(); + + ilLMObject::_writeTitle($this->getId(), $md_gen->getTitle()); + + foreach ($md_gen->getDescriptionIds() as $id) { + $md_des = $md_gen->getDescription($id); + // ilLMObject::_writeDescription($this->getId(),$md_des->getDescription()); + break; + } + break; + + case 'Educational': + include_once("./Services/Object/classes/class.ilObjectLP.php"); + $obj_lp = ilObjectLP::getInstance($this->getLMId()); + if (in_array( + $obj_lp->getCurrentMode(), + array(ilLPObjSettings::LP_MODE_TLT, ilLPObjSettings::LP_MODE_COLLECTION_TLT) + )) { + include_once("./Services/Tracking/classes/class.ilLPStatusWrapper.php"); + ilLPStatusWrapper::_refreshStatus($this->getLMId()); + } + break; + + default: + } + return true; + } + + + /** + * lookup named identifier (ILIAS_NID) + */ + public static function _lookupNID($a_lm_id, $a_lm_obj_id, $a_type) + { + include_once 'Services/MetaData/classes/class.ilMD.php'; + //echo "-".$a_lm_id."-".$a_lm_obj_id."-".$a_type."-"; + $md = new ilMD($a_lm_id, $a_lm_obj_id, $a_type); + $md_gen = $md->getGeneral(); + if (is_object($md_gen)) { + foreach ($md_gen->getIdentifierIds() as $id) { + $md_id = $md_gen->getIdentifier($id); + if ($md_id->getCatalog() == "ILIAS_NID") { + return $md_id->getEntry(); + } + } + } + + return false; + } + + + /** + * create meta data entry + */ + public function createMetaData() + { + include_once 'Services/MetaData/classes/class.ilMDCreator.php'; + + $ilUser = $this->user; + + $md_creator = new ilMDCreator($this->getLMId(), $this->getId(), $this->getType()); + $md_creator->setTitle($this->getTitle()); + $md_creator->setTitleLanguage($ilUser->getPref('language')); + $md_creator->setDescription($this->getDescription()); + $md_creator->setDescriptionLanguage($ilUser->getPref('language')); + $md_creator->setKeywordLanguage($ilUser->getPref('language')); + $md_creator->setLanguage($ilUser->getPref('language')); + $md_creator->create(); + + return true; + } + + /** + * update meta data entry + */ + public function updateMetaData() + { + include_once("Services/MetaData/classes/class.ilMD.php"); + include_once("Services/MetaData/classes/class.ilMDGeneral.php"); + include_once("Services/MetaData/classes/class.ilMDDescription.php"); + + $md = new ilMD($this->getLMId(), $this->getId(), $this->getType()); + $md_gen = $md->getGeneral(); + $md_gen->setTitle($this->getTitle()); + + // sets first description (maybe not appropriate) + $md_des_ids = $md_gen->getDescriptionIds(); + if (count($md_des_ids) > 0) { + $md_des = $md_gen->getDescription($md_des_ids[0]); + // $md_des->setDescription($this->getDescription()); + $md_des->update(); + } + $md_gen->update(); + } + + + /** + * delete meta data entry + */ + public function deleteMetaData() + { + // Delete meta data + include_once('Services/MetaData/classes/class.ilMD.php'); + $md = new ilMD($this->getLMId(), $this->getId(), $this->getType()); + $md->deleteAll(); + } + + + + /** + * this method should only be called by class ilLMObjectFactory + */ + public function setDataRecord($a_record) + { + $this->data_record = $a_record; + } + + public function read() + { + $ilDB = $this->db; + + if (!isset($this->data_record)) { + $query = "SELECT * FROM lm_data WHERE obj_id = " . + $ilDB->quote($this->id, "integer"); + $obj_set = $ilDB->query($query); + $this->data_record = $ilDB->fetchAssoc($obj_set); + } + + $this->type = $this->data_record["type"]; + $this->setImportId($this->data_record["import_id"]); + $this->setTitle($this->data_record["title"]); + $this->setShortTitle($this->data_record["short_title"]); + $this->setLayout($this->data_record["layout"]); + } + + + /** + * Preload data records by lm + * + * @param integer $a_lm_id lm id + * @return int number of preloaded records + */ + public static function preloadDataByLM($a_lm_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT * FROM lm_data " . + " WHERE lm_id = " . $ilDB->quote($a_lm_id, "integer") + ); + while ($rec = $ilDB->fetchAssoc($set)) { + self::$data_records[$rec["obj_id"]] = $rec; + } + return count(self::$data_records); + } + + + /** + * set title of lm object + * + * @param string $a_title title of chapter or page + */ + public function setTitle($a_title) + { + $this->title = $a_title; + } + + /** + * get title of lm object + * + * @return string title of chapter or page + */ + public function getTitle() + { + return $this->title; + } + + /** + * set short title of lm object + * + * @param string $a_title short title of chapter or page + */ + public function setShortTitle($a_title) + { + $this->short_title = $a_title; + } + + /** + * get short title of lm object + * + * @return string short title of chapter or page + */ + public function getShortTitle() + { + return $this->short_title; + } + + + /** + * Lookup title + * + * @param int lm object id + */ + protected static function _lookup($a_obj_id, $a_field) + { + global $DIC; + + $ilDB = $DIC->database(); + + if (isset(self::$data_records[$a_obj_id])) { + return self::$data_records[$a_obj_id][$a_field]; + } + + $query = "SELECT " . $a_field . " FROM lm_data WHERE obj_id = " . + $ilDB->quote($a_obj_id, "integer"); + $obj_set = $ilDB->query($query); + $obj_rec = $ilDB->fetchAssoc($obj_set); + + return $obj_rec[$a_field]; + } + + /** + * Lookup title + * + * @param int $a_obj_id object id + * @return string + */ + public static function _lookupTitle($a_obj_id) + { + return self::_lookup($a_obj_id, "title"); + } + + /** + * Lookup short title + * + * @param int $a_obj_id object id + * @return string + */ + public static function _lookupShortTitle($a_obj_id) + { + return self::_lookup($a_obj_id, "short_title"); + } + + /** + * Lookup type + * + * @param int id of pg st + * @param int id of lm object [optional] + */ + public static function _lookupType($a_obj_id, $a_lm_id = 0) + { + global $DIC; + + $ilDB = $DIC->database(); + + if (isset(self::$data_records[$a_obj_id])) { + if ($a_lm_id == 0 || self::$data_records[$a_obj_id]["lm_id"] == $a_lm_id) { + return self::$data_records[$a_obj_id]["type"]; + } + } + + if ($a_lm_id) { + $and = ' AND lm_id = ' . $ilDB->quote($a_lm_id, 'integer'); + } + + $query = "SELECT type FROM lm_data WHERE obj_id = " . $ilDB->quote($a_obj_id, "integer") . $and; + $obj_set = $ilDB->query($query); + $obj_rec = $ilDB->fetchAssoc($obj_set); + + return $obj_rec["type"]; + } + + + public static function _writeTitle($a_obj_id, $a_title) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "UPDATE lm_data SET " . + " title = " . $ilDB->quote($a_title, "text") . + " WHERE obj_id = " . $ilDB->quote($a_obj_id, "integer"); + $ilDB->manipulate($query); + } + + + public function setDescription($a_description) + { + $this->description = $a_description; + } + + public function getDescription() + { + return $this->description; + } + + public function setType($a_type) + { + $this->type = $a_type; + } + + public function getType() + { + return $this->type; + } + + public function setLMId($a_lm_id) + { + $this->lm_id = $a_lm_id; + } + + public function getLMId() + { + return $this->lm_id; + } + + public function setContentObject(&$a_content_obj) + { + $this->content_object = $a_content_obj; + } + + public function &getContentObject() + { + return $this->content_object; + } + + public function setId($a_id) + { + $this->id = $a_id; + } + + public function getId() + { + return $this->id; + } + + public function getImportId() + { + return $this->import_id; + } + + public function setImportId($a_id) + { + $this->import_id = $a_id; + } + + /** + * Set layout + * + * @param string layout + */ + public function setLayout($a_val) + { + $this->layout = $a_val; + } + + /** + * Get layout + * + * @return string layout + */ + public function getLayout() + { + return $this->layout; + } + + /** + * write import id to db (static) + * + * @param int $a_id lm object id + * @param string $a_import_id import id + * @access public + */ + public static function _writeImportId($a_id, $a_import_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "UPDATE lm_data " . + "SET " . + "import_id = " . $ilDB->quote($a_import_id, "text") . "," . + "last_update = " . $ilDB->now() . " " . + "WHERE obj_id = " . $ilDB->quote($a_id, "integer"); + + $ilDB->manipulate($q); + } + + public function create($a_upload = false) + { + $ilDB = $this->db; + + // insert object data + $this->setId($ilDB->nextId("lm_data")); + $query = "INSERT INTO lm_data (obj_id, title, type, layout, lm_id, import_id, short_title, create_date) " . + "VALUES (" . + $ilDB->quote($this->getId(), "integer") . "," . + $ilDB->quote($this->getTitle(), "text") . "," . + $ilDB->quote($this->getType(), "text") . ", " . + $ilDB->quote($this->getLayout(), "text") . ", " . + $ilDB->quote($this->getLMId(), "integer") . "," . + $ilDB->quote($this->getImportId(), "text") . "," . + $ilDB->quote($this->getShortTitle(), "text") . + ", " . $ilDB->now() . ")"; + $ilDB->manipulate($query); + + // create history entry + include_once("./Services/History/classes/class.ilHistory.php"); + ilHistory::_createEntry( + $this->getId(), + "create", + "", + $this->content_object->getType() . ":" . $this->getType() + ); + + if (!$a_upload) { + $this->createMetaData(); + } + } + + /** + * update complete object + */ + public function update() + { + $ilDB = $this->db; + + $this->updateMetaData(); + + $query = "UPDATE lm_data SET " . + " lm_id = " . $ilDB->quote($this->getLMId(), "integer") . + " ,title = " . $ilDB->quote($this->getTitle(), "text") . + " ,short_title = " . $ilDB->quote($this->getShortTitle(), "text") . + " ,layout = " . $ilDB->quote($this->getLayout(), "text") . + " WHERE obj_id = " . $ilDB->quote($this->getId(), "integer"); + + $ilDB->manipulate($query); + } + + + /** + * update public access flags in lm_data for all pages of a content object + * @static + * @access public + * @param array page ids + * @param integer content object id + * @return of the jedi + */ + public static function _writePublicAccessStatus($a_pages, $a_cont_obj_id) + { + global $DIC; + + $ilDB = $DIC->database(); + $ilLog = $DIC["ilLog"]; + $ilErr = $DIC["ilErr"]; + + if (!is_array($a_pages)) { + $a_pages = array(0); + /*$message = sprintf('ilLMObject::_writePublicAccessStatus(): Invalid parameter! $a_pages must be an array'); + $ilLog->write($message,$ilLog->WARNING); + $ilErr->raiseError($message,$ilErr->MESSAGE); + return false;*/ + } + + if (empty($a_cont_obj_id)) { + $message = sprintf('ilLMObject::_writePublicAccessStatus(): Invalid parameter! $a_cont_obj_id is empty'); + $ilLog->write($message, $ilLog->WARNING); + $ilErr->raiseError($message, $ilErr->MESSAGE); + return false; + } + + // update structure entries: if at least one page of a chapter is public set chapter to public too + $lm_tree = new ilTree($a_cont_obj_id); + $lm_tree->setTableNames('lm_tree', 'lm_data'); + $lm_tree->setTreeTablePK("lm_id"); + $lm_tree->readRootId(); + + // get all st entries of cont_obj + $q = "SELECT obj_id FROM lm_data " . + "WHERE lm_id = " . $ilDB->quote($a_cont_obj_id, "integer") . " " . + "AND type = 'st'"; + $r = $ilDB->query($q); + + // add chapters with a public page to a_pages + while ($row = $ilDB->fetchAssoc($r)) { + $childs = $lm_tree->getChilds($row["obj_id"]); + + foreach ($childs as $page) { + if ($page["type"] == "pg" and in_array($page["obj_id"], $a_pages)) { + array_push($a_pages, $row["obj_id"]); + break; + } + } + } + + // update public access status of all pages of cont_obj + $q = "UPDATE lm_data SET " . + "public_access = CASE " . + "WHEN " . $ilDB->in("obj_id", $a_pages, false, "integer") . " " . + "THEN " . $ilDB->quote("y", "text") . + "ELSE " . $ilDB->quote("n", "text") . + "END " . + "WHERE lm_id = " . $ilDB->quote($a_cont_obj_id, "integer") . " " . + "AND " . $ilDB->in("type", array("pg", "st"), false, "text"); + $ilDB->manipulate($q); + + return true; + } + + public static function _isPagePublic($a_node_id, $a_check_public_mode = false) + { + global $DIC; + + $ilDB = $DIC->database(); + $ilLog = $DIC["ilLog"]; + + if (empty($a_node_id)) { + $message = sprintf('ilLMObject::_isPagePublic(): Invalid parameter! $a_node_id is empty'); + $ilLog->write($message, $ilLog->WARNING); + return false; + } + + if ($a_check_public_mode === true) { + $lm_id = ilLMObject::_lookupContObjId($a_node_id); + + $q = "SELECT public_access_mode FROM content_object WHERE id = " . + $ilDB->quote($lm_id, "integer"); + $r = $ilDB->query($q); + $row = $ilDB->fetchAssoc($r); + + if ($row["public_access_mode"] == "complete") { + return true; + } + } + + $q = "SELECT public_access FROM lm_data WHERE obj_id=" . + $ilDB->quote($a_node_id, "integer"); + $r = $ilDB->query($q); + $row = $ilDB->fetchAssoc($r); + + return ilUtil::yn2tf($row["public_access"]); + } + + /** + * delete lm object data + */ + public function delete($a_delete_meta_data = true) + { + $ilDB = $this->db; + + $query = "DELETE FROM lm_data WHERE obj_id = " . + $ilDB->quote($this->getId(), "integer"); + $ilDB->manipulate($query); + + $this->deleteMetaData(); + } + + /** + * get current object id for import id (static) + * + * import ids can exist multiple times (if the same learning module + * has been imported multiple times). we get the object id of + * the last imported object, that is not in trash + * + * @param int $a_import_id import id + * + * @return int id + */ + public static function _getIdForImportId($a_import_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "SELECT obj_id FROM lm_data WHERE import_id = " . + $ilDB->quote($a_import_id, "text") . " " . + " ORDER BY create_date DESC"; + $obj_set = $ilDB->query($q); + while ($obj_rec = $ilDB->fetchAssoc($obj_set)) { + $lm_id = ilLMObject::_lookupContObjID($obj_rec["obj_id"]); + + // link only in learning module, that is not trashed + include_once("./Services/Help/classes/class.ilObjHelpSettings.php"); + $ref_ids = ilObject::_getAllReferences($lm_id); // will be 0 if import of lm is in progress (new import) + if (count($ref_ids) == 0 || ilObject::_hasUntrashedReference($lm_id) || + ilObjHelpSettings::isHelpLM($lm_id)) { + return $obj_rec["obj_id"]; + } + } + + return 0; + } + + /** + * Get all items for an import ID + * + * (only for items notnot in trash) + * + * @param int $a_import_id import id + * + * @return int id + */ + public static function _getAllObjectsForImportId($a_import_id, $a_in_lm = 0) + { + global $DIC; + + $ilDB = $DIC->database(); + + $where = ($a_in_lm > 0) + ? " AND lm_id = " . $ilDB->quote($a_in_lm, "integer") . " " + : ""; + + $q = "SELECT * FROM lm_data WHERE import_id = " . + $ilDB->quote($a_import_id, "text") . " " . + $where . + " ORDER BY create_date DESC"; + $obj_set = $ilDB->query($q); + + $items = array(); + while ($obj_rec = $ilDB->fetchAssoc($obj_set)) { + // check, whether lm is not trashed + if (ilObject::_hasUntrashedReference($obj_rec["lm_id"])) { + $items[] = $obj_rec; + } + } + + return $items; + } + + /** + * checks wether a lm content object with specified id exists or not + * + * @param int $id id + * + * @return boolean true, if lm content object exists + */ + public static function _exists($a_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + include_once("./Services/Link/classes/class.ilInternalLink.php"); + if (is_int(strpos($a_id, "_"))) { + $a_id = ilInternalLink::_extractObjIdOfTarget($a_id); + } + + $q = "SELECT * FROM lm_data WHERE obj_id = " . + $ilDB->quote($a_id, "integer"); + $obj_set = $ilDB->query($q); + if ($obj_rec = $ilDB->fetchAssoc($obj_set)) { + return true; + } else { + return false; + } + } + + /** + * static + */ + public static function getObjectList($lm_id, $type = "") + { + global $DIC; + + $ilDB = $DIC->database(); + + $type_str = ($type != "") + ? "AND type = " . $ilDB->quote($type, "text") . " " + : ""; + + $query = "SELECT * FROM lm_data " . + "WHERE lm_id= " . $ilDB->quote($lm_id, "integer") . " " . + $type_str . " " . + "ORDER BY title"; + $obj_set = $ilDB->query($query); + $obj_list = array(); + while ($obj_rec = $ilDB->fetchAssoc($obj_set)) { + $obj_list[] = array("obj_id" => $obj_rec["obj_id"], + "title" => $obj_rec["title"], + "import_id" => $obj_rec["import_id"], + "type" => $obj_rec["type"]); + } + return $obj_list; + } + + + /** + * delete all objects of content object (digi book / learning module) + */ + public static function _deleteAllObjectData(&$a_cobj) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT * FROM lm_data " . + "WHERE lm_id= " . $ilDB->quote($a_cobj->getId(), "integer"); + $obj_set = $ilDB->query($query); + + require_once("./Modules/LearningModule/classes/class.ilLMObjectFactory.php"); + while ($obj_rec = $ilDB->fetchAssoc($obj_set)) { + $lm_obj = ilLMObjectFactory::getInstance($a_cobj, $obj_rec["obj_id"], false); + + if (is_object($lm_obj)) { + $lm_obj->delete(true); + } + } + + return true; + } + + /** + * get learning module / digibook id for lm object + */ + public static function _lookupContObjID($a_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + if (isset(self::$data_records[$a_id])) { + return self::$data_records[$a_id]["lm_id"]; + } + + $query = "SELECT lm_id FROM lm_data WHERE obj_id = " . + $ilDB->quote($a_id, "integer"); + $obj_set = $ilDB->query($query); + $obj_rec = $ilDB->fetchAssoc($obj_set); + + return $obj_rec["lm_id"]; + } + + /** + * put this object into content object tree + */ + public static function putInTree($a_obj, $a_parent_id = "", $a_target_node_id = "") + { + global $DIC; + + $ilLog = $DIC["ilLog"]; + + $tree = new ilTree($a_obj->getContentObject()->getId()); + $tree->setTableNames('lm_tree', 'lm_data'); + $tree->setTreeTablePK("lm_id"); + + // determine parent + $parent_id = ($a_parent_id != "") + ? $a_parent_id + : $tree->getRootId(); + + // determine target + if ($a_target_node_id != "") { + $target = $a_target_node_id; + } else { + // determine last child that serves as predecessor + if ($a_obj->getType() == "st") { + $s_types = array("st", "pg"); + $childs = $tree->getChildsByTypeFilter($parent_id, $s_types); + } else { + $s_types = "pg"; + $childs = $tree->getChildsByType($parent_id, $s_types); + } + + if (count($childs) == 0) { + $target = IL_FIRST_NODE; + } else { + $target = $childs[count($childs) - 1]["obj_id"]; + } + } + + if ($tree->isInTree($parent_id) && !$tree->isInTree($a_obj->getId())) { + $ilLog->write("LMObject::putInTree: insertNode, ID: " . $a_obj->getId() . + "Parent ID: " . $parent_id . ", Target: " . $target); + + $tree->insertNode($a_obj->getId(), $parent_id, $target); + } + } + + /** + * Get learningmodule tree + * + * @param int learning module object id + * + * @return object tree object + */ + public static function getTree($a_cont_obj_id) + { + $tree = new ilTree($a_cont_obj_id); + $tree->setTableNames('lm_tree', 'lm_data'); + $tree->setTreeTablePK("lm_id"); + $tree->readRootId(); + + return $tree; + } + + /** + * Copy a set of chapters/pages into the clipboard + */ + public static function clipboardCut($a_cont_obj_id, $a_ids) + { + $tree = ilLMObject::getTree($a_cont_obj_id); + + if (!is_array($a_ids)) { + return false; + } else { + // get all "top" ids, i.e. remove ids, that have a selected parent + foreach ($a_ids as $id) { + $path = $tree->getPathId($id); + $take = true; + foreach ($path as $path_id) { + if ($path_id != $id && in_array($path_id, $a_ids)) { + $take = false; + } + } + if ($take) { + $cut_ids[] = $id; + } + } + } + + ilLMObject::clipboardCopy($a_cont_obj_id, $cut_ids); + + // remove the objects from the tree + // note: we are getting chapters which are *not* in the tree + // we do not delete any pages/chapters here + foreach ($cut_ids as $id) { + $curnode = $tree->getNodeData($id); + if ($tree->isInTree($id)) { + $tree->deleteTree($curnode); + } + } + } + + /** + * Copy a set of chapters/pages into the clipboard + */ + public static function clipboardCopy($a_cont_obj_id, $a_ids) + { + global $DIC; + + $ilUser = $DIC->user(); + + $tree = ilLMObject::getTree($a_cont_obj_id); + + $ilUser->clipboardDeleteObjectsOfType("pg"); + $ilUser->clipboardDeleteObjectsOfType("st"); + + // put them into the clipboard + $time = date("Y-m-d H:i:s", time()); + $order = 0; + foreach ($a_ids as $id) { + $curnode = array(); + if ($tree->isInTree($id)) { + $curnode = $tree->getNodeData($id); + $subnodes = $tree->getSubTree($curnode); + foreach ($subnodes as $subnode) { + if ($subnode["child"] != $id) { + $ilUser->addObjectToClipboard( + $subnode["child"], + $subnode["type"], + $subnode["title"], + $subnode["parent"], + $time, + $subnode["lft"] + ); + } + } + } + $order = ($curnode["lft"] > 0) + ? $curnode["lft"] + : (int) ($order + 1); + $ilUser->addObjectToClipboard( + $id, + ilLMObject::_lookupType($id), + ilLMObject::_lookupTitle($id), + 0, + $time, + $order + ); + } + } + + /** + * Paste item (tree) from clipboard to current lm + */ + public static function pasteTree( + $a_target_lm, + $a_item_id, + $a_parent_id, + $a_target, + $a_insert_time, + &$a_copied_nodes, + $a_as_copy = false, + $a_source_lm = null + ) { + global $DIC; + + $ilUser = $DIC->user(); + $ilLog = $DIC["ilLog"]; + + include_once("./Modules/LearningModule/classes/class.ilStructureObject.php"); + include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); + + $item_lm_id = ilLMObject::_lookupContObjID($a_item_id); + $item_type = ilLMObject::_lookupType($a_item_id); + $lm_obj = ilObjectFactory::getInstanceByObjId($item_lm_id); + if ($item_type == "st") { + $item = new ilStructureObject($lm_obj, $a_item_id); + } elseif ($item_type == "pg") { + $item = new ilLMPageObject($lm_obj, $a_item_id); + } + + $ilLog->write("Getting from clipboard type " . $item_type . ", " . + "Item ID: " . $a_item_id . ", of original LM: " . $item_lm_id); + + if ($item_lm_id != $a_target_lm->getId() && !$a_as_copy) { + // @todo: check whether st is NOT in tree + + // "move" metadata to new lm + include_once("Services/MetaData/classes/class.ilMD.php"); + $md = new ilMD($item_lm_id, $item->getId(), $item->getType()); + $new_md = $md->cloneMD($a_target_lm->getId(), $item->getId(), $item->getType()); + + // update lm object + $item->setLMId($a_target_lm->getId()); + $item->setContentObject($a_target_lm); + $item->update(); + + // delete old meta data set + $md->deleteAll(); + + if ($item_type == "pg") { + $page = $item->getPageObject(); + $page->buildDom(); + $page->setParentId($a_target_lm->getId()); + $page->update(); + } + } + + if ($a_as_copy) { + $target_item = $item->copy($a_target_lm); + $a_copied_nodes[$item->getId()] = $target_item->getId(); + } else { + $target_item = $item; + } + + $ilLog->write("Putting into tree type " . $target_item->getType() . + "Item ID: " . $target_item->getId() . ", Parent: " . $a_parent_id . ", " . + "Target: " . $a_target . ", Item LM:" . $target_item->getContentObject()->getId()); + + ilLMObject::putInTree($target_item, $a_parent_id, $a_target); + + if ($a_source_lm == null) { + $childs = $ilUser->getClipboardChilds($item->getId(), $a_insert_time); + } else { + $childs = $a_source_lm->lm_tree->getChilds($item->getId()); + foreach ($childs as $k => $child) { + $childs[$k]["id"] = $childs[$k]["child"]; + } + } + + foreach ($childs as $child) { + ilLMObject::pasteTree( + $a_target_lm, + $child["id"], + $target_item->getId(), + IL_LAST_NODE, + $a_insert_time, + $a_copied_nodes, + $a_as_copy, + $a_source_lm + ); + } + + return $target_item->getId(); + // @todo: write history (see pastePage) + } + + /** + * Save titles for lm objects + * + * @param array titles (key is ID, value is title) + */ + public static function saveTitles($a_lm, $a_titles, $a_lang = "-") + { + include_once("./Modules/LearningModule/classes/class.ilLMObjTranslation.php"); + + if ($a_lang == "") { + $a_lang = "-"; + } + if (is_array($a_titles)) { + include_once("./Services/Form/classes/class.ilFormPropertyGUI.php"); + include_once("./Services/MetaData/classes/class.ilMD.php"); + foreach ($a_titles as $id => $title) { + // see #20375 + $title = ilFormPropertyGUI::removeProhibitedCharacters($title); + if ($a_lang == "-") { + $lmobj = ilLMObjectFactory::getInstance($a_lm, $id, false); + if (is_object($lmobj)) { + // Update Title and description + $md = new ilMD($a_lm->getId(), $id, $lmobj->getType()); + $md_gen = $md->getGeneral(); + if (is_object($md_gen)) { // see bug #0015843 + $md_gen->setTitle($title); + $md_gen->update(); + $md->update(); + } + ilLMObject::_writeTitle($id, $title); + } + } else { + $lmobjtrans = new ilLMObjTranslation($id, $a_lang); + $lmobjtrans->setTitle($title); + $lmobjtrans->save(); + } + } + } + } + + /** + * Update internal links, after multiple pages have been copied + */ + public static function updateInternalLinks($a_copied_nodes, $a_parent_type = "lm") + { + $all_fixes = array(); + foreach ($a_copied_nodes as $original_id => $copied_id) { + $copied_type = ilLMObject::_lookupType($copied_id); + $copy_lm = ilLMObject::_lookupContObjID($copied_id); + + if ($copied_type == "pg") { + foreach (ilPageObject::lookupTranslations($a_parent_type, $copied_id) as $l) { + // + // 1. Outgoing links from the copied page. + // + //$targets = ilInternalLink::_getTargetsOfSource($a_parent_type.":pg", $copied_id); + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + $tpg = new ilLMPage($copied_id, 0, $l); + $tpg->buildDom(); + $il = $tpg->getInternalLinks(); + $targets = array(); + foreach ($il as $l) { + $targets[] = array("type" => ilInternalLink::_extractTypeOfTarget($l["Target"]), + "id" => (int) ilInternalLink::_extractObjIdOfTarget($l["Target"]), + "inst" => (int) ilInternalLink::_extractInstOfTarget($l["Target"])); + } + $fix = array(); + foreach ($targets as $target) { + if (($target["inst"] == 0 || $target["inst"] = IL_INST_ID) && + ($target["type"] == "pg" || $target["type"] == "st")) { + // first check, whether target is also within the copied set + if ($a_copied_nodes[$target["id"]] > 0) { + $fix[$target["id"]] = $a_copied_nodes[$target["id"]]; + } else { + // now check, if a copy if the target is already in the same lm + + // only if target is not already in the same lm! + $trg_lm = ilLMObject::_lookupContObjID($target["id"]); + if ($trg_lm != $copy_lm) { + $lm_data = ilLMObject::_getAllObjectsForImportId("il__" . $target["type"] . "_" . $target["id"]); + $found = false; + + foreach ($lm_data as $item) { + if (!$found && ($item["lm_id"] == $copy_lm)) { + $fix[$target["id"]] = $item["obj_id"]; + $found = true; + } + } + } + } + } + } + + // outgoing links to be fixed + if (count($fix) > 0) { + //echo "
--".$copied_id; + //var_dump($fix); + $t = ilObject::_lookupType($copy_lm); + if (is_array($all_fixes[$t . ":" . $copied_id])) { + $all_fixes[$t . ":" . $copied_id] += $fix; + } else { + $all_fixes[$t . ":" . $copied_id] = $fix; + } + } + } + } + + if ($copied_type == "pg" || + $copied_type == "st") { + + // + // 2. Incoming links to the original pages + // + // A->B A2 (A+B currently copied) + // A->C B2 + // B->A + // C->A C2->A (C already copied) + $original_lm = ilLMObject::_lookupContObjID($original_id); + $original_type = ilObject::_lookupType($original_lm); + + if ($original_lm != $copy_lm) { + + // This gets sources that link to A+B (so we have C here) + // (this also does already the trick when instance map areas are given in C) + // int_link, where target_type, target_id, target_inst -> ok + $sources = ilInternalLink::_getSourcesOfTarget( + $copied_type, + $original_id, + 0 + ); + + // mobs linking to $original_id + // map_area, where link_type, target -> ok + $mobs = ilMapArea::_getMobsForTarget("int", "il__" . $copied_type . + "_" . $original_id); + + // pages using these mobs + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + foreach ($mobs as $mob) { + // mob_usage, where id -> ok + // mep_item, where foreign_id, type -> ok + // mep_tree, where child -> already existed + // il_news_item, where mob_id -> ok + // map_area, where link_type, target -> aready existed + // media_item, where id -> already existed + // personal_clipboard, where item_id, type -> ok + $usages = ilObjMediaObject::lookupUsages($mob); + foreach ($usages as $usage) { + if ($usage["type"] == "lm:pg" | $usage["type"] == "lm:st") { + $sources[] = $usage; + } + } + } + $fix = array(); + foreach ($sources as $source) { + $stype = explode(":", $source["type"]); + $source_type = $stype[1]; + + if ($source_type == "pg" || $source_type == "st") { + // first of all: source must be in original lm + $src_lm = ilLMObject::_lookupContObjID($source["id"]); + + if ($src_lm == $original_lm) { + // check, if a copy if the source is already in the same lm + // now we look for the latest copy of C in LM2 + $lm_data = ilLMObject::_getAllObjectsForImportId( + "il__" . $source_type . "_" . $source["id"], + $copy_lm + ); + $found = false; + foreach ($lm_data as $item) { + if (!$found) { + $fix[$item["obj_id"]][$original_id] = $copied_id; + $found = true; + } + } + } + } + } + // outgoing links to be fixed + if (count($fix) > 0) { + foreach ($fix as $page_id => $fix_array) { + $t = ilObject::_lookupType($copy_lm); + if (is_array($all_fixes[$t . ":" . $page_id])) { + $all_fixes[$t . ":" . $page_id] += $fix_array; + } else { + $all_fixes[$t . ":" . $page_id] = $fix_array; + } + } + } + } + } + } + + foreach ($all_fixes as $pg => $fixes) { + $pg = explode(":", $pg); + include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); + foreach (ilPageObject::lookupTranslations($pg[0], $pg[1]) as $l) { + $page = ilPageObjectFactory::getInstance($pg[0], $pg[1], 0, $l); + if ($page->moveIntLinks($fixes)) { + $page->update(true, true); + } + } + } + } + + /** + * Check for unique types (all pages or all chapters) + */ + public static function uniqueTypesCheck($a_items) + { + $types = array(); + if (is_array($a_items)) { + foreach ($a_items as $item) { + $type = ilLMObject::_lookupType($item); + $types[$type] = $type; + } + } + + if (count($types) > 1) { + return false; + } + return true; + } + + /** + * Write layout setting + * + * @param int lm object id + * @param string layout + */ + public static function writeLayout($a_obj_id, $a_layout, $a_lm = null) + { + global $DIC; + + $ilDB = $DIC->database(); + + $t = ilLMObject::_lookupType($a_obj_id); + + if ($t == "pg") { + $query = "UPDATE lm_data SET " . + " layout = " . $ilDB->quote($a_layout, "text") . + " WHERE obj_id = " . $ilDB->quote($a_obj_id, "integer"); + $ilDB->manipulate($query); + } elseif ($t == "st" && is_object($a_lm)) { + $node = $a_lm->getLMTree()->getNodeData($a_obj_id); + $child_nodes = $a_lm->getLMTree()->getSubTree($node); + if (is_array($child_nodes) && count($child_nodes) > 0) { + foreach ($child_nodes as $c) { + if ($c["type"] == "pg") { + $query = "UPDATE lm_data SET " . + " layout = " . $ilDB->quote($a_layout, "text") . + " WHERE obj_id = " . $ilDB->quote($c["child"], "integer"); + $ilDB->manipulate($query); + } + } + } + } + } + + /** + * Lookup type + * + * @param int lm object id + */ + public static function lookupLayout($a_obj_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT layout FROM lm_data WHERE obj_id = " . + $ilDB->quote($a_obj_id, "integer"); + $obj_set = $ilDB->query($query); + $obj_rec = $ilDB->fetchAssoc($obj_set); + + return $obj_rec["layout"]; + } + + /** + * Get pages of chapter + * + * @param + * @return + */ + public static function getPagesOfChapter($a_lm_id, $a_chap_id) + { + // update structure entries: if at least one page of a chapter is public set chapter to public too + $lm_tree = new ilTree($a_lm_id); + $lm_tree->setTableNames('lm_tree', 'lm_data'); + $lm_tree->setTreeTablePK("lm_id"); + $lm_tree->readRootId(); + + $childs = $lm_tree->getChildsByType($a_chap_id, "pg"); + + return $childs; + } + + /** + * Get all objects of learning module + * + * @param + * @return + */ + public static function _getAllLMObjectsOfLM($a_lm_id, $a_type = "") + { + global $DIC; + + $ilDB = $DIC->database(); + + $and = ($a_type != "") + ? " AND type = " . $ilDB->quote($a_type, "text") + : ""; + + $set = $ilDB->query("SELECT obj_id FROM lm_data " . + " WHERE lm_id = " . $ilDB->quote($a_lm_id, "integer") . $and); + $obj_ids = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $obj_ids[] = $rec["obj_id"]; + } + + return $obj_ids; + } + + + //// + //// Export ID handling + //// + + /** + * Save export id + * + * @param + * @return + */ + public static function saveExportId($a_lm_id, $a_lmobj_id, $a_exp_id, $a_type = "pg") + { + global $DIC; + + $ilDB = $DIC->database(); + + include_once("Services/MetaData/classes/class.ilMDIdentifier.php"); + + if (trim($a_exp_id) == "") { + // delete export ids, if existing + $entries = ilMDIdentifier::_getEntriesForObj( + $a_lm_id, + $a_lmobj_id, + $a_type + ); + + foreach ($entries as $id => $e) { + if ($e["catalog"] == "ILIAS_NID") { + $identifier = new ilMDIdentifier(); + $identifier->setMetaId($id); + $identifier->delete(); + } + } + } else { + // update existing entry + $entries = ilMDIdentifier::_getEntriesForObj( + $a_lm_id, + $a_lmobj_id, + $a_type + ); + + $updated = false; + foreach ($entries as $id => $e) { + if ($e["catalog"] == "ILIAS_NID") { + $identifier = new ilMDIdentifier(); + $identifier->setMetaId($id); + $identifier->read(); + $identifier->setEntry($a_exp_id); + $identifier->update(); + $updated = true; + } + } + + // nothing updated? create a new one + if (!$updated) { + include_once("./Services/MetaData/classes/class.ilMD.php"); + $md = new ilMD($a_lm_id, $a_lmobj_id, $a_type); + $md_gen = $md->getGeneral(); + $identifier = $md_gen->addIdentifier(); + $identifier->setEntry($a_exp_id); + $identifier->setCatalog("ILIAS_NID"); + $identifier->save(); + } + } + } + + /** + * Get export ID + * + * @param + * @return + */ + public static function getExportId($a_lm_id, $a_lmobj_id, $a_type = "pg") + { + // look for export id + include_once("./Services/MetaData/classes/class.ilMDIdentifier.php"); + $entries = ilMDIdentifier::_getEntriesForObj( + $a_lm_id, + $a_lmobj_id, + $a_type + ); + + foreach ($entries as $e) { + if ($e["catalog"] == "ILIAS_NID") { + return $e["entry"]; + } + } + } + + /** + * Does export ID exist in lm? + * + * @param + * @return + */ + public function existsExportID($a_lm_id, $a_exp_id, $a_type = "pg") + { + include_once("./Services/MetaData/classes/class.ilMDIdentifier.php"); + return ilMDIdentifier::existsIdInRbacObject($a_lm_id, $a_type, "ILIAS_NID", $a_exp_id); + } + + /** + * Get duplicate export IDs (count export ID usages) + */ + public static function getDuplicateExportIDs($a_lm_id, $a_type = "pg") + { + include_once("./Services/MetaData/classes/class.ilMDIdentifier.php"); + $entries = ilMDIdentifier::_getEntriesForRbacObj($a_lm_id, $a_type); + $res = array(); + foreach ($entries as $e) { + if ($e["catalog"] == "ILIAS_NID") { + if (ilLMObject::_exists($e["obj_id"])) { + $res[trim($e["entry"])]++; + } + } + } + return $res; + } + + /** + * Does export ID exist in lm? + * + * @param + * @return + */ + public function getExportIDInfo($a_lm_id, $a_exp_id, $a_type = "pg") + { + include_once("./Services/MetaData/classes/class.ilMDIdentifier.php"); + $data = ilMDIdentifier::readIdData($a_lm_id, $a_type, "ILIAS_NID", $a_exp_id); + return $data; + } + + /** + * Get affective title + * + * @param + * @return + */ + public static function _getPresentationTitle( + $a_node, + $a_mode = IL_PAGE_TITLE, + $a_include_numbers = false, + $a_time_scheduled_activation = false, + $a_force_content = false, + $a_lm_id = 0, + $a_lang = "-" + ) { + if ($a_lang == "") { + $a_lang = "-"; + } + + if ($a_node["type"] == "st") { + include_once './Modules/LearningModule/classes/class.ilStructureObject.php'; + return ilStructureObject::_getPresentationTitle( + $a_node["child"], + IL_CHAPTER_TITLE, + $a_include_numbers, + $a_time_scheduled_activation, + $a_force_content, + $a_lm_id, + $a_lang + ); + } else { + include_once './Modules/LearningModule/classes/class.ilLMPageObject.php'; + return ilLMPageObject::_getPresentationTitle( + $a_node["child"], + $a_mode, + $a_include_numbers, + $a_time_scheduled_activation, + $a_force_content, + $a_lm_id, + $a_lang + ); + } + } + + /** + * Get short titles + * + * @param + * @return array + */ + public static function getShortTitles($a_lm_id, $a_lang = "-") + { + global $DIC; + + $db = $DIC->database(); + + $title_data = array(); + if ($a_lang == "-") { + $set = $db->query("SELECT t.child, d.obj_id, d.title, d.short_title FROM lm_data d LEFT JOIN lm_tree t ON (d.obj_id = t.child) WHERE d.lm_id = " . + $db->quote($a_lm_id, "integer") . " ORDER BY t.lft, d.title"); + } else { + $set = $db->query("SELECT t.child, d.obj_id, tr.title, tr.short_title, d.title default_title, d.short_title default_short_title FROM lm_data d " . + " LEFT JOIN lm_tree t ON (d.obj_id = t.child) " . + " LEFT JOIN lm_data_transl tr ON (tr.id = d.obj_id AND tr.lang=" . $db->quote($a_lang, "text") . ") WHERE d.lm_id = " . + $db->quote($a_lm_id, "integer") . " ORDER BY t.lft, d.title"); + } + while ($rec = $db->fetchAssoc($set)) { + $title_data[] = $rec; + } + return $title_data; + } + + /** + * Write short title + * + * @param integer $a_id object id + * @param string $a_short_title short title + */ + public static function writeShortTitle($a_id, $a_short_title, $a_lang = "-") + { + global $DIC; + + $db = $DIC->database(); + + if ($a_lang != "-" && $a_lang != "") { + $trans = new ilLMObjTranslation($a_id, $a_lang); + $trans->setShortTitle($a_short_title); + $trans->save(); + } else { + $db->manipulate( + "UPDATE lm_data SET " . + " short_title = " . $db->quote($a_short_title, "text") . + " WHERE obj_id = " . $db->quote($a_id, "integer") + ); + } + } } -?> diff --git a/Modules/LearningModule/classes/class.ilLMObjectFactory.php b/Modules/LearningModule/classes/class.ilLMObjectFactory.php index 2204eab9083a2757c5868ee82d743603ac493768..e829fca0fa88340f1b641a4d78952847cb8cbf7e 100755 --- a/Modules/LearningModule/classes/class.ilLMObjectFactory.php +++ b/Modules/LearningModule/classes/class.ilLMObjectFactory.php @@ -1,28 +1,28 @@ database(); + $ilDB = $DIC->database(); - $query = "SELECT * FROM lm_data WHERE obj_id = ". - $ilDB->quote($a_id, "integer"); - $obj_set = $ilDB->query($query); - $obj_rec = $ilDB->fetchAssoc($obj_set); + $query = "SELECT * FROM lm_data WHERE obj_id = " . + $ilDB->quote($a_id, "integer"); + $obj_set = $ilDB->query($query); + $obj_rec = $ilDB->fetchAssoc($obj_set); - switch($obj_rec["type"]) - { - case "st": - $obj = new ilStructureObject($a_content_obj); - $obj->setId($obj_rec["obj_id"]); - $obj->setDataRecord($obj_rec); - $obj->read(); - break; - - case "pg": - $obj = new ilLMPageObject($a_content_obj, 0, $a_halt); - $obj->setId($obj_rec["obj_id"]); - $obj->setDataRecord($obj_rec); - $obj->read(); - break; - } - return $obj; - } + switch ($obj_rec["type"]) { + case "st": + $obj = new ilStructureObject($a_content_obj); + $obj->setId($obj_rec["obj_id"]); + $obj->setDataRecord($obj_rec); + $obj->read(); + break; + case "pg": + $obj = new ilLMPageObject($a_content_obj, 0, $a_halt); + $obj->setId($obj_rec["obj_id"]); + $obj->setDataRecord($obj_rec); + $obj->read(); + break; + } + return $obj; + } } -?> diff --git a/Modules/LearningModule/classes/class.ilLMObjectGUI.php b/Modules/LearningModule/classes/class.ilLMObjectGUI.php index e413ab75c1965317f66bd0616865b7819210ca2a..77ff434b50db472c2bedeb33f65c80fc16775689 100755 --- a/Modules/LearningModule/classes/class.ilLMObjectGUI.php +++ b/Modules/LearningModule/classes/class.ilLMObjectGUI.php @@ -15,239 +15,226 @@ */ class ilLMObjectGUI { - var $tpl; - var $lng; - var $obj; - var $ctrl; - var $content_object; - var $actions; - - - /** - * constructor - * - * @param object $a_content_obj content object - */ - function __construct(&$a_content_obj) - { - global $DIC; - - $tpl = $DIC["tpl"]; - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - - $this->tpl = $tpl; - $this->lng = $lng; - $this->ctrl = $ilCtrl; - $this->content_object = $a_content_obj; - } - - - /** - * build action array - * - * @param array $a_actions action array (key = action key, - * value = action language string) - * @access private - */ - function setActions($a_actions = "") - { - if (is_array($a_actions)) - { - foreach ($a_actions as $name => $lng) - { - $this->actions[$name] = array("name" => $name, "lng" => $lng); - } - } - else - { - $this->actions = ""; - } - } - - - /** - * get target frame for command (command is method name without "Object", e.g. "perm") - * @param string $a_cmd command - * @param string $a_target_frame default target frame (is returned, if no special - * target frame was set) - * @access public - */ - function getTargetFrame($a_cmd, $a_target_frame = "") - { - if ($this->target_frame[$a_cmd] != "") - { - return $this->target_frame[$a_cmd]; - } - elseif (!empty($a_target_frame)) - { - return "target=\"".$a_target_frame."\""; - } - else - { - return; - } - } - - /** - * structure / page object creation form - */ - function create() - { - $new_type = $_REQUEST["new_type"]; - - $this->ctrl->setParameter($this, "new_type", $new_type); - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this, "save")); - $form->setTitle( $this->lng->txt($new_type."_new")); - - $title = new ilTextInputGUI($this->lng->txt("title"), "Fobject[title]"); - //$title->setRequired(true); - $form->addItem($title); - - $desc = new ilTextAreaInputGUI($this->lng->txt("description"), "Fobject[desc]"); - $form->addItem($desc); - - $form->addCommandButton("save", $this->lng->txt($new_type."_add")); - $form->addCommandButton("cancel", $this->lng->txt("cancel")); - - $this->tpl->setContent($form->getHTML()); - } - - - /** - * put this object into content object tree - */ - function putInTree() - { - $tree = new ilTree($this->content_object->getId()); - $tree->setTableNames('lm_tree', 'lm_data'); - $tree->setTreeTablePK("lm_id"); - - $parent_id = (!empty($_GET["obj_id"])) - ? $_GET["obj_id"] - : $tree->getRootId(); - - if (!empty($_GET["target"])) - { - $target = $_GET["target"]; - } - else - { - // determine last child of current type - $childs = $tree->getChildsByType($parent_id, $this->obj->getType()); - if (count($childs) == 0) - { - $target = IL_FIRST_NODE; - } - else - { - $target = $childs[count($childs) - 1]["obj_id"]; - } - } - if (!$tree->isInTree($this->obj->getId())) - { - $tree->insertNode($this->obj->getId(), $parent_id, $target); - } - } - - - /** - * Confirm deletion screen (delete page or structure objects) - */ - function delete() - { - $this->setTabs(); - - $cont_obj_gui = new ilObjContentObjectGUI("",$this->content_object->getRefId(), - true, false); - $cont_obj_gui->delete($this->obj->getId()); - } - - - /** - * cancel deletion of page/structure objects - */ - function cancelDelete() - { - ilSession::clear("saved_post"); - $this->ctrl->redirect($this, $_GET["backcmd"]); - } - - - /** - * page and structure object deletion - */ - function confirmedDelete() - { - $cont_obj_gui = new ilObjContentObjectGUI("",$this->content_object->getRefId(), - true, false); - $cont_obj_gui->confirmedDelete($this->obj->getId()); - $this->ctrl->redirect($this, $_GET["backcmd"]); - } - - - /** - * output a cell in object list - */ - function add_cell($val, $link = "") - { - if(!empty($link)) - { - $this->tpl->setCurrentBlock("begin_link"); - $this->tpl->setVariable("LINK_TARGET", $link); - $this->tpl->parseCurrentBlock(); - $this->tpl->touchBlock("end_link"); - } - - $this->tpl->setCurrentBlock("text"); - $this->tpl->setVariable("TEXT_CONTENT", $val); - $this->tpl->parseCurrentBlock(); - $this->tpl->setCurrentBlock("table_cell"); - $this->tpl->parseCurrentBlock(); - } - - - /** - * show possible action (form buttons) - * - * @access public - */ - function showActions($a_actions) - { - foreach ($a_actions as $name => $lng) - { - $d[$name] = array("name" => $name, "lng" => $lng); - } - - $notoperations = array(); - $operations = array(); - - $operations = $d; - - if (count($operations) > 0) - { - foreach ($operations as $val) - { - $this->tpl->setCurrentBlock("operation_btn"); - $this->tpl->setVariable("BTN_NAME", $val["name"]); - $this->tpl->setVariable("BTN_VALUE", $this->lng->txt($val["lng"])); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setCurrentBlock("operation"); - $this->tpl->setVariable("IMG_ARROW",ilUtil::getImagePath("arrow_downright.svg")); - $this->tpl->parseCurrentBlock(); - } - } - - /** - * check the content object tree - */ - function checkTree() - { - $this->content_object->checkTree(); - } + public $tpl; + public $lng; + public $obj; + public $ctrl; + public $content_object; + public $actions; + + + /** + * constructor + * + * @param object $a_content_obj content object + */ + public function __construct(&$a_content_obj) + { + global $DIC; + + $tpl = $DIC["tpl"]; + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + + $this->tpl = $tpl; + $this->lng = $lng; + $this->ctrl = $ilCtrl; + $this->content_object = $a_content_obj; + } + + + /** + * build action array + * + * @param array $a_actions action array (key = action key, + * value = action language string) + * @access private + */ + public function setActions($a_actions = "") + { + if (is_array($a_actions)) { + foreach ($a_actions as $name => $lng) { + $this->actions[$name] = array("name" => $name, "lng" => $lng); + } + } else { + $this->actions = ""; + } + } + + + /** + * get target frame for command (command is method name without "Object", e.g. "perm") + * @param string $a_cmd command + * @param string $a_target_frame default target frame (is returned, if no special + * target frame was set) + * @access public + */ + public function getTargetFrame($a_cmd, $a_target_frame = "") + { + if ($this->target_frame[$a_cmd] != "") { + return $this->target_frame[$a_cmd]; + } elseif (!empty($a_target_frame)) { + return "target=\"" . $a_target_frame . "\""; + } else { + return; + } + } + + /** + * structure / page object creation form + */ + public function create() + { + $new_type = $_REQUEST["new_type"]; + + $this->ctrl->setParameter($this, "new_type", $new_type); + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this, "save")); + $form->setTitle($this->lng->txt($new_type . "_new")); + + $title = new ilTextInputGUI($this->lng->txt("title"), "Fobject[title]"); + //$title->setRequired(true); + $form->addItem($title); + + $desc = new ilTextAreaInputGUI($this->lng->txt("description"), "Fobject[desc]"); + $form->addItem($desc); + + $form->addCommandButton("save", $this->lng->txt($new_type . "_add")); + $form->addCommandButton("cancel", $this->lng->txt("cancel")); + + $this->tpl->setContent($form->getHTML()); + } + + + /** + * put this object into content object tree + */ + public function putInTree() + { + $tree = new ilTree($this->content_object->getId()); + $tree->setTableNames('lm_tree', 'lm_data'); + $tree->setTreeTablePK("lm_id"); + + $parent_id = (!empty($_GET["obj_id"])) + ? $_GET["obj_id"] + : $tree->getRootId(); + + if (!empty($_GET["target"])) { + $target = $_GET["target"]; + } else { + // determine last child of current type + $childs = $tree->getChildsByType($parent_id, $this->obj->getType()); + if (count($childs) == 0) { + $target = IL_FIRST_NODE; + } else { + $target = $childs[count($childs) - 1]["obj_id"]; + } + } + if (!$tree->isInTree($this->obj->getId())) { + $tree->insertNode($this->obj->getId(), $parent_id, $target); + } + } + + + /** + * Confirm deletion screen (delete page or structure objects) + */ + public function delete() + { + $this->setTabs(); + + $cont_obj_gui = new ilObjContentObjectGUI( + "", + $this->content_object->getRefId(), + true, + false + ); + $cont_obj_gui->delete($this->obj->getId()); + } + + + /** + * cancel deletion of page/structure objects + */ + public function cancelDelete() + { + ilSession::clear("saved_post"); + $this->ctrl->redirect($this, $_GET["backcmd"]); + } + + + /** + * page and structure object deletion + */ + public function confirmedDelete() + { + $cont_obj_gui = new ilObjContentObjectGUI( + "", + $this->content_object->getRefId(), + true, + false + ); + $cont_obj_gui->confirmedDelete($this->obj->getId()); + $this->ctrl->redirect($this, $_GET["backcmd"]); + } + + + /** + * output a cell in object list + */ + public function add_cell($val, $link = "") + { + if (!empty($link)) { + $this->tpl->setCurrentBlock("begin_link"); + $this->tpl->setVariable("LINK_TARGET", $link); + $this->tpl->parseCurrentBlock(); + $this->tpl->touchBlock("end_link"); + } + + $this->tpl->setCurrentBlock("text"); + $this->tpl->setVariable("TEXT_CONTENT", $val); + $this->tpl->parseCurrentBlock(); + $this->tpl->setCurrentBlock("table_cell"); + $this->tpl->parseCurrentBlock(); + } + + + /** + * show possible action (form buttons) + * + * @access public + */ + public function showActions($a_actions) + { + foreach ($a_actions as $name => $lng) { + $d[$name] = array("name" => $name, "lng" => $lng); + } + + $notoperations = array(); + $operations = array(); + + $operations = $d; + + if (count($operations) > 0) { + foreach ($operations as $val) { + $this->tpl->setCurrentBlock("operation_btn"); + $this->tpl->setVariable("BTN_NAME", $val["name"]); + $this->tpl->setVariable("BTN_VALUE", $this->lng->txt($val["lng"])); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setCurrentBlock("operation"); + $this->tpl->setVariable("IMG_ARROW", ilUtil::getImagePath("arrow_downright.svg")); + $this->tpl->parseCurrentBlock(); + } + } + + /** + * check the content object tree + */ + public function checkTree() + { + $this->content_object->checkTree(); + } } -?> diff --git a/Modules/LearningModule/classes/class.ilLMPage.php b/Modules/LearningModule/classes/class.ilLMPage.php index e6bb8554487054d8b1ddf24fc16a75f5aa5473cc..111c31b4acba55b88885e8f5397d04f8eb0c3383 100644 --- a/Modules/LearningModule/classes/class.ilLMPage.php +++ b/Modules/LearningModule/classes/class.ilLMPage.php @@ -5,7 +5,7 @@ include_once("./Services/COPage/classes/class.ilPageObject.php"); /** - * Extension of ilPageObject for learning modules + * Extension of ilPageObject for learning modules * * @author Alex Killing * @version $Id$ @@ -13,48 +13,44 @@ include_once("./Services/COPage/classes/class.ilPageObject.php"); */ class ilLMPage extends ilPageObject { - /** - * Get parent type - * - * @return string parent type - */ - function getParentType() - { - return "lm"; - } - - /** - * After constructor - * - * @param - * @return - */ - function afterConstructor() - { - $this->getPageConfig()->configureByObjectId($this->getParentId()); - } + /** + * Get parent type + * + * @return string parent type + */ + public function getParentType() + { + return "lm"; + } + + /** + * After constructor + * + * @param + * @return + */ + public function afterConstructor() + { + $this->getPageConfig()->configureByObjectId($this->getParentId()); + } - /** - * Before page content update - * - * Note: This one is "work in progress", currently only text paragraphs call this hook - * It is called before the page content object invokes the update procedure of - * ilPageObject - * - * @param - * @return - */ - function beforePageContentUpdate($a_page_content) - { - if ($a_page_content->getType() == "par") - { - include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); - $glos = ilObjContentObject::lookupAutoGlossaries($this->getParentId()); - $a_page_content->autoLinkGlossaries($glos); - } - } - + /** + * Before page content update + * + * Note: This one is "work in progress", currently only text paragraphs call this hook + * It is called before the page content object invokes the update procedure of + * ilPageObject + * + * @param + * @return + */ + public function beforePageContentUpdate($a_page_content) + { + if ($a_page_content->getType() == "par") { + include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); + $glos = ilObjContentObject::lookupAutoGlossaries($this->getParentId()); + $a_page_content->autoLinkGlossaries($glos); + } + } } - -?> diff --git a/Modules/LearningModule/classes/class.ilLMPageConfig.php b/Modules/LearningModule/classes/class.ilLMPageConfig.php index 7f4b37c01aaa9492863ce7a0ac7cc1dbe0dd044e..cfd11b2ebacbf29cdf292c549fea9c2e420ac8cb 100644 --- a/Modules/LearningModule/classes/class.ilLMPageConfig.php +++ b/Modules/LearningModule/classes/class.ilLMPageConfig.php @@ -5,7 +5,7 @@ include_once("./Services/COPage/classes/class.ilPageConfig.php"); /** - * Learning module page configuration + * Learning module page configuration * * @author Alex Killing * @version $Id$ @@ -13,57 +13,50 @@ include_once("./Services/COPage/classes/class.ilPageConfig.php"); */ class ilLMPageConfig extends ilPageConfig { - /** - * Init - */ - function init() - { - $lm_set = new ilSetting("lm"); - - $this->setPreventHTMLUnmasking(false); - $this->setPreventRteUsage(true); - $this->setUseAttachedContent(true); - $this->setIntLinkHelpDefaultType("StructureObject"); - $this->setIntLinkHelpDefaultId($_GET["ref_id"]); - $this->removeIntLinkFilter("File"); - $this->setEnableActivation(true); - $this->setEnableSelfAssessment(true, false); - $this->setEnableInternalLinks(true); - $this->setEnableKeywords(true); - $this->setEnableInternalLinks(true); - $this->setEnableAnchors(true); - $this->setMultiLangSupport(true); - if ($lm_set->get("time_scheduled_page_activation")) - { - $this->setEnableScheduledActivation(true); - } + /** + * Init + */ + public function init() + { + $lm_set = new ilSetting("lm"); + + $this->setPreventHTMLUnmasking(false); + $this->setPreventRteUsage(true); + $this->setUseAttachedContent(true); + $this->setIntLinkHelpDefaultType("StructureObject"); + $this->setIntLinkHelpDefaultId($_GET["ref_id"]); + $this->removeIntLinkFilter("File"); + $this->setEnableActivation(true); + $this->setEnableSelfAssessment(true, false); + $this->setEnableInternalLinks(true); + $this->setEnableKeywords(true); + $this->setEnableInternalLinks(true); + $this->setEnableAnchors(true); + $this->setMultiLangSupport(true); + if ($lm_set->get("time_scheduled_page_activation")) { + $this->setEnableScheduledActivation(true); + } - $mset = new ilSetting("mobs"); - if ($mset->get("mep_activate_pages")) - { - $this->setEnablePCType("ContentInclude", true); - } - } + $mset = new ilSetting("mobs"); + if ($mset->get("mep_activate_pages")) { + $this->setEnablePCType("ContentInclude", true); + } + } - /** - * Object specific configuration - * - * @param int $a_obj_id object id - */ - function configureByObjectId($a_obj_id) - { - if ($a_obj_id > 0) - { - include_once("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); - $this->setDisableDefaultQuestionFeedback(ilObjLearningModule::_lookupDisableDefaultFeedback($a_obj_id)); - - if (ilObjContentObject::isOnlineHelpModule($a_obj_id, true)) - { - $this->setEnableSelfAssessment(false, false); - } - } - } - + /** + * Object specific configuration + * + * @param int $a_obj_id object id + */ + public function configureByObjectId($a_obj_id) + { + if ($a_obj_id > 0) { + include_once("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); + $this->setDisableDefaultQuestionFeedback(ilObjLearningModule::_lookupDisableDefaultFeedback($a_obj_id)); + + if (ilObjContentObject::isOnlineHelpModule($a_obj_id, true)) { + $this->setEnableSelfAssessment(false, false); + } + } + } } - -?> diff --git a/Modules/LearningModule/classes/class.ilLMPageGUI.php b/Modules/LearningModule/classes/class.ilLMPageGUI.php index ff4385ccbabf9aa8ba71b41a9d121d7908c1840b..923a7f31fbfacd207dbb4fb67e000740952ac341 100644 --- a/Modules/LearningModule/classes/class.ilLMPageGUI.php +++ b/Modules/LearningModule/classes/class.ilLMPageGUI.php @@ -6,7 +6,7 @@ include_once("./Services/COPage/classes/class.ilPageObjectGUI.php"); include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); /** - * Extension of ilPageObjectGUI for learning modules + * Extension of ilPageObjectGUI for learning modules * * @author Alex Killing * @version $Id$ @@ -16,107 +16,96 @@ include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); */ class ilLMPageGUI extends ilPageObjectGUI { - /** - * @var ilDB - */ - protected $db; - - /** - * Constructor - */ - function __construct($a_id = 0, $a_old_nr = 0, $a_prevent_get_id = false, $a_lang = "") - { - global $DIC; - - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - $this->db = $DIC->database(); - $this->plugin_admin = $DIC["ilPluginAdmin"]; - $this->log = $DIC["ilLog"]; - parent::__construct("lm", $a_id, $a_old_nr, $a_prevent_get_id, $a_lang); - - include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); - $this->getPageConfig()->setUseStoredQuestionTries(ilObjContentObject::_lookupStoreTries($this->getPageObject()->getParentId())); - } - - /** - * On feedback editing forwarding - */ - function onFeedbackEditingForwarding() - { - $lng = $this->lng; - - if (strtolower($_GET["cmdClass"]) == "ilassquestionfeedbackeditinggui") - { - include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); - if (ilObjContentObject::_lookupDisableDefaultFeedback($this->getPageObject()->getParentId())) - { - ilUtil::sendInfo($lng->txt("cont_def_feedb_deactivated")); - } - else - { - ilUtil::sendInfo($lng->txt("cont_def_feedb_activated")); - } - } - } - - /** - * Process answer - */ - function processAnswer() - { - $ilUser = $this->user; - $ilDB = $this->db; - $lng = $this->lng; - $ilPluginAdmin = $this->plugin_admin; - $ilLog = $this->log; - - parent::processAnswer(); - - // - // Send notifications to authors that want to be informed on blocked users - // - - $parent_id = ilPageObject::lookupParentId((int) $_GET["page_id"], "lm"); - - // is restriction mode set? - include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); - if (ilObjContentObject::_lookupRestrictForwardNavigation($parent_id)) - { - // check if user is blocked - $id = ilUtil::stripSlashes($_POST["id"]); - - include_once("./Services/COPage/classes/class.ilPageQuestionProcessor.php"); - $as = ilPageQuestionProcessor::getAnswerStatus($id, $ilUser->getId()); - // get question information - include_once("./Modules/TestQuestionPool/classes/class.ilAssQuestionList.php"); - $qlist = new ilAssQuestionList($ilDB, $lng, $ilPluginAdmin); - $qlist->setParentObjId(0); - $qlist->setJoinObjectData(false); - $qlist->addFieldFilter("question_id", array($id)); - $qlist->load(); - $qdata = $qlist->getQuestionDataArray(); - // has the user been blocked? - if ($as["try"] >= $qdata[$as["qst_id"]]["nr_of_tries"] && $qdata[$as["qst_id"]]["nr_of_tries"] > 0 && !$as["passed"]) - { - include_once "./Services/Notification/classes/class.ilNotification.php"; - $users = ilNotification::getNotificationsForObject(ilNotification::TYPE_LM_BLOCKED_USERS, $parent_id); - - if (count($users) > 0) - { - include_once("./Modules/LearningModule/classes/class.ilLMMailNotification.php"); - $not = new ilLMMailNotification(); - $not->setType(ilLMMailNotification::TYPE_USER_BLOCKED); - $not->setQuestionId($id); - $not->setRefId((int) $_GET["ref_id"]); - $not->setRecipients($users); - $not->send(); - } - } - - } - } - + /** + * @var ilDB + */ + protected $db; + + /** + * Constructor + */ + public function __construct($a_id = 0, $a_old_nr = 0, $a_prevent_get_id = false, $a_lang = "") + { + global $DIC; + + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + $this->db = $DIC->database(); + $this->plugin_admin = $DIC["ilPluginAdmin"]; + $this->log = $DIC["ilLog"]; + parent::__construct("lm", $a_id, $a_old_nr, $a_prevent_get_id, $a_lang); + + include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); + $this->getPageConfig()->setUseStoredQuestionTries(ilObjContentObject::_lookupStoreTries($this->getPageObject()->getParentId())); + } + + /** + * On feedback editing forwarding + */ + public function onFeedbackEditingForwarding() + { + $lng = $this->lng; + + if (strtolower($_GET["cmdClass"]) == "ilassquestionfeedbackeditinggui") { + include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); + if (ilObjContentObject::_lookupDisableDefaultFeedback($this->getPageObject()->getParentId())) { + ilUtil::sendInfo($lng->txt("cont_def_feedb_deactivated")); + } else { + ilUtil::sendInfo($lng->txt("cont_def_feedb_activated")); + } + } + } + + /** + * Process answer + */ + public function processAnswer() + { + $ilUser = $this->user; + $ilDB = $this->db; + $lng = $this->lng; + $ilPluginAdmin = $this->plugin_admin; + $ilLog = $this->log; + + parent::processAnswer(); + + // + // Send notifications to authors that want to be informed on blocked users + // + + $parent_id = ilPageObject::lookupParentId((int) $_GET["page_id"], "lm"); + + // is restriction mode set? + include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); + if (ilObjContentObject::_lookupRestrictForwardNavigation($parent_id)) { + // check if user is blocked + $id = ilUtil::stripSlashes($_POST["id"]); + + include_once("./Services/COPage/classes/class.ilPageQuestionProcessor.php"); + $as = ilPageQuestionProcessor::getAnswerStatus($id, $ilUser->getId()); + // get question information + include_once("./Modules/TestQuestionPool/classes/class.ilAssQuestionList.php"); + $qlist = new ilAssQuestionList($ilDB, $lng, $ilPluginAdmin); + $qlist->setParentObjId(0); + $qlist->setJoinObjectData(false); + $qlist->addFieldFilter("question_id", array($id)); + $qlist->load(); + $qdata = $qlist->getQuestionDataArray(); + // has the user been blocked? + if ($as["try"] >= $qdata[$as["qst_id"]]["nr_of_tries"] && $qdata[$as["qst_id"]]["nr_of_tries"] > 0 && !$as["passed"]) { + include_once "./Services/Notification/classes/class.ilNotification.php"; + $users = ilNotification::getNotificationsForObject(ilNotification::TYPE_LM_BLOCKED_USERS, $parent_id); + + if (count($users) > 0) { + include_once("./Modules/LearningModule/classes/class.ilLMMailNotification.php"); + $not = new ilLMMailNotification(); + $not->setType(ilLMMailNotification::TYPE_USER_BLOCKED); + $not->setQuestionId($id); + $not->setRefId((int) $_GET["ref_id"]); + $not->setRecipients($users); + $not->send(); + } + } + } + } } - -?> diff --git a/Modules/LearningModule/classes/class.ilLMPageObject.php b/Modules/LearningModule/classes/class.ilLMPageObject.php index 31cf9038795607a00cced6b2d09c5bc38361be18..eb1369a36ebd50255e33af6c9089da01f9a9dc2c 100755 --- a/Modules/LearningModule/classes/class.ilLMPageObject.php +++ b/Modules/LearningModule/classes/class.ilLMPageObject.php @@ -5,9 +5,9 @@ require_once("./Modules/LearningModule/classes/class.ilLMObject.php"); require_once("./Modules/LearningModule/classes/class.ilLMPage.php"); -define ("IL_CHAPTER_TITLE", "st_title"); -define ("IL_PAGE_TITLE", "pg_title"); -define ("IL_NO_HEADER", "none"); +define("IL_CHAPTER_TITLE", "st_title"); +define("IL_PAGE_TITLE", "pg_title"); +define("IL_NO_HEADER", "none"); /** * Class ilLMPageObject @@ -28,693 +28,676 @@ define ("IL_NO_HEADER", "none"); */ class ilLMPageObject extends ilLMObject { - var $is_alias; - var $origin_id; - var $id; - var $dom; - var $page_object; - - /** - * Constructor - * @access public - */ - function __construct(&$a_content_obj, $a_id = 0, $a_halt = true) - { - parent::__construct($a_content_obj, $a_id); - $this->setType("pg"); - $this->id = $a_id; - - $this->is_alias = false; - $this->contains_int_link = false; - $this->mobs_contained = array(); - $this->files_contained = array(); - $this->halt_on_error = $a_halt; - - if($a_id != 0) - { - $this->read(); - } - } - - function __desctruct() - { - if(is_object($this->page_object)) - { - unset($this->page_object); - } - } - - /** - * - */ - function read() - { - parent::read(); - - $this->page_object = new ilLMPage($this->id, 0); - } - - function create($a_upload = false, $a_omit_page_object_creation = false) - { - parent::create($a_upload); - if ($a_omit_page_object_creation) - { - return; - } - if(!is_object($this->page_object)) - { - $this->page_object = new ilLMPage(); - } - $this->page_object->setId($this->getId()); - $this->page_object->setParentId($this->getLMId()); - $this->page_object->create($a_upload); - } - - function delete($a_delete_meta_data = true) - { - parent::delete($a_delete_meta_data); - $this->page_object->delete(); - } - - - /** - * copy page - */ - function copy($a_target_lm) - { - // copy page - $lm_page = new ilLMPageObject($a_target_lm); - $lm_page->setTitle($this->getTitle()); - $lm_page->setShortTitle($this->getShortTitle()); - $lm_page->setLayout($this->getLayout()); - $lm_page->setLMId($a_target_lm->getId()); - $lm_page->setType($this->getType()); - $lm_page->setDescription($this->getDescription()); - $lm_page->setImportId("il__pg_".$this->getId()); - $lm_page->create(true); // setting "upload" flag to true prevents creating of meta data - - // check whether export id already exists in the target lm - $del_exp_id = false; - $exp_id = ilLMPageObject::getExportId($this->getLMId(), $this->getId()); - if (trim($exp_id) != "") - { - if (ilLMPageObject::existsExportID($a_target_lm->getId(), $exp_id)) - { - $del_exp_id = true; - } - } - - // copy meta data - include_once("Services/MetaData/classes/class.ilMD.php"); - $md = new ilMD($this->getLMId(), $this->getId(), $this->getType()); - $new_md = $md->cloneMD($a_target_lm->getId(), $lm_page->getId(), $this->getType()); - - // check whether export id already exists in the target lm - if ($del_exp_id) - { - ilLMPageObject::saveExportId($a_target_lm->getId(), $lm_page->getId(), ""); - } - else - { - ilLMPageObject::saveExportId($a_target_lm->getId(), $lm_page->getId(), - trim($exp_id)); - } - - // copy page content and activation - $page = $lm_page->getPageObject(); - $this->page_object->copy($page->getId(), $page->getParentType(), $page->getParentId()); - /*$page->setXMLContent($this->page_object->copyXMLContent()); - $page->setActive($this->page_object->getActive()); - $page->setActivationStart($this->page_object->getActivationStart()); - $page->setActivationEnd($this->page_object->getActivationEnd()); - $page->buildDom(); - $page->update();*/ - $lm_page->read(); // this gets the updated page object into lm page - - // copy translations - include_once("./Modules/LearningModule/classes/class.ilLMObjTranslation.php"); - ilLMObjTranslation::copy($this->getId(), $lm_page->getId()); - - return $lm_page; - } - - /** - * copy a page to another content object (learning module / dlib book) - */ - function ©ToOtherContObject(&$a_cont_obj, &$a_copied_nodes) - { - // copy page - $lm_page = new ilLMPageObject($a_cont_obj); - $lm_page->setTitle($this->getTitle()); - $lm_page->setShortTitle($this->getShortTitle()); - $lm_page->setLMId($a_cont_obj->getId()); - $lm_page->setImportId("il__pg_".$this->getId()); - $lm_page->setType($this->getType()); - $lm_page->setDescription($this->getDescription()); - $lm_page->create(true); // setting "upload" flag to true prevents creating of meta data - $a_copied_nodes[$this->getId()] = $lm_page->getId(); - - // copy meta data - include_once("Services/MetaData/classes/class.ilMD.php"); - $md = new ilMD($this->getLMId(), $this->getId(), $this->getType()); - $new_md = $md->cloneMD($a_cont_obj->getId(), $lm_page->getId(), $this->getType()); - - // copy page content - $page = $lm_page->getPageObject(); - $page->setXMLContent($this->page_object->getXMLContent()); - $page->buildDom(); - $page->update(); - - return $lm_page; - } - - /** - * split page at hierarchical id - * - * the main reason for this method being static is that a lm page - * object is not available within ilPageContentGUI where this method - * is called - */ - static function _splitPage($a_page_id, $a_pg_parent_type, $a_hier_id) - { - // get content object (learning module / digilib book) - $lm_id = ilLMObject::_lookupContObjID($a_page_id); - $type = ilObject::_lookupType($lm_id, false); - include_once ("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); - $cont_obj = new ilObjLearningModule($lm_id, false); - $source_lm_page = new ilLMPageObject($cont_obj, $a_page_id); - - // create new page - $lm_page = new ilLMPageObject($cont_obj); - $lm_page->setTitle($source_lm_page->getTitle()); - $lm_page->setLMId($source_lm_page->getLMId()); - $lm_page->setType($source_lm_page->getType()); - $lm_page->setDescription($source_lm_page->getDescription()); - $lm_page->create(true); - - - // copy complete content of source page to new page - $source_page = $source_lm_page->getPageObject(); - $page = $lm_page->getPageObject(); - $page->setXMLContent($source_page->copyXMLContent()); -//echo htmlentities($source_page->copyXMLContent()); - $page->buildDom(true); - $page->update(); -// echo "-".$page->getId()."-".$page->getParentType()."-"; - - // copy meta data - include_once("Services/MetaData/classes/class.ilMD.php"); - $md = new ilMD($source_lm_page->getLMId(), $a_page_id, $source_lm_page->getType()); - $md->cloneMD($source_lm_page->getLMId(), $lm_page->getId(), $source_lm_page->getType()); - - // insert new page in tree (after original page) - $tree = new ilTree($cont_obj->getId()); - $tree->setTableNames('lm_tree','lm_data'); - $tree->setTreeTablePK("lm_id"); - if ($tree->isInTree($source_lm_page->getId())) - { - $parent_node = $tree->getParentNodeData($source_lm_page->getId()); - $tree->insertNode($lm_page->getId(), $parent_node["child"], $source_lm_page->getId()); - } - - // remove all nodes < hierarchical id from new page (incl. update) - $page->addHierIds(); - $page->deleteContentBeforeHierId($a_hier_id); -// $page->update(); - - // remove all nodes >= hierarchical id from source page - $source_page->buildDom(); - $source_page->addHierIds(); - $source_page->deleteContentFromHierId($a_hier_id); - - return $lm_page; - - } - - /** - * split page to next page at hierarchical id - * - * the main reason for this method being static is that a lm page - * object is not available within ilPageContentGUI where this method - * is called - */ - static function _splitPageNext($a_page_id, $a_pg_parent_type, $a_hier_id) - { - // get content object (learning module / digilib book) - $lm_id = ilLMObject::_lookupContObjID($a_page_id); - $type = ilObject::_lookupType($lm_id, false); - include_once ("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); - $cont_obj = new ilObjLearningModule($lm_id, false); - $tree = new ilTree($cont_obj->getId()); - $tree->setTableNames('lm_tree','lm_data'); - $tree->setTreeTablePK("lm_id"); - - $source_lm_page = new ilLMPageObject($cont_obj, $a_page_id); - $source_page = $source_lm_page->getPageObject(); - - // get next page - $succ = $tree->fetchSuccessorNode($a_page_id, "pg"); - if ($succ["child"] > 0) - { - $target_lm_page = new ilLMPageObject($cont_obj, $succ["child"]); - $target_page = $target_lm_page->getPageObject(); - $target_page->buildDom(); - $target_page->addHierIds(); - - // move nodes to target page - $source_page->buildDom(); - $source_page->addHierIds(); - ilLMPage::_moveContentAfterHierId($source_page, $target_page, $a_hier_id); - //$source_page->deleteContentFromHierId($a_hier_id); - - return $succ["child"]; - } - - } - - - /** - * assign page object - * - * @param object $a_page_obj page object - */ - function assignPageObject(&$a_page_obj) - { - $this->page_object = $a_page_obj; - } - - - /** - * get assigned page object - * - * @return object page object - */ - function &getPageObject() - { - return $this->page_object; - } - - - /** - * set id - */ - function setId($a_id) - { - $this->id = $a_id; - } - - function getId() - { - return $this->id; - } - - /** - * set wether page object is an alias - */ - function setAlias($a_is_alias) - { - $this->is_alias = $a_is_alias; - } - - function isAlias() - { - return $this->is_alias; - } - - // only for page aliases - function setOriginID($a_id) - { - return $this->origin_id = $a_id; - } - - // only for page aliases - function getOriginID() - { - return $this->origin_id; - } - - /** - * static - */ - public static function getPageList($lm_id) - { - return ilLMObject::getObjectList($lm_id, "pg"); - } - - /** - * Get all pages of lm that contain any internal links - */ - static function getPagesWithLinksList($a_lm_id, $a_par_type) - { - $pages = ilLMPageObject::getPageList($a_lm_id); - $ids = array(); - foreach($pages as $page) - { - $ids[] = $page["obj_id"]; - } - - $linked_pages = ilLMPage::getPagesWithLinks($a_par_type, $a_lm_id); - $result = array(); - foreach($pages as $page) - { - if (is_array($linked_pages[$page["obj_id"]])) - { - $result[] = $page; - } - } - return $result; - } - - /** - * presentation title doesn't have to be page title, it may be - * chapter title + page title or chapter title only, depending on settings - * - * @param string $a_mode IL_CHAPTER_TITLE | IL_PAGE_TITLE | IL_NO_HEADER - */ - static function _getPresentationTitle($a_pg_id, $a_mode = IL_CHAPTER_TITLE, - $a_include_numbers = false, $a_time_scheduled_activation = false, - $a_force_content = false, $a_lm_id = 0, $a_lang = "-", $a_include_short = false) - { - if($a_mode == IL_NO_HEADER && !$a_force_content) - { - return ""; - } - - if ($a_lm_id == 0) - { - $a_lm_id = ilLMObject::_lookupContObjID($a_pg_id); - } - - if ($a_lm_id == 0) - { - return ""; - } - - // this is optimized when ilLMObject::preloadDataByLM is invoked (e.g. done in ilLMExplorerGUI) - $title = ""; - if ($a_include_short) - { - $title = trim(ilLMObject::_lookupShortTitle($a_pg_id)); - } - if ($title == "") - { - $title = ilLMObject::_lookupTitle($a_pg_id); - } - - // this is also optimized since ilObjectTranslation re-uses instances for one lm - include_once("./Services/Object/classes/class.ilObjectTranslation.php"); - $ot = ilObjectTranslation::getInstance($a_lm_id); - $languages = $ot->getLanguages(); - - if ($a_lang != "-" && $ot->getContentActivated() && isset($languages[$a_lang])) - { - include_once("./Modules/LearningModule/classes/class.ilLMObjTranslation.php"); - $lmobjtrans = new ilLMObjTranslation($a_pg_id, $a_lang); - $trans_title = ""; - if ($a_include_short) - { - $trans_title = trim($lmobjtrans->getShortTitle()); - } - if ($trans_title == "") - { - $trans_title = $lmobjtrans->getTitle(); - } - if ($trans_title != "") - { - $title = $trans_title; - } - } - - if($a_mode == IL_PAGE_TITLE) - { - return $title; - } - - include_once("./Modules/LearningModule/classes/class.ilLMTree.php"); - $tree = ilLMTree::getInstance($a_lm_id); - - if ($tree->isInTree($a_pg_id)) - { - $pred_node = $tree->fetchPredecessorNode($a_pg_id, "st"); - $childs = $tree->getChildsByType($pred_node["obj_id"], "pg"); - $cnt_str = ""; - if(count($childs) > 1) - { - $cnt = 0; - foreach($childs as $child) - { - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - $active = ilLMPage::_lookupActive($child["obj_id"], - ilObject::_lookupType($a_lm_id), $a_time_scheduled_activation); - - if (!$active) - { - $act_data = ilLMPage::_lookupActivationData((int) $child["obj_id"], ilObject::_lookupType($a_lm_id)); - if ($act_data["show_activation_info"] && - (ilUtil::now() < $act_data["activation_start"])) - { - $active = true; - } - } - - if ($child["type"] != "pg" || $active) - { - $cnt++; - } - if($child["obj_id"] == $a_pg_id) - { - $cur_cnt = $cnt; - } - } - if ($cnt > 1) - { - $cnt_str = " (".$cur_cnt."/".$cnt.")"; - } - } - require_once("./Modules/LearningModule/classes/class.ilStructureObject.php"); - //$struct_obj = new ilStructureObject($pred_node["obj_id"]); - //return $struct_obj->getTitle(); - return ilStructureObject::_getPresentationTitle($pred_node["obj_id"], IL_CHAPTER_TITLE, - $a_include_numbers, false, false, 0, $a_lang, true).$cnt_str; - - //return $pred_node["title"].$cnt_str; - } - else - { - return $title; - } - } - - /** - * export page object to xml (see ilias_co.dtd) - * - * @param object $a_xml_writer ilXmlWriter object that receives the - * xml data - */ - function exportXML(&$a_xml_writer, $a_mode = "normal", $a_inst = 0) - { - $attrs = array(); - $a_xml_writer->xmlStartTag("PageObject", $attrs); - - switch ($a_mode) - { - case "normal": - // MetaData - $this->exportXMLMetaData($a_xml_writer); - - // PageContent - $this->exportXMLPageContent($a_xml_writer, $a_inst); - break; - - case "alias": - $attrs = array(); - $attrs["OriginId"] = "il_".$a_inst. - "_pg_".$this->getId(); - $a_xml_writer->xmlElement("PageAlias", $attrs); - break; - } - - // Layout - // not implemented - - $a_xml_writer->xmlEndTag("PageObject"); - } - - /** - * export page alias to xml - */ - static function _exportXMLAlias(&$a_xml_writer, $a_id, $a_inst = 0) - { - $attrs = array(); - $a_xml_writer->xmlStartTag("PageObject", $attrs); - - $attrs = array(); - $attrs["OriginId"] = "il_".$a_inst. - "_pg_".$a_id; - $a_xml_writer->xmlElement("PageAlias", $attrs); - - $a_xml_writer->xmlEndTag("PageObject"); - } - - - /** - * export page objects meta data to xml (see ilias_co.dtd) - * - * @param object $a_xml_writer ilXmlWriter object that receives the - * xml data - */ - function exportXMLMetaData(&$a_xml_writer) - { - include_once("Services/MetaData/classes/class.ilMD2XML.php"); - $md2xml = new ilMD2XML($this->getLMId(), $this->getId(), $this->getType()); - $md2xml->setExportMode(true); - $md2xml->startExport(); - $a_xml_writer->appendXML($md2xml->getXML()); - } - - function modifyExportIdentifier($a_tag, $a_param, $a_value) - { - if ($a_tag == "Identifier" && $a_param == "Entry") - { - $a_value = "il_".IL_INST_ID."_pg_".$this->getId(); - //$a_value = ilUtil::insertInstIntoID($a_value); - } - - return $a_value; - } - - - /** - * export page objects meta data to xml (see ilias_co.dtd) - * - * @param object $a_xml_writer ilXmlWriter object that receives the - * xml data - */ - function exportXMLPageContent(&$a_xml_writer, $a_inst = 0) - { -//echo "exportxmlpagecontent:$a_inst:
"; - $cont_obj = $this->getContentObject(); - - $this->page_object->buildDom(); - $this->page_object->insertInstIntoIDs($a_inst); - $this->mobs_contained = $this->page_object->collectMediaObjects(false); - //$this->files_contained = $this->page_object->collectFileItems(); - include_once("./Services/COPage/classes/class.ilPCFileList.php"); - $this->files_contained = ilPCFileList::collectFileItems($this->page_object, $this->page_object->getDomDoc()); -// $this->questions_contained = $this->page_object->getQuestionIds(); - $xml = $this->page_object->getXMLFromDom(false, false, false, "", true); - $xml = str_replace("&","&", $xml); - $a_xml_writer->appendXML($xml); - - $this->page_object->freeDom(); - } - - /** - * Get question ids - * - * note: this method must be called afer exportXMLPageContent - */ - function getQuestionIds() - { - include_once("./Services/COPage/classes/class.ilPCQuestion.php"); - return ilPCQuestion::_getQuestionIdsForPage($this->content_object->getType(), - $this->getId()); - } - - /** - * get ids of all media objects within the page - * - * note: this method must be called afer exportXMLPageContent - */ - function getMediaObjectIds() - { - return $this->mobs_contained; - } - - /** - * get ids of all file items within the page - * - * note: this method must be called afer exportXMLPageContent - */ - function getFileItemIds() - { - return $this->files_contained; - } - - /** - * export page object to fo - * - * @param object $a_xml_writer ilXmlWriter object that receives the - * xml data - */ - function exportFO(&$a_xml_writer) - { - $title = ilLMPageObject::_getPresentationTitle($this->getId()); - if ($title != "") - { - $attrs = array(); - $attrs["font-family"] = "Times"; - $attrs["font-size"] = "14pt"; - $a_xml_writer->xmlElement("fo:block", $attrs, $title); - } - - // PageContent - $this->page_object->buildDom(); - $fo = $this->page_object->getFO(); - $a_xml_writer->appendXML($fo); - } - - /** - * Get questions of learning module - * - * @param - * @return - */ - static function queryQuestionsOfLearningModule($a_lm_id, $a_order_field, - $a_order_dir, $a_offset, $a_limit) - { - global $DIC; - - $ilDB = $DIC->database(); - $rbacreview = $DIC->rbac()->review(); - - - // count query - $count_query = "SELECT count(pq.question_id) cnt "; - - // basic query - $query = "SELECT pq.page_id, pq.question_id "; - - $from = " FROM page_question pq JOIN lm_tree t ON (t.lm_id = ".$ilDB->quote($a_lm_id, "integer"). - " AND pq.page_id = t.child and pq.page_parent_type = ".$ilDB->quote("lm", "text").") ". - " WHERE t.lm_id = ".$ilDB->quote($a_lm_id, "integer"); - $count_query.= $from; - $query.= $from; - - - // count query - $set = $ilDB->query($count_query); - $cnt = 0; - if ($rec = $ilDB->fetchAssoc($set)) - { - $cnt = $rec["cnt"]; - } - - $offset = (int) $a_offset; - $limit = (int) $a_limit; - if ($a_limit > 0) - { - $ilDB->setLimit($limit, $offset); - } - - // set query - $set = $ilDB->query($query); - $result = array(); - while($rec = $ilDB->fetchAssoc($set)) - { - $result[] = $rec; - } - return array("cnt" => $cnt, "set" => $result); - } + public $is_alias; + public $origin_id; + public $id; + public $dom; + public $page_object; + + /** + * Constructor + * @access public + */ + public function __construct(&$a_content_obj, $a_id = 0, $a_halt = true) + { + parent::__construct($a_content_obj, $a_id); + $this->setType("pg"); + $this->id = $a_id; + + $this->is_alias = false; + $this->contains_int_link = false; + $this->mobs_contained = array(); + $this->files_contained = array(); + $this->halt_on_error = $a_halt; + + if ($a_id != 0) { + $this->read(); + } + } + + public function __desctruct() + { + if (is_object($this->page_object)) { + unset($this->page_object); + } + } + + /** + * + */ + public function read() + { + parent::read(); + + $this->page_object = new ilLMPage($this->id, 0); + } + + public function create($a_upload = false, $a_omit_page_object_creation = false) + { + parent::create($a_upload); + if ($a_omit_page_object_creation) { + return; + } + if (!is_object($this->page_object)) { + $this->page_object = new ilLMPage(); + } + $this->page_object->setId($this->getId()); + $this->page_object->setParentId($this->getLMId()); + $this->page_object->create($a_upload); + } + + public function delete($a_delete_meta_data = true) + { + parent::delete($a_delete_meta_data); + $this->page_object->delete(); + } + + + /** + * copy page + */ + public function copy($a_target_lm) + { + // copy page + $lm_page = new ilLMPageObject($a_target_lm); + $lm_page->setTitle($this->getTitle()); + $lm_page->setShortTitle($this->getShortTitle()); + $lm_page->setLayout($this->getLayout()); + $lm_page->setLMId($a_target_lm->getId()); + $lm_page->setType($this->getType()); + $lm_page->setDescription($this->getDescription()); + $lm_page->setImportId("il__pg_" . $this->getId()); + $lm_page->create(true); // setting "upload" flag to true prevents creating of meta data + + // check whether export id already exists in the target lm + $del_exp_id = false; + $exp_id = ilLMPageObject::getExportId($this->getLMId(), $this->getId()); + if (trim($exp_id) != "") { + if (ilLMPageObject::existsExportID($a_target_lm->getId(), $exp_id)) { + $del_exp_id = true; + } + } + + // copy meta data + include_once("Services/MetaData/classes/class.ilMD.php"); + $md = new ilMD($this->getLMId(), $this->getId(), $this->getType()); + $new_md = $md->cloneMD($a_target_lm->getId(), $lm_page->getId(), $this->getType()); + + // check whether export id already exists in the target lm + if ($del_exp_id) { + ilLMPageObject::saveExportId($a_target_lm->getId(), $lm_page->getId(), ""); + } else { + ilLMPageObject::saveExportId( + $a_target_lm->getId(), + $lm_page->getId(), + trim($exp_id) + ); + } + + // copy page content and activation + $page = $lm_page->getPageObject(); + $this->page_object->copy($page->getId(), $page->getParentType(), $page->getParentId()); + /*$page->setXMLContent($this->page_object->copyXMLContent()); + $page->setActive($this->page_object->getActive()); + $page->setActivationStart($this->page_object->getActivationStart()); + $page->setActivationEnd($this->page_object->getActivationEnd()); + $page->buildDom(); + $page->update();*/ + $lm_page->read(); // this gets the updated page object into lm page + + // copy translations + include_once("./Modules/LearningModule/classes/class.ilLMObjTranslation.php"); + ilLMObjTranslation::copy($this->getId(), $lm_page->getId()); + + return $lm_page; + } + + /** + * copy a page to another content object (learning module / dlib book) + */ + public function ©ToOtherContObject(&$a_cont_obj, &$a_copied_nodes) + { + // copy page + $lm_page = new ilLMPageObject($a_cont_obj); + $lm_page->setTitle($this->getTitle()); + $lm_page->setShortTitle($this->getShortTitle()); + $lm_page->setLMId($a_cont_obj->getId()); + $lm_page->setImportId("il__pg_" . $this->getId()); + $lm_page->setType($this->getType()); + $lm_page->setDescription($this->getDescription()); + $lm_page->create(true); // setting "upload" flag to true prevents creating of meta data + $a_copied_nodes[$this->getId()] = $lm_page->getId(); + + // copy meta data + include_once("Services/MetaData/classes/class.ilMD.php"); + $md = new ilMD($this->getLMId(), $this->getId(), $this->getType()); + $new_md = $md->cloneMD($a_cont_obj->getId(), $lm_page->getId(), $this->getType()); + + // copy page content + $page = $lm_page->getPageObject(); + $page->setXMLContent($this->page_object->getXMLContent()); + $page->buildDom(); + $page->update(); + + return $lm_page; + } + + /** + * split page at hierarchical id + * + * the main reason for this method being static is that a lm page + * object is not available within ilPageContentGUI where this method + * is called + */ + public static function _splitPage($a_page_id, $a_pg_parent_type, $a_hier_id) + { + // get content object (learning module / digilib book) + $lm_id = ilLMObject::_lookupContObjID($a_page_id); + $type = ilObject::_lookupType($lm_id, false); + include_once("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); + $cont_obj = new ilObjLearningModule($lm_id, false); + $source_lm_page = new ilLMPageObject($cont_obj, $a_page_id); + + // create new page + $lm_page = new ilLMPageObject($cont_obj); + $lm_page->setTitle($source_lm_page->getTitle()); + $lm_page->setLMId($source_lm_page->getLMId()); + $lm_page->setType($source_lm_page->getType()); + $lm_page->setDescription($source_lm_page->getDescription()); + $lm_page->create(true); + + + // copy complete content of source page to new page + $source_page = $source_lm_page->getPageObject(); + $page = $lm_page->getPageObject(); + $page->setXMLContent($source_page->copyXMLContent()); + //echo htmlentities($source_page->copyXMLContent()); + $page->buildDom(true); + $page->update(); + // echo "-".$page->getId()."-".$page->getParentType()."-"; + + // copy meta data + include_once("Services/MetaData/classes/class.ilMD.php"); + $md = new ilMD($source_lm_page->getLMId(), $a_page_id, $source_lm_page->getType()); + $md->cloneMD($source_lm_page->getLMId(), $lm_page->getId(), $source_lm_page->getType()); + + // insert new page in tree (after original page) + $tree = new ilTree($cont_obj->getId()); + $tree->setTableNames('lm_tree', 'lm_data'); + $tree->setTreeTablePK("lm_id"); + if ($tree->isInTree($source_lm_page->getId())) { + $parent_node = $tree->getParentNodeData($source_lm_page->getId()); + $tree->insertNode($lm_page->getId(), $parent_node["child"], $source_lm_page->getId()); + } + + // remove all nodes < hierarchical id from new page (incl. update) + $page->addHierIds(); + $page->deleteContentBeforeHierId($a_hier_id); + // $page->update(); + + // remove all nodes >= hierarchical id from source page + $source_page->buildDom(); + $source_page->addHierIds(); + $source_page->deleteContentFromHierId($a_hier_id); + + return $lm_page; + } + + /** + * split page to next page at hierarchical id + * + * the main reason for this method being static is that a lm page + * object is not available within ilPageContentGUI where this method + * is called + */ + public static function _splitPageNext($a_page_id, $a_pg_parent_type, $a_hier_id) + { + // get content object (learning module / digilib book) + $lm_id = ilLMObject::_lookupContObjID($a_page_id); + $type = ilObject::_lookupType($lm_id, false); + include_once("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); + $cont_obj = new ilObjLearningModule($lm_id, false); + $tree = new ilTree($cont_obj->getId()); + $tree->setTableNames('lm_tree', 'lm_data'); + $tree->setTreeTablePK("lm_id"); + + $source_lm_page = new ilLMPageObject($cont_obj, $a_page_id); + $source_page = $source_lm_page->getPageObject(); + + // get next page + $succ = $tree->fetchSuccessorNode($a_page_id, "pg"); + if ($succ["child"] > 0) { + $target_lm_page = new ilLMPageObject($cont_obj, $succ["child"]); + $target_page = $target_lm_page->getPageObject(); + $target_page->buildDom(); + $target_page->addHierIds(); + + // move nodes to target page + $source_page->buildDom(); + $source_page->addHierIds(); + ilLMPage::_moveContentAfterHierId($source_page, $target_page, $a_hier_id); + //$source_page->deleteContentFromHierId($a_hier_id); + + return $succ["child"]; + } + } + + + /** + * assign page object + * + * @param object $a_page_obj page object + */ + public function assignPageObject(&$a_page_obj) + { + $this->page_object = $a_page_obj; + } + + + /** + * get assigned page object + * + * @return object page object + */ + public function &getPageObject() + { + return $this->page_object; + } + + + /** + * set id + */ + public function setId($a_id) + { + $this->id = $a_id; + } + + public function getId() + { + return $this->id; + } + + /** + * set wether page object is an alias + */ + public function setAlias($a_is_alias) + { + $this->is_alias = $a_is_alias; + } + + public function isAlias() + { + return $this->is_alias; + } + + // only for page aliases + public function setOriginID($a_id) + { + return $this->origin_id = $a_id; + } + + // only for page aliases + public function getOriginID() + { + return $this->origin_id; + } + + /** + * static + */ + public static function getPageList($lm_id) + { + return ilLMObject::getObjectList($lm_id, "pg"); + } + + /** + * Get all pages of lm that contain any internal links + */ + public static function getPagesWithLinksList($a_lm_id, $a_par_type) + { + $pages = ilLMPageObject::getPageList($a_lm_id); + $ids = array(); + foreach ($pages as $page) { + $ids[] = $page["obj_id"]; + } + + $linked_pages = ilLMPage::getPagesWithLinks($a_par_type, $a_lm_id); + $result = array(); + foreach ($pages as $page) { + if (is_array($linked_pages[$page["obj_id"]])) { + $result[] = $page; + } + } + return $result; + } + + /** + * presentation title doesn't have to be page title, it may be + * chapter title + page title or chapter title only, depending on settings + * + * @param string $a_mode IL_CHAPTER_TITLE | IL_PAGE_TITLE | IL_NO_HEADER + */ + public static function _getPresentationTitle( + $a_pg_id, + $a_mode = IL_CHAPTER_TITLE, + $a_include_numbers = false, + $a_time_scheduled_activation = false, + $a_force_content = false, + $a_lm_id = 0, + $a_lang = "-", + $a_include_short = false + ) { + if ($a_mode == IL_NO_HEADER && !$a_force_content) { + return ""; + } + + if ($a_lm_id == 0) { + $a_lm_id = ilLMObject::_lookupContObjID($a_pg_id); + } + + if ($a_lm_id == 0) { + return ""; + } + + // this is optimized when ilLMObject::preloadDataByLM is invoked (e.g. done in ilLMExplorerGUI) + $title = ""; + if ($a_include_short) { + $title = trim(ilLMObject::_lookupShortTitle($a_pg_id)); + } + if ($title == "") { + $title = ilLMObject::_lookupTitle($a_pg_id); + } + + // this is also optimized since ilObjectTranslation re-uses instances for one lm + include_once("./Services/Object/classes/class.ilObjectTranslation.php"); + $ot = ilObjectTranslation::getInstance($a_lm_id); + $languages = $ot->getLanguages(); + + if ($a_lang != "-" && $ot->getContentActivated() && isset($languages[$a_lang])) { + include_once("./Modules/LearningModule/classes/class.ilLMObjTranslation.php"); + $lmobjtrans = new ilLMObjTranslation($a_pg_id, $a_lang); + $trans_title = ""; + if ($a_include_short) { + $trans_title = trim($lmobjtrans->getShortTitle()); + } + if ($trans_title == "") { + $trans_title = $lmobjtrans->getTitle(); + } + if ($trans_title != "") { + $title = $trans_title; + } + } + + if ($a_mode == IL_PAGE_TITLE) { + return $title; + } + + include_once("./Modules/LearningModule/classes/class.ilLMTree.php"); + $tree = ilLMTree::getInstance($a_lm_id); + + if ($tree->isInTree($a_pg_id)) { + $pred_node = $tree->fetchPredecessorNode($a_pg_id, "st"); + $childs = $tree->getChildsByType($pred_node["obj_id"], "pg"); + $cnt_str = ""; + if (count($childs) > 1) { + $cnt = 0; + foreach ($childs as $child) { + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + $active = ilLMPage::_lookupActive( + $child["obj_id"], + ilObject::_lookupType($a_lm_id), + $a_time_scheduled_activation + ); + + if (!$active) { + $act_data = ilLMPage::_lookupActivationData((int) $child["obj_id"], ilObject::_lookupType($a_lm_id)); + if ($act_data["show_activation_info"] && + (ilUtil::now() < $act_data["activation_start"])) { + $active = true; + } + } + + if ($child["type"] != "pg" || $active) { + $cnt++; + } + if ($child["obj_id"] == $a_pg_id) { + $cur_cnt = $cnt; + } + } + if ($cnt > 1) { + $cnt_str = " (" . $cur_cnt . "/" . $cnt . ")"; + } + } + require_once("./Modules/LearningModule/classes/class.ilStructureObject.php"); + //$struct_obj = new ilStructureObject($pred_node["obj_id"]); + //return $struct_obj->getTitle(); + return ilStructureObject::_getPresentationTitle( + $pred_node["obj_id"], + IL_CHAPTER_TITLE, + $a_include_numbers, + false, + false, + 0, + $a_lang, + true + ) . $cnt_str; + + //return $pred_node["title"].$cnt_str; + } else { + return $title; + } + } + + /** + * export page object to xml (see ilias_co.dtd) + * + * @param object $a_xml_writer ilXmlWriter object that receives the + * xml data + */ + public function exportXML(&$a_xml_writer, $a_mode = "normal", $a_inst = 0) + { + $attrs = array(); + $a_xml_writer->xmlStartTag("PageObject", $attrs); + + switch ($a_mode) { + case "normal": + // MetaData + $this->exportXMLMetaData($a_xml_writer); + + // PageContent + $this->exportXMLPageContent($a_xml_writer, $a_inst); + break; + + case "alias": + $attrs = array(); + $attrs["OriginId"] = "il_" . $a_inst . + "_pg_" . $this->getId(); + $a_xml_writer->xmlElement("PageAlias", $attrs); + break; + } + + // Layout + // not implemented + + $a_xml_writer->xmlEndTag("PageObject"); + } + + /** + * export page alias to xml + */ + public static function _exportXMLAlias(&$a_xml_writer, $a_id, $a_inst = 0) + { + $attrs = array(); + $a_xml_writer->xmlStartTag("PageObject", $attrs); + + $attrs = array(); + $attrs["OriginId"] = "il_" . $a_inst . + "_pg_" . $a_id; + $a_xml_writer->xmlElement("PageAlias", $attrs); + + $a_xml_writer->xmlEndTag("PageObject"); + } + + + /** + * export page objects meta data to xml (see ilias_co.dtd) + * + * @param object $a_xml_writer ilXmlWriter object that receives the + * xml data + */ + public function exportXMLMetaData(&$a_xml_writer) + { + include_once("Services/MetaData/classes/class.ilMD2XML.php"); + $md2xml = new ilMD2XML($this->getLMId(), $this->getId(), $this->getType()); + $md2xml->setExportMode(true); + $md2xml->startExport(); + $a_xml_writer->appendXML($md2xml->getXML()); + } + + public function modifyExportIdentifier($a_tag, $a_param, $a_value) + { + if ($a_tag == "Identifier" && $a_param == "Entry") { + $a_value = "il_" . IL_INST_ID . "_pg_" . $this->getId(); + //$a_value = ilUtil::insertInstIntoID($a_value); + } + + return $a_value; + } + + + /** + * export page objects meta data to xml (see ilias_co.dtd) + * + * @param object $a_xml_writer ilXmlWriter object that receives the + * xml data + */ + public function exportXMLPageContent(&$a_xml_writer, $a_inst = 0) + { + //echo "exportxmlpagecontent:$a_inst:
"; + $cont_obj = $this->getContentObject(); + + $this->page_object->buildDom(); + $this->page_object->insertInstIntoIDs($a_inst); + $this->mobs_contained = $this->page_object->collectMediaObjects(false); + //$this->files_contained = $this->page_object->collectFileItems(); + include_once("./Services/COPage/classes/class.ilPCFileList.php"); + $this->files_contained = ilPCFileList::collectFileItems($this->page_object, $this->page_object->getDomDoc()); + // $this->questions_contained = $this->page_object->getQuestionIds(); + $xml = $this->page_object->getXMLFromDom(false, false, false, "", true); + $xml = str_replace("&", "&", $xml); + $a_xml_writer->appendXML($xml); + + $this->page_object->freeDom(); + } + + /** + * Get question ids + * + * note: this method must be called afer exportXMLPageContent + */ + public function getQuestionIds() + { + include_once("./Services/COPage/classes/class.ilPCQuestion.php"); + return ilPCQuestion::_getQuestionIdsForPage( + $this->content_object->getType(), + $this->getId() + ); + } + + /** + * get ids of all media objects within the page + * + * note: this method must be called afer exportXMLPageContent + */ + public function getMediaObjectIds() + { + return $this->mobs_contained; + } + + /** + * get ids of all file items within the page + * + * note: this method must be called afer exportXMLPageContent + */ + public function getFileItemIds() + { + return $this->files_contained; + } + + /** + * export page object to fo + * + * @param object $a_xml_writer ilXmlWriter object that receives the + * xml data + */ + public function exportFO(&$a_xml_writer) + { + $title = ilLMPageObject::_getPresentationTitle($this->getId()); + if ($title != "") { + $attrs = array(); + $attrs["font-family"] = "Times"; + $attrs["font-size"] = "14pt"; + $a_xml_writer->xmlElement("fo:block", $attrs, $title); + } + + // PageContent + $this->page_object->buildDom(); + $fo = $this->page_object->getFO(); + $a_xml_writer->appendXML($fo); + } + + /** + * Get questions of learning module + * + * @param + * @return + */ + public static function queryQuestionsOfLearningModule( + $a_lm_id, + $a_order_field, + $a_order_dir, + $a_offset, + $a_limit + ) { + global $DIC; + + $ilDB = $DIC->database(); + $rbacreview = $DIC->rbac()->review(); + + + // count query + $count_query = "SELECT count(pq.question_id) cnt "; + + // basic query + $query = "SELECT pq.page_id, pq.question_id "; + + $from = " FROM page_question pq JOIN lm_tree t ON (t.lm_id = " . $ilDB->quote($a_lm_id, "integer") . + " AND pq.page_id = t.child and pq.page_parent_type = " . $ilDB->quote("lm", "text") . ") " . + " WHERE t.lm_id = " . $ilDB->quote($a_lm_id, "integer"); + $count_query.= $from; + $query.= $from; + + + // count query + $set = $ilDB->query($count_query); + $cnt = 0; + if ($rec = $ilDB->fetchAssoc($set)) { + $cnt = $rec["cnt"]; + } + + $offset = (int) $a_offset; + $limit = (int) $a_limit; + if ($a_limit > 0) { + $ilDB->setLimit($limit, $offset); + } + + // set query + $set = $ilDB->query($query); + $result = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $result[] = $rec; + } + return array("cnt" => $cnt, "set" => $result); + } } -?> diff --git a/Modules/LearningModule/classes/class.ilLMPageObjectGUI.php b/Modules/LearningModule/classes/class.ilLMPageObjectGUI.php index 2ebecbfcb03781a7120a165b7a014ec9b06b928f..6ab562c201dcbed8a0faa5a47fb2e189a951f3d8 100755 --- a/Modules/LearningModule/classes/class.ilLMPageObjectGUI.php +++ b/Modules/LearningModule/classes/class.ilLMPageObjectGUI.php @@ -20,571 +20,558 @@ require_once("./Services/Link/classes/class.ilInternalLinkGUI.php"); */ class ilLMPageObjectGUI extends ilLMObjectGUI { - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilSetting - */ - protected $settings; - - var $obj; - - /** - * Constructor - * - * @param object $a_content_obj content object (lm | dbk) - * @access public - */ - function __construct(&$a_content_obj) - { - global $DIC; - - $this->tpl = $DIC["tpl"]; - $this->ctrl = $DIC->ctrl(); - $this->tabs = $DIC->tabs(); - $this->settings = $DIC->settings(); - $this->lng = $DIC->language(); - parent::__construct($a_content_obj); - - } - - - /** - * Set content object dependent page object (co page) - */ - function setLMPageObject($a_pg_obj) - { - $this->obj = $a_pg_obj; - $this->obj->setLMId($this->content_object->getId()); - } - - /** - * execute command - */ - function executeCommand() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - $ilSetting = $this->settings; - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - -//echo "
:cmd:".$this->ctrl->getCmd().":cmdClass:".$this->ctrl->getCmdClass().":". -// ":nextClass:".$next_class.":"; flush(); - - switch($next_class) - { - case "illmpagegui": - - // Determine whether the view of a learning resource should - // be shown in the frameset of ilias, or in a separate window. - $showViewInFrameset = true; - $lm_set = new ilSetting("lm"); - - $this->ctrl->setReturn($this, "edit"); - if (!ilPageObject::_exists("lm", $this->obj->getId(), $_GET["transl"]) && - ilPageObject::_exists("lm", $this->obj->getId(), "-")) - { - if ($_GET["totransl"] == "") - { - $_GET["totransl"] = $_GET["transl"]; - $ilCtrl->setCmd("switchToLanguage"); - } - $ilCtrl->setCmdClass("illmpagegui"); - $page_gui = new ilLMPageGUI($this->obj->getId(), 0, false, "-"); - } - else - { - $page_gui = new ilLMPageGUI($this->obj->getId()); - } - $page_gui->setEditPreview(true); - $page_gui->activateMetaDataEditor($this->content_object, - $this->obj->getType(), $this->obj->getId(), - $this->obj, "MDUpdateListener"); - if ($ilSetting->get("block_activated_news")) - { - $page_gui->setEnabledNews(true, $this->obj->content_object->getId(), - $this->obj->content_object->getType()); - } - - // set page view link - if ($showViewInFrameset) - { - $view_frame = ilFrameTargetInfo::_getFrame("MainContent"); - } - else - { - $view_frame = "ilContObj".$this->content_object->getID(); - } - $page_gui->setViewPageLink(ILIAS_HTTP_PATH."/goto.php?target=pg_".$this->obj->getId(). - "_".$_GET["ref_id"], - $view_frame); - - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $page_gui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId( - $this->content_object->getStyleSheetId(), "lm")); - $page_gui->setTemplateTargetVar("ADM_CONTENT"); - $page_gui->getPageObject()->buildDom(); - $int_links = $page_gui->getPageObject()->getInternalLinks(); - $link_xml = $this->getLinkXML($int_links); - $page_gui->setLinkXML($link_xml); - - $page_gui->enableChangeComments($this->content_object->isActiveHistoryUserComments()); - $page_gui->setFileDownloadLink("ilias.php?cmd=downloadFile&ref_id=".$_GET["ref_id"]."&baseClass=ilLMPresentationGUI"); - $page_gui->setFullscreenLink("ilias.php?cmd=fullscreen&ref_id=".$_GET["ref_id"]."&baseClass=ilLMPresentationGUI"); - $page_gui->setLinkParams("ref_id=".$this->content_object->getRefId()); - $page_gui->setSourcecodeDownloadScript("ilias.php?ref_id=".$_GET["ref_id"]."&baseClass=ilLMPresentationGUI"); - $page_gui->setPresentationTitle( - ilLMPageObject::_getPresentationTitle($this->obj->getId(), - $this->content_object->getPageHeader(), $this->content_object->isActiveNumbering())); - $page_gui->setLocator($contObjLocator); - $page_gui->setHeader($this->lng->txt("page").": ".$this->obj->getTitle()); - $page_gui->setActivationListener($this, "activatePage"); - - $up_gui = "ilobjlearningmodulegui"; - $ilCtrl->setParameterByClass($up_gui, "active_node", $this->obj->getId()); - - $tpl->setTitleIcon(ilUtil::getImagePath("icon_pg.svg")); - $tpl->setTitle($this->lng->txt("page").": ".$this->obj->getTitle()); - if ($this->content_object->getLayoutPerPage()) - { - $page_gui->setTabHook($this, "addPageTabs"); - } - $ret = $this->ctrl->forwardCommand($page_gui); - $tpl->setContent($ret); - break; - - default: - $ret = $this->$cmd(); - break; - } - } - - - /* - * display content of page (edit view) - */ - function edit() - { -//echo "
umschuss"; - $this->ctrl->setCmdClass("ilLMPageGUI"); - $this->ctrl->setCmd("edit"); - $this->executeCommand(); - //$this->setTabs(); - } - - /* - * display content of page (edit view) - */ - function preview() - { - $this->ctrl->setCmdClass("ilLMPageGUI"); - $this->ctrl->setCmd("preview"); - $this->executeCommand(); -// $this->setTabs(); - } - - /** - * save co page object - */ - function save() - { - $this->obj = new ilLMPageObject($this->content_object); - $this->obj->setType("pg"); - $this->obj->setTitle(ilUtil::stripSlashes($_POST["Fobject"]["title"])); - $this->obj->setDescription(ilUtil::stripSlashes($_POST["Fobject"]["desc"])); - $this->obj->setLMId($this->content_object->getId()); - $this->obj->create(); - - // obj_id is empty, if page is created from "all pages" screen - // -> a free page is created (not in the tree) -//echo "
savePage:".$_GET["obj_id"].":"; - if ($_GET["obj_id"] != 0) - { - $this->putInTree(); - - // check the tree - $this->checkTree(); - - ilUtil::redirect($this->ctrl->getLinkTargetByClass("ilStructureObjectGUI", - "edit", "", true)); - } - $up_gui = "ilobjlearningmodulegui"; - $this->ctrl->redirectByClass($up_gui, "pages"); - } - - /** - * cancel - */ - function cancel() - { - if ($_GET["obj_id"] != 0) - { - ilUtil::redirect($this->ctrl->getLinkTargetByClass("ilStructureObjectGUI", - "view", "", true)); - } - $up_gui = "ilobjlearningmodulegui"; - $this->ctrl->redirectByClass($up_gui, "pages"); - } - - /** - * get link targets - */ - function getLinkXML($a_int_links) - { - if ($a_layoutframes == "") - { - $a_layoutframes = array(); - } - $link_info = ""; - foreach ($a_int_links as $int_link) - { - $target = $int_link["Target"]; - if (substr($target, 0, 4) == "il__") - { - $target_arr = explode("_", $target); - $target_id = $target_arr[count($target_arr) - 1]; - $type = $int_link["Type"]; - $targetframe = ($int_link["TargetFrame"] != "") - ? $int_link["TargetFrame"] - : "None"; - - // anchor - $anc = $anc_add = ""; - if ($int_link["Anchor"] != "") - { - $anc = $int_link["Anchor"]; - $anc_add = "_".rawurlencode($int_link["Anchor"]); - } - - switch($type) - { - case "PageObject": - case "StructureObject": - $lm_id = ilLMObject::_lookupContObjID($target_id); - $cont_obj = $this->content_object; - if ($lm_id == $cont_obj->getId()) - { - $ltarget = ""; - if ($type == "PageObject") - { - $this->ctrl->setParameter($this, "obj_id", $target_id); - $href = $this->ctrl->getLinkTargetByClass(get_class($this), "edit"); - } - else - { - $this->ctrl->setParameterByClass("ilstructureobjectgui", "obj_id", $target_id); - $href = $this->ctrl->getLinkTargetByClass("ilstructureobjectgui", "view"); - } - $href = str_replace("&", "&", $href); - $this->ctrl->setParameter($this, "obj_id", $_GET["obj_id"]); - } - else - { - if ($type == "PageObject") - { - $href = "goto.php?target=pg_".$target_id.$anc_add; - } - else - { - $href = "goto.php?target=st_".$target_id; - } - $ltarget = "ilContObj".$lm_id; - } - if ($lm_id == "") - { - $href = ""; - } - break; - - case "GlossaryItem": - $ltarget = $nframe = "_blank"; - $href = "ilias.php?cmdClass=illmpresentationgui&baseClass=ilLMPresentationGUI&". - "obj_type=$type&cmd=glossary&ref_id=".$_GET["ref_id"]. - "&obj_id=".$target_id."&frame=$nframe"; - break; - - case "MediaObject": - $ltarget = $nframe = "_blank"; - $href = "ilias.php?cmdClass=illmpresentationgui&baseClass=ilLMPresentationGUI&obj_type=$type&cmd=media&ref_id=".$_GET["ref_id"]. - "&mob_id=".$target_id."&frame=$nframe"; - break; - - case "RepositoryItem": - $obj_type = ilObject::_lookupType($target_id, true); - $obj_id = ilObject::_lookupObjId($target_id); - $href = "./goto.php?target=".$obj_type."_".$target_id; - $t_frame = ilFrameTargetInfo::_getFrame("MainContent", $obj_type); - $ltarget = $t_frame; - break; - - case "File": - $this->ctrl->setParameter($this, "file_id", "il__file_".$target_id); - $href = $this->ctrl->getLinkTarget($this, "downloadFile"); - $this->ctrl->setParameter($this, "file_id", ""); - break; - - case "User": - $obj_type = ilObject::_lookupType($target_id); - if ($obj_type == "usr") - { - include_once("./Services/User/classes/class.ilUserUtil.php"); - $back = $this->ctrl->getLinkTarget($this, "edit"); - //var_dump($back); exit; - $this->ctrl->setParameterByClass("ilpublicuserprofilegui", "user_id", $target_id); - $this->ctrl->setParameterByClass("ilpublicuserprofilegui", "back_url", - rawurlencode($back)); - $href = ""; - include_once("./Services/User/classes/class.ilUserUtil.php"); - if (ilUserUtil::hasPublicProfile($target_id)) - { - $href = $this->ctrl->getLinkTargetByClass("ilpublicuserprofilegui", "getHTML"); - } - $this->ctrl->setParameterByClass("ilpublicuserprofilegui", "user_id", ""); - $lcontent = ilUserUtil::getNamePresentation($target_id, false, false); - } - break; - - } - - if ($href != "") - { - $anc_par = 'Anchor="' . $anc . '"'; - $link_info .= ""; - } - } - } - $link_info.= ""; -//echo ":".htmlentities($link_info).":"; - return $link_info; - } - - /** - * update history - */ - function updateHistory() - { - require_once("./Services/History/classes/class.ilHistory.php"); - ilHistory::_createEntry($this->obj->getId(), "update", - "", $this->content_object->getType().":pg", - "", true); - } - - /** - * redirect script - * - * @param string $a_target - */ - public static function _goto($a_target) - { - global $DIC; - - $rbacsystem = $DIC->rbac()->system(); - $ilErr = $DIC["ilErr"]; - $lng = $DIC->language(); - $ilAccess = $DIC->access(); - - $first = strpos($a_target, "_"); - $second = strpos($a_target, "_", $first + 1); - $page_id = substr($a_target, 0, $first); - if ($first > 0) - { - $page_id = substr($a_target, 0, $first); - if ($second > 0) - { - $ref_id = substr($a_target, $first + 1, $second - ($first + 1)); - $anchor = substr($a_target, $second + 1); - } - else - { - $ref_id = substr($a_target, $first + 1); - } - } - else - { - $page_id = $a_target; - } - - // determine learning object - $lm_id = ilLMObject::_lookupContObjID($page_id); - - // get all references - $ref_ids = ilObject::_getAllReferences($lm_id); - - // always try passed ref id first - if (in_array($ref_id, $ref_ids)) - { - $ref_ids = array_merge(array($ref_id), $ref_ids); - } - - // check read permissions - foreach ($ref_ids as $ref_id) - { - // check read permissions - if ($ilAccess->checkAccess("read", "", $ref_id)) - { - // don't redirect anymore, just set parameters - // (goto.php includes "ilias.php") - $_GET["baseClass"] = "ilLMPresentationGUI"; - $_GET["obj_id"] = $page_id; - $_GET["ref_id"] = $ref_id; - $_GET["anchor"] = $anchor; - include_once("ilias.php"); - exit; - } - } - - if ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) - { - if ($lm_id > 0) - { - ilUtil::sendFailure(sprintf($lng->txt("msg_no_perm_read_item"), - ilObject::_lookupTitle($lm_id)), true); - } - else - { - $lng->loadLanguageModule("content"); - ilUtil::sendFailure($lng->txt("page_does_not_exist"), true); - } - include_once("./Services/Object/classes/class.ilObjectGUI.php"); - ilObjectGUI::_gotoRepositoryRoot(); - } - - $ilErr->raiseError($lng->txt("msg_no_perm_read_lm"), $ilErr->FATAL); - } - - /** - * Edit layout of page - */ - function editLayout() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - $page_gui = new ilLMPageGUI($this->obj->getId()); - $page_gui->setEditPreview(true); - $page_gui->activateMetaDataEditor($this->content_object, - $this->obj->getType(), $this->obj->getId(), - $this->obj, "MDUpdateListener"); - $page_gui->setActivationListener($this, "activatePage"); - $page_gui->setTabHook($this, "addPageTabs"); - $lm_set = new ilSetting("lm"); - $tpl->setTitleIcon(ilUtil::getImagePath("icon_pg.svg")); - $tpl->setTitle($this->lng->txt("page").": ".$this->obj->getTitle()); - $ilCtrl->getHTML($page_gui); - $ilTabs->setTabActive("cont_layout"); - $this->initEditLayoutForm(); - $tpl->setContent($this->form->getHTML()); - } - - /** - * Init edit layout form. - * - * @param int $a_mode Edit Mode - */ - public function initEditLayoutForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - // default layout - $layout = new ilRadioGroupInputGUI($lng->txt("cont_layout"), "layout"); - - if (is_file($im = ilUtil::getImagePath("layout_".$this->content_object->getLayout().".png"))) - { - $im_tag = ilUtil::img($im, $this->content_object->getLayout()); - } - $layout->addOption(new ilRadioOption("
".$im_tag."". - $lng->txt("cont_lm_default_layout"). - ": ".$lng->txt("cont_layout_".$this->content_object->getLayout()). - "
", "")); - - foreach(ilObjContentObject::getAvailableLayouts() as $l) - { - $im_tag = ""; - if (is_file($im = ilUtil::getImagePath("layout_".$l.".png"))) - { - $im_tag = ilUtil::img($im, $l); - } - $layout->addOption(new ilRadioOption("
".$im_tag."". - $lng->txt("cont_layout_".$l).": ".$lng->txt("cont_layout_".$l."_desc"). - "
", $l)); - } - - $layout->setValue($this->obj->getLayout()); - $this->form->addItem($layout); - - $this->form->addCommandButton("saveLayout", $lng->txt("save")); - - $this->form->setTitle($lng->txt("cont_page_layout")); - $this->form->setFormAction($ilCtrl->getFormAction($this)); - - } - - /** - * Save layout - * - */ - public function saveLayout() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->initEditLayoutForm(); - if ($this->form->checkInput()) - { - ilLMObject::writeLayout($this->obj->getId(), $this->form->getInput("layout")); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "editLayout"); - } - $this->form->setValuesByPost(); - $tpl->setContent($this->form->getHtml()); - } - - /** - * Add page tabs - */ - function addPageTabs() - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - - $ilTabs->addTarget("cont_layout", - $ilCtrl->getLinkTarget($this, 'editLayout'), "editLayout"); - } - - /** - * download file of file lists - */ - function downloadFile() - { - $pg_obj = $this->obj->getPageObject(); - $pg_obj->buildDom(); - $int_links = $pg_obj->getInternalLinks(); - foreach ($int_links as $il) - { - if ($il["Target"] == str_replace("_file_", "_dfile_", $_GET["file_id"])) - { - $file = explode("_", $_GET["file_id"]); - $file_id = (int) $file[count($file) - 1]; - require_once("./Modules/File/classes/class.ilObjFile.php"); - $fileObj = new ilObjFile($file_id, false); - $fileObj->sendFile(); - exit; - } - } - } - + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilSetting + */ + protected $settings; + + public $obj; + + /** + * Constructor + * + * @param object $a_content_obj content object (lm | dbk) + * @access public + */ + public function __construct(&$a_content_obj) + { + global $DIC; + + $this->tpl = $DIC["tpl"]; + $this->ctrl = $DIC->ctrl(); + $this->tabs = $DIC->tabs(); + $this->settings = $DIC->settings(); + $this->lng = $DIC->language(); + parent::__construct($a_content_obj); + } + + + /** + * Set content object dependent page object (co page) + */ + public function setLMPageObject($a_pg_obj) + { + $this->obj = $a_pg_obj; + $this->obj->setLMId($this->content_object->getId()); + } + + /** + * execute command + */ + public function executeCommand() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + $ilSetting = $this->settings; + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + //echo "
:cmd:".$this->ctrl->getCmd().":cmdClass:".$this->ctrl->getCmdClass().":". + // ":nextClass:".$next_class.":"; flush(); + + switch ($next_class) { + case "illmpagegui": + + // Determine whether the view of a learning resource should + // be shown in the frameset of ilias, or in a separate window. + $showViewInFrameset = true; + $lm_set = new ilSetting("lm"); + + $this->ctrl->setReturn($this, "edit"); + if (!ilPageObject::_exists("lm", $this->obj->getId(), $_GET["transl"]) && + ilPageObject::_exists("lm", $this->obj->getId(), "-")) { + if ($_GET["totransl"] == "") { + $_GET["totransl"] = $_GET["transl"]; + $ilCtrl->setCmd("switchToLanguage"); + } + $ilCtrl->setCmdClass("illmpagegui"); + $page_gui = new ilLMPageGUI($this->obj->getId(), 0, false, "-"); + } else { + $page_gui = new ilLMPageGUI($this->obj->getId()); + } + $page_gui->setEditPreview(true); + $page_gui->activateMetaDataEditor( + $this->content_object, + $this->obj->getType(), + $this->obj->getId(), + $this->obj, + "MDUpdateListener" + ); + if ($ilSetting->get("block_activated_news")) { + $page_gui->setEnabledNews( + true, + $this->obj->content_object->getId(), + $this->obj->content_object->getType() + ); + } + + // set page view link + if ($showViewInFrameset) { + $view_frame = ilFrameTargetInfo::_getFrame("MainContent"); + } else { + $view_frame = "ilContObj" . $this->content_object->getID(); + } + $page_gui->setViewPageLink( + ILIAS_HTTP_PATH . "/goto.php?target=pg_" . $this->obj->getId() . + "_" . $_GET["ref_id"], + $view_frame + ); + + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $page_gui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId( + $this->content_object->getStyleSheetId(), + "lm" + )); + $page_gui->setTemplateTargetVar("ADM_CONTENT"); + $page_gui->getPageObject()->buildDom(); + $int_links = $page_gui->getPageObject()->getInternalLinks(); + $link_xml = $this->getLinkXML($int_links); + $page_gui->setLinkXML($link_xml); + + $page_gui->enableChangeComments($this->content_object->isActiveHistoryUserComments()); + $page_gui->setFileDownloadLink("ilias.php?cmd=downloadFile&ref_id=" . $_GET["ref_id"] . "&baseClass=ilLMPresentationGUI"); + $page_gui->setFullscreenLink("ilias.php?cmd=fullscreen&ref_id=" . $_GET["ref_id"] . "&baseClass=ilLMPresentationGUI"); + $page_gui->setLinkParams("ref_id=" . $this->content_object->getRefId()); + $page_gui->setSourcecodeDownloadScript("ilias.php?ref_id=" . $_GET["ref_id"] . "&baseClass=ilLMPresentationGUI"); + $page_gui->setPresentationTitle( + ilLMPageObject::_getPresentationTitle( + $this->obj->getId(), + $this->content_object->getPageHeader(), + $this->content_object->isActiveNumbering() + ) + ); + $page_gui->setLocator($contObjLocator); + $page_gui->setHeader($this->lng->txt("page") . ": " . $this->obj->getTitle()); + $page_gui->setActivationListener($this, "activatePage"); + + $up_gui = "ilobjlearningmodulegui"; + $ilCtrl->setParameterByClass($up_gui, "active_node", $this->obj->getId()); + + $tpl->setTitleIcon(ilUtil::getImagePath("icon_pg.svg")); + $tpl->setTitle($this->lng->txt("page") . ": " . $this->obj->getTitle()); + if ($this->content_object->getLayoutPerPage()) { + $page_gui->setTabHook($this, "addPageTabs"); + } + $ret = $this->ctrl->forwardCommand($page_gui); + $tpl->setContent($ret); + break; + + default: + $ret = $this->$cmd(); + break; + } + } + + + /* + * display content of page (edit view) + */ + public function edit() + { + //echo "
umschuss"; + $this->ctrl->setCmdClass("ilLMPageGUI"); + $this->ctrl->setCmd("edit"); + $this->executeCommand(); + //$this->setTabs(); + } + + /* + * display content of page (edit view) + */ + public function preview() + { + $this->ctrl->setCmdClass("ilLMPageGUI"); + $this->ctrl->setCmd("preview"); + $this->executeCommand(); + // $this->setTabs(); + } + + /** + * save co page object + */ + public function save() + { + $this->obj = new ilLMPageObject($this->content_object); + $this->obj->setType("pg"); + $this->obj->setTitle(ilUtil::stripSlashes($_POST["Fobject"]["title"])); + $this->obj->setDescription(ilUtil::stripSlashes($_POST["Fobject"]["desc"])); + $this->obj->setLMId($this->content_object->getId()); + $this->obj->create(); + + // obj_id is empty, if page is created from "all pages" screen + // -> a free page is created (not in the tree) + //echo "
savePage:".$_GET["obj_id"].":"; + if ($_GET["obj_id"] != 0) { + $this->putInTree(); + + // check the tree + $this->checkTree(); + + ilUtil::redirect($this->ctrl->getLinkTargetByClass( + "ilStructureObjectGUI", + "edit", + "", + true + )); + } + $up_gui = "ilobjlearningmodulegui"; + $this->ctrl->redirectByClass($up_gui, "pages"); + } + + /** + * cancel + */ + public function cancel() + { + if ($_GET["obj_id"] != 0) { + ilUtil::redirect($this->ctrl->getLinkTargetByClass( + "ilStructureObjectGUI", + "view", + "", + true + )); + } + $up_gui = "ilobjlearningmodulegui"; + $this->ctrl->redirectByClass($up_gui, "pages"); + } + + /** + * get link targets + */ + public function getLinkXML($a_int_links) + { + if ($a_layoutframes == "") { + $a_layoutframes = array(); + } + $link_info = ""; + foreach ($a_int_links as $int_link) { + $target = $int_link["Target"]; + if (substr($target, 0, 4) == "il__") { + $target_arr = explode("_", $target); + $target_id = $target_arr[count($target_arr) - 1]; + $type = $int_link["Type"]; + $targetframe = ($int_link["TargetFrame"] != "") + ? $int_link["TargetFrame"] + : "None"; + + // anchor + $anc = $anc_add = ""; + if ($int_link["Anchor"] != "") { + $anc = $int_link["Anchor"]; + $anc_add = "_" . rawurlencode($int_link["Anchor"]); + } + + switch ($type) { + case "PageObject": + case "StructureObject": + $lm_id = ilLMObject::_lookupContObjID($target_id); + $cont_obj = $this->content_object; + if ($lm_id == $cont_obj->getId()) { + $ltarget = ""; + if ($type == "PageObject") { + $this->ctrl->setParameter($this, "obj_id", $target_id); + $href = $this->ctrl->getLinkTargetByClass(get_class($this), "edit"); + } else { + $this->ctrl->setParameterByClass("ilstructureobjectgui", "obj_id", $target_id); + $href = $this->ctrl->getLinkTargetByClass("ilstructureobjectgui", "view"); + } + $href = str_replace("&", "&", $href); + $this->ctrl->setParameter($this, "obj_id", $_GET["obj_id"]); + } else { + if ($type == "PageObject") { + $href = "goto.php?target=pg_" . $target_id . $anc_add; + } else { + $href = "goto.php?target=st_" . $target_id; + } + $ltarget = "ilContObj" . $lm_id; + } + if ($lm_id == "") { + $href = ""; + } + break; + + case "GlossaryItem": + $ltarget = $nframe = "_blank"; + $href = "ilias.php?cmdClass=illmpresentationgui&baseClass=ilLMPresentationGUI&" . + "obj_type=$type&cmd=glossary&ref_id=" . $_GET["ref_id"] . + "&obj_id=" . $target_id . "&frame=$nframe"; + break; + + case "MediaObject": + $ltarget = $nframe = "_blank"; + $href = "ilias.php?cmdClass=illmpresentationgui&baseClass=ilLMPresentationGUI&obj_type=$type&cmd=media&ref_id=" . $_GET["ref_id"] . + "&mob_id=" . $target_id . "&frame=$nframe"; + break; + + case "RepositoryItem": + $obj_type = ilObject::_lookupType($target_id, true); + $obj_id = ilObject::_lookupObjId($target_id); + $href = "./goto.php?target=" . $obj_type . "_" . $target_id; + $t_frame = ilFrameTargetInfo::_getFrame("MainContent", $obj_type); + $ltarget = $t_frame; + break; + + case "File": + $this->ctrl->setParameter($this, "file_id", "il__file_" . $target_id); + $href = $this->ctrl->getLinkTarget($this, "downloadFile"); + $this->ctrl->setParameter($this, "file_id", ""); + break; + + case "User": + $obj_type = ilObject::_lookupType($target_id); + if ($obj_type == "usr") { + include_once("./Services/User/classes/class.ilUserUtil.php"); + $back = $this->ctrl->getLinkTarget($this, "edit"); + //var_dump($back); exit; + $this->ctrl->setParameterByClass("ilpublicuserprofilegui", "user_id", $target_id); + $this->ctrl->setParameterByClass( + "ilpublicuserprofilegui", + "back_url", + rawurlencode($back) + ); + $href = ""; + include_once("./Services/User/classes/class.ilUserUtil.php"); + if (ilUserUtil::hasPublicProfile($target_id)) { + $href = $this->ctrl->getLinkTargetByClass("ilpublicuserprofilegui", "getHTML"); + } + $this->ctrl->setParameterByClass("ilpublicuserprofilegui", "user_id", ""); + $lcontent = ilUserUtil::getNamePresentation($target_id, false, false); + } + break; + + } + + if ($href != "") { + $anc_par = 'Anchor="' . $anc . '"'; + $link_info .= ""; + } + } + } + $link_info.= ""; + //echo ":".htmlentities($link_info).":"; + return $link_info; + } + + /** + * update history + */ + public function updateHistory() + { + require_once("./Services/History/classes/class.ilHistory.php"); + ilHistory::_createEntry( + $this->obj->getId(), + "update", + "", + $this->content_object->getType() . ":pg", + "", + true + ); + } + + /** + * redirect script + * + * @param string $a_target + */ + public static function _goto($a_target) + { + global $DIC; + + $rbacsystem = $DIC->rbac()->system(); + $ilErr = $DIC["ilErr"]; + $lng = $DIC->language(); + $ilAccess = $DIC->access(); + + $first = strpos($a_target, "_"); + $second = strpos($a_target, "_", $first + 1); + $page_id = substr($a_target, 0, $first); + if ($first > 0) { + $page_id = substr($a_target, 0, $first); + if ($second > 0) { + $ref_id = substr($a_target, $first + 1, $second - ($first + 1)); + $anchor = substr($a_target, $second + 1); + } else { + $ref_id = substr($a_target, $first + 1); + } + } else { + $page_id = $a_target; + } + + // determine learning object + $lm_id = ilLMObject::_lookupContObjID($page_id); + + // get all references + $ref_ids = ilObject::_getAllReferences($lm_id); + + // always try passed ref id first + if (in_array($ref_id, $ref_ids)) { + $ref_ids = array_merge(array($ref_id), $ref_ids); + } + + // check read permissions + foreach ($ref_ids as $ref_id) { + // check read permissions + if ($ilAccess->checkAccess("read", "", $ref_id)) { + // don't redirect anymore, just set parameters + // (goto.php includes "ilias.php") + $_GET["baseClass"] = "ilLMPresentationGUI"; + $_GET["obj_id"] = $page_id; + $_GET["ref_id"] = $ref_id; + $_GET["anchor"] = $anchor; + include_once("ilias.php"); + exit; + } + } + + if ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) { + if ($lm_id > 0) { + ilUtil::sendFailure(sprintf( + $lng->txt("msg_no_perm_read_item"), + ilObject::_lookupTitle($lm_id) + ), true); + } else { + $lng->loadLanguageModule("content"); + ilUtil::sendFailure($lng->txt("page_does_not_exist"), true); + } + include_once("./Services/Object/classes/class.ilObjectGUI.php"); + ilObjectGUI::_gotoRepositoryRoot(); + } + + $ilErr->raiseError($lng->txt("msg_no_perm_read_lm"), $ilErr->FATAL); + } + + /** + * Edit layout of page + */ + public function editLayout() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + $page_gui = new ilLMPageGUI($this->obj->getId()); + $page_gui->setEditPreview(true); + $page_gui->activateMetaDataEditor( + $this->content_object, + $this->obj->getType(), + $this->obj->getId(), + $this->obj, + "MDUpdateListener" + ); + $page_gui->setActivationListener($this, "activatePage"); + $page_gui->setTabHook($this, "addPageTabs"); + $lm_set = new ilSetting("lm"); + $tpl->setTitleIcon(ilUtil::getImagePath("icon_pg.svg")); + $tpl->setTitle($this->lng->txt("page") . ": " . $this->obj->getTitle()); + $ilCtrl->getHTML($page_gui); + $ilTabs->setTabActive("cont_layout"); + $this->initEditLayoutForm(); + $tpl->setContent($this->form->getHTML()); + } + + /** + * Init edit layout form. + * + * @param int $a_mode Edit Mode + */ + public function initEditLayoutForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + // default layout + $layout = new ilRadioGroupInputGUI($lng->txt("cont_layout"), "layout"); + + if (is_file($im = ilUtil::getImagePath("layout_" . $this->content_object->getLayout() . ".png"))) { + $im_tag = ilUtil::img($im, $this->content_object->getLayout()); + } + $layout->addOption(new ilRadioOption("
" . $im_tag . "" . + $lng->txt("cont_lm_default_layout") . + ": " . $lng->txt("cont_layout_" . $this->content_object->getLayout()) . + "
", "")); + + foreach (ilObjContentObject::getAvailableLayouts() as $l) { + $im_tag = ""; + if (is_file($im = ilUtil::getImagePath("layout_" . $l . ".png"))) { + $im_tag = ilUtil::img($im, $l); + } + $layout->addOption(new ilRadioOption("
" . $im_tag . "" . + $lng->txt("cont_layout_" . $l) . ": " . $lng->txt("cont_layout_" . $l . "_desc") . + "
", $l)); + } + + $layout->setValue($this->obj->getLayout()); + $this->form->addItem($layout); + + $this->form->addCommandButton("saveLayout", $lng->txt("save")); + + $this->form->setTitle($lng->txt("cont_page_layout")); + $this->form->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * Save layout + * + */ + public function saveLayout() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $this->initEditLayoutForm(); + if ($this->form->checkInput()) { + ilLMObject::writeLayout($this->obj->getId(), $this->form->getInput("layout")); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "editLayout"); + } + $this->form->setValuesByPost(); + $tpl->setContent($this->form->getHtml()); + } + + /** + * Add page tabs + */ + public function addPageTabs() + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + + $ilTabs->addTarget( + "cont_layout", + $ilCtrl->getLinkTarget($this, 'editLayout'), + "editLayout" + ); + } + + /** + * download file of file lists + */ + public function downloadFile() + { + $pg_obj = $this->obj->getPageObject(); + $pg_obj->buildDom(); + $int_links = $pg_obj->getInternalLinks(); + foreach ($int_links as $il) { + if ($il["Target"] == str_replace("_file_", "_dfile_", $_GET["file_id"])) { + $file = explode("_", $_GET["file_id"]); + $file_id = (int) $file[count($file) - 1]; + require_once("./Modules/File/classes/class.ilObjFile.php"); + $fileObj = new ilObjFile($file_id, false); + $fileObj->sendFile(); + exit; + } + } + } } -?> diff --git a/Modules/LearningModule/classes/class.ilLMPagesTableGUI.php b/Modules/LearningModule/classes/class.ilLMPagesTableGUI.php index 90ab37dbf9f133550476e4451d00c3c3bf106c13..ca2dbe39291af8450f636dad542383f379a66b1c 100644 --- a/Modules/LearningModule/classes/class.ilLMPagesTableGUI.php +++ b/Modules/LearningModule/classes/class.ilLMPagesTableGUI.php @@ -14,154 +14,145 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilLMPagesTableGUI extends ilTable2GUI { - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_lm) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_lm) + { + 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->lm = $a_lm; - $this->lm_set = new ilSetting("lm"); - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setData(ilLMPageObject::getPageList($this->lm->getId())); - $this->setTitle($lng->txt("cont_pages")); - - $this->addColumn($this->lng->txt(""), "", "1"); - $this->addColumn($this->lng->txt("type"), "", "1"); - $this->addColumn($this->lng->txt("title")); - $this->addColumn($this->lng->txt("cont_usage")); - - $this->setSelectAllCheckbox("id[]"); - - if ($this->lm->getLayoutPerPage()) - { - $this->addColumn($this->lng->txt("cont_layout")); - } - - $this->setLimit(9999); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.page_list_row.html", "Modules/LearningModule"); - - if(ilEditClipboard::getContentObjectType() == "pg" && - ilEditClipboard::getAction() == "copy") - { - $this->addMultiCommand("pastePage", $lng->txt("pastePage")); - } + $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->lm = $a_lm; + $this->lm_set = new ilSetting("lm"); + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setData(ilLMPageObject::getPageList($this->lm->getId())); + $this->setTitle($lng->txt("cont_pages")); + + $this->addColumn($this->lng->txt(""), "", "1"); + $this->addColumn($this->lng->txt("type"), "", "1"); + $this->addColumn($this->lng->txt("title")); + $this->addColumn($this->lng->txt("cont_usage")); + + $this->setSelectAllCheckbox("id[]"); + + if ($this->lm->getLayoutPerPage()) { + $this->addColumn($this->lng->txt("cont_layout")); + } + + $this->setLimit(9999); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.page_list_row.html", "Modules/LearningModule"); + + if (ilEditClipboard::getContentObjectType() == "pg" && + ilEditClipboard::getAction() == "copy") { + $this->addMultiCommand("pastePage", $lng->txt("pastePage")); + } - if ($this->lm->getLayoutPerPage()) - { - $this->addMultiCommand("setPageLayout", $lng->txt("cont_set_layout")); - } - - $this->addMultiCommand("activatePages", $lng->txt("cont_de_activate")); - $this->addMultiCommand("movePage", $lng->txt("movePage")); - $this->addMultiCommand("copyPage", $lng->txt("copyPage")); - $this->addMultiCommand("delete", $lng->txt("delete")); - $this->addMultiCommand("selectHeader", $lng->txt("selectHeader")); - $this->addMultiCommand("selectFooter", $lng->txt("selectFooter")); + if ($this->lm->getLayoutPerPage()) { + $this->addMultiCommand("setPageLayout", $lng->txt("cont_set_layout")); + } + + $this->addMultiCommand("activatePages", $lng->txt("cont_de_activate")); + $this->addMultiCommand("movePage", $lng->txt("movePage")); + $this->addMultiCommand("copyPage", $lng->txt("copyPage")); + $this->addMultiCommand("delete", $lng->txt("delete")); + $this->addMultiCommand("selectHeader", $lng->txt("selectHeader")); + $this->addMultiCommand("selectFooter", $lng->txt("selectFooter")); -// $this->addCommandButton("", $lng->txt("")); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; -//var_dump($a_set); + // $this->addCommandButton("", $lng->txt("")); + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + //var_dump($a_set); - // icon... - - // check activation - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - $active = ilLMPage::_lookupActive($a_set["obj_id"], $this->lm->getType(), - $this->lm_set->get("time_scheduled_page_activation")); - - // is page scheduled? - $img_sc = ($this->lm_set->get("time_scheduled_page_activation") && - ilLMPage::_isScheduledActivation($a_set["obj_id"], $this->lm->getType())) - ? "_sc" - : ""; + // icon... + + // check activation + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + $active = ilLMPage::_lookupActive( + $a_set["obj_id"], + $this->lm->getType(), + $this->lm_set->get("time_scheduled_page_activation") + ); + + // is page scheduled? + $img_sc = ($this->lm_set->get("time_scheduled_page_activation") && + ilLMPage::_isScheduledActivation($a_set["obj_id"], $this->lm->getType())) + ? "_sc" + : ""; - if (!$active) - { - $img = "icon_pg_d".$img_sc.".svg"; - $alt = $lng->txt("cont_page_deactivated"); - } - else - { - if (ilLMPage::_lookupContainsDeactivatedElements($a_set["obj_id"], - $this->lm->getType())) - { - $img = "icon_pg_del".$img_sc.".svg"; - $alt = $lng->txt("cont_page_deactivated_elements"); - } - else - { - $img = "icon_pg".$img_sc.".svg"; - $alt = $this->lng->txt("pg"); - } - } - $this->tpl->setVariable("ICON", ilUtil::img(ilUtil::getImagePath($img), $alt)); + if (!$active) { + $img = "icon_pg_d" . $img_sc . ".svg"; + $alt = $lng->txt("cont_page_deactivated"); + } else { + if (ilLMPage::_lookupContainsDeactivatedElements( + $a_set["obj_id"], + $this->lm->getType() + )) { + $img = "icon_pg_del" . $img_sc . ".svg"; + $alt = $lng->txt("cont_page_deactivated_elements"); + } else { + $img = "icon_pg" . $img_sc . ".svg"; + $alt = $this->lng->txt("pg"); + } + } + $this->tpl->setVariable("ICON", ilUtil::img(ilUtil::getImagePath($img), $alt)); - // title/link - $ilCtrl->setParameter($this, "backcmd", ""); - $ilCtrl->setParameterByClass("ilLMPageObjectGUI", "obj_id", $a_set["obj_id"]); - $this->tpl->setVariable("HREF_TITLE", - $ilCtrl->getLinkTargetByClass("ilLMPageObjectGUI", "edit")); - $this->tpl->setVariable("TITLE", $a_set["title"]); - $this->tpl->setVariable("ID", $a_set["obj_id"]); - - // context - if ($this->lm->lm_tree->isInTree($a_set["obj_id"])) - { - $path_str = $this->parent_obj->getContextPath($a_set["obj_id"]); - } - else - { - $path_str = "---"; - } + // title/link + $ilCtrl->setParameter($this, "backcmd", ""); + $ilCtrl->setParameterByClass("ilLMPageObjectGUI", "obj_id", $a_set["obj_id"]); + $this->tpl->setVariable( + "HREF_TITLE", + $ilCtrl->getLinkTargetByClass("ilLMPageObjectGUI", "edit") + ); + $this->tpl->setVariable("TITLE", $a_set["title"]); + $this->tpl->setVariable("ID", $a_set["obj_id"]); + + // context + if ($this->lm->lm_tree->isInTree($a_set["obj_id"])) { + $path_str = $this->parent_obj->getContextPath($a_set["obj_id"]); + } else { + $path_str = "---"; + } - // check whether page is header or footer - $add_str = ""; - if ($a_set["obj_id"] == $this->lm->getHeaderPage()) - { - $add_str = " (".$lng->txt("cont_header").")"; - } - if ($a_set["obj_id"] == $this->lm->getFooterPage()) - { - $add_str.= " (".$lng->txt("cont_footer").")"; - } - - $this->tpl->setVariable("USAGE", $path_str.$add_str); - - // layout - if ($this->lm->getLayoutPerPage()) - { - if (($l = ilLMObject::lookupLayout($a_set["obj_id"])) != "") - { - $this->tpl->setVariable("LAYOUT", - $lng->txt("cont_layout_".$l)); - } - } - } + // check whether page is header or footer + $add_str = ""; + if ($a_set["obj_id"] == $this->lm->getHeaderPage()) { + $add_str = " (" . $lng->txt("cont_header") . ")"; + } + if ($a_set["obj_id"] == $this->lm->getFooterPage()) { + $add_str.= " (" . $lng->txt("cont_footer") . ")"; + } + + $this->tpl->setVariable("USAGE", $path_str . $add_str); + // layout + if ($this->lm->getLayoutPerPage()) { + if (($l = ilLMObject::lookupLayout($a_set["obj_id"])) != "") { + $this->tpl->setVariable( + "LAYOUT", + $lng->txt("cont_layout_" . $l) + ); + } + } + } } -?> diff --git a/Modules/LearningModule/classes/class.ilLMPresentationGUI.php b/Modules/LearningModule/classes/class.ilLMPresentationGUI.php index 2f3996f5399ce094aaade61dea64c754b6ccdab1..97e490abd315475299376298df064783ec17fe7d 100755 --- a/Modules/LearningModule/classes/class.ilLMPresentationGUI.php +++ b/Modules/LearningModule/classes/class.ilLMPresentationGUI.php @@ -22,3275 +22,3110 @@ require_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); */ class ilLMPresentationGUI { - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * @var ilNavigationHistory - */ - protected $nav_history; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilSetting - */ - protected $settings; - - /** - * @var ilMainMenuGUI - */ - protected $main_menu; - - /** - * @var ilLocatorGUI - */ - protected $locator; - - /** - * @var ilTree - */ - protected $tree; - - /** - * @var ilHelpGUI - */ - protected $help; - - var $lm; - var $tpl; - var $lng; - var $layout_doc; - var $offline; - var $offline_directory; - protected $current_page_id = false; - protected $focus_id = 0; // focus id is set e.g. from learning objectives course, we focus on a chapter/page - protected $export_all_languages = false; - - function __construct() - { - global $DIC; - - $this->user = $DIC->user(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->error = $DIC["ilErr"]; - $this->nav_history = $DIC["ilNavigationHistory"]; - $this->access = $DIC->access(); - $this->settings = $DIC->settings(); - $this->locator = $DIC["ilLocator"]; - $this->tree = $DIC->repositoryTree(); - $this->help = $DIC["ilHelp"]; - $ilUser = $DIC->user(); - $lng = $DIC->language(); - $tpl = $DIC["tpl"]; - $rbacsystem = $DIC->rbac()->system(); - $ilCtrl = $DIC->ctrl(); - $ilErr = $DIC["ilErr"]; - - // load language vars - $lng->loadLanguageModule("content"); - - $this->lng = $lng; - $this->tpl = $tpl; - $this->offline = false; - $this->frames = array(); - $this->ctrl = $ilCtrl; - $this->ctrl->saveParameter($this, array("ref_id", "transl", "focus_id", "focus_return")); - $this->lm_set = new ilSetting("lm"); - - include_once("./Modules/LearningModule/classes/class.ilObjLearningModuleGUI.php"); - $this->lm_gui = new ilObjLearningModuleGUI($data,$_GET["ref_id"],true,false); - $this->lm = $this->lm_gui->object; - - // language translation - include_once("./Services/Object/classes/class.ilObjectTranslation.php"); - $this->ot = ilObjectTranslation::getInstance($this->lm->getId()); - //include_once("./Services/COPage/classes/class.ilPageMultiLang.php"); - //$this->ml = new ilPageMultiLang("lm", $this->lm->getId()); - $this->lang = "-"; - if ($this->ot->getContentActivated()) - { - $langs = $this->ot->getLanguages(); - if (isset($langs[$_GET["transl"]]) || $_GET["transl"] == $this->ot->getMasterLanguage()) - { - $this->lang = $_GET["transl"]; - } - else if (isset($langs[$ilUser->getCurrentLanguage()])) - { - $this->lang = $ilUser->getCurrentLanguage(); - } - if ($this->lang == $this->ot->getMasterLanguage()) - { - $this->lang = "-"; - } - } - - // check, if learning module is online - if (!$rbacsystem->checkAccess("write", $_GET["ref_id"])) - { - if ($this->lm->getOfflineStatus()) - { - $ilErr->raiseError($lng->txt("permission_denied"), $ilErr->WARNING); - } - } - - include_once("./Modules/LearningModule/classes/class.ilLMTree.php"); - $this->lm_tree = ilLMTree::getInstance($this->lm->getId()); - - /*$this->lm_tree = new ilTree($this->lm->getId()); - $this->lm_tree->setTableNames('lm_tree','lm_data'); - $this->lm_tree->setTreeTablePK("lm_id");*/ - - if ((int) $_GET["focus_id"] > 0 && $this->lm_tree->isInTree((int) $_GET["focus_id"])) - { - $this->focus_id = (int) $_GET["focus_id"]; - } - } - - - /** - * execute command - */ - function executeCommand() - { - $ilNavigationHistory = $this->nav_history; - $ilAccess = $this->access; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - // check read permission and parent conditions - // todo: replace all this by ilAccess call - if (!$ilAccess->checkAccess("read", "", $_GET["ref_id"]) && - (!(($this->ctrl->getCmd() == "infoScreen" || $this->ctrl->getNextClass() == "ilinfoscreengui") - && $ilAccess->checkAccess("visible", "", $_GET["ref_id"])))) - { - $ilErr->raiseError($lng->txt("permission_denied"), $ilErr->WARNING); - } - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd("layout", array("showPrintView")); - - $cmd = (isset($_POST['cmd']['citation'])) - ? "ilCitation" - : $cmd; - - $obj_id = $_GET["obj_id"]; - $this->ctrl->setParameter($this, "obj_id", $_GET["obj_id"]); - $ilNavigationHistory->addItem($_GET["ref_id"], $this->ctrl->getLinkTarget($this),"lm"); - $this->ctrl->setParameter($this, "obj_id", $obj_id); - - switch($next_class) - { - case "ilnotegui": - $ret = $this->layout(); - break; - - case "ilinfoscreengui": - $ret = $this->outputInfoScreen(); - break; - - case "ilcommonactiondispatchergui": - include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); - $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); - $gui->enableCommentsSettings(false); - $this->ctrl->forwardCommand($gui); - break; - - case "illmpagegui": - include_once("./Modules/LearningModule/classes/class.ilLMPageGUI.php"); - $page_gui = $this->getLMPageGUI($_GET["obj_id"]); - $this->basicPageGuiInit($page_gui); - $ret = $ilCtrl->forwardCommand($page_gui); - break; - - case "ilglossarydefpagegui": - include_once("./Modules/Glossary/classes/class.ilGlossaryDefPageGUI.php"); - $page_gui = new ilGlossaryDefPageGUI($_GET["obj_id"]); - $this->basicPageGuiInit($page_gui); - $ret = $ilCtrl->forwardCommand($page_gui); - break; - - case "illearningprogressgui": - $this->initScreenHead("learning_progress"); - include_once './Services/Tracking/classes/class.ilLearningProgressGUI.php'; - $new_gui = new ilLearningProgressGUI(ilLearningProgressGUI::LP_CONTEXT_REPOSITORY, $_GET["ref_id"], $ilUser->getId()); - $this->ctrl->forwardCommand($new_gui); - break; - - case "ilratinggui": - include_once("./Services/Rating/classes/class.ilRatingGUI.php"); - $rating_gui = new ilRatingGUI(); - $rating_gui->setObject($this->lm->getId(), "lm", $_GET["obj_id"], "lm"); - $this->ctrl->forwardCommand($rating_gui); - break; - - default: - $ret = $this->$cmd(); - break; - } - } - - - /** - * set offline mode (content is generated for offline package) - */ - function setOfflineMode($a_offline = true, $a_all_languages = false) - { - $this->offline = $a_offline; - $this->export_all_languages = $a_all_languages; - } - - - /** - * checks wether offline content generation is activated - */ - function offlineMode() - { - return $this->offline; - } - - /** - * set export format - * - * @param string $a_format "html" / "scorm" - */ - function setExportFormat($a_format) - { - $this->export_format = $a_format; - } - - /** - * get export format - * - * @return string export format - */ - function getExportFormat() - { - return $this->export_format; - } - - /** - * this dummy function is needed for offline package creation - */ - function nop() - { - } + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilNavigationHistory + */ + protected $nav_history; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var ilMainMenuGUI + */ + protected $main_menu; + + /** + * @var ilLocatorGUI + */ + protected $locator; + + /** + * @var ilTree + */ + protected $tree; + + /** + * @var ilHelpGUI + */ + protected $help; + + public $lm; + public $tpl; + public $lng; + public $layout_doc; + public $offline; + public $offline_directory; + protected $current_page_id = false; + protected $focus_id = 0; // focus id is set e.g. from learning objectives course, we focus on a chapter/page + protected $export_all_languages = false; + + public function __construct() + { + global $DIC; + + $this->user = $DIC->user(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->error = $DIC["ilErr"]; + $this->nav_history = $DIC["ilNavigationHistory"]; + $this->access = $DIC->access(); + $this->settings = $DIC->settings(); + $this->locator = $DIC["ilLocator"]; + $this->tree = $DIC->repositoryTree(); + $this->help = $DIC["ilHelp"]; + $ilUser = $DIC->user(); + $lng = $DIC->language(); + $tpl = $DIC["tpl"]; + $rbacsystem = $DIC->rbac()->system(); + $ilCtrl = $DIC->ctrl(); + $ilErr = $DIC["ilErr"]; + + // load language vars + $lng->loadLanguageModule("content"); + + $this->lng = $lng; + $this->tpl = $tpl; + $this->offline = false; + $this->frames = array(); + $this->ctrl = $ilCtrl; + $this->ctrl->saveParameter($this, array("ref_id", "transl", "focus_id", "focus_return")); + $this->lm_set = new ilSetting("lm"); + + include_once("./Modules/LearningModule/classes/class.ilObjLearningModuleGUI.php"); + $this->lm_gui = new ilObjLearningModuleGUI($data, $_GET["ref_id"], true, false); + $this->lm = $this->lm_gui->object; + + // language translation + include_once("./Services/Object/classes/class.ilObjectTranslation.php"); + $this->ot = ilObjectTranslation::getInstance($this->lm->getId()); + //include_once("./Services/COPage/classes/class.ilPageMultiLang.php"); + //$this->ml = new ilPageMultiLang("lm", $this->lm->getId()); + $this->lang = "-"; + if ($this->ot->getContentActivated()) { + $langs = $this->ot->getLanguages(); + if (isset($langs[$_GET["transl"]]) || $_GET["transl"] == $this->ot->getMasterLanguage()) { + $this->lang = $_GET["transl"]; + } elseif (isset($langs[$ilUser->getCurrentLanguage()])) { + $this->lang = $ilUser->getCurrentLanguage(); + } + if ($this->lang == $this->ot->getMasterLanguage()) { + $this->lang = "-"; + } + } + + // check, if learning module is online + if (!$rbacsystem->checkAccess("write", $_GET["ref_id"])) { + if ($this->lm->getOfflineStatus()) { + $ilErr->raiseError($lng->txt("permission_denied"), $ilErr->WARNING); + } + } + + include_once("./Modules/LearningModule/classes/class.ilLMTree.php"); + $this->lm_tree = ilLMTree::getInstance($this->lm->getId()); + + /*$this->lm_tree = new ilTree($this->lm->getId()); + $this->lm_tree->setTableNames('lm_tree','lm_data'); + $this->lm_tree->setTreeTablePK("lm_id");*/ + + if ((int) $_GET["focus_id"] > 0 && $this->lm_tree->isInTree((int) $_GET["focus_id"])) { + $this->focus_id = (int) $_GET["focus_id"]; + } + } + + + /** + * execute command + */ + public function executeCommand() + { + $ilNavigationHistory = $this->nav_history; + $ilAccess = $this->access; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + // check read permission and parent conditions + // todo: replace all this by ilAccess call + if (!$ilAccess->checkAccess("read", "", $_GET["ref_id"]) && + (!(($this->ctrl->getCmd() == "infoScreen" || $this->ctrl->getNextClass() == "ilinfoscreengui") + && $ilAccess->checkAccess("visible", "", $_GET["ref_id"])))) { + $ilErr->raiseError($lng->txt("permission_denied"), $ilErr->WARNING); + } + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd("layout", array("showPrintView")); + + $cmd = (isset($_POST['cmd']['citation'])) + ? "ilCitation" + : $cmd; + + $obj_id = $_GET["obj_id"]; + $this->ctrl->setParameter($this, "obj_id", $_GET["obj_id"]); + $ilNavigationHistory->addItem($_GET["ref_id"], $this->ctrl->getLinkTarget($this), "lm"); + $this->ctrl->setParameter($this, "obj_id", $obj_id); + + switch ($next_class) { + case "ilnotegui": + $ret = $this->layout(); + break; + + case "ilinfoscreengui": + $ret = $this->outputInfoScreen(); + break; + + case "ilcommonactiondispatchergui": + include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); + $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); + $gui->enableCommentsSettings(false); + $this->ctrl->forwardCommand($gui); + break; + + case "illmpagegui": + include_once("./Modules/LearningModule/classes/class.ilLMPageGUI.php"); + $page_gui = $this->getLMPageGUI($_GET["obj_id"]); + $this->basicPageGuiInit($page_gui); + $ret = $ilCtrl->forwardCommand($page_gui); + break; + + case "ilglossarydefpagegui": + include_once("./Modules/Glossary/classes/class.ilGlossaryDefPageGUI.php"); + $page_gui = new ilGlossaryDefPageGUI($_GET["obj_id"]); + $this->basicPageGuiInit($page_gui); + $ret = $ilCtrl->forwardCommand($page_gui); + break; + + case "illearningprogressgui": + $this->initScreenHead("learning_progress"); + include_once './Services/Tracking/classes/class.ilLearningProgressGUI.php'; + $new_gui = new ilLearningProgressGUI(ilLearningProgressGUI::LP_CONTEXT_REPOSITORY, $_GET["ref_id"], $ilUser->getId()); + $this->ctrl->forwardCommand($new_gui); + break; + + case "ilratinggui": + include_once("./Services/Rating/classes/class.ilRatingGUI.php"); + $rating_gui = new ilRatingGUI(); + $rating_gui->setObject($this->lm->getId(), "lm", $_GET["obj_id"], "lm"); + $this->ctrl->forwardCommand($rating_gui); + break; + + default: + $ret = $this->$cmd(); + break; + } + } + + + /** + * set offline mode (content is generated for offline package) + */ + public function setOfflineMode($a_offline = true, $a_all_languages = false) + { + $this->offline = $a_offline; + $this->export_all_languages = $a_all_languages; + } + + + /** + * checks wether offline content generation is activated + */ + public function offlineMode() + { + return $this->offline; + } + + /** + * set export format + * + * @param string $a_format "html" / "scorm" + */ + public function setExportFormat($a_format) + { + $this->export_format = $a_format; + } + + /** + * get export format + * + * @return string export format + */ + public function getExportFormat() + { + return $this->export_format; + } + + /** + * this dummy function is needed for offline package creation + */ + public function nop() + { + } + + /** + * calls export of digilib-object + * at this point other lm-objects can be exported + * + * @param + * @access public + * @return + */ + public function export() + { + } + + /** + * Get tracker + * + * @return ilLMTracker tracker instance + */ + public function getTracker() + { + include_once("./Modules/LearningModule/classes/class.ilLMTracker.php"); + $tracker = ilLMTracker::getInstance($this->lm->getRefId()); + $tracker->setCurrentPage($this->getCurrentPageId()); + return $tracker; + } + + public function attrib2arr($a_attributes) + { + $attr = array(); + if (!is_array($a_attributes)) { + return $attr; + } + foreach ($a_attributes as $attribute) { + $attr[$attribute->name()] = $attribute->value(); + } + return $attr; + } + + /** + * get frames of current frame set + */ + public function getCurrentFrameSet() + { + return $this->frames; + } + + /** + * Determine layout + */ + public function determineLayout() + { + if ($this->getExportFormat() == "scorm") { + $layout = "1window"; + } else { + $layout = $this->lm->getLayout(); + if ($this->lm->getLayoutPerPage()) { + $pg_id = $this->getCurrentPageId(); + if (!in_array($_GET["frame"], array("", "_blank")) && $_GET["from_page"] > 0) { + $pg_id = (int) $_GET["from_page"]; + } + + // this is needed, e.g. lm is toc2win, page is 3window and media linked to media frame + if (in_array($_GET["cmd"], array("media", "glossary")) && $_GET["back_pg"] > 0) { + $pg_id = (int) $_GET["back_pg"]; + } + + if ($pg_id > 0) { + $lay = ilLMObject::lookupLayout($pg_id); + if ($lay != "") { + $layout = $lay; + } + } + } + } + + return $layout; + } + + public function resume() + { + $ilUser = $this->user; + + if ($ilUser->getId() != ANONYMOUS_USER_ID && $_GET["focus_id"] == "") { + include_once("./Modules/LearningModule/classes/class.ilObjLearningModuleAccess.php"); + $last_accessed_page = ilObjLearningModuleAccess::_getLastAccessedPage((int) $_GET["ref_id"], $ilUser->getId()); + + // if last accessed page was final page do nothing, start over + if ($last_accessed_page && + $last_accessed_page != $this->lm_tree->getLastActivePage()) { + $_GET["obj_id"] = $last_accessed_page; + } + } + + $this->layout(); + } + + /** + * generates frame layout + */ + public function layout($a_xml = "main.xml", $doShow = true) + { + global $DIC; + + $tpl = $this->tpl; + $ilSetting = $this->settings; + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + $layout = $this->determineLayout(); + + // xmldocfile is deprecated! Use domxml_open_file instead. + // But since using relative pathes with domxml under windows don't work, + // we need another solution: + $xmlfile = file_get_contents("./Modules/LearningModule/layouts/lm/" . $layout . "/" . $a_xml); + + if (!$doc = domxml_open_mem($xmlfile)) { + include_once("./Modules/LearningModule/exceptions/class.ilLMPresentationException.php"); + throw new ilLMPresentationException("ilLMPresentation: XML File invalid. Error reading " . + $layout . "/" . $a_xml . "."); + } + $this->layout_doc = $doc; + //echo ":".htmlentities($xmlfile).":$layout:$a_xml:"; + + // get current frame node + $xpc = xpath_new_context($doc); + $path = (empty($_GET["frame"]) || ($_GET["frame"] == "_blank")) + ? "/ilLayout/ilFrame[1]" + : "//ilFrame[@name='" . $_GET["frame"] . "']"; + $result = xpath_eval($xpc, $path); + $found = $result->nodeset; + if (count($found) != 1) { + include_once("./Modules/LearningModule/exceptions/class.ilLMPresentationException.php"); + throw new ilLMPresentationException("ilLMPresentation: XML File invalid. Found " . count($found) . " nodes for " . + " path " . $path . " in " . $layout . "/" . $a_xml . ". LM Layout is " . $this->lm->getLayout()); + } + $node = $found[0]; + + // ProcessFrameset + // node is frameset, if it has cols or rows attribute + $attributes = $this->attrib2arr($node->attributes()); + + $this->frames = array(); + if ((!empty($attributes["rows"])) || (!empty($attributes["cols"]))) { + $content .= $this->buildTag("start", "frameset", $attributes); + //$this->frames = array(); + $this->processNodes($content, $node); + $content .= $this->buildTag("end", "frameset"); + $this->tpl = new ilTemplate("tpl.frameset.html", true, true, "Modules/LearningModule"); + $this->renderPageTitle(); + $this->tpl->setVariable("FS_CONTENT", $content); + if (!$doshow) { + $content = $this->tpl->get(); + } + } else { // node is frame -> process the content tags + // ProcessContentTag + //if ((empty($attributes["template"]) || !empty($_GET["obj_type"]))) + if ((empty($attributes["template"]) || !empty($_GET["obj_type"])) + && ($_GET["frame"] != "_blank" || $_GET["obj_type"] != "MediaObject")) { + // we got a variable content frame (can display different + // object types (PageObject, MediaObject, GlossarItem) + // and contains elements for them) + + // determine object type + if (empty($_GET["obj_type"])) { + $obj_type = "PageObject"; + } else { + $obj_type = $_GET["obj_type"]; + } + + // get object specific node + $childs = $node->child_nodes(); + $found = false; + foreach ($childs as $child) { + if ($child->node_name() == $obj_type) { + $found = true; + $attributes = $this->attrib2arr($child->attributes()); + $node = $child; + //echo "
2node:".$node->node_name(); + break; + } + } + if (!$found) { + include_once("./Modules/LearningModule/exceptions/class.ilLMPresentationException.php"); + throw new ilLMPresentationException("ilLMPresentation: No template specified for frame '" . + $_GET["frame"] . "' and object type '" . $obj_type . "'."); + } + } + + // get template + $in_module = ($attributes["template_location"] == "module") + ? true + : false; + if ($in_module) { + $this->tpl = new ilTemplate($attributes["template"], true, true, $in_module); + $this->tpl->setBodyClass(""); + } else { + $this->tpl = $tpl; + } + + // set style sheets + if (!$this->offlineMode()) { + $this->tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); + } else { + $style_name = $ilUser->getPref("style") . ".css"; + $this->tpl->setVariable("LOCATION_STYLESHEET", "./style/" . $style_name); + } + + include_once("./Services/jQuery/classes/class.iljQueryUtil.php"); + + iljQueryUtil::initjQuery($this->tpl); + iljQueryUtil::initjQueryUI($this->tpl); + + include_once("./Services/UICore/classes/class.ilUIFramework.php"); + ilUIFramework::init($this->tpl); + + // to make e.g. advanced seletions lists work: + $GLOBALS["tpl"] = $this->tpl; + + $childs = $node->child_nodes(); + + foreach ($childs as $child) { + $child_attr = $this->attrib2arr($child->attributes()); + + switch ($child->node_name()) { + case "ilMainMenu": + $this->ilMainMenu(); + //$this->renderPageTitle(); + break; + + case "ilTOC": + $this->ilTOC($child_attr["target_frame"]); + break; + + case "ilPage": + $this->renderPageTitle(); + switch ($this->lm->getType()) { + case "lm": + unset($_SESSION["tr_id"]); + unset($_SESSION["bib_id"]); + unset($_SESSION["citation"]); + $content = $this->ilPage($child); + break; + } + break; + + case "ilGlossary": + $content = $this->ilGlossary($child); + break; + + case "ilLMNavigation": + $this->ilLMNavigation(); + break; + + case "ilMedia": + $this->ilMedia(); + break; + + case "ilLocator": + $this->ilLocator(); + break; + + case "ilJavaScript": + $this->ilJavaScript( + $child_attr["inline"], + $child_attr["file"], + $child_attr["location"] + ); + break; + + case "ilLMMenu": + $this->ilLMMenu(); + break; + + case "ilLMHead": + $this->ilLMHead(); + break; + + case "ilLMSubMenu": + $this->ilLMSubMenu(); + break; + + case "ilLMNotes": + $this->ilLMNotes(); + break; + } + } + + // TODO: Very dirty hack to force the import of JavaScripts in learning content in the FAQ frame (e.g. if jsMath is in the content) + // Unfortunately there is no standardized way to do this somewhere else. Calling fillJavaScripts always in ilTemplate causes multiple additions of the the js files. + // 19.7.2014: outcommented, since fillJavaScriptFiles is called in the next blocks, and the + // following lines would add the js files two times + // if (strcmp($_GET["frame"], "topright") == 0) $this->tpl->fillJavaScriptFiles(); + // if (strcmp($_GET["frame"], "right") == 0) $this->tpl->fillJavaScriptFiles(); + // if (strcmp($_GET["frame"], "botright") == 0) $this->tpl->fillJavaScriptFiles(); + + if (!$this->offlineMode()) { + include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); + ilAccordionGUI::addJavaScript(); + ilAccordionGUI::addCss(); + + + $this->tpl->addJavascript("./Modules/LearningModule/js/LearningModule.js"); + include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); + $close_call = "il.LearningModule.setCloseHTML('" . ilGlyphGUI::get(ilGlyphGUI::CLOSE) . "');"; + $this->tpl->addOnLoadCode($close_call); + + //$store->set("cf_".$this->lm->getId()); + + // handle initial content + if ($_GET["frame"] == "") { + include_once("./Services/Authentication/classes/class.ilSessionIStorage.php"); + $store = new ilSessionIStorage("lm"); + $last_frame_url = $store->get("cf_" . $this->lm->getId()); + if ($last_frame_url != "") { + $this->tpl->addOnLoadCode("il.LearningModule.setLastFrameUrl('" . $last_frame_url . "', 'center_bottom');"); + } + + if (in_array($layout, array("toc2windyn"))) { + $this->tpl->addOnLoadCode("il.LearningModule.setSaveUrl('" . + $ilCtrl->getLinkTarget($this, "saveFrameUrl", "", false, false) . "'); + il.LearningModule.openInitFrames(); + "); + } + $this->tpl->addOnLoadCode("il.LearningModule.setTocRefreshUrl('" . + $ilCtrl->getLinkTarget($this, "refreshToc", "", false, false) . "'); + "); + } + + // from main menu + // $this->tpl->addJavascript("./Services/JavaScript/js/Basic.js"); + $this->tpl->addJavascript("./Services/Navigation/js/ServiceNavigation.js"); + ilYuiUtil::initConnection($this->tpl); + $this->tpl->fillJavaScriptFiles(); + $this->tpl->fillScreenReaderFocus(); + + $this->tpl->fillCssFiles(); + } else { + // reset standard css files + $this->tpl->resetJavascript(); + $this->tpl->resetCss(); + $this->tpl->setBodyClass("ilLMNoMenu"); + + include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); + foreach (ilObjContentObject::getSupplyingExportFiles() as $f) { + if ($f["type"] == "js") { + $this->tpl->addJavascript($f["target"]); + } + if ($f["type"] == "css") { + $this->tpl->addCSS($f["target"]); + } + } + $this->tpl->fillJavaScriptFiles(true); + $this->tpl->fillCssFiles(true); + } + + + $this->tpl->fillBodyClass(); + } + + if ($doShow) { + // (horrible) workaround for preventing template engine + // from hiding paragraph text that is enclosed + // in curly brackets (e.g. "{a}", see ilPageObjectGUI::showPage()) + + $this->tpl->fillTabs(); + if ($this->fill_on_load_code) { + $this->tpl->fillOnLoadCode(); + //$this->tpl->fillViewAppendInlineCss(); + } + $content = $this->tpl->get(); + $content = str_replace("{", "{", $content); + $content = str_replace("}", "}", $content); + + header('Content-type: text/html; charset=UTF-8'); + echo $content; + } else { + $this->tpl->fillLeftNav(); + $this->tpl->fillOnLoadCode(); + //$this->tpl->fillViewAppendInlineCss(); + $content = $this->tpl->get(); + } + + return($content); + } + + /** + * Save frame url + * + * @param + * @return + */ + public function saveFrameUrl() + { + include_once("./Services/Authentication/classes/class.ilSessionIStorage.php"); + $store = new ilSessionIStorage("lm"); + if ($_GET["url"] != "") { + $store->set("cf_" . $this->lm->getId(), $_GET["url"]); + } else { + $store->set("cf_" . $this->lm->getId(), $_GET["url"]); + } + } + + + public function fullscreen() + { + return $this->layout("fullscreen.xml", !$this->offlineMode()); + } + + public function media() + { + if ($_GET["frame"] != "_blank") { + return $this->layout("main.xml", !$this->offlineMode()); + } else { + return $this->layout("fullscreen.xml", !$this->offlineMode()); + } + } + + public function glossary() + { + global $DIC; + + $ilUser = $this->user; + + if ($_GET["frame"] != "_blank") { + $this->layout(); + } else { + $this->tpl = new ilTemplate("tpl.glossary_term_output.html", true, true, true); + $GLOBALS["tpl"] = $this->tpl; + $this->renderPageTitle(); + + // set style sheets + if (!$this->offlineMode()) { + $this->tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); + } else { + $style_name = $ilUser->getPref("style") . ".css"; + ; + $this->tpl->setVariable("LOCATION_STYLESHEET", "./style/" . $style_name); + } + + $this->ilGlossary($child); + if (!$this->offlineMode()) { + $this->tpl->show(); + } else { + return $this->tpl->get(); + } + } + } + + /** + * output main menu + */ + public function ilMainMenu() + { + // LTI + global $DIC; + $ltiview = $DIC["lti"]; + if ($ltiview->isActive()) { + include_once './Services/LTI/classes/class.ilMainMenuGUI.php'; + $ilMainMenu = new LTI\ilMainMenuGUI("_top", false, $this->tpl); + } else { + include_once './Services/MainMenu/classes/class.ilMainMenuGUI.php'; + $ilMainMenu = new ilMainMenuGUI("_top", false, $this->tpl); + } + + if ($this->offlineMode()) { + $this->tpl->touchBlock("pg_intro"); + $this->tpl->touchBlock("pg_outro"); + return; + } + + $page_id = $this->getCurrentPageId(); + if ($page_id > 0) { + $ilMainMenu->setLoginTargetPar("pg_" . $page_id . "_" . $this->lm->getRefId()); + } + + //$this->tpl->touchBlock("mm_intro"); + //$this->tpl->touchBlock("mm_outro"); + $this->tpl->touchBlock("pg_intro"); + $this->tpl->touchBlock("pg_outro"); + $this->tpl->setBodyClass("std"); + $this->tpl->setVariable("MAINMENU", $ilMainMenu->getHTML()); + // LTI + $this->tpl->setVariable("MAINMENU_SPACER", $ilMainMenu->getSpacerClass()); + } + + /** + * table of contents + */ + public function ilTOC($a_get_explorer = false) + { + include_once("./Modules/LearningModule/classes/class.ilLMTOCExplorerGUI.php"); + $exp = new ilLMTOCExplorerGUI($this, "ilTOC", $this, $this->lang, $this->focus_id, $this->export_all_languages); + $exp->setMainTemplate($this->tpl); + $exp->setTracker($this->getTracker()); + if (!$exp->handleCommand()) { + // determine highlighted and force open nodes + $page_id = $this->getCurrentPageId(); + if ($this->deactivated_page) { + $page_id = $_GET["obj_id"]; + } + if ($page_id > 0) { + $exp->setPathOpen((int) $page_id); + } + // empty chapter + if ($this->chapter_has_no_active_page && + ilLMObject::_lookupType($_GET["obj_id"]) == "st") { + $exp->setHighlightNode($_GET["obj_id"]); + } else { + if ($this->lm->getTOCMode() == "pages") { + if ($this->deactivated_page) { + $exp->setHighlightNode($_GET["obj_id"]); + } else { + $exp->setHighlightNode($page_id); + } + } else { + $exp->setHighlightNode($this->lm_tree->getParentId($page_id)); + } + } + if ($this->offlineMode()) { + $exp->setOfflineMode(true); + } + + if ($a_get_explorer) { + return $exp; + } else { + $this->tpl->setCurrentBlock("il_toc"); + $this->tpl->setVariable("EXPLORER", $exp->getHTML()); + $this->tpl->parseCurrentBlock(); + } + } + } + + /** + * Get lm presentationtitle + * + * @param + * @return + */ + public function getLMPresentationTitle() + { + if ($this->offlineMode() && $this->lang != "" && $this->lang != "-") { + include_once("./Services/Object/classes/class.ilObjectTranslation.php"); + $ot = ilObjectTranslation::getInstance($this->lm->getId()); + $data = $ot->getLanguages(); + $ltitle = $data[$this->lang]["title"]; + if ($ltitle != "") { + return $ltitle; + } + } + return $this->lm->getTitle(); + } + + + /** + * output learning module menu + */ + public function ilLMMenu() + { + $this->tpl->setVariable("MENU", $this->lm_gui->setilLMMenu( + $this->offlineMode() + , + $this->getExportFormat(), + "content", + false, + true, + $this->getCurrentPageId(), + $this->lang, + $this->export_all_languages + )); + } + + /** + * output lm header + */ + public function ilLMHead() + { + $this->tpl->setCurrentBlock("header_image"); + if ($this->offlineMode()) { + $this->tpl->setVariable("IMG_HEADER", "./images/icon_lm.svg"); + } else { + $this->tpl->setVariable("IMG_HEADER", ilUtil::getImagePath("icon_lm.svg")); + } + $this->tpl->parseCurrentBlock(); + $this->tpl->setCurrentBlock("lm_head"); + $this->tpl->setVariable("HEADER", $this->getLMPresentationTitle()); + $this->tpl->parseCurrentBlock(); + } + + /** + * output learning module submenu + */ + public function ilLMSubMenu() + { + $rbacsystem = $this->rbacsystem; + + if ($this->abstract) { + return; + } + + $showViewInFrameset = true; + + if ($showViewInFrameset) { + $buttonTarget = ilFrameTargetInfo::_getFrame("MainContent"); + } else { + $buttonTarget = "_top"; + } + + + include_once("./Services/UICore/classes/class.ilTemplate.php"); + $tpl_menu = new ilTemplate("tpl.lm_sub_menu.html", true, true, true); + + $pg_id = $this->getCurrentPageId(); + if ($pg_id == 0) { + return; + } + + // edit learning module + if (!$this->offlineMode()) { + if ($rbacsystem->checkAccess("write", $_GET["ref_id"])) { + $tpl_menu->setCurrentBlock("edit_page"); + $page_id = $this->getCurrentPageId(); + $tpl_menu->setVariable("EDIT_LINK", ILIAS_HTTP_PATH . "/ilias.php?baseClass=ilLMEditorGUI&ref_id=" . $_GET["ref_id"] . + "&obj_id=" . $page_id . "&to_page=1"); + $tpl_menu->setVariable("EDIT_TXT", $this->lng->txt("edit_page")); + $tpl_menu->setVariable("EDIT_TARGET", $buttonTarget); + $tpl_menu->parseCurrentBlock(); + } + + $page_id = $this->getCurrentPageId(); + + include_once("./Services/PermanentLink/classes/class.ilPermanentLinkGUI.php"); + $plinkgui = new ilPermanentLinkGUI( + "pg", + $page_id . "_" . $this->lm->getRefId(), + "", + "_top" + ); + + $title = $this->getLMPresentationTitle(); + $pg_title = ilLMPageObject::_getPresentationTitle( + $page_id, + $this->lm->getPageHeader(), + $this->lm->isActiveNumbering(), + $this->lm_set->get("time_scheduled_page_activation"), + false, + 0, + $this->lang + ); + if ($pg_title != "") { + $title.= ": " . $pg_title; + } + + $plinkgui->setTitle($title); + + $tpl_menu->setCurrentBlock("perma_link"); + $tpl_menu->setVariable("PERMA_LINK", $plinkgui->getHTML()); + $tpl_menu->parseCurrentBlock(); + } + + $this->tpl->setVariable("SUBMENU", $tpl_menu->get()); + } + + + /** + * Redraw header action + */ + public function redrawHeaderAction() + { + echo $this->addHeaderAction(true); + exit; + } + + /** + * Add header action + */ + public function addHeaderAction($a_redraw = false) + { + $ilAccess = $this->access; + $tpl = $this->tpl; + + include_once "Services/Object/classes/class.ilCommonActionDispatcherGUI.php"; + $dispatcher = new ilCommonActionDispatcherGUI( + ilCommonActionDispatcherGUI::TYPE_REPOSITORY, + $ilAccess, + $this->lm->getType(), + $_GET["ref_id"], + $this->lm->getId() + ); + $dispatcher->setSubObject("pg", $this->getCurrentPageId()); + + 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), + $this->tpl + ); + + $lg = $dispatcher->initHeaderAction(); + $lg->enableNotes(true); + $lg->enableComments($this->lm->publicNotes(), false); + + if ($this->lm->hasRating() && !$this->offlineMode()) { + $lg->enableRating( + true, + $this->lng->txt("lm_rating"), + false, + array("ilcommonactiondispatchergui", "ilratinggui") + ); + } + + if (!$a_redraw) { + $this->tpl->setVariable("HEAD_ACTION", $lg->getHeaderAction($this->tpl)); + } else { + // we need to add onload code manually (rating, comments, etc.) + return $lg->getHeaderAction() . + $tpl->getOnLoadCodeForAsynch(); + } + } + + /** + * output notes of page + */ + public function ilLMNotes() + { + $ilAccess = $this->access; + $ilSetting = $this->settings; + + + // no notes in offline (export) mode + if ($this->offlineMode()) { + return; + } + + // output notes (on top) + + if (!$ilSetting->get("disable_notes")) { + $this->addHeaderAction(); + } + + // now output comments + + if ($ilSetting->get("disable_comments")) { + return; + } + + if (!$this->lm->publicNotes()) { + return; + } + + $next_class = $this->ctrl->getNextClass($this); + + include_once("Services/Notes/classes/class.ilNoteGUI.php"); + $pg_id = $this->getCurrentPageId(); + if ($pg_id == 0) { + return; + } + + $notes_gui = new ilNoteGUI($this->lm->getId(), $this->getCurrentPageId(), "pg"); + + if ($ilAccess->checkAccess("write", "", $_GET["ref_id"]) && + $ilSetting->get("comments_del_tutor", 1)) { + $notes_gui->enablePublicNotesDeletion(true); + } + + $this->ctrl->setParameter($this, "frame", $_GET["frame"]); + $this->ctrl->setParameter($this, "obj_id", $_GET["obj_id"]); + + $notes_gui->enablePrivateNotes(); + if ($this->lm->publicNotes()) { + $notes_gui->enablePublicNotes(); + } + + if ($next_class == "ilnotegui") { + $html = $this->ctrl->forwardCommand($notes_gui); + } else { + $html = $notes_gui->getNotesHTML(); + } + $this->tpl->setVariable("NOTES", $html); + } + + + /** + * locator + */ + public function ilLocator($a_std_templ_loaded = false) + { + global $DIC; + $ltiview = $DIC["lti"]; + $ilLocator = $this->locator; + $tree = $this->tree; + $ilCtrl = $this->ctrl; + + require_once("./Modules/LearningModule/classes/class.ilStructureObject.php"); + + if (empty($_GET["obj_id"])) { + $a_id = $this->lm_tree->getRootId(); + } else { + $a_id = $_GET["obj_id"]; + } + + if (!$a_std_templ_loaded) { + $this->tpl->addBlockFile("STATUSLINE", "statusline", "tpl.statusline.html"); + } + + if (!$this->lm->cleanFrames()) { + $frame_param = $_GET["frame"]; + $frame_target = ""; + } elseif (!$this->offlineMode()) { + $frame_param = ""; + $frame_target = ilFrameTargetInfo::_getFrame("MainContent"); + } else { + $frame_param = ""; + $frame_target = "_top"; + } + + if (!$this->offlineMode()) { + // LTI + if ($ltiview->isActive()) { + // Do nothing, its complicated... + } else { + $ilLocator->addItem("...", ""); + + $par_id = $tree->getParentId($_GET["ref_id"]); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $par_id); + $ilLocator->addItem( + ilObject::_lookupTitle(ilObject::_lookupObjId($par_id)), + $ilCtrl->getLinkTargetByClass("ilrepositorygui", "frameset"), + ilFrameTargetInfo::_getFrame("MainContent"), + $par_id + ); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + } + } else { + $ilLocator->setOffline(true); + } + + if ($this->lm_tree->isInTree($a_id)) { + $path = $this->lm_tree->getPathFull($a_id); + + foreach ($path as $key => $row) { + if ($row["type"] != "pg") { + if ($row["child"] != $this->lm_tree->getRootId()) { + $ilLocator->addItem( + ilUtil::shortenText( + ilStructureObject::_getPresentationTitle( + $row["child"], + IL_CHAPTER_TITLE, + $this->lm->isActiveNumbering(), + $this->lm_set->get("time_scheduled_page_activation"), + false, + 0, + $this->lang + ), + 50, + true + ), + $this->getLink($_GET["ref_id"], "layout", $row["child"], $frame_param, "StructureObject"), + $frame_target + ); + } else { + $ilLocator->addItem( + ilUtil::shortenText($this->getLMPresentationTitle(), 50, true), + $this->getLink($_GET["ref_id"], "layout", "", $frame_param), + $frame_target, + $_GET["ref_id"] + ); + } + } + } + } else { // lonely page + $ilLocator->addItem( + $this->getLMPresentationTitle(), + $this->getLink($_GET["ref_id"], "layout", "", $_GET["frame"]) + ); + + require_once("./Modules/LearningModule/classes/class.ilLMObjectFactory.php"); + $lm_obj = ilLMObjectFactory::getInstance($this->lm, $a_id); + + $ilLocator->addItem( + $lm_obj->getTitle(), + $this->getLink($_GET["ref_id"], "layout", $a_id, $frame_param), + $frame_target + ); + } + + if (DEBUG) { + $debug = "DEBUG: " . $this->type . "::" . $this->id . "::" . $_GET["cmd"] . "
"; + } + + //$prop_name = $this->objDefinition->getPropertyName($_GET["cmd"],$this->type); + + + $this->tpl->setLocator(); + } + + /** + * Get the current page id + * + * @return bool|int current page id + */ + public function getCurrentPageId() + { + $ilUser = $this->user; + + if (!$this->offlineMode() && $this->current_page_id !== false) { + return $this->current_page_id; + } + + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + + $this->chapter_has_no_active_page = false; + $this->deactivated_page = false; + + // determine object id + if (empty($_GET["obj_id"])) { + $obj_id = $this->lm_tree->getRootId(); + } else { + $obj_id = $_GET["obj_id"]; + $active = ilLMPage::_lookupActive( + $obj_id, + $this->lm->getType(), + $this->lm_set->get("time_scheduled_page_activation") + ); + + if (!$active && + ilLMPageObject::_lookupType($obj_id) == "pg") { + $this->deactivated_page = true; + } + } + + // obj_id not in tree -> it is a unassigned page -> return page id + if (!$this->lm_tree->isInTree($obj_id)) { + return $obj_id; + } + + $curr_node = $this->lm_tree->getNodeData($obj_id); + + $active = ilLMPage::_lookupActive( + $obj_id, + $this->lm->getType(), + $this->lm_set->get("time_scheduled_page_activation") + ); + + if ($curr_node["type"] == "pg" && + $active) { // page in tree -> return page id + $page_id = $curr_node["obj_id"]; + } else { // no page -> search for next page and return its id + $succ_node = true; + $active = false; + $page_id = $obj_id; + while ($succ_node && !$active) { + $succ_node = $this->lm_tree->fetchSuccessorNode($page_id, "pg"); + $page_id = $succ_node["obj_id"]; + $active = ilLMPage::_lookupActive( + $page_id, + $this->lm->getType(), + $this->lm_set->get("time_scheduled_page_activation") + ); + } + + if ($succ_node["type"] != "pg") { + $this->chapter_has_no_active_page = true; + return 0; + } + + // if public access get first public page in chapter + if ($ilUser->getId() == ANONYMOUS_USER_ID && + $this->lm_gui->object->getPublicAccessMode() == 'selected') { + $public = ilLMObject::_isPagePublic($page_id); + + while ($public === false && $page_id > 0) { + $succ_node = $this->lm_tree->fetchSuccessorNode($page_id, 'pg'); + $page_id = $succ_node['obj_id']; + $public = ilLMObject::_isPagePublic($page_id); + } + } + + // check whether page found is within "clicked" chapter + if ($this->lm_tree->isInTree($page_id)) { + $path = $this->lm_tree->getPathId($page_id); + if (!in_array($_GET["obj_id"], $path)) { + $this->chapter_has_no_active_page = true; + } + } + } + + $this->current_page_id = $page_id; + return $page_id; + } + + public function ilCitation() + { + $page_id = $this->getCurrentPageId(); + $this->tpl = new ilTemplate("tpl.page.html", true, true, true); + $this->ilLocator(); + $this->tpl->setVariable("MENU", $this->lm_gui->setilCitationMenu()); + + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + + $this->pg_obj = $this->getLMPage($page_id); + $xml = $this->pg_obj->getXMLContent(); + $this->lm_gui->showCitation($xml); + $this->tpl->show(); + } + + + public function getLayoutLinkTargets() + { + if (!is_object($this->layout_doc)) { + return array(); + } + + $xpc = xpath_new_context($this->layout_doc); + + $path = "/ilLayout/ilLinkTargets/LinkTarget"; + $res = xpath_eval($xpc, $path); + $targets = array(); + for ($i = 0; $i < count($res->nodeset); $i++) { + $type = $res->nodeset[$i]->get_attribute("Type"); + $frame = $res->nodeset[$i]->get_attribute("Frame"); + $onclick = $res->nodeset[$i]->get_attribute("OnClick"); + $targets[$type] = array("Type" => $type, "Frame" => $frame, "OnClick" => $onclick); + } + + return $targets; + } + + /** + * process content tag + * + * @param $a_page_node page node + * @param int $a_page_id header / footer page id + * @return string + */ + public function ilPage(&$a_page_node, $a_page_id = 0) + { + $access = $this->access; + + $ilUser = $this->user; + $ilHelp = $this->help; + + + $ilHelp = $this->help; + $ilHelp->setScreenIdComponent("lm"); + $ilHelp->setScreenId("content"); + $ilHelp->setSubScreenId("content"); + + $this->fill_on_load_code = true; + + + // check page id + $requested_page_lm = ilLMPage::lookupParentId($this->getCurrentPageId(), "lm"); + if ($requested_page_lm != $this->lm->getId()) { + if ($_REQUEST["frame"] == "") { + $this->showNoPageAccess(); + return ""; + } else { + $read_access = false; + foreach (ilObject::_getAllReferences($requested_page_lm) as $ref_id) { + if ($access->checkAccess("read", "", $ref_id)) { + $read_access = true; + } + } + if (!$read_access) { + $this->showNoPageAccess(); + return ""; + } + } + } + + // check if page is (not) visible in public area + if ($ilUser->getId() == ANONYMOUS_USER_ID && + $this->lm_gui->object->getPublicAccessMode() == 'selected') { + $public = ilLMObject::_isPagePublic($this->getCurrentPageId()); + + if (!$public) { + return $this->showNoPublicAccess($this->getCurrentPageId()); + } + } + + if (!ilObjContentObject::_checkPreconditionsOfPage($this->lm->getRefId(), $this->lm->getId(), $this->getCurrentPageId())) { + return $this->showPreconditionsOfPage($this->getCurrentPageId()); + } + + // if navigation is restricted based on correct answered questions + // check if we have preceeding pages including unsanswered/incorrect answered questions + if (!$this->offlineMode()) { + if ($this->lm->getRestrictForwardNavigation()) { + if ($this->getTracker()->hasPredIncorrectAnswers($this->getCurrentPageId())) { + $this->showNavRestrictionDueToQuestions(); + return; + } + } + } + + + require_once("./Modules/LearningModule/classes/class.ilLMPageGUI.php"); + require_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); + + // page id is e.g. > 0 when footer or header page is processed + if ($a_page_id == 0) { + $page_id = $this->getCurrentPageId(); + //echo ":".$page_id.":"; + // highlighting? + + if ($_GET["srcstring"] != "" && !$this->offlineMode()) { + include_once './Services/Search/classes/class.ilUserSearchCache.php'; + $cache = ilUserSearchCache::_getInstance($ilUser->getId()); + $cache->switchSearchType(ilUserSearchCache::LAST_QUERY); + $search_string = $cache->getQuery(); + + // advanced search? + if (is_array($search_string)) { + $search_string = $search_string["lom_content"]; + } + + include_once("./Services/UIComponent/TextHighlighter/classes/class.ilTextHighlighterGUI.php"); + include_once("./Services/Search/classes/class.ilQueryParser.php"); + $p = new ilQueryParser($search_string); + $p->parse(); + + $words = $p->getQuotedWords(); + if (is_array($words)) { + foreach ($words as $w) { + ilTextHighlighterGUI::highlight("ilLMPageContent", $w, $this->tpl); + } + } + + $this->fill_on_load_code = true; + } + } else { + $page_id = $a_page_id; + } + + // content style + $this->tpl->setCurrentBlock("ContentStyle"); + if (!$this->offlineMode()) { + $this->tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath($this->lm->getStyleSheetId()) + ); + } else { + $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", "content_style/content.css"); + } + $this->tpl->parseCurrentBlock(); + + // no active page found in chapter + if ($this->chapter_has_no_active_page && + ilLMObject::_lookupType($_GET["obj_id"]) == "st") { + $mtpl = new ilTemplate( + "tpl.no_content_message.html", + true, + true, + "Modules/LearningModule" + ); + $mtpl->setVariable("MESSAGE", $this->lng->txt("cont_no_page_in_chapter")); + //$mtpl->setVariable("SRC_ICON", ilUtil::getImagePath("icon_st.svg", + // false, "output", $this->offlineMode())); + $mtpl->setVariable( + "ITEM_TITLE", + ilLMObject::_lookupTitle($_GET["obj_id"]) + ); + $this->tpl->setVariable("PAGE_CONTENT", $mtpl->get()); + return $mtpl->get(); + } + + // current page is deactivated + if ($this->deactivated_page) { + $mtpl = new ilTemplate( + "tpl.no_content_message.html", + true, + true, + "Modules/LearningModule" + ); + $m = $this->lng->txt("cont_page_currently_deactivated"); + $act_data = ilLMPage::_lookupActivationData((int) $_GET["obj_id"], $this->lm->getType()); + if ($act_data["show_activation_info"] && + (ilUtil::now() < $act_data["activation_start"])) { + $m.= "

" . 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 = '
' . + $rating_gui->getHtml(true, true, "il.LearningModule.saveRating(%rating%);") . + "
"; + } + + $this->tpl->setVariable("PAGE_CONTENT", $rating . $head . $focus_mess . $ret . $foot); + //echo htmlentities("-".$ret."-"); + return $head . $focus_mess . $ret . $foot; + } + + public function updatePageRating() + { + $ilUser = $this->user; + + $pg_id = $_GET["pgid"]; + if (!$this->ctrl->isAsynch() || !$pg_id) { + exit(); + } + + include_once './Services/Rating/classes/class.ilRating.php'; + $rating = (int) $_POST["rating"]; + if ($rating) { + ilRating::writeRatingForUserAndObject( + $this->lm->getId(), + "lm", + $pg_id, + "lm", + $ilUser->getId(), + $_POST["rating"] + ); + } else { + ilRating::resetRatingForUserAndObject( + $this->lm->getId(), + "lm", + $pg_id, + "lm", + $ilUser->getId() + ); + } + + include_once './Services/Rating/classes/class.ilRatingGUI.php'; + $rating = new ilRatingGUI(); + $rating->setObject($this->lm->getId(), "lm", $pg_id, "lm", $ilUser->getId()); + $rating->setYourRatingText($this->lng->txt("lm_rate_page")); + + echo $rating->getHtml(true, true, "il.LearningModule.saveRating(%rating%);"); + + echo $this->tpl->getOnLoadCodeForAsynch(); + exit(); + } + + /** + * Basic page gui initialisation + * + * @param + * @return + */ + public function basicPageGuiInit($a_page_gui) + { + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $a_page_gui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId( + $this->lm->getStyleSheetId(), + "lm" + )); + if (!$this->offlineMode()) { + $a_page_gui->setOutputMode("presentation"); + $this->fill_on_load_code = true; + } else { + $a_page_gui->setOutputMode("offline"); + $a_page_gui->setOfflineDirectory($this->getOfflineDirectory()); + $this->fill_on_load_code = false; + } + if (!$this->offlineMode()) { + $this->ctrl->setParameter($this, "obj_id", $this->getCurrentPageId()); // see #22403 + } + $a_page_gui->setFileDownloadLink($this->getLink($_GET["ref_id"], "downloadFile")); + if (!$this->offlineMode()) { + $this->ctrl->setParameter($this, "obj_id", $_GET["obj_id"]); + } + $a_page_gui->setFullscreenLink($this->getLink($_GET["ref_id"], "fullscreen")); + } + + /** + * show preconditions of the page + */ + public function showPreconditionsOfPage() + { + $conds = ilObjContentObject::_getMissingPreconditionsOfPage($this->lm->getRefId(), $this->lm->getId(), $this->getCurrentPageId()); + $topchap = ilObjContentObject::_getMissingPreconditionsTopChapter($this->lm->getRefId(), $this->lm->getId(), $this->getCurrentPageId()); + + $page_id = $this->getCurrentPageId(); + + // content style + $this->tpl->setCurrentBlock("ContentStyle"); + if (!$this->offlineMode()) { + $this->tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath($this->lm->getStyleSheetId()) + ); + } else { + $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", "content_style/content.css"); + } + $this->tpl->parseCurrentBlock(); + + $this->tpl->addBlockFile("PAGE_CONTENT", "pg_content", "tpl.page_preconditions.html", true); + + // list all missing preconditions + include_once("./Services/Repository/classes/class.ilRepositoryExplorer.php"); + foreach ($conds as $cond) { + include_once("./Services/Link/classes/class.ilLink.php"); + $obj_link = ilLink::_getLink($cond["trigger_ref_id"]); + $this->tpl->setCurrentBlock("condition"); + $this->tpl->setVariable("VAL_ITEM", ilObject::_lookupTitle($cond["trigger_obj_id"])); + $this->tpl->setVariable("LINK_ITEM", $obj_link); + if ($cond["operator"] == "passed") { + $cond_str = $this->lng->txt("passed"); + } else { + $cond_str = $this->lng->txt("condition_" . $cond["operator"]); + } + $this->tpl->setVariable("VAL_CONDITION", $cond_str . " " . $cond["value"]); + $this->tpl->parseCurrentBlock(); + } + $this->tpl->setCurrentBlock("pg_content"); + + $this->tpl->setVariable( + "TXT_MISSING_PRECONDITIONS", + sprintf( + $this->lng->txt("cont_missing_preconditions"), + ilLMObject::_lookupTitle($topchap) + ) + ); + $this->tpl->setVariable("TXT_ITEM", $this->lng->txt("object")); + $this->tpl->setVariable("TXT_CONDITION", $this->lng->txt("condition")); + + // output skip chapter link + $parent = $this->lm_tree->getParentId($topchap); + $childs = $this->lm_tree->getChildsByType($parent, "st"); + $next = ""; + $j=-2; + $i=1; + foreach ($childs as $child) { + if ($child["child"] == $topchap) { + $j = $i; + } + if ($i++ == ($j+1)) { + $succ_node = $this->lm_tree->fetchSuccessorNode($child["child"], "pg"); + } + } + if ($succ_node != "") { + $framestr = (!empty($_GET["frame"])) + ? "frame=" . $_GET["frame"] . "&" + : ""; + + $showViewInFrameset = true; + $link = "
getLink($this->lm->getRefId(), "layout", $succ_node["obj_id"], $_GET["frame"]) . + "\">" . $this->lng->txt("cont_skip_chapter") . ""; + $this->tpl->setVariable("LINK_SKIP_CHAPTER", $link); + } + + $this->tpl->parseCurrentBlock(); + } + + /** + * get xml for links + */ + public function getLinkXML($a_int_links, $a_layoutframes) + { + $ilCtrl = $this->ctrl; + + // Determine whether the view of a learning resource should + // be shown in the frameset of ilias, or in a separate window. + $showViewInFrameset = true; + + if ($a_layoutframes == "") { + $a_layoutframes = array(); + } + $link_info = ""; + foreach ($a_int_links as $int_link) { + $target = $int_link["Target"]; + if (substr($target, 0, 4) == "il__") { + $target_arr = explode("_", $target); + $target_id = $target_arr[count($target_arr) - 1]; + $type = $int_link["Type"]; + $targetframe = ($int_link["TargetFrame"] != "") + ? $int_link["TargetFrame"] + : "None"; + + // anchor + $anc = $anc_add = ""; + if ($int_link["Anchor"] != "") { + $anc = $int_link["Anchor"]; + $anc_add = "_" . rawurlencode($int_link["Anchor"]); + } + $lcontent = ""; + switch ($type) { + case "PageObject": + case "StructureObject": + $lm_id = ilLMObject::_lookupContObjID($target_id); + if ($lm_id == $this->lm->getId() || + ($targetframe != "None" && $targetframe != "New")) { + $ltarget = $a_layoutframes[$targetframe]["Frame"]; + //$nframe = ($ltarget == "") + // ? $_GET["frame"] + // : $ltarget; + $nframe = ($ltarget == "") + ? "" + : $ltarget; + if ($ltarget == "") { + if ($showViewInFrameset) { + $ltarget="_parent"; + } else { + $ltarget="_top"; + } + } + // scorm always in 1window view and link target + // is always same frame + if ($this->getExportFormat() == "scorm" && + $this->offlineMode()) { + $ltarget = ""; + } + $href = + $this->getLink( + $_GET["ref_id"], + "layout", + $target_id, + $nframe, + $type, + "append", + $anc + ); + if ($lm_id == "") { + $href = ""; + } + } else { + if (!$this->offlineMode()) { + if ($type == "PageObject") { + $href = "./goto.php?target=pg_" . $target_id . $anc_add; + } else { + $href = "./goto.php?target=st_" . $target_id; + } + } else { + if ($type == "PageObject") { + $href = ILIAS_HTTP_PATH . "/goto.php?target=pg_" . $target_id . $anc_add . "&client_id=" . CLIENT_ID; + } else { + $href = ILIAS_HTTP_PATH . "/goto.php?target=st_" . $target_id . "&client_id=" . CLIENT_ID; + } + } + if ($targetframe != "New") { + $ltarget = ilFrameTargetInfo::_getFrame("MainContent"); + } else { + $ltarget = "_blank"; + } + } + break; + + case "GlossaryItem": + if ($targetframe == "None") { + $targetframe = "Glossary"; + } + $ltarget = $a_layoutframes[$targetframe]["Frame"]; + $nframe = ($ltarget == "") + ? $_GET["frame"] + : $ltarget; + $href = + $this->getLink($_GET["ref_id"], $a_cmd = "glossary", $target_id, $nframe, $type); + break; + + case "MediaObject": + $ltarget = $a_layoutframes[$targetframe]["Frame"]; + $nframe = ($ltarget == "") + ? $_GET["frame"] + : $ltarget; + $href = + $this->getLink($_GET["ref_id"], $a_cmd = "media", $target_id, $nframe, $type); + break; + + case "RepositoryItem": + $obj_type = ilObject::_lookupType($target_id, true); + $obj_id = ilObject::_lookupObjId($target_id); + if (!$this->offlineMode()) { + $href = "./goto.php?target=" . $obj_type . "_" . $target_id; + } else { + $href = ILIAS_HTTP_PATH . "/goto.php?target=" . $obj_type . "_" . $target_id . "&client_id=" . CLIENT_ID; + } + $ltarget = ilFrameTargetInfo::_getFrame("MainContent"); + break; + + case "WikiPage": + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + $href = ilWikiPage::getGotoForWikiPageTarget($target_id); + break; + + case "File": + if (!$this->offlineMode()) { + $ilCtrl->setParameter($this, "obj_id", $this->getCurrentPageId()); + $ilCtrl->setParameter($this, "file_id", "il__file_" . $target_id); + $href = $ilCtrl->getLinkTarget($this, "downloadFile"); + $ilCtrl->setParameter($this, "file_id", ""); + $ilCtrl->setParameter($this, "obj_id", $_GET["obj_id"]); + } + break; + + case "User": + $obj_type = ilObject::_lookupType($target_id); + if ($obj_type == "usr") { + include_once("./Services/User/classes/class.ilUserUtil.php"); + $back = $this->ctrl->getLinkTarget($this, "layout"); + //var_dump($back); exit; + $this->ctrl->setParameterByClass("ilpublicuserprofilegui", "user_id", $target_id); + $this->ctrl->setParameterByClass( + "ilpublicuserprofilegui", + "back_url", + rawurlencode($back) + ); + $href = ""; + include_once("./Services/User/classes/class.ilUserUtil.php"); + if (ilUserUtil::hasPublicProfile($target_id)) { + $href = $this->ctrl->getLinkTargetByClass("ilpublicuserprofilegui", "getHTML"); + } + $this->ctrl->setParameterByClass("ilpublicuserprofilegui", "user_id", ""); + $lcontent = ilUserUtil::getNamePresentation($target_id, false, false); + } + break; + + } + + $anc_par = 'Anchor="' . $anc . '"'; + + if ($href != "") { + $link_info .= ""; + } + + // set equal link info for glossary links of target "None" and "Glossary" + /* + if ($targetframe=="None" && $type=="GlossaryItem") + { + $link_info.=""; + }*/ + } + } + $link_info.= ""; + return $link_info; + } + + /** + * Get XMl for Link Targets + */ + public function getLinkTargetsXML() + { + $link_info = ""; + foreach ($this->getLayoutLinkTargets() as $k => $t) { + $link_info.=""; + } + $link_info.= ""; + return $link_info; + } + + /** + * show glossary term + */ + public function ilGlossary() + { + $ilCtrl = $this->ctrl; + + require_once("./Modules/Glossary/classes/class.ilGlossaryTermGUI.php"); + $term_gui = new ilGlossaryTermGUI($_GET["obj_id"]); + + // content style + $this->tpl->setCurrentBlock("ContentStyle"); + if (!$this->offlineMode()) { + $this->tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath($this->lm->getStyleSheetId()) + ); + } else { + $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", "content_style/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(); + + $int_links = $term_gui->getInternalLinks(); + $link_xml = $this->getLinkXML($int_links, $this->getLayoutLinkTargets()); + $link_xml.= $this->getLinkTargetsXML(); + $term_gui->setLinkXML($link_xml); + + $term_gui->setOfflineDirectory($this->getOfflineDirectory()); + if (!$this->offlineMode()) { + $ilCtrl->setParameter($this, "pg_type", "glo"); + } + $term_gui->output($this->offlineMode(), $this->tpl); + + + + if (!$this->offlineMode()) { + $ilCtrl->setParameter($this, "pg_type", ""); + } + } + + /** + * output media + */ + public function ilMedia() + { + $ilUser = $this->user; + + $this->tpl->setCurrentBlock("ContentStyle"); + if (!$this->offlineMode()) { + $this->tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath($this->lm->getStyleSheetId()) + ); + } else { + $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", "content_style/content.css"); + } + $this->tpl->parseCurrentBlock(); + + $this->renderPageTitle(); + + // set style sheets + if (!$this->offlineMode()) { + $this->tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); + } else { + $style_name = $ilUser->getPref("style") . ".css"; + ; + $this->tpl->setVariable("LOCATION_STYLESHEET", "./style/" . $style_name); + } + + $this->tpl->setCurrentBlock("ilMedia"); + + //$int_links = $page_object->getInternalLinks(); + $med_links = ilMediaItem::_getMapAreasIntLinks($_GET["mob_id"]); + $link_xml = $this->getLinkXML($med_links, $this->getLayoutLinkTargets()); + $link_xml.= $this->getLinkTargetsXML(); + //echo "

".htmlentities($link_xml); + require_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $media_obj = new ilObjMediaObject($_GET["mob_id"]); + if (!empty($_GET["pg_id"])) { + require_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + $pg_obj = $this->getLMPage($_GET["pg_id"]); + $pg_obj->buildDom(); + + $xml = ""; + // todo: we get always the first alias now (problem if mob is used multiple + // times in page) + $xml.= $pg_obj->getMediaAliasElement($_GET["mob_id"]); + $xml.= $media_obj->getXML(IL_MODE_OUTPUT); + $xml.= $link_xml; + $xml.=""; + } else { + $xml = ""; + // todo: we get always the first alias now (problem if mob is used multiple + // times in page) + $xml.= $media_obj->getXML(IL_MODE_ALIAS); + $xml.= $media_obj->getXML(IL_MODE_OUTPUT); + $xml.= $link_xml; + $xml.=""; + } + + //echo htmlentities($xml); exit; + + // todo: utf-header should be set globally + //header('Content-type: text/html; charset=UTF-8'); + + $xsl = file_get_contents("./Services/COPage/xsl/page.xsl"); + $args = array( '/_xml' => $xml, '/_xsl' => $xsl ); + $xh = xslt_create(); + + //echo "XML:".htmlentities($xml); + // determine target frames for internal links + //$pg_frame = $_GET["frame"]; + if (!$this->offlineMode()) { + $wb_path = ilUtil::getWebspaceDir("output") . "/"; + } else { + $wb_path = ""; + } + + $mode = ($_GET["cmd"] == "fullscreen") + ? "fullscreen" + : "media"; + $enlarge_path = ilUtil::getImagePath("enlarge.svg", false, "output", $this->offlineMode()); + $fullscreen_link = + $this->getLink($this->lm->getRefId(), "fullscreen"); + $params = array('mode' => $mode, 'enlarge_path' => $enlarge_path, + 'link_params' => "ref_id=" . $this->lm->getRefId(),'fullscreen_link' => $fullscreen_link, + 'ref_id' => $this->lm->getRefId(), 'pg_frame' => $pg_frame, 'webspace_path' => $wb_path); + $output = xslt_process($xh, "arg:/_xml", "arg:/_xsl", null, $args, $params); + echo xslt_error($xh); + xslt_free($xh); + + // unmask user html + $this->tpl->setVariable("MEDIA_CONTENT", $output); + + // add js + include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); + ilObjMediaObjectGUI::includePresentationJS($this->tpl); + } + + /** + * Puts JS into template + */ + public function ilJavaScript($a_inline = "", $a_file = "", $a_location = "") + { + if ($a_inline != "") { + $js_tpl = new ilTemplate($a_inline, true, false, $a_location); + $js = $js_tpl->get(); + $this->tpl->setVariable("INLINE_JS", $js); + } + } + + /** + * Get successor page + * + * @param + * @return + */ + public function getSuccessorPage() + { + $ilUser = $this->user; + + $page_id = $this->getCurrentPageId(); + + if (empty($page_id)) { + return 0; + } + + // determine successor page_id + $found = false; + + // empty chapter + if ($this->chapter_has_no_active_page && + ilLMObject::_lookupType($_GET["obj_id"]) == "st") { + $c_id = $_GET["obj_id"]; + } else { + if ($this->deactivated_page) { + $c_id = $_GET["obj_id"]; + } else { + $c_id = $page_id; + } + } + while (!$found) { + $succ_node = $this->lm_tree->fetchSuccessorNode($c_id, "pg"); + $c_id = $succ_node["obj_id"]; + + $active = ilLMPage::_lookupActive( + $c_id, + $this->lm->getType(), + $this->lm_set->get("time_scheduled_page_activation") + ); + + if ($succ_node["obj_id"] > 0 && + $ilUser->getId() == ANONYMOUS_USER_ID && + ($this->lm->getPublicAccessMode() == "selected" && + !ilLMObject::_isPagePublic($succ_node["obj_id"]))) { + $found = false; + } elseif ($succ_node["obj_id"] > 0 && !$active) { + // look, whether activation data should be shown + $act_data = ilLMPage::_lookupActivationData((int) $succ_node["obj_id"], $this->lm->getType()); + if ($act_data["show_activation_info"] && + (ilUtil::now() < $act_data["activation_start"])) { + $found = true; + } else { + $found = false; + } + } else { + $found = true; + } + } + + if ($found) { + return $succ_node["obj_id"]; + } + return 0; + } + + + /** + * inserts sequential learning module navigation + * at template variable LMNAVIGATION_CONTENT + */ + public function ilLMNavigation() + { + $ilUser = $this->user; + + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + + include_once("./Services/Accessibility/classes/class.ilAccessKeyGUI.php"); + + $page_id = $this->getCurrentPageId(); + + if (empty($page_id)) { + return; + } + + // process navigation for free page + if (!$this->lm_tree->isInTree($page_id)) { + if ($this->offlineMode() || $_GET["back_pg"] == "") { + return; + } + $limpos = strpos($_GET["back_pg"], ":"); + if ($limpos > 0) { + $back_pg = substr($_GET["back_pg"], 0, $limpos); + } else { + $back_pg = $_GET["back_pg"]; + } + if (!$this->lm->cleanFrames()) { + $back_href = + $this->getLink( + $this->lm->getRefId(), + "layout", + $back_pg, + $_GET["frame"], + "", + "reduce" + ); + $back_target = ""; + } else { + $back_href = + $this->getLink( + $this->lm->getRefId(), + "layout", + $back_pg, + "", + "", + "reduce" + ); + $back_target = 'target="' . ilFrameTargetInfo::_getFrame("MainContent") . '" '; + } + $back_img = + ilUtil::getImagePath("nav_arr2_L.png", false, "output", $this->offlineMode()); + $this->tpl->setCurrentBlock("ilLMNavigation_Prev"); + $this->tpl->setVariable("IMG_PREV", $back_img); + $this->tpl->setVariable("HREF_PREV", $back_href); + $this->tpl->setVariable("FRAME_PREV", $back_target); + $this->tpl->setVariable("TXT_PREV", $this->lng->txt("back")); + $this->tpl->setVariable("ALT_PREV", $this->lng->txt("back")); + $this->tpl->setVariable( + "PREV_ACC_KEY", + ilAccessKeyGUI::getAttribute(ilAccessKey::PREVIOUS) + ); + $this->tpl->setVariable("SPACER_PREV", $this->offlineMode() + ? "images/spacer.png" + : ilUtil::getImagePath("spacer.png")); + $this->tpl->parseCurrentBlock(); + $this->tpl->setCurrentBlock("ilLMNavigation_Prev2"); + $this->tpl->setVariable("IMG_PREV2", $back_img); + $this->tpl->setVariable("HREF_PREV2", $back_href); + $this->tpl->setVariable("FRAME_PREV2", $back_target); + $this->tpl->setVariable("TXT_PREV2", $this->lng->txt("back")); + $this->tpl->setVariable("ALT_PREV2", $this->lng->txt("back")); + $this->tpl->setVariable("SPACER_PREV2", $this->offlineMode() + ? "images/spacer.png" + : ilUtil::getImagePath("spacer.png")); + $this->tpl->parseCurrentBlock(); + return; + } + + // determine successor page_id + $found = false; + + // empty chapter + if ($this->chapter_has_no_active_page && + ilLMObject::_lookupType($_GET["obj_id"]) == "st") { + $c_id = $_GET["obj_id"]; + } else { + if ($this->deactivated_page) { + $c_id = $_GET["obj_id"]; + } else { + $c_id = $page_id; + } + } + while (!$found) { + $succ_node = $this->lm_tree->fetchSuccessorNode($c_id, "pg"); + $c_id = $succ_node["obj_id"]; + + $active = ilLMPage::_lookupActive( + $c_id, + $this->lm->getType(), + $this->lm_set->get("time_scheduled_page_activation") + ); + + if ($succ_node["obj_id"] > 0 && + $ilUser->getId() == ANONYMOUS_USER_ID && + ($this->lm->getPublicAccessMode() == "selected" && + !ilLMObject::_isPagePublic($succ_node["obj_id"]))) { + $found = false; + } elseif ($succ_node["obj_id"] > 0 && !$active) { + // look, whether activation data should be shown + $act_data = ilLMPage::_lookupActivationData((int) $succ_node["obj_id"], $this->lm->getType()); + if ($act_data["show_activation_info"] && + (ilUtil::now() < $act_data["activation_start"])) { + $found = true; + } else { + $found = false; + } + } else { + $found = true; + } + } + + $succ_str = ($succ_node !== false) + ? " -> " . $succ_node["obj_id"] . "_" . $succ_node["type"] + : ""; + + // determine predecessor page id + $found = false; + if ($this->deactivated_page) { + $c_id = $_GET["obj_id"]; + } else { + $c_id = $page_id; + } + while (!$found) { + $pre_node = $this->lm_tree->fetchPredecessorNode($c_id, "pg"); + $c_id = $pre_node["obj_id"]; + $active = ilLMPage::_lookupActive( + $c_id, + $this->lm->getType(), + $this->lm_set->get("time_scheduled_page_activation") + ); + if ($pre_node["obj_id"] > 0 && + $ilUser->getId() == ANONYMOUS_USER_ID && + ($this->lm->getPublicAccessMode() == "selected" && + !ilLMObject::_isPagePublic($pre_node["obj_id"]))) { + $found = false; + } elseif ($pre_node["obj_id"] > 0 && !$active) { + // look, whether activation data should be shown + $act_data = ilLMPage::_lookupActivationData((int) $pre_node["obj_id"], $this->lm->getType()); + if ($act_data["show_activation_info"] && + (ilUtil::now() < $act_data["activation_start"])) { + $found = true; + } else { + $found = false; + } + } else { + $found = true; + } + } + + $pre_str = ($pre_node !== false) + ? $pre_node["obj_id"] . "_" . $pre_node["type"] . " -> " + : ""; + + // determine target frame + $framestr = (!empty($_GET["frame"])) + ? "frame=" . $_GET["frame"] . "&" + : ""; + + + // Determine whether the view of a learning resource should + // be shown in the frameset of ilias, or in a separate window. + $showViewInFrameset = true; + + if ($pre_node != "") { + // get presentation title + $prev_title = ilLMPageObject::_getPresentationTitle( + $pre_node["obj_id"], + $this->lm->getPageHeader(), + $this->lm->isActiveNumbering(), + $this->lm_set->get("time_scheduled_page_activation"), + false, + 0, + $this->lang, + true + ); + $prev_title = ilUtil::shortenText($prev_title, 50, true); + $prev_img = + ilUtil::getImagePath("nav_arr_L.png", false, "output", $this->offlineMode()); + + if (!$this->lm->cleanFrames()) { + $prev_href = + $this->getLink($this->lm->getRefId(), "layout", $pre_node["obj_id"], $_GET["frame"]); + $prev_target = ""; + } elseif ($showViewInFrameset && !$this->offlineMode()) { + $prev_href = + $this->getLink($this->lm->getRefId(), "layout", $pre_node["obj_id"]); + $prev_target = 'target="' . ilFrameTargetInfo::_getFrame("MainContent") . '" '; + } else { + $prev_href = + $this->getLink($this->lm->getRefId(), "layout", $pre_node["obj_id"]); + $prev_target = 'target="_top" '; + } + + if ($ilUser->getId() == ANONYMOUS_USER_ID && + ($this->lm->getPublicAccessMode() == 'selected' && !ilLMObject::_isPagePublic($pre_node["obj_id"]))) { + $output = $this->lng->txt("msg_page_not_public"); + } + + $this->tpl->setCurrentBlock("ilLMNavigation_Prev"); + $this->tpl->setVariable("IMG_PREV", $prev_img); + $this->tpl->setVariable("HREF_PREV", $prev_href); + $this->tpl->setVariable("FRAME_PREV", $prev_target); + $this->tpl->setVariable("TXT_PREV", $prev_title); + $this->tpl->setVariable("ALT_PREV", $this->lng->txt("previous")); + $this->tpl->setVariable("SPACER_PREV", $this->offlineMode() + ? "images/spacer.png" + : ilUtil::getImagePath("spacer.png")); + $this->tpl->setVariable( + "PREV_ACC_KEY", + ilAccessKeyGUI::getAttribute(ilAccessKey::PREVIOUS) + ); + $this->tpl->parseCurrentBlock(); + $this->tpl->setCurrentBlock("ilLMNavigation_Prev2"); + $this->tpl->setVariable("IMG_PREV2", $prev_img); + $this->tpl->setVariable("HREF_PREV2", $prev_href); + $this->tpl->setVariable("FRAME_PREV2", $prev_target); + $this->tpl->setVariable("TXT_PREV2", $prev_title); + $this->tpl->setVariable("ALT_PREV2", $this->lng->txt("previous")); + $this->tpl->setVariable("SPACER_PREV2", $this->offlineMode() + ? "images/spacer.png" + : ilUtil::getImagePath("spacer.png")); + $this->tpl->parseCurrentBlock(); + } + if ($succ_node != "") { + // get presentation title + $succ_title = ilLMPageObject::_getPresentationTitle( + $succ_node["obj_id"], + $this->lm->getPageHeader(), + $this->lm->isActiveNumbering(), + $this->lm_set->get("time_scheduled_page_activation"), + false, + 0, + $this->lang, + true + ); + $succ_title = ilUtil::shortenText($succ_title, 50, true); + $succ_img = + ilUtil::getImagePath("nav_arr_R.png", false, "output", $this->offlineMode()); + if (!$this->lm->cleanFrames()) { + $succ_href = + $this->getLink($this->lm->getRefId(), "layout", $succ_node["obj_id"], $_GET["frame"]); + $succ_target = ""; + } elseif ($showViewInFrameset && !$this->offlineMode()) { + $succ_href = + $this->getLink($this->lm->getRefId(), "layout", $succ_node["obj_id"]); + $succ_target = ' target="' . ilFrameTargetInfo::_getFrame("MainContent") . '" '; + } else { + $succ_href = + $this->getLink($this->lm->getRefId(), "layout", $succ_node["obj_id"]); + $succ_target = ' target="_top" '; + } + + if ($ilUser->getId() == ANONYMOUS_USER_ID && + ($this->lm->getPublicAccessMode() == 'selected' && !ilLMObject::_isPagePublic($pre_node["obj_id"]))) { + $output = $this->lng->txt("msg_page_not_public"); + } + + $this->tpl->setCurrentBlock("ilLMNavigation_Next"); + $this->tpl->setVariable("IMG_SUCC", $succ_img); + $this->tpl->setVariable("HREF_SUCC", $succ_href); + $this->tpl->setVariable("FRAME_SUCC", $succ_target); + $this->tpl->setVariable("TXT_SUCC", $succ_title); + $this->tpl->setVariable("ALT_SUCC", $this->lng->txt("next")); + $this->tpl->setVariable("SPACER_SUCC", $this->offlineMode() + ? "images/spacer.png" + : ilUtil::getImagePath("spacer.png")); + $this->tpl->setVariable( + "NEXT_ACC_KEY", + ilAccessKeyGUI::getAttribute(ilAccessKey::NEXT) + ); + $this->tpl->parseCurrentBlock(); + $this->tpl->setCurrentBlock("ilLMNavigation_Next2"); + $this->tpl->setVariable("IMG_SUCC2", $succ_img); + $this->tpl->setVariable("HREF_SUCC2", $succ_href); + $this->tpl->setVariable("FRAME_SUCC2", $succ_target); + $this->tpl->setVariable("TXT_SUCC2", $succ_title); + $this->tpl->setVariable("ALT_SUCC2", $this->lng->txt("next")); + $this->tpl->setVariable("SPACER_SUCC2", $this->offlineMode() + ? "images/spacer.png" + : ilUtil::getImagePath("spacer.png")); + $this->tpl->parseCurrentBlock(); + + // check if successor page is not restricted + if (!$this->offlineMode()) { + if ($this->lm->getRestrictForwardNavigation()) { + if ($this->getTracker()->hasPredIncorrectAnswers($succ_node["obj_id"])) { + $this->tpl->addOnLoadCode("$('.ilc_page_rnav_RightNavigation').addClass('ilNoDisplay');"); + } + } + } + } + } + + + public function processNodes(&$a_content, &$a_node) + { + $child_nodes = $a_node->child_nodes(); + foreach ($child_nodes as $child) { + if ($child->node_name() == "ilFrame") { + $attributes = $this->attrib2arr($child->attributes()); + // node is frameset, if it has cols or rows attribute + if ((!empty($attributes["rows"])) || (!empty($attrubtes["cols"]))) { + // if framset has name, another http request is necessary + // (html framesets don't have names, so we need a wrapper frame) + if (!empty($attributes["name"])) { + unset($attributes["template"]); + unset($attributes["template_location"]); + $attributes["src"] = + $this->getLink( + $this->lm->getRefId(), + "layout", + $_GET["obj_id"], + $attributes["name"], + "", + "keep", + "", + $_GET["srcstring"] + ); + $attributes["title"] = $this->lng->txt("cont_frame_" . $attributes["name"]); + $a_content .= $this->buildTag("", "frame", $attributes); + $this->frames[$attributes["name"]] = $attributes["name"]; + //echo "
processNodes:add1 ".$attributes["name"]; + } else { // ok, no name means that we can easily output the frameset tag + $a_content .= $this->buildTag("start", "frameset", $attributes); + $this->processNodes($a_content, $child); + $a_content .= $this->buildTag("end", "frameset"); + } + } else { // frame with + unset($attributes["template"]); + unset($attributes["template_location"]); + $attributes["src"] = + $this->getLink( + $this->lm->getRefId(), + "layout", + $_GET["obj_id"], + $attributes["name"], + "", + "keep", + "", + $_GET["srcstring"] + ); + $attributes["title"] = $this->lng->txt("cont_frame_" . $attributes["name"]); + if ($attributes["name"] == "toc") { + $attributes["src"].= "#" . $_GET["obj_id"]; + } else { + // Handle Anchors + if ($_GET["anchor"] != "") { + $attributes["src"].= "#" . rawurlencode($_GET["anchor"]); + } + } + $a_content .= $this->buildTag("", "frame", $attributes); + $this->frames[$attributes["name"]] = $attributes["name"]; + } + } + } + } + + /** + * generate a tag with given name and attributes + * + * @param string "start" | "end" | "" for starting or ending tag or complete tag + * @param string element/tag name + * @param array array of attributes + */ + public function buildTag($type, $name, $attr="") + { + $tag = "<"; + + if ($type == "end") { + $tag.= "/"; + } + + $tag.= $name; + + if (is_array($attr)) { + foreach ($attr as $k => $v) { + $tag .= " " . $k . "=\"$v\""; + } + } + + if ($type == "") { + $tag.= "/"; + } + + $tag.= ">\n"; + + return $tag; + } + + + /** + * table of contents + */ + public function showTableOfContents() + { + $ilUser = $this->user; + + if (!$this->lm->isActiveTOC() || !$this->lm->isActiveLMMenu()) { + return; + } + + //$this->tpl = new ilTemplate("tpl.lm_toc.html", true, true, true); + $this->tpl->setCurrentBlock("ContentStyle"); + if (!$this->offlineMode()) { + $this->tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath($this->lm->getStyleSheetId()) + ); + } else { + $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", "content_style/content.css"); + } + $this->tpl->parseCurrentBlock(); + + $this->renderPageTitle(); + + // set style sheets + if (!$this->offlineMode()) { + $this->tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); + } else { + $style_name = $ilUser->getPref("style") . ".css"; + ; + $this->tpl->setVariable("LOCATION_STYLESHEET", "./style/" . $style_name); + } + + //$this->tpl->addBlockFile("CONTENT", "content", "tpl.lm_toc.html", true); + //var_dump($GLOBALS["tpl"]); echo "

"; + //exit; + $this->tpl->getStandardTemplate(); + $this->ilLocator(true); + + $a_global_tabs = !$this->offlineMode(); + + $this->tpl->setVariable("TABS", $this->lm_gui->setilLMMenu( + $this->offlineMode() + , + $this->getExportFormat(), + "toc", + $a_global_tabs, + false, + 0, + $this->lang, + $this->export_all_languages + )); + + // set title header + $this->tpl->setVariable("TXT_TOC", $this->lng->txt("cont_toc")); + $this->tpl->setTitle($this->getLMPresentationTitle()); + $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_lm.svg")); + + include_once("./Modules/LearningModule/classes/class.ilLMTableOfContentsExplorerGUI.php"); + $exp = new ilLMTableOfContentsExplorerGUI($this, "showTableOfContents", $this, $this->lang, $this->export_all_languages); + $exp->setMainTemplate($this->tpl); + $exp->setTracker($this->getTracker()); + if (!$exp->handleCommand()) { + // determine highlighted and force open nodes + $page_id = $this->getCurrentPageId(); + if ($this->deactivated_page) { + $page_id = $_GET["obj_id"]; + } + + // highlight current node + if (!$this->offlineMode()) { + // empty chapter + if ($this->chapter_has_no_active_page && + ilLMObject::_lookupType($_GET["obj_id"]) == "st") { + $exp->setHighlightNode($_GET["obj_id"]); + } else { + if ($this->lm->getTOCMode() == "pages") { + if ($this->deactivated_page) { + $exp->setHighlightNode($_GET["obj_id"]); + } else { + $exp->setHighlightNode($page_id); + } + } else { + $exp->setHighlightNode($this->lm_tree->getParentId($page_id)); + } + } + } + if ($this->offlineMode()) { + $exp->setOfflineMode(true); + } + // var_dump($exp->getHTML()."_"); + $this->tpl->setVariable("ADM_CONTENT", $exp->getHTML()); + } + if ($this->offlineMode()) { + // reset standard css files + $this->tpl->resetJavascript(); + $this->tpl->resetCss(); + $this->tpl->setBodyClass("ilLMNoMenu"); + + include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); + foreach (ilObjContentObject::getSupplyingExportFiles() as $f) { + if ($f["type"] == "js") { + $this->tpl->addJavascript($f["target"]); + } + if ($f["type"] == "css") { + $this->tpl->addCSS($f["target"]); + } + } + $this->tpl->fillJavaScriptFiles(true); + $this->tpl->fillOnLoadCode(); + //var_dump(htmlentities($this->tpl->get())); exit; + return $this->tpl->get(); + } else { + $this->tpl->show(); + } + } + + + /** + * 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->outputInfoScreen(); + } /** - * calls export of digilib-object - * at this point other lm-objects can be exported - * - * @param - * @access public - * @return + * info screen call from inside learning module */ - function export() - { - } - - /** - * Get tracker - * - * @return ilLMTracker tracker instance - */ - function getTracker() - { - include_once("./Modules/LearningModule/classes/class.ilLMTracker.php"); - $tracker = ilLMTracker::getInstance($this->lm->getRefId()); - $tracker->setCurrentPage($this->getCurrentPageId()); - return $tracker; - } - - function attrib2arr($a_attributes) - { - $attr = array(); - if(!is_array($a_attributes)) - { - return $attr; - } - foreach ($a_attributes as $attribute) - { - $attr[$attribute->name()] = $attribute->value(); - } - return $attr; - } - - /** - * get frames of current frame set - */ - function getCurrentFrameSet() - { - return $this->frames; - } - - /** - * Determine layout - */ - function determineLayout() - { - if ($this->getExportFormat() == "scorm") - { - $layout = "1window"; - } - else - { - $layout = $this->lm->getLayout(); - if ($this->lm->getLayoutPerPage()) - { - $pg_id = $this->getCurrentPageId(); - if (!in_array($_GET["frame"], array("", "_blank")) && $_GET["from_page"] > 0) - { - $pg_id = (int) $_GET["from_page"]; - } - - // this is needed, e.g. lm is toc2win, page is 3window and media linked to media frame - if (in_array($_GET["cmd"], array("media", "glossary")) && $_GET["back_pg"] > 0) - { - $pg_id = (int) $_GET["back_pg"]; - } - - if ($pg_id > 0) - { - $lay = ilLMObject::lookupLayout($pg_id); - if ($lay != "") - { - $layout = $lay; - } - } - } - } - - return $layout; - } - - function resume() - { - $ilUser = $this->user; - - if ($ilUser->getId() != ANONYMOUS_USER_ID && $_GET["focus_id"] == "") - { - include_once("./Modules/LearningModule/classes/class.ilObjLearningModuleAccess.php"); - $last_accessed_page = ilObjLearningModuleAccess::_getLastAccessedPage((int)$_GET["ref_id"], $ilUser->getId()); - - // if last accessed page was final page do nothing, start over - if($last_accessed_page && - $last_accessed_page != $this->lm_tree->getLastActivePage()) - { - $_GET["obj_id"] = $last_accessed_page; - } - } - - $this->layout(); - } - - /** - * generates frame layout - */ - function layout($a_xml = "main.xml", $doShow = true) - { - global $DIC; - - $tpl = $this->tpl; - $ilSetting = $this->settings; - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - $layout = $this->determineLayout(); - - // xmldocfile is deprecated! Use domxml_open_file instead. - // But since using relative pathes with domxml under windows don't work, - // we need another solution: - $xmlfile = file_get_contents("./Modules/LearningModule/layouts/lm/".$layout."/".$a_xml); - - if (!$doc = domxml_open_mem($xmlfile)) - { - include_once("./Modules/LearningModule/exceptions/class.ilLMPresentationException.php"); - throw new ilLMPresentationException("ilLMPresentation: XML File invalid. Error reading ". - $layout."/".$a_xml."."); - } - $this->layout_doc = $doc; -//echo ":".htmlentities($xmlfile).":$layout:$a_xml:"; - - // get current frame node - $xpc = xpath_new_context($doc); - $path = (empty($_GET["frame"]) || ($_GET["frame"] == "_blank")) - ? "/ilLayout/ilFrame[1]" - : "//ilFrame[@name='".$_GET["frame"]."']"; - $result = xpath_eval($xpc, $path); - $found = $result->nodeset; - if (count($found) != 1) - { - include_once("./Modules/LearningModule/exceptions/class.ilLMPresentationException.php"); - throw new ilLMPresentationException("ilLMPresentation: XML File invalid. Found ".count($found)." nodes for ". - " path ".$path." in ".$layout."/".$a_xml.". LM Layout is ".$this->lm->getLayout()); - } - $node = $found[0]; - - // ProcessFrameset - // node is frameset, if it has cols or rows attribute - $attributes = $this->attrib2arr($node->attributes()); - - $this->frames = array(); - if((!empty($attributes["rows"])) || (!empty($attributes["cols"]))) - { - $content .= $this->buildTag("start", "frameset", $attributes); - //$this->frames = array(); - $this->processNodes($content, $node); - $content .= $this->buildTag("end", "frameset"); - $this->tpl = new ilTemplate("tpl.frameset.html", true, true, "Modules/LearningModule"); - $this->renderPageTitle(); - $this->tpl->setVariable("FS_CONTENT", $content); - if (!$doshow) - { - $content = $this->tpl->get(); - } - } - else // node is frame -> process the content tags - { - // ProcessContentTag - //if ((empty($attributes["template"]) || !empty($_GET["obj_type"]))) - if ((empty($attributes["template"]) || !empty($_GET["obj_type"])) - && ($_GET["frame"] != "_blank" || $_GET["obj_type"] != "MediaObject")) - { - // we got a variable content frame (can display different - // object types (PageObject, MediaObject, GlossarItem) - // and contains elements for them) - - // determine object type - if(empty($_GET["obj_type"])) - { - $obj_type = "PageObject"; - } - else - { - $obj_type = $_GET["obj_type"]; - } - - // get object specific node - $childs = $node->child_nodes(); - $found = false; - foreach($childs as $child) - { - if ($child->node_name() == $obj_type) - { - $found = true; - $attributes = $this->attrib2arr($child->attributes()); - $node = $child; -//echo "
2node:".$node->node_name(); - break; - } - } - if (!$found) - { - include_once("./Modules/LearningModule/exceptions/class.ilLMPresentationException.php"); - throw new ilLMPresentationException("ilLMPresentation: No template specified for frame '". - $_GET["frame"]."' and object type '".$obj_type."'."); - } - } - - // get template - $in_module = ($attributes["template_location"] == "module") - ? true - : false; - if ($in_module) - { - $this->tpl = new ilTemplate($attributes["template"], true, true, $in_module); - $this->tpl->setBodyClass(""); - } - else - { - $this->tpl = $tpl; - } - - // set style sheets - if (!$this->offlineMode()) - { - $this->tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); - } - else - { - $style_name = $ilUser->getPref("style").".css"; - $this->tpl->setVariable("LOCATION_STYLESHEET","./style/".$style_name); - } - - include_once("./Services/jQuery/classes/class.iljQueryUtil.php"); - - iljQueryUtil::initjQuery($this->tpl); - iljQueryUtil::initjQueryUI($this->tpl); - - include_once("./Services/UICore/classes/class.ilUIFramework.php"); - ilUIFramework::init($this->tpl); - - // to make e.g. advanced seletions lists work: - $GLOBALS["tpl"] = $this->tpl; - - $childs = $node->child_nodes(); - - foreach($childs as $child) - { - - $child_attr = $this->attrib2arr($child->attributes()); - - switch ($child->node_name()) - { - case "ilMainMenu": - $this->ilMainMenu(); - //$this->renderPageTitle(); - break; - - case "ilTOC": - $this->ilTOC($child_attr["target_frame"]); - break; - - case "ilPage": - $this->renderPageTitle(); - switch($this->lm->getType()) - { - case "lm": - unset($_SESSION["tr_id"]); - unset($_SESSION["bib_id"]); - unset($_SESSION["citation"]); - $content = $this->ilPage($child); - break; - } - break; - - case "ilGlossary": - $content = $this->ilGlossary($child); - break; - - case "ilLMNavigation": - $this->ilLMNavigation(); - break; - - case "ilMedia": - $this->ilMedia(); - break; - - case "ilLocator": - $this->ilLocator(); - break; - - case "ilJavaScript": - $this->ilJavaScript($child_attr["inline"], $child_attr["file"], - $child_attr["location"]); - break; - - case "ilLMMenu": - $this->ilLMMenu(); - break; - - case "ilLMHead": - $this->ilLMHead(); - break; - - case "ilLMSubMenu": - $this->ilLMSubMenu(); - break; - - case "ilLMNotes": - $this->ilLMNotes(); - break; - } - } - - // TODO: Very dirty hack to force the import of JavaScripts in learning content in the FAQ frame (e.g. if jsMath is in the content) - // Unfortunately there is no standardized way to do this somewhere else. Calling fillJavaScripts always in ilTemplate causes multiple additions of the the js files. - // 19.7.2014: outcommented, since fillJavaScriptFiles is called in the next blocks, and the - // following lines would add the js files two times -// if (strcmp($_GET["frame"], "topright") == 0) $this->tpl->fillJavaScriptFiles(); -// if (strcmp($_GET["frame"], "right") == 0) $this->tpl->fillJavaScriptFiles(); -// if (strcmp($_GET["frame"], "botright") == 0) $this->tpl->fillJavaScriptFiles(); - - if (!$this->offlineMode()) - { - include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); - ilAccordionGUI::addJavaScript(); - ilAccordionGUI::addCss(); - - - $this->tpl->addJavascript("./Modules/LearningModule/js/LearningModule.js"); - include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); - $close_call = "il.LearningModule.setCloseHTML('".ilGlyphGUI::get(ilGlyphGUI::CLOSE)."');"; - $this->tpl->addOnLoadCode($close_call); - - //$store->set("cf_".$this->lm->getId()); - - // handle initial content - if ($_GET["frame"] == "") - { - include_once("./Services/Authentication/classes/class.ilSessionIStorage.php"); - $store = new ilSessionIStorage("lm"); - $last_frame_url = $store->get("cf_".$this->lm->getId()); - if ($last_frame_url != "") - { - $this->tpl->addOnLoadCode("il.LearningModule.setLastFrameUrl('".$last_frame_url."', 'center_bottom');"); - } - - if (in_array($layout, array("toc2windyn"))) - { - $this->tpl->addOnLoadCode("il.LearningModule.setSaveUrl('". - $ilCtrl->getLinkTarget($this, "saveFrameUrl", "", false, false)."'); - il.LearningModule.openInitFrames(); - "); - } - $this->tpl->addOnLoadCode("il.LearningModule.setTocRefreshUrl('". - $ilCtrl->getLinkTarget($this, "refreshToc", "", false, false)."'); - "); - } - - // from main menu -// $this->tpl->addJavascript("./Services/JavaScript/js/Basic.js"); - $this->tpl->addJavascript("./Services/Navigation/js/ServiceNavigation.js"); - ilYuiUtil::initConnection($this->tpl); - $this->tpl->fillJavaScriptFiles(); - $this->tpl->fillScreenReaderFocus(); - - $this->tpl->fillCssFiles(); - } - else - { - // reset standard css files - $this->tpl->resetJavascript(); - $this->tpl->resetCss(); - $this->tpl->setBodyClass("ilLMNoMenu"); - - include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); - foreach (ilObjContentObject::getSupplyingExportFiles() as $f) - { - if ($f["type"] == "js") - { - $this->tpl->addJavascript($f["target"]); - } - if ($f["type"] == "css") - { - $this->tpl->addCSS($f["target"]); - } - } - $this->tpl->fillJavaScriptFiles(true); - $this->tpl->fillCssFiles(true); - } - - - $this->tpl->fillBodyClass(); - - } - - if ($doShow) - { - // (horrible) workaround for preventing template engine - // from hiding paragraph text that is enclosed - // in curly brackets (e.g. "{a}", see ilPageObjectGUI::showPage()) - - $this->tpl->fillTabs(); - if ($this->fill_on_load_code) - { - $this->tpl->fillOnLoadCode(); - //$this->tpl->fillViewAppendInlineCss(); - } - $content = $this->tpl->get(); - $content = str_replace("{", "{", $content); - $content = str_replace("}", "}", $content); - - header('Content-type: text/html; charset=UTF-8'); - echo $content; - } - else - { - $this->tpl->fillLeftNav(); - $this->tpl->fillOnLoadCode(); - //$this->tpl->fillViewAppendInlineCss(); - $content = $this->tpl->get(); - } - - return($content); - } - - /** - * Save frame url - * - * @param - * @return - */ - function saveFrameUrl() - { - include_once("./Services/Authentication/classes/class.ilSessionIStorage.php"); - $store = new ilSessionIStorage("lm"); - if ($_GET["url"] != "") - { - $store->set("cf_".$this->lm->getId(), $_GET["url"]); - } - else - { - $store->set("cf_".$this->lm->getId(), $_GET["url"]); - } - } - - - function fullscreen() - { - return $this->layout("fullscreen.xml", !$this->offlineMode()); - } - - function media() - { - if ($_GET["frame"] != "_blank") - { - return $this->layout("main.xml", !$this->offlineMode()); - } - else - { - return $this->layout("fullscreen.xml", !$this->offlineMode()); - } - } - - function glossary() - { - global $DIC; - - $ilUser = $this->user; - - if ($_GET["frame"] != "_blank") - { - $this->layout(); - } - else - { - $this->tpl = new ilTemplate("tpl.glossary_term_output.html", true, true, true); - $GLOBALS["tpl"] = $this->tpl; - $this->renderPageTitle(); - - // set style sheets - if (!$this->offlineMode()) - { - $this->tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); - } - else - { - $style_name = $ilUser->getPref("style").".css";; - $this->tpl->setVariable("LOCATION_STYLESHEET","./style/".$style_name); - } - - $this->ilGlossary($child); - if (!$this->offlineMode()) - { - $this->tpl->show(); - } - else - { - return $this->tpl->get(); - } - } - } - - /** - * output main menu - */ - function ilMainMenu() - { - // LTI - global $DIC; - $ltiview = $DIC["lti"]; - if ($ltiview->isActive()) - { - include_once './Services/LTI/classes/class.ilMainMenuGUI.php'; - $ilMainMenu = new LTI\ilMainMenuGUI("_top", false, $this->tpl); - } - else - { - include_once './Services/MainMenu/classes/class.ilMainMenuGUI.php'; - $ilMainMenu = new ilMainMenuGUI("_top", false, $this->tpl); - } - - if ($this->offlineMode()) - { - $this->tpl->touchBlock("pg_intro"); - $this->tpl->touchBlock("pg_outro"); - return; - } - - $page_id = $this->getCurrentPageId(); - if ($page_id > 0) - { - $ilMainMenu->setLoginTargetPar("pg_".$page_id."_".$this->lm->getRefId()); - } - - //$this->tpl->touchBlock("mm_intro"); - //$this->tpl->touchBlock("mm_outro"); - $this->tpl->touchBlock("pg_intro"); - $this->tpl->touchBlock("pg_outro"); - $this->tpl->setBodyClass("std"); - $this->tpl->setVariable("MAINMENU", $ilMainMenu->getHTML()); - // LTI - $this->tpl->setVariable("MAINMENU_SPACER", $ilMainMenu->getSpacerClass()); - } - - /** - * table of contents - */ - function ilTOC($a_get_explorer = false) - { - include_once("./Modules/LearningModule/classes/class.ilLMTOCExplorerGUI.php"); - $exp = new ilLMTOCExplorerGUI($this, "ilTOC", $this, $this->lang, $this->focus_id, $this->export_all_languages); - $exp->setMainTemplate($this->tpl); - $exp->setTracker($this->getTracker()); - if (!$exp->handleCommand()) - { - // determine highlighted and force open nodes - $page_id = $this->getCurrentPageId(); - if ($this->deactivated_page) - { - $page_id = $_GET["obj_id"]; - } - if ($page_id > 0) - { - $exp->setPathOpen((int) $page_id); - } - // empty chapter - if ($this->chapter_has_no_active_page && - ilLMObject::_lookupType($_GET["obj_id"]) == "st") - { - $exp->setHighlightNode($_GET["obj_id"]); - } - else - { - if ($this->lm->getTOCMode() == "pages") - { - if ($this->deactivated_page) - { - $exp->setHighlightNode($_GET["obj_id"]); - } - else - { - $exp->setHighlightNode($page_id); - } - } - else - { - $exp->setHighlightNode($this->lm_tree->getParentId($page_id)); - } - } - if ($this->offlineMode()) - { - $exp->setOfflineMode(true); - } - - if ($a_get_explorer) - { - return $exp; - } - else - { - $this->tpl->setCurrentBlock("il_toc"); - $this->tpl->setVariable("EXPLORER", $exp->getHTML()); - $this->tpl->parseCurrentBlock(); - } - } - } - - /** - * Get lm presentationtitle - * - * @param - * @return - */ - function getLMPresentationTitle() - { - if ($this->offlineMode() && $this->lang != "" && $this->lang != "-") - { - include_once("./Services/Object/classes/class.ilObjectTranslation.php"); - $ot = ilObjectTranslation::getInstance($this->lm->getId()); - $data = $ot->getLanguages(); - $ltitle = $data[$this->lang]["title"]; - if ($ltitle != "") - { - return $ltitle; - } - } - return $this->lm->getTitle(); - } - - - /** - * output learning module menu - */ - function ilLMMenu() - { - $this->tpl->setVariable("MENU", $this->lm_gui->setilLMMenu($this->offlineMode() - ,$this->getExportFormat(), "content", false, true, $this->getCurrentPageId(), - $this->lang, $this->export_all_languages)); - } - - /** - * output lm header - */ - function ilLMHead() - { - $this->tpl->setCurrentBlock("header_image"); - if ($this->offlineMode()) - { - $this->tpl->setVariable("IMG_HEADER", "./images/icon_lm.svg"); - } - else - { - $this->tpl->setVariable("IMG_HEADER", ilUtil::getImagePath("icon_lm.svg")); - } - $this->tpl->parseCurrentBlock(); - $this->tpl->setCurrentBlock("lm_head"); - $this->tpl->setVariable("HEADER", $this->getLMPresentationTitle()); - $this->tpl->parseCurrentBlock(); - } - - /** - * output learning module submenu - */ - function ilLMSubMenu() - { - $rbacsystem = $this->rbacsystem; - - if ($this->abstract) - { - return; - } - - $showViewInFrameset = true; - - if ($showViewInFrameset) - { - $buttonTarget = ilFrameTargetInfo::_getFrame("MainContent"); - } - else - { - $buttonTarget = "_top"; - } - - - include_once("./Services/UICore/classes/class.ilTemplate.php"); - $tpl_menu = new ilTemplate("tpl.lm_sub_menu.html", true, true, true); - - $pg_id = $this->getCurrentPageId(); - if ($pg_id == 0) - { - return; - } - - // edit learning module - if (!$this->offlineMode()) - { - if ($rbacsystem->checkAccess("write", $_GET["ref_id"])) - { - $tpl_menu->setCurrentBlock("edit_page"); - $page_id = $this->getCurrentPageId(); - $tpl_menu->setVariable("EDIT_LINK", ILIAS_HTTP_PATH."/ilias.php?baseClass=ilLMEditorGUI&ref_id=".$_GET["ref_id"]. - "&obj_id=".$page_id."&to_page=1"); - $tpl_menu->setVariable("EDIT_TXT", $this->lng->txt("edit_page")); - $tpl_menu->setVariable("EDIT_TARGET", $buttonTarget); - $tpl_menu->parseCurrentBlock(); - } - - $page_id = $this->getCurrentPageId(); - - include_once("./Services/PermanentLink/classes/class.ilPermanentLinkGUI.php"); - $plinkgui = new ilPermanentLinkGUI("pg", - $page_id."_".$this->lm->getRefId(), - "", - "_top"); - - $title = $this->getLMPresentationTitle(); - $pg_title = ilLMPageObject::_getPresentationTitle($page_id, - $this->lm->getPageHeader(), $this->lm->isActiveNumbering(), - $this->lm_set->get("time_scheduled_page_activation"), false, 0, $this->lang); - if ($pg_title != "") - { - $title.= ": ".$pg_title; - } - - $plinkgui->setTitle($title); - - $tpl_menu->setCurrentBlock("perma_link"); - $tpl_menu->setVariable("PERMA_LINK", $plinkgui->getHTML()); - $tpl_menu->parseCurrentBlock(); - - } - - $this->tpl->setVariable("SUBMENU", $tpl_menu->get()); - } - - - /** - * Redraw header action - */ - function redrawHeaderAction() - { - echo $this->addHeaderAction(true); - exit; - } - - /** - * Add header action - */ - function addHeaderAction($a_redraw = false) - { - $ilAccess = $this->access; - $tpl = $this->tpl; - - include_once "Services/Object/classes/class.ilCommonActionDispatcherGUI.php"; - $dispatcher = new ilCommonActionDispatcherGUI(ilCommonActionDispatcherGUI::TYPE_REPOSITORY, - $ilAccess, $this->lm->getType(), $_GET["ref_id"], $this->lm->getId()); - $dispatcher->setSubObject("pg", $this->getCurrentPageId()); - - 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), - $this->tpl); - - $lg = $dispatcher->initHeaderAction(); - $lg->enableNotes(true); - $lg->enableComments($this->lm->publicNotes(), false); - - if($this->lm->hasRating() && !$this->offlineMode()) - { - $lg->enableRating(true, $this->lng->txt("lm_rating"), false, - array("ilcommonactiondispatchergui", "ilratinggui")); - } - - if(!$a_redraw) - { - $this->tpl->setVariable("HEAD_ACTION", $lg->getHeaderAction($this->tpl)); - } - else - { - // we need to add onload code manually (rating, comments, etc.) - return $lg->getHeaderAction(). - $tpl->getOnLoadCodeForAsynch(); - } - } - - /** - * output notes of page - */ - function ilLMNotes() - { - $ilAccess = $this->access; - $ilSetting = $this->settings; - - - // no notes in offline (export) mode - if ($this->offlineMode()) - { - return; - } - - // output notes (on top) - - if (!$ilSetting->get("disable_notes")) - { - $this->addHeaderAction(); - } - - // now output comments - - if ($ilSetting->get("disable_comments")) - { - return; - } - - if (!$this->lm->publicNotes()) - { - return; - } - - $next_class = $this->ctrl->getNextClass($this); - - include_once("Services/Notes/classes/class.ilNoteGUI.php"); - $pg_id = $this->getCurrentPageId(); - if ($pg_id == 0) - { - return; - } - - $notes_gui = new ilNoteGUI($this->lm->getId(), $this->getCurrentPageId(), "pg"); - - if ($ilAccess->checkAccess("write", "", $_GET["ref_id"]) && - $ilSetting->get("comments_del_tutor", 1)) - { - $notes_gui->enablePublicNotesDeletion(true); - } - - $this->ctrl->setParameter($this, "frame", $_GET["frame"]); - $this->ctrl->setParameter($this, "obj_id", $_GET["obj_id"]); - - $notes_gui->enablePrivateNotes(); - if ($this->lm->publicNotes()) - { - $notes_gui->enablePublicNotes(); - } - - if ($next_class == "ilnotegui") - { - $html = $this->ctrl->forwardCommand($notes_gui); - } - else - { - $html = $notes_gui->getNotesHTML(); - } - $this->tpl->setVariable("NOTES", $html); - } - - - /** - * locator - */ - function ilLocator($a_std_templ_loaded = false) - { - global $DIC; - $ltiview = $DIC["lti"]; - $ilLocator = $this->locator; - $tree = $this->tree; - $ilCtrl = $this->ctrl; - - require_once("./Modules/LearningModule/classes/class.ilStructureObject.php"); - - if (empty($_GET["obj_id"])) - { - $a_id = $this->lm_tree->getRootId(); - } - else - { - $a_id = $_GET["obj_id"]; - } - - if (!$a_std_templ_loaded) - { - $this->tpl->addBlockFile("STATUSLINE", "statusline", "tpl.statusline.html"); - } - - if (!$this->lm->cleanFrames()) - { - $frame_param = $_GET["frame"]; - $frame_target = ""; - } - else if (!$this->offlineMode()) - { - $frame_param = ""; - $frame_target = ilFrameTargetInfo::_getFrame("MainContent"); - } - else - { - $frame_param = ""; - $frame_target = "_top"; - } - - if (!$this->offlineMode()) - { - // LTI - if ($ltiview->isActive()) - { - // Do nothing, its complicated... - } - else - { - $ilLocator->addItem("...", ""); - - $par_id = $tree->getParentId($_GET["ref_id"]); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $par_id); - $ilLocator->addItem( - ilObject::_lookupTitle(ilObject::_lookupObjId($par_id)), - $ilCtrl->getLinkTargetByClass("ilrepositorygui", "frameset"), - ilFrameTargetInfo::_getFrame("MainContent"), $par_id); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - } - } - else - { - $ilLocator->setOffline(true); - } - - if($this->lm_tree->isInTree($a_id)) - { - $path = $this->lm_tree->getPathFull($a_id); - - foreach ($path as $key => $row) - { - if ($row["type"] != "pg") - { - if($row["child"] != $this->lm_tree->getRootId()) - { - $ilLocator->addItem( - ilUtil::shortenText( - ilStructureObject::_getPresentationTitle($row["child"], IL_CHAPTER_TITLE, - $this->lm->isActiveNumbering(), - $this->lm_set->get("time_scheduled_page_activation"), false, 0, $this->lang), - 50,true), - $this->getLink($_GET["ref_id"], "layout", $row["child"], $frame_param, "StructureObject"), - $frame_target); - } - else - { - $ilLocator->addItem( - ilUtil::shortenText($this->getLMPresentationTitle(),50,true), - $this->getLink($_GET["ref_id"], "layout", "", $frame_param), - $frame_target, $_GET["ref_id"]); - } - } - } - } - else // lonely page - { - - $ilLocator->addItem( - $this->getLMPresentationTitle(), - $this->getLink($_GET["ref_id"], "layout", "", $_GET["frame"])); - - require_once("./Modules/LearningModule/classes/class.ilLMObjectFactory.php"); - $lm_obj = ilLMObjectFactory::getInstance($this->lm, $a_id); - - $ilLocator->addItem( - $lm_obj->getTitle(), - $this->getLink($_GET["ref_id"], "layout", $a_id, $frame_param), - $frame_target); - } - - if (DEBUG) - { - $debug = "DEBUG: ".$this->type."::".$this->id."::".$_GET["cmd"]."
"; - } - - //$prop_name = $this->objDefinition->getPropertyName($_GET["cmd"],$this->type); - - - $this->tpl->setLocator(); - } - - /** - * Get the current page id - * - * @return bool|int current page id - */ - function getCurrentPageId() - { - $ilUser = $this->user; - - if (!$this->offlineMode() && $this->current_page_id !== false) - { - return $this->current_page_id; - } - - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - - $this->chapter_has_no_active_page = false; - $this->deactivated_page = false; - - // determine object id - if(empty($_GET["obj_id"])) - { - $obj_id = $this->lm_tree->getRootId(); - } - else - { - $obj_id = $_GET["obj_id"]; - $active = ilLMPage::_lookupActive($obj_id, - $this->lm->getType(), $this->lm_set->get("time_scheduled_page_activation")); - - if (!$active && - ilLMPageObject::_lookupType($obj_id) == "pg") - { - $this->deactivated_page = true; - } - } - - // obj_id not in tree -> it is a unassigned page -> return page id - if (!$this->lm_tree->isInTree($obj_id)) - { - return $obj_id; - } - - $curr_node = $this->lm_tree->getNodeData($obj_id); - - $active = ilLMPage::_lookupActive($obj_id, - $this->lm->getType(), $this->lm_set->get("time_scheduled_page_activation")); - - if ($curr_node["type"] == "pg" && - $active) // page in tree -> return page id - { - $page_id = $curr_node["obj_id"]; - } - else // no page -> search for next page and return its id - { - $succ_node = true; - $active = false; - $page_id = $obj_id; - while($succ_node && !$active) - { - $succ_node = $this->lm_tree->fetchSuccessorNode($page_id, "pg"); - $page_id = $succ_node["obj_id"]; - $active = ilLMPage::_lookupActive($page_id, - $this->lm->getType(), $this->lm_set->get("time_scheduled_page_activation")); - } - - if ($succ_node["type"] != "pg") - { - $this->chapter_has_no_active_page = true; - return 0; - } - - // if public access get first public page in chapter - if($ilUser->getId() == ANONYMOUS_USER_ID && - $this->lm_gui->object->getPublicAccessMode() == 'selected') - { - $public = ilLMObject::_isPagePublic($page_id); - - while ($public === false && $page_id > 0) - { - $succ_node = $this->lm_tree->fetchSuccessorNode($page_id, 'pg'); - $page_id = $succ_node['obj_id']; - $public = ilLMObject::_isPagePublic($page_id); - } - } - - // check whether page found is within "clicked" chapter - if ($this->lm_tree->isInTree($page_id)) - { - $path = $this->lm_tree->getPathId($page_id); - if (!in_array($_GET["obj_id"], $path)) - { - $this->chapter_has_no_active_page = true; - } - } - } - - $this->current_page_id = $page_id; - return $page_id; - } - - function ilCitation() - { - $page_id = $this->getCurrentPageId(); - $this->tpl = new ilTemplate("tpl.page.html",true,true,true); - $this->ilLocator(); - $this->tpl->setVariable("MENU",$this->lm_gui->setilCitationMenu()); - - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - - $this->pg_obj = $this->getLMPage($page_id); - $xml = $this->pg_obj->getXMLContent(); - $this->lm_gui->showCitation($xml); - $this->tpl->show(); - } - - - function getLayoutLinkTargets() - { - - if (!is_object($this->layout_doc)) - return array (); - - $xpc = xpath_new_context($this->layout_doc); - - $path = "/ilLayout/ilLinkTargets/LinkTarget"; - $res = xpath_eval($xpc, $path); - $targets = array(); - for ($i = 0; $i < count($res->nodeset); $i++) - { - $type = $res->nodeset[$i]->get_attribute("Type"); - $frame = $res->nodeset[$i]->get_attribute("Frame"); - $onclick = $res->nodeset[$i]->get_attribute("OnClick"); - $targets[$type] = array("Type" => $type, "Frame" => $frame, "OnClick" => $onclick); - } - - return $targets; - } - - /** - * process content tag - * - * @param $a_page_node page node - * @param int $a_page_id header / footer page id - * @return string - */ - function ilPage(&$a_page_node, $a_page_id = 0) - { - $access = $this->access; - - $ilUser = $this->user; - $ilHelp = $this->help; - - - $ilHelp = $this->help; - $ilHelp->setScreenIdComponent("lm"); - $ilHelp->setScreenId("content"); - $ilHelp->setSubScreenId("content"); - - $this->fill_on_load_code = true; - - - // check page id - $requested_page_lm = ilLMPage::lookupParentId($this->getCurrentPageId(), "lm"); - if ($requested_page_lm != $this->lm->getId()) - { - if ($_REQUEST["frame"] == "") - { - $this->showNoPageAccess(); - return ""; - } - else - { - $read_access = false; - foreach (ilObject::_getAllReferences($requested_page_lm) as $ref_id) - { - if ($access->checkAccess("read", "", $ref_id)) - { - $read_access = true; - } - } - if (!$read_access) - { - $this->showNoPageAccess(); - return ""; - } - } - } - - // check if page is (not) visible in public area - if($ilUser->getId() == ANONYMOUS_USER_ID && - $this->lm_gui->object->getPublicAccessMode() == 'selected') - { - $public = ilLMObject::_isPagePublic($this->getCurrentPageId()); - - if (!$public) - return $this->showNoPublicAccess($this->getCurrentPageId()); - } - - if (!ilObjContentObject::_checkPreconditionsOfPage($this->lm->getRefId(),$this->lm->getId(), $this->getCurrentPageId())) - { - return $this->showPreconditionsOfPage($this->getCurrentPageId()); - } - - // if navigation is restricted based on correct answered questions - // check if we have preceeding pages including unsanswered/incorrect answered questions - if (!$this->offlineMode()) - { - if ($this->lm->getRestrictForwardNavigation()) - { - if ($this->getTracker()->hasPredIncorrectAnswers($this->getCurrentPageId())) - { - $this->showNavRestrictionDueToQuestions(); - return; - } - } - } - - - require_once("./Modules/LearningModule/classes/class.ilLMPageGUI.php"); - require_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); - - // page id is e.g. > 0 when footer or header page is processed - if ($a_page_id == 0) - { - $page_id = $this->getCurrentPageId(); -//echo ":".$page_id.":"; - // highlighting? - - if ($_GET["srcstring"] != "" && !$this->offlineMode()) - { - include_once './Services/Search/classes/class.ilUserSearchCache.php'; - $cache = ilUserSearchCache::_getInstance($ilUser->getId()); - $cache->switchSearchType(ilUserSearchCache::LAST_QUERY); - $search_string = $cache->getQuery(); - - // advanced search? - if(is_array($search_string)) - { - $search_string = $search_string["lom_content"]; - } - - include_once("./Services/UIComponent/TextHighlighter/classes/class.ilTextHighlighterGUI.php"); - include_once("./Services/Search/classes/class.ilQueryParser.php"); - $p = new ilQueryParser($search_string); - $p->parse(); - - $words = $p->getQuotedWords(); - if (is_array($words)) - { - foreach ($words as $w) - { - ilTextHighlighterGUI::highlight("ilLMPageContent", $w, $this->tpl); - } - } - - $this->fill_on_load_code = true; - } - } - else - { - $page_id = $a_page_id; - } - - // content style - $this->tpl->setCurrentBlock("ContentStyle"); - if (!$this->offlineMode()) - { - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->lm->getStyleSheetId())); - } - else - { - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", "content_style/content.css"); - } - $this->tpl->parseCurrentBlock(); - - // no active page found in chapter - if ($this->chapter_has_no_active_page && - ilLMObject::_lookupType($_GET["obj_id"]) == "st") - { - $mtpl = new ilTemplate("tpl.no_content_message.html", true, true, - "Modules/LearningModule"); - $mtpl->setVariable("MESSAGE", $this->lng->txt("cont_no_page_in_chapter")); - //$mtpl->setVariable("SRC_ICON", ilUtil::getImagePath("icon_st.svg", - // false, "output", $this->offlineMode())); - $mtpl->setVariable("ITEM_TITLE", - ilLMObject::_lookupTitle($_GET["obj_id"])); - $this->tpl->setVariable("PAGE_CONTENT", $mtpl->get()); - return $mtpl->get(); - } - - // current page is deactivated - if ($this->deactivated_page) - { - $mtpl = new ilTemplate("tpl.no_content_message.html", true, true, - "Modules/LearningModule"); - $m = $this->lng->txt("cont_page_currently_deactivated"); - $act_data = ilLMPage::_lookupActivationData((int) $_GET["obj_id"], $this->lm->getType()); - if ($act_data["show_activation_info"] && - (ilUtil::now() < $act_data["activation_start"])) - { - $m.= "

".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 = '
'. - $rating_gui->getHtml(true, true, "il.LearningModule.saveRating(%rating%);"). - "
"; - } - - $this->tpl->setVariable("PAGE_CONTENT", $rating.$head.$focus_mess.$ret.$foot); -//echo htmlentities("-".$ret."-"); - return $head.$focus_mess.$ret.$foot; - } - - function updatePageRating() - { - $ilUser = $this->user; - - $pg_id = $_GET["pgid"]; - if(!$this->ctrl->isAsynch() || !$pg_id) - { - exit(); - } - - include_once './Services/Rating/classes/class.ilRating.php'; - $rating = (int)$_POST["rating"]; - if($rating) - { - ilRating::writeRatingForUserAndObject($this->lm->getId(), "lm", - $pg_id, "lm", $ilUser->getId(), $_POST["rating"]); - } - else - { - ilRating::resetRatingForUserAndObject($this->lm->getId(), "lm", - $pg_id, "lm", $ilUser->getId()); - } - - include_once './Services/Rating/classes/class.ilRatingGUI.php'; - $rating = new ilRatingGUI(); - $rating->setObject($this->lm->getId(), "lm", $pg_id, "lm", $ilUser->getId()); - $rating->setYourRatingText($this->lng->txt("lm_rate_page")); - - echo $rating->getHtml(true, true, "il.LearningModule.saveRating(%rating%);"); - - echo $this->tpl->getOnLoadCodeForAsynch(); - exit(); - } - - /** - * Basic page gui initialisation - * - * @param - * @return - */ - function basicPageGuiInit($a_page_gui) - { - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $a_page_gui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId( - $this->lm->getStyleSheetId(), "lm")); - if (!$this->offlineMode()) - { - $a_page_gui->setOutputMode("presentation"); - $this->fill_on_load_code = true; - } - else - { - $a_page_gui->setOutputMode("offline"); - $a_page_gui->setOfflineDirectory($this->getOfflineDirectory()); - $this->fill_on_load_code = false; - } - if (!$this->offlineMode()) - { - $this->ctrl->setParameter($this, "obj_id", $this->getCurrentPageId()); // see #22403 - } - $a_page_gui->setFileDownloadLink($this->getLink($_GET["ref_id"], "downloadFile")); - if (!$this->offlineMode()) - { - $this->ctrl->setParameter($this, "obj_id", $_GET["obj_id"]); - } - $a_page_gui->setFullscreenLink($this->getLink($_GET["ref_id"], "fullscreen")); - } - - /** - * show preconditions of the page - */ - function showPreconditionsOfPage() - { - $conds = ilObjContentObject::_getMissingPreconditionsOfPage($this->lm->getRefId(),$this->lm->getId(), $this->getCurrentPageId()); - $topchap = ilObjContentObject::_getMissingPreconditionsTopChapter($this->lm->getRefId(),$this->lm->getId(), $this->getCurrentPageId()); - - $page_id = $this->getCurrentPageId(); - - // content style - $this->tpl->setCurrentBlock("ContentStyle"); - if (!$this->offlineMode()) - { - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->lm->getStyleSheetId())); - } - else - { - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", "content_style/content.css"); - } - $this->tpl->parseCurrentBlock(); - - $this->tpl->addBlockFile("PAGE_CONTENT", "pg_content", "tpl.page_preconditions.html", true); - - // list all missing preconditions - include_once("./Services/Repository/classes/class.ilRepositoryExplorer.php"); - foreach($conds as $cond) - { - include_once("./Services/Link/classes/class.ilLink.php"); - $obj_link = ilLink::_getLink($cond["trigger_ref_id"]); - $this->tpl->setCurrentBlock("condition"); - $this->tpl->setVariable("VAL_ITEM", ilObject::_lookupTitle($cond["trigger_obj_id"])); - $this->tpl->setVariable("LINK_ITEM", $obj_link); - if ($cond["operator"] == "passed") - { - $cond_str = $this->lng->txt("passed"); - } - else - { - $cond_str = $this->lng->txt("condition_".$cond["operator"]); - } - $this->tpl->setVariable("VAL_CONDITION", $cond_str." ".$cond["value"]); - $this->tpl->parseCurrentBlock(); - } - $this->tpl->setCurrentBlock("pg_content"); - - $this->tpl->setVariable("TXT_MISSING_PRECONDITIONS", - sprintf($this->lng->txt("cont_missing_preconditions"), - ilLMObject::_lookupTitle($topchap))); - $this->tpl->setVariable("TXT_ITEM", $this->lng->txt("object")); - $this->tpl->setVariable("TXT_CONDITION", $this->lng->txt("condition")); - - // output skip chapter link - $parent = $this->lm_tree->getParentId($topchap); - $childs = $this->lm_tree->getChildsByType($parent, "st"); - $next = ""; - $j=-2; $i=1; - foreach($childs as $child) - { - if ($child["child"] == $topchap) - { - $j = $i; - } - if ($i++ == ($j+1)) - { - $succ_node = $this->lm_tree->fetchSuccessorNode($child["child"], "pg"); - } - } - if($succ_node != "") - { - $framestr = (!empty($_GET["frame"])) - ? "frame=".$_GET["frame"]."&" - : ""; - - $showViewInFrameset = true; - $link = "
getLink($this->lm->getRefId(), "layout", $succ_node["obj_id"], $_GET["frame"]). - "\">".$this->lng->txt("cont_skip_chapter").""; - $this->tpl->setVariable("LINK_SKIP_CHAPTER", $link); - } - - $this->tpl->parseCurrentBlock(); - } - - /** - * get xml for links - */ - function getLinkXML($a_int_links, $a_layoutframes) - { - $ilCtrl = $this->ctrl; - - // Determine whether the view of a learning resource should - // be shown in the frameset of ilias, or in a separate window. - $showViewInFrameset = true; - - if ($a_layoutframes == "") - { - $a_layoutframes = array(); - } - $link_info = ""; - foreach ($a_int_links as $int_link) - { - $target = $int_link["Target"]; - if (substr($target, 0, 4) == "il__") - { - $target_arr = explode("_", $target); - $target_id = $target_arr[count($target_arr) - 1]; - $type = $int_link["Type"]; - $targetframe = ($int_link["TargetFrame"] != "") - ? $int_link["TargetFrame"] - : "None"; - - // anchor - $anc = $anc_add = ""; - if ($int_link["Anchor"] != "") - { - $anc = $int_link["Anchor"]; - $anc_add = "_".rawurlencode($int_link["Anchor"]); - } - $lcontent = ""; - switch($type) - { - case "PageObject": - case "StructureObject": - $lm_id = ilLMObject::_lookupContObjID($target_id); - if ($lm_id == $this->lm->getId() || - ($targetframe != "None" && $targetframe != "New")) - { - $ltarget = $a_layoutframes[$targetframe]["Frame"]; - //$nframe = ($ltarget == "") - // ? $_GET["frame"] - // : $ltarget; - $nframe = ($ltarget == "") - ? "" - : $ltarget; - if ($ltarget == "") - { - if ($showViewInFrameset) { - $ltarget="_parent"; - } else { - $ltarget="_top"; - } - } - // scorm always in 1window view and link target - // is always same frame - if ($this->getExportFormat() == "scorm" && - $this->offlineMode()) - { - $ltarget = ""; - } - $href = - $this->getLink($_GET["ref_id"], "layout", $target_id, $nframe, $type, - "append", $anc); - if ($lm_id == "") - { - $href = ""; - } - } - else - { - if (!$this->offlineMode()) - { - if ($type == "PageObject") - { - $href = "./goto.php?target=pg_".$target_id.$anc_add; - } - else - { - $href = "./goto.php?target=st_".$target_id; - } - } - else - { - if ($type == "PageObject") - { - $href = ILIAS_HTTP_PATH."/goto.php?target=pg_".$target_id.$anc_add."&client_id=".CLIENT_ID; - } - else - { - $href = ILIAS_HTTP_PATH."/goto.php?target=st_".$target_id."&client_id=".CLIENT_ID; - } - } - if ($targetframe != "New") - { - $ltarget = ilFrameTargetInfo::_getFrame("MainContent"); - } - else - { - $ltarget = "_blank"; - } - } - break; - - case "GlossaryItem": - if ($targetframe == "None") - { - $targetframe = "Glossary"; - } - $ltarget = $a_layoutframes[$targetframe]["Frame"]; - $nframe = ($ltarget == "") - ? $_GET["frame"] - : $ltarget; - $href = - $this->getLink($_GET["ref_id"], $a_cmd = "glossary", $target_id, $nframe, $type); - break; - - case "MediaObject": - $ltarget = $a_layoutframes[$targetframe]["Frame"]; - $nframe = ($ltarget == "") - ? $_GET["frame"] - : $ltarget; - $href = - $this->getLink($_GET["ref_id"], $a_cmd = "media", $target_id, $nframe, $type); - break; - - case "RepositoryItem": - $obj_type = ilObject::_lookupType($target_id, true); - $obj_id = ilObject::_lookupObjId($target_id); - if (!$this->offlineMode()) - { - $href = "./goto.php?target=".$obj_type."_".$target_id; - } - else - { - $href = ILIAS_HTTP_PATH."/goto.php?target=".$obj_type."_".$target_id."&client_id=".CLIENT_ID; - } - $ltarget = ilFrameTargetInfo::_getFrame("MainContent"); - break; - - case "WikiPage": - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $href = ilWikiPage::getGotoForWikiPageTarget($target_id); - break; - - case "File": - if (!$this->offlineMode()) - { - $ilCtrl->setParameter($this, "obj_id", $this->getCurrentPageId()); - $ilCtrl->setParameter($this, "file_id", "il__file_".$target_id); - $href = $ilCtrl->getLinkTarget($this, "downloadFile"); - $ilCtrl->setParameter($this, "file_id", ""); - $ilCtrl->setParameter($this, "obj_id", $_GET["obj_id"]); - } - break; - - case "User": - $obj_type = ilObject::_lookupType($target_id); - if ($obj_type == "usr") - { - include_once("./Services/User/classes/class.ilUserUtil.php"); - $back = $this->ctrl->getLinkTarget($this, "layout"); - //var_dump($back); exit; - $this->ctrl->setParameterByClass("ilpublicuserprofilegui", "user_id", $target_id); - $this->ctrl->setParameterByClass("ilpublicuserprofilegui", "back_url", - rawurlencode($back)); - $href = ""; - include_once("./Services/User/classes/class.ilUserUtil.php"); - if (ilUserUtil::hasPublicProfile($target_id)) - { - $href = $this->ctrl->getLinkTargetByClass("ilpublicuserprofilegui", "getHTML"); - } - $this->ctrl->setParameterByClass("ilpublicuserprofilegui", "user_id", ""); - $lcontent = ilUserUtil::getNamePresentation($target_id, false, false); - } - break; - - } - - $anc_par = 'Anchor="'.$anc.'"'; - - if ($href != "") - { - $link_info .= ""; - } - - // set equal link info for glossary links of target "None" and "Glossary" - /* - if ($targetframe=="None" && $type=="GlossaryItem") - { - $link_info.=""; - }*/ - } - } - $link_info.= ""; - return $link_info; - } - - /** - * Get XMl for Link Targets - */ - function getLinkTargetsXML() - { - $link_info = ""; - foreach ($this->getLayoutLinkTargets() as $k => $t) - { - $link_info.=""; - } - $link_info.= ""; - return $link_info; - } - - /** - * show glossary term - */ - function ilGlossary() - { - $ilCtrl = $this->ctrl; - - require_once("./Modules/Glossary/classes/class.ilGlossaryTermGUI.php"); - $term_gui = new ilGlossaryTermGUI($_GET["obj_id"]); - - // content style - $this->tpl->setCurrentBlock("ContentStyle"); - if (!$this->offlineMode()) - { - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->lm->getStyleSheetId())); - } - else - { - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", "content_style/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(); - - $int_links = $term_gui->getInternalLinks(); - $link_xml = $this->getLinkXML($int_links, $this->getLayoutLinkTargets()); - $link_xml.= $this->getLinkTargetsXML(); - $term_gui->setLinkXML($link_xml); - - $term_gui->setOfflineDirectory($this->getOfflineDirectory()); - if (!$this->offlineMode()) - { - $ilCtrl->setParameter($this, "pg_type", "glo"); - } - $term_gui->output($this->offlineMode(), $this->tpl); - - - - if (!$this->offlineMode()) - { - $ilCtrl->setParameter($this, "pg_type", ""); - } - } - - /** - * output media - */ - function ilMedia() - { - $ilUser = $this->user; - - $this->tpl->setCurrentBlock("ContentStyle"); - if (!$this->offlineMode()) - { - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->lm->getStyleSheetId())); - } - else - { - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", "content_style/content.css"); - } - $this->tpl->parseCurrentBlock(); - - $this->renderPageTitle(); - - // set style sheets - if (!$this->offlineMode()) - { - $this->tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); - } - else - { - $style_name = $ilUser->getPref("style").".css";; - $this->tpl->setVariable("LOCATION_STYLESHEET","./style/".$style_name); - } - - $this->tpl->setCurrentBlock("ilMedia"); - - //$int_links = $page_object->getInternalLinks(); - $med_links = ilMediaItem::_getMapAreasIntLinks($_GET["mob_id"]); - $link_xml = $this->getLinkXML($med_links, $this->getLayoutLinkTargets()); - $link_xml.= $this->getLinkTargetsXML(); -//echo "

".htmlentities($link_xml); - require_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $media_obj = new ilObjMediaObject($_GET["mob_id"]); - if (!empty ($_GET["pg_id"])) - { - require_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - $pg_obj = $this->getLMPage($_GET["pg_id"]); - $pg_obj->buildDom(); - - $xml = ""; - // todo: we get always the first alias now (problem if mob is used multiple - // times in page) - $xml.= $pg_obj->getMediaAliasElement($_GET["mob_id"]); - $xml.= $media_obj->getXML(IL_MODE_OUTPUT); - $xml.= $link_xml; - $xml.=""; - } - else - { - $xml = ""; - // todo: we get always the first alias now (problem if mob is used multiple - // times in page) - $xml.= $media_obj->getXML(IL_MODE_ALIAS); - $xml.= $media_obj->getXML(IL_MODE_OUTPUT); - $xml.= $link_xml; - $xml.=""; - } - -//echo htmlentities($xml); exit; - - // todo: utf-header should be set globally - //header('Content-type: text/html; charset=UTF-8'); - - $xsl = file_get_contents("./Services/COPage/xsl/page.xsl"); - $args = array( '/_xml' => $xml, '/_xsl' => $xsl ); - $xh = xslt_create(); - -//echo "XML:".htmlentities($xml); - // determine target frames for internal links - //$pg_frame = $_GET["frame"]; - if (!$this->offlineMode()) - { - $wb_path = ilUtil::getWebspaceDir("output")."/"; - } - else - { - $wb_path = ""; - } - - $mode = ($_GET["cmd"] == "fullscreen") - ? "fullscreen" - : "media"; - $enlarge_path = ilUtil::getImagePath("enlarge.svg", false, "output", $this->offlineMode()); - $fullscreen_link = - $this->getLink($this->lm->getRefId(), "fullscreen"); - $params = array ('mode' => $mode, 'enlarge_path' => $enlarge_path, - 'link_params' => "ref_id=".$this->lm->getRefId(),'fullscreen_link' => $fullscreen_link, - 'ref_id' => $this->lm->getRefId(), 'pg_frame' => $pg_frame, 'webspace_path' => $wb_path); - $output = xslt_process($xh,"arg:/_xml","arg:/_xsl",NULL,$args, $params); - echo xslt_error($xh); - xslt_free($xh); - - // unmask user html - $this->tpl->setVariable("MEDIA_CONTENT", $output); - - // add js - include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); - ilObjMediaObjectGUI::includePresentationJS($this->tpl); - } - - /** - * Puts JS into template - */ - function ilJavaScript($a_inline = "", $a_file = "", $a_location = "") - { - if ($a_inline != "") - { - $js_tpl = new ilTemplate($a_inline, true, false, $a_location); - $js = $js_tpl->get(); - $this->tpl->setVariable("INLINE_JS", $js); - } - } - - /** - * Get successor page - * - * @param - * @return - */ - function getSuccessorPage() - { - $ilUser = $this->user; - - $page_id = $this->getCurrentPageId(); - - if(empty($page_id)) - { - return 0; - } - - // determine successor page_id - $found = false; - - // empty chapter - if ($this->chapter_has_no_active_page && - ilLMObject::_lookupType($_GET["obj_id"]) == "st") - { - $c_id = $_GET["obj_id"]; - } - else - { - if ($this->deactivated_page) - { - $c_id = $_GET["obj_id"]; - } - else - { - $c_id = $page_id; - } - } - while (!$found) - { - $succ_node = $this->lm_tree->fetchSuccessorNode($c_id, "pg"); - $c_id = $succ_node["obj_id"]; - - $active = ilLMPage::_lookupActive($c_id, - $this->lm->getType(), $this->lm_set->get("time_scheduled_page_activation")); - - if ($succ_node["obj_id"] > 0 && - $ilUser->getId() == ANONYMOUS_USER_ID && - ( $this->lm->getPublicAccessMode() == "selected" && - !ilLMObject::_isPagePublic($succ_node["obj_id"]))) - { - $found = false; - } - else if ($succ_node["obj_id"] > 0 && !$active) - { - // look, whether activation data should be shown - $act_data = ilLMPage::_lookupActivationData((int) $succ_node["obj_id"], $this->lm->getType()); - if ($act_data["show_activation_info"] && - (ilUtil::now() < $act_data["activation_start"])) - { - $found = true; - } - else - { - $found = false; - } - } - else - { - $found = true; - } - } - - if ($found) - { - return $succ_node["obj_id"]; - } - return 0; - } - - - /** - * inserts sequential learning module navigation - * at template variable LMNAVIGATION_CONTENT - */ - function ilLMNavigation() - { - $ilUser = $this->user; - - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - - include_once("./Services/Accessibility/classes/class.ilAccessKeyGUI.php"); - - $page_id = $this->getCurrentPageId(); - - if(empty($page_id)) - { - return; - } - - // process navigation for free page - if(!$this->lm_tree->isInTree($page_id)) - { - if ($this->offlineMode() || $_GET["back_pg"] == "") - { - return; - } - $limpos = strpos($_GET["back_pg"], ":"); - if ($limpos > 0) - { - $back_pg = substr($_GET["back_pg"], 0, $limpos); - } - else - { - $back_pg = $_GET["back_pg"]; - } - if (!$this->lm->cleanFrames()) - { - $back_href = - $this->getLink($this->lm->getRefId(), "layout", $back_pg, $_GET["frame"], - "", "reduce"); - $back_target = ""; - } - else - { - $back_href = - $this->getLink($this->lm->getRefId(), "layout", $back_pg, "", - "", "reduce"); - $back_target = 'target="'.ilFrameTargetInfo::_getFrame("MainContent").'" '; - } - $back_img = - ilUtil::getImagePath("nav_arr2_L.png", false, "output", $this->offlineMode()); - $this->tpl->setCurrentBlock("ilLMNavigation_Prev"); - $this->tpl->setVariable("IMG_PREV", $back_img); - $this->tpl->setVariable("HREF_PREV", $back_href); - $this->tpl->setVariable("FRAME_PREV", $back_target); - $this->tpl->setVariable("TXT_PREV", $this->lng->txt("back")); - $this->tpl->setVariable("ALT_PREV", $this->lng->txt("back")); - $this->tpl->setVariable("PREV_ACC_KEY", - ilAccessKeyGUI::getAttribute(ilAccessKey::PREVIOUS)); - $this->tpl->setVariable("SPACER_PREV", $this->offlineMode() - ? "images/spacer.png" - : ilUtil::getImagePath("spacer.png")); - $this->tpl->parseCurrentBlock(); - $this->tpl->setCurrentBlock("ilLMNavigation_Prev2"); - $this->tpl->setVariable("IMG_PREV2", $back_img); - $this->tpl->setVariable("HREF_PREV2", $back_href); - $this->tpl->setVariable("FRAME_PREV2", $back_target); - $this->tpl->setVariable("TXT_PREV2", $this->lng->txt("back")); - $this->tpl->setVariable("ALT_PREV2", $this->lng->txt("back")); - $this->tpl->setVariable("SPACER_PREV2", $this->offlineMode() - ? "images/spacer.png" - : ilUtil::getImagePath("spacer.png")); - $this->tpl->parseCurrentBlock(); - return; - } - - // determine successor page_id - $found = false; - - // empty chapter - if ($this->chapter_has_no_active_page && - ilLMObject::_lookupType($_GET["obj_id"]) == "st") - { - $c_id = $_GET["obj_id"]; - } - else - { - if ($this->deactivated_page) - { - $c_id = $_GET["obj_id"]; - } - else - { - $c_id = $page_id; - } - } - while (!$found) - { - $succ_node = $this->lm_tree->fetchSuccessorNode($c_id, "pg"); - $c_id = $succ_node["obj_id"]; - - $active = ilLMPage::_lookupActive($c_id, - $this->lm->getType(), $this->lm_set->get("time_scheduled_page_activation")); - - if ($succ_node["obj_id"] > 0 && - $ilUser->getId() == ANONYMOUS_USER_ID && - ( $this->lm->getPublicAccessMode() == "selected" && - !ilLMObject::_isPagePublic($succ_node["obj_id"]))) - { - $found = false; - } - else if ($succ_node["obj_id"] > 0 && !$active) - { - // look, whether activation data should be shown - $act_data = ilLMPage::_lookupActivationData((int) $succ_node["obj_id"], $this->lm->getType()); - if ($act_data["show_activation_info"] && - (ilUtil::now() < $act_data["activation_start"])) - { - $found = true; - } - else - { - $found = false; - } - } - else - { - $found = true; - } - } - - $succ_str = ($succ_node !== false) - ? " -> ".$succ_node["obj_id"]."_".$succ_node["type"] - : ""; - - // determine predecessor page id - $found = false; - if ($this->deactivated_page) - { - $c_id = $_GET["obj_id"]; - } - else - { - $c_id = $page_id; - } - while (!$found) - { - $pre_node = $this->lm_tree->fetchPredecessorNode($c_id, "pg"); - $c_id = $pre_node["obj_id"]; - $active = ilLMPage::_lookupActive($c_id, - $this->lm->getType(), $this->lm_set->get("time_scheduled_page_activation")); - if ($pre_node["obj_id"] > 0 && - $ilUser->getId() == ANONYMOUS_USER_ID && - ($this->lm->getPublicAccessMode() == "selected" && - !ilLMObject::_isPagePublic($pre_node["obj_id"]))) - { - $found = false; - } - else if ($pre_node["obj_id"] > 0 && !$active) - { - // look, whether activation data should be shown - $act_data = ilLMPage::_lookupActivationData((int) $pre_node["obj_id"], $this->lm->getType()); - if ($act_data["show_activation_info"] && - (ilUtil::now() < $act_data["activation_start"])) - { - $found = true; - } - else - { - $found = false; - } - } - else - { - $found = true; - } - } - - $pre_str = ($pre_node !== false) - ? $pre_node["obj_id"]."_".$pre_node["type"]." -> " - : ""; - - // determine target frame - $framestr = (!empty($_GET["frame"])) - ? "frame=".$_GET["frame"]."&" - : ""; - - - // Determine whether the view of a learning resource should - // be shown in the frameset of ilias, or in a separate window. - $showViewInFrameset = true; - - if($pre_node != "") - { - // get presentation title - $prev_title = ilLMPageObject::_getPresentationTitle($pre_node["obj_id"], - $this->lm->getPageHeader(), $this->lm->isActiveNumbering(), - $this->lm_set->get("time_scheduled_page_activation"), false, 0, $this->lang, true); - $prev_title = ilUtil::shortenText($prev_title, 50, true); - $prev_img = - ilUtil::getImagePath("nav_arr_L.png", false, "output", $this->offlineMode()); - - if (!$this->lm->cleanFrames()) - { - $prev_href = - $this->getLink($this->lm->getRefId(), "layout", $pre_node["obj_id"], $_GET["frame"]); - $prev_target = ""; - } - else if ($showViewInFrameset && !$this->offlineMode()) - { - $prev_href = - $this->getLink($this->lm->getRefId(), "layout", $pre_node["obj_id"]); - $prev_target = 'target="'.ilFrameTargetInfo::_getFrame("MainContent").'" '; - } - else - { - $prev_href = - $this->getLink($this->lm->getRefId(), "layout", $pre_node["obj_id"]); - $prev_target = 'target="_top" '; - } - - if($ilUser->getId() == ANONYMOUS_USER_ID && - ($this->lm->getPublicAccessMode() == 'selected' && !ilLMObject::_isPagePublic($pre_node["obj_id"]))) - { - $output = $this->lng->txt("msg_page_not_public"); - } - - $this->tpl->setCurrentBlock("ilLMNavigation_Prev"); - $this->tpl->setVariable("IMG_PREV", $prev_img); - $this->tpl->setVariable("HREF_PREV", $prev_href); - $this->tpl->setVariable("FRAME_PREV", $prev_target); - $this->tpl->setVariable("TXT_PREV", $prev_title); - $this->tpl->setVariable("ALT_PREV", $this->lng->txt("previous")); - $this->tpl->setVariable("SPACER_PREV", $this->offlineMode() - ? "images/spacer.png" - : ilUtil::getImagePath("spacer.png")); - $this->tpl->setVariable("PREV_ACC_KEY", - ilAccessKeyGUI::getAttribute(ilAccessKey::PREVIOUS)); - $this->tpl->parseCurrentBlock(); - $this->tpl->setCurrentBlock("ilLMNavigation_Prev2"); - $this->tpl->setVariable("IMG_PREV2", $prev_img); - $this->tpl->setVariable("HREF_PREV2", $prev_href); - $this->tpl->setVariable("FRAME_PREV2", $prev_target); - $this->tpl->setVariable("TXT_PREV2", $prev_title); - $this->tpl->setVariable("ALT_PREV2", $this->lng->txt("previous")); - $this->tpl->setVariable("SPACER_PREV2", $this->offlineMode() - ? "images/spacer.png" - : ilUtil::getImagePath("spacer.png")); - $this->tpl->parseCurrentBlock(); - } - if($succ_node != "") - { - // get presentation title - $succ_title = ilLMPageObject::_getPresentationTitle($succ_node["obj_id"], - $this->lm->getPageHeader(), $this->lm->isActiveNumbering(), - $this->lm_set->get("time_scheduled_page_activation"), false, 0, $this->lang, true); - $succ_title = ilUtil::shortenText($succ_title, 50, true); - $succ_img = - ilUtil::getImagePath("nav_arr_R.png", false, "output", $this->offlineMode()); - if (!$this->lm->cleanFrames()) - { - $succ_href = - $this->getLink($this->lm->getRefId(), "layout", $succ_node["obj_id"], $_GET["frame"]); - $succ_target = ""; - } - else if ($showViewInFrameset && !$this->offlineMode()) - { - $succ_href = - $this->getLink($this->lm->getRefId(), "layout", $succ_node["obj_id"]); - $succ_target = ' target="'.ilFrameTargetInfo::_getFrame("MainContent").'" '; - } - else - { - $succ_href = - $this->getLink($this->lm->getRefId(), "layout", $succ_node["obj_id"]); - $succ_target = ' target="_top" '; - } - - if($ilUser->getId() == ANONYMOUS_USER_ID && - ($this->lm->getPublicAccessMode() == 'selected' && !ilLMObject::_isPagePublic($pre_node["obj_id"]))) - { - $output = $this->lng->txt("msg_page_not_public"); - } - - $this->tpl->setCurrentBlock("ilLMNavigation_Next"); - $this->tpl->setVariable("IMG_SUCC", $succ_img); - $this->tpl->setVariable("HREF_SUCC", $succ_href); - $this->tpl->setVariable("FRAME_SUCC", $succ_target); - $this->tpl->setVariable("TXT_SUCC", $succ_title); - $this->tpl->setVariable("ALT_SUCC", $this->lng->txt("next")); - $this->tpl->setVariable("SPACER_SUCC", $this->offlineMode() - ? "images/spacer.png" - : ilUtil::getImagePath("spacer.png")); - $this->tpl->setVariable("NEXT_ACC_KEY", - ilAccessKeyGUI::getAttribute(ilAccessKey::NEXT)); - $this->tpl->parseCurrentBlock(); - $this->tpl->setCurrentBlock("ilLMNavigation_Next2"); - $this->tpl->setVariable("IMG_SUCC2", $succ_img); - $this->tpl->setVariable("HREF_SUCC2", $succ_href); - $this->tpl->setVariable("FRAME_SUCC2", $succ_target); - $this->tpl->setVariable("TXT_SUCC2", $succ_title); - $this->tpl->setVariable("ALT_SUCC2", $this->lng->txt("next")); - $this->tpl->setVariable("SPACER_SUCC2", $this->offlineMode() - ? "images/spacer.png" - : ilUtil::getImagePath("spacer.png")); - $this->tpl->parseCurrentBlock(); - - // check if successor page is not restricted - if (!$this->offlineMode()) - { - if ($this->lm->getRestrictForwardNavigation()) - { - if ($this->getTracker()->hasPredIncorrectAnswers($succ_node["obj_id"])) - { - $this->tpl->addOnLoadCode("$('.ilc_page_rnav_RightNavigation').addClass('ilNoDisplay');"); - } - } - } - } - } - - - function processNodes(&$a_content, &$a_node) - { - $child_nodes = $a_node->child_nodes(); - foreach ($child_nodes as $child) - { - if($child->node_name() == "ilFrame") - { - $attributes = $this->attrib2arr($child->attributes()); - // node is frameset, if it has cols or rows attribute - if ((!empty($attributes["rows"])) || (!empty($attrubtes["cols"]))) - { - // if framset has name, another http request is necessary - // (html framesets don't have names, so we need a wrapper frame) - if(!empty($attributes["name"])) - { - unset($attributes["template"]); - unset($attributes["template_location"]); - $attributes["src"] = - $this->getLink($this->lm->getRefId(), "layout", $_GET["obj_id"], $attributes["name"], - "", "keep", "", $_GET["srcstring"]); - $attributes["title"] = $this->lng->txt("cont_frame_".$attributes["name"]); - $a_content .= $this->buildTag("", "frame", $attributes); - $this->frames[$attributes["name"]] = $attributes["name"]; -//echo "
processNodes:add1 ".$attributes["name"]; - } - else // ok, no name means that we can easily output the frameset tag - { - $a_content .= $this->buildTag("start", "frameset", $attributes); - $this->processNodes($a_content, $child); - $a_content .= $this->buildTag("end", "frameset"); - } - } - else // frame with - { - unset($attributes["template"]); - unset($attributes["template_location"]); - $attributes["src"] = - $this->getLink($this->lm->getRefId(), "layout", $_GET["obj_id"], $attributes["name"], - "", "keep", "", $_GET["srcstring"]); - $attributes["title"] = $this->lng->txt("cont_frame_".$attributes["name"]); - if ($attributes["name"] == "toc") - { - $attributes["src"].= "#".$_GET["obj_id"]; - } - else - { - // Handle Anchors - if ($_GET["anchor"] != "") - { - $attributes["src"].= "#".rawurlencode($_GET["anchor"]); - } - } - $a_content .= $this->buildTag("", "frame", $attributes); - $this->frames[$attributes["name"]] = $attributes["name"]; - } - } - } - } - - /** - * generate a tag with given name and attributes - * - * @param string "start" | "end" | "" for starting or ending tag or complete tag - * @param string element/tag name - * @param array array of attributes - */ - function buildTag ($type, $name, $attr="") - { - $tag = "<"; - - if ($type == "end") - $tag.= "/"; - - $tag.= $name; - - if (is_array($attr)) - { - foreach ($attr as $k => $v) { - $tag .= " " . $k . "=\"$v\""; - } - } - - if ($type == "") - $tag.= "/"; - - $tag.= ">\n"; - - return $tag; - } - - - /** - * table of contents - */ - function showTableOfContents() - { - $ilUser = $this->user; - - if (!$this->lm->isActiveTOC() || !$this->lm->isActiveLMMenu()) - { - return; - } - - //$this->tpl = new ilTemplate("tpl.lm_toc.html", true, true, true); - $this->tpl->setCurrentBlock("ContentStyle"); - if (!$this->offlineMode()) - { - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->lm->getStyleSheetId())); - } - else - { - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", "content_style/content.css"); - } - $this->tpl->parseCurrentBlock(); - - $this->renderPageTitle(); - - // set style sheets - if (!$this->offlineMode()) - { - $this->tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); - } - else - { - $style_name = $ilUser->getPref("style").".css";; - $this->tpl->setVariable("LOCATION_STYLESHEET","./style/".$style_name); - } - - //$this->tpl->addBlockFile("CONTENT", "content", "tpl.lm_toc.html", true); - //var_dump($GLOBALS["tpl"]); echo "

"; - //exit; - $this->tpl->getStandardTemplate(); - $this->ilLocator(true); - - $a_global_tabs = !$this->offlineMode(); - - $this->tpl->setVariable("TABS", $this->lm_gui->setilLMMenu($this->offlineMode() - ,$this->getExportFormat(), "toc", $a_global_tabs, false, 0, - $this->lang, $this->export_all_languages)); - - // set title header - $this->tpl->setVariable("TXT_TOC", $this->lng->txt("cont_toc")); - $this->tpl->setTitle($this->getLMPresentationTitle()); - $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_lm.svg")); - - include_once("./Modules/LearningModule/classes/class.ilLMTableOfContentsExplorerGUI.php"); - $exp = new ilLMTableOfContentsExplorerGUI($this, "showTableOfContents", $this, $this->lang, $this->export_all_languages); - $exp->setMainTemplate($this->tpl); - $exp->setTracker($this->getTracker()); - if (!$exp->handleCommand()) - { - // determine highlighted and force open nodes - $page_id = $this->getCurrentPageId(); - if ($this->deactivated_page) - { - $page_id = $_GET["obj_id"]; - } - - // highlight current node - if (!$this->offlineMode()) - { - // empty chapter - if ($this->chapter_has_no_active_page && - ilLMObject::_lookupType($_GET["obj_id"]) == "st") - { - $exp->setHighlightNode($_GET["obj_id"]); - } else - { - if ($this->lm->getTOCMode() == "pages") - { - if ($this->deactivated_page) - { - $exp->setHighlightNode($_GET["obj_id"]); - } else - { - $exp->setHighlightNode($page_id); - } - } else - { - $exp->setHighlightNode($this->lm_tree->getParentId($page_id)); - } - } - } - if ($this->offlineMode()) - { - $exp->setOfflineMode(true); - } -// var_dump($exp->getHTML()."_"); - $this->tpl->setVariable("ADM_CONTENT", $exp->getHTML()); - } - if ($this->offlineMode()) - { - // reset standard css files - $this->tpl->resetJavascript(); - $this->tpl->resetCss(); - $this->tpl->setBodyClass("ilLMNoMenu"); - - include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); - foreach (ilObjContentObject::getSupplyingExportFiles() as $f) - { - if ($f["type"] == "js") - { - $this->tpl->addJavascript($f["target"]); - } - if ($f["type"] == "css") - { - $this->tpl->addCSS($f["target"]); - } - } - $this->tpl->fillJavaScriptFiles(true); - $this->tpl->fillOnLoadCode(); - //var_dump(htmlentities($this->tpl->get())); exit; - return $this->tpl->get(); - } - else - { - $this->tpl->show(); - } - } - - - /** - * 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->outputInfoScreen(); - } - - /** - * info screen call from inside learning module - */ - function showInfoScreen() - { - $this->outputInfoScreen(true); - } - - protected function initScreenHead($a_active_tab = "info") - { - $ilAccess = $this->access; - $ilLocator = $this->locator; - $ilUser = $this->user; - - $this->renderPageTitle(); - - // set style sheets - if (!$this->offlineMode()) - { - $this->tpl->setStyleSheetLocation(ilUtil::getStyleSheetLocation()); - } - else - { - $style_name = $ilUser->getPref("style").".css";; - $this->tpl->setStyleSheetLocation("./".$style_name); - } - - $this->tpl->getStandardTemplate(); - $this->tpl->setTitle($this->getLMPresentationTitle()); - $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_lm.svg")); - - $this->tpl->setVariable("TABS", $this->lm_gui->setilLMMenu($this->offlineMode() - ,$this->getExportFormat(), $a_active_tab, true, false, 0, - $this->lang, $this->export_all_languages)); - - // Full locator, if read permission is given - if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - $this->ilLocator(true); - } - else - { - $ilLocator->addRepositoryItems(); - $this->tpl->setLocator(); - } - } - - /** - * info screen - */ - function outputInfoScreen($a_standard_locator = false) - { - $ilAccess = $this->access; - - $this->initScreenHead(); - - $this->lng->loadLanguageModule("meta"); - - include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); - - $info = new ilInfoScreenGUI($this->lm_gui); - $info->enablePrivateNotes(); - $info->enableLearningProgress(); - - $info->enableNews(); - if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) - { - $news_set = new ilSetting("news"); - $enable_internal_rss = $news_set->get("enable_rss_for_internal"); - - $info->enableNewsEditing(); - - if ($enable_internal_rss) - { - $info->setBlockProperty("news", "settings", true); - } - } - - // add read / back button - /* - if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - if ($_GET["obj_id"] > 0) - { - $this->ctrl->setParameter($this, "obj_id", $_GET["obj_id"]); - $info->addButton($this->lng->txt("back"), - $this->ctrl->getLinkTarget($this, "layout")); - } - else - { - $info->addButton($this->lng->txt("view"), - $this->ctrl->getLinkTarget($this, "layout")); - } - }*/ - - // show standard meta data section - $info->addMetaDataSections($this->lm->getId(),0, $this->lm->getType()); - - if ($this->offlineMode()) - { - $this->tpl->setContent($info->getHTML()); - return $this->tpl->get(); - } - else - { - // forward the command - $this->ctrl->forwardCommand($info); - //$this->tpl->setContent("aa"); - $this->tpl->show(); - } - } - - /** - * show selection screen for print view - */ - function showPrintViewSelection() - { - $ilUser = $this->user; - $lng = $this->lng; - - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - if (!$this->lm->isActivePrintView() || !$this->lm->isActiveLMMenu()) - { - return; - } - - include_once("./Modules/LearningModule/classes/class.ilStructureObject.php"); - - //$this->tpl = new ilTemplate("tpl.lm_toc.html", true, true, true); - $this->tpl->setCurrentBlock("ContentStyle"); - if (!$this->offlineMode()) - { - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->lm->getStyleSheetId())); - } - else - { - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", "content_style/content.css"); - } - $this->tpl->parseCurrentBlock(); - - $this->renderPageTitle(); - $this->tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); - $this->tpl->getStandardTemplate(); - - $this->tpl->setVariable("TABS", $this->lm_gui->setilLMMenu($this->offlineMode() - ,$this->getExportFormat(), "print", true,false, 0, - $this->lang, $this->export_all_languages)); - - $this->ilLocator(true); - $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", - "tpl.lm_print_selection.html", "Modules/LearningModule"); - - // set title header - $this->tpl->setTitle($this->getLMPresentationTitle()); - $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_lm.svg")); - - /*$this->tpl->setVariable("TXT_BACK", $this->lng->txt("back")); - $this->ctrl->setParameterByClass("illmpresentationgui", "obj_id", $_GET["obj_id"]); - $this->tpl->setVariable("LINK_BACK", - $this->ctrl->getLinkTargetByClass("illmpresentationgui", ""));*/ - - $this->ctrl->setParameterByClass("illmpresentationgui", "obj_id", $_GET["obj_id"]); - $this->tpl->setVariable("FORMACTION", $this->ctrl->getFormaction($this)); - - $nodes = $this->lm_tree->getSubtree($this->lm_tree->getNodeData($this->lm_tree->getRootId())); - $nodes = $this->filterNonAccessibleNode($nodes); - - if (!is_array($_POST["item"])) - { - if ($_GET["obj_id"] != "") - { - $_POST["item"][$_GET["obj_id"]] = "y"; - } - else - { - $_POST["item"][1] = "y"; - } - } - - $this->initPrintViewSelectionForm(); - - foreach ($nodes as $node) - { - - // check page activation - $active = ilLMPage::_lookupActive($node["obj_id"], $this->lm->getType(), - $this->lm_set->get("time_scheduled_page_activation")); - - if ($node["type"] == "pg" && - !$active) - { - continue; - } - - $text = $img_scr = $img_alt = ""; - $disabled = false; - $checked = false; - - switch ($node["type"]) - { - // page - case "pg": - $text = - ilLMPageObject::_getPresentationTitle($node["obj_id"], - $this->lm->getPageHeader(), $this->lm->isActiveNumbering(), - $this->lm_set->get("time_scheduled_page_activation"), false, 0, $this->lang); - - if($ilUser->getId() == ANONYMOUS_USER_ID && - $this->lm_gui->object->getPublicAccessMode() == "selected") - { - if (!ilLMObject::_isPagePublic($node["obj_id"])) - { - $disabled = true; - $text.= " (".$this->lng->txt("cont_no_access").")"; - } - } - $img_src = ilUtil::getImagePath("icon_pg.svg"); - $img_alt = $lng->txt("icon")." ".$lng->txt("pg"); - break; - - // learning module - case "du": - $text = $this->getLMPresentationTitle(); - $img_src = ilUtil::getImagePath("icon_lm.svg"); - $img_alt = $lng->txt("icon")." ".$lng->txt("obj_lm"); - break; - - // chapter - case "st": - $text = - ilStructureObject::_getPresentationTitle($node["obj_id"], IL_CHAPTER_TITLE, - $this->lm->isActiveNumbering(), - $this->lm_set->get("time_scheduled_page_activation"), false, 0, $this->lang); - if($ilUser->getId() == ANONYMOUS_USER_ID && - $this->lm_gui->object->getPublicAccessMode() == "selected") - { - if (!ilLMObject::_isPagePublic($node["obj_id"])) - { - $disabled = true; - $text.= " (".$this->lng->txt("cont_no_access").")"; - } - } - $img_src = ilUtil::getImagePath("icon_st.svg"); - $img_alt = $lng->txt("icon")." ".$lng->txt("st"); - break; - } - - if (!ilObjContentObject::_checkPreconditionsOfPage($this->lm->getRefId(),$this->lm->getId(), $node["obj_id"])) - { - $text.= " (".$this->lng->txt("cont_no_access").")"; - } - - $this->nl->addListNode($node["obj_id"], $text, $node["parent"], $checked, $disabled, - $img_src, $img_alt); - } - - - // check for free page - if ($_GET["obj_id"] > 0 && !$this->lm_tree->isInTree($_GET["obj_id"])) - { - $text = - ilLMPageObject::_getPresentationTitle($_GET["obj_id"], - $this->lm->getPageHeader(), $this->lm->isActiveNumbering(), - $this->lm_set->get("time_scheduled_page_activation"), false, 0, $this->lang); - - if($ilUser->getId() == ANONYMOUS_USER_ID && - $this->lm_gui->object->getPublicAccessMode() == "selected") - { - if (!ilLMObject::_isPagePublic($_GET["obj_id"])) - { - $disabled = true; - $text.= " (".$this->lng->txt("cont_no_access").")"; - } - } - $img_src = ilUtil::getImagePath("icon_pg.svg"); - $id = $_GET["obj_id"]; - - $checked = true; - - $this->nl->addListNode($id, $text, 0, $checked, $disabled, - $img_src, $img_alt); - } - - $f = $this->form->getHTML(); - - // submit toolbar - $tb = new ilToolbarGUI(); - $tb->addFormButton($lng->txt("cont_show_print_view"), "showPrintView"); - $this->tpl->setVariable("TOOLBAR", $tb->getHTML()); - - $this->tpl->setVariable("ITEM_SELECTION", $f); - $this->tpl->show(); - - } + public function showInfoScreen() + { + $this->outputInfoScreen(true); + } + + protected function initScreenHead($a_active_tab = "info") + { + $ilAccess = $this->access; + $ilLocator = $this->locator; + $ilUser = $this->user; + + $this->renderPageTitle(); + + // set style sheets + if (!$this->offlineMode()) { + $this->tpl->setStyleSheetLocation(ilUtil::getStyleSheetLocation()); + } else { + $style_name = $ilUser->getPref("style") . ".css"; + ; + $this->tpl->setStyleSheetLocation("./" . $style_name); + } + + $this->tpl->getStandardTemplate(); + $this->tpl->setTitle($this->getLMPresentationTitle()); + $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_lm.svg")); + + $this->tpl->setVariable("TABS", $this->lm_gui->setilLMMenu( + $this->offlineMode() + , + $this->getExportFormat(), + $a_active_tab, + true, + false, + 0, + $this->lang, + $this->export_all_languages + )); + + // Full locator, if read permission is given + if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) { + $this->ilLocator(true); + } else { + $ilLocator->addRepositoryItems(); + $this->tpl->setLocator(); + } + } + + /** + * info screen + */ + public function outputInfoScreen($a_standard_locator = false) + { + $ilAccess = $this->access; + + $this->initScreenHead(); + + $this->lng->loadLanguageModule("meta"); + + include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); + + $info = new ilInfoScreenGUI($this->lm_gui); + $info->enablePrivateNotes(); + $info->enableLearningProgress(); + + $info->enableNews(); + if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) { + $news_set = new ilSetting("news"); + $enable_internal_rss = $news_set->get("enable_rss_for_internal"); + + $info->enableNewsEditing(); + + if ($enable_internal_rss) { + $info->setBlockProperty("news", "settings", true); + } + } + + // add read / back button + /* + if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) + { + if ($_GET["obj_id"] > 0) + { + $this->ctrl->setParameter($this, "obj_id", $_GET["obj_id"]); + $info->addButton($this->lng->txt("back"), + $this->ctrl->getLinkTarget($this, "layout")); + } + else + { + $info->addButton($this->lng->txt("view"), + $this->ctrl->getLinkTarget($this, "layout")); + } + }*/ + + // show standard meta data section + $info->addMetaDataSections($this->lm->getId(), 0, $this->lm->getType()); + + if ($this->offlineMode()) { + $this->tpl->setContent($info->getHTML()); + return $this->tpl->get(); + } else { + // forward the command + $this->ctrl->forwardCommand($info); + //$this->tpl->setContent("aa"); + $this->tpl->show(); + } + } + + /** + * show selection screen for print view + */ + public function showPrintViewSelection() + { + $ilUser = $this->user; + $lng = $this->lng; + + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + if (!$this->lm->isActivePrintView() || !$this->lm->isActiveLMMenu()) { + return; + } + + include_once("./Modules/LearningModule/classes/class.ilStructureObject.php"); + + //$this->tpl = new ilTemplate("tpl.lm_toc.html", true, true, true); + $this->tpl->setCurrentBlock("ContentStyle"); + if (!$this->offlineMode()) { + $this->tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath($this->lm->getStyleSheetId()) + ); + } else { + $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", "content_style/content.css"); + } + $this->tpl->parseCurrentBlock(); + + $this->renderPageTitle(); + $this->tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); + $this->tpl->getStandardTemplate(); + + $this->tpl->setVariable("TABS", $this->lm_gui->setilLMMenu( + $this->offlineMode() + , + $this->getExportFormat(), + "print", + true, + false, + 0, + $this->lang, + $this->export_all_languages + )); + + $this->ilLocator(true); + $this->tpl->addBlockFile( + "ADM_CONTENT", + "adm_content", + "tpl.lm_print_selection.html", + "Modules/LearningModule" + ); + + // set title header + $this->tpl->setTitle($this->getLMPresentationTitle()); + $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_lm.svg")); + + /*$this->tpl->setVariable("TXT_BACK", $this->lng->txt("back")); + $this->ctrl->setParameterByClass("illmpresentationgui", "obj_id", $_GET["obj_id"]); + $this->tpl->setVariable("LINK_BACK", + $this->ctrl->getLinkTargetByClass("illmpresentationgui", ""));*/ + + $this->ctrl->setParameterByClass("illmpresentationgui", "obj_id", $_GET["obj_id"]); + $this->tpl->setVariable("FORMACTION", $this->ctrl->getFormaction($this)); + + $nodes = $this->lm_tree->getSubtree($this->lm_tree->getNodeData($this->lm_tree->getRootId())); + $nodes = $this->filterNonAccessibleNode($nodes); + + if (!is_array($_POST["item"])) { + if ($_GET["obj_id"] != "") { + $_POST["item"][$_GET["obj_id"]] = "y"; + } else { + $_POST["item"][1] = "y"; + } + } + + $this->initPrintViewSelectionForm(); + + foreach ($nodes as $node) { + + // check page activation + $active = ilLMPage::_lookupActive( + $node["obj_id"], + $this->lm->getType(), + $this->lm_set->get("time_scheduled_page_activation") + ); + + if ($node["type"] == "pg" && + !$active) { + continue; + } + + $text = $img_scr = $img_alt = ""; + $disabled = false; + $checked = false; + + switch ($node["type"]) { + // page + case "pg": + $text = + ilLMPageObject::_getPresentationTitle( + $node["obj_id"], + $this->lm->getPageHeader(), + $this->lm->isActiveNumbering(), + $this->lm_set->get("time_scheduled_page_activation"), + false, + 0, + $this->lang + ); + + if ($ilUser->getId() == ANONYMOUS_USER_ID && + $this->lm_gui->object->getPublicAccessMode() == "selected") { + if (!ilLMObject::_isPagePublic($node["obj_id"])) { + $disabled = true; + $text.= " (" . $this->lng->txt("cont_no_access") . ")"; + } + } + $img_src = ilUtil::getImagePath("icon_pg.svg"); + $img_alt = $lng->txt("icon") . " " . $lng->txt("pg"); + break; + + // learning module + case "du": + $text = $this->getLMPresentationTitle(); + $img_src = ilUtil::getImagePath("icon_lm.svg"); + $img_alt = $lng->txt("icon") . " " . $lng->txt("obj_lm"); + break; + + // chapter + case "st": + $text = + ilStructureObject::_getPresentationTitle( + $node["obj_id"], + IL_CHAPTER_TITLE, + $this->lm->isActiveNumbering(), + $this->lm_set->get("time_scheduled_page_activation"), + false, + 0, + $this->lang + ); + if ($ilUser->getId() == ANONYMOUS_USER_ID && + $this->lm_gui->object->getPublicAccessMode() == "selected") { + if (!ilLMObject::_isPagePublic($node["obj_id"])) { + $disabled = true; + $text.= " (" . $this->lng->txt("cont_no_access") . ")"; + } + } + $img_src = ilUtil::getImagePath("icon_st.svg"); + $img_alt = $lng->txt("icon") . " " . $lng->txt("st"); + break; + } + + if (!ilObjContentObject::_checkPreconditionsOfPage($this->lm->getRefId(), $this->lm->getId(), $node["obj_id"])) { + $text.= " (" . $this->lng->txt("cont_no_access") . ")"; + } + + $this->nl->addListNode( + $node["obj_id"], + $text, + $node["parent"], + $checked, + $disabled, + $img_src, + $img_alt + ); + } + + + // check for free page + if ($_GET["obj_id"] > 0 && !$this->lm_tree->isInTree($_GET["obj_id"])) { + $text = + ilLMPageObject::_getPresentationTitle( + $_GET["obj_id"], + $this->lm->getPageHeader(), + $this->lm->isActiveNumbering(), + $this->lm_set->get("time_scheduled_page_activation"), + false, + 0, + $this->lang + ); + + if ($ilUser->getId() == ANONYMOUS_USER_ID && + $this->lm_gui->object->getPublicAccessMode() == "selected") { + if (!ilLMObject::_isPagePublic($_GET["obj_id"])) { + $disabled = true; + $text.= " (" . $this->lng->txt("cont_no_access") . ")"; + } + } + $img_src = ilUtil::getImagePath("icon_pg.svg"); + $id = $_GET["obj_id"]; + + $checked = true; + + $this->nl->addListNode( + $id, + $text, + 0, + $checked, + $disabled, + $img_src, + $img_alt + ); + } + + $f = $this->form->getHTML(); + + // submit toolbar + $tb = new ilToolbarGUI(); + $tb->addFormButton($lng->txt("cont_show_print_view"), "showPrintView"); + $this->tpl->setVariable("TOOLBAR", $tb->getHTML()); + + $this->tpl->setVariable("ITEM_SELECTION", $f); + $this->tpl->show(); + } /** * @param array $nodes @@ -3301,8 +3136,7 @@ class ilLMPresentationGUI $tracker = $this->getTracker(); // if navigation is restricted based on correct answered questions // check if we have preceeding pages including unsanswered/incorrect answered questions - if (!$this->offlineMode()) - { + if (!$this->offlineMode()) { if ($this->lm->getRestrictForwardNavigation()) { $nodes = array_filter($nodes, function ($node) use ($tracker) { return !$tracker->hasPredIncorrectAnswers($node["child"]); @@ -3313,1156 +3147,1081 @@ class ilLMPresentationGUI } - /** - * Init print view selection form. - */ - public function initPrintViewSelectionForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - // 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("cont_current_chapter"), "chapter"); - $radg->addOption($op2); - $op3= new ilRadioOption($lng->txt("cont_selected_pg_chap"), "selection"); - $radg->addOption($op3); - - include_once("./Services/Form/classes/class.ilNestedListInputGUI.php"); - $nl = new ilNestedListInputGUI("", "obj_id"); - $this->nl = $nl; - $op3->addSubItem($nl); - - - $this->form->addItem($radg); - - $this->form->addCommandButton("showPrintView", $lng->txt("cont_show_print_view")); - $this->form->setOpenTag(false); - $this->form->setCloseTag(false); - - $this->form->setTitle($lng->txt("cont_print_selection")); - $this->form->setFormAction($ilCtrl->getFormAction($this)); - } - - /** - * show print view - */ - function showPrintView() - { - $ilUser = $this->user; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - - if (!$this->lm->isActivePrintView() || !$this->lm->isActiveLMMenu()) - { - return; - } - - $this->renderPageTitle(); - - $c_obj_id = $this->getCurrentPageId(); - // set values according to selection - if ($_POST["sel_type"] == "page") - { - if (!is_array($_POST["obj_id"]) || !in_array($c_obj_id, $_POST["obj_id"])) - { - $_POST["obj_id"][] = $c_obj_id; - } - } - if ($_POST["sel_type"] == "chapter" && $c_obj_id > 0) - { - - $path = $this->lm_tree->getPathFull($c_obj_id); - $chap_id = $path[1]["child"]; - if ($chap_id > 0) - { - $_POST["obj_id"][] = $chap_id; - } - } - -//var_dump($_GET); -//var_dump($_POST); - // set style sheets - if (!$this->offlineMode()) - { - $this->tpl->setVariable("LOCATION_STYLESHEET", ilObjStyleSheet::getContentPrintStyle()); - } - else - { - $style_name = $ilUser->getPref("style").".css";; - $this->tpl->setVariable("LOCATION_STYLESHEET","./style/".$style_name); - } - - // content style - $this->tpl->setCurrentBlock("ContentStyle"); - if (!$this->offlineMode()) - { - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->lm->getStyleSheetId())); - } - else - { - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", "content_style/content.css"); - } - $this->tpl->parseCurrentBlock(); - - // syntax style - $this->tpl->setCurrentBlock("SyntaxStyle"); - $this->tpl->setVariable("LOCATION_SYNTAX_STYLESHEET", - ilObjStyleSheet::getSyntaxStylePath()); - $this->tpl->parseCurrentBlock(); - - //$this->tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); - $this->tpl->addBlockFile("CONTENT", "content", "tpl.lm_print_view.html", true); - - // set title header - $this->tpl->setVariable("HEADER", $this->getLMPresentationTitle()); - - $nodes = $this->lm_tree->getSubtree($this->lm_tree->getNodeData($this->lm_tree->getRootId())); - - include_once("./Modules/LearningModule/classes/class.ilLMPageGUI.php"); - include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); - include_once("./Modules/LearningModule/classes/class.ilStructureObject.php"); - - $act_level = 99999; - $activated = false; - - $glossary_links = array(); - $output_header = false; - $media_links = array(); - - // get header and footer - if ($this->lm->getFooterPage() > 0 && !$this->lm->getHideHeaderFooterPrint()) - { - if (ilLMObject::_exists($this->lm->getFooterPage())) - { - $page_object_gui = $this->getLMPageGUI($this->lm->getFooterPage()); - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $page_object_gui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId( - $this->lm->getStyleSheetId(), "lm")); - - - // determine target frames for internal links - $page_object_gui->setLinkFrame($_GET["frame"]); - $page_object_gui->setOutputMode("print"); - $page_object_gui->setPresentationTitle(""); - $page_object_gui->setFileDownloadLink("#"); - $page_object_gui->setFullscreenLink("#"); - $page_object_gui->setSourceCodeDownloadScript("#"); - $footer_page_content = $page_object_gui->showPage(); - } - } - if ($this->lm->getHeaderPage() > 0 && !$this->lm->getHideHeaderFooterPrint()) - { - if (ilLMObject::_exists($this->lm->getHeaderPage())) - { - $page_object_gui = $this->getLMPageGUI($this->lm->getHeaderPage()); - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $page_object_gui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId( - $this->lm->getStyleSheetId(), "lm")); - - - // determine target frames for internal links - $page_object_gui->setLinkFrame($_GET["frame"]); - $page_object_gui->setOutputMode("print"); - $page_object_gui->setPresentationTitle(""); - $page_object_gui->setFileDownloadLink("#"); - $page_object_gui->setFullscreenLink("#"); - $page_object_gui->setSourceCodeDownloadScript("#"); - $header_page_content = $page_object_gui->showPage(); - } - } - - // add free selected pages - if (is_array($_POST["obj_id"])) - { - foreach($_POST["obj_id"] as $k) - { - if ($k > 0 && !$this->lm_tree->isInTree($k)) - { - if (ilLMObject::_lookupType($k) == "pg") - { - $nodes[] = array("obj_id" => $k, "type" => "pg", "free" => true); - } - } - } - } - else - { - ilUtil::sendFailure($lng->txt("cont_print_no_page_selected"),true); - $ilCtrl->redirect($this, "showPrintViewSelection"); - } - - foreach ($nodes as $node_key => $node) - { - // check page activation - $active = ilLMPage::_lookupActive($node["obj_id"], $this->lm->getType(), - $this->lm_set->get("time_scheduled_page_activation")); - if ($node["type"] == "pg" && !$active) - { - continue; - } - - // print all subchapters/subpages if higher chapter - // has been selected - if ($node["depth"] <= $act_level) - { - if (is_array($_POST["obj_id"]) && in_array($node["obj_id"], $_POST["obj_id"])) - { - $act_level = $node["depth"]; - $activated = true; - } - else - { - $act_level = 99999; - $activated = false; - } - } + /** + * Init print view selection form. + */ + public function initPrintViewSelectionForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + // 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("cont_current_chapter"), "chapter"); + $radg->addOption($op2); + $op3= new ilRadioOption($lng->txt("cont_selected_pg_chap"), "selection"); + $radg->addOption($op3); + + include_once("./Services/Form/classes/class.ilNestedListInputGUI.php"); + $nl = new ilNestedListInputGUI("", "obj_id"); + $this->nl = $nl; + $op3->addSubItem($nl); + + + $this->form->addItem($radg); + + $this->form->addCommandButton("showPrintView", $lng->txt("cont_show_print_view")); + $this->form->setOpenTag(false); + $this->form->setCloseTag(false); + + $this->form->setTitle($lng->txt("cont_print_selection")); + $this->form->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * show print view + */ + public function showPrintView() + { + $ilUser = $this->user; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + + if (!$this->lm->isActivePrintView() || !$this->lm->isActiveLMMenu()) { + return; + } + + $this->renderPageTitle(); + + $c_obj_id = $this->getCurrentPageId(); + // set values according to selection + if ($_POST["sel_type"] == "page") { + if (!is_array($_POST["obj_id"]) || !in_array($c_obj_id, $_POST["obj_id"])) { + $_POST["obj_id"][] = $c_obj_id; + } + } + if ($_POST["sel_type"] == "chapter" && $c_obj_id > 0) { + $path = $this->lm_tree->getPathFull($c_obj_id); + $chap_id = $path[1]["child"]; + if ($chap_id > 0) { + $_POST["obj_id"][] = $chap_id; + } + } + + //var_dump($_GET); + //var_dump($_POST); + // set style sheets + if (!$this->offlineMode()) { + $this->tpl->setVariable("LOCATION_STYLESHEET", ilObjStyleSheet::getContentPrintStyle()); + } else { + $style_name = $ilUser->getPref("style") . ".css"; + ; + $this->tpl->setVariable("LOCATION_STYLESHEET", "./style/" . $style_name); + } + + // content style + $this->tpl->setCurrentBlock("ContentStyle"); + if (!$this->offlineMode()) { + $this->tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath($this->lm->getStyleSheetId()) + ); + } else { + $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", "content_style/content.css"); + } + $this->tpl->parseCurrentBlock(); + + // syntax style + $this->tpl->setCurrentBlock("SyntaxStyle"); + $this->tpl->setVariable( + "LOCATION_SYNTAX_STYLESHEET", + ilObjStyleSheet::getSyntaxStylePath() + ); + $this->tpl->parseCurrentBlock(); + + //$this->tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); + $this->tpl->addBlockFile("CONTENT", "content", "tpl.lm_print_view.html", true); + + // set title header + $this->tpl->setVariable("HEADER", $this->getLMPresentationTitle()); + + $nodes = $this->lm_tree->getSubtree($this->lm_tree->getNodeData($this->lm_tree->getRootId())); + + include_once("./Modules/LearningModule/classes/class.ilLMPageGUI.php"); + include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); + include_once("./Modules/LearningModule/classes/class.ilStructureObject.php"); + + $act_level = 99999; + $activated = false; + + $glossary_links = array(); + $output_header = false; + $media_links = array(); + + // get header and footer + if ($this->lm->getFooterPage() > 0 && !$this->lm->getHideHeaderFooterPrint()) { + if (ilLMObject::_exists($this->lm->getFooterPage())) { + $page_object_gui = $this->getLMPageGUI($this->lm->getFooterPage()); + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $page_object_gui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId( + $this->lm->getStyleSheetId(), + "lm" + )); + + + // determine target frames for internal links + $page_object_gui->setLinkFrame($_GET["frame"]); + $page_object_gui->setOutputMode("print"); + $page_object_gui->setPresentationTitle(""); + $page_object_gui->setFileDownloadLink("#"); + $page_object_gui->setFullscreenLink("#"); + $page_object_gui->setSourceCodeDownloadScript("#"); + $footer_page_content = $page_object_gui->showPage(); + } + } + if ($this->lm->getHeaderPage() > 0 && !$this->lm->getHideHeaderFooterPrint()) { + if (ilLMObject::_exists($this->lm->getHeaderPage())) { + $page_object_gui = $this->getLMPageGUI($this->lm->getHeaderPage()); + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $page_object_gui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId( + $this->lm->getStyleSheetId(), + "lm" + )); + + + // determine target frames for internal links + $page_object_gui->setLinkFrame($_GET["frame"]); + $page_object_gui->setOutputMode("print"); + $page_object_gui->setPresentationTitle(""); + $page_object_gui->setFileDownloadLink("#"); + $page_object_gui->setFullscreenLink("#"); + $page_object_gui->setSourceCodeDownloadScript("#"); + $header_page_content = $page_object_gui->showPage(); + } + } + + // add free selected pages + if (is_array($_POST["obj_id"])) { + foreach ($_POST["obj_id"] as $k) { + if ($k > 0 && !$this->lm_tree->isInTree($k)) { + if (ilLMObject::_lookupType($k) == "pg") { + $nodes[] = array("obj_id" => $k, "type" => "pg", "free" => true); + } + } + } + } else { + ilUtil::sendFailure($lng->txt("cont_print_no_page_selected"), true); + $ilCtrl->redirect($this, "showPrintViewSelection"); + } + + foreach ($nodes as $node_key => $node) { + // check page activation + $active = ilLMPage::_lookupActive( + $node["obj_id"], + $this->lm->getType(), + $this->lm_set->get("time_scheduled_page_activation") + ); + if ($node["type"] == "pg" && !$active) { + continue; + } + + // print all subchapters/subpages if higher chapter + // has been selected + if ($node["depth"] <= $act_level) { + if (is_array($_POST["obj_id"]) && in_array($node["obj_id"], $_POST["obj_id"])) { + $act_level = $node["depth"]; + $activated = true; + } else { + $act_level = 99999; + $activated = false; + } + } if ($this->lm->getRestrictForwardNavigation()) { if ($this->getTracker()->hasPredIncorrectAnswers($node["obj_id"])) { continue; } } - if ($activated && - ilObjContentObject::_checkPreconditionsOfPage($this->lm->getRefId(),$this->lm->getId(), $node["obj_id"])) - { - // output learning module header - if ($node["type"] == "du") - { - $output_header = true; - } - - // output chapter title - if ($node["type"] == "st") - { - if($ilUser->getId() == ANONYMOUS_USER_ID && - $this->lm_gui->object->getPublicAccessMode() == "selected") - { - if (!ilLMObject::_isPagePublic($node["obj_id"])) - { - continue; - } - } - - $chap = new ilStructureObject($this->lm, $node["obj_id"]); - $this->tpl->setCurrentBlock("print_chapter"); - - $chapter_title = $chap->_getPresentationTitle($node["obj_id"], - $this->lm->isActiveNumbering(), - $this->lm_set->get("time_scheduled_page_activation"), 0, $this->lang); - $this->tpl->setVariable("CHAP_TITLE", - $chapter_title); - - if ($this->lm->getPageHeader() == IL_CHAPTER_TITLE) - { - if ($nodes[$node_key + 1]["type"] == "pg") - { - $this->tpl->setVariable("CHAP_HEADER", - $header_page_content); - $did_chap_page_header = true; - } - } - - $this->tpl->parseCurrentBlock(); - $this->tpl->setCurrentBlock("print_block"); - $this->tpl->parseCurrentBlock(); - } - - // output page - if ($node["type"] == "pg") - { - if($ilUser->getId() == ANONYMOUS_USER_ID && - $this->lm_gui->object->getPublicAccessMode() == "selected") - { - if (!ilLMObject::_isPagePublic($node["obj_id"])) - { - continue; - } - } - - $this->tpl->setCurrentBlock("print_item"); - - // get page - $page_id = $node["obj_id"]; - $page_object_gui = $this->getLMPageGUI($page_id); - $page_object = $page_object_gui->getPageObject(); - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $page_object_gui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId( - $this->lm->getStyleSheetId(), "lm")); - - - // get lm page - $lm_pg_obj = new ilLMPageObject($this->lm, $page_id); - $lm_pg_obj->setLMId($this->lm->getId()); - - // determine target frames for internal links - $page_object_gui->setLinkFrame($_GET["frame"]); - $page_object_gui->setOutputMode("print"); - $page_object_gui->setPresentationTitle(""); - - if ($this->lm->getPageHeader() == IL_PAGE_TITLE || $node["free"] === true) - { - $page_title = ilLMPageObject::_getPresentationTitle($lm_pg_obj->getId(), - $this->lm->getPageHeader(), $this->lm->isActiveNumbering(), - $this->lm_set->get("time_scheduled_page_activation"), false, 0, $this->lang); - - // prevent page title after chapter title - // that have the same content - if ($this->lm->isActiveNumbering()) - { - $chapter_title = trim(substr($chapter_title, - strpos($chapter_title, " "))); - } - - if ($page_title != $chapter_title) - { - $page_object_gui->setPresentationTitle($page_title); - } - } - - // handle header / footer - $hcont = $header_page_content; - $fcont = $footer_page_content; - - if ($this->lm->getPageHeader() == IL_CHAPTER_TITLE) - { - if ($did_chap_page_header) - { - $hcont = ""; - } - if ($nodes[$node_key + 1]["type"] == "pg" && - !($nodes[$node_key + 1]["depth"] <= $act_level - && !in_array($nodes[$node_key + 1]["obj_id"], $_POST["obj_id"]))) - { - $fcont = ""; - } - } - - $page_object_gui->setFileDownloadLink("#"); - $page_object_gui->setFullscreenLink("#"); - $page_object_gui->setSourceCodeDownloadScript("#"); - $page_content = $page_object_gui->showPage(); - if ($this->lm->getPageHeader() != IL_PAGE_TITLE) - { - $this->tpl->setVariable("CONTENT", - $hcont.$page_content.$fcont); - } - else - { - $this->tpl->setVariable("CONTENT", - $hcont.$page_content.$fcont."
"); - } - $chapter_title = ""; - $this->tpl->parseCurrentBlock(); - $this->tpl->setCurrentBlock("print_block"); - $this->tpl->parseCurrentBlock(); - - // get internal links - $int_links = ilInternalLink::_getTargetsOfSource($this->lm->getType().":pg", $node["obj_id"]); - - $got_mobs = false; - - foreach ($int_links as $key => $link) - { - if ($link["type"] == "git" && - ($link["inst"] == IL_INST_ID || $link["inst"] == 0)) - { - $glossary_links[$key] = $link; - } - if ($link["type"] == "mob" && - ($link["inst"] == IL_INST_ID || $link["inst"] == 0)) - { - $got_mobs = true; - $mob_links[$key] = $link; - } - } - - // this is not cool because of performance reasons - // unfortunately the int link table does not - // store the target frame (we want to append all linked - // images but not inline images (i.e. mobs with no target - // frame)) - if ($got_mobs) - { - $page_object->buildDom(); - $links = $page_object->getInternalLinks(); - foreach($links as $link) - { - if ($link["Type"] == "MediaObject" - && $link["TargetFrame"] != "" - && $link["TargetFrame"] != "None") - { - $media_links[] = $link; - } - } - } - } - } - } - - $annex_cnt = 0; - $annexes = array(); - - // glossary - if (count($glossary_links) > 0 && !$this->lm->isActivePreventGlossaryAppendix()) - { - include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - include_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); - - // sort terms - $terms = array(); - - foreach($glossary_links as $key => $link) - { - $term = ilGlossaryTerm::_lookGlossaryTerm($link["id"]); - $terms[$term.":".$key] = array("key" => $key, "link" => $link, "term" => $term); - } - $terms = ilUtil::sortArray($terms, "term", "asc"); - //ksort($terms); - - foreach($terms as $t) - { - $link = $t["link"]; - $key = $t["key"]; - $defs = ilGlossaryDefinition::getDefinitionList($link["id"]); - $def_cnt = 1; - - // output all definitions of term - foreach($defs as $def) - { - // definition + number, if more than 1 definition - if (count($defs) > 1) - { - $this->tpl->setCurrentBlock("def_title"); - $this->tpl->setVariable("TXT_DEFINITION", - $this->lng->txt("cont_definition")." ".($def_cnt++)); - $this->tpl->parseCurrentBlock(); - } - include_once("./Modules/Glossary/classes/class.ilGlossaryDefPageGUI.php"); - $page_gui = new ilGlossaryDefPageGUI($def["id"]); - $page_gui->setTemplateOutput(false); - $page_gui->setOutputMode("print"); - - $this->tpl->setCurrentBlock("definition"); - $page_gui->setFileDownloadLink("#"); - $page_gui->setFullscreenLink("#"); - $page_gui->setSourceCodeDownloadScript("#"); - $output = $page_gui->showPage(); - $this->tpl->setVariable("VAL_DEFINITION", $output); - $this->tpl->parseCurrentBlock(); - } - - // output term - $this->tpl->setCurrentBlock("term"); - $this->tpl->setVariable("VAL_TERM", - $term = ilGlossaryTerm::_lookGlossaryTerm($link["id"])); - $this->tpl->parseCurrentBlock(); - } - - // output glossary header - $annex_cnt++; - $this->tpl->setCurrentBlock("glossary"); - $annex_title = $this->lng->txt("cont_annex")." ". - chr(64+$annex_cnt).": ".$this->lng->txt("glo"); - $this->tpl->setVariable("TXT_GLOSSARY", $annex_title); - $this->tpl->parseCurrentBlock(); - - $annexes[] = $annex_title; - } - - // referenced images - if (count($media_links) > 0) - { - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - include_once("./Services/MediaObjects/classes/class.ilMediaItem.php"); - - foreach($media_links as $media) - { - if (substr($media["Target"],0,4) == "il__") - { - $arr = explode("_",$media["Target"]); - $id = $arr[count($arr) - 1]; - - $med_obj = new ilObjMediaObject($id); - $med_item = $med_obj->getMediaItem("Standard"); - if (is_object($med_item)) - { - if (is_int(strpos($med_item->getFormat(), "image"))) - { - $this->tpl->setCurrentBlock("ref_image"); - - // image source - if ($med_item->getLocationType() == "LocalFile") - { - $this->tpl->setVariable("IMG_SOURCE", - ilUtil::getWebspaceDir("output")."/mobs/mm_".$id. - "/".$med_item->getLocation()); - } - else - { - $this->tpl->setVariable("IMG_SOURCE", - $med_item->getLocation()); - } - - if ($med_item->getCaption() != "") - { - $this->tpl->setVariable("IMG_TITLE", $med_item->getCaption()); - } - else - { - $this->tpl->setVariable("IMG_TITLE", $med_obj->getTitle()); - } - $this->tpl->parseCurrentBlock(); - } - } - } - } - - // output glossary header - $annex_cnt++; - $this->tpl->setCurrentBlock("ref_images"); - $annex_title = $this->lng->txt("cont_annex")." ". - chr(64+$annex_cnt).": ".$this->lng->txt("cont_ref_images"); - $this->tpl->setVariable("TXT_REF_IMAGES", $annex_title); - $this->tpl->parseCurrentBlock(); - - $annexes[] = $annex_title; - } - - // output learning module title and toc - if ($output_header) - { - $this->tpl->setCurrentBlock("print_header"); - $this->tpl->setVariable("LM_TITLE", $this->getLMPresentationTitle()); - if ($this->lm->getDescription() != "none") - { - include_once("Services/MetaData/classes/class.ilMD.php"); - $md = new ilMD($this->lm->getId(), 0, $this->lm->getType()); - $md_gen = $md->getGeneral(); - foreach($md_gen->getDescriptionIds() as $id) - { - $md_des = $md_gen->getDescription($id); - $description = $md_des->getDescription(); - } - - $this->tpl->setVariable("LM_DESCRIPTION", - $description); - } - $this->tpl->parseCurrentBlock(); - - // output toc - $nodes2 = $nodes; - foreach ($nodes2 as $node2) - { - if ($node2["type"] == "st" - && ilObjContentObject::_checkPreconditionsOfPage($this->lm->getRefId(),$this->lm->getId(), $node2["obj_id"])) - { - for ($j=1; $j < $node2["depth"]; $j++) - { - $this->tpl->setCurrentBlock("indent"); - $this->tpl->setVariable("IMG_BLANK", ilUtil::getImagePath("browser/blank.png")); - $this->tpl->parseCurrentBlock(); - } - $this->tpl->setCurrentBlock("toc_entry"); - $this->tpl->setVariable("TXT_TOC_TITLE", - ilStructureObject::_getPresentationTitle($node2["obj_id"], IL_CHAPTER_TITLE, - $this->lm->isActiveNumbering(), - $this->lm_set->get("time_scheduled_page_activation"), false, 0, $this->lang)); - $this->tpl->parseCurrentBlock(); - } - } - - // annexes - foreach ($annexes as $annex) - { - $this->tpl->setCurrentBlock("indent"); - $this->tpl->setVariable("IMG_BLANK", ilUtil::getImagePath("browser/blank.png")); - $this->tpl->parseCurrentBlock(); - $this->tpl->setCurrentBlock("toc_entry"); - $this->tpl->setVariable("TXT_TOC_TITLE", $annex); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setCurrentBlock("toc"); - $this->tpl->setVariable("TXT_TOC", $this->lng->txt("cont_toc")); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setCurrentBlock("print_start_block"); - $this->tpl->parseCurrentBlock(); - } - - // output author information - include_once 'Services/MetaData/classes/class.ilMD.php'; - $md = new ilMD($this->lm->getId(),0, $this->lm->getType()); - if(is_object($lifecycle = $md->getLifecycle())) - { - $sep = $author = ""; - foreach(($ids = $lifecycle->getContributeIds()) as $con_id) - { - $md_con = $lifecycle->getContribute($con_id); - if ($md_con->getRole() == "Author") - { - foreach($ent_ids = $md_con->getEntityIds() as $ent_id) - { - $md_ent = $md_con->getEntity($ent_id); - $author = $author.$sep.$md_ent->getEntity(); - $sep = ", "; - } - } - } - if ($author != "") - { - $this->lng->loadLanguageModule("meta"); - $this->tpl->setCurrentBlock("author"); - $this->tpl->setVariable("TXT_AUTHOR", $this->lng->txt("meta_author")); - $this->tpl->setVariable("LM_AUTHOR", $author); - $this->tpl->parseCurrentBlock(); - } - } - - - // output copyright information - if (is_object($md_rights = $md->getRights())) - { - $copyright = $md_rights->getDescription(); - include_once('Services/MetaData/classes/class.ilMDUtils.php'); - $copyright = ilMDUtils::_parseCopyright($copyright); - - if ($copyright != "") - { - $this->lng->loadLanguageModule("meta"); - $this->tpl->setCurrentBlock("copyright"); - $this->tpl->setVariable("TXT_COPYRIGHT", $this->lng->txt("meta_copyright")); - $this->tpl->setVariable("LM_COPYRIGHT", $copyright); - $this->tpl->parseCurrentBlock(); - } - } - - $this->tpl->show(false); - } - - /** - * download file of file lists - */ - function downloadFile() - { - $pg_obj = $this->getLMPage($this->getCurrentPageId()); - $pg_obj->buildDom(); - $int_links = $pg_obj->getInternalLinks(); - foreach ($int_links as $il) - { - if ($il["Target"] == str_replace("_file_", "_dfile_", $_GET["file_id"])) - { - $file = explode("_", $_GET["file_id"]); - $file_id = (int)$file[count($file) - 1]; - require_once("./Modules/File/classes/class.ilObjFile.php"); - $fileObj = new ilObjFile($file_id, false); - $fileObj->sendFile(); - exit; - } - } - if (in_array($_GET["file_id"], $pg_obj->getAllFileObjIds())) - { - require_once("./Modules/File/classes/class.ilObjFile.php"); - $file = explode("_", $_GET["file_id"]); - $file_id = (int)$file[count($file) - 1]; - $fileObj = new ilObjFile($file_id, false); - $fileObj->sendFile(); - exit; - } - } - - - /** - * download source code paragraph - */ - function download_paragraph () - { - require_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - $pg_obj = $this->getLMPage($_GET["pg_id"]); - $pg_obj->send_paragraph ($_GET["par_id"], $_GET["downloadtitle"]); - } - - /** - * show download list - */ - function showDownloadList() - { - if (!$this->lm->isActiveDownloads() || !$this->lm->isActiveLMMenu()) - { - return; - } - - //$this->tpl = new ilTemplate("tpl.lm_toc.html", true, true, true); - $this->tpl->setCurrentBlock("ContentStyle"); - if (!$this->offlineMode()) - { - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->lm->getStyleSheetId())); - } - else - { - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", "content_style/content.css"); - } - $this->tpl->parseCurrentBlock(); - - $this->renderPageTitle(); - $this->tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); - $this->tpl->getStandardTemplate(); - - $this->tpl->setVariable("TABS", $this->lm_gui->setilLMMenu($this->offlineMode() - ,$this->getExportFormat(), "download", true,false, 0, - $this->lang, $this->export_all_languages)); - - $this->ilLocator(true); - //$this->tpl->stopTitleFloating(); - $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.lm_download_list.html", "Modules/LearningModule"); - - // set title header - $this->tpl->setTitle($this->getLMPresentationTitle()); - $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_lm.svg")); - - /* - $this->tpl->setVariable("TXT_BACK", $this->lng->txt("back")); - $this->ctrl->setParameter($this, "obj_id", $_GET["obj_id"]); - $this->tpl->setVariable("LINK_BACK", - $this->ctrl->getLinkTarget($this, "")); */ - - // output copyright information - include_once 'Services/MetaData/classes/class.ilMD.php'; - $md = new ilMD($this->lm->getId(),0, $this->lm->getType()); - if (is_object($md_rights = $md->getRights())) - { - $copyright = $md_rights->getDescription(); - - include_once('Services/MetaData/classes/class.ilMDUtils.php'); - $copyright = ilMDUtils::_parseCopyright($copyright); - - if ($copyright != "") - { - $this->lng->loadLanguageModule("meta"); - $this->tpl->setCurrentBlock("copyright"); - $this->tpl->setVariable("TXT_COPYRIGHT", $this->lng->txt("meta_copyright")); - $this->tpl->setVariable("LM_COPYRIGHT", $copyright); - $this->tpl->parseCurrentBlock(); - } - } - - - include_once("./Modules/LearningModule/classes/class.ilLMDownloadTableGUI.php"); - $download_table = new ilLMDownloadTableGUI($this, "showDownloadList", $this->lm); - $this->tpl->setVariable("DOWNLOAD_TABLE", $download_table->getHTML()); - $this->tpl->show(); - } - - - /** - * send download file (xml/html) - */ - function downloadExportFile() - { - if (!$this->lm->isActiveDownloads() || !$this->lm->isActiveLMMenu()) - { - return; - } - - $base_type = explode("_", $_GET["type"]); - $base_type = $base_type[0]; - $file = $this->lm->getPublicExportFile($base_type); - if ($this->lm->getPublicExportFile($base_type) != "") - { - $dir = $this->lm->getExportDirectory($_GET["type"]); - if (is_file($dir."/".$file)) - { - ilUtil::deliverFile($dir."/".$file, $file); - exit; - } - } - } - - /** - * Get focused link (used in learning objectives courses) - * - * @param int $a_ref_id reference id of learning module - * @param int $a_obj_id chapter or page id - * @param int $a_return_ref_id return ref id - * - * @return string link - */ - function getFocusLink($a_ref_id, $a_obj_id, $a_return_ref_id) - { - return "ilias.php?baseClass=ilLMPresentationGUI&ref_id=".$a_ref_id."&obj_id=".$a_obj_id."&focus_id=". - $a_obj_id."&focus_return=".$a_return_ref_id; - } - - - /** - * handles links for learning module presentation - */ - function getLink($a_ref_id, $a_cmd = "", $a_obj_id = "", $a_frame = "", $a_type = "", - $a_back_link = "append", $a_anchor = "", $a_srcstring = "") - { - $ilCtrl = $this->ctrl; - - if ($a_cmd == "") - { - $a_cmd = "layout"; - } - - // handling of free pages - $cur_page_id = $this->getCurrentPageId(); - $back_pg = $_GET["back_pg"]; - if ($a_obj_id != "" && !$this->lm_tree->isInTree($a_obj_id) && $cur_page_id != "" && - $a_back_link == "append") - { - if ($back_pg != "") - { - $back_pg = $cur_page_id.":".$back_pg; - } - else - { - $back_pg = $cur_page_id; - } - } - else - { - if ($a_back_link == "reduce") - { - $limpos = strpos($_GET["back_pg"], ":"); - - if ($limpos > 0) - { - $back_pg = substr($back_pg, strpos($back_pg, ":") + 1); - } - else - { - $back_pg = ""; - } - } - else if ($a_back_link != "keep") - { - $back_pg = ""; - } - } - - // handle online links - if (!$this->offlineMode()) - { - if ($_GET["from_page"] == "") - { - // added if due to #23216 (from page has been set in lots of usual navigation links) - if (!in_array($a_frame, array("", "_blank"))) - { - $this->ctrl->setParameter($this, "from_page", $cur_page_id); - } - } - else - { - // faq link on page (in faq frame) includes faq link on other page - // if added due to bug #11007 - if (!in_array($a_frame, array("", "_blank"))) - { - $this->ctrl->setParameter($this, "from_page", $_GET["from_page"]); - } - } - - if ($a_anchor != "") - { - $this->ctrl->setParameter($this, "anchor", rawurlencode($a_anchor)); - } - if ($a_srcstring != "") - { - $this->ctrl->setParameter($this, "srcstring", $a_srcstring); - } - switch ($a_cmd) - { - case "fullscreen": - $link = $this->ctrl->getLinkTarget($this, "fullscreen", "", false, false); - break; - - default: - - if ($back_pg != "") - { - $this->ctrl->setParameter($this, "back_pg", $back_pg); - } - if ($a_frame != "") - { - $this->ctrl->setParameter($this, "frame", $a_frame); - } - if ($a_obj_id != "") - { - switch ($a_type) - { - case "MediaObject": - $this->ctrl->setParameter($this, "mob_id", $a_obj_id); - break; - - default: - $this->ctrl->setParameter($this, "obj_id", $a_obj_id); - $link.= "&obj_id=".$a_obj_id; - break; - } - } - if ($a_type != "") - { - $this->ctrl->setParameter($this, "obj_type", $a_type); - } - $link = $this->ctrl->getLinkTarget($this, $a_cmd, $a_anchor); + if ($activated && + ilObjContentObject::_checkPreconditionsOfPage($this->lm->getRefId(), $this->lm->getId(), $node["obj_id"])) { + // output learning module header + if ($node["type"] == "du") { + $output_header = true; + } + + // output chapter title + if ($node["type"] == "st") { + if ($ilUser->getId() == ANONYMOUS_USER_ID && + $this->lm_gui->object->getPublicAccessMode() == "selected") { + if (!ilLMObject::_isPagePublic($node["obj_id"])) { + continue; + } + } + + $chap = new ilStructureObject($this->lm, $node["obj_id"]); + $this->tpl->setCurrentBlock("print_chapter"); + + $chapter_title = $chap->_getPresentationTitle( + $node["obj_id"], + $this->lm->isActiveNumbering(), + $this->lm_set->get("time_scheduled_page_activation"), + 0, + $this->lang + ); + $this->tpl->setVariable( + "CHAP_TITLE", + $chapter_title + ); + + if ($this->lm->getPageHeader() == IL_CHAPTER_TITLE) { + if ($nodes[$node_key + 1]["type"] == "pg") { + $this->tpl->setVariable( + "CHAP_HEADER", + $header_page_content + ); + $did_chap_page_header = true; + } + } + + $this->tpl->parseCurrentBlock(); + $this->tpl->setCurrentBlock("print_block"); + $this->tpl->parseCurrentBlock(); + } + + // output page + if ($node["type"] == "pg") { + if ($ilUser->getId() == ANONYMOUS_USER_ID && + $this->lm_gui->object->getPublicAccessMode() == "selected") { + if (!ilLMObject::_isPagePublic($node["obj_id"])) { + continue; + } + } + + $this->tpl->setCurrentBlock("print_item"); + + // get page + $page_id = $node["obj_id"]; + $page_object_gui = $this->getLMPageGUI($page_id); + $page_object = $page_object_gui->getPageObject(); + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $page_object_gui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId( + $this->lm->getStyleSheetId(), + "lm" + )); + + + // get lm page + $lm_pg_obj = new ilLMPageObject($this->lm, $page_id); + $lm_pg_obj->setLMId($this->lm->getId()); + + // determine target frames for internal links + $page_object_gui->setLinkFrame($_GET["frame"]); + $page_object_gui->setOutputMode("print"); + $page_object_gui->setPresentationTitle(""); + + if ($this->lm->getPageHeader() == IL_PAGE_TITLE || $node["free"] === true) { + $page_title = ilLMPageObject::_getPresentationTitle( + $lm_pg_obj->getId(), + $this->lm->getPageHeader(), + $this->lm->isActiveNumbering(), + $this->lm_set->get("time_scheduled_page_activation"), + false, + 0, + $this->lang + ); + + // prevent page title after chapter title + // that have the same content + if ($this->lm->isActiveNumbering()) { + $chapter_title = trim(substr( + $chapter_title, + strpos($chapter_title, " ") + )); + } + + if ($page_title != $chapter_title) { + $page_object_gui->setPresentationTitle($page_title); + } + } + + // handle header / footer + $hcont = $header_page_content; + $fcont = $footer_page_content; + + if ($this->lm->getPageHeader() == IL_CHAPTER_TITLE) { + if ($did_chap_page_header) { + $hcont = ""; + } + if ($nodes[$node_key + 1]["type"] == "pg" && + !($nodes[$node_key + 1]["depth"] <= $act_level + && !in_array($nodes[$node_key + 1]["obj_id"], $_POST["obj_id"]))) { + $fcont = ""; + } + } + + $page_object_gui->setFileDownloadLink("#"); + $page_object_gui->setFullscreenLink("#"); + $page_object_gui->setSourceCodeDownloadScript("#"); + $page_content = $page_object_gui->showPage(); + if ($this->lm->getPageHeader() != IL_PAGE_TITLE) { + $this->tpl->setVariable( + "CONTENT", + $hcont . $page_content . $fcont + ); + } else { + $this->tpl->setVariable( + "CONTENT", + $hcont . $page_content . $fcont . "
" + ); + } + $chapter_title = ""; + $this->tpl->parseCurrentBlock(); + $this->tpl->setCurrentBlock("print_block"); + $this->tpl->parseCurrentBlock(); + + // get internal links + $int_links = ilInternalLink::_getTargetsOfSource($this->lm->getType() . ":pg", $node["obj_id"]); + + $got_mobs = false; + + foreach ($int_links as $key => $link) { + if ($link["type"] == "git" && + ($link["inst"] == IL_INST_ID || $link["inst"] == 0)) { + $glossary_links[$key] = $link; + } + if ($link["type"] == "mob" && + ($link["inst"] == IL_INST_ID || $link["inst"] == 0)) { + $got_mobs = true; + $mob_links[$key] = $link; + } + } + + // this is not cool because of performance reasons + // unfortunately the int link table does not + // store the target frame (we want to append all linked + // images but not inline images (i.e. mobs with no target + // frame)) + if ($got_mobs) { + $page_object->buildDom(); + $links = $page_object->getInternalLinks(); + foreach ($links as $link) { + if ($link["Type"] == "MediaObject" + && $link["TargetFrame"] != "" + && $link["TargetFrame"] != "None") { + $media_links[] = $link; + } + } + } + } + } + } + + $annex_cnt = 0; + $annexes = array(); + + // glossary + if (count($glossary_links) > 0 && !$this->lm->isActivePreventGlossaryAppendix()) { + include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + include_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); + + // sort terms + $terms = array(); + + foreach ($glossary_links as $key => $link) { + $term = ilGlossaryTerm::_lookGlossaryTerm($link["id"]); + $terms[$term . ":" . $key] = array("key" => $key, "link" => $link, "term" => $term); + } + $terms = ilUtil::sortArray($terms, "term", "asc"); + //ksort($terms); + + foreach ($terms as $t) { + $link = $t["link"]; + $key = $t["key"]; + $defs = ilGlossaryDefinition::getDefinitionList($link["id"]); + $def_cnt = 1; + + // output all definitions of term + foreach ($defs as $def) { + // definition + number, if more than 1 definition + if (count($defs) > 1) { + $this->tpl->setCurrentBlock("def_title"); + $this->tpl->setVariable( + "TXT_DEFINITION", + $this->lng->txt("cont_definition") . " " . ($def_cnt++) + ); + $this->tpl->parseCurrentBlock(); + } + include_once("./Modules/Glossary/classes/class.ilGlossaryDefPageGUI.php"); + $page_gui = new ilGlossaryDefPageGUI($def["id"]); + $page_gui->setTemplateOutput(false); + $page_gui->setOutputMode("print"); + + $this->tpl->setCurrentBlock("definition"); + $page_gui->setFileDownloadLink("#"); + $page_gui->setFullscreenLink("#"); + $page_gui->setSourceCodeDownloadScript("#"); + $output = $page_gui->showPage(); + $this->tpl->setVariable("VAL_DEFINITION", $output); + $this->tpl->parseCurrentBlock(); + } + + // output term + $this->tpl->setCurrentBlock("term"); + $this->tpl->setVariable( + "VAL_TERM", + $term = ilGlossaryTerm::_lookGlossaryTerm($link["id"]) + ); + $this->tpl->parseCurrentBlock(); + } + + // output glossary header + $annex_cnt++; + $this->tpl->setCurrentBlock("glossary"); + $annex_title = $this->lng->txt("cont_annex") . " " . + chr(64+$annex_cnt) . ": " . $this->lng->txt("glo"); + $this->tpl->setVariable("TXT_GLOSSARY", $annex_title); + $this->tpl->parseCurrentBlock(); + + $annexes[] = $annex_title; + } + + // referenced images + if (count($media_links) > 0) { + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + include_once("./Services/MediaObjects/classes/class.ilMediaItem.php"); + + foreach ($media_links as $media) { + if (substr($media["Target"], 0, 4) == "il__") { + $arr = explode("_", $media["Target"]); + $id = $arr[count($arr) - 1]; + + $med_obj = new ilObjMediaObject($id); + $med_item = $med_obj->getMediaItem("Standard"); + if (is_object($med_item)) { + if (is_int(strpos($med_item->getFormat(), "image"))) { + $this->tpl->setCurrentBlock("ref_image"); + + // image source + if ($med_item->getLocationType() == "LocalFile") { + $this->tpl->setVariable( + "IMG_SOURCE", + ilUtil::getWebspaceDir("output") . "/mobs/mm_" . $id . + "/" . $med_item->getLocation() + ); + } else { + $this->tpl->setVariable( + "IMG_SOURCE", + $med_item->getLocation() + ); + } + + if ($med_item->getCaption() != "") { + $this->tpl->setVariable("IMG_TITLE", $med_item->getCaption()); + } else { + $this->tpl->setVariable("IMG_TITLE", $med_obj->getTitle()); + } + $this->tpl->parseCurrentBlock(); + } + } + } + } + + // output glossary header + $annex_cnt++; + $this->tpl->setCurrentBlock("ref_images"); + $annex_title = $this->lng->txt("cont_annex") . " " . + chr(64+$annex_cnt) . ": " . $this->lng->txt("cont_ref_images"); + $this->tpl->setVariable("TXT_REF_IMAGES", $annex_title); + $this->tpl->parseCurrentBlock(); + + $annexes[] = $annex_title; + } + + // output learning module title and toc + if ($output_header) { + $this->tpl->setCurrentBlock("print_header"); + $this->tpl->setVariable("LM_TITLE", $this->getLMPresentationTitle()); + if ($this->lm->getDescription() != "none") { + include_once("Services/MetaData/classes/class.ilMD.php"); + $md = new ilMD($this->lm->getId(), 0, $this->lm->getType()); + $md_gen = $md->getGeneral(); + foreach ($md_gen->getDescriptionIds() as $id) { + $md_des = $md_gen->getDescription($id); + $description = $md_des->getDescription(); + } + + $this->tpl->setVariable( + "LM_DESCRIPTION", + $description + ); + } + $this->tpl->parseCurrentBlock(); + + // output toc + $nodes2 = $nodes; + foreach ($nodes2 as $node2) { + if ($node2["type"] == "st" + && ilObjContentObject::_checkPreconditionsOfPage($this->lm->getRefId(), $this->lm->getId(), $node2["obj_id"])) { + for ($j=1; $j < $node2["depth"]; $j++) { + $this->tpl->setCurrentBlock("indent"); + $this->tpl->setVariable("IMG_BLANK", ilUtil::getImagePath("browser/blank.png")); + $this->tpl->parseCurrentBlock(); + } + $this->tpl->setCurrentBlock("toc_entry"); + $this->tpl->setVariable( + "TXT_TOC_TITLE", + ilStructureObject::_getPresentationTitle( + $node2["obj_id"], + IL_CHAPTER_TITLE, + $this->lm->isActiveNumbering(), + $this->lm_set->get("time_scheduled_page_activation"), + false, + 0, + $this->lang + ) + ); + $this->tpl->parseCurrentBlock(); + } + } + + // annexes + foreach ($annexes as $annex) { + $this->tpl->setCurrentBlock("indent"); + $this->tpl->setVariable("IMG_BLANK", ilUtil::getImagePath("browser/blank.png")); + $this->tpl->parseCurrentBlock(); + $this->tpl->setCurrentBlock("toc_entry"); + $this->tpl->setVariable("TXT_TOC_TITLE", $annex); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setCurrentBlock("toc"); + $this->tpl->setVariable("TXT_TOC", $this->lng->txt("cont_toc")); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setCurrentBlock("print_start_block"); + $this->tpl->parseCurrentBlock(); + } + + // output author information + include_once 'Services/MetaData/classes/class.ilMD.php'; + $md = new ilMD($this->lm->getId(), 0, $this->lm->getType()); + if (is_object($lifecycle = $md->getLifecycle())) { + $sep = $author = ""; + foreach (($ids = $lifecycle->getContributeIds()) as $con_id) { + $md_con = $lifecycle->getContribute($con_id); + if ($md_con->getRole() == "Author") { + foreach ($ent_ids = $md_con->getEntityIds() as $ent_id) { + $md_ent = $md_con->getEntity($ent_id); + $author = $author . $sep . $md_ent->getEntity(); + $sep = ", "; + } + } + } + if ($author != "") { + $this->lng->loadLanguageModule("meta"); + $this->tpl->setCurrentBlock("author"); + $this->tpl->setVariable("TXT_AUTHOR", $this->lng->txt("meta_author")); + $this->tpl->setVariable("LM_AUTHOR", $author); + $this->tpl->parseCurrentBlock(); + } + } + + + // output copyright information + if (is_object($md_rights = $md->getRights())) { + $copyright = $md_rights->getDescription(); + include_once('Services/MetaData/classes/class.ilMDUtils.php'); + $copyright = ilMDUtils::_parseCopyright($copyright); + + if ($copyright != "") { + $this->lng->loadLanguageModule("meta"); + $this->tpl->setCurrentBlock("copyright"); + $this->tpl->setVariable("TXT_COPYRIGHT", $this->lng->txt("meta_copyright")); + $this->tpl->setVariable("LM_COPYRIGHT", $copyright); + $this->tpl->parseCurrentBlock(); + } + } + + $this->tpl->show(false); + } + + /** + * download file of file lists + */ + public function downloadFile() + { + $pg_obj = $this->getLMPage($this->getCurrentPageId()); + $pg_obj->buildDom(); + $int_links = $pg_obj->getInternalLinks(); + foreach ($int_links as $il) { + if ($il["Target"] == str_replace("_file_", "_dfile_", $_GET["file_id"])) { + $file = explode("_", $_GET["file_id"]); + $file_id = (int) $file[count($file) - 1]; + require_once("./Modules/File/classes/class.ilObjFile.php"); + $fileObj = new ilObjFile($file_id, false); + $fileObj->sendFile(); + exit; + } + } + if (in_array($_GET["file_id"], $pg_obj->getAllFileObjIds())) { + require_once("./Modules/File/classes/class.ilObjFile.php"); + $file = explode("_", $_GET["file_id"]); + $file_id = (int) $file[count($file) - 1]; + $fileObj = new ilObjFile($file_id, false); + $fileObj->sendFile(); + exit; + } + } + + + /** + * download source code paragraph + */ + public function download_paragraph() + { + require_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + $pg_obj = $this->getLMPage($_GET["pg_id"]); + $pg_obj->send_paragraph($_GET["par_id"], $_GET["downloadtitle"]); + } + + /** + * show download list + */ + public function showDownloadList() + { + if (!$this->lm->isActiveDownloads() || !$this->lm->isActiveLMMenu()) { + return; + } + + //$this->tpl = new ilTemplate("tpl.lm_toc.html", true, true, true); + $this->tpl->setCurrentBlock("ContentStyle"); + if (!$this->offlineMode()) { + $this->tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath($this->lm->getStyleSheetId()) + ); + } else { + $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", "content_style/content.css"); + } + $this->tpl->parseCurrentBlock(); + + $this->renderPageTitle(); + $this->tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); + $this->tpl->getStandardTemplate(); + + $this->tpl->setVariable("TABS", $this->lm_gui->setilLMMenu( + $this->offlineMode() + , + $this->getExportFormat(), + "download", + true, + false, + 0, + $this->lang, + $this->export_all_languages + )); + + $this->ilLocator(true); + //$this->tpl->stopTitleFloating(); + $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.lm_download_list.html", "Modules/LearningModule"); + + // set title header + $this->tpl->setTitle($this->getLMPresentationTitle()); + $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_lm.svg")); + + /* + $this->tpl->setVariable("TXT_BACK", $this->lng->txt("back")); + $this->ctrl->setParameter($this, "obj_id", $_GET["obj_id"]); + $this->tpl->setVariable("LINK_BACK", + $this->ctrl->getLinkTarget($this, "")); */ + + // output copyright information + include_once 'Services/MetaData/classes/class.ilMD.php'; + $md = new ilMD($this->lm->getId(), 0, $this->lm->getType()); + if (is_object($md_rights = $md->getRights())) { + $copyright = $md_rights->getDescription(); + + include_once('Services/MetaData/classes/class.ilMDUtils.php'); + $copyright = ilMDUtils::_parseCopyright($copyright); + + if ($copyright != "") { + $this->lng->loadLanguageModule("meta"); + $this->tpl->setCurrentBlock("copyright"); + $this->tpl->setVariable("TXT_COPYRIGHT", $this->lng->txt("meta_copyright")); + $this->tpl->setVariable("LM_COPYRIGHT", $copyright); + $this->tpl->parseCurrentBlock(); + } + } + + + include_once("./Modules/LearningModule/classes/class.ilLMDownloadTableGUI.php"); + $download_table = new ilLMDownloadTableGUI($this, "showDownloadList", $this->lm); + $this->tpl->setVariable("DOWNLOAD_TABLE", $download_table->getHTML()); + $this->tpl->show(); + } + + + /** + * send download file (xml/html) + */ + public function downloadExportFile() + { + if (!$this->lm->isActiveDownloads() || !$this->lm->isActiveLMMenu()) { + return; + } + + $base_type = explode("_", $_GET["type"]); + $base_type = $base_type[0]; + $file = $this->lm->getPublicExportFile($base_type); + if ($this->lm->getPublicExportFile($base_type) != "") { + $dir = $this->lm->getExportDirectory($_GET["type"]); + if (is_file($dir . "/" . $file)) { + ilUtil::deliverFile($dir . "/" . $file, $file); + exit; + } + } + } + + /** + * Get focused link (used in learning objectives courses) + * + * @param int $a_ref_id reference id of learning module + * @param int $a_obj_id chapter or page id + * @param int $a_return_ref_id return ref id + * + * @return string link + */ + public function getFocusLink($a_ref_id, $a_obj_id, $a_return_ref_id) + { + return "ilias.php?baseClass=ilLMPresentationGUI&ref_id=" . $a_ref_id . "&obj_id=" . $a_obj_id . "&focus_id=" . + $a_obj_id . "&focus_return=" . $a_return_ref_id; + } + + + /** + * handles links for learning module presentation + */ + public function getLink( + $a_ref_id, + $a_cmd = "", + $a_obj_id = "", + $a_frame = "", + $a_type = "", + $a_back_link = "append", + $a_anchor = "", + $a_srcstring = "" + ) { + $ilCtrl = $this->ctrl; + + if ($a_cmd == "") { + $a_cmd = "layout"; + } + + // handling of free pages + $cur_page_id = $this->getCurrentPageId(); + $back_pg = $_GET["back_pg"]; + if ($a_obj_id != "" && !$this->lm_tree->isInTree($a_obj_id) && $cur_page_id != "" && + $a_back_link == "append") { + if ($back_pg != "") { + $back_pg = $cur_page_id . ":" . $back_pg; + } else { + $back_pg = $cur_page_id; + } + } else { + if ($a_back_link == "reduce") { + $limpos = strpos($_GET["back_pg"], ":"); + + if ($limpos > 0) { + $back_pg = substr($back_pg, strpos($back_pg, ":") + 1); + } else { + $back_pg = ""; + } + } elseif ($a_back_link != "keep") { + $back_pg = ""; + } + } + + // handle online links + if (!$this->offlineMode()) { + if ($_GET["from_page"] == "") { + // added if due to #23216 (from page has been set in lots of usual navigation links) + if (!in_array($a_frame, array("", "_blank"))) { + $this->ctrl->setParameter($this, "from_page", $cur_page_id); + } + } else { + // faq link on page (in faq frame) includes faq link on other page + // if added due to bug #11007 + if (!in_array($a_frame, array("", "_blank"))) { + $this->ctrl->setParameter($this, "from_page", $_GET["from_page"]); + } + } + + if ($a_anchor != "") { + $this->ctrl->setParameter($this, "anchor", rawurlencode($a_anchor)); + } + if ($a_srcstring != "") { + $this->ctrl->setParameter($this, "srcstring", $a_srcstring); + } + switch ($a_cmd) { + case "fullscreen": + $link = $this->ctrl->getLinkTarget($this, "fullscreen", "", false, false); + break; + + default: + + if ($back_pg != "") { + $this->ctrl->setParameter($this, "back_pg", $back_pg); + } + if ($a_frame != "") { + $this->ctrl->setParameter($this, "frame", $a_frame); + } + if ($a_obj_id != "") { + switch ($a_type) { + case "MediaObject": + $this->ctrl->setParameter($this, "mob_id", $a_obj_id); + break; + + default: + $this->ctrl->setParameter($this, "obj_id", $a_obj_id); + $link.= "&obj_id=" . $a_obj_id; + break; + } + } + if ($a_type != "") { + $this->ctrl->setParameter($this, "obj_type", $a_type); + } + $link = $this->ctrl->getLinkTarget($this, $a_cmd, $a_anchor); // $link = str_replace("&", "&", $link); - - $this->ctrl->setParameter($this, "frame", ""); - $this->ctrl->setParameter($this, "obj_id", ""); - $this->ctrl->setParameter($this, "mob_id", ""); - break; - } - } - else // handle offline links - { - $lang_suffix = ""; - if ($this->export_all_languages) - { - if ($this->lang != "" && $this->lang != "-") - { - $lang_suffix = "_".$this->lang; - } - } - - switch ($a_cmd) - { - case "downloadFile": - break; - - case "fullscreen": - $link = "fullscreen.html"; // id is handled by xslt - break; - - case "layout": - - if ($a_obj_id == "") - { - $a_obj_id = $this->lm_tree->getRootId(); - $pg_node = $this->lm_tree->fetchSuccessorNode($a_obj_id, "pg"); - $a_obj_id = $pg_node["obj_id"]; - } - if ($a_type == "StructureObject") - { - $pg_node = $this->lm_tree->fetchSuccessorNode($a_obj_id, "pg"); - $a_obj_id = $pg_node["obj_id"]; - } - if ($a_frame != "" && $a_frame != "_blank") - { - if ($a_frame != "toc") - { - $link = "frame_".$a_obj_id."_".$a_frame.$lang_suffix.".html"; - } - else // don't save multiple toc frames (all the same) - { - $link = "frame_".$a_frame.$lang_suffix.".html"; - } - } - else - { - //if ($nid = ilLMObject::_lookupNID($this->lm->getId(), $a_obj_id, "pg")) - if ($nid = ilLMPageObject::getExportId($this->lm->getId(), $a_obj_id)) - { - $link = "lm_pg_".$nid.$lang_suffix.".html"; - } - else - { - $link = "lm_pg_".$a_obj_id.$lang_suffix.".html"; - } - } - break; - - case "glossary": - $link = "term_".$a_obj_id.".html"; - break; - - case "media": - $link = "media_".$a_obj_id.".html"; - break; - - default: - break; - } - } - - $this->ctrl->clearParameters($this); - - return $link; - } - - /** - * Show message screen - * - * @param - * @return - */ - function showMessageScreen($a_content) - { - // content style - $this->tpl->setCurrentBlock("ContentStyle"); - if (!$this->offlineMode()) - { - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->lm->getStyleSheetId())); - } - else - { - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", "content_style/content.css"); - } - $this->tpl->parseCurrentBlock(); - - $tpl = new ilTemplate("tpl.page_message_screen.html", true, true, "Modules/LearningModule"); - $tpl->setVariable("TXT_PAGE_NO_PUBLIC_ACCESS", $a_content); - - $this->tpl->setVariable("PAGE_CONTENT", $tpl->get()); - } - - - /** - * Show info message, if page is not accessible in public area - */ - function showNoPublicAccess() - { - $this->showMessageScreen($this->lng->txt("msg_page_no_public_access")); - } - - /** - * Show info message, if page is not accessible in public area - */ - function showNoPageAccess() - { - $this->showMessageScreen($this->lng->txt("msg_no_page_access")); - } - - /** - * Show message if navigation to page is not allowed due to unanswered - * questions. - */ - function showNavRestrictionDueToQuestions() - { - $this->showMessageScreen($this->lng->txt("cont_no_page_access_unansw_q")); - } - - - function getSourcecodeDownloadLink() { - if (!$this->offlineMode()) - { - //$this->ctrl->setParameter($this, session_name(), session_id()); - $target = $this->ctrl->getLinkTarget($this, ""); - $target = ilUtil::appendUrlParameterString($target, session_name()."=".session_id()); - return $this->ctrl->getLinkTarget($this, ""); - } - else - { - return ""; - } - } - - /** - * set offline directory to offdir - * - * @param offdir contains diretory where to store files - * - * current used in code paragraph - */ - function setOfflineDirectory ($offdir) { - $this->offline_directory = $offdir; - } - - - /** - * get offline directory - * @return directory where to store offline files - * - * current used in code paragraph - */ - function getOfflineDirectory () { - return $this->offline_directory; - } - - /** - * store paragraph into file directory - * files/codefile_$pg_id_$paragraph_id/downloadtitle - */ - function handleCodeParagraph ($page_id, $paragraph_id, $title, $text) { - $directory = $this->getOfflineDirectory()."/codefiles/".$page_id."/".$paragraph_id; - ilUtil::makeDirParents ($directory); - $file = $directory."/".$title; - if (!($fp = @fopen($file,"w+"))) - { - die ("Error: Could not open \"".$file."\" for writing". - " in ".__FILE__." on line ".__LINE__."
"); - } - chmod($file, 0770); - fwrite($fp, $text); - fclose($fp); - } - - // #8613 - protected function renderPageTitle() - { - $this->tpl->setHeaderPageTitle($this->getLMPresentationTitle()); - $this->tpl->fillWindowTitle(); - $this->tpl->fillContentLanguage(); - } - - - /** - * Get lm page gui object - * - * @param - * @return - */ - function getLMPageGUI($a_id) - { - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - include_once("./Modules/LearningModule/classes/class.ilLMPageGUI.php"); - if ($this->lang != "-" && ilPageObject::_exists("lm", $a_id, $this->lang)) - { - return new ilLMPageGUI($a_id, 0, false, $this->lang); - } - return new ilLMPageGUI($a_id); - } - - /** - * Get lm page object - * - * @param - * @return - */ - function getLMPage($a_id) - { - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - if ($this->lang != "-" && ilPageObject::_exists("lm", $a_id, $this->lang)) - { - return new ilLMPage($a_id, 0, $this->lang); - } - return new ilLMPage($a_id); - } - - /** - * Refresh toc (called if questions have been answered correctly) - */ - function refreshToc() - { - $exp = $this->ilTOC(true); - - echo $exp->getHTML(). - ""; - exit; - } + + $this->ctrl->setParameter($this, "frame", ""); + $this->ctrl->setParameter($this, "obj_id", ""); + $this->ctrl->setParameter($this, "mob_id", ""); + break; + } + } else { // handle offline links + $lang_suffix = ""; + if ($this->export_all_languages) { + if ($this->lang != "" && $this->lang != "-") { + $lang_suffix = "_" . $this->lang; + } + } -} + switch ($a_cmd) { + case "downloadFile": + break; + + case "fullscreen": + $link = "fullscreen.html"; // id is handled by xslt + break; + + case "layout": + + if ($a_obj_id == "") { + $a_obj_id = $this->lm_tree->getRootId(); + $pg_node = $this->lm_tree->fetchSuccessorNode($a_obj_id, "pg"); + $a_obj_id = $pg_node["obj_id"]; + } + if ($a_type == "StructureObject") { + $pg_node = $this->lm_tree->fetchSuccessorNode($a_obj_id, "pg"); + $a_obj_id = $pg_node["obj_id"]; + } + if ($a_frame != "" && $a_frame != "_blank") { + if ($a_frame != "toc") { + $link = "frame_" . $a_obj_id . "_" . $a_frame . $lang_suffix . ".html"; + } else { // don't save multiple toc frames (all the same) + $link = "frame_" . $a_frame . $lang_suffix . ".html"; + } + } else { + //if ($nid = ilLMObject::_lookupNID($this->lm->getId(), $a_obj_id, "pg")) + if ($nid = ilLMPageObject::getExportId($this->lm->getId(), $a_obj_id)) { + $link = "lm_pg_" . $nid . $lang_suffix . ".html"; + } else { + $link = "lm_pg_" . $a_obj_id . $lang_suffix . ".html"; + } + } + break; + + case "glossary": + $link = "term_" . $a_obj_id . ".html"; + break; + + case "media": + $link = "media_" . $a_obj_id . ".html"; + break; + + default: + break; + } + } + + $this->ctrl->clearParameters($this); + + return $link; + } + + /** + * Show message screen + * + * @param + * @return + */ + public function showMessageScreen($a_content) + { + // content style + $this->tpl->setCurrentBlock("ContentStyle"); + if (!$this->offlineMode()) { + $this->tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath($this->lm->getStyleSheetId()) + ); + } else { + $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", "content_style/content.css"); + } + $this->tpl->parseCurrentBlock(); + + $tpl = new ilTemplate("tpl.page_message_screen.html", true, true, "Modules/LearningModule"); + $tpl->setVariable("TXT_PAGE_NO_PUBLIC_ACCESS", $a_content); + + $this->tpl->setVariable("PAGE_CONTENT", $tpl->get()); + } + + + /** + * Show info message, if page is not accessible in public area + */ + public function showNoPublicAccess() + { + $this->showMessageScreen($this->lng->txt("msg_page_no_public_access")); + } + + /** + * Show info message, if page is not accessible in public area + */ + public function showNoPageAccess() + { + $this->showMessageScreen($this->lng->txt("msg_no_page_access")); + } + + /** + * Show message if navigation to page is not allowed due to unanswered + * questions. + */ + public function showNavRestrictionDueToQuestions() + { + $this->showMessageScreen($this->lng->txt("cont_no_page_access_unansw_q")); + } + + + public function getSourcecodeDownloadLink() + { + if (!$this->offlineMode()) { + //$this->ctrl->setParameter($this, session_name(), session_id()); + $target = $this->ctrl->getLinkTarget($this, ""); + $target = ilUtil::appendUrlParameterString($target, session_name() . "=" . session_id()); + return $this->ctrl->getLinkTarget($this, ""); + } else { + return ""; + } + } + + /** + * set offline directory to offdir + * + * @param offdir contains diretory where to store files + * + * current used in code paragraph + */ + public function setOfflineDirectory($offdir) + { + $this->offline_directory = $offdir; + } + + + /** + * get offline directory + * @return directory where to store offline files + * + * current used in code paragraph + */ + public function getOfflineDirectory() + { + return $this->offline_directory; + } + + /** + * store paragraph into file directory + * files/codefile_$pg_id_$paragraph_id/downloadtitle + */ + public function handleCodeParagraph($page_id, $paragraph_id, $title, $text) + { + $directory = $this->getOfflineDirectory() . "/codefiles/" . $page_id . "/" . $paragraph_id; + ilUtil::makeDirParents($directory); + $file = $directory . "/" . $title; + if (!($fp = @fopen($file, "w+"))) { + die("Error: Could not open \"" . $file . "\" for writing" . + " in " . __FILE__ . " on line " . __LINE__ . "
"); + } + chmod($file, 0770); + fwrite($fp, $text); + fclose($fp); + } + + // #8613 + protected function renderPageTitle() + { + $this->tpl->setHeaderPageTitle($this->getLMPresentationTitle()); + $this->tpl->fillWindowTitle(); + $this->tpl->fillContentLanguage(); + } + + + /** + * Get lm page gui object + * + * @param + * @return + */ + public function getLMPageGUI($a_id) + { + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + include_once("./Modules/LearningModule/classes/class.ilLMPageGUI.php"); + if ($this->lang != "-" && ilPageObject::_exists("lm", $a_id, $this->lang)) { + return new ilLMPageGUI($a_id, 0, false, $this->lang); + } + return new ilLMPageGUI($a_id); + } + + /** + * Get lm page object + * + * @param + * @return + */ + public function getLMPage($a_id) + { + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + if ($this->lang != "-" && ilPageObject::_exists("lm", $a_id, $this->lang)) { + return new ilLMPage($a_id, 0, $this->lang); + } + return new ilLMPage($a_id); + } + + /** + * Refresh toc (called if questions have been answered correctly) + */ + public function refreshToc() + { + $exp = $this->ilTOC(true); -?> + echo $exp->getHTML() . + ""; + exit; + } +} diff --git a/Modules/LearningModule/classes/class.ilLMQuestionListTableGUI.php b/Modules/LearningModule/classes/class.ilLMQuestionListTableGUI.php index 8ac04ebd0de06b0d73ffeda48650473853308b2f..1e31b7b69833ae9c0e5a3a08ed6f078016c06b41 100644 --- a/Modules/LearningModule/classes/class.ilLMQuestionListTableGUI.php +++ b/Modules/LearningModule/classes/class.ilLMQuestionListTableGUI.php @@ -16,144 +16,142 @@ include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); */ class ilLMQuestionListTableGUI extends ilTable2GUI { - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_lm) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $this->rbacsystem = $DIC->rbac()->system(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilAccess = $DIC->access(); - $lng = $DIC->language(); - $rbacsystem = $DIC->rbac()->system(); - - $this->lm = $a_lm; - - $this->setId("lm_qst".$this->lm->getId()); - - parent::__construct($a_parent_obj, $a_parent_cmd); -// $this->setTitle($this->lng->txt("users")); - - //$this->addColumn("", "", "1", true); - $this->addColumn($this->lng->txt("pg")); - $this->addColumn($this->lng->txt("question")); - $this->addColumn($this->lng->txt("cont_users_answered")); - $this->addColumn($this->lng->txt("cont_correct_after_first")); - $this->addColumn($this->lng->txt("cont_second")); - $this->addColumn($this->lng->txt("cont_third_and_more")); - $this->addColumn($this->lng->txt("cont_never")); - - $this->setExternalSorting(true); - $this->setExternalSegmentation(true); - $this->setEnableHeader(true); - //$this->setFormAction($ilCtrl->getFormAction($this->parent_obj, "applyFilter")); - $this->setFormAction($ilCtrl->getFormAction($this->parent_obj, $this->parent_cmd)); - $this->setRowTemplate("tpl.lm_question_row.html", "Modules/LearningModule"); - //$this->disable("footer"); - $this->setEnableTitle(true); -// $this->initFilter(); -// $this->setFilterCommand("applyFilter"); -// $this->setDefaultOrderField("login"); -// $this->setDefaultOrderDirection("asc"); - -// $this->setSelectAllCheckbox("id[]"); - -// $this->addMultiCommand("activateUsers", $lng->txt("activate")); - - $this->getItems(); - } - - /** - * Get user items - */ - function getItems() - { - $lng = $this->lng; -//if ($GLOBALS["kk"]++ == 1) nj(); - - $this->determineOffsetAndOrder(); - - include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); - - $questions = ilLMPageObject::queryQuestionsOfLearningModule( - $this->lm->getId(), - ilUtil::stripSlashes($this->getOrderField()), - ilUtil::stripSlashes($this->getOrderDirection()), - ilUtil::stripSlashes($this->getOffset()), - ilUtil::stripSlashes($this->getLimit()) - ); - - if (count($questions["set"]) == 0 && $this->getOffset() > 0) - { - $this->resetOffset(); - $questions = ilLMPageObject::queryQuestionsOfLearningModule( - $this->lm->getId(), - ilUtil::stripSlashes($this->getOrderField()), - ilUtil::stripSlashes($this->getOrderDirection()), - ilUtil::stripSlashes($this->getOffset()), - ilUtil::stripSlashes($this->getLimit()) - ); - } - - $this->setMaxCount($questions["cnt"]); - $this->setData($questions["set"]); - } - - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->tpl->setVariable("PAGE_TITLE", - ilLMObject::_lookupTitle($a_set["page_id"])); - $this->tpl->setVariable("QUESTION", - assQuestion::_getQuestionText($a_set["question_id"])); - - include_once("./Services/COPage/classes/class.ilPageQuestionProcessor.php"); - $stats = ilPageQuestionProcessor::getQuestionStatistics($a_set["question_id"]); - - $this->tpl->setVariable("VAL_ANSWERED", (int) $stats["all"]); - if ($stats["all"] == 0) - { - $this->tpl->setVariable("VAL_CORRECT_FIRST", 0); - $this->tpl->setVariable("VAL_CORRECT_SECOND", 0); - $this->tpl->setVariable("VAL_CORRECT_THIRD_OR_MORE", 0); - $this->tpl->setVariable("VAL_NEVER", 0); - } - else - { - $this->tpl->setVariable("VAL_CORRECT_FIRST", $stats["first"]. - " (".(100/$stats["all"] * $stats["first"])." %)"); - $this->tpl->setVariable("VAL_CORRECT_SECOND", $stats["second"]. - " (".(100/$stats["all"] * $stats["second"])." %)"); - $this->tpl->setVariable("VAL_CORRECT_THIRD_AND_MORE", $stats["third_or_more"]. - " (".(100/$stats["all"] * $stats["third_or_more"])." %)"); - $nev = $stats["all"] - $stats["first"] - $stats["second"] - $stats["third_or_more"]; - $this->tpl->setVariable("VAL_NEVER", $nev. - " (".(100/$stats["all"] * $nev)." %)"); - } - } + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_lm) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->rbacsystem = $DIC->rbac()->system(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilAccess = $DIC->access(); + $lng = $DIC->language(); + $rbacsystem = $DIC->rbac()->system(); + + $this->lm = $a_lm; + + $this->setId("lm_qst" . $this->lm->getId()); + + parent::__construct($a_parent_obj, $a_parent_cmd); + // $this->setTitle($this->lng->txt("users")); + + //$this->addColumn("", "", "1", true); + $this->addColumn($this->lng->txt("pg")); + $this->addColumn($this->lng->txt("question")); + $this->addColumn($this->lng->txt("cont_users_answered")); + $this->addColumn($this->lng->txt("cont_correct_after_first")); + $this->addColumn($this->lng->txt("cont_second")); + $this->addColumn($this->lng->txt("cont_third_and_more")); + $this->addColumn($this->lng->txt("cont_never")); + + $this->setExternalSorting(true); + $this->setExternalSegmentation(true); + $this->setEnableHeader(true); + //$this->setFormAction($ilCtrl->getFormAction($this->parent_obj, "applyFilter")); + $this->setFormAction($ilCtrl->getFormAction($this->parent_obj, $this->parent_cmd)); + $this->setRowTemplate("tpl.lm_question_row.html", "Modules/LearningModule"); + //$this->disable("footer"); + $this->setEnableTitle(true); + // $this->initFilter(); + // $this->setFilterCommand("applyFilter"); + // $this->setDefaultOrderField("login"); + // $this->setDefaultOrderDirection("asc"); + + // $this->setSelectAllCheckbox("id[]"); + + // $this->addMultiCommand("activateUsers", $lng->txt("activate")); + + $this->getItems(); + } + + /** + * Get user items + */ + public function getItems() + { + $lng = $this->lng; + //if ($GLOBALS["kk"]++ == 1) nj(); + + $this->determineOffsetAndOrder(); + + include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); + + $questions = ilLMPageObject::queryQuestionsOfLearningModule( + $this->lm->getId(), + ilUtil::stripSlashes($this->getOrderField()), + ilUtil::stripSlashes($this->getOrderDirection()), + ilUtil::stripSlashes($this->getOffset()), + ilUtil::stripSlashes($this->getLimit()) + ); + + if (count($questions["set"]) == 0 && $this->getOffset() > 0) { + $this->resetOffset(); + $questions = ilLMPageObject::queryQuestionsOfLearningModule( + $this->lm->getId(), + ilUtil::stripSlashes($this->getOrderField()), + ilUtil::stripSlashes($this->getOrderDirection()), + ilUtil::stripSlashes($this->getOffset()), + ilUtil::stripSlashes($this->getLimit()) + ); + } + + $this->setMaxCount($questions["cnt"]); + $this->setData($questions["set"]); + } + + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->tpl->setVariable( + "PAGE_TITLE", + ilLMObject::_lookupTitle($a_set["page_id"]) + ); + $this->tpl->setVariable( + "QUESTION", + assQuestion::_getQuestionText($a_set["question_id"]) + ); + + include_once("./Services/COPage/classes/class.ilPageQuestionProcessor.php"); + $stats = ilPageQuestionProcessor::getQuestionStatistics($a_set["question_id"]); + + $this->tpl->setVariable("VAL_ANSWERED", (int) $stats["all"]); + if ($stats["all"] == 0) { + $this->tpl->setVariable("VAL_CORRECT_FIRST", 0); + $this->tpl->setVariable("VAL_CORRECT_SECOND", 0); + $this->tpl->setVariable("VAL_CORRECT_THIRD_OR_MORE", 0); + $this->tpl->setVariable("VAL_NEVER", 0); + } else { + $this->tpl->setVariable("VAL_CORRECT_FIRST", $stats["first"] . + " (" . (100/$stats["all"] * $stats["first"]) . " %)"); + $this->tpl->setVariable("VAL_CORRECT_SECOND", $stats["second"] . + " (" . (100/$stats["all"] * $stats["second"]) . " %)"); + $this->tpl->setVariable("VAL_CORRECT_THIRD_AND_MORE", $stats["third_or_more"] . + " (" . (100/$stats["all"] * $stats["third_or_more"]) . " %)"); + $nev = $stats["all"] - $stats["first"] - $stats["second"] - $stats["third_or_more"]; + $this->tpl->setVariable("VAL_NEVER", $nev . + " (" . (100/$stats["all"] * $nev) . " %)"); + } + } } - -?> diff --git a/Modules/LearningModule/classes/class.ilLMTOCExplorerGUI.php b/Modules/LearningModule/classes/class.ilLMTOCExplorerGUI.php index 0dca8f103231047fc6e09066ec0f7c2fb43482c7..38a22cc5c03c8d0fd5d7fb345007d8aa376d892d 100644 --- a/Modules/LearningModule/classes/class.ilLMTOCExplorerGUI.php +++ b/Modules/LearningModule/classes/class.ilLMTOCExplorerGUI.php @@ -13,380 +13,354 @@ include_once("./Modules/LearningModule/classes/class.ilLMExplorerGUI.php"); */ class ilLMTOCExplorerGUI extends ilLMExplorerGUI { - protected $lang; - protected $highlight_node; - protected $tracker; - protected $export_all_languages; - - /** - * Constructor - * - * @param object $a_parent_obj parent gui object - * @param string $a_parent_cmd parent cmd - * @param ilLMPresentationGUI $a_lm_pres learning module presentation gui object - * @param string $a_lang language - */ - function __construct($a_parent_obj, $a_parent_cmd, ilLMPresentationGUI $a_lm_pres, $a_lang = "-", - $a_focus_id = 0, $export_all_languages = false) - { - global $DIC; - - $this->user = $DIC->user(); - $this->lm_pres = $a_lm_pres; - $this->lm = $this->lm_pres->lm; - $exp_id = (!$this->getOfflineMode() && $this->lm->getProgressIcons()) - ? "ilLMProgressTree" - : ""; - parent::__construct($a_parent_obj, $a_parent_cmd, $this->lm, $exp_id); - $this->lm_set = new ilSetting("lm"); - $this->lang = $a_lang; - if ($a_focus_id > 0) - { - $this->setSecondaryHighlightedNodes(array($a_focus_id)); - } - if ($this->lm->getTOCMode() != "pages") - { - $this->setTypeWhiteList(array("st", "du")); - } - $this->focus_id = $a_focus_id; - $this->export_all_languages = $export_all_languages; - } - - /** - * Get root node - */ - function getRootNode() - { - $root_id = $this->getTree()->readRootId(); - if ($this->focus_id > 0 && $this->getTree()->isInTree($this->focus_id) && - ilLMObject::_lookupType($this->focus_id) == "st") - { -// $root_id = $this->focus_id; - } - return $this->getTree()->getNodeData($root_id); - } - - /** - * Set tracker - * - * @param ilLMTracker $a_val tracker object - */ - function setTracker($a_val) - { - $this->tracker = $a_val; - } - - /** - * Get tracker - * - * @return ilLMTracker tracker object - */ - function getTracker() - { - return $this->tracker; - } - - /** - * Set highlighted node - * - * @param int $a_val node id - */ - function setHighlightNode($a_val) - { - $this->highlight_node = $a_val; - } - - /** - * Get highlighted node - * - * @return int node id - */ - function getHighlightNode() - { - return $this->highlight_node; - } - - /** - * Is node highlighted? - * - * @param mixed $a_node node object/array - * @return boolean node visible true/false - */ - function isNodeHighlighted($a_node) - { - if ($a_node["child"] == $this->getHighlightNode()) - { - return true; - } - return false; - } - - /** - * Get node content - * - * @param array $a_node node array - * @return string node content - */ - function getNodeContent($a_node) - { - if ($a_node["child"] == $this->getNodeId($this->getRootNode())) - { - return $this->lm_pres->getLMPresentationTitle(); - } - - if ($a_node["type"] == "st") - { - return ilStructureObject::_getPresentationTitle($a_node["child"], IL_CHAPTER_TITLE, - $this->lm->isActiveNumbering(), false, false, $this->lm->getId(), $this->lang, true); - } - else if ($a_node["type"] == "pg") - { - return ilLMPageObject::_getPresentationTitle($a_node["child"], - $this->lm->getPageHeader(), $this->lm->isActiveNumbering(), - $this->lm_set->get("time_scheduled_page_activation"), true, $this->lm->getId(), $this->lang, true); - } - else if ($a_node["child"] == $this->getNodeId($this->getRootNode())) - { - return $this->lm->getTitle(); - } - - return $a_node["title"]; - } - - - /** - * Get node icon - * - * @param array $a_node node array - * @return string icon path - */ - function getNodeIcon($a_node) - { - // overwrite chapter icons with lp info? - if(!$this->getOfflineMode() && $a_node["type"] == "st") - { - $icon = $this->checkLPIcon($a_node["child"]); - if ($icon != "") - { - return $icon; - } - } - - // use progress icons (does not depend on lp mode) - if(!$this->getOfflineMode() && $this->lm->getProgressIcons()) - { - return $this->tracker->getIconForLMObject($a_node, $this->highlight_node); - } - - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - - if ($a_node["type"] == "du") - { - $a_node["type"] = "lm"; - } - $a_name = "icon_".$a_node["type"].".svg"; - if ($a_node["type"] == "pg") - { - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - $lm_set = new ilSetting("lm"); - $active = ilLMPage::_lookupActive($a_node["child"], $this->lm->getType(), - $lm_set->get("time_scheduled_page_activation")); - - // is page scheduled? - $img_sc = ($lm_set->get("time_scheduled_page_activation") && - ilLMPage::_isScheduledActivation($a_node["child"], $this->lm->getType()) && !$active - && !$this->getOfflineMode()) - ? "_sc" - : ""; - - $a_name = "icon_pg".$img_sc.".svg"; - - if (!$active && !$this->getOfflineMode()) - { - $a_name = "icon_pg_d".$img_sc.".svg"; - } - } - - return ilUtil::getImagePath($a_name, false, "output", $this->getOfflineMode()); - } - - /** - * Is node clickable - * - * @param array $a_node node array - * @return bool clickable? - */ - function isNodeClickable($a_node) - { - $ilUser = $this->user; - - $orig_node_id = $a_node["child"]; - - // if navigation is restricted based on correct answered questions - // check if we have preceeding pages including unsanswered/incorrect answered questions - if (!$this->getOfflineMode()) - { - if ($this->lm->getRestrictForwardNavigation()) - { - if ($this->getTracker()->hasPredIncorrectAnswers($orig_node_id)) - { - return false; - } - } - } - - if ($a_node["type"] == "st") - { - if (!$this->getOfflineMode()) - { - if ($this->lm->getTOCMode() != "pages") - { - $a_node = $this->getTree()->fetchSuccessorNode($a_node["child"], "pg"); - } - else - { - // faster, but needs pages to be in explorer - $a_node = $this->getSuccessorNode($a_node["child"], "pg"); - } - if ($a_node["child"] == 0) - { - return false; - } - } - else - { - // get next activated page - $found = false; - while (!$found) - { - if ($this->lm->getTOCMode() != "pages") - { - $a_node = $this->getTree()->fetchSuccessorNode($a_node["child"], "pg"); - } - else - { - $a_node = $this->getSuccessorNode($a_node["child"], "pg"); - } - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - $active = ilLMPage::_lookupActive($a_node["child"], $this->lm->getType(), - $this->lm_set->get("time_scheduled_page_activation")); - - if ($a_node["child"] > 0 && !$active) - { - $found = false; - } - else - { - $found = true; - } - } - if ($a_node["child"] <= 0) - { - return false; - } - else - { - $path = $this->getTree()->getPathId($a_node["child"]); - if (!in_array($orig_node_id, $path)) - { - return false; - } - } - } - } - - if ($a_node["type"] == "pg") - { - // check public area mode - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - if($ilUser->getId() == ANONYMOUS_USER_ID && !ilLMObject::_isPagePublic($a_node["child"], true)) - { - return false; - } - } - - return true; - - } - - - /** - * Get node icon alt text - * - * @param array $a_node node array - * @return string alt text - */ - function getNodeIconAlt($a_node) - { - } - - /** - * Get href for node - * - * @param mixed $a_node node object/array - * @return string href attribute - */ - function getNodeHref($a_node) - { - if (!$this->getOfflineMode()) - { - return $this->lm_pres->getLink($this->lm->getRefId(), "", $a_node["child"]); - //return parent::buildLinkTarget($a_node_id, $a_type); - } - else - { - if ($a_node["type"] != "pg") - { - // get next activated page - $found = false; - while (!$found) - { - $a_node = $this->getTree()->fetchSuccessorNode($a_node["child"], "pg"); - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - $active = ilLMPage::_lookupActive($a_node["child"], $this->lm->getType(), - $this->lm_set->get("time_scheduled_page_activation")); - - if ($a_node["child"] > 0 && !$active) - { - $found = false; - } - else - { - $found = true; - } - } - } - - $lang_suffix = ""; - if ($this->export_all_languages) - { - if ($this->lang != "" && $this->lang != "-") - { - $lang_suffix = "_".$this->lang; - } - } - - include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); - if ($nid = ilLMPageObject::getExportId($this->lm->getId(), $a_node["child"])) - { - return "lm_pg_".$nid.$lang_suffix.".html"; - } - return "lm_pg_".$a_node["child"].$lang_suffix.".html"; - } - - } - - /** - * Is node visible? - * - * @param mixed $a_node node object/array - * @return boolean node visible true/false - */ - function isNodeVisible($a_node) - { - include_once("./Modules/LearningModule/classes/class.ilLMTracker.php"); - return ilLMTracker::_isNodeVisible($a_node); - } + protected $lang; + protected $highlight_node; + protected $tracker; + protected $export_all_languages; + + /** + * Constructor + * + * @param object $a_parent_obj parent gui object + * @param string $a_parent_cmd parent cmd + * @param ilLMPresentationGUI $a_lm_pres learning module presentation gui object + * @param string $a_lang language + */ + public function __construct( + $a_parent_obj, + $a_parent_cmd, + ilLMPresentationGUI $a_lm_pres, + $a_lang = "-", + $a_focus_id = 0, + $export_all_languages = false + ) { + global $DIC; + + $this->user = $DIC->user(); + $this->lm_pres = $a_lm_pres; + $this->lm = $this->lm_pres->lm; + $exp_id = (!$this->getOfflineMode() && $this->lm->getProgressIcons()) + ? "ilLMProgressTree" + : ""; + parent::__construct($a_parent_obj, $a_parent_cmd, $this->lm, $exp_id); + $this->lm_set = new ilSetting("lm"); + $this->lang = $a_lang; + if ($a_focus_id > 0) { + $this->setSecondaryHighlightedNodes(array($a_focus_id)); + } + if ($this->lm->getTOCMode() != "pages") { + $this->setTypeWhiteList(array("st", "du")); + } + $this->focus_id = $a_focus_id; + $this->export_all_languages = $export_all_languages; + } + + /** + * Get root node + */ + public function getRootNode() + { + $root_id = $this->getTree()->readRootId(); + if ($this->focus_id > 0 && $this->getTree()->isInTree($this->focus_id) && + ilLMObject::_lookupType($this->focus_id) == "st") { + // $root_id = $this->focus_id; + } + return $this->getTree()->getNodeData($root_id); + } + + /** + * Set tracker + * + * @param ilLMTracker $a_val tracker object + */ + public function setTracker($a_val) + { + $this->tracker = $a_val; + } + + /** + * Get tracker + * + * @return ilLMTracker tracker object + */ + public function getTracker() + { + return $this->tracker; + } + + /** + * Set highlighted node + * + * @param int $a_val node id + */ + public function setHighlightNode($a_val) + { + $this->highlight_node = $a_val; + } + + /** + * Get highlighted node + * + * @return int node id + */ + public function getHighlightNode() + { + return $this->highlight_node; + } + + /** + * Is node highlighted? + * + * @param mixed $a_node node object/array + * @return boolean node visible true/false + */ + public function isNodeHighlighted($a_node) + { + if ($a_node["child"] == $this->getHighlightNode()) { + return true; + } + return false; + } + + /** + * Get node content + * + * @param array $a_node node array + * @return string node content + */ + public function getNodeContent($a_node) + { + if ($a_node["child"] == $this->getNodeId($this->getRootNode())) { + return $this->lm_pres->getLMPresentationTitle(); + } + + if ($a_node["type"] == "st") { + return ilStructureObject::_getPresentationTitle( + $a_node["child"], + IL_CHAPTER_TITLE, + $this->lm->isActiveNumbering(), + false, + false, + $this->lm->getId(), + $this->lang, + true + ); + } elseif ($a_node["type"] == "pg") { + return ilLMPageObject::_getPresentationTitle( + $a_node["child"], + $this->lm->getPageHeader(), + $this->lm->isActiveNumbering(), + $this->lm_set->get("time_scheduled_page_activation"), + true, + $this->lm->getId(), + $this->lang, + true + ); + } elseif ($a_node["child"] == $this->getNodeId($this->getRootNode())) { + return $this->lm->getTitle(); + } + + return $a_node["title"]; + } + + + /** + * Get node icon + * + * @param array $a_node node array + * @return string icon path + */ + public function getNodeIcon($a_node) + { + // overwrite chapter icons with lp info? + if (!$this->getOfflineMode() && $a_node["type"] == "st") { + $icon = $this->checkLPIcon($a_node["child"]); + if ($icon != "") { + return $icon; + } + } + + // use progress icons (does not depend on lp mode) + if (!$this->getOfflineMode() && $this->lm->getProgressIcons()) { + return $this->tracker->getIconForLMObject($a_node, $this->highlight_node); + } + + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + + if ($a_node["type"] == "du") { + $a_node["type"] = "lm"; + } + $a_name = "icon_" . $a_node["type"] . ".svg"; + if ($a_node["type"] == "pg") { + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + $lm_set = new ilSetting("lm"); + $active = ilLMPage::_lookupActive( + $a_node["child"], + $this->lm->getType(), + $lm_set->get("time_scheduled_page_activation") + ); + + // is page scheduled? + $img_sc = ($lm_set->get("time_scheduled_page_activation") && + ilLMPage::_isScheduledActivation($a_node["child"], $this->lm->getType()) && !$active + && !$this->getOfflineMode()) + ? "_sc" + : ""; + + $a_name = "icon_pg" . $img_sc . ".svg"; + + if (!$active && !$this->getOfflineMode()) { + $a_name = "icon_pg_d" . $img_sc . ".svg"; + } + } + + return ilUtil::getImagePath($a_name, false, "output", $this->getOfflineMode()); + } + + /** + * Is node clickable + * + * @param array $a_node node array + * @return bool clickable? + */ + public function isNodeClickable($a_node) + { + $ilUser = $this->user; + + $orig_node_id = $a_node["child"]; + + // if navigation is restricted based on correct answered questions + // check if we have preceeding pages including unsanswered/incorrect answered questions + if (!$this->getOfflineMode()) { + if ($this->lm->getRestrictForwardNavigation()) { + if ($this->getTracker()->hasPredIncorrectAnswers($orig_node_id)) { + return false; + } + } + } + + if ($a_node["type"] == "st") { + if (!$this->getOfflineMode()) { + if ($this->lm->getTOCMode() != "pages") { + $a_node = $this->getTree()->fetchSuccessorNode($a_node["child"], "pg"); + } else { + // faster, but needs pages to be in explorer + $a_node = $this->getSuccessorNode($a_node["child"], "pg"); + } + if ($a_node["child"] == 0) { + return false; + } + } else { + // get next activated page + $found = false; + while (!$found) { + if ($this->lm->getTOCMode() != "pages") { + $a_node = $this->getTree()->fetchSuccessorNode($a_node["child"], "pg"); + } else { + $a_node = $this->getSuccessorNode($a_node["child"], "pg"); + } + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + $active = ilLMPage::_lookupActive( + $a_node["child"], + $this->lm->getType(), + $this->lm_set->get("time_scheduled_page_activation") + ); + + if ($a_node["child"] > 0 && !$active) { + $found = false; + } else { + $found = true; + } + } + if ($a_node["child"] <= 0) { + return false; + } else { + $path = $this->getTree()->getPathId($a_node["child"]); + if (!in_array($orig_node_id, $path)) { + return false; + } + } + } + } + + if ($a_node["type"] == "pg") { + // check public area mode + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + if ($ilUser->getId() == ANONYMOUS_USER_ID && !ilLMObject::_isPagePublic($a_node["child"], true)) { + return false; + } + } + + return true; + } + + + /** + * Get node icon alt text + * + * @param array $a_node node array + * @return string alt text + */ + public function getNodeIconAlt($a_node) + { + } + + /** + * Get href for node + * + * @param mixed $a_node node object/array + * @return string href attribute + */ + public function getNodeHref($a_node) + { + if (!$this->getOfflineMode()) { + return $this->lm_pres->getLink($this->lm->getRefId(), "", $a_node["child"]); + //return parent::buildLinkTarget($a_node_id, $a_type); + } else { + if ($a_node["type"] != "pg") { + // get next activated page + $found = false; + while (!$found) { + $a_node = $this->getTree()->fetchSuccessorNode($a_node["child"], "pg"); + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + $active = ilLMPage::_lookupActive( + $a_node["child"], + $this->lm->getType(), + $this->lm_set->get("time_scheduled_page_activation") + ); + + if ($a_node["child"] > 0 && !$active) { + $found = false; + } else { + $found = true; + } + } + } + + $lang_suffix = ""; + if ($this->export_all_languages) { + if ($this->lang != "" && $this->lang != "-") { + $lang_suffix = "_" . $this->lang; + } + } + + include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); + if ($nid = ilLMPageObject::getExportId($this->lm->getId(), $a_node["child"])) { + return "lm_pg_" . $nid . $lang_suffix . ".html"; + } + return "lm_pg_" . $a_node["child"] . $lang_suffix . ".html"; + } + } + + /** + * Is node visible? + * + * @param mixed $a_node node object/array + * @return boolean node visible true/false + */ + public function isNodeVisible($a_node) + { + include_once("./Modules/LearningModule/classes/class.ilLMTracker.php"); + return ilLMTracker::_isNodeVisible($a_node); + } } - -?> diff --git a/Modules/LearningModule/classes/class.ilLMTableOfContentsExplorerGUI.php b/Modules/LearningModule/classes/class.ilLMTableOfContentsExplorerGUI.php index 8c852021e2c8a3fde5ea4c4cc704faa7a49275f3..7961f434b3ad16541997d8b6ef0852b60f4cef5f 100644 --- a/Modules/LearningModule/classes/class.ilLMTableOfContentsExplorerGUI.php +++ b/Modules/LearningModule/classes/class.ilLMTableOfContentsExplorerGUI.php @@ -13,24 +13,21 @@ include_once("./Modules/LearningModule/classes/class.ilLMTOCExplorerGUI.php"); */ class ilLMTableOfContentsExplorerGUI extends ilLMTOCExplorerGUI { - /** - * Constructor - * - * @param object $a_parent_obj parent gui object - * @param string $a_parent_cmd parent cmd - * @param ilLMPresentationGUI $a_lm_pres learning module presentation gui object - * @param string $a_lang language - */ - function __construct($a_parent_obj, $a_parent_cmd, ilLMPresentationGUI $a_lm_pres, $a_lang = "-") - { - parent::__construct($a_parent_obj, $a_parent_cmd, $a_lm_pres, $a_lang); - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - $chaps = ilLMObject::_getAllLMObjectsOfLM($this->lm->getId(), $a_type = "st"); - foreach ($chaps as $c) - { - $this->setNodeOpen($c); - } - } + /** + * Constructor + * + * @param object $a_parent_obj parent gui object + * @param string $a_parent_cmd parent cmd + * @param ilLMPresentationGUI $a_lm_pres learning module presentation gui object + * @param string $a_lang language + */ + public function __construct($a_parent_obj, $a_parent_cmd, ilLMPresentationGUI $a_lm_pres, $a_lang = "-") + { + parent::__construct($a_parent_obj, $a_parent_cmd, $a_lm_pres, $a_lang); + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + $chaps = ilLMObject::_getAllLMObjectsOfLM($this->lm->getId(), $a_type = "st"); + foreach ($chaps as $c) { + $this->setNodeOpen($c); + } + } } - -?> diff --git a/Modules/LearningModule/classes/class.ilLMTracker.php b/Modules/LearningModule/classes/class.ilLMTracker.php index c0acca2f84ec67b86d1fd217373e630cdbaae8e6..69d7546268692c9fb57420d4bf46b71244cdf135 100644 --- a/Modules/LearningModule/classes/class.ilLMTracker.php +++ b/Modules/LearningModule/classes/class.ilLMTracker.php @@ -11,711 +11,646 @@ */ class ilLMTracker { - /** - * @var ilDB - */ - protected $db; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilPluginAdmin - */ - protected $plugin_admin; - - /** - * @var ilObjUser - */ - protected $user; - - const NOT_ATTEMPTED = 0; - const IN_PROGRESS = 1; - const COMPLETED = 2; - const FAILED = 3; - const CURRENT = 99; - - protected $lm_ref_id; - protected $lm_obj_id; - protected $lm_tree; - protected $lm_obj_ids = array(); - protected $tree_arr = array(); // tree array - protected $re_arr = array(); // read event data array - protected $loaded_for_node = false; // current node for that the tracking data has been loaded - protected $dirty = false; - protected $page_questions = array(); - protected $all_questions = array(); - protected $answer_status = array(); - protected $has_incorrect_answers = false; - protected $current_page_id = 0; - - static $instances = array(); - static $instancesbyobj = array(); - - //// - //// Constructing - //// - - /** - * Constructor - * - * @param ilObjLearningModule $a_lm learning module - */ - private function __construct($a_id, $a_by_obj_id = false, $a_user_id) - { - global $DIC; - - $this->db = $DIC->database(); - $this->lng = $DIC->language(); - $this->plugin_admin = $DIC["ilPluginAdmin"]; - $this->user = $DIC->user(); - $this->user_id = $a_user_id; - - if ($a_by_obj_id) - { - $this->lm_ref_id = 0; - $this->lm_obj_id = $a_id; - } - else - { - $this->lm_ref_id = $a_id; - $this->lm_obj_id = ilObject::_lookupObjId($a_id); - } - - include_once("./Modules/LearningModule/classes/class.ilLMTree.php"); - $this->lm_tree = ilLMTree::getInstance($this->lm_obj_id); - } - - /** - * Get instance - * - * @param - * @return - */ - static function getInstance($a_ref_id, $a_user_id = 0) - { - global $DIC; - - $ilUser = $DIC->user(); - - if ($a_user_id == 0) - { - $a_user_id = $ilUser->getId(); - } - - if (!isset(self::$instances[$a_ref_id][$a_user_id])) - { - self::$instances[$a_ref_id][$a_user_id] = new ilLMTracker($a_ref_id, false, $a_user_id); - } - return self::$instances[$a_ref_id][$a_user_id]; - } - - /** - * Get instance - * - * @param - * @return - */ - static function getInstanceByObjId($a_obj_id, $a_user_id = 0) - { - global $DIC; - - $ilUser = $DIC->user(); - - if ($a_user_id == 0) - { - $a_user_id = $ilUser->getId(); - } - - if (!isset(self::$instancesbyobj[$a_obj_id][$a_user_id])) - { - self::$instancesbyobj[$a_obj_id][$a_user_id] = new ilLMTracker($a_obj_id, true, $a_user_id); - } - return self::$instancesbyobj[$a_obj_id][$a_user_id]; - } - - //// - //// Tracking - //// - - /** - * Track access to lm page - * - * @param int $a_page_id page id - */ - function trackAccess($a_page_id) - { - if ($this->lm_ref_id == 0) - { - die("ilLMTracker: No Ref Id given."); - } - - // track page and chapter access - $this->trackPageAndChapterAccess($a_page_id); - - // track last page access (must be done after calling trackPageAndChapterAccess()) - $this->trackLastPageAccess($this->user_id, $this->lm_ref_id, $a_page_id); - - // #9483 - // general learning module lp tracking - include_once("./Services/Tracking/classes/class.ilLearningProgress.php"); - ilLearningProgress::_tracProgress($this->user_id, $this->lm_obj_id, - $this->lm_ref_id, "lm"); - - // obsolete? - include_once("./Services/Tracking/classes/class.ilLPStatusWrapper.php"); - ilLPStatusWrapper::_updateStatus($this->lm_obj_id, $this->user_id); - - // mark currently loaded data as dirty to force reload if necessary - $this->dirty = true; - } - - /** - * Track last accessed page for a learning module - * - * @param int $usr_id user id - * @param int $lm_id learning module id - * @param int $obj_id page id - */ - function trackLastPageAccess($usr_id, $lm_id, $obj_id) - { - $ilDB = $this->db; - - // first check if an entry for this user and this lm already exist, when so, delete - $q = "DELETE FROM lo_access ". - "WHERE usr_id = ".$ilDB->quote((int) $usr_id, "integer")." ". - "AND lm_id = ".$ilDB->quote((int) $lm_id, "integer"); - $ilDB->manipulate($q); - - $title = ""; - - $q = "INSERT INTO lo_access ". - "(timestamp,usr_id,lm_id,obj_id,lm_title) ". - "VALUES ". - "(".$ilDB->now().",". - $ilDB->quote((int) $usr_id, "integer").",". - $ilDB->quote((int) $lm_id, "integer").",". - $ilDB->quote((int) $obj_id, "integer").",". - $ilDB->quote($title, "text").")"; - $ilDB->manipulate($q); - } - - - /** - * Track page and chapter access - */ - protected function trackPageAndChapterAccess($a_page_id) - { - $ilDB = $this->db; - - $now = time(); - - // - // 1. Page access: current page - // - $set = $ilDB->query("SELECT obj_id FROM lm_read_event". - " WHERE obj_id = ".$ilDB->quote($a_page_id, "integer"). - " AND usr_id = ".$ilDB->quote($this->user_id, "integer")); - if (!$ilDB->fetchAssoc($set)) - { - $fields = array( - "obj_id" => array("integer", $a_page_id), - "usr_id" => array("integer", $this->user_id) - ); - // $ilDB->insert("lm_read_event", $fields); - $ilDB->replace("lm_read_event", $fields, array()); // #15144 - } - - // update all parent chapters - $ilDB->manipulate("UPDATE lm_read_event SET". - " read_count = read_count + 1 ". - " , last_access = ".$ilDB->quote($now, "integer"). - " WHERE obj_id = ".$ilDB->quote($a_page_id, "integer"). - " AND usr_id = ".$ilDB->quote($this->user_id, "integer")); - - - // - // 2. Chapter access: based on last page accessed - // - - // get last accessed page - $set = $ilDB->query("SELECT * FROM lo_access WHERE ". - "usr_id = ".$ilDB->quote($this->user_id, "integer")." AND ". - "lm_id = ".$ilDB->quote($this->lm_ref_id, "integer")); - $res = $ilDB->fetchAssoc($set); - if($res["obj_id"]) - { - include_once('Services/Tracking/classes/class.ilObjUserTracking.php'); - $valid_timespan = ilObjUserTracking::_getValidTimeSpan(); - - $pg_ts = new ilDateTime($res["timestamp"], IL_CAL_DATETIME); - $pg_ts = $pg_ts->get(IL_CAL_UNIX); - $pg_id = $res["obj_id"]; - if(!$this->lm_tree->isInTree($pg_id)) - { - return; - } - - $time_diff = $read_diff = 0; - - // spent_seconds or read_count ? - if (($now-$pg_ts) <= $valid_timespan) - { - $time_diff = $now-$pg_ts; - } - else - { - $read_diff = 1; - } - - // find parent chapter(s) for that page - $parent_st_ids = array(); - foreach($this->lm_tree->getPathFull($pg_id) as $item) - { - if($item["type"] == "st") - { - $parent_st_ids[] = $item["obj_id"]; - } - } - - if($parent_st_ids && ($time_diff || $read_diff)) - { - // get existing chapter entries - $ex_st = array(); - $set = $ilDB->query("SELECT obj_id FROM lm_read_event". - " WHERE ".$ilDB->in("obj_id", $parent_st_ids, "", "integer"). - " AND usr_id = ".$ilDB->quote($this->user_id, "integer")); - while($row = $ilDB->fetchAssoc($set)) - { - $ex_st[] = $row["obj_id"]; - } - - // add missing chapter entries - $missing_st = array_diff($parent_st_ids, $ex_st); - if(sizeof($missing_st)) - { - foreach($missing_st as $st_id) - { - $fields = array( - "obj_id" => array("integer", $st_id), - "usr_id" => array("integer", $this->user_id) - ); - // $ilDB->insert("lm_read_event", $fields); - $ilDB->replace("lm_read_event", $fields, array()); // #15144 - } - } - - // update all parent chapters - $ilDB->manipulate("UPDATE lm_read_event SET". - " read_count = read_count + ".$ilDB->quote($read_diff, "integer"). - " , spent_seconds = spent_seconds + ".$ilDB->quote($time_diff, "integer"). - " , last_access = ".$ilDB->quote($now, "integer"). - " WHERE ".$ilDB->in("obj_id", $parent_st_ids, "", "integer"). - " AND usr_id = ".$ilDB->quote($this->user_id, "integer")); - } - } - } - - - //// - //// Tracking - //// - - /** - * Set current page - * - * @param id $a_val current page id - */ - public function setCurrentPage($a_val) - { - $this->current_page_id = $a_val; - } - - /** - * Get current page - * - * @return id current page id - */ - public function getCurrentPage() - { - return $this->current_page_id; - } - - /** - * Load LM tracking data. Loaded when needed. - * - * @param - * @return - */ - protected function loadLMTrackingData() - { - $ilDB = $this->db; - - // we must prevent loading tracking data multiple times during a request where possible - // please note that the dirty flag works only to a certain limit - // e.g. if questions are answered the flag is not set (yet) - // or if pages/chapter are added/deleted the flag is not set - if ($this->loaded_for_node === (int) $this->getCurrentPage() && !$this->dirty) - { - return; - } - - $this->loaded_for_node = (int) $this->getCurrentPage(); - $this->dirty = false; - - // load lm tree in array - $this->tree_arr = array(); - $nodes = $this->lm_tree->getSubTree($this->lm_tree->getNodeData($this->lm_tree->readRootId())); - foreach ($nodes as $node) - { - $this->tree_arr["childs"][$node["parent"]][] = $node; - $this->tree_arr["parent"][$node["child"]] = $node["parent"]; - $this->tree_arr["nodes"][$node["child"]] = $node; - } - - // load all lm obj ids of learning module - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - $this->lm_obj_ids = ilLMObject::_getAllLMObjectsOfLM($this->lm_obj_id); - - // load read event data - $this->re_arr = array(); - $set = $ilDB->query("SELECT * FROM lm_read_event ". - " WHERE ".$ilDB->in("obj_id", $this->lm_obj_ids, false, "integer"). - " AND usr_id = ".$ilDB->quote($this->user_id, "integer")); - while ($rec = $ilDB->fetchAssoc($set)) - { - $this->re_arr[$rec["obj_id"]] = $rec; - } - - // load question/pages information - $this->page_questions = array(); - $this->all_questions = array(); - include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); - $q = ilLMPageObject::queryQuestionsOfLearningModule($this->lm_obj_id, "", "", 0, 0); - foreach ($q["set"] as $quest) - { - $this->page_questions[$quest["page_id"]][] = $quest["question_id"]; - $this->all_questions[] = $quest["question_id"]; - } - - // load question answer information - include_once("./Services/COPage/classes/class.ilPageQuestionProcessor.php"); - $this->answer_status = ilPageQuestionProcessor::getAnswerStatus($this->all_questions, $this->user_id); - - $this->has_incorrect_answers = false; - - $has_pred_incorrect_answers = false; - $has_pred_incorrect_not_unlocked_answers = false; - $this->determineProgressStatus($this->lm_tree->readRootId(), $has_pred_incorrect_answers, $has_pred_incorrect_not_unlocked_answers); - - $this->has_incorrect_answers = $has_pred_incorrect_answers; - } - - /** - * Have all questoins been answered correctly (and questions exist)? - * - * @return bool true, if learning module contains any question and all questions (in the chapter structure) have been answered correctly - */ - function getAllQuestionsCorrect() - { - $this->loadLMTrackingData(); - if (count($this->all_questions) > 0 && !$this->has_incorrect_answers) - { - return true; - } - return false; - } - - - /** - * Determine progress status of nodes - * - * @param int $a_obj_id lm object id - * @return int status - */ - protected function determineProgressStatus($a_obj_id, &$a_has_pred_incorrect_answers, &$a_has_pred_incorrect_not_unlocked_answers) - { - $status = ilLMTracker::NOT_ATTEMPTED; - - if (isset($this->tree_arr["nodes"][$a_obj_id])) - { - $this->tree_arr["nodes"][$a_obj_id]["has_pred_incorrect_answers"] = $a_has_pred_incorrect_answers; - $this->tree_arr["nodes"][$a_obj_id]["has_pred_incorrect_not_unlocked_answers"] = $a_has_pred_incorrect_not_unlocked_answers; - - if (is_array($this->tree_arr["childs"][$a_obj_id])) - { - // sort childs in correct order - $this->tree_arr["childs"][$a_obj_id] = ilUtil::sortArray($this->tree_arr["childs"][$a_obj_id], "lft", "asc", true); - - $cnt_completed = 0; - foreach ($this->tree_arr["childs"][$a_obj_id] as $c) - { - // if child is not activated/displayed count child as implicitly completed - // rationale: everything that is visible for the learner determines the status - // see also bug #14642 - if (!self::_isNodeVisible($c)) - { - $cnt_completed++; - continue; - } - $c_stat = $this->determineProgressStatus($c["child"], $a_has_pred_incorrect_answers, - $a_has_pred_incorrect_not_unlocked_answers); - if ($status != ilLMTracker::FAILED) - { - if ($c_stat == ilLMTracker::FAILED) - { - $status = ilLMTracker::IN_PROGRESS; - } - else if ($c_stat == ilLMTracker::IN_PROGRESS) - { - $status = ilLMTracker::IN_PROGRESS; - } - else if ($c_stat == ilLMTracker::COMPLETED || $c_stat == ilLMTracker::CURRENT) - { - $status = ilLMTracker::IN_PROGRESS; - $cnt_completed++; - } - } - // if an item is failed or in progress or (not attempted and contains questions) - // the next item has predecessing incorrect answers - if ($this->tree_arr["nodes"][$c["child"]]["type"] == "pg") - { - if ($c_stat == ilLMTracker::FAILED || $c_stat == ilLMTracker::IN_PROGRESS || - ($c_stat == ilLMTracker::NOT_ATTEMPTED && is_array($this->page_questions[$c["child"]]) && count($this->page_questions[$c["child"]]) > 0)) - { - $a_has_pred_incorrect_answers = true; - if (!$this->tree_arr["nodes"][$c["child"]]["unlocked"]) - { - $a_has_pred_incorrect_not_unlocked_answers = true; - } - } - } - } - if ($cnt_completed == count($this->tree_arr["childs"][$a_obj_id])) - { - $status = ilLMTracker::COMPLETED; - } - } - else if ($this->tree_arr["nodes"][$a_obj_id]["type"] == "pg") - { - // check read event data - if (isset($this->re_arr[$a_obj_id]) && $this->re_arr[$a_obj_id]["read_count"] > 0) - { - $status = ilLMTracker::COMPLETED; - } - else if ($a_obj_id == $this->getCurrentPage()) - { - $status = ilLMTracker::CURRENT; - } - - $unlocked = false; - if (is_array($this->page_questions[$a_obj_id])) - { - // check questions, if one is failed -> failed - $unlocked = true; - foreach ($this->page_questions[$a_obj_id] as $q_id) - { - if (is_array($this->answer_status[$q_id]) - && $this->answer_status[$q_id]["try"] > 0 - && !$this->answer_status[$q_id]["passed"]) - { - $status = ilLMTracker::FAILED; - if (!$this->answer_status[$q_id]["unlocked"]) - { - $unlocked = false; - } - } - } - - // check questions, if one is not answered -> in progress - if ($status != ilLMTracker::FAILED) - { - foreach ($this->page_questions[$a_obj_id] as $q_id) - { - if (!is_array($this->answer_status[$q_id]) - || $this->answer_status[$q_id]["try"] == 0) - { - if ($status != ilLMTracker::NOT_ATTEMPTED) - { - $status = ilLMTracker::IN_PROGRESS; - } - } - } - $unlocked = false; - } - } - $this->tree_arr["nodes"][$a_obj_id]["unlocked"] = $unlocked; - $this->tree_arr["nodes"][$a_obj_id]["has_pred_incorrect_answers"] = $a_has_pred_incorrect_answers; - $this->tree_arr["nodes"][$a_obj_id]["has_pred_incorrect_not_unlocked_answers"] = $a_has_pred_incorrect_not_unlocked_answers; - } - } - else // free pages (currently not called, since only walking through tree structure) - { - - } - $this->tree_arr["nodes"][$a_obj_id]["status"] = $status; - - return $status; - } - - - /** - * Get icon for lm object - * - * @param array $a_node node array - * @param int $a_highlighted_node current node id - * @return string image path - */ - public function getIconForLMObject($a_node, $a_highlighted_node = 0) - { - $this->loadLMTrackingData(); - if ($a_node["child"] == $a_highlighted_node) - { - return ilUtil::getImagePath('scorm/running.svg'); - } - if (isset($this->tree_arr["nodes"][$a_node["child"]])) - { - switch ($this->tree_arr["nodes"][$a_node["child"]]["status"]) - { - case ilLMTracker::IN_PROGRESS: - return ilUtil::getImagePath('scorm/incomplete.svg'); - - case ilLMTracker::FAILED: - return ilUtil::getImagePath('scorm/failed.svg'); - - case ilLMTracker::COMPLETED: - return ilUtil::getImagePath('scorm/completed.svg'); - } - } - return ilUtil::getImagePath('scorm/not_attempted.svg'); - } - - /** - * Has predecessing incorrect answers - * - * @param int $a_obj_id - * @return bool true if incorrect/unsanswered questions exist in predecessing pages - */ - function hasPredIncorrectAnswers($a_obj_id, $a_ignore_unlock = false) - { - $this->loadLMTrackingData(); - $ret = false; - if (is_array($this->tree_arr["nodes"][$a_obj_id])) - { - if ($a_ignore_unlock) - { - $ret = $this->tree_arr["nodes"][$a_obj_id]["has_pred_incorrect_answers"]; - } - else - { - $ret = $this->tree_arr["nodes"][$a_obj_id]["has_pred_incorrect_not_unlocked_answers"]; - } - } - return $ret; - } - - //// - //// Blocked Users - //// - - /** - * Get blocked users information - * - * @param - * @return - */ - function getBlockedUsersInformation() - { - $ilDB = $this->db; - $lng = $this->lng; - $ilPluginAdmin = $this->plugin_admin; - $ilUser = $this->user; - - $blocked_users = array(); - - // load question/pages information - $this->page_questions = array(); - $this->all_questions = array(); - $page_for_question = array(); - include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); - $q = ilLMPageObject::queryQuestionsOfLearningModule($this->lm_obj_id, "", "", 0, 0); - foreach ($q["set"] as $quest) - { - $this->page_questions[$quest["page_id"]][] = $quest["question_id"]; - $this->all_questions[] = $quest["question_id"]; - $page_for_question[$quest["question_id"]] = $quest["page_id"]; - } - // get question information - include_once("./Modules/TestQuestionPool/classes/class.ilAssQuestionList.php"); - $qlist = new ilAssQuestionList($ilDB, $lng, $ilPluginAdmin); - $qlist->setParentObjId(0); - $qlist->setJoinObjectData(false); - $qlist->addFieldFilter("question_id", $this->all_questions); - $qlist->load(); - $qdata = $qlist->getQuestionDataArray(); - - // load question answer information - include_once("./Services/COPage/classes/class.ilPageQuestionProcessor.php"); - $this->answer_status = ilPageQuestionProcessor::getAnswerStatus($this->all_questions); - include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); - foreach ($this->answer_status as $as) - { - if ($as["try"] >= $qdata[$as["qst_id"]]["nr_of_tries"] && $qdata[$as["qst_id"]]["nr_of_tries"] > 0 && !$as["passed"]) - { - //var_dump($qdata[$as["qst_id"]]); - $name = ilObjUser::_lookupName($as["user_id"]); - $as["user_name"] = $name["lastname"].", ".$name["firstname"]." [".$name["login"]."]"; - $as["question_text"] = $qdata[$as["qst_id"]]["question_text"]; - $as["page_id"] = $page_for_question[$as["qst_id"]]; - $as["page_title"] = ilLMPageObject::_lookupTitle($as["page_id"]); - $blocked_users[] = $as; - } - } - - return $blocked_users; - } - - /** - * Is node visible for the learner - * - * @param mixed $a_node node object/array - * @return boolean node visible true/false - */ - static function _isNodeVisible($a_node) - { - include_once("./Services/COPage/classes/class.ilPageObject.php"); - - if ($a_node["type"] != "pg") - { - return true; - } - - $lm_set = new ilSetting("lm"); - $active = ilPageObject::_lookupActive($a_node["child"], "lm", - $lm_set->get("time_scheduled_page_activation")); - - if(!$active) - { - $act_data = ilPageObject::_lookupActivationData((int) $a_node["child"], "lm"); - if ($act_data["show_activation_info"] && - (ilUtil::now() < $act_data["activation_start"])) - { - return true; - } - else - { - return false; - } - } - else - { - return true; - } - } - - + /** + * @var ilDB + */ + protected $db; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilPluginAdmin + */ + protected $plugin_admin; + + /** + * @var ilObjUser + */ + protected $user; + + const NOT_ATTEMPTED = 0; + const IN_PROGRESS = 1; + const COMPLETED = 2; + const FAILED = 3; + const CURRENT = 99; + + protected $lm_ref_id; + protected $lm_obj_id; + protected $lm_tree; + protected $lm_obj_ids = array(); + protected $tree_arr = array(); // tree array + protected $re_arr = array(); // read event data array + protected $loaded_for_node = false; // current node for that the tracking data has been loaded + protected $dirty = false; + protected $page_questions = array(); + protected $all_questions = array(); + protected $answer_status = array(); + protected $has_incorrect_answers = false; + protected $current_page_id = 0; + + public static $instances = array(); + public static $instancesbyobj = array(); + + //// + //// Constructing + //// + + /** + * Constructor + * + * @param ilObjLearningModule $a_lm learning module + */ + private function __construct($a_id, $a_by_obj_id = false, $a_user_id) + { + global $DIC; + + $this->db = $DIC->database(); + $this->lng = $DIC->language(); + $this->plugin_admin = $DIC["ilPluginAdmin"]; + $this->user = $DIC->user(); + $this->user_id = $a_user_id; + + if ($a_by_obj_id) { + $this->lm_ref_id = 0; + $this->lm_obj_id = $a_id; + } else { + $this->lm_ref_id = $a_id; + $this->lm_obj_id = ilObject::_lookupObjId($a_id); + } + + include_once("./Modules/LearningModule/classes/class.ilLMTree.php"); + $this->lm_tree = ilLMTree::getInstance($this->lm_obj_id); + } + + /** + * Get instance + * + * @param + * @return + */ + public static function getInstance($a_ref_id, $a_user_id = 0) + { + global $DIC; + + $ilUser = $DIC->user(); + + if ($a_user_id == 0) { + $a_user_id = $ilUser->getId(); + } + + if (!isset(self::$instances[$a_ref_id][$a_user_id])) { + self::$instances[$a_ref_id][$a_user_id] = new ilLMTracker($a_ref_id, false, $a_user_id); + } + return self::$instances[$a_ref_id][$a_user_id]; + } + + /** + * Get instance + * + * @param + * @return + */ + public static function getInstanceByObjId($a_obj_id, $a_user_id = 0) + { + global $DIC; + + $ilUser = $DIC->user(); + + if ($a_user_id == 0) { + $a_user_id = $ilUser->getId(); + } + + if (!isset(self::$instancesbyobj[$a_obj_id][$a_user_id])) { + self::$instancesbyobj[$a_obj_id][$a_user_id] = new ilLMTracker($a_obj_id, true, $a_user_id); + } + return self::$instancesbyobj[$a_obj_id][$a_user_id]; + } + + //// + //// Tracking + //// + + /** + * Track access to lm page + * + * @param int $a_page_id page id + */ + public function trackAccess($a_page_id) + { + if ($this->lm_ref_id == 0) { + die("ilLMTracker: No Ref Id given."); + } + + // track page and chapter access + $this->trackPageAndChapterAccess($a_page_id); + + // track last page access (must be done after calling trackPageAndChapterAccess()) + $this->trackLastPageAccess($this->user_id, $this->lm_ref_id, $a_page_id); + + // #9483 + // general learning module lp tracking + include_once("./Services/Tracking/classes/class.ilLearningProgress.php"); + ilLearningProgress::_tracProgress( + $this->user_id, + $this->lm_obj_id, + $this->lm_ref_id, + "lm" + ); + + // obsolete? + include_once("./Services/Tracking/classes/class.ilLPStatusWrapper.php"); + ilLPStatusWrapper::_updateStatus($this->lm_obj_id, $this->user_id); + + // mark currently loaded data as dirty to force reload if necessary + $this->dirty = true; + } + + /** + * Track last accessed page for a learning module + * + * @param int $usr_id user id + * @param int $lm_id learning module id + * @param int $obj_id page id + */ + public function trackLastPageAccess($usr_id, $lm_id, $obj_id) + { + $ilDB = $this->db; + + // first check if an entry for this user and this lm already exist, when so, delete + $q = "DELETE FROM lo_access " . + "WHERE usr_id = " . $ilDB->quote((int) $usr_id, "integer") . " " . + "AND lm_id = " . $ilDB->quote((int) $lm_id, "integer"); + $ilDB->manipulate($q); + + $title = ""; + + $q = "INSERT INTO lo_access " . + "(timestamp,usr_id,lm_id,obj_id,lm_title) " . + "VALUES " . + "(" . $ilDB->now() . "," . + $ilDB->quote((int) $usr_id, "integer") . "," . + $ilDB->quote((int) $lm_id, "integer") . "," . + $ilDB->quote((int) $obj_id, "integer") . "," . + $ilDB->quote($title, "text") . ")"; + $ilDB->manipulate($q); + } + + + /** + * Track page and chapter access + */ + protected function trackPageAndChapterAccess($a_page_id) + { + $ilDB = $this->db; + + $now = time(); + + // + // 1. Page access: current page + // + $set = $ilDB->query("SELECT obj_id FROM lm_read_event" . + " WHERE obj_id = " . $ilDB->quote($a_page_id, "integer") . + " AND usr_id = " . $ilDB->quote($this->user_id, "integer")); + if (!$ilDB->fetchAssoc($set)) { + $fields = array( + "obj_id" => array("integer", $a_page_id), + "usr_id" => array("integer", $this->user_id) + ); + // $ilDB->insert("lm_read_event", $fields); + $ilDB->replace("lm_read_event", $fields, array()); // #15144 + } + + // update all parent chapters + $ilDB->manipulate("UPDATE lm_read_event SET" . + " read_count = read_count + 1 " . + " , last_access = " . $ilDB->quote($now, "integer") . + " WHERE obj_id = " . $ilDB->quote($a_page_id, "integer") . + " AND usr_id = " . $ilDB->quote($this->user_id, "integer")); + + + // + // 2. Chapter access: based on last page accessed + // + + // get last accessed page + $set = $ilDB->query("SELECT * FROM lo_access WHERE " . + "usr_id = " . $ilDB->quote($this->user_id, "integer") . " AND " . + "lm_id = " . $ilDB->quote($this->lm_ref_id, "integer")); + $res = $ilDB->fetchAssoc($set); + if ($res["obj_id"]) { + include_once('Services/Tracking/classes/class.ilObjUserTracking.php'); + $valid_timespan = ilObjUserTracking::_getValidTimeSpan(); + + $pg_ts = new ilDateTime($res["timestamp"], IL_CAL_DATETIME); + $pg_ts = $pg_ts->get(IL_CAL_UNIX); + $pg_id = $res["obj_id"]; + if (!$this->lm_tree->isInTree($pg_id)) { + return; + } + + $time_diff = $read_diff = 0; + + // spent_seconds or read_count ? + if (($now-$pg_ts) <= $valid_timespan) { + $time_diff = $now-$pg_ts; + } else { + $read_diff = 1; + } + + // find parent chapter(s) for that page + $parent_st_ids = array(); + foreach ($this->lm_tree->getPathFull($pg_id) as $item) { + if ($item["type"] == "st") { + $parent_st_ids[] = $item["obj_id"]; + } + } + + if ($parent_st_ids && ($time_diff || $read_diff)) { + // get existing chapter entries + $ex_st = array(); + $set = $ilDB->query("SELECT obj_id FROM lm_read_event" . + " WHERE " . $ilDB->in("obj_id", $parent_st_ids, "", "integer") . + " AND usr_id = " . $ilDB->quote($this->user_id, "integer")); + while ($row = $ilDB->fetchAssoc($set)) { + $ex_st[] = $row["obj_id"]; + } + + // add missing chapter entries + $missing_st = array_diff($parent_st_ids, $ex_st); + if (sizeof($missing_st)) { + foreach ($missing_st as $st_id) { + $fields = array( + "obj_id" => array("integer", $st_id), + "usr_id" => array("integer", $this->user_id) + ); + // $ilDB->insert("lm_read_event", $fields); + $ilDB->replace("lm_read_event", $fields, array()); // #15144 + } + } + + // update all parent chapters + $ilDB->manipulate("UPDATE lm_read_event SET" . + " read_count = read_count + " . $ilDB->quote($read_diff, "integer") . + " , spent_seconds = spent_seconds + " . $ilDB->quote($time_diff, "integer") . + " , last_access = " . $ilDB->quote($now, "integer") . + " WHERE " . $ilDB->in("obj_id", $parent_st_ids, "", "integer") . + " AND usr_id = " . $ilDB->quote($this->user_id, "integer")); + } + } + } + + + //// + //// Tracking + //// + + /** + * Set current page + * + * @param id $a_val current page id + */ + public function setCurrentPage($a_val) + { + $this->current_page_id = $a_val; + } + + /** + * Get current page + * + * @return id current page id + */ + public function getCurrentPage() + { + return $this->current_page_id; + } + + /** + * Load LM tracking data. Loaded when needed. + * + * @param + * @return + */ + protected function loadLMTrackingData() + { + $ilDB = $this->db; + + // we must prevent loading tracking data multiple times during a request where possible + // please note that the dirty flag works only to a certain limit + // e.g. if questions are answered the flag is not set (yet) + // or if pages/chapter are added/deleted the flag is not set + if ($this->loaded_for_node === (int) $this->getCurrentPage() && !$this->dirty) { + return; + } + + $this->loaded_for_node = (int) $this->getCurrentPage(); + $this->dirty = false; + + // load lm tree in array + $this->tree_arr = array(); + $nodes = $this->lm_tree->getSubTree($this->lm_tree->getNodeData($this->lm_tree->readRootId())); + foreach ($nodes as $node) { + $this->tree_arr["childs"][$node["parent"]][] = $node; + $this->tree_arr["parent"][$node["child"]] = $node["parent"]; + $this->tree_arr["nodes"][$node["child"]] = $node; + } + + // load all lm obj ids of learning module + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + $this->lm_obj_ids = ilLMObject::_getAllLMObjectsOfLM($this->lm_obj_id); + + // load read event data + $this->re_arr = array(); + $set = $ilDB->query("SELECT * FROM lm_read_event " . + " WHERE " . $ilDB->in("obj_id", $this->lm_obj_ids, false, "integer") . + " AND usr_id = " . $ilDB->quote($this->user_id, "integer")); + while ($rec = $ilDB->fetchAssoc($set)) { + $this->re_arr[$rec["obj_id"]] = $rec; + } + + // load question/pages information + $this->page_questions = array(); + $this->all_questions = array(); + include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); + $q = ilLMPageObject::queryQuestionsOfLearningModule($this->lm_obj_id, "", "", 0, 0); + foreach ($q["set"] as $quest) { + $this->page_questions[$quest["page_id"]][] = $quest["question_id"]; + $this->all_questions[] = $quest["question_id"]; + } + + // load question answer information + include_once("./Services/COPage/classes/class.ilPageQuestionProcessor.php"); + $this->answer_status = ilPageQuestionProcessor::getAnswerStatus($this->all_questions, $this->user_id); + + $this->has_incorrect_answers = false; + + $has_pred_incorrect_answers = false; + $has_pred_incorrect_not_unlocked_answers = false; + $this->determineProgressStatus($this->lm_tree->readRootId(), $has_pred_incorrect_answers, $has_pred_incorrect_not_unlocked_answers); + + $this->has_incorrect_answers = $has_pred_incorrect_answers; + } + + /** + * Have all questoins been answered correctly (and questions exist)? + * + * @return bool true, if learning module contains any question and all questions (in the chapter structure) have been answered correctly + */ + public function getAllQuestionsCorrect() + { + $this->loadLMTrackingData(); + if (count($this->all_questions) > 0 && !$this->has_incorrect_answers) { + return true; + } + return false; + } + + + /** + * Determine progress status of nodes + * + * @param int $a_obj_id lm object id + * @return int status + */ + protected function determineProgressStatus($a_obj_id, &$a_has_pred_incorrect_answers, &$a_has_pred_incorrect_not_unlocked_answers) + { + $status = ilLMTracker::NOT_ATTEMPTED; + + if (isset($this->tree_arr["nodes"][$a_obj_id])) { + $this->tree_arr["nodes"][$a_obj_id]["has_pred_incorrect_answers"] = $a_has_pred_incorrect_answers; + $this->tree_arr["nodes"][$a_obj_id]["has_pred_incorrect_not_unlocked_answers"] = $a_has_pred_incorrect_not_unlocked_answers; + + if (is_array($this->tree_arr["childs"][$a_obj_id])) { + // sort childs in correct order + $this->tree_arr["childs"][$a_obj_id] = ilUtil::sortArray($this->tree_arr["childs"][$a_obj_id], "lft", "asc", true); + + $cnt_completed = 0; + foreach ($this->tree_arr["childs"][$a_obj_id] as $c) { + // if child is not activated/displayed count child as implicitly completed + // rationale: everything that is visible for the learner determines the status + // see also bug #14642 + if (!self::_isNodeVisible($c)) { + $cnt_completed++; + continue; + } + $c_stat = $this->determineProgressStatus( + $c["child"], + $a_has_pred_incorrect_answers, + $a_has_pred_incorrect_not_unlocked_answers + ); + if ($status != ilLMTracker::FAILED) { + if ($c_stat == ilLMTracker::FAILED) { + $status = ilLMTracker::IN_PROGRESS; + } elseif ($c_stat == ilLMTracker::IN_PROGRESS) { + $status = ilLMTracker::IN_PROGRESS; + } elseif ($c_stat == ilLMTracker::COMPLETED || $c_stat == ilLMTracker::CURRENT) { + $status = ilLMTracker::IN_PROGRESS; + $cnt_completed++; + } + } + // if an item is failed or in progress or (not attempted and contains questions) + // the next item has predecessing incorrect answers + if ($this->tree_arr["nodes"][$c["child"]]["type"] == "pg") { + if ($c_stat == ilLMTracker::FAILED || $c_stat == ilLMTracker::IN_PROGRESS || + ($c_stat == ilLMTracker::NOT_ATTEMPTED && is_array($this->page_questions[$c["child"]]) && count($this->page_questions[$c["child"]]) > 0)) { + $a_has_pred_incorrect_answers = true; + if (!$this->tree_arr["nodes"][$c["child"]]["unlocked"]) { + $a_has_pred_incorrect_not_unlocked_answers = true; + } + } + } + } + if ($cnt_completed == count($this->tree_arr["childs"][$a_obj_id])) { + $status = ilLMTracker::COMPLETED; + } + } elseif ($this->tree_arr["nodes"][$a_obj_id]["type"] == "pg") { + // check read event data + if (isset($this->re_arr[$a_obj_id]) && $this->re_arr[$a_obj_id]["read_count"] > 0) { + $status = ilLMTracker::COMPLETED; + } elseif ($a_obj_id == $this->getCurrentPage()) { + $status = ilLMTracker::CURRENT; + } + + $unlocked = false; + if (is_array($this->page_questions[$a_obj_id])) { + // check questions, if one is failed -> failed + $unlocked = true; + foreach ($this->page_questions[$a_obj_id] as $q_id) { + if (is_array($this->answer_status[$q_id]) + && $this->answer_status[$q_id]["try"] > 0 + && !$this->answer_status[$q_id]["passed"]) { + $status = ilLMTracker::FAILED; + if (!$this->answer_status[$q_id]["unlocked"]) { + $unlocked = false; + } + } + } + + // check questions, if one is not answered -> in progress + if ($status != ilLMTracker::FAILED) { + foreach ($this->page_questions[$a_obj_id] as $q_id) { + if (!is_array($this->answer_status[$q_id]) + || $this->answer_status[$q_id]["try"] == 0) { + if ($status != ilLMTracker::NOT_ATTEMPTED) { + $status = ilLMTracker::IN_PROGRESS; + } + } + } + $unlocked = false; + } + } + $this->tree_arr["nodes"][$a_obj_id]["unlocked"] = $unlocked; + $this->tree_arr["nodes"][$a_obj_id]["has_pred_incorrect_answers"] = $a_has_pred_incorrect_answers; + $this->tree_arr["nodes"][$a_obj_id]["has_pred_incorrect_not_unlocked_answers"] = $a_has_pred_incorrect_not_unlocked_answers; + } + } else { // free pages (currently not called, since only walking through tree structure) + + } + $this->tree_arr["nodes"][$a_obj_id]["status"] = $status; + + return $status; + } + + + /** + * Get icon for lm object + * + * @param array $a_node node array + * @param int $a_highlighted_node current node id + * @return string image path + */ + public function getIconForLMObject($a_node, $a_highlighted_node = 0) + { + $this->loadLMTrackingData(); + if ($a_node["child"] == $a_highlighted_node) { + return ilUtil::getImagePath('scorm/running.svg'); + } + if (isset($this->tree_arr["nodes"][$a_node["child"]])) { + switch ($this->tree_arr["nodes"][$a_node["child"]]["status"]) { + case ilLMTracker::IN_PROGRESS: + return ilUtil::getImagePath('scorm/incomplete.svg'); + + case ilLMTracker::FAILED: + return ilUtil::getImagePath('scorm/failed.svg'); + + case ilLMTracker::COMPLETED: + return ilUtil::getImagePath('scorm/completed.svg'); + } + } + return ilUtil::getImagePath('scorm/not_attempted.svg'); + } + + /** + * Has predecessing incorrect answers + * + * @param int $a_obj_id + * @return bool true if incorrect/unsanswered questions exist in predecessing pages + */ + public function hasPredIncorrectAnswers($a_obj_id, $a_ignore_unlock = false) + { + $this->loadLMTrackingData(); + $ret = false; + if (is_array($this->tree_arr["nodes"][$a_obj_id])) { + if ($a_ignore_unlock) { + $ret = $this->tree_arr["nodes"][$a_obj_id]["has_pred_incorrect_answers"]; + } else { + $ret = $this->tree_arr["nodes"][$a_obj_id]["has_pred_incorrect_not_unlocked_answers"]; + } + } + return $ret; + } + + //// + //// Blocked Users + //// + + /** + * Get blocked users information + * + * @param + * @return + */ + public function getBlockedUsersInformation() + { + $ilDB = $this->db; + $lng = $this->lng; + $ilPluginAdmin = $this->plugin_admin; + $ilUser = $this->user; + + $blocked_users = array(); + + // load question/pages information + $this->page_questions = array(); + $this->all_questions = array(); + $page_for_question = array(); + include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); + $q = ilLMPageObject::queryQuestionsOfLearningModule($this->lm_obj_id, "", "", 0, 0); + foreach ($q["set"] as $quest) { + $this->page_questions[$quest["page_id"]][] = $quest["question_id"]; + $this->all_questions[] = $quest["question_id"]; + $page_for_question[$quest["question_id"]] = $quest["page_id"]; + } + // get question information + include_once("./Modules/TestQuestionPool/classes/class.ilAssQuestionList.php"); + $qlist = new ilAssQuestionList($ilDB, $lng, $ilPluginAdmin); + $qlist->setParentObjId(0); + $qlist->setJoinObjectData(false); + $qlist->addFieldFilter("question_id", $this->all_questions); + $qlist->load(); + $qdata = $qlist->getQuestionDataArray(); + + // load question answer information + include_once("./Services/COPage/classes/class.ilPageQuestionProcessor.php"); + $this->answer_status = ilPageQuestionProcessor::getAnswerStatus($this->all_questions); + include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); + foreach ($this->answer_status as $as) { + if ($as["try"] >= $qdata[$as["qst_id"]]["nr_of_tries"] && $qdata[$as["qst_id"]]["nr_of_tries"] > 0 && !$as["passed"]) { + //var_dump($qdata[$as["qst_id"]]); + $name = ilObjUser::_lookupName($as["user_id"]); + $as["user_name"] = $name["lastname"] . ", " . $name["firstname"] . " [" . $name["login"] . "]"; + $as["question_text"] = $qdata[$as["qst_id"]]["question_text"]; + $as["page_id"] = $page_for_question[$as["qst_id"]]; + $as["page_title"] = ilLMPageObject::_lookupTitle($as["page_id"]); + $blocked_users[] = $as; + } + } + + return $blocked_users; + } + + /** + * Is node visible for the learner + * + * @param mixed $a_node node object/array + * @return boolean node visible true/false + */ + public static function _isNodeVisible($a_node) + { + include_once("./Services/COPage/classes/class.ilPageObject.php"); + + if ($a_node["type"] != "pg") { + return true; + } + + $lm_set = new ilSetting("lm"); + $active = ilPageObject::_lookupActive( + $a_node["child"], + "lm", + $lm_set->get("time_scheduled_page_activation") + ); + + if (!$active) { + $act_data = ilPageObject::_lookupActivationData((int) $a_node["child"], "lm"); + if ($act_data["show_activation_info"] && + (ilUtil::now() < $act_data["activation_start"])) { + return true; + } else { + return false; + } + } else { + return true; + } + } } - -?> \ No newline at end of file diff --git a/Modules/LearningModule/classes/class.ilLMTree.php b/Modules/LearningModule/classes/class.ilLMTree.php index c90395f9ded5b4fe55dcf1a056872181c6a3492e..4d9999cfe4466b264ee1c2638b1f46b8f0246f65 100644 --- a/Modules/LearningModule/classes/class.ilLMTree.php +++ b/Modules/LearningModule/classes/class.ilLMTree.php @@ -3,85 +3,81 @@ /* Copyright (c) 1998-2014 ILIAS open source, Extended GPL, see docs/LICENSE */ /** - * + * * * @author Alex Killing * @version $Id\$ - * @ingroup + * @ingroup */ class ilLMTree extends ilTree { - /** - * @var ilDB - */ - protected $db; - - static $instances = array(); + /** + * @var ilDB + */ + protected $db; - /** - * Constructor - * - * @param integer $a_tree_id tree id - */ - function __construct($a_tree_id) - { - global $DIC; + public static $instances = array(); - $this->db = $DIC->database(); - parent::__construct($a_tree_id); - $this->setTableNames('lm_tree','lm_data'); - $this->setTreeTablePK("lm_id"); - $this->useCache(true); - } + /** + * Constructor + * + * @param integer $a_tree_id tree id + */ + public function __construct($a_tree_id) + { + global $DIC; - /** - * Get Instance - * - * @param - * @return - */ - static function getInstance($a_tree_id) - { - if (isset(self::$instances[$a_tree_id])) - { - return self::$instances[$a_tree_id]; - } - $tree = new ilLMTree($a_tree_id); - self::$instances[$a_tree_id] = $tree; + $this->db = $DIC->database(); + parent::__construct($a_tree_id); + $this->setTableNames('lm_tree', 'lm_data'); + $this->setTreeTablePK("lm_id"); + $this->useCache(true); + } - return $tree; - } + /** + * Get Instance + * + * @param + * @return + */ + public static function getInstance($a_tree_id) + { + if (isset(self::$instances[$a_tree_id])) { + return self::$instances[$a_tree_id]; + } + $tree = new ilLMTree($a_tree_id); + self::$instances[$a_tree_id] = $tree; + return $tree; + } - /** - * Check if cache is active - * @return bool - */ - public function isCacheUsed() - { - return $this->use_cache; - } - - public function getLastActivePage() - { - $ilDB = $this->db; - - $ilDB->setLimit(1); - - $sql = "SELECT lm_data.obj_id". - " FROM lm_data". - " JOIN lm_tree ON (lm_tree.child = lm_data.obj_id)". - " JOIN page_object ON (page_object.page_id = lm_data.obj_id AND page_object.parent_type = ".$ilDB->quote("lm", "text").")". - " WHERE lm_tree.lm_id = ".$ilDB->quote($this->tree_id, "integer"). - " AND lm_data.type = ".$ilDB->quote("pg", "text"). - " AND page_object.active = ".$ilDB->quote(1, "integer"). - " ORDER BY lm_tree.rgt DESC"; - $set = $ilDB->query($sql); - $row = $ilDB->fetchAssoc($set); - return (int)$row["obj_id"]; - } + /** + * Check if cache is active + * @return bool + */ + public function isCacheUsed() + { + return $this->use_cache; + } + + public function getLastActivePage() + { + $ilDB = $this->db; + + $ilDB->setLimit(1); + + $sql = "SELECT lm_data.obj_id" . + " FROM lm_data" . + " JOIN lm_tree ON (lm_tree.child = lm_data.obj_id)" . + " JOIN page_object ON (page_object.page_id = lm_data.obj_id AND page_object.parent_type = " . $ilDB->quote("lm", "text") . ")" . + " WHERE lm_tree.lm_id = " . $ilDB->quote($this->tree_id, "integer") . + " AND lm_data.type = " . $ilDB->quote("pg", "text") . + " AND page_object.active = " . $ilDB->quote(1, "integer") . + " ORDER BY lm_tree.rgt DESC"; + $set = $ilDB->query($sql); + $row = $ilDB->fetchAssoc($set); + return (int) $row["obj_id"]; + } } - -?> \ No newline at end of file diff --git a/Modules/LearningModule/classes/class.ilLearningModuleCronLinkCheck.php b/Modules/LearningModule/classes/class.ilLearningModuleCronLinkCheck.php index 9dbf16b15bc10c0706dd642bf6cdfa8b599be0fb..ac6951ad7f53477011976220a0210837f602973c 100644 --- a/Modules/LearningModule/classes/class.ilLearningModuleCronLinkCheck.php +++ b/Modules/LearningModule/classes/class.ilLearningModuleCronLinkCheck.php @@ -1,114 +1,110 @@ - - * @version $Id$ - * - * @package ModulesLearningModule - */ -class ilLearningModuleCronLinkCheck extends ilCronJob -{ - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var Logger - */ - protected $log; - - /** - * @var ilDB - */ - protected $db; - - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - $this->log = $DIC["ilLog"]; - $this->db = $DIC->database(); - } - - public function getId() - { - return "lm_link_check"; - } - - public function getTitle() - { - $lng = $this->lng; - - return $lng->txt("check_link"); - } - - public function getDescription() - { - $lng = $this->lng; - - return $lng->txt("check_link_desc"); - } - - 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() - { - $ilLog = $this->log; - $ilDB = $this->db; - - $status = ilCronJobResult::STATUS_NO_ACTION; - - include_once'./Services/LinkChecker/classes/class.ilLinkChecker.php'; - - $link_checker = new ilLinkChecker($ilDB); - $link_checker->setMailStatus(true); - - $link_checker->checkLinks(); - - $counter = 0; - foreach($link_checker->getLogMessages() as $message) - { - $ilLog->write($message); - $counter++; - } - - if($counter) - { - $status = ilCronJobResult::STATUS_OK; - } - $result = new ilCronJobResult(); - $result->setStatus($status); - return $result; - } -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @package ModulesLearningModule + */ +class ilLearningModuleCronLinkCheck extends ilCronJob +{ + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var Logger + */ + protected $log; + + /** + * @var ilDB + */ + protected $db; + + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + $this->log = $DIC["ilLog"]; + $this->db = $DIC->database(); + } + + public function getId() + { + return "lm_link_check"; + } + + public function getTitle() + { + $lng = $this->lng; + + return $lng->txt("check_link"); + } + + public function getDescription() + { + $lng = $this->lng; + + return $lng->txt("check_link_desc"); + } + + 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() + { + $ilLog = $this->log; + $ilDB = $this->db; + + $status = ilCronJobResult::STATUS_NO_ACTION; + + include_once'./Services/LinkChecker/classes/class.ilLinkChecker.php'; + + $link_checker = new ilLinkChecker($ilDB); + $link_checker->setMailStatus(true); + + $link_checker->checkLinks(); + + $counter = 0; + foreach ($link_checker->getLogMessages() as $message) { + $ilLog->write($message); + $counter++; + } + + if ($counter) { + $status = ilCronJobResult::STATUS_OK; + } + $result = new ilCronJobResult(); + $result->setStatus($status); + return $result; + } +} diff --git a/Modules/LearningModule/classes/class.ilLearningModuleDataSet.php b/Modules/LearningModule/classes/class.ilLearningModuleDataSet.php index 832ae4f1918d292483532c5ab24e99f669ff27a2..0997940bfea68c157c16c7350e393611b0b7d882 100644 --- a/Modules/LearningModule/classes/class.ilLearningModuleDataSet.php +++ b/Modules/LearningModule/classes/class.ilLearningModuleDataSet.php @@ -5,7 +5,7 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); /** * LearningModule Data set class - * + * * This class implements the following entities: * - lm: data from content_object * - lm_tree: data from lm_tree/lm_data @@ -18,671 +18,662 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); */ class ilLearningModuleDataSet extends ilDataSet { - protected $master_lang_only = false; - protected $transl_into = false; - protected $transl_into_lm = null; - protected $transl_lang = ""; - - /** - * @var ilLogger - */ - protected $lm_log; - - /** - * Constructor - */ - function __construct() - { - parent::__construct(); - - $this->lm_log = ilLoggerFactory::getLogger('lm'); - } - /** - * Set master language only (export) - * - * @param bool $a_val export only master language - */ - function setMasterLanguageOnly($a_val) - { - $this->master_lang_only = $a_val; - } - - /** - * Get master language only (export) - * - * @return bool export only master language - */ - function getMasterLanguageOnly() - { - return $this->master_lang_only; - } - - /** - * Set translation import mode - * - * @param ilObjLearningModule $a_lm learning module - * @param string $a_lang language - */ - function setTranslationImportMode($a_lm, $a_lang = "") - { - if ($a_lm != null) - { - $this->transl_into = true; - $this->transl_into_lm = $a_lm; - $this->transl_lang = $a_lang; - } - else - { - $this->transl_into = false; - } - } - - /** - * Get translation import mode - * - * @return bool check if translation import is activated - */ - function getTranslationImportMode() - { - return $this->transl_into; - } - - /** - * Get translation lm (import - * - * @return ilObjLearningModule learning module - */ - function getTranslationLM() - { - return $this->transl_into_lm; - } - - /** - * Get translation language (import - * - * @return string language - */ - function getTranslationLang() - { - return $this->transl_lang; - } - - /** - * Get supported versions - * - * @param - * @return - */ - public function getSupportedVersions() - { - return array("5.1.0", "5.4.0"); - } - - /** - * Get xml namespace - * - * @param - * @return - */ - function getXmlNamespace($a_entity, $a_schema_version) - { - return "http://www.ilias.de/xml/Modules/LearningModule/".$a_entity; - } - - /** - * Get field types for entity - * - * @param string $a_entity entity - * @param string $a_version version number - * @return array types array - */ - protected function getTypes($a_entity, $a_version) - { - if ($a_entity == "lm") - { - switch ($a_version) - { - case "5.1.0": - return array( - "Id" => "integer", - "Title" => "text", - "Description" => "text", - "DefaultLayout" => "text", - "PageHeader" => "text", - "TocActive" => "text", - "LMMenuActive" => "text", - "TOCMode" => "text", - "PrintViewActive" => "text", - "Numbering" => "text", - "HistUserComments" => "text", - "PublicAccessMode" => "text", - "PubNotes" => "text", - "HeaderPage" => "integer", - "FooterPage" => "integer", - "LayoutPerPage" => "integer", - "Rating" => "integer", - "HideHeadFootPrint" => "integer", - "DisableDefFeedback" => "integer", - "RatingPages" => "integer", - "ProgrIcons" => "integer", - "StoreTries" => "integer", - "RestrictForwNav" => "integer", - "Comments" => "integer", - "ForTranslation" => "integer", - "StyleId" => "integer" - ); - - case "5.4.0": - return array( - "Id" => "integer", - "Title" => "text", - "Description" => "text", - "DefaultLayout" => "text", - "PageHeader" => "text", - "TocActive" => "text", - "LMMenuActive" => "text", - "TOCMode" => "text", - "PrintViewActive" => "text", - "NoGloAppendix" => "text", - "Numbering" => "text", - "HistUserComments" => "text", - "PublicAccessMode" => "text", - "PubNotes" => "text", - "HeaderPage" => "integer", - "FooterPage" => "integer", - "LayoutPerPage" => "integer", - "Rating" => "integer", - "HideHeadFootPrint" => "integer", - "DisableDefFeedback" => "integer", - "RatingPages" => "integer", - "ProgrIcons" => "integer", - "StoreTries" => "integer", - "RestrictForwNav" => "integer", - "Comments" => "integer", - "ForTranslation" => "integer", - "StyleId" => "integer" - ); - - } - } - - if ($a_entity == "lm_tree") - { - switch ($a_version) - { - case "5.1.0": - case "5.4.0": - return array( - "LmId" => "integer", - "Child" => "integer", - "Parent" => "integer", - "Depth" => "integer", - "Type" => "text", - "Title" => "text", - "ShortTitle" => "text", - "PublicAccess" => "text", - "Active" => "text", - "Layout" => "text", - "ImportId" => "text" - ); - } - } - - if ($a_entity == "lm_menu") - { - switch ($a_version) - { - case "5.1.0": - case "5.4.0": - return array( - "LmId" => "integer", - "LinkType" => "text", - "Title" => "text", - "Target" => "text", - "LinkRefId" => "text", - "Active" => "text" - ); - } - } - - if ($a_entity == "lm_data_transl") - { - switch ($a_version) - { - case "5.1.0": - case "5.4.0": - return array( - "Id" => "integer", - "Lang" => "text", - "Title" => "text", - "ShortTitle" => "text" - ); - } - } - - } - - /** - * Read data - * - * @param - * @return - */ - 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 == "lm") - { - switch ($a_version) - { - case "5.1.0": - case "5.4.0": - switch ($a_version) - { - case "5.1.0": - $q = "SELECT id, title, description,". - " default_layout, page_header, toc_active, lm_menu_active, toc_mode, print_view_active, numbering,". - " hist_user_comments, public_access_mode, header_page, footer_page, layout_per_page, rating, ". - " hide_head_foot_print, disable_def_feedback, rating_pages, store_tries, restrict_forw_nav, progr_icons, stylesheet style_id". - " FROM content_object JOIN object_data ON (content_object.id = object_data.obj_id)". - " WHERE ".$ilDB->in("id", $a_ids, false, "integer"); - break; - - case "5.4.0": - $q = "SELECT id, title, description,". - " default_layout, page_header, toc_active, lm_menu_active, toc_mode, print_view_active, numbering,". - " hist_user_comments, public_access_mode, no_glo_appendix, header_page, footer_page, layout_per_page, rating, ". - " hide_head_foot_print, disable_def_feedback, rating_pages, store_tries, restrict_forw_nav, progr_icons, stylesheet style_id". - " FROM content_object JOIN object_data ON (content_object.id = object_data.obj_id)". - " WHERE ".$ilDB->in("id", $a_ids, false, "integer"); - - } - - $set = $ilDB->query($q); - $this->data = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - // comments activated? - include_once("./Services/Notes/classes/class.ilNote.php"); - $rec["comments"] = ilNote::commentsActivated($rec["id"], 0, "lm"); - - if ($this->getMasterLanguageOnly()) - { - $rec["for_translation"] = 1; - } - $tmp = array(); - foreach ($rec as $k => $v) - { - $tmp[$this->convertToLeadingUpper($k)] - = $v; - } - $rec = $tmp; - - $this->data[] = $rec; - } - break; - - - break; - } - } - - if ($a_entity == "lm_tree") - { - switch ($a_version) - { - case "5.1.0": - case "5.4.0": - // the order by lft is very important, this ensures that parent nodes are written before - // their childs and that the import can add nodes simply with a "add at last child" target - $q = "SELECT lm_tree.lm_id, child, parent, depth, type, title, short_title, public_access, active, layout, import_id". - " FROM lm_tree JOIN lm_data ON (lm_tree.child = lm_data.obj_id)". - " WHERE ".$ilDB->in("lm_tree.lm_id", $a_ids, false, "integer"). - " ORDER BY lft"; - - $set = $ilDB->query($q); - $this->data = array(); - $obj_ids = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $set2 = $ilDB->query("SELECT for_translation FROM content_object WHERE id = ".$ilDB->quote($rec["lm_id"], "integer")); - $rec2 = $ilDB->fetchAssoc($set2); - if (!$rec2["for_translation"]) - { - $rec["import_id"] = "il_".IL_INST_ID."_".$rec["type"]."_".$rec["child"]; - } - $tmp = array(); - foreach ($rec as $k => $v) - { - $tmp[$this->convertToLeadingUpper($k)] - = $v; - } - $rec = $tmp; - $obj_ids[] = $rec["Child"]; - $this->data[] = $rec; - } - - // add free pages #18976 - $set3 = $ilDB->query($q = "SELECT lm_id, type, title, short_title, public_access, active, layout, import_id, obj_id child FROM lm_data ". - "WHERE ".$ilDB->in("lm_id", $a_ids, false, "integer"). - " AND ".$ilDB->in("obj_id", $obj_ids, true, "integer"). - " AND type = ".$ilDB->quote("pg", "text")); - while ($rec3 = $ilDB->fetchAssoc($set3)) - { - $set2 = $ilDB->query("SELECT for_translation FROM content_object WHERE id = ".$ilDB->quote($rec3["lm_id"], "integer")); - $rec2 = $ilDB->fetchAssoc($set2); - if (!$rec2["for_translation"]) - { - $rec3["import_id"] = "il_".IL_INST_ID."_pg_".$rec3["child"]; - } - $rec3["type"] = "free_pg"; - $rec3["depth"] = 0; - $rec3["parent"] = 0; - $tmp = array(); - foreach ($rec3 as $k => $v) - { - $tmp[$this->convertToLeadingUpper($k)] - = $v; - } - $this->data[] = $tmp; - } - break; - } - } - - if ($a_entity == "lm_menu") - { - switch ($a_version) - { - case "5.1.0": - case "5.4.0": - $this->getDirectDataFromQuery("SELECT lm_id, link_type, title, target, link_ref_id, active". - " FROM lm_menu ". - " WHERE ".$ilDB->in("lm_id", $a_ids, false, "integer")); - break; - } - } - - if ($a_entity == "lm_data_transl") - { - switch ($a_version) - { - case "5.1.0": - case "5.4.0": - $this->getDirectDataFromQuery("SELECT id, lang, title, short_title". - " FROM lm_data_transl ". - " WHERE ".$ilDB->in("id", $a_ids, false, "integer")); - break; - } - } - - - } - - /** - * Determine the dependent sets of data - */ - protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) - { - switch ($a_entity) - { - case "lm": - return array ( - "lm_tree" => array("ids" => $a_rec["Id"]), - "lm_menu" => array("ids" => $a_rec["Id"]) - ); - - case "lm_tree": - if ($this->getMasterLanguageOnly()) - { - return false; - } - else - { - return array ( - "lm_data_transl" => array("ids" => $a_rec["Child"]) - ); - } - } - - return false; - } - - - /** - * Import record - * - * @param - * @return - */ - function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) - { -//var_dump($a_rec); - - switch ($a_entity) - { - case "lm": - - if ($this->getTranslationImportMode()) - { - return; - } - - include_once("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); - if($new_id = $a_mapping->getMapping('Services/Container','objs',$a_rec['Id'])) - { - $newObj = ilObjectFactory::getInstanceByObjId($new_id,false); - } - else - { - $newObj = new ilObjLearningModule(); - $newObj->setType("lm"); - $newObj->create(true); - $newObj->createLMTree(); - } - - $newObj->setTitle($a_rec["Title"]); - $newObj->setDescription($a_rec["Description"]); - $newObj->setLayout($a_rec["DefaultLayout"]); - $newObj->setPageHeader($a_rec["PageHeader"]); - $newObj->setActiveTOC(ilUtil::yn2tf($a_rec["TocActive"])); - $newObj->setActiveLMMenu(ilUtil::yn2tf($a_rec["LmMenuActive"])); - $newObj->setTOCMode($a_rec["TocMode"]); - $newObj->setActivePrintView(ilUtil::yn2tf($a_rec["PrintViewActive"])); - $newObj->setActivePreventGlossaryAppendix(ilUtil::yn2tf($a_rec["NoGloAppendix"])); - $newObj->setActiveNumbering(ilUtil::yn2tf($a_rec["Numbering"])); - $newObj->setHistoryUserComments(ilUtil::yn2tf($a_rec["HistUserComments"])); - $newObj->setPublicAccessMode($a_rec["PublicAccessMode"]); - $newObj->setPublicNotes(ilUtil::yn2tf($a_rec["PubNotes"])); - // Header Page/ Footer Page ??? - $newObj->setLayoutPerPage($a_rec["LayoutPerPage"]); - $newObj->setRating($a_rec["Rating"]); - $newObj->setHideHeaderFooterPrint($a_rec["HideHeadFootPrint"]); - $newObj->setDisableDefaultFeedback($a_rec["DisableDefFeedback"]); - $newObj->setRatingPages($a_rec["RatingPages"]); - $newObj->setForTranslation($a_rec["ForTranslation"]); - $newObj->setProgressIcons($a_rec["ProgrIcons"]); - $newObj->setStoreTries($a_rec["StoreTries"]); - $newObj->setRestrictForwardNavigation($a_rec["RestrictForwNav"]); - if ($a_rec["HeaderPage"] > 0) - { - $a_mapping->addMapping("Modules/LearningModule", "lm_header_page", $a_rec["HeaderPage"], "-"); - } - if ($a_rec["FooterPage"] > 0) - { - $a_mapping->addMapping("Modules/LearningModule", "lm_footer_page", $a_rec["FooterPage"], "-"); - } - - $newObj->update(true); - $this->current_obj = $newObj; - - // activated comments - include_once("./Services/Notes/classes/class.ilNote.php"); - ilNote::activateComments($newObj->getId(), 0, "lm", (int) $a_rec["Comments"]); - - $a_mapping->addMapping("Modules/LearningModule", "lm", $a_rec["Id"], $newObj->getId()); - $a_mapping->addMapping("Modules/LearningModule", "lm_style", $newObj->getId(), $a_rec["StyleId"]); - $a_mapping->addMapping("Services/Object", "obj", $a_rec["Id"], $newObj->getId()); - $a_mapping->addMapping("Services/MetaData", "md", - $a_rec["Id"].":0:lm", $newObj->getId().":0:lm"); - break; - - case "lm_tree": - if (!$this->getTranslationImportMode()) - { - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - include_once("./Modules/LearningModule/classes/class.ilStructureObject.php"); - include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); - switch ($a_rec["Type"]) - { - case "st": - $parent = (int) $a_mapping->getMapping("Modules/LearningModule", "lm_tree", $a_rec["Parent"]); - $st_obj = new ilStructureObject($this->current_obj); - $st_obj->setType("st"); - $st_obj->setLMId($this->current_obj->getId()); - $st_obj->setTitle($a_rec["Title"]); - $st_obj->setShortTitle($a_rec["ShortTitle"]); - $st_obj->setImportId($a_rec["ImportId"]); - $st_obj->create(true); - ilLMObject::putInTree($st_obj, $parent, IL_LAST_NODE); - $a_mapping->addMapping("Modules/LearningModule", "lm_tree", $a_rec["Child"], - $st_obj->getId()); - $a_mapping->addMapping("Services/MetaData", "md", - $a_rec["LmId"].":".$a_rec["Child"].":st", $this->current_obj->getId().":".$st_obj->getId().":st"); - break; - - case "pg": - $parent = (int) $a_mapping->getMapping("Modules/LearningModule", "lm_tree", $a_rec["Parent"]); - $pg_obj = new ilLMPageObject($this->current_obj); - $pg_obj->setType("pg"); - $pg_obj->setLMId($this->current_obj->getId()); - $pg_obj->setTitle($a_rec["Title"]); - $pg_obj->setShortTitle($a_rec["ShortTitle"]); - $pg_obj->setImportId($a_rec["ImportId"]); - $pg_obj->create(true, true); - ilLMObject::putInTree($pg_obj, $parent, IL_LAST_NODE); - $a_mapping->addMapping("Modules/LearningModule", "lm_tree", $a_rec["Child"], - $pg_obj->getId()); - $a_mapping->addMapping("Modules/LearningModule", "pg", $a_rec["Child"], $pg_obj->getId()); - $this->lm_log->debug("add pg map (1), old : ".$a_rec["Child"].", new: ".$pg_obj->getId()); - $a_mapping->addMapping("Services/COPage", "pg", "lm:".$a_rec["Child"], - "lm:".$pg_obj->getId()); - $a_mapping->addMapping("Services/MetaData", "md", - $a_rec["LmId"].":".$a_rec["Child"].":pg", $this->current_obj->getId().":".$pg_obj->getId().":pg"); - break; - - // add free pages #18976 - case "free_pg": - $pg_obj = new ilLMPageObject($this->current_obj); - $pg_obj->setType("pg"); - $pg_obj->setLMId($this->current_obj->getId()); - $pg_obj->setTitle($a_rec["Title"]); - $pg_obj->setShortTitle($a_rec["ShortTitle"]); - $pg_obj->setImportId($a_rec["ImportId"]); - $pg_obj->create(true, true); - $a_mapping->addMapping("Modules/LearningModule", "lm_tree", $a_rec["Child"], - $pg_obj->getId()); - $a_mapping->addMapping("Modules/LearningModule", "pg", $a_rec["Child"], $pg_obj->getId()); - $this->lm_log->debug("add pg map (2), old : ".$a_rec["Child"].", new: ".$pg_obj->getId()); - $a_mapping->addMapping("Services/COPage", "pg", "lm:".$a_rec["Child"], - "lm:".$pg_obj->getId()); - $a_mapping->addMapping("Services/MetaData", "md", - $a_rec["LmId"].":".$a_rec["Child"].":pg", $this->current_obj->getId().":".$pg_obj->getId().":pg"); - break; - } - } - else - { - include_once("./Modules/LearningModule/classes/class.ilLMObjTranslation.php"); - switch ($a_rec["Type"]) - { - case "st": - //"il_inst_st_66" - $imp_id = explode("_", $a_rec["ImportId"]); - if ($imp_id[0] == "il" && - (int) $imp_id[1] == (int) IL_INST_ID && - $imp_id[2] == "st" - ) - { - $st_id = $imp_id[3]; - if (ilLMObject::_lookupContObjId($st_id) == $this->getTranslationLM()->getId()) - { - $trans = new ilLMObjTranslation($st_id, $this->getTranslationLang()); - $trans->setTitle($a_rec["Title"]); - $trans->save(); - $a_mapping->addMapping("Modules/LearningModule", "link", - "il_".$this->getCurrentInstallationId()."_".$a_rec["Type"]."_".$a_rec["Child"], $a_rec["ImportId"]); - } - } - // no meta-data mapping, since we do not want to import metadata - break; - - case "pg": - //"il_inst_pg_66" - $imp_id = explode("_", $a_rec["ImportId"]); - if ($imp_id[0] == "il" && - (int) $imp_id[1] == (int) IL_INST_ID && - $imp_id[2] == "pg" - ) - { - $pg_id = $imp_id[3]; - if (ilLMObject::_lookupContObjId($pg_id) == $this->getTranslationLM()->getId()) - { - $trans = new ilLMObjTranslation($pg_id, $this->getTranslationLang()); - $trans->setTitle($a_rec["Title"]); - $trans->save(); - $a_mapping->addMapping("Modules/LearningModule", "pg", $a_rec["Child"], $pg_id); - $this->lm_log->debug("add pg map (3), old : ".$a_rec["Child"].", new: ".$pg_id); - $a_mapping->addMapping("Modules/LearningModule", "link", - "il_".$this->getCurrentInstallationId()."_".$a_rec["Type"]."_".$a_rec["Child"], $a_rec["ImportId"]); - $a_mapping->addMapping("Services/COPage", "pg", "lm:".$a_rec["Child"], - "lm:".$pg_id); - } - } - // no meta-data mapping, since we do not want to import metadata - break; - } - } - break; - - case "lm_data_transl": - include_once("./Modules/LearningModule/classes/class.ilLMObjTranslation.php"); - if (!$this->getTranslationImportMode()) - { - // save page/chapter title translation - $lm_obj_id = $a_mapping->getMapping("Modules/LearningModule", "lm_tree", $a_rec["Id"]); - if ($lm_obj_id > 0) - { - $t = new ilLMObjTranslation($lm_obj_id, $a_rec["Lang"]); - $t->setTitle($a_rec["Title"]); - $t->setShortTitle($a_rec["ShortTitle"]); - $t->save(); - } - } - break; - - case "lm_menu": - $lm_id = (int)$a_mapping->getMapping("Modules/LearningModule", "lm", $a_rec["LmId"]); - if ($lm_id > 0) - { - $lm_menu_ed = new ilLMMenuEditor(); - $lm_menu_ed->setObjId($lm_id); - $lm_menu_ed->setTitle($a_rec["Title"]); - $lm_menu_ed->setTarget($a_rec["Target"]); - $lm_menu_ed->setLinkType($a_rec["LinkType"]); - $lm_menu_ed->setLinkRefId($a_rec["LinkRefId"]); - $lm_menu_ed->setActive($a_rec["Active"]); - $lm_menu_ed->create(); - } - break; - - } - } + protected $master_lang_only = false; + protected $transl_into = false; + protected $transl_into_lm = null; + protected $transl_lang = ""; + + /** + * @var ilLogger + */ + protected $lm_log; + + /** + * Constructor + */ + public function __construct() + { + parent::__construct(); + + $this->lm_log = ilLoggerFactory::getLogger('lm'); + } + /** + * Set master language only (export) + * + * @param bool $a_val export only master language + */ + public function setMasterLanguageOnly($a_val) + { + $this->master_lang_only = $a_val; + } + + /** + * Get master language only (export) + * + * @return bool export only master language + */ + public function getMasterLanguageOnly() + { + return $this->master_lang_only; + } + + /** + * Set translation import mode + * + * @param ilObjLearningModule $a_lm learning module + * @param string $a_lang language + */ + public function setTranslationImportMode($a_lm, $a_lang = "") + { + if ($a_lm != null) { + $this->transl_into = true; + $this->transl_into_lm = $a_lm; + $this->transl_lang = $a_lang; + } else { + $this->transl_into = false; + } + } + + /** + * Get translation import mode + * + * @return bool check if translation import is activated + */ + public function getTranslationImportMode() + { + return $this->transl_into; + } + + /** + * Get translation lm (import + * + * @return ilObjLearningModule learning module + */ + public function getTranslationLM() + { + return $this->transl_into_lm; + } + + /** + * Get translation language (import + * + * @return string language + */ + public function getTranslationLang() + { + return $this->transl_lang; + } + + /** + * Get supported versions + * + * @param + * @return + */ + public function getSupportedVersions() + { + return array("5.1.0", "5.4.0"); + } + + /** + * Get xml namespace + * + * @param + * @return + */ + public function getXmlNamespace($a_entity, $a_schema_version) + { + return "http://www.ilias.de/xml/Modules/LearningModule/" . $a_entity; + } + + /** + * Get field types for entity + * + * @param string $a_entity entity + * @param string $a_version version number + * @return array types array + */ + protected function getTypes($a_entity, $a_version) + { + if ($a_entity == "lm") { + switch ($a_version) { + case "5.1.0": + return array( + "Id" => "integer", + "Title" => "text", + "Description" => "text", + "DefaultLayout" => "text", + "PageHeader" => "text", + "TocActive" => "text", + "LMMenuActive" => "text", + "TOCMode" => "text", + "PrintViewActive" => "text", + "Numbering" => "text", + "HistUserComments" => "text", + "PublicAccessMode" => "text", + "PubNotes" => "text", + "HeaderPage" => "integer", + "FooterPage" => "integer", + "LayoutPerPage" => "integer", + "Rating" => "integer", + "HideHeadFootPrint" => "integer", + "DisableDefFeedback" => "integer", + "RatingPages" => "integer", + "ProgrIcons" => "integer", + "StoreTries" => "integer", + "RestrictForwNav" => "integer", + "Comments" => "integer", + "ForTranslation" => "integer", + "StyleId" => "integer" + ); + + case "5.4.0": + return array( + "Id" => "integer", + "Title" => "text", + "Description" => "text", + "DefaultLayout" => "text", + "PageHeader" => "text", + "TocActive" => "text", + "LMMenuActive" => "text", + "TOCMode" => "text", + "PrintViewActive" => "text", + "NoGloAppendix" => "text", + "Numbering" => "text", + "HistUserComments" => "text", + "PublicAccessMode" => "text", + "PubNotes" => "text", + "HeaderPage" => "integer", + "FooterPage" => "integer", + "LayoutPerPage" => "integer", + "Rating" => "integer", + "HideHeadFootPrint" => "integer", + "DisableDefFeedback" => "integer", + "RatingPages" => "integer", + "ProgrIcons" => "integer", + "StoreTries" => "integer", + "RestrictForwNav" => "integer", + "Comments" => "integer", + "ForTranslation" => "integer", + "StyleId" => "integer" + ); + + } + } + + if ($a_entity == "lm_tree") { + switch ($a_version) { + case "5.1.0": + case "5.4.0": + return array( + "LmId" => "integer", + "Child" => "integer", + "Parent" => "integer", + "Depth" => "integer", + "Type" => "text", + "Title" => "text", + "ShortTitle" => "text", + "PublicAccess" => "text", + "Active" => "text", + "Layout" => "text", + "ImportId" => "text" + ); + } + } + + if ($a_entity == "lm_menu") { + switch ($a_version) { + case "5.1.0": + case "5.4.0": + return array( + "LmId" => "integer", + "LinkType" => "text", + "Title" => "text", + "Target" => "text", + "LinkRefId" => "text", + "Active" => "text" + ); + } + } + + if ($a_entity == "lm_data_transl") { + switch ($a_version) { + case "5.1.0": + case "5.4.0": + return array( + "Id" => "integer", + "Lang" => "text", + "Title" => "text", + "ShortTitle" => "text" + ); + } + } + } + + /** + * 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 == "lm") { + switch ($a_version) { + case "5.1.0": + case "5.4.0": + switch ($a_version) { + case "5.1.0": + $q = "SELECT id, title, description," . + " default_layout, page_header, toc_active, lm_menu_active, toc_mode, print_view_active, numbering," . + " hist_user_comments, public_access_mode, header_page, footer_page, layout_per_page, rating, " . + " hide_head_foot_print, disable_def_feedback, rating_pages, store_tries, restrict_forw_nav, progr_icons, stylesheet style_id" . + " FROM content_object JOIN object_data ON (content_object.id = object_data.obj_id)" . + " WHERE " . $ilDB->in("id", $a_ids, false, "integer"); + break; + + case "5.4.0": + $q = "SELECT id, title, description," . + " default_layout, page_header, toc_active, lm_menu_active, toc_mode, print_view_active, numbering," . + " hist_user_comments, public_access_mode, no_glo_appendix, header_page, footer_page, layout_per_page, rating, " . + " hide_head_foot_print, disable_def_feedback, rating_pages, store_tries, restrict_forw_nav, progr_icons, stylesheet style_id" . + " FROM content_object JOIN object_data ON (content_object.id = object_data.obj_id)" . + " WHERE " . $ilDB->in("id", $a_ids, false, "integer"); + + } + + $set = $ilDB->query($q); + $this->data = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + // comments activated? + include_once("./Services/Notes/classes/class.ilNote.php"); + $rec["comments"] = ilNote::commentsActivated($rec["id"], 0, "lm"); + + if ($this->getMasterLanguageOnly()) { + $rec["for_translation"] = 1; + } + $tmp = array(); + foreach ($rec as $k => $v) { + $tmp[$this->convertToLeadingUpper($k)] + = $v; + } + $rec = $tmp; + + $this->data[] = $rec; + } + break; + + + break; + } + } + + if ($a_entity == "lm_tree") { + switch ($a_version) { + case "5.1.0": + case "5.4.0": + // the order by lft is very important, this ensures that parent nodes are written before + // their childs and that the import can add nodes simply with a "add at last child" target + $q = "SELECT lm_tree.lm_id, child, parent, depth, type, title, short_title, public_access, active, layout, import_id" . + " FROM lm_tree JOIN lm_data ON (lm_tree.child = lm_data.obj_id)" . + " WHERE " . $ilDB->in("lm_tree.lm_id", $a_ids, false, "integer") . + " ORDER BY lft"; + + $set = $ilDB->query($q); + $this->data = array(); + $obj_ids = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $set2 = $ilDB->query("SELECT for_translation FROM content_object WHERE id = " . $ilDB->quote($rec["lm_id"], "integer")); + $rec2 = $ilDB->fetchAssoc($set2); + if (!$rec2["for_translation"]) { + $rec["import_id"] = "il_" . IL_INST_ID . "_" . $rec["type"] . "_" . $rec["child"]; + } + $tmp = array(); + foreach ($rec as $k => $v) { + $tmp[$this->convertToLeadingUpper($k)] + = $v; + } + $rec = $tmp; + $obj_ids[] = $rec["Child"]; + $this->data[] = $rec; + } + + // add free pages #18976 + $set3 = $ilDB->query($q = "SELECT lm_id, type, title, short_title, public_access, active, layout, import_id, obj_id child FROM lm_data " . + "WHERE " . $ilDB->in("lm_id", $a_ids, false, "integer") . + " AND " . $ilDB->in("obj_id", $obj_ids, true, "integer") . + " AND type = " . $ilDB->quote("pg", "text")); + while ($rec3 = $ilDB->fetchAssoc($set3)) { + $set2 = $ilDB->query("SELECT for_translation FROM content_object WHERE id = " . $ilDB->quote($rec3["lm_id"], "integer")); + $rec2 = $ilDB->fetchAssoc($set2); + if (!$rec2["for_translation"]) { + $rec3["import_id"] = "il_" . IL_INST_ID . "_pg_" . $rec3["child"]; + } + $rec3["type"] = "free_pg"; + $rec3["depth"] = 0; + $rec3["parent"] = 0; + $tmp = array(); + foreach ($rec3 as $k => $v) { + $tmp[$this->convertToLeadingUpper($k)] + = $v; + } + $this->data[] = $tmp; + } + break; + } + } + + if ($a_entity == "lm_menu") { + switch ($a_version) { + case "5.1.0": + case "5.4.0": + $this->getDirectDataFromQuery("SELECT lm_id, link_type, title, target, link_ref_id, active" . + " FROM lm_menu " . + " WHERE " . $ilDB->in("lm_id", $a_ids, false, "integer")); + break; + } + } + + if ($a_entity == "lm_data_transl") { + switch ($a_version) { + case "5.1.0": + case "5.4.0": + $this->getDirectDataFromQuery("SELECT id, lang, title, short_title" . + " FROM lm_data_transl " . + " WHERE " . $ilDB->in("id", $a_ids, false, "integer")); + break; + } + } + } + + /** + * Determine the dependent sets of data + */ + protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) + { + switch ($a_entity) { + case "lm": + return array( + "lm_tree" => array("ids" => $a_rec["Id"]), + "lm_menu" => array("ids" => $a_rec["Id"]) + ); + + case "lm_tree": + if ($this->getMasterLanguageOnly()) { + return false; + } else { + return array( + "lm_data_transl" => array("ids" => $a_rec["Child"]) + ); + } + } + + return false; + } + + + /** + * Import record + * + * @param + * @return + */ + public function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) + { + //var_dump($a_rec); + + switch ($a_entity) { + case "lm": + + if ($this->getTranslationImportMode()) { + return; + } + + include_once("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); + if ($new_id = $a_mapping->getMapping('Services/Container', 'objs', $a_rec['Id'])) { + $newObj = ilObjectFactory::getInstanceByObjId($new_id, false); + } else { + $newObj = new ilObjLearningModule(); + $newObj->setType("lm"); + $newObj->create(true); + $newObj->createLMTree(); + } + + $newObj->setTitle($a_rec["Title"]); + $newObj->setDescription($a_rec["Description"]); + $newObj->setLayout($a_rec["DefaultLayout"]); + $newObj->setPageHeader($a_rec["PageHeader"]); + $newObj->setActiveTOC(ilUtil::yn2tf($a_rec["TocActive"])); + $newObj->setActiveLMMenu(ilUtil::yn2tf($a_rec["LmMenuActive"])); + $newObj->setTOCMode($a_rec["TocMode"]); + $newObj->setActivePrintView(ilUtil::yn2tf($a_rec["PrintViewActive"])); + $newObj->setActivePreventGlossaryAppendix(ilUtil::yn2tf($a_rec["NoGloAppendix"])); + $newObj->setActiveNumbering(ilUtil::yn2tf($a_rec["Numbering"])); + $newObj->setHistoryUserComments(ilUtil::yn2tf($a_rec["HistUserComments"])); + $newObj->setPublicAccessMode($a_rec["PublicAccessMode"]); + $newObj->setPublicNotes(ilUtil::yn2tf($a_rec["PubNotes"])); + // Header Page/ Footer Page ??? + $newObj->setLayoutPerPage($a_rec["LayoutPerPage"]); + $newObj->setRating($a_rec["Rating"]); + $newObj->setHideHeaderFooterPrint($a_rec["HideHeadFootPrint"]); + $newObj->setDisableDefaultFeedback($a_rec["DisableDefFeedback"]); + $newObj->setRatingPages($a_rec["RatingPages"]); + $newObj->setForTranslation($a_rec["ForTranslation"]); + $newObj->setProgressIcons($a_rec["ProgrIcons"]); + $newObj->setStoreTries($a_rec["StoreTries"]); + $newObj->setRestrictForwardNavigation($a_rec["RestrictForwNav"]); + if ($a_rec["HeaderPage"] > 0) { + $a_mapping->addMapping("Modules/LearningModule", "lm_header_page", $a_rec["HeaderPage"], "-"); + } + if ($a_rec["FooterPage"] > 0) { + $a_mapping->addMapping("Modules/LearningModule", "lm_footer_page", $a_rec["FooterPage"], "-"); + } + + $newObj->update(true); + $this->current_obj = $newObj; + + // activated comments + include_once("./Services/Notes/classes/class.ilNote.php"); + ilNote::activateComments($newObj->getId(), 0, "lm", (int) $a_rec["Comments"]); + + $a_mapping->addMapping("Modules/LearningModule", "lm", $a_rec["Id"], $newObj->getId()); + $a_mapping->addMapping("Modules/LearningModule", "lm_style", $newObj->getId(), $a_rec["StyleId"]); + $a_mapping->addMapping("Services/Object", "obj", $a_rec["Id"], $newObj->getId()); + $a_mapping->addMapping( + "Services/MetaData", + "md", + $a_rec["Id"] . ":0:lm", + $newObj->getId() . ":0:lm" + ); + break; + + case "lm_tree": + if (!$this->getTranslationImportMode()) { + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + include_once("./Modules/LearningModule/classes/class.ilStructureObject.php"); + include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); + switch ($a_rec["Type"]) { + case "st": + $parent = (int) $a_mapping->getMapping("Modules/LearningModule", "lm_tree", $a_rec["Parent"]); + $st_obj = new ilStructureObject($this->current_obj); + $st_obj->setType("st"); + $st_obj->setLMId($this->current_obj->getId()); + $st_obj->setTitle($a_rec["Title"]); + $st_obj->setShortTitle($a_rec["ShortTitle"]); + $st_obj->setImportId($a_rec["ImportId"]); + $st_obj->create(true); + ilLMObject::putInTree($st_obj, $parent, IL_LAST_NODE); + $a_mapping->addMapping( + "Modules/LearningModule", + "lm_tree", + $a_rec["Child"], + $st_obj->getId() + ); + $a_mapping->addMapping( + "Services/MetaData", + "md", + $a_rec["LmId"] . ":" . $a_rec["Child"] . ":st", + $this->current_obj->getId() . ":" . $st_obj->getId() . ":st" + ); + break; + + case "pg": + $parent = (int) $a_mapping->getMapping("Modules/LearningModule", "lm_tree", $a_rec["Parent"]); + $pg_obj = new ilLMPageObject($this->current_obj); + $pg_obj->setType("pg"); + $pg_obj->setLMId($this->current_obj->getId()); + $pg_obj->setTitle($a_rec["Title"]); + $pg_obj->setShortTitle($a_rec["ShortTitle"]); + $pg_obj->setImportId($a_rec["ImportId"]); + $pg_obj->create(true, true); + ilLMObject::putInTree($pg_obj, $parent, IL_LAST_NODE); + $a_mapping->addMapping( + "Modules/LearningModule", + "lm_tree", + $a_rec["Child"], + $pg_obj->getId() + ); + $a_mapping->addMapping("Modules/LearningModule", "pg", $a_rec["Child"], $pg_obj->getId()); + $this->lm_log->debug("add pg map (1), old : " . $a_rec["Child"] . ", new: " . $pg_obj->getId()); + $a_mapping->addMapping( + "Services/COPage", + "pg", + "lm:" . $a_rec["Child"], + "lm:" . $pg_obj->getId() + ); + $a_mapping->addMapping( + "Services/MetaData", + "md", + $a_rec["LmId"] . ":" . $a_rec["Child"] . ":pg", + $this->current_obj->getId() . ":" . $pg_obj->getId() . ":pg" + ); + break; + + // add free pages #18976 + case "free_pg": + $pg_obj = new ilLMPageObject($this->current_obj); + $pg_obj->setType("pg"); + $pg_obj->setLMId($this->current_obj->getId()); + $pg_obj->setTitle($a_rec["Title"]); + $pg_obj->setShortTitle($a_rec["ShortTitle"]); + $pg_obj->setImportId($a_rec["ImportId"]); + $pg_obj->create(true, true); + $a_mapping->addMapping( + "Modules/LearningModule", + "lm_tree", + $a_rec["Child"], + $pg_obj->getId() + ); + $a_mapping->addMapping("Modules/LearningModule", "pg", $a_rec["Child"], $pg_obj->getId()); + $this->lm_log->debug("add pg map (2), old : " . $a_rec["Child"] . ", new: " . $pg_obj->getId()); + $a_mapping->addMapping( + "Services/COPage", + "pg", + "lm:" . $a_rec["Child"], + "lm:" . $pg_obj->getId() + ); + $a_mapping->addMapping( + "Services/MetaData", + "md", + $a_rec["LmId"] . ":" . $a_rec["Child"] . ":pg", + $this->current_obj->getId() . ":" . $pg_obj->getId() . ":pg" + ); + break; + } + } else { + include_once("./Modules/LearningModule/classes/class.ilLMObjTranslation.php"); + switch ($a_rec["Type"]) { + case "st": + //"il_inst_st_66" + $imp_id = explode("_", $a_rec["ImportId"]); + if ($imp_id[0] == "il" && + (int) $imp_id[1] == (int) IL_INST_ID && + $imp_id[2] == "st" + ) { + $st_id = $imp_id[3]; + if (ilLMObject::_lookupContObjId($st_id) == $this->getTranslationLM()->getId()) { + $trans = new ilLMObjTranslation($st_id, $this->getTranslationLang()); + $trans->setTitle($a_rec["Title"]); + $trans->save(); + $a_mapping->addMapping( + "Modules/LearningModule", + "link", + "il_" . $this->getCurrentInstallationId() . "_" . $a_rec["Type"] . "_" . $a_rec["Child"], + $a_rec["ImportId"] + ); + } + } + // no meta-data mapping, since we do not want to import metadata + break; + + case "pg": + //"il_inst_pg_66" + $imp_id = explode("_", $a_rec["ImportId"]); + if ($imp_id[0] == "il" && + (int) $imp_id[1] == (int) IL_INST_ID && + $imp_id[2] == "pg" + ) { + $pg_id = $imp_id[3]; + if (ilLMObject::_lookupContObjId($pg_id) == $this->getTranslationLM()->getId()) { + $trans = new ilLMObjTranslation($pg_id, $this->getTranslationLang()); + $trans->setTitle($a_rec["Title"]); + $trans->save(); + $a_mapping->addMapping("Modules/LearningModule", "pg", $a_rec["Child"], $pg_id); + $this->lm_log->debug("add pg map (3), old : " . $a_rec["Child"] . ", new: " . $pg_id); + $a_mapping->addMapping( + "Modules/LearningModule", + "link", + "il_" . $this->getCurrentInstallationId() . "_" . $a_rec["Type"] . "_" . $a_rec["Child"], + $a_rec["ImportId"] + ); + $a_mapping->addMapping( + "Services/COPage", + "pg", + "lm:" . $a_rec["Child"], + "lm:" . $pg_id + ); + } + } + // no meta-data mapping, since we do not want to import metadata + break; + } + } + break; + + case "lm_data_transl": + include_once("./Modules/LearningModule/classes/class.ilLMObjTranslation.php"); + if (!$this->getTranslationImportMode()) { + // save page/chapter title translation + $lm_obj_id = $a_mapping->getMapping("Modules/LearningModule", "lm_tree", $a_rec["Id"]); + if ($lm_obj_id > 0) { + $t = new ilLMObjTranslation($lm_obj_id, $a_rec["Lang"]); + $t->setTitle($a_rec["Title"]); + $t->setShortTitle($a_rec["ShortTitle"]); + $t->save(); + } + } + break; + + case "lm_menu": + $lm_id = (int) $a_mapping->getMapping("Modules/LearningModule", "lm", $a_rec["LmId"]); + if ($lm_id > 0) { + $lm_menu_ed = new ilLMMenuEditor(); + $lm_menu_ed->setObjId($lm_id); + $lm_menu_ed->setTitle($a_rec["Title"]); + $lm_menu_ed->setTarget($a_rec["Target"]); + $lm_menu_ed->setLinkType($a_rec["LinkType"]); + $lm_menu_ed->setLinkRefId($a_rec["LinkRefId"]); + $lm_menu_ed->setActive($a_rec["Active"]); + $lm_menu_ed->create(); + } + break; + + } + } } -?> \ No newline at end of file diff --git a/Modules/LearningModule/classes/class.ilLearningModuleExportConfig.php b/Modules/LearningModule/classes/class.ilLearningModuleExportConfig.php index 67cadf7f6bd4a8157ec11c7556530d4436524b91..0a6346eeb52bd808843e8a3ad185cbd8411c1fc1 100644 --- a/Modules/LearningModule/classes/class.ilLearningModuleExportConfig.php +++ b/Modules/LearningModule/classes/class.ilLearningModuleExportConfig.php @@ -12,40 +12,37 @@ include_once("./Services/Export/classes/class.ilExportConfig.php"); */ class ilLearningModuleExportConfig extends ilExportConfig { - protected $master_only = false; - protected $include_media = true; + protected $master_only = false; + protected $include_media = true; - /** - * Set master language only - * - * @param bool $a_val export only master language - */ - function setMasterLanguageOnly($a_val, $a_include_media = true) - { - $this->master_only = $a_val; - $this->include_media = $a_include_media; - } + /** + * Set master language only + * + * @param bool $a_val export only master language + */ + public function setMasterLanguageOnly($a_val, $a_include_media = true) + { + $this->master_only = $a_val; + $this->include_media = $a_include_media; + } - /** - * Get master language only - * - * @return bool export only master language - */ - function getMasterLanguageOnly() - { - return $this->master_only; - } - - /** - * Get include media - * - * @return bool export media? - */ - function getIncludeMedia() - { - return $this->include_media; - } + /** + * Get master language only + * + * @return bool export only master language + */ + public function getMasterLanguageOnly() + { + return $this->master_only; + } + /** + * Get include media + * + * @return bool export media? + */ + public function getIncludeMedia() + { + return $this->include_media; + } } - -?> \ No newline at end of file diff --git a/Modules/LearningModule/classes/class.ilLearningModuleExporter.php b/Modules/LearningModule/classes/class.ilLearningModuleExporter.php index 1a9d9eefef590dc8422b57369376f79201ac4257..c75a8521e6f1e3dad1affa9e2fdf8e812820ee84 100644 --- a/Modules/LearningModule/classes/class.ilLearningModuleExporter.php +++ b/Modules/LearningModule/classes/class.ilLearningModuleExporter.php @@ -12,224 +12,202 @@ include_once("./Services/Export/classes/class.ilXmlExporter.php"); */ class ilLearningModuleExporter extends ilXmlExporter { - private $ds; - /** - * @var ilLearningModuleExportConfig - */ - private $config; - - /** - * Initialisation - */ - function init() - { - include_once("./Modules/LearningModule/classes/class.ilLearningModuleDataSet.php"); - $this->ds = new ilLearningModuleDataSet(); - $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); - $this->ds->setDSPrefix("ds"); - $this->config = $this->getExport()->getConfig("Modules/LearningModule"); - if ($this->config->getMasterLanguageOnly()) - { - $conf = $this->getExport()->getConfig("Services/COPage"); - $conf->setMasterLanguageOnly(true, $this->config->getIncludeMedia()); - $this->ds->setMasterLanguageOnly(true); - } - } - - /** - * Get tail dependencies - * - * @param string entity - * @param string target release - * @param array ids - * @return array array of array with keys "component", entity", "ids" - */ - function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) - { - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); - - $deps = array(); - - if ($a_entity == "lm") - { - $md_ids = array(); - - // lm related ids - foreach ($a_ids as $id) - { - $md_ids[] = $id . ":0:lm"; - } - - // chapter related ids - foreach ($a_ids as $id) - { - $chaps = ilLMObject::getObjectList($id, "st"); - foreach ($chaps as $c) - { - $md_ids[] = $id . ":" . $c["obj_id"] . ":st"; - } - } - - // page related ids - $pg_ids = array(); - foreach ($a_ids as $id) - { - $pages = ilLMPageObject::getPageList($id); - foreach ($pages as $p) - { - $pg_ids[] = "lm:" . $p["obj_id"]; - $md_ids[] = $id . ":" . $p["obj_id"] . ":pg"; - } - } - - // style, multilang, metadata per page/chap? - - $deps = array( - array( - "component" => "Services/COPage", - "entity" => "pg", - "ids" => $pg_ids), - array( - "component" => "Services/MetaData", - "entity" => "md", - "ids" => $md_ids), - ); - - if (!$this->config->getMasterLanguageOnly()) - { - $deps[] = array( - "component" => "Services/Object", - "entity" => "transl", - "ids" => $md_ids); - } + private $ds; + /** + * @var ilLearningModuleExportConfig + */ + private $config; + + /** + * Initialisation + */ + public function init() + { + include_once("./Modules/LearningModule/classes/class.ilLearningModuleDataSet.php"); + $this->ds = new ilLearningModuleDataSet(); + $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); + $this->ds->setDSPrefix("ds"); + $this->config = $this->getExport()->getConfig("Modules/LearningModule"); + if ($this->config->getMasterLanguageOnly()) { + $conf = $this->getExport()->getConfig("Services/COPage"); + $conf->setMasterLanguageOnly(true, $this->config->getIncludeMedia()); + $this->ds->setMasterLanguageOnly(true); + } + } + + /** + * Get tail dependencies + * + * @param string entity + * @param string target release + * @param array ids + * @return array array of array with keys "component", entity", "ids" + */ + public function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) + { + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); + + $deps = array(); + + if ($a_entity == "lm") { + $md_ids = array(); + + // lm related ids + foreach ($a_ids as $id) { + $md_ids[] = $id . ":0:lm"; + } + + // chapter related ids + foreach ($a_ids as $id) { + $chaps = ilLMObject::getObjectList($id, "st"); + foreach ($chaps as $c) { + $md_ids[] = $id . ":" . $c["obj_id"] . ":st"; + } + } + + // page related ids + $pg_ids = array(); + foreach ($a_ids as $id) { + $pages = ilLMPageObject::getPageList($id); + foreach ($pages as $p) { + $pg_ids[] = "lm:" . $p["obj_id"]; + $md_ids[] = $id . ":" . $p["obj_id"] . ":pg"; + } + } + + // style, multilang, metadata per page/chap? + + $deps = array( + array( + "component" => "Services/COPage", + "entity" => "pg", + "ids" => $pg_ids), + array( + "component" => "Services/MetaData", + "entity" => "md", + "ids" => $md_ids), + ); + + if (!$this->config->getMasterLanguageOnly()) { + $deps[] = array( + "component" => "Services/Object", + "entity" => "transl", + "ids" => $md_ids); + } $deps[] = array( "component" => "Services/Object", "entity" => "tile", "ids" => $a_ids); - // help export - foreach ($a_ids as $id) - { - include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); - if (ilObjContentObject::isOnlineHelpModule($id, true)) - { - $deps[] = array( - "component" => "Services/Help", - "entity" => "help", - "ids" => array($id)); - } - } - - // style - foreach ($a_ids as $id) - { - include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); - if (($s = ilObjContentObject::_lookupStyleSheetId($id)) > 0) - { - $deps[] = array( - "component" => "Services/Style", - "entity" => "sty", - "ids" => $s - ); - } - } - } - - return $deps; - } - - - - /** - * Get xml representation - * - * @param string entity - * @param string target release - * @param string id - * @return string xml string - */ - public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) - { - // workaround: old question export - $q_ids = array(); - include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); - $pages = ilLMPageObject::getPageList($a_id); - foreach ($pages as $p) - { - $langs = array("-"); - if (!$this->config->getMasterLanguageOnly()) - { - $trans = ilPageObject::lookupTranslations("lm", $p["obj_id"]); - foreach ($trans as $t) - { - if ($t != "-") - { - $langs[] = $t; - } - } - } - foreach ($langs as $l) - { - // collect questions - include_once("./Services/COPage/classes/class.ilPCQuestion.php"); - foreach (ilPCQuestion::_getQuestionIdsForPage("lm", $p["obj_id"], $l) as $q_id) - { - $q_ids[$q_id] = $q_id; - } - } - } - if (count($q_ids) > 0) - { - $dir = $this->getExport()->export_run_dir; - $qti_file = fopen($dir."/qti.xml", "w"); - include_once("./Modules/TestQuestionPool/classes/class.ilObjQuestionPool.php"); - $pool = new ilObjQuestionPool(); - fwrite($qti_file, $pool->questionsToXML($q_ids)); - fclose($qti_file); - } - - return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); - - /*include_once './Modules/LearningModule/classes/class.ilObjLearningModule.php'; - $lm = new ilObjLearningModule($a_id,false); - - include_once './Modules/LearningModule/classes/class.ilContObjectExport.php'; - $exp = new ilContObjectExport($lm); - $zip = $exp->buildExportFile();*/ - } - - /** - * Returns schema versions that the component can export to. - * ILIAS chooses the first one, that has min/max constraints which - * fit to the target release. Please put the newest on top. - * - * @return - */ - function getValidSchemaVersions($a_entity) - { - return array ( - "5.4.0" => array( - "namespace" => "http://www.ilias.de/Modules/LearningModule/lm/5_4", - "xsd_file" => "ilias_lm_5_4.xsd", - "uses_dataset" => true, - "min" => "5.4.0", - "max" => ""), - "5.1.0" => array( - "namespace" => "http://www.ilias.de/Modules/LearningModule/lm/5_1", - "xsd_file" => "ilias_lm_5_1.xsd", - "uses_dataset" => true, - "min" => "5.1.0", - "max" => ""), - "4.1.0" => array( - "namespace" => "http://www.ilias.de/Modules/LearningModule/lm/4_1", - "xsd_file" => "ilias_lm_4_1.xsd", - "uses_dataset" => false, - "min" => "4.1.0", - "max" => "") - ); - } - + // help export + foreach ($a_ids as $id) { + include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); + if (ilObjContentObject::isOnlineHelpModule($id, true)) { + $deps[] = array( + "component" => "Services/Help", + "entity" => "help", + "ids" => array($id)); + } + } + + // style + foreach ($a_ids as $id) { + include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); + if (($s = ilObjContentObject::_lookupStyleSheetId($id)) > 0) { + $deps[] = array( + "component" => "Services/Style", + "entity" => "sty", + "ids" => $s + ); + } + } + } + + return $deps; + } + + + + /** + * Get xml representation + * + * @param string entity + * @param string target release + * @param string id + * @return string xml string + */ + public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) + { + // workaround: old question export + $q_ids = array(); + include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); + $pages = ilLMPageObject::getPageList($a_id); + foreach ($pages as $p) { + $langs = array("-"); + if (!$this->config->getMasterLanguageOnly()) { + $trans = ilPageObject::lookupTranslations("lm", $p["obj_id"]); + foreach ($trans as $t) { + if ($t != "-") { + $langs[] = $t; + } + } + } + foreach ($langs as $l) { + // collect questions + include_once("./Services/COPage/classes/class.ilPCQuestion.php"); + foreach (ilPCQuestion::_getQuestionIdsForPage("lm", $p["obj_id"], $l) as $q_id) { + $q_ids[$q_id] = $q_id; + } + } + } + if (count($q_ids) > 0) { + $dir = $this->getExport()->export_run_dir; + $qti_file = fopen($dir . "/qti.xml", "w"); + include_once("./Modules/TestQuestionPool/classes/class.ilObjQuestionPool.php"); + $pool = new ilObjQuestionPool(); + fwrite($qti_file, $pool->questionsToXML($q_ids)); + fclose($qti_file); + } + + return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); + + /*include_once './Modules/LearningModule/classes/class.ilObjLearningModule.php'; + $lm = new ilObjLearningModule($a_id,false); + + include_once './Modules/LearningModule/classes/class.ilContObjectExport.php'; + $exp = new ilContObjectExport($lm); + $zip = $exp->buildExportFile();*/ + } + + /** + * Returns schema versions that the component can export to. + * ILIAS chooses the first one, that has min/max constraints which + * fit to the target release. Please put the newest on top. + * + * @return + */ + public function getValidSchemaVersions($a_entity) + { + return array( + "5.4.0" => array( + "namespace" => "http://www.ilias.de/Modules/LearningModule/lm/5_4", + "xsd_file" => "ilias_lm_5_4.xsd", + "uses_dataset" => true, + "min" => "5.4.0", + "max" => ""), + "5.1.0" => array( + "namespace" => "http://www.ilias.de/Modules/LearningModule/lm/5_1", + "xsd_file" => "ilias_lm_5_1.xsd", + "uses_dataset" => true, + "min" => "5.1.0", + "max" => ""), + "4.1.0" => array( + "namespace" => "http://www.ilias.de/Modules/LearningModule/lm/4_1", + "xsd_file" => "ilias_lm_4_1.xsd", + "uses_dataset" => false, + "min" => "4.1.0", + "max" => "") + ); + } } - -?> \ No newline at end of file diff --git a/Modules/LearningModule/classes/class.ilLearningModuleImportConfig.php b/Modules/LearningModule/classes/class.ilLearningModuleImportConfig.php index e213afcb8ea673853999b7c8800ae27231ed1267..407042178d5c3782e1528181e07fd0c5908fb745 100644 --- a/Modules/LearningModule/classes/class.ilLearningModuleImportConfig.php +++ b/Modules/LearningModule/classes/class.ilLearningModuleImportConfig.php @@ -12,60 +12,54 @@ include_once("./Services/Export/classes/class.ilImportConfig.php"); */ class ilLearningModuleImportConfig extends ilImportConfig { - protected $transl_into = false; - protected $transl_into_lm = null; - protected $transl_lang = ""; + protected $transl_into = false; + protected $transl_into_lm = null; + protected $transl_lang = ""; - /** - * Set translation import mode - * - * @param ilObjLearningModule $a_lm learning module - * @param string $a_lang language - */ - function setTranslationImportMode($a_lm, $a_lang = "") - { - if ($a_lm != null) - { - $this->transl_into = true; - $this->transl_into_lm = $a_lm; - $this->transl_lang = $a_lang; - } - else - { - $this->transl_into = false; - } - } + /** + * Set translation import mode + * + * @param ilObjLearningModule $a_lm learning module + * @param string $a_lang language + */ + public function setTranslationImportMode($a_lm, $a_lang = "") + { + if ($a_lm != null) { + $this->transl_into = true; + $this->transl_into_lm = $a_lm; + $this->transl_lang = $a_lang; + } else { + $this->transl_into = false; + } + } - /** - * Get translation import mode - * - * @return bool check if translation import is activated - */ - function getTranslationImportMode() - { - return $this->transl_into; - } + /** + * Get translation import mode + * + * @return bool check if translation import is activated + */ + public function getTranslationImportMode() + { + return $this->transl_into; + } - /** - * Get translation lm - * - * @return ilObjLearningModule learning module - */ - function getTranslationLM() - { - return $this->transl_into_lm; - } - - /** - * Get translation language - * - * @return string language - */ - function getTranslationLang() - { - return $this->transl_lang; - } + /** + * Get translation lm + * + * @return ilObjLearningModule learning module + */ + public function getTranslationLM() + { + return $this->transl_into_lm; + } + /** + * Get translation language + * + * @return string language + */ + public function getTranslationLang() + { + return $this->transl_lang; + } } - -?> \ No newline at end of file diff --git a/Modules/LearningModule/classes/class.ilLearningModuleImporter.php b/Modules/LearningModule/classes/class.ilLearningModuleImporter.php index 17dd2f760312a1428059ae939c1d84f26fc498dc..f4e61a3e59e35bc277680500c2853ff6f57a9c7f 100644 --- a/Modules/LearningModule/classes/class.ilLearningModuleImporter.php +++ b/Modules/LearningModule/classes/class.ilLearningModuleImporter.php @@ -12,206 +12,193 @@ include_once("./Services/Export/classes/class.ilXmlImporter.php"); */ class ilLearningModuleImporter extends ilXmlImporter { - protected $config; - - /** - * @var ilLogger - */ - protected $log; - - /** - * Initialisation - */ - function init() - { - include_once("./Modules/LearningModule/classes/class.ilLearningModuleDataSet.php"); - $this->ds = new ilLearningModuleDataSet(); - $this->ds->setDSPrefix("ds"); - - $this->log = ilLoggerFactory::getLogger('lm'); - - $this->config = $this->getImport()->getConfig("Modules/LearningModule"); - if ($this->config->getTranslationImportMode()) - { - $this->ds->setTranslationImportMode( - $this->config->getTranslationLM(), - $this->config->getTranslationLang()); - $cop_config = $this->getImport()->getConfig("Services/COPage"); - $cop_config->setUpdateIfExists(true); - $cop_config->setForceLanguage($this->config->getTranslationLang()); - $cop_config->setReuseOriginallyExportedMedia(true); - $cop_config->setSkipInternalLinkResolve(true); - - $mob_config = $this->getImport()->getConfig("Services/MediaObjects"); - $mob_config->setUsePreviousImportIds(true); - } - } - - - /** - * Import XML - * - * @param - * @return - */ - function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) - { - include_once './Modules/File/classes/class.ilObjFile.php'; - - $this->log->debug("import XML Representation"); - - // case i container - if($new_id = $a_mapping->getMapping('Services/Container','objs',$a_id)) - { - $newObj = ilObjectFactory::getInstanceByObjId($new_id,false); - $newObj->createLMTree(); - $this->log->debug("got mapping, new id is: ".$new_id); - } - - // 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'; - - // old school import - // currently this means we got a container and mapping, too, since - // for single lms the processing in ilObjContentObjectGUI->importFileObject is used - // (this should be streamlined, see glossary) - if (file_exists($xml_file)) - { - $newObj->setImportDirectory(dirname(rtrim($this->getImportDirectory(), '/'))); - $mess = $newObj->importFromDirectory($this->getImportDirectory(), true, $a_mapping); - $this->log->debug("imported from directory ($mess)"); - $a_mapping->addMapping("Modules/LearningModule", "lm", $a_id, $newObj->getId()); - $a_mapping->addMapping("Services/Object", "obj", $a_id, $newObj->getId()); - } - else // new import version (does mapping, too) - { - $this->log->debug("create ilDataSetIportParser instance"); - include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); - $parser = new ilDataSetImportParser($a_entity, $this->getSchemaVersion(), - $a_xml, $this->ds, $a_mapping); - } - - // import qti stuff - $this->log->debug("import qti data"); - $qti_file = $this->getImportDirectory().'/qti.xml'; - $this->qtis = array(); - if (is_file($qti_file)) - { - include_once "./Services/QTI/classes/class.ilQTIParser.php"; - include_once("./Modules/Test/classes/class.ilObjTest.php"); - $qtiParser = new ilQTIParser ($qti_file, - IL_MO_VERIFY_QTI, 0, ""); - $result = $qtiParser->startParsing (); - $founditems = & $qtiParser->getFoundItems (); - $testObj = new ilObjTest(0, true); - if (count($founditems) > 0) - { - $qtiParser = new ilQTIParser($qti_file, IL_MO_PARSE_QTI, 0, ""); - $qtiParser->setTestObject($testObj); - $result = $qtiParser->startParsing(); - $this->qtis = array_merge($this->qtis, $qtiParser->getImportMapping()); - } - } - } - - /** - * Final processing - * - * @param array mapping array - */ - function finalProcessing($a_mapping) - { - $pg_map = $a_mapping->getMappingsOfEntity("Modules/LearningModule", "pg"); - - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); - $this->log->debug("pg map entries: ".count($pg_map)); - foreach ($pg_map as $pg_id) - { - $lm_id = ilLMPageObject::_lookupContObjID($pg_id); - ilLMPage::_writeParentId("lm", $pg_id, $lm_id); - $this->log->debug("write parent id, pg id: ".$pg_id.", lm id: ".$lm_id); - } - - // header footer page - foreach ($a_mapping->getMappingsOfEntity("Modules/LearningModule", "lm_header_page") as $old_id => $dummy) - { - $new_page_id = (int) $a_mapping->getMapping("Modules/LearningModule", "pg", $old_id); - if ($new_page_id > 0) - { - $lm_id = ilLMPageObject::_lookupContObjID($new_page_id); - ilObjLearningModule::writeHeaderPage($lm_id, $new_page_id); - } - } - foreach ($a_mapping->getMappingsOfEntity("Modules/LearningModule", "lm_footer_page") as $old_id => $dummy) - { - $new_page_id = (int) $a_mapping->getMapping("Modules/LearningModule", "pg", $old_id); - if ($new_page_id > 0) - { - $lm_id = ilLMPageObject::_lookupContObjID($new_page_id); - ilObjLearningModule::writeFooterPage($lm_id, $new_page_id); - } - } - - - $link_map = $a_mapping->getMappingsOfEntity("Modules/LearningModule", "link"); - $pages = $a_mapping->getMappingsOfEntity("Services/COPage", "pgl"); - foreach ($pages as $p) - { - $id = explode(":", $p); - if (count($id) == 3) - { - include_once("./Services/COPage/classes/class.ilPageObject.php"); - if (ilPageObject::_exists($id[0], $id[1], $id[2], true)) - { - include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); - $new_page = ilPageObjectFactory::getInstance($id[0], $id[1], 0, $id[2]); - $new_page->buildDom(); - - // fix question references - $updated = $new_page->resolveQuestionReferences($this->qtis); - - // in translation mode use link mapping to fix internal links - //$a_mapping->addMapping("Modules/LearningModule", "link", - if ($this->config->getTranslationImportMode()) - { - $il = $new_page->resolveIntLinks($link_map); - if ($il) - { - $updated = true; - } - } - - if ($updated) - { - $new_page->update(false, true); - } - } - } - } - - // assign style - $alls_map = $a_mapping->getMappingsOfEntity("Modules/LearningModule", "lm_style"); - foreach ($alls_map as $new_lm_id => $old_style_id) - { - $new_style_id = (int) $a_mapping->getMapping("Services/Style", "sty", $old_style_id); - if ($new_lm_id > 0 && $new_style_id > 0) - { - include_once("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); - $lm = new ilObjLearningModule($new_lm_id, false); - $lm->writeStyleSheetId($new_style_id); - } - } - - // menu item ref ids - $ref_mapping = $a_mapping->getMappingsOfEntity('Services/Container', 'refs'); - $lm_map = $a_mapping->getMappingsOfEntity("Modules/LearningModule", "lm"); - foreach ($lm_map as $old_lm_id => $new_lm_id) - { - ilLMMenuEditor::fixImportMenuItems($new_lm_id, $ref_mapping); - } - } + protected $config; + + /** + * @var ilLogger + */ + protected $log; + + /** + * Initialisation + */ + public function init() + { + include_once("./Modules/LearningModule/classes/class.ilLearningModuleDataSet.php"); + $this->ds = new ilLearningModuleDataSet(); + $this->ds->setDSPrefix("ds"); + + $this->log = ilLoggerFactory::getLogger('lm'); + + $this->config = $this->getImport()->getConfig("Modules/LearningModule"); + if ($this->config->getTranslationImportMode()) { + $this->ds->setTranslationImportMode( + $this->config->getTranslationLM(), + $this->config->getTranslationLang() + ); + $cop_config = $this->getImport()->getConfig("Services/COPage"); + $cop_config->setUpdateIfExists(true); + $cop_config->setForceLanguage($this->config->getTranslationLang()); + $cop_config->setReuseOriginallyExportedMedia(true); + $cop_config->setSkipInternalLinkResolve(true); + + $mob_config = $this->getImport()->getConfig("Services/MediaObjects"); + $mob_config->setUsePreviousImportIds(true); + } + } + + + /** + * Import XML + * + * @param + * @return + */ + public function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) + { + include_once './Modules/File/classes/class.ilObjFile.php'; + + $this->log->debug("import XML Representation"); + + // case i container + if ($new_id = $a_mapping->getMapping('Services/Container', 'objs', $a_id)) { + $newObj = ilObjectFactory::getInstanceByObjId($new_id, false); + $newObj->createLMTree(); + $this->log->debug("got mapping, new id is: " . $new_id); + } + + // 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'; + + // old school import + // currently this means we got a container and mapping, too, since + // for single lms the processing in ilObjContentObjectGUI->importFileObject is used + // (this should be streamlined, see glossary) + if (file_exists($xml_file)) { + $newObj->setImportDirectory(dirname(rtrim($this->getImportDirectory(), '/'))); + $mess = $newObj->importFromDirectory($this->getImportDirectory(), true, $a_mapping); + $this->log->debug("imported from directory ($mess)"); + $a_mapping->addMapping("Modules/LearningModule", "lm", $a_id, $newObj->getId()); + $a_mapping->addMapping("Services/Object", "obj", $a_id, $newObj->getId()); + } else { // new import version (does mapping, too) + $this->log->debug("create ilDataSetIportParser instance"); + include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); + $parser = new ilDataSetImportParser( + $a_entity, + $this->getSchemaVersion(), + $a_xml, + $this->ds, + $a_mapping + ); + } + + // import qti stuff + $this->log->debug("import qti data"); + $qti_file = $this->getImportDirectory() . '/qti.xml'; + $this->qtis = array(); + if (is_file($qti_file)) { + include_once "./Services/QTI/classes/class.ilQTIParser.php"; + include_once("./Modules/Test/classes/class.ilObjTest.php"); + $qtiParser = new ilQTIParser( + $qti_file, + IL_MO_VERIFY_QTI, + 0, + "" + ); + $result = $qtiParser->startParsing(); + $founditems = &$qtiParser->getFoundItems(); + $testObj = new ilObjTest(0, true); + if (count($founditems) > 0) { + $qtiParser = new ilQTIParser($qti_file, IL_MO_PARSE_QTI, 0, ""); + $qtiParser->setTestObject($testObj); + $result = $qtiParser->startParsing(); + $this->qtis = array_merge($this->qtis, $qtiParser->getImportMapping()); + } + } + } + + /** + * Final processing + * + * @param array mapping array + */ + public function finalProcessing($a_mapping) + { + $pg_map = $a_mapping->getMappingsOfEntity("Modules/LearningModule", "pg"); + + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); + $this->log->debug("pg map entries: " . count($pg_map)); + foreach ($pg_map as $pg_id) { + $lm_id = ilLMPageObject::_lookupContObjID($pg_id); + ilLMPage::_writeParentId("lm", $pg_id, $lm_id); + $this->log->debug("write parent id, pg id: " . $pg_id . ", lm id: " . $lm_id); + } + + // header footer page + foreach ($a_mapping->getMappingsOfEntity("Modules/LearningModule", "lm_header_page") as $old_id => $dummy) { + $new_page_id = (int) $a_mapping->getMapping("Modules/LearningModule", "pg", $old_id); + if ($new_page_id > 0) { + $lm_id = ilLMPageObject::_lookupContObjID($new_page_id); + ilObjLearningModule::writeHeaderPage($lm_id, $new_page_id); + } + } + foreach ($a_mapping->getMappingsOfEntity("Modules/LearningModule", "lm_footer_page") as $old_id => $dummy) { + $new_page_id = (int) $a_mapping->getMapping("Modules/LearningModule", "pg", $old_id); + if ($new_page_id > 0) { + $lm_id = ilLMPageObject::_lookupContObjID($new_page_id); + ilObjLearningModule::writeFooterPage($lm_id, $new_page_id); + } + } + + + $link_map = $a_mapping->getMappingsOfEntity("Modules/LearningModule", "link"); + $pages = $a_mapping->getMappingsOfEntity("Services/COPage", "pgl"); + foreach ($pages as $p) { + $id = explode(":", $p); + if (count($id) == 3) { + include_once("./Services/COPage/classes/class.ilPageObject.php"); + if (ilPageObject::_exists($id[0], $id[1], $id[2], true)) { + include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); + $new_page = ilPageObjectFactory::getInstance($id[0], $id[1], 0, $id[2]); + $new_page->buildDom(); + + // fix question references + $updated = $new_page->resolveQuestionReferences($this->qtis); + + // in translation mode use link mapping to fix internal links + //$a_mapping->addMapping("Modules/LearningModule", "link", + if ($this->config->getTranslationImportMode()) { + $il = $new_page->resolveIntLinks($link_map); + if ($il) { + $updated = true; + } + } + + if ($updated) { + $new_page->update(false, true); + } + } + } + } + + // assign style + $alls_map = $a_mapping->getMappingsOfEntity("Modules/LearningModule", "lm_style"); + foreach ($alls_map as $new_lm_id => $old_style_id) { + $new_style_id = (int) $a_mapping->getMapping("Services/Style", "sty", $old_style_id); + if ($new_lm_id > 0 && $new_style_id > 0) { + include_once("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); + $lm = new ilObjLearningModule($new_lm_id, false); + $lm->writeStyleSheetId($new_style_id); + } + } + + // menu item ref ids + $ref_mapping = $a_mapping->getMappingsOfEntity('Services/Container', 'refs'); + $lm_map = $a_mapping->getMappingsOfEntity("Modules/LearningModule", "lm"); + foreach ($lm_map as $old_lm_id => $new_lm_id) { + ilLMMenuEditor::fixImportMenuItems($new_lm_id, $ref_mapping); + } + } } - -?> \ No newline at end of file diff --git a/Modules/LearningModule/classes/class.ilLearningModuleLP.php b/Modules/LearningModule/classes/class.ilLearningModuleLP.php index 854eb774ad53eff27946f19dd1166262866036ef..3331ab7c7c5eb0b473c773522b5c9936960974d4 100644 --- a/Modules/LearningModule/classes/class.ilLearningModuleLP.php +++ b/Modules/LearningModule/classes/class.ilLearningModuleLP.php @@ -1,57 +1,52 @@ - - * @version $Id: class.ilLPStatusPlugin.php 43734 2013-07-29 15:27:58Z jluetzen $ - * @package ModulesLearningModule - */ -class ilLearningModuleLP extends ilObjectLP -{ - public static function getDefaultModes($a_lp_active) - { - if(!$a_lp_active) - { - return array( - ilLPObjSettings::LP_MODE_DEACTIVATED, - ilLPObjSettings::LP_MODE_QUESTIONS, - ilLPObjSettings::LP_MODE_VISITED_PAGES - ); - } - else - { - return array( - ilLPObjSettings::LP_MODE_DEACTIVATED, - ilLPObjSettings::LP_MODE_MANUAL, - ilLPObjSettings::LP_MODE_QUESTIONS, - ilLPObjSettings::LP_MODE_VISITED_PAGES - ); - } - } - - public function getDefaultMode() - { - return ilLPObjSettings::LP_MODE_MANUAL; - } - - public function getValidModes() - { - return array( - ilLPObjSettings::LP_MODE_DEACTIVATED, - ilLPObjSettings::LP_MODE_MANUAL, - ilLPObjSettings::LP_MODE_COLLECTION_MANUAL, - ilLPObjSettings::LP_MODE_VISITS, - ilLPObjSettings::LP_MODE_TLT, - ilLPObjSettings::LP_MODE_COLLECTION_TLT, - ilLPObjSettings::LP_MODE_QUESTIONS, - ilLPObjSettings::LP_MODE_VISITED_PAGES - ); - } -} - -?> \ No newline at end of file + + * @version $Id: class.ilLPStatusPlugin.php 43734 2013-07-29 15:27:58Z jluetzen $ + * @package ModulesLearningModule + */ +class ilLearningModuleLP extends ilObjectLP +{ + public static function getDefaultModes($a_lp_active) + { + if (!$a_lp_active) { + return array( + ilLPObjSettings::LP_MODE_DEACTIVATED, + ilLPObjSettings::LP_MODE_QUESTIONS, + ilLPObjSettings::LP_MODE_VISITED_PAGES + ); + } else { + return array( + ilLPObjSettings::LP_MODE_DEACTIVATED, + ilLPObjSettings::LP_MODE_MANUAL, + ilLPObjSettings::LP_MODE_QUESTIONS, + ilLPObjSettings::LP_MODE_VISITED_PAGES + ); + } + } + + public function getDefaultMode() + { + return ilLPObjSettings::LP_MODE_MANUAL; + } + + public function getValidModes() + { + return array( + ilLPObjSettings::LP_MODE_DEACTIVATED, + ilLPObjSettings::LP_MODE_MANUAL, + ilLPObjSettings::LP_MODE_COLLECTION_MANUAL, + ilLPObjSettings::LP_MODE_VISITS, + ilLPObjSettings::LP_MODE_TLT, + ilLPObjSettings::LP_MODE_COLLECTION_TLT, + ilLPObjSettings::LP_MODE_QUESTIONS, + ilLPObjSettings::LP_MODE_VISITED_PAGES + ); + } +} diff --git a/Modules/LearningModule/classes/class.ilLearningModuleNewsRendererGUI.php b/Modules/LearningModule/classes/class.ilLearningModuleNewsRendererGUI.php index c29d0cc650047b842a13a3cb6717e634e4ebc159..e933f123f69aa6ba496eb0eb05f6fd40e066519a 100644 --- a/Modules/LearningModule/classes/class.ilLearningModuleNewsRendererGUI.php +++ b/Modules/LearningModule/classes/class.ilLearningModuleNewsRendererGUI.php @@ -12,24 +12,20 @@ include_once("./Services/News/classes/class.ilNewsDefaultRendererGUI.php"); */ class ilLearningModuleNewsRendererGUI extends ilNewsDefaultRendererGUI { - /** - * Get object link - * - * @return string link href url - */ - function getObjectLink() - { - include_once("./Services/Link/classes/class.ilLink.php"); - $n = $this->getNewsItem(); - if ($n->getContextSubObjType() == "pg" - && $n->getContextSubObjId() > 0) - { - //$add = "&target=pg_".$n->getContextSubObjId()."_".$this->getNewsRefId(); - return ilLink::_getLink($n->getContextSubObjId()."_".$this->getNewsRefId(), "pg"); - } - return ilLink::_getLink($this->getNewsRefId()); - } - + /** + * Get object link + * + * @return string link href url + */ + public function getObjectLink() + { + include_once("./Services/Link/classes/class.ilLink.php"); + $n = $this->getNewsItem(); + if ($n->getContextSubObjType() == "pg" + && $n->getContextSubObjId() > 0) { + //$add = "&target=pg_".$n->getContextSubObjId()."_".$this->getNewsRefId(); + return ilLink::_getLink($n->getContextSubObjId() . "_" . $this->getNewsRefId(), "pg"); + } + return ilLink::_getLink($this->getNewsRefId()); + } } - -?> \ No newline at end of file diff --git a/Modules/LearningModule/classes/class.ilLearningModulePageCollector.php b/Modules/LearningModule/classes/class.ilLearningModulePageCollector.php index 3e568e02251c33b5f6f586e797025a79fc3c0344..370dd8bc314a47d264f9fe8869b677b2638a475d 100644 --- a/Modules/LearningModule/classes/class.ilLearningModulePageCollector.php +++ b/Modules/LearningModule/classes/class.ilLearningModulePageCollector.php @@ -12,21 +12,19 @@ include_once("./Services/COPage/interfaces/interface.ilCOPageCollectorInterface. */ class ilLearningModulePageCollector implements ilCOPageCollectorInterface { - /** - * @inheritdoc - */ - public function getAllPageIds($obj_id) - { - $pages = []; - foreach (ilPageObject::getAllPages("lm", $obj_id) as $p) - { - $pages[] = [ - "parent_type" => "lm", - "id" => $p["id"], - "lang" => $p["lang"] - ]; - } - return $pages; - } - -} \ No newline at end of file + /** + * @inheritdoc + */ + public function getAllPageIds($obj_id) + { + $pages = []; + foreach (ilPageObject::getAllPages("lm", $obj_id) as $p) { + $pages[] = [ + "parent_type" => "lm", + "id" => $p["id"], + "lang" => $p["lang"] + ]; + } + return $pages; + } +} diff --git a/Modules/LearningModule/classes/class.ilLinksTableGUI.php b/Modules/LearningModule/classes/class.ilLinksTableGUI.php index ab5da2c7731d15178181d5a363d82293358d06c1..aaf79dd60ddea1050ea3a5ad974ac3cc88a8e2ee 100755 --- a/Modules/LearningModule/classes/class.ilLinksTableGUI.php +++ b/Modules/LearningModule/classes/class.ilLinksTableGUI.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->addColumn($lng->txt("pg"), "", ""); + $this->addColumn($lng->txt("cont_internal_links"), "", ""); + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate( + "tpl.links_table_row.html", + "Modules/LearningModule" + ); + $this->lm_id = $a_lm_id; + $this->lm_type = $a_lm_type; + $this->getLinks(); + + $this->setTitle($lng->txt("cont_internal_links")); + } + + /** + * Get pages incl. links + */ + public function getLinks() + { + $pages = ilLMPageObject::getPagesWithLinksList($this->lm_id, $this->lm_type); + $this->setData($pages); + } + + /** + * 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->addColumn($lng->txt("pg"), "", ""); - $this->addColumn($lng->txt("cont_internal_links"), "", ""); - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.links_table_row.html", - "Modules/LearningModule"); - $this->lm_id = $a_lm_id; - $this->lm_type = $a_lm_type; - $this->getLinks(); - - $this->setTitle($lng->txt("cont_internal_links")); - } - - /** - * Get pages incl. links - */ - function getLinks() - { - $pages = ilLMPageObject::getPagesWithLinksList($this->lm_id, $this->lm_type); - $this->setData($pages); - } - - /** - * 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->tpl->setVariable("TXT_PAGE_TITLE", $a_set["title"]); + $ilCtrl->setParameterByClass( + "illmpageobjectgui", + "obj_id", + $a_set["obj_id"] + ); + $this->tpl->setVariable( + "HREF_PAGE", + $ilCtrl->getLinkTargetByClass("illmpageobjectgui", "edit") + ); + + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + $page_object = new ilLMPage($a_set["obj_id"]); + $page_object->buildDom(); + $int_links = $page_object->getInternalLinks(); + + foreach ($int_links as $link) { + $target = $link["Target"]; + if (substr($target, 0, 4) == "il__") { + $target_arr = explode("_", $target); + $target_id = $target_arr[count($target_arr) - 1]; + $type = $link["Type"]; + + switch ($type) { + case "PageObject": + $this->tpl->setCurrentBlock("link"); + $this->tpl->setVariable("TXT_LINK_TYPE", $lng->txt("pg")); + if (ilLMObject::_exists($target_id)) { + $lm_id = ilLMObject::_lookupContObjID($target_id); + $add_str = ($lm_id != $this->lm_id) + ? " (" . ilObject::_lookupTitle($lm_id) . ")" + : ""; + $this->tpl->setVariable( + "TXT_LINK_TITLE", + ilLMObject::_lookupTitle($target_id) . $add_str + ); + } else { + $this->tpl->setVariable( + "TXT_MISSING", + "" . $lng->txt("cont_target_missing") . " [" . $target_id . "]" . "" + ); + } + $this->tpl->parseCurrentBlock(); + break; + + case "StructureObject": + $this->tpl->setCurrentBlock("link"); + $this->tpl->setVariable("TXT_LINK_TYPE", $lng->txt("st")); + if (ilLMObject::_exists($target_id)) { + $lm_id = ilLMObject::_lookupContObjID($target_id); + $add_str = ($lm_id != $this->lm_id) + ? " (" . ilObject::_lookupTitle($lm_id) . ")" + : ""; + $this->tpl->setVariable( + "TXT_LINK_TITLE", + ilLMObject::_lookupTitle($target_id) . $add_str + ); + } else { + $this->tpl->setVariable( + "TXT_MISSING", + "" . $lng->txt("cont_target_missing") . " [" . $target_id . "]" . "" + ); + } + $this->tpl->parseCurrentBlock(); + break; - $this->tpl->setVariable("TXT_PAGE_TITLE", $a_set["title"]); - $ilCtrl->setParameterByClass("illmpageobjectgui", "obj_id", - $a_set["obj_id"]); - $this->tpl->setVariable("HREF_PAGE", - $ilCtrl->getLinkTargetByClass("illmpageobjectgui", "edit")); - - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - $page_object = new ilLMPage($a_set["obj_id"]); - $page_object->buildDom(); - $int_links = $page_object->getInternalLinks(); - - foreach($int_links as $link) - { - $target = $link["Target"]; - if (substr($target, 0, 4) == "il__") - { - $target_arr = explode("_", $target); - $target_id = $target_arr[count($target_arr) - 1]; - $type = $link["Type"]; - - switch($type) - { - case "PageObject": - $this->tpl->setCurrentBlock("link"); - $this->tpl->setVariable("TXT_LINK_TYPE", $lng->txt("pg")); - if (ilLMObject::_exists($target_id)) - { - $lm_id = ilLMObject::_lookupContObjID($target_id); - $add_str = ($lm_id != $this->lm_id) - ? " (".ilObject::_lookupTitle($lm_id).")" - : ""; - $this->tpl->setVariable("TXT_LINK_TITLE", - ilLMObject::_lookupTitle($target_id).$add_str); - } - else - { - $this->tpl->setVariable("TXT_MISSING", - "".$lng->txt("cont_target_missing")." [".$target_id."]".""); - } - $this->tpl->parseCurrentBlock(); - break; - - case "StructureObject": - $this->tpl->setCurrentBlock("link"); - $this->tpl->setVariable("TXT_LINK_TYPE", $lng->txt("st")); - if (ilLMObject::_exists($target_id)) - { - $lm_id = ilLMObject::_lookupContObjID($target_id); - $add_str = ($lm_id != $this->lm_id) - ? " (".ilObject::_lookupTitle($lm_id).")" - : ""; - $this->tpl->setVariable("TXT_LINK_TITLE", - ilLMObject::_lookupTitle($target_id).$add_str); - } - else - { - $this->tpl->setVariable("TXT_MISSING", - "".$lng->txt("cont_target_missing")." [".$target_id."]".""); - } - $this->tpl->parseCurrentBlock(); - break; + case "GlossaryItem": + $this->tpl->setCurrentBlock("link"); + $this->tpl->setVariable("TXT_LINK_TYPE", $lng->txt("cont_term")); + include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + if (ilGlossaryTerm::_exists($target_id)) { + $this->tpl->setVariable( + "TXT_LINK_TITLE", + ilGlossaryTerm::_lookGlossaryTerm($target_id) + ); + } else { + $this->tpl->setVariable( + "TXT_MISSING", + "" . $lng->txt("cont_target_missing") . " [" . $target_id . "]" . "" + ); + } + $this->tpl->parseCurrentBlock(); + break; - case "GlossaryItem": - $this->tpl->setCurrentBlock("link"); - $this->tpl->setVariable("TXT_LINK_TYPE", $lng->txt("cont_term")); - include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - if (ilGlossaryTerm::_exists($target_id)) - { - $this->tpl->setVariable("TXT_LINK_TITLE", - ilGlossaryTerm::_lookGlossaryTerm($target_id)); - } - else - { - $this->tpl->setVariable("TXT_MISSING", - "".$lng->txt("cont_target_missing")." [".$target_id."]".""); - } - $this->tpl->parseCurrentBlock(); - break; + case "MediaObject": + $this->tpl->setCurrentBlock("link"); + $this->tpl->setVariable("TXT_LINK_TYPE", $lng->txt("mob")); + if (ilObject::_exists($target_id)) { + $this->tpl->setVariable( + "TXT_LINK_TITLE", + ilObject::_lookupTitle($target_id) + ); + } else { + $this->tpl->setVariable( + "TXT_MISSING", + "" . $lng->txt("cont_target_missing") . " [" . $target_id . "]" . "" + ); + } + $this->tpl->parseCurrentBlock(); + break; - case "MediaObject": - $this->tpl->setCurrentBlock("link"); - $this->tpl->setVariable("TXT_LINK_TYPE", $lng->txt("mob")); - if (ilObject::_exists($target_id)) - { - $this->tpl->setVariable("TXT_LINK_TITLE", - ilObject::_lookupTitle($target_id)); - } - else - { - $this->tpl->setVariable("TXT_MISSING", - "".$lng->txt("cont_target_missing")." [".$target_id."]".""); - } - $this->tpl->parseCurrentBlock(); - break; - - case "RepositoryItem": - $this->tpl->setCurrentBlock("link"); - $this->tpl->setVariable("TXT_LINK_TYPE", $lng->txt("cont_repository_item")); - $obj_type = ilObject::_lookupType($target_id, true); - $obj_id = ilObject::_lookupObjId($target_id); - if (ilObject::_exists($obj_id)) - { - $this->tpl->setVariable("TXT_LINK_TITLE", - ilObject::_lookupTitle($obj_id)." (". - $lng->txt(("obj_".$obj_type)) - .")"); - } - else - { - $this->tpl->setVariable("TXT_MISSING", - "".$lng->txt("cont_target_missing")." [".$target_id."]".""); - } - $this->tpl->parseCurrentBlock(); - break; - - } - } - else - { - $type = $link["Type"]; - - switch($type) - { - case "PageObject": - $this->tpl->setVariable("TXT_LINK_TYPE", $lng->txt("pg")); - break; - case "StructureObject": - $this->tpl->setVariable("TXT_LINK_TYPE", $lng->txt("st")); - break; - case "GlossaryItem": - $this->tpl->setVariable("TXT_LINK_TYPE", $lng->txt("cont_term")); - break; - case "MediaObject": - $this->tpl->setVariable("TXT_LINK_TYPE", $lng->txt("mob")); - break; - case "RepositoryItem": - $this->tpl->setVariable("TXT_LINK_TYPE", $lng->txt("cont_repository_item")); - break; - } - - $this->tpl->setCurrentBlock("link"); - $this->tpl->setVariable("TXT_MISSING", - "".$lng->txt("cont_target_missing")." [".$target."]".""); - $this->tpl->parseCurrentBlock(); - } - } - } + case "RepositoryItem": + $this->tpl->setCurrentBlock("link"); + $this->tpl->setVariable("TXT_LINK_TYPE", $lng->txt("cont_repository_item")); + $obj_type = ilObject::_lookupType($target_id, true); + $obj_id = ilObject::_lookupObjId($target_id); + if (ilObject::_exists($obj_id)) { + $this->tpl->setVariable( + "TXT_LINK_TITLE", + ilObject::_lookupTitle($obj_id) . " (" . + $lng->txt(("obj_" . $obj_type)) + . ")" + ); + } else { + $this->tpl->setVariable( + "TXT_MISSING", + "" . $lng->txt("cont_target_missing") . " [" . $target_id . "]" . "" + ); + } + $this->tpl->parseCurrentBlock(); + break; + } + } else { + $type = $link["Type"]; + + switch ($type) { + case "PageObject": + $this->tpl->setVariable("TXT_LINK_TYPE", $lng->txt("pg")); + break; + case "StructureObject": + $this->tpl->setVariable("TXT_LINK_TYPE", $lng->txt("st")); + break; + case "GlossaryItem": + $this->tpl->setVariable("TXT_LINK_TYPE", $lng->txt("cont_term")); + break; + case "MediaObject": + $this->tpl->setVariable("TXT_LINK_TYPE", $lng->txt("mob")); + break; + case "RepositoryItem": + $this->tpl->setVariable("TXT_LINK_TYPE", $lng->txt("cont_repository_item")); + break; + } + + $this->tpl->setCurrentBlock("link"); + $this->tpl->setVariable( + "TXT_MISSING", + "" . $lng->txt("cont_target_missing") . " [" . $target . "]" . "" + ); + $this->tpl->parseCurrentBlock(); + } + } + } } -?> diff --git a/Modules/LearningModule/classes/class.ilObjContentObject.php b/Modules/LearningModule/classes/class.ilObjContentObject.php index aa512f188e61ea65b338fc1a646517188f76046b..29cb465e0c373a5fb0f3240d81c55e9ae95745ed 100755 --- a/Modules/LearningModule/classes/class.ilObjContentObject.php +++ b/Modules/LearningModule/classes/class.ilObjContentObject.php @@ -19,3799 +19,3613 @@ require_once "Services/MetaData/classes/class.ilMDLanguageItem.php"; */ class ilObjContentObject extends ilObject { - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilLocatorGUI - */ - protected $locator; - - var $lm_tree; - var $meta_data; - var $layout; - var $style_id; - var $pg_header; - var $online; - var $for_translation = 0; - protected $rating; - protected $rating_pages; - var $auto_glossaries = array(); - - private $import_dir = ''; - /** - * @var ilLogger - */ - protected $log; - - /** - * Constructor - * @access public - * @param integer reference_id or object_id - * @param boolean treat the id as reference_id (true) or object_id (false) - */ - function __construct($a_id = 0,$a_call_by_reference = true) - { - global $DIC; - - $this->user = $DIC->user(); - $this->db = $DIC->database(); - $this->tree = $DIC->repositoryTree(); - $this->lng = $DIC->language(); - $this->error = $DIC["ilErr"]; - if (isset($DIC["tpl"])) - { - $this->tpl = $DIC["tpl"]; - } - if (isset($DIC["ilLocator"])) - { - $this->locator = $DIC["ilLocator"]; - } - - // this also calls read() method! (if $a_id is set) - parent::__construct($a_id,$a_call_by_reference); - - $this->log = ilLoggerFactory::getLogger('lm'); - - $this->mob_ids = array(); - $this->file_ids = array(); - $this->q_ids = array(); - } - - /** - * create content object - */ - function create($a_no_meta_data = false) - { - $this->setOfflineStatus(true); - parent::create(); - - // meta data will be created by - // import parser - if (!$a_no_meta_data) - { - $this->createMetaData(); - } - - $this->createProperties(); - $this->updateAutoGlossaries(); - } - - - - /** - * read data of content object - */ - function read() - { - $ilDB = $this->db; - - parent::read(); -# echo "Content
\n"; - - $this->lm_tree = new ilTree($this->getId()); - $this->lm_tree->setTableNames('lm_tree','lm_data'); - $this->lm_tree->setTreeTablePK("lm_id"); - - $this->readProperties(); - - // read auto glossaries - $set = $ilDB->query("SELECT * FROM lm_glossaries ". - " WHERE lm_id = ".$ilDB->quote($this->getId(), "integer") - ); - $glos = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $glos[] = $rec["glo_id"]; - } - $this->setAutoGlossaries($glos); - - //parent::read(); - } - - /** - * get title of content object - * - * @return string title - */ - function getTitle() - { - return parent::getTitle(); - } - - /** - * set title of content object - */ - function setTitle($a_title) - { - parent::setTitle($a_title); -// $this->meta_data->setTitle($a_title); - } - - /** - * get description of content object - * - * @return string description - */ - function getDescription() - { - return parent::getDescription(); - } - - /** - * set description of content object - */ - function setDescription($a_description) - { - parent::setDescription($a_description); -// $this->meta_data->setDescription($a_description); - } - - - function getImportId() - { - return $this->import_id; - } - - function setImportId($a_id) - { - $this->import_id = $a_id; - } - - /** - * Set layout per page - * - * @param boolean layout per page - */ - function setLayoutPerPage($a_val) - { - $this->layout_per_page = $a_val; - } - - /** - * Get layout per page - * - * @return boolean layout per page - */ - function getLayoutPerPage() - { - return $this->layout_per_page; - } - - /** - * Set disable default feedback for questions - * - * @param bool $a_val disable default feedback - */ - function setDisableDefaultFeedback($a_val) - { - $this->disable_def_feedback = $a_val; - } - - /** - * Get disable default feedback for questions - * - * @return bool disable default feedback - */ - function getDisableDefaultFeedback() - { - return $this->disable_def_feedback; - } - - /** - * Set progress icons - * - * @param bool $a_val show progress icons - */ - function setProgressIcons($a_val) - { - $this->progr_icons = $a_val; - } - - /** - * Get progress icons - * - * @return bool show progress icons - */ - function getProgressIcons() - { - return $this->progr_icons; - } - - /** - * Set store tries - * - * @param bool $a_val store tries - */ - function setStoreTries($a_val) - { - $this->store_tries = $a_val; - } - - /** - * Get store tries - * - * @return bool store tries - */ - function getStoreTries() - { - return $this->store_tries; - } - - /** - * Set restrict forward navigation - * - * @param bool $a_val restrict forward navigation - */ - function setRestrictForwardNavigation($a_val) - { - $this->restrict_forw_nav = $a_val; - } - - /** - * Get restrict forward navigation - * - * @return bool restrict forward navigation - */ - function getRestrictForwardNavigation() - { - return $this->restrict_forw_nav; - } - - - function &getTree() - { - return $this->lm_tree; - } - - /** - * update complete object (meta data and properties) - */ - function update() - { - $this->updateMetaData(); - parent::update(); - $this->updateProperties(); - $this->updateAutoGlossaries(); - } - - /** - * Update auto glossaries - * - * @param - * @return - */ - function updateAutoGlossaries() - { - $ilDB = $this->db; - - // update auto glossaries - $ilDB->manipulate("DELETE FROM lm_glossaries WHERE ". - " lm_id = ".$ilDB->quote($this->getId(), "integer") - ); - foreach ($this->getAutoGlossaries() as $glo_id) - { - $ilDB->manipulate("INSERT INTO lm_glossaries ". - "(lm_id, glo_id) VALUES (". - $ilDB->quote($this->getId(), "integer").",". - $ilDB->quote($glo_id, "integer"). - ")"); - } - } - - - /** - * if implemented, this function should be called from an Out/GUI-Object - */ - function import() - { - // nothing to do. just display the dialogue in Out - return; - } - - - /** - * put content object in main tree - * - */ - function putInTree($a_parent) - { - $tree = $this->tree; - - // put this object in tree under $a_parent - parent::putInTree($a_parent); - - // make new tree for this object - //$tree->addTree($this->getId()); - } - - - /** - * create content object tree (that stores structure object hierarchie) - * - * todo: rename LM to ConOb - */ - function createLMTree() - { - $this->lm_tree = new ilTree($this->getId()); - $this->lm_tree->setTreeTablePK("lm_id"); - $this->lm_tree->setTableNames('lm_tree','lm_data'); - $this->lm_tree->addTree($this->getId(), 1); - } - - /** - * Set auto glossaries - * - * @param array $a_val int - */ - function setAutoGlossaries($a_val) - { - $this->auto_glossaries = array(); - if (is_array($a_val)) - { - foreach ($a_val as $v) - { - $v = (int) $v; - if ($v > 0 && ilObject::_lookupType($v) == "glo" && - !in_array($v, $this->auto_glossaries)) - { - $this->auto_glossaries[] = $v; - } - } - } - } - - /** - * Get auto glossaries - * - * @return array int - */ - function getAutoGlossaries() - { - return $this->auto_glossaries; - } - - /** - * Remove auto glossary - * - * @param - * @return - */ - function removeAutoGlossary($a_glo_id) - { - $glo_ids = array(); - foreach($this->getAutoGlossaries() as $g) - { - if ($g != $a_glo_id) - { - $glo_ids[] = $g; - } - } - $this->setAutoGlossaries($glo_ids); - } - - - /** - * Add first chapter and page - */ - function addFirstChapterAndPage() - { - $lng = $this->lng; - - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - include_once("./Modules/LearningModule/classes/class.ilStructureObject.php"); - include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); - - $root_id = $this->lm_tree->getRootId(); - - // chapter - $chap = new ilStructureObject($this); - $chap->setType("st"); - $chap->setTitle($lng->txt("cont_new_chap")); - $chap->setLMId($this->getId()); - $chap->create(); - ilLMObject::putInTree($chap, $root_id, IL_FIRST_NODE); - - // page - $page = new ilLMPageObject($this); - $page->setType("pg"); - $page->setTitle($lng->txt("cont_new_page")); - $page->setLMId($this->getId()); - $page->create(); - ilLMObject::putInTree($page, $chap->getId(), IL_FIRST_NODE); - } - - /** - * Set for translation - * - * @param bool $a_val lm has been imported for translation purposes - */ - function setForTranslation($a_val) - { - $this->for_translation = $a_val; - } - - /** - * Get for translation - * - * @return bool lm has been imported for translation purposes - */ - function getForTranslation() - { - return $this->for_translation; - } - - /** - * get content object tree - */ - function &getLMTree() - { - return $this->lm_tree; - } - - - /** - * creates data directory for import files - * (data_dir/lm_data/lm_/import, depending on data - * directory that is set in ILIAS setup/ini) - */ - function createImportDirectory() - { - $ilErr = $this->error; - - $lm_data_dir = ilUtil::getDataDir()."/lm_data"; - if(!is_writable($lm_data_dir)) - { - $ilErr->raiseError("Content object Data Directory (".$lm_data_dir - .") not writeable.", $ilErr->FATAL); - } - - // create learning module directory (data_dir/lm_data/lm_) - $lm_dir = $lm_data_dir."/lm_".$this->getId(); - ilUtil::makeDir($lm_dir); - if(!@is_dir($lm_dir)) - { - $ilErr->raiseError("Creation of Learning Module Directory failed.", $ilErr->FATAL); - } - - // create import subdirectory (data_dir/lm_data/lm_/import) - $import_dir = $lm_dir."/import"; - ilUtil::makeDir($import_dir); - if(!@is_dir($import_dir)) - { - $ilErr->raiseError("Creation of Import Directory failed.", $ilErr->FATAL); - } - } - - /** - * get data directory - */ - function getDataDirectory() - { - return ilUtil::getDataDir()."/lm_data". - "/lm_".$this->getId(); - } - - /** - * get import directory of lm - */ - function getImportDirectory() - { - if(strlen($this->import_dir)) - { - return $this->import_dir; - } - - $import_dir = ilUtil::getDataDir()."/lm_data". - "/lm_".$this->getId()."/import"; - if(@is_dir($import_dir)) - { - return $import_dir; - } - else - { - return false; - } - } - - /** - * Set import directory for further use in ilContObjParser - * - * @param string import directory - * @return void - */ - public function setImportDirectory($a_import_dir) - { - $this->import_dir = $a_import_dir; - } - - - /** - * creates data directory for export files - * (data_dir/lm_data/lm_/export, depending on data - * directory that is set in ILIAS setup/ini) - */ - function createExportDirectory($a_type = "xml") - { - $ilErr = $this->error; - - $lm_data_dir = ilUtil::getDataDir()."/lm_data"; - if(!is_writable($lm_data_dir)) - { - $ilErr->raiseError("Content object Data Directory (".$lm_data_dir - .") not writeable.", $ilErr->FATAL); - } - // create learning module directory (data_dir/lm_data/lm_) - $lm_dir = $lm_data_dir."/lm_".$this->getId(); - ilUtil::makeDir($lm_dir); - if(!@is_dir($lm_dir)) - { - $ilErr->raiseError("Creation of Learning Module Directory failed.", $ilErr->FATAL); - } - // create Export subdirectory (data_dir/lm_data/lm_/Export) - switch ($a_type) - { - // scorm - case "scorm": - $export_dir = $lm_dir."/export_scorm"; - break; - - default: // = xml - if (substr($a_type, 0, 4) == "html") - { - $export_dir = $lm_dir."/export_".$a_type; - } - else - { - $export_dir = $lm_dir."/export"; - } - break; - } - ilUtil::makeDir($export_dir); - - if(!@is_dir($export_dir)) - { - $ilErr->raiseError("Creation of Export Directory failed.", $ilErr->FATAL); - } - } - - /** - * get export directory of lm - */ - function getExportDirectory($a_type = "xml") - { - switch ($a_type) - { - case "scorm": - $export_dir = ilUtil::getDataDir()."/lm_data"."/lm_".$this->getId()."/export_scorm"; - break; - - default: // = xml - if (substr($a_type, 0, 4) == "html") - { - $export_dir = ilUtil::getDataDir()."/lm_data"."/lm_".$this->getId()."/export_".$a_type; - } - else - { - $export_dir = ilUtil::getDataDir()."/lm_data"."/lm_".$this->getId()."/export"; - } - break; - } - return $export_dir; - } - - - /** - * delete learning module and all related data - * - * this method has been tested on may 9th 2004 - * meta data, content object data, data directory, bib items - * learning module tree and pages have been deleted correctly as desired - * - * @access public - * @return boolean true if all object data were removed; false if only a references were removed - */ - function delete() - { - $ilDB = $this->db; - - // always call parent delete function first!! - if (!parent::delete()) - { - return false; - } - - // delete lm object data - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - ilLMObject::_deleteAllObjectData($this); - - // delete meta data of content object - $this->deleteMetaData(); - - - // delete learning module tree - $this->lm_tree->removeTree($this->lm_tree->getTreeId()); - - // delete data directory - ilUtil::delDir($this->getDataDirectory()); - - // delete content object record - $q = "DELETE FROM content_object WHERE id = ". - $ilDB->quote($this->getId(), "integer"); - $ilDB->manipulate($q); - - // delete lm menu entries - $q = "DELETE FROM lm_menu WHERE lm_id = ". - $ilDB->quote($this->getId(), "integer"); - $ilDB->manipulate($q); - - // remove auto glossary entries - $ilDB->manipulate("DELETE FROM lm_glossaries WHERE ". - " lm_id = ".$ilDB->quote($this->getId(), "integer") - ); - - - return true; - } - - - /** - * get default page layout of content object (see directory layouts/) - * - * @return string default layout - */ - function getLayout() - { - return $this->layout; - } - - /** - * set default page layout - * - * @param string $a_layout default page layout - */ - function setLayout($a_layout) - { - $this->layout = $a_layout; - } - - /** - * get ID of assigned style sheet object - */ - function getStyleSheetId() - { - return $this->style_id; - } - - /** - * set ID of assigned style sheet object - */ - function setStyleSheetId($a_style_id) - { - $this->style_id = $a_style_id; - } - - /** - * write ID of assigned style sheet object to db - */ - function writeStyleSheetId($a_style_id) - { - $ilDB = $this->db; - - $q = "UPDATE content_object SET ". - " stylesheet = ".$ilDB->quote((int) $a_style_id, "integer"). - " WHERE id = ".$ilDB->quote($this->getId(), "integer"); - $ilDB->manipulate($q); - - $this->style_id = $a_style_id; - } - - /** - * Write header page - * - * @param int $a_lm_id learning module id - * @param int $a_page_id page - */ - static function writeHeaderPage($a_lm_id, $a_page_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $ilDB->manipulate("UPDATE content_object SET ". - " header_page = ".$ilDB->quote($a_page_id, "integer"). - " WHERE id = ".$ilDB->quote($a_lm_id, "integer") - ); - } - - /** - * Write footer page - * - * @param int $a_lm_id learning module id - * @param int $a_page_id page - */ - static function writeFooterPage($a_lm_id, $a_page_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $ilDB->manipulate("UPDATE content_object SET ". - " footer_page = ".$ilDB->quote($a_page_id, "integer"). - " WHERE id = ".$ilDB->quote($a_lm_id, "integer") - ); - } - - - /** - * move learning modules from one style to another - */ - static function _moveLMStyles($a_from_style, $a_to_style) - { - global $DIC; - - $ilDB = $DIC->database(); - - if ($a_from_style < 0) // change / delete all individual styles - { - $q = "SELECT stylesheet FROM content_object, style_data ". - " WHERE content_object.stylesheet = style_data.id ". - " AND style_data.standard = ".$ilDB->quote(0, "integer"). - " AND content_object.stylesheet > ".$ilDB->quote(0, "integer"); - $style_set = $ilDB->query($q); - while($style_rec = $ilDB->fetchAssoc($style_set)) - { - // assign learning modules to new style - $q = "UPDATE content_object SET ". - " stylesheet = ".$ilDB->quote((int) $a_to_style, "integer"). - " WHERE stylesheet = ".$ilDB->quote($style_rec["stylesheet"], "integer"); - $ilDB->manipulate($q); - - // delete style - $style_obj = ilObjectFactory::getInstanceByObjId($style_rec["stylesheet"]); - $style_obj->delete(); - } - } - else - { - $q = "UPDATE content_object SET ". - " stylesheet = ".$ilDB->quote((int) $a_to_style, "integer"). - " WHERE stylesheet = ".$ilDB->quote($a_from_style, "integer"); - $ilDB->manipulate($q); - } - } - - /** - * Lookup property - * - * @param int $a_obj_id object id - * @param string $a_field property field name - * @return string property value - */ - static protected function _lookup($a_obj_id, $a_field) - { - global $DIC; - - $ilDB = $DIC->database(); - $ilLog = $DIC["ilLog"]; - - $q = "SELECT ".$a_field." FROM content_object ". - " WHERE id = ".$ilDB->quote($a_obj_id, "integer"); - - $res = $ilDB->query($q); - $rec = $ilDB->fetchAssoc($res); - - return $rec[$a_field]; - } - - /** - * Lookup forward restriction navigation - * - * @param int $a_obj_id object id - * @return string property value - */ - static function _lookupRestrictForwardNavigation($a_obj_id) - { - return self::_lookup($a_obj_id, "restrict_forw_nav"); - } - - /** - * lookup style sheet ID - */ - static function _lookupStyleSheetId($a_cont_obj_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "SELECT stylesheet FROM content_object ". - " WHERE id = ".$ilDB->quote($a_cont_obj_id, "integer"); - $res = $ilDB->query($q); - $sheet = $ilDB->fetchAssoc($res); - - return $sheet["stylesheet"]; - } - - /** - * lookup style sheet ID - */ - static function _lookupContObjIdByStyleId($a_style_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "SELECT id FROM content_object ". - " WHERE stylesheet = ".$ilDB->quote($a_style_id, "integer"); - $res = $ilDB->query($q); - $obj_ids = array(); - while($cont = $ilDB->fetchAssoc($res)) - { - $obj_ids[] = $cont["id"]; - } - return $obj_ids; - } - - /** - * Lookup disable default feedback - */ - static function _lookupDisableDefaultFeedback($a_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "SELECT disable_def_feedback FROM content_object ". - " WHERE id = ".$ilDB->quote($a_id, "integer"); - $res = $ilDB->query($q); - $rec = $ilDB->fetchAssoc($res); - - return $rec["disable_def_feedback"]; - } - - /** - * Lookup disable default feedback - */ - static function _lookupStoreTries($a_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "SELECT store_tries FROM content_object ". - " WHERE id = ".$ilDB->quote($a_id, "integer"); - $res = $ilDB->query($q); - $rec = $ilDB->fetchAssoc($res); - - return $rec["store_tries"]; - } - - - /** - * gets the number of learning modules assigned to a content style - * - * @param int $a_style_id style id - */ - static function _getNrOfAssignedLMs($a_style_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "SELECT count(*) as cnt FROM content_object ". - " WHERE stylesheet = ".$ilDB->quote($a_style_id, "integer"); - $cset = $ilDB->query($q); - $crow = $ilDB->fetchAssoc($cset); - - return (int) $crow["cnt"]; - } - - - /** - * get number of learning modules with individual styles - */ - static function _getNrLMsIndividualStyles() - { - global $DIC; - - $ilDB = $DIC->database(); - - // joining with style table (not perfectly nice) - $q = "SELECT count(*) as cnt FROM content_object, style_data ". - " WHERE stylesheet = style_data.id ". - " AND standard = ".$ilDB->quote(0, "integer"); - $cset = $ilDB->query($q); - $crow = $ilDB->fetchAssoc($cset); - - return (int) $crow["cnt"]; - } - - /** - * get number of learning modules assigned no style - */ - static function _getNrLMsNoStyle() - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "SELECT count(*) as cnt FROM content_object ". - " WHERE stylesheet = ".$ilDB->quote(0, "integer"); - $cset = $ilDB->query($q); - $crow = $ilDB->fetchAssoc($cset); - - return (int) $crow["cnt"]; - } - - /** - * delete all style references to style - * - * @param int $a_style_id style_id - */ - static function _deleteStyleAssignments($a_style_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "UPDATE content_object SET ". - " stylesheet = ".$ilDB->quote(0, "integer"). - " WHERE stylesheet = ".$ilDB->quote((int) $a_style_id, "integer"); - - $ilDB->manipulate($q); - } - - /** - * get page header mode (IL_CHAPTER_TITLE | IL_PAGE_TITLE | IL_NO_HEADER) - */ - function getPageHeader() - { - return $this->pg_header; - } - - /** - * set page header mode - * - * @param string $a_pg_header IL_CHAPTER_TITLE | IL_PAGE_TITLE | IL_NO_HEADER - */ - function setPageHeader($a_pg_header = IL_CHAPTER_TITLE) - { - $this->pg_header = $a_pg_header; - } - - /** - * get toc mode ("chapters" | "pages") - */ - function getTOCMode() - { - return $this->toc_mode; - } - - /** - * get public access mode ("complete" | "selected") - */ - function getPublicAccessMode() - { - return $this->public_access_mode; - } - - /** - * set toc mode - * - * @param string $a_toc_mode "chapters" | "pages" - */ - function setTOCMode($a_toc_mode = "chapters") - { - $this->toc_mode = $a_toc_mode; - } - - function setActiveLMMenu($a_act_lm_menu) - { - $this->lm_menu_active = $a_act_lm_menu; - } - - function isActiveLMMenu() - { - return $this->lm_menu_active; - } - - function setActiveTOC($a_toc) - { - $this->toc_active = $a_toc; - } - - function isActiveTOC() - { - return $this->toc_active; - } - - function setActiveNumbering($a_num) - { - $this->numbering = $a_num; - } - - function isActiveNumbering() - { - return $this->numbering; - } - - function setActivePrintView($a_print) - { - $this->print_view_active = $a_print; - } - - function isActivePrintView() - { - return $this->print_view_active; - } - - function setActivePreventGlossaryAppendix($a_print) - { - $this->prevent_glossary_appendix_active = $a_print; - } - - function isActivePreventGlossaryAppendix() - { - return $this->prevent_glossary_appendix_active; - } - - /** - * Set hide header footer in print mode - * - * @param bool $a_val hide header and footer? - */ - function setHideHeaderFooterPrint($a_val) - { - $this->hide_header_footer_print = $a_val; - } - - /** - * Get hide header footer in print mode - * - * @return bool hide header and footer? - */ - function getHideHeaderFooterPrint() - { - return $this->hide_header_footer_print; - } - - function setActiveDownloads($a_down) - { - $this->downloads_active = $a_down; - } - - function isActiveDownloads() - { - return $this->downloads_active; - } - - function setActiveDownloadsPublic($a_down) - { - $this->downloads_public_active = $a_down; - } - - function isActiveDownloadsPublic() - { - return $this->downloads_public_active; - } - - function setPublicNotes($a_pub_notes) - { - $this->pub_notes = $a_pub_notes; - } - - function publicNotes() - { - return $this->pub_notes; - } - - function setCleanFrames($a_clean) - { - $this->clean_frames = $a_clean; - } - - function cleanFrames() - { - return $this->clean_frames; - } - - function setHistoryUserComments($a_comm) - { - $this->user_comments = $a_comm; - } - - function setPublicAccessMode($a_mode) - { - $this->public_access_mode = $a_mode; - } - - function isActiveHistoryUserComments() - { - return $this->user_comments; - } - - function setHeaderPage($a_pg) - { - $this->header_page = $a_pg; - } - - function getHeaderPage() - { - return $this->header_page; - } - - function setFooterPage($a_pg) - { - $this->footer_page = $a_pg; - } - - function getFooterPage() - { - return $this->footer_page; - } - - /** - * read content object properties - */ - function readProperties() - { - $ilDB = $this->db; - - $q = "SELECT * FROM content_object WHERE id = ". - $ilDB->quote($this->getId(), "integer"); - $lm_set = $ilDB->query($q); - $lm_rec = $ilDB->fetchAssoc($lm_set); - $this->setLayout($lm_rec["default_layout"]); - $this->setStyleSheetId((int) $lm_rec["stylesheet"]); - $this->setPageHeader($lm_rec["page_header"]); - $this->setTOCMode($lm_rec["toc_mode"]); - $this->setActiveTOC(ilUtil::yn2tf($lm_rec["toc_active"])); - $this->setActiveNumbering(ilUtil::yn2tf($lm_rec["numbering"])); - $this->setActivePrintView(ilUtil::yn2tf($lm_rec["print_view_active"])); - $this->setActivePreventGlossaryAppendix(ilUtil::yn2tf($lm_rec["no_glo_appendix"])); - $this->setHideHeaderFooterPrint($lm_rec["hide_head_foot_print"]); - $this->setActiveDownloads(ilUtil::yn2tf($lm_rec["downloads_active"])); - $this->setActiveDownloadsPublic(ilUtil::yn2tf($lm_rec["downloads_public_active"])); - $this->setActiveLMMenu(ilUtil::yn2tf($lm_rec["lm_menu_active"])); - $this->setCleanFrames(ilUtil::yn2tf($lm_rec["clean_frames"])); - $this->setHeaderPage((int) $lm_rec["header_page"]); - $this->setFooterPage((int) $lm_rec["footer_page"]); - $this->setHistoryUserComments(ilUtil::yn2tf($lm_rec["hist_user_comments"])); - $this->setPublicAccessMode($lm_rec["public_access_mode"]); - $this->setPublicExportFile("xml", $lm_rec["public_xml_file"]); - $this->setPublicExportFile("html", $lm_rec["public_html_file"]); - $this->setPublicExportFile("scorm", $lm_rec["public_scorm_file"]); - $this->setLayoutPerPage($lm_rec["layout_per_page"]); - $this->setRating($lm_rec["rating"]); - $this->setRatingPages($lm_rec["rating_pages"]); - $this->setDisableDefaultFeedback($lm_rec["disable_def_feedback"]); - $this->setProgressIcons($lm_rec["progr_icons"]); - $this->setStoreTries($lm_rec["store_tries"]); - $this->setRestrictForwardNavigation($lm_rec["restrict_forw_nav"]); - - // #14661 - include_once("./Services/Notes/classes/class.ilNote.php"); - $this->setPublicNotes(ilNote::commentsActivated($this->getId(), 0, $this->getType())); - - $this->setForTranslation($lm_rec["for_translation"]); - } - - /** - * Update content object properties - */ - function updateProperties() - { - $ilDB = $this->db; - - // force clean_frames to be set, if layout per page is activated - if ($this->getLayoutPerPage()) - { - $this->setCleanFrames(true); - } - - $q = "UPDATE content_object SET ". - " default_layout = ".$ilDB->quote($this->getLayout(), "text").", ". - " stylesheet = ".$ilDB->quote($this->getStyleSheetId(), "integer").",". - " page_header = ".$ilDB->quote($this->getPageHeader(), "text").",". - " toc_mode = ".$ilDB->quote($this->getTOCMode(), "text").",". - " toc_active = ".$ilDB->quote(ilUtil::tf2yn($this->isActiveTOC()), "text").",". - " numbering = ".$ilDB->quote(ilUtil::tf2yn($this->isActiveNumbering()), "text").",". - " print_view_active = ".$ilDB->quote(ilUtil::tf2yn($this->isActivePrintView()), "text").",". - " no_glo_appendix = ".$ilDB->quote(ilUtil::tf2yn($this->isActivePreventGlossaryAppendix()), "text").",". - " hide_head_foot_print = ".$ilDB->quote($this->getHideHeaderFooterPrint(), "integer").",". - " downloads_active = ".$ilDB->quote(ilUtil::tf2yn($this->isActiveDownloads()), "text").",". - " downloads_public_active = ".$ilDB->quote(ilUtil::tf2yn($this->isActiveDownloadsPublic()), "text").",". - " clean_frames = ".$ilDB->quote(ilUtil::tf2yn($this->cleanFrames()), "text").",". - " hist_user_comments = ".$ilDB->quote(ilUtil::tf2yn($this->isActiveHistoryUserComments()), "text").",". - " public_access_mode = ".$ilDB->quote($this->getPublicAccessMode(), "text").",". - " public_xml_file = ".$ilDB->quote($this->getPublicExportFile("xml"), "text").",". - " public_html_file = ".$ilDB->quote($this->getPublicExportFile("html"), "text").",". - " public_scorm_file = ".$ilDB->quote($this->getPublicExportFile("scorm"), "text").",". - " header_page = ".$ilDB->quote($this->getHeaderPage(), "integer").",". - " footer_page = ".$ilDB->quote($this->getFooterPage(), "integer").",". - " lm_menu_active = ".$ilDB->quote(ilUtil::tf2yn($this->isActiveLMMenu()), "text").", ". - " layout_per_page = ".$ilDB->quote($this->getLayoutPerPage(), "integer").", ". - " rating = ".$ilDB->quote($this->hasRating(), "integer").", ". - " rating_pages = ".$ilDB->quote($this->hasRatingPages(), "integer").", ". - " disable_def_feedback = ".$ilDB->quote($this->getDisableDefaultFeedback(), "integer").", ". - " progr_icons = ".$ilDB->quote($this->getProgressIcons(), "integer").", ". - " store_tries = ".$ilDB->quote($this->getStoreTries(), "integer").", ". - " restrict_forw_nav = ".$ilDB->quote($this->getRestrictForwardNavigation(), "integer").", ". - " for_translation = ".$ilDB->quote((int) $this->getForTranslation(), "integer")." ". - " WHERE id = ".$ilDB->quote($this->getId(), "integer"); - $ilDB->manipulate($q); - // #14661 - include_once("./Services/Notes/classes/class.ilNote.php"); - ilNote::activateComments($this->getId(), 0, $this->getType(), $this->publicNotes()); - } - - /** - * create new properties record - */ - function createProperties() - { - $ilDB = $this->db; - - $q = "INSERT INTO content_object (id) VALUES (".$ilDB->quote($this->getId(), "integer").")"; - $ilDB->manipulate($q); - - // #14661 - include_once("./Services/Notes/classes/class.ilNote.php"); - ilNote::activateComments($this->getId(), 0, $this->getType(), true); - - $this->readProperties(); // to get db default values - } - - - /** - * get all available lm layouts - */ - static function getAvailableLayouts() - { - $dir = opendir("./Modules/LearningModule/layouts/lm"); - - $layouts = array(); - - while($file = readdir($dir)) - { - if ($file != "." && $file != ".." && $file != "CVS" && $file != ".svn") - { - // directories - if (@is_dir("./Modules/LearningModule/layouts/lm/".$file)) - { - $layouts[$file] = $file; - } - } - } - asort($layouts); - - // workaround: fix ordering - $ret = array( - 'toc2win' => 'toc2win', - 'toc2windyn' => 'toc2windyn', - '1window' => '1window', - '2window' => '2window', - '3window' => '3window', - 'presentation' => 'presentation', - 'fullscreen' => 'fullscreen' - ); - - foreach ($layouts as $l) - { - if (!in_array($l, $ret)) - { - $ret[$l] = $l; - } - } - - return $ret; - } - - /** - * checks wether the preconditions of a page are fulfilled or not - */ - static function _checkPreconditionsOfPage($cont_ref_id,$cont_obj_id, $page_id) - { - global $DIC; - - $ilUser = $DIC->user(); - $ilErr = $DIC["ilErr"]; - - $lm_tree = new ilTree($cont_obj_id); - $lm_tree->setTableNames('lm_tree','lm_data'); - $lm_tree->setTreeTablePK("lm_id"); - - if ($lm_tree->isInTree($page_id)) - { - $path = $lm_tree->getPathFull($page_id, $lm_tree->readRootId()); - foreach ($path as $node) - { - if ($node["type"] == "st") - { - if (!ilConditionHandler::_checkAllConditionsOfTarget($cont_ref_id,$node["child"], "st")) - { - return false; - } - } - } - } - - return true; - } - - /** - * gets all missing preconditions of page - */ - static function _getMissingPreconditionsOfPage($cont_ref_id,$cont_obj_id, $page_id) - { - $lm_tree = new ilTree($cont_obj_id); - $lm_tree->setTableNames('lm_tree','lm_data'); - $lm_tree->setTreeTablePK("lm_id"); - - $conds = array(); - if ($lm_tree->isInTree($page_id)) - { - // get full path of page - $path = $lm_tree->getPathFull($page_id, $lm_tree->readRootId()); - foreach ($path as $node) - { - if ($node["type"] == "st") - { - // get all preconditions of upper chapters - $tconds = ilConditionHandler::_getPersistedConditionsOfTarget($cont_ref_id,$node["child"], "st"); - foreach ($tconds as $tcond) - { - // store all missing preconditions - if (!ilConditionHandler::_checkCondition($tcond)) - { - $conds[] = $tcond; - } - } - } - } - } - - return $conds; - } - - /** - * get top chapter of page for that any precondition is missing - */ - static function _getMissingPreconditionsTopChapter($cont_obj_ref_id,$cont_obj_id, $page_id) - { - $lm_tree = new ilTree($cont_obj_id); - $lm_tree->setTableNames('lm_tree','lm_data'); - $lm_tree->setTreeTablePK("lm_id"); - - $conds = array(); - if ($lm_tree->isInTree($page_id)) - { - // get full path of page - $path = $lm_tree->getPathFull($page_id, $lm_tree->readRootId()); - foreach ($path as $node) - { - if ($node["type"] == "st") - { - // get all preconditions of upper chapters - $tconds = ilConditionHandler::_getPersistedConditionsOfTarget($cont_obj_ref_id,$node["child"], "st"); - foreach ($tconds as $tcond) - { - // look for missing precondition - if (!ilConditionHandler::_checkCondition($tcond)) - { - return $node["child"]; - } - } - } - } - } - - return ""; - } - - /** - * checks if page has a successor page - */ - static function hasSuccessorPage($a_cont_obj_id, $a_page_id) - { - $tree = new ilTree($a_cont_obj_id); - $tree->setTableNames('lm_tree','lm_data'); - $tree->setTreeTablePK("lm_id"); - if ($tree->isInTree($a_page_id)) - { - $succ = $tree->fetchSuccessorNode($a_page_id, "pg"); - if ($succ > 0) - { - return true; - } - } - return false; - } - - - function checkTree() - { - $tree = new ilTree($this->getId()); - $tree->setTableNames('lm_tree','lm_data'); - $tree->setTreeTablePK("lm_id"); - $tree->checkTree(); - $tree->checkTreeChilds(); -//echo "checked"; - } - - /** - * fix tree - */ - function fixTree() - { - $ilDB = $this->db; - - $tree = $this->getLMTree(); - - // check numbering, if errors, renumber - // it is very important to keep this step before deleting subtrees - // in the following steps - $set = $ilDB->query("SELECT DISTINCT l1.lm_id". - " FROM lm_tree l1". - " JOIN lm_tree l2 ON ( l1.child = l2.parent". - " AND l1.lm_id = l2.lm_id )". - " JOIN lm_data ON ( l1.child = lm_data.obj_id )". - " WHERE (l2.lft < l1.lft". - " OR l2.rgt > l1.rgt OR l2.lft > l1.rgt OR l2.rgt < l1.lft)". - " AND l1.lm_id = ".$ilDB->quote($this->getId(), "integer"). - " ORDER BY lm_data.create_date DESC" - ); - if ($rec = $ilDB->fetchAssoc($set)) - { - $tree->renumber(); - } - - // delete subtrees that have no lm_data records (changed due to #20637) - $set = $ilDB->query("SELECT * FROM lm_tree WHERE lm_tree.lm_id = ".$ilDB->quote($this->getId(), "integer")); - while ($node = $ilDB->fetchAssoc($set)) - { - $q = "SELECT * FROM lm_data WHERE obj_id = ". - $ilDB->quote($node["child"], "integer"); - $obj_set = $ilDB->query($q); - $obj_rec = $ilDB->fetchAssoc($obj_set); - if (!$obj_rec) - { - $node_data = $tree->getNodeData($node["child"]); - $node_data["child"] = $node["child"]; - $tree->deleteTree($node_data); - } - } - - // delete subtrees that have pages as parent - $nodes = $tree->getSubtree($tree->getNodeData($tree->getRootId())); - foreach ($nodes as $node) - { - $q = "SELECT * FROM lm_data WHERE obj_id = ". - $ilDB->quote($node["parent"], "integer"); - $obj_set = $ilDB->query($q); - $obj_rec = $ilDB->fetchAssoc($obj_set); - if ($obj_rec["type"] == "pg") - { - $node_data = $tree->getNodeData($node["child"]); - if ($tree->isInTree($node["child"])) - { - $tree->deleteTree($node_data); - } - } - } - - // check for multi-references pages or chapters - // if errors -> create copies of them here - $set = $ilDB->query("SELECT DISTINCT l1.lm_id". - " FROM lm_tree l1". - " JOIN lm_tree l2 ON ( l1.child = l2.child AND l1.lm_id <> l2.lm_id )". - " JOIN lm_data ON (l1.child = lm_data.obj_id)". - " WHERE l1.child <> 1". - " AND l1.lm_id <> lm_data.lm_id". - " AND l1.lm_id = ".$ilDB->quote($this->getId(), "integer")); - if ($rec = $ilDB->fetchAssoc($set)) - { - $set = $ilDB->query("SELECT DISTINCT l1.child ". - " FROM lm_tree l1". - " JOIN lm_tree l2 ON ( l1.child = l2.child AND l1.lm_id <> l2.lm_id )". - " JOIN lm_data ON (l1.child = lm_data.obj_id)". - " WHERE l1.child <> 1". - " AND l1.lm_id <> lm_data.lm_id". - " AND l1.lm_id = ".$ilDB->quote($this->getId(), "integer")); - include_once("./Modules/LearningModule/classes/class.ilLMObjectFactory.php"); - while ($rec = $ilDB->fetchAssoc($set)) - { - $cobj = ilLMObjectFactory::getInstance($this, $rec["child"]); - - if (is_object($cobj)) - { - if ($cobj->getType() == "pg") - { - // make a copy of it - $pg_copy = $cobj->copy($this); - - // replace the child in the tree with the copy (id) - $ilDB->manipulate("UPDATE lm_tree SET ". - " child = ".$ilDB->quote($pg_copy->getId(), "integer"). - " WHERE child = ".$ilDB->quote($cobj->getId(), "integer"). - " AND lm_id = ".$ilDB->quote($this->getId(), "integer") - ); - } - else if ($cobj->getType() == "st") - { - // make a copy of it - $st_copy = $cobj->copy($this); - - // replace the child in the tree with the copy (id) - $ilDB->manipulate("UPDATE lm_tree SET ". - " child = ".$ilDB->quote($st_copy->getId(), "integer"). - " WHERE child = ".$ilDB->quote($cobj->getId(), "integer"). - " AND lm_id = ".$ilDB->quote($this->getId(), "integer") - ); - - // make all childs refer to the copy now - $ilDB->manipulate("UPDATE lm_tree SET ". - " parent = ".$ilDB->quote($st_copy->getId(), "integer"). - " WHERE parent = ".$ilDB->quote($cobj->getId(), "integer"). - " AND lm_id = ".$ilDB->quote($this->getId(), "integer") - ); - } - } - } - } - - // missing copage entries - $set = $ilDB->queryF("SELECT * FROM lm_data ". - " WHERE lm_id = %s AND type = %s", - array("integer", "text"), - array($this->getId(), "pg") - ); - while ($rec = $ilDB->fetchAssoc($set)) - { - if (!ilPageObject::_exists("lm", $rec["obj_id"], "-")) { - $lm_page = new ilLMPage(); - $lm_page->setId($rec["obj_id"]); - $lm_page->setParentId($this->getId()); - $lm_page->create(); - } - } - - } - - /** - * Check tree (this has been copied from fixTree due to a bug fixing, should be reorganised) - */ - function checkStructure() - { - $issues = []; - $ilDB = $this->db; - - $tree = $this->getLMTree(); - - // check numbering, if errors, renumber - // it is very important to keep this step before deleting subtrees - // in the following steps - $set = $ilDB->query("SELECT l1.child, l1.lft l1lft, l1.rgt l1rgt, l2.parent, l2.lft l2lft, l2.rgt l2rgt". - " FROM lm_tree l1". - " JOIN lm_tree l2 ON ( l1.child = l2.parent". - " AND l1.lm_id = l2.lm_id )". - " JOIN lm_data ON ( l1.child = lm_data.obj_id )". - " WHERE (l2.lft < l1.lft". - " OR l2.rgt > l1.rgt OR l2.lft > l1.rgt OR l2.rgt < l1.lft)". - " AND l1.lm_id = ".$ilDB->quote($this->getId(), "integer"). - " ORDER BY lm_data.create_date DESC" - ); - while ($rec = $ilDB->fetchAssoc($set)) - { - $issues[] = "Tree numbering: ".print_r($rec, true); - } - - // delete subtrees that have no lm_data records (changed due to #20637) - $set = $ilDB->query("SELECT * FROM lm_tree WHERE lm_tree.lm_id = ".$ilDB->quote($this->getId(), "integer")); - while ($node = $ilDB->fetchAssoc($set)) - { - $q = "SELECT * FROM lm_data WHERE obj_id = ". - $ilDB->quote($node["child"], "integer"); - $obj_set = $ilDB->query($q); - $obj_rec = $ilDB->fetchAssoc($obj_set); - if (!$obj_rec) - { - $issues[] = "Tree entry without data entry: ".print_r($node, true); - } - } - - // delete subtrees that have pages as parent - $nodes = $tree->getSubtree($tree->getNodeData($tree->getRootId())); - foreach ($nodes as $node) - { - $q = "SELECT * FROM lm_data WHERE obj_id = ". - $ilDB->quote($node["parent"], "integer"); - $obj_set = $ilDB->query($q); - $obj_rec = $ilDB->fetchAssoc($obj_set); - if ($obj_rec["type"] == "pg") - { - $node_data = $tree->getNodeData($node["child"]); - if ($tree->isInTree($node["child"])) - { - $issues[] = "Subtree with page parent: ".print_r($node_data, true); - } - } - } - - // check for multi-references pages or chapters - // if errors -> create copies of them here - $set = $ilDB->query("SELECT DISTINCT l1.lm_id". - " FROM lm_tree l1". - " JOIN lm_tree l2 ON ( l1.child = l2.child AND l1.lm_id <> l2.lm_id )". - " JOIN lm_data ON (l1.child = lm_data.obj_id)". - " WHERE l1.child <> 1". - " AND l1.lm_id <> lm_data.lm_id". - " AND l1.lm_id = ".$ilDB->quote($this->getId(), "integer")); - if ($rec = $ilDB->fetchAssoc($set)) - { - $set = $ilDB->query("SELECT DISTINCT l1.child ". - " FROM lm_tree l1". - " JOIN lm_tree l2 ON ( l1.child = l2.child AND l1.lm_id <> l2.lm_id )". - " JOIN lm_data ON (l1.child = lm_data.obj_id)". - " WHERE l1.child <> 1". - " AND l1.lm_id <> lm_data.lm_id". - " AND l1.lm_id = ".$ilDB->quote($this->getId(), "integer")); - include_once("./Modules/LearningModule/classes/class.ilLMObjectFactory.php"); - while ($rec = $ilDB->fetchAssoc($set)) - { - $set3 = $ilDB->queryF("SELECT * FROM lm_tree ". - " WHERE child = %s ", - array("integer"), - array($rec["child"]) - ); - while ($rec3 = $ilDB->fetchAssoc($set3)) - { - $issues[] = "Multi-reference item: ".print_r($rec3, true); - } - } - } - - // missing copage entries - $set = $ilDB->queryF("SELECT * FROM lm_data ". - " WHERE lm_id = %s AND type = %s", - array("integer", "text"), - array($this->getId(), "pg") - ); - while ($rec = $ilDB->fetchAssoc($set)) - { - if (!ilPageObject::_exists("lm", $rec["obj_id"], "-")) { - $issues[] = "Missing COPage: ".print_r($rec, true); - } - } - - - return $issues; - } - - /** - * export object to xml (see ilias_co.dtd) - * - * @param object $a_xml_writer ilXmlWriter object that receives the - * xml data - */ - function exportXML(&$a_xml_writer, $a_inst, $a_target_dir, &$expLog) - { - $attrs = array(); - switch($this->getType()) - { - case "lm": - $attrs["Type"] = "LearningModule"; - break; - } - $a_xml_writer->xmlStartTag("ContentObject", $attrs); - - // MetaData - $this->exportXMLMetaData($a_xml_writer); - - // StructureObjects -//echo "ContObj:".$a_inst.":
"; - $expLog->write(date("[y-m-d H:i:s] ")."Start Export Structure Objects"); - $this->exportXMLStructureObjects($a_xml_writer, $a_inst, $expLog); - $expLog->write(date("[y-m-d H:i:s] ")."Finished Export Structure Objects"); - - // PageObjects - $expLog->write(date("[y-m-d H:i:s] ")."Start Export Page Objects"); - $this->exportXMLPageObjects($a_xml_writer, $a_inst, $expLog); - $expLog->write(date("[y-m-d H:i:s] ")."Finished Export Page Objects"); - - // MediaObjects - $expLog->write(date("[y-m-d H:i:s] ")."Start Export Media Objects"); - $this->exportXMLMediaObjects($a_xml_writer, $a_inst, $a_target_dir, $expLog); - $expLog->write(date("[y-m-d H:i:s] ")."Finished Export Media Objects"); - - // FileItems - $expLog->write(date("[y-m-d H:i:s] ")."Start Export File Items"); - $this->exportFileItems($a_target_dir, $expLog); - $expLog->write(date("[y-m-d H:i:s] ")."Finished Export File Items"); - - // Questions - if (count($this->q_ids) > 0) - { - $qti_file = fopen($a_target_dir."/qti.xml", "w"); - include_once("./Modules/TestQuestionPool/classes/class.ilObjQuestionPool.php"); - $pool = new ilObjQuestionPool(); - fwrite($qti_file, $pool->questionsToXML($this->q_ids)); - fclose($qti_file); - } - - // To do: implement version selection/detection - // Properties - $expLog->write(date("[y-m-d H:i:s] ")."Start Export Properties"); - $this->exportXMLProperties($a_xml_writer, $expLog); - $expLog->write(date("[y-m-d H:i:s] ")."Finished Export Properties"); - - $a_xml_writer->xmlEndTag("ContentObject"); - } - - /** - * export content objects meta data to xml (see ilias_co.dtd) - * - * @param object $a_xml_writer ilXmlWriter object that receives the - * xml data - */ - function exportXMLMetaData(&$a_xml_writer) - { - include_once("Services/MetaData/classes/class.ilMD2XML.php"); - $md2xml = new ilMD2XML($this->getId(), 0, $this->getType()); - $md2xml->setExportMode(true); - $md2xml->startExport(); - $a_xml_writer->appendXML($md2xml->getXML()); - } - - /** - * export structure objects to xml (see ilias_co.dtd) - * - * @param object $a_xml_writer ilXmlWriter object that receives the - * xml data - */ - function exportXMLStructureObjects(&$a_xml_writer, $a_inst, &$expLog) - { - include_once './Modules/LearningModule/classes/class.ilStructureObject.php'; - - $childs = $this->lm_tree->getChilds($this->lm_tree->getRootId()); - foreach ($childs as $child) - { - if($child["type"] != "st") - { - continue; - } - - $structure_obj = new ilStructureObject($this, $child["obj_id"]); - $structure_obj->exportXML($a_xml_writer, $a_inst, $expLog); - unset($structure_obj); - } - } - - - /** - * export page objects to xml (see ilias_co.dtd) - * - * @param object $a_xml_writer ilXmlWriter object that receives the - * xml data - */ - function exportXMLPageObjects(&$a_xml_writer, $a_inst, &$expLog) - { - include_once "./Modules/LearningModule/classes/class.ilLMPageObject.php"; - include_once "./Modules/LearningModule/classes/class.ilLMPage.php"; - - $pages = ilLMPageObject::getPageList($this->getId()); - foreach ($pages as $page) - { - if (ilLMPage::_exists($this->getType(), $page["obj_id"])) - { - $expLog->write(date("[y-m-d H:i:s] ")."Page Object ".$page["obj_id"]); - - // export xml to writer object - $page_obj = new ilLMPageObject($this, $page["obj_id"]); - $page_obj->exportXML($a_xml_writer, "normal", $a_inst); - - // collect media objects - $mob_ids = $page_obj->getMediaObjectIDs(); - foreach($mob_ids as $mob_id) - { - $this->mob_ids[$mob_id] = $mob_id; - } - - // collect all file items - $file_ids = $page_obj->getFileItemIds(); - foreach($file_ids as $file_id) - { - $this->file_ids[$file_id] = $file_id; - } - - // collect all questions - $q_ids = $page_obj->getQuestionIds(); - foreach($q_ids as $q_id) - { - $this->q_ids[$q_id] = $q_id; - } - - unset($page_obj); - } - } - } - - /** - * export media objects to xml (see ilias_co.dtd) - * - * @param object $a_xml_writer ilXmlWriter object that receives the - * xml data - */ - function exportXMLMediaObjects(&$a_xml_writer, $a_inst, $a_target_dir, &$expLog) - { - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - - $linked_mobs = array(); - - // mobs directly embedded into pages - foreach ($this->mob_ids as $mob_id) - { - if ($mob_id > 0 && ilObject::_lookupType($mob_id) == "mob") - { - $expLog->write(date("[y-m-d H:i:s] ")."Media Object ".$mob_id); - $media_obj = new ilObjMediaObject($mob_id); - $media_obj->exportXML($a_xml_writer, $a_inst); - $media_obj->exportFiles($a_target_dir); - - $lmobs = $media_obj->getLinkedMediaObjects($this->mob_ids); - $linked_mobs = array_merge($linked_mobs, $lmobs); - - unset($media_obj); - } - } - - // linked mobs (in map areas) - foreach ($linked_mobs as $mob_id) - { - if ($mob_id > 0) - { - $expLog->write(date("[y-m-d H:i:s] ")."Media Object ".$mob_id); - $media_obj = new ilObjMediaObject($mob_id); - $media_obj->exportXML($a_xml_writer, $a_inst); - $media_obj->exportFiles($a_target_dir); - unset($media_obj); - } - } - - } - - /** - * export files of file itmes - * - */ - function exportFileItems($a_target_dir, &$expLog) - { - include_once("./Modules/File/classes/class.ilObjFile.php"); - - foreach ($this->file_ids as $file_id) - { - $expLog->write(date("[y-m-d H:i:s] ")."File Item ".$file_id); - $file_obj = new ilObjFile($file_id, false); - $file_obj->export($a_target_dir); - unset($file_obj); - } - } - - /** - * export properties of content object - * - */ - function exportXMLProperties($a_xml_writer, &$expLog) - { - $attrs = array(); - $a_xml_writer->xmlStartTag("Properties", $attrs); - - // Layout - $attrs = array("Name" => "Layout", "Value" => $this->getLayout()); - $a_xml_writer->xmlElement("Property", $attrs); - - // Page Header - $attrs = array("Name" => "PageHeader", "Value" => $this->getPageHeader()); - $a_xml_writer->xmlElement("Property", $attrs); - - // TOC Mode - $attrs = array("Name" => "TOCMode", "Value" => $this->getTOCMode()); - $a_xml_writer->xmlElement("Property", $attrs); - - // LM Menu Activation - $attrs = array("Name" => "ActiveLMMenu", "Value" => - ilUtil::tf2yn($this->isActiveLMMenu())); - $a_xml_writer->xmlElement("Property", $attrs); - - // Numbering Activation - $attrs = array("Name" => "ActiveNumbering", "Value" => - ilUtil::tf2yn($this->isActiveNumbering())); - $a_xml_writer->xmlElement("Property", $attrs); - - // Table of contents button activation - $attrs = array("Name" => "ActiveTOC", "Value" => - ilUtil::tf2yn($this->isActiveTOC())); - $a_xml_writer->xmlElement("Property", $attrs); - - // Print view button activation - $attrs = array("Name" => "ActivePrintView", "Value" => - ilUtil::tf2yn($this->isActivePrintView())); - $a_xml_writer->xmlElement("Property", $attrs); - - // Note that download button is not saved, because - // download files do not exist after import - - // Clean frames - $attrs = array("Name" => "CleanFrames", "Value" => - ilUtil::tf2yn($this->cleanFrames())); - $a_xml_writer->xmlElement("Property", $attrs); - - // Public notes activation - $attrs = array("Name" => "PublicNotes", "Value" => - ilUtil::tf2yn($this->publicNotes())); - $a_xml_writer->xmlElement("Property", $attrs); - - // History comments for authors activation - $attrs = array("Name" => "HistoryUserComments", "Value" => - ilUtil::tf2yn($this->isActiveHistoryUserComments())); - $a_xml_writer->xmlElement("Property", $attrs); - - // Rating - $attrs = array("Name" => "Rating", "Value" => - ilUtil::tf2yn($this->hasRating())); - $a_xml_writer->xmlElement("Property", $attrs); - $attrs = array("Name" => "RatingPages", "Value" => - ilUtil::tf2yn($this->hasRatingPages())); - $a_xml_writer->xmlElement("Property", $attrs); - - // Header Page - if ($this->getHeaderPage() > 0) - { - $attrs = array("Name" => "HeaderPage", "Value" => - "il_".IL_INST_ID."_pg_".$this->getHeaderPage()); - $a_xml_writer->xmlElement("Property", $attrs); - } - - // Footer Page - if ($this->getFooterPage() > 0) - { - $attrs = array("Name" => "FooterPage", "Value" => - "il_".IL_INST_ID."_pg_".$this->getFooterPage()); - $a_xml_writer->xmlElement("Property", $attrs); - } - - // layout per page - $attrs = array("Name" => "LayoutPerPage", "Value" => - $this->getLayoutPerPage()); - $a_xml_writer->xmlElement("Property", $attrs); - - // progress icons - $attrs = array("Name" => "ProgressIcons", "Value" => - $this->getProgressIcons()); - $a_xml_writer->xmlElement("Property", $attrs); - - // store tries - $attrs = array("Name" => "StoreTries", "Value" => - $this->getStoreTries()); - $a_xml_writer->xmlElement("Property", $attrs); - - // restrict forward navigation - $attrs = array("Name" => "RestrictForwardNavigation", "Value" => - $this->getRestrictForwardNavigation()); - $a_xml_writer->xmlElement("Property", $attrs); - - // disable default feedback - $attrs = array("Name" => "DisableDefaultFeedback", "Value" => - $this->getDisableDefaultFeedback()); - $a_xml_writer->xmlElement("Property", $attrs); - - $a_xml_writer->xmlEndTag("Properties"); - } - - /** - * get export files - */ - function getExportFiles() - { - $file = array(); - - $types = array("xml", "html", "scorm"); - - foreach ($types as $type) - { - $dir = $this->getExportDirectory($type); - // quit if import dir not available - if (!@is_dir($dir) or - !is_writeable($dir)) - { - continue; - } - - // open directory - $cdir = dir($dir); - - // initialize array - - // get files and save the in the array - while ($entry = $cdir->read()) - { - if ($entry != "." and - $entry != ".." and - substr($entry, -4) == ".zip" and - preg_match("~^[0-9]{10}_{2}[0-9]+_{2}(lm_)*[0-9]+\.zip\$~", $entry)) - { - $file[$entry.$type] = array("type" => $type, "file" => $entry, - "size" => filesize($dir."/".$entry)); - } - } - - // close import directory - $cdir->close(); - } - - // sort files - ksort ($file); - reset ($file); - return $file; - } - - /** - * specify public export file for type - * - * @param string $a_type type ("xml" / "html") - * @param string $a_file file name - */ - function setPublicExportFile($a_type, $a_file) - { - $this->public_export_file[$a_type] = $a_file; - } - - /** - * get public export file - * - * @param string $a_type type ("xml" / "html") - * - * @return string $a_file file name - */ - function getPublicExportFile($a_type) - { - return $this->public_export_file[$a_type]; - } - - /** - * get offline files - */ - function getOfflineFiles($dir) - { - // quit if offline dir not available - if (!@is_dir($dir) or - !is_writeable($dir)) - { - return array(); - } - - // open directory - $dir = dir($dir); - - // initialize array - $file = array(); - - // get files and save the in the array - while ($entry = $dir->read()) - { - if ($entry != "." and - $entry != ".." and - substr($entry, -4) == ".pdf" and - preg_match("~^[0-9]{10}_{2}[0-9]+_{2}(lm_)*[0-9]+\.pdf\$~", $entry)) - { - $file[] = $entry; - } - } - - // close import directory - $dir->close(); - - // sort files - sort ($file); - reset ($file); - - return $file; - } - - /** - * export scorm package - */ - function exportSCORM($a_target_dir, $log) - { - ilUtil::delDir($a_target_dir); - ilUtil::makeDir($a_target_dir); - //ilUtil::makeDir($a_target_dir."/res"); - - // export everything to html - $this->exportHTML($a_target_dir."/res", $log, false, "scorm"); - - // build manifest file - include("./Modules/LearningModule/classes/class.ilLMContObjectManifestBuilder.php"); - $man_builder = new ilLMContObjectManifestBuilder($this); - $man_builder->buildManifest(); - $man_builder->dump($a_target_dir); - - // copy scorm 1.2 schema definitions - copy("Modules/LearningModule/scorm_xsd/adlcp_rootv1p2.xsd", $a_target_dir."/adlcp_rootv1p2.xsd"); - copy("Modules/LearningModule/scorm_xsd/imscp_rootv1p1p2.xsd", $a_target_dir."/imscp_rootv1p1p2.xsd"); - copy("Modules/LearningModule/scorm_xsd/imsmd_rootv1p2p1.xsd", $a_target_dir."/imsmd_rootv1p2p1.xsd"); - copy("Modules/LearningModule/scorm_xsd/ims_xml.xsd", $a_target_dir."/ims_xml.xsd"); - - // zip it all - $date = time(); - $zip_file = $a_target_dir."/".$date."__".IL_INST_ID."__". - $this->getType()."_".$this->getId().".zip"; - //echo "zip-".$a_target_dir."-to-".$zip_file; - ilUtil::zip(array($a_target_dir."/res", - $a_target_dir."/imsmanifest.xml", - $a_target_dir."/adlcp_rootv1p2.xsd", - $a_target_dir."/imscp_rootv1p1p2.xsd", - $a_target_dir."/ims_xml.xsd", - $a_target_dir."/imsmd_rootv1p2p1.xsd") - , $zip_file); - - $dest_file = $this->getExportDirectory("scorm")."/".$date."__".IL_INST_ID."__". - $this->getType()."_".$this->getId().".zip"; - - rename($zip_file, $dest_file); - ilUtil::delDir($a_target_dir); - - } - - - /** - * export html package - */ - function exportHTML($a_target_dir, $log, $a_zip_file = true, $a_export_format = "html", $a_lang = "") - { - $tpl = $this->tpl; - $ilLocator = $this->locator; - $ilUser = $this->user; - - $user_lang = $ilUser->getLanguage(); - - // initialize temporary target directory - ilUtil::delDir($a_target_dir); - ilUtil::makeDir($a_target_dir); - $mob_dir = $a_target_dir."/mobs"; - ilUtil::makeDir($mob_dir); - $file_dir = $a_target_dir."/files"; - ilUtil::makeDir($file_dir); - $teximg_dir = $a_target_dir."/teximg"; - ilUtil::makeDir($teximg_dir); - $style_dir = $a_target_dir."/style"; - ilUtil::makeDir($style_dir); - $style_img_dir = $a_target_dir."/style/images"; - ilUtil::makeDir($style_img_dir); - $content_style_dir = $a_target_dir."/content_style"; - ilUtil::makeDir($content_style_dir); - $content_style_img_dir = $a_target_dir."/content_style/images"; - ilUtil::makeDir($content_style_img_dir); + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilLocatorGUI + */ + protected $locator; + + public $lm_tree; + public $meta_data; + public $layout; + public $style_id; + public $pg_header; + public $online; + public $for_translation = 0; + protected $rating; + protected $rating_pages; + public $auto_glossaries = array(); + + private $import_dir = ''; + /** + * @var ilLogger + */ + protected $log; + + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + global $DIC; + + $this->user = $DIC->user(); + $this->db = $DIC->database(); + $this->tree = $DIC->repositoryTree(); + $this->lng = $DIC->language(); + $this->error = $DIC["ilErr"]; + if (isset($DIC["tpl"])) { + $this->tpl = $DIC["tpl"]; + } + if (isset($DIC["ilLocator"])) { + $this->locator = $DIC["ilLocator"]; + } + + // this also calls read() method! (if $a_id is set) + parent::__construct($a_id, $a_call_by_reference); + + $this->log = ilLoggerFactory::getLogger('lm'); + + $this->mob_ids = array(); + $this->file_ids = array(); + $this->q_ids = array(); + } + + /** + * create content object + */ + public function create($a_no_meta_data = false) + { + $this->setOfflineStatus(true); + parent::create(); + + // meta data will be created by + // import parser + if (!$a_no_meta_data) { + $this->createMetaData(); + } + + $this->createProperties(); + $this->updateAutoGlossaries(); + } + + + + /** + * read data of content object + */ + public function read() + { + $ilDB = $this->db; + + parent::read(); + # echo "Content
\n"; + + $this->lm_tree = new ilTree($this->getId()); + $this->lm_tree->setTableNames('lm_tree', 'lm_data'); + $this->lm_tree->setTreeTablePK("lm_id"); + + $this->readProperties(); + + // read auto glossaries + $set = $ilDB->query( + "SELECT * FROM lm_glossaries " . + " WHERE lm_id = " . $ilDB->quote($this->getId(), "integer") + ); + $glos = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $glos[] = $rec["glo_id"]; + } + $this->setAutoGlossaries($glos); + + //parent::read(); + } + + /** + * get title of content object + * + * @return string title + */ + public function getTitle() + { + return parent::getTitle(); + } + + /** + * set title of content object + */ + public function setTitle($a_title) + { + parent::setTitle($a_title); + // $this->meta_data->setTitle($a_title); + } + + /** + * get description of content object + * + * @return string description + */ + public function getDescription() + { + return parent::getDescription(); + } + + /** + * set description of content object + */ + public function setDescription($a_description) + { + parent::setDescription($a_description); + // $this->meta_data->setDescription($a_description); + } + + + public function getImportId() + { + return $this->import_id; + } + + public function setImportId($a_id) + { + $this->import_id = $a_id; + } + + /** + * Set layout per page + * + * @param boolean layout per page + */ + public function setLayoutPerPage($a_val) + { + $this->layout_per_page = $a_val; + } + + /** + * Get layout per page + * + * @return boolean layout per page + */ + public function getLayoutPerPage() + { + return $this->layout_per_page; + } + + /** + * Set disable default feedback for questions + * + * @param bool $a_val disable default feedback + */ + public function setDisableDefaultFeedback($a_val) + { + $this->disable_def_feedback = $a_val; + } + + /** + * Get disable default feedback for questions + * + * @return bool disable default feedback + */ + public function getDisableDefaultFeedback() + { + return $this->disable_def_feedback; + } + + /** + * Set progress icons + * + * @param bool $a_val show progress icons + */ + public function setProgressIcons($a_val) + { + $this->progr_icons = $a_val; + } + + /** + * Get progress icons + * + * @return bool show progress icons + */ + public function getProgressIcons() + { + return $this->progr_icons; + } + + /** + * Set store tries + * + * @param bool $a_val store tries + */ + public function setStoreTries($a_val) + { + $this->store_tries = $a_val; + } + + /** + * Get store tries + * + * @return bool store tries + */ + public function getStoreTries() + { + return $this->store_tries; + } + + /** + * Set restrict forward navigation + * + * @param bool $a_val restrict forward navigation + */ + public function setRestrictForwardNavigation($a_val) + { + $this->restrict_forw_nav = $a_val; + } + + /** + * Get restrict forward navigation + * + * @return bool restrict forward navigation + */ + public function getRestrictForwardNavigation() + { + return $this->restrict_forw_nav; + } + + + public function &getTree() + { + return $this->lm_tree; + } + + /** + * update complete object (meta data and properties) + */ + public function update() + { + $this->updateMetaData(); + parent::update(); + $this->updateProperties(); + $this->updateAutoGlossaries(); + } + + /** + * Update auto glossaries + * + * @param + * @return + */ + public function updateAutoGlossaries() + { + $ilDB = $this->db; + + // update auto glossaries + $ilDB->manipulate( + "DELETE FROM lm_glossaries WHERE " . + " lm_id = " . $ilDB->quote($this->getId(), "integer") + ); + foreach ($this->getAutoGlossaries() as $glo_id) { + $ilDB->manipulate("INSERT INTO lm_glossaries " . + "(lm_id, glo_id) VALUES (" . + $ilDB->quote($this->getId(), "integer") . "," . + $ilDB->quote($glo_id, "integer") . + ")"); + } + } + + + /** + * if implemented, this function should be called from an Out/GUI-Object + */ + public function import() + { + // nothing to do. just display the dialogue in Out + return; + } + + + /** + * put content object in main tree + * + */ + public function putInTree($a_parent) + { + $tree = $this->tree; + + // put this object in tree under $a_parent + parent::putInTree($a_parent); + + // make new tree for this object + //$tree->addTree($this->getId()); + } + + + /** + * create content object tree (that stores structure object hierarchie) + * + * todo: rename LM to ConOb + */ + public function createLMTree() + { + $this->lm_tree = new ilTree($this->getId()); + $this->lm_tree->setTreeTablePK("lm_id"); + $this->lm_tree->setTableNames('lm_tree', 'lm_data'); + $this->lm_tree->addTree($this->getId(), 1); + } + + /** + * Set auto glossaries + * + * @param array $a_val int + */ + public function setAutoGlossaries($a_val) + { + $this->auto_glossaries = array(); + if (is_array($a_val)) { + foreach ($a_val as $v) { + $v = (int) $v; + if ($v > 0 && ilObject::_lookupType($v) == "glo" && + !in_array($v, $this->auto_glossaries)) { + $this->auto_glossaries[] = $v; + } + } + } + } + + /** + * Get auto glossaries + * + * @return array int + */ + public function getAutoGlossaries() + { + return $this->auto_glossaries; + } + + /** + * Remove auto glossary + * + * @param + * @return + */ + public function removeAutoGlossary($a_glo_id) + { + $glo_ids = array(); + foreach ($this->getAutoGlossaries() as $g) { + if ($g != $a_glo_id) { + $glo_ids[] = $g; + } + } + $this->setAutoGlossaries($glo_ids); + } + + + /** + * Add first chapter and page + */ + public function addFirstChapterAndPage() + { + $lng = $this->lng; + + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + include_once("./Modules/LearningModule/classes/class.ilStructureObject.php"); + include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); + + $root_id = $this->lm_tree->getRootId(); + + // chapter + $chap = new ilStructureObject($this); + $chap->setType("st"); + $chap->setTitle($lng->txt("cont_new_chap")); + $chap->setLMId($this->getId()); + $chap->create(); + ilLMObject::putInTree($chap, $root_id, IL_FIRST_NODE); + + // page + $page = new ilLMPageObject($this); + $page->setType("pg"); + $page->setTitle($lng->txt("cont_new_page")); + $page->setLMId($this->getId()); + $page->create(); + ilLMObject::putInTree($page, $chap->getId(), IL_FIRST_NODE); + } + + /** + * Set for translation + * + * @param bool $a_val lm has been imported for translation purposes + */ + public function setForTranslation($a_val) + { + $this->for_translation = $a_val; + } + + /** + * Get for translation + * + * @return bool lm has been imported for translation purposes + */ + public function getForTranslation() + { + return $this->for_translation; + } + + /** + * get content object tree + */ + public function &getLMTree() + { + return $this->lm_tree; + } + + + /** + * creates data directory for import files + * (data_dir/lm_data/lm_/import, depending on data + * directory that is set in ILIAS setup/ini) + */ + public function createImportDirectory() + { + $ilErr = $this->error; + + $lm_data_dir = ilUtil::getDataDir() . "/lm_data"; + if (!is_writable($lm_data_dir)) { + $ilErr->raiseError("Content object Data Directory (" . $lm_data_dir + . ") not writeable.", $ilErr->FATAL); + } + + // create learning module directory (data_dir/lm_data/lm_) + $lm_dir = $lm_data_dir . "/lm_" . $this->getId(); + ilUtil::makeDir($lm_dir); + if (!@is_dir($lm_dir)) { + $ilErr->raiseError("Creation of Learning Module Directory failed.", $ilErr->FATAL); + } + + // create import subdirectory (data_dir/lm_data/lm_/import) + $import_dir = $lm_dir . "/import"; + ilUtil::makeDir($import_dir); + if (!@is_dir($import_dir)) { + $ilErr->raiseError("Creation of Import Directory failed.", $ilErr->FATAL); + } + } + + /** + * get data directory + */ + public function getDataDirectory() + { + return ilUtil::getDataDir() . "/lm_data" . + "/lm_" . $this->getId(); + } + + /** + * get import directory of lm + */ + public function getImportDirectory() + { + if (strlen($this->import_dir)) { + return $this->import_dir; + } + + $import_dir = ilUtil::getDataDir() . "/lm_data" . + "/lm_" . $this->getId() . "/import"; + if (@is_dir($import_dir)) { + return $import_dir; + } else { + return false; + } + } + + /** + * Set import directory for further use in ilContObjParser + * + * @param string import directory + * @return void + */ + public function setImportDirectory($a_import_dir) + { + $this->import_dir = $a_import_dir; + } + + + /** + * creates data directory for export files + * (data_dir/lm_data/lm_/export, depending on data + * directory that is set in ILIAS setup/ini) + */ + public function createExportDirectory($a_type = "xml") + { + $ilErr = $this->error; + + $lm_data_dir = ilUtil::getDataDir() . "/lm_data"; + if (!is_writable($lm_data_dir)) { + $ilErr->raiseError("Content object Data Directory (" . $lm_data_dir + . ") not writeable.", $ilErr->FATAL); + } + // create learning module directory (data_dir/lm_data/lm_) + $lm_dir = $lm_data_dir . "/lm_" . $this->getId(); + ilUtil::makeDir($lm_dir); + if (!@is_dir($lm_dir)) { + $ilErr->raiseError("Creation of Learning Module Directory failed.", $ilErr->FATAL); + } + // create Export subdirectory (data_dir/lm_data/lm_/Export) + switch ($a_type) { + // scorm + case "scorm": + $export_dir = $lm_dir . "/export_scorm"; + break; + + default: // = xml + if (substr($a_type, 0, 4) == "html") { + $export_dir = $lm_dir . "/export_" . $a_type; + } else { + $export_dir = $lm_dir . "/export"; + } + break; + } + ilUtil::makeDir($export_dir); + + if (!@is_dir($export_dir)) { + $ilErr->raiseError("Creation of Export Directory failed.", $ilErr->FATAL); + } + } + + /** + * get export directory of lm + */ + public function getExportDirectory($a_type = "xml") + { + switch ($a_type) { + case "scorm": + $export_dir = ilUtil::getDataDir() . "/lm_data" . "/lm_" . $this->getId() . "/export_scorm"; + break; + + default: // = xml + if (substr($a_type, 0, 4) == "html") { + $export_dir = ilUtil::getDataDir() . "/lm_data" . "/lm_" . $this->getId() . "/export_" . $a_type; + } else { + $export_dir = ilUtil::getDataDir() . "/lm_data" . "/lm_" . $this->getId() . "/export"; + } + break; + } + return $export_dir; + } + + + /** + * delete learning module and all related data + * + * this method has been tested on may 9th 2004 + * meta data, content object data, data directory, bib items + * learning module tree and pages have been deleted correctly as desired + * + * @access public + * @return boolean true if all object data were removed; false if only a references were removed + */ + public function delete() + { + $ilDB = $this->db; + + // always call parent delete function first!! + if (!parent::delete()) { + return false; + } + + // delete lm object data + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + ilLMObject::_deleteAllObjectData($this); + + // delete meta data of content object + $this->deleteMetaData(); + + + // delete learning module tree + $this->lm_tree->removeTree($this->lm_tree->getTreeId()); + + // delete data directory + ilUtil::delDir($this->getDataDirectory()); + + // delete content object record + $q = "DELETE FROM content_object WHERE id = " . + $ilDB->quote($this->getId(), "integer"); + $ilDB->manipulate($q); + + // delete lm menu entries + $q = "DELETE FROM lm_menu WHERE lm_id = " . + $ilDB->quote($this->getId(), "integer"); + $ilDB->manipulate($q); + + // remove auto glossary entries + $ilDB->manipulate( + "DELETE FROM lm_glossaries WHERE " . + " lm_id = " . $ilDB->quote($this->getId(), "integer") + ); + + + return true; + } + + + /** + * get default page layout of content object (see directory layouts/) + * + * @return string default layout + */ + public function getLayout() + { + return $this->layout; + } + + /** + * set default page layout + * + * @param string $a_layout default page layout + */ + public function setLayout($a_layout) + { + $this->layout = $a_layout; + } + + /** + * get ID of assigned style sheet object + */ + public function getStyleSheetId() + { + return $this->style_id; + } + + /** + * set ID of assigned style sheet object + */ + public function setStyleSheetId($a_style_id) + { + $this->style_id = $a_style_id; + } + + /** + * write ID of assigned style sheet object to db + */ + public function writeStyleSheetId($a_style_id) + { + $ilDB = $this->db; + + $q = "UPDATE content_object SET " . + " stylesheet = " . $ilDB->quote((int) $a_style_id, "integer") . + " WHERE id = " . $ilDB->quote($this->getId(), "integer"); + $ilDB->manipulate($q); + + $this->style_id = $a_style_id; + } + + /** + * Write header page + * + * @param int $a_lm_id learning module id + * @param int $a_page_id page + */ + public static function writeHeaderPage($a_lm_id, $a_page_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $ilDB->manipulate( + "UPDATE content_object SET " . + " header_page = " . $ilDB->quote($a_page_id, "integer") . + " WHERE id = " . $ilDB->quote($a_lm_id, "integer") + ); + } + + /** + * Write footer page + * + * @param int $a_lm_id learning module id + * @param int $a_page_id page + */ + public static function writeFooterPage($a_lm_id, $a_page_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $ilDB->manipulate( + "UPDATE content_object SET " . + " footer_page = " . $ilDB->quote($a_page_id, "integer") . + " WHERE id = " . $ilDB->quote($a_lm_id, "integer") + ); + } + + + /** + * move learning modules from one style to another + */ + public static function _moveLMStyles($a_from_style, $a_to_style) + { + global $DIC; + + $ilDB = $DIC->database(); + + if ($a_from_style < 0) { // change / delete all individual styles + $q = "SELECT stylesheet FROM content_object, style_data " . + " WHERE content_object.stylesheet = style_data.id " . + " AND style_data.standard = " . $ilDB->quote(0, "integer") . + " AND content_object.stylesheet > " . $ilDB->quote(0, "integer"); + $style_set = $ilDB->query($q); + while ($style_rec = $ilDB->fetchAssoc($style_set)) { + // assign learning modules to new style + $q = "UPDATE content_object SET " . + " stylesheet = " . $ilDB->quote((int) $a_to_style, "integer") . + " WHERE stylesheet = " . $ilDB->quote($style_rec["stylesheet"], "integer"); + $ilDB->manipulate($q); + + // delete style + $style_obj = ilObjectFactory::getInstanceByObjId($style_rec["stylesheet"]); + $style_obj->delete(); + } + } else { + $q = "UPDATE content_object SET " . + " stylesheet = " . $ilDB->quote((int) $a_to_style, "integer") . + " WHERE stylesheet = " . $ilDB->quote($a_from_style, "integer"); + $ilDB->manipulate($q); + } + } + + /** + * Lookup property + * + * @param int $a_obj_id object id + * @param string $a_field property field name + * @return string property value + */ + protected static function _lookup($a_obj_id, $a_field) + { + global $DIC; + + $ilDB = $DIC->database(); + $ilLog = $DIC["ilLog"]; + + $q = "SELECT " . $a_field . " FROM content_object " . + " WHERE id = " . $ilDB->quote($a_obj_id, "integer"); + + $res = $ilDB->query($q); + $rec = $ilDB->fetchAssoc($res); + + return $rec[$a_field]; + } + + /** + * Lookup forward restriction navigation + * + * @param int $a_obj_id object id + * @return string property value + */ + public static function _lookupRestrictForwardNavigation($a_obj_id) + { + return self::_lookup($a_obj_id, "restrict_forw_nav"); + } + + /** + * lookup style sheet ID + */ + public static function _lookupStyleSheetId($a_cont_obj_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "SELECT stylesheet FROM content_object " . + " WHERE id = " . $ilDB->quote($a_cont_obj_id, "integer"); + $res = $ilDB->query($q); + $sheet = $ilDB->fetchAssoc($res); + + return $sheet["stylesheet"]; + } + + /** + * lookup style sheet ID + */ + public static function _lookupContObjIdByStyleId($a_style_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "SELECT id FROM content_object " . + " WHERE stylesheet = " . $ilDB->quote($a_style_id, "integer"); + $res = $ilDB->query($q); + $obj_ids = array(); + while ($cont = $ilDB->fetchAssoc($res)) { + $obj_ids[] = $cont["id"]; + } + return $obj_ids; + } + + /** + * Lookup disable default feedback + */ + public static function _lookupDisableDefaultFeedback($a_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "SELECT disable_def_feedback FROM content_object " . + " WHERE id = " . $ilDB->quote($a_id, "integer"); + $res = $ilDB->query($q); + $rec = $ilDB->fetchAssoc($res); + + return $rec["disable_def_feedback"]; + } + + /** + * Lookup disable default feedback + */ + public static function _lookupStoreTries($a_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "SELECT store_tries FROM content_object " . + " WHERE id = " . $ilDB->quote($a_id, "integer"); + $res = $ilDB->query($q); + $rec = $ilDB->fetchAssoc($res); + + return $rec["store_tries"]; + } + + + /** + * gets the number of learning modules assigned to a content style + * + * @param int $a_style_id style id + */ + public static function _getNrOfAssignedLMs($a_style_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "SELECT count(*) as cnt FROM content_object " . + " WHERE stylesheet = " . $ilDB->quote($a_style_id, "integer"); + $cset = $ilDB->query($q); + $crow = $ilDB->fetchAssoc($cset); + + return (int) $crow["cnt"]; + } + + + /** + * get number of learning modules with individual styles + */ + public static function _getNrLMsIndividualStyles() + { + global $DIC; + + $ilDB = $DIC->database(); + + // joining with style table (not perfectly nice) + $q = "SELECT count(*) as cnt FROM content_object, style_data " . + " WHERE stylesheet = style_data.id " . + " AND standard = " . $ilDB->quote(0, "integer"); + $cset = $ilDB->query($q); + $crow = $ilDB->fetchAssoc($cset); + + return (int) $crow["cnt"]; + } + + /** + * get number of learning modules assigned no style + */ + public static function _getNrLMsNoStyle() + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "SELECT count(*) as cnt FROM content_object " . + " WHERE stylesheet = " . $ilDB->quote(0, "integer"); + $cset = $ilDB->query($q); + $crow = $ilDB->fetchAssoc($cset); + + return (int) $crow["cnt"]; + } + + /** + * delete all style references to style + * + * @param int $a_style_id style_id + */ + public static function _deleteStyleAssignments($a_style_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "UPDATE content_object SET " . + " stylesheet = " . $ilDB->quote(0, "integer") . + " WHERE stylesheet = " . $ilDB->quote((int) $a_style_id, "integer"); + + $ilDB->manipulate($q); + } + + /** + * get page header mode (IL_CHAPTER_TITLE | IL_PAGE_TITLE | IL_NO_HEADER) + */ + public function getPageHeader() + { + return $this->pg_header; + } + + /** + * set page header mode + * + * @param string $a_pg_header IL_CHAPTER_TITLE | IL_PAGE_TITLE | IL_NO_HEADER + */ + public function setPageHeader($a_pg_header = IL_CHAPTER_TITLE) + { + $this->pg_header = $a_pg_header; + } + + /** + * get toc mode ("chapters" | "pages") + */ + public function getTOCMode() + { + return $this->toc_mode; + } + + /** + * get public access mode ("complete" | "selected") + */ + public function getPublicAccessMode() + { + return $this->public_access_mode; + } + + /** + * set toc mode + * + * @param string $a_toc_mode "chapters" | "pages" + */ + public function setTOCMode($a_toc_mode = "chapters") + { + $this->toc_mode = $a_toc_mode; + } + + public function setActiveLMMenu($a_act_lm_menu) + { + $this->lm_menu_active = $a_act_lm_menu; + } + + public function isActiveLMMenu() + { + return $this->lm_menu_active; + } + + public function setActiveTOC($a_toc) + { + $this->toc_active = $a_toc; + } + + public function isActiveTOC() + { + return $this->toc_active; + } + + public function setActiveNumbering($a_num) + { + $this->numbering = $a_num; + } + + public function isActiveNumbering() + { + return $this->numbering; + } + + public function setActivePrintView($a_print) + { + $this->print_view_active = $a_print; + } + + public function isActivePrintView() + { + return $this->print_view_active; + } + + public function setActivePreventGlossaryAppendix($a_print) + { + $this->prevent_glossary_appendix_active = $a_print; + } + + public function isActivePreventGlossaryAppendix() + { + return $this->prevent_glossary_appendix_active; + } + + /** + * Set hide header footer in print mode + * + * @param bool $a_val hide header and footer? + */ + public function setHideHeaderFooterPrint($a_val) + { + $this->hide_header_footer_print = $a_val; + } + + /** + * Get hide header footer in print mode + * + * @return bool hide header and footer? + */ + public function getHideHeaderFooterPrint() + { + return $this->hide_header_footer_print; + } + + public function setActiveDownloads($a_down) + { + $this->downloads_active = $a_down; + } + + public function isActiveDownloads() + { + return $this->downloads_active; + } + + public function setActiveDownloadsPublic($a_down) + { + $this->downloads_public_active = $a_down; + } + + public function isActiveDownloadsPublic() + { + return $this->downloads_public_active; + } + + public function setPublicNotes($a_pub_notes) + { + $this->pub_notes = $a_pub_notes; + } + + public function publicNotes() + { + return $this->pub_notes; + } + + public function setCleanFrames($a_clean) + { + $this->clean_frames = $a_clean; + } + + public function cleanFrames() + { + return $this->clean_frames; + } + + public function setHistoryUserComments($a_comm) + { + $this->user_comments = $a_comm; + } + + public function setPublicAccessMode($a_mode) + { + $this->public_access_mode = $a_mode; + } + + public function isActiveHistoryUserComments() + { + return $this->user_comments; + } + + public function setHeaderPage($a_pg) + { + $this->header_page = $a_pg; + } + + public function getHeaderPage() + { + return $this->header_page; + } + + public function setFooterPage($a_pg) + { + $this->footer_page = $a_pg; + } + + public function getFooterPage() + { + return $this->footer_page; + } + + /** + * read content object properties + */ + public function readProperties() + { + $ilDB = $this->db; + + $q = "SELECT * FROM content_object WHERE id = " . + $ilDB->quote($this->getId(), "integer"); + $lm_set = $ilDB->query($q); + $lm_rec = $ilDB->fetchAssoc($lm_set); + $this->setLayout($lm_rec["default_layout"]); + $this->setStyleSheetId((int) $lm_rec["stylesheet"]); + $this->setPageHeader($lm_rec["page_header"]); + $this->setTOCMode($lm_rec["toc_mode"]); + $this->setActiveTOC(ilUtil::yn2tf($lm_rec["toc_active"])); + $this->setActiveNumbering(ilUtil::yn2tf($lm_rec["numbering"])); + $this->setActivePrintView(ilUtil::yn2tf($lm_rec["print_view_active"])); + $this->setActivePreventGlossaryAppendix(ilUtil::yn2tf($lm_rec["no_glo_appendix"])); + $this->setHideHeaderFooterPrint($lm_rec["hide_head_foot_print"]); + $this->setActiveDownloads(ilUtil::yn2tf($lm_rec["downloads_active"])); + $this->setActiveDownloadsPublic(ilUtil::yn2tf($lm_rec["downloads_public_active"])); + $this->setActiveLMMenu(ilUtil::yn2tf($lm_rec["lm_menu_active"])); + $this->setCleanFrames(ilUtil::yn2tf($lm_rec["clean_frames"])); + $this->setHeaderPage((int) $lm_rec["header_page"]); + $this->setFooterPage((int) $lm_rec["footer_page"]); + $this->setHistoryUserComments(ilUtil::yn2tf($lm_rec["hist_user_comments"])); + $this->setPublicAccessMode($lm_rec["public_access_mode"]); + $this->setPublicExportFile("xml", $lm_rec["public_xml_file"]); + $this->setPublicExportFile("html", $lm_rec["public_html_file"]); + $this->setPublicExportFile("scorm", $lm_rec["public_scorm_file"]); + $this->setLayoutPerPage($lm_rec["layout_per_page"]); + $this->setRating($lm_rec["rating"]); + $this->setRatingPages($lm_rec["rating_pages"]); + $this->setDisableDefaultFeedback($lm_rec["disable_def_feedback"]); + $this->setProgressIcons($lm_rec["progr_icons"]); + $this->setStoreTries($lm_rec["store_tries"]); + $this->setRestrictForwardNavigation($lm_rec["restrict_forw_nav"]); + + // #14661 + include_once("./Services/Notes/classes/class.ilNote.php"); + $this->setPublicNotes(ilNote::commentsActivated($this->getId(), 0, $this->getType())); + + $this->setForTranslation($lm_rec["for_translation"]); + } + + /** + * Update content object properties + */ + public function updateProperties() + { + $ilDB = $this->db; + + // force clean_frames to be set, if layout per page is activated + if ($this->getLayoutPerPage()) { + $this->setCleanFrames(true); + } + + $q = "UPDATE content_object SET " . + " default_layout = " . $ilDB->quote($this->getLayout(), "text") . ", " . + " stylesheet = " . $ilDB->quote($this->getStyleSheetId(), "integer") . "," . + " page_header = " . $ilDB->quote($this->getPageHeader(), "text") . "," . + " toc_mode = " . $ilDB->quote($this->getTOCMode(), "text") . "," . + " toc_active = " . $ilDB->quote(ilUtil::tf2yn($this->isActiveTOC()), "text") . "," . + " numbering = " . $ilDB->quote(ilUtil::tf2yn($this->isActiveNumbering()), "text") . "," . + " print_view_active = " . $ilDB->quote(ilUtil::tf2yn($this->isActivePrintView()), "text") . "," . + " no_glo_appendix = " . $ilDB->quote(ilUtil::tf2yn($this->isActivePreventGlossaryAppendix()), "text") . "," . + " hide_head_foot_print = " . $ilDB->quote($this->getHideHeaderFooterPrint(), "integer") . "," . + " downloads_active = " . $ilDB->quote(ilUtil::tf2yn($this->isActiveDownloads()), "text") . "," . + " downloads_public_active = " . $ilDB->quote(ilUtil::tf2yn($this->isActiveDownloadsPublic()), "text") . "," . + " clean_frames = " . $ilDB->quote(ilUtil::tf2yn($this->cleanFrames()), "text") . "," . + " hist_user_comments = " . $ilDB->quote(ilUtil::tf2yn($this->isActiveHistoryUserComments()), "text") . "," . + " public_access_mode = " . $ilDB->quote($this->getPublicAccessMode(), "text") . "," . + " public_xml_file = " . $ilDB->quote($this->getPublicExportFile("xml"), "text") . "," . + " public_html_file = " . $ilDB->quote($this->getPublicExportFile("html"), "text") . "," . + " public_scorm_file = " . $ilDB->quote($this->getPublicExportFile("scorm"), "text") . "," . + " header_page = " . $ilDB->quote($this->getHeaderPage(), "integer") . "," . + " footer_page = " . $ilDB->quote($this->getFooterPage(), "integer") . "," . + " lm_menu_active = " . $ilDB->quote(ilUtil::tf2yn($this->isActiveLMMenu()), "text") . ", " . + " layout_per_page = " . $ilDB->quote($this->getLayoutPerPage(), "integer") . ", " . + " rating = " . $ilDB->quote($this->hasRating(), "integer") . ", " . + " rating_pages = " . $ilDB->quote($this->hasRatingPages(), "integer") . ", " . + " disable_def_feedback = " . $ilDB->quote($this->getDisableDefaultFeedback(), "integer") . ", " . + " progr_icons = " . $ilDB->quote($this->getProgressIcons(), "integer") . ", " . + " store_tries = " . $ilDB->quote($this->getStoreTries(), "integer") . ", " . + " restrict_forw_nav = " . $ilDB->quote($this->getRestrictForwardNavigation(), "integer") . ", " . + " for_translation = " . $ilDB->quote((int) $this->getForTranslation(), "integer") . " " . + " WHERE id = " . $ilDB->quote($this->getId(), "integer"); + $ilDB->manipulate($q); + // #14661 + include_once("./Services/Notes/classes/class.ilNote.php"); + ilNote::activateComments($this->getId(), 0, $this->getType(), $this->publicNotes()); + } + + /** + * create new properties record + */ + public function createProperties() + { + $ilDB = $this->db; + + $q = "INSERT INTO content_object (id) VALUES (" . $ilDB->quote($this->getId(), "integer") . ")"; + $ilDB->manipulate($q); + + // #14661 + include_once("./Services/Notes/classes/class.ilNote.php"); + ilNote::activateComments($this->getId(), 0, $this->getType(), true); + + $this->readProperties(); // to get db default values + } + + + /** + * get all available lm layouts + */ + public static function getAvailableLayouts() + { + $dir = opendir("./Modules/LearningModule/layouts/lm"); + + $layouts = array(); + + while ($file = readdir($dir)) { + if ($file != "." && $file != ".." && $file != "CVS" && $file != ".svn") { + // directories + if (@is_dir("./Modules/LearningModule/layouts/lm/" . $file)) { + $layouts[$file] = $file; + } + } + } + asort($layouts); + + // workaround: fix ordering + $ret = array( + 'toc2win' => 'toc2win', + 'toc2windyn' => 'toc2windyn', + '1window' => '1window', + '2window' => '2window', + '3window' => '3window', + 'presentation' => 'presentation', + 'fullscreen' => 'fullscreen' + ); + + foreach ($layouts as $l) { + if (!in_array($l, $ret)) { + $ret[$l] = $l; + } + } + + return $ret; + } + + /** + * checks wether the preconditions of a page are fulfilled or not + */ + public static function _checkPreconditionsOfPage($cont_ref_id, $cont_obj_id, $page_id) + { + global $DIC; + + $ilUser = $DIC->user(); + $ilErr = $DIC["ilErr"]; + + $lm_tree = new ilTree($cont_obj_id); + $lm_tree->setTableNames('lm_tree', 'lm_data'); + $lm_tree->setTreeTablePK("lm_id"); + + if ($lm_tree->isInTree($page_id)) { + $path = $lm_tree->getPathFull($page_id, $lm_tree->readRootId()); + foreach ($path as $node) { + if ($node["type"] == "st") { + if (!ilConditionHandler::_checkAllConditionsOfTarget($cont_ref_id, $node["child"], "st")) { + return false; + } + } + } + } + + return true; + } + + /** + * gets all missing preconditions of page + */ + public static function _getMissingPreconditionsOfPage($cont_ref_id, $cont_obj_id, $page_id) + { + $lm_tree = new ilTree($cont_obj_id); + $lm_tree->setTableNames('lm_tree', 'lm_data'); + $lm_tree->setTreeTablePK("lm_id"); + + $conds = array(); + if ($lm_tree->isInTree($page_id)) { + // get full path of page + $path = $lm_tree->getPathFull($page_id, $lm_tree->readRootId()); + foreach ($path as $node) { + if ($node["type"] == "st") { + // get all preconditions of upper chapters + $tconds = ilConditionHandler::_getPersistedConditionsOfTarget($cont_ref_id, $node["child"], "st"); + foreach ($tconds as $tcond) { + // store all missing preconditions + if (!ilConditionHandler::_checkCondition($tcond)) { + $conds[] = $tcond; + } + } + } + } + } + + return $conds; + } + + /** + * get top chapter of page for that any precondition is missing + */ + public static function _getMissingPreconditionsTopChapter($cont_obj_ref_id, $cont_obj_id, $page_id) + { + $lm_tree = new ilTree($cont_obj_id); + $lm_tree->setTableNames('lm_tree', 'lm_data'); + $lm_tree->setTreeTablePK("lm_id"); + + $conds = array(); + if ($lm_tree->isInTree($page_id)) { + // get full path of page + $path = $lm_tree->getPathFull($page_id, $lm_tree->readRootId()); + foreach ($path as $node) { + if ($node["type"] == "st") { + // get all preconditions of upper chapters + $tconds = ilConditionHandler::_getPersistedConditionsOfTarget($cont_obj_ref_id, $node["child"], "st"); + foreach ($tconds as $tcond) { + // look for missing precondition + if (!ilConditionHandler::_checkCondition($tcond)) { + return $node["child"]; + } + } + } + } + } + + return ""; + } + + /** + * checks if page has a successor page + */ + public static function hasSuccessorPage($a_cont_obj_id, $a_page_id) + { + $tree = new ilTree($a_cont_obj_id); + $tree->setTableNames('lm_tree', 'lm_data'); + $tree->setTreeTablePK("lm_id"); + if ($tree->isInTree($a_page_id)) { + $succ = $tree->fetchSuccessorNode($a_page_id, "pg"); + if ($succ > 0) { + return true; + } + } + return false; + } + + + public function checkTree() + { + $tree = new ilTree($this->getId()); + $tree->setTableNames('lm_tree', 'lm_data'); + $tree->setTreeTablePK("lm_id"); + $tree->checkTree(); + $tree->checkTreeChilds(); + //echo "checked"; + } + + /** + * fix tree + */ + public function fixTree() + { + $ilDB = $this->db; + + $tree = $this->getLMTree(); + + // check numbering, if errors, renumber + // it is very important to keep this step before deleting subtrees + // in the following steps + $set = $ilDB->query( + "SELECT DISTINCT l1.lm_id" . + " FROM lm_tree l1" . + " JOIN lm_tree l2 ON ( l1.child = l2.parent" . + " AND l1.lm_id = l2.lm_id )" . + " JOIN lm_data ON ( l1.child = lm_data.obj_id )" . + " WHERE (l2.lft < l1.lft" . + " OR l2.rgt > l1.rgt OR l2.lft > l1.rgt OR l2.rgt < l1.lft)" . + " AND l1.lm_id = " . $ilDB->quote($this->getId(), "integer") . + " ORDER BY lm_data.create_date DESC" + ); + if ($rec = $ilDB->fetchAssoc($set)) { + $tree->renumber(); + } + + // delete subtrees that have no lm_data records (changed due to #20637) + $set = $ilDB->query("SELECT * FROM lm_tree WHERE lm_tree.lm_id = " . $ilDB->quote($this->getId(), "integer")); + while ($node = $ilDB->fetchAssoc($set)) { + $q = "SELECT * FROM lm_data WHERE obj_id = " . + $ilDB->quote($node["child"], "integer"); + $obj_set = $ilDB->query($q); + $obj_rec = $ilDB->fetchAssoc($obj_set); + if (!$obj_rec) { + $node_data = $tree->getNodeData($node["child"]); + $node_data["child"] = $node["child"]; + $tree->deleteTree($node_data); + } + } + + // delete subtrees that have pages as parent + $nodes = $tree->getSubtree($tree->getNodeData($tree->getRootId())); + foreach ($nodes as $node) { + $q = "SELECT * FROM lm_data WHERE obj_id = " . + $ilDB->quote($node["parent"], "integer"); + $obj_set = $ilDB->query($q); + $obj_rec = $ilDB->fetchAssoc($obj_set); + if ($obj_rec["type"] == "pg") { + $node_data = $tree->getNodeData($node["child"]); + if ($tree->isInTree($node["child"])) { + $tree->deleteTree($node_data); + } + } + } + + // check for multi-references pages or chapters + // if errors -> create copies of them here + $set = $ilDB->query("SELECT DISTINCT l1.lm_id" . + " FROM lm_tree l1" . + " JOIN lm_tree l2 ON ( l1.child = l2.child AND l1.lm_id <> l2.lm_id )" . + " JOIN lm_data ON (l1.child = lm_data.obj_id)" . + " WHERE l1.child <> 1" . + " AND l1.lm_id <> lm_data.lm_id" . + " AND l1.lm_id = " . $ilDB->quote($this->getId(), "integer")); + if ($rec = $ilDB->fetchAssoc($set)) { + $set = $ilDB->query("SELECT DISTINCT l1.child " . + " FROM lm_tree l1" . + " JOIN lm_tree l2 ON ( l1.child = l2.child AND l1.lm_id <> l2.lm_id )" . + " JOIN lm_data ON (l1.child = lm_data.obj_id)" . + " WHERE l1.child <> 1" . + " AND l1.lm_id <> lm_data.lm_id" . + " AND l1.lm_id = " . $ilDB->quote($this->getId(), "integer")); + include_once("./Modules/LearningModule/classes/class.ilLMObjectFactory.php"); + while ($rec = $ilDB->fetchAssoc($set)) { + $cobj = ilLMObjectFactory::getInstance($this, $rec["child"]); + + if (is_object($cobj)) { + if ($cobj->getType() == "pg") { + // make a copy of it + $pg_copy = $cobj->copy($this); + + // replace the child in the tree with the copy (id) + $ilDB->manipulate( + "UPDATE lm_tree SET " . + " child = " . $ilDB->quote($pg_copy->getId(), "integer") . + " WHERE child = " . $ilDB->quote($cobj->getId(), "integer") . + " AND lm_id = " . $ilDB->quote($this->getId(), "integer") + ); + } elseif ($cobj->getType() == "st") { + // make a copy of it + $st_copy = $cobj->copy($this); + + // replace the child in the tree with the copy (id) + $ilDB->manipulate( + "UPDATE lm_tree SET " . + " child = " . $ilDB->quote($st_copy->getId(), "integer") . + " WHERE child = " . $ilDB->quote($cobj->getId(), "integer") . + " AND lm_id = " . $ilDB->quote($this->getId(), "integer") + ); + + // make all childs refer to the copy now + $ilDB->manipulate( + "UPDATE lm_tree SET " . + " parent = " . $ilDB->quote($st_copy->getId(), "integer") . + " WHERE parent = " . $ilDB->quote($cobj->getId(), "integer") . + " AND lm_id = " . $ilDB->quote($this->getId(), "integer") + ); + } + } + } + } + + // missing copage entries + $set = $ilDB->queryF( + "SELECT * FROM lm_data " . + " WHERE lm_id = %s AND type = %s", + array("integer", "text"), + array($this->getId(), "pg") + ); + while ($rec = $ilDB->fetchAssoc($set)) { + if (!ilPageObject::_exists("lm", $rec["obj_id"], "-")) { + $lm_page = new ilLMPage(); + $lm_page->setId($rec["obj_id"]); + $lm_page->setParentId($this->getId()); + $lm_page->create(); + } + } + } + + /** + * Check tree (this has been copied from fixTree due to a bug fixing, should be reorganised) + */ + public function checkStructure() + { + $issues = []; + $ilDB = $this->db; + + $tree = $this->getLMTree(); + + // check numbering, if errors, renumber + // it is very important to keep this step before deleting subtrees + // in the following steps + $set = $ilDB->query( + "SELECT l1.child, l1.lft l1lft, l1.rgt l1rgt, l2.parent, l2.lft l2lft, l2.rgt l2rgt" . + " FROM lm_tree l1" . + " JOIN lm_tree l2 ON ( l1.child = l2.parent" . + " AND l1.lm_id = l2.lm_id )" . + " JOIN lm_data ON ( l1.child = lm_data.obj_id )" . + " WHERE (l2.lft < l1.lft" . + " OR l2.rgt > l1.rgt OR l2.lft > l1.rgt OR l2.rgt < l1.lft)" . + " AND l1.lm_id = " . $ilDB->quote($this->getId(), "integer") . + " ORDER BY lm_data.create_date DESC" + ); + while ($rec = $ilDB->fetchAssoc($set)) { + $issues[] = "Tree numbering: " . print_r($rec, true); + } + + // delete subtrees that have no lm_data records (changed due to #20637) + $set = $ilDB->query("SELECT * FROM lm_tree WHERE lm_tree.lm_id = " . $ilDB->quote($this->getId(), "integer")); + while ($node = $ilDB->fetchAssoc($set)) { + $q = "SELECT * FROM lm_data WHERE obj_id = " . + $ilDB->quote($node["child"], "integer"); + $obj_set = $ilDB->query($q); + $obj_rec = $ilDB->fetchAssoc($obj_set); + if (!$obj_rec) { + $issues[] = "Tree entry without data entry: " . print_r($node, true); + } + } + + // delete subtrees that have pages as parent + $nodes = $tree->getSubtree($tree->getNodeData($tree->getRootId())); + foreach ($nodes as $node) { + $q = "SELECT * FROM lm_data WHERE obj_id = " . + $ilDB->quote($node["parent"], "integer"); + $obj_set = $ilDB->query($q); + $obj_rec = $ilDB->fetchAssoc($obj_set); + if ($obj_rec["type"] == "pg") { + $node_data = $tree->getNodeData($node["child"]); + if ($tree->isInTree($node["child"])) { + $issues[] = "Subtree with page parent: " . print_r($node_data, true); + } + } + } + + // check for multi-references pages or chapters + // if errors -> create copies of them here + $set = $ilDB->query("SELECT DISTINCT l1.lm_id" . + " FROM lm_tree l1" . + " JOIN lm_tree l2 ON ( l1.child = l2.child AND l1.lm_id <> l2.lm_id )" . + " JOIN lm_data ON (l1.child = lm_data.obj_id)" . + " WHERE l1.child <> 1" . + " AND l1.lm_id <> lm_data.lm_id" . + " AND l1.lm_id = " . $ilDB->quote($this->getId(), "integer")); + if ($rec = $ilDB->fetchAssoc($set)) { + $set = $ilDB->query("SELECT DISTINCT l1.child " . + " FROM lm_tree l1" . + " JOIN lm_tree l2 ON ( l1.child = l2.child AND l1.lm_id <> l2.lm_id )" . + " JOIN lm_data ON (l1.child = lm_data.obj_id)" . + " WHERE l1.child <> 1" . + " AND l1.lm_id <> lm_data.lm_id" . + " AND l1.lm_id = " . $ilDB->quote($this->getId(), "integer")); + include_once("./Modules/LearningModule/classes/class.ilLMObjectFactory.php"); + while ($rec = $ilDB->fetchAssoc($set)) { + $set3 = $ilDB->queryF( + "SELECT * FROM lm_tree " . + " WHERE child = %s ", + array("integer"), + array($rec["child"]) + ); + while ($rec3 = $ilDB->fetchAssoc($set3)) { + $issues[] = "Multi-reference item: " . print_r($rec3, true); + } + } + } + + // missing copage entries + $set = $ilDB->queryF( + "SELECT * FROM lm_data " . + " WHERE lm_id = %s AND type = %s", + array("integer", "text"), + array($this->getId(), "pg") + ); + while ($rec = $ilDB->fetchAssoc($set)) { + if (!ilPageObject::_exists("lm", $rec["obj_id"], "-")) { + $issues[] = "Missing COPage: " . print_r($rec, true); + } + } + + + return $issues; + } + + /** + * export object to xml (see ilias_co.dtd) + * + * @param object $a_xml_writer ilXmlWriter object that receives the + * xml data + */ + public function exportXML(&$a_xml_writer, $a_inst, $a_target_dir, &$expLog) + { + $attrs = array(); + switch ($this->getType()) { + case "lm": + $attrs["Type"] = "LearningModule"; + break; + } + $a_xml_writer->xmlStartTag("ContentObject", $attrs); + + // MetaData + $this->exportXMLMetaData($a_xml_writer); + + // StructureObjects + //echo "ContObj:".$a_inst.":
"; + $expLog->write(date("[y-m-d H:i:s] ") . "Start Export Structure Objects"); + $this->exportXMLStructureObjects($a_xml_writer, $a_inst, $expLog); + $expLog->write(date("[y-m-d H:i:s] ") . "Finished Export Structure Objects"); + + // PageObjects + $expLog->write(date("[y-m-d H:i:s] ") . "Start Export Page Objects"); + $this->exportXMLPageObjects($a_xml_writer, $a_inst, $expLog); + $expLog->write(date("[y-m-d H:i:s] ") . "Finished Export Page Objects"); + + // MediaObjects + $expLog->write(date("[y-m-d H:i:s] ") . "Start Export Media Objects"); + $this->exportXMLMediaObjects($a_xml_writer, $a_inst, $a_target_dir, $expLog); + $expLog->write(date("[y-m-d H:i:s] ") . "Finished Export Media Objects"); + + // FileItems + $expLog->write(date("[y-m-d H:i:s] ") . "Start Export File Items"); + $this->exportFileItems($a_target_dir, $expLog); + $expLog->write(date("[y-m-d H:i:s] ") . "Finished Export File Items"); + + // Questions + if (count($this->q_ids) > 0) { + $qti_file = fopen($a_target_dir . "/qti.xml", "w"); + include_once("./Modules/TestQuestionPool/classes/class.ilObjQuestionPool.php"); + $pool = new ilObjQuestionPool(); + fwrite($qti_file, $pool->questionsToXML($this->q_ids)); + fclose($qti_file); + } + + // To do: implement version selection/detection + // Properties + $expLog->write(date("[y-m-d H:i:s] ") . "Start Export Properties"); + $this->exportXMLProperties($a_xml_writer, $expLog); + $expLog->write(date("[y-m-d H:i:s] ") . "Finished Export Properties"); + + $a_xml_writer->xmlEndTag("ContentObject"); + } + + /** + * export content objects meta data to xml (see ilias_co.dtd) + * + * @param object $a_xml_writer ilXmlWriter object that receives the + * xml data + */ + public function exportXMLMetaData(&$a_xml_writer) + { + include_once("Services/MetaData/classes/class.ilMD2XML.php"); + $md2xml = new ilMD2XML($this->getId(), 0, $this->getType()); + $md2xml->setExportMode(true); + $md2xml->startExport(); + $a_xml_writer->appendXML($md2xml->getXML()); + } + + /** + * export structure objects to xml (see ilias_co.dtd) + * + * @param object $a_xml_writer ilXmlWriter object that receives the + * xml data + */ + public function exportXMLStructureObjects(&$a_xml_writer, $a_inst, &$expLog) + { + include_once './Modules/LearningModule/classes/class.ilStructureObject.php'; + + $childs = $this->lm_tree->getChilds($this->lm_tree->getRootId()); + foreach ($childs as $child) { + if ($child["type"] != "st") { + continue; + } + + $structure_obj = new ilStructureObject($this, $child["obj_id"]); + $structure_obj->exportXML($a_xml_writer, $a_inst, $expLog); + unset($structure_obj); + } + } + + + /** + * export page objects to xml (see ilias_co.dtd) + * + * @param object $a_xml_writer ilXmlWriter object that receives the + * xml data + */ + public function exportXMLPageObjects(&$a_xml_writer, $a_inst, &$expLog) + { + include_once "./Modules/LearningModule/classes/class.ilLMPageObject.php"; + include_once "./Modules/LearningModule/classes/class.ilLMPage.php"; + + $pages = ilLMPageObject::getPageList($this->getId()); + foreach ($pages as $page) { + if (ilLMPage::_exists($this->getType(), $page["obj_id"])) { + $expLog->write(date("[y-m-d H:i:s] ") . "Page Object " . $page["obj_id"]); + + // export xml to writer object + $page_obj = new ilLMPageObject($this, $page["obj_id"]); + $page_obj->exportXML($a_xml_writer, "normal", $a_inst); + + // collect media objects + $mob_ids = $page_obj->getMediaObjectIDs(); + foreach ($mob_ids as $mob_id) { + $this->mob_ids[$mob_id] = $mob_id; + } + + // collect all file items + $file_ids = $page_obj->getFileItemIds(); + foreach ($file_ids as $file_id) { + $this->file_ids[$file_id] = $file_id; + } + + // collect all questions + $q_ids = $page_obj->getQuestionIds(); + foreach ($q_ids as $q_id) { + $this->q_ids[$q_id] = $q_id; + } + + unset($page_obj); + } + } + } + + /** + * export media objects to xml (see ilias_co.dtd) + * + * @param object $a_xml_writer ilXmlWriter object that receives the + * xml data + */ + public function exportXMLMediaObjects(&$a_xml_writer, $a_inst, $a_target_dir, &$expLog) + { + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + + $linked_mobs = array(); + + // mobs directly embedded into pages + foreach ($this->mob_ids as $mob_id) { + if ($mob_id > 0 && ilObject::_lookupType($mob_id) == "mob") { + $expLog->write(date("[y-m-d H:i:s] ") . "Media Object " . $mob_id); + $media_obj = new ilObjMediaObject($mob_id); + $media_obj->exportXML($a_xml_writer, $a_inst); + $media_obj->exportFiles($a_target_dir); + + $lmobs = $media_obj->getLinkedMediaObjects($this->mob_ids); + $linked_mobs = array_merge($linked_mobs, $lmobs); + + unset($media_obj); + } + } + + // linked mobs (in map areas) + foreach ($linked_mobs as $mob_id) { + if ($mob_id > 0) { + $expLog->write(date("[y-m-d H:i:s] ") . "Media Object " . $mob_id); + $media_obj = new ilObjMediaObject($mob_id); + $media_obj->exportXML($a_xml_writer, $a_inst); + $media_obj->exportFiles($a_target_dir); + unset($media_obj); + } + } + } + + /** + * export files of file itmes + * + */ + public function exportFileItems($a_target_dir, &$expLog) + { + include_once("./Modules/File/classes/class.ilObjFile.php"); + + foreach ($this->file_ids as $file_id) { + $expLog->write(date("[y-m-d H:i:s] ") . "File Item " . $file_id); + $file_obj = new ilObjFile($file_id, false); + $file_obj->export($a_target_dir); + unset($file_obj); + } + } + + /** + * export properties of content object + * + */ + public function exportXMLProperties($a_xml_writer, &$expLog) + { + $attrs = array(); + $a_xml_writer->xmlStartTag("Properties", $attrs); + + // Layout + $attrs = array("Name" => "Layout", "Value" => $this->getLayout()); + $a_xml_writer->xmlElement("Property", $attrs); + + // Page Header + $attrs = array("Name" => "PageHeader", "Value" => $this->getPageHeader()); + $a_xml_writer->xmlElement("Property", $attrs); + + // TOC Mode + $attrs = array("Name" => "TOCMode", "Value" => $this->getTOCMode()); + $a_xml_writer->xmlElement("Property", $attrs); + + // LM Menu Activation + $attrs = array("Name" => "ActiveLMMenu", "Value" => + ilUtil::tf2yn($this->isActiveLMMenu())); + $a_xml_writer->xmlElement("Property", $attrs); + + // Numbering Activation + $attrs = array("Name" => "ActiveNumbering", "Value" => + ilUtil::tf2yn($this->isActiveNumbering())); + $a_xml_writer->xmlElement("Property", $attrs); + + // Table of contents button activation + $attrs = array("Name" => "ActiveTOC", "Value" => + ilUtil::tf2yn($this->isActiveTOC())); + $a_xml_writer->xmlElement("Property", $attrs); + + // Print view button activation + $attrs = array("Name" => "ActivePrintView", "Value" => + ilUtil::tf2yn($this->isActivePrintView())); + $a_xml_writer->xmlElement("Property", $attrs); + + // Note that download button is not saved, because + // download files do not exist after import + + // Clean frames + $attrs = array("Name" => "CleanFrames", "Value" => + ilUtil::tf2yn($this->cleanFrames())); + $a_xml_writer->xmlElement("Property", $attrs); + + // Public notes activation + $attrs = array("Name" => "PublicNotes", "Value" => + ilUtil::tf2yn($this->publicNotes())); + $a_xml_writer->xmlElement("Property", $attrs); + + // History comments for authors activation + $attrs = array("Name" => "HistoryUserComments", "Value" => + ilUtil::tf2yn($this->isActiveHistoryUserComments())); + $a_xml_writer->xmlElement("Property", $attrs); + + // Rating + $attrs = array("Name" => "Rating", "Value" => + ilUtil::tf2yn($this->hasRating())); + $a_xml_writer->xmlElement("Property", $attrs); + $attrs = array("Name" => "RatingPages", "Value" => + ilUtil::tf2yn($this->hasRatingPages())); + $a_xml_writer->xmlElement("Property", $attrs); + + // Header Page + if ($this->getHeaderPage() > 0) { + $attrs = array("Name" => "HeaderPage", "Value" => + "il_" . IL_INST_ID . "_pg_" . $this->getHeaderPage()); + $a_xml_writer->xmlElement("Property", $attrs); + } + + // Footer Page + if ($this->getFooterPage() > 0) { + $attrs = array("Name" => "FooterPage", "Value" => + "il_" . IL_INST_ID . "_pg_" . $this->getFooterPage()); + $a_xml_writer->xmlElement("Property", $attrs); + } + + // layout per page + $attrs = array("Name" => "LayoutPerPage", "Value" => + $this->getLayoutPerPage()); + $a_xml_writer->xmlElement("Property", $attrs); + + // progress icons + $attrs = array("Name" => "ProgressIcons", "Value" => + $this->getProgressIcons()); + $a_xml_writer->xmlElement("Property", $attrs); + + // store tries + $attrs = array("Name" => "StoreTries", "Value" => + $this->getStoreTries()); + $a_xml_writer->xmlElement("Property", $attrs); + + // restrict forward navigation + $attrs = array("Name" => "RestrictForwardNavigation", "Value" => + $this->getRestrictForwardNavigation()); + $a_xml_writer->xmlElement("Property", $attrs); + + // disable default feedback + $attrs = array("Name" => "DisableDefaultFeedback", "Value" => + $this->getDisableDefaultFeedback()); + $a_xml_writer->xmlElement("Property", $attrs); + + $a_xml_writer->xmlEndTag("Properties"); + } + + /** + * get export files + */ + public function getExportFiles() + { + $file = array(); + + $types = array("xml", "html", "scorm"); + + foreach ($types as $type) { + $dir = $this->getExportDirectory($type); + // quit if import dir not available + if (!@is_dir($dir) or + !is_writeable($dir)) { + continue; + } + + // open directory + $cdir = dir($dir); + + // initialize array + + // get files and save the in the array + while ($entry = $cdir->read()) { + if ($entry != "." and + $entry != ".." and + substr($entry, -4) == ".zip" and + preg_match("~^[0-9]{10}_{2}[0-9]+_{2}(lm_)*[0-9]+\.zip\$~", $entry)) { + $file[$entry . $type] = array("type" => $type, "file" => $entry, + "size" => filesize($dir . "/" . $entry)); + } + } + + // close import directory + $cdir->close(); + } + + // sort files + ksort($file); + reset($file); + return $file; + } + + /** + * specify public export file for type + * + * @param string $a_type type ("xml" / "html") + * @param string $a_file file name + */ + public function setPublicExportFile($a_type, $a_file) + { + $this->public_export_file[$a_type] = $a_file; + } + + /** + * get public export file + * + * @param string $a_type type ("xml" / "html") + * + * @return string $a_file file name + */ + public function getPublicExportFile($a_type) + { + return $this->public_export_file[$a_type]; + } + + /** + * get offline files + */ + public function getOfflineFiles($dir) + { + // quit if offline dir not available + if (!@is_dir($dir) or + !is_writeable($dir)) { + return array(); + } + + // open directory + $dir = dir($dir); + + // initialize array + $file = array(); + + // get files and save the in the array + while ($entry = $dir->read()) { + if ($entry != "." and + $entry != ".." and + substr($entry, -4) == ".pdf" and + preg_match("~^[0-9]{10}_{2}[0-9]+_{2}(lm_)*[0-9]+\.pdf\$~", $entry)) { + $file[] = $entry; + } + } + + // close import directory + $dir->close(); + + // sort files + sort($file); + reset($file); + + return $file; + } + + /** + * export scorm package + */ + public function exportSCORM($a_target_dir, $log) + { + ilUtil::delDir($a_target_dir); + ilUtil::makeDir($a_target_dir); + //ilUtil::makeDir($a_target_dir."/res"); + + // export everything to html + $this->exportHTML($a_target_dir . "/res", $log, false, "scorm"); + + // build manifest file + include("./Modules/LearningModule/classes/class.ilLMContObjectManifestBuilder.php"); + $man_builder = new ilLMContObjectManifestBuilder($this); + $man_builder->buildManifest(); + $man_builder->dump($a_target_dir); + + // copy scorm 1.2 schema definitions + copy("Modules/LearningModule/scorm_xsd/adlcp_rootv1p2.xsd", $a_target_dir . "/adlcp_rootv1p2.xsd"); + copy("Modules/LearningModule/scorm_xsd/imscp_rootv1p1p2.xsd", $a_target_dir . "/imscp_rootv1p1p2.xsd"); + copy("Modules/LearningModule/scorm_xsd/imsmd_rootv1p2p1.xsd", $a_target_dir . "/imsmd_rootv1p2p1.xsd"); + copy("Modules/LearningModule/scorm_xsd/ims_xml.xsd", $a_target_dir . "/ims_xml.xsd"); + + // zip it all + $date = time(); + $zip_file = $a_target_dir . "/" . $date . "__" . IL_INST_ID . "__" . + $this->getType() . "_" . $this->getId() . ".zip"; + //echo "zip-".$a_target_dir."-to-".$zip_file; + ilUtil::zip(array($a_target_dir . "/res", + $a_target_dir . "/imsmanifest.xml", + $a_target_dir . "/adlcp_rootv1p2.xsd", + $a_target_dir . "/imscp_rootv1p1p2.xsd", + $a_target_dir . "/ims_xml.xsd", + $a_target_dir . "/imsmd_rootv1p2p1.xsd"), $zip_file); + + $dest_file = $this->getExportDirectory("scorm") . "/" . $date . "__" . IL_INST_ID . "__" . + $this->getType() . "_" . $this->getId() . ".zip"; + + rename($zip_file, $dest_file); + ilUtil::delDir($a_target_dir); + } + + + /** + * export html package + */ + public function exportHTML($a_target_dir, $log, $a_zip_file = true, $a_export_format = "html", $a_lang = "") + { + $tpl = $this->tpl; + $ilLocator = $this->locator; + $ilUser = $this->user; + + $user_lang = $ilUser->getLanguage(); + + // initialize temporary target directory + ilUtil::delDir($a_target_dir); + ilUtil::makeDir($a_target_dir); + $mob_dir = $a_target_dir . "/mobs"; + ilUtil::makeDir($mob_dir); + $file_dir = $a_target_dir . "/files"; + ilUtil::makeDir($file_dir); + $teximg_dir = $a_target_dir . "/teximg"; + ilUtil::makeDir($teximg_dir); + $style_dir = $a_target_dir . "/style"; + ilUtil::makeDir($style_dir); + $style_img_dir = $a_target_dir . "/style/images"; + ilUtil::makeDir($style_img_dir); + $content_style_dir = $a_target_dir . "/content_style"; + ilUtil::makeDir($content_style_dir); + $content_style_img_dir = $a_target_dir . "/content_style/images"; + ilUtil::makeDir($content_style_img_dir); // init the mathjax rendering for HTML export - include_once './Services/MathJax/classes/class.ilMathJax.php'; - ilMathJax::getInstance()->init(ilMathJax::PURPOSE_EXPORT); - - // export system style sheet - $location_stylesheet = ilUtil::getStyleSheetLocation("filesystem"); - $style_name = $ilUser->prefs["style"].".css"; - copy($location_stylesheet, $style_dir."/".$style_name); - $fh = fopen($location_stylesheet, "r"); - $css = fread($fh, filesize($location_stylesheet)); - preg_match_all("/url\(([^\)]*)\)/",$css,$files); - foreach (array_unique($files[1]) as $fileref) - { - $css_fileref = str_replace(array("'", '"'), "", $fileref); - $fileref = dirname($location_stylesheet)."/".$css_fileref; - if (is_file($fileref)) - { -//echo "
make dir: ".dirname($style_dir."/".$css_fileref); - ilUtil::makeDirParents(dirname($style_dir."/".$css_fileref)); -//echo "
copy: ".$fileref." TO ".$style_dir."/".$css_fileref; - copy($fileref, $style_dir."/".$css_fileref); - } - } - fclose($fh); - $location_stylesheet = ilUtil::getStyleSheetLocation(); - - // export content style sheet - if ($this->getStyleSheetId() < 1) - { - $cont_stylesheet = "./Services/COPage/css/content.css"; - - $css = fread(fopen($cont_stylesheet,'r'),filesize($cont_stylesheet)); - preg_match_all("/url\(([^\)]*)\)/",$css,$files); - foreach (array_unique($files[1]) as $fileref) - { - $target_fileref = str_replace("..", ".", $fileref); - $target_fileref = str_replace('"', "", $target_fileref); - if (is_file($target_fileref)) - { - copy($target_fileref, $content_style_img_dir."/".basename($target_fileref)); - } - $css = str_replace($fileref, "images/".basename($target_fileref),$css); - } - fwrite(fopen($content_style_dir."/content.css",'w'),$css); - } - else - { - $style = new ilObjStyleSheet($this->getStyleSheetId()); - $style->writeCSSFile($content_style_dir."/content.css", "images"); - $style->copyImagesToDir($content_style_img_dir); - } - - // export syntax highlighting style - $syn_stylesheet = ilObjStyleSheet::getSyntaxStylePath(); - copy($syn_stylesheet, $a_target_dir."/syntaxhighlight.css"); - - // get learning module presentation gui class - include_once("./Modules/LearningModule/classes/class.ilLMPresentationGUI.php"); - $_GET["cmd"] = "nop"; - $get_transl = $_GET["transl"]; - $_GET["transl"] = ""; - $lm_gui = new ilLMPresentationGUI(); - $lm_gui->setOfflineMode(true, ($a_lang == "all")); - $lm_gui->setOfflineDirectory($a_target_dir); - $lm_gui->setExportFormat($a_export_format); - - $ot = ilObjectTranslation::getInstance($this->getId()); - $langs = array(); - if ($a_lang != "all") - { - $langs = array($a_lang); - } - else - { - $ot_langs = $ot->getLanguages(); - foreach ($ot_langs as $otl) - { - $langs[] = $otl["lang_code"]; - } - } - - // init collector arrays - $this->offline_mobs = array(); - $this->offline_int_links = array(); - $this->offline_files = array(); - - // iterate all languages - foreach ($langs as $lang) - { - - if ($lang != "") - { - $ilUser->setLanguage($lang); - $ilUser->setCurrentLanguage($lang); - } - else - { - $ilUser->setLanguage($user_lang); - $ilUser->setCurrentLanguage($user_lang); - } - - if ($lang != "") - { - if ($lang == $ot->getMasterLanguage()) - { - $lm_gui->lang = ""; - } - else - { - $lm_gui->lang = $lang; - } - } - - // export pages - // now: forward ("all" info to export files and links) - $this->exportHTMLPages($lm_gui, $a_target_dir, $lm_gui->lang, ($a_lang == "all")); - - // export table of contents - $ilLocator->clearItems(); - if ($this->isActiveTOC()) - { - $tpl = new ilTemplate("tpl.main.html", true, true); - - $GLOBALS["tpl"] = $tpl; - - $lm_gui->tpl = $tpl; - $content = $lm_gui->showTableOfContents(); - //var_dump($content); exit; - if ($a_lang == "all") - { - $file = $a_target_dir . "/table_of_contents_".$lang.".html"; - } - else - { - $file = $a_target_dir . "/table_of_contents.html"; - } - - // open file - if (!($fp = @fopen($file,"w+"))) - { - die ("Error: Could not open \"".$file."\" for writing". - " in ".__FILE__." on line ".__LINE__."
"); - } - chmod($file, 0770); - fwrite($fp, $content); - fclose($fp); - } - } - - // export glossary terms - $this->exportHTMLGlossaryTerms($lm_gui, $a_target_dir); - - // export all media objects - $linked_mobs = array(); - foreach ($this->offline_mobs as $mob) - { - if (ilObject::_exists($mob) && ilObject::_lookupType($mob) == "mob") - { - $this->exportHTMLMOB($a_target_dir, $lm_gui, $mob, "_blank", $linked_mobs); - } - } - $linked_mobs2 = array(); // mobs linked in link areas - foreach ($linked_mobs as $mob) - { - if (ilObject::_exists($mob)) - { - $this->exportHTMLMOB($a_target_dir, $lm_gui, $mob, "_blank", $linked_mobs2); - } - } - $_GET["obj_type"] = "MediaObject"; - $_GET["obj_id"] = $a_mob_id; - $_GET["cmd"] = ""; - - // export all file objects - foreach ($this->offline_files as $file) - { - $this->exportHTMLFile($a_target_dir, $file); - } - - // export questions (images) - if (count($this->q_ids) > 0) - { - foreach ($this->q_ids as $q_id) - { - ilUtil::makeDirParents($a_target_dir."/assessment/0/".$q_id."/images"); - ilUtil::rCopy(ilUtil::getWebspaceDir()."/assessment/0/".$q_id."/images", - $a_target_dir."/assessment/0/".$q_id."/images"); - } - } - - // export images - $image_dir = $a_target_dir."/images"; - ilUtil::makeDir($image_dir); - ilUtil::makeDir($image_dir."/browser"); - copy(ilUtil::getImagePath("enlarge.svg", false, "filesystem"), - $image_dir."/enlarge.svg"); - copy(ilUtil::getImagePath("browser/blank.png", false, "filesystem"), - $image_dir."/browser/plus.png"); - copy(ilUtil::getImagePath("browser/blank.png", false, "filesystem"), - $image_dir."/browser/minus.png"); - copy(ilUtil::getImagePath("browser/blank.png", false, "filesystem"), - $image_dir."/browser/blank.png"); - copy(ilUtil::getImagePath("spacer.png", false, "filesystem"), - $image_dir."/spacer.png"); - copy(ilUtil::getImagePath("icon_st.svg", false, "filesystem"), - $image_dir."/icon_st.svg"); - copy(ilUtil::getImagePath("icon_pg.svg", false, "filesystem"), - $image_dir."/icon_pg.svg"); - copy(ilUtil::getImagePath("icon_lm.svg", false, "filesystem"), - $image_dir."/icon_lm.svg"); - copy(ilUtil::getImagePath("nav_arr_L.png", false, "filesystem"), - $image_dir."/nav_arr_L.png"); - copy(ilUtil::getImagePath("nav_arr_R.png", false, "filesystem"), - $image_dir."/nav_arr_R.png"); - - // export flv/mp3 player - $services_dir = $a_target_dir."/Services"; - ilUtil::makeDir($services_dir); - $media_service_dir = $services_dir."/MediaObjects"; - ilUtil::makeDir($media_service_dir); - include_once("./Services/MediaObjects/classes/class.ilPlayerUtil.php"); - $flv_dir = $a_target_dir."/".ilPlayerUtil::getFlashVideoPlayerDirectory(); - ilUtil::makeDirParents($flv_dir); - $mp3_dir = $media_service_dir."/flash_mp3_player"; - ilUtil::makeDir($mp3_dir); -// copy(ilPlayerUtil::getFlashVideoPlayerFilename(true), -// $flv_dir."/".ilPlayerUtil::getFlashVideoPlayerFilename()); - ilPlayerUtil::copyPlayerFilesToTargetDirectory($flv_dir); - include_once("./Services/UIComponent/Explorer2/classes/class.ilExplorerBaseGUI.php"); - ilExplorerBaseGUI::createHTMLExportDirs($a_target_dir); - ilPlayerUtil::copyPlayerFilesToTargetDirectory($flv_dir); - - // js files - ilUtil::makeDir($a_target_dir.'/js'); - ilUtil::makeDir($a_target_dir.'/js/yahoo'); - ilUtil::makeDir($a_target_dir.'/css'); - include_once("./Services/YUI/classes/class.ilYuiUtil.php"); - foreach (self::getSupplyingExportFiles($a_target_dir) as $f) - { - if ($f["source"] != "") - { - ilUtil::makeDirParents(dirname($f["target"])); - copy($f["source"], $f["target"]); - } - } - // template workaround: reset of template - $tpl = new ilTemplate("tpl.main.html", true, true); - $tpl->setVariable("LOCATION_STYLESHEET",$location_stylesheet); - $tpl->addBlockFile("CONTENT", "content", "tpl.adm_content.html"); - - if ($a_lang != "") - { - $ilUser->setLanguage($user_lang); - $ilUser->setCurrentLanguage($user_lang); - } - - // zip everything - if ($a_zip_file) - { - if ($a_lang == "") - { - $zip_target_dir = $this->getExportDirectory("html"); - } - else - { - $zip_target_dir = $this->getExportDirectory("html_".$a_lang); - ilUtil::makeDir($zip_target_dir); - } - - // zip it all - $date = time(); - $zip_file = $zip_target_dir."/".$date."__".IL_INST_ID."__". - $this->getType()."_".$this->getId().".zip"; -//echo "-".$a_target_dir."-".$zip_file."-"; exit; - ilUtil::zip($a_target_dir, $zip_file); - ilUtil::delDir($a_target_dir); - } - } - - /** - * Get supplying export files - * - * @param - * @return - */ - static function getSupplyingExportFiles($a_target_dir = ".") - { - include_once("./Services/YUI/classes/class.ilYuiUtil.php"); - include_once("./Services/jQuery/classes/class.iljQueryUtil.php"); - include_once("./Services/MediaObjects/classes/class.ilPlayerUtil.php"); - include_once("./Services/UIComponent/Explorer2/classes/class.ilExplorerBaseGUI.php"); - $scripts = array( - array("source" => ilYuiUtil::getLocalPath('yahoo/yahoo-min.js'), - "target" => $a_target_dir.'/js/yahoo/yahoo-min.js', - "type" => "js"), - array("source" => ilYuiUtil::getLocalPath('yahoo-dom-event/yahoo-dom-event.js'), - "target" => $a_target_dir.'/js/yahoo/yahoo-dom-event.js', - "type" => "js"), - array("source" => ilYuiUtil::getLocalPath('animation/animation-min.js'), - "target" => $a_target_dir.'/js/yahoo/animation-min.js', - "type" => "js"), - array("source" => './Services/JavaScript/js/Basic.js', - "target" => $a_target_dir.'/js/Basic.js', - "type" => "js"), - array("source" => './Services/Accordion/js/accordion.js', - "target" => $a_target_dir.'/js/accordion.js', - "type" => "js"), - array("source" => './Services/Accordion/css/accordion.css', - "target" => $a_target_dir.'/css/accordion.css', - "type" => "css"), - array("source" => iljQueryUtil::getLocaljQueryPath(), - "target" => $a_target_dir.'/js/jquery.js', - "type" => "js"), - array("source" => iljQueryUtil::getLocalMaphilightPath(), - "target" => $a_target_dir.'/js/maphilight.js', - "type" => "js"), - array("source" => iljQueryUtil::getLocaljQueryUIPath(), - "target" => $a_target_dir.'/js/jquery-ui-min.js', - "type" => "js"), - array("source" => './Services/COPage/js/ilCOPagePres.js', - "target" => $a_target_dir.'/js/ilCOPagePres.js', - "type" => "js"), - array("source" => './Modules/Scorm2004/scripts/questions/pure.js', - "target" => $a_target_dir.'/js/pure.js', - "type" => "js"), - array("source" => './Modules/Scorm2004/scripts/questions/question_handling.js', - "target" => $a_target_dir.'/js/question_handling.js', - "type" => "js"), - array("source" => './Modules/TestQuestionPool/js/ilMatchingQuestion.js', - "target" => $a_target_dir.'/js/ilMatchingQuestion.js', - "type" => "js"), - array("source" => './Modules/Scorm2004/templates/default/question_handling.css', - "target" => $a_target_dir.'/css/question_handling.css', - "type" => "css"), - array("source" => './Modules/TestQuestionPool/templates/default/test_javascript.css', - "target" => $a_target_dir.'/css/test_javascript.css', - "type" => "css"), - array("source" => ilPlayerUtil::getLocalMediaElementJsPath(), - "target" => $a_target_dir."/".ilPlayerUtil::getLocalMediaElementJsPath(), - "type" => "js"), - array("source" => ilPlayerUtil::getLocalMediaElementCssPath(), - "target" => $a_target_dir."/".ilPlayerUtil::getLocalMediaElementCssPath(), - "type" => "css"), - array("source" => ilExplorerBaseGUI::getLocalExplorerJsPath(), - "target" => $a_target_dir."/".ilExplorerBaseGUI::getLocalExplorerJsPath(), - "type" => "js"), - array("source" => ilExplorerBaseGUI::getLocalJsTreeJsPath(), - "target" => $a_target_dir."/".ilExplorerBaseGUI::getLocalJsTreeJsPath(), - "type" => "js"), - array("source" => ilExplorerBaseGUI::getLocalJsTreeCssPath(), - "target" => $a_target_dir."/".ilExplorerBaseGUI::getLocalJsTreeCssPath(), - "type" => "css"), - array("source" => './Modules/LearningModule/js/LearningModule.js', - "target" => $a_target_dir.'/js/LearningModule.js', - "type" => "js") - ); - - $mathJaxSetting = new ilSetting("MathJax"); - $use_mathjax = $mathJaxSetting->get("enable"); - if ($use_mathjax) - { - $scripts[] = array("source" => "", - "target" => $mathJaxSetting->get("path_to_mathjax"), - "type" => "js"); - } - - // auto linking js - include_once("./Services/Link/classes/class.ilLinkifyUtil.php"); - foreach (ilLinkifyUtil::getLocalJsPaths() as $p) - { - if (is_int(strpos($p, "ExtLink"))) - { - $scripts[] = array("source" => $p, - "target" => $a_target_dir.'/js/ilExtLink.js', - "type" => "js"); - } - if (is_int(strpos($p, "linkify"))) - { - $scripts[] = array("source" => $p, - "target" => $a_target_dir.'/js/linkify.js', - "type" => "js"); - } - } - - return $scripts; - - } - - /** - * export file object - */ - function exportHTMLFile($a_target_dir, $a_file_id) - { - $file_dir = $a_target_dir."/files/file_".$a_file_id; - ilUtil::makeDir($file_dir); - include_once("./Modules/File/classes/class.ilObjFile.php"); - $file_obj = new ilObjFile($a_file_id, false); - $source_file = $file_obj->getDirectory($file_obj->getVersion())."/".$file_obj->getFileName(); - if (!is_file($source_file)) - { - $source_file = $file_obj->getDirectory()."/".$file_obj->getFileName(); - } - if (is_file($source_file)) - { - copy($source_file, $file_dir."/".$file_obj->getFileName()); - } - } - - /** - * export media object to html - */ - function exportHTMLMOB($a_target_dir, &$a_lm_gui, $a_mob_id, $a_frame, &$a_linked_mobs) - { - $tpl = $this->tpl; - - $mob_dir = $a_target_dir."/mobs"; - - $source_dir = ilUtil::getWebspaceDir()."/mobs/mm_".$a_mob_id; - if (@is_dir($source_dir)) - { - ilUtil::makeDir($mob_dir."/mm_".$a_mob_id); - ilUtil::rCopy($source_dir, $mob_dir."/mm_".$a_mob_id); - } - - $tpl = new ilTemplate("tpl.main.html", true, true); - $tpl->addBlockFile("CONTENT", "content", "tpl.adm_content.html"); - $_GET["obj_type"] = "MediaObject"; - $_GET["mob_id"] = $a_mob_id; - $_GET["frame"] = $a_frame; - $_GET["cmd"] = ""; - $content = $a_lm_gui->media(); - $file = $a_target_dir."/media_".$a_mob_id.".html"; - - // open file - if (!($fp = @fopen($file,"w+"))) - { - die ("Error: Could not open \"".$file."\" for writing". - " in ".__FILE__." on line ".__LINE__."
"); - } - chmod($file, 0770); - fwrite($fp, $content); - fclose($fp); - - // fullscreen - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $mob_obj = new ilObjMediaObject($a_mob_id); - if ($mob_obj->hasFullscreenItem()) - { - $tpl = new ilTemplate("tpl.main.html", true, true); - $tpl->addBlockFile("CONTENT", "content", "tpl.adm_content.html"); - $_GET["obj_type"] = ""; - $_GET["frame"] = ""; - $_GET["mob_id"] = $a_mob_id; - $_GET["cmd"] = "fullscreen"; - $content = $a_lm_gui->fullscreen(); - $file = $a_target_dir."/fullscreen_".$a_mob_id.".html"; - - // open file - if (!($fp = @fopen($file,"w+"))) - { - die ("Error: Could not open \"".$file."\" for writing". - " in ".__FILE__." on line ".__LINE__."
"); - } - chmod($file, 0770); - fwrite($fp, $content); - fclose($fp); - } - $linked_mobs = $mob_obj->getLinkedMediaObjects(); - foreach ($linked_mobs as $id) - { - $this->log->debug("HTML Export: Add media object $id (".ilObject::_lookupTitle($id).") ". - " due to media object ".$a_mob_id." (".ilObject::_lookupTitle($a_mob_id).")."); - } - $a_linked_mobs = array_merge($a_linked_mobs, $linked_mobs); - } - - /** - * export glossary terms - */ - function exportHTMLGlossaryTerms(&$a_lm_gui, $a_target_dir) - { - $ilLocator = $this->locator; - - foreach($this->offline_int_links as $int_link) - { - $ilLocator->clearItems(); - if ($int_link["type"] == "git") - { - $tpl = new ilTemplate("tpl.main.html", true, true); - $tpl->addBlockFile("CONTENT", "content", "tpl.adm_content.html"); - - $_GET["obj_id"] = $int_link["id"]; - $_GET["frame"] = "_blank"; - $content = $a_lm_gui->glossary(); - $file = $a_target_dir."/term_".$int_link["id"].".html"; - - // open file - if (!($fp = @fopen($file,"w+"))) - { - die ("Error: Could not open \"".$file."\" for writing". - " in ".__FILE__." on line ".__LINE__."
"); - } - chmod($file, 0770); - fwrite($fp, $content); - fclose($fp); - - // store linked/embedded media objects of glosssary term - include_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); - $defs = ilGlossaryDefinition::getDefinitionList($int_link["id"]); - foreach($defs as $def) - { - $def_mobs = ilObjMediaObject::_getMobsOfObject("gdf:pg", $def["id"]); - foreach($def_mobs as $def_mob) - { - $this->offline_mobs[$def_mob] = $def_mob; - include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - $this->log->debug("HTML Export: Add media object $def_mob (".ilObject::_lookupTitle($def_mob).") ". - " due to glossary entry ".$int_link["id"]." (".ilGlossaryTerm::_lookGlossaryTerm($int_link["id"]).")."); - } - - // get all files of page - $def_files = ilObjFile::_getFilesOfObject("gdf:pg", $page["obj_id"]); - $this->offline_files = array_merge($this->offline_files, $def_files); - - } - - } - } - } - - /** - * export all pages of learning module to html file - */ - function exportHTMLPages(&$a_lm_gui, $a_target_dir, $a_lang = "", $a_all_languages = false) - { - $ilLocator = $this->locator; - - $pages = ilLMPageObject::getPageList($this->getId()); - - $lm_tree = $this->getLMTree(); - $first_page = $lm_tree->fetchSuccessorNode($lm_tree->getRootId(), "pg"); - $this->first_page_id = $first_page["child"]; - - // iterate all learning module pages - $mobs = array(); - $int_links = array(); - $this->offline_files = array(); - - include_once("./Services/COPage/classes/class.ilPageContentUsage.php"); - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - - // get html export id mapping - $lm_set = new ilSetting("lm"); - $exp_id_map = array(); - - if ($lm_set->get("html_export_ids")) - { - foreach ($pages as $page) - { - $exp_id = ilLMPageObject::getExportId($this->getId(), $page["obj_id"]); - if (trim($exp_id) != "") - { - $exp_id_map[$page["obj_id"]] = trim($exp_id); - } - } - } -//exit; - if ($a_lang == "") - { - $a_lang = "-"; - } - - reset($pages); - foreach ($pages as $page) - { - if (ilLMPage::_exists($this->getType(), $page["obj_id"])) - { - $ilLocator->clearItems(); - $this->exportPageHTML($a_lm_gui, $a_target_dir, $page["obj_id"], - "", $exp_id_map, $a_lang, $a_all_languages); - - // get all snippets of page - $pcs = ilPageContentUsage::getUsagesOfPage($page["obj_id"], $this->getType().":pg", 0, false, $a_lang); - foreach ($pcs as $pc) - { - if ($pc["type"] == "incl") - { - $incl_mobs = ilObjMediaObject::_getMobsOfObject("mep:pg", $pc["id"]); - foreach($incl_mobs as $incl_mob) - { - $mobs[$incl_mob] = $incl_mob; - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - $this->log->debug("HTML Export: Add media object $incl_mob (".ilObject::_lookupTitle($incl_mob).") ". - " due to snippet ".$pc["id"]." in page ".$page["obj_id"]." (".ilLMObject::_lookupTitle($page["obj_id"]).")."); - } - } - } - - // get all media objects of page - $pg_mobs = ilObjMediaObject::_getMobsOfObject($this->getType().":pg", $page["obj_id"], 0, $a_lang); - foreach($pg_mobs as $pg_mob) - { - $mobs[$pg_mob] = $pg_mob; - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - $this->log->debug("HTML Export: Add media object $pg_mob (".ilObject::_lookupTitle($pg_mob).") ". - " due to page ".$page["obj_id"]." (".ilLMObject::_lookupTitle($page["obj_id"]).")."); - } - - // get all internal links of page - $pg_links = ilInternalLink::_getTargetsOfSource($this->getType().":pg", $page["obj_id"], $a_lang); - $int_links = array_merge($int_links, $pg_links); - - // get all files of page - include_once("./Modules/File/classes/class.ilObjFile.php"); - $pg_files = ilObjFile::_getFilesOfObject($this->getType().":pg", $page["obj_id"], 0, $a_lang); - $this->offline_files = array_merge($this->offline_files, $pg_files); - - // collect all questions - include_once("./Services/COPage/classes/class.ilPCQuestion.php"); - $q_ids = ilPCQuestion::_getQuestionIdsForPage($this->getType(), $page["obj_id"], $a_lang); - foreach($q_ids as $q_id) - { - $this->q_ids[$q_id] = $q_id; - } - - } - } - foreach ($mobs as $m) - { - $this->offline_mobs[$m] = $m; - } - foreach ($int_links as $k => $v) - { - $this->offline_int_links[$k] = $v; - } - } - - - - /** - * export page html - */ - function exportPageHTML(&$a_lm_gui, $a_target_dir, $a_lm_page_id, $a_frame = "", - $a_exp_id_map = array(), $a_lang = "-", $a_all_languages = false) - { - $tpl = $this->tpl; - - $lang_suffix = ""; - if ($a_lang != "-" && $a_lang != "" && $a_all_languages) - { - $lang_suffix = "_".$a_lang; - } - -//echo "
B: export Page HTML ($a_lm_page_id)"; flush(); - // template workaround: reset of template - $tpl = new ilTemplate("tpl.main.html", true, true); - $tpl->addBlockFile("CONTENT", "content", "tpl.adm_content.html"); - - include_once("./Services/COPage/classes/class.ilPCQuestion.php"); - ilPCQuestion::resetInitialState(); - - $_GET["obj_id"] = $a_lm_page_id; - $_GET["frame"] = $a_frame; - - if ($a_frame == "") - { - //if ($nid = ilLMObject::_lookupNID($a_lm_gui->lm->getId(), $a_lm_page_id, "pg")) - if (is_array($a_exp_id_map) && isset($a_exp_id_map[$a_lm_page_id])) - { - $file = $a_target_dir."/lm_pg_".$a_exp_id_map[$a_lm_page_id].$lang_suffix.".html"; - } - else - { - $file = $a_target_dir."/lm_pg_".$a_lm_page_id.$lang_suffix.".html"; - } - } - else - { - if ($a_frame != "toc") - { - $file = $a_target_dir."/frame_".$a_lm_page_id."_".$a_frame.$lang_suffix.".html"; - } - else - { - $file = $a_target_dir."/frame_".$a_frame.$lang_suffix.".html"; - } - } - - // return if file is already existing - if (@is_file($file)) - { - return; - } - - $content = $a_lm_gui->layout("main.xml", false); - - // open file - if (!($fp = @fopen($file,"w+"))) - { - die ("Error: Could not open \"".$file."\" for writing". - " in ".__FILE__." on line ".__LINE__."
"); - } - - // set file permissions - chmod($file, 0770); - - // write xml data into the file - fwrite($fp, $content); - - // close file - fclose($fp); - - if ($this->first_page_id == $a_lm_page_id && $a_frame == "") - { - copy($file, $a_target_dir."/index".$lang_suffix.".html"); - } - - // write frames of frameset - $frameset = $a_lm_gui->getCurrentFrameSet(); - - foreach ($frameset as $frame) - { - $this->exportPageHTML($a_lm_gui, $a_target_dir, $a_lm_page_id, $frame); - } - - } - - /** - * export object to fo - * - * @param object $a_xml_writer ilXmlWriter object that receives the - * xml data - */ - function exportFO(&$a_xml_writer, $a_target_dir) - { - // fo:root (start) - $attrs = array(); - $attrs["xmlns:fo"] = "http://www.w3.org/1999/XSL/Format"; - $a_xml_writer->xmlStartTag("fo:root", $attrs); - - // fo:layout-master-set (start) - $attrs = array(); - $a_xml_writer->xmlStartTag("fo:layout-master-set", $attrs); - - // fo:simple-page-master (start) - $attrs = array(); - $attrs["master-name"] = "DinA4"; - $attrs["page-height"] = "29.7cm"; - $attrs["page-width"] = "21cm"; - $attrs["margin-top"] = "4cm"; - $attrs["margin-bottom"] = "1cm"; - $attrs["margin-left"] = "2.8cm"; - $attrs["margin-right"] = "7.3cm"; - $a_xml_writer->xmlStartTag("fo:simple-page-master", $attrs); - - // fo:region-body (complete) - $attrs = array(); - $attrs["margin-top"] = "0cm"; - $attrs["margin-bottom"] = "1.25cm"; - $a_xml_writer->xmlElement("fo:region-body", $attrs); - - // fo:region-before (complete) - $attrs = array(); - $attrs["extent"] = "1cm"; - $a_xml_writer->xmlElement("fo:region-before", $attrs); - - // fo:region-after (complete) - $attrs = array(); - $attrs["extent"] = "1cm"; - $a_xml_writer->xmlElement("fo:region-after", $attrs); - - // fo:simple-page-master (end) - $a_xml_writer->xmlEndTag("fo:simple-page-master"); - - // fo:layout-master-set (end) - $a_xml_writer->xmlEndTag("fo:layout-master-set"); - - // fo:page-sequence (start) - $attrs = array(); - $attrs["master-reference"] = "DinA4"; - $a_xml_writer->xmlStartTag("fo:page-sequence", $attrs); - - // fo:flow (start) - $attrs = array(); - $attrs["flow-name"] = "xsl-region-body"; - $a_xml_writer->xmlStartTag("fo:flow", $attrs); - - - // StructureObjects - $this->exportFOStructureObjects($a_xml_writer, $expLog); - - // fo:flow (end) - $a_xml_writer->xmlEndTag("fo:flow"); - - // fo:page-sequence (end) - $a_xml_writer->xmlEndTag("fo:page-sequence"); - - // fo:root (end) - $a_xml_writer->xmlEndTag("fo:root"); - } - - /** - * export structure objects to fo - * - * @param object $a_xml_writer ilXmlWriter object that receives the - * xml data - */ - function exportFOStructureObjects(&$a_xml_writer) - { - $childs = $this->lm_tree->getChilds($this->lm_tree->getRootId()); - foreach ($childs as $child) - { - if($child["type"] != "st") - { - continue; - } - - $structure_obj = new ilStructureObject($this, $child["obj_id"]); - $structure_obj->exportFO($a_xml_writer, $expLog); - unset($structure_obj); - } - } - - function getXMLZip() - { - include_once("./Modules/LearningModule/classes/class.ilContObjectExport.php"); - - $cont_exp = new ilContObjectExport($this,'xml'); - - $export_file = $cont_exp->buildExportFile(); - return $export_file; - } - - /** - * Execute Drag Drop Action - * - * @param string $source_id Source element ID - * @param string $target_id Target element ID - * @param string $first_child Insert as first child of target - * @param string $movecopy Position ("move" | "copy") - */ - function executeDragDrop($source_id, $target_id, $first_child, $as_subitem = false, $movecopy = "move") - { - $lmtree = new ilTree($this->getId()); - $lmtree->setTableNames('lm_tree','lm_data'); - $lmtree->setTreeTablePK("lm_id"); -//echo "-".$source_id."-".$target_id."-".$first_child."-".$as_subitem."-"; - $source_obj = ilLMObjectFactory::getInstance($this, $source_id, true); - $source_obj->setLMId($this->getId()); - - if (!$first_child) - { - $target_obj = ilLMObjectFactory::getInstance($this, $target_id, true); - $target_obj->setLMId($this->getId()); - $target_parent = $lmtree->getParentId($target_id); - } - - // handle pages - if ($source_obj->getType() == "pg") - { -//echo "1"; - if ($lmtree->isInTree($source_obj->getId())) - { - $node_data = $lmtree->getNodeData($source_obj->getId()); - - // cut on move - if ($movecopy == "move") - { - $parent_id = $lmtree->getParentId($source_obj->getId()); - $lmtree->deleteTree($node_data); - - // write history entry - require_once("./Services/History/classes/class.ilHistory.php"); - ilHistory::_createEntry($source_obj->getId(), "cut", - array(ilLMObject::_lookupTitle($parent_id), $parent_id), - $this->getType().":pg"); - ilHistory::_createEntry($parent_id, "cut_page", - array(ilLMObject::_lookupTitle($source_obj->getId()), $source_obj->getId()), - $this->getType().":st"); - } - else - { - // copy page - $new_page = $source_obj->copy(); - $source_id = $new_page->getId(); - $source_obj = $new_page; - } - - // paste page - if(!$lmtree->isInTree($source_obj->getId())) - { - if ($first_child) // as first child - { - $target_pos = IL_FIRST_NODE; - $parent = $target_id; - } - else if ($as_subitem) // as last child - { - $parent = $target_id; - $target_pos = IL_FIRST_NODE; - $pg_childs = $lmtree->getChildsByType($parent, "pg"); - if (count($pg_childs) != 0) - { - $target_pos = $pg_childs[count($pg_childs) - 1]["obj_id"]; - } - } - else // at position - { - $target_pos = $target_id; - $parent = $target_parent; - } - - // insert page into tree - $lmtree->insertNode($source_obj->getId(), - $parent, $target_pos); - - // write history entry - if ($movecopy == "move") - { - // write history comments - include_once("./Services/History/classes/class.ilHistory.php"); - ilHistory::_createEntry($source_obj->getId(), "paste", - array(ilLMObject::_lookupTitle($parent), $parent), - $this->getType().":pg"); - ilHistory::_createEntry($parent, "paste_page", - array(ilLMObject::_lookupTitle($source_obj->getId()), $source_obj->getId()), - $this->getType().":st"); - } - - } - } - } - - // handle chapters - if ($source_obj->getType() == "st") - { -//echo "2"; - $source_node = $lmtree->getNodeData($source_id); - $subnodes = $lmtree->getSubtree($source_node); - - // check, if target is within subtree - foreach ($subnodes as $subnode) - { - if($subnode["obj_id"] == $target_id) - { - return; - } - } - - $target_pos = $target_id; - - if ($first_child) // as first subchapter - { - $target_pos = IL_FIRST_NODE; - $target_parent = $target_id; - - $pg_childs = $lmtree->getChildsByType($target_parent, "pg"); - if (count($pg_childs) != 0) - { - $target_pos = $pg_childs[count($pg_childs) - 1]["obj_id"]; - } - } - else if ($as_subitem) // as last subchapter - { - $target_parent = $target_id; - $target_pos = IL_FIRST_NODE; - $childs = $lmtree->getChilds($target_parent); - if (count($childs) != 0) - { - $target_pos = $childs[count($childs) - 1]["obj_id"]; - } - } - - // insert into -/* - if ($position == "into") - { - $target_parent = $target_id; - $target_pos = IL_FIRST_NODE; - - // if target_pos is still first node we must skip all pages - if ($target_pos == IL_FIRST_NODE) - { - $pg_childs =& $lmtree->getChildsByType($target_parent, "pg"); - if (count($pg_childs) != 0) - { - $target_pos = $pg_childs[count($pg_childs) - 1]["obj_id"]; - } - } - } -*/ - - - // delete source tree - if ($movecopy == "move") - { - $lmtree->deleteTree($source_node); - } - else - { - // copy chapter (incl. subcontents) - $new_chapter = $source_obj->copy($lmtree, $target_parent, $target_pos); - } - - if (!$lmtree->isInTree($source_id)) - { - $lmtree->insertNode($source_id, $target_parent, $target_pos); - - // insert moved tree - if ($movecopy == "move") - { - foreach ($subnodes as $node) - { - if($node["obj_id"] != $source_id) - { - $lmtree->insertNode($node["obj_id"], $node["parent"]); - } - } - } - } - - // check the tree - $this->checkTree(); - } - - $this->checkTree(); - } - - /** - * Validate all pages - */ - function validatePages() - { - include_once "./Modules/LearningModule/classes/class.ilLMPageObject.php"; - include_once "./Modules/LearningModule/classes/class.ilLMPage.php"; - - $mess = ""; - - $pages = ilLMPageObject::getPageList($this->getId()); - foreach ($pages as $page) - { - if (ilLMPage::_exists($this->getType(), $page["obj_id"])) - { - $cpage = new ilLMPage($page["obj_id"]); - $cpage->buildDom(); - $error = @$cpage->validateDom(); - - if ($error != "") - { - $this->lng->loadLanguageModule("content"); - ilUtil::sendInfo($this->lng->txt("cont_import_validation_errors")); - $title = ilLMObject::_lookupTitle($page["obj_id"]); - $page_obj = new ilLMPageObject($this, $page["obj_id"]); - $mess.= $this->lng->txt("obj_pg").": ".$title; - $mess.= '
'; - foreach ($error as $e) - { - $err_mess = implode($e, " - "); - if (!is_int(strpos($err_mess, ":0:"))) - { - $mess.= htmlentities($err_mess)."
"; - } - } - $mess.= '
'; - $mess.= "
"; - } - } - } - - return $mess; - } - - /** - * Import lm from zip file - * - * @param - * @return - */ - function importFromZipFile($a_tmp_file, $a_filename, $a_validate = true, - $a_import_into_help_module = 0) - { - $lng = $this->lng; - - // create import directory - $this->createImportDirectory(); - - // copy uploaded file to import directory - $file = pathinfo($a_filename); - $full_path = $this->getImportDirectory()."/".$a_filename; - - ilUtil::moveUploadedFile($a_tmp_file, - $a_filename, $full_path); - - // unzip file - ilUtil::unzip($full_path); - - $subdir = basename($file["basename"],".".$file["extension"]); - - $mess = $this->importFromDirectory( - $this->getImportDirectory()."/".$subdir, $a_validate); - - - // delete import directory - ilUtil::delDir($this->getImportDirectory()); - - return $mess; - } - - - /** - * Import lm from directory - * - * @param - * @return - */ - // begin-patch optes_lok_export - function importFromDirectory($a_directory, $a_validate = true, $a_mapping = null) - // end-patch optes_lok_export - { - $lng = $this->lng; - - $this->log->debug("import from directory ".$a_directory); - - // determine filename of xml file - $subdir = basename($a_directory); - $xml_file = $a_directory."/".$subdir.".xml"; - - // check directory exists within zip file - if (!is_dir($a_directory)) - { - $this->log->error(sprintf($lng->txt("cont_no_subdir_in_zip"), $subdir)); - return sprintf($lng->txt("cont_no_subdir_in_zip"), $subdir); - } - - // check whether xml file exists within zip file - if (!is_file($xml_file)) - { - $this->log->error(sprintf($lng->txt("cont_zip_file_invalid"), $subdir."/".$subdir.".xml")); - return sprintf($lng->txt("cont_zip_file_invalid"), $subdir."/".$subdir.".xml"); - } - - // import questions - $this->log->debug("import qti"); - $qti_file = $a_directory."/qti.xml"; - $qtis = array(); - if (is_file($qti_file)) - { - include_once "./Services/QTI/classes/class.ilQTIParser.php"; - include_once("./Modules/Test/classes/class.ilObjTest.php"); - $qtiParser = new ilQTIParser ($qti_file, - IL_MO_VERIFY_QTI, 0, ""); - $result = $qtiParser->startParsing (); - $founditems = & $qtiParser->getFoundItems (); - $testObj = new ilObjTest(0, true); - if (count($founditems) > 0) - { - $qtiParser = new ilQTIParser($qti_file, IL_MO_PARSE_QTI, 0, ""); - $qtiParser->setTestObject($testObj); - $result = $qtiParser->startParsing(); - $qtis = array_merge($qtis, $qtiParser->getImportMapping()); - } - } - - $this->log->debug("get ilContObjParser"); - include_once ("./Modules/LearningModule/classes/class.ilContObjParser.php"); - $subdir = "."; - $contParser = new ilContObjParser($this, $xml_file, $subdir, $a_directory); - // smeyer: added \ilImportMapping lok im/export - $contParser->setImportMapping($a_mapping); - $contParser->setQuestionMapping($qtis); - $contParser->startParsing(); - ilObject::_writeImportId($this->getId(), $this->getImportId()); - $this->MDUpdateListener('General'); - - // import style - $style_file = $a_directory."/style.xml"; - $style_zip_file = $a_directory."/style.zip"; - if (is_file($style_zip_file)) // try to import style.zip first - { - require_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $style = new ilObjStyleSheet(); - $style->import($style_zip_file); - $this->writeStyleSheetId($style->getId()); - } - else if (is_file($style_file)) // try to import style.xml - { - require_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $style = new ilObjStyleSheet(); - $style->import($style_file); - $this->writeStyleSheetId($style->getId()); - } - -// // validate - if ($a_validate) - { - $mess = $this->validatePages(); - } - - if ($mess == "") - { - // handle internal links to this learning module - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - ilLMPage::_handleImportRepositoryLinks($this->getImportId(), - $this->getType(), $this->getRefId()); - } - - return $mess; - } - - /** - * Clone learning module - * - * @access public - * @param int target ref_id - * @param int copy id - * - */ - public function cloneObject($a_target_id,$a_copy_id = 0, $a_omit_tree = false) - { - $new_obj = parent::cloneObject($a_target_id,$a_copy_id, $a_omit_tree); - $this->cloneMetaData($new_obj); - //$new_obj->createProperties(); - - //copy online status if object is not the root copy object - $cp_options = ilCopyWizardOptions::_getInstance($a_copy_id); - - if(!$cp_options->isRootNode($this->getRefId())) - { - $new_obj->setOfflineStatus($this->getOfflineStatus()); - } - -// $new_obj->setTitle($this->getTitle()); - $new_obj->setDescription($this->getDescription()); - $new_obj->setLayoutPerPage($this->getLayoutPerPage()); - $new_obj->setLayout($this->getLayout()); - $new_obj->setTOCMode($this->getTOCMode()); - $new_obj->setActiveLMMenu($this->isActiveLMMenu()); - $new_obj->setActiveTOC($this->isActiveTOC()); - $new_obj->setActiveNumbering($this->isActiveNumbering()); - $new_obj->setActivePrintView($this->isActivePrintView()); - $new_obj->setActivePreventGlossaryAppendix($this->isActivePreventGlossaryAppendix()); - $new_obj->setActiveDownloads($this->isActiveDownloads()); - $new_obj->setActiveDownloadsPublic($this->isActiveDownloadsPublic()); - $new_obj->setPublicNotes($this->publicNotes()); - $new_obj->setCleanFrames($this->cleanFrames()); - $new_obj->setHistoryUserComments($this->isActiveHistoryUserComments()); - $new_obj->setPublicAccessMode($this->getPublicAccessMode()); - $new_obj->setPageHeader($this->getPageHeader()); - $new_obj->setRating($this->hasRating()); - $new_obj->setRatingPages($this->hasRatingPages()); - $new_obj->setDisableDefaultFeedback($this->getDisableDefaultFeedback()); - $new_obj->setProgressIcons($this->getProgressIcons()); - $new_obj->setStoreTries($this->getStoreTries()); - $new_obj->setRestrictForwardNavigation($this->getRestrictForwardNavigation()); - $new_obj->setAutoGlossaries($this->getAutoGlossaries()); - - $new_obj->update(); - - $new_obj->createLMTree(); - - // copy style - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $style_id = $this->getStyleSheetId(); - if ($style_id > 0 && - !ilObjStyleSheet::_lookupStandard($style_id)) - { - $style_obj = ilObjectFactory::getInstanceByObjId($style_id); - $new_id = $style_obj->ilClone(); - $new_obj->setStyleSheetId($new_id); - } - else // or just set the same standard style - { - $new_obj->setStyleSheetId($style_id); - } - $new_obj->update(); - - // copy content - $copied_nodes = $this->copyAllPagesAndChapters($new_obj, $a_copy_id); - - // page header and footer - if ($this->getHeaderPage() > 0 && ($new_page_header = $copied_nodes[$this->getHeaderPage()]) > 0) - { - $new_obj->setHeaderPage($new_page_header); - } - if ($this->getFooterPage() > 0 && ($new_page_footer = $copied_nodes[$this->getFooterPage()]) > 0) - { - $new_obj->setFooterPage($new_page_footer); - } - $new_obj->update(); - - // Copy learning progress settings - include_once('Services/Tracking/classes/class.ilLPObjSettings.php'); - $obj_settings = new ilLPObjSettings($this->getId()); - $obj_settings->cloneSettings($new_obj->getId()); - unset($obj_settings); - - // copy (page) multilang settings - include_once("./Services/Object/classes/class.ilObjectTranslation.php"); - $ot = ilObjectTranslation::getInstance($this->getId()); - $ot->copy($new_obj->getId()); - - // copy lm menu - include_once './Modules/LearningModule/classes/class.ilLMMenuEditor.php'; - $menu = new ilLMMenuEditor(); - $menu->setObjId($this->getId()); - $new_menu = new ilLMMenuEditor(); - $new_menu->setObjId($new_obj->getId()); - foreach ($menu->getMenuEntries() as $entry) - { - /*'id' => $row->id, - 'title' => $row->title, - 'link' => $row->target, - 'type' => $row->link_type, - 'ref_id' => $row->link_ref_id, - 'active'*/ - - $new_menu->setTarget($entry["link"]); - $new_menu->setTitle($entry["title"]); - $new_menu->setLinkType($entry["type"]); - $new_menu->setLinkRefId($entry["ref_id"]); - $new_menu->create(); - ilLMMenuEditor::writeActive($new_menu->getEntryId(), $entry["active"] == "y" ? true : false); - } - - - return $new_obj; - } - - /** - * Copy all pages and chapters - * - * @param object $a_target_obj target learning module - */ - function copyAllPagesAndChapters($a_target_obj, $a_copy_id = 0) - { - $parent_id = $a_target_obj->lm_tree->readRootId(); - - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); - - // get all chapters of root lm - $chapters = $this->lm_tree->getChildsByType($this->lm_tree->readRootId(), "st"); - $copied_nodes = array(); - //$time = time(); - foreach ($chapters as $chap) - { - $cid = ilLMObject::pasteTree($a_target_obj, $chap["child"], $parent_id, - IL_LAST_NODE, $time, $copied_nodes, true, $this); - $target = $cid; - } - - // copy free pages - $pages = ilLMPageObject::getPageList($this->getId()); - foreach ($pages as $p) - { - if (!$this->lm_tree->isInTree($p["obj_id"])) - { - $item = new ilLMPageObject($this, $p["obj_id"]); - $target_item = $item->copy($a_target_obj); - $copied_nodes[$item->getId()] = $target_item->getId(); - } - } - - // Add mapping for pages and chapters - include_once './Services/CopyWizard/classes/class.ilCopyWizardOptions.php'; - $options = ilCopyWizardOptions::_getInstance($a_copy_id); - foreach($copied_nodes as $old_id => $new_id) - { - $options->appendMapping( - $this->getRefId().'_'.$old_id, - $a_target_obj->getRefId().'_'.$new_id - ); - } - - ilLMObject::updateInternalLinks($copied_nodes); - - $a_target_obj->checkTree(); - - return $copied_nodes; - } - - - /** - * Lookup auto glossaries - * - * @param - * @return - */ - static function lookupAutoGlossaries($a_lm_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - // read auto glossaries - $set = $ilDB->query("SELECT * FROM lm_glossaries ". - " WHERE lm_id = ".$ilDB->quote($a_lm_id, "integer") - ); - $glos = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $glos[] = $rec["glo_id"]; - } - return $glos; - } - - /** - * Auto link glossary terms - * - * @param - * @return - */ - function autoLinkGlossaryTerms($a_glo_ref_id) - { - // get terms - include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - $terms = ilGlossaryTerm::getTermList($a_glo_ref_id); - - // each get page: get content - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - $pages = ilLMPage::getAllPages($this->getType(), $this->getId()); - - // determine terms that occur in the page - $found_pages = array(); - foreach ($pages as $p) - { - $pg = new ilLMPage($p["id"]); - $c = $pg->getXMLContent(); - foreach ($terms as $t) - { - if (is_int(stripos($c, $t["term"]))) - { - $found_pages[$p["id"]]["terms"][] = $t; - if (!is_object($found_pages[$p["id"]]["page"])) - { - $found_pages[$p["id"]]["page"] = $pg; - } - } - } - reset($terms); - } - - // ilPCParagraph autoLinkGlossariesPage with page and terms - include_once("./Services/COPage/classes/class.ilPCParagraph.php"); - foreach ($found_pages as $id => $fp) - { - ilPCParagraph::autoLinkGlossariesPage($fp["page"], $fp["terms"]); - } - - - } - - - //// - //// Online help - //// - - /** - * Is module an online module - * - * @return boolean true, if current learning module is an online help lm - */ - static function isOnlineHelpModule($a_id, $a_as_obj_id = false) - { - if (!$a_as_obj_id && $a_id > 0 && $a_id == OH_REF_ID) - { - return true; - } - if ($a_as_obj_id && $a_id > 0 && $a_id == ilObject::_lookupObjId(OH_REF_ID)) - { - return true; - } - return false; - } - - public function setRating($a_value) - { - $this->rating = (bool)$a_value; - } - - public function hasRating() - { - return $this->rating; - } - - public function setRatingPages($a_value) - { - $this->rating_pages = (bool)$a_value; - } - - public function hasRatingPages() - { - return $this->rating_pages; - } - - - public function MDUpdateListener($a_element) - { - parent::MDUpdateListener($a_element); - - include_once 'Services/MetaData/classes/class.ilMD.php'; - - switch($a_element) - { - case 'Educational': - include_once("./Services/Object/classes/class.ilObjectLP.php"); - $obj_lp = ilObjectLP::getInstance($this->getId()); - if(in_array($obj_lp->getCurrentMode(), - array(ilLPObjSettings::LP_MODE_TLT, ilLPObjSettings::LP_MODE_COLLECTION_TLT))) - { - include_once("./Services/Tracking/classes/class.ilLPStatusWrapper.php"); - ilLPStatusWrapper::_refreshStatus($this->getId()); - } - break; - - case 'General': - - // Update Title and description - $md = new ilMD($this->getId(),0, $this->getType()); - if(!is_object($md_gen = $md->getGeneral())) - { - return false; - } - - include_once("./Services/Object/classes/class.ilObjectTranslation.php"); - $ot = ilObjectTranslation::getInstance($this->getId()); - if ($ot->getContentActivated()) - { - $ot->setDefaultTitle($md_gen->getTitle()); - - foreach($md_gen->getDescriptionIds() as $id) - { - $md_des = $md_gen->getDescription($id); - $ot->setDefaultDescription($md_des->getDescription()); - break; - } - $ot->save(); - } - break; - - } - return true; - } - - /** - * Get public export files - * - * @return array array of arrays with keys "type" (html, scorm or xml), "file" (filename) and "size" in bytes, "dir_type" detailed directoy type, e.g. html_de - */ - function getPublicExportFiles() - { - $dirs = array("xml", "scorm"); - $export_files = array(); - - include_once("./Services/Object/classes/class.ilObjectTranslation.php"); - $ot = ilObjectTranslation::getInstance($this->getId()); - if ($ot->getContentActivated()) - { - $langs = $ot->getLanguages(); - foreach ($langs as $l => $ldata) - { - $dirs[] = "html_".$l; - } - $dirs[] = "html_all"; - } - else - { - $dirs[] = "html"; - } - - foreach($dirs as $dir) - { - $type = explode("_", $dir); - $type = $type[0]; - if ($this->getPublicExportFile($type) != "") - { - if (is_file($this->getExportDirectory($dir)."/". - $this->getPublicExportFile($type))) - { - $size = filesize($this->getExportDirectory($dir)."/". - $this->getPublicExportFile($type)); - $export_files[] = array("type" => $type, - "dir_type" => $dir, - "file" => $this->getPublicExportFile($type), - "size" => $size); - } - } - } - - return $export_files; - } - - + include_once './Services/MathJax/classes/class.ilMathJax.php'; + ilMathJax::getInstance()->init(ilMathJax::PURPOSE_EXPORT); + + // export system style sheet + $location_stylesheet = ilUtil::getStyleSheetLocation("filesystem"); + $style_name = $ilUser->prefs["style"] . ".css"; + copy($location_stylesheet, $style_dir . "/" . $style_name); + $fh = fopen($location_stylesheet, "r"); + $css = fread($fh, filesize($location_stylesheet)); + preg_match_all("/url\(([^\)]*)\)/", $css, $files); + foreach (array_unique($files[1]) as $fileref) { + $css_fileref = str_replace(array("'", '"'), "", $fileref); + $fileref = dirname($location_stylesheet) . "/" . $css_fileref; + if (is_file($fileref)) { + //echo "
make dir: ".dirname($style_dir."/".$css_fileref); + ilUtil::makeDirParents(dirname($style_dir . "/" . $css_fileref)); + //echo "
copy: ".$fileref." TO ".$style_dir."/".$css_fileref; + copy($fileref, $style_dir . "/" . $css_fileref); + } + } + fclose($fh); + $location_stylesheet = ilUtil::getStyleSheetLocation(); + + // export content style sheet + if ($this->getStyleSheetId() < 1) { + $cont_stylesheet = "./Services/COPage/css/content.css"; + + $css = fread(fopen($cont_stylesheet, 'r'), filesize($cont_stylesheet)); + preg_match_all("/url\(([^\)]*)\)/", $css, $files); + foreach (array_unique($files[1]) as $fileref) { + $target_fileref = str_replace("..", ".", $fileref); + $target_fileref = str_replace('"', "", $target_fileref); + if (is_file($target_fileref)) { + copy($target_fileref, $content_style_img_dir . "/" . basename($target_fileref)); + } + $css = str_replace($fileref, "images/" . basename($target_fileref), $css); + } + fwrite(fopen($content_style_dir . "/content.css", 'w'), $css); + } else { + $style = new ilObjStyleSheet($this->getStyleSheetId()); + $style->writeCSSFile($content_style_dir . "/content.css", "images"); + $style->copyImagesToDir($content_style_img_dir); + } + + // export syntax highlighting style + $syn_stylesheet = ilObjStyleSheet::getSyntaxStylePath(); + copy($syn_stylesheet, $a_target_dir . "/syntaxhighlight.css"); + + // get learning module presentation gui class + include_once("./Modules/LearningModule/classes/class.ilLMPresentationGUI.php"); + $_GET["cmd"] = "nop"; + $get_transl = $_GET["transl"]; + $_GET["transl"] = ""; + $lm_gui = new ilLMPresentationGUI(); + $lm_gui->setOfflineMode(true, ($a_lang == "all")); + $lm_gui->setOfflineDirectory($a_target_dir); + $lm_gui->setExportFormat($a_export_format); + + $ot = ilObjectTranslation::getInstance($this->getId()); + $langs = array(); + if ($a_lang != "all") { + $langs = array($a_lang); + } else { + $ot_langs = $ot->getLanguages(); + foreach ($ot_langs as $otl) { + $langs[] = $otl["lang_code"]; + } + } + + // init collector arrays + $this->offline_mobs = array(); + $this->offline_int_links = array(); + $this->offline_files = array(); + + // iterate all languages + foreach ($langs as $lang) { + if ($lang != "") { + $ilUser->setLanguage($lang); + $ilUser->setCurrentLanguage($lang); + } else { + $ilUser->setLanguage($user_lang); + $ilUser->setCurrentLanguage($user_lang); + } + + if ($lang != "") { + if ($lang == $ot->getMasterLanguage()) { + $lm_gui->lang = ""; + } else { + $lm_gui->lang = $lang; + } + } + + // export pages + // now: forward ("all" info to export files and links) + $this->exportHTMLPages($lm_gui, $a_target_dir, $lm_gui->lang, ($a_lang == "all")); + + // export table of contents + $ilLocator->clearItems(); + if ($this->isActiveTOC()) { + $tpl = new ilTemplate("tpl.main.html", true, true); + + $GLOBALS["tpl"] = $tpl; + + $lm_gui->tpl = $tpl; + $content = $lm_gui->showTableOfContents(); + //var_dump($content); exit; + if ($a_lang == "all") { + $file = $a_target_dir . "/table_of_contents_" . $lang . ".html"; + } else { + $file = $a_target_dir . "/table_of_contents.html"; + } + + // open file + if (!($fp = @fopen($file, "w+"))) { + die("Error: Could not open \"" . $file . "\" for writing" . + " in " . __FILE__ . " on line " . __LINE__ . "
"); + } + chmod($file, 0770); + fwrite($fp, $content); + fclose($fp); + } + } + + // export glossary terms + $this->exportHTMLGlossaryTerms($lm_gui, $a_target_dir); + + // export all media objects + $linked_mobs = array(); + foreach ($this->offline_mobs as $mob) { + if (ilObject::_exists($mob) && ilObject::_lookupType($mob) == "mob") { + $this->exportHTMLMOB($a_target_dir, $lm_gui, $mob, "_blank", $linked_mobs); + } + } + $linked_mobs2 = array(); // mobs linked in link areas + foreach ($linked_mobs as $mob) { + if (ilObject::_exists($mob)) { + $this->exportHTMLMOB($a_target_dir, $lm_gui, $mob, "_blank", $linked_mobs2); + } + } + $_GET["obj_type"] = "MediaObject"; + $_GET["obj_id"] = $a_mob_id; + $_GET["cmd"] = ""; + + // export all file objects + foreach ($this->offline_files as $file) { + $this->exportHTMLFile($a_target_dir, $file); + } + + // export questions (images) + if (count($this->q_ids) > 0) { + foreach ($this->q_ids as $q_id) { + ilUtil::makeDirParents($a_target_dir . "/assessment/0/" . $q_id . "/images"); + ilUtil::rCopy( + ilUtil::getWebspaceDir() . "/assessment/0/" . $q_id . "/images", + $a_target_dir . "/assessment/0/" . $q_id . "/images" + ); + } + } + + // export images + $image_dir = $a_target_dir . "/images"; + ilUtil::makeDir($image_dir); + ilUtil::makeDir($image_dir . "/browser"); + copy( + ilUtil::getImagePath("enlarge.svg", false, "filesystem"), + $image_dir . "/enlarge.svg" + ); + copy( + ilUtil::getImagePath("browser/blank.png", false, "filesystem"), + $image_dir . "/browser/plus.png" + ); + copy( + ilUtil::getImagePath("browser/blank.png", false, "filesystem"), + $image_dir . "/browser/minus.png" + ); + copy( + ilUtil::getImagePath("browser/blank.png", false, "filesystem"), + $image_dir . "/browser/blank.png" + ); + copy( + ilUtil::getImagePath("spacer.png", false, "filesystem"), + $image_dir . "/spacer.png" + ); + copy( + ilUtil::getImagePath("icon_st.svg", false, "filesystem"), + $image_dir . "/icon_st.svg" + ); + copy( + ilUtil::getImagePath("icon_pg.svg", false, "filesystem"), + $image_dir . "/icon_pg.svg" + ); + copy( + ilUtil::getImagePath("icon_lm.svg", false, "filesystem"), + $image_dir . "/icon_lm.svg" + ); + copy( + ilUtil::getImagePath("nav_arr_L.png", false, "filesystem"), + $image_dir . "/nav_arr_L.png" + ); + copy( + ilUtil::getImagePath("nav_arr_R.png", false, "filesystem"), + $image_dir . "/nav_arr_R.png" + ); + + // export flv/mp3 player + $services_dir = $a_target_dir . "/Services"; + ilUtil::makeDir($services_dir); + $media_service_dir = $services_dir . "/MediaObjects"; + ilUtil::makeDir($media_service_dir); + include_once("./Services/MediaObjects/classes/class.ilPlayerUtil.php"); + $flv_dir = $a_target_dir . "/" . ilPlayerUtil::getFlashVideoPlayerDirectory(); + ilUtil::makeDirParents($flv_dir); + $mp3_dir = $media_service_dir . "/flash_mp3_player"; + ilUtil::makeDir($mp3_dir); + // copy(ilPlayerUtil::getFlashVideoPlayerFilename(true), + // $flv_dir."/".ilPlayerUtil::getFlashVideoPlayerFilename()); + ilPlayerUtil::copyPlayerFilesToTargetDirectory($flv_dir); + include_once("./Services/UIComponent/Explorer2/classes/class.ilExplorerBaseGUI.php"); + ilExplorerBaseGUI::createHTMLExportDirs($a_target_dir); + ilPlayerUtil::copyPlayerFilesToTargetDirectory($flv_dir); + + // js files + ilUtil::makeDir($a_target_dir . '/js'); + ilUtil::makeDir($a_target_dir . '/js/yahoo'); + ilUtil::makeDir($a_target_dir . '/css'); + include_once("./Services/YUI/classes/class.ilYuiUtil.php"); + foreach (self::getSupplyingExportFiles($a_target_dir) as $f) { + if ($f["source"] != "") { + ilUtil::makeDirParents(dirname($f["target"])); + copy($f["source"], $f["target"]); + } + } + // template workaround: reset of template + $tpl = new ilTemplate("tpl.main.html", true, true); + $tpl->setVariable("LOCATION_STYLESHEET", $location_stylesheet); + $tpl->addBlockFile("CONTENT", "content", "tpl.adm_content.html"); + + if ($a_lang != "") { + $ilUser->setLanguage($user_lang); + $ilUser->setCurrentLanguage($user_lang); + } + + // zip everything + if ($a_zip_file) { + if ($a_lang == "") { + $zip_target_dir = $this->getExportDirectory("html"); + } else { + $zip_target_dir = $this->getExportDirectory("html_" . $a_lang); + ilUtil::makeDir($zip_target_dir); + } + + // zip it all + $date = time(); + $zip_file = $zip_target_dir . "/" . $date . "__" . IL_INST_ID . "__" . + $this->getType() . "_" . $this->getId() . ".zip"; + //echo "-".$a_target_dir."-".$zip_file."-"; exit; + ilUtil::zip($a_target_dir, $zip_file); + ilUtil::delDir($a_target_dir); + } + } + + /** + * Get supplying export files + * + * @param + * @return + */ + public static function getSupplyingExportFiles($a_target_dir = ".") + { + include_once("./Services/YUI/classes/class.ilYuiUtil.php"); + include_once("./Services/jQuery/classes/class.iljQueryUtil.php"); + include_once("./Services/MediaObjects/classes/class.ilPlayerUtil.php"); + include_once("./Services/UIComponent/Explorer2/classes/class.ilExplorerBaseGUI.php"); + $scripts = array( + array("source" => ilYuiUtil::getLocalPath('yahoo/yahoo-min.js'), + "target" => $a_target_dir . '/js/yahoo/yahoo-min.js', + "type" => "js"), + array("source" => ilYuiUtil::getLocalPath('yahoo-dom-event/yahoo-dom-event.js'), + "target" => $a_target_dir . '/js/yahoo/yahoo-dom-event.js', + "type" => "js"), + array("source" => ilYuiUtil::getLocalPath('animation/animation-min.js'), + "target" => $a_target_dir . '/js/yahoo/animation-min.js', + "type" => "js"), + array("source" => './Services/JavaScript/js/Basic.js', + "target" => $a_target_dir . '/js/Basic.js', + "type" => "js"), + array("source" => './Services/Accordion/js/accordion.js', + "target" => $a_target_dir . '/js/accordion.js', + "type" => "js"), + array("source" => './Services/Accordion/css/accordion.css', + "target" => $a_target_dir . '/css/accordion.css', + "type" => "css"), + array("source" => iljQueryUtil::getLocaljQueryPath(), + "target" => $a_target_dir . '/js/jquery.js', + "type" => "js"), + array("source" => iljQueryUtil::getLocalMaphilightPath(), + "target" => $a_target_dir . '/js/maphilight.js', + "type" => "js"), + array("source" => iljQueryUtil::getLocaljQueryUIPath(), + "target" => $a_target_dir . '/js/jquery-ui-min.js', + "type" => "js"), + array("source" => './Services/COPage/js/ilCOPagePres.js', + "target" => $a_target_dir . '/js/ilCOPagePres.js', + "type" => "js"), + array("source" => './Modules/Scorm2004/scripts/questions/pure.js', + "target" => $a_target_dir . '/js/pure.js', + "type" => "js"), + array("source" => './Modules/Scorm2004/scripts/questions/question_handling.js', + "target" => $a_target_dir . '/js/question_handling.js', + "type" => "js"), + array("source" => './Modules/TestQuestionPool/js/ilMatchingQuestion.js', + "target" => $a_target_dir . '/js/ilMatchingQuestion.js', + "type" => "js"), + array("source" => './Modules/Scorm2004/templates/default/question_handling.css', + "target" => $a_target_dir . '/css/question_handling.css', + "type" => "css"), + array("source" => './Modules/TestQuestionPool/templates/default/test_javascript.css', + "target" => $a_target_dir . '/css/test_javascript.css', + "type" => "css"), + array("source" => ilPlayerUtil::getLocalMediaElementJsPath(), + "target" => $a_target_dir . "/" . ilPlayerUtil::getLocalMediaElementJsPath(), + "type" => "js"), + array("source" => ilPlayerUtil::getLocalMediaElementCssPath(), + "target" => $a_target_dir . "/" . ilPlayerUtil::getLocalMediaElementCssPath(), + "type" => "css"), + array("source" => ilExplorerBaseGUI::getLocalExplorerJsPath(), + "target" => $a_target_dir . "/" . ilExplorerBaseGUI::getLocalExplorerJsPath(), + "type" => "js"), + array("source" => ilExplorerBaseGUI::getLocalJsTreeJsPath(), + "target" => $a_target_dir . "/" . ilExplorerBaseGUI::getLocalJsTreeJsPath(), + "type" => "js"), + array("source" => ilExplorerBaseGUI::getLocalJsTreeCssPath(), + "target" => $a_target_dir . "/" . ilExplorerBaseGUI::getLocalJsTreeCssPath(), + "type" => "css"), + array("source" => './Modules/LearningModule/js/LearningModule.js', + "target" => $a_target_dir . '/js/LearningModule.js', + "type" => "js") + ); + + $mathJaxSetting = new ilSetting("MathJax"); + $use_mathjax = $mathJaxSetting->get("enable"); + if ($use_mathjax) { + $scripts[] = array("source" => "", + "target" => $mathJaxSetting->get("path_to_mathjax"), + "type" => "js"); + } + + // auto linking js + include_once("./Services/Link/classes/class.ilLinkifyUtil.php"); + foreach (ilLinkifyUtil::getLocalJsPaths() as $p) { + if (is_int(strpos($p, "ExtLink"))) { + $scripts[] = array("source" => $p, + "target" => $a_target_dir . '/js/ilExtLink.js', + "type" => "js"); + } + if (is_int(strpos($p, "linkify"))) { + $scripts[] = array("source" => $p, + "target" => $a_target_dir . '/js/linkify.js', + "type" => "js"); + } + } + + return $scripts; + } + + /** + * export file object + */ + public function exportHTMLFile($a_target_dir, $a_file_id) + { + $file_dir = $a_target_dir . "/files/file_" . $a_file_id; + ilUtil::makeDir($file_dir); + include_once("./Modules/File/classes/class.ilObjFile.php"); + $file_obj = new ilObjFile($a_file_id, false); + $source_file = $file_obj->getDirectory($file_obj->getVersion()) . "/" . $file_obj->getFileName(); + if (!is_file($source_file)) { + $source_file = $file_obj->getDirectory() . "/" . $file_obj->getFileName(); + } + if (is_file($source_file)) { + copy($source_file, $file_dir . "/" . $file_obj->getFileName()); + } + } + + /** + * export media object to html + */ + public function exportHTMLMOB($a_target_dir, &$a_lm_gui, $a_mob_id, $a_frame, &$a_linked_mobs) + { + $tpl = $this->tpl; + + $mob_dir = $a_target_dir . "/mobs"; + + $source_dir = ilUtil::getWebspaceDir() . "/mobs/mm_" . $a_mob_id; + if (@is_dir($source_dir)) { + ilUtil::makeDir($mob_dir . "/mm_" . $a_mob_id); + ilUtil::rCopy($source_dir, $mob_dir . "/mm_" . $a_mob_id); + } + + $tpl = new ilTemplate("tpl.main.html", true, true); + $tpl->addBlockFile("CONTENT", "content", "tpl.adm_content.html"); + $_GET["obj_type"] = "MediaObject"; + $_GET["mob_id"] = $a_mob_id; + $_GET["frame"] = $a_frame; + $_GET["cmd"] = ""; + $content = $a_lm_gui->media(); + $file = $a_target_dir . "/media_" . $a_mob_id . ".html"; + + // open file + if (!($fp = @fopen($file, "w+"))) { + die("Error: Could not open \"" . $file . "\" for writing" . + " in " . __FILE__ . " on line " . __LINE__ . "
"); + } + chmod($file, 0770); + fwrite($fp, $content); + fclose($fp); + + // fullscreen + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $mob_obj = new ilObjMediaObject($a_mob_id); + if ($mob_obj->hasFullscreenItem()) { + $tpl = new ilTemplate("tpl.main.html", true, true); + $tpl->addBlockFile("CONTENT", "content", "tpl.adm_content.html"); + $_GET["obj_type"] = ""; + $_GET["frame"] = ""; + $_GET["mob_id"] = $a_mob_id; + $_GET["cmd"] = "fullscreen"; + $content = $a_lm_gui->fullscreen(); + $file = $a_target_dir . "/fullscreen_" . $a_mob_id . ".html"; + + // open file + if (!($fp = @fopen($file, "w+"))) { + die("Error: Could not open \"" . $file . "\" for writing" . + " in " . __FILE__ . " on line " . __LINE__ . "
"); + } + chmod($file, 0770); + fwrite($fp, $content); + fclose($fp); + } + $linked_mobs = $mob_obj->getLinkedMediaObjects(); + foreach ($linked_mobs as $id) { + $this->log->debug("HTML Export: Add media object $id (" . ilObject::_lookupTitle($id) . ") " . + " due to media object " . $a_mob_id . " (" . ilObject::_lookupTitle($a_mob_id) . ")."); + } + $a_linked_mobs = array_merge($a_linked_mobs, $linked_mobs); + } + + /** + * export glossary terms + */ + public function exportHTMLGlossaryTerms(&$a_lm_gui, $a_target_dir) + { + $ilLocator = $this->locator; + + foreach ($this->offline_int_links as $int_link) { + $ilLocator->clearItems(); + if ($int_link["type"] == "git") { + $tpl = new ilTemplate("tpl.main.html", true, true); + $tpl->addBlockFile("CONTENT", "content", "tpl.adm_content.html"); + + $_GET["obj_id"] = $int_link["id"]; + $_GET["frame"] = "_blank"; + $content = $a_lm_gui->glossary(); + $file = $a_target_dir . "/term_" . $int_link["id"] . ".html"; + + // open file + if (!($fp = @fopen($file, "w+"))) { + die("Error: Could not open \"" . $file . "\" for writing" . + " in " . __FILE__ . " on line " . __LINE__ . "
"); + } + chmod($file, 0770); + fwrite($fp, $content); + fclose($fp); + + // store linked/embedded media objects of glosssary term + include_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); + $defs = ilGlossaryDefinition::getDefinitionList($int_link["id"]); + foreach ($defs as $def) { + $def_mobs = ilObjMediaObject::_getMobsOfObject("gdf:pg", $def["id"]); + foreach ($def_mobs as $def_mob) { + $this->offline_mobs[$def_mob] = $def_mob; + include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + $this->log->debug("HTML Export: Add media object $def_mob (" . ilObject::_lookupTitle($def_mob) . ") " . + " due to glossary entry " . $int_link["id"] . " (" . ilGlossaryTerm::_lookGlossaryTerm($int_link["id"]) . ")."); + } + + // get all files of page + $def_files = ilObjFile::_getFilesOfObject("gdf:pg", $page["obj_id"]); + $this->offline_files = array_merge($this->offline_files, $def_files); + } + } + } + } + + /** + * export all pages of learning module to html file + */ + public function exportHTMLPages(&$a_lm_gui, $a_target_dir, $a_lang = "", $a_all_languages = false) + { + $ilLocator = $this->locator; + + $pages = ilLMPageObject::getPageList($this->getId()); + + $lm_tree = $this->getLMTree(); + $first_page = $lm_tree->fetchSuccessorNode($lm_tree->getRootId(), "pg"); + $this->first_page_id = $first_page["child"]; + + // iterate all learning module pages + $mobs = array(); + $int_links = array(); + $this->offline_files = array(); + + include_once("./Services/COPage/classes/class.ilPageContentUsage.php"); + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + + // get html export id mapping + $lm_set = new ilSetting("lm"); + $exp_id_map = array(); + + if ($lm_set->get("html_export_ids")) { + foreach ($pages as $page) { + $exp_id = ilLMPageObject::getExportId($this->getId(), $page["obj_id"]); + if (trim($exp_id) != "") { + $exp_id_map[$page["obj_id"]] = trim($exp_id); + } + } + } + //exit; + if ($a_lang == "") { + $a_lang = "-"; + } + + reset($pages); + foreach ($pages as $page) { + if (ilLMPage::_exists($this->getType(), $page["obj_id"])) { + $ilLocator->clearItems(); + $this->exportPageHTML( + $a_lm_gui, + $a_target_dir, + $page["obj_id"], + "", + $exp_id_map, + $a_lang, + $a_all_languages + ); + + // get all snippets of page + $pcs = ilPageContentUsage::getUsagesOfPage($page["obj_id"], $this->getType() . ":pg", 0, false, $a_lang); + foreach ($pcs as $pc) { + if ($pc["type"] == "incl") { + $incl_mobs = ilObjMediaObject::_getMobsOfObject("mep:pg", $pc["id"]); + foreach ($incl_mobs as $incl_mob) { + $mobs[$incl_mob] = $incl_mob; + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + $this->log->debug("HTML Export: Add media object $incl_mob (" . ilObject::_lookupTitle($incl_mob) . ") " . + " due to snippet " . $pc["id"] . " in page " . $page["obj_id"] . " (" . ilLMObject::_lookupTitle($page["obj_id"]) . ")."); + } + } + } + + // get all media objects of page + $pg_mobs = ilObjMediaObject::_getMobsOfObject($this->getType() . ":pg", $page["obj_id"], 0, $a_lang); + foreach ($pg_mobs as $pg_mob) { + $mobs[$pg_mob] = $pg_mob; + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + $this->log->debug("HTML Export: Add media object $pg_mob (" . ilObject::_lookupTitle($pg_mob) . ") " . + " due to page " . $page["obj_id"] . " (" . ilLMObject::_lookupTitle($page["obj_id"]) . ")."); + } + + // get all internal links of page + $pg_links = ilInternalLink::_getTargetsOfSource($this->getType() . ":pg", $page["obj_id"], $a_lang); + $int_links = array_merge($int_links, $pg_links); + + // get all files of page + include_once("./Modules/File/classes/class.ilObjFile.php"); + $pg_files = ilObjFile::_getFilesOfObject($this->getType() . ":pg", $page["obj_id"], 0, $a_lang); + $this->offline_files = array_merge($this->offline_files, $pg_files); + + // collect all questions + include_once("./Services/COPage/classes/class.ilPCQuestion.php"); + $q_ids = ilPCQuestion::_getQuestionIdsForPage($this->getType(), $page["obj_id"], $a_lang); + foreach ($q_ids as $q_id) { + $this->q_ids[$q_id] = $q_id; + } + } + } + foreach ($mobs as $m) { + $this->offline_mobs[$m] = $m; + } + foreach ($int_links as $k => $v) { + $this->offline_int_links[$k] = $v; + } + } + + + + /** + * export page html + */ + public function exportPageHTML( + &$a_lm_gui, + $a_target_dir, + $a_lm_page_id, + $a_frame = "", + $a_exp_id_map = array(), + $a_lang = "-", + $a_all_languages = false + ) { + $tpl = $this->tpl; + + $lang_suffix = ""; + if ($a_lang != "-" && $a_lang != "" && $a_all_languages) { + $lang_suffix = "_" . $a_lang; + } + + //echo "
B: export Page HTML ($a_lm_page_id)"; flush(); + // template workaround: reset of template + $tpl = new ilTemplate("tpl.main.html", true, true); + $tpl->addBlockFile("CONTENT", "content", "tpl.adm_content.html"); + + include_once("./Services/COPage/classes/class.ilPCQuestion.php"); + ilPCQuestion::resetInitialState(); + + $_GET["obj_id"] = $a_lm_page_id; + $_GET["frame"] = $a_frame; + + if ($a_frame == "") { + //if ($nid = ilLMObject::_lookupNID($a_lm_gui->lm->getId(), $a_lm_page_id, "pg")) + if (is_array($a_exp_id_map) && isset($a_exp_id_map[$a_lm_page_id])) { + $file = $a_target_dir . "/lm_pg_" . $a_exp_id_map[$a_lm_page_id] . $lang_suffix . ".html"; + } else { + $file = $a_target_dir . "/lm_pg_" . $a_lm_page_id . $lang_suffix . ".html"; + } + } else { + if ($a_frame != "toc") { + $file = $a_target_dir . "/frame_" . $a_lm_page_id . "_" . $a_frame . $lang_suffix . ".html"; + } else { + $file = $a_target_dir . "/frame_" . $a_frame . $lang_suffix . ".html"; + } + } + + // return if file is already existing + if (@is_file($file)) { + return; + } + + $content = $a_lm_gui->layout("main.xml", false); + + // open file + if (!($fp = @fopen($file, "w+"))) { + die("Error: Could not open \"" . $file . "\" for writing" . + " in " . __FILE__ . " on line " . __LINE__ . "
"); + } + + // set file permissions + chmod($file, 0770); + + // write xml data into the file + fwrite($fp, $content); + + // close file + fclose($fp); + + if ($this->first_page_id == $a_lm_page_id && $a_frame == "") { + copy($file, $a_target_dir . "/index" . $lang_suffix . ".html"); + } + + // write frames of frameset + $frameset = $a_lm_gui->getCurrentFrameSet(); + + foreach ($frameset as $frame) { + $this->exportPageHTML($a_lm_gui, $a_target_dir, $a_lm_page_id, $frame); + } + } + + /** + * export object to fo + * + * @param object $a_xml_writer ilXmlWriter object that receives the + * xml data + */ + public function exportFO(&$a_xml_writer, $a_target_dir) + { + // fo:root (start) + $attrs = array(); + $attrs["xmlns:fo"] = "http://www.w3.org/1999/XSL/Format"; + $a_xml_writer->xmlStartTag("fo:root", $attrs); + + // fo:layout-master-set (start) + $attrs = array(); + $a_xml_writer->xmlStartTag("fo:layout-master-set", $attrs); + + // fo:simple-page-master (start) + $attrs = array(); + $attrs["master-name"] = "DinA4"; + $attrs["page-height"] = "29.7cm"; + $attrs["page-width"] = "21cm"; + $attrs["margin-top"] = "4cm"; + $attrs["margin-bottom"] = "1cm"; + $attrs["margin-left"] = "2.8cm"; + $attrs["margin-right"] = "7.3cm"; + $a_xml_writer->xmlStartTag("fo:simple-page-master", $attrs); + + // fo:region-body (complete) + $attrs = array(); + $attrs["margin-top"] = "0cm"; + $attrs["margin-bottom"] = "1.25cm"; + $a_xml_writer->xmlElement("fo:region-body", $attrs); + + // fo:region-before (complete) + $attrs = array(); + $attrs["extent"] = "1cm"; + $a_xml_writer->xmlElement("fo:region-before", $attrs); + + // fo:region-after (complete) + $attrs = array(); + $attrs["extent"] = "1cm"; + $a_xml_writer->xmlElement("fo:region-after", $attrs); + + // fo:simple-page-master (end) + $a_xml_writer->xmlEndTag("fo:simple-page-master"); + + // fo:layout-master-set (end) + $a_xml_writer->xmlEndTag("fo:layout-master-set"); + + // fo:page-sequence (start) + $attrs = array(); + $attrs["master-reference"] = "DinA4"; + $a_xml_writer->xmlStartTag("fo:page-sequence", $attrs); + + // fo:flow (start) + $attrs = array(); + $attrs["flow-name"] = "xsl-region-body"; + $a_xml_writer->xmlStartTag("fo:flow", $attrs); + + + // StructureObjects + $this->exportFOStructureObjects($a_xml_writer, $expLog); + + // fo:flow (end) + $a_xml_writer->xmlEndTag("fo:flow"); + + // fo:page-sequence (end) + $a_xml_writer->xmlEndTag("fo:page-sequence"); + + // fo:root (end) + $a_xml_writer->xmlEndTag("fo:root"); + } + + /** + * export structure objects to fo + * + * @param object $a_xml_writer ilXmlWriter object that receives the + * xml data + */ + public function exportFOStructureObjects(&$a_xml_writer) + { + $childs = $this->lm_tree->getChilds($this->lm_tree->getRootId()); + foreach ($childs as $child) { + if ($child["type"] != "st") { + continue; + } + + $structure_obj = new ilStructureObject($this, $child["obj_id"]); + $structure_obj->exportFO($a_xml_writer, $expLog); + unset($structure_obj); + } + } + + public function getXMLZip() + { + include_once("./Modules/LearningModule/classes/class.ilContObjectExport.php"); + + $cont_exp = new ilContObjectExport($this, 'xml'); + + $export_file = $cont_exp->buildExportFile(); + return $export_file; + } + + /** + * Execute Drag Drop Action + * + * @param string $source_id Source element ID + * @param string $target_id Target element ID + * @param string $first_child Insert as first child of target + * @param string $movecopy Position ("move" | "copy") + */ + public function executeDragDrop($source_id, $target_id, $first_child, $as_subitem = false, $movecopy = "move") + { + $lmtree = new ilTree($this->getId()); + $lmtree->setTableNames('lm_tree', 'lm_data'); + $lmtree->setTreeTablePK("lm_id"); + //echo "-".$source_id."-".$target_id."-".$first_child."-".$as_subitem."-"; + $source_obj = ilLMObjectFactory::getInstance($this, $source_id, true); + $source_obj->setLMId($this->getId()); + + if (!$first_child) { + $target_obj = ilLMObjectFactory::getInstance($this, $target_id, true); + $target_obj->setLMId($this->getId()); + $target_parent = $lmtree->getParentId($target_id); + } + + // handle pages + if ($source_obj->getType() == "pg") { + //echo "1"; + if ($lmtree->isInTree($source_obj->getId())) { + $node_data = $lmtree->getNodeData($source_obj->getId()); + + // cut on move + if ($movecopy == "move") { + $parent_id = $lmtree->getParentId($source_obj->getId()); + $lmtree->deleteTree($node_data); + + // write history entry + require_once("./Services/History/classes/class.ilHistory.php"); + ilHistory::_createEntry( + $source_obj->getId(), + "cut", + array(ilLMObject::_lookupTitle($parent_id), $parent_id), + $this->getType() . ":pg" + ); + ilHistory::_createEntry( + $parent_id, + "cut_page", + array(ilLMObject::_lookupTitle($source_obj->getId()), $source_obj->getId()), + $this->getType() . ":st" + ); + } else { + // copy page + $new_page = $source_obj->copy(); + $source_id = $new_page->getId(); + $source_obj = $new_page; + } + + // paste page + if (!$lmtree->isInTree($source_obj->getId())) { + if ($first_child) { // as first child + $target_pos = IL_FIRST_NODE; + $parent = $target_id; + } elseif ($as_subitem) { // as last child + $parent = $target_id; + $target_pos = IL_FIRST_NODE; + $pg_childs = $lmtree->getChildsByType($parent, "pg"); + if (count($pg_childs) != 0) { + $target_pos = $pg_childs[count($pg_childs) - 1]["obj_id"]; + } + } else { // at position + $target_pos = $target_id; + $parent = $target_parent; + } + + // insert page into tree + $lmtree->insertNode( + $source_obj->getId(), + $parent, + $target_pos + ); + + // write history entry + if ($movecopy == "move") { + // write history comments + include_once("./Services/History/classes/class.ilHistory.php"); + ilHistory::_createEntry( + $source_obj->getId(), + "paste", + array(ilLMObject::_lookupTitle($parent), $parent), + $this->getType() . ":pg" + ); + ilHistory::_createEntry( + $parent, + "paste_page", + array(ilLMObject::_lookupTitle($source_obj->getId()), $source_obj->getId()), + $this->getType() . ":st" + ); + } + } + } + } + + // handle chapters + if ($source_obj->getType() == "st") { + //echo "2"; + $source_node = $lmtree->getNodeData($source_id); + $subnodes = $lmtree->getSubtree($source_node); + + // check, if target is within subtree + foreach ($subnodes as $subnode) { + if ($subnode["obj_id"] == $target_id) { + return; + } + } + + $target_pos = $target_id; + + if ($first_child) { // as first subchapter + $target_pos = IL_FIRST_NODE; + $target_parent = $target_id; + + $pg_childs = $lmtree->getChildsByType($target_parent, "pg"); + if (count($pg_childs) != 0) { + $target_pos = $pg_childs[count($pg_childs) - 1]["obj_id"]; + } + } elseif ($as_subitem) { // as last subchapter + $target_parent = $target_id; + $target_pos = IL_FIRST_NODE; + $childs = $lmtree->getChilds($target_parent); + if (count($childs) != 0) { + $target_pos = $childs[count($childs) - 1]["obj_id"]; + } + } + + // insert into + /* + if ($position == "into") + { + $target_parent = $target_id; + $target_pos = IL_FIRST_NODE; + + // if target_pos is still first node we must skip all pages + if ($target_pos == IL_FIRST_NODE) + { + $pg_childs =& $lmtree->getChildsByType($target_parent, "pg"); + if (count($pg_childs) != 0) + { + $target_pos = $pg_childs[count($pg_childs) - 1]["obj_id"]; + } + } + } + */ + + + // delete source tree + if ($movecopy == "move") { + $lmtree->deleteTree($source_node); + } else { + // copy chapter (incl. subcontents) + $new_chapter = $source_obj->copy($lmtree, $target_parent, $target_pos); + } + + if (!$lmtree->isInTree($source_id)) { + $lmtree->insertNode($source_id, $target_parent, $target_pos); + + // insert moved tree + if ($movecopy == "move") { + foreach ($subnodes as $node) { + if ($node["obj_id"] != $source_id) { + $lmtree->insertNode($node["obj_id"], $node["parent"]); + } + } + } + } + + // check the tree + $this->checkTree(); + } + + $this->checkTree(); + } + + /** + * Validate all pages + */ + public function validatePages() + { + include_once "./Modules/LearningModule/classes/class.ilLMPageObject.php"; + include_once "./Modules/LearningModule/classes/class.ilLMPage.php"; + + $mess = ""; + + $pages = ilLMPageObject::getPageList($this->getId()); + foreach ($pages as $page) { + if (ilLMPage::_exists($this->getType(), $page["obj_id"])) { + $cpage = new ilLMPage($page["obj_id"]); + $cpage->buildDom(); + $error = @$cpage->validateDom(); + + if ($error != "") { + $this->lng->loadLanguageModule("content"); + ilUtil::sendInfo($this->lng->txt("cont_import_validation_errors")); + $title = ilLMObject::_lookupTitle($page["obj_id"]); + $page_obj = new ilLMPageObject($this, $page["obj_id"]); + $mess.= $this->lng->txt("obj_pg") . ": " . $title; + $mess.= '
'; + foreach ($error as $e) { + $err_mess = implode($e, " - "); + if (!is_int(strpos($err_mess, ":0:"))) { + $mess.= htmlentities($err_mess) . "
"; + } + } + $mess.= '
'; + $mess.= "
"; + } + } + } + + return $mess; + } + + /** + * Import lm from zip file + * + * @param + * @return + */ + public function importFromZipFile( + $a_tmp_file, + $a_filename, + $a_validate = true, + $a_import_into_help_module = 0 + ) { + $lng = $this->lng; + + // create import directory + $this->createImportDirectory(); + + // copy uploaded file to import directory + $file = pathinfo($a_filename); + $full_path = $this->getImportDirectory() . "/" . $a_filename; + + ilUtil::moveUploadedFile( + $a_tmp_file, + $a_filename, + $full_path + ); + + // unzip file + ilUtil::unzip($full_path); + + $subdir = basename($file["basename"], "." . $file["extension"]); + + $mess = $this->importFromDirectory( + $this->getImportDirectory() . "/" . $subdir, + $a_validate + ); + + + // delete import directory + ilUtil::delDir($this->getImportDirectory()); + + return $mess; + } + + + /** + * Import lm from directory + * + * @param + * @return + */ + // begin-patch optes_lok_export + public function importFromDirectory($a_directory, $a_validate = true, $a_mapping = null) + // end-patch optes_lok_export + { + $lng = $this->lng; + + $this->log->debug("import from directory " . $a_directory); + + // determine filename of xml file + $subdir = basename($a_directory); + $xml_file = $a_directory . "/" . $subdir . ".xml"; + + // check directory exists within zip file + if (!is_dir($a_directory)) { + $this->log->error(sprintf($lng->txt("cont_no_subdir_in_zip"), $subdir)); + return sprintf($lng->txt("cont_no_subdir_in_zip"), $subdir); + } + + // check whether xml file exists within zip file + if (!is_file($xml_file)) { + $this->log->error(sprintf($lng->txt("cont_zip_file_invalid"), $subdir . "/" . $subdir . ".xml")); + return sprintf($lng->txt("cont_zip_file_invalid"), $subdir . "/" . $subdir . ".xml"); + } + + // import questions + $this->log->debug("import qti"); + $qti_file = $a_directory . "/qti.xml"; + $qtis = array(); + if (is_file($qti_file)) { + include_once "./Services/QTI/classes/class.ilQTIParser.php"; + include_once("./Modules/Test/classes/class.ilObjTest.php"); + $qtiParser = new ilQTIParser( + $qti_file, + IL_MO_VERIFY_QTI, + 0, + "" + ); + $result = $qtiParser->startParsing(); + $founditems = &$qtiParser->getFoundItems(); + $testObj = new ilObjTest(0, true); + if (count($founditems) > 0) { + $qtiParser = new ilQTIParser($qti_file, IL_MO_PARSE_QTI, 0, ""); + $qtiParser->setTestObject($testObj); + $result = $qtiParser->startParsing(); + $qtis = array_merge($qtis, $qtiParser->getImportMapping()); + } + } + + $this->log->debug("get ilContObjParser"); + include_once("./Modules/LearningModule/classes/class.ilContObjParser.php"); + $subdir = "."; + $contParser = new ilContObjParser($this, $xml_file, $subdir, $a_directory); + // smeyer: added \ilImportMapping lok im/export + $contParser->setImportMapping($a_mapping); + $contParser->setQuestionMapping($qtis); + $contParser->startParsing(); + ilObject::_writeImportId($this->getId(), $this->getImportId()); + $this->MDUpdateListener('General'); + + // import style + $style_file = $a_directory . "/style.xml"; + $style_zip_file = $a_directory . "/style.zip"; + if (is_file($style_zip_file)) { // try to import style.zip first + require_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $style = new ilObjStyleSheet(); + $style->import($style_zip_file); + $this->writeStyleSheetId($style->getId()); + } elseif (is_file($style_file)) { // try to import style.xml + require_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $style = new ilObjStyleSheet(); + $style->import($style_file); + $this->writeStyleSheetId($style->getId()); + } + + // // validate + if ($a_validate) { + $mess = $this->validatePages(); + } + + if ($mess == "") { + // handle internal links to this learning module + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + ilLMPage::_handleImportRepositoryLinks( + $this->getImportId(), + $this->getType(), + $this->getRefId() + ); + } + + return $mess; + } + + /** + * Clone learning module + * + * @access public + * @param int target ref_id + * @param int copy id + * + */ + public function cloneObject($a_target_id, $a_copy_id = 0, $a_omit_tree = false) + { + $new_obj = parent::cloneObject($a_target_id, $a_copy_id, $a_omit_tree); + $this->cloneMetaData($new_obj); + //$new_obj->createProperties(); + + //copy online status if object is not the root copy object + $cp_options = ilCopyWizardOptions::_getInstance($a_copy_id); + + if (!$cp_options->isRootNode($this->getRefId())) { + $new_obj->setOfflineStatus($this->getOfflineStatus()); + } + + // $new_obj->setTitle($this->getTitle()); + $new_obj->setDescription($this->getDescription()); + $new_obj->setLayoutPerPage($this->getLayoutPerPage()); + $new_obj->setLayout($this->getLayout()); + $new_obj->setTOCMode($this->getTOCMode()); + $new_obj->setActiveLMMenu($this->isActiveLMMenu()); + $new_obj->setActiveTOC($this->isActiveTOC()); + $new_obj->setActiveNumbering($this->isActiveNumbering()); + $new_obj->setActivePrintView($this->isActivePrintView()); + $new_obj->setActivePreventGlossaryAppendix($this->isActivePreventGlossaryAppendix()); + $new_obj->setActiveDownloads($this->isActiveDownloads()); + $new_obj->setActiveDownloadsPublic($this->isActiveDownloadsPublic()); + $new_obj->setPublicNotes($this->publicNotes()); + $new_obj->setCleanFrames($this->cleanFrames()); + $new_obj->setHistoryUserComments($this->isActiveHistoryUserComments()); + $new_obj->setPublicAccessMode($this->getPublicAccessMode()); + $new_obj->setPageHeader($this->getPageHeader()); + $new_obj->setRating($this->hasRating()); + $new_obj->setRatingPages($this->hasRatingPages()); + $new_obj->setDisableDefaultFeedback($this->getDisableDefaultFeedback()); + $new_obj->setProgressIcons($this->getProgressIcons()); + $new_obj->setStoreTries($this->getStoreTries()); + $new_obj->setRestrictForwardNavigation($this->getRestrictForwardNavigation()); + $new_obj->setAutoGlossaries($this->getAutoGlossaries()); + + $new_obj->update(); + + $new_obj->createLMTree(); + + // copy style + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $style_id = $this->getStyleSheetId(); + if ($style_id > 0 && + !ilObjStyleSheet::_lookupStandard($style_id)) { + $style_obj = ilObjectFactory::getInstanceByObjId($style_id); + $new_id = $style_obj->ilClone(); + $new_obj->setStyleSheetId($new_id); + } else { // or just set the same standard style + $new_obj->setStyleSheetId($style_id); + } + $new_obj->update(); + + // copy content + $copied_nodes = $this->copyAllPagesAndChapters($new_obj, $a_copy_id); + + // page header and footer + if ($this->getHeaderPage() > 0 && ($new_page_header = $copied_nodes[$this->getHeaderPage()]) > 0) { + $new_obj->setHeaderPage($new_page_header); + } + if ($this->getFooterPage() > 0 && ($new_page_footer = $copied_nodes[$this->getFooterPage()]) > 0) { + $new_obj->setFooterPage($new_page_footer); + } + $new_obj->update(); + + // Copy learning progress settings + include_once('Services/Tracking/classes/class.ilLPObjSettings.php'); + $obj_settings = new ilLPObjSettings($this->getId()); + $obj_settings->cloneSettings($new_obj->getId()); + unset($obj_settings); + + // copy (page) multilang settings + include_once("./Services/Object/classes/class.ilObjectTranslation.php"); + $ot = ilObjectTranslation::getInstance($this->getId()); + $ot->copy($new_obj->getId()); + + // copy lm menu + include_once './Modules/LearningModule/classes/class.ilLMMenuEditor.php'; + $menu = new ilLMMenuEditor(); + $menu->setObjId($this->getId()); + $new_menu = new ilLMMenuEditor(); + $new_menu->setObjId($new_obj->getId()); + foreach ($menu->getMenuEntries() as $entry) { + /*'id' => $row->id, + 'title' => $row->title, + 'link' => $row->target, + 'type' => $row->link_type, + 'ref_id' => $row->link_ref_id, + 'active'*/ + + $new_menu->setTarget($entry["link"]); + $new_menu->setTitle($entry["title"]); + $new_menu->setLinkType($entry["type"]); + $new_menu->setLinkRefId($entry["ref_id"]); + $new_menu->create(); + ilLMMenuEditor::writeActive($new_menu->getEntryId(), $entry["active"] == "y" ? true : false); + } + + + return $new_obj; + } + + /** + * Copy all pages and chapters + * + * @param object $a_target_obj target learning module + */ + public function copyAllPagesAndChapters($a_target_obj, $a_copy_id = 0) + { + $parent_id = $a_target_obj->lm_tree->readRootId(); + + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); + + // get all chapters of root lm + $chapters = $this->lm_tree->getChildsByType($this->lm_tree->readRootId(), "st"); + $copied_nodes = array(); + //$time = time(); + foreach ($chapters as $chap) { + $cid = ilLMObject::pasteTree( + $a_target_obj, + $chap["child"], + $parent_id, + IL_LAST_NODE, + $time, + $copied_nodes, + true, + $this + ); + $target = $cid; + } + + // copy free pages + $pages = ilLMPageObject::getPageList($this->getId()); + foreach ($pages as $p) { + if (!$this->lm_tree->isInTree($p["obj_id"])) { + $item = new ilLMPageObject($this, $p["obj_id"]); + $target_item = $item->copy($a_target_obj); + $copied_nodes[$item->getId()] = $target_item->getId(); + } + } + + // Add mapping for pages and chapters + include_once './Services/CopyWizard/classes/class.ilCopyWizardOptions.php'; + $options = ilCopyWizardOptions::_getInstance($a_copy_id); + foreach ($copied_nodes as $old_id => $new_id) { + $options->appendMapping( + $this->getRefId() . '_' . $old_id, + $a_target_obj->getRefId() . '_' . $new_id + ); + } + + ilLMObject::updateInternalLinks($copied_nodes); + + $a_target_obj->checkTree(); + + return $copied_nodes; + } + + + /** + * Lookup auto glossaries + * + * @param + * @return + */ + public static function lookupAutoGlossaries($a_lm_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + // read auto glossaries + $set = $ilDB->query( + "SELECT * FROM lm_glossaries " . + " WHERE lm_id = " . $ilDB->quote($a_lm_id, "integer") + ); + $glos = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $glos[] = $rec["glo_id"]; + } + return $glos; + } + + /** + * Auto link glossary terms + * + * @param + * @return + */ + public function autoLinkGlossaryTerms($a_glo_ref_id) + { + // get terms + include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + $terms = ilGlossaryTerm::getTermList($a_glo_ref_id); + + // each get page: get content + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + $pages = ilLMPage::getAllPages($this->getType(), $this->getId()); + + // determine terms that occur in the page + $found_pages = array(); + foreach ($pages as $p) { + $pg = new ilLMPage($p["id"]); + $c = $pg->getXMLContent(); + foreach ($terms as $t) { + if (is_int(stripos($c, $t["term"]))) { + $found_pages[$p["id"]]["terms"][] = $t; + if (!is_object($found_pages[$p["id"]]["page"])) { + $found_pages[$p["id"]]["page"] = $pg; + } + } + } + reset($terms); + } + + // ilPCParagraph autoLinkGlossariesPage with page and terms + include_once("./Services/COPage/classes/class.ilPCParagraph.php"); + foreach ($found_pages as $id => $fp) { + ilPCParagraph::autoLinkGlossariesPage($fp["page"], $fp["terms"]); + } + } + + + //// + //// Online help + //// + + /** + * Is module an online module + * + * @return boolean true, if current learning module is an online help lm + */ + public static function isOnlineHelpModule($a_id, $a_as_obj_id = false) + { + if (!$a_as_obj_id && $a_id > 0 && $a_id == OH_REF_ID) { + return true; + } + if ($a_as_obj_id && $a_id > 0 && $a_id == ilObject::_lookupObjId(OH_REF_ID)) { + return true; + } + return false; + } + + public function setRating($a_value) + { + $this->rating = (bool) $a_value; + } + + public function hasRating() + { + return $this->rating; + } + + public function setRatingPages($a_value) + { + $this->rating_pages = (bool) $a_value; + } + + public function hasRatingPages() + { + return $this->rating_pages; + } + + + public function MDUpdateListener($a_element) + { + parent::MDUpdateListener($a_element); + + include_once 'Services/MetaData/classes/class.ilMD.php'; + + switch ($a_element) { + case 'Educational': + include_once("./Services/Object/classes/class.ilObjectLP.php"); + $obj_lp = ilObjectLP::getInstance($this->getId()); + if (in_array( + $obj_lp->getCurrentMode(), + array(ilLPObjSettings::LP_MODE_TLT, ilLPObjSettings::LP_MODE_COLLECTION_TLT) + )) { + include_once("./Services/Tracking/classes/class.ilLPStatusWrapper.php"); + ilLPStatusWrapper::_refreshStatus($this->getId()); + } + break; + + case 'General': + + // Update Title and description + $md = new ilMD($this->getId(), 0, $this->getType()); + if (!is_object($md_gen = $md->getGeneral())) { + return false; + } + + include_once("./Services/Object/classes/class.ilObjectTranslation.php"); + $ot = ilObjectTranslation::getInstance($this->getId()); + if ($ot->getContentActivated()) { + $ot->setDefaultTitle($md_gen->getTitle()); + + foreach ($md_gen->getDescriptionIds() as $id) { + $md_des = $md_gen->getDescription($id); + $ot->setDefaultDescription($md_des->getDescription()); + break; + } + $ot->save(); + } + break; + + } + return true; + } + + /** + * Get public export files + * + * @return array array of arrays with keys "type" (html, scorm or xml), "file" (filename) and "size" in bytes, "dir_type" detailed directoy type, e.g. html_de + */ + public function getPublicExportFiles() + { + $dirs = array("xml", "scorm"); + $export_files = array(); + + include_once("./Services/Object/classes/class.ilObjectTranslation.php"); + $ot = ilObjectTranslation::getInstance($this->getId()); + if ($ot->getContentActivated()) { + $langs = $ot->getLanguages(); + foreach ($langs as $l => $ldata) { + $dirs[] = "html_" . $l; + } + $dirs[] = "html_all"; + } else { + $dirs[] = "html"; + } + + foreach ($dirs as $dir) { + $type = explode("_", $dir); + $type = $type[0]; + if ($this->getPublicExportFile($type) != "") { + if (is_file($this->getExportDirectory($dir) . "/" . + $this->getPublicExportFile($type))) { + $size = filesize($this->getExportDirectory($dir) . "/" . + $this->getPublicExportFile($type)); + $export_files[] = array("type" => $type, + "dir_type" => $dir, + "file" => $this->getPublicExportFile($type), + "size" => $size); + } + } + } + + return $export_files; + } } -?> diff --git a/Modules/LearningModule/classes/class.ilObjContentObjectAccess.php b/Modules/LearningModule/classes/class.ilObjContentObjectAccess.php index 813c832eddfff74d700b5b93f87df73ea89bbd22..0e1456b38380b8799e925ddb230fde36f761ad7a 100644 --- a/Modules/LearningModule/classes/class.ilObjContentObjectAccess.php +++ b/Modules/LearningModule/classes/class.ilObjContentObjectAccess.php @@ -16,231 +16,206 @@ include_once("./Services/Object/classes/class.ilObjectAccess.php"); */ class ilObjContentObjectAccess extends ilObjectAccess { - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilAccessHandler - */ - protected $access; - - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->user = $DIC->user(); - $this->lng = $DIC->language(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->access = $DIC->access(); - } - - static $lo_access; - - /** - * checks wether a user may invoke a command or not - * (this method is called by ilAccessHandler::checkAccess) - * - * @param string $a_cmd command (not permission!) - * @param string $a_permission permission - * @param int $a_ref_id reference id - * @param int $a_obj_id object id - * @param int $a_user_id user id (if not provided, current user is taken) - * - * @return boolean true, if everything is ok - */ - function _checkAccess($a_cmd, $a_permission, $a_ref_id, $a_obj_id, $a_user_id = "") - { - $ilUser = $this->user; - $lng = $this->lng; - $rbacsystem = $this->rbacsystem; - $ilAccess = $this->access; - - if ($a_user_id == "") - { - $a_user_id = $ilUser->getId(); - } - - switch ($a_cmd) - { - case "continue": - - // continue is now default and works all the time - // see ilLMPresentationGUI::resume() - /* - if ($ilUser->getId() == ANONYMOUS_USER_ID) - { - $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("lm_no_continue_for_anonym")); - return false; - } - if (ilObjContentObjectAccess::_getLastAccessedPage($a_ref_id,$a_user_id) <= 0) - { - $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("not_accessed_yet")); - return false; - } - */ - break; - - // for permission query feature - case "info": - if(!ilObject::lookupOfflineStatus($a_obj_id)) - { - $ilAccess->addInfoItem(IL_STATUS_MESSAGE, $lng->txt("online")); - } - break; - - } - - return true; - } - - // - // access relevant methods - // - - - /** - * get last accessed page - * - * @param int $a_obj_id content object id - * @param int $a_user_id user object id - */ - static function _getLastAccessedPage($a_ref_id, $a_user_id = "") - { - global $DIC; - - $ilDB = $DIC->database(); - $ilUser = $DIC->user(); - - if ($a_user_id == "") - { - $a_user_id = $ilUser->getId(); - } - - if (isset(self::$lo_access[$a_ref_id])) - { - $acc_rec["obj_id"] = self::$lo_access[$a_ref_id]; - } - else - { - $q = "SELECT * FROM lo_access WHERE ". - "usr_id = ".$ilDB->quote($a_user_id, "integer")." AND ". - "lm_id = ".$ilDB->quote($a_ref_id, "integer"); - - $acc_set = $ilDB->query($q); - $acc_rec = $ilDB->fetchAssoc($acc_set); - } - - if ($acc_rec["obj_id"] > 0) - { - $lm_id = ilObject::_lookupObjId($a_ref_id); - $mtree = new ilTree($lm_id); - $mtree->setTableNames('lm_tree','lm_data'); - $mtree->setTreeTablePK("lm_id"); - if ($mtree->isInTree($acc_rec["obj_id"])) - { - return $acc_rec["obj_id"]; - } - } - - return 0; - } - - /** - * check whether goto script will succeed - */ - static function _checkGoto($a_target) - { - global $DIC; - - $ilAccess = $DIC->access(); - - $t_arr = explode("_", $a_target); - - if (($t_arr[0] != "lm" && $t_arr[0] != "st" - && $t_arr[0] != "pg") - || ((int) $t_arr[1]) <= 0) - { - return false; - } - - if ($t_arr[0] == "lm") - { - if ($ilAccess->checkAccess("read", "", $t_arr[1]) || - $ilAccess->checkAccess("visible", "", $t_arr[1])) - { - return true; - } - } - else - { - if ($t_arr[2] > 0) - { - $ref_ids = array($t_arr[2]); - } - else - { - // determine learning object - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - $lm_id = ilLMObject::_lookupContObjID($t_arr[1]); - $ref_ids = ilObject::_getAllReferences($lm_id); - } - // check read permissions - foreach ($ref_ids as $ref_id) - { - // Permission check - if ($ilAccess->checkAccess("read", "", $ref_id)) - { - return true; - } - } - - } - return false; - } - - /** - * Preload data - * - * @param array $a_obj_ids array of object ids - */ - static function _preloadData($a_obj_ids, $a_ref_ids) - { - global $DIC; - - $ilDB = $DIC->database(); - $ilUser = $DIC->user(); - - $q = "SELECT obj_id, lm_id FROM lo_access WHERE ". - "usr_id = ".$ilDB->quote($ilUser->getId(), "integer")." AND ". - $ilDB->in("lm_id", $a_ref_ids, false, "integer");; - $set = $ilDB->query($q); - foreach ($a_ref_ids as $r) - { - self::$lo_access[$r] = 0; - } - while ($rec = $ilDB->fetchAssoc($set)) - { - self::$lo_access[$rec["lm_id"]] = $rec["obj_id"]; - } - - } - + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilAccessHandler + */ + protected $access; + + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->user = $DIC->user(); + $this->lng = $DIC->language(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->access = $DIC->access(); + } + + public static $lo_access; + + /** + * checks wether a user may invoke a command or not + * (this method is called by ilAccessHandler::checkAccess) + * + * @param string $a_cmd command (not permission!) + * @param string $a_permission permission + * @param int $a_ref_id reference id + * @param int $a_obj_id object id + * @param int $a_user_id user id (if not provided, current user is taken) + * + * @return boolean true, if everything is ok + */ + public function _checkAccess($a_cmd, $a_permission, $a_ref_id, $a_obj_id, $a_user_id = "") + { + $ilUser = $this->user; + $lng = $this->lng; + $rbacsystem = $this->rbacsystem; + $ilAccess = $this->access; + + if ($a_user_id == "") { + $a_user_id = $ilUser->getId(); + } + + switch ($a_cmd) { + case "continue": + + // continue is now default and works all the time + // see ilLMPresentationGUI::resume() + /* + if ($ilUser->getId() == ANONYMOUS_USER_ID) + { + $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("lm_no_continue_for_anonym")); + return false; + } + if (ilObjContentObjectAccess::_getLastAccessedPage($a_ref_id,$a_user_id) <= 0) + { + $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("not_accessed_yet")); + return false; + } + */ + break; + + // for permission query feature + case "info": + if (!ilObject::lookupOfflineStatus($a_obj_id)) { + $ilAccess->addInfoItem(IL_STATUS_MESSAGE, $lng->txt("online")); + } + break; + + } + + return true; + } + + // + // access relevant methods + // + + + /** + * get last accessed page + * + * @param int $a_obj_id content object id + * @param int $a_user_id user object id + */ + public static function _getLastAccessedPage($a_ref_id, $a_user_id = "") + { + global $DIC; + + $ilDB = $DIC->database(); + $ilUser = $DIC->user(); + + if ($a_user_id == "") { + $a_user_id = $ilUser->getId(); + } + + if (isset(self::$lo_access[$a_ref_id])) { + $acc_rec["obj_id"] = self::$lo_access[$a_ref_id]; + } else { + $q = "SELECT * FROM lo_access WHERE " . + "usr_id = " . $ilDB->quote($a_user_id, "integer") . " AND " . + "lm_id = " . $ilDB->quote($a_ref_id, "integer"); + + $acc_set = $ilDB->query($q); + $acc_rec = $ilDB->fetchAssoc($acc_set); + } + + if ($acc_rec["obj_id"] > 0) { + $lm_id = ilObject::_lookupObjId($a_ref_id); + $mtree = new ilTree($lm_id); + $mtree->setTableNames('lm_tree', 'lm_data'); + $mtree->setTreeTablePK("lm_id"); + if ($mtree->isInTree($acc_rec["obj_id"])) { + return $acc_rec["obj_id"]; + } + } + + return 0; + } + + /** + * check whether goto script will succeed + */ + public static function _checkGoto($a_target) + { + global $DIC; + + $ilAccess = $DIC->access(); + + $t_arr = explode("_", $a_target); + + if (($t_arr[0] != "lm" && $t_arr[0] != "st" + && $t_arr[0] != "pg") + || ((int) $t_arr[1]) <= 0) { + return false; + } + + if ($t_arr[0] == "lm") { + if ($ilAccess->checkAccess("read", "", $t_arr[1]) || + $ilAccess->checkAccess("visible", "", $t_arr[1])) { + return true; + } + } else { + if ($t_arr[2] > 0) { + $ref_ids = array($t_arr[2]); + } else { + // determine learning object + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + $lm_id = ilLMObject::_lookupContObjID($t_arr[1]); + $ref_ids = ilObject::_getAllReferences($lm_id); + } + // check read permissions + foreach ($ref_ids as $ref_id) { + // Permission check + if ($ilAccess->checkAccess("read", "", $ref_id)) { + return true; + } + } + } + return false; + } + + /** + * Preload data + * + * @param array $a_obj_ids array of object ids + */ + public static function _preloadData($a_obj_ids, $a_ref_ids) + { + global $DIC; + + $ilDB = $DIC->database(); + $ilUser = $DIC->user(); + + $q = "SELECT obj_id, lm_id FROM lo_access WHERE " . + "usr_id = " . $ilDB->quote($ilUser->getId(), "integer") . " AND " . + $ilDB->in("lm_id", $a_ref_ids, false, "integer"); + ; + $set = $ilDB->query($q); + foreach ($a_ref_ids as $r) { + self::$lo_access[$r] = 0; + } + while ($rec = $ilDB->fetchAssoc($set)) { + self::$lo_access[$rec["lm_id"]] = $rec["obj_id"]; + } + } } - -?> diff --git a/Modules/LearningModule/classes/class.ilObjContentObjectGUI.php b/Modules/LearningModule/classes/class.ilObjContentObjectGUI.php index f17caa0d88a00752664fae60de38f875d788c682..8482a99f1d605e97bc72fe5499f963a74a8e23df 100755 --- a/Modules/LearningModule/classes/class.ilObjContentObjectGUI.php +++ b/Modules/LearningModule/classes/class.ilObjContentObjectGUI.php @@ -14,4085 +14,3990 @@ */ class ilObjContentObjectGUI extends ilObjectGUI implements ilLinkCheckerGUIRowHandling { - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilPluginAdmin - */ - protected $plugin_admin; - - /** - * @var ilHelpGUI - */ - protected $help; - - /** - * @var ilDB - */ - protected $db; - - /** - * @var Logger - */ - protected $log; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLocatorGUI - */ - protected $locator; - - /** - * Constructor - * - * @access public - */ - function __construct($a_data,$a_id = 0,$a_call_by_reference = true, $a_prepare_output = false) - { - global $DIC; - - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $this->tabs = $DIC->tabs(); - $this->error = $DIC["ilErr"]; - $this->settings = $DIC->settings(); - $this->user = $DIC->user(); - $this->tpl = $DIC["tpl"]; - $this->toolbar = $DIC->toolbar(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->tree = $DIC->repositoryTree(); - $this->plugin_admin = $DIC["ilPluginAdmin"]; - $this->help = $DIC["ilHelp"]; - $this->locator = $DIC["ilLocator"]; - $this->db = $DIC->database(); - $this->log = $DIC["ilLog"]; - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $this->ctrl = $ilCtrl; - $lng->loadLanguageModule("content"); - $lng->loadLanguageModule("obj"); - parent::__construct($a_data,$a_id,$a_call_by_reference,false); - } - - /** - * execute command - * @return bool|mixed - * @throws ilCtrlException - */ - function executeCommand() - { - $ilAccess = $this->access; - $lng = $this->lng; - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $ilErr = $this->error; - - if ($this->ctrl->getRedirectSource() == "ilinternallinkgui") - { - $this->explorer(); - return; - } - - if ($this->ctrl->getCmdClass() == "ilinternallinkgui") - { - $this->ctrl->setReturn($this, "explorer"); - } - - // get next class that processes or forwards current command - $next_class = $this->ctrl->getNextClass($this); - - // get current command - if ($_GET["to_props"] == 1) - { - $cmd = $this->ctrl->getCmd("properties"); - } - else - { - $cmd = $this->ctrl->getCmd("chapters"); - } - - - switch($next_class) - { - case 'illtiproviderobjectsettinggui': - - $this->setTabs(); - $ilTabs->setTabActive("settings"); - $this->setSubTabs("lti_provider"); - - $lti_gui = new ilLTIProviderObjectSettingGUI($this->object->getRefId()); - $lti_gui->setCustomRolesForSelection($GLOBALS['DIC']->rbac()->review()->getLocalRoles($this->object->getRefId())); - $lti_gui->offerLTIRolesForSelection(true); - $this->ctrl->forwardCommand($lti_gui); - break; - - - - case "illearningprogressgui": - $this->addHeaderAction(); - $this->addLocations(); - include_once './Services/Tracking/classes/class.ilLearningProgressGUI.php'; - $this->setTabs("learning_progress"); - - $new_gui = new ilLearningProgressGUI(ilLearningProgressGUI::LP_CONTEXT_REPOSITORY,$this->object->getRefId()); - $this->ctrl->forwardCommand($new_gui); - - break; - - case 'ilobjectmetadatagui': - if(!$ilAccess->checkAccess('write','',$this->object->getRefId())) - { - $ilErr->raiseError($this->lng->txt('permission_denied'),$ilErr->WARNING); - } - - $this->addHeaderAction(); - $this->addLocations(); - $this->setTabs("meta"); - - include_once 'Services/Object/classes/class.ilObjectMetaDataGUI.php'; - $md_gui = new ilObjectMetaDataGUI($this->object); - $md_gui->addMDObserver($this->object, 'MDUpdateListener', 'Educational'); // #9510 - $md_gui->addMDObserver($this->object, 'MDUpdateListener', 'General'); - $this->ctrl->forwardCommand($md_gui); - break; - - case "ilobjstylesheetgui": - $this->addLocations(); - 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" || $_GET["new_type"]=="sty") - { - $style_gui->setCreationMode(true); - } - $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 "illmpageobjectgui": - - $ilTabs->setBackTarget($lng->txt("learning module"), - $ilCtrl->getLinkTarget($this, "chapters")); - $this->ctrl->saveParameter($this, array("obj_id")); - $this->addLocations(); - $this->ctrl->setReturn($this, "chapters"); - - $pg_gui = new ilLMPageObjectGUI($this->object); - if ($_GET["obj_id"] != "") - { - $obj = ilLMObjectFactory::getInstance($this->object, $_GET["obj_id"]); - $pg_gui->setLMPageObject($obj); - } - $ret = $this->ctrl->forwardCommand($pg_gui); - break; - - case "ilstructureobjectgui": - $ilTabs->setBackTarget($lng->txt("learning module"), - $ilCtrl->getLinkTarget($this, "chapters")); - - $this->ctrl->saveParameter($this, array("obj_id")); - $this->addLocations(); - $this->ctrl->setReturn($this, "chapters"); - $st_gui = new ilStructureObjectGUI($this->object, $this->object->lm_tree); - if ($_GET["obj_id"] != "") - { - $obj = ilLMObjectFactory::getInstance($this->object, $_GET["obj_id"]); - $st_gui->setStructureObject($obj); - } - $ret = $this->ctrl->forwardCommand($st_gui); - if ($cmd == "save" || $cmd == "cancel") - { - if ($_GET["obj_id"] == "") - { - $this->ctrl->redirect($this, "chapters"); - } - else - { - $this->ctrl->setCmd("subchap"); - $this->executeCommand(); - } - } - break; - - case 'ilpermissiongui': - if (strtolower($_GET["baseClass"]) == "iladministrationgui") - { - $this->prepareOutput(); - } - else - { - $this->addHeaderAction(); - $this->addLocations(true); - $this->setTabs("perm"); - } - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $ret = $this->ctrl->forwardCommand($perm_gui); - break; - - // infoscreen - case 'ilinfoscreengui': - $this->addHeaderAction(); - $this->addLocations(true); - $this->setTabs("info"); - include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); - $info = new ilInfoScreenGUI($this); - $info->enablePrivateNotes(); - $info->enableLearningProgress(); - - $info->enableNews(); - if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) - { - $info->enableNewsEditing(); - $info->setBlockProperty("news", "settings", true); - } - - // show standard meta data section - $info->addMetaDataSections($this->object->getId(), 0, - $this->object->getType()); - - $ret = $this->ctrl->forwardCommand($info); - break; - - case "ilexportgui": - ilUtil::sendInfo($this->lng->txt("lm_only_one_download_per_type")); - $this->addHeaderAction(); - $this->addLocations(true); - $this->setTabs("export"); - include_once("./Services/Export/classes/class.ilExportGUI.php"); - $exp_gui = new ilExportGUI($this); - $exp_gui->addFormat("xml"); - include_once("./Services/Object/classes/class.ilObjectTranslation.php"); - $ot = ilObjectTranslation::getInstance($this->object->getId()); - if ($ot->getContentActivated()) - { - $exp_gui->addFormat("xml_master", "XML (".$lng->txt("cont_master_language_only").")", $this, "export"); - $exp_gui->addFormat("xml_masternomedia", "XML (".$lng->txt("cont_master_language_only_no_media").")", $this, "export"); - - $lng->loadLanguageModule("meta"); - $langs = $ot->getLanguages(); - foreach ($langs as $l => $ldata) - { - $exp_gui->addFormat("html_".$l, "HTML (".$lng->txt("meta_l_".$l).")", $this, "exportHTML"); - } - $exp_gui->addFormat("html_all", "HTML (".$lng->txt("cont_all_languages").")", $this, "exportHTML"); - } - else - { - $exp_gui->addFormat("html", "", $this, "exportHTML"); - } - - $exp_gui->addFormat("scorm", "", $this, "exportSCORM"); - $exp_gui->addCustomColumn($lng->txt("cont_public_access"), - $this, "getPublicAccessColValue"); - $exp_gui->addCustomMultiCommand($lng->txt("cont_public_access"), - $this, "publishExportFile"); - $ret = $this->ctrl->forwardCommand($exp_gui); - break; - - case 'ilobjecttranslationgui': - $this->addHeaderAction(); - $this->addLocations(true); - $this->setTabs("settings"); - $this->setSubTabs("obj_multilinguality"); - include_once("./Services/Object/classes/class.ilObjectTranslationGUI.php"); - $transgui = new ilObjectTranslationGUI($this); - $transgui->setTitleDescrOnlyMode(false); - $this->ctrl->forwardCommand($transgui); - break; - - - case "ilcommonactiondispatchergui": - include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); - $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); - $this->ctrl->forwardCommand($gui); - break; - - case 'ilobjectcopygui': - $this->prepareOutput(); - include_once './Services/Object/classes/class.ilObjectCopyGUI.php'; - $cp = new ilObjectCopyGUI($this); - $cp->setType('lm'); - $this->ctrl->forwardCommand($cp); - break; - - case "ilmobmultisrtuploadgui": - $this->addHeaderAction(); - $this->addLocations(true); - $this->setTabs("content"); - $this->setContentSubTabs("srt_files"); - include_once("./Services/MediaObjects/classes/class.ilMobMultiSrtUploadGUI.php"); - include_once("./Modules/LearningModule/classes/class.ilLMMultiSrt.php"); - $gui = new ilMobMultiSrtUploadGUI(new ilLMMultiSrt($this->object)); - $this->ctrl->forwardCommand($gui); - break; - - case "illmimportgui": - $this->addHeaderAction(); - $this->addLocations(true); - $this->setTabs("content"); - $this->setContentSubTabs("import"); - include_once("./Modules/LearningModule/classes/class.ilLMImportGUI.php"); - $gui = new ilLMImportGUI($this->object); - $this->ctrl->forwardCommand($gui); - break; - - case "illmeditshorttitlesgui": - $this->addHeaderAction(); - $this->addLocations(true); - $this->setTabs("content"); - $this->setContentSubTabs("short_titles"); - include_once("./Modules/LearningModule/classes/class.ilLMEditShortTitlesGUI.php"); - $gui = new ilLMEditShortTitlesGUI($this); - $this->ctrl->forwardCommand($gui); - break; - - default: - $new_type = $_POST["new_type"] - ? $_POST["new_type"] - : $_GET["new_type"]; - - - if ($cmd == "create" && - !in_array($new_type, array("lm"))) - { - switch ($new_type) - { - case "pg": - $this->setTabs(); - $this->ctrl->setCmdClass("ilLMPageObjectGUI"); - $ret = $this->executeCommand(); - break; - - case "st": - $this->setTabs(); - $this->ctrl->setCmdClass("ilStructureObjectGUI"); - $ret = $this->executeCommand(); - break; - } - } - else - { - // creation of new dbk/lm in repository - if ($this->getCreationMode() == true && - in_array($new_type, array("lm"))) - { - $this->prepareOutput(); - if ($cmd == "") // this may be due to too big upload files - { - $cmd = "create"; - } - $cmd .= "Object"; - $ret = $this->$cmd(); - } - else - { - $this->addHeaderAction(); - $this->addLocations(); - $ret = $this->$cmd(); - } - } - break; - } - return $ret; - } - - static function _forwards() - { - return array("ilLMPageObjectGUI", "ilStructureObjectGUI","ilObjStyleSheetGUI"); - } - - /** - * edit properties form - */ - function properties() - { - $lng = $this->lng; - - $lng->loadLanguageModule("style"); - $this->setTabs("settings"); - $this->setSubTabs("settings"); - - // lm properties - $this->initPropertiesForm(); - $this->getPropertiesFormValues(); - - if($this->object->getType() == "lm") - { - // Edit ecs export settings - include_once 'Modules/LearningModule/classes/class.ilECSLearningModuleSettings.php'; - $ecs = new ilECSLearningModuleSettings($this->object); - $ecs->addSettingsToForm($this->form, 'lm'); - } - - $this->tpl->setContent($this->form->getHTML()); - } - - /** - * Init properties form - */ - function initPropertiesForm() - { - $obj_service = $this->object_service; - - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilSetting = $this->settings; - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - // title - $ti = new ilTextInputGUI($lng->txt("title"), "title"); - $ti->setRequired(true); - $this->form->addItem($ti); - - // description - $ta = new ilTextAreaInputGUI($lng->txt("desc"), "description"); - $this->form->addItem($ta); - - $lng->loadLanguageModule("rep"); - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($this->lng->txt('rep_activation_availability')); - $this->form->addItem($section); - - // online - $online = new ilCheckboxInputGUI($lng->txt("cont_online"), "cobj_online"); - $this->form->addItem($online); - - // presentation - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($this->lng->txt('cont_presentation')); - $this->form->addItem($section); - - // tile image - $obj_service->commonSettings()->legacyForm($this->form, $this->object)->addTileImage(); - - // default layout - $layout = self::getLayoutOption($lng->txt("cont_def_layout"), "lm_layout"); - $this->form->addItem($layout); - - // layout per page - $lpp = new ilCheckboxInputGUI($lng->txt("cont_layout_per_page"), "layout_per_page"); - $lpp->setInfo($this->lng->txt("cont_layout_per_page_info")); - $this->form->addItem($lpp); - - // page header - $page_header = new ilSelectInputGUI($lng->txt("cont_page_header"), "lm_pg_header"); - $option = array ("st_title" => $this->lng->txt("cont_st_title"), - "pg_title" => $this->lng->txt("cont_pg_title"), - "none" => $this->lng->txt("cont_none")); - $page_header->setOptions($option); - $this->form->addItem($page_header); - - // chapter numeration - $chap_num = new ilCheckboxInputGUI($lng->txt("cont_act_number"), "cobj_act_number"); - $this->form->addItem($chap_num); - - // toc mode - $toc_mode = new ilSelectInputGUI($lng->txt("cont_toc_mode"), "toc_mode"); - $option = array ("chapters" => $this->lng->txt("cont_chapters_only"), - "pages" => $this->lng->txt("cont_chapters_and_pages")); - $toc_mode->setOptions($option); - $this->form->addItem($toc_mode); - - // show progress icons - $progr_icons = new ilCheckboxInputGUI($lng->txt("cont_progress_icons"), "progr_icons"); - $progr_icons->setInfo($this->lng->txt("cont_progress_icons_info")); - $this->form->addItem($progr_icons); - - // self assessment - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($this->lng->txt('cont_self_assessment')); - $this->form->addItem($section); - - // tries - $radg = new ilRadioGroupInputGUI($lng->txt("cont_tries"), "store_tries"); - $radg->setValue(0); - $op1 = new ilRadioOption($lng->txt("cont_tries_reset_on_visit"), 0,$lng->txt("cont_tries_reset_on_visit_info")); - $radg->addOption($op1); - $op2 = new ilRadioOption($lng->txt("cont_tries_store"), 1,$lng->txt("cont_tries_store_info")); - $radg->addOption($op2); - $this->form->addItem($radg); - - // restrict forward navigation - $qfeed = new ilCheckboxInputGUI($lng->txt("cont_restrict_forw_nav"), "restrict_forw_nav"); - $qfeed->setInfo($this->lng->txt("cont_restrict_forw_nav_info")); - $this->form->addItem($qfeed); - - // notification - $not = new ilCheckboxInputGUI($lng->txt("cont_notify_on_blocked_users"), "notification_blocked_users"); - $not->setInfo($this->lng->txt("cont_notify_on_blocked_users_info")); - $qfeed->addSubItem($not); - - // disable default feedback for questions - $qfeed = new ilCheckboxInputGUI($lng->txt("cont_disable_def_feedback"), "disable_def_feedback"); - $qfeed->setInfo($this->lng->txt("cont_disable_def_feedback_info")); - $this->form->addItem($qfeed); - - // additional features - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($this->lng->txt('obj_features')); - $this->form->addItem($section); - - // public notes - if (!$ilSetting->get('disable_comments')) - { - $this->lng->loadLanguageModule("notes"); - $pub_nodes = new ilCheckboxInputGUI($lng->txt("notes_comments"), "cobj_pub_notes"); - $pub_nodes->setInfo($this->lng->txt("cont_lm_comments_desc")); - $this->form->addItem($pub_nodes); - } - - // history user comments - $com = new ilCheckboxInputGUI($lng->txt("enable_hist_user_comments"), "cobj_user_comments"); - $com->setInfo($this->lng->txt("enable_hist_user_comments_desc")); - $this->form->addItem($com); - - // rating - $this->lng->loadLanguageModule('rating'); - $rate = new ilCheckboxInputGUI($this->lng->txt('rating_activate_rating'), 'rating'); - $rate->setInfo($this->lng->txt('rating_activate_rating_info')); - $this->form->addItem($rate); - $ratep = new ilCheckboxInputGUI($this->lng->txt('lm_activate_rating'), 'rating_pages'); - $this->form->addItem($ratep); - - $this->form->setTitle($lng->txt("cont_lm_properties")); - $this->form->addCommandButton("saveProperties", $lng->txt("save")); - $this->form->setFormAction($ilCtrl->getFormAction($this)); - } - - /** - * Get values for properties form - */ - function getPropertiesFormValues() - { - $ilUser = $this->user; - - $values = array(); - - $title = $this->object->getTitle(); - $description = $this->object->getDescription(); - include_once("./Services/Object/classes/class.ilObjectTranslation.php"); - $ot = ilObjectTranslation::getInstance($this->object->getId()); - if ($ot->getContentActivated()) - { - $title = $ot->getDefaultTitle(); - $description = $ot->getDefaultDescription(); - } - - $values["title"] = $title; - $values["description"] = $description; - if(!$this->object->getOfflineStatus()) - { - $values["cobj_online"] = true; - } - $values["lm_layout"] = $this->object->getLayout(); - $values["lm_pg_header"] = $this->object->getPageHeader(); - if ($this->object->isActiveNumbering()) - { - $values["cobj_act_number"] = true; - } - $values["toc_mode"] = $this->object->getTOCMode(); - if ($this->object->publicNotes()) - { - $values["cobj_pub_notes"] = true; - } - if ($this->object->cleanFrames()) - { - $values["cobj_clean_frames"] = true; - } - if ($this->object->isActiveHistoryUserComments()) - { - $values["cobj_user_comments"] = true; - } - $values["layout_per_page"] = $this->object->getLayoutPerPage(); - $values["rating"] = $this->object->hasRating(); - $values["rating_pages"] = $this->object->hasRatingPages(); - $values["disable_def_feedback"] = $this->object->getDisableDefaultFeedback(); - $values["progr_icons"] = $this->object->getProgressIcons(); - $values["store_tries"] = $this->object->getStoreTries(); - $values["restrict_forw_nav"] = $this->object->getRestrictForwardNavigation(); - - include_once "./Services/Notification/classes/class.ilNotification.php"; - $values["notification_blocked_users"] = ilNotification::hasNotification( - ilNotification::TYPE_LM_BLOCKED_USERS, $ilUser->getId(), - $this->object->getId()); - - $this->form->setValuesByArray($values); - } - - /** - * save properties - */ - function saveProperties() - { - $lng = $this->lng; - $ilUser = $this->user; - $ilSetting = $this->settings; - $obj_service = $this->object_service; - - $valid = false; - $this->initPropertiesForm(); - if ($this->form->checkInput()) - { - include_once("./Services/Object/classes/class.ilObjectTranslation.php"); - $ot = ilObjectTranslation::getInstance($this->object->getId()); - if ($ot->getContentActivated()) - { - $ot->setDefaultTitle($_POST['title']); - $ot->setDefaultDescription($_POST['description']); - $ot->save(); - } - - $this->object->setTitle($_POST['title']); - $this->object->setDescription($_POST['description']); - $this->object->setLayout($_POST["lm_layout"]); - $this->object->setPageHeader($_POST["lm_pg_header"]); - $this->object->setTOCMode($_POST["toc_mode"]); - $this->object->setOfflineStatus(!($_POST['cobj_online'])); - $this->object->setActiveNumbering($_POST["cobj_act_number"]); - $this->object->setCleanFrames($_POST["cobj_clean_frames"]); - if (!$ilSetting->get('disable_comments')) - { - $this->object->setPublicNotes($_POST["cobj_pub_notes"]); - } - $this->object->setHistoryUserComments($_POST["cobj_user_comments"]); - $this->object->setLayoutPerPage($_POST["layout_per_page"]); - $this->object->setRating($_POST["rating"]); - $this->object->setRatingPages($_POST["rating_pages"]); - $this->object->setDisableDefaultFeedback((int) $_POST["disable_def_feedback"]); - $this->object->setProgressIcons((int) $_POST["progr_icons"]); - - $add_info = ""; - if ($_POST["restrict_forw_nav"] && !$_POST["store_tries"]) - { - $_POST["store_tries"] = 1; - $add_info = "
".$lng->txt("cont_automatically_set_store_tries"); - $add_info = str_replace("$1", $lng->txt("cont_tries_store"), $add_info); - $add_info = str_replace("$2", $lng->txt("cont_restrict_forw_nav"), $add_info); - } - - $this->object->setStoreTries((int) $_POST["store_tries"]); - $this->object->setRestrictForwardNavigation((int) $_POST["restrict_forw_nav"]); - $this->object->updateProperties(); - $this->object->update(); - - // tile image - $obj_service->commonSettings()->legacyForm($this->form, $this->object)->saveTileImage(); - - include_once "./Services/Notification/classes/class.ilNotification.php"; - ilNotification::setNotification(ilNotification::TYPE_LM_BLOCKED_USERS, - $ilUser->getId(), $this->object->getId(), - (bool)$this->form->getInput("notification_blocked_users")); - - - if($this->object->getType() == 'lm') - { - // Update ecs export settings - include_once 'Modules/LearningModule/classes/class.ilECSLearningModuleSettings.php'; - $ecs = new ilECSLearningModuleSettings($this->object); - if($ecs->handleSettingsUpdate()) - { - $valid = true; - } - } - else - { - $valid = true; - } - } - - if($valid) - { - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified").$add_info, true); - $this->ctrl->redirect($this, "properties"); - } - else - { - $lng->loadLanguageModule("style"); - $this->setTabs("settings"); - $this->setSubTabs("cont_general_properties"); - - $this->form->setValuesByPost(); - $this->tpl->setContent($this->form->getHTML()); - } - } - - /** - * Edit style properties - */ - function editStyleProperties() - { - $tpl = $this->tpl; - - $this->initStylePropertiesForm(); - $tpl->setContent($this->form->getHTML()); - } - - /** - * Init style properties form - */ - function initStylePropertiesForm() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilTabs = $this->tabs; - $ilSetting = $this->settings; - - $lng->loadLanguageModule("style"); - $this->setTabs(); - $ilTabs->setTabActive("settings"); - $this->setSubTabs("cont_style"); - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - $fixed_style = $ilSetting->get("fixed_content_style_id"); - $def_style = $ilSetting->get("default_content_style_id"); - $style_id = $this->object->getStyleSheetId(); - - if ($fixed_style > 0) - { - $st = new ilNonEditableValueGUI($lng->txt("cont_current_style")); - $st->setValue(ilObject::_lookupTitle($fixed_style)." (". - $this->lng->txt("global_fixed").")"); - $this->form->addItem($st); - } - else - { - $st_styles = ilObjStyleSheet::_getStandardStyles(true, false, - $_GET["ref_id"]); - - if ($def_style > 0) - { - $st_styles[0] = ilObject::_lookupTitle($def_style)." (".$this->lng->txt("default").")"; - } - else - { - $st_styles[0] = $this->lng->txt("default"); - } - ksort($st_styles); - - if ($style_id > 0) - { - // individual style - if (!ilObjStyleSheet::_lookupStandard($style_id)) - { - $st = new ilNonEditableValueGUI($lng->txt("cont_current_style")); - $st->setValue(ilObject::_lookupTitle($style_id)); - $this->form->addItem($st); - - // delete command - $this->form->addCommandButton("editStyle", - $lng->txt("cont_edit_style")); - $this->form->addCommandButton("deleteStyle", - $lng->txt("cont_delete_style")); - } - } - - if ($style_id <= 0 || ilObjStyleSheet::_lookupStandard($style_id)) - { - $style_sel = new ilSelectInputGUI($lng->txt("cont_current_style"), "style_id"); - $style_sel->setOptions($st_styles); - $style_sel->setValue($style_id); - $this->form->addItem($style_sel); - $this->form->addCommandButton("saveStyleSettings", - $lng->txt("save")); - $this->form->addCommandButton("createStyle", - $lng->txt("sty_create_ind_style")); - } - } - $this->form->setTitle($lng->txt("cont_style")); - $this->form->setFormAction($ilCtrl->getFormAction($this)); - } - - /** - * Create Style - */ - function createStyle() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirectByClass("ilobjstylesheetgui", "create"); - } - - /** - * Edit Style - */ - function editStyle() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirectByClass("ilobjstylesheetgui", "edit"); - } - - /** - * Delete Style - */ - function deleteStyle() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirectByClass("ilobjstylesheetgui", "delete"); - } - - /** - * Save style settings - */ - function saveStyleSettings() - { - $ilSetting = $this->settings; - - if ($ilSetting->get("fixed_content_style_id") <= 0 && - (ilObjStyleSheet::_lookupStandard($this->object->getStyleSheetId()) - || $this->object->getStyleSheetId() == 0)) - { - $this->object->setStyleSheetId(ilUtil::stripSlashes($_POST["style_id"])); - $this->object->update(); - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - } - $this->ctrl->redirect($this, "editStyleProperties"); - } - - /** - * Init menu form - */ - public function initMenuForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - - // enable menu - $menu = new ilCheckboxInputGUI($this->lng->txt("cont_active"), "cobj_act_lm_menu"); - $menu->setChecked($this->object->isActiveLMMenu()); - $form->addItem($menu); - - // toc - $toc = new ilCheckboxInputGUI($this->lng->txt("cont_toc"), "cobj_act_toc"); - $toc->setChecked($this->object->isActiveTOC()); - $form->addItem($toc); - - // print view - $print = new ilCheckboxInputGUI($this->lng->txt("cont_print_view"), "cobj_act_print"); - $print->setChecked($this->object->isActivePrintView()); - $form->addItem($print); - - // prevent glossary appendix - $glo = new ilCheckboxInputGUI($this->lng->txt("cont_print_view_pre_glo"), "cobj_act_print_prev_glo"); - $glo->setChecked($this->object->isActivePreventGlossaryAppendix()); - $print->addSubItem($glo); - - // hide header and footer in print view - $hhfp = new ilCheckboxInputGUI($this->lng->txt("cont_hide_head_foot_print"), "hide_head_foot_print"); - $hhfp->setChecked($this->object->getHideHeaderFooterPrint()); - $print->addSubItem($hhfp); - - // downloads - $no_download_file_available = - " ".$lng->txt("cont_no_download_file_available"). - " ".$lng->txt("change").""; - $types = array("xml", "html", "scorm"); - foreach($types as $type) - { - if ($this->object->getPublicExportFile($type) != "") - { - if (is_file($this->object->getExportDirectory($type)."/". - $this->object->getPublicExportFile($type))) - { - $no_download_file_available = ""; - } - } - } - $dl = new ilCheckboxInputGUI($this->lng->txt("cont_downloads"), "cobj_act_downloads"); - $dl->setInfo($this->lng->txt("cont_downloads_desc").$no_download_file_available); - $dl->setChecked($this->object->isActiveDownloads()); - $form->addItem($dl); - - // downloads in public area - $pdl = new ilCheckboxInputGUI($this->lng->txt("cont_downloads_public_desc"), "cobj_act_downloads_public"); - $pdl->setChecked($this->object->isActiveDownloadsPublic()); - $dl->addSubItem($pdl); - - $form->addCommandButton("saveMenuProperties", $lng->txt("save")); - - $form->setTitle($lng->txt("cont_lm_menu")); - $form->setFormAction($ilCtrl->getFormAction($this)); - - return $form; - } - - /** - * Edit menu properies - */ - function editMenuProperties() - { - $lng = $this->lng; - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - - $lng->loadLanguageModule("style"); - $this->setTabs(); - $ilTabs->setTabActive("settings"); - $this->setSubTabs("cont_lm_menu"); - - $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); - $ilToolbar->addFormButton($this->lng->txt("add_menu_entry"), "addMenuEntry"); - $ilToolbar->setCloseFormTag(false); - - $form = $this->initMenuForm(); - $form->setOpenTag(false); - $form->setCloseTag(false); - - $this->__initLMMenuEditor(); - $entries = $this->lmme_obj->getMenuEntries(); - include_once("./Modules/LearningModule/classes/class.ilLMMenuItemsTableGUI.php"); - $table = new ilLMMenuItemsTableGUI($this, "editMenuProperties", $this->lmme_obj); - $table->setOpenFormTag(false); - - $tpl->setContent($form->getHTML()."
".$table->getHTML()); - } - - /** - * save properties - */ - function saveMenuProperties() - { - $this->object->setActiveLMMenu((int) $_POST["cobj_act_lm_menu"]); - $this->object->setActiveTOC((int) $_POST["cobj_act_toc"]); - $this->object->setActivePrintView((int) $_POST["cobj_act_print"]); - $this->object->setActivePreventGlossaryAppendix((int) $_POST["cobj_act_print_prev_glo"]); - $this->object->setHideHeaderFooterPrint((int) $_POST["hide_head_foot_print"]); - $this->object->setActiveDownloads((int) $_POST["cobj_act_downloads"]); - $this->object->setActiveDownloadsPublic((int) $_POST["cobj_act_downloads_public"]); - $this->object->updateProperties(); - - $this->__initLMMenuEditor(); -//var_dump($_POST["menu_entries"]); exit; - $this->lmme_obj->updateActiveStatus($_POST["menu_entries"]); - - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "editMenuProperties"); - } - - /** - * output explorer tree - */ - function explorer() - { - $ilCtrl = $this->ctrl; - - $gui_class = "ilobjlearningmodulegui"; - - $ilCtrl->setParameterByClass($gui_class, "active_node", $_GET["active_node"]); - - $this->tpl = new ilTemplate("tpl.main.html", true, true); - - $this->tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); - - $this->tpl->addBlockFile("CONTENT", "content", "tpl.explorer.html"); - $this->tpl->setVariable("IMG_SPACE", ilUtil::getImagePath("spacer.png", false)); - - require_once ("./Modules/LearningModule/classes/class.ilLMEditorExplorer.php"); - $exp = new ilLMEditorExplorer($this->ctrl->getLinkTarget($this, "view"), - $this->object, $gui_class); - - $exp->setTargetGet("obj_id"); - $exp->setExpandTarget($this->ctrl->getLinkTarget($this, "explorer")); - - if ($_GET["lmmovecopy"] == "1") - { - $this->proceedDragDrop(); - } - - - if ($_GET["lmexpand"] == "") - { - $mtree = new ilTree($this->object->getId()); - $mtree->setTableNames('lm_tree','lm_data'); - $mtree->setTreeTablePK("lm_id"); - $expanded = $mtree->readRootId(); - } - else - { - $expanded = $_GET["lmexpand"]; - } - if ($_GET["active_node"] != "") - { - $path = $this->lm_tree->getPathId($_GET["active_node"]); - $exp->setForceOpenPath($path); - - $exp->highlightNode($_GET["active_node"]); - } - $exp->setExpand($expanded); - - // build html-output - $exp->setOutput(0); - $output = $exp->getOutput(); - - // asynchronous output - if ($ilCtrl->isAsynch()) - { - echo $output; exit; - } - - include_once("./Services/COPage/classes/class.ilPageEditorGUI.php"); - - $this->tpl->setCurrentBlock("content"); - $this->tpl->setVariable("TXT_EXPLORER_HEADER", $this->lng->txt("cont_chap_and_pages")); - $this->tpl->setVariable("EXP_REFRESH", $this->lng->txt("refresh")); - $this->tpl->setVariable("EXPLORER",$output); - $this->ctrl->setParameter($this, "lmexpand", $_GET["lmexpand"]); - $this->tpl->setVariable("ACTION", $this->ctrl->getLinkTarget($this, "explorer")); - $this->tpl->parseCurrentBlock(); - $this->tpl->show(false); - exit; - } - - /** - * popup window for wysiwyg editor - */ - function popup() - { - include_once "./Services/COPage/classes/class.ilWysiwygUtil.php"; - $popup = new ilWysiwygUtil(); - $popup->show($_GET["ptype"]); - exit; - } - - /** - * proceed drag and drop operations on pages/chapters - */ - function proceedDragDrop() - { - $ilCtrl = $this->ctrl; - - $this->object->executeDragDrop($_POST["il_hform_source_id"], $_POST["il_hform_target_id"], - $_POST["il_hform_fc"], $_POST["il_hform_as_subitem"]); - $ilCtrl->redirect($this, "chapters"); - } - - /* protected function initCreationForms($a_new_type) - { - $forms = array(self::CFORM_NEW => $this->initCreateForm($a_new_type), - self::CFORM_IMPORT => $this->initImportForm()); - - return $forms; - }*/ - - protected function afterSave(ilObject $a_new_object) - { - $a_new_object->setCleanFrames(true); - $a_new_object->update(); - - // create content object tree - $a_new_object->createLMTree(); - - // create a first chapter - $a_new_object->addFirstChapterAndPage(); - - // always send a message - ilUtil::sendSuccess($this->lng->txt($this->type."_added"), true); - ilUtil::redirect("ilias.php?ref_id=".$a_new_object->getRefId(). - "&baseClass=ilLMEditorGUI"); - } - - /** - * Init import form. - */ - public function initImportForm($a_new_type) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - - $new_type = $_POST["new_type"] ? $_POST["new_type"] : $_GET["new_type"]; - $this->ctrl->setParameter($this, "new_type", $new_type); - - $form->setTarget(ilFrameTargetInfo::_getFrame("MainContent")); - $form->setTableWidth("600px"); - - // import file - //$fi = new ilFileInputGUI($this->lng->txt("file"), "xmldoc"); - $fi = new ilFileInputGUI($this->lng->txt("file"), "importfile"); - $fi->setSuffixes(array("zip")); - $fi->setRequired(true); - $fi->setSize(30); - $form->addItem($fi); - - // validation - $cb = new ilCheckboxInputGUI($this->lng->txt("cont_validate_file"), "validate"); - $cb->setInfo($this->lng->txt("")); - $form->addItem($cb); - - $form->addCommandButton("importFile", $lng->txt("import")); - $form->addCommandButton("cancel", $lng->txt("cancel")); - - $form->setTitle($this->lng->txt("import_".$new_type)); - $form->setFormAction($ilCtrl->getFormAction($this)); - - return $form; - } - - /** - * export object - * - * @access public - */ - function exportObject() - { - return; - } - - /** - * display dialogue for importing XML-LeaningObjects - * - * @access public - */ - function importObject() - { - $this->createObject(); - return; - } - - - /** - * display status information or report errors messages - * in case of error - * - * @access public - */ - function importFileObject($parent_id = NULL, $a_catch_errors = true) - { - $rbacsystem = $this->rbacsystem; - $ilErr = $this->error; - $tpl = $this->tpl; - - $form = $this->initImportForm("lm"); - - try - { - // the new import - parent::importFileObject(null, false); - return; - } - catch (ilManifestFileNotFoundImportException $e) - { - // we just run through in this case. - $no_manifest = true; - } - catch (ilException $e) - { - // display message and form again - ilUtil::sendFailure($this->lng->txt("obj_import_file_error")."
".$e->getMessage()); - $form->setValuesByPost(); - $tpl->setContent($form->getHtml()); - return; - } - - if (!$no_manifest) - { - return; // something different has gone wrong, but we have a manifest, this is definitely not "the old" import - } - - // the "old" (pre 5.1) import - - include_once "./Modules/LearningModule/classes/class.ilObjLearningModule.php"; - - if (!$rbacsystem->checkAccess("create", $_GET["ref_id"], $_GET["new_type"])) - { - $ilErr->raiseError($this->lng->txt("no_create_permission"), $ilErr->MESSAGE); - return; - } - - if ($form->checkInput()) - { - // create and insert object in objecttree - include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); - $newObj = new ilObjContentObject(); - $newObj->setType($_GET["new_type"]); - $newObj->setTitle($_FILES["importfile"]["name"]); - $newObj->setDescription(""); - $newObj->create(true); - $newObj->createReference(); - $newObj->putInTree($_GET["ref_id"]); - $newObj->setPermissions($_GET["ref_id"]); - - // create learning module tree - $newObj->createLMTree(); - - // since the "new" import already did the extracting - $mess = $newObj->importFromDirectory($this->tmp_import_dir, $_POST["validate"]); - - if ($mess == "") - { - ilUtil::sendSuccess($this->lng->txt($this->type."_added"),true); - ilUtil::redirect("ilias.php?ref_id=".$newObj->getRefId(). - "&baseClass=ilLMEditorGUI"); - } - else - { - $link = ''.$this->lng->txt("btn_next").''; - $tpl->setContent("
".$link."

".$mess.$link); - } - } - else - { - $form->setValuesByPost(); - $tpl->setContent($form->getHtml()); - } - } - - /** - * show chapters - */ - function chapters() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->setTabs(); - $this->setContentSubTabs("chapters"); - - $ilCtrl->setParameter($this, "backcmd", "chapters"); - - include_once("./Modules/LearningModule/classes/class.ilChapterHierarchyFormGUI.php"); - $form_gui = new ilChapterHierarchyFormGUI($this->object->getType(), $_GET["transl"]); - $form_gui->setFormAction($ilCtrl->getFormAction($this)); - $form_gui->setTitle($this->object->getTitle()); - $form_gui->setIcon(ilUtil::getImagePath("icon_lm.svg")); - $form_gui->setTree($this->lm_tree); - $form_gui->setMaxDepth(0); - $form_gui->setCurrentTopNodeId($this->tree->getRootId()); - $form_gui->addMultiCommand($lng->txt("delete"), "delete"); - $form_gui->addMultiCommand($lng->txt("cut"), "cutItems"); - $form_gui->addMultiCommand($lng->txt("copy"), "copyItems"); - if ($this->object->getLayoutPerPage()) - { - $form_gui->addMultiCommand($lng->txt("cont_set_layout"), "setPageLayoutInHierarchy"); - } - $form_gui->setDragIcon(ilUtil::getImagePath("icon_st.svg")); - $form_gui->addCommand($lng->txt("cont_save_all_titles"), "saveAllTitles"); - $up_gui = "ilobjlearningmodulegui"; - - $ctpl = new ilTemplate("tpl.chap_and_pages.html", true, true, "Modules/LearningModule"); - $ctpl->setVariable("HIERARCHY_FORM", $form_gui->getHTML()); - $ilCtrl->setParameter($this, "obj_id", ""); - - $ml_head = self::getMultiLangHeader($this->object->getId(), $this); - - $this->tpl->setContent($ml_head.$ctpl->get()); - } - - /** - * Get multi lang header - * - * @param - * @return - */ - static function getMultiLangHeader($a_lm_id, $a_gui_class, $a_mode = "") - { - global $DIC; - - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - - // multi language - include_once("./Services/Object/classes/class.ilObjectTranslation.php"); - $ot = ilObjectTranslation::getInstance($a_lm_id); - if ($ot->getContentActivated()) - { - $ilCtrl->setParameter($a_gui_class, "lang_switch_mode", $a_mode); - $lng->loadLanguageModule("meta"); - - // info - include_once("./Services/COPage/classes/class.ilPageMultiLangGUI.php"); - $ml_gui = new ilPageMultiLangGUI("lm", $a_lm_id); - $ml_head = $ml_gui->getMultiLangInfo($_GET["transl"]); - - // language switch - include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"); - $list = new ilAdvancedSelectionListGUI(); - $list->setListTitle($lng->txt("actions")); - $list->setId("copage_act"); - $entries = false; - if (!in_array($_GET["transl"], array("", "-"))) - { - $l = $ot->getMasterLanguage(); - $list->addItem($lng->txt("cont_edit_language_version").": ". - $lng->txt("meta_l_".$l), "", - $ilCtrl->getLinkTarget($a_gui_class, "editMasterLanguage")); - $entries = true; - } - - foreach ($ot->getLanguages() as $al => $lang) - { - if ($_GET["transl"] != $al && - $al != $ot->getMasterLanguage()) - { - $ilCtrl->setParameter($a_gui_class, "totransl", $al); - $list->addItem($lng->txt("cont_edit_language_version").": ". - $lng->txt("meta_l_".$al), "", - $ilCtrl->getLinkTarget($a_gui_class, "switchToLanguage")); - $ilCtrl->setParameter($a_gui_class, "totransl", $_GET["totransl"]); - } - $entries = true; - } - - if ($entries) - { - $ml_head = '
'.$ml_head.'
'.$list->getHTML()."
"; - } - $ilCtrl->setParameter($a_gui_class, "lang_switch_mode", ""); - } - - return $ml_head; - } - - - /* - * List all pages of learning module - */ - function pages() - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->setTabs(); - $this->setContentSubTabs("pages"); - - $ilCtrl->setParameter($this, "backcmd", "pages"); - $ilCtrl->setParameterByClass("illmpageobjectgui", "new_type", "pg"); - $ilToolbar->addButton($lng->txt("pg_add"), - $ilCtrl->getLinkTargetByClass("illmpageobjectgui", "create")); - $ilCtrl->setParameterByClass("illmpageobjectgui", "new_type", ""); - - include_once("./Modules/LearningModule/classes/class.ilLMPagesTableGUI.php"); - $t = new ilLMPagesTableGUI($this, "pages", $this->object); - $tpl->setContent($t->getHTML()); - } - - /** - * List all broken links - */ - function listLinks() - { - $tpl = $this->tpl; - - $this->setTabs(); - $this->setContentSubTabs("internal_links"); - - include_once("./Modules/LearningModule/classes/class.ilLinksTableGUI.php"); - $table_gui = new ilLinksTableGUI($this, "listLinks", - $this->object->getId(), $this->object->getType()); - - $tpl->setContent($table_gui->getHTML()); - } - - /** - * Show maintenance - */ - function showMaintenance() - { - $ilToolbar = $this->toolbar; - - $this->setTabs(); - $this->setContentSubTabs("maintenance"); - - $ilToolbar->addButton($this->lng->txt("cont_fix_tree"), - $this->ctrl->getLinkTarget($this, "fixTreeConfirm")); - } - - /** - * activates or deactivates pages - */ - function activatePages() - { - if (is_array($_POST["id"])) - { - foreach($_POST["id"] as $id) - { - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - $act = ilLMPage::_lookupActive($id, $this->object->getType()); - ilLMPage::_writeActive($id, $this->object->getType(), !$act); - } - } - - $this->ctrl->redirect($this, "pages"); - } - - /** - * paste page - */ - function pastePage() - { - $ilErr = $this->error; - - if(ilEditClipboard::getContentObjectType() != "pg") - { - $ilErr->raiseError($this->lng->txt("no_page_in_clipboard"), $ilErr->MESSAGE); - } - - // paste selected object - $id = ilEditClipboard::getContentObjectId(); - - // copy page, if action is copy - if (ilEditClipboard::getAction() == "copy") - { - // check wether page belongs to lm - if (ilLMObject::_lookupContObjID(ilEditClipboard::getContentObjectId()) - == $this->object->getID()) - { - $lm_page = new ilLMPageObject($this->object, $id); - $new_page = $lm_page->copy(); - $id = $new_page->getId(); - } - else - { - // get page from other content object into current content object - $lm_id = ilLMObject::_lookupContObjID(ilEditClipboard::getContentObjectId()); - $lm_obj = ilObjectFactory::getInstanceByObjId($lm_id); - $lm_page = new ilLMPageObject($lm_obj, $id); - $copied_nodes = array(); - $new_page = $lm_page->copyToOtherContObject($this->object, $copied_nodes); - $id = $new_page->getId(); - ilLMObject::updateInternalLinks($copied_nodes); - } - } - - // cut is not be possible in "all pages" form yet - if (ilEditClipboard::getAction() == "cut") - { - // check wether page belongs not to lm - if (ilLMObject::_lookupContObjID(ilEditClipboard::getContentObjectId()) - != $this->object->getID()) - { - $lm_id = ilLMObject::_lookupContObjID(ilEditClipboard::getContentObjectId()); - $lm_obj = ilObjectFactory::getInstanceByObjId($lm_id); - $lm_page = new ilLMPageObject($lm_obj, $id); - $lm_page->setLMId($this->object->getID()); - $lm_page->update(); - $page = $lm_page->getPageObject(); - $page->buildDom(); - $page->setParentId($this->object->getID()); - $page->update(); - } - } - - - ilEditClipboard::clear(); - $this->ctrl->redirect($this, "pages"); - } - - /** - * copy page - */ - function copyPage() - { - $ilErr = $this->error; - - if(!isset($_POST["id"])) - { - $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); - } - - $items = ilUtil::stripSlashesArray($_POST["id"]); - ilLMObject::clipboardCopy($this->object->getId(), $items); - ilEditClipboard::setAction("copy"); - - ilUtil::sendInfo($this->lng->txt("cont_selected_items_have_been_copied"), true); - - $this->ctrl->redirect($this, "pages"); - } - - /** - * confirm deletion screen for page object and structure object deletion - * - * @param int $a_parent_subobj_id id of parent object (structure object) - * of the objects, that should be deleted - * (or no parent object id for top level) - */ - function delete($a_parent_subobj_id = 0) - { - $ilErr = $this->error; - - if(!isset($_POST["id"])) - { - $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); - } - - if(count($_POST["id"]) == 1 && $_POST["id"][0] == IL_FIRST_NODE) - { - $ilErr->raiseError($this->lng->txt("cont_select_item"), $ilErr->MESSAGE); - } - - if ($a_parent_subobj_id == 0) - { - $this->setTabs(); - } - - if ($a_parent_subobj_id != 0) - { - $this->ctrl->setParameterByClass("ilStructureObjectGUI", "backcmd", $_GET["backcmd"]); - $this->ctrl->setParameterByClass("ilStructureObjectGUI", "obj_id", $a_parent_subobj_id); - $form_action = $this->ctrl->getFormActionByClass("ilStructureObjectGUI"); - } - else - { - $this->ctrl->setParameter($this, "backcmd", $_GET["backcmd"]); - $form_action = $this->ctrl->getFormAction($this); - } - - // display confirmation message - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($form_action); - $cgui->setHeaderText($this->lng->txt("info_delete_sure")); - $cgui->setCancel($this->lng->txt("cancel"), "cancelDelete"); - $cgui->setConfirm($this->lng->txt("confirm"), "confirmedDelete"); - - foreach($_POST["id"] as $id) - { - if ($id != IL_FIRST_NODE) - { - $obj = new ilLMObject($this->object, $id); - $caption = ilUtil::getImageTagByType($obj->getType(), $this->tpl->tplPath). - " ".$obj->getTitle(); - - $cgui->addItem("id[]", $id, $caption); - } - } - - $this->tpl->setContent($cgui->getHTML()); - } - - /** - * cancel delete - */ - function cancelDelete() - { - $this->ctrl->redirect($this, $_GET["backcmd"]); - - } - - /** - * delete page object or structure objects - * - * @param int $a_parent_subobj_id id of parent object (structure object) - * of the objects, that should be deleted - * (or no parent object id for top level) - */ - function confirmedDelete($a_parent_subobj_id = 0) - { - $ilErr = $this->error; - - $tree = new ilTree($this->object->getId()); - $tree->setTableNames('lm_tree','lm_data'); - $tree->setTreeTablePK("lm_id"); - - // check number of objects - if (!$_POST["id"]) - { - $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); - } - - // delete all selected objects - foreach ($_POST["id"] as $id) - { - if ($id != IL_FIRST_NODE) - { - $obj = ilLMObjectFactory::getInstance($this->object, $id, false); - $node_data = $tree->getNodeData($id); - if (is_object($obj)) - { - $obj->setLMId($this->object->getId()); - - include_once("./Services/History/classes/class.ilHistory.php"); - ilHistory::_createEntry($this->object->getId(), "delete_".$obj->getType(), - array(ilLMObject::_lookupTitle($id), $id), - $this->object->getType()); - - $obj->delete(); - } - if($tree->isInTree($id)) - { - $tree->deleteTree($node_data); - } - } - } - - // check the tree - $this->object->checkTree(); - - // feedback - ilUtil::sendSuccess($this->lng->txt("info_deleted"),true); - - if ($a_parent_subobj_id == 0) - { - $this->ctrl->redirect($this, $_GET["backcmd"]); - } - } - - - - /** - * get context path in content object tree - * - * @param int $a_endnode_id id of endnode - * @param int $a_startnode_id id of startnode - */ - function getContextPath($a_endnode_id, $a_startnode_id = 1) - { - $path = ""; - - $tmpPath = $this->lm_tree->getPathFull($a_endnode_id, $a_startnode_id); - - // count -1, to exclude the learning module itself - for ($i = 1; $i < (count($tmpPath) - 1); $i++) - { - if ($path != "") - { - $path .= " > "; - } - - $path .= $tmpPath[$i]["title"]; - } - - return $path; - } - - - - /** - * show possible action (form buttons) - * - * @access public - */ - function showActions($a_actions) - { - foreach ($a_actions as $name => $lng) - { - $d[$name] = array("name" => $name, "lng" => $lng); - } - - $notoperations = array(); - - $operations = array(); - - if (is_array($d)) - { - foreach ($d as $row) - { - if (!in_array($row["name"], $notoperations)) - { - $operations[] = $row; - } - } - } - - if (count($operations)>0) - { - foreach ($operations as $val) - { - $this->tpl->setCurrentBlock("operation_btn"); - $this->tpl->setVariable("BTN_NAME", $val["name"]); - $this->tpl->setVariable("BTN_VALUE", $this->lng->txt($val["lng"])); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setCurrentBlock("operation"); - $this->tpl->setVariable("IMG_ARROW",ilUtil::getImagePath("arrow_downright.svg")); - $this->tpl->parseCurrentBlock(); - } - } - - /** - * view content object - */ - function view() - { - if (strtolower($_GET["baseClass"]) == "iladministrationgui") - { - $this->prepareOutput(); - parent::viewObject(); - } - else - { - $this->viewObject(); - } - } - - - /** - * move a single chapter (selection) - */ - function moveChapter($a_parent_subobj_id = 0) - { - $ilErr = $this->error; - - if(!isset($_POST["id"])) - { - $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); - } - if(count($_POST["id"]) > 1) - { - $ilErr->raiseError($this->lng->txt("cont_select_max_one_item"), $ilErr->MESSAGE); - } - - if(count($_POST["id"]) == 1 && $_POST["id"][0] == IL_FIRST_NODE) - { - $ilErr->raiseError($this->lng->txt("cont_select_item"), $ilErr->MESSAGE); - } - - // SAVE POST VALUES - ilEditClipboard::storeContentObject("st", $_POST["id"][0], "move"); - - ilUtil::sendInfo($this->lng->txt("cont_chap_select_target_now"), true); - - if ($a_parent_subobj_id == 0) - { - $this->ctrl->redirect($this, "chapters"); - } - } - - - /** - * copy a single chapter (selection) - */ - function copyChapter($a_parent_subobj_id = 0) - { - $this->copyItems(); - } - - /** - * paste chapter - */ - function pasteChapter($a_parent_subobj_id = 0) - { - return $this->insertChapterClip(false); - } - - /** - * move page - */ - function movePage() - { - $ilErr = $this->error; - - if(!isset($_POST["id"])) - { - $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); - } - - ilUtil::sendInfo($this->lng->txt("cont_selected_items_have_been_cut"), true); - - $items = ilUtil::stripSlashesArray($_POST["id"]); - ilLMObject::clipboardCut($this->object->getId(), $items); - ilEditClipboard::setAction("cut"); - - $this->ctrl->redirect($this, "pages"); - } - - /** - * cancel action - */ - function cancel() - { - if ($_GET["new_type"] == "pg") - { - $this->ctrl->redirect($this, "pages"); - } - else - { - $this->ctrl->redirect($this, "chapters"); - } - } - - - /** - * export content object - */ - function export() - { - $ot = ilObjectTranslation::getInstance($this->object->getId()); - $opt = ""; - if ($ot->getContentActivated()) - { - $format = explode("_", $_POST["format"]); - $opt = ilUtil::stripSlashes($format[1]); - } - - - require_once("./Modules/LearningModule/classes/class.ilContObjectExport.php"); - $cont_exp = new ilContObjectExport($this->object); - $cont_exp->buildExportFile($opt); -// $this->ctrl->redirect($this, "exportList"); - } - - /** - * Get public access value for export table - */ - function getPublicAccessColValue($a_type, $a_file) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $changelink = "".$lng->txt("change").""; - if (!$this->object->isActiveLMMenu()) - { - $add = "
".$lng->txt("cont_download_no_menu")." ".$changelink; - } - else if (!$this->object->isActiveDownloads()) - { - $add = "
".$lng->txt("cont_download_no_download")." ".$changelink; - } - - $basetype = explode("_", $a_type); - $basetype = $basetype[0]; - - if ($this->object->getPublicExportFile($basetype) == $a_file) - { - return $lng->txt("yes").$add; - } - - return " "; - } - - - - /** - * download export file - */ - function publishExportFile($a_files) - { - $ilCtrl = $this->ctrl; - - if(!isset($a_files)) - { - ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); - } - else - { - foreach ($a_files as $f) - { - $file = explode(":", $f); - if (is_int(strpos($file[0], "_"))) - { - $file[0] = explode("_", $file[0])[0]; - } - $export_dir = $this->object->getExportDirectory($file[0]); - - if ($this->object->getPublicExportFile($file[0]) == - $file[1]) - { - $this->object->setPublicExportFile($file[0], ""); - } - else - { - $this->object->setPublicExportFile($file[0], $file[1]); - } - } - $this->object->update(); - } - $ilCtrl->redirectByClass("ilexportgui"); - } - - /** - * download export file - */ - function downloadPDFFile() - { - $ilErr = $this->error; - - if(!isset($_POST["file"])) - { - $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); - } - - if (count($_POST["file"]) > 1) - { - $ilErr->raiseError($this->lng->txt("cont_select_max_one_item"), $ilErr->MESSAGE); - } - - - $export_dir = $this->object->getOfflineDirectory(); - - $file = basename($_POST["file"][0]); - - ilUtil::deliverFile($export_dir."/".$file, $file); - } - - - /** - * confirm screen for tree fixing - * - */ - function fixTreeConfirm() - { - $this->setTabs(); - $this->setContentSubTabs("maintenance"); - - // display confirmation message - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($this->ctrl->getFormAction($this)); - $cgui->setHeaderText($this->lng->txt("cont_fix_tree_confirm")); - $cgui->setCancel($this->lng->txt("cancel"), "showMaintenance"); - $cgui->setConfirm($this->lng->txt("cont_fix_tree"), "fixTree"); - $issues = $this->object->checkStructure(); - $mess = ""; - if (count($issues) > 0) { - $mess = "Found Issues:
".implode("
", $issues); - } - $this->tpl->setContent($cgui->getHTML().$mess); - } - - /** - * Fix tree - */ - function fixTree() - { - $this->object->fixTree(); - ilUtil::sendSuccess($this->lng->txt("cont_tree_fixed"), true); - $this->ctrl->redirect($this, "showMaintenance"); - } - - /** - * get lm menu html - */ - function setilLMMenu($a_offline = false, $a_export_format = "", - $a_active = "content", $a_use_global_tabs = false, $a_as_subtabs = false, - $a_cur_page = 0, $a_lang = "", $a_export_all = false) - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - $ilAccess = $this->access; - $ilTabs = $this->tabs; - $rbacsystem = $this->rbacsystem; - $ilPluginAdmin = $this->plugin_admin; - $ilHelp = $this->help; - - $ilHelp->setScreenIdComponent("lm"); - - if ($a_as_subtabs) - { - $addcmd = "addSubTabTarget"; - $getcmd = "getSubTabHTML"; - } - else - { - $addcmd = "addTarget"; - $getcmd = "getHTML"; - } - - $active[$a_active] = true; - - if (!$this->object->isActiveLMMenu()) - { - return ""; - } - - if ($a_use_global_tabs) - { - $tabs_gui = $ilTabs; - } - else - { - $tabs_gui = new ilTabsGUI(); - } - - // workaround for preventing tooltips in export - if ($a_offline) - { - $tabs_gui->setSetupMode(true); - } - - // Determine whether the view of a learning resource should - // be shown in the frameset of ilias, or in a separate window. - $showViewInFrameset = true; - - if ($showViewInFrameset && !$a_offline) - { - $buttonTarget = ilFrameTargetInfo::_getFrame("MainContent"); - } - else - { - $buttonTarget = "_top"; - } - - if ($a_export_format == "scorm") - { - $buttonTarget = ""; - } - - // content - if (!$a_offline && $ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - $ilCtrl->setParameterByClass("illmpresentationgui", "obj_id", $_GET["obj_id"]); - $tabs_gui->$addcmd("content", - $ilCtrl->getLinkTargetByClass("illmpresentationgui", "layout"), - "", "", $buttonTarget, $active["content"]); - if ($active["content"]) - { - $ilHelp->setScreenId("content"); - $ilHelp->setSubScreenId("content"); - } - } - else if ($a_offline) - { - $tabs_gui->setForcePresentationOfSingleTab(true); - } - - // table of contents - if($this->object->isActiveTOC() && $ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - if (!$a_offline) - { - $ilCtrl->setParameterByClass("illmpresentationgui", "obj_id", $_GET["obj_id"]); - $link = $ilCtrl->getLinkTargetByClass("illmpresentationgui", "showTableOfContents"); - } - else - { - if ($a_export_all) - { - $link = "./table_of_contents_".$a_lang.".html"; - } - else - { - $link = "./table_of_contents.html"; - } - } - $tabs_gui->$addcmd("cont_toc", $link, - "", "", $buttonTarget, $active["toc"]); - } - - // print view - if($this->object->isActivePrintView() && $ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - if (!$a_offline) // has to be implemented for offline mode - { - $ilCtrl->setParameterByClass("illmpresentationgui", "obj_id", $_GET["obj_id"]); - $link = $ilCtrl->getLinkTargetByClass("illmpresentationgui", "showPrintViewSelection"); - $tabs_gui->$addcmd("cont_print_view", $link, - "", "", $buttonTarget, $active["print"]); - } - } - - // download - if($ilUser->getId() == ANONYMOUS_USER_ID) - { - $is_public = $this->object->isActiveDownloadsPublic(); - } - else - { - $is_public = true; - } - - if($this->object->isActiveDownloads() && !$a_offline && $is_public && - $ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - $ilCtrl->setParameterByClass("illmpresentationgui", "obj_id", $_GET["obj_id"]); - $link = $ilCtrl->getLinkTargetByClass("illmpresentationgui", "showDownloadList"); - $tabs_gui->$addcmd("download", $link, - "", "", $buttonTarget, $active["download"]); - } - - // info button - if ($a_export_format != "scorm" && !$a_offline) - { - if (!$a_offline) - { - $ilCtrl->setParameterByClass("illmpresentationgui", "obj_id", $_GET["obj_id"]); - $link = $this->ctrl->getLinkTargetByClass( - array("illmpresentationgui", "ilinfoscreengui"), "showSummary"); - } - else - { - $link = "./info.html"; - } - - $tabs_gui->$addcmd('info_short', $link, - "", "", $buttonTarget, $active["info"]); - } - - include_once './Services/Tracking/classes/class.ilLearningProgressAccess.php'; - if(!$a_offline && - $ilAccess->checkAccess("read", "", $_GET["ref_id"]) && // #14075 - ilLearningProgressAccess::checkAccess($_GET["ref_id"])) - { - include_once './Services/Object/classes/class.ilObjectLP.php'; - $olp = ilObjectLP::getInstance($this->object->getId()); - if($olp->getCurrentMode() == ilLPObjSettings::LP_MODE_COLLECTION_MANUAL) - { - $tabs_gui->$addcmd("learning_progress", - $this->ctrl->getLinkTargetByClass(array("illmpresentationgui", "illearningprogressgui"), "editManual"), - "", "", $buttonTarget, $active["learning_progress"]); - } - else if($olp->getCurrentMode() == ilLPObjSettings::LP_MODE_COLLECTION_TLT) - { - $tabs_gui->$addcmd("learning_progress", - $this->ctrl->getLinkTargetByClass(array("illmpresentationgui", "illearningprogressgui"), "showtlt"), - "", "", $buttonTarget, $active["learning_progress"]); - } - } - - // get user defined menu entries - $this->__initLMMenuEditor(); - $entries = $this->lmme_obj->getMenuEntries(true); - if (count($entries) > 0 && $ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - foreach ($entries as $entry) - { - // build goto-link for internal resources - if ($entry["type"] == "intern") - { - $entry["link"] = ILIAS_HTTP_PATH."/goto.php?target=".$entry["link"]; - } - - // add http:// prefix if not exist - if (!strstr($entry["link"],'://') && !strstr($entry["link"],'mailto:')) - { - $entry["link"] = "http://".$entry["link"]; - } - - if (!strstr($entry["link"],'mailto:')) - { - $entry["link"] = ilUtil::appendUrlParameterString($entry["link"], "ref_id=".$this->ref_id."&structure_id=".$this->obj_id); - } - $tabs_gui->$addcmd($entry["title"], - $entry["link"], - "", "", "_blank", "", true); - } - } - - // edit learning module - if (!$a_offline && $a_cur_page > 0) - { - if ($rbacsystem->checkAccess("write", $_GET["ref_id"])) - { - //$page_id = $this->getCurrentPageId(); - $page_id = $a_cur_page; - $tabs_gui->$addcmd("edit_page", ILIAS_HTTP_PATH."/ilias.php?baseClass=ilLMEditorGUI&ref_id=".$_GET["ref_id"]. - "&obj_id=".$page_id."&to_page=1", - "", "", $buttonTarget, $active["edit_page"]); - } - } - - // user interface hook [uihk] - $pl_names = $ilPluginAdmin->getActivePluginsForSlot(IL_COMP_SERVICE, "UIComponent", "uihk"); - $plugin_html = false; - foreach ($pl_names as $pl) - { - $ui_plugin = ilPluginAdmin::getPluginObject(IL_COMP_SERVICE, "UIComponent", "uihk", $pl); - $gui_class = $ui_plugin->getUIClassInstance(); - $resp = $gui_class->modifyGUI("Modules/LearningModule", "lm_menu_tabs", - array("lm_menu_tabs" => $tabs_gui)); - } - - return $tabs_gui->$getcmd(); - } - - /** - * export content object - */ - function createPDF() - { - require_once("./Modules/LearningModule/classes/class.ilContObjectExport.php"); - $cont_exp = new ilContObjectExport($this->object, "pdf"); - $cont_exp->buildExportFile(); - $this->offlineList(); - } - - /** - * create html package - */ - function exportHTML() - { - include_once("./Services/Object/classes/class.ilObjectTranslation.php"); - $ot = ilObjectTranslation::getInstance($this->object->getId()); - $lang = ""; - if ($ot->getContentActivated()) - { - $format = explode("_", $_POST["format"]); - $lang = ilUtil::stripSlashes($format[1]); - } - require_once("./Modules/LearningModule/classes/class.ilContObjectExport.php"); - $cont_exp = new ilContObjectExport($this->object, "html", $lang); - $cont_exp->buildExportFile(); - } - - /** - * create scorm package - */ - function exportSCORM() - { - require_once("./Modules/LearningModule/classes/class.ilContObjectExport.php"); - $cont_exp = new ilContObjectExport($this->object, "scorm"); - $cont_exp->buildExportFile(); - } - - /** - * display locator - * - * @param boolean $a_omit_obj_id set to true, if obj id is not page id (e.g. permission gui) - */ - function addLocations($a_omit_obj_id = false) - { - $locator = $this->locator; - - if (!$a_omit_obj_id) - { - $obj_id = $_GET["obj_id"]; - } - $lmtree = $this->object->getTree(); - - if (($obj_id != 0) && $lmtree->isInTree($obj_id)) - { - $path = $lmtree->getPathFull($obj_id); - } - else - { - $path = $lmtree->getPathFull($lmtree->getRootId()); - if ($obj_id != 0) - { - $path[] = array("type" => "pg", "child" => $this->obj_id, - "title" => ilLMPageObject::_getPresentationTitle($this->obj_id)); - } - } - - foreach ($path as $key => $row) - { - if ($row["child"] == 1) - { - $this->ctrl->setParameter($this, "obj_id", ""); - $locator->addItem($this->object->getTitle(), $this->ctrl->getLinkTarget($this, "chapters")); - } - else - { - $title = $row["title"]; - switch($row["type"]) - { - case "st": - $this->ctrl->setParameterByClass("ilstructureobjectgui", "obj_id", $row["child"]); - $locator->addItem($title, $this->ctrl->getLinkTargetByClass("ilstructureobjectgui", "view")); - break; - - case "pg": - $this->ctrl->setParameterByClass("illmpageobjectgui", "obj_id", $row["child"]); - $locator->addItem($title, $this->ctrl->getLinkTargetByClass("illmpageobjectgui", "edit")); - break; - } - } - } - if (!$a_omit_obj_id) - { - $this->ctrl->setParameter($this, "obj_id", $_GET["obj_id"]); - } - } - - //// - //// Questions - //// - - - /** - * List questions - */ - function listQuestions() - { - $tpl = $this->tpl; - - $this->setTabs("questions"); - $this->setQuestionsSubTabs("question_stats"); - - include_once("./Modules/LearningModule/classes/class.ilLMQuestionListTableGUI.php"); - $table = new ilLMQuestionListTableGUI($this, "listQuestions", $this->object); - $tpl->setContent($table->getHTML()); - - } - - /** - * List blocked users - */ - function listBlockedUsers() - { - $tpl = $this->tpl; - - $this->setTabs("questions"); - $this->setQuestionsSubTabs("blocked_users"); - - include_once("./Modules/LearningModule/classes/class.ilLMBlockedUsersTableGUI.php"); - $table = new ilLMBlockedUsersTableGUI($this, "listBlockedUsers", $this->object); - $tpl->setContent($table->getHTML()); - - } - - /** - * Reset number of tries - */ - function resetNumberOfTries() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("./Services/COPage/classes/class.ilPageQuestionProcessor.php"); - if (is_array($_POST["userquest_id"])) - { - foreach ($_POST["userquest_id"] as $uqid) - { - $uqid = explode(":", $uqid); - ilPageQuestionProcessor::resetTries((int) $uqid[0], (int) $uqid[1]); - } - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - } - $ilCtrl->redirect($this, "listBlockedUsers"); - } - - /** - * Unlock blocked question - */ - function unlockQuestion() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("./Services/COPage/classes/class.ilPageQuestionProcessor.php"); - if (is_array($_POST["userquest_id"])) - { - foreach ($_POST["userquest_id"] as $uqid) - { - $uqid = explode(":", $uqid); - ilPageQuestionProcessor::unlock((int) $uqid[0], (int) $uqid[1]); - } - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - } - $ilCtrl->redirect($this, "listBlockedUsers"); - } - - /** - * Send Mail to blocked users - */ - function sendMailToBlockedUsers() - { - $ilCtrl = $this->ctrl; - - if (!is_array($_POST["userquest_id"])) - { - ilUtil::sendFailure($this->lng->txt("no_checkbox"), 1); - $ilCtrl->redirect($this, "listBlockedUsers"); - } - - $rcps = array(); - foreach($_POST["userquest_id"] as $uqid) - { - $uqid = explode(":", $uqid); - $login = ilObjUser::_lookupLogin($uqid[1]); - if (!in_array($login, $rcps)) - { - $rcps[] = $login; - } - } - require_once 'Services/Mail/classes/class.ilMailFormCall.php'; - ilUtil::redirect(ilMailFormCall::getRedirectTarget($this, 'listBlockedUsers', - array(), - array( - 'type' => 'new', - 'rcp_to' => implode(',',$rcps), - 'sig' => $this->getBlockedUsersMailSignature() - ))); - } - - /** - * Get mail signature for blocked users - */ - protected function getBlockedUsersMailSignature() - { - $link = chr(13).chr(10).chr(13).chr(10); - $link .= $this->lng->txt('cont_blocked_users_mail_link'); - $link .= chr(13).chr(10).chr(13).chr(10); - include_once './Services/Link/classes/class.ilLink.php'; - $link .= ilLink::_getLink($this->object->getRefId()); - return rawurlencode(base64_encode($link)); - } - - - //// - //// Tabs - //// - - - /** - * output tabs - */ - function setTabs($a_act = "") - { - $lng = $this->lng; - $ilHelp = $this->help; - - $ilHelp->setScreenIdComponent("lm"); - - $this->addTabs($a_act); - parent::setTitleAndDescription(); - $this->tpl->setTitle($this->object->getTitle()); - $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_lm.svg"), - $lng->txt("obj_lm")); - } - - /** - * Set pages tabs - * - * @param string $a_active active subtab - */ - function setContentSubTabs($a_active) - { - $ilTabs = $this->tabs; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $lm_set = new ilSetting("lm"); - - // chapters - $ilTabs->addSubtab("chapters", - $lng->txt("cont_chapters"), - $ilCtrl->getLinkTarget($this, "chapters")); - - // all pages - $ilTabs->addSubtab("pages", - $lng->txt("cont_all_pages"), - $ilCtrl->getLinkTarget($this, "pages")); - - // all pages - $ilTabs->addSubtab("short_titles", - $lng->txt("cont_short_titles"), - $ilCtrl->getLinkTargetByClass("illmeditshorttitlesgui", "")); - - // export ids - if ($lm_set->get("html_export_ids")) - { - if (!ilObjContentObject::isOnlineHelpModule($this->object->getRefId())) - { - $ilTabs->addSubtab("export_ids", - $lng->txt("cont_html_export_ids"), - $ilCtrl->getLinkTarget($this, "showExportIDsOverview")); - } - } - if (ilObjContentObject::isOnlineHelpModule($this->object->getRefId())) - { - $lng->loadLanguageModule("help"); - $ilTabs->addSubtab("export_ids", - $lng->txt("cont_online_help_ids"), - $ilCtrl->getLinkTarget($this, "showExportIDsOverview")); - - $ilTabs->addSubtab("help_tooltips", - $lng->txt("help_tooltips"), - $ilCtrl->getLinkTarget($this, "showTooltipList")); - } - - // list links - $ilTabs->addSubtab("internal_links", - $lng->txt("cont_internal_links"), - $ilCtrl->getLinkTarget($this, "listLinks")); - - // web link checker - $ilTabs->addSubtab("link_check", - $lng->txt("link_check"), - $ilCtrl->getLinkTarget($this, "linkChecker")); - - $ilTabs->addSubtab("history", - $lng->txt("history"), - $this->ctrl->getLinkTarget($this, "history")); - - // maintenance - $ilTabs->addSubtab("maintenance", - $lng->txt("cont_maintenance"), - $ilCtrl->getLinkTarget($this, "showMaintenance")); - - // srt files - $ilTabs->addSubtab("srt_files", - $lng->txt("cont_subtitle_files"), - $ilCtrl->getLinkTargetByClass("ilmobmultisrtuploadgui", "")); - - // srt files - $ilTabs->addSubtab("import", - $lng->txt("cont_import"), - $ilCtrl->getLinkTargetByClass("illmimportgui", "")); - - $ilTabs->activateSubTab($a_active); - $ilTabs->activateTab("content"); - } - - /** - * Set pages tabs - * - * @param string $a_active active subtab - */ - function setQuestionsSubTabs($a_active) - { - $ilTabs = $this->tabs; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - // chapters - $ilTabs->addSubtab("question_stats", - $lng->txt("cont_question_stats"), - $ilCtrl->getLinkTarget($this, "listQuestions")); - - // blocked users - $ilTabs->addSubtab("blocked_users", - $lng->txt("cont_blocked_users"), - $ilCtrl->getLinkTarget($this, "listBlockedUsers")); - - $ilTabs->activateSubTab($a_active); - } - - /** - * Adds tabs - */ - function addTabs($a_act = "") - { - $rbacsystem = $this->rbacsystem; - $ilTabs = $this->tabs; - $lng = $this->lng; - - // content - $ilTabs->addTab("content", - $lng->txt("content"), - $this->ctrl->getLinkTarget($this, "chapters")); - - // info - $ilTabs->addTab("info", - $lng->txt("info_short"), - $this->ctrl->getLinkTargetByClass("ilinfoscreengui",'showSummary')); - - // settings - $ilTabs->addTab("settings", - $lng->txt("settings"), - $this->ctrl->getLinkTarget($this,'properties')); - - // questions - $ilTabs->addTab("questions", - $lng->txt("objs_qst"), - $this->ctrl->getLinkTarget($this, "listQuestions")); - - // learning progress - include_once './Services/Tracking/classes/class.ilLearningProgressAccess.php'; - if(ilLearningProgressAccess::checkAccess($this->object->getRefId()) and ($this->object->getType() == 'lm')) - { - $ilTabs->addTab('learning_progress', - $lng->txt("learning_progress"), - $this->ctrl->getLinkTargetByClass(array('illearningprogressgui'),'')); - } - - if ($this->object->getType() != "lm") - { - // bibliographical data - $ilTabs->addTab("bib_data", - $lng->txt("bib_data"), - $this->ctrl->getLinkTarget($this, "editBibItem")); - } - - // meta data - include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php"; - $mdgui = new ilObjectMetaDataGUI($this->object); - $mdtab = $mdgui->getTab(); - if($mdtab) - { - $ilTabs->addTab("meta", - $lng->txt("meta_data"), - $mdtab); - } - - if ($this->object->getType() == "lm") - { - // export - $ilTabs->addTab("export", - $lng->txt("export"), - $this->ctrl->getLinkTargetByClass("ilexportgui", "")); - } - - // permissions - if ($rbacsystem->checkAccess('edit_permission',$this->object->getRefId())) - { - $ilTabs->addTab("perm", - $lng->txt("perm_settings"), - $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm")); - } - - if ($a_act != "") - { - $ilTabs->activateTab($a_act); - } - - // presentation view - $ilTabs->addNonTabbedLink("pres_mode", $lng->txt("cont_presentation_view"), - "ilias.php?baseClass=ilLMPresentationGUI&ref_id=".$this->object->getRefID(), "_top"); - } - - /** - * Set sub tabs - */ - function setSubTabs($a_active) - { - $ilTabs = $this->tabs; - $ilSetting = $this->settings; - - if (in_array($a_active, - array("settings", "cont_style", "cont_lm_menu", "public_section", - "cont_glossaries", "cont_multilinguality", "obj_multilinguality", - "lti_provider"))) - { - // general properties - $ilTabs->addSubTabTarget("settings", - $this->ctrl->getLinkTarget($this, 'properties'), - "", ""); - - // style properties - $ilTabs->addSubTabTarget("cont_style", - $this->ctrl->getLinkTarget($this, 'editStyleProperties'), - "", ""); - - // menu properties - $ilTabs->addSubTabTarget("cont_lm_menu", - $this->ctrl->getLinkTarget($this, 'editMenuProperties'), - "", ""); - - // glossaries - $ilTabs->addSubTabTarget("cont_glossaries", - $this->ctrl->getLinkTarget($this, 'editGlossaries'), - "", ""); - - if ($ilSetting->get("pub_section")) - { - // public section - $ilTabs->addSubTabTarget("public_section", - $this->ctrl->getLinkTarget($this, 'editPublicSection'), - "", ""); - } - - $ilTabs->addSubTabTarget("obj_multilinguality", - $this->ctrl->getLinkTargetByClass("ilobjecttranslationgui", "")); - - $lti_settings = new ilLTIProviderObjectSettingGUI($this->object->getRefId()); - if($lti_settings->hasSettingsAccess()) - { - $ilTabs->addSubTabTarget( - 'lti_provider', - $this->ctrl->getLinkTargetByClass(ilLTIProviderObjectSettingGUI::class) - ); - } - - $ilTabs->setSubTabActive($a_active); - } - } - - function editPublicSection() - { - $ilTabs = $this->tabs; - $ilToolbar = $this->toolbar; - $ilAccess = $this->access; - - - if (!$ilAccess->checkAccessOfUser(ANONYMOUS_USER_ID, "read", "", $this->object->getRefId())) - { - ilUtil::sendInfo($this->lng->txt("cont_anonymous_user_missing_perm")); - } - - $this->setTabs(); - $this->setSubTabs("public_section"); - $ilTabs->setTabActive("settings"); - - $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.lm_public_selector.html", - "Modules/LearningModule"); - - // get learning module object - $this->lm_obj = new ilObjLearningModule($this->ref_id, true); - - - // public mode - $modes = array("complete" => $this->lng->txt("all_pages"), "selected" => $this->lng->txt("selected_pages_only")); - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $si = new ilSelectInputGUI($this->lng->txt("choose_public_mode"), "lm_public_mode"); - $si->setOptions($modes); - $si->setValue($this->object->getPublicAccessMode()); - $ilToolbar->addInputItem($si, true); - $ilToolbar->addFormButton($this->lng->txt("save"), "savePublicSectionAccess"); - $ilToolbar->setFormAction($this->ctrl->getFormAction($this,"savePublicSectionAccess")); - - if ($this->object->getPublicAccessMode() == "selected") - { - $this->tpl->setCurrentBlock("select_pages"); - $this->tpl->setVariable("FORMACTION", $this->ctrl->getLinkTarget($this, "savePublicSectionPages")); - - include_once ("./Modules/LearningModule/classes/class.ilPublicSectionExplorerGUI.php"); - $tree = new ilPublicSectionExplorerGUI($this,"editPublicSection", $this->lm_obj); - $tree->setSelectMode("pages", true); - $tree->setSkipRootNode(true); - - $this->tpl->setVariable("EXPLORER",$tree->getHTML()); - $this->tpl->setVariable("TXT_SAVE", $this->lng->txt("save")); - - $this->tpl->parseCurrentBlock(); - } - } - - function savePublicSection() - { - //var_dump($_POST["lm_public_mode"]);exit; - $this->object->setPublicAccessMode($_POST["lm_public_mode"]); - $this->object->updateProperties(); - ilLMObject::_writePublicAccessStatus($_POST["pages"],$this->object->getId()); - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "editPublicSection"); - } - - /** - * Saves lm access mode - */ - function savePublicSectionAccess() - { - $this->object->setPublicAccessMode($_POST["lm_public_mode"]); - $this->object->updateProperties(); - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "editPublicSection"); - } - - /** - * Saves public lm pages - */ - function savePublicSectionPages() - { - ilLMObject::_writePublicAccessStatus($_POST["pages"],$this->object->getId()); - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "editPublicSection"); - } - - /** - * history - * - * @access public - */ - function history() - { - $this->setTabs("content"); - $this->setContentSubTabs("history"); - - require_once("./Services/History/classes/class.ilHistoryTableGUI.php"); - $hist_gui = new ilHistoryTableGUI($this,"history", - $this->object->getId() ,$this->object->getType()); - $hist_gui->initTable(); - $hist_gui->setCommentVisibility($this->object->isActiveHistoryUserComments()); - - $this->tpl->setContent($hist_gui->getHTML()); - } - - /** - * - * @see ilLinkCheckerGUIRowHandling::formatInvalidLinkArray() - * @param array Unformatted array - * @return array Formatted array - * @access public - * - */ - public function formatInvalidLinkArray(Array $row) - { - $row['title'] = ilLMPageObject::_getPresentationTitle($row['page_id'], $this->object->getPageHeader()); - - require_once 'Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php'; - $actions = new ilAdvancedSelectionListGUI(); - $actions->setSelectionHeaderClass('small'); - $actions->setItemLinkClass('xsmall'); - $actions->setListTitle($this->lng->txt('actions')); - $actions->setId($row['page_id']); - $this->ctrl->setParameterByClass('ilLMPageObjectGUI', 'obj_id', $row['page_id']); - $actions->addItem( - $this->lng->txt('edit'), - '', - $this->ctrl->getLinkTargetByClass('ilLMPageObjectGUI', 'edit') - ); - $this->ctrl->clearParametersByClass('ilLMPageObjectGUI'); - $row['action_html'] = $actions->getHTML(); - - return $row; - } - - function linkChecker() - { - $ilUser = $this->user; - $tpl = $this->tpl; - - $this->__initLinkChecker(); - - $this->setTabs(); - $this->setContentSubTabs("link_check"); - - require_once './Services/LinkChecker/classes/class.ilLinkCheckerTableGUI.php'; - - $toolbar = new ilToolbarGUI(); - - // #13684 - include_once "Services/Cron/classes/class.ilCronManager.php"; - if(ilCronManager::isJobActive("lm_link_check")) - { - include_once './Services/LinkChecker/classes/class.ilLinkCheckNotify.php'; - include_once 'Services/Form/classes/class.ilPropertyFormGUI.php'; - - $chb = new ilCheckboxInputGUI($this->lng->txt('link_check_message_a'), 'link_check_message'); - $chb->setValue(1); - $chb->setChecked((bool)ilLinkCheckNotify::_getNotifyStatus($ilUser->getId(),$this->object->getId())); - $chb->setOptionTitle($this->lng->txt('link_check_message_b')); - - $toolbar->addInputItem($chb); - $toolbar->addFormButton($this->lng->txt('save'), 'saveLinkCheck'); - $toolbar->setFormAction($this->ctrl->getLinkTarget($this, 'saveLinkCheck')); - } - - $tgui = new ilLinkCheckerTableGUI($this, 'linkChecker'); - $tgui->setLinkChecker($this->link_checker_obj) - ->setRowHandler($this) - ->setRefreshButton($this->lng->txt('refresh'), 'refreshLinkCheck'); - - return $tpl->setContent($tgui->prepareHTML()->getHTML().$toolbar->getHTML()); - } - - function saveLinkCheck() - { - $ilDB = $this->db; - $ilUser = $this->user; - - include_once './Services/LinkChecker/classes/class.ilLinkCheckNotify.php'; - - $link_check_notify = new ilLinkCheckNotify($ilDB); - $link_check_notify->setUserId($ilUser->getId()); - $link_check_notify->setObjId($this->object->getId()); - - if($_POST['link_check_message']) - { - ilUtil::sendSuccess($this->lng->txt('link_check_message_enabled')); - $link_check_notify->addNotifier(); - } - else - { - ilUtil::sendSuccess($this->lng->txt('link_check_message_disabled')); - $link_check_notify->deleteNotifier(); - } - $this->linkChecker(); - - return true; - } - - - - function refreshLinkCheck() - { - $this->__initLinkChecker(); - $this->link_checker_obj->checkLinks(); - ilUtil::sendSuccess($this->lng->txt('link_checker_refreshed')); - - $this->linkChecker(); - - return true; - } - - function __initLinkChecker() - { - $ilDB = $this->db; - - include_once './Services/LinkChecker/classes/class.ilLinkChecker.php'; - - $this->link_checker_obj = new ilLinkChecker($ilDB,false); - $this->link_checker_obj->setObjId($this->object->getId()); - - return true; - } - - function __initLMMenuEditor() - { - include_once './Modules/LearningModule/classes/class.ilLMMenuEditor.php'; - - $this->lmme_obj = new ilLMMenuEditor(); - $this->lmme_obj->setObjId($this->object->getId()); - - return true; - } - - /** - * display add menu entry form - */ - function addMenuEntry() - { - $ilTabs = $this->tabs; - $ilToolbar = $this->toolbar; - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - - $this->setTabs(); - - $ilTabs->setTabActive("settings"); - $this->setSubTabs("cont_lm_menu"); - - $ilToolbar->addButton($this->lng->txt("lm_menu_select_internal_object"), - $ilCtrl->getLinkTarget($this, "showEntrySelector")); - - $form = $this->initMenuEntryForm("create"); - $this->tpl->setContent($form->getHTML()); - } - - /** - * Init menu entry form. - * - * @param string $a_mode Edit Mode - */ - public function initMenuEntryForm($a_mode = "edit") - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - - // title - $ti = new ilTextInputGUI($this->lng->txt("lm_menu_entry_title"), "title"); - $ti->setMaxLength(255); - $ti->setSize(40); - $form->addItem($ti); - - // target - $ta = new ilTextInputGUI($this->lng->txt("lm_menu_entry_target"), "target"); - $ta->setMaxLength(255); - $ta->setSize(40); - $form->addItem($ta); - - if ($a_mode == "edit") - { - $this->__initLMMenuEditor(); - $this->lmme_obj->readEntry($_REQUEST["menu_entry"]); - $ti->setValue($this->lmme_obj->getTitle()); - $ta->setValue($this->lmme_obj->getTarget()); - } - - if (isset($_GET["link_ref_id"])) - { - $link_ref_id = (int) $_GET["link_ref_id"]; - $obj_type = ilObject::_lookupType($link_ref_id,true); - $obj_id = ilObject::_lookupObjectId($link_ref_id); - $title = ilObject::_lookupTitle($obj_id); - - $target_link = $obj_type."_".$link_ref_id; - $ti->setValue($title); - $ta->setValue($target_link); - - // link ref id - $hi = new ilHiddenInputGUI("link_ref_id"); - $hi->setValue($link_ref_id); - $form->addItem($hi); - } - - - // save and cancel commands - if ($a_mode == "create") - { - $form->addCommandButton("saveMenuEntry", $lng->txt("save")); - $form->addCommandButton("editMenuProperties", $lng->txt("cancel")); - $form->setTitle($lng->txt("lm_menu_new_entry")); - } - else - { - $form->addCommandButton("updateMenuEntry", $lng->txt("save")); - $form->addCommandButton("editMenuProperties", $lng->txt("cancel")); - $form->setTitle($lng->txt("lm_menu_edit_entry")); - } - - $form->setFormAction($ilCtrl->getFormAction($this)); - - return $form; - } - - /** - * save new menu entry - */ - function saveMenuEntry() - { - $ilCtrl = $this->ctrl; - - // check title and target - if (empty($_POST["title"])) - { - ilUtil::sendFailure($this->lng->txt("please_enter_title") , true); - $ilCtrl->redirect($this, "addMenuEntry"); - } - if (empty($_POST["target"])) - { - ilUtil::sendFailure($this->lng->txt("please_enter_target"), true); - $ilCtrl->redirect($this, "addMenuEntry"); - } - - $this->__initLMMenuEditor(); - $this->lmme_obj->setTitle($_POST["title"]); - $this->lmme_obj->setTarget($_POST["target"]); - $this->lmme_obj->setLinkRefId($_POST["link_ref_id"]); - - if ($_POST["link_ref_id"]) - { - $this->lmme_obj->setLinkType("intern"); - } - - $this->lmme_obj->create(); - - ilUtil::sendSuccess($this->lng->txt("msg_entry_added"), true); - $this->ctrl->redirect($this, "editMenuProperties"); - } - - /** - * drop a menu entry - */ - function deleteMenuEntry() - { - $ilErr = $this->error; - - if (empty($_GET["menu_entry"])) - { - $ilErr->raiseError($this->lng->txt("no_menu_entry_id"), $ilErr->MESSAGE); - } - - $this->__initLMMenuEditor(); - $this->lmme_obj->delete($_GET["menu_entry"]); - - ilUtil::sendSuccess($this->lng->txt("msg_entry_removed"), true); - $this->ctrl->redirect($this, "editMenuProperties"); - } - - /** - * edit menu entry form - */ - function editMenuEntry() - { - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - $ilErr = $this->error; - - $this->setTabs(); - - $ilTabs->setTabActive("settings"); - $this->setSubTabs("cont_lm_menu"); - - - if (empty($_GET["menu_entry"])) - { - $ilErr->raiseError($this->lng->txt("no_menu_entry_id"), $ilErr->MESSAGE); - } - - $ilCtrl->saveParameter($this, array("menu_entry")); - $ilToolbar->addButton($this->lng->txt("lm_menu_select_internal_object"), - $ilCtrl->getLinkTarget($this, "showEntrySelector")); - - $form = $this->initMenuEntryForm("edit"); - $this->tpl->setContent($form->getHTML()); - } - - /** - * update a menu entry - */ - function updateMenuEntry() - { - $ilErr = $this->error; - - if (empty($_REQUEST["menu_entry"])) - { - $ilErr->raiseError($this->lng->txt("no_menu_entry_id"), $ilErr->MESSAGE); - } - - // check title and target - if (empty($_POST["title"])) - { - $ilErr->raiseError($this->lng->txt("please_enter_title"), $ilErr->MESSAGE); - } - if (empty($_POST["target"])) - { - $ilErr->raiseError($this->lng->txt("please_enter_target"), $ilErr->MESSAGE); - } - - $this->__initLMMenuEditor(); - $this->lmme_obj->readEntry($_REQUEST["menu_entry"]); - $this->lmme_obj->setTitle($_POST["title"]); - $this->lmme_obj->setTarget($_POST["target"]); - if ($_POST["link_ref_id"]) - { - $this->lmme_obj->setLinkType("intern"); - } - if (is_int(strpos($_POST["target"] , "."))) - { - $this->lmme_obj->setLinkType("extern"); - } - $this->lmme_obj->update(); - - ilUtil::sendSuccess($this->lng->txt("msg_entry_updated"), true); - $this->ctrl->redirect($this, "editMenuProperties"); - } - - function showEntrySelector() - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - - $this->setTabs(); - - $ilTabs->setTabActive("settings"); - $this->setSubTabs("cont_lm_menu"); - - $ilCtrl->saveParameter($this, array("menu_entry")); - - $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.lm_menu_object_selector.html","Modules/LearningModule"); - - ilUtil::sendInfo($this->lng->txt("lm_menu_select_object_to_add")); - - require_once ("./Modules/LearningModule/classes/class.ilLMMenuObjectSelector.php"); - $exp = new ilLMMenuObjectSelector($this->ctrl->getLinkTarget($this,'test'),$this); - - $exp->setExpand($_GET["lm_menu_expand"] ? $_GET["lm_menu_expand"] : $this->tree->readRootId()); - $exp->setExpandTarget($this->ctrl->getLinkTarget($this,'showEntrySelector')); - $exp->setTargetGet("ref_id"); - $exp->setRefId($this->cur_ref_id); - - $sel_types = array('mcst', 'mep', 'cat', 'lm','glo','frm','exc','tst','svy', 'chat', 'wiki', 'sahs', - "crs", "grp", "book", "tst", "file"); - $exp->setSelectableTypes($sel_types); - - // build html-output - $exp->setOutput(0); - $output = $exp->getOutput(); - - // get page ids - foreach ($exp->format_options as $node) - { - if (!$node["container"]) - { - $pages[] = $node["child"]; - } - } - - // access mode selector - $this->tpl->setVariable("TXT_SET_PUBLIC_MODE", $this->lng->txt("set_public_mode")); - $this->tpl->setVariable("TXT_CHOOSE_PUBLIC_MODE", $this->lng->txt("choose_public_mode")); - $modes = array("complete" => $this->lng->txt("all_pages"), "selected" => $this->lng->txt("selected_pages_only")); - $select_public_mode = ilUtil::formSelect ($this->object->getPublicAccessMode(),"lm_public_mode",$modes, false, true); - $this->tpl->setVariable("SELECT_PUBLIC_MODE", $select_public_mode); - - $this->tpl->setVariable("TXT_EXPLORER_HEADER", $this->lng->txt("choose_public_pages")); - $this->tpl->setVariable("EXP_REFRESH", $this->lng->txt("refresh")); - $this->tpl->setVariable("EXPLORER",$output); - $this->tpl->setVariable("ONCLICK",$js_pages); - $this->tpl->setVariable("TXT_CHECKALL", $this->lng->txt("check_all")); - $this->tpl->setVariable("TXT_UNCHECKALL", $this->lng->txt("uncheck_all")); - $this->tpl->setVariable("TXT_SAVE", $this->lng->txt("save")); - $this->tpl->setVariable("FORMACTION", $this->ctrl->getLinkTarget($this, "savePublicSection")); - } - - /** - * select page as header - */ - function selectHeader() - { - $ilErr = $this->error; - - if(!isset($_POST["id"])) - { - $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); - } - if(count($_POST["id"]) > 1) - { - $ilErr->raiseError($this->lng->txt("cont_select_max_one_item"), $ilErr->MESSAGE); - } - if ($_POST["id"][0] != $this->object->getHeaderPage()) - { - $this->object->setHeaderPage($_POST["id"][0]); - } - else - { - $this->object->setHeaderPage(0); - } - $this->object->updateProperties(); - $this->ctrl->redirect($this, "pages"); - } - - /** - * select page as footer - */ - function selectFooter() - { - $ilErr = $this->error; - - if(!isset($_POST["id"])) - { - $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); - } - if(count($_POST["id"]) > 1) - { - $ilErr->raiseError($this->lng->txt("cont_select_max_one_item"), $ilErr->MESSAGE); - } - if ($_POST["id"][0] != $this->object->getFooterPage()) - { - $this->object->setFooterPage($_POST["id"][0]); - } - else - { - $this->object->setFooterPage(0); - } - $this->object->updateProperties(); - $this->ctrl->redirect($this, "pages"); - } - - /** - * Save all titles of chapters/pages - */ - function saveAllTitles() - { - $ilCtrl = $this->ctrl; - - ilLMObject::saveTitles($this->object, ilUtil::stripSlashesArray($_POST["title"]), $_GET["transl"]); - - ilUtil::sendSuccess($this->lng->txt("lm_save_titles"), true); - $ilCtrl->redirect($this, "chapters"); - } - - /** - * Insert (multiple) chapters at node - */ - function insertChapter() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - include_once("./Modules/LearningModule/classes/class.ilChapterHierarchyFormGUI.php"); - - $num = ilChapterHierarchyFormGUI::getPostMulti(); - $node_id = ilChapterHierarchyFormGUI::getPostNodeId(); - - if (!ilChapterHierarchyFormGUI::getPostFirstChild()) // insert after node id - { - $parent_id = $this->lm_tree->getParentId($node_id); - $target = $node_id; - } - else // insert as first child - { - $parent_id = $node_id; - $target = IL_FIRST_NODE; - } - - for ($i = 1; $i <= $num; $i++) - { - $chap = new ilStructureObject($this->object); - $chap->setType("st"); - $chap->setTitle($lng->txt("cont_new_chap")); - $chap->setLMId($this->object->getId()); - $chap->create(); - ilLMObject::putInTree($chap, $parent_id, $target); - } - - $ilCtrl->redirect($this, "chapters"); - } - - /** - * Insert Chapter from clipboard - */ - function insertChapterClip() - { - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - $ilLog = $this->log; - - include_once("./Modules/LearningModule/classes/class.ilChapterHierarchyFormGUI.php"); - - $node_id = ilChapterHierarchyFormGUI::getPostNodeId(); - $first_child = ilChapterHierarchyFormGUI::getPostFirstChild(); - - $ilLog->write("InsertChapterClip, num: $num, node_id: $node_id, ". - " getPostFirstChild ".ilChapterHierarchyFormGUI::getPostFirstChild()); - - if (!$first_child) // insert after node id - { - $parent_id = $this->lm_tree->getParentId($node_id); - $target = $node_id; - } - else // insert as first child - { - $parent_id = $node_id; - $target = IL_FIRST_NODE; - } - - // copy and paste - $chapters = $ilUser->getClipboardObjects("st", true); - $copied_nodes = array(); - foreach ($chapters as $chap) - { - $ilLog->write("Call pasteTree, Target LM: ".$this->object->getId().", Chapter ID: ".$chap["id"] - .", Parent ID: ".$parent_id.", Target: ".$target); - $cid = ilLMObject::pasteTree($this->object, $chap["id"], $parent_id, - $target, $chap["insert_time"], $copied_nodes, - (ilEditClipboard::getAction() == "copy")); - $target = $cid; - } - ilLMObject::updateInternalLinks($copied_nodes); - - if (ilEditClipboard::getAction() == "cut") - { - $ilUser->clipboardDeleteObjectsOfType("pg"); - $ilUser->clipboardDeleteObjectsOfType("st"); - ilEditClipboard::clear(); - } - - $this->object->checkTree(); - $ilCtrl->redirect($this, "chapters"); - } - - /** - * redirect script - * - * @param string $a_target - */ - public static function _goto($a_target) - { - global $DIC; - - $ilAccess = $DIC->access(); - $ilErr = $DIC["ilErr"]; - $lng = $DIC->language(); - - if ($ilAccess->checkAccess("read", "", $a_target)) - { - $_GET["baseClass"] = "ilLMPresentationGUI"; - $_GET["ref_id"] = $a_target; - $_GET["cmd"] = "resume"; - include("ilias.php"); - exit; - } else if ($ilAccess->checkAccess("visible", "", $a_target)) - { - $_GET["baseClass"] = "ilLMPresentationGUI"; - $_GET["ref_id"] = $a_target; - $_GET["cmd"] = "infoScreen"; - include("ilias.php"); - exit; - } - else if ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) - { - ilUtil::sendFailure(sprintf($lng->txt("msg_no_perm_read_item"), - ilObject::_lookupTitle(ilObject::_lookupObjId($a_target))), true); - ilObjectGUI::_gotoRepositoryRoot(); - } - - - $ilErr->raiseError($lng->txt("msg_no_perm_read_lm"), $ilErr->FATAL); - } - - /** - * Copy items to clipboard, then cut them from the current tree - */ - function cutItems($a_return = "chapters") - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $items = ilUtil::stripSlashesArray($_POST["id"]); - if (!is_array($items)) - { - ilUtil::sendFailure($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, $a_return); - } - - $todel = array(); // delete IDs < 0 (needed for non-js editing) - foreach($items as $k => $item) - { - if ($item < 0) - { - $todel[] = $k; - } - } - foreach($todel as $k) - { - unset($items[$k]); - } - ilLMObject::clipboardCut($this->object->getId(), $items); - ilEditClipboard::setAction("cut"); - ilUtil::sendInfo($lng->txt("cont_selected_items_have_been_cut"), true); - - $ilCtrl->redirect($this, $a_return); - } - - /** - * Copy items to clipboard - */ - function copyItems() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $items = ilUtil::stripSlashesArray($_POST["id"]); - if (!is_array($items)) - { - ilUtil::sendFailure($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "chapters"); - } - - $todel = array(); // delete IDs < 0 (needed for non-js editing) - foreach($items as $k => $item) - { - if ($item < 0) - { - $todel[] = $k; - } - } - foreach($todel as $k) - { - unset($items[$k]); - } - ilLMObject::clipboardCopy($this->object->getId(), $items); - ilEditClipboard::setAction("copy"); - ilUtil::sendInfo($lng->txt("cont_selected_items_have_been_copied"), true); - $ilCtrl->redirect($this, "chapters"); - } - - /** - * Cut chapter(s) - */ - function cutChapter() - { - $this->cutItems("chapters"); - } - - //// - //// HTML export IDs - //// - - /** - * Show export IDs overview - * - * @param - * @return - */ - function showExportIDsOverview($a_validation = false) - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->setTabs(); - $this->setContentSubTabs("export_ids"); - - if (ilObjContentObject::isOnlineHelpModule($this->object->getRefId())) - { - // toolbar - $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $lm_tree = $this->object->getTree(); - $childs = $lm_tree->getChilds($lm_tree->readRootId()); - $options = array("" => $lng->txt("all")); - foreach ($childs as $c) - { - $options[$c["child"]] = $c["title"]; - } - $si = new ilSelectInputGUI($this->lng->txt("help_component"), "help_chap"); - $si->setOptions($options); - $si->setValue(ilSession::get("help_chap")); - $ilToolbar->addInputItem($si, true); - $ilToolbar->addFormButton($lng->txt("help_filter"), "filterHelpChapters"); - - include_once("./Modules/LearningModule/classes/class.ilHelpMappingTableGUI.php"); - $tbl = new ilHelpMappingTableGUI($this, "showExportIDsOverview", $a_validation, false); - } - else - { - include_once("./Modules/LearningModule/classes/class.ilExportIDTableGUI.php"); - $tbl = new ilExportIDTableGUI($this, "showExportIDsOverview", $a_validation, false); - } - - $tpl->setContent($tbl->getHTML()); - } - - /** - * Filter help chapters - * - * @param - * @return - */ - function filterHelpChapters() - { - $ilCtrl = $this->ctrl; - - ilSession::set("help_chap", ilUtil::stripSlashes($_POST["help_chap"])); - $ilCtrl->redirect($this, "showExportIDsOverview"); - } - - - /** - * Save export IDs - */ - function saveExportIds() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - // check all export ids - $ok = true; - if (is_array($_POST["exportid"])) - { - foreach ($_POST["exportid"] as $pg_id => $exp_id) - { - if ($exp_id != "" && !preg_match("/^([a-zA-Z]+)[0-9a-zA-Z_]*$/", - trim($exp_id))) - { - $ok = false; - } - } - } - if (!$ok) - { - ilUtil::sendFailure($lng->txt("cont_exp_ids_not_resp_format1").": a-z, A-Z, 0-9, '_'. ". - $lng->txt("cont_exp_ids_not_resp_format3")." ". - $lng->txt("cont_exp_ids_not_resp_format2")); - $this->showExportIDsOverview(true); - return; - } - - - if (is_array($_POST["exportid"])) - { - foreach ($_POST["exportid"] as $pg_id => $exp_id) - { - ilLMPageObject::saveExportId($this->object->getId(), $pg_id, - ilUtil::stripSlashes($exp_id), ilLMObject::_lookupType($pg_id)); - } - } - - ilUtil::sendSuccess($lng->txt("cont_saved_export_ids"), true); - $ilCtrl->redirect($this, "showExportIdsOverview"); - } - - /** - * Save help mapping - * - * @param - * @return - */ - function saveHelpMapping() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("./Services/Help/classes/class.ilHelpMapping.php"); - if (is_array($_POST["screen_ids"])) - { - foreach ($_POST["screen_ids"] as $chap => $ids) - { - $ids = explode("\n", $ids); - ilHelpMapping::saveScreenIdsForChapter($chap, $ids); - } - } - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "showExportIdsOverview"); - } - - //// - //// Help tooltips - //// - - /** - * Show export IDs overview - * - * @param - * @return - */ - function showTooltipList() - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->setTabs(); - $this->setContentSubTabs("help_tooltips"); - - $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); - include_once("./Services/Form/classes/class.ilTextInputGUI.php"); - $ti = new ilTextInputGUI($this->lng->txt("help_tooltip_id"), "tooltip_id"); - $ti->setMaxLength(200); - $ti->setSize(20); - $ilToolbar->addInputItem($ti, true); - $ilToolbar->addFormButton($lng->txt("add"), "addTooltip"); - $ilToolbar->addSeparator(); - - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $options = ilHelp::getTooltipComponents(); - if (ilSession::get("help_tt_comp") != "") - { - $options[ilSession::get("help_tt_comp")] = ilSession::get("help_tt_comp"); - } - $si = new ilSelectInputGUI($this->lng->txt("help_component"), "help_tt_comp"); - $si->setOptions($options); - $si->setValue(ilSession::get("help_tt_comp")); - $ilToolbar->addInputItem($si, true); - $ilToolbar->addFormButton($lng->txt("help_filter"), "filterTooltips"); - - include_once("./Modules/LearningModule/classes/class.ilHelpTooltipTableGUI.php"); - $tbl = new ilHelpTooltipTableGUI($this, "showTooltipList", ilSession::get("help_tt_comp")); - - $tpl->setContent($tbl->getHTML()); - } - - /** - * Add tooltip - * - * @param - * @return - */ - function addTooltip() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $tt_id = ilUtil::stripSlashes($_POST["tooltip_id"]); - if (trim($tt_id) != "") - { - if (is_int(strpos($tt_id, "_"))) - { - include_once("./Services/Help/classes/class.ilHelp.php"); - ilHelp::addTooltip(trim($tt_id), ""); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - - $fu = strpos($tt_id, "_"); - $comp = substr($tt_id, 0, $fu); - ilSession::set("help_tt_comp", ilUtil::stripSlashes($comp)); - } - else - { - ilUtil::sendFailure($lng->txt("cont_help_no_valid_tooltip_id"), true); - } - } - $ilCtrl->redirect($this, "showTooltipList"); - } - - /** - * Filter tooltips - * - * @param - * @return - */ - function filterTooltips() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - ilSession::set("help_tt_comp", ilUtil::stripSlashes($_POST["help_tt_comp"])); - $ilCtrl->redirect($this, "showTooltipList"); - } - - - /** - * Save tooltips - * - * @param - * @return - */ - function saveTooltips() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - include_once("./Services/Help/classes/class.ilHelp.php"); - - if (is_array($_POST["text"])) - { - foreach ($_POST["text"] as $id => $text) - { - ilHelp::updateTooltip((int) $id, ilUtil::stripSlashes($text), - ilUtil::stripSlashes($_POST["tt_id"][(int) $id])); - } - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - } - $ilCtrl->redirect($this, "showTooltipList"); - } - - /** - * Delete tooltips - */ - function deleteTooltips() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if (is_array($_POST["id"])) - { - include_once("./Services/Help/classes/class.ilHelp.php"); - foreach ($_POST["id"] as $id) - { - ilHelp::deleteTooltip((int) $id); - } - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - } - $ilCtrl->redirect($this, "showTooltipList"); - } - - //// - //// Set layout - //// - - /** - * Get layout option - * - * @return object layout form option - */ - static function getLayoutOption($a_txt, $a_var, $a_def_option = "") - { - global $DIC; - - $lng = $DIC->language(); - - // default layout - $layout = new ilRadioGroupInputGUI($a_txt, $a_var); - if ($a_def_option != "") - { - if (is_file($im = ilUtil::getImagePath("layout_".$a_def_option.".png"))) - { - $im_tag = ilUtil::img($im, $a_def_option); - } - $layout->addOption(new ilRadioOption("
".$im_tag."". - $lng->txt("cont_lm_default_layout"). - ": ".$lng->txt("cont_layout_".$a_def_option). - "
", "")); - } - foreach(ilObjContentObject::getAvailableLayouts() as $l) - { - $im_tag = ""; - if (is_file($im = ilUtil::getImagePath("layout_".$l.".png"))) - { - $im_tag = ilUtil::img($im, $l); - } - $layout->addOption(new ilRadioOption("
". - $im_tag."".$lng->txt("cont_layout_".$l).": ". - $lng->txt("cont_layout_".$l."_desc")."
", $l)); - } - - return $layout; - } - - /** - * Set layout for multipl pages - */ - function setPageLayoutInHierarchy() - { - $ilCtrl = $this->ctrl; - $ilCtrl->setParameter($this, "hierarchy", "1"); - $this->setPageLayout(true); - } - - - /** - * Set layout for multipl pages - */ - function setPageLayout($a_in_hierarchy = false) - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if (!is_array($_POST["id"])) - { - ilUtil::sendFailure($lng->txt("no_checkbox"), true); - - if ($a_in_hierarchy) - { - $ilCtrl->redirect($this, "chapters"); - } - else - { - $ilCtrl->redirect($this, "pages"); - } - } - - $this->initSetPageLayoutForm(); - - $tpl->setContent($this->form->getHTML()); - } - - /** - * Init set page layout form. - */ - public function initSetPageLayoutForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - if (is_array($_POST["id"])) - { - foreach ($_POST["id"] as $id) - { - $hi = new ilHiddenInputGUI("id[]"); - $hi->setValue($id); - $this->form->addItem($hi); - } - } - $layout = self::getLayoutOption($lng->txt("cont_layout"), "layout", - $this->object->getLayout()); - $this->form->addItem($layout); - - $this->form->addCommandButton("savePageLayout", $lng->txt("save")); - $this->form->addCommandButton("pages", $lng->txt("cancel")); - - $this->form->setTitle($lng->txt("cont_set_layout")); - $this->form->setFormAction($ilCtrl->getFormAction($this)); - - } - - /** - * Save page layout - */ - function savePageLayout() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameter($this, "hierarchy", $_GET["hierarchy"]); - - foreach ($_POST["id"] as $id) - { - ilLMPageObject::writeLayout(ilUtil::stripSlashes($id), - ilUtil::stripSlashes($_POST["layout"]), - $this->object); - } - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - - if ($_GET["hierarchy"] == 1) - { - $ilCtrl->redirect($this, "chapters"); - } - else - { - $ilCtrl->redirect($this, "pages"); - } - } - - // - // Auto glossaries - // - - /** - * Edit automatically linked glossaries - * - * @param - * @return - */ - function editGlossaries() - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - $this->setTabs(); - $ilTabs->setTabActive("settings"); - $this->setSubTabs("cont_glossaries"); - - $ilToolbar->addButton($lng->txt("add"), - $ilCtrl->getLinkTarget($this, "showLMGlossarySelector")); - - include_once("./Modules/LearningModule/classes/class.ilLMGlossaryTableGUI.php"); - $tab = new ilLMGlossaryTableGUI($this->object, $this, "editGlossaries"); - - $tpl->setContent($tab->getHTML()); - } - - /** - * Select LM Glossary - * - * @param - * @return - */ - function showLMGlossarySelector() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $tree = $this->tree; - $ilUser = $this->user; - $ilTabs = $this->tabs; - - $this->setTabs(); - $ilTabs->setTabActive("settings"); - $this->setSubTabs("cont_glossaries"); - - include_once 'Services/Search/classes/class.ilSearchRootSelector.php'; - - $exp = new ilSearchRootSelector($ilCtrl->getLinkTarget($this,'showLMGlossarySelector')); - $exp->setExpand($_GET["search_root_expand"] ? $_GET["search_root_expand"] : $tree->readRootId()); - $exp->setExpandTarget($ilCtrl->getLinkTarget($this,'showLMGlossarySelector')); - $exp->setTargetClass(get_class($this)); - $exp->setCmd('confirmGlossarySelection'); - $exp->setClickableTypes(array("glo")); - $exp->addFilter("glo"); - - // build html-output - $exp->setOutput(0); - $tpl->setContent($exp->getOutput()); - - } - - /** - * Confirm glossary selection - */ - function confirmGlossarySelection() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $ilCtrl->setParameter($this, "glo_ref_id", $_GET["root_id"]); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("cont_link_glo_in_lm")); - $cgui->setCancel($lng->txt("no"), "selectLMGlossary"); - $cgui->setConfirm($lng->txt("yes"), "selectLMGlossaryLink"); - $tpl->setContent($cgui->getHTML()); - } - - /** - * Select a glossary and link all its terms - * - * @param - * @return - */ - function selectLMGlossaryLink() - { - $glo_ref_id = (int) $_GET["glo_ref_id"]; - $glo_id = ilObject::_lookupObjId($glo_ref_id); - $this->object->autoLinkGlossaryTerms($glo_ref_id); - $this->selectLMGlossary(); - } - - - /** - * Select lm glossary - * - * @param - * @return - */ - function selectLMGlossary() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $glos = $this->object->getAutoGlossaries(); - $glo_ref_id = (int) $_GET["glo_ref_id"]; - $glo_id = ilObject::_lookupObjId($glo_ref_id); - if (!in_array($glo_id, $glos)) - { - $glos[] = $glo_id; - } - $this->object->setAutoGlossaries($glos); - $this->object->update(); - - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "editGlossaries"); - } - - /** - * Remove lm glossary - * - * @param - * @return - */ - function removeLMGlossary() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->object->removeAutoGlossary((int) $_GET["glo_id"]); - $this->object->update(); - - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "editGlossaries"); - } - - /** - * Edit master language - * - * @param - * @return - */ - function editMasterLanguage() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameter($this, "transl", ""); - if ($_GET["lang_switch_mode"] == "short_titles") - { - $ilCtrl->redirectByClass("illmeditshorttitlesgui", ""); - } - $ilCtrl->redirect($this, "chapters"); - } - - /** - * Switch to language - * - * @param - * @return - */ - function switchToLanguage() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameter($this, "transl", $_GET["totransl"]); - if ($_GET["lang_switch_mode"] == "short_titles") - { - $ilCtrl->redirectByClass("illmeditshorttitlesgui", ""); - } - $ilCtrl->redirect($this, "chapters"); - } - - function redrawHeaderAction() - { - // #12281 - return parent::redrawHeaderActionObject(); - } - + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilPluginAdmin + */ + protected $plugin_admin; + + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var ilDB + */ + protected $db; + + /** + * @var Logger + */ + protected $log; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLocatorGUI + */ + protected $locator; + + /** + * Constructor + * + * @access public + */ + public function __construct($a_data, $a_id = 0, $a_call_by_reference = true, $a_prepare_output = false) + { + global $DIC; + + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->tabs = $DIC->tabs(); + $this->error = $DIC["ilErr"]; + $this->settings = $DIC->settings(); + $this->user = $DIC->user(); + $this->tpl = $DIC["tpl"]; + $this->toolbar = $DIC->toolbar(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->tree = $DIC->repositoryTree(); + $this->plugin_admin = $DIC["ilPluginAdmin"]; + $this->help = $DIC["ilHelp"]; + $this->locator = $DIC["ilLocator"]; + $this->db = $DIC->database(); + $this->log = $DIC["ilLog"]; + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $this->ctrl = $ilCtrl; + $lng->loadLanguageModule("content"); + $lng->loadLanguageModule("obj"); + parent::__construct($a_data, $a_id, $a_call_by_reference, false); + } + + /** + * execute command + * @return bool|mixed + * @throws ilCtrlException + */ + public function executeCommand() + { + $ilAccess = $this->access; + $lng = $this->lng; + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $ilErr = $this->error; + + if ($this->ctrl->getRedirectSource() == "ilinternallinkgui") { + $this->explorer(); + return; + } + + if ($this->ctrl->getCmdClass() == "ilinternallinkgui") { + $this->ctrl->setReturn($this, "explorer"); + } + + // get next class that processes or forwards current command + $next_class = $this->ctrl->getNextClass($this); + + // get current command + if ($_GET["to_props"] == 1) { + $cmd = $this->ctrl->getCmd("properties"); + } else { + $cmd = $this->ctrl->getCmd("chapters"); + } + + + switch ($next_class) { + case 'illtiproviderobjectsettinggui': + + $this->setTabs(); + $ilTabs->setTabActive("settings"); + $this->setSubTabs("lti_provider"); + + $lti_gui = new ilLTIProviderObjectSettingGUI($this->object->getRefId()); + $lti_gui->setCustomRolesForSelection($GLOBALS['DIC']->rbac()->review()->getLocalRoles($this->object->getRefId())); + $lti_gui->offerLTIRolesForSelection(true); + $this->ctrl->forwardCommand($lti_gui); + break; + + + + case "illearningprogressgui": + $this->addHeaderAction(); + $this->addLocations(); + include_once './Services/Tracking/classes/class.ilLearningProgressGUI.php'; + $this->setTabs("learning_progress"); + + $new_gui = new ilLearningProgressGUI(ilLearningProgressGUI::LP_CONTEXT_REPOSITORY, $this->object->getRefId()); + $this->ctrl->forwardCommand($new_gui); + + break; + + case 'ilobjectmetadatagui': + if (!$ilAccess->checkAccess('write', '', $this->object->getRefId())) { + $ilErr->raiseError($this->lng->txt('permission_denied'), $ilErr->WARNING); + } + + $this->addHeaderAction(); + $this->addLocations(); + $this->setTabs("meta"); + + include_once 'Services/Object/classes/class.ilObjectMetaDataGUI.php'; + $md_gui = new ilObjectMetaDataGUI($this->object); + $md_gui->addMDObserver($this->object, 'MDUpdateListener', 'Educational'); // #9510 + $md_gui->addMDObserver($this->object, 'MDUpdateListener', 'General'); + $this->ctrl->forwardCommand($md_gui); + break; + + case "ilobjstylesheetgui": + $this->addLocations(); + 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" || $_GET["new_type"]=="sty") { + $style_gui->setCreationMode(true); + } + $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 "illmpageobjectgui": + + $ilTabs->setBackTarget( + $lng->txt("learning module"), + $ilCtrl->getLinkTarget($this, "chapters") + ); + $this->ctrl->saveParameter($this, array("obj_id")); + $this->addLocations(); + $this->ctrl->setReturn($this, "chapters"); + + $pg_gui = new ilLMPageObjectGUI($this->object); + if ($_GET["obj_id"] != "") { + $obj = ilLMObjectFactory::getInstance($this->object, $_GET["obj_id"]); + $pg_gui->setLMPageObject($obj); + } + $ret = $this->ctrl->forwardCommand($pg_gui); + break; + + case "ilstructureobjectgui": + $ilTabs->setBackTarget( + $lng->txt("learning module"), + $ilCtrl->getLinkTarget($this, "chapters") + ); + + $this->ctrl->saveParameter($this, array("obj_id")); + $this->addLocations(); + $this->ctrl->setReturn($this, "chapters"); + $st_gui = new ilStructureObjectGUI($this->object, $this->object->lm_tree); + if ($_GET["obj_id"] != "") { + $obj = ilLMObjectFactory::getInstance($this->object, $_GET["obj_id"]); + $st_gui->setStructureObject($obj); + } + $ret = $this->ctrl->forwardCommand($st_gui); + if ($cmd == "save" || $cmd == "cancel") { + if ($_GET["obj_id"] == "") { + $this->ctrl->redirect($this, "chapters"); + } else { + $this->ctrl->setCmd("subchap"); + $this->executeCommand(); + } + } + break; + + case 'ilpermissiongui': + if (strtolower($_GET["baseClass"]) == "iladministrationgui") { + $this->prepareOutput(); + } else { + $this->addHeaderAction(); + $this->addLocations(true); + $this->setTabs("perm"); + } + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $ret = $this->ctrl->forwardCommand($perm_gui); + break; + + // infoscreen + case 'ilinfoscreengui': + $this->addHeaderAction(); + $this->addLocations(true); + $this->setTabs("info"); + include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); + $info = new ilInfoScreenGUI($this); + $info->enablePrivateNotes(); + $info->enableLearningProgress(); + + $info->enableNews(); + if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) { + $info->enableNewsEditing(); + $info->setBlockProperty("news", "settings", true); + } + + // show standard meta data section + $info->addMetaDataSections( + $this->object->getId(), + 0, + $this->object->getType() + ); + + $ret = $this->ctrl->forwardCommand($info); + break; + + case "ilexportgui": + ilUtil::sendInfo($this->lng->txt("lm_only_one_download_per_type")); + $this->addHeaderAction(); + $this->addLocations(true); + $this->setTabs("export"); + include_once("./Services/Export/classes/class.ilExportGUI.php"); + $exp_gui = new ilExportGUI($this); + $exp_gui->addFormat("xml"); + include_once("./Services/Object/classes/class.ilObjectTranslation.php"); + $ot = ilObjectTranslation::getInstance($this->object->getId()); + if ($ot->getContentActivated()) { + $exp_gui->addFormat("xml_master", "XML (" . $lng->txt("cont_master_language_only") . ")", $this, "export"); + $exp_gui->addFormat("xml_masternomedia", "XML (" . $lng->txt("cont_master_language_only_no_media") . ")", $this, "export"); + + $lng->loadLanguageModule("meta"); + $langs = $ot->getLanguages(); + foreach ($langs as $l => $ldata) { + $exp_gui->addFormat("html_" . $l, "HTML (" . $lng->txt("meta_l_" . $l) . ")", $this, "exportHTML"); + } + $exp_gui->addFormat("html_all", "HTML (" . $lng->txt("cont_all_languages") . ")", $this, "exportHTML"); + } else { + $exp_gui->addFormat("html", "", $this, "exportHTML"); + } + + $exp_gui->addFormat("scorm", "", $this, "exportSCORM"); + $exp_gui->addCustomColumn( + $lng->txt("cont_public_access"), + $this, + "getPublicAccessColValue" + ); + $exp_gui->addCustomMultiCommand( + $lng->txt("cont_public_access"), + $this, + "publishExportFile" + ); + $ret = $this->ctrl->forwardCommand($exp_gui); + break; + + case 'ilobjecttranslationgui': + $this->addHeaderAction(); + $this->addLocations(true); + $this->setTabs("settings"); + $this->setSubTabs("obj_multilinguality"); + include_once("./Services/Object/classes/class.ilObjectTranslationGUI.php"); + $transgui = new ilObjectTranslationGUI($this); + $transgui->setTitleDescrOnlyMode(false); + $this->ctrl->forwardCommand($transgui); + break; + + + case "ilcommonactiondispatchergui": + include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); + $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); + $this->ctrl->forwardCommand($gui); + break; + + case 'ilobjectcopygui': + $this->prepareOutput(); + include_once './Services/Object/classes/class.ilObjectCopyGUI.php'; + $cp = new ilObjectCopyGUI($this); + $cp->setType('lm'); + $this->ctrl->forwardCommand($cp); + break; + + case "ilmobmultisrtuploadgui": + $this->addHeaderAction(); + $this->addLocations(true); + $this->setTabs("content"); + $this->setContentSubTabs("srt_files"); + include_once("./Services/MediaObjects/classes/class.ilMobMultiSrtUploadGUI.php"); + include_once("./Modules/LearningModule/classes/class.ilLMMultiSrt.php"); + $gui = new ilMobMultiSrtUploadGUI(new ilLMMultiSrt($this->object)); + $this->ctrl->forwardCommand($gui); + break; + + case "illmimportgui": + $this->addHeaderAction(); + $this->addLocations(true); + $this->setTabs("content"); + $this->setContentSubTabs("import"); + include_once("./Modules/LearningModule/classes/class.ilLMImportGUI.php"); + $gui = new ilLMImportGUI($this->object); + $this->ctrl->forwardCommand($gui); + break; + + case "illmeditshorttitlesgui": + $this->addHeaderAction(); + $this->addLocations(true); + $this->setTabs("content"); + $this->setContentSubTabs("short_titles"); + include_once("./Modules/LearningModule/classes/class.ilLMEditShortTitlesGUI.php"); + $gui = new ilLMEditShortTitlesGUI($this); + $this->ctrl->forwardCommand($gui); + break; + + default: + $new_type = $_POST["new_type"] + ? $_POST["new_type"] + : $_GET["new_type"]; + + + if ($cmd == "create" && + !in_array($new_type, array("lm"))) { + switch ($new_type) { + case "pg": + $this->setTabs(); + $this->ctrl->setCmdClass("ilLMPageObjectGUI"); + $ret = $this->executeCommand(); + break; + + case "st": + $this->setTabs(); + $this->ctrl->setCmdClass("ilStructureObjectGUI"); + $ret = $this->executeCommand(); + break; + } + } else { + // creation of new dbk/lm in repository + if ($this->getCreationMode() == true && + in_array($new_type, array("lm"))) { + $this->prepareOutput(); + if ($cmd == "") { // this may be due to too big upload files + $cmd = "create"; + } + $cmd .= "Object"; + $ret = $this->$cmd(); + } else { + $this->addHeaderAction(); + $this->addLocations(); + $ret = $this->$cmd(); + } + } + break; + } + return $ret; + } + + public static function _forwards() + { + return array("ilLMPageObjectGUI", "ilStructureObjectGUI","ilObjStyleSheetGUI"); + } + + /** + * edit properties form + */ + public function properties() + { + $lng = $this->lng; + + $lng->loadLanguageModule("style"); + $this->setTabs("settings"); + $this->setSubTabs("settings"); + + // lm properties + $this->initPropertiesForm(); + $this->getPropertiesFormValues(); + + if ($this->object->getType() == "lm") { + // Edit ecs export settings + include_once 'Modules/LearningModule/classes/class.ilECSLearningModuleSettings.php'; + $ecs = new ilECSLearningModuleSettings($this->object); + $ecs->addSettingsToForm($this->form, 'lm'); + } + + $this->tpl->setContent($this->form->getHTML()); + } + + /** + * Init properties form + */ + public function initPropertiesForm() + { + $obj_service = $this->object_service; + + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilSetting = $this->settings; + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + // title + $ti = new ilTextInputGUI($lng->txt("title"), "title"); + $ti->setRequired(true); + $this->form->addItem($ti); + + // description + $ta = new ilTextAreaInputGUI($lng->txt("desc"), "description"); + $this->form->addItem($ta); + + $lng->loadLanguageModule("rep"); + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($this->lng->txt('rep_activation_availability')); + $this->form->addItem($section); + + // online + $online = new ilCheckboxInputGUI($lng->txt("cont_online"), "cobj_online"); + $this->form->addItem($online); + + // presentation + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($this->lng->txt('cont_presentation')); + $this->form->addItem($section); + + // tile image + $obj_service->commonSettings()->legacyForm($this->form, $this->object)->addTileImage(); + + // default layout + $layout = self::getLayoutOption($lng->txt("cont_def_layout"), "lm_layout"); + $this->form->addItem($layout); + + // layout per page + $lpp = new ilCheckboxInputGUI($lng->txt("cont_layout_per_page"), "layout_per_page"); + $lpp->setInfo($this->lng->txt("cont_layout_per_page_info")); + $this->form->addItem($lpp); + + // page header + $page_header = new ilSelectInputGUI($lng->txt("cont_page_header"), "lm_pg_header"); + $option = array("st_title" => $this->lng->txt("cont_st_title"), + "pg_title" => $this->lng->txt("cont_pg_title"), + "none" => $this->lng->txt("cont_none")); + $page_header->setOptions($option); + $this->form->addItem($page_header); + + // chapter numeration + $chap_num = new ilCheckboxInputGUI($lng->txt("cont_act_number"), "cobj_act_number"); + $this->form->addItem($chap_num); + + // toc mode + $toc_mode = new ilSelectInputGUI($lng->txt("cont_toc_mode"), "toc_mode"); + $option = array("chapters" => $this->lng->txt("cont_chapters_only"), + "pages" => $this->lng->txt("cont_chapters_and_pages")); + $toc_mode->setOptions($option); + $this->form->addItem($toc_mode); + + // show progress icons + $progr_icons = new ilCheckboxInputGUI($lng->txt("cont_progress_icons"), "progr_icons"); + $progr_icons->setInfo($this->lng->txt("cont_progress_icons_info")); + $this->form->addItem($progr_icons); + + // self assessment + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($this->lng->txt('cont_self_assessment')); + $this->form->addItem($section); + + // tries + $radg = new ilRadioGroupInputGUI($lng->txt("cont_tries"), "store_tries"); + $radg->setValue(0); + $op1 = new ilRadioOption($lng->txt("cont_tries_reset_on_visit"), 0, $lng->txt("cont_tries_reset_on_visit_info")); + $radg->addOption($op1); + $op2 = new ilRadioOption($lng->txt("cont_tries_store"), 1, $lng->txt("cont_tries_store_info")); + $radg->addOption($op2); + $this->form->addItem($radg); + + // restrict forward navigation + $qfeed = new ilCheckboxInputGUI($lng->txt("cont_restrict_forw_nav"), "restrict_forw_nav"); + $qfeed->setInfo($this->lng->txt("cont_restrict_forw_nav_info")); + $this->form->addItem($qfeed); + + // notification + $not = new ilCheckboxInputGUI($lng->txt("cont_notify_on_blocked_users"), "notification_blocked_users"); + $not->setInfo($this->lng->txt("cont_notify_on_blocked_users_info")); + $qfeed->addSubItem($not); + + // disable default feedback for questions + $qfeed = new ilCheckboxInputGUI($lng->txt("cont_disable_def_feedback"), "disable_def_feedback"); + $qfeed->setInfo($this->lng->txt("cont_disable_def_feedback_info")); + $this->form->addItem($qfeed); + + // additional features + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($this->lng->txt('obj_features')); + $this->form->addItem($section); + + // public notes + if (!$ilSetting->get('disable_comments')) { + $this->lng->loadLanguageModule("notes"); + $pub_nodes = new ilCheckboxInputGUI($lng->txt("notes_comments"), "cobj_pub_notes"); + $pub_nodes->setInfo($this->lng->txt("cont_lm_comments_desc")); + $this->form->addItem($pub_nodes); + } + + // history user comments + $com = new ilCheckboxInputGUI($lng->txt("enable_hist_user_comments"), "cobj_user_comments"); + $com->setInfo($this->lng->txt("enable_hist_user_comments_desc")); + $this->form->addItem($com); + + // rating + $this->lng->loadLanguageModule('rating'); + $rate = new ilCheckboxInputGUI($this->lng->txt('rating_activate_rating'), 'rating'); + $rate->setInfo($this->lng->txt('rating_activate_rating_info')); + $this->form->addItem($rate); + $ratep = new ilCheckboxInputGUI($this->lng->txt('lm_activate_rating'), 'rating_pages'); + $this->form->addItem($ratep); + + $this->form->setTitle($lng->txt("cont_lm_properties")); + $this->form->addCommandButton("saveProperties", $lng->txt("save")); + $this->form->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * Get values for properties form + */ + public function getPropertiesFormValues() + { + $ilUser = $this->user; + + $values = array(); + + $title = $this->object->getTitle(); + $description = $this->object->getDescription(); + include_once("./Services/Object/classes/class.ilObjectTranslation.php"); + $ot = ilObjectTranslation::getInstance($this->object->getId()); + if ($ot->getContentActivated()) { + $title = $ot->getDefaultTitle(); + $description = $ot->getDefaultDescription(); + } + + $values["title"] = $title; + $values["description"] = $description; + if (!$this->object->getOfflineStatus()) { + $values["cobj_online"] = true; + } + $values["lm_layout"] = $this->object->getLayout(); + $values["lm_pg_header"] = $this->object->getPageHeader(); + if ($this->object->isActiveNumbering()) { + $values["cobj_act_number"] = true; + } + $values["toc_mode"] = $this->object->getTOCMode(); + if ($this->object->publicNotes()) { + $values["cobj_pub_notes"] = true; + } + if ($this->object->cleanFrames()) { + $values["cobj_clean_frames"] = true; + } + if ($this->object->isActiveHistoryUserComments()) { + $values["cobj_user_comments"] = true; + } + $values["layout_per_page"] = $this->object->getLayoutPerPage(); + $values["rating"] = $this->object->hasRating(); + $values["rating_pages"] = $this->object->hasRatingPages(); + $values["disable_def_feedback"] = $this->object->getDisableDefaultFeedback(); + $values["progr_icons"] = $this->object->getProgressIcons(); + $values["store_tries"] = $this->object->getStoreTries(); + $values["restrict_forw_nav"] = $this->object->getRestrictForwardNavigation(); + + include_once "./Services/Notification/classes/class.ilNotification.php"; + $values["notification_blocked_users"] = ilNotification::hasNotification( + ilNotification::TYPE_LM_BLOCKED_USERS, + $ilUser->getId(), + $this->object->getId() + ); + + $this->form->setValuesByArray($values); + } + + /** + * save properties + */ + public function saveProperties() + { + $lng = $this->lng; + $ilUser = $this->user; + $ilSetting = $this->settings; + $obj_service = $this->object_service; + + $valid = false; + $this->initPropertiesForm(); + if ($this->form->checkInput()) { + include_once("./Services/Object/classes/class.ilObjectTranslation.php"); + $ot = ilObjectTranslation::getInstance($this->object->getId()); + if ($ot->getContentActivated()) { + $ot->setDefaultTitle($_POST['title']); + $ot->setDefaultDescription($_POST['description']); + $ot->save(); + } + + $this->object->setTitle($_POST['title']); + $this->object->setDescription($_POST['description']); + $this->object->setLayout($_POST["lm_layout"]); + $this->object->setPageHeader($_POST["lm_pg_header"]); + $this->object->setTOCMode($_POST["toc_mode"]); + $this->object->setOfflineStatus(!($_POST['cobj_online'])); + $this->object->setActiveNumbering($_POST["cobj_act_number"]); + $this->object->setCleanFrames($_POST["cobj_clean_frames"]); + if (!$ilSetting->get('disable_comments')) { + $this->object->setPublicNotes($_POST["cobj_pub_notes"]); + } + $this->object->setHistoryUserComments($_POST["cobj_user_comments"]); + $this->object->setLayoutPerPage($_POST["layout_per_page"]); + $this->object->setRating($_POST["rating"]); + $this->object->setRatingPages($_POST["rating_pages"]); + $this->object->setDisableDefaultFeedback((int) $_POST["disable_def_feedback"]); + $this->object->setProgressIcons((int) $_POST["progr_icons"]); + + $add_info = ""; + if ($_POST["restrict_forw_nav"] && !$_POST["store_tries"]) { + $_POST["store_tries"] = 1; + $add_info = "
" . $lng->txt("cont_automatically_set_store_tries"); + $add_info = str_replace("$1", $lng->txt("cont_tries_store"), $add_info); + $add_info = str_replace("$2", $lng->txt("cont_restrict_forw_nav"), $add_info); + } + + $this->object->setStoreTries((int) $_POST["store_tries"]); + $this->object->setRestrictForwardNavigation((int) $_POST["restrict_forw_nav"]); + $this->object->updateProperties(); + $this->object->update(); + + // tile image + $obj_service->commonSettings()->legacyForm($this->form, $this->object)->saveTileImage(); + + include_once "./Services/Notification/classes/class.ilNotification.php"; + ilNotification::setNotification( + ilNotification::TYPE_LM_BLOCKED_USERS, + $ilUser->getId(), + $this->object->getId(), + (bool) $this->form->getInput("notification_blocked_users") + ); + + + if ($this->object->getType() == 'lm') { + // Update ecs export settings + include_once 'Modules/LearningModule/classes/class.ilECSLearningModuleSettings.php'; + $ecs = new ilECSLearningModuleSettings($this->object); + if ($ecs->handleSettingsUpdate()) { + $valid = true; + } + } else { + $valid = true; + } + } + + if ($valid) { + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified") . $add_info, true); + $this->ctrl->redirect($this, "properties"); + } else { + $lng->loadLanguageModule("style"); + $this->setTabs("settings"); + $this->setSubTabs("cont_general_properties"); + + $this->form->setValuesByPost(); + $this->tpl->setContent($this->form->getHTML()); + } + } + + /** + * Edit style properties + */ + public function editStyleProperties() + { + $tpl = $this->tpl; + + $this->initStylePropertiesForm(); + $tpl->setContent($this->form->getHTML()); + } + + /** + * Init style properties form + */ + public function initStylePropertiesForm() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilTabs = $this->tabs; + $ilSetting = $this->settings; + + $lng->loadLanguageModule("style"); + $this->setTabs(); + $ilTabs->setTabActive("settings"); + $this->setSubTabs("cont_style"); + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + $fixed_style = $ilSetting->get("fixed_content_style_id"); + $def_style = $ilSetting->get("default_content_style_id"); + $style_id = $this->object->getStyleSheetId(); + + if ($fixed_style > 0) { + $st = new ilNonEditableValueGUI($lng->txt("cont_current_style")); + $st->setValue(ilObject::_lookupTitle($fixed_style) . " (" . + $this->lng->txt("global_fixed") . ")"); + $this->form->addItem($st); + } else { + $st_styles = ilObjStyleSheet::_getStandardStyles( + true, + false, + $_GET["ref_id"] + ); + + if ($def_style > 0) { + $st_styles[0] = ilObject::_lookupTitle($def_style) . " (" . $this->lng->txt("default") . ")"; + } else { + $st_styles[0] = $this->lng->txt("default"); + } + ksort($st_styles); + + if ($style_id > 0) { + // individual style + if (!ilObjStyleSheet::_lookupStandard($style_id)) { + $st = new ilNonEditableValueGUI($lng->txt("cont_current_style")); + $st->setValue(ilObject::_lookupTitle($style_id)); + $this->form->addItem($st); + + // delete command + $this->form->addCommandButton( + "editStyle", + $lng->txt("cont_edit_style") + ); + $this->form->addCommandButton( + "deleteStyle", + $lng->txt("cont_delete_style") + ); + } + } + + if ($style_id <= 0 || ilObjStyleSheet::_lookupStandard($style_id)) { + $style_sel = new ilSelectInputGUI($lng->txt("cont_current_style"), "style_id"); + $style_sel->setOptions($st_styles); + $style_sel->setValue($style_id); + $this->form->addItem($style_sel); + $this->form->addCommandButton( + "saveStyleSettings", + $lng->txt("save") + ); + $this->form->addCommandButton( + "createStyle", + $lng->txt("sty_create_ind_style") + ); + } + } + $this->form->setTitle($lng->txt("cont_style")); + $this->form->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * Create Style + */ + public function createStyle() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirectByClass("ilobjstylesheetgui", "create"); + } + + /** + * Edit Style + */ + public function editStyle() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirectByClass("ilobjstylesheetgui", "edit"); + } + + /** + * Delete Style + */ + public function deleteStyle() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirectByClass("ilobjstylesheetgui", "delete"); + } + + /** + * Save style settings + */ + public function saveStyleSettings() + { + $ilSetting = $this->settings; + + if ($ilSetting->get("fixed_content_style_id") <= 0 && + (ilObjStyleSheet::_lookupStandard($this->object->getStyleSheetId()) + || $this->object->getStyleSheetId() == 0)) { + $this->object->setStyleSheetId(ilUtil::stripSlashes($_POST["style_id"])); + $this->object->update(); + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + } + $this->ctrl->redirect($this, "editStyleProperties"); + } + + /** + * Init menu form + */ + public function initMenuForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + + // enable menu + $menu = new ilCheckboxInputGUI($this->lng->txt("cont_active"), "cobj_act_lm_menu"); + $menu->setChecked($this->object->isActiveLMMenu()); + $form->addItem($menu); + + // toc + $toc = new ilCheckboxInputGUI($this->lng->txt("cont_toc"), "cobj_act_toc"); + $toc->setChecked($this->object->isActiveTOC()); + $form->addItem($toc); + + // print view + $print = new ilCheckboxInputGUI($this->lng->txt("cont_print_view"), "cobj_act_print"); + $print->setChecked($this->object->isActivePrintView()); + $form->addItem($print); + + // prevent glossary appendix + $glo = new ilCheckboxInputGUI($this->lng->txt("cont_print_view_pre_glo"), "cobj_act_print_prev_glo"); + $glo->setChecked($this->object->isActivePreventGlossaryAppendix()); + $print->addSubItem($glo); + + // hide header and footer in print view + $hhfp = new ilCheckboxInputGUI($this->lng->txt("cont_hide_head_foot_print"), "hide_head_foot_print"); + $hhfp->setChecked($this->object->getHideHeaderFooterPrint()); + $print->addSubItem($hhfp); + + // downloads + $no_download_file_available = + " " . $lng->txt("cont_no_download_file_available") . + " " . $lng->txt("change") . ""; + $types = array("xml", "html", "scorm"); + foreach ($types as $type) { + if ($this->object->getPublicExportFile($type) != "") { + if (is_file($this->object->getExportDirectory($type) . "/" . + $this->object->getPublicExportFile($type))) { + $no_download_file_available = ""; + } + } + } + $dl = new ilCheckboxInputGUI($this->lng->txt("cont_downloads"), "cobj_act_downloads"); + $dl->setInfo($this->lng->txt("cont_downloads_desc") . $no_download_file_available); + $dl->setChecked($this->object->isActiveDownloads()); + $form->addItem($dl); + + // downloads in public area + $pdl = new ilCheckboxInputGUI($this->lng->txt("cont_downloads_public_desc"), "cobj_act_downloads_public"); + $pdl->setChecked($this->object->isActiveDownloadsPublic()); + $dl->addSubItem($pdl); + + $form->addCommandButton("saveMenuProperties", $lng->txt("save")); + + $form->setTitle($lng->txt("cont_lm_menu")); + $form->setFormAction($ilCtrl->getFormAction($this)); + + return $form; + } + + /** + * Edit menu properies + */ + public function editMenuProperties() + { + $lng = $this->lng; + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + + $lng->loadLanguageModule("style"); + $this->setTabs(); + $ilTabs->setTabActive("settings"); + $this->setSubTabs("cont_lm_menu"); + + $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); + $ilToolbar->addFormButton($this->lng->txt("add_menu_entry"), "addMenuEntry"); + $ilToolbar->setCloseFormTag(false); + + $form = $this->initMenuForm(); + $form->setOpenTag(false); + $form->setCloseTag(false); + + $this->__initLMMenuEditor(); + $entries = $this->lmme_obj->getMenuEntries(); + include_once("./Modules/LearningModule/classes/class.ilLMMenuItemsTableGUI.php"); + $table = new ilLMMenuItemsTableGUI($this, "editMenuProperties", $this->lmme_obj); + $table->setOpenFormTag(false); + + $tpl->setContent($form->getHTML() . "
" . $table->getHTML()); + } + + /** + * save properties + */ + public function saveMenuProperties() + { + $this->object->setActiveLMMenu((int) $_POST["cobj_act_lm_menu"]); + $this->object->setActiveTOC((int) $_POST["cobj_act_toc"]); + $this->object->setActivePrintView((int) $_POST["cobj_act_print"]); + $this->object->setActivePreventGlossaryAppendix((int) $_POST["cobj_act_print_prev_glo"]); + $this->object->setHideHeaderFooterPrint((int) $_POST["hide_head_foot_print"]); + $this->object->setActiveDownloads((int) $_POST["cobj_act_downloads"]); + $this->object->setActiveDownloadsPublic((int) $_POST["cobj_act_downloads_public"]); + $this->object->updateProperties(); + + $this->__initLMMenuEditor(); + //var_dump($_POST["menu_entries"]); exit; + $this->lmme_obj->updateActiveStatus($_POST["menu_entries"]); + + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "editMenuProperties"); + } + + /** + * output explorer tree + */ + public function explorer() + { + $ilCtrl = $this->ctrl; + + $gui_class = "ilobjlearningmodulegui"; + + $ilCtrl->setParameterByClass($gui_class, "active_node", $_GET["active_node"]); + + $this->tpl = new ilTemplate("tpl.main.html", true, true); + + $this->tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); + + $this->tpl->addBlockFile("CONTENT", "content", "tpl.explorer.html"); + $this->tpl->setVariable("IMG_SPACE", ilUtil::getImagePath("spacer.png", false)); + + require_once("./Modules/LearningModule/classes/class.ilLMEditorExplorer.php"); + $exp = new ilLMEditorExplorer( + $this->ctrl->getLinkTarget($this, "view"), + $this->object, + $gui_class + ); + + $exp->setTargetGet("obj_id"); + $exp->setExpandTarget($this->ctrl->getLinkTarget($this, "explorer")); + + if ($_GET["lmmovecopy"] == "1") { + $this->proceedDragDrop(); + } + + + if ($_GET["lmexpand"] == "") { + $mtree = new ilTree($this->object->getId()); + $mtree->setTableNames('lm_tree', 'lm_data'); + $mtree->setTreeTablePK("lm_id"); + $expanded = $mtree->readRootId(); + } else { + $expanded = $_GET["lmexpand"]; + } + if ($_GET["active_node"] != "") { + $path = $this->lm_tree->getPathId($_GET["active_node"]); + $exp->setForceOpenPath($path); + + $exp->highlightNode($_GET["active_node"]); + } + $exp->setExpand($expanded); + + // build html-output + $exp->setOutput(0); + $output = $exp->getOutput(); + + // asynchronous output + if ($ilCtrl->isAsynch()) { + echo $output; + exit; + } + + include_once("./Services/COPage/classes/class.ilPageEditorGUI.php"); + + $this->tpl->setCurrentBlock("content"); + $this->tpl->setVariable("TXT_EXPLORER_HEADER", $this->lng->txt("cont_chap_and_pages")); + $this->tpl->setVariable("EXP_REFRESH", $this->lng->txt("refresh")); + $this->tpl->setVariable("EXPLORER", $output); + $this->ctrl->setParameter($this, "lmexpand", $_GET["lmexpand"]); + $this->tpl->setVariable("ACTION", $this->ctrl->getLinkTarget($this, "explorer")); + $this->tpl->parseCurrentBlock(); + $this->tpl->show(false); + exit; + } + + /** + * popup window for wysiwyg editor + */ + public function popup() + { + include_once "./Services/COPage/classes/class.ilWysiwygUtil.php"; + $popup = new ilWysiwygUtil(); + $popup->show($_GET["ptype"]); + exit; + } + + /** + * proceed drag and drop operations on pages/chapters + */ + public function proceedDragDrop() + { + $ilCtrl = $this->ctrl; + + $this->object->executeDragDrop( + $_POST["il_hform_source_id"], + $_POST["il_hform_target_id"], + $_POST["il_hform_fc"], + $_POST["il_hform_as_subitem"] + ); + $ilCtrl->redirect($this, "chapters"); + } + + /* protected function initCreationForms($a_new_type) + { + $forms = array(self::CFORM_NEW => $this->initCreateForm($a_new_type), + self::CFORM_IMPORT => $this->initImportForm()); + + return $forms; + }*/ + + protected function afterSave(ilObject $a_new_object) + { + $a_new_object->setCleanFrames(true); + $a_new_object->update(); + + // create content object tree + $a_new_object->createLMTree(); + + // create a first chapter + $a_new_object->addFirstChapterAndPage(); + + // always send a message + ilUtil::sendSuccess($this->lng->txt($this->type . "_added"), true); + ilUtil::redirect("ilias.php?ref_id=" . $a_new_object->getRefId() . + "&baseClass=ilLMEditorGUI"); + } + + /** + * Init import form. + */ + public function initImportForm($a_new_type) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + + $new_type = $_POST["new_type"] ? $_POST["new_type"] : $_GET["new_type"]; + $this->ctrl->setParameter($this, "new_type", $new_type); + + $form->setTarget(ilFrameTargetInfo::_getFrame("MainContent")); + $form->setTableWidth("600px"); + + // import file + //$fi = new ilFileInputGUI($this->lng->txt("file"), "xmldoc"); + $fi = new ilFileInputGUI($this->lng->txt("file"), "importfile"); + $fi->setSuffixes(array("zip")); + $fi->setRequired(true); + $fi->setSize(30); + $form->addItem($fi); + + // validation + $cb = new ilCheckboxInputGUI($this->lng->txt("cont_validate_file"), "validate"); + $cb->setInfo($this->lng->txt("")); + $form->addItem($cb); + + $form->addCommandButton("importFile", $lng->txt("import")); + $form->addCommandButton("cancel", $lng->txt("cancel")); + + $form->setTitle($this->lng->txt("import_" . $new_type)); + $form->setFormAction($ilCtrl->getFormAction($this)); + + return $form; + } + + /** + * export object + * + * @access public + */ + public function exportObject() + { + return; + } + + /** + * display dialogue for importing XML-LeaningObjects + * + * @access public + */ + public function importObject() + { + $this->createObject(); + return; + } + + + /** + * display status information or report errors messages + * in case of error + * + * @access public + */ + public function importFileObject($parent_id = null, $a_catch_errors = true) + { + $rbacsystem = $this->rbacsystem; + $ilErr = $this->error; + $tpl = $this->tpl; + + $form = $this->initImportForm("lm"); + + try { + // the new import + parent::importFileObject(null, false); + return; + } catch (ilManifestFileNotFoundImportException $e) { + // we just run through in this case. + $no_manifest = true; + } catch (ilException $e) { + // display message and form again + ilUtil::sendFailure($this->lng->txt("obj_import_file_error") . "
" . $e->getMessage()); + $form->setValuesByPost(); + $tpl->setContent($form->getHtml()); + return; + } + + if (!$no_manifest) { + return; // something different has gone wrong, but we have a manifest, this is definitely not "the old" import + } + + // the "old" (pre 5.1) import + + include_once "./Modules/LearningModule/classes/class.ilObjLearningModule.php"; + + if (!$rbacsystem->checkAccess("create", $_GET["ref_id"], $_GET["new_type"])) { + $ilErr->raiseError($this->lng->txt("no_create_permission"), $ilErr->MESSAGE); + return; + } + + if ($form->checkInput()) { + // create and insert object in objecttree + include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); + $newObj = new ilObjContentObject(); + $newObj->setType($_GET["new_type"]); + $newObj->setTitle($_FILES["importfile"]["name"]); + $newObj->setDescription(""); + $newObj->create(true); + $newObj->createReference(); + $newObj->putInTree($_GET["ref_id"]); + $newObj->setPermissions($_GET["ref_id"]); + + // create learning module tree + $newObj->createLMTree(); + + // since the "new" import already did the extracting + $mess = $newObj->importFromDirectory($this->tmp_import_dir, $_POST["validate"]); + + if ($mess == "") { + ilUtil::sendSuccess($this->lng->txt($this->type . "_added"), true); + ilUtil::redirect("ilias.php?ref_id=" . $newObj->getRefId() . + "&baseClass=ilLMEditorGUI"); + } else { + $link = '' . $this->lng->txt("btn_next") . ''; + $tpl->setContent("
" . $link . "

" . $mess . $link); + } + } else { + $form->setValuesByPost(); + $tpl->setContent($form->getHtml()); + } + } + + /** + * show chapters + */ + public function chapters() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $this->setTabs(); + $this->setContentSubTabs("chapters"); + + $ilCtrl->setParameter($this, "backcmd", "chapters"); + + include_once("./Modules/LearningModule/classes/class.ilChapterHierarchyFormGUI.php"); + $form_gui = new ilChapterHierarchyFormGUI($this->object->getType(), $_GET["transl"]); + $form_gui->setFormAction($ilCtrl->getFormAction($this)); + $form_gui->setTitle($this->object->getTitle()); + $form_gui->setIcon(ilUtil::getImagePath("icon_lm.svg")); + $form_gui->setTree($this->lm_tree); + $form_gui->setMaxDepth(0); + $form_gui->setCurrentTopNodeId($this->tree->getRootId()); + $form_gui->addMultiCommand($lng->txt("delete"), "delete"); + $form_gui->addMultiCommand($lng->txt("cut"), "cutItems"); + $form_gui->addMultiCommand($lng->txt("copy"), "copyItems"); + if ($this->object->getLayoutPerPage()) { + $form_gui->addMultiCommand($lng->txt("cont_set_layout"), "setPageLayoutInHierarchy"); + } + $form_gui->setDragIcon(ilUtil::getImagePath("icon_st.svg")); + $form_gui->addCommand($lng->txt("cont_save_all_titles"), "saveAllTitles"); + $up_gui = "ilobjlearningmodulegui"; + + $ctpl = new ilTemplate("tpl.chap_and_pages.html", true, true, "Modules/LearningModule"); + $ctpl->setVariable("HIERARCHY_FORM", $form_gui->getHTML()); + $ilCtrl->setParameter($this, "obj_id", ""); + + $ml_head = self::getMultiLangHeader($this->object->getId(), $this); + + $this->tpl->setContent($ml_head . $ctpl->get()); + } + + /** + * Get multi lang header + * + * @param + * @return + */ + public static function getMultiLangHeader($a_lm_id, $a_gui_class, $a_mode = "") + { + global $DIC; + + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + + // multi language + include_once("./Services/Object/classes/class.ilObjectTranslation.php"); + $ot = ilObjectTranslation::getInstance($a_lm_id); + if ($ot->getContentActivated()) { + $ilCtrl->setParameter($a_gui_class, "lang_switch_mode", $a_mode); + $lng->loadLanguageModule("meta"); + + // info + include_once("./Services/COPage/classes/class.ilPageMultiLangGUI.php"); + $ml_gui = new ilPageMultiLangGUI("lm", $a_lm_id); + $ml_head = $ml_gui->getMultiLangInfo($_GET["transl"]); + + // language switch + include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"); + $list = new ilAdvancedSelectionListGUI(); + $list->setListTitle($lng->txt("actions")); + $list->setId("copage_act"); + $entries = false; + if (!in_array($_GET["transl"], array("", "-"))) { + $l = $ot->getMasterLanguage(); + $list->addItem( + $lng->txt("cont_edit_language_version") . ": " . + $lng->txt("meta_l_" . $l), + "", + $ilCtrl->getLinkTarget($a_gui_class, "editMasterLanguage") + ); + $entries = true; + } + + foreach ($ot->getLanguages() as $al => $lang) { + if ($_GET["transl"] != $al && + $al != $ot->getMasterLanguage()) { + $ilCtrl->setParameter($a_gui_class, "totransl", $al); + $list->addItem( + $lng->txt("cont_edit_language_version") . ": " . + $lng->txt("meta_l_" . $al), + "", + $ilCtrl->getLinkTarget($a_gui_class, "switchToLanguage") + ); + $ilCtrl->setParameter($a_gui_class, "totransl", $_GET["totransl"]); + } + $entries = true; + } + + if ($entries) { + $ml_head = '
' . $ml_head . '
' . $list->getHTML() . "
"; + } + $ilCtrl->setParameter($a_gui_class, "lang_switch_mode", ""); + } + + return $ml_head; + } + + + /* + * List all pages of learning module + */ + public function pages() + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->setTabs(); + $this->setContentSubTabs("pages"); + + $ilCtrl->setParameter($this, "backcmd", "pages"); + $ilCtrl->setParameterByClass("illmpageobjectgui", "new_type", "pg"); + $ilToolbar->addButton( + $lng->txt("pg_add"), + $ilCtrl->getLinkTargetByClass("illmpageobjectgui", "create") + ); + $ilCtrl->setParameterByClass("illmpageobjectgui", "new_type", ""); + + include_once("./Modules/LearningModule/classes/class.ilLMPagesTableGUI.php"); + $t = new ilLMPagesTableGUI($this, "pages", $this->object); + $tpl->setContent($t->getHTML()); + } + + /** + * List all broken links + */ + public function listLinks() + { + $tpl = $this->tpl; + + $this->setTabs(); + $this->setContentSubTabs("internal_links"); + + include_once("./Modules/LearningModule/classes/class.ilLinksTableGUI.php"); + $table_gui = new ilLinksTableGUI( + $this, + "listLinks", + $this->object->getId(), + $this->object->getType() + ); + + $tpl->setContent($table_gui->getHTML()); + } + + /** + * Show maintenance + */ + public function showMaintenance() + { + $ilToolbar = $this->toolbar; + + $this->setTabs(); + $this->setContentSubTabs("maintenance"); + + $ilToolbar->addButton( + $this->lng->txt("cont_fix_tree"), + $this->ctrl->getLinkTarget($this, "fixTreeConfirm") + ); + } + + /** + * activates or deactivates pages + */ + public function activatePages() + { + if (is_array($_POST["id"])) { + foreach ($_POST["id"] as $id) { + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + $act = ilLMPage::_lookupActive($id, $this->object->getType()); + ilLMPage::_writeActive($id, $this->object->getType(), !$act); + } + } + + $this->ctrl->redirect($this, "pages"); + } + + /** + * paste page + */ + public function pastePage() + { + $ilErr = $this->error; + + if (ilEditClipboard::getContentObjectType() != "pg") { + $ilErr->raiseError($this->lng->txt("no_page_in_clipboard"), $ilErr->MESSAGE); + } + + // paste selected object + $id = ilEditClipboard::getContentObjectId(); + + // copy page, if action is copy + if (ilEditClipboard::getAction() == "copy") { + // check wether page belongs to lm + if (ilLMObject::_lookupContObjID(ilEditClipboard::getContentObjectId()) + == $this->object->getID()) { + $lm_page = new ilLMPageObject($this->object, $id); + $new_page = $lm_page->copy(); + $id = $new_page->getId(); + } else { + // get page from other content object into current content object + $lm_id = ilLMObject::_lookupContObjID(ilEditClipboard::getContentObjectId()); + $lm_obj = ilObjectFactory::getInstanceByObjId($lm_id); + $lm_page = new ilLMPageObject($lm_obj, $id); + $copied_nodes = array(); + $new_page = $lm_page->copyToOtherContObject($this->object, $copied_nodes); + $id = $new_page->getId(); + ilLMObject::updateInternalLinks($copied_nodes); + } + } + + // cut is not be possible in "all pages" form yet + if (ilEditClipboard::getAction() == "cut") { + // check wether page belongs not to lm + if (ilLMObject::_lookupContObjID(ilEditClipboard::getContentObjectId()) + != $this->object->getID()) { + $lm_id = ilLMObject::_lookupContObjID(ilEditClipboard::getContentObjectId()); + $lm_obj = ilObjectFactory::getInstanceByObjId($lm_id); + $lm_page = new ilLMPageObject($lm_obj, $id); + $lm_page->setLMId($this->object->getID()); + $lm_page->update(); + $page = $lm_page->getPageObject(); + $page->buildDom(); + $page->setParentId($this->object->getID()); + $page->update(); + } + } + + + ilEditClipboard::clear(); + $this->ctrl->redirect($this, "pages"); + } + + /** + * copy page + */ + public function copyPage() + { + $ilErr = $this->error; + + if (!isset($_POST["id"])) { + $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); + } + + $items = ilUtil::stripSlashesArray($_POST["id"]); + ilLMObject::clipboardCopy($this->object->getId(), $items); + ilEditClipboard::setAction("copy"); + + ilUtil::sendInfo($this->lng->txt("cont_selected_items_have_been_copied"), true); + + $this->ctrl->redirect($this, "pages"); + } + + /** + * confirm deletion screen for page object and structure object deletion + * + * @param int $a_parent_subobj_id id of parent object (structure object) + * of the objects, that should be deleted + * (or no parent object id for top level) + */ + public function delete($a_parent_subobj_id = 0) + { + $ilErr = $this->error; + + if (!isset($_POST["id"])) { + $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); + } + + if (count($_POST["id"]) == 1 && $_POST["id"][0] == IL_FIRST_NODE) { + $ilErr->raiseError($this->lng->txt("cont_select_item"), $ilErr->MESSAGE); + } + + if ($a_parent_subobj_id == 0) { + $this->setTabs(); + } + + if ($a_parent_subobj_id != 0) { + $this->ctrl->setParameterByClass("ilStructureObjectGUI", "backcmd", $_GET["backcmd"]); + $this->ctrl->setParameterByClass("ilStructureObjectGUI", "obj_id", $a_parent_subobj_id); + $form_action = $this->ctrl->getFormActionByClass("ilStructureObjectGUI"); + } else { + $this->ctrl->setParameter($this, "backcmd", $_GET["backcmd"]); + $form_action = $this->ctrl->getFormAction($this); + } + + // display confirmation message + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($form_action); + $cgui->setHeaderText($this->lng->txt("info_delete_sure")); + $cgui->setCancel($this->lng->txt("cancel"), "cancelDelete"); + $cgui->setConfirm($this->lng->txt("confirm"), "confirmedDelete"); + + foreach ($_POST["id"] as $id) { + if ($id != IL_FIRST_NODE) { + $obj = new ilLMObject($this->object, $id); + $caption = ilUtil::getImageTagByType($obj->getType(), $this->tpl->tplPath) . + " " . $obj->getTitle(); + + $cgui->addItem("id[]", $id, $caption); + } + } + + $this->tpl->setContent($cgui->getHTML()); + } + + /** + * cancel delete + */ + public function cancelDelete() + { + $this->ctrl->redirect($this, $_GET["backcmd"]); + } + + /** + * delete page object or structure objects + * + * @param int $a_parent_subobj_id id of parent object (structure object) + * of the objects, that should be deleted + * (or no parent object id for top level) + */ + public function confirmedDelete($a_parent_subobj_id = 0) + { + $ilErr = $this->error; + + $tree = new ilTree($this->object->getId()); + $tree->setTableNames('lm_tree', 'lm_data'); + $tree->setTreeTablePK("lm_id"); + + // check number of objects + if (!$_POST["id"]) { + $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); + } + + // delete all selected objects + foreach ($_POST["id"] as $id) { + if ($id != IL_FIRST_NODE) { + $obj = ilLMObjectFactory::getInstance($this->object, $id, false); + $node_data = $tree->getNodeData($id); + if (is_object($obj)) { + $obj->setLMId($this->object->getId()); + + include_once("./Services/History/classes/class.ilHistory.php"); + ilHistory::_createEntry( + $this->object->getId(), + "delete_" . $obj->getType(), + array(ilLMObject::_lookupTitle($id), $id), + $this->object->getType() + ); + + $obj->delete(); + } + if ($tree->isInTree($id)) { + $tree->deleteTree($node_data); + } + } + } + + // check the tree + $this->object->checkTree(); + + // feedback + ilUtil::sendSuccess($this->lng->txt("info_deleted"), true); + + if ($a_parent_subobj_id == 0) { + $this->ctrl->redirect($this, $_GET["backcmd"]); + } + } + + + + /** + * get context path in content object tree + * + * @param int $a_endnode_id id of endnode + * @param int $a_startnode_id id of startnode + */ + public function getContextPath($a_endnode_id, $a_startnode_id = 1) + { + $path = ""; + + $tmpPath = $this->lm_tree->getPathFull($a_endnode_id, $a_startnode_id); + + // count -1, to exclude the learning module itself + for ($i = 1; $i < (count($tmpPath) - 1); $i++) { + if ($path != "") { + $path .= " > "; + } + + $path .= $tmpPath[$i]["title"]; + } + + return $path; + } + + + + /** + * show possible action (form buttons) + * + * @access public + */ + public function showActions($a_actions) + { + foreach ($a_actions as $name => $lng) { + $d[$name] = array("name" => $name, "lng" => $lng); + } + + $notoperations = array(); + + $operations = array(); + + if (is_array($d)) { + foreach ($d as $row) { + if (!in_array($row["name"], $notoperations)) { + $operations[] = $row; + } + } + } + + if (count($operations)>0) { + foreach ($operations as $val) { + $this->tpl->setCurrentBlock("operation_btn"); + $this->tpl->setVariable("BTN_NAME", $val["name"]); + $this->tpl->setVariable("BTN_VALUE", $this->lng->txt($val["lng"])); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setCurrentBlock("operation"); + $this->tpl->setVariable("IMG_ARROW", ilUtil::getImagePath("arrow_downright.svg")); + $this->tpl->parseCurrentBlock(); + } + } + + /** + * view content object + */ + public function view() + { + if (strtolower($_GET["baseClass"]) == "iladministrationgui") { + $this->prepareOutput(); + parent::viewObject(); + } else { + $this->viewObject(); + } + } + + + /** + * move a single chapter (selection) + */ + public function moveChapter($a_parent_subobj_id = 0) + { + $ilErr = $this->error; + + if (!isset($_POST["id"])) { + $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); + } + if (count($_POST["id"]) > 1) { + $ilErr->raiseError($this->lng->txt("cont_select_max_one_item"), $ilErr->MESSAGE); + } + + if (count($_POST["id"]) == 1 && $_POST["id"][0] == IL_FIRST_NODE) { + $ilErr->raiseError($this->lng->txt("cont_select_item"), $ilErr->MESSAGE); + } + + // SAVE POST VALUES + ilEditClipboard::storeContentObject("st", $_POST["id"][0], "move"); + + ilUtil::sendInfo($this->lng->txt("cont_chap_select_target_now"), true); + + if ($a_parent_subobj_id == 0) { + $this->ctrl->redirect($this, "chapters"); + } + } + + + /** + * copy a single chapter (selection) + */ + public function copyChapter($a_parent_subobj_id = 0) + { + $this->copyItems(); + } + + /** + * paste chapter + */ + public function pasteChapter($a_parent_subobj_id = 0) + { + return $this->insertChapterClip(false); + } + + /** + * move page + */ + public function movePage() + { + $ilErr = $this->error; + + if (!isset($_POST["id"])) { + $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); + } + + ilUtil::sendInfo($this->lng->txt("cont_selected_items_have_been_cut"), true); + + $items = ilUtil::stripSlashesArray($_POST["id"]); + ilLMObject::clipboardCut($this->object->getId(), $items); + ilEditClipboard::setAction("cut"); + + $this->ctrl->redirect($this, "pages"); + } + + /** + * cancel action + */ + public function cancel() + { + if ($_GET["new_type"] == "pg") { + $this->ctrl->redirect($this, "pages"); + } else { + $this->ctrl->redirect($this, "chapters"); + } + } + + + /** + * export content object + */ + public function export() + { + $ot = ilObjectTranslation::getInstance($this->object->getId()); + $opt = ""; + if ($ot->getContentActivated()) { + $format = explode("_", $_POST["format"]); + $opt = ilUtil::stripSlashes($format[1]); + } + + + require_once("./Modules/LearningModule/classes/class.ilContObjectExport.php"); + $cont_exp = new ilContObjectExport($this->object); + $cont_exp->buildExportFile($opt); + // $this->ctrl->redirect($this, "exportList"); + } + + /** + * Get public access value for export table + */ + public function getPublicAccessColValue($a_type, $a_file) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $changelink = "" . $lng->txt("change") . ""; + if (!$this->object->isActiveLMMenu()) { + $add = "
" . $lng->txt("cont_download_no_menu") . " " . $changelink; + } elseif (!$this->object->isActiveDownloads()) { + $add = "
" . $lng->txt("cont_download_no_download") . " " . $changelink; + } + + $basetype = explode("_", $a_type); + $basetype = $basetype[0]; + + if ($this->object->getPublicExportFile($basetype) == $a_file) { + return $lng->txt("yes") . $add; + } + + return " "; + } + + + + /** + * download export file + */ + public function publishExportFile($a_files) + { + $ilCtrl = $this->ctrl; + + if (!isset($a_files)) { + ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); + } else { + foreach ($a_files as $f) { + $file = explode(":", $f); + if (is_int(strpos($file[0], "_"))) { + $file[0] = explode("_", $file[0])[0]; + } + $export_dir = $this->object->getExportDirectory($file[0]); + + if ($this->object->getPublicExportFile($file[0]) == + $file[1]) { + $this->object->setPublicExportFile($file[0], ""); + } else { + $this->object->setPublicExportFile($file[0], $file[1]); + } + } + $this->object->update(); + } + $ilCtrl->redirectByClass("ilexportgui"); + } + + /** + * download export file + */ + public function downloadPDFFile() + { + $ilErr = $this->error; + + if (!isset($_POST["file"])) { + $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); + } + + if (count($_POST["file"]) > 1) { + $ilErr->raiseError($this->lng->txt("cont_select_max_one_item"), $ilErr->MESSAGE); + } + + + $export_dir = $this->object->getOfflineDirectory(); + + $file = basename($_POST["file"][0]); + + ilUtil::deliverFile($export_dir . "/" . $file, $file); + } + + + /** + * confirm screen for tree fixing + * + */ + public function fixTreeConfirm() + { + $this->setTabs(); + $this->setContentSubTabs("maintenance"); + + // display confirmation message + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($this->ctrl->getFormAction($this)); + $cgui->setHeaderText($this->lng->txt("cont_fix_tree_confirm")); + $cgui->setCancel($this->lng->txt("cancel"), "showMaintenance"); + $cgui->setConfirm($this->lng->txt("cont_fix_tree"), "fixTree"); + $issues = $this->object->checkStructure(); + $mess = ""; + if (count($issues) > 0) { + $mess = "Found Issues:
" . implode("
", $issues); + } + $this->tpl->setContent($cgui->getHTML() . $mess); + } + + /** + * Fix tree + */ + public function fixTree() + { + $this->object->fixTree(); + ilUtil::sendSuccess($this->lng->txt("cont_tree_fixed"), true); + $this->ctrl->redirect($this, "showMaintenance"); + } + + /** + * get lm menu html + */ + public function setilLMMenu( + $a_offline = false, + $a_export_format = "", + $a_active = "content", + $a_use_global_tabs = false, + $a_as_subtabs = false, + $a_cur_page = 0, + $a_lang = "", + $a_export_all = false + ) { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + $ilAccess = $this->access; + $ilTabs = $this->tabs; + $rbacsystem = $this->rbacsystem; + $ilPluginAdmin = $this->plugin_admin; + $ilHelp = $this->help; + + $ilHelp->setScreenIdComponent("lm"); + + if ($a_as_subtabs) { + $addcmd = "addSubTabTarget"; + $getcmd = "getSubTabHTML"; + } else { + $addcmd = "addTarget"; + $getcmd = "getHTML"; + } + + $active[$a_active] = true; + + if (!$this->object->isActiveLMMenu()) { + return ""; + } + + if ($a_use_global_tabs) { + $tabs_gui = $ilTabs; + } else { + $tabs_gui = new ilTabsGUI(); + } + + // workaround for preventing tooltips in export + if ($a_offline) { + $tabs_gui->setSetupMode(true); + } + + // Determine whether the view of a learning resource should + // be shown in the frameset of ilias, or in a separate window. + $showViewInFrameset = true; + + if ($showViewInFrameset && !$a_offline) { + $buttonTarget = ilFrameTargetInfo::_getFrame("MainContent"); + } else { + $buttonTarget = "_top"; + } + + if ($a_export_format == "scorm") { + $buttonTarget = ""; + } + + // content + if (!$a_offline && $ilAccess->checkAccess("read", "", $_GET["ref_id"])) { + $ilCtrl->setParameterByClass("illmpresentationgui", "obj_id", $_GET["obj_id"]); + $tabs_gui->$addcmd( + "content", + $ilCtrl->getLinkTargetByClass("illmpresentationgui", "layout"), + "", + "", + $buttonTarget, + $active["content"] + ); + if ($active["content"]) { + $ilHelp->setScreenId("content"); + $ilHelp->setSubScreenId("content"); + } + } elseif ($a_offline) { + $tabs_gui->setForcePresentationOfSingleTab(true); + } + + // table of contents + if ($this->object->isActiveTOC() && $ilAccess->checkAccess("read", "", $_GET["ref_id"])) { + if (!$a_offline) { + $ilCtrl->setParameterByClass("illmpresentationgui", "obj_id", $_GET["obj_id"]); + $link = $ilCtrl->getLinkTargetByClass("illmpresentationgui", "showTableOfContents"); + } else { + if ($a_export_all) { + $link = "./table_of_contents_" . $a_lang . ".html"; + } else { + $link = "./table_of_contents.html"; + } + } + $tabs_gui->$addcmd( + "cont_toc", + $link, + "", + "", + $buttonTarget, + $active["toc"] + ); + } + + // print view + if ($this->object->isActivePrintView() && $ilAccess->checkAccess("read", "", $_GET["ref_id"])) { + if (!$a_offline) { // has to be implemented for offline mode + $ilCtrl->setParameterByClass("illmpresentationgui", "obj_id", $_GET["obj_id"]); + $link = $ilCtrl->getLinkTargetByClass("illmpresentationgui", "showPrintViewSelection"); + $tabs_gui->$addcmd( + "cont_print_view", + $link, + "", + "", + $buttonTarget, + $active["print"] + ); + } + } + + // download + if ($ilUser->getId() == ANONYMOUS_USER_ID) { + $is_public = $this->object->isActiveDownloadsPublic(); + } else { + $is_public = true; + } + + if ($this->object->isActiveDownloads() && !$a_offline && $is_public && + $ilAccess->checkAccess("read", "", $_GET["ref_id"])) { + $ilCtrl->setParameterByClass("illmpresentationgui", "obj_id", $_GET["obj_id"]); + $link = $ilCtrl->getLinkTargetByClass("illmpresentationgui", "showDownloadList"); + $tabs_gui->$addcmd( + "download", + $link, + "", + "", + $buttonTarget, + $active["download"] + ); + } + + // info button + if ($a_export_format != "scorm" && !$a_offline) { + if (!$a_offline) { + $ilCtrl->setParameterByClass("illmpresentationgui", "obj_id", $_GET["obj_id"]); + $link = $this->ctrl->getLinkTargetByClass( + array("illmpresentationgui", "ilinfoscreengui"), + "showSummary" + ); + } else { + $link = "./info.html"; + } + + $tabs_gui->$addcmd( + 'info_short', + $link, + "", + "", + $buttonTarget, + $active["info"] + ); + } + + include_once './Services/Tracking/classes/class.ilLearningProgressAccess.php'; + if (!$a_offline && + $ilAccess->checkAccess("read", "", $_GET["ref_id"]) && // #14075 + ilLearningProgressAccess::checkAccess($_GET["ref_id"])) { + include_once './Services/Object/classes/class.ilObjectLP.php'; + $olp = ilObjectLP::getInstance($this->object->getId()); + if ($olp->getCurrentMode() == ilLPObjSettings::LP_MODE_COLLECTION_MANUAL) { + $tabs_gui->$addcmd( + "learning_progress", + $this->ctrl->getLinkTargetByClass(array("illmpresentationgui", "illearningprogressgui"), "editManual"), + "", + "", + $buttonTarget, + $active["learning_progress"] + ); + } elseif ($olp->getCurrentMode() == ilLPObjSettings::LP_MODE_COLLECTION_TLT) { + $tabs_gui->$addcmd( + "learning_progress", + $this->ctrl->getLinkTargetByClass(array("illmpresentationgui", "illearningprogressgui"), "showtlt"), + "", + "", + $buttonTarget, + $active["learning_progress"] + ); + } + } + + // get user defined menu entries + $this->__initLMMenuEditor(); + $entries = $this->lmme_obj->getMenuEntries(true); + if (count($entries) > 0 && $ilAccess->checkAccess("read", "", $_GET["ref_id"])) { + foreach ($entries as $entry) { + // build goto-link for internal resources + if ($entry["type"] == "intern") { + $entry["link"] = ILIAS_HTTP_PATH . "/goto.php?target=" . $entry["link"]; + } + + // add http:// prefix if not exist + if (!strstr($entry["link"], '://') && !strstr($entry["link"], 'mailto:')) { + $entry["link"] = "http://" . $entry["link"]; + } + + if (!strstr($entry["link"], 'mailto:')) { + $entry["link"] = ilUtil::appendUrlParameterString($entry["link"], "ref_id=" . $this->ref_id . "&structure_id=" . $this->obj_id); + } + $tabs_gui->$addcmd( + $entry["title"], + $entry["link"], + "", + "", + "_blank", + "", + true + ); + } + } + + // edit learning module + if (!$a_offline && $a_cur_page > 0) { + if ($rbacsystem->checkAccess("write", $_GET["ref_id"])) { + //$page_id = $this->getCurrentPageId(); + $page_id = $a_cur_page; + $tabs_gui->$addcmd( + "edit_page", + ILIAS_HTTP_PATH . "/ilias.php?baseClass=ilLMEditorGUI&ref_id=" . $_GET["ref_id"] . + "&obj_id=" . $page_id . "&to_page=1", + "", + "", + $buttonTarget, + $active["edit_page"] + ); + } + } + + // user interface hook [uihk] + $pl_names = $ilPluginAdmin->getActivePluginsForSlot(IL_COMP_SERVICE, "UIComponent", "uihk"); + $plugin_html = false; + foreach ($pl_names as $pl) { + $ui_plugin = ilPluginAdmin::getPluginObject(IL_COMP_SERVICE, "UIComponent", "uihk", $pl); + $gui_class = $ui_plugin->getUIClassInstance(); + $resp = $gui_class->modifyGUI( + "Modules/LearningModule", + "lm_menu_tabs", + array("lm_menu_tabs" => $tabs_gui) + ); + } + + return $tabs_gui->$getcmd(); + } + + /** + * export content object + */ + public function createPDF() + { + require_once("./Modules/LearningModule/classes/class.ilContObjectExport.php"); + $cont_exp = new ilContObjectExport($this->object, "pdf"); + $cont_exp->buildExportFile(); + $this->offlineList(); + } + + /** + * create html package + */ + public function exportHTML() + { + include_once("./Services/Object/classes/class.ilObjectTranslation.php"); + $ot = ilObjectTranslation::getInstance($this->object->getId()); + $lang = ""; + if ($ot->getContentActivated()) { + $format = explode("_", $_POST["format"]); + $lang = ilUtil::stripSlashes($format[1]); + } + require_once("./Modules/LearningModule/classes/class.ilContObjectExport.php"); + $cont_exp = new ilContObjectExport($this->object, "html", $lang); + $cont_exp->buildExportFile(); + } + + /** + * create scorm package + */ + public function exportSCORM() + { + require_once("./Modules/LearningModule/classes/class.ilContObjectExport.php"); + $cont_exp = new ilContObjectExport($this->object, "scorm"); + $cont_exp->buildExportFile(); + } + + /** + * display locator + * + * @param boolean $a_omit_obj_id set to true, if obj id is not page id (e.g. permission gui) + */ + public function addLocations($a_omit_obj_id = false) + { + $locator = $this->locator; + + if (!$a_omit_obj_id) { + $obj_id = $_GET["obj_id"]; + } + $lmtree = $this->object->getTree(); + + if (($obj_id != 0) && $lmtree->isInTree($obj_id)) { + $path = $lmtree->getPathFull($obj_id); + } else { + $path = $lmtree->getPathFull($lmtree->getRootId()); + if ($obj_id != 0) { + $path[] = array("type" => "pg", "child" => $this->obj_id, + "title" => ilLMPageObject::_getPresentationTitle($this->obj_id)); + } + } + + foreach ($path as $key => $row) { + if ($row["child"] == 1) { + $this->ctrl->setParameter($this, "obj_id", ""); + $locator->addItem($this->object->getTitle(), $this->ctrl->getLinkTarget($this, "chapters")); + } else { + $title = $row["title"]; + switch ($row["type"]) { + case "st": + $this->ctrl->setParameterByClass("ilstructureobjectgui", "obj_id", $row["child"]); + $locator->addItem($title, $this->ctrl->getLinkTargetByClass("ilstructureobjectgui", "view")); + break; + + case "pg": + $this->ctrl->setParameterByClass("illmpageobjectgui", "obj_id", $row["child"]); + $locator->addItem($title, $this->ctrl->getLinkTargetByClass("illmpageobjectgui", "edit")); + break; + } + } + } + if (!$a_omit_obj_id) { + $this->ctrl->setParameter($this, "obj_id", $_GET["obj_id"]); + } + } + + //// + //// Questions + //// + + + /** + * List questions + */ + public function listQuestions() + { + $tpl = $this->tpl; + + $this->setTabs("questions"); + $this->setQuestionsSubTabs("question_stats"); + + include_once("./Modules/LearningModule/classes/class.ilLMQuestionListTableGUI.php"); + $table = new ilLMQuestionListTableGUI($this, "listQuestions", $this->object); + $tpl->setContent($table->getHTML()); + } + + /** + * List blocked users + */ + public function listBlockedUsers() + { + $tpl = $this->tpl; + + $this->setTabs("questions"); + $this->setQuestionsSubTabs("blocked_users"); + + include_once("./Modules/LearningModule/classes/class.ilLMBlockedUsersTableGUI.php"); + $table = new ilLMBlockedUsersTableGUI($this, "listBlockedUsers", $this->object); + $tpl->setContent($table->getHTML()); + } + + /** + * Reset number of tries + */ + public function resetNumberOfTries() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("./Services/COPage/classes/class.ilPageQuestionProcessor.php"); + if (is_array($_POST["userquest_id"])) { + foreach ($_POST["userquest_id"] as $uqid) { + $uqid = explode(":", $uqid); + ilPageQuestionProcessor::resetTries((int) $uqid[0], (int) $uqid[1]); + } + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + } + $ilCtrl->redirect($this, "listBlockedUsers"); + } + + /** + * Unlock blocked question + */ + public function unlockQuestion() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("./Services/COPage/classes/class.ilPageQuestionProcessor.php"); + if (is_array($_POST["userquest_id"])) { + foreach ($_POST["userquest_id"] as $uqid) { + $uqid = explode(":", $uqid); + ilPageQuestionProcessor::unlock((int) $uqid[0], (int) $uqid[1]); + } + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + } + $ilCtrl->redirect($this, "listBlockedUsers"); + } + + /** + * Send Mail to blocked users + */ + public function sendMailToBlockedUsers() + { + $ilCtrl = $this->ctrl; + + if (!is_array($_POST["userquest_id"])) { + ilUtil::sendFailure($this->lng->txt("no_checkbox"), 1); + $ilCtrl->redirect($this, "listBlockedUsers"); + } + + $rcps = array(); + foreach ($_POST["userquest_id"] as $uqid) { + $uqid = explode(":", $uqid); + $login = ilObjUser::_lookupLogin($uqid[1]); + if (!in_array($login, $rcps)) { + $rcps[] = $login; + } + } + require_once 'Services/Mail/classes/class.ilMailFormCall.php'; + ilUtil::redirect(ilMailFormCall::getRedirectTarget( + $this, + 'listBlockedUsers', + array(), + array( + 'type' => 'new', + 'rcp_to' => implode(',', $rcps), + 'sig' => $this->getBlockedUsersMailSignature() + ) + )); + } + + /** + * Get mail signature for blocked users + */ + protected function getBlockedUsersMailSignature() + { + $link = chr(13) . chr(10) . chr(13) . chr(10); + $link .= $this->lng->txt('cont_blocked_users_mail_link'); + $link .= chr(13) . chr(10) . chr(13) . chr(10); + include_once './Services/Link/classes/class.ilLink.php'; + $link .= ilLink::_getLink($this->object->getRefId()); + return rawurlencode(base64_encode($link)); + } + + + //// + //// Tabs + //// + + + /** + * output tabs + */ + public function setTabs($a_act = "") + { + $lng = $this->lng; + $ilHelp = $this->help; + + $ilHelp->setScreenIdComponent("lm"); + + $this->addTabs($a_act); + parent::setTitleAndDescription(); + $this->tpl->setTitle($this->object->getTitle()); + $this->tpl->setTitleIcon( + ilUtil::getImagePath("icon_lm.svg"), + $lng->txt("obj_lm") + ); + } + + /** + * Set pages tabs + * + * @param string $a_active active subtab + */ + public function setContentSubTabs($a_active) + { + $ilTabs = $this->tabs; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $lm_set = new ilSetting("lm"); + + // chapters + $ilTabs->addSubtab( + "chapters", + $lng->txt("cont_chapters"), + $ilCtrl->getLinkTarget($this, "chapters") + ); + + // all pages + $ilTabs->addSubtab( + "pages", + $lng->txt("cont_all_pages"), + $ilCtrl->getLinkTarget($this, "pages") + ); + + // all pages + $ilTabs->addSubtab( + "short_titles", + $lng->txt("cont_short_titles"), + $ilCtrl->getLinkTargetByClass("illmeditshorttitlesgui", "") + ); + + // export ids + if ($lm_set->get("html_export_ids")) { + if (!ilObjContentObject::isOnlineHelpModule($this->object->getRefId())) { + $ilTabs->addSubtab( + "export_ids", + $lng->txt("cont_html_export_ids"), + $ilCtrl->getLinkTarget($this, "showExportIDsOverview") + ); + } + } + if (ilObjContentObject::isOnlineHelpModule($this->object->getRefId())) { + $lng->loadLanguageModule("help"); + $ilTabs->addSubtab( + "export_ids", + $lng->txt("cont_online_help_ids"), + $ilCtrl->getLinkTarget($this, "showExportIDsOverview") + ); + + $ilTabs->addSubtab( + "help_tooltips", + $lng->txt("help_tooltips"), + $ilCtrl->getLinkTarget($this, "showTooltipList") + ); + } + + // list links + $ilTabs->addSubtab( + "internal_links", + $lng->txt("cont_internal_links"), + $ilCtrl->getLinkTarget($this, "listLinks") + ); + + // web link checker + $ilTabs->addSubtab( + "link_check", + $lng->txt("link_check"), + $ilCtrl->getLinkTarget($this, "linkChecker") + ); + + $ilTabs->addSubtab( + "history", + $lng->txt("history"), + $this->ctrl->getLinkTarget($this, "history") + ); + + // maintenance + $ilTabs->addSubtab( + "maintenance", + $lng->txt("cont_maintenance"), + $ilCtrl->getLinkTarget($this, "showMaintenance") + ); + + // srt files + $ilTabs->addSubtab( + "srt_files", + $lng->txt("cont_subtitle_files"), + $ilCtrl->getLinkTargetByClass("ilmobmultisrtuploadgui", "") + ); + + // srt files + $ilTabs->addSubtab( + "import", + $lng->txt("cont_import"), + $ilCtrl->getLinkTargetByClass("illmimportgui", "") + ); + + $ilTabs->activateSubTab($a_active); + $ilTabs->activateTab("content"); + } + + /** + * Set pages tabs + * + * @param string $a_active active subtab + */ + public function setQuestionsSubTabs($a_active) + { + $ilTabs = $this->tabs; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + // chapters + $ilTabs->addSubtab( + "question_stats", + $lng->txt("cont_question_stats"), + $ilCtrl->getLinkTarget($this, "listQuestions") + ); + + // blocked users + $ilTabs->addSubtab( + "blocked_users", + $lng->txt("cont_blocked_users"), + $ilCtrl->getLinkTarget($this, "listBlockedUsers") + ); + + $ilTabs->activateSubTab($a_active); + } + + /** + * Adds tabs + */ + public function addTabs($a_act = "") + { + $rbacsystem = $this->rbacsystem; + $ilTabs = $this->tabs; + $lng = $this->lng; + + // content + $ilTabs->addTab( + "content", + $lng->txt("content"), + $this->ctrl->getLinkTarget($this, "chapters") + ); + + // info + $ilTabs->addTab( + "info", + $lng->txt("info_short"), + $this->ctrl->getLinkTargetByClass("ilinfoscreengui", 'showSummary') + ); + + // settings + $ilTabs->addTab( + "settings", + $lng->txt("settings"), + $this->ctrl->getLinkTarget($this, 'properties') + ); + + // questions + $ilTabs->addTab( + "questions", + $lng->txt("objs_qst"), + $this->ctrl->getLinkTarget($this, "listQuestions") + ); + + // learning progress + include_once './Services/Tracking/classes/class.ilLearningProgressAccess.php'; + if (ilLearningProgressAccess::checkAccess($this->object->getRefId()) and ($this->object->getType() == 'lm')) { + $ilTabs->addTab( + 'learning_progress', + $lng->txt("learning_progress"), + $this->ctrl->getLinkTargetByClass(array('illearningprogressgui'), '') + ); + } + + if ($this->object->getType() != "lm") { + // bibliographical data + $ilTabs->addTab( + "bib_data", + $lng->txt("bib_data"), + $this->ctrl->getLinkTarget($this, "editBibItem") + ); + } + + // meta data + include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php"; + $mdgui = new ilObjectMetaDataGUI($this->object); + $mdtab = $mdgui->getTab(); + if ($mdtab) { + $ilTabs->addTab( + "meta", + $lng->txt("meta_data"), + $mdtab + ); + } + + if ($this->object->getType() == "lm") { + // export + $ilTabs->addTab( + "export", + $lng->txt("export"), + $this->ctrl->getLinkTargetByClass("ilexportgui", "") + ); + } + + // permissions + if ($rbacsystem->checkAccess('edit_permission', $this->object->getRefId())) { + $ilTabs->addTab( + "perm", + $lng->txt("perm_settings"), + $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm") + ); + } + + if ($a_act != "") { + $ilTabs->activateTab($a_act); + } + + // presentation view + $ilTabs->addNonTabbedLink( + "pres_mode", + $lng->txt("cont_presentation_view"), + "ilias.php?baseClass=ilLMPresentationGUI&ref_id=" . $this->object->getRefID(), + "_top" + ); + } + + /** + * Set sub tabs + */ + public function setSubTabs($a_active) + { + $ilTabs = $this->tabs; + $ilSetting = $this->settings; + + if (in_array( + $a_active, + array("settings", "cont_style", "cont_lm_menu", "public_section", + "cont_glossaries", "cont_multilinguality", "obj_multilinguality", + "lti_provider") + )) { + // general properties + $ilTabs->addSubTabTarget( + "settings", + $this->ctrl->getLinkTarget($this, 'properties'), + "", + "" + ); + + // style properties + $ilTabs->addSubTabTarget( + "cont_style", + $this->ctrl->getLinkTarget($this, 'editStyleProperties'), + "", + "" + ); + + // menu properties + $ilTabs->addSubTabTarget( + "cont_lm_menu", + $this->ctrl->getLinkTarget($this, 'editMenuProperties'), + "", + "" + ); + + // glossaries + $ilTabs->addSubTabTarget( + "cont_glossaries", + $this->ctrl->getLinkTarget($this, 'editGlossaries'), + "", + "" + ); + + if ($ilSetting->get("pub_section")) { + // public section + $ilTabs->addSubTabTarget( + "public_section", + $this->ctrl->getLinkTarget($this, 'editPublicSection'), + "", + "" + ); + } + + $ilTabs->addSubTabTarget( + "obj_multilinguality", + $this->ctrl->getLinkTargetByClass("ilobjecttranslationgui", "") + ); + + $lti_settings = new ilLTIProviderObjectSettingGUI($this->object->getRefId()); + if ($lti_settings->hasSettingsAccess()) { + $ilTabs->addSubTabTarget( + 'lti_provider', + $this->ctrl->getLinkTargetByClass(ilLTIProviderObjectSettingGUI::class) + ); + } + + $ilTabs->setSubTabActive($a_active); + } + } + + public function editPublicSection() + { + $ilTabs = $this->tabs; + $ilToolbar = $this->toolbar; + $ilAccess = $this->access; + + + if (!$ilAccess->checkAccessOfUser(ANONYMOUS_USER_ID, "read", "", $this->object->getRefId())) { + ilUtil::sendInfo($this->lng->txt("cont_anonymous_user_missing_perm")); + } + + $this->setTabs(); + $this->setSubTabs("public_section"); + $ilTabs->setTabActive("settings"); + + $this->tpl->addBlockFile( + "ADM_CONTENT", + "adm_content", + "tpl.lm_public_selector.html", + "Modules/LearningModule" + ); + + // get learning module object + $this->lm_obj = new ilObjLearningModule($this->ref_id, true); + + + // public mode + $modes = array("complete" => $this->lng->txt("all_pages"), "selected" => $this->lng->txt("selected_pages_only")); + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $si = new ilSelectInputGUI($this->lng->txt("choose_public_mode"), "lm_public_mode"); + $si->setOptions($modes); + $si->setValue($this->object->getPublicAccessMode()); + $ilToolbar->addInputItem($si, true); + $ilToolbar->addFormButton($this->lng->txt("save"), "savePublicSectionAccess"); + $ilToolbar->setFormAction($this->ctrl->getFormAction($this, "savePublicSectionAccess")); + + if ($this->object->getPublicAccessMode() == "selected") { + $this->tpl->setCurrentBlock("select_pages"); + $this->tpl->setVariable("FORMACTION", $this->ctrl->getLinkTarget($this, "savePublicSectionPages")); + + include_once("./Modules/LearningModule/classes/class.ilPublicSectionExplorerGUI.php"); + $tree = new ilPublicSectionExplorerGUI($this, "editPublicSection", $this->lm_obj); + $tree->setSelectMode("pages", true); + $tree->setSkipRootNode(true); + + $this->tpl->setVariable("EXPLORER", $tree->getHTML()); + $this->tpl->setVariable("TXT_SAVE", $this->lng->txt("save")); + + $this->tpl->parseCurrentBlock(); + } + } + + public function savePublicSection() + { + //var_dump($_POST["lm_public_mode"]);exit; + $this->object->setPublicAccessMode($_POST["lm_public_mode"]); + $this->object->updateProperties(); + ilLMObject::_writePublicAccessStatus($_POST["pages"], $this->object->getId()); + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "editPublicSection"); + } + + /** + * Saves lm access mode + */ + public function savePublicSectionAccess() + { + $this->object->setPublicAccessMode($_POST["lm_public_mode"]); + $this->object->updateProperties(); + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "editPublicSection"); + } + + /** + * Saves public lm pages + */ + public function savePublicSectionPages() + { + ilLMObject::_writePublicAccessStatus($_POST["pages"], $this->object->getId()); + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "editPublicSection"); + } + + /** + * history + * + * @access public + */ + public function history() + { + $this->setTabs("content"); + $this->setContentSubTabs("history"); + + require_once("./Services/History/classes/class.ilHistoryTableGUI.php"); + $hist_gui = new ilHistoryTableGUI( + $this, + "history", + $this->object->getId(), + $this->object->getType() + ); + $hist_gui->initTable(); + $hist_gui->setCommentVisibility($this->object->isActiveHistoryUserComments()); + + $this->tpl->setContent($hist_gui->getHTML()); + } + + /** + * + * @see ilLinkCheckerGUIRowHandling::formatInvalidLinkArray() + * @param array Unformatted array + * @return array Formatted array + * @access public + * + */ + public function formatInvalidLinkArray(array $row) + { + $row['title'] = ilLMPageObject::_getPresentationTitle($row['page_id'], $this->object->getPageHeader()); + + require_once 'Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php'; + $actions = new ilAdvancedSelectionListGUI(); + $actions->setSelectionHeaderClass('small'); + $actions->setItemLinkClass('xsmall'); + $actions->setListTitle($this->lng->txt('actions')); + $actions->setId($row['page_id']); + $this->ctrl->setParameterByClass('ilLMPageObjectGUI', 'obj_id', $row['page_id']); + $actions->addItem( + $this->lng->txt('edit'), + '', + $this->ctrl->getLinkTargetByClass('ilLMPageObjectGUI', 'edit') + ); + $this->ctrl->clearParametersByClass('ilLMPageObjectGUI'); + $row['action_html'] = $actions->getHTML(); + + return $row; + } + + public function linkChecker() + { + $ilUser = $this->user; + $tpl = $this->tpl; + + $this->__initLinkChecker(); + + $this->setTabs(); + $this->setContentSubTabs("link_check"); + + require_once './Services/LinkChecker/classes/class.ilLinkCheckerTableGUI.php'; + + $toolbar = new ilToolbarGUI(); + + // #13684 + include_once "Services/Cron/classes/class.ilCronManager.php"; + if (ilCronManager::isJobActive("lm_link_check")) { + include_once './Services/LinkChecker/classes/class.ilLinkCheckNotify.php'; + include_once 'Services/Form/classes/class.ilPropertyFormGUI.php'; + + $chb = new ilCheckboxInputGUI($this->lng->txt('link_check_message_a'), 'link_check_message'); + $chb->setValue(1); + $chb->setChecked((bool) ilLinkCheckNotify::_getNotifyStatus($ilUser->getId(), $this->object->getId())); + $chb->setOptionTitle($this->lng->txt('link_check_message_b')); + + $toolbar->addInputItem($chb); + $toolbar->addFormButton($this->lng->txt('save'), 'saveLinkCheck'); + $toolbar->setFormAction($this->ctrl->getLinkTarget($this, 'saveLinkCheck')); + } + + $tgui = new ilLinkCheckerTableGUI($this, 'linkChecker'); + $tgui->setLinkChecker($this->link_checker_obj) + ->setRowHandler($this) + ->setRefreshButton($this->lng->txt('refresh'), 'refreshLinkCheck'); + + return $tpl->setContent($tgui->prepareHTML()->getHTML() . $toolbar->getHTML()); + } + + public function saveLinkCheck() + { + $ilDB = $this->db; + $ilUser = $this->user; + + include_once './Services/LinkChecker/classes/class.ilLinkCheckNotify.php'; + + $link_check_notify = new ilLinkCheckNotify($ilDB); + $link_check_notify->setUserId($ilUser->getId()); + $link_check_notify->setObjId($this->object->getId()); + + if ($_POST['link_check_message']) { + ilUtil::sendSuccess($this->lng->txt('link_check_message_enabled')); + $link_check_notify->addNotifier(); + } else { + ilUtil::sendSuccess($this->lng->txt('link_check_message_disabled')); + $link_check_notify->deleteNotifier(); + } + $this->linkChecker(); + + return true; + } + + + + public function refreshLinkCheck() + { + $this->__initLinkChecker(); + $this->link_checker_obj->checkLinks(); + ilUtil::sendSuccess($this->lng->txt('link_checker_refreshed')); + + $this->linkChecker(); + + return true; + } + + public function __initLinkChecker() + { + $ilDB = $this->db; + + include_once './Services/LinkChecker/classes/class.ilLinkChecker.php'; + + $this->link_checker_obj = new ilLinkChecker($ilDB, false); + $this->link_checker_obj->setObjId($this->object->getId()); + + return true; + } + + public function __initLMMenuEditor() + { + include_once './Modules/LearningModule/classes/class.ilLMMenuEditor.php'; + + $this->lmme_obj = new ilLMMenuEditor(); + $this->lmme_obj->setObjId($this->object->getId()); + + return true; + } + + /** + * display add menu entry form + */ + public function addMenuEntry() + { + $ilTabs = $this->tabs; + $ilToolbar = $this->toolbar; + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + + $this->setTabs(); + + $ilTabs->setTabActive("settings"); + $this->setSubTabs("cont_lm_menu"); + + $ilToolbar->addButton( + $this->lng->txt("lm_menu_select_internal_object"), + $ilCtrl->getLinkTarget($this, "showEntrySelector") + ); + + $form = $this->initMenuEntryForm("create"); + $this->tpl->setContent($form->getHTML()); + } + + /** + * Init menu entry form. + * + * @param string $a_mode Edit Mode + */ + public function initMenuEntryForm($a_mode = "edit") + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + + // title + $ti = new ilTextInputGUI($this->lng->txt("lm_menu_entry_title"), "title"); + $ti->setMaxLength(255); + $ti->setSize(40); + $form->addItem($ti); + + // target + $ta = new ilTextInputGUI($this->lng->txt("lm_menu_entry_target"), "target"); + $ta->setMaxLength(255); + $ta->setSize(40); + $form->addItem($ta); + + if ($a_mode == "edit") { + $this->__initLMMenuEditor(); + $this->lmme_obj->readEntry($_REQUEST["menu_entry"]); + $ti->setValue($this->lmme_obj->getTitle()); + $ta->setValue($this->lmme_obj->getTarget()); + } + + if (isset($_GET["link_ref_id"])) { + $link_ref_id = (int) $_GET["link_ref_id"]; + $obj_type = ilObject::_lookupType($link_ref_id, true); + $obj_id = ilObject::_lookupObjectId($link_ref_id); + $title = ilObject::_lookupTitle($obj_id); + + $target_link = $obj_type . "_" . $link_ref_id; + $ti->setValue($title); + $ta->setValue($target_link); + + // link ref id + $hi = new ilHiddenInputGUI("link_ref_id"); + $hi->setValue($link_ref_id); + $form->addItem($hi); + } + + + // save and cancel commands + if ($a_mode == "create") { + $form->addCommandButton("saveMenuEntry", $lng->txt("save")); + $form->addCommandButton("editMenuProperties", $lng->txt("cancel")); + $form->setTitle($lng->txt("lm_menu_new_entry")); + } else { + $form->addCommandButton("updateMenuEntry", $lng->txt("save")); + $form->addCommandButton("editMenuProperties", $lng->txt("cancel")); + $form->setTitle($lng->txt("lm_menu_edit_entry")); + } + + $form->setFormAction($ilCtrl->getFormAction($this)); + + return $form; + } + + /** + * save new menu entry + */ + public function saveMenuEntry() + { + $ilCtrl = $this->ctrl; + + // check title and target + if (empty($_POST["title"])) { + ilUtil::sendFailure($this->lng->txt("please_enter_title"), true); + $ilCtrl->redirect($this, "addMenuEntry"); + } + if (empty($_POST["target"])) { + ilUtil::sendFailure($this->lng->txt("please_enter_target"), true); + $ilCtrl->redirect($this, "addMenuEntry"); + } + + $this->__initLMMenuEditor(); + $this->lmme_obj->setTitle($_POST["title"]); + $this->lmme_obj->setTarget($_POST["target"]); + $this->lmme_obj->setLinkRefId($_POST["link_ref_id"]); + + if ($_POST["link_ref_id"]) { + $this->lmme_obj->setLinkType("intern"); + } + + $this->lmme_obj->create(); + + ilUtil::sendSuccess($this->lng->txt("msg_entry_added"), true); + $this->ctrl->redirect($this, "editMenuProperties"); + } + + /** + * drop a menu entry + */ + public function deleteMenuEntry() + { + $ilErr = $this->error; + + if (empty($_GET["menu_entry"])) { + $ilErr->raiseError($this->lng->txt("no_menu_entry_id"), $ilErr->MESSAGE); + } + + $this->__initLMMenuEditor(); + $this->lmme_obj->delete($_GET["menu_entry"]); + + ilUtil::sendSuccess($this->lng->txt("msg_entry_removed"), true); + $this->ctrl->redirect($this, "editMenuProperties"); + } + + /** + * edit menu entry form + */ + public function editMenuEntry() + { + $ilToolbar = $this->toolbar; + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + $ilErr = $this->error; + + $this->setTabs(); + + $ilTabs->setTabActive("settings"); + $this->setSubTabs("cont_lm_menu"); + + + if (empty($_GET["menu_entry"])) { + $ilErr->raiseError($this->lng->txt("no_menu_entry_id"), $ilErr->MESSAGE); + } + + $ilCtrl->saveParameter($this, array("menu_entry")); + $ilToolbar->addButton( + $this->lng->txt("lm_menu_select_internal_object"), + $ilCtrl->getLinkTarget($this, "showEntrySelector") + ); + + $form = $this->initMenuEntryForm("edit"); + $this->tpl->setContent($form->getHTML()); + } + + /** + * update a menu entry + */ + public function updateMenuEntry() + { + $ilErr = $this->error; + + if (empty($_REQUEST["menu_entry"])) { + $ilErr->raiseError($this->lng->txt("no_menu_entry_id"), $ilErr->MESSAGE); + } + + // check title and target + if (empty($_POST["title"])) { + $ilErr->raiseError($this->lng->txt("please_enter_title"), $ilErr->MESSAGE); + } + if (empty($_POST["target"])) { + $ilErr->raiseError($this->lng->txt("please_enter_target"), $ilErr->MESSAGE); + } + + $this->__initLMMenuEditor(); + $this->lmme_obj->readEntry($_REQUEST["menu_entry"]); + $this->lmme_obj->setTitle($_POST["title"]); + $this->lmme_obj->setTarget($_POST["target"]); + if ($_POST["link_ref_id"]) { + $this->lmme_obj->setLinkType("intern"); + } + if (is_int(strpos($_POST["target"], "."))) { + $this->lmme_obj->setLinkType("extern"); + } + $this->lmme_obj->update(); + + ilUtil::sendSuccess($this->lng->txt("msg_entry_updated"), true); + $this->ctrl->redirect($this, "editMenuProperties"); + } + + public function showEntrySelector() + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + + $this->setTabs(); + + $ilTabs->setTabActive("settings"); + $this->setSubTabs("cont_lm_menu"); + + $ilCtrl->saveParameter($this, array("menu_entry")); + + $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.lm_menu_object_selector.html", "Modules/LearningModule"); + + ilUtil::sendInfo($this->lng->txt("lm_menu_select_object_to_add")); + + require_once("./Modules/LearningModule/classes/class.ilLMMenuObjectSelector.php"); + $exp = new ilLMMenuObjectSelector($this->ctrl->getLinkTarget($this, 'test'), $this); + + $exp->setExpand($_GET["lm_menu_expand"] ? $_GET["lm_menu_expand"] : $this->tree->readRootId()); + $exp->setExpandTarget($this->ctrl->getLinkTarget($this, 'showEntrySelector')); + $exp->setTargetGet("ref_id"); + $exp->setRefId($this->cur_ref_id); + + $sel_types = array('mcst', 'mep', 'cat', 'lm','glo','frm','exc','tst','svy', 'chat', 'wiki', 'sahs', + "crs", "grp", "book", "tst", "file"); + $exp->setSelectableTypes($sel_types); + + // build html-output + $exp->setOutput(0); + $output = $exp->getOutput(); + + // get page ids + foreach ($exp->format_options as $node) { + if (!$node["container"]) { + $pages[] = $node["child"]; + } + } + + // access mode selector + $this->tpl->setVariable("TXT_SET_PUBLIC_MODE", $this->lng->txt("set_public_mode")); + $this->tpl->setVariable("TXT_CHOOSE_PUBLIC_MODE", $this->lng->txt("choose_public_mode")); + $modes = array("complete" => $this->lng->txt("all_pages"), "selected" => $this->lng->txt("selected_pages_only")); + $select_public_mode = ilUtil::formSelect($this->object->getPublicAccessMode(), "lm_public_mode", $modes, false, true); + $this->tpl->setVariable("SELECT_PUBLIC_MODE", $select_public_mode); + + $this->tpl->setVariable("TXT_EXPLORER_HEADER", $this->lng->txt("choose_public_pages")); + $this->tpl->setVariable("EXP_REFRESH", $this->lng->txt("refresh")); + $this->tpl->setVariable("EXPLORER", $output); + $this->tpl->setVariable("ONCLICK", $js_pages); + $this->tpl->setVariable("TXT_CHECKALL", $this->lng->txt("check_all")); + $this->tpl->setVariable("TXT_UNCHECKALL", $this->lng->txt("uncheck_all")); + $this->tpl->setVariable("TXT_SAVE", $this->lng->txt("save")); + $this->tpl->setVariable("FORMACTION", $this->ctrl->getLinkTarget($this, "savePublicSection")); + } + + /** + * select page as header + */ + public function selectHeader() + { + $ilErr = $this->error; + + if (!isset($_POST["id"])) { + $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); + } + if (count($_POST["id"]) > 1) { + $ilErr->raiseError($this->lng->txt("cont_select_max_one_item"), $ilErr->MESSAGE); + } + if ($_POST["id"][0] != $this->object->getHeaderPage()) { + $this->object->setHeaderPage($_POST["id"][0]); + } else { + $this->object->setHeaderPage(0); + } + $this->object->updateProperties(); + $this->ctrl->redirect($this, "pages"); + } + + /** + * select page as footer + */ + public function selectFooter() + { + $ilErr = $this->error; + + if (!isset($_POST["id"])) { + $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); + } + if (count($_POST["id"]) > 1) { + $ilErr->raiseError($this->lng->txt("cont_select_max_one_item"), $ilErr->MESSAGE); + } + if ($_POST["id"][0] != $this->object->getFooterPage()) { + $this->object->setFooterPage($_POST["id"][0]); + } else { + $this->object->setFooterPage(0); + } + $this->object->updateProperties(); + $this->ctrl->redirect($this, "pages"); + } + + /** + * Save all titles of chapters/pages + */ + public function saveAllTitles() + { + $ilCtrl = $this->ctrl; + + ilLMObject::saveTitles($this->object, ilUtil::stripSlashesArray($_POST["title"]), $_GET["transl"]); + + ilUtil::sendSuccess($this->lng->txt("lm_save_titles"), true); + $ilCtrl->redirect($this, "chapters"); + } + + /** + * Insert (multiple) chapters at node + */ + public function insertChapter() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + include_once("./Modules/LearningModule/classes/class.ilChapterHierarchyFormGUI.php"); + + $num = ilChapterHierarchyFormGUI::getPostMulti(); + $node_id = ilChapterHierarchyFormGUI::getPostNodeId(); + + if (!ilChapterHierarchyFormGUI::getPostFirstChild()) { // insert after node id + $parent_id = $this->lm_tree->getParentId($node_id); + $target = $node_id; + } else { // insert as first child + $parent_id = $node_id; + $target = IL_FIRST_NODE; + } + + for ($i = 1; $i <= $num; $i++) { + $chap = new ilStructureObject($this->object); + $chap->setType("st"); + $chap->setTitle($lng->txt("cont_new_chap")); + $chap->setLMId($this->object->getId()); + $chap->create(); + ilLMObject::putInTree($chap, $parent_id, $target); + } + + $ilCtrl->redirect($this, "chapters"); + } + + /** + * Insert Chapter from clipboard + */ + public function insertChapterClip() + { + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + $ilLog = $this->log; + + include_once("./Modules/LearningModule/classes/class.ilChapterHierarchyFormGUI.php"); + + $node_id = ilChapterHierarchyFormGUI::getPostNodeId(); + $first_child = ilChapterHierarchyFormGUI::getPostFirstChild(); + + $ilLog->write("InsertChapterClip, num: $num, node_id: $node_id, " . + " getPostFirstChild " . ilChapterHierarchyFormGUI::getPostFirstChild()); + + if (!$first_child) { // insert after node id + $parent_id = $this->lm_tree->getParentId($node_id); + $target = $node_id; + } else { // insert as first child + $parent_id = $node_id; + $target = IL_FIRST_NODE; + } + + // copy and paste + $chapters = $ilUser->getClipboardObjects("st", true); + $copied_nodes = array(); + foreach ($chapters as $chap) { + $ilLog->write("Call pasteTree, Target LM: " . $this->object->getId() . ", Chapter ID: " . $chap["id"] + . ", Parent ID: " . $parent_id . ", Target: " . $target); + $cid = ilLMObject::pasteTree( + $this->object, + $chap["id"], + $parent_id, + $target, + $chap["insert_time"], + $copied_nodes, + (ilEditClipboard::getAction() == "copy") + ); + $target = $cid; + } + ilLMObject::updateInternalLinks($copied_nodes); + + if (ilEditClipboard::getAction() == "cut") { + $ilUser->clipboardDeleteObjectsOfType("pg"); + $ilUser->clipboardDeleteObjectsOfType("st"); + ilEditClipboard::clear(); + } + + $this->object->checkTree(); + $ilCtrl->redirect($this, "chapters"); + } + + /** + * redirect script + * + * @param string $a_target + */ + public static function _goto($a_target) + { + global $DIC; + + $ilAccess = $DIC->access(); + $ilErr = $DIC["ilErr"]; + $lng = $DIC->language(); + + if ($ilAccess->checkAccess("read", "", $a_target)) { + $_GET["baseClass"] = "ilLMPresentationGUI"; + $_GET["ref_id"] = $a_target; + $_GET["cmd"] = "resume"; + include("ilias.php"); + exit; + } elseif ($ilAccess->checkAccess("visible", "", $a_target)) { + $_GET["baseClass"] = "ilLMPresentationGUI"; + $_GET["ref_id"] = $a_target; + $_GET["cmd"] = "infoScreen"; + include("ilias.php"); + exit; + } elseif ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) { + ilUtil::sendFailure(sprintf( + $lng->txt("msg_no_perm_read_item"), + ilObject::_lookupTitle(ilObject::_lookupObjId($a_target)) + ), true); + ilObjectGUI::_gotoRepositoryRoot(); + } + + + $ilErr->raiseError($lng->txt("msg_no_perm_read_lm"), $ilErr->FATAL); + } + + /** + * Copy items to clipboard, then cut them from the current tree + */ + public function cutItems($a_return = "chapters") + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $items = ilUtil::stripSlashesArray($_POST["id"]); + if (!is_array($items)) { + ilUtil::sendFailure($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, $a_return); + } + + $todel = array(); // delete IDs < 0 (needed for non-js editing) + foreach ($items as $k => $item) { + if ($item < 0) { + $todel[] = $k; + } + } + foreach ($todel as $k) { + unset($items[$k]); + } + ilLMObject::clipboardCut($this->object->getId(), $items); + ilEditClipboard::setAction("cut"); + ilUtil::sendInfo($lng->txt("cont_selected_items_have_been_cut"), true); + + $ilCtrl->redirect($this, $a_return); + } + + /** + * Copy items to clipboard + */ + public function copyItems() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $items = ilUtil::stripSlashesArray($_POST["id"]); + if (!is_array($items)) { + ilUtil::sendFailure($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "chapters"); + } + + $todel = array(); // delete IDs < 0 (needed for non-js editing) + foreach ($items as $k => $item) { + if ($item < 0) { + $todel[] = $k; + } + } + foreach ($todel as $k) { + unset($items[$k]); + } + ilLMObject::clipboardCopy($this->object->getId(), $items); + ilEditClipboard::setAction("copy"); + ilUtil::sendInfo($lng->txt("cont_selected_items_have_been_copied"), true); + $ilCtrl->redirect($this, "chapters"); + } + + /** + * Cut chapter(s) + */ + public function cutChapter() + { + $this->cutItems("chapters"); + } + + //// + //// HTML export IDs + //// + + /** + * Show export IDs overview + * + * @param + * @return + */ + public function showExportIDsOverview($a_validation = false) + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $this->setTabs(); + $this->setContentSubTabs("export_ids"); + + if (ilObjContentObject::isOnlineHelpModule($this->object->getRefId())) { + // toolbar + $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $lm_tree = $this->object->getTree(); + $childs = $lm_tree->getChilds($lm_tree->readRootId()); + $options = array("" => $lng->txt("all")); + foreach ($childs as $c) { + $options[$c["child"]] = $c["title"]; + } + $si = new ilSelectInputGUI($this->lng->txt("help_component"), "help_chap"); + $si->setOptions($options); + $si->setValue(ilSession::get("help_chap")); + $ilToolbar->addInputItem($si, true); + $ilToolbar->addFormButton($lng->txt("help_filter"), "filterHelpChapters"); + + include_once("./Modules/LearningModule/classes/class.ilHelpMappingTableGUI.php"); + $tbl = new ilHelpMappingTableGUI($this, "showExportIDsOverview", $a_validation, false); + } else { + include_once("./Modules/LearningModule/classes/class.ilExportIDTableGUI.php"); + $tbl = new ilExportIDTableGUI($this, "showExportIDsOverview", $a_validation, false); + } + + $tpl->setContent($tbl->getHTML()); + } + + /** + * Filter help chapters + * + * @param + * @return + */ + public function filterHelpChapters() + { + $ilCtrl = $this->ctrl; + + ilSession::set("help_chap", ilUtil::stripSlashes($_POST["help_chap"])); + $ilCtrl->redirect($this, "showExportIDsOverview"); + } + + + /** + * Save export IDs + */ + public function saveExportIds() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + // check all export ids + $ok = true; + if (is_array($_POST["exportid"])) { + foreach ($_POST["exportid"] as $pg_id => $exp_id) { + if ($exp_id != "" && !preg_match( + "/^([a-zA-Z]+)[0-9a-zA-Z_]*$/", + trim($exp_id) + )) { + $ok = false; + } + } + } + if (!$ok) { + ilUtil::sendFailure($lng->txt("cont_exp_ids_not_resp_format1") . ": a-z, A-Z, 0-9, '_'. " . + $lng->txt("cont_exp_ids_not_resp_format3") . " " . + $lng->txt("cont_exp_ids_not_resp_format2")); + $this->showExportIDsOverview(true); + return; + } + + + if (is_array($_POST["exportid"])) { + foreach ($_POST["exportid"] as $pg_id => $exp_id) { + ilLMPageObject::saveExportId( + $this->object->getId(), + $pg_id, + ilUtil::stripSlashes($exp_id), + ilLMObject::_lookupType($pg_id) + ); + } + } + + ilUtil::sendSuccess($lng->txt("cont_saved_export_ids"), true); + $ilCtrl->redirect($this, "showExportIdsOverview"); + } + + /** + * Save help mapping + * + * @param + * @return + */ + public function saveHelpMapping() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("./Services/Help/classes/class.ilHelpMapping.php"); + if (is_array($_POST["screen_ids"])) { + foreach ($_POST["screen_ids"] as $chap => $ids) { + $ids = explode("\n", $ids); + ilHelpMapping::saveScreenIdsForChapter($chap, $ids); + } + } + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "showExportIdsOverview"); + } + + //// + //// Help tooltips + //// + + /** + * Show export IDs overview + * + * @param + * @return + */ + public function showTooltipList() + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->setTabs(); + $this->setContentSubTabs("help_tooltips"); + + $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); + include_once("./Services/Form/classes/class.ilTextInputGUI.php"); + $ti = new ilTextInputGUI($this->lng->txt("help_tooltip_id"), "tooltip_id"); + $ti->setMaxLength(200); + $ti->setSize(20); + $ilToolbar->addInputItem($ti, true); + $ilToolbar->addFormButton($lng->txt("add"), "addTooltip"); + $ilToolbar->addSeparator(); + + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $options = ilHelp::getTooltipComponents(); + if (ilSession::get("help_tt_comp") != "") { + $options[ilSession::get("help_tt_comp")] = ilSession::get("help_tt_comp"); + } + $si = new ilSelectInputGUI($this->lng->txt("help_component"), "help_tt_comp"); + $si->setOptions($options); + $si->setValue(ilSession::get("help_tt_comp")); + $ilToolbar->addInputItem($si, true); + $ilToolbar->addFormButton($lng->txt("help_filter"), "filterTooltips"); + + include_once("./Modules/LearningModule/classes/class.ilHelpTooltipTableGUI.php"); + $tbl = new ilHelpTooltipTableGUI($this, "showTooltipList", ilSession::get("help_tt_comp")); + + $tpl->setContent($tbl->getHTML()); + } + + /** + * Add tooltip + * + * @param + * @return + */ + public function addTooltip() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $tt_id = ilUtil::stripSlashes($_POST["tooltip_id"]); + if (trim($tt_id) != "") { + if (is_int(strpos($tt_id, "_"))) { + include_once("./Services/Help/classes/class.ilHelp.php"); + ilHelp::addTooltip(trim($tt_id), ""); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + + $fu = strpos($tt_id, "_"); + $comp = substr($tt_id, 0, $fu); + ilSession::set("help_tt_comp", ilUtil::stripSlashes($comp)); + } else { + ilUtil::sendFailure($lng->txt("cont_help_no_valid_tooltip_id"), true); + } + } + $ilCtrl->redirect($this, "showTooltipList"); + } + + /** + * Filter tooltips + * + * @param + * @return + */ + public function filterTooltips() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + ilSession::set("help_tt_comp", ilUtil::stripSlashes($_POST["help_tt_comp"])); + $ilCtrl->redirect($this, "showTooltipList"); + } + + + /** + * Save tooltips + * + * @param + * @return + */ + public function saveTooltips() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + include_once("./Services/Help/classes/class.ilHelp.php"); + + if (is_array($_POST["text"])) { + foreach ($_POST["text"] as $id => $text) { + ilHelp::updateTooltip( + (int) $id, + ilUtil::stripSlashes($text), + ilUtil::stripSlashes($_POST["tt_id"][(int) $id]) + ); + } + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + } + $ilCtrl->redirect($this, "showTooltipList"); + } + + /** + * Delete tooltips + */ + public function deleteTooltips() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if (is_array($_POST["id"])) { + include_once("./Services/Help/classes/class.ilHelp.php"); + foreach ($_POST["id"] as $id) { + ilHelp::deleteTooltip((int) $id); + } + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + } + $ilCtrl->redirect($this, "showTooltipList"); + } + + //// + //// Set layout + //// + + /** + * Get layout option + * + * @return object layout form option + */ + public static function getLayoutOption($a_txt, $a_var, $a_def_option = "") + { + global $DIC; + + $lng = $DIC->language(); + + // default layout + $layout = new ilRadioGroupInputGUI($a_txt, $a_var); + if ($a_def_option != "") { + if (is_file($im = ilUtil::getImagePath("layout_" . $a_def_option . ".png"))) { + $im_tag = ilUtil::img($im, $a_def_option); + } + $layout->addOption(new ilRadioOption("
" . $im_tag . "" . + $lng->txt("cont_lm_default_layout") . + ": " . $lng->txt("cont_layout_" . $a_def_option) . + "
", "")); + } + foreach (ilObjContentObject::getAvailableLayouts() as $l) { + $im_tag = ""; + if (is_file($im = ilUtil::getImagePath("layout_" . $l . ".png"))) { + $im_tag = ilUtil::img($im, $l); + } + $layout->addOption(new ilRadioOption("
" . + $im_tag . "" . $lng->txt("cont_layout_" . $l) . ": " . + $lng->txt("cont_layout_" . $l . "_desc") . "
", $l)); + } + + return $layout; + } + + /** + * Set layout for multipl pages + */ + public function setPageLayoutInHierarchy() + { + $ilCtrl = $this->ctrl; + $ilCtrl->setParameter($this, "hierarchy", "1"); + $this->setPageLayout(true); + } + + + /** + * Set layout for multipl pages + */ + public function setPageLayout($a_in_hierarchy = false) + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if (!is_array($_POST["id"])) { + ilUtil::sendFailure($lng->txt("no_checkbox"), true); + + if ($a_in_hierarchy) { + $ilCtrl->redirect($this, "chapters"); + } else { + $ilCtrl->redirect($this, "pages"); + } + } + + $this->initSetPageLayoutForm(); + + $tpl->setContent($this->form->getHTML()); + } + + /** + * Init set page layout form. + */ + public function initSetPageLayoutForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + if (is_array($_POST["id"])) { + foreach ($_POST["id"] as $id) { + $hi = new ilHiddenInputGUI("id[]"); + $hi->setValue($id); + $this->form->addItem($hi); + } + } + $layout = self::getLayoutOption( + $lng->txt("cont_layout"), + "layout", + $this->object->getLayout() + ); + $this->form->addItem($layout); + + $this->form->addCommandButton("savePageLayout", $lng->txt("save")); + $this->form->addCommandButton("pages", $lng->txt("cancel")); + + $this->form->setTitle($lng->txt("cont_set_layout")); + $this->form->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * Save page layout + */ + public function savePageLayout() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameter($this, "hierarchy", $_GET["hierarchy"]); + + foreach ($_POST["id"] as $id) { + ilLMPageObject::writeLayout( + ilUtil::stripSlashes($id), + ilUtil::stripSlashes($_POST["layout"]), + $this->object + ); + } + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + + if ($_GET["hierarchy"] == 1) { + $ilCtrl->redirect($this, "chapters"); + } else { + $ilCtrl->redirect($this, "pages"); + } + } + + // + // Auto glossaries + // + + /** + * Edit automatically linked glossaries + * + * @param + * @return + */ + public function editGlossaries() + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + $this->setTabs(); + $ilTabs->setTabActive("settings"); + $this->setSubTabs("cont_glossaries"); + + $ilToolbar->addButton( + $lng->txt("add"), + $ilCtrl->getLinkTarget($this, "showLMGlossarySelector") + ); + + include_once("./Modules/LearningModule/classes/class.ilLMGlossaryTableGUI.php"); + $tab = new ilLMGlossaryTableGUI($this->object, $this, "editGlossaries"); + + $tpl->setContent($tab->getHTML()); + } + + /** + * Select LM Glossary + * + * @param + * @return + */ + public function showLMGlossarySelector() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $tree = $this->tree; + $ilUser = $this->user; + $ilTabs = $this->tabs; + + $this->setTabs(); + $ilTabs->setTabActive("settings"); + $this->setSubTabs("cont_glossaries"); + + include_once 'Services/Search/classes/class.ilSearchRootSelector.php'; + + $exp = new ilSearchRootSelector($ilCtrl->getLinkTarget($this, 'showLMGlossarySelector')); + $exp->setExpand($_GET["search_root_expand"] ? $_GET["search_root_expand"] : $tree->readRootId()); + $exp->setExpandTarget($ilCtrl->getLinkTarget($this, 'showLMGlossarySelector')); + $exp->setTargetClass(get_class($this)); + $exp->setCmd('confirmGlossarySelection'); + $exp->setClickableTypes(array("glo")); + $exp->addFilter("glo"); + + // build html-output + $exp->setOutput(0); + $tpl->setContent($exp->getOutput()); + } + + /** + * Confirm glossary selection + */ + public function confirmGlossarySelection() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $ilCtrl->setParameter($this, "glo_ref_id", $_GET["root_id"]); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("cont_link_glo_in_lm")); + $cgui->setCancel($lng->txt("no"), "selectLMGlossary"); + $cgui->setConfirm($lng->txt("yes"), "selectLMGlossaryLink"); + $tpl->setContent($cgui->getHTML()); + } + + /** + * Select a glossary and link all its terms + * + * @param + * @return + */ + public function selectLMGlossaryLink() + { + $glo_ref_id = (int) $_GET["glo_ref_id"]; + $glo_id = ilObject::_lookupObjId($glo_ref_id); + $this->object->autoLinkGlossaryTerms($glo_ref_id); + $this->selectLMGlossary(); + } + + + /** + * Select lm glossary + * + * @param + * @return + */ + public function selectLMGlossary() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $glos = $this->object->getAutoGlossaries(); + $glo_ref_id = (int) $_GET["glo_ref_id"]; + $glo_id = ilObject::_lookupObjId($glo_ref_id); + if (!in_array($glo_id, $glos)) { + $glos[] = $glo_id; + } + $this->object->setAutoGlossaries($glos); + $this->object->update(); + + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "editGlossaries"); + } + + /** + * Remove lm glossary + * + * @param + * @return + */ + public function removeLMGlossary() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->object->removeAutoGlossary((int) $_GET["glo_id"]); + $this->object->update(); + + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "editGlossaries"); + } + + /** + * Edit master language + * + * @param + * @return + */ + public function editMasterLanguage() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameter($this, "transl", ""); + if ($_GET["lang_switch_mode"] == "short_titles") { + $ilCtrl->redirectByClass("illmeditshorttitlesgui", ""); + } + $ilCtrl->redirect($this, "chapters"); + } + + /** + * Switch to language + * + * @param + * @return + */ + public function switchToLanguage() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameter($this, "transl", $_GET["totransl"]); + if ($_GET["lang_switch_mode"] == "short_titles") { + $ilCtrl->redirectByClass("illmeditshorttitlesgui", ""); + } + $ilCtrl->redirect($this, "chapters"); + } + + public function redrawHeaderAction() + { + // #12281 + return parent::redrawHeaderActionObject(); + } } -?> diff --git a/Modules/LearningModule/classes/class.ilObjLearningModule.php b/Modules/LearningModule/classes/class.ilObjLearningModule.php index 1c1d87e4453d130293ae26d8930723b42d0673a0..60b97cff7357b78a2a008dac7b5dd60f069f34de 100755 --- a/Modules/LearningModule/classes/class.ilObjLearningModule.php +++ b/Modules/LearningModule/classes/class.ilObjLearningModule.php @@ -15,16 +15,13 @@ require_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); class ilObjLearningModule extends ilObjContentObject { - /** - * Constructor - * @access public - */ - function __construct($a_id = 0,$a_call_by_reference = true) - { - $this->type = "lm"; - parent::__construct($a_id, $a_call_by_reference); - } - + /** + * Constructor + * @access public + */ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + $this->type = "lm"; + parent::__construct($a_id, $a_call_by_reference); + } } - -?> diff --git a/Modules/LearningModule/classes/class.ilObjLearningModuleAccess.php b/Modules/LearningModule/classes/class.ilObjLearningModuleAccess.php index 8e09a9707472518bc6532bc7ee8fd1f8e8bc524f..f78e82bf8c9481395b5cb2ac03c07244cb2599d9 100644 --- a/Modules/LearningModule/classes/class.ilObjLearningModuleAccess.php +++ b/Modules/LearningModule/classes/class.ilObjLearningModuleAccess.php @@ -16,118 +16,114 @@ require_once('./Services/Object/classes/class.ilObject2.php'); * * @ingroup ModulesIliasLearningModule */ -class ilObjLearningModuleAccess extends ilObjContentObjectAccess implements ilConditionHandling, ilWACCheckingClass { - - /** - * Constructor - */ - function __construct() - { - global $DIC; - parent::__construct(); - - $this->access = $DIC->access(); - } - - - static protected $lm_set = null; - - /** - * Get possible conditions operators - */ - public static function getConditionOperators() { - // currently only one mode "ilConditionHandler::OPERATOR_LP" - // which is automatically added by condition handling, if lp is activated - return array(); - } - - - /** - * check condition - * - * @param type $a_svy_id - * @param type $a_operator - * @param type $a_value - * @param type $a_usr_id - * - * @return boolean - */ - public static function checkCondition($a_trigger_obj_id, $a_operator, $a_value, $a_usr_id) { - return true; - } - - - /** - * @param $a_set - * @return mixed - */ - static function _lookupSetting($a_set) - { - if (!is_array(self::$lm_set)) - { - $lm_set = new ilSetting("lm"); - self::$lm_set = $lm_set->getAll(); - } - - return self::$lm_set[$a_set]; - } - - /** - * 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() - { - if (self::_lookupSetting("lm_starting_point") == "first") - { - $commands = array - ( - array("permission" => "read", "cmd" => "view", "lang_var" => "show", - "default" => true), - array("permission" => "read", "cmd" => "continue", "lang_var" => "continue_work") - ); - } - else - { - $commands = array - ( - array("permission" => "read", "cmd" => "continue", "lang_var" => "continue_work", "default" => true) - ); - } - $commands[] = array("permission" => "write", "cmd" => "edit", "lang_var" => "edit_content"); - $commands[] = array("permission" => "write", "cmd" => "properties", "lang_var" => "settings"); - - return $commands; - } - - - /** - * @param ilWACPath $ilWACPath - * - * @return bool - */ - public function canBeDelivered(ilWACPath $ilWACPath) { - $ilAccess = $this->access; - /** - * @var $ilAccess ilAccessHandler - */ - preg_match("/lm_data\\/lm_([0-9]*)\\//ui", $ilWACPath->getPath(), $results); - foreach (ilObject2::_getAllReferences($results[1]) as $ref_id) { - if ($ilAccess->checkAccess('read', '', $ref_id)) { - return true; - } - } - - return false; - } +class ilObjLearningModuleAccess extends ilObjContentObjectAccess implements ilConditionHandling, ilWACCheckingClass +{ + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + parent::__construct(); + + $this->access = $DIC->access(); + } + + + protected static $lm_set = null; + + /** + * Get possible conditions operators + */ + public static function getConditionOperators() + { + // currently only one mode "ilConditionHandler::OPERATOR_LP" + // which is automatically added by condition handling, if lp is activated + return array(); + } + + + /** + * check condition + * + * @param type $a_svy_id + * @param type $a_operator + * @param type $a_value + * @param type $a_usr_id + * + * @return boolean + */ + public static function checkCondition($a_trigger_obj_id, $a_operator, $a_value, $a_usr_id) + { + return true; + } + + + /** + * @param $a_set + * @return mixed + */ + public static function _lookupSetting($a_set) + { + if (!is_array(self::$lm_set)) { + $lm_set = new ilSetting("lm"); + self::$lm_set = $lm_set->getAll(); + } + + return self::$lm_set[$a_set]; + } + + /** + * 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() + { + if (self::_lookupSetting("lm_starting_point") == "first") { + $commands = array( + array("permission" => "read", "cmd" => "view", "lang_var" => "show", + "default" => true), + array("permission" => "read", "cmd" => "continue", "lang_var" => "continue_work") + ); + } else { + $commands = array( + array("permission" => "read", "cmd" => "continue", "lang_var" => "continue_work", "default" => true) + ); + } + $commands[] = array("permission" => "write", "cmd" => "edit", "lang_var" => "edit_content"); + $commands[] = array("permission" => "write", "cmd" => "properties", "lang_var" => "settings"); + + return $commands; + } + + + /** + * @param ilWACPath $ilWACPath + * + * @return bool + */ + public function canBeDelivered(ilWACPath $ilWACPath) + { + $ilAccess = $this->access; + /** + * @var $ilAccess ilAccessHandler + */ + preg_match("/lm_data\\/lm_([0-9]*)\\//ui", $ilWACPath->getPath(), $results); + foreach (ilObject2::_getAllReferences($results[1]) as $ref_id) { + if ($ilAccess->checkAccess('read', '', $ref_id)) { + return true; + } + } + + return false; + } } - -?> diff --git a/Modules/LearningModule/classes/class.ilObjLearningModuleGUI.php b/Modules/LearningModule/classes/class.ilObjLearningModuleGUI.php index f67526f1fe14c834bfa27641932190812446913c..6111f01e8bb1f57810d29a77a543ad32888be18c 100755 --- a/Modules/LearningModule/classes/class.ilObjLearningModuleGUI.php +++ b/Modules/LearningModule/classes/class.ilObjLearningModuleGUI.php @@ -19,57 +19,50 @@ require_once("./Modules/LearningModule/classes/class.ilObjContentObjectGUI.php") */ class ilObjLearningModuleGUI extends ilObjContentObjectGUI { - var $object; - /** - * Constructor - * @access public - */ - function __construct($a_data,$a_id = 0,$a_call_by_reference = true, $a_prepare_output = true) - { - $this->type = "lm"; + public $object; + /** + * Constructor + * @access public + */ + public function __construct($a_data, $a_id = 0, $a_call_by_reference = true, $a_prepare_output = true) + { + $this->type = "lm"; - parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); + parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); - # BETTER DO IT HERE THAN IN PARENT CLASS ( PROBLEMS FOR import, create) - $this->assignObject(); + # BETTER DO IT HERE THAN IN PARENT CLASS ( PROBLEMS FOR import, create) + $this->assignObject(); - // SAME REASON - if($a_id != 0) - { - $this->lm_tree = $this->object->getLMTree(); - } - } + // SAME REASON + if ($a_id != 0) { + $this->lm_tree = $this->object->getLMTree(); + } + } - function assignObject() - { - include_once("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); + public function assignObject() + { + include_once("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); - $this->link_params = "ref_id=".$this->ref_id; - $this->object = new ilObjLearningModule($this->id, true); - } + $this->link_params = "ref_id=" . $this->ref_id; + $this->object = new ilObjLearningModule($this->id, true); + } - /* - function setLearningModuleObject(&$a_lm_obj) - { - $this->lm_obj =& $a_lm_obj; - //$this->obj =& $this->lm_obj; - }*/ + /* + function setLearningModuleObject(&$a_lm_obj) + { + $this->lm_obj =& $a_lm_obj; + //$this->obj =& $this->lm_obj; + }*/ - // MOVED ALL *style METHODS TO base class - - function view() - { - if (strtolower($_GET["baseClass"]) == "iladministrationgui") - { - $this->prepareOutput(); - parent::viewObject(); - } - else - { - $this->properties(); - } - } + // MOVED ALL *style METHODS TO base class + public function view() + { + if (strtolower($_GET["baseClass"]) == "iladministrationgui") { + $this->prepareOutput(); + parent::viewObject(); + } else { + $this->properties(); + } + } } - -?> diff --git a/Modules/LearningModule/classes/class.ilObjLearningModuleListGUI.php b/Modules/LearningModule/classes/class.ilObjLearningModuleListGUI.php index cc2a926a60676713c2bf304de8446ff76899ded3..c38167cba3c69036110bc02b6297a87046bda07b 100644 --- a/Modules/LearningModule/classes/class.ilObjLearningModuleListGUI.php +++ b/Modules/LearningModule/classes/class.ilObjLearningModuleListGUI.php @@ -14,167 +14,160 @@ include_once "Services/Object/classes/class.ilObjectListGUI.php"; */ class ilObjLearningModuleListGUI extends ilObjectListGUI { - /** - * initialisation - * - * this method should be overwritten by derived classes - */ - function init() - { - $this->static_link_enabled = true; - $this->delete_enabled = true; - $this->cut_enabled = true; - $this->copy_enabled = true; - $this->subscribe_enabled = true; - $this->link_enabled = true; - $this->info_screen_enabled = true; - $this->type = "lm"; - $this->gui_class_name = "ilobjlearningmodulegui"; - - // general commands array - include_once('./Modules/LearningModule/classes/class.ilObjLearningModuleAccess.php'); - $this->commands = ilObjLearningModuleAccess::_getCommands(); - } - - function setChildId($a_child_id) - { - $this->child_id = $a_child_id; - } - function getChildId() - { - return $this->child_id; - } - - /** - * Overwrite this method, if link target is not build by ctrl class - * (e.g. "forum.php"). This is the case - * for all links now, but bringing everything to ilCtrl should - * be realised in the future. - * - * @param string $a_cmd command - * - */ - function getCommandLink($a_cmd) - { - $ilCtrl = $this->ctrl; - - switch($a_cmd) - { - case "continue": - $cmd_link = "ilias.php?baseClass=ilLMPresentationGUI&ref_id=".$this->ref_id. - "&cmd=resume"; - break; - - case "page": - // Used for presentation of single pages chapters in search results - $cmd_link = "ilias.php?baseClass=ilLMPresentationGUI&ref_id=".$this->ref_id. - "&obj_id=".$this->getChildId(); - break; - - case "view": - $cmd_link = "ilias.php?baseClass=ilLMPresentationGUI&ref_id=".$this->ref_id; - break; - - case "edit": - $cmd_link = "ilias.php?baseClass=ilLMEditorGUI&ref_id=".$this->ref_id; - break; - - case "properties": - $cmd_link = "ilias.php?baseClass=ilLMEditorGUI&ref_id=".$this->ref_id."&to_props=1"; - break; - - case "infoScreen": - $cmd_link = "ilias.php?baseClass=ilLMPresentationGUI&ref_id=".$this->ref_id. - "&cmd=infoScreen&file_id".$this->getChildId(); - break; - - case 'downloadFile': - $cmd_link = 'ilias.php?baseClass=ilLMPresentationGUI&ref_id='.$this->ref_id. - '&cmd=downloadFile&file_id='.$this->getChildId(); - break; - - default: - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $this->ref_id); - $cmd_link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", $a_cmd); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - break; - } - - return $cmd_link; - } - - - /** - * Get command target frame - * - * @param string $a_cmd command - * - * @return string command target frame - */ - function getCommandFrame($a_cmd) - { - switch($a_cmd) - { - case "view": - case "continue": - case 'list': - $frame = ilFrameTargetInfo::_getFrame("MainContent"); - break; - - case "edit": - case "properties": - $frame = ilFrameTargetInfo::_getFrame("MainContent"); - break; - - case "infoScreen": - $frame = ilFrameTargetInfo::_getFrame("MainContent"); - break; - - default: - $frame = ""; - break; - } - - return $frame; - } - - - /** - * Get item properties - * - * @return array array of property arrays: - * "alert" (boolean) => display as an alert property (usually in red) - * "property" (string) => property name - * "value" (string) => property value - */ - function getProperties() - { - $lng = $this->lng; - $rbacsystem = $this->rbacsystem; - - $props = parent::getProperties(); - - if ($rbacsystem->checkAccess('write',$this->ref_id)) - { - $props[] = array("alert" => false, "property" => $lng->txt("type"), - "value" => $lng->txt("lm")); - } - - return $props; - } - - /** - * Get command icon image - */ - function getCommandImage($a_cmd) - { - switch ($a_cmd) - { - default: - return ""; - } - } - - + /** + * initialisation + * + * this method should be overwritten by derived classes + */ + public function init() + { + $this->static_link_enabled = true; + $this->delete_enabled = true; + $this->cut_enabled = true; + $this->copy_enabled = true; + $this->subscribe_enabled = true; + $this->link_enabled = true; + $this->info_screen_enabled = true; + $this->type = "lm"; + $this->gui_class_name = "ilobjlearningmodulegui"; + + // general commands array + include_once('./Modules/LearningModule/classes/class.ilObjLearningModuleAccess.php'); + $this->commands = ilObjLearningModuleAccess::_getCommands(); + } + + public function setChildId($a_child_id) + { + $this->child_id = $a_child_id; + } + public function getChildId() + { + return $this->child_id; + } + + /** + * Overwrite this method, if link target is not build by ctrl class + * (e.g. "forum.php"). This is the case + * for all links now, but bringing everything to ilCtrl should + * be realised in the future. + * + * @param string $a_cmd command + * + */ + public function getCommandLink($a_cmd) + { + $ilCtrl = $this->ctrl; + + switch ($a_cmd) { + case "continue": + $cmd_link = "ilias.php?baseClass=ilLMPresentationGUI&ref_id=" . $this->ref_id . + "&cmd=resume"; + break; + + case "page": + // Used for presentation of single pages chapters in search results + $cmd_link = "ilias.php?baseClass=ilLMPresentationGUI&ref_id=" . $this->ref_id . + "&obj_id=" . $this->getChildId(); + break; + + case "view": + $cmd_link = "ilias.php?baseClass=ilLMPresentationGUI&ref_id=" . $this->ref_id; + break; + + case "edit": + $cmd_link = "ilias.php?baseClass=ilLMEditorGUI&ref_id=" . $this->ref_id; + break; + + case "properties": + $cmd_link = "ilias.php?baseClass=ilLMEditorGUI&ref_id=" . $this->ref_id . "&to_props=1"; + break; + + case "infoScreen": + $cmd_link = "ilias.php?baseClass=ilLMPresentationGUI&ref_id=" . $this->ref_id . + "&cmd=infoScreen&file_id" . $this->getChildId(); + break; + + case 'downloadFile': + $cmd_link = 'ilias.php?baseClass=ilLMPresentationGUI&ref_id=' . $this->ref_id . + '&cmd=downloadFile&file_id=' . $this->getChildId(); + break; + + default: + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $this->ref_id); + $cmd_link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", $a_cmd); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + break; + } + + return $cmd_link; + } + + + /** + * Get command target frame + * + * @param string $a_cmd command + * + * @return string command target frame + */ + public function getCommandFrame($a_cmd) + { + switch ($a_cmd) { + case "view": + case "continue": + case 'list': + $frame = ilFrameTargetInfo::_getFrame("MainContent"); + break; + + case "edit": + case "properties": + $frame = ilFrameTargetInfo::_getFrame("MainContent"); + break; + + case "infoScreen": + $frame = ilFrameTargetInfo::_getFrame("MainContent"); + break; + + default: + $frame = ""; + break; + } + + return $frame; + } + + + /** + * Get item properties + * + * @return array array of property arrays: + * "alert" (boolean) => display as an alert property (usually in red) + * "property" (string) => property name + * "value" (string) => property value + */ + public function getProperties() + { + $lng = $this->lng; + $rbacsystem = $this->rbacsystem; + + $props = parent::getProperties(); + + if ($rbacsystem->checkAccess('write', $this->ref_id)) { + $props[] = array("alert" => false, "property" => $lng->txt("type"), + "value" => $lng->txt("lm")); + } + + return $props; + } + + /** + * Get command icon image + */ + public function getCommandImage($a_cmd) + { + switch ($a_cmd) { + default: + return ""; + } + } } // END class.ilObjCategoryGUI -?> diff --git a/Modules/LearningModule/classes/class.ilObjLearningModuleSubItemListGUI.php b/Modules/LearningModule/classes/class.ilObjLearningModuleSubItemListGUI.php index 78510be7d4ad57528bf3e6d106c0809966feeb65..4f9760dffadac4a987300ab8d031c16cd1888ce8 100644 --- a/Modules/LearningModule/classes/class.ilObjLearningModuleSubItemListGUI.php +++ b/Modules/LearningModule/classes/class.ilObjLearningModuleSubItemListGUI.php @@ -1,130 +1,124 @@ * @version $Id$ -* * -* @ingroup +* +* @ingroup */ class ilObjLearningModuleSubItemListGUI extends ilSubItemListGUI { - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - /** - * Constructor - */ - function __construct($a_cmd_class) - { - global $DIC; - parent::__construct($a_cmd_class); + /** + * Constructor + */ + public function __construct($a_cmd_class) + { + global $DIC; + parent::__construct($a_cmd_class); - $this->user = $DIC->user(); - } + $this->user = $DIC->user(); + } - - /** - * get html - * @return - */ - public function getHTML() - { - $lng = $this->lng; - $ilUser = $this->user; - - include_once 'Modules/LearningModule/classes/class.ilLMObject.php'; - foreach($this->getSubItemIds(true) as $sub_item) - { - if(is_object($this->getHighlighter()) and strlen($this->getHighlighter()->getContent($this->getObjId(),$sub_item))) - { - $this->tpl->setCurrentBlock('sea_fragment'); - $this->tpl->setVariable('TXT_FRAGMENT',$this->getHighlighter()->getContent($this->getObjId(),$sub_item)); - $this->tpl->parseCurrentBlock(); - } - $this->tpl->setCurrentBlock('subitem'); + + /** + * get html + * @return + */ + public function getHTML() + { + $lng = $this->lng; + $ilUser = $this->user; + + include_once 'Modules/LearningModule/classes/class.ilLMObject.php'; + foreach ($this->getSubItemIds(true) as $sub_item) { + if (is_object($this->getHighlighter()) and strlen($this->getHighlighter()->getContent($this->getObjId(), $sub_item))) { + $this->tpl->setCurrentBlock('sea_fragment'); + $this->tpl->setVariable('TXT_FRAGMENT', $this->getHighlighter()->getContent($this->getObjId(), $sub_item)); + $this->tpl->parseCurrentBlock(); + } + $this->tpl->setCurrentBlock('subitem'); - $this->tpl->setVariable('SEPERATOR',':'); - - - switch(ilLMObject::_lookupType($sub_item,$this->getObjId())) - { - case 'pg': - $this->getItemListGUI()->setChildId($sub_item); - $this->tpl->setVariable("SUBITEM_TYPE",$lng->txt('obj_pg')); - $link = $this->getItemListGUI()->getCommandLink('page'); - include_once './Services/Search/classes/class.ilUserSearchCache.php'; - $link .= ('&srcstring=1'); - $this->tpl->setVariable('LINK',$link); - $this->tpl->setVariable('TARGET',$this->getItemListGUI()->getCommandFrame('page')); - $this->tpl->setVariable('TITLE',ilLMObject::_lookupTitle($sub_item)); - break; - - case 'st': - - $this->getItemListGUI()->setChildId($sub_item); - $this->tpl->setVariable("SUBITEM_TYPE",$lng->txt('obj_st')); - $link = $this->getItemListGUI()->getCommandLink('page'); - include_once './Services/Search/classes/class.ilUserSearchCache.php'; - $link .= ('&srcstring=1'); - $this->tpl->setVariable('LINK',$link); - $this->tpl->setVariable('TARGET',$this->getItemListGUI()->getCommandFrame('page')); - $this->tpl->setVariable('TITLE',ilLMObject::_lookupTitle($sub_item)); - break; + $this->tpl->setVariable('SEPERATOR', ':'); + + + switch (ilLMObject::_lookupType($sub_item, $this->getObjId())) { + case 'pg': + $this->getItemListGUI()->setChildId($sub_item); + $this->tpl->setVariable("SUBITEM_TYPE", $lng->txt('obj_pg')); + $link = $this->getItemListGUI()->getCommandLink('page'); + include_once './Services/Search/classes/class.ilUserSearchCache.php'; + $link .= ('&srcstring=1'); + $this->tpl->setVariable('LINK', $link); + $this->tpl->setVariable('TARGET', $this->getItemListGUI()->getCommandFrame('page')); + $this->tpl->setVariable('TITLE', ilLMObject::_lookupTitle($sub_item)); + break; + + case 'st': + + $this->getItemListGUI()->setChildId($sub_item); + $this->tpl->setVariable("SUBITEM_TYPE", $lng->txt('obj_st')); + $link = $this->getItemListGUI()->getCommandLink('page'); + include_once './Services/Search/classes/class.ilUserSearchCache.php'; + $link .= ('&srcstring=1'); + $this->tpl->setVariable('LINK', $link); + $this->tpl->setVariable('TARGET', $this->getItemListGUI()->getCommandFrame('page')); + $this->tpl->setVariable('TITLE', ilLMObject::_lookupTitle($sub_item)); + break; - default: + default: - if(ilObject::_lookupType($sub_item) != 'file') - { - return ''; - } - - $this->getItemListGUI()->setChildId('il__file_'.$sub_item); - $this->tpl->setVariable('SUBITEM_TYPE',$lng->txt('obj_file')); - $link = $this->getItemListGUI()->getCommandLink('downloadFile'); - $this->tpl->setVariable('LINK',$link); - $this->tpl->setVariable('TITLE',ilObject::_lookupTitle($sub_item)); - break; - } + if (ilObject::_lookupType($sub_item) != 'file') { + return ''; + } + + $this->getItemListGUI()->setChildId('il__file_' . $sub_item); + $this->tpl->setVariable('SUBITEM_TYPE', $lng->txt('obj_file')); + $link = $this->getItemListGUI()->getCommandLink('downloadFile'); + $this->tpl->setVariable('LINK', $link); + $this->tpl->setVariable('TITLE', ilObject::_lookupTitle($sub_item)); + break; + } - if(count($this->getSubItemIds(true)) > 1) - { - $this->parseRelevance($sub_item); - } - - $this->tpl->parseCurrentBlock(); - } - - $this->showDetailsLink(); - - return $this->tpl->get(); - } + if (count($this->getSubItemIds(true)) > 1) { + $this->parseRelevance($sub_item); + } + + $this->tpl->parseCurrentBlock(); + } + + $this->showDetailsLink(); + + return $this->tpl->get(); + } } -?> \ No newline at end of file diff --git a/Modules/LearningModule/classes/class.ilObjLearningResourcesSettings.php b/Modules/LearningModule/classes/class.ilObjLearningResourcesSettings.php index 02c02509e53bd0f3e134769d9193aaf45b3930dd..aa4172b1c73092d9e8f9822c43afabce7bbf720a 100755 --- a/Modules/LearningModule/classes/class.ilObjLearningResourcesSettings.php +++ b/Modules/LearningModule/classes/class.ilObjLearningResourcesSettings.php @@ -1,105 +1,100 @@ +* +* @author Alex Killing * @version $Id$ * * @ingroup ModuleLearningModule */ class ilObjLearningResourcesSettings extends ilObject { - - /** - * Constructor - * @access public - * @param integer reference_id or object_id - * @param boolean treat the id as reference_id (true) or object_id (false) - */ - function __construct($a_id = 0,$a_call_by_reference = true) - { - global $DIC; - - $this->db = $DIC->database(); - $this->type = "lrss"; - parent::__construct($a_id,$a_call_by_reference); - } - - /** - * update object data - * - * @access public - * @return boolean - */ - function update() - { - $ilDB = $this->db; - - if (!parent::update()) - { - return false; - } + + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + global $DIC; - return true; - } - - /** - * read style folder data - */ - function read() - { - $ilDB = $this->db; + $this->db = $DIC->database(); + $this->type = "lrss"; + parent::__construct($a_id, $a_call_by_reference); + } - parent::read(); + /** + * update object data + * + * @access public + * @return boolean + */ + public function update() + { + $ilDB = $this->db; + + if (!parent::update()) { + return false; + } - } - + return true; + } + + /** + * read style folder data + */ + public function read() + { + $ilDB = $this->db; - - + parent::read(); + } + - /** - * delete object and all related data - * - * @access public - * @return boolean true if all object data were removed; false if only a references were removed - */ - function delete() - { - // always call parent delete function first!! - if (!parent::delete()) - { - return false; - } - - //put here your module specific stuff - - return true; - } + + + /** + * delete object and all related data + * + * @access public + * @return boolean true if all object data were removed; false if only a references were removed + */ + public function delete() + { + // always call parent delete function first!! + if (!parent::delete()) { + return false; + } + + //put here your module specific stuff + + return true; + } } // END class.ilObjLearningResourcesSettings -?> diff --git a/Modules/LearningModule/classes/class.ilObjLearningResourcesSettingsAccess.php b/Modules/LearningModule/classes/class.ilObjLearningResourcesSettingsAccess.php index 35c1c0fedc255afcd06fe4742f9e8630f68b4047..fc21829c4341df6584ad4cad9e475b6d1445f583 100755 --- a/Modules/LearningModule/classes/class.ilObjLearningResourcesSettingsAccess.php +++ b/Modules/LearningModule/classes/class.ilObjLearningResourcesSettingsAccess.php @@ -1,24 +1,24 @@ diff --git a/Modules/LearningModule/classes/class.ilObjLearningResourcesSettingsGUI.php b/Modules/LearningModule/classes/class.ilObjLearningResourcesSettingsGUI.php index 00f9640528e269fcbe286d97bedeffbd7e4fefce..0374c2e42be6f3539e4c721edf05c2cf06e3d962 100755 --- a/Modules/LearningModule/classes/class.ilObjLearningResourcesSettingsGUI.php +++ b/Modules/LearningModule/classes/class.ilObjLearningResourcesSettingsGUI.php @@ -17,273 +17,305 @@ include_once('./Services/PrivacySecurity/classes/class.ilPrivacySettings.php'); */ class ilObjLearningResourcesSettingsGUI extends ilObjectGUI { - /** - * @var ilRbacSystem - */ - protected $rbacsystem; + /** + * @var ilRbacSystem + */ + protected $rbacsystem; - /** - * @var ilErrorHandling - */ - protected $error; + /** + * @var ilErrorHandling + */ + protected $error; private static $ERROR_MESSAGE; - /** - * Contructor - * - * @access public - */ - public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) - { - global $DIC; - - $this->rbacsystem = $DIC->rbac()->system(); - $this->error = $DIC["ilErr"]; - $this->access = $DIC->access(); - $this->settings = $DIC->settings(); - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->type = 'lrss'; - parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); - - $this->lng->loadLanguageModule('content'); - } - - /** - * Execute command - * - * @access public - * - */ - public function executeCommand() - { - $ilErr = $this->error; - $ilAccess = $this->access; - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - $this->prepareOutput(); - - if(!$ilAccess->checkAccess('read','',$this->object->getRefId())) - { - $ilErr->raiseError($this->lng->txt('no_permission'),$ilErr->WARNING); - } - - switch($next_class) - { - case 'ilpermissiongui': - $this->tabs_gui->setTabActive('perm_settings'); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $ret = $this->ctrl->forwardCommand($perm_gui); - break; - - default: - if(!$cmd || $cmd == 'view') - { - $cmd = "editSettings"; - } - - $this->$cmd(); - break; - } - return true; - } - - /** - * Get tabs - * - * @access public - * - */ - public function getAdminTabs() - { - $rbacsystem = $this->rbacsystem; - - if ($rbacsystem->checkAccess("visible,read",$this->object->getRefId())) - { - $this->tabs_gui->addTarget("cont_edit_lrs_settings", - $this->ctrl->getLinkTarget($this, "editSettings"), - array("editSettings", "view")); - } - - if ($rbacsystem->checkAccess('edit_permission',$this->object->getRefId())) - { - $this->tabs_gui->addTarget("perm_settings", - $this->ctrl->getLinkTargetByClass('ilpermissiongui',"perm"), - array(),'ilpermissiongui'); - } - } - - /** - * Edit learning resources settings. - */ - public function editSettings() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilSetting = $this->settings; - - $lm_set = new ilSetting("lm"); - $lng->loadLanguageModule("scormdebug"); - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this)); - $form->setTitle($lng->txt("cont_lrs_settings")); - - // Page History - $cb_prop = new ilCheckboxInputGUI($lng->txt("cont_enable_page_history"), - "page_history"); - $cb_prop->setInfo($lng->txt("cont_enable_page_history_info")); - $cb_prop->setChecked($lm_set->get("page_history", 1)); - $form->addItem($cb_prop); - - // Time scheduled page activation - $cb_prop = new ilCheckboxInputGUI($lng->txt("cont_enable_time_scheduled_page_activation"), - "time_scheduled_page_activation"); - $cb_prop->setInfo($lng->txt("cont_enable_time_scheduled_page_activation_info")); - $cb_prop->setChecked($lm_set->get("time_scheduled_page_activation")); - $form->addItem($cb_prop); - - // lm starting point - $options = array( - "" => $this->lng->txt("cont_last_visited_page"), - "first" => $this->lng->txt("cont_first_page") - ); - $si = new ilSelectInputGUI($this->lng->txt("cont_lm_starting_point"), "lm_starting_point"); - $si->setOptions($options); - $si->setValue($lm_set->get("lm_starting_point")); - $si->setInfo($this->lng->txt("cont_lm_starting_point_info")); - $form->addItem($si); - - // Activate replace media object function - $cb_prop = new ilCheckboxInputGUI($lng->txt("cont_replace_mob_feature"), - "replace_mob_feature"); - $cb_prop->setInfo($lng->txt("cont_replace_mob_feature_info")); - $cb_prop->setChecked($lm_set->get("replace_mob_feature")); - $form->addItem($cb_prop); - - // Activate HTML export IDs - $cb_prop = new ilCheckboxInputGUI($lng->txt("cont_html_export_ids"), - "html_export_ids"); - $cb_prop->setInfo($lng->txt("cont_html_export_ids_info")); - $cb_prop->setChecked($lm_set->get("html_export_ids")); - $form->addItem($cb_prop); - - // Upload dir for learning resources - $tx_prop = new ilTextInputGUI($lng->txt("cont_upload_dir"), - "cont_upload_dir"); - $tx_prop->setInfo($lng->txt("cont_upload_dir_info")); - $tx_prop->setValue($lm_set->get("cont_upload_dir")); - $form->addItem($tx_prop); - - // scormDebugger activation - $cb_prop = new ilCheckboxInputGUI($lng->txt("scormdebug_global_activate"),"scormdebug_global_activate"); - $cb_prop->setInfo($lng->txt("scormdebug_global_activate_info")); - $cb_prop->setChecked($lm_set->get("scormdebug_global_activate")); - $form->addItem($cb_prop); - - // scorm2004 disableRTECaching - $cb_prop = new ilCheckboxInputGUI($lng->txt("scormdebug_disable_cache"), - "scormdebug_disable_cache"); - $cb_prop->setInfo($lng->txt("scormdebug_disable_cache_info")); - $cb_prop->setChecked($lm_set->get("scormdebug_disable_cache")); - $form->addItem($cb_prop); - - // scorm2004 without session - $cb_prop = new ilCheckboxInputGUI($lng->txt("scorm_without_session"), - "scorm_without_session"); - $cb_prop->setInfo($lng->txt("scorm_without_session_info")); - $cb_prop->setChecked($lm_set->get("scorm_without_session")); - $form->addItem($cb_prop); - - $privacy = ilPrivacySettings::_getInstance(); - $check = new ilCheckboxInputGui($lng->txt('enable_sahs_protocol_data'), 'enable_sahs_pd'); - $check->setInfo($this->lng->txt('enable_sahs_protocol_data_desc')); - $check->setChecked($privacy->enabledSahsProtocolData()); - $form->addItem($check); - - // show and export protocol data with name - $check = new ilCheckboxInputGui($this->lng->txt('ps_export_scorm'), 'export_scorm'); - $check->setInfo($this->lng->txt('enable_export_scorm_desc')); - $check->setChecked($privacy->enabledExportSCORM()); - $form->addItem($check); - - // scorm auto-setting for learning progress - $cb_prop = new ilCheckboxInputGUI($lng->txt("scorm_lp_auto_activate"),"scorm_lp_auto_activate"); - $cb_prop->setInfo($lng->txt("scorm_lp_auto_activate_info")); - $cb_prop->setChecked($lm_set->get("scorm_lp_auto_activate")); - $form->addItem($cb_prop); - - // command buttons - if ($this->checkPermissionBool("write")) - { - $form->addCommandButton("saveSettings", $lng->txt("save")); - $form->addCommandButton("view", $lng->txt("cancel")); - } - - $this->tpl->setContent($form->getHTML()); - } - - /** - * Save learning resources settings - */ - public function saveSettings() - { - $ilCtrl = $this->ctrl; - $ilSetting = $this->settings; - - $this->checkPermission("write"); - - $lm_set = new ilSetting("lm"); - $lm_set->set("time_scheduled_page_activation", - ilUtil::stripSlashes($_POST["time_scheduled_page_activation"])); - $lm_set->set("lm_starting_point", - ilUtil::stripSlashes($_POST["lm_starting_point"])); - $lm_set->set("page_history", - (int) ilUtil::stripSlashes($_POST["page_history"])); - $lm_set->set("replace_mob_feature", - ilUtil::stripSlashes($_POST["replace_mob_feature"])); - $lm_set->set("html_export_ids", - ilUtil::stripSlashes($_POST["html_export_ids"])); - $lm_set->set("cont_upload_dir", - ilUtil::stripSlashes($_POST["cont_upload_dir"])); - $lm_set->setScormDebug("scormdebug_global_activate", - ilUtil::stripSlashes($_POST["scormdebug_global_activate"])); - $lm_set->set("scorm_login_as_learner_id", - ilUtil::stripSlashes($_POST["scorm_login_as_learner_id"])); - $lm_set->set("scormdebug_disable_cache", - ilUtil::stripSlashes($_POST["scormdebug_disable_cache"])); - $lm_set->set("scorm_without_session", - ilUtil::stripSlashes($_POST["scorm_without_session"])); - $lm_set->set("scorm_lp_auto_activate", - ilUtil::stripSlashes($_POST["scorm_lp_auto_activate"])); - - $privacy = ilPrivacySettings::_getInstance(); - $privacy->enableSahsProtocolData((int) $_POST['enable_sahs_pd']); - $privacy->enableExportSCORM((int) $_POST['export_scorm']); - $privacy->save(); - - ilUtil::sendSuccess($this->lng->txt("settings_saved"),true); - - $ilCtrl->redirect($this, "view"); - } - - public function addToExternalSettingsForm($a_form_id) - { - switch($a_form_id) - { - case ilAdministrationSettingsFormHandler::FORM_PRIVACY: - - $privacy = ilPrivacySettings::_getInstance(); - - $fields = array('enable_sahs_protocol_data' => array($privacy->enabledSahsProtocolData(), ilAdministrationSettingsFormHandler::VALUE_BOOL)); - - return array(array("editSettings", $fields)); - } - } + /** + * Contructor + * + * @access public + */ + public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) + { + global $DIC; + + $this->rbacsystem = $DIC->rbac()->system(); + $this->error = $DIC["ilErr"]; + $this->access = $DIC->access(); + $this->settings = $DIC->settings(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->type = 'lrss'; + parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); + + $this->lng->loadLanguageModule('content'); + } + + /** + * Execute command + * + * @access public + * + */ + public function executeCommand() + { + $ilErr = $this->error; + $ilAccess = $this->access; + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + $this->prepareOutput(); + + if (!$ilAccess->checkAccess('read', '', $this->object->getRefId())) { + $ilErr->raiseError($this->lng->txt('no_permission'), $ilErr->WARNING); + } + + switch ($next_class) { + case 'ilpermissiongui': + $this->tabs_gui->setTabActive('perm_settings'); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $ret = $this->ctrl->forwardCommand($perm_gui); + break; + + default: + if (!$cmd || $cmd == 'view') { + $cmd = "editSettings"; + } + + $this->$cmd(); + break; + } + return true; + } + + /** + * Get tabs + * + * @access public + * + */ + public function getAdminTabs() + { + $rbacsystem = $this->rbacsystem; + + if ($rbacsystem->checkAccess("visible,read", $this->object->getRefId())) { + $this->tabs_gui->addTarget( + "cont_edit_lrs_settings", + $this->ctrl->getLinkTarget($this, "editSettings"), + array("editSettings", "view") + ); + } + + if ($rbacsystem->checkAccess('edit_permission', $this->object->getRefId())) { + $this->tabs_gui->addTarget( + "perm_settings", + $this->ctrl->getLinkTargetByClass('ilpermissiongui', "perm"), + array(), + 'ilpermissiongui' + ); + } + } + + /** + * Edit learning resources settings. + */ + public function editSettings() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilSetting = $this->settings; + + $lm_set = new ilSetting("lm"); + $lng->loadLanguageModule("scormdebug"); + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this)); + $form->setTitle($lng->txt("cont_lrs_settings")); + + // Page History + $cb_prop = new ilCheckboxInputGUI( + $lng->txt("cont_enable_page_history"), + "page_history" + ); + $cb_prop->setInfo($lng->txt("cont_enable_page_history_info")); + $cb_prop->setChecked($lm_set->get("page_history", 1)); + $form->addItem($cb_prop); + + // Time scheduled page activation + $cb_prop = new ilCheckboxInputGUI( + $lng->txt("cont_enable_time_scheduled_page_activation"), + "time_scheduled_page_activation" + ); + $cb_prop->setInfo($lng->txt("cont_enable_time_scheduled_page_activation_info")); + $cb_prop->setChecked($lm_set->get("time_scheduled_page_activation")); + $form->addItem($cb_prop); + + // lm starting point + $options = array( + "" => $this->lng->txt("cont_last_visited_page"), + "first" => $this->lng->txt("cont_first_page") + ); + $si = new ilSelectInputGUI($this->lng->txt("cont_lm_starting_point"), "lm_starting_point"); + $si->setOptions($options); + $si->setValue($lm_set->get("lm_starting_point")); + $si->setInfo($this->lng->txt("cont_lm_starting_point_info")); + $form->addItem($si); + + // Activate replace media object function + $cb_prop = new ilCheckboxInputGUI( + $lng->txt("cont_replace_mob_feature"), + "replace_mob_feature" + ); + $cb_prop->setInfo($lng->txt("cont_replace_mob_feature_info")); + $cb_prop->setChecked($lm_set->get("replace_mob_feature")); + $form->addItem($cb_prop); + + // Activate HTML export IDs + $cb_prop = new ilCheckboxInputGUI( + $lng->txt("cont_html_export_ids"), + "html_export_ids" + ); + $cb_prop->setInfo($lng->txt("cont_html_export_ids_info")); + $cb_prop->setChecked($lm_set->get("html_export_ids")); + $form->addItem($cb_prop); + + // Upload dir for learning resources + $tx_prop = new ilTextInputGUI( + $lng->txt("cont_upload_dir"), + "cont_upload_dir" + ); + $tx_prop->setInfo($lng->txt("cont_upload_dir_info")); + $tx_prop->setValue($lm_set->get("cont_upload_dir")); + $form->addItem($tx_prop); + + // scormDebugger activation + $cb_prop = new ilCheckboxInputGUI($lng->txt("scormdebug_global_activate"), "scormdebug_global_activate"); + $cb_prop->setInfo($lng->txt("scormdebug_global_activate_info")); + $cb_prop->setChecked($lm_set->get("scormdebug_global_activate")); + $form->addItem($cb_prop); + + // scorm2004 disableRTECaching + $cb_prop = new ilCheckboxInputGUI( + $lng->txt("scormdebug_disable_cache"), + "scormdebug_disable_cache" + ); + $cb_prop->setInfo($lng->txt("scormdebug_disable_cache_info")); + $cb_prop->setChecked($lm_set->get("scormdebug_disable_cache")); + $form->addItem($cb_prop); + + // scorm2004 without session + $cb_prop = new ilCheckboxInputGUI( + $lng->txt("scorm_without_session"), + "scorm_without_session" + ); + $cb_prop->setInfo($lng->txt("scorm_without_session_info")); + $cb_prop->setChecked($lm_set->get("scorm_without_session")); + $form->addItem($cb_prop); + + $privacy = ilPrivacySettings::_getInstance(); + $check = new ilCheckboxInputGui($lng->txt('enable_sahs_protocol_data'), 'enable_sahs_pd'); + $check->setInfo($this->lng->txt('enable_sahs_protocol_data_desc')); + $check->setChecked($privacy->enabledSahsProtocolData()); + $form->addItem($check); + + // show and export protocol data with name + $check = new ilCheckboxInputGui($this->lng->txt('ps_export_scorm'), 'export_scorm'); + $check->setInfo($this->lng->txt('enable_export_scorm_desc')); + $check->setChecked($privacy->enabledExportSCORM()); + $form->addItem($check); + + // scorm auto-setting for learning progress + $cb_prop = new ilCheckboxInputGUI($lng->txt("scorm_lp_auto_activate"), "scorm_lp_auto_activate"); + $cb_prop->setInfo($lng->txt("scorm_lp_auto_activate_info")); + $cb_prop->setChecked($lm_set->get("scorm_lp_auto_activate")); + $form->addItem($cb_prop); + + // command buttons + if ($this->checkPermissionBool("write")) { + $form->addCommandButton("saveSettings", $lng->txt("save")); + $form->addCommandButton("view", $lng->txt("cancel")); + } + + $this->tpl->setContent($form->getHTML()); + } + + /** + * Save learning resources settings + */ + public function saveSettings() + { + $ilCtrl = $this->ctrl; + $ilSetting = $this->settings; + + $this->checkPermission("write"); + + $lm_set = new ilSetting("lm"); + $lm_set->set( + "time_scheduled_page_activation", + ilUtil::stripSlashes($_POST["time_scheduled_page_activation"]) + ); + $lm_set->set( + "lm_starting_point", + ilUtil::stripSlashes($_POST["lm_starting_point"]) + ); + $lm_set->set( + "page_history", + (int) ilUtil::stripSlashes($_POST["page_history"]) + ); + $lm_set->set( + "replace_mob_feature", + ilUtil::stripSlashes($_POST["replace_mob_feature"]) + ); + $lm_set->set( + "html_export_ids", + ilUtil::stripSlashes($_POST["html_export_ids"]) + ); + $lm_set->set( + "cont_upload_dir", + ilUtil::stripSlashes($_POST["cont_upload_dir"]) + ); + $lm_set->setScormDebug( + "scormdebug_global_activate", + ilUtil::stripSlashes($_POST["scormdebug_global_activate"]) + ); + $lm_set->set( + "scorm_login_as_learner_id", + ilUtil::stripSlashes($_POST["scorm_login_as_learner_id"]) + ); + $lm_set->set( + "scormdebug_disable_cache", + ilUtil::stripSlashes($_POST["scormdebug_disable_cache"]) + ); + $lm_set->set( + "scorm_without_session", + ilUtil::stripSlashes($_POST["scorm_without_session"]) + ); + $lm_set->set( + "scorm_lp_auto_activate", + ilUtil::stripSlashes($_POST["scorm_lp_auto_activate"]) + ); + + $privacy = ilPrivacySettings::_getInstance(); + $privacy->enableSahsProtocolData((int) $_POST['enable_sahs_pd']); + $privacy->enableExportSCORM((int) $_POST['export_scorm']); + $privacy->save(); + + ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); + + $ilCtrl->redirect($this, "view"); + } + + public function addToExternalSettingsForm($a_form_id) + { + switch ($a_form_id) { + case ilAdministrationSettingsFormHandler::FORM_PRIVACY: + + $privacy = ilPrivacySettings::_getInstance(); + + $fields = array('enable_sahs_protocol_data' => array($privacy->enabledSahsProtocolData(), ilAdministrationSettingsFormHandler::VALUE_BOOL)); + + return array(array("editSettings", $fields)); + } + } } - -?> \ No newline at end of file diff --git a/Modules/LearningModule/classes/class.ilPublicSectionExplorerGUI.php b/Modules/LearningModule/classes/class.ilPublicSectionExplorerGUI.php index 346b40ed0a8492d88f155be225ffbab7b7b47c0a..d8f9fd94cccba0307198d4b4d771573b5acfe0ca 100644 --- a/Modules/LearningModule/classes/class.ilPublicSectionExplorerGUI.php +++ b/Modules/LearningModule/classes/class.ilPublicSectionExplorerGUI.php @@ -1,166 +1,162 @@ - - * @version $Id$ - * - * @ingroup ModulesLearningModule - */ -class ilPublicSectionExplorerGUI extends ilTreeExplorerGUI -{ - var $exp_id = "public_section"; - - /** - * constructor - * - * @param object $a_parent_obj - * @param string $a_parent_cmd - * @param ilObjLearningModule $a_lm - */ - public function __construct($a_parent_obj,$a_parent_cmd, $a_lm) - { - $this->lm = $a_lm; - - include_once("./Modules/LearningModule/classes/class.ilLMTree.php"); - $tree = ilLMTree::getInstance($this->lm->getId()); - - parent::__construct("lm_public_section_".$this->lm->getId(),$a_parent_obj,$a_parent_cmd,$tree); - } - - /** - * get node content - * - * @param mixed $a_node - * @return string note name - */ - public function getNodeContent($a_node) - { - $lang = ($_GET["transl"] != "") - ? $_GET["transl"] - : "-"; - return ilLMObject::_getPresentationTitle($a_node, IL_PAGE_TITLE, - $this->lm->isActiveNumbering(), false, false, $this->lm->getId(), $lang); - } - - /** - * Get node icon - * - * @param array $a_node node array - * @return string icon path - */ - function getNodeIcon($a_node) - { - if ($a_node["child"] == $this->getNodeId($this->getRootNode())) - { - $icon = ilUtil::getImagePath("icon_lm.svg"); - } - else - { - $a_name = "icon_".$a_node["type"].".svg"; - if ($a_node["type"] == "pg") - { - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - $lm_set = new ilSetting("lm"); - $active = ilLMPage::_lookupActive($a_node["child"], $this->lm->getType(), - $lm_set->get("time_scheduled_page_activation")); - - // is page scheduled? - $img_sc = ($lm_set->get("time_scheduled_page_activation") && - ilLMPage::_isScheduledActivation($a_node["child"], $this->lm->getType())) - ? "_sc" - : ""; - - $a_name = "icon_pg".$img_sc.".svg"; - - if (!$active) - { - $a_name = "icon_pg_d".$img_sc.".svg"; - } - else - { - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - $contains_dis = ilLMPage::_lookupContainsDeactivatedElements($a_node["child"], - $this->lm->getType()); - if ($contains_dis) - { - $a_name = "icon_pg_del".$img_sc.".svg"; - } - } - } - $icon = ilUtil::getImagePath($a_name); - } - - return $icon; - } - - /** - * select public pages and open public chapter - */ - public function beforeRendering() - { - //select public pages and open public chapters - foreach($this->getAllNodes() as $node) - { - if($node["public_access"] == "y" && $node["type"] == "pg") - { - $this->setNodeSelected($node["obj_id"]); - } - if($node["public_access"] == "y" && $node["type"]== "st") - { - $this->setNodeOpen($node["obj_id"]); - } - } - } - - /** - * Returns all nodes from tree recursive - * - * @param mixed $from_id - * @return array nodes - */ - protected function getAllNodes($from_id = null) - { - $nodes = array(); - - if($from_id === null) - { - $from_id = $this->getNodeId($this->getRootNode()); - } - - foreach($this->getChildsOfNode($from_id) as $node) - { - $nodes[] = $node; - - if($node["type"] == "st") - { - $nodes = array_merge($nodes, $this->getAllNodes($node["obj_id"])); - } - } - return $nodes; - } - - /** - * Is not clickable? - * - * @param array $a_node node array - * @return bool - */ - function isNodeClickable($a_node) - { - if ($a_node["type"] == "pg") - { - return true; - } - return false; - } - -} \ No newline at end of file + + * @version $Id$ + * + * @ingroup ModulesLearningModule + */ +class ilPublicSectionExplorerGUI extends ilTreeExplorerGUI +{ + public $exp_id = "public_section"; + + /** + * constructor + * + * @param object $a_parent_obj + * @param string $a_parent_cmd + * @param ilObjLearningModule $a_lm + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_lm) + { + $this->lm = $a_lm; + + include_once("./Modules/LearningModule/classes/class.ilLMTree.php"); + $tree = ilLMTree::getInstance($this->lm->getId()); + + parent::__construct("lm_public_section_" . $this->lm->getId(), $a_parent_obj, $a_parent_cmd, $tree); + } + + /** + * get node content + * + * @param mixed $a_node + * @return string note name + */ + public function getNodeContent($a_node) + { + $lang = ($_GET["transl"] != "") + ? $_GET["transl"] + : "-"; + return ilLMObject::_getPresentationTitle( + $a_node, + IL_PAGE_TITLE, + $this->lm->isActiveNumbering(), + false, + false, + $this->lm->getId(), + $lang + ); + } + + /** + * Get node icon + * + * @param array $a_node node array + * @return string icon path + */ + public function getNodeIcon($a_node) + { + if ($a_node["child"] == $this->getNodeId($this->getRootNode())) { + $icon = ilUtil::getImagePath("icon_lm.svg"); + } else { + $a_name = "icon_" . $a_node["type"] . ".svg"; + if ($a_node["type"] == "pg") { + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + $lm_set = new ilSetting("lm"); + $active = ilLMPage::_lookupActive( + $a_node["child"], + $this->lm->getType(), + $lm_set->get("time_scheduled_page_activation") + ); + + // is page scheduled? + $img_sc = ($lm_set->get("time_scheduled_page_activation") && + ilLMPage::_isScheduledActivation($a_node["child"], $this->lm->getType())) + ? "_sc" + : ""; + + $a_name = "icon_pg" . $img_sc . ".svg"; + + if (!$active) { + $a_name = "icon_pg_d" . $img_sc . ".svg"; + } else { + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + $contains_dis = ilLMPage::_lookupContainsDeactivatedElements( + $a_node["child"], + $this->lm->getType() + ); + if ($contains_dis) { + $a_name = "icon_pg_del" . $img_sc . ".svg"; + } + } + } + $icon = ilUtil::getImagePath($a_name); + } + + return $icon; + } + + /** + * select public pages and open public chapter + */ + public function beforeRendering() + { + //select public pages and open public chapters + foreach ($this->getAllNodes() as $node) { + if ($node["public_access"] == "y" && $node["type"] == "pg") { + $this->setNodeSelected($node["obj_id"]); + } + if ($node["public_access"] == "y" && $node["type"]== "st") { + $this->setNodeOpen($node["obj_id"]); + } + } + } + + /** + * Returns all nodes from tree recursive + * + * @param mixed $from_id + * @return array nodes + */ + protected function getAllNodes($from_id = null) + { + $nodes = array(); + + if ($from_id === null) { + $from_id = $this->getNodeId($this->getRootNode()); + } + + foreach ($this->getChildsOfNode($from_id) as $node) { + $nodes[] = $node; + + if ($node["type"] == "st") { + $nodes = array_merge($nodes, $this->getAllNodes($node["obj_id"])); + } + } + return $nodes; + } + + /** + * Is not clickable? + * + * @param array $a_node node array + * @return bool + */ + public function isNodeClickable($a_node) + { + if ($a_node["type"] == "pg") { + return true; + } + return false; + } +} diff --git a/Modules/LearningModule/classes/class.ilStructureObject.php b/Modules/LearningModule/classes/class.ilStructureObject.php index 528f14257c8a10dfe77e0c07c3c107d427427b26..169ffd2297deb1ad878f110ca0bb554d8e15a43f 100755 --- a/Modules/LearningModule/classes/class.ilStructureObject.php +++ b/Modules/LearningModule/classes/class.ilStructureObject.php @@ -16,371 +16,352 @@ require_once("./Modules/LearningModule/classes/class.ilLMObject.php"); */ class ilStructureObject extends ilLMObject { - var $is_alias; - var $origin_id; - var $tree; - - /** - * Constructor - * @access public - */ - function __construct(&$a_content_obj, $a_id = 0) - { - $this->setType("st"); - parent::__construct($a_content_obj, $a_id); - } - - function create($a_upload = false) - { - parent::create($a_upload); - } - - /** - * Delete Chapter - */ - function delete($a_delete_meta_data = true) - { - // only relevant for online help authoring - include_once("./Services/Help/classes/class.ilHelpMapping.php"); - ilHelpMapping::removeScreenIdsOfChapter($this->getId()); - - $this->tree = new ilTree($this->getLmId()); - $this->tree->setTableNames('lm_tree', 'lm_data'); - $this->tree->setTreeTablePK("lm_id"); - $node_data = $this->tree->getNodeData($this->getId()); - $this->delete_rec($this->tree, $a_delete_meta_data); - $this->tree->deleteTree($node_data); - } - - /** - * Delete sub tree - */ - private function delete_rec(&$a_tree, $a_delete_meta_data = true) - { - $childs = $a_tree->getChilds($this->getId()); - foreach ($childs as $child) - { - $obj = ilLMObjectFactory::getInstance($this->content_object, $child["obj_id"], false); - if (is_object($obj)) - { - if($obj->getType() == "st") - { - $obj->delete_rec($a_tree, $a_delete_meta_data); - } - if($obj->getType() == "pg") - { - $obj->delete($a_delete_meta_data); - } - } - unset($obj); - } - parent::delete($a_delete_meta_data); - } - - /** - * copy chapter - */ - function copy($a_target_lm) - { - $chap = new ilStructureObject($a_target_lm); - $chap->setTitle($this->getTitle()); - if ($this->getLMId() != $a_target_lm->getId()) - { - $chap->setImportId("il__st_".$this->getId()); - } - $chap->setLMId($a_target_lm->getId()); - $chap->setType($this->getType()); - $chap->setDescription($this->getDescription()); - $chap->create(true); - $a_copied_nodes[$this->getId()] = $chap->getId(); - - // copy meta data - include_once("Services/MetaData/classes/class.ilMD.php"); - $md = new ilMD($this->getLMId(), $this->getId(), $this->getType()); - $new_md = $md->cloneMD($a_target_lm->getId(), $chap->getId(), $this->getType()); - - // copy translations - include_once("./Modules/LearningModule/classes/class.ilLMObjTranslation.php"); - ilLMObjTranslation::copy($this->getId(), $chap->getId()); - - - return $chap; - } - - /** - * export object to xml (see ilias_co.dtd) - * - * @param object $a_xml_writer ilXmlWriter object that receives the - * xml data - */ - function exportXML(&$a_xml_writer, $a_inst, &$expLog) - { - $expLog->write(date("[y-m-d H:i:s] ")."Structure Object ".$this->getId()); - $attrs = array(); - $a_xml_writer->xmlStartTag("StructureObject", $attrs); - - // MetaData - $this->exportXMLMetaData($a_xml_writer); - - // StructureObjects - $this->exportXMLPageObjects($a_xml_writer, $a_inst); - - // PageObjects - $this->exportXMLStructureObjects($a_xml_writer, $a_inst, $expLog); - - // Layout - // not implemented - - $a_xml_writer->xmlEndTag("StructureObject"); - } - - - /** - * export structure objects meta data to xml (see ilias_co.dtd) - * - * @param object $a_xml_writer ilXmlWriter object that receives the - * xml data - */ - function exportXMLMetaData(&$a_xml_writer) - { - include_once("Services/MetaData/classes/class.ilMD2XML.php"); - $md2xml = new ilMD2XML($this->getLMId(), $this->getId(), $this->getType()); - $md2xml->setExportMode(true); - $md2xml->startExport(); - $a_xml_writer->appendXML($md2xml->getXML()); - } - - function modifyExportIdentifier($a_tag, $a_param, $a_value) - { - if ($a_tag == "Identifier" && $a_param == "Entry") - { - $a_value = "il_".IL_INST_ID."_st_".$this->getId(); - } - - return $a_value; - } - - /** - * get presentation title - * - */ - static function _getPresentationTitle($a_st_id, $a_mode = IL_CHAPTER_TITLE, $a_include_numbers = false, - $a_time_scheduled_activation = false, $a_force_content = false, $a_lm_id = 0, $a_lang = "-", $a_include_short = false) - { - global $DIC; - - $ilDB = $DIC->database(); - - if ($a_lm_id == 0) - { - $a_lm_id = ilLMObject::_lookupContObjID($a_st_id); - } - - if ($a_lm_id == 0) - { - return ""; - } - - // this is optimized when ilLMObject::preloadDataByLM is invoked (e.g. done in ilLMExplorerGUI) - $title = ""; - if ($a_include_short) - { - $title = trim(ilLMObject::_lookupShortTitle($a_st_id)); - } - if ($title == "") - { - $title = ilLMObject::_lookupTitle($a_st_id); - } - - // this is also optimized since ilObjectTranslation re-uses instances for one lm - include_once("./Services/Object/classes/class.ilObjectTranslation.php"); - $ot = ilObjectTranslation::getInstance($a_lm_id); - $languages = $ot->getLanguages(); - - if ($a_lang != "-" && $ot->getContentActivated() && isset($languages[$a_lang])) - { - include_once("./Modules/LearningModule/classes/class.ilLMObjTranslation.php"); - $lmobjtrans = new ilLMObjTranslation($a_st_id, $a_lang); - $trans_title = ""; - if ($a_include_short) - { - $trans_title = trim($lmobjtrans->getShortTitle()); - } - if ($trans_title == "") - { - $trans_title = $lmobjtrans->getTitle(); - } - if ($trans_title != "") - { - $title = $trans_title; - } - } - - include_once("./Modules/LearningModule/classes/class.ilLMTree.php"); - $tree = ilLMTree::getInstance($a_lm_id); - - if ($a_include_numbers) - { - // this is optimized, since isInTree is cached - if ($tree->isInTree($a_st_id)) - { - // optimization needed from here - - // get chapter tree node - $query = "SELECT * FROM lm_tree WHERE child = ". - $ilDB->quote($a_st_id, "integer")." AND lm_id = ". - $ilDB->quote($a_lm_id, "integer"); - $tree_set = $ilDB->query($query); - $tree_node = $tree_set->fetchRow(ilDBConstants::FETCHMODE_ASSOC); - $depth = $tree_node["depth"]; - - $nr = $tree->getChildSequenceNumber($tree_node, "st")." "; - for ($i = $depth - 1; $i > 1; $i --) - { - // get next parent tree node - $query = "SELECT * FROM lm_tree WHERE child = ". - $ilDB->quote($tree_node["parent"], "integer")." AND lm_id = ". - $ilDB->quote($a_lm_id, "integer"); - $tree_set = $ilDB->query($query); - $tree_node = $tree_set->fetchRow(ilDBConstants::FETCHMODE_ASSOC); - $seq = $tree->getChildSequenceNumber($tree_node, "st"); - - $nr = $seq.".".$nr; - } - } - } - - return $nr.$title; - } - - - - /** - * export page objects of structure object (see ilias_co.dtd) - * - * @param object $a_xml_writer ilXmlWriter object that receives the - * xml data - */ - function exportXMLPageObjects(&$a_xml_writer, $a_inst = 0) - { - include_once './Modules/LearningModule/classes/class.ilLMPageObject.php'; - - $this->tree = new ilTree($this->getLmId()); - $this->tree->setTableNames('lm_tree', 'lm_data'); - $this->tree->setTreeTablePK("lm_id"); - - $childs = $this->tree->getChilds($this->getId()); - foreach ($childs as $child) - { - if($child["type"] != "pg") - { - continue; - } - - // export xml to writer object - ilLMPageObject::_exportXMLAlias($a_xml_writer, $child["obj_id"], $a_inst); - } - } - - - /** - * export (sub)structure objects of structure object (see ilias_co.dtd) - * - * @param object $a_xml_writer ilXmlWriter object that receives the - * xml data - */ - function exportXMLStructureObjects(&$a_xml_writer, $a_inst, &$expLog) - { - $this->tree = new ilTree($this->getLmId()); - $this->tree->setTableNames('lm_tree', 'lm_data'); - $this->tree->setTreeTablePK("lm_id"); - - $childs = $this->tree->getChilds($this->getId()); - foreach ($childs as $child) - { - if($child["type"] != "st") - { - continue; - } - - // export xml to writer object - $structure_obj = new ilStructureObject($this->getContentObject(), - $child["obj_id"]); - $structure_obj->exportXML($a_xml_writer, $a_inst, $expLog); - unset($structure_obj); - } - } - - /** - * export object to fo - * - * @param object $a_xml_writer ilXmlWriter object that receives the - * xml data - */ - function exportFO(&$a_xml_writer) - { - - // fo:block (complete) - $attrs = array(); - $attrs["font-family"] = "Times"; - $attrs["font-size"] = "14pt"; - $a_xml_writer->xmlElement("fo:block", $attrs, $this->getTitle()); - - // page objects - $this->exportFOPageObjects($a_xml_writer); - } - - /** - * export page objects of structure object (see ilias_co.dtd) - * - * @param object $a_xml_writer ilXmlWriter object that receives the - * xml data - */ - function exportFOPageObjects(&$a_xml_writer) - { - $this->tree = new ilTree($this->getLmId()); - $this->tree->setTableNames('lm_tree', 'lm_data'); - $this->tree->setTreeTablePK("lm_id"); - - $childs = $this->tree->getChilds($this->getId()); - foreach ($childs as $child) - { - if($child["type"] != "pg") - { - continue; - } - - // export xml to writer object - $page_obj = new ilLMPageObject($this->getContentObject(), $child["obj_id"]); - $page_obj->exportFO($a_xml_writer); - } - } - - /** - * export (sub)structure objects of structure object (see ilias_co.dtd) - * - * @param object $a_xml_writer ilXmlWriter object that receives the - * xml data - */ - static function getChapterList($a_lm_id) - { - $tree = new ilTree($a_lm_id); - $tree->setTableNames('lm_tree', 'lm_data'); - $tree->setTreeTablePK("lm_id"); - - $chapters = array(); - $ndata = $tree->getNodeData($tree->readRootId()); - $childs = $tree->getSubtree($ndata); - foreach ($childs as $child) - { - if($child["type"] == "st") - { - $chapters[] = $child; - } - - } - return $chapters; - } - + public $is_alias; + public $origin_id; + public $tree; + + /** + * Constructor + * @access public + */ + public function __construct(&$a_content_obj, $a_id = 0) + { + $this->setType("st"); + parent::__construct($a_content_obj, $a_id); + } + + public function create($a_upload = false) + { + parent::create($a_upload); + } + + /** + * Delete Chapter + */ + public function delete($a_delete_meta_data = true) + { + // only relevant for online help authoring + include_once("./Services/Help/classes/class.ilHelpMapping.php"); + ilHelpMapping::removeScreenIdsOfChapter($this->getId()); + + $this->tree = new ilTree($this->getLmId()); + $this->tree->setTableNames('lm_tree', 'lm_data'); + $this->tree->setTreeTablePK("lm_id"); + $node_data = $this->tree->getNodeData($this->getId()); + $this->delete_rec($this->tree, $a_delete_meta_data); + $this->tree->deleteTree($node_data); + } + + /** + * Delete sub tree + */ + private function delete_rec(&$a_tree, $a_delete_meta_data = true) + { + $childs = $a_tree->getChilds($this->getId()); + foreach ($childs as $child) { + $obj = ilLMObjectFactory::getInstance($this->content_object, $child["obj_id"], false); + if (is_object($obj)) { + if ($obj->getType() == "st") { + $obj->delete_rec($a_tree, $a_delete_meta_data); + } + if ($obj->getType() == "pg") { + $obj->delete($a_delete_meta_data); + } + } + unset($obj); + } + parent::delete($a_delete_meta_data); + } + + /** + * copy chapter + */ + public function copy($a_target_lm) + { + $chap = new ilStructureObject($a_target_lm); + $chap->setTitle($this->getTitle()); + if ($this->getLMId() != $a_target_lm->getId()) { + $chap->setImportId("il__st_" . $this->getId()); + } + $chap->setLMId($a_target_lm->getId()); + $chap->setType($this->getType()); + $chap->setDescription($this->getDescription()); + $chap->create(true); + $a_copied_nodes[$this->getId()] = $chap->getId(); + + // copy meta data + include_once("Services/MetaData/classes/class.ilMD.php"); + $md = new ilMD($this->getLMId(), $this->getId(), $this->getType()); + $new_md = $md->cloneMD($a_target_lm->getId(), $chap->getId(), $this->getType()); + + // copy translations + include_once("./Modules/LearningModule/classes/class.ilLMObjTranslation.php"); + ilLMObjTranslation::copy($this->getId(), $chap->getId()); + + + return $chap; + } + + /** + * export object to xml (see ilias_co.dtd) + * + * @param object $a_xml_writer ilXmlWriter object that receives the + * xml data + */ + public function exportXML(&$a_xml_writer, $a_inst, &$expLog) + { + $expLog->write(date("[y-m-d H:i:s] ") . "Structure Object " . $this->getId()); + $attrs = array(); + $a_xml_writer->xmlStartTag("StructureObject", $attrs); + + // MetaData + $this->exportXMLMetaData($a_xml_writer); + + // StructureObjects + $this->exportXMLPageObjects($a_xml_writer, $a_inst); + + // PageObjects + $this->exportXMLStructureObjects($a_xml_writer, $a_inst, $expLog); + + // Layout + // not implemented + + $a_xml_writer->xmlEndTag("StructureObject"); + } + + + /** + * export structure objects meta data to xml (see ilias_co.dtd) + * + * @param object $a_xml_writer ilXmlWriter object that receives the + * xml data + */ + public function exportXMLMetaData(&$a_xml_writer) + { + include_once("Services/MetaData/classes/class.ilMD2XML.php"); + $md2xml = new ilMD2XML($this->getLMId(), $this->getId(), $this->getType()); + $md2xml->setExportMode(true); + $md2xml->startExport(); + $a_xml_writer->appendXML($md2xml->getXML()); + } + + public function modifyExportIdentifier($a_tag, $a_param, $a_value) + { + if ($a_tag == "Identifier" && $a_param == "Entry") { + $a_value = "il_" . IL_INST_ID . "_st_" . $this->getId(); + } + + return $a_value; + } + + /** + * get presentation title + * + */ + public static function _getPresentationTitle( + $a_st_id, + $a_mode = IL_CHAPTER_TITLE, + $a_include_numbers = false, + $a_time_scheduled_activation = false, + $a_force_content = false, + $a_lm_id = 0, + $a_lang = "-", + $a_include_short = false + ) { + global $DIC; + + $ilDB = $DIC->database(); + + if ($a_lm_id == 0) { + $a_lm_id = ilLMObject::_lookupContObjID($a_st_id); + } + + if ($a_lm_id == 0) { + return ""; + } + + // this is optimized when ilLMObject::preloadDataByLM is invoked (e.g. done in ilLMExplorerGUI) + $title = ""; + if ($a_include_short) { + $title = trim(ilLMObject::_lookupShortTitle($a_st_id)); + } + if ($title == "") { + $title = ilLMObject::_lookupTitle($a_st_id); + } + + // this is also optimized since ilObjectTranslation re-uses instances for one lm + include_once("./Services/Object/classes/class.ilObjectTranslation.php"); + $ot = ilObjectTranslation::getInstance($a_lm_id); + $languages = $ot->getLanguages(); + + if ($a_lang != "-" && $ot->getContentActivated() && isset($languages[$a_lang])) { + include_once("./Modules/LearningModule/classes/class.ilLMObjTranslation.php"); + $lmobjtrans = new ilLMObjTranslation($a_st_id, $a_lang); + $trans_title = ""; + if ($a_include_short) { + $trans_title = trim($lmobjtrans->getShortTitle()); + } + if ($trans_title == "") { + $trans_title = $lmobjtrans->getTitle(); + } + if ($trans_title != "") { + $title = $trans_title; + } + } + + include_once("./Modules/LearningModule/classes/class.ilLMTree.php"); + $tree = ilLMTree::getInstance($a_lm_id); + + if ($a_include_numbers) { + // this is optimized, since isInTree is cached + if ($tree->isInTree($a_st_id)) { + // optimization needed from here + + // get chapter tree node + $query = "SELECT * FROM lm_tree WHERE child = " . + $ilDB->quote($a_st_id, "integer") . " AND lm_id = " . + $ilDB->quote($a_lm_id, "integer"); + $tree_set = $ilDB->query($query); + $tree_node = $tree_set->fetchRow(ilDBConstants::FETCHMODE_ASSOC); + $depth = $tree_node["depth"]; + + $nr = $tree->getChildSequenceNumber($tree_node, "st") . " "; + for ($i = $depth - 1; $i > 1; $i--) { + // get next parent tree node + $query = "SELECT * FROM lm_tree WHERE child = " . + $ilDB->quote($tree_node["parent"], "integer") . " AND lm_id = " . + $ilDB->quote($a_lm_id, "integer"); + $tree_set = $ilDB->query($query); + $tree_node = $tree_set->fetchRow(ilDBConstants::FETCHMODE_ASSOC); + $seq = $tree->getChildSequenceNumber($tree_node, "st"); + + $nr = $seq . "." . $nr; + } + } + } + + return $nr . $title; + } + + + + /** + * export page objects of structure object (see ilias_co.dtd) + * + * @param object $a_xml_writer ilXmlWriter object that receives the + * xml data + */ + public function exportXMLPageObjects(&$a_xml_writer, $a_inst = 0) + { + include_once './Modules/LearningModule/classes/class.ilLMPageObject.php'; + + $this->tree = new ilTree($this->getLmId()); + $this->tree->setTableNames('lm_tree', 'lm_data'); + $this->tree->setTreeTablePK("lm_id"); + + $childs = $this->tree->getChilds($this->getId()); + foreach ($childs as $child) { + if ($child["type"] != "pg") { + continue; + } + + // export xml to writer object + ilLMPageObject::_exportXMLAlias($a_xml_writer, $child["obj_id"], $a_inst); + } + } + + + /** + * export (sub)structure objects of structure object (see ilias_co.dtd) + * + * @param object $a_xml_writer ilXmlWriter object that receives the + * xml data + */ + public function exportXMLStructureObjects(&$a_xml_writer, $a_inst, &$expLog) + { + $this->tree = new ilTree($this->getLmId()); + $this->tree->setTableNames('lm_tree', 'lm_data'); + $this->tree->setTreeTablePK("lm_id"); + + $childs = $this->tree->getChilds($this->getId()); + foreach ($childs as $child) { + if ($child["type"] != "st") { + continue; + } + + // export xml to writer object + $structure_obj = new ilStructureObject( + $this->getContentObject(), + $child["obj_id"] + ); + $structure_obj->exportXML($a_xml_writer, $a_inst, $expLog); + unset($structure_obj); + } + } + + /** + * export object to fo + * + * @param object $a_xml_writer ilXmlWriter object that receives the + * xml data + */ + public function exportFO(&$a_xml_writer) + { + + // fo:block (complete) + $attrs = array(); + $attrs["font-family"] = "Times"; + $attrs["font-size"] = "14pt"; + $a_xml_writer->xmlElement("fo:block", $attrs, $this->getTitle()); + + // page objects + $this->exportFOPageObjects($a_xml_writer); + } + + /** + * export page objects of structure object (see ilias_co.dtd) + * + * @param object $a_xml_writer ilXmlWriter object that receives the + * xml data + */ + public function exportFOPageObjects(&$a_xml_writer) + { + $this->tree = new ilTree($this->getLmId()); + $this->tree->setTableNames('lm_tree', 'lm_data'); + $this->tree->setTreeTablePK("lm_id"); + + $childs = $this->tree->getChilds($this->getId()); + foreach ($childs as $child) { + if ($child["type"] != "pg") { + continue; + } + + // export xml to writer object + $page_obj = new ilLMPageObject($this->getContentObject(), $child["obj_id"]); + $page_obj->exportFO($a_xml_writer); + } + } + + /** + * export (sub)structure objects of structure object (see ilias_co.dtd) + * + * @param object $a_xml_writer ilXmlWriter object that receives the + * xml data + */ + public static function getChapterList($a_lm_id) + { + $tree = new ilTree($a_lm_id); + $tree->setTableNames('lm_tree', 'lm_data'); + $tree->setTreeTablePK("lm_id"); + + $chapters = array(); + $ndata = $tree->getNodeData($tree->readRootId()); + $childs = $tree->getSubtree($ndata); + foreach ($childs as $child) { + if ($child["type"] == "st") { + $chapters[] = $child; + } + } + return $chapters; + } } -?> diff --git a/Modules/LearningModule/classes/class.ilStructureObjectGUI.php b/Modules/LearningModule/classes/class.ilStructureObjectGUI.php index b909e10411ef66c5b0fc3ced695b44bba9b5832d..68b35133a37b9fa2cd96b6878caba4a231b63e8b 100755 --- a/Modules/LearningModule/classes/class.ilStructureObjectGUI.php +++ b/Modules/LearningModule/classes/class.ilStructureObjectGUI.php @@ -20,1061 +20,1025 @@ require_once("./Modules/LearningModule/classes/class.ilLMObject.php"); */ class ilStructureObjectGUI extends ilLMObjectGUI { - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var Logger - */ - protected $log; - - var $obj; // structure object - var $tree; - - /** - * Constructor - * @access public - */ - function __construct(&$a_content_obj, &$a_tree) - { - global $DIC; - - $this->tree = $DIC->repositoryTree(); - $this->user = $DIC->user(); - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->error = $DIC["ilErr"]; - $this->tabs = $DIC->tabs(); - $this->log = $DIC["ilLog"]; - $this->tpl = $DIC["tpl"]; - parent::__construct($a_content_obj); - $this->tree = $a_tree; - } - - /** - * set structure object - * - * @param object $a_st_object structure object - */ - function setStructureObject(&$a_st_object) - { - $this->obj = $a_st_object; - } - - - /** - * this function is called by condition handler gui interface - */ - function getType() - { - return "st"; - } - - /** - * execute command - */ - function executeCommand() - { -//echo "
:cmd:".$this->ctrl->getCmd().":cmdClass:".$this->ctrl->getCmdClass().":"; - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - switch($next_class) - { - case 'ilobjectmetadatagui': - - $this->setTabs(); - - include_once 'Services/Object/classes/class.ilObjectMetaDataGUI.php'; - $md_gui = new ilObjectMetaDataGUI($this->content_object, $this->obj->getType(), $this->obj->getId()); - $md_gui->addMDObserver($this->obj, 'MDUpdateListener', 'General'); - $md_gui->addMDObserver($this->obj, 'MDUpdateListener', 'Educational'); // #9510 - $this->ctrl->forwardCommand($md_gui); - break; - - case "ilconditionhandlergui": - $ilTabs = $this->tabs; - include_once './Services/Conditions/classes/class.ilConditionHandlerGUI.php'; - - $this->setTabs(); - $this->initConditionHandlerInterface(); - $this->ctrl->forwardCommand($this->condHI); - $ilTabs->setTabActive('preconditions'); - break; - - default: - if($cmd == 'listConditions') - { - $this->setTabs(); - $this->initConditionHandlerInterface(); - $this->condHI->executeCommand(); - } - elseif(($cmd == "create") && ($_POST["new_type"] == "pg")) - { - $this->setTabs(); - $pg_gui = new ilLMPageObjectGUI($this->content_object); - $pg_gui->executeCommand(); - } - else - { - $this->$cmd(); - } - break; - } - } - - - /** - * create new page or chapter in chapter - */ - function create() - { - if ($_GET["obj_id"] != "") - { - $this->setTabs(); - } - parent::create(); - } - - function edit() - { - $this->view(); - } - - /* - * display pages of structure object - */ - function view() - { - $tree = $this->tree; - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->showHierarchy(); - } - - - /** - * Show subhiearchy of pages and subchapters - */ - function showHierarchy() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->setTabs(); - - $ilCtrl->setParameter($this, "backcmd", "showHierarchy"); - - include_once("./Modules/LearningModule/classes/class.ilChapterHierarchyFormGUI.php"); - $form_gui = new ilChapterHierarchyFormGUI($this->content_object->getType(), $_GET["transl"]); - $form_gui->setFormAction($ilCtrl->getFormAction($this)); - $form_gui->setTitle($this->obj->getTitle()); - $form_gui->setIcon(ilUtil::getImagePath("icon_st.svg")); - $form_gui->setTree($this->tree); - $form_gui->setCurrentTopNodeId($this->obj->getId()); - $form_gui->addMultiCommand($lng->txt("delete"), "delete"); - $form_gui->addMultiCommand($lng->txt("cut"), "cutItems"); - $form_gui->addMultiCommand($lng->txt("copy"), "copyItems"); - $form_gui->addMultiCommand($lng->txt("cont_de_activate"), "activatePages"); - if ($this->content_object->getLayoutPerPage()) - { - $form_gui->addMultiCommand($lng->txt("cont_set_layout"), "setPageLayout"); - } - $form_gui->setDragIcon(ilUtil::getImagePath("icon_pg.svg")); - $form_gui->addCommand($lng->txt("cont_save_all_titles"), "saveAllTitles"); - $form_gui->addHelpItem($lng->txt("cont_chapters_after_pages")); - $up_gui = "ilobjlearningmodulegui"; - $ilCtrl->setParameterByClass($up_gui, "active_node", $this->obj->getId()); - $ilCtrl->setParameterByClass($up_gui, "active_node", ""); - - $ctpl = new ilTemplate("tpl.chap_and_pages.html", true, true, "Modules/LearningModule"); - $ctpl->setVariable("HIERARCHY_FORM", $form_gui->getHTML()); - $ilCtrl->setParameter($this, "obj_id", $_GET["obj_id"]); - - include_once("./Modules/LearningModule/classes/class.ilObjContentObjectGUI.php"); - $ml_head = ilObjContentObjectGUI::getMultiLangHeader($this->content_object->getId(), $this); - - $this->tpl->setContent($ml_head.$ctpl->get()); - } - - /** - * Copy items to clipboard, then cut them from the current tree - */ - function cutItems($a_return = "view") - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $items = ilUtil::stripSlashesArray($_POST["id"]); - if (!is_array($items)) - { - ilUtil::sendFailure($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "showHierarchy"); - } - - $todel = array(); // delete IDs < 0 (needed for non-js editing) - foreach($items as $k => $item) - { - if ($item < 0) - { - $todel[] = $k; - } - } - foreach($todel as $k) - { - unset($items[$k]); - } - - if (!ilLMObject::uniqueTypesCheck($items)) - { - ilUtil::sendFailure($lng->txt("cont_choose_pages_or_chapters_only"), true); - $ilCtrl->redirect($this, "showHierarchy"); - } - - ilLMObject::clipboardCut($this->content_object->getId(), $items); - ilEditClipboard::setAction("cut"); - //ilUtil::sendInfo($this->lng->txt("msg_cut_clipboard"), true); - ilUtil::sendInfo($lng->txt("cont_selected_items_have_been_cut"), true); - - $ilCtrl->redirect($this, $a_return); - } - - /** - * Copy items to clipboard - */ - function copyItems($a_return = "view") - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $items = ilUtil::stripSlashesArray($_POST["id"]); - if (!is_array($items)) - { - ilUtil::sendFailure($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "showHierarchy"); - } - - $todel = array(); // delete IDs < 0 (needed for non-js editing) - foreach($items as $k => $item) - { - if ($item < 0) - { - $todel[] = $k; - } - } - foreach($todel as $k) - { - unset($items[$k]); - } - - if (!ilLMObject::uniqueTypesCheck($items)) - { - ilUtil::sendFailure($lng->txt("cont_choose_pages_or_chapters_only"), true); - $ilCtrl->redirect($this, "showHierarchy"); - } - - ilLMObject::clipboardCopy($this->content_object->getId(), $items); - ilEditClipboard::setAction("copy"); - - ilUtil::sendInfo($lng->txt("cont_selected_items_have_been_copied"), true); - $ilCtrl->redirect($this, $a_return); - } - - /** - * Save all titles of chapters/pages - */ - function saveAllTitles() - { - $ilCtrl = $this->ctrl; - - ilLMObject::saveTitles($this->content_object, ilUtil::stripSlashesArray($_POST["title"]), $_GET["transl"]); - - ilUtil::sendSuccess($this->lng->txt("lm_save_titles"), true); - $ilCtrl->redirect($this, "showHierarchy"); - } - - /* - * display subchapters of structure object - */ - function subchap() - { - $tree = $this->tree; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilUser = $this->user; - - $this->setTabs(); - - $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.structure_edit.html", "Modules/LearningModule"); - $num = 0; - - $this->tpl->setCurrentBlock("form"); - $this->ctrl->setParameter($this, "backcmd", "subchap"); - $this->tpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this)); - $this->tpl->setVariable("HEADER_TEXT", $this->lng->txt("cont_subchapters")); - $this->tpl->setVariable("CHECKBOX_TOP", IL_FIRST_NODE); - - $cnt = 0; - $childs = $this->tree->getChilds($this->obj->getId()); - foreach ($childs as $child) - { - if($child["type"] != "st") - { - continue; - } - $this->tpl->setCurrentBlock("table_row"); - // color changing - $css_row = ilUtil::switchColor($cnt++,"tblrow1","tblrow2"); - - // checkbox - $this->tpl->setVariable("CHECKBOX_ID", $child["obj_id"]); - $this->tpl->setVariable("CSS_ROW", $css_row); - $this->tpl->setVariable("IMG_OBJ", ilUtil::getImagePath("icon_st.svg")); - - // type - $this->ctrl->setParameterByClass("ilStructureObjectGUI", "obj_id", $child["obj_id"]); - $link = $this->ctrl->getLinkTargetByClass("ilStructureObjectGUI", "view"); - $this->tpl->setVariable("LINK_TARGET", $link); - - // title - $this->tpl->setVariable("TEXT_CONTENT", - ilStructureObject::_getPresentationTitle($child["obj_id"], IL_CHAPTER_TITLE, - $this->content_object->isActiveNumbering())); - - $this->tpl->parseCurrentBlock(); - } - if($cnt == 0) - { - $this->tpl->setCurrentBlock("notfound"); - $this->tpl->setVariable("NUM_COLS", 3); - $this->tpl->setVariable("TXT_OBJECT_NOT_FOUND", $this->lng->txt("obj_not_found")); - $this->tpl->parseCurrentBlock(); - } - //else - //{ - // SHOW VALID ACTIONS - $this->tpl->setVariable("NUM_COLS", 3); - $acts = array("delete" => "delete", "cutChapter" => "cut", - "copyChapter" => "copyChapter"); - if ($ilUser->clipboardHasObjectsOfType("st")) - { - $acts["pasteChapter"] = "pasteChapter"; - } - $this->showActions($acts); - //} - - // SHOW POSSIBLE SUB OBJECTS - $this->tpl->setVariable("NUM_COLS", 3); - //$this->showPossibleSubObjects("st"); - $subobj = array("st"); - $opts = ilUtil::formSelect(12,"new_type",$subobj); - //$this->tpl->setVariable("IMG_ARROW", ilUtil::getImagePath("arrow_downright.svg")); - $this->tpl->setCurrentBlock("add_object"); - $this->tpl->setVariable("SELECT_OBJTYPE", $opts); - //$this->tpl->setVariable("FORMACTION_OBJ_ADD", "adm_object.php?cmd=create&ref_id=".$_GET["ref_id"]); - $this->tpl->setVariable("BTN_NAME", "create"); - $this->tpl->setVariable("TXT_ADD", $this->lng->txt("insert")); - $this->tpl->parseCurrentBlock(); - - //$this->tpl->setVariable("NUM_COLS", 2); - //$this->showPossibleSubObjects("st"); - - $this->tpl->setCurrentBlock("form"); - $this->tpl->parseCurrentBlock(); - - $ilCtrl->setParameter($this, "obj_id", $_GET["obj_id"]); - - } - - /** - * output a cell in object list - */ - function add_cell($val, $link = "") - { - if(!empty($link)) - { - $this->tpl->setCurrentBlock("begin_link"); - $this->tpl->setVariable("LINK_TARGET", $link); - $this->tpl->parseCurrentBlock(); - $this->tpl->touchBlock("end_link"); - } - - $this->tpl->setCurrentBlock("text"); - $this->tpl->setVariable("TEXT_CONTENT", $val); - $this->tpl->parseCurrentBlock(); - $this->tpl->setCurrentBlock("table_cell"); - $this->tpl->parseCurrentBlock(); - } - - - /** - * save new chapter - */ - function save() - { - - $this->obj = new ilStructureObject($this->content_object); - - $this->obj->setType("st"); - $this->obj->setTitle(ilUtil::stripSlashes($_POST["Fobject"]["title"])); - $this->obj->setDescription(ilUtil::stripSlashes($_POST["Fobject"]["desc"])); - $this->obj->setLMId($this->content_object->getId()); - $this->obj->create(); - - $this->putInTree(); - - // check the tree - $this->checkTree(); - - if (!empty($_GET["obj_id"])) - { - $this->ctrl->redirect($this, "subchap"); - } - - } - - /** - * put chapter into tree - */ - function putInTree() - { -//echo "st:putInTree"; - // chapters should be behind pages in the tree - // so if target is first node, the target is substituted with - // the last child of type pg - if ($_GET["target"] == IL_FIRST_NODE) - { - $tree = new ilTree($this->content_object->getId()); - $tree->setTableNames('lm_tree','lm_data'); - $tree->setTreeTablePK("lm_id"); - - // determine parent node id - $parent_id = (!empty($_GET["obj_id"])) - ? $_GET["obj_id"] - : $tree->getRootId(); - // determine last child of type pg - $childs = $tree->getChildsByType($parent_id, "pg"); - if (count($childs) != 0) - { - $_GET["target"] = $childs[count($childs) - 1]["obj_id"]; - } - } - if (empty($_GET["target"])) - { - $_GET["target"] = IL_LAST_NODE; - } - - parent::putInTree(); - } - - /** - * cut page - */ - function cutPage() - { - $this->cutItems(); - } - - /** - * copy page - */ - function copyPage() - { - $this->copyItems(); - } - - /** - * paste page - */ - function pastePage() - { - $ilUser = $this->user; - $ilErr = $this->error; - - if (!$ilUser->clipboardHasObjectsOfType("pg")) - { - $ilErr->raiseError($this->lng->txt("no_page_in_clipboard"), $ilErr->MESSAGE); - } - - return $this->insertPageClip(); - } - - - /** - * Cut chapter(s) - */ - function cutChapter() - { - $this->cutItems("subchap"); - } - - /** - * copy a single chapter (selection) - */ - function copyChapter() - { - $this->copyItems("subchap"); - } - - /** - * paste chapter - */ - function pasteChapter() - { - $ilUser = $this->user; - - return $this->insertChapterClip(false, "subchap"); - } - - /** - * activates or deactivates pages - */ - function activatePages() - { - $lng = $this->lng; - - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - if (is_array($_POST["id"])) - { - $act_items = array(); - // get all "top" ids, i.e. remove ids, that have a selected parent - foreach($_POST["id"] as $id) - { - $path = $this->tree->getPathId($id); - $take = true; - foreach($path as $path_id) - { - if ($path_id != $id && in_array($path_id, $_POST["id"])) - { - $take = false; - } - } - if ($take) - { - $act_items[] = $id; - } - } - - - foreach($act_items as $id) - { - $childs = $this->tree->getChilds($id); - foreach($childs as $child) - { - if (ilLMObject::_lookupType($child["child"]) == "pg") - { - $act = ilLMPage::_lookupActive($child["child"], - $this->content_object->getType()); - ilLMPage::_writeActive($child["child"], - $this->content_object->getType(), !$act); - } - } - if (ilLMObject::_lookupType($id) == "pg") - { - $act = ilLMPage::_lookupActive($id, - $this->content_object->getType()); - ilLMPage::_writeActive($id, - $this->content_object->getType(), !$act); - } - } - } - else - { - ilUtil::sendFailure($lng->txt("no_checkbox"), true); - } - - $this->ctrl->redirect($this, "view"); - } - - // - // Condition handling stuff - // - - function initConditionHandlerInterface() - { - include_once("./Services/Conditions/classes/class.ilConditionHandlerGUI.php"); - - $this->condHI = new ilConditionHandlerGUI($this); - $this->condHI->setBackButtons(array()); - $this->condHI->setAutomaticValidation(false); - $this->condHI->setTargetType("st"); - $this->condHI->setTargetRefId($this->content_object->getRefId()); - $this->condHI->setTargetId($this->obj->getId()); - $this->condHI->setTargetTitle($this->obj->getTitle()); - } - - - /** - * cancel creation of new page or chapter - */ - function cancel() - { - if ($_GET["obj_id"] != 0) - { - if ($_GET["new_type"] == "pg") - { - $this->ctrl->redirect($this, "view"); - } - else - { - $this->ctrl->redirect($this, "subchap"); - } - } - } - - - /** - * output tabs - */ - function setTabs() - { - $ilTabs = $this->tabs; - $ilUser = $this->user; - $lng = $this->lng; - - // subelements - $ilTabs->addTarget("cont_pages_and_subchapters", - $this->ctrl->getLinkTarget($this,'showHierarchy'), - array("view", "showHierarchy"), get_class($this)); - - // preconditions - $ilTabs->addTarget("preconditions", - $this->ctrl->getLinkTarget($this, 'listConditions'), - "listConditions", get_class($this)); - - // metadata - include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php"; - $mdgui = new ilObjectMetaDataGUI($this->content_object, $this->obj->getType(), $this->obj->getId()); - $mdtab = $mdgui->getTab(); - if($mdtab) - { - $ilTabs->addTarget("meta_data", - $mdtab, - "", "ilmdeditorgui"); - } - - $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_st.svg")); - $this->tpl->setTitle( - $this->lng->txt($this->obj->getType()).": ".$this->obj->getTitle()); - - // presentation view - $ilTabs->addNonTabbedLink("pres_mode", $lng->txt("cont_presentation_view"), - ILIAS_HTTP_PATH."/goto.php?target=st_".$this->obj->getId(), "_top"); - } - - /** - * redirect script - * - * @param string $a_target - */ - public static function _goto($a_target, $a_target_ref_id = "") - { - global $DIC; - - $rbacsystem = $DIC->rbac()->system(); - $ilErr = $DIC["ilErr"]; - $lng = $DIC->language(); - $ilAccess = $DIC->access(); - - // determine learning object - $lm_id = ilLMObject::_lookupContObjID($a_target); - - // get all references - $ref_ids = ilObject::_getAllReferences($lm_id); - - // always try passed ref id first - if (in_array($a_target_ref_id, $ref_ids)) - { - $ref_ids = array_merge(array($a_target_ref_id), $ref_ids); - } - - // check read permissions - foreach ($ref_ids as $ref_id) - { - // Permission check - if ($ilAccess->checkAccess("read", "", $ref_id)) - { - // don't redirect anymore, just set parameters - // (goto.php includes "ilias.php") - $_GET["baseClass"] = "ilLMPresentationGUI"; - $_GET["obj_id"] = $a_target; - $_GET["ref_id"] = $ref_id; - include_once("ilias.php"); - exit;; - } - } - - if ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) - { - ilUtil::sendFailure(sprintf($lng->txt("msg_no_perm_read_item"), - ilObject::_lookupTitle($lm_id)), true); - include_once("./Services/Object/classes/class.ilObjectGUI.php"); - ilObjectGUI::_gotoRepositoryRoot(); - } - - $ilErr->raiseError($lng->txt("msg_no_perm_read_lm"), $ilErr->FATAL); - } - - /** - * Insert (multiple) chapters at node - */ - function insertChapter($a_as_sub = false) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - include_once("./Modules/LearningModule/classes/class.ilChapterHierarchyFormGUI.php"); - - $num = ilChapterHierarchyFormGUI::getPostMulti(); - $node_id = ilChapterHierarchyFormGUI::getPostNodeId(); - - if ($a_as_sub) // as subchapter - { - if (!ilChapterHierarchyFormGUI::getPostFirstChild()) // insert under parent - { - $parent_id = $node_id; - $target = ""; - } - else // we shouldnt end up here - { - $ilCtrl->redirect($this, "showHierarchy"); - return; - } - } - else // as chapter - { - if (!ilChapterHierarchyFormGUI::getPostFirstChild()) // insert after node id - { - $parent_id = $this->tree->getParentId($node_id); - $target = $node_id; - } - else // insert as first child - { - $parent_id = $node_id; - $target = IL_FIRST_NODE; - } - } - for ($i = 1; $i <= $num; $i++) - { - $chap = new ilStructureObject($this->content_object); - $chap->setType("st"); - $chap->setTitle($lng->txt("cont_new_chap")); - $chap->setLMId($this->content_object->getId()); - $chap->create(); - ilLMObject::putInTree($chap, $parent_id, $target); - } - - $ilCtrl->redirect($this, "view"); - } - - /** - * Insert (multiple) subchapters at node - */ - function insertSubchapter() - { - $ilCtrl = $this->ctrl; - - $this->insertChapter(true); - } - - /** - * Insert Chapter from clipboard - */ - function insertChapterClip($a_as_sub = false, $a_return = "view") - { - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - $ilLog = $this->log; - - $ilLog->write("Insert Chapter From Clipboard"); - - include_once("./Modules/LearningModule/classes/class.ilChapterHierarchyFormGUI.php"); - - $node_id = ilChapterHierarchyFormGUI::getPostNodeId(); - $first_child = ilChapterHierarchyFormGUI::getPostFirstChild(); - - if ($a_as_sub) // as subchapter - { - if (!$first_child) // insert under parent - { - $parent_id = $node_id; - $target = ""; - } - else // we shouldnt end up here - { - $ilCtrl->redirect($this, "showHierarchy"); - return; - } - } - else // as chapter - { - if (!$first_child) // insert after node id - { - $parent_id = $this->tree->getParentId($node_id); - $target = $node_id; - } - else // insert as first child - { - $parent_id = $node_id; - $target = IL_FIRST_NODE; - - // do not move a chapter in front of a page - $childs = $this->tree->getChildsByType($parent_id, "pg"); - if (count($childs) != 0) - { - $target = $childs[count($childs) - 1]["obj_id"]; - } - } - } - - // copy and paste - $chapters = $ilUser->getClipboardObjects("st", true); - $copied_nodes = array(); - - foreach ($chapters as $chap) - { - $ilLog->write("Call pasteTree, Target LM: ".$this->content_object->getId().", Chapter ID: ".$chap["id"] - .", Parent ID: ".$parent_id.", Target: ".$target); - $cid = ilLMObject::pasteTree($this->content_object, $chap["id"], $parent_id, - $target, $chap["insert_time"], $copied_nodes, - (ilEditClipboard::getAction() == "copy")); - $target = $cid; - } - ilLMObject::updateInternalLinks($copied_nodes); - - if (ilEditClipboard::getAction() == "cut") - { - $ilUser->clipboardDeleteObjectsOfType("pg"); - $ilUser->clipboardDeleteObjectsOfType("st"); - ilEditClipboard::clear(); - } - - $this->content_object->checkTree(); - $ilCtrl->redirect($this, $a_return); - } - - /** - * Insert Chapter from clipboard - */ - function insertSubchapterClip() - { - $this->insertChapterClip(true); - } - - /** - * Insert (multiple) pages at node - */ - function insertPage() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - include_once("./Modules/LearningModule/classes/class.ilChapterHierarchyFormGUI.php"); - - $num = ilChapterHierarchyFormGUI::getPostMulti(); - $node_id = ilChapterHierarchyFormGUI::getPostNodeId(); - - if (!ilChapterHierarchyFormGUI::getPostFirstChild()) // insert after node id - { - $parent_id = $this->tree->getParentId($node_id); - $target = $node_id; - } - else // insert as first child - { - $parent_id = $node_id; - $target = IL_FIRST_NODE; - } - - for ($i = 1; $i <= $num; $i++) - { - $page = new ilLMPageObject($this->content_object); - $page->setType("pg"); - $page->setTitle($lng->txt("cont_new_page")); - $page->setLMId($this->content_object->getId()); - $page->create(); - ilLMObject::putInTree($page, $parent_id, $target); - } - - $ilCtrl->redirect($this, "showHierarchy"); - } - - /** - * Insert pages from clipboard - */ - function insertPageClip() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - include_once("./Modules/LearningModule/classes/class.ilChapterHierarchyFormGUI.php"); - - $node_id = ilChapterHierarchyFormGUI::getPostNodeId(); - $first_child = ilChapterHierarchyFormGUI::getPostFirstChild(); - - if (!$first_child) // insert after node id - { - $parent_id = $this->tree->getParentId($node_id); - $target = $node_id; - } - else // insert as first child - { - $parent_id = $node_id; - $target = IL_FIRST_NODE; - } - - // cut and paste - $pages = $ilUser->getClipboardObjects("pg"); - $copied_nodes = array(); - foreach ($pages as $pg) - { - $cid = ilLMObject::pasteTree($this->content_object, $pg["id"], $parent_id, $target, - $pg["insert_time"], $copied_nodes, - (ilEditClipboard::getAction() == "copy")); - $target = $cid; - } - ilLMObject::updateInternalLinks($copied_nodes); - - if (ilEditClipboard::getAction() == "cut") - { - $ilUser->clipboardDeleteObjectsOfType("pg"); - $ilUser->clipboardDeleteObjectsOfType("st"); - ilEditClipboard::clear(); - } - - $ilCtrl->redirect($this, "view"); - } - - - /** - * Perform drag and drop action - */ - function proceedDragDrop() - { - $ilCtrl = $this->ctrl; - -//echo "-".$_POST["il_hform_source_id"]."-".$_POST["il_hform_target_id"]."-".$_POST["il_hform_fc"]."-"; - $this->content_object->executeDragDrop($_POST["il_hform_source_id"], $_POST["il_hform_target_id"], - $_POST["il_hform_fc"], $_POST["il_hform_as_subitem"]); - $ilCtrl->redirect($this, "showHierarchy"); - } - - //// - //// Pages layout - //// - - /** - * Set layout for multipl pages - */ - function setPageLayout() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if (!is_array($_POST["id"])) - { - ilUtil::sendFailure($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "showHierarchy"); - } - - $this->initSetPageLayoutForm(); - - $tpl->setContent($this->form->getHTML()); - } - - /** - * Init set page layout form. - */ - public function initSetPageLayoutForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - if (is_array($_POST["id"])) - { - foreach ($_POST["id"] as $id) - { - $hi = new ilHiddenInputGUI("id[]"); - $hi->setValue($id); - $this->form->addItem($hi); - } - } - $layout = ilObjContentObjectGUI::getLayoutOption($lng->txt("cont_layout"), "layout", - $this->content_object->getLayout()); - - $this->form->addItem($layout); - - $this->form->addCommandButton("savePageLayout", $lng->txt("save")); - $this->form->addCommandButton("showHierarchy", $lng->txt("cancel")); - - $this->form->setTitle($lng->txt("cont_set_layout")); - $this->form->setFormAction($ilCtrl->getFormAction($this)); - - } - - /** - * Save page layout - */ - function savePageLayout() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - foreach ($_POST["id"] as $id) - { - $id = ilUtil::stripSlashes($id); - ilLMPageObject::writeLayout(ilUtil::stripSlashes($id), - ilUtil::stripSlashes($_POST["layout"]), - $this->content_object); - } - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "showHierarchy"); - } - - /** - * Edit master language - * - * @param - * @return - */ - function editMasterLanguage() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameter($this, "transl", ""); - $ilCtrl->redirect($this, "showHierarchy"); - } - - /** - * Switch to language - * - * @param - * @return - */ - function switchToLanguage() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameter($this, "transl", $_GET["totransl"]); - $ilCtrl->redirect($this, "showHierarchy"); - } - + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var Logger + */ + protected $log; + + public $obj; // structure object + public $tree; + + /** + * Constructor + * @access public + */ + public function __construct(&$a_content_obj, &$a_tree) + { + global $DIC; + + $this->tree = $DIC->repositoryTree(); + $this->user = $DIC->user(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->error = $DIC["ilErr"]; + $this->tabs = $DIC->tabs(); + $this->log = $DIC["ilLog"]; + $this->tpl = $DIC["tpl"]; + parent::__construct($a_content_obj); + $this->tree = $a_tree; + } + + /** + * set structure object + * + * @param object $a_st_object structure object + */ + public function setStructureObject(&$a_st_object) + { + $this->obj = $a_st_object; + } + + + /** + * this function is called by condition handler gui interface + */ + public function getType() + { + return "st"; + } + + /** + * execute command + */ + public function executeCommand() + { + //echo "
:cmd:".$this->ctrl->getCmd().":cmdClass:".$this->ctrl->getCmdClass().":"; + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + switch ($next_class) { + case 'ilobjectmetadatagui': + + $this->setTabs(); + + include_once 'Services/Object/classes/class.ilObjectMetaDataGUI.php'; + $md_gui = new ilObjectMetaDataGUI($this->content_object, $this->obj->getType(), $this->obj->getId()); + $md_gui->addMDObserver($this->obj, 'MDUpdateListener', 'General'); + $md_gui->addMDObserver($this->obj, 'MDUpdateListener', 'Educational'); // #9510 + $this->ctrl->forwardCommand($md_gui); + break; + + case "ilconditionhandlergui": + $ilTabs = $this->tabs; + include_once './Services/Conditions/classes/class.ilConditionHandlerGUI.php'; + + $this->setTabs(); + $this->initConditionHandlerInterface(); + $this->ctrl->forwardCommand($this->condHI); + $ilTabs->setTabActive('preconditions'); + break; + + default: + if ($cmd == 'listConditions') { + $this->setTabs(); + $this->initConditionHandlerInterface(); + $this->condHI->executeCommand(); + } elseif (($cmd == "create") && ($_POST["new_type"] == "pg")) { + $this->setTabs(); + $pg_gui = new ilLMPageObjectGUI($this->content_object); + $pg_gui->executeCommand(); + } else { + $this->$cmd(); + } + break; + } + } + + + /** + * create new page or chapter in chapter + */ + public function create() + { + if ($_GET["obj_id"] != "") { + $this->setTabs(); + } + parent::create(); + } + + public function edit() + { + $this->view(); + } + + /* + * display pages of structure object + */ + public function view() + { + $tree = $this->tree; + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->showHierarchy(); + } + + + /** + * Show subhiearchy of pages and subchapters + */ + public function showHierarchy() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $this->setTabs(); + + $ilCtrl->setParameter($this, "backcmd", "showHierarchy"); + + include_once("./Modules/LearningModule/classes/class.ilChapterHierarchyFormGUI.php"); + $form_gui = new ilChapterHierarchyFormGUI($this->content_object->getType(), $_GET["transl"]); + $form_gui->setFormAction($ilCtrl->getFormAction($this)); + $form_gui->setTitle($this->obj->getTitle()); + $form_gui->setIcon(ilUtil::getImagePath("icon_st.svg")); + $form_gui->setTree($this->tree); + $form_gui->setCurrentTopNodeId($this->obj->getId()); + $form_gui->addMultiCommand($lng->txt("delete"), "delete"); + $form_gui->addMultiCommand($lng->txt("cut"), "cutItems"); + $form_gui->addMultiCommand($lng->txt("copy"), "copyItems"); + $form_gui->addMultiCommand($lng->txt("cont_de_activate"), "activatePages"); + if ($this->content_object->getLayoutPerPage()) { + $form_gui->addMultiCommand($lng->txt("cont_set_layout"), "setPageLayout"); + } + $form_gui->setDragIcon(ilUtil::getImagePath("icon_pg.svg")); + $form_gui->addCommand($lng->txt("cont_save_all_titles"), "saveAllTitles"); + $form_gui->addHelpItem($lng->txt("cont_chapters_after_pages")); + $up_gui = "ilobjlearningmodulegui"; + $ilCtrl->setParameterByClass($up_gui, "active_node", $this->obj->getId()); + $ilCtrl->setParameterByClass($up_gui, "active_node", ""); + + $ctpl = new ilTemplate("tpl.chap_and_pages.html", true, true, "Modules/LearningModule"); + $ctpl->setVariable("HIERARCHY_FORM", $form_gui->getHTML()); + $ilCtrl->setParameter($this, "obj_id", $_GET["obj_id"]); + + include_once("./Modules/LearningModule/classes/class.ilObjContentObjectGUI.php"); + $ml_head = ilObjContentObjectGUI::getMultiLangHeader($this->content_object->getId(), $this); + + $this->tpl->setContent($ml_head . $ctpl->get()); + } + + /** + * Copy items to clipboard, then cut them from the current tree + */ + public function cutItems($a_return = "view") + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $items = ilUtil::stripSlashesArray($_POST["id"]); + if (!is_array($items)) { + ilUtil::sendFailure($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "showHierarchy"); + } + + $todel = array(); // delete IDs < 0 (needed for non-js editing) + foreach ($items as $k => $item) { + if ($item < 0) { + $todel[] = $k; + } + } + foreach ($todel as $k) { + unset($items[$k]); + } + + if (!ilLMObject::uniqueTypesCheck($items)) { + ilUtil::sendFailure($lng->txt("cont_choose_pages_or_chapters_only"), true); + $ilCtrl->redirect($this, "showHierarchy"); + } + + ilLMObject::clipboardCut($this->content_object->getId(), $items); + ilEditClipboard::setAction("cut"); + //ilUtil::sendInfo($this->lng->txt("msg_cut_clipboard"), true); + ilUtil::sendInfo($lng->txt("cont_selected_items_have_been_cut"), true); + + $ilCtrl->redirect($this, $a_return); + } + + /** + * Copy items to clipboard + */ + public function copyItems($a_return = "view") + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $items = ilUtil::stripSlashesArray($_POST["id"]); + if (!is_array($items)) { + ilUtil::sendFailure($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "showHierarchy"); + } + + $todel = array(); // delete IDs < 0 (needed for non-js editing) + foreach ($items as $k => $item) { + if ($item < 0) { + $todel[] = $k; + } + } + foreach ($todel as $k) { + unset($items[$k]); + } + + if (!ilLMObject::uniqueTypesCheck($items)) { + ilUtil::sendFailure($lng->txt("cont_choose_pages_or_chapters_only"), true); + $ilCtrl->redirect($this, "showHierarchy"); + } + + ilLMObject::clipboardCopy($this->content_object->getId(), $items); + ilEditClipboard::setAction("copy"); + + ilUtil::sendInfo($lng->txt("cont_selected_items_have_been_copied"), true); + $ilCtrl->redirect($this, $a_return); + } + + /** + * Save all titles of chapters/pages + */ + public function saveAllTitles() + { + $ilCtrl = $this->ctrl; + + ilLMObject::saveTitles($this->content_object, ilUtil::stripSlashesArray($_POST["title"]), $_GET["transl"]); + + ilUtil::sendSuccess($this->lng->txt("lm_save_titles"), true); + $ilCtrl->redirect($this, "showHierarchy"); + } + + /* + * display subchapters of structure object + */ + public function subchap() + { + $tree = $this->tree; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilUser = $this->user; + + $this->setTabs(); + + $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.structure_edit.html", "Modules/LearningModule"); + $num = 0; + + $this->tpl->setCurrentBlock("form"); + $this->ctrl->setParameter($this, "backcmd", "subchap"); + $this->tpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this)); + $this->tpl->setVariable("HEADER_TEXT", $this->lng->txt("cont_subchapters")); + $this->tpl->setVariable("CHECKBOX_TOP", IL_FIRST_NODE); + + $cnt = 0; + $childs = $this->tree->getChilds($this->obj->getId()); + foreach ($childs as $child) { + if ($child["type"] != "st") { + continue; + } + $this->tpl->setCurrentBlock("table_row"); + // color changing + $css_row = ilUtil::switchColor($cnt++, "tblrow1", "tblrow2"); + + // checkbox + $this->tpl->setVariable("CHECKBOX_ID", $child["obj_id"]); + $this->tpl->setVariable("CSS_ROW", $css_row); + $this->tpl->setVariable("IMG_OBJ", ilUtil::getImagePath("icon_st.svg")); + + // type + $this->ctrl->setParameterByClass("ilStructureObjectGUI", "obj_id", $child["obj_id"]); + $link = $this->ctrl->getLinkTargetByClass("ilStructureObjectGUI", "view"); + $this->tpl->setVariable("LINK_TARGET", $link); + + // title + $this->tpl->setVariable( + "TEXT_CONTENT", + ilStructureObject::_getPresentationTitle( + $child["obj_id"], + IL_CHAPTER_TITLE, + $this->content_object->isActiveNumbering() + ) + ); + + $this->tpl->parseCurrentBlock(); + } + if ($cnt == 0) { + $this->tpl->setCurrentBlock("notfound"); + $this->tpl->setVariable("NUM_COLS", 3); + $this->tpl->setVariable("TXT_OBJECT_NOT_FOUND", $this->lng->txt("obj_not_found")); + $this->tpl->parseCurrentBlock(); + } + //else + //{ + // SHOW VALID ACTIONS + $this->tpl->setVariable("NUM_COLS", 3); + $acts = array("delete" => "delete", "cutChapter" => "cut", + "copyChapter" => "copyChapter"); + if ($ilUser->clipboardHasObjectsOfType("st")) { + $acts["pasteChapter"] = "pasteChapter"; + } + $this->showActions($acts); + //} + + // SHOW POSSIBLE SUB OBJECTS + $this->tpl->setVariable("NUM_COLS", 3); + //$this->showPossibleSubObjects("st"); + $subobj = array("st"); + $opts = ilUtil::formSelect(12, "new_type", $subobj); + //$this->tpl->setVariable("IMG_ARROW", ilUtil::getImagePath("arrow_downright.svg")); + $this->tpl->setCurrentBlock("add_object"); + $this->tpl->setVariable("SELECT_OBJTYPE", $opts); + //$this->tpl->setVariable("FORMACTION_OBJ_ADD", "adm_object.php?cmd=create&ref_id=".$_GET["ref_id"]); + $this->tpl->setVariable("BTN_NAME", "create"); + $this->tpl->setVariable("TXT_ADD", $this->lng->txt("insert")); + $this->tpl->parseCurrentBlock(); + + //$this->tpl->setVariable("NUM_COLS", 2); + //$this->showPossibleSubObjects("st"); + + $this->tpl->setCurrentBlock("form"); + $this->tpl->parseCurrentBlock(); + + $ilCtrl->setParameter($this, "obj_id", $_GET["obj_id"]); + } + + /** + * output a cell in object list + */ + public function add_cell($val, $link = "") + { + if (!empty($link)) { + $this->tpl->setCurrentBlock("begin_link"); + $this->tpl->setVariable("LINK_TARGET", $link); + $this->tpl->parseCurrentBlock(); + $this->tpl->touchBlock("end_link"); + } + + $this->tpl->setCurrentBlock("text"); + $this->tpl->setVariable("TEXT_CONTENT", $val); + $this->tpl->parseCurrentBlock(); + $this->tpl->setCurrentBlock("table_cell"); + $this->tpl->parseCurrentBlock(); + } + + + /** + * save new chapter + */ + public function save() + { + $this->obj = new ilStructureObject($this->content_object); + + $this->obj->setType("st"); + $this->obj->setTitle(ilUtil::stripSlashes($_POST["Fobject"]["title"])); + $this->obj->setDescription(ilUtil::stripSlashes($_POST["Fobject"]["desc"])); + $this->obj->setLMId($this->content_object->getId()); + $this->obj->create(); + + $this->putInTree(); + + // check the tree + $this->checkTree(); + + if (!empty($_GET["obj_id"])) { + $this->ctrl->redirect($this, "subchap"); + } + } + + /** + * put chapter into tree + */ + public function putInTree() + { + //echo "st:putInTree"; + // chapters should be behind pages in the tree + // so if target is first node, the target is substituted with + // the last child of type pg + if ($_GET["target"] == IL_FIRST_NODE) { + $tree = new ilTree($this->content_object->getId()); + $tree->setTableNames('lm_tree', 'lm_data'); + $tree->setTreeTablePK("lm_id"); + + // determine parent node id + $parent_id = (!empty($_GET["obj_id"])) + ? $_GET["obj_id"] + : $tree->getRootId(); + // determine last child of type pg + $childs = $tree->getChildsByType($parent_id, "pg"); + if (count($childs) != 0) { + $_GET["target"] = $childs[count($childs) - 1]["obj_id"]; + } + } + if (empty($_GET["target"])) { + $_GET["target"] = IL_LAST_NODE; + } + + parent::putInTree(); + } + + /** + * cut page + */ + public function cutPage() + { + $this->cutItems(); + } + + /** + * copy page + */ + public function copyPage() + { + $this->copyItems(); + } + + /** + * paste page + */ + public function pastePage() + { + $ilUser = $this->user; + $ilErr = $this->error; + + if (!$ilUser->clipboardHasObjectsOfType("pg")) { + $ilErr->raiseError($this->lng->txt("no_page_in_clipboard"), $ilErr->MESSAGE); + } + + return $this->insertPageClip(); + } + + + /** + * Cut chapter(s) + */ + public function cutChapter() + { + $this->cutItems("subchap"); + } + + /** + * copy a single chapter (selection) + */ + public function copyChapter() + { + $this->copyItems("subchap"); + } + + /** + * paste chapter + */ + public function pasteChapter() + { + $ilUser = $this->user; + + return $this->insertChapterClip(false, "subchap"); + } + + /** + * activates or deactivates pages + */ + public function activatePages() + { + $lng = $this->lng; + + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + if (is_array($_POST["id"])) { + $act_items = array(); + // get all "top" ids, i.e. remove ids, that have a selected parent + foreach ($_POST["id"] as $id) { + $path = $this->tree->getPathId($id); + $take = true; + foreach ($path as $path_id) { + if ($path_id != $id && in_array($path_id, $_POST["id"])) { + $take = false; + } + } + if ($take) { + $act_items[] = $id; + } + } + + + foreach ($act_items as $id) { + $childs = $this->tree->getChilds($id); + foreach ($childs as $child) { + if (ilLMObject::_lookupType($child["child"]) == "pg") { + $act = ilLMPage::_lookupActive( + $child["child"], + $this->content_object->getType() + ); + ilLMPage::_writeActive( + $child["child"], + $this->content_object->getType(), + !$act + ); + } + } + if (ilLMObject::_lookupType($id) == "pg") { + $act = ilLMPage::_lookupActive( + $id, + $this->content_object->getType() + ); + ilLMPage::_writeActive( + $id, + $this->content_object->getType(), + !$act + ); + } + } + } else { + ilUtil::sendFailure($lng->txt("no_checkbox"), true); + } + + $this->ctrl->redirect($this, "view"); + } + + // + // Condition handling stuff + // + + public function initConditionHandlerInterface() + { + include_once("./Services/Conditions/classes/class.ilConditionHandlerGUI.php"); + + $this->condHI = new ilConditionHandlerGUI($this); + $this->condHI->setBackButtons(array()); + $this->condHI->setAutomaticValidation(false); + $this->condHI->setTargetType("st"); + $this->condHI->setTargetRefId($this->content_object->getRefId()); + $this->condHI->setTargetId($this->obj->getId()); + $this->condHI->setTargetTitle($this->obj->getTitle()); + } + + + /** + * cancel creation of new page or chapter + */ + public function cancel() + { + if ($_GET["obj_id"] != 0) { + if ($_GET["new_type"] == "pg") { + $this->ctrl->redirect($this, "view"); + } else { + $this->ctrl->redirect($this, "subchap"); + } + } + } + + + /** + * output tabs + */ + public function setTabs() + { + $ilTabs = $this->tabs; + $ilUser = $this->user; + $lng = $this->lng; + + // subelements + $ilTabs->addTarget( + "cont_pages_and_subchapters", + $this->ctrl->getLinkTarget($this, 'showHierarchy'), + array("view", "showHierarchy"), + get_class($this) + ); + + // preconditions + $ilTabs->addTarget( + "preconditions", + $this->ctrl->getLinkTarget($this, 'listConditions'), + "listConditions", + get_class($this) + ); + + // metadata + include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php"; + $mdgui = new ilObjectMetaDataGUI($this->content_object, $this->obj->getType(), $this->obj->getId()); + $mdtab = $mdgui->getTab(); + if ($mdtab) { + $ilTabs->addTarget( + "meta_data", + $mdtab, + "", + "ilmdeditorgui" + ); + } + + $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_st.svg")); + $this->tpl->setTitle( + $this->lng->txt($this->obj->getType()) . ": " . $this->obj->getTitle() + ); + + // presentation view + $ilTabs->addNonTabbedLink( + "pres_mode", + $lng->txt("cont_presentation_view"), + ILIAS_HTTP_PATH . "/goto.php?target=st_" . $this->obj->getId(), + "_top" + ); + } + + /** + * redirect script + * + * @param string $a_target + */ + public static function _goto($a_target, $a_target_ref_id = "") + { + global $DIC; + + $rbacsystem = $DIC->rbac()->system(); + $ilErr = $DIC["ilErr"]; + $lng = $DIC->language(); + $ilAccess = $DIC->access(); + + // determine learning object + $lm_id = ilLMObject::_lookupContObjID($a_target); + + // get all references + $ref_ids = ilObject::_getAllReferences($lm_id); + + // always try passed ref id first + if (in_array($a_target_ref_id, $ref_ids)) { + $ref_ids = array_merge(array($a_target_ref_id), $ref_ids); + } + + // check read permissions + foreach ($ref_ids as $ref_id) { + // Permission check + if ($ilAccess->checkAccess("read", "", $ref_id)) { + // don't redirect anymore, just set parameters + // (goto.php includes "ilias.php") + $_GET["baseClass"] = "ilLMPresentationGUI"; + $_GET["obj_id"] = $a_target; + $_GET["ref_id"] = $ref_id; + include_once("ilias.php"); + exit; + ; + } + } + + if ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) { + ilUtil::sendFailure(sprintf( + $lng->txt("msg_no_perm_read_item"), + ilObject::_lookupTitle($lm_id) + ), true); + include_once("./Services/Object/classes/class.ilObjectGUI.php"); + ilObjectGUI::_gotoRepositoryRoot(); + } + + $ilErr->raiseError($lng->txt("msg_no_perm_read_lm"), $ilErr->FATAL); + } + + /** + * Insert (multiple) chapters at node + */ + public function insertChapter($a_as_sub = false) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + include_once("./Modules/LearningModule/classes/class.ilChapterHierarchyFormGUI.php"); + + $num = ilChapterHierarchyFormGUI::getPostMulti(); + $node_id = ilChapterHierarchyFormGUI::getPostNodeId(); + + if ($a_as_sub) { // as subchapter + if (!ilChapterHierarchyFormGUI::getPostFirstChild()) { // insert under parent + $parent_id = $node_id; + $target = ""; + } else { // we shouldnt end up here + $ilCtrl->redirect($this, "showHierarchy"); + return; + } + } else { // as chapter + if (!ilChapterHierarchyFormGUI::getPostFirstChild()) { // insert after node id + $parent_id = $this->tree->getParentId($node_id); + $target = $node_id; + } else { // insert as first child + $parent_id = $node_id; + $target = IL_FIRST_NODE; + } + } + for ($i = 1; $i <= $num; $i++) { + $chap = new ilStructureObject($this->content_object); + $chap->setType("st"); + $chap->setTitle($lng->txt("cont_new_chap")); + $chap->setLMId($this->content_object->getId()); + $chap->create(); + ilLMObject::putInTree($chap, $parent_id, $target); + } + + $ilCtrl->redirect($this, "view"); + } + + /** + * Insert (multiple) subchapters at node + */ + public function insertSubchapter() + { + $ilCtrl = $this->ctrl; + + $this->insertChapter(true); + } + + /** + * Insert Chapter from clipboard + */ + public function insertChapterClip($a_as_sub = false, $a_return = "view") + { + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + $ilLog = $this->log; + + $ilLog->write("Insert Chapter From Clipboard"); + + include_once("./Modules/LearningModule/classes/class.ilChapterHierarchyFormGUI.php"); + + $node_id = ilChapterHierarchyFormGUI::getPostNodeId(); + $first_child = ilChapterHierarchyFormGUI::getPostFirstChild(); + + if ($a_as_sub) { // as subchapter + if (!$first_child) { // insert under parent + $parent_id = $node_id; + $target = ""; + } else { // we shouldnt end up here + $ilCtrl->redirect($this, "showHierarchy"); + return; + } + } else { // as chapter + if (!$first_child) { // insert after node id + $parent_id = $this->tree->getParentId($node_id); + $target = $node_id; + } else { // insert as first child + $parent_id = $node_id; + $target = IL_FIRST_NODE; + + // do not move a chapter in front of a page + $childs = $this->tree->getChildsByType($parent_id, "pg"); + if (count($childs) != 0) { + $target = $childs[count($childs) - 1]["obj_id"]; + } + } + } + + // copy and paste + $chapters = $ilUser->getClipboardObjects("st", true); + $copied_nodes = array(); + + foreach ($chapters as $chap) { + $ilLog->write("Call pasteTree, Target LM: " . $this->content_object->getId() . ", Chapter ID: " . $chap["id"] + . ", Parent ID: " . $parent_id . ", Target: " . $target); + $cid = ilLMObject::pasteTree( + $this->content_object, + $chap["id"], + $parent_id, + $target, + $chap["insert_time"], + $copied_nodes, + (ilEditClipboard::getAction() == "copy") + ); + $target = $cid; + } + ilLMObject::updateInternalLinks($copied_nodes); + + if (ilEditClipboard::getAction() == "cut") { + $ilUser->clipboardDeleteObjectsOfType("pg"); + $ilUser->clipboardDeleteObjectsOfType("st"); + ilEditClipboard::clear(); + } + + $this->content_object->checkTree(); + $ilCtrl->redirect($this, $a_return); + } + + /** + * Insert Chapter from clipboard + */ + public function insertSubchapterClip() + { + $this->insertChapterClip(true); + } + + /** + * Insert (multiple) pages at node + */ + public function insertPage() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + include_once("./Modules/LearningModule/classes/class.ilChapterHierarchyFormGUI.php"); + + $num = ilChapterHierarchyFormGUI::getPostMulti(); + $node_id = ilChapterHierarchyFormGUI::getPostNodeId(); + + if (!ilChapterHierarchyFormGUI::getPostFirstChild()) { // insert after node id + $parent_id = $this->tree->getParentId($node_id); + $target = $node_id; + } else { // insert as first child + $parent_id = $node_id; + $target = IL_FIRST_NODE; + } + + for ($i = 1; $i <= $num; $i++) { + $page = new ilLMPageObject($this->content_object); + $page->setType("pg"); + $page->setTitle($lng->txt("cont_new_page")); + $page->setLMId($this->content_object->getId()); + $page->create(); + ilLMObject::putInTree($page, $parent_id, $target); + } + + $ilCtrl->redirect($this, "showHierarchy"); + } + + /** + * Insert pages from clipboard + */ + public function insertPageClip() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + include_once("./Modules/LearningModule/classes/class.ilChapterHierarchyFormGUI.php"); + + $node_id = ilChapterHierarchyFormGUI::getPostNodeId(); + $first_child = ilChapterHierarchyFormGUI::getPostFirstChild(); + + if (!$first_child) { // insert after node id + $parent_id = $this->tree->getParentId($node_id); + $target = $node_id; + } else { // insert as first child + $parent_id = $node_id; + $target = IL_FIRST_NODE; + } + + // cut and paste + $pages = $ilUser->getClipboardObjects("pg"); + $copied_nodes = array(); + foreach ($pages as $pg) { + $cid = ilLMObject::pasteTree( + $this->content_object, + $pg["id"], + $parent_id, + $target, + $pg["insert_time"], + $copied_nodes, + (ilEditClipboard::getAction() == "copy") + ); + $target = $cid; + } + ilLMObject::updateInternalLinks($copied_nodes); + + if (ilEditClipboard::getAction() == "cut") { + $ilUser->clipboardDeleteObjectsOfType("pg"); + $ilUser->clipboardDeleteObjectsOfType("st"); + ilEditClipboard::clear(); + } + + $ilCtrl->redirect($this, "view"); + } + + + /** + * Perform drag and drop action + */ + public function proceedDragDrop() + { + $ilCtrl = $this->ctrl; + + //echo "-".$_POST["il_hform_source_id"]."-".$_POST["il_hform_target_id"]."-".$_POST["il_hform_fc"]."-"; + $this->content_object->executeDragDrop( + $_POST["il_hform_source_id"], + $_POST["il_hform_target_id"], + $_POST["il_hform_fc"], + $_POST["il_hform_as_subitem"] + ); + $ilCtrl->redirect($this, "showHierarchy"); + } + + //// + //// Pages layout + //// + + /** + * Set layout for multipl pages + */ + public function setPageLayout() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if (!is_array($_POST["id"])) { + ilUtil::sendFailure($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "showHierarchy"); + } + + $this->initSetPageLayoutForm(); + + $tpl->setContent($this->form->getHTML()); + } + + /** + * Init set page layout form. + */ + public function initSetPageLayoutForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + if (is_array($_POST["id"])) { + foreach ($_POST["id"] as $id) { + $hi = new ilHiddenInputGUI("id[]"); + $hi->setValue($id); + $this->form->addItem($hi); + } + } + $layout = ilObjContentObjectGUI::getLayoutOption( + $lng->txt("cont_layout"), + "layout", + $this->content_object->getLayout() + ); + + $this->form->addItem($layout); + + $this->form->addCommandButton("savePageLayout", $lng->txt("save")); + $this->form->addCommandButton("showHierarchy", $lng->txt("cancel")); + + $this->form->setTitle($lng->txt("cont_set_layout")); + $this->form->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * Save page layout + */ + public function savePageLayout() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + foreach ($_POST["id"] as $id) { + $id = ilUtil::stripSlashes($id); + ilLMPageObject::writeLayout( + ilUtil::stripSlashes($id), + ilUtil::stripSlashes($_POST["layout"]), + $this->content_object + ); + } + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "showHierarchy"); + } + + /** + * Edit master language + * + * @param + * @return + */ + public function editMasterLanguage() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameter($this, "transl", ""); + $ilCtrl->redirect($this, "showHierarchy"); + } + + /** + * Switch to language + * + * @param + * @return + */ + public function switchToLanguage() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameter($this, "transl", $_GET["totransl"]); + $ilCtrl->redirect($this, "showHierarchy"); + } } -?> diff --git a/Modules/LearningModule/exceptions/class.ilLMException.php b/Modules/LearningModule/exceptions/class.ilLMException.php index d76737ab0d8ca45b39eba404ffd6522272c8f9ee..1be52dc426a771fb7a2230a433dee7a63a53d074 100644 --- a/Modules/LearningModule/exceptions/class.ilLMException.php +++ b/Modules/LearningModule/exceptions/class.ilLMException.php @@ -1,27 +1,26 @@ - * @version $Id$ - * + * @version $Id$ + * */ class ilLMException extends ilException { - /** - * Constructor - * - * A message is not optional as in build in class Exception - * - * @param string $a_message message - */ - public function __construct($a_message) - { - parent::__construct($a_message); - } + /** + * Constructor + * + * A message is not optional as in build in class Exception + * + * @param string $a_message message + */ + public function __construct($a_message) + { + parent::__construct($a_message); + } } -?> diff --git a/Modules/LearningModule/exceptions/class.ilLMPresentationException.php b/Modules/LearningModule/exceptions/class.ilLMPresentationException.php index 9b2961170ba33585320b8166e2f0232746c44186..6f061ee6dc7f651f221837e91e807b17fca6e72e 100644 --- a/Modules/LearningModule/exceptions/class.ilLMPresentationException.php +++ b/Modules/LearningModule/exceptions/class.ilLMPresentationException.php @@ -1,27 +1,26 @@ - * @version $Id$ - * + * @version $Id$ + * */ class ilLMPresentationException extends ilException { - /** - * Constructor - * - * A message is not optional as in build in class Exception - * - * @param string $a_message message - */ - public function __construct($a_message) - { - parent::__construct($a_message); - } + /** + * Constructor + * + * A message is not optional as in build in class Exception + * + * @param string $a_message message + */ + public function __construct($a_message) + { + parent::__construct($a_message); + } } -?> diff --git a/Modules/MediaCast/classes/class.ilMediaCastDataSet.php b/Modules/MediaCast/classes/class.ilMediaCastDataSet.php index 42a08fc58270270d3ca2cfd4ff184bd5962d1962..20f7807da7a18ef13a13abcda4438660de6af047 100644 --- a/Modules/MediaCast/classes/class.ilMediaCastDataSet.php +++ b/Modules/MediaCast/classes/class.ilMediaCastDataSet.php @@ -5,216 +5,210 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); /** * Media cast data set class - * + * * @author Alex Killing * @version $Id$ * @ingroup ingroup ModulesMediaCast */ class ilMediaCastDataSet extends ilDataSet -{ - protected $order = array(); // [array] - - /** - * Get supported versions - * - * @param - * @return - */ - public function getSupportedVersions() - { - return array("5.0.0", "4.1.0"); - } - - /** - * Get xml namespace - * - * @param - * @return - */ - function getXmlNamespace($a_entity, $a_schema_version) - { - return "http://www.ilias.de/xml/Modules/MediaCast/".$a_entity; - } - - /** - * Get field types for entity - * - * @param - * @return - */ - protected function getTypes($a_entity, $a_version) - { - if ($a_entity == "mcst") - { - switch ($a_version) - { - case "4.1.0": - return array( - "Id" => "integer", - "Title" => "text", - "Description" => "text", - "PublicFiles" => "integer", - "Downloadable" => "integer", - "DefaultAccess" => "integer"); +{ + protected $order = array(); // [array] + + /** + * Get supported versions + * + * @param + * @return + */ + public function getSupportedVersions() + { + return array("5.0.0", "4.1.0"); + } + + /** + * Get xml namespace + * + * @param + * @return + */ + public function getXmlNamespace($a_entity, $a_schema_version) + { + return "http://www.ilias.de/xml/Modules/MediaCast/" . $a_entity; + } + + /** + * Get field types for entity + * + * @param + * @return + */ + protected function getTypes($a_entity, $a_version) + { + if ($a_entity == "mcst") { + switch ($a_version) { + case "4.1.0": + return array( + "Id" => "integer", + "Title" => "text", + "Description" => "text", + "PublicFiles" => "integer", + "Downloadable" => "integer", + "DefaultAccess" => "integer"); - case "5.0.0": - return array( - "Id" => "integer", - "Title" => "text", - "Description" => "text", - "PublicFiles" => "integer", - "Downloadable" => "integer", - "DefaultAccess" => "integer", - "Sortmode" => "integer", - "Viewmode" => "text", - "PublicFeed" => "integer", - "KeepRssMin" => "integer", - "Order" => "text" - ); - } - } + case "5.0.0": + return array( + "Id" => "integer", + "Title" => "text", + "Description" => "text", + "PublicFiles" => "integer", + "Downloadable" => "integer", + "DefaultAccess" => "integer", + "Sortmode" => "integer", + "Viewmode" => "text", + "PublicFeed" => "integer", + "KeepRssMin" => "integer", + "Order" => "text" + ); + } + } + } - } + /** + * Read data + * + * @param + * @return + */ + public function readData($a_entity, $a_version, $a_ids, $a_field = "") + { + $ilDB = $this->db; - /** - * Read data - * - * @param - * @return - */ - 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 == "mcst") { + switch ($a_version) { + case "4.1.0": + $this->getDirectDataFromQuery("SELECT id, title, description, " . + " public_files, downloadable, def_access default_access" . + " FROM il_media_cast_data JOIN object_data ON (il_media_cast_data.id = object_data.obj_id) " . + "WHERE " . + $ilDB->in("id", $a_ids, false, "integer")); + break; - if (!is_array($a_ids)) - { - $a_ids = array($a_ids); - } - - if ($a_entity == "mcst") - { - switch ($a_version) - { - case "4.1.0": - $this->getDirectDataFromQuery("SELECT id, title, description, ". - " public_files, downloadable, def_access default_access". - " FROM il_media_cast_data JOIN object_data ON (il_media_cast_data.id = object_data.obj_id) ". - "WHERE ". - $ilDB->in("id", $a_ids, false, "integer")); - break; + case "5.0.0": + $this->getDirectDataFromQuery("SELECT id, title, description, " . + " public_files, downloadable, def_access default_access, sortmode, viewmode" . + " FROM il_media_cast_data JOIN object_data ON (il_media_cast_data.id = object_data.obj_id) " . + "WHERE " . + $ilDB->in("id", $a_ids, false, "integer")); + + // #17174 - manual order? + $order = array(); + $set = $ilDB->query("SELECT * FROM il_media_cast_data_ord" . + " WHERE " . $ilDB->in("obj_id", $a_ids, false, "integer") . + " ORDER BY pos"); + while ($row = $ilDB->fetchAssoc($set)) { + $order[$row["obj_id"]][] = $row["item_id"]; + } + + include_once("./Services/Block/classes/class.ilBlockSetting.php"); + foreach ($this->data as $k => $v) { + $this->data[$k]["PublicFeed"] = ilBlockSetting::_lookup("news", "public_feed", 0, $v["Id"]); + $this->data[$k]["KeepRssMin"] = (int) ilBlockSetting::_lookup("news", "keep_rss_min", 0, $v["Id"]); + + // manual order? + if ($this->data[$k]["Sortmode"] == 4 && + array_key_exists($v["Id"], $order)) { + $this->data[$k]["Order"] = implode(";", $order[$v["Id"]]); + } + } + break; + } + } + } + + /** + * Determine the dependent sets of data + */ + protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) + { + return false; + } + + + /** + * Import record + * + * @param + * @return + */ + public function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) + { + //echo $a_entity; + //var_dump($a_rec); - case "5.0.0": - $this->getDirectDataFromQuery("SELECT id, title, description, ". - " public_files, downloadable, def_access default_access, sortmode, viewmode". - " FROM il_media_cast_data JOIN object_data ON (il_media_cast_data.id = object_data.obj_id) ". - "WHERE ". - $ilDB->in("id", $a_ids, false, "integer")); - - // #17174 - manual order? - $order = array(); - $set = $ilDB->query("SELECT * FROM il_media_cast_data_ord". - " WHERE ".$ilDB->in("obj_id", $a_ids, false, "integer"). - " ORDER BY pos"); - while($row = $ilDB->fetchAssoc($set)) - { - $order[$row["obj_id"]][] = $row["item_id"]; - } - - include_once("./Services/Block/classes/class.ilBlockSetting.php"); - foreach ($this->data as $k => $v) - { - $this->data[$k]["PublicFeed"] = ilBlockSetting::_lookup("news", "public_feed", 0, $v["Id"]); - $this->data[$k]["KeepRssMin"] = (int) ilBlockSetting::_lookup("news", "keep_rss_min", 0, $v["Id"]); - - // manual order? - if($this->data[$k]["Sortmode"] == 4 && - array_key_exists($v["Id"], $order)) - { - $this->data[$k]["Order"] = implode(";", $order[$v["Id"]]); - } - } - break; - } - } + switch ($a_entity) { + case "mcst": + include_once("./Modules/MediaCast/classes/class.ilObjMediaCast.php"); + + if ($new_id = $a_mapping->getMapping('Services/Container', 'objs', $a_rec['Id'])) { + $newObj = ilObjectFactory::getInstanceByObjId($new_id, false); + } else { + $newObj = new ilObjMediaCast(); + $newObj->setType("mcst"); + $newObj->create(true); + } + + $newObj->setTitle($a_rec["Title"]); + $newObj->setDescription($a_rec["Description"]); + $newObj->setDefaultAccess($a_rec["DefaultAccess"]); + $newObj->setDownloadable($a_rec["Downloadable"]); + $newObj->setPublicFiles($a_rec["PublicFiles"]); - } - - /** - * Determine the dependent sets of data - */ - protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) - { - return false; - } - - - /** - * Import record - * - * @param - * @return - */ - function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) - { -//echo $a_entity; -//var_dump($a_rec); + if ($a_schema_version == "5.0.0") { + $newObj->setOrder($a_rec["Sortmode"]); + $newObj->setViewMode($a_rec["Viewmode"]); + + if ($a_rec["Order"]) { + $this->order[$newObj->getId()] = explode(";", $a_rec["Order"]); + } - switch ($a_entity) - { - case "mcst": - include_once("./Modules/MediaCast/classes/class.ilObjMediaCast.php"); - - if($new_id = $a_mapping->getMapping('Services/Container','objs',$a_rec['Id'])) - { - $newObj = ilObjectFactory::getInstanceByObjId($new_id,false); - } - else - { - $newObj = new ilObjMediaCast(); - $newObj->setType("mcst"); - $newObj->create(true); - } - - $newObj->setTitle($a_rec["Title"]); - $newObj->setDescription($a_rec["Description"]); - $newObj->setDefaultAccess($a_rec["DefaultAccess"]); - $newObj->setDownloadable($a_rec["Downloadable"]); - $newObj->setPublicFiles($a_rec["PublicFiles"]); + include_once("./Services/Block/classes/class.ilBlockSetting.php"); + ilBlockSetting::_write( + "news", + "public_feed", + $a_rec["PublicFeed"], + 0, + $newObj->getId() + ); - if ($a_schema_version == "5.0.0") - { - $newObj->setOrder($a_rec["Sortmode"]); - $newObj->setViewMode($a_rec["Viewmode"]); - - if($a_rec["Order"]) - { - $this->order[$newObj->getId()] = explode(";", $a_rec["Order"]); - } + ilBlockSetting::_write( + "news", + "keep_rss_min", + $a_rec["KeepRssMin"], + 0, + $newObj->getId() + ); + } - include_once("./Services/Block/classes/class.ilBlockSetting.php"); - ilBlockSetting::_write("news", "public_feed", - $a_rec["PublicFeed"], - 0, $newObj->getId()); - - ilBlockSetting::_write("news", "keep_rss_min", - $a_rec["KeepRssMin"], - 0, $newObj->getId()); - } - - $newObj->update(true); - $this->current_obj = $newObj; - $a_mapping->addMapping("Modules/MediaCast", "mcst", $a_rec["Id"], $newObj->getId()); - $a_mapping->addMapping("Services/News", "news_context", - $a_rec["Id"].":mcst:0:", - $newObj->getId().":mcst:0:"); + $newObj->update(true); + $this->current_obj = $newObj; + $a_mapping->addMapping("Modules/MediaCast", "mcst", $a_rec["Id"], $newObj->getId()); + $a_mapping->addMapping( + "Services/News", + "news_context", + $a_rec["Id"] . ":mcst:0:", + $newObj->getId() . ":mcst:0:" + ); //var_dump($a_mapping->mappings["Services/News"]["news_context"]); - break; - } - } - - public function getOrder() - { - return $this->order; - } + break; + } + } + + public function getOrder() + { + return $this->order; + } } -?> \ No newline at end of file diff --git a/Modules/MediaCast/classes/class.ilMediaCastExporter.php b/Modules/MediaCast/classes/class.ilMediaCastExporter.php index 544d84269245172e85e7cca880bb2dd735b0d68b..30e0ce54fc7c42c4625078d634bff42fcbe9d091 100644 --- a/Modules/MediaCast/classes/class.ilMediaCastExporter.php +++ b/Modules/MediaCast/classes/class.ilMediaCastExporter.php @@ -12,18 +12,18 @@ include_once("./Services/Export/classes/class.ilXmlExporter.php"); */ class ilMediaCastExporter extends ilXmlExporter { - private $ds; + private $ds; - /** - * Initialisation - */ - function init() - { - include_once("./Modules/MediaCast/classes/class.ilMediaCastDataSet.php"); - $this->ds = new ilMediaCastDataSet(); - $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); - $this->ds->setDSPrefix("ds"); - } + /** + * Initialisation + */ + public function init() + { + include_once("./Modules/MediaCast/classes/class.ilMediaCastDataSet.php"); + $this->ds = new ilMediaCastDataSet(); + $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); + $this->ds->setDSPrefix("ds"); + } /** @@ -34,9 +34,8 @@ class ilMediaCastExporter extends ilXmlExporter * @param array ids * @return array array of array with keys "component", entity", "ids" */ - function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) + public function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) { - include_once("./Modules/MediaCast/classes/class.ilObjMediaCast.php"); $mc_items_ids = array(); @@ -63,46 +62,43 @@ class ilMediaCastExporter extends ilXmlExporter "ids" => $a_ids); return $deps; - } + } - /** - * Get xml representation - * - * @param string entity - * @param string target release - * @param string id - * @return string xml string - */ - public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) - { - return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); - } - - /** - * Returns schema versions that the component can export to. - * ILIAS chooses the first one, that has min/max constraints which - * fit to the target release. Please put the newest on top. - * - * @return - */ - function getValidSchemaVersions($a_entity) - { - return array ( - "5.0.0" => array( - "namespace" => "http://www.ilias.de/Modules/MediaCast/mcst/5_0", - "xsd_file" => "ilias_mcst_5_0.xsd", - "uses_dataset" => true, - "min" => "5.0.0", - "max" => ""), - "4.1.0" => array( - "namespace" => "http://www.ilias.de/Modules/MediaCast/mcst/4_1", - "xsd_file" => "ilias_mcst_4_1.xsd", - "uses_dataset" => true, - "min" => "4.1.0", - "max" => "") - ); - } + /** + * Get xml representation + * + * @param string entity + * @param string target release + * @param string id + * @return string xml string + */ + public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) + { + return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); + } + /** + * Returns schema versions that the component can export to. + * ILIAS chooses the first one, that has min/max constraints which + * fit to the target release. Please put the newest on top. + * + * @return + */ + public function getValidSchemaVersions($a_entity) + { + return array( + "5.0.0" => array( + "namespace" => "http://www.ilias.de/Modules/MediaCast/mcst/5_0", + "xsd_file" => "ilias_mcst_5_0.xsd", + "uses_dataset" => true, + "min" => "5.0.0", + "max" => ""), + "4.1.0" => array( + "namespace" => "http://www.ilias.de/Modules/MediaCast/mcst/4_1", + "xsd_file" => "ilias_mcst_4_1.xsd", + "uses_dataset" => true, + "min" => "4.1.0", + "max" => "") + ); + } } - -?> \ No newline at end of file diff --git a/Modules/MediaCast/classes/class.ilMediaCastHandlerGUI.php b/Modules/MediaCast/classes/class.ilMediaCastHandlerGUI.php index 3c0fb03c8ae2c5c0d9a51dd5e4c6ee624dccc1a6..73ee50959333cdd46f7240fac611efb69f6b4ce2 100755 --- a/Modules/MediaCast/classes/class.ilMediaCastHandlerGUI.php +++ b/Modules/MediaCast/classes/class.ilMediaCastHandlerGUI.php @@ -13,80 +13,79 @@ */ class ilMediaCastHandlerGUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilTemplate + */ + protected $tpl; - /** - * @var ilNavigationHistory - */ - protected $nav_history; + /** + * @var ilNavigationHistory + */ + protected $nav_history; - function __construct() - { - global $DIC; + public function __construct() + { + global $DIC; - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $this->tpl = $DIC["tpl"]; - $this->nav_history = $DIC["ilNavigationHistory"]; - $ilCtrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->tpl = $DIC["tpl"]; + $this->nav_history = $DIC["ilNavigationHistory"]; + $ilCtrl = $DIC->ctrl(); - // initialisation stuff - $this->ctrl = $ilCtrl; - } - - /** - * execute command - */ - function executeCommand() - { - $lng = $this->lng; - $ilAccess = $this->access; - $tpl = $this->tpl; - $ilNavigationHistory = $this->nav_history; - - $cmd = $this->ctrl->getCmd(); - $next_class = $this->ctrl->getNextClass($this); - if ($next_class == "") - { - $this->ctrl->setCmdClass("ilobjmediacastgui"); - $next_class = $this->ctrl->getNextClass($this); - } + // initialisation stuff + $this->ctrl = $ilCtrl; + } + + /** + * execute command + */ + public function executeCommand() + { + $lng = $this->lng; + $ilAccess = $this->access; + $tpl = $this->tpl; + $ilNavigationHistory = $this->nav_history; + + $cmd = $this->ctrl->getCmd(); + $next_class = $this->ctrl->getNextClass($this); + if ($next_class == "") { + $this->ctrl->setCmdClass("ilobjmediacastgui"); + $next_class = $this->ctrl->getNextClass($this); + } - // add entry to navigation history - if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - $ilNavigationHistory->addItem($_GET["ref_id"], - "ilias.php?baseClass=ilMediaCastHandlerGUI&cmd=showContent&ref_id=".$_GET["ref_id"], "mcst"); - } + // add entry to navigation history + if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) { + $ilNavigationHistory->addItem( + $_GET["ref_id"], + "ilias.php?baseClass=ilMediaCastHandlerGUI&cmd=showContent&ref_id=" . $_GET["ref_id"], + "mcst" + ); + } - switch ($next_class) - { - case 'ilobjmediacastgui': - require_once "./Modules/MediaCast/classes/class.ilObjMediaCastGUI.php"; - $mc_gui = new ilObjMediaCastGUI("", (int) $_GET["ref_id"], true, false); - $this->ctrl->forwardCommand($mc_gui); - break; - } - - $tpl->show(); - } + switch ($next_class) { + case 'ilobjmediacastgui': + require_once "./Modules/MediaCast/classes/class.ilObjMediaCastGUI.php"; + $mc_gui = new ilObjMediaCastGUI("", (int) $_GET["ref_id"], true, false); + $this->ctrl->forwardCommand($mc_gui); + break; + } + $tpl->show(); + } } diff --git a/Modules/MediaCast/classes/class.ilMediaCastImporter.php b/Modules/MediaCast/classes/class.ilMediaCastImporter.php index c7272e6fca2ca654b086dc66c2fbf446a71509d3..77f28d59f62f043dd5703e59d9450060ae410a3a 100644 --- a/Modules/MediaCast/classes/class.ilMediaCastImporter.php +++ b/Modules/MediaCast/classes/class.ilMediaCastImporter.php @@ -13,49 +13,49 @@ include_once("./Services/Export/classes/class.ilXmlImporter.php"); class ilMediaCastImporter extends ilXmlImporter { - /** - * Initialisation - */ - function init() - { - include_once("./Modules/MediaCast/classes/class.ilMediaCastDataSet.php"); - $this->ds = new ilMediaCastDataSet(); - $this->ds->setDSPrefix("ds"); - } + /** + * Initialisation + */ + public function init() + { + include_once("./Modules/MediaCast/classes/class.ilMediaCastDataSet.php"); + $this->ds = new ilMediaCastDataSet(); + $this->ds->setDSPrefix("ds"); + } - /** - * Import XML - * - * @param - * @return - */ - function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) - { - include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); - $parser = new ilDataSetImportParser($a_entity, $this->getSchemaVersion(), - $a_xml, $this->ds, $a_mapping); - } - - function finalProcessing($a_mapping) - { - // restore manual order - $order = $this->ds->getOrder(); - if(sizeof($order)) - { - foreach($order as $obj_id => $items) - { - $map = array(); - foreach($items as $old_id) - { - $map[] = $a_mapping->getMapping("Services/News", "news", $old_id); - } - - $mcst = new ilObjMediaCast($obj_id, false); - $mcst->saveOrder($map); - } - } - } + /** + * Import XML + * + * @param + * @return + */ + public function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) + { + include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); + $parser = new ilDataSetImportParser( + $a_entity, + $this->getSchemaVersion(), + $a_xml, + $this->ds, + $a_mapping + ); + } + + public function finalProcessing($a_mapping) + { + // restore manual order + $order = $this->ds->getOrder(); + if (sizeof($order)) { + foreach ($order as $obj_id => $items) { + $map = array(); + foreach ($items as $old_id) { + $map[] = $a_mapping->getMapping("Services/News", "news", $old_id); + } + + $mcst = new ilObjMediaCast($obj_id, false); + $mcst->saveOrder($map); + } + } + } } - -?> \ No newline at end of file diff --git a/Modules/MediaCast/classes/class.ilMediaCastLP.php b/Modules/MediaCast/classes/class.ilMediaCastLP.php index 6640bab5cc80f868fc617a1419e3841f45450c6d..c9eb6afa39f8d97317b97d644e47151f7a6bccd9 100644 --- a/Modules/MediaCast/classes/class.ilMediaCastLP.php +++ b/Modules/MediaCast/classes/class.ilMediaCastLP.php @@ -10,26 +10,26 @@ require_once 'Services/Object/classes/class.ilObjectLP.php'; */ class ilMediaCastLP extends ilObjectLP { - public static function getDefaultModes($a_lp_active) - { - return array( - ilLPObjSettings::LP_MODE_DEACTIVATED - ); - } - - /** - * @return int - */ - public function getDefaultMode() - { - return ilLPObjSettings::LP_MODE_DEACTIVATED; - } + public static function getDefaultModes($a_lp_active) + { + return array( + ilLPObjSettings::LP_MODE_DEACTIVATED + ); + } + + /** + * @return int + */ + public function getDefaultMode() + { + return ilLPObjSettings::LP_MODE_DEACTIVATED; + } - public function getValidModes() - { - return array( - ilLPObjSettings::LP_MODE_DEACTIVATED, - ilLPObjSettings::LP_MODE_COLLECTION_MOBS - ); - } -} \ No newline at end of file + public function getValidModes() + { + return array( + ilLPObjSettings::LP_MODE_DEACTIVATED, + ilLPObjSettings::LP_MODE_COLLECTION_MOBS + ); + } +} diff --git a/Modules/MediaCast/classes/class.ilMediaCastSettings.php b/Modules/MediaCast/classes/class.ilMediaCastSettings.php index fe251e21b64c1c7f3575a24fd4bcd988b90ec1b2..686b2530ae5ad8b86b64a6d84970540d5ad566a4 100644 --- a/Modules/MediaCast/classes/class.ilMediaCastSettings.php +++ b/Modules/MediaCast/classes/class.ilMediaCastSettings.php @@ -1,168 +1,171 @@ - -* @version $Id$ -* -* -* @ingroup ModulesMediaCast -*/ -class ilMediaCastSettings -{ - private static $instance = null; - private $defaultAccess = "users"; - private $purposeSuffixes = array(); - private $mimeTypes = array(); - - /** - * singleton contructor - * - * @access private - * - */ - private function __construct() - { - $this->initStorage(); - $this->read(); - } - - /** - * get singleton instance - * - * @access public - * @static - * - */ - public static function _getInstance() - { - if(self::$instance) - { - return self::$instance; - } - return self::$instance = new ilMediaCastSettings(); - } - - /** - * set filetypes for purposes - * - * @access public - * - */ - public function setPurposeSuffixes($purpose_filetypes) - { - $this->purposeSuffixes = $purpose_filetypes; - } - - /** - * get filetypes for purposes - * - * @access public - * - */ - public function getPurposeSuffixes() - { - return $this->purposeSuffixes; - } - - public function getDefaultAccess() { - return $this->defaultAccess; - } - - public function setDefaultAccess($value) { - $this->defaultAccess = $value == "users" ? "users" : "public"; - } - - /** - * @return array of mimetypes - */ - public function getMimeTypes() { - return $this->mimeTypes; - } - - /** - * @param unknown_type $mimeTypes - */ - public function setMimeTypes(array $mimeTypes) { - $this->mimeTypes = $mimeTypes; - } - - - /** - * save - * - * @access public - */ - public function save() - { - foreach ($this->purposeSuffixes as $purpose => $filetypes) { - $this->storage->set($purpose . "_types", implode(",",$filetypes)); - } - $this->storage->set("defaultaccess",$this->defaultAccess); - $this->storage->set("mimetypes", implode(",", $this->getMimeTypes())); - } - - /** - * Read settings - * - * @access private - * @param - * - */ - private function read() - { - foreach ($this->purposeSuffixes as $purpose => $filetypes) { - if ($this->storage->get($purpose."_types") != false) { - $this->purposeSuffixes[$purpose] = explode(",",$this->storage->get($purpose."_types")); - } - } - $this->setDefaultAccess($this->storage->get("defaultaccess")); - if ($this->storage->get("mimetypes")) - $this->setMimeTypes(explode(",", $this->storage->get("mimetypes"))); - } - - /** - * Init storage class (ilSetting) - * @access private - * - */ - private function initStorage() - { - include_once('./Services/Administration/classes/class.ilSetting.php'); - $this->storage = new ilSetting('mcst'); - include_once('./Modules/MediaCast/classes/class.ilObjMediaCast.php'); - $this->purposeSuffixes = array_flip(ilObjMediaCast::$purposes); - - $this->purposeSuffixes["Standard"] = array("mp3","flv","mp4","mov","wmv","gif","png", "jpg", "jpeg"); - $this->purposeSuffixes["AudioPortable"] = array("mp3"); - $this->purposeSuffixes["VideoPortable"] = array("mp4","mov"); - $this->setDefaultAccess("users"); - include_once("./Services/Utilities/classes/class.ilMimeTypeUtil.php"); - $mimeTypes = array_unique(array_values(ilMimeTypeUtil::getExt2MimeMap())); - sort($mimeTypes); - $this->setMimeTypes($mimeTypes); - } -} -?> \ No newline at end of file + +* @version $Id$ +* +* +* @ingroup ModulesMediaCast +*/ +class ilMediaCastSettings +{ + private static $instance = null; + private $defaultAccess = "users"; + private $purposeSuffixes = array(); + private $mimeTypes = array(); + + /** + * singleton contructor + * + * @access private + * + */ + private function __construct() + { + $this->initStorage(); + $this->read(); + } + + /** + * get singleton instance + * + * @access public + * @static + * + */ + public static function _getInstance() + { + if (self::$instance) { + return self::$instance; + } + return self::$instance = new ilMediaCastSettings(); + } + + /** + * set filetypes for purposes + * + * @access public + * + */ + public function setPurposeSuffixes($purpose_filetypes) + { + $this->purposeSuffixes = $purpose_filetypes; + } + + /** + * get filetypes for purposes + * + * @access public + * + */ + public function getPurposeSuffixes() + { + return $this->purposeSuffixes; + } + + public function getDefaultAccess() + { + return $this->defaultAccess; + } + + public function setDefaultAccess($value) + { + $this->defaultAccess = $value == "users" ? "users" : "public"; + } + + /** + * @return array of mimetypes + */ + public function getMimeTypes() + { + return $this->mimeTypes; + } + + /** + * @param unknown_type $mimeTypes + */ + public function setMimeTypes(array $mimeTypes) + { + $this->mimeTypes = $mimeTypes; + } + + + /** + * save + * + * @access public + */ + public function save() + { + foreach ($this->purposeSuffixes as $purpose => $filetypes) { + $this->storage->set($purpose . "_types", implode(",", $filetypes)); + } + $this->storage->set("defaultaccess", $this->defaultAccess); + $this->storage->set("mimetypes", implode(",", $this->getMimeTypes())); + } + + /** + * Read settings + * + * @access private + * @param + * + */ + private function read() + { + foreach ($this->purposeSuffixes as $purpose => $filetypes) { + if ($this->storage->get($purpose . "_types") != false) { + $this->purposeSuffixes[$purpose] = explode(",", $this->storage->get($purpose . "_types")); + } + } + $this->setDefaultAccess($this->storage->get("defaultaccess")); + if ($this->storage->get("mimetypes")) { + $this->setMimeTypes(explode(",", $this->storage->get("mimetypes"))); + } + } + + /** + * Init storage class (ilSetting) + * @access private + * + */ + private function initStorage() + { + include_once('./Services/Administration/classes/class.ilSetting.php'); + $this->storage = new ilSetting('mcst'); + include_once('./Modules/MediaCast/classes/class.ilObjMediaCast.php'); + $this->purposeSuffixes = array_flip(ilObjMediaCast::$purposes); + + $this->purposeSuffixes["Standard"] = array("mp3","flv","mp4","mov","wmv","gif","png", "jpg", "jpeg"); + $this->purposeSuffixes["AudioPortable"] = array("mp3"); + $this->purposeSuffixes["VideoPortable"] = array("mp4","mov"); + $this->setDefaultAccess("users"); + include_once("./Services/Utilities/classes/class.ilMimeTypeUtil.php"); + $mimeTypes = array_unique(array_values(ilMimeTypeUtil::getExt2MimeMap())); + sort($mimeTypes); + $this->setMimeTypes($mimeTypes); + } +} diff --git a/Modules/MediaCast/classes/class.ilMediaCastTableGUI.php b/Modules/MediaCast/classes/class.ilMediaCastTableGUI.php index 090e1d3bbfcebf3202e0680e0b42772c21660545..2e33338fb0875cf0cf9cb77a7ea6fed5f94f6cf7 100755 --- a/Modules/MediaCast/classes/class.ilMediaCastTableGUI.php +++ b/Modules/MediaCast/classes/class.ilMediaCastTableGUI.php @@ -15,251 +15,248 @@ include_once("Services/Table/classes/class.ilTable2GUI.php"); */ class ilMediaCastTableGUI extends ilTable2GUI { - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - protected $downloadable = false; - protected $edit_order; - - function __construct($a_parent_obj, $a_parent_cmd = "", $a_edit_order = false, - $a_presentation_mode = false) - { - global $DIC; + protected $downloadable = false; + protected $edit_order; + + public function __construct( + $a_parent_obj, + $a_parent_cmd = "", + $a_edit_order = false, + $a_presentation_mode = false + ) { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->edit_order = (bool)$a_edit_order; - $this->presentation_mode = (bool)$a_presentation_mode; - - parent::__construct($a_parent_obj, $a_parent_cmd); - - // Check whether download-buttons will be displayed - $mediacast = new ilObjMediaCast($a_parent_obj->id); - $this->downloadable = $mediacast->getDownloadable(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->edit_order = (bool) $a_edit_order; + $this->presentation_mode = (bool) $a_presentation_mode; + + parent::__construct($a_parent_obj, $a_parent_cmd); + + // Check whether download-buttons will be displayed + $mediacast = new ilObjMediaCast($a_parent_obj->id); + $this->downloadable = $mediacast->getDownloadable(); - if (!$this->presentation_mode) - { - $this->addColumn("", "", "1"); - } - $this->addColumn($lng->txt("title")); - $this->addColumn($lng->txt("properties")); - if(!$this->edit_order) - { - $this->addColumn($lng->txt("mcst_play"), "", "320px"); - } - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.table_media_cast_row.html", - "Modules/MediaCast"); - - $this->setShowRowsSelector(true); + if (!$this->presentation_mode) { + $this->addColumn("", "", "1"); + } + $this->addColumn($lng->txt("title")); + $this->addColumn($lng->txt("properties")); + if (!$this->edit_order) { + $this->addColumn($lng->txt("mcst_play"), "", "320px"); + } + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate( + "tpl.table_media_cast_row.html", + "Modules/MediaCast" + ); + + $this->setShowRowsSelector(true); - // this messes up the db ordering, where the id is also taken into - // account, if the creation date is the same (this happens e.g. on import) + // this messes up the db ordering, where the id is also taken into + // account, if the creation date is the same (this happens e.g. on import) // $this->setDefaultOrderField("creation_date"); // $this->setDefaultOrderDirection("desc"); - } - - /** - * Standard Version of Fill Row. Most likely to - * be overwritten by derived class. - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; + } + + /** + * Standard Version of Fill Row. Most likely to + * be overwritten by derived class. + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - - $news_set = new ilSetting("news"); - $enable_internal_rss = $news_set->get("enable_rss_for_internal"); + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + + $news_set = new ilSetting("news"); + $enable_internal_rss = $news_set->get("enable_rss_for_internal"); - if ($this->presentation_mode) - { - $ilCtrl->setParameterByClass("ilobjmediacastgui", "presentation", "1"); - } - - // access - if ($enable_internal_rss && !$this->presentation_mode) - { - $this->tpl->setCurrentBlock("access"); - $this->tpl->setVariable("TXT_ACCESS", $lng->txt("news_news_item_visibility")); - if ($a_set["visibility"] == NEWS_PUBLIC) - { - $this->tpl->setVariable("VAL_ACCESS", $lng->txt("news_visibility_public")); - } - else - { - $this->tpl->setVariable("VAL_ACCESS", $lng->txt("news_visibility_users")); - } - $this->tpl->parseCurrentBlock(); - } - - $ilCtrl->setParameterByClass("ilobjmediacastgui", "item_id", ""); + if ($this->presentation_mode) { + $ilCtrl->setParameterByClass("ilobjmediacastgui", "presentation", "1"); + } + + // access + if ($enable_internal_rss && !$this->presentation_mode) { + $this->tpl->setCurrentBlock("access"); + $this->tpl->setVariable("TXT_ACCESS", $lng->txt("news_news_item_visibility")); + if ($a_set["visibility"] == NEWS_PUBLIC) { + $this->tpl->setVariable("VAL_ACCESS", $lng->txt("news_visibility_public")); + } else { + $this->tpl->setVariable("VAL_ACCESS", $lng->txt("news_visibility_users")); + } + $this->tpl->parseCurrentBlock(); + } + + $ilCtrl->setParameterByClass("ilobjmediacastgui", "item_id", ""); - if (ilObject::_exists($a_set["mob_id"])) - { - if ($a_set["update_date"] != "") - { - $this->tpl->setCurrentBlock("last_update"); - $this->tpl->setVariable("TXT_LAST_UPDATE", - $lng->txt("last_update")); - $this->tpl->setVariable("VAL_LAST_UPDATE", - ilDatePresentation::formatDate(new ilDateTime($a_set["update_date"], IL_CAL_DATETIME))); - $this->tpl->parseCurrentBlock(); - } - - $mob = new ilObjMediaObject($a_set["mob_id"]); - $med = $mob->getMediaItem("Standard"); - - $this->tpl->setVariable("VAL_TITLE", - $a_set["title"]); - $this->tpl->setVariable("VAL_DESCRIPTION", - $a_set["content"]); - $this->tpl->setVariable("TXT_CREATED", - $lng->txt("created")); - $this->tpl->setVariable("VAL_CREATED", - ilDatePresentation::formatDate(new ilDateTime($a_set["creation_date"], IL_CAL_DATETIME))); - - $this->tpl->setVariable("TXT_DURATION", - $lng->txt("mcst_play_time")); - - if ($a_set["playtime"] != "00:00:00") - { - $this->tpl->setVariable("VAL_DURATION", - $a_set["playtime"]); - } - else - { - $this->tpl->setVariable("VAL_DURATION", "-"); - } + if (ilObject::_exists($a_set["mob_id"])) { + if ($a_set["update_date"] != "") { + $this->tpl->setCurrentBlock("last_update"); + $this->tpl->setVariable( + "TXT_LAST_UPDATE", + $lng->txt("last_update") + ); + $this->tpl->setVariable( + "VAL_LAST_UPDATE", + ilDatePresentation::formatDate(new ilDateTime($a_set["update_date"], IL_CAL_DATETIME)) + ); + $this->tpl->parseCurrentBlock(); + } + + $mob = new ilObjMediaObject($a_set["mob_id"]); + $med = $mob->getMediaItem("Standard"); + + $this->tpl->setVariable( + "VAL_TITLE", + $a_set["title"] + ); + $this->tpl->setVariable( + "VAL_DESCRIPTION", + $a_set["content"] + ); + $this->tpl->setVariable( + "TXT_CREATED", + $lng->txt("created") + ); + $this->tpl->setVariable( + "VAL_CREATED", + ilDatePresentation::formatDate(new ilDateTime($a_set["creation_date"], IL_CAL_DATETIME)) + ); + + $this->tpl->setVariable( + "TXT_DURATION", + $lng->txt("mcst_play_time") + ); + + if ($a_set["playtime"] != "00:00:00") { + $this->tpl->setVariable( + "VAL_DURATION", + $a_set["playtime"] + ); + } else { + $this->tpl->setVariable("VAL_DURATION", "-"); + } - if(!$this->edit_order) - { - if ($this->downloadable) - { - $ilCtrl->setParameterByClass("ilobjmediacastgui", "item_id", $a_set["id"]); - // to keep always the order of the purposes - // iterate through purposes and display the according mediaitems - foreach (ilObjMediaCast::$purposes as $purpose) - { - $a_mob = $mob->getMediaItem($purpose); - if (!is_object($a_mob)) - continue; - $ilCtrl->setParameterByClass("ilobjmediacastgui", "purpose", $a_mob->getPurpose()); - $file = ilObjMediaObject::_lookupItemPath($a_mob->getMobId(), false, false, $a_mob->getPurpose()); - if (is_file($file)) - { - $size = filesize($file); - $size = ", ".sprintf("%.1f MB",$size/1024/1024); - } - $format = ($a_mob->getFormat()!= "")?$a_mob->getFormat():"audio/mpeg"; - $this->tpl->setCurrentBlock("downloadable"); - $this->tpl->setVariable("TXT_DOWNLOAD", $lng->txt("mcst_download_" . strtolower($a_mob->getPurpose()))); - $this->tpl->setVariable("CMD_DOWNLOAD", $ilCtrl->getLinkTargetByClass("ilobjmediacastgui", "downloadItem")); - $this->tpl->setVariable("TITLE_DOWNLOAD", "(".$format.$size.")"); - $this->tpl->parseCurrentBlock(); - } - } - - include_once("./Services/MediaObjects/classes/class.ilMediaPlayerGUI.php"); - - // the news id will be used as player id, see also ilObjMediaCastGUI - $event_url = ($this->presentation_mode) - ? $ilCtrl->getLinkTarget($this->parent_obj, "handlePlayerEvent", "", true, false) - : ""; - $mpl = new ilMediaPlayerGUI($a_set["id"], $event_url); - if (is_object($med)) - { - require_once('./Services/WebAccessChecker/classes/class.ilWACSignedPath.php'); - if (strcasecmp("Reference", $med->getLocationType()) == 0) { - $a_file = $med->getLocation(); - } - else { - $a_file = ilObjMediaObject::_getURL($mob->getId()) . "/" . $med->getLocation(); - } - $mpl->setFile(ilWACSignedPath::signFile($a_file)); - $mpl->setMimeType ($med->getFormat()); - //$mpl->setDisplayHeight($med->getHeight()); - $mpl->setDisplayWidth("640"); - $mpl->setDisplayHeight("480"); - $mpl->setVideoPreviewPic(ilWACSignedPath::signFile($mob->getVideoPreviewPic())); - $mpl->setTitle($a_set["title"]); - $mpl->setDescription($a_set["content"]); - - $med_alt = $mob->getMediaItem("VideoAlternative"); - if (is_object($med_alt)) - { - $a_val = ilObjMediaObject::_getURL($mob->getId()) . "/" . $med_alt->getLocation(); - $mpl->setAlternativeVideoFile(ilWACSignedPath::signFile($a_val)); - $mpl->setAlternativeVideoMimeType($med_alt->getFormat()); - } - } + if (!$this->edit_order) { + if ($this->downloadable) { + $ilCtrl->setParameterByClass("ilobjmediacastgui", "item_id", $a_set["id"]); + // to keep always the order of the purposes + // iterate through purposes and display the according mediaitems + foreach (ilObjMediaCast::$purposes as $purpose) { + $a_mob = $mob->getMediaItem($purpose); + if (!is_object($a_mob)) { + continue; + } + $ilCtrl->setParameterByClass("ilobjmediacastgui", "purpose", $a_mob->getPurpose()); + $file = ilObjMediaObject::_lookupItemPath($a_mob->getMobId(), false, false, $a_mob->getPurpose()); + if (is_file($file)) { + $size = filesize($file); + $size = ", " . sprintf("%.1f MB", $size/1024/1024); + } + $format = ($a_mob->getFormat()!= "")?$a_mob->getFormat():"audio/mpeg"; + $this->tpl->setCurrentBlock("downloadable"); + $this->tpl->setVariable("TXT_DOWNLOAD", $lng->txt("mcst_download_" . strtolower($a_mob->getPurpose()))); + $this->tpl->setVariable("CMD_DOWNLOAD", $ilCtrl->getLinkTargetByClass("ilobjmediacastgui", "downloadItem")); + $this->tpl->setVariable("TITLE_DOWNLOAD", "(" . $format . $size . ")"); + $this->tpl->parseCurrentBlock(); + } + } + + include_once("./Services/MediaObjects/classes/class.ilMediaPlayerGUI.php"); + + // the news id will be used as player id, see also ilObjMediaCastGUI + $event_url = ($this->presentation_mode) + ? $ilCtrl->getLinkTarget($this->parent_obj, "handlePlayerEvent", "", true, false) + : ""; + $mpl = new ilMediaPlayerGUI($a_set["id"], $event_url); + if (is_object($med)) { + require_once('./Services/WebAccessChecker/classes/class.ilWACSignedPath.php'); + if (strcasecmp("Reference", $med->getLocationType()) == 0) { + $a_file = $med->getLocation(); + } else { + $a_file = ilObjMediaObject::_getURL($mob->getId()) . "/" . $med->getLocation(); + } + $mpl->setFile(ilWACSignedPath::signFile($a_file)); + $mpl->setMimeType($med->getFormat()); + //$mpl->setDisplayHeight($med->getHeight()); + $mpl->setDisplayWidth("640"); + $mpl->setDisplayHeight("480"); + $mpl->setVideoPreviewPic(ilWACSignedPath::signFile($mob->getVideoPreviewPic())); + $mpl->setTitle($a_set["title"]); + $mpl->setDescription($a_set["content"]); + + $med_alt = $mob->getMediaItem("VideoAlternative"); + if (is_object($med_alt)) { + $a_val = ilObjMediaObject::_getURL($mob->getId()) . "/" . $med_alt->getLocation(); + $mpl->setAlternativeVideoFile(ilWACSignedPath::signFile($a_val)); + $mpl->setAlternativeVideoMimeType($med_alt->getFormat()); + } + } - //$this->tpl->setVariable("PLAYER", $mpl->getMp3PlayerHtml()); - $this->tpl->setVariable("PLAYER", $mpl->getPreviewHtml()); - - // edit link - $ilCtrl->setParameterByClass("ilobjmediacastgui", "item_id", $a_set["id"]); - if ($ilAccess->checkAccess("write", "", $_GET["ref_id"]) && - !$this->presentation_mode) - { - $this->tpl->setCurrentBlock("edit"); - $this->tpl->setVariable("TXT_EDIT", $lng->txt("edit")); - $this->tpl->setVariable("CMD_EDIT", - $ilCtrl->getLinkTargetByClass("ilobjmediacastgui", "editCastItem")); - - if (!is_int(strpos($med->getFormat(), "image/"))) - { - $this->tpl->setVariable("TXT_DET_PLAYTIME", $lng->txt("mcst_det_playtime")); - $this->tpl->setVariable("CMD_DET_PLAYTIME", - $ilCtrl->getLinkTargetByClass("ilobjmediacastgui", "determinePlaytime")); - } - $this->tpl->parseCurrentBlock(); - - $this->tpl->setCurrentBlock("edit_checkbox"); - $this->tpl->setVariable("VAL_ID", $a_set["id"]); - $this->tpl->parseCurrentBlock(); -// $this->tpl->touchBlock("contrl_col"); - } - } - else - { - $this->tpl->setCurrentBlock("edit_order"); - $this->tpl->setVariable("VAL_ID", $a_set["id"]); - $this->tpl->setVariable("VAL_ORDER", $a_set["order"]); - $this->tpl->parseCurrentBlock(); -// $this->tpl->touchBlock("contrl_col"); - } - - // download and play counter - if (!$this->presentation_mode) - { - if ($a_set["mob_cnt_download"] > 0) - { - $this->tpl->setCurrentBlock("prop"); - $this->tpl->setVariable("TXT_PROP", $lng->txt("mcst_download_cnt")); - $this->tpl->setVariable("VAL_PROP", $a_set["mob_cnt_download"]); - $this->tpl->parseCurrentBlock(); - } - if ($a_set["mob_cnt_play"] > 0) - { - $this->tpl->setCurrentBlock("prop"); - $this->tpl->setVariable("TXT_PROP", $lng->txt("mcst_play_cnt")); - $this->tpl->setVariable("VAL_PROP", $a_set["mob_cnt_play"]); - $this->tpl->parseCurrentBlock(); - } - } - } - - } + //$this->tpl->setVariable("PLAYER", $mpl->getMp3PlayerHtml()); + $this->tpl->setVariable("PLAYER", $mpl->getPreviewHtml()); + // edit link + $ilCtrl->setParameterByClass("ilobjmediacastgui", "item_id", $a_set["id"]); + if ($ilAccess->checkAccess("write", "", $_GET["ref_id"]) && + !$this->presentation_mode) { + $this->tpl->setCurrentBlock("edit"); + $this->tpl->setVariable("TXT_EDIT", $lng->txt("edit")); + $this->tpl->setVariable( + "CMD_EDIT", + $ilCtrl->getLinkTargetByClass("ilobjmediacastgui", "editCastItem") + ); + + if (!is_int(strpos($med->getFormat(), "image/"))) { + $this->tpl->setVariable("TXT_DET_PLAYTIME", $lng->txt("mcst_det_playtime")); + $this->tpl->setVariable( + "CMD_DET_PLAYTIME", + $ilCtrl->getLinkTargetByClass("ilobjmediacastgui", "determinePlaytime") + ); + } + $this->tpl->parseCurrentBlock(); + + $this->tpl->setCurrentBlock("edit_checkbox"); + $this->tpl->setVariable("VAL_ID", $a_set["id"]); + $this->tpl->parseCurrentBlock(); + // $this->tpl->touchBlock("contrl_col"); + } + } else { + $this->tpl->setCurrentBlock("edit_order"); + $this->tpl->setVariable("VAL_ID", $a_set["id"]); + $this->tpl->setVariable("VAL_ORDER", $a_set["order"]); + $this->tpl->parseCurrentBlock(); + // $this->tpl->touchBlock("contrl_col"); + } + + // download and play counter + if (!$this->presentation_mode) { + if ($a_set["mob_cnt_download"] > 0) { + $this->tpl->setCurrentBlock("prop"); + $this->tpl->setVariable("TXT_PROP", $lng->txt("mcst_download_cnt")); + $this->tpl->setVariable("VAL_PROP", $a_set["mob_cnt_download"]); + $this->tpl->parseCurrentBlock(); + } + if ($a_set["mob_cnt_play"] > 0) { + $this->tpl->setCurrentBlock("prop"); + $this->tpl->setVariable("TXT_PROP", $lng->txt("mcst_play_cnt")); + $this->tpl->setVariable("VAL_PROP", $a_set["mob_cnt_play"]); + $this->tpl->parseCurrentBlock(); + } + } + } + } } -?> diff --git a/Modules/MediaCast/classes/class.ilObjMediaCast.php b/Modules/MediaCast/classes/class.ilObjMediaCast.php index 27aa268d584a1e240ca9236e5d3bf27a632dee30..23dfd9d0a118cf09def1b80aaa2f9b2cfa4c21f3 100755 --- a/Modules/MediaCast/classes/class.ilObjMediaCast.php +++ b/Modules/MediaCast/classes/class.ilObjMediaCast.php @@ -6,554 +6,541 @@ require_once "./Services/Object/classes/class.ilObject.php"; /** * Class ilObjMediaCast -* -* @author Alex Killing +* +* @author Alex Killing * @version $Id$ * */ class ilObjMediaCast extends ilObject { - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - public static $purposes = array ("Standard", "VideoAlternative", "VideoPortable", "AudioPortable"); + public static $purposes = array("Standard", "VideoAlternative", "VideoPortable", "AudioPortable"); protected $online = false; - protected $publicfiles = false; - protected $downloadable = true; - protected $order; - protected $view_mode = ""; - - const ORDER_TITLE = 1; - const ORDER_CREATION_DATE_ASC = 2; - const ORDER_CREATION_DATE_DESC = 3; - const ORDER_MANUAL = 4; - - const VIEW_LIST = ""; - const VIEW_GALLERY = "gallery"; - - /** - * access to rss news - * - * @var 0 = logged in users, 1 = public access - */ - protected $defaultAccess = 0; - - // mapping for copy process - protected $mob_mapping = []; - - /** - * Constructor - * @access public - * @param integer reference_id or object_id - * @param boolean treat the id as reference_id (true) or object_id (false) - */ - function __construct($a_id = 0,$a_call_by_reference = true) - { - global $DIC; - - $this->db = $DIC->database(); - $this->user = $DIC->user(); - $this->type = "mcst"; - parent::__construct($a_id,$a_call_by_reference); - $mcst_set = new ilSetting("mcst"); - $this->setDefaultAccess($mcst_set->get("defaultaccess") == "users" ? 0 : 1); - $this->setOrder(self::ORDER_CREATION_DATE_DESC); - } - - /** - * Set Online. - * - * @param boolean $a_online Online - */ - function setOnline($a_online) - { - $this->online = $a_online; - } - - /** - * Get Online. - * - * @return boolean Online - */ - function getOnline() - { - return $this->online; - } - - /** - * Set PublicFiles. - * - * @param boolean $a_publicfiles PublicFiles - */ - function setPublicFiles($a_publicfiles) - { - $this->publicfiles = $a_publicfiles; - } - - /** - * Get PublicFiles. - * - * @return boolean PublicFiles - */ - function getPublicFiles() - { - return $this->publicfiles; - } - - /** - * Set view mode - * - * @param string $a_val view mode - */ - function setViewMode($a_val) - { - $this->view_mode = $a_val; - } - - /** - * Get view mode - * - * @return string view mode - */ - function getViewMode() - { - return $this->view_mode; - } - /** - * Set ItemsArray. - * - * @param array $a_itemsarray ItemsArray - */ - function setItemsArray($a_itemsarray) - { - $this->itemsarray = $a_itemsarray; - } - - /** - * Get ItemsArray. - * - * @return array ItemsArray - */ - function getItemsArray() - { - return $this->itemsarray; - } - - /** - * Get sorted items array - * - * @param - * @return - */ - function getSortedItemsArray() - { - $med_items = $this->getItemsArray(); - - // sort by order setting - switch($this->getOrder()) - { - case ilObjMediaCast::ORDER_TITLE: - $med_items = ilUtil::sortArray($med_items, "title", "asc", false, true); - break; - - case ilObjMediaCast::ORDER_CREATION_DATE_ASC: - $med_items = ilUtil::sortArray($med_items, "creation_date", "asc", false, true); - break; - - case ilObjMediaCast::ORDER_CREATION_DATE_DESC: - $med_items = ilUtil::sortArray($med_items, "creation_date", "desc", false, true); - break; - - case ilObjMediaCast::ORDER_MANUAL: - $order = array_flip($this->readOrder()); - $pos = sizeof($order); - foreach(array_keys($med_items) as $idx) - { - if(array_key_exists($idx, $order)) - { - $med_items[$idx]["order"] = ($order[$idx]+1)*10; - } - // item has no order yet - else - { - $med_items[$idx]["order"] = (++$pos)*10; - } - } - - $med_items = ilUtil::sortArray($med_items, "order", "asc", true, true); - break; - } - - return $med_items; - } - - - /** - * Set Downloadable. - * - * @param boolean $a_downloadable Downloadable - */ - function setDownloadable($a_downloadable) - { - $this->downloadable = $a_downloadable; - } - /** - * Get Downloadable. - * - * @return boolean Downloadable - */ - function getDownloadable() - { - return $this->downloadable; - } - - /** - * return default access for news items - * - * @return int 0 for logged in users, 1 for public access - */ - function getDefaultAccess() { - return $this->defaultAccess; - } - - /** - * set default access: 0 logged in users, 1 for public access - * - * @param int $value - */ - function setDefaultAccess($value) { - $this->defaultAccess = (int) $value == 0 ? 0 : 1; - } - - /** - * Set order. - * - * @param boolean $a_value - */ - function setOrder($a_value) - { - $this->order = $a_value; - } - /** - * Get order. - * - * @return boolean - */ - function getOrder() - { - return $this->order; - } - - /** - * Gets the disk usage of the object in bytes. + protected $publicfiles = false; + protected $downloadable = true; + protected $order; + protected $view_mode = ""; + + const ORDER_TITLE = 1; + const ORDER_CREATION_DATE_ASC = 2; + const ORDER_CREATION_DATE_DESC = 3; + const ORDER_MANUAL = 4; + + const VIEW_LIST = ""; + const VIEW_GALLERY = "gallery"; + + /** + * access to rss news + * + * @var 0 = logged in users, 1 = public access + */ + protected $defaultAccess = 0; + + // mapping for copy process + protected $mob_mapping = []; + + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + global $DIC; + + $this->db = $DIC->database(); + $this->user = $DIC->user(); + $this->type = "mcst"; + parent::__construct($a_id, $a_call_by_reference); + $mcst_set = new ilSetting("mcst"); + $this->setDefaultAccess($mcst_set->get("defaultaccess") == "users" ? 0 : 1); + $this->setOrder(self::ORDER_CREATION_DATE_DESC); + } + + /** + * Set Online. + * + * @param boolean $a_online Online + */ + public function setOnline($a_online) + { + $this->online = $a_online; + } + + /** + * Get Online. + * + * @return boolean Online + */ + public function getOnline() + { + return $this->online; + } + + /** + * Set PublicFiles. + * + * @param boolean $a_publicfiles PublicFiles + */ + public function setPublicFiles($a_publicfiles) + { + $this->publicfiles = $a_publicfiles; + } + + /** + * Get PublicFiles. + * + * @return boolean PublicFiles + */ + public function getPublicFiles() + { + return $this->publicfiles; + } + + /** + * Set view mode + * + * @param string $a_val view mode + */ + public function setViewMode($a_val) + { + $this->view_mode = $a_val; + } + + /** + * Get view mode + * + * @return string view mode + */ + public function getViewMode() + { + return $this->view_mode; + } + /** + * Set ItemsArray. + * + * @param array $a_itemsarray ItemsArray + */ + public function setItemsArray($a_itemsarray) + { + $this->itemsarray = $a_itemsarray; + } + + /** + * Get ItemsArray. + * + * @return array ItemsArray + */ + public function getItemsArray() + { + return $this->itemsarray; + } + + /** + * Get sorted items array + * + * @param + * @return + */ + public function getSortedItemsArray() + { + $med_items = $this->getItemsArray(); + + // sort by order setting + switch ($this->getOrder()) { + case ilObjMediaCast::ORDER_TITLE: + $med_items = ilUtil::sortArray($med_items, "title", "asc", false, true); + break; + + case ilObjMediaCast::ORDER_CREATION_DATE_ASC: + $med_items = ilUtil::sortArray($med_items, "creation_date", "asc", false, true); + break; + + case ilObjMediaCast::ORDER_CREATION_DATE_DESC: + $med_items = ilUtil::sortArray($med_items, "creation_date", "desc", false, true); + break; + + case ilObjMediaCast::ORDER_MANUAL: + $order = array_flip($this->readOrder()); + $pos = sizeof($order); + foreach (array_keys($med_items) as $idx) { + if (array_key_exists($idx, $order)) { + $med_items[$idx]["order"] = ($order[$idx]+1)*10; + } + // item has no order yet + else { + $med_items[$idx]["order"] = (++$pos)*10; + } + } + + $med_items = ilUtil::sortArray($med_items, "order", "asc", true, true); + break; + } + + return $med_items; + } + + + /** + * Set Downloadable. + * + * @param boolean $a_downloadable Downloadable + */ + public function setDownloadable($a_downloadable) + { + $this->downloadable = $a_downloadable; + } + /** + * Get Downloadable. + * + * @return boolean Downloadable + */ + public function getDownloadable() + { + return $this->downloadable; + } + + /** + * return default access for news items + * + * @return int 0 for logged in users, 1 for public access + */ + public function getDefaultAccess() + { + return $this->defaultAccess; + } + + /** + * set default access: 0 logged in users, 1 for public access + * + * @param int $value + */ + public function setDefaultAccess($value) + { + $this->defaultAccess = (int) $value == 0 ? 0 : 1; + } + + /** + * Set order. + * + * @param boolean $a_value + */ + public function setOrder($a_value) + { + $this->order = $a_value; + } + /** + * Get order. + * + * @return boolean + */ + public function getOrder() + { + return $this->order; + } + + /** + * Gets the disk usage of the object in bytes. + * + * @access public + * @return integer the disk usage in bytes + */ + public function getDiskUsage() + { + require_once("./Modules/MediaCast/classes/class.ilObjMediaCastAccess.php"); + return ilObjMediaCastAccess::_lookupDiskUsage($this->id); + } + + /** + * Create mew media cast + */ + public function create() + { + $ilDB = $this->db; + + parent::create(); + + $query = "INSERT INTO il_media_cast_data (" . + " id" . + ", is_online" . + ", public_files" . + ", downloadable" . + ", def_access" . + ", sortmode" . + ", viewmode" . + " ) VALUES (" . + $ilDB->quote($this->getId(), "integer") + . "," . $ilDB->quote((int) $this->getOnline(), "integer") + . "," . $ilDB->quote((int) $this->getPublicFiles(), "integer") + . "," . $ilDB->quote((int) $this->getDownloadable(), "integer") + . "," . $ilDB->quote((int) $this->getDefaultAccess(), "integer") + . "," . $ilDB->quote((int) $this->getOrder(), "integer") + . "," . $ilDB->quote((int) $this->getViewMode(), "text") + . ")"; + $ilDB->manipulate($query); + } + + /** + * update object data * - * @access public - * @return integer the disk usage in bytes - */ - function getDiskUsage() - { - require_once("./Modules/MediaCast/classes/class.ilObjMediaCastAccess.php"); - return ilObjMediaCastAccess::_lookupDiskUsage($this->id); - } - - /** - * Create mew media cast - */ - function create() - { - $ilDB = $this->db; - - parent::create(); - - $query = "INSERT INTO il_media_cast_data (". - " id". - ", is_online". - ", public_files". - ", downloadable". - ", def_access". - ", sortmode". - ", viewmode". - " ) VALUES (". - $ilDB->quote($this->getId(), "integer") - .",".$ilDB->quote((int) $this->getOnline(), "integer") - .",".$ilDB->quote((int) $this->getPublicFiles(), "integer") - .",".$ilDB->quote((int) $this->getDownloadable(), "integer") - .",".$ilDB->quote((int) $this->getDefaultAccess(), "integer") - .",".$ilDB->quote((int) $this->getOrder(), "integer") - .",".$ilDB->quote((int) $this->getViewMode(), "text") - .")"; - $ilDB->manipulate($query); - - } - - /** - * update object data - * - * @access public - * @return boolean - */ - function update() - { - $ilDB = $this->db; - - if (!parent::update()) - { - return false; - } - - // update media cast data - $query = "UPDATE il_media_cast_data SET ". - " is_online = ".$ilDB->quote((int) $this->getOnline(), "integer"). - ", public_files = ".$ilDB->quote((int) $this->getPublicFiles(), "integer"). - ", downloadable = ".$ilDB->quote((int) $this->getDownloadable(), "integer"). - ", def_access = ".$ilDB->quote((int) $this->getDefaultAccess(), "integer"). - ", sortmode = ".$ilDB->quote((int) $this->getOrder(), "integer"). - ", viewmode = ".$ilDB->quote($this->getViewMode(), "text"). - " WHERE id = ".$ilDB->quote((int) $this->getId(), "integer"); - - $ilDB->manipulate($query); - - return true; - } - - /** - * Read media cast - */ - function read() - { - $ilDB = $this->db; - - parent::read(); - $this->readItems(); - - $query = "SELECT * FROM il_media_cast_data WHERE id = ". - $ilDB->quote($this->getId(), "integer"); - $set = $ilDB->query($query); - $rec = $ilDB->fetchAssoc($set); - - $this->setOnline($rec["is_online"]); - $this->setPublicFiles($rec["public_files"]); - $this->setDownloadable($rec["downloadable"]); - $this->setDefaultAccess($rec["def_access"]); - $this->setOrder($rec["sortmode"]); - $this->setViewMode($rec["viewmode"]); - - } - - - /** - * delete object and all related data - * - * @access public - * @return boolean true if all object data were removed; false if only a references were removed - */ - function delete() - { - $ilDB = $this->db; - - // always call parent delete function first!! - if (!parent::delete()) - { - return false; - } - - // delete all items - $med_items = $this->getItemsArray(); - foreach ($med_items as $item) - { - include_once("./Services/News/classes/class.ilNewsItem.php"); - $news_item = new ilNewsItem($item["id"]); - $news_item->delete(); - } - - $this->deleteOrder(); - - // delete record of table il_media_cast_data - $query = "DELETE FROM il_media_cast_data". - " WHERE id = ".$ilDB->quote($this->getId(), "integer"); - $ilDB->manipulate($query); - - return true; - } - - /** - * Get all items of media cast. - */ - function readItems($a_oldest_first = false) - { - // - include_once("./Services/News/classes/class.ilNewsItem.php"); - $it = new ilNewsItem(); - $it->setContextObjId($this->getId()); - $it->setContextObjType($this->getType()); - $this->itemsarray = $it->queryNewsForContext(false, 0, "", false, $a_oldest_first); - - return $this->itemsarray; - } - - function deleteOrder() - { - $ilDB = $this->db; - - if(!$this->getId()) - { - return; - } - - $sql = "DELETE FROM il_media_cast_data_ord". - " WHERE obj_id = ".$ilDB->quote($this->getId(), "integer"); - $ilDB->manipulate($sql); - } - - function readOrder() - { - $ilDB = $this->db; - - if(!$this->getId()) - { - return; - } - - $all = array(); - $sql = "SELECT item_id FROM il_media_cast_data_ord". - " WHERE obj_id = ".$ilDB->quote($this->getId(), "integer"). - " ORDER BY pos"; - $res = $ilDB->query($sql); - while($row = $ilDB->fetchAssoc($res)) - { - $all[] = $row["item_id"]; - } - return $all; - } - - function saveOrder(array $a_items) - { - $ilDB = $this->db; - - if(!$this->getId()) - { - return; - } - - $this->deleteOrder(); - - $pos = 0; - foreach($a_items as $item_id) - { - $pos++; - - $sql = "INSERT INTO il_media_cast_data_ord (obj_id,item_id,pos)". - " VALUES (".$ilDB->quote($this->getId(), "integer").",". - $ilDB->quote($item_id, "integer").",". - $ilDB->quote($pos, "integer").")"; - $ilDB->manipulate($sql); - } - } - - /** - * Clone media cast - * - * @param int target ref_id - * @param int copy id - */ - public function cloneObject($a_target_id,$a_copy_id = 0, $a_omit_tree = false) - { - $new_obj = parent::cloneObject($a_target_id,$a_copy_id, $a_omit_tree); - - //copy online status if object is not the root copy object - $cp_options = ilCopyWizardOptions::_getInstance($a_copy_id); - - if(!$cp_options->isRootNode($this->getRefId())) - { - $new_obj->setOnline($this->getOnline()); - } - - //$new_obj->setTitle($this->getTitle()); - $new_obj->setPublicFiles($this->getPublicFiles()); - $new_obj->setDownloadable($this->getDownloadable()); - $new_obj->setDefaultAccess($this->getDefaultAccess()); - $new_obj->setOrder($this->getOrder()); - $new_obj->setViewMode($this->getViewMode()); - $new_obj->update(); - - include_once("./Services/Block/classes/class.ilBlockSetting.php"); - $pf = ilBlockSetting::_lookup("news", "public_feed", 0, $this->getId()); - $keeprss = (int) ilBlockSetting::_lookup("news", "keep_rss_min", 0, $this->getId()); - ilBlockSetting::_write("news", "public_feed", $pf, 0, $new_obj->getId()); - ilBlockSetting::_write("news", "keep_rss_min", $keeprss, 0, $new_obj->getId()); - - // copy items - $this->copyItems($new_obj); - - // copy order!? - - // clone LP settings - include_once('./Services/Tracking/classes/class.ilLPObjSettings.php'); - $obj_settings = new ilLPObjSettings($this->getId()); - $obj_settings->cloneSettings($new_obj->getId()); - unset($obj_settings); + * @access public + * @return boolean + */ + public function update() + { + $ilDB = $this->db; + + if (!parent::update()) { + return false; + } + + // update media cast data + $query = "UPDATE il_media_cast_data SET " . + " is_online = " . $ilDB->quote((int) $this->getOnline(), "integer") . + ", public_files = " . $ilDB->quote((int) $this->getPublicFiles(), "integer") . + ", downloadable = " . $ilDB->quote((int) $this->getDownloadable(), "integer") . + ", def_access = " . $ilDB->quote((int) $this->getDefaultAccess(), "integer") . + ", sortmode = " . $ilDB->quote((int) $this->getOrder(), "integer") . + ", viewmode = " . $ilDB->quote($this->getViewMode(), "text") . + " WHERE id = " . $ilDB->quote((int) $this->getId(), "integer"); + + $ilDB->manipulate($query); + + return true; + } + + /** + * Read media cast + */ + public function read() + { + $ilDB = $this->db; + + parent::read(); + $this->readItems(); + + $query = "SELECT * FROM il_media_cast_data WHERE id = " . + $ilDB->quote($this->getId(), "integer"); + $set = $ilDB->query($query); + $rec = $ilDB->fetchAssoc($set); + + $this->setOnline($rec["is_online"]); + $this->setPublicFiles($rec["public_files"]); + $this->setDownloadable($rec["downloadable"]); + $this->setDefaultAccess($rec["def_access"]); + $this->setOrder($rec["sortmode"]); + $this->setViewMode($rec["viewmode"]); + } + + + /** + * delete object and all related data + * + * @access public + * @return boolean true if all object data were removed; false if only a references were removed + */ + public function delete() + { + $ilDB = $this->db; + + // always call parent delete function first!! + if (!parent::delete()) { + return false; + } + + // delete all items + $med_items = $this->getItemsArray(); + foreach ($med_items as $item) { + include_once("./Services/News/classes/class.ilNewsItem.php"); + $news_item = new ilNewsItem($item["id"]); + $news_item->delete(); + } + + $this->deleteOrder(); + + // delete record of table il_media_cast_data + $query = "DELETE FROM il_media_cast_data" . + " WHERE id = " . $ilDB->quote($this->getId(), "integer"); + $ilDB->manipulate($query); + + return true; + } + + /** + * Get all items of media cast. + */ + public function readItems($a_oldest_first = false) + { + // + include_once("./Services/News/classes/class.ilNewsItem.php"); + $it = new ilNewsItem(); + $it->setContextObjId($this->getId()); + $it->setContextObjType($this->getType()); + $this->itemsarray = $it->queryNewsForContext(false, 0, "", false, $a_oldest_first); + + return $this->itemsarray; + } + + public function deleteOrder() + { + $ilDB = $this->db; + + if (!$this->getId()) { + return; + } + + $sql = "DELETE FROM il_media_cast_data_ord" . + " WHERE obj_id = " . $ilDB->quote($this->getId(), "integer"); + $ilDB->manipulate($sql); + } + + public function readOrder() + { + $ilDB = $this->db; + + if (!$this->getId()) { + return; + } + + $all = array(); + $sql = "SELECT item_id FROM il_media_cast_data_ord" . + " WHERE obj_id = " . $ilDB->quote($this->getId(), "integer") . + " ORDER BY pos"; + $res = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($res)) { + $all[] = $row["item_id"]; + } + return $all; + } + + public function saveOrder(array $a_items) + { + $ilDB = $this->db; + + if (!$this->getId()) { + return; + } + + $this->deleteOrder(); + + $pos = 0; + foreach ($a_items as $item_id) { + $pos++; + + $sql = "INSERT INTO il_media_cast_data_ord (obj_id,item_id,pos)" . + " VALUES (" . $ilDB->quote($this->getId(), "integer") . "," . + $ilDB->quote($item_id, "integer") . "," . + $ilDB->quote($pos, "integer") . ")"; + $ilDB->manipulate($sql); + } + } + + /** + * Clone media cast + * + * @param int target ref_id + * @param int copy id + */ + public function cloneObject($a_target_id, $a_copy_id = 0, $a_omit_tree = false) + { + $new_obj = parent::cloneObject($a_target_id, $a_copy_id, $a_omit_tree); + + //copy online status if object is not the root copy object + $cp_options = ilCopyWizardOptions::_getInstance($a_copy_id); + + if (!$cp_options->isRootNode($this->getRefId())) { + $new_obj->setOnline($this->getOnline()); + } + + //$new_obj->setTitle($this->getTitle()); + $new_obj->setPublicFiles($this->getPublicFiles()); + $new_obj->setDownloadable($this->getDownloadable()); + $new_obj->setDefaultAccess($this->getDefaultAccess()); + $new_obj->setOrder($this->getOrder()); + $new_obj->setViewMode($this->getViewMode()); + $new_obj->update(); + + include_once("./Services/Block/classes/class.ilBlockSetting.php"); + $pf = ilBlockSetting::_lookup("news", "public_feed", 0, $this->getId()); + $keeprss = (int) ilBlockSetting::_lookup("news", "keep_rss_min", 0, $this->getId()); + ilBlockSetting::_write("news", "public_feed", $pf, 0, $new_obj->getId()); + ilBlockSetting::_write("news", "keep_rss_min", $keeprss, 0, $new_obj->getId()); + + // copy items + $this->copyItems($new_obj); + + // copy order!? + + // clone LP settings + include_once('./Services/Tracking/classes/class.ilLPObjSettings.php'); + $obj_settings = new ilLPObjSettings($this->getId()); + $obj_settings->cloneSettings($new_obj->getId()); + unset($obj_settings); /** @var ilScormLP $olp */ $olp = ilObjectLP::getInstance($this->getId()); $collection = $olp->getCollectionInstance(); - if($collection) - { + if ($collection) { $collection->cloneCollection($new_obj->getRefId(), $cp_options->getCopyId(), $this->mob_mapping); } - return $new_obj; - } - - /** - * Copy items - * - * @param - * @return - */ - function copyItems($a_new_obj) - { - $ilUser = $this->user; - - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - foreach($this->readItems(true) as $item) - { - // copy media object - $mob_id = $item["mob_id"]; - $mob = new ilObjMediaObject($mob_id); - $new_mob = $mob->duplicate(); - - // copy news item - // create new media cast item - include_once("./Services/News/classes/class.ilNewsItem.php"); - $mc_item = new ilNewsItem(); - $mc_item->setMobId($new_mob->getId()); - $mc_item->setContentType(NEWS_AUDIO); - $mc_item->setContextObjId($a_new_obj->getId()); - $mc_item->setContextObjType($a_new_obj->getType()); - $mc_item->setUserId($ilUser->getId()); - $mc_item->setPlaytime($item["playtime"]); - $mc_item->setTitle($item["title"]); - $mc_item->setContent($item["content"]); - $mc_item->setVisibility($item["visibility"]); - $mc_item->create(); - $this->mob_mapping[$mob_id] = $new_mob->getId(); - } - } - - public function handleLPUpdate($a_user_id, $a_mob_id) - { - // using read events to persist mob status - require_once 'Services/Tracking/classes/class.ilChangeEvent.php'; - ilChangeEvent::_recordReadEvent("mob", $this->getRefId(), - $a_mob_id, $a_user_id); - - // trigger LP update - require_once 'Services/Tracking/classes/class.ilLPStatusWrapper.php'; - ilLPStatusWrapper::_updateStatus($this->getId(), $a_user_id); - } + return $new_obj; + } + + /** + * Copy items + * + * @param + * @return + */ + public function copyItems($a_new_obj) + { + $ilUser = $this->user; + + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + foreach ($this->readItems(true) as $item) { + // copy media object + $mob_id = $item["mob_id"]; + $mob = new ilObjMediaObject($mob_id); + $new_mob = $mob->duplicate(); + + // copy news item + // create new media cast item + include_once("./Services/News/classes/class.ilNewsItem.php"); + $mc_item = new ilNewsItem(); + $mc_item->setMobId($new_mob->getId()); + $mc_item->setContentType(NEWS_AUDIO); + $mc_item->setContextObjId($a_new_obj->getId()); + $mc_item->setContextObjType($a_new_obj->getType()); + $mc_item->setUserId($ilUser->getId()); + $mc_item->setPlaytime($item["playtime"]); + $mc_item->setTitle($item["title"]); + $mc_item->setContent($item["content"]); + $mc_item->setVisibility($item["visibility"]); + $mc_item->create(); + $this->mob_mapping[$mob_id] = $new_mob->getId(); + } + } + + public function handleLPUpdate($a_user_id, $a_mob_id) + { + // using read events to persist mob status + require_once 'Services/Tracking/classes/class.ilChangeEvent.php'; + ilChangeEvent::_recordReadEvent( + "mob", + $this->getRefId(), + $a_mob_id, + $a_user_id + ); + + // trigger LP update + require_once 'Services/Tracking/classes/class.ilLPStatusWrapper.php'; + ilLPStatusWrapper::_updateStatus($this->getId(), $a_user_id); + } } - -?> diff --git a/Modules/MediaCast/classes/class.ilObjMediaCastAccess.php b/Modules/MediaCast/classes/class.ilObjMediaCastAccess.php index 3d248bcbb8bf078596fd4303dc0c283857b3b9c6..21381bc84324ce323d4fc2093b30d509a18193f6 100755 --- a/Modules/MediaCast/classes/class.ilObjMediaCastAccess.php +++ b/Modules/MediaCast/classes/class.ilObjMediaCastAccess.php @@ -15,213 +15,199 @@ include_once("./Services/Object/classes/class.ilObjectAccess.php"); */ class ilObjMediaCastAccess extends ilObjectAccess { - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilAccessHandler - */ - protected $access; - - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->user = $DIC->user(); - $this->lng = $DIC->language(); - $this->rbacsystem = $DIC->rbac()->system(); - $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" => "showContent", "lang_var" => "show", - "default" => true), - array("permission" => "write", "cmd" => "listItems", "lang_var" => "edit_content"), - array("permission" => "write", "cmd" => "editSettings", "lang_var" => "settings") - ); - - return $commands; - } - - /** - * checks wether a user may invoke a command or not - * (this method is called by ilAccessHandler::checkAccess) - * - * @param string $a_cmd command (not permission!) - * @param string $a_permission permission - * @param int $a_ref_id reference id - * @param int $a_obj_id object id - * @param int $a_user_id user id (if not provided, current user is taken) - * - * @return boolean true, if everything is ok - */ - function _checkAccess($a_cmd, $a_permission, $a_ref_id, $a_obj_id, $a_user_id = "") - { - $ilUser = $this->user; - $lng = $this->lng; - $rbacsystem = $this->rbacsystem; - $ilAccess = $this->access; - - if ($a_user_id == "") - { - $a_user_id = $ilUser->getId(); - } - - switch ($a_cmd) - { - case "listItems": - - if(!ilObjMediaCastAccess::_lookupOnline($a_obj_id) - && !$rbacsystem->checkAccessOfUser($a_user_id,'write',$a_ref_id)) - { - $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("offline")); - return false; - } - break; - - // for permission query feature - case "infoScreen": - if(!ilObjMediaCastAccess::_lookupOnline($a_obj_id)) - { - $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("offline")); - } - else - { - $ilAccess->addInfoItem(IL_STATUS_MESSAGE, $lng->txt("online")); - } - break; - - } - switch ($a_permission) - { - case "read": - case "visible": - if (!ilObjMediaCastAccess::_lookupOnline($a_obj_id) && - (!$rbacsystem->checkAccessOfUser($a_user_id, 'write', $a_ref_id))) - { - $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("offline")); - return false; - } - break; - } - - return true; - } - - /** - * check whether goto script will succeed - */ - static function _checkGoto($a_target) - { - global $DIC; - - $ilAccess = $DIC->access(); - - $t_arr = explode("_", $a_target); - - if ($t_arr[0] != "mcst" || ((int) $t_arr[1]) <= 0) - { - return false; - } - - if ($ilAccess->checkAccess("read", "", $t_arr[1])) - { - return true; - } - return false; - } - - /** - * Check wether media cast is online - * - * @param int $a_id media cast id - */ - static function _lookupOnline($a_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "SELECT * FROM il_media_cast_data WHERE id = ".$ilDB->quote($a_id); - $mc_set = $ilDB->query($q); - $mc_rec = $mc_set->fetchRow(ilDBConstants::FETCHMODE_ASSOC); - - return $mc_rec["is_online"]; - } - - /** - * Check wether files should be public - * - * @param int $a_id media cast id - */ - static function _lookupPublicFiles($a_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "SELECT * FROM il_media_cast_data WHERE id = ".$ilDB->quote($a_id); - $mc_set = $ilDB->query($q); - $mc_rec = $mc_set->fetchRow(ilDBConstants::FETCHMODE_ASSOC); - - return $mc_rec["public_files"]; - } - - /** - * Returns the number of bytes used on the harddisk by the file object - * with the specified object id. - * @param int object id of a file object. - */ - static function _lookupDiskUsage($a_id) - { - require_once('Modules/MediaCast/classes/class.ilObjMediaCast.php'); - require_once("./Services/News/classes/class.ilNewsItem.php"); - require_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $obj = new ilObjMediaCast($a_id, false); - $obj->read(); - $items = $obj->getItemsArray(); - $size = 0; - foreach ($items as $item) - { - $news_item = new ilNewsItem($item["id"]); - $news_item->read(); - $mobId = $news_item->getMobId(); - $size += ilUtil::dirsize(ilObjMediaObject::_getDirectory($mobId)); - } - return $size; - } + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilAccessHandler + */ + protected $access; + + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->user = $DIC->user(); + $this->lng = $DIC->language(); + $this->rbacsystem = $DIC->rbac()->system(); + $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"), + * ); + */ + public static function _getCommands() + { + $commands = array( + array("permission" => "read", "cmd" => "showContent", "lang_var" => "show", + "default" => true), + array("permission" => "write", "cmd" => "listItems", "lang_var" => "edit_content"), + array("permission" => "write", "cmd" => "editSettings", "lang_var" => "settings") + ); + + return $commands; + } + + /** + * checks wether a user may invoke a command or not + * (this method is called by ilAccessHandler::checkAccess) + * + * @param string $a_cmd command (not permission!) + * @param string $a_permission permission + * @param int $a_ref_id reference id + * @param int $a_obj_id object id + * @param int $a_user_id user id (if not provided, current user is taken) + * + * @return boolean true, if everything is ok + */ + public function _checkAccess($a_cmd, $a_permission, $a_ref_id, $a_obj_id, $a_user_id = "") + { + $ilUser = $this->user; + $lng = $this->lng; + $rbacsystem = $this->rbacsystem; + $ilAccess = $this->access; + + if ($a_user_id == "") { + $a_user_id = $ilUser->getId(); + } + + switch ($a_cmd) { + case "listItems": + + if (!ilObjMediaCastAccess::_lookupOnline($a_obj_id) + && !$rbacsystem->checkAccessOfUser($a_user_id, 'write', $a_ref_id)) { + $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("offline")); + return false; + } + break; + + // for permission query feature + case "infoScreen": + if (!ilObjMediaCastAccess::_lookupOnline($a_obj_id)) { + $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("offline")); + } else { + $ilAccess->addInfoItem(IL_STATUS_MESSAGE, $lng->txt("online")); + } + break; + + } + switch ($a_permission) { + case "read": + case "visible": + if (!ilObjMediaCastAccess::_lookupOnline($a_obj_id) && + (!$rbacsystem->checkAccessOfUser($a_user_id, 'write', $a_ref_id))) { + $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("offline")); + return false; + } + break; + } + + return true; + } + + /** + * check whether goto script will succeed + */ + public static function _checkGoto($a_target) + { + global $DIC; + + $ilAccess = $DIC->access(); + + $t_arr = explode("_", $a_target); + + if ($t_arr[0] != "mcst" || ((int) $t_arr[1]) <= 0) { + return false; + } + + if ($ilAccess->checkAccess("read", "", $t_arr[1])) { + return true; + } + return false; + } + + /** + * Check wether media cast is online + * + * @param int $a_id media cast id + */ + public static function _lookupOnline($a_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "SELECT * FROM il_media_cast_data WHERE id = " . $ilDB->quote($a_id); + $mc_set = $ilDB->query($q); + $mc_rec = $mc_set->fetchRow(ilDBConstants::FETCHMODE_ASSOC); + + return $mc_rec["is_online"]; + } + + /** + * Check wether files should be public + * + * @param int $a_id media cast id + */ + public static function _lookupPublicFiles($a_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "SELECT * FROM il_media_cast_data WHERE id = " . $ilDB->quote($a_id); + $mc_set = $ilDB->query($q); + $mc_rec = $mc_set->fetchRow(ilDBConstants::FETCHMODE_ASSOC); + + return $mc_rec["public_files"]; + } + + /** + * Returns the number of bytes used on the harddisk by the file object + * with the specified object id. + * @param int object id of a file object. + */ + public static function _lookupDiskUsage($a_id) + { + require_once('Modules/MediaCast/classes/class.ilObjMediaCast.php'); + require_once("./Services/News/classes/class.ilNewsItem.php"); + require_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $obj = new ilObjMediaCast($a_id, false); + $obj->read(); + $items = $obj->getItemsArray(); + $size = 0; + foreach ($items as $item) { + $news_item = new ilNewsItem($item["id"]); + $news_item->read(); + $mobId = $news_item->getMobId(); + $size += ilUtil::dirsize(ilObjMediaObject::_getDirectory($mobId)); + } + return $size; + } } - -?> diff --git a/Modules/MediaCast/classes/class.ilObjMediaCastGUI.php b/Modules/MediaCast/classes/class.ilObjMediaCastGUI.php index 20d12089ac856ec4b5dac38240bbed7975a800ea..945d9a1cfe3edd36f4f65c644b697400f971d8f3 100755 --- a/Modules/MediaCast/classes/class.ilObjMediaCastGUI.php +++ b/Modules/MediaCast/classes/class.ilObjMediaCastGUI.php @@ -7,9 +7,9 @@ require_once "./Services/Object/classes/class.ilObjectGUI.php"; /** * Class ilObjMediaCastGUI * -* @author Alex Killing +* @author Alex Killing * @version $Id$ -* +* * @ilCtrl_Calls ilObjMediaCastGUI: ilPermissionGUI, ilInfoScreenGUI, ilExportGUI * @ilCtrl_Calls ilObjMediaCastGUI: ilCommonActionDispatcherGUI * @ilCtrl_Calls ilObjMediaCastGUI: ilLearningProgressGUI, ilObjectCopyGUI @@ -17,1836 +17,1753 @@ require_once "./Services/Object/classes/class.ilObjectGUI.php"; */ class ilObjMediaCastGUI extends ilObjectGUI { - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var Logger - */ - protected $log; - - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * @var ilHelpGUI - */ - protected $help; + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var Logger + */ + protected $log; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilHelpGUI + */ + protected $help; - private $additionalPurposes = array ("VideoPortable", "AudioPortable"); - private $purposeSuffixes = array (); + private $additionalPurposes = array("VideoPortable", "AudioPortable"); + private $purposeSuffixes = array(); private $mimeTypes = array(); - /** - * Constructor - * @access public - */ - function __construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output = true) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - $this->tabs = $DIC->tabs(); - $this->tpl = $DIC["tpl"]; - $this->access = $DIC->access(); - $this->toolbar = $DIC->toolbar(); - $this->log = $DIC["ilLog"]; - $this->error = $DIC["ilErr"]; - $this->help = $DIC["ilHelp"]; - $this->locator = $DIC["ilLocator"]; - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->type = "mcst"; - parent::__construct($a_data,$a_id,$a_call_by_reference,$a_prepare_output); - $lng->loadLanguageModule("mcst"); - $lng->loadLanguageModule("news"); - $lng->loadLanguageModule("rep"); - - $ilCtrl->saveParameter($this, "item_id"); - - include_once ("./Modules/MediaCast/classes/class.ilMediaCastSettings.php"); - $settings = ilMediaCastSettings::_getInstance(); - $this->purposeSuffixes = $settings->getPurposeSuffixes(); - $this->mimeTypes = array(); - $mime_types = $settings->getMimeTypes(); - foreach ($mime_types as $mt) - { - $this->mimeTypes[$mt] = $mt; - } - - include_once("./Services/Utilities/classes/class.ilMimeTypeUtil.php"); - foreach (ilMimeTypeUtil::getExt2MimeMap() as $mt) - { - $this->mimeTypes[$mt] = $mt; - } - asort($this->mimeTypes); - } - - function executeCommand() - { - $ilUser = $this->user; - $ilTabs = $this->tabs; + /** + * Constructor + * @access public + */ + public function __construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output = true) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + $this->tabs = $DIC->tabs(); + $this->tpl = $DIC["tpl"]; + $this->access = $DIC->access(); + $this->toolbar = $DIC->toolbar(); + $this->log = $DIC["ilLog"]; + $this->error = $DIC["ilErr"]; + $this->help = $DIC["ilHelp"]; + $this->locator = $DIC["ilLocator"]; + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->type = "mcst"; + parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); + $lng->loadLanguageModule("mcst"); + $lng->loadLanguageModule("news"); + $lng->loadLanguageModule("rep"); + + $ilCtrl->saveParameter($this, "item_id"); + + include_once("./Modules/MediaCast/classes/class.ilMediaCastSettings.php"); + $settings = ilMediaCastSettings::_getInstance(); + $this->purposeSuffixes = $settings->getPurposeSuffixes(); + $this->mimeTypes = array(); + $mime_types = $settings->getMimeTypes(); + foreach ($mime_types as $mt) { + $this->mimeTypes[$mt] = $mt; + } + + include_once("./Services/Utilities/classes/class.ilMimeTypeUtil.php"); + foreach (ilMimeTypeUtil::getExt2MimeMap() as $mt) { + $this->mimeTypes[$mt] = $mt; + } + asort($this->mimeTypes); + } + + public function executeCommand() + { + $ilUser = $this->user; + $ilTabs = $this->tabs; - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - $this->prepareOutput(); + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + $this->prepareOutput(); - switch($next_class) - { - case "ilinfoscreengui": - if (!$this->checkPermissionBool("read")) - { - $this->checkPermission("visible"); - } - $this->infoScreen(); // forwards command - break; - - case "ilexportgui": + switch ($next_class) { + case "ilinfoscreengui": + if (!$this->checkPermissionBool("read")) { + $this->checkPermission("visible"); + } + $this->infoScreen(); // forwards command + 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"); - $ret = $this->ctrl->forwardCommand($exp_gui); + $ilTabs->activateTab("export"); + include_once("./Services/Export/classes/class.ilExportGUI.php"); + $exp_gui = new ilExportGUI($this); + $exp_gui->addFormat("xml"); + $ret = $this->ctrl->forwardCommand($exp_gui); // $this->tpl->show(); - break; - - case 'ilpermissiongui': - $ilTabs->activateTab("id_permissions"); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $ret = $this->ctrl->forwardCommand($perm_gui); - break; - - case 'ilobjectcopygui': - include_once './Services/Object/classes/class.ilObjectCopyGUI.php'; - $cp = new ilObjectCopyGUI($this); - $cp->setType('mcst'); - $this->ctrl->forwardCommand($cp); - break; - - case "ilcommonactiondispatchergui": - include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); - $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); - $this->ctrl->forwardCommand($gui); - break; - - case "illearningprogressgui": - $ilTabs->activateTab('learning_progress'); - require_once 'Services/Tracking/classes/class.ilLearningProgressGUI.php'; - $new_gui = new ilLearningProgressGUI( - ilLearningProgressGUI::LP_CONTEXT_REPOSITORY, - $this->object->getRefId(), - $_GET['user_id'] ? $_GET['user_id'] : $ilUser->getId() - ); - $this->ctrl->forwardCommand($new_gui); - $this->tabs_gui->setTabActive('learning_progress'); - break; - - default: - if(!$cmd) - { - $cmd = "infoScreen"; - } - $cmd .= "Object"; - if ($cmd != "infoScreenObject") - { - $this->checkPermission("read"); - } - else - { - $this->checkPermission("visible"); - } - $this->$cmd(); - - break; - } - - $this->addHeaderAction(); + break; + + case 'ilpermissiongui': + $ilTabs->activateTab("id_permissions"); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $ret = $this->ctrl->forwardCommand($perm_gui); + break; + + case 'ilobjectcopygui': + include_once './Services/Object/classes/class.ilObjectCopyGUI.php'; + $cp = new ilObjectCopyGUI($this); + $cp->setType('mcst'); + $this->ctrl->forwardCommand($cp); + break; + + case "ilcommonactiondispatchergui": + include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); + $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); + $this->ctrl->forwardCommand($gui); + break; + + case "illearningprogressgui": + $ilTabs->activateTab('learning_progress'); + require_once 'Services/Tracking/classes/class.ilLearningProgressGUI.php'; + $new_gui = new ilLearningProgressGUI( + ilLearningProgressGUI::LP_CONTEXT_REPOSITORY, + $this->object->getRefId(), + $_GET['user_id'] ? $_GET['user_id'] : $ilUser->getId() + ); + $this->ctrl->forwardCommand($new_gui); + $this->tabs_gui->setTabActive('learning_progress'); + break; + + default: + if (!$cmd) { + $cmd = "infoScreen"; + } + $cmd .= "Object"; + if ($cmd != "infoScreenObject") { + $this->checkPermission("read"); + } else { + $this->checkPermission("visible"); + } + $this->$cmd(); + + break; + } + + $this->addHeaderAction(); - return true; - } - - protected function initCreationForms($a_new_type) - { - $forms = array(self::CFORM_NEW => $this->initCreateForm($a_new_type), - self::CFORM_IMPORT => $this->initImportForm($a_new_type), - self::CFORM_CLONE => $this->fillCloneTemplate(null, $a_new_type)); - - return $forms; - } - - /** - * save object - * @access public - */ - function afterSave(ilObject $newObj) - { - // always send a message - ilUtil::sendSuccess($this->lng->txt("object_added"),true); - ilUtil::redirect("ilias.php?baseClass=ilMediaCastHandlerGUI&ref_id=".$newObj->getRefId()."&cmd=editSettings"); - } - - /** - * List items of media cast. - */ - function listItemsObject($a_presentation_mode = false) - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilAccess = $this->access; - $ilTabs = $this->tabs; - $ilToolbar = $this->toolbar; - - $this->checkPermission("read"); - - if ($a_presentation_mode) - { - $this->addContentSubTabs("content"); - } - else - { - $this->addContentSubTabs("manage"); - } - - $med_items = $this->object->getSortedItemsArray(); - - include_once("./Modules/MediaCast/classes/class.ilMediaCastTableGUI.php"); - if ($a_presentation_mode) - { - $table_gui = new ilMediaCastTableGUI($this, "showContent", false, true); - } - else - { - $table_gui = new ilMediaCastTableGUI($this, "listItems"); - } - - $table_gui->setData($med_items); - - if ($ilAccess->checkAccess("write", "", $_GET["ref_id"]) && !$a_presentation_mode) - { - $ilToolbar->addButton($lng->txt("add"), $this->ctrl->getLinkTarget($this, "addCastItem")); - - $table_gui->addMultiCommand("confirmDeletionItems", $lng->txt("delete")); - $table_gui->setSelectAllCheckbox("item_id"); - } - - $feed_icon_html = $this->getFeedIconsHTML(); - if ($feed_icon_html != "") - { - $table_gui->setHeaderHTML($feed_icon_html); - } - - $tpl->setContent($table_gui->getHTML()); - } - - /** - * Get feed icons HTML - * - * @param - * @return - */ - function getFeedIconsHTML() - { - $lng = $this->lng; - - $html = ""; - - include_once("./Services/Block/classes/class.ilBlockSetting.php"); - $public_feed = ilBlockSetting::_lookup("news", "public_feed", - 0, $this->object->getId()); - - // rss icon/link - if ($public_feed) - { - $news_set = new ilSetting("news"); - $enable_internal_rss = $news_set->get("enable_rss_for_internal"); - - if ($enable_internal_rss) - { - // create dummy object in db (we need an id) - $items = $this->object->getItemsArray(); - include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); - $html = ""; - foreach (ilObjMediaCast::$purposes as $purpose) - { - foreach ($items as $id => $item) - { - $mob = new ilObjMediaObject($item["mob_id"]); - $mob->read(); - if ($mob->hasPurposeItem($purpose)) - { - if ($html == "") - { - $html = " "; - } - $url = ILIAS_HTTP_PATH."/feed.php?client_id=".rawurlencode(CLIENT_ID)."&"."ref_id=".$_GET["ref_id"]."&purpose=$purpose"; - $title = $lng->txt("news_feed_url"); - - include_once("./Services/News/classes/class.ilRSSButtonGUI.php"); - switch (strtolower($purpose)) - { - case "audioportable": - $type1 = ilRSSButtonGUI::ICON_RSS_AUDIO; - $type2 = ilRSSButtonGUI::ICON_ITUNES_AUDIO; - break; - - case "videoportable": - $type1 = ilRSSButtonGUI::ICON_RSS_VIDEO; - $type2 = ilRSSButtonGUI::ICON_ITUNES_VIDEO; - break; - - default: - $type1 = ilRSSButtonGUI::ICON_RSS; - $type2 = ilRSSButtonGUI::ICON_ITUNES; - break; - } - $row1 .= " ".ilRSSButtonGUI::get($type1, $url); - if ($this->object->getPublicFiles()) - { - $url = preg_replace("/https?/i","itpc",$url); - $title = $lng->txt("news_feed_url"); - - include_once("./Services/News/classes/class.ilRSSButtonGUI.php"); - $row2 .= " ".ilRSSButtonGUI::get($type2, $url); - } - break; - } - } - } - if ($html != "") - { - $html .= $row1; - if ($row2 != "") - { - $html .= $row2; - } - } - } - } - return $html; - } - - - /** - * Add media cast item - */ - function addCastItemObject() - { - $tpl = $this->tpl; - - $this->checkPermission("write"); - - $this->initAddCastItemForm(); - $tpl->setContent($this->form_gui->getHTML()); - } - - /** - * Edit media cast item - */ - function editCastItemObject() - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - - $this->checkPermission("write"); - - // conversion toolbar - include_once("./Services/MediaObjects/classes/class.ilFFmpeg.php"); - if (ilFFmpeg::enabled()) - { - $this->mcst_item = new ilNewsItem($_GET["item_id"]); - include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); - $mob = new ilObjMediaObject($this->mcst_item->getMobId()); - - $conv_cnt = 0; - // we had other purposes as source as well, but - // currently only "Standard" is implemented in the convertFile method - foreach (array("Standard") as $p) - { - /* - $med = $mob->getMediaItem($p); - if (is_object($med)) - { - $options = ilFFmpeg::getPossibleTargetMimeTypes($med->getFormat()); - if (count($options) > 0) - { - if ($conv_cnt > 0) - { - $ilToolbar->addSeparator(); - } - - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $si = new ilSelectInputGUI($this->lng->txt("mcst_conv_". - strtolower($p)."_to"), "target_format"); - $si->setOptions($options); - $ilToolbar->addInputItem($si, true); - - $si = new ilSelectInputGUI(", ".$this->lng->txt("mcst_target").": ", - "target_purpose"); - $si->setOptions(array("Standard" => $this->lng->txt("mcst_purpose_standard"), - "VideoAlternative" => $this->lng->txt("mcst_purpose_videoalternative") - )); - $si->setValue($p); - $ilToolbar->addInputItem($si, true); - - $ilToolbar->addFormButton($this->lng->txt("mcst_convert"), "convertFile"); - - $conv_cnt++; - } - } - */ - - $med = $mob->getMediaItem($p); - if (is_object($med)) - { - if (ilFFmpeg::supportsImageExtraction($med->getFormat())) - { - // second - include_once("./Services/Form/classes/class.ilTextInputGUI.php"); - $ni = new ilTextInputGUI($this->lng->txt("mcst_second"), "sec"); - $ni->setMaxLength(4); - $ni->setSize(4); - $ni->setValue(1); - $ilToolbar->addInputItem($ni, true); - - $ilToolbar->addFormButton($this->lng->txt("mcst_extract_preview_image"), "extractPreviewImage"); - $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); - } - } - - /*if ($conv_cnt > 0) - { - $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); - }*/ - } - } - - $this->initAddCastItemForm("edit"); - $this->getCastItemValues(); - $tpl->setContent($this->form_gui->getHTML()); - } - - /** - * Init add cast item form. - */ - function initAddCastItemForm($a_mode = "create") - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - $this->checkPermission("write"); - $ilTabs->activateTab("edit_content"); - - $lng->loadLanguageModule("mcst"); - - $news_set = new ilSetting("news"); - $enable_internal_rss = $news_set->get("enable_rss_for_internal"); - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form_gui = new ilPropertyFormGUI(); - $this->form_gui->setMultipart(true); - - // Property Title - $text_input = new ilTextInputGUI($lng->txt("title"), "title"); - $text_input->setMaxLength(200); - $this->form_gui->addItem($text_input); - - // Property Content - $text_area = new ilTextAreaInputGUI($lng->txt("description"), "description"); - $text_area->setRequired(false); - $this->form_gui->addItem($text_area); - - // Property Visibility - if ($enable_internal_rss) - { - $radio_group = new ilRadioGroupInputGUI($lng->txt("access_scope"), "visibility"); - $radio_option = new ilRadioOption($lng->txt("access_users"), "users"); - $radio_group->addOption($radio_option); - $radio_option = new ilRadioOption($lng->txt("access_public"), "public"); - $radio_group->addOption($radio_option); - $radio_group->setInfo($lng->txt("mcst_visibility_info")); - $radio_group->setRequired(true); - $radio_group->setValue($this->object->getDefaultAccess() == 0 ? "users" : "public"); - $this->form_gui->addItem($radio_group); - } - - // Duration - $dur = new ilDurationInputGUI($lng->txt("mcst_duration"), "duration"); - $dur->setInfo($lng->txt("mcst_duration_info")); - $dur->setShowDays(false); - $dur->setShowHours(true); - $dur->setShowSeconds(true); - $this->form_gui->addItem($dur); - - foreach (ilObjMediaCast::$purposes as $purpose) - { - if ($purpose == "VideoAlternative" && - $a_mode == "create") - { - continue; - } - - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($lng->txt("mcst_".strtolower($purpose)."_title")); - $this->form_gui->addItem($section); - if ($a_mode != "create") - { - $value = new ilHiddenInputGUI("value_".$purpose); - $label = new ilNonEditableValueGUI($lng->txt("value")); - $label->setPostVar("label_value_".$purpose); - $label->setInfo($lng->txt("mcst_current_value_info")); - $this->form_gui->addItem($label); - $this->form_gui->addItem($value); - - } - $file = new ilFileInputGUI($lng->txt("file"), "file_".$purpose); - $file->setSuffixes($this->purposeSuffixes[$purpose]); - $this->form_gui->addItem($file); - $text_input = new ilRegExpInputGUI($lng->txt("url"), "url_".$purpose); - $text_input->setPattern("/https?\:\/\/.+/i"); - $text_input->setInfo($lng->txt("mcst_reference_info")); - $this->form_gui->addItem($text_input); - if ($purpose != "Standard") - { - $clearCheckBox = new ilCheckboxInputGUI(); - $clearCheckBox->setPostVar("delete_".$purpose); - $clearCheckBox->setTitle($lng->txt("mcst_clear_purpose_title")); - $this->form_gui->addItem($clearCheckBox); - } else { - - // mime type selection - $mimeTypeSelection = new ilSelectInputGUI(); - $mimeTypeSelection->setPostVar("mimetype_".$purpose); - $mimeTypeSelection->setTitle($lng->txt("mcst_mimetype")); - $mimeTypeSelection->setInfo($lng->txt("mcst_mimetype_info")); - $options = array("" => $lng->txt("mcst_automatic_detection")); - $options = array_merge($options, $this->mimeTypes); - $mimeTypeSelection->setOptions($options); - $this->form_gui->addItem($mimeTypeSelection); - - // preview picure - $pp = new ilImageFileInputGUI($lng->txt("mcst_preview_picture"), "preview_pic"); - $pp->setSuffixes(array("png", "jpeg", "jpg")); - $pp->setInfo($lng->txt("mcst_preview_picture_info")." mp4, mp3, png, jp(e)g, gif"); - $this->form_gui->addItem($pp); - - } - - } - - // save/cancel button - if ($a_mode == "create") - { - $this->form_gui->setTitle($lng->txt("mcst_add_new_item")); - $this->form_gui->addCommandButton("saveCastItem", $lng->txt("save")); - } - else - { - $this->form_gui->setTitle($lng->txt("mcst_edit_item")); - $this->form_gui->addCommandButton("updateCastItem", $lng->txt("save")); - } - $this->form_gui->addCommandButton("listItems", $lng->txt("cancel")); - $this->form_gui->setFormAction($ilCtrl->getFormAction($this, "saveCastItem")); - - } - - /** - * Get cast item values into form. - */ - public function getCastItemValues() - { - $lng = $this->lng; - - // get mob - $this->mcst_item = new ilNewsItem($_GET["item_id"]); - include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); - $mob = new ilObjMediaObject($this->mcst_item->getMobId()); - - // preview - $ppic = $mob->getVideoPreviewPic(); - if ($ppic != "") - { - $i = $this->form_gui->getItemByPostVar("preview_pic"); - $i->setImage($ppic); - } - - - $values = array(); - $mediaItems = $this->getMediaItems($_GET["item_id"]); - if (count ($mediaItems) > 0) - { - foreach ($mediaItems as $med) - { - if (!isset ($values["title"])) - { - // first item, so set title, description, ... - $values["title"] = $this->mcst_item->getTitle(); - $values["description"] = $this->mcst_item->getContent(); - $values["visibility"] = $this->mcst_item->getVisibility(); - $length = explode(":", $this->mcst_item->getPlaytime()); - $values["duration"] = array("hh" => $length[0], "mm" => $length[1], "ss" => $length[2]); - } - - $values["value_".$med->getPurpose()] = (strlen($med->getLocation())> 100) ? "...".substr($med->getLocation(), strlen($med->getLocation()) - 100) : $med->getLocation(); - $values["label_value_".$med->getPurpose()] = (strlen($med->getLocation())> 100) ? "...".substr($med->getLocation(), strlen($med->getLocation()) - 100) : $med->getLocation(); - $values["mimetype_".$med->getPurpose()] = $med->getFormat(); - } - } - foreach (ilObjMediaCast::$purposes as $purpose) { - if (!isset ($values["value_".$purpose])) - { - $values["label_value_".$purpose] = $lng->txt("none"); - $values["value_".$purpose] = $lng->txt("none"); - } - } - $this->form_gui->setValuesByArray($values); - } - - /** - * Save new cast item - */ - function saveCastItemObject() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - $lng = $this->lng; - $ilTabs = $this->tabs; - - $this->checkPermission("write"); - $ilTabs->activateTab("edit_content"); - - $this->initAddCastItemForm(); - - if (!$this->form_gui->checkInput() || - ($_POST["url_Standard"] == "" && !$_FILES['file_Standard']['tmp_name'])) - { - if (($_POST["url_Standard"] == "" && !$_FILES['file_Standard']['tmp_name'])) - { - ilUtil::sendFailure($lng->txt("mcst_input_either_file_or_url")); - } - $this->populateFormFromPost(); - } - else - { - // create dummy object in db (we need an id) - include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); - $mob = new ilObjMediaObject(); - $mob->create(); - - //handle standard purpose - $file = $this->createMediaItemForPurpose($mob, "Standard"); - - // set title and description - // set title to basename of file if left empty - $title = $this->form_gui->getInput("title") != "" ? $this->form_gui->getInput("title") : basename($file); - $description = $this->form_gui->getInput("description"); - $mob->setTitle($title); - $mob->setDescription($description); - - // save preview pic - $prevpic = $this->form_gui->getInput("preview_pic"); - if ($prevpic["size"] > 0) - { - $mob->uploadVideoPreviewPic($prevpic); - } - - // determine duration for standard purpose - $duration = $this->getDuration($file); - - // handle other purposes - foreach ($this->additionalPurposes as $purpose) - { - // check if some purpose has been uploaded - $file_gui = $this->form_gui->getInput("file_".$purpose); - $url_gui = $this->form_gui->getInput("url_".$purpose); - if ($url_gui || $file_gui["size"] > 0) - { - $this->createMediaItemForPurpose ($mob, $purpose); - } - } - - $mob->update(); - - if ($prevpic["size"] == 0) - { - // re-read media object - $mob = new ilObjMediaObject($mob->getId()); - $mob->generatePreviewPic(320, 240); - } - - // - // @todo: save usage - // - - $news_set = new ilSetting("news"); - $enable_internal_rss = $news_set->get("enable_rss_for_internal"); - - // create new media cast item - include_once("./Services/News/classes/class.ilNewsItem.php"); - $mc_item = new ilNewsItem(); - $mc_item->setMobId($mob->getId()); - $mc_item->setContentType(NEWS_AUDIO); - $mc_item->setContextObjId($this->object->getId()); - $mc_item->setContextObjType($this->object->getType()); - $mc_item->setUserId($ilUser->getId()); - $mc_item->setPlaytime($duration); - $mc_item->setTitle($title); - $mc_item->setContent($description); - $mc_item->setLimitation(false); - if ($enable_internal_rss) - { - $mc_item->setVisibility($this->form_gui->getInput("visibility")); - } - else - { - $mc_item->setVisibility("users"); - } - $mc_item->create(); - - $ilCtrl->redirect($this, "listItems"); - } - } - - /** - * get duration from form or from file analyzer - * - * @param unknown_type $file - * @return unknown - */ - private function getDuration($file) - { - $duration = isset($this->form_gui) - ? $this->form_gui->getInput("duration") - : array("hh"=>0, "mm"=>0, "ss"=>0); - if ($duration["hh"] == 0 && $duration["mm"] == 0 && $duration["ss"] == 0 && is_file($file)) - { - include_once("./Services/MediaObjects/classes/class.ilMediaAnalyzer.php"); - $ana = new ilMediaAnalyzer(); - $ana->setFile($file); - $ana->analyzeFile(); - $dur = $ana->getPlaytimeString(); - $dur = explode(":", $dur); - $duration["mm"] = $dur[0]; - $duration["ss"] = $dur[1]; - } - $duration = str_pad($duration["hh"], 2 , "0", STR_PAD_LEFT).":". - str_pad($duration["mm"], 2 , "0", STR_PAD_LEFT).":". - str_pad($duration["ss"], 2 , "0", STR_PAD_LEFT); - return $duration; - } - - /** - * handle media item for given purpose - * - * @param ilMediaObject $mob - * @param string file - */ - private function createMediaItemForPurpose ($mob, $purpose) - { - $mediaItem = new ilMediaItem(); - $mob->addMediaItem($mediaItem); - $mediaItem->setPurpose($purpose); - return $this->updateMediaItem($mob, $mediaItem); - } - - /** - * update media item from form - * - * @param IlObjectMediaObject $mob - * @param IlMediaItem $mediaItem - * @return string file - */ - private function updateMediaItem ($mob, & $mediaItem) - { - $purpose = $mediaItem->getPurpose(); - $url_gui = $this->form_gui->getInput ("url_".$purpose); - $file_gui = $this->form_gui->getInput ("file_".$purpose); - if ($url_gui) - { - // http - $file = $this->form_gui->getInput ("url_".$purpose); - $title = basename ($file); - $location = $this->form_gui->getInput ("url_".$purpose); - $locationType = "Reference"; - } elseif ($file_gui["size"] > 0){ - // lokal - // determine and create mob directory, move uploaded file to directory - $mob_dir = ilObjMediaObject::_getDirectory($mob->getId()); - if (!is_dir($mob_dir)) - $mob->createDirectory(); - - $file_name = ilUtil::getASCIIFilename($_FILES['file_'.$purpose]['name']); - $file_name = str_replace(" ", "_", $file_name); - - $file = $mob_dir."/".$file_name; - $title = $file_name; - $locationType = "LocalFile"; - $location = $title; - ilUtil::moveUploadedFile($_FILES['file_'.$purpose]['tmp_name'], $file_name, $file); - ilUtil::renameExecutables($mob_dir); - - } - - // check if not automatic mimetype detection - if ($_POST["mimetype_".$purpose] != "") - { - $mediaItem->setFormat($_POST["mimetype_".$purpose]); - } - elseif ($mediaItem->getLocation () != "") - { - $format = ilObjMediaObject::getMimeType($mediaItem->getLocation(), ($locationType == "Reference")); - $mediaItem->setFormat($format); - } - - if (isset($file)) - { - // get mime type, if not already set! - if (!isset($format)) - { - $format = ilObjMediaObject::getMimeType($file, ($locationType == "Reference")); - } - - // set real meta and object data - $mediaItem->setFormat($format); - $mediaItem->setLocation($location); - $mediaItem->setLocationType($locationType); - $mediaItem->setHAlign("Left"); - $mediaItem->setHeight(self::isAudio($format)?0:180); - } - - if ($purpose == "Standard") - { - if (isset($title)) - $mob->setTitle ($title); - if (isset($format)) - $mob->setDescription($format); - } - - return $file; - } - - /** - * Update cast item - */ - function updateCastItemObject() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - $ilLog = $this->log; - - $this->checkPermission("write"); - - $this->initAddCastItemForm("edit"); - - if ($this->form_gui->checkInput()) - { - // create new media cast item - include_once("./Services/News/classes/class.ilNewsItem.php"); - $mc_item = new ilNewsItem($_GET["item_id"]); - $mob_id = $mc_item->getMobId(); - - // create dummy object in db (we need an id) - include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); - $mob = new ilObjMediaObject($mob_id); - - - foreach (ilObjMediaCast::$purposes as $purpose) - { - if ($this->form_gui->getInput("delete_".$purpose)) - { - $mob->removeMediaItem($purpose); - $ilLog->write ("Mcst: deleting purpose $purpose"); - continue; - } - $media_item = $mob->getMediaItem($purpose); - $url_gui = $this->form_gui->getInput("url_".$purpose); - $file_gui = $this->form_gui->getInput("file_".$purpose); - - if ($media_item == null) - { - if ($purpose != "Standard" && - ($url_gui || $file_gui["size"]>0)) - { - // check if we added an additional purpose when updating - // either by url or by file - $file = $this->createMediaItemForPurpose($mob, $purpose); - } - } else - { - $file = $this->updateMediaItem($mob, $media_item); - } - - if ($purpose == "Standard") - { - $duration = $this->getDuration($file); - $title = $this->form_gui->getInput("title") != "" ? $this->form_gui->getInput("title") : basename($file); - $description = $this->form_gui->getInput("description"); - - $mob->setTitle($title); - $mob->setDescription($description); - - $prevpic = $this->form_gui->getInput("preview_pic"); - if ($prevpic["size"] > 0) - { - $mob->uploadVideoPreviewPic($prevpic); - } - else - { - $prevpici = $this->form_gui->getItemByPostVar("preview_pic"); - if ($prevpici->getDeletionFlag()) - { - $mob->removeAdditionalFile($mob->getVideoPreviewPic(true)); - } - } - } - } - - // set real meta and object data - $mob->update(); - - // - // @todo: save usage - // - - $news_set = new ilSetting("news"); - $enable_internal_rss = $news_set->get("enable_rss_for_internal"); - - $mc_item->setUserId($ilUser->getId()); - if (isset($duration)) - { - $mc_item->setPlaytime($duration); - } - $mc_item->setTitle($title); - $mc_item->setContent($description); - if ($enable_internal_rss) - { - $mc_item->setVisibility($this->form_gui->getInput("visibility")); - } - $mc_item->update(); - - $ilCtrl->redirect($this, "listItems"); - } - else - { - $this->populateFormFromPost(); - } - } - - /** - * Confirmation Screen. - */ - function confirmDeletionItemsObject() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - $this->checkPermission("write"); - $ilTabs->activateTab("edit_content"); - - if (!is_array($_POST["item_id"])) - { - $this->listItemsObject(); - return; - } - - include_once("Services/Utilities/classes/class.ilConfirmationGUI.php"); - $c_gui = new ilConfirmationGUI(); - - // set confirm/cancel commands - $c_gui->setFormAction($ilCtrl->getFormAction($this, "deleteItems")); - $c_gui->setHeaderText($lng->txt("info_delete_sure")); - $c_gui->setCancel($lng->txt("cancel"), "listItems"); - $c_gui->setConfirm($lng->txt("confirm"), "deleteItems"); - - // add items to delete - include_once("./Services/News/classes/class.ilNewsItem.php"); - foreach($_POST["item_id"] as $item_id) - { - $item = new ilNewsItem($item_id); - $c_gui->addItem("item_id[]", $item_id, $item->getTitle(), - ilUtil::getImagePath("icon_mcst.svg")); - } - - $tpl->setContent($c_gui->getHTML()); - } - - /** - * Delete news items. - */ - function deleteItemsObject() - { - $ilCtrl = $this->ctrl; - - $this->checkPermission("write"); - - // delete all selected news items - foreach($_POST["item_id"] as $item_id) - { - $mc_item = new ilNewsItem($item_id); - $mc_item->delete(); - } - - $ilCtrl->redirect($this, "listItems"); - } - - /** - * Download news media item - */ - function downloadItemObject() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - $this->checkPermission("read"); - $news_item = new ilNewsItem($_GET["item_id"]); - $this->object->handleLPUpdate($ilUser->getId(), $news_item->getMobId()); - if (!$news_item->deliverMobFile($_GET["purpose"], (int) $_GET["presentation"])) - { - $ilCtrl->redirect($this, "listItems"); - } - exit; - } - - /** - * Delete news items. - */ - function determinePlaytimeObject() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $mc_item = new ilNewsItem($_GET["item_id"]); - $mob = $mc_item->getMobId(); - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $mob = new ilObjMediaObject($mob); - $mob_dir = ilObjMediaObject::_getDirectory($mob->getId()); - $m_item = $mob->getMediaItem("Standard"); - $file = $mob_dir."/".$m_item->getLocation(); - $duration = $this->getDuration($file); - if ($duration != "00:00:00") - { - $mc_item->setPlaytime($duration); - $mc_item->update(); - ilUtil::sendSuccess($lng->txt("mcst_set_playtime"), true); - } - else - { - ilUtil::sendFailure($lng->txt("mcst_unable_to_determin_playtime"), true); - } - - $ilCtrl->redirect($this, "listItems"); - } - - /** - * 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 infoScreenObject() - { - if (!$this->checkPermissionBool("read")) - { - $this->checkPermission("visible"); - } - $this->ctrl->setCmd("showSummary"); - $this->ctrl->setCmdClass("ilinfoscreengui"); - $this->infoScreen(); - } - - /** - * show information screen - */ - function infoScreen() - { - $ilAccess = $this->access; - $ilErr = $this->error; - $ilTabs = $this->tabs; - - $ilTabs->activateTab("id_info"); - - if (!$this->checkPermissionBool("read")) - { - $this->checkPermission("visible"); - } - - include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); - $info = new ilInfoScreenGUI($this); - - $info->enablePrivateNotes(); - - // general information - $this->lng->loadLanguageModule("meta"); - $this->lng->loadLanguageModule("mcst"); - $med_items = $this->object->getItemsArray(); - $info->addSection($this->lng->txt("meta_general")); - $info->addProperty($this->lng->txt("mcst_nr_items"), - (int) count($med_items)); - - if (count($med_items) > 0) - { - $cur = current($med_items); - $last = ilDatePresentation::formatDate(new ilDateTime($cur["creation_date"], IL_CAL_DATETIME)); - } - else - { - $last = "-"; - } - - $info->addProperty($this->lng->txt("mcst_last_submission"), $last); - - // forward the command - $this->ctrl->forwardCommand($info); - } - - /** - * get tabs - * @access public - */ - function setTabs() - { - $ilAccess = $this->access; - $ilTabs = $this->tabs; - $lng = $this->lng; - $ilHelp = $this->help; - - $ilHelp->setScreenIdComponent("mcst"); - - // list items - if ($ilAccess->checkAccess('read', "", $this->object->getRefId())) - { - $ilTabs->addTab("content", - $lng->txt("content"), - $this->ctrl->getLinkTarget($this, "showContent")); - } - - // info screen - if ($ilAccess->checkAccess('visible', "", $this->object->getRefId()) || - $ilAccess->checkAccess('read', "", $this->object->getRefId())) - { - $ilTabs->addTab("id_info", - $lng->txt("info_short"), - $this->ctrl->getLinkTargetByClass("ilinfoscreengui", "showSummary")); - } - - // settings - if ($ilAccess->checkAccess('write', "", $this->object->getRefId())) - { - $ilTabs->addTab("id_settings", - $lng->txt("settings"), - $this->ctrl->getLinkTarget($this, "editSettings")); - } - - require_once 'Services/Tracking/classes/class.ilLearningProgressAccess.php'; - if(ilLearningProgressAccess::checkAccess($this->object->getRefId())) - { - $ilTabs->addTab( - 'learning_progress', - $lng->txt('learning_progress'), - $this->ctrl->getLinkTargetByClass(array(__CLASS__, 'illearningprogressgui'),'') - ); - } - - // export - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - $ilTabs->addTab("export", - $lng->txt("export"), - $this->ctrl->getLinkTargetByClass("ilexportgui", "")); - } - - // edit permissions - if ($ilAccess->checkAccess('edit_permission', "", $this->object->getRefId())) - { - $ilTabs->addTab("id_permissions", - $lng->txt("perm_settings"), - $this->ctrl->getLinkTargetByClass("ilpermissiongui", "perm")); - } - } - - /** - * Add content subtabs - * - * @param - * @return - */ - function addContentSubTabs($a_active = "content") - { - $ilTabs = $this->tabs; - $ilAccess = $this->access; - $lng = $this->lng; - - $ilTabs->addSubTab("content", - $lng->txt("view"), - $this->ctrl->getLinkTarget($this, "showContent")); - - if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) - { - $ilTabs->addSubTab("manage", - $lng->txt("mcst_manage"), - $this->ctrl->getLinkTarget($this, "listItems")); - - if ($this->object->getOrder() == ilObjMediaCast::ORDER_MANUAL) - { - $ilTabs->addSubTab("sorting", - $lng->txt("mcst_ordering"), - $this->ctrl->getLinkTarget($this, "editOrder")); - } - } - - $ilTabs->activateSubTab($a_active); - $ilTabs->activateTab("content"); - } - - - /** - * Edit settings - */ - function editSettingsObject() - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - $this->checkPermission("write"); - $ilTabs->activateTab("id_settings"); - - $this->initSettingsForm(); - $tpl->setContent($this->form_gui->getHtml()); - } - - /** - * Init Settings Form - */ - function initSettingsForm() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $obj_service = $this->object_service; - - $lng->loadLanguageModule("mcst"); - - require_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form_gui = new ilPropertyFormGUI(); - $this->form_gui->setTitle($lng->txt("mcst_settings")); - - // Title - $tit = new ilTextInputGUI($lng->txt("title"), "title"); - $tit->setValue($this->object->getTitle()); - $tit->setRequired(true); - $this->form_gui->addItem($tit); - - // description - $des = new ilTextAreaInputGUI($lng->txt("description"), "description"); - $des->setValue($this->object->getLongDescription()); - $this->form_gui->addItem($des); - - $sh = new ilFormSectionHeaderGUI(); - $sh->setTitle($lng->txt("rep_activation_availability")); - $this->form_gui->addItem($sh); - - // Online - $online = new ilCheckboxInputGUI($lng->txt("online"), "online"); - $online->setChecked($this->object->getOnline()); - $this->form_gui->addItem($online); - - // presentation - $sh = new ilFormSectionHeaderGUI(); - $sh->setTitle($lng->txt("obj_presentation")); - $this->form_gui->addItem($sh); - - // tile image - $obj_service->commonSettings()->legacyForm($this->form_gui, $this->object)->addTileImage(); - - // Sorting - $sort = new ilRadioGroupInputGUI($lng->txt("mcst_ordering"), "order"); - $sort->addOption(new ilRadioOption($lng->txt("mcst_ordering_title"), - ilObjMediaCast::ORDER_TITLE)); - $sort->addOption(new ilRadioOption($lng->txt("mcst_ordering_creation_date_asc"), - ilObjMediaCast::ORDER_CREATION_DATE_ASC)); - $sort->addOption(new ilRadioOption($lng->txt("mcst_ordering_creation_date_desc"), - ilObjMediaCast::ORDER_CREATION_DATE_DESC)); - $sort->addOption(new ilRadioOption($lng->txt("mcst_ordering_manual"), - ilObjMediaCast::ORDER_MANUAL)); - $sort->setValue($this->object->getOrder()); - $this->form_gui->addItem($sort); - - // view mode - $options = array( - ilObjMediaCast::VIEW_LIST => $lng->txt("mcst_list"), - ilObjMediaCast::VIEW_GALLERY => $lng->txt("mcst_gallery") - ); - $si = new ilRadioGroupInputGUI($this->lng->txt("mcst_viewmode"), "viewmode"); - $si->addOption(new ilRadioOption($lng->txt("mcst_list"), - ilObjMediaCast::VIEW_LIST)); - $si->addOption(new ilRadioOption($lng->txt("mcst_gallery"), - ilObjMediaCast::VIEW_GALLERY)); - -// $si->setOptions($options); - $si->setValue($this->object->getViewMode()); - $this->form_gui->addItem($si); - - - // Downloadable - $downloadable = new ilCheckboxInputGUI($lng->txt("mcst_downloadable"), "downloadable"); - $downloadable->setChecked($this->object->getDownloadable()); - $downloadable->setInfo($lng->txt("mcst_downloadable_info")); - $this->form_gui->addItem($downloadable); - - $news_set = new ilSetting("news"); - $enable_internal_rss = $news_set->get("enable_rss_for_internal"); - - //Default Visibility - if ($enable_internal_rss) - { - // webfeed - $sh = new ilFormSectionHeaderGUI(); - $sh->setTitle($lng->txt("mcst_webfeed")); - $this->form_gui->addItem($sh); - - $radio_group = new ilRadioGroupInputGUI($lng->txt("news_default_visibility"), "defaultaccess"); - $radio_option = new ilRadioOption($lng->txt("news_visibility_users"), "0"); - $radio_option->setInfo($lng->txt("news_news_item_def_visibility_users_info")); - $radio_group->addOption($radio_option); - $radio_option = new ilRadioOption($lng->txt("news_visibility_public"), "1"); - $radio_option->setInfo($lng->txt("news_news_item_def_visibility_public_info")); - $radio_group->addOption($radio_option); - $radio_group->setRequired(false); - $radio_group->setValue($this->object->getDefaultAccess()); - #$ch->addSubItem($radio_group); - $this->form_gui->addItem($radio_group); - - //Extra Feed - include_once("./Services/Block/classes/class.ilBlockSetting.php"); - $public_feed = ilBlockSetting::_lookup("news", "public_feed", 0, $this->object->getId()); - $ch = new ilCheckboxInputGUI($lng->txt("news_public_feed"), "extra_feed"); - $ch->setInfo($lng->txt("news_public_feed_info")); - $ch->setChecked($public_feed); - $this->form_gui->addItem($ch); - - // keep minimal x number of items - $ni = new ilNumberInputGUI($this->lng->txt("news_keep_minimal_x_items"), "keep_rss_min"); - $ni->setMaxValue(100); - $ni->setMinValue(0); - $ni->setMaxLength(3); - $ni->setSize(3); - $ni->setInfo($this->lng->txt("news_keep_minimal_x_items_info")." (". - ilNewsItem::_lookupRSSPeriod()." ".(ilNewsItem::_lookupRSSPeriod() == 1 ? $lng->txt("day") : $lng->txt("days")).")"); - $ni->setValue((int) ilBlockSetting::_lookup("news", "keep_rss_min", 0, $this->object->getId())); - $ch->addSubItem($ni); - - // Include Files in Pubic Items - $incl_files = new ilCheckboxInputGUI($lng->txt("mcst_incl_files_in_rss"), "public_files"); - $incl_files->setChecked($this->object->getPublicFiles()); - $incl_files->setInfo($lng->txt("mcst_incl_files_in_rss_info")); - #$ch->addSubItem($incl_files); - $this->form_gui->addItem($incl_files); - } - - // Form action and save button - $this->form_gui->addCommandButton("saveSettings", $lng->txt("save")); - $this->form_gui->setFormAction($ilCtrl->getFormAction($this, "saveSettings")); - } - - /** - * Save Settings - */ - function saveSettingsObject() - { - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - $obj_service = $this->object_service; - - $this->checkPermission("write"); - $ilTabs->activateTab("id_settings"); - - $this->initSettingsForm(); - if ($this->form_gui->checkInput()) - { - $news_set = new ilSetting("news"); - $enable_internal_rss = $news_set->get("enable_rss_for_internal"); - - $this->object->setTitle($this->form_gui->getInput("title")); - $this->object->setDescription($this->form_gui->getInput("description")); - $this->object->setOnline($this->form_gui->getInput("online")); - $this->object->setDownloadable($this->form_gui->getInput("downloadable")); - $this->object->setOrder($this->form_gui->getInput("order")); - $this->object->setViewMode($this->form_gui->getInput("viewmode")); - - // tile image - $obj_service->commonSettings()->legacyForm($this->form_gui, $this->object)->saveTileImage(); - - if ($enable_internal_rss) - { - $this->object->setPublicFiles($this->form_gui->getInput("public_files")); - $this->object->setDefaultAccess($this->form_gui->getInput("defaultaccess")); - } - $this->object->update(); - - if ($enable_internal_rss) - { - include_once("./Services/Block/classes/class.ilBlockSetting.php"); - ilBlockSetting::_write("news", "public_feed", - $this->form_gui->getInput("extra_feed"), - 0, $this->object->getId()); - - ilBlockSetting::_write("news", "keep_rss_min", - $this->form_gui->getInput("keep_rss_min"), - 0, $this->object->getId()); - } - - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"),true); - $ilCtrl->redirect($this, "editSettings"); - } - else - { - $this->form_gui->setValuesByPost(); - $this->tpl->setContent($this->form_gui->getHTML()); - } - } - - // add media cast to locator - function addLocatorItems() - { - $ilLocator = $this->locator; - - if (is_object($this->object)) - { - $ilLocator->addItem($this->object->getTitle(), $this->ctrl->getLinkTarget($this, "listItems"), "", $_GET["ref_id"]); - } - } - - public static function _goto($a_target) - { - global $DIC; - - $ilAccess = $DIC->access(); - $ilErr = $DIC["ilErr"]; - $lng = $DIC->language(); - - if ($ilAccess->checkAccess("read", "", $a_target)) - { - $_GET["cmd"] = "showContent"; - $_GET["ref_id"] = $a_target; - $_GET["baseClass"] = "ilmediacasthandlergui"; - $_GET["cmdClass"] = "ilobjmediacastgui"; - include("ilias.php"); - exit; - } - else if ($ilAccess->checkAccess("visible", "", $a_target)) - { - ilObjectGUI::_gotoRepositoryNode($a_target, "infoScreen"); - } - else if ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) - { - ilUtil::sendFailure(sprintf($lng->txt("msg_no_perm_read_item"), - ilObject::_lookupTitle(ilObject::_lookupObjId($a_target)))); - ilObjectGUI::_gotoRepositoryRoot(); - } - - $ilErr->raiseError($lng->txt("msg_no_perm_read"), $ilErr->FATAL); - - } - - /** - * detect audio mimetype - * - * @param string $extension - * @return true, if extension contains string "audio" - */ - protected static function isAudio($extension) { - return strpos($extension,"audio") !== false; - } - - /** - * get MediaItem for id and updates local variable mcst_item - * - * @return ilMediaItem - * - */ - protected function getMediaItem ($id) { - include_once("./Services/News/classes/class.ilNewsItem.php"); - $this->mcst_item = new ilNewsItem($id); - // create dummy object in db (we need an id) - include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); - $mob = new ilObjMediaObject($this->mcst_item->getMobId()); - return $mob->getMediaItem("Standard"); - } - -/** - * get MediaItems for id and updates local variable mcst_item - * - * @return array of ilMediaItem - * - */ - protected function getMediaItems ($id) { - include_once("./Services/News/classes/class.ilNewsItem.php"); - $this->mcst_item = new ilNewsItem($id); - // create dummy object in db (we need an id) - include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); - $mob = new ilObjMediaObject($this->mcst_item->getMobId()); - return $mob->getMediaItems(); - } - - private function populateFormFromPost() - { - $tpl = $this->tpl; - //issue: we have to display the current settings - // problem: POST does not contain values of disabled textfields - // solution: use hidden field and label to display-> here we need to synchronize the labels - // with the values from the hidden fields. - foreach (ilObjMediaCast::$purposes as $purpose) - { - if ($_POST["value_".$purpose]) - { - $_POST["label_value_".$purpose] = $_POST["value_".$purpose]; - } - } - - $this->form_gui->setValuesByPost(); - $tpl->setContent($this->form_gui->getHTML()); - } - - protected function editOrderObject() - { - $ilTabs = $this->tabs; - $lng = $this->lng; - $tpl = $this->tpl; - - $this->checkPermission("write"); - $ilTabs->activateTab("edit_content"); - - $this->addContentSubTabs("sorting"); - - // sort by order setting - switch($this->object->getOrder()) - { - case ilObjMediaCast::ORDER_TITLE: - case ilObjMediaCast::ORDER_CREATION_DATE_ASC: - case ilObjMediaCast::ORDER_CREATION_DATE_DESC: - return $this->listItemsObject(); - - case ilObjMediaCast::ORDER_MANUAL: - // sub-tabs - break; - } - - include_once("./Modules/MediaCast/classes/class.ilMediaCastTableGUI.php"); - $table_gui = new ilMediaCastTableGUI($this, "editOrder", true); - - $table_gui->setTitle($lng->txt("mcst_media_cast")); - $table_gui->setData($this->object->getSortedItemsArray()); - - $table_gui->addCommandButton("saveOrder", $lng->txt("mcst_save_order")); - - $tpl->setContent($table_gui->getHTML()); - } - - function saveOrderObject() - { - $lng = $this->lng; - - asort($_POST["item_id"]); - - $items = array(); - foreach(array_keys($_POST["item_id"]) as $id) - { - $items[] = $id; - } - $this->object->saveOrder($items); - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - $this->ctrl->redirect($this, "editOrder"); - } - - //// - //// Show content - //// - - /** - * Show content - * - * @param - * @return - */ - function showContentObject() - { - $ilUser = $this->user; - - // need read events for parent for LP statistics - require_once 'Services/Tracking/classes/class.ilChangeEvent.php'; - ilChangeEvent::_recordReadEvent("mcst", $this->object->getRefId(), - $this->object->getId(), $ilUser->getId()); - - // trigger LP update - require_once 'Services/Tracking/classes/class.ilLPStatusWrapper.php'; - ilLPStatusWrapper::_updateStatus($this->object->getId(), $ilUser->getId()); - - if ($this->object->getViewMode() == ilObjMediaCast::VIEW_GALLERY) - { - $this->showGallery(); - } - else - { - $this->listItemsObject(true); - } - global $tpl; - $tpl->setPermanentLink($this->object->getType(), $this->object->getRefId()); - } - - function showGallery() - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - - $tpl->addJavascript("./Modules/MediaCast/js/MediaCast.js"); - - $ilTabs->activateTab("content"); - - $this->addContentSubTabs("content"); - - $ctpl = new ilTemplate("tpl.mcst_content.html", true, true, "Modules/MediaCast"); - - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - require_once('./Services/WebAccessChecker/classes/class.ilWACSignedPath.php'); - foreach ($this->object->getSortedItemsArray() as $item) - { - $mob = new ilObjMediaObject($item["mob_id"]); - $med = $mob->getMediaItem("Standard"); - - $ctpl->setCurrentBlock("item"); - $ctpl->setVariable("TITLE", $item["title"]); - $ctpl->setVariable("TIME", $item["playtime"]); - $ctpl->setVariable("ID", $item["id"]); - - if ($mob->getVideoPreviewPic() != "") - { - $ctpl->setVariable("PREVIEW_PIC", - ilUtil::img(ilWACSignedPath::signFile($mob->getVideoPreviewPic()), $item["title"], 320, 240)); - } - else - { - $ctpl->setVariable("PREVIEW_PIC", - ilUtil::img(ilUtil::getImagePath("mcst_preview.svg"), $item["title"], 320, 240)); - } - - // player - if (is_object($med)) - { - include_once("./Services/MediaObjects/classes/class.ilMediaPlayerGUI.php"); - - // the news id will be used as player id, see also ilMediaCastTableGUI - $mpl = new ilMediaPlayerGUI($item["id"], - $ilCtrl->getLinkTarget($this, "handlePlayerEvent", "", true, false)); - - if (strcasecmp("Reference", $med->getLocationType()) == 0) - { - ilWACSignedPath::signFolderOfStartFile($med->getLocation()); - $mpl->setFile($med->getLocation()); - } - else - { - $path_to_file = ilObjMediaObject::_getURL($mob->getId()) . "/" . $med->getLocation(); - ilWACSignedPath::signFolderOfStartFile($path_to_file); - $mpl->setFile($path_to_file); - } - $mpl->setMimeType ($med->getFormat()); - //$mpl->setDisplayHeight($med->getHeight()); - $mpl->setDisplayHeight("480"); - $mpl->setDisplayWidth("640"); - $mpl->setVideoPreviewPic(ilWACSignedPath::signFile($mob->getVideoPreviewPic())); - $mpl->setTitle($item["title"]); - $mpl->setDescription($item["content"]); - $mpl->setForceAudioPreview(true); - if ($this->object->getDownloadable()) - { - $ilCtrl->setParameterByClass("ilobjmediacastgui", "item_id", $item["id"]); - $ilCtrl->setParameterByClass("ilobjmediacastgui", "purpose", "Standard"); - $mpl->setDownloadLink($ilCtrl->getLinkTargetByClass("ilobjmediacastgui", "downloadItem")); - } - $med_alt = $mob->getMediaItem("VideoAlternative"); - if (is_object($med_alt)) - { - $mpl->setAlternativeVideoFile(ilWACSignedPath::signFile(ilObjMediaObject::_getURL($mob->getId())."/". - $med_alt->getLocation())); - $mpl->setAlternativeVideoMimeType($med_alt->getFormat()); - } - - $ctpl->setVariable("PLAYER", $mpl->getPreviewHtml()); - } - - - $ctpl->parseCurrentBlock(); - } - - $feed_icon_html = $this->getFeedIconsHTML(); - - if ($feed_icon_html != "") - { - $feed_icon_html = '

'.$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) - ? "
".implode($ret, "
") - : ""; - - ilUtil::sendInfo($this->lng->txt("mcst_converted_file").$add, true); - } - catch (ilException $e) - { - $ret = ilFFmpeg::getLastReturnValues(); - $add = (is_array($ret) && count($ret) > 0) - ? "
".implode($ret, "
") - : ""; - ilUtil::sendFailure($e->getMessage().$add, true); - } - - - $ilCtrl->redirect($this, "editCastItem"); - } - - /** - * Extract preview image - * - * @param - * @return - */ - function extractPreviewImageObject() - { - $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()); - - try - { - $sec = (int) $_POST["sec"]; - if ($sec < 0) - { - $sec = 0; - } - if ($mob->getVideoPreviewPic() != "") - { - $mob->removeAdditionalFile($mob->getVideoPreviewPic(true)); - } - include_once("./Services/MediaObjects/classes/class.ilFFmpeg.php"); - $med = $mob->getMediaItem("Standard"); - $mob_file = ilObjMediaObject::_getDirectory($mob->getId())."/".$med->getLocation(); - $new_file = ilFFmpeg::extractImage($mob_file, "mob_vpreview.png", - ilObjMediaObject::_getDirectory($mob->getId()), $sec); - - if ($new_file != "") - { - ilUtil::sendInfo($this->lng->txt("mcst_image_extracted"), true); - } - else - { - ilUtil::sendFailure($this->lng->txt("mcst_no_extraction_possible"), true); - } - } - catch (ilException $e) - { - if (DEVMODE == 1) - { - $ret = ilFFmpeg::getLastReturnValues(); - $add = (is_array($ret) && count($ret) > 0) - ? "
".implode($ret, "
") - : ""; - } - ilUtil::sendFailure($e->getMessage().$add, true); - } - - - $ilCtrl->redirect($this, "editCastItem"); - } - - /** - * Handle player event - * - * @param - * @return - */ - function handlePlayerEventObject() - { - if ($_GET["event"] == "play") - { - $player = explode("_", $_GET["player"]); - $news_id = (int) $player[1]; - include_once("./Services/News/classes/class.ilNewsItem.php"); - $item = new ilNewsItem($news_id); - $item->increasePlayCounter(); - - $mob_id = $item->getMobId(); - if($mob_id) - { - $ilUser = $this->user; - $this->object->handleLPUpdate($ilUser->getId(), $mob_id); - } - } - exit; - } - - + return true; + } + + protected function initCreationForms($a_new_type) + { + $forms = array(self::CFORM_NEW => $this->initCreateForm($a_new_type), + self::CFORM_IMPORT => $this->initImportForm($a_new_type), + self::CFORM_CLONE => $this->fillCloneTemplate(null, $a_new_type)); + + return $forms; + } + + /** + * save object + * @access public + */ + public function afterSave(ilObject $newObj) + { + // always send a message + ilUtil::sendSuccess($this->lng->txt("object_added"), true); + ilUtil::redirect("ilias.php?baseClass=ilMediaCastHandlerGUI&ref_id=" . $newObj->getRefId() . "&cmd=editSettings"); + } + + /** + * List items of media cast. + */ + public function listItemsObject($a_presentation_mode = false) + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilAccess = $this->access; + $ilTabs = $this->tabs; + $ilToolbar = $this->toolbar; + + $this->checkPermission("read"); + + if ($a_presentation_mode) { + $this->addContentSubTabs("content"); + } else { + $this->addContentSubTabs("manage"); + } + + $med_items = $this->object->getSortedItemsArray(); + + include_once("./Modules/MediaCast/classes/class.ilMediaCastTableGUI.php"); + if ($a_presentation_mode) { + $table_gui = new ilMediaCastTableGUI($this, "showContent", false, true); + } else { + $table_gui = new ilMediaCastTableGUI($this, "listItems"); + } + + $table_gui->setData($med_items); + + if ($ilAccess->checkAccess("write", "", $_GET["ref_id"]) && !$a_presentation_mode) { + $ilToolbar->addButton($lng->txt("add"), $this->ctrl->getLinkTarget($this, "addCastItem")); + + $table_gui->addMultiCommand("confirmDeletionItems", $lng->txt("delete")); + $table_gui->setSelectAllCheckbox("item_id"); + } + + $feed_icon_html = $this->getFeedIconsHTML(); + if ($feed_icon_html != "") { + $table_gui->setHeaderHTML($feed_icon_html); + } + + $tpl->setContent($table_gui->getHTML()); + } + + /** + * Get feed icons HTML + * + * @param + * @return + */ + public function getFeedIconsHTML() + { + $lng = $this->lng; + + $html = ""; + + include_once("./Services/Block/classes/class.ilBlockSetting.php"); + $public_feed = ilBlockSetting::_lookup( + "news", + "public_feed", + 0, + $this->object->getId() + ); + + // rss icon/link + if ($public_feed) { + $news_set = new ilSetting("news"); + $enable_internal_rss = $news_set->get("enable_rss_for_internal"); + + if ($enable_internal_rss) { + // create dummy object in db (we need an id) + $items = $this->object->getItemsArray(); + include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); + $html = ""; + foreach (ilObjMediaCast::$purposes as $purpose) { + foreach ($items as $id => $item) { + $mob = new ilObjMediaObject($item["mob_id"]); + $mob->read(); + if ($mob->hasPurposeItem($purpose)) { + if ($html == "") { + $html = " "; + } + $url = ILIAS_HTTP_PATH . "/feed.php?client_id=" . rawurlencode(CLIENT_ID) . "&" . "ref_id=" . $_GET["ref_id"] . "&purpose=$purpose"; + $title = $lng->txt("news_feed_url"); + + include_once("./Services/News/classes/class.ilRSSButtonGUI.php"); + switch (strtolower($purpose)) { + case "audioportable": + $type1 = ilRSSButtonGUI::ICON_RSS_AUDIO; + $type2 = ilRSSButtonGUI::ICON_ITUNES_AUDIO; + break; + + case "videoportable": + $type1 = ilRSSButtonGUI::ICON_RSS_VIDEO; + $type2 = ilRSSButtonGUI::ICON_ITUNES_VIDEO; + break; + + default: + $type1 = ilRSSButtonGUI::ICON_RSS; + $type2 = ilRSSButtonGUI::ICON_ITUNES; + break; + } + $row1 .= " " . ilRSSButtonGUI::get($type1, $url); + if ($this->object->getPublicFiles()) { + $url = preg_replace("/https?/i", "itpc", $url); + $title = $lng->txt("news_feed_url"); + + include_once("./Services/News/classes/class.ilRSSButtonGUI.php"); + $row2 .= " " . ilRSSButtonGUI::get($type2, $url); + } + break; + } + } + } + if ($html != "") { + $html .= $row1; + if ($row2 != "") { + $html .= $row2; + } + } + } + } + return $html; + } + + + /** + * Add media cast item + */ + public function addCastItemObject() + { + $tpl = $this->tpl; + + $this->checkPermission("write"); + + $this->initAddCastItemForm(); + $tpl->setContent($this->form_gui->getHTML()); + } + + /** + * Edit media cast item + */ + public function editCastItemObject() + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $ilCtrl = $this->ctrl; + + $this->checkPermission("write"); + + // conversion toolbar + include_once("./Services/MediaObjects/classes/class.ilFFmpeg.php"); + if (ilFFmpeg::enabled()) { + $this->mcst_item = new ilNewsItem($_GET["item_id"]); + include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); + $mob = new ilObjMediaObject($this->mcst_item->getMobId()); + + $conv_cnt = 0; + // we had other purposes as source as well, but + // currently only "Standard" is implemented in the convertFile method + foreach (array("Standard") as $p) { + /* + $med = $mob->getMediaItem($p); + if (is_object($med)) + { + $options = ilFFmpeg::getPossibleTargetMimeTypes($med->getFormat()); + if (count($options) > 0) + { + if ($conv_cnt > 0) + { + $ilToolbar->addSeparator(); + } + + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $si = new ilSelectInputGUI($this->lng->txt("mcst_conv_". + strtolower($p)."_to"), "target_format"); + $si->setOptions($options); + $ilToolbar->addInputItem($si, true); + + $si = new ilSelectInputGUI(", ".$this->lng->txt("mcst_target").": ", + "target_purpose"); + $si->setOptions(array("Standard" => $this->lng->txt("mcst_purpose_standard"), + "VideoAlternative" => $this->lng->txt("mcst_purpose_videoalternative") + )); + $si->setValue($p); + $ilToolbar->addInputItem($si, true); + + $ilToolbar->addFormButton($this->lng->txt("mcst_convert"), "convertFile"); + + $conv_cnt++; + } + } + */ + + $med = $mob->getMediaItem($p); + if (is_object($med)) { + if (ilFFmpeg::supportsImageExtraction($med->getFormat())) { + // second + include_once("./Services/Form/classes/class.ilTextInputGUI.php"); + $ni = new ilTextInputGUI($this->lng->txt("mcst_second"), "sec"); + $ni->setMaxLength(4); + $ni->setSize(4); + $ni->setValue(1); + $ilToolbar->addInputItem($ni, true); + + $ilToolbar->addFormButton($this->lng->txt("mcst_extract_preview_image"), "extractPreviewImage"); + $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); + } + } + + /*if ($conv_cnt > 0) + { + $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); + }*/ + } + } + + $this->initAddCastItemForm("edit"); + $this->getCastItemValues(); + $tpl->setContent($this->form_gui->getHTML()); + } + + /** + * Init add cast item form. + */ + public function initAddCastItemForm($a_mode = "create") + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + $this->checkPermission("write"); + $ilTabs->activateTab("edit_content"); + + $lng->loadLanguageModule("mcst"); + + $news_set = new ilSetting("news"); + $enable_internal_rss = $news_set->get("enable_rss_for_internal"); + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form_gui = new ilPropertyFormGUI(); + $this->form_gui->setMultipart(true); + + // Property Title + $text_input = new ilTextInputGUI($lng->txt("title"), "title"); + $text_input->setMaxLength(200); + $this->form_gui->addItem($text_input); + + // Property Content + $text_area = new ilTextAreaInputGUI($lng->txt("description"), "description"); + $text_area->setRequired(false); + $this->form_gui->addItem($text_area); + + // Property Visibility + if ($enable_internal_rss) { + $radio_group = new ilRadioGroupInputGUI($lng->txt("access_scope"), "visibility"); + $radio_option = new ilRadioOption($lng->txt("access_users"), "users"); + $radio_group->addOption($radio_option); + $radio_option = new ilRadioOption($lng->txt("access_public"), "public"); + $radio_group->addOption($radio_option); + $radio_group->setInfo($lng->txt("mcst_visibility_info")); + $radio_group->setRequired(true); + $radio_group->setValue($this->object->getDefaultAccess() == 0 ? "users" : "public"); + $this->form_gui->addItem($radio_group); + } + + // Duration + $dur = new ilDurationInputGUI($lng->txt("mcst_duration"), "duration"); + $dur->setInfo($lng->txt("mcst_duration_info")); + $dur->setShowDays(false); + $dur->setShowHours(true); + $dur->setShowSeconds(true); + $this->form_gui->addItem($dur); + + foreach (ilObjMediaCast::$purposes as $purpose) { + if ($purpose == "VideoAlternative" && + $a_mode == "create") { + continue; + } + + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($lng->txt("mcst_" . strtolower($purpose) . "_title")); + $this->form_gui->addItem($section); + if ($a_mode != "create") { + $value = new ilHiddenInputGUI("value_" . $purpose); + $label = new ilNonEditableValueGUI($lng->txt("value")); + $label->setPostVar("label_value_" . $purpose); + $label->setInfo($lng->txt("mcst_current_value_info")); + $this->form_gui->addItem($label); + $this->form_gui->addItem($value); + } + $file = new ilFileInputGUI($lng->txt("file"), "file_" . $purpose); + $file->setSuffixes($this->purposeSuffixes[$purpose]); + $this->form_gui->addItem($file); + $text_input = new ilRegExpInputGUI($lng->txt("url"), "url_" . $purpose); + $text_input->setPattern("/https?\:\/\/.+/i"); + $text_input->setInfo($lng->txt("mcst_reference_info")); + $this->form_gui->addItem($text_input); + if ($purpose != "Standard") { + $clearCheckBox = new ilCheckboxInputGUI(); + $clearCheckBox->setPostVar("delete_" . $purpose); + $clearCheckBox->setTitle($lng->txt("mcst_clear_purpose_title")); + $this->form_gui->addItem($clearCheckBox); + } else { + + // mime type selection + $mimeTypeSelection = new ilSelectInputGUI(); + $mimeTypeSelection->setPostVar("mimetype_" . $purpose); + $mimeTypeSelection->setTitle($lng->txt("mcst_mimetype")); + $mimeTypeSelection->setInfo($lng->txt("mcst_mimetype_info")); + $options = array("" => $lng->txt("mcst_automatic_detection")); + $options = array_merge($options, $this->mimeTypes); + $mimeTypeSelection->setOptions($options); + $this->form_gui->addItem($mimeTypeSelection); + + // preview picure + $pp = new ilImageFileInputGUI($lng->txt("mcst_preview_picture"), "preview_pic"); + $pp->setSuffixes(array("png", "jpeg", "jpg")); + $pp->setInfo($lng->txt("mcst_preview_picture_info") . " mp4, mp3, png, jp(e)g, gif"); + $this->form_gui->addItem($pp); + } + } + + // save/cancel button + if ($a_mode == "create") { + $this->form_gui->setTitle($lng->txt("mcst_add_new_item")); + $this->form_gui->addCommandButton("saveCastItem", $lng->txt("save")); + } else { + $this->form_gui->setTitle($lng->txt("mcst_edit_item")); + $this->form_gui->addCommandButton("updateCastItem", $lng->txt("save")); + } + $this->form_gui->addCommandButton("listItems", $lng->txt("cancel")); + $this->form_gui->setFormAction($ilCtrl->getFormAction($this, "saveCastItem")); + } + + /** + * Get cast item values into form. + */ + public function getCastItemValues() + { + $lng = $this->lng; + + // get mob + $this->mcst_item = new ilNewsItem($_GET["item_id"]); + include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); + $mob = new ilObjMediaObject($this->mcst_item->getMobId()); + + // preview + $ppic = $mob->getVideoPreviewPic(); + if ($ppic != "") { + $i = $this->form_gui->getItemByPostVar("preview_pic"); + $i->setImage($ppic); + } + + + $values = array(); + $mediaItems = $this->getMediaItems($_GET["item_id"]); + if (count($mediaItems) > 0) { + foreach ($mediaItems as $med) { + if (!isset($values["title"])) { + // first item, so set title, description, ... + $values["title"] = $this->mcst_item->getTitle(); + $values["description"] = $this->mcst_item->getContent(); + $values["visibility"] = $this->mcst_item->getVisibility(); + $length = explode(":", $this->mcst_item->getPlaytime()); + $values["duration"] = array("hh" => $length[0], "mm" => $length[1], "ss" => $length[2]); + } + + $values["value_" . $med->getPurpose()] = (strlen($med->getLocation())> 100) ? "..." . substr($med->getLocation(), strlen($med->getLocation()) - 100) : $med->getLocation(); + $values["label_value_" . $med->getPurpose()] = (strlen($med->getLocation())> 100) ? "..." . substr($med->getLocation(), strlen($med->getLocation()) - 100) : $med->getLocation(); + $values["mimetype_" . $med->getPurpose()] = $med->getFormat(); + } + } + foreach (ilObjMediaCast::$purposes as $purpose) { + if (!isset($values["value_" . $purpose])) { + $values["label_value_" . $purpose] = $lng->txt("none"); + $values["value_" . $purpose] = $lng->txt("none"); + } + } + $this->form_gui->setValuesByArray($values); + } + + /** + * Save new cast item + */ + public function saveCastItemObject() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + $lng = $this->lng; + $ilTabs = $this->tabs; + + $this->checkPermission("write"); + $ilTabs->activateTab("edit_content"); + + $this->initAddCastItemForm(); + + if (!$this->form_gui->checkInput() || + ($_POST["url_Standard"] == "" && !$_FILES['file_Standard']['tmp_name'])) { + if (($_POST["url_Standard"] == "" && !$_FILES['file_Standard']['tmp_name'])) { + ilUtil::sendFailure($lng->txt("mcst_input_either_file_or_url")); + } + $this->populateFormFromPost(); + } else { + // create dummy object in db (we need an id) + include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); + $mob = new ilObjMediaObject(); + $mob->create(); + + //handle standard purpose + $file = $this->createMediaItemForPurpose($mob, "Standard"); + + // set title and description + // set title to basename of file if left empty + $title = $this->form_gui->getInput("title") != "" ? $this->form_gui->getInput("title") : basename($file); + $description = $this->form_gui->getInput("description"); + $mob->setTitle($title); + $mob->setDescription($description); + + // save preview pic + $prevpic = $this->form_gui->getInput("preview_pic"); + if ($prevpic["size"] > 0) { + $mob->uploadVideoPreviewPic($prevpic); + } + + // determine duration for standard purpose + $duration = $this->getDuration($file); + + // handle other purposes + foreach ($this->additionalPurposes as $purpose) { + // check if some purpose has been uploaded + $file_gui = $this->form_gui->getInput("file_" . $purpose); + $url_gui = $this->form_gui->getInput("url_" . $purpose); + if ($url_gui || $file_gui["size"] > 0) { + $this->createMediaItemForPurpose($mob, $purpose); + } + } + + $mob->update(); + + if ($prevpic["size"] == 0) { + // re-read media object + $mob = new ilObjMediaObject($mob->getId()); + $mob->generatePreviewPic(320, 240); + } + + // + // @todo: save usage + // + + $news_set = new ilSetting("news"); + $enable_internal_rss = $news_set->get("enable_rss_for_internal"); + + // create new media cast item + include_once("./Services/News/classes/class.ilNewsItem.php"); + $mc_item = new ilNewsItem(); + $mc_item->setMobId($mob->getId()); + $mc_item->setContentType(NEWS_AUDIO); + $mc_item->setContextObjId($this->object->getId()); + $mc_item->setContextObjType($this->object->getType()); + $mc_item->setUserId($ilUser->getId()); + $mc_item->setPlaytime($duration); + $mc_item->setTitle($title); + $mc_item->setContent($description); + $mc_item->setLimitation(false); + if ($enable_internal_rss) { + $mc_item->setVisibility($this->form_gui->getInput("visibility")); + } else { + $mc_item->setVisibility("users"); + } + $mc_item->create(); + + $ilCtrl->redirect($this, "listItems"); + } + } + + /** + * get duration from form or from file analyzer + * + * @param unknown_type $file + * @return unknown + */ + private function getDuration($file) + { + $duration = isset($this->form_gui) + ? $this->form_gui->getInput("duration") + : array("hh"=>0, "mm"=>0, "ss"=>0); + if ($duration["hh"] == 0 && $duration["mm"] == 0 && $duration["ss"] == 0 && is_file($file)) { + include_once("./Services/MediaObjects/classes/class.ilMediaAnalyzer.php"); + $ana = new ilMediaAnalyzer(); + $ana->setFile($file); + $ana->analyzeFile(); + $dur = $ana->getPlaytimeString(); + $dur = explode(":", $dur); + $duration["mm"] = $dur[0]; + $duration["ss"] = $dur[1]; + } + $duration = str_pad($duration["hh"], 2, "0", STR_PAD_LEFT) . ":" . + str_pad($duration["mm"], 2, "0", STR_PAD_LEFT) . ":" . + str_pad($duration["ss"], 2, "0", STR_PAD_LEFT); + return $duration; + } + + /** + * handle media item for given purpose + * + * @param ilMediaObject $mob + * @param string file + */ + private function createMediaItemForPurpose($mob, $purpose) + { + $mediaItem = new ilMediaItem(); + $mob->addMediaItem($mediaItem); + $mediaItem->setPurpose($purpose); + return $this->updateMediaItem($mob, $mediaItem); + } + + /** + * update media item from form + * + * @param IlObjectMediaObject $mob + * @param IlMediaItem $mediaItem + * @return string file + */ + private function updateMediaItem($mob, &$mediaItem) + { + $purpose = $mediaItem->getPurpose(); + $url_gui = $this->form_gui->getInput("url_" . $purpose); + $file_gui = $this->form_gui->getInput("file_" . $purpose); + if ($url_gui) { + // http + $file = $this->form_gui->getInput("url_" . $purpose); + $title = basename($file); + $location = $this->form_gui->getInput("url_" . $purpose); + $locationType = "Reference"; + } elseif ($file_gui["size"] > 0) { + // lokal + // determine and create mob directory, move uploaded file to directory + $mob_dir = ilObjMediaObject::_getDirectory($mob->getId()); + if (!is_dir($mob_dir)) { + $mob->createDirectory(); + } + + $file_name = ilUtil::getASCIIFilename($_FILES['file_' . $purpose]['name']); + $file_name = str_replace(" ", "_", $file_name); + + $file = $mob_dir . "/" . $file_name; + $title = $file_name; + $locationType = "LocalFile"; + $location = $title; + ilUtil::moveUploadedFile($_FILES['file_' . $purpose]['tmp_name'], $file_name, $file); + ilUtil::renameExecutables($mob_dir); + } + + // check if not automatic mimetype detection + if ($_POST["mimetype_" . $purpose] != "") { + $mediaItem->setFormat($_POST["mimetype_" . $purpose]); + } elseif ($mediaItem->getLocation() != "") { + $format = ilObjMediaObject::getMimeType($mediaItem->getLocation(), ($locationType == "Reference")); + $mediaItem->setFormat($format); + } + + if (isset($file)) { + // get mime type, if not already set! + if (!isset($format)) { + $format = ilObjMediaObject::getMimeType($file, ($locationType == "Reference")); + } + + // set real meta and object data + $mediaItem->setFormat($format); + $mediaItem->setLocation($location); + $mediaItem->setLocationType($locationType); + $mediaItem->setHAlign("Left"); + $mediaItem->setHeight(self::isAudio($format)?0:180); + } + + if ($purpose == "Standard") { + if (isset($title)) { + $mob->setTitle($title); + } + if (isset($format)) { + $mob->setDescription($format); + } + } + + return $file; + } + + /** + * Update cast item + */ + public function updateCastItemObject() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + $ilLog = $this->log; + + $this->checkPermission("write"); + + $this->initAddCastItemForm("edit"); + + if ($this->form_gui->checkInput()) { + // create new media cast item + include_once("./Services/News/classes/class.ilNewsItem.php"); + $mc_item = new ilNewsItem($_GET["item_id"]); + $mob_id = $mc_item->getMobId(); + + // create dummy object in db (we need an id) + include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); + $mob = new ilObjMediaObject($mob_id); + + + foreach (ilObjMediaCast::$purposes as $purpose) { + if ($this->form_gui->getInput("delete_" . $purpose)) { + $mob->removeMediaItem($purpose); + $ilLog->write("Mcst: deleting purpose $purpose"); + continue; + } + $media_item = $mob->getMediaItem($purpose); + $url_gui = $this->form_gui->getInput("url_" . $purpose); + $file_gui = $this->form_gui->getInput("file_" . $purpose); + + if ($media_item == null) { + if ($purpose != "Standard" && + ($url_gui || $file_gui["size"]>0)) { + // check if we added an additional purpose when updating + // either by url or by file + $file = $this->createMediaItemForPurpose($mob, $purpose); + } + } else { + $file = $this->updateMediaItem($mob, $media_item); + } + + if ($purpose == "Standard") { + $duration = $this->getDuration($file); + $title = $this->form_gui->getInput("title") != "" ? $this->form_gui->getInput("title") : basename($file); + $description = $this->form_gui->getInput("description"); + + $mob->setTitle($title); + $mob->setDescription($description); + + $prevpic = $this->form_gui->getInput("preview_pic"); + if ($prevpic["size"] > 0) { + $mob->uploadVideoPreviewPic($prevpic); + } else { + $prevpici = $this->form_gui->getItemByPostVar("preview_pic"); + if ($prevpici->getDeletionFlag()) { + $mob->removeAdditionalFile($mob->getVideoPreviewPic(true)); + } + } + } + } + + // set real meta and object data + $mob->update(); + + // + // @todo: save usage + // + + $news_set = new ilSetting("news"); + $enable_internal_rss = $news_set->get("enable_rss_for_internal"); + + $mc_item->setUserId($ilUser->getId()); + if (isset($duration)) { + $mc_item->setPlaytime($duration); + } + $mc_item->setTitle($title); + $mc_item->setContent($description); + if ($enable_internal_rss) { + $mc_item->setVisibility($this->form_gui->getInput("visibility")); + } + $mc_item->update(); + + $ilCtrl->redirect($this, "listItems"); + } else { + $this->populateFormFromPost(); + } + } + + /** + * Confirmation Screen. + */ + public function confirmDeletionItemsObject() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + $this->checkPermission("write"); + $ilTabs->activateTab("edit_content"); + + if (!is_array($_POST["item_id"])) { + $this->listItemsObject(); + return; + } + + include_once("Services/Utilities/classes/class.ilConfirmationGUI.php"); + $c_gui = new ilConfirmationGUI(); + + // set confirm/cancel commands + $c_gui->setFormAction($ilCtrl->getFormAction($this, "deleteItems")); + $c_gui->setHeaderText($lng->txt("info_delete_sure")); + $c_gui->setCancel($lng->txt("cancel"), "listItems"); + $c_gui->setConfirm($lng->txt("confirm"), "deleteItems"); + + // add items to delete + include_once("./Services/News/classes/class.ilNewsItem.php"); + foreach ($_POST["item_id"] as $item_id) { + $item = new ilNewsItem($item_id); + $c_gui->addItem( + "item_id[]", + $item_id, + $item->getTitle(), + ilUtil::getImagePath("icon_mcst.svg") + ); + } + + $tpl->setContent($c_gui->getHTML()); + } + + /** + * Delete news items. + */ + public function deleteItemsObject() + { + $ilCtrl = $this->ctrl; + + $this->checkPermission("write"); + + // delete all selected news items + foreach ($_POST["item_id"] as $item_id) { + $mc_item = new ilNewsItem($item_id); + $mc_item->delete(); + } + + $ilCtrl->redirect($this, "listItems"); + } + + /** + * Download news media item + */ + public function downloadItemObject() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + $this->checkPermission("read"); + $news_item = new ilNewsItem($_GET["item_id"]); + $this->object->handleLPUpdate($ilUser->getId(), $news_item->getMobId()); + if (!$news_item->deliverMobFile($_GET["purpose"], (int) $_GET["presentation"])) { + $ilCtrl->redirect($this, "listItems"); + } + exit; + } + + /** + * Delete news items. + */ + public function determinePlaytimeObject() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $mc_item = new ilNewsItem($_GET["item_id"]); + $mob = $mc_item->getMobId(); + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $mob = new ilObjMediaObject($mob); + $mob_dir = ilObjMediaObject::_getDirectory($mob->getId()); + $m_item = $mob->getMediaItem("Standard"); + $file = $mob_dir . "/" . $m_item->getLocation(); + $duration = $this->getDuration($file); + if ($duration != "00:00:00") { + $mc_item->setPlaytime($duration); + $mc_item->update(); + ilUtil::sendSuccess($lng->txt("mcst_set_playtime"), true); + } else { + ilUtil::sendFailure($lng->txt("mcst_unable_to_determin_playtime"), true); + } + + $ilCtrl->redirect($this, "listItems"); + } + + /** + * 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 infoScreenObject() + { + if (!$this->checkPermissionBool("read")) { + $this->checkPermission("visible"); + } + $this->ctrl->setCmd("showSummary"); + $this->ctrl->setCmdClass("ilinfoscreengui"); + $this->infoScreen(); + } + + /** + * show information screen + */ + public function infoScreen() + { + $ilAccess = $this->access; + $ilErr = $this->error; + $ilTabs = $this->tabs; + + $ilTabs->activateTab("id_info"); + + if (!$this->checkPermissionBool("read")) { + $this->checkPermission("visible"); + } + + include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); + $info = new ilInfoScreenGUI($this); + + $info->enablePrivateNotes(); + + // general information + $this->lng->loadLanguageModule("meta"); + $this->lng->loadLanguageModule("mcst"); + $med_items = $this->object->getItemsArray(); + $info->addSection($this->lng->txt("meta_general")); + $info->addProperty( + $this->lng->txt("mcst_nr_items"), + (int) count($med_items) + ); + + if (count($med_items) > 0) { + $cur = current($med_items); + $last = ilDatePresentation::formatDate(new ilDateTime($cur["creation_date"], IL_CAL_DATETIME)); + } else { + $last = "-"; + } + + $info->addProperty($this->lng->txt("mcst_last_submission"), $last); + + // forward the command + $this->ctrl->forwardCommand($info); + } + + /** + * get tabs + * @access public + */ + public function setTabs() + { + $ilAccess = $this->access; + $ilTabs = $this->tabs; + $lng = $this->lng; + $ilHelp = $this->help; + + $ilHelp->setScreenIdComponent("mcst"); + + // list items + if ($ilAccess->checkAccess('read', "", $this->object->getRefId())) { + $ilTabs->addTab( + "content", + $lng->txt("content"), + $this->ctrl->getLinkTarget($this, "showContent") + ); + } + + // info screen + if ($ilAccess->checkAccess('visible', "", $this->object->getRefId()) || + $ilAccess->checkAccess('read', "", $this->object->getRefId())) { + $ilTabs->addTab( + "id_info", + $lng->txt("info_short"), + $this->ctrl->getLinkTargetByClass("ilinfoscreengui", "showSummary") + ); + } + + // settings + if ($ilAccess->checkAccess('write', "", $this->object->getRefId())) { + $ilTabs->addTab( + "id_settings", + $lng->txt("settings"), + $this->ctrl->getLinkTarget($this, "editSettings") + ); + } + + require_once 'Services/Tracking/classes/class.ilLearningProgressAccess.php'; + if (ilLearningProgressAccess::checkAccess($this->object->getRefId())) { + $ilTabs->addTab( + 'learning_progress', + $lng->txt('learning_progress'), + $this->ctrl->getLinkTargetByClass(array(__CLASS__, 'illearningprogressgui'), '') + ); + } + + // export + if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) { + $ilTabs->addTab( + "export", + $lng->txt("export"), + $this->ctrl->getLinkTargetByClass("ilexportgui", "") + ); + } + + // edit permissions + if ($ilAccess->checkAccess('edit_permission', "", $this->object->getRefId())) { + $ilTabs->addTab( + "id_permissions", + $lng->txt("perm_settings"), + $this->ctrl->getLinkTargetByClass("ilpermissiongui", "perm") + ); + } + } + + /** + * Add content subtabs + * + * @param + * @return + */ + public function addContentSubTabs($a_active = "content") + { + $ilTabs = $this->tabs; + $ilAccess = $this->access; + $lng = $this->lng; + + $ilTabs->addSubTab( + "content", + $lng->txt("view"), + $this->ctrl->getLinkTarget($this, "showContent") + ); + + if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) { + $ilTabs->addSubTab( + "manage", + $lng->txt("mcst_manage"), + $this->ctrl->getLinkTarget($this, "listItems") + ); + + if ($this->object->getOrder() == ilObjMediaCast::ORDER_MANUAL) { + $ilTabs->addSubTab( + "sorting", + $lng->txt("mcst_ordering"), + $this->ctrl->getLinkTarget($this, "editOrder") + ); + } + } + + $ilTabs->activateSubTab($a_active); + $ilTabs->activateTab("content"); + } + + + /** + * Edit settings + */ + public function editSettingsObject() + { + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + $this->checkPermission("write"); + $ilTabs->activateTab("id_settings"); + + $this->initSettingsForm(); + $tpl->setContent($this->form_gui->getHtml()); + } + + /** + * Init Settings Form + */ + public function initSettingsForm() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $obj_service = $this->object_service; + + $lng->loadLanguageModule("mcst"); + + require_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form_gui = new ilPropertyFormGUI(); + $this->form_gui->setTitle($lng->txt("mcst_settings")); + + // Title + $tit = new ilTextInputGUI($lng->txt("title"), "title"); + $tit->setValue($this->object->getTitle()); + $tit->setRequired(true); + $this->form_gui->addItem($tit); + + // description + $des = new ilTextAreaInputGUI($lng->txt("description"), "description"); + $des->setValue($this->object->getLongDescription()); + $this->form_gui->addItem($des); + + $sh = new ilFormSectionHeaderGUI(); + $sh->setTitle($lng->txt("rep_activation_availability")); + $this->form_gui->addItem($sh); + + // Online + $online = new ilCheckboxInputGUI($lng->txt("online"), "online"); + $online->setChecked($this->object->getOnline()); + $this->form_gui->addItem($online); + + // presentation + $sh = new ilFormSectionHeaderGUI(); + $sh->setTitle($lng->txt("obj_presentation")); + $this->form_gui->addItem($sh); + + // tile image + $obj_service->commonSettings()->legacyForm($this->form_gui, $this->object)->addTileImage(); + + // Sorting + $sort = new ilRadioGroupInputGUI($lng->txt("mcst_ordering"), "order"); + $sort->addOption(new ilRadioOption( + $lng->txt("mcst_ordering_title"), + ilObjMediaCast::ORDER_TITLE + )); + $sort->addOption(new ilRadioOption( + $lng->txt("mcst_ordering_creation_date_asc"), + ilObjMediaCast::ORDER_CREATION_DATE_ASC + )); + $sort->addOption(new ilRadioOption( + $lng->txt("mcst_ordering_creation_date_desc"), + ilObjMediaCast::ORDER_CREATION_DATE_DESC + )); + $sort->addOption(new ilRadioOption( + $lng->txt("mcst_ordering_manual"), + ilObjMediaCast::ORDER_MANUAL + )); + $sort->setValue($this->object->getOrder()); + $this->form_gui->addItem($sort); + + // view mode + $options = array( + ilObjMediaCast::VIEW_LIST => $lng->txt("mcst_list"), + ilObjMediaCast::VIEW_GALLERY => $lng->txt("mcst_gallery") + ); + $si = new ilRadioGroupInputGUI($this->lng->txt("mcst_viewmode"), "viewmode"); + $si->addOption(new ilRadioOption( + $lng->txt("mcst_list"), + ilObjMediaCast::VIEW_LIST + )); + $si->addOption(new ilRadioOption( + $lng->txt("mcst_gallery"), + ilObjMediaCast::VIEW_GALLERY + )); + + // $si->setOptions($options); + $si->setValue($this->object->getViewMode()); + $this->form_gui->addItem($si); + + + // Downloadable + $downloadable = new ilCheckboxInputGUI($lng->txt("mcst_downloadable"), "downloadable"); + $downloadable->setChecked($this->object->getDownloadable()); + $downloadable->setInfo($lng->txt("mcst_downloadable_info")); + $this->form_gui->addItem($downloadable); + + $news_set = new ilSetting("news"); + $enable_internal_rss = $news_set->get("enable_rss_for_internal"); + + //Default Visibility + if ($enable_internal_rss) { + // webfeed + $sh = new ilFormSectionHeaderGUI(); + $sh->setTitle($lng->txt("mcst_webfeed")); + $this->form_gui->addItem($sh); + + $radio_group = new ilRadioGroupInputGUI($lng->txt("news_default_visibility"), "defaultaccess"); + $radio_option = new ilRadioOption($lng->txt("news_visibility_users"), "0"); + $radio_option->setInfo($lng->txt("news_news_item_def_visibility_users_info")); + $radio_group->addOption($radio_option); + $radio_option = new ilRadioOption($lng->txt("news_visibility_public"), "1"); + $radio_option->setInfo($lng->txt("news_news_item_def_visibility_public_info")); + $radio_group->addOption($radio_option); + $radio_group->setRequired(false); + $radio_group->setValue($this->object->getDefaultAccess()); + #$ch->addSubItem($radio_group); + $this->form_gui->addItem($radio_group); + + //Extra Feed + include_once("./Services/Block/classes/class.ilBlockSetting.php"); + $public_feed = ilBlockSetting::_lookup("news", "public_feed", 0, $this->object->getId()); + $ch = new ilCheckboxInputGUI($lng->txt("news_public_feed"), "extra_feed"); + $ch->setInfo($lng->txt("news_public_feed_info")); + $ch->setChecked($public_feed); + $this->form_gui->addItem($ch); + + // keep minimal x number of items + $ni = new ilNumberInputGUI($this->lng->txt("news_keep_minimal_x_items"), "keep_rss_min"); + $ni->setMaxValue(100); + $ni->setMinValue(0); + $ni->setMaxLength(3); + $ni->setSize(3); + $ni->setInfo($this->lng->txt("news_keep_minimal_x_items_info") . " (" . + ilNewsItem::_lookupRSSPeriod() . " " . (ilNewsItem::_lookupRSSPeriod() == 1 ? $lng->txt("day") : $lng->txt("days")) . ")"); + $ni->setValue((int) ilBlockSetting::_lookup("news", "keep_rss_min", 0, $this->object->getId())); + $ch->addSubItem($ni); + + // Include Files in Pubic Items + $incl_files = new ilCheckboxInputGUI($lng->txt("mcst_incl_files_in_rss"), "public_files"); + $incl_files->setChecked($this->object->getPublicFiles()); + $incl_files->setInfo($lng->txt("mcst_incl_files_in_rss_info")); + #$ch->addSubItem($incl_files); + $this->form_gui->addItem($incl_files); + } + + // Form action and save button + $this->form_gui->addCommandButton("saveSettings", $lng->txt("save")); + $this->form_gui->setFormAction($ilCtrl->getFormAction($this, "saveSettings")); + } + + /** + * Save Settings + */ + public function saveSettingsObject() + { + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + $obj_service = $this->object_service; + + $this->checkPermission("write"); + $ilTabs->activateTab("id_settings"); + + $this->initSettingsForm(); + if ($this->form_gui->checkInput()) { + $news_set = new ilSetting("news"); + $enable_internal_rss = $news_set->get("enable_rss_for_internal"); + + $this->object->setTitle($this->form_gui->getInput("title")); + $this->object->setDescription($this->form_gui->getInput("description")); + $this->object->setOnline($this->form_gui->getInput("online")); + $this->object->setDownloadable($this->form_gui->getInput("downloadable")); + $this->object->setOrder($this->form_gui->getInput("order")); + $this->object->setViewMode($this->form_gui->getInput("viewmode")); + + // tile image + $obj_service->commonSettings()->legacyForm($this->form_gui, $this->object)->saveTileImage(); + + if ($enable_internal_rss) { + $this->object->setPublicFiles($this->form_gui->getInput("public_files")); + $this->object->setDefaultAccess($this->form_gui->getInput("defaultaccess")); + } + $this->object->update(); + + if ($enable_internal_rss) { + include_once("./Services/Block/classes/class.ilBlockSetting.php"); + ilBlockSetting::_write( + "news", + "public_feed", + $this->form_gui->getInput("extra_feed"), + 0, + $this->object->getId() + ); + + ilBlockSetting::_write( + "news", + "keep_rss_min", + $this->form_gui->getInput("keep_rss_min"), + 0, + $this->object->getId() + ); + } + + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "editSettings"); + } else { + $this->form_gui->setValuesByPost(); + $this->tpl->setContent($this->form_gui->getHTML()); + } + } + + // add media cast to locator + public function addLocatorItems() + { + $ilLocator = $this->locator; + + if (is_object($this->object)) { + $ilLocator->addItem($this->object->getTitle(), $this->ctrl->getLinkTarget($this, "listItems"), "", $_GET["ref_id"]); + } + } + + public static function _goto($a_target) + { + global $DIC; + + $ilAccess = $DIC->access(); + $ilErr = $DIC["ilErr"]; + $lng = $DIC->language(); + + if ($ilAccess->checkAccess("read", "", $a_target)) { + $_GET["cmd"] = "showContent"; + $_GET["ref_id"] = $a_target; + $_GET["baseClass"] = "ilmediacasthandlergui"; + $_GET["cmdClass"] = "ilobjmediacastgui"; + include("ilias.php"); + exit; + } elseif ($ilAccess->checkAccess("visible", "", $a_target)) { + ilObjectGUI::_gotoRepositoryNode($a_target, "infoScreen"); + } elseif ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) { + ilUtil::sendFailure(sprintf( + $lng->txt("msg_no_perm_read_item"), + ilObject::_lookupTitle(ilObject::_lookupObjId($a_target)) + )); + ilObjectGUI::_gotoRepositoryRoot(); + } + + $ilErr->raiseError($lng->txt("msg_no_perm_read"), $ilErr->FATAL); + } + + /** + * detect audio mimetype + * + * @param string $extension + * @return true, if extension contains string "audio" + */ + protected static function isAudio($extension) + { + return strpos($extension, "audio") !== false; + } + + /** + * get MediaItem for id and updates local variable mcst_item + * + * @return ilMediaItem + * + */ + protected function getMediaItem($id) + { + include_once("./Services/News/classes/class.ilNewsItem.php"); + $this->mcst_item = new ilNewsItem($id); + // create dummy object in db (we need an id) + include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); + $mob = new ilObjMediaObject($this->mcst_item->getMobId()); + return $mob->getMediaItem("Standard"); + } + + /** + * get MediaItems for id and updates local variable mcst_item + * + * @return array of ilMediaItem + * + */ + protected function getMediaItems($id) + { + include_once("./Services/News/classes/class.ilNewsItem.php"); + $this->mcst_item = new ilNewsItem($id); + // create dummy object in db (we need an id) + include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); + $mob = new ilObjMediaObject($this->mcst_item->getMobId()); + return $mob->getMediaItems(); + } + + private function populateFormFromPost() + { + $tpl = $this->tpl; + //issue: we have to display the current settings + // problem: POST does not contain values of disabled textfields + // solution: use hidden field and label to display-> here we need to synchronize the labels + // with the values from the hidden fields. + foreach (ilObjMediaCast::$purposes as $purpose) { + if ($_POST["value_" . $purpose]) { + $_POST["label_value_" . $purpose] = $_POST["value_" . $purpose]; + } + } + + $this->form_gui->setValuesByPost(); + $tpl->setContent($this->form_gui->getHTML()); + } + + protected function editOrderObject() + { + $ilTabs = $this->tabs; + $lng = $this->lng; + $tpl = $this->tpl; + + $this->checkPermission("write"); + $ilTabs->activateTab("edit_content"); + + $this->addContentSubTabs("sorting"); + + // sort by order setting + switch ($this->object->getOrder()) { + case ilObjMediaCast::ORDER_TITLE: + case ilObjMediaCast::ORDER_CREATION_DATE_ASC: + case ilObjMediaCast::ORDER_CREATION_DATE_DESC: + return $this->listItemsObject(); + + case ilObjMediaCast::ORDER_MANUAL: + // sub-tabs + break; + } + + include_once("./Modules/MediaCast/classes/class.ilMediaCastTableGUI.php"); + $table_gui = new ilMediaCastTableGUI($this, "editOrder", true); + + $table_gui->setTitle($lng->txt("mcst_media_cast")); + $table_gui->setData($this->object->getSortedItemsArray()); + + $table_gui->addCommandButton("saveOrder", $lng->txt("mcst_save_order")); + + $tpl->setContent($table_gui->getHTML()); + } + + public function saveOrderObject() + { + $lng = $this->lng; + + asort($_POST["item_id"]); + + $items = array(); + foreach (array_keys($_POST["item_id"]) as $id) { + $items[] = $id; + } + $this->object->saveOrder($items); + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + $this->ctrl->redirect($this, "editOrder"); + } + + //// + //// Show content + //// + + /** + * Show content + * + * @param + * @return + */ + public function showContentObject() + { + $ilUser = $this->user; + + // need read events for parent for LP statistics + require_once 'Services/Tracking/classes/class.ilChangeEvent.php'; + ilChangeEvent::_recordReadEvent( + "mcst", + $this->object->getRefId(), + $this->object->getId(), + $ilUser->getId() + ); + + // trigger LP update + require_once 'Services/Tracking/classes/class.ilLPStatusWrapper.php'; + ilLPStatusWrapper::_updateStatus($this->object->getId(), $ilUser->getId()); + + if ($this->object->getViewMode() == ilObjMediaCast::VIEW_GALLERY) { + $this->showGallery(); + } else { + $this->listItemsObject(true); + } + global $tpl; + $tpl->setPermanentLink($this->object->getType(), $this->object->getRefId()); + } + + public function showGallery() + { + $tpl = $this->tpl; + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + + $tpl->addJavascript("./Modules/MediaCast/js/MediaCast.js"); + + $ilTabs->activateTab("content"); + + $this->addContentSubTabs("content"); + + $ctpl = new ilTemplate("tpl.mcst_content.html", true, true, "Modules/MediaCast"); + + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + require_once('./Services/WebAccessChecker/classes/class.ilWACSignedPath.php'); + foreach ($this->object->getSortedItemsArray() as $item) { + $mob = new ilObjMediaObject($item["mob_id"]); + $med = $mob->getMediaItem("Standard"); + + $ctpl->setCurrentBlock("item"); + $ctpl->setVariable("TITLE", $item["title"]); + $ctpl->setVariable("TIME", $item["playtime"]); + $ctpl->setVariable("ID", $item["id"]); + + if ($mob->getVideoPreviewPic() != "") { + $ctpl->setVariable( + "PREVIEW_PIC", + ilUtil::img(ilWACSignedPath::signFile($mob->getVideoPreviewPic()), $item["title"], 320, 240) + ); + } else { + $ctpl->setVariable( + "PREVIEW_PIC", + ilUtil::img(ilUtil::getImagePath("mcst_preview.svg"), $item["title"], 320, 240) + ); + } + + // player + if (is_object($med)) { + include_once("./Services/MediaObjects/classes/class.ilMediaPlayerGUI.php"); + + // the news id will be used as player id, see also ilMediaCastTableGUI + $mpl = new ilMediaPlayerGUI( + $item["id"], + $ilCtrl->getLinkTarget($this, "handlePlayerEvent", "", true, false) + ); + + if (strcasecmp("Reference", $med->getLocationType()) == 0) { + ilWACSignedPath::signFolderOfStartFile($med->getLocation()); + $mpl->setFile($med->getLocation()); + } else { + $path_to_file = ilObjMediaObject::_getURL($mob->getId()) . "/" . $med->getLocation(); + ilWACSignedPath::signFolderOfStartFile($path_to_file); + $mpl->setFile($path_to_file); + } + $mpl->setMimeType($med->getFormat()); + //$mpl->setDisplayHeight($med->getHeight()); + $mpl->setDisplayHeight("480"); + $mpl->setDisplayWidth("640"); + $mpl->setVideoPreviewPic(ilWACSignedPath::signFile($mob->getVideoPreviewPic())); + $mpl->setTitle($item["title"]); + $mpl->setDescription($item["content"]); + $mpl->setForceAudioPreview(true); + if ($this->object->getDownloadable()) { + $ilCtrl->setParameterByClass("ilobjmediacastgui", "item_id", $item["id"]); + $ilCtrl->setParameterByClass("ilobjmediacastgui", "purpose", "Standard"); + $mpl->setDownloadLink($ilCtrl->getLinkTargetByClass("ilobjmediacastgui", "downloadItem")); + } + $med_alt = $mob->getMediaItem("VideoAlternative"); + if (is_object($med_alt)) { + $mpl->setAlternativeVideoFile(ilWACSignedPath::signFile(ilObjMediaObject::_getURL($mob->getId()) . "/" . + $med_alt->getLocation())); + $mpl->setAlternativeVideoMimeType($med_alt->getFormat()); + } + + $ctpl->setVariable("PLAYER", $mpl->getPreviewHtml()); + } + + + $ctpl->parseCurrentBlock(); + } + + $feed_icon_html = $this->getFeedIconsHTML(); + + if ($feed_icon_html != "") { + $feed_icon_html = '

' . $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) + ? "
" . implode($ret, "
") + : ""; + + ilUtil::sendInfo($this->lng->txt("mcst_converted_file") . $add, true); + } catch (ilException $e) { + $ret = ilFFmpeg::getLastReturnValues(); + $add = (is_array($ret) && count($ret) > 0) + ? "
" . implode($ret, "
") + : ""; + ilUtil::sendFailure($e->getMessage() . $add, true); + } + + + $ilCtrl->redirect($this, "editCastItem"); + } + + /** + * Extract preview image + * + * @param + * @return + */ + public function extractPreviewImageObject() + { + $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()); + + try { + $sec = (int) $_POST["sec"]; + if ($sec < 0) { + $sec = 0; + } + if ($mob->getVideoPreviewPic() != "") { + $mob->removeAdditionalFile($mob->getVideoPreviewPic(true)); + } + include_once("./Services/MediaObjects/classes/class.ilFFmpeg.php"); + $med = $mob->getMediaItem("Standard"); + $mob_file = ilObjMediaObject::_getDirectory($mob->getId()) . "/" . $med->getLocation(); + $new_file = ilFFmpeg::extractImage( + $mob_file, + "mob_vpreview.png", + ilObjMediaObject::_getDirectory($mob->getId()), + $sec + ); + + if ($new_file != "") { + ilUtil::sendInfo($this->lng->txt("mcst_image_extracted"), true); + } else { + ilUtil::sendFailure($this->lng->txt("mcst_no_extraction_possible"), true); + } + } catch (ilException $e) { + if (DEVMODE == 1) { + $ret = ilFFmpeg::getLastReturnValues(); + $add = (is_array($ret) && count($ret) > 0) + ? "
" . implode($ret, "
") + : ""; + } + ilUtil::sendFailure($e->getMessage() . $add, true); + } + + + $ilCtrl->redirect($this, "editCastItem"); + } + + /** + * Handle player event + * + * @param + * @return + */ + public function handlePlayerEventObject() + { + if ($_GET["event"] == "play") { + $player = explode("_", $_GET["player"]); + $news_id = (int) $player[1]; + include_once("./Services/News/classes/class.ilNewsItem.php"); + $item = new ilNewsItem($news_id); + $item->increasePlayCounter(); + + $mob_id = $item->getMobId(); + if ($mob_id) { + $ilUser = $this->user; + $this->object->handleLPUpdate($ilUser->getId(), $mob_id); + } + } + exit; + } } -?> \ No newline at end of file diff --git a/Modules/MediaCast/classes/class.ilObjMediaCastListGUI.php b/Modules/MediaCast/classes/class.ilObjMediaCastListGUI.php index 03c3ad0c0a67ccd9a43c06b62f1c81deaac46ff9..dce9b84c007b620c63390defd1942814793d431c 100755 --- a/Modules/MediaCast/classes/class.ilObjMediaCastListGUI.php +++ b/Modules/MediaCast/classes/class.ilObjMediaCastListGUI.php @@ -15,112 +15,107 @@ include_once "Services/Object/classes/class.ilObjectListGUI.php"; */ class ilObjMediaCastListGUI 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; - $this->info_screen_enabled = true; - $this->type = "mcst"; - $this->gui_class_name = "ilobjmediacastgui"; - - // general commands array - include_once('./Modules/MediaCast/classes/class.ilObjMediaCastAccess.php'); - $this->commands = ilObjMediaCastAccess::_getCommands(); - } - - - /** - * inititialize new item - * - * @param int $a_ref_id reference id - * @param int $a_obj_id object id - * @param string $a_title title - * @param string $a_description description - */ - function initItem($a_ref_id, $a_obj_id, $a_title = "", $a_description = "") - { - parent::initItem($a_ref_id, $a_obj_id, $a_title, $a_description); - } - - - /** - * Get command target frame - * - * @param string $a_cmd command - * - * @return string command target frame - */ - function getCommandFrame($a_cmd) - { - switch($a_cmd) - { - default: - $frame = ilFrameTargetInfo::_getFrame("MainContent"); - break; - } - - return $frame; - } - - - - /** - * Get item properties - * - * @return array array of property arrays: - * "alert" (boolean) => display as an alert property (usually in red) - * "property" (string) => property name - * "value" (string) => property value - */ - function getProperties() - { - $lng = $this->lng; - $ilUser = $this->user; - - $props = array(); - - include_once("./Modules/MediaCast/classes/class.ilObjMediaCastAccess.php"); - - if (!ilObjMediaCastAccess::_lookupOnline($this->obj_id)) - { - $props[] = array("alert" => true, "property" => $lng->txt("status"), - "value" => $lng->txt("offline")); - } - - return $props; - } - - - /** - * Get command link url. - * - * @param int $a_ref_id reference id - * @param string $a_cmd command - * - */ - function getCommandLink($a_cmd) - { - // separate method for this line - $cmd_link = "ilias.php?baseClass=ilMediaCastHandlerGUI&ref_id=".$this->ref_id."&cmd=$a_cmd"; - - return $cmd_link; - } - - function setChildId($a_child_id) - { - $this->child_id = $a_child_id; - } - function getChildId() - { - return $this->child_id; - } - - + /** + * initialisation + */ + public function init() + { + $this->copy_enabled = true; + $this->delete_enabled = true; + $this->cut_enabled = true; + $this->subscribe_enabled = true; + $this->link_enabled = true; + $this->info_screen_enabled = true; + $this->type = "mcst"; + $this->gui_class_name = "ilobjmediacastgui"; + + // general commands array + include_once('./Modules/MediaCast/classes/class.ilObjMediaCastAccess.php'); + $this->commands = ilObjMediaCastAccess::_getCommands(); + } + + + /** + * inititialize new item + * + * @param int $a_ref_id reference id + * @param int $a_obj_id object id + * @param string $a_title title + * @param string $a_description description + */ + public function initItem($a_ref_id, $a_obj_id, $a_title = "", $a_description = "") + { + parent::initItem($a_ref_id, $a_obj_id, $a_title, $a_description); + } + + + /** + * Get command target frame + * + * @param string $a_cmd command + * + * @return string command target frame + */ + public function getCommandFrame($a_cmd) + { + switch ($a_cmd) { + default: + $frame = ilFrameTargetInfo::_getFrame("MainContent"); + break; + } + + return $frame; + } + + + + /** + * Get item properties + * + * @return array array of property arrays: + * "alert" (boolean) => display as an alert property (usually in red) + * "property" (string) => property name + * "value" (string) => property value + */ + public function getProperties() + { + $lng = $this->lng; + $ilUser = $this->user; + + $props = array(); + + include_once("./Modules/MediaCast/classes/class.ilObjMediaCastAccess.php"); + + if (!ilObjMediaCastAccess::_lookupOnline($this->obj_id)) { + $props[] = array("alert" => true, "property" => $lng->txt("status"), + "value" => $lng->txt("offline")); + } + + return $props; + } + + + /** + * Get command link url. + * + * @param int $a_ref_id reference id + * @param string $a_cmd command + * + */ + public function getCommandLink($a_cmd) + { + // separate method for this line + $cmd_link = "ilias.php?baseClass=ilMediaCastHandlerGUI&ref_id=" . $this->ref_id . "&cmd=$a_cmd"; + + return $cmd_link; + } + + public function setChildId($a_child_id) + { + $this->child_id = $a_child_id; + } + public function getChildId() + { + return $this->child_id; + } } // END class.ilObjMediaCastListGUI -?> diff --git a/Modules/MediaCast/classes/class.ilObjMediaCastSettings.php b/Modules/MediaCast/classes/class.ilObjMediaCastSettings.php index 03efc680a2a6e2c34bb980f8642837684fc8c774..86844a735e6305c70106542c8c86d1d8ca1302fa 100755 --- a/Modules/MediaCast/classes/class.ilObjMediaCastSettings.php +++ b/Modules/MediaCast/classes/class.ilObjMediaCastSettings.php @@ -1,105 +1,100 @@ +* +* @author Alex Killing * @version $Id$ * * @ingroup ModulesMediaCast */ class ilObjMediaCastSettings extends ilObject { - - /** - * Constructor - * @access public - * @param integer reference_id or object_id - * @param boolean treat the id as reference_id (true) or object_id (false) - */ - function __construct($a_id = 0,$a_call_by_reference = true) - { - global $DIC; - - $this->db = $DIC->database(); - $this->type = "mcts"; - parent::__construct($a_id,$a_call_by_reference); - } - - /** - * update object data - * - * @access public - * @return boolean - */ - function update() - { - $ilDB = $this->db; - - if (!parent::update()) - { - return false; - } + + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + global $DIC; - return true; - } - - /** - * read style folder data - */ - function read() - { - $ilDB = $this->db; + $this->db = $DIC->database(); + $this->type = "mcts"; + parent::__construct($a_id, $a_call_by_reference); + } - parent::read(); + /** + * update object data + * + * @access public + * @return boolean + */ + public function update() + { + $ilDB = $this->db; + + if (!parent::update()) { + return false; + } - } - + return true; + } + + /** + * read style folder data + */ + public function read() + { + $ilDB = $this->db; - - + parent::read(); + } + - /** - * delete object and all related data - * - * @access public - * @return boolean true if all object data were removed; false if only a references were removed - */ - function delete() - { - // always call parent delete function first!! - if (!parent::delete()) - { - return false; - } - - //put here your module specific stuff - - return true; - } + + + /** + * delete object and all related data + * + * @access public + * @return boolean true if all object data were removed; false if only a references were removed + */ + public function delete() + { + // always call parent delete function first!! + if (!parent::delete()) { + return false; + } + + //put here your module specific stuff + + return true; + } } // END class.ilObjMediaCastSettings -?> diff --git a/Modules/MediaCast/classes/class.ilObjMediaCastSettingsAccess.php b/Modules/MediaCast/classes/class.ilObjMediaCastSettingsAccess.php index 1b26e3c601c668138718ed652dd9810e9bbcb3de..d751287429d93faa076ea2b4a4a1d91a6c6f5398 100755 --- a/Modules/MediaCast/classes/class.ilObjMediaCastSettingsAccess.php +++ b/Modules/MediaCast/classes/class.ilObjMediaCastSettingsAccess.php @@ -1,24 +1,24 @@ diff --git a/Modules/MediaCast/classes/class.ilObjMediaCastSettingsGUI.php b/Modules/MediaCast/classes/class.ilObjMediaCastSettingsGUI.php index ed0674e8f0ad2da3508d9de2f4ad21d5f1e6c4dc..f7083501fe312c9d4e3d7e78585bd93a1670dbb7 100755 --- a/Modules/MediaCast/classes/class.ilObjMediaCastSettingsGUI.php +++ b/Modules/MediaCast/classes/class.ilObjMediaCastSettingsGUI.php @@ -1,24 +1,24 @@ rbacsystem = $DIC->rbac()->system(); - $this->error = $DIC["ilErr"]; - $this->access = $DIC->access(); - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->type = 'mcts'; - parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); - - $this->lng->loadLanguageModule('mcst'); - $this->initMediaCastSettings(); - } - - /** - * Execute command - * - * @access public - * - */ - public function executeCommand() - { - $rbacsystem = $this->rbacsystem; - $ilErr = $this->error; - $ilAccess = $this->access; - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - $this->prepareOutput(); - - if(!$ilAccess->checkAccess('read','',$this->object->getRefId())) - { - $ilErr->raiseError($this->lng->txt('no_permission'),$ilErr->WARNING); - } - - switch($next_class) - { - case 'ilpermissiongui': - $this->tabs_gui->setTabActive('perm_settings'); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $this->ctrl->forwardCommand($perm_gui); - break; - - default: - if(!$cmd || $cmd == 'view') - { - $cmd = "editSettings"; - } - - $this->$cmd(); - break; - } - return true; - } - - /** - * Get tabs - * - * @access public - * - */ - public function getAdminTabs() - { - $rbacsystem = $this->rbacsystem; - $ilAccess = $this->access; - - if ($rbacsystem->checkAccess("visible,read",$this->object->getRefId())) - { - $this->tabs_gui->addTarget("mcst_edit_settings", - $this->ctrl->getLinkTarget($this, "editSettings"), - array("editSettings", "view")); - } - - if ($rbacsystem->checkAccess('edit_permission',$this->object->getRefId())) - { - $this->tabs_gui->addTarget("perm_settings", - $this->ctrl->getLinkTargetByClass('ilpermissiongui',"perm"), - array(),'ilpermissiongui'); - } - } - - /** - * Edit mediacast settings. - */ - public function editSettings() - { - $this->tabs_gui->setTabActive('mcst_edit_settings'); - $this->initFormSettings(); - return true; - } - - /** - * Save mediacast settings - */ - public function saveSettings() - { - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - foreach ($this->settings->getPurposeSuffixes() as $purpose => $filetypes) { - $purposeSuffixes[$purpose] = explode(",", preg_replace("/[^\w,]/", "", strtolower($_POST[$purpose]))); - } - - $this->settings->setPurposeSuffixes($purposeSuffixes); - $this->settings->setDefaultAccess ($_POST["defaultaccess"]); - $this->settings->setMimeTypes (explode(",", $_POST["mimetypes"])); - - $this->settings->save(); - - ilUtil::sendSuccess($this->lng->txt("settings_saved"),true); - } - - $ilCtrl->redirect($this, "view"); - } - - /** - * Save mediacast settings - */ - public function cancel() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirect($this, "view"); - } - - /** - * iniitialize settings storage for media cast - * - */ - protected function initMediaCastSettings() - { - include_once('Modules/MediaCast/classes/class.ilMediaCastSettings.php'); - $this->settings = ilMediaCastSettings::_getInstance(); - } - - /** - * Init settings property form - * - * @access protected - */ - protected function initFormSettings() - { - $lng = $this->lng; - $ilAccess = $this->access; - include_once('Services/Form/classes/class.ilPropertyFormGUI.php'); - - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - $form->setTitle($this->lng->txt('settings')); - - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - $form->addCommandButton('saveSettings',$this->lng->txt('save')); - $form->addCommandButton('cancel',$this->lng->txt('cancel')); - } - - //Default Visibility - $radio_group = new ilRadioGroupInputGUI($lng->txt("mcst_default_visibility"), "defaultaccess"); - $radio_option = new ilRadioOption($lng->txt("mcst_visibility_users"), "users"); - $radio_group->addOption($radio_option); - $radio_option = new ilRadioOption($lng->txt("mcst_visibility_public"), "public"); - $radio_group->addOption($radio_option); - $radio_group->setInfo($lng->txt("mcst_news_item_visibility_info")); - $radio_group->setRequired(false); - $radio_group->setValue($this->settings->getDefaultAccess()); - #$ch->addSubItem($radio_group); - $form->addItem($radio_group); - - - foreach ($this->settings->getPurposeSuffixes() as $purpose => $filetypes) - { - if ($purpose != "VideoAlternative") - { - $text = new ilTextInputGUI($lng->txt("mcst_".strtolower($purpose)."_settings_title"),$purpose); - $text->setValue(implode(",",$filetypes)); - $text->setInfo($lng->txt("mcst_".strtolower($purpose)."_settings_info")); - $form->addItem($text); - } - } - - $text = new ilTextAreaInputGUI($lng->txt("mcst_mimetypes"), "mimetypes"); - $text->setInfo($lng->txt("mcst_mimetypes_info")); - $text->setCols(120); - $text->setRows(10); - if (is_array($this->settings->getMimeTypes())) - $text->setValue(implode(",",$this->settings->getMimeTypes())); - $form->addItem($text); - - $this->tpl->setContent($form->getHTML()); - } + /** + * Contructor + * + * @access public + */ + public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) + { + global $DIC; + + $this->rbacsystem = $DIC->rbac()->system(); + $this->error = $DIC["ilErr"]; + $this->access = $DIC->access(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->type = 'mcts'; + parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); + + $this->lng->loadLanguageModule('mcst'); + $this->initMediaCastSettings(); + } + + /** + * Execute command + * + * @access public + * + */ + public function executeCommand() + { + $rbacsystem = $this->rbacsystem; + $ilErr = $this->error; + $ilAccess = $this->access; + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + $this->prepareOutput(); + + if (!$ilAccess->checkAccess('read', '', $this->object->getRefId())) { + $ilErr->raiseError($this->lng->txt('no_permission'), $ilErr->WARNING); + } + + switch ($next_class) { + case 'ilpermissiongui': + $this->tabs_gui->setTabActive('perm_settings'); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $this->ctrl->forwardCommand($perm_gui); + break; + + default: + if (!$cmd || $cmd == 'view') { + $cmd = "editSettings"; + } + + $this->$cmd(); + break; + } + return true; + } + + /** + * Get tabs + * + * @access public + * + */ + public function getAdminTabs() + { + $rbacsystem = $this->rbacsystem; + $ilAccess = $this->access; + + if ($rbacsystem->checkAccess("visible,read", $this->object->getRefId())) { + $this->tabs_gui->addTarget( + "mcst_edit_settings", + $this->ctrl->getLinkTarget($this, "editSettings"), + array("editSettings", "view") + ); + } + + if ($rbacsystem->checkAccess('edit_permission', $this->object->getRefId())) { + $this->tabs_gui->addTarget( + "perm_settings", + $this->ctrl->getLinkTargetByClass('ilpermissiongui', "perm"), + array(), + 'ilpermissiongui' + ); + } + } + + /** + * Edit mediacast settings. + */ + public function editSettings() + { + $this->tabs_gui->setTabActive('mcst_edit_settings'); + $this->initFormSettings(); + return true; + } + + /** + * Save mediacast settings + */ + public function saveSettings() + { + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + + if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) { + foreach ($this->settings->getPurposeSuffixes() as $purpose => $filetypes) { + $purposeSuffixes[$purpose] = explode(",", preg_replace("/[^\w,]/", "", strtolower($_POST[$purpose]))); + } + + $this->settings->setPurposeSuffixes($purposeSuffixes); + $this->settings->setDefaultAccess($_POST["defaultaccess"]); + $this->settings->setMimeTypes(explode(",", $_POST["mimetypes"])); + + $this->settings->save(); + + ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); + } + + $ilCtrl->redirect($this, "view"); + } + + /** + * Save mediacast settings + */ + public function cancel() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirect($this, "view"); + } + + /** + * iniitialize settings storage for media cast + * + */ + protected function initMediaCastSettings() + { + include_once('Modules/MediaCast/classes/class.ilMediaCastSettings.php'); + $this->settings = ilMediaCastSettings::_getInstance(); + } + + /** + * Init settings property form + * + * @access protected + */ + protected function initFormSettings() + { + $lng = $this->lng; + $ilAccess = $this->access; + include_once('Services/Form/classes/class.ilPropertyFormGUI.php'); + + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this)); + $form->setTitle($this->lng->txt('settings')); + + if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) { + $form->addCommandButton('saveSettings', $this->lng->txt('save')); + $form->addCommandButton('cancel', $this->lng->txt('cancel')); + } + + //Default Visibility + $radio_group = new ilRadioGroupInputGUI($lng->txt("mcst_default_visibility"), "defaultaccess"); + $radio_option = new ilRadioOption($lng->txt("mcst_visibility_users"), "users"); + $radio_group->addOption($radio_option); + $radio_option = new ilRadioOption($lng->txt("mcst_visibility_public"), "public"); + $radio_group->addOption($radio_option); + $radio_group->setInfo($lng->txt("mcst_news_item_visibility_info")); + $radio_group->setRequired(false); + $radio_group->setValue($this->settings->getDefaultAccess()); + #$ch->addSubItem($radio_group); + $form->addItem($radio_group); + + + foreach ($this->settings->getPurposeSuffixes() as $purpose => $filetypes) { + if ($purpose != "VideoAlternative") { + $text = new ilTextInputGUI($lng->txt("mcst_" . strtolower($purpose) . "_settings_title"), $purpose); + $text->setValue(implode(",", $filetypes)); + $text->setInfo($lng->txt("mcst_" . strtolower($purpose) . "_settings_info")); + $form->addItem($text); + } + } + + $text = new ilTextAreaInputGUI($lng->txt("mcst_mimetypes"), "mimetypes"); + $text->setInfo($lng->txt("mcst_mimetypes_info")); + $text->setCols(120); + $text->setRows(10); + if (is_array($this->settings->getMimeTypes())) { + $text->setValue(implode(",", $this->settings->getMimeTypes())); + } + $form->addItem($text); + + $this->tpl->setContent($form->getHTML()); + } } -?> \ No newline at end of file diff --git a/Modules/MediaPool/classes/class.ilMediaPoolAppEventListener.php b/Modules/MediaPool/classes/class.ilMediaPoolAppEventListener.php index 136355eb27fc851dc0007c040be80584023e469f..7ca2cb256d23dd21013b64ef686037546885c44c 100644 --- a/Modules/MediaPool/classes/class.ilMediaPoolAppEventListener.php +++ b/Modules/MediaPool/classes/class.ilMediaPoolAppEventListener.php @@ -10,32 +10,28 @@ */ class ilMediaPoolAppEventListener { - /** - * Handle an event in a listener. - * - * @param string $a_component component, e.g. "Modules/Forum" or "Services/User" - * @param string $a_event event e.g. "createUser", "updateUser", "deleteUser", ... - * @param array $a_parameter parameter array (assoc), array("name" => ..., "phone_office" => ...) - */ - static function handleEvent($a_component, $a_event, $a_parameter) - { - include_once("./Services/Tagging/classes/class.ilTagging.php"); - - switch($a_component) - { - case "Services/Object": - switch ($a_event) - { - case "update": - if ($a_parameter["obj_type"] == "mob") - { - include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); - ilMediaPoolItem::updateObjectTitle($a_parameter["obj_id"]); - } - break; - } - break; - } - } + /** + * Handle an event in a listener. + * + * @param string $a_component component, e.g. "Modules/Forum" or "Services/User" + * @param string $a_event event e.g. "createUser", "updateUser", "deleteUser", ... + * @param array $a_parameter parameter array (assoc), array("name" => ..., "phone_office" => ...) + */ + public static function handleEvent($a_component, $a_event, $a_parameter) + { + include_once("./Services/Tagging/classes/class.ilTagging.php"); + + switch ($a_component) { + case "Services/Object": + switch ($a_event) { + case "update": + if ($a_parameter["obj_type"] == "mob") { + include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); + ilMediaPoolItem::updateObjectTitle($a_parameter["obj_id"]); + } + break; + } + break; + } + } } -?> diff --git a/Modules/MediaPool/classes/class.ilMediaPoolDataSet.php b/Modules/MediaPool/classes/class.ilMediaPoolDataSet.php index 76317c81ffc393ee795c072c3b618e7b40bdd366..7f7339a875070e48349ea4cf15b884f46702ce52 100644 --- a/Modules/MediaPool/classes/class.ilMediaPoolDataSet.php +++ b/Modules/MediaPool/classes/class.ilMediaPoolDataSet.php @@ -5,7 +5,7 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); /** * Media Pool Data set class - * + * * This class implements the following entities: * - mep_data: data from table mep_data * - mep_tree: data from a join on mep_tree and mep_item @@ -16,408 +16,384 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); */ class ilMediaPoolDataSet extends ilDataSet { - - protected $master_lang_only = false; - protected $transl_into = false; - protected $transl_into_lm = null; - protected $transl_lang = ""; - - /** - * Get supported versions - * - * @param - * @return - */ - public function getSupportedVersions() - { - return array("5.1.0", "4.1.0"); - } - - /** - * Get xml namespace - * - * @param - * @return - */ - function getXmlNamespace($a_entity, $a_schema_version) - { - return "http://www.ilias.de/xml/Modules/MediaPool/".$a_entity; - } - - /** - * Set master language only (export) - * - * @param bool $a_val export only master language - */ - function setMasterLanguageOnly($a_val) - { - $this->master_lang_only = $a_val; - } - - /** - * Get master language only (export) - * - * @return bool export only master language - */ - function getMasterLanguageOnly() - { - return $this->master_lang_only; - } - - /** - * Set translation import mode - * - * @param ilObjLearningModule $a_lm learning module - * @param string $a_lang language - */ - function setTranslationImportMode($a_lm, $a_lang = "") - { - if ($a_lm != null) - { - $this->transl_into = true; - $this->transl_into_lm = $a_lm; - $this->transl_lang = $a_lang; - } - else - { - $this->transl_into = false; - } - } - - /** - * Get translation import mode - * - * @return bool check if translation import is activated - */ - function getTranslationImportMode() - { - return $this->transl_into; - } - - /** - * Get translation lm (import - * - * @return ilObjLearningModule learning module - */ - function getTranslationLM() - { - return $this->transl_into_lm; - } - - /** - * Get translation language (import - * - * @return string language - */ - function getTranslationLang() - { - return $this->transl_lang; - } - - /** - * Get field types for entity - * - * @param - * @return - */ - protected function getTypes($a_entity, $a_version) - { - // mep - if ($a_entity == "mep") - { - switch ($a_version) - { - case "4.1.0": - return array( - "Id" => "integer", - "Title" => "text", - "Description" => "text", - "DefaultWidth" => "integer", - "DefaultHeight" => "integer"); - - case "5.1.0": - return array( - "Id" => "integer", - "Title" => "text", - "Description" => "text", - "DefaultWidth" => "integer", - "DefaultHeight" => "integer", - "ForTranslation" => "integer" - ); - } - } - - // mep_tree - if ($a_entity == "mep_tree") - { - switch ($a_version) - { - case "4.1.0": - case "5.1.0": - return array( - "MepId" => "integer", - "Child" => "integer", - "Parent" => "integer", - "Depth" => "integer", - "Type" => "text", - "Title" => "text", - "ForeignId" => "integer", - "ImportId" => "text" - ); - } - } - } - - /** - * Read data - * - * @param - * @return - */ - function readData($a_entity, $a_version, $a_ids, $a_field = "") - { - $ilDB = $this->db; - - if (!is_array($a_ids)) - { - $a_ids = array($a_ids); - } - - // mep_data - if ($a_entity == "mep") - { - switch ($a_version) - { - case "4.1.0": - $this->getDirectDataFromQuery("SELECT id, title, description, ". - " default_width, default_height". - " FROM mep_data JOIN object_data ON (mep_data.id = object_data.obj_id) ". - "WHERE ". - $ilDB->in("id", $a_ids, false, "integer")); - break; - - case "5.1.0": - $q = "SELECT id, title, description, ". - " default_width, default_height". - " FROM mep_data JOIN object_data ON (mep_data.id = object_data.obj_id) ". - "WHERE ". - $ilDB->in("id", $a_ids, false, "integer"); - - $set = $ilDB->query($q); - $this->data = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - if ($this->getMasterLanguageOnly()) - { - $rec["for_translation"] = 1; - } - $tmp = array(); - foreach ($rec as $k => $v) - { - $tmp[$this->convertToLeadingUpper($k)] - = $v; - } - $rec = $tmp; - - $this->data[] = $rec; - } - break; - - } - } - - // mep_tree - if ($a_entity == "mep_tree") - { - switch ($a_version) - { - case "4.1.0": - $this->getDirectDataFromQuery("SELECT mep_id, child ". - " ,parent,depth,type,title,foreign_id ". - " FROM mep_tree JOIN mep_item ON (child = obj_id) ". - " WHERE ". - $ilDB->in("mep_id", $a_ids, false, "integer"). - " ORDER BY depth"); - break; - - case "5.1.0": - $type = ""; - if ($this->getMasterLanguageOnly()) - { - $type = " AND type <> ".$ilDB->quote("mob", "text"); - } - - $q = "SELECT mep_id, child ". - " ,parent,depth,type,title,foreign_id, import_id ". - " FROM mep_tree JOIN mep_item ON (child = obj_id) ". - " WHERE ". - $ilDB->in("mep_id", $a_ids, false, "integer"). - $type. - " ORDER BY depth"; - - $set = $ilDB->query($q); - $this->data = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $set2 = $ilDB->query("SELECT for_translation FROM mep_data WHERE id = ".$ilDB->quote($rec["mep_id"], true)); - $rec2 = $ilDB->fetchAssoc($set2); - if (!$rec2["for_translation"]) - { - $rec["import_id"] = "il_".IL_INST_ID."_".$rec["type"]."_".$rec["child"]; - } - $tmp = array(); - foreach ($rec as $k => $v) - { - $tmp[$this->convertToLeadingUpper($k)] - = $v; - } - $rec = $tmp; - - $this->data[] = $rec; - } - - break; - } - } - } - - /** - * Determine the dependent sets of data - */ - protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) - { - switch ($a_entity) - { - case "mep": - return array ( - "mep_tree" => array("ids" => $a_rec["Id"]) - ); - } - return false; - } - - //// - //// Needs abstraction (interface?) and version handling - //// - - - /** - * Import record - * - * @param - * @return - */ - function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) - { -//echo $a_entity; -//var_dump($a_rec); - - switch ($a_entity) - { - case "mep": - - if ($this->getTranslationImportMode()) - { - return; - } - - include_once("./Modules/MediaPool/classes/class.ilObjMediaPool.php"); - - if($new_id = $a_mapping->getMapping('Services/Container','objs',$a_rec['Id'])) - { - $newObj = ilObjectFactory::getInstanceByObjId($new_id,false); - } - else - { - $newObj = new ilObjMediaPool(); - $newObj->setType("mep"); - $newObj->create(true); - } - - $newObj->setTitle($a_rec["Title"]); - $newObj->setDescription($a_rec["Description"]); - $newObj->setDefaultWidth($a_rec["DefaultWidth"]); - $newObj->setDefaultHeight($a_rec["DefaultHeight"]); - $newObj->setForTranslation($a_rec["ForTranslation"]); - $newObj->update(); - - $this->current_obj = $newObj; - $a_mapping->addMapping("Modules/MediaPool", "mep", $a_rec["Id"], $newObj->getId()); - $a_mapping->addMapping("Services/Object", "obj", $a_rec["Id"], $newObj->getId()); - break; - - case "mep_tree": - if (!$this->getTranslationImportMode()) - { - switch ($a_rec["Type"]) - { - case "fold": - $parent = (int) $a_mapping->getMapping("Modules/MediaPool", "mep_tree", $a_rec["Parent"]); - $fold_id = - $this->current_obj->createFolder($a_rec["Title"], $parent); - $a_mapping->addMapping("Modules/MediaPool", "mep_tree", $a_rec["Child"], - $fold_id); - break; - - case "mob": - $parent = (int) $a_mapping->getMapping("Modules/MediaPool", "mep_tree", $a_rec["Parent"]); - $mob_id = (int) $a_mapping->getMapping("Services/MediaObjects", "mob", $a_rec["ForeignId"]); - $item = new ilMediaPoolItem(); - $item->setType("mob"); - $item->setForeignId($mob_id); - $item->setImportId($a_rec["ImportId"]); - $item->setTitle($a_rec["Title"]); - $item->create(); - if ($item->getId() > 0) - { - $this->current_obj->insertInTree($item->getId(), $parent); - } - break; - - case "pg": - $parent = (int) $a_mapping->getMapping("Modules/MediaPool", "mep_tree", $a_rec["Parent"]); - - $item = new ilMediaPoolItem(); - $item->setType("pg"); - $item->setTitle($a_rec["Title"]); - $item->setImportId($a_rec["ImportId"]); - $item->create(); - $a_mapping->addMapping("Modules/MediaPool", "pg", $a_rec["Child"], $item->getId()); - $a_mapping->addMapping("Services/COPage", "pg", "mep:".$a_rec["Child"], - "mep:".$item->getId()); - if ($item->getId() > 0) - { - $this->current_obj->insertInTree($item->getId(), $parent); - } - break; - - } - } - else - { - if ($a_rec["Type"] == "pg") - { - $imp_id = explode("_", $a_rec["ImportId"]); - if ($imp_id[0] == "il" && - (int) $imp_id[1] == (int) IL_INST_ID && - $imp_id[2] == "pg" - ) - { - $pg_id = $imp_id[3]; - include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); - $pool = ilMediaPoolItem::getPoolForItemId($pg_id); - $pool = current($pool); - if ($pool == $this->getTranslationLM()->getId()) - { - $a_mapping->addMapping("Modules/MediaPool", "pg", $a_rec["Child"], $pg_id); - $a_mapping->addMapping("Services/COPage", "pg", "mep:".$a_rec["Child"], - "mep:".$pg_id); - } - } - } - } - break; - } - } + protected $master_lang_only = false; + protected $transl_into = false; + protected $transl_into_lm = null; + protected $transl_lang = ""; + + /** + * Get supported versions + * + * @param + * @return + */ + public function getSupportedVersions() + { + return array("5.1.0", "4.1.0"); + } + + /** + * Get xml namespace + * + * @param + * @return + */ + public function getXmlNamespace($a_entity, $a_schema_version) + { + return "http://www.ilias.de/xml/Modules/MediaPool/" . $a_entity; + } + + /** + * Set master language only (export) + * + * @param bool $a_val export only master language + */ + public function setMasterLanguageOnly($a_val) + { + $this->master_lang_only = $a_val; + } + + /** + * Get master language only (export) + * + * @return bool export only master language + */ + public function getMasterLanguageOnly() + { + return $this->master_lang_only; + } + + /** + * Set translation import mode + * + * @param ilObjLearningModule $a_lm learning module + * @param string $a_lang language + */ + public function setTranslationImportMode($a_lm, $a_lang = "") + { + if ($a_lm != null) { + $this->transl_into = true; + $this->transl_into_lm = $a_lm; + $this->transl_lang = $a_lang; + } else { + $this->transl_into = false; + } + } + + /** + * Get translation import mode + * + * @return bool check if translation import is activated + */ + public function getTranslationImportMode() + { + return $this->transl_into; + } + + /** + * Get translation lm (import + * + * @return ilObjLearningModule learning module + */ + public function getTranslationLM() + { + return $this->transl_into_lm; + } + + /** + * Get translation language (import + * + * @return string language + */ + public function getTranslationLang() + { + return $this->transl_lang; + } + + /** + * Get field types for entity + * + * @param + * @return + */ + protected function getTypes($a_entity, $a_version) + { + // mep + if ($a_entity == "mep") { + switch ($a_version) { + case "4.1.0": + return array( + "Id" => "integer", + "Title" => "text", + "Description" => "text", + "DefaultWidth" => "integer", + "DefaultHeight" => "integer"); + + case "5.1.0": + return array( + "Id" => "integer", + "Title" => "text", + "Description" => "text", + "DefaultWidth" => "integer", + "DefaultHeight" => "integer", + "ForTranslation" => "integer" + ); + } + } + + // mep_tree + if ($a_entity == "mep_tree") { + switch ($a_version) { + case "4.1.0": + case "5.1.0": + return array( + "MepId" => "integer", + "Child" => "integer", + "Parent" => "integer", + "Depth" => "integer", + "Type" => "text", + "Title" => "text", + "ForeignId" => "integer", + "ImportId" => "text" + ); + } + } + } + + /** + * 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); + } + + // mep_data + if ($a_entity == "mep") { + switch ($a_version) { + case "4.1.0": + $this->getDirectDataFromQuery("SELECT id, title, description, " . + " default_width, default_height" . + " FROM mep_data JOIN object_data ON (mep_data.id = object_data.obj_id) " . + "WHERE " . + $ilDB->in("id", $a_ids, false, "integer")); + break; + + case "5.1.0": + $q = "SELECT id, title, description, " . + " default_width, default_height" . + " FROM mep_data JOIN object_data ON (mep_data.id = object_data.obj_id) " . + "WHERE " . + $ilDB->in("id", $a_ids, false, "integer"); + + $set = $ilDB->query($q); + $this->data = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + if ($this->getMasterLanguageOnly()) { + $rec["for_translation"] = 1; + } + $tmp = array(); + foreach ($rec as $k => $v) { + $tmp[$this->convertToLeadingUpper($k)] + = $v; + } + $rec = $tmp; + + $this->data[] = $rec; + } + break; + + } + } + + // mep_tree + if ($a_entity == "mep_tree") { + switch ($a_version) { + case "4.1.0": + $this->getDirectDataFromQuery("SELECT mep_id, child " . + " ,parent,depth,type,title,foreign_id " . + " FROM mep_tree JOIN mep_item ON (child = obj_id) " . + " WHERE " . + $ilDB->in("mep_id", $a_ids, false, "integer") . + " ORDER BY depth"); + break; + + case "5.1.0": + $type = ""; + if ($this->getMasterLanguageOnly()) { + $type = " AND type <> " . $ilDB->quote("mob", "text"); + } + + $q = "SELECT mep_id, child " . + " ,parent,depth,type,title,foreign_id, import_id " . + " FROM mep_tree JOIN mep_item ON (child = obj_id) " . + " WHERE " . + $ilDB->in("mep_id", $a_ids, false, "integer") . + $type . + " ORDER BY depth"; + + $set = $ilDB->query($q); + $this->data = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $set2 = $ilDB->query("SELECT for_translation FROM mep_data WHERE id = " . $ilDB->quote($rec["mep_id"], true)); + $rec2 = $ilDB->fetchAssoc($set2); + if (!$rec2["for_translation"]) { + $rec["import_id"] = "il_" . IL_INST_ID . "_" . $rec["type"] . "_" . $rec["child"]; + } + $tmp = array(); + foreach ($rec as $k => $v) { + $tmp[$this->convertToLeadingUpper($k)] + = $v; + } + $rec = $tmp; + + $this->data[] = $rec; + } + + break; + } + } + } + + /** + * Determine the dependent sets of data + */ + protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) + { + switch ($a_entity) { + case "mep": + return array( + "mep_tree" => array("ids" => $a_rec["Id"]) + ); + } + return false; + } + + //// + //// Needs abstraction (interface?) and version handling + //// + + + /** + * Import record + * + * @param + * @return + */ + public function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) + { + //echo $a_entity; + //var_dump($a_rec); + + switch ($a_entity) { + case "mep": + + if ($this->getTranslationImportMode()) { + return; + } + + include_once("./Modules/MediaPool/classes/class.ilObjMediaPool.php"); + + if ($new_id = $a_mapping->getMapping('Services/Container', 'objs', $a_rec['Id'])) { + $newObj = ilObjectFactory::getInstanceByObjId($new_id, false); + } else { + $newObj = new ilObjMediaPool(); + $newObj->setType("mep"); + $newObj->create(true); + } + + $newObj->setTitle($a_rec["Title"]); + $newObj->setDescription($a_rec["Description"]); + $newObj->setDefaultWidth($a_rec["DefaultWidth"]); + $newObj->setDefaultHeight($a_rec["DefaultHeight"]); + $newObj->setForTranslation($a_rec["ForTranslation"]); + $newObj->update(); + + $this->current_obj = $newObj; + $a_mapping->addMapping("Modules/MediaPool", "mep", $a_rec["Id"], $newObj->getId()); + $a_mapping->addMapping("Services/Object", "obj", $a_rec["Id"], $newObj->getId()); + break; + + case "mep_tree": + if (!$this->getTranslationImportMode()) { + switch ($a_rec["Type"]) { + case "fold": + $parent = (int) $a_mapping->getMapping("Modules/MediaPool", "mep_tree", $a_rec["Parent"]); + $fold_id = + $this->current_obj->createFolder($a_rec["Title"], $parent); + $a_mapping->addMapping( + "Modules/MediaPool", + "mep_tree", + $a_rec["Child"], + $fold_id + ); + break; + + case "mob": + $parent = (int) $a_mapping->getMapping("Modules/MediaPool", "mep_tree", $a_rec["Parent"]); + $mob_id = (int) $a_mapping->getMapping("Services/MediaObjects", "mob", $a_rec["ForeignId"]); + $item = new ilMediaPoolItem(); + $item->setType("mob"); + $item->setForeignId($mob_id); + $item->setImportId($a_rec["ImportId"]); + $item->setTitle($a_rec["Title"]); + $item->create(); + if ($item->getId() > 0) { + $this->current_obj->insertInTree($item->getId(), $parent); + } + break; + + case "pg": + $parent = (int) $a_mapping->getMapping("Modules/MediaPool", "mep_tree", $a_rec["Parent"]); + + $item = new ilMediaPoolItem(); + $item->setType("pg"); + $item->setTitle($a_rec["Title"]); + $item->setImportId($a_rec["ImportId"]); + $item->create(); + $a_mapping->addMapping("Modules/MediaPool", "pg", $a_rec["Child"], $item->getId()); + $a_mapping->addMapping( + "Services/COPage", + "pg", + "mep:" . $a_rec["Child"], + "mep:" . $item->getId() + ); + if ($item->getId() > 0) { + $this->current_obj->insertInTree($item->getId(), $parent); + } + break; + + } + } else { + if ($a_rec["Type"] == "pg") { + $imp_id = explode("_", $a_rec["ImportId"]); + if ($imp_id[0] == "il" && + (int) $imp_id[1] == (int) IL_INST_ID && + $imp_id[2] == "pg" + ) { + $pg_id = $imp_id[3]; + include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); + $pool = ilMediaPoolItem::getPoolForItemId($pg_id); + $pool = current($pool); + if ($pool == $this->getTranslationLM()->getId()) { + $a_mapping->addMapping("Modules/MediaPool", "pg", $a_rec["Child"], $pg_id); + $a_mapping->addMapping( + "Services/COPage", + "pg", + "mep:" . $a_rec["Child"], + "mep:" . $pg_id + ); + } + } + } + } + break; + } + } } -?> \ No newline at end of file diff --git a/Modules/MediaPool/classes/class.ilMediaPoolExplorerGUI.php b/Modules/MediaPool/classes/class.ilMediaPoolExplorerGUI.php index 55fb4692e87b09b57fe44c7df68ddf90514f1ac2..ae27360ab829b972fd23a5f9b7cf4465e0be8239 100644 --- a/Modules/MediaPool/classes/class.ilMediaPoolExplorerGUI.php +++ b/Modules/MediaPool/classes/class.ilMediaPoolExplorerGUI.php @@ -13,104 +13,96 @@ include_once("./Services/UIComponent/Explorer2/classes/class.ilTreeExplorerGUI.p */ class ilMediaPoolExplorerGUI extends ilTreeExplorerGUI { - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - /** - * Constructor - */ - public function __construct($a_parent_obj, $a_parent_cmd, $a_media_pool) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_media_pool) + { + global $DIC; - $this->user = $DIC->user(); - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $ilUser = $DIC->user(); - - $this->media_pool = $a_media_pool; - parent::__construct("mep_exp", $a_parent_obj, $a_parent_cmd, $a_media_pool->getTree()); - - $this->setTypeWhiteList(array("dummy", "fold")); - $this->setSkipRootNode(false); - $this->setAjax(true); - $this->setOrderField("title"); + $this->user = $DIC->user(); + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $ilUser = $DIC->user(); + + $this->media_pool = $a_media_pool; + parent::__construct("mep_exp", $a_parent_obj, $a_parent_cmd, $a_media_pool->getTree()); + + $this->setTypeWhiteList(array("dummy", "fold")); + $this->setSkipRootNode(false); + $this->setAjax(true); + $this->setOrderField("title"); - $this->setNodeOpen($this->tree->readRootId()); - } + $this->setNodeOpen($this->tree->readRootId()); + } - /** - * Get node content - * - * @param array - * @return - */ - function getNodeContent($a_node) - { - $lng = $this->lng; + /** + * Get node content + * + * @param array + * @return + */ + public function getNodeContent($a_node) + { + $lng = $this->lng; - if ($a_node["child"] == $this->getNodeId($this->getRootNode())) - { - return $this->media_pool->getTitle(); - } - - return $a_node["title"]; - } - - /** - * Get node icon - * - * @param array - * @return - */ - function getNodeIcon($a_node) - { - if ($a_node["child"] == $this->getNodeId($this->getRootNode())) - { - $icon = ilUtil::getImagePath("icon_mep.svg"); - } - else - { - $icon = ilUtil::getImagePath("icon_".$a_node["type"].".svg"); - } - - return $icon; - } - - /** - * Is node highlighted? - * - * @param mixed $a_node node object/array - * @return boolean node visible true/false - */ - function isNodeHighlighted($a_node) - { - if ($a_node["child"] == $_GET["mepitem_id"] || - ($_GET["mepitem_id"] == "" && $a_node["child"] == $this->getNodeId($this->getRootNode()))) - { - return true; - } - return false; - } - - /** - * Get href for node - * - * @param mixed $a_node node object/array - * @return string href attribute - */ - function getNodeHref($a_node) - { - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameterByClass("ilobjmediapoolgui", "mepitem_id", $a_node["child"]); - $ret = $ilCtrl->getLinkTargetByClass("ilobjmediapoolgui", "listMedia"); - $ilCtrl->setParameterByClass("ilobjmediapoolgui", "mepitem_id", $_GET["mepitem_id"]); - return $ret; - } + if ($a_node["child"] == $this->getNodeId($this->getRootNode())) { + return $this->media_pool->getTitle(); + } + + return $a_node["title"]; + } + + /** + * Get node icon + * + * @param array + * @return + */ + public function getNodeIcon($a_node) + { + if ($a_node["child"] == $this->getNodeId($this->getRootNode())) { + $icon = ilUtil::getImagePath("icon_mep.svg"); + } else { + $icon = ilUtil::getImagePath("icon_" . $a_node["type"] . ".svg"); + } + + return $icon; + } + /** + * Is node highlighted? + * + * @param mixed $a_node node object/array + * @return boolean node visible true/false + */ + public function isNodeHighlighted($a_node) + { + if ($a_node["child"] == $_GET["mepitem_id"] || + ($_GET["mepitem_id"] == "" && $a_node["child"] == $this->getNodeId($this->getRootNode()))) { + return true; + } + return false; + } + + /** + * Get href for node + * + * @param mixed $a_node node object/array + * @return string href attribute + */ + public function getNodeHref($a_node) + { + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameterByClass("ilobjmediapoolgui", "mepitem_id", $a_node["child"]); + $ret = $ilCtrl->getLinkTargetByClass("ilobjmediapoolgui", "listMedia"); + $ilCtrl->setParameterByClass("ilobjmediapoolgui", "mepitem_id", $_GET["mepitem_id"]); + return $ret; + } } - -?> diff --git a/Modules/MediaPool/classes/class.ilMediaPoolExportConfig.php b/Modules/MediaPool/classes/class.ilMediaPoolExportConfig.php index c4d00df1817b8e7697f4f3d11f060f9a90bc43c6..a2fd6879aef7bff0e09481512afee235459787cb 100644 --- a/Modules/MediaPool/classes/class.ilMediaPoolExportConfig.php +++ b/Modules/MediaPool/classes/class.ilMediaPoolExportConfig.php @@ -12,41 +12,38 @@ include_once("./Services/Export/classes/class.ilExportConfig.php"); */ class ilMediaPoolExportConfig extends ilExportConfig { - protected $master_only = false; - protected $include_media = true; + protected $master_only = false; + protected $include_media = true; - /** - * Set master language only - * - * @param bool $a_val - * @param bool $a_include_media - */ - function setMasterLanguageOnly($a_val, $a_include_media = true) - { - $this->master_only = $a_val; - $this->include_media = $a_include_media; - } + /** + * Set master language only + * + * @param bool $a_val + * @param bool $a_include_media + */ + public function setMasterLanguageOnly($a_val, $a_include_media = true) + { + $this->master_only = $a_val; + $this->include_media = $a_include_media; + } - /** - * Get master language only - * - * @return bool export only master language - */ - function getMasterLanguageOnly() - { - return $this->master_only; - } - - /** - * Get include media - * - * @return bool export media? - */ - function getIncludeMedia() - { - return $this->include_media; - } + /** + * Get master language only + * + * @return bool export only master language + */ + public function getMasterLanguageOnly() + { + return $this->master_only; + } + /** + * Get include media + * + * @return bool export media? + */ + public function getIncludeMedia() + { + return $this->include_media; + } } - -?> \ No newline at end of file diff --git a/Modules/MediaPool/classes/class.ilMediaPoolExporter.php b/Modules/MediaPool/classes/class.ilMediaPoolExporter.php index 2baf7b74d6fe1919337881a5049f85328d5b42c6..a6b47a5cab4d23e739905a2cff58ec0a67d9ae51 100644 --- a/Modules/MediaPool/classes/class.ilMediaPoolExporter.php +++ b/Modules/MediaPool/classes/class.ilMediaPoolExporter.php @@ -12,153 +12,143 @@ include_once("./Services/Export/classes/class.ilXmlExporter.php"); */ class ilMediaPoolExporter extends ilXmlExporter { - private $ds; - /** - * @var ilMediaPoolExportConfig - */ - private $config; - - /** - * Initialisation - */ - function init() - { - include_once("./Modules/MediaPool/classes/class.ilMediaPoolDataSet.php"); - $this->ds = new ilMediaPoolDataSet(); - $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); - $this->ds->setDSPrefix("ds"); - $this->config = $this->getExport()->getConfig("Modules/MediaPool"); - if ($this->config->getMasterLanguageOnly()) - { - $conf = $this->getExport()->getConfig("Services/COPage"); - $conf->setMasterLanguageOnly(true, $this->config->getIncludeMedia()); - $this->ds->setMasterLanguageOnly(true); - } - } - - /** - * Get head dependencies - * - * @param string entity - * @param string target release - * @param array ids - * @return array array of array with keys "component", entity", "ids" - */ - function getXmlExportHeadDependencies($a_entity, $a_target_release, $a_ids) - { - include_once("./Modules/MediaPool/classes/class.ilObjMediaPool.php"); - include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); - $pg_ids = array(); - $mob_ids = array(); - - foreach ($a_ids as $id) - { - $m_ids = ilObjMediaPool::getAllMobIds($id); - foreach ($m_ids as $m) - { - $mob_ids[] = $m; - } - } - - if ($this->config->getMasterLanguageOnly()) - { - return array(); - } - - return array ( - array( - "component" => "Services/MediaObjects", - "entity" => "mob", - "ids" => $mob_ids) - ); - } - - - /** - * Get tail dependencies - * - * @param string entity - * @param string target release - * @param array ids - * @return array array of array with keys "component", entity", "ids" - */ - function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) - { - include_once("./Modules/MediaPool/classes/class.ilObjMediaPool.php"); - include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); - $pg_ids = array(); - $mob_ids = array(); - - foreach ($a_ids as $id) - { - $pages = ilMediaPoolItem::getIdsForType($id, "pg"); - foreach ($pages as $p) - { - $pg_ids[] = "mep:".$p; - } - } - - $deps = array ( - array( - "component" => "Services/COPage", - "entity" => "pg", - "ids" => $pg_ids) - ); - - if (!$this->config->getMasterLanguageOnly()) - { - $deps[] = array( - "component" => "Services/Object", - "entity" => "transl", - "ids" => $a_ids); - } + private $ds; + /** + * @var ilMediaPoolExportConfig + */ + private $config; + + /** + * Initialisation + */ + public function init() + { + include_once("./Modules/MediaPool/classes/class.ilMediaPoolDataSet.php"); + $this->ds = new ilMediaPoolDataSet(); + $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); + $this->ds->setDSPrefix("ds"); + $this->config = $this->getExport()->getConfig("Modules/MediaPool"); + if ($this->config->getMasterLanguageOnly()) { + $conf = $this->getExport()->getConfig("Services/COPage"); + $conf->setMasterLanguageOnly(true, $this->config->getIncludeMedia()); + $this->ds->setMasterLanguageOnly(true); + } + } + + /** + * Get head dependencies + * + * @param string entity + * @param string target release + * @param array ids + * @return array array of array with keys "component", entity", "ids" + */ + public function getXmlExportHeadDependencies($a_entity, $a_target_release, $a_ids) + { + include_once("./Modules/MediaPool/classes/class.ilObjMediaPool.php"); + include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); + $pg_ids = array(); + $mob_ids = array(); + + foreach ($a_ids as $id) { + $m_ids = ilObjMediaPool::getAllMobIds($id); + foreach ($m_ids as $m) { + $mob_ids[] = $m; + } + } + + if ($this->config->getMasterLanguageOnly()) { + return array(); + } + + return array( + array( + "component" => "Services/MediaObjects", + "entity" => "mob", + "ids" => $mob_ids) + ); + } + + + /** + * Get tail dependencies + * + * @param string entity + * @param string target release + * @param array ids + * @return array array of array with keys "component", entity", "ids" + */ + public function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) + { + include_once("./Modules/MediaPool/classes/class.ilObjMediaPool.php"); + include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); + $pg_ids = array(); + $mob_ids = array(); + + foreach ($a_ids as $id) { + $pages = ilMediaPoolItem::getIdsForType($id, "pg"); + foreach ($pages as $p) { + $pg_ids[] = "mep:" . $p; + } + } + + $deps = array( + array( + "component" => "Services/COPage", + "entity" => "pg", + "ids" => $pg_ids) + ); + + if (!$this->config->getMasterLanguageOnly()) { + $deps[] = array( + "component" => "Services/Object", + "entity" => "transl", + "ids" => $a_ids); + } $deps[] = array( "component" => "Services/Object", "entity" => "tile", "ids" => $a_ids); - return $deps; - } - - /** - * Get xml representation - * - * @param string entity - * @param string schema version - * @param string id - * @return string xml string - */ - public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) - { - return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); - } - - /** - * Returns schema versions that the component can export to. - * ILIAS chooses the first one, that has min/max constraints which - * fit to the target release. Please put the newest on top. - * - * @return - */ - function getValidSchemaVersions($a_entity) - { - return array ( - "5.1.0" => array( - "namespace" => "http://www.ilias.de/Modules/MediaPool/mep/5_1", - "xsd_file" => "ilias_mep_5_1.xsd", - "uses_dataset" => true, - "min" => "5.1.0", - "max" => ""), - "4.1.0" => array( - "namespace" => "http://www.ilias.de/Modules/MediaPool/mep/4_1", - "xsd_file" => "ilias_mep_4_1.xsd", - "uses_dataset" => true, - "min" => "4.1.0", - "max" => "") - ); - } - + return $deps; + } + + /** + * Get xml representation + * + * @param string entity + * @param string schema version + * @param string id + * @return string xml string + */ + public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) + { + return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); + } + + /** + * Returns schema versions that the component can export to. + * ILIAS chooses the first one, that has min/max constraints which + * fit to the target release. Please put the newest on top. + * + * @return + */ + public function getValidSchemaVersions($a_entity) + { + return array( + "5.1.0" => array( + "namespace" => "http://www.ilias.de/Modules/MediaPool/mep/5_1", + "xsd_file" => "ilias_mep_5_1.xsd", + "uses_dataset" => true, + "min" => "5.1.0", + "max" => ""), + "4.1.0" => array( + "namespace" => "http://www.ilias.de/Modules/MediaPool/mep/4_1", + "xsd_file" => "ilias_mep_4_1.xsd", + "uses_dataset" => true, + "min" => "4.1.0", + "max" => "") + ); + } } - -?> \ No newline at end of file diff --git a/Modules/MediaPool/classes/class.ilMediaPoolImportConfig.php b/Modules/MediaPool/classes/class.ilMediaPoolImportConfig.php index 96812c11c185872040381e6ecc9004cbb9566095..6045bb06360bb66397618e2599173881c75d1ead 100644 --- a/Modules/MediaPool/classes/class.ilMediaPoolImportConfig.php +++ b/Modules/MediaPool/classes/class.ilMediaPoolImportConfig.php @@ -12,60 +12,54 @@ include_once("./Services/Export/classes/class.ilImportConfig.php"); */ class ilMediaPoolImportConfig extends ilImportConfig { - protected $transl_into = false; - protected $transl_into_lm = null; - protected $transl_lang = ""; + protected $transl_into = false; + protected $transl_into_lm = null; + protected $transl_lang = ""; - /** - * Set translation import mode - * - * @param ilObjLearningModule $a_lm learning module - * @param string $a_lang language - */ - function setTranslationImportMode($a_lm, $a_lang = "") - { - if ($a_lm != null) - { - $this->transl_into = true; - $this->transl_into_lm = $a_lm; - $this->transl_lang = $a_lang; - } - else - { - $this->transl_into = false; - } - } + /** + * Set translation import mode + * + * @param ilObjLearningModule $a_lm learning module + * @param string $a_lang language + */ + public function setTranslationImportMode($a_lm, $a_lang = "") + { + if ($a_lm != null) { + $this->transl_into = true; + $this->transl_into_lm = $a_lm; + $this->transl_lang = $a_lang; + } else { + $this->transl_into = false; + } + } - /** - * Get translation import mode - * - * @return bool check if translation import is activated - */ - function getTranslationImportMode() - { - return $this->transl_into; - } + /** + * Get translation import mode + * + * @return bool check if translation import is activated + */ + public function getTranslationImportMode() + { + return $this->transl_into; + } - /** - * Get translation lm - * - * @return ilObjLearningModule learning module - */ - function getTranslationLM() - { - return $this->transl_into_lm; - } - - /** - * Get translation language - * - * @return string language - */ - function getTranslationLang() - { - return $this->transl_lang; - } + /** + * Get translation lm + * + * @return ilObjLearningModule learning module + */ + public function getTranslationLM() + { + return $this->transl_into_lm; + } + /** + * Get translation language + * + * @return string language + */ + public function getTranslationLang() + { + return $this->transl_lang; + } } - -?> \ No newline at end of file diff --git a/Modules/MediaPool/classes/class.ilMediaPoolImportGUI.php b/Modules/MediaPool/classes/class.ilMediaPoolImportGUI.php index bfec1706d9c241cb7fa39e5b1a95f8db0f30081c..e661cf4aa56310a829ef189b2553c15b7d7e3a65 100644 --- a/Modules/MediaPool/classes/class.ilMediaPoolImportGUI.php +++ b/Modules/MediaPool/classes/class.ilMediaPoolImportGUI.php @@ -11,138 +11,135 @@ */ class ilMediaPoolImportGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTemplate - */ - protected $tpl; - - protected $lm; - - /** - * Constructor - */ - function __construct($a_mep) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - $this->mep = $a_mep; - } - - /** - * Execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - - $cmd = $ilCtrl->getCmd("showTranslationImportForm"); - - if (in_array($cmd, array("showTranslationImportForm", "importTranslation"))) - { - $this->$cmd(); - } - } - - /** - * Translation import - * - * @param - * @return - */ - function showTranslationImportForm() - { - $lng = $this->lng; - $tpl = $this->tpl; - - ilUtil::sendInfo($lng->txt("mep_trans_import_info")); - $form = $this->initTranslationImportForm(); - $tpl->setContent($form->getHTML()); - } - - /** - * Init translation input form. - */ - public function initTranslationImportForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $lng->loadLanguageModule("meta"); - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - - // import file - $fi = new ilFileInputGUI($lng->txt("file"), "importfile"); - $fi->setSuffixes(array("zip")); - $fi->setRequired(true); - $fi->setSize(30); - $form->addItem($fi); - - include_once("./Services/MetaData/classes/class.ilMDLanguageItem.php"); - include_once("./Services/Object/classes/class.ilObjectTranslation.php"); - $ot = ilObjectTranslation::getInstance($this->mep->getId()); - foreach ($ot->getLanguages() as $l) - { - if ($l["lang_code"] != $ot->getMasterLanguage()) - { - $options[$l["lang_code"]] = $lng->txt("meta_l_".$l["lang_code"]); - } - } - $si = new ilSelectInputGUI($lng->txt("mep_import_lang"), "import_lang"); - $si->setOptions($options); - $form->addItem($si); - - $form->addCommandButton("importTranslation", $lng->txt("import")); - $form->setTitle($lng->txt("mep_import_trans")); - $form->setFormAction($ilCtrl->getFormAction($this)); - - return $form; - } - - /** - * Import translation - */ - function importTranslation() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - include_once("./Services/Export/classes/class.ilImport.php"); - $imp = new ilImport(); - $conf = $imp->getConfig("Modules/MediaPool"); - - $target_lang = ilUtil::stripSlashes($_POST["import_lang"]); - include_once("./Services/Object/classes/class.ilObjectTranslation.php"); - $ot = ilObjectTranslation::getInstance($this->mep->getId()); - if ($target_lang == $ot->getMasterLanguage()) - { - ilUtil::sendFailure($lng->txt("mep_transl_master_language_not_allowed"), true); - $ilCtrl->redirect($this, "showTranslationImportForm"); - } - - $conf->setTranslationImportMode($this->mep, $target_lang); - $imp->importObject(null, $_FILES["importfile"]["tmp_name"], - $_FILES["importfile"]["name"], "mep", "Modules/MediaPool"); -//echo "h"; exit; - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "showTranslationImportForm"); - } - - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTemplate + */ + protected $tpl; + + protected $lm; + + /** + * Constructor + */ + public function __construct($a_mep) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + $this->mep = $a_mep; + } + + /** + * Execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $cmd = $ilCtrl->getCmd("showTranslationImportForm"); + + if (in_array($cmd, array("showTranslationImportForm", "importTranslation"))) { + $this->$cmd(); + } + } + + /** + * Translation import + * + * @param + * @return + */ + public function showTranslationImportForm() + { + $lng = $this->lng; + $tpl = $this->tpl; + + ilUtil::sendInfo($lng->txt("mep_trans_import_info")); + $form = $this->initTranslationImportForm(); + $tpl->setContent($form->getHTML()); + } + + /** + * Init translation input form. + */ + public function initTranslationImportForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $lng->loadLanguageModule("meta"); + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + + // import file + $fi = new ilFileInputGUI($lng->txt("file"), "importfile"); + $fi->setSuffixes(array("zip")); + $fi->setRequired(true); + $fi->setSize(30); + $form->addItem($fi); + + include_once("./Services/MetaData/classes/class.ilMDLanguageItem.php"); + include_once("./Services/Object/classes/class.ilObjectTranslation.php"); + $ot = ilObjectTranslation::getInstance($this->mep->getId()); + foreach ($ot->getLanguages() as $l) { + if ($l["lang_code"] != $ot->getMasterLanguage()) { + $options[$l["lang_code"]] = $lng->txt("meta_l_" . $l["lang_code"]); + } + } + $si = new ilSelectInputGUI($lng->txt("mep_import_lang"), "import_lang"); + $si->setOptions($options); + $form->addItem($si); + + $form->addCommandButton("importTranslation", $lng->txt("import")); + $form->setTitle($lng->txt("mep_import_trans")); + $form->setFormAction($ilCtrl->getFormAction($this)); + + return $form; + } + + /** + * Import translation + */ + public function importTranslation() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + include_once("./Services/Export/classes/class.ilImport.php"); + $imp = new ilImport(); + $conf = $imp->getConfig("Modules/MediaPool"); + + $target_lang = ilUtil::stripSlashes($_POST["import_lang"]); + include_once("./Services/Object/classes/class.ilObjectTranslation.php"); + $ot = ilObjectTranslation::getInstance($this->mep->getId()); + if ($target_lang == $ot->getMasterLanguage()) { + ilUtil::sendFailure($lng->txt("mep_transl_master_language_not_allowed"), true); + $ilCtrl->redirect($this, "showTranslationImportForm"); + } + + $conf->setTranslationImportMode($this->mep, $target_lang); + $imp->importObject( + null, + $_FILES["importfile"]["tmp_name"], + $_FILES["importfile"]["name"], + "mep", + "Modules/MediaPool" + ); + //echo "h"; exit; + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "showTranslationImportForm"); + } } - -?> \ No newline at end of file diff --git a/Modules/MediaPool/classes/class.ilMediaPoolImporter.php b/Modules/MediaPool/classes/class.ilMediaPoolImporter.php index 89b33b06f95c8c166d2beb60348acc80e0d894e1..a9cdf7ac9ca2368e3cbd64bace10a7cec39df0e9 100644 --- a/Modules/MediaPool/classes/class.ilMediaPoolImporter.php +++ b/Modules/MediaPool/classes/class.ilMediaPoolImporter.php @@ -13,66 +13,66 @@ include_once("./Services/Export/classes/class.ilXmlImporter.php"); class ilMediaPoolImporter extends ilXmlImporter { - /** - * Initialisation - */ - function init() - { - include_once("./Modules/MediaPool/classes/class.ilMediaPoolDataSet.php"); - $this->ds = new ilMediaPoolDataSet(); - $this->ds->setDSPrefix("ds"); + /** + * Initialisation + */ + public function init() + { + include_once("./Modules/MediaPool/classes/class.ilMediaPoolDataSet.php"); + $this->ds = new ilMediaPoolDataSet(); + $this->ds->setDSPrefix("ds"); - $this->config = $this->getImport()->getConfig("Modules/MediaPool"); - if ($this->config->getTranslationImportMode()) - { - $this->ds->setTranslationImportMode( - $this->config->getTranslationLM(), - $this->config->getTranslationLang()); - $cop_config = $this->getImport()->getConfig("Services/COPage"); - $cop_config->setUpdateIfExists(true); - $cop_config->setForceLanguage($this->config->getTranslationLang()); - $cop_config->setReuseOriginallyExportedMedia(true); - $cop_config->setSkipInternalLinkResolve(true); + $this->config = $this->getImport()->getConfig("Modules/MediaPool"); + if ($this->config->getTranslationImportMode()) { + $this->ds->setTranslationImportMode( + $this->config->getTranslationLM(), + $this->config->getTranslationLang() + ); + $cop_config = $this->getImport()->getConfig("Services/COPage"); + $cop_config->setUpdateIfExists(true); + $cop_config->setForceLanguage($this->config->getTranslationLang()); + $cop_config->setReuseOriginallyExportedMedia(true); + $cop_config->setSkipInternalLinkResolve(true); - $mob_config = $this->getImport()->getConfig("Services/MediaObjects"); - $mob_config->setUsePreviousImportIds(true); - } + $mob_config = $this->getImport()->getConfig("Services/MediaObjects"); + $mob_config->setUsePreviousImportIds(true); + } + } - } + /** + * Import XML + * + * @param + * @return + */ + public function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) + { + include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); + $parser = new ilDataSetImportParser( + $a_entity, + $this->getSchemaVersion(), + $a_xml, + $this->ds, + $a_mapping + ); + } - /** - * Import XML - * - * @param - * @return - */ - function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) - { - 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) - { - $pg_map = $a_mapping->getMappingsOfEntity("Modules/MediaPool", "pg"); - - include_once("./Modules/MediaPool/classes/class.ilMediaPoolPage.php"); - include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); - foreach ($pg_map as $pg_id) - { - $mep_id = ilMediaPoolItem::getPoolForItemId($pg_id); - $mep_id = current($mep_id); - ilMediaPoolPage::_writeParentId("mep", $pg_id, $mep_id); - } - } + /** + * Final processing + * + * @param array mapping array + */ + public function finalProcessing($a_mapping) + { + $pg_map = $a_mapping->getMappingsOfEntity("Modules/MediaPool", "pg"); + include_once("./Modules/MediaPool/classes/class.ilMediaPoolPage.php"); + include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); + foreach ($pg_map as $pg_id) { + $mep_id = ilMediaPoolItem::getPoolForItemId($pg_id); + $mep_id = current($mep_id); + ilMediaPoolPage::_writeParentId("mep", $pg_id, $mep_id); + } + } } - -?> \ No newline at end of file diff --git a/Modules/MediaPool/classes/class.ilMediaPoolItem.php b/Modules/MediaPool/classes/class.ilMediaPoolItem.php index 12e49a9f1fb309a80bf3cadf530c95690742e897..99f20bf7fda152ff5f100ca53d4119f55c281dce 100644 --- a/Modules/MediaPool/classes/class.ilMediaPoolItem.php +++ b/Modules/MediaPool/classes/class.ilMediaPoolItem.php @@ -10,321 +10,319 @@ */ class ilMediaPoolItem { - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; - protected $import_id; + protected $import_id; - /** - * Construtor - * - * @param int media pool item id - */ - function __construct($a_id = 0) - { - global $DIC; + /** + * Construtor + * + * @param int media pool item id + */ + public function __construct($a_id = 0) + { + global $DIC; - $this->db = $DIC->database(); - if ($a_id > 0) - { - $this->setId($a_id); - $this->read(); - } - } - - /** - * Set id - * - * @param int id - */ - function setId($a_val) - { - $this->id = $a_val; - } - - /** - * Get id - * - * @return int id - */ - function getId() - { - return $this->id; - } + $this->db = $DIC->database(); + if ($a_id > 0) { + $this->setId($a_id); + $this->read(); + } + } + + /** + * Set id + * + * @param int id + */ + public function setId($a_val) + { + $this->id = $a_val; + } + + /** + * Get id + * + * @return int id + */ + public function getId() + { + return $this->id; + } - /** - * Set type - * - * @param string type - */ - function setType($a_val) - { - $this->type = $a_val; - } - - /** - * Get type - * - * @return string type - */ - function getType() - { - return $this->type; - } - - /** - * Set foreign id - * - * @param int foreign id - */ - function setForeignId($a_val) - { - $this->foreign_id = $a_val; - } - - /** - * Get foreign id - * - * @return int foreign id - */ - function getForeignId() - { - return $this->foreign_id; - } + /** + * Set type + * + * @param string type + */ + public function setType($a_val) + { + $this->type = $a_val; + } + + /** + * Get type + * + * @return string type + */ + public function getType() + { + return $this->type; + } + + /** + * Set foreign id + * + * @param int foreign id + */ + public function setForeignId($a_val) + { + $this->foreign_id = $a_val; + } + + /** + * Get foreign id + * + * @return int foreign id + */ + public function getForeignId() + { + return $this->foreign_id; + } - /** - * Set import id - * - * @param string $a_val import id - */ - function setImportId($a_val) - { - $this->import_id = $a_val; - } - - /** - * Get import id - * - * @return string import id - */ - function getImportId() - { - return $this->import_id; - } - - /** - * Set title - * - * @param string title - */ - function setTitle($a_val) - { - $this->title = $a_val; - } - - /** - * Get title - * - * @return string title - */ - function getTitle() - { - return $this->title; - } - - /** - * Create - */ - function create() - { - $ilDB = $this->db; - - $nid = $ilDB->nextId("mep_item"); - $ilDB->manipulate("INSERT INTO mep_item ". - "(obj_id, type, foreign_id, title, import_id) VALUES (". - $ilDB->quote($nid, "integer").",". - $ilDB->quote($this->getType(), "text").",". - $ilDB->quote($this->getForeignId(), "integer").",". - $ilDB->quote($this->getTitle(), "text").",". - $ilDB->quote($this->getImportId(), "text"). - ")"); - $this->setId($nid); - } - - /** - * Read - */ - function read() - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT * FROM mep_item WHERE ". - "obj_id = ".$ilDB->quote($this->getId(), "integer") - ); - if ($rec = $ilDB->fetchAssoc($set)) - { - $this->setType($rec["type"]); - $this->setForeignId($rec["foreign_id"]); - $this->setTitle($rec["title"]); - $this->setImportId($rec["import_id"]); - } - } - - /** - * Update - * - * @param - * @return - */ - function update() - { - $ilDB = $this->db; - - $ilDB->manipulate("UPDATE mep_item SET ". - " type = ".$ilDB->quote($this->getType(), "text").",". - " foreign_id = ".$ilDB->quote($this->getForeignId(), "integer").",". - " title = ".$ilDB->quote($this->getTitle(), "text").",". - " import_id = ".$ilDB->quote($this->getImportId(), "text"). - " WHERE obj_id = ".$ilDB->quote($this->getId(), "integer") - ); - } - - /** - * Delete - * - * @param - * @return - */ - function delete() - { - $ilDB = $this->db; - - $ilDB->manipulate("DELETE FROM mep_item WHERE " - ." obj_id = ".$ilDB->quote($this->getId(), "integer") - ); - } - - /** - * Lookup - * - * @param - * @return - */ - private static function lookup($a_id, $a_field) - { - global $DIC; + /** + * Set import id + * + * @param string $a_val import id + */ + public function setImportId($a_val) + { + $this->import_id = $a_val; + } + + /** + * Get import id + * + * @return string import id + */ + public function getImportId() + { + return $this->import_id; + } + + /** + * Set title + * + * @param string title + */ + public function setTitle($a_val) + { + $this->title = $a_val; + } + + /** + * Get title + * + * @return string title + */ + public function getTitle() + { + return $this->title; + } + + /** + * Create + */ + public function create() + { + $ilDB = $this->db; + + $nid = $ilDB->nextId("mep_item"); + $ilDB->manipulate("INSERT INTO mep_item " . + "(obj_id, type, foreign_id, title, import_id) VALUES (" . + $ilDB->quote($nid, "integer") . "," . + $ilDB->quote($this->getType(), "text") . "," . + $ilDB->quote($this->getForeignId(), "integer") . "," . + $ilDB->quote($this->getTitle(), "text") . "," . + $ilDB->quote($this->getImportId(), "text") . + ")"); + $this->setId($nid); + } + + /** + * Read + */ + public function read() + { + $ilDB = $this->db; + + $set = $ilDB->query( + "SELECT * FROM mep_item WHERE " . + "obj_id = " . $ilDB->quote($this->getId(), "integer") + ); + if ($rec = $ilDB->fetchAssoc($set)) { + $this->setType($rec["type"]); + $this->setForeignId($rec["foreign_id"]); + $this->setTitle($rec["title"]); + $this->setImportId($rec["import_id"]); + } + } + + /** + * Update + * + * @param + * @return + */ + public function update() + { + $ilDB = $this->db; + + $ilDB->manipulate( + "UPDATE mep_item SET " . + " type = " . $ilDB->quote($this->getType(), "text") . "," . + " foreign_id = " . $ilDB->quote($this->getForeignId(), "integer") . "," . + " title = " . $ilDB->quote($this->getTitle(), "text") . "," . + " import_id = " . $ilDB->quote($this->getImportId(), "text") . + " WHERE obj_id = " . $ilDB->quote($this->getId(), "integer") + ); + } + + /** + * Delete + * + * @param + * @return + */ + public function delete() + { + $ilDB = $this->db; + + $ilDB->manipulate( + "DELETE FROM mep_item WHERE " + . " obj_id = " . $ilDB->quote($this->getId(), "integer") + ); + } + + /** + * Lookup + * + * @param + * @return + */ + private static function lookup($a_id, $a_field) + { + global $DIC; - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT ".$a_field." FROM mep_item WHERE ". - " obj_id = ".$ilDB->quote($a_id, "integer")); - if ($rec = $ilDB->fetchAssoc($set)) - { - return $rec[$a_field]; - } - return false; - } - - /** - * Lookup Foreign Id - * - * @param int mep item id - */ - static function lookupForeignId($a_id) - { - return self::lookup($a_id, "foreign_id"); - } + $ilDB = $DIC->database(); + + $set = $ilDB->query("SELECT " . $a_field . " FROM mep_item WHERE " . + " obj_id = " . $ilDB->quote($a_id, "integer")); + if ($rec = $ilDB->fetchAssoc($set)) { + return $rec[$a_field]; + } + return false; + } + + /** + * Lookup Foreign Id + * + * @param int mep item id + */ + public static function lookupForeignId($a_id) + { + return self::lookup($a_id, "foreign_id"); + } - /** - * Lookup type - * - * @param int mep item id - */ - static function lookupType($a_id) - { - return self::lookup($a_id, "type"); - } + /** + * Lookup type + * + * @param int mep item id + */ + public static function lookupType($a_id) + { + return self::lookup($a_id, "type"); + } - /** - * Lookup title - * - * @param int mep item id - */ - static function lookupTitle($a_id) - { - return self::lookup($a_id, "title"); - } - - /** - * Update object title - * - * @param - * @return - */ - static function updateObjectTitle($a_obj) - { - global $DIC; + /** + * Lookup title + * + * @param int mep item id + */ + public static function lookupTitle($a_id) + { + return self::lookup($a_id, "title"); + } + + /** + * Update object title + * + * @param + * @return + */ + public static function updateObjectTitle($a_obj) + { + global $DIC; - $ilDB = $DIC->database(); + $ilDB = $DIC->database(); - if (ilObject::_lookupType($a_obj) == "mob") - { - $title = ilObject::_lookupTitle($a_obj); - $ilDB->manipulate("UPDATE mep_item SET ". - " title = ".$ilDB->quote($title, "text"). - " WHERE foreign_id = ".$ilDB->quote($a_obj, "integer"). - " AND type = ".$ilDB->quote("mob", "text") - ); - } - } - - /** - * Get media pools for item id - */ - static function getPoolForItemId($a_id) - { - global $DIC; + if (ilObject::_lookupType($a_obj) == "mob") { + $title = ilObject::_lookupTitle($a_obj); + $ilDB->manipulate( + "UPDATE mep_item SET " . + " title = " . $ilDB->quote($title, "text") . + " WHERE foreign_id = " . $ilDB->quote($a_obj, "integer") . + " AND type = " . $ilDB->quote("mob", "text") + ); + } + } + + /** + * Get media pools for item id + */ + public static function getPoolForItemId($a_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT * FROM mep_tree ". - " WHERE child = ".$ilDB->quote($a_id, "integer") - ); - $pool_ids = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $pool_ids[] = $rec["mep_id"]; - } - return $pool_ids; // currently this array should contain only one id - } + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT * FROM mep_tree " . + " WHERE child = " . $ilDB->quote($a_id, "integer") + ); + $pool_ids = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $pool_ids[] = $rec["mep_id"]; + } + return $pool_ids; // currently this array should contain only one id + } - /** - * Get all ids for type - * - * @param - * @return - */ - static function getIdsForType($a_id, $a_type) - { - global $DIC; + /** + * Get all ids for type + * + * @param + * @return + */ + public static function getIdsForType($a_id, $a_type) + { + global $DIC; - $ilDB = $DIC->database(); + $ilDB = $DIC->database(); - $set = $ilDB->query("SELECT mep_tree.child as id". - " FROM mep_tree JOIN mep_item ON (mep_tree.child = mep_item.obj_id) WHERE ". - " mep_tree.mep_id = ".$ilDB->quote($a_id, "integer")." AND ". - " mep_item.type = ".$ilDB->quote($a_type, "text") - ); - - $ids = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $ids[] = $rec["id"]; - } - return $ids; - } + $set = $ilDB->query( + "SELECT mep_tree.child as id" . + " FROM mep_tree JOIN mep_item ON (mep_tree.child = mep_item.obj_id) WHERE " . + " mep_tree.mep_id = " . $ilDB->quote($a_id, "integer") . " AND " . + " mep_item.type = " . $ilDB->quote($a_type, "text") + ); + $ids = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $ids[] = $rec["id"]; + } + return $ids; + } } -?> \ No newline at end of file diff --git a/Modules/MediaPool/classes/class.ilMediaPoolPage.php b/Modules/MediaPool/classes/class.ilMediaPoolPage.php index c02840355a404f677838742469d2cf6f100a7893..ec8b7bca2a043ea7b5caedc6bdec8f3db992c7cf 100644 --- a/Modules/MediaPool/classes/class.ilMediaPoolPage.php +++ b/Modules/MediaPool/classes/class.ilMediaPoolPage.php @@ -5,234 +5,225 @@ include_once("./Services/COPage/classes/class.ilPageObject.php"); /** * Class ilMediaPoolPage -* -* @author Alex Killing +* +* @author Alex Killing * @version $Id$ * * @ingroup ModulesMediaPool */ class ilMediaPoolPage extends ilPageObject { - /** - * Get parent type - * - * @return string parent type - */ - function getParentType() - { - return "mep"; - } - - /** - * update object data - * - * @access public - * @return boolean - */ - function update($a_validate = true, $a_no_history = false) - { - $ilDB = $this->db; - parent::update($a_validate, $a_no_history); - - return true; - } - - /** - * Read media_pool data - */ - function read() - { - $ilDB = $this->db; - - // get co page - parent::read(); - } - - - /** - * delete media_pool page and al related data - * - * @access public - */ - function delete() - { - $ilDB = $this->db; - - - // delete internal links information to this page -// include_once("./Services/Link/classes/class.ilInternalLink.php"); -// ilInternalLink::_deleteAllLinksToTarget("mep", $this->getId()); - - - // delete co page - parent::delete(); - - return true; - } - - /** - * delete media pool page and al related data - * - * @access public - */ - static function deleteAllPagesOfMediaPool($a_media_pool_id) - { - global $DIC; - - $ilDB = $DIC->database(); - -// todo + /** + * Get parent type + * + * @return string parent type + */ + public function getParentType() + { + return "mep"; + } + + /** + * update object data + * + * @access public + * @return boolean + */ + public function update($a_validate = true, $a_no_history = false) + { + $ilDB = $this->db; + parent::update($a_validate, $a_no_history); + + return true; + } + + /** + * Read media_pool data + */ + public function read() + { + $ilDB = $this->db; + + // get co page + parent::read(); + } + + + /** + * delete media_pool page and al related data + * + * @access public + */ + public function delete() + { + $ilDB = $this->db; + + + // delete internal links information to this page + // include_once("./Services/Link/classes/class.ilInternalLink.php"); + // ilInternalLink::_deleteAllLinksToTarget("mep", $this->getId()); + + + // delete co page + parent::delete(); + + return true; + } + + /** + * delete media pool page and al related data + * + * @access public + */ + public static function deleteAllPagesOfMediaPool($a_media_pool_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + // todo /* - $query = "SELECT * FROM il_media_pool_page". - " WHERE media_pool_id = ".$ilDB->quote($a_media_pool_id, "integer"); - $set = $ilDB->query($query); - - while($rec = $ilDB->fetchAssoc($set)) - { - $mp_page = new ilMediaPoolPage($rec["id"]); - $mp_page->delete(); - } + $query = "SELECT * FROM il_media_pool_page". + " WHERE media_pool_id = ".$ilDB->quote($a_media_pool_id, "integer"); + $set = $ilDB->query($query); + + while($rec = $ilDB->fetchAssoc($set)) + { + $mp_page = new ilMediaPoolPage($rec["id"]); + $mp_page->delete(); + } */ - } - - /** - * Checks whether a page with given title exists - */ - static function exists($a_media_pool_id, $a_title) - { - global $DIC; - - $ilDB = $DIC->database(); - -// todo -/* - - $query = "SELECT * FROM il_media_pool_page". - " WHERE media_pool_id = ".$ilDB->quote($a_media_pool_id, "integer"). - " AND title = ".$ilDB->quote($a_title, "text"); - $set = $ilDB->query($query); - if($rec = $ilDB->fetchAssoc($set)) - { - return true; - } -*/ - return false; - } - - /** - * Lookup title - */ - static function lookupTitle($a_page_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); - return ilMediaPoolItem::lookupTitle($a_page_id); - } - - - /** - * Check whether page exists in media pool or not - * - * @param int media pool id - * @param string page name - * @return boolean page exists true/false - */ - static function _mediaPoolPageExists($a_media_pool_id, $a_title) - { - global $DIC; - - $ilDB = $DIC->database(); -// todo -/* - $query = "SELECT id FROM il_media_pool_page". - " WHERE media_pool_id = ".$ilDB->quote($a_media_pool_id, "integer"). - " AND title = ".$ilDB->quote($a_title, "text"); - $set = $ilDB->query($query); - - $pages = array(); - if ($rec = $ilDB->fetchAssoc($set)) - { - return true; - } -*/ - return false; - } - - /** - * get all usages of current media object - */ - function getUsages($a_incl_hist = true) - { - return self::lookupUsages($this->getId(), $a_incl_hist); - } - - /** - * Lookup usages of media object - * - * @todo: This should be all in one context -> mob id table - */ - static function lookupUsages($a_id, $a_incl_hist = true) - { - global $DIC; - - $ilDB = $DIC->database(); - - // get usages in pages - $q = "SELECT * FROM page_pc_usage WHERE pc_id = ". - $ilDB->quote($a_id, "integer"). - " AND pc_type = ".$ilDB->quote("incl", "text"); - - if (!$a_incl_hist) - { - $q.= " AND usage_hist_nr = ".$ilDB->quote(0, "integer"); - } - - $us_set = $ilDB->query($q); - $ret = array(); - while($us_rec = $ilDB->fetchAssoc($us_set)) - { - $ut = ""; - if(is_int(strpos($us_rec["usage_type"], ":"))) - { - $us_arr = explode(":", $us_rec["usage_type"]); - $ut = $us_arr[1]; - $ct = $us_arr[0]; - } - - // check whether page exists - $skip = false; - if ($ut == "pg") - { - include_once("./Services/COPage/classes/class.ilPageObject.php"); - if (!ilPageObject::_exists($ct, $us_rec["usage_id"])) - { - $skip = true; - } - } - - if (!$skip) - { - $ret[] = array("type" => $us_rec["usage_type"], - "id" => $us_rec["usage_id"], - "hist_nr" => $us_rec["usage_hist_nr"]); - } - } - - // get usages in media pools - $q = "SELECT DISTINCT mep_id FROM mep_tree JOIN mep_item ON (child = obj_id) WHERE mep_item.obj_id = ". - $ilDB->quote($a_id, "integer")." AND mep_item.type = ".$ilDB->quote("pg", "text"); - $us_set = $ilDB->query($q); - while($us_rec = $ilDB->fetchAssoc($us_set)) - { - $ret[] = array("type" => "mep", - "id" => $us_rec["mep_id"]); - } - - return $ret; - } - + } + + /** + * Checks whether a page with given title exists + */ + public static function exists($a_media_pool_id, $a_title) + { + global $DIC; + + $ilDB = $DIC->database(); + + // todo + /* + + $query = "SELECT * FROM il_media_pool_page". + " WHERE media_pool_id = ".$ilDB->quote($a_media_pool_id, "integer"). + " AND title = ".$ilDB->quote($a_title, "text"); + $set = $ilDB->query($query); + if($rec = $ilDB->fetchAssoc($set)) + { + return true; + } + */ + return false; + } + + /** + * Lookup title + */ + public static function lookupTitle($a_page_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); + return ilMediaPoolItem::lookupTitle($a_page_id); + } + + + /** + * Check whether page exists in media pool or not + * + * @param int media pool id + * @param string page name + * @return boolean page exists true/false + */ + public static function _mediaPoolPageExists($a_media_pool_id, $a_title) + { + global $DIC; + + $ilDB = $DIC->database(); + // todo + /* + $query = "SELECT id FROM il_media_pool_page". + " WHERE media_pool_id = ".$ilDB->quote($a_media_pool_id, "integer"). + " AND title = ".$ilDB->quote($a_title, "text"); + $set = $ilDB->query($query); + + $pages = array(); + if ($rec = $ilDB->fetchAssoc($set)) + { + return true; + } + */ + return false; + } + + /** + * get all usages of current media object + */ + public function getUsages($a_incl_hist = true) + { + return self::lookupUsages($this->getId(), $a_incl_hist); + } + + /** + * Lookup usages of media object + * + * @todo: This should be all in one context -> mob id table + */ + public static function lookupUsages($a_id, $a_incl_hist = true) + { + global $DIC; + + $ilDB = $DIC->database(); + + // get usages in pages + $q = "SELECT * FROM page_pc_usage WHERE pc_id = " . + $ilDB->quote($a_id, "integer") . + " AND pc_type = " . $ilDB->quote("incl", "text"); + + if (!$a_incl_hist) { + $q.= " AND usage_hist_nr = " . $ilDB->quote(0, "integer"); + } + + $us_set = $ilDB->query($q); + $ret = array(); + while ($us_rec = $ilDB->fetchAssoc($us_set)) { + $ut = ""; + if (is_int(strpos($us_rec["usage_type"], ":"))) { + $us_arr = explode(":", $us_rec["usage_type"]); + $ut = $us_arr[1]; + $ct = $us_arr[0]; + } + + // check whether page exists + $skip = false; + if ($ut == "pg") { + include_once("./Services/COPage/classes/class.ilPageObject.php"); + if (!ilPageObject::_exists($ct, $us_rec["usage_id"])) { + $skip = true; + } + } + + if (!$skip) { + $ret[] = array("type" => $us_rec["usage_type"], + "id" => $us_rec["usage_id"], + "hist_nr" => $us_rec["usage_hist_nr"]); + } + } + + // get usages in media pools + $q = "SELECT DISTINCT mep_id FROM mep_tree JOIN mep_item ON (child = obj_id) WHERE mep_item.obj_id = " . + $ilDB->quote($a_id, "integer") . " AND mep_item.type = " . $ilDB->quote("pg", "text"); + $us_set = $ilDB->query($q); + while ($us_rec = $ilDB->fetchAssoc($us_set)) { + $ret[] = array("type" => "mep", + "id" => $us_rec["mep_id"]); + } + + return $ret; + } } -?> diff --git a/Modules/MediaPool/classes/class.ilMediaPoolPageConfig.php b/Modules/MediaPool/classes/class.ilMediaPoolPageConfig.php index efe07d159cc9719ececfbef757a05b203c38725f..82c2beb56fb6df7c879a3dbf68718dfa59cb1fd6 100644 --- a/Modules/MediaPool/classes/class.ilMediaPoolPageConfig.php +++ b/Modules/MediaPool/classes/class.ilMediaPoolPageConfig.php @@ -5,7 +5,7 @@ include_once("./Services/COPage/classes/class.ilPageConfig.php"); /** - * Media pool page configuration + * Media pool page configuration * * @author Alex Killing * @version $Id$ @@ -13,16 +13,13 @@ include_once("./Services/COPage/classes/class.ilPageConfig.php"); */ class ilMediaPoolPageConfig extends ilPageConfig { - /** - * Init - */ - function init() - { - $this->setEnableInternalLinks(false); - $this->setPreventHTMLUnmasking(false); - $this->setMultiLangSupport(true); - } - + /** + * Init + */ + public function init() + { + $this->setEnableInternalLinks(false); + $this->setPreventHTMLUnmasking(false); + $this->setMultiLangSupport(true); + } } - -?> diff --git a/Modules/MediaPool/classes/class.ilMediaPoolPageGUI.php b/Modules/MediaPool/classes/class.ilMediaPoolPageGUI.php index 3e945d03e45f849b67a189a62fc289264e10b6d3..3024ffca077555f1b3c4b59ac5b7c996f8cf7e00 100644 --- a/Modules/MediaPool/classes/class.ilMediaPoolPageGUI.php +++ b/Modules/MediaPool/classes/class.ilMediaPoolPageGUI.php @@ -7,8 +7,8 @@ include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); /** * Class ilMediaPoolPage GUI class -* -* @author Alex Killing +* +* @author Alex Killing * @version $Id$ * * @ilCtrl_Calls ilMediaPoolPageGUI: ilPageEditorGUI, ilEditClipboardGUI, ilMediaPoolTargetSelector @@ -18,152 +18,151 @@ include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); */ class ilMediaPoolPageGUI extends ilPageObjectGUI { - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * Constructor - */ - function __construct($a_id = 0, $a_old_nr = 0, $a_prevent_get_id = false, $a_lang = "") - { - global $DIC; - - $this->tpl = $DIC["tpl"]; - $this->ctrl = $DIC->ctrl(); - $this->tabs = $DIC->tabs(); - $this->access = $DIC->access(); - $this->lng = $DIC->language(); - $tpl = $DIC["tpl"]; - - parent::__construct("mep", $a_id, $a_old_nr, $a_prevent_get_id, $a_lang); - - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $this->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId(0)); - - $this->setEditPreview(true); - } - - /** - * execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - switch($next_class) - { - default: - return parent::executeCommand(); - } - } - - /** - * Set Media Pool Page Object. - * - * @param object $a_media_pool_page Media Pool Page Object - */ - function setMediaPoolPage($a_media_pool_page) - { - $this->setPageObject($a_media_pool_page); - } - - /** - * Get Media Pool Page Object. - * - * @return object Media Pool Page Object - */ - function getMediaPoolPage() - { - return $this->getPageObject(); - } - - /** - * Get media pool page gui for id and title - */ - static function getGUIForTitle($a_media_pool_id, $a_title, $a_old_nr = 0) - { - global $DIC; - - $ilDB = $DIC->database(); - - include_once("./Modules/MediaPool/classes/class.ilMediaPoolPage.php"); - $id = ilMediaPoolPage::getPageIdForTitle($a_media_pool_id, $a_title); - $page_gui = new ilMediaPoolPageGUI($id, $a_old_nr); - - return $page_gui; - } - - /** - * View media pool page. - */ - function preview() - { - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - $lng = $this->lng; - - return parent::preview(); - } - - /** - * Show page - */ - function showPage($a_no_title = false) - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - - // get raw page content is used for including into other pages - if (!$this->getRawPageContent()) - { - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $tpl->setCurrentBlock("ContentStyle"); - $tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath(0)); - $tpl->parseCurrentBlock(); - - $tpl->setCurrentBlock("SyntaxStyle"); - $tpl->setVariable("LOCATION_SYNTAX_STYLESHEET", - ilObjStyleSheet::getSyntaxStylePath()); - $tpl->parseCurrentBlock(); - } - - $this->setTemplateOutput(false); - if (!$a_no_title) - { - $this->setPresentationTitle(ilMediaPoolItem::lookupTitle($this->getMediaPoolPage()->getId())); - } - $output = parent::showPage(); - - return $output; - } - - function getTabs($a_activate = "") - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - - parent::getTabs($a_activate); - } - - /** - * Get raw content - * - * @param - * @return - */ - function getRawContent() - { - $this->setRawPageContent(true); - $this->setLinkXML(""); - return $this->showPage(true); - } - + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * Constructor + */ + public function __construct($a_id = 0, $a_old_nr = 0, $a_prevent_get_id = false, $a_lang = "") + { + global $DIC; + + $this->tpl = $DIC["tpl"]; + $this->ctrl = $DIC->ctrl(); + $this->tabs = $DIC->tabs(); + $this->access = $DIC->access(); + $this->lng = $DIC->language(); + $tpl = $DIC["tpl"]; + + parent::__construct("mep", $a_id, $a_old_nr, $a_prevent_get_id, $a_lang); + + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $this->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId(0)); + + $this->setEditPreview(true); + } + + /** + * execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + switch ($next_class) { + default: + return parent::executeCommand(); + } + } + + /** + * Set Media Pool Page Object. + * + * @param object $a_media_pool_page Media Pool Page Object + */ + public function setMediaPoolPage($a_media_pool_page) + { + $this->setPageObject($a_media_pool_page); + } + + /** + * Get Media Pool Page Object. + * + * @return object Media Pool Page Object + */ + public function getMediaPoolPage() + { + return $this->getPageObject(); + } + + /** + * Get media pool page gui for id and title + */ + public static function getGUIForTitle($a_media_pool_id, $a_title, $a_old_nr = 0) + { + global $DIC; + + $ilDB = $DIC->database(); + + include_once("./Modules/MediaPool/classes/class.ilMediaPoolPage.php"); + $id = ilMediaPoolPage::getPageIdForTitle($a_media_pool_id, $a_title); + $page_gui = new ilMediaPoolPageGUI($id, $a_old_nr); + + return $page_gui; + } + + /** + * View media pool page. + */ + public function preview() + { + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + $lng = $this->lng; + + return parent::preview(); + } + + /** + * Show page + */ + public function showPage($a_no_title = false) + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + + // get raw page content is used for including into other pages + if (!$this->getRawPageContent()) { + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $tpl->setCurrentBlock("ContentStyle"); + $tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath(0) + ); + $tpl->parseCurrentBlock(); + + $tpl->setCurrentBlock("SyntaxStyle"); + $tpl->setVariable( + "LOCATION_SYNTAX_STYLESHEET", + ilObjStyleSheet::getSyntaxStylePath() + ); + $tpl->parseCurrentBlock(); + } + + $this->setTemplateOutput(false); + if (!$a_no_title) { + $this->setPresentationTitle(ilMediaPoolItem::lookupTitle($this->getMediaPoolPage()->getId())); + } + $output = parent::showPage(); + + return $output; + } + + public function getTabs($a_activate = "") + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + + parent::getTabs($a_activate); + } + + /** + * Get raw content + * + * @param + * @return + */ + public function getRawContent() + { + $this->setRawPageContent(true); + $this->setLinkXML(""); + return $this->showPage(true); + } } -?> diff --git a/Modules/MediaPool/classes/class.ilMediaPoolPageUsagesTableGUI.php b/Modules/MediaPool/classes/class.ilMediaPoolPageUsagesTableGUI.php index 0ab40103ab8a8bb0f2afdda521ab83f18cc110bf..528c9bfaa43bd688024db158249d1a38c0f342f0 100644 --- a/Modules/MediaPool/classes/class.ilMediaPoolPageUsagesTableGUI.php +++ b/Modules/MediaPool/classes/class.ilMediaPoolPageUsagesTableGUI.php @@ -14,281 +14,243 @@ include_once("Services/Table/classes/class.ilTable2GUI.php"); */ class ilMediaPoolPageUsagesTableGUI extends ilTable2GUI { - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_page, $a_incl_hist) - { - global $DIC; + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_page, $a_incl_hist) + { + 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(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->page = $a_page; - $this->incl_hist = $a_incl_hist; - $this->addColumn("", "", "1"); // checkbox - $this->setEnableHeader(false); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.mep_page_usage_row.html", "Modules/MediaPool"); - $this->getItems(); - $this->setTitle($lng->txt("cont_mob_usages")); - } + $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); + $this->page = $a_page; + $this->incl_hist = $a_incl_hist; + $this->addColumn("", "", "1"); // checkbox + $this->setEnableHeader(false); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.mep_page_usage_row.html", "Modules/MediaPool"); + $this->getItems(); + $this->setTitle($lng->txt("cont_mob_usages")); + } - /** - * Get usages - */ - function getItems() - { - $usages = $this->page->getUsages($this->incl_hist); - - $clip_cnt = 0; - $to_del = array(); - $agg_usages = array(); - foreach($usages as $k => $usage) - { - if ($usage["type"] == "clip") - { - $clip_cnt++; - } - else - { - if (empty($agg_usages[$usage["type"].":".$usage["id"]])) - { - $usage["hist_nr"] = array($usage["hist_nr"]); - $agg_usages[$usage["type"].":".$usage["id"]] = $usage; - } - else - { - $agg_usages[$usage["type"].":".$usage["id"]]["hist_nr"][] = - $usage["hist_nr"]; - } - } - } + /** + * Get usages + */ + public function getItems() + { + $usages = $this->page->getUsages($this->incl_hist); + + $clip_cnt = 0; + $to_del = array(); + $agg_usages = array(); + foreach ($usages as $k => $usage) { + if ($usage["type"] == "clip") { + $clip_cnt++; + } else { + if (empty($agg_usages[$usage["type"] . ":" . $usage["id"]])) { + $usage["hist_nr"] = array($usage["hist_nr"]); + $agg_usages[$usage["type"] . ":" . $usage["id"]] = $usage; + } else { + $agg_usages[$usage["type"] . ":" . $usage["id"]]["hist_nr"][] = + $usage["hist_nr"]; + } + } + } - // usages in clipboards - if ($clip_cnt > 0) - { - $agg_usages[] = array("type" => "clip", "cnt" => $clip_cnt); - } + // usages in clipboards + if ($clip_cnt > 0) { + $agg_usages[] = array("type" => "clip", "cnt" => $clip_cnt); + } - $this->setData($agg_usages); - } - - /** - * Standard Version of Fill Row. Most likely to - * be overwritten by derived class. - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; + $this->setData($agg_usages); + } + + /** + * Standard Version of Fill Row. Most likely to + * be overwritten by derived class. + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; - $usage = $a_set; - -//var_dump($usage); + $usage = $a_set; + + //var_dump($usage); - if(is_int(strpos($usage["type"], ":"))) - { - $us_arr = explode(":", $usage["type"]); - $usage["type"] = $us_arr[1]; - $cont_type = $us_arr[0]; - } -//var_dump($usage); + if (is_int(strpos($usage["type"], ":"))) { + $us_arr = explode(":", $usage["type"]); + $usage["type"] = $us_arr[1]; + $cont_type = $us_arr[0]; + } + //var_dump($usage); - include_once('./Services/Link/classes/class.ilLink.php'); + include_once('./Services/Link/classes/class.ilLink.php'); - switch($usage["type"]) - { - case "pg": - include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); - $page_obj = ilPageObjectFactory::getInstance($cont_type, $usage["id"]); - $item = array(); + switch ($usage["type"]) { + case "pg": + include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); + $page_obj = ilPageObjectFactory::getInstance($cont_type, $usage["id"]); + $item = array(); - //$this->tpl->setVariable("TXT_OBJECT", $usage["type"].":".$usage["id"]); - switch ($cont_type) - { - case "lm": - require_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); - require_once("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); - require_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - $lm_obj = new ilObjLearningModule($page_obj->getParentId(), false); - $item["obj_type_txt"] = $this->lng->txt("obj_".$cont_type); - $item["obj_title"] = $lm_obj->getTitle(); - $item["sub_txt"] = $this->lng->txt("pg"); - $item["sub_title"] = ilLMObject::_lookupTitle($page_obj->getId()); - $ref_id = $this->getFirstWritableRefId($lm_obj->getId()); - if ($ref_id > 0) - { - $item["obj_link"] = ilLink::_getStaticLink($page_obj->getId()."_".$ref_id, "pg"); - } - break; + //$this->tpl->setVariable("TXT_OBJECT", $usage["type"].":".$usage["id"]); + switch ($cont_type) { + case "lm": + require_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); + require_once("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); + require_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + $lm_obj = new ilObjLearningModule($page_obj->getParentId(), false); + $item["obj_type_txt"] = $this->lng->txt("obj_" . $cont_type); + $item["obj_title"] = $lm_obj->getTitle(); + $item["sub_txt"] = $this->lng->txt("pg"); + $item["sub_title"] = ilLMObject::_lookupTitle($page_obj->getId()); + $ref_id = $this->getFirstWritableRefId($lm_obj->getId()); + if ($ref_id > 0) { + $item["obj_link"] = ilLink::_getStaticLink($page_obj->getId() . "_" . $ref_id, "pg"); + } + break; - case "wpg": - require_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $item["obj_type_txt"] = $this->lng->txt("obj_wiki"); - $item["obj_title"] = ilObject::_lookupTitle($page_obj->getParentId()); - $item["sub_txt"] = $this->lng->txt("pg"); - $item["sub_title"] = ilWikiPage::lookupTitle($page_obj->getId()); - $ref_id = $this->getFirstWritableRefId($page_obj->getParentId()); - if ($ref_id > 0) - { - $item["obj_link"] = ilLink::_getStaticLink($ref_id, "wiki"); - } - break; + case "wpg": + require_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + $item["obj_type_txt"] = $this->lng->txt("obj_wiki"); + $item["obj_title"] = ilObject::_lookupTitle($page_obj->getParentId()); + $item["sub_txt"] = $this->lng->txt("pg"); + $item["sub_title"] = ilWikiPage::lookupTitle($page_obj->getId()); + $ref_id = $this->getFirstWritableRefId($page_obj->getParentId()); + if ($ref_id > 0) { + $item["obj_link"] = ilLink::_getStaticLink($ref_id, "wiki"); + } + break; - case "gdf": - require_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - require_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); - $term_id = ilGlossaryDefinition::_lookupTermId($page_obj->getId()); - $glo_id = ilGlossaryTerm::_lookGlossaryId($term_id); - $item["obj_type_txt"] = $this->lng->txt("obj_glo"); - $item["obj_title"] = ilObject::_lookupTitle($glo_id); - $item["sub_txt"] = $this->lng->txt("cont_term"); - $item["sub_title"] = ilGlossaryTerm::_lookGlossaryTerm($term_id); - $ref_id = $this->getFirstWritableRefId($page_obj->getParentId()); - if ($ref_id > 0) - { - $item["obj_link"] = ilLink::_getStaticLink($ref_id, "glo"); - } - break; + case "gdf": + require_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + require_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); + $term_id = ilGlossaryDefinition::_lookupTermId($page_obj->getId()); + $glo_id = ilGlossaryTerm::_lookGlossaryId($term_id); + $item["obj_type_txt"] = $this->lng->txt("obj_glo"); + $item["obj_title"] = ilObject::_lookupTitle($glo_id); + $item["sub_txt"] = $this->lng->txt("cont_term"); + $item["sub_title"] = ilGlossaryTerm::_lookGlossaryTerm($term_id); + $ref_id = $this->getFirstWritableRefId($page_obj->getParentId()); + if ($ref_id > 0) { + $item["obj_link"] = ilLink::_getStaticLink($ref_id, "glo"); + } + break; - case "cont": - $item["obj_type_txt"] = $this->lng->txt("obj_".$cont_type); - $item["obj_title"] = ilObject::_lookupTitle($page_obj->getId()); - $ref_id = $this->getFirstWritableRefId($page_obj->getId()); - if ($ref_id > 0) - { - $item["obj_link"] = ilLink::_getStaticLink($ref_id, $cont_type); - } - break; - } - break; + case "cont": + $item["obj_type_txt"] = $this->lng->txt("obj_" . $cont_type); + $item["obj_title"] = ilObject::_lookupTitle($page_obj->getId()); + $ref_id = $this->getFirstWritableRefId($page_obj->getId()); + if ($ref_id > 0) { + $item["obj_link"] = ilLink::_getStaticLink($ref_id, $cont_type); + } + break; + } + break; - case "mep": - $item["obj_type_txt"] = $this->lng->txt("obj_mep"); - $item["obj_title"] = ilObject::_lookupTitle($usage["id"]); - $ref_id = $this->getFirstWritableRefId($usage["id"]); - if ($ref_id > 0) - { - $item["obj_link"] = ilLink::_getStaticLink($ref_id, "mep"); - } - break; + case "mep": + $item["obj_type_txt"] = $this->lng->txt("obj_mep"); + $item["obj_title"] = ilObject::_lookupTitle($usage["id"]); + $ref_id = $this->getFirstWritableRefId($usage["id"]); + if ($ref_id > 0) { + $item["obj_link"] = ilLink::_getStaticLink($ref_id, "mep"); + } + break; - case "map": - $item["obj_type_txt"] = $this->lng->txt("obj_mob"); - $item["obj_title"] = ilObject::_lookupTitle($usage["id"]); - $item["sub_txt"] = $this->lng->txt("cont_link_area"); - break; - } - - // show versions - if (is_array($usage["hist_nr"]) && - (count($usage["hist_nr"]) > 1 || $usage["hist_nr"][0] > 0)) - { - asort($usage["hist_nr"]); - $ver = $sep = ""; - if ($usage["hist_nr"][0] == 0) - { - array_shift($usage["hist_nr"]); - $usage["hist_nr"][] = 0; - } + case "map": + $item["obj_type_txt"] = $this->lng->txt("obj_mob"); + $item["obj_title"] = ilObject::_lookupTitle($usage["id"]); + $item["sub_txt"] = $this->lng->txt("cont_link_area"); + break; + } + + // show versions + if (is_array($usage["hist_nr"]) && + (count($usage["hist_nr"]) > 1 || $usage["hist_nr"][0] > 0)) { + asort($usage["hist_nr"]); + $ver = $sep = ""; + if ($usage["hist_nr"][0] == 0) { + array_shift($usage["hist_nr"]); + $usage["hist_nr"][] = 0; + } - if (count($usage["hist_nr"]) > 5) - { - $ver.= "..., "; - $cnt = count($usage["hist_nr"]) - 5; - for ($i = 0; $i < $cnt; $i++) - { - unset($usage["hist_nr"][$i]); - } - } - foreach ($usage["hist_nr"] as $nr) - { - if ($nr > 0) - { - $ver.= $sep.$nr; - } - else - { - $ver.= $sep.$this->lng->txt("cont_current_version"); - } - $sep = ", "; - } + if (count($usage["hist_nr"]) > 5) { + $ver.= "..., "; + $cnt = count($usage["hist_nr"]) - 5; + for ($i = 0; $i < $cnt; $i++) { + unset($usage["hist_nr"][$i]); + } + } + foreach ($usage["hist_nr"] as $nr) { + if ($nr > 0) { + $ver.= $sep . $nr; + } else { + $ver.= $sep . $this->lng->txt("cont_current_version"); + } + $sep = ", "; + } - $this->tpl->setCurrentBlock("versions"); - $this->tpl->setVariable("TXT_VERSIONS", $this->lng->txt("cont_versions")); - $this->tpl->setVariable("VAL_VERSIONS", $ver); - $this->tpl->parseCurrentBlock(); - } + $this->tpl->setCurrentBlock("versions"); + $this->tpl->setVariable("TXT_VERSIONS", $this->lng->txt("cont_versions")); + $this->tpl->setVariable("VAL_VERSIONS", $ver); + $this->tpl->parseCurrentBlock(); + } - if ($item["obj_type_txt"] != "") - { - $this->tpl->setCurrentBlock("type"); - $this->tpl->setVariable("TXT_TYPE", $this->lng->txt("type")); - $this->tpl->setVariable("VAL_TYPE", $item["obj_type_txt"]); - $this->tpl->parseCurrentBlock(); - } + if ($item["obj_type_txt"] != "") { + $this->tpl->setCurrentBlock("type"); + $this->tpl->setVariable("TXT_TYPE", $this->lng->txt("type")); + $this->tpl->setVariable("VAL_TYPE", $item["obj_type_txt"]); + $this->tpl->parseCurrentBlock(); + } - if ($usage["type"] != "clip") - { - if ($item["obj_link"]) - { - $this->tpl->setCurrentBlock("linked_item"); - $this->tpl->setVariable("TXT_OBJECT", $item["obj_title"]); - $this->tpl->setVariable("HREF_LINK", $item["obj_link"]); - $this->tpl->parseCurrentBlock(); - } - else - { - $this->tpl->setVariable("TXT_OBJECT_NO_LINK", $item["obj_title"]); - } - - if ($item["sub_txt"] != "") - { - $this->tpl->setVariable("SEP", ", "); - $this->tpl->setVariable("SUB_TXT", $item["sub_txt"]); - if ($item["sub_title"] != "") - { - $this->tpl->setVariable("SEP2", ": "); - $this->tpl->setVariable("SUB_TITLE", $item["sub_title"]); - } - } - - } - else - { - $this->tpl->setVariable("TXT_OBJECT_NO_LINK", $this->lng->txt("cont_users_have_mob_in_clip1"). - " ".$usage["cnt"]." ".$this->lng->txt("cont_users_have_mob_in_clip2")); + if ($usage["type"] != "clip") { + if ($item["obj_link"]) { + $this->tpl->setCurrentBlock("linked_item"); + $this->tpl->setVariable("TXT_OBJECT", $item["obj_title"]); + $this->tpl->setVariable("HREF_LINK", $item["obj_link"]); + $this->tpl->parseCurrentBlock(); + } else { + $this->tpl->setVariable("TXT_OBJECT_NO_LINK", $item["obj_title"]); + } + + if ($item["sub_txt"] != "") { + $this->tpl->setVariable("SEP", ", "); + $this->tpl->setVariable("SUB_TXT", $item["sub_txt"]); + if ($item["sub_title"] != "") { + $this->tpl->setVariable("SEP2", ": "); + $this->tpl->setVariable("SUB_TITLE", $item["sub_title"]); + } + } + } else { + $this->tpl->setVariable("TXT_OBJECT_NO_LINK", $this->lng->txt("cont_users_have_mob_in_clip1") . + " " . $usage["cnt"] . " " . $this->lng->txt("cont_users_have_mob_in_clip2")); + } + } - } - } - - function getFirstWritableRefId($a_obj_id) - { - $ilAccess = $this->access; - - $ref_ids = ilObject::_getAllReferences($a_obj_id); - foreach ($ref_ids as $ref_id) - { - if ($ilAccess->checkAccess("write", "", $ref_id)) - { - return $ref_id; - } - } - return 0; - } + public function getFirstWritableRefId($a_obj_id) + { + $ilAccess = $this->access; + + $ref_ids = ilObject::_getAllReferences($a_obj_id); + foreach ($ref_ids as $ref_id) { + if ($ilAccess->checkAccess("write", "", $ref_id)) { + return $ref_id; + } + } + return 0; + } } -?> diff --git a/Modules/MediaPool/classes/class.ilMediaPoolPresentationGUI.php b/Modules/MediaPool/classes/class.ilMediaPoolPresentationGUI.php index 8182c52899f20f6b4e1a2bb74d967c644aa8d75f..96ca11dc836b390832cc70e3cf2fbe2357409074 100755 --- a/Modules/MediaPool/classes/class.ilMediaPoolPresentationGUI.php +++ b/Modules/MediaPool/classes/class.ilMediaPoolPresentationGUI.php @@ -13,95 +13,94 @@ */ class ilMediaPoolPresentationGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilNavigationHistory - */ - protected $nav_history; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilObjectDefinition - */ - protected $objDefinition; - - /** - * Constructor - * @access public - */ - function __construct() - { - global $DIC; - - $this->access = $DIC->access(); - $this->nav_history = $DIC["ilNavigationHistory"]; - $tpl = $DIC["tpl"]; - $lng = $DIC->language(); - $objDefinition = $DIC["objDefinition"]; - $ilCtrl = $DIC->ctrl(); - - $lng->loadLanguageModule("content"); - - $this->ctrl = $ilCtrl; - - // initiate variables - $this->tpl = $tpl; - $this->lng = $lng; - $this->objDefinition = $objDefinition; - } - - /** - * execute command - * @return mixed - * @throws ilCtrlException - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - $ilNavigationHistory = $this->nav_history; - - $next_class = $this->ctrl->getNextClass($this); - - // add entry to navigation history - if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - $ilNavigationHistory->addItem($_GET["ref_id"], - "ilias.php?baseClass=ilMediaPoolPresentationGUI&ref_id=".$_GET["ref_id"], "mep"); - } - - switch($next_class) - { - case "ilobjmediapoolgui": - require_once ("./Modules/MediaPool/classes/class.ilObjMediaPoolGUI.php"); - $mep_gui = new ilObjMediaPoolGUI($_GET["ref_id"]); - $ilCtrl->forwardCommand($mep_gui); - break; - - default: - $this->ctrl->setCmdClass("ilobjmediapoolgui"); - return $this->executeCommand(); - break; - } - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilNavigationHistory + */ + protected $nav_history; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilObjectDefinition + */ + protected $objDefinition; + + /** + * Constructor + * @access public + */ + public function __construct() + { + global $DIC; + + $this->access = $DIC->access(); + $this->nav_history = $DIC["ilNavigationHistory"]; + $tpl = $DIC["tpl"]; + $lng = $DIC->language(); + $objDefinition = $DIC["objDefinition"]; + $ilCtrl = $DIC->ctrl(); + + $lng->loadLanguageModule("content"); + + $this->ctrl = $ilCtrl; + + // initiate variables + $this->tpl = $tpl; + $this->lng = $lng; + $this->objDefinition = $objDefinition; + } + + /** + * execute command + * @return mixed + * @throws ilCtrlException + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + $ilNavigationHistory = $this->nav_history; + + $next_class = $this->ctrl->getNextClass($this); + + // add entry to navigation history + if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) { + $ilNavigationHistory->addItem( + $_GET["ref_id"], + "ilias.php?baseClass=ilMediaPoolPresentationGUI&ref_id=" . $_GET["ref_id"], + "mep" + ); + } + + switch ($next_class) { + case "ilobjmediapoolgui": + require_once("./Modules/MediaPool/classes/class.ilObjMediaPoolGUI.php"); + $mep_gui = new ilObjMediaPoolGUI($_GET["ref_id"]); + $ilCtrl->forwardCommand($mep_gui); + break; + + default: + $this->ctrl->setCmdClass("ilobjmediapoolgui"); + return $this->executeCommand(); + break; + } + } } -?> \ No newline at end of file diff --git a/Modules/MediaPool/classes/class.ilMediaPoolTableGUI.php b/Modules/MediaPool/classes/class.ilMediaPoolTableGUI.php index 2c64a22ac1fe5c4283d5f19b8f20547b858c4fe2..94710ece333071be2d9d45aad76413086bc1777b 100755 --- a/Modules/MediaPool/classes/class.ilMediaPoolTableGUI.php +++ b/Modules/MediaPool/classes/class.ilMediaPoolTableGUI.php @@ -13,603 +13,580 @@ include_once("Services/Table/classes/class.ilTable2GUI.php"); */ class ilMediaPoolTableGUI extends ilTable2GUI { - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilRbacReview - */ - protected $rbacreview; - - /** - * @var ilObjUser - */ - protected $user; - - const IL_MEP_SELECT = "select"; - const IL_MEP_EDIT = "edit"; - const IL_MEP_SELECT_CONTENT = "selectc"; - var $insert_command = "create_mob"; - const IL_MEP_SELECT_SINGLE = "selectsingle"; - protected $parent_tpl = null; // parent / global tpl (where we can add javascript) - - /** - * @var ilAdvancedMDRecordGUI - */ - protected $adv_filter_record_gui; - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, - $a_media_pool, $a_folder_par = "obj_id", - $a_mode = ilMediaPoolTableGUI::IL_MEP_EDIT, $a_all_objects = false, $a_parent_tpl = null) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $this->rbacreview = $DIC->rbac()->review(); - $this->user = $DIC->user(); - - $ilCtrl = $DIC->ctrl(); - $ilAccess = $DIC->access(); - $lng = $DIC->language(); - - if ($a_parent_tpl == null) - { - $a_parent_tpl = $GLOBALS["tpl"]; - } - $this->parent_tpl = $a_parent_tpl; - if ($a_all_objects) - { - $this->setId("mepall"); - if (is_object($a_parent_obj->object)) - { - $this->setId("mepall" . $a_parent_obj->object->getId()); - } - } - else - { - $this->setId("mepfold"); - if (is_object($a_parent_obj->object)) - { - $this->setId("mepfold".$a_parent_obj->object->getId()); - } - } - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setMode($a_mode); - $this->all_objects = $a_all_objects; - $lng->loadLanguageModule("mep"); - - $this->media_pool = $a_media_pool; - $this->tree = ilObjMediaPool::_getPoolTree($this->media_pool->getId()); - $this->folder_par = $a_folder_par; - - if ($this->all_objects) - { - $this->setExternalSorting(true); - $this->initFilter(); - } - // folder determination - if ($_GET[$this->folder_par] > 0) - { - $this->current_folder = $_GET[$this->folder_par]; - } - else if ($_SESSION["mep_pool_folder"] > 0 && $this->tree->isInTree($_SESSION["mep_pool_folder"])) - { - $this->current_folder = $_SESSION["mep_pool_folder"]; - } - else - { - $this->current_folder = $this->tree->getRootId(); - } - $_SESSION["mep_pool_folder"] = $this->current_folder; - - // standard columns - $this->addColumn("", "", "1"); // checkbox - $this->addColumn($lng->txt("mep_thumbnail"), "", "1"); - $this->addColumn($lng->txt("mep_title_and_description")); - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.mep_list_row.html", "Modules/MediaPool"); - - if ($this->showAdvMetadata()) - { - // adv metadata init (adds filter) - include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecordGUI.php'); - $this->adv_filter_record_gui = new ilAdvancedMDRecordGUI(ilAdvancedMDRecordGUI::MODE_FILTER, 'mep', $this->media_pool->getId(), 'mob'); - $this->adv_filter_record_gui->setTableGUI($this); - $this->adv_filter_record_gui->parse(); - - // adv metadata columns - $adv_th_record_gui = new ilAdvancedMDRecordGUI(ilAdvancedMDRecordGUI::MODE_TABLE_HEAD, 'mep', $this->media_pool->getId(), 'mob'); - $adv_th_record_gui->setTableGUI($this); - $adv_th_record_gui->parse(); - if ($a_mode == self::IL_MEP_SELECT) - { - $this->setFilterCommand("insert_applyFilter"); - $this->setResetCommand("insert_resetFilter"); - } - } - - // actions column - $this->addColumn($lng->txt("actions")); - - // get items - $this->getItems(); - - // title - if ($a_mode != ilMediaPoolTableGUI::IL_MEP_EDIT) - { - if ($this->current_folder != $this->tree->getRootId() && !$this->all_objects) - { - $node = $this->tree->getNodeData($this->current_folder); - $this->setTitle( - $lng->txt("mep_choose_from_folder") . ": " . $node["title"], "icon_fold.svg", - $node["title"]); - } else - { - $this->setTitle( - $lng->txt("mep_choose_from_mep") . ": " . - ilObject::_lookupTitle($this->media_pool->getId()), - "icon_mep.svg", - ilObject::_lookupTitle($this->media_pool->getId())); - } - } - - // action commands - if ($ilAccess->checkAccess("write", "", $this->media_pool->getRefId()) && - $this->getMode() == ilMediaPoolTableGUI::IL_MEP_EDIT) - { - $this->addMultiCommand("copyToClipboard", $lng->txt("cont_copy_to_clipboard")); - $this->addMultiCommand("confirmRemove", $lng->txt("remove")); - - if (!$this->all_objects) - { -/* $this->addCommandButton("createFolderForm", $lng->txt("mep_create_folder")); - $this->addCommandButton("createMediaObject", $lng->txt("mep_create_mob")); - - $mset = new ilSetting("mobs"); - if ($mset->get("mep_activate_pages")) - { - $this->addCommandButton("createMediaPoolPage", $lng->txt("mep_create_content_snippet")); - }*/ - } - } - - if ($this->getMode() == ilMediaPoolTableGUI::IL_MEP_SELECT_SINGLE) - { - // ... even more coupling with ilpcmediaobjectgui - $this->addMultiCommand("selectObjectReference", $lng->txt("cont_select")); - } - - if ($this->getMode() == ilMediaPoolTableGUI::IL_MEP_EDIT && - $ilAccess->checkAccess("write", "", $this->media_pool->getRefId())) - { - $this->setSelectAllCheckbox("id"); - } - } - - /** - * Show adv metadata - * @return bool - */ - protected function showAdvMetadata() - { - if ($this->all_objects) - { - return true; - } - - return false; - } - - - /** - * needed for advmd filter handling - * - * @return ilAdvancedMDRecordGUI - */ - protected function getAdvMDRecordGUI() - { - return $this->adv_filter_record_gui; - } - - /** - * Set inser command - * - * @param string inser command - */ - function setInsertCommand($a_val) - { - $this->insert_command = $a_val; - } - - /** - * Get inser command - * - * @return string inser command - */ - function getInsertCommand() - { - return $this->insert_command; - } - - /** - * Get HTML - * - * @param - * @return - */ - function getHTML() - { - $html = parent::getHTML(); - include_once("./Modules/MediaPool/classes/class.ilObjMediaPoolGUI.php"); - $html.= ilObjMediaPoolGUI::getPreviewModalHTML($this->media_pool->getRefId(), $this->parent_tpl); - return $html; - } - - - /** - * Init filter - */ - function initFilter() - { - $lng = $this->lng; - $rbacreview = $this->rbacreview; - $ilUser = $this->user; - - // title/description - include_once("./Services/Form/classes/class.ilTextInputGUI.php"); - $ti = new ilTextInputGUI($lng->txt("title"), "title"); - $ti->setMaxLength(64); - $ti->setSize(20); - $this->addFilterItem($ti); - $ti->readFromSession(); - $this->filter["title"] = $ti->getValue(); - - // keyword - $GLOBALS['lng']->loadLanguageModule('meta'); - $ke = new ilTextInputGUI($lng->txt('meta_keyword'),'keyword'); - $ke->setMaxLength(64); - $ke->setSize(20); - $this->addFilterItem($ke); - $ke->readFromSession(); - $this->filter['keyword'] = $ke->getValue(); - - // Caption - $ca = new ilTextInputGUI($lng->txt('cont_caption'),'caption'); - $ca->setMaxLength(64); - $ca->setSize(20); - $this->addFilterItem($ca); - $ca->readFromSession(); - $this->filter['caption'] = $ca->getValue(); - - // format - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $options = array( - "" => $lng->txt("mep_all"), - ); - $formats = $this->media_pool->getUsedFormats(); - $options = array_merge($options, $formats); - $si = new ilSelectInputGUI($this->lng->txt("mep_format"), "format"); - $si->setOptions($options); - $this->addFilterItem($si); - $si->readFromSession(); - $this->filter["format"] = $si->getValue(); - - } - - /** - * Set Mode. - * - * @param string $a_mode Mode - */ - function setMode($a_mode) - { - $this->mode = $a_mode; - } - - /** - * Get Mode. - * - * @return string Mode - */ - function getMode() - { - return $this->mode; - } - - /** - * Get items of current folder - */ - function getItems() - { - if (!$this->all_objects) - { - $fobjs = $this->media_pool->getChilds($this->current_folder, "fold"); - $f2objs = array(); - foreach ($fobjs as $obj) - { - $f2objs[$obj["title"].":".$obj["child"]] = $obj; - } - ksort($f2objs); - - // get current media objects / pages - if ($this->getMode() == ilMediaPoolTableGUI::IL_MEP_SELECT) - { - $mobjs = $this->media_pool->getChilds($this->current_folder, "mob"); - } - else if ($this->getMode() == ilMediaPoolTableGUI::IL_MEP_SELECT_CONTENT) - { - $mobjs = $this->media_pool->getChilds($this->current_folder, "pg"); - } - else - { - $mobjs = $this->media_pool->getChildsExceptFolders($this->current_folder); - } - $m2objs = array(); - foreach ($mobjs as $obj) - { - $m2objs[$obj["title"].":".$obj["child"]] = $obj; - } - ksort($m2objs); - - // merge everything together - $objs = array_merge($f2objs, $m2objs); - } - else - { - $objs = $this->media_pool->getMediaObjects( - $this->filter["title"], - $this->filter["format"], - $this->filter['keyword'], - $this->filter['caption'] - ); - } - - // add advanced metadata - if ($this->showAdvMetadata()) - { - include_once("./Services/AdvancedMetaData/classes/class.ilAdvancedMDValues.php"); - $objs = ilAdvancedMDValues::queryForRecords($this->media_pool->getRefId(), - "mep", "mob", 0, "mob", $objs, "", "foreign_id", $this->adv_filter_record_gui->getFilterElements()); - } -//echo ("
".$this->media_pool->getRefId()); -//var_dump($objs); exit; - $this->setData($objs); - } - - /** - * Prepare output - * - * @param - * @return - */ - function prepareOutput() - { - $lng = $this->lng; - - if ($this->getMode() == ilMediaPoolTableGUI::IL_MEP_SELECT || - $this->getMode() == ilMediaPoolTableGUI::IL_MEP_SELECT_CONTENT) - { - $this->addMultiCommand($this->getInsertCommand(), $lng->txt("insert")); - $this->addCommandButton("cancelCreate", $lng->txt("cancel")); - } - } - - /** - * Standard Version of Fill Row. Most likely to - * be overwritten by derived class. - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - - $this->tpl->setCurrentBlock("link"); - - // adv metadata columns - if ($this->showAdvMetadata()) - { - $adv_cell_record_gui = new ilAdvancedMDRecordGUI(ilAdvancedMDRecordGUI::MODE_TABLE_CELLS, 'mep', $this->media_pool->getId(), 'mob'); - $adv_cell_record_gui->setTableGUI($this); - $adv_cell_record_gui->setRowData($a_set); - $this->tpl->setVariable("ADV_CELLS", $adv_cell_record_gui->parse()); - } - - - switch($a_set["type"]) - { - case "fold": - $this->tpl->setVariable("TXT_TITLE", $a_set["title"]); - $ilCtrl->setParameter($this->parent_obj, $this->folder_par, $a_set["obj_id"]); - $this->tpl->setVariable("LINK_VIEW", - $ilCtrl->getLinkTarget($this->parent_obj, $this->parent_cmd)); - $this->tpl->parseCurrentBlock(); - - if ($ilAccess->checkAccess("write", "", $this->media_pool->getRefId()) && - $this->getMode() == ilMediaPoolTableGUI::IL_MEP_EDIT) - { - $this->tpl->setCurrentBlock("edit"); - $this->tpl->setVariable("TXT_EDIT", $lng->txt("edit")); - $ilCtrl->setParameter($this->parent_obj, $this->folder_par, $a_set["obj_id"]); - $this->tpl->setVariable("EDIT_LINK", - $ilCtrl->getLinkTarget($this->parent_obj, "editFolder")); - $ilCtrl->setParameter($this->parent_obj, $this->folder_par, $_GET[$this->folder_par]); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setCurrentBlock("tbl_content"); - $this->tpl->setVariable("IMG", ilUtil::img(ilUtil::getImagePath("icon_".$a_set["type"].".svg"))); - $ilCtrl->setParameter($this->parent_obj, $this->folder_par, $this->current_folder); - break; - - case "pg": - if ($this->getMode() == ilMediaPoolTableGUI::IL_MEP_SELECT || - $this->getMode() == ilMediaPoolTableGUI::IL_MEP_SELECT_SINGLE) - { - $this->tpl->setVariable("TXT_NO_LINK_TITLE", $a_set["title"]); - } - else - { - $this->tpl->setVariable("ONCLICK", "il.MediaPool.preview('".$a_set["child"]."'); return false;"); - $this->tpl->setVariable("TXT_TITLE", $a_set["title"]); - $ilCtrl->setParameterByClass("ilobjmediapoolgui", "mepitem_id", $a_set["child"]); - } - - if ($ilAccess->checkAccess("write", "", $this->media_pool->getRefId()) && - $this->getMode() == ilMediaPoolTableGUI::IL_MEP_EDIT) - { - $this->tpl->setCurrentBlock("edit"); - $this->tpl->setVariable("TXT_EDIT", $lng->txt("edit")); - $ilCtrl->setParameterByClass("ilmediapoolpagegui", "mepitem_id", $a_set["child"]); - $this->tpl->setVariable("EDIT_LINK", - $ilCtrl->getLinkTargetByClass("ilmediapoolpagegui", "edit")); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setCurrentBlock("tbl_content"); - $this->tpl->setVariable("IMG", ilUtil::img(ilUtil::getImagePath("icon_pg.svg"))); - $ilCtrl->setParameter($this->parent_obj, $this->folder_par, $this->current_folder); - break; - - case "mob": - $this->tpl->setVariable("ONCLICK", "il.MediaPool.preview('".$a_set["child"]."'); return false;"); - $this->tpl->setVariable("TXT_TITLE", $a_set["title"]); - $ilCtrl->setParameterByClass("ilobjmediaobjectgui", "mepitem_id", $a_set["child"]); - $ilCtrl->setParameter($this->parent_obj, "mob_id", $a_set["foreign_id"]); - - // edit link - if ($ilAccess->checkAccess("write", "", $this->media_pool->getRefId()) && - $this->getMode() == ilMediaPoolTableGUI::IL_MEP_EDIT) - { - $this->tpl->setCurrentBlock("edit"); - $this->tpl->setVariable("TXT_EDIT", $lng->txt("edit")); - $this->tpl->setVariable("EDIT_LINK", - $ilCtrl->getLinkTargetByClass("ilobjmediaobjectgui", "edit")); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setCurrentBlock("link"); - $this->tpl->setCurrentBlock("tbl_content"); - - // output thumbnail (or mob icon) - if (ilObject::_lookupType($a_set["foreign_id"]) == "mob") - { - $mob = new ilObjMediaObject($a_set["foreign_id"]); - $med = $mob->getMediaItem("Standard"); - $target = ""; - if ($med) - { - $target = $med->getThumbnailTarget(); - } - if ($target != "") - { - $this->tpl->setVariable("IMG", ilUtil::img($target)); - } - else - { - $this->tpl->setVariable("IMG", - ilUtil::img(ilUtil::getImagePath("icon_".$a_set["type"].".svg"))); - } - if ($med && ilUtil::deducibleSize($med->getFormat()) && - $med->getLocationType() == "Reference") - { - $size = @getimagesize($med->getLocation()); - if ($size[0] > 0 && $size[1] > 0) - { - $wr = $size[0] / 80; - $hr = $size[1] / 80; - $r = max($wr, $hr); - $w = (int) ($size[0]/$r); - $h = (int) ($size[1]/$r); - $this->tpl->setVariable("IMG", - ilUtil::img($med->getLocation(), "", $w, $h)); - } - } - - // output media info - include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); - $this->tpl->setVariable("MEDIA_INFO", - ilObjMediaObjectGUI::_getMediaInfoHTML($mob)); - $ilCtrl->setParameter($this->parent_obj, $this->folder_par, $this->current_folder); - } - break; - } - - if ($ilAccess->checkAccess("write", "", $this->media_pool->getRefId())) - { - if (($this->getMode() == ilMediaPoolTableGUI::IL_MEP_EDIT || - ($this->getMode() == ilMediaPoolTableGUI::IL_MEP_SELECT && $a_set["type"] == "mob") || - ($this->getMode() == ilMediaPoolTableGUI::IL_MEP_SELECT_CONTENT && $a_set["type"] == "pg") - )) - { - $this->tpl->setCurrentBlock("chbox"); - $this->tpl->setVariable("CHECKBOX_ID", $a_set["child"]); - $this->tpl->parseCurrentBlock(); - $this->tpl->setCurrentBlock("tbl_content"); - } - else if ($this->getMode() == ilMediaPoolTableGUI::IL_MEP_SELECT_SINGLE && $a_set["type"] == "mob") - { - $this->tpl->setCurrentBlock("radio"); - $this->tpl->setVariable("RADIO_ID", $a_set["child"]); - $this->tpl->parseCurrentBlock(); - $this->tpl->setCurrentBlock("tbl_content"); - } - } - } - - /** - * get HTML - * - * @param - * @return - */ - function render() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $mtpl = new ilTemplate("tpl.media_sel_table.html", true, true, "Modules/MediaPool"); - - $pre = ""; - if ($this->current_folder != $this->tree->getRootId() && !$this->all_objects) - { - $path = $this->tree->getPathFull($this->current_folder); - - include_once("./Services/Locator/classes/class.ilLocatorGUI.php"); - $loc = new ilLocatorGUI(); - foreach ($path as $p) - { - $ilCtrl->setParameter($this->parent_obj, $this->folder_par, $p["child"]); - $title = $p["title"]; - if ($this->tree->getRootId() == $p["child"]) - { - $title = ilObject::_lookupTitle($this->media_pool->getId()); - } - $loc->addItem( - $title, - $ilCtrl->getLinkTarget($this->parent_obj, $this->parent_cmd) - ); - } - $ilCtrl->setParameter($this->parent_obj, $this->folder_par, - $this->current_folder); - - $mtpl->setCurrentBlock("loc"); - $mtpl->setVariable("LOC", $loc->getHTML()); - $mtpl->parseCurrentBlock(); - } - - $mtpl->setVariable("TABLE", parent::render()); - - return $mtpl->get(); - } + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilRbacReview + */ + protected $rbacreview; + + /** + * @var ilObjUser + */ + protected $user; + + const IL_MEP_SELECT = "select"; + const IL_MEP_EDIT = "edit"; + const IL_MEP_SELECT_CONTENT = "selectc"; + public $insert_command = "create_mob"; + const IL_MEP_SELECT_SINGLE = "selectsingle"; + protected $parent_tpl = null; // parent / global tpl (where we can add javascript) + + /** + * @var ilAdvancedMDRecordGUI + */ + protected $adv_filter_record_gui; + + /** + * Constructor + */ + public function __construct( + $a_parent_obj, + $a_parent_cmd, + $a_media_pool, + $a_folder_par = "obj_id", + $a_mode = ilMediaPoolTableGUI::IL_MEP_EDIT, + $a_all_objects = false, + $a_parent_tpl = null + ) { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->rbacreview = $DIC->rbac()->review(); + $this->user = $DIC->user(); + + $ilCtrl = $DIC->ctrl(); + $ilAccess = $DIC->access(); + $lng = $DIC->language(); + + if ($a_parent_tpl == null) { + $a_parent_tpl = $GLOBALS["tpl"]; + } + $this->parent_tpl = $a_parent_tpl; + if ($a_all_objects) { + $this->setId("mepall"); + if (is_object($a_parent_obj->object)) { + $this->setId("mepall" . $a_parent_obj->object->getId()); + } + } else { + $this->setId("mepfold"); + if (is_object($a_parent_obj->object)) { + $this->setId("mepfold" . $a_parent_obj->object->getId()); + } + } + + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setMode($a_mode); + $this->all_objects = $a_all_objects; + $lng->loadLanguageModule("mep"); + + $this->media_pool = $a_media_pool; + $this->tree = ilObjMediaPool::_getPoolTree($this->media_pool->getId()); + $this->folder_par = $a_folder_par; + + if ($this->all_objects) { + $this->setExternalSorting(true); + $this->initFilter(); + } + // folder determination + if ($_GET[$this->folder_par] > 0) { + $this->current_folder = $_GET[$this->folder_par]; + } elseif ($_SESSION["mep_pool_folder"] > 0 && $this->tree->isInTree($_SESSION["mep_pool_folder"])) { + $this->current_folder = $_SESSION["mep_pool_folder"]; + } else { + $this->current_folder = $this->tree->getRootId(); + } + $_SESSION["mep_pool_folder"] = $this->current_folder; + + // standard columns + $this->addColumn("", "", "1"); // checkbox + $this->addColumn($lng->txt("mep_thumbnail"), "", "1"); + $this->addColumn($lng->txt("mep_title_and_description")); + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.mep_list_row.html", "Modules/MediaPool"); + + if ($this->showAdvMetadata()) { + // adv metadata init (adds filter) + include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecordGUI.php'); + $this->adv_filter_record_gui = new ilAdvancedMDRecordGUI(ilAdvancedMDRecordGUI::MODE_FILTER, 'mep', $this->media_pool->getId(), 'mob'); + $this->adv_filter_record_gui->setTableGUI($this); + $this->adv_filter_record_gui->parse(); + + // adv metadata columns + $adv_th_record_gui = new ilAdvancedMDRecordGUI(ilAdvancedMDRecordGUI::MODE_TABLE_HEAD, 'mep', $this->media_pool->getId(), 'mob'); + $adv_th_record_gui->setTableGUI($this); + $adv_th_record_gui->parse(); + if ($a_mode == self::IL_MEP_SELECT) { + $this->setFilterCommand("insert_applyFilter"); + $this->setResetCommand("insert_resetFilter"); + } + } + + // actions column + $this->addColumn($lng->txt("actions")); + + // get items + $this->getItems(); + + // title + if ($a_mode != ilMediaPoolTableGUI::IL_MEP_EDIT) { + if ($this->current_folder != $this->tree->getRootId() && !$this->all_objects) { + $node = $this->tree->getNodeData($this->current_folder); + $this->setTitle( + $lng->txt("mep_choose_from_folder") . ": " . $node["title"], + "icon_fold.svg", + $node["title"] + ); + } else { + $this->setTitle( + $lng->txt("mep_choose_from_mep") . ": " . + ilObject::_lookupTitle($this->media_pool->getId()), + "icon_mep.svg", + ilObject::_lookupTitle($this->media_pool->getId()) + ); + } + } + + // action commands + if ($ilAccess->checkAccess("write", "", $this->media_pool->getRefId()) && + $this->getMode() == ilMediaPoolTableGUI::IL_MEP_EDIT) { + $this->addMultiCommand("copyToClipboard", $lng->txt("cont_copy_to_clipboard")); + $this->addMultiCommand("confirmRemove", $lng->txt("remove")); + + if (!$this->all_objects) { + /* $this->addCommandButton("createFolderForm", $lng->txt("mep_create_folder")); + $this->addCommandButton("createMediaObject", $lng->txt("mep_create_mob")); + + $mset = new ilSetting("mobs"); + if ($mset->get("mep_activate_pages")) + { + $this->addCommandButton("createMediaPoolPage", $lng->txt("mep_create_content_snippet")); + }*/ + } + } + + if ($this->getMode() == ilMediaPoolTableGUI::IL_MEP_SELECT_SINGLE) { + // ... even more coupling with ilpcmediaobjectgui + $this->addMultiCommand("selectObjectReference", $lng->txt("cont_select")); + } + + if ($this->getMode() == ilMediaPoolTableGUI::IL_MEP_EDIT && + $ilAccess->checkAccess("write", "", $this->media_pool->getRefId())) { + $this->setSelectAllCheckbox("id"); + } + } + + /** + * Show adv metadata + * @return bool + */ + protected function showAdvMetadata() + { + if ($this->all_objects) { + return true; + } + + return false; + } + + + /** + * needed for advmd filter handling + * + * @return ilAdvancedMDRecordGUI + */ + protected function getAdvMDRecordGUI() + { + return $this->adv_filter_record_gui; + } + + /** + * Set inser command + * + * @param string inser command + */ + public function setInsertCommand($a_val) + { + $this->insert_command = $a_val; + } + + /** + * Get inser command + * + * @return string inser command + */ + public function getInsertCommand() + { + return $this->insert_command; + } + + /** + * Get HTML + * + * @param + * @return + */ + public function getHTML() + { + $html = parent::getHTML(); + include_once("./Modules/MediaPool/classes/class.ilObjMediaPoolGUI.php"); + $html.= ilObjMediaPoolGUI::getPreviewModalHTML($this->media_pool->getRefId(), $this->parent_tpl); + return $html; + } + + + /** + * Init filter + */ + public function initFilter() + { + $lng = $this->lng; + $rbacreview = $this->rbacreview; + $ilUser = $this->user; + + // title/description + include_once("./Services/Form/classes/class.ilTextInputGUI.php"); + $ti = new ilTextInputGUI($lng->txt("title"), "title"); + $ti->setMaxLength(64); + $ti->setSize(20); + $this->addFilterItem($ti); + $ti->readFromSession(); + $this->filter["title"] = $ti->getValue(); + + // keyword + $GLOBALS['lng']->loadLanguageModule('meta'); + $ke = new ilTextInputGUI($lng->txt('meta_keyword'), 'keyword'); + $ke->setMaxLength(64); + $ke->setSize(20); + $this->addFilterItem($ke); + $ke->readFromSession(); + $this->filter['keyword'] = $ke->getValue(); + + // Caption + $ca = new ilTextInputGUI($lng->txt('cont_caption'), 'caption'); + $ca->setMaxLength(64); + $ca->setSize(20); + $this->addFilterItem($ca); + $ca->readFromSession(); + $this->filter['caption'] = $ca->getValue(); + + // format + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $options = array( + "" => $lng->txt("mep_all"), + ); + $formats = $this->media_pool->getUsedFormats(); + $options = array_merge($options, $formats); + $si = new ilSelectInputGUI($this->lng->txt("mep_format"), "format"); + $si->setOptions($options); + $this->addFilterItem($si); + $si->readFromSession(); + $this->filter["format"] = $si->getValue(); + } + + /** + * Set Mode. + * + * @param string $a_mode Mode + */ + public function setMode($a_mode) + { + $this->mode = $a_mode; + } + + /** + * Get Mode. + * + * @return string Mode + */ + public function getMode() + { + return $this->mode; + } + + /** + * Get items of current folder + */ + public function getItems() + { + if (!$this->all_objects) { + $fobjs = $this->media_pool->getChilds($this->current_folder, "fold"); + $f2objs = array(); + foreach ($fobjs as $obj) { + $f2objs[$obj["title"] . ":" . $obj["child"]] = $obj; + } + ksort($f2objs); + + // get current media objects / pages + if ($this->getMode() == ilMediaPoolTableGUI::IL_MEP_SELECT) { + $mobjs = $this->media_pool->getChilds($this->current_folder, "mob"); + } elseif ($this->getMode() == ilMediaPoolTableGUI::IL_MEP_SELECT_CONTENT) { + $mobjs = $this->media_pool->getChilds($this->current_folder, "pg"); + } else { + $mobjs = $this->media_pool->getChildsExceptFolders($this->current_folder); + } + $m2objs = array(); + foreach ($mobjs as $obj) { + $m2objs[$obj["title"] . ":" . $obj["child"]] = $obj; + } + ksort($m2objs); + + // merge everything together + $objs = array_merge($f2objs, $m2objs); + } else { + $objs = $this->media_pool->getMediaObjects( + $this->filter["title"], + $this->filter["format"], + $this->filter['keyword'], + $this->filter['caption'] + ); + } + + // add advanced metadata + if ($this->showAdvMetadata()) { + include_once("./Services/AdvancedMetaData/classes/class.ilAdvancedMDValues.php"); + $objs = ilAdvancedMDValues::queryForRecords( + $this->media_pool->getRefId(), + "mep", + "mob", + 0, + "mob", + $objs, + "", + "foreign_id", + $this->adv_filter_record_gui->getFilterElements() + ); + } + //echo ("
".$this->media_pool->getRefId()); + //var_dump($objs); exit; + $this->setData($objs); + } + + /** + * Prepare output + * + * @param + * @return + */ + public function prepareOutput() + { + $lng = $this->lng; + + if ($this->getMode() == ilMediaPoolTableGUI::IL_MEP_SELECT || + $this->getMode() == ilMediaPoolTableGUI::IL_MEP_SELECT_CONTENT) { + $this->addMultiCommand($this->getInsertCommand(), $lng->txt("insert")); + $this->addCommandButton("cancelCreate", $lng->txt("cancel")); + } + } + + /** + * Standard Version of Fill Row. Most likely to + * be overwritten by derived class. + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + + $this->tpl->setCurrentBlock("link"); + + // adv metadata columns + if ($this->showAdvMetadata()) { + $adv_cell_record_gui = new ilAdvancedMDRecordGUI(ilAdvancedMDRecordGUI::MODE_TABLE_CELLS, 'mep', $this->media_pool->getId(), 'mob'); + $adv_cell_record_gui->setTableGUI($this); + $adv_cell_record_gui->setRowData($a_set); + $this->tpl->setVariable("ADV_CELLS", $adv_cell_record_gui->parse()); + } + + + switch ($a_set["type"]) { + case "fold": + $this->tpl->setVariable("TXT_TITLE", $a_set["title"]); + $ilCtrl->setParameter($this->parent_obj, $this->folder_par, $a_set["obj_id"]); + $this->tpl->setVariable( + "LINK_VIEW", + $ilCtrl->getLinkTarget($this->parent_obj, $this->parent_cmd) + ); + $this->tpl->parseCurrentBlock(); + + if ($ilAccess->checkAccess("write", "", $this->media_pool->getRefId()) && + $this->getMode() == ilMediaPoolTableGUI::IL_MEP_EDIT) { + $this->tpl->setCurrentBlock("edit"); + $this->tpl->setVariable("TXT_EDIT", $lng->txt("edit")); + $ilCtrl->setParameter($this->parent_obj, $this->folder_par, $a_set["obj_id"]); + $this->tpl->setVariable( + "EDIT_LINK", + $ilCtrl->getLinkTarget($this->parent_obj, "editFolder") + ); + $ilCtrl->setParameter($this->parent_obj, $this->folder_par, $_GET[$this->folder_par]); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setCurrentBlock("tbl_content"); + $this->tpl->setVariable("IMG", ilUtil::img(ilUtil::getImagePath("icon_" . $a_set["type"] . ".svg"))); + $ilCtrl->setParameter($this->parent_obj, $this->folder_par, $this->current_folder); + break; + + case "pg": + if ($this->getMode() == ilMediaPoolTableGUI::IL_MEP_SELECT || + $this->getMode() == ilMediaPoolTableGUI::IL_MEP_SELECT_SINGLE) { + $this->tpl->setVariable("TXT_NO_LINK_TITLE", $a_set["title"]); + } else { + $this->tpl->setVariable("ONCLICK", "il.MediaPool.preview('" . $a_set["child"] . "'); return false;"); + $this->tpl->setVariable("TXT_TITLE", $a_set["title"]); + $ilCtrl->setParameterByClass("ilobjmediapoolgui", "mepitem_id", $a_set["child"]); + } + + if ($ilAccess->checkAccess("write", "", $this->media_pool->getRefId()) && + $this->getMode() == ilMediaPoolTableGUI::IL_MEP_EDIT) { + $this->tpl->setCurrentBlock("edit"); + $this->tpl->setVariable("TXT_EDIT", $lng->txt("edit")); + $ilCtrl->setParameterByClass("ilmediapoolpagegui", "mepitem_id", $a_set["child"]); + $this->tpl->setVariable( + "EDIT_LINK", + $ilCtrl->getLinkTargetByClass("ilmediapoolpagegui", "edit") + ); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setCurrentBlock("tbl_content"); + $this->tpl->setVariable("IMG", ilUtil::img(ilUtil::getImagePath("icon_pg.svg"))); + $ilCtrl->setParameter($this->parent_obj, $this->folder_par, $this->current_folder); + break; + + case "mob": + $this->tpl->setVariable("ONCLICK", "il.MediaPool.preview('" . $a_set["child"] . "'); return false;"); + $this->tpl->setVariable("TXT_TITLE", $a_set["title"]); + $ilCtrl->setParameterByClass("ilobjmediaobjectgui", "mepitem_id", $a_set["child"]); + $ilCtrl->setParameter($this->parent_obj, "mob_id", $a_set["foreign_id"]); + + // edit link + if ($ilAccess->checkAccess("write", "", $this->media_pool->getRefId()) && + $this->getMode() == ilMediaPoolTableGUI::IL_MEP_EDIT) { + $this->tpl->setCurrentBlock("edit"); + $this->tpl->setVariable("TXT_EDIT", $lng->txt("edit")); + $this->tpl->setVariable( + "EDIT_LINK", + $ilCtrl->getLinkTargetByClass("ilobjmediaobjectgui", "edit") + ); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setCurrentBlock("link"); + $this->tpl->setCurrentBlock("tbl_content"); + + // output thumbnail (or mob icon) + if (ilObject::_lookupType($a_set["foreign_id"]) == "mob") { + $mob = new ilObjMediaObject($a_set["foreign_id"]); + $med = $mob->getMediaItem("Standard"); + $target = ""; + if ($med) { + $target = $med->getThumbnailTarget(); + } + if ($target != "") { + $this->tpl->setVariable("IMG", ilUtil::img($target)); + } else { + $this->tpl->setVariable( + "IMG", + ilUtil::img(ilUtil::getImagePath("icon_" . $a_set["type"] . ".svg")) + ); + } + if ($med && ilUtil::deducibleSize($med->getFormat()) && + $med->getLocationType() == "Reference") { + $size = @getimagesize($med->getLocation()); + if ($size[0] > 0 && $size[1] > 0) { + $wr = $size[0] / 80; + $hr = $size[1] / 80; + $r = max($wr, $hr); + $w = (int) ($size[0]/$r); + $h = (int) ($size[1]/$r); + $this->tpl->setVariable( + "IMG", + ilUtil::img($med->getLocation(), "", $w, $h) + ); + } + } + + // output media info + include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); + $this->tpl->setVariable( + "MEDIA_INFO", + ilObjMediaObjectGUI::_getMediaInfoHTML($mob) + ); + $ilCtrl->setParameter($this->parent_obj, $this->folder_par, $this->current_folder); + } + break; + } + + if ($ilAccess->checkAccess("write", "", $this->media_pool->getRefId())) { + if (( + $this->getMode() == ilMediaPoolTableGUI::IL_MEP_EDIT || + ($this->getMode() == ilMediaPoolTableGUI::IL_MEP_SELECT && $a_set["type"] == "mob") || + ($this->getMode() == ilMediaPoolTableGUI::IL_MEP_SELECT_CONTENT && $a_set["type"] == "pg") + )) { + $this->tpl->setCurrentBlock("chbox"); + $this->tpl->setVariable("CHECKBOX_ID", $a_set["child"]); + $this->tpl->parseCurrentBlock(); + $this->tpl->setCurrentBlock("tbl_content"); + } elseif ($this->getMode() == ilMediaPoolTableGUI::IL_MEP_SELECT_SINGLE && $a_set["type"] == "mob") { + $this->tpl->setCurrentBlock("radio"); + $this->tpl->setVariable("RADIO_ID", $a_set["child"]); + $this->tpl->parseCurrentBlock(); + $this->tpl->setCurrentBlock("tbl_content"); + } + } + } + + /** + * get HTML + * + * @param + * @return + */ + public function render() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $mtpl = new ilTemplate("tpl.media_sel_table.html", true, true, "Modules/MediaPool"); + + $pre = ""; + if ($this->current_folder != $this->tree->getRootId() && !$this->all_objects) { + $path = $this->tree->getPathFull($this->current_folder); + + include_once("./Services/Locator/classes/class.ilLocatorGUI.php"); + $loc = new ilLocatorGUI(); + foreach ($path as $p) { + $ilCtrl->setParameter($this->parent_obj, $this->folder_par, $p["child"]); + $title = $p["title"]; + if ($this->tree->getRootId() == $p["child"]) { + $title = ilObject::_lookupTitle($this->media_pool->getId()); + } + $loc->addItem( + $title, + $ilCtrl->getLinkTarget($this->parent_obj, $this->parent_cmd) + ); + } + $ilCtrl->setParameter( + $this->parent_obj, + $this->folder_par, + $this->current_folder + ); + + $mtpl->setCurrentBlock("loc"); + $mtpl->setVariable("LOC", $loc->getHTML()); + $mtpl->parseCurrentBlock(); + } + + $mtpl->setVariable("TABLE", parent::render()); + + return $mtpl->get(); + } } -?> diff --git a/Modules/MediaPool/classes/class.ilMepMultiSrt.php b/Modules/MediaPool/classes/class.ilMepMultiSrt.php index 55e520c1ab7a3c829094dddcc4b012b9c816b5fd..d28b07ea159e433208eb8b77f9d10bcf98fabc84 100644 --- a/Modules/MediaPool/classes/class.ilMepMultiSrt.php +++ b/Modules/MediaPool/classes/class.ilMepMultiSrt.php @@ -13,48 +13,44 @@ include_once("./Services/MediaObjects/interfaces/interface.ilMobMultiSrtInt.php" */ class ilMepMultiSrt implements ilMobMultiSrtInt { - - function __construct($a_mep) - { - $this->mep = $a_mep; - } - - /** - * Get directory for multi srt upload - * - * @return string diretory - */ - function getUploadDir() - { - return ilUtil::getDataDir()."/mep_data". - "/mep_".$this->mep->getId()."/srt_tmp"; - } - - /** - * - * - * @param - * @return - */ - function getMobIds() - { - $mobs = array(); - - foreach (ilObjMediaPool::getAllMobIds($this->mep->getId()) as $id) - { - $mobs[$id] = $id; - } - $pages = ilMediaPoolItem::getIdsForType($this->mep->getId(), "pg"); - foreach ($pages as $p) - { - // all media objects - $pg_mobs = ilObjMediaObject::_getMobsOfObject("mep:pg", $p, 0, ""); - foreach ($pg_mobs as $k => $pg_mob) - { - $mobs[$k] = $pg_mob; - } - } - - return $mobs; - } -} \ No newline at end of file + public function __construct($a_mep) + { + $this->mep = $a_mep; + } + + /** + * Get directory for multi srt upload + * + * @return string diretory + */ + public function getUploadDir() + { + return ilUtil::getDataDir() . "/mep_data" . + "/mep_" . $this->mep->getId() . "/srt_tmp"; + } + + /** + * + * + * @param + * @return + */ + public function getMobIds() + { + $mobs = array(); + + foreach (ilObjMediaPool::getAllMobIds($this->mep->getId()) as $id) { + $mobs[$id] = $id; + } + $pages = ilMediaPoolItem::getIdsForType($this->mep->getId(), "pg"); + foreach ($pages as $p) { + // all media objects + $pg_mobs = ilObjMediaObject::_getMobsOfObject("mep:pg", $p, 0, ""); + foreach ($pg_mobs as $k => $pg_mob) { + $mobs[$k] = $pg_mob; + } + } + + return $mobs; + } +} diff --git a/Modules/MediaPool/classes/class.ilObjMediaPool.php b/Modules/MediaPool/classes/class.ilObjMediaPool.php index 44c1b3c20bb47bfc141ab09d7020d023e7f350bf..67bfe22e1737037ee3122e8766cab50fcc81e722 100755 --- a/Modules/MediaPool/classes/class.ilObjMediaPool.php +++ b/Modules/MediaPool/classes/class.ilObjMediaPool.php @@ -20,677 +20,636 @@ require_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); */ class ilObjMediaPool extends ilObject { - protected $mep_tree; - var $for_translation = 0; - - /** - * Constructor - * @access public - * @param integer reference_id or object_id - * @param boolean treat the id as reference_id (true) or object_id (false) - */ - function __construct($a_id = 0,$a_call_by_reference = true) - { - global $DIC; - - $this->db = $DIC->database(); - $this->lng = $DIC->language(); - // this also calls read() method! (if $a_id is set) - $this->type = "mep"; - parent::__construct($a_id,$a_call_by_reference); - } - - /** - * Set default width - * - * @param int default width - */ - function setDefaultWidth($a_val) - { - $this->default_width = $a_val; - } - - /** - * Get default width - * - * @return int default width - */ - function getDefaultWidth() - { - return $this->default_width; - } - - /** - * Set default height - * - * @param int default height - */ - function setDefaultHeight($a_val) - { - $this->default_height = $a_val; - } - - /** - * Get default height - * - * @return int default height - */ - function getDefaultHeight() - { - return $this->default_height; - } - - /** - * Set for translation - * - * @param bool $a_val lm has been imported for translation purposes - */ - function setForTranslation($a_val) - { - $this->for_translation = $a_val; - } - - /** - * Get for translation - * - * @return bool lm has been imported for translation purposes - */ - function getForTranslation() - { - return $this->for_translation; - } - - /** - * Read pool data - */ - function read() - { - $ilDB = $this->db; - - parent::read(); - - $set = $ilDB->query("SELECT * FROM mep_data ". - " WHERE id = ".$ilDB->quote($this->getId(), "integer") - ); - if ($rec = $ilDB->fetchAssoc($set)) - { - $this->setDefaultWidth($rec["default_width"]); - $this->setDefaultHeight($rec["default_height"]); - $this->setForTranslation($rec["for_translation"]); - } - $this->mep_tree = ilObjMediaPool::_getPoolTree($this->getId()); - } - - - /** - * Get Pool Tree - * - * @param int Media pool ID - * - * @return object Tree object of media pool - */ - static function _getPoolTree($a_obj_id) - { - $tree = new ilTree($a_obj_id); - $tree->setTreeTablePK("mep_id"); - $tree->setTableNames("mep_tree", "mep_item"); - - return $tree; - } - - /** - * Get pool tree - * - * @return object - */ - function getPoolTree() - { - return self::_getPoolTree($this->getId()); - } - - - /** - * create new media pool - */ - function create() - { - $ilDB = $this->db; - - parent::create(); - - $ilDB->manipulate("INSERT INTO mep_data ". - "(id, default_width, default_height, for_translation) VALUES (". - $ilDB->quote($this->getId(), "integer").", ". - $ilDB->quote($this->getDefaultWidth(), "integer").", ". - $ilDB->quote($this->getDefaultHeight(), "integer").", ". - $ilDB->quote($this->getForTranslation(), "integer"). - ")"); - - $this->createMepTree(); - } - - /** - * Create media pool tree - * - * @param - * @return - */ - function createMepTree() - { - // create media pool tree - $this->mep_tree = new ilTree($this->getId()); - $this->mep_tree->setTreeTablePK("mep_id"); - $this->mep_tree->setTableNames('mep_tree','mep_item'); - $this->mep_tree->addTree($this->getId(), 1); - } - - - /** - * get media pool folder tree - */ - function &getTree() - { - return $this->mep_tree; - } - - /** - * update object data - * - * @access public - * @return boolean - */ - function update() - { - $ilDB = $this->db; - - if (!parent::update()) - { - return false; - } - - // put here object specific stuff - $ilDB->manipulate("UPDATE mep_data SET ". - " default_width = ".$ilDB->quote($this->getDefaultWidth(), "integer").",". - " default_height = ".$ilDB->quote($this->getDefaultHeight(), "integer").",". - " for_translation = ".$ilDB->quote($this->getForTranslation(), "integer")." ". - " WHERE id = ".$ilDB->quote($this->getId(), "integer") - ); - - return true; - } - - - /** - * delete object and all related data - * - * this method has been tested on may 9th 2004 - * media pool tree, media objects and folders - * have been deleted correctly as desired - * - * @access public - * @return boolean true if all object data were removed; false if only a references were removed - */ - function delete() - { - // always call parent delete function first!! - if (!parent::delete()) - { - return false; - } - - // get childs - $childs = $this->mep_tree->getSubTree($this->mep_tree->getNodeData($this->mep_tree->readRootId())); - - // delete tree - $this->mep_tree->removeTree($this->mep_tree->getTreeId()); - - // delete childs - foreach ($childs as $child) - { - $fid = ilMediaPoolItem::lookupForeignId($child["obj_id"]); - switch ($child["type"]) - { - case "mob": - if (ilObject::_lookupType($fid) == "mob") - { - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $mob = new ilObjMediaObject($fid); - $mob->delete(); - } - break; - } - } - - return true; - } - - /** - * get childs of node - */ - function getChilds($obj_id = "", $a_type = "") - { - $objs = array(); - $mobs = array(); - $pgs = array(); - if ($obj_id == "") - { - $obj_id = $this->mep_tree->getRootId(); - } - - if ($a_type == "fold" || $a_type == "") - { - $objs = $this->mep_tree->getChildsByType($obj_id, "fold"); - } - if ($a_type == "mob" || $a_type == "") - { - $mobs = $this->mep_tree->getChildsByType($obj_id, "mob"); - } - foreach($mobs as $key => $mob) - { - $objs[] = $mob; - } - if ($a_type == "pg" || $a_type == "") - { - $pgs = $this->mep_tree->getChildsByType($obj_id, "pg"); - } - foreach($pgs as $key => $pg) - { - $objs[] = $pg; - } - - return $objs; - } - - /** - * get childs of node - */ - function getChildsExceptFolders($obj_id = "") - { - if ($obj_id == "") - { - $obj_id = $this->mep_tree->getRootId(); - } - - $objs = $this->mep_tree->getFilteredChilds(array("fold", "dummy"), $obj_id); - return $objs; - } - - /** - * Get media objects - */ - function getMediaObjects($a_title_filter = "", $a_format_filter = "", $a_keyword_filter = '', $a_caption_filter) - { - $ilDB = $this->db; - - $query = "SELECT DISTINCT mep_tree.*, object_data.* ". - "FROM mep_tree JOIN mep_item ON (mep_tree.child = mep_item.obj_id) ". - " JOIN object_data ON (mep_item.foreign_id = object_data.obj_id) "; - - if ($a_format_filter != "" or $a_caption_filter != '') - { - $query.= " JOIN media_item ON (media_item.mob_id = object_data.obj_id) "; - } - - $query .= - " WHERE mep_tree.mep_id = ".$ilDB->quote($this->getId(), "integer"). - " AND object_data.type = ".$ilDB->quote("mob", "text"); - - // filter - if (trim($a_title_filter) != "") // title - { - $query.= " AND ".$ilDB->like("object_data.title", "text", "%".trim($a_title_filter)."%"); - } - if ($a_format_filter != "") // format - { - $filter = ($a_format_filter == "unknown") - ? "" - : $a_format_filter; - $query.= " AND ".$ilDB->equals("media_item.format", $filter, "text", true); - } - if(trim($a_caption_filter)) - { - $query .= 'AND '.$ilDB->like('media_item.caption', 'text', '%'.trim($a_caption_filter).'%'); - } - - $query.= - " ORDER BY object_data.title"; - - $objs = array(); - $set = $ilDB->query($query); - while ($rec = $ilDB->fetchAssoc($set)) - { - $rec["foreign_id"] = $rec["obj_id"]; - $rec["obj_id"] = ""; - $objs[] = $rec; - } - - // Keyword filter - if($a_keyword_filter) - { - include_once './Services/MetaData/classes/class.ilMDKeyword.php'; - $res = ilMDKeyword::_searchKeywords($a_keyword_filter,'mob',0); - - foreach($objs as $obj) - { - if(in_array($obj['foreign_id'],$res)) - { - $filtered[] = $obj; - } - } - return (array) $filtered; - } - return $objs; - } - - - /** - * @param int $a_id of the media pool - * @return array of obj_id's (int) of media objects - */ - public static function getAllMobIds($a_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT foreign_id as id FROM ". - " mep_tree JOIN mep_item ON (mep_tree.child = mep_item.obj_id) ". - " JOIN object_data ON (mep_item.foreign_id = object_data.obj_id) ". - " WHERE mep_tree.mep_id = ".$ilDB->quote($a_id, "integer"). - " AND mep_item.type = ".$ilDB->quote("mob", "text"). - " AND object_data.type = ".$ilDB->quote("mob", "text"); - $set = $ilDB->query($query); - $ids = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $ids[] = $rec["id"]; - } - return $ids; - } - - /** - * Get used formats - */ - function getUsedFormats() - { - $ilDB = $this->db; - $lng = $this->lng; - - $query = "SELECT DISTINCT media_item.format f FROM mep_tree ". - " JOIN mep_item ON (mep_item.obj_id = mep_tree.child) ". - " JOIN object_data ON (mep_item.foreign_id = object_data.obj_id) ". - " JOIN media_item ON (media_item.mob_id = object_data.obj_id) ". - " WHERE mep_tree.mep_id = ".$ilDB->quote($this->getId(), "integer"). - " AND object_data.type = ".$ilDB->quote("mob", "text"). - " ORDER BY f"; - $formats = array(); - $set = $ilDB->query($query); - while ($rec = $ilDB->fetchAssoc($set)) - { - if ($rec["f"] != "") - { - $formats[$rec["f"]] = $rec["f"]; - } - else - { - $formats["unknown"] = $lng->txt("mep_unknown"); - } - } - - return $formats; - } - - function getParentId($obj_id = "") - { - if ($obj_id == "") - { - return false; - } - if ($obj_id == $this->mep_tree->getRootId()) - { - return false; - } - - return $this->mep_tree->getParentId($obj_id); - } - - /** - * Insert into tree - * @param int $a_obj_id (mep_item obj_id) - * @param int $a_parent - */ - function insertInTree($a_obj_id, $a_parent = "") - { - if (!$this->mep_tree->isInTree($a_obj_id)) - { - $parent = ($a_parent == "") - ? $this->mep_tree->getRootId() - : $a_parent; - $this->mep_tree->insertNode($a_obj_id, $parent); - return true; - } - else - { - return false; - } - } - - - /** - * Delete a child of media tree - * @param int mep_item id - */ - function deleteChild($obj_id) - { - $node_data = $this->mep_tree->getNodeData($obj_id); - $subtree = $this->mep_tree->getSubtree($node_data); - - // delete tree - if($this->mep_tree->isInTree($obj_id)) - { - $this->mep_tree->deleteTree($node_data); - } - - // delete objects - foreach ($subtree as $node) - { - $fid = ilMediaPoolItem::lookupForeignId($node["child"]); - if ($node["type"] == "mob") - { - if (ilObject::_lookupType($fid) == "mob") - { - $obj = new ilObjMediaObject($fid); - $obj->delete(); - } - } - - if ($node["type"] == "fold") - { - if ($fid > 0 && ilObject::_lookupType($fid) == "fold") - { - $obj = new ilObjFolder($fid, false); - $obj->delete(); - } - } - - if ($node["type"] == "pg") - { - include_once("./Modules/MediaPool/classes/class.ilMediaPoolPage.php"); - if (ilPageObject::_exists("mep", $node["child"])) - { - $pg = new ilMediaPoolPage($node["child"]); - $pg->delete(); - } - } - - include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); - $item = new ilMediaPoolItem($node["child"]); - $item->delete(); - } - } - - /** - * Check whether foreign id is in tree - * - * @param - * @return - */ - static function isForeignIdInTree($a_pool_id, $a_foreign_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT * FROM mep_tree JOIN mep_item ON (child = obj_id) WHERE ". - " foreign_id = ".$ilDB->quote($a_foreign_id, "integer"). - " AND mep_id = ".$ilDB->quote($a_pool_id, "integer") - ); - if ($rec = $ilDB->fetchAssoc($set)) - { - return true; - } - return false; - } - - /** - * Check wheter a mep item id is in the media pool - */ - static function isItemIdInTree($a_pool_id, $a_item_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT * FROM mep_tree WHERE child = ". - $ilDB->quote($a_item_id, "integer"). - " AND mep_id = ".$ilDB->quote($a_pool_id, "integer")); - if ($rec = $ilDB->fetchAssoc($set)) - { - return true; - } - return false; - } - - /** - * Create a new folder - * - * @param - * @return - */ - function createFolder($a_title, $a_parent = 0) - { - // perform save - $mep_item = new ilMediaPoolItem(); - $mep_item->setTitle($a_title); - $mep_item->setType("fold"); - $mep_item->create(); - if ($mep_item->getId() > 0) - { - $tree = $this->getTree(); - $parent = $a_parent > 0 - ? $a_parent - : $tree->getRootId(); - $this->insertInTree($mep_item->getId(), $parent); - return $mep_item->getId(); - } - return false; - } - - /** - * Clone media pool - * - * @param int target ref_id - * @param int copy id - */ - public function cloneObject($a_target_id,$a_copy_id = 0, $a_omit_tree = false) - { - $new_obj = parent::cloneObject($a_target_id,$a_copy_id, $a_omit_tree); - - $new_obj->setTitle($this->getTitle()); - $new_obj->setDescription($this->getDescription()); - $new_obj->setDefaultWidth($this->getDefaultWidth()); - $new_obj->setDefaultHeight($this->getDefaultHeight()); - $new_obj->update(); - - // copy content - $this->copyTreeContent($new_obj, $new_obj->getTree()->readRootId(), - $this->getTree()->readRootId()); - - return $new_obj; - } - - /** - * Copy tree content - * - * @param - * @return - */ - function copyTreeContent($a_new_obj, $a_target_parent, $a_source_parent) - { - include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); - include_once("./Modules/MediaPool/classes/class.ilMediaPoolPage.php"); - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - - // get all chapters of root lm - $nodes = $this->getTree()->getChilds($a_source_parent); - foreach ($nodes as $node) - { - $item = new ilMediaPoolItem(); - $item->setType($node["type"]); - switch ($node["type"]) - { - case "mob": - $mob_id = ilMediaPoolItem::lookupForeignId($node["child"]); - $mob = new ilObjMediaObject($mob_id); - $new_mob = $mob->duplicate(); - $item->setForeignId($new_mob->getId()); - $item->setTitle($new_mob->getTitle()); - $item->create(); - break; - - case "pg": - $item->setTitle($node["title"]); - $item->create(); - $page = new ilMediaPoolPage($node["child"]); - $new_page = new ilMediaPoolPage(); - $new_page->setParentId($a_new_obj->getId()); - $new_page->setId($item->getId()); - $new_page->create(); - - // copy page - $page->copy($new_page->getId(), $new_page->getParentType(), $new_page->getParentId(), true); - break; - - case "fold": - $item->setTitle($node["title"]); - $item->create(); - break; - } - - // insert item into tree - $a_new_obj->insertInTree($item->getId(), $a_target_parent); - - // handle childs - $this->copyTreeContent($a_new_obj, $item->getId(), $node["child"]); - } - } - - /** - * Export - * - * @param - */ - function exportXML($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/MediaPool"); - $conf->setMasterLanguageOnly(true, ($a_mode == "master")); - $exp->exportObject($this->getType(),$this->getId(), "4.4.0"); - } - } - + protected $mep_tree; + public $for_translation = 0; + + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + global $DIC; + + $this->db = $DIC->database(); + $this->lng = $DIC->language(); + // this also calls read() method! (if $a_id is set) + $this->type = "mep"; + parent::__construct($a_id, $a_call_by_reference); + } + + /** + * Set default width + * + * @param int default width + */ + public function setDefaultWidth($a_val) + { + $this->default_width = $a_val; + } + + /** + * Get default width + * + * @return int default width + */ + public function getDefaultWidth() + { + return $this->default_width; + } + + /** + * Set default height + * + * @param int default height + */ + public function setDefaultHeight($a_val) + { + $this->default_height = $a_val; + } + + /** + * Get default height + * + * @return int default height + */ + public function getDefaultHeight() + { + return $this->default_height; + } + + /** + * Set for translation + * + * @param bool $a_val lm has been imported for translation purposes + */ + public function setForTranslation($a_val) + { + $this->for_translation = $a_val; + } + + /** + * Get for translation + * + * @return bool lm has been imported for translation purposes + */ + public function getForTranslation() + { + return $this->for_translation; + } + + /** + * Read pool data + */ + public function read() + { + $ilDB = $this->db; + + parent::read(); + + $set = $ilDB->query( + "SELECT * FROM mep_data " . + " WHERE id = " . $ilDB->quote($this->getId(), "integer") + ); + if ($rec = $ilDB->fetchAssoc($set)) { + $this->setDefaultWidth($rec["default_width"]); + $this->setDefaultHeight($rec["default_height"]); + $this->setForTranslation($rec["for_translation"]); + } + $this->mep_tree = ilObjMediaPool::_getPoolTree($this->getId()); + } + + + /** + * Get Pool Tree + * + * @param int Media pool ID + * + * @return object Tree object of media pool + */ + public static function _getPoolTree($a_obj_id) + { + $tree = new ilTree($a_obj_id); + $tree->setTreeTablePK("mep_id"); + $tree->setTableNames("mep_tree", "mep_item"); + + return $tree; + } + + /** + * Get pool tree + * + * @return object + */ + public function getPoolTree() + { + return self::_getPoolTree($this->getId()); + } + + + /** + * create new media pool + */ + public function create() + { + $ilDB = $this->db; + + parent::create(); + + $ilDB->manipulate("INSERT INTO mep_data " . + "(id, default_width, default_height, for_translation) VALUES (" . + $ilDB->quote($this->getId(), "integer") . ", " . + $ilDB->quote($this->getDefaultWidth(), "integer") . ", " . + $ilDB->quote($this->getDefaultHeight(), "integer") . ", " . + $ilDB->quote($this->getForTranslation(), "integer") . + ")"); + + $this->createMepTree(); + } + + /** + * Create media pool tree + * + * @param + * @return + */ + public function createMepTree() + { + // create media pool tree + $this->mep_tree = new ilTree($this->getId()); + $this->mep_tree->setTreeTablePK("mep_id"); + $this->mep_tree->setTableNames('mep_tree', 'mep_item'); + $this->mep_tree->addTree($this->getId(), 1); + } + + + /** + * get media pool folder tree + */ + public function &getTree() + { + return $this->mep_tree; + } + + /** + * update object data + * + * @access public + * @return boolean + */ + public function update() + { + $ilDB = $this->db; + + if (!parent::update()) { + return false; + } + + // put here object specific stuff + $ilDB->manipulate( + "UPDATE mep_data SET " . + " default_width = " . $ilDB->quote($this->getDefaultWidth(), "integer") . "," . + " default_height = " . $ilDB->quote($this->getDefaultHeight(), "integer") . "," . + " for_translation = " . $ilDB->quote($this->getForTranslation(), "integer") . " " . + " WHERE id = " . $ilDB->quote($this->getId(), "integer") + ); + + return true; + } + + + /** + * delete object and all related data + * + * this method has been tested on may 9th 2004 + * media pool tree, media objects and folders + * have been deleted correctly as desired + * + * @access public + * @return boolean true if all object data were removed; false if only a references were removed + */ + public function delete() + { + // always call parent delete function first!! + if (!parent::delete()) { + return false; + } + + // get childs + $childs = $this->mep_tree->getSubTree($this->mep_tree->getNodeData($this->mep_tree->readRootId())); + + // delete tree + $this->mep_tree->removeTree($this->mep_tree->getTreeId()); + + // delete childs + foreach ($childs as $child) { + $fid = ilMediaPoolItem::lookupForeignId($child["obj_id"]); + switch ($child["type"]) { + case "mob": + if (ilObject::_lookupType($fid) == "mob") { + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $mob = new ilObjMediaObject($fid); + $mob->delete(); + } + break; + } + } + + return true; + } + + /** + * get childs of node + */ + public function getChilds($obj_id = "", $a_type = "") + { + $objs = array(); + $mobs = array(); + $pgs = array(); + if ($obj_id == "") { + $obj_id = $this->mep_tree->getRootId(); + } + + if ($a_type == "fold" || $a_type == "") { + $objs = $this->mep_tree->getChildsByType($obj_id, "fold"); + } + if ($a_type == "mob" || $a_type == "") { + $mobs = $this->mep_tree->getChildsByType($obj_id, "mob"); + } + foreach ($mobs as $key => $mob) { + $objs[] = $mob; + } + if ($a_type == "pg" || $a_type == "") { + $pgs = $this->mep_tree->getChildsByType($obj_id, "pg"); + } + foreach ($pgs as $key => $pg) { + $objs[] = $pg; + } + + return $objs; + } + + /** + * get childs of node + */ + public function getChildsExceptFolders($obj_id = "") + { + if ($obj_id == "") { + $obj_id = $this->mep_tree->getRootId(); + } + + $objs = $this->mep_tree->getFilteredChilds(array("fold", "dummy"), $obj_id); + return $objs; + } + + /** + * Get media objects + */ + public function getMediaObjects($a_title_filter = "", $a_format_filter = "", $a_keyword_filter = '', $a_caption_filter) + { + $ilDB = $this->db; + + $query = "SELECT DISTINCT mep_tree.*, object_data.* " . + "FROM mep_tree JOIN mep_item ON (mep_tree.child = mep_item.obj_id) " . + " JOIN object_data ON (mep_item.foreign_id = object_data.obj_id) "; + + if ($a_format_filter != "" or $a_caption_filter != '') { + $query.= " JOIN media_item ON (media_item.mob_id = object_data.obj_id) "; + } + + $query .= + " WHERE mep_tree.mep_id = " . $ilDB->quote($this->getId(), "integer") . + " AND object_data.type = " . $ilDB->quote("mob", "text"); + + // filter + if (trim($a_title_filter) != "") { // title + $query.= " AND " . $ilDB->like("object_data.title", "text", "%" . trim($a_title_filter) . "%"); + } + if ($a_format_filter != "") { // format + $filter = ($a_format_filter == "unknown") + ? "" + : $a_format_filter; + $query.= " AND " . $ilDB->equals("media_item.format", $filter, "text", true); + } + if (trim($a_caption_filter)) { + $query .= 'AND ' . $ilDB->like('media_item.caption', 'text', '%' . trim($a_caption_filter) . '%'); + } + + $query.= + " ORDER BY object_data.title"; + + $objs = array(); + $set = $ilDB->query($query); + while ($rec = $ilDB->fetchAssoc($set)) { + $rec["foreign_id"] = $rec["obj_id"]; + $rec["obj_id"] = ""; + $objs[] = $rec; + } + + // Keyword filter + if ($a_keyword_filter) { + include_once './Services/MetaData/classes/class.ilMDKeyword.php'; + $res = ilMDKeyword::_searchKeywords($a_keyword_filter, 'mob', 0); + + foreach ($objs as $obj) { + if (in_array($obj['foreign_id'], $res)) { + $filtered[] = $obj; + } + } + return (array) $filtered; + } + return $objs; + } + + + /** + * @param int $a_id of the media pool + * @return array of obj_id's (int) of media objects + */ + public static function getAllMobIds($a_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT foreign_id as id FROM " . + " mep_tree JOIN mep_item ON (mep_tree.child = mep_item.obj_id) " . + " JOIN object_data ON (mep_item.foreign_id = object_data.obj_id) " . + " WHERE mep_tree.mep_id = " . $ilDB->quote($a_id, "integer") . + " AND mep_item.type = " . $ilDB->quote("mob", "text") . + " AND object_data.type = " . $ilDB->quote("mob", "text"); + $set = $ilDB->query($query); + $ids = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $ids[] = $rec["id"]; + } + return $ids; + } + + /** + * Get used formats + */ + public function getUsedFormats() + { + $ilDB = $this->db; + $lng = $this->lng; + + $query = "SELECT DISTINCT media_item.format f FROM mep_tree " . + " JOIN mep_item ON (mep_item.obj_id = mep_tree.child) " . + " JOIN object_data ON (mep_item.foreign_id = object_data.obj_id) " . + " JOIN media_item ON (media_item.mob_id = object_data.obj_id) " . + " WHERE mep_tree.mep_id = " . $ilDB->quote($this->getId(), "integer") . + " AND object_data.type = " . $ilDB->quote("mob", "text") . + " ORDER BY f"; + $formats = array(); + $set = $ilDB->query($query); + while ($rec = $ilDB->fetchAssoc($set)) { + if ($rec["f"] != "") { + $formats[$rec["f"]] = $rec["f"]; + } else { + $formats["unknown"] = $lng->txt("mep_unknown"); + } + } + + return $formats; + } + + public function getParentId($obj_id = "") + { + if ($obj_id == "") { + return false; + } + if ($obj_id == $this->mep_tree->getRootId()) { + return false; + } + + return $this->mep_tree->getParentId($obj_id); + } + + /** + * Insert into tree + * @param int $a_obj_id (mep_item obj_id) + * @param int $a_parent + */ + public function insertInTree($a_obj_id, $a_parent = "") + { + if (!$this->mep_tree->isInTree($a_obj_id)) { + $parent = ($a_parent == "") + ? $this->mep_tree->getRootId() + : $a_parent; + $this->mep_tree->insertNode($a_obj_id, $parent); + return true; + } else { + return false; + } + } + + + /** + * Delete a child of media tree + * @param int mep_item id + */ + public function deleteChild($obj_id) + { + $node_data = $this->mep_tree->getNodeData($obj_id); + $subtree = $this->mep_tree->getSubtree($node_data); + + // delete tree + if ($this->mep_tree->isInTree($obj_id)) { + $this->mep_tree->deleteTree($node_data); + } + + // delete objects + foreach ($subtree as $node) { + $fid = ilMediaPoolItem::lookupForeignId($node["child"]); + if ($node["type"] == "mob") { + if (ilObject::_lookupType($fid) == "mob") { + $obj = new ilObjMediaObject($fid); + $obj->delete(); + } + } + + if ($node["type"] == "fold") { + if ($fid > 0 && ilObject::_lookupType($fid) == "fold") { + $obj = new ilObjFolder($fid, false); + $obj->delete(); + } + } + + if ($node["type"] == "pg") { + include_once("./Modules/MediaPool/classes/class.ilMediaPoolPage.php"); + if (ilPageObject::_exists("mep", $node["child"])) { + $pg = new ilMediaPoolPage($node["child"]); + $pg->delete(); + } + } + + include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); + $item = new ilMediaPoolItem($node["child"]); + $item->delete(); + } + } + + /** + * Check whether foreign id is in tree + * + * @param + * @return + */ + public static function isForeignIdInTree($a_pool_id, $a_foreign_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT * FROM mep_tree JOIN mep_item ON (child = obj_id) WHERE " . + " foreign_id = " . $ilDB->quote($a_foreign_id, "integer") . + " AND mep_id = " . $ilDB->quote($a_pool_id, "integer") + ); + if ($rec = $ilDB->fetchAssoc($set)) { + return true; + } + return false; + } + + /** + * Check wheter a mep item id is in the media pool + */ + public static function isItemIdInTree($a_pool_id, $a_item_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query("SELECT * FROM mep_tree WHERE child = " . + $ilDB->quote($a_item_id, "integer") . + " AND mep_id = " . $ilDB->quote($a_pool_id, "integer")); + if ($rec = $ilDB->fetchAssoc($set)) { + return true; + } + return false; + } + + /** + * Create a new folder + * + * @param + * @return + */ + public function createFolder($a_title, $a_parent = 0) + { + // perform save + $mep_item = new ilMediaPoolItem(); + $mep_item->setTitle($a_title); + $mep_item->setType("fold"); + $mep_item->create(); + if ($mep_item->getId() > 0) { + $tree = $this->getTree(); + $parent = $a_parent > 0 + ? $a_parent + : $tree->getRootId(); + $this->insertInTree($mep_item->getId(), $parent); + return $mep_item->getId(); + } + return false; + } + + /** + * Clone media pool + * + * @param int target ref_id + * @param int copy id + */ + public function cloneObject($a_target_id, $a_copy_id = 0, $a_omit_tree = false) + { + $new_obj = parent::cloneObject($a_target_id, $a_copy_id, $a_omit_tree); + + $new_obj->setTitle($this->getTitle()); + $new_obj->setDescription($this->getDescription()); + $new_obj->setDefaultWidth($this->getDefaultWidth()); + $new_obj->setDefaultHeight($this->getDefaultHeight()); + $new_obj->update(); + + // copy content + $this->copyTreeContent( + $new_obj, + $new_obj->getTree()->readRootId(), + $this->getTree()->readRootId() + ); + + return $new_obj; + } + + /** + * Copy tree content + * + * @param + * @return + */ + public function copyTreeContent($a_new_obj, $a_target_parent, $a_source_parent) + { + include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); + include_once("./Modules/MediaPool/classes/class.ilMediaPoolPage.php"); + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + + // get all chapters of root lm + $nodes = $this->getTree()->getChilds($a_source_parent); + foreach ($nodes as $node) { + $item = new ilMediaPoolItem(); + $item->setType($node["type"]); + switch ($node["type"]) { + case "mob": + $mob_id = ilMediaPoolItem::lookupForeignId($node["child"]); + $mob = new ilObjMediaObject($mob_id); + $new_mob = $mob->duplicate(); + $item->setForeignId($new_mob->getId()); + $item->setTitle($new_mob->getTitle()); + $item->create(); + break; + + case "pg": + $item->setTitle($node["title"]); + $item->create(); + $page = new ilMediaPoolPage($node["child"]); + $new_page = new ilMediaPoolPage(); + $new_page->setParentId($a_new_obj->getId()); + $new_page->setId($item->getId()); + $new_page->create(); + + // copy page + $page->copy($new_page->getId(), $new_page->getParentType(), $new_page->getParentId(), true); + break; + + case "fold": + $item->setTitle($node["title"]); + $item->create(); + break; + } + + // insert item into tree + $a_new_obj->insertInTree($item->getId(), $a_target_parent); + + // handle childs + $this->copyTreeContent($a_new_obj, $item->getId(), $node["child"]); + } + } + + /** + * Export + * + * @param + */ + public function exportXML($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/MediaPool"); + $conf->setMasterLanguageOnly(true, ($a_mode == "master")); + $exp->exportObject($this->getType(), $this->getId(), "4.4.0"); + } + } } -?> \ No newline at end of file diff --git a/Modules/MediaPool/classes/class.ilObjMediaPoolAccess.php b/Modules/MediaPool/classes/class.ilObjMediaPoolAccess.php index 42c5ca50c886abbe8119c6c57ac4dca5f11769cd..0447b2872e4dc4cfc60687a6c1def7eaecd41e16 100644 --- a/Modules/MediaPool/classes/class.ilObjMediaPoolAccess.php +++ b/Modules/MediaPool/classes/class.ilObjMediaPoolAccess.php @@ -16,53 +16,48 @@ include_once("./Services/Object/classes/class.ilObjectAccess.php"); class ilObjMediaPoolAccess extends ilObjectAccess { - /** - * 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" => "", "lang_var" => "show", - "default" => true), - array("permission" => "write", "cmd" => "", "lang_var" => "edit_content", - "default" => false), - array("permission" => "write", "cmd" => "edit", "lang_var" => "settings", - "default" => false) - ); - - return $commands; - } - - - /** - * check whether goto script will succeed - */ - static function _checkGoto($a_target) - { - global $DIC; - - $ilAccess = $DIC->access(); - - $t_arr = explode("_", $a_target); - - if ($ilAccess->checkAccess("read", "", $t_arr[1]) || - $ilAccess->checkAccess("visible", "", $t_arr[1])) - { - return true; - } - return false; - } - + /** + * 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" => "", "lang_var" => "show", + "default" => true), + array("permission" => "write", "cmd" => "", "lang_var" => "edit_content", + "default" => false), + array("permission" => "write", "cmd" => "edit", "lang_var" => "settings", + "default" => false) + ); + + 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 ($ilAccess->checkAccess("read", "", $t_arr[1]) || + $ilAccess->checkAccess("visible", "", $t_arr[1])) { + return true; + } + return false; + } } - -?> diff --git a/Modules/MediaPool/classes/class.ilObjMediaPoolGUI.php b/Modules/MediaPool/classes/class.ilObjMediaPoolGUI.php index 186e52c87eb74a6c9977a07863619cbbccfdc9d4..bf914595a5ed53970bacc0d6a7d9b0cf0ecc2437 100755 --- a/Modules/MediaPool/classes/class.ilObjMediaPoolGUI.php +++ b/Modules/MediaPool/classes/class.ilObjMediaPoolGUI.php @@ -25,2192 +25,2191 @@ include_once("./Services/Clipboard/classes/class.ilEditClipboardGUI.php"); */ class ilObjMediaPoolGUI extends ilObject2GUI { - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * @var ilHelpGUI - */ - protected $help; - - /** - * @var ilTemplate - */ - protected $main_tpl; - - /** - * @var \ILIAS\FileUpload\FileUpload - */ - protected $upload; - - /** - * @var ilLogger - */ - protected $mep_log; - - /** - * Constructor - */ - function __construct($a_id = 0, $a_id_type = self::REPOSITORY_NODE_ID, $a_parent_node_id = 0) - { - global $DIC; - - parent::__construct($a_id, $a_id_type, $a_parent_node_id); - - $this->tabs = $DIC->tabs(); - $this->error = $DIC["ilErr"]; - $this->locator = $DIC["ilLocator"]; - $this->help = $DIC["ilHelp"]; - - $this->main_tpl = $DIC->ui()->mainTemplate(); - - $this->upload = $DIC->upload(); - - $this->mep_log = ilLoggerFactory::getLogger("mep"); - } - - var $output_prepared; - - /** - * Initialisation - */ - protected function afterConstructor() - { - $lng = $this->lng; - - $lng->loadLanguageModule("mep"); - - if ($this->ctrl->getCmd() == "explorer") - { - $this->ctrl->saveParameter($this, array("ref_id")); - } - else - { - $this->ctrl->saveParameter($this, array("ref_id", "mepitem_id")); - } - $this->ctrl->saveParameter($this, array("mep_mode")); - - $lng->loadLanguageModule("content"); - } - - /** - * Get type - */ - final function getType() - { - return "mep"; - } - - /** - * execute command - * - * @return bool|void - * @throws ilCtrlException - */ - function executeCommand() - { - $ilTabs = $this->tabs; - $lng = $this->lng; - $ilAccess = $this->access; - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - - if ($this->ctrl->getRedirectSource() == "ilinternallinkgui") - { - $this->explorer(); - return; - } - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - $new_type = $_POST["new_type"] - ? $_POST["new_type"] - : $_GET["new_type"]; - - if ($new_type != "" && ($cmd != "confirmRemove" && $cmd != "copyToClipboard" - && $cmd != "pasteFromClipboard")) - { - $this->setCreationMode(true); - } - - if (!$this->getCreationMode()) - { - $tree = $this->object->getTree(); - if ($_GET["mepitem_id"] == "") - { - $_GET["mepitem_id"] = $tree->getRootId(); - } - } - if ($cmd == "create") - { - switch($_POST["new_type"]) - { - case "mob": - $this->ctrl->redirectByClass("ilobjmediaobjectgui", "create"); - break; - - case "fold": - $this->ctrl->redirectByClass("ilobjfoldergui", "create"); - break; - } - } - - switch($next_class) - { - case 'ilobjectmetadatagui'; - $this->checkPermission("write"); - - $this->prepareOutput(); - $this->addHeaderAction(); - - $this->tabs_gui->activateTab('meta_data'); - include_once 'Services/Object/classes/class.ilObjectMetaDataGUI.php'; - $md_gui = new ilObjectMetaDataGUI($this->object, 'mob'); - $this->ctrl->forwardCommand($md_gui); - $this->tpl->show(); - break; - - - case 'ilmediapoolpagegui': - $this->checkPermission("write"); - $this->prepareOutput(); - $this->addHeaderAction(); - $ilTabs->clearTargets(); - include_once("./Modules/MediaPool/classes/class.ilMediaPoolPageGUI.php"); - $mep_page_gui = new ilMediaPoolPageGUI($_GET["mepitem_id"], $_GET["old_nr"]); - - if (!$ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - $mep_page_gui->setEnableEditing(false); - } - $ret = $this->ctrl->forwardCommand($mep_page_gui); - if ($ret != "") - { - $tpl->setContent($ret); - } - $this->setMediaPoolPageTabs(); - $this->tpl->show(); - break; - - case "ilobjmediaobjectgui": - $this->checkPermission("write"); - if ($cmd == "create" || $cmd == "save" || $cmd == "cancel") - { - $ret_obj = $_GET["mepitem_id"]; - $ilObjMediaObjectGUI = new ilObjMediaObjectGUI("", 0, false, false); - $ilObjMediaObjectGUI->setWidthPreset($this->object->getDefaultWidth()); - $ilObjMediaObjectGUI->setHeightPreset($this->object->getDefaultHeight()); - } - else - { - $ret_obj = $tree->getParentId($_GET["mepitem_id"]); - $ilObjMediaObjectGUI = new ilObjMediaObjectGUI("", ilMediaPoolItem::lookupForeignId($_GET["mepitem_id"]), false, false); - $this->ctrl->setParameter($this, "mepitem_id", $this->getParentFolderId()); - $ilTabs->setBackTarget($lng->txt("back"), - $this->ctrl->getLinkTarget($this, - $_GET["mep_mode"] ? $_GET["mep_mode"] : "listMedia")); - } - if ($this->ctrl->getCmdClass() == "ilinternallinkgui") - { - $this->ctrl->setReturn($this, "explorer"); - } - else - { - $this->ctrl->setParameter($this, "mepitem_id", $ret_obj); - $this->ctrl->setReturn($this, - $_GET["mep_mode"] ? $_GET["mep_mode"] : "listMedia"); - $this->ctrl->setParameter($this, "mepitem_id", $_GET["mepitem_id"]); - } - $this->getTemplate(); - $ilObjMediaObjectGUI->setTabs(); - $this->setLocator(); - - // set adv metadata record dobject - $ilObjMediaObjectGUI->setAdvMdRecordObject($this->object->getRefId(), "mep", "mob"); - - $ret = $this->ctrl->forwardCommand($ilObjMediaObjectGUI); - - if ($cmd == "save" && $ret != false) - { - $mep_item = new ilMediaPoolItem(); - $mep_item->setTitle($ret->getTitle()); - $mep_item->setType("mob"); - $mep_item->setForeignId($ret->getId()); - $mep_item->create(); - - $parent = ($_GET["mepitem_id"] == "") - ? $tree->getRootId() - : $_GET["mepitem_id"]; - $tree->insertNode($mep_item->getId(), $parent); - ilUtil::redirect("ilias.php?baseClass=ilMediaPoolPresentationGUI&cmd=listMedia&ref_id=". - $_GET["ref_id"]."&mepitem_id=".$_GET["mepitem_id"]); - } - else - { - $this->tpl->show(); - } - break; - - case "ilobjfoldergui": - $this->checkPermission("write"); - $this->addHeaderAction(); - $folder_gui = new ilObjFolderGUI("", 0, false, false); - $this->ctrl->setReturn($this, "listMedia"); - $cmd.="Object"; - switch($cmd) - { - case "createObject": - $this->prepareOutput(); - $folder_gui = new ilObjFolderGUI("", 0, false, false); - $folder_gui->setFormAction("save", - $this->ctrl->getFormActionByClass("ilobjfoldergui")); - $folder_gui->createObject(); - $this->tpl->show(); - break; - - case "saveObject": - //$folder_gui->setReturnLocation("save", $this->ctrl->getLinkTarget($this, "listMedia")); - $parent = ($_GET["mepitem_id"] == "") - ? $tree->getRootId() - : $_GET["mepitem_id"]; - $folder_gui->setFolderTree($tree); - $folder_gui->saveObject($parent); - //$this->ctrl->redirect($this, "listMedia"); - break; - - case "editObject": - $this->prepareOutput(); - $folder_gui = new ilObjFolderGUI("", ilMediaPoolItem::lookupForeignId($_GET["mepitem_id"]), false, false); - $this->ctrl->setParameter($this, "foldereditmode", "1"); - $folder_gui->setFormAction("update", $this->ctrl->getFormActionByClass("ilobjfoldergui")); - $folder_gui->editObject(); - $this->tpl->show(); - break; - - case "updateObject": - $folder_gui = new ilObjFolderGUI("", ilMediaPoolItem::lookupForeignId($_GET["mepitem_id"]), false, false); - $this->ctrl->setParameter($this, "mepitem_id", $this->getParentFolderId()); - $this->ctrl->setReturn($this, "listMedia"); - $folder_gui->updateObject(true); // this returns to parent - break; - - case "cancelObject": - if ($_GET["foldereditmode"]) - { - $this->ctrl->setParameter($this, "mepitem_id", $this->getParentFolderId()); - } - $this->ctrl->redirect($this, "listMedia"); - break; - } - break; - - case "ileditclipboardgui": - $this->prepareOutput(); - $this->addHeaderAction(); - $this->ctrl->setReturn($this, $_GET["mep_mode"] ? $_GET["mep_mode"] : "listMedia"); - $clip_gui = new ilEditClipboardGUI(); - $clip_gui->setMultipleSelections(true); - $clip_gui->setInsertButtonTitle($lng->txt("mep_copy_to_mep")); - $ilTabs->setTabActive("clipboard"); - $this->ctrl->forwardCommand($clip_gui); - $this->tpl->show(); - break; - - case 'ilinfoscreengui': - $this->prepareOutput(); - $this->addHeaderAction(); - $this->infoScreen(); - $this->tpl->show(); - break; - - case 'ilpermissiongui': - $this->checkPermission("edit_permission"); - $this->prepareOutput(); - $this->addHeaderAction(); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $this->ctrl->forwardCommand($perm_gui); - $this->tpl->show(); - break; - - case "ilexportgui": - $this->checkPermission("write"); - $this->prepareOutput(); - $this->addHeaderAction(); - include_once("./Services/Export/classes/class.ilExportGUI.php"); - $exp_gui = new ilExportGUI($this); - $exp_gui->addFormat("xml"); - include_once("./Services/Object/classes/class.ilObjectTranslation.php"); - $ot = ilObjectTranslation::getInstance($this->object->getId()); - if ($ot->getContentActivated()) - { - $exp_gui->addFormat("xml_master", "XML (".$lng->txt("mep_master_language_only").")", $this, "export"); - $exp_gui->addFormat("xml_masternomedia", "XML (".$lng->txt("mep_master_language_only_no_media").")", $this, "export"); - } - $this->ctrl->forwardCommand($exp_gui); - $this->tpl->show(); - break; - - case "ilfilesystemgui": - $this->checkPermission("write"); - $this->prepareOutput(); - $this->addHeaderAction(); - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTarget($this, "listMedia")); - $mset = new ilSetting("mobs"); - if (trim($mset->get("upload_dir")) != "") - { - include_once("./Services/FileSystem/classes/class.ilFileSystemGUI.php"); - $fs_gui = new ilFileSystemGUI($mset->get("upload_dir")); - $fs_gui->setPostDirPath(true); - $fs_gui->setTableId("mepud".$this->object->getId()); - $fs_gui->setAllowFileCreation(false); - $fs_gui->setAllowDirectoryCreation(false); - $fs_gui->clearCommands(); - $fs_gui->addCommand($this, "selectUploadDirFiles", $this->lng->txt("mep_sel_upload_dir_files"), - false, true); - $this->ctrl->forwardCommand($fs_gui); - } - $this->tpl->show(); - break; - - case "ilcommonactiondispatchergui": - include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); - $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); - $this->ctrl->forwardCommand($gui); - break; - - case 'ilobjecttranslationgui': - $this->prepareOutput(); - $this->addHeaderAction(); - //$this->setTabs("settings"); - $ilTabs->activateTab("settings"); - $this->setSettingsSubTabs("obj_multilinguality"); - include_once("./Services/Object/classes/class.ilObjectTranslationGUI.php"); - $transgui = new ilObjectTranslationGUI($this); - $transgui->setTitleDescrOnlyMode(false); - $this->ctrl->forwardCommand($transgui); - $this->tpl->show(); - break; - - case "ilmediapoolimportgui": - $this->prepareOutput(); - $this->addHeaderAction(); - $ilTabs->activateTab("import"); - include_once("./Modules/MediaPool/classes/class.ilMediaPoolImportGUI.php"); - $gui = new ilMediaPoolImportGUI($this->object); - $this->ctrl->forwardCommand($gui); - $this->tpl->show(); - break; - - case "ilmobmultisrtuploadgui": - $this->checkPermission("write"); - $this->prepareOutput(); - $this->addHeaderAction(); - //$this->setTabs("content"); - $this->setContentSubTabs("srt_files"); - include_once("./Services/MediaObjects/classes/class.ilMobMultiSrtUploadGUI.php"); - include_once("./Modules/MediaPool/classes/class.ilMepMultiSrt.php"); - $gui = new ilMobMultiSrtUploadGUI(new ilMepMultiSrt($this->object)); - $this->ctrl->forwardCommand($gui); - $this->tpl->show(); - break; - - - default: - $this->prepareOutput(); - $this->addHeaderAction(); - $cmd = $this->ctrl->getCmd("listMedia"); - $this->$cmd(); - if (!$this->getCreationMode()) - { - $this->tpl->show(); - } - break; - } - } - - /** - * obsolete? - */ - function createMediaObject() - { - $this->ctrl->redirectByClass("ilobjmediaobjectgui", "create"); - } - - protected function initCreationForms($a_new_type) - { - $forms = array(self::CFORM_NEW => $this->initCreateForm($a_new_type), - self::CFORM_IMPORT => $this->initImportForm($a_new_type)); - - return $forms; - } - - /** - * save object - */ - function afterSave(ilObject $newObj) - { - // always send a message - ilUtil::sendSuccess($this->lng->txt("object_added"),true); - - //ilUtil::redirect($this->getReturnLocation("save","adm_object.php?".$this->link_params)); - ilUtil::redirect("ilias.php?baseClass=ilMediaPoolPresentationGUI&ref_id=".$newObj->getRefId()."&cmd=listMedia"); - } - - protected function initEditCustomForm(ilPropertyFormGUI $a_form) - { - $obj_service = $this->object_service; - - // default width - $ni = new ilNumberInputGUI($this->lng->txt("mep_default_width"), "default_width"); - $ni->setMinValue(0); - $ni->setSuffix("px"); - $ni->setMaxLength(5); - $ni->setSize(5); - $a_form->addItem($ni); - - // default height - $ni = new ilNumberInputGUI($this->lng->txt("mep_default_height"), "default_height"); - $ni->setSuffix("px"); - $ni->setMinValue(0); - $ni->setMaxLength(5); - $ni->setSize(5); - $ni->setInfo($this->lng->txt("mep_default_width_height_info")); - $a_form->addItem($ni); - - // presentation - $pres = new ilFormSectionHeaderGUI(); - $pres->setTitle($this->lng->txt('obj_presentation')); - $a_form->addItem($pres); - - // tile image - $obj_service->commonSettings()->legacyForm($a_form, $this->object)->addTileImage(); - - // additional features - $feat = new ilFormSectionHeaderGUI(); - $feat->setTitle($this->lng->txt('obj_features')); - $a_form->addItem($feat); - - include_once './Services/Container/classes/class.ilContainer.php'; - include_once './Services/Object/classes/class.ilObjectServiceSettingsGUI.php'; - ilObjectServiceSettingsGUI::initServiceSettingsForm( - $this->object->getId(), - $a_form, - array( - ilObjectServiceSettingsGUI::CUSTOM_METADATA - ) - ); - - } - - /** - * edit object - * - * @access public - */ - public function edit() - { - $tpl = $this->tpl; - $ilTabs = $this->tabs_gui; - $ilErr = $this->ilErr; - - $this->setSettingsSubTabs("settings"); - - if (!$this->checkPermissionBool("write")) - { - $ilErr->raiseError($this->lng->txt("msg_no_perm_write"),$ilErr->MESSAGE); - } - - $ilTabs->activateTab("settings"); - - $form = $this->initEditForm(); - $values = $this->getEditFormValues(); - if($values) - { - $form->setValuesByArray($values, true); - } - - $this->addExternalEditFormCustom($form); - - $tpl->setContent($form->getHTML()); - } - - - protected function getEditFormCustomValues(array &$a_values) - { - if ($this->object->getDefaultWidth() > 0) - { - $a_values["default_width"] = $this->object->getDefaultWidth(); - } - if ($this->object->getDefaultHeight() > 0) - { - $a_values["default_height"] = $this->object->getDefaultHeight(); - } - } - - protected function updateCustom(ilPropertyFormGUI $a_form) - { - $obj_service = $this->object_service; - - $this->object->setDefaultWidth($a_form->getInput("default_width")); - $this->object->setDefaultHeight($a_form->getInput("default_height")); - - - // additional features - include_once './Services/Object/classes/class.ilObjectServiceSettingsGUI.php'; - ilObjectServiceSettingsGUI::updateServiceSettingsForm( - $this->object->getId(), - $a_form, - array( - ilObjectServiceSettingsGUI::CUSTOM_METADATA - ) - ); - - // tile image - $obj_service->commonSettings()->legacyForm($a_form, $this->object)->saveTileImage(); - - } - - /** - * list media objects - */ - function listMedia() - { - $ilAccess = $this->access; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $ilToolbar = $this->toolbar; - $lng = $this->lng; - - $ilCtrl->setParameter($this, "mep_mode", "listMedia"); - - $this->checkPermission("read"); - - $ilTabs->setTabActive("content"); - $this->setContentSubTabs("content"); - - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - $ilToolbar->addButton($lng->txt("mep_create_mob"), - $ilCtrl->getLinkTarget($this, "createMediaObject")); - - $mset = new ilSetting("mobs"); - if ($mset->get("mep_activate_pages")) - { - $ilToolbar->addButton($lng->txt("mep_create_content_snippet"), - $ilCtrl->getLinkTarget($this, "createMediaPoolPage")); - } - - $ilToolbar->addButton($lng->txt("mep_create_folder"), - $ilCtrl->getLinkTarget($this, "createFolderForm")); - - if (trim($mset->get("upload_dir")) != "" && ilMainMenuGUI::_checkAdministrationPermission()) - { - $ilToolbar->addButton($lng->txt("mep_create_from_upload_dir"), - $ilCtrl->getLinkTargetByClass("ilfilesystemgui", "listFiles")); - } - - $ilToolbar->addButton($lng->txt("mep_bulk_upload"), - $ilCtrl->getLinkTarget($this, "bulkUpload")); - } - - // tree - include_once("./Modules/MediaPool/classes/class.ilMediaPoolExplorerGUI.php"); - $exp = new ilMediaPoolExplorerGUI($this, "listMedia", $this->object); - if (!$exp->handleCommand()) - { - $this->tpl->setLeftNavContent($exp->getHTML()); - } - else - { - return; - } - - include_once("./Modules/MediaPool/classes/class.ilMediaPoolTableGUI.php"); - $mep_table_gui = new ilMediaPoolTableGUI($this, "listMedia", $this->object, "mepitem_id"); - $tpl->setContent($mep_table_gui->getHTML()); - } - - /** - * list all objects - */ - function allMedia() - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - $ilCtrl->setParameter($this, "mep_mode", "allMedia"); - - $this->checkPermission("read"); - $ilTabs->setTabActive("content"); - $this->setContentSubTabs("mep_all_mobs"); - - - include_once("./Modules/MediaPool/classes/class.ilMediaPoolTableGUI.php"); - $mep_table_gui = new ilMediaPoolTableGUI($this, "allMedia", $this->object, - "mepitem_id", ilMediaPoolTableGUI::IL_MEP_EDIT, true); - - - if(isset($_GET['force_filter']) and $_GET['force_filter']) - { - $_POST['title'] = ilMediaPoolItem::lookupTitle((int) $_GET['force_filter']); - - include_once("./Services/Table/classes/class.ilTablePropertiesStorage.php"); - $tprop = new ilTablePropertiesStorage(); - $tprop->storeProperty( - $mep_table_gui->getId(), - $ilUser->getId(), - 'filter', - 1 - ); - $mep_table_gui->resetFilter(); - $mep_table_gui->resetOffset(); - $mep_table_gui->writeFilterToSession(); - - // Read again - $mep_table_gui = new ilMediaPoolTableGUI($this, "allMedia", $this->object, - "mepitem_id", ilMediaPoolTableGUI::IL_MEP_EDIT, true); - } - - $tpl->setContent($mep_table_gui->getHTML()); - } - - /** - * Apply filter - */ - function applyFilter() - { - include_once("./Modules/MediaPool/classes/class.ilMediaPoolTableGUI.php"); - $mtab = new ilMediaPoolTableGUI($this, "allMedia", $this->object, - "mepitem_id", ilMediaPoolTableGUI::IL_MEP_EDIT, true); - $mtab->writeFilterToSession(); - $mtab->resetOffset(); - $this->allMedia(); - } - - /** - * Reset filter - */ - function resetFilter() - { - include_once("./Modules/MediaPool/classes/class.ilMediaPoolTableGUI.php"); - $mtab = new ilMediaPoolTableGUI($this, "allMedia", $this->object, - "mepitem_id", ilMediaPoolTableGUI::IL_MEP_EDIT, true); - $mtab->resetFilter(); - $mtab->resetOffset(); - $this->allMedia(); - } - - /** - * Get standard template - */ - function getTemplate() - { - $this->tpl->getStandardTemplate(); - } - - - /** - * Get folder parent ID - */ - function getParentFolderId() - { - if ($_GET["mepitem_id"] == "") - { - return ""; - } - $par_id = $this->object->getPoolTree()->getParentId($_GET["mepitem_id"]); - if ($par_id != $this->object->getPoolTree()->getRootId()) - { - return $par_id; - } - else - { - return ""; - } - } - - /** - * show media object - */ - protected function showMedia() - { - $this->checkPermission("read"); - - $item = new ilMediaPoolItem((int) $_GET["mepitem_id"]); - $mob_id = $item->getForeignId(); - - $this->tpl = new ilTemplate("tpl.fullscreen.html", true, true, "Services/COPage"); - include_once("Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $this->tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath(0)); - - - require_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - require_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); - ilObjMediaObjectGUI::includePresentationJS($this->tpl); - $media_obj = new ilObjMediaObject((int) $mob_id); - - - $this->tpl->setVariable("TITLE", " - ".$media_obj->getTitle()); - - $xml = ""; - // todo: we get always the first alias now (problem if mob is used multiple - // times in page) - $xml.= $media_obj->getXML(IL_MODE_ALIAS); - $xml.= $media_obj->getXML(IL_MODE_OUTPUT); - $xml.= $link_xml; - $xml.=""; - - $xsl = file_get_contents("./Services/COPage/xsl/page.xsl"); - $args = array( '/_xml' => $xml, '/_xsl' => $xsl ); - $xh = xslt_create(); - - $wb_path = ilUtil::getWebspaceDir("output")."/"; - - $mode = ($_GET["cmd"] != "showPreview") - ? "fullscreen" - : "media"; - $enlarge_path = ilUtil::getImagePath("enlarge.svg", false, "output"); - $fullscreen_link = - $this->ctrl->getLinkTarget($this, "showFullscreen", "", false, false); - $params = array ('mode' => $mode, 'enlarge_path' => $enlarge_path, - 'link_params' => "ref_id=".$_GET["ref_id"],'fullscreen_link' => $fullscreen_link, - 'ref_id' => $_GET["ref_id"], 'pg_frame' => $pg_frame, 'webspace_path' => $wb_path); - $output = xslt_process($xh,"arg:/_xml","arg:/_xsl",NULL,$args, $params); - echo xslt_error($xh); - xslt_free($xh); - // unmask user html - $this->tpl->setVariable("MEDIA_CONTENT", $output); - } - - /** - * Show page - * - * @param - * @return - */ - function showPage() - { - $tpl = $this->tpl; - - $tpl = new ilTemplate("tpl.main.html", true, true); - - include_once("./Services/Container/classes/class.ilContainerPage.php"); - include_once("./Services/Container/classes/class.ilContainerPageGUI.php"); - - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); - $tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath(0)); - $tpl->setCurrentBlock("SyntaxStyle"); - $tpl->setVariable("LOCATION_SYNTAX_STYLESHEET", - ilObjStyleSheet::getSyntaxStylePath()); - $tpl->parseCurrentBlock(); - - // get page object - //include_once("./Services/Object/classes/class.ilObjectTranslation.php"); - //$ot = ilObjectTranslation::getInstance($this->object->getId()); - //$lang = $ot->getEffectiveContentLang($ilUser->getCurrentLanguage(), "cont"); - include_once("./Modules/MediaPool/classes/class.ilMediaPoolPageGUI.php"); - $page_gui = new ilMediaPoolPageGUI((int) $_GET["mepitem_id"]); - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - //$page_gui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId( - // $this->object->getStyleSheetId(), $this->object->getType())); - - $page_gui->setTemplateOutput(false); - $page_gui->setHeader(""); - $ret = $page_gui->showPage(true); - - $tpl->setBodyClass("ilMediaPoolPagePreviewBody"); - $tpl->setVariable("CONTENT", $ret); - //$ret = "
".$ret."
"; - - - $tpl->show(); - exit; - } - - - /** - * Show content snippet - */ - function showPreview() - { - $this->checkPermission("read"); - - $item = new ilMediaPoolItem((int) $_GET["mepitem_id"]); - - switch ($item->getType()) - { - case "mob": - $this->showMedia(); - break; - - case "pg": - $this->showPage(); - break; - } - } - - - /** - * show fullscreen - */ - function showFullscreen() - { - $this->showMedia(); - } - - /** - * confirm remove of mobs - */ - function confirmRemove() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilErr = $this->error; - - $this->checkPermission("write"); - - if(!isset($_POST["id"])) - { - $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); - } - - // display confirmation message - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($this->ctrl->getFormAction($this)); - $cgui->setHeaderText($this->lng->txt("info_remove_sure")); - $cgui->setCancel($this->lng->txt("cancel"), "cancelRemove"); - $cgui->setConfirm($this->lng->txt("confirm"), "remove"); - - foreach($_POST["id"] as $obj_id) - { - $type = ilMediaPoolItem::lookupType($obj_id); - $title = ilMediaPoolItem::lookupTitle($obj_id); - - // check whether page can be removed - $add = ""; - if ($type == "pg") - { - include_once("./Services/COPage/classes/class.ilPageContentUsage.php"); - $usages = ilPageContentUsage::getUsages("incl", $obj_id, false); - if (count($usages) > 0) - { - ilUtil::sendFailure(sprintf($lng->txt("mep_content_snippet_in_use"), $title), true); - $ilCtrl->redirect($this, "listMedia"); - } - else - { - // check whether the snippet is used in older versions of pages - $usages = ilPageContentUsage::getUsages("incl", $obj_id, true); - if (count($usages) > 0) - { - $add = "
".$lng->txt("mep_content_snippet_used_in_older_versions")."
"; - } - } - } - - $caption = ilUtil::getImageTagByType($type, $this->tpl->tplPath). - " ".$title.$add; - - $cgui->addItem("id[]", $obj_id, $caption); - } - - $this->tpl->setContent($cgui->getHTML()); - } - - /** - * paste from clipboard - */ - function openClipboard() - { - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - - $this->checkPermission("write"); - - $ilCtrl->setParameterByClass("ileditclipboardgui", "returnCommand", - rawurlencode($ilCtrl->getLinkTarget($this, - "insertFromClipboard", "", false, false))); - $ilCtrl->redirectByClass("ilEditClipboardGUI", "getObject"); - } - - - /** - * insert media object from clipboard - */ - function insertFromClipboard() - { - $ilAccess = $this->access; - - $this->checkPermission("write"); - - include_once("./Services/Clipboard/classes/class.ilEditClipboardGUI.php"); - $ids = ilEditClipboardGUI::_getSelectedIDs(); - $not_inserted = array(); - if (is_array($ids)) - { - foreach ($ids as $id2) - { - $id = explode(":", $id2); - $type = $id[0]; - $id = $id[1]; - - if ($type == "mob") // media object - { - if (ilObjMEdiaPool::isForeignIdInTree($this->object->getId(), $id)) - { - $not_inserted[] = ilObject::_lookupTitle($id)." [". - $id."]"; - } - else - { - $item = new ilMediaPoolItem(); - $item->setType("mob"); - $item->setForeignId($id); - $item->setTitle(ilObject::_lookupTitle($id)); - $item->create(); - if ($item->getId() > 0) - { - $this->object->insertInTree($item->getId(), $_GET["mepitem_id"]); - } - } - } - if ($type == "incl") // content snippet - { - include_once("./Modules/MediaPool/classes/class.ilMediaPoolPage.php"); - include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); - if (ilObjMEdiaPool::isItemIdInTree($this->object->getId(), $id)) - { - $not_inserted[] = ilMediaPoolPage::lookupTitle($id)." [". - $id."]"; - } - else - { - $original = new ilMediaPoolPage($id); - - // copy the page into the pool - $item = new ilMediaPoolItem(); - $item->setType("pg"); - $item->setTitle(ilMediaPoolItem::lookupTitle($id)); - $item->create(); - if ($item->getId() > 0) - { - $this->object->insertInTree($item->getId(), $_GET["mepitem_id"]); - - // create page - include_once("./Modules/MediaPool/classes/class.ilMediaPoolPage.php"); - $page = new ilMediaPoolPage(); - $page->setId($item->getId()); - $page->setParentId($this->object->getId()); - $page->create(); - - // copy content - $original->copy($page->getId(), $page->getParentType(), $page->getParentId(), true); - - } - } - } - } - } - if (count($not_inserted) > 0) - { - ilUtil::sendInfo($this->lng->txt("mep_not_insert_already_exist")."
". - implode($not_inserted,"
"), true); - } - $this->ctrl->redirect($this, $_GET["mep_mode"] ? $_GET["mep_mode"] : "listMedia"); - } - - - /** - * cancel deletion of media objects/folders - */ - function cancelRemove() - { - $this->ctrl->redirect($this, $_GET["mep_mode"] ? $_GET["mep_mode"] : "listMedia"); - } - - /** - * confirm deletion of - */ - function remove() - { - $ilAccess = $this->access; - - $this->checkPermission("write"); - - foreach($_POST["id"] as $obj_id) - { - $this->object->deleteChild($obj_id); - } - - ilUtil::sendSuccess($this->lng->txt("cont_obj_removed"),true); - $this->ctrl->redirect($this, $_GET["mep_mode"] ? $_GET["mep_mode"] : "listMedia"); - } - - - /** - * copy media objects to clipboard - */ - function copyToClipboard() - { - $ilUser = $this->user; - $ilAccess = $this->access; - - $this->checkPermission("write"); - - if(!isset($_POST["id"])) - { - ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); - $this->ctrl->redirect($this, $_GET["mep_mode"] ? $_GET["mep_mode"] : "listMedia"); - } - - foreach ($_POST["id"] as $obj_id) - { - $type = ilMediaPoolItem::lookupType($obj_id); - if ($type == "fold") - { - ilUtil::sendFailure($this->lng->txt("cont_cant_copy_folders"), true); - $this->ctrl->redirect($this, $_GET["mep_mode"] ? $_GET["mep_mode"] : "listMedia"); - } - } - foreach ($_POST["id"] as $obj_id) - { - $fid = ilMediaPoolItem::lookupForeignId($obj_id); - $type = ilMediaPoolItem::lookupType($obj_id); - if ($type == "mob") - { - $ilUser->addObjectToClipboard($fid, "mob", ""); - } - if ($type == "pg") - { - $ilUser->addObjectToClipboard($obj_id, "incl", ""); - } - } - ilUtil::sendSuccess($this->lng->txt("copied_to_clipboard"),true); - $this->ctrl->redirect($this, $_GET["mep_mode"] ? $_GET["mep_mode"] : "listMedia"); - } - - /** - * add locator items for media pool - */ - function addLocatorItems() - { - $ilLocator = $this->locator; - $ilAccess = $this->access; - - if (!$this->getCreationMode() && $this->ctrl->getCmd() != "explorer") - { - $tree = $this->object->getTree(); - $obj_id = ($_GET["mepitem_id"] == "") - ? $tree->getRootId() - : $_GET["mepitem_id"]; - $path = $tree->getPathFull($obj_id); - foreach($path as $node) - { - if ($node["child"] == $tree->getRootId()) - { - $this->ctrl->setParameter($this, "mepitem_id", ""); - if ($ilAccess->checkAccess("read", "", $this->object->getRefId())) - { - $link = $this->ctrl->getLinkTarget($this, "listMedia"); - } - else if ($ilAccess->checkAccess("visible", "", $this->object->getRefId())) - { - $link = $this->ctrl->getLinkTarget($this, "infoScreen"); - } - $title = $this->object->getTitle(); - $this->ctrl->setParameter($this, "mepitem_id", $_GET["mepitem_id"]); - $ilLocator->addItem($title, $link, "", $_GET["ref_id"]); - } - } - } - } - - //// - //// FOLDER Handling - //// - - /** - * create folder form - */ - function createFolderForm() - { - $ilAccess = $this->access; - $tpl = $this->tpl; - - $this->checkPermission("write"); - - $this->initFolderForm("create"); - $tpl->setContent($this->form->getHTML()); - } - - /** - * Edit folder - * - * @param - * @return - */ - function editFolder() - { - $tpl = $this->tpl; - - $this->checkPermission("write"); - - $this->initFolderForm(); - $this->getFolderValues(); - $tpl->setContent($this->form->getHTML()); - } - - /** - * Get current values for folder from - */ - public function getFolderValues() - { - $values = array(); - - $values["title"] = ilMediaPoolItem::lookupTitle($_GET["mepitem_id"]); - - $this->form->setValuesByArray($values); - } - - /** - * Save folder form - */ - public function saveFolder() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->checkPermission("write"); - - $this->initFolderForm("create"); - if ($this->form->checkInput()) - { - if ($this->object->createFolder($_POST["title"], (int) $_GET["mepitem_id"])) - { - ilUtil::sendSuccess($lng->txt("mep_folder_created"), true); - } - $ilCtrl->redirect($this, "listMedia"); - } - - $this->form->setValuesByPost(); - $tpl->setContent($this->form->getHtml()); - } - - /** - * Update folder - */ - function updateFolder() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - - $this->checkPermission("write"); - - $this->initFolderForm("edit"); - if ($this->form->checkInput()) - { - $item = new ilMediaPoolItem($_GET["mepitem_id"]); - $item->setTitle($_POST["title"]); - $item->update(); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->setParameter($this, "mepitem_id", - $this->object->getTree()->getParentId($_GET["mepitem_id"])); - $ilCtrl->redirect($this, "listMedia"); - } - - $this->form->setValuesByPost(); - $tpl->setContent($this->form->getHtml()); - } - - /** - * Init folder form. - * - * @param int $a_mode Edit Mode - */ - public function initFolderForm($a_mode = "edit") - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - // desc - $ti = new ilTextInputGUI($lng->txt("title"), "title"); - $ti->setMaxLength(128); - $ti->setRequired(true); - $this->form->addItem($ti); - - // save and cancel commands - if ($a_mode == "create") - { - $this->form->addCommandButton("saveFolder", $lng->txt("save")); - $this->form->addCommandButton("cancelSave", $lng->txt("cancel")); - $this->form->setTitle($lng->txt("mep_new_folder")); - } - else - { - $this->form->addCommandButton("updateFolder", $lng->txt("save")); - $this->form->addCommandButton("cancelFolderUpdate", $lng->txt("cancel")); - $this->form->setTitle($lng->txt("mep_edit_folder")); - } - - $this->form->setFormAction($ilCtrl->getFormAction($this)); - } - - /** - * Cancel save - */ - function cancelFolderUpdate() - { - $ilCtrl = $this->ctrl; - $ilCtrl->setParameter($this, "mepitem_id", - $this->object->getTree()->getParentId($_GET["mepitem_id"])); - $ilCtrl->redirect($this, "listMedia"); - } - - /** - * Cancel save - */ - function cancelSave() - { - $ilCtrl = $this->ctrl; - $ilCtrl->redirect($this, "listMedia"); - } - - //// - //// CONTENT SNIPPETS Handling - //// - - /** - * Create new content snippet - */ - function createMediaPoolPage() - { - $tpl = $this->tpl; - - $this->checkPermission("write"); - - $this->initMediaPoolPageForm("create"); - $tpl->setContent($this->form->getHTML()); - } - - /** - * Edit media pool page - * - * @param - * @return - */ - function editMediaPoolPage() - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - $this->checkPermission("write"); - - $ilTabs->clearTargets(); - - include_once("./Modules/MediaPool/classes/class.ilMediaPoolPageGUI.php"); - $mep_page_gui = new ilMediaPoolPageGUI($_GET["mepitem_id"], $_GET["old_nr"]); - $mep_page_gui->getTabs(); - - $this->setMediaPoolPageTabs(); - - $this->initMediaPoolPageForm("edit"); - $this->getMediaPoolPageValues(); - $tpl->setContent($this->form->getHTML()); - } - - /** - * Save media pool page - */ - public function saveMediaPoolPage() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->checkPermission("write"); - - $this->initMediaPoolPageForm("create"); - if ($this->form->checkInput()) - { - // create media pool item - include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); - $item = new ilMediaPoolItem(); - $item->setTitle($_POST["title"]); - $item->setType("pg"); - $item->create(); - - if ($item->getId() > 0) - { - // put in tree - $tree = $this->object->getTree(); - $parent = $_GET["mepitem_id"] > 0 - ? $_GET["mepitem_id"] - : $tree->getRootId(); - $this->object->insertInTree($item->getId(), $parent); - - // create page - include_once("./Modules/MediaPool/classes/class.ilMediaPoolPage.php"); - $page = new ilMediaPoolPage(); - $page->setId($item->getId()); - $page->setParentId($this->object->getId()); - $page->create(); - - $ilCtrl->setParameterByClass("ilmediapoolpagegui", "mepitem_id", $item->getId()); - $ilCtrl->redirectByClass("ilmediapoolpagegui", "edit"); - - } - $ilCtrl->redirect($this, "listMedia"); - } - - $this->form->setValuesByPost(); - $tpl->setContent($this->form->getHtml()); - } - - /** - * Update media pool page - */ - function updateMediaPoolPage() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - - $this->checkPermission("write"); - - $this->initMediaPoolPageForm("edit"); - if ($this->form->checkInput()) - { - $item = new ilMediaPoolItem($_GET["mepitem_id"]); - $item->setTitle($_POST["title"]); - $item->update(); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "editMediaPoolPage"); - } - - $this->form->setValuesByPost(); - $tpl->setContent($this->form->getHtml()); - } - /** - * Init page form. - * - * @param int $a_mode Edit Mode - */ - public function initMediaPoolPageForm($a_mode = "edit") - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - // title - $ti = new ilTextInputGUI($lng->txt("title"), "title"); - $ti->setMaxLength(128); - $ti->setRequired(true); - $this->form->addItem($ti); - - // save and cancel commands - if ($a_mode == "create") - { - $this->form->addCommandButton("saveMediaPoolPage", $lng->txt("save")); - $this->form->addCommandButton("cancelSave", $lng->txt("cancel")); - $this->form->setTitle($lng->txt("mep_new_content_snippet")); - } - else - { - $this->form->addCommandButton("updateMediaPoolPage", $lng->txt("save")); - $this->form->setTitle($lng->txt("mep_edit_content_snippet")); - } - - $this->form->setFormAction($ilCtrl->getFormAction($this)); - } - - /** - * Get current values for media pool page from - */ - public function getMediaPoolPageValues() - { - $values = array(); - - include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); - $values["title"] = ilMediaPoolItem::lookupTitle($_GET["mepitem_id"]); - - $this->form->setValuesByArray($values); - } - - /** - * Set media pool page tabs - * - * @param - * @return - */ - function setMediaPoolPageTabs() - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $ilTabs->addTarget("cont_usage", $ilCtrl->getLinkTarget($this, "showMediaPoolPageUsages"), - array("showMediaPoolPageUsages", "showAllMediaPoolPageUsages"), get_class($this)); - $ilTabs->addTarget("settings", $ilCtrl->getLinkTarget($this, "editMediaPoolPage"), - "editMediaPoolPage", get_class($this)); - $ilCtrl->setParameter($this, "mepitem_id", $this->object->getPoolTree()->getParentId($_GET["mepitem_id"])); - $ilTabs->setBackTarget($lng->txt("mep_folder"), $ilCtrl->getLinkTarget($this, "listMedia")); - $ilCtrl->setParameter($this, "mepitem_id", $_GET["mepitem_id"]); - } - - /** - * List usages of the contnet snippet - */ - function showAllMediaPoolPageUsages() - { - $this->showMediaPoolPageUsages(true); - } - - - /** - * List usages of the contnet snippet - */ - function showMediaPoolPageUsages($a_all = false) - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - - $this->checkPermission("write"); - - $ilTabs->clearTargets(); - - $ilTabs->addSubTab("current_usages", $lng->txt("cont_current_usages"), - $ilCtrl->getLinkTarget($this, "showMediaPoolPageUsages")); - - $ilTabs->addSubTab("all_usages", $lng->txt("cont_all_usages"), - $ilCtrl->getLinkTarget($this, "showAllMediaPoolPageUsages")); - - if ($a_all) - { - $ilTabs->activateSubTab("all_usages"); - $cmd = "showAllMediaPoolPageUsages"; - } - else - { - $ilTabs->activateSubTab("current_usages"); - $cmd = "showMediaPoolPageUsages"; - } - - - include_once("./Modules/MediaPool/classes/class.ilMediaPoolPageGUI.php"); - $mep_page_gui = new ilMediaPoolPageGUI($_GET["mepitem_id"], $_GET["old_nr"]); - $mep_page_gui->getTabs(); - - $this->setMediaPoolPageTabs(); - - include_once("./Modules/MediaPool/classes/class.ilMediaPoolPage.php"); - $page = new ilMediaPoolPage((int) $_GET["mepitem_id"]); - - include_once("./Modules/MediaPool/classes/class.ilMediaPoolPageUsagesTableGUI.php"); - $table = new ilMediaPoolPageUsagesTableGUI($this, $cmd, $page, $a_all); - - $tpl->setContent($table->getHTML()); - - } - - - //// - //// OTHER Functions... - //// - - /** - * Set sub tabs for content tab - * - * @param string - */ - function setContentSubTabs($a_active) - { - $ilAccess = $this->access; - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - - $ilTabs->addSubTab("content", $this->lng->txt("objs_fold"), $this->ctrl->getLinkTarget($this, "")); - - $ilCtrl->setParameter($this, "mepitem_id", ""); - $ilTabs->addSubTab("mep_all_mobs", $this->lng->txt("mep_all_mobs"), $this->ctrl->getLinkTarget($this, "allMedia")); - $ilCtrl->setParameter($this, "mepitem_id", $_GET["mepitem_id"]); - - if ($ilAccess->checkAccess('write', '', $this->ref_id)) - { - $ilTabs->addSubtab("srt_files", - $this->lng->txt("mep_media_subtitles"), - $ilCtrl->getLinkTargetByClass("ilmobmultisrtuploadgui", "")); - } - - $ilTabs->activateSubTab($a_active); - } - - - /** - * Set tabs - */ - function setTabs() - { - $ilAccess = $this->access; - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $ilHelp = $this->help; - - $ilHelp->setScreenIdComponent("mep"); - - if ($ilAccess->checkAccess('read', '', $this->ref_id) || - $ilAccess->checkAccess('write', '', $this->ref_id)) - { - $ilTabs->addTab("content", $this->lng->txt("mep_content"), $this->ctrl->getLinkTarget($this, "")); - } - - // info tab - if ($ilAccess->checkAccess('visible', '', $this->ref_id) || - $ilAccess->checkAccess('read', '', $this->ref_id) || - $ilAccess->checkAccess('write', '', $this->ref_id)) - { - $force_active = ($this->ctrl->getNextClass() == "ilinfoscreengui" - || strtolower($_GET["cmdClass"]) == "ilnotegui") - ? true - : false; - $ilTabs->addTarget("info_short", - $this->ctrl->getLinkTargetByClass( - array("ilobjmediapoolgui", "ilinfoscreengui"), "showSummary"), - array("showSummary", "infoScreen"), - "", "", $force_active); - } - - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - $ilTabs->addTarget("settings", $this->ctrl->getLinkTarget($this, "edit"), - "edit", array("", "ilobjmediapoolgui")); - } - - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - $ilTabs->addTarget("clipboard", $this->ctrl->getLinkTarget($this, "openClipboard"), - "view", "ileditclipboardgui"); - } - - // properties - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - // meta data - include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php"; - $mdgui = new ilObjectMetaDataGUI($this->object, "mob"); - $mdtab = $mdgui->getTab(); - if ($mdtab) - { - $ilTabs->addTarget("meta_data", $mdtab, - "", "ilobjectmetadatagui"); - } - } - - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - $ilTabs->addTarget("export", $this->ctrl->getLinkTargetByClass("ilexportgui", ""), - "", "ilexportgui"); - - $ilTabs->addTarget("import", $this->ctrl->getLinkTargetByClass("ilmediapoolimportgui", ""), - "", "ilmediapoolimportgui"); - } - - if ($ilAccess->checkAccess("edit_permission", "", $this->object->getRefId())) - { - $ilTabs->addTarget("perm_settings", - $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm"), array("perm","info","owner"), 'ilpermissiongui'); - } - - } - - /** - * Set setting sub tabs - * - * @param - * @return - */ - function setSettingsSubTabs($a_active) - { - $ilTabs = $this->tabs; - $lng = $this->lng; - $ilAccess = $this->access; - - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - $ilTabs->addSubTab("settings", - $lng->txt("settings"), - $this->ctrl->getLinkTarget($this, "edit")); - - $mset = new ilSetting("mobs"); - if ($mset->get("mep_activate_pages")) - { - $ilTabs->addSubTabTarget("obj_multilinguality", - $this->ctrl->getLinkTargetByClass("ilobjecttranslationgui", "")); - } - } - - $ilTabs->setSubTabActive($a_active); - } - - - /** - * goto target media pool - */ - public static function _goto($a_target) - { - global $DIC; - - $ilAccess = $DIC->access(); - $ilErr = $DIC["ilErr"]; - $lng = $DIC->language(); - - $targets = explode('_',$a_target); - if(count((array) $targets) > 1) - { - $ref_id = $targets[0]; - $subitem_id = $targets[1]; - } - else - { - $ref_id = $targets[0]; - } - - if ($ilAccess->checkAccess("read", "", $ref_id)) - { - $_GET["baseClass"] = "ilMediaPoolPresentationGUI"; - $_GET["ref_id"] = $ref_id; - $_GET['mepitem_id'] = $subitem_id; - include("ilias.php"); - exit; - } else if ($ilAccess->checkAccess("visible", "", $ref_id)) - { - $_GET["baseClass"] = "ilMediaPoolPresentationGUI"; - $_GET["ref_id"] = $ref_id; - $_GET["cmd"] = "infoScreen"; - include("ilias.php"); - exit; - } - else if ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) - { - ilUtil::sendFailure(sprintf($lng->txt("msg_no_perm_read_item"), - ilObject::_lookupTitle(ilObject::_lookupObjId($a_target))), true); - ilObjectGUI::_gotoRepositoryRoot(); - } - - $ilErr->raiseError($lng->txt("msg_no_perm_read"), $ilErr->FATAL); - } - - /** - * 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 infoScreenObject() - { - $this->ctrl->setCmd("showSummary"); - $this->ctrl->setCmdClass("ilinfoscreengui"); - $this->infoScreen(); - } - - /** - * show information screen - */ - function infoScreen() - { - $this->tabs->activateTab("info_short"); - $ilAccess = $this->access; - $ilErr = $this->error; - - if (!$ilAccess->checkAccess("visible", "", $this->ref_id) && - !$ilAccess->checkAccess("read", "", $this->ref_id) && - !$ilAccess->checkAccess("write", "", $this->ref_id)) - { - $ilErr->raiseError($this->lng->txt("msg_no_perm_read"), $ilErr->MESSAGE); - } - - if ($this->ctrl->getCmd() == "infoScreen") - { - $this->ctrl->setCmd("showSummary"); - $this->ctrl->setCmdClass("ilinfoscreengui"); - } - - include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); - $info = new ilInfoScreenGUI($this); - - $info->enablePrivateNotes(); - - - // standard meta data - $info->addMetaDataSections($this->object->getId(),0, $this->object->getType()); - - // forward the command - $this->ctrl->forwardCommand($info); - } - - - //// - //// Upload directory handling - //// - - /** - * Select files from upload directory - */ - function selectUploadDirFiles($a_files = null) - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilToolbar = $this->toolbar; - - if(!$a_files) - { - $a_files = $_POST["file"]; - } - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTarget($this, "listMedia")); - - $this->checkPermission("write"); - - if (ilMainMenuGUI::_checkAdministrationPermission()) - { - - // action type - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $options = array( - "rename" => $lng->txt("mep_up_dir_move"), - "copy" => $lng->txt("mep_up_dir_copy"), - ); - $si = new ilSelectInputGUI("", "action"); - $si->setOptions($options); - $ilToolbar->addInputItem($si); - $ilToolbar->setCloseFormTag(false); - $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); - $ilToolbar->setFormName("mep_up_form"); - - include_once("./Modules/MediaPool/classes/class.ilUploadDirFilesTableGUI.php"); - $tab = new ilUploadDirFilesTableGUI($this, "selectUploadDirFiles", - $a_files); - $tab->setFormName("mep_up_form"); - $tpl->setContent($tab->getHTML()); - } - } - - /** - * Create media object from upload directory - */ - function createMediaFromUploadDir() - { - $this->checkPermission("write"); - - $mset = new ilSetting("mobs"); - $upload_dir = trim($mset->get("upload_dir")); - - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - - if (is_array($_POST["file"]) && ilMainMenuGUI::_checkAdministrationPermission()) - { - foreach ($_POST["file"] as $f) - { - $f = str_replace("..", "", $f); - $fullpath = $upload_dir."/".$f; - $mob = new ilObjMediaObject(); - $mob->setTitle(basename($fullpath)); - $mob->setDescription(""); - $mob->create(); - - // determine and create mob directory, move uploaded file to directory - //$mob_dir = ilUtil::getWebspaceDir()."/mobs/mm_".$a_mob->getId(); - $mob->createDirectory(); - $mob_dir = ilObjMediaObject::_getDirectory($mob->getId()); - - $media_item = new ilMediaItem(); - $mob->addMediaItem($media_item); - $media_item->setPurpose("Standard"); - - $file = $mob_dir."/".basename($fullpath); - - // virus handling - $vir = ilUtil::virusHandling($fullpath, basename($fullpath)); - if (!$vir[0]) - { - ilUtil::sendFailure($this->lng->txt("file_is_infected")."
".$vir[1], true); - ilUtil::redirect("ilias.php?baseClass=ilMediaPoolPresentationGUI&cmd=listMedia&ref_id=". - $_GET["ref_id"]."&mepitem_id=".$_GET["mepitem_id"]); - } - - switch ($_POST["action"]) - { - case "rename": - rename($fullpath, $file); - break; - - case "copy": - copy($fullpath, $file); - break; - } - - // get mime type - $format = ilObjMediaObject::getMimeType($file); - $location = basename($fullpath); - - // set real meta and object data - $media_item->setFormat($format); - $media_item->setLocation($location); - $media_item->setLocationType("LocalFile"); - - $mob->setDescription($format); - - // determine width and height of known image types - $wh = ilObjMediaObject::_determineWidthHeight($format, - "File", $mob_dir."/".$location, $media_item->getLocation(), - true, true, "", ""); - $media_item->setWidth($wh["width"]); - $media_item->setHeight($wh["height"]); - if ($wh["info"] != "") - { - // ilUtil::sendInfo($wh["info"], true); - } - - $media_item->setHAlign("Left"); - ilUtil::renameExecutables($mob_dir); - $mob->update(); - - - // put it into current folder - $mep_item = new ilMediaPoolItem(); - $mep_item->setTitle($mob->getTitle()); - $mep_item->setType("mob"); - $mep_item->setForeignId($mob->getId()); - $mep_item->create(); - - $tree = $this->object->getTree(); - $parent = ($_GET["mepitem_id"] == "") - ? $tree->getRootId() - : $_GET["mepitem_id"]; - $tree->insertNode($mep_item->getId(), $parent); - } - } - ilUtil::redirect("ilias.php?baseClass=ilMediaPoolPresentationGUI&cmd=listMedia&ref_id=". - $_GET["ref_id"]."&mepitem_id=".$_GET["mepitem_id"]); - - } - - /** - * Get preview modal html - */ - static function getPreviewModalHTML($a_mpool_ref_id, $a_tpl) - { - global $DIC; - - $tpl = $DIC["tpl"]; - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - require_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); - ilObjMediaObjectGUI::includePresentationJS($a_tpl); - - $tpl->addJavaScript("./Modules/MediaPool/js/ilMediaPool.js"); - - $ilCtrl->setParameterByClass("ilobjmediapoolgui", "mepitem_id", ""); - $ilCtrl->setParameterByClass("ilobjmediapoolgui", "ref_id", $a_mpool_ref_id); - $tpl->addOnloadCode("il.MediaPool.setPreviewUrl('".$ilCtrl->getLinkTargetByClass(array("ilmediapoolpresentationgui", "ilobjmediapoolgui"), "showPreview", "", false, false)."');"); - $ilCtrl->setParameterByClass("ilobjmediapoolgui", "mepitem_id", $_GET["mepitem_id"]); - $ilCtrl->setParameterByClass("ilobjmediapoolgui", "ref_id", $_GET["red_id"]); - - include_once("./Services/UIComponent/Modal/classes/class.ilModalGUI.php"); - $modal = ilModalGUI::getInstance(); - $modal->setHeading($lng->txt("preview")); - $modal->setId("ilMepPreview"); - $modal->setType(ilModalGUI::TYPE_LARGE); - $modal->setBody(""); - - return $modal->getHTML(); - } - - /** - * export content object - */ - function export() - { - $ot = ilObjectTranslation::getInstance($this->object->getId()); - $opt = ""; - if ($ot->getContentActivated()) - { - $format = explode("_", $_POST["format"]); - $opt = ilUtil::stripSlashes($format[1]); - } - - $this->object->exportXML($opt); - } - - // - // BULK UPLOAD - // - - /** - * Bulk upload - */ - protected function bulkUpload() - { - $this->checkPermission("write"); - - $main_tpl = $this->main_tpl; - - $form = $this->initBulkUploadForm(); - $main_tpl->setContent($form->getHTML()); - } - - /** - * Init bulk upload form - */ - public function initBulkUploadForm() - { - $ctrl = $this->ctrl; - $lng = $this->lng; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - - $form->setFormAction($ctrl->getFormAction($this)); - $form->setPreventDoubleSubmission(false); - - $item = new ilFileStandardDropzoneInputGUI($lng->txt("mep_media_files"), 'media_files'); - $item->setUploadUrl($ctrl->getLinkTarget($this, "performBulkUpload", "", true, true)); - $item->setMaxFiles(20); - $form->addItem($item); - - $form->addCommandButton("performBulkUpload", $lng->txt("upload")); - - $form->setTitle($lng->txt("mep_bulk_upload")); - - return $form; - } - - /** - * Save bulk upload form - */ - public function performBulkUpload() - { - $this->checkPermission("write"); - - $ctrl = $this->ctrl; - $lng = $this->lng; - $main_tpl = $this->main_tpl; - $upload = $this->upload; - $log = $this->mep_log; - - $form = $this->initBulkUploadForm(); - if ($form->checkInput()) - { - $mep_item_ids = []; - // Check if this is a request to upload a file - $log->debug("checking for uploads..."); - if ($upload->hasUploads()) { - $log->debug("has upload..."); - try { - $upload->process(); - $log->debug("nr of results: ".count($upload->getResults())); - foreach ($upload->getResults() as $result) - { - $title = $result->getName(); - - $mob = new ilObjMediaObject(); - $mob->setTitle($title); - $mob->setDescription(""); - $mob->create(); - - $mob->createDirectory(); - $media_item = new ilMediaItem(); - $mob->addMediaItem($media_item); - $media_item->setPurpose("Standard"); - - $mob_dir = ilObjMediaObject::_getRelativeDirectory($mob->getId()); - $file_name = ilObjMediaObject::fixFilename($title); - $file = $mob_dir."/".$file_name; - - $upload->moveOneFileTo($result, - $mob_dir, - Location::WEB, - $file_name, - true - ); - - $mep_item = new ilMediaPoolItem(); - $mep_item->setTitle($title); - $mep_item->setType("mob"); - $mep_item->setForeignId($mob->getId()); - $mep_item->create(); - - $tree = $this->object->getTree(); - $parent = ($_GET["mepitem_id"] == "") - ? $tree->getRootId() - : $_GET["mepitem_id"]; - $tree->insertNode($mep_item->getId(), $parent); - - // get mime type - $format = ilObjMediaObject::getMimeType($file); - $location = $file_name; - - // set real meta and object data - $media_item->setFormat($format); - $media_item->setLocation($location); - $media_item->setLocationType("LocalFile"); - $media_item->setUploadHash(ilUtil::stripSlashes($_POST["ilfilehash"])); - $mob->update(); - $mep_item_ids[] = $mob->getId(); - } - } - catch (Exception $e) - { - $log->debug("Got exception: ".$e->getMessage()); - echo json_encode(array( 'success' => false, 'message' => $e->getMessage())); - } - $log->debug("end of 'has_uploads'"); - } - $log->debug("has no upload..."); - - $log->debug("calling redirect... (".$_POST["ilfilehash"].")"); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ctrl->setParameter($this, "mep_hash", $_POST["ilfilehash"]); - $ctrl->redirect($this, "editTitlesAndDescriptions"); - } - - $form->setValuesByPost(); - $main_tpl->setContent($form->getHtml()); - } - - /** - * Edit titles and descriptions - */ - protected function editTitlesAndDescriptions() - { - $ctrl = $this->ctrl; - $lng = $this->lng; - - $this->checkPermission("write"); - $ctrl->saveParameter($this,"mep_hash"); - - $main_tpl = $this->main_tpl; - - include_once("./Services/MediaObjects/classes/class.ilMediaItem.php"); - $media_items = ilMediaItem::getMediaItemsForUploadHash($_GET["mep_hash"]); - - include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); - - $tb = new ilToolbarGUI(); - $tb->setFormAction($ctrl->getFormAction($this)); - $tb->addFormButton($lng->txt("save"), "saveTitlesAndDescriptions"); - $tb->setOpenFormTag(true); - $tb->setCloseFormTag(false); - $tb->setId("tb_top"); - - $html = $tb->getHTML(); - foreach ($media_items as $mi) - { - $acc = new ilAccordionGUI(); - $acc->setBehaviour(ilAccordionGUI::ALL_CLOSED); - $acc->setId("acc_".$mi["mob_id"]); - - $mob = new ilObjMediaObject($mi["mob_id"]); - $form = $this->initMediaBulkForm($mi["mob_id"], $mob->getTitle()); - $acc->addItem($mob->getTitle(), $form->getHTML()); - - $html.= $acc->getHTML(); - } - - $html.= $tb->getHTML(); - $tb->setOpenFormTag(false); - $tb->setCloseFormTag(true); - $tb->setId("tb_bottom"); - - $main_tpl->setContent($html); - } - - /** - * Init media bulk form. - */ - public function initMediaBulkForm($a_id, $a_title) - { - $lng = $this->lng; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setOpenTag(false); - $form->setCloseTag(false); - - // title - $ti = new ilTextInputGUI($lng->txt("title"), "title_".$a_id); - $ti->setValue($a_title); - $form->addItem($ti); - - // description - $ti = new ilTextAreaInputGUI($lng->txt("description"), "description_".$a_id); - $form->addItem($ti); - - return $form; - } - - /** - * Save titles and descriptions - */ - protected function saveTitlesAndDescriptions() - { - $lng = $this->lng; - $ctrl = $this->ctrl; - - $this->checkPermission("write"); - //var_dump(_$POST); exit; - - $media_items = ilMediaItem::getMediaItemsForUploadHash($_GET["mep_hash"]); - include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); - - foreach ($media_items as $mi) - { - $mob = new ilObjMediaObject($mi["mob_id"]); - $form = $this->initMediaBulkForm($mi["mob_id"], $mob->getTitle()); - $form->checkInput(); - $title = $form->getInput("title_" . $mi["mob_id"]); - $desc = $form->getInput("description_" . $mi["mob_id"]); - if (trim($title) != "") - { - $mob->setTitle($title); - } - $mob->setDescription($desc); - $mob->update(); - } - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ctrl->redirect($this, "listMedia"); - } - - + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var ilTemplate + */ + protected $main_tpl; + + /** + * @var \ILIAS\FileUpload\FileUpload + */ + protected $upload; + + /** + * @var ilLogger + */ + protected $mep_log; + + /** + * Constructor + */ + public function __construct($a_id = 0, $a_id_type = self::REPOSITORY_NODE_ID, $a_parent_node_id = 0) + { + global $DIC; + + parent::__construct($a_id, $a_id_type, $a_parent_node_id); + + $this->tabs = $DIC->tabs(); + $this->error = $DIC["ilErr"]; + $this->locator = $DIC["ilLocator"]; + $this->help = $DIC["ilHelp"]; + + $this->main_tpl = $DIC->ui()->mainTemplate(); + + $this->upload = $DIC->upload(); + + $this->mep_log = ilLoggerFactory::getLogger("mep"); + } + + public $output_prepared; + + /** + * Initialisation + */ + protected function afterConstructor() + { + $lng = $this->lng; + + $lng->loadLanguageModule("mep"); + + if ($this->ctrl->getCmd() == "explorer") { + $this->ctrl->saveParameter($this, array("ref_id")); + } else { + $this->ctrl->saveParameter($this, array("ref_id", "mepitem_id")); + } + $this->ctrl->saveParameter($this, array("mep_mode")); + + $lng->loadLanguageModule("content"); + } + + /** + * Get type + */ + final public function getType() + { + return "mep"; + } + + /** + * execute command + * + * @return bool|void + * @throws ilCtrlException + */ + public function executeCommand() + { + $ilTabs = $this->tabs; + $lng = $this->lng; + $ilAccess = $this->access; + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + + if ($this->ctrl->getRedirectSource() == "ilinternallinkgui") { + $this->explorer(); + return; + } + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + $new_type = $_POST["new_type"] + ? $_POST["new_type"] + : $_GET["new_type"]; + + if ($new_type != "" && ($cmd != "confirmRemove" && $cmd != "copyToClipboard" + && $cmd != "pasteFromClipboard")) { + $this->setCreationMode(true); + } + + if (!$this->getCreationMode()) { + $tree = $this->object->getTree(); + if ($_GET["mepitem_id"] == "") { + $_GET["mepitem_id"] = $tree->getRootId(); + } + } + if ($cmd == "create") { + switch ($_POST["new_type"]) { + case "mob": + $this->ctrl->redirectByClass("ilobjmediaobjectgui", "create"); + break; + + case "fold": + $this->ctrl->redirectByClass("ilobjfoldergui", "create"); + break; + } + } + + switch ($next_class) { + case 'ilobjectmetadatagui': + $this->checkPermission("write"); + + $this->prepareOutput(); + $this->addHeaderAction(); + + $this->tabs_gui->activateTab('meta_data'); + include_once 'Services/Object/classes/class.ilObjectMetaDataGUI.php'; + $md_gui = new ilObjectMetaDataGUI($this->object, 'mob'); + $this->ctrl->forwardCommand($md_gui); + $this->tpl->show(); + break; + + + case 'ilmediapoolpagegui': + $this->checkPermission("write"); + $this->prepareOutput(); + $this->addHeaderAction(); + $ilTabs->clearTargets(); + include_once("./Modules/MediaPool/classes/class.ilMediaPoolPageGUI.php"); + $mep_page_gui = new ilMediaPoolPageGUI($_GET["mepitem_id"], $_GET["old_nr"]); + + if (!$ilAccess->checkAccess("write", "", $this->object->getRefId())) { + $mep_page_gui->setEnableEditing(false); + } + $ret = $this->ctrl->forwardCommand($mep_page_gui); + if ($ret != "") { + $tpl->setContent($ret); + } + $this->setMediaPoolPageTabs(); + $this->tpl->show(); + break; + + case "ilobjmediaobjectgui": + $this->checkPermission("write"); + if ($cmd == "create" || $cmd == "save" || $cmd == "cancel") { + $ret_obj = $_GET["mepitem_id"]; + $ilObjMediaObjectGUI = new ilObjMediaObjectGUI("", 0, false, false); + $ilObjMediaObjectGUI->setWidthPreset($this->object->getDefaultWidth()); + $ilObjMediaObjectGUI->setHeightPreset($this->object->getDefaultHeight()); + } else { + $ret_obj = $tree->getParentId($_GET["mepitem_id"]); + $ilObjMediaObjectGUI = new ilObjMediaObjectGUI("", ilMediaPoolItem::lookupForeignId($_GET["mepitem_id"]), false, false); + $this->ctrl->setParameter($this, "mepitem_id", $this->getParentFolderId()); + $ilTabs->setBackTarget( + $lng->txt("back"), + $this->ctrl->getLinkTarget( + $this, + $_GET["mep_mode"] ? $_GET["mep_mode"] : "listMedia" + ) + ); + } + if ($this->ctrl->getCmdClass() == "ilinternallinkgui") { + $this->ctrl->setReturn($this, "explorer"); + } else { + $this->ctrl->setParameter($this, "mepitem_id", $ret_obj); + $this->ctrl->setReturn( + $this, + $_GET["mep_mode"] ? $_GET["mep_mode"] : "listMedia" + ); + $this->ctrl->setParameter($this, "mepitem_id", $_GET["mepitem_id"]); + } + $this->getTemplate(); + $ilObjMediaObjectGUI->setTabs(); + $this->setLocator(); + + // set adv metadata record dobject + $ilObjMediaObjectGUI->setAdvMdRecordObject($this->object->getRefId(), "mep", "mob"); + + $ret = $this->ctrl->forwardCommand($ilObjMediaObjectGUI); + + if ($cmd == "save" && $ret != false) { + $mep_item = new ilMediaPoolItem(); + $mep_item->setTitle($ret->getTitle()); + $mep_item->setType("mob"); + $mep_item->setForeignId($ret->getId()); + $mep_item->create(); + + $parent = ($_GET["mepitem_id"] == "") + ? $tree->getRootId() + : $_GET["mepitem_id"]; + $tree->insertNode($mep_item->getId(), $parent); + ilUtil::redirect("ilias.php?baseClass=ilMediaPoolPresentationGUI&cmd=listMedia&ref_id=" . + $_GET["ref_id"] . "&mepitem_id=" . $_GET["mepitem_id"]); + } else { + $this->tpl->show(); + } + break; + + case "ilobjfoldergui": + $this->checkPermission("write"); + $this->addHeaderAction(); + $folder_gui = new ilObjFolderGUI("", 0, false, false); + $this->ctrl->setReturn($this, "listMedia"); + $cmd.="Object"; + switch ($cmd) { + case "createObject": + $this->prepareOutput(); + $folder_gui = new ilObjFolderGUI("", 0, false, false); + $folder_gui->setFormAction( + "save", + $this->ctrl->getFormActionByClass("ilobjfoldergui") + ); + $folder_gui->createObject(); + $this->tpl->show(); + break; + + case "saveObject": + //$folder_gui->setReturnLocation("save", $this->ctrl->getLinkTarget($this, "listMedia")); + $parent = ($_GET["mepitem_id"] == "") + ? $tree->getRootId() + : $_GET["mepitem_id"]; + $folder_gui->setFolderTree($tree); + $folder_gui->saveObject($parent); + //$this->ctrl->redirect($this, "listMedia"); + break; + + case "editObject": + $this->prepareOutput(); + $folder_gui = new ilObjFolderGUI("", ilMediaPoolItem::lookupForeignId($_GET["mepitem_id"]), false, false); + $this->ctrl->setParameter($this, "foldereditmode", "1"); + $folder_gui->setFormAction("update", $this->ctrl->getFormActionByClass("ilobjfoldergui")); + $folder_gui->editObject(); + $this->tpl->show(); + break; + + case "updateObject": + $folder_gui = new ilObjFolderGUI("", ilMediaPoolItem::lookupForeignId($_GET["mepitem_id"]), false, false); + $this->ctrl->setParameter($this, "mepitem_id", $this->getParentFolderId()); + $this->ctrl->setReturn($this, "listMedia"); + $folder_gui->updateObject(true); // this returns to parent + break; + + case "cancelObject": + if ($_GET["foldereditmode"]) { + $this->ctrl->setParameter($this, "mepitem_id", $this->getParentFolderId()); + } + $this->ctrl->redirect($this, "listMedia"); + break; + } + break; + + case "ileditclipboardgui": + $this->prepareOutput(); + $this->addHeaderAction(); + $this->ctrl->setReturn($this, $_GET["mep_mode"] ? $_GET["mep_mode"] : "listMedia"); + $clip_gui = new ilEditClipboardGUI(); + $clip_gui->setMultipleSelections(true); + $clip_gui->setInsertButtonTitle($lng->txt("mep_copy_to_mep")); + $ilTabs->setTabActive("clipboard"); + $this->ctrl->forwardCommand($clip_gui); + $this->tpl->show(); + break; + + case 'ilinfoscreengui': + $this->prepareOutput(); + $this->addHeaderAction(); + $this->infoScreen(); + $this->tpl->show(); + break; + + case 'ilpermissiongui': + $this->checkPermission("edit_permission"); + $this->prepareOutput(); + $this->addHeaderAction(); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $this->ctrl->forwardCommand($perm_gui); + $this->tpl->show(); + break; + + case "ilexportgui": + $this->checkPermission("write"); + $this->prepareOutput(); + $this->addHeaderAction(); + include_once("./Services/Export/classes/class.ilExportGUI.php"); + $exp_gui = new ilExportGUI($this); + $exp_gui->addFormat("xml"); + include_once("./Services/Object/classes/class.ilObjectTranslation.php"); + $ot = ilObjectTranslation::getInstance($this->object->getId()); + if ($ot->getContentActivated()) { + $exp_gui->addFormat("xml_master", "XML (" . $lng->txt("mep_master_language_only") . ")", $this, "export"); + $exp_gui->addFormat("xml_masternomedia", "XML (" . $lng->txt("mep_master_language_only_no_media") . ")", $this, "export"); + } + $this->ctrl->forwardCommand($exp_gui); + $this->tpl->show(); + break; + + case "ilfilesystemgui": + $this->checkPermission("write"); + $this->prepareOutput(); + $this->addHeaderAction(); + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, "listMedia") + ); + $mset = new ilSetting("mobs"); + if (trim($mset->get("upload_dir")) != "") { + include_once("./Services/FileSystem/classes/class.ilFileSystemGUI.php"); + $fs_gui = new ilFileSystemGUI($mset->get("upload_dir")); + $fs_gui->setPostDirPath(true); + $fs_gui->setTableId("mepud" . $this->object->getId()); + $fs_gui->setAllowFileCreation(false); + $fs_gui->setAllowDirectoryCreation(false); + $fs_gui->clearCommands(); + $fs_gui->addCommand( + $this, + "selectUploadDirFiles", + $this->lng->txt("mep_sel_upload_dir_files"), + false, + true + ); + $this->ctrl->forwardCommand($fs_gui); + } + $this->tpl->show(); + break; + + case "ilcommonactiondispatchergui": + include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); + $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); + $this->ctrl->forwardCommand($gui); + break; + + case 'ilobjecttranslationgui': + $this->prepareOutput(); + $this->addHeaderAction(); + //$this->setTabs("settings"); + $ilTabs->activateTab("settings"); + $this->setSettingsSubTabs("obj_multilinguality"); + include_once("./Services/Object/classes/class.ilObjectTranslationGUI.php"); + $transgui = new ilObjectTranslationGUI($this); + $transgui->setTitleDescrOnlyMode(false); + $this->ctrl->forwardCommand($transgui); + $this->tpl->show(); + break; + + case "ilmediapoolimportgui": + $this->prepareOutput(); + $this->addHeaderAction(); + $ilTabs->activateTab("import"); + include_once("./Modules/MediaPool/classes/class.ilMediaPoolImportGUI.php"); + $gui = new ilMediaPoolImportGUI($this->object); + $this->ctrl->forwardCommand($gui); + $this->tpl->show(); + break; + + case "ilmobmultisrtuploadgui": + $this->checkPermission("write"); + $this->prepareOutput(); + $this->addHeaderAction(); + //$this->setTabs("content"); + $this->setContentSubTabs("srt_files"); + include_once("./Services/MediaObjects/classes/class.ilMobMultiSrtUploadGUI.php"); + include_once("./Modules/MediaPool/classes/class.ilMepMultiSrt.php"); + $gui = new ilMobMultiSrtUploadGUI(new ilMepMultiSrt($this->object)); + $this->ctrl->forwardCommand($gui); + $this->tpl->show(); + break; + + + default: + $this->prepareOutput(); + $this->addHeaderAction(); + $cmd = $this->ctrl->getCmd("listMedia"); + $this->$cmd(); + if (!$this->getCreationMode()) { + $this->tpl->show(); + } + break; + } + } + + /** + * obsolete? + */ + public function createMediaObject() + { + $this->ctrl->redirectByClass("ilobjmediaobjectgui", "create"); + } + + protected function initCreationForms($a_new_type) + { + $forms = array(self::CFORM_NEW => $this->initCreateForm($a_new_type), + self::CFORM_IMPORT => $this->initImportForm($a_new_type)); + + return $forms; + } + + /** + * save object + */ + public function afterSave(ilObject $newObj) + { + // always send a message + ilUtil::sendSuccess($this->lng->txt("object_added"), true); + + //ilUtil::redirect($this->getReturnLocation("save","adm_object.php?".$this->link_params)); + ilUtil::redirect("ilias.php?baseClass=ilMediaPoolPresentationGUI&ref_id=" . $newObj->getRefId() . "&cmd=listMedia"); + } + + protected function initEditCustomForm(ilPropertyFormGUI $a_form) + { + $obj_service = $this->object_service; + + // default width + $ni = new ilNumberInputGUI($this->lng->txt("mep_default_width"), "default_width"); + $ni->setMinValue(0); + $ni->setSuffix("px"); + $ni->setMaxLength(5); + $ni->setSize(5); + $a_form->addItem($ni); + + // default height + $ni = new ilNumberInputGUI($this->lng->txt("mep_default_height"), "default_height"); + $ni->setSuffix("px"); + $ni->setMinValue(0); + $ni->setMaxLength(5); + $ni->setSize(5); + $ni->setInfo($this->lng->txt("mep_default_width_height_info")); + $a_form->addItem($ni); + + // presentation + $pres = new ilFormSectionHeaderGUI(); + $pres->setTitle($this->lng->txt('obj_presentation')); + $a_form->addItem($pres); + + // tile image + $obj_service->commonSettings()->legacyForm($a_form, $this->object)->addTileImage(); + + // additional features + $feat = new ilFormSectionHeaderGUI(); + $feat->setTitle($this->lng->txt('obj_features')); + $a_form->addItem($feat); + + include_once './Services/Container/classes/class.ilContainer.php'; + include_once './Services/Object/classes/class.ilObjectServiceSettingsGUI.php'; + ilObjectServiceSettingsGUI::initServiceSettingsForm( + $this->object->getId(), + $a_form, + array( + ilObjectServiceSettingsGUI::CUSTOM_METADATA + ) + ); + } + + /** + * edit object + * + * @access public + */ + public function edit() + { + $tpl = $this->tpl; + $ilTabs = $this->tabs_gui; + $ilErr = $this->ilErr; + + $this->setSettingsSubTabs("settings"); + + if (!$this->checkPermissionBool("write")) { + $ilErr->raiseError($this->lng->txt("msg_no_perm_write"), $ilErr->MESSAGE); + } + + $ilTabs->activateTab("settings"); + + $form = $this->initEditForm(); + $values = $this->getEditFormValues(); + if ($values) { + $form->setValuesByArray($values, true); + } + + $this->addExternalEditFormCustom($form); + + $tpl->setContent($form->getHTML()); + } + + + protected function getEditFormCustomValues(array &$a_values) + { + if ($this->object->getDefaultWidth() > 0) { + $a_values["default_width"] = $this->object->getDefaultWidth(); + } + if ($this->object->getDefaultHeight() > 0) { + $a_values["default_height"] = $this->object->getDefaultHeight(); + } + } + + protected function updateCustom(ilPropertyFormGUI $a_form) + { + $obj_service = $this->object_service; + + $this->object->setDefaultWidth($a_form->getInput("default_width")); + $this->object->setDefaultHeight($a_form->getInput("default_height")); + + + // additional features + include_once './Services/Object/classes/class.ilObjectServiceSettingsGUI.php'; + ilObjectServiceSettingsGUI::updateServiceSettingsForm( + $this->object->getId(), + $a_form, + array( + ilObjectServiceSettingsGUI::CUSTOM_METADATA + ) + ); + + // tile image + $obj_service->commonSettings()->legacyForm($a_form, $this->object)->saveTileImage(); + } + + /** + * list media objects + */ + public function listMedia() + { + $ilAccess = $this->access; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $ilToolbar = $this->toolbar; + $lng = $this->lng; + + $ilCtrl->setParameter($this, "mep_mode", "listMedia"); + + $this->checkPermission("read"); + + $ilTabs->setTabActive("content"); + $this->setContentSubTabs("content"); + + if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) { + $ilToolbar->addButton( + $lng->txt("mep_create_mob"), + $ilCtrl->getLinkTarget($this, "createMediaObject") + ); + + $mset = new ilSetting("mobs"); + if ($mset->get("mep_activate_pages")) { + $ilToolbar->addButton( + $lng->txt("mep_create_content_snippet"), + $ilCtrl->getLinkTarget($this, "createMediaPoolPage") + ); + } + + $ilToolbar->addButton( + $lng->txt("mep_create_folder"), + $ilCtrl->getLinkTarget($this, "createFolderForm") + ); + + if (trim($mset->get("upload_dir")) != "" && ilMainMenuGUI::_checkAdministrationPermission()) { + $ilToolbar->addButton( + $lng->txt("mep_create_from_upload_dir"), + $ilCtrl->getLinkTargetByClass("ilfilesystemgui", "listFiles") + ); + } + + $ilToolbar->addButton( + $lng->txt("mep_bulk_upload"), + $ilCtrl->getLinkTarget($this, "bulkUpload") + ); + } + + // tree + include_once("./Modules/MediaPool/classes/class.ilMediaPoolExplorerGUI.php"); + $exp = new ilMediaPoolExplorerGUI($this, "listMedia", $this->object); + if (!$exp->handleCommand()) { + $this->tpl->setLeftNavContent($exp->getHTML()); + } else { + return; + } + + include_once("./Modules/MediaPool/classes/class.ilMediaPoolTableGUI.php"); + $mep_table_gui = new ilMediaPoolTableGUI($this, "listMedia", $this->object, "mepitem_id"); + $tpl->setContent($mep_table_gui->getHTML()); + } + + /** + * list all objects + */ + public function allMedia() + { + $tpl = $this->tpl; + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + $ilCtrl->setParameter($this, "mep_mode", "allMedia"); + + $this->checkPermission("read"); + $ilTabs->setTabActive("content"); + $this->setContentSubTabs("mep_all_mobs"); + + + include_once("./Modules/MediaPool/classes/class.ilMediaPoolTableGUI.php"); + $mep_table_gui = new ilMediaPoolTableGUI( + $this, + "allMedia", + $this->object, + "mepitem_id", + ilMediaPoolTableGUI::IL_MEP_EDIT, + true + ); + + + if (isset($_GET['force_filter']) and $_GET['force_filter']) { + $_POST['title'] = ilMediaPoolItem::lookupTitle((int) $_GET['force_filter']); + + include_once("./Services/Table/classes/class.ilTablePropertiesStorage.php"); + $tprop = new ilTablePropertiesStorage(); + $tprop->storeProperty( + $mep_table_gui->getId(), + $ilUser->getId(), + 'filter', + 1 + ); + $mep_table_gui->resetFilter(); + $mep_table_gui->resetOffset(); + $mep_table_gui->writeFilterToSession(); + + // Read again + $mep_table_gui = new ilMediaPoolTableGUI( + $this, + "allMedia", + $this->object, + "mepitem_id", + ilMediaPoolTableGUI::IL_MEP_EDIT, + true + ); + } + + $tpl->setContent($mep_table_gui->getHTML()); + } + + /** + * Apply filter + */ + public function applyFilter() + { + include_once("./Modules/MediaPool/classes/class.ilMediaPoolTableGUI.php"); + $mtab = new ilMediaPoolTableGUI( + $this, + "allMedia", + $this->object, + "mepitem_id", + ilMediaPoolTableGUI::IL_MEP_EDIT, + true + ); + $mtab->writeFilterToSession(); + $mtab->resetOffset(); + $this->allMedia(); + } + + /** + * Reset filter + */ + public function resetFilter() + { + include_once("./Modules/MediaPool/classes/class.ilMediaPoolTableGUI.php"); + $mtab = new ilMediaPoolTableGUI( + $this, + "allMedia", + $this->object, + "mepitem_id", + ilMediaPoolTableGUI::IL_MEP_EDIT, + true + ); + $mtab->resetFilter(); + $mtab->resetOffset(); + $this->allMedia(); + } + + /** + * Get standard template + */ + public function getTemplate() + { + $this->tpl->getStandardTemplate(); + } + + + /** + * Get folder parent ID + */ + public function getParentFolderId() + { + if ($_GET["mepitem_id"] == "") { + return ""; + } + $par_id = $this->object->getPoolTree()->getParentId($_GET["mepitem_id"]); + if ($par_id != $this->object->getPoolTree()->getRootId()) { + return $par_id; + } else { + return ""; + } + } + + /** + * show media object + */ + protected function showMedia() + { + $this->checkPermission("read"); + + $item = new ilMediaPoolItem((int) $_GET["mepitem_id"]); + $mob_id = $item->getForeignId(); + + $this->tpl = new ilTemplate("tpl.fullscreen.html", true, true, "Services/COPage"); + include_once("Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $this->tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); + $this->tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath(0) + ); + + + require_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + require_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); + ilObjMediaObjectGUI::includePresentationJS($this->tpl); + $media_obj = new ilObjMediaObject((int) $mob_id); + + + $this->tpl->setVariable("TITLE", " - " . $media_obj->getTitle()); + + $xml = ""; + // todo: we get always the first alias now (problem if mob is used multiple + // times in page) + $xml.= $media_obj->getXML(IL_MODE_ALIAS); + $xml.= $media_obj->getXML(IL_MODE_OUTPUT); + $xml.= $link_xml; + $xml.=""; + + $xsl = file_get_contents("./Services/COPage/xsl/page.xsl"); + $args = array( '/_xml' => $xml, '/_xsl' => $xsl ); + $xh = xslt_create(); + + $wb_path = ilUtil::getWebspaceDir("output") . "/"; + + $mode = ($_GET["cmd"] != "showPreview") + ? "fullscreen" + : "media"; + $enlarge_path = ilUtil::getImagePath("enlarge.svg", false, "output"); + $fullscreen_link = + $this->ctrl->getLinkTarget($this, "showFullscreen", "", false, false); + $params = array('mode' => $mode, 'enlarge_path' => $enlarge_path, + 'link_params' => "ref_id=" . $_GET["ref_id"],'fullscreen_link' => $fullscreen_link, + 'ref_id' => $_GET["ref_id"], 'pg_frame' => $pg_frame, 'webspace_path' => $wb_path); + $output = xslt_process($xh, "arg:/_xml", "arg:/_xsl", null, $args, $params); + echo xslt_error($xh); + xslt_free($xh); + // unmask user html + $this->tpl->setVariable("MEDIA_CONTENT", $output); + } + + /** + * Show page + * + * @param + * @return + */ + public function showPage() + { + $tpl = $this->tpl; + + $tpl = new ilTemplate("tpl.main.html", true, true); + + include_once("./Services/Container/classes/class.ilContainerPage.php"); + include_once("./Services/Container/classes/class.ilContainerPageGUI.php"); + + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); + $tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath(0) + ); + $tpl->setCurrentBlock("SyntaxStyle"); + $tpl->setVariable( + "LOCATION_SYNTAX_STYLESHEET", + ilObjStyleSheet::getSyntaxStylePath() + ); + $tpl->parseCurrentBlock(); + + // get page object + //include_once("./Services/Object/classes/class.ilObjectTranslation.php"); + //$ot = ilObjectTranslation::getInstance($this->object->getId()); + //$lang = $ot->getEffectiveContentLang($ilUser->getCurrentLanguage(), "cont"); + include_once("./Modules/MediaPool/classes/class.ilMediaPoolPageGUI.php"); + $page_gui = new ilMediaPoolPageGUI((int) $_GET["mepitem_id"]); + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + //$page_gui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId( + // $this->object->getStyleSheetId(), $this->object->getType())); + + $page_gui->setTemplateOutput(false); + $page_gui->setHeader(""); + $ret = $page_gui->showPage(true); + + $tpl->setBodyClass("ilMediaPoolPagePreviewBody"); + $tpl->setVariable("CONTENT", $ret); + //$ret = "
".$ret."
"; + + + $tpl->show(); + exit; + } + + + /** + * Show content snippet + */ + public function showPreview() + { + $this->checkPermission("read"); + + $item = new ilMediaPoolItem((int) $_GET["mepitem_id"]); + + switch ($item->getType()) { + case "mob": + $this->showMedia(); + break; + + case "pg": + $this->showPage(); + break; + } + } + + + /** + * show fullscreen + */ + public function showFullscreen() + { + $this->showMedia(); + } + + /** + * confirm remove of mobs + */ + public function confirmRemove() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilErr = $this->error; + + $this->checkPermission("write"); + + if (!isset($_POST["id"])) { + $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); + } + + // display confirmation message + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($this->ctrl->getFormAction($this)); + $cgui->setHeaderText($this->lng->txt("info_remove_sure")); + $cgui->setCancel($this->lng->txt("cancel"), "cancelRemove"); + $cgui->setConfirm($this->lng->txt("confirm"), "remove"); + + foreach ($_POST["id"] as $obj_id) { + $type = ilMediaPoolItem::lookupType($obj_id); + $title = ilMediaPoolItem::lookupTitle($obj_id); + + // check whether page can be removed + $add = ""; + if ($type == "pg") { + include_once("./Services/COPage/classes/class.ilPageContentUsage.php"); + $usages = ilPageContentUsage::getUsages("incl", $obj_id, false); + if (count($usages) > 0) { + ilUtil::sendFailure(sprintf($lng->txt("mep_content_snippet_in_use"), $title), true); + $ilCtrl->redirect($this, "listMedia"); + } else { + // check whether the snippet is used in older versions of pages + $usages = ilPageContentUsage::getUsages("incl", $obj_id, true); + if (count($usages) > 0) { + $add = "
" . $lng->txt("mep_content_snippet_used_in_older_versions") . "
"; + } + } + } + + $caption = ilUtil::getImageTagByType($type, $this->tpl->tplPath) . + " " . $title . $add; + + $cgui->addItem("id[]", $obj_id, $caption); + } + + $this->tpl->setContent($cgui->getHTML()); + } + + /** + * paste from clipboard + */ + public function openClipboard() + { + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + + $this->checkPermission("write"); + + $ilCtrl->setParameterByClass( + "ileditclipboardgui", + "returnCommand", + rawurlencode($ilCtrl->getLinkTarget( + $this, + "insertFromClipboard", + "", + false, + false + )) + ); + $ilCtrl->redirectByClass("ilEditClipboardGUI", "getObject"); + } + + + /** + * insert media object from clipboard + */ + public function insertFromClipboard() + { + $ilAccess = $this->access; + + $this->checkPermission("write"); + + include_once("./Services/Clipboard/classes/class.ilEditClipboardGUI.php"); + $ids = ilEditClipboardGUI::_getSelectedIDs(); + $not_inserted = array(); + if (is_array($ids)) { + foreach ($ids as $id2) { + $id = explode(":", $id2); + $type = $id[0]; + $id = $id[1]; + + if ($type == "mob") { // media object + if (ilObjMEdiaPool::isForeignIdInTree($this->object->getId(), $id)) { + $not_inserted[] = ilObject::_lookupTitle($id) . " [" . + $id . "]"; + } else { + $item = new ilMediaPoolItem(); + $item->setType("mob"); + $item->setForeignId($id); + $item->setTitle(ilObject::_lookupTitle($id)); + $item->create(); + if ($item->getId() > 0) { + $this->object->insertInTree($item->getId(), $_GET["mepitem_id"]); + } + } + } + if ($type == "incl") { // content snippet + include_once("./Modules/MediaPool/classes/class.ilMediaPoolPage.php"); + include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); + if (ilObjMEdiaPool::isItemIdInTree($this->object->getId(), $id)) { + $not_inserted[] = ilMediaPoolPage::lookupTitle($id) . " [" . + $id . "]"; + } else { + $original = new ilMediaPoolPage($id); + + // copy the page into the pool + $item = new ilMediaPoolItem(); + $item->setType("pg"); + $item->setTitle(ilMediaPoolItem::lookupTitle($id)); + $item->create(); + if ($item->getId() > 0) { + $this->object->insertInTree($item->getId(), $_GET["mepitem_id"]); + + // create page + include_once("./Modules/MediaPool/classes/class.ilMediaPoolPage.php"); + $page = new ilMediaPoolPage(); + $page->setId($item->getId()); + $page->setParentId($this->object->getId()); + $page->create(); + + // copy content + $original->copy($page->getId(), $page->getParentType(), $page->getParentId(), true); + } + } + } + } + } + if (count($not_inserted) > 0) { + ilUtil::sendInfo($this->lng->txt("mep_not_insert_already_exist") . "
" . + implode($not_inserted, "
"), true); + } + $this->ctrl->redirect($this, $_GET["mep_mode"] ? $_GET["mep_mode"] : "listMedia"); + } + + + /** + * cancel deletion of media objects/folders + */ + public function cancelRemove() + { + $this->ctrl->redirect($this, $_GET["mep_mode"] ? $_GET["mep_mode"] : "listMedia"); + } + + /** + * confirm deletion of + */ + public function remove() + { + $ilAccess = $this->access; + + $this->checkPermission("write"); + + foreach ($_POST["id"] as $obj_id) { + $this->object->deleteChild($obj_id); + } + + ilUtil::sendSuccess($this->lng->txt("cont_obj_removed"), true); + $this->ctrl->redirect($this, $_GET["mep_mode"] ? $_GET["mep_mode"] : "listMedia"); + } + + + /** + * copy media objects to clipboard + */ + public function copyToClipboard() + { + $ilUser = $this->user; + $ilAccess = $this->access; + + $this->checkPermission("write"); + + if (!isset($_POST["id"])) { + ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); + $this->ctrl->redirect($this, $_GET["mep_mode"] ? $_GET["mep_mode"] : "listMedia"); + } + + foreach ($_POST["id"] as $obj_id) { + $type = ilMediaPoolItem::lookupType($obj_id); + if ($type == "fold") { + ilUtil::sendFailure($this->lng->txt("cont_cant_copy_folders"), true); + $this->ctrl->redirect($this, $_GET["mep_mode"] ? $_GET["mep_mode"] : "listMedia"); + } + } + foreach ($_POST["id"] as $obj_id) { + $fid = ilMediaPoolItem::lookupForeignId($obj_id); + $type = ilMediaPoolItem::lookupType($obj_id); + if ($type == "mob") { + $ilUser->addObjectToClipboard($fid, "mob", ""); + } + if ($type == "pg") { + $ilUser->addObjectToClipboard($obj_id, "incl", ""); + } + } + ilUtil::sendSuccess($this->lng->txt("copied_to_clipboard"), true); + $this->ctrl->redirect($this, $_GET["mep_mode"] ? $_GET["mep_mode"] : "listMedia"); + } + + /** + * add locator items for media pool + */ + public function addLocatorItems() + { + $ilLocator = $this->locator; + $ilAccess = $this->access; + + if (!$this->getCreationMode() && $this->ctrl->getCmd() != "explorer") { + $tree = $this->object->getTree(); + $obj_id = ($_GET["mepitem_id"] == "") + ? $tree->getRootId() + : $_GET["mepitem_id"]; + $path = $tree->getPathFull($obj_id); + foreach ($path as $node) { + if ($node["child"] == $tree->getRootId()) { + $this->ctrl->setParameter($this, "mepitem_id", ""); + if ($ilAccess->checkAccess("read", "", $this->object->getRefId())) { + $link = $this->ctrl->getLinkTarget($this, "listMedia"); + } elseif ($ilAccess->checkAccess("visible", "", $this->object->getRefId())) { + $link = $this->ctrl->getLinkTarget($this, "infoScreen"); + } + $title = $this->object->getTitle(); + $this->ctrl->setParameter($this, "mepitem_id", $_GET["mepitem_id"]); + $ilLocator->addItem($title, $link, "", $_GET["ref_id"]); + } + } + } + } + + //// + //// FOLDER Handling + //// + + /** + * create folder form + */ + public function createFolderForm() + { + $ilAccess = $this->access; + $tpl = $this->tpl; + + $this->checkPermission("write"); + + $this->initFolderForm("create"); + $tpl->setContent($this->form->getHTML()); + } + + /** + * Edit folder + * + * @param + * @return + */ + public function editFolder() + { + $tpl = $this->tpl; + + $this->checkPermission("write"); + + $this->initFolderForm(); + $this->getFolderValues(); + $tpl->setContent($this->form->getHTML()); + } + + /** + * Get current values for folder from + */ + public function getFolderValues() + { + $values = array(); + + $values["title"] = ilMediaPoolItem::lookupTitle($_GET["mepitem_id"]); + + $this->form->setValuesByArray($values); + } + + /** + * Save folder form + */ + public function saveFolder() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $this->checkPermission("write"); + + $this->initFolderForm("create"); + if ($this->form->checkInput()) { + if ($this->object->createFolder($_POST["title"], (int) $_GET["mepitem_id"])) { + ilUtil::sendSuccess($lng->txt("mep_folder_created"), true); + } + $ilCtrl->redirect($this, "listMedia"); + } + + $this->form->setValuesByPost(); + $tpl->setContent($this->form->getHtml()); + } + + /** + * Update folder + */ + public function updateFolder() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + + $this->checkPermission("write"); + + $this->initFolderForm("edit"); + if ($this->form->checkInput()) { + $item = new ilMediaPoolItem($_GET["mepitem_id"]); + $item->setTitle($_POST["title"]); + $item->update(); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->setParameter( + $this, + "mepitem_id", + $this->object->getTree()->getParentId($_GET["mepitem_id"]) + ); + $ilCtrl->redirect($this, "listMedia"); + } + + $this->form->setValuesByPost(); + $tpl->setContent($this->form->getHtml()); + } + + /** + * Init folder form. + * + * @param int $a_mode Edit Mode + */ + public function initFolderForm($a_mode = "edit") + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + // desc + $ti = new ilTextInputGUI($lng->txt("title"), "title"); + $ti->setMaxLength(128); + $ti->setRequired(true); + $this->form->addItem($ti); + + // save and cancel commands + if ($a_mode == "create") { + $this->form->addCommandButton("saveFolder", $lng->txt("save")); + $this->form->addCommandButton("cancelSave", $lng->txt("cancel")); + $this->form->setTitle($lng->txt("mep_new_folder")); + } else { + $this->form->addCommandButton("updateFolder", $lng->txt("save")); + $this->form->addCommandButton("cancelFolderUpdate", $lng->txt("cancel")); + $this->form->setTitle($lng->txt("mep_edit_folder")); + } + + $this->form->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * Cancel save + */ + public function cancelFolderUpdate() + { + $ilCtrl = $this->ctrl; + $ilCtrl->setParameter( + $this, + "mepitem_id", + $this->object->getTree()->getParentId($_GET["mepitem_id"]) + ); + $ilCtrl->redirect($this, "listMedia"); + } + + /** + * Cancel save + */ + public function cancelSave() + { + $ilCtrl = $this->ctrl; + $ilCtrl->redirect($this, "listMedia"); + } + + //// + //// CONTENT SNIPPETS Handling + //// + + /** + * Create new content snippet + */ + public function createMediaPoolPage() + { + $tpl = $this->tpl; + + $this->checkPermission("write"); + + $this->initMediaPoolPageForm("create"); + $tpl->setContent($this->form->getHTML()); + } + + /** + * Edit media pool page + * + * @param + * @return + */ + public function editMediaPoolPage() + { + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + $this->checkPermission("write"); + + $ilTabs->clearTargets(); + + include_once("./Modules/MediaPool/classes/class.ilMediaPoolPageGUI.php"); + $mep_page_gui = new ilMediaPoolPageGUI($_GET["mepitem_id"], $_GET["old_nr"]); + $mep_page_gui->getTabs(); + + $this->setMediaPoolPageTabs(); + + $this->initMediaPoolPageForm("edit"); + $this->getMediaPoolPageValues(); + $tpl->setContent($this->form->getHTML()); + } + + /** + * Save media pool page + */ + public function saveMediaPoolPage() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $this->checkPermission("write"); + + $this->initMediaPoolPageForm("create"); + if ($this->form->checkInput()) { + // create media pool item + include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); + $item = new ilMediaPoolItem(); + $item->setTitle($_POST["title"]); + $item->setType("pg"); + $item->create(); + + if ($item->getId() > 0) { + // put in tree + $tree = $this->object->getTree(); + $parent = $_GET["mepitem_id"] > 0 + ? $_GET["mepitem_id"] + : $tree->getRootId(); + $this->object->insertInTree($item->getId(), $parent); + + // create page + include_once("./Modules/MediaPool/classes/class.ilMediaPoolPage.php"); + $page = new ilMediaPoolPage(); + $page->setId($item->getId()); + $page->setParentId($this->object->getId()); + $page->create(); + + $ilCtrl->setParameterByClass("ilmediapoolpagegui", "mepitem_id", $item->getId()); + $ilCtrl->redirectByClass("ilmediapoolpagegui", "edit"); + } + $ilCtrl->redirect($this, "listMedia"); + } + + $this->form->setValuesByPost(); + $tpl->setContent($this->form->getHtml()); + } + + /** + * Update media pool page + */ + public function updateMediaPoolPage() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + + $this->checkPermission("write"); + + $this->initMediaPoolPageForm("edit"); + if ($this->form->checkInput()) { + $item = new ilMediaPoolItem($_GET["mepitem_id"]); + $item->setTitle($_POST["title"]); + $item->update(); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "editMediaPoolPage"); + } + + $this->form->setValuesByPost(); + $tpl->setContent($this->form->getHtml()); + } + /** + * Init page form. + * + * @param int $a_mode Edit Mode + */ + public function initMediaPoolPageForm($a_mode = "edit") + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + // title + $ti = new ilTextInputGUI($lng->txt("title"), "title"); + $ti->setMaxLength(128); + $ti->setRequired(true); + $this->form->addItem($ti); + + // save and cancel commands + if ($a_mode == "create") { + $this->form->addCommandButton("saveMediaPoolPage", $lng->txt("save")); + $this->form->addCommandButton("cancelSave", $lng->txt("cancel")); + $this->form->setTitle($lng->txt("mep_new_content_snippet")); + } else { + $this->form->addCommandButton("updateMediaPoolPage", $lng->txt("save")); + $this->form->setTitle($lng->txt("mep_edit_content_snippet")); + } + + $this->form->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * Get current values for media pool page from + */ + public function getMediaPoolPageValues() + { + $values = array(); + + include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); + $values["title"] = ilMediaPoolItem::lookupTitle($_GET["mepitem_id"]); + + $this->form->setValuesByArray($values); + } + + /** + * Set media pool page tabs + * + * @param + * @return + */ + public function setMediaPoolPageTabs() + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $ilTabs->addTarget( + "cont_usage", + $ilCtrl->getLinkTarget($this, "showMediaPoolPageUsages"), + array("showMediaPoolPageUsages", "showAllMediaPoolPageUsages"), + get_class($this) + ); + $ilTabs->addTarget( + "settings", + $ilCtrl->getLinkTarget($this, "editMediaPoolPage"), + "editMediaPoolPage", + get_class($this) + ); + $ilCtrl->setParameter($this, "mepitem_id", $this->object->getPoolTree()->getParentId($_GET["mepitem_id"])); + $ilTabs->setBackTarget($lng->txt("mep_folder"), $ilCtrl->getLinkTarget($this, "listMedia")); + $ilCtrl->setParameter($this, "mepitem_id", $_GET["mepitem_id"]); + } + + /** + * List usages of the contnet snippet + */ + public function showAllMediaPoolPageUsages() + { + $this->showMediaPoolPageUsages(true); + } + + + /** + * List usages of the contnet snippet + */ + public function showMediaPoolPageUsages($a_all = false) + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + + $this->checkPermission("write"); + + $ilTabs->clearTargets(); + + $ilTabs->addSubTab( + "current_usages", + $lng->txt("cont_current_usages"), + $ilCtrl->getLinkTarget($this, "showMediaPoolPageUsages") + ); + + $ilTabs->addSubTab( + "all_usages", + $lng->txt("cont_all_usages"), + $ilCtrl->getLinkTarget($this, "showAllMediaPoolPageUsages") + ); + + if ($a_all) { + $ilTabs->activateSubTab("all_usages"); + $cmd = "showAllMediaPoolPageUsages"; + } else { + $ilTabs->activateSubTab("current_usages"); + $cmd = "showMediaPoolPageUsages"; + } + + + include_once("./Modules/MediaPool/classes/class.ilMediaPoolPageGUI.php"); + $mep_page_gui = new ilMediaPoolPageGUI($_GET["mepitem_id"], $_GET["old_nr"]); + $mep_page_gui->getTabs(); + + $this->setMediaPoolPageTabs(); + + include_once("./Modules/MediaPool/classes/class.ilMediaPoolPage.php"); + $page = new ilMediaPoolPage((int) $_GET["mepitem_id"]); + + include_once("./Modules/MediaPool/classes/class.ilMediaPoolPageUsagesTableGUI.php"); + $table = new ilMediaPoolPageUsagesTableGUI($this, $cmd, $page, $a_all); + + $tpl->setContent($table->getHTML()); + } + + + //// + //// OTHER Functions... + //// + + /** + * Set sub tabs for content tab + * + * @param string + */ + public function setContentSubTabs($a_active) + { + $ilAccess = $this->access; + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + + $ilTabs->addSubTab("content", $this->lng->txt("objs_fold"), $this->ctrl->getLinkTarget($this, "")); + + $ilCtrl->setParameter($this, "mepitem_id", ""); + $ilTabs->addSubTab("mep_all_mobs", $this->lng->txt("mep_all_mobs"), $this->ctrl->getLinkTarget($this, "allMedia")); + $ilCtrl->setParameter($this, "mepitem_id", $_GET["mepitem_id"]); + + if ($ilAccess->checkAccess('write', '', $this->ref_id)) { + $ilTabs->addSubtab( + "srt_files", + $this->lng->txt("mep_media_subtitles"), + $ilCtrl->getLinkTargetByClass("ilmobmultisrtuploadgui", "") + ); + } + + $ilTabs->activateSubTab($a_active); + } + + + /** + * Set tabs + */ + public function setTabs() + { + $ilAccess = $this->access; + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $ilHelp = $this->help; + + $ilHelp->setScreenIdComponent("mep"); + + if ($ilAccess->checkAccess('read', '', $this->ref_id) || + $ilAccess->checkAccess('write', '', $this->ref_id)) { + $ilTabs->addTab("content", $this->lng->txt("mep_content"), $this->ctrl->getLinkTarget($this, "")); + } + + // info tab + if ($ilAccess->checkAccess('visible', '', $this->ref_id) || + $ilAccess->checkAccess('read', '', $this->ref_id) || + $ilAccess->checkAccess('write', '', $this->ref_id)) { + $force_active = ($this->ctrl->getNextClass() == "ilinfoscreengui" + || strtolower($_GET["cmdClass"]) == "ilnotegui") + ? true + : false; + $ilTabs->addTarget( + "info_short", + $this->ctrl->getLinkTargetByClass( + array("ilobjmediapoolgui", "ilinfoscreengui"), + "showSummary" + ), + array("showSummary", "infoScreen"), + "", + "", + $force_active + ); + } + + if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) { + $ilTabs->addTarget( + "settings", + $this->ctrl->getLinkTarget($this, "edit"), + "edit", + array("", "ilobjmediapoolgui") + ); + } + + if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) { + $ilTabs->addTarget( + "clipboard", + $this->ctrl->getLinkTarget($this, "openClipboard"), + "view", + "ileditclipboardgui" + ); + } + + // properties + if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) { + // meta data + include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php"; + $mdgui = new ilObjectMetaDataGUI($this->object, "mob"); + $mdtab = $mdgui->getTab(); + if ($mdtab) { + $ilTabs->addTarget( + "meta_data", + $mdtab, + "", + "ilobjectmetadatagui" + ); + } + } + + if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) { + $ilTabs->addTarget( + "export", + $this->ctrl->getLinkTargetByClass("ilexportgui", ""), + "", + "ilexportgui" + ); + + $ilTabs->addTarget( + "import", + $this->ctrl->getLinkTargetByClass("ilmediapoolimportgui", ""), + "", + "ilmediapoolimportgui" + ); + } + + if ($ilAccess->checkAccess("edit_permission", "", $this->object->getRefId())) { + $ilTabs->addTarget( + "perm_settings", + $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm"), + array("perm","info","owner"), + 'ilpermissiongui' + ); + } + } + + /** + * Set setting sub tabs + * + * @param + * @return + */ + public function setSettingsSubTabs($a_active) + { + $ilTabs = $this->tabs; + $lng = $this->lng; + $ilAccess = $this->access; + + if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) { + $ilTabs->addSubTab( + "settings", + $lng->txt("settings"), + $this->ctrl->getLinkTarget($this, "edit") + ); + + $mset = new ilSetting("mobs"); + if ($mset->get("mep_activate_pages")) { + $ilTabs->addSubTabTarget( + "obj_multilinguality", + $this->ctrl->getLinkTargetByClass("ilobjecttranslationgui", "") + ); + } + } + + $ilTabs->setSubTabActive($a_active); + } + + + /** + * goto target media pool + */ + public static function _goto($a_target) + { + global $DIC; + + $ilAccess = $DIC->access(); + $ilErr = $DIC["ilErr"]; + $lng = $DIC->language(); + + $targets = explode('_', $a_target); + if (count((array) $targets) > 1) { + $ref_id = $targets[0]; + $subitem_id = $targets[1]; + } else { + $ref_id = $targets[0]; + } + + if ($ilAccess->checkAccess("read", "", $ref_id)) { + $_GET["baseClass"] = "ilMediaPoolPresentationGUI"; + $_GET["ref_id"] = $ref_id; + $_GET['mepitem_id'] = $subitem_id; + include("ilias.php"); + exit; + } elseif ($ilAccess->checkAccess("visible", "", $ref_id)) { + $_GET["baseClass"] = "ilMediaPoolPresentationGUI"; + $_GET["ref_id"] = $ref_id; + $_GET["cmd"] = "infoScreen"; + include("ilias.php"); + exit; + } elseif ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) { + ilUtil::sendFailure(sprintf( + $lng->txt("msg_no_perm_read_item"), + ilObject::_lookupTitle(ilObject::_lookupObjId($a_target)) + ), true); + ilObjectGUI::_gotoRepositoryRoot(); + } + + $ilErr->raiseError($lng->txt("msg_no_perm_read"), $ilErr->FATAL); + } + + /** + * 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 infoScreenObject() + { + $this->ctrl->setCmd("showSummary"); + $this->ctrl->setCmdClass("ilinfoscreengui"); + $this->infoScreen(); + } + + /** + * show information screen + */ + public function infoScreen() + { + $this->tabs->activateTab("info_short"); + $ilAccess = $this->access; + $ilErr = $this->error; + + if (!$ilAccess->checkAccess("visible", "", $this->ref_id) && + !$ilAccess->checkAccess("read", "", $this->ref_id) && + !$ilAccess->checkAccess("write", "", $this->ref_id)) { + $ilErr->raiseError($this->lng->txt("msg_no_perm_read"), $ilErr->MESSAGE); + } + + if ($this->ctrl->getCmd() == "infoScreen") { + $this->ctrl->setCmd("showSummary"); + $this->ctrl->setCmdClass("ilinfoscreengui"); + } + + include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); + $info = new ilInfoScreenGUI($this); + + $info->enablePrivateNotes(); + + + // standard meta data + $info->addMetaDataSections($this->object->getId(), 0, $this->object->getType()); + + // forward the command + $this->ctrl->forwardCommand($info); + } + + + //// + //// Upload directory handling + //// + + /** + * Select files from upload directory + */ + public function selectUploadDirFiles($a_files = null) + { + $tpl = $this->tpl; + $ilTabs = $this->tabs; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilToolbar = $this->toolbar; + + if (!$a_files) { + $a_files = $_POST["file"]; + } + + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, "listMedia") + ); + + $this->checkPermission("write"); + + if (ilMainMenuGUI::_checkAdministrationPermission()) { + + // action type + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $options = array( + "rename" => $lng->txt("mep_up_dir_move"), + "copy" => $lng->txt("mep_up_dir_copy"), + ); + $si = new ilSelectInputGUI("", "action"); + $si->setOptions($options); + $ilToolbar->addInputItem($si); + $ilToolbar->setCloseFormTag(false); + $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); + $ilToolbar->setFormName("mep_up_form"); + + include_once("./Modules/MediaPool/classes/class.ilUploadDirFilesTableGUI.php"); + $tab = new ilUploadDirFilesTableGUI( + $this, + "selectUploadDirFiles", + $a_files + ); + $tab->setFormName("mep_up_form"); + $tpl->setContent($tab->getHTML()); + } + } + + /** + * Create media object from upload directory + */ + public function createMediaFromUploadDir() + { + $this->checkPermission("write"); + + $mset = new ilSetting("mobs"); + $upload_dir = trim($mset->get("upload_dir")); + + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + + if (is_array($_POST["file"]) && ilMainMenuGUI::_checkAdministrationPermission()) { + foreach ($_POST["file"] as $f) { + $f = str_replace("..", "", $f); + $fullpath = $upload_dir . "/" . $f; + $mob = new ilObjMediaObject(); + $mob->setTitle(basename($fullpath)); + $mob->setDescription(""); + $mob->create(); + + // determine and create mob directory, move uploaded file to directory + //$mob_dir = ilUtil::getWebspaceDir()."/mobs/mm_".$a_mob->getId(); + $mob->createDirectory(); + $mob_dir = ilObjMediaObject::_getDirectory($mob->getId()); + + $media_item = new ilMediaItem(); + $mob->addMediaItem($media_item); + $media_item->setPurpose("Standard"); + + $file = $mob_dir . "/" . basename($fullpath); + + // virus handling + $vir = ilUtil::virusHandling($fullpath, basename($fullpath)); + if (!$vir[0]) { + ilUtil::sendFailure($this->lng->txt("file_is_infected") . "
" . $vir[1], true); + ilUtil::redirect("ilias.php?baseClass=ilMediaPoolPresentationGUI&cmd=listMedia&ref_id=" . + $_GET["ref_id"] . "&mepitem_id=" . $_GET["mepitem_id"]); + } + + switch ($_POST["action"]) { + case "rename": + rename($fullpath, $file); + break; + + case "copy": + copy($fullpath, $file); + break; + } + + // get mime type + $format = ilObjMediaObject::getMimeType($file); + $location = basename($fullpath); + + // set real meta and object data + $media_item->setFormat($format); + $media_item->setLocation($location); + $media_item->setLocationType("LocalFile"); + + $mob->setDescription($format); + + // determine width and height of known image types + $wh = ilObjMediaObject::_determineWidthHeight( + $format, + "File", + $mob_dir . "/" . $location, + $media_item->getLocation(), + true, + true, + "", + "" + ); + $media_item->setWidth($wh["width"]); + $media_item->setHeight($wh["height"]); + if ($wh["info"] != "") { + // ilUtil::sendInfo($wh["info"], true); + } + + $media_item->setHAlign("Left"); + ilUtil::renameExecutables($mob_dir); + $mob->update(); + + + // put it into current folder + $mep_item = new ilMediaPoolItem(); + $mep_item->setTitle($mob->getTitle()); + $mep_item->setType("mob"); + $mep_item->setForeignId($mob->getId()); + $mep_item->create(); + + $tree = $this->object->getTree(); + $parent = ($_GET["mepitem_id"] == "") + ? $tree->getRootId() + : $_GET["mepitem_id"]; + $tree->insertNode($mep_item->getId(), $parent); + } + } + ilUtil::redirect("ilias.php?baseClass=ilMediaPoolPresentationGUI&cmd=listMedia&ref_id=" . + $_GET["ref_id"] . "&mepitem_id=" . $_GET["mepitem_id"]); + } + + /** + * Get preview modal html + */ + public static function getPreviewModalHTML($a_mpool_ref_id, $a_tpl) + { + global $DIC; + + $tpl = $DIC["tpl"]; + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + require_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); + ilObjMediaObjectGUI::includePresentationJS($a_tpl); + + $tpl->addJavaScript("./Modules/MediaPool/js/ilMediaPool.js"); + + $ilCtrl->setParameterByClass("ilobjmediapoolgui", "mepitem_id", ""); + $ilCtrl->setParameterByClass("ilobjmediapoolgui", "ref_id", $a_mpool_ref_id); + $tpl->addOnloadCode("il.MediaPool.setPreviewUrl('" . $ilCtrl->getLinkTargetByClass(array("ilmediapoolpresentationgui", "ilobjmediapoolgui"), "showPreview", "", false, false) . "');"); + $ilCtrl->setParameterByClass("ilobjmediapoolgui", "mepitem_id", $_GET["mepitem_id"]); + $ilCtrl->setParameterByClass("ilobjmediapoolgui", "ref_id", $_GET["red_id"]); + + include_once("./Services/UIComponent/Modal/classes/class.ilModalGUI.php"); + $modal = ilModalGUI::getInstance(); + $modal->setHeading($lng->txt("preview")); + $modal->setId("ilMepPreview"); + $modal->setType(ilModalGUI::TYPE_LARGE); + $modal->setBody(""); + + return $modal->getHTML(); + } + + /** + * export content object + */ + public function export() + { + $ot = ilObjectTranslation::getInstance($this->object->getId()); + $opt = ""; + if ($ot->getContentActivated()) { + $format = explode("_", $_POST["format"]); + $opt = ilUtil::stripSlashes($format[1]); + } + + $this->object->exportXML($opt); + } + + // + // BULK UPLOAD + // + + /** + * Bulk upload + */ + protected function bulkUpload() + { + $this->checkPermission("write"); + + $main_tpl = $this->main_tpl; + + $form = $this->initBulkUploadForm(); + $main_tpl->setContent($form->getHTML()); + } + + /** + * Init bulk upload form + */ + public function initBulkUploadForm() + { + $ctrl = $this->ctrl; + $lng = $this->lng; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + + $form->setFormAction($ctrl->getFormAction($this)); + $form->setPreventDoubleSubmission(false); + + $item = new ilFileStandardDropzoneInputGUI($lng->txt("mep_media_files"), 'media_files'); + $item->setUploadUrl($ctrl->getLinkTarget($this, "performBulkUpload", "", true, true)); + $item->setMaxFiles(20); + $form->addItem($item); + + $form->addCommandButton("performBulkUpload", $lng->txt("upload")); + + $form->setTitle($lng->txt("mep_bulk_upload")); + + return $form; + } + + /** + * Save bulk upload form + */ + public function performBulkUpload() + { + $this->checkPermission("write"); + + $ctrl = $this->ctrl; + $lng = $this->lng; + $main_tpl = $this->main_tpl; + $upload = $this->upload; + $log = $this->mep_log; + + $form = $this->initBulkUploadForm(); + if ($form->checkInput()) { + $mep_item_ids = []; + // Check if this is a request to upload a file + $log->debug("checking for uploads..."); + if ($upload->hasUploads()) { + $log->debug("has upload..."); + try { + $upload->process(); + $log->debug("nr of results: " . count($upload->getResults())); + foreach ($upload->getResults() as $result) { + $title = $result->getName(); + + $mob = new ilObjMediaObject(); + $mob->setTitle($title); + $mob->setDescription(""); + $mob->create(); + + $mob->createDirectory(); + $media_item = new ilMediaItem(); + $mob->addMediaItem($media_item); + $media_item->setPurpose("Standard"); + + $mob_dir = ilObjMediaObject::_getRelativeDirectory($mob->getId()); + $file_name = ilObjMediaObject::fixFilename($title); + $file = $mob_dir . "/" . $file_name; + + $upload->moveOneFileTo( + $result, + $mob_dir, + Location::WEB, + $file_name, + true + ); + + $mep_item = new ilMediaPoolItem(); + $mep_item->setTitle($title); + $mep_item->setType("mob"); + $mep_item->setForeignId($mob->getId()); + $mep_item->create(); + + $tree = $this->object->getTree(); + $parent = ($_GET["mepitem_id"] == "") + ? $tree->getRootId() + : $_GET["mepitem_id"]; + $tree->insertNode($mep_item->getId(), $parent); + + // get mime type + $format = ilObjMediaObject::getMimeType($file); + $location = $file_name; + + // set real meta and object data + $media_item->setFormat($format); + $media_item->setLocation($location); + $media_item->setLocationType("LocalFile"); + $media_item->setUploadHash(ilUtil::stripSlashes($_POST["ilfilehash"])); + $mob->update(); + $mep_item_ids[] = $mob->getId(); + } + } catch (Exception $e) { + $log->debug("Got exception: " . $e->getMessage()); + echo json_encode(array( 'success' => false, 'message' => $e->getMessage())); + } + $log->debug("end of 'has_uploads'"); + } + $log->debug("has no upload..."); + + $log->debug("calling redirect... (" . $_POST["ilfilehash"] . ")"); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ctrl->setParameter($this, "mep_hash", $_POST["ilfilehash"]); + $ctrl->redirect($this, "editTitlesAndDescriptions"); + } + + $form->setValuesByPost(); + $main_tpl->setContent($form->getHtml()); + } + + /** + * Edit titles and descriptions + */ + protected function editTitlesAndDescriptions() + { + $ctrl = $this->ctrl; + $lng = $this->lng; + + $this->checkPermission("write"); + $ctrl->saveParameter($this, "mep_hash"); + + $main_tpl = $this->main_tpl; + + include_once("./Services/MediaObjects/classes/class.ilMediaItem.php"); + $media_items = ilMediaItem::getMediaItemsForUploadHash($_GET["mep_hash"]); + + include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); + + $tb = new ilToolbarGUI(); + $tb->setFormAction($ctrl->getFormAction($this)); + $tb->addFormButton($lng->txt("save"), "saveTitlesAndDescriptions"); + $tb->setOpenFormTag(true); + $tb->setCloseFormTag(false); + $tb->setId("tb_top"); + + $html = $tb->getHTML(); + foreach ($media_items as $mi) { + $acc = new ilAccordionGUI(); + $acc->setBehaviour(ilAccordionGUI::ALL_CLOSED); + $acc->setId("acc_" . $mi["mob_id"]); + + $mob = new ilObjMediaObject($mi["mob_id"]); + $form = $this->initMediaBulkForm($mi["mob_id"], $mob->getTitle()); + $acc->addItem($mob->getTitle(), $form->getHTML()); + + $html.= $acc->getHTML(); + } + + $html.= $tb->getHTML(); + $tb->setOpenFormTag(false); + $tb->setCloseFormTag(true); + $tb->setId("tb_bottom"); + + $main_tpl->setContent($html); + } + + /** + * Init media bulk form. + */ + public function initMediaBulkForm($a_id, $a_title) + { + $lng = $this->lng; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setOpenTag(false); + $form->setCloseTag(false); + + // title + $ti = new ilTextInputGUI($lng->txt("title"), "title_" . $a_id); + $ti->setValue($a_title); + $form->addItem($ti); + + // description + $ti = new ilTextAreaInputGUI($lng->txt("description"), "description_" . $a_id); + $form->addItem($ti); + + return $form; + } + + /** + * Save titles and descriptions + */ + protected function saveTitlesAndDescriptions() + { + $lng = $this->lng; + $ctrl = $this->ctrl; + + $this->checkPermission("write"); + //var_dump(_$POST); exit; + + $media_items = ilMediaItem::getMediaItemsForUploadHash($_GET["mep_hash"]); + include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); + + foreach ($media_items as $mi) { + $mob = new ilObjMediaObject($mi["mob_id"]); + $form = $this->initMediaBulkForm($mi["mob_id"], $mob->getTitle()); + $form->checkInput(); + $title = $form->getInput("title_" . $mi["mob_id"]); + $desc = $form->getInput("description_" . $mi["mob_id"]); + if (trim($title) != "") { + $mob->setTitle($title); + } + $mob->setDescription($desc); + $mob->update(); + } + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ctrl->redirect($this, "listMedia"); + } } -?> \ No newline at end of file diff --git a/Modules/MediaPool/classes/class.ilObjMediaPoolListGUI.php b/Modules/MediaPool/classes/class.ilObjMediaPoolListGUI.php index d0391e639462d86d0d0b49b8110e53f7ac41d369..269d9437b9b9baa483b53e142b266f6d350671c8 100644 --- a/Modules/MediaPool/classes/class.ilObjMediaPoolListGUI.php +++ b/Modules/MediaPool/classes/class.ilObjMediaPoolListGUI.php @@ -14,107 +14,99 @@ include_once "Services/Object/classes/class.ilObjectListGUI.php"; */ class ilObjMediaPoolListGUI extends ilObjectListGUI { - /** - * initialisation - */ - function init() - { - $this->copy_enabled = true; - #$this->static_link_enabled = true; - $this->delete_enabled = true; - $this->cut_enabled = true; - $this->subscribe_enabled = true; - $this->link_enabled = true; - $this->info_screen_enabled = true; - $this->type = "mep"; - $this->gui_class_name = "ilobjmediapoolgui"; - - // general commands array - include_once('Modules/MediaPool/classes/class.ilObjMediaPoolAccess.php'); - $this->commands = ilObjMediaPoolAccess::_getCommands(); - - } - - - /** - * inititialize new item - * - * @param int $a_ref_id reference id - * @param int $a_obj_id object id - * @param string $a_title title - * @param string $a_description description - */ - function initItem($a_ref_id, $a_obj_id, $a_title = "", $a_description = "") - { - parent::initItem($a_ref_id, $a_obj_id, $a_title, $a_description); - } - - - /** - * Get command target frame - * - * @param string $a_cmd command - * - * @return string command target frame - */ - function getCommandFrame($a_cmd) - { - switch($a_cmd) - { - case "": - $frame = ilFrameTargetInfo::_getFrame("MainContent"); - break; - - default: - } - - return $frame; - } - - - - /** - * Get item properties - * - * @return array array of property arrays: - * "alert" (boolean) => display as an alert property (usually in red) - * "property" (string) => property name - * "value" (string) => property value - */ - function getProperties() - { - $lng = $this->lng; - $ilUser = $this->user; - - $props = array(); - - return $props; - } - - - /** - * Get command link url. - * - * @param int $a_ref_id reference id - * @param string $a_cmd command - * - */ - function getCommandLink($a_cmd) - { - - if ($a_cmd == "infoScreen") - { - $cmd = "&cmd=infoScreenFrameset"; - } - - // separate method for this line - $cmd_link = "ilias.php?baseClass=ilMediaPoolPresentationGUI". - "&ref_id=".$this->ref_id.'&cmd='.$a_cmd; - - return $cmd_link; - } - - - + /** + * initialisation + */ + public function init() + { + $this->copy_enabled = true; + #$this->static_link_enabled = true; + $this->delete_enabled = true; + $this->cut_enabled = true; + $this->subscribe_enabled = true; + $this->link_enabled = true; + $this->info_screen_enabled = true; + $this->type = "mep"; + $this->gui_class_name = "ilobjmediapoolgui"; + + // general commands array + include_once('Modules/MediaPool/classes/class.ilObjMediaPoolAccess.php'); + $this->commands = ilObjMediaPoolAccess::_getCommands(); + } + + + /** + * inititialize new item + * + * @param int $a_ref_id reference id + * @param int $a_obj_id object id + * @param string $a_title title + * @param string $a_description description + */ + public function initItem($a_ref_id, $a_obj_id, $a_title = "", $a_description = "") + { + parent::initItem($a_ref_id, $a_obj_id, $a_title, $a_description); + } + + + /** + * Get command target frame + * + * @param string $a_cmd command + * + * @return string command target frame + */ + public function getCommandFrame($a_cmd) + { + switch ($a_cmd) { + case "": + $frame = ilFrameTargetInfo::_getFrame("MainContent"); + break; + + default: + } + + return $frame; + } + + + + /** + * Get item properties + * + * @return array array of property arrays: + * "alert" (boolean) => display as an alert property (usually in red) + * "property" (string) => property name + * "value" (string) => property value + */ + public function getProperties() + { + $lng = $this->lng; + $ilUser = $this->user; + + $props = array(); + + return $props; + } + + + /** + * Get command link url. + * + * @param int $a_ref_id reference id + * @param string $a_cmd command + * + */ + public function getCommandLink($a_cmd) + { + if ($a_cmd == "infoScreen") { + $cmd = "&cmd=infoScreenFrameset"; + } + + // separate method for this line + $cmd_link = "ilias.php?baseClass=ilMediaPoolPresentationGUI" . + "&ref_id=" . $this->ref_id . '&cmd=' . $a_cmd; + + return $cmd_link; + } } // END class.ilObjTestListGUI -?> diff --git a/Modules/MediaPool/classes/class.ilObjMediaPoolSubItemListGUI.php b/Modules/MediaPool/classes/class.ilObjMediaPoolSubItemListGUI.php index b46f9c5316b193488d75de9afda4de122347bff6..cfb178fdc61cdb8a97240490827555fe28549ab6 100644 --- a/Modules/MediaPool/classes/class.ilObjMediaPoolSubItemListGUI.php +++ b/Modules/MediaPool/classes/class.ilObjMediaPoolSubItemListGUI.php @@ -1,153 +1,144 @@ * @version $Id$ -* +* * * @ingroup ModulesMediaPool */ class ilObjMediaPoolSubItemListGUI extends ilSubItemListGUI { - /** - * get html - * @return - */ - public function getHTML() - { - $lng = $this->lng; - - $lng->loadLanguageModule('content'); - foreach($this->getSubItemIds(true) as $sub_item) - { - if(is_object($this->getHighlighter()) and strlen($this->getHighlighter()->getContent($this->getObjId(),$sub_item))) - { - $this->tpl->setCurrentBlock('sea_fragment'); - $this->tpl->setVariable('TXT_FRAGMENT',$this->getHighlighter()->getContent($this->getObjId(),$sub_item)); - $this->tpl->parseCurrentBlock(); - } - $this->tpl->setCurrentBlock('subitem'); - $this->tpl->setVariable('SEPERATOR',':'); - - include_once './Modules/MediaPool/classes/class.ilMediaPoolItem.php'; - switch(ilMediaPoolItem::lookupType($sub_item)) - { - case 'fold': - $this->tpl->setVariable('LINK',ilLink::_getLink($this->getRefId(),'mep',array(),'_'.$sub_item)); - $this->tpl->setVariable('TARGET',$this->getItemListGUI()->getCommandFrame('')); - break; - - case 'mob': - $this->tpl->setVariable('LINK', - $this->getItemListGUI()->getCommandLink('allMedia'). - '&force_filter='.$sub_item - ); - $this->tpl->setVariable('TARGET',$this->getItemListGUI()->getCommandFrame('')); - break; - - default: + /** + * get html + * @return + */ + public function getHTML() + { + $lng = $this->lng; + + $lng->loadLanguageModule('content'); + foreach ($this->getSubItemIds(true) as $sub_item) { + if (is_object($this->getHighlighter()) and strlen($this->getHighlighter()->getContent($this->getObjId(), $sub_item))) { + $this->tpl->setCurrentBlock('sea_fragment'); + $this->tpl->setVariable('TXT_FRAGMENT', $this->getHighlighter()->getContent($this->getObjId(), $sub_item)); + $this->tpl->parseCurrentBlock(); + } + $this->tpl->setCurrentBlock('subitem'); + $this->tpl->setVariable('SEPERATOR', ':'); + + include_once './Modules/MediaPool/classes/class.ilMediaPoolItem.php'; + switch (ilMediaPoolItem::lookupType($sub_item)) { + case 'fold': + $this->tpl->setVariable('LINK', ilLink::_getLink($this->getRefId(), 'mep', array(), '_' . $sub_item)); + $this->tpl->setVariable('TARGET', $this->getItemListGUI()->getCommandFrame('')); + break; + + case 'mob': + $this->tpl->setVariable( + 'LINK', + $this->getItemListGUI()->getCommandLink('allMedia') . + '&force_filter=' . $sub_item + ); + $this->tpl->setVariable('TARGET', $this->getItemListGUI()->getCommandFrame('')); + break; + + default: - } - - - $this->tpl->setVariable('SUBITEM_TYPE',$lng->txt('obj_'.ilMediaPoolItem::lookupType($sub_item))); - $this->tpl->setVariable('TITLE',ilMediaPoolItem::lookupTitle($sub_item)); - #$this->getItemListGUI()->setChildId($sub_item); - - // begin-patch mime_filter + } + + + $this->tpl->setVariable('SUBITEM_TYPE', $lng->txt('obj_' . ilMediaPoolItem::lookupType($sub_item))); + $this->tpl->setVariable('TITLE', ilMediaPoolItem::lookupTitle($sub_item)); + #$this->getItemListGUI()->setChildId($sub_item); + + // begin-patch mime_filter - if(!$this->parseImage($sub_item)) - { - include_once './Modules/MediaPool/classes/class.ilMediaPoolItem.php'; - $this->tpl->setVariable('SUBITEM_TYPE',$lng->txt('obj_'.ilMediaPoolItem::lookupType($sub_item))); - $this->tpl->setVariable('SEPERATOR',':'); - } - + if (!$this->parseImage($sub_item)) { + include_once './Modules/MediaPool/classes/class.ilMediaPoolItem.php'; + $this->tpl->setVariable('SUBITEM_TYPE', $lng->txt('obj_' . ilMediaPoolItem::lookupType($sub_item))); + $this->tpl->setVariable('SEPERATOR', ':'); + } + - if(count($this->getSubItemIds(true)) > 1) - { - $this->parseRelevance($sub_item); - } + if (count($this->getSubItemIds(true)) > 1) { + $this->parseRelevance($sub_item); + } - $this->tpl->parseCurrentBlock(); - } - - $this->showDetailsLink(); - - return $this->tpl->get(); - } - - protected function parseImage($a_sub_id) - { - include_once './Modules/MediaPool/classes/class.ilMediaPoolItem.php'; - $sub_id = ilMediaPoolItem::lookupForeignId($a_sub_id); - // output thumbnail (or mob icon) - if (ilObject::_lookupType($sub_id) == "mob") - { - include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); - $mob = new ilObjMediaObject($sub_id); - $med = $mob->getMediaItem("Standard"); - $target = $med->getThumbnailTarget(); - - if ($target != "") - { - // begin-patch mime_filter - $this->tpl->setVariable('LINKED_LINK', - ilLink::_getLink( - $this->getRefId(), - 'mep', - array('action' => 'showMedia', 'mob_id' => $sub_id,'mepitem_id' => $a_sub_id))); - $this->tpl->setVariable('LINKED_TARGET','_blank'); - $this->tpl->setVariable("LINKED_IMAGE", ilUtil::img($target)); - // end-patch mime_filter - } - else - { - $this->tpl->setVariable("SUB_ITEM_IMAGE",ilUtil::img(ilUtil::getImagePath("icon_".$a_set["type"].".gif"))); - } - if (ilUtil::deducibleSize($med->getFormat()) && $med->getLocationType() == "Reference") - { - $size = @getimagesize($med->getLocation()); - if ($size[0] > 0 && $size[1] > 0) - { - $wr = $size[0] / 80; - $hr = $size[1] / 80; - $r = max($wr, hr); - $w = (int) ($size[0]/$r); - $h = (int) ($size[1]/$r); - $this->tpl->setVariable("SUB_ITEM_IMAGE",ilUtil::img($med->getLocation(), "", $w, $h)); - return true; - } - } - } - return false; - - } + $this->tpl->parseCurrentBlock(); + } + + $this->showDetailsLink(); + + return $this->tpl->get(); + } + + protected function parseImage($a_sub_id) + { + include_once './Modules/MediaPool/classes/class.ilMediaPoolItem.php'; + $sub_id = ilMediaPoolItem::lookupForeignId($a_sub_id); + // output thumbnail (or mob icon) + if (ilObject::_lookupType($sub_id) == "mob") { + include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); + $mob = new ilObjMediaObject($sub_id); + $med = $mob->getMediaItem("Standard"); + $target = $med->getThumbnailTarget(); + + if ($target != "") { + // begin-patch mime_filter + $this->tpl->setVariable( + 'LINKED_LINK', + ilLink::_getLink( + $this->getRefId(), + 'mep', + array('action' => 'showMedia', 'mob_id' => $sub_id,'mepitem_id' => $a_sub_id) + ) + ); + $this->tpl->setVariable('LINKED_TARGET', '_blank'); + $this->tpl->setVariable("LINKED_IMAGE", ilUtil::img($target)); + // end-patch mime_filter + } else { + $this->tpl->setVariable("SUB_ITEM_IMAGE", ilUtil::img(ilUtil::getImagePath("icon_" . $a_set["type"] . ".gif"))); + } + if (ilUtil::deducibleSize($med->getFormat()) && $med->getLocationType() == "Reference") { + $size = @getimagesize($med->getLocation()); + if ($size[0] > 0 && $size[1] > 0) { + $wr = $size[0] / 80; + $hr = $size[1] / 80; + $r = max($wr, hr); + $w = (int) ($size[0]/$r); + $h = (int) ($size[1]/$r); + $this->tpl->setVariable("SUB_ITEM_IMAGE", ilUtil::img($med->getLocation(), "", $w, $h)); + return true; + } + } + } + return false; + } } -?> \ No newline at end of file diff --git a/Modules/MediaPool/classes/class.ilUploadDirFilesTableGUI.php b/Modules/MediaPool/classes/class.ilUploadDirFilesTableGUI.php index 837f565f45de0492cb77ec3876bffde5c0a5a398..506d5249f9d9abe5a33fdb4b288c1981def3503d 100644 --- a/Modules/MediaPool/classes/class.ilUploadDirFilesTableGUI.php +++ b/Modules/MediaPool/classes/class.ilUploadDirFilesTableGUI.php @@ -13,89 +13,81 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilUploadDirFilesTableGUI extends ilTable2GUI { - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_files) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_files) + { + 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(); - $mset = new ilSetting("mobs"); - $this->upload_dir = trim($mset->get("upload_dir")); + $mset = new ilSetting("mobs"); + $this->upload_dir = trim($mset->get("upload_dir")); -//var_dump($_POST); - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setData($this->getFiles($a_files)); - $this->setTitle($lng->txt("mep_upload_dir_files")); - $this->setLimit(9999); + //var_dump($_POST); + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setData($this->getFiles($a_files)); + $this->setTitle($lng->txt("mep_upload_dir_files")); + $this->setLimit(9999); - $this->addColumn("", "", "1", true); - $this->addColumn($this->lng->txt("mep_file")); - $this->setOpenFormTag(false); + $this->addColumn("", "", "1", true); + $this->addColumn($this->lng->txt("mep_file")); + $this->setOpenFormTag(false); - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.upload_dir_files_row.html", "Modules/MediaPool"); - $this->disable("footer"); - $this->setEnableTitle(true); - $this->setSelectAllCheckbox("file[]"); + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.upload_dir_files_row.html", "Modules/MediaPool"); + $this->disable("footer"); + $this->setEnableTitle(true); + $this->setSelectAllCheckbox("file[]"); - $this->addMultiCommand("createMediaFromUploadDir", $lng->txt("mep_create_media_files")); - //$this->addCommandButton("", $lng->txt("")); - } + $this->addMultiCommand("createMediaFromUploadDir", $lng->txt("mep_create_media_files")); + //$this->addCommandButton("", $lng->txt("")); + } - /** - * Get files - */ - function getFiles($a_files) - { - $files = array(); - foreach ($a_files as $f) - { - if (is_file($this->upload_dir."/".$f)) - { - $files[] = $f; - } - else if (is_dir($this->upload_dir."/".$f)) - { - $dir = ilUtil::getDir($this->upload_dir."/".$f, true); - foreach ($dir as $d) - { - if ($d["type"] == "file") - { - $files[] = $f.$d["subdir"]."/".$d["entry"]; - } - } - } - } + /** + * Get files + */ + public function getFiles($a_files) + { + $files = array(); + foreach ($a_files as $f) { + if (is_file($this->upload_dir . "/" . $f)) { + $files[] = $f; + } elseif (is_dir($this->upload_dir . "/" . $f)) { + $dir = ilUtil::getDir($this->upload_dir . "/" . $f, true); + foreach ($dir as $d) { + if ($d["type"] == "file") { + $files[] = $f . $d["subdir"] . "/" . $d["entry"]; + } + } + } + } - return $files; - } + return $files; + } - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - - $this->tpl->setVariable("TXT_FILE", $a_set); - $this->tpl->setVariable("VAL_FILE", $a_set); - } + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $this->tpl->setVariable("TXT_FILE", $a_set); + $this->tpl->setVariable("VAL_FILE", $a_set); + } } -?> diff --git a/Modules/Poll/classes/class.ilFSStoragePoll.php b/Modules/Poll/classes/class.ilFSStoragePoll.php index 354624d783c4d81c16c13f991843173bbe20666c..0ba426f19cde640ded0d946db17882c067daa646 100644 --- a/Modules/Poll/classes/class.ilFSStoragePoll.php +++ b/Modules/Poll/classes/class.ilFSStoragePoll.php @@ -1,50 +1,48 @@ - -* @version $Id$ -* -* @ingroup ModulesPoll -*/ -class ilFSStoragePoll extends ilFileSystemStorage -{ - public function __construct($a_container_id = 0) - { - parent::__construct(self::STORAGE_SECURED, true, $a_container_id); - } - - protected function getPathPostfix() - { - return 'poll'; - } - - protected function getPathPrefix() - { - return 'ilPoll'; - } -} - -?> \ No newline at end of file + +* @version $Id$ +* +* @ingroup ModulesPoll +*/ +class ilFSStoragePoll extends ilFileSystemStorage +{ + public function __construct($a_container_id = 0) + { + parent::__construct(self::STORAGE_SECURED, true, $a_container_id); + } + + protected function getPathPostfix() + { + return 'poll'; + } + + protected function getPathPrefix() + { + return 'ilPoll'; + } +} diff --git a/Modules/Poll/classes/class.ilObjPoll.php b/Modules/Poll/classes/class.ilObjPoll.php index 5e2f53ddd4deceb091ee7c6661740eeb2de30ba9..773c8271bf7dada205aa12812c74370bcced5fbc 100644 --- a/Modules/Poll/classes/class.ilObjPoll.php +++ b/Modules/Poll/classes/class.ilObjPoll.php @@ -1,827 +1,784 @@ - -* @version $Id: class.ilObjFolder.php 25528 2010-09-03 10:37:11Z smeyer $ -* -* @extends ilObject2 -*/ -class ilObjPoll extends ilObject2 -{ - protected $online; // [bool] - protected $access_type; // [int] - protected $access_begin; // [timestamp] - protected $access_end; // [timestamp] - protected $access_visibility; // [bool] - protected $question; // [string] - protected $image; // [string] - protected $view_results; // [int] - protected $period; // [bool] - protected $period_begin; // [timestamp] - protected $period_end; // [timestamp] - - // 4.5 - protected $max_number_answers = 1; // [int] - protected $result_sort_by_votes = false; // [bool] - protected $mode_non_anonymous = false; // [bool] - protected $show_comments = false; //[bool] - protected $show_results_as = 1; //[int] - - const VIEW_RESULTS_ALWAYS = 1; - const VIEW_RESULTS_NEVER = 2; - const VIEW_RESULTS_AFTER_VOTE = 3; - const VIEW_RESULTS_AFTER_PERIOD = 4; - - const SHOW_RESULTS_AS_BARCHART = 1; - const SHOW_RESULTS_AS_PIECHART = 2; - - function __construct($a_id = 0, $a_reference = true) - { - global $DIC; +db = $DIC->database(); - // default - $this->setOnline(false); - $this->setViewResults(self::VIEW_RESULTS_AFTER_VOTE); - $this->setAccessType(ilObjectActivation::TIMINGS_DEACTIVATED); - $this->setVotingPeriod(false); - - parent::__construct($a_id, $a_reference); - } - - function initType() - { - $this->type = "poll"; - } - - function setOnline($a_value) - { - $this->online = (bool)$a_value; - } - - function isOnline() - { - return $this->online; - } - - function setAccessType($a_value) - { - $this->access_type = (int)$a_value; - } - - function getAccessType() - { - return $this->access_type; - } - - function setAccessBegin($a_value) - { - $this->access_begin = (int)$a_value; - } - - function getAccessBegin() - { - return $this->access_begin; - } - - function setAccessEnd($a_value) - { - $this->access_end = (int)$a_value; - } - - function getAccessEnd() - { - return $this->access_end; - } - - function setAccessVisibility($a_value) - { - $this->access_visibility = (bool)$a_value; - } - - function getAccessVisibility() - { - return $this->access_visibility; - } - - function setQuestion($a_value) - { - $this->question = (string)$a_value; - } - - function getQuestion() - { - return $this->question; - } - - function setImage($a_value) - { - $this->image = (string)$a_value; - } - - function getImage() - { - return $this->image; - } - - function setViewResults($a_value) - { - $this->view_results = (int)$a_value; - } - - function getViewResults() - { - return $this->view_results; - } - - function setVotingPeriod($a_value) - { - $this->period = (bool)$a_value; - } - - function getVotingPeriod() - { - return $this->period; - } - - function setVotingPeriodBegin($a_value) - { - $this->period_begin = (int)$a_value; - } - - function getVotingPeriodBegin() - { - return $this->period_begin; - } - - function setVotingPeriodEnd($a_value) - { - $this->period_end = (int)$a_value; - } - - function getVotingPeriodEnd() - { - return $this->period_end; - } - - function setMaxNumberOfAnswers($a_value) - { - $this->max_number_answers = (int)$a_value; - } - - function getMaxNumberOfAnswers() - { - return $this->max_number_answers; - } - - function setSortResultByVotes($a_value) - { - $this->result_sort_by_votes = (bool)$a_value; - } - - function getSortResultByVotes() - { - return $this->result_sort_by_votes; - } - - function setNonAnonymous($a_value) - { - $this->mode_non_anonymous = (bool)$a_value; - } - - function getNonAnonymous() - { - return $this->mode_non_anonymous; - } - - function setShowComments($a_value) - { - $this->show_comments = (bool)$a_value; - } - - function getShowComments() - { - return $this->show_comments; - } - - function setShowResultsAs($a_value) - { - $this->show_results_as = (int)$a_value; - } - - function getShowResultsAs() - { - return $this->show_results_as; - } - - protected function doRead() - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT * FROM il_poll". - " WHERE id = ".$ilDB->quote($this->getId(), "integer")); - $row = $ilDB->fetchAssoc($set); - $this->setQuestion($row["question"]); - $this->setImage($row["image"]); - $this->setOnline($row["online_status"]); - $this->setViewResults($row["view_results"]); - $this->setVotingPeriod($row["period"]); - $this->setVotingPeriodBegin($row["period_begin"]); - $this->setVotingPeriodEnd($row["period_end"]); - $this->setMaxNumberOfAnswers($row["max_answers"]); - $this->setSortResultByVotes($row["result_sort"]); - $this->setNonAnonymous($row["non_anon"]); - $this->setShowResultsAs($row["show_results_as"]); - - // #14661 - include_once("./Services/Notes/classes/class.ilNote.php"); - $this->setShowComments(ilNote::commentsActivated($this->getId(), 0, $this->getType())); - - if($this->ref_id) - { - $activation = ilObjectActivation::getItem($this->ref_id); - $this->setAccessType($activation["timing_type"]); - if($this->getAccessType() == ilObjectActivation::TIMINGS_ACTIVATION) - { - // default entry values should not be loaded if not activated - $this->setAccessBegin($activation["timing_start"]); - $this->setAccessEnd($activation["timing_end"]); - $this->setAccessVisibility($activation["visible"]); - } - } - } - - protected function propertiesToDB() - { - $fields = array( - "question" => array("text", $this->getQuestion()), - "image" => array("text", $this->getImage()), - "online_status" => array("integer", $this->isOnline()), - "view_results" => array("integer", $this->getViewResults()), - "period" => array("integer", $this->getVotingPeriod()), - "period_begin" => array("integer", $this->getVotingPeriodBegin()), - "period_end" => array("integer", $this->getVotingPeriodEnd()), - "max_answers" => array("integer", $this->getMaxNumberOfAnswers()), - "result_sort" => array("integer", $this->getSortResultByVotes()), - "non_anon" => array("integer", $this->getNonAnonymous()), - "show_results_as" => array("integer", $this->getShowResultsAs()), - ); - - return $fields; - } - - protected function doCreate() - { - $ilDB = $this->db; - - if($this->getId()) - { - $fields = $this->propertiesToDB(); - $fields["id"] = array("integer", $this->getId()); - - $ilDB->insert("il_poll", $fields); - - - // object activation default entry will be created on demand - - - // block handling - include_once "Modules/Poll/classes/class.ilPollBlock.php"; - $block = new ilPollBlock(); - $block->setType("poll"); - $block->setContextObjId($this->getId()); - $block->setContextObjType("poll"); - $block->create(); - } - } - - protected function doUpdate() - { - $ilDB = $this->db; - - if($this->getId()) - { - $fields = $this->propertiesToDB(); - - $ilDB->update("il_poll", $fields, - array("id"=>array("integer", $this->getId()))); - - // #14661 - include_once("./Services/Notes/classes/class.ilNote.php"); - ilNote::activateComments($this->getId(), 0, $this->getType(), $this->getShowComments()); - - if($this->ref_id) - { - $activation = new ilObjectActivation(); - $activation->setTimingType($this->getAccessType()); - $activation->setTimingStart($this->getAccessBegin()); - $activation->setTimingEnd($this->getAccessEnd()); - $activation->toggleVisible($this->getAccessVisibility()); - $activation->update($this->ref_id); - } - - } - } - - protected function doDelete() - { - $ilDB = $this->db; - - if($this->getId()) - { - $this->deleteImage(); - $this->deleteAllAnswers(); - - if($this->ref_id) - { - ilObjectActivation::deleteAllEntries($this->ref_id); - } - - $ilDB->manipulate("DELETE FROM il_poll". - " WHERE id = ".$ilDB->quote($this->id, "integer")); - } - } - - /** - * Clone poll - * - * @param ilObjPoll new object - * @param int target ref_id - * @param int copy id - * @return ilObjPoll - */ - public function doCloneObject($new_obj, $a_target_id, $a_copy_id = 0) - { - assert($new_obj instanceof ilObjPoll); - - // question/image - $new_obj->setQuestion($this->getQuestion()); - $image = $this->getImageFullPath(); - if($image) - { - $image = array("tmp_name"=>$image, - "name"=>$this->getImage()); - $new_obj->uploadImage($image, true); - } - - //copy online status if object is not the root copy object - $cp_options = ilCopyWizardOptions::_getInstance($a_copy_id); - - if(!$cp_options->isRootNode($this->getRefId())) - { - $new_obj->setOnline($this->isOnline()); - } - - $new_obj->setViewResults($this->getViewResults()); - $new_obj->setShowComments($this->getShowComments()); - $new_obj->setShowResultsAs($this->getShowResultsAs()); - $new_obj->update(); - - // answers - $answers = $this->getAnswers(); - if($answers) - { - foreach($answers as $item) - { - $new_obj->saveAnswer($item["answer"]); - } - } - - return $new_obj; - } - - - // - // image - // - - /** - * Get image incl. path - * - * @param bool $a_as_thumb - */ - function getImageFullPath($a_as_thumb = false) - { - $img = $this->getImage(); - if($img) - { - $path = $this->initStorage($this->id); - if(!$a_as_thumb) - { - return $path.$img; - } - else - { - return $path."thb_".$img; - } - } - } - - /** - * remove existing file - */ - public function deleteImage() - { - if($this->id) - { - include_once "Modules/Poll/classes/class.ilFSStoragePoll.php"; - $storage = new ilFSStoragePoll($this->id); - $storage->delete(); - - $this->setImage(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/Poll/classes/class.ilFSStoragePoll.php"; - $storage = new ilFSStoragePoll($a_id); - $storage->create(); - - $path = $storage->getAbsolutePath()."/"; - - if($a_subdir) - { - $path .= $a_subdir."/"; - - if(!is_dir($path)) - { - mkdir($path); - } - } - - return $path; - } - - /** - * Upload new image file - * - * @param array $a_upload - * @return bool - */ - function uploadImage(array $a_upload, $a_clone = false) - { - if(!$this->id) - { - return false; - } - - $this->deleteImage(); - - // #10074 - $clean_name = preg_replace("/[^a-zA-Z0-9\_\.\-]/", "", $a_upload["name"]); - - $path = $this->initStorage($this->id); - $original = "org_".$this->id."_".$clean_name; - $thumb = "thb_".$this->id."_".$clean_name; - $processed = $this->id."_".$clean_name; - - $success = false; - if(!$a_clone) - { - $success = ilUtil::moveUploadedFile($a_upload["tmp_name"], $original, $path.$original); - } - else - { - $success = copy($a_upload["tmp_name"], $path.$original); - } - - if($success) - { - chmod($path.$original, 0770); - - // take quality 100 to avoid jpeg artefacts when uploading jpeg files - // taking only frame [0] to avoid problems with animated gifs - $original_file = ilUtil::escapeShellArg($path.$original); - $thumb_file = ilUtil::escapeShellArg($path.$thumb); - $processed_file = ilUtil::escapeShellArg($path.$processed); - ilUtil::execConvert($original_file."[0] -geometry \"100x100>\" -quality 100 PNG:".$thumb_file); - ilUtil::execConvert($original_file."[0] -geometry \"".self::getImageSize().">\" -quality 100 PNG:".$processed_file); - - $this->setImage($processed); - return true; - } - return false; - } - - public static function getImageSize() - { - // :TODO: - return "300x300"; - } - - - // - // Answer - // - - function getAnswers() - { - $ilDB = $this->db; - - $res = array(); - - $sql = "SELECT * FROM il_poll_answer". - " WHERE poll_id = ".$ilDB->quote($this->getId(), "integer"). - " ORDER BY pos ASC"; - $set = $ilDB->query($sql); - while($row = $ilDB->fetchAssoc($set)) - { - $res[] = $row; - } - return $res; - } - - function getAnswer($a_id) - { - $ilDB = $this->db; - - $sql = "SELECT * FROM il_poll_answer". - " WHERE id = ".$ilDB->quote($a_id, "integer"); - $set = $ilDB->query($sql); - return (array)$ilDB->fetchAssoc($set); - } - - function saveAnswer($a_text, $a_pos = null) - { - $ilDB = $this->db; - - if(!trim($a_text)) - { - return; - } - - $id = $ilDB->nextId("il_poll_answer"); - - if(!$a_pos) - { - // append - $sql = "SELECT max(pos) pos". - " FROM il_poll_answer". - " WHERE poll_id = ".$ilDB->quote($this->getId(), "integer"); - $set = $ilDB->query($sql); - $a_pos = $ilDB->fetchAssoc($set); - $a_pos = (int)$a_pos["pos"]+10; - } - - $fields = array( - "id" => array("integer", $id), - "poll_id" => array("integer", $this->getId()), - "answer" => array("text", trim($a_text)), - "pos" => array("integer", $a_pos) - ); - $ilDB->insert("il_poll_answer", $fields); - - return $id; - } - - function updateAnswer($a_id, $a_text) - { - $ilDB = $this->db; - - $ilDB->update("il_poll_answer", - array("answer" => array("text", $a_text)), - array("id" => array("integer", $a_id))); - } - - function rebuildAnswerPositions() - { - $answers = $this->getAnswers(); - - $pos = array(); - foreach($answers as $item) - { - $pos[$item["id"]] = $item["pos"]; - } - - $this->updateAnswerPositions($pos); - } - - function updateAnswerPositions(array $a_pos) - { - $ilDB = $this->db; - - asort($a_pos); - - $pos = 0; - foreach(array_keys($a_pos) as $id) - { - $pos += 10; - - $ilDB->update("il_poll_answer", - array("pos" => array("integer", $pos)), - array("id" => array("integer", $id))); - } - } - - function deleteAnswer($a_id) - { - $ilDB = $this->db; - - if($a_id) - { - $ilDB->manipulate("DELETE FROM il_poll_vote". - " WHERE answer_id = ".$ilDB->quote($this->getId(), "integer")); - - $ilDB->manipulate("DELETE FROM il_poll_answer". - " WHERE id = ".$ilDB->quote($a_id, "integer")); - } - } - - protected function deleteAllAnswers() - { - $ilDB = $this->db; - - if($this->getId()) - { - $this->deleteAllVotes(); - - $ilDB->manipulate("DELETE FROM il_poll_answer". - " WHERE poll_id = ".$ilDB->quote($this->getId(), "integer")); - } - } - - public function deleteAllVotes() - { - $ilDB = $this->db; - - if($this->getId()) - { - $ilDB->manipulate("DELETE FROM il_poll_vote". - " WHERE poll_id = ".$ilDB->quote($this->getId(), "integer")); - } - } - - function saveAnswers(array $a_answers) - { - $existing = $this->getAnswers(); - - $ids = array(); - $pos = 0; - foreach($a_answers as $answer) - { - if(trim($answer)) - { - // existing answer? - $found = false; - foreach($existing as $idx => $item) - { - if(trim($answer) == $item["answer"]) - { - $found = true; - unset($existing[$idx]); - - $id = $item["id"]; - } - } - - // create new answer - if(!$found) - { - $id = $this->saveAnswer($answer); - } - - // add existing answer id to order - if($id) - { - $ids[$id] = ++$pos; - } - } - } - - // remove obsolete answers - if(sizeof($existing)) - { - foreach($existing as $item) - { - $this->deleteAnswer($item["id"]); - } - } - - // save current order - if(sizeof($ids)) - { - $this->updateAnswerPositions($ids); - } - - return sizeof($ids); - } - - - // - // votes - // - - function saveVote($a_user_id, $a_answers) - { - $ilDB = $this->db; - - if($this->hasUserVoted($a_user_id)) - { - return; - } - - if(!is_array($a_answers)) - { - $a_answers = array($a_answers); - } - - foreach($a_answers as $answer_id) - { - $fields = array("user_id" => array("integer", $a_user_id), - "poll_id" => array("integer", $this->getId()), - "answer_id" => array("integer", $answer_id)); - $ilDB->insert("il_poll_vote", $fields); - } - } - - function hasUserVoted($a_user_id) - { - $ilDB = $this->db; - - $sql = "SELECT user_id". - " FROM il_poll_vote". - " WHERE poll_id = ".$ilDB->quote($this->getId(), "integer"). - " AND user_id = ".$ilDB->quote($a_user_id, "integer"); - $ilDB->setLimit(1); - $set = $ilDB->query($sql); - return (bool)$ilDB->numRows($set); - } - - function countVotes() - { - $ilDB = $this->db; - - $sql = "SELECT COUNT(DISTINCT(user_id)) cnt". - " FROM il_poll_vote". - " WHERE poll_id = ".$ilDB->quote($this->getId(), "integer"); - $set = $ilDB->query($sql); - $row = $ilDB->fetchAssoc($set); - return (int)$row["cnt"]; - } - - function getVotePercentages() - { - $ilDB = $this->db; - - $res = array(); - $cnt = 0; - - $sql = "SELECT answer_id, count(*) cnt". - " FROM il_poll_vote". - " WHERE poll_id = ".$ilDB->quote($this->getId(), "integer"). - " GROUP BY answer_id"; - $set = $ilDB->query($sql); - while($row = $ilDB->fetchAssoc($set)) - { - $cnt += $row["cnt"]; - $res[$row["answer_id"]] = array("abs"=>$row["cnt"], "perc"=>0); - } - - foreach($res as $id => $item) - { - $res[$id]["perc"] = $item["abs"]/$cnt*100; - } - - return array("perc"=>$res, "total"=>$this->countVotes()); - } - - public function getVotesByUsers() - { - $ilDB = $this->db; - - $res = array(); - - $sql = "SELECT answer_id, user_id, firstname, lastname, login". - " FROM il_poll_vote". - " JOIN usr_data ON (usr_data.usr_id = il_poll_vote.user_id)". - " WHERE poll_id = ".$ilDB->quote($this->getId(), "integer"); - $set = $ilDB->query($sql); - while($row = $ilDB->fetchAssoc($set)) - { - if(!isset($res[$row["user_id"]])) - { - $res[$row["user_id"]] = $row; - } - $res[$row["user_id"]]["answers"][] = $row["answer_id"]; - } - - return $res; - } -} - -?> \ No newline at end of file +/* Copyright (c) 1998-2009 ILIAS open source, Extended GPL, see docs/LICENSE */ + +require_once "Services/Object/classes/class.ilObject2.php"; +require_once "Services/Object/classes/class.ilObjectActivation.php"; + +/** +* Class ilObjPoll +* +* @author Jörg Lützenkirchen +* @version $Id: class.ilObjFolder.php 25528 2010-09-03 10:37:11Z smeyer $ +* +* @extends ilObject2 +*/ +class ilObjPoll extends ilObject2 +{ + protected $online; // [bool] + protected $access_type; // [int] + protected $access_begin; // [timestamp] + protected $access_end; // [timestamp] + protected $access_visibility; // [bool] + protected $question; // [string] + protected $image; // [string] + protected $view_results; // [int] + protected $period; // [bool] + protected $period_begin; // [timestamp] + protected $period_end; // [timestamp] + + // 4.5 + protected $max_number_answers = 1; // [int] + protected $result_sort_by_votes = false; // [bool] + protected $mode_non_anonymous = false; // [bool] + protected $show_comments = false; //[bool] + protected $show_results_as = 1; //[int] + + const VIEW_RESULTS_ALWAYS = 1; + const VIEW_RESULTS_NEVER = 2; + const VIEW_RESULTS_AFTER_VOTE = 3; + const VIEW_RESULTS_AFTER_PERIOD = 4; + + const SHOW_RESULTS_AS_BARCHART = 1; + const SHOW_RESULTS_AS_PIECHART = 2; + + public function __construct($a_id = 0, $a_reference = true) + { + global $DIC; + + $this->db = $DIC->database(); + // default + $this->setOnline(false); + $this->setViewResults(self::VIEW_RESULTS_AFTER_VOTE); + $this->setAccessType(ilObjectActivation::TIMINGS_DEACTIVATED); + $this->setVotingPeriod(false); + + parent::__construct($a_id, $a_reference); + } + + public function initType() + { + $this->type = "poll"; + } + + public function setOnline($a_value) + { + $this->online = (bool) $a_value; + } + + public function isOnline() + { + return $this->online; + } + + public function setAccessType($a_value) + { + $this->access_type = (int) $a_value; + } + + public function getAccessType() + { + return $this->access_type; + } + + public function setAccessBegin($a_value) + { + $this->access_begin = (int) $a_value; + } + + public function getAccessBegin() + { + return $this->access_begin; + } + + public function setAccessEnd($a_value) + { + $this->access_end = (int) $a_value; + } + + public function getAccessEnd() + { + return $this->access_end; + } + + public function setAccessVisibility($a_value) + { + $this->access_visibility = (bool) $a_value; + } + + public function getAccessVisibility() + { + return $this->access_visibility; + } + + public function setQuestion($a_value) + { + $this->question = (string) $a_value; + } + + public function getQuestion() + { + return $this->question; + } + + public function setImage($a_value) + { + $this->image = (string) $a_value; + } + + public function getImage() + { + return $this->image; + } + + public function setViewResults($a_value) + { + $this->view_results = (int) $a_value; + } + + public function getViewResults() + { + return $this->view_results; + } + + public function setVotingPeriod($a_value) + { + $this->period = (bool) $a_value; + } + + public function getVotingPeriod() + { + return $this->period; + } + + public function setVotingPeriodBegin($a_value) + { + $this->period_begin = (int) $a_value; + } + + public function getVotingPeriodBegin() + { + return $this->period_begin; + } + + public function setVotingPeriodEnd($a_value) + { + $this->period_end = (int) $a_value; + } + + public function getVotingPeriodEnd() + { + return $this->period_end; + } + + public function setMaxNumberOfAnswers($a_value) + { + $this->max_number_answers = (int) $a_value; + } + + public function getMaxNumberOfAnswers() + { + return $this->max_number_answers; + } + + public function setSortResultByVotes($a_value) + { + $this->result_sort_by_votes = (bool) $a_value; + } + + public function getSortResultByVotes() + { + return $this->result_sort_by_votes; + } + + public function setNonAnonymous($a_value) + { + $this->mode_non_anonymous = (bool) $a_value; + } + + public function getNonAnonymous() + { + return $this->mode_non_anonymous; + } + + public function setShowComments($a_value) + { + $this->show_comments = (bool) $a_value; + } + + public function getShowComments() + { + return $this->show_comments; + } + + public function setShowResultsAs($a_value) + { + $this->show_results_as = (int) $a_value; + } + + public function getShowResultsAs() + { + return $this->show_results_as; + } + + protected function doRead() + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT * FROM il_poll" . + " WHERE id = " . $ilDB->quote($this->getId(), "integer")); + $row = $ilDB->fetchAssoc($set); + $this->setQuestion($row["question"]); + $this->setImage($row["image"]); + $this->setOnline($row["online_status"]); + $this->setViewResults($row["view_results"]); + $this->setVotingPeriod($row["period"]); + $this->setVotingPeriodBegin($row["period_begin"]); + $this->setVotingPeriodEnd($row["period_end"]); + $this->setMaxNumberOfAnswers($row["max_answers"]); + $this->setSortResultByVotes($row["result_sort"]); + $this->setNonAnonymous($row["non_anon"]); + $this->setShowResultsAs($row["show_results_as"]); + + // #14661 + include_once("./Services/Notes/classes/class.ilNote.php"); + $this->setShowComments(ilNote::commentsActivated($this->getId(), 0, $this->getType())); + + if ($this->ref_id) { + $activation = ilObjectActivation::getItem($this->ref_id); + $this->setAccessType($activation["timing_type"]); + if ($this->getAccessType() == ilObjectActivation::TIMINGS_ACTIVATION) { + // default entry values should not be loaded if not activated + $this->setAccessBegin($activation["timing_start"]); + $this->setAccessEnd($activation["timing_end"]); + $this->setAccessVisibility($activation["visible"]); + } + } + } + + protected function propertiesToDB() + { + $fields = array( + "question" => array("text", $this->getQuestion()), + "image" => array("text", $this->getImage()), + "online_status" => array("integer", $this->isOnline()), + "view_results" => array("integer", $this->getViewResults()), + "period" => array("integer", $this->getVotingPeriod()), + "period_begin" => array("integer", $this->getVotingPeriodBegin()), + "period_end" => array("integer", $this->getVotingPeriodEnd()), + "max_answers" => array("integer", $this->getMaxNumberOfAnswers()), + "result_sort" => array("integer", $this->getSortResultByVotes()), + "non_anon" => array("integer", $this->getNonAnonymous()), + "show_results_as" => array("integer", $this->getShowResultsAs()), + ); + + return $fields; + } + + protected function doCreate() + { + $ilDB = $this->db; + + if ($this->getId()) { + $fields = $this->propertiesToDB(); + $fields["id"] = array("integer", $this->getId()); + + $ilDB->insert("il_poll", $fields); + + + // object activation default entry will be created on demand + + + // block handling + include_once "Modules/Poll/classes/class.ilPollBlock.php"; + $block = new ilPollBlock(); + $block->setType("poll"); + $block->setContextObjId($this->getId()); + $block->setContextObjType("poll"); + $block->create(); + } + } + + protected function doUpdate() + { + $ilDB = $this->db; + + if ($this->getId()) { + $fields = $this->propertiesToDB(); + + $ilDB->update( + "il_poll", + $fields, + array("id"=>array("integer", $this->getId())) + ); + + // #14661 + include_once("./Services/Notes/classes/class.ilNote.php"); + ilNote::activateComments($this->getId(), 0, $this->getType(), $this->getShowComments()); + + if ($this->ref_id) { + $activation = new ilObjectActivation(); + $activation->setTimingType($this->getAccessType()); + $activation->setTimingStart($this->getAccessBegin()); + $activation->setTimingEnd($this->getAccessEnd()); + $activation->toggleVisible($this->getAccessVisibility()); + $activation->update($this->ref_id); + } + } + } + + protected function doDelete() + { + $ilDB = $this->db; + + if ($this->getId()) { + $this->deleteImage(); + $this->deleteAllAnswers(); + + if ($this->ref_id) { + ilObjectActivation::deleteAllEntries($this->ref_id); + } + + $ilDB->manipulate("DELETE FROM il_poll" . + " WHERE id = " . $ilDB->quote($this->id, "integer")); + } + } + + /** + * Clone poll + * + * @param ilObjPoll new object + * @param int target ref_id + * @param int copy id + * @return ilObjPoll + */ + public function doCloneObject($new_obj, $a_target_id, $a_copy_id = 0) + { + assert($new_obj instanceof ilObjPoll); + + // question/image + $new_obj->setQuestion($this->getQuestion()); + $image = $this->getImageFullPath(); + if ($image) { + $image = array("tmp_name"=>$image, + "name"=>$this->getImage()); + $new_obj->uploadImage($image, true); + } + + //copy online status if object is not the root copy object + $cp_options = ilCopyWizardOptions::_getInstance($a_copy_id); + + if (!$cp_options->isRootNode($this->getRefId())) { + $new_obj->setOnline($this->isOnline()); + } + + $new_obj->setViewResults($this->getViewResults()); + $new_obj->setShowComments($this->getShowComments()); + $new_obj->setShowResultsAs($this->getShowResultsAs()); + $new_obj->update(); + + // answers + $answers = $this->getAnswers(); + if ($answers) { + foreach ($answers as $item) { + $new_obj->saveAnswer($item["answer"]); + } + } + + return $new_obj; + } + + + // + // image + // + + /** + * Get image incl. path + * + * @param bool $a_as_thumb + */ + public function getImageFullPath($a_as_thumb = false) + { + $img = $this->getImage(); + if ($img) { + $path = $this->initStorage($this->id); + if (!$a_as_thumb) { + return $path . $img; + } else { + return $path . "thb_" . $img; + } + } + } + + /** + * remove existing file + */ + public function deleteImage() + { + if ($this->id) { + include_once "Modules/Poll/classes/class.ilFSStoragePoll.php"; + $storage = new ilFSStoragePoll($this->id); + $storage->delete(); + + $this->setImage(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/Poll/classes/class.ilFSStoragePoll.php"; + $storage = new ilFSStoragePoll($a_id); + $storage->create(); + + $path = $storage->getAbsolutePath() . "/"; + + if ($a_subdir) { + $path .= $a_subdir . "/"; + + if (!is_dir($path)) { + mkdir($path); + } + } + + return $path; + } + + /** + * Upload new image file + * + * @param array $a_upload + * @return bool + */ + public function uploadImage(array $a_upload, $a_clone = false) + { + if (!$this->id) { + return false; + } + + $this->deleteImage(); + + // #10074 + $clean_name = preg_replace("/[^a-zA-Z0-9\_\.\-]/", "", $a_upload["name"]); + + $path = $this->initStorage($this->id); + $original = "org_" . $this->id . "_" . $clean_name; + $thumb = "thb_" . $this->id . "_" . $clean_name; + $processed = $this->id . "_" . $clean_name; + + $success = false; + if (!$a_clone) { + $success = ilUtil::moveUploadedFile($a_upload["tmp_name"], $original, $path . $original); + } else { + $success = copy($a_upload["tmp_name"], $path . $original); + } + + if ($success) { + chmod($path . $original, 0770); + + // take quality 100 to avoid jpeg artefacts when uploading jpeg files + // taking only frame [0] to avoid problems with animated gifs + $original_file = ilUtil::escapeShellArg($path . $original); + $thumb_file = ilUtil::escapeShellArg($path . $thumb); + $processed_file = ilUtil::escapeShellArg($path . $processed); + ilUtil::execConvert($original_file . "[0] -geometry \"100x100>\" -quality 100 PNG:" . $thumb_file); + ilUtil::execConvert($original_file . "[0] -geometry \"" . self::getImageSize() . ">\" -quality 100 PNG:" . $processed_file); + + $this->setImage($processed); + return true; + } + return false; + } + + public static function getImageSize() + { + // :TODO: + return "300x300"; + } + + + // + // Answer + // + + public function getAnswers() + { + $ilDB = $this->db; + + $res = array(); + + $sql = "SELECT * FROM il_poll_answer" . + " WHERE poll_id = " . $ilDB->quote($this->getId(), "integer") . + " ORDER BY pos ASC"; + $set = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($set)) { + $res[] = $row; + } + return $res; + } + + public function getAnswer($a_id) + { + $ilDB = $this->db; + + $sql = "SELECT * FROM il_poll_answer" . + " WHERE id = " . $ilDB->quote($a_id, "integer"); + $set = $ilDB->query($sql); + return (array) $ilDB->fetchAssoc($set); + } + + public function saveAnswer($a_text, $a_pos = null) + { + $ilDB = $this->db; + + if (!trim($a_text)) { + return; + } + + $id = $ilDB->nextId("il_poll_answer"); + + if (!$a_pos) { + // append + $sql = "SELECT max(pos) pos" . + " FROM il_poll_answer" . + " WHERE poll_id = " . $ilDB->quote($this->getId(), "integer"); + $set = $ilDB->query($sql); + $a_pos = $ilDB->fetchAssoc($set); + $a_pos = (int) $a_pos["pos"]+10; + } + + $fields = array( + "id" => array("integer", $id), + "poll_id" => array("integer", $this->getId()), + "answer" => array("text", trim($a_text)), + "pos" => array("integer", $a_pos) + ); + $ilDB->insert("il_poll_answer", $fields); + + return $id; + } + + public function updateAnswer($a_id, $a_text) + { + $ilDB = $this->db; + + $ilDB->update( + "il_poll_answer", + array("answer" => array("text", $a_text)), + array("id" => array("integer", $a_id)) + ); + } + + public function rebuildAnswerPositions() + { + $answers = $this->getAnswers(); + + $pos = array(); + foreach ($answers as $item) { + $pos[$item["id"]] = $item["pos"]; + } + + $this->updateAnswerPositions($pos); + } + + public function updateAnswerPositions(array $a_pos) + { + $ilDB = $this->db; + + asort($a_pos); + + $pos = 0; + foreach (array_keys($a_pos) as $id) { + $pos += 10; + + $ilDB->update( + "il_poll_answer", + array("pos" => array("integer", $pos)), + array("id" => array("integer", $id)) + ); + } + } + + public function deleteAnswer($a_id) + { + $ilDB = $this->db; + + if ($a_id) { + $ilDB->manipulate("DELETE FROM il_poll_vote" . + " WHERE answer_id = " . $ilDB->quote($this->getId(), "integer")); + + $ilDB->manipulate("DELETE FROM il_poll_answer" . + " WHERE id = " . $ilDB->quote($a_id, "integer")); + } + } + + protected function deleteAllAnswers() + { + $ilDB = $this->db; + + if ($this->getId()) { + $this->deleteAllVotes(); + + $ilDB->manipulate("DELETE FROM il_poll_answer" . + " WHERE poll_id = " . $ilDB->quote($this->getId(), "integer")); + } + } + + public function deleteAllVotes() + { + $ilDB = $this->db; + + if ($this->getId()) { + $ilDB->manipulate("DELETE FROM il_poll_vote" . + " WHERE poll_id = " . $ilDB->quote($this->getId(), "integer")); + } + } + + public function saveAnswers(array $a_answers) + { + $existing = $this->getAnswers(); + + $ids = array(); + $pos = 0; + foreach ($a_answers as $answer) { + if (trim($answer)) { + // existing answer? + $found = false; + foreach ($existing as $idx => $item) { + if (trim($answer) == $item["answer"]) { + $found = true; + unset($existing[$idx]); + + $id = $item["id"]; + } + } + + // create new answer + if (!$found) { + $id = $this->saveAnswer($answer); + } + + // add existing answer id to order + if ($id) { + $ids[$id] = ++$pos; + } + } + } + + // remove obsolete answers + if (sizeof($existing)) { + foreach ($existing as $item) { + $this->deleteAnswer($item["id"]); + } + } + + // save current order + if (sizeof($ids)) { + $this->updateAnswerPositions($ids); + } + + return sizeof($ids); + } + + + // + // votes + // + + public function saveVote($a_user_id, $a_answers) + { + $ilDB = $this->db; + + if ($this->hasUserVoted($a_user_id)) { + return; + } + + if (!is_array($a_answers)) { + $a_answers = array($a_answers); + } + + foreach ($a_answers as $answer_id) { + $fields = array("user_id" => array("integer", $a_user_id), + "poll_id" => array("integer", $this->getId()), + "answer_id" => array("integer", $answer_id)); + $ilDB->insert("il_poll_vote", $fields); + } + } + + public function hasUserVoted($a_user_id) + { + $ilDB = $this->db; + + $sql = "SELECT user_id" . + " FROM il_poll_vote" . + " WHERE poll_id = " . $ilDB->quote($this->getId(), "integer") . + " AND user_id = " . $ilDB->quote($a_user_id, "integer"); + $ilDB->setLimit(1); + $set = $ilDB->query($sql); + return (bool) $ilDB->numRows($set); + } + + public function countVotes() + { + $ilDB = $this->db; + + $sql = "SELECT COUNT(DISTINCT(user_id)) cnt" . + " FROM il_poll_vote" . + " WHERE poll_id = " . $ilDB->quote($this->getId(), "integer"); + $set = $ilDB->query($sql); + $row = $ilDB->fetchAssoc($set); + return (int) $row["cnt"]; + } + + public function getVotePercentages() + { + $ilDB = $this->db; + + $res = array(); + $cnt = 0; + + $sql = "SELECT answer_id, count(*) cnt" . + " FROM il_poll_vote" . + " WHERE poll_id = " . $ilDB->quote($this->getId(), "integer") . + " GROUP BY answer_id"; + $set = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($set)) { + $cnt += $row["cnt"]; + $res[$row["answer_id"]] = array("abs"=>$row["cnt"], "perc"=>0); + } + + foreach ($res as $id => $item) { + $res[$id]["perc"] = $item["abs"]/$cnt*100; + } + + return array("perc"=>$res, "total"=>$this->countVotes()); + } + + public function getVotesByUsers() + { + $ilDB = $this->db; + + $res = array(); + + $sql = "SELECT answer_id, user_id, firstname, lastname, login" . + " FROM il_poll_vote" . + " JOIN usr_data ON (usr_data.usr_id = il_poll_vote.user_id)" . + " WHERE poll_id = " . $ilDB->quote($this->getId(), "integer"); + $set = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($set)) { + if (!isset($res[$row["user_id"]])) { + $res[$row["user_id"]] = $row; + } + $res[$row["user_id"]]["answers"][] = $row["answer_id"]; + } + + return $res; + } +} diff --git a/Modules/Poll/classes/class.ilObjPollAccess.php b/Modules/Poll/classes/class.ilObjPollAccess.php index 84233f257c515927f262bac472cb2d345658d5af..17f6cb6c195a5f57a640e8823c314d97b901a4bd 100644 --- a/Modules/Poll/classes/class.ilObjPollAccess.php +++ b/Modules/Poll/classes/class.ilObjPollAccess.php @@ -1,194 +1,187 @@ - -* @version $Id: class.ilObjRootFolderAccess.php 15678 2008-01-06 20:40:55Z akill $ -* -*/ -class ilObjPollAccess extends ilObjectAccess implements ilWACCheckingClass -{ - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilAccessHandler - */ - protected $access; - - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->user = $DIC->user(); - $this->lng = $DIC->language(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->access = $DIC->access(); - } - - /** - * checks wether a user may invoke a command or not - * (this method is called by ilAccessHandler::checkAccess) - * - * @param string $a_cmd command (not permission!) - * @param string $a_permission permission - * @param int $a_ref_id reference id - * @param int $a_obj_id object id - * @param int $a_user_id user id (if not provided, current user is taken) - * - * @return boolean true, if everything is ok - */ - function _checkAccess($a_cmd, $a_permission, $a_ref_id, $a_obj_id, $a_user_id = "") - { - $ilUser = $this->user; - $lng = $this->lng; - $rbacsystem = $this->rbacsystem; - $ilAccess = $this->access; - - if ($a_user_id == "") - { - $a_user_id = $ilUser->getId(); - } - - // check "global" online switch - if(!self::_lookupOnline($a_obj_id) && - !$rbacsystem->checkAccessOfUser($a_user_id,'write',$a_ref_id)) - { - $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("offline")); - return false; - } - - return true; - } - - /** - * get status - */ - public static function _lookupOnline($a_obj_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $result = $ilDB->query("SELECT * FROM il_poll". - " WHERE id = ".$ilDB->quote($a_obj_id, "integer")); - $row = $ilDB->fetchAssoc($result); - return $row["online_status"]; - } - - /** - * Is activated? - * - * @param int $a_obj_id - * @param int $a_ref_id - * @return boolean - */ - public static function _isActivated($a_ref_id) - { - include_once './Services/Object/classes/class.ilObjectActivation.php'; - $item = ilObjectActivation::getItem($a_ref_id); - switch($item['timing_type']) - { - case ilObjectActivation::TIMINGS_ACTIVATION: - if(time() < $item['timing_start'] or - time() > $item['timing_end']) - { - return false; - } - // fallthrough - - default: - return true; - } - } - - /** - * 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" => "write", "cmd" => "export", "lang_var" => "export") - ); - - return $commands; - } - - /** - * check whether goto script will succeed - */ - static function _checkGoto($a_target) - { - global $DIC; - - $ilAccess = $DIC->access(); - - $t_arr = explode("_", $a_target); - - if ($t_arr[0] != "poll" || ((int) $t_arr[1]) <= 0) - { - return false; - } - - if ($ilAccess->checkAccess("read", "", $t_arr[1])) - { - return true; - } - return false; - } - - - /** - * @param ilWACPath $ilWACPath - * - * @return bool - */ - public function canBeDelivered(ilWACPath $ilWACPath) { - $ilAccess = $this->access; - preg_match("/\\/poll_([\\d]*)\\//uism", $ilWACPath->getPath(), $results); - - foreach (ilObject2::_getAllReferences($results[1]) as $ref_id) { - if ($ilAccess->checkAccess('read', '', $ref_id)) { - return true; - } - } - - return false; - } -} - -?> + +* @version $Id: class.ilObjRootFolderAccess.php 15678 2008-01-06 20:40:55Z akill $ +* +*/ +class ilObjPollAccess extends ilObjectAccess implements ilWACCheckingClass +{ + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilAccessHandler + */ + protected $access; + + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->user = $DIC->user(); + $this->lng = $DIC->language(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->access = $DIC->access(); + } + + /** + * checks wether a user may invoke a command or not + * (this method is called by ilAccessHandler::checkAccess) + * + * @param string $a_cmd command (not permission!) + * @param string $a_permission permission + * @param int $a_ref_id reference id + * @param int $a_obj_id object id + * @param int $a_user_id user id (if not provided, current user is taken) + * + * @return boolean true, if everything is ok + */ + public function _checkAccess($a_cmd, $a_permission, $a_ref_id, $a_obj_id, $a_user_id = "") + { + $ilUser = $this->user; + $lng = $this->lng; + $rbacsystem = $this->rbacsystem; + $ilAccess = $this->access; + + if ($a_user_id == "") { + $a_user_id = $ilUser->getId(); + } + + // check "global" online switch + if (!self::_lookupOnline($a_obj_id) && + !$rbacsystem->checkAccessOfUser($a_user_id, 'write', $a_ref_id)) { + $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("offline")); + return false; + } + + return true; + } + + /** + * get status + */ + public static function _lookupOnline($a_obj_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $result = $ilDB->query("SELECT * FROM il_poll" . + " WHERE id = " . $ilDB->quote($a_obj_id, "integer")); + $row = $ilDB->fetchAssoc($result); + return $row["online_status"]; + } + + /** + * Is activated? + * + * @param int $a_obj_id + * @param int $a_ref_id + * @return boolean + */ + public static function _isActivated($a_ref_id) + { + include_once './Services/Object/classes/class.ilObjectActivation.php'; + $item = ilObjectActivation::getItem($a_ref_id); + switch ($item['timing_type']) { + case ilObjectActivation::TIMINGS_ACTIVATION: + if (time() < $item['timing_start'] or + time() > $item['timing_end']) { + return false; + } + // fallthrough + + // no break + default: + return true; + } + } + + /** + * 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" => "write", "cmd" => "export", "lang_var" => "export") + ); + + 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 ($t_arr[0] != "poll" || ((int) $t_arr[1]) <= 0) { + return false; + } + + if ($ilAccess->checkAccess("read", "", $t_arr[1])) { + return true; + } + return false; + } + + + /** + * @param ilWACPath $ilWACPath + * + * @return bool + */ + public function canBeDelivered(ilWACPath $ilWACPath) + { + $ilAccess = $this->access; + preg_match("/\\/poll_([\\d]*)\\//uism", $ilWACPath->getPath(), $results); + + foreach (ilObject2::_getAllReferences($results[1]) as $ref_id) { + if ($ilAccess->checkAccess('read', '', $ref_id)) { + return true; + } + } + + return false; + } +} diff --git a/Modules/Poll/classes/class.ilObjPollGUI.php b/Modules/Poll/classes/class.ilObjPollGUI.php index bb6adaeae9b1367dfc877294d2cab616e5f0cc34..2a9aa9f64d83670dbd933dfbe7d5365582584fa9 100644 --- a/Modules/Poll/classes/class.ilObjPollGUI.php +++ b/Modules/Poll/classes/class.ilObjPollGUI.php @@ -1,737 +1,721 @@ - -* $Id: class.ilObjFolderGUI.php 25134 2010-08-13 14:22:11Z smeyer $ -* -* @ilCtrl_Calls ilObjPollGUI: ilInfoScreenGUI, ilNoteGUI, ilCommonActionDispatcherGUI -* @ilCtrl_Calls ilObjPollGUI: ilPermissionGUI, ilObjectCopyGUI, ilExportGUI -* -* @extends ilObject2GUI -*/ -class ilObjPollGUI extends ilObject2GUI -{ - /** - * @var ilHelpGUI - */ - protected $help; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilNavigationHistory - */ - protected $nav_history; - - /** - * @var \ILIAS\DI\Container - */ - protected $ui; - - function __construct($a_id = 0, $a_id_type = self::REPOSITORY_NODE_ID, $a_parent_node_id = 0) - { - global $DIC; - - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $this->help = $DIC["ilHelp"]; - $this->tpl = $DIC["tpl"]; - $this->tabs = $DIC->tabs(); - $this->nav_history = $DIC["ilNavigationHistory"]; - $this->toolbar = $DIC->toolbar(); - $this->user = $DIC->user(); - $this->tree = $DIC->repositoryTree(); - $this->locator = $DIC["ilLocator"]; - $lng = $DIC->language(); - $this->ui = $DIC->ui(); - - parent::__construct($a_id, $a_id_type, $a_parent_node_id); - - $lng->loadLanguageModule("poll"); - } - - function getType() - { - return "poll"; - } - - protected function afterSave(ilObject $a_new_object) - { - $ilCtrl = $this->ctrl; - - ilUtil::sendSuccess($this->lng->txt("object_added"), true); - $ilCtrl->redirect($this, "render"); - } - - protected function initEditCustomForm(ilPropertyFormGUI $a_form) - { - $lng = $this->lng; - - // activation - - include_once "Services/Object/classes/class.ilObjectActivation.php"; - $this->lng->loadLanguageModule('rep'); - - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($this->lng->txt('rep_activation_availability')); - $a_form->addItem($section); - - // additional info only with multiple references - $act_obj_info = $act_ref_info = ""; - if(sizeof(ilObject::_getAllReferences($this->object->getId())) > 1) - { - $act_obj_info = ' '.$this->lng->txt('rep_activation_online_object_info'); - $act_ref_info = $this->lng->txt('rep_activation_access_ref_info'); - } - - $online = new ilCheckboxInputGUI($this->lng->txt('rep_activation_online'),'online'); - $online->setInfo($this->lng->txt('poll_activation_online_info').$act_obj_info); - $a_form->addItem($online); - - include_once "Services/Form/classes/class.ilDateDurationInputGUI.php"; - $dur = new ilDateDurationInputGUI($this->lng->txt('rep_visibility_until'), "access_period"); - $dur->setShowTime(true); - $a_form->addItem($dur); - - - // period/results - - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($this->lng->txt('poll_voting_period_and_results')); - $a_form->addItem($section); - - $vdur = new ilDateDurationInputGUI($this->lng->txt('poll_voting_period_limited'), "voting_period"); - $vdur->setShowTime(true); - $a_form->addItem($vdur); - - $results = new ilRadioGroupInputGUI($lng->txt("poll_view_results"), "results"); - $results->setRequired(true); - $results->addOption(new ilRadioOption($lng->txt("poll_view_results_always"), - ilObjPoll::VIEW_RESULTS_ALWAYS)); - $results->addOption(new ilRadioOption($lng->txt("poll_view_results_never"), - ilObjPoll::VIEW_RESULTS_NEVER)); - $results->addOption(new ilRadioOption($lng->txt("poll_view_results_after_vote"), - ilObjPoll::VIEW_RESULTS_AFTER_VOTE)); - $results->addOption(new ilRadioOption($lng->txt("poll_view_results_after_period"), - ilObjPoll::VIEW_RESULTS_AFTER_PERIOD)); - $a_form->addItem($results); - - $show_result_as = new ilRadioGroupInputGUI($lng->txt("poll_show_results_as"), "show_results_as"); - $show_result_as->setRequired(true); - $result_bar = new ilRadioOption($lng->txt("poll_barchart"), - ilObjPoll::SHOW_RESULTS_AS_BARCHART); - $show_result_as->addOption($result_bar); - $show_result_as->addOption(new ilRadioOption($lng->txt("poll_piechart"), - ilObjPoll::SHOW_RESULTS_AS_PIECHART)); - $a_form->addItem($show_result_as); - - $sort = new ilRadioGroupInputGUI($lng->txt("poll_result_sorting"), "sort"); - $sort->setRequired(true); - $sort->addOption(new ilRadioOption($lng->txt("poll_result_sorting_answers"), 0)); - $sort->addOption(new ilRadioOption($lng->txt("poll_result_sorting_votes"), 1)); - $a_form->addItem($sort); - - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($this->lng->txt('poll_comments')); - $a_form->addItem($section); - - $comment = new ilCheckboxInputGUI($this->lng->txt('poll_comments'), 'comment'); - //$comment->setInfo($this->lng->txt('poll_comments_info')); - $a_form->addItem($comment); - } - - protected function getEditFormCustomValues(array &$a_values) - { - include_once "Services/Object/classes/class.ilObjectActivation.php"; - - $a_values["online"] = $this->object->IsOnline(); - $a_values["results"] = $this->object->getViewResults(); - $a_values["access_period"]["start"] = $this->object->getAccessBegin() - ? new ilDateTime($this->object->getAccessBegin(), IL_CAL_UNIX) - : null; - $a_values["access_period"]["end"] = $this->object->getAccessEnd() - ? new ilDateTime($this->object->getAccessEnd(), IL_CAL_UNIX) - : null; - $a_values["voting_period"]["start"] = $this->object->getVotingPeriodBegin() - ? new ilDateTime($this->object->getVotingPeriodBegin(), IL_CAL_UNIX) - : null; - $a_values["voting_period"]["end"] = $this->object->getVotingPeriodEnd() - ? new ilDateTime($this->object->getVotingPeriodEnd(), IL_CAL_UNIX) - : null; - $a_values["sort"] = $this->object->getSortResultByVotes(); - $a_values["comment"] = $this->object->getShowComments(); - $a_values["show_results_as"] = $this->object->getShowResultsAs(); - } - - protected function validateCustom(ilPropertyFormGUI $a_form) - { - #20594 - if(!$a_form->getInput("voting_period") && - $a_form->getInput("results") == ilObjPoll::VIEW_RESULTS_AFTER_PERIOD) - { - ilUtil::sendFailure($this->lng->txt("form_input_not_valid")); - $a_form->getItemByPostVar("results")->setAlert($this->lng->txt("poll_view_results_after_period_impossible")); - return false; - } - return parent::validateCustom($a_form); - } - - protected function updateCustom(ilPropertyFormGUI $a_form) - { - $this->object->setViewResults($a_form->getInput("results")); - $this->object->setOnline($a_form->getInput("online")); - $this->object->setSortResultByVotes($a_form->getInput("sort")); - $this->object->setShowComments($a_form->getInput("comment")); - $this->object->setShowResultsAs($a_form->getInput("show_results_as")); - - include_once "Services/Object/classes/class.ilObjectActivation.php"; - $period = $a_form->getItemByPostVar("access_period"); - if($period->getStart() && $period->getEnd()) - { - $this->object->setAccessType(ilObjectActivation::TIMINGS_ACTIVATION); - $this->object->setAccessBegin($period->getStart()->get(IL_CAL_UNIX)); - $this->object->setAccessEnd($period->getEnd()->get(IL_CAL_UNIX)); - } - else - { - $this->object->setAccessType(ilObjectActivation::TIMINGS_DEACTIVATED); - } - - $period = $a_form->getItemByPostVar("voting_period"); - if($period->getStart() && $period->getEnd()) - { - $this->object->setVotingPeriod(1); - $this->object->setVotingPeriodBegin($period->getStart()->get(IL_CAL_UNIX)); - $this->object->setVotingPeriodEnd($period->getEnd()->get(IL_CAL_UNIX)); - } - else - { - $this->object->setVotingPeriodBegin(null); - $this->object->setVotingPeriodEnd(null); - $this->object->setVotingPeriod(0); - } - } - - function setTabs() - { - $lng = $this->lng; - $ilHelp = $this->help; - - $ilHelp->setScreenIdComponent("poll"); - - if ($this->checkPermissionBool("write")) - { - $this->tabs_gui->addTab("content", - $lng->txt("content"), - $this->ctrl->getLinkTarget($this, "")); - } - - if ($this->checkPermissionBool("write")) - { - $this->tabs_gui->addTab("settings", - $lng->txt("settings"), - $this->ctrl->getLinkTarget($this, "edit")); - - $this->tabs_gui->addTab("participants", - $lng->txt("poll_result"), - $this->ctrl->getLinkTarget($this, "showParticipants")); - - $this->tabs_gui->addTab("export", - $lng->txt("export"), - $this->ctrl->getLinkTargetByClass("ilexportgui", "")); - } - - // will add permissions if needed - parent::setTabs(); - } - - function executeCommand() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - $ilNavigationHistory = $this->nav_history; - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd(); - - $tpl->getStandardTemplate(); - - // add entry to navigation history - if(!$this->getCreationMode() && - $this->getAccessHandler()->checkAccess("read", "", $this->node_id)) - { - $link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", "frameset"); - $ilNavigationHistory->addItem($this->node_id, $link, "poll"); - } - - switch($next_class) - { - case "ilinfoscreengui": - $this->prepareOutput(); - $this->infoScreenForward(); - 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": - include_once "./Services/Object/classes/class.ilObjectCopyGUI.php"; - $cp = new ilObjectCopyGUI($this); - $cp->setType("poll"); - $this->ctrl->forwardCommand($cp); - 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"); - $ilCtrl->forwardCommand($exp_gui); - break; - - default: - return parent::executeCommand(); - } - - return true; - } - - - // --- ObjectGUI End - - - /** - * Render object context - */ - function render($a_form = null) - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilToolbar = $this->toolbar; - $ilUser = $this->user; - $ui = $this->ui; - - if(!$this->checkPermissionBool("write")) - { - ilUtil::sendInfo($lng->txt("no_permission")); - return; - } - - $ilTabs->activateTab("content"); - - if(!$a_form) - { - if($this->object->countVotes()) - { - $url = $ilCtrl->getLinkTarget($this, "showParticipants"); - - $mbox = $ui->factory()->messageBox()->info($lng->txt("poll_votes_no_edit")) - ->withLinks([$ui->factory()->link()->standard($lng->txt("poll_result"), - $url)]); - - $message = $ui->renderer()->render($mbox); - - } - - $a_form = $this->initQuestionForm($this->object->countVotes()); - } - - $tpl->setPermanentLink('poll', $this->node_id); - - $tpl->setContent($message.$a_form->getHTML()); - } - - protected function initQuestionForm($a_read_only = false) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this, "saveQuestion")); - $form->setTitle($lng->txt("obj_poll")); - - $question = new ilTextAreaInputGUI($lng->txt("poll_question"), "question"); - $question->setRequired(true); - $question->setCols(40); - $question->setRows(2); - $question->setValue($this->object->getQuestion()); - $question->setDisabled($a_read_only); - $form->addItem($question); - - $dimensions = " (".ilObjPoll::getImageSize()."px)"; - $img = new ilImageFileInputGUI($lng->txt("poll_image").$dimensions, "image"); - $img->setDisabled($a_read_only); - $form->addItem($img); - - // show existing file - $file = $this->object->getImageFullPath(true); - if($file) - { - $img->setImage($file); - } - - $anonymous = new ilRadioGroupInputGUI($lng->txt("poll_mode"), "mode"); - $anonymous->setRequired(true); - $option = new ilRadioOption($lng->txt("poll_mode_anonymous"), 0); - $option->setInfo($lng->txt("poll_mode_anonymous_info")); - $anonymous->addOption($option); - $option = new ilRadioOption($lng->txt("poll_mode_personal"), 1); - $option->setInfo($lng->txt("poll_mode_personal_info")); - $anonymous->addOption($option); - $anonymous->setValue($this->object->getNonAnonymous()); - $anonymous->setDisabled($a_read_only); - $form->addItem($anonymous); - - $nanswers = new ilNumberInputGUI($lng->txt("poll_max_number_of_answers"), "nanswers"); - $nanswers->setRequired(true); - $nanswers->setMinValue(1); - $nanswers->setSize(3); - $nanswers->setValue($this->object->getMaxNumberOfAnswers()); - $nanswers->setDisabled($a_read_only); - $form->addItem($nanswers); - - $answers = new ilTextInputGUI($lng->txt("poll_answers"), "answers"); - $answers->setRequired(true); - $answers->setMulti(true, true); - $answers->setDisabled($a_read_only); - $form->addItem($answers); - - $multi_answers = array(); - foreach($this->object->getAnswers() as $idx => $item) - { - if(!$idx) - { - $answers->setValue($item["answer"]); - } - $multi_answers[] = $item["answer"]; - } - $answers->setMultiValues($multi_answers); - - if(!$a_read_only) - { - $form->addCommandButton("saveQuestion", $lng->txt("save")); - } - - return $form; - } - - function saveQuestion() - { - $form = $this->initQuestionForm(); - if($form->checkInput()) - { - $this->object->setQuestion($form->getInput("question")); - $this->object->setNonAnonymous($form->getInput("mode")); - - $image = $form->getItemByPostVar("image"); - if($_FILES["image"]["tmp_name"]) - { - $this->object->uploadImage($_FILES["image"]); - } - else if($image->getDeletionFlag()) - { - $this->object->deleteImage(); - } - - $nr_of_anwers = $this->object->saveAnswers($form->getInput("answers")); - - // #15073 - $this->object->setMaxNumberOfAnswers(min($form->getInput("nanswers"), $nr_of_anwers)); - - if($this->object->update()) - { - ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); - $this->ctrl->redirect($this, "render"); - } - } - - $form->setValuesByPost(); - $this->render($form); - } - - protected function setParticipantsSubTabs($a_active) - { - $ilTabs = $this->tabs; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if(!$this->object->getNonAnonymous()) - { - return; - } - - $ilTabs->addSubTab("result_answers", $lng->txt("poll_result_answers"), - $ilCtrl->getLinkTarget($this, "showParticipants")); - $ilTabs->addSubTab("result_users", $lng->txt("poll_result_users"), - $ilCtrl->getLinkTarget($this, "showParticipantVotes")); - - $ilTabs->activateSubTab($a_active); - } - - function showParticipants() - { - $lng = $this->lng; - $ilTabs = $this->tabs; - $tpl = $this->tpl; - - if(!$this->checkPermissionBool("write")) - { - ilUtil::sendInfo($lng->txt("no_permission")); - return; - } - - $ilTabs->activateTab("participants"); - $this->setParticipantsSubTabs("result_answers"); - - include_once "Modules/Poll/classes/class.ilPollAnswerTableGUI.php"; - $tbl = new ilPollAnswerTableGUI($this, "showParticipants"); - $tpl->setContent($tbl->getHTML()); - } - - function showParticipantVotes() - { - $ilTabs = $this->tabs; - $lng = $this->lng; - $tpl = $this->tpl; - - if(!$this->checkPermissionBool("write") || - !$this->object->getNonAnonymous()) - { - ilUtil::sendInfo($lng->txt("no_permission")); - return; - } - - $ilTabs->activateTab("participants"); - $this->setParticipantsSubTabs("result_users"); - - include_once "Modules/Poll/classes/class.ilPollUserTableGUI.php"; - $tbl = new ilPollUserTableGUI($this, "showParticipantVotes"); - $tpl->setContent($tbl->getHTML()); - } - - function confirmDeleteAllVotes() - { - $lng = $this->lng; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - if(!$this->checkPermissionBool("write")) - { - ilUtil::sendInfo($lng->txt("no_permission")); - return; - } - - $ilTabs->activateTab("participants"); - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setHeaderText($lng->txt("poll_delete_votes_sure")); - - $cgui->setFormAction($this->ctrl->getFormAction($this)); - $cgui->setCancel($lng->txt("cancel"), "showParticipants"); - $cgui->setConfirm($lng->txt("confirm"), "deleteAllVotes"); - - $tpl->setContent($cgui->getHTML()); - } - - function deleteAllVotes() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if(!$this->checkPermissionBool("write")) - { - ilUtil::sendInfo($lng->txt("no_permission")); - return; - } - - $this->object->deleteAllVotes(); - - $ilCtrl->redirect($this, "showParticipants"); - } - - function vote() - { - $tree = $this->tree; - $ilUser = $this->user; - - $valid = true; - if($this->object->getMaxNumberOfAnswers() > 1) - { - if(sizeof($_POST["aw"]) > $this->object->getMaxNumberOfAnswers()) - { - $valid = false; - } - if(!sizeof($_POST["aw"])) - { - $valid = false; - } - } - else - { - if((int)!$_POST["aw"]) - { - $valid = false; - } - } - - if($valid) - { - unset($_SESSION["last_poll_vote"][$this->object->getId()]); - $this->object->saveVote($ilUser->getId(), $_POST["aw"]); - - $this->sendNotifications(); - } - else - { - $_SESSION["last_poll_vote"][$this->object->getId()] = $_POST["aw"]; - } - - include_once "Services/Link/classes/class.ilLink.php"; - ilUtil::redirect(ilLink::_getLink($tree->getParentId($this->ref_id))); - } - - function subscribe() - { - $ilUser = $this->user; - $tree = $this->tree; - $lng = $this->lng; - - include_once "./Services/Notification/classes/class.ilNotification.php"; - ilNotification::setNotification(ilNotification::TYPE_POLL, $ilUser->getId(), $this->object->getId(), true); - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - include_once "Services/Link/classes/class.ilLink.php"; - ilUtil::redirect(ilLink::_getLink($tree->getParentId($this->ref_id))); - } - - function unsubscribe() - { - $ilUser = $this->user; - $tree = $this->tree; - $lng = $this->lng; - - include_once "./Services/Notification/classes/class.ilNotification.php"; - ilNotification::setNotification(ilNotification::TYPE_POLL, $ilUser->getId(), $this->object->getId(), false); - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - include_once "Services/Link/classes/class.ilLink.php"; - ilUtil::redirect(ilLink::_getLink($tree->getParentId($this->ref_id))); - } - - protected function sendNotifications() - { - $ilUser = $this->user; - - // recipients - include_once "./Services/Notification/classes/class.ilNotification.php"; - $users = ilNotification::getNotificationsForObject(ilNotification::TYPE_POLL, - $this->object->getId(), null, true); - if(!sizeof($users)) - { - return; - } - - include_once "./Services/Notification/classes/class.ilSystemNotification.php"; - $ntf = new ilSystemNotification(); - $ntf->setLangModules(array("poll")); - $ntf->setRefId($this->ref_id); - - if($this->object->getNonAnonymous()) - { - $ntf->setChangedByUserId($ilUser->getId()); - } - - $ntf->setSubjectLangId('poll_vote_notification_subject'); - $ntf->setIntroductionLangId('poll_vote_notification_body'); - $ntf->setGotoLangId('poll_vote_notification_link'); - $ntf->setReasonLangId('poll_vote_notification_reason'); - - $notified = $ntf->sendMail($users, null, "read"); - - ilNotification::updateNotificationTime(ilNotification::TYPE_POLL, $this->object->getId(), $notified); - } - - /** - * return user view - * - * @return string - */ - function getHTML() - { - - } - - function addLocatorItems() - { - $ilLocator = $this->locator; - - if (is_object($this->object)) - { - $ilLocator->addItem($this->object->getTitle(), $this->ctrl->getLinkTarget($this, ""), "", $this->node_id); - } - } - - /** - * Deep link - * - * @param string $a_target - */ - public static function _goto($a_target) - { - global $DIC; - - $tree = $DIC->repositoryTree(); - $ilAccess = $DIC->access(); - - $id = explode("_", $a_target); - $ref_id = $id[0]; - - // #13728 - used in notification mostly - if ($ilAccess->checkAccess("write", "", $ref_id)) - { - $_GET["baseClass"] = "ilRepositoryGUI"; - $_GET["ref_id"] = $ref_id; - $_GET["cmd"] = "showParticipants"; - include("ilias.php"); - exit; - } - else - { - // is sideblock: so show parent instead - $container_id = $tree->getParentId($ref_id); - - // #11810 - include_once "Services/Link/classes/class.ilLink.php"; - ilUtil::redirect(ilLink::_getLink($container_id). - "#poll".ilObject::_lookupObjId($id[0])); - } - } -} - -?> \ No newline at end of file + +* $Id: class.ilObjFolderGUI.php 25134 2010-08-13 14:22:11Z smeyer $ +* +* @ilCtrl_Calls ilObjPollGUI: ilInfoScreenGUI, ilNoteGUI, ilCommonActionDispatcherGUI +* @ilCtrl_Calls ilObjPollGUI: ilPermissionGUI, ilObjectCopyGUI, ilExportGUI +* +* @extends ilObject2GUI +*/ +class ilObjPollGUI extends ilObject2GUI +{ + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilNavigationHistory + */ + protected $nav_history; + + /** + * @var \ILIAS\DI\Container + */ + protected $ui; + + public function __construct($a_id = 0, $a_id_type = self::REPOSITORY_NODE_ID, $a_parent_node_id = 0) + { + global $DIC; + + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->help = $DIC["ilHelp"]; + $this->tpl = $DIC["tpl"]; + $this->tabs = $DIC->tabs(); + $this->nav_history = $DIC["ilNavigationHistory"]; + $this->toolbar = $DIC->toolbar(); + $this->user = $DIC->user(); + $this->tree = $DIC->repositoryTree(); + $this->locator = $DIC["ilLocator"]; + $lng = $DIC->language(); + $this->ui = $DIC->ui(); + + parent::__construct($a_id, $a_id_type, $a_parent_node_id); + + $lng->loadLanguageModule("poll"); + } + + public function getType() + { + return "poll"; + } + + protected function afterSave(ilObject $a_new_object) + { + $ilCtrl = $this->ctrl; + + ilUtil::sendSuccess($this->lng->txt("object_added"), true); + $ilCtrl->redirect($this, "render"); + } + + protected function initEditCustomForm(ilPropertyFormGUI $a_form) + { + $lng = $this->lng; + + // activation + + include_once "Services/Object/classes/class.ilObjectActivation.php"; + $this->lng->loadLanguageModule('rep'); + + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($this->lng->txt('rep_activation_availability')); + $a_form->addItem($section); + + // additional info only with multiple references + $act_obj_info = $act_ref_info = ""; + if (sizeof(ilObject::_getAllReferences($this->object->getId())) > 1) { + $act_obj_info = ' ' . $this->lng->txt('rep_activation_online_object_info'); + $act_ref_info = $this->lng->txt('rep_activation_access_ref_info'); + } + + $online = new ilCheckboxInputGUI($this->lng->txt('rep_activation_online'), 'online'); + $online->setInfo($this->lng->txt('poll_activation_online_info') . $act_obj_info); + $a_form->addItem($online); + + include_once "Services/Form/classes/class.ilDateDurationInputGUI.php"; + $dur = new ilDateDurationInputGUI($this->lng->txt('rep_visibility_until'), "access_period"); + $dur->setShowTime(true); + $a_form->addItem($dur); + + + // period/results + + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($this->lng->txt('poll_voting_period_and_results')); + $a_form->addItem($section); + + $vdur = new ilDateDurationInputGUI($this->lng->txt('poll_voting_period_limited'), "voting_period"); + $vdur->setShowTime(true); + $a_form->addItem($vdur); + + $results = new ilRadioGroupInputGUI($lng->txt("poll_view_results"), "results"); + $results->setRequired(true); + $results->addOption(new ilRadioOption( + $lng->txt("poll_view_results_always"), + ilObjPoll::VIEW_RESULTS_ALWAYS + )); + $results->addOption(new ilRadioOption( + $lng->txt("poll_view_results_never"), + ilObjPoll::VIEW_RESULTS_NEVER + )); + $results->addOption(new ilRadioOption( + $lng->txt("poll_view_results_after_vote"), + ilObjPoll::VIEW_RESULTS_AFTER_VOTE + )); + $results->addOption(new ilRadioOption( + $lng->txt("poll_view_results_after_period"), + ilObjPoll::VIEW_RESULTS_AFTER_PERIOD + )); + $a_form->addItem($results); + + $show_result_as = new ilRadioGroupInputGUI($lng->txt("poll_show_results_as"), "show_results_as"); + $show_result_as->setRequired(true); + $result_bar = new ilRadioOption( + $lng->txt("poll_barchart"), + ilObjPoll::SHOW_RESULTS_AS_BARCHART + ); + $show_result_as->addOption($result_bar); + $show_result_as->addOption(new ilRadioOption( + $lng->txt("poll_piechart"), + ilObjPoll::SHOW_RESULTS_AS_PIECHART + )); + $a_form->addItem($show_result_as); + + $sort = new ilRadioGroupInputGUI($lng->txt("poll_result_sorting"), "sort"); + $sort->setRequired(true); + $sort->addOption(new ilRadioOption($lng->txt("poll_result_sorting_answers"), 0)); + $sort->addOption(new ilRadioOption($lng->txt("poll_result_sorting_votes"), 1)); + $a_form->addItem($sort); + + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($this->lng->txt('poll_comments')); + $a_form->addItem($section); + + $comment = new ilCheckboxInputGUI($this->lng->txt('poll_comments'), 'comment'); + //$comment->setInfo($this->lng->txt('poll_comments_info')); + $a_form->addItem($comment); + } + + protected function getEditFormCustomValues(array &$a_values) + { + include_once "Services/Object/classes/class.ilObjectActivation.php"; + + $a_values["online"] = $this->object->IsOnline(); + $a_values["results"] = $this->object->getViewResults(); + $a_values["access_period"]["start"] = $this->object->getAccessBegin() + ? new ilDateTime($this->object->getAccessBegin(), IL_CAL_UNIX) + : null; + $a_values["access_period"]["end"] = $this->object->getAccessEnd() + ? new ilDateTime($this->object->getAccessEnd(), IL_CAL_UNIX) + : null; + $a_values["voting_period"]["start"] = $this->object->getVotingPeriodBegin() + ? new ilDateTime($this->object->getVotingPeriodBegin(), IL_CAL_UNIX) + : null; + $a_values["voting_period"]["end"] = $this->object->getVotingPeriodEnd() + ? new ilDateTime($this->object->getVotingPeriodEnd(), IL_CAL_UNIX) + : null; + $a_values["sort"] = $this->object->getSortResultByVotes(); + $a_values["comment"] = $this->object->getShowComments(); + $a_values["show_results_as"] = $this->object->getShowResultsAs(); + } + + protected function validateCustom(ilPropertyFormGUI $a_form) + { + #20594 + if (!$a_form->getInput("voting_period") && + $a_form->getInput("results") == ilObjPoll::VIEW_RESULTS_AFTER_PERIOD) { + ilUtil::sendFailure($this->lng->txt("form_input_not_valid")); + $a_form->getItemByPostVar("results")->setAlert($this->lng->txt("poll_view_results_after_period_impossible")); + return false; + } + return parent::validateCustom($a_form); + } + + protected function updateCustom(ilPropertyFormGUI $a_form) + { + $this->object->setViewResults($a_form->getInput("results")); + $this->object->setOnline($a_form->getInput("online")); + $this->object->setSortResultByVotes($a_form->getInput("sort")); + $this->object->setShowComments($a_form->getInput("comment")); + $this->object->setShowResultsAs($a_form->getInput("show_results_as")); + + include_once "Services/Object/classes/class.ilObjectActivation.php"; + $period = $a_form->getItemByPostVar("access_period"); + if ($period->getStart() && $period->getEnd()) { + $this->object->setAccessType(ilObjectActivation::TIMINGS_ACTIVATION); + $this->object->setAccessBegin($period->getStart()->get(IL_CAL_UNIX)); + $this->object->setAccessEnd($period->getEnd()->get(IL_CAL_UNIX)); + } else { + $this->object->setAccessType(ilObjectActivation::TIMINGS_DEACTIVATED); + } + + $period = $a_form->getItemByPostVar("voting_period"); + if ($period->getStart() && $period->getEnd()) { + $this->object->setVotingPeriod(1); + $this->object->setVotingPeriodBegin($period->getStart()->get(IL_CAL_UNIX)); + $this->object->setVotingPeriodEnd($period->getEnd()->get(IL_CAL_UNIX)); + } else { + $this->object->setVotingPeriodBegin(null); + $this->object->setVotingPeriodEnd(null); + $this->object->setVotingPeriod(0); + } + } + + public function setTabs() + { + $lng = $this->lng; + $ilHelp = $this->help; + + $ilHelp->setScreenIdComponent("poll"); + + if ($this->checkPermissionBool("write")) { + $this->tabs_gui->addTab( + "content", + $lng->txt("content"), + $this->ctrl->getLinkTarget($this, "") + ); + } + + if ($this->checkPermissionBool("write")) { + $this->tabs_gui->addTab( + "settings", + $lng->txt("settings"), + $this->ctrl->getLinkTarget($this, "edit") + ); + + $this->tabs_gui->addTab( + "participants", + $lng->txt("poll_result"), + $this->ctrl->getLinkTarget($this, "showParticipants") + ); + + $this->tabs_gui->addTab( + "export", + $lng->txt("export"), + $this->ctrl->getLinkTargetByClass("ilexportgui", "") + ); + } + + // will add permissions if needed + parent::setTabs(); + } + + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + $ilNavigationHistory = $this->nav_history; + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd(); + + $tpl->getStandardTemplate(); + + // add entry to navigation history + if (!$this->getCreationMode() && + $this->getAccessHandler()->checkAccess("read", "", $this->node_id)) { + $link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", "frameset"); + $ilNavigationHistory->addItem($this->node_id, $link, "poll"); + } + + switch ($next_class) { + case "ilinfoscreengui": + $this->prepareOutput(); + $this->infoScreenForward(); + 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": + include_once "./Services/Object/classes/class.ilObjectCopyGUI.php"; + $cp = new ilObjectCopyGUI($this); + $cp->setType("poll"); + $this->ctrl->forwardCommand($cp); + 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"); + $ilCtrl->forwardCommand($exp_gui); + break; + + default: + return parent::executeCommand(); + } + + return true; + } + + + // --- ObjectGUI End + + + /** + * Render object context + */ + public function render($a_form = null) + { + $tpl = $this->tpl; + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilToolbar = $this->toolbar; + $ilUser = $this->user; + $ui = $this->ui; + + if (!$this->checkPermissionBool("write")) { + ilUtil::sendInfo($lng->txt("no_permission")); + return; + } + + $ilTabs->activateTab("content"); + + if (!$a_form) { + if ($this->object->countVotes()) { + $url = $ilCtrl->getLinkTarget($this, "showParticipants"); + + $mbox = $ui->factory()->messageBox()->info($lng->txt("poll_votes_no_edit")) + ->withLinks([$ui->factory()->link()->standard( + $lng->txt("poll_result"), + $url + )]); + + $message = $ui->renderer()->render($mbox); + } + + $a_form = $this->initQuestionForm($this->object->countVotes()); + } + + $tpl->setPermanentLink('poll', $this->node_id); + + $tpl->setContent($message . $a_form->getHTML()); + } + + protected function initQuestionForm($a_read_only = false) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this, "saveQuestion")); + $form->setTitle($lng->txt("obj_poll")); + + $question = new ilTextAreaInputGUI($lng->txt("poll_question"), "question"); + $question->setRequired(true); + $question->setCols(40); + $question->setRows(2); + $question->setValue($this->object->getQuestion()); + $question->setDisabled($a_read_only); + $form->addItem($question); + + $dimensions = " (" . ilObjPoll::getImageSize() . "px)"; + $img = new ilImageFileInputGUI($lng->txt("poll_image") . $dimensions, "image"); + $img->setDisabled($a_read_only); + $form->addItem($img); + + // show existing file + $file = $this->object->getImageFullPath(true); + if ($file) { + $img->setImage($file); + } + + $anonymous = new ilRadioGroupInputGUI($lng->txt("poll_mode"), "mode"); + $anonymous->setRequired(true); + $option = new ilRadioOption($lng->txt("poll_mode_anonymous"), 0); + $option->setInfo($lng->txt("poll_mode_anonymous_info")); + $anonymous->addOption($option); + $option = new ilRadioOption($lng->txt("poll_mode_personal"), 1); + $option->setInfo($lng->txt("poll_mode_personal_info")); + $anonymous->addOption($option); + $anonymous->setValue($this->object->getNonAnonymous()); + $anonymous->setDisabled($a_read_only); + $form->addItem($anonymous); + + $nanswers = new ilNumberInputGUI($lng->txt("poll_max_number_of_answers"), "nanswers"); + $nanswers->setRequired(true); + $nanswers->setMinValue(1); + $nanswers->setSize(3); + $nanswers->setValue($this->object->getMaxNumberOfAnswers()); + $nanswers->setDisabled($a_read_only); + $form->addItem($nanswers); + + $answers = new ilTextInputGUI($lng->txt("poll_answers"), "answers"); + $answers->setRequired(true); + $answers->setMulti(true, true); + $answers->setDisabled($a_read_only); + $form->addItem($answers); + + $multi_answers = array(); + foreach ($this->object->getAnswers() as $idx => $item) { + if (!$idx) { + $answers->setValue($item["answer"]); + } + $multi_answers[] = $item["answer"]; + } + $answers->setMultiValues($multi_answers); + + if (!$a_read_only) { + $form->addCommandButton("saveQuestion", $lng->txt("save")); + } + + return $form; + } + + public function saveQuestion() + { + $form = $this->initQuestionForm(); + if ($form->checkInput()) { + $this->object->setQuestion($form->getInput("question")); + $this->object->setNonAnonymous($form->getInput("mode")); + + $image = $form->getItemByPostVar("image"); + if ($_FILES["image"]["tmp_name"]) { + $this->object->uploadImage($_FILES["image"]); + } elseif ($image->getDeletionFlag()) { + $this->object->deleteImage(); + } + + $nr_of_anwers = $this->object->saveAnswers($form->getInput("answers")); + + // #15073 + $this->object->setMaxNumberOfAnswers(min($form->getInput("nanswers"), $nr_of_anwers)); + + if ($this->object->update()) { + ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); + $this->ctrl->redirect($this, "render"); + } + } + + $form->setValuesByPost(); + $this->render($form); + } + + protected function setParticipantsSubTabs($a_active) + { + $ilTabs = $this->tabs; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if (!$this->object->getNonAnonymous()) { + return; + } + + $ilTabs->addSubTab( + "result_answers", + $lng->txt("poll_result_answers"), + $ilCtrl->getLinkTarget($this, "showParticipants") + ); + $ilTabs->addSubTab( + "result_users", + $lng->txt("poll_result_users"), + $ilCtrl->getLinkTarget($this, "showParticipantVotes") + ); + + $ilTabs->activateSubTab($a_active); + } + + public function showParticipants() + { + $lng = $this->lng; + $ilTabs = $this->tabs; + $tpl = $this->tpl; + + if (!$this->checkPermissionBool("write")) { + ilUtil::sendInfo($lng->txt("no_permission")); + return; + } + + $ilTabs->activateTab("participants"); + $this->setParticipantsSubTabs("result_answers"); + + include_once "Modules/Poll/classes/class.ilPollAnswerTableGUI.php"; + $tbl = new ilPollAnswerTableGUI($this, "showParticipants"); + $tpl->setContent($tbl->getHTML()); + } + + public function showParticipantVotes() + { + $ilTabs = $this->tabs; + $lng = $this->lng; + $tpl = $this->tpl; + + if (!$this->checkPermissionBool("write") || + !$this->object->getNonAnonymous()) { + ilUtil::sendInfo($lng->txt("no_permission")); + return; + } + + $ilTabs->activateTab("participants"); + $this->setParticipantsSubTabs("result_users"); + + include_once "Modules/Poll/classes/class.ilPollUserTableGUI.php"; + $tbl = new ilPollUserTableGUI($this, "showParticipantVotes"); + $tpl->setContent($tbl->getHTML()); + } + + public function confirmDeleteAllVotes() + { + $lng = $this->lng; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + if (!$this->checkPermissionBool("write")) { + ilUtil::sendInfo($lng->txt("no_permission")); + return; + } + + $ilTabs->activateTab("participants"); + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setHeaderText($lng->txt("poll_delete_votes_sure")); + + $cgui->setFormAction($this->ctrl->getFormAction($this)); + $cgui->setCancel($lng->txt("cancel"), "showParticipants"); + $cgui->setConfirm($lng->txt("confirm"), "deleteAllVotes"); + + $tpl->setContent($cgui->getHTML()); + } + + public function deleteAllVotes() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if (!$this->checkPermissionBool("write")) { + ilUtil::sendInfo($lng->txt("no_permission")); + return; + } + + $this->object->deleteAllVotes(); + + $ilCtrl->redirect($this, "showParticipants"); + } + + public function vote() + { + $tree = $this->tree; + $ilUser = $this->user; + + $valid = true; + if ($this->object->getMaxNumberOfAnswers() > 1) { + if (sizeof($_POST["aw"]) > $this->object->getMaxNumberOfAnswers()) { + $valid = false; + } + if (!sizeof($_POST["aw"])) { + $valid = false; + } + } else { + if ((int) !$_POST["aw"]) { + $valid = false; + } + } + + if ($valid) { + unset($_SESSION["last_poll_vote"][$this->object->getId()]); + $this->object->saveVote($ilUser->getId(), $_POST["aw"]); + + $this->sendNotifications(); + } else { + $_SESSION["last_poll_vote"][$this->object->getId()] = $_POST["aw"]; + } + + include_once "Services/Link/classes/class.ilLink.php"; + ilUtil::redirect(ilLink::_getLink($tree->getParentId($this->ref_id))); + } + + public function subscribe() + { + $ilUser = $this->user; + $tree = $this->tree; + $lng = $this->lng; + + include_once "./Services/Notification/classes/class.ilNotification.php"; + ilNotification::setNotification(ilNotification::TYPE_POLL, $ilUser->getId(), $this->object->getId(), true); + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + include_once "Services/Link/classes/class.ilLink.php"; + ilUtil::redirect(ilLink::_getLink($tree->getParentId($this->ref_id))); + } + + public function unsubscribe() + { + $ilUser = $this->user; + $tree = $this->tree; + $lng = $this->lng; + + include_once "./Services/Notification/classes/class.ilNotification.php"; + ilNotification::setNotification(ilNotification::TYPE_POLL, $ilUser->getId(), $this->object->getId(), false); + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + include_once "Services/Link/classes/class.ilLink.php"; + ilUtil::redirect(ilLink::_getLink($tree->getParentId($this->ref_id))); + } + + protected function sendNotifications() + { + $ilUser = $this->user; + + // recipients + include_once "./Services/Notification/classes/class.ilNotification.php"; + $users = ilNotification::getNotificationsForObject( + ilNotification::TYPE_POLL, + $this->object->getId(), + null, + true + ); + if (!sizeof($users)) { + return; + } + + include_once "./Services/Notification/classes/class.ilSystemNotification.php"; + $ntf = new ilSystemNotification(); + $ntf->setLangModules(array("poll")); + $ntf->setRefId($this->ref_id); + + if ($this->object->getNonAnonymous()) { + $ntf->setChangedByUserId($ilUser->getId()); + } + + $ntf->setSubjectLangId('poll_vote_notification_subject'); + $ntf->setIntroductionLangId('poll_vote_notification_body'); + $ntf->setGotoLangId('poll_vote_notification_link'); + $ntf->setReasonLangId('poll_vote_notification_reason'); + + $notified = $ntf->sendMail($users, null, "read"); + + ilNotification::updateNotificationTime(ilNotification::TYPE_POLL, $this->object->getId(), $notified); + } + + /** + * return user view + * + * @return string + */ + public function getHTML() + { + } + + public function addLocatorItems() + { + $ilLocator = $this->locator; + + if (is_object($this->object)) { + $ilLocator->addItem($this->object->getTitle(), $this->ctrl->getLinkTarget($this, ""), "", $this->node_id); + } + } + + /** + * Deep link + * + * @param string $a_target + */ + public static function _goto($a_target) + { + global $DIC; + + $tree = $DIC->repositoryTree(); + $ilAccess = $DIC->access(); + + $id = explode("_", $a_target); + $ref_id = $id[0]; + + // #13728 - used in notification mostly + if ($ilAccess->checkAccess("write", "", $ref_id)) { + $_GET["baseClass"] = "ilRepositoryGUI"; + $_GET["ref_id"] = $ref_id; + $_GET["cmd"] = "showParticipants"; + include("ilias.php"); + exit; + } else { + // is sideblock: so show parent instead + $container_id = $tree->getParentId($ref_id); + + // #11810 + include_once "Services/Link/classes/class.ilLink.php"; + ilUtil::redirect(ilLink::_getLink($container_id) . + "#poll" . ilObject::_lookupObjId($id[0])); + } + } +} diff --git a/Modules/Poll/classes/class.ilObjPollListGUI.php b/Modules/Poll/classes/class.ilObjPollListGUI.php index aa128c462dbc414d946e6cbe8c101db96d698259..36f75eebe8b30b053223a4a3f41657b6c71f513c 100644 --- a/Modules/Poll/classes/class.ilObjPollListGUI.php +++ b/Modules/Poll/classes/class.ilObjPollListGUI.php @@ -1,66 +1,63 @@ - -* $Id: class.ilObjRootFolderListGUI.php 23764 2010-05-06 15:11:30Z smeyer $ -* -* @extends ilObjectListGUI -*/ -class ilObjPollListGUI extends ilObjectListGUI -{ - /** - * initialisation - */ - function init() - { - $this->copy_enabled = false; - $this->delete_enabled = true; - $this->cut_enabled = false; - $this->subscribe_enabled = false; - $this->link_enabled = false; - $this->info_screen_enabled = true; - $this->type = "poll"; - $this->gui_class_name = "ilobjpollgui"; - - // general commands array - include_once('./Modules/Poll/classes/class.ilObjPollAccess.php'); - $this->commands = ilObjPollAccess::_getCommands(); - } - - /** - * Get item properties - * - * @return array array of property arrays: - * "alert" (boolean) => display as an alert property (usually in red) - * "property" (string) => property name - * "value" (string) => property value - */ - function getProperties() - { - $lng = $this->lng; - - // BEGIN WebDAV: Get parent properties - // BEGIN ChangeEvent: Get parent properties - $props = parent::getProperties(); - // END ChangeEvent: Get parent properties - // END WebDAV: Get parent properties - - // offline - include_once 'Modules/Poll/classes/class.ilObjPollAccess.php'; - if(!ilObjPollAccess::_lookupOnline($this->obj_id)) - { - $props[] = array("alert" => true, "property" => $lng->txt("status"), - "value" => $lng->txt("offline")); - } - - return $props; - } -} - -?> \ No newline at end of file + +* $Id: class.ilObjRootFolderListGUI.php 23764 2010-05-06 15:11:30Z smeyer $ +* +* @extends ilObjectListGUI +*/ +class ilObjPollListGUI extends ilObjectListGUI +{ + /** + * initialisation + */ + public function init() + { + $this->copy_enabled = false; + $this->delete_enabled = true; + $this->cut_enabled = false; + $this->subscribe_enabled = false; + $this->link_enabled = false; + $this->info_screen_enabled = true; + $this->type = "poll"; + $this->gui_class_name = "ilobjpollgui"; + + // general commands array + include_once('./Modules/Poll/classes/class.ilObjPollAccess.php'); + $this->commands = ilObjPollAccess::_getCommands(); + } + + /** + * Get item properties + * + * @return array array of property arrays: + * "alert" (boolean) => display as an alert property (usually in red) + * "property" (string) => property name + * "value" (string) => property value + */ + public function getProperties() + { + $lng = $this->lng; + + // BEGIN WebDAV: Get parent properties + // BEGIN ChangeEvent: Get parent properties + $props = parent::getProperties(); + // END ChangeEvent: Get parent properties + // END WebDAV: Get parent properties + + // offline + include_once 'Modules/Poll/classes/class.ilObjPollAccess.php'; + if (!ilObjPollAccess::_lookupOnline($this->obj_id)) { + $props[] = array("alert" => true, "property" => $lng->txt("status"), + "value" => $lng->txt("offline")); + } + + return $props; + } +} diff --git a/Modules/Poll/classes/class.ilPollAnswerTableGUI.php b/Modules/Poll/classes/class.ilPollAnswerTableGUI.php index 0fed340398db6b94e1b56280f7c1bfcb7712e27d..79216c2e359a040aecde1aceafae5addeb861104 100644 --- a/Modules/Poll/classes/class.ilPollAnswerTableGUI.php +++ b/Modules/Poll/classes/class.ilPollAnswerTableGUI.php @@ -1,118 +1,110 @@ - -* @version $Id$ -* -* @ingroup ModulesPoll -*/ -class ilPollAnswerTableGUI extends ilTable2GUI -{ - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd) - { - global $DIC; +ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->setId("ilobjpollaw"); - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->addColumn($lng->txt("poll_sortorder"), "pos"); - $this->addColumn($lng->txt("poll_answer"), "answer"); - $this->addColumn($lng->txt("poll_absolute"), "votes"); - $this->addColumn($lng->txt("poll_percentage"), "percentage"); - - $total = $this->getItems(); - - $this->setTitle($this->lng->txt("poll_question").": \"". - $a_parent_obj->object->getQuestion()."\""); - $this->setDescription(sprintf($lng->txt("poll_population"), $total)); - - if($total) - { - $this->addCommandButton("confirmDeleteAllVotes", $lng->txt("poll_delete_votes")); - } - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd)); - $this->setRowTemplate("tpl.answer_row.html", "Modules/Poll"); - $this->setDefaultOrderField("pos"); - $this->setDefaultOrderDirection("asc"); - - $this->setExportFormats(array(self::EXPORT_CSV, self::EXPORT_EXCEL)); - } - - public function numericOrdering($a_field) - { - if($a_field != "answer") - { - return true; - } - return false; - } - - function getItems() - { - $data = $this->parent_obj->object->getAnswers(); - $perc = $this->parent_obj->object->getVotePercentages(); - $total = $perc["total"]; - $perc = $perc["perc"]; - - // add current percentages - foreach($data as $idx => $item) - { - if(!isset($perc[$item["id"]])) - { - $data[$idx]["percentage"] = 0; - $data[$idx]["votes"] = 0; - } - else - { - $data[$idx]["percentage"] = round($perc[$item["id"]]["perc"]); - $data[$idx]["votes"] = $perc[$item["id"]]["abs"]; - } - } - - $this->setData($data); - - return $total; - } - - protected function fillRow($a_set) - { - $this->tpl->setVariable("VALUE_POS", $a_set["pos"]/10); - $this->tpl->setVariable("TXT_ANSWER", nl2br($a_set["answer"])); - $this->tpl->setVariable("VALUE_VOTES", $a_set["votes"]); - $this->tpl->setVariable("VALUE_PERCENTAGE", $a_set["percentage"]); - } - - protected function fillRowCSV($a_csv, $a_set) - { - $a_csv->addColumn($a_set["pos"]/10); - $a_csv->addColumn($a_set["answer"]); - $a_csv->addColumn($a_set["votes"]); - $a_csv->addColumn($a_set["percentage"]); - $a_csv->addRow(); - } - - protected function fillRowExcel(ilExcel $a_excel, &$a_row, $a_set) - { - $a_excel->setCell($a_row, 0, $a_set["pos"]/10); - $a_excel->setCell($a_row, 1, $a_set["answer"]); - $a_excel->setCell($a_row, 2, $a_set["votes"]); - $a_excel->setCell($a_row, 3, $a_set["percentage"]."%"); - } -} - -?> \ No newline at end of file +include_once("./Services/Table/classes/class.ilTable2GUI.php"); + +/** +* TableGUI class for poll answers +* +* @author Jörg Lützenkirchen +* @version $Id$ +* +* @ingroup ModulesPoll +*/ +class ilPollAnswerTableGUI extends ilTable2GUI +{ + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->setId("ilobjpollaw"); + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->addColumn($lng->txt("poll_sortorder"), "pos"); + $this->addColumn($lng->txt("poll_answer"), "answer"); + $this->addColumn($lng->txt("poll_absolute"), "votes"); + $this->addColumn($lng->txt("poll_percentage"), "percentage"); + + $total = $this->getItems(); + + $this->setTitle($this->lng->txt("poll_question") . ": \"" . + $a_parent_obj->object->getQuestion() . "\""); + $this->setDescription(sprintf($lng->txt("poll_population"), $total)); + + if ($total) { + $this->addCommandButton("confirmDeleteAllVotes", $lng->txt("poll_delete_votes")); + } + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd)); + $this->setRowTemplate("tpl.answer_row.html", "Modules/Poll"); + $this->setDefaultOrderField("pos"); + $this->setDefaultOrderDirection("asc"); + + $this->setExportFormats(array(self::EXPORT_CSV, self::EXPORT_EXCEL)); + } + + public function numericOrdering($a_field) + { + if ($a_field != "answer") { + return true; + } + return false; + } + + public function getItems() + { + $data = $this->parent_obj->object->getAnswers(); + $perc = $this->parent_obj->object->getVotePercentages(); + $total = $perc["total"]; + $perc = $perc["perc"]; + + // add current percentages + foreach ($data as $idx => $item) { + if (!isset($perc[$item["id"]])) { + $data[$idx]["percentage"] = 0; + $data[$idx]["votes"] = 0; + } else { + $data[$idx]["percentage"] = round($perc[$item["id"]]["perc"]); + $data[$idx]["votes"] = $perc[$item["id"]]["abs"]; + } + } + + $this->setData($data); + + return $total; + } + + protected function fillRow($a_set) + { + $this->tpl->setVariable("VALUE_POS", $a_set["pos"]/10); + $this->tpl->setVariable("TXT_ANSWER", nl2br($a_set["answer"])); + $this->tpl->setVariable("VALUE_VOTES", $a_set["votes"]); + $this->tpl->setVariable("VALUE_PERCENTAGE", $a_set["percentage"]); + } + + protected function fillRowCSV($a_csv, $a_set) + { + $a_csv->addColumn($a_set["pos"]/10); + $a_csv->addColumn($a_set["answer"]); + $a_csv->addColumn($a_set["votes"]); + $a_csv->addColumn($a_set["percentage"]); + $a_csv->addRow(); + } + + protected function fillRowExcel(ilExcel $a_excel, &$a_row, $a_set) + { + $a_excel->setCell($a_row, 0, $a_set["pos"]/10); + $a_excel->setCell($a_row, 1, $a_set["answer"]); + $a_excel->setCell($a_row, 2, $a_set["votes"]); + $a_excel->setCell($a_row, 3, $a_set["percentage"] . "%"); + } +} diff --git a/Modules/Poll/classes/class.ilPollBlock.php b/Modules/Poll/classes/class.ilPollBlock.php index 643d05e88d45b6ccb4021a35dc6b55cff0d06116..3413b15c1dc7a03943e5d2e1b8b551badb15dbe7 100644 --- a/Modules/Poll/classes/class.ilPollBlock.php +++ b/Modules/Poll/classes/class.ilPollBlock.php @@ -11,186 +11,169 @@ include_once("./Services/Block/classes/class.ilCustomBlock.php"); */ class ilPollBlock extends ilCustomBlock { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * Constructor - */ - function __construct($a_id = 0) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_id = 0) + { + global $DIC; - parent::__construct($a_id); - $this->lng = $DIC->language(); - } + parent::__construct($a_id); + $this->lng = $DIC->language(); + } - protected $poll; // [ilObjPoll] - protected $answers; // [array] - protected $visible; // [bool] - protected $active; // [bool] - - /** - * Set ref id (needed for poll access) - * - * @param int $a_id - */ - public function setRefId($a_id) - { - include_once "Modules/Poll/classes/class.ilObjPoll.php"; - $this->poll = new ilObjPoll($a_id, true); - $this->answers = $this->poll->getAnswers(); - } - - /** - * Get poll object - * - * @return ilObjPoll - */ - public function getPoll() - { - return $this->poll; - } - - /** - * Check if user will see any content (vote/result) - * - * @param int $a_user_id - * @return boolean - */ - public function hasAnyContent($a_user_id, $a_ref_id) - { - if(!sizeof($this->answers)) - { - return false; - } - - include_once "Modules/Poll/classes/class.ilObjPollAccess.php"; - $this->active = ilObjPollAccess::_isActivated($a_ref_id); - if(!$this->active) - { - return false; - } - - if(!$this->mayVote($a_user_id) && - !$this->maySeeResults($a_user_id)) - { - return false; - } - - return true; - } - - public function mayVote($a_user_id) - { - if(!$this->active) - { - return false; - } - - if($a_user_id == ANONYMOUS_USER_ID) - { - return false; - } - - if($this->poll->hasUserVoted($a_user_id)) - { - return false; - } - - if($this->poll->getVotingPeriod() && - ($this->poll->getVotingPeriodBegin() > time() || - $this->poll->getVotingPeriodEnd() < time())) - { - return false; - } - - return true; - } - - public function mayNotResultsYet() - { - if($this->poll->getViewResults() == ilObjPoll::VIEW_RESULTS_AFTER_PERIOD && - $this->poll->getVotingPeriod() && - $this->poll->getVotingPeriodEnd() > time()) - { - return true; - } - return false; - } - - public function maySeeResults($a_user_id) - { - if(!$this->active) - { - return false; - } - - switch($this->poll->getViewResults()) - { - case ilObjPoll::VIEW_RESULTS_NEVER: - return false; - - case ilObjPoll::VIEW_RESULTS_ALWAYS: - // fallthrough - - // #12023 - see mayNotResultsYet() - case ilObjPoll::VIEW_RESULTS_AFTER_PERIOD: - return true; - - case ilObjPoll::VIEW_RESULTS_AFTER_VOTE: - if($this->poll->hasUserVoted($a_user_id)) - { - return true; - } - return false; - } - } - - public function getMessage($a_user_id) - { - $lng = $this->lng; - - if(!sizeof($this->answers)) - { - return $lng->txt("poll_block_message_no_answers"); - } - - if(!$this->active) - { - if(!$this->poll->isOnline()) - { - return $lng->txt("poll_block_message_offline"); - } - if($this->poll->getAccessBegin() > time()) - { - $date = ilDatePresentation::formatDate(new ilDateTime($this->poll->getAccessBegin(), IL_CAL_UNIX)); - return sprintf($lng->txt("poll_block_message_inactive"), $date); - } - } - } + protected $poll; // [ilObjPoll] + protected $answers; // [array] + protected $visible; // [bool] + protected $active; // [bool] + + /** + * Set ref id (needed for poll access) + * + * @param int $a_id + */ + public function setRefId($a_id) + { + include_once "Modules/Poll/classes/class.ilObjPoll.php"; + $this->poll = new ilObjPoll($a_id, true); + $this->answers = $this->poll->getAnswers(); + } + + /** + * Get poll object + * + * @return ilObjPoll + */ + public function getPoll() + { + return $this->poll; + } + + /** + * Check if user will see any content (vote/result) + * + * @param int $a_user_id + * @return boolean + */ + public function hasAnyContent($a_user_id, $a_ref_id) + { + if (!sizeof($this->answers)) { + return false; + } + + include_once "Modules/Poll/classes/class.ilObjPollAccess.php"; + $this->active = ilObjPollAccess::_isActivated($a_ref_id); + if (!$this->active) { + return false; + } + + if (!$this->mayVote($a_user_id) && + !$this->maySeeResults($a_user_id)) { + return false; + } + + return true; + } + + public function mayVote($a_user_id) + { + if (!$this->active) { + return false; + } + + if ($a_user_id == ANONYMOUS_USER_ID) { + return false; + } + + if ($this->poll->hasUserVoted($a_user_id)) { + return false; + } + + if ($this->poll->getVotingPeriod() && + ($this->poll->getVotingPeriodBegin() > time() || + $this->poll->getVotingPeriodEnd() < time())) { + return false; + } + + return true; + } + + public function mayNotResultsYet() + { + if ($this->poll->getViewResults() == ilObjPoll::VIEW_RESULTS_AFTER_PERIOD && + $this->poll->getVotingPeriod() && + $this->poll->getVotingPeriodEnd() > time()) { + return true; + } + return false; + } + + public function maySeeResults($a_user_id) + { + if (!$this->active) { + return false; + } + + switch ($this->poll->getViewResults()) { + case ilObjPoll::VIEW_RESULTS_NEVER: + return false; + + case ilObjPoll::VIEW_RESULTS_ALWAYS: + // fallthrough + + // #12023 - see mayNotResultsYet() + case ilObjPoll::VIEW_RESULTS_AFTER_PERIOD: + return true; + + case ilObjPoll::VIEW_RESULTS_AFTER_VOTE: + if ($this->poll->hasUserVoted($a_user_id)) { + return true; + } + return false; + } + } + + public function getMessage($a_user_id) + { + $lng = $this->lng; + + if (!sizeof($this->answers)) { + return $lng->txt("poll_block_message_no_answers"); + } + + if (!$this->active) { + if (!$this->poll->isOnline()) { + return $lng->txt("poll_block_message_offline"); + } + if ($this->poll->getAccessBegin() > time()) { + $date = ilDatePresentation::formatDate(new ilDateTime($this->poll->getAccessBegin(), IL_CAL_UNIX)); + return sprintf($lng->txt("poll_block_message_inactive"), $date); + } + } + } - /** - * Show Results as (Barchart or Piechart) - * @return int - * - */ - public function showResultsAs() - { - return $this->poll->getShowResultsAs(); - } + /** + * Show Results as (Barchart or Piechart) + * @return int + * + */ + public function showResultsAs() + { + return $this->poll->getShowResultsAs(); + } - /** - * Are Comments enabled or disabled - * @return bool - */ - public function showComments() - { - return $this->poll->getShowComments(); - } + /** + * Are Comments enabled or disabled + * @return bool + */ + public function showComments() + { + return $this->poll->getShowComments(); + } } - -?> \ No newline at end of file diff --git a/Modules/Poll/classes/class.ilPollBlockGUI.php b/Modules/Poll/classes/class.ilPollBlockGUI.php index cf47c2daa9101cab2c8500a91d5e8032e5856445..cd01476e05903c167446320f72fcf60f055a700e 100644 --- a/Modules/Poll/classes/class.ilPollBlockGUI.php +++ b/Modules/Poll/classes/class.ilPollBlockGUI.php @@ -6,7 +6,7 @@ include_once("./Services/Block/classes/class.ilBlockGUI.php"); include_once("./Modules/Poll/classes/class.ilObjPoll.php"); /** -* BlockGUI class for polls. +* BlockGUI class for polls. * * @author Jörg Lützenkirchen * @version $Id$ @@ -16,508 +16,490 @@ include_once("./Modules/Poll/classes/class.ilObjPoll.php"); */ class ilPollBlockGUI extends ilBlockGUI { - static $block_type = "poll"; - - protected $poll_block; // [ilPollBlock] - - static $js_init = false; - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $this->user = $DIC->user(); - $this->access = $DIC->access(); - $lng = $DIC->language(); - - parent::__construct(); - - $lng->loadLanguageModule("poll"); - $this->setRowTemplate("tpl.block.html", "Modules/Poll"); - } - - /** - * @inheritdoc - */ - public function getBlockType(): string - { - return self::$block_type; - } - - /** - * @inheritdoc - */ - protected function isRepositoryObject(): bool - { - return true; - } - - /** - * Get repository object GUI name - * - * @return string - */ - protected function getRepositoryObjectGUIName() - { - return "ilobjpollgui"; - } - - /** - * Get Screen Mode for current command. - */ - static function getScreenMode() - { - return IL_SCREEN_SIDE; - } - - /** - * Do most of the initialisation. - */ - function setBlock($a_block) - { - $this->setBlockId($a_block->getId()); - $this->poll_block = $a_block; - } - - /** - * execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - - $next_class = $ilCtrl->getNextClass(); - $cmd = $ilCtrl->getCmd("getHTML"); - - switch ($next_class) - { - default: - return $this->$cmd(); - } - } - - function fillRow($a_poll) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilUser = $this->user; - $tpl = $this->main_tpl; - - - // handle messages - - $mess = $this->poll_block->getMessage($ilUser->getId()); - if($mess) - { - $this->tpl->setVariable("TXT_QUESTION", $mess); - return; - } - - - // nested form problem - if(!$_SESSION["il_cont_admin_panel"]) - { - // vote - - if($this->poll_block->mayVote($ilUser->getId())) - { - $this->tpl->setCurrentBlock("mode_info_bl"); - if($this->poll_block->getPoll()->getNonAnonymous()) - { - $mode_info = $lng->txt("poll_non_anonymous_warning"); - } - else - { - $mode_info = $lng->txt("poll_anonymous_warning"); - } - $this->tpl->setVariable("MODE_INFO", $mode_info); - $this->tpl->parseCurrentBlock(); - - $is_multi_answer = ($this->poll_block->getPoll()->getMaxNumberOfAnswers() > 1); - - if(isset($_SESSION["last_poll_vote"][$this->poll_block->getPoll()->getId()])) - { - $last_vote = $_SESSION["last_poll_vote"][$this->poll_block->getPoll()->getId()]; - unset($_SESSION["last_poll_vote"][$this->poll_block->getPoll()->getId()]); - - if($is_multi_answer) - { - $error = sprintf($lng->txt("poll_vote_error_multi"), - $this->poll_block->getPoll()->getMaxNumberOfAnswers()); - } - else - { - $error = $lng->txt("poll_vote_error_single"); - } - - $this->tpl->setCurrentBlock("error_bl"); - $this->tpl->setVariable("FORM_ERROR", $error); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setCurrentBlock("answer"); - foreach($a_poll->getAnswers() as $item) - { - if(!$is_multi_answer) - { - $this->tpl->setVariable("ANSWER_INPUT", "radio"); - $this->tpl->setVariable("ANSWER_NAME", "aw"); - } - else - { - $this->tpl->setVariable("ANSWER_INPUT", "checkbox"); - $this->tpl->setVariable("ANSWER_NAME", "aw[]"); - - if(is_array($last_vote) && in_array($item["id"], $last_vote)) - { - $this->tpl->setVariable("ANSWER_STATUS", 'checked="checked"'); - } - } - $this->tpl->setVariable("VALUE_ANSWER", $item["id"]); - $this->tpl->setVariable("TXT_ANSWER_VOTE", nl2br($item["answer"])); - $this->tpl->parseCurrentBlock(); - } - - $ilCtrl->setParameterByClass($this->getRepositoryObjectGUIName(), - "ref_id", $this->getRefId()); - $url = $ilCtrl->getLinkTargetByClass(array("ilrepositorygui", $this->getRepositoryObjectGUIName()), - "vote"); - $ilCtrl->clearParametersByClass($this->getRepositoryObjectGUIName()); - - $url .= "#poll".$a_poll->getID(); - - $this->tpl->setVariable("URL_FORM", $url); - $this->tpl->setVariable("CMD_FORM", "vote"); - $this->tpl->setVariable("TXT_SUBMIT", $lng->txt("poll_vote")); - - if($this->poll_block->getPoll()->getVotingPeriod()) - { - $this->tpl->setVariable("TXT_VOTING_END_PERIOD", - sprintf($lng->txt("poll_voting_period_info"), - ilDatePresentation::formatDate(new ilDateTime($this->poll_block->getPoll()->getVotingPeriodEnd(), IL_CAL_UNIX)))); - } - } - - - // result - if ($this->poll_block->maySeeResults($ilUser->getId())) - { - if (!$this->poll_block->mayNotResultsYet($ilUser->getId())) - { - $answers = array(); - foreach ($a_poll->getAnswers() as $item) - { - $answers[$item["id"]] = $item["answer"]; - } - - $perc = $this->poll_block->getPoll()->getVotePercentages(); - $total = $perc["total"]; - $perc = $perc["perc"]; - - $this->tpl->setVariable("TOTAL_ANSWERS", sprintf($lng->txt("poll_population"), $total)); - - if($total) - { - // sort results by votes / original position - if ($this->poll_block->getPoll()->getSortResultByVotes()) - { - $order = array_keys(ilUtil::sortArray($perc, "abs", "desc", true, true)); - - foreach (array_keys($answers) as $answer_id) - { - if (!in_array($answer_id, $order)) - { - $order[] = $answer_id; - } - } - } - else - { - $order = array_keys($answers); - } - - // pie chart - if ($this->poll_block->showResultsAs() == ilObjPoll::SHOW_RESULTS_AS_PIECHART) - { - - include_once("./Services/Chart/classes/class.ilChart.php"); - - $chart = ilChart::getInstanceByType(ilCHart::TYPE_PIE, "poll_results_pie_". $this->getRefId()); - $chart->setSize("100%", 200); - $chart->setAutoResize(true); - - $chart_data = $chart->getDataInstance(); - - foreach ($order as $answer_id) - { - $chart_data->addPoint( - round($perc[$answer_id]["perc"]), - nl2br($answers[$answer_id]) - ); - } - - // disable legend, use inner labels - currently not preferred - // $chart_data->setLabelRadius(0.8); - - $chart->addData($chart_data); - - $pie_legend_id = "poll_legend_".$this->getRefId(); - $legend = new ilChartLegend(); - $legend->setContainer($pie_legend_id); - $chart->setLegend($legend); - - $this->tpl->setVariable("PIE_LEGEND_ID", $pie_legend_id); - $this->tpl->setVariable("PIE_CHART", $chart->getHTML()); - } - // bar chart - else - { - include_once "Services/UIComponent/ProgressBar/classes/class.ilProgressBar.php"; - - $this->tpl->setCurrentBlock("answer_result"); - foreach ($order as $answer_id) - { - $pbar = ilProgressBar::getInstance(); - $pbar->setCurrent(round($perc[$answer_id]["perc"])); - $this->tpl->setVariable("PERC_ANSWER_RESULT", $pbar->render()); - $this->tpl->setVariable("TXT_ANSWER_RESULT", nl2br($answers[$answer_id])); - $this->tpl->parseCurrentBlock(); - } - } - } - } - else - { - $rel = ilDatePresentation::useRelativeDates(); - ilDatePresentation::setUseRelativeDates(false); - $end = $this->poll_block->getPoll()->getVotingPeriodEnd(); - $end = ilDatePresentation::formatDate(new ilDateTime($end, IL_CAL_UNIX)); - ilDatePresentation::setUseRelativeDates($rel); - - // #14607 - $info = ""; - if($this->poll_block->getPoll()->hasUserVoted($ilUser->getId())) - { - $info .= $lng->txt("poll_block_message_already_voted")." "; - } - - $this->tpl->setVariable("TOTAL_ANSWERS", $info. - sprintf($lng->txt("poll_block_results_available_on"), $end)); - } - } - else if($this->poll_block->getPoll()->hasUserVoted($ilUser->getId())) - { - $this->tpl->setVariable("TOTAL_ANSWERS", $lng->txt("poll_block_message_already_voted")); - } - } - - if(!$this->poll_block->mayVote($ilUser->getId()) && !$this->poll_block->getPoll()->hasUserVoted($ilUser->getId())) - { - if($this->poll_block->getPoll()->getVotingPeriod()) - { - $this->tpl->setVariable("TXT_VOTING_PERIOD", - sprintf($lng->txt("poll_voting_period_full_info"), - ilDatePresentation::formatDate(new ilDateTime($this->poll_block->getPoll()->getVotingPeriodBegin(), IL_CAL_UNIX)), - ilDatePresentation::formatDate(new ilDateTime($this->poll_block->getPoll()->getVotingPeriodEnd(), IL_CAL_UNIX)) - )); - } - } - else - { - $this->tpl->setVariable("TXT_QUESTION", nl2br(trim($a_poll->getQuestion()))); - - $img = $a_poll->getImageFullPath(); - if($img) - { - require_once('./Services/WebAccessChecker/classes/class.ilWACSignedPath.php'); - $this->tpl->setVariable("URL_IMAGE", ilWACSignedPath::signFile($img)); - } - } - - - $this->tpl->setVariable("ANCHOR_ID", $a_poll->getID()); - //$this->tpl->setVariable("TXT_QUESTION", nl2br(trim($a_poll->getQuestion()))); - - $desc = trim($a_poll->getDescription()); - if($desc) - { - $this->tpl->setVariable("TXT_DESC", nl2br($desc)); - } - - - if ($this->poll_block->showComments()) { - $this->tpl->setCurrentBlock("comment_link"); - $this->tpl->setVariable("LANG_COMMENTS", $lng->txt('poll_comments')); - $this->tpl->setVariable("COMMENT_JSCALL", $this->commentJSCall()); - $this->tpl->setVariable("COMMENTS_COUNT_ID", $this->getRefId()); - - $comments_count = $this->getNumberOfComments($this->getRefId()); - - if($comments_count > 0) - { - $this->tpl->setVariable("COMMENTS_COUNT", "(".$comments_count.")"); - } - - if(!self::$js_init) - { - $redraw_url = $ilCtrl->getLinkTarget($this, "getNumberOfCommentsForRedraw", - "", true, false); - $this->tpl->setVariable("COMMENTS_REDRAW_URL", $redraw_url); - - $tpl->addJavaScript("Modules/Poll/js/ilPoll.js"); - self::$js_init = true; - } - } - - } - - /** - * Get block HTML code. - */ - function getHTML() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilAccess = $this->access; - $ilUser = $this->user; - - $this->poll_block->setRefId($this->getRefId()); - $this->may_write = $ilAccess->checkAccess("write", "", $this->getRefId()); - $this->has_content = $this->poll_block->hasAnyContent($ilUser->getId(), $this->getRefId()); - - #22078 and 22079 it always contains something. - /*if(!$this->may_write && !$this->has_content) - { - return ""; - }*/ - - $poll_obj = $this->poll_block->getPoll(); - $this->setTitle($poll_obj->getTitle()); - $this->setData(array($poll_obj)); - - $ilCtrl->setParameterByClass($this->getRepositoryObjectGUIName(), - "ref_id", $this->getRefId()); - - if(!$this->poll_block->getMessage($ilUser->getId())) - { - // notification - include_once "./Services/Notification/classes/class.ilNotification.php"; - if(ilNotification::hasNotification(ilNotification::TYPE_POLL, $ilUser->getId(), $this->poll_block->getPoll()->getId())) - { - $this->addBlockCommand( - $ilCtrl->getLinkTargetByClass(array("ilrepositorygui", $this->getRepositoryObjectGUIName()), - "unsubscribe"), - $lng->txt("poll_notification_unsubscribe")); - } - else - { - $this->addBlockCommand( - $ilCtrl->getLinkTargetByClass(array("ilrepositorygui", $this->getRepositoryObjectGUIName()), - "subscribe"), - $lng->txt("poll_notification_subscribe")); - } - } - - if ($this->may_write) - { - // edit - $this->addBlockCommand( - $ilCtrl->getLinkTargetByClass(array("ilrepositorygui", $this->getRepositoryObjectGUIName()), - "render"), - $lng->txt("edit_content")); - $this->addBlockCommand( - $ilCtrl->getLinkTargetByClass(array("ilrepositorygui", $this->getRepositoryObjectGUIName()), - "edit"), - $lng->txt("settings")); - - /* delete (#10993 - see ilBlockGUI) - $parent_id = $tree->getParentId($this->getRefId()); - $type = ilObject::_lookupType($parent_id, true); - $class = $objDefinition->getClassName($type); - if($class) - { - $class = "ilobj".strtolower($class)."gui"; - $ilCtrl->setParameterByClass($class, "ref_id", $parent_id); - $ilCtrl->setParameterByClass($class, "item_ref_id", $this->getRefId()); - $this->addBlockCommand( - $ilCtrl->getLinkTargetByClass($class, "delete"), - $lng->txt("delete")); - } - */ - } - - $ilCtrl->clearParametersByClass($this->getRepositoryObjectGUIName()); - - return parent::getHTML(); - } - - /** - * Builds JavaScript Call to open CommentLayer via html link - * - * @return string jsCall - */ - private function commentJSCall() - { - include_once("./Services/Notes/classes/class.ilNoteGUI.php"); - include_once("./Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); - - $refId = $this->getRefId(); - $objectId = ilObject2::_lookupObjectId($refId); - - $ajaxHash = ilCommonActionDispatcherGUI::buildAjaxHash( - ilCommonActionDispatcherGUI::TYPE_REPOSITORY, $refId, "poll", $objectId); - - - $comment = new ilNoteGUI(); - $jsCall = $comment->getListCommentsJSCall($ajaxHash, "ilPoll.redrawComments(".$refId.");"); - - return $jsCall; - } - - /** - * Returns comment count for JS Redraw - */ - public function getNumberOfCommentsForRedraw() - { - $number = $this->getNumberOfComments($_GET["poll_id"]); - - if($number > 0) - { - echo "(".$number.")"; - } - else - { - echo ""; - } - - exit(); - } - - /** - * Get comment count - * - * @param int $ref_id - * @return int - */ - public function getNumberOfComments($ref_id) - { - include_once("./Services/Notes/classes/class.ilNote.php"); - - $obj_id = ilObject2::_lookupObjectId($ref_id); - $number = ilNote::_countNotesAndComments($obj_id); - - if(count($number) == 0) - { - return 0; - } - - return $number[$obj_id][IL_NOTE_PUBLIC]; - } + public static $block_type = "poll"; + + protected $poll_block; // [ilPollBlock] + + public static $js_init = false; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->user = $DIC->user(); + $this->access = $DIC->access(); + $lng = $DIC->language(); + + parent::__construct(); + + $lng->loadLanguageModule("poll"); + $this->setRowTemplate("tpl.block.html", "Modules/Poll"); + } + + /** + * @inheritdoc + */ + public function getBlockType() : string + { + return self::$block_type; + } + + /** + * @inheritdoc + */ + protected function isRepositoryObject() : bool + { + return true; + } + + /** + * Get repository object GUI name + * + * @return string + */ + protected function getRepositoryObjectGUIName() + { + return "ilobjpollgui"; + } + + /** + * Get Screen Mode for current command. + */ + public static function getScreenMode() + { + return IL_SCREEN_SIDE; + } + + /** + * Do most of the initialisation. + */ + public function setBlock($a_block) + { + $this->setBlockId($a_block->getId()); + $this->poll_block = $a_block; + } + + /** + * execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $next_class = $ilCtrl->getNextClass(); + $cmd = $ilCtrl->getCmd("getHTML"); + + switch ($next_class) { + default: + return $this->$cmd(); + } + } + + public function fillRow($a_poll) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilUser = $this->user; + $tpl = $this->main_tpl; + + + // handle messages + + $mess = $this->poll_block->getMessage($ilUser->getId()); + if ($mess) { + $this->tpl->setVariable("TXT_QUESTION", $mess); + return; + } + + + // nested form problem + if (!$_SESSION["il_cont_admin_panel"]) { + // vote + + if ($this->poll_block->mayVote($ilUser->getId())) { + $this->tpl->setCurrentBlock("mode_info_bl"); + if ($this->poll_block->getPoll()->getNonAnonymous()) { + $mode_info = $lng->txt("poll_non_anonymous_warning"); + } else { + $mode_info = $lng->txt("poll_anonymous_warning"); + } + $this->tpl->setVariable("MODE_INFO", $mode_info); + $this->tpl->parseCurrentBlock(); + + $is_multi_answer = ($this->poll_block->getPoll()->getMaxNumberOfAnswers() > 1); + + if (isset($_SESSION["last_poll_vote"][$this->poll_block->getPoll()->getId()])) { + $last_vote = $_SESSION["last_poll_vote"][$this->poll_block->getPoll()->getId()]; + unset($_SESSION["last_poll_vote"][$this->poll_block->getPoll()->getId()]); + + if ($is_multi_answer) { + $error = sprintf( + $lng->txt("poll_vote_error_multi"), + $this->poll_block->getPoll()->getMaxNumberOfAnswers() + ); + } else { + $error = $lng->txt("poll_vote_error_single"); + } + + $this->tpl->setCurrentBlock("error_bl"); + $this->tpl->setVariable("FORM_ERROR", $error); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setCurrentBlock("answer"); + foreach ($a_poll->getAnswers() as $item) { + if (!$is_multi_answer) { + $this->tpl->setVariable("ANSWER_INPUT", "radio"); + $this->tpl->setVariable("ANSWER_NAME", "aw"); + } else { + $this->tpl->setVariable("ANSWER_INPUT", "checkbox"); + $this->tpl->setVariable("ANSWER_NAME", "aw[]"); + + if (is_array($last_vote) && in_array($item["id"], $last_vote)) { + $this->tpl->setVariable("ANSWER_STATUS", 'checked="checked"'); + } + } + $this->tpl->setVariable("VALUE_ANSWER", $item["id"]); + $this->tpl->setVariable("TXT_ANSWER_VOTE", nl2br($item["answer"])); + $this->tpl->parseCurrentBlock(); + } + + $ilCtrl->setParameterByClass( + $this->getRepositoryObjectGUIName(), + "ref_id", + $this->getRefId() + ); + $url = $ilCtrl->getLinkTargetByClass( + array("ilrepositorygui", $this->getRepositoryObjectGUIName()), + "vote" + ); + $ilCtrl->clearParametersByClass($this->getRepositoryObjectGUIName()); + + $url .= "#poll" . $a_poll->getID(); + + $this->tpl->setVariable("URL_FORM", $url); + $this->tpl->setVariable("CMD_FORM", "vote"); + $this->tpl->setVariable("TXT_SUBMIT", $lng->txt("poll_vote")); + + if ($this->poll_block->getPoll()->getVotingPeriod()) { + $this->tpl->setVariable( + "TXT_VOTING_END_PERIOD", + sprintf( + $lng->txt("poll_voting_period_info"), + ilDatePresentation::formatDate(new ilDateTime($this->poll_block->getPoll()->getVotingPeriodEnd(), IL_CAL_UNIX)) + ) + ); + } + } + + + // result + if ($this->poll_block->maySeeResults($ilUser->getId())) { + if (!$this->poll_block->mayNotResultsYet($ilUser->getId())) { + $answers = array(); + foreach ($a_poll->getAnswers() as $item) { + $answers[$item["id"]] = $item["answer"]; + } + + $perc = $this->poll_block->getPoll()->getVotePercentages(); + $total = $perc["total"]; + $perc = $perc["perc"]; + + $this->tpl->setVariable("TOTAL_ANSWERS", sprintf($lng->txt("poll_population"), $total)); + + if ($total) { + // sort results by votes / original position + if ($this->poll_block->getPoll()->getSortResultByVotes()) { + $order = array_keys(ilUtil::sortArray($perc, "abs", "desc", true, true)); + + foreach (array_keys($answers) as $answer_id) { + if (!in_array($answer_id, $order)) { + $order[] = $answer_id; + } + } + } else { + $order = array_keys($answers); + } + + // pie chart + if ($this->poll_block->showResultsAs() == ilObjPoll::SHOW_RESULTS_AS_PIECHART) { + include_once("./Services/Chart/classes/class.ilChart.php"); + + $chart = ilChart::getInstanceByType(ilCHart::TYPE_PIE, "poll_results_pie_" . $this->getRefId()); + $chart->setSize("100%", 200); + $chart->setAutoResize(true); + + $chart_data = $chart->getDataInstance(); + + foreach ($order as $answer_id) { + $chart_data->addPoint( + round($perc[$answer_id]["perc"]), + nl2br($answers[$answer_id]) + ); + } + + // disable legend, use inner labels - currently not preferred + // $chart_data->setLabelRadius(0.8); + + $chart->addData($chart_data); + + $pie_legend_id = "poll_legend_" . $this->getRefId(); + $legend = new ilChartLegend(); + $legend->setContainer($pie_legend_id); + $chart->setLegend($legend); + + $this->tpl->setVariable("PIE_LEGEND_ID", $pie_legend_id); + $this->tpl->setVariable("PIE_CHART", $chart->getHTML()); + } + // bar chart + else { + include_once "Services/UIComponent/ProgressBar/classes/class.ilProgressBar.php"; + + $this->tpl->setCurrentBlock("answer_result"); + foreach ($order as $answer_id) { + $pbar = ilProgressBar::getInstance(); + $pbar->setCurrent(round($perc[$answer_id]["perc"])); + $this->tpl->setVariable("PERC_ANSWER_RESULT", $pbar->render()); + $this->tpl->setVariable("TXT_ANSWER_RESULT", nl2br($answers[$answer_id])); + $this->tpl->parseCurrentBlock(); + } + } + } + } else { + $rel = ilDatePresentation::useRelativeDates(); + ilDatePresentation::setUseRelativeDates(false); + $end = $this->poll_block->getPoll()->getVotingPeriodEnd(); + $end = ilDatePresentation::formatDate(new ilDateTime($end, IL_CAL_UNIX)); + ilDatePresentation::setUseRelativeDates($rel); + + // #14607 + $info = ""; + if ($this->poll_block->getPoll()->hasUserVoted($ilUser->getId())) { + $info .= $lng->txt("poll_block_message_already_voted") . " "; + } + + $this->tpl->setVariable("TOTAL_ANSWERS", $info . + sprintf($lng->txt("poll_block_results_available_on"), $end)); + } + } elseif ($this->poll_block->getPoll()->hasUserVoted($ilUser->getId())) { + $this->tpl->setVariable("TOTAL_ANSWERS", $lng->txt("poll_block_message_already_voted")); + } + } + + if (!$this->poll_block->mayVote($ilUser->getId()) && !$this->poll_block->getPoll()->hasUserVoted($ilUser->getId())) { + if ($this->poll_block->getPoll()->getVotingPeriod()) { + $this->tpl->setVariable( + "TXT_VOTING_PERIOD", + sprintf( + $lng->txt("poll_voting_period_full_info"), + ilDatePresentation::formatDate(new ilDateTime($this->poll_block->getPoll()->getVotingPeriodBegin(), IL_CAL_UNIX)), + ilDatePresentation::formatDate(new ilDateTime($this->poll_block->getPoll()->getVotingPeriodEnd(), IL_CAL_UNIX)) + ) + ); + } + } else { + $this->tpl->setVariable("TXT_QUESTION", nl2br(trim($a_poll->getQuestion()))); + + $img = $a_poll->getImageFullPath(); + if ($img) { + require_once('./Services/WebAccessChecker/classes/class.ilWACSignedPath.php'); + $this->tpl->setVariable("URL_IMAGE", ilWACSignedPath::signFile($img)); + } + } + + + $this->tpl->setVariable("ANCHOR_ID", $a_poll->getID()); + //$this->tpl->setVariable("TXT_QUESTION", nl2br(trim($a_poll->getQuestion()))); + + $desc = trim($a_poll->getDescription()); + if ($desc) { + $this->tpl->setVariable("TXT_DESC", nl2br($desc)); + } + + + if ($this->poll_block->showComments()) { + $this->tpl->setCurrentBlock("comment_link"); + $this->tpl->setVariable("LANG_COMMENTS", $lng->txt('poll_comments')); + $this->tpl->setVariable("COMMENT_JSCALL", $this->commentJSCall()); + $this->tpl->setVariable("COMMENTS_COUNT_ID", $this->getRefId()); + + $comments_count = $this->getNumberOfComments($this->getRefId()); + + if ($comments_count > 0) { + $this->tpl->setVariable("COMMENTS_COUNT", "(" . $comments_count . ")"); + } + + if (!self::$js_init) { + $redraw_url = $ilCtrl->getLinkTarget( + $this, + "getNumberOfCommentsForRedraw", + "", + true, + false + ); + $this->tpl->setVariable("COMMENTS_REDRAW_URL", $redraw_url); + + $tpl->addJavaScript("Modules/Poll/js/ilPoll.js"); + self::$js_init = true; + } + } + } + + /** + * Get block HTML code. + */ + public function getHTML() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilAccess = $this->access; + $ilUser = $this->user; + + $this->poll_block->setRefId($this->getRefId()); + $this->may_write = $ilAccess->checkAccess("write", "", $this->getRefId()); + $this->has_content = $this->poll_block->hasAnyContent($ilUser->getId(), $this->getRefId()); + + #22078 and 22079 it always contains something. + /*if(!$this->may_write && !$this->has_content) + { + return ""; + }*/ + + $poll_obj = $this->poll_block->getPoll(); + $this->setTitle($poll_obj->getTitle()); + $this->setData(array($poll_obj)); + + $ilCtrl->setParameterByClass( + $this->getRepositoryObjectGUIName(), + "ref_id", + $this->getRefId() + ); + + if (!$this->poll_block->getMessage($ilUser->getId())) { + // notification + include_once "./Services/Notification/classes/class.ilNotification.php"; + if (ilNotification::hasNotification(ilNotification::TYPE_POLL, $ilUser->getId(), $this->poll_block->getPoll()->getId())) { + $this->addBlockCommand( + $ilCtrl->getLinkTargetByClass( + array("ilrepositorygui", $this->getRepositoryObjectGUIName()), + "unsubscribe" + ), + $lng->txt("poll_notification_unsubscribe") + ); + } else { + $this->addBlockCommand( + $ilCtrl->getLinkTargetByClass( + array("ilrepositorygui", $this->getRepositoryObjectGUIName()), + "subscribe" + ), + $lng->txt("poll_notification_subscribe") + ); + } + } + + if ($this->may_write) { + // edit + $this->addBlockCommand( + $ilCtrl->getLinkTargetByClass( + array("ilrepositorygui", $this->getRepositoryObjectGUIName()), + "render" + ), + $lng->txt("edit_content") + ); + $this->addBlockCommand( + $ilCtrl->getLinkTargetByClass( + array("ilrepositorygui", $this->getRepositoryObjectGUIName()), + "edit" + ), + $lng->txt("settings") + ); + + /* delete (#10993 - see ilBlockGUI) + $parent_id = $tree->getParentId($this->getRefId()); + $type = ilObject::_lookupType($parent_id, true); + $class = $objDefinition->getClassName($type); + if($class) + { + $class = "ilobj".strtolower($class)."gui"; + $ilCtrl->setParameterByClass($class, "ref_id", $parent_id); + $ilCtrl->setParameterByClass($class, "item_ref_id", $this->getRefId()); + $this->addBlockCommand( + $ilCtrl->getLinkTargetByClass($class, "delete"), + $lng->txt("delete")); + } + */ + } + + $ilCtrl->clearParametersByClass($this->getRepositoryObjectGUIName()); + + return parent::getHTML(); + } + + /** + * Builds JavaScript Call to open CommentLayer via html link + * + * @return string jsCall + */ + private function commentJSCall() + { + include_once("./Services/Notes/classes/class.ilNoteGUI.php"); + include_once("./Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); + + $refId = $this->getRefId(); + $objectId = ilObject2::_lookupObjectId($refId); + + $ajaxHash = ilCommonActionDispatcherGUI::buildAjaxHash( + ilCommonActionDispatcherGUI::TYPE_REPOSITORY, + $refId, + "poll", + $objectId + ); + + + $comment = new ilNoteGUI(); + $jsCall = $comment->getListCommentsJSCall($ajaxHash, "ilPoll.redrawComments(" . $refId . ");"); + + return $jsCall; + } + + /** + * Returns comment count for JS Redraw + */ + public function getNumberOfCommentsForRedraw() + { + $number = $this->getNumberOfComments($_GET["poll_id"]); + + if ($number > 0) { + echo "(" . $number . ")"; + } else { + echo ""; + } + + exit(); + } + + /** + * Get comment count + * + * @param int $ref_id + * @return int + */ + public function getNumberOfComments($ref_id) + { + include_once("./Services/Notes/classes/class.ilNote.php"); + + $obj_id = ilObject2::_lookupObjectId($ref_id); + $number = ilNote::_countNotesAndComments($obj_id); + + if (count($number) == 0) { + return 0; + } + + return $number[$obj_id][IL_NOTE_PUBLIC]; + } } - -?> \ No newline at end of file diff --git a/Modules/Poll/classes/class.ilPollDataSet.php b/Modules/Poll/classes/class.ilPollDataSet.php index 11d0b0263335afc64d8ea2214a5fea08d3db25f5..2cabcdcf853e574bbfb59679c855402e788a4c58 100644 --- a/Modules/Poll/classes/class.ilPollDataSet.php +++ b/Modules/Poll/classes/class.ilPollDataSet.php @@ -5,7 +5,7 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); /** * Poll Dataset class - * + * * This class implements the following entities: * - poll: object data * - poll_answer: data from table il_poll_answer @@ -16,244 +16,222 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); */ class ilPollDataSet extends ilDataSet { - protected $current_blog; - - /** - * Get supported versions - */ - public function getSupportedVersions() - { - return array("4.3.0", "5.0.0"); - } - - /** - * Get xml namespace - */ - function getXmlNamespace($a_entity, $a_schema_version) - { - return "http://www.ilias.de/xml/Modules/Poll/".$a_entity; - } - - /** - * Get field types for entity - */ - protected function getTypes($a_entity, $a_version) - { - if ($a_entity == "poll") - { - switch ($a_version) - { - case "4.3.0": - return array( - "Id" => "integer", - "Title" => "text", - "Description" => "text", - "Question" => "text", - "Image" => "text", - "ViewResults" => "integer", - "Dir" => "directory" - ); - break; - case "5.0.0": - return array( - "Id" => "integer", - "Title" => "text", - "Description" => "text", - "Question" => "text", - "Image" => "text", - "ViewResults" => "integer", - "Dir" => "directory", - "ShowResultsAs" => "integer", - "ShowComments" => "integer", - "MaxAnswers" => "integer", - "ResultSort" => "integer", - "NonAnon" => "integer", - "Period" => "integer", - "PeriodBegin" => "integer", - "PeriodEnd" => "integer" + protected $current_blog; + + /** + * Get supported versions + */ + public function getSupportedVersions() + { + return array("4.3.0", "5.0.0"); + } + + /** + * Get xml namespace + */ + public function getXmlNamespace($a_entity, $a_schema_version) + { + return "http://www.ilias.de/xml/Modules/Poll/" . $a_entity; + } + + /** + * Get field types for entity + */ + protected function getTypes($a_entity, $a_version) + { + if ($a_entity == "poll") { + switch ($a_version) { + case "4.3.0": + return array( + "Id" => "integer", + "Title" => "text", + "Description" => "text", + "Question" => "text", + "Image" => "text", + "ViewResults" => "integer", + "Dir" => "directory" + ); + break; + case "5.0.0": + return array( + "Id" => "integer", + "Title" => "text", + "Description" => "text", + "Question" => "text", + "Image" => "text", + "ViewResults" => "integer", + "Dir" => "directory", + "ShowResultsAs" => "integer", + "ShowComments" => "integer", + "MaxAnswers" => "integer", + "ResultSort" => "integer", + "NonAnon" => "integer", + "Period" => "integer", + "PeriodBegin" => "integer", + "PeriodEnd" => "integer" - ); - break; - } - } - - if ($a_entity == "poll_answer") - { - switch ($a_version) - { - case "4.3.0": - case "5.0.0": - return array( - "Id" => "integer", - "PollId" => "integer", - "Answer" => "text", - "Pos" => "integer", - ); - break; - } - } - } + ); + break; + } + } + + if ($a_entity == "poll_answer") { + switch ($a_version) { + case "4.3.0": + case "5.0.0": + return array( + "Id" => "integer", + "PollId" => "integer", + "Answer" => "text", + "Pos" => "integer", + ); + break; + } + } + } - /** - * 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 (!is_array($a_ids)) { + $a_ids = array($a_ids); } - - if ($a_entity == "poll") - { - switch ($a_version) - { - case "4.3.0": - $this->getDirectDataFromQuery("SELECT pl.id,od.title,od.description,". - "pl.question,pl.image,pl.view_results". - " FROM il_poll pl". - " JOIN object_data od ON (od.obj_id = pl.id)". - " WHERE ".$ilDB->in("pl.id", $a_ids, false, "integer"). - " AND od.type = ".$ilDB->quote("poll", "text")); - break; - case "5.0.0": - $this->getDirectDataFromQuery("SELECT pl.id,od.title,od.description". - ",pl.question,pl.image,pl.view_results,pl.show_results_as". - ",pl.max_answers,pl.result_sort,pl.non_anon,pl.period,pl.period_begin,pl.period_end". - " FROM il_poll pl". - " JOIN object_data od ON (od.obj_id = pl.id)". - " WHERE " . $ilDB->in("pl.id", $a_ids, false, "integer"). - " AND od.type = " . $ilDB->quote("poll", "text")); - break; + + if ($a_entity == "poll") { + switch ($a_version) { + case "4.3.0": + $this->getDirectDataFromQuery("SELECT pl.id,od.title,od.description," . + "pl.question,pl.image,pl.view_results" . + " FROM il_poll pl" . + " JOIN object_data od ON (od.obj_id = pl.id)" . + " WHERE " . $ilDB->in("pl.id", $a_ids, false, "integer") . + " AND od.type = " . $ilDB->quote("poll", "text")); + break; + case "5.0.0": + $this->getDirectDataFromQuery("SELECT pl.id,od.title,od.description" . + ",pl.question,pl.image,pl.view_results,pl.show_results_as" . + ",pl.max_answers,pl.result_sort,pl.non_anon,pl.period,pl.period_begin,pl.period_end" . + " FROM il_poll pl" . + " JOIN object_data od ON (od.obj_id = pl.id)" . + " WHERE " . $ilDB->in("pl.id", $a_ids, false, "integer") . + " AND od.type = " . $ilDB->quote("poll", "text")); + break; - } - } + } + } - if ($a_entity == "poll_answer") - { - switch ($a_version) - { - case "4.3.0": - case "5.0.0": - $this->getDirectDataFromQuery("SELECT id,poll_id,answer,pos". - " FROM il_poll_answer WHERE ". - $ilDB->in("poll_id", $a_ids, false, "integer")); - break; - } - } - } - - /** - * Determine the dependent sets of data - */ - protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) - { - switch ($a_entity) - { - case "poll": - return array ( - "poll_answer" => array("ids" => $a_rec["Id"]) - ); - } - return false; - } + if ($a_entity == "poll_answer") { + switch ($a_version) { + case "4.3.0": + case "5.0.0": + $this->getDirectDataFromQuery("SELECT id,poll_id,answer,pos" . + " FROM il_poll_answer WHERE " . + $ilDB->in("poll_id", $a_ids, false, "integer")); + break; + } + } + } + + /** + * Determine the dependent sets of data + */ + protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) + { + switch ($a_entity) { + case "poll": + return array( + "poll_answer" => array("ids" => $a_rec["Id"]) + ); + } + return false; + } - /** - * Get xml record - * - * @param - * @return - */ - function getXmlRecord($a_entity, $a_version, $a_set) - { - if ($a_entity == "poll") - { - include_once("./Modules/Poll/classes/class.ilObjPoll.php"); - $dir = ilObjPoll::initStorage($a_set["Id"]); - $a_set["Dir"] = $dir; - - include_once("./Services/Notes/classes/class.ilNote.php"); - $a_set["ShowComments"] = ilNote::commentsActivated($a_set["Id"], 0, "poll"); - } + /** + * Get xml record + * + * @param + * @return + */ + public function getXmlRecord($a_entity, $a_version, $a_set) + { + if ($a_entity == "poll") { + include_once("./Modules/Poll/classes/class.ilObjPoll.php"); + $dir = ilObjPoll::initStorage($a_set["Id"]); + $a_set["Dir"] = $dir; + + include_once("./Services/Notes/classes/class.ilNote.php"); + $a_set["ShowComments"] = ilNote::commentsActivated($a_set["Id"], 0, "poll"); + } - return $a_set; - } - - /** - * Import record - * - * @param - * @return - */ - function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) - { - switch ($a_entity) - { - case "poll": - include_once("./Modules/Poll/classes/class.ilObjPoll.php"); - - // container copy - if($new_id = $a_mapping->getMapping("Services/Container", "objs", $a_rec["Id"])) - { - $newObj = ilObjectFactory::getInstanceByObjId($new_id, false); - } - else - { - $newObj = new ilObjPoll(); - $newObj->create(); - } - - $newObj->setTitle($a_rec["Title"]); - $newObj->setDescription($a_rec["Description"]); - if((int)$a_rec["MaxAnswers"]) - { - $newObj->setMaxNumberOfAnswers($a_rec["MaxAnswers"]); - } - $newObj->setSortResultByVotes((bool)$a_rec["ResultSort"]); - $newObj->setNonAnonymous((bool)$a_rec["NonAnon"]); - if((int)$a_rec["ShowResultsAs"]) - { - $newObj->setShowResultsAs($a_rec["ShowResultsAs"]); - } - $newObj->setShowComments($a_rec["ShowComments"]); - $newObj->setQuestion($a_rec["Question"]); - $newObj->setImage($a_rec["Image"]); - $newObj->setViewResults($a_rec["ViewResults"]); - $newObj->setVotingPeriod($a_rec["Period"]); - $newObj->setVotingPeriodBegin($a_rec["PeriodBegin"]); - $newObj->setVotingPeriodEnd($a_rec["PeriodEnd"]); - $newObj->update(); - - // handle image(s) - if($a_rec["Image"]) - { - $dir = str_replace("..", "", $a_rec["Dir"]); - if ($dir != "" && $this->getImportDirectory() != "") - { - $source_dir = $this->getImportDirectory()."/".$dir; - $target_dir = ilObjPoll::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 "poll": + include_once("./Modules/Poll/classes/class.ilObjPoll.php"); + + // container copy + if ($new_id = $a_mapping->getMapping("Services/Container", "objs", $a_rec["Id"])) { + $newObj = ilObjectFactory::getInstanceByObjId($new_id, false); + } else { + $newObj = new ilObjPoll(); + $newObj->create(); + } + + $newObj->setTitle($a_rec["Title"]); + $newObj->setDescription($a_rec["Description"]); + if ((int) $a_rec["MaxAnswers"]) { + $newObj->setMaxNumberOfAnswers($a_rec["MaxAnswers"]); + } + $newObj->setSortResultByVotes((bool) $a_rec["ResultSort"]); + $newObj->setNonAnonymous((bool) $a_rec["NonAnon"]); + if ((int) $a_rec["ShowResultsAs"]) { + $newObj->setShowResultsAs($a_rec["ShowResultsAs"]); + } + $newObj->setShowComments($a_rec["ShowComments"]); + $newObj->setQuestion($a_rec["Question"]); + $newObj->setImage($a_rec["Image"]); + $newObj->setViewResults($a_rec["ViewResults"]); + $newObj->setVotingPeriod($a_rec["Period"]); + $newObj->setVotingPeriodBegin($a_rec["PeriodBegin"]); + $newObj->setVotingPeriodEnd($a_rec["PeriodEnd"]); + $newObj->update(); + + // handle image(s) + if ($a_rec["Image"]) { + $dir = str_replace("..", "", $a_rec["Dir"]); + if ($dir != "" && $this->getImportDirectory() != "") { + $source_dir = $this->getImportDirectory() . "/" . $dir; + $target_dir = ilObjPoll::initStorage($newObj->getId()); + ilUtil::rCopy($source_dir, $target_dir); + } + } - $a_mapping->addMapping("Modules/Poll", "poll", $a_rec["Id"], $newObj->getId()); - break; + $a_mapping->addMapping("Modules/Poll", "poll", $a_rec["Id"], $newObj->getId()); + break; - case "poll_answer": - $poll_id = (int) $a_mapping->getMapping("Modules/Poll", "poll", $a_rec["PollId"]); - if($poll_id) - { - $poll = new ilObjPoll($poll_id, false); - $poll->saveAnswer($a_rec["Answer"], $a_rec["pos"]); - } - break; - } - } + case "poll_answer": + $poll_id = (int) $a_mapping->getMapping("Modules/Poll", "poll", $a_rec["PollId"]); + if ($poll_id) { + $poll = new ilObjPoll($poll_id, false); + $poll->saveAnswer($a_rec["Answer"], $a_rec["pos"]); + } + break; + } + } } - -?> \ No newline at end of file diff --git a/Modules/Poll/classes/class.ilPollExporter.php b/Modules/Poll/classes/class.ilPollExporter.php index 0cde4b26e604ed3b73d3aa19ee2280566353cb37..ea0920afdd3884210ff0c10613928450e447118a 100644 --- a/Modules/Poll/classes/class.ilPollExporter.php +++ b/Modules/Poll/classes/class.ilPollExporter.php @@ -1,50 +1,48 @@ - - * @version $Id$ - * - * @ingroup ModulesPoll - */ -class ilPollExporter extends ilXmlExporter -{ - protected $ds; - - public function init() - { - include_once("./Modules/Poll/classes/class.ilPollDataSet.php"); - $this->ds = new ilPollDataSet(); - $this->ds->setDSPrefix("ds"); - } - - 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/Services/Modules/Poll/4_3", - "xsd_file" => "ilias_poll_4_3.xsd", - "uses_dataset" => true, - "min" => "4.3.0", - "max" => "4.4.99"), - "5.0.0" => array( - "namespace" => "http://www.ilias.de/Services/Modules/Poll/5_0", - "xsd_file" => "ilias_poll_5_0.xsd", - "uses_dataset" => true, - "min" => "5.0.0", - "max" => "") - ); - } - -} -?> \ No newline at end of file + + * @version $Id$ + * + * @ingroup ModulesPoll + */ +class ilPollExporter extends ilXmlExporter +{ + protected $ds; + + public function init() + { + include_once("./Modules/Poll/classes/class.ilPollDataSet.php"); + $this->ds = new ilPollDataSet(); + $this->ds->setDSPrefix("ds"); + } + + 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/Services/Modules/Poll/4_3", + "xsd_file" => "ilias_poll_4_3.xsd", + "uses_dataset" => true, + "min" => "4.3.0", + "max" => "4.4.99"), + "5.0.0" => array( + "namespace" => "http://www.ilias.de/Services/Modules/Poll/5_0", + "xsd_file" => "ilias_poll_5_0.xsd", + "uses_dataset" => true, + "min" => "5.0.0", + "max" => "") + ); + } +} diff --git a/Modules/Poll/classes/class.ilPollImporter.php b/Modules/Poll/classes/class.ilPollImporter.php index 89434328d4689b6c9e7aafefedc8814a59c1f9a8..2b0fd01aac331da7b6776d02d21c43edf49f6873 100644 --- a/Modules/Poll/classes/class.ilPollImporter.php +++ b/Modules/Poll/classes/class.ilPollImporter.php @@ -12,31 +12,34 @@ include_once("./Services/Export/classes/class.ilXmlImporter.php"); */ class ilPollImporter extends ilXmlImporter { - protected $ds; - - /** - * Initialisation - */ - function init() - { - include_once("./Modules/Poll/classes/class.ilPollDataSet.php"); - $this->ds = new ilPollDataSet(); - $this->ds->setDSPrefix("ds"); - } + protected $ds; + + /** + * Initialisation + */ + public function init() + { + include_once("./Modules/Poll/classes/class.ilPollDataSet.php"); + $this->ds = new ilPollDataSet(); + $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); - } + /** + * 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 + ); + } } - -?> \ No newline at end of file diff --git a/Modules/Poll/classes/class.ilPollUserTableGUI.php b/Modules/Poll/classes/class.ilPollUserTableGUI.php index d6dc85be872aa501989453b39f7760443699ea6b..024e2a69fe6e68f9830d65137377fec2a8057776 100644 --- a/Modules/Poll/classes/class.ilPollUserTableGUI.php +++ b/Modules/Poll/classes/class.ilPollUserTableGUI.php @@ -1,135 +1,118 @@ - -* @version $Id$ -* -* @ingroup ModulesPoll -*/ -class ilPollUserTableGUI extends ilTable2GUI -{ - protected $answer_ids; // [array] - - function __construct($a_parent_obj, $a_parent_cmd) - { - global $DIC; +ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->setId("ilobjpollusr"); - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->addColumn($lng->txt("login"), "login"); - $this->addColumn($lng->txt("lastname"), "lastname"); - $this->addColumn($lng->txt("firstname"), "firstname"); - - foreach($this->getParentObject()->object->getAnswers() as $answer) - { - $this->answer_ids[] = $answer["id"]; - $this->addColumn($answer["answer"], "answer".$answer["id"]); - } - - $this->getItems($this->answer_ids); - - $this->setTitle($this->lng->txt("poll_question").": \"". - $this->getParentObject()->object->getQuestion()."\""); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd)); - $this->setRowTemplate("tpl.user_row.html", "Modules/Poll"); - $this->setDefaultOrderField("login"); - $this->setDefaultOrderDirection("asc"); - - $this->setExportFormats(array(self::EXPORT_CSV, self::EXPORT_EXCEL)); - } - - protected function getItems(array $a_answer_ids) - { - $data = array(); - - foreach($this->getParentObject()->object->getVotesByUsers() as $user_id => $vote) - { - $answers = $vote["answers"]; - unset($vote["answers"]); - - foreach($a_answer_ids as $answer_id) - { - $vote["answer".$answer_id] = in_array($answer_id, $answers); - } - - $data[] = $vote; - } - - $this->setData($data); - } - - protected function fillRow($a_set) - { - $this->tpl->setCurrentBlock("answer_bl"); - foreach($this->answer_ids as $answer_id) - { - if($a_set["answer".$answer_id]) - { - $this->tpl->setVariable("ANSWER", ''); - } - else - { - $this->tpl->setVariable("ANSWER", " "); - } - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setVariable("LOGIN", $a_set["login"]); - $this->tpl->setVariable("FIRSTNAME", $a_set["firstname"]); - $this->tpl->setVariable("LASTNAME", $a_set["lastname"]); - } - - protected function fillRowCSV($a_csv, $a_set) - { - $a_csv->addColumn($a_set["login"]); - $a_csv->addColumn($a_set["lastname"]); - $a_csv->addColumn($a_set["firstname"]); - foreach($this->answer_ids as $answer_id) - { - if($a_set["answer".$answer_id]) - { - $a_csv->addColumn(true); - } - else - { - $a_csv->addColumn(false); - } - } - $a_csv->addRow(); - } - - protected function fillRowExcel(ilExcel $a_excel, &$a_row, $a_set) - { - $a_excel->setCell($a_row, 0, $a_set["login"]); - $a_excel->setCell($a_row, 1, $a_set["lastname"]); - $a_excel->setCell($a_row, 2, $a_set["firstname"]); - - $col = 2; - foreach($this->answer_ids as $answer_id) - { - if($a_set["answer".$answer_id]) - { - $a_excel->setCell($a_row, ++$col, true); - } - else - { - $a_excel->setCell($a_row, ++$col, false); - } - } - } -} - -?> \ No newline at end of file +include_once("./Services/Table/classes/class.ilTable2GUI.php"); + +/** +* TableGUI class for poll users +* +* @author Jörg Lützenkirchen +* @version $Id$ +* +* @ingroup ModulesPoll +*/ +class ilPollUserTableGUI extends ilTable2GUI +{ + protected $answer_ids; // [array] + + public function __construct($a_parent_obj, $a_parent_cmd) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->setId("ilobjpollusr"); + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->addColumn($lng->txt("login"), "login"); + $this->addColumn($lng->txt("lastname"), "lastname"); + $this->addColumn($lng->txt("firstname"), "firstname"); + + foreach ($this->getParentObject()->object->getAnswers() as $answer) { + $this->answer_ids[] = $answer["id"]; + $this->addColumn($answer["answer"], "answer" . $answer["id"]); + } + + $this->getItems($this->answer_ids); + + $this->setTitle($this->lng->txt("poll_question") . ": \"" . + $this->getParentObject()->object->getQuestion() . "\""); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd)); + $this->setRowTemplate("tpl.user_row.html", "Modules/Poll"); + $this->setDefaultOrderField("login"); + $this->setDefaultOrderDirection("asc"); + + $this->setExportFormats(array(self::EXPORT_CSV, self::EXPORT_EXCEL)); + } + + protected function getItems(array $a_answer_ids) + { + $data = array(); + + foreach ($this->getParentObject()->object->getVotesByUsers() as $user_id => $vote) { + $answers = $vote["answers"]; + unset($vote["answers"]); + + foreach ($a_answer_ids as $answer_id) { + $vote["answer" . $answer_id] = in_array($answer_id, $answers); + } + + $data[] = $vote; + } + + $this->setData($data); + } + + protected function fillRow($a_set) + { + $this->tpl->setCurrentBlock("answer_bl"); + foreach ($this->answer_ids as $answer_id) { + if ($a_set["answer" . $answer_id]) { + $this->tpl->setVariable("ANSWER", ''); + } else { + $this->tpl->setVariable("ANSWER", " "); + } + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setVariable("LOGIN", $a_set["login"]); + $this->tpl->setVariable("FIRSTNAME", $a_set["firstname"]); + $this->tpl->setVariable("LASTNAME", $a_set["lastname"]); + } + + protected function fillRowCSV($a_csv, $a_set) + { + $a_csv->addColumn($a_set["login"]); + $a_csv->addColumn($a_set["lastname"]); + $a_csv->addColumn($a_set["firstname"]); + foreach ($this->answer_ids as $answer_id) { + if ($a_set["answer" . $answer_id]) { + $a_csv->addColumn(true); + } else { + $a_csv->addColumn(false); + } + } + $a_csv->addRow(); + } + + protected function fillRowExcel(ilExcel $a_excel, &$a_row, $a_set) + { + $a_excel->setCell($a_row, 0, $a_set["login"]); + $a_excel->setCell($a_row, 1, $a_set["lastname"]); + $a_excel->setCell($a_row, 2, $a_set["firstname"]); + + $col = 2; + foreach ($this->answer_ids as $answer_id) { + if ($a_set["answer" . $answer_id]) { + $a_excel->setCell($a_row, ++$col, true); + } else { + $a_excel->setCell($a_row, ++$col, false); + } + } + } +} diff --git a/Modules/Portfolio/classes/class.ilFSStoragePortfolio.php b/Modules/Portfolio/classes/class.ilFSStoragePortfolio.php index 459ae3328654ed9428c36bf1285ee61bbd7b8110..1218864e9d98ba6ee624c6e50b78a7589341754c 100644 --- a/Modules/Portfolio/classes/class.ilFSStoragePortfolio.php +++ b/Modules/Portfolio/classes/class.ilFSStoragePortfolio.php @@ -1,50 +1,48 @@ - -* @version $Id$ -* -* @ingroup ModulesPortfolio -*/ -class ilFSStoragePortfolio extends ilFileSystemStorage -{ - public function __construct($a_container_id = 0) - { - parent::__construct(self::STORAGE_SECURED, true, $a_container_id); - } - - protected function getPathPostfix() - { - return 'prtf'; - } - - protected function getPathPrefix() - { - return 'ilPortfolio'; - } -} - -?> \ No newline at end of file + +* @version $Id$ +* +* @ingroup ModulesPortfolio +*/ +class ilFSStoragePortfolio extends ilFileSystemStorage +{ + public function __construct($a_container_id = 0) + { + parent::__construct(self::STORAGE_SECURED, true, $a_container_id); + } + + protected function getPathPostfix() + { + return 'prtf'; + } + + protected function getPathPrefix() + { + return 'ilPortfolio'; + } +} diff --git a/Modules/Portfolio/classes/class.ilObjPortfolio.php b/Modules/Portfolio/classes/class.ilObjPortfolio.php index 233f8d663d501b67ddd0f3beb51e25aa6c7daf43..ecddd290cc300afbfaec6427e4e0aca11bae68fe 100644 --- a/Modules/Portfolio/classes/class.ilObjPortfolio.php +++ b/Modules/Portfolio/classes/class.ilObjPortfolio.php @@ -1,257 +1,242 @@ - - * @version $Id$ - * - * @ingroup ModulesPortfolio - */ -class ilObjPortfolio extends ilObjPortfolioBase -{ - protected $default; // [bool] - - function initType() - { - $this->type = "prtf"; - } - - // - // PROPERTIES - // - - /** - * Set default - * - * @param bool $a_value - */ - function setDefault($a_value) - { - $this->default = (bool)$a_value; - } - - /** - * Is default? - * - * @return bool - */ - function isDefault() - { - return $this->default; - } - - - // - // CRUD - // - - protected function doReadCustom(array $a_row) - { - $this->setDefault((bool)$a_row["is_default"]); - } - - protected function doUpdate() - { - // must be online to be default - if(!$this->isOnline() && $this->isDefault()) - { - $this->setDefault(false); - } - - parent::doUpdate(); - } - - protected function doUpdateCustom(array &$a_fields) - { - $a_fields["is_default"] = array("integer", $this->isDefault()); - } - - protected function deleteAllPages() - { - // delete pages - include_once "Modules/Portfolio/classes/class.ilPortfolioPage.php"; - $pages = ilPortfolioPage::getAllPortfolioPages($this->id); - foreach($pages as $page) - { - $page_obj = new ilPortfolioPage($page["id"]); - $page_obj->setPortfolioId($this->id); - $page_obj->delete(); - } - } - - - // - // HELPER - // - - /** - * Set the user default portfolio - * - * @param int $a_user_id - * @param int $a_portfolio_id - */ - public static function setUserDefault($a_user_id, $a_portfolio_id = null) - { - global $DIC; +database(); - - $all = array(); - foreach(self::getPortfoliosOfUser($a_user_id) as $item) - { - $all[] = $item["id"]; - } - if($all) - { - $ilDB->manipulate("UPDATE usr_portfolio". - " SET is_default = ".$ilDB->quote(false, "integer"). - " WHERE ".$ilDB->in("id", $all, "", "integer")); - } - - if($a_portfolio_id) - { - $ilDB->manipulate("UPDATE usr_portfolio". - " SET is_default = ".$ilDB->quote(true, "integer"). - " WHERE id = ".$ilDB->quote($a_portfolio_id, "integer")); - } - } - - /** - * Get views of user - * - * @param int $a_user_id - * @return array - */ - static function getPortfoliosOfUser($a_user_id) - { - global $DIC; +require_once "Modules/Portfolio/classes/class.ilObjPortfolioBase.php"; - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT up.*,od.title,od.description". - " FROM usr_portfolio up". - " JOIN object_data od ON (up.id = od.obj_id)". - " WHERE od.owner = ".$ilDB->quote($a_user_id, "integer"). - " AND od.type = ".$ilDB->quote("prtf", "text"). - " ORDER BY od.title"); - $res = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $res[] = $rec; - } - return $res; - } - - /** - * Get default portfolio of user - * - * @param type $a_user_id - * @return int - */ - static function getDefaultPortfolio($a_user_id) - { - global $DIC; +/** + * Portfolio + * + * @author Jörg Lützenkirchen + * @version $Id$ + * + * @ingroup ModulesPortfolio + */ +class ilObjPortfolio extends ilObjPortfolioBase +{ + protected $default; // [bool] - $ilDB = $DIC->database(); - $ilSetting = $DIC->settings(); - - if(!$ilSetting->get('user_portfolios')) - { - return; - } - - $set = $ilDB->query("SELECT up.id FROM usr_portfolio up". - " JOIN object_data od ON (up.id = od.obj_id)". - " WHERE od.owner = ".$ilDB->quote($a_user_id, "integer"). - " AND up.is_default = ".$ilDB->quote(1, "integer")); - $res = $ilDB->fetchAssoc($set); - if($res["id"]) - { - return $res["id"]; - } - } - - /** - * Delete all portfolio data for user - * - * @param int $a_user_id - */ - public static function deleteUserPortfolios($a_user_id) - { - $all = self::getPortfoliosOfUser($a_user_id); - if($all) - { - include_once "Modules/Portfolio/classes/class.ilPortfolioAccessHandler.php"; - $access_handler = new ilPortfolioAccessHandler(); - - foreach($all as $item) - { - $access_handler->removePermission($item["id"]); - - $portfolio = new self($item["id"], false); - $portfolio->delete(); - } - } - } - - public function deleteImage() - { - if($this->id) - { - parent::deleteImage(); - $this->handleQuotaUpdate(); - } - } - - function uploadImage(array $a_upload) - { - if(parent::uploadImage($a_upload)) - { - $this->handleQuotaUpdate(); - return true; - } - return false; - } - - 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()), - true); - } - - public static function getAvailablePortfolioLinksForUserIds(array $a_owner_ids, $a_back_url = null) - { - $res = array(); - - include_once "Modules/Portfolio/classes/class.ilPortfolioAccessHandler.php"; - $access_handler = new ilPortfolioAccessHandler(); - - $params = null; - if($a_back_url) - { - $params = array("back_url"=>rawurlencode($a_back_url)); - } - - include_once "Services/Link/classes/class.ilLink.php"; - foreach($access_handler->getShardObjectsDataForUserIds($a_owner_ids) as $owner_id => $items) - { - foreach($items as $id => $title) - { - $url = ilLink::_getLink($id, 'prtf', $params); - $res[$owner_id][$url] = $title; - } - } - - return $res; - } -} - -?> \ No newline at end of file + public function initType() + { + $this->type = "prtf"; + } + + // + // PROPERTIES + // + + /** + * Set default + * + * @param bool $a_value + */ + public function setDefault($a_value) + { + $this->default = (bool) $a_value; + } + + /** + * Is default? + * + * @return bool + */ + public function isDefault() + { + return $this->default; + } + + + // + // CRUD + // + + protected function doReadCustom(array $a_row) + { + $this->setDefault((bool) $a_row["is_default"]); + } + + protected function doUpdate() + { + // must be online to be default + if (!$this->isOnline() && $this->isDefault()) { + $this->setDefault(false); + } + + parent::doUpdate(); + } + + protected function doUpdateCustom(array &$a_fields) + { + $a_fields["is_default"] = array("integer", $this->isDefault()); + } + + protected function deleteAllPages() + { + // delete pages + include_once "Modules/Portfolio/classes/class.ilPortfolioPage.php"; + $pages = ilPortfolioPage::getAllPortfolioPages($this->id); + foreach ($pages as $page) { + $page_obj = new ilPortfolioPage($page["id"]); + $page_obj->setPortfolioId($this->id); + $page_obj->delete(); + } + } + + + // + // HELPER + // + + /** + * Set the user default portfolio + * + * @param int $a_user_id + * @param int $a_portfolio_id + */ + public static function setUserDefault($a_user_id, $a_portfolio_id = null) + { + global $DIC; + + $ilDB = $DIC->database(); + + $all = array(); + foreach (self::getPortfoliosOfUser($a_user_id) as $item) { + $all[] = $item["id"]; + } + if ($all) { + $ilDB->manipulate("UPDATE usr_portfolio" . + " SET is_default = " . $ilDB->quote(false, "integer") . + " WHERE " . $ilDB->in("id", $all, "", "integer")); + } + + if ($a_portfolio_id) { + $ilDB->manipulate("UPDATE usr_portfolio" . + " SET is_default = " . $ilDB->quote(true, "integer") . + " WHERE id = " . $ilDB->quote($a_portfolio_id, "integer")); + } + } + + /** + * Get views of user + * + * @param int $a_user_id + * @return array + */ + public static function getPortfoliosOfUser($a_user_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query("SELECT up.*,od.title,od.description" . + " FROM usr_portfolio up" . + " JOIN object_data od ON (up.id = od.obj_id)" . + " WHERE od.owner = " . $ilDB->quote($a_user_id, "integer") . + " AND od.type = " . $ilDB->quote("prtf", "text") . + " ORDER BY od.title"); + $res = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $res[] = $rec; + } + return $res; + } + + /** + * Get default portfolio of user + * + * @param type $a_user_id + * @return int + */ + public static function getDefaultPortfolio($a_user_id) + { + global $DIC; + + $ilDB = $DIC->database(); + $ilSetting = $DIC->settings(); + + if (!$ilSetting->get('user_portfolios')) { + return; + } + + $set = $ilDB->query("SELECT up.id FROM usr_portfolio up" . + " JOIN object_data od ON (up.id = od.obj_id)" . + " WHERE od.owner = " . $ilDB->quote($a_user_id, "integer") . + " AND up.is_default = " . $ilDB->quote(1, "integer")); + $res = $ilDB->fetchAssoc($set); + if ($res["id"]) { + return $res["id"]; + } + } + + /** + * Delete all portfolio data for user + * + * @param int $a_user_id + */ + public static function deleteUserPortfolios($a_user_id) + { + $all = self::getPortfoliosOfUser($a_user_id); + if ($all) { + include_once "Modules/Portfolio/classes/class.ilPortfolioAccessHandler.php"; + $access_handler = new ilPortfolioAccessHandler(); + + foreach ($all as $item) { + $access_handler->removePermission($item["id"]); + + $portfolio = new self($item["id"], false); + $portfolio->delete(); + } + } + } + + public function deleteImage() + { + if ($this->id) { + parent::deleteImage(); + $this->handleQuotaUpdate(); + } + } + + public function uploadImage(array $a_upload) + { + if (parent::uploadImage($a_upload)) { + $this->handleQuotaUpdate(); + return true; + } + return false; + } + + 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()), + true + ); + } + + public static function getAvailablePortfolioLinksForUserIds(array $a_owner_ids, $a_back_url = null) + { + $res = array(); + + include_once "Modules/Portfolio/classes/class.ilPortfolioAccessHandler.php"; + $access_handler = new ilPortfolioAccessHandler(); + + $params = null; + if ($a_back_url) { + $params = array("back_url"=>rawurlencode($a_back_url)); + } + + include_once "Services/Link/classes/class.ilLink.php"; + foreach ($access_handler->getShardObjectsDataForUserIds($a_owner_ids) as $owner_id => $items) { + foreach ($items as $id => $title) { + $url = ilLink::_getLink($id, 'prtf', $params); + $res[$owner_id][$url] = $title; + } + } + + return $res; + } +} diff --git a/Modules/Portfolio/classes/class.ilObjPortfolioAccess.php b/Modules/Portfolio/classes/class.ilObjPortfolioAccess.php index 2b701c428f032b95f6b60d802c6bf8c3df4d4368..508009a509dfc4ac072685cc5e84faf513596091 100644 --- a/Modules/Portfolio/classes/class.ilObjPortfolioAccess.php +++ b/Modules/Portfolio/classes/class.ilObjPortfolioAccess.php @@ -1,26 +1,24 @@ - -* @version $Id: class.ilObjRootFolderAccess.php 15678 2008-01-06 20:40:55Z akill $ -* -*/ -class ilObjPortfolioAccess -{ - /** - * check whether goto script will succeed - */ - static function _checkGoto($a_target) - { - $t_arr = explode("_", $a_target); - - include_once "Services/PersonalWorkspace/classes/class.ilSharedResourceGUI.php"; - return ilSharedResourceGUI::hasAccess($t_arr[1], true); - } -} - -?> + +* @version $Id: class.ilObjRootFolderAccess.php 15678 2008-01-06 20:40:55Z akill $ +* +*/ +class ilObjPortfolioAccess +{ + /** + * check whether goto script will succeed + */ + public static function _checkGoto($a_target) + { + $t_arr = explode("_", $a_target); + + include_once "Services/PersonalWorkspace/classes/class.ilSharedResourceGUI.php"; + return ilSharedResourceGUI::hasAccess($t_arr[1], true); + } +} diff --git a/Modules/Portfolio/classes/class.ilObjPortfolioAdministration.php b/Modules/Portfolio/classes/class.ilObjPortfolioAdministration.php index bb9ad21bf9fd43ed3a2f596c89a3c9d7cd33138a..a77bb898c280e35acef4815b68a90f8d6b233e49 100644 --- a/Modules/Portfolio/classes/class.ilObjPortfolioAdministration.php +++ b/Modules/Portfolio/classes/class.ilObjPortfolioAdministration.php @@ -3,7 +3,7 @@ /** * Class ilObjPortfolioAdministration -* +* * @author Jörg Lützenkirchen * @version $Id:$ * @@ -14,37 +14,34 @@ require_once "./Services/Object/classes/class.ilObject.php"; class ilObjPortfolioAdministration extends ilObject { - /** - * Constructor - * @access public - * @param integer reference_id or object_id - * @param boolean treat the id as reference_id (true) or object_id (false) - */ - public function __construct($a_id = 0,$a_call_by_reference = true) - { - $this->type = "prfa"; - parent::__construct($a_id,$a_call_by_reference); - - $this->lng->loadLanguageModule("prtf"); - } + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + $this->type = "prfa"; + parent::__construct($a_id, $a_call_by_reference); - /** - * update object data - * - * @access public - * @return boolean - */ - public function update() - { - if (!parent::update()) - { - return false; - } + $this->lng->loadLanguageModule("prtf"); + } - // put here object specific stuff - - return true; - } + /** + * update object data + * + * @access public + * @return boolean + */ + public function update() + { + if (!parent::update()) { + return false; + } -} -?> + // put here object specific stuff + + return true; + } +} diff --git a/Modules/Portfolio/classes/class.ilObjPortfolioAdministrationAccess.php b/Modules/Portfolio/classes/class.ilObjPortfolioAdministrationAccess.php index f39c3fd6b3fec5497ff65233ffd4de9372fd44b6..7fabd2039b7ba34e07c31db9d783df8fc9b5ea0e 100644 --- a/Modules/Portfolio/classes/class.ilObjPortfolioAdministrationAccess.php +++ b/Modules/Portfolio/classes/class.ilObjPortfolioAdministrationAccess.php @@ -13,8 +13,4 @@ include_once("./Services/Object/classes/class.ilObjectAccess.php"); */ class ilObjPortfolioAdministrationAccess extends ilObjectAccess { - - } - -?> diff --git a/Modules/Portfolio/classes/class.ilObjPortfolioAdministrationGUI.php b/Modules/Portfolio/classes/class.ilObjPortfolioAdministrationGUI.php index cd32ad2c2af70316885178bc67aa8043d8849107..ca52303c0fd86bfb628c4e8d8115e3e2fa1084cb 100644 --- a/Modules/Portfolio/classes/class.ilObjPortfolioAdministrationGUI.php +++ b/Modules/Portfolio/classes/class.ilObjPortfolioAdministrationGUI.php @@ -15,353 +15,340 @@ include_once("./Services/Object/classes/class.ilObjectGUI.php"); */ class ilObjPortfolioAdministrationGUI extends ilObjectGUI { - /** - * @var \ILIAS\DI\UIServices - */ - protected $ui; - - /** - * @var \Psr\Http\Message\ServerRequestInterface - */ - protected $request; - - /** - * @var ilPortfolioDeclarationOfAuthorship - */ - protected $declaration_authorship; - - /** - * Contructor - * - * @access public - */ - public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) - { - global $DIC; - - $this->lng = $DIC->language(); - $this->settings = $DIC->settings(); - $this->ctrl = $DIC->ctrl(); - $this->access = $DIC->access(); - $this->type = "prfa"; - $this->ui = $DIC->ui(); - $this->request = $DIC->http()->request(); - parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); - - $this->declaration_authorship = new ilPortfolioDeclarationOfAuthorship(); - - $this->lng->loadLanguageModule("prtf"); - } - - /** - * Execute command - * - * @access public - * - */ - public function executeCommand() - { - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - $this->prepareOutput(); - - switch($next_class) - { - case 'ilpermissiongui': - $this->tabs_gui->activateTab('perm_settings'); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $this->ctrl->forwardCommand($perm_gui); - break; - - default: - if(!$cmd || $cmd == 'view') - { - $cmd = "editSettings"; - } - - $this->$cmd(); - break; - } - return true; - } - - /** - * Get tabs - * - * @access public - * - */ - public function getAdminTabs() - { - $lng = $this->lng; - $tabs = $this->tabs_gui; - - - if ($this->checkPermissionBool("visible,read")) - { - $tabs->addTab("settings", $lng->txt("settings"), - $this->ctrl->getLinkTarget($this, "editSettings")); - $tabs->addTab("authorship", $lng->txt("prtf_decl_authorship"), - $this->ctrl->getLinkTarget($this, "editDeclarationOfAuthorship")); - } - - if ($this->checkPermissionBool('edit_permission')) - { - $tabs->addTab("perm_settings", $lng->txt("perm_settings"), - $this->ctrl->getLinkTargetByClass('ilpermissiongui',"perm")); - } - } - - - /** - * Edit settings. - */ - public function editSettings($a_form = null) - { - $lng = $this->lng; - $ilSetting = $this->settings; - - $this->tabs_gui->activateTab('settings'); - - /* - if ($ilSetting->get('user_portfolios')) - { - ilUtil::sendInfo($lng->txt("prtf_admin_toggle_info")); - } - else - { - ilUtil::sendInfo($lng->txt("prtf_admin_inactive_info")); - } - */ - - if(!$a_form) - { - $a_form = $this->initFormSettings(); - } - $this->tpl->setContent($a_form->getHTML()); - return true; - } - - /** - * Save settings - */ - public function saveSettings() - { - $ilCtrl = $this->ctrl; - $ilSetting = $this->settings; - - $this->checkPermission("write"); - - $form = $this->initFormSettings(); - if($form->checkInput()) - { - $ilSetting->set('user_portfolios', (int)$form->getInput("prtf")); - - $banner = (bool)$form->getInput("banner"); - - $prfa_set = new ilSetting("prfa"); - $prfa_set->set("pd_block", (bool)$form->getInput("pd_block")); - $prfa_set->set("banner", $banner); - $prfa_set->set("banner_width", (int)$form->getInput("width")); - $prfa_set->set("banner_height", (int)$form->getInput("height")); - $prfa_set->set("mask", (bool)$form->getInput("mask")); - $prfa_set->set("mycrs", (bool)$form->getInput("mycrs")); - - ilUtil::sendSuccess($this->lng->txt("settings_saved"),true); - $ilCtrl->redirect($this, "editSettings"); - } - - $form->setValuesByPost(); - $this->editSettings($form); - } - - /** - * Save settings - */ - public function cancel() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirect($this, "view"); - } - - /** - * Init settings property form - * - * @access protected - */ - protected function initFormSettings() - { - $lng = $this->lng; - $ilSetting = $this->settings; - $ilAccess = $this->access; - - include_once('Services/Form/classes/class.ilPropertyFormGUI.php'); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - $form->setTitle($this->lng->txt('prtf_settings')); - - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - $form->addCommandButton('saveSettings',$this->lng->txt('save')); - $form->addCommandButton('cancel',$this->lng->txt('cancel')); - } - - // Enable 'Portfolios' - $lng->loadLanguageModule('pd'); - $lng->loadLanguageModule('user'); - $prtf_prop = new ilCheckboxInputGUI($lng->txt('pd_enable_prtf'), 'prtf'); - $prtf_prop->setValue('1'); - $prtf_prop->setInfo($lng->txt('user_portfolios_desc')); - $prtf_prop->setChecked(($ilSetting->get('user_portfolios') ? '1' : '0')); - $form->addItem($prtf_prop); - - $prfa_set = new ilSetting("prfa"); - - $pdblock = new ilCheckboxInputGUI($lng->txt("prtf_pd_block"), "pd_block"); - $pdblock->setInfo($lng->txt("prtf_pd_block_info")); - $pdblock->setChecked($prfa_set->get("pd_block", false)); - $form->addItem($pdblock); - - $banner = new ilCheckboxInputGUI($lng->txt("prtf_preview_banner"), "banner"); - $banner->setInfo($lng->txt("prtf_preview_banner_info")); - $form->addItem($banner); - - $width = new ilNumberInputGUI($lng->txt("prtf_preview_banner_width"), "width"); - $width->setRequired(true); - $width->setSize(4); - $banner->addSubItem($width); - - $height = new ilNumberInputGUI($lng->txt("prtf_preview_banner_height"), "height"); - $height->setRequired(true); - $height->setSize(4); - $banner->addSubItem($height); - - $banner->setChecked($prfa_set->get("banner", false)); - if($prfa_set->get("banner")) - { - $width->setValue($prfa_set->get("banner_width")); - $height->setValue($prfa_set->get("banner_height")); - } - else - { - $width->setValue(1370); - $height->setValue(100); - } - - $mask = new ilCheckboxInputGUI($lng->txt("prtf_allow_html"), "mask"); - $mask->setInfo($lng->txt("prtf_allow_html_info")); - $mask->setChecked($prfa_set->get("mask", false)); - $form->addItem($mask); - - $mycourses = new ilCheckboxInputGUI($lng->txt("prtf_allow_my_courses"), "mycrs"); - $mycourses->setInfo($lng->txt("prtf_allow_my_courses_info")); - $mycourses->setChecked($prfa_set->get("mycrs", true)); - $form->addItem($mycourses); - - return $form; - } - - public function addToExternalSettingsForm($a_form_id) - { - $ilSetting = $this->settings; - - switch($a_form_id) - { - case ilAdministrationSettingsFormHandler::FORM_WSP: - - $fields = array('pd_enable_prtf' => array($ilSetting->get('user_portfolios'), ilAdministrationSettingsFormHandler::VALUE_BOOL)); - - return array(array("editSettings", $fields)); - } - } - - // - // Declaration of authorship - // - - /** - * Edit declaration of authorship - */ - protected function editDeclarationOfAuthorship() - { - $main_tpl = $this->tpl; - $renderer = $ui = $this->ui->renderer(); - $form = $this->initAuthorshipForm(); - - $this->tabs_gui->activateTab("authorship"); - - $main_tpl->setContent($renderer->render($form)); - } - - /** - * Init authorship form. - * @return \ILIAS\UI\Component\Input\Container\Form\Standard - */ - public function initAuthorshipForm() - { - $ui = $this->ui; - $f = $ui->factory(); - $ctrl = $this->ctrl; - $lng = $this->lng; - - $lng->loadLanguageModule("meta"); - - foreach ($lng->getInstalledLanguages() as $l) - { - $txt = $lng->txt("meta_l_" . $l); - if ($lng->getDefaultLanguage() == $l) - { - $txt.= " (".$lng->txt("default").")"; - } - $fields["decl_" . $l] = $f->input()->field()->textarea($txt) - ->withRequired(false) - ->withValue((string) $this->declaration_authorship->getForLanguage($l)); - } - - // section - $section1 = $f->input()->field()->section($fields, $lng->txt("prtf_decl_authorship")); - - $form_action = $ctrl->getLinkTarget($this, "saveAuthorship"); - return $f->input()->container()->form()->standard($form_action, ["sec" => $section1]); - } - - /** - * Save authorship - */ - public function saveAuthorship() - { - $request = $this->request; - $form = $this->initAuthorshipForm(); - $lng = $this->lng; - $ctrl = $this->ctrl; - - if ($this->checkPermissionBool("write")) - { - if ($request->getMethod() == "POST") - { - $form = $form->withRequest($request); - $data = $form->getData(); - if (is_array($data["sec"])) - { - foreach ($lng->getInstalledLanguages() as $l) - { - $this->declaration_authorship->setForLanguage($l, $data["sec"]["decl_" . $l]); - } - - ilUtil::sendInfo($lng->txt("msg_obj_modified"), true); - } - } - } - else - { - ilUtil::sendFailure($lng->txt("msg_no_perm_write"), true); - } - $ctrl->redirect($this, "editDeclarationOfAuthorship"); - } - + /** + * @var \ILIAS\DI\UIServices + */ + protected $ui; + + /** + * @var \Psr\Http\Message\ServerRequestInterface + */ + protected $request; + + /** + * @var ilPortfolioDeclarationOfAuthorship + */ + protected $declaration_authorship; + + /** + * Contructor + * + * @access public + */ + public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) + { + global $DIC; + + $this->lng = $DIC->language(); + $this->settings = $DIC->settings(); + $this->ctrl = $DIC->ctrl(); + $this->access = $DIC->access(); + $this->type = "prfa"; + $this->ui = $DIC->ui(); + $this->request = $DIC->http()->request(); + parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); + + $this->declaration_authorship = new ilPortfolioDeclarationOfAuthorship(); + + $this->lng->loadLanguageModule("prtf"); + } + + /** + * Execute command + * + * @access public + * + */ + public function executeCommand() + { + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + $this->prepareOutput(); + + switch ($next_class) { + case 'ilpermissiongui': + $this->tabs_gui->activateTab('perm_settings'); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $this->ctrl->forwardCommand($perm_gui); + break; + + default: + if (!$cmd || $cmd == 'view') { + $cmd = "editSettings"; + } + + $this->$cmd(); + break; + } + return true; + } + + /** + * Get tabs + * + * @access public + * + */ + public function getAdminTabs() + { + $lng = $this->lng; + $tabs = $this->tabs_gui; + + + if ($this->checkPermissionBool("visible,read")) { + $tabs->addTab( + "settings", + $lng->txt("settings"), + $this->ctrl->getLinkTarget($this, "editSettings") + ); + $tabs->addTab( + "authorship", + $lng->txt("prtf_decl_authorship"), + $this->ctrl->getLinkTarget($this, "editDeclarationOfAuthorship") + ); + } + + if ($this->checkPermissionBool('edit_permission')) { + $tabs->addTab( + "perm_settings", + $lng->txt("perm_settings"), + $this->ctrl->getLinkTargetByClass('ilpermissiongui', "perm") + ); + } + } + + + /** + * Edit settings. + */ + public function editSettings($a_form = null) + { + $lng = $this->lng; + $ilSetting = $this->settings; + + $this->tabs_gui->activateTab('settings'); + + /* + if ($ilSetting->get('user_portfolios')) + { + ilUtil::sendInfo($lng->txt("prtf_admin_toggle_info")); + } + else + { + ilUtil::sendInfo($lng->txt("prtf_admin_inactive_info")); + } + */ + + if (!$a_form) { + $a_form = $this->initFormSettings(); + } + $this->tpl->setContent($a_form->getHTML()); + return true; + } + + /** + * Save settings + */ + public function saveSettings() + { + $ilCtrl = $this->ctrl; + $ilSetting = $this->settings; + + $this->checkPermission("write"); + + $form = $this->initFormSettings(); + if ($form->checkInput()) { + $ilSetting->set('user_portfolios', (int) $form->getInput("prtf")); + + $banner = (bool) $form->getInput("banner"); + + $prfa_set = new ilSetting("prfa"); + $prfa_set->set("pd_block", (bool) $form->getInput("pd_block")); + $prfa_set->set("banner", $banner); + $prfa_set->set("banner_width", (int) $form->getInput("width")); + $prfa_set->set("banner_height", (int) $form->getInput("height")); + $prfa_set->set("mask", (bool) $form->getInput("mask")); + $prfa_set->set("mycrs", (bool) $form->getInput("mycrs")); + + ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "editSettings"); + } + + $form->setValuesByPost(); + $this->editSettings($form); + } + + /** + * Save settings + */ + public function cancel() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirect($this, "view"); + } + + /** + * Init settings property form + * + * @access protected + */ + protected function initFormSettings() + { + $lng = $this->lng; + $ilSetting = $this->settings; + $ilAccess = $this->access; + + include_once('Services/Form/classes/class.ilPropertyFormGUI.php'); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this)); + $form->setTitle($this->lng->txt('prtf_settings')); + + if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) { + $form->addCommandButton('saveSettings', $this->lng->txt('save')); + $form->addCommandButton('cancel', $this->lng->txt('cancel')); + } + + // Enable 'Portfolios' + $lng->loadLanguageModule('pd'); + $lng->loadLanguageModule('user'); + $prtf_prop = new ilCheckboxInputGUI($lng->txt('pd_enable_prtf'), 'prtf'); + $prtf_prop->setValue('1'); + $prtf_prop->setInfo($lng->txt('user_portfolios_desc')); + $prtf_prop->setChecked(($ilSetting->get('user_portfolios') ? '1' : '0')); + $form->addItem($prtf_prop); + + $prfa_set = new ilSetting("prfa"); + + $pdblock = new ilCheckboxInputGUI($lng->txt("prtf_pd_block"), "pd_block"); + $pdblock->setInfo($lng->txt("prtf_pd_block_info")); + $pdblock->setChecked($prfa_set->get("pd_block", false)); + $form->addItem($pdblock); + + $banner = new ilCheckboxInputGUI($lng->txt("prtf_preview_banner"), "banner"); + $banner->setInfo($lng->txt("prtf_preview_banner_info")); + $form->addItem($banner); + + $width = new ilNumberInputGUI($lng->txt("prtf_preview_banner_width"), "width"); + $width->setRequired(true); + $width->setSize(4); + $banner->addSubItem($width); + + $height = new ilNumberInputGUI($lng->txt("prtf_preview_banner_height"), "height"); + $height->setRequired(true); + $height->setSize(4); + $banner->addSubItem($height); + + $banner->setChecked($prfa_set->get("banner", false)); + if ($prfa_set->get("banner")) { + $width->setValue($prfa_set->get("banner_width")); + $height->setValue($prfa_set->get("banner_height")); + } else { + $width->setValue(1370); + $height->setValue(100); + } + + $mask = new ilCheckboxInputGUI($lng->txt("prtf_allow_html"), "mask"); + $mask->setInfo($lng->txt("prtf_allow_html_info")); + $mask->setChecked($prfa_set->get("mask", false)); + $form->addItem($mask); + + $mycourses = new ilCheckboxInputGUI($lng->txt("prtf_allow_my_courses"), "mycrs"); + $mycourses->setInfo($lng->txt("prtf_allow_my_courses_info")); + $mycourses->setChecked($prfa_set->get("mycrs", true)); + $form->addItem($mycourses); + + return $form; + } + + public function addToExternalSettingsForm($a_form_id) + { + $ilSetting = $this->settings; + + switch ($a_form_id) { + case ilAdministrationSettingsFormHandler::FORM_WSP: + + $fields = array('pd_enable_prtf' => array($ilSetting->get('user_portfolios'), ilAdministrationSettingsFormHandler::VALUE_BOOL)); + + return array(array("editSettings", $fields)); + } + } + + // + // Declaration of authorship + // + + /** + * Edit declaration of authorship + */ + protected function editDeclarationOfAuthorship() + { + $main_tpl = $this->tpl; + $renderer = $ui = $this->ui->renderer(); + $form = $this->initAuthorshipForm(); + + $this->tabs_gui->activateTab("authorship"); + + $main_tpl->setContent($renderer->render($form)); + } + + /** + * Init authorship form. + * @return \ILIAS\UI\Component\Input\Container\Form\Standard + */ + public function initAuthorshipForm() + { + $ui = $this->ui; + $f = $ui->factory(); + $ctrl = $this->ctrl; + $lng = $this->lng; + + $lng->loadLanguageModule("meta"); + + foreach ($lng->getInstalledLanguages() as $l) { + $txt = $lng->txt("meta_l_" . $l); + if ($lng->getDefaultLanguage() == $l) { + $txt.= " (" . $lng->txt("default") . ")"; + } + $fields["decl_" . $l] = $f->input()->field()->textarea($txt) + ->withRequired(false) + ->withValue((string) $this->declaration_authorship->getForLanguage($l)); + } + + // section + $section1 = $f->input()->field()->section($fields, $lng->txt("prtf_decl_authorship")); + + $form_action = $ctrl->getLinkTarget($this, "saveAuthorship"); + return $f->input()->container()->form()->standard($form_action, ["sec" => $section1]); + } + + /** + * Save authorship + */ + public function saveAuthorship() + { + $request = $this->request; + $form = $this->initAuthorshipForm(); + $lng = $this->lng; + $ctrl = $this->ctrl; + + if ($this->checkPermissionBool("write")) { + if ($request->getMethod() == "POST") { + $form = $form->withRequest($request); + $data = $form->getData(); + if (is_array($data["sec"])) { + foreach ($lng->getInstalledLanguages() as $l) { + $this->declaration_authorship->setForLanguage($l, $data["sec"]["decl_" . $l]); + } + + ilUtil::sendInfo($lng->txt("msg_obj_modified"), true); + } + } + } else { + ilUtil::sendFailure($lng->txt("msg_no_perm_write"), true); + } + $ctrl->redirect($this, "editDeclarationOfAuthorship"); + } } - -?> \ No newline at end of file diff --git a/Modules/Portfolio/classes/class.ilObjPortfolioBase.php b/Modules/Portfolio/classes/class.ilObjPortfolioBase.php index 2ea89bcf374d0a04eed5048004a3f08aaf951052..0ebf7316681e6e6107fef2577a19220b96c4e629 100644 --- a/Modules/Portfolio/classes/class.ilObjPortfolioBase.php +++ b/Modules/Portfolio/classes/class.ilObjPortfolioBase.php @@ -1,713 +1,665 @@ - - * @version $Id$ - * - * @ingroup ModulesPortfolio - */ -abstract class ilObjPortfolioBase extends ilObject2 -{ - - /** - * Constructor - */ - function __construct($a_id = 0, $a_reference = true) - { - global $DIC; - parent::__construct($a_id, $a_reference); - - $this->db = $DIC->database(); - } - - protected $online; // [bool] - protected $comments; // [bool] - protected $bg_color; // [string] - protected $font_color; // [string] - protected $img; // [string] - protected $ppic; // [string] - protected $style; // [bool] - - - // - // PROPERTIES - // - - /** - * Set online status - * - * @param bool $a_value - */ - function setOnline($a_value) - { - $this->online = (bool)$a_value; - } - - /** - * Is online? - * - * @return bool - */ - function isOnline() - { - return $this->online; - } - - /** - * Is online? - * - * @return bool - */ - public static function lookupOnline($a_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT is_online". - " FROM usr_portfolio". - " WHERE id = ".$ilDB->quote($a_id, "integer")); - $row = $ilDB->fetchAssoc($set); - return (bool)$row["is_online"]; - } - - /** - * Set public comments status - * - * @param bool $a_value - */ - function setPublicComments($a_value) - { - $this->comments = (bool)$a_value; - } - - /** - * Active public comments? - * - * @return bool - */ - function hasPublicComments() - { - return $this->comments; - } - - /** - * Get profile picture status - * - * @return bool - */ - function hasProfilePicture() - { - return $this->ppic; - } - - /** - * Toggle profile picture status - * - * @param bool $a_status - */ - function setProfilePicture($a_status) - { - $this->ppic = (bool)$a_status; - } - - /** - * Get background color - * - * @return string - */ - function getBackgroundColor() - { - if(!$this->bg_color) - { - $this->bg_color = "ffffff"; - } - return $this->bg_color; - } - - /** - * Set background color - * - * @param string $a_value - */ - function setBackgroundColor($a_value) - { - $this->bg_color = (string)$a_value; - } - - /** - * Get font color - * - * @return string - */ - function getFontColor() - { - if(!$this->font_color) - { - $this->font_color = "505050"; - } - return $this->font_color; - } - - /** - * Set font color - * - * @param string $a_value - */ - function setFontColor($a_value) - { - $this->font_color = (string)$a_value; - } - - /** - * Get banner image - * - * @return string - */ - function getImage() - { - return $this->img; - } - - /** - * Set banner image - * - * @param string $a_value - */ - function setImage($a_value) - { - $this->img = (string)$a_value; - } - - /** - * Get style sheet id - * - * @return bool - */ - function getStyleSheetId() - { - return (int)$this->style; - } - - /** - * Set style sheet id - * - * @param int $a_style - */ - function setStyleSheetId($a_style) - { - $this->style = (int)$a_style; - } - - - // - // CRUD - // - - protected function doRead() - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT * FROM usr_portfolio". - " WHERE id = ".$ilDB->quote($this->id, "integer")); - $row = $ilDB->fetchAssoc($set); - - $this->setOnline((bool)$row["is_online"]); - $this->setProfilePicture((bool)$row["ppic"]); - $this->setBackgroundColor($row["bg_color"]); - $this->setFontColor($row["font_color"]); - $this->setImage($row["img"]); - - // #14661 - include_once("./Services/Notes/classes/class.ilNote.php"); - $this->setPublicComments(ilNote::commentsActivated($this->id, 0, $this->getType())); - - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $this->setStyleSheetId(ilObjStyleSheet::lookupObjectStyle($this->id)); - - $this->doReadCustom($row); - } - - protected function doReadCustom(array $a_row) - { - - } - - protected function doCreate() - { - $ilDB = $this->db; - - $ilDB->manipulate("INSERT INTO usr_portfolio (id,is_online)". - " VALUES (".$ilDB->quote($this->id, "integer").",". - $ilDB->quote(0, "integer").")"); - } - - protected function doUpdate() - { - $ilDB = $this->db; - - $fields = array( - "is_online" => array("integer", $this->isOnline()), - "ppic" => array("integer", $this->hasProfilePicture()), - "bg_color" => array("text", $this->getBackgroundColor()), - "font_color" => array("text", $this->getFontcolor()), - "img" => array("text", $this->getImage()) - ); - $this->doUpdateCustom($fields); - - // #14661 - include_once("./Services/Notes/classes/class.ilNote.php"); - ilNote::activateComments($this->id, 0, $this->getType(), $this->hasPublicComments()); - - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - ilObjStyleSheet::writeStyleUsage($this->id, $this->getStyleSheetId()); - - $ilDB->update("usr_portfolio", $fields, - array("id"=>array("integer", $this->id))); - } - - protected function doUpdateCustom(array &$a_fields) - { - - } - - protected function doDelete() - { - $ilDB = $this->db; - - $this->deleteAllPages(); - $this->deleteImage(); - - $ilDB->manipulate("DELETE FROM usr_portfolio". - " WHERE id = ".$ilDB->quote($this->id, "integer")); - } - - abstract protected function deleteAllPages(); - - - // - // IMAGES - // - - /** - * Get banner image incl. path - * - * @param bool $a_as_thumb - */ - function getImageFullPath($a_as_thumb = false) - { - if($this->img) - { - $path = $this->initStorage($this->id); - if(!$a_as_thumb) - { - return $path.$this->img; - } - else - { - return $path."thb_".$this->img; - } - } - } - - /** - * remove existing file - */ - public function deleteImage() - { - if($this->id) - { - include_once "Modules/Portfolio/classes/class.ilFSStoragePortfolio.php"; - $storage = new ilFSStoragePortfolio($this->id); - $storage->delete(); - - $this->setImage(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/Portfolio/classes/class.ilFSStoragePortfolio.php"; - $storage = new ilFSStoragePortfolio($a_id); - $storage->create(); - - $path = $storage->getAbsolutePath()."/"; - - if($a_subdir) - { - $path .= $a_subdir."/"; - - if(!is_dir($path)) - { - mkdir($path); - } - } - - return $path; - } - - /** - * Upload new image file - * - * @param array $a_upload - * @return bool - */ - function uploadImage(array $a_upload) - { - if(!$this->id) - { - return false; - } - - $this->deleteImage(); - - // #10074 - $clean_name = preg_replace("/[^a-zA-Z0-9\_\.\-]/", "", $a_upload["name"]); - - $path = $this->initStorage($this->id); - $original = "org_".$this->id."_".$clean_name; - $thumb = "thb_".$this->id."_".$clean_name; - $processed = $this->id."_".$clean_name; - - if (ilUtil::moveUploadedFile($a_upload["tmp_name"], $original, $path.$original)) - { - chmod($path.$original, 0770); - - $prfa_set = new ilSetting("prfa"); - /* as banner height should overflow, we only handle width - $dimensions = $prfa_set->get("banner_width")."x". - $prfa_set->get("banner_height"); - */ - $dimensions = $prfa_set->get("banner_width"); - - // take quality 100 to avoid jpeg artefacts when uploading jpeg files - // taking only frame [0] to avoid problems with animated gifs - $original_file = ilUtil::escapeShellArg($path.$original); - $thumb_file = ilUtil::escapeShellArg($path.$thumb); - $processed_file = ilUtil::escapeShellArg($path.$processed); - ilUtil::execConvert($original_file."[0] -geometry 100x100 -quality 100 JPEG:".$thumb_file); - ilUtil::execConvert($original_file."[0] -geometry ".$dimensions." -quality 100 JPEG:".$processed_file); - - $this->setImage($processed); - - return true; - } - return false; - } - - - // - // TRANSMOGRIFIER - // - - /** - * Clone basic settings - * - * @param ilObjPortfolioBase $a_source - * @param ilObjPortfolioBase $a_target - */ - protected static function cloneBasics(ilObjPortfolioBase $a_source, ilObjPortfolioBase $a_target) - { - // copy portfolio properties - $a_target->setPublicComments($a_source->hasPublicComments()); - $a_target->setProfilePicture($a_source->hasProfilePicture()); - $a_target->setFontColor($a_source->getFontColor()); - $a_target->setBackgroundColor($a_source->getBackgroundColor()); - $a_target->setImage($a_source->getImage()); - $a_target->update(); - - // banner/images - $source_dir = $a_source->initStorage($a_source->getId()); - $target_dir = $a_target->initStorage($a_target->getId()); - ilFSStoragePortfolio::_copyDirectory($source_dir, $target_dir); - - // set/copy stylesheet - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $style_id = $a_source->getStyleSheetId(); - if ($style_id > 0 && !ilObjStyleSheet::_lookupStandard($style_id)) - { - $style_obj = ilObjectFactory::getInstanceByObjId($style_id); - $new_id = $style_obj->ilClone(); - $a_target->setStyleSheetId($new_id); - $a_target->update(); - } - } - - /** - * Build template from portfolio and vice versa - * - * @param ilObjPortfolioBase $a_source - * @param ilObjPortfolioBase $a_target - * @param array $a_recipe - */ - public static function clonePagesAndSettings(ilObjPortfolioBase $a_source, ilObjPortfolioBase $a_target, array $a_recipe = null, $copy_all = false) - { - global $DIC; - - $lng = $DIC->language(); - $ilUser = $DIC->user(); - - $source_id = $a_source->getId(); - $target_id = $a_target->getId(); - - if($a_source instanceof ilObjPortfolioTemplate && - $a_target instanceof ilObjPortfolio) - { - $direction = "t2p"; - } - else if($a_source instanceof ilObjPortfolio && - $a_target instanceof ilObjPortfolioTemplate) - { - $direction = "p2t"; - } - else - { - return; - } - - self::cloneBasics($a_source, $a_target); - - // personal skills - include_once "Services/Skill/classes/class.ilPersonalSkill.php"; - $pskills = array_keys(ilPersonalSkill::getSelectedUserSkills($ilUser->getId())); - - // copy pages - $blog_count = 0; - include_once "Modules/Portfolio/classes/class.ilPortfolioTemplatePage.php"; - $page_map = array(); - foreach(ilPortfolioPage::getAllPortfolioPages($source_id) as $page) - { - $page_id = $page["id"]; - - if($direction == "t2p") - { - $source_page = new ilPortfolioTemplatePage($page_id); - $target_page = new ilPortfolioPage(); - } - else - { - $source_page = new ilPortfolioPage($page_id); - $target_page = new ilPortfolioTemplatePage(); - } - $source_page->setPortfolioId($source_id); - $target_page->setPortfolioId($target_id); - - $page_type = $source_page->getType(); - $page_title = $source_page->getTitle(); - - - - - $page_recipe = null; - if(is_array($a_recipe)) - { - $page_recipe = $a_recipe[$page_id]; - } - - $valid = false; - switch($page_type) - { - // blog => blog template - case ilPortfolioTemplatePage::TYPE_BLOG: - if($direction == "p2t") - { - $page_type = ilPortfolioTemplatePage::TYPE_BLOG_TEMPLATE; - $page_title = $lng->txt("obj_blog")." ".(++$blog_count); - $valid = true; - } - break; - - // blog template => blog (needs recipe) - case ilPortfolioTemplatePage::TYPE_BLOG_TEMPLATE: - if($direction == "t2p" && (is_array($page_recipe) || $copy_all)) - { - $page_type = ilPortfolioPage::TYPE_BLOG; - if ($copy_all) - { - $page_title = self::createBlogInPersonalWorkspace($page_title); - $valid = true; - } - else - { - if ($page_recipe[0] == "blog") - { - switch ($page_recipe[1]) - { - case "create": - $page_title = self::createBlogInPersonalWorkspace($page_recipe[2]); - $valid = true; - break; - - case "reuse": - $page_title = $page_recipe[2]; - $valid = true; - break; - - case "ignore": - // do nothing - break; - } - } - } - } - break; - - // page editor - default: - $target_page->setXMLContent($source_page->copyXmlContent(true)); // copy mobs - $target_page->buildDom(true); - - - // parse content / blocks - - if($direction == "t2p") - { - $dom = $target_page->getDom(); - if($dom instanceof php4DOMDocument) - { - $dom = $dom->myDOMDocument; - } - - // update profile/consultation hours user id - self::updateDomNodes($dom, "//PageContent/Profile", "User", $ilUser->getId()); - self::updateDomNodes($dom, "//PageContent/ConsultationHours", "User", $ilUser->getId()); - self::updateDomNodes($dom, "//PageContent/MyCourses", "User", $ilUser->getId()); - - // skills - $xpath = new DOMXPath($dom); - $nodes = $xpath->query("//PageContent/Skills"); - foreach($nodes as $node) - { - $skill_id = $node->getAttribute("Id"); - - // existing personal skills - if(in_array($skill_id, $pskills)) - { - $node->setAttribute("User", $ilUser->getId()); - } - // new skill - else if($copy_all || in_array($skill_id, $a_recipe["skills"])) - { - include_once "Services/Skill/classes/class.ilPersonalSkill.php"; - ilPersonalSkill::addPersonalSkill($ilUser->getId(), $skill_id); - - $node->setAttribute("User", $ilUser->getId()); - } - // remove skill - else - { - $page_element = $node->parentNode; - $page_element->parentNode->removeChild($page_element); - } - } - } - - $valid = true; - break; - } - - if($valid) - { - // #12038 - update xml from dom - $target_page->setXMLContent($target_page->getXMLFromDom()); - - $target_page->setType($page_type); - $target_page->setTitle($page_title); - $target_page->create(); - - if($page_type == ilPortfolioPage::TYPE_PAGE) - { - $target_page->update(); // handle mob usages! - } - $page_map[$source_page->getId()] = $target_page->getId(); - } - } - - ilPortfolioPage::updateInternalLinks($page_map, $a_target); - } - - protected static function updateDomNodes($a_dom, $a_xpath, $a_attr_id, $a_attr_value) - { - $xpath_temp = new DOMXPath($a_dom); - $nodes = $xpath_temp->query($a_xpath); - foreach ($nodes as $node) - { - $node->setAttribute($a_attr_id, $a_attr_value); - } - } - - protected static function createBlogInPersonalWorkspace($a_title) - { - global $DIC; - - $ilUser = $DIC->user(); - - static $ws_access = null; - - include_once "Modules/Blog/classes/class.ilObjBlog.php"; - $blog = new ilObjBlog(); - $blog->setType("blog"); - $blog->setTitle($a_title); - $blog->create(); - - if(!$ws_access) - { - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; - $tree = new ilWorkspaceTree($ilUser->getId()); - - // #13235 - if(!$tree->getRootId()) - { - $tree->createTreeForUser($ilUser->getId()); - } - - $ws_access = new ilWorkspaceAccessHandler($tree); - } - - $tree = $ws_access->getTree(); - $node_id = $tree->insertObject($tree->getRootId(), $blog->getId()); - $ws_access->setPermissions($tree->getRootId(), $node_id); - - return $blog->getId(); - } - - /** - * Fix internal portfolio links - * - * @param array - */ - function fixLinksOnTitleChange($a_title_changes) - { - foreach(ilPortfolioPage::getAllPortfolioPages($this->getId()) as $port_page) - { - if ($this->getType() == "prtt") - { - $page = new ilPortfolioTemplatePage($port_page["id"]); - } - else - { - $page = new ilPortfolioPage($port_page["id"]); - } - if ($page->renameLinksOnTitleChange($a_title_changes)) - { - $page->update(true, true); - } - } - } - -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @ingroup ModulesPortfolio + */ +abstract class ilObjPortfolioBase extends ilObject2 +{ + + /** + * Constructor + */ + public function __construct($a_id = 0, $a_reference = true) + { + global $DIC; + parent::__construct($a_id, $a_reference); + + $this->db = $DIC->database(); + } + + protected $online; // [bool] + protected $comments; // [bool] + protected $bg_color; // [string] + protected $font_color; // [string] + protected $img; // [string] + protected $ppic; // [string] + protected $style; // [bool] + + + // + // PROPERTIES + // + + /** + * Set online status + * + * @param bool $a_value + */ + public function setOnline($a_value) + { + $this->online = (bool) $a_value; + } + + /** + * Is online? + * + * @return bool + */ + public function isOnline() + { + return $this->online; + } + + /** + * Is online? + * + * @return bool + */ + public static function lookupOnline($a_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query("SELECT is_online" . + " FROM usr_portfolio" . + " WHERE id = " . $ilDB->quote($a_id, "integer")); + $row = $ilDB->fetchAssoc($set); + return (bool) $row["is_online"]; + } + + /** + * Set public comments status + * + * @param bool $a_value + */ + public function setPublicComments($a_value) + { + $this->comments = (bool) $a_value; + } + + /** + * Active public comments? + * + * @return bool + */ + public function hasPublicComments() + { + return $this->comments; + } + + /** + * Get profile picture status + * + * @return bool + */ + public function hasProfilePicture() + { + return $this->ppic; + } + + /** + * Toggle profile picture status + * + * @param bool $a_status + */ + public function setProfilePicture($a_status) + { + $this->ppic = (bool) $a_status; + } + + /** + * Get background color + * + * @return string + */ + public function getBackgroundColor() + { + if (!$this->bg_color) { + $this->bg_color = "ffffff"; + } + return $this->bg_color; + } + + /** + * Set background color + * + * @param string $a_value + */ + public function setBackgroundColor($a_value) + { + $this->bg_color = (string) $a_value; + } + + /** + * Get font color + * + * @return string + */ + public function getFontColor() + { + if (!$this->font_color) { + $this->font_color = "505050"; + } + return $this->font_color; + } + + /** + * Set font color + * + * @param string $a_value + */ + public function setFontColor($a_value) + { + $this->font_color = (string) $a_value; + } + + /** + * Get banner image + * + * @return string + */ + public function getImage() + { + return $this->img; + } + + /** + * Set banner image + * + * @param string $a_value + */ + public function setImage($a_value) + { + $this->img = (string) $a_value; + } + + /** + * Get style sheet id + * + * @return bool + */ + public function getStyleSheetId() + { + return (int) $this->style; + } + + /** + * Set style sheet id + * + * @param int $a_style + */ + public function setStyleSheetId($a_style) + { + $this->style = (int) $a_style; + } + + + // + // CRUD + // + + protected function doRead() + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT * FROM usr_portfolio" . + " WHERE id = " . $ilDB->quote($this->id, "integer")); + $row = $ilDB->fetchAssoc($set); + + $this->setOnline((bool) $row["is_online"]); + $this->setProfilePicture((bool) $row["ppic"]); + $this->setBackgroundColor($row["bg_color"]); + $this->setFontColor($row["font_color"]); + $this->setImage($row["img"]); + + // #14661 + include_once("./Services/Notes/classes/class.ilNote.php"); + $this->setPublicComments(ilNote::commentsActivated($this->id, 0, $this->getType())); + + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $this->setStyleSheetId(ilObjStyleSheet::lookupObjectStyle($this->id)); + + $this->doReadCustom($row); + } + + protected function doReadCustom(array $a_row) + { + } + + protected function doCreate() + { + $ilDB = $this->db; + + $ilDB->manipulate("INSERT INTO usr_portfolio (id,is_online)" . + " VALUES (" . $ilDB->quote($this->id, "integer") . "," . + $ilDB->quote(0, "integer") . ")"); + } + + protected function doUpdate() + { + $ilDB = $this->db; + + $fields = array( + "is_online" => array("integer", $this->isOnline()), + "ppic" => array("integer", $this->hasProfilePicture()), + "bg_color" => array("text", $this->getBackgroundColor()), + "font_color" => array("text", $this->getFontcolor()), + "img" => array("text", $this->getImage()) + ); + $this->doUpdateCustom($fields); + + // #14661 + include_once("./Services/Notes/classes/class.ilNote.php"); + ilNote::activateComments($this->id, 0, $this->getType(), $this->hasPublicComments()); + + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + ilObjStyleSheet::writeStyleUsage($this->id, $this->getStyleSheetId()); + + $ilDB->update( + "usr_portfolio", + $fields, + array("id"=>array("integer", $this->id)) + ); + } + + protected function doUpdateCustom(array &$a_fields) + { + } + + protected function doDelete() + { + $ilDB = $this->db; + + $this->deleteAllPages(); + $this->deleteImage(); + + $ilDB->manipulate("DELETE FROM usr_portfolio" . + " WHERE id = " . $ilDB->quote($this->id, "integer")); + } + + abstract protected function deleteAllPages(); + + + // + // IMAGES + // + + /** + * Get banner image incl. path + * + * @param bool $a_as_thumb + */ + public function getImageFullPath($a_as_thumb = false) + { + if ($this->img) { + $path = $this->initStorage($this->id); + if (!$a_as_thumb) { + return $path . $this->img; + } else { + return $path . "thb_" . $this->img; + } + } + } + + /** + * remove existing file + */ + public function deleteImage() + { + if ($this->id) { + include_once "Modules/Portfolio/classes/class.ilFSStoragePortfolio.php"; + $storage = new ilFSStoragePortfolio($this->id); + $storage->delete(); + + $this->setImage(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/Portfolio/classes/class.ilFSStoragePortfolio.php"; + $storage = new ilFSStoragePortfolio($a_id); + $storage->create(); + + $path = $storage->getAbsolutePath() . "/"; + + if ($a_subdir) { + $path .= $a_subdir . "/"; + + if (!is_dir($path)) { + mkdir($path); + } + } + + return $path; + } + + /** + * Upload new image file + * + * @param array $a_upload + * @return bool + */ + public function uploadImage(array $a_upload) + { + if (!$this->id) { + return false; + } + + $this->deleteImage(); + + // #10074 + $clean_name = preg_replace("/[^a-zA-Z0-9\_\.\-]/", "", $a_upload["name"]); + + $path = $this->initStorage($this->id); + $original = "org_" . $this->id . "_" . $clean_name; + $thumb = "thb_" . $this->id . "_" . $clean_name; + $processed = $this->id . "_" . $clean_name; + + if (ilUtil::moveUploadedFile($a_upload["tmp_name"], $original, $path . $original)) { + chmod($path . $original, 0770); + + $prfa_set = new ilSetting("prfa"); + /* as banner height should overflow, we only handle width + $dimensions = $prfa_set->get("banner_width")."x". + $prfa_set->get("banner_height"); + */ + $dimensions = $prfa_set->get("banner_width"); + + // take quality 100 to avoid jpeg artefacts when uploading jpeg files + // taking only frame [0] to avoid problems with animated gifs + $original_file = ilUtil::escapeShellArg($path . $original); + $thumb_file = ilUtil::escapeShellArg($path . $thumb); + $processed_file = ilUtil::escapeShellArg($path . $processed); + ilUtil::execConvert($original_file . "[0] -geometry 100x100 -quality 100 JPEG:" . $thumb_file); + ilUtil::execConvert($original_file . "[0] -geometry " . $dimensions . " -quality 100 JPEG:" . $processed_file); + + $this->setImage($processed); + + return true; + } + return false; + } + + + // + // TRANSMOGRIFIER + // + + /** + * Clone basic settings + * + * @param ilObjPortfolioBase $a_source + * @param ilObjPortfolioBase $a_target + */ + protected static function cloneBasics(ilObjPortfolioBase $a_source, ilObjPortfolioBase $a_target) + { + // copy portfolio properties + $a_target->setPublicComments($a_source->hasPublicComments()); + $a_target->setProfilePicture($a_source->hasProfilePicture()); + $a_target->setFontColor($a_source->getFontColor()); + $a_target->setBackgroundColor($a_source->getBackgroundColor()); + $a_target->setImage($a_source->getImage()); + $a_target->update(); + + // banner/images + $source_dir = $a_source->initStorage($a_source->getId()); + $target_dir = $a_target->initStorage($a_target->getId()); + ilFSStoragePortfolio::_copyDirectory($source_dir, $target_dir); + + // set/copy stylesheet + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $style_id = $a_source->getStyleSheetId(); + if ($style_id > 0 && !ilObjStyleSheet::_lookupStandard($style_id)) { + $style_obj = ilObjectFactory::getInstanceByObjId($style_id); + $new_id = $style_obj->ilClone(); + $a_target->setStyleSheetId($new_id); + $a_target->update(); + } + } + + /** + * Build template from portfolio and vice versa + * + * @param ilObjPortfolioBase $a_source + * @param ilObjPortfolioBase $a_target + * @param array $a_recipe + */ + public static function clonePagesAndSettings(ilObjPortfolioBase $a_source, ilObjPortfolioBase $a_target, array $a_recipe = null, $copy_all = false) + { + global $DIC; + + $lng = $DIC->language(); + $ilUser = $DIC->user(); + + $source_id = $a_source->getId(); + $target_id = $a_target->getId(); + + if ($a_source instanceof ilObjPortfolioTemplate && + $a_target instanceof ilObjPortfolio) { + $direction = "t2p"; + } elseif ($a_source instanceof ilObjPortfolio && + $a_target instanceof ilObjPortfolioTemplate) { + $direction = "p2t"; + } else { + return; + } + + self::cloneBasics($a_source, $a_target); + + // personal skills + include_once "Services/Skill/classes/class.ilPersonalSkill.php"; + $pskills = array_keys(ilPersonalSkill::getSelectedUserSkills($ilUser->getId())); + + // copy pages + $blog_count = 0; + include_once "Modules/Portfolio/classes/class.ilPortfolioTemplatePage.php"; + $page_map = array(); + foreach (ilPortfolioPage::getAllPortfolioPages($source_id) as $page) { + $page_id = $page["id"]; + + if ($direction == "t2p") { + $source_page = new ilPortfolioTemplatePage($page_id); + $target_page = new ilPortfolioPage(); + } else { + $source_page = new ilPortfolioPage($page_id); + $target_page = new ilPortfolioTemplatePage(); + } + $source_page->setPortfolioId($source_id); + $target_page->setPortfolioId($target_id); + + $page_type = $source_page->getType(); + $page_title = $source_page->getTitle(); + + + + + $page_recipe = null; + if (is_array($a_recipe)) { + $page_recipe = $a_recipe[$page_id]; + } + + $valid = false; + switch ($page_type) { + // blog => blog template + case ilPortfolioTemplatePage::TYPE_BLOG: + if ($direction == "p2t") { + $page_type = ilPortfolioTemplatePage::TYPE_BLOG_TEMPLATE; + $page_title = $lng->txt("obj_blog") . " " . (++$blog_count); + $valid = true; + } + break; + + // blog template => blog (needs recipe) + case ilPortfolioTemplatePage::TYPE_BLOG_TEMPLATE: + if ($direction == "t2p" && (is_array($page_recipe) || $copy_all)) { + $page_type = ilPortfolioPage::TYPE_BLOG; + if ($copy_all) { + $page_title = self::createBlogInPersonalWorkspace($page_title); + $valid = true; + } else { + if ($page_recipe[0] == "blog") { + switch ($page_recipe[1]) { + case "create": + $page_title = self::createBlogInPersonalWorkspace($page_recipe[2]); + $valid = true; + break; + + case "reuse": + $page_title = $page_recipe[2]; + $valid = true; + break; + + case "ignore": + // do nothing + break; + } + } + } + } + break; + + // page editor + default: + $target_page->setXMLContent($source_page->copyXmlContent(true)); // copy mobs + $target_page->buildDom(true); + + + // parse content / blocks + + if ($direction == "t2p") { + $dom = $target_page->getDom(); + if ($dom instanceof php4DOMDocument) { + $dom = $dom->myDOMDocument; + } + + // update profile/consultation hours user id + self::updateDomNodes($dom, "//PageContent/Profile", "User", $ilUser->getId()); + self::updateDomNodes($dom, "//PageContent/ConsultationHours", "User", $ilUser->getId()); + self::updateDomNodes($dom, "//PageContent/MyCourses", "User", $ilUser->getId()); + + // skills + $xpath = new DOMXPath($dom); + $nodes = $xpath->query("//PageContent/Skills"); + foreach ($nodes as $node) { + $skill_id = $node->getAttribute("Id"); + + // existing personal skills + if (in_array($skill_id, $pskills)) { + $node->setAttribute("User", $ilUser->getId()); + } + // new skill + elseif ($copy_all || in_array($skill_id, $a_recipe["skills"])) { + include_once "Services/Skill/classes/class.ilPersonalSkill.php"; + ilPersonalSkill::addPersonalSkill($ilUser->getId(), $skill_id); + + $node->setAttribute("User", $ilUser->getId()); + } + // remove skill + else { + $page_element = $node->parentNode; + $page_element->parentNode->removeChild($page_element); + } + } + } + + $valid = true; + break; + } + + if ($valid) { + // #12038 - update xml from dom + $target_page->setXMLContent($target_page->getXMLFromDom()); + + $target_page->setType($page_type); + $target_page->setTitle($page_title); + $target_page->create(); + + if ($page_type == ilPortfolioPage::TYPE_PAGE) { + $target_page->update(); // handle mob usages! + } + $page_map[$source_page->getId()] = $target_page->getId(); + } + } + + ilPortfolioPage::updateInternalLinks($page_map, $a_target); + } + + protected static function updateDomNodes($a_dom, $a_xpath, $a_attr_id, $a_attr_value) + { + $xpath_temp = new DOMXPath($a_dom); + $nodes = $xpath_temp->query($a_xpath); + foreach ($nodes as $node) { + $node->setAttribute($a_attr_id, $a_attr_value); + } + } + + protected static function createBlogInPersonalWorkspace($a_title) + { + global $DIC; + + $ilUser = $DIC->user(); + + static $ws_access = null; + + include_once "Modules/Blog/classes/class.ilObjBlog.php"; + $blog = new ilObjBlog(); + $blog->setType("blog"); + $blog->setTitle($a_title); + $blog->create(); + + if (!$ws_access) { + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; + $tree = new ilWorkspaceTree($ilUser->getId()); + + // #13235 + if (!$tree->getRootId()) { + $tree->createTreeForUser($ilUser->getId()); + } + + $ws_access = new ilWorkspaceAccessHandler($tree); + } + + $tree = $ws_access->getTree(); + $node_id = $tree->insertObject($tree->getRootId(), $blog->getId()); + $ws_access->setPermissions($tree->getRootId(), $node_id); + + return $blog->getId(); + } + + /** + * Fix internal portfolio links + * + * @param array + */ + public function fixLinksOnTitleChange($a_title_changes) + { + foreach (ilPortfolioPage::getAllPortfolioPages($this->getId()) as $port_page) { + if ($this->getType() == "prtt") { + $page = new ilPortfolioTemplatePage($port_page["id"]); + } else { + $page = new ilPortfolioPage($port_page["id"]); + } + if ($page->renameLinksOnTitleChange($a_title_changes)) { + $page->update(true, true); + } + } + } +} diff --git a/Modules/Portfolio/classes/class.ilObjPortfolioBaseGUI.php b/Modules/Portfolio/classes/class.ilObjPortfolioBaseGUI.php index f99ed687fdb4d16a3844c9185003c49b7bee41ce..040353991fabb4879e14add0f9fe7aa83322b6b3 100644 --- a/Modules/Portfolio/classes/class.ilObjPortfolioBaseGUI.php +++ b/Modules/Portfolio/classes/class.ilObjPortfolioBaseGUI.php @@ -1,1109 +1,1029 @@ - - * @version $Id$ - * - * @ingroup ModulesPortfolio - */ -abstract class ilObjPortfolioBaseGUI extends ilObject2GUI -{ - /** - * @var ilHelpGUI - */ - protected $help; - - /** - * @var ilMainMenuGUI - */ - protected $main_menu; - - protected $user_id; // [int] - protected $additional = array(); - protected $perma_link; // [string] - protected $page_id; // [int] - protected $page_mode; // [string] preview|edit - - public function __construct($a_id = 0, $a_id_type = self::REPOSITORY_NODE_ID, $a_parent_node_id = 0) - { - global $DIC; - - $this->user = $DIC->user(); - $this->locator = $DIC["ilLocator"]; - $this->toolbar = $DIC->toolbar(); - $this->settings = $DIC->settings(); - $this->tree = $DIC->repositoryTree(); - $this->help = $DIC["ilHelp"]; - $this->main_menu = $DIC["ilMainMenu"]; - $this->tpl = $DIC["tpl"]; - $ilUser = $DIC->user(); - - parent::__construct($a_id, $a_id_type, $a_parent_node_id); - - $this->user_id = $ilUser->getId(); - - $this->lng->loadLanguageModule("prtf"); - $this->lng->loadLanguageModule("user"); - $this->lng->loadLanguageModule("obj"); - } - - protected function addLocatorItems() - { - $ilLocator = $this->locator; - - if($this->object) - { - $ilLocator->addItem(strip_tags($this->object->getTitle()), - $this->ctrl->getLinkTarget($this, "view")); - } - - if($this->page_id) - { - $page = $this->getPageInstance($this->page_id); - $title = $page->getTitle(); - if($page->getType() == ilPortfolioPage::TYPE_BLOG) - { - $title = ilObject::_lookupTitle($title); - } - $this->ctrl->setParameterByClass($this->getPageGUIClassName(), "ppage", $this->page_id); - $ilLocator->addItem($title, - $this->ctrl->getLinkTargetByClass($this->getPageGUIClassName(), "edit")); - } - } - - protected function determinePageCall() - { - // edit - if(isset($_REQUEST["ppage"])) - { - if(!$this->checkPermissionBool("write")) - { - $this->ctrl->redirect($this, "view"); - } - - $this->page_id = $_REQUEST["ppage"]; - $this->page_mode = "edit"; - $this->ctrl->setParameter($this, "ppage", $this->page_id); - return true; - } - // preview - else - { - $this->page_id = $_REQUEST["user_page"]; - $this->page_mode = "preview"; - $this->ctrl->setParameter($this, "user_page", $this->page_id); - return false; - } - } - - protected function handlePageCall($a_cmd) - { - $this->tabs_gui->clearTargets(); - $this->tabs_gui->setBackTarget($this->lng->txt("back"), - $this->ctrl->getLinkTarget($this, "view")); - - if(!$this->page_id) - { - $this->ctrl->redirect($this, "view"); - } - - $page_gui = $this->getPageGUIInstance($this->page_id); - - // needed for editor - $page_gui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId( - $this->object->getStyleSheetId(), $this->getType())); - - $ret = $this->ctrl->forwardCommand($page_gui); - - if ($ret != "" && $ret !== true) - { - // preview (fullscreen) - if($this->page_mode == "preview") - { - // embedded call which did not generate any output (e.g. calendar month navigation) - if($ret != ilPortfolioPageGUI::EMBEDDED_NO_OUTPUT) - { - // suppress (portfolio) notes for blog postings - $this->preview(false, $ret, ($a_cmd != "previewEmbedded")); - } - else - { - $this->preview(false); - } - } - // edit - else - { - $this->setContentStyleSheet(); - if (is_string($ret)) - { - $this->tpl->setContent($ret); - } - } - } - } - - /** - * Set Additonal Information (used in public profile?) - * - * @param array $a_additional Additonal Information - */ - public function setAdditional($a_additional) - { - $this->additional = $a_additional; - } - - /** - * Get Additonal Information. - * - * @return array Additonal Information - */ - public function getAdditional() - { - return $this->additional; - } - - /** - * Set custom perma link (used in public profile?) - * - * @param int $a_obj_id - * @param string $a_type - */ - public function setPermaLink($a_obj_id, $a_type) - { - $this->perma_link = array("obj_id"=>$a_obj_id, "type"=>$a_type); - } - - - // - // CREATE/EDIT - // - - protected function setSettingsSubTabs($a_active) - { - // #17455 - $this->lng->loadLanguageModule($this->getType()); - - // general properties - $this->tabs_gui->addSubTab("properties", - $this->lng->txt($this->getType()."_properties"), - $this->ctrl->getLinkTarget($this, 'edit')); - - $this->tabs_gui->addSubTab("style", - $this->lng->txt("obj_sty"), - $this->ctrl->getLinkTarget($this, 'editStyleProperties')); - - $this->tabs_gui->activateSubTab($a_active); - } - - protected function initEditCustomForm(ilPropertyFormGUI $a_form) - { - $this->setSettingsSubTabs("properties"); - - - // profile picture - $ppic = new ilCheckboxInputGUI($this->lng->txt("prtf_profile_picture"), "ppic"); - $a_form->addItem($ppic); - - $prfa_set = new ilSetting("prfa"); - if($prfa_set->get("banner")) - { - include_once "Services/Form/classes/class.ilFileInputGUI.php"; - ilFileInputGUI::setPersonalWorkspaceQuotaCheck(true); - - $dimensions = " (".$prfa_set->get("banner_width")."x". - $prfa_set->get("banner_height").")"; - - $img = new ilImageFileInputGUI($this->lng->txt("prtf_banner").$dimensions, "banner"); - $a_form->addItem($img); - - // show existing file - $file = $this->object->getImageFullPath(true); - if($file) - { - $img->setImage($file); - } - } - - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($this->lng->txt('obj_features')); - $a_form->addItem($section); - - // comments - $comments = new ilCheckboxInputGUI($this->lng->txt("prtf_public_comments"), "comments"); - $a_form->addItem($comments); - - /* #15000 - $bg_color = new ilColorPickerInputGUI($this->lng->txt("prtf_background_color"), "bg_color"); - $a_form->addItem($bg_color); - - $font_color = new ilColorPickerInputGUI($this->lng->txt("prtf_font_color"), "font_color"); - $a_form->addItem($font_color); - */ - } - - protected function getEditFormCustomValues(array &$a_values) - { - $a_values["comments"] = $this->object->hasPublicComments(); - $a_values["ppic"] = $this->object->hasProfilePicture(); - /* - $a_values["bg_color"] = $this->object->getBackgroundColor(); - $a_values["font_color"] = $this->object->getFontColor(); - */ - } - - public function updateCustom(ilPropertyFormGUI $a_form) - { - $this->object->setPublicComments($a_form->getInput("comments")); - $this->object->setProfilePicture($a_form->getInput("ppic")); - /* - $this->object->setBackgroundColor($a_form->getInput("bg_color")); - $this->object->setFontcolor($a_form->getInput("font_color")); - */ - - $prfa_set = new ilSetting("prfa"); - - if($_FILES["banner"]["tmp_name"]) - { - $this->object->uploadImage($_FILES["banner"]); - } - else if($prfa_set->get('banner') and $a_form->getItemByPostVar("banner")->getDeletionFlag()) - { - $this->object->deleteImage(); - } - } - - - // - // PAGES - // - - abstract protected function getPageInstance($a_page_id = null, $a_portfolio_id = null); - - abstract protected function getPageGUIInstance($a_page_id); - - abstract public function getPageGUIClassName(); - - /** - * Show list of portfolio pages - */ - public function view() - { - $ilToolbar = $this->toolbar; - $ilSetting = $this->settings; - $tree = $this->tree; - - if(!$this->checkPermissionBool("write")) - { - $this->ctrl->redirect($this, "infoScreen"); - } - - $this->tabs_gui->activateTab("pages"); - - include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; - - $button = ilLinkButton::getInstance(); - $button->setCaption("prtf_add_page"); - $button->setUrl($this->ctrl->getLinkTarget($this, "addPage")); - $ilToolbar->addStickyItem($button); - - if(!$ilSetting->get('disable_wsp_blogs')) - { - $button = ilLinkButton::getInstance(); - $button->setCaption("prtf_add_blog"); - $button->setUrl($this->ctrl->getLinkTarget($this, "addBlog")); - $ilToolbar->addStickyItem($button); - } - - - // #16571 - if($this->getType() == "prtf") - { - $ilToolbar->addSeparator(); - - $button = ilLinkButton::getInstance(); - $button->setCaption("export_html"); - $button->setUrl($this->ctrl->getLinkTarget($this, "export")); - $ilToolbar->addButtonInstance($button); - - $button = ilLinkButton::getInstance(); - $button->setCaption("prtf_pdf"); - $button->setUrl($this->ctrl->getLinkTarget($this, "exportPDFSelection")); - $ilToolbar->addButtonInstance($button); - } - - include_once "Modules/Portfolio/classes/class.ilPortfolioPageTableGUI.php"; - $table = new ilPortfolioPageTableGUI($this, "view"); - - // exercise portfolio? - include_once "Modules/Portfolio/classes/class.ilPortfolioExerciseGUI.php"; - $message = ilPortfolioExerciseGUI::checkExercise($this->user_id, $this->object->getId(), $table->dataExists()); - - $this->tpl->setContent($message.$table->getHTML()); - } - - /** - * Show portfolio page creation form - */ - protected function addPage() - { - $ilHelp = $this->help; - - $this->tabs_gui->clearTargets(); - $this->tabs_gui->setBackTarget($this->lng->txt("back"), - $this->ctrl->getLinkTarget($this, "view")); - - $ilHelp->setScreenIdComponent("prtf"); - $ilHelp->setScreenId("add_page"); - - - $form = $this->initPageForm("create"); - $this->tpl->setContent($form->getHTML()); - } - - /** - * Init portfolio page form - * - * @param string $a_mode - * @return ilPropertyFormGUI - */ - public function initPageForm($a_mode = "create") - { - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - - // title - $ti = new ilTextInputGUI($this->lng->txt("title"), "title"); - $ti->setMaxLength(200); - $ti->setRequired(true); - $form->addItem($ti); - - // save and cancel commands - if ($a_mode == "create") - { - include_once "Services/COPage/Layout/classes/class.ilPageLayout.php"; - $templates = ilPageLayout::activeLayouts(false, ilPageLayout::MODULE_PORTFOLIO); - if($templates) - { - $use_template = new ilRadioGroupInputGUI($this->lng->txt("prtf_use_page_layout"), "tmpl"); - $use_template->setRequired(true); - $form->addItem($use_template); - - $opt = new ilRadioOption($this->lng->txt("none"), 0); - $use_template->addOption($opt); - - foreach ($templates as $templ) - { - $templ->readObject(); - - $opt = new ilRadioOption($templ->getTitle().$templ->getPreview(), $templ->getId()); - $use_template->addOption($opt); - } - } - - $form->setTitle($this->lng->txt("prtf_add_page").": ". - $this->object->getTitle()); - $form->addCommandButton("savePage", $this->lng->txt("save")); - $form->addCommandButton("view", $this->lng->txt("cancel")); - } - else - { - /* edit is done directly in table gui - $form->setTitle($this->lng->txt("prtf_edit_page")); - $form->addCommandButton("updatePage", $this->lng->txt("save")); - $form->addCommandButton("view", $this->lng->txt("cancel")); - */ - } - - return $form; - } - - /** - * Create new portfolio page - */ - public function savePage() - { - $form = $this->initPageForm("create"); - if ($form->checkInput() && $this->checkPermissionBool("write")) - { - include_once("Modules/Portfolio/classes/class.ilPortfolioPage.php"); - $page = $this->getPageInstance(); - $page->setType(ilPortfolioPage::TYPE_PAGE); - $page->setTitle($form->getInput("title")); - - // use template as basis - $layout_id = $form->getInput("tmpl"); - if($layout_id) - { - include_once("./Services/COPage/Layout/classes/class.ilPageLayout.php"); - $layout_obj = new ilPageLayout($layout_id); - $page->setXMLContent($layout_obj->getXMLContent()); - } - - $page->create(); - - ilUtil::sendSuccess($this->lng->txt("prtf_page_created"), true); - $this->ctrl->redirect($this, "view"); - } - - $this->tabs_gui->clearTargets(); - $this->tabs_gui->setBackTarget($this->lng->txt("back"), - $this->ctrl->getLinkTarget($this, "view")); - - $form->setValuesByPost(); - $this->tpl->setContent($form->getHtml()); - } - - /** - * Show portfolio blog page creation form - */ - protected function addBlog() - { - $ilHelp = $this->help; - - $this->tabs_gui->clearTargets(); - $this->tabs_gui->setBackTarget($this->lng->txt("back"), - $this->ctrl->getLinkTarget($this, "view")); - - $ilHelp->setScreenIdComponent("prtf"); - $ilHelp->setScreenId("add_blog"); - - $form = $this->initBlogForm(); - $this->tpl->setContent($form->getHTML()); - } - - abstract protected function initBlogForm(); - - abstract protected function saveBlog(); - - /** - * Save ordering of portfolio pages - */ - function savePortfolioPagesOrdering() - { - if(!$this->checkPermissionBool("write")) - { - return; - } - - $title_changes = array(); - - if (is_array($_POST["order"])) - { - foreach ($_POST["order"] as $k => $v) - { - $page = $this->getPageInstance(ilUtil::stripSlashes($k)); - if($_POST["title"][$k]) - { - $new_title = trim(ilUtil::stripSlashes($_POST["title"][$k])); - if ($page->getTitle() != $new_title) - { - $title_changes[$page->getId()] = array("old" => $page->getTitle(), "new" => $new_title); - $page->setTitle($new_title); - } - } - $page->setOrderNr(ilUtil::stripSlashes($v)); - $page->update(); - } - ilPortfolioPage::fixOrdering($this->object->getId()); - } - - $this->object->fixLinksOnTitleChange($title_changes); - - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "view"); - } - - /** - * Confirm portfolio deletion - */ - function confirmPortfolioPageDeletion() - { - $prtf_pages = $_REQUEST["prtf_pages"]; - - if (!is_array($prtf_pages) || count($prtf_pages) == 0) - { - ilUtil::sendInfo($this->lng->txt("no_checkbox"), true); - $this->ctrl->redirect($this, "view"); - } - else - { - $this->tabs_gui->activateTab("pages"); - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($this->ctrl->getFormAction($this)); - $cgui->setHeaderText($this->lng->txt("prtf_sure_delete_portfolio_pages")); - $cgui->setCancel($this->lng->txt("cancel"), "view"); - $cgui->setConfirm($this->lng->txt("delete"), "deletePortfolioPages"); - - foreach ($prtf_pages as $id) - { - $page = $this->getPageInstance((int) $id); - if ($page->getPortfolioId() != $this->object->getId()) - { - continue; - } - - $title = $page->getTitle(); - if($page->getType() == ilPortfolioPage::TYPE_BLOG) - { - $title = $this->lng->txt("obj_blog").": ".ilObject::_lookupTitle((int)$title); - } - $cgui->addItem("prtf_pages[]", $id, $title); - } - - $this->tpl->setContent($cgui->getHTML()); - } - } - - /** - * Delete portfolio pages - */ - function deletePortfolioPages() - { - if(!$this->checkPermissionBool("write")) - { - return; - } - - if (is_array($_POST["prtf_pages"])) - { - foreach ($_POST["prtf_pages"] as $id) - { - $page = $this->getPageInstance($id); - $page->delete(); - } - } - ilUtil::sendSuccess($this->lng->txt("prtf_portfolio_page_deleted"), true); - $this->ctrl->redirect($this, "view"); - } - - /** - * Show user page - */ - function preview($a_return = false, $a_content = false, $a_show_notes = true) - { - $ilSetting = $this->settings; - $ilUser = $this->user; - - $portfolio_id = $this->object->getId(); - $user_id = $this->object->getOwner(); - - $this->tabs_gui->clearTargets(); - - $pages = ilPortfolioPage::getAllPortfolioPages($portfolio_id); - $current_page = (int)$_GET["user_page"]; - - // validate current page - if($pages && $current_page) - { - $found = false; - foreach($pages as $page) - { - if($page["id"] == $current_page) - { - $found = true; - break; - } - } - if(!$found) - { - $current_page = null; - } - } - - // display first page of portfolio if none given - if(!$current_page && $pages) - { - $current_page = $pages; - $current_page = array_shift($current_page); - $current_page = $current_page["id"]; - } - - // #13788 - keep page after login - if($this->user_id == ANONYMOUS_USER_ID && - $this->getType() == "prtf") - { - $this->tpl->setLoginTargetPar("prtf_".$this->object->getId()."_".$current_page); - } - - $back_caption = ""; - - // public profile - if($_REQUEST["back_url"]) - { - $back = $_REQUEST["back_url"]; - } - else if($_GET["baseClass"] != "ilPublicUserProfileGUI" && - $this->user_id && $this->user_id != ANONYMOUS_USER_ID) - { - if(!$this->checkPermissionBool("write")) - { - // shared - if($this->getType() == "prtf") - { - $this->ctrl->setParameterByClass("ilportfoliorepositorygui", "shr_id", $this->object->getOwner()); - $back = $this->ctrl->getLinkTargetByClass(array("ilpersonaldesktopgui", "ilportfoliorepositorygui"), "showOther"); - $this->ctrl->setParameterByClass("ilportfoliorepositorygui", "shr_id", ""); - } - // listgui / parent container - else - { - // #12819 - $tree = $this->tree; - $parent_id = $tree->getParentId($this->node_id); - include_once "Services/Link/classes/class.ilLink.php"; - $back = ilLink::_getStaticLink($parent_id); - } - } - // owner - else - { - $back = $this->ctrl->getLinkTarget($this, "view"); - if($this->getType() == "prtf") - { - $back_caption = $this->lng->txt("prtf_back_to_portfolio_owner"); - } - else - { - // #19316 - $this->lng->loadLanguageModule("prtt"); - $back_caption = $this->lng->txt("prtt_edit"); - } - } - } - - $ilMainMenu = $this->main_menu; - $ilMainMenu->setMode(ilMainMenuGUI::MODE_TOPBAR_ONLY); - if($back) - { - // might already be set in ilPublicUserProfileGUI - $ilMainMenu->setTopBarBack($back, $back_caption); - } - - // render tabs - $current_blog = null; - if(count($pages) > 1) - { - foreach ($pages as $p) - { - if($p["type"] == ilPortfolioPage::TYPE_BLOG) - { - // needed for blog comments (see below) - if($p["id"] == $current_page) - { - $current_blog = (int)$p["title"]; - } - include_once "Modules/Blog/classes/class.ilObjBlog.php"; - $p["title"] = ilObjBlog::_lookupTitle($p["title"]); - } - - $this->ctrl->setParameter($this, "user_page", $p["id"]); - $this->tabs_gui->addTab("user_page_".$p["id"], - $p["title"], - $this->ctrl->getLinkTarget($this, "preview")); - } - - $this->tabs_gui->activateTab("user_page_".$current_page); - } - - $this->ctrl->setParameter($this, "user_page", $current_page); - - if(!$a_content) - { - // #18291 - if($current_page) - { - // get current page content - $page_gui = $this->getPageGUIInstance($current_page); - $page_gui->setEmbedded(true); - - $content = $this->ctrl->getHTML($page_gui); - } - } - else - { - $content = $a_content; - } - - if($a_return && $this->checkPermissionBool("write")) - { - return $content; - } - - // blog posting comments are handled within the blog - $notes = ""; - if($a_show_notes && $this->object->hasPublicComments() && !$current_blog && $current_page) - { - include_once("./Services/Notes/classes/class.ilNoteGUI.php"); - $note_gui = new ilNoteGUI($portfolio_id, $current_page, "pfpg"); - $note_gui->setRepositoryMode(false); - $note_gui->enablePublicNotes(true); - $note_gui->enablePrivateNotes(false); - - $note_gui->enablePublicNotesDeletion(($this->user_id == $user_id) && - $ilSetting->get("comments_del_tutor", 1)); - - $next_class = $this->ctrl->getNextClass($this); - if ($next_class == "ilnotegui") - { - $notes = $this->ctrl->forwardCommand($note_gui); - } - else - { - $notes = $note_gui->getNotesHTML(); - } - } - - if($this->perma_link === null) - { - if($this->getType() == "prtf") - { - $this->tpl->setPermanentLink($this->getType(), $this->object->getId(), "_".$current_page); - } - else - { - $this->tpl->setPermanentLink($this->getType(), $this->object->getRefId()); - } - } - else - { - $this->tpl->setPermanentLink($this->perma_link["type"], $this->perma_link["obj_id"]); - } - - // #18208 - see ilPortfolioTemplatePageGUI::getPageContentUserId() - if($this->getType() == "prtt" && !$this->checkPermissionBool("write")) - { - $user_id = $ilUser->getId(); - } - - self::renderFullscreenHeader($this->object, $this->tpl, $user_id); - - // #13564 - $this->ctrl->setParameter($this, "user_page", ""); - $this->tpl->setTitleUrl($this->ctrl->getLinkTarget($this, "preview")); - $this->ctrl->setParameter($this, "user_page", $this->page_id); - - // blog pages do their own (page) style handling - if(!$current_blog) - { - $content = '
'. - '
'. - $content. - '
'; - - $this->setContentStyleSheet($this->tpl); - } - - // #10717 - $this->tpl->setContent($content. - '
'.$notes.'
'); - } - - /** - * Render banner, user name - * - * @param object $a_tpl - * @param int $a_user_id - * @param bool $a_export_path - */ - public static function renderFullscreenHeader($a_portfolio, $a_tpl, $a_user_id, $a_export = false) - { - global $DIC; - - $ilUser = $DIC->user(); - - if(!$a_export) - { - require_once('Services/Tracking/classes/class.ilChangeEvent.php'); - ilChangeEvent::_recordReadEvent( - $a_portfolio->getType(), - ($a_portfolio->getType() == "prtt") - ? $a_portfolio->getRefId() - : $a_portfolio->getId(), - $a_portfolio->getId(), - $ilUser->getId() - ); - } - - $name = ilObjUser::_lookupName($a_user_id); - $name = $name["lastname"].", ".($t = $name["title"] ? $t . " " : "").$name["firstname"]; - - // show banner? - $banner = $banner_width = $banner_height = false; - $prfa_set = new ilSetting("prfa"); - if($prfa_set->get("banner")) - { - require_once('./Services/WebAccessChecker/classes/class.ilWACSignedPath.php'); - $banner = ilWACSignedPath::signFile($a_portfolio->getImageFullPath()); - $banner_width = $prfa_set->get("banner_width"); - $banner_height = $prfa_set->get("banner_height"); - if($a_export) - { - $banner = basename($banner); - } - } - - // profile picture - $ppic = null; - if($a_portfolio->hasProfilePicture()) - { - $ppic = ilObjUser::_getPersonalPicturePath($a_user_id, "xsmall", true, true); - if($a_export) - { - $ppic = basename($ppic); - } - } - - $a_tpl->resetHeaderBlock(false); - // $a_tpl->setBackgroundColor($a_portfolio->getBackgroundColor()); - $a_tpl->setBanner($banner, $banner_width, $banner_height, $a_export); - $a_tpl->setTitleIcon($ppic); - $a_tpl->setTitle($a_portfolio->getTitle()); - // $a_tpl->setTitleColor($a_portfolio->getFontColor()); - $a_tpl->setDescription($name); - - // to get rid of locator in portfolio template preview - $a_tpl->setVariable("LOCATOR", ""); - - // :TODO: obsolete? - // $a_tpl->setBodyClass("std ilExternal ilPortfolio"); - } - - function export() - { - include_once "Modules/Portfolio/classes/class.ilPortfolioHTMLExport.php"; - $export = new ilPortfolioHTMLExport($this, $this->object); - $zip = $export->buildExportFile(); - - ilUtil::deliverFile($zip, $this->object->getTitle().".zip", '', false, true); - } - - - /** - * Select target portfolio for page(s) copy - */ - function copyPageForm($a_form = null) - { - $prtf_pages = $_REQUEST["prtf_pages"]; - - if (!is_array($prtf_pages) || count($prtf_pages) == 0) - { - ilUtil::sendInfo($this->lng->txt("no_checkbox"), true); - $this->ctrl->redirect($this, "view"); - } - else - { - $this->tabs_gui->activateTab("pages"); - - if(!$a_form) - { - $a_form = $this->initCopyPageForm(); - } - - foreach($prtf_pages as $page_id) - { - $item = new ilHiddenInputGUI("prtf_pages[]"); - $item->setValue((int) $page_id); - $a_form->addItem($item); - } - - $this->tpl->setContent($a_form->getHTML()); - } - } - - function copyPage() - { - $form = $this->initCopyPageForm(); - if($form->checkInput()) - { - // existing - if($form->getInput("target") == "old") - { - $portfolio_id = $form->getInput("prtf"); - } - // new - else - { - $portfolio = new ilObjPortfolio(); - $portfolio->setTitle($form->getInput("title")); - $portfolio->create(); - $portfolio_id = $portfolio->getId(); - } - - // copy page(s) - foreach($_POST["prtf_pages"] as $page_id) - { - $source = $this->getPageInstance($page_id); - $target = $this->getPageInstance(null, $portfolio_id); - $target->setXMLContent($source->copyXmlContent(true)); // copy mobs - $target->setType($source->getType()); - $target->setTitle($source->getTitle()); - $target->create(); - } - - ilUtil::sendSuccess($this->lng->txt("prtf_pages_copied"), true); - $this->ctrl->redirect($this, "view"); - } - - $form->setValuesByPost(); - $this->copyPageForm($form); - } - - abstract protected function initCopyPageFormOptions(ilPropertyFormGUI $a_form); - - function initCopyPageForm() - { - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - $form->setTitle($this->lng->txt("prtf_copy_page")); - - $this->initCopyPageFormOptions($form); - - $form->addCommandButton("copyPage", $this->lng->txt("save")); - $form->addCommandButton("view", $this->lng->txt("cancel")); - - return $form; - } - - - //// - //// 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, - $_GET["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($this->getType()."_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(ilUtil::stripSlashes($_POST["style_id"])); - $this->object->update(); - - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - } - $this->ctrl->redirect($this, "editStyleProperties"); - } -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @ingroup ModulesPortfolio + */ +abstract class ilObjPortfolioBaseGUI extends ilObject2GUI +{ + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var ilMainMenuGUI + */ + protected $main_menu; + + protected $user_id; // [int] + protected $additional = array(); + protected $perma_link; // [string] + protected $page_id; // [int] + protected $page_mode; // [string] preview|edit + + public function __construct($a_id = 0, $a_id_type = self::REPOSITORY_NODE_ID, $a_parent_node_id = 0) + { + global $DIC; + + $this->user = $DIC->user(); + $this->locator = $DIC["ilLocator"]; + $this->toolbar = $DIC->toolbar(); + $this->settings = $DIC->settings(); + $this->tree = $DIC->repositoryTree(); + $this->help = $DIC["ilHelp"]; + $this->main_menu = $DIC["ilMainMenu"]; + $this->tpl = $DIC["tpl"]; + $ilUser = $DIC->user(); + + parent::__construct($a_id, $a_id_type, $a_parent_node_id); + + $this->user_id = $ilUser->getId(); + + $this->lng->loadLanguageModule("prtf"); + $this->lng->loadLanguageModule("user"); + $this->lng->loadLanguageModule("obj"); + } + + protected function addLocatorItems() + { + $ilLocator = $this->locator; + + if ($this->object) { + $ilLocator->addItem( + strip_tags($this->object->getTitle()), + $this->ctrl->getLinkTarget($this, "view") + ); + } + + if ($this->page_id) { + $page = $this->getPageInstance($this->page_id); + $title = $page->getTitle(); + if ($page->getType() == ilPortfolioPage::TYPE_BLOG) { + $title = ilObject::_lookupTitle($title); + } + $this->ctrl->setParameterByClass($this->getPageGUIClassName(), "ppage", $this->page_id); + $ilLocator->addItem( + $title, + $this->ctrl->getLinkTargetByClass($this->getPageGUIClassName(), "edit") + ); + } + } + + protected function determinePageCall() + { + // edit + if (isset($_REQUEST["ppage"])) { + if (!$this->checkPermissionBool("write")) { + $this->ctrl->redirect($this, "view"); + } + + $this->page_id = $_REQUEST["ppage"]; + $this->page_mode = "edit"; + $this->ctrl->setParameter($this, "ppage", $this->page_id); + return true; + } + // preview + else { + $this->page_id = $_REQUEST["user_page"]; + $this->page_mode = "preview"; + $this->ctrl->setParameter($this, "user_page", $this->page_id); + return false; + } + } + + protected function handlePageCall($a_cmd) + { + $this->tabs_gui->clearTargets(); + $this->tabs_gui->setBackTarget( + $this->lng->txt("back"), + $this->ctrl->getLinkTarget($this, "view") + ); + + if (!$this->page_id) { + $this->ctrl->redirect($this, "view"); + } + + $page_gui = $this->getPageGUIInstance($this->page_id); + + // needed for editor + $page_gui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId( + $this->object->getStyleSheetId(), + $this->getType() + )); + + $ret = $this->ctrl->forwardCommand($page_gui); + + if ($ret != "" && $ret !== true) { + // preview (fullscreen) + if ($this->page_mode == "preview") { + // embedded call which did not generate any output (e.g. calendar month navigation) + if ($ret != ilPortfolioPageGUI::EMBEDDED_NO_OUTPUT) { + // suppress (portfolio) notes for blog postings + $this->preview(false, $ret, ($a_cmd != "previewEmbedded")); + } else { + $this->preview(false); + } + } + // edit + else { + $this->setContentStyleSheet(); + if (is_string($ret)) { + $this->tpl->setContent($ret); + } + } + } + } + + /** + * Set Additonal Information (used in public profile?) + * + * @param array $a_additional Additonal Information + */ + public function setAdditional($a_additional) + { + $this->additional = $a_additional; + } + + /** + * Get Additonal Information. + * + * @return array Additonal Information + */ + public function getAdditional() + { + return $this->additional; + } + + /** + * Set custom perma link (used in public profile?) + * + * @param int $a_obj_id + * @param string $a_type + */ + public function setPermaLink($a_obj_id, $a_type) + { + $this->perma_link = array("obj_id"=>$a_obj_id, "type"=>$a_type); + } + + + // + // CREATE/EDIT + // + + protected function setSettingsSubTabs($a_active) + { + // #17455 + $this->lng->loadLanguageModule($this->getType()); + + // general properties + $this->tabs_gui->addSubTab( + "properties", + $this->lng->txt($this->getType() . "_properties"), + $this->ctrl->getLinkTarget($this, 'edit') + ); + + $this->tabs_gui->addSubTab( + "style", + $this->lng->txt("obj_sty"), + $this->ctrl->getLinkTarget($this, 'editStyleProperties') + ); + + $this->tabs_gui->activateSubTab($a_active); + } + + protected function initEditCustomForm(ilPropertyFormGUI $a_form) + { + $this->setSettingsSubTabs("properties"); + + + // profile picture + $ppic = new ilCheckboxInputGUI($this->lng->txt("prtf_profile_picture"), "ppic"); + $a_form->addItem($ppic); + + $prfa_set = new ilSetting("prfa"); + if ($prfa_set->get("banner")) { + include_once "Services/Form/classes/class.ilFileInputGUI.php"; + ilFileInputGUI::setPersonalWorkspaceQuotaCheck(true); + + $dimensions = " (" . $prfa_set->get("banner_width") . "x" . + $prfa_set->get("banner_height") . ")"; + + $img = new ilImageFileInputGUI($this->lng->txt("prtf_banner") . $dimensions, "banner"); + $a_form->addItem($img); + + // show existing file + $file = $this->object->getImageFullPath(true); + if ($file) { + $img->setImage($file); + } + } + + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($this->lng->txt('obj_features')); + $a_form->addItem($section); + + // comments + $comments = new ilCheckboxInputGUI($this->lng->txt("prtf_public_comments"), "comments"); + $a_form->addItem($comments); + + /* #15000 + $bg_color = new ilColorPickerInputGUI($this->lng->txt("prtf_background_color"), "bg_color"); + $a_form->addItem($bg_color); + + $font_color = new ilColorPickerInputGUI($this->lng->txt("prtf_font_color"), "font_color"); + $a_form->addItem($font_color); + */ + } + + protected function getEditFormCustomValues(array &$a_values) + { + $a_values["comments"] = $this->object->hasPublicComments(); + $a_values["ppic"] = $this->object->hasProfilePicture(); + /* + $a_values["bg_color"] = $this->object->getBackgroundColor(); + $a_values["font_color"] = $this->object->getFontColor(); + */ + } + + public function updateCustom(ilPropertyFormGUI $a_form) + { + $this->object->setPublicComments($a_form->getInput("comments")); + $this->object->setProfilePicture($a_form->getInput("ppic")); + /* + $this->object->setBackgroundColor($a_form->getInput("bg_color")); + $this->object->setFontcolor($a_form->getInput("font_color")); + */ + + $prfa_set = new ilSetting("prfa"); + + if ($_FILES["banner"]["tmp_name"]) { + $this->object->uploadImage($_FILES["banner"]); + } elseif ($prfa_set->get('banner') and $a_form->getItemByPostVar("banner")->getDeletionFlag()) { + $this->object->deleteImage(); + } + } + + + // + // PAGES + // + + abstract protected function getPageInstance($a_page_id = null, $a_portfolio_id = null); + + abstract protected function getPageGUIInstance($a_page_id); + + abstract public function getPageGUIClassName(); + + /** + * Show list of portfolio pages + */ + public function view() + { + $ilToolbar = $this->toolbar; + $ilSetting = $this->settings; + $tree = $this->tree; + + if (!$this->checkPermissionBool("write")) { + $this->ctrl->redirect($this, "infoScreen"); + } + + $this->tabs_gui->activateTab("pages"); + + include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; + + $button = ilLinkButton::getInstance(); + $button->setCaption("prtf_add_page"); + $button->setUrl($this->ctrl->getLinkTarget($this, "addPage")); + $ilToolbar->addStickyItem($button); + + if (!$ilSetting->get('disable_wsp_blogs')) { + $button = ilLinkButton::getInstance(); + $button->setCaption("prtf_add_blog"); + $button->setUrl($this->ctrl->getLinkTarget($this, "addBlog")); + $ilToolbar->addStickyItem($button); + } + + + // #16571 + if ($this->getType() == "prtf") { + $ilToolbar->addSeparator(); + + $button = ilLinkButton::getInstance(); + $button->setCaption("export_html"); + $button->setUrl($this->ctrl->getLinkTarget($this, "export")); + $ilToolbar->addButtonInstance($button); + + $button = ilLinkButton::getInstance(); + $button->setCaption("prtf_pdf"); + $button->setUrl($this->ctrl->getLinkTarget($this, "exportPDFSelection")); + $ilToolbar->addButtonInstance($button); + } + + include_once "Modules/Portfolio/classes/class.ilPortfolioPageTableGUI.php"; + $table = new ilPortfolioPageTableGUI($this, "view"); + + // exercise portfolio? + include_once "Modules/Portfolio/classes/class.ilPortfolioExerciseGUI.php"; + $message = ilPortfolioExerciseGUI::checkExercise($this->user_id, $this->object->getId(), $table->dataExists()); + + $this->tpl->setContent($message . $table->getHTML()); + } + + /** + * Show portfolio page creation form + */ + protected function addPage() + { + $ilHelp = $this->help; + + $this->tabs_gui->clearTargets(); + $this->tabs_gui->setBackTarget( + $this->lng->txt("back"), + $this->ctrl->getLinkTarget($this, "view") + ); + + $ilHelp->setScreenIdComponent("prtf"); + $ilHelp->setScreenId("add_page"); + + + $form = $this->initPageForm("create"); + $this->tpl->setContent($form->getHTML()); + } + + /** + * Init portfolio page form + * + * @param string $a_mode + * @return ilPropertyFormGUI + */ + public function initPageForm($a_mode = "create") + { + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this)); + + // title + $ti = new ilTextInputGUI($this->lng->txt("title"), "title"); + $ti->setMaxLength(200); + $ti->setRequired(true); + $form->addItem($ti); + + // save and cancel commands + if ($a_mode == "create") { + include_once "Services/COPage/Layout/classes/class.ilPageLayout.php"; + $templates = ilPageLayout::activeLayouts(false, ilPageLayout::MODULE_PORTFOLIO); + if ($templates) { + $use_template = new ilRadioGroupInputGUI($this->lng->txt("prtf_use_page_layout"), "tmpl"); + $use_template->setRequired(true); + $form->addItem($use_template); + + $opt = new ilRadioOption($this->lng->txt("none"), 0); + $use_template->addOption($opt); + + foreach ($templates as $templ) { + $templ->readObject(); + + $opt = new ilRadioOption($templ->getTitle() . $templ->getPreview(), $templ->getId()); + $use_template->addOption($opt); + } + } + + $form->setTitle($this->lng->txt("prtf_add_page") . ": " . + $this->object->getTitle()); + $form->addCommandButton("savePage", $this->lng->txt("save")); + $form->addCommandButton("view", $this->lng->txt("cancel")); + } else { + /* edit is done directly in table gui + $form->setTitle($this->lng->txt("prtf_edit_page")); + $form->addCommandButton("updatePage", $this->lng->txt("save")); + $form->addCommandButton("view", $this->lng->txt("cancel")); + */ + } + + return $form; + } + + /** + * Create new portfolio page + */ + public function savePage() + { + $form = $this->initPageForm("create"); + if ($form->checkInput() && $this->checkPermissionBool("write")) { + include_once("Modules/Portfolio/classes/class.ilPortfolioPage.php"); + $page = $this->getPageInstance(); + $page->setType(ilPortfolioPage::TYPE_PAGE); + $page->setTitle($form->getInput("title")); + + // use template as basis + $layout_id = $form->getInput("tmpl"); + if ($layout_id) { + include_once("./Services/COPage/Layout/classes/class.ilPageLayout.php"); + $layout_obj = new ilPageLayout($layout_id); + $page->setXMLContent($layout_obj->getXMLContent()); + } + + $page->create(); + + ilUtil::sendSuccess($this->lng->txt("prtf_page_created"), true); + $this->ctrl->redirect($this, "view"); + } + + $this->tabs_gui->clearTargets(); + $this->tabs_gui->setBackTarget( + $this->lng->txt("back"), + $this->ctrl->getLinkTarget($this, "view") + ); + + $form->setValuesByPost(); + $this->tpl->setContent($form->getHtml()); + } + + /** + * Show portfolio blog page creation form + */ + protected function addBlog() + { + $ilHelp = $this->help; + + $this->tabs_gui->clearTargets(); + $this->tabs_gui->setBackTarget( + $this->lng->txt("back"), + $this->ctrl->getLinkTarget($this, "view") + ); + + $ilHelp->setScreenIdComponent("prtf"); + $ilHelp->setScreenId("add_blog"); + + $form = $this->initBlogForm(); + $this->tpl->setContent($form->getHTML()); + } + + abstract protected function initBlogForm(); + + abstract protected function saveBlog(); + + /** + * Save ordering of portfolio pages + */ + public function savePortfolioPagesOrdering() + { + if (!$this->checkPermissionBool("write")) { + return; + } + + $title_changes = array(); + + if (is_array($_POST["order"])) { + foreach ($_POST["order"] as $k => $v) { + $page = $this->getPageInstance(ilUtil::stripSlashes($k)); + if ($_POST["title"][$k]) { + $new_title = trim(ilUtil::stripSlashes($_POST["title"][$k])); + if ($page->getTitle() != $new_title) { + $title_changes[$page->getId()] = array("old" => $page->getTitle(), "new" => $new_title); + $page->setTitle($new_title); + } + } + $page->setOrderNr(ilUtil::stripSlashes($v)); + $page->update(); + } + ilPortfolioPage::fixOrdering($this->object->getId()); + } + + $this->object->fixLinksOnTitleChange($title_changes); + + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "view"); + } + + /** + * Confirm portfolio deletion + */ + public function confirmPortfolioPageDeletion() + { + $prtf_pages = $_REQUEST["prtf_pages"]; + + if (!is_array($prtf_pages) || count($prtf_pages) == 0) { + ilUtil::sendInfo($this->lng->txt("no_checkbox"), true); + $this->ctrl->redirect($this, "view"); + } else { + $this->tabs_gui->activateTab("pages"); + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($this->ctrl->getFormAction($this)); + $cgui->setHeaderText($this->lng->txt("prtf_sure_delete_portfolio_pages")); + $cgui->setCancel($this->lng->txt("cancel"), "view"); + $cgui->setConfirm($this->lng->txt("delete"), "deletePortfolioPages"); + + foreach ($prtf_pages as $id) { + $page = $this->getPageInstance((int) $id); + if ($page->getPortfolioId() != $this->object->getId()) { + continue; + } + + $title = $page->getTitle(); + if ($page->getType() == ilPortfolioPage::TYPE_BLOG) { + $title = $this->lng->txt("obj_blog") . ": " . ilObject::_lookupTitle((int) $title); + } + $cgui->addItem("prtf_pages[]", $id, $title); + } + + $this->tpl->setContent($cgui->getHTML()); + } + } + + /** + * Delete portfolio pages + */ + public function deletePortfolioPages() + { + if (!$this->checkPermissionBool("write")) { + return; + } + + if (is_array($_POST["prtf_pages"])) { + foreach ($_POST["prtf_pages"] as $id) { + $page = $this->getPageInstance($id); + $page->delete(); + } + } + ilUtil::sendSuccess($this->lng->txt("prtf_portfolio_page_deleted"), true); + $this->ctrl->redirect($this, "view"); + } + + /** + * Show user page + */ + public function preview($a_return = false, $a_content = false, $a_show_notes = true) + { + $ilSetting = $this->settings; + $ilUser = $this->user; + + $portfolio_id = $this->object->getId(); + $user_id = $this->object->getOwner(); + + $this->tabs_gui->clearTargets(); + + $pages = ilPortfolioPage::getAllPortfolioPages($portfolio_id); + $current_page = (int) $_GET["user_page"]; + + // validate current page + if ($pages && $current_page) { + $found = false; + foreach ($pages as $page) { + if ($page["id"] == $current_page) { + $found = true; + break; + } + } + if (!$found) { + $current_page = null; + } + } + + // display first page of portfolio if none given + if (!$current_page && $pages) { + $current_page = $pages; + $current_page = array_shift($current_page); + $current_page = $current_page["id"]; + } + + // #13788 - keep page after login + if ($this->user_id == ANONYMOUS_USER_ID && + $this->getType() == "prtf") { + $this->tpl->setLoginTargetPar("prtf_" . $this->object->getId() . "_" . $current_page); + } + + $back_caption = ""; + + // public profile + if ($_REQUEST["back_url"]) { + $back = $_REQUEST["back_url"]; + } elseif ($_GET["baseClass"] != "ilPublicUserProfileGUI" && + $this->user_id && $this->user_id != ANONYMOUS_USER_ID) { + if (!$this->checkPermissionBool("write")) { + // shared + if ($this->getType() == "prtf") { + $this->ctrl->setParameterByClass("ilportfoliorepositorygui", "shr_id", $this->object->getOwner()); + $back = $this->ctrl->getLinkTargetByClass(array("ilpersonaldesktopgui", "ilportfoliorepositorygui"), "showOther"); + $this->ctrl->setParameterByClass("ilportfoliorepositorygui", "shr_id", ""); + } + // listgui / parent container + else { + // #12819 + $tree = $this->tree; + $parent_id = $tree->getParentId($this->node_id); + include_once "Services/Link/classes/class.ilLink.php"; + $back = ilLink::_getStaticLink($parent_id); + } + } + // owner + else { + $back = $this->ctrl->getLinkTarget($this, "view"); + if ($this->getType() == "prtf") { + $back_caption = $this->lng->txt("prtf_back_to_portfolio_owner"); + } else { + // #19316 + $this->lng->loadLanguageModule("prtt"); + $back_caption = $this->lng->txt("prtt_edit"); + } + } + } + + $ilMainMenu = $this->main_menu; + $ilMainMenu->setMode(ilMainMenuGUI::MODE_TOPBAR_ONLY); + if ($back) { + // might already be set in ilPublicUserProfileGUI + $ilMainMenu->setTopBarBack($back, $back_caption); + } + + // render tabs + $current_blog = null; + if (count($pages) > 1) { + foreach ($pages as $p) { + if ($p["type"] == ilPortfolioPage::TYPE_BLOG) { + // needed for blog comments (see below) + if ($p["id"] == $current_page) { + $current_blog = (int) $p["title"]; + } + include_once "Modules/Blog/classes/class.ilObjBlog.php"; + $p["title"] = ilObjBlog::_lookupTitle($p["title"]); + } + + $this->ctrl->setParameter($this, "user_page", $p["id"]); + $this->tabs_gui->addTab( + "user_page_" . $p["id"], + $p["title"], + $this->ctrl->getLinkTarget($this, "preview") + ); + } + + $this->tabs_gui->activateTab("user_page_" . $current_page); + } + + $this->ctrl->setParameter($this, "user_page", $current_page); + + if (!$a_content) { + // #18291 + if ($current_page) { + // get current page content + $page_gui = $this->getPageGUIInstance($current_page); + $page_gui->setEmbedded(true); + + $content = $this->ctrl->getHTML($page_gui); + } + } else { + $content = $a_content; + } + + if ($a_return && $this->checkPermissionBool("write")) { + return $content; + } + + // blog posting comments are handled within the blog + $notes = ""; + if ($a_show_notes && $this->object->hasPublicComments() && !$current_blog && $current_page) { + include_once("./Services/Notes/classes/class.ilNoteGUI.php"); + $note_gui = new ilNoteGUI($portfolio_id, $current_page, "pfpg"); + $note_gui->setRepositoryMode(false); + $note_gui->enablePublicNotes(true); + $note_gui->enablePrivateNotes(false); + + $note_gui->enablePublicNotesDeletion(($this->user_id == $user_id) && + $ilSetting->get("comments_del_tutor", 1)); + + $next_class = $this->ctrl->getNextClass($this); + if ($next_class == "ilnotegui") { + $notes = $this->ctrl->forwardCommand($note_gui); + } else { + $notes = $note_gui->getNotesHTML(); + } + } + + if ($this->perma_link === null) { + if ($this->getType() == "prtf") { + $this->tpl->setPermanentLink($this->getType(), $this->object->getId(), "_" . $current_page); + } else { + $this->tpl->setPermanentLink($this->getType(), $this->object->getRefId()); + } + } else { + $this->tpl->setPermanentLink($this->perma_link["type"], $this->perma_link["obj_id"]); + } + + // #18208 - see ilPortfolioTemplatePageGUI::getPageContentUserId() + if ($this->getType() == "prtt" && !$this->checkPermissionBool("write")) { + $user_id = $ilUser->getId(); + } + + self::renderFullscreenHeader($this->object, $this->tpl, $user_id); + + // #13564 + $this->ctrl->setParameter($this, "user_page", ""); + $this->tpl->setTitleUrl($this->ctrl->getLinkTarget($this, "preview")); + $this->ctrl->setParameter($this, "user_page", $this->page_id); + + // blog pages do their own (page) style handling + if (!$current_blog) { + $content = '
' . + '
' . + $content . + '
'; + + $this->setContentStyleSheet($this->tpl); + } + + // #10717 + $this->tpl->setContent($content . + '
' . $notes . '
'); + } + + /** + * Render banner, user name + * + * @param object $a_tpl + * @param int $a_user_id + * @param bool $a_export_path + */ + public static function renderFullscreenHeader($a_portfolio, $a_tpl, $a_user_id, $a_export = false) + { + global $DIC; + + $ilUser = $DIC->user(); + + if (!$a_export) { + require_once('Services/Tracking/classes/class.ilChangeEvent.php'); + ilChangeEvent::_recordReadEvent( + $a_portfolio->getType(), + ($a_portfolio->getType() == "prtt") + ? $a_portfolio->getRefId() + : $a_portfolio->getId(), + $a_portfolio->getId(), + $ilUser->getId() + ); + } + + $name = ilObjUser::_lookupName($a_user_id); + $name = $name["lastname"] . ", " . ($t = $name["title"] ? $t . " " : "") . $name["firstname"]; + + // show banner? + $banner = $banner_width = $banner_height = false; + $prfa_set = new ilSetting("prfa"); + if ($prfa_set->get("banner")) { + require_once('./Services/WebAccessChecker/classes/class.ilWACSignedPath.php'); + $banner = ilWACSignedPath::signFile($a_portfolio->getImageFullPath()); + $banner_width = $prfa_set->get("banner_width"); + $banner_height = $prfa_set->get("banner_height"); + if ($a_export) { + $banner = basename($banner); + } + } + + // profile picture + $ppic = null; + if ($a_portfolio->hasProfilePicture()) { + $ppic = ilObjUser::_getPersonalPicturePath($a_user_id, "xsmall", true, true); + if ($a_export) { + $ppic = basename($ppic); + } + } + + $a_tpl->resetHeaderBlock(false); + // $a_tpl->setBackgroundColor($a_portfolio->getBackgroundColor()); + $a_tpl->setBanner($banner, $banner_width, $banner_height, $a_export); + $a_tpl->setTitleIcon($ppic); + $a_tpl->setTitle($a_portfolio->getTitle()); + // $a_tpl->setTitleColor($a_portfolio->getFontColor()); + $a_tpl->setDescription($name); + + // to get rid of locator in portfolio template preview + $a_tpl->setVariable("LOCATOR", ""); + + // :TODO: obsolete? + // $a_tpl->setBodyClass("std ilExternal ilPortfolio"); + } + + public function export() + { + include_once "Modules/Portfolio/classes/class.ilPortfolioHTMLExport.php"; + $export = new ilPortfolioHTMLExport($this, $this->object); + $zip = $export->buildExportFile(); + + ilUtil::deliverFile($zip, $this->object->getTitle() . ".zip", '', false, true); + } + + + /** + * Select target portfolio for page(s) copy + */ + public function copyPageForm($a_form = null) + { + $prtf_pages = $_REQUEST["prtf_pages"]; + + if (!is_array($prtf_pages) || count($prtf_pages) == 0) { + ilUtil::sendInfo($this->lng->txt("no_checkbox"), true); + $this->ctrl->redirect($this, "view"); + } else { + $this->tabs_gui->activateTab("pages"); + + if (!$a_form) { + $a_form = $this->initCopyPageForm(); + } + + foreach ($prtf_pages as $page_id) { + $item = new ilHiddenInputGUI("prtf_pages[]"); + $item->setValue((int) $page_id); + $a_form->addItem($item); + } + + $this->tpl->setContent($a_form->getHTML()); + } + } + + public function copyPage() + { + $form = $this->initCopyPageForm(); + if ($form->checkInput()) { + // existing + if ($form->getInput("target") == "old") { + $portfolio_id = $form->getInput("prtf"); + } + // new + else { + $portfolio = new ilObjPortfolio(); + $portfolio->setTitle($form->getInput("title")); + $portfolio->create(); + $portfolio_id = $portfolio->getId(); + } + + // copy page(s) + foreach ($_POST["prtf_pages"] as $page_id) { + $source = $this->getPageInstance($page_id); + $target = $this->getPageInstance(null, $portfolio_id); + $target->setXMLContent($source->copyXmlContent(true)); // copy mobs + $target->setType($source->getType()); + $target->setTitle($source->getTitle()); + $target->create(); + } + + ilUtil::sendSuccess($this->lng->txt("prtf_pages_copied"), true); + $this->ctrl->redirect($this, "view"); + } + + $form->setValuesByPost(); + $this->copyPageForm($form); + } + + abstract protected function initCopyPageFormOptions(ilPropertyFormGUI $a_form); + + public function initCopyPageForm() + { + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this)); + $form->setTitle($this->lng->txt("prtf_copy_page")); + + $this->initCopyPageFormOptions($form); + + $form->addCommandButton("copyPage", $this->lng->txt("save")); + $form->addCommandButton("view", $this->lng->txt("cancel")); + + return $form; + } + + + //// + //// 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, + $_GET["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($this->getType() . "_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(ilUtil::stripSlashes($_POST["style_id"])); + $this->object->update(); + + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + } + $this->ctrl->redirect($this, "editStyleProperties"); + } +} diff --git a/Modules/Portfolio/classes/class.ilObjPortfolioGUI.php b/Modules/Portfolio/classes/class.ilObjPortfolioGUI.php index 28fd29fff5b1e57185ca2259b44d39eaf7e8c47d..7817f72f45ee48e9ffd944a5e2b4de91d0c5def3 100644 --- a/Modules/Portfolio/classes/class.ilObjPortfolioGUI.php +++ b/Modules/Portfolio/classes/class.ilObjPortfolioGUI.php @@ -1,1658 +1,1557 @@ - - * @version $Id$ - * - * @ilCtrl_Calls ilObjPortfolioGUI: ilPortfolioPageGUI, ilPageObjectGUI - * @ilCtrl_Calls ilObjPortfolioGUI: ilWorkspaceAccessGUI, ilNoteGUI - * @ilCtrl_Calls ilObjPortfolioGUI: ilObjStyleSheetGUI, ilPortfolioExerciseGUI - * - * @ingroup ModulesPortfolio - */ -class ilObjPortfolioGUI extends ilObjPortfolioBaseGUI -{ - /** - * @var ilHelpGUI - */ - protected $help; - - protected $ws_access; // [ilWorkspaceAccessHandler] - - /** - * @var \ILIAS\DI\UIServices - */ - protected $ui; - - /** - * @var ilPortfolioDeclarationOfAuthorship - */ - protected $declaration_authorship; - - public function __construct($a_id = 0) - { - global $DIC; - - $this->lng = $DIC->language(); - $this->help = $DIC["ilHelp"]; - $this->settings = $DIC->settings(); - $this->access = $DIC->access(); - $this->user = $DIC->user(); - $this->ctrl = $DIC->ctrl(); - $this->ui = $DIC->ui(); - - parent::__construct($a_id, self::PORTFOLIO_OBJECT_ID, 0); - $this->declaration_authorship = new ilPortfolioDeclarationOfAuthorship(); - - $this->ctrl->saveParameter($this, "exc_back_ref_id"); - } - - public function getType() - { - return "prtf"; - } - - protected function checkPermissionBool($a_perm, $a_cmd = "", $a_type = "", $a_node_id = null) - { - if($a_perm == "create") - { - return true; - } - if(!$a_node_id) - { - $a_node_id = $this->obj_id; - } - return $this->access_handler->checkAccess($a_perm, "", $a_node_id); - } - - function executeCommand() - { - $lng = $this->lng; - - $this->checkPermission("read"); - - // goto link to portfolio page - if($_GET["gtp"]) - { - $_GET["user_page"] = $_GET["gtp"]; - } - - $this->setTitleAndDescription(); - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd("view"); - - /* - if($_REQUEST["ecal"]) - { - $cmd = "preview"; - $next_class = ""; - } - */ - - switch($next_class) - { - case "ilworkspaceaccessgui"; - if($this->checkPermissionBool("write")) - { - $this->setTabs(); - $this->tabs_gui->activateTab("share"); - - if($this->access_handler->getPermissions($this->object->getId()) && - !$this->object->isOnline()) - { - //ilUtil::sendInfo($lng->txt("prtf_shared_offline_info")); - } - - $this->tpl->setPermanentLink("prtf", $this->object->getId()); - - include_once('./Services/PersonalWorkspace/classes/class.ilWorkspaceAccessGUI.php'); - $wspacc = new ilWorkspaceAccessGUI($this->object->getId(), $this->access_handler, true); - $wspacc->setBlockingMessage($this->getOfflineMessage()); - $this->ctrl->forwardCommand($wspacc); - } - break; - - case 'ilportfoliopagegui': - if($this->determinePageCall()) - { - // only in edit mode - $this->addLocator(); - - include_once "Services/Form/classes/class.ilFileInputGUI.php"; - ilFileInputGUI::setPersonalWorkspaceQuotaCheck(true); - } - $this->handlePageCall($cmd); - break; - - case "ilnotegui"; - $this->preview(); - 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" || $_GET["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 "ilportfolioexercisegui": - $this->ctrl->setReturn($this, "view"); - include_once "Modules/Portfolio/classes/class.ilPortfolioExerciseGUI.php"; - $gui = new ilPortfolioExerciseGUI($this->user_id, $this->object->getId()); - $this->ctrl->forwardCommand($gui); - break; - - default: - - if($cmd != "preview") - { - $this->addLocator(); - $this->setTabs(); - } - $this->$cmd(); - break; - } - - return true; - } - - protected function setTabs() - { - $ilHelp = $this->help; - - $ilHelp->setScreenIdComponent("prtf"); - - if($this->checkPermissionBool("write")) - { - $this->tabs_gui->addTab("pages", - $this->lng->txt("content"), - $this->ctrl->getLinkTarget($this, "view")); - - $this->tabs_gui->addTab("settings", - $this->lng->txt("settings"), - $this->ctrl->getLinkTarget($this, "edit")); - - $this->tabs_gui->addNonTabbedLink("preview", - $this->lng->txt("user_profile_preview"), - $this->ctrl->getLinkTarget($this, "preview")); - - $this->lng->loadLanguageModule("wsp"); - $this->tabs_gui->addTab("share", - $this->lng->txt("wsp_permissions"), - $this->ctrl->getLinkTargetByClass("ilworkspaceaccessgui", "share")); - } - } - - protected function addLocator() - { - if(!$this->creation_mode) - { - $this->ctrl->setParameter($this, "prt_id", $this->object->getId()); - } - - parent::addLocatorItems(); - - $this->tpl->setLocator(); - } - - protected function setTitleAndDescription() - { - // parent::setTitleAndDescription(); - - $title = $this->lng->txt("portfolio"); - if($this->object) - { - $title .= ": ".$this->object->getTitle(); - } - $this->tpl->setTitle($title); - $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_prtf.svg"), - $this->lng->txt("portfolio")); - - if($this->object && - !$this->object->isOnline()) - { - $this->tpl->setAlertProperties(array( - array("alert" => true, - "property" => $this->lng->txt("status"), - "value" => $this->lng->txt("offline")) - )); - } - } - - - // - // CREATE/EDIT - // - - /** - * create new object form - * - * @access public - */ - public function create() - { - $tpl = $this->tpl; - $ilErr = $this->ilErr; - - $new_type = $_REQUEST["new_type"]; - - // add new object to custom parent container - $this->ctrl->saveParameter($this, "crtptrefid"); - // use forced callback after object creation - $this->ctrl->saveParameter($this, "crtcb"); - - if (!$this->checkPermissionBool("create", "", $new_type)) - { - $ilErr->raiseError($this->lng->txt("permission_denied"),$ilErr->MESSAGE); - } - else - { - $this->lng->loadLanguageModule($new_type); - $this->ctrl->setParameter($this, "new_type", $new_type); - - $forms = $this->initCreationForms($new_type); - - // copy form validation error: do not show other creation forms - if($_GET["cpfl"] && isset($forms[self::CFORM_CLONE])) - { - $forms = array(self::CFORM_CLONE => $forms[self::CFORM_CLONE]); - } - $tpl->setContent($this->getCreateInfoMessage().$this->getCreationFormsHTML($forms)); - } - } - - /** - * Get cereat info message - * - * @param - * @return - */ - protected function getCreateInfoMessage() - { - global $DIC; - - $ctrl = $this->ctrl; - $lng = $this->lng; - $ui = $DIC->ui(); - $ilSetting =$DIC->settings(); - - $message = ""; - // page type: blog - if (!$ilSetting->get('disable_wsp_blogs')) - { - $options = array(); - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - $tree = new ilWorkspaceTree($this->user_id); - $root = $tree->readRootId(); - if ($root) - { - $root = $tree->getNodeData($root); - foreach ($tree->getSubTree($root) as $node) - { - if ($node["type"] == "blog") - { - $options[$node["obj_id"]] = $node["title"]; - } - } - asort($options); - } - if (!sizeof($options)) - { - - // #18147 - $this->lng->loadLanguageModule('pd'); - $url = $this->ctrl->getLinkTargetByClass("ilpersonaldesktopgui", "jumpToWorkspace"); - $text = $this->lng->txt("pd_personal_workspace"); - - $text = sprintf($this->lng->txt("prtf_no_blogs_info"), $text); - - $mbox = $ui->factory()->messageBox()->info($text) - ->withLinks([$ui->factory()->link()->standard($this->lng->txt("pd_personal_workspace"), - $url)]); - - $message = $ui->renderer()->render($mbox); - } - - } - return $message; - } - - - protected function initCreationForms($a_new_type) - { - return array(self::CFORM_NEW => $this->initCreateForm($a_new_type)); - } - - protected function initCreateForm($a_new_type) - { - $ilSetting = $this->settings; - - $this->ctrl->setParameter($this, "new_type", $this->getType()); - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - - // title - $ti = new ilTextInputGUI($this->lng->txt("title"), "title"); - $ti->setSize(min(40, ilObject::TITLE_LENGTH)); - $ti->setMaxLength(ilObject::TITLE_LENGTH); - $ti->setRequired(true); - $form->addItem($ti); - - /* description - $ta = new ilTextAreaInputGUI($this->lng->txt("description"), "desc"); - $ta->setCols(40); - $ta->setRows(2); - $form->addItem($ta); - */ - - $main = new ilRadioGroupInputGUI($this->lng->txt("prtf_creation_mode"), "mode"); - $main->setValue("mode_scratch"); - $form->addItem($main); - - $opt_scratch = new ilRadioOption($this->lng->txt("prtf_creation_mode_scratch"), "mode_scratch"); - $main->addOption($opt_scratch); - - - // 1st page - - $type = new ilRadioGroupInputGUI($this->lng->txt("prtf_first_page_title"), "ptype"); - $type->setRequired(true); - $opt_scratch->addSubItem($type); - - $type_page = new ilRadioOption($this->lng->txt("page"), "page"); - $type->addOption($type_page); - - // page type: page - $tf = new ilTextInputGUI($this->lng->txt("title"), "fpage"); - $tf->setMaxLength(128); - $tf->setSize(40); - $tf->setRequired(true); - $type_page->addSubItem($tf); - - // page templates - include_once "Services/COPage/Layout/classes/class.ilPageLayout.php"; - $templates = ilPageLayout::activeLayouts(false, ilPageLayout::MODULE_PORTFOLIO); - if($templates) - { - $options = array(0 => $this->lng->txt("none")); - foreach ($templates as $templ) - { - $templ->readObject(); - $options[$templ->getId()] = $templ->getTitle(); - } - - $use_template = new ilSelectInputGUI($this->lng->txt("prtf_use_page_layout"), "tmpl"); - $use_template->setRequired(true); - $use_template->setOptions($options); - $type_page->addSubItem($use_template); - } - - // page type: blog - if(!$ilSetting->get('disable_wsp_blogs')) - { - $options = array(); - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - $tree = new ilWorkspaceTree($this->user_id); - $root = $tree->readRootId(); - if($root) - { - $root = $tree->getNodeData($root); - foreach ($tree->getSubTree($root) as $node) - { - if ($node["type"] == "blog") - { - $options[$node["obj_id"]] = $node["title"]; - } - } - asort($options); - } - if(sizeof($options)) - { - $type_blog = new ilRadioOption($this->lng->txt("obj_blog"), "blog"); - $type->addOption($type_blog); - - $obj = new ilSelectInputGUI($this->lng->txt("obj_blog"), "blog"); - $obj->setRequired(true); - $obj->setOptions(array(""=>$this->lng->txt("please_select"))+$options); - $type_blog->addSubItem($obj); - } - else - { - $type->setValue("page"); - } - } - - - // portfolio templates - - $opt_tmpl = new ilRadioOption($this->lng->txt("prtf_creation_mode_template"), "mode_tmpl"); - $main->addOption($opt_tmpl); - - include_once "Modules/Portfolio/classes/class.ilObjPortfolioTemplate.php"; - $templates = ilObjPortfolioTemplate::getAvailablePortfolioTemplates(); - if(!sizeof($templates)) - { - $opt_tmpl->setDisabled(true); - } - else - { - $tmpl = new ilSelectInputGUI($this->lng->txt("obj_prtt"), "prtt"); - $tmpl->setRequired(true); - $tmpl->setOptions(array(""=>$this->lng->txt("please_select"))+$templates); - $opt_tmpl->addSubItem($tmpl); - - // incoming from repository - if((int)$_REQUEST["prtt_pre"]) - { - $tmpl->setValue((int)$_REQUEST["prtt_pre"]); - $main->setValue("mode_tmpl"); - } - } - - - $form->setTitle($this->lng->txt("prtf_create_portfolio")); - $form->addCommandButton("save", $this->lng->txt("create")); - $form->addCommandButton("toRepository", $this->lng->txt("cancel")); - - return $form; - } - - public function save() - { - $form = $this->initCreateForm("prtf"); - if($form->checkInput()) - { - // trigger portfolio template "import" process - if($form->getInput("mode") == "mode_tmpl") - { - $_REQUEST["pt"] = $form->getInput("title"); - $_REQUEST["prtt_pre"] = (int)$_REQUEST["prtt"]; - return $this->createFromTemplateDirect($form->getInput("title")); - //return $this->createPortfolioFromTemplate(); - } - } - - return parent::save(); - } - - protected function afterSave(ilObject $a_new_object) - { - // create 1st page / blog - include_once("Modules/Portfolio/classes/class.ilPortfolioPage.php"); - $page = $this->getPageInstance(null, $a_new_object->getId()); - if($_POST["ptype"] == "page") - { - $page->setType(ilPortfolioPage::TYPE_PAGE); - $page->setTitle($_POST["fpage"]); - - // use template as basis - $layout_id = $_POST["tmpl"]; - if($layout_id) - { - include_once("./Services/COPage/Layout/classes/class.ilPageLayout.php"); - $layout_obj = new ilPageLayout($layout_id); - $page->setXMLContent($layout_obj->getXMLContent()); - } - } - else - { - $page->setType(ilPortfolioPage::TYPE_BLOG); - $page->setTitle($_POST["blog"]); - } - $page->create(); - - ilUtil::sendSuccess($this->lng->txt("prtf_portfolio_created"), true); - $this->ctrl->setParameter($this, "prt_id", $a_new_object->getId()); - $this->ctrl->redirect($this, "view"); - } - - protected function toRepository() - { - $ilAccess = $this->access; - - // return to exercise (portfolio assignment) - $exc_ref_id = (int)$_REQUEST["exc_id"]; - if($exc_ref_id && - $ilAccess->checkAccess("read", "", $exc_ref_id)) - { - include_once "Services/Link/classes/class.ilLink.php"; - ilUtil::redirect(ilLink::_getLink($exc_ref_id, "exc")); - } - - $this->ctrl->redirectByClass("ilportfoliorepositorygui", "show"); - } - - protected function initEditForm() - { - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - - // title - $ti = new ilTextInputGUI($this->lng->txt("title"), "title"); - $ti->setSize(min(40, ilObject::TITLE_LENGTH)); - $ti->setMaxLength(ilObject::TITLE_LENGTH); - $ti->setRequired(true); - $ti->setValue($this->object->getTitle()); - $form->addItem($ti); - - /* description - $ta = new ilTextAreaInputGUI($this->lng->txt("description"), "desc"); - $ta->setCols(40); - $ta->setRows(2); - $ta->setValue($this->object->getDescription()); - $form->addItem($ta); - */ - - // :TODO: online - $online = new ilCheckboxInputGUI($this->lng->txt("online"), "online"); - $online->setChecked($this->object->isOnline()); - $form->addItem($online); - - $this->initEditCustomForm($form); - - $form->setTitle($this->lng->txt("prtf_edit_portfolio")); - $form->addCommandButton("update", $this->lng->txt("save")); - $form->addCommandButton("view", $this->lng->txt("cancel")); - - return $form; - } - - protected function getEditFormCustomValues(array &$a_values) - { - $a_values["online"] = $this->object->isOnline(); - - parent::getEditFormCustomValues($a_values); - } - - public function updateCustom(ilPropertyFormGUI $a_form) - { - $this->object->setOnline($a_form->getInput("online")); - - // if portfolio is not online, it cannot be default - if(!$a_form->getInput("online")) - { - ilObjPortfolio::setUserDefault($this->user_id, 0); - } - - parent::updateCustom($a_form); - } - - - // - // PAGES - // - - /** - * Get portfolio template page instance - * - * @param int $a_page_id - * @param int $a_portfolio_id - * @return ilPortfolioPage - */ - protected function getPageInstance($a_page_id = null, $a_portfolio_id = null) - { - // #11531 - if(!$a_portfolio_id && $this->object) - { - $a_portfolio_id = $this->object->getId(); - } - include_once "Modules/Portfolio/classes/class.ilPortfolioPage.php"; - $page = new ilPortfolioPage($a_page_id); - $page->setPortfolioId($a_portfolio_id); - return $page; - } - - /** - * Get portfolio template page gui instance - * - * @param int $a_page_id - * @return ilPortfolioPageGUI - */ - protected function getPageGUIInstance($a_page_id) - { - include_once("Modules/Portfolio/classes/class.ilPortfolioPageGUI.php"); - $page_gui = new ilPortfolioPageGUI( - $this->object->getId(), - $a_page_id, - 0, - $this->object->hasPublicComments() - ); - $page_gui->setAdditional($this->getAdditional()); - return $page_gui; - } - - public function getPageGUIClassName() - { - return "ilportfoliopagegui"; - } - - protected function initCopyPageFormOptions(ilPropertyFormGUI $a_form) - { - - $a_tgt = new ilRadioGroupInputGUI($this->lng->txt("target"), "target"); - $a_tgt->setRequired(true); - $a_form->addItem($a_tgt); - - $old = new ilRadioOption($this->lng->txt("prtf_existing_portfolio"), "old"); - $a_tgt->addOption($old); - - $options = array(); - $all = ilObjPortfolio::getPortfoliosOfUser($this->user_id); - foreach($all as $item) - { - $options[$item["id"]] = $item["title"]; - } - $prtf = new ilSelectInputGUI($this->lng->txt("portfolio"), "prtf"); - $prtf->setRequired(true); - $prtf->setOptions($options); - $old->addSubItem($prtf); - - $new = new ilRadioOption($this->lng->txt("prtf_new_portfolio"), "new"); - $a_tgt->addOption($new); - - $tf = new ilTextInputGUI($this->lng->txt("title"), "title"); - $tf->setMaxLength(128); - $tf->setSize(40); - $tf->setRequired(true); - $new->addSubItem($tf); - } - - - // - // BLOG - // - - /** - * Init blog page form - * - * @param string $a_mode - * @return ilPropertyFormGUI - */ - public function initBlogForm() - { - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - - $options = array(); - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - $tree = new ilWorkspaceTree($this->user_id); - $root = $tree->readRootId(); - if($root) - { - $root = $tree->getNodeData($root); - foreach ($tree->getSubTree($root, true, "blog") as $node) - { - $options[$node["obj_id"]] = $node["title"]; - } - asort($options); - } - - // add blog - $radg = new ilRadioGroupInputGUI($this->lng->txt("obj_blog"), "creation_mode"); - $radg->setInfo($this->lng->txt("")); - $radg->setValue("new"); - $radg->setInfo($this->lng->txt("")); - - $op1 = new ilRadioOption($this->lng->txt("prtf_add_new_blog"), "new" ,$this->lng->txt("prtf_add_new_blog_info")); - $radg->addOption($op1); - $form->addItem($radg); - - // Blog title - $ti = new ilTextInputGUI($this->lng->txt("title"), "title"); - $ti->setRequired(true); - $op1->addSubItem($ti); - - - if(sizeof($options)) - { - $op2 = new ilRadioOption($this->lng->txt("prtf_add_existing_blog"), "existing"); - $radg->addOption($op2); - - $obj = new ilSelectInputGUI($this->lng->txt("obj_blog"), "blog"); - $obj->setOptions($options); - $op2->addSubItem($obj); - } - - $form->setTitle($this->lng->txt("prtf_add_blog").": ". - $this->object->getTitle()); - $form->addCommandButton("saveBlog", $this->lng->txt("save")); - $form->addCommandButton("view", $this->lng->txt("cancel")); - - return $form; - } - - /** - * Create new portfolio blog page - */ - public function saveBlog() - { - global $DIC; - - $ilUser = $DIC->user(); - - $form = $this->initBlogForm(); - if ($form->checkInput() && $this->checkPermissionBool("write")) - { - if ($form->getInput("creation_mode") == "existing") - { - $page = $this->getPageInstance(); - $page->setType(ilPortfolioPage::TYPE_BLOG); - $page->setTitle($form->getInput("blog")); - $page->create(); - } - else - { - $blog = new ilObjBlog(); - $blog->setTitle($form->getInput("title")); - $blog->create(); - - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - $tree = new ilWorkspaceTree($ilUser->getId()); - - // @todo: see also e.g. ilExSubmissionObjectGUI->getOverviewContentBlog, this needs refactoring, consumer should not - // be responsibel to handle this - if(!$tree->getRootId()) - { - $tree->createTreeForUser($ilUser->getId()); - } - - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; - $access_handler = new ilWorkspaceAccessHandler($tree); - $node_id = $tree->insertObject($tree->readRootId(), $blog->getId()); - $access_handler->setPermissions($tree->readRootId(), $node_id); - - $page = $this->getPageInstance(); - $page->setType(ilPortfolioPage::TYPE_BLOG); - $page->setTitle($blog->getId()); - $page->create(); - } - - ilUtil::sendSuccess($this->lng->txt("prtf_blog_page_created"), true); - $this->ctrl->redirect($this, "view"); - } - - $this->tabs_gui->clearTargets(); - $this->tabs_gui->setBackTarget($this->lng->txt("back"), - $this->ctrl->getLinkTarget($this, "view")); - - $form->setValuesByPost(); - $this->tpl->setContent($form->getHtml()); - } - - - // - // CREATE FROM TEMPLATE - // - - protected function createPortfolioFromTemplate(ilPropertyFormGUI $a_form = null) - { - $title = trim($_REQUEST["pt"]); - $prtt_id = (int)$_REQUEST["prtt"]; - - // valid template? - include_once "Modules/Portfolio/classes/class.ilObjPortfolioTemplate.php"; - $templates = array_keys(ilObjPortfolioTemplate::getAvailablePortfolioTemplates()); - if(!sizeof($templates) || !in_array($prtt_id, $templates)) - { - $this->toRepository(); - } - unset($templates); - - $this->ctrl->setParameter($this, "prtt", $prtt_id); - - if(!$a_form) - { - $a_form = $this->initCreatePortfolioFromTemplateForm($prtt_id, $title); - } - if($a_form) - { - $this->tpl->setContent($a_form->getHTML()); - } - else - { - $this->createPortfolioFromTemplateProcess(false); - } - } - - protected function initCreatePortfolioFromTemplateForm($a_prtt_id, $a_title) - { - $ilSetting = $this->settings; - $ilUser = $this->user; - - if((int)$_REQUEST["exc_id"]) - { - $this->ctrl->setParameter($this, "exc_id", (int)$_REQUEST["exc_id"]); - $this->ctrl->setParameter($this, "ass_id", (int)$_REQUEST["ass_id"]); - } - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - - $tmpl = new ilNonEditableValueGUI($this->lng->txt("obj_prtt")); - $tmpl->setValue(ilObject::_lookupTitle($a_prtt_id)); - $form->addItem($tmpl); - - $title = new ilNonEditableValueGUI($this->lng->txt("title"), "pt"); - $title->setValue($a_title); - $form->addItem($title); - - // gather user blogs - if(!$ilSetting->get('disable_wsp_blogs')) - { - $blog_options = array(); - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - $tree = new ilWorkspaceTree($this->user_id); - $root = $tree->readRootId(); - if($root) - { - $root = $tree->getNodeData($root); - foreach ($tree->getSubTree($root, true, "blog") as $node) - { - $blog_options[$node["obj_id"]] = $node["title"]; - } - asort($blog_options); - } - } - - $has_form_content = false; - - include_once "Services/WebDAV/classes/class.ilDiskQuotaActivationChecker.php"; - $check_quota = ilDiskQuotaActivationChecker::_isPersonalWorkspaceActive(); - $quota_sum = 0; - - include_once "Services/Skill/classes/class.ilPersonalSkill.php"; - $pskills = array_keys(ilPersonalSkill::getSelectedUserSkills($ilUser->getId())); - $skill_ids = array(); - - include_once "Modules/Portfolio/classes/class.ilPortfolioTemplatePage.php"; - foreach(ilPortfolioTemplatePage::getAllPortfolioPages($a_prtt_id) as $page) - { - switch($page["type"]) - { - case ilPortfolioTemplatePage::TYPE_PAGE: - // skills - $source_page = new ilPortfolioTemplatePage($page["id"]); - $source_page->buildDom(true); - $skill_ids = $this->getSkillsToPortfolioAssignment($pskills, $skill_ids, $source_page); - - if($check_quota) - { - $quota_sum += $source_page->getPageDiskSize(); - } - if(sizeof($skill_ids)) - { - $has_form_content = true; - } - break; - - case ilPortfolioTemplatePage::TYPE_BLOG_TEMPLATE: - if(!$ilSetting->get('disable_wsp_blogs')) - { - $has_form_content = true; - - $field_id = "blog_".$page["id"]; - - $blog = new ilRadioGroupInputGUI($this->lng->txt("obj_blog").": ". - $page["title"], $field_id); - $blog->setRequired(true); - $blog->setValue("blog_create"); - $form->addItem($blog); - - $new_blog = new ilRadioOption($this->lng->txt("prtf_template_import_blog_create"), "blog_create"); - $blog->addOption($new_blog); - - $title = new ilTextInputGUI($this->lng->txt("title"), $field_id."_create_title"); - $title->setRequired(true); - $new_blog->addSubItem($title); - - if(sizeof($blog_options)) - { - $reuse_blog = new ilRadioOption($this->lng->txt("prtf_template_import_blog_reuse"), "blog_resuse"); - $blog->addOption($reuse_blog); - - $obj = new ilSelectInputGUI($this->lng->txt("obj_blog"), $field_id."_reuse_blog"); - $obj->setRequired(true); - $obj->setOptions(array(""=>$this->lng->txt("please_select"))+$blog_options); - $reuse_blog->addSubItem($obj); - } - - $blog->addOption(new ilRadioOption($this->lng->txt("prtf_template_import_blog_ignore"), "blog_ignore")); - } - break; - } - } - - if($skill_ids) - { - include_once "Services/Skill/classes/class.ilSkillTreeNode.php"; - $skills = new ilCheckboxGroupInputGUI($this->lng->txt("skills"), "skill_ids"); - $skills->setInfo($this->lng->txt("prtf_template_import_new_skills")); - $skills->setValue($skill_ids); - foreach($skill_ids as $skill_id) - { - $skills->addOption(new ilCheckboxOption(ilSkillTreeNode::_lookupTitle($skill_id), $skill_id)); - } - $form->addItem($skills); - } - - if($quota_sum) - { - include_once "Services/DiskQuota/classes/class.ilDiskQuotaHandler.php"; - if(!ilDiskQuotaHandler::isUploadPossible($quota_sum)) - { - ilUtil::sendFailure($this->lng->txt("prtf_template_import_quota_failure"), true); - $this->ctrl->redirect($this, "create"); - } - } - - // no dialog needed, go ahead - if(!$has_form_content) - { - return; - } - - $form->setTitle($this->lng->txt("prtf_creation_mode").": ".$this->lng->txt("prtf_creation_mode_template")); - $form->addCommandButton("createPortfolioFromTemplateProcess", $this->lng->txt("continue")); - $form->addCommandButton("toRepository", $this->lng->txt("cancel")); - - return $form; - } - - protected function createPortfolioFromTemplateProcess($a_process_form = true) - { - $ilSetting = $this->settings; - $ilUser = $this->user; - $ilAccess = $this->access; - - $title = trim($_REQUEST["pt"]); - $prtt_id = (int)$_REQUEST["prtt"]; - - // valid template? - include_once "Modules/Portfolio/classes/class.ilObjPortfolioTemplate.php"; - $templates = array_keys(ilObjPortfolioTemplate::getAvailablePortfolioTemplates()); - if(!sizeof($templates) || !in_array($prtt_id, $templates)) - { - $this->toRepository(); - } - unset($templates); - - // build page recipe (aka import form values) - $recipe = null; - if($a_process_form) - { - $this->ctrl->setParameter($this, "prtt", $prtt_id); - - $form = $this->initCreatePortfolioFromTemplateForm($prtt_id, $title); - if($form->checkInput()) - { - include_once "Modules/Portfolio/classes/class.ilPortfolioTemplatePage.php"; - foreach(ilPortfolioTemplatePage::getAllPortfolioPages($prtt_id) as $page) - { - switch($page["type"]) - { - case ilPortfolioTemplatePage::TYPE_BLOG_TEMPLATE: - if(!$ilSetting->get('disable_wsp_blogs')) - { - $field_id = "blog_".$page["id"]; - switch($form->getInput($field_id)) - { - case "blog_create": - $recipe[$page["id"]] = array("blog", "create", - trim($form->getInput($field_id."_create_title"))); - break; - - case "blog_resuse": - $recipe[$page["id"]] = array("blog", "reuse", - (int)$form->getInput($field_id."_reuse_blog")); - break; - - case "blog_ignore": - $recipe[$page["id"]] = array("blog", "ignore"); - break; - } - } - break; - } - } - - $recipe["skills"] = (array)$form->getInput("skill_ids"); - } - else - { - $form->setValuesByPost(); - return $this->createPortfolioFromTemplate($form); - } - } - - $source = new ilObjPortfolioTemplate($prtt_id, false); - - // create portfolio - include_once "Modules/Portfolio/classes/class.ilObjPortfolio.php"; - $target = new ilObjPortfolio(); - $target->setTitle($title); - $target->create(); - $target_id = $target->getId(); - - $source->clonePagesAndSettings($source, $target, $recipe); - - // link portfolio to exercise assignment - $this->linkPortfolioToAssignment($target_id); - - ilUtil::sendSuccess($this->lng->txt("prtf_portfolio_created_from_template"), true); - $this->ctrl->setParameter($this, "prt_id", $target_id); - $this->ctrl->redirect($this, "preview"); - } - - /** - * Create portfolio template direct - */ - protected function createFromTemplateDirect($title = "") - { - $prtt_id = (int)$_REQUEST["prtt_pre"]; - if ($title == "") - { - $title = ilObject::_lookupTitle($prtt_id); - } - - // valid template? - include_once "Modules/Portfolio/classes/class.ilObjPortfolioTemplate.php"; - $templates = array_keys(ilObjPortfolioTemplate::getAvailablePortfolioTemplates()); - if(!sizeof($templates) || !in_array($prtt_id, $templates)) - { - $this->toRepository(); - } - unset($templates); - - $source = new ilObjPortfolioTemplate($prtt_id, false); - - // create portfolio - include_once "Modules/Portfolio/classes/class.ilObjPortfolio.php"; - $target = new ilObjPortfolio(); - $target->setTitle($title); - $target->create(); - $target_id = $target->getId(); - - $source->clonePagesAndSettings($source, $target, null, true); - - // link portfolio to exercise assignment - //$this->linkPortfolioToAssignment($target_id); - - ilUtil::sendSuccess($this->lng->txt("prtf_portfolio_created_from_template"), true); - $this->ctrl->setParameter($this, "prt_id", $target_id); - $this->ctrl->redirect($this, "preview"); - } - - - public static function _goto($a_target) - { - $id = explode("_", $a_target); - - $_GET["baseClass"] = "ilsharedresourceGUI"; - $_GET["prt_id"] = $id[0]; - if(sizeof($id) == 2) - { - $_GET["gtp"] = $id[1]; - } - - include("ilias.php"); - exit; - } - - public function createPortfolioFromAssignment() - { - $ilUser = $this->user; - $ilSetting = $this->settings; - - include_once "Modules/Portfolio/classes/class.ilObjPortfolioTemplate.php"; - include_once "Modules/Portfolio/classes/class.ilPortfolioTemplatePage.php"; - include_once "Modules/Portfolio/classes/class.ilObjPortfolio.php"; - - $title = trim($_REQUEST["pt"]); - $prtt_id = (int)$_REQUEST["prtt"]; - - // get assignment template - $ass_template_id = 0; - if ((int)$_REQUEST["ass_id"] > 0) - { - include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); - $ass = new ilExAssignment((int)$_REQUEST["ass_id"]); - $ass_template_id = ilObject::_lookupObjectId($ass->getPortfolioTemplateId()); - } - - if($prtt_id > 0) - { - $templates = array_keys(ilObjPortfolioTemplate::getAvailablePortfolioTemplates()); - if(!sizeof($templates) || !in_array($prtt_id, $templates)) - { - if ($ass_template_id != $prtt_id) - { - $this->toRepository(); - } - } - - //quota manipulation - include_once "Services/WebDAV/classes/class.ilDiskQuotaActivationChecker.php"; - $check_quota = (int)ilDiskQuotaActivationChecker::_isPersonalWorkspaceActive(); - $quota_sum = 0; - - //skills manipulation - include_once "Services/Skill/classes/class.ilPersonalSkill.php"; - $pskills = array_keys(ilPersonalSkill::getSelectedUserSkills($ilUser->getId())); - $skill_ids = array(); - - $recipe = array(); - foreach(ilPortfolioTemplatePage::getAllPortfolioPages($prtt_id) as $page) - { - switch($page["type"]) - { - case ilPortfolioTemplatePage::TYPE_BLOG_TEMPLATE: - if(!$ilSetting->get('disable_wsp_blogs')) - { - $recipe[$page["id"]] = array("blog", "create", $page['title']); - } - break; - case ilPortfolioTemplatePage::TYPE_PAGE: - $source_page = new ilPortfolioTemplatePage($page["id"]); - $source_page->buildDom(true); - if($check_quota) - { - $quota_sum += $source_page->getPageDiskSize(); - } - $skill_ids = $this->getSkillsToPortfolioAssignment($pskills, $skill_ids, $source_page); - break; - } - } - - if($quota_sum) - { - include_once "Services/DiskQuota/classes/class.ilDiskQuotaHandler.php"; - if(!ilDiskQuotaHandler::isUploadPossible($quota_sum)) - { - ilUtil::sendFailure($this->lng->txt("prtf_template_import_quota_failure"), true); - $this->ctrl->redirect($this, "create"); - } - } - - if($skill_ids) - { - $recipe["skills"] = $skill_ids; - } - - } - - // create portfolio - $target = new ilObjPortfolio(); - $target->setTitle($title); - $target->create(); - $target_id = $target->getId(); - - if($prtt_id) - { - $source = new ilObjPortfolioTemplate($prtt_id, false); - $source->clonePagesAndSettings($source, $target,$recipe); - } - - // link portfolio to exercise assignment - $this->linkPortfolioToAssignment($target_id); - - $this->ctrl->setParameter($this, "prt_id", $target_id); - if($prtt_id) - { - ilUtil::sendSuccess($this->lng->txt("prtf_portfolio_created_from_template"), true); - $this->ctrl->redirect($this, "preview"); - } - else - { - ilUtil::sendSuccess($this->lng->txt("prtf_portfolio_created"), true); - $this->ctrl->redirect($this, "view"); - } - } - - function linkPortfolioToAssignment($a_target_id) - { - $ilAccess = $this->access; - $ilUser = $this->user; - - $exc_ref_id = (int)$_REQUEST["exc_id"]; - $ass_id = (int)$_REQUEST["ass_id"]; - - if($exc_ref_id && - $ass_id && - $ilAccess->checkAccess("read", "", $exc_ref_id)) - { - include_once "Modules/Exercise/classes/class.ilObjExercise.php"; - include_once "Modules/Exercise/classes/class.ilExAssignment.php"; - $exc = new ilObjExercise($exc_ref_id); - $ass = new ilExAssignment($ass_id); - if($ass->getExerciseId() == $exc->getId() && - $ass->getType() == ilExAssignment::TYPE_PORTFOLIO) - { - // #16205 - include_once "Modules/Exercise/classes/class.ilExSubmission.php"; - $sub = new ilExSubmission($ass, $ilUser->getId()); - $sub->addResourceObject($a_target_id); - } - } - } - - /** - * @param array a_pskills - * @param array a_skill_ids - * @param ilPortfolioTemplatePage $a_source_page - * @return array - */ - function getSkillsToPortfolioAssignment($a_pskills, $a_skill_ids, $a_source_page) - { - $dom = $a_source_page->getDom(); - if($dom instanceof php4DOMDocument) - { - $dom = $dom->myDOMDocument; - } - $xpath = new DOMXPath($dom); - $nodes = $xpath->query("//PageContent/Skills"); - foreach($nodes as $node) - { - $skill_id = $node->getAttribute("Id"); - if(!in_array($skill_id, $a_pskills)) - { - $a_skill_ids[] = $skill_id; - } - } - unset($nodes); - unset($xpath); - unset($dom); - - return $a_skill_ids; - - } - - /** - * Export PDF selection - * - * @param - */ - function exportPDFSelection() - { - global $DIC; - - $tpl = $DIC["tpl"]; - - $form = $this->initPDFSelectionForm(); - - $tpl->setContent($form->getHTML()); - - } - - /** - * Init print view selection form. - */ - public function initPDFSelectionForm() - { - global $DIC; - - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $tabs = $DIC->tabs(); - - $tabs->clearTargets(); - $tabs->setBackTarget($lng->txt("back"), $ilCtrl->getLinkTarget($this, "view")); - - $pages = ilPortfolioPage::getAllPortfolioPages($this->object->getId()); - - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - - // because of PDF export - $form->setPreventDoubleSubmission(false); - - // declaration of authorship - if ($this->declaration_authorship->getForUser($this->user) != "") - { - $cb = new ilCheckboxInputGUI($this->lng->txt("prtf_decl_authorship"), "decl_author"); - $cb->setInfo($this->declaration_authorship->getForUser($this->user)); - $form->addItem($cb); - } - - // signature - $cb = new ilCheckboxInputGUI($this->lng->txt("prtf_signature"), "signature"); - $cb->setInfo($this->lng->txt("prtf_signature_info")); - $form->addItem($cb); - - - // selection type - $radg = new ilRadioGroupInputGUI($lng->txt("prtf_print_selection"), "sel_type"); - $radg->setValue("all_pages"); - $op2 = new ilRadioOption($lng->txt("prtf_all_pages"), "all_pages"); - $radg->addOption($op2); - $op3= new ilRadioOption($lng->txt("prtf_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) - { - if ($p["type"] != ilPortfolioPage::TYPE_BLOG) - { - $nl->addListNode($p["id"], $p["title"], 0, false, false, - ilUtil::getImagePath("icon_pg.svg"), $lng->txt("page")); - } - else - { - $nl->addListNode($p["id"], $lng->txt("obj_blog").": ".ilObject::_lookupTitle($p["title"]), 0, false, false, - ilUtil::getImagePath("icon_blog.svg"), $lng->txt("obj_blog")); - $pages2 = ilBlogPosting::getAllPostings($p["title"]); - foreach ($pages2 as $p2) - { - $nl->addListNode("b".$p2["id"], $p2["title"], $p["id"], false, false, - ilUtil::getImagePath("icon_pg.svg"), $lng->txt("page")); - } - } - } - - $form->addItem($radg); - - $form->addCommandButton("exportPDF", $lng->txt("prtf_pdf")); - if (DEVMODE == "1") - { - $form->addCommandButton("exportPDFDev", $lng->txt("prtf_pdf")." (DEV)"); - } - - $form->setTitle($lng->txt("prtf_print_options")); - $form->setFormAction($ilCtrl->getFormAction($this, "exportPDF")); - - return $form; - } - - /** - * @throws ilWACException - */ - public function exportPDFDev() - { - $this->exportPDF(true); - } - - /** - * @param bool $a_dev_mode - * @throws ilWACException - */ - public function exportPDF($a_dev_mode = false) - { - require_once 'Services/WebAccessChecker/classes/class.ilWACSignedPath.php'; - ilWACSignedPath::setTokenMaxLifetimeInSeconds(180); - - // prepare generation before contents are processed (for mathjax) - ilPDFGeneratorUtils::prepareGenerationRequest("Portfolio", "ContentExport"); - - $html = $this->printView(true); - - // :TODO: fixing css dummy parameters - $html = preg_replace("/\?dummy\=[0-9]+/", "", $html); - $html = preg_replace("/\?vers\=[0-9A-Za-z\-]+/", "", $html); - - $html = preg_replace("/src=\"\\.\\//ims", "src=\"" . ILIAS_HTTP_PATH . "/", $html); - $html = preg_replace("/href=\"\\.\\//ims", "href=\"" . ILIAS_HTTP_PATH . "/", $html); - - - if ($a_dev_mode) - { - echo $html; - exit; - } - - //$html = str_replace("&", "&", $html); - - $pdf_factory = new ilHtmlToPdfTransformerFactory(); - $pdf_factory->deliverPDFFromHTMLString($html, "portfolio.pdf", ilHtmlToPdfTransformerFactory::PDF_OUTPUT_DOWNLOAD, "Portfolio", "ContentExport"); - } - - public function printView($a_pdf_export = false) - { - global $tpl; - - $lng = $this->lng; - - $pages = ilPortfolioPage::getAllPortfolioPages($this->object->getId()); - - - $tpl = new ilTemplate("tpl.main.html", true, true); - - $tpl->setBodyClass("ilPrtfPdfBody"); - - $tpl->setCurrentBlock("AdditionalStyle"); - $tpl->setVariable("LOCATION_ADDITIONAL_STYLESHEET", ilUtil::getStyleSheetLocation("filesystem")); - $tpl->parseCurrentBlock(); - - $tpl->setCurrentBlock("ContentStyle"); - $tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->object->getStyleSheetId(), false)); - $tpl->parseCurrentBlock(); - - $tpl->setVariable("LOCATION_STYLESHEET", ilObjStyleSheet::getContentPrintStyle()); - //$this->setContentStyleSheet($tpl); - - // syntax style - $tpl->setCurrentBlock("SyntaxStyle"); - $tpl->setVariable("LOCATION_SYNTAX_STYLESHEET", - ilObjStyleSheet::getSyntaxStylePath()); - $tpl->parseCurrentBlock(); - - - include_once("./Modules/Portfolio/classes/class.ilPortfolioPageGUI.php"); - - $page_content = ""; - - // cover page - $cover_tpl = new ilTemplate("tpl.prtf_cover.html", true, true, "Modules/Portfolio"); - foreach ($pages as $page) - { - if ($page["type"] != ilPortfolioPage::TYPE_BLOG) - { - if ($_POST["sel_type"] == "selection" && (!is_array($_POST["obj_id"]) || !in_array($page["id"], $_POST["obj_id"]))) - { - continue; - } - $cover_tpl->setCurrentBlock("content_item"); - $cover_tpl->setVariable("ITEM_TITLE", $page["title"]); - $cover_tpl->parseCurrentBlock(); - } - else - { - $cover_tpl->setCurrentBlock("content_item"); - $cover_tpl->setVariable("ITEM_TITLE", $lng->txt("obj_blog").": ".ilObject::_lookupTitle($page["title"])); - $cover_tpl->parseCurrentBlock(); - } - } - - if ($_POST["signature"]) - { - $cover_tpl->setCurrentBlock("signature"); - $cover_tpl->setVariable("TXT_SIGNATURE", $lng->txt("prtf_signature_date")); - $cover_tpl->parseCurrentBlock(); - } - - if ($_POST["decl_author"]) - { - $cover_tpl->setCurrentBlock("decl_author"); - $cover_tpl->setVariable("TXT_DECL_AUTHOR", - nl2br($this->declaration_authorship->getForUser($this->user))); - $cover_tpl->parseCurrentBlock(); - } - - $cover_tpl->setVariable("PORTFOLIO_TITLE", $this->object->getTitle()); - $cover_tpl->setVariable("PORTFOLIO_ICON", ilUtil::getImagePath("icon_prtf.svg")); - - $cover_tpl->setVariable("TXT_AUTHOR", $lng->txt("prtf_author")); - $cover_tpl->setVariable("TXT_LINK", $lng->txt("prtf_link")); - $cover_tpl->setVariable("TXT_DATE", $lng->txt("prtf_date_of_print")); - - $author = ilObjUser::_lookupName($this->object->getOwner()); - $author_str = $author["firstname"]." ".$author["lastname"]; - $cover_tpl->setVariable("AUTHOR", $author_str); - - include_once('./Services/Link/classes/class.ilLink.php'); - $href = ilLink::_getStaticLink($this->object->getId(), "prtf"); - $cover_tpl->setVariable("LINK", $href); - - ilDatePresentation::setUseRelativeDates(false); - $date_str = ilDatePresentation::formatDate(new ilDate(date("Y-m-d"), IL_CAL_DATE)); - $cover_tpl->setVariable("DATE", $date_str); - - $page_content .= $cover_tpl->get(); - $page_content .= '

'; - - $page_head_tpl = new ilTemplate("tpl.prtf_page_head.html", true, true, "Modules/Portfolio"); - $page_head_tpl->setVariable("AUTHOR", $author_str); - $page_head_tpl->setVariable("DATE", $date_str); - $page_head_str = $page_head_tpl->get(); - - foreach ($pages as $page) - { - if ($page["type"] != ilPortfolioPage::TYPE_BLOG) - { - if ($_POST["sel_type"] == "selection" && (!is_array($_POST["obj_id"]) || !in_array($page["id"], $_POST["obj_id"]))) - { - continue; - } - - $page_gui = new ilPortfolioPageGUI($this->object->getId(), $page["id"]); - $page_gui->setOutputMode("print"); - $page_gui->setPresentationTitle($page["title"]); - $html = $this->ctrl->getHTML($page_gui); - $page_content .= $page_head_str.$html; - - if ($a_pdf_export) - { - $page_content .= '

'; - } - } - else - { - $pages2 = ilBlogPosting::getAllPostings($page["title"]); - foreach ($pages2 as $p2) - { - if ($_POST["sel_type"] == "selection" && (!is_array($_POST["obj_id"]) || !in_array("b".$p2["id"], $_POST["obj_id"]))) - { - continue; - } - $page_gui = new ilBlogPostingGUI(0, null, $p2["id"]); - $page_gui->setFileDownloadLink("#"); - $page_gui->setFullscreenLink("#"); - $page_gui->setSourcecodeDownloadScript("#"); - $page_gui->setOutputMode("print"); - $page_content .= $page_head_str.$page_gui->showPage(ilObject::_lookupTitle($page["title"]).": ".$page_gui->getBlogPosting()->getTitle()); - - if ($a_pdf_export) - { - $page_content .= '

'; - } - } - } - } - - $page_content = '
'.$page_content.'
'; - - if(!$a_pdf_export) - { - $page_content .= ''; - } - - $tpl->setVariable("CONTENT", $page_content); - - if(!$a_pdf_export) - { - $tpl->show(false); - exit; - } - else - { - $tpl->fillJavaScriptFiles(); - $ret = $tpl->get("DEFAULT", false, false, false, true, false, false); - return $ret; - } - } - - /** - * Get offline message for sharing tab - * - * @return string - */ - protected function getOfflineMessage() - { - $ui = $this->ui; - $lng = $this->lng; - $ctrl = $this->ctrl; - - if (!$this->object->isOnline()) - { - $f = $ui->factory(); - $renderer = $ui->renderer(); - - $buttons = [$f->button()->standard($lng->txt("prtf_set_online"), - $ctrl->getLinkTarget($this, "setOnlineAndShare"))]; - - return $renderer->render($f->messageBox()->info($lng->txt("prtf_no_offline_share_info")) - ->withButtons($buttons)); - } - return ""; - } - - /** - * Set online and switch to share screen - */ - protected function setOnlineAndShare() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if (ilObjPortfolio::_lookupOwner($this->object->getId()) == $this->user_id) - { - $this->object->setOnline(true); - $this->object->update(); - ilUtil::sendSuccess($lng->txt("prtf_has_been_set_online"), true); - } - $ilCtrl->redirectByClass("ilworkspaceaccessgui", ""); - } - -} -?> \ No newline at end of file + '; + } + + $tpl->setVariable("CONTENT", $page_content); + + if (!$a_pdf_export) { + $tpl->show(false); + exit; + } else { + $tpl->fillJavaScriptFiles(); + $ret = $tpl->get("DEFAULT", false, false, false, true, false, false); + return $ret; + } + } + + /** + * Get offline message for sharing tab + * + * @return string + */ + protected function getOfflineMessage() + { + $ui = $this->ui; + $lng = $this->lng; + $ctrl = $this->ctrl; + + if (!$this->object->isOnline()) { + $f = $ui->factory(); + $renderer = $ui->renderer(); + + $buttons = [$f->button()->standard( + $lng->txt("prtf_set_online"), + $ctrl->getLinkTarget($this, "setOnlineAndShare") + )]; + + return $renderer->render($f->messageBox()->info($lng->txt("prtf_no_offline_share_info")) + ->withButtons($buttons)); + } + return ""; + } + + /** + * Set online and switch to share screen + */ + protected function setOnlineAndShare() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if (ilObjPortfolio::_lookupOwner($this->object->getId()) == $this->user_id) { + $this->object->setOnline(true); + $this->object->update(); + ilUtil::sendSuccess($lng->txt("prtf_has_been_set_online"), true); + } + $ilCtrl->redirectByClass("ilworkspaceaccessgui", ""); + } +} diff --git a/Modules/Portfolio/classes/class.ilObjPortfolioTemplate.php b/Modules/Portfolio/classes/class.ilObjPortfolioTemplate.php index bfba538db8c0360c72ee6211bb2d1579fe99c252..10181ac4bc75446eb27371447df350fed10d6208 100644 --- a/Modules/Portfolio/classes/class.ilObjPortfolioTemplate.php +++ b/Modules/Portfolio/classes/class.ilObjPortfolioTemplate.php @@ -1,221 +1,203 @@ - - * @version $Id$ - * - * @ingroup ModulesPortfolio - */ -class ilObjPortfolioTemplate extends ilObjPortfolioBase -{ - protected $activation_limited; // [bool] - protected $activation_visibility; // [bool] - protected $activation_starting_time; // [integer] - protected $activation_ending_time; // [integer] - - public function initType() - { - $this->type = "prtt"; - } - - protected function doRead() - { - parent::doRead(); - - if($this->ref_id) - { - include_once "./Services/Object/classes/class.ilObjectActivation.php"; - $activation = ilObjectActivation::getItem($this->ref_id); - switch($activation["timing_type"]) - { - case ilObjectActivation::TIMINGS_ACTIVATION: - $this->setActivationLimited(true); - $this->setActivationStartDate($activation["timing_start"]); - $this->setActivationEndDate($activation["timing_end"]); - $this->setActivationVisibility($activation["visible"]); - break; - - default: - $this->setActivationLimited(false); - break; - } - } - } - - protected function doCreate() - { - parent::doCreate(); - $this->updateActivation(); - } - - protected function doUpdate() - { - parent::doUpdate(); - $this->updateActivation(); - } - - protected function deleteAllPages() - { - // delete pages - include_once "Modules/Portfolio/classes/class.ilPortfolioTemplatePage.php"; - $pages = ilPortfolioTemplatePage::getAllPortfolioPages($this->id); - foreach($pages as $page) - { - $page_obj = new ilPortfolioTemplatePage($page["id"]); - $page_obj->setPortfolioId($this->id); - $page_obj->delete(); - } - } - - protected function doCloneObject($new_obj, $a_target_id, $a_copy_id = null) - { - //copy online status if object is not the root copy object - $cp_options = ilCopyWizardOptions::_getInstance($a_copy_id); - - if(!$cp_options->isRootNode($this->getRefId())) - { - $new_obj->setOnline($this->isOnline()); - } - - self::cloneBasics($this, $new_obj); - - // copy pages - include_once "Modules/Portfolio/classes/class.ilPortfolioTemplatePage.php"; - foreach(ilPortfolioPage::getAllPortfolioPages($this->getId()) as $page) - { - // see ilObjWiki::cloneObject(); - - $page = new ilPortfolioTemplatePage($page["id"]); - - $new_page = new ilPortfolioTemplatePage(); - $new_page->setPortfolioId($new_obj->getId()); - $new_page->setTitle($page->getTitle()); - $new_page->setType($page->getType()); - $new_page->setOrderNr($page->getOrderNr()); - $new_page->create(); - - $page->copy($new_page->getId(), "", 0, true); - } - } - - - // - // ACTIVATION - // - - protected function updateActivation() - { - // moved activation to ilObjectActivation - if($this->ref_id) - { - include_once "./Services/Object/classes/class.ilObjectActivation.php"; - ilObjectActivation::getItem($this->ref_id); - - $item = new ilObjectActivation; - if(!$this->isActivationLimited()) - { - $item->setTimingType(ilObjectActivation::TIMINGS_DEACTIVATED); - } - else - { - $item->setTimingType(ilObjectActivation::TIMINGS_ACTIVATION); - $item->setTimingStart($this->getActivationStartDate()); - $item->setTimingEnd($this->getActivationEndDate()); - $item->toggleVisible($this->getActivationVisibility()); - } - - $item->update($this->ref_id); - } - } - - public function isActivationLimited() - { - return (bool)$this->activation_limited; - } - - public function setActivationLimited($a_value) - { - $this->activation_limited = (bool)$a_value; - } - - public function setActivationVisibility($a_value) - { - $this->activation_visibility = (bool) $a_value; - } - - public function getActivationVisibility() - { - return $this->activation_visibility; - } - - public function setActivationStartDate($starting_time = NULL) - { - $this->activation_starting_time = $starting_time; - } - - public function setActivationEndDate($ending_time = NULL) - { - $this->activation_ending_time = $ending_time; - } - - public function getActivationStartDate() - { - return (strlen($this->activation_starting_time)) ? $this->activation_starting_time : NULL; - } - - public function getActivationEndDate() - { - return (strlen($this->activation_ending_time)) ? $this->activation_ending_time : NULL; - } - - - // - // HELPER - // - - public static function getAvailablePortfolioTemplates($a_permission = "read") - { - global $DIC; +user(); - $ilAccess = $DIC->access(); - - $res = array(); - - foreach(ilObject::_getObjectsByType("prtt") as $obj) - { - $has_permission = false; - - if($obj["owner"] == $ilUser->getId()) - { - $has_permission = true; - } - else - { - foreach(ilObject::_getAllReferences($obj["obj_id"]) as $ref_id) - { - if($ilAccess->checkAccess($a_permission, "", $ref_id)) - { - $has_permission = true; - break; - } - } - } - - if($has_permission) - { - $res[$obj["obj_id"]] = $obj["title"]; - } - } - - asort($res); - return $res; - } -} - -?> \ No newline at end of file +require_once "Modules/Portfolio/classes/class.ilObjPortfolioBase.php"; + +/** + * Portfolio + * + * @author Jörg Lützenkirchen + * @version $Id$ + * + * @ingroup ModulesPortfolio + */ +class ilObjPortfolioTemplate extends ilObjPortfolioBase +{ + protected $activation_limited; // [bool] + protected $activation_visibility; // [bool] + protected $activation_starting_time; // [integer] + protected $activation_ending_time; // [integer] + + public function initType() + { + $this->type = "prtt"; + } + + protected function doRead() + { + parent::doRead(); + + if ($this->ref_id) { + include_once "./Services/Object/classes/class.ilObjectActivation.php"; + $activation = ilObjectActivation::getItem($this->ref_id); + switch ($activation["timing_type"]) { + case ilObjectActivation::TIMINGS_ACTIVATION: + $this->setActivationLimited(true); + $this->setActivationStartDate($activation["timing_start"]); + $this->setActivationEndDate($activation["timing_end"]); + $this->setActivationVisibility($activation["visible"]); + break; + + default: + $this->setActivationLimited(false); + break; + } + } + } + + protected function doCreate() + { + parent::doCreate(); + $this->updateActivation(); + } + + protected function doUpdate() + { + parent::doUpdate(); + $this->updateActivation(); + } + + protected function deleteAllPages() + { + // delete pages + include_once "Modules/Portfolio/classes/class.ilPortfolioTemplatePage.php"; + $pages = ilPortfolioTemplatePage::getAllPortfolioPages($this->id); + foreach ($pages as $page) { + $page_obj = new ilPortfolioTemplatePage($page["id"]); + $page_obj->setPortfolioId($this->id); + $page_obj->delete(); + } + } + + protected function doCloneObject($new_obj, $a_target_id, $a_copy_id = null) + { + //copy online status if object is not the root copy object + $cp_options = ilCopyWizardOptions::_getInstance($a_copy_id); + + if (!$cp_options->isRootNode($this->getRefId())) { + $new_obj->setOnline($this->isOnline()); + } + + self::cloneBasics($this, $new_obj); + + // copy pages + include_once "Modules/Portfolio/classes/class.ilPortfolioTemplatePage.php"; + foreach (ilPortfolioPage::getAllPortfolioPages($this->getId()) as $page) { + // see ilObjWiki::cloneObject(); + + $page = new ilPortfolioTemplatePage($page["id"]); + + $new_page = new ilPortfolioTemplatePage(); + $new_page->setPortfolioId($new_obj->getId()); + $new_page->setTitle($page->getTitle()); + $new_page->setType($page->getType()); + $new_page->setOrderNr($page->getOrderNr()); + $new_page->create(); + + $page->copy($new_page->getId(), "", 0, true); + } + } + + + // + // ACTIVATION + // + + protected function updateActivation() + { + // moved activation to ilObjectActivation + if ($this->ref_id) { + include_once "./Services/Object/classes/class.ilObjectActivation.php"; + ilObjectActivation::getItem($this->ref_id); + + $item = new ilObjectActivation; + if (!$this->isActivationLimited()) { + $item->setTimingType(ilObjectActivation::TIMINGS_DEACTIVATED); + } else { + $item->setTimingType(ilObjectActivation::TIMINGS_ACTIVATION); + $item->setTimingStart($this->getActivationStartDate()); + $item->setTimingEnd($this->getActivationEndDate()); + $item->toggleVisible($this->getActivationVisibility()); + } + + $item->update($this->ref_id); + } + } + + public function isActivationLimited() + { + return (bool) $this->activation_limited; + } + + public function setActivationLimited($a_value) + { + $this->activation_limited = (bool) $a_value; + } + + public function setActivationVisibility($a_value) + { + $this->activation_visibility = (bool) $a_value; + } + + public function getActivationVisibility() + { + return $this->activation_visibility; + } + + public function setActivationStartDate($starting_time = null) + { + $this->activation_starting_time = $starting_time; + } + + public function setActivationEndDate($ending_time = null) + { + $this->activation_ending_time = $ending_time; + } + + public function getActivationStartDate() + { + return (strlen($this->activation_starting_time)) ? $this->activation_starting_time : null; + } + + public function getActivationEndDate() + { + return (strlen($this->activation_ending_time)) ? $this->activation_ending_time : null; + } + + + // + // HELPER + // + + public static function getAvailablePortfolioTemplates($a_permission = "read") + { + global $DIC; + + $ilUser = $DIC->user(); + $ilAccess = $DIC->access(); + + $res = array(); + + foreach (ilObject::_getObjectsByType("prtt") as $obj) { + $has_permission = false; + + if ($obj["owner"] == $ilUser->getId()) { + $has_permission = true; + } else { + foreach (ilObject::_getAllReferences($obj["obj_id"]) as $ref_id) { + if ($ilAccess->checkAccess($a_permission, "", $ref_id)) { + $has_permission = true; + break; + } + } + } + + if ($has_permission) { + $res[$obj["obj_id"]] = $obj["title"]; + } + } + + asort($res); + return $res; + } +} diff --git a/Modules/Portfolio/classes/class.ilObjPortfolioTemplateAccess.php b/Modules/Portfolio/classes/class.ilObjPortfolioTemplateAccess.php index 69c677e4e1fbd20ec2663d6ef6840d64abe11955..c694128cf26e32d413acc24318ed126a20714850 100644 --- a/Modules/Portfolio/classes/class.ilObjPortfolioTemplateAccess.php +++ b/Modules/Portfolio/classes/class.ilObjPortfolioTemplateAccess.php @@ -1,145 +1,132 @@ - -* @version $Id: class.ilObjRootFolderAccess.php 15678 2008-01-06 20:40:55Z akill $ -* -*/ -class ilObjPortfolioTemplateAccess extends ilObjectAccess -{ - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilAccessHandler - */ - protected $access; - - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->user = $DIC->user(); - $this->lng = $DIC->language(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->access = $DIC->access(); - } - - public static function _getCommands() - { - $commands = array - ( - array("permission" => "read", "cmd" => "preview", "lang_var" => "preview", "default" => true), - array("permission" => "write", "cmd" => "view", "lang_var" => "edit"), - array("permission" => "read", "cmd" => "createfromtemplate", "lang_var" => "prtf_create_portfolio_from_template"), - // array("permission" => "write", "cmd" => "export", "lang_var" => "export_html") - ); - - return $commands; - } - - public function _checkAccess($a_cmd, $a_permission, $a_ref_id, $a_obj_id, $a_user_id = "") - { - $ilUser = $this->user; - $lng = $this->lng; - $rbacsystem = $this->rbacsystem; - $ilAccess = $this->access; - - if ($a_user_id == "") - { - $a_user_id = $ilUser->getId(); - } - - switch ($a_cmd) - { - case "view": - if(!self::_lookupOnline($a_obj_id) - && !$rbacsystem->checkAccessOfUser($a_user_id,'write',$a_ref_id)) - { - $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("offline")); - return false; - } - break; - - // for permission query feature - case "infoScreen": - if(!self::_lookupOnline($a_obj_id)) - { - $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("offline")); - } - else - { - $ilAccess->addInfoItem(IL_STATUS_MESSAGE, $lng->txt("online")); - } - break; - - } - - switch($a_permission) - { - case "read": - case "visible": - if (!self::_lookupOnline($a_obj_id) && - (!$rbacsystem->checkAccessOfUser($a_user_id, 'write', $a_ref_id))) - { - $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("offline")); - return false; - } - break; - } - - return true; - } - - public static function _lookupOnline($a_id) - { - include_once "Modules/Portfolio/classes/class.ilObjPortfolioTemplate.php"; - return ilObjPortfolioTemplate::lookupOnline($a_id); - } - - /** - * check whether goto script will succeed - */ - public static function _checkGoto($a_target) - { - global $DIC; - - $ilAccess = $DIC->access(); - - $t_arr = explode("_", $a_target); - - if ($t_arr[0] != "prtt" || ((int) $t_arr[1]) <= 0) - { - return false; - } - - if ($ilAccess->checkAccess("read", "", $t_arr[1])) - { - return true; - } - return false; - } -} - -?> \ No newline at end of file + +* @version $Id: class.ilObjRootFolderAccess.php 15678 2008-01-06 20:40:55Z akill $ +* +*/ +class ilObjPortfolioTemplateAccess extends ilObjectAccess +{ + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilAccessHandler + */ + protected $access; + + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->user = $DIC->user(); + $this->lng = $DIC->language(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->access = $DIC->access(); + } + + public static function _getCommands() + { + $commands = array( + array("permission" => "read", "cmd" => "preview", "lang_var" => "preview", "default" => true), + array("permission" => "write", "cmd" => "view", "lang_var" => "edit"), + array("permission" => "read", "cmd" => "createfromtemplate", "lang_var" => "prtf_create_portfolio_from_template"), + // array("permission" => "write", "cmd" => "export", "lang_var" => "export_html") + ); + + return $commands; + } + + public function _checkAccess($a_cmd, $a_permission, $a_ref_id, $a_obj_id, $a_user_id = "") + { + $ilUser = $this->user; + $lng = $this->lng; + $rbacsystem = $this->rbacsystem; + $ilAccess = $this->access; + + if ($a_user_id == "") { + $a_user_id = $ilUser->getId(); + } + + switch ($a_cmd) { + case "view": + if (!self::_lookupOnline($a_obj_id) + && !$rbacsystem->checkAccessOfUser($a_user_id, 'write', $a_ref_id)) { + $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("offline")); + return false; + } + break; + + // for permission query feature + case "infoScreen": + if (!self::_lookupOnline($a_obj_id)) { + $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("offline")); + } else { + $ilAccess->addInfoItem(IL_STATUS_MESSAGE, $lng->txt("online")); + } + break; + + } + + switch ($a_permission) { + case "read": + case "visible": + if (!self::_lookupOnline($a_obj_id) && + (!$rbacsystem->checkAccessOfUser($a_user_id, 'write', $a_ref_id))) { + $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("offline")); + return false; + } + break; + } + + return true; + } + + public static function _lookupOnline($a_id) + { + include_once "Modules/Portfolio/classes/class.ilObjPortfolioTemplate.php"; + return ilObjPortfolioTemplate::lookupOnline($a_id); + } + + /** + * check whether goto script will succeed + */ + public static function _checkGoto($a_target) + { + global $DIC; + + $ilAccess = $DIC->access(); + + $t_arr = explode("_", $a_target); + + if ($t_arr[0] != "prtt" || ((int) $t_arr[1]) <= 0) { + return false; + } + + if ($ilAccess->checkAccess("read", "", $t_arr[1])) { + return true; + } + return false; + } +} diff --git a/Modules/Portfolio/classes/class.ilObjPortfolioTemplateGUI.php b/Modules/Portfolio/classes/class.ilObjPortfolioTemplateGUI.php index 138be6927f8a2579cef0d1b47cb958f2de9d06c7..79991b32e64d58542423d5fe63479b0f093306d6 100644 --- a/Modules/Portfolio/classes/class.ilObjPortfolioTemplateGUI.php +++ b/Modules/Portfolio/classes/class.ilObjPortfolioTemplateGUI.php @@ -1,563 +1,547 @@ - - * @version $Id$ - * - * @ilCtrl_Calls ilObjPortfolioTemplateGUI: ilPortfolioTemplatePageGUI, ilPageObjectGUI, ilNoteGUI - * @ilCtrl_Calls ilObjPortfolioTemplateGUI: ilObjectCopyGUI, ilInfoScreenGUI, ilCommonActionDispatcherGUI - * @ilCtrl_Calls ilObjPortfolioTemplateGUI: ilPermissionGUI, ilExportGUI, ilObjStyleSheetGUI - * - * @ingroup ModulesPortfolio - */ -class ilObjPortfolioTemplateGUI extends ilObjPortfolioBaseGUI -{ - /** - * @var ilNavigationHistory - */ - protected $nav_history; - - /** - * @var ilHelpGUI - */ - protected $help; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - - /** - * Constructor - */ - function __construct($a_id = 0, $a_id_type = self::REPOSITORY_NODE_ID, $a_parent_node_id = 0) - { - parent::__construct($a_id, $a_id_type, $a_parent_node_id); - global $DIC; - - $this->nav_history = $DIC["ilNavigationHistory"]; - $this->help = $DIC["ilHelp"]; - $this->tabs = $DIC->tabs(); - $this->toolbar = $DIC->toolbar(); - $this->user = $DIC->user(); - } - - public function getType() - { - return "prtt"; - } - - public function executeCommand() - { - $ilNavigationHistory = $this->nav_history; - - // add entry to navigation history - if(!$this->getCreationMode() && - $this->getAccessHandler()->checkAccess("read", "", $this->node_id)) - { - $link = $this->ctrl->getLinkTarget($this, "view"); - $ilNavigationHistory->addItem($this->node_id, $link, "prtt"); - } - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd("view"); - - switch($next_class) - { - case 'ilportfoliotemplatepagegui': - $this->determinePageCall(); // has to be done before locator! - $this->prepareOutput(); - $this->handlePageCall($cmd); - break; - - case "ilnotegui"; - $this->preview(); - break; - - case "ilinfoscreengui": - $this->prepareOutput(); - $this->addHeaderAction("view"); - $this->infoScreenForward(); - break; - - case "ilcommonactiondispatchergui": - include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); - $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); - $this->ctrl->forwardCommand($gui); - break; - - case "ilpermissiongui": - $this->prepareOutput(); - $this->tabs_gui->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("prtt"); - $this->ctrl->forwardCommand($cp); - break; - - case 'ilexportgui': - $this->prepareOutput(); - $this->tabs_gui->activateTab("export"); - include_once("./Services/Export/classes/class.ilExportGUI.php"); - $exp_gui = new ilExportGUI($this); - $exp_gui->addFormat("xml"); - $this->ctrl->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" || $_GET["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; - - default: - $this->addHeaderAction($cmd); - return ilObject2GUI::executeCommand(); - } - } - - protected function setTabs() - { - $ilHelp = $this->help; - - $ilHelp->setScreenIdComponent("prtt"); - - if($this->checkPermissionBool("write")) - { - $this->tabs_gui->addTab("pages", - $this->lng->txt("content"), - $this->ctrl->getLinkTarget($this, "view")); - } - - if ($this->checkPermissionBool("read")) - { - $this->tabs_gui->addTab("id_info", - $this->lng->txt("info_short"), - $this->ctrl->getLinkTargetByClass(array("ilobjportfoliotemplategui", "ilinfoscreengui"), "showSummary")); - } - - if($this->checkPermissionBool("write")) - { - $this->tabs_gui->addTab("settings", - $this->lng->txt("settings"), - $this->ctrl->getLinkTarget($this, "edit")); - - $this->tabs_gui->addTab("export", - $this->lng->txt("export"), - $this->ctrl->getLinkTargetByClass("ilexportgui", "")); - } - - if ($this->checkPermissionBool("read")) - { - $this->tabs_gui->addNonTabbedLink("preview", - $this->lng->txt("user_profile_preview"), - $this->ctrl->getLinkTarget($this, "preview")); - } - - // will add permissions if needed - ilObject2GUI::setTabs(); - } - - /** - * 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; - $ilToolbar = $this->toolbar; - - $ilTabs->activateTab("id_info"); - - $this->checkPermission("visible"); - - if ($this->checkPermissionBool("read")) - { - $this->lng->loadLanguageModule("cntr"); - - include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; - $button = ilLinkButton::getInstance(); - $button->setPrimary(true); - $button->setCaption("prtf_create_portfolio_from_template"); - $button->setUrl($this->ctrl->getLinkTarget($this, "createfromtemplate")); - $ilToolbar->addButtonInstance($button); - } - - include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); - $info = new ilInfoScreenGUI($this); - - $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()); - - $this->ctrl->forwardCommand($info); - } - - - // - // CREATE/EDIT - // - - protected function initDidacticTemplate(ilPropertyFormGUI $a_form) - { - $ilUser = $this->user; - - include_once "Modules/Portfolio/classes/class.ilObjPortfolio.php"; - $all = ilObjPortfolio::getPortfoliosOfUser($ilUser->getId()); - if(sizeof($all)) - { - $opts = array(""=>$this->lng->txt("please_select")); - foreach($all as $item) - { - $opts[$item["id"]] = $item["title"]; - } - $prtf = new ilSelectInputGUI($this->lng->txt("prtf_create_template_from_portfolio"), "prtf"); - $prtf->setInfo($this->lng->txt("prtf_create_template_from_portfolio_info")); - $prtf->setOptions($opts); - $a_form->addItem($prtf); - } - - // yeah, I know. - return $a_form; - } - - protected function afterSave(ilObject $a_new_object) - { - if($_POST["prtf"]) - { - include_once "Modules/Portfolio/classes/class.ilObjPortfolio.php"; - $source = new ilObjPortfolio($_POST["prtf"], false); - - ilObjPortfolio::clonePagesAndSettings($source, $a_new_object); - } - - ilUtil::sendSuccess($this->lng->txt("prtt_portfolio_created"), true); - $this->ctrl->setParameter($this, "prt_id", $a_new_object->getId()); - $this->ctrl->redirect($this, "view"); - } - - protected function initEditCustomForm(ilPropertyFormGUI $a_form) - { - $obj_service = $this->object_service; - // activation/availability - - include_once "Services/Object/classes/class.ilObjectActivation.php"; - $this->lng->loadLanguageModule('rep'); - - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($this->lng->txt('rep_activation_availability')); - $a_form->addItem($section); - - // additional info only with multiple references - $act_obj_info = $act_ref_info = ""; - if(sizeof(ilObject::_getAllReferences($this->object->getId())) > 1) - { - $act_obj_info = ' '.$this->lng->txt('rep_activation_online_object_info'); - $act_ref_info = $this->lng->txt('rep_activation_access_ref_info'); - } - - $online = new ilCheckboxInputGUI($this->lng->txt('rep_activation_online'),'online'); - $online->setInfo($this->lng->txt('prtt_activation_online_info').$act_obj_info); - $a_form->addItem($online); - - include_once "Services/Form/classes/class.ilDateDurationInputGUI.php"; - $dur = new ilDateDurationInputGUI($this->lng->txt("rep_visibility_until"), "access_period"); - $dur->setShowTime(true); - $dur->setEndText($this->lng->txt('rep_activation_limited_end')); - $a_form->addItem($dur); - - $visible = new ilCheckboxInputGUI($this->lng->txt('rep_activation_limited_visibility'), 'access_visiblity'); - $visible->setInfo($this->lng->txt('prtt_activation_limited_visibility_info')); - $dur->addSubItem($visible); - - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($this->lng->txt('obj_presentation')); - $a_form->addItem($section); - - // tile image - $obj_service->commonSettings()->legacyForm($a_form, $this->object)->addTileImage(); - - - parent::initEditCustomForm($a_form); - - $tit = $a_form->getItemByPostVar("title"); - $tit->setInfo($this->lng->txt('prtt_title_info')); - } - - protected function getEditFormCustomValues(array &$a_values) - { - $a_values["online"] = $this->object->isOnline(); - $a_values["access_period"]["start"] = $this->object->getActivationStartDate() - ? new ilDateTime($this->object->getActivationStartDate(), IL_CAL_UNIX) - : null; - $a_values["access_period"]["end"] = $this->object->getActivationEndDate() - ? new ilDateTime($this->object->getActivationEndDate(), IL_CAL_UNIX) - : null; - $a_values["access_visiblity"] = $this->object->getActivationVisibility(); - - parent::getEditFormCustomValues($a_values); - } - - public function updateCustom(ilPropertyFormGUI $a_form) - { - $obj_service = $this->object_service; - - $this->object->setOnline($a_form->getInput("online")); - - // activation - $period = $a_form->getItemByPostVar("access_period"); - if($period->getStart() && $period->getEnd()) - { - $this->object->setActivationLimited(true); - $this->object->setActivationVisibility($a_form->getInput("access_visiblity")); - $this->object->setActivationStartDate($period->getStart()->get(IL_CAL_UNIX)); - $this->object->setActivationEndDate($period->getEnd()->get(IL_CAL_UNIX)); - } - else - { - $this->object->setActivationLimited(false); - } - - parent::updateCustom($a_form); - - $obj_service->commonSettings()->legacyForm($a_form, $this->object)->saveTileImage(); - - } - - - // - // PAGES - // - - /** - * Get portfolio template page instance - * - * @param int $a_page_id - * @param int $a_portfolio_id - * @return ilPortfolioTemplatePage - */ - protected function getPageInstance($a_page_id = null, $a_portfolio_id = null) - { - if(!$a_portfolio_id && $this->object) - { - $a_portfolio_id = $this->object->getId(); - } - include_once "Modules/Portfolio/classes/class.ilPortfolioTemplatePage.php"; - $page = new ilPortfolioTemplatePage($a_page_id); - $page->setPortfolioId($a_portfolio_id); - return $page; - } - - /** - * Get portfolio template page gui instance - * - * @param int $a_page_id - * @return ilPortfolioTemplatePageGUI - */ - protected function getPageGUIInstance($a_page_id) - { - include_once("Modules/Portfolio/classes/class.ilPortfolioTemplatePageGUI.php"); - $page_gui = new ilPortfolioTemplatePageGUI( - $this->object->getId(), - $a_page_id, - 0, - $this->object->hasPublicComments() - ); - $page_gui->setAdditional($this->getAdditional()); - return $page_gui; - } - - public function getPageGUIClassName() - { - return "ilportfoliotemplatepagegui"; - } - - protected function initCopyPageFormOptions(ilPropertyFormGUI $a_form) - { - // always existing prtft - $hi = new ilHiddenInputGUI("target"); - $hi->setValue("old"); - $a_form->addItem($hi); - - $options = array(); - $all = ilObjPortfolioTemplate::getAvailablePortfolioTemplates("write"); - foreach($all as $id => $title) - { - $options[$id] = $title; - } - $prtf = new ilSelectInputGUI($this->lng->txt("obj_prtt"), "prtf"); - $prtf->setRequired(true); - $prtf->setOptions($options); - $a_form->addItem($prtf); - - } - - - // - // BLOG - // - - /** - * Init blog template page form - * - * @param string $a_mode - * @return ilPropertyFormGUI - */ - public function initBlogForm() - { - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - - $obj = new ilTextInputGUI($this->lng->txt("title"), "blog"); - $obj->setRequired(true); - $form->addItem($obj); - - // save and cancel commands - $form->setTitle($this->lng->txt("prtf_add_blog").": ". - $this->object->getTitle()); - $form->addCommandButton("saveBlog", $this->lng->txt("save")); - $form->addCommandButton("view", $this->lng->txt("cancel")); - - return $form; - } - - /** - * Create new portfolio blog template page - */ - public function saveBlog() - { - $form = $this->initBlogForm(); - if ($form->checkInput() && $this->checkPermissionBool("write")) - { - $page = $this->getPageInstance(); - $page->setType(ilPortfolioTemplatePage::TYPE_BLOG_TEMPLATE); - $page->setTitle($form->getInput("blog")); - $page->create(); - - ilUtil::sendSuccess($this->lng->txt("prtf_blog_page_created"), true); - $this->ctrl->redirect($this, "view"); - } - - $this->tabs_gui->clearTargets(); - $this->tabs_gui->setBackTarget($this->lng->txt("back"), - $this->ctrl->getLinkTarget($this, "view")); - - $form->setValuesByPost(); - $this->tpl->setContent($form->getHtml()); - } - - - // - // TRANSMOGRIFIER - // - - function preview($a_return = false, $a_content = false, $a_show_notes = true) - { - if(!$this->checkPermissionBool("write") && - $this->checkPermissionBool("read")) - { - $this->lng->loadLanguageModule("cntr"); - - include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; - $button = ilLinkButton::getInstance(); - $button->setPrimary(true); - $button->setCaption("prtf_create_portfolio_from_template"); - $button->setUrl($this->ctrl->getLinkTarget($this, "createfromtemplate")); - $this->tpl->setHeaderActionMenu($button->render()); - } - - return parent::preview($a_return , $a_content, $a_show_notes); - } - - public function createFromTemplateOld() - { - $this->ctrl->setParameterByClass("ilobjportfoliogui", "prtt_pre", $this->object->getId()); - $this->ctrl->redirectByClass(array("ilpersonaldesktopgui", "ilportfoliorepositorygui", "ilobjportfoliogui"), "create"); - } - - public function createFromTemplate() - { - $this->ctrl->setParameterByClass("ilobjportfoliogui", "prtt_pre", $this->object->getId()); - $this->ctrl->redirectByClass(array("ilpersonaldesktopgui", "ilportfoliorepositorygui", "ilobjportfoliogui"), "createFromTemplateDirect"); - } - - public static function _goto($a_target) - { - $id = explode("_", $a_target); - - $_GET["baseClass"] = "ilRepositoryGUI"; - $_GET["ref_id"] = $id[0]; - $_GET["cmd"] = "preview"; - - include("ilias.php"); - exit; - } -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @ilCtrl_Calls ilObjPortfolioTemplateGUI: ilPortfolioTemplatePageGUI, ilPageObjectGUI, ilNoteGUI + * @ilCtrl_Calls ilObjPortfolioTemplateGUI: ilObjectCopyGUI, ilInfoScreenGUI, ilCommonActionDispatcherGUI + * @ilCtrl_Calls ilObjPortfolioTemplateGUI: ilPermissionGUI, ilExportGUI, ilObjStyleSheetGUI + * + * @ingroup ModulesPortfolio + */ +class ilObjPortfolioTemplateGUI extends ilObjPortfolioBaseGUI +{ + /** + * @var ilNavigationHistory + */ + protected $nav_history; + + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + + /** + * Constructor + */ + public function __construct($a_id = 0, $a_id_type = self::REPOSITORY_NODE_ID, $a_parent_node_id = 0) + { + parent::__construct($a_id, $a_id_type, $a_parent_node_id); + global $DIC; + + $this->nav_history = $DIC["ilNavigationHistory"]; + $this->help = $DIC["ilHelp"]; + $this->tabs = $DIC->tabs(); + $this->toolbar = $DIC->toolbar(); + $this->user = $DIC->user(); + } + + public function getType() + { + return "prtt"; + } + + public function executeCommand() + { + $ilNavigationHistory = $this->nav_history; + + // add entry to navigation history + if (!$this->getCreationMode() && + $this->getAccessHandler()->checkAccess("read", "", $this->node_id)) { + $link = $this->ctrl->getLinkTarget($this, "view"); + $ilNavigationHistory->addItem($this->node_id, $link, "prtt"); + } + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd("view"); + + switch ($next_class) { + case 'ilportfoliotemplatepagegui': + $this->determinePageCall(); // has to be done before locator! + $this->prepareOutput(); + $this->handlePageCall($cmd); + break; + + case "ilnotegui": + $this->preview(); + break; + + case "ilinfoscreengui": + $this->prepareOutput(); + $this->addHeaderAction("view"); + $this->infoScreenForward(); + break; + + case "ilcommonactiondispatchergui": + include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); + $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); + $this->ctrl->forwardCommand($gui); + break; + + case "ilpermissiongui": + $this->prepareOutput(); + $this->tabs_gui->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("prtt"); + $this->ctrl->forwardCommand($cp); + break; + + case 'ilexportgui': + $this->prepareOutput(); + $this->tabs_gui->activateTab("export"); + include_once("./Services/Export/classes/class.ilExportGUI.php"); + $exp_gui = new ilExportGUI($this); + $exp_gui->addFormat("xml"); + $this->ctrl->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" || $_GET["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; + + default: + $this->addHeaderAction($cmd); + return ilObject2GUI::executeCommand(); + } + } + + protected function setTabs() + { + $ilHelp = $this->help; + + $ilHelp->setScreenIdComponent("prtt"); + + if ($this->checkPermissionBool("write")) { + $this->tabs_gui->addTab( + "pages", + $this->lng->txt("content"), + $this->ctrl->getLinkTarget($this, "view") + ); + } + + if ($this->checkPermissionBool("read")) { + $this->tabs_gui->addTab( + "id_info", + $this->lng->txt("info_short"), + $this->ctrl->getLinkTargetByClass(array("ilobjportfoliotemplategui", "ilinfoscreengui"), "showSummary") + ); + } + + if ($this->checkPermissionBool("write")) { + $this->tabs_gui->addTab( + "settings", + $this->lng->txt("settings"), + $this->ctrl->getLinkTarget($this, "edit") + ); + + $this->tabs_gui->addTab( + "export", + $this->lng->txt("export"), + $this->ctrl->getLinkTargetByClass("ilexportgui", "") + ); + } + + if ($this->checkPermissionBool("read")) { + $this->tabs_gui->addNonTabbedLink( + "preview", + $this->lng->txt("user_profile_preview"), + $this->ctrl->getLinkTarget($this, "preview") + ); + } + + // will add permissions if needed + ilObject2GUI::setTabs(); + } + + /** + * 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; + $ilToolbar = $this->toolbar; + + $ilTabs->activateTab("id_info"); + + $this->checkPermission("visible"); + + if ($this->checkPermissionBool("read")) { + $this->lng->loadLanguageModule("cntr"); + + include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; + $button = ilLinkButton::getInstance(); + $button->setPrimary(true); + $button->setCaption("prtf_create_portfolio_from_template"); + $button->setUrl($this->ctrl->getLinkTarget($this, "createfromtemplate")); + $ilToolbar->addButtonInstance($button); + } + + include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); + $info = new ilInfoScreenGUI($this); + + $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()); + + $this->ctrl->forwardCommand($info); + } + + + // + // CREATE/EDIT + // + + protected function initDidacticTemplate(ilPropertyFormGUI $a_form) + { + $ilUser = $this->user; + + include_once "Modules/Portfolio/classes/class.ilObjPortfolio.php"; + $all = ilObjPortfolio::getPortfoliosOfUser($ilUser->getId()); + if (sizeof($all)) { + $opts = array(""=>$this->lng->txt("please_select")); + foreach ($all as $item) { + $opts[$item["id"]] = $item["title"]; + } + $prtf = new ilSelectInputGUI($this->lng->txt("prtf_create_template_from_portfolio"), "prtf"); + $prtf->setInfo($this->lng->txt("prtf_create_template_from_portfolio_info")); + $prtf->setOptions($opts); + $a_form->addItem($prtf); + } + + // yeah, I know. + return $a_form; + } + + protected function afterSave(ilObject $a_new_object) + { + if ($_POST["prtf"]) { + include_once "Modules/Portfolio/classes/class.ilObjPortfolio.php"; + $source = new ilObjPortfolio($_POST["prtf"], false); + + ilObjPortfolio::clonePagesAndSettings($source, $a_new_object); + } + + ilUtil::sendSuccess($this->lng->txt("prtt_portfolio_created"), true); + $this->ctrl->setParameter($this, "prt_id", $a_new_object->getId()); + $this->ctrl->redirect($this, "view"); + } + + protected function initEditCustomForm(ilPropertyFormGUI $a_form) + { + $obj_service = $this->object_service; + // activation/availability + + include_once "Services/Object/classes/class.ilObjectActivation.php"; + $this->lng->loadLanguageModule('rep'); + + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($this->lng->txt('rep_activation_availability')); + $a_form->addItem($section); + + // additional info only with multiple references + $act_obj_info = $act_ref_info = ""; + if (sizeof(ilObject::_getAllReferences($this->object->getId())) > 1) { + $act_obj_info = ' ' . $this->lng->txt('rep_activation_online_object_info'); + $act_ref_info = $this->lng->txt('rep_activation_access_ref_info'); + } + + $online = new ilCheckboxInputGUI($this->lng->txt('rep_activation_online'), 'online'); + $online->setInfo($this->lng->txt('prtt_activation_online_info') . $act_obj_info); + $a_form->addItem($online); + + include_once "Services/Form/classes/class.ilDateDurationInputGUI.php"; + $dur = new ilDateDurationInputGUI($this->lng->txt("rep_visibility_until"), "access_period"); + $dur->setShowTime(true); + $dur->setEndText($this->lng->txt('rep_activation_limited_end')); + $a_form->addItem($dur); + + $visible = new ilCheckboxInputGUI($this->lng->txt('rep_activation_limited_visibility'), 'access_visiblity'); + $visible->setInfo($this->lng->txt('prtt_activation_limited_visibility_info')); + $dur->addSubItem($visible); + + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($this->lng->txt('obj_presentation')); + $a_form->addItem($section); + + // tile image + $obj_service->commonSettings()->legacyForm($a_form, $this->object)->addTileImage(); + + + parent::initEditCustomForm($a_form); + + $tit = $a_form->getItemByPostVar("title"); + $tit->setInfo($this->lng->txt('prtt_title_info')); + } + + protected function getEditFormCustomValues(array &$a_values) + { + $a_values["online"] = $this->object->isOnline(); + $a_values["access_period"]["start"] = $this->object->getActivationStartDate() + ? new ilDateTime($this->object->getActivationStartDate(), IL_CAL_UNIX) + : null; + $a_values["access_period"]["end"] = $this->object->getActivationEndDate() + ? new ilDateTime($this->object->getActivationEndDate(), IL_CAL_UNIX) + : null; + $a_values["access_visiblity"] = $this->object->getActivationVisibility(); + + parent::getEditFormCustomValues($a_values); + } + + public function updateCustom(ilPropertyFormGUI $a_form) + { + $obj_service = $this->object_service; + + $this->object->setOnline($a_form->getInput("online")); + + // activation + $period = $a_form->getItemByPostVar("access_period"); + if ($period->getStart() && $period->getEnd()) { + $this->object->setActivationLimited(true); + $this->object->setActivationVisibility($a_form->getInput("access_visiblity")); + $this->object->setActivationStartDate($period->getStart()->get(IL_CAL_UNIX)); + $this->object->setActivationEndDate($period->getEnd()->get(IL_CAL_UNIX)); + } else { + $this->object->setActivationLimited(false); + } + + parent::updateCustom($a_form); + + $obj_service->commonSettings()->legacyForm($a_form, $this->object)->saveTileImage(); + } + + + // + // PAGES + // + + /** + * Get portfolio template page instance + * + * @param int $a_page_id + * @param int $a_portfolio_id + * @return ilPortfolioTemplatePage + */ + protected function getPageInstance($a_page_id = null, $a_portfolio_id = null) + { + if (!$a_portfolio_id && $this->object) { + $a_portfolio_id = $this->object->getId(); + } + include_once "Modules/Portfolio/classes/class.ilPortfolioTemplatePage.php"; + $page = new ilPortfolioTemplatePage($a_page_id); + $page->setPortfolioId($a_portfolio_id); + return $page; + } + + /** + * Get portfolio template page gui instance + * + * @param int $a_page_id + * @return ilPortfolioTemplatePageGUI + */ + protected function getPageGUIInstance($a_page_id) + { + include_once("Modules/Portfolio/classes/class.ilPortfolioTemplatePageGUI.php"); + $page_gui = new ilPortfolioTemplatePageGUI( + $this->object->getId(), + $a_page_id, + 0, + $this->object->hasPublicComments() + ); + $page_gui->setAdditional($this->getAdditional()); + return $page_gui; + } + + public function getPageGUIClassName() + { + return "ilportfoliotemplatepagegui"; + } + + protected function initCopyPageFormOptions(ilPropertyFormGUI $a_form) + { + // always existing prtft + $hi = new ilHiddenInputGUI("target"); + $hi->setValue("old"); + $a_form->addItem($hi); + + $options = array(); + $all = ilObjPortfolioTemplate::getAvailablePortfolioTemplates("write"); + foreach ($all as $id => $title) { + $options[$id] = $title; + } + $prtf = new ilSelectInputGUI($this->lng->txt("obj_prtt"), "prtf"); + $prtf->setRequired(true); + $prtf->setOptions($options); + $a_form->addItem($prtf); + } + + + // + // BLOG + // + + /** + * Init blog template page form + * + * @param string $a_mode + * @return ilPropertyFormGUI + */ + public function initBlogForm() + { + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this)); + + $obj = new ilTextInputGUI($this->lng->txt("title"), "blog"); + $obj->setRequired(true); + $form->addItem($obj); + + // save and cancel commands + $form->setTitle($this->lng->txt("prtf_add_blog") . ": " . + $this->object->getTitle()); + $form->addCommandButton("saveBlog", $this->lng->txt("save")); + $form->addCommandButton("view", $this->lng->txt("cancel")); + + return $form; + } + + /** + * Create new portfolio blog template page + */ + public function saveBlog() + { + $form = $this->initBlogForm(); + if ($form->checkInput() && $this->checkPermissionBool("write")) { + $page = $this->getPageInstance(); + $page->setType(ilPortfolioTemplatePage::TYPE_BLOG_TEMPLATE); + $page->setTitle($form->getInput("blog")); + $page->create(); + + ilUtil::sendSuccess($this->lng->txt("prtf_blog_page_created"), true); + $this->ctrl->redirect($this, "view"); + } + + $this->tabs_gui->clearTargets(); + $this->tabs_gui->setBackTarget( + $this->lng->txt("back"), + $this->ctrl->getLinkTarget($this, "view") + ); + + $form->setValuesByPost(); + $this->tpl->setContent($form->getHtml()); + } + + + // + // TRANSMOGRIFIER + // + + public function preview($a_return = false, $a_content = false, $a_show_notes = true) + { + if (!$this->checkPermissionBool("write") && + $this->checkPermissionBool("read")) { + $this->lng->loadLanguageModule("cntr"); + + include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; + $button = ilLinkButton::getInstance(); + $button->setPrimary(true); + $button->setCaption("prtf_create_portfolio_from_template"); + $button->setUrl($this->ctrl->getLinkTarget($this, "createfromtemplate")); + $this->tpl->setHeaderActionMenu($button->render()); + } + + return parent::preview($a_return, $a_content, $a_show_notes); + } + + public function createFromTemplateOld() + { + $this->ctrl->setParameterByClass("ilobjportfoliogui", "prtt_pre", $this->object->getId()); + $this->ctrl->redirectByClass(array("ilpersonaldesktopgui", "ilportfoliorepositorygui", "ilobjportfoliogui"), "create"); + } + + public function createFromTemplate() + { + $this->ctrl->setParameterByClass("ilobjportfoliogui", "prtt_pre", $this->object->getId()); + $this->ctrl->redirectByClass(array("ilpersonaldesktopgui", "ilportfoliorepositorygui", "ilobjportfoliogui"), "createFromTemplateDirect"); + } + + public static function _goto($a_target) + { + $id = explode("_", $a_target); + + $_GET["baseClass"] = "ilRepositoryGUI"; + $_GET["ref_id"] = $id[0]; + $_GET["cmd"] = "preview"; + + include("ilias.php"); + exit; + } +} diff --git a/Modules/Portfolio/classes/class.ilObjPortfolioTemplateListGUI.php b/Modules/Portfolio/classes/class.ilObjPortfolioTemplateListGUI.php index c7dc81a8384ac99e8606d0d907357cad9a167a2a..9b97a9c0777ce8865af0eb3660f638665c48ae9d 100644 --- a/Modules/Portfolio/classes/class.ilObjPortfolioTemplateListGUI.php +++ b/Modules/Portfolio/classes/class.ilObjPortfolioTemplateListGUI.php @@ -1,56 +1,53 @@ - -* $Id: class.ilObjRootFolderListGUI.php 23764 2010-05-06 15:11:30Z smeyer $ -* -* @extends ilObjectListGUI -*/ -class ilObjPortfolioTemplateListGUI 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; - $this->info_screen_enabled = true; - $this->type = "prtt"; - $this->gui_class_name = "ilobjportfoliotemplategui"; - - // general commands array - include_once('./Modules/Portfolio/classes/class.ilObjPortfolioTemplateAccess.php'); - $this->commands = ilObjPortfolioTemplateAccess::_getCommands(); - } - - public function getProperties() - { - $lng = $this->lng; - - $props = array(); - - include_once("./Modules/Portfolio/classes/class.ilObjPortfolioTemplateAccess.php"); - if(!ilObjPortfolioTemplateAccess::_lookupOnline($this->obj_id)) - { - $props[] = array( - "alert" => true, - "property" => $lng->txt("status"), - "value" => $lng->txt("offline") - ); - } - - return $props; - } -} - -?> \ No newline at end of file + +* $Id: class.ilObjRootFolderListGUI.php 23764 2010-05-06 15:11:30Z smeyer $ +* +* @extends ilObjectListGUI +*/ +class ilObjPortfolioTemplateListGUI extends ilObjectListGUI +{ + /** + * initialisation + */ + public function init() + { + $this->copy_enabled = true; + $this->delete_enabled = true; + $this->cut_enabled = true; + $this->subscribe_enabled = true; + $this->link_enabled = true; + $this->info_screen_enabled = true; + $this->type = "prtt"; + $this->gui_class_name = "ilobjportfoliotemplategui"; + + // general commands array + include_once('./Modules/Portfolio/classes/class.ilObjPortfolioTemplateAccess.php'); + $this->commands = ilObjPortfolioTemplateAccess::_getCommands(); + } + + public function getProperties() + { + $lng = $this->lng; + + $props = array(); + + include_once("./Modules/Portfolio/classes/class.ilObjPortfolioTemplateAccess.php"); + if (!ilObjPortfolioTemplateAccess::_lookupOnline($this->obj_id)) { + $props[] = array( + "alert" => true, + "property" => $lng->txt("status"), + "value" => $lng->txt("offline") + ); + } + + return $props; + } +} diff --git a/Modules/Portfolio/classes/class.ilPCConsultationHours.php b/Modules/Portfolio/classes/class.ilPCConsultationHours.php index 8f0116c34624af86699ca482fc8bd3db4015dc3d..5ee073ac38cf7cbcdc906e5c62a88281a477554d 100644 --- a/Modules/Portfolio/classes/class.ilPCConsultationHours.php +++ b/Modules/Portfolio/classes/class.ilPCConsultationHours.php @@ -1,123 +1,115 @@ - -* @version $Id: class.ilPCListItem.php 22210 2009-10-26 09:46:06Z akill $ -* -* @ingroup ServicesCOPage -*/ -class ilPCConsultationHours extends ilPageContent -{ - /** - * @var ilObjUser - */ - protected $user; - - var $dom; - - /** - * Init page content component. - */ - function init() - { - global $DIC; - $this->user = $DIC->user(); - $this->setType("cach"); - } - - /** - * Get lang vars needed for editing - * @return array array of lang var keys - */ - static function getLangVars() - { - return array("ed_insert_consultation_hours", "pc_cach"); - } - - /** - * Set node - */ - function setNode($a_node) - { - parent::setNode($a_node); // this is the PageContent node - $this->cach_node =& $a_node->first_child(); // this is the consultation hours node - } - - /** - * Create consultation hours node in xml. - * - * @param object $a_pg_obj Page Object - * @param string $a_hier_id Hierarchical ID - */ - 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->cach_node = $this->dom->create_element("ConsultationHours"); - $this->cach_node = $this->node->append_child($this->cach_node); - } - - /** - * Set consultation hours settings - * - * @param int $a_mode - * @param int $a_grp_id - */ - function setData($a_mode, array $a_grp_ids) - { - $ilUser = $this->user; - - $this->cach_node->set_attribute("Mode", $a_mode); - $this->cach_node->set_attribute("User", $ilUser->getId()); - - // remove all children first - $children = $this->cach_node->child_nodes(); - if($children) - { - foreach($children as $child) - { - $this->cach_node->remove_child($child); - } - } - - if($a_mode == "manual") - { - foreach($a_grp_ids as $grp_id) - { - $field_node = $this->dom->create_element("ConsultationHoursGroup"); - $field_node = $this->cach_node->append_child($field_node); - $field_node->set_attribute("Id", $grp_id); - } - } - } - - /** - * Get consultation hours group ids - * - * @return string - */ - function getGroupIds() - { - $res = array(); - if (is_object($this->cach_node)) - { - $children = $this->cach_node->child_nodes(); - if($children) - { - foreach($children as $child) - { - $res[] = $child->get_attribute("Id"); - } - } - } - return $res; - } -} -?> \ No newline at end of file + +* @version $Id: class.ilPCListItem.php 22210 2009-10-26 09:46:06Z akill $ +* +* @ingroup ServicesCOPage +*/ +class ilPCConsultationHours extends ilPageContent +{ + /** + * @var ilObjUser + */ + protected $user; + + public $dom; + + /** + * Init page content component. + */ + public function init() + { + global $DIC; + $this->user = $DIC->user(); + $this->setType("cach"); + } + + /** + * Get lang vars needed for editing + * @return array array of lang var keys + */ + public static function getLangVars() + { + return array("ed_insert_consultation_hours", "pc_cach"); + } + + /** + * Set node + */ + public function setNode($a_node) + { + parent::setNode($a_node); // this is the PageContent node + $this->cach_node =&$a_node->first_child(); // this is the consultation hours node + } + + /** + * Create consultation hours node in xml. + * + * @param object $a_pg_obj Page Object + * @param string $a_hier_id Hierarchical ID + */ + public 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->cach_node = $this->dom->create_element("ConsultationHours"); + $this->cach_node = $this->node->append_child($this->cach_node); + } + + /** + * Set consultation hours settings + * + * @param int $a_mode + * @param int $a_grp_id + */ + public function setData($a_mode, array $a_grp_ids) + { + $ilUser = $this->user; + + $this->cach_node->set_attribute("Mode", $a_mode); + $this->cach_node->set_attribute("User", $ilUser->getId()); + + // remove all children first + $children = $this->cach_node->child_nodes(); + if ($children) { + foreach ($children as $child) { + $this->cach_node->remove_child($child); + } + } + + if ($a_mode == "manual") { + foreach ($a_grp_ids as $grp_id) { + $field_node = $this->dom->create_element("ConsultationHoursGroup"); + $field_node = $this->cach_node->append_child($field_node); + $field_node->set_attribute("Id", $grp_id); + } + } + } + + /** + * Get consultation hours group ids + * + * @return string + */ + public function getGroupIds() + { + $res = array(); + if (is_object($this->cach_node)) { + $children = $this->cach_node->child_nodes(); + if ($children) { + foreach ($children as $child) { + $res[] = $child->get_attribute("Id"); + } + } + } + return $res; + } +} diff --git a/Modules/Portfolio/classes/class.ilPCConsultationHoursGUI.php b/Modules/Portfolio/classes/class.ilPCConsultationHoursGUI.php index 09a488625c6a7096aa7d033fd1c7221af8b9aaf5..8881b3aeb6388e6be03491aa33049f065ad92f15 100644 --- a/Modules/Portfolio/classes/class.ilPCConsultationHoursGUI.php +++ b/Modules/Portfolio/classes/class.ilPCConsultationHoursGUI.php @@ -1,245 +1,218 @@ - -* @version $I$ -* -* @ingroup ServicesCOPage -*/ -class ilPCConsultationHoursGUI extends ilPageContentGUI -{ - /** - * @var ilObjUser - */ - protected $user; - - /** - * Constructor - * @access 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->user = $DIC->user(); - $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 consultation hours form - * - * @param ilPropertyFormGUI $a_form - */ - function insert(ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - - $this->displayValidationError(); - - if(!$a_form) - { - $a_form = $this->initForm(true); - } - $tpl->setContent($a_form->getHTML()); - } - - /** - * Edit consultation hours form - * - * @param ilPropertyFormGUI $a_form - */ - function edit(ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - - $this->displayValidationError(); - - if(!$a_form) - { - $a_form = $this->initForm(); - } - $tpl->setContent($a_form->getHTML()); - } - - /** - * Init consultation hours form - * - * @param bool $a_insert - * @return ilPropertyFormGUI - */ - protected function initForm($a_insert = false) - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - $lng = $this->lng; - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this)); - if ($a_insert) - { - $form->setTitle($this->lng->txt("cont_insert_consultation_hours")); - } - else - { - $form->setTitle($this->lng->txt("cont_update_consultation_hours")); - } - - $mode = new ilRadioGroupInputGUI($this->lng->txt("cont_cach_mode"), "mode"); - $mode->setRequired(true); - $form->addItem($mode); - - $opt_auto = new ilRadioOption($this->lng->txt("cont_cach_mode_automatic"), "auto"); - $opt_auto->setInfo($this->lng->txt("cont_cach_mode_automatic_info")); - $mode->addOption($opt_auto); - - $opt_manual = new ilRadioOption($this->lng->txt("cont_cach_mode_manual"), "manual"); - $opt_manual->setInfo($this->lng->txt("cont_cach_mode_manual_info")); - $mode->addOption($opt_manual); - - if(!$this->getPageConfig()->getEnablePCType("PlaceHolder")) - { - include_once "Services/Calendar/classes/ConsultationHours/class.ilConsultationHourGroups.php"; - $grp_ids = ilConsultationHourGroups::getGroupsOfUser($ilUser->getId()); - if(sizeof($grp_ids)) - { - $this->lng->loadLanguageModule("dateplaner"); - $groups = new ilCheckboxGroupInputGUI($this->lng->txt("cal_ch_app_grp"), "grp"); - $groups->setRequired(true); - $opt_manual->addSubItem($groups); - - foreach($grp_ids as $grp_obj) - { - $groups->addOption(new ilCheckboxOption($grp_obj->getTitle(), $grp_obj->getGroupId())); - } - } - else - { - $opt_manual->setDisabled(true); - } - } - else - { - $opt_manual->setDisabled(true); - } - - if ($a_insert) - { - $mode->setValue("auto"); - - $form->addCommandButton("create_consultation_hours", $this->lng->txt("select")); - $form->addCommandButton("cancelCreate", $this->lng->txt("cancel")); - } - else - { - // set values - $grp_ids = $this->content_obj->getGroupIds(); - if(sizeof($grp_ids)) - { - $mode->setValue("manual"); - $groups->setValue($grp_ids); - } - else - { - $mode->setValue("auto"); - } - - $form->addCommandButton("update", $this->lng->txt("select")); - $form->addCommandButton("cancelUpdate", $this->lng->txt("cancel")); - } - - return $form; - } - - /** - * Create new consultation hours - */ - function create() - { - $form = $this->initForm(true); - if($form->checkInput()) - { - $grp_ids = null; - $mode = $form->getInput("mode"); - if($mode == "manual") - { - $grp_ids = $form->getInput("grp"); - } - - $this->content_obj = new ilPCConsultationHours($this->getPage()); - $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); - $this->content_obj->setData($mode, (array)$grp_ids); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - } - - $form->setValuesByPost(); - return $this->insert($form); - } - - /** - * Update consultation hours - */ - function update() - { - $form = $this->initForm(); - if($form->checkInput()) - { - $grp_ids = array(); - $mode = $form->getInput("mode"); - if($mode == "manual") - { - $grp_ids = $form->getInput("grp"); - } - - $this->content_obj->setData($mode, $grp_ids); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - } - - $this->pg_obj->addHierIDs(); - $form->setValuesByPost(); - return $this->edit($form); - } -} - -?> \ No newline at end of file + +* @version $I$ +* +* @ingroup ServicesCOPage +*/ +class ilPCConsultationHoursGUI extends ilPageContentGUI +{ + /** + * @var ilObjUser + */ + protected $user; + + /** + * Constructor + * @access public + */ + 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->user = $DIC->user(); + $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 consultation hours form + * + * @param ilPropertyFormGUI $a_form + */ + public function insert(ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + + $this->displayValidationError(); + + if (!$a_form) { + $a_form = $this->initForm(true); + } + $tpl->setContent($a_form->getHTML()); + } + + /** + * Edit consultation hours form + * + * @param ilPropertyFormGUI $a_form + */ + public function edit(ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + + $this->displayValidationError(); + + if (!$a_form) { + $a_form = $this->initForm(); + } + $tpl->setContent($a_form->getHTML()); + } + + /** + * Init consultation hours form + * + * @param bool $a_insert + * @return ilPropertyFormGUI + */ + protected function initForm($a_insert = false) + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + $lng = $this->lng; + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this)); + if ($a_insert) { + $form->setTitle($this->lng->txt("cont_insert_consultation_hours")); + } else { + $form->setTitle($this->lng->txt("cont_update_consultation_hours")); + } + + $mode = new ilRadioGroupInputGUI($this->lng->txt("cont_cach_mode"), "mode"); + $mode->setRequired(true); + $form->addItem($mode); + + $opt_auto = new ilRadioOption($this->lng->txt("cont_cach_mode_automatic"), "auto"); + $opt_auto->setInfo($this->lng->txt("cont_cach_mode_automatic_info")); + $mode->addOption($opt_auto); + + $opt_manual = new ilRadioOption($this->lng->txt("cont_cach_mode_manual"), "manual"); + $opt_manual->setInfo($this->lng->txt("cont_cach_mode_manual_info")); + $mode->addOption($opt_manual); + + if (!$this->getPageConfig()->getEnablePCType("PlaceHolder")) { + include_once "Services/Calendar/classes/ConsultationHours/class.ilConsultationHourGroups.php"; + $grp_ids = ilConsultationHourGroups::getGroupsOfUser($ilUser->getId()); + if (sizeof($grp_ids)) { + $this->lng->loadLanguageModule("dateplaner"); + $groups = new ilCheckboxGroupInputGUI($this->lng->txt("cal_ch_app_grp"), "grp"); + $groups->setRequired(true); + $opt_manual->addSubItem($groups); + + foreach ($grp_ids as $grp_obj) { + $groups->addOption(new ilCheckboxOption($grp_obj->getTitle(), $grp_obj->getGroupId())); + } + } else { + $opt_manual->setDisabled(true); + } + } else { + $opt_manual->setDisabled(true); + } + + if ($a_insert) { + $mode->setValue("auto"); + + $form->addCommandButton("create_consultation_hours", $this->lng->txt("select")); + $form->addCommandButton("cancelCreate", $this->lng->txt("cancel")); + } else { + // set values + $grp_ids = $this->content_obj->getGroupIds(); + if (sizeof($grp_ids)) { + $mode->setValue("manual"); + $groups->setValue($grp_ids); + } else { + $mode->setValue("auto"); + } + + $form->addCommandButton("update", $this->lng->txt("select")); + $form->addCommandButton("cancelUpdate", $this->lng->txt("cancel")); + } + + return $form; + } + + /** + * Create new consultation hours + */ + public function create() + { + $form = $this->initForm(true); + if ($form->checkInput()) { + $grp_ids = null; + $mode = $form->getInput("mode"); + if ($mode == "manual") { + $grp_ids = $form->getInput("grp"); + } + + $this->content_obj = new ilPCConsultationHours($this->getPage()); + $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); + $this->content_obj->setData($mode, (array) $grp_ids); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + } + + $form->setValuesByPost(); + return $this->insert($form); + } + + /** + * Update consultation hours + */ + public function update() + { + $form = $this->initForm(); + if ($form->checkInput()) { + $grp_ids = array(); + $mode = $form->getInput("mode"); + if ($mode == "manual") { + $grp_ids = $form->getInput("grp"); + } + + $this->content_obj->setData($mode, $grp_ids); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + } + + $this->pg_obj->addHierIDs(); + $form->setValuesByPost(); + return $this->edit($form); + } +} diff --git a/Modules/Portfolio/classes/class.ilPCMyCourses.php b/Modules/Portfolio/classes/class.ilPCMyCourses.php index 3ca0802b9d2f5c6aa1d08fdcad742d638c5584be..28e2a09e49a2c4b2e162a97f15ac7c2b15341a96 100644 --- a/Modules/Portfolio/classes/class.ilPCMyCourses.php +++ b/Modules/Portfolio/classes/class.ilPCMyCourses.php @@ -1,98 +1,95 @@ - -* @version $Id: class.ilPCListItem.php 22210 2009-10-26 09:46:06Z akill $ -* -* @ingroup ModulesPortfolio -*/ -class ilPCMyCourses extends ilPageContent -{ - /** - * @var ilObjUser - */ - protected $user; - - var $dom; - - /** - * Init page content component. - */ - function init() - { - global $DIC; - $this->user = $DIC->user(); - $this->setType("mcrs"); - } - - /** - * Get lang vars needed for editing - * @return array array of lang var keys - */ - static function getLangVars() - { - return array("ed_insert_my_courses", "pc_mcrs"); - } - - /** - * Set node - */ - function setNode($a_node) - { - parent::setNode($a_node); // this is the PageContent node - $this->mcrs_node =& $a_node->first_child(); // this is the courses node - } - - /** - * Create courses node in xml. - * - * @param object $a_pg_obj Page Object - * @param string $a_hier_id Hierarchical ID - */ - 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->mcrs_node = $this->dom->create_element("MyCourses"); - $this->mcrs_node = $this->node->append_child($this->mcrs_node); - } - - /** - * Set courses settings - */ - function setData($a_sort) - { - $ilUser = $this->user; - - $this->mcrs_node->set_attribute("User", $ilUser->getId()); - $this->mcrs_node->set_attribute("Sort", $a_sort); - - /* remove all children first - $children = $this->cach_node->child_nodes(); - if($children) - { - foreach($children as $child) - { - $this->cach_node->remove_child($child); - } - } - */ - } - - function getSorting() - { - if (is_object($this->mcrs_node)) - { - return $this->mcrs_node->get_attribute("Sort"); - } - } -} - -?> \ No newline at end of file + +* @version $Id: class.ilPCListItem.php 22210 2009-10-26 09:46:06Z akill $ +* +* @ingroup ModulesPortfolio +*/ +class ilPCMyCourses extends ilPageContent +{ + /** + * @var ilObjUser + */ + protected $user; + + public $dom; + + /** + * Init page content component. + */ + public function init() + { + global $DIC; + $this->user = $DIC->user(); + $this->setType("mcrs"); + } + + /** + * Get lang vars needed for editing + * @return array array of lang var keys + */ + public static function getLangVars() + { + return array("ed_insert_my_courses", "pc_mcrs"); + } + + /** + * Set node + */ + public function setNode($a_node) + { + parent::setNode($a_node); // this is the PageContent node + $this->mcrs_node =&$a_node->first_child(); // this is the courses node + } + + /** + * Create courses node in xml. + * + * @param object $a_pg_obj Page Object + * @param string $a_hier_id Hierarchical ID + */ + public 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->mcrs_node = $this->dom->create_element("MyCourses"); + $this->mcrs_node = $this->node->append_child($this->mcrs_node); + } + + /** + * Set courses settings + */ + public function setData($a_sort) + { + $ilUser = $this->user; + + $this->mcrs_node->set_attribute("User", $ilUser->getId()); + $this->mcrs_node->set_attribute("Sort", $a_sort); + + /* remove all children first + $children = $this->cach_node->child_nodes(); + if($children) + { + foreach($children as $child) + { + $this->cach_node->remove_child($child); + } + } + */ + } + + public function getSorting() + { + if (is_object($this->mcrs_node)) { + return $this->mcrs_node->get_attribute("Sort"); + } + } +} diff --git a/Modules/Portfolio/classes/class.ilPCMyCoursesGUI.php b/Modules/Portfolio/classes/class.ilPCMyCoursesGUI.php index 89f7d300902433e3925bc3a53e3f888dc6c5b3a0..91947402b09c0b57f9b8345a72a9260f3f03db06 100644 --- a/Modules/Portfolio/classes/class.ilPCMyCoursesGUI.php +++ b/Modules/Portfolio/classes/class.ilPCMyCoursesGUI.php @@ -1,190 +1,175 @@ - -* @version $I$ -* -* @ingroup ModulesPortfolio -*/ -class ilPCMyCoursesGUI extends ilPageContentGUI -{ - /** - * Constructor - * @access 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(); - 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 courses form - * - * @param ilPropertyFormGUI $a_form - */ - function insert(ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - - /* #12816 - no form needed yet - $this->create(); - */ - - $this->displayValidationError(); - - if(!$a_form) - { - $a_form = $this->initForm(true); - } - $tpl->setContent($a_form->getHTML()); - } - - /** - * Edit courses form - * - * @param ilPropertyFormGUI $a_form - */ - function edit(ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - - $this->displayValidationError(); - - if(!$a_form) - { - $a_form = $this->initForm(); - } - $tpl->setContent($a_form->getHTML()); - } - - /** - * Init courses form - * - * @param bool $a_insert - * @return ilPropertyFormGUI - */ - protected function initForm($a_insert = false) - { - $ilCtrl = $this->ctrl; - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this)); - if ($a_insert) - { - $form->setTitle($this->lng->txt("cont_insert_my_courses")); - } - else - { - $form->setTitle($this->lng->txt("cont_update_my_courses")); - } - - $sort = new ilRadioGroupInputGUI($this->lng->txt("cont_mycourses_sortorder"), "sort"); - $sort->setInfo($this->lng->txt("cont_mycourses_sortorder_info")); //#15511 - $sort->setRequired(true); - $form->addItem($sort); - - $sort->addOption(new ilRadioOption($this->lng->txt("cont_mycourses_sortorder_alphabetical"), "alpha")); - $sort->addOption(new ilRadioOption($this->lng->txt("cont_mycourses_sortorder_location"), "loc")); - - if ($a_insert) - { - $sort->setValue("alpha"); - - $form->addCommandButton("create_my_courses", $this->lng->txt("save")); - $form->addCommandButton("cancelCreate", $this->lng->txt("cancel")); - } - else - { - $sort->setValue($this->content_obj->getSorting()); - - $form->addCommandButton("update", $this->lng->txt("save")); - $form->addCommandButton("cancelUpdate", $this->lng->txt("cancel")); - } - - return $form; - } - - /** - * Create new courses - */ - function create() - { - $form = $this->initForm(true); - if($form->checkInput()) - { - $sort = $form->getInput("sort"); - - $this->content_obj = new ilPCMyCourses($this->getPage()); - $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); - $this->content_obj->setData($sort); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - } - - $form->setValuesByPost(); - return $this->insert($form); - } - - /** - * Update courses - */ - function update() - { - $form = $this->initForm(); - if($form->checkInput()) - { - $sort = $form->getInput("sort"); - - $this->content_obj->setData($sort); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - } - - $this->pg_obj->addHierIDs(); - $form->setValuesByPost(); - return $this->edit($form); - } -} - -?> \ No newline at end of file + +* @version $I$ +* +* @ingroup ModulesPortfolio +*/ +class ilPCMyCoursesGUI extends ilPageContentGUI +{ + /** + * Constructor + * @access public + */ + 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(); + 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 courses form + * + * @param ilPropertyFormGUI $a_form + */ + public function insert(ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + + /* #12816 - no form needed yet + $this->create(); + */ + + $this->displayValidationError(); + + if (!$a_form) { + $a_form = $this->initForm(true); + } + $tpl->setContent($a_form->getHTML()); + } + + /** + * Edit courses form + * + * @param ilPropertyFormGUI $a_form + */ + public function edit(ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + + $this->displayValidationError(); + + if (!$a_form) { + $a_form = $this->initForm(); + } + $tpl->setContent($a_form->getHTML()); + } + + /** + * Init courses form + * + * @param bool $a_insert + * @return ilPropertyFormGUI + */ + protected function initForm($a_insert = false) + { + $ilCtrl = $this->ctrl; + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this)); + if ($a_insert) { + $form->setTitle($this->lng->txt("cont_insert_my_courses")); + } else { + $form->setTitle($this->lng->txt("cont_update_my_courses")); + } + + $sort = new ilRadioGroupInputGUI($this->lng->txt("cont_mycourses_sortorder"), "sort"); + $sort->setInfo($this->lng->txt("cont_mycourses_sortorder_info")); //#15511 + $sort->setRequired(true); + $form->addItem($sort); + + $sort->addOption(new ilRadioOption($this->lng->txt("cont_mycourses_sortorder_alphabetical"), "alpha")); + $sort->addOption(new ilRadioOption($this->lng->txt("cont_mycourses_sortorder_location"), "loc")); + + if ($a_insert) { + $sort->setValue("alpha"); + + $form->addCommandButton("create_my_courses", $this->lng->txt("save")); + $form->addCommandButton("cancelCreate", $this->lng->txt("cancel")); + } else { + $sort->setValue($this->content_obj->getSorting()); + + $form->addCommandButton("update", $this->lng->txt("save")); + $form->addCommandButton("cancelUpdate", $this->lng->txt("cancel")); + } + + return $form; + } + + /** + * Create new courses + */ + public function create() + { + $form = $this->initForm(true); + if ($form->checkInput()) { + $sort = $form->getInput("sort"); + + $this->content_obj = new ilPCMyCourses($this->getPage()); + $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); + $this->content_obj->setData($sort); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + } + + $form->setValuesByPost(); + return $this->insert($form); + } + + /** + * Update courses + */ + public function update() + { + $form = $this->initForm(); + if ($form->checkInput()) { + $sort = $form->getInput("sort"); + + $this->content_obj->setData($sort); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + } + + $this->pg_obj->addHierIDs(); + $form->setValuesByPost(); + return $this->edit($form); + } +} diff --git a/Modules/Portfolio/classes/class.ilPDPortfolioBlockGUI.php b/Modules/Portfolio/classes/class.ilPDPortfolioBlockGUI.php index a2476d1344491755fcf2d46f9402ba0649377ee6..1477befbc4fc0ccf5306fc88b8fcc9cbb532f633 100644 --- a/Modules/Portfolio/classes/class.ilPDPortfolioBlockGUI.php +++ b/Modules/Portfolio/classes/class.ilPDPortfolioBlockGUI.php @@ -13,193 +13,180 @@ include_once 'Services/Block/classes/class.ilBlockGUI.php'; */ class ilPDPortfolioBlockGUI extends ilBlockGUI { - /** - * @var ilSetting - */ - protected $settings; - - static $block_type = 'pdportf'; - protected $default_portfolio = 0; - - /** - * Constructor - */ - public function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $this->settings = $DIC->settings(); - $this->user = $DIC->user(); - - parent::__construct(); - - $this->setLimit(5); - $this->setAvailableDetailLevels(2); - } - - /** - * @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() - { - switch($_GET['cmd']) - { - case '...': - return IL_SCREEN_CENTER; - break; - - default: - return IL_SCREEN_SIDE; - break; - } - } - - /** - * Execute command - */ - public function executeCommand() - { - $ilCtrl = $this->ctrl; - - $cmd = $ilCtrl->getCmd('getHTML'); - - return $this->$cmd(); - } - - /** - * Execute command - */ - public function getHTML() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilSetting = $this->settings; - $ilUser = $this->user; - - if (!$ilSetting->get('user_portfolios')) - { - return ''; - } - - if($this->getCurrentDetailLevel() == 0) - { - return ''; - } - else - { - include_once("./Modules/Portfolio/classes/class.ilObjPortfolio.php"); - $this->default_portfolio = ilObjPortfolio::getDefaultPortfolio($ilUser->getId()); - - $lng->loadLanguageModule("prtf"); - $this->setTitle($lng->txt('prtf_tab_portfolios')); - $this->addBlockCommand($ilCtrl->getLinkTargetByClass(array("ilpersonaldesktopgui", "ilportfoliorepositorygui"), ""), - $lng->txt("prtf_manage_portfolios")); - $this->addBlockCommand($ilCtrl->getLinkTargetByClass(array("ilpersonaldesktopgui", "ilportfoliorepositorygui", "ilobjportfoliogui"), "create"), - $lng->txt("prtf_add_portfolio")); - - $html = parent::getHTML(); - return $html; - } - } - - /** - * Fill data section - */ - public function fillDataSection() - { - $ilUser = $this->user; - - include_once "Modules/Portfolio/classes/class.ilObjPortfolio.php"; - $data = ilObjPortfolio::getPortfoliosOfUser($ilUser->getId()); - $this->setData($data); - - if($this->getCurrentDetailLevel() > 1 && count($this->getData()) > 0) - { - $this->setRowTemplate("tpl.pd_portf_block_row.html", "Modules/Portfolio"); - if($this->getCurrentDetailLevel() > 2) - { - $this->setColSpan(2); - } - parent::fillDataSection(); - } - else - { - $this->setEnableNumInfo(false); - if (count($this->getData()) == 0) - { - $this->setEnableDetailRow(false); - } - $this->setDataSection($this->getOverview()); - } - } - - /** - * get flat bookmark list for personal desktop - */ - public function fillRow($p) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if($this->getCurrentDetailLevel() > 1) - { - $ilCtrl->setParameterByClass("ilobjportfoliogui", "prt_id", $p["id"]); - $this->tpl->setVariable("HREF", $ilCtrl->getLinkTargetByClass(array("ilpersonaldesktopgui", "ilportfoliorepositorygui", "ilobjportfoliogui"), "preview")); - $this->tpl->setVariable("TITLE", trim($p["title"])); - - if ($this->default_portfolio == $p["id"]) - { - // #16490 - $this->tpl->setVariable("DESC", $lng->txt("prtf_default_portfolio")); - } - - $ilCtrl->setParameterByClass("ilobjportfoliogui", "prt_id", ""); - } - } - - /** - * Get overview. - */ - protected function getOverview() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if (count($this->getData()) == 0) - { - // ilias.php?cmd=create&cmdClass=ilobjportfoliogui&cmdNode=5f:o8:oh&baseClass=ilPersonalDesktopGUI - return ''; - } - else - { - $t = (count($this->getData()) == 1) - ? $lng->txt("obj_prtf") - : $lng->txt("prtf_portfolios"); - return '"; - } - } - + /** + * @var ilSetting + */ + protected $settings; + + public static $block_type = 'pdportf'; + protected $default_portfolio = 0; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->settings = $DIC->settings(); + $this->user = $DIC->user(); + + parent::__construct(); + + $this->setLimit(5); + $this->setAvailableDetailLevels(2); + } + + /** + * @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() + { + switch ($_GET['cmd']) { + case '...': + return IL_SCREEN_CENTER; + break; + + default: + return IL_SCREEN_SIDE; + break; + } + } + + /** + * Execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $cmd = $ilCtrl->getCmd('getHTML'); + + return $this->$cmd(); + } + + /** + * Execute command + */ + public function getHTML() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilSetting = $this->settings; + $ilUser = $this->user; + + if (!$ilSetting->get('user_portfolios')) { + return ''; + } + + if ($this->getCurrentDetailLevel() == 0) { + return ''; + } else { + include_once("./Modules/Portfolio/classes/class.ilObjPortfolio.php"); + $this->default_portfolio = ilObjPortfolio::getDefaultPortfolio($ilUser->getId()); + + $lng->loadLanguageModule("prtf"); + $this->setTitle($lng->txt('prtf_tab_portfolios')); + $this->addBlockCommand( + $ilCtrl->getLinkTargetByClass(array("ilpersonaldesktopgui", "ilportfoliorepositorygui"), ""), + $lng->txt("prtf_manage_portfolios") + ); + $this->addBlockCommand( + $ilCtrl->getLinkTargetByClass(array("ilpersonaldesktopgui", "ilportfoliorepositorygui", "ilobjportfoliogui"), "create"), + $lng->txt("prtf_add_portfolio") + ); + + $html = parent::getHTML(); + return $html; + } + } + + /** + * Fill data section + */ + public function fillDataSection() + { + $ilUser = $this->user; + + include_once "Modules/Portfolio/classes/class.ilObjPortfolio.php"; + $data = ilObjPortfolio::getPortfoliosOfUser($ilUser->getId()); + $this->setData($data); + + if ($this->getCurrentDetailLevel() > 1 && count($this->getData()) > 0) { + $this->setRowTemplate("tpl.pd_portf_block_row.html", "Modules/Portfolio"); + if ($this->getCurrentDetailLevel() > 2) { + $this->setColSpan(2); + } + parent::fillDataSection(); + } else { + $this->setEnableNumInfo(false); + if (count($this->getData()) == 0) { + $this->setEnableDetailRow(false); + } + $this->setDataSection($this->getOverview()); + } + } + + /** + * get flat bookmark list for personal desktop + */ + public function fillRow($p) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if ($this->getCurrentDetailLevel() > 1) { + $ilCtrl->setParameterByClass("ilobjportfoliogui", "prt_id", $p["id"]); + $this->tpl->setVariable("HREF", $ilCtrl->getLinkTargetByClass(array("ilpersonaldesktopgui", "ilportfoliorepositorygui", "ilobjportfoliogui"), "preview")); + $this->tpl->setVariable("TITLE", trim($p["title"])); + + if ($this->default_portfolio == $p["id"]) { + // #16490 + $this->tpl->setVariable("DESC", $lng->txt("prtf_default_portfolio")); + } + + $ilCtrl->setParameterByClass("ilobjportfoliogui", "prt_id", ""); + } + } + + /** + * Get overview. + */ + protected function getOverview() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if (count($this->getData()) == 0) { + // ilias.php?cmd=create&cmdClass=ilobjportfoliogui&cmdNode=5f:o8:oh&baseClass=ilPersonalDesktopGUI + return ''; + } else { + $t = (count($this->getData()) == 1) + ? $lng->txt("obj_prtf") + : $lng->txt("prtf_portfolios"); + return '"; + } + } } -?> \ No newline at end of file diff --git a/Modules/Portfolio/classes/class.ilPortfolioAccessHandler.php b/Modules/Portfolio/classes/class.ilPortfolioAccessHandler.php index a05a79729710083e983832e049c03f7c13a10403..3224b9134a6260d461ecc023d455ef920e186fdc 100644 --- a/Modules/Portfolio/classes/class.ilPortfolioAccessHandler.php +++ b/Modules/Portfolio/classes/class.ilPortfolioAccessHandler.php @@ -1,668 +1,616 @@ - - * @version $Id: class.ilPersonalDesktopGUI.php 26976 2010-12-16 13:24:38Z akill $ - * - * @ingroup ModulesPortfolio - */ -class ilPortfolioAccessHandler implements ilWACCheckingClass -{ - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilRbacReview - */ - protected $rbacreview; - - /** - * @var ilSetting - */ - protected $settings; - - /** - * @var ilDB - */ - protected $db; - - /** - * @var ilAccessHandler - */ - protected $access; - - public function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - $this->rbacreview = $DIC->rbac()->review(); - $this->settings = $DIC->settings(); - $this->db = $DIC->database(); - $this->access = $DIC->access(); - $lng = $DIC->language(); - $lng->loadLanguageModule("wsp"); - } - - /** - * check access for an object - * - * @param string $a_permission - * @param string $a_cmd - * @param int $a_node_id - * @param string $a_type (optional) - * @return bool - */ - public function checkAccess($a_permission, $a_cmd, $a_node_id, $a_type = "") - { - $ilUser = $this->user; - - return $this->checkAccessOfUser($ilUser->getId(),$a_permission, $a_cmd, $a_node_id, $a_type); - } - - /** - * check access for an object - * - * @param integer $a_user_id - * @param string $a_permission - * @param string $a_cmd - * @param int $a_node_id - * @param string $a_type (optional) - * @return bool - */ - public function checkAccessOfUser($a_user_id, $a_permission, $a_cmd, $a_node_id, $a_type = "") - { - $rbacreview = $this->rbacreview; - $ilUser = $this->user; - $ilSetting = $this->settings; - - // #20310 - if(!$ilSetting->get("enable_global_profiles") && $ilUser->getId() == ANONYMOUS_USER_ID) - { - return false; - } - - // #12059 - if (!$ilSetting->get('user_portfolios')) - { - return false; - } - - // :TODO: create permission for parent node with type ?! - - $pf = new ilObjPortfolio($a_node_id, false); - if(!$pf->getId()) - { - return false; - } - - // portfolio owner has all rights - if($pf->getOwner() == $a_user_id) - { - return true; - } - - // #11921 - if(!$pf->isOnline()) - { - return false; - } - - // other users can only read - if($a_permission == "read" || $a_permission == "visible") - { - // get all objects with explicit permission - $objects = self::_getPermissions($a_node_id); - if($objects) - { - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessGUI.php"; - - // check if given user is member of object or has role - foreach($objects as $obj_id) - { - switch($obj_id) - { - case ilWorkspaceAccessGUI::PERMISSION_ALL: - return true; - - case ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD: - // check against input kept in session - if(self::getSharedNodePassword($a_node_id) == self::getSharedSessionPassword($a_node_id) || - $a_permission == "visible") - { - return true; - } - break; - - case ilWorkspaceAccessGUI::PERMISSION_REGISTERED: - if($ilUser->getId() != ANONYMOUS_USER_ID) - { - return true; - } - break; - - default: - switch(ilObject::_lookupType($obj_id)) - { - case "grp": - // member of group? - if(ilGroupParticipants::_getInstanceByObjId($obj_id)->isAssigned($a_user_id)) - { - return true; - } - break; - - case "crs": - // member of course? - if(ilCourseParticipants::_getInstanceByObjId($obj_id)->isAssigned($a_user_id)) - { - return true; - } - break; - - case "role": - // has role? - if($rbacreview->isAssigned($a_user_id, $obj_id)) - { - return true; - } - break; - - case "usr": - // direct assignment - if($a_user_id == $obj_id) - { - return true; - } - break; - } - break; - } - } - } - } - - return false; - } - - /** - * Set permissions after creating node/object - * - * @param int $a_parent_node_id - * @param int $a_node_id - */ - public function setPermissions($a_parent_node_id, $a_node_id) - { - // nothing to do as owner has irrefutable rights to any portfolio object - } - - /** - * Add permission to node for object - * - * @param int $a_node_id - * @param int $a_object_id - * @param string $a_extended_data - */ - public function addPermission($a_node_id, $a_object_id, $a_extended_data = null) - { - $ilDB = $this->db; - $ilUser = $this->user; - - // current owner must not be added - if($a_object_id == $ilUser->getId()) - { - return; - } - - $ilDB->manipulate("INSERT INTO usr_portf_acl (node_id, object_id, extended_data, tstamp)". - " VALUES (".$ilDB->quote($a_node_id, "integer").", ". - $ilDB->quote($a_object_id, "integer").",". - $ilDB->quote($a_extended_data, "text").",". - $ilDB->quote(time(), "integer").")"); - - // portfolio as profile - $this->syncProfile($a_node_id); - } - - /** - * Remove permission[s] (for object) to node - * - * @param int $a_node_id - * @param int $a_object_id - */ - public function removePermission($a_node_id, $a_object_id = null) - { - $ilDB = $this->db; - - $query = "DELETE FROM usr_portf_acl". - " WHERE node_id = ".$ilDB->quote($a_node_id, "integer"); - - if($a_object_id) - { - $query .= " AND object_id = ".$ilDB->quote($a_object_id, "integer"); - } - - $ilDB->manipulate($query); - - // portfolio as profile - $this->syncProfile($a_node_id); - } - - /** - * Get all permissions to node - * - * @param int $a_node_id - * @return array - */ - public function getPermissions($a_node_id) - { - return self::_getPermissions($a_node_id); - } - - /** - * Get all permissions to node - * - * @param int $a_node_id - * @return array - */ - public static function _getPermissions($a_node_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT object_id FROM usr_portf_acl". - " WHERE node_id = ".$ilDB->quote($a_node_id, "integer")); - $res = array(); - while($row = $ilDB->fetchAssoc($set)) - { - $res[] = $row["object_id"]; - } - return $res; - } - - public function hasRegisteredPermission($a_node_id) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT object_id FROM usr_portf_acl". - " WHERE node_id = ".$ilDB->quote($a_node_id, "integer"). - " AND object_id = ".$ilDB->quote(ilWorkspaceAccessGUI::PERMISSION_REGISTERED, "integer")); - return (bool)$ilDB->numRows($set); - } - - public function hasGlobalPermission($a_node_id) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT object_id FROM usr_portf_acl". - " WHERE node_id = ".$ilDB->quote($a_node_id, "integer"). - " AND object_id = ".$ilDB->quote(ilWorkspaceAccessGUI::PERMISSION_ALL, "integer")); - return (bool)$ilDB->numRows($set); - } - - public function hasGlobalPasswordPermission($a_node_id) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT object_id FROM usr_portf_acl". - " WHERE node_id = ".$ilDB->quote($a_node_id, "integer"). - " AND object_id = ".$ilDB->quote(ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD, "integer")); - return (bool)$ilDB->numRows($set); - } - - public function getObjectsIShare($a_online_only = true) - { - $ilDB = $this->db; - $ilUser = $this->user; - - $res = array(); - - $sql = "SELECT obj.obj_id". - " FROM object_data obj". - " JOIN usr_portfolio prtf ON (prtf.id = obj.obj_id)". - " JOIN usr_portf_acl acl ON (acl.node_id = obj.obj_id)". - " WHERE obj.owner = ".$ilDB->quote($ilUser->getId(), "integer"); - - if($a_online_only) - { - $sql .= " AND prtf.is_online = ".$ilDB->quote(1, "integer"); - } - - $set = $ilDB->query($sql); - while ($row = $ilDB->fetchAssoc($set)) - { - $res[] = $row["obj_id"]; - } - - return $res; - } - - public static function getPossibleSharedTargets() - { - global $DIC; - - $ilUser = $DIC->user(); - - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessGUI.php"; - include_once "Services/Membership/classes/class.ilParticipants.php"; - $grp_ids = ilParticipants::_getMembershipByType($ilUser->getId(), "grp"); - $crs_ids = ilParticipants::_getMembershipByType($ilUser->getId(), "crs"); - - $obj_ids = array_merge($grp_ids, $crs_ids); - $obj_ids[] = $ilUser->getId(); - $obj_ids[] = ilWorkspaceAccessGUI::PERMISSION_REGISTERED; - $obj_ids[] = ilWorkspaceAccessGUI::PERMISSION_ALL; - $obj_ids[] = ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD; - - return $obj_ids; - } - - public function getSharedOwners() - { - $ilUser = $this->user; - $ilDB = $this->db; - - $obj_ids = $this->getPossibleSharedTargets(); - - $user_ids = array(); - $set = $ilDB->query("SELECT DISTINCT(obj.owner), u.lastname, u.firstname, u.title". - " FROM object_data obj". - " JOIN usr_portfolio prtf ON (prtf.id = obj.obj_id)". - " JOIN usr_portf_acl acl ON (acl.node_id = obj.obj_id)". - " JOIN usr_data u on (u.usr_id = obj.owner)". - " WHERE ".$ilDB->in("acl.object_id", $obj_ids, "", "integer"). - " AND obj.owner <> ".$ilDB->quote($ilUser->getId(), "integer"). - " AND prtf.is_online = ".$ilDB->quote(1, "integer"). - " ORDER BY u.lastname, u.firstname, u.title"); - while ($row = $ilDB->fetchAssoc($set)) - { - $user_ids[$row["owner"]] = $row["lastname"].", ".$row["firstname"]; - if($row["title"]) - { - $user_ids[$row["owner"]] .= ", ".$row["title"]; - } - } - - return $user_ids; - } - - public function getSharedObjects($a_owner_id) - { - $ilDB = $this->db; - - $obj_ids = $this->getPossibleSharedTargets(); - - $res = array(); - $set = $ilDB->query("SELECT obj.obj_id, obj.owner". - " FROM object_data obj". - " JOIN usr_portfolio prtf ON (prtf.id = obj.obj_id)". - " JOIN usr_portf_acl acl ON (acl.node_id = obj.obj_id)". - " WHERE ".$ilDB->in("acl.object_id", $obj_ids, "", "integer"). - " AND obj.owner = ".$ilDB->quote($a_owner_id, "integer"). - " AND prtf.is_online = ".$ilDB->quote(1, "integer")); - while ($row = $ilDB->fetchAssoc($set)) - { - $res[$row["obj_id"]] = $row["obj_id"]; - } - - return $res; - } - - public function getShardObjectsDataForUserIds(array $a_owner_ids) - { - $ilDB = $this->db; - - $obj_ids = $this->getPossibleSharedTargets(); - - $res = array(); - - $set = $ilDB->query("SELECT obj.obj_id, obj.owner, obj.title". - " FROM object_data obj". - " JOIN usr_portfolio prtf ON (prtf.id = obj.obj_id)". - " JOIN usr_portf_acl acl ON (acl.node_id = obj.obj_id)". - " WHERE ".$ilDB->in("acl.object_id", $obj_ids, "", "integer"). - " AND ".$ilDB->in("obj.owner", $a_owner_ids, "", "integer"). - " AND prtf.is_online = ".$ilDB->quote(1, "integer")); - while ($row = $ilDB->fetchAssoc($set)) - { - $res[$row["owner"]][$row["obj_id"]] = $row["title"]; - } - - return $res; - } - - public function findSharedObjects(array $a_filter = null, array $a_crs_ids = null, array $a_grp_ids = null) - { - $ilDB = $this->db; - $ilUser = $this->user; - if(!$a_filter["acl_type"]) - { - $obj_ids = $this->getPossibleSharedTargets(); - } - else - { - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessGUI.php"; - - switch($a_filter["acl_type"]) - { - case "all": - $obj_ids = array(ilWorkspaceAccessGUI::PERMISSION_ALL); - break; - - case "password": - $obj_ids = array(ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD); - break; - - case "registered": - $obj_ids = array(ilWorkspaceAccessGUI::PERMISSION_REGISTERED); - break; - - case "course": - $obj_ids = $a_crs_ids; - break; - - case "group": - $obj_ids = $a_grp_ids; - break; - - case "user": - $obj_ids = array($ilUser->getId()); - break; - } - } - - $res = array(); - - $sql = "SELECT obj.obj_id,obj.title,obj.owner". - ",acl.object_id acl_type, acl.tstamp acl_date". - " FROM object_data obj". - " JOIN usr_portfolio prtf ON (prtf.id = obj.obj_id)". - " JOIN usr_portf_acl acl ON (acl.node_id = obj.obj_id)". - " WHERE ".$ilDB->in("acl.object_id", $obj_ids, "", "integer"). - " AND obj.owner <> ".$ilDB->quote($ilUser->getId(), "integer"). - " AND obj.type = ".$ilDB->quote("prtf", "text"). - " AND prtf.is_online = ".$ilDB->quote(1, "integer"); - - if($a_filter["title"] && strlen($a_filter["title"]) >= 3) - { - $sql .= " AND ".$ilDB->like("obj.title", "text", "%".$a_filter["title"]."%"); - } - if($a_filter["user"] && strlen($a_filter["user"]) >= 3) - { - $usr_ids = array(); - $set = $ilDB->query("SELECT usr_id FROM usr_data". - " WHERE (".$ilDB->like("login", "text", "%".$a_filter["user"]."%")." ". - "OR ".$ilDB->like("firstname", "text", "%".$a_filter["user"]."%")." ". - "OR ".$ilDB->like("lastname", "text", "%".$a_filter["user"]."%")." ". - "OR ".$ilDB->like("email", "text", "%".$a_filter["user"]."%").")"); - while($row = $ilDB->fetchAssoc($set)) - { - $usr_ids[] = $row["usr_id"]; - } - if(!sizeof($usr_ids)) - { - return; - } - $sql .= " AND ".$ilDB->in("obj.owner", $usr_ids, "", "integer"); - } - - if($a_filter["acl_date"]) - { - $dt = $a_filter["acl_date"]->get(IL_CAL_DATE); - $dt = new ilDateTime($dt." 00:00:00", IL_CAL_DATETIME); - $sql .= " AND acl.tstamp > ".$ilDB->quote($dt->get(IL_CAL_UNIX), "integer"); - } - - if($a_filter["crsgrp"]) - { - include_once "Services/Membership/classes/class.ilParticipants.php"; - $part = ilParticipants::getInstanceByObjId($a_filter['crsgrp']); - $part = $part->getParticipants(); - if(!sizeof($part)) - { - return; - } - $sql .= " AND ".$ilDB->in("obj.owner", $part, "", "integer"); - } - - // we use the oldest share date - $sql .= " ORDER BY acl.tstamp"; - - $set = $ilDB->query($sql); - while ($row = $ilDB->fetchAssoc($set)) - { - if(!isset($res[$row["obj_id"]])) - { - $row["acl_type"] = array($row["acl_type"]); - $res[$row["obj_id"]] = $row; - } - else - { - $res[$row["obj_id"]]["acl_type"][] = $row["acl_type"]; - } - } - - return $res; - } - - public static function getSharedNodePassword($a_node_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessGUI.php"; - - $set = $ilDB->query("SELECT extended_data FROM usr_portf_acl". - " WHERE node_id = ".$ilDB->quote($a_node_id, "integer"). - " AND object_id = ".$ilDB->quote(ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD, "integer")); - $res = $ilDB->fetchAssoc($set); - if($res) - { - return $res["extended_data"]; - } - } - - public static function keepSharedSessionPassword($a_node_id, $a_password) - { - $_SESSION["ilshpw_".$a_node_id] = $a_password; - } - - public static function getSharedSessionPassword($a_node_id) - { - return $_SESSION["ilshpw_".$a_node_id]; - } - - protected function syncProfile($a_node_id) - { - $ilUser = $this->user; - - // #12845 - include_once "Modules/Portfolio/classes/class.ilObjPortfolio.php"; - if(ilObjPortfolio::getDefaultPortfolio($ilUser->getId()) == $a_node_id) - { - $has_registered = $this->hasRegisteredPermission($a_node_id); - $has_global = $this->hasGlobalPermission($a_node_id); - - // not published anymore - remove portfolio as profile - if(!$has_registered && !$has_global) - { - $ilUser->setPref("public_profile", "n"); - $ilUser->writePrefs(); - ilObjPortfolio::setUserDefault($ilUser->getId()); - } - // adapt profile setting - else - { - $new_pref = "y"; - if($has_global) - { - $new_pref = "g"; - } - if($ilUser->getPref("public_profile") != $new_pref) - { - $ilUser->setPref("public_profile", $new_pref); - $ilUser->writePrefs(); - } - } - } - } - - - /** - * @param ilWACPath $ilWACPath - * - * @return bool - */ - public function canBeDelivered(ilWACPath $ilWACPath) { - $ilUser = $this->user; - $ilAccess = $this->access; - - if (preg_match("/\\/prtf_([\\d]*)\\//uism", $ilWACPath->getPath(), $results)) - { - // portfolio (custom) - $obj_id = $results[1]; - if(ilObject::_lookupType($obj_id) == "prtf") - { - if ($this->checkAccessOfUser($ilUser->getId(), "read", "view", $obj_id, "prtf")) { - return true; - } - } - // portfolio template (RBAC) - else - { - $ref_ids = ilObject::_getAllReferences($obj_id); - foreach($ref_ids as $ref_id) - { - if ($ilAccess->checkAccessOfUser($ilUser->getId(), "read", "view", $ref_id, "prtt", $obj_id)) - { - return true; - } - } - } - } - - return false; - } -} - -?> \ No newline at end of file + + * @version $Id: class.ilPersonalDesktopGUI.php 26976 2010-12-16 13:24:38Z akill $ + * + * @ingroup ModulesPortfolio + */ +class ilPortfolioAccessHandler implements ilWACCheckingClass +{ + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilRbacReview + */ + protected $rbacreview; + + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var ilDB + */ + protected $db; + + /** + * @var ilAccessHandler + */ + protected $access; + + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + $this->rbacreview = $DIC->rbac()->review(); + $this->settings = $DIC->settings(); + $this->db = $DIC->database(); + $this->access = $DIC->access(); + $lng = $DIC->language(); + $lng->loadLanguageModule("wsp"); + } + + /** + * check access for an object + * + * @param string $a_permission + * @param string $a_cmd + * @param int $a_node_id + * @param string $a_type (optional) + * @return bool + */ + public function checkAccess($a_permission, $a_cmd, $a_node_id, $a_type = "") + { + $ilUser = $this->user; + + return $this->checkAccessOfUser($ilUser->getId(), $a_permission, $a_cmd, $a_node_id, $a_type); + } + + /** + * check access for an object + * + * @param integer $a_user_id + * @param string $a_permission + * @param string $a_cmd + * @param int $a_node_id + * @param string $a_type (optional) + * @return bool + */ + public function checkAccessOfUser($a_user_id, $a_permission, $a_cmd, $a_node_id, $a_type = "") + { + $rbacreview = $this->rbacreview; + $ilUser = $this->user; + $ilSetting = $this->settings; + + // #20310 + if (!$ilSetting->get("enable_global_profiles") && $ilUser->getId() == ANONYMOUS_USER_ID) { + return false; + } + + // #12059 + if (!$ilSetting->get('user_portfolios')) { + return false; + } + + // :TODO: create permission for parent node with type ?! + + $pf = new ilObjPortfolio($a_node_id, false); + if (!$pf->getId()) { + return false; + } + + // portfolio owner has all rights + if ($pf->getOwner() == $a_user_id) { + return true; + } + + // #11921 + if (!$pf->isOnline()) { + return false; + } + + // other users can only read + if ($a_permission == "read" || $a_permission == "visible") { + // get all objects with explicit permission + $objects = self::_getPermissions($a_node_id); + if ($objects) { + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessGUI.php"; + + // check if given user is member of object or has role + foreach ($objects as $obj_id) { + switch ($obj_id) { + case ilWorkspaceAccessGUI::PERMISSION_ALL: + return true; + + case ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD: + // check against input kept in session + if (self::getSharedNodePassword($a_node_id) == self::getSharedSessionPassword($a_node_id) || + $a_permission == "visible") { + return true; + } + break; + + case ilWorkspaceAccessGUI::PERMISSION_REGISTERED: + if ($ilUser->getId() != ANONYMOUS_USER_ID) { + return true; + } + break; + + default: + switch (ilObject::_lookupType($obj_id)) { + case "grp": + // member of group? + if (ilGroupParticipants::_getInstanceByObjId($obj_id)->isAssigned($a_user_id)) { + return true; + } + break; + + case "crs": + // member of course? + if (ilCourseParticipants::_getInstanceByObjId($obj_id)->isAssigned($a_user_id)) { + return true; + } + break; + + case "role": + // has role? + if ($rbacreview->isAssigned($a_user_id, $obj_id)) { + return true; + } + break; + + case "usr": + // direct assignment + if ($a_user_id == $obj_id) { + return true; + } + break; + } + break; + } + } + } + } + + return false; + } + + /** + * Set permissions after creating node/object + * + * @param int $a_parent_node_id + * @param int $a_node_id + */ + public function setPermissions($a_parent_node_id, $a_node_id) + { + // nothing to do as owner has irrefutable rights to any portfolio object + } + + /** + * Add permission to node for object + * + * @param int $a_node_id + * @param int $a_object_id + * @param string $a_extended_data + */ + public function addPermission($a_node_id, $a_object_id, $a_extended_data = null) + { + $ilDB = $this->db; + $ilUser = $this->user; + + // current owner must not be added + if ($a_object_id == $ilUser->getId()) { + return; + } + + $ilDB->manipulate("INSERT INTO usr_portf_acl (node_id, object_id, extended_data, tstamp)" . + " VALUES (" . $ilDB->quote($a_node_id, "integer") . ", " . + $ilDB->quote($a_object_id, "integer") . "," . + $ilDB->quote($a_extended_data, "text") . "," . + $ilDB->quote(time(), "integer") . ")"); + + // portfolio as profile + $this->syncProfile($a_node_id); + } + + /** + * Remove permission[s] (for object) to node + * + * @param int $a_node_id + * @param int $a_object_id + */ + public function removePermission($a_node_id, $a_object_id = null) + { + $ilDB = $this->db; + + $query = "DELETE FROM usr_portf_acl" . + " WHERE node_id = " . $ilDB->quote($a_node_id, "integer"); + + if ($a_object_id) { + $query .= " AND object_id = " . $ilDB->quote($a_object_id, "integer"); + } + + $ilDB->manipulate($query); + + // portfolio as profile + $this->syncProfile($a_node_id); + } + + /** + * Get all permissions to node + * + * @param int $a_node_id + * @return array + */ + public function getPermissions($a_node_id) + { + return self::_getPermissions($a_node_id); + } + + /** + * Get all permissions to node + * + * @param int $a_node_id + * @return array + */ + public static function _getPermissions($a_node_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query("SELECT object_id FROM usr_portf_acl" . + " WHERE node_id = " . $ilDB->quote($a_node_id, "integer")); + $res = array(); + while ($row = $ilDB->fetchAssoc($set)) { + $res[] = $row["object_id"]; + } + return $res; + } + + public function hasRegisteredPermission($a_node_id) + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT object_id FROM usr_portf_acl" . + " WHERE node_id = " . $ilDB->quote($a_node_id, "integer") . + " AND object_id = " . $ilDB->quote(ilWorkspaceAccessGUI::PERMISSION_REGISTERED, "integer")); + return (bool) $ilDB->numRows($set); + } + + public function hasGlobalPermission($a_node_id) + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT object_id FROM usr_portf_acl" . + " WHERE node_id = " . $ilDB->quote($a_node_id, "integer") . + " AND object_id = " . $ilDB->quote(ilWorkspaceAccessGUI::PERMISSION_ALL, "integer")); + return (bool) $ilDB->numRows($set); + } + + public function hasGlobalPasswordPermission($a_node_id) + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT object_id FROM usr_portf_acl" . + " WHERE node_id = " . $ilDB->quote($a_node_id, "integer") . + " AND object_id = " . $ilDB->quote(ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD, "integer")); + return (bool) $ilDB->numRows($set); + } + + public function getObjectsIShare($a_online_only = true) + { + $ilDB = $this->db; + $ilUser = $this->user; + + $res = array(); + + $sql = "SELECT obj.obj_id" . + " FROM object_data obj" . + " JOIN usr_portfolio prtf ON (prtf.id = obj.obj_id)" . + " JOIN usr_portf_acl acl ON (acl.node_id = obj.obj_id)" . + " WHERE obj.owner = " . $ilDB->quote($ilUser->getId(), "integer"); + + if ($a_online_only) { + $sql .= " AND prtf.is_online = " . $ilDB->quote(1, "integer"); + } + + $set = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($set)) { + $res[] = $row["obj_id"]; + } + + return $res; + } + + public static function getPossibleSharedTargets() + { + global $DIC; + + $ilUser = $DIC->user(); + + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessGUI.php"; + include_once "Services/Membership/classes/class.ilParticipants.php"; + $grp_ids = ilParticipants::_getMembershipByType($ilUser->getId(), "grp"); + $crs_ids = ilParticipants::_getMembershipByType($ilUser->getId(), "crs"); + + $obj_ids = array_merge($grp_ids, $crs_ids); + $obj_ids[] = $ilUser->getId(); + $obj_ids[] = ilWorkspaceAccessGUI::PERMISSION_REGISTERED; + $obj_ids[] = ilWorkspaceAccessGUI::PERMISSION_ALL; + $obj_ids[] = ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD; + + return $obj_ids; + } + + public function getSharedOwners() + { + $ilUser = $this->user; + $ilDB = $this->db; + + $obj_ids = $this->getPossibleSharedTargets(); + + $user_ids = array(); + $set = $ilDB->query("SELECT DISTINCT(obj.owner), u.lastname, u.firstname, u.title" . + " FROM object_data obj" . + " JOIN usr_portfolio prtf ON (prtf.id = obj.obj_id)" . + " JOIN usr_portf_acl acl ON (acl.node_id = obj.obj_id)" . + " JOIN usr_data u on (u.usr_id = obj.owner)" . + " WHERE " . $ilDB->in("acl.object_id", $obj_ids, "", "integer") . + " AND obj.owner <> " . $ilDB->quote($ilUser->getId(), "integer") . + " AND prtf.is_online = " . $ilDB->quote(1, "integer") . + " ORDER BY u.lastname, u.firstname, u.title"); + while ($row = $ilDB->fetchAssoc($set)) { + $user_ids[$row["owner"]] = $row["lastname"] . ", " . $row["firstname"]; + if ($row["title"]) { + $user_ids[$row["owner"]] .= ", " . $row["title"]; + } + } + + return $user_ids; + } + + public function getSharedObjects($a_owner_id) + { + $ilDB = $this->db; + + $obj_ids = $this->getPossibleSharedTargets(); + + $res = array(); + $set = $ilDB->query("SELECT obj.obj_id, obj.owner" . + " FROM object_data obj" . + " JOIN usr_portfolio prtf ON (prtf.id = obj.obj_id)" . + " JOIN usr_portf_acl acl ON (acl.node_id = obj.obj_id)" . + " WHERE " . $ilDB->in("acl.object_id", $obj_ids, "", "integer") . + " AND obj.owner = " . $ilDB->quote($a_owner_id, "integer") . + " AND prtf.is_online = " . $ilDB->quote(1, "integer")); + while ($row = $ilDB->fetchAssoc($set)) { + $res[$row["obj_id"]] = $row["obj_id"]; + } + + return $res; + } + + public function getShardObjectsDataForUserIds(array $a_owner_ids) + { + $ilDB = $this->db; + + $obj_ids = $this->getPossibleSharedTargets(); + + $res = array(); + + $set = $ilDB->query("SELECT obj.obj_id, obj.owner, obj.title" . + " FROM object_data obj" . + " JOIN usr_portfolio prtf ON (prtf.id = obj.obj_id)" . + " JOIN usr_portf_acl acl ON (acl.node_id = obj.obj_id)" . + " WHERE " . $ilDB->in("acl.object_id", $obj_ids, "", "integer") . + " AND " . $ilDB->in("obj.owner", $a_owner_ids, "", "integer") . + " AND prtf.is_online = " . $ilDB->quote(1, "integer")); + while ($row = $ilDB->fetchAssoc($set)) { + $res[$row["owner"]][$row["obj_id"]] = $row["title"]; + } + + return $res; + } + + public function findSharedObjects(array $a_filter = null, array $a_crs_ids = null, array $a_grp_ids = null) + { + $ilDB = $this->db; + $ilUser = $this->user; + if (!$a_filter["acl_type"]) { + $obj_ids = $this->getPossibleSharedTargets(); + } else { + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessGUI.php"; + + switch ($a_filter["acl_type"]) { + case "all": + $obj_ids = array(ilWorkspaceAccessGUI::PERMISSION_ALL); + break; + + case "password": + $obj_ids = array(ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD); + break; + + case "registered": + $obj_ids = array(ilWorkspaceAccessGUI::PERMISSION_REGISTERED); + break; + + case "course": + $obj_ids = $a_crs_ids; + break; + + case "group": + $obj_ids = $a_grp_ids; + break; + + case "user": + $obj_ids = array($ilUser->getId()); + break; + } + } + + $res = array(); + + $sql = "SELECT obj.obj_id,obj.title,obj.owner" . + ",acl.object_id acl_type, acl.tstamp acl_date" . + " FROM object_data obj" . + " JOIN usr_portfolio prtf ON (prtf.id = obj.obj_id)" . + " JOIN usr_portf_acl acl ON (acl.node_id = obj.obj_id)" . + " WHERE " . $ilDB->in("acl.object_id", $obj_ids, "", "integer") . + " AND obj.owner <> " . $ilDB->quote($ilUser->getId(), "integer") . + " AND obj.type = " . $ilDB->quote("prtf", "text") . + " AND prtf.is_online = " . $ilDB->quote(1, "integer"); + + if ($a_filter["title"] && strlen($a_filter["title"]) >= 3) { + $sql .= " AND " . $ilDB->like("obj.title", "text", "%" . $a_filter["title"] . "%"); + } + if ($a_filter["user"] && strlen($a_filter["user"]) >= 3) { + $usr_ids = array(); + $set = $ilDB->query("SELECT usr_id FROM usr_data" . + " WHERE (" . $ilDB->like("login", "text", "%" . $a_filter["user"] . "%") . " " . + "OR " . $ilDB->like("firstname", "text", "%" . $a_filter["user"] . "%") . " " . + "OR " . $ilDB->like("lastname", "text", "%" . $a_filter["user"] . "%") . " " . + "OR " . $ilDB->like("email", "text", "%" . $a_filter["user"] . "%") . ")"); + while ($row = $ilDB->fetchAssoc($set)) { + $usr_ids[] = $row["usr_id"]; + } + if (!sizeof($usr_ids)) { + return; + } + $sql .= " AND " . $ilDB->in("obj.owner", $usr_ids, "", "integer"); + } + + if ($a_filter["acl_date"]) { + $dt = $a_filter["acl_date"]->get(IL_CAL_DATE); + $dt = new ilDateTime($dt . " 00:00:00", IL_CAL_DATETIME); + $sql .= " AND acl.tstamp > " . $ilDB->quote($dt->get(IL_CAL_UNIX), "integer"); + } + + if ($a_filter["crsgrp"]) { + include_once "Services/Membership/classes/class.ilParticipants.php"; + $part = ilParticipants::getInstanceByObjId($a_filter['crsgrp']); + $part = $part->getParticipants(); + if (!sizeof($part)) { + return; + } + $sql .= " AND " . $ilDB->in("obj.owner", $part, "", "integer"); + } + + // we use the oldest share date + $sql .= " ORDER BY acl.tstamp"; + + $set = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($set)) { + if (!isset($res[$row["obj_id"]])) { + $row["acl_type"] = array($row["acl_type"]); + $res[$row["obj_id"]] = $row; + } else { + $res[$row["obj_id"]]["acl_type"][] = $row["acl_type"]; + } + } + + return $res; + } + + public static function getSharedNodePassword($a_node_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessGUI.php"; + + $set = $ilDB->query("SELECT extended_data FROM usr_portf_acl" . + " WHERE node_id = " . $ilDB->quote($a_node_id, "integer") . + " AND object_id = " . $ilDB->quote(ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD, "integer")); + $res = $ilDB->fetchAssoc($set); + if ($res) { + return $res["extended_data"]; + } + } + + public static function keepSharedSessionPassword($a_node_id, $a_password) + { + $_SESSION["ilshpw_" . $a_node_id] = $a_password; + } + + public static function getSharedSessionPassword($a_node_id) + { + return $_SESSION["ilshpw_" . $a_node_id]; + } + + protected function syncProfile($a_node_id) + { + $ilUser = $this->user; + + // #12845 + include_once "Modules/Portfolio/classes/class.ilObjPortfolio.php"; + if (ilObjPortfolio::getDefaultPortfolio($ilUser->getId()) == $a_node_id) { + $has_registered = $this->hasRegisteredPermission($a_node_id); + $has_global = $this->hasGlobalPermission($a_node_id); + + // not published anymore - remove portfolio as profile + if (!$has_registered && !$has_global) { + $ilUser->setPref("public_profile", "n"); + $ilUser->writePrefs(); + ilObjPortfolio::setUserDefault($ilUser->getId()); + } + // adapt profile setting + else { + $new_pref = "y"; + if ($has_global) { + $new_pref = "g"; + } + if ($ilUser->getPref("public_profile") != $new_pref) { + $ilUser->setPref("public_profile", $new_pref); + $ilUser->writePrefs(); + } + } + } + } + + + /** + * @param ilWACPath $ilWACPath + * + * @return bool + */ + public function canBeDelivered(ilWACPath $ilWACPath) + { + $ilUser = $this->user; + $ilAccess = $this->access; + + if (preg_match("/\\/prtf_([\\d]*)\\//uism", $ilWACPath->getPath(), $results)) { + // portfolio (custom) + $obj_id = $results[1]; + if (ilObject::_lookupType($obj_id) == "prtf") { + if ($this->checkAccessOfUser($ilUser->getId(), "read", "view", $obj_id, "prtf")) { + return true; + } + } + // portfolio template (RBAC) + else { + $ref_ids = ilObject::_getAllReferences($obj_id); + foreach ($ref_ids as $ref_id) { + if ($ilAccess->checkAccessOfUser($ilUser->getId(), "read", "view", $ref_id, "prtt", $obj_id)) { + return true; + } + } + } + } + + return false; + } +} diff --git a/Modules/Portfolio/classes/class.ilPortfolioAppEventListener.php b/Modules/Portfolio/classes/class.ilPortfolioAppEventListener.php index cb87e0aa9e3912342916012db6942dce508623e7..ded06d3bf7d3776d6b93cefe1a773a644b2a0106 100644 --- a/Modules/Portfolio/classes/class.ilPortfolioAppEventListener.php +++ b/Modules/Portfolio/classes/class.ilPortfolioAppEventListener.php @@ -9,34 +9,32 @@ */ class ilPortfolioAppEventListener { - public static function handleEvent($component, $event, $parameter) - { - switch ($component) { - case "Services/Object": - switch ($event) { - case "beforeDeletion": - self::beforeDeletion($parameter); - break; - } - break; - } - } + public static function handleEvent($component, $event, $parameter) + { + switch ($component) { + case "Services/Object": + switch ($event) { + case "beforeDeletion": + self::beforeDeletion($parameter); + break; + } + break; + } + } - /** - * @param array $parameter - */ - protected static function beforeDeletion($parameter) - { - if (is_object($parameter["object"])) - { - /** @var ilObject $obj */ - $obj = $parameter["object"]; - if (get_class($obj) == "ilObjBlog") - { - $blog_id = $obj->getId(); - $action = new ilPortfolioPageAction(); - $action->deletePagesOfBlog($blog_id); - } - } - } -} \ No newline at end of file + /** + * @param array $parameter + */ + protected static function beforeDeletion($parameter) + { + if (is_object($parameter["object"])) { + /** @var ilObject $obj */ + $obj = $parameter["object"]; + if (get_class($obj) == "ilObjBlog") { + $blog_id = $obj->getId(); + $action = new ilPortfolioPageAction(); + $action->deletePagesOfBlog($blog_id); + } + } + } +} diff --git a/Modules/Portfolio/classes/class.ilPortfolioDataSet.php b/Modules/Portfolio/classes/class.ilPortfolioDataSet.php index c19945e6f0db74c108ce2e4c05f601fde4f8fef0..c146019203fca5f368a583ae577ca120fddd6aa5 100644 --- a/Modules/Portfolio/classes/class.ilPortfolioDataSet.php +++ b/Modules/Portfolio/classes/class.ilPortfolioDataSet.php @@ -1,238 +1,218 @@ - - * @version $Id$ - * @ingroup ModulesPortfolio - */ -class ilPortfolioDataSet extends ilDataSet -{ - protected $current_portfolio; - - /** - * Get supported versions - */ - public function getSupportedVersions() - { - return array("4.4.0", "5.0.0"); - } - - /** - * Get xml namespace - */ - function getXmlNamespace($a_entity, $a_schema_version) - { - return "http://www.ilias.de/xml/Modules/Portfolio/".$a_entity; - } - - /** - * Get field types for entity - */ - protected function getTypes($a_entity, $a_version) - { - if ($a_entity == "prtt") - { - switch ($a_version) - { - case "4.4.0": - case "5.0.0": - return array( - "Id" => "integer", - "Title" => "text", - "Description" => "text", - "Comments" => "integer", - "BgColor" => "text", - "FontColor" => "text", - "Img" => "text", - "Ppic" => "integer", - "Dir" => "directory" - ); - } - } - - if ($a_entity == "portfolio_page") - { - switch ($a_version) - { - case "4.4.0": - case "5.0.0": - return array( - "Id" => "integer", - "PortfolioId" => "integer", - "Title" => "integer", - "OrderNr" => "integer", - "Type" => "text" - ); - } - } - } - - /** - * Read data - * - * @param - * @return - */ - 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 == "prtt") - { - switch ($a_version) - { - case "4.4.0": - $this->getDirectDataFromQuery("SELECT prtf.id,od.title,od.description,". - "prtf.comments,prtf.bg_color,prtf.font_color,prtf.img,prtf.ppic". - " FROM usr_portfolio prtf". - " JOIN object_data od ON (od.obj_id = prtf.id)". - " WHERE ".$ilDB->in("prtf.id", $a_ids, false, "integer"). - " AND od.type = ".$ilDB->quote("prtt", "text")); - break; - - case "5.0.0": - $this->getDirectDataFromQuery("SELECT prtf.id,od.title,od.description,". - "prtf.bg_color,prtf.font_color,prtf.img,prtf.ppic". - " FROM usr_portfolio prtf". - " JOIN object_data od ON (od.obj_id = prtf.id)". - " WHERE ".$ilDB->in("prtf.id", $a_ids, false, "integer"). - " AND od.type = ".$ilDB->quote("prtt", "text")); - break; - } - } - - if ($a_entity == "portfolio_page") - { - switch ($a_version) - { - case "4.4.0": - case "5.0.0": - $this->getDirectDataFromQuery("SELECT id,portfolio_id,title,order_nr,type". - " FROM usr_portfolio_page". - " WHERE ".$ilDB->in("portfolio_id", $a_ids, false, "integer")); - break; - } - } - } - - /** - * Determine the dependent sets of data - */ - protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) - { - switch ($a_entity) - { - case "prtt": - return array ( - "portfolio_page" => array("ids" => $a_rec["Id"]) - ); - } - return false; - } - - /** - * Get xml record - * - * @param - * @return - */ - function getXmlRecord($a_entity, $a_version, $a_set) - { - if ($a_entity == "prtt") - { - include_once("./Modules/Portfolio/classes/class.ilObjPortfolioTemplate.php"); - $dir = ilObjPortfolioTemplate::initStorage($a_set["Id"]); - $a_set["Dir"] = $dir; - - include_once("./Services/Notes/classes/class.ilNote.php"); - $a_set["Comments"] = ilNote::commentsActivated($a_set["Id"], 0, "prtt"); - } - - return $a_set; - } - - /** - * Import record - * - * @param - * @return - */ - function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) - { - switch ($a_entity) - { - case "prtt": - include_once("./Modules/Portfolio/classes/class.ilObjPortfolioTemplate.php"); - - // container copy - if($new_id = $a_mapping->getMapping("Services/Container", "objs", $a_rec["Id"])) - { - $newObj = ilObjectFactory::getInstanceByObjId($new_id, false); - } - else - { - $newObj = new ilObjPortfolioTemplate(); - $newObj->create(); - } - - $newObj->setTitle($a_rec["Title"]); - $newObj->setDescription($a_rec["Description"]); - $newObj->setPublicComments($a_rec["Comments"]); - $newObj->setBackgroundColor($a_rec["BgColor"]); - $newObj->setFontColor($a_rec["FontColor"]); - $newObj->setProfilePicture($a_rec["Ppic"]); - $newObj->setImage($a_rec["Img"]); - $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 = ilObjPortfolioTemplate::initStorage($newObj->getId()); - ilUtil::rCopy($source_dir, $target_dir); - } - } - - $a_mapping->addMapping("Modules/Portfolio", "prtt", $a_rec["Id"], $newObj->getId()); - $a_mapping->addMapping("Services/Object", "obj", $a_rec["Id"], $newObj->getId()); - break; - - case "portfolio_page": - $prtt_id = (int)$a_mapping->getMapping("Modules/Portfolio", "prtt", $a_rec["PortfolioId"]); - if($prtt_id) - { - include_once("./Modules/Portfolio/classes/class.ilPortfolioTemplatePage.php"); - $newObj = new ilPortfolioTemplatePage(); - $newObj->setPortfolioId($prtt_id); - $newObj->setTitle($a_rec["Title"]); - $newObj->setType($a_rec["Type"]); - $newObj->setOrderNr($a_rec["OrderNr"]); - $newObj->create(true); - - $a_mapping->addMapping("Services/COPage", "pg", "prtt:".$a_rec["Id"], "prtt:".$newObj->getId()); - } - break; - } - } -} - -?> \ No newline at end of file + + * @version $Id$ + * @ingroup ModulesPortfolio + */ +class ilPortfolioDataSet extends ilDataSet +{ + protected $current_portfolio; + + /** + * Get supported versions + */ + public function getSupportedVersions() + { + return array("4.4.0", "5.0.0"); + } + + /** + * Get xml namespace + */ + public function getXmlNamespace($a_entity, $a_schema_version) + { + return "http://www.ilias.de/xml/Modules/Portfolio/" . $a_entity; + } + + /** + * Get field types for entity + */ + protected function getTypes($a_entity, $a_version) + { + if ($a_entity == "prtt") { + switch ($a_version) { + case "4.4.0": + case "5.0.0": + return array( + "Id" => "integer", + "Title" => "text", + "Description" => "text", + "Comments" => "integer", + "BgColor" => "text", + "FontColor" => "text", + "Img" => "text", + "Ppic" => "integer", + "Dir" => "directory" + ); + } + } + + if ($a_entity == "portfolio_page") { + switch ($a_version) { + case "4.4.0": + case "5.0.0": + return array( + "Id" => "integer", + "PortfolioId" => "integer", + "Title" => "integer", + "OrderNr" => "integer", + "Type" => "text" + ); + } + } + } + + /** + * 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 == "prtt") { + switch ($a_version) { + case "4.4.0": + $this->getDirectDataFromQuery("SELECT prtf.id,od.title,od.description," . + "prtf.comments,prtf.bg_color,prtf.font_color,prtf.img,prtf.ppic" . + " FROM usr_portfolio prtf" . + " JOIN object_data od ON (od.obj_id = prtf.id)" . + " WHERE " . $ilDB->in("prtf.id", $a_ids, false, "integer") . + " AND od.type = " . $ilDB->quote("prtt", "text")); + break; + + case "5.0.0": + $this->getDirectDataFromQuery("SELECT prtf.id,od.title,od.description," . + "prtf.bg_color,prtf.font_color,prtf.img,prtf.ppic" . + " FROM usr_portfolio prtf" . + " JOIN object_data od ON (od.obj_id = prtf.id)" . + " WHERE " . $ilDB->in("prtf.id", $a_ids, false, "integer") . + " AND od.type = " . $ilDB->quote("prtt", "text")); + break; + } + } + + if ($a_entity == "portfolio_page") { + switch ($a_version) { + case "4.4.0": + case "5.0.0": + $this->getDirectDataFromQuery("SELECT id,portfolio_id,title,order_nr,type" . + " FROM usr_portfolio_page" . + " WHERE " . $ilDB->in("portfolio_id", $a_ids, false, "integer")); + break; + } + } + } + + /** + * Determine the dependent sets of data + */ + protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) + { + switch ($a_entity) { + case "prtt": + return array( + "portfolio_page" => array("ids" => $a_rec["Id"]) + ); + } + return false; + } + + /** + * Get xml record + * + * @param + * @return + */ + public function getXmlRecord($a_entity, $a_version, $a_set) + { + if ($a_entity == "prtt") { + include_once("./Modules/Portfolio/classes/class.ilObjPortfolioTemplate.php"); + $dir = ilObjPortfolioTemplate::initStorage($a_set["Id"]); + $a_set["Dir"] = $dir; + + include_once("./Services/Notes/classes/class.ilNote.php"); + $a_set["Comments"] = ilNote::commentsActivated($a_set["Id"], 0, "prtt"); + } + + 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 "prtt": + include_once("./Modules/Portfolio/classes/class.ilObjPortfolioTemplate.php"); + + // container copy + if ($new_id = $a_mapping->getMapping("Services/Container", "objs", $a_rec["Id"])) { + $newObj = ilObjectFactory::getInstanceByObjId($new_id, false); + } else { + $newObj = new ilObjPortfolioTemplate(); + $newObj->create(); + } + + $newObj->setTitle($a_rec["Title"]); + $newObj->setDescription($a_rec["Description"]); + $newObj->setPublicComments($a_rec["Comments"]); + $newObj->setBackgroundColor($a_rec["BgColor"]); + $newObj->setFontColor($a_rec["FontColor"]); + $newObj->setProfilePicture($a_rec["Ppic"]); + $newObj->setImage($a_rec["Img"]); + $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 = ilObjPortfolioTemplate::initStorage($newObj->getId()); + ilUtil::rCopy($source_dir, $target_dir); + } + } + + $a_mapping->addMapping("Modules/Portfolio", "prtt", $a_rec["Id"], $newObj->getId()); + $a_mapping->addMapping("Services/Object", "obj", $a_rec["Id"], $newObj->getId()); + break; + + case "portfolio_page": + $prtt_id = (int) $a_mapping->getMapping("Modules/Portfolio", "prtt", $a_rec["PortfolioId"]); + if ($prtt_id) { + include_once("./Modules/Portfolio/classes/class.ilPortfolioTemplatePage.php"); + $newObj = new ilPortfolioTemplatePage(); + $newObj->setPortfolioId($prtt_id); + $newObj->setTitle($a_rec["Title"]); + $newObj->setType($a_rec["Type"]); + $newObj->setOrderNr($a_rec["OrderNr"]); + $newObj->create(true); + + $a_mapping->addMapping("Services/COPage", "pg", "prtt:" . $a_rec["Id"], "prtt:" . $newObj->getId()); + } + break; + } + } +} diff --git a/Modules/Portfolio/classes/class.ilPortfolioDeclarationOfAuthorship.php b/Modules/Portfolio/classes/class.ilPortfolioDeclarationOfAuthorship.php index 41ced4baa663be5849668db173acf7e05bdc5088..1433fea6ac88ba804cd5b19ef639c3c858ceb8a1 100644 --- a/Modules/Portfolio/classes/class.ilPortfolioDeclarationOfAuthorship.php +++ b/Modules/Portfolio/classes/class.ilPortfolioDeclarationOfAuthorship.php @@ -10,67 +10,64 @@ */ class ilPortfolioDeclarationOfAuthorship { - /** - * @var ilSetting - */ - protected $prtf_settings; + /** + * @var ilSetting + */ + protected $prtf_settings; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * Constructor - */ - public function __construct() - { - global $DIC; + /** + * Constructor + */ + public function __construct() + { + global $DIC; - $this->lng = $DIC->language(); - $this->prtf_settings = new ilSetting("prtf"); - } + $this->lng = $DIC->language(); + $this->prtf_settings = new ilSetting("prtf"); + } - /** - * Get for language - * - * @param string $l - * @return string - */ - public function getForLanguage(string $l): string - { - return $this->prtf_settings->get("decl_author_". $l); - } + /** + * Get for language + * + * @param string $l + * @return string + */ + public function getForLanguage(string $l) : string + { + return $this->prtf_settings->get("decl_author_" . $l); + } - /** - * Set for language - * - * @param string $l - * @param string $value - * @return string - */ - public function setForLanguage(string $l, string $value): string - { - return $this->prtf_settings->set("decl_author_". $l, $value); - } + /** + * Set for language + * + * @param string $l + * @param string $value + * @return string + */ + public function setForLanguage(string $l, string $value) : string + { + return $this->prtf_settings->set("decl_author_" . $l, $value); + } - /** - * Get for user - * - * @param ilObjUser $user - * @return string - */ - public function getForUser(ilObjUser $user): string - { - $lng = $this->lng; + /** + * Get for user + * + * @param ilObjUser $user + * @return string + */ + public function getForUser(ilObjUser $user) : string + { + $lng = $this->lng; - $decl = $this->getForLanguage($user->getLanguage()); - if ($decl == "") - { - $decl = $this->getForLanguage($lng->getDefaultLanguage()); - } - return $decl; - } - - -} \ No newline at end of file + $decl = $this->getForLanguage($user->getLanguage()); + if ($decl == "") { + $decl = $this->getForLanguage($lng->getDefaultLanguage()); + } + return $decl; + } +} diff --git a/Modules/Portfolio/classes/class.ilPortfolioExerciseGUI.php b/Modules/Portfolio/classes/class.ilPortfolioExerciseGUI.php index 43a10c58a709eebcdf70be947d09fb96f4a697c1..5ccbeb5d8ba24405b09ca3ed4d671b38654ab598 100644 --- a/Modules/Portfolio/classes/class.ilPortfolioExerciseGUI.php +++ b/Modules/Portfolio/classes/class.ilPortfolioExerciseGUI.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 ilPortfolioExerciseGUI @@ -11,300 +11,275 @@ include_once "Modules/Exercise/classes/class.ilExSubmission.php"; * @author Jörg Lützenkirchen * $Id: class.ilObjFolderGUI.php 25134 2010-08-13 14:22:11Z smeyer $ * -* @ilCtrl_Calls ilPortfolioExerciseGUI: +* @ilCtrl_Calls ilPortfolioExerciseGUI: */ class ilPortfolioExerciseGUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - protected $user_id; // [int] - protected $obj_id; // [int] - protected $ass_id; // [int] - protected $file; // [string] - - public function __construct($a_user_id, $a_obj_id) - { - global $DIC; + protected $user_id; // [int] + protected $obj_id; // [int] + protected $ass_id; // [int] + protected $file; // [string] + + public function __construct($a_user_id, $a_obj_id) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->user_id = $a_user_id; - $this->obj_id = $a_obj_id; - $this->ass_id = (int)$_GET["ass"]; - $this->file = trim($_GET["file"]); - } - - function executeCommand() - { - $ilCtrl = $this->ctrl; - - if(!$this->ass_id || - !$this->user_id) - { - $this->ctrl->returnToParent($this); - } - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd(); - - switch($next_class) - { - default: - $this->$cmd(); - break; - } - - return true; - } - - public static function checkExercise($a_user_id, $a_obj_id, $a_add_submit = false, $as_array = false) - { - global $DIC; + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->user_id = $a_user_id; + $this->obj_id = $a_obj_id; + $this->ass_id = (int) $_GET["ass"]; + $this->file = trim($_GET["file"]); + } + + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + if (!$this->ass_id || + !$this->user_id) { + $this->ctrl->returnToParent($this); + } + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd(); + + switch ($next_class) { + default: + $this->$cmd(); + break; + } + + return true; + } + + public static function checkExercise($a_user_id, $a_obj_id, $a_add_submit = false, $as_array = false) + { + global $DIC; - $tree = $DIC->repositoryTree(); - - $info = array(); - - $exercises = ilExSubmission::findUserFiles($a_user_id, $a_obj_id); - // #0022794 - if (!$exercises) - { - $exercises = ilExSubmission::findUserFiles($a_user_id, $a_obj_id.".sec"); - } - if($exercises) - { - 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($a_user_id, $exercise["ass_id"], $a_add_submit, $as_array); - if($part) - { - $info[] = $part; - } - } - } - if(sizeof($info) && !$as_array) - { - return implode("
", $info); - } - } - if ($as_array) - { - return $info; - } - } - - protected static function getExerciseInfo($a_user_id, $a_assignment_id, $a_add_submit = false, $as_array = false) - { - global $DIC; + $tree = $DIC->repositoryTree(); + + $info = array(); + + $exercises = ilExSubmission::findUserFiles($a_user_id, $a_obj_id); + // #0022794 + if (!$exercises) { + $exercises = ilExSubmission::findUserFiles($a_user_id, $a_obj_id . ".sec"); + } + if ($exercises) { + 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($a_user_id, $exercise["ass_id"], $a_add_submit, $as_array); + if ($part) { + $info[] = $part; + } + } + } + if (sizeof($info) && !$as_array) { + return implode("
", $info); + } + } + if ($as_array) { + return $info; + } + } + + protected static function getExerciseInfo($a_user_id, $a_assignment_id, $a_add_submit = false, $as_array = false) + { + global $DIC; - $ui = $DIC->ui(); + $ui = $DIC->ui(); - $links = []; - $buttons = []; - $elements = []; + $links = []; + $buttons = []; + $elements = []; - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - - include_once "Modules/Exercise/classes/class.ilExAssignment.php"; - $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(); + + include_once "Modules/Exercise/classes/class.ilExAssignment.php"; + $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"); - $info_arr["ass_title"] = $ass->getTitle(); - $text = sprintf($lng->txt("prtf_exercise_info"), - $ass->getTitle(), - ilObject::_lookupTitle($exercise_id)); - $links[] = $ui->factory()->link()->standard(ilObject::_lookupTitle($exercise_id), $exc_link); - $info_arr["exc_title"] = ilObject::_lookupTitle($exercise_id); - - // submit button - if($a_add_submit && !$times_up && !$as_array) - { - $ilCtrl->setParameterByClass("ilportfolioexercisegui", "ass", $a_assignment_id); - $submit_link = $ilCtrl->getLinkTargetByClass("ilportfolioexercisegui", "finalize"); - $ilCtrl->setParameterByClass("ilportfolioexercisegui", "ass", ""); - - $buttons[] = $ui->factory()->button()->primary($lng->txt("prtf_finalize_portfolio"), $submit_link); - } - - // submitted files - include_once "Modules/Exercise/classes/class.ilExSubmission.php"; - $submission = new ilExSubmission($ass, $a_user_id); - $info_arr["submitted"] = false; - if($submission->hasSubmitted()) - { - // #16888 - $submitted = $submission->getSelectedObject(); + $info_arr["ass_title"] = $ass->getTitle(); + $text = sprintf( + $lng->txt("prtf_exercise_info"), + $ass->getTitle(), + ilObject::_lookupTitle($exercise_id) + ); + $links[] = $ui->factory()->link()->standard(ilObject::_lookupTitle($exercise_id), $exc_link); + $info_arr["exc_title"] = ilObject::_lookupTitle($exercise_id); + + // submit button + if ($a_add_submit && !$times_up && !$as_array) { + $ilCtrl->setParameterByClass("ilportfolioexercisegui", "ass", $a_assignment_id); + $submit_link = $ilCtrl->getLinkTargetByClass("ilportfolioexercisegui", "finalize"); + $ilCtrl->setParameterByClass("ilportfolioexercisegui", "ass", ""); + + $buttons[] = $ui->factory()->button()->primary($lng->txt("prtf_finalize_portfolio"), $submit_link); + } + + // submitted files + include_once "Modules/Exercise/classes/class.ilExSubmission.php"; + $submission = new ilExSubmission($ass, $a_user_id); + $info_arr["submitted"] = false; + if ($submission->hasSubmitted()) { + // #16888 + $submitted = $submission->getSelectedObject(); - if (!$as_array) - { - $ilCtrl->setParameterByClass("ilportfolioexercisegui", "ass", $a_assignment_id); - $dl_link = $ilCtrl->getLinkTargetByClass("ilportfolioexercisegui", "downloadExcSubFile"); - $ilCtrl->setParameterByClass("ilportfolioexercisegui", "ass", ""); + if (!$as_array) { + $ilCtrl->setParameterByClass("ilportfolioexercisegui", "ass", $a_assignment_id); + $dl_link = $ilCtrl->getLinkTargetByClass("ilportfolioexercisegui", "downloadExcSubFile"); + $ilCtrl->setParameterByClass("ilportfolioexercisegui", "ass", ""); - $rel = ilDatePresentation::useRelativeDates(); - ilDatePresentation::setUseRelativeDates(false); + $rel = ilDatePresentation::useRelativeDates(); + ilDatePresentation::setUseRelativeDates(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; - } - } + $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 .= "

"; - } + $ass_files = $ass->getFiles(); + if (!$as_array) { + if (count($ass_files) > 0) { + if ($tooltip) { + $tooltip .= "

"; + } - $items = []; + $items = []; - foreach ($ass_files as $file) - { - $ilCtrl->setParameterByClass("ilportfolioexercisegui", "ass", $a_assignment_id); - $ilCtrl->setParameterByClass("ilportfolioexercisegui", "file", urlencode($file["name"])); - $dl_link = $ilCtrl->getLinkTargetByClass("ilportfolioexercisegui", "downloadExcAssFile"); - $ilCtrl->setParameterByClass("ilportfolioexercisegui", "file", ""); - $ilCtrl->setParameterByClass("ilportfolioexercisegui", "ass", ""); + foreach ($ass_files as $file) { + $ilCtrl->setParameterByClass("ilportfolioexercisegui", "ass", $a_assignment_id); + $ilCtrl->setParameterByClass("ilportfolioexercisegui", "file", urlencode($file["name"])); + $dl_link = $ilCtrl->getLinkTargetByClass("ilportfolioexercisegui", "downloadExcAssFile"); + $ilCtrl->setParameterByClass("ilportfolioexercisegui", "file", ""); + $ilCtrl->setParameterByClass("ilportfolioexercisegui", "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()); + } - if ($as_array) - { - return $info_arr; - } + if ($as_array) { + return $info_arr; + } - $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); - } - - 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"]); - } - } - } - } - } - - function downloadExcSubFile() - { - $ass = new ilExAssignment($this->ass_id); - $submission = new ilExSubmission($ass, $this->user_id); - $submitted = $submission->getFiles(); - if (count($submitted) > 0) - { - $submitted = array_pop($submitted); + return $ui->renderer()->render($elements); + } + + public 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"]); + } + } + } + } + } + + public function downloadExcSubFile() + { + $ass = new ilExAssignment($this->ass_id); + $submission = new ilExSubmission($ass, $this->user_id); + $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 portfolio to exercise - */ - protected function finalize() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - 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->submitPortfolio($this->obj_id); - - ilUtil::sendSuccess($lng->txt("prtf_finalized"), true); - $ilCtrl->returnToParent($this); - } -} - + ilUtil::deliverFile($submitted["filename"], $title); + } + } + + /** + * Finalize and submit portfolio to exercise + */ + protected function finalize() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + 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->submitPortfolio($this->obj_id); + + ilUtil::sendSuccess($lng->txt("prtf_finalized"), true); + $ilCtrl->returnToParent($this); + } +} diff --git a/Modules/Portfolio/classes/class.ilPortfolioExporter.php b/Modules/Portfolio/classes/class.ilPortfolioExporter.php index ee08c22c237bc2140160413c8e917d2f9357d902..5c9135e867d921794b68dc115887ab15bc9bd192 100644 --- a/Modules/Portfolio/classes/class.ilPortfolioExporter.php +++ b/Modules/Portfolio/classes/class.ilPortfolioExporter.php @@ -1,83 +1,78 @@ - - * @version $Id$ - * @ingroup ModulesPortfolio - */ -class ilPortfolioExporter extends ilXmlExporter -{ - protected $ds; - - public function init() - { - include_once("./Modules/Portfolio/classes/class.ilPortfolioDataSet.php"); - $this->ds = new ilPortfolioDataSet(); - $this->ds->setDSPrefix("ds"); - } - - public function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) - { - include_once("./Modules/Portfolio/classes/class.ilPortfolioTemplatePage.php"); - $pg_ids = array(); - foreach ($a_ids as $id) - { - foreach(ilPortfolioTemplatePage::getAllPortfolioPages($id) as $p) - { - $pg_ids[] = "prtt:".$p["id"]; - } - } - - $deps[] = - array( - "component" => "Services/COPage", - "entity" => "pg", - "ids" => $pg_ids); - - // style - $obj_ids = (is_array($a_ids)) - ? $a_ids - : array($a_ids); - $deps[] = array( - "component" => "Services/Style", - "entity" => "object_style", - "ids" => $obj_ids - ); - - return $deps; - - } - - 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.4.0" => array( - "namespace" => "http://www.ilias.de/Modules/Portfolio/4_4", - "xsd_file" => "ilias_portfolio_4_4.xsd", - "uses_dataset" => true, - "min" => "4.4.0", - "max" => "4.9.9"), - "5.0.0" => array( - "namespace" => "http://www.ilias.de/Modules/Portfolio/5_0", - "xsd_file" => "ilias_portfolio_5_0.xsd", - "uses_dataset" => true, - "min" => "5.0.0", - "max" => "") - ); - } -} - -?> \ No newline at end of file + + * @version $Id$ + * @ingroup ModulesPortfolio + */ +class ilPortfolioExporter extends ilXmlExporter +{ + protected $ds; + + public function init() + { + include_once("./Modules/Portfolio/classes/class.ilPortfolioDataSet.php"); + $this->ds = new ilPortfolioDataSet(); + $this->ds->setDSPrefix("ds"); + } + + public function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) + { + include_once("./Modules/Portfolio/classes/class.ilPortfolioTemplatePage.php"); + $pg_ids = array(); + foreach ($a_ids as $id) { + foreach (ilPortfolioTemplatePage::getAllPortfolioPages($id) as $p) { + $pg_ids[] = "prtt:" . $p["id"]; + } + } + + $deps[] = + array( + "component" => "Services/COPage", + "entity" => "pg", + "ids" => $pg_ids); + + // style + $obj_ids = (is_array($a_ids)) + ? $a_ids + : array($a_ids); + $deps[] = array( + "component" => "Services/Style", + "entity" => "object_style", + "ids" => $obj_ids + ); + + return $deps; + } + + 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.4.0" => array( + "namespace" => "http://www.ilias.de/Modules/Portfolio/4_4", + "xsd_file" => "ilias_portfolio_4_4.xsd", + "uses_dataset" => true, + "min" => "4.4.0", + "max" => "4.9.9"), + "5.0.0" => array( + "namespace" => "http://www.ilias.de/Modules/Portfolio/5_0", + "xsd_file" => "ilias_portfolio_5_0.xsd", + "uses_dataset" => true, + "min" => "5.0.0", + "max" => "") + ); + } +} diff --git a/Modules/Portfolio/classes/class.ilPortfolioHTMLExport.php b/Modules/Portfolio/classes/class.ilPortfolioHTMLExport.php index 6efe1ee2c5bf9e21db5e399990dc37ca9f640ffc..57238612141f1d369cb7a930349e86a95af5595f 100644 --- a/Modules/Portfolio/classes/class.ilPortfolioHTMLExport.php +++ b/Modules/Portfolio/classes/class.ilPortfolioHTMLExport.php @@ -1,308 +1,290 @@ - - * @version $Id$ - * - * @ingroup ModulesPortfolio - */ -class ilPortfolioHTMLExport -{ - protected $portfolio_gui; - protected $export_material; - - /** - * Constructor - * - * @param - */ - function __construct($a_portfolio_gui, $a_object) - { - $this->portfolio_gui = $a_portfolio_gui; - $this->object = $a_object; - $this->export_material = array(); // #16571 - } - - /** - * Build export file - * - * @param - * @return - */ - function buildExportFile() - { - // create export file - include_once("./Services/Export/classes/class.ilExport.php"); - ilExport::_createExportDirectory($this->object->getId(), "html", "prtf"); - $exp_dir = ilExport::_getExportDirectory($this->object->getId(), "html", "prtf"); - - $this->subdir = $this->object->getType()."_".$this->object->getId(); - $this->export_dir = $exp_dir."/".$this->subdir; - - // initialize temporary target directory - ilUtil::delDir($this->export_dir); - ilUtil::makeDir($this->export_dir); - - // system style html exporter - include_once("./Services/Style/System/classes/class.ilSystemStyleHTMLExport.php"); - $this->sys_style_html_export = new ilSystemStyleHTMLExport($this->export_dir); - // $this->sys_style_html_export->addImage("icon_prtf.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($this->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 - $prfa_set = new ilSetting("prfa"); - if($prfa_set->get("banner")) - { - $banner = $this->object->getImageFullPath(); - if($banner) // #16096 - { - copy($banner, $this->export_dir."/".basename($banner)); - } - } - // page element: profile picture - $ppic = ilObjUser::_getPersonalPicturePath($this->object->getOwner(), "big", true, true); - if($ppic) - { - $ppic = array_shift(explode("?", $ppic)); - copy($ppic, $this->export_dir."/".basename($ppic)); - } - // header image: profile picture - $ppic = ilObjUser::_getPersonalPicturePath($this->object->getOwner(), "xsmall", true, true); - if($ppic) - { - $ppic = array_shift(explode("?", $ppic)); - copy($ppic, $this->export_dir."/".basename($ppic)); - } - - // export pages - $this->exportHTMLPages(); - - // add js/images/file to zip - $images = $files = $js_files = array(); - include_once("./Services/UICore/classes/class.ilUIFramework.php"); - $js_files = ilUIFramework::getJSFiles(); - foreach($this->export_material as $items) - { - $images = array_merge($images, $items["images"]); - $files = array_merge($files, $items["files"]); - $js_files = array_merge($js_files, $items["js"]); - } - foreach(array_unique($images) as $image) - { - if(is_file($image)) - { - copy($image, $this->export_dir."/images/".basename($image)); - } - } - foreach(array_unique($js_files) as $js_file) - { - if(is_file($js_file)) - { - copy($js_file, $this->export_dir."/js/".basename($js_file)); - } - } - foreach(array_unique($files) as $file) - { - if(is_file($file)) - { - copy($file, $this->export_dir."/files/".basename($file)); - } - } - - // zip everything - if (true) - { - // zip it all - $date = time(); - $zip_file = ilExport::_getExportDirectory($this->object->getId(), "html", "prtf"). - "/".$date."__".IL_INST_ID."__". - $this->object->getType()."_".$this->object->getId().".zip"; - ilUtil::zip($this->export_dir, $zip_file); - ilUtil::delDir($this->export_dir); - } - - return $zip_file; - } - - /** - * Export all pages - */ - function exportHTMLPages() - { - require_once "Modules/Portfolio/classes/class.ilPortfolioPage.php"; - $pages = ilPortfolioPage::getAllPortfolioPages($this->object->getId()); - - $this->tabs = array(); - foreach($pages as $page) - { - // substitute blog id with title - if($page["type"] == ilPortfolioPage::TYPE_BLOG) - { - include_once "Modules/Blog/classes/class.ilObjBlog.php"; - $page["title"] = ilObjBlog::_lookupTitle((int)$page["title"]); - } - - $this->tabs[$page["id"]] = $page["title"]; - } - - // for sub-pages, e.g. blog postings - $tpl_callback = array($this, "buildExportTemplate"); - - include_once("./Services/COPage/classes/class.ilPageContentUsage.php"); - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - include_once("./Modules/Portfolio/classes/class.ilPortfolioPage.php"); - $has_index = false; - foreach ($pages as $page) - { - if (ilPortfolioPage::_exists("prtf", $page["id"])) - { - $this->active_tab = "user_page_".$page["id"]; - - if($page["type"] == ilPortfolioPage::TYPE_BLOG) - { - $link_template = "prtf_".$page["id"]."_bl{TYPE}_{ID}.html"; - - include_once "Modules/Blog/classes/class.ilObjBlogGUI.php"; - $blog = new ilObjBlogGUI((int)$page["title"], ilObject2GUI::WORKSPACE_OBJECT_ID); - $blog->exportHTMLPages($this->export_dir."/", $link_template, $tpl_callback, $this->co_page_html_export, "prtf_".$page["id"].".html"); - } - else - { - $this->exportPageHTML($page["id"]); - $this->co_page_html_export->collectPageElements("prtf:pg", $page["id"]); - } - - if(!$has_index) - { - if (is_file($this->export_dir."/prtf_".$page["id"].".html")) // #20144 - { - copy($this->export_dir . "/prtf_" . $page["id"] . ".html", - $this->export_dir . "/index.html"); - $has_index = true; - } - } - } - } - $this->co_page_html_export->exportPageElements(); - } - - function buildExportTemplate(array $a_js_files = null) - { - global $DIC; - - $ilTabs = $DIC->tabs(); - - $this->tpl = $this->co_page_html_export->getPreparedMainTemplate(); - $this->tpl->getStandardTemplate(); - $this->tpl->addOnLoadCode('il.Tooltip.init();', 3); - - // js files - if(is_array($a_js_files)) - { - foreach($a_js_files as $js_file) - { - $this->tpl->setCurrentBlock("js_file"); - $this->tpl->setVariable("JS_FILE", !stristr($js_file, "://") - ? "./js/".basename($js_file) - : $js_file); - $this->tpl->parseCurrentBlock(); - } - } - - // workaround - $this->tpl->setVariable("MAINMENU", "
"); - $this->tpl->setTitle($this->object->getTitle()); - - $ilTabs->clearTargets(); - if($this->tabs) - { - foreach($this->tabs as $id => $caption) - { - $ilTabs->addTab("user_page_".$id, $caption, "prtf_".$id.".html"); - } - - $ilTabs->activateTab($this->active_tab); - } - - include_once "Modules/Portfolio/classes/class.ilObjPortfolioGUI.php"; - ilObjPortfolioGUI::renderFullscreenHeader($this->object, $this->tpl, $this->object->getOwner(), true); - - return $this->tpl; - } - - function writeExportFile($a_file, $a_content, $a_onload = null, $a_js_files = null) - { - $file = $this->export_dir."/".$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/Portfolio"); - $ep_tpl->setVariable("PAGE_CONTENT", $a_content); - - $this->buildExportTemplate($a_js_files); - $this->tpl->setContent($ep_tpl->get()); - - if(is_array($a_onload)) - { - foreach($a_onload as $item) - { - $this->tpl->addOnLoadCode($item); - } - } - - - $content = $this->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; - } - - /** - * Export page html - */ - function exportPageHTML($a_post_id) - { - // page - include_once "Modules/Portfolio/classes/class.ilPortfolioPageGUI.php"; - $pgui = new ilPortfolioPageGUI($this->object->getId(), $a_post_id); - $pgui->setOutputMode("offline"); - $pgui->setFullscreenLink("fullscreen.html"); // #12930 - see page.xsl - $page_content = $pgui->showPage(); - - $material = $pgui->getExportMaterial(); - $this->export_material[] = $material; - - include_once("./Services/UICore/classes/class.ilUIFramework.php"); - $js_files = array_merge(ilUIFramework::getJSFiles(), $material["js"]); - - $this->writeExportFile("prtf_".$a_post_id.".html", $page_content, $pgui->getJsOnloadCode(), $js_files); - } -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @ingroup ModulesPortfolio + */ +class ilPortfolioHTMLExport +{ + protected $portfolio_gui; + protected $export_material; + + /** + * Constructor + * + * @param + */ + public function __construct($a_portfolio_gui, $a_object) + { + $this->portfolio_gui = $a_portfolio_gui; + $this->object = $a_object; + $this->export_material = array(); // #16571 + } + + /** + * Build export file + * + * @param + * @return + */ + public function buildExportFile() + { + // create export file + include_once("./Services/Export/classes/class.ilExport.php"); + ilExport::_createExportDirectory($this->object->getId(), "html", "prtf"); + $exp_dir = ilExport::_getExportDirectory($this->object->getId(), "html", "prtf"); + + $this->subdir = $this->object->getType() . "_" . $this->object->getId(); + $this->export_dir = $exp_dir . "/" . $this->subdir; + + // initialize temporary target directory + ilUtil::delDir($this->export_dir); + ilUtil::makeDir($this->export_dir); + + // system style html exporter + include_once("./Services/Style/System/classes/class.ilSystemStyleHTMLExport.php"); + $this->sys_style_html_export = new ilSystemStyleHTMLExport($this->export_dir); + // $this->sys_style_html_export->addImage("icon_prtf.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($this->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 + $prfa_set = new ilSetting("prfa"); + if ($prfa_set->get("banner")) { + $banner = $this->object->getImageFullPath(); + if ($banner) { // #16096 + copy($banner, $this->export_dir . "/" . basename($banner)); + } + } + // page element: profile picture + $ppic = ilObjUser::_getPersonalPicturePath($this->object->getOwner(), "big", true, true); + if ($ppic) { + $ppic = array_shift(explode("?", $ppic)); + copy($ppic, $this->export_dir . "/" . basename($ppic)); + } + // header image: profile picture + $ppic = ilObjUser::_getPersonalPicturePath($this->object->getOwner(), "xsmall", true, true); + if ($ppic) { + $ppic = array_shift(explode("?", $ppic)); + copy($ppic, $this->export_dir . "/" . basename($ppic)); + } + + // export pages + $this->exportHTMLPages(); + + // add js/images/file to zip + $images = $files = $js_files = array(); + include_once("./Services/UICore/classes/class.ilUIFramework.php"); + $js_files = ilUIFramework::getJSFiles(); + foreach ($this->export_material as $items) { + $images = array_merge($images, $items["images"]); + $files = array_merge($files, $items["files"]); + $js_files = array_merge($js_files, $items["js"]); + } + foreach (array_unique($images) as $image) { + if (is_file($image)) { + copy($image, $this->export_dir . "/images/" . basename($image)); + } + } + foreach (array_unique($js_files) as $js_file) { + if (is_file($js_file)) { + copy($js_file, $this->export_dir . "/js/" . basename($js_file)); + } + } + foreach (array_unique($files) as $file) { + if (is_file($file)) { + copy($file, $this->export_dir . "/files/" . basename($file)); + } + } + + // zip everything + if (true) { + // zip it all + $date = time(); + $zip_file = ilExport::_getExportDirectory($this->object->getId(), "html", "prtf") . + "/" . $date . "__" . IL_INST_ID . "__" . + $this->object->getType() . "_" . $this->object->getId() . ".zip"; + ilUtil::zip($this->export_dir, $zip_file); + ilUtil::delDir($this->export_dir); + } + + return $zip_file; + } + + /** + * Export all pages + */ + public function exportHTMLPages() + { + require_once "Modules/Portfolio/classes/class.ilPortfolioPage.php"; + $pages = ilPortfolioPage::getAllPortfolioPages($this->object->getId()); + + $this->tabs = array(); + foreach ($pages as $page) { + // substitute blog id with title + if ($page["type"] == ilPortfolioPage::TYPE_BLOG) { + include_once "Modules/Blog/classes/class.ilObjBlog.php"; + $page["title"] = ilObjBlog::_lookupTitle((int) $page["title"]); + } + + $this->tabs[$page["id"]] = $page["title"]; + } + + // for sub-pages, e.g. blog postings + $tpl_callback = array($this, "buildExportTemplate"); + + include_once("./Services/COPage/classes/class.ilPageContentUsage.php"); + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + include_once("./Modules/Portfolio/classes/class.ilPortfolioPage.php"); + $has_index = false; + foreach ($pages as $page) { + if (ilPortfolioPage::_exists("prtf", $page["id"])) { + $this->active_tab = "user_page_" . $page["id"]; + + if ($page["type"] == ilPortfolioPage::TYPE_BLOG) { + $link_template = "prtf_" . $page["id"] . "_bl{TYPE}_{ID}.html"; + + include_once "Modules/Blog/classes/class.ilObjBlogGUI.php"; + $blog = new ilObjBlogGUI((int) $page["title"], ilObject2GUI::WORKSPACE_OBJECT_ID); + $blog->exportHTMLPages($this->export_dir . "/", $link_template, $tpl_callback, $this->co_page_html_export, "prtf_" . $page["id"] . ".html"); + } else { + $this->exportPageHTML($page["id"]); + $this->co_page_html_export->collectPageElements("prtf:pg", $page["id"]); + } + + if (!$has_index) { + if (is_file($this->export_dir . "/prtf_" . $page["id"] . ".html")) { // #20144 + copy( + $this->export_dir . "/prtf_" . $page["id"] . ".html", + $this->export_dir . "/index.html" + ); + $has_index = true; + } + } + } + } + $this->co_page_html_export->exportPageElements(); + } + + public function buildExportTemplate(array $a_js_files = null) + { + global $DIC; + + $ilTabs = $DIC->tabs(); + + $this->tpl = $this->co_page_html_export->getPreparedMainTemplate(); + $this->tpl->getStandardTemplate(); + $this->tpl->addOnLoadCode('il.Tooltip.init();', 3); + + // js files + if (is_array($a_js_files)) { + foreach ($a_js_files as $js_file) { + $this->tpl->setCurrentBlock("js_file"); + $this->tpl->setVariable("JS_FILE", !stristr($js_file, "://") + ? "./js/" . basename($js_file) + : $js_file); + $this->tpl->parseCurrentBlock(); + } + } + + // workaround + $this->tpl->setVariable("MAINMENU", "
"); + $this->tpl->setTitle($this->object->getTitle()); + + $ilTabs->clearTargets(); + if ($this->tabs) { + foreach ($this->tabs as $id => $caption) { + $ilTabs->addTab("user_page_" . $id, $caption, "prtf_" . $id . ".html"); + } + + $ilTabs->activateTab($this->active_tab); + } + + include_once "Modules/Portfolio/classes/class.ilObjPortfolioGUI.php"; + ilObjPortfolioGUI::renderFullscreenHeader($this->object, $this->tpl, $this->object->getOwner(), true); + + return $this->tpl; + } + + public function writeExportFile($a_file, $a_content, $a_onload = null, $a_js_files = null) + { + $file = $this->export_dir . "/" . $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/Portfolio" + ); + $ep_tpl->setVariable("PAGE_CONTENT", $a_content); + + $this->buildExportTemplate($a_js_files); + $this->tpl->setContent($ep_tpl->get()); + + if (is_array($a_onload)) { + foreach ($a_onload as $item) { + $this->tpl->addOnLoadCode($item); + } + } + + + $content = $this->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; + } + + /** + * Export page html + */ + public function exportPageHTML($a_post_id) + { + // page + include_once "Modules/Portfolio/classes/class.ilPortfolioPageGUI.php"; + $pgui = new ilPortfolioPageGUI($this->object->getId(), $a_post_id); + $pgui->setOutputMode("offline"); + $pgui->setFullscreenLink("fullscreen.html"); // #12930 - see page.xsl + $page_content = $pgui->showPage(); + + $material = $pgui->getExportMaterial(); + $this->export_material[] = $material; + + include_once("./Services/UICore/classes/class.ilUIFramework.php"); + $js_files = array_merge(ilUIFramework::getJSFiles(), $material["js"]); + + $this->writeExportFile("prtf_" . $a_post_id . ".html", $page_content, $pgui->getJsOnloadCode(), $js_files); + } +} diff --git a/Modules/Portfolio/classes/class.ilPortfolioImporter.php b/Modules/Portfolio/classes/class.ilPortfolioImporter.php index 1e5ee30ad5a0cf3800a466b45e5c857e4710ecb7..290ed2805251a6282754ac22c7e48c7fad646121 100644 --- a/Modules/Portfolio/classes/class.ilPortfolioImporter.php +++ b/Modules/Portfolio/classes/class.ilPortfolioImporter.php @@ -1,60 +1,62 @@ - - * @version $Id: $ - * @ingroup ModulesPortfolio - */ -class ilPortfolioImporter extends ilXmlImporter -{ - protected $ds; - - /** - * Initialisation - */ - function init() - { - include_once("./Modules/Portfolio/classes/class.ilPortfolioDataSet.php"); - $this->ds = new ilPortfolioDataSet(); - $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) - { - $prttpg_map = $a_mapping->getMappingsOfEntity("Services/COPage", "pg"); - foreach ($prttpg_map as $prttpg_id) - { - $prttpg_id = substr($prttpg_id, 5); - $prtt_id = ilPortfolioTemplatePage::findPortfolioForPage($prttpg_id); - ilPortfolioTemplatePage::_writeParentId("prtt", $prttpg_id, $prtt_id); - } - } -} - -?> \ No newline at end of file + + * @version $Id: $ + * @ingroup ModulesPortfolio + */ +class ilPortfolioImporter extends ilXmlImporter +{ + protected $ds; + + /** + * Initialisation + */ + public function init() + { + include_once("./Modules/Portfolio/classes/class.ilPortfolioDataSet.php"); + $this->ds = new ilPortfolioDataSet(); + $this->ds->setDSPrefix("ds"); + } + + /** + * 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) + { + $prttpg_map = $a_mapping->getMappingsOfEntity("Services/COPage", "pg"); + foreach ($prttpg_map as $prttpg_id) { + $prttpg_id = substr($prttpg_id, 5); + $prtt_id = ilPortfolioTemplatePage::findPortfolioForPage($prttpg_id); + ilPortfolioTemplatePage::_writeParentId("prtt", $prttpg_id, $prtt_id); + } + } +} diff --git a/Modules/Portfolio/classes/class.ilPortfolioPage.php b/Modules/Portfolio/classes/class.ilPortfolioPage.php index 115006e75f9634e3ce4f0da98dadeefbbbcff586..4c281e63f6d21587dbf8ce570f875567ffdb7425 100644 --- a/Modules/Portfolio/classes/class.ilPortfolioPage.php +++ b/Modules/Portfolio/classes/class.ilPortfolioPage.php @@ -1,509 +1,480 @@ - - * @version $Id$ - * - * @ingroup ModulesPortfolio - */ -class ilPortfolioPage extends ilPageObject -{ - protected $portfolio_id; - protected $type = 1; - protected $title; - protected $order_nr; - - const TYPE_PAGE = 1; - const TYPE_BLOG = 2; - - /** - * Get parent type - * - * @return string parent type - */ - function getParentType() - { - return "prtf"; - } - - /** - * Set portfolio id - * - * @param int $a_val portfolio id - */ - function setPortfolioId($a_val) - { - $this->portfolio_id = $a_val; - } - - /** - * Get portfolio id - * - * @return int portfolio id - */ - function getPortfolioId() - { - return $this->portfolio_id; - } - - /** - * Set type - * - * @param int type - */ - function setType($a_val) - { - $this->type = $a_val; - } - - /** - * Get type - * - * @return int type - */ - function getType() - { - return $this->type; - } - - /** - * Set Title - * - * @param string $a_title Title - */ - function setTitle($a_title) - { - $this->title = $a_title; - } - - /** - * Get Title. - * - * @return string Title - */ - function getTitle() - { - $lng = $this->lng; - - // because of migration of extended user profiles - if($this->title == "###-") - { - return $lng->txt("profile"); - } - - return $this->title; - } - - /** - * Set order nr - * - * @param int order nr - */ - function setOrderNr($a_val) - { - $this->order_nr = (int)$a_val; - } - - /** - * Get order nr - * - * @return int order nr - */ - function getOrderNr() - { - return $this->order_nr; - } - - /** - * Lookup max order nr for portfolio - * - * @param int $a_portfolio_id - * @return int - */ - static function lookupMaxOrderNr($a_portfolio_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT MAX(order_nr) m FROM usr_portfolio_page". - " WHERE portfolio_id = ".$ilDB->quote($a_portfolio_id, "integer")); - $rec = $ilDB->fetchAssoc($set); - return (int) $rec["m"]; - } - - /** - * Get properties for insert/update statements - * - * @return array - */ - protected function getPropertiesForDB() - { - $fields = array("portfolio_id" => array("integer", $this->portfolio_id), - "type" => array("integer", $this->getType()), - "title" => array("text", $this->getTitle()), - "order_nr" => array("integer", $this->getOrderNr())); - - return $fields; - } - - /** - * Create new portfolio page - */ - function create($a_import = false) - { - $ilDB = $this->db; - - if(!$a_import) - { - $this->setOrderNr(self::lookupMaxOrderNr($this->portfolio_id) + 10); - } - - $id = $ilDB->nextId("usr_portfolio_page"); - $this->setId($id); - - $fields = $this->getPropertiesForDB(); - $fields["id"] = array("integer", $id); - - $ilDB->insert("usr_portfolio_page", $fields); - - if(!$a_import) - { - parent::create(); - // $this->saveInternalLinks($this->getDomDoc()); - } - } - - /** - * Update page - * - * @return boolean - */ - function update($a_validate = true, $a_no_history = false) - { - $ilDB = $this->db; - - $id = $this->getId(); - if($id) - { - $fields = $this->getPropertiesForDB(); - $ilDB->update("usr_portfolio_page", $fields, - array("id"=>array("integer", $id))); - - parent::update($a_validate, $a_no_history); - return true; - } - return false; - } - - /** - * Read page data - */ - function read() - { - $ilDB = $this->db; - - $query = "SELECT * FROM usr_portfolio_page". - " WHERE id = ".$ilDB->quote($this->getId(), "integer"); - $set = $ilDB->query($query); - $rec = $ilDB->fetchAssoc($set); - - $this->setPortfolioId($rec["portfolio_id"]); - $this->setType($rec["type"]); - $this->setTitle($rec["title"]); - $this->setOrderNr($rec["order_nr"]); - - // get co page - parent::read(); - } - - /** - * delete portfolio page and all related data - */ - function delete() - { - $ilDB = $this->db; - - $id = $this->getId(); - if($id) - { - // delete internal links information to this page - include_once("./Services/Link/classes/class.ilInternalLink.php"); - ilInternalLink::_deleteAllLinksToTarget("user", $this->getId()); - - // delete record of table usr_portfolio_page - $query = "DELETE FROM usr_portfolio_page". - " WHERE id = ".$ilDB->quote($this->getId(), "integer"); - $ilDB->manipulate($query); - - // delete co page - parent::delete(); - } - } - - /** - * Lookup portfolio page property - * - * @param int $a_id - * @param string $a_prop - * @return mixed - */ - protected static function lookupProperty($a_id, $a_prop) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT ".$a_prop. - " FROM usr_portfolio_page". - " WHERE id = ".$ilDB->quote($a_id, "integer")); - $rec = $ilDB->fetchAssoc($set); - return $rec[$a_prop]; - } - - /** - * Lookup title - * - * @param int $a_page_id - */ - static function lookupTitle($a_page_id) - { - return self::lookupProperty($a_page_id, "title"); - } - - /** - * Get pages of portfolio - * - * @param int $a_portfolio_id - * @return array - */ - static function getAllPortfolioPages($a_portfolio_id) - { - global $DIC; - - $ilDB = $DIC->database(); - $lng = $DIC->language(); - - $set = $ilDB->query("SELECT * FROM usr_portfolio_page". - " WHERE portfolio_id = ".$ilDB->quote($a_portfolio_id, "integer"). - " ORDER BY order_nr"); - $pages = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - // because of migration of extended user profiles - if($rec["title"] == "###-") - { - $rec["title"] = $lng->txt("profile"); - } - - $pages[] = $rec; - } - return $pages; - } - - /** - * Fix ordering - * - * @param int $a_portfolio_id - */ - public static function fixOrdering($a_portfolio_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $pages = self::getAllPortfolioPages($a_portfolio_id); - $cnt = 10; - foreach ($pages as $p) - { - $ilDB->manipulate("UPDATE usr_portfolio_page SET ". - " order_nr = ".$ilDB->quote($cnt, "integer"). - " WHERE id = ".$ilDB->quote($p["id"], "integer") - ); - $cnt+= 10; - } - } - - /** - * Get portfolio id of page id - * - * @param int $a_page_id - * @return int - */ - public static function findPortfolioForPage($a_page_id) - { - return self::lookupProperty($a_page_id, "portfolio_id"); - } - - /** - * Get goto href for internal wiki page link target - * - * @param - * @return string - */ - static function getGotoForPortfolioPageTarget($a_target, $a_offline = false) - { - global $DIC; - - $pid = self::findPortfolioForPage((int) $a_target); - $type = ilObject::_lookupType($pid); - if ($type == "prtt") - { - $ctrl = $DIC->ctrl(); - $ctrl->setParameterByClass("ilobjportfoliotemplategui", "user_page", $a_target); - $href = $ctrl->getLinkTargetByClass(array("ilRepositoryGUI", "ilObjPortfolioTemplateGUI", "ilobjportfoliotemplategui"), "preview"); - } - else - { - if (!$a_offline) - { - $href = "./goto.php?client_id=" . CLIENT_ID . "&target=prtf_" . $pid . "_" . $a_target; - } else - { - $href = "prtf_".$a_target.".html"; - } - } - return $href; - } - - /** - * Update internal links, after multiple pages have been copied - */ - static function updateInternalLinks($a_copied_nodes, ilObjPortfolioBase $a_target_obj) - { -// var_dump($a_copied_nodes); - $all_fixes = array(); - foreach($a_copied_nodes as $original_id => $copied_id) - { - $pid = self::findPortfolioForPage((int) $copied_id); - - // - // 1. Outgoing links from the copied page. - // - //$targets = ilInternalLink::_getTargetsOfSource($a_parent_type.":pg", $copied_id); - if ($a_target_obj->getType() == "prtf") - { - $tpg = new ilPortfolioPage($copied_id); - } - if ($a_target_obj->getType() == "prtt") - { - $tpg = new ilPortfolioTemplatePage($copied_id); - } - $tpg->buildDom(); - $il = $tpg->getInternalLinks(); -// var_dump($il); - $targets = array(); - foreach($il as $l) - { - $targets[] = array("type" => ilInternalLink::_extractTypeOfTarget($l["Target"]), - "id" => (int) ilInternalLink::_extractObjIdOfTarget($l["Target"]), - "inst" => (int) ilInternalLink::_extractInstOfTarget($l["Target"])); - } - $fix = array(); - foreach($targets as $target) - { - if (($target["inst"] == 0 || $target["inst"] = IL_INST_ID) && - ($target["type"] == "ppage")) - { - // first check, whether target is also within the copied set - if ($a_copied_nodes[$target["id"]] > 0) - { - $fix[$target["id"]] = $a_copied_nodes[$target["id"]]; - } - } - } -// var_dump($fix); - // outgoing links to be fixed - if (count($fix) > 0) - { - $t = ilObject::_lookupType($pid); - if (is_array($all_fixes[$t.":".$copied_id])) - { - $all_fixes[$t.":".$copied_id] += $fix; - } - else - { - $all_fixes[$t.":".$copied_id] = $fix; - } - } - } -// var_dump($all_fixes); - foreach ($all_fixes as $pg => $fixes) - { - $pg = explode(":", $pg); - include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); - $page = ilPageObjectFactory::getInstance($pg[0], $pg[1]); - if ($page->moveIntLinks($fixes)) - { - $page->update(true, true); - } - } - } - - - /** - * @param $a_title_changes - */ - function renameLinksOnTitleChange($a_title_changes) - { - $this->buildDom(); - - $changed = false; - - // resolve normal internal links - $xpc = xpath_new_context($this->dom); - $path = "//IntLink"; - $res = xpath_eval($xpc, $path); - for ($i = 0; $i < count($res->nodeset); $i++) - { - $target = $res->nodeset[$i]->get_attribute("Target"); - $type = $res->nodeset[$i]->get_attribute("Type"); - $obj_id = ilInternalLink::_extractObjIdOfTarget($target); - if (isset($a_title_changes[$obj_id]) && is_int(strpos($target, "__"))) - { - if ($type == "PortfolioPage") - { - if ($res->nodeset[$i]->get_content() == $a_title_changes[$obj_id]["old"]) - { - $res->nodeset[$i]->set_content($a_title_changes[$obj_id]["new"]); - $changed = true; - } - } - } - } - unset($xpc); - - return $changed; - } - - /** - * Get portfolio pages for blog - * - * @param int $a_blog_id - * @return ilPortfolioPage[] - */ - static function getPagesForBlog($a_blog_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT * FROM usr_portfolio_page". - " WHERE title = ".$ilDB->quote($a_blog_id, "text"). - " AND type = ".$ilDB->quote(self::TYPE_BLOG, "integer")); - $pages = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $pages[] = new ilPortfolioPage($rec["id"]); - } - return $pages; - } - -} -?> + + * @version $Id$ + * + * @ingroup ModulesPortfolio + */ +class ilPortfolioPage extends ilPageObject +{ + protected $portfolio_id; + protected $type = 1; + protected $title; + protected $order_nr; + + const TYPE_PAGE = 1; + const TYPE_BLOG = 2; + + /** + * Get parent type + * + * @return string parent type + */ + public function getParentType() + { + return "prtf"; + } + + /** + * Set portfolio id + * + * @param int $a_val portfolio id + */ + public function setPortfolioId($a_val) + { + $this->portfolio_id = $a_val; + } + + /** + * Get portfolio id + * + * @return int portfolio id + */ + public function getPortfolioId() + { + return $this->portfolio_id; + } + + /** + * Set type + * + * @param int type + */ + public function setType($a_val) + { + $this->type = $a_val; + } + + /** + * Get type + * + * @return int type + */ + public function getType() + { + return $this->type; + } + + /** + * Set Title + * + * @param string $a_title Title + */ + public function setTitle($a_title) + { + $this->title = $a_title; + } + + /** + * Get Title. + * + * @return string Title + */ + public function getTitle() + { + $lng = $this->lng; + + // because of migration of extended user profiles + if ($this->title == "###-") { + return $lng->txt("profile"); + } + + return $this->title; + } + + /** + * Set order nr + * + * @param int order nr + */ + public function setOrderNr($a_val) + { + $this->order_nr = (int) $a_val; + } + + /** + * Get order nr + * + * @return int order nr + */ + public function getOrderNr() + { + return $this->order_nr; + } + + /** + * Lookup max order nr for portfolio + * + * @param int $a_portfolio_id + * @return int + */ + public static function lookupMaxOrderNr($a_portfolio_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query("SELECT MAX(order_nr) m FROM usr_portfolio_page" . + " WHERE portfolio_id = " . $ilDB->quote($a_portfolio_id, "integer")); + $rec = $ilDB->fetchAssoc($set); + return (int) $rec["m"]; + } + + /** + * Get properties for insert/update statements + * + * @return array + */ + protected function getPropertiesForDB() + { + $fields = array("portfolio_id" => array("integer", $this->portfolio_id), + "type" => array("integer", $this->getType()), + "title" => array("text", $this->getTitle()), + "order_nr" => array("integer", $this->getOrderNr())); + + return $fields; + } + + /** + * Create new portfolio page + */ + public function create($a_import = false) + { + $ilDB = $this->db; + + if (!$a_import) { + $this->setOrderNr(self::lookupMaxOrderNr($this->portfolio_id) + 10); + } + + $id = $ilDB->nextId("usr_portfolio_page"); + $this->setId($id); + + $fields = $this->getPropertiesForDB(); + $fields["id"] = array("integer", $id); + + $ilDB->insert("usr_portfolio_page", $fields); + + if (!$a_import) { + parent::create(); + // $this->saveInternalLinks($this->getDomDoc()); + } + } + + /** + * Update page + * + * @return boolean + */ + public function update($a_validate = true, $a_no_history = false) + { + $ilDB = $this->db; + + $id = $this->getId(); + if ($id) { + $fields = $this->getPropertiesForDB(); + $ilDB->update( + "usr_portfolio_page", + $fields, + array("id"=>array("integer", $id)) + ); + + parent::update($a_validate, $a_no_history); + return true; + } + return false; + } + + /** + * Read page data + */ + public function read() + { + $ilDB = $this->db; + + $query = "SELECT * FROM usr_portfolio_page" . + " WHERE id = " . $ilDB->quote($this->getId(), "integer"); + $set = $ilDB->query($query); + $rec = $ilDB->fetchAssoc($set); + + $this->setPortfolioId($rec["portfolio_id"]); + $this->setType($rec["type"]); + $this->setTitle($rec["title"]); + $this->setOrderNr($rec["order_nr"]); + + // get co page + parent::read(); + } + + /** + * delete portfolio page and all related data + */ + public function delete() + { + $ilDB = $this->db; + + $id = $this->getId(); + if ($id) { + // delete internal links information to this page + include_once("./Services/Link/classes/class.ilInternalLink.php"); + ilInternalLink::_deleteAllLinksToTarget("user", $this->getId()); + + // delete record of table usr_portfolio_page + $query = "DELETE FROM usr_portfolio_page" . + " WHERE id = " . $ilDB->quote($this->getId(), "integer"); + $ilDB->manipulate($query); + + // delete co page + parent::delete(); + } + } + + /** + * Lookup portfolio page property + * + * @param int $a_id + * @param string $a_prop + * @return mixed + */ + protected static function lookupProperty($a_id, $a_prop) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query("SELECT " . $a_prop . + " FROM usr_portfolio_page" . + " WHERE id = " . $ilDB->quote($a_id, "integer")); + $rec = $ilDB->fetchAssoc($set); + return $rec[$a_prop]; + } + + /** + * Lookup title + * + * @param int $a_page_id + */ + public static function lookupTitle($a_page_id) + { + return self::lookupProperty($a_page_id, "title"); + } + + /** + * Get pages of portfolio + * + * @param int $a_portfolio_id + * @return array + */ + public static function getAllPortfolioPages($a_portfolio_id) + { + global $DIC; + + $ilDB = $DIC->database(); + $lng = $DIC->language(); + + $set = $ilDB->query("SELECT * FROM usr_portfolio_page" . + " WHERE portfolio_id = " . $ilDB->quote($a_portfolio_id, "integer") . + " ORDER BY order_nr"); + $pages = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + // because of migration of extended user profiles + if ($rec["title"] == "###-") { + $rec["title"] = $lng->txt("profile"); + } + + $pages[] = $rec; + } + return $pages; + } + + /** + * Fix ordering + * + * @param int $a_portfolio_id + */ + public static function fixOrdering($a_portfolio_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $pages = self::getAllPortfolioPages($a_portfolio_id); + $cnt = 10; + foreach ($pages as $p) { + $ilDB->manipulate( + "UPDATE usr_portfolio_page SET " . + " order_nr = " . $ilDB->quote($cnt, "integer") . + " WHERE id = " . $ilDB->quote($p["id"], "integer") + ); + $cnt+= 10; + } + } + + /** + * Get portfolio id of page id + * + * @param int $a_page_id + * @return int + */ + public static function findPortfolioForPage($a_page_id) + { + return self::lookupProperty($a_page_id, "portfolio_id"); + } + + /** + * Get goto href for internal wiki page link target + * + * @param + * @return string + */ + public static function getGotoForPortfolioPageTarget($a_target, $a_offline = false) + { + global $DIC; + + $pid = self::findPortfolioForPage((int) $a_target); + $type = ilObject::_lookupType($pid); + if ($type == "prtt") { + $ctrl = $DIC->ctrl(); + $ctrl->setParameterByClass("ilobjportfoliotemplategui", "user_page", $a_target); + $href = $ctrl->getLinkTargetByClass(array("ilRepositoryGUI", "ilObjPortfolioTemplateGUI", "ilobjportfoliotemplategui"), "preview"); + } else { + if (!$a_offline) { + $href = "./goto.php?client_id=" . CLIENT_ID . "&target=prtf_" . $pid . "_" . $a_target; + } else { + $href = "prtf_" . $a_target . ".html"; + } + } + return $href; + } + + /** + * Update internal links, after multiple pages have been copied + */ + public static function updateInternalLinks($a_copied_nodes, ilObjPortfolioBase $a_target_obj) + { + // var_dump($a_copied_nodes); + $all_fixes = array(); + foreach ($a_copied_nodes as $original_id => $copied_id) { + $pid = self::findPortfolioForPage((int) $copied_id); + + // + // 1. Outgoing links from the copied page. + // + //$targets = ilInternalLink::_getTargetsOfSource($a_parent_type.":pg", $copied_id); + if ($a_target_obj->getType() == "prtf") { + $tpg = new ilPortfolioPage($copied_id); + } + if ($a_target_obj->getType() == "prtt") { + $tpg = new ilPortfolioTemplatePage($copied_id); + } + $tpg->buildDom(); + $il = $tpg->getInternalLinks(); + // var_dump($il); + $targets = array(); + foreach ($il as $l) { + $targets[] = array("type" => ilInternalLink::_extractTypeOfTarget($l["Target"]), + "id" => (int) ilInternalLink::_extractObjIdOfTarget($l["Target"]), + "inst" => (int) ilInternalLink::_extractInstOfTarget($l["Target"])); + } + $fix = array(); + foreach ($targets as $target) { + if (($target["inst"] == 0 || $target["inst"] = IL_INST_ID) && + ($target["type"] == "ppage")) { + // first check, whether target is also within the copied set + if ($a_copied_nodes[$target["id"]] > 0) { + $fix[$target["id"]] = $a_copied_nodes[$target["id"]]; + } + } + } + // var_dump($fix); + // outgoing links to be fixed + if (count($fix) > 0) { + $t = ilObject::_lookupType($pid); + if (is_array($all_fixes[$t . ":" . $copied_id])) { + $all_fixes[$t . ":" . $copied_id] += $fix; + } else { + $all_fixes[$t . ":" . $copied_id] = $fix; + } + } + } + // var_dump($all_fixes); + foreach ($all_fixes as $pg => $fixes) { + $pg = explode(":", $pg); + include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); + $page = ilPageObjectFactory::getInstance($pg[0], $pg[1]); + if ($page->moveIntLinks($fixes)) { + $page->update(true, true); + } + } + } + + + /** + * @param $a_title_changes + */ + public function renameLinksOnTitleChange($a_title_changes) + { + $this->buildDom(); + + $changed = false; + + // resolve normal internal links + $xpc = xpath_new_context($this->dom); + $path = "//IntLink"; + $res = xpath_eval($xpc, $path); + for ($i = 0; $i < count($res->nodeset); $i++) { + $target = $res->nodeset[$i]->get_attribute("Target"); + $type = $res->nodeset[$i]->get_attribute("Type"); + $obj_id = ilInternalLink::_extractObjIdOfTarget($target); + if (isset($a_title_changes[$obj_id]) && is_int(strpos($target, "__"))) { + if ($type == "PortfolioPage") { + if ($res->nodeset[$i]->get_content() == $a_title_changes[$obj_id]["old"]) { + $res->nodeset[$i]->set_content($a_title_changes[$obj_id]["new"]); + $changed = true; + } + } + } + } + unset($xpc); + + return $changed; + } + + /** + * Get portfolio pages for blog + * + * @param int $a_blog_id + * @return ilPortfolioPage[] + */ + public static function getPagesForBlog($a_blog_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query("SELECT * FROM usr_portfolio_page" . + " WHERE title = " . $ilDB->quote($a_blog_id, "text") . + " AND type = " . $ilDB->quote(self::TYPE_BLOG, "integer")); + $pages = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $pages[] = new ilPortfolioPage($rec["id"]); + } + return $pages; + } +} diff --git a/Modules/Portfolio/classes/class.ilPortfolioPageAction.php b/Modules/Portfolio/classes/class.ilPortfolioPageAction.php index 389370bd07c39007a189168db9bdba1cf0f6051d..b578075b36a80c0630f2e0257c362c19b06fca0c 100644 --- a/Modules/Portfolio/classes/class.ilPortfolioPageAction.php +++ b/Modules/Portfolio/classes/class.ilPortfolioPageAction.php @@ -10,40 +10,35 @@ */ class ilPortfolioPageAction { - /** - * @var ilObjUser - */ - protected $actor; + /** + * @var ilObjUser + */ + protected $actor; - /** - * Constructor - */ - public function __construct(ilObjUser $actor = null) - { - global $DIC; - if (is_null($actor)) - { - $actor = $DIC->user(); - } - $this->actor = $actor; - } + /** + * Constructor + */ + public function __construct(ilObjUser $actor = null) + { + global $DIC; + if (is_null($actor)) { + $actor = $DIC->user(); + } + $this->actor = $actor; + } - /** - * Delete pages of blog - * - * @param int $a_blog_id - */ - public function deletePagesOfBlog($a_blog_id) - { - $pages = ilPortfolioPage::getPagesForBlog($a_blog_id); - foreach ($pages as $page) - { - if (ilObject::_lookupOwner($page->getPortfolioId()) == $this->actor->getId()) - { - $page->delete(); - } - } - } - - -} \ No newline at end of file + /** + * Delete pages of blog + * + * @param int $a_blog_id + */ + public function deletePagesOfBlog($a_blog_id) + { + $pages = ilPortfolioPage::getPagesForBlog($a_blog_id); + foreach ($pages as $page) { + if (ilObject::_lookupOwner($page->getPortfolioId()) == $this->actor->getId()) { + $page->delete(); + } + } + } +} diff --git a/Modules/Portfolio/classes/class.ilPortfolioPageConfig.php b/Modules/Portfolio/classes/class.ilPortfolioPageConfig.php index b420ac471956f0aadf99ca9aa2fd11ec8fa8a62f..ad5421c0d2458e1e6d85b412148e995a17c7f844 100644 --- a/Modules/Portfolio/classes/class.ilPortfolioPageConfig.php +++ b/Modules/Portfolio/classes/class.ilPortfolioPageConfig.php @@ -5,7 +5,7 @@ include_once("./Services/COPage/classes/class.ilPageConfig.php"); /** - * Portfolio page configuration + * Portfolio page configuration * * @author Alex Killing * @version $Id$ @@ -13,75 +13,68 @@ include_once("./Services/COPage/classes/class.ilPageConfig.php"); */ class ilPortfolioPageConfig extends ilPageConfig { - /** - * @var ilSetting - */ - protected $settings; + /** + * @var ilSetting + */ + protected $settings; - /** - * @var ilRbacSystem - */ - protected $rbacsystem; + /** + * @var ilRbacSystem + */ + protected $rbacsystem; - /** - * Init - */ - function init() - { - global $DIC; + /** + * Init + */ + public function init() + { + global $DIC; - $this->settings = $DIC->settings(); - $this->rbacsystem = $DIC->rbac()->system(); + $this->settings = $DIC->settings(); + $this->rbacsystem = $DIC->rbac()->system(); - $ilSetting = $this->settings; - $rbacsystem = $this->rbacsystem; - - $prfa_set = new ilSetting("prfa"); - $this->setPreventHTMLUnmasking(!(bool)$prfa_set->get("mask", false)); + $ilSetting = $this->settings; + $rbacsystem = $this->rbacsystem; + + $prfa_set = new ilSetting("prfa"); + $this->setPreventHTMLUnmasking(!(bool) $prfa_set->get("mask", false)); - $this->setEnableInternalLinks(true); - $this->setIntLinkFilterWhiteList(true); - $this->addIntLinkFilter("User"); - $this->addIntLinkFilter("PortfolioPage"); - $this->removeIntLinkFilter("File"); - $this->setIntLinkHelpDefaultId($_GET["prt_id"], false); - $this->setIntLinkHelpDefaultType("PortfolioPage"); - $this->setEnablePCType("Profile", true); - $this->setEditLockSupport(false); - - if(!$ilSetting->get('disable_wsp_certificates')) - { - $this->setEnablePCType("Verification", true); - } - $skmg_set = new ilSetting("skmg"); - if($skmg_set->get("enable_skmg")) - { - $this->setEnablePCType("Skills", true); - } - - include_once './Services/Calendar/classes/class.ilCalendarUserSettings.php'; - $settings = ilCalendarSettings::_getInstance(); - if($settings->isEnabled() && - $rbacsystem->checkAccess('add_consultation_hours', $settings->getCalendarSettingsId()) && - $settings->areConsultationHoursEnabled()) - { - $this->setEnablePCType("ConsultationHours", true); - } - - $prfa_set = new ilSetting("prfa"); - if($prfa_set->get("mycrs", true)) - { - $this->setEnablePCType("MyCourses", true); - } + $this->setEnableInternalLinks(true); + $this->setIntLinkFilterWhiteList(true); + $this->addIntLinkFilter("User"); + $this->addIntLinkFilter("PortfolioPage"); + $this->removeIntLinkFilter("File"); + $this->setIntLinkHelpDefaultId($_GET["prt_id"], false); + $this->setIntLinkHelpDefaultType("PortfolioPage"); + $this->setEnablePCType("Profile", true); + $this->setEditLockSupport(false); + + if (!$ilSetting->get('disable_wsp_certificates')) { + $this->setEnablePCType("Verification", true); + } + $skmg_set = new ilSetting("skmg"); + if ($skmg_set->get("enable_skmg")) { + $this->setEnablePCType("Skills", true); + } + + include_once './Services/Calendar/classes/class.ilCalendarUserSettings.php'; + $settings = ilCalendarSettings::_getInstance(); + if ($settings->isEnabled() && + $rbacsystem->checkAccess('add_consultation_hours', $settings->getCalendarSettingsId()) && + $settings->areConsultationHoursEnabled()) { + $this->setEnablePCType("ConsultationHours", true); + } + + $prfa_set = new ilSetting("prfa"); + if ($prfa_set->get("mycrs", true)) { + $this->setEnablePCType("MyCourses", true); + } - $mset = new ilSetting("mobs"); - if ($mset->get("mep_activate_pages")) - { - $this->setEnablePCType("ContentInclude", true); - } + $mset = new ilSetting("mobs"); + if ($mset->get("mep_activate_pages")) { + $this->setEnablePCType("ContentInclude", true); + } - $this->setEnablePCType("LearningHistory", true); - } + $this->setEnablePCType("LearningHistory", true); + } } - -?> diff --git a/Modules/Portfolio/classes/class.ilPortfolioPageGUI.php b/Modules/Portfolio/classes/class.ilPortfolioPageGUI.php index 4981357ed72ef4849adb4a9180d6e080b8dda290..0ca26ead74e32382f8cfd4373d40fb887583764e 100644 --- a/Modules/Portfolio/classes/class.ilPortfolioPageGUI.php +++ b/Modules/Portfolio/classes/class.ilPortfolioPageGUI.php @@ -1,1320 +1,1217 @@ - - * @version $Id$ - * - * @ilCtrl_Calls ilPortfolioPageGUI: ilPageEditorGUI, ilEditClipboardGUI, ilMediaPoolTargetSelector - * @ilCtrl_Calls ilPortfolioPageGUI: ilPageObjectGUI, ilObjBlogGUI, ilBlogPostingGUI - * @ilCtrl_Calls ilPortfolioPageGUI: ilCalendarMonthGUI, ilConsultationHoursGUI, ilLearningHistoryGUI - * - * @ingroup ModulesPortfolio - */ -class ilPortfolioPageGUI extends ilPageObjectGUI -{ - /** - * @var ilObjectDefinition - */ - protected $obj_definition; - - /** - * @var ilTree - */ - protected $tree; - - const EMBEDDED_NO_OUTPUT = -99; - - protected $js_onload_code = array(); - protected $additional = array(); - protected $export_material = array("js"=>array(), "images"=>array(), "files"=>array()); - - protected static $initialized = 0; - - /** - * Constructor - */ - function __construct($a_portfolio_id, $a_id = 0, $a_old_nr = 0, $a_enable_comments = true) - { - global $DIC; - - $this->tpl = $DIC["tpl"]; - $this->ctrl = $DIC->ctrl(); - $this->user = $DIC->user(); - $this->obj_definition = $DIC["objDefinition"]; - $this->access = $DIC->access(); - $this->tree = $DIC->repositoryTree(); - $this->lng = $DIC->language(); - $tpl = $DIC["tpl"]; - - $this->portfolio_id = (int)$a_portfolio_id; - $this->enable_comments = (bool)$a_enable_comments; - - parent::__construct($this->getParentType(), $a_id, $a_old_nr); - $this->getPageObject()->setPortfolioId($this->portfolio_id); - - // content style - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - - $tpl->setCurrentBlock("SyntaxStyle"); - $tpl->setVariable("LOCATION_SYNTAX_STYLESHEET", - ilObjStyleSheet::getSyntaxStylePath()); - $tpl->parseCurrentBlock(); - - $tpl->setCurrentBlock("ContentStyle"); - $tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath(0)); - $tpl->setVariable("LOCATION_ADDITIONAL_STYLESHEET", - ilObjStyleSheet::getPlaceHolderStylePath()); - $tpl->parseCurrentBlock(); - } - - function getParentType() - { - return "prtf"; - } - - protected function getPageContentUserId($a_user_id) - { - // user id from content-xml - return $a_user_id; - } - - /** - * execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - switch($next_class) - { - case "ilobjbloggui": - // #12879 - we need the wsp-id for the keywords - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - $wsp_tree = new ilWorkspaceTree($ilUser->getId()); - $blog_obj_id = (int)$this->getPageObject()->getTitle(); - $blog_node_id = $wsp_tree->lookupNodeId($blog_obj_id); - - include_once "Modules/Blog/classes/class.ilObjBlogGUI.php"; - $blog_gui = new ilObjBlogGUI($blog_node_id, ilObjBlogGUI::WORKSPACE_NODE_ID); - $blog_gui->disableNotes(!$this->enable_comments); - $blog_gui->prtf_embed = true; // disables prepareOutput()/getStandardTemplate() in blog - return $ilCtrl->forwardCommand($blog_gui); - - case "ilcalendarmonthgui": - - - // booking action - if($cmd && $cmd != "preview") - { - $categories = ilCalendarCategories::_getInstance(); - if($categories->getMode() == 0) - { - if($_GET['chuid']) - { - $categories->setCHUserId((int) $_GET['chuid']); - } - $categories->initialize(ilCalendarCategories::MODE_PORTFOLIO_CONSULTATION, null, true); - } - - if($_GET['seed']) - { - $seed = new ilDate((string) $_GET['seed'], IL_CAL_DATE); - } - else - { - $seed = new ilDate(time(),IL_CAL_UNIX); - } - - include_once('./Services/Calendar/classes/class.ilCalendarMonthGUI.php'); - $month_gui = new ilCalendarMonthGUI($seed); - return $ilCtrl->forwardCommand($month_gui); - } - // calendar month navigation - else - { - $ilCtrl->setParameter($this, "cmd", "preview"); - return self::EMBEDDED_NO_OUTPUT; - } - - case "ilpageobjectgui": - die("Deprecated. ilPortfolioPage gui forwarding to ilpageobject"); - return; - - default: - $this->setPresentationTitle($this->getPageObject()->getTitle()); - return parent::executeCommand(); - } - } - - /** - * Show page - * - * @return string page output - */ - function showPage() - { - $ilUser = $this->user; - - if(!$this->getPageObject()) - { - return; - } - - switch($this->getPageObject()->getType()) - { - case ilPortfolioPage::TYPE_BLOG; - return $this->renderBlog($ilUser->getId(), (int)$this->getPageObject()->getTitle()); - - default: - $this->setTemplateOutput(false); - // $this->setPresentationTitle($this->getPageObject()->getTitle()); - $output = parent::showPage(); - - return $output; - } - } - - /** - * Set all tabs - * - * @param - * @return - */ - function getTabs($a_activate = "") - { - if(!$this->embedded) - { - parent::getTabs($a_activate); - } - } - - /** - * Set embedded mode: will suppress tabs - * - * @param bool $a_value - */ - function setEmbedded($a_value) - { - $this->embedded = (bool)$a_value; - } - - /** - * Set Additonal Information. - * - * @param array $a_additional Additonal Information - */ - function setAdditional($a_additional) - { - $this->additional = $a_additional; - } - - /** - * Get Additonal Information. - * - * @return array Additonal Information - */ - function getAdditional() - { - return $this->additional; - } - - function getJsOnloadCode() - { - return $this->js_onload_code; - } - - function postOutputProcessing($a_output) - { - $parts = array( - "Profile" => array("0-9", "a-z", "0-9a-z_;\W"), // user, mode, fields - "Verification" => array("0-9", "a-z", "0-9"), // user, type, id - "Blog" => array("0-9", "0-9", "0-9;\W"), // user, blog id, posting ids - "BlogTeaser" => array("0-9", "0-9", "0-9;\W"), // user, blog id, posting ids - "Skills" => array("0-9", "0-9"), // user, skill id - "SkillsTeaser" => array("0-9", "0-9"), // user, skill id - "ConsultationHours" => array("0-9", "a-z", "0-9;\W"), // user, mode, group ids - "ConsultationHoursTeaser" => array("0-9", "a-z", "0-9;\W"), // user, mode, group ids - "MyCourses" => array("0-9", "a-z*"), // user, sort - "MyCoursesTeaser" => array("0-9", "a-z*") // user, sort - ); - - foreach($parts as $type => $def) - { - // #15732 - allow optional parts - $def_parts = array(); - foreach($def as $part) - { - $is_opt = (substr($part, -1) == "*"); - if(!$is_opt) - { - $def_parts[] = "#"; - $end_marker = "+"; - } - else - { - $def_parts[] = "#*"; - $end_marker = "*"; - $part = substr($part, 0, -1); - } - $def_parts[] = "([".$part."]".$end_marker.")"; - } - $def = implode("", $def_parts); - - if(preg_match_all( - "/".$this->pl_start.$type.$def.$this->pl_end."/", - $a_output, $blocks)) - { - foreach($blocks[0] as $idx => $block) - { - switch($type) - { - case "Profile": - case "Blog": - case "BlogTeaser": - case "Skills": - case "SkillsTeaser": - case "ConsultationHours": - case "ConsultationHoursTeaser": - case "MyCourses": - case "MyCoursesTeaser": - $subs = null; - if(trim($blocks[3][$idx])) - { - foreach(explode(";", $blocks[3][$idx]) as $sub) - { - if(trim($sub)) - { - $subs[] = trim($sub); - } - } - } - $snippet = $this->{"render".$type}($blocks[1][$idx], - $blocks[2][$idx], $subs); - break; - - default: - $snippet = $this->{"render".$type}($blocks[1][$idx], - $blocks[2][$idx], $blocks[3][$idx]); - break; - } - - $snippet = $this->renderPageElement($type, $snippet); - $a_output = str_replace($block, $snippet, $a_output); - } - } - } - - $a_output = $this->makePlaceHoldersClickable($a_output); - - return $a_output; - } - - protected function renderPageElement($a_type, $a_html) - { - return trim($a_html); - } - - protected function renderTeaser($a_type, $a_title, $a_options = null) - { - $options = ""; - if($a_options) - { - $options = ''; - } - - return '

'.$a_title.'

'. - '
'.$this->lng->txt("prtf_page_element_teaser_".$a_type).'
'. - $options.'
'; - } - - protected function renderProfile($a_user_id, $a_type, array $a_fields = null) - { - $ilCtrl = $this->ctrl; - - $user_id = $this->getPageContentUserId($a_user_id); - - if($this->getOutputMode() == "offline") - { - // profile picture is done in ilPortfolioHTMLExport - - $this->export_material["js"][] = "http://maps.google.com/maps/api/js?sensor=false"; - $this->export_material["js"][] = "./Services/Maps/js/ServiceGoogleMaps.js"; - $this->export_material["js"][] = "./Services/Maps/js/OpenLayers.js"; - $this->export_material["js"][] = "./Services/Maps/js/ServiceOpenLayers.js"; - } - - include_once("./Services/User/classes/class.ilPublicUserProfileGUI.php"); - $pub_profile = new ilPublicUserProfileGUI($user_id); - $pub_profile->setEmbedded(true, ($this->getOutputMode() == "offline")); - - // full circle: additional was set in the original public user profile call - $pub_profile->setAdditional($this->getAdditional()); - - if($a_type == "manual" && sizeof($a_fields)) - { - $prefs = array(); - foreach($a_fields as $field) - { - $field = trim($field); - if($field) - { - $prefs["public_".$field] = "y"; - } - } - - $pub_profile->setCustomPrefs($prefs); - } - - if($this->getOutputMode() != "offline") - { - return $ilCtrl->getHTML($pub_profile); - } - else - { - return $pub_profile->getEmbeddable(); - } - } - - /** - * @param $a_user_id - * @param $a_type - * @param $a_id - * @return string - * @throws ilException - */ - protected function renderVerification($a_user_id, $a_type, $a_id) - { - $objDefinition = $this->obj_definition; - - $outputMode = $this->getOutputMode(); - - // not used - // $user_id = $this->getPageContentUserId($a_user_id); - if ($a_type === 'crta' && $outputMode === 'offline') { - $fileService = new ilPortfolioCertificateFileService(); - - $certificatePdfFile = $fileService->createCertificateFilePath($a_user_id, $a_id); - $this->export_material["files"][] = $certificatePdfFile; - - $url = 'files/' . basename($certificatePdfFile); - - $userCertificateRepository = new ilUserCertificateRepository(); - - return $this->createPersistentCertificateUrl($a_id, $userCertificateRepository, $url); - } elseif ($a_type === 'crta' && $outputMode === 'print') { - $userCertificateRepository = new ilUserCertificateRepository(); - $url = $this->getPagePermaLink(); - - return $this->createPersistentCertificateUrl($a_id, $userCertificateRepository, $url); - } - elseif ($a_type === 'crta') { - $this->ctrl->setParameter($this, "dlid", $a_id); - $url = $this->ctrl->getLinkTarget($this, "dl" . $a_type); - $this->ctrl->setParameter($this, "dlid", ""); - - $userCertificateRepository = new ilUserCertificateRepository(); - - return $this->createPersistentCertificateUrl($a_id, $userCertificateRepository, $url); - } - - $class = "ilObj".$objDefinition->getClassName($a_type)."GUI"; - include_once $objDefinition->getLocation($a_type)."/class.".$class.".php"; - $verification = new $class($a_id, ilObject2GUI::WORKSPACE_OBJECT_ID); - - if($outputMode == "print") - { - $url = $this->getPagePermaLink(); - } - else if($outputMode != "offline") - { - // direct download link - $this->ctrl->setParameter($this, "dlid", $a_id); - $url = $this->ctrl->getLinkTarget($this, "dl".$a_type); - $this->ctrl->setParameter($this, "dlid", ""); - } - else - { - $file = $verification->object->getFilePath(); - $url = "files/".basename($file); - - $this->export_material["files"][] = $file; - } - - return $verification->render(true, $url); - } - - protected function dltstv() - { - $id = $_GET["dlid"]; - if($id) - { - include_once "Modules/Test/classes/class.ilObjTestVerificationGUI.php"; - $verification = new ilObjTestVerificationGUI($id, ilObject2GUI::WORKSPACE_OBJECT_ID); - $verification->downloadFromPortfolioPage($this->getPageObject()); - } - } - - protected function dlexcv() - { - $id = $_GET["dlid"]; - if($id) - { - include_once "Modules/Exercise/classes/class.ilObjExerciseVerificationGUI.php"; - $verification = new ilObjExerciseVerificationGUI($id, ilObject2GUI::WORKSPACE_OBJECT_ID); - $verification->downloadFromPortfolioPage($this->getPageObject()); - } - } - - protected function dlcrsv() - { - $id = $_GET["dlid"]; - if($id) - { - include_once "Modules/Course/classes/Verification/class.ilObjCourseVerificationGUI.php"; - $verification = new ilObjCourseVerificationGUI($id, ilObject2GUI::WORKSPACE_OBJECT_ID); - $verification->downloadFromPortfolioPage($this->getPageObject()); - } - } - - protected function dlscov() - { - $id = $_GET["dlid"]; - if($id) - { - include_once "Modules/ScormAicc/classes/Verification/class.ilObjSCORMVerificationGUI.php"; - $verification = new ilObjSCORMVerificationGUI($id, ilObject2GUI::WORKSPACE_OBJECT_ID); - $verification->downloadFromPortfolioPage($this->getPageObject()); - } - } - - protected function dlcrta() - { - $objectId = $_GET["dlid"]; - if($objectId) { - $object = new ilObjPersistentCertificateVerificationGUI(); - $object->downloadFromPortfolioPage($this->getPageObject(), $objectId, $this->user->getId()); - } - } - - protected function renderBlog($a_user_id, $a_blog_id, array $a_posting_ids = null) - { - $ilCtrl = $this->ctrl; - - // not used - // $user_id = $this->getPageContentUserId($a_user_id); - - // full blog (separate tab/page) - if(!$a_posting_ids) - { - include_once "Modules/Blog/classes/class.ilObjBlogGUI.php"; - if (ilObject::_lookupType($a_blog_id) != "blog") { - return; - } - $blog = new ilObjBlogGUI($a_blog_id, ilObject2GUI::WORKSPACE_OBJECT_ID); - $blog->disableNotes(!$this->enable_comments); - $blog->setContentStyleSheet(); - - if($this->getOutputMode() != "offline") - { - return $ilCtrl->getHTML($blog); - } - else - { - - } - } - // embedded postings - else - { - $html = array(); - - include_once "Modules/Blog/classes/class.ilObjBlog.php"; - $html[] = ilObjBlog::_lookupTitle($a_blog_id); - - include_once "Modules/Blog/classes/class.ilBlogPostingGUI.php"; - foreach($a_posting_ids as $post) - { - $page = new ilBlogPostingGUI(0, null, $post); - if($this->getOutputMode() != "offline") - { - $page->setOutputMode(IL_PAGE_PREVIEW); - } - else - { - $page->setOutputMode("offline"); - } - $html[] = $page->showPage(); - } - - return implode("\n", $html); - } - } - - protected function renderBlogTeaser($a_user_id, $a_blog_id, array $a_posting_ids = null) - { - // not used - // $user_id = $this->getPageContentUserId($a_user_id); - - $postings = ""; - if($a_posting_ids) - { - $postings = array("
    "); - include_once "Modules/Blog/classes/class.ilBlogPosting.php"; - foreach($a_posting_ids as $post) - { - $post = new ilBlogPosting($post); - $postings[] = "
  • ".$post->getTitle()." - ". - ilDatePresentation::formatDate($post->getCreated())."
  • "; - } - $postings[] = "
"; - $postings = implode("\n", $postings); - } - - return $this->renderTeaser("blog", $this->lng->txt("obj_blog").' "'. - ilObject::_lookupTitle($a_blog_id).'"', $postings); - } - - protected function renderSkills($a_user_id, $a_skills_id) - { - if($this->getOutputMode() == "preview") - { - return $this->renderSkillsTeaser($a_user_id, $a_skills_id); - } - - $user_id = $this->getPageContentUserId($a_user_id); - - include_once "Services/Skill/classes/class.ilPersonalSkillsGUI.php"; - $gui = new ilPersonalSkillsGUI(); - if($this->getOutputMode() == "offline") - { - $gui->setOfflineMode("./files/"); - } - $html = $gui->getSkillHTML($a_skills_id, $user_id); - - return $html; - } - - protected function renderSkillsTeaser($a_user_id, $a_skills_id) - { - // not used - // $user_id = $this->getPageContentUserId($a_user_id); - - include_once "Services/Skill/classes/class.ilSkillTreeNode.php"; - - return $this->renderTeaser("skills", $this->lng->txt("skills").' "'. - ilSkillTreeNode::_lookupTitle($a_skills_id).'"'); - } - - protected function renderConsultationHoursTeaser($a_user_id, $a_mode, $a_group_ids) - { - // not used - // $user_id = $this->getPageContentUserId($a_user_id); - - if($a_mode == "auto") - { - $mode = $this->lng->txt("cont_cach_mode_automatic"); - $groups = null; - } - else - { - $mode = $this->lng->txt("cont_cach_mode_manual"); - - include_once "Services/Calendar/classes/ConsultationHours/class.ilConsultationHourGroups.php"; - $groups = array(); - foreach($a_group_ids as $grp_id) - { - $groups[] = ilConsultationHourGroups::lookupTitle($grp_id); - } - $groups = " (".implode(", ", $groups).")"; - } - - $this->lng->loadLanguageModule("dateplaner"); - return $this->renderTeaser("consultation_hours", - $this->lng->txt("app_consultation_hours"), $mode.$groups); - } - - protected function renderConsultationHours($a_user_id, $a_mode, $a_group_ids) - { - $ilUser = $this->user; - - if($this->getOutputMode() == "preview") - { - return $this->renderConsultationHoursTeaser($a_user_id, $a_mode, $a_group_ids); - } - - if($this->getOutputMode() == "offline") - { - return; - } - - if($this->getOutputMode() == "print") - { - return; - } - - $user_id = $this->getPageContentUserId($a_user_id); - - // only if not owner - if($ilUser->getId() != $user_id) - { - $_GET["bkid"] = $user_id; - } - - if($a_mode != "manual") - { - $a_group_ids = null; - } - - include_once('./Services/Calendar/classes/class.ilCalendarCategories.php'); - ilCalendarCategories::_getInstance()->setCHUserId($user_id); - ilCalendarCategories::_getInstance()->initialize(ilCalendarCategories::MODE_PORTFOLIO_CONSULTATION, null, true); - - if(!$_REQUEST["seed"]) - { - $seed = new ilDate(time(), IL_CAL_UNIX); - } - else - { - $seed = new ilDate($_REQUEST["seed"], IL_CAL_DATE); - } - - include_once('./Services/Calendar/classes/class.ilCalendarMonthGUI.php'); - $month_gui = new ilCalendarMonthGUI($seed); - $month_gui->setConsulationHoursUserId($user_id); - - // custom schedule filter: handle booking group ids - include_once('./Services/Calendar/classes/class.ilCalendarScheduleFilterBookings.php'); - $filter = new ilCalendarScheduleFilterBookings($user_id, $a_group_ids); - $month_gui->addScheduleFilter($filter); - - $this->tpl->addCss(ilUtil::getStyleSheetLocation('filesystem','delos.css','Services/Calendar')); - - $this->lng->loadLanguageModule("dateplaner"); - return '

'.$this->lng->txt("app_consultation_hours").'

'. - $this->ctrl->getHTML($month_gui); - } - - protected function isMyCoursesActive() - { - $prfa_set = new ilSetting("prfa"); - return (bool)$prfa_set->get("mycrs", true); - } - - protected function renderMyCoursesTeaser($a_user_id, $a_default_sorting) - { - // not used - // $user_id = $this->getPageContentUserId($a_user_id); - - $title = $this->isMyCoursesActive() - ? "my_courses" - : "my_courses_inactive"; - - return $this->renderTeaser($title, - $this->lng->txt("prtf_page_element_my_courses_title")); - } - - protected function renderMyCourses($a_user_id, $a_default_sorting) - { - $ilAccess = $this->access; - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - - if($this->getOutputMode() == "preview") - { - return $this->renderMyCoursesTeaser($a_user_id, $a_default_sorting); - } - - if(!$this->isMyCoursesActive()) - { - return; - } - - $img_path = null; - if($this->getOutputMode() == "offline") - { - $this->export_material["images"][] = "./templates/default/images/icon_crs.svg"; - $this->export_material["images"][] = "./templates/default/images/icon_lobj.svg"; - $this->export_material["images"][] = "./templates/default/images/scorm/complete.svg"; - $this->export_material["images"][] = "./templates/default/images/scorm/not_attempted.svg"; - $this->export_material["images"][] = "./templates/default/images/scorm/failed.svg"; - $this->export_material["images"][] = "./templates/default/images/scorm/incomplete.svg"; - - $img_path = "images/"; - } - - $user_id = $this->getPageContentUserId($a_user_id); - - // sorting pref - if($_POST["srt"] && - in_array($_POST["srt"], array("alpha", "loc"))) - { - $ilUser->writePref("prtf_mcrs_sort", $_POST["srt"]); - } - $sorting = $ilUser->getPref("prtf_mcrs_sort"); - if(!$sorting) - { - $sorting = $a_default_sorting; - } - - $data = $this->getCoursesOfUser($user_id, ($sorting == "loc")); - if(sizeof($data)) - { - if($sorting != "loc") - { - $data = ilUtil::sortArray($data, "title", "ASC"); - } - else - { - $data = ilUtil::sortArray($data, "path_sort", "ASC"); - } - - $tpl = new ilTemplate("tpl.pc_my_courses.html", true, true, "Modules/Portfolio"); - $tpl->setVariable("TITLE", $this->lng->txt("prtf_page_element_my_courses_title")); - $tpl->setVariable("INFO", $this->lng->txt("prtf_page_element_my_courses_info")); // #14464 - - include_once("./Services/Tracking/classes/class.ilLearningProgressBaseGUI.php"); - $this->lng->loadLanguageModule("trac"); - $this->lng->loadLanguageModule("crs"); - - include_once("./Services/Container/classes/class.ilContainerObjectiveGUI.php"); - include_once("./Services/Link/classes/class.ilLink.php"); - - // sorting - if($this->getOutputMode() != "print") - { - $options = array( - "alpha" => $this->lng->txt("cont_mycourses_sortorder_alphabetical"), - "loc" => $this->lng->txt("cont_mycourses_sortorder_location") - ); - $tpl->setVariable("SORT_SELECT", ilUtil::formSelect($sorting, "srt", $options, false, true, 0, "", - array("onchange" => "form.submit()"))); - $tpl->setVariable("SORT_FORM", $this->getCourseSortAction($ilCtrl)); - } - - $old_path = null; - - foreach($data as $course) - { - if($sorting == "loc") - { - if($course["path"] != $old_path) - { - $tpl->setCurrentBlock("path_bl"); - $tpl->setVariable("PATH", $course["path"]); - $tpl->parseCurrentBlock(); - - $old_path = $course["path"]; - } - } - - if(isset($course["lp_status"])) - { - $lp_icon = ilLearningProgressBaseGUI::_getImagePathForStatus($course["lp_status"]); - $lp_alt = ilLearningProgressBaseGUI::_getStatusText($course["lp_status"]); - - if($img_path) - { - $lp_icon = $img_path.basename($lp_icon); - } - - $tpl->setCurrentBlock("lp_bl"); - $tpl->setVariable("LP_ICON_URL", $lp_icon); - $tpl->setVariable("LP_ICON_ALT", $lp_alt); - $tpl->parseCurrentBlock(); - } - - $do_links = false; - if($ilUser->getId() != ANONYMOUS_USER_ID) - { - $do_links = $ilAccess->checkAccessOfUser($ilUser->getId(), "read", "", $course["ref_id"], "crs") || - ($ilAccess->checkAccessOfUser($ilUser->getId(), "visible", "", $course["ref_id"], "crs") && - $ilAccess->checkAccessOfUser($ilUser->getId(), "join", "", $course["ref_id"], "crs")); - } - - if(isset($course["objectives"])) - { - include_once './Modules/Course/classes/Objectives/class.ilLOSettings.php'; - $loc_settings = ilLOSettings::getInstanceByObjId($course["obj_id"]); - $has_initial_test = (bool)$loc_settings->getInitialTest(); - - foreach($course["objectives"] as $objtv) - { - if($do_links) - { - $params = array("oobj"=>$objtv["id"]); - $url = ilLink::_getLink($course["ref_id"], "crs", $params); - - // #15510 - $url .= "#objtv_acc_".$objtv["id"]; - - if ($this->getOutputMode() != "print") - { - $tpl->touchBlock("objective_dnone"); - } - - $tpl->setCurrentBlock("objective_link_bl"); - - if(trim($objtv["desc"])) - { - $desc = nl2br($objtv["desc"]); - $tt_id = "objtvtt_".$objtv["id"]."_".((int)self::$initialized); - - include_once "Services/UIComponent/Tooltip/classes/class.ilTooltipGUI.php"; - ilToolTipGUI::addTooltip($tt_id, $desc, "", "bottom center", "top center", false); - - $tpl->setVariable("OBJECTIVE_LINK_ID", $tt_id); - } - - $tpl->setVariable("OBJECTIVE_LINK_URL", $url); - $tpl->setVariable("OBJECTIVE_LINK_TITLE", $objtv["title"]); - $tpl->parseCurrentBlock(); - } - else - { - $tpl->setCurrentBlock("objective_nolink_bl"); - $tpl->setVariable("OBJECTIVE_NOLINK_TITLE", $objtv["title"]); - $tpl->parseCurrentBlock(); - } - - $objtv_icon = ilUtil::getTypeIconPath("lobj", $objtv["id"]); - if($img_path) - { - $objtv_icon = $img_path.basename($objtv_icon); - } - - $tpl->setCurrentBlock("objective_bl"); - $tpl->setVariable("OBJTV_ICON_URL", $objtv_icon); - $tpl->setVariable("OBJTV_ICON_ALT", $this->lng->txt("crs_objectives")); - - if($objtv["type"]) - { - $tpl->setVariable("LP_OBJTV_PROGRESS", - ilContainerObjectiveGUI::buildObjectiveProgressBar($has_initial_test, $objtv["id"], $objtv, true, false, (int)self::$initialized)); - } - - $tpl->parseCurrentBlock(); - } - - $tpl->setCurrentBlock("objectives_bl"); - $tpl->setVariable("OBJTV_LIST_CRS_ID", $course["obj_id"]); - $tpl->parseCurrentBlock(); - } - - // always check against current user - if($do_links) - { - $tpl->setCurrentBlock("course_link_bl"); - $tpl->setVariable("COURSE_LINK_TITLE", $course["title"]); - $tpl->setVariable("COURSE_LINK_URL", ilLink::_getLink($course["ref_id"])); - $tpl->parseCurrentBlock(); - } - else - { - $tpl->setCurrentBlock("course_nolink_bl"); - $tpl->setVariable("COURSE_NOLINK_TITLE", $course["title"]); - $tpl->parseCurrentBlock(); - } - - $crs_icon = ilUtil::getTypeIconPath("crs", $course["obj_id"]); - if($img_path) - { - $crs_icon = $img_path.basename($crs_icon); - } - - $tpl->setCurrentBlock("course_bl"); - - if(isset($course["objectives"])) - { - $tpl->setVariable("TOGGLE_CLASS", "ilPCMyCoursesToggle"); - } - else - { - $tpl->setVariable("NO_TOGGLE", ' style="visibility:hidden;"'); - } - - $tpl->setVariable("CRS_ICON_URL", $crs_icon); - $tpl->setVariable("CRS_ICON_ALT", $this->lng->txt("obj_crs")); - $tpl->parseCurrentBlock(); - } - - // #15508 - if(!self::$initialized) - { - $GLOBALS["tpl"]->addJavaScript("Modules/Portfolio/js/ilPortfolio.js"); - $GLOBALS["tpl"]->addOnLoadCode("ilPortfolio.init()"); - } - self::$initialized++; - - return $tpl->get(); - } - } - - /** - * Get course sort action - * - * @param ilCtrl $ctrl - * @return string - */ - protected function getCourseSortAction($ctrl) - { - return $ctrl->getFormActionByClass("ilobjportfoliogui", "preview"); - } - - - protected function getCoursesOfUser($a_user_id, $a_add_path = false) - { - $tree = $this->tree; - - // see ilPDSelectedItemsBlockGUI - - include_once 'Modules/Course/classes/class.ilObjCourseAccess.php'; - include_once 'Services/Membership/classes/class.ilParticipants.php'; - $items = ilParticipants::_getMembershipByType($a_user_id, 'crs'); - - $repo_title = $tree->getNodeData(ROOT_FOLDER_ID); - $repo_title = $repo_title["title"]; - if($repo_title == "ILIAS") - { - $repo_title = $this->lng->txt("repository"); - } - - $references = $lp_obj_refs = array(); - foreach($items as $obj_id) - { - $ref_id = ilObject::_getAllReferences($obj_id); - if(is_array($ref_id) && count($ref_id)) - { - $ref_id = array_pop($ref_id); - if(!$tree->isDeleted($ref_id)) - { - $visible = false; - $active = ilObjCourseAccess::_isActivated($obj_id, $visible, false); - if($active && $visible) - { - $references[$ref_id] = array( - 'ref_id' => $ref_id, - 'obj_id' => $obj_id, - 'title' => ilObject::_lookupTitle($obj_id) - ); - - if($a_add_path) - { - $path = array(); - foreach($tree->getPathFull($ref_id) as $item) - { - $path[] = $item["title"]; - } - // top level comes first - if(sizeof($path) == 2) - { - $path[0] = 0; - } - else - { - $path[0] = 1; - } - $references[$ref_id]["path_sort"] = implode("__", $path); - array_shift($path); - array_pop($path); - if(!sizeof($path)) - { - array_unshift($path, $repo_title); - } - $references[$ref_id]["path"] = implode(" › ", $path); - } - - $lp_obj_refs[$obj_id] = $ref_id; - } - } - } - } - - // get lp data for valid courses - - if(sizeof($lp_obj_refs)) - { - // listing the objectives should NOT depend on any LP status / setting - include_once 'Modules/Course/classes/class.ilObjCourse.php'; - foreach($lp_obj_refs as $obj_id => $ref_id) - { - // only if set in DB (default mode is not relevant - if(ilObjCourse::_lookupViewMode($obj_id) == IL_CRS_VIEW_OBJECTIVE) - { - $references[$ref_id]["objectives"] = $this->parseObjectives($obj_id, $a_user_id); - } - } - - // LP must be active, personal and not anonymized - include_once "Services/Tracking/classes/class.ilObjUserTracking.php"; - if (ilObjUserTracking::_enabledLearningProgress() && - ilObjUserTracking::_enabledUserRelatedData() && - ilObjUserTracking::_hasLearningProgressLearner()) - { - // see ilLPProgressTableGUI - include_once "Services/Tracking/classes/class.ilTrQuery.php"; - include_once "Services/Tracking/classes/class.ilLPStatusFactory.php"; - $lp_data = ilTrQuery::getObjectsStatusForUser($a_user_id, $lp_obj_refs); - foreach($lp_data as $item) - { - $ref_id = $item["ref_ids"]; - $references[$ref_id]["lp_status"] = $item["status"]; - } - } - } - - return $references; - } - - protected function parseObjectives($a_obj_id, $a_user_id) - { - $res = array(); - - // we need the collection for the correct order - include_once "Services/Tracking/classes/class.ilLPObjSettings.php"; - include_once "Services/Tracking/classes/collection/class.ilLPCollectionOfObjectives.php"; - $coll_objtv = new ilLPCollectionOfObjectives($a_obj_id, ilLPObjSettings::LP_MODE_OBJECTIVES); - $coll_objtv = $coll_objtv->getItems(); - if($coll_objtv) - { - // #13373 - $lo_results = $this->parseLOUserResults($a_obj_id, $a_user_id); - - include_once "Modules/Course/classes/Objectives/class.ilLOTestAssignments.php"; - $lo_ass = ilLOTestAssignments::getInstance($a_obj_id); - - $tmp = array(); - - include_once "Modules/Course/classes/class.ilCourseObjective.php"; - foreach($coll_objtv as $objective_id) - { - $title = ilCourseObjective::lookupObjectiveTitle($objective_id, true); - - $tmp[$objective_id] = array( - "id" => $objective_id, - "title" => $title["title"], - "desc" => $title["description"], - "itest" => $lo_ass->getTestByObjective($objective_id, ilLOSettings::TYPE_TEST_INITIAL), - "qtest" => $lo_ass->getTestByObjective($objective_id, ilLOSettings::TYPE_TEST_QUALIFIED) - ); - - if(array_key_exists($objective_id, $lo_results)) - { - $lo_result = $lo_results[$objective_id]; - $tmp[$objective_id]["user_id"] = $lo_result["user_id"]; - $tmp[$objective_id]["result_perc"] = $lo_result["result_perc"]; - $tmp[$objective_id]["limit_perc"] = $lo_result["limit_perc"]; - $tmp[$objective_id]["status"] = $lo_result["status"]; - $tmp[$objective_id]["type"] = $lo_result["type"]; - $tmp[$objective_id]["initial"] = $lo_result["initial"]; - } - } - - // order - foreach($coll_objtv as $objtv_id) - { - $res[] = $tmp[$objtv_id]; - } - } - - return $res; - } - - // see ilContainerObjectiveGUI::parseLOUserResults() - protected function parseLOUserResults($a_course_obj_id, $a_user_id) - { - $res = array(); - - include_once "Modules/Course/classes/Objectives/class.ilLOUserResults.php"; - $lur = new ilLOUserResults($a_course_obj_id, $a_user_id); - foreach($lur->getCourseResultsForUserPresentation() as $objective_id => $types) - { - // show either initial or qualified for objective - if(isset($types[ilLOUserResults::TYPE_INITIAL])) - { - $initial_status = $types[ilLOUserResults::TYPE_INITIAL]["status"]; - } - - // qualified test has priority - if(isset($types[ilLOUserResults::TYPE_QUALIFIED])) - { - $result = $types[ilLOUserResults::TYPE_QUALIFIED]; - $result["type"] = ilLOUserResults::TYPE_QUALIFIED; - $result["initial"] = $types[ilLOUserResults::TYPE_INITIAL]; - } - else - { - $result = $types[ilLOUserResults::TYPE_INITIAL]; - $result["type"] = ilLOUserResults::TYPE_INITIAL; - } - - $result["initial_status"] = $initial_status; - - $res[$objective_id] = $result; - } - - return $res; - } - - public function getExportMaterial() - { - return $this->export_material; - } - - /** - * Modify page content after xsl - * - * @param string $a_html - * @return string - */ - function makePlaceHoldersClickable($a_html) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilUser = $this->user; - - $c_pos = 0; - $start = strpos($a_html, "{{{{{PlaceHolder#"); - if (is_int($start)) - { - $end = strpos($a_html, "}}}}}", $start); - } - $i = 1; - while ($end > 0) - { - $param = substr($a_html, $start + 17, $end - $start - 17); - $param = explode("#", $param); - - $html = $param[2]; - switch ($param[2]) - { - case "Text": - $html = $lng->txt("cont_text_placeh"); - break; - - case "Media": - $html = $lng->txt("cont_media_placeh"); - break; - - case "Question": - $html = $lng->txt("cont_question_placeh"); - break; - - case "Verification": - $html = $lng->txt("cont_verification_placeh"); - break; - } - - // only if not owner - if ($ilUser->getId() == ilObjPortfolio::_lookupOwner($this->portfolio_id) - && $this->getOutputMode() == "presentation") - { - switch ($param[2]) - { - case "Text": - $ilCtrl->setParameterByClass("ilportfoliopagegui", "prt_id", $_GET["prt_id"]); - $ilCtrl->setParameterByClass("ilportfoliopagegui", "ppage", $this->getId()); - $ilCtrl->setParameterByClass("ilportfoliopagegui", "pl_pc_id", $param[0]); - $ilCtrl->setParameterByClass("ilportfoliopagegui", "pl_hier_id", $param[1]); - $href = $ilCtrl->getLinkTargetByClass("ilportfoliopagegui", "insertJSAtPlaceholder"); - $html = "" . $html . ""; - break; - - case "Media": - $ilCtrl->setParameterByClass("ilpcmediaobjectgui", "prt_id", $_GET["prt_id"]); - $ilCtrl->setParameterByClass("ilpcmediaobjectgui", "ppage", $this->getId()); - $ilCtrl->setParameterByClass("ilpcmediaobjectgui", "pl_pc_id", $param[0]); - $ilCtrl->setParameterByClass("ilpcmediaobjectgui", "pl_hier_id", $param[1]); - $ilCtrl->setParameterByClass("ilpcmediaobjectgui", "subCmd", "insertNew"); - $href = $ilCtrl->getLinkTargetByClass(array("ilPortfolioPageGUI", "ilPageEditorGUI", "ilPCPlaceHolderGUI", "ilpcmediaobjectgui"), "insert"); - $html = "" . $html . ""; - break; - } - } - - $h2 = substr($a_html, 0, $start). - $html. - substr($a_html, $end + 5); - $a_html = $h2; - $i++; - - $start = strpos($a_html, "{{{{{PlaceHolder#", $start + 5); - $end = 0; - if (is_int($start)) - { - $end = strpos($a_html, "}}}}}", $start); - } - } - return $a_html; - } - - /** - * Get view page link - * - * @param - * @return - */ - function getViewPageLink() - { - global $DIC; - - $ctrl = $DIC->ctrl(); - - $ctrl->setParameterByClass("ilobjportfoliogui", "user_page", $_GET["ppage"]); - return $ctrl->getLinkTargetByClass("ilobjportfoliogui", "preview"); - } - - /** - * Get view page link - * - * @param - * @return - */ - function getViewPageText() - { - return $this->lng->txt("preview"); - } - - /** - * Get page perma link - * - * @param - * @return - */ - function getPagePermaLink() - { - include_once("./Services/Link/classes/class.ilLink.php"); - $pid = ilPortfolioPage::findPortfolioForPage($this->getId()); - $href = ilLink::_getStaticLink($pid, "prtf", true, "_".$this->getId()); - return $href; - } - - /** - * @param $a_id - * @param $userCertificateRepository - * @param $url - * @return string - */ - private function createPersistentCertificateUrl($a_id, $userCertificateRepository, $url): string - { - $presentation = $userCertificateRepository->fetchActiveCertificateForPresentation($this->user->getId(), $a_id); - $caption = $this->lng->txt('certificate') . ': '; - $caption .= $this->lng->txt($presentation->getUserCertificate()->getObjType()) . ' '; - $caption .= '"' . $presentation->getObjectTitle() . '"'; - - return ''; - } - -} - -?> + + * @version $Id$ + * + * @ilCtrl_Calls ilPortfolioPageGUI: ilPageEditorGUI, ilEditClipboardGUI, ilMediaPoolTargetSelector + * @ilCtrl_Calls ilPortfolioPageGUI: ilPageObjectGUI, ilObjBlogGUI, ilBlogPostingGUI + * @ilCtrl_Calls ilPortfolioPageGUI: ilCalendarMonthGUI, ilConsultationHoursGUI, ilLearningHistoryGUI + * + * @ingroup ModulesPortfolio + */ +class ilPortfolioPageGUI extends ilPageObjectGUI +{ + /** + * @var ilObjectDefinition + */ + protected $obj_definition; + + /** + * @var ilTree + */ + protected $tree; + + const EMBEDDED_NO_OUTPUT = -99; + + protected $js_onload_code = array(); + protected $additional = array(); + protected $export_material = array("js"=>array(), "images"=>array(), "files"=>array()); + + protected static $initialized = 0; + + /** + * Constructor + */ + public function __construct($a_portfolio_id, $a_id = 0, $a_old_nr = 0, $a_enable_comments = true) + { + global $DIC; + + $this->tpl = $DIC["tpl"]; + $this->ctrl = $DIC->ctrl(); + $this->user = $DIC->user(); + $this->obj_definition = $DIC["objDefinition"]; + $this->access = $DIC->access(); + $this->tree = $DIC->repositoryTree(); + $this->lng = $DIC->language(); + $tpl = $DIC["tpl"]; + + $this->portfolio_id = (int) $a_portfolio_id; + $this->enable_comments = (bool) $a_enable_comments; + + parent::__construct($this->getParentType(), $a_id, $a_old_nr); + $this->getPageObject()->setPortfolioId($this->portfolio_id); + + // content style + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + + $tpl->setCurrentBlock("SyntaxStyle"); + $tpl->setVariable( + "LOCATION_SYNTAX_STYLESHEET", + ilObjStyleSheet::getSyntaxStylePath() + ); + $tpl->parseCurrentBlock(); + + $tpl->setCurrentBlock("ContentStyle"); + $tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath(0) + ); + $tpl->setVariable( + "LOCATION_ADDITIONAL_STYLESHEET", + ilObjStyleSheet::getPlaceHolderStylePath() + ); + $tpl->parseCurrentBlock(); + } + + public function getParentType() + { + return "prtf"; + } + + protected function getPageContentUserId($a_user_id) + { + // user id from content-xml + return $a_user_id; + } + + /** + * execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + switch ($next_class) { + case "ilobjbloggui": + // #12879 - we need the wsp-id for the keywords + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + $wsp_tree = new ilWorkspaceTree($ilUser->getId()); + $blog_obj_id = (int) $this->getPageObject()->getTitle(); + $blog_node_id = $wsp_tree->lookupNodeId($blog_obj_id); + + include_once "Modules/Blog/classes/class.ilObjBlogGUI.php"; + $blog_gui = new ilObjBlogGUI($blog_node_id, ilObjBlogGUI::WORKSPACE_NODE_ID); + $blog_gui->disableNotes(!$this->enable_comments); + $blog_gui->prtf_embed = true; // disables prepareOutput()/getStandardTemplate() in blog + return $ilCtrl->forwardCommand($blog_gui); + + case "ilcalendarmonthgui": + + + // booking action + if ($cmd && $cmd != "preview") { + $categories = ilCalendarCategories::_getInstance(); + if ($categories->getMode() == 0) { + if ($_GET['chuid']) { + $categories->setCHUserId((int) $_GET['chuid']); + } + $categories->initialize(ilCalendarCategories::MODE_PORTFOLIO_CONSULTATION, null, true); + } + + if ($_GET['seed']) { + $seed = new ilDate((string) $_GET['seed'], IL_CAL_DATE); + } else { + $seed = new ilDate(time(), IL_CAL_UNIX); + } + + include_once('./Services/Calendar/classes/class.ilCalendarMonthGUI.php'); + $month_gui = new ilCalendarMonthGUI($seed); + return $ilCtrl->forwardCommand($month_gui); + } + // calendar month navigation + else { + $ilCtrl->setParameter($this, "cmd", "preview"); + return self::EMBEDDED_NO_OUTPUT; + } + + // no break + case "ilpageobjectgui": + die("Deprecated. ilPortfolioPage gui forwarding to ilpageobject"); + return; + + default: + $this->setPresentationTitle($this->getPageObject()->getTitle()); + return parent::executeCommand(); + } + } + + /** + * Show page + * + * @return string page output + */ + public function showPage() + { + $ilUser = $this->user; + + if (!$this->getPageObject()) { + return; + } + + switch ($this->getPageObject()->getType()) { + case ilPortfolioPage::TYPE_BLOG: + return $this->renderBlog($ilUser->getId(), (int) $this->getPageObject()->getTitle()); + + default: + $this->setTemplateOutput(false); + // $this->setPresentationTitle($this->getPageObject()->getTitle()); + $output = parent::showPage(); + + return $output; + } + } + + /** + * Set all tabs + * + * @param + * @return + */ + public function getTabs($a_activate = "") + { + if (!$this->embedded) { + parent::getTabs($a_activate); + } + } + + /** + * Set embedded mode: will suppress tabs + * + * @param bool $a_value + */ + public function setEmbedded($a_value) + { + $this->embedded = (bool) $a_value; + } + + /** + * Set Additonal Information. + * + * @param array $a_additional Additonal Information + */ + public function setAdditional($a_additional) + { + $this->additional = $a_additional; + } + + /** + * Get Additonal Information. + * + * @return array Additonal Information + */ + public function getAdditional() + { + return $this->additional; + } + + public function getJsOnloadCode() + { + return $this->js_onload_code; + } + + public function postOutputProcessing($a_output) + { + $parts = array( + "Profile" => array("0-9", "a-z", "0-9a-z_;\W"), // user, mode, fields + "Verification" => array("0-9", "a-z", "0-9"), // user, type, id + "Blog" => array("0-9", "0-9", "0-9;\W"), // user, blog id, posting ids + "BlogTeaser" => array("0-9", "0-9", "0-9;\W"), // user, blog id, posting ids + "Skills" => array("0-9", "0-9"), // user, skill id + "SkillsTeaser" => array("0-9", "0-9"), // user, skill id + "ConsultationHours" => array("0-9", "a-z", "0-9;\W"), // user, mode, group ids + "ConsultationHoursTeaser" => array("0-9", "a-z", "0-9;\W"), // user, mode, group ids + "MyCourses" => array("0-9", "a-z*"), // user, sort + "MyCoursesTeaser" => array("0-9", "a-z*") // user, sort + ); + + foreach ($parts as $type => $def) { + // #15732 - allow optional parts + $def_parts = array(); + foreach ($def as $part) { + $is_opt = (substr($part, -1) == "*"); + if (!$is_opt) { + $def_parts[] = "#"; + $end_marker = "+"; + } else { + $def_parts[] = "#*"; + $end_marker = "*"; + $part = substr($part, 0, -1); + } + $def_parts[] = "([" . $part . "]" . $end_marker . ")"; + } + $def = implode("", $def_parts); + + if (preg_match_all( + "/" . $this->pl_start . $type . $def . $this->pl_end . "/", + $a_output, + $blocks + )) { + foreach ($blocks[0] as $idx => $block) { + switch ($type) { + case "Profile": + case "Blog": + case "BlogTeaser": + case "Skills": + case "SkillsTeaser": + case "ConsultationHours": + case "ConsultationHoursTeaser": + case "MyCourses": + case "MyCoursesTeaser": + $subs = null; + if (trim($blocks[3][$idx])) { + foreach (explode(";", $blocks[3][$idx]) as $sub) { + if (trim($sub)) { + $subs[] = trim($sub); + } + } + } + $snippet = $this->{"render" . $type}( + $blocks[1][$idx], + $blocks[2][$idx], + $subs + ); + break; + + default: + $snippet = $this->{"render" . $type}( + $blocks[1][$idx], + $blocks[2][$idx], + $blocks[3][$idx] + ); + break; + } + + $snippet = $this->renderPageElement($type, $snippet); + $a_output = str_replace($block, $snippet, $a_output); + } + } + } + + $a_output = $this->makePlaceHoldersClickable($a_output); + + return $a_output; + } + + protected function renderPageElement($a_type, $a_html) + { + return trim($a_html); + } + + protected function renderTeaser($a_type, $a_title, $a_options = null) + { + $options = ""; + if ($a_options) { + $options = ''; + } + + return '

' . $a_title . '

' . + '
' . $this->lng->txt("prtf_page_element_teaser_" . $a_type) . '
' . + $options . '
'; + } + + protected function renderProfile($a_user_id, $a_type, array $a_fields = null) + { + $ilCtrl = $this->ctrl; + + $user_id = $this->getPageContentUserId($a_user_id); + + if ($this->getOutputMode() == "offline") { + // profile picture is done in ilPortfolioHTMLExport + + $this->export_material["js"][] = "http://maps.google.com/maps/api/js?sensor=false"; + $this->export_material["js"][] = "./Services/Maps/js/ServiceGoogleMaps.js"; + $this->export_material["js"][] = "./Services/Maps/js/OpenLayers.js"; + $this->export_material["js"][] = "./Services/Maps/js/ServiceOpenLayers.js"; + } + + include_once("./Services/User/classes/class.ilPublicUserProfileGUI.php"); + $pub_profile = new ilPublicUserProfileGUI($user_id); + $pub_profile->setEmbedded(true, ($this->getOutputMode() == "offline")); + + // full circle: additional was set in the original public user profile call + $pub_profile->setAdditional($this->getAdditional()); + + if ($a_type == "manual" && sizeof($a_fields)) { + $prefs = array(); + foreach ($a_fields as $field) { + $field = trim($field); + if ($field) { + $prefs["public_" . $field] = "y"; + } + } + + $pub_profile->setCustomPrefs($prefs); + } + + if ($this->getOutputMode() != "offline") { + return $ilCtrl->getHTML($pub_profile); + } else { + return $pub_profile->getEmbeddable(); + } + } + + /** + * @param $a_user_id + * @param $a_type + * @param $a_id + * @return string + * @throws ilException + */ + protected function renderVerification($a_user_id, $a_type, $a_id) + { + $objDefinition = $this->obj_definition; + + $outputMode = $this->getOutputMode(); + + // not used + // $user_id = $this->getPageContentUserId($a_user_id); + if ($a_type === 'crta' && $outputMode === 'offline') { + $fileService = new ilPortfolioCertificateFileService(); + + $certificatePdfFile = $fileService->createCertificateFilePath($a_user_id, $a_id); + $this->export_material["files"][] = $certificatePdfFile; + + $url = 'files/' . basename($certificatePdfFile); + + $userCertificateRepository = new ilUserCertificateRepository(); + + return $this->createPersistentCertificateUrl($a_id, $userCertificateRepository, $url); + } elseif ($a_type === 'crta' && $outputMode === 'print') { + $userCertificateRepository = new ilUserCertificateRepository(); + $url = $this->getPagePermaLink(); + + return $this->createPersistentCertificateUrl($a_id, $userCertificateRepository, $url); + } elseif ($a_type === 'crta') { + $this->ctrl->setParameter($this, "dlid", $a_id); + $url = $this->ctrl->getLinkTarget($this, "dl" . $a_type); + $this->ctrl->setParameter($this, "dlid", ""); + + $userCertificateRepository = new ilUserCertificateRepository(); + + return $this->createPersistentCertificateUrl($a_id, $userCertificateRepository, $url); + } + + $class = "ilObj" . $objDefinition->getClassName($a_type) . "GUI"; + include_once $objDefinition->getLocation($a_type) . "/class." . $class . ".php"; + $verification = new $class($a_id, ilObject2GUI::WORKSPACE_OBJECT_ID); + + if ($outputMode == "print") { + $url = $this->getPagePermaLink(); + } elseif ($outputMode != "offline") { + // direct download link + $this->ctrl->setParameter($this, "dlid", $a_id); + $url = $this->ctrl->getLinkTarget($this, "dl" . $a_type); + $this->ctrl->setParameter($this, "dlid", ""); + } else { + $file = $verification->object->getFilePath(); + $url = "files/" . basename($file); + + $this->export_material["files"][] = $file; + } + + return $verification->render(true, $url); + } + + protected function dltstv() + { + $id = $_GET["dlid"]; + if ($id) { + include_once "Modules/Test/classes/class.ilObjTestVerificationGUI.php"; + $verification = new ilObjTestVerificationGUI($id, ilObject2GUI::WORKSPACE_OBJECT_ID); + $verification->downloadFromPortfolioPage($this->getPageObject()); + } + } + + protected function dlexcv() + { + $id = $_GET["dlid"]; + if ($id) { + include_once "Modules/Exercise/classes/class.ilObjExerciseVerificationGUI.php"; + $verification = new ilObjExerciseVerificationGUI($id, ilObject2GUI::WORKSPACE_OBJECT_ID); + $verification->downloadFromPortfolioPage($this->getPageObject()); + } + } + + protected function dlcrsv() + { + $id = $_GET["dlid"]; + if ($id) { + include_once "Modules/Course/classes/Verification/class.ilObjCourseVerificationGUI.php"; + $verification = new ilObjCourseVerificationGUI($id, ilObject2GUI::WORKSPACE_OBJECT_ID); + $verification->downloadFromPortfolioPage($this->getPageObject()); + } + } + + protected function dlscov() + { + $id = $_GET["dlid"]; + if ($id) { + include_once "Modules/ScormAicc/classes/Verification/class.ilObjSCORMVerificationGUI.php"; + $verification = new ilObjSCORMVerificationGUI($id, ilObject2GUI::WORKSPACE_OBJECT_ID); + $verification->downloadFromPortfolioPage($this->getPageObject()); + } + } + + protected function dlcrta() + { + $objectId = $_GET["dlid"]; + if ($objectId) { + $object = new ilObjPersistentCertificateVerificationGUI(); + $object->downloadFromPortfolioPage($this->getPageObject(), $objectId, $this->user->getId()); + } + } + + protected function renderBlog($a_user_id, $a_blog_id, array $a_posting_ids = null) + { + $ilCtrl = $this->ctrl; + + // not used + // $user_id = $this->getPageContentUserId($a_user_id); + + // full blog (separate tab/page) + if (!$a_posting_ids) { + include_once "Modules/Blog/classes/class.ilObjBlogGUI.php"; + if (ilObject::_lookupType($a_blog_id) != "blog") { + return; + } + $blog = new ilObjBlogGUI($a_blog_id, ilObject2GUI::WORKSPACE_OBJECT_ID); + $blog->disableNotes(!$this->enable_comments); + $blog->setContentStyleSheet(); + + if ($this->getOutputMode() != "offline") { + return $ilCtrl->getHTML($blog); + } else { + } + } + // embedded postings + else { + $html = array(); + + include_once "Modules/Blog/classes/class.ilObjBlog.php"; + $html[] = ilObjBlog::_lookupTitle($a_blog_id); + + include_once "Modules/Blog/classes/class.ilBlogPostingGUI.php"; + foreach ($a_posting_ids as $post) { + $page = new ilBlogPostingGUI(0, null, $post); + if ($this->getOutputMode() != "offline") { + $page->setOutputMode(IL_PAGE_PREVIEW); + } else { + $page->setOutputMode("offline"); + } + $html[] = $page->showPage(); + } + + return implode("\n", $html); + } + } + + protected function renderBlogTeaser($a_user_id, $a_blog_id, array $a_posting_ids = null) + { + // not used + // $user_id = $this->getPageContentUserId($a_user_id); + + $postings = ""; + if ($a_posting_ids) { + $postings = array("
    "); + include_once "Modules/Blog/classes/class.ilBlogPosting.php"; + foreach ($a_posting_ids as $post) { + $post = new ilBlogPosting($post); + $postings[] = "
  • " . $post->getTitle() . " - " . + ilDatePresentation::formatDate($post->getCreated()) . "
  • "; + } + $postings[] = "
"; + $postings = implode("\n", $postings); + } + + return $this->renderTeaser("blog", $this->lng->txt("obj_blog") . ' "' . + ilObject::_lookupTitle($a_blog_id) . '"', $postings); + } + + protected function renderSkills($a_user_id, $a_skills_id) + { + if ($this->getOutputMode() == "preview") { + return $this->renderSkillsTeaser($a_user_id, $a_skills_id); + } + + $user_id = $this->getPageContentUserId($a_user_id); + + include_once "Services/Skill/classes/class.ilPersonalSkillsGUI.php"; + $gui = new ilPersonalSkillsGUI(); + if ($this->getOutputMode() == "offline") { + $gui->setOfflineMode("./files/"); + } + $html = $gui->getSkillHTML($a_skills_id, $user_id); + + return $html; + } + + protected function renderSkillsTeaser($a_user_id, $a_skills_id) + { + // not used + // $user_id = $this->getPageContentUserId($a_user_id); + + include_once "Services/Skill/classes/class.ilSkillTreeNode.php"; + + return $this->renderTeaser("skills", $this->lng->txt("skills") . ' "' . + ilSkillTreeNode::_lookupTitle($a_skills_id) . '"'); + } + + protected function renderConsultationHoursTeaser($a_user_id, $a_mode, $a_group_ids) + { + // not used + // $user_id = $this->getPageContentUserId($a_user_id); + + if ($a_mode == "auto") { + $mode = $this->lng->txt("cont_cach_mode_automatic"); + $groups = null; + } else { + $mode = $this->lng->txt("cont_cach_mode_manual"); + + include_once "Services/Calendar/classes/ConsultationHours/class.ilConsultationHourGroups.php"; + $groups = array(); + foreach ($a_group_ids as $grp_id) { + $groups[] = ilConsultationHourGroups::lookupTitle($grp_id); + } + $groups = " (" . implode(", ", $groups) . ")"; + } + + $this->lng->loadLanguageModule("dateplaner"); + return $this->renderTeaser( + "consultation_hours", + $this->lng->txt("app_consultation_hours"), + $mode . $groups + ); + } + + protected function renderConsultationHours($a_user_id, $a_mode, $a_group_ids) + { + $ilUser = $this->user; + + if ($this->getOutputMode() == "preview") { + return $this->renderConsultationHoursTeaser($a_user_id, $a_mode, $a_group_ids); + } + + if ($this->getOutputMode() == "offline") { + return; + } + + if ($this->getOutputMode() == "print") { + return; + } + + $user_id = $this->getPageContentUserId($a_user_id); + + // only if not owner + if ($ilUser->getId() != $user_id) { + $_GET["bkid"] = $user_id; + } + + if ($a_mode != "manual") { + $a_group_ids = null; + } + + include_once('./Services/Calendar/classes/class.ilCalendarCategories.php'); + ilCalendarCategories::_getInstance()->setCHUserId($user_id); + ilCalendarCategories::_getInstance()->initialize(ilCalendarCategories::MODE_PORTFOLIO_CONSULTATION, null, true); + + if (!$_REQUEST["seed"]) { + $seed = new ilDate(time(), IL_CAL_UNIX); + } else { + $seed = new ilDate($_REQUEST["seed"], IL_CAL_DATE); + } + + include_once('./Services/Calendar/classes/class.ilCalendarMonthGUI.php'); + $month_gui = new ilCalendarMonthGUI($seed); + $month_gui->setConsulationHoursUserId($user_id); + + // custom schedule filter: handle booking group ids + include_once('./Services/Calendar/classes/class.ilCalendarScheduleFilterBookings.php'); + $filter = new ilCalendarScheduleFilterBookings($user_id, $a_group_ids); + $month_gui->addScheduleFilter($filter); + + $this->tpl->addCss(ilUtil::getStyleSheetLocation('filesystem', 'delos.css', 'Services/Calendar')); + + $this->lng->loadLanguageModule("dateplaner"); + return '

' . $this->lng->txt("app_consultation_hours") . '

' . + $this->ctrl->getHTML($month_gui); + } + + protected function isMyCoursesActive() + { + $prfa_set = new ilSetting("prfa"); + return (bool) $prfa_set->get("mycrs", true); + } + + protected function renderMyCoursesTeaser($a_user_id, $a_default_sorting) + { + // not used + // $user_id = $this->getPageContentUserId($a_user_id); + + $title = $this->isMyCoursesActive() + ? "my_courses" + : "my_courses_inactive"; + + return $this->renderTeaser( + $title, + $this->lng->txt("prtf_page_element_my_courses_title") + ); + } + + protected function renderMyCourses($a_user_id, $a_default_sorting) + { + $ilAccess = $this->access; + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + + if ($this->getOutputMode() == "preview") { + return $this->renderMyCoursesTeaser($a_user_id, $a_default_sorting); + } + + if (!$this->isMyCoursesActive()) { + return; + } + + $img_path = null; + if ($this->getOutputMode() == "offline") { + $this->export_material["images"][] = "./templates/default/images/icon_crs.svg"; + $this->export_material["images"][] = "./templates/default/images/icon_lobj.svg"; + $this->export_material["images"][] = "./templates/default/images/scorm/complete.svg"; + $this->export_material["images"][] = "./templates/default/images/scorm/not_attempted.svg"; + $this->export_material["images"][] = "./templates/default/images/scorm/failed.svg"; + $this->export_material["images"][] = "./templates/default/images/scorm/incomplete.svg"; + + $img_path = "images/"; + } + + $user_id = $this->getPageContentUserId($a_user_id); + + // sorting pref + if ($_POST["srt"] && + in_array($_POST["srt"], array("alpha", "loc"))) { + $ilUser->writePref("prtf_mcrs_sort", $_POST["srt"]); + } + $sorting = $ilUser->getPref("prtf_mcrs_sort"); + if (!$sorting) { + $sorting = $a_default_sorting; + } + + $data = $this->getCoursesOfUser($user_id, ($sorting == "loc")); + if (sizeof($data)) { + if ($sorting != "loc") { + $data = ilUtil::sortArray($data, "title", "ASC"); + } else { + $data = ilUtil::sortArray($data, "path_sort", "ASC"); + } + + $tpl = new ilTemplate("tpl.pc_my_courses.html", true, true, "Modules/Portfolio"); + $tpl->setVariable("TITLE", $this->lng->txt("prtf_page_element_my_courses_title")); + $tpl->setVariable("INFO", $this->lng->txt("prtf_page_element_my_courses_info")); // #14464 + + include_once("./Services/Tracking/classes/class.ilLearningProgressBaseGUI.php"); + $this->lng->loadLanguageModule("trac"); + $this->lng->loadLanguageModule("crs"); + + include_once("./Services/Container/classes/class.ilContainerObjectiveGUI.php"); + include_once("./Services/Link/classes/class.ilLink.php"); + + // sorting + if ($this->getOutputMode() != "print") { + $options = array( + "alpha" => $this->lng->txt("cont_mycourses_sortorder_alphabetical"), + "loc" => $this->lng->txt("cont_mycourses_sortorder_location") + ); + $tpl->setVariable("SORT_SELECT", ilUtil::formSelect( + $sorting, + "srt", + $options, + false, + true, + 0, + "", + array("onchange" => "form.submit()") + )); + $tpl->setVariable("SORT_FORM", $this->getCourseSortAction($ilCtrl)); + } + + $old_path = null; + + foreach ($data as $course) { + if ($sorting == "loc") { + if ($course["path"] != $old_path) { + $tpl->setCurrentBlock("path_bl"); + $tpl->setVariable("PATH", $course["path"]); + $tpl->parseCurrentBlock(); + + $old_path = $course["path"]; + } + } + + if (isset($course["lp_status"])) { + $lp_icon = ilLearningProgressBaseGUI::_getImagePathForStatus($course["lp_status"]); + $lp_alt = ilLearningProgressBaseGUI::_getStatusText($course["lp_status"]); + + if ($img_path) { + $lp_icon = $img_path . basename($lp_icon); + } + + $tpl->setCurrentBlock("lp_bl"); + $tpl->setVariable("LP_ICON_URL", $lp_icon); + $tpl->setVariable("LP_ICON_ALT", $lp_alt); + $tpl->parseCurrentBlock(); + } + + $do_links = false; + if ($ilUser->getId() != ANONYMOUS_USER_ID) { + $do_links = $ilAccess->checkAccessOfUser($ilUser->getId(), "read", "", $course["ref_id"], "crs") || + ($ilAccess->checkAccessOfUser($ilUser->getId(), "visible", "", $course["ref_id"], "crs") && + $ilAccess->checkAccessOfUser($ilUser->getId(), "join", "", $course["ref_id"], "crs")); + } + + if (isset($course["objectives"])) { + include_once './Modules/Course/classes/Objectives/class.ilLOSettings.php'; + $loc_settings = ilLOSettings::getInstanceByObjId($course["obj_id"]); + $has_initial_test = (bool) $loc_settings->getInitialTest(); + + foreach ($course["objectives"] as $objtv) { + if ($do_links) { + $params = array("oobj"=>$objtv["id"]); + $url = ilLink::_getLink($course["ref_id"], "crs", $params); + + // #15510 + $url .= "#objtv_acc_" . $objtv["id"]; + + if ($this->getOutputMode() != "print") { + $tpl->touchBlock("objective_dnone"); + } + + $tpl->setCurrentBlock("objective_link_bl"); + + if (trim($objtv["desc"])) { + $desc = nl2br($objtv["desc"]); + $tt_id = "objtvtt_" . $objtv["id"] . "_" . ((int) self::$initialized); + + include_once "Services/UIComponent/Tooltip/classes/class.ilTooltipGUI.php"; + ilToolTipGUI::addTooltip($tt_id, $desc, "", "bottom center", "top center", false); + + $tpl->setVariable("OBJECTIVE_LINK_ID", $tt_id); + } + + $tpl->setVariable("OBJECTIVE_LINK_URL", $url); + $tpl->setVariable("OBJECTIVE_LINK_TITLE", $objtv["title"]); + $tpl->parseCurrentBlock(); + } else { + $tpl->setCurrentBlock("objective_nolink_bl"); + $tpl->setVariable("OBJECTIVE_NOLINK_TITLE", $objtv["title"]); + $tpl->parseCurrentBlock(); + } + + $objtv_icon = ilUtil::getTypeIconPath("lobj", $objtv["id"]); + if ($img_path) { + $objtv_icon = $img_path . basename($objtv_icon); + } + + $tpl->setCurrentBlock("objective_bl"); + $tpl->setVariable("OBJTV_ICON_URL", $objtv_icon); + $tpl->setVariable("OBJTV_ICON_ALT", $this->lng->txt("crs_objectives")); + + if ($objtv["type"]) { + $tpl->setVariable( + "LP_OBJTV_PROGRESS", + ilContainerObjectiveGUI::buildObjectiveProgressBar($has_initial_test, $objtv["id"], $objtv, true, false, (int) self::$initialized) + ); + } + + $tpl->parseCurrentBlock(); + } + + $tpl->setCurrentBlock("objectives_bl"); + $tpl->setVariable("OBJTV_LIST_CRS_ID", $course["obj_id"]); + $tpl->parseCurrentBlock(); + } + + // always check against current user + if ($do_links) { + $tpl->setCurrentBlock("course_link_bl"); + $tpl->setVariable("COURSE_LINK_TITLE", $course["title"]); + $tpl->setVariable("COURSE_LINK_URL", ilLink::_getLink($course["ref_id"])); + $tpl->parseCurrentBlock(); + } else { + $tpl->setCurrentBlock("course_nolink_bl"); + $tpl->setVariable("COURSE_NOLINK_TITLE", $course["title"]); + $tpl->parseCurrentBlock(); + } + + $crs_icon = ilUtil::getTypeIconPath("crs", $course["obj_id"]); + if ($img_path) { + $crs_icon = $img_path . basename($crs_icon); + } + + $tpl->setCurrentBlock("course_bl"); + + if (isset($course["objectives"])) { + $tpl->setVariable("TOGGLE_CLASS", "ilPCMyCoursesToggle"); + } else { + $tpl->setVariable("NO_TOGGLE", ' style="visibility:hidden;"'); + } + + $tpl->setVariable("CRS_ICON_URL", $crs_icon); + $tpl->setVariable("CRS_ICON_ALT", $this->lng->txt("obj_crs")); + $tpl->parseCurrentBlock(); + } + + // #15508 + if (!self::$initialized) { + $GLOBALS["tpl"]->addJavaScript("Modules/Portfolio/js/ilPortfolio.js"); + $GLOBALS["tpl"]->addOnLoadCode("ilPortfolio.init()"); + } + self::$initialized++; + + return $tpl->get(); + } + } + + /** + * Get course sort action + * + * @param ilCtrl $ctrl + * @return string + */ + protected function getCourseSortAction($ctrl) + { + return $ctrl->getFormActionByClass("ilobjportfoliogui", "preview"); + } + + + protected function getCoursesOfUser($a_user_id, $a_add_path = false) + { + $tree = $this->tree; + + // see ilPDSelectedItemsBlockGUI + + include_once 'Modules/Course/classes/class.ilObjCourseAccess.php'; + include_once 'Services/Membership/classes/class.ilParticipants.php'; + $items = ilParticipants::_getMembershipByType($a_user_id, 'crs'); + + $repo_title = $tree->getNodeData(ROOT_FOLDER_ID); + $repo_title = $repo_title["title"]; + if ($repo_title == "ILIAS") { + $repo_title = $this->lng->txt("repository"); + } + + $references = $lp_obj_refs = array(); + foreach ($items as $obj_id) { + $ref_id = ilObject::_getAllReferences($obj_id); + if (is_array($ref_id) && count($ref_id)) { + $ref_id = array_pop($ref_id); + if (!$tree->isDeleted($ref_id)) { + $visible = false; + $active = ilObjCourseAccess::_isActivated($obj_id, $visible, false); + if ($active && $visible) { + $references[$ref_id] = array( + 'ref_id' => $ref_id, + 'obj_id' => $obj_id, + 'title' => ilObject::_lookupTitle($obj_id) + ); + + if ($a_add_path) { + $path = array(); + foreach ($tree->getPathFull($ref_id) as $item) { + $path[] = $item["title"]; + } + // top level comes first + if (sizeof($path) == 2) { + $path[0] = 0; + } else { + $path[0] = 1; + } + $references[$ref_id]["path_sort"] = implode("__", $path); + array_shift($path); + array_pop($path); + if (!sizeof($path)) { + array_unshift($path, $repo_title); + } + $references[$ref_id]["path"] = implode(" › ", $path); + } + + $lp_obj_refs[$obj_id] = $ref_id; + } + } + } + } + + // get lp data for valid courses + + if (sizeof($lp_obj_refs)) { + // listing the objectives should NOT depend on any LP status / setting + include_once 'Modules/Course/classes/class.ilObjCourse.php'; + foreach ($lp_obj_refs as $obj_id => $ref_id) { + // only if set in DB (default mode is not relevant + if (ilObjCourse::_lookupViewMode($obj_id) == IL_CRS_VIEW_OBJECTIVE) { + $references[$ref_id]["objectives"] = $this->parseObjectives($obj_id, $a_user_id); + } + } + + // LP must be active, personal and not anonymized + include_once "Services/Tracking/classes/class.ilObjUserTracking.php"; + if (ilObjUserTracking::_enabledLearningProgress() && + ilObjUserTracking::_enabledUserRelatedData() && + ilObjUserTracking::_hasLearningProgressLearner()) { + // see ilLPProgressTableGUI + include_once "Services/Tracking/classes/class.ilTrQuery.php"; + include_once "Services/Tracking/classes/class.ilLPStatusFactory.php"; + $lp_data = ilTrQuery::getObjectsStatusForUser($a_user_id, $lp_obj_refs); + foreach ($lp_data as $item) { + $ref_id = $item["ref_ids"]; + $references[$ref_id]["lp_status"] = $item["status"]; + } + } + } + + return $references; + } + + protected function parseObjectives($a_obj_id, $a_user_id) + { + $res = array(); + + // we need the collection for the correct order + include_once "Services/Tracking/classes/class.ilLPObjSettings.php"; + include_once "Services/Tracking/classes/collection/class.ilLPCollectionOfObjectives.php"; + $coll_objtv = new ilLPCollectionOfObjectives($a_obj_id, ilLPObjSettings::LP_MODE_OBJECTIVES); + $coll_objtv = $coll_objtv->getItems(); + if ($coll_objtv) { + // #13373 + $lo_results = $this->parseLOUserResults($a_obj_id, $a_user_id); + + include_once "Modules/Course/classes/Objectives/class.ilLOTestAssignments.php"; + $lo_ass = ilLOTestAssignments::getInstance($a_obj_id); + + $tmp = array(); + + include_once "Modules/Course/classes/class.ilCourseObjective.php"; + foreach ($coll_objtv as $objective_id) { + $title = ilCourseObjective::lookupObjectiveTitle($objective_id, true); + + $tmp[$objective_id] = array( + "id" => $objective_id, + "title" => $title["title"], + "desc" => $title["description"], + "itest" => $lo_ass->getTestByObjective($objective_id, ilLOSettings::TYPE_TEST_INITIAL), + "qtest" => $lo_ass->getTestByObjective($objective_id, ilLOSettings::TYPE_TEST_QUALIFIED) + ); + + if (array_key_exists($objective_id, $lo_results)) { + $lo_result = $lo_results[$objective_id]; + $tmp[$objective_id]["user_id"] = $lo_result["user_id"]; + $tmp[$objective_id]["result_perc"] = $lo_result["result_perc"]; + $tmp[$objective_id]["limit_perc"] = $lo_result["limit_perc"]; + $tmp[$objective_id]["status"] = $lo_result["status"]; + $tmp[$objective_id]["type"] = $lo_result["type"]; + $tmp[$objective_id]["initial"] = $lo_result["initial"]; + } + } + + // order + foreach ($coll_objtv as $objtv_id) { + $res[] = $tmp[$objtv_id]; + } + } + + return $res; + } + + // see ilContainerObjectiveGUI::parseLOUserResults() + protected function parseLOUserResults($a_course_obj_id, $a_user_id) + { + $res = array(); + + include_once "Modules/Course/classes/Objectives/class.ilLOUserResults.php"; + $lur = new ilLOUserResults($a_course_obj_id, $a_user_id); + foreach ($lur->getCourseResultsForUserPresentation() as $objective_id => $types) { + // show either initial or qualified for objective + if (isset($types[ilLOUserResults::TYPE_INITIAL])) { + $initial_status = $types[ilLOUserResults::TYPE_INITIAL]["status"]; + } + + // qualified test has priority + if (isset($types[ilLOUserResults::TYPE_QUALIFIED])) { + $result = $types[ilLOUserResults::TYPE_QUALIFIED]; + $result["type"] = ilLOUserResults::TYPE_QUALIFIED; + $result["initial"] = $types[ilLOUserResults::TYPE_INITIAL]; + } else { + $result = $types[ilLOUserResults::TYPE_INITIAL]; + $result["type"] = ilLOUserResults::TYPE_INITIAL; + } + + $result["initial_status"] = $initial_status; + + $res[$objective_id] = $result; + } + + return $res; + } + + public function getExportMaterial() + { + return $this->export_material; + } + + /** + * Modify page content after xsl + * + * @param string $a_html + * @return string + */ + public function makePlaceHoldersClickable($a_html) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilUser = $this->user; + + $c_pos = 0; + $start = strpos($a_html, "{{{{{PlaceHolder#"); + if (is_int($start)) { + $end = strpos($a_html, "}}}}}", $start); + } + $i = 1; + while ($end > 0) { + $param = substr($a_html, $start + 17, $end - $start - 17); + $param = explode("#", $param); + + $html = $param[2]; + switch ($param[2]) { + case "Text": + $html = $lng->txt("cont_text_placeh"); + break; + + case "Media": + $html = $lng->txt("cont_media_placeh"); + break; + + case "Question": + $html = $lng->txt("cont_question_placeh"); + break; + + case "Verification": + $html = $lng->txt("cont_verification_placeh"); + break; + } + + // only if not owner + if ($ilUser->getId() == ilObjPortfolio::_lookupOwner($this->portfolio_id) + && $this->getOutputMode() == "presentation") { + switch ($param[2]) { + case "Text": + $ilCtrl->setParameterByClass("ilportfoliopagegui", "prt_id", $_GET["prt_id"]); + $ilCtrl->setParameterByClass("ilportfoliopagegui", "ppage", $this->getId()); + $ilCtrl->setParameterByClass("ilportfoliopagegui", "pl_pc_id", $param[0]); + $ilCtrl->setParameterByClass("ilportfoliopagegui", "pl_hier_id", $param[1]); + $href = $ilCtrl->getLinkTargetByClass("ilportfoliopagegui", "insertJSAtPlaceholder"); + $html = "" . $html . ""; + break; + + case "Media": + $ilCtrl->setParameterByClass("ilpcmediaobjectgui", "prt_id", $_GET["prt_id"]); + $ilCtrl->setParameterByClass("ilpcmediaobjectgui", "ppage", $this->getId()); + $ilCtrl->setParameterByClass("ilpcmediaobjectgui", "pl_pc_id", $param[0]); + $ilCtrl->setParameterByClass("ilpcmediaobjectgui", "pl_hier_id", $param[1]); + $ilCtrl->setParameterByClass("ilpcmediaobjectgui", "subCmd", "insertNew"); + $href = $ilCtrl->getLinkTargetByClass(array("ilPortfolioPageGUI", "ilPageEditorGUI", "ilPCPlaceHolderGUI", "ilpcmediaobjectgui"), "insert"); + $html = "" . $html . ""; + break; + } + } + + $h2 = substr($a_html, 0, $start) . + $html . + substr($a_html, $end + 5); + $a_html = $h2; + $i++; + + $start = strpos($a_html, "{{{{{PlaceHolder#", $start + 5); + $end = 0; + if (is_int($start)) { + $end = strpos($a_html, "}}}}}", $start); + } + } + return $a_html; + } + + /** + * Get view page link + * + * @param + * @return + */ + public function getViewPageLink() + { + global $DIC; + + $ctrl = $DIC->ctrl(); + + $ctrl->setParameterByClass("ilobjportfoliogui", "user_page", $_GET["ppage"]); + return $ctrl->getLinkTargetByClass("ilobjportfoliogui", "preview"); + } + + /** + * Get view page link + * + * @param + * @return + */ + public function getViewPageText() + { + return $this->lng->txt("preview"); + } + + /** + * Get page perma link + * + * @param + * @return + */ + public function getPagePermaLink() + { + include_once("./Services/Link/classes/class.ilLink.php"); + $pid = ilPortfolioPage::findPortfolioForPage($this->getId()); + $href = ilLink::_getStaticLink($pid, "prtf", true, "_" . $this->getId()); + return $href; + } + + /** + * @param $a_id + * @param $userCertificateRepository + * @param $url + * @return string + */ + private function createPersistentCertificateUrl($a_id, $userCertificateRepository, $url) : string + { + $presentation = $userCertificateRepository->fetchActiveCertificateForPresentation($this->user->getId(), $a_id); + $caption = $this->lng->txt('certificate') . ': '; + $caption .= $this->lng->txt($presentation->getUserCertificate()->getObjType()) . ' '; + $caption .= '"' . $presentation->getObjectTitle() . '"'; + + return ''; + } +} diff --git a/Modules/Portfolio/classes/class.ilPortfolioPageTableGUI.php b/Modules/Portfolio/classes/class.ilPortfolioPageTableGUI.php index ba440e60e7ba1bd2250db2fcfa80188d4bcc1e14..ee3d7616c56b37b87356547751f48725d14d9c68 100644 --- a/Modules/Portfolio/classes/class.ilPortfolioPageTableGUI.php +++ b/Modules/Portfolio/classes/class.ilPortfolioPageTableGUI.php @@ -1,215 +1,206 @@ - - * @version $Id$ - * - * @ingroup ModulesPortfolio - */ -class ilPortfolioPageTableGUI extends ilTable2GUI -{ - /** - * @var ilObjUser - */ - protected $user; - - protected $portfolio; // [ilObjPortfolio] - protected $is_template; // [bool] - protected $page_gui; // [string] - - /** - * Constructor - */ - function __construct(ilObjPortfolioBaseGUI $a_parent_obj, $a_parent_cmd) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->disable("numinfo"); - $this->setLimit(9999); - - $this->portfolio = $a_parent_obj->object; - $this->page_gui = $this->parent_obj->getPageGUIClassName(); - $this->is_template = ($this->portfolio->getType() == "prtt"); - - $this->setTitle($lng->txt("tabs")); - - //$this->addColumn($this->lng->txt(""), "", "1"); - $this->addColumn($this->lng->txt("user_order")); - $this->addColumn($this->lng->txt("title")); - $this->addColumn($this->lng->txt("type")); - $this->addColumn($this->lng->txt("actions")); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.portfolio_page_row.html", "Modules/Portfolio"); - - //$this->addMultiCommand("confirmPortfolioPageDeletion", $lng->txt("delete")); - //$this->addMultiCommand("copyPageForm", $lng->txt("prtf_copy_page")); - - $this->addCommandButton("savePortfolioPagesOrdering", - $lng->txt("user_save_ordering_and_titles")); - - $this->getItems(); - - $lng->loadLanguageModule("blog"); - } - - function getItems() - { - $ilUser = $this->user; - - $data = ilPortfolioPage::getAllPortfolioPages($this->portfolio->getId()); - $this->setData($data); - - if(!$this->is_template) - { - $this->blogs = array(); - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - $tree = new ilWorkspaceTree($ilUser->getId()); - $root = $tree->readRootId(); - if($root) - { - $root = $tree->getNodeData($root); - foreach ($tree->getSubTree($root) as $node) - { - if ($node["type"] == "blog") - { - $this->blogs[$node["obj_id"]] = $node["wsp_id"]; - } - } - } - - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; - include_once("./Modules/Blog/classes/class.ilObjBlog.php"); - } - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $action_items = []; - - switch($a_set["type"]) - { - case ilPortfolioPage::TYPE_PAGE: - $this->tpl->setCurrentBlock("title_field"); - $this->tpl->setVariable("ID", $a_set["id"]); - $this->tpl->setVariable("VAL_TITLE", ilUtil::prepareFormOutput($a_set["title"])); - $this->tpl->parseCurrentBlock(); - - $ilCtrl->setParameterByClass($this->page_gui, - "ppage", $a_set["id"]); - $action_item = ilLinkButton::getInstance(); - $action_item->setCaption('edit_page'); - $action_item->setUrl($ilCtrl->getLinkTargetByClass($this->page_gui, "edit")); - $action_items[] = $action_item; - - - $this->tpl->setVariable("TYPE", $lng->txt("page")); - break; - - case ilPortfolioPage::TYPE_BLOG: - if(!$this->is_template) - { - $this->tpl->setCurrentBlock("title_static"); - $this->tpl->setVariable("VAL_TITLE_STATIC", ilObjBlog::_lookupTitle($a_set["title"])); - $this->tpl->parseCurrentBlock(); - - $obj_id = (int)$a_set["title"]; - if(isset($this->blogs[$obj_id])) - { - $node_id = $this->blogs[$obj_id]; - $link = ilWorkspaceAccessHandler::getGotoLink($node_id, $obj_id); - - // #11519 - $ilCtrl->setParameterByClass($this->page_gui, - "ppage", $a_set["id"]); - $link = $ilCtrl->getLinkTargetByClass(array($this->page_gui, "ilobjbloggui"), "render"); - - $action_item = ilLinkButton::getInstance(); - $action_item->setCaption('blog_edit'); - $action_item->setUrl($link); - $action_items[] = $action_item; - - - } - $this->tpl->setVariable("TYPE", $lng->txt("obj_blog")); - } - break; - - case ilPortfolioTemplatePage::TYPE_BLOG_TEMPLATE: - if($this->is_template) - { - $this->tpl->setCurrentBlock("title_field"); - $this->tpl->setVariable("ID", $a_set["id"]); - $this->tpl->setVariable("VAL_TITLE", ilUtil::prepareFormOutput($a_set["title"])); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setCurrentBlock("title_static"); - //$this->tpl->setVariable("VAL_TITLE_STATIC", $lng->txt("obj_blog")); - $this->tpl->parseCurrentBlock(); - $this->tpl->setVariable("TYPE", $lng->txt("obj_blog")); - } - break; - } - - $ilCtrl->setParameter($this->parent_obj, "prtf_pages[]", $a_set["id"]); - - // copy - $action_item = ilLinkButton::getInstance(); - $action_item->setCaption('prtf_copy_tab'); - $action_item->setUrl($ilCtrl->getLinkTarget($this->parent_obj, "copyPageForm")); - $action_items[] = $action_item; - - // delete - $action_item = ilLinkButton::getInstance(); - $action_item->setCaption('delete'); - $action_item->setUrl($ilCtrl->getLinkTarget($this->parent_obj, "confirmPortfolioPageDeletion")); - $action_items[] = $action_item; - - - $ilCtrl->setParameter($this->parent_obj, "prtf_pages[]", ""); - - if (count($action_items) > 0) - { - $split_button = ilSplitButtonGUI::getInstance(); - $i = 0; - foreach ($action_items as $item) - { - if ($i++ == 0) - { - $split_button->setDefaultButton($item); - } - else - { - $split_button->addMenuItem(new ilButtonToSplitButtonMenuItemAdapter($item)); - } - } - $this->tpl->setVariable("SPLIT_BUTTON", $split_button->render()); - } - - - $this->tpl->setVariable("ID", $a_set["id"]); - $this->tpl->setVariable("VAL_ORDER_NR", $a_set["order_nr"]); - } -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @ingroup ModulesPortfolio + */ +class ilPortfolioPageTableGUI extends ilTable2GUI +{ + /** + * @var ilObjUser + */ + protected $user; + + protected $portfolio; // [ilObjPortfolio] + protected $is_template; // [bool] + protected $page_gui; // [string] + + /** + * Constructor + */ + public function __construct(ilObjPortfolioBaseGUI $a_parent_obj, $a_parent_cmd) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->disable("numinfo"); + $this->setLimit(9999); + + $this->portfolio = $a_parent_obj->object; + $this->page_gui = $this->parent_obj->getPageGUIClassName(); + $this->is_template = ($this->portfolio->getType() == "prtt"); + + $this->setTitle($lng->txt("tabs")); + + //$this->addColumn($this->lng->txt(""), "", "1"); + $this->addColumn($this->lng->txt("user_order")); + $this->addColumn($this->lng->txt("title")); + $this->addColumn($this->lng->txt("type")); + $this->addColumn($this->lng->txt("actions")); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.portfolio_page_row.html", "Modules/Portfolio"); + + //$this->addMultiCommand("confirmPortfolioPageDeletion", $lng->txt("delete")); + //$this->addMultiCommand("copyPageForm", $lng->txt("prtf_copy_page")); + + $this->addCommandButton( + "savePortfolioPagesOrdering", + $lng->txt("user_save_ordering_and_titles") + ); + + $this->getItems(); + + $lng->loadLanguageModule("blog"); + } + + public function getItems() + { + $ilUser = $this->user; + + $data = ilPortfolioPage::getAllPortfolioPages($this->portfolio->getId()); + $this->setData($data); + + if (!$this->is_template) { + $this->blogs = array(); + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + $tree = new ilWorkspaceTree($ilUser->getId()); + $root = $tree->readRootId(); + if ($root) { + $root = $tree->getNodeData($root); + foreach ($tree->getSubTree($root) as $node) { + if ($node["type"] == "blog") { + $this->blogs[$node["obj_id"]] = $node["wsp_id"]; + } + } + } + + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; + include_once("./Modules/Blog/classes/class.ilObjBlog.php"); + } + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $action_items = []; + + switch ($a_set["type"]) { + case ilPortfolioPage::TYPE_PAGE: + $this->tpl->setCurrentBlock("title_field"); + $this->tpl->setVariable("ID", $a_set["id"]); + $this->tpl->setVariable("VAL_TITLE", ilUtil::prepareFormOutput($a_set["title"])); + $this->tpl->parseCurrentBlock(); + + $ilCtrl->setParameterByClass( + $this->page_gui, + "ppage", + $a_set["id"] + ); + $action_item = ilLinkButton::getInstance(); + $action_item->setCaption('edit_page'); + $action_item->setUrl($ilCtrl->getLinkTargetByClass($this->page_gui, "edit")); + $action_items[] = $action_item; + + + $this->tpl->setVariable("TYPE", $lng->txt("page")); + break; + + case ilPortfolioPage::TYPE_BLOG: + if (!$this->is_template) { + $this->tpl->setCurrentBlock("title_static"); + $this->tpl->setVariable("VAL_TITLE_STATIC", ilObjBlog::_lookupTitle($a_set["title"])); + $this->tpl->parseCurrentBlock(); + + $obj_id = (int) $a_set["title"]; + if (isset($this->blogs[$obj_id])) { + $node_id = $this->blogs[$obj_id]; + $link = ilWorkspaceAccessHandler::getGotoLink($node_id, $obj_id); + + // #11519 + $ilCtrl->setParameterByClass( + $this->page_gui, + "ppage", + $a_set["id"] + ); + $link = $ilCtrl->getLinkTargetByClass(array($this->page_gui, "ilobjbloggui"), "render"); + + $action_item = ilLinkButton::getInstance(); + $action_item->setCaption('blog_edit'); + $action_item->setUrl($link); + $action_items[] = $action_item; + } + $this->tpl->setVariable("TYPE", $lng->txt("obj_blog")); + } + break; + + case ilPortfolioTemplatePage::TYPE_BLOG_TEMPLATE: + if ($this->is_template) { + $this->tpl->setCurrentBlock("title_field"); + $this->tpl->setVariable("ID", $a_set["id"]); + $this->tpl->setVariable("VAL_TITLE", ilUtil::prepareFormOutput($a_set["title"])); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setCurrentBlock("title_static"); + //$this->tpl->setVariable("VAL_TITLE_STATIC", $lng->txt("obj_blog")); + $this->tpl->parseCurrentBlock(); + $this->tpl->setVariable("TYPE", $lng->txt("obj_blog")); + } + break; + } + + $ilCtrl->setParameter($this->parent_obj, "prtf_pages[]", $a_set["id"]); + + // copy + $action_item = ilLinkButton::getInstance(); + $action_item->setCaption('prtf_copy_tab'); + $action_item->setUrl($ilCtrl->getLinkTarget($this->parent_obj, "copyPageForm")); + $action_items[] = $action_item; + + // delete + $action_item = ilLinkButton::getInstance(); + $action_item->setCaption('delete'); + $action_item->setUrl($ilCtrl->getLinkTarget($this->parent_obj, "confirmPortfolioPageDeletion")); + $action_items[] = $action_item; + + + $ilCtrl->setParameter($this->parent_obj, "prtf_pages[]", ""); + + if (count($action_items) > 0) { + $split_button = ilSplitButtonGUI::getInstance(); + $i = 0; + foreach ($action_items as $item) { + if ($i++ == 0) { + $split_button->setDefaultButton($item); + } else { + $split_button->addMenuItem(new ilButtonToSplitButtonMenuItemAdapter($item)); + } + } + $this->tpl->setVariable("SPLIT_BUTTON", $split_button->render()); + } + + + $this->tpl->setVariable("ID", $a_set["id"]); + $this->tpl->setVariable("VAL_ORDER_NR", $a_set["order_nr"]); + } +} diff --git a/Modules/Portfolio/classes/class.ilPortfolioRepositoryGUI.php b/Modules/Portfolio/classes/class.ilPortfolioRepositoryGUI.php index 78e8fbed7d2f01285c5a65cb9c89a8c19ce90a54..407e6925d66f852db74945dee8ab930057ac3ba8 100644 --- a/Modules/Portfolio/classes/class.ilPortfolioRepositoryGUI.php +++ b/Modules/Portfolio/classes/class.ilPortfolioRepositoryGUI.php @@ -1,643 +1,624 @@ - - * @version $Id$ - * - * @ilCtrl_Calls ilPortfolioRepositoryGUI: ilObjPortfolioGUI, ilObjExerciseGUI - * - * @ingroup ModulesPortfolio - */ -class ilPortfolioRepositoryGUI -{ - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilHelpGUI - */ - protected $help; - - /** - * @var ilLocatorGUI - */ - protected $locator; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilSetting - */ - protected $settings; - - protected $user_id; // [int] - protected $access_handler; // [ilPortfolioAccessHandler] - - /** - * @var \ILIAS\DI\UIServices - */ - protected $ui; - - public function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - $this->ctrl = $DIC->ctrl(); - $this->tpl = $DIC["tpl"]; - $this->tabs = $DIC->tabs(); - $this->help = $DIC["ilHelp"]; - $this->locator = $DIC["ilLocator"]; - $this->toolbar = $DIC->toolbar(); - $this->settings = $DIC->settings(); - $this->ui = $DIC->ui(); - $lng = $DIC->language(); - $ilUser = $DIC->user(); - - $lng->loadLanguageModule("prtf"); - $lng->loadLanguageModule("user"); - - include_once('./Modules/Portfolio/classes/class.ilPortfolioAccessHandler.php'); - $this->access_handler = new ilPortfolioAccessHandler(); - - $this->user_id = $ilUser->getId(); - } - - public function executeCommand() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd("show"); - - $tpl->setTitle($lng->txt("portfolio")); - $tpl->setTitleIcon(ilUtil::getImagePath("icon_prtf.svg"), - $lng->txt("portfolio")); - - switch($next_class) - { - case "ilobjportfoliogui": - - include_once('./Modules/Portfolio/classes/class.ilObjPortfolioGUI.php'); - $gui = new ilObjPortfolioGUI((int) $_REQUEST["prt_id"]); - - if($cmd != "preview") - { - $this->setLocator(); - - if ((int) $_GET["exc_back_ref_id"] > 0) - { - include_once("./Services/Link/classes/class.ilLink.php"); - $ilTabs->setBack2Target($lng->txt("obj_exc"), ilLink::_getLink((int) $_GET["exc_back_ref_id"])); - } - else - { - $ilTabs->setBack2Target($lng->txt("prtf_tab_portfolios"), $ilCtrl->getLinkTarget($this, "show")); - } - } - - $ilCtrl->forwardCommand($gui); - break; - - default: - $this->setLocator(); - $this->setTabs(); - $this->$cmd(); - break; - } - - return true; - } - - public function setTabs() - { - $ilTabs = $this->tabs; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilHelp = $this->help; - - $ilHelp->setScreenIdComponent("prtf"); - - $ilTabs->addTab("mypf", $lng->txt("prtf_tab_portfolios"), - $ilCtrl->getLinkTarget($this)); - - $ilTabs->addTab("otpf", $lng->txt("prtf_tab_other_users"), - $ilCtrl->getLinkTarget($this, "showotherFilter")); - - $ilTabs->activateTab("mypf"); - } - - protected function setLocator() - { - $ilLocator = $this->locator; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - - $ilLocator->addItem($lng->txt("portfolio"), - $ilCtrl->getLinkTarget($this, "show")); - - $tpl->setLocator(); - } - - protected function checkAccess($a_permission, $a_portfolio_id = null) - { - if($a_portfolio_id) - { - return $this->access_handler->checkAccess($a_permission, "", $a_portfolio_id); - } - // currently only object-based permissions - return true; - } - - - // - // LIST INCL. ACTIONS - // - - protected function show() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - - include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; - $button = ilLinkButton::getInstance(); - $button->setCaption("prtf_add_portfolio"); - $button->setUrl($ilCtrl->getLinkTargetByClass("ilObjPortfolioGUI", "create")); - $ilToolbar->addButtonInstance($button); - $portfolio_list = $this->getPortfolioList(); - - $tpl->setContent($portfolio_list.ilDiskQuotaHandler::getStatusLegend()); - } - - /** - * Get portfolio list - * - * @param - * @return string - */ - protected function getPortfolioList() - { - $ui = $this->ui; - $f = $ui->factory(); - $renderer = $ui->renderer(); - $lng = $this->lng; - $ctrl = $this->ctrl; - - $access_handler = new ilPortfolioAccessHandler(); - - $shared_objects = $access_handler->getObjectsIShare(false); - - $items = []; - - foreach (ilObjPortfolio::getPortfoliosOfUser($this->user_id) as $port) - { - // icon - $icon = $f->icon()->custom(ilUtil::getImagePath("icon_prtf.svg"), - $lng->txt("obj_portfolio"), "medium"); - if (!$port["is_online"] || !in_array($port["id"], $shared_objects)) - { - $icon = $icon->withDisabled(true); - } - - // actions - $prtf_path = array(get_class($this), "ilobjportfoliogui"); - $action = []; - // ... preview - $ctrl->setParameterByClass("ilobjportfoliogui", "prt_id", $port["id"]); - $preview_action = $ctrl->getLinkTargetByClass($prtf_path, "preview"); - $action[] = $f->button()->shy($lng->txt("user_profile_preview"), $preview_action); - // ... edit content - $action[] = $f->button()->shy($lng->txt("prtf_edit_content"), - $ctrl->getLinkTargetByClass($prtf_path, "view")); - $ctrl->setParameter($this, "prt_id", $port["id"]); - if($port["is_online"]) - { - // ... set offline - $action[] = $f->button()->shy($lng->txt("prtf_set_offline"), - $ctrl->getLinkTarget($this, "setOffline")); - } - else - { - // ... set online - $action[] = $f->button()->shy($lng->txt("prtf_set_online"), - $ctrl->getLinkTarget($this, "setOnline")); - } - $ctrl->setParameter($this, "prt_id", ""); - // ... settings - $action[] = $f->button()->shy($lng->txt("settings"), - $ctrl->getLinkTargetByClass($prtf_path, "edit")); - // ... sharing - $action[] = $f->button()->shy($lng->txt("wsp_permissions"), - $ctrl->getLinkTargetByClass(array(get_class($this), "ilobjportfoliogui", "ilWorkspaceAccessGUI"), "share")); - $ctrl->setParameterByClass("ilobjportfoliogui", "prt_id", ""); - - if($port["is_online"]) - { - if(!$port["is_default"]) - { - // ... set as default - $ctrl->setParameter($this, "prt_id", $port["id"]); - - $action[] = $f->button()->shy($lng->txt("prtf_set_as_default"), - $ctrl->getLinkTarget($this, "setDefaultConfirmation")); - - $ctrl->setParameter($this, "prt_id", ""); - } - else - { - // ... unset as default - $action[] = $f->button()->shy($lng->txt("prtf_unset_as_default"), - $ctrl->getLinkTarget($this, "unsetDefault")); - } - } - // ... delete - $ctrl->setParameter($this, "prtfs[]", $port["id"]); - $action[] = $f->button()->shy($lng->txt("delete"), - $ctrl->getLinkTarget($this, "confirmPortfolioDeletion")); - $ctrl->setParameter($this, "prtfs[]", ""); - $actions = $f->dropdown()->standard($action); - - - // properties - $props = []; - // ... online - $props[$lng->txt("online")] = ($port["is_online"]) - ? $lng->txt("yes") - : "".$lng->txt("no").""; - // ... shared - $props[$lng->txt("wsp_status_shared")] = (in_array($port["id"], $shared_objects)) - ? $lng->txt("yes") - : "".$lng->txt("no").""; - // ... default (my profile) - if ($port["is_default"]) - { - $props[$lng->txt("prtf_default_portfolio")] = $lng->txt("yes"); - } - // ... handed in - // exercise portfolio? - include_once "Modules/Portfolio/classes/class.ilPortfolioExerciseGUI.php"; - $exercises = ilPortfolioExerciseGUI::checkExercise($this->user_id, $port["id"], false, true); - foreach ($exercises as $exinfo) - { - if ($exinfo["submitted"]) - { - $props[$exinfo["ass_title"]] = - str_replace("$1", $exinfo["submitted_date"], $lng->txt("prtf_submission_on")); - } - else - { - $props[$exinfo["ass_title"]] = "".$lng->txt("prtf_no_submission").""; - } - } - - - $items[] = $f->item()->standard($f->button()->shy($port["title"], $preview_action)) - ->withActions($actions) - ->withProperties($props) - ->withLeadIcon($icon); - } - - - $std_list = $f->panel()->listing()->standard($lng->txt("prtf_portfolios"), array( - $f->item()->group("", $items) - )); - - return $renderer->render($std_list); - } - - - /** - * Set online - */ - protected function setOnline() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $prt_id = (int) $_GET["prt_id"]; - if (ilObjPortfolio::_lookupOwner($prt_id) == $this->user_id) - { - $portfolio = new ilObjPortfolio($prt_id, false); - $portfolio->setOnline(true); - $portfolio->update(); - ilUtil::sendSuccess($lng->txt("saved_successfully"), true); - $ilCtrl->redirect($this, "show"); - } - $ilCtrl->redirect($this, "show"); - } - - /** - * Set offline - */ - protected function setOffline() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $prt_id = (int) $_GET["prt_id"]; - if (ilObjPortfolio::_lookupOwner($prt_id) == $this->user_id) - { - $portfolio = new ilObjPortfolio($prt_id, false); - $portfolio->setOnline(false); - $portfolio->update(); - ilUtil::sendSuccess($lng->txt("saved_successfully"), true); - $ilCtrl->redirect($this, "show"); - } - $ilCtrl->redirect($this, "show"); - } - - - protected function saveTitles() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - foreach($_POST["title"] as $id => $title) - { - if(trim($title)) - { - if($this->checkAccess("write", $id)) - { - $portfolio = new ilObjPortfolio($id, false); - $portfolio->setTitle(ilUtil::stripSlashes($title)); - - if(is_array($_POST["online"]) && in_array($id, $_POST["online"])) - { - $portfolio->setOnline(true); - } - else - { - $portfolio->setOnline(false); - } - - $portfolio->update(); - } - } - } - - ilUtil::sendSuccess($lng->txt("saved_successfully"), true); - $ilCtrl->redirect($this, "show"); - } - - protected function confirmPortfolioDeletion() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - $prtfs = $_REQUEST["prtfs"]; - - if (!is_array($prtfs) || count($prtfs) == 0) - { - ilUtil::sendInfo($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "show"); - } - else - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("prtf_sure_delete_portfolios")); - $cgui->setCancel($lng->txt("cancel"), "show"); - $cgui->setConfirm($lng->txt("delete"), "deletePortfolios"); - - foreach ($prtfs as $id) - { - $cgui->addItem("prtfs[]", $id, ilObjPortfolio::_lookupTitle($id)); - } - - $tpl->setContent($cgui->getHTML()); - } - } - - protected function deletePortfolios() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if (is_array($_POST["prtfs"])) - { - foreach ($_POST["prtfs"] as $id) - { - if($this->checkAccess("write", $id)) - { - $portfolio = new ilObjPortfolio($id, false); - if ($portfolio->getOwner() == $this->user_id) - { - $this->access_handler->removePermission($id); - $portfolio->delete(); - } - } - } - } - ilUtil::sendSuccess($lng->txt("prtf_portfolio_deleted"), true); - $ilCtrl->redirect($this, "show"); - } - - - // - // DEFAULT PORTFOLIO (aka profile) - // - - protected function unsetDefault() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilUser = $this->user; - - if($this->checkAccess("write")) - { - // #12845 - $ilUser->setPref("public_profile", "n"); - $ilUser->writePrefs(); - - ilObjPortfolio::setUserDefault($this->user_id); - ilUtil::sendSuccess($lng->txt("prtf_unset_default_share_info"), true); - } - $ilCtrl->redirect($this, "show"); - } - - /** - * Confirm sharing when setting default - */ - protected function setDefaultConfirmation() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - $ilSetting = $this->settings; - - $prtf_id = (int)$_REQUEST["prt_id"]; - - if($prtf_id && $this->checkAccess("write")) - { - // if already shared, no need to ask again - if($this->access_handler->hasRegisteredPermission($prtf_id) || - $this->access_handler->hasGlobalPermission($prtf_id)) - { - return $this->setDefault($prtf_id); - } - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($lng->txt("cancel"), - $ilCtrl->getLinkTarget($this, "show")); - - $ilCtrl->setParameter($this, "prt_id", $prtf_id); - - // #20310 - if(!$ilSetting->get("enable_global_profiles")) - { - $ilCtrl->redirect($this, "setDefaultRegistered"); - } - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("prtf_set_default_publish_confirmation")); - $cgui->setCancel($lng->txt("prtf_set_default_publish_global"), "setDefaultGlobal"); - $cgui->setConfirm($lng->txt("prtf_set_default_publish_registered"), "setDefaultRegistered"); - $tpl->setContent($cgui->getHTML()); - - return; - } - - $ilCtrl->redirect($this, "show"); - } - - protected function setDefaultGlobal() - { - $ilCtrl = $this->ctrl; - - $prtf_id = (int)$_REQUEST["prt_id"]; - if($prtf_id && $this->checkAccess("write")) - { - $this->access_handler->addPermission($prtf_id, ilWorkspaceAccessGUI::PERMISSION_ALL); - $this->setDefault($prtf_id); - } - $ilCtrl->redirect($this, "show"); - } - - protected function setDefaultRegistered() - { - $ilCtrl = $this->ctrl; - - $prtf_id = (int)$_REQUEST["prt_id"]; - if($prtf_id && $this->checkAccess("write")) - { - $this->access_handler->addPermission($prtf_id, ilWorkspaceAccessGUI::PERMISSION_REGISTERED); - $this->setDefault($prtf_id); - } - $ilCtrl->redirect($this, "show"); - } - - protected function setDefault($a_prtf_id) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilUser = $this->user; - - if($a_prtf_id && $this->checkAccess("write")) - { - // #12845 - if($this->access_handler->hasGlobalPermission($a_prtf_id)) - { - $ilUser->setPref("public_profile", "g"); - $ilUser->writePrefs(); - } - else if($this->access_handler->hasRegisteredPermission($a_prtf_id)) - { - $ilUser->setPref("public_profile", "y"); - $ilUser->writePrefs(); - } - else - { - return; - } - ilObjPortfolio::setUserDefault($this->user_id, $a_prtf_id); - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - } - $ilCtrl->redirect($this, "show"); - } - - - // - // SHARE - // - - protected function showOtherFilter() - { - $this->showOther(false); - } - - protected function showOther($a_load_data = true) - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - $ilTabs->activateTab("otpf"); - - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceShareTableGUI.php"; - $tbl = new ilWorkspaceShareTableGUI($this, "showOther", $this->access_handler, null, $a_load_data); - $tpl->setContent($tbl->getHTML()); - } - - protected function applyShareFilter() - { - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceShareTableGUI.php"; - $tbl = new ilWorkspaceShareTableGUI($this, "showOther", $this->access_handler); - $tbl->resetOffset(); - $tbl->writeFilterToSession(); - - $this->showOther(); - } - - protected function resetShareFilter() - { - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceShareTableGUI.php"; - $tbl = new ilWorkspaceShareTableGUI($this, "showOther", $this->access_handler); - $tbl->resetOffset(); - $tbl->resetFilter(); - - $this->showOther(); - } -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @ilCtrl_Calls ilPortfolioRepositoryGUI: ilObjPortfolioGUI, ilObjExerciseGUI + * + * @ingroup ModulesPortfolio + */ +class ilPortfolioRepositoryGUI +{ + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var ilLocatorGUI + */ + protected $locator; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilSetting + */ + protected $settings; + + protected $user_id; // [int] + protected $access_handler; // [ilPortfolioAccessHandler] + + /** + * @var \ILIAS\DI\UIServices + */ + protected $ui; + + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + $this->ctrl = $DIC->ctrl(); + $this->tpl = $DIC["tpl"]; + $this->tabs = $DIC->tabs(); + $this->help = $DIC["ilHelp"]; + $this->locator = $DIC["ilLocator"]; + $this->toolbar = $DIC->toolbar(); + $this->settings = $DIC->settings(); + $this->ui = $DIC->ui(); + $lng = $DIC->language(); + $ilUser = $DIC->user(); + + $lng->loadLanguageModule("prtf"); + $lng->loadLanguageModule("user"); + + include_once('./Modules/Portfolio/classes/class.ilPortfolioAccessHandler.php'); + $this->access_handler = new ilPortfolioAccessHandler(); + + $this->user_id = $ilUser->getId(); + } + + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd("show"); + + $tpl->setTitle($lng->txt("portfolio")); + $tpl->setTitleIcon( + ilUtil::getImagePath("icon_prtf.svg"), + $lng->txt("portfolio") + ); + + switch ($next_class) { + case "ilobjportfoliogui": + + include_once('./Modules/Portfolio/classes/class.ilObjPortfolioGUI.php'); + $gui = new ilObjPortfolioGUI((int) $_REQUEST["prt_id"]); + + if ($cmd != "preview") { + $this->setLocator(); + + if ((int) $_GET["exc_back_ref_id"] > 0) { + include_once("./Services/Link/classes/class.ilLink.php"); + $ilTabs->setBack2Target($lng->txt("obj_exc"), ilLink::_getLink((int) $_GET["exc_back_ref_id"])); + } else { + $ilTabs->setBack2Target($lng->txt("prtf_tab_portfolios"), $ilCtrl->getLinkTarget($this, "show")); + } + } + + $ilCtrl->forwardCommand($gui); + break; + + default: + $this->setLocator(); + $this->setTabs(); + $this->$cmd(); + break; + } + + return true; + } + + public function setTabs() + { + $ilTabs = $this->tabs; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilHelp = $this->help; + + $ilHelp->setScreenIdComponent("prtf"); + + $ilTabs->addTab( + "mypf", + $lng->txt("prtf_tab_portfolios"), + $ilCtrl->getLinkTarget($this) + ); + + $ilTabs->addTab( + "otpf", + $lng->txt("prtf_tab_other_users"), + $ilCtrl->getLinkTarget($this, "showotherFilter") + ); + + $ilTabs->activateTab("mypf"); + } + + protected function setLocator() + { + $ilLocator = $this->locator; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + + $ilLocator->addItem( + $lng->txt("portfolio"), + $ilCtrl->getLinkTarget($this, "show") + ); + + $tpl->setLocator(); + } + + protected function checkAccess($a_permission, $a_portfolio_id = null) + { + if ($a_portfolio_id) { + return $this->access_handler->checkAccess($a_permission, "", $a_portfolio_id); + } + // currently only object-based permissions + return true; + } + + + // + // LIST INCL. ACTIONS + // + + protected function show() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilToolbar = $this->toolbar; + $ilCtrl = $this->ctrl; + + include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; + $button = ilLinkButton::getInstance(); + $button->setCaption("prtf_add_portfolio"); + $button->setUrl($ilCtrl->getLinkTargetByClass("ilObjPortfolioGUI", "create")); + $ilToolbar->addButtonInstance($button); + $portfolio_list = $this->getPortfolioList(); + + $tpl->setContent($portfolio_list . ilDiskQuotaHandler::getStatusLegend()); + } + + /** + * Get portfolio list + * + * @param + * @return string + */ + protected function getPortfolioList() + { + $ui = $this->ui; + $f = $ui->factory(); + $renderer = $ui->renderer(); + $lng = $this->lng; + $ctrl = $this->ctrl; + + $access_handler = new ilPortfolioAccessHandler(); + + $shared_objects = $access_handler->getObjectsIShare(false); + + $items = []; + + foreach (ilObjPortfolio::getPortfoliosOfUser($this->user_id) as $port) { + // icon + $icon = $f->icon()->custom( + ilUtil::getImagePath("icon_prtf.svg"), + $lng->txt("obj_portfolio"), + "medium" + ); + if (!$port["is_online"] || !in_array($port["id"], $shared_objects)) { + $icon = $icon->withDisabled(true); + } + + // actions + $prtf_path = array(get_class($this), "ilobjportfoliogui"); + $action = []; + // ... preview + $ctrl->setParameterByClass("ilobjportfoliogui", "prt_id", $port["id"]); + $preview_action = $ctrl->getLinkTargetByClass($prtf_path, "preview"); + $action[] = $f->button()->shy($lng->txt("user_profile_preview"), $preview_action); + // ... edit content + $action[] = $f->button()->shy( + $lng->txt("prtf_edit_content"), + $ctrl->getLinkTargetByClass($prtf_path, "view") + ); + $ctrl->setParameter($this, "prt_id", $port["id"]); + if ($port["is_online"]) { + // ... set offline + $action[] = $f->button()->shy( + $lng->txt("prtf_set_offline"), + $ctrl->getLinkTarget($this, "setOffline") + ); + } else { + // ... set online + $action[] = $f->button()->shy( + $lng->txt("prtf_set_online"), + $ctrl->getLinkTarget($this, "setOnline") + ); + } + $ctrl->setParameter($this, "prt_id", ""); + // ... settings + $action[] = $f->button()->shy( + $lng->txt("settings"), + $ctrl->getLinkTargetByClass($prtf_path, "edit") + ); + // ... sharing + $action[] = $f->button()->shy( + $lng->txt("wsp_permissions"), + $ctrl->getLinkTargetByClass(array(get_class($this), "ilobjportfoliogui", "ilWorkspaceAccessGUI"), "share") + ); + $ctrl->setParameterByClass("ilobjportfoliogui", "prt_id", ""); + + if ($port["is_online"]) { + if (!$port["is_default"]) { + // ... set as default + $ctrl->setParameter($this, "prt_id", $port["id"]); + + $action[] = $f->button()->shy( + $lng->txt("prtf_set_as_default"), + $ctrl->getLinkTarget($this, "setDefaultConfirmation") + ); + + $ctrl->setParameter($this, "prt_id", ""); + } else { + // ... unset as default + $action[] = $f->button()->shy( + $lng->txt("prtf_unset_as_default"), + $ctrl->getLinkTarget($this, "unsetDefault") + ); + } + } + // ... delete + $ctrl->setParameter($this, "prtfs[]", $port["id"]); + $action[] = $f->button()->shy( + $lng->txt("delete"), + $ctrl->getLinkTarget($this, "confirmPortfolioDeletion") + ); + $ctrl->setParameter($this, "prtfs[]", ""); + $actions = $f->dropdown()->standard($action); + + + // properties + $props = []; + // ... online + $props[$lng->txt("online")] = ($port["is_online"]) + ? $lng->txt("yes") + : "" . $lng->txt("no") . ""; + // ... shared + $props[$lng->txt("wsp_status_shared")] = (in_array($port["id"], $shared_objects)) + ? $lng->txt("yes") + : "" . $lng->txt("no") . ""; + // ... default (my profile) + if ($port["is_default"]) { + $props[$lng->txt("prtf_default_portfolio")] = $lng->txt("yes"); + } + // ... handed in + // exercise portfolio? + include_once "Modules/Portfolio/classes/class.ilPortfolioExerciseGUI.php"; + $exercises = ilPortfolioExerciseGUI::checkExercise($this->user_id, $port["id"], false, true); + foreach ($exercises as $exinfo) { + if ($exinfo["submitted"]) { + $props[$exinfo["ass_title"]] = + str_replace("$1", $exinfo["submitted_date"], $lng->txt("prtf_submission_on")); + } else { + $props[$exinfo["ass_title"]] = "" . $lng->txt("prtf_no_submission") . ""; + } + } + + + $items[] = $f->item()->standard($f->button()->shy($port["title"], $preview_action)) + ->withActions($actions) + ->withProperties($props) + ->withLeadIcon($icon); + } + + + $std_list = $f->panel()->listing()->standard($lng->txt("prtf_portfolios"), array( + $f->item()->group("", $items) + )); + + return $renderer->render($std_list); + } + + + /** + * Set online + */ + protected function setOnline() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $prt_id = (int) $_GET["prt_id"]; + if (ilObjPortfolio::_lookupOwner($prt_id) == $this->user_id) { + $portfolio = new ilObjPortfolio($prt_id, false); + $portfolio->setOnline(true); + $portfolio->update(); + ilUtil::sendSuccess($lng->txt("saved_successfully"), true); + $ilCtrl->redirect($this, "show"); + } + $ilCtrl->redirect($this, "show"); + } + + /** + * Set offline + */ + protected function setOffline() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $prt_id = (int) $_GET["prt_id"]; + if (ilObjPortfolio::_lookupOwner($prt_id) == $this->user_id) { + $portfolio = new ilObjPortfolio($prt_id, false); + $portfolio->setOnline(false); + $portfolio->update(); + ilUtil::sendSuccess($lng->txt("saved_successfully"), true); + $ilCtrl->redirect($this, "show"); + } + $ilCtrl->redirect($this, "show"); + } + + + protected function saveTitles() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + foreach ($_POST["title"] as $id => $title) { + if (trim($title)) { + if ($this->checkAccess("write", $id)) { + $portfolio = new ilObjPortfolio($id, false); + $portfolio->setTitle(ilUtil::stripSlashes($title)); + + if (is_array($_POST["online"]) && in_array($id, $_POST["online"])) { + $portfolio->setOnline(true); + } else { + $portfolio->setOnline(false); + } + + $portfolio->update(); + } + } + } + + ilUtil::sendSuccess($lng->txt("saved_successfully"), true); + $ilCtrl->redirect($this, "show"); + } + + protected function confirmPortfolioDeletion() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + $prtfs = $_REQUEST["prtfs"]; + + if (!is_array($prtfs) || count($prtfs) == 0) { + ilUtil::sendInfo($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "show"); + } else { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("prtf_sure_delete_portfolios")); + $cgui->setCancel($lng->txt("cancel"), "show"); + $cgui->setConfirm($lng->txt("delete"), "deletePortfolios"); + + foreach ($prtfs as $id) { + $cgui->addItem("prtfs[]", $id, ilObjPortfolio::_lookupTitle($id)); + } + + $tpl->setContent($cgui->getHTML()); + } + } + + protected function deletePortfolios() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if (is_array($_POST["prtfs"])) { + foreach ($_POST["prtfs"] as $id) { + if ($this->checkAccess("write", $id)) { + $portfolio = new ilObjPortfolio($id, false); + if ($portfolio->getOwner() == $this->user_id) { + $this->access_handler->removePermission($id); + $portfolio->delete(); + } + } + } + } + ilUtil::sendSuccess($lng->txt("prtf_portfolio_deleted"), true); + $ilCtrl->redirect($this, "show"); + } + + + // + // DEFAULT PORTFOLIO (aka profile) + // + + protected function unsetDefault() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilUser = $this->user; + + if ($this->checkAccess("write")) { + // #12845 + $ilUser->setPref("public_profile", "n"); + $ilUser->writePrefs(); + + ilObjPortfolio::setUserDefault($this->user_id); + ilUtil::sendSuccess($lng->txt("prtf_unset_default_share_info"), true); + } + $ilCtrl->redirect($this, "show"); + } + + /** + * Confirm sharing when setting default + */ + protected function setDefaultConfirmation() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + $ilSetting = $this->settings; + + $prtf_id = (int) $_REQUEST["prt_id"]; + + if ($prtf_id && $this->checkAccess("write")) { + // if already shared, no need to ask again + if ($this->access_handler->hasRegisteredPermission($prtf_id) || + $this->access_handler->hasGlobalPermission($prtf_id)) { + return $this->setDefault($prtf_id); + } + + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $lng->txt("cancel"), + $ilCtrl->getLinkTarget($this, "show") + ); + + $ilCtrl->setParameter($this, "prt_id", $prtf_id); + + // #20310 + if (!$ilSetting->get("enable_global_profiles")) { + $ilCtrl->redirect($this, "setDefaultRegistered"); + } + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("prtf_set_default_publish_confirmation")); + $cgui->setCancel($lng->txt("prtf_set_default_publish_global"), "setDefaultGlobal"); + $cgui->setConfirm($lng->txt("prtf_set_default_publish_registered"), "setDefaultRegistered"); + $tpl->setContent($cgui->getHTML()); + + return; + } + + $ilCtrl->redirect($this, "show"); + } + + protected function setDefaultGlobal() + { + $ilCtrl = $this->ctrl; + + $prtf_id = (int) $_REQUEST["prt_id"]; + if ($prtf_id && $this->checkAccess("write")) { + $this->access_handler->addPermission($prtf_id, ilWorkspaceAccessGUI::PERMISSION_ALL); + $this->setDefault($prtf_id); + } + $ilCtrl->redirect($this, "show"); + } + + protected function setDefaultRegistered() + { + $ilCtrl = $this->ctrl; + + $prtf_id = (int) $_REQUEST["prt_id"]; + if ($prtf_id && $this->checkAccess("write")) { + $this->access_handler->addPermission($prtf_id, ilWorkspaceAccessGUI::PERMISSION_REGISTERED); + $this->setDefault($prtf_id); + } + $ilCtrl->redirect($this, "show"); + } + + protected function setDefault($a_prtf_id) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilUser = $this->user; + + if ($a_prtf_id && $this->checkAccess("write")) { + // #12845 + if ($this->access_handler->hasGlobalPermission($a_prtf_id)) { + $ilUser->setPref("public_profile", "g"); + $ilUser->writePrefs(); + } elseif ($this->access_handler->hasRegisteredPermission($a_prtf_id)) { + $ilUser->setPref("public_profile", "y"); + $ilUser->writePrefs(); + } else { + return; + } + ilObjPortfolio::setUserDefault($this->user_id, $a_prtf_id); + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + } + $ilCtrl->redirect($this, "show"); + } + + + // + // SHARE + // + + protected function showOtherFilter() + { + $this->showOther(false); + } + + protected function showOther($a_load_data = true) + { + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + $ilTabs->activateTab("otpf"); + + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceShareTableGUI.php"; + $tbl = new ilWorkspaceShareTableGUI($this, "showOther", $this->access_handler, null, $a_load_data); + $tpl->setContent($tbl->getHTML()); + } + + protected function applyShareFilter() + { + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceShareTableGUI.php"; + $tbl = new ilWorkspaceShareTableGUI($this, "showOther", $this->access_handler); + $tbl->resetOffset(); + $tbl->writeFilterToSession(); + + $this->showOther(); + } + + protected function resetShareFilter() + { + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceShareTableGUI.php"; + $tbl = new ilWorkspaceShareTableGUI($this, "showOther", $this->access_handler); + $tbl->resetOffset(); + $tbl->resetFilter(); + + $this->showOther(); + } +} diff --git a/Modules/Portfolio/classes/class.ilPortfolioTableGUI.php b/Modules/Portfolio/classes/class.ilPortfolioTableGUI.php index 9125d3e036e6bb252cdf02ac23d97fd0b56cc8f8..254c158180ef5b93b363e61555d542df2f139c69 100644 --- a/Modules/Portfolio/classes/class.ilPortfolioTableGUI.php +++ b/Modules/Portfolio/classes/class.ilPortfolioTableGUI.php @@ -1,148 +1,154 @@ - - * @version $Id$ - * - * @ingroup ModulesPortfolio - */ -class ilPortfolioTableGUI extends ilTable2GUI -{ - /** - * @var ilObjUser - */ - protected $user; - - protected $user_id; - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_user_id) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->user_id = (int)$a_user_id; - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setTitle($lng->txt("prtf_portfolios")); - - $this->addColumn($this->lng->txt(""), "", "1"); - $this->addColumn($this->lng->txt("title"), "title", "50%"); - $this->addColumn($this->lng->txt("online"), "is_online"); - $this->addColumn($this->lng->txt("prtf_default_portfolio"), "is_default"); - $this->addColumn($this->lng->txt("actions")); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.portfolio_row.html", "Modules/Portfolio"); - - $this->addMultiCommand("confirmPortfolioDeletion", $lng->txt("delete")); - $this->addCommandButton("saveTitles", $lng->txt("prtf_save_status_and_titles")); - - $this->getItems(); - - $lng->loadLanguageModule("wsp"); - - include_once('./Services/Link/classes/class.ilLink.php'); - } - - protected function getItems() - { - $ilUser = $this->user; - - include_once "Modules/Portfolio/classes/class.ilPortfolioAccessHandler.php"; - $access_handler = new ilPortfolioAccessHandler(); - - include_once "Modules/Portfolio/classes/class.ilObjPortfolio.php"; - $data = ilObjPortfolio::getPortfoliosOfUser($this->user_id); - - $this->shared_objects = $access_handler->getObjectsIShare(false); - - $this->setData($data); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->tpl->setCurrentBlock("title_form"); - $this->tpl->setVariable("VAL_ID", $a_set["id"]); - $this->tpl->setVariable("VAL_TITLE", ilUtil::prepareFormOutput($a_set["title"])); - $this->tpl->parseCurrentBlock(); - - if(in_array($a_set["id"], $this->shared_objects)) - { - $this->tpl->setCurrentBlock("shared"); - $this->tpl->setVariable("TXT_SHARED", $lng->txt("wsp_status_shared")); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setCurrentBlock("chck"); - $this->tpl->setVariable("VAL_ID", $a_set["id"]); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setCurrentBlock("edit"); - $this->tpl->setVariable("VAL_ID", $a_set["id"]); - $this->tpl->setVariable("STATUS_ONLINE", - ($a_set["is_online"]) ? " checked=\"checked\"" : ""); - $this->tpl->setVariable("VAL_DEFAULT", - ($a_set["is_default"]) ? $lng->txt("yes") : ""); - $this->tpl->parseCurrentBlock(); - - $prtf_path = array(get_class($this->parent_obj), "ilobjportfoliogui"); - - $ilCtrl->setParameterByClass("ilobjportfoliogui", "prt_id", $a_set["id"]); - $this->tpl->setCurrentBlock("action"); - - $this->tpl->setVariable("URL_ACTION", - $ilCtrl->getLinkTargetByClass($prtf_path, "preview")); - $this->tpl->setVariable("TXT_ACTION", $lng->txt("user_profile_preview")); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setVariable("URL_ACTION", - $ilCtrl->getLinkTargetByClass($prtf_path, "view")); - $this->tpl->setVariable("TXT_ACTION", $lng->txt("prtf_edit_portfolio")); - $this->tpl->parseCurrentBlock(); - - $ilCtrl->setParameterByClass("ilobjportfoliogui", "prt_id", ""); - - if($a_set["is_online"]) - { - if(!$a_set["is_default"]) - { - $ilCtrl->setParameter($this->parent_obj, "prt_id", $a_set["id"]); - - $this->tpl->setVariable("URL_ACTION", - $ilCtrl->getLinkTarget($this->parent_obj, "setDefaultConfirmation")); - $this->tpl->setVariable("TXT_ACTION", $lng->txt("prtf_set_as_default")); - $this->tpl->parseCurrentBlock(); - - $ilCtrl->setParameter($this->parent_obj, "prt_id", ""); - } - else - { - $this->tpl->setVariable("URL_ACTION", - $ilCtrl->getLinkTarget($this->parent_obj, "unsetDefault")); - $this->tpl->setVariable("TXT_ACTION", $lng->txt("prtf_unset_as_default")); - $this->tpl->parseCurrentBlock(); - } - } - } - -}?> + + * @version $Id$ + * + * @ingroup ModulesPortfolio + */ +class ilPortfolioTableGUI extends ilTable2GUI +{ + /** + * @var ilObjUser + */ + protected $user; + + protected $user_id; + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_user_id) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->user_id = (int) $a_user_id; + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setTitle($lng->txt("prtf_portfolios")); + + $this->addColumn($this->lng->txt(""), "", "1"); + $this->addColumn($this->lng->txt("title"), "title", "50%"); + $this->addColumn($this->lng->txt("online"), "is_online"); + $this->addColumn($this->lng->txt("prtf_default_portfolio"), "is_default"); + $this->addColumn($this->lng->txt("actions")); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.portfolio_row.html", "Modules/Portfolio"); + + $this->addMultiCommand("confirmPortfolioDeletion", $lng->txt("delete")); + $this->addCommandButton("saveTitles", $lng->txt("prtf_save_status_and_titles")); + + $this->getItems(); + + $lng->loadLanguageModule("wsp"); + + include_once('./Services/Link/classes/class.ilLink.php'); + } + + protected function getItems() + { + $ilUser = $this->user; + + include_once "Modules/Portfolio/classes/class.ilPortfolioAccessHandler.php"; + $access_handler = new ilPortfolioAccessHandler(); + + include_once "Modules/Portfolio/classes/class.ilObjPortfolio.php"; + $data = ilObjPortfolio::getPortfoliosOfUser($this->user_id); + + $this->shared_objects = $access_handler->getObjectsIShare(false); + + $this->setData($data); + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $this->tpl->setCurrentBlock("title_form"); + $this->tpl->setVariable("VAL_ID", $a_set["id"]); + $this->tpl->setVariable("VAL_TITLE", ilUtil::prepareFormOutput($a_set["title"])); + $this->tpl->parseCurrentBlock(); + + if (in_array($a_set["id"], $this->shared_objects)) { + $this->tpl->setCurrentBlock("shared"); + $this->tpl->setVariable("TXT_SHARED", $lng->txt("wsp_status_shared")); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setCurrentBlock("chck"); + $this->tpl->setVariable("VAL_ID", $a_set["id"]); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setCurrentBlock("edit"); + $this->tpl->setVariable("VAL_ID", $a_set["id"]); + $this->tpl->setVariable( + "STATUS_ONLINE", + ($a_set["is_online"]) ? " checked=\"checked\"" : "" + ); + $this->tpl->setVariable( + "VAL_DEFAULT", + ($a_set["is_default"]) ? $lng->txt("yes") : "" + ); + $this->tpl->parseCurrentBlock(); + + $prtf_path = array(get_class($this->parent_obj), "ilobjportfoliogui"); + + $ilCtrl->setParameterByClass("ilobjportfoliogui", "prt_id", $a_set["id"]); + $this->tpl->setCurrentBlock("action"); + + $this->tpl->setVariable( + "URL_ACTION", + $ilCtrl->getLinkTargetByClass($prtf_path, "preview") + ); + $this->tpl->setVariable("TXT_ACTION", $lng->txt("user_profile_preview")); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setVariable( + "URL_ACTION", + $ilCtrl->getLinkTargetByClass($prtf_path, "view") + ); + $this->tpl->setVariable("TXT_ACTION", $lng->txt("prtf_edit_portfolio")); + $this->tpl->parseCurrentBlock(); + + $ilCtrl->setParameterByClass("ilobjportfoliogui", "prt_id", ""); + + if ($a_set["is_online"]) { + if (!$a_set["is_default"]) { + $ilCtrl->setParameter($this->parent_obj, "prt_id", $a_set["id"]); + + $this->tpl->setVariable( + "URL_ACTION", + $ilCtrl->getLinkTarget($this->parent_obj, "setDefaultConfirmation") + ); + $this->tpl->setVariable("TXT_ACTION", $lng->txt("prtf_set_as_default")); + $this->tpl->parseCurrentBlock(); + + $ilCtrl->setParameter($this->parent_obj, "prt_id", ""); + } else { + $this->tpl->setVariable( + "URL_ACTION", + $ilCtrl->getLinkTarget($this->parent_obj, "unsetDefault") + ); + $this->tpl->setVariable("TXT_ACTION", $lng->txt("prtf_unset_as_default")); + $this->tpl->parseCurrentBlock(); + } + } + } +} diff --git a/Modules/Portfolio/classes/class.ilPortfolioTemplatePage.php b/Modules/Portfolio/classes/class.ilPortfolioTemplatePage.php index 56ecb910e3958d62921cdbdac2dd9e0f15c548b8..202d88ce270f0ad2def493ed60c0844e6908c45c 100644 --- a/Modules/Portfolio/classes/class.ilPortfolioTemplatePage.php +++ b/Modules/Portfolio/classes/class.ilPortfolioTemplatePage.php @@ -1,54 +1,50 @@ - - * @version $Id$ - * - * @ingroup ModulesPortfolio - */ -class ilPortfolioTemplatePage extends ilPortfolioPage -{ - const TYPE_BLOG_TEMPLATE = 3; - - /** - * Get parent type - * - * @return string parent type - */ - function getParentType() - { - return "prtt"; - } - - public function getPageDiskSize() - { - $quota_sum = 0; - - $this->buildDom(); - $dom = $this->getDom(); - if($dom instanceof php4DOMDocument) - { - $dom = $dom->myDOMDocument; - } - $xpath_temp = new DOMXPath($dom); - - // mobs - include_once "Services/MediaObjects/classes/class.ilObjMediaObject.php"; - $nodes = $xpath_temp->query("//PageContent/MediaObject/MediaAlias"); - foreach($nodes as $node) - { - $mob_id = array_pop(explode("_", $node->getAttribute("OriginId"))); - $mob_dir = ilObjMediaObject::_getDirectory($mob_id); - $quota_sum += ilUtil::dirSize($mob_dir); - } - - return $quota_sum; - } -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @ingroup ModulesPortfolio + */ +class ilPortfolioTemplatePage extends ilPortfolioPage +{ + const TYPE_BLOG_TEMPLATE = 3; + + /** + * Get parent type + * + * @return string parent type + */ + public function getParentType() + { + return "prtt"; + } + + public function getPageDiskSize() + { + $quota_sum = 0; + + $this->buildDom(); + $dom = $this->getDom(); + if ($dom instanceof php4DOMDocument) { + $dom = $dom->myDOMDocument; + } + $xpath_temp = new DOMXPath($dom); + + // mobs + include_once "Services/MediaObjects/classes/class.ilObjMediaObject.php"; + $nodes = $xpath_temp->query("//PageContent/MediaObject/MediaAlias"); + foreach ($nodes as $node) { + $mob_id = array_pop(explode("_", $node->getAttribute("OriginId"))); + $mob_dir = ilObjMediaObject::_getDirectory($mob_id); + $quota_sum += ilUtil::dirSize($mob_dir); + } + + return $quota_sum; + } +} diff --git a/Modules/Portfolio/classes/class.ilPortfolioTemplatePageConfig.php b/Modules/Portfolio/classes/class.ilPortfolioTemplatePageConfig.php index 5bbef14035b314e1255e659ccb6e7abfdf5b9cee..f1cdc9a8f36154524732b3ca2473bf45c7133a6e 100644 --- a/Modules/Portfolio/classes/class.ilPortfolioTemplatePageConfig.php +++ b/Modules/Portfolio/classes/class.ilPortfolioTemplatePageConfig.php @@ -1,49 +1,46 @@ - - * @version $Id$ - * @ingroup ModulesPortfolio - */ -class ilPortfolioTemplatePageConfig extends ilPortfolioPageConfig -{ - public function init() - { - global $DIC; - - $this->settings = $DIC->settings(); - parent::init(); - $this->setIntLinkHelpDefaultId($_GET["ref_id"]); - $this->addIntLinkFilter("PortfolioTemplatePage"); - $this->removeIntLinkFilter("PortfolioPage"); - $this->setIntLinkHelpDefaultType("PortfolioTemplatePage"); - - $this->setEnablePCType("Verification", false); - $this->setEnablePCType("PlaceHolder", true); - } - - public function getAvailablePlaceholderTypes() - { - $ilSetting = $this->settings; - - // no questions - $all = array( - ilPCPlaceHolderGUI::TYPE_TEXT, - ilPCPlaceHolderGUI::TYPE_MEDIA - ); - - if(!$ilSetting->get('disable_wsp_certificates')) - { - $all[] = ilPCPlaceHolderGUI::TYPE_VERIFICATION; - } - - return $all; - } -} - -?> \ No newline at end of file + + * @version $Id$ + * @ingroup ModulesPortfolio + */ +class ilPortfolioTemplatePageConfig extends ilPortfolioPageConfig +{ + public function init() + { + global $DIC; + + $this->settings = $DIC->settings(); + parent::init(); + $this->setIntLinkHelpDefaultId($_GET["ref_id"]); + $this->addIntLinkFilter("PortfolioTemplatePage"); + $this->removeIntLinkFilter("PortfolioPage"); + $this->setIntLinkHelpDefaultType("PortfolioTemplatePage"); + + $this->setEnablePCType("Verification", false); + $this->setEnablePCType("PlaceHolder", true); + } + + public function getAvailablePlaceholderTypes() + { + $ilSetting = $this->settings; + + // no questions + $all = array( + ilPCPlaceHolderGUI::TYPE_TEXT, + ilPCPlaceHolderGUI::TYPE_MEDIA + ); + + if (!$ilSetting->get('disable_wsp_certificates')) { + $all[] = ilPCPlaceHolderGUI::TYPE_VERIFICATION; + } + + return $all; + } +} diff --git a/Modules/Portfolio/classes/class.ilPortfolioTemplatePageGUI.php b/Modules/Portfolio/classes/class.ilPortfolioTemplatePageGUI.php index 37253f6a721f1e1056621cff8cbbd5c7321670d8..c1265ea55a678b25229db4cbab1ef42b0a4b829c 100644 --- a/Modules/Portfolio/classes/class.ilPortfolioTemplatePageGUI.php +++ b/Modules/Portfolio/classes/class.ilPortfolioTemplatePageGUI.php @@ -1,109 +1,102 @@ - - * @version $Id$ - * - * @ilCtrl_Calls ilPortfolioTemplatePageGUI: ilPageEditorGUI, ilEditClipboardGUI - * @ilCtrl_Calls ilPortfolioTemplatePageGUI: ilPageObjectGUI, ilMediaPoolTargetSelector - * @ilCtrl_Calls ilPortfolioTemplatePageGUI: ilCalendarMonthGUI, ilConsultationHoursGUI - * - * @ingroup ModulesPortfolio - */ -class ilPortfolioTemplatePageGUI extends ilPortfolioPageGUI -{ - function getParentType() - { - return "prtt"; - } - - protected function getPageContentUserId($a_user_id) - { - $ilUser = $this->user; - - // user - if(!$this->may_write) - { - return $ilUser->getId(); - } - // author - else - { - return $a_user_id; - } - } - - function showPage() - { - if(!$this->getPageObject()) - { - return; - } - - switch($this->getPageObject()->getType()) - { - case ilPortfolioTemplatePage::TYPE_BLOG_TEMPLATE: - return $this->renderPageElement("BlogTemplate", $this->renderBlogTemplate()); - - default: - - // needed for placeholders - include_once "Services/Style/Content/classes/class.ilObjStyleSheet.php"; - $this->tpl->addCss(ilObjStyleSheet::getPlaceHolderStylePath()); - - return parent::showPage(); - } - } - - protected function renderPageElement($a_type, $a_html) - { - return parent::renderPageElement($a_type, $this->addPlaceholderInfo($a_html)); - } - - protected function addPlaceholderInfo($a_html) - { - return '
'. - ''. - $this->lng->txt("prtf_template_editor_placeholder_info"). - ''. - trim($a_html). - '
'; - } - - protected function renderBlogTemplate() - { - return $this->renderTeaser("blog_template", $this->lng->txt("obj_blog")); - } - - /** - * Get view page link - * - * @param - * @return - */ - function getViewPageLink() - { - global $DIC; - - $ctrl = $DIC->ctrl(); - - $ctrl->setParameterByClass("ilobjportfoliotemplategui", "user_page", $_GET["ppage"]); - return $ctrl->getLinkTargetByClass("ilobjportfoliotemplategui", "preview"); - } - - /** - * @inheritdoc - */ - protected function getCourseSortAction($ctrl) - { - return $ctrl->getFormActionByClass("ilobjportfoliotemplategui", "preview"); - } - -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @ilCtrl_Calls ilPortfolioTemplatePageGUI: ilPageEditorGUI, ilEditClipboardGUI + * @ilCtrl_Calls ilPortfolioTemplatePageGUI: ilPageObjectGUI, ilMediaPoolTargetSelector + * @ilCtrl_Calls ilPortfolioTemplatePageGUI: ilCalendarMonthGUI, ilConsultationHoursGUI + * + * @ingroup ModulesPortfolio + */ +class ilPortfolioTemplatePageGUI extends ilPortfolioPageGUI +{ + public function getParentType() + { + return "prtt"; + } + + protected function getPageContentUserId($a_user_id) + { + $ilUser = $this->user; + + // user + if (!$this->may_write) { + return $ilUser->getId(); + } + // author + else { + return $a_user_id; + } + } + + public function showPage() + { + if (!$this->getPageObject()) { + return; + } + + switch ($this->getPageObject()->getType()) { + case ilPortfolioTemplatePage::TYPE_BLOG_TEMPLATE: + return $this->renderPageElement("BlogTemplate", $this->renderBlogTemplate()); + + default: + + // needed for placeholders + include_once "Services/Style/Content/classes/class.ilObjStyleSheet.php"; + $this->tpl->addCss(ilObjStyleSheet::getPlaceHolderStylePath()); + + return parent::showPage(); + } + } + + protected function renderPageElement($a_type, $a_html) + { + return parent::renderPageElement($a_type, $this->addPlaceholderInfo($a_html)); + } + + protected function addPlaceholderInfo($a_html) + { + return '
' . + '' . + $this->lng->txt("prtf_template_editor_placeholder_info") . + '' . + trim($a_html) . + '
'; + } + + protected function renderBlogTemplate() + { + return $this->renderTeaser("blog_template", $this->lng->txt("obj_blog")); + } + + /** + * Get view page link + * + * @param + * @return + */ + public function getViewPageLink() + { + global $DIC; + + $ctrl = $DIC->ctrl(); + + $ctrl->setParameterByClass("ilobjportfoliotemplategui", "user_page", $_GET["ppage"]); + return $ctrl->getLinkTargetByClass("ilobjportfoliotemplategui", "preview"); + } + + /** + * @inheritdoc + */ + protected function getCourseSortAction($ctrl) + { + return $ctrl->getFormActionByClass("ilobjportfoliotemplategui", "preview"); + } +} diff --git a/Modules/Portfolio/classes/class.ilPrtfGlobalScreenProvider.php b/Modules/Portfolio/classes/class.ilPrtfGlobalScreenProvider.php index a09193271b83b16b609c6183576003b3de98dc4a..c87272ff4c142b5498257f94b9b987a797babe20 100644 --- a/Modules/Portfolio/classes/class.ilPrtfGlobalScreenProvider.php +++ b/Modules/Portfolio/classes/class.ilPrtfGlobalScreenProvider.php @@ -8,64 +8,70 @@ use ILIAS\GlobalScreen\Scope\MainMenu\Provider\AbstractStaticMainMenuProvider; * * @author Fabian Schmid */ -class ilPrtfGlobalScreenProvider extends AbstractStaticMainMenuProvider { +class ilPrtfGlobalScreenProvider extends AbstractStaticMainMenuProvider +{ - /** - * @var IdentificationInterface - */ - protected $top_item; + /** + * @var IdentificationInterface + */ + protected $top_item; - public function __construct(\ILIAS\DI\Container $dic) { - parent::__construct($dic); - $this->top_item = (new ilPDGlobalScreenProvider($dic))->getTopItem(); - } + public function __construct(\ILIAS\DI\Container $dic) + { + parent::__construct($dic); + $this->top_item = (new ilPDGlobalScreenProvider($dic))->getTopItem(); + } - /** - * Some other components want to provide Items for the main menu which are - * located at the PD TopTitem by default. Therefore we have to provide our - * TopTitem Identification for others - * - * @return IdentificationInterface - */ - public function getTopItem(): IdentificationInterface { - return $this->top_item; - } + /** + * Some other components want to provide Items for the main menu which are + * located at the PD TopTitem by default. Therefore we have to provide our + * TopTitem Identification for others + * + * @return IdentificationInterface + */ + public function getTopItem() : IdentificationInterface + { + return $this->top_item; + } - /** - * @inheritDoc - */ - public function getStaticTopItems(): array { - return []; - } + /** + * @inheritDoc + */ + public function getStaticTopItems() : array + { + return []; + } - /** - * @inheritDoc - */ - public function getStaticSubItems(): array { - $dic = $this->dic; + /** + * @inheritDoc + */ + public function getStaticSubItems() : array + { + $dic = $this->dic; - return [$this->mainmenu->link($this->if->identifier('mm_pd_port')) - ->withTitle($this->dic->language()->txt("portfolio")) - ->withAction("ilias.php?baseClass=ilPersonalDesktopGUI&cmd=jumpToPortfolio") - ->withParent($this->getTopItem()) - ->withPosition(6) - ->withNonAvailableReason($this->dic->ui()->factory()->legacy("{$this->dic->language()->txt('component_not_active')}")) - ->withAvailableCallable( - function () use ($dic) { - return (bool)($dic->settings()->get('user_portfolios')); - } - )]; - } + return [$this->mainmenu->link($this->if->identifier('mm_pd_port')) + ->withTitle($this->dic->language()->txt("portfolio")) + ->withAction("ilias.php?baseClass=ilPersonalDesktopGUI&cmd=jumpToPortfolio") + ->withParent($this->getTopItem()) + ->withPosition(6) + ->withNonAvailableReason($this->dic->ui()->factory()->legacy("{$this->dic->language()->txt('component_not_active')}")) + ->withAvailableCallable( + function () use ($dic) { + return (bool) ($dic->settings()->get('user_portfolios')); + } + )]; + } - /** - * @inheritDoc - */ - public function getProviderNameForPresentation(): string { - return "Services/Portfolio"; - } + /** + * @inheritDoc + */ + public function getProviderNameForPresentation() : string + { + return "Services/Portfolio"; + } } diff --git a/Modules/RootFolder/classes/class.ilObjRootFolder.php b/Modules/RootFolder/classes/class.ilObjRootFolder.php index f4712746db72c8bcd47a45f83012ccb61fae54ba..fedbc6b34f940042077f35b779df1f65816b305e 100755 --- a/Modules/RootFolder/classes/class.ilObjRootFolder.php +++ b/Modules/RootFolder/classes/class.ilObjRootFolder.php @@ -1,24 +1,24 @@ type = "root"; - parent::__construct($a_id, $a_call_by_reference); - } - - - - /** - * delete rootfolder and all related data - * - * @access public - * @return boolean true if all object data were removed; false if only a references were removed - */ - function delete() - { - // delete is disabled - - $message = get_class($this)."::delete(): Can't delete root folder!"; - $this->ilias->raiseError($message,$this->ilias->error_obj->WARNING); - return false; - - // always call parent delete function first!! - if (!parent::delete()) - { - return false; - } - - // put here rootfolder specific stuff - - return true;; - } - - /** - * get all translations from this category - * - * @access public - * @return array - */ - function getTranslations() - { - global $ilDB; - - $q = "SELECT * FROM object_translation WHERE obj_id = ". - $ilDB->quote($this->getId(),'integer')." ORDER BY lang_default DESC"; - $r = $this->ilias->db->query($q); - - $num = 0; - - $data["Fobject"] = array(); - while ($row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - $data["Fobject"][$num]= array("title" => $row->title, - "desc" => $row->description, - "lang" => $row->lang_code - ); - $num++; - } - - // first entry is always the default language - $data["default_language"] = 0; - - return $data ? $data : array(); - } - - // remove translations of current category - function deleteTranslation($a_lang) - { - global $ilDB; - - $query = "DELETE FROM object_translation WHERE obj_id= ". - $ilDB->quote($this->getId(),'integer')." AND lang_code = ". - $ilDB->quote($a_lang, 'text'); - $res = $ilDB->manipulate($query); - } - - // remove all Translations of current category - function removeTranslations() - { - global $ilDB; - - $query = "DELETE FROM object_translation WHERE obj_id= ". - $ilDB->quote($this->getId(),'integer'); - $res = $ilDB->manipulate($query); - } - - // add a new translation to current category - function addTranslation($a_title,$a_desc,$a_lang,$a_lang_default) - { - global $ilDB; - - if (empty($a_title)) - { - $a_title = "NO TITLE"; - } - - $query = "INSERT INTO object_translation ". - "(obj_id,title,description,lang_code,lang_default) ". - "VALUES ". - "(".$ilDB->quote($this->getId(),'integer').",". - $ilDB->quote($a_title,'text').",". - $ilDB->quote($a_desc,'text').",". - $ilDB->quote($a_lang,'text').",". - $ilDB->quote($a_lang_default,'integer').")"; - $res = $ilDB->manipulate($query); - return true; - } - - function addAdditionalSubItemInformation(&$a_item_data) - { - include_once './Services/Object/classes/class.ilObjectActivation.php'; - ilObjectActivation::addAdditionalSubItemInformation($a_item_data); - } - + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id, $a_call_by_reference = true) + { + $this->type = "root"; + parent::__construct($a_id, $a_call_by_reference); + } + + + + /** + * delete rootfolder and all related data + * + * @access public + * @return boolean true if all object data were removed; false if only a references were removed + */ + public function delete() + { + // delete is disabled + + $message = get_class($this) . "::delete(): Can't delete root folder!"; + $this->ilias->raiseError($message, $this->ilias->error_obj->WARNING); + return false; + + // always call parent delete function first!! + if (!parent::delete()) { + return false; + } + + // put here rootfolder specific stuff + + return true; + ; + } + + /** + * get all translations from this category + * + * @access public + * @return array + */ + public function getTranslations() + { + global $ilDB; + + $q = "SELECT * FROM object_translation WHERE obj_id = " . + $ilDB->quote($this->getId(), 'integer') . " ORDER BY lang_default DESC"; + $r = $this->ilias->db->query($q); + + $num = 0; + + $data["Fobject"] = array(); + while ($row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + $data["Fobject"][$num]= array("title" => $row->title, + "desc" => $row->description, + "lang" => $row->lang_code + ); + $num++; + } + + // first entry is always the default language + $data["default_language"] = 0; + + return $data ? $data : array(); + } + + // remove translations of current category + public function deleteTranslation($a_lang) + { + global $ilDB; + + $query = "DELETE FROM object_translation WHERE obj_id= " . + $ilDB->quote($this->getId(), 'integer') . " AND lang_code = " . + $ilDB->quote($a_lang, 'text'); + $res = $ilDB->manipulate($query); + } + + // remove all Translations of current category + public function removeTranslations() + { + global $ilDB; + + $query = "DELETE FROM object_translation WHERE obj_id= " . + $ilDB->quote($this->getId(), 'integer'); + $res = $ilDB->manipulate($query); + } + + // add a new translation to current category + public function addTranslation($a_title, $a_desc, $a_lang, $a_lang_default) + { + global $ilDB; + + if (empty($a_title)) { + $a_title = "NO TITLE"; + } + + $query = "INSERT INTO object_translation " . + "(obj_id,title,description,lang_code,lang_default) " . + "VALUES " . + "(" . $ilDB->quote($this->getId(), 'integer') . "," . + $ilDB->quote($a_title, 'text') . "," . + $ilDB->quote($a_desc, 'text') . "," . + $ilDB->quote($a_lang, 'text') . "," . + $ilDB->quote($a_lang_default, 'integer') . ")"; + $res = $ilDB->manipulate($query); + return true; + } + + public function addAdditionalSubItemInformation(&$a_item_data) + { + include_once './Services/Object/classes/class.ilObjectActivation.php'; + ilObjectActivation::addAdditionalSubItemInformation($a_item_data); + } } // END class.ObjRootFolder -?> diff --git a/Modules/RootFolder/classes/class.ilObjRootFolderAccess.php b/Modules/RootFolder/classes/class.ilObjRootFolderAccess.php index 19748a9a671fdad8b04c846cb4bc8fbe9aaeff6f..bcc8a1283a6a3f99f0c5e80786508eb5c3feac60 100644 --- a/Modules/RootFolder/classes/class.ilObjRootFolderAccess.php +++ b/Modules/RootFolder/classes/class.ilObjRootFolderAccess.php @@ -1,24 +1,24 @@ "read", "cmd" => "view", "lang_var" => "show"), - * array("permission" => "write", "cmd" => "edit", "lang_var" => "edit"), - * ); - */ - static function _getCommands() - { - $commands = array - ( - array("permission" => "read", "cmd" => "render", "lang_var" => "show", - "default" => true), - array("permission" => "write", "cmd" => "edit", "lang_var" => "edit"), - ); - - return $commands; - } - + /** + * 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" => "render", "lang_var" => "show", + "default" => true), + array("permission" => "write", "cmd" => "edit", "lang_var" => "edit"), + ); + + return $commands; + } } - -?> diff --git a/Modules/RootFolder/classes/class.ilObjRootFolderGUI.php b/Modules/RootFolder/classes/class.ilObjRootFolderGUI.php index 549055bac3542648742cfc2dcb72bb936b6b47cc..6fb681bdcb12ccf8cda20eb7511fa6f7193e2c2f 100755 --- a/Modules/RootFolder/classes/class.ilObjRootFolderGUI.php +++ b/Modules/RootFolder/classes/class.ilObjRootFolderGUI.php @@ -9,10 +9,10 @@ * @author Stefan Meyer * @version $Id$Id: class.ilObjRootFolderGUI.php,v 1.13 2006/03/10 09:22:58 akill Exp $ * -* @ilCtrl_Calls ilObjRootFolderGUI: ilPermissionGUI, ilContainerPageGUI, ilContainerLinkListGUI, +* @ilCtrl_Calls ilObjRootFolderGUI: ilPermissionGUI, ilContainerPageGUI, ilContainerLinkListGUI, * @ilCtrl_Calls ilObjRootFolderGUI: ilColumnGUI, ilObjectCopyGUI, ilObjStyleSheetGUI * @ilCtrl_Calls ilObjRootFolderGUI: ilCommonActionDispatcherGUI, ilObjectTranslationGUI -* +* * @extends ilObjectGUI */ @@ -21,547 +21,528 @@ require_once "./Modules/Category/classes/class.ilObjCategoryGUI.php"; class ilObjRootFolderGUI extends ilContainerGUI { - /** - * Constructor - * @access public - */ - public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) - { - global $lng; - - $this->type = "root"; - parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); - - $lng->loadLanguageModule("cntr"); - $lng->loadLanguageModule("obj"); - } - - /** - * import categories form - */ - function importCategoriesFormObject () - { - ilObjCategoryGUI::_importCategoriesForm($this->ref_id, $this->tpl); - } - - /** - * import cancelled - * - * @access private - */ - function importCancelledObject() - { - $this->ctrl->returnToParent($this); - } - - /** - * import categories - */ - function importCategoriesObject() - { - ilObjCategoryGUI::_importCategories($this->ref_id,0); - } - - - /** - * import categories - */ - function importCategoriesWithRolObject() - { - ilObjCategoryGUI::_importCategories($this->ref_id,1); - } - - - function getTabs() - { - global $rbacsystem, $lng, $ilHelp; - - $ilHelp->setScreenIdComponent("root"); - - $this->ctrl->setParameter($this,"ref_id",$this->ref_id); - - if ($rbacsystem->checkAccess('read',$this->ref_id)) - { - $this->tabs_gui->addTab('view_content', $lng->txt("content"), - $this->ctrl->getLinkTarget($this, "")); - } - - if ($rbacsystem->checkAccess('write',$this->ref_id)) - { - $force_active = ($_GET["cmd"] == "edit") - ? true - : false; - $this->tabs_gui->addTarget("settings", - $this->ctrl->getLinkTarget($this, "edit"), "edit", get_class($this) - , "", $force_active); - } - - // parent tabs (all container: edit_permission, clipboard, trash - parent::getTabs(); - - } - - function executeCommand() - { - global $rbacsystem; - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - // show repository tree - $this->showRepTree(); - - switch($next_class) - { - case 'ilcontainerlinklistgui': - include_once("Services/Container/classes/class.ilContainerLinkListGUI.php"); - $link_list_gui = new ilContainerLinkListGUI(); - $ret =& $this->ctrl->forwardCommand($link_list_gui); - break; - - // container page editing - case "ilcontainerpagegui": - $this->prepareOutput(false); - $ret = $this->forwardToPageObject(); - if ($ret != "") - { - $this->tpl->setContent($ret); - } - break; - - case 'ilpermissiongui': - $this->prepareOutput(); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $ret =& $this->ctrl->forwardCommand($perm_gui); - break; - - case "ilcolumngui": - $this->checkPermission("read"); - $this->prepareOutput(); - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->object->getStyleSheetId())); - $this->renderObject(); - break; - - case 'ilobjectcopygui': - $this->prepareOutput(); - include_once './Services/Object/classes/class.ilObjectCopyGUI.php'; - $cp = new ilObjectCopyGUI($this); - $cp->setType('root'); - $this->ctrl->forwardCommand($cp); - break; - - case "ilobjstylesheetgui": - $this->forwardToStyleSheet(); - break; - - case "ilcommonactiondispatchergui": - include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); - $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); - $this->ctrl->forwardCommand($gui); - break; - - case 'ilobjecttranslationgui': - $this->checkPermissionBool("write"); - $this->prepareOutput(); - //$this->tabs_gui->setTabActive('export'); - $this->setEditTabs("settings_trans"); - include_once("./Services/Object/classes/class.ilObjectTranslationGUI.php"); - $transgui = new ilObjectTranslationGUI($this); - $this->ctrl->forwardCommand($transgui); - break; - - default: - - // fix bug http://www.ilias.de/mantis/view.php?id=10305 - if ($cmd == "infoScreen") - { - $this->checkPermission("visible"); - } - else - { - $this->checkPermission("read"); - } - $this->prepareOutput(); - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->object->getStyleSheetId())); - - if(!$cmd) - { - $cmd = "render"; - } - - $cmd .= "Object"; - $this->$cmd(); - - break; - } - return true; - } - - /** - * Render root folder - */ - function renderObject() - { - global $ilTabs; - - include_once "Services/Object/classes/class.ilObjectListGUI.php"; - ilObjectListGUI::prepareJSLinks("", - $this->ctrl->getLinkTargetByClass(array("ilcommonactiondispatchergui", "ilnotegui"), "", "", true, false), - $this->ctrl->getLinkTargetByClass(array("ilcommonactiondispatchergui", "iltagginggui"), "", "", true, false)); - - $ilTabs->activateTab("view_content"); - $ret = parent::renderObject(); - return $ret; - } - - /** - * View root folder - * @return bool|void - * @throws ilObjectException - */ - function viewObject() - { - $this->checkPermission('read'); - - if (strtolower($_GET["baseClass"]) == "iladministrationgui") - { - parent::viewObject(); - return true; - } - - $this->renderObject(); - return true; - } - - - - /** - * called by prepare output - */ - function setTitleAndDescription() - { - global $lng; - - parent::setTitleAndDescription(); - $this->tpl->setDescription(""); - if (!ilContainer::_lookupContainerSetting($this->object->getId(), "hide_header_icon_and_title")) - { - if ($this->object->getTitle() == "ILIAS") - { - $this->tpl->setTitle($lng->txt("repository")); - } - else - { - if ($this->object->getDescription() != "") - { - $this->tpl->setDescription($this->object->getDescription()); // #13479 - } - } - } - } - - protected function setEditTabs($active_tab = "settings_misc") - { - $this->tabs_gui->addSubTab("settings_misc", - $this->lng->txt("settings"), - $this->ctrl->getLinkTarget($this, "edit")); - - /*$this->tabs_gui->addSubTab("settings_trans", - $this->lng->txt("title_and_translations"), - $this->ctrl->getLinkTarget($this, "editTranslations"));*/ - - $this->tabs_gui->addSubTab("settings_trans", - $this->lng->txt("obj_multilinguality"), - $this->ctrl->getLinkTargetByClass("ilobjecttranslationgui", "")); - - - $this->tabs_gui->activateTab("settings"); - $this->tabs_gui->activateSubTab($active_tab); - } - - function initEditForm() - { - $this->setEditTabs(); - $obj_service = $this->getObjectService(); - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - $form->setTitle($this->lng->txt("repository")); - - // presentation - $pres = new ilFormSectionHeaderGUI(); - $pres->setTitle($this->lng->txt('obj_presentation')); - $form->addItem($pres); - - // list presentation - $form = $this->initListPresentationForm($form); - - $this->initSortingForm( - $form, - array( - ilContainer::SORT_TITLE, - ilContainer::SORT_CREATION, - ilcontainer::SORT_MANUAL - ) - ); - - - $this->showCustomIconsEditing(1, $form, false); - - $form = $obj_service->commonSettings()->legacyForm($form, $this->object)->addTitleIconVisibility(); - - //$hide = new ilCheckboxInputGUI($this->lng->txt("cntr_hide_title_and_icon"), "hide_header_icon_and_title"); - //$hide->setChecked(ilContainer::_lookupContainerSetting($this->object->getId(), "hide_header_icon_and_title")); - //$form->addItem($hide); - - - $form->addCommandButton("update", $this->lng->txt("save")); - $form->addCommandButton("addTranslation", $this->lng->txt("add_translation")); - - return $form; - } - - function getEditFormValues() - { - // values are set in initEditForm() - } - - /** - * updates object entry in object_data - * - * @access public - */ - function updateObject() - { - global $ilSetting; - - $obj_service = $this->getObjectService(); - - if (!$this->checkPermissionBool("write")) - { - $this->ilias->raiseError($this->lng->txt("msg_no_perm_write"),$this->ilias->error_obj->MESSAGE); - } - else - { - $form = $this->initEditForm(); - if($form->checkInput()) - { - $this->saveSortingSettings($form); - - // list presentation - $this->saveListPresentation($form); - - if ($ilSetting->get('custom_icons')) { - global $DIC; - /** @var \ilObjectCustomIconFactory $customIconFactory */ - $customIconFactory = $DIC['object.customicons.factory']; - $customIcon = $customIconFactory->getByObjId($this->object->getId(), $this->object->getType()); - - /** @var \ilImageFileInputGUI $item */ - $fileData = (array)$form->getInput('cont_icon'); - $item = $form->getItemByPostVar('cont_icon'); - - if ($item->getDeletionFlag()) { - $customIcon->remove(); - } - - if ($fileData['tmp_name']) { - $customIcon->saveFromHttpRequest(); - } - // cognos-blu-patch: end - } - - // custom icon - $obj_service->commonSettings()->legacyForm($form, $this->object)->saveTitleIconVisibility(); - - // hide icon/title - //ilContainer::_writeContainerSetting($this->object->getId(), - // "hide_header_icon_and_title", - // $form->getInput("hide_header_icon_and_title")); - - // BEGIN ChangeEvent: Record update - global $ilUser; - require_once('Services/Tracking/classes/class.ilChangeEvent.php'); - ilChangeEvent::_recordWriteEvent($this->object->getId(), $ilUser->getId(), 'update'); - ilChangeEvent::_catchupWriteEvents($this->object->getId(), $ilUser->getId()); - // END ChangeEvent: Record update - - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"),true); - $this->ctrl->redirect($this, "edit"); - } - - // display form to correct errors - $this->setEditTabs(); - $form->setValuesByPost(); - $this->tpl->setContent($form->getHTML()); - } - } - - /** - * Edit title and translations - */ - function editTranslationsObject($a_get_post_values = false) - { - global $tpl; - - - $this->ctrl->redirectByClass("ilobjecttranslationgui", ""); - - $this->lng->loadLanguageModule($this->object->getType()); - $this->setEditTabs("settings_trans"); - - include_once("./Services/Object/classes/class.ilObjectTranslationTableGUI.php"); - $table = new ilObjectTranslationTableGUI($this, "editTranslations", true, - "Translation"); - 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->getTranslations(); - foreach($data["Fobject"] as $k => $v) - { - $data["Fobject"][$k]["default"] = ($k == $data["default_language"]); - } - $table->setData($data["Fobject"]); - } - $tpl->setContent($table->getHTML()); - } - - /** - * Save title and translations - */ - function saveTranslationsObject() - { - if (!$this->checkPermissionBool("write")) - { - $this->ilias->raiseError($this->lng->txt("permission_denied"),$this->ilias->error_obj->MESSAGE); - } - - // default language set? - if (!isset($_POST["default"]) && count($_POST["lang"]) > 0) - { - ilUtil::sendFailure($this->lng->txt("msg_no_default_language")); - return $this->editTranslationsObject(true); - } - - // all languages set? - if (array_key_exists("",$_POST["lang"])) - { - ilUtil::sendFailure($this->lng->txt("msg_no_language_selected")); - return $this->editTranslationsObject(true); - } - - // no single language is selected more than once? - if (count(array_unique($_POST["lang"])) < count($_POST["lang"])) - { - ilUtil::sendFailure($this->lng->txt("msg_multi_language_selected")); - return $this->editTranslationsObject(true); - } - - // save the stuff - $this->object->removeTranslations(); - - if(sizeof($_POST["title"])) - { - foreach($_POST["title"] as $k => $v) - { - // update object data if default - $is_default = ($_POST["default"] == $k); - if($is_default) - { - $this->object->setTitle(ilUtil::stripSlashes($v)); - $this->object->setDescription(ilUtil::stripSlashes($_POST["desc"][$k])); - $this->object->update(); - } - - $this->object->addTranslation( - ilUtil::stripSlashes($v), - ilUtil::stripSlashes($_POST["desc"][$k]), - ilUtil::stripSlashes($_POST["lang"][$k]), - $is_default); - } - } - else - { - // revert to original title - $this->object->setTitle("ILIAS"); - $this->object->setDescription(""); - $this->object->update(); - } - - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "editTranslations"); - } - - /** - * Add a translation - */ - function addTranslationObject() - { - if(sizeof($_POST["title"])) - { - $k = max(array_keys($_POST["title"]))+1; - } - else - { - $k = 0; - } - $_POST["title"][$k] = ""; - $this->editTranslationsObject(true); - } - - /** - * Remove translation - */ - function deleteTranslationsObject() - { - $del_default = true; - foreach($_POST["title"] as $k => $v) - { - if ($_POST["check"][$k]) - { - unset($_POST["title"][$k]); - unset($_POST["desc"][$k]); - unset($_POST["lang"][$k]); - if($_POST["default"] == $k) - { - $del_default = true; - } - } - } - // set new default - if($del_default && sizeof($_POST["title"])) - { - $_POST["default"] = array_shift(array_keys($_POST["title"])); - } - $this->saveTranslationsObject(); - } - - /** - * goto target group - */ - public static function _goto($a_target) - { - global $ilAccess, $ilErr, $lng; - - ilObjectGUI::_gotoRepositoryRoot(true); - } - + /** + * Constructor + * @access public + */ + public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) + { + global $lng; + + $this->type = "root"; + parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); + + $lng->loadLanguageModule("cntr"); + $lng->loadLanguageModule("obj"); + } + + /** + * import categories form + */ + public function importCategoriesFormObject() + { + ilObjCategoryGUI::_importCategoriesForm($this->ref_id, $this->tpl); + } + + /** + * import cancelled + * + * @access private + */ + public function importCancelledObject() + { + $this->ctrl->returnToParent($this); + } + + /** + * import categories + */ + public function importCategoriesObject() + { + ilObjCategoryGUI::_importCategories($this->ref_id, 0); + } + + + /** + * import categories + */ + public function importCategoriesWithRolObject() + { + ilObjCategoryGUI::_importCategories($this->ref_id, 1); + } + + + public function getTabs() + { + global $rbacsystem, $lng, $ilHelp; + + $ilHelp->setScreenIdComponent("root"); + + $this->ctrl->setParameter($this, "ref_id", $this->ref_id); + + if ($rbacsystem->checkAccess('read', $this->ref_id)) { + $this->tabs_gui->addTab( + 'view_content', + $lng->txt("content"), + $this->ctrl->getLinkTarget($this, "") + ); + } + + if ($rbacsystem->checkAccess('write', $this->ref_id)) { + $force_active = ($_GET["cmd"] == "edit") + ? true + : false; + $this->tabs_gui->addTarget( + "settings", + $this->ctrl->getLinkTarget($this, "edit"), + "edit", + get_class($this), + "", + $force_active + ); + } + + // parent tabs (all container: edit_permission, clipboard, trash + parent::getTabs(); + } + + public function executeCommand() + { + global $rbacsystem; + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + // show repository tree + $this->showRepTree(); + + switch ($next_class) { + case 'ilcontainerlinklistgui': + include_once("Services/Container/classes/class.ilContainerLinkListGUI.php"); + $link_list_gui = new ilContainerLinkListGUI(); + $ret =&$this->ctrl->forwardCommand($link_list_gui); + break; + + // container page editing + case "ilcontainerpagegui": + $this->prepareOutput(false); + $ret = $this->forwardToPageObject(); + if ($ret != "") { + $this->tpl->setContent($ret); + } + break; + + case 'ilpermissiongui': + $this->prepareOutput(); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $ret =&$this->ctrl->forwardCommand($perm_gui); + break; + + case "ilcolumngui": + $this->checkPermission("read"); + $this->prepareOutput(); + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $this->tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath($this->object->getStyleSheetId()) + ); + $this->renderObject(); + break; + + case 'ilobjectcopygui': + $this->prepareOutput(); + include_once './Services/Object/classes/class.ilObjectCopyGUI.php'; + $cp = new ilObjectCopyGUI($this); + $cp->setType('root'); + $this->ctrl->forwardCommand($cp); + break; + + case "ilobjstylesheetgui": + $this->forwardToStyleSheet(); + break; + + case "ilcommonactiondispatchergui": + include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); + $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); + $this->ctrl->forwardCommand($gui); + break; + + case 'ilobjecttranslationgui': + $this->checkPermissionBool("write"); + $this->prepareOutput(); + //$this->tabs_gui->setTabActive('export'); + $this->setEditTabs("settings_trans"); + include_once("./Services/Object/classes/class.ilObjectTranslationGUI.php"); + $transgui = new ilObjectTranslationGUI($this); + $this->ctrl->forwardCommand($transgui); + break; + + default: + + // fix bug http://www.ilias.de/mantis/view.php?id=10305 + if ($cmd == "infoScreen") { + $this->checkPermission("visible"); + } else { + $this->checkPermission("read"); + } + $this->prepareOutput(); + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $this->tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath($this->object->getStyleSheetId()) + ); + + if (!$cmd) { + $cmd = "render"; + } + + $cmd .= "Object"; + $this->$cmd(); + + break; + } + return true; + } + + /** + * Render root folder + */ + public function renderObject() + { + global $ilTabs; + + include_once "Services/Object/classes/class.ilObjectListGUI.php"; + ilObjectListGUI::prepareJSLinks( + "", + $this->ctrl->getLinkTargetByClass(array("ilcommonactiondispatchergui", "ilnotegui"), "", "", true, false), + $this->ctrl->getLinkTargetByClass(array("ilcommonactiondispatchergui", "iltagginggui"), "", "", true, false) + ); + + $ilTabs->activateTab("view_content"); + $ret = parent::renderObject(); + return $ret; + } + + /** + * View root folder + * @return bool|void + * @throws ilObjectException + */ + public function viewObject() + { + $this->checkPermission('read'); + + if (strtolower($_GET["baseClass"]) == "iladministrationgui") { + parent::viewObject(); + return true; + } + + $this->renderObject(); + return true; + } + + + + /** + * called by prepare output + */ + public function setTitleAndDescription() + { + global $lng; + + parent::setTitleAndDescription(); + $this->tpl->setDescription(""); + if (!ilContainer::_lookupContainerSetting($this->object->getId(), "hide_header_icon_and_title")) { + if ($this->object->getTitle() == "ILIAS") { + $this->tpl->setTitle($lng->txt("repository")); + } else { + if ($this->object->getDescription() != "") { + $this->tpl->setDescription($this->object->getDescription()); // #13479 + } + } + } + } + + protected function setEditTabs($active_tab = "settings_misc") + { + $this->tabs_gui->addSubTab( + "settings_misc", + $this->lng->txt("settings"), + $this->ctrl->getLinkTarget($this, "edit") + ); + + /*$this->tabs_gui->addSubTab("settings_trans", + $this->lng->txt("title_and_translations"), + $this->ctrl->getLinkTarget($this, "editTranslations"));*/ + + $this->tabs_gui->addSubTab( + "settings_trans", + $this->lng->txt("obj_multilinguality"), + $this->ctrl->getLinkTargetByClass("ilobjecttranslationgui", "") + ); + + + $this->tabs_gui->activateTab("settings"); + $this->tabs_gui->activateSubTab($active_tab); + } + + public function initEditForm() + { + $this->setEditTabs(); + $obj_service = $this->getObjectService(); + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this)); + $form->setTitle($this->lng->txt("repository")); + + // presentation + $pres = new ilFormSectionHeaderGUI(); + $pres->setTitle($this->lng->txt('obj_presentation')); + $form->addItem($pres); + + // list presentation + $form = $this->initListPresentationForm($form); + + $this->initSortingForm( + $form, + array( + ilContainer::SORT_TITLE, + ilContainer::SORT_CREATION, + ilcontainer::SORT_MANUAL + ) + ); + + + $this->showCustomIconsEditing(1, $form, false); + + $form = $obj_service->commonSettings()->legacyForm($form, $this->object)->addTitleIconVisibility(); + + //$hide = new ilCheckboxInputGUI($this->lng->txt("cntr_hide_title_and_icon"), "hide_header_icon_and_title"); + //$hide->setChecked(ilContainer::_lookupContainerSetting($this->object->getId(), "hide_header_icon_and_title")); + //$form->addItem($hide); + + + $form->addCommandButton("update", $this->lng->txt("save")); + $form->addCommandButton("addTranslation", $this->lng->txt("add_translation")); + + return $form; + } + + public function getEditFormValues() + { + // values are set in initEditForm() + } + + /** + * updates object entry in object_data + * + * @access public + */ + public function updateObject() + { + global $ilSetting; + + $obj_service = $this->getObjectService(); + + if (!$this->checkPermissionBool("write")) { + $this->ilias->raiseError($this->lng->txt("msg_no_perm_write"), $this->ilias->error_obj->MESSAGE); + } else { + $form = $this->initEditForm(); + if ($form->checkInput()) { + $this->saveSortingSettings($form); + + // list presentation + $this->saveListPresentation($form); + + if ($ilSetting->get('custom_icons')) { + global $DIC; + /** @var \ilObjectCustomIconFactory $customIconFactory */ + $customIconFactory = $DIC['object.customicons.factory']; + $customIcon = $customIconFactory->getByObjId($this->object->getId(), $this->object->getType()); + + /** @var \ilImageFileInputGUI $item */ + $fileData = (array) $form->getInput('cont_icon'); + $item = $form->getItemByPostVar('cont_icon'); + + if ($item->getDeletionFlag()) { + $customIcon->remove(); + } + + if ($fileData['tmp_name']) { + $customIcon->saveFromHttpRequest(); + } + // cognos-blu-patch: end + } + + // custom icon + $obj_service->commonSettings()->legacyForm($form, $this->object)->saveTitleIconVisibility(); + + // hide icon/title + //ilContainer::_writeContainerSetting($this->object->getId(), + // "hide_header_icon_and_title", + // $form->getInput("hide_header_icon_and_title")); + + // BEGIN ChangeEvent: Record update + global $ilUser; + require_once('Services/Tracking/classes/class.ilChangeEvent.php'); + ilChangeEvent::_recordWriteEvent($this->object->getId(), $ilUser->getId(), 'update'); + ilChangeEvent::_catchupWriteEvents($this->object->getId(), $ilUser->getId()); + // END ChangeEvent: Record update + + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "edit"); + } + + // display form to correct errors + $this->setEditTabs(); + $form->setValuesByPost(); + $this->tpl->setContent($form->getHTML()); + } + } + + /** + * Edit title and translations + */ + public function editTranslationsObject($a_get_post_values = false) + { + global $tpl; + + + $this->ctrl->redirectByClass("ilobjecttranslationgui", ""); + + $this->lng->loadLanguageModule($this->object->getType()); + $this->setEditTabs("settings_trans"); + + include_once("./Services/Object/classes/class.ilObjectTranslationTableGUI.php"); + $table = new ilObjectTranslationTableGUI( + $this, + "editTranslations", + true, + "Translation" + ); + 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->getTranslations(); + foreach ($data["Fobject"] as $k => $v) { + $data["Fobject"][$k]["default"] = ($k == $data["default_language"]); + } + $table->setData($data["Fobject"]); + } + $tpl->setContent($table->getHTML()); + } + + /** + * Save title and translations + */ + public function saveTranslationsObject() + { + if (!$this->checkPermissionBool("write")) { + $this->ilias->raiseError($this->lng->txt("permission_denied"), $this->ilias->error_obj->MESSAGE); + } + + // default language set? + if (!isset($_POST["default"]) && count($_POST["lang"]) > 0) { + ilUtil::sendFailure($this->lng->txt("msg_no_default_language")); + return $this->editTranslationsObject(true); + } + + // all languages set? + if (array_key_exists("", $_POST["lang"])) { + ilUtil::sendFailure($this->lng->txt("msg_no_language_selected")); + return $this->editTranslationsObject(true); + } + + // no single language is selected more than once? + if (count(array_unique($_POST["lang"])) < count($_POST["lang"])) { + ilUtil::sendFailure($this->lng->txt("msg_multi_language_selected")); + return $this->editTranslationsObject(true); + } + + // save the stuff + $this->object->removeTranslations(); + + if (sizeof($_POST["title"])) { + foreach ($_POST["title"] as $k => $v) { + // update object data if default + $is_default = ($_POST["default"] == $k); + if ($is_default) { + $this->object->setTitle(ilUtil::stripSlashes($v)); + $this->object->setDescription(ilUtil::stripSlashes($_POST["desc"][$k])); + $this->object->update(); + } + + $this->object->addTranslation( + ilUtil::stripSlashes($v), + ilUtil::stripSlashes($_POST["desc"][$k]), + ilUtil::stripSlashes($_POST["lang"][$k]), + $is_default + ); + } + } else { + // revert to original title + $this->object->setTitle("ILIAS"); + $this->object->setDescription(""); + $this->object->update(); + } + + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "editTranslations"); + } + + /** + * Add a translation + */ + public function addTranslationObject() + { + if (sizeof($_POST["title"])) { + $k = max(array_keys($_POST["title"]))+1; + } else { + $k = 0; + } + $_POST["title"][$k] = ""; + $this->editTranslationsObject(true); + } + + /** + * Remove translation + */ + public function deleteTranslationsObject() + { + $del_default = true; + foreach ($_POST["title"] as $k => $v) { + if ($_POST["check"][$k]) { + unset($_POST["title"][$k]); + unset($_POST["desc"][$k]); + unset($_POST["lang"][$k]); + if ($_POST["default"] == $k) { + $del_default = true; + } + } + } + // set new default + if ($del_default && sizeof($_POST["title"])) { + $_POST["default"] = array_shift(array_keys($_POST["title"])); + } + $this->saveTranslationsObject(); + } + + /** + * goto target group + */ + public static function _goto($a_target) + { + global $ilAccess, $ilErr, $lng; + + ilObjectGUI::_gotoRepositoryRoot(true); + } } -?> diff --git a/Modules/RootFolder/classes/class.ilObjRootFolderListGUI.php b/Modules/RootFolder/classes/class.ilObjRootFolderListGUI.php index 74e8274d24e9a9e70582f2a296829d3dec373917..a14aa85caaac9f12537c44f63feafb8ef9ff0a69 100755 --- a/Modules/RootFolder/classes/class.ilObjRootFolderListGUI.php +++ b/Modules/RootFolder/classes/class.ilObjRootFolderListGUI.php @@ -1,24 +1,24 @@ copy_enabled = false; - $this->delete_enabled = true; - $this->cut_enabled = true; - $this->subscribe_enabled = true; - $this->link_enabled = false; - $this->type = "root"; - $this->gui_class_name = "ilobjrootfoldergui"; + /** + * initialisation + */ + public function init() + { + $this->copy_enabled = false; + $this->delete_enabled = true; + $this->cut_enabled = true; + $this->subscribe_enabled = true; + $this->link_enabled = false; + $this->type = "root"; + $this->gui_class_name = "ilobjrootfoldergui"; - // general commands array - include_once('./Modules/RootFolder/classes/class.ilObjRootFolderAccess.php'); - $this->commands = ilObjRootFolderAccess::_getCommands(); - } + // general commands array + include_once('./Modules/RootFolder/classes/class.ilObjRootFolderAccess.php'); + $this->commands = ilObjRootFolderAccess::_getCommands(); + } - /** - * Get command link url. - * - * @param int $a_ref_id reference id - * @param string $a_cmd command - * - */ - function getCommandLink($a_cmd) - { - global $ilCtrl; - - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $this->ref_id); - $cmd_link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", $a_cmd); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - - return $cmd_link; - } + /** + * Get command link url. + * + * @param int $a_ref_id reference id + * @param string $a_cmd command + * + */ + public function getCommandLink($a_cmd) + { + global $ilCtrl; + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $this->ref_id); + $cmd_link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", $a_cmd); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + return $cmd_link; + } } // END class.ilObjRootFolderGUI -?> diff --git a/Modules/Survey/classes/class.SurveySearch.php b/Modules/Survey/classes/class.SurveySearch.php index 35f8d71a99092882a4dbfe72a1281389708a75b0..c9f5160dc4f2598fcb1d46ccc5ddd2f9e49111d0 100755 --- a/Modules/Survey/classes/class.SurveySearch.php +++ b/Modules/Survey/classes/class.SurveySearch.php @@ -31,172 +31,158 @@ * @version $Id$ * @ingroup ModulesSurvey */ -class SurveySearch +class SurveySearch { - /** - * @var ilRbacSystem - */ - protected $rbacsystem; + /** + * @var ilRbacSystem + */ + protected $rbacsystem; - const CONCAT_AND = 0; - const CONCAT_OR = 1; - - /** - * Search terms - * - * An array containing all search terms - * - * @var array - */ - var $search_terms; + const CONCAT_AND = 0; + const CONCAT_OR = 1; + + /** + * Search terms + * + * An array containing all search terms + * + * @var array + */ + public $search_terms; - /** - * Concatenation - * - * The concatenation type of the search terms - * - * @var integer - */ - var $concatenation; + /** + * Concatenation + * + * The concatenation type of the search terms + * + * @var integer + */ + public $concatenation; - /** - * Search field - * - * A database field to restrict the search results - * - * @var string - */ - var $search_field; + /** + * Search field + * + * A database field to restrict the search results + * + * @var string + */ + public $search_field; - /** - * Search type - * - * A question type to restrict the search results - * - * @var string - */ - var $search_type; + /** + * Search type + * + * A question type to restrict the search results + * + * @var string + */ + public $search_type; - /** - * Search results - * - * An array containing the results of a search - * - * @var array - */ - var $search_results; + /** + * Search results + * + * An array containing the results of a search + * + * @var array + */ + public $search_results; - /** - * The reference to the ILIAS database class - * - * The reference to the ILIAS database class - * - * @var object - */ - var $ilDB; + /** + * The reference to the ILIAS database class + * + * The reference to the ILIAS database class + * + * @var object + */ + public $ilDB; - /** - * SurveySearch constructor - * - * The constructor takes possible arguments an creates an instance of the SurveySearch 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($search_text = "", $concatenation = self::CONCAT_AND, $search_field = "all", $search_type = "all") - { - global $DIC; + /** + * SurveySearch constructor + * + * The constructor takes possible arguments an creates an instance of the SurveySearch 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($search_text = "", $concatenation = self::CONCAT_AND, $search_field = "all", $search_type = "all") + { + global $DIC; - $this->rbacsystem = $DIC->rbac()->system(); - $ilDB = $DIC->database(); + $this->rbacsystem = $DIC->rbac()->system(); + $ilDB = $DIC->database(); - $this->ilDB = $ilDB; + $this->ilDB = $ilDB; - $this->search_terms = explode(" +", $search_text); - $this->concatenation = $concatenation; - $this->search_field = $search_field; - $this->search_type = $search_type; - $this->search_results = array(); - } - - /** - * Executes a search - * - * Executes a search - * - * @access public - */ - function search() - { - $ilDB = $this->ilDB; - - $where = ""; - $fields = array(); - if (strcmp($this->search_type, "all") != 0) - { - $where = "svy_qtype.type_tag = " . $ilDB->quote($this->search_type, 'text'); - } - foreach ($this->search_terms as $term) - { - switch ($this->search_field) - { - case "all": - $fields["$term"] = array(); - array_push($fields["$term"], $ilDB->like("svy_question.title", 'text', "%" .$term . "%")); - array_push($fields["$term"], $ilDB->like("svy_question.description", 'text', "%" .$term . "%")); - array_push($fields["$term"], $ilDB->like("svy_question.author", 'text', "%" .$term . "%")); - array_push($fields["$term"], $ilDB->like("svy_question.questiontext", 'text', "%" .$term . "%")); - break; - default: - $fields["$term"] = array(); - array_push($fields["$term"], $ilDB->like("svy_question." . $this->search_field, 'text', "%" .$term . "%")); - break; - } - } - $cumulated_fields = array(); - foreach ($fields as $params) - { - array_push($cumulated_fields, "(" . join($params, " OR ") . ")"); - } - $str_where = ""; - if ($this->concatenation == self::CONCAT_AND) - { - $str_where = "(" . join($cumulated_fields, " AND ") . ")"; - } - else - { - $str_where = "(" . join($cumulated_fields, " OR ") . ")"; - } - if ($str_where) - { - $str_where = " AND $str_where"; - } - if ($where) - { - $str_where .= " AND (" . $where . ")"; - } - $result = $ilDB->query("SELECT svy_question.*, svy_qtype.type_tag, object_reference.ref_id FROM " . - "svy_question, svy_qtype, object_reference WHERE svy_question.questiontype_fi = svy_qtype.questiontype_id ". - "AND svy_question.original_id IS NULL AND svy_question.obj_fi = object_reference.obj_id AND ". - "svy_question.obj_fi > 0$str_where"); - $result_array = array(); - $rbacsystem = $this->rbacsystem; - if ($result->numRows() > 0) - { - while ($row = $ilDB->fetchAssoc($result)) - { - if (($row["complete"] == 1) and ($rbacsystem->checkAccess('write', $row["ref_id"]))) - { - array_push($result_array, $row); - } - } - } - $this->search_results =& $result_array; - } + $this->search_terms = explode(" +", $search_text); + $this->concatenation = $concatenation; + $this->search_field = $search_field; + $this->search_type = $search_type; + $this->search_results = array(); + } + + /** + * Executes a search + * + * Executes a search + * + * @access public + */ + public function search() + { + $ilDB = $this->ilDB; + + $where = ""; + $fields = array(); + if (strcmp($this->search_type, "all") != 0) { + $where = "svy_qtype.type_tag = " . $ilDB->quote($this->search_type, 'text'); + } + foreach ($this->search_terms as $term) { + switch ($this->search_field) { + case "all": + $fields["$term"] = array(); + array_push($fields["$term"], $ilDB->like("svy_question.title", 'text', "%" . $term . "%")); + array_push($fields["$term"], $ilDB->like("svy_question.description", 'text', "%" . $term . "%")); + array_push($fields["$term"], $ilDB->like("svy_question.author", 'text', "%" . $term . "%")); + array_push($fields["$term"], $ilDB->like("svy_question.questiontext", 'text', "%" . $term . "%")); + break; + default: + $fields["$term"] = array(); + array_push($fields["$term"], $ilDB->like("svy_question." . $this->search_field, 'text', "%" . $term . "%")); + break; + } + } + $cumulated_fields = array(); + foreach ($fields as $params) { + array_push($cumulated_fields, "(" . join($params, " OR ") . ")"); + } + $str_where = ""; + if ($this->concatenation == self::CONCAT_AND) { + $str_where = "(" . join($cumulated_fields, " AND ") . ")"; + } else { + $str_where = "(" . join($cumulated_fields, " OR ") . ")"; + } + if ($str_where) { + $str_where = " AND $str_where"; + } + if ($where) { + $str_where .= " AND (" . $where . ")"; + } + $result = $ilDB->query("SELECT svy_question.*, svy_qtype.type_tag, object_reference.ref_id FROM " . + "svy_question, svy_qtype, object_reference WHERE svy_question.questiontype_fi = svy_qtype.questiontype_id " . + "AND svy_question.original_id IS NULL AND svy_question.obj_fi = object_reference.obj_id AND " . + "svy_question.obj_fi > 0$str_where"); + $result_array = array(); + $rbacsystem = $this->rbacsystem; + if ($result->numRows() > 0) { + while ($row = $ilDB->fetchAssoc($result)) { + if (($row["complete"] == 1) and ($rbacsystem->checkAccess('write', $row["ref_id"]))) { + array_push($result_array, $row); + } + } + } + $this->search_results =&$result_array; + } } - -?> \ No newline at end of file diff --git a/Modules/Survey/classes/class.ilObjSurvey.php b/Modules/Survey/classes/class.ilObjSurvey.php index e71c834e06f6a18eba9fbaf0e6b9a0d443076b4f..e8cf204d443681a455d4dd2b8fdf444f2201fc83 100755 --- a/Modules/Survey/classes/class.ilObjSurvey.php +++ b/Modules/Survey/classes/class.ilObjSurvey.php @@ -5,7 +5,7 @@ include_once "./Services/Object/classes/class.ilObject.php"; /** * Class ilObjSurvey -* +* * @author Helmut Schottmüller * @version $Id$ * @@ -14,6678 +14,6282 @@ include_once "./Services/Object/classes/class.ilObject.php"; */ class ilObjSurvey extends ilObject { - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilPluginAdmin - */ - protected $plugin_admin; - - const EVALUATION_ACCESS_OFF = 0; - const EVALUATION_ACCESS_ALL = 1; - const EVALUATION_ACCESS_PARTICIPANTS = 2; - - const INVITATION_OFF = 0; - const INVITATION_ON = 1; - - const MODE_UNLIMITED = 0; - const MODE_PREDEFINED_USERS = 1; - - const ANONYMIZE_OFF = 0; // personalized, no codes - const ANONYMIZE_ON = 1; // anonymized, codes - const ANONYMIZE_FREEACCESS = 2; // anonymized, no codes - const ANONYMIZE_CODE_ALL = 3; // personalized, codes - - const QUESTIONTITLES_HIDDEN = 0; - const QUESTIONTITLES_VISIBLE = 1; - - // constants to define the print view values. - const PRINT_HIDE_LABELS = 1; // Show only the titles in "print" and "PDF Export" - const PRINT_SHOW_LABELS = 3; // Show titles and labels in "print" and "PDF Export" - - /** - * A unique positive numerical ID which identifies the survey. - * This is the primary key from a database table. - * - * @var integer - */ - var $survey_id; - - /** - * 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; - - /** - * A text representation of the surveys introduction. - * - * @var string - */ - var $introduction; - - /** - * A text representation of the surveys outro. - * - * @var string - */ - var $outro; - - - /** - * Indicates the evaluation access for learners - * - * @var string - */ - var $evaluation_access; - - /** - * The start date of the survey - * - * @var string - */ - var $start_date; - - /** - * The end date of the survey - * - * @var string - */ - var $end_date; - - /** - * The questions contained in this survey - * - * @var array - */ - var $questions; - - /** - * Defines if the survey will be places on users personal desktops - * - * @var integer - */ - var $invitation; - - /** - * Defines the type of user invitation - * - * @var integer - */ - var $invitation_mode; - - /** - * Indicates the anonymization of the survey - * @var integer - */ - var $anonymize; - - /** - * Indicates if the question titles are shown during a query - * @var integer - */ - var $display_question_titles; - - /** - * Indicates if a survey code may be exported with the survey statistics - * - * @var boolean - **/ - var $surveyCodeSecurity; - - var $mailnotification; - var $mailaddresses; - var $mailparticipantdata; - var $template_id; - var $pool_usage; - - /** - * @var ilLogger - */ - protected $log; - - protected $activation_visibility; - protected $activation_starting_time; - protected $activation_ending_time; - - // 360° - protected $mode_360_self_eval; // [bool] - protected $mode_360_self_appr; // [bool] - protected $mode_360_self_rate; // [bool] - protected $mode_360_results; // [int] - protected $mode_skill_service; // [bool] - - const RESULTS_360_NONE = 0; - const RESULTS_360_OWN = 1; - const RESULTS_360_ALL = 2; - - // reminder/notification - protected $reminder_status; // [bool] - protected $reminder_start; // [ilDate] - protected $reminder_end; // [ilDate] - protected $reminder_frequency; // [int] - protected $reminder_target; // [int] - protected $reminder_last_sent; // [bool] - protected $reminder_tmpl; // [int] - protected $tutor_ntf_status; // [bool] - protected $tutor_ntf_recipients; // [array] - protected $tutor_ntf_target; // [int] - - protected $view_own_results; // [bool] - protected $mail_own_results; // [bool] - protected $mail_confirmation; // [bool] - - protected $anon_user_list; // [bool] - - const NOTIFICATION_PARENT_COURSE = 1; - const NOTIFICATION_INVITED_USERS = 2; - const NOTIFICATION_APPRAISEES = 3; - const NOTIFICATION_RATERS = 4; - const NOTIFICATION_APPRAISEES_AND_RATERS = 5; - - protected $mode; //[int] - protected $mode_self_eval_results; //[int] - - //MODE TYPES - const MODE_STANDARD = 0; - const MODE_360 = 1; - const MODE_SELF_EVAL = 2; - - //self evaluation only access to results - const RESULTS_SELF_EVAL_NONE = 0; - const RESULTS_SELF_EVAL_OWN = 1; - const RESULTS_SELF_EVAL_ALL = 2; - - - /** - * Constructor - * @access public - * @param integer reference_id or object_id - * @param boolean treat the id as reference_id (true) or object_id (false) - */ - function __construct($a_id = 0,$a_call_by_reference = true) - { - global $DIC; - - $this->user = $DIC->user(); - $this->lng = $DIC->language(); - $this->db = $DIC->database(); - $this->access = $DIC->access(); - $this->log = $DIC["ilLog"]; - $this->plugin_admin = $DIC["ilPluginAdmin"]; - $this->tree = $DIC->repositoryTree(); - $ilUser = $DIC->user(); - $lng = $DIC->language(); - - $this->type = "svy"; - $this->survey_id = -1; - $this->introduction = ""; - $this->outro = $lng->txt("survey_finished"); - $this->author = $ilUser->getFullname(); - $this->evaluation_access = self::EVALUATION_ACCESS_OFF; - $this->questions = array(); - $this->invitation = self::INVITATION_OFF; - $this->invitation_mode = self::MODE_PREDEFINED_USERS; - $this->anonymize = self::ANONYMIZE_OFF; - $this->display_question_titles = self::QUESTIONTITLES_VISIBLE; - $this->surveyCodeSecurity = TRUE; - $this->template_id = NULL; - $this->pool_usage = true; - $this->log = ilLoggerFactory::getLogger("svy"); - $this->mode = self::MODE_STANDARD; - $this->mode_self_eval_results = self::RESULTS_SELF_EVAL_OWN; - - parent::__construct($a_id,$a_call_by_reference); - } - - /** - * create survey object - */ - function create($a_upload = false) - { - parent::create(); - if(!$a_upload) - { - $this->createMetaData(); - } - $this->setOfflineStatus(true); - $this->update($a_upload); - } - -/** -* Create meta data entry -* -* @access public -*/ - function createMetaData() - { - parent::createMetaData(); - $this->saveAuthorToMetadata(); - } - - /** - * update object data - * - * @access public - * @return boolean - */ - function update($a_upload = false) - { - if (!$a_upload) { - $this->updateMetaData(); - } - - if (!parent::update()) - { - return false; - } - - // put here object specific stuff - - return true; - } - - function createReference() - { - $result = parent::createReference(); - $this->saveToDb(); - return $result; - } - - /** - * read object data from db into object - * @access public - */ - public function read() - { - parent::read(); - $this->loadFromDb(); - } - - /** - * Adds a question to the survey (used in importer!) - * - * @param integer $question_id The question id of the question - * @access public - */ - function addQuestion($question_id) - { - array_push($this->questions, $question_id); - } - - /** - * delete object and all related data - * - * @access public - * @return boolean true if all object data were removed; false if only a references were removed - */ - function delete() - { - if ($this->countReferences() == 1) - { - $this->deleteMetaData(); - - // Delete all survey questions, constraints and materials - foreach ($this->questions as $question_id) - { - $this->removeQuestion($question_id); - } - $this->deleteSurveyRecord(); - - ilUtil::delDir($this->getImportDirectory()); - } - - $remove = parent::delete(); - - // always call parent delete function first!! - if (!$remove) - { - return false; - } - return true; - } - - /** - * Deletes the survey from the database - * - * @access public - */ - function deleteSurveyRecord() - { - $ilDB = $this->db; - - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_svy WHERE survey_id = %s", - array('integer'), - array($this->getSurveyId()) - ); - - $result = $ilDB->queryF("SELECT questionblock_fi FROM svy_qblk_qst WHERE survey_fi = %s", - array('integer'), - array($this->getSurveyId()) - ); - $questionblocks = array(); - while ($row = $ilDB->fetchAssoc($result)) - { - array_push($questionblocks, $row["questionblock_fi"]); - } - if (count($questionblocks)) - { - $affectedRows = $ilDB->manipulate("DELETE FROM svy_qblk WHERE " . $ilDB->in('questionblock_id', $questionblocks, false, 'integer')); - } - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk_qst WHERE survey_fi = %s", - array('integer'), - array($this->getSurveyId()) - ); - $this->deleteAllUserData(false); - - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_anonymous WHERE survey_fi = %s", - array('integer'), - array($this->getSurveyId()) - ); - - // delete export files - $svy_data_dir = ilUtil::getDataDir()."/svy_data"; - $directory = $svy_data_dir."/svy_".$this->getId(); - if (is_dir($directory)) - { - ilUtil::delDir($directory); - } - - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $mobs = ilObjMediaObject::_getMobsOfObject("svy:html", $this->getId()); - // 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, "svy:html", $this->getId()); - $mob_obj = new ilObjMediaObject($mob); - $mob_obj->delete(); - } - } - - /** - * Deletes all user data of a survey - * - * @access public - * @param bool $reset_LP notice that the LP can only be reset it the determining components still exist - */ - function deleteAllUserData($reset_LP = true) - { - $ilDB = $this->db; - - $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s", - array('integer'), - array($this->getSurveyId()) - ); - $active_array = array(); - while ($row = $ilDB->fetchAssoc($result)) - { - array_push($active_array, $row["finished_id"]); - } - - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_finished WHERE survey_fi = %s", - array('integer'), - array($this->getSurveyId()) - ); - - foreach ($active_array as $active_fi) - { - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_answer WHERE active_fi = %s", - array('integer'), - array($active_fi) - ); - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_times WHERE finished_fi = %s", - array('integer'), - array($active_fi) - ); - } - - if ($reset_LP) { - include_once "Services/Object/classes/class.ilObjectLP.php"; - $lp_obj = ilObjectLP::getInstance($this->getId()); - $lp_obj->resetLPDataForCompleteObject(); - } - } - - /** - * Deletes the user data of a given array of survey participants - * - * @access public - */ - function removeSelectedSurveyResults($finished_ids) - { - $ilDB = $this->db; - - $user_ids[] = array(); - - foreach ($finished_ids as $finished_id) - { - $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE finished_id = %s", - array('integer'), - array($finished_id) - ); - $row = $ilDB->fetchAssoc($result); - - if($row["user_fi"]) - { - $user_ids[] = $row["user_fi"]; - } - - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_answer WHERE active_fi = %s", - array('integer'), - array($row["finished_id"]) - ); - - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_finished WHERE finished_id = %s", - array('integer'), - array($finished_id) - ); - - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_times WHERE finished_fi = %s", - array('integer'), - array($row["finished_id"]) - ); - } - - if(sizeof($user_ids)) - { - include_once "Services/Object/classes/class.ilObjectLP.php"; - $lp_obj = ilObjectLP::getInstance($this->getId()); - $lp_obj->resetLPDataForUserIds($user_ids); - } - } - - function &getSurveyParticipants($finished_ids = null, $force_non_anonymous = false) - { - $ilDB = $this->db; - - $sql = "SELECT * FROM svy_finished". - " WHERE survey_fi = ".$ilDB->quote($this->getSurveyId(), "integer"); - if($finished_ids) - { - $sql .= " AND ".$ilDB->in("finished_id", $finished_ids, "", "integer"); - } - - $result = $ilDB->query($sql); - $participants = array(); - if ($result->numRows() > 0) - { - while ($row = $ilDB->fetchAssoc($result)) - { - $userdata = $this->getUserDataFromActiveId($row["finished_id"], $force_non_anonymous); - $userdata["finished"] = (bool)$row["state"]; - $userdata["finished_tstamp"] = $row["tstamp"]; - $participants[$userdata["sortname"] . $userdata["active_id"]] = $userdata; - } - } - return $participants; - } - -/** -* Returns 1, if a survey is complete for use -* -* @return boolean 1, if the survey is complete for use, otherwise 0 -* @access public -*/ - function isComplete() - { - if (($this->getTitle()) and (count($this->questions))) - { - return 1; - } - else - { - return 0; - } - } - -/** -* Saves the completion status of the survey -* -* @access public -*/ - function saveCompletionStatus() - { - $ilDB = $this->db; - - $complete = 0; - if ($this->isComplete()) - { - $complete = 1; - } - if ($this->getSurveyId() > 0) - { - $affectedRows = $ilDB->manipulateF("UPDATE svy_svy SET complete = %s, tstamp = %s WHERE survey_id = %s", - array('text','integer','integer'), - array($this->isComplete(), time(), $this->getSurveyId()) - ); - } - } - -/** -* Takes a question and creates a copy of the question for use in the survey -* -* @param integer $question_id The database id of the question -* @result integer The database id of the copied question -* @access public -*/ - function duplicateQuestionForSurvey($question_id, $a_force = false) - { - $ilUser = $this->user; - - $questiontype = $this->getQuestionType($question_id); - $question_gui = $this->getQuestionGUI($questiontype, $question_id); - - // check if question is a pool question at all, if not do nothing - if($this->getId() == $question_gui->object->getObjId() && !$a_force) - { - return $question_id; - } - - $duplicate_id = $question_gui->object->duplicate(true, "", "", "", $this->getId()); - return $duplicate_id; - } - -/** -* Inserts a question in the survey and saves the relation to the database -* -* @access public -*/ - function insertQuestion($question_id) - { - $ilDB = $this->db; - - $this->log->debug("insert question, id:".$question_id); - - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - if (!SurveyQuestion::_isComplete($question_id)) - { - $this->log->debug("question is not complete"); - return FALSE; - } - else - { - // get maximum sequence index in test - // @todo: refactor this - $result = $ilDB->queryF("SELECT survey_question_id FROM svy_svy_qst WHERE survey_fi = %s", - array('integer'), - array($this->getSurveyId()) - ); - $sequence = $result->numRows(); - $duplicate_id = $this->duplicateQuestionForSurvey($question_id); - $this->log->debug("duplicate, id: ".$question_id.", duplicate id: ".$duplicate_id); - - // check if question is not already in the survey, see #22018 - if ($this->isQuestionInSurvey($duplicate_id)) - { - return false; - } - - $next_id = $ilDB->nextId('svy_svy_qst'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_svy_qst (survey_question_id, survey_fi, question_fi, sequence, tstamp) VALUES (%s, %s, %s, %s, %s)", - array('integer', 'integer', 'integer', 'integer', 'integer'), - array($next_id, $this->getSurveyId(), $duplicate_id, $sequence, time()) - ); - - $this->log->debug("added entry to svy_svy_qst, id: ".$next_id.", question id: ".$duplicate_id.", sequence: ".$sequence); - - $this->loadQuestionsFromDb(); - return TRUE; - } - } - - /** - * Check if a question is already in the survey - * - * @param question id (as primary key from svy_question table) - * @return bool - */ - function isQuestionInSurvey($a_question_fi) - { - global $DIC; -//return false; - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT * FROM svy_svy_qst ". - " WHERE survey_fi = ".$ilDB->quote($this->getSurveyId(), "integer"). - " AND question_fi = ".$ilDB->quote($a_question_fi, "integer")); - if ($rec = $ilDB->fetchAssoc($set)) - { - return true; - } - return false; - } - - - -/** -* Inserts a questionblock in the survey and saves the relation to the database -* -* @access public -*/ - function insertQuestionblock($questionblock_id) - { - $ilDB = $this->db; - $result = $ilDB->queryF("SELECT svy_qblk.title, svy_qblk.show_questiontext, svy_qblk.show_blocktitle,". - " svy_qblk_qst.question_fi FROM svy_qblk, svy_qblk_qst, svy_svy_qst". - " WHERE svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi". - " AND svy_svy_qst.question_fi = svy_qblk_qst.question_fi". - " AND svy_qblk.questionblock_id = %s". - " ORDER BY svy_svy_qst.sequence", - array('integer'), - array($questionblock_id) - ); - $questions = array(); - $show_questiontext = 0; - $show_blocktitle = 0; - while ($row = $ilDB->fetchAssoc($result)) - { - $duplicate_id = $this->duplicateQuestionForSurvey($row["question_fi"]); - array_push($questions, $duplicate_id); - $title = $row["title"]; - $show_questiontext = $row["show_questiontext"]; - $show_blocktitle = $row["show_blocktitle"]; - } - $this->createQuestionblock($title, $show_questiontext, $show_blocktitle, $questions); - } - - public function saveUserSettings($usr_id, $key, $title, $value) - { - $ilDB = $this->db; - - $next_id = $ilDB->nextId('svy_settings'); - $affectedRows = $ilDB->insert("svy_settings", array( - "settings_id" => array("integer", $next_id), - "usr_id" => array("integer", $usr_id), - "keyword" => array("text", $key), - "title" => array("text", $title), - "value" => array("clob", $value) - )); - } - - public function deleteUserSettings($id) - { - $ilDB = $this->db; - - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_settings WHERE settings_id = %s", - array('integer'), - array($id) - ); - return $affectedRows; - } - - public function getUserSettings($usr_id, $key) - { - $ilDB = $this->db; - - $result = $ilDB->queryF("SELECT * FROM svy_settings WHERE usr_id = %s AND keyword = %s", - array('integer', 'text'), - array($usr_id, $key) - ); - $found = array(); - if ($result->numRows()) - { - while ($row = $ilDB->fetchAssoc($result)) - { - $found[$row['settings_id']] = $row; - } - } - return $found; - } - -/** -* Saves a survey object to a database -* -* @access public -*/ - function saveToDb() - { - $ilDB = $this->db; - - // date handling - $rmd_start = $this->getReminderStart(); - if(is_object($rmd_start)) - { - $rmd_start = $rmd_start->get(IL_CAL_DATE); - } - $rmd_end = $this->getReminderEnd(); - if(is_object($rmd_end)) - { - $rmd_end = $rmd_end->get(IL_CAL_DATE); - } - - include_once("./Services/RTE/classes/class.ilRTE.php"); - if ($this->getSurveyId() < 1) - { - $next_id = $ilDB->nextId('svy_svy'); - $affectedRows = $ilDB->insert("svy_svy", array( - "survey_id" => array("integer", $next_id), - "obj_fi" => array("integer", $this->getId()), - "author" => array("text", $this->getAuthor()), - "introduction" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getIntroduction(), 0)), - "outro" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getOutro(), 0)), - "startdate" => array("text", $this->getStartDate()), - "enddate" => array("text", $this->getEndDate()), - "evaluation_access" => array("text", $this->getEvaluationAccess()), - "invitation" => array("text", $this->getInvitation()), - "invitation_mode" => array("text", $this->getInvitationMode()), - "complete" => array("text", $this->isComplete()), - "created" => array("integer", time()), - "anonymize" => array("text", $this->getAnonymize()), - "show_question_titles" => array("text", $this->getShowQuestionTitles()), - "mailnotification" => array('integer', ($this->getMailNotification()) ? 1 : 0), - "mailaddresses" => array('text', strlen($this->getMailAddresses()) ? $this->getMailAddresses() : NULL), - "mailparticipantdata" => array('text', strlen($this->getMailParticipantData()) ? $this->getMailParticipantData() : NULL), - "tstamp" => array("integer", time()), - "template_id" => array("integer", $this->getTemplate()), - "pool_usage" => array("integer", $this->getPoolUsage()), - // Mode type - "mode" => array("integer", $this->getMode()), - // 360° - "mode_360_self_eval" => array("integer", $this->get360SelfEvaluation()), - "mode_360_self_rate" => array("integer", $this->get360SelfRaters()), - "mode_360_self_appr" => array("integer", $this->get360SelfAppraisee()), - "mode_360_results" => array("integer", $this->get360Results()), - // competences - "mode_skill_service" => array("integer", (int) $this->getSkillService()), - // Self Evaluation Only - "mode_self_eval_results" => array("integer", ilObjSurvey::RESULTS_SELF_EVAL_OWN), - // reminder/notification - "reminder_status" => array("integer", (int)$this->getReminderStatus()), - "reminder_start" => array("datetime", $rmd_start), - "reminder_end" => array("datetime", $rmd_end), - "reminder_frequency" => array("integer", (int)$this->getReminderFrequency()), - "reminder_target" => array("integer", (int)$this->getReminderTarget()), - "reminder_last_sent" => array("datetime", $this->getReminderLastSent()), - "reminder_tmpl" => array("text", $this->getReminderTemplate(true)), - "tutor_ntf_status" => array("integer", (int)$this->getTutorNotificationStatus()), - "tutor_ntf_reci" => array("text", implode(";", (array)$this->getTutorNotificationRecipients())), - "tutor_ntf_target" => array("integer", (int)$this->getTutorNotificationTarget()), - "own_results_view" => array("integer", $this->hasViewOwnResults()), - "own_results_mail" => array("integer", $this->hasMailOwnResults()), - "confirmation_mail" => array("integer", $this->hasMailConfirmation()), - "anon_user_list" => array("integer", $this->hasAnonymousUserList()) - )); - $this->setSurveyId($next_id); - } - else - { - $affectedRows = $ilDB->update("svy_svy", array( - "author" => array("text", $this->getAuthor()), - "introduction" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getIntroduction(), 0)), - "outro" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getOutro(), 0)), - "startdate" => array("text", $this->getStartDate()), - "enddate" => array("text", $this->getEndDate()), - "evaluation_access" => array("text", $this->getEvaluationAccess()), - "invitation" => array("text", $this->getInvitation()), - "invitation_mode" => array("text", $this->getInvitationMode()), - "complete" => array("text", $this->isComplete()), - "anonymize" => array("text", $this->getAnonymize()), - "show_question_titles" => array("text", $this->getShowQuestionTitles()), - "mailnotification" => array('integer', ($this->getMailNotification()) ? 1 : 0), - "mailaddresses" => array('text', strlen($this->getMailAddresses()) ? $this->getMailAddresses() : NULL), - "mailparticipantdata" => array('text', strlen($this->getMailParticipantData()) ? $this->getMailParticipantData() : NULL), - "tstamp" => array("integer", time()), - "template_id" => array("integer", $this->getTemplate()), - "pool_usage" => array("integer", $this->getPoolUsage()), - //MODE TYPE - "mode" => array("integer", $this->getMode()), - // 360° - "mode_360_self_eval" => array("integer", $this->get360SelfEvaluation()), - "mode_360_self_rate" => array("integer", $this->get360SelfRaters()), - "mode_360_self_appr" => array("integer", $this->get360SelfAppraisee()), - "mode_360_results" => array("integer", $this->get360Results()), - // Competences - "mode_skill_service" => array("integer", (int) $this->getSkillService()), - // Self Evaluation Only - "mode_self_eval_results" => array("integer", $this->getSelfEvaluationResults()), - // reminder/notification - "reminder_status" => array("integer", $this->getReminderStatus()), - "reminder_start" => array("datetime", $rmd_start), - "reminder_end" => array("datetime", $rmd_end), - "reminder_frequency" => array("integer", $this->getReminderFrequency()), - "reminder_target" => array("integer", $this->getReminderTarget()), - "reminder_last_sent" => array("datetime", $this->getReminderLastSent()), - "reminder_tmpl" => array("text", $this->getReminderTemplate()), - "tutor_ntf_status" => array("integer", $this->getTutorNotificationStatus()), - "tutor_ntf_reci" => array("text", implode(";", (array)$this->getTutorNotificationRecipients())), - "tutor_ntf_target" => array("integer", $this->getTutorNotificationTarget()), - "own_results_view" => array("integer", $this->hasViewOwnResults()), - "own_results_mail" => array("integer", $this->hasMailOwnResults()), - "confirmation_mail" => array("integer", $this->hasMailConfirmation()), - "anon_user_list" => array("integer", $this->hasAnonymousUserList()) - ), array( - "survey_id" => array("integer", $this->getSurveyId()) - )); - } - if ($affectedRows) - { - // save questions to db - $this->saveQuestionsToDb(); - } - - // moved activation to ilObjectActivation - if($this->ref_id) - { - include_once "./Services/Object/classes/class.ilObjectActivation.php"; - ilObjectActivation::getItem($this->ref_id); - - $item = new ilObjectActivation; - if(!$this->isActivationLimited()) - { - $item->setTimingType(ilObjectActivation::TIMINGS_DEACTIVATED); - } - else - { - $item->setTimingType(ilObjectActivation::TIMINGS_ACTIVATION); - $item->setTimingStart($this->getActivationStartDate()); - $item->setTimingEnd($this->getActivationEndDate()); - $item->toggleVisible($this->getActivationVisibility()); - } - - $item->update($this->ref_id); - } - } - -/** -* Saves the survey questions to the database -* -* @access public -* @see $questions -*/ - function saveQuestionsToDb() - { - $ilDB = $this->db; - - $this->log->debug("save questions"); - - // gather old questions state - $old_questions = array(); - $result = $ilDB->queryF("SELECT survey_question_id,question_fi,sequence". - " FROM svy_svy_qst WHERE survey_fi = %s", - array('integer'), - array($this->getSurveyId()) - ); - while($row = $ilDB->fetchAssoc($result)) - { - $old_questions[$row["question_fi"]] = $row; // problem, as soon as duplicates exist, they will be hidden here - } - - // #15231 - diff with current questions state - $insert = $update = $delete = array(); - foreach($this->questions as $seq => $fi) - { - if(!array_key_exists($fi, $old_questions)) // really new fi IDs - { - $insert[] = $fi; // this should be ok, should not create duplicates here - } - else if($old_questions[$fi]["sequence"] != $seq) // we are updating one of the duplicates (if any) - { - $update[$fi] = $old_questions[$fi]["survey_question_id"]; - } - // keep track of still relevant questions - unset($old_questions[$fi]); // deleting old question, if they are not in current array - } - - // delete obsolete question relations - if(sizeof($old_questions)) - { - $del_ids = array(); - foreach($old_questions as $fi => $old) - { - $del_ids[] = $old["survey_question_id"]; - } - $ilDB->manipulate($q = "DELETE FROM svy_svy_qst". - " WHERE ".$ilDB->in("survey_question_id", $del_ids, "", "integer")); - $this->log->debug("delete: ".$q); - } - unset($old_questions); - - // create/update question relations - foreach($this->questions as $seq => $fi) - { - if(in_array($fi, $insert)) - { - // check if question is not already in the survey, see #22018 - if (!$this->isQuestionInSurvey($fi)) - { - $next_id = $ilDB->nextId('svy_svy_qst'); - $ilDB->manipulateF("INSERT INTO svy_svy_qst" . - " (survey_question_id, survey_fi, question_fi, heading, sequence, tstamp)" . - " VALUES (%s, %s, %s, %s, %s, %s)", - array('integer', 'integer', 'integer', 'text', 'integer', 'integer'), - array($next_id, $this->getSurveyId(), $fi, null, $seq, time()) - ); - $this->log->debug("insert svy_svy_qst, id:" . $next_id . ", fi: " . $fi . ", seq:" . $seq); - } - } - else if(array_key_exists($fi, $update)) - { - $ilDB->manipulate("UPDATE svy_svy_qst". - " SET sequence = ".$ilDB->quote($seq, "integer"). - ", tstamp = ".$ilDB->quote(time(), "integer"). - " WHERE survey_question_id = ".$ilDB->quote($update[$fi], "integer")); - $this->log->debug("update svy_svy_qst, id:".$update[$fi].", fi: ".$fi.", seq:".$seq); - } - } - } - -/** -* Checks for an anomyous survey id in the database an returns the id -* -* @param string $id A survey access code -* @result object Anonymous survey id if found, empty string otherwise -* @access public -*/ - function getAnonymousId($id) - { - $ilDB = $this->db; - $result = $ilDB->queryF("SELECT anonymous_id FROM svy_finished WHERE anonymous_id = %s", - array('text'), - array($id) - ); - if ($result->numRows()) - { - $row = $ilDB->fetchAssoc($result); - return $row["anonymous_id"]; - } - else - { - return ""; - } - } - -/** -* Returns a question gui object to a given questiontype and question id -* -* @result object Resulting question gui object -* @access public -*/ - function getQuestionGUI($questiontype, $question_id) - { - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php"; - return SurveyQuestionGUI::_getQuestionGUI($questiontype, $question_id); - } - -/** -* 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 -*/ - function getQuestionType($question_id) - { - $ilDB = $this->db; - if ($question_id < 1) return -1; - $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 survey database id -* -* @result integer survey database id -* @access public -*/ - function getSurveyId() - { - return $this->survey_id; - } - - /** - * set anonymize status - */ - function setAnonymize($a_anonymize) - { - switch ($a_anonymize) - { - case self::ANONYMIZE_OFF: - case self::ANONYMIZE_ON: - case self::ANONYMIZE_FREEACCESS: - case self::ANONYMIZE_CODE_ALL: - $this->anonymize = $a_anonymize; - break; - default: - $this->anonymize = self::ANONYMIZE_OFF; - break; - } - } - - /** - * get anonymize status - * - * @return integer status - */ - function getAnonymize() - { - return ($this->anonymize) ? $this->anonymize : 0; - } - - /** - * Checks if the survey is accessable without a survey code - * - * @return boolean status - */ - function isAccessibleWithoutCode() - { - return ($this->getAnonymize() == self::ANONYMIZE_OFF || - $this->getAnonymize() == self::ANONYMIZE_FREEACCESS); - } - - /** - * Checks if the survey results are to be anonymized - * - * @return boolean status - */ - function hasAnonymizedResults() - { - return ($this->getAnonymize() == self::ANONYMIZE_ON || - $this->getAnonymize() == self::ANONYMIZE_FREEACCESS); - } - -/** -* Loads a survey object from a database -* -* @access public -*/ - function loadFromDb() - { - $ilDB = $this->db; - $result = $ilDB->queryF("SELECT * FROM svy_svy WHERE obj_fi = %s", - array('integer'), - array($this->getId()) - ); - if ($result->numRows() == 1) - { - $data = $ilDB->fetchAssoc($result); - $this->setSurveyId($data["survey_id"]); - $this->setAuthor($data["author"]); - include_once("./Services/RTE/classes/class.ilRTE.php"); - $this->setIntroduction(ilRTE::_replaceMediaObjectImageSrc($data["introduction"], 1)); - if (strcmp($data["outro"], "survey_finished") == 0) - { - $this->setOutro($this->lng->txt("survey_finished")); - } - else - { - $this->setOutro(ilRTE::_replaceMediaObjectImageSrc($data["outro"], 1)); - } - $this->setInvitation($data["invitation"]); - $this->setInvitationMode($data["invitation_mode"]); - $this->setShowQuestionTitles($data["show_question_titles"]); - $this->setStartDate($data["startdate"]); - $this->setEndDate($data["enddate"]); - $this->setAnonymize($data["anonymize"]); - $this->setEvaluationAccess($data["evaluation_access"]); - $this->loadQuestionsFromDb(); - $this->setMailNotification($data['mailnotification']); - $this->setMailAddresses($data['mailaddresses']); - $this->setMailParticipantData($data['mailparticipantdata']); - $this->setTemplate($data['template_id']); - $this->setPoolUsage($data['pool_usage']); - // Mode - $this->setMode($data['mode']); - // 360° - $this->set360SelfEvaluation($data['mode_360_self_eval']); - $this->set360SelfRaters($data['mode_360_self_rate']); - $this->set360SelfAppraisee($data['mode_360_self_appr']); - $this->set360Results($data['mode_360_results']); - // Mode self evaluated - $this->setSelfEvaluationResults($data['mode_self_eval_results']); - // Competences - $this->setSkillService($data['mode_skill_service']); - // reminder/notification - $this->setReminderStatus($data["reminder_status"]); - $this->setReminderStart($data["reminder_start"] ? new ilDate($data["reminder_start"], IL_CAL_DATE) : null); - $this->setReminderEnd($data["reminder_end"] ? new ilDate($data["reminder_end"], IL_CAL_DATE) : null); - $this->setReminderFrequency($data["reminder_frequency"]); - $this->setReminderTarget($data["reminder_target"]); - $this->setReminderLastSent($data["reminder_last_sent"]); - $this->setReminderTemplate($data["reminder_tmpl"]); - $this->setTutorNotificationStatus($data["tutor_ntf_status"]); - $this->setTutorNotificationRecipients(explode(";", $data["tutor_ntf_reci"])); - $this->setTutorNotificationTarget($data["tutor_ntf_target"]); - - $this->setViewOwnResults($data["own_results_view"]); - $this->setMailOwnResults($data["own_results_mail"]); - $this->setMailConfirmation($data["confirmation_mail"]); - - $this->setAnonymousUserList($data["anon_user_list"]); - } - - // moved activation to ilObjectActivation - if($this->ref_id) - { - include_once "./Services/Object/classes/class.ilObjectActivation.php"; - $activation = ilObjectActivation::getItem($this->ref_id); - switch($activation["timing_type"]) - { - case ilObjectActivation::TIMINGS_ACTIVATION: - $this->setActivationLimited(true); - $this->setActivationStartDate($activation["timing_start"]); - $this->setActivationEndDate($activation["timing_end"]); - $this->setActivationVisibility($activation["visible"]); - break; - - default: - $this->setActivationLimited(false); - break; - } - } - } - -/** -* Loads the survey questions from the database -* -* @access public -* @see $questions -*/ - function loadQuestionsFromDb() - { - $ilDB = $this->db; - $this->questions = array(); - $result = $ilDB->queryF("SELECT * FROM svy_svy_qst WHERE survey_fi = %s ORDER BY sequence", - array('integer'), - array($this->getSurveyId()) - ); - while ($data = $ilDB->fetchAssoc($result)) - { - $this->questions[$data["sequence"]] = $data["question_fi"]; - } - } - - /** - * Remove duplicate sequence entries, see #22018 - */ - function fixSequenceStructure() - { - global $DIC; - - $ilDB = $DIC->database(); -//return; - // we keep all survey question ids with their lowest sequence - $result = $ilDB->queryF("SELECT * FROM svy_svy_qst WHERE survey_fi = %s ORDER BY sequence", - array('integer'), - array($this->getSurveyId()) - ); - - // step 1: find duplicates -> $to_delete_ids - $fis = array(); - $to_delete_ids = array(); - while ($data = $ilDB->fetchAssoc($result)) - { - if (in_array($data["question_fi"], $fis)) // found a duplicate - { - $to_delete_ids[] = $data["survey_question_id"]; - } - else - { - $fis[] = $data["question_fi"]; - } - } - - // step 2: we delete the duplicates - if (count($to_delete_ids) > 0) - { - $ilDB->manipulate($q = "DELETE FROM svy_svy_qst" . - " WHERE " . $ilDB->in("survey_question_id", $to_delete_ids, false, "integer") . - " AND survey_fi = " . $ilDB->quote($this->getSurveyId(), "integer")); - $this->log->debug("delete: " . $q); - - $ilDB->manipulate($q = "DELETE FROM svy_qblk_qst " . - " WHERE " . $ilDB->in("question_fi", $fis, true, "integer") . - " AND survey_fi = " . $ilDB->quote($this->getSurveyId(), "integer")); - $this->log->debug("delete: " . $q); - } - - // step 3: we fix the sequence - $set = $ilDB->query("SELECT * FROM svy_svy_qst ". - " WHERE survey_fi = " . $ilDB->quote($this->getSurveyId(), "integer")." ORDER BY sequence"); - $seq = 0; - while ($rec = $ilDB->fetchAssoc($set)) - { - $ilDB->manipulate($q = "UPDATE svy_svy_qst SET ". - " sequence = ".$ilDB->quote($seq++ , "integer"). - " WHERE survey_question_id = ".$ilDB->quote($rec["survey_question_id"], "integer") - ); - $this->log->debug("update: " . $q); - } - } - - -/** -* Sets the authors name of the ilObjSurvey object -* -* @param string $author A string containing the name of the test author -* @access public -* @see $author -*/ - function setAuthor($author = "") - { - $this->author = $author; - } - -/** -* Saves an authors name into the lifecycle metadata if no lifecycle metadata exists -* This will only be called for conversion of "old" tests where the author hasn't been -* stored in the lifecycle metadata -* -* @param string $a_author A string containing the name of the test author -* @access private -* @see $author -*/ - function saveAuthorToMetadata($a_author = "") - { - $md = new ilMD($this->getId(), 0, $this->getType()); - $md_life =& $md->getLifecycle(); - if (!$md_life) - { - if (strlen($a_author) == 0) - { - $ilUser = $this->user; - $a_author = $ilUser->getFullname(); - } - - $md_life =& $md->addLifecycle(); - $md_life->save(); - $con =& $md_life->addContribute(); - $con->setRole("Author"); - $con->save(); - $ent =& $con->addEntity(); - $ent->setEntity($a_author); - $ent->save(); - } - } - -/** -* Gets the authors name of the ilObjSurvey object -* -* @return string The string containing the name of the test author -* @access public -* @see $author -*/ - function getAuthor() - { - $author = array(); - include_once "./Services/MetaData/classes/class.ilMD.php"; - $md = new ilMD($this->getId(), 0, $this->getType()); - $md_life =& $md->getLifecycle(); - if ($md_life) - { - $ids =& $md_life->getContributeIds(); - foreach ($ids as $id) - { - $md_cont =& $md_life->getContribute($id); - if (strcmp($md_cont->getRole(), "Author") == 0) - { - $entids =& $md_cont->getEntityIds(); - foreach ($entids as $entid) - { - $md_ent =& $md_cont->getEntity($entid); - array_push($author, $md_ent->getEntity()); - } - } - } - } - return join($author, ","); - } - -/** -* Gets the status of the display_question_titles attribute -* -* @return integer The status of the display_question_titles attribute -* @see $display_question_titles -*/ - public function getShowQuestionTitles() - { - return ($this->display_question_titles) ? 1 : 0; - } - - /** - * Sets the status of the display_question_titles attribute - * - * @param integer $a_show The status of the display_question_titles attribute - * @see $display_question_titles - */ - public function setShowQuestionTitles($a_show) - { - $this->display_question_titles = ($a_show) ? 1 : 0; - } - -/** -* Sets the question titles visible during the query -* -* @access public -* @see $display_question_titles -*/ - function showQuestionTitles() - { - $this->display_question_titles = 1; - } - -/** -* Sets the question titles hidden during the query -* -* @access public -* @see $display_question_titles -*/ - function hideQuestionTitles() - { - $this->display_question_titles = 0; - } - -/** -* Sets the invitation status -* -* @param integer $invitation The invitation status -* @access public -* @see $invitation -*/ - function setInvitation($invitation = 0) - { - $ilDB = $this->db; - $ilAccess = $this->access; - - $this->invitation = $invitation; - if ($invitation == self::INVITATION_OFF) - { - $this->disinviteAllUsers(); - } - else if ($invitation == self::INVITATION_ON) - { - if ($this->getInvitationMode() == self::MODE_UNLIMITED) - { - $result = $ilDB->query("SELECT usr_id FROM usr_data"); - while ($row = $ilDB->fetchAssoc($result)) - { - if ($ilAccess->checkAccessOfUser($row["usr_id"], "read", "", $this->getRefId(), "svy", $this->getId())) - { - $this->inviteUser($row['usr_id']); - } - } - } - } - } - -/** -* Sets the invitation mode -* -* @param integer $invitation_mode The invitation mode -* @access public -* @see $invitation_mode -*/ - function setInvitationMode($invitation_mode = 0) - { - $this->invitation_mode = $invitation_mode; - } - -/** -* Sets the invitation status and mode (a more performant solution if you change both) -* -* @param integer $invitation The invitation status -* @param integer $invitation_mode The invitation mode -* @access public -* @see $invitation_mode -*/ - function setInvitationAndMode($invitation = 0, $invitation_mode = 0) - { - $this->invitation_mode = $invitation_mode; - $this->setInvitation($invitation); - } - -/** -* Sets the introduction text -* -* @param string $introduction A string containing the introduction -* @see $introduction -*/ - public function setIntroduction($introduction = "") - { - $this->introduction = $introduction; - } - -/** -* Sets the outro text -* -* @param string $outro A string containing the outro -* @see $outro -*/ - public function setOutro($outro = "") - { - $this->outro = $outro; - } - -/** -* Gets the invitation status -* -* @return integer The invitation status -* @access public -* @see $invitation -*/ - function getInvitation() - { - return ($this->invitation) ? $this->invitation : self::INVITATION_OFF; - } - -/** -* Gets the invitation mode -* -* @return integer The invitation mode -* @access public -* @see $invitation -*/ - function getInvitationMode() - { - include_once "./Services/Administration/classes/class.ilSetting.php"; - $surveySetting = new ilSetting("survey"); - $unlimited_invitation = $surveySetting->get("unlimited_invitation"); - if (!$unlimited_invitation && $this->invitation_mode == self::MODE_UNLIMITED) - { - return self::MODE_PREDEFINED_USERS; - } - else - { - return ($this->invitation_mode) ? $this->invitation_mode : self::MODE_UNLIMITED; - } - } - -/** -* Gets the start date of the survey -* -* @return string Survey start date (YYYY-MM-DD) -* @access public -* @see $start_date -*/ - function getStartDate() - { - return (strlen($this->start_date)) ? $this->start_date : NULL; - } - -/** -* Checks if the survey can be started -* -* @return array An array containing the following keys: result (boolean) and messages (array) -* @access public -*/ - function canStartSurvey($anonymous_id = NULL, $a_no_rbac = false) - { - $ilAccess = $this->access; - - $result = TRUE; - $messages = array(); - $edit_settings = false; - // check start date - if (preg_match("/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/", $this->getStartDate(), $matches)) - { - $epoch_time = mktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]); - $now = time(); - if ($now < $epoch_time) - { - array_push($messages,$this->lng->txt('start_date_not_reached').' ('. - ilDatePresentation::formatDate(new ilDateTime($this->getStartDate(), IL_CAL_TIMESTAMP)). ")"); - $result = FALSE; - $edit_settings = true; - } - } - // check end date - if (preg_match("/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/", $this->getEndDate(), $matches)) - { - $epoch_time = mktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]); - $now = time(); - if ($now > $epoch_time) - { - array_push($messages,$this->lng->txt('end_date_reached').' ('. - ilDatePresentation::formatDate(new ilDateTime($this->getEndDate(), IL_CAL_TIMESTAMP)). ")"); - $result = FALSE; - $edit_settings = true; - } - } - - // check online status - if($this->getOfflineStatus()) - { - array_push($messages, $this->lng->txt("survey_is_offline")); - $result = FALSE; - $edit_settings = true; - } - // check rbac permissions - if (!$a_no_rbac && !$ilAccess->checkAccess("read", "", $this->ref_id)) - { - array_push($messages, $this->lng->txt("cannot_participate_survey")); - $result = FALSE; - } - /* - // 2. check previous access - if (!$result["error"]) - { - $ilUser = $this->user; - $survey_started = $this->isSurveyStarted($ilUser->getId(), $anonymous_id); - if ($survey_started === 1) - { - array_push($messages, $this->lng->txt("already_completed_survey")); - $result = FALSE; - } - } - */ - return array( - "result" => $result, - "messages" => $messages, - "edit_settings" => $edit_settings - ); - } - -/** -* Sets the start date of the survey -* -* @param string $start_data Survey start date (YYYYMMDDHHMMSS) -* @access public -* @see $start_date -*/ - function setStartDate($start_date = "") - { - $this->start_date = $start_date; - } - - /** - * Sets the start date of the survey - * - * @param string $start_date Survey start date (YYYY-MM-DD) - * @param string $start_time Survey start time (HH:MM:SS) - * @access public - * @see $start_date - */ - function setStartDateAndTime($start_date = "", $start_time) - { - $y = ''; $m = ''; $d = ''; $h = ''; $i = ''; $s = ''; - if (preg_match("/(\d{4})-(\d{2})-(\d{2})/", $start_date, $matches)) - { - $y = $matches[1]; - $m = $matches[2]; - $d = $matches[3]; - } - if (preg_match("/(\d{2}):(\d{2}):(\d{2})/", $start_time, $matches)) - { - $h = $matches[1]; - $i = $matches[2]; - $s = $matches[3]; - } - $this->start_date = sprintf('%04d%02d%02d%02d%02d%02d', $y, $m, $d, $h, $i, $s); - } - -/** -* Gets the end date of the survey -* -* @return string Survey end date (YYYY-MM-DD) -* @access public -* @see $end_date -*/ - function getEndDate() - { - return (strlen($this->end_date)) ? $this->end_date : NULL; - } - -/** -* Sets the end date of the survey -* -* @param string $end_date Survey end date (YYYYMMDDHHMMSS) -* @access public -* @see $end_date -*/ - function setEndDate($end_date = "") - { - $this->end_date = $end_date; - } - - /** - * Sets the end date of the survey - * - * @param string $end_date Survey end date (YYYY-MM-DD) - * @param string $end_time Survey end time (HH:MM:SS) - * @access public - * @see $start_date - */ - function setEndDateAndTime($end_date = "", $end_time) - { - $y = ''; $m = ''; $d = ''; $h = ''; $i = ''; $s = ''; - if (preg_match("/(\d{4})-(\d{2})-(\d{2})/", $end_date, $matches)) - { - $y = $matches[1]; - $m = $matches[2]; - $d = $matches[3]; - } - if (preg_match("/(\d{2}):(\d{2}):(\d{2})/", $end_time, $matches)) - { - $h = $matches[1]; - $i = $matches[2]; - $s = $matches[3]; - } - $this->end_date = sprintf('%04d%02d%02d%02d%02d%02d', $y, $m, $d, $h, $i, $s); - } - -/** -* Gets the learners evaluation access -* -* @return integer The evaluation access -* @access public -* @see $evaluation_access -*/ - function getEvaluationAccess() - { - return ($this->evaluation_access) ? $this->evaluation_access : self::EVALUATION_ACCESS_OFF; - } - -/** -* Sets the learners evaluation access -* -* @param integer $evaluation_access The evaluation access -* @access public -* @see $evaluation_access -*/ - function setEvaluationAccess($evaluation_access = self::EVALUATION_ACCESS_OFF) - { - $this->evaluation_access = ($evaluation_access) ? $evaluation_access : self::EVALUATION_ACCESS_OFF; - } - - function setActivationVisibility($a_value) - { - $this->activation_visibility = (bool) $a_value; - } - - function getActivationVisibility() - { - return $this->activation_visibility; - } - - function isActivationLimited() - { - return (bool)$this->activation_limited; - } - - function setActivationLimited($a_value) - { - $this->activation_limited = (bool)$a_value; - } - -/** -* Gets the introduction text -* -* @return string The introduction of the survey object -* @access public -* @see $introduction -*/ - function getIntroduction() - { - return (strlen($this->introduction)) ? $this->introduction : NULL; - } - -/** -* Gets the outro text -* -* @return string The outro of the survey object -* @access public -* @see $outro -*/ - function getOutro() - { - return (strlen($this->outro)) ? $this->outro : NULL; - } - -/** -* Gets the question id's of the questions which are already in the survey -* -* @return array The questions of the survey -* @access public -*/ - function &getExistingQuestions() - { - $ilDB = $this->db; - $existing_questions = array(); - $result = $ilDB->queryF("SELECT svy_question.original_id FROM svy_question, svy_svy_qst WHERE " . - "svy_svy_qst.survey_fi = %s AND svy_svy_qst.question_fi = svy_question.question_id", - array('integer'), - array($this->getSurveyId()) - ); - while ($data = $ilDB->fetchAssoc($result)) - { - if($data["original_id"]) - { - array_push($existing_questions, $data["original_id"]); - } - } - return $existing_questions; - } - -/** -* Get the titles of all available survey question pools -* -* @return array An array of survey question pool titles -* @access public -*/ - function &getQuestionpoolTitles($could_be_offline = FALSE, $showPath = FALSE) - { - include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"; - return ilObjSurveyQuestionPool::_getAvailableQuestionpools($use_object_id = TRUE, $could_be_offline, $showPath); - } - -/** -* Move questions and/or questionblocks to another position -* -* @param array $move_questions An array with the question id's of the questions to move -* @param integer $target_index The question id of the target position -* @param integer $insert_mode 0, if insert before the target position, 1 if insert after the target position -* @access public -*/ - function moveQuestions($move_questions, $target_index, $insert_mode) - { - $array_pos = array_search($target_index, $this->questions); - if ($insert_mode == 0) - { - $part1 = array_slice($this->questions, 0, $array_pos); - $part2 = array_slice($this->questions, $array_pos); - } - else if ($insert_mode == 1) - { - $part1 = array_slice($this->questions, 0, $array_pos + 1); - $part2 = array_slice($this->questions, $array_pos + 1); - } - foreach ($move_questions as $question_id) - { - if (!(array_search($question_id, $part1) === FALSE)) - { - unset($part1[array_search($question_id, $part1)]); - } - if (!(array_search($question_id, $part2) === FALSE)) - { - unset($part2[array_search($question_id, $part2)]); - } - } - $part1 = array_values($part1); - $part2 = array_values($part2); - $this->questions = array_values(array_merge($part1, $move_questions, $part2)); - foreach ($move_questions as $question_id) - { - $constraints = $this->getConstraints($question_id); - foreach ($constraints as $idx => $constraint) - { - foreach ($part2 as $next_question_id) - { - if ($constraint["question"] == $next_question_id) - { - // constraint concerning a question that follows -> delete constraint - $this->deleteConstraint($constraint["id"]); - } - } - } - } - $this->saveQuestionsToDb(); - } - -/** -* Remove a question from the survey -* -* @param integer $question_id The database id of the question -* @access public -*/ - function removeQuestion($question_id) - { - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - $question = self::_instanciateQuestion($question_id); - #20610 if no question found, do nothing. - if($question) - { - $question->delete($question_id); - $this->removeConstraintsConcerningQuestion($question_id); - } - } - -/** -* Remove constraints concerning a question with a given question_id -* -* @param integer $question_id The database id of the question -* @access public -*/ - function removeConstraintsConcerningQuestion($question_id) - { - $ilDB = $this->db; - $result = $ilDB->queryF("SELECT constraint_fi FROM svy_qst_constraint WHERE question_fi = %s AND survey_fi = %s", - array('integer','integer'), - array($question_id, $this->getSurveyId()) - ); - if ($result->numRows() > 0) - { - $remove_constraints = array(); - while ($row = $ilDB->fetchAssoc($result)) - { - array_push($remove_constraints, $row["constraint_fi"]); - } - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qst_constraint WHERE question_fi = %s AND survey_fi = %s", - array('integer','integer'), - array($question_id, $this->getSurveyId()) - ); - foreach ($remove_constraints as $key => $constraint_id) - { - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_constraint WHERE constraint_id = %s", - array('integer'), - array($constraint_id) - ); - } - } - } - -/** -* Remove questions from the survey -* -* @param array $remove_questions An array with the question id's of the questions to remove -* @param array $remove_questionblocks An array with the questionblock id's of the questions blocks to remove -* @access public -*/ - function removeQuestions($remove_questions, $remove_questionblocks) - { - $ilDB = $this->db; - - $block_sizes = array(); - foreach ($this->getSurveyQuestions() as $question_id => $data) - { - if (in_array($question_id, $remove_questions) or in_array($data["questionblock_id"], $remove_questionblocks)) - { - unset($this->questions[array_search($question_id, $this->questions)]); - $this->removeQuestion($question_id); - } - else if($data["questionblock_id"]) - { - $block_sizes[$data["questionblock_id"]]++; - } - } - - // blocks with just 1 question need to be deleted - foreach($block_sizes as $block_id => $size) - { - if($size < 2) - { - $remove_questionblocks[] = $block_id; - } - } - - foreach (array_unique($remove_questionblocks) as $questionblock_id) - { - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk WHERE questionblock_id = %s", - array('integer'), - array($questionblock_id) - ); - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk_qst WHERE questionblock_fi = %s AND survey_fi = %s", - array('integer','integer'), - array($questionblock_id, $this->getSurveyId()) - ); - } - - $this->questions = array_values($this->questions); - $this->saveQuestionsToDb(); - } - -/** -* Unfolds question blocks of a question pool -* -* @param array $questionblocks An array of question block id's -* @access public -*/ - function unfoldQuestionblocks($questionblocks) - { - $ilDB = $this->db; - foreach ($questionblocks as $index) - { - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk WHERE questionblock_id = %s", - array('integer'), - array($index) - ); - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk_qst WHERE questionblock_fi = %s AND survey_fi = %s", - array('integer','integer'), - array($index, $this->getSurveyId()) - ); - } - } - - function removeQuestionFromBlock($question_id, $questionblock_id) - { - $ilDB = $this->db; - - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk_qst WHERE questionblock_fi = %s AND survey_fi = %s AND question_fi = %s", - array('integer','integer','integer'), - array($questionblock_id, $this->getSurveyId(), $question_id) - ); - } - - function addQuestionToBlock($question_id, $questionblock_id) - { - $ilDB = $this->db; - - // see #22018 - if (!$this->isQuestionInAnyBlock($question_id)) - { - $next_id = $ilDB->nextId('svy_qblk_qst'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qblk_qst (qblk_qst_id, survey_fi, questionblock_fi, " . - "question_fi) VALUES (%s, %s, %s, %s)", - array('integer', 'integer', 'integer', 'integer'), - array($next_id, $this->getSurveyId(), $questionblock_id, $question_id) - ); - - $this->deleteConstraints($question_id); // #13713 - } - } - - /** - * Is question already in a block? - * - * @param int $a_question_fi question id as in svy_question - * @return bool - */ - function isQuestionInAnyBlock($a_question_fi) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT * FROM svy_qblk_qst ". - " WHERE survey_fi = ".$ilDB->quote($this->getSurveyId(), "integer"). - " AND question_fi = ".$ilDB->quote($a_question_fi, "integer")); - if ($rec = $ilDB->fetchAssoc($set)) - { - return true; - } - return false; - } - - -/** -* Returns the question titles of all questions of a question block -* -* @result array The titles of the the question block questions -* @access public -*/ - function &getQuestionblockQuestions($questionblock_id) - { - $ilDB = $this->db; - $titles = array(); - $result = $ilDB->queryF("SELECT svy_question.title, svy_qblk_qst.question_fi, svy_qblk_qst.survey_fi FROM ". - "svy_qblk, svy_qblk_qst, svy_question WHERE svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi AND " . - "svy_question.question_id = svy_qblk_qst.question_fi AND svy_qblk.questionblock_id = %s", - array('integer'), - array($questionblock_id) - ); - $survey_id = ""; - while ($row = $ilDB->fetchAssoc($result)) - { - $titles[$row["question_fi"]] = $row["title"]; - $survey_id = $row["survey_fi"]; - } - $result = $ilDB->queryF("SELECT question_fi, sequence FROM svy_svy_qst WHERE survey_fi = %s ORDER BY sequence", - array('integer'), - array($survey_id) - ); - $resultarray = array(); - $counter = 1; - while ($row = $ilDB->fetchAssoc($result)) - { - if (array_key_exists($row["question_fi"], $titles)) - { - $resultarray[$counter++] = $titles[$row["question_fi"]]; - } - } - return $resultarray; - } - -/** -* Returns the question id's of all questions of a question block -* -* @result array The id's of the the question block questions -* @access public -*/ - function &getQuestionblockQuestionIds($questionblock_id) - { - $ilDB = $this->db; - - // we need a correct order here, see #22011 - $result = $ilDB->queryF("SELECT a.question_fi FROM svy_qblk_qst a JOIN svy_svy_qst b ON (a.question_fi = b.question_fi) ". - " WHERE a.questionblock_fi = %s ORDER BY b.sequence", - array("integer"), - array($questionblock_id) - ); - $ids = array(); - if ($result->numRows()) - { - while ($data = $ilDB->fetchAssoc($result)) - { - if (!in_array($data['question_fi'], $ids)) // no duplicates, see #22018 - { - array_push($ids, $data['question_fi']); - } - } - } - - return $ids; - } - -/** -* Returns the database row for a given question block -* -* @param integer $questionblock_id The database id of the question block -* @result array The database row of the question block -* @access public -*/ - static function _getQuestionblock($questionblock_id) - { - global $DIC; - - $ilDB = $DIC->database(); - $result = $ilDB->queryF("SELECT * FROM svy_qblk WHERE questionblock_id = %s", - array('integer'), - array($questionblock_id) - ); - $row = $ilDB->fetchAssoc($result); - return $row; - } - -/** -* Adds a questionblock to the database -* -* @param string $title The questionblock title -* @param integer $owner The database id of the owner -* @return integer The database id of the newly created questionblock -* @access public -*/ - static function _addQuestionblock($title = "", $owner = 0, $show_questiontext = true, $show_blocktitle = false) - { - global $DIC; - - $ilDB = $DIC->database(); - $next_id = $ilDB->nextId('svy_qblk'); - $ilDB->manipulateF("INSERT INTO svy_qblk (questionblock_id, title, show_questiontext,". - " show_blocktitle, owner_fi, tstamp) " . - "VALUES (%s, %s, %s, %s, %s, %s)", - array('integer','text','integer','integer','integer','integer'), - array($next_id, $title, $show_questiontext, $show_blocktitle, $owner, time()) - ); - return $next_id; - } - -/** -* Creates a question block for the survey -* -* @param string $title The title of the question block -* @param array $questions An array with the database id's of the question block questions -* @access public -*/ - function createQuestionblock($title, $show_questiontext, $show_blocktitle, $questions) - { - $ilDB = $this->db; - - // if the selected questions are not in a continous selection, move all questions of the - // questionblock at the position of the first selected question - $this->moveQuestions($questions, $questions[0], 0); - - // now save the question block - $ilUser = $this->user; - $next_id = $ilDB->nextId('svy_qblk'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qblk (questionblock_id, title, show_questiontext,". - " show_blocktitle, owner_fi, tstamp) VALUES (%s, %s, %s, %s, %s, %s)", - array('integer','text','text','text','integer','integer'), - array($next_id, $title, $show_questiontext, $show_blocktitle, $ilUser->getId(), time()) - ); - if ($affectedRows) - { - $questionblock_id = $next_id; - foreach ($questions as $index) - { - if (!$this->isQuestionInAnyBlock($index)) - { - $next_id = $ilDB->nextId('svy_qblk_qst'); // #22018 - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qblk_qst (qblk_qst_id, survey_fi, questionblock_fi, " . - "question_fi) VALUES (%s, %s, %s, %s)", - array('integer', 'integer', 'integer', 'integer'), - array($next_id, $this->getSurveyId(), $questionblock_id, $index) - ); - $this->deleteConstraints($index); - } - } - } - } - -/** -* Modifies a question block -* -* @param integer $questionblock_id The database id of the question block -* @param string $title The title of the question block -* @access public -*/ - function modifyQuestionblock($questionblock_id, $title, $show_questiontext, $show_blocktitle) - { - $ilDB = $this->db; - $affectedRows = $ilDB->manipulateF("UPDATE svy_qblk SET title = %s, show_questiontext = %s,". - " show_blocktitle = %s WHERE questionblock_id = %s", - array('text','text','text','integer'), - array($title, $show_questiontext, $show_blocktitle, $questionblock_id) - ); - } - -/** -* Deletes the constraints for a question -* -* @param integer $question_id The database id of the question -* @access public -*/ - function deleteConstraints($question_id) - { - $ilDB = $this->db; - $result = $ilDB->queryF("SELECT constraint_fi FROM svy_qst_constraint WHERE question_fi = %s AND survey_fi = %s", - array('integer','integer'), - array($question_id, $this->getSurveyId()) - ); - $constraints = array(); - while ($row = $ilDB->fetchAssoc($result)) - { - array_push($constraints, $row["constraint_fi"]); - } - foreach ($constraints as $constraint_id) - { - $this->deleteConstraint($constraint_id); - } - } - -/** -* Deletes a constraint of a question -* -* @param integer $constraint_id The database id of the constraint -* @param integer $question_id The database id of the question -* @access public -*/ - function deleteConstraint($constraint_id) - { - $ilDB = $this->db; - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_constraint WHERE constraint_id = %s", - array('integer'), - array($constraint_id) - ); - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qst_constraint WHERE constraint_fi = %s", - array('integer'), - array($constraint_id) - ); - } - -/** -* Returns the survey questions and questionblocks in an array -* -* @access public -*/ - public function &getSurveyQuestions($with_answers = false) - { - $ilDB = $this->db; - // get questionblocks - $all_questions = array(); - $result = $ilDB->queryF("SELECT svy_qtype.type_tag, svy_qtype.plugin, svy_question.question_id, ". - "svy_svy_qst.heading FROM svy_qtype, svy_question, svy_svy_qst WHERE svy_svy_qst.survey_fi = %s AND " . - "svy_svy_qst.question_fi = svy_question.question_id AND svy_question.questiontype_fi = svy_qtype.questiontype_id " . - "ORDER BY svy_svy_qst.sequence", - array('integer'), - array($this->getSurveyId()) - ); - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - while ($row = $ilDB->fetchAssoc($result)) - { - $add = true; - if ($row["plugin"]) - { - if (!$this->isPluginActive($row["type_tag"])) - { - $add = false; - } - } - if ($add) - { - $question = self::_instanciateQuestion($row["question_id"]); - $questionrow = $question->getQuestionDataArray($row["question_id"]); - foreach ($row as $key => $value) - { - $questionrow[$key] = $value; - } - $all_questions[$row["question_id"]] = $questionrow; - $all_questions[$row["question_id"]]["usableForPrecondition"] = $question->usableForPrecondition(); - $all_questions[$row["question_id"]]["availableRelations"] = $question->getAvailableRelations(); - } - } - // get all questionblocks - $questionblocks = array(); - if (count($all_questions)) - { - $result = $ilDB->queryF("SELECT svy_qblk.*, svy_qblk_qst.question_fi FROM svy_qblk, svy_qblk_qst WHERE " . - "svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi AND svy_qblk_qst.survey_fi = %s " . - "AND " . $ilDB->in('svy_qblk_qst.question_fi', array_keys($all_questions), false, 'integer'), - array('integer'), - array($this->getSurveyId()) - ); - while ($row = $ilDB->fetchAssoc($result)) - { - $questionblocks[$row['question_fi']] = $row; - } - } - - foreach ($all_questions as $question_id => $row) - { - $constraints = $this->getConstraints($question_id); - if (isset($questionblocks[$question_id])) - { - $all_questions[$question_id]["questionblock_title"] = $questionblocks[$question_id]['title']; - $all_questions[$question_id]["questionblock_id"] = $questionblocks[$question_id]['questionblock_id']; - $all_questions[$question_id]["constraints"] = $constraints; - } - else - { - $all_questions[$question_id]["questionblock_title"] = ""; - $all_questions[$question_id]["questionblock_id"] = ""; - $all_questions[$question_id]["constraints"] = $constraints; - } - if ($with_answers) - { - $answers = array(); - $result = $ilDB->queryF("SELECT svy_variable.*, svy_category.title 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($question_id) - ); - if ($result->numRows() > 0) - { - while ($data = $ilDB->fetchAssoc($result)) - { - array_push($answers, $data["title"]); - } - } - $all_questions[$question_id]["answers"] = $answers; - } - } - return $all_questions; - } - -/** -* Sets the obligatory states for questions in a survey from the questions form -* -* @param array $obligatory_questions The questions which should be set obligatory from the questions form, the remaining questions should be setted not obligatory -* @access public -*/ - function setObligatoryStates($obligatory_questions) - { - $ilDB = $this->db; - $result = $ilDB->queryF("SELECT * FROM svy_svy_qst WHERE survey_fi = %s", - array('integer'), - array($this->getSurveyId()) - ); - if ($result->numRows()) - { - while ($row = $ilDB->fetchAssoc($result)) - { - if (!array_key_exists($row["question_fi"], $obligatory_questions)) - { - $obligatory_questions[$row["question_fi"]] = 0; - } - } - } - - // set the obligatory states in the database - foreach ($obligatory_questions as $question_fi => $obligatory) - { - // #12420 - $ilDB->manipulate("UPDATE svy_question". - " SET obligatory = ".$ilDB->quote($obligatory, "integer"). - " WHERE question_id = ".$ilDB->quote($question_fi, "integer")); - } - } - -/** -* Returns the survey pages in an array (a page contains one or more questions) -* -* @access public -*/ - function &getSurveyPages() - { - $ilDB = $this->db; - // get questionblocks - $all_questions = array(); - $result = $ilDB->queryF("SELECT svy_question.*, svy_qtype.type_tag, svy_svy_qst.heading FROM " . - "svy_question, svy_qtype, svy_svy_qst WHERE svy_svy_qst.survey_fi = %s AND " . - "svy_svy_qst.question_fi = svy_question.question_id AND svy_question.questiontype_fi = svy_qtype.questiontype_id ". - "ORDER BY svy_svy_qst.sequence", - array('integer'), - array($this->getSurveyId()) - ); - while ($row = $ilDB->fetchAssoc($result)) - { - $all_questions[$row["question_id"]] = $row; - } - // get all questionblocks - $questionblocks = array(); - if (count($all_questions)) - { - $result = $ilDB->queryF("SELECT svy_qblk.*, svy_qblk_qst.question_fi FROM svy_qblk, svy_qblk_qst ". - "WHERE svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi AND svy_qblk_qst.survey_fi = %s ". - "AND " . $ilDB->in('svy_qblk_qst.question_fi', array_keys($all_questions), false, 'integer'), - array('integer'), - array($this->getSurveyId()) - ); - while ($row = $ilDB->fetchAssoc($result)) - { - $questionblocks[$row['question_fi']] = $row; - } - } - - $all_pages = array(); - $pageindex = -1; - $currentblock = ""; - foreach ($all_questions as $question_id => $row) - { - $constraints = array(); - if (isset($questionblocks[$question_id])) - { - if (!$currentblock or ($currentblock != $questionblocks[$question_id]['questionblock_id'])) - { - $pageindex++; - } - $all_questions[$question_id]['page'] = $pageindex; - $all_questions[$question_id]["questionblock_title"] = $questionblocks[$question_id]['title']; - $all_questions[$question_id]["questionblock_id"] = $questionblocks[$question_id]['questionblock_id']; - $all_questions[$question_id]["questionblock_show_questiontext"] = $questionblocks[$question_id]['show_questiontext']; - $all_questions[$question_id]["questionblock_show_blocktitle"] = $questionblocks[$question_id]['show_blocktitle']; - $currentblock = $questionblocks[$question_id]['questionblock_id']; - $constraints = $this->getConstraints($question_id); - $all_questions[$question_id]["constraints"] = $constraints; - } - else - { - $pageindex++; - $all_questions[$question_id]['page'] = $pageindex; - $all_questions[$question_id]["questionblock_title"] = ""; - $all_questions[$question_id]["questionblock_id"] = ""; - $all_questions[$question_id]["questionblock_show_questiontext"] = 1; - $all_questions[$question_id]["questionblock_show_blocktitle"] = 1; - $currentblock = ""; - $constraints = $this->getConstraints($question_id); - $all_questions[$question_id]["constraints"] = $constraints; - } - if (!isset($all_pages[$pageindex])) - { - $all_pages[$pageindex] = array(); - } - array_push($all_pages[$pageindex], $all_questions[$question_id]); - } - // calculate position percentage for every page - $max = count($all_pages); - $counter = 1; - foreach ($all_pages as $index => $block) - { - foreach ($block as $blockindex => $question) - { - $all_pages[$index][$blockindex]["position"] = $counter / $max; - } - $counter++; - } - - return $all_pages; - } - -/** -* Returns the next "page" of a running test -* -* @param integer $active_page_question_id The database id of one of the questions on that page -* @param integer $direction The direction of the next page (-1 = previous page, 1 = next page) -* @return mixed An array containing the question id's of the questions on the next page if there is a next page, 0 if the next page is before the start page, 1 if the next page is after the last page -* @access public -*/ - function getNextPage($active_page_question_id, $direction) - { - $foundpage = -1; - $pages =& $this->getSurveyPages(); - if (strcmp($active_page_question_id, "") == 0) - { - return $pages[0]; - } - foreach ($pages as $key => $question_array) - { - foreach ($question_array as $question) - { - if ($active_page_question_id == $question["question_id"]) - { - $foundpage = $key; - } - } - } - if ($foundpage == -1) - { - // error: page not found - } - else - { - $foundpage += $direction; - if ($foundpage < 0) - { - return 0; - } - if ($foundpage >= count($pages)) - { - return 1; - } - return $pages[$foundpage]; - } - } - -/** -* Returns the available question pools for the active user -* -* @return array The available question pools -* @access public -*/ - function &getAvailableQuestionpools($use_obj_id = false, $could_be_offline = false, $showPath = FALSE, $permission = "read") - { - include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"; - return ilObjSurveyQuestionPool::_getAvailableQuestionpools($use_obj_id, $could_be_offline, $showPath, $permission); - } - - /** - * Returns a precondition with a given id - * - * @access public - */ - function getPrecondition($id) - { - $ilDB = $this->db; - - $result_array = array(); - $result = $ilDB->queryF("SELECT svy_constraint.*, svy_relation.*, svy_qst_constraint.question_fi ref_question_fi FROM svy_qst_constraint, svy_constraint, ". - "svy_relation WHERE svy_constraint.relation_fi = svy_relation.relation_id AND ". - "svy_qst_constraint.constraint_fi = svy_constraint.constraint_id AND svy_constraint.constraint_id = %s", - array('integer'), - array($id) - ); - $pc = array(); - if ($result->numRows()) - { - $pc = $ilDB->fetchAssoc($result); - } - return $pc; - } - -/** -* Returns the constraints to a given question or questionblock -* -* @access public -*/ - function getConstraints($question_id) - { - $ilDB = $this->db; - - $result_array = array(); - $result = $ilDB->queryF("SELECT svy_constraint.*, svy_relation.* FROM svy_qst_constraint, svy_constraint, svy_relation ". - "WHERE svy_constraint.relation_fi = svy_relation.relation_id AND ". - "svy_qst_constraint.constraint_fi = svy_constraint.constraint_id AND svy_qst_constraint.question_fi = %s ". - "AND svy_qst_constraint.survey_fi = %s", - array('integer','integer'), - array($question_id, $this->getSurveyId()) - ); - while ($row = $ilDB->fetchAssoc($result)) - { - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - $question_type = SurveyQuestion::_getQuestionType($row["question_fi"]); - SurveyQuestion::_includeClass($question_type); - $question = new $question_type(); - $question->loadFromDb($row["question_fi"]); - $valueoutput = $question->getPreconditionValueOutput($row["value"]); - array_push($result_array, array("id" => $row["constraint_id"], "question" => $row["question_fi"], "short" => $row["shortname"], "long" => $row["longname"], "value" => $row["value"], "conjunction" => $row["conjunction"], "valueoutput" => $valueoutput)); - } - return $result_array; - } - -/** -* Returns the constraints to a given question or questionblock -* -* @access public -*/ - static function _getConstraints($survey_id) - { - global $DIC; - - $ilDB = $DIC->database(); - $result_array = array(); - $result = $ilDB->queryF("SELECT svy_qst_constraint.question_fi as for_question, svy_constraint.*, svy_relation.* ". - "FROM svy_qst_constraint, svy_constraint, svy_relation WHERE svy_constraint.relation_fi = svy_relation.relation_id ". - "AND svy_qst_constraint.constraint_fi = svy_constraint.constraint_id AND svy_qst_constraint.survey_fi = %s", - array('integer'), - array($survey_id) - ); - while ($row = $ilDB->fetchAssoc($result)) - { - array_push($result_array, array("id" => $row["constraint_id"], "for_question" => $row["for_question"], "question" => $row["question_fi"], "short" => $row["shortname"], "long" => $row["longname"], "relation_id" => $row["relation_id"], "value" => $row["value"], 'conjunction' => $row['conjunction'])); - } - return $result_array; - } - - -/** -* Returns all variables of a question -* -* @access public -*/ - function &getVariables($question_id) - { - $ilDB = $this->db; - - $result_array = array(); - $result = $ilDB->queryF("SELECT svy_variable.*, svy_category.title FROM svy_variable LEFT JOIN ". - "svy_category ON svy_variable.category_fi = svy_category.category_id WHERE svy_variable.question_fi = %s ". - "ORDER BY svy_variable.sequence", - array('integer'), - array($question_id) - ); - while ($row = $ilDB->fetchObject($result)) - { - $result_array[$row->sequence] = $row; - } - return $result_array; - } - - /** - * Adds a constraint - * - * @param integer $if_question_id The question id of the question which defines a precondition - * @param integer $relation The database id of the relation - * @param mixed $value The value compared with the relation - * @access public - */ - function addConstraint($if_question_id, $relation, $value, $conjunction) - { - $ilDB = $this->db; - - $next_id = $ilDB->nextId('svy_constraint'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_constraint (constraint_id, question_fi, relation_fi, value, conjunction) VALUES ". - "(%s, %s, %s, %s, %s)", - array('integer','integer','integer','float', 'integer'), - array($next_id, $if_question_id, $relation, $value, $conjunction) - ); - if ($affectedRows) - { - return $next_id; - } - else - { - return null; - } - } - - -/** -* Adds a constraint to a question -* -* @param integer $to_question_id The question id of the question where to add the constraint -* @param integer $constraint_id The id of the constraint -*/ - public function addConstraintToQuestion($to_question_id, $constraint_id) - { - $ilDB = $this->db; - - $next_id = $ilDB->nextId('svy_qst_constraint'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qst_constraint (question_constraint_id, survey_fi, question_fi, ". - "constraint_fi) VALUES (%s, %s, %s, %s)", - array('integer','integer','integer','integer'), - array($next_id, $this->getSurveyId(), $to_question_id, $constraint_id) - ); - } - - /** - * Updates a precondition - * - * @param integer $precondition_id The id of the original precondition - * @param integer $to_question_id The question id of the question where to add the constraint - * @param integer $if_question_id The question id of the question which defines a precondition - * @param integer $relation The database id of the relation - * @param mixed $value The value compared with the relation - * @access public - */ - function updateConstraint($precondition_id, $if_question_id, $relation, $value, $conjunction) - { - $ilDB = $this->db; - $affectedRows = $ilDB->manipulateF("UPDATE svy_constraint SET question_fi = %s, relation_fi = %s, value = %s, conjunction = %s ". - "WHERE constraint_id = %s", - array('integer','integer','float','integer','integer'), - array($if_question_id, $relation, $value, $conjunction, $precondition_id) - ); - } - - public function updateConjunctionForQuestions($questions, $conjunction) - { - $ilDB = $this->db; - foreach ($questions as $question_id) - { - $affectedRows = $ilDB->manipulateF("UPDATE svy_constraint SET conjunction = %s ". - "WHERE constraint_id IN (SELECT constraint_fi FROM svy_qst_constraint WHERE svy_qst_constraint.question_fi = %s)", - array('integer','integer'), - array($conjunction, $question_id) - ); - } - } - -/** -* Returns all available relations -* -* @access public -*/ - function getAllRelations($short_as_key = false) - { - $ilDB = $this->db; - - // #7987 - $custom_order = array("equal", "not_equal", "less", "less_or_equal", "more", "more_or_equal"); - $custom_order = array_flip($custom_order); - - $result_array = array(); - $result = $ilDB->query("SELECT * FROM svy_relation"); - while ($row = $ilDB->fetchAssoc($result)) - { - if ($short_as_key) - { - $result_array[$row["shortname"]] = array("short" => $row["shortname"], "long" => $row["longname"], "id" => $row["relation_id"], "order" => $custom_order[$row["longname"]]); - } - else - { - $result_array[$row["relation_id"]] = array("short" => $row["shortname"], "long" => $row["longname"], "order" => $custom_order[$row["longname"]]); - } - } - - $result_array = ilUtil::sortArray($result_array, "order", "ASC", true, true); - foreach($result_array as $idx => $item) - { - unset($result_array[$idx]["order"]); - } - - return $result_array; - } - - /** - * Disinvite all users - */ - public function disinviteAllUsers() - { - $ilDB = $this->db; - $result = $ilDB->queryF("SELECT user_fi FROM svy_inv_usr WHERE survey_fi = %s", - array('integer'), - array($this->getSurveyId()) - ); - while ($row = $ilDB->fetchAssoc($result)) - { - $this->disinviteUser($row['user_fi']); - } - } - -/** -* Disinvites a user from a survey -* -* @param integer $user_id The database id of the disinvited user -*/ - public function disinviteUser($user_id) - { - $ilDB = $this->db; - - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_inv_usr WHERE survey_fi = %s AND user_fi = %s", - array('integer','integer'), - array($this->getSurveyId(), $user_id) - ); - include_once './Services/User/classes/class.ilObjUser.php'; - ilObjUser::_dropDesktopItem($user_id, $this->getRefId(), "svy"); - } - -/** -* Invites a user to a survey -* -* @param integer $user_id The database id of the invited user -* @access public -*/ - function inviteUser($user_id) - { - $ilDB = $this->db; - - $result = $ilDB->queryF("SELECT user_fi FROM svy_inv_usr WHERE user_fi = %s AND survey_fi = %s", - array('integer','integer'), - array($user_id, $this->getSurveyId()) - ); - if ($result->numRows() < 1) - { - $next_id = $ilDB->nextId('svy_inv_usr'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_inv_usr (invited_user_id, survey_fi, user_fi, tstamp) " . - "VALUES (%s, %s, %s, %s)", - array('integer','integer','integer','integer'), - array($next_id, $this->getSurveyId(), $user_id, time()) - ); - } - if ($this->getInvitation() == self::INVITATION_ON) - { - include_once './Services/User/classes/class.ilObjUser.php'; - ilObjUser::_addDesktopItem($user_id, $this->getRefId(), "svy"); - } - } - -/** -* Returns a list of all invited users in a survey -* -* @return array The user id's of the invited users -* @access public -*/ - function &getInvitedUsers() - { - $ilDB = $this->db; - - $result_array = array(); - $result = $ilDB->queryF("SELECT user_fi FROM svy_inv_usr WHERE survey_fi = %s", - array('integer'), - array($this->getSurveyId()) - ); - while ($row = $ilDB->fetchAssoc($result)) - { - array_push($result_array, $row["user_fi"]); - } - return $result_array; - } - -/** -* Deletes the working data of a question in the database -* -* @param integer $question_id The database id of the question -* @param integer $active_id The active id of the user who worked through the question -* @access public -*/ - function deleteWorkingData($question_id, $active_id) - { - $ilDB = $this->db; - - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_answer WHERE question_fi = %s AND active_fi = %s", - array('integer','integer'), - array($question_id, $active_id) - ); - } - -/** -* Gets the working data of question from the database -* -* @param integer $question_id The database id of the question -* @param integer $active_id The active id of the user who worked through the question -* @return array The resulting database dataset as an array -* @access public -*/ - function loadWorkingData($question_id, $active_id) - { - $ilDB = $this->db; - $result_array = array(); - $result = $ilDB->queryF("SELECT * FROM svy_answer WHERE question_fi = %s AND active_fi = %s", - array('integer','integer'), - array($question_id, $active_id) - ); - if ($result->numRows() >= 1) - { - while ($row = $ilDB->fetchAssoc($result)) - { - array_push($result_array, $row); - } - return $result_array; - } - else - { - return $result_array; - } - } - -/** -* Starts the survey creating an entry in the database -* -* @param integer $user_id The database id of the user who starts the survey -* @access public -*/ - function startSurvey($user_id, $anonymous_id, $appraisee_id) - { - $ilDB = $this->db; - - if ($this->getAnonymize() && (strlen($anonymous_id) == 0)) return; - - if (strcmp($user_id, "") == 0) - { - if ($user_id == ANONYMOUS_USER_ID) - { - $user_id = 0; - } - } - $next_id = $ilDB->nextId('svy_finished'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_finished (finished_id, survey_fi, user_fi, anonymous_id, state, tstamp, appr_id) ". - "VALUES (%s, %s, %s, %s, %s, %s, %s)", - array('integer','integer','integer','text','text','integer','integer'), - array($next_id, $this->getSurveyId(), $user_id, $anonymous_id, 0, time(), $appraisee_id) - ); - return $next_id; - } - -/** -* Finishes the survey creating an entry in the database -* -* @param integer $user_id The database id of the user who finishes the survey -* @access public -*/ - function finishSurvey($finished_id) - { - $ilDB = $this->db; - - $ilDB->manipulateF("UPDATE svy_finished SET state = %s, tstamp = %s". - " WHERE survey_fi = %s AND finished_id = %s", - array('text','integer','integer','integer'), - array(1, time(), $this->getSurveyId(), $finished_id) - ); - - // self eval writes skills on finishing - if ($this->getMode() == ilObjSurvey::MODE_SELF_EVAL) - { - $user = $this->getUserDataFromActiveId($finished_id); - $sskill = new ilSurveySkill($this); - $sskill->writeSelfEvalSkills($user['usr_id']); - } - - $this->checkTutorNotification(); - } - - /** - * Sets the number of the active survey page - * - * @param integer $finished_id The database id of the active user - * @param integer $page_id The index of the page - * @access public - */ - function setPage($finished_id, $page_id) - { - $ilDB = $this->db; - - $affectedRows = $ilDB->manipulateF("UPDATE svy_finished SET lastpage = %s WHERE finished_id = %s", - array('integer','integer'), - array(($page_id) ? $page_id : 0, $finished_id) - ); - } - - /** - * @param $a_user_id user who did the survey - * @param $a_anonymize_id - * @param $a_appr_id - */ - function sendNotificationMail($a_user_id, $a_anonymize_id, $a_appr_id) - { - // #12755 - $placeholders = array( - "FIRST_NAME" => "firstname", - "LAST_NAME" => "lastname", - "LOGIN" => "login", - // old style - "firstname" => "firstname" - ); - - //mailaddresses is just text split by commas. - //sendMail can send emails if it gets an user id or an email as first parameter. - $recipients = preg_split('/,/', $this->mailaddresses); - foreach ($recipients as $recipient) - { - // #11298 - $ntf = new ilSystemNotification(); - $ntf->setLangModules(array("survey")); - $ntf->setRefId($this->getRefId()); - $ntf->setSubjectLangId('finished_mail_subject'); - - $messagetext = $this->mailparticipantdata; - if(trim($messagetext)) - { - if (!$this->hasAnonymizedResults()) - { - $data = ilObjUser::_getUserData(array($a_user_id)); - $data = $data[0]; - } - foreach ($placeholders as $key => $mapping) - { - if ($this->hasAnonymizedResults()) // #16480 - { - $messagetext = str_replace('[' . $key . ']', '', $messagetext); - } - else - { - $messagetext = str_replace('[' . $key . ']', trim($data[$mapping]), $messagetext); - } - } - $ntf->setIntroductionDirect($messagetext); - } - else - { - $ntf->setIntroductionLangId('survey_notification_finished_introduction'); - } - - // 360°? add appraisee data - if($a_appr_id) - { - $ntf->addAdditionalInfo('survey_360_appraisee', - ilUserUtil::getNamePresentation($a_appr_id)); - } - - $active_id = $this->getActiveID($a_user_id, $a_anonymize_id, $a_appr_id); - $ntf->addAdditionalInfo('results', - $this->getParticipantTextResults($active_id), true); - - $ntf->setGotoLangId('survey_notification_tutor_link'); - $ntf->setReasonLangId('survey_notification_finished_reason'); - - if(is_numeric($recipient)) - { - $lng = $ntf->getUserLanguage($recipient); - $ntf->sendMail(array($recipient), null, null); - } - else - { - $recipient = trim($recipient); - $user_ids = ilObjUser::getUserIdsByEmail($recipient); - if(empty($user_ids)) - { - $ntf->sendMail(array($recipient), null, null); - } - else - { - foreach($user_ids as $user_id) - { - $lng = $ntf->getUserLanguage($user_id); - $ntf->sendMail(array($user_id), null, null); - } - } - - } - - } - } - - protected function getParticipantTextResults($active_id) - { - $textresult = ""; - $userResults =& $this->getUserSpecificResults(array($active_id)); - $questions =& $this->getSurveyQuestions(true); - $questioncounter = 1; - foreach ($questions as $question_id => $question_data) - { - $textresult .= $questioncounter++ . ". " . $question_data["title"] . "\n"; - $found = $userResults[$question_id][$active_id]; - $text = ""; - if (is_array($found)) - { - $text = implode("\n", $found); - } - else - { - $text = $found; - } - if (strlen($text) == 0) $text = self::getSurveySkippedValue(); - $text = str_replace("
", "\n", $text); - $textresult .= $text . "\n\n"; - } - return $textresult; - } - -/** -* Checks if a user already started a survey -* -* @param integer $user_id The database id of the user -* @return mixed false, if the user has not started the survey, 0 if the user has started the survey but not finished it, 1 if the user has finished the survey -* @access public -*/ - function isSurveyStarted($user_id, $anonymize_id, $appr_id = 0) - { - $ilDB = $this->db; - - // #15031 - should not matter if code was used by registered or anonymous (each code must be unique) - if($anonymize_id) - { - $result = $ilDB->queryF("SELECT * FROM svy_finished". - " WHERE survey_fi = %s AND anonymous_id = %s AND appr_id = %s", - array('integer','text','integer'), - array($this->getSurveyId(), $anonymize_id, $appr_id) - ); - } - else - { - $result = $ilDB->queryF("SELECT * FROM svy_finished". - " WHERE survey_fi = %s AND user_fi = %s AND appr_id = %s", - array('integer','integer','integer'), - array($this->getSurveyId(), $user_id, $appr_id) - ); - } - if ($result->numRows() == 0) - { - return false; - } - else - { - $row = $ilDB->fetchAssoc($result); - // yes, we are doing it this way - $_SESSION["finished_id"][$this->getId()] = $row["finished_id"]; - - return (int)$row["state"]; - } - } - - /** - * Checks if a user already started a survey - * - * @param integer $user_id The database id of the user - * @return mixed false, if the user has not started the survey, 0 if the user has started the survey but not finished it, 1 if the user has finished the survey - * @access public - */ - function getActiveID($user_id, $anonymize_id, $appr_id) - { - $ilDB = $this->db; - - // see self::isSurveyStarted() - - // #15031 - should not matter if code was used by registered or anonymous (each code must be unique) - if($anonymize_id) - { - $result = $ilDB->queryF("SELECT finished_id FROM svy_finished". - " WHERE survey_fi = %s AND anonymous_id = %s AND appr_id = %s", - array('integer','text','integer'), - array($this->getSurveyId(), $anonymize_id, $appr_id) - ); - } - else - { - $result = $ilDB->queryF("SELECT finished_id FROM svy_finished". - " WHERE survey_fi = %s AND user_fi = %s AND appr_id = %s", - array('integer','integer','integer'), - array($this->getSurveyId(), $user_id, $appr_id) - ); - } - if ($result->numRows() == 0) - { - return false; - } - else - { - $row = $ilDB->fetchAssoc($result); - return $row["finished_id"]; - } - } - -/** -* Returns the question id of the last active page a user visited in a survey -* -* @param integer $active_id The active id of the user -* @return mixed Empty string if the user has not worked through a page, question id of the last page otherwise -* @access public -*/ - function getLastActivePage($active_id) - { - $ilDB = $this->db; - $result = $ilDB->queryF("SELECT lastpage FROM svy_finished WHERE finished_id = %s", - array('integer'), - array($active_id) - ); - if ($result->numRows() == 0) - { - return ""; - } - else - { - $row = $ilDB->fetchAssoc($result); - return ($row["lastpage"]) ? $row["lastpage"] : ''; - } - } - -/** -* Checks if a constraint is valid -* -* @param array $constraint_data The database row containing the constraint data -* @param array $working_data The user input of the related question -* @return boolean true if the constraint is valid, otherwise false -* @access public -*/ - function checkConstraint($constraint_data, $working_data) - { - if (count($working_data) == 0) - { - return 0; - } - - if ((count($working_data) == 1) and (strcmp($working_data[0]["value"], "") == 0)) - { - return 0; - } - - $found = false; - foreach ($working_data as $data) - { - switch ($constraint_data["short"]) - { - case "<": - if ($data["value"] < $constraint_data["value"]) - { - $found = true; - } - break; - - case "<=": - if ($data["value"] <= $constraint_data["value"]) - { - $found = true; - } - break; - - case "=": - if ($data["value"] == $constraint_data["value"]) - { - $found = true; - } - break; - - case "<>": - if ($data["value"] <> $constraint_data["value"]) - { - $found = true; - } - break; - - case ">=": - if ($data["value"] >= $constraint_data["value"]) - { - $found = true; - } - break; - - case ">": - if ($data["value"] > $constraint_data["value"]) - { - $found = true; - } - break; - } - if ($found) - { - break; - } - } - - return (int)$found; - } - - static function _hasDatasets($survey_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s", - array('integer'), - array($survey_id) - ); - return ($result->numRows()) ? true : false; - } - - /** - * Get the finished id's of all survey participants - * - * @return array An array containing finished_id's of all survey participants - * @access public - */ - function &getSurveyFinishedIds() - { - $ilDB = $this->db; - $ilLog = $this->log; - - $users = array(); - $result = $ilDB->queryF("SELECT * FROM svy_finished WHERE survey_fi = %s", - array('integer'), - array($this->getSurveyId()) - ); - if ($result->numRows()) - { - while ($row = $ilDB->fetchAssoc($result)) - { - array_push($users, $row["finished_id"]); - } - } - return $users; - } - - /** - * Calculates the evaluation data for the user specific results - * - * @return array An array containing the user specific results - * @access public - */ - function getUserSpecificResults($finished_ids) - { - $evaluation = array(); - - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - foreach (array_keys($this->getSurveyQuestions()) as $question_id) - { - // get question instance - $question_type = SurveyQuestion::_getQuestionType($question_id); - SurveyQuestion::_includeClass($question_type); - $question = new $question_type(); - $question->loadFromDb($question_id); - - $q_eval = SurveyQuestion::_instanciateQuestionEvaluation($question_id, $finished_ids); - $q_res = $q_eval->getResults(); - - $data = array(); - foreach($finished_ids as $user_id) - { - $data[$user_id] = $q_eval->parseUserSpecificResults($q_res, $user_id); - } - - $evaluation[$question_id] = $data; - } - - return $evaluation; - } - - /** - * Returns the user information from an active_id (survey_finished.finished_id) - * - * @param integer $active_id The active id of the user - * @return array An array containing the user data - * @access public - */ - function getUserDataFromActiveId($active_id, $force_non_anonymous = false) - { - $ilDB = $this->db; - - $surveySetting = new ilSetting("survey"); - $use_anonymous_id = array_key_exists("use_anonymous_id", $_GET) ? $_GET["use_anonymous_id"] : $surveySetting->get("use_anonymous_id"); - $result = $ilDB->queryF("SELECT * FROM svy_finished WHERE finished_id = %s", - array('integer'), - array($active_id) - ); - $row = array(); - $foundrows = $result->numRows(); - if ($foundrows) - { - $row = $ilDB->fetchAssoc($result); - } - $name = ($use_anonymous_id) ? $row["anonymous_id"] : $this->lng->txt("anonymous"); - $userdata = array( - "fullname" => $name, - "sortname" => $name, - "firstname" => "", - "lastname" => "", - "login" => "", - "gender" => "", - "active_id" => "$active_id" - ); - if ($foundrows) - { - if (($row["user_fi"] > 0) && - (($row["user_fi"] != ANONYMOUS_USER_ID && - !$this->hasAnonymizedResults() && - !$this->get360Mode()) || // 360° uses ANONYMIZE_CODE_ALL which is wrong - see ilObjSurveyGUI::afterSave() - (bool)$force_non_anonymous)) - { - include_once './Services/User/classes/class.ilObjUser.php'; - if (strlen(ilObjUser::_lookupLogin($row["user_fi"])) == 0) - { - $userdata["fullname"] = $userdata["sortname"] = $this->lng->txt("deleted_user"); - } - else - { - $user = new ilObjUser($row["user_fi"]); - $userdata['usr_id'] = $row['user_fi']; - $userdata["fullname"] = $user->getFullname(); - $gender = $user->getGender(); - if (strlen($gender) == 1) $gender = $this->lng->txt("gender_$gender"); - $userdata["gender"] = $gender; - $userdata["firstname"] = $user->getFirstname(); - $userdata["lastname"] = $user->getLastname(); - $userdata["sortname"] = $user->getLastname() . ", " . $user->getFirstname(); - $userdata["login"] = $user->getLogin(); - } - } - } - return $userdata; - } - -/** -* Calculates the evaluation data for a given user or anonymous id -* -* @param array $questions An array containing all relevant information on the survey's questions -* @param integer $user_id The database id of the user -* @param string $anonymous_id The unique anonymous id for an anonymous survey -* @return array An array containing the evaluation parameters for the user -* @access public -*/ - function &getEvaluationByUser($questions, $active_id) - { - $ilDB = $this->db; - - // collect all answers - $answers = array(); - $result = $ilDB->queryF("SELECT * FROM svy_answer WHERE active_fi = %s", - array('integer'), - array($active_id) - ); - while ($row = $ilDB->fetchAssoc($result)) - { - if (!is_array($answers[$row["question_fi"]])) - { - $answers[$row["question_fi"]] = array(); - } - array_push($answers[$row["question_fi"]], $row); - } - $userdata = $this->getUserDataFromActiveId($active_id); - $resultset = array( - "name" => $userdata["fullname"], - "firstname" => $userdata["firstname"], - "lastname" => $userdata["lastname"], - "login" => $userdata["login"], - "gender" => $userdata["gender"], - "answers" => array() - ); - foreach ($questions as $key => $question) - { - if (array_key_exists($key, $answers)) - { - $resultset["answers"][$key] = $answers[$key]; - } - else - { - $resultset["answers"][$key] = array(); - } - sort($resultset["answers"][$key]); - } - return $resultset; - } - -/** -* Calculates the data for the output of the question browser -* -* @access public -*/ - function getQuestionsTable($arrFilter) - { - $ilUser = $this->user; - $ilDB = $this->db; - $where = ""; - if (is_array($arrFilter)) - { - if (array_key_exists('title', $arrFilter) && strlen($arrFilter['title'])) - { - $where .= " AND " . $ilDB->like('svy_question.title', 'text', "%%" . $arrFilter['title'] . "%%"); - } - if (array_key_exists('description', $arrFilter) && strlen($arrFilter['description'])) - { - $where .= " AND " . $ilDB->like('svy_question.description', 'text', "%%" . $arrFilter['description'] . "%%"); - } - if (array_key_exists('author', $arrFilter) && strlen($arrFilter['author'])) - { - $where .= " AND " . $ilDB->like('svy_question.author', 'text', "%%" . $arrFilter['author'] . "%%"); - } - if (array_key_exists('type', $arrFilter) && strlen($arrFilter['type'])) - { - $where .= " AND svy_qtype.type_tag = " . $ilDB->quote($arrFilter['type'], 'text'); - } - if (array_key_exists('spl', $arrFilter) && strlen($arrFilter['spl'])) - { - $where .= " AND svy_question.obj_fi = " . $ilDB->quote($arrFilter['spl'], 'integer'); - } - } - - $spls =& $this->getAvailableQuestionpools($use_obj_id = TRUE, $could_be_offline = FALSE, $showPath = FALSE); - $forbidden = ""; - $forbidden = " AND " . $ilDB->in('svy_question.obj_fi', array_keys($spls), false, 'integer'); - $forbidden .= " AND svy_question.complete = " . $ilDB->quote("1", 'text'); - $existing = ""; - $existing_questions =& $this->getExistingQuestions(); - if (count($existing_questions)) - { - $existing = " AND " . $ilDB->in('svy_question.question_id', $existing_questions, true, 'integer'); - } - - include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"; - $trans = ilObjSurveyQuestionPool::_getQuestionTypeTranslations(); - - $query_result = $ilDB->query("SELECT svy_question.*, svy_qtype.type_tag, svy_qtype.plugin, object_reference.ref_id". - " FROM svy_question, svy_qtype, object_reference". - " WHERE svy_question.original_id IS NULL".$forbidden.$existing. - " AND svy_question.obj_fi = object_reference.obj_id AND svy_question.tstamp > 0". - " AND svy_question.questiontype_fi = svy_qtype.questiontype_id " . $where); - - $rows = array(); - if ($query_result->numRows()) - { - while ($row = $ilDB->fetchAssoc($query_result)) - { - if (array_key_exists('spl_txt', $arrFilter) && strlen($arrFilter['spl_txt'])) - { - if(!stristr($spls[$row["obj_fi"]], $arrFilter['spl_txt'])) - { - continue; - } - } - - $row['ttype'] = $trans[$row['type_tag']]; - if ($row["plugin"]) - { - if ($this->isPluginActive($row["type_tag"])) - { - array_push($rows, $row); - } - } - else - { - array_push($rows, $row); - } - } - } - return $rows; - } - -/** -* Calculates the data for the output of the questionblock browser -* -* @access public -*/ - function getQuestionblocksTable($arrFilter) - { - $ilUser = $this->user; - $ilDB = $this->db; - - $where = ""; - if (is_array($arrFilter)) - { - if (array_key_exists('title', $arrFilter) && strlen($arrFilter['title'])) - { - $where .= " AND " . $ilDB->like('svy_qblk.title', 'text', "%%" . $arrFilter['title'] . "%%"); - } - } + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilPluginAdmin + */ + protected $plugin_admin; + + const EVALUATION_ACCESS_OFF = 0; + const EVALUATION_ACCESS_ALL = 1; + const EVALUATION_ACCESS_PARTICIPANTS = 2; + + const INVITATION_OFF = 0; + const INVITATION_ON = 1; + + const MODE_UNLIMITED = 0; + const MODE_PREDEFINED_USERS = 1; + + const ANONYMIZE_OFF = 0; // personalized, no codes + const ANONYMIZE_ON = 1; // anonymized, codes + const ANONYMIZE_FREEACCESS = 2; // anonymized, no codes + const ANONYMIZE_CODE_ALL = 3; // personalized, codes + + const QUESTIONTITLES_HIDDEN = 0; + const QUESTIONTITLES_VISIBLE = 1; + + // constants to define the print view values. + const PRINT_HIDE_LABELS = 1; // Show only the titles in "print" and "PDF Export" + const PRINT_SHOW_LABELS = 3; // Show titles and labels in "print" and "PDF Export" + + /** + * A unique positive numerical ID which identifies the survey. + * This is the primary key from a database table. + * + * @var integer + */ + public $survey_id; + + /** + * 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; + + /** + * A text representation of the surveys introduction. + * + * @var string + */ + public $introduction; + + /** + * A text representation of the surveys outro. + * + * @var string + */ + public $outro; + + + /** + * Indicates the evaluation access for learners + * + * @var string + */ + public $evaluation_access; + + /** + * The start date of the survey + * + * @var string + */ + public $start_date; + + /** + * The end date of the survey + * + * @var string + */ + public $end_date; + + /** + * The questions contained in this survey + * + * @var array + */ + public $questions; + + /** + * Defines if the survey will be places on users personal desktops + * + * @var integer + */ + public $invitation; + + /** + * Defines the type of user invitation + * + * @var integer + */ + public $invitation_mode; + + /** + * Indicates the anonymization of the survey + * @var integer + */ + public $anonymize; + + /** + * Indicates if the question titles are shown during a query + * @var integer + */ + public $display_question_titles; + + /** + * Indicates if a survey code may be exported with the survey statistics + * + * @var boolean + **/ + public $surveyCodeSecurity; + + public $mailnotification; + public $mailaddresses; + public $mailparticipantdata; + public $template_id; + public $pool_usage; + + /** + * @var ilLogger + */ + protected $log; + + protected $activation_visibility; + protected $activation_starting_time; + protected $activation_ending_time; + + // 360° + protected $mode_360_self_eval; // [bool] + protected $mode_360_self_appr; // [bool] + protected $mode_360_self_rate; // [bool] + protected $mode_360_results; // [int] + protected $mode_skill_service; // [bool] + + const RESULTS_360_NONE = 0; + const RESULTS_360_OWN = 1; + const RESULTS_360_ALL = 2; + + // reminder/notification + protected $reminder_status; // [bool] + protected $reminder_start; // [ilDate] + protected $reminder_end; // [ilDate] + protected $reminder_frequency; // [int] + protected $reminder_target; // [int] + protected $reminder_last_sent; // [bool] + protected $reminder_tmpl; // [int] + protected $tutor_ntf_status; // [bool] + protected $tutor_ntf_recipients; // [array] + protected $tutor_ntf_target; // [int] + + protected $view_own_results; // [bool] + protected $mail_own_results; // [bool] + protected $mail_confirmation; // [bool] + + protected $anon_user_list; // [bool] + + const NOTIFICATION_PARENT_COURSE = 1; + const NOTIFICATION_INVITED_USERS = 2; + const NOTIFICATION_APPRAISEES = 3; + const NOTIFICATION_RATERS = 4; + const NOTIFICATION_APPRAISEES_AND_RATERS = 5; + + protected $mode; //[int] + protected $mode_self_eval_results; //[int] + + //MODE TYPES + const MODE_STANDARD = 0; + const MODE_360 = 1; + const MODE_SELF_EVAL = 2; + + //self evaluation only access to results + const RESULTS_SELF_EVAL_NONE = 0; + const RESULTS_SELF_EVAL_OWN = 1; + const RESULTS_SELF_EVAL_ALL = 2; + + + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + global $DIC; + + $this->user = $DIC->user(); + $this->lng = $DIC->language(); + $this->db = $DIC->database(); + $this->access = $DIC->access(); + $this->log = $DIC["ilLog"]; + $this->plugin_admin = $DIC["ilPluginAdmin"]; + $this->tree = $DIC->repositoryTree(); + $ilUser = $DIC->user(); + $lng = $DIC->language(); + + $this->type = "svy"; + $this->survey_id = -1; + $this->introduction = ""; + $this->outro = $lng->txt("survey_finished"); + $this->author = $ilUser->getFullname(); + $this->evaluation_access = self::EVALUATION_ACCESS_OFF; + $this->questions = array(); + $this->invitation = self::INVITATION_OFF; + $this->invitation_mode = self::MODE_PREDEFINED_USERS; + $this->anonymize = self::ANONYMIZE_OFF; + $this->display_question_titles = self::QUESTIONTITLES_VISIBLE; + $this->surveyCodeSecurity = true; + $this->template_id = null; + $this->pool_usage = true; + $this->log = ilLoggerFactory::getLogger("svy"); + $this->mode = self::MODE_STANDARD; + $this->mode_self_eval_results = self::RESULTS_SELF_EVAL_OWN; + + parent::__construct($a_id, $a_call_by_reference); + } + + /** + * create survey object + */ + public function create($a_upload = false) + { + parent::create(); + if (!$a_upload) { + $this->createMetaData(); + } + $this->setOfflineStatus(true); + $this->update($a_upload); + } + + /** + * Create meta data entry + * + * @access public + */ + public function createMetaData() + { + parent::createMetaData(); + $this->saveAuthorToMetadata(); + } + + /** + * update object data + * + * @access public + * @return boolean + */ + public function update($a_upload = false) + { + if (!$a_upload) { + $this->updateMetaData(); + } + + if (!parent::update()) { + return false; + } + + // put here object specific stuff + + return true; + } + + public function createReference() + { + $result = parent::createReference(); + $this->saveToDb(); + return $result; + } + + /** + * read object data from db into object + * @access public + */ + public function read() + { + parent::read(); + $this->loadFromDb(); + } + + /** + * Adds a question to the survey (used in importer!) + * + * @param integer $question_id The question id of the question + * @access public + */ + public function addQuestion($question_id) + { + array_push($this->questions, $question_id); + } + + /** + * delete object and all related data + * + * @access public + * @return boolean true if all object data were removed; false if only a references were removed + */ + public function delete() + { + if ($this->countReferences() == 1) { + $this->deleteMetaData(); + + // Delete all survey questions, constraints and materials + foreach ($this->questions as $question_id) { + $this->removeQuestion($question_id); + } + $this->deleteSurveyRecord(); + + ilUtil::delDir($this->getImportDirectory()); + } + + $remove = parent::delete(); + + // always call parent delete function first!! + if (!$remove) { + return false; + } + return true; + } + + /** + * Deletes the survey from the database + * + * @access public + */ + public function deleteSurveyRecord() + { + $ilDB = $this->db; + + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_svy WHERE survey_id = %s", + array('integer'), + array($this->getSurveyId()) + ); + + $result = $ilDB->queryF( + "SELECT questionblock_fi FROM svy_qblk_qst WHERE survey_fi = %s", + array('integer'), + array($this->getSurveyId()) + ); + $questionblocks = array(); + while ($row = $ilDB->fetchAssoc($result)) { + array_push($questionblocks, $row["questionblock_fi"]); + } + if (count($questionblocks)) { + $affectedRows = $ilDB->manipulate("DELETE FROM svy_qblk WHERE " . $ilDB->in('questionblock_id', $questionblocks, false, 'integer')); + } + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_qblk_qst WHERE survey_fi = %s", + array('integer'), + array($this->getSurveyId()) + ); + $this->deleteAllUserData(false); + + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_anonymous WHERE survey_fi = %s", + array('integer'), + array($this->getSurveyId()) + ); + + // delete export files + $svy_data_dir = ilUtil::getDataDir() . "/svy_data"; + $directory = $svy_data_dir . "/svy_" . $this->getId(); + if (is_dir($directory)) { + ilUtil::delDir($directory); + } + + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $mobs = ilObjMediaObject::_getMobsOfObject("svy:html", $this->getId()); + // 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, "svy:html", $this->getId()); + $mob_obj = new ilObjMediaObject($mob); + $mob_obj->delete(); + } + } + + /** + * Deletes all user data of a survey + * + * @access public + * @param bool $reset_LP notice that the LP can only be reset it the determining components still exist + */ + public function deleteAllUserData($reset_LP = true) + { + $ilDB = $this->db; + + $result = $ilDB->queryF( + "SELECT finished_id FROM svy_finished WHERE survey_fi = %s", + array('integer'), + array($this->getSurveyId()) + ); + $active_array = array(); + while ($row = $ilDB->fetchAssoc($result)) { + array_push($active_array, $row["finished_id"]); + } + + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_finished WHERE survey_fi = %s", + array('integer'), + array($this->getSurveyId()) + ); + + foreach ($active_array as $active_fi) { + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_answer WHERE active_fi = %s", + array('integer'), + array($active_fi) + ); + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_times WHERE finished_fi = %s", + array('integer'), + array($active_fi) + ); + } + + if ($reset_LP) { + include_once "Services/Object/classes/class.ilObjectLP.php"; + $lp_obj = ilObjectLP::getInstance($this->getId()); + $lp_obj->resetLPDataForCompleteObject(); + } + } + + /** + * Deletes the user data of a given array of survey participants + * + * @access public + */ + public function removeSelectedSurveyResults($finished_ids) + { + $ilDB = $this->db; + + $user_ids[] = array(); + + foreach ($finished_ids as $finished_id) { + $result = $ilDB->queryF( + "SELECT finished_id FROM svy_finished WHERE finished_id = %s", + array('integer'), + array($finished_id) + ); + $row = $ilDB->fetchAssoc($result); + + if ($row["user_fi"]) { + $user_ids[] = $row["user_fi"]; + } + + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_answer WHERE active_fi = %s", + array('integer'), + array($row["finished_id"]) + ); + + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_finished WHERE finished_id = %s", + array('integer'), + array($finished_id) + ); + + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_times WHERE finished_fi = %s", + array('integer'), + array($row["finished_id"]) + ); + } + + if (sizeof($user_ids)) { + include_once "Services/Object/classes/class.ilObjectLP.php"; + $lp_obj = ilObjectLP::getInstance($this->getId()); + $lp_obj->resetLPDataForUserIds($user_ids); + } + } + + public function &getSurveyParticipants($finished_ids = null, $force_non_anonymous = false) + { + $ilDB = $this->db; + + $sql = "SELECT * FROM svy_finished" . + " WHERE survey_fi = " . $ilDB->quote($this->getSurveyId(), "integer"); + if ($finished_ids) { + $sql .= " AND " . $ilDB->in("finished_id", $finished_ids, "", "integer"); + } + + $result = $ilDB->query($sql); + $participants = array(); + if ($result->numRows() > 0) { + while ($row = $ilDB->fetchAssoc($result)) { + $userdata = $this->getUserDataFromActiveId($row["finished_id"], $force_non_anonymous); + $userdata["finished"] = (bool) $row["state"]; + $userdata["finished_tstamp"] = $row["tstamp"]; + $participants[$userdata["sortname"] . $userdata["active_id"]] = $userdata; + } + } + return $participants; + } + + /** + * Returns 1, if a survey is complete for use + * + * @return boolean 1, if the survey is complete for use, otherwise 0 + * @access public + */ + public function isComplete() + { + if (($this->getTitle()) and (count($this->questions))) { + return 1; + } else { + return 0; + } + } + + /** + * Saves the completion status of the survey + * + * @access public + */ + public function saveCompletionStatus() + { + $ilDB = $this->db; + + $complete = 0; + if ($this->isComplete()) { + $complete = 1; + } + if ($this->getSurveyId() > 0) { + $affectedRows = $ilDB->manipulateF( + "UPDATE svy_svy SET complete = %s, tstamp = %s WHERE survey_id = %s", + array('text','integer','integer'), + array($this->isComplete(), time(), $this->getSurveyId()) + ); + } + } + + /** + * Takes a question and creates a copy of the question for use in the survey + * + * @param integer $question_id The database id of the question + * @result integer The database id of the copied question + * @access public + */ + public function duplicateQuestionForSurvey($question_id, $a_force = false) + { + $ilUser = $this->user; + + $questiontype = $this->getQuestionType($question_id); + $question_gui = $this->getQuestionGUI($questiontype, $question_id); + + // check if question is a pool question at all, if not do nothing + if ($this->getId() == $question_gui->object->getObjId() && !$a_force) { + return $question_id; + } + + $duplicate_id = $question_gui->object->duplicate(true, "", "", "", $this->getId()); + return $duplicate_id; + } + + /** + * Inserts a question in the survey and saves the relation to the database + * + * @access public + */ + public function insertQuestion($question_id) + { + $ilDB = $this->db; + + $this->log->debug("insert question, id:" . $question_id); + + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + if (!SurveyQuestion::_isComplete($question_id)) { + $this->log->debug("question is not complete"); + return false; + } else { + // get maximum sequence index in test + // @todo: refactor this + $result = $ilDB->queryF( + "SELECT survey_question_id FROM svy_svy_qst WHERE survey_fi = %s", + array('integer'), + array($this->getSurveyId()) + ); + $sequence = $result->numRows(); + $duplicate_id = $this->duplicateQuestionForSurvey($question_id); + $this->log->debug("duplicate, id: " . $question_id . ", duplicate id: " . $duplicate_id); + + // check if question is not already in the survey, see #22018 + if ($this->isQuestionInSurvey($duplicate_id)) { + return false; + } + + $next_id = $ilDB->nextId('svy_svy_qst'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_svy_qst (survey_question_id, survey_fi, question_fi, sequence, tstamp) VALUES (%s, %s, %s, %s, %s)", + array('integer', 'integer', 'integer', 'integer', 'integer'), + array($next_id, $this->getSurveyId(), $duplicate_id, $sequence, time()) + ); + + $this->log->debug("added entry to svy_svy_qst, id: " . $next_id . ", question id: " . $duplicate_id . ", sequence: " . $sequence); + + $this->loadQuestionsFromDb(); + return true; + } + } + + /** + * Check if a question is already in the survey + * + * @param question id (as primary key from svy_question table) + * @return bool + */ + public function isQuestionInSurvey($a_question_fi) + { + global $DIC; + //return false; + $ilDB = $DIC->database(); + + $set = $ilDB->query("SELECT * FROM svy_svy_qst " . + " WHERE survey_fi = " . $ilDB->quote($this->getSurveyId(), "integer") . + " AND question_fi = " . $ilDB->quote($a_question_fi, "integer")); + if ($rec = $ilDB->fetchAssoc($set)) { + return true; + } + return false; + } + + + + /** + * Inserts a questionblock in the survey and saves the relation to the database + * + * @access public + */ + public function insertQuestionblock($questionblock_id) + { + $ilDB = $this->db; + $result = $ilDB->queryF( + "SELECT svy_qblk.title, svy_qblk.show_questiontext, svy_qblk.show_blocktitle," . + " svy_qblk_qst.question_fi FROM svy_qblk, svy_qblk_qst, svy_svy_qst" . + " WHERE svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi" . + " AND svy_svy_qst.question_fi = svy_qblk_qst.question_fi" . + " AND svy_qblk.questionblock_id = %s" . + " ORDER BY svy_svy_qst.sequence", + array('integer'), + array($questionblock_id) + ); + $questions = array(); + $show_questiontext = 0; + $show_blocktitle = 0; + while ($row = $ilDB->fetchAssoc($result)) { + $duplicate_id = $this->duplicateQuestionForSurvey($row["question_fi"]); + array_push($questions, $duplicate_id); + $title = $row["title"]; + $show_questiontext = $row["show_questiontext"]; + $show_blocktitle = $row["show_blocktitle"]; + } + $this->createQuestionblock($title, $show_questiontext, $show_blocktitle, $questions); + } + + public function saveUserSettings($usr_id, $key, $title, $value) + { + $ilDB = $this->db; + + $next_id = $ilDB->nextId('svy_settings'); + $affectedRows = $ilDB->insert("svy_settings", array( + "settings_id" => array("integer", $next_id), + "usr_id" => array("integer", $usr_id), + "keyword" => array("text", $key), + "title" => array("text", $title), + "value" => array("clob", $value) + )); + } + + public function deleteUserSettings($id) + { + $ilDB = $this->db; + + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_settings WHERE settings_id = %s", + array('integer'), + array($id) + ); + return $affectedRows; + } + + public function getUserSettings($usr_id, $key) + { + $ilDB = $this->db; + + $result = $ilDB->queryF( + "SELECT * FROM svy_settings WHERE usr_id = %s AND keyword = %s", + array('integer', 'text'), + array($usr_id, $key) + ); + $found = array(); + if ($result->numRows()) { + while ($row = $ilDB->fetchAssoc($result)) { + $found[$row['settings_id']] = $row; + } + } + return $found; + } + + /** + * Saves a survey object to a database + * + * @access public + */ + public function saveToDb() + { + $ilDB = $this->db; + + // date handling + $rmd_start = $this->getReminderStart(); + if (is_object($rmd_start)) { + $rmd_start = $rmd_start->get(IL_CAL_DATE); + } + $rmd_end = $this->getReminderEnd(); + if (is_object($rmd_end)) { + $rmd_end = $rmd_end->get(IL_CAL_DATE); + } + + include_once("./Services/RTE/classes/class.ilRTE.php"); + if ($this->getSurveyId() < 1) { + $next_id = $ilDB->nextId('svy_svy'); + $affectedRows = $ilDB->insert("svy_svy", array( + "survey_id" => array("integer", $next_id), + "obj_fi" => array("integer", $this->getId()), + "author" => array("text", $this->getAuthor()), + "introduction" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getIntroduction(), 0)), + "outro" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getOutro(), 0)), + "startdate" => array("text", $this->getStartDate()), + "enddate" => array("text", $this->getEndDate()), + "evaluation_access" => array("text", $this->getEvaluationAccess()), + "invitation" => array("text", $this->getInvitation()), + "invitation_mode" => array("text", $this->getInvitationMode()), + "complete" => array("text", $this->isComplete()), + "created" => array("integer", time()), + "anonymize" => array("text", $this->getAnonymize()), + "show_question_titles" => array("text", $this->getShowQuestionTitles()), + "mailnotification" => array('integer', ($this->getMailNotification()) ? 1 : 0), + "mailaddresses" => array('text', strlen($this->getMailAddresses()) ? $this->getMailAddresses() : null), + "mailparticipantdata" => array('text', strlen($this->getMailParticipantData()) ? $this->getMailParticipantData() : null), + "tstamp" => array("integer", time()), + "template_id" => array("integer", $this->getTemplate()), + "pool_usage" => array("integer", $this->getPoolUsage()), + // Mode type + "mode" => array("integer", $this->getMode()), + // 360° + "mode_360_self_eval" => array("integer", $this->get360SelfEvaluation()), + "mode_360_self_rate" => array("integer", $this->get360SelfRaters()), + "mode_360_self_appr" => array("integer", $this->get360SelfAppraisee()), + "mode_360_results" => array("integer", $this->get360Results()), + // competences + "mode_skill_service" => array("integer", (int) $this->getSkillService()), + // Self Evaluation Only + "mode_self_eval_results" => array("integer", ilObjSurvey::RESULTS_SELF_EVAL_OWN), + // reminder/notification + "reminder_status" => array("integer", (int) $this->getReminderStatus()), + "reminder_start" => array("datetime", $rmd_start), + "reminder_end" => array("datetime", $rmd_end), + "reminder_frequency" => array("integer", (int) $this->getReminderFrequency()), + "reminder_target" => array("integer", (int) $this->getReminderTarget()), + "reminder_last_sent" => array("datetime", $this->getReminderLastSent()), + "reminder_tmpl" => array("text", $this->getReminderTemplate(true)), + "tutor_ntf_status" => array("integer", (int) $this->getTutorNotificationStatus()), + "tutor_ntf_reci" => array("text", implode(";", (array) $this->getTutorNotificationRecipients())), + "tutor_ntf_target" => array("integer", (int) $this->getTutorNotificationTarget()), + "own_results_view" => array("integer", $this->hasViewOwnResults()), + "own_results_mail" => array("integer", $this->hasMailOwnResults()), + "confirmation_mail" => array("integer", $this->hasMailConfirmation()), + "anon_user_list" => array("integer", $this->hasAnonymousUserList()) + )); + $this->setSurveyId($next_id); + } else { + $affectedRows = $ilDB->update("svy_svy", array( + "author" => array("text", $this->getAuthor()), + "introduction" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getIntroduction(), 0)), + "outro" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getOutro(), 0)), + "startdate" => array("text", $this->getStartDate()), + "enddate" => array("text", $this->getEndDate()), + "evaluation_access" => array("text", $this->getEvaluationAccess()), + "invitation" => array("text", $this->getInvitation()), + "invitation_mode" => array("text", $this->getInvitationMode()), + "complete" => array("text", $this->isComplete()), + "anonymize" => array("text", $this->getAnonymize()), + "show_question_titles" => array("text", $this->getShowQuestionTitles()), + "mailnotification" => array('integer', ($this->getMailNotification()) ? 1 : 0), + "mailaddresses" => array('text', strlen($this->getMailAddresses()) ? $this->getMailAddresses() : null), + "mailparticipantdata" => array('text', strlen($this->getMailParticipantData()) ? $this->getMailParticipantData() : null), + "tstamp" => array("integer", time()), + "template_id" => array("integer", $this->getTemplate()), + "pool_usage" => array("integer", $this->getPoolUsage()), + //MODE TYPE + "mode" => array("integer", $this->getMode()), + // 360° + "mode_360_self_eval" => array("integer", $this->get360SelfEvaluation()), + "mode_360_self_rate" => array("integer", $this->get360SelfRaters()), + "mode_360_self_appr" => array("integer", $this->get360SelfAppraisee()), + "mode_360_results" => array("integer", $this->get360Results()), + // Competences + "mode_skill_service" => array("integer", (int) $this->getSkillService()), + // Self Evaluation Only + "mode_self_eval_results" => array("integer", $this->getSelfEvaluationResults()), + // reminder/notification + "reminder_status" => array("integer", $this->getReminderStatus()), + "reminder_start" => array("datetime", $rmd_start), + "reminder_end" => array("datetime", $rmd_end), + "reminder_frequency" => array("integer", $this->getReminderFrequency()), + "reminder_target" => array("integer", $this->getReminderTarget()), + "reminder_last_sent" => array("datetime", $this->getReminderLastSent()), + "reminder_tmpl" => array("text", $this->getReminderTemplate()), + "tutor_ntf_status" => array("integer", $this->getTutorNotificationStatus()), + "tutor_ntf_reci" => array("text", implode(";", (array) $this->getTutorNotificationRecipients())), + "tutor_ntf_target" => array("integer", $this->getTutorNotificationTarget()), + "own_results_view" => array("integer", $this->hasViewOwnResults()), + "own_results_mail" => array("integer", $this->hasMailOwnResults()), + "confirmation_mail" => array("integer", $this->hasMailConfirmation()), + "anon_user_list" => array("integer", $this->hasAnonymousUserList()) + ), array( + "survey_id" => array("integer", $this->getSurveyId()) + )); + } + if ($affectedRows) { + // save questions to db + $this->saveQuestionsToDb(); + } + + // moved activation to ilObjectActivation + if ($this->ref_id) { + include_once "./Services/Object/classes/class.ilObjectActivation.php"; + ilObjectActivation::getItem($this->ref_id); + + $item = new ilObjectActivation; + if (!$this->isActivationLimited()) { + $item->setTimingType(ilObjectActivation::TIMINGS_DEACTIVATED); + } else { + $item->setTimingType(ilObjectActivation::TIMINGS_ACTIVATION); + $item->setTimingStart($this->getActivationStartDate()); + $item->setTimingEnd($this->getActivationEndDate()); + $item->toggleVisible($this->getActivationVisibility()); + } + + $item->update($this->ref_id); + } + } + + /** + * Saves the survey questions to the database + * + * @access public + * @see $questions + */ + public function saveQuestionsToDb() + { + $ilDB = $this->db; + + $this->log->debug("save questions"); + + // gather old questions state + $old_questions = array(); + $result = $ilDB->queryF( + "SELECT survey_question_id,question_fi,sequence" . + " FROM svy_svy_qst WHERE survey_fi = %s", + array('integer'), + array($this->getSurveyId()) + ); + while ($row = $ilDB->fetchAssoc($result)) { + $old_questions[$row["question_fi"]] = $row; // problem, as soon as duplicates exist, they will be hidden here + } + + // #15231 - diff with current questions state + $insert = $update = $delete = array(); + foreach ($this->questions as $seq => $fi) { + if (!array_key_exists($fi, $old_questions)) { // really new fi IDs + $insert[] = $fi; // this should be ok, should not create duplicates here + } elseif ($old_questions[$fi]["sequence"] != $seq) { // we are updating one of the duplicates (if any) + $update[$fi] = $old_questions[$fi]["survey_question_id"]; + } + // keep track of still relevant questions + unset($old_questions[$fi]); // deleting old question, if they are not in current array + } + + // delete obsolete question relations + if (sizeof($old_questions)) { + $del_ids = array(); + foreach ($old_questions as $fi => $old) { + $del_ids[] = $old["survey_question_id"]; + } + $ilDB->manipulate($q = "DELETE FROM svy_svy_qst" . + " WHERE " . $ilDB->in("survey_question_id", $del_ids, "", "integer")); + $this->log->debug("delete: " . $q); + } + unset($old_questions); + + // create/update question relations + foreach ($this->questions as $seq => $fi) { + if (in_array($fi, $insert)) { + // check if question is not already in the survey, see #22018 + if (!$this->isQuestionInSurvey($fi)) { + $next_id = $ilDB->nextId('svy_svy_qst'); + $ilDB->manipulateF( + "INSERT INTO svy_svy_qst" . + " (survey_question_id, survey_fi, question_fi, heading, sequence, tstamp)" . + " VALUES (%s, %s, %s, %s, %s, %s)", + array('integer', 'integer', 'integer', 'text', 'integer', 'integer'), + array($next_id, $this->getSurveyId(), $fi, null, $seq, time()) + ); + $this->log->debug("insert svy_svy_qst, id:" . $next_id . ", fi: " . $fi . ", seq:" . $seq); + } + } elseif (array_key_exists($fi, $update)) { + $ilDB->manipulate("UPDATE svy_svy_qst" . + " SET sequence = " . $ilDB->quote($seq, "integer") . + ", tstamp = " . $ilDB->quote(time(), "integer") . + " WHERE survey_question_id = " . $ilDB->quote($update[$fi], "integer")); + $this->log->debug("update svy_svy_qst, id:" . $update[$fi] . ", fi: " . $fi . ", seq:" . $seq); + } + } + } + + /** + * Checks for an anomyous survey id in the database an returns the id + * + * @param string $id A survey access code + * @result object Anonymous survey id if found, empty string otherwise + * @access public + */ + public function getAnonymousId($id) + { + $ilDB = $this->db; + $result = $ilDB->queryF( + "SELECT anonymous_id FROM svy_finished WHERE anonymous_id = %s", + array('text'), + array($id) + ); + if ($result->numRows()) { + $row = $ilDB->fetchAssoc($result); + return $row["anonymous_id"]; + } else { + return ""; + } + } + + /** + * Returns a question gui object to a given questiontype and question id + * + * @result object Resulting question gui object + * @access public + */ + public function getQuestionGUI($questiontype, $question_id) + { + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php"; + return SurveyQuestionGUI::_getQuestionGUI($questiontype, $question_id); + } + + /** + * 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 function getQuestionType($question_id) + { + $ilDB = $this->db; + if ($question_id < 1) { + return -1; + } + $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 survey database id + * + * @result integer survey database id + * @access public + */ + public function getSurveyId() + { + return $this->survey_id; + } + + /** + * set anonymize status + */ + public function setAnonymize($a_anonymize) + { + switch ($a_anonymize) { + case self::ANONYMIZE_OFF: + case self::ANONYMIZE_ON: + case self::ANONYMIZE_FREEACCESS: + case self::ANONYMIZE_CODE_ALL: + $this->anonymize = $a_anonymize; + break; + default: + $this->anonymize = self::ANONYMIZE_OFF; + break; + } + } + + /** + * get anonymize status + * + * @return integer status + */ + public function getAnonymize() + { + return ($this->anonymize) ? $this->anonymize : 0; + } + + /** + * Checks if the survey is accessable without a survey code + * + * @return boolean status + */ + public function isAccessibleWithoutCode() + { + return ($this->getAnonymize() == self::ANONYMIZE_OFF || + $this->getAnonymize() == self::ANONYMIZE_FREEACCESS); + } + + /** + * Checks if the survey results are to be anonymized + * + * @return boolean status + */ + public function hasAnonymizedResults() + { + return ($this->getAnonymize() == self::ANONYMIZE_ON || + $this->getAnonymize() == self::ANONYMIZE_FREEACCESS); + } + + /** + * Loads a survey object from a database + * + * @access public + */ + public function loadFromDb() + { + $ilDB = $this->db; + $result = $ilDB->queryF( + "SELECT * FROM svy_svy WHERE obj_fi = %s", + array('integer'), + array($this->getId()) + ); + if ($result->numRows() == 1) { + $data = $ilDB->fetchAssoc($result); + $this->setSurveyId($data["survey_id"]); + $this->setAuthor($data["author"]); + include_once("./Services/RTE/classes/class.ilRTE.php"); + $this->setIntroduction(ilRTE::_replaceMediaObjectImageSrc($data["introduction"], 1)); + if (strcmp($data["outro"], "survey_finished") == 0) { + $this->setOutro($this->lng->txt("survey_finished")); + } else { + $this->setOutro(ilRTE::_replaceMediaObjectImageSrc($data["outro"], 1)); + } + $this->setInvitation($data["invitation"]); + $this->setInvitationMode($data["invitation_mode"]); + $this->setShowQuestionTitles($data["show_question_titles"]); + $this->setStartDate($data["startdate"]); + $this->setEndDate($data["enddate"]); + $this->setAnonymize($data["anonymize"]); + $this->setEvaluationAccess($data["evaluation_access"]); + $this->loadQuestionsFromDb(); + $this->setMailNotification($data['mailnotification']); + $this->setMailAddresses($data['mailaddresses']); + $this->setMailParticipantData($data['mailparticipantdata']); + $this->setTemplate($data['template_id']); + $this->setPoolUsage($data['pool_usage']); + // Mode + $this->setMode($data['mode']); + // 360° + $this->set360SelfEvaluation($data['mode_360_self_eval']); + $this->set360SelfRaters($data['mode_360_self_rate']); + $this->set360SelfAppraisee($data['mode_360_self_appr']); + $this->set360Results($data['mode_360_results']); + // Mode self evaluated + $this->setSelfEvaluationResults($data['mode_self_eval_results']); + // Competences + $this->setSkillService($data['mode_skill_service']); + // reminder/notification + $this->setReminderStatus($data["reminder_status"]); + $this->setReminderStart($data["reminder_start"] ? new ilDate($data["reminder_start"], IL_CAL_DATE) : null); + $this->setReminderEnd($data["reminder_end"] ? new ilDate($data["reminder_end"], IL_CAL_DATE) : null); + $this->setReminderFrequency($data["reminder_frequency"]); + $this->setReminderTarget($data["reminder_target"]); + $this->setReminderLastSent($data["reminder_last_sent"]); + $this->setReminderTemplate($data["reminder_tmpl"]); + $this->setTutorNotificationStatus($data["tutor_ntf_status"]); + $this->setTutorNotificationRecipients(explode(";", $data["tutor_ntf_reci"])); + $this->setTutorNotificationTarget($data["tutor_ntf_target"]); + + $this->setViewOwnResults($data["own_results_view"]); + $this->setMailOwnResults($data["own_results_mail"]); + $this->setMailConfirmation($data["confirmation_mail"]); + + $this->setAnonymousUserList($data["anon_user_list"]); + } + + // moved activation to ilObjectActivation + if ($this->ref_id) { + include_once "./Services/Object/classes/class.ilObjectActivation.php"; + $activation = ilObjectActivation::getItem($this->ref_id); + switch ($activation["timing_type"]) { + case ilObjectActivation::TIMINGS_ACTIVATION: + $this->setActivationLimited(true); + $this->setActivationStartDate($activation["timing_start"]); + $this->setActivationEndDate($activation["timing_end"]); + $this->setActivationVisibility($activation["visible"]); + break; + + default: + $this->setActivationLimited(false); + break; + } + } + } + + /** + * Loads the survey questions from the database + * + * @access public + * @see $questions + */ + public function loadQuestionsFromDb() + { + $ilDB = $this->db; + $this->questions = array(); + $result = $ilDB->queryF( + "SELECT * FROM svy_svy_qst WHERE survey_fi = %s ORDER BY sequence", + array('integer'), + array($this->getSurveyId()) + ); + while ($data = $ilDB->fetchAssoc($result)) { + $this->questions[$data["sequence"]] = $data["question_fi"]; + } + } + + /** + * Remove duplicate sequence entries, see #22018 + */ + public function fixSequenceStructure() + { + global $DIC; + + $ilDB = $DIC->database(); + //return; + // we keep all survey question ids with their lowest sequence + $result = $ilDB->queryF( + "SELECT * FROM svy_svy_qst WHERE survey_fi = %s ORDER BY sequence", + array('integer'), + array($this->getSurveyId()) + ); + + // step 1: find duplicates -> $to_delete_ids + $fis = array(); + $to_delete_ids = array(); + while ($data = $ilDB->fetchAssoc($result)) { + if (in_array($data["question_fi"], $fis)) { // found a duplicate + $to_delete_ids[] = $data["survey_question_id"]; + } else { + $fis[] = $data["question_fi"]; + } + } + + // step 2: we delete the duplicates + if (count($to_delete_ids) > 0) { + $ilDB->manipulate($q = "DELETE FROM svy_svy_qst" . + " WHERE " . $ilDB->in("survey_question_id", $to_delete_ids, false, "integer") . + " AND survey_fi = " . $ilDB->quote($this->getSurveyId(), "integer")); + $this->log->debug("delete: " . $q); + + $ilDB->manipulate($q = "DELETE FROM svy_qblk_qst " . + " WHERE " . $ilDB->in("question_fi", $fis, true, "integer") . + " AND survey_fi = " . $ilDB->quote($this->getSurveyId(), "integer")); + $this->log->debug("delete: " . $q); + } + + // step 3: we fix the sequence + $set = $ilDB->query("SELECT * FROM svy_svy_qst " . + " WHERE survey_fi = " . $ilDB->quote($this->getSurveyId(), "integer") . " ORDER BY sequence"); + $seq = 0; + while ($rec = $ilDB->fetchAssoc($set)) { + $ilDB->manipulate( + $q = "UPDATE svy_svy_qst SET " . + " sequence = " . $ilDB->quote($seq++, "integer") . + " WHERE survey_question_id = " . $ilDB->quote($rec["survey_question_id"], "integer") + ); + $this->log->debug("update: " . $q); + } + } + + + /** + * Sets the authors name of the ilObjSurvey object + * + * @param string $author A string containing the name of the test author + * @access public + * @see $author + */ + public function setAuthor($author = "") + { + $this->author = $author; + } + + /** + * Saves an authors name into the lifecycle metadata if no lifecycle metadata exists + * This will only be called for conversion of "old" tests where the author hasn't been + * stored in the lifecycle metadata + * + * @param string $a_author A string containing the name of the test author + * @access private + * @see $author + */ + public function saveAuthorToMetadata($a_author = "") + { + $md = new ilMD($this->getId(), 0, $this->getType()); + $md_life =&$md->getLifecycle(); + if (!$md_life) { + if (strlen($a_author) == 0) { + $ilUser = $this->user; + $a_author = $ilUser->getFullname(); + } + + $md_life =&$md->addLifecycle(); + $md_life->save(); + $con =&$md_life->addContribute(); + $con->setRole("Author"); + $con->save(); + $ent =&$con->addEntity(); + $ent->setEntity($a_author); + $ent->save(); + } + } + + /** + * Gets the authors name of the ilObjSurvey object + * + * @return string The string containing the name of the test author + * @access public + * @see $author + */ + public function getAuthor() + { + $author = array(); + include_once "./Services/MetaData/classes/class.ilMD.php"; + $md = new ilMD($this->getId(), 0, $this->getType()); + $md_life =&$md->getLifecycle(); + if ($md_life) { + $ids =&$md_life->getContributeIds(); + foreach ($ids as $id) { + $md_cont =&$md_life->getContribute($id); + if (strcmp($md_cont->getRole(), "Author") == 0) { + $entids =&$md_cont->getEntityIds(); + foreach ($entids as $entid) { + $md_ent =&$md_cont->getEntity($entid); + array_push($author, $md_ent->getEntity()); + } + } + } + } + return join($author, ","); + } + + /** + * Gets the status of the display_question_titles attribute + * + * @return integer The status of the display_question_titles attribute + * @see $display_question_titles + */ + public function getShowQuestionTitles() + { + return ($this->display_question_titles) ? 1 : 0; + } + + /** + * Sets the status of the display_question_titles attribute + * + * @param integer $a_show The status of the display_question_titles attribute + * @see $display_question_titles + */ + public function setShowQuestionTitles($a_show) + { + $this->display_question_titles = ($a_show) ? 1 : 0; + } + + /** + * Sets the question titles visible during the query + * + * @access public + * @see $display_question_titles + */ + public function showQuestionTitles() + { + $this->display_question_titles = 1; + } + + /** + * Sets the question titles hidden during the query + * + * @access public + * @see $display_question_titles + */ + public function hideQuestionTitles() + { + $this->display_question_titles = 0; + } + + /** + * Sets the invitation status + * + * @param integer $invitation The invitation status + * @access public + * @see $invitation + */ + public function setInvitation($invitation = 0) + { + $ilDB = $this->db; + $ilAccess = $this->access; + + $this->invitation = $invitation; + if ($invitation == self::INVITATION_OFF) { + $this->disinviteAllUsers(); + } elseif ($invitation == self::INVITATION_ON) { + if ($this->getInvitationMode() == self::MODE_UNLIMITED) { + $result = $ilDB->query("SELECT usr_id FROM usr_data"); + while ($row = $ilDB->fetchAssoc($result)) { + if ($ilAccess->checkAccessOfUser($row["usr_id"], "read", "", $this->getRefId(), "svy", $this->getId())) { + $this->inviteUser($row['usr_id']); + } + } + } + } + } + + /** + * Sets the invitation mode + * + * @param integer $invitation_mode The invitation mode + * @access public + * @see $invitation_mode + */ + public function setInvitationMode($invitation_mode = 0) + { + $this->invitation_mode = $invitation_mode; + } + + /** + * Sets the invitation status and mode (a more performant solution if you change both) + * + * @param integer $invitation The invitation status + * @param integer $invitation_mode The invitation mode + * @access public + * @see $invitation_mode + */ + public function setInvitationAndMode($invitation = 0, $invitation_mode = 0) + { + $this->invitation_mode = $invitation_mode; + $this->setInvitation($invitation); + } + + /** + * Sets the introduction text + * + * @param string $introduction A string containing the introduction + * @see $introduction + */ + public function setIntroduction($introduction = "") + { + $this->introduction = $introduction; + } + + /** + * Sets the outro text + * + * @param string $outro A string containing the outro + * @see $outro + */ + public function setOutro($outro = "") + { + $this->outro = $outro; + } + + /** + * Gets the invitation status + * + * @return integer The invitation status + * @access public + * @see $invitation + */ + public function getInvitation() + { + return ($this->invitation) ? $this->invitation : self::INVITATION_OFF; + } + + /** + * Gets the invitation mode + * + * @return integer The invitation mode + * @access public + * @see $invitation + */ + public function getInvitationMode() + { + include_once "./Services/Administration/classes/class.ilSetting.php"; + $surveySetting = new ilSetting("survey"); + $unlimited_invitation = $surveySetting->get("unlimited_invitation"); + if (!$unlimited_invitation && $this->invitation_mode == self::MODE_UNLIMITED) { + return self::MODE_PREDEFINED_USERS; + } else { + return ($this->invitation_mode) ? $this->invitation_mode : self::MODE_UNLIMITED; + } + } + + /** + * Gets the start date of the survey + * + * @return string Survey start date (YYYY-MM-DD) + * @access public + * @see $start_date + */ + public function getStartDate() + { + return (strlen($this->start_date)) ? $this->start_date : null; + } + + /** + * Checks if the survey can be started + * + * @return array An array containing the following keys: result (boolean) and messages (array) + * @access public + */ + public function canStartSurvey($anonymous_id = null, $a_no_rbac = false) + { + $ilAccess = $this->access; + + $result = true; + $messages = array(); + $edit_settings = false; + // check start date + if (preg_match("/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/", $this->getStartDate(), $matches)) { + $epoch_time = mktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]); + $now = time(); + if ($now < $epoch_time) { + array_push($messages, $this->lng->txt('start_date_not_reached') . ' (' . + ilDatePresentation::formatDate(new ilDateTime($this->getStartDate(), IL_CAL_TIMESTAMP)) . ")"); + $result = false; + $edit_settings = true; + } + } + // check end date + if (preg_match("/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/", $this->getEndDate(), $matches)) { + $epoch_time = mktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]); + $now = time(); + if ($now > $epoch_time) { + array_push($messages, $this->lng->txt('end_date_reached') . ' (' . + ilDatePresentation::formatDate(new ilDateTime($this->getEndDate(), IL_CAL_TIMESTAMP)) . ")"); + $result = false; + $edit_settings = true; + } + } + + // check online status + if ($this->getOfflineStatus()) { + array_push($messages, $this->lng->txt("survey_is_offline")); + $result = false; + $edit_settings = true; + } + // check rbac permissions + if (!$a_no_rbac && !$ilAccess->checkAccess("read", "", $this->ref_id)) { + array_push($messages, $this->lng->txt("cannot_participate_survey")); + $result = false; + } + /* + // 2. check previous access + if (!$result["error"]) + { + $ilUser = $this->user; + $survey_started = $this->isSurveyStarted($ilUser->getId(), $anonymous_id); + if ($survey_started === 1) + { + array_push($messages, $this->lng->txt("already_completed_survey")); + $result = FALSE; + } + } + */ + return array( + "result" => $result, + "messages" => $messages, + "edit_settings" => $edit_settings + ); + } + + /** + * Sets the start date of the survey + * + * @param string $start_data Survey start date (YYYYMMDDHHMMSS) + * @access public + * @see $start_date + */ + public function setStartDate($start_date = "") + { + $this->start_date = $start_date; + } + + /** + * Sets the start date of the survey + * + * @param string $start_date Survey start date (YYYY-MM-DD) + * @param string $start_time Survey start time (HH:MM:SS) + * @access public + * @see $start_date + */ + public function setStartDateAndTime($start_date = "", $start_time) + { + $y = ''; + $m = ''; + $d = ''; + $h = ''; + $i = ''; + $s = ''; + if (preg_match("/(\d{4})-(\d{2})-(\d{2})/", $start_date, $matches)) { + $y = $matches[1]; + $m = $matches[2]; + $d = $matches[3]; + } + if (preg_match("/(\d{2}):(\d{2}):(\d{2})/", $start_time, $matches)) { + $h = $matches[1]; + $i = $matches[2]; + $s = $matches[3]; + } + $this->start_date = sprintf('%04d%02d%02d%02d%02d%02d', $y, $m, $d, $h, $i, $s); + } + + /** + * Gets the end date of the survey + * + * @return string Survey end date (YYYY-MM-DD) + * @access public + * @see $end_date + */ + public function getEndDate() + { + return (strlen($this->end_date)) ? $this->end_date : null; + } + + /** + * Sets the end date of the survey + * + * @param string $end_date Survey end date (YYYYMMDDHHMMSS) + * @access public + * @see $end_date + */ + public function setEndDate($end_date = "") + { + $this->end_date = $end_date; + } + + /** + * Sets the end date of the survey + * + * @param string $end_date Survey end date (YYYY-MM-DD) + * @param string $end_time Survey end time (HH:MM:SS) + * @access public + * @see $start_date + */ + public function setEndDateAndTime($end_date = "", $end_time) + { + $y = ''; + $m = ''; + $d = ''; + $h = ''; + $i = ''; + $s = ''; + if (preg_match("/(\d{4})-(\d{2})-(\d{2})/", $end_date, $matches)) { + $y = $matches[1]; + $m = $matches[2]; + $d = $matches[3]; + } + if (preg_match("/(\d{2}):(\d{2}):(\d{2})/", $end_time, $matches)) { + $h = $matches[1]; + $i = $matches[2]; + $s = $matches[3]; + } + $this->end_date = sprintf('%04d%02d%02d%02d%02d%02d', $y, $m, $d, $h, $i, $s); + } + + /** + * Gets the learners evaluation access + * + * @return integer The evaluation access + * @access public + * @see $evaluation_access + */ + public function getEvaluationAccess() + { + return ($this->evaluation_access) ? $this->evaluation_access : self::EVALUATION_ACCESS_OFF; + } + + /** + * Sets the learners evaluation access + * + * @param integer $evaluation_access The evaluation access + * @access public + * @see $evaluation_access + */ + public function setEvaluationAccess($evaluation_access = self::EVALUATION_ACCESS_OFF) + { + $this->evaluation_access = ($evaluation_access) ? $evaluation_access : self::EVALUATION_ACCESS_OFF; + } + + public function setActivationVisibility($a_value) + { + $this->activation_visibility = (bool) $a_value; + } + + public function getActivationVisibility() + { + return $this->activation_visibility; + } + + public function isActivationLimited() + { + return (bool) $this->activation_limited; + } + + public function setActivationLimited($a_value) + { + $this->activation_limited = (bool) $a_value; + } + + /** + * Gets the introduction text + * + * @return string The introduction of the survey object + * @access public + * @see $introduction + */ + public function getIntroduction() + { + return (strlen($this->introduction)) ? $this->introduction : null; + } + + /** + * Gets the outro text + * + * @return string The outro of the survey object + * @access public + * @see $outro + */ + public function getOutro() + { + return (strlen($this->outro)) ? $this->outro : null; + } + + /** + * Gets the question id's of the questions which are already in the survey + * + * @return array The questions of the survey + * @access public + */ + public function &getExistingQuestions() + { + $ilDB = $this->db; + $existing_questions = array(); + $result = $ilDB->queryF( + "SELECT svy_question.original_id FROM svy_question, svy_svy_qst WHERE " . + "svy_svy_qst.survey_fi = %s AND svy_svy_qst.question_fi = svy_question.question_id", + array('integer'), + array($this->getSurveyId()) + ); + while ($data = $ilDB->fetchAssoc($result)) { + if ($data["original_id"]) { + array_push($existing_questions, $data["original_id"]); + } + } + return $existing_questions; + } + + /** + * Get the titles of all available survey question pools + * + * @return array An array of survey question pool titles + * @access public + */ + public function &getQuestionpoolTitles($could_be_offline = false, $showPath = false) + { + include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"; + return ilObjSurveyQuestionPool::_getAvailableQuestionpools($use_object_id = true, $could_be_offline, $showPath); + } + + /** + * Move questions and/or questionblocks to another position + * + * @param array $move_questions An array with the question id's of the questions to move + * @param integer $target_index The question id of the target position + * @param integer $insert_mode 0, if insert before the target position, 1 if insert after the target position + * @access public + */ + public function moveQuestions($move_questions, $target_index, $insert_mode) + { + $array_pos = array_search($target_index, $this->questions); + if ($insert_mode == 0) { + $part1 = array_slice($this->questions, 0, $array_pos); + $part2 = array_slice($this->questions, $array_pos); + } elseif ($insert_mode == 1) { + $part1 = array_slice($this->questions, 0, $array_pos + 1); + $part2 = array_slice($this->questions, $array_pos + 1); + } + foreach ($move_questions as $question_id) { + if (!(array_search($question_id, $part1) === false)) { + unset($part1[array_search($question_id, $part1)]); + } + if (!(array_search($question_id, $part2) === false)) { + unset($part2[array_search($question_id, $part2)]); + } + } + $part1 = array_values($part1); + $part2 = array_values($part2); + $this->questions = array_values(array_merge($part1, $move_questions, $part2)); + foreach ($move_questions as $question_id) { + $constraints = $this->getConstraints($question_id); + foreach ($constraints as $idx => $constraint) { + foreach ($part2 as $next_question_id) { + if ($constraint["question"] == $next_question_id) { + // constraint concerning a question that follows -> delete constraint + $this->deleteConstraint($constraint["id"]); + } + } + } + } + $this->saveQuestionsToDb(); + } + + /** + * Remove a question from the survey + * + * @param integer $question_id The database id of the question + * @access public + */ + public function removeQuestion($question_id) + { + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + $question = self::_instanciateQuestion($question_id); + #20610 if no question found, do nothing. + if ($question) { + $question->delete($question_id); + $this->removeConstraintsConcerningQuestion($question_id); + } + } + + /** + * Remove constraints concerning a question with a given question_id + * + * @param integer $question_id The database id of the question + * @access public + */ + public function removeConstraintsConcerningQuestion($question_id) + { + $ilDB = $this->db; + $result = $ilDB->queryF( + "SELECT constraint_fi FROM svy_qst_constraint WHERE question_fi = %s AND survey_fi = %s", + array('integer','integer'), + array($question_id, $this->getSurveyId()) + ); + if ($result->numRows() > 0) { + $remove_constraints = array(); + while ($row = $ilDB->fetchAssoc($result)) { + array_push($remove_constraints, $row["constraint_fi"]); + } + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_qst_constraint WHERE question_fi = %s AND survey_fi = %s", + array('integer','integer'), + array($question_id, $this->getSurveyId()) + ); + foreach ($remove_constraints as $key => $constraint_id) { + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_constraint WHERE constraint_id = %s", + array('integer'), + array($constraint_id) + ); + } + } + } + + /** + * Remove questions from the survey + * + * @param array $remove_questions An array with the question id's of the questions to remove + * @param array $remove_questionblocks An array with the questionblock id's of the questions blocks to remove + * @access public + */ + public function removeQuestions($remove_questions, $remove_questionblocks) + { + $ilDB = $this->db; + + $block_sizes = array(); + foreach ($this->getSurveyQuestions() as $question_id => $data) { + if (in_array($question_id, $remove_questions) or in_array($data["questionblock_id"], $remove_questionblocks)) { + unset($this->questions[array_search($question_id, $this->questions)]); + $this->removeQuestion($question_id); + } elseif ($data["questionblock_id"]) { + $block_sizes[$data["questionblock_id"]]++; + } + } + + // blocks with just 1 question need to be deleted + foreach ($block_sizes as $block_id => $size) { + if ($size < 2) { + $remove_questionblocks[] = $block_id; + } + } + + foreach (array_unique($remove_questionblocks) as $questionblock_id) { + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_qblk WHERE questionblock_id = %s", + array('integer'), + array($questionblock_id) + ); + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_qblk_qst WHERE questionblock_fi = %s AND survey_fi = %s", + array('integer','integer'), + array($questionblock_id, $this->getSurveyId()) + ); + } + + $this->questions = array_values($this->questions); + $this->saveQuestionsToDb(); + } + + /** + * Unfolds question blocks of a question pool + * + * @param array $questionblocks An array of question block id's + * @access public + */ + public function unfoldQuestionblocks($questionblocks) + { + $ilDB = $this->db; + foreach ($questionblocks as $index) { + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_qblk WHERE questionblock_id = %s", + array('integer'), + array($index) + ); + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_qblk_qst WHERE questionblock_fi = %s AND survey_fi = %s", + array('integer','integer'), + array($index, $this->getSurveyId()) + ); + } + } + + public function removeQuestionFromBlock($question_id, $questionblock_id) + { + $ilDB = $this->db; + + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_qblk_qst WHERE questionblock_fi = %s AND survey_fi = %s AND question_fi = %s", + array('integer','integer','integer'), + array($questionblock_id, $this->getSurveyId(), $question_id) + ); + } + + public function addQuestionToBlock($question_id, $questionblock_id) + { + $ilDB = $this->db; + + // see #22018 + if (!$this->isQuestionInAnyBlock($question_id)) { + $next_id = $ilDB->nextId('svy_qblk_qst'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_qblk_qst (qblk_qst_id, survey_fi, questionblock_fi, " . + "question_fi) VALUES (%s, %s, %s, %s)", + array('integer', 'integer', 'integer', 'integer'), + array($next_id, $this->getSurveyId(), $questionblock_id, $question_id) + ); + + $this->deleteConstraints($question_id); // #13713 + } + } + + /** + * Is question already in a block? + * + * @param int $a_question_fi question id as in svy_question + * @return bool + */ + public function isQuestionInAnyBlock($a_question_fi) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query("SELECT * FROM svy_qblk_qst " . + " WHERE survey_fi = " . $ilDB->quote($this->getSurveyId(), "integer") . + " AND question_fi = " . $ilDB->quote($a_question_fi, "integer")); + if ($rec = $ilDB->fetchAssoc($set)) { + return true; + } + return false; + } + + + /** + * Returns the question titles of all questions of a question block + * + * @result array The titles of the the question block questions + * @access public + */ + public function &getQuestionblockQuestions($questionblock_id) + { + $ilDB = $this->db; + $titles = array(); + $result = $ilDB->queryF( + "SELECT svy_question.title, svy_qblk_qst.question_fi, svy_qblk_qst.survey_fi FROM " . + "svy_qblk, svy_qblk_qst, svy_question WHERE svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi AND " . + "svy_question.question_id = svy_qblk_qst.question_fi AND svy_qblk.questionblock_id = %s", + array('integer'), + array($questionblock_id) + ); + $survey_id = ""; + while ($row = $ilDB->fetchAssoc($result)) { + $titles[$row["question_fi"]] = $row["title"]; + $survey_id = $row["survey_fi"]; + } + $result = $ilDB->queryF( + "SELECT question_fi, sequence FROM svy_svy_qst WHERE survey_fi = %s ORDER BY sequence", + array('integer'), + array($survey_id) + ); + $resultarray = array(); + $counter = 1; + while ($row = $ilDB->fetchAssoc($result)) { + if (array_key_exists($row["question_fi"], $titles)) { + $resultarray[$counter++] = $titles[$row["question_fi"]]; + } + } + return $resultarray; + } + + /** + * Returns the question id's of all questions of a question block + * + * @result array The id's of the the question block questions + * @access public + */ + public function &getQuestionblockQuestionIds($questionblock_id) + { + $ilDB = $this->db; + + // we need a correct order here, see #22011 + $result = $ilDB->queryF( + "SELECT a.question_fi FROM svy_qblk_qst a JOIN svy_svy_qst b ON (a.question_fi = b.question_fi) " . + " WHERE a.questionblock_fi = %s ORDER BY b.sequence", + array("integer"), + array($questionblock_id) + ); + $ids = array(); + if ($result->numRows()) { + while ($data = $ilDB->fetchAssoc($result)) { + if (!in_array($data['question_fi'], $ids)) { // no duplicates, see #22018 + array_push($ids, $data['question_fi']); + } + } + } + + return $ids; + } + + /** + * Returns the database row for a given question block + * + * @param integer $questionblock_id The database id of the question block + * @result array The database row of the question block + * @access public + */ + public static function _getQuestionblock($questionblock_id) + { + global $DIC; + + $ilDB = $DIC->database(); + $result = $ilDB->queryF( + "SELECT * FROM svy_qblk WHERE questionblock_id = %s", + array('integer'), + array($questionblock_id) + ); + $row = $ilDB->fetchAssoc($result); + return $row; + } + + /** + * Adds a questionblock to the database + * + * @param string $title The questionblock title + * @param integer $owner The database id of the owner + * @return integer The database id of the newly created questionblock + * @access public + */ + public static function _addQuestionblock($title = "", $owner = 0, $show_questiontext = true, $show_blocktitle = false) + { + global $DIC; + + $ilDB = $DIC->database(); + $next_id = $ilDB->nextId('svy_qblk'); + $ilDB->manipulateF( + "INSERT INTO svy_qblk (questionblock_id, title, show_questiontext," . + " show_blocktitle, owner_fi, tstamp) " . + "VALUES (%s, %s, %s, %s, %s, %s)", + array('integer','text','integer','integer','integer','integer'), + array($next_id, $title, $show_questiontext, $show_blocktitle, $owner, time()) + ); + return $next_id; + } + + /** + * Creates a question block for the survey + * + * @param string $title The title of the question block + * @param array $questions An array with the database id's of the question block questions + * @access public + */ + public function createQuestionblock($title, $show_questiontext, $show_blocktitle, $questions) + { + $ilDB = $this->db; + + // if the selected questions are not in a continous selection, move all questions of the + // questionblock at the position of the first selected question + $this->moveQuestions($questions, $questions[0], 0); + + // now save the question block + $ilUser = $this->user; + $next_id = $ilDB->nextId('svy_qblk'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_qblk (questionblock_id, title, show_questiontext," . + " show_blocktitle, owner_fi, tstamp) VALUES (%s, %s, %s, %s, %s, %s)", + array('integer','text','text','text','integer','integer'), + array($next_id, $title, $show_questiontext, $show_blocktitle, $ilUser->getId(), time()) + ); + if ($affectedRows) { + $questionblock_id = $next_id; + foreach ($questions as $index) { + if (!$this->isQuestionInAnyBlock($index)) { + $next_id = $ilDB->nextId('svy_qblk_qst'); // #22018 + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_qblk_qst (qblk_qst_id, survey_fi, questionblock_fi, " . + "question_fi) VALUES (%s, %s, %s, %s)", + array('integer', 'integer', 'integer', 'integer'), + array($next_id, $this->getSurveyId(), $questionblock_id, $index) + ); + $this->deleteConstraints($index); + } + } + } + } + + /** + * Modifies a question block + * + * @param integer $questionblock_id The database id of the question block + * @param string $title The title of the question block + * @access public + */ + public function modifyQuestionblock($questionblock_id, $title, $show_questiontext, $show_blocktitle) + { + $ilDB = $this->db; + $affectedRows = $ilDB->manipulateF( + "UPDATE svy_qblk SET title = %s, show_questiontext = %s," . + " show_blocktitle = %s WHERE questionblock_id = %s", + array('text','text','text','integer'), + array($title, $show_questiontext, $show_blocktitle, $questionblock_id) + ); + } + + /** + * Deletes the constraints for a question + * + * @param integer $question_id The database id of the question + * @access public + */ + public function deleteConstraints($question_id) + { + $ilDB = $this->db; + $result = $ilDB->queryF( + "SELECT constraint_fi FROM svy_qst_constraint WHERE question_fi = %s AND survey_fi = %s", + array('integer','integer'), + array($question_id, $this->getSurveyId()) + ); + $constraints = array(); + while ($row = $ilDB->fetchAssoc($result)) { + array_push($constraints, $row["constraint_fi"]); + } + foreach ($constraints as $constraint_id) { + $this->deleteConstraint($constraint_id); + } + } + + /** + * Deletes a constraint of a question + * + * @param integer $constraint_id The database id of the constraint + * @param integer $question_id The database id of the question + * @access public + */ + public function deleteConstraint($constraint_id) + { + $ilDB = $this->db; + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_constraint WHERE constraint_id = %s", + array('integer'), + array($constraint_id) + ); + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_qst_constraint WHERE constraint_fi = %s", + array('integer'), + array($constraint_id) + ); + } + + /** + * Returns the survey questions and questionblocks in an array + * + * @access public + */ + public function &getSurveyQuestions($with_answers = false) + { + $ilDB = $this->db; + // get questionblocks + $all_questions = array(); + $result = $ilDB->queryF( + "SELECT svy_qtype.type_tag, svy_qtype.plugin, svy_question.question_id, " . + "svy_svy_qst.heading FROM svy_qtype, svy_question, svy_svy_qst WHERE svy_svy_qst.survey_fi = %s AND " . + "svy_svy_qst.question_fi = svy_question.question_id AND svy_question.questiontype_fi = svy_qtype.questiontype_id " . + "ORDER BY svy_svy_qst.sequence", + array('integer'), + array($this->getSurveyId()) + ); + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + while ($row = $ilDB->fetchAssoc($result)) { + $add = true; + if ($row["plugin"]) { + if (!$this->isPluginActive($row["type_tag"])) { + $add = false; + } + } + if ($add) { + $question = self::_instanciateQuestion($row["question_id"]); + $questionrow = $question->getQuestionDataArray($row["question_id"]); + foreach ($row as $key => $value) { + $questionrow[$key] = $value; + } + $all_questions[$row["question_id"]] = $questionrow; + $all_questions[$row["question_id"]]["usableForPrecondition"] = $question->usableForPrecondition(); + $all_questions[$row["question_id"]]["availableRelations"] = $question->getAvailableRelations(); + } + } + // get all questionblocks + $questionblocks = array(); + if (count($all_questions)) { + $result = $ilDB->queryF( + "SELECT svy_qblk.*, svy_qblk_qst.question_fi FROM svy_qblk, svy_qblk_qst WHERE " . + "svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi AND svy_qblk_qst.survey_fi = %s " . + "AND " . $ilDB->in('svy_qblk_qst.question_fi', array_keys($all_questions), false, 'integer'), + array('integer'), + array($this->getSurveyId()) + ); + while ($row = $ilDB->fetchAssoc($result)) { + $questionblocks[$row['question_fi']] = $row; + } + } + + foreach ($all_questions as $question_id => $row) { + $constraints = $this->getConstraints($question_id); + if (isset($questionblocks[$question_id])) { + $all_questions[$question_id]["questionblock_title"] = $questionblocks[$question_id]['title']; + $all_questions[$question_id]["questionblock_id"] = $questionblocks[$question_id]['questionblock_id']; + $all_questions[$question_id]["constraints"] = $constraints; + } else { + $all_questions[$question_id]["questionblock_title"] = ""; + $all_questions[$question_id]["questionblock_id"] = ""; + $all_questions[$question_id]["constraints"] = $constraints; + } + if ($with_answers) { + $answers = array(); + $result = $ilDB->queryF( + "SELECT svy_variable.*, svy_category.title 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($question_id) + ); + if ($result->numRows() > 0) { + while ($data = $ilDB->fetchAssoc($result)) { + array_push($answers, $data["title"]); + } + } + $all_questions[$question_id]["answers"] = $answers; + } + } + return $all_questions; + } + + /** + * Sets the obligatory states for questions in a survey from the questions form + * + * @param array $obligatory_questions The questions which should be set obligatory from the questions form, the remaining questions should be setted not obligatory + * @access public + */ + public function setObligatoryStates($obligatory_questions) + { + $ilDB = $this->db; + $result = $ilDB->queryF( + "SELECT * FROM svy_svy_qst WHERE survey_fi = %s", + array('integer'), + array($this->getSurveyId()) + ); + if ($result->numRows()) { + while ($row = $ilDB->fetchAssoc($result)) { + if (!array_key_exists($row["question_fi"], $obligatory_questions)) { + $obligatory_questions[$row["question_fi"]] = 0; + } + } + } + + // set the obligatory states in the database + foreach ($obligatory_questions as $question_fi => $obligatory) { + // #12420 + $ilDB->manipulate("UPDATE svy_question" . + " SET obligatory = " . $ilDB->quote($obligatory, "integer") . + " WHERE question_id = " . $ilDB->quote($question_fi, "integer")); + } + } + + /** + * Returns the survey pages in an array (a page contains one or more questions) + * + * @access public + */ + public function &getSurveyPages() + { + $ilDB = $this->db; + // get questionblocks + $all_questions = array(); + $result = $ilDB->queryF( + "SELECT svy_question.*, svy_qtype.type_tag, svy_svy_qst.heading FROM " . + "svy_question, svy_qtype, svy_svy_qst WHERE svy_svy_qst.survey_fi = %s AND " . + "svy_svy_qst.question_fi = svy_question.question_id AND svy_question.questiontype_fi = svy_qtype.questiontype_id " . + "ORDER BY svy_svy_qst.sequence", + array('integer'), + array($this->getSurveyId()) + ); + while ($row = $ilDB->fetchAssoc($result)) { + $all_questions[$row["question_id"]] = $row; + } + // get all questionblocks + $questionblocks = array(); + if (count($all_questions)) { + $result = $ilDB->queryF( + "SELECT svy_qblk.*, svy_qblk_qst.question_fi FROM svy_qblk, svy_qblk_qst " . + "WHERE svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi AND svy_qblk_qst.survey_fi = %s " . + "AND " . $ilDB->in('svy_qblk_qst.question_fi', array_keys($all_questions), false, 'integer'), + array('integer'), + array($this->getSurveyId()) + ); + while ($row = $ilDB->fetchAssoc($result)) { + $questionblocks[$row['question_fi']] = $row; + } + } + + $all_pages = array(); + $pageindex = -1; + $currentblock = ""; + foreach ($all_questions as $question_id => $row) { + $constraints = array(); + if (isset($questionblocks[$question_id])) { + if (!$currentblock or ($currentblock != $questionblocks[$question_id]['questionblock_id'])) { + $pageindex++; + } + $all_questions[$question_id]['page'] = $pageindex; + $all_questions[$question_id]["questionblock_title"] = $questionblocks[$question_id]['title']; + $all_questions[$question_id]["questionblock_id"] = $questionblocks[$question_id]['questionblock_id']; + $all_questions[$question_id]["questionblock_show_questiontext"] = $questionblocks[$question_id]['show_questiontext']; + $all_questions[$question_id]["questionblock_show_blocktitle"] = $questionblocks[$question_id]['show_blocktitle']; + $currentblock = $questionblocks[$question_id]['questionblock_id']; + $constraints = $this->getConstraints($question_id); + $all_questions[$question_id]["constraints"] = $constraints; + } else { + $pageindex++; + $all_questions[$question_id]['page'] = $pageindex; + $all_questions[$question_id]["questionblock_title"] = ""; + $all_questions[$question_id]["questionblock_id"] = ""; + $all_questions[$question_id]["questionblock_show_questiontext"] = 1; + $all_questions[$question_id]["questionblock_show_blocktitle"] = 1; + $currentblock = ""; + $constraints = $this->getConstraints($question_id); + $all_questions[$question_id]["constraints"] = $constraints; + } + if (!isset($all_pages[$pageindex])) { + $all_pages[$pageindex] = array(); + } + array_push($all_pages[$pageindex], $all_questions[$question_id]); + } + // calculate position percentage for every page + $max = count($all_pages); + $counter = 1; + foreach ($all_pages as $index => $block) { + foreach ($block as $blockindex => $question) { + $all_pages[$index][$blockindex]["position"] = $counter / $max; + } + $counter++; + } + + return $all_pages; + } + + /** + * Returns the next "page" of a running test + * + * @param integer $active_page_question_id The database id of one of the questions on that page + * @param integer $direction The direction of the next page (-1 = previous page, 1 = next page) + * @return mixed An array containing the question id's of the questions on the next page if there is a next page, 0 if the next page is before the start page, 1 if the next page is after the last page + * @access public + */ + public function getNextPage($active_page_question_id, $direction) + { + $foundpage = -1; + $pages =&$this->getSurveyPages(); + if (strcmp($active_page_question_id, "") == 0) { + return $pages[0]; + } + foreach ($pages as $key => $question_array) { + foreach ($question_array as $question) { + if ($active_page_question_id == $question["question_id"]) { + $foundpage = $key; + } + } + } + if ($foundpage == -1) { + // error: page not found + } else { + $foundpage += $direction; + if ($foundpage < 0) { + return 0; + } + if ($foundpage >= count($pages)) { + return 1; + } + return $pages[$foundpage]; + } + } + + /** + * Returns the available question pools for the active user + * + * @return array The available question pools + * @access public + */ + public function &getAvailableQuestionpools($use_obj_id = false, $could_be_offline = false, $showPath = false, $permission = "read") + { + include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"; + return ilObjSurveyQuestionPool::_getAvailableQuestionpools($use_obj_id, $could_be_offline, $showPath, $permission); + } + + /** + * Returns a precondition with a given id + * + * @access public + */ + public function getPrecondition($id) + { + $ilDB = $this->db; + + $result_array = array(); + $result = $ilDB->queryF( + "SELECT svy_constraint.*, svy_relation.*, svy_qst_constraint.question_fi ref_question_fi FROM svy_qst_constraint, svy_constraint, " . + "svy_relation WHERE svy_constraint.relation_fi = svy_relation.relation_id AND " . + "svy_qst_constraint.constraint_fi = svy_constraint.constraint_id AND svy_constraint.constraint_id = %s", + array('integer'), + array($id) + ); + $pc = array(); + if ($result->numRows()) { + $pc = $ilDB->fetchAssoc($result); + } + return $pc; + } + + /** + * Returns the constraints to a given question or questionblock + * + * @access public + */ + public function getConstraints($question_id) + { + $ilDB = $this->db; + + $result_array = array(); + $result = $ilDB->queryF( + "SELECT svy_constraint.*, svy_relation.* FROM svy_qst_constraint, svy_constraint, svy_relation " . + "WHERE svy_constraint.relation_fi = svy_relation.relation_id AND " . + "svy_qst_constraint.constraint_fi = svy_constraint.constraint_id AND svy_qst_constraint.question_fi = %s " . + "AND svy_qst_constraint.survey_fi = %s", + array('integer','integer'), + array($question_id, $this->getSurveyId()) + ); + while ($row = $ilDB->fetchAssoc($result)) { + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + $question_type = SurveyQuestion::_getQuestionType($row["question_fi"]); + SurveyQuestion::_includeClass($question_type); + $question = new $question_type(); + $question->loadFromDb($row["question_fi"]); + $valueoutput = $question->getPreconditionValueOutput($row["value"]); + array_push($result_array, array("id" => $row["constraint_id"], "question" => $row["question_fi"], "short" => $row["shortname"], "long" => $row["longname"], "value" => $row["value"], "conjunction" => $row["conjunction"], "valueoutput" => $valueoutput)); + } + return $result_array; + } + + /** + * Returns the constraints to a given question or questionblock + * + * @access public + */ + public static function _getConstraints($survey_id) + { + global $DIC; + + $ilDB = $DIC->database(); + $result_array = array(); + $result = $ilDB->queryF( + "SELECT svy_qst_constraint.question_fi as for_question, svy_constraint.*, svy_relation.* " . + "FROM svy_qst_constraint, svy_constraint, svy_relation WHERE svy_constraint.relation_fi = svy_relation.relation_id " . + "AND svy_qst_constraint.constraint_fi = svy_constraint.constraint_id AND svy_qst_constraint.survey_fi = %s", + array('integer'), + array($survey_id) + ); + while ($row = $ilDB->fetchAssoc($result)) { + array_push($result_array, array("id" => $row["constraint_id"], "for_question" => $row["for_question"], "question" => $row["question_fi"], "short" => $row["shortname"], "long" => $row["longname"], "relation_id" => $row["relation_id"], "value" => $row["value"], 'conjunction' => $row['conjunction'])); + } + return $result_array; + } + + + /** + * Returns all variables of a question + * + * @access public + */ + public function &getVariables($question_id) + { + $ilDB = $this->db; + + $result_array = array(); + $result = $ilDB->queryF( + "SELECT svy_variable.*, svy_category.title FROM svy_variable LEFT JOIN " . + "svy_category ON svy_variable.category_fi = svy_category.category_id WHERE svy_variable.question_fi = %s " . + "ORDER BY svy_variable.sequence", + array('integer'), + array($question_id) + ); + while ($row = $ilDB->fetchObject($result)) { + $result_array[$row->sequence] = $row; + } + return $result_array; + } + + /** + * Adds a constraint + * + * @param integer $if_question_id The question id of the question which defines a precondition + * @param integer $relation The database id of the relation + * @param mixed $value The value compared with the relation + * @access public + */ + public function addConstraint($if_question_id, $relation, $value, $conjunction) + { + $ilDB = $this->db; + + $next_id = $ilDB->nextId('svy_constraint'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_constraint (constraint_id, question_fi, relation_fi, value, conjunction) VALUES " . + "(%s, %s, %s, %s, %s)", + array('integer','integer','integer','float', 'integer'), + array($next_id, $if_question_id, $relation, $value, $conjunction) + ); + if ($affectedRows) { + return $next_id; + } else { + return null; + } + } + + + /** + * Adds a constraint to a question + * + * @param integer $to_question_id The question id of the question where to add the constraint + * @param integer $constraint_id The id of the constraint + */ + public function addConstraintToQuestion($to_question_id, $constraint_id) + { + $ilDB = $this->db; + + $next_id = $ilDB->nextId('svy_qst_constraint'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_qst_constraint (question_constraint_id, survey_fi, question_fi, " . + "constraint_fi) VALUES (%s, %s, %s, %s)", + array('integer','integer','integer','integer'), + array($next_id, $this->getSurveyId(), $to_question_id, $constraint_id) + ); + } + + /** + * Updates a precondition + * + * @param integer $precondition_id The id of the original precondition + * @param integer $to_question_id The question id of the question where to add the constraint + * @param integer $if_question_id The question id of the question which defines a precondition + * @param integer $relation The database id of the relation + * @param mixed $value The value compared with the relation + * @access public + */ + public function updateConstraint($precondition_id, $if_question_id, $relation, $value, $conjunction) + { + $ilDB = $this->db; + $affectedRows = $ilDB->manipulateF( + "UPDATE svy_constraint SET question_fi = %s, relation_fi = %s, value = %s, conjunction = %s " . + "WHERE constraint_id = %s", + array('integer','integer','float','integer','integer'), + array($if_question_id, $relation, $value, $conjunction, $precondition_id) + ); + } + + public function updateConjunctionForQuestions($questions, $conjunction) + { + $ilDB = $this->db; + foreach ($questions as $question_id) { + $affectedRows = $ilDB->manipulateF( + "UPDATE svy_constraint SET conjunction = %s " . + "WHERE constraint_id IN (SELECT constraint_fi FROM svy_qst_constraint WHERE svy_qst_constraint.question_fi = %s)", + array('integer','integer'), + array($conjunction, $question_id) + ); + } + } + + /** + * Returns all available relations + * + * @access public + */ + public function getAllRelations($short_as_key = false) + { + $ilDB = $this->db; + + // #7987 + $custom_order = array("equal", "not_equal", "less", "less_or_equal", "more", "more_or_equal"); + $custom_order = array_flip($custom_order); + + $result_array = array(); + $result = $ilDB->query("SELECT * FROM svy_relation"); + while ($row = $ilDB->fetchAssoc($result)) { + if ($short_as_key) { + $result_array[$row["shortname"]] = array("short" => $row["shortname"], "long" => $row["longname"], "id" => $row["relation_id"], "order" => $custom_order[$row["longname"]]); + } else { + $result_array[$row["relation_id"]] = array("short" => $row["shortname"], "long" => $row["longname"], "order" => $custom_order[$row["longname"]]); + } + } + + $result_array = ilUtil::sortArray($result_array, "order", "ASC", true, true); + foreach ($result_array as $idx => $item) { + unset($result_array[$idx]["order"]); + } + + return $result_array; + } + + /** + * Disinvite all users + */ + public function disinviteAllUsers() + { + $ilDB = $this->db; + $result = $ilDB->queryF( + "SELECT user_fi FROM svy_inv_usr WHERE survey_fi = %s", + array('integer'), + array($this->getSurveyId()) + ); + while ($row = $ilDB->fetchAssoc($result)) { + $this->disinviteUser($row['user_fi']); + } + } + + /** + * Disinvites a user from a survey + * + * @param integer $user_id The database id of the disinvited user + */ + public function disinviteUser($user_id) + { + $ilDB = $this->db; + + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_inv_usr WHERE survey_fi = %s AND user_fi = %s", + array('integer','integer'), + array($this->getSurveyId(), $user_id) + ); + include_once './Services/User/classes/class.ilObjUser.php'; + ilObjUser::_dropDesktopItem($user_id, $this->getRefId(), "svy"); + } + + /** + * Invites a user to a survey + * + * @param integer $user_id The database id of the invited user + * @access public + */ + public function inviteUser($user_id) + { + $ilDB = $this->db; + + $result = $ilDB->queryF( + "SELECT user_fi FROM svy_inv_usr WHERE user_fi = %s AND survey_fi = %s", + array('integer','integer'), + array($user_id, $this->getSurveyId()) + ); + if ($result->numRows() < 1) { + $next_id = $ilDB->nextId('svy_inv_usr'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_inv_usr (invited_user_id, survey_fi, user_fi, tstamp) " . + "VALUES (%s, %s, %s, %s)", + array('integer','integer','integer','integer'), + array($next_id, $this->getSurveyId(), $user_id, time()) + ); + } + if ($this->getInvitation() == self::INVITATION_ON) { + include_once './Services/User/classes/class.ilObjUser.php'; + ilObjUser::_addDesktopItem($user_id, $this->getRefId(), "svy"); + } + } + + /** + * Returns a list of all invited users in a survey + * + * @return array The user id's of the invited users + * @access public + */ + public function &getInvitedUsers() + { + $ilDB = $this->db; + + $result_array = array(); + $result = $ilDB->queryF( + "SELECT user_fi FROM svy_inv_usr WHERE survey_fi = %s", + array('integer'), + array($this->getSurveyId()) + ); + while ($row = $ilDB->fetchAssoc($result)) { + array_push($result_array, $row["user_fi"]); + } + return $result_array; + } + + /** + * Deletes the working data of a question in the database + * + * @param integer $question_id The database id of the question + * @param integer $active_id The active id of the user who worked through the question + * @access public + */ + public function deleteWorkingData($question_id, $active_id) + { + $ilDB = $this->db; + + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_answer WHERE question_fi = %s AND active_fi = %s", + array('integer','integer'), + array($question_id, $active_id) + ); + } + + /** + * Gets the working data of question from the database + * + * @param integer $question_id The database id of the question + * @param integer $active_id The active id of the user who worked through the question + * @return array The resulting database dataset as an array + * @access public + */ + public function loadWorkingData($question_id, $active_id) + { + $ilDB = $this->db; + $result_array = array(); + $result = $ilDB->queryF( + "SELECT * FROM svy_answer WHERE question_fi = %s AND active_fi = %s", + array('integer','integer'), + array($question_id, $active_id) + ); + if ($result->numRows() >= 1) { + while ($row = $ilDB->fetchAssoc($result)) { + array_push($result_array, $row); + } + return $result_array; + } else { + return $result_array; + } + } + + /** + * Starts the survey creating an entry in the database + * + * @param integer $user_id The database id of the user who starts the survey + * @access public + */ + public function startSurvey($user_id, $anonymous_id, $appraisee_id) + { + $ilDB = $this->db; + + if ($this->getAnonymize() && (strlen($anonymous_id) == 0)) { + return; + } + + if (strcmp($user_id, "") == 0) { + if ($user_id == ANONYMOUS_USER_ID) { + $user_id = 0; + } + } + $next_id = $ilDB->nextId('svy_finished'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_finished (finished_id, survey_fi, user_fi, anonymous_id, state, tstamp, appr_id) " . + "VALUES (%s, %s, %s, %s, %s, %s, %s)", + array('integer','integer','integer','text','text','integer','integer'), + array($next_id, $this->getSurveyId(), $user_id, $anonymous_id, 0, time(), $appraisee_id) + ); + return $next_id; + } + + /** + * Finishes the survey creating an entry in the database + * + * @param integer $user_id The database id of the user who finishes the survey + * @access public + */ + public function finishSurvey($finished_id) + { + $ilDB = $this->db; + + $ilDB->manipulateF( + "UPDATE svy_finished SET state = %s, tstamp = %s" . + " WHERE survey_fi = %s AND finished_id = %s", + array('text','integer','integer','integer'), + array(1, time(), $this->getSurveyId(), $finished_id) + ); + + // self eval writes skills on finishing + if ($this->getMode() == ilObjSurvey::MODE_SELF_EVAL) { + $user = $this->getUserDataFromActiveId($finished_id); + $sskill = new ilSurveySkill($this); + $sskill->writeSelfEvalSkills($user['usr_id']); + } + + $this->checkTutorNotification(); + } + + /** + * Sets the number of the active survey page + * + * @param integer $finished_id The database id of the active user + * @param integer $page_id The index of the page + * @access public + */ + public function setPage($finished_id, $page_id) + { + $ilDB = $this->db; + + $affectedRows = $ilDB->manipulateF( + "UPDATE svy_finished SET lastpage = %s WHERE finished_id = %s", + array('integer','integer'), + array(($page_id) ? $page_id : 0, $finished_id) + ); + } + + /** + * @param $a_user_id user who did the survey + * @param $a_anonymize_id + * @param $a_appr_id + */ + public function sendNotificationMail($a_user_id, $a_anonymize_id, $a_appr_id) + { + // #12755 + $placeholders = array( + "FIRST_NAME" => "firstname", + "LAST_NAME" => "lastname", + "LOGIN" => "login", + // old style + "firstname" => "firstname" + ); + + //mailaddresses is just text split by commas. + //sendMail can send emails if it gets an user id or an email as first parameter. + $recipients = preg_split('/,/', $this->mailaddresses); + foreach ($recipients as $recipient) { + // #11298 + $ntf = new ilSystemNotification(); + $ntf->setLangModules(array("survey")); + $ntf->setRefId($this->getRefId()); + $ntf->setSubjectLangId('finished_mail_subject'); + + $messagetext = $this->mailparticipantdata; + if (trim($messagetext)) { + if (!$this->hasAnonymizedResults()) { + $data = ilObjUser::_getUserData(array($a_user_id)); + $data = $data[0]; + } + foreach ($placeholders as $key => $mapping) { + if ($this->hasAnonymizedResults()) { // #16480 + $messagetext = str_replace('[' . $key . ']', '', $messagetext); + } else { + $messagetext = str_replace('[' . $key . ']', trim($data[$mapping]), $messagetext); + } + } + $ntf->setIntroductionDirect($messagetext); + } else { + $ntf->setIntroductionLangId('survey_notification_finished_introduction'); + } + + // 360°? add appraisee data + if ($a_appr_id) { + $ntf->addAdditionalInfo( + 'survey_360_appraisee', + ilUserUtil::getNamePresentation($a_appr_id) + ); + } + + $active_id = $this->getActiveID($a_user_id, $a_anonymize_id, $a_appr_id); + $ntf->addAdditionalInfo( + 'results', + $this->getParticipantTextResults($active_id), + true + ); + + $ntf->setGotoLangId('survey_notification_tutor_link'); + $ntf->setReasonLangId('survey_notification_finished_reason'); + + if (is_numeric($recipient)) { + $lng = $ntf->getUserLanguage($recipient); + $ntf->sendMail(array($recipient), null, null); + } else { + $recipient = trim($recipient); + $user_ids = ilObjUser::getUserIdsByEmail($recipient); + if (empty($user_ids)) { + $ntf->sendMail(array($recipient), null, null); + } else { + foreach ($user_ids as $user_id) { + $lng = $ntf->getUserLanguage($user_id); + $ntf->sendMail(array($user_id), null, null); + } + } + } + } + } + + protected function getParticipantTextResults($active_id) + { + $textresult = ""; + $userResults =&$this->getUserSpecificResults(array($active_id)); + $questions =&$this->getSurveyQuestions(true); + $questioncounter = 1; + foreach ($questions as $question_id => $question_data) { + $textresult .= $questioncounter++ . ". " . $question_data["title"] . "\n"; + $found = $userResults[$question_id][$active_id]; + $text = ""; + if (is_array($found)) { + $text = implode("\n", $found); + } else { + $text = $found; + } + if (strlen($text) == 0) { + $text = self::getSurveySkippedValue(); + } + $text = str_replace("
", "\n", $text); + $textresult .= $text . "\n\n"; + } + return $textresult; + } + + /** + * Checks if a user already started a survey + * + * @param integer $user_id The database id of the user + * @return mixed false, if the user has not started the survey, 0 if the user has started the survey but not finished it, 1 if the user has finished the survey + * @access public + */ + public function isSurveyStarted($user_id, $anonymize_id, $appr_id = 0) + { + $ilDB = $this->db; + + // #15031 - should not matter if code was used by registered or anonymous (each code must be unique) + if ($anonymize_id) { + $result = $ilDB->queryF( + "SELECT * FROM svy_finished" . + " WHERE survey_fi = %s AND anonymous_id = %s AND appr_id = %s", + array('integer','text','integer'), + array($this->getSurveyId(), $anonymize_id, $appr_id) + ); + } else { + $result = $ilDB->queryF( + "SELECT * FROM svy_finished" . + " WHERE survey_fi = %s AND user_fi = %s AND appr_id = %s", + array('integer','integer','integer'), + array($this->getSurveyId(), $user_id, $appr_id) + ); + } + if ($result->numRows() == 0) { + return false; + } else { + $row = $ilDB->fetchAssoc($result); + // yes, we are doing it this way + $_SESSION["finished_id"][$this->getId()] = $row["finished_id"]; + + return (int) $row["state"]; + } + } + + /** + * Checks if a user already started a survey + * + * @param integer $user_id The database id of the user + * @return mixed false, if the user has not started the survey, 0 if the user has started the survey but not finished it, 1 if the user has finished the survey + * @access public + */ + public function getActiveID($user_id, $anonymize_id, $appr_id) + { + $ilDB = $this->db; + + // see self::isSurveyStarted() + + // #15031 - should not matter if code was used by registered or anonymous (each code must be unique) + if ($anonymize_id) { + $result = $ilDB->queryF( + "SELECT finished_id FROM svy_finished" . + " WHERE survey_fi = %s AND anonymous_id = %s AND appr_id = %s", + array('integer','text','integer'), + array($this->getSurveyId(), $anonymize_id, $appr_id) + ); + } else { + $result = $ilDB->queryF( + "SELECT finished_id FROM svy_finished" . + " WHERE survey_fi = %s AND user_fi = %s AND appr_id = %s", + array('integer','integer','integer'), + array($this->getSurveyId(), $user_id, $appr_id) + ); + } + if ($result->numRows() == 0) { + return false; + } else { + $row = $ilDB->fetchAssoc($result); + return $row["finished_id"]; + } + } + + /** + * Returns the question id of the last active page a user visited in a survey + * + * @param integer $active_id The active id of the user + * @return mixed Empty string if the user has not worked through a page, question id of the last page otherwise + * @access public + */ + public function getLastActivePage($active_id) + { + $ilDB = $this->db; + $result = $ilDB->queryF( + "SELECT lastpage FROM svy_finished WHERE finished_id = %s", + array('integer'), + array($active_id) + ); + if ($result->numRows() == 0) { + return ""; + } else { + $row = $ilDB->fetchAssoc($result); + return ($row["lastpage"]) ? $row["lastpage"] : ''; + } + } + + /** + * Checks if a constraint is valid + * + * @param array $constraint_data The database row containing the constraint data + * @param array $working_data The user input of the related question + * @return boolean true if the constraint is valid, otherwise false + * @access public + */ + public function checkConstraint($constraint_data, $working_data) + { + if (count($working_data) == 0) { + return 0; + } + + if ((count($working_data) == 1) and (strcmp($working_data[0]["value"], "") == 0)) { + return 0; + } + + $found = false; + foreach ($working_data as $data) { + switch ($constraint_data["short"]) { + case "<": + if ($data["value"] < $constraint_data["value"]) { + $found = true; + } + break; + + case "<=": + if ($data["value"] <= $constraint_data["value"]) { + $found = true; + } + break; + + case "=": + if ($data["value"] == $constraint_data["value"]) { + $found = true; + } + break; + + case "<>": + if ($data["value"] <> $constraint_data["value"]) { + $found = true; + } + break; + + case ">=": + if ($data["value"] >= $constraint_data["value"]) { + $found = true; + } + break; + + case ">": + if ($data["value"] > $constraint_data["value"]) { + $found = true; + } + break; + } + if ($found) { + break; + } + } + + return (int) $found; + } + + public static function _hasDatasets($survey_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $result = $ilDB->queryF( + "SELECT finished_id FROM svy_finished WHERE survey_fi = %s", + array('integer'), + array($survey_id) + ); + return ($result->numRows()) ? true : false; + } + + /** + * Get the finished id's of all survey participants + * + * @return array An array containing finished_id's of all survey participants + * @access public + */ + public function &getSurveyFinishedIds() + { + $ilDB = $this->db; + $ilLog = $this->log; + + $users = array(); + $result = $ilDB->queryF( + "SELECT * FROM svy_finished WHERE survey_fi = %s", + array('integer'), + array($this->getSurveyId()) + ); + if ($result->numRows()) { + while ($row = $ilDB->fetchAssoc($result)) { + array_push($users, $row["finished_id"]); + } + } + return $users; + } + + /** + * Calculates the evaluation data for the user specific results + * + * @return array An array containing the user specific results + * @access public + */ + public function getUserSpecificResults($finished_ids) + { + $evaluation = array(); + + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + foreach (array_keys($this->getSurveyQuestions()) as $question_id) { + // get question instance + $question_type = SurveyQuestion::_getQuestionType($question_id); + SurveyQuestion::_includeClass($question_type); + $question = new $question_type(); + $question->loadFromDb($question_id); + + $q_eval = SurveyQuestion::_instanciateQuestionEvaluation($question_id, $finished_ids); + $q_res = $q_eval->getResults(); + + $data = array(); + foreach ($finished_ids as $user_id) { + $data[$user_id] = $q_eval->parseUserSpecificResults($q_res, $user_id); + } + + $evaluation[$question_id] = $data; + } + + return $evaluation; + } + + /** + * Returns the user information from an active_id (survey_finished.finished_id) + * + * @param integer $active_id The active id of the user + * @return array An array containing the user data + * @access public + */ + public function getUserDataFromActiveId($active_id, $force_non_anonymous = false) + { + $ilDB = $this->db; + + $surveySetting = new ilSetting("survey"); + $use_anonymous_id = array_key_exists("use_anonymous_id", $_GET) ? $_GET["use_anonymous_id"] : $surveySetting->get("use_anonymous_id"); + $result = $ilDB->queryF( + "SELECT * FROM svy_finished WHERE finished_id = %s", + array('integer'), + array($active_id) + ); + $row = array(); + $foundrows = $result->numRows(); + if ($foundrows) { + $row = $ilDB->fetchAssoc($result); + } + $name = ($use_anonymous_id) ? $row["anonymous_id"] : $this->lng->txt("anonymous"); + $userdata = array( + "fullname" => $name, + "sortname" => $name, + "firstname" => "", + "lastname" => "", + "login" => "", + "gender" => "", + "active_id" => "$active_id" + ); + if ($foundrows) { + if (($row["user_fi"] > 0) && + (($row["user_fi"] != ANONYMOUS_USER_ID && + !$this->hasAnonymizedResults() && + !$this->get360Mode()) || // 360° uses ANONYMIZE_CODE_ALL which is wrong - see ilObjSurveyGUI::afterSave() + (bool) $force_non_anonymous)) { + include_once './Services/User/classes/class.ilObjUser.php'; + if (strlen(ilObjUser::_lookupLogin($row["user_fi"])) == 0) { + $userdata["fullname"] = $userdata["sortname"] = $this->lng->txt("deleted_user"); + } else { + $user = new ilObjUser($row["user_fi"]); + $userdata['usr_id'] = $row['user_fi']; + $userdata["fullname"] = $user->getFullname(); + $gender = $user->getGender(); + if (strlen($gender) == 1) { + $gender = $this->lng->txt("gender_$gender"); + } + $userdata["gender"] = $gender; + $userdata["firstname"] = $user->getFirstname(); + $userdata["lastname"] = $user->getLastname(); + $userdata["sortname"] = $user->getLastname() . ", " . $user->getFirstname(); + $userdata["login"] = $user->getLogin(); + } + } + } + return $userdata; + } + + /** + * Calculates the evaluation data for a given user or anonymous id + * + * @param array $questions An array containing all relevant information on the survey's questions + * @param integer $user_id The database id of the user + * @param string $anonymous_id The unique anonymous id for an anonymous survey + * @return array An array containing the evaluation parameters for the user + * @access public + */ + public function &getEvaluationByUser($questions, $active_id) + { + $ilDB = $this->db; + + // collect all answers + $answers = array(); + $result = $ilDB->queryF( + "SELECT * FROM svy_answer WHERE active_fi = %s", + array('integer'), + array($active_id) + ); + while ($row = $ilDB->fetchAssoc($result)) { + if (!is_array($answers[$row["question_fi"]])) { + $answers[$row["question_fi"]] = array(); + } + array_push($answers[$row["question_fi"]], $row); + } + $userdata = $this->getUserDataFromActiveId($active_id); + $resultset = array( + "name" => $userdata["fullname"], + "firstname" => $userdata["firstname"], + "lastname" => $userdata["lastname"], + "login" => $userdata["login"], + "gender" => $userdata["gender"], + "answers" => array() + ); + foreach ($questions as $key => $question) { + if (array_key_exists($key, $answers)) { + $resultset["answers"][$key] = $answers[$key]; + } else { + $resultset["answers"][$key] = array(); + } + sort($resultset["answers"][$key]); + } + return $resultset; + } + + /** + * Calculates the data for the output of the question browser + * + * @access public + */ + public function getQuestionsTable($arrFilter) + { + $ilUser = $this->user; + $ilDB = $this->db; + $where = ""; + if (is_array($arrFilter)) { + if (array_key_exists('title', $arrFilter) && strlen($arrFilter['title'])) { + $where .= " AND " . $ilDB->like('svy_question.title', 'text', "%%" . $arrFilter['title'] . "%%"); + } + if (array_key_exists('description', $arrFilter) && strlen($arrFilter['description'])) { + $where .= " AND " . $ilDB->like('svy_question.description', 'text', "%%" . $arrFilter['description'] . "%%"); + } + if (array_key_exists('author', $arrFilter) && strlen($arrFilter['author'])) { + $where .= " AND " . $ilDB->like('svy_question.author', 'text', "%%" . $arrFilter['author'] . "%%"); + } + if (array_key_exists('type', $arrFilter) && strlen($arrFilter['type'])) { + $where .= " AND svy_qtype.type_tag = " . $ilDB->quote($arrFilter['type'], 'text'); + } + if (array_key_exists('spl', $arrFilter) && strlen($arrFilter['spl'])) { + $where .= " AND svy_question.obj_fi = " . $ilDB->quote($arrFilter['spl'], 'integer'); + } + } + + $spls =&$this->getAvailableQuestionpools($use_obj_id = true, $could_be_offline = false, $showPath = false); + $forbidden = ""; + $forbidden = " AND " . $ilDB->in('svy_question.obj_fi', array_keys($spls), false, 'integer'); + $forbidden .= " AND svy_question.complete = " . $ilDB->quote("1", 'text'); + $existing = ""; + $existing_questions =&$this->getExistingQuestions(); + if (count($existing_questions)) { + $existing = " AND " . $ilDB->in('svy_question.question_id', $existing_questions, true, 'integer'); + } + + include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"; + $trans = ilObjSurveyQuestionPool::_getQuestionTypeTranslations(); + + $query_result = $ilDB->query("SELECT svy_question.*, svy_qtype.type_tag, svy_qtype.plugin, object_reference.ref_id" . + " FROM svy_question, svy_qtype, object_reference" . + " WHERE svy_question.original_id IS NULL" . $forbidden . $existing . + " AND svy_question.obj_fi = object_reference.obj_id AND svy_question.tstamp > 0" . + " AND svy_question.questiontype_fi = svy_qtype.questiontype_id " . $where); + + $rows = array(); + if ($query_result->numRows()) { + while ($row = $ilDB->fetchAssoc($query_result)) { + if (array_key_exists('spl_txt', $arrFilter) && strlen($arrFilter['spl_txt'])) { + if (!stristr($spls[$row["obj_fi"]], $arrFilter['spl_txt'])) { + continue; + } + } + + $row['ttype'] = $trans[$row['type_tag']]; + if ($row["plugin"]) { + if ($this->isPluginActive($row["type_tag"])) { + array_push($rows, $row); + } + } else { + array_push($rows, $row); + } + } + } + return $rows; + } + + /** + * Calculates the data for the output of the questionblock browser + * + * @access public + */ + public function getQuestionblocksTable($arrFilter) + { + $ilUser = $this->user; + $ilDB = $this->db; + + $where = ""; + if (is_array($arrFilter)) { + if (array_key_exists('title', $arrFilter) && strlen($arrFilter['title'])) { + $where .= " AND " . $ilDB->like('svy_qblk.title', 'text', "%%" . $arrFilter['title'] . "%%"); + } + } - $query_result = $ilDB->query("SELECT svy_qblk.*, svy_svy.obj_fi FROM svy_qblk , svy_qblk_qst, svy_svy WHERE ". - "svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi AND svy_svy.survey_id = svy_qblk_qst.survey_fi ". - "$where GROUP BY svy_qblk.questionblock_id, svy_qblk.title, svy_qblk.show_questiontext, svy_qblk.show_blocktitle, ". - "svy_qblk.owner_fi, svy_qblk.tstamp, svy_svy.obj_fi"); - $rows = array(); - if ($query_result->numRows()) - { - $survey_ref_ids = ilUtil::_getObjectsByOperations("svy", "write"); - $surveytitles = array(); - foreach ($survey_ref_ids as $survey_ref_id) - { - $survey_id = ilObject::_lookupObjId($survey_ref_id); - $surveytitles[$survey_id] = ilObject::_lookupTitle($survey_id); - } - while ($row = $ilDB->fetchAssoc($query_result)) - { - $questions_array =& $this->getQuestionblockQuestions($row["questionblock_id"]); - $counter = 1; - foreach ($questions_array as $key => $value) - { - $questions_array[$key] = "$counter. $value"; - $counter++; - } - if (strlen($surveytitles[$row["obj_fi"]])) // only questionpools which are not in trash - { - $rows[$row["questionblock_id"]] = array( - "questionblock_id" => $row["questionblock_id"], - "title" => $row["title"], - "svy" => $surveytitles[$row["obj_fi"]], - "contains" => join($questions_array, ", "), - "owner" => $row["owner_fi"] - ); - } - } - } - return $rows; - } - - /** - * Returns a QTI xml representation of the survey - * - * @return string The QTI xml representation of the survey - * @access public - */ - function toXML() - { - include_once("./Services/Xml/classes/class.ilXmlWriter.php"); - $a_xml_writer = new ilXmlWriter; - // set xml header - $a_xml_writer->xmlHeader(); - $attrs = array( - "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance", - "xsi:noNamespaceSchemaLocation" => "http://www.ilias.de/download/xsd/ilias_survey_4_2.xsd" - ); - $a_xml_writer->xmlStartTag("surveyobject", $attrs); - $attrs = array( - "id" => $this->getSurveyId(), - "title" => $this->getTitle() - ); - $a_xml_writer->xmlStartTag("survey", $attrs); - - $a_xml_writer->xmlElement("description", NULL, $this->getDescription()); - $a_xml_writer->xmlElement("author", NULL, $this->getAuthor()); - $a_xml_writer->xmlStartTag("objectives"); - $attrs = array( - "label" => "introduction" - ); - $this->addMaterialTag($a_xml_writer, $this->getIntroduction(), TRUE, TRUE, $attrs); - $attrs = array( - "label" => "outro" - ); - $this->addMaterialTag($a_xml_writer, $this->getOutro(), TRUE, TRUE, $attrs); - $a_xml_writer->xmlEndTag("objectives"); - - if ($this->getAnonymize()) - { - $attribs = array("enabled" => "1"); - } - else - { - $attribs = array("enabled" => "0"); - } - $a_xml_writer->xmlElement("anonymisation", $attribs); - $a_xml_writer->xmlStartTag("restrictions"); - if ($this->getAnonymize() == 2) - { - $attribs = array("type" => "free"); - } - else - { - $attribs = array("type" => "restricted"); - } - $a_xml_writer->xmlElement("access", $attribs); - if ($this->getStartDate()) - { - $attrs = array("type" => "date"); - preg_match("/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/", $this->getStartDate(), $matches); - $a_xml_writer->xmlElement("startingtime", $attrs, sprintf("%04d-%02d-%02dT%02d:%02d:00", $matches[1], $matches[2], $matches[3], $matches[4], $matches[5], $matches[6])); - } - if ($this->getEndDate()) - { - $attrs = array("type" => "date"); - preg_match("/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/", $this->getEndDate(), $matches); - $a_xml_writer->xmlElement("endingtime", $attrs, sprintf("%04d-%02d-%02dT%02d:%02d:00", $matches[1], $matches[2], $matches[3], $matches[4], $matches[5], $matches[6])); - - } - $a_xml_writer->xmlEndTag("restrictions"); - - // constraints - $pages =& $this->getSurveyPages(); - $hasconstraints = FALSE; - foreach ($pages as $question_array) - { - foreach ($question_array as $question) - { - if (count($question["constraints"])) - { - $hasconstraints = TRUE; - } - } - } - - if ($hasconstraints) - { - $a_xml_writer->xmlStartTag("constraints"); - foreach ($pages as $question_array) - { - foreach ($question_array as $question) - { - if (count($question["constraints"])) - { - // found constraints - foreach ($question["constraints"] as $constraint) - { - $attribs = array( - "sourceref" => $question["question_id"], - "destref" => $constraint["question"], - "relation" => $constraint["short"], - "value" => $constraint["value"], - "conjunction" => $constraint["conjunction"] - ); - $a_xml_writer->xmlElement("constraint", $attribs); - } - } - } - } - $a_xml_writer->xmlEndTag("constraints"); - } - - // add the rest of the preferences in qtimetadata tags, because there is no correspondent definition in QTI - $a_xml_writer->xmlStartTag("metadata"); - - $custom_properties = array(); - $custom_properties["evaluation_access"] = $this->getEvaluationAccess(); - $custom_properties["status"] = !$this->getOfflineStatus(); - $custom_properties["display_question_titles"] = $this->getShowQuestionTitles(); - $custom_properties["pool_usage"] = (int)$this->getPoolUsage(); - - $custom_properties["own_results_view"] = (int)$this->hasViewOwnResults(); - $custom_properties["own_results_mail"] = (int)$this->hasMailOwnResults(); - $custom_properties["confirmation_mail"] = (int)$this->hasMailConfirmation(); - - $custom_properties["anon_user_list"] = (int)$this->hasAnonymousUserList(); - $custom_properties["mode"] = (int)$this->getMode(); - $custom_properties["mode_360_self_eval"] = (int)$this->get360SelfEvaluation(); - $custom_properties["mode_360_self_rate"] = (int)$this->get360SelfRaters(); - $custom_properties["mode_360_self_appr"] = (int)$this->get360SelfAppraisee(); - $custom_properties["mode_360_results"] = $this->get360Results(); - $custom_properties["mode_skill_service"] = (int)$this->getSkillService(); - $custom_properties["mode_self_eval_results"] = (int)$this->getSelfEvaluationResults(); - - - // :TODO: skills? - - // reminder/tutor notification are (currently?) not exportable - - foreach($custom_properties as $label => $value) - { - $a_xml_writer->xmlStartTag("metadatafield"); - $a_xml_writer->xmlElement("fieldlabel", NULL, $label); - $a_xml_writer->xmlElement("fieldentry", NULL, $value); - $a_xml_writer->xmlEndTag("metadatafield"); - } - - $a_xml_writer->xmlStartTag("metadatafield"); - $a_xml_writer->xmlElement("fieldlabel", NULL, "SCORM"); - include_once "./Services/MetaData/classes/class.ilMD.php"; - $md = new ilMD($this->getId(),0, $this->getType()); - $writer = new ilXmlWriter(); - $md->toXml($writer); - $metadata = $writer->xmlDumpMem(); - $a_xml_writer->xmlElement("fieldentry", NULL, $metadata); - $a_xml_writer->xmlEndTag("metadatafield"); - - $a_xml_writer->xmlEndTag("metadata"); - $a_xml_writer->xmlEndTag("survey"); - - $attribs = array("id" => $this->getId()); - $a_xml_writer->xmlStartTag("surveyquestions", $attribs); - // add questionblock descriptions - foreach ($pages as $question_array) - { - if (count($question_array) > 1) - { - $attribs = array("id" => $question_array[0]["question_id"]); - $attribs = array("showQuestiontext" => $question_array[0]["questionblock_show_questiontext"], - "showBlocktitle" => $question_array[0]["questionblock_show_blocktitle"]); - $a_xml_writer->xmlStartTag("questionblock", $attribs); - if (strlen($question_array[0]["questionblock_title"])) - { - $a_xml_writer->xmlElement("questionblocktitle", NULL, $question_array[0]["questionblock_title"]); - } - } - foreach ($question_array as $question) - { - if (strlen($question["heading"])) - { - $a_xml_writer->xmlElement("textblock", NULL, $question["heading"]); - } - $questionObject = self::_instanciateQuestion($question["question_id"]); - //questionObject contains all the fields from the database. (loadFromDb) - //we don't need the value from svy_qst_oblig table, we already have the values from svy_question table. - //if ($questionObject !== FALSE) $questionObject->insertXML($a_xml_writer, FALSE, $obligatory_states[$question["question_id"]]); - if ($questionObject !== FALSE) $questionObject->insertXML($a_xml_writer, FALSE); - } - if (count($question_array) > 1) - { - $a_xml_writer->xmlEndTag("questionblock"); - } - } - - $a_xml_writer->xmlEndTag("surveyquestions"); - $a_xml_writer->xmlEndTag("surveyobject"); - $xml = $a_xml_writer->xmlDumpMem(FALSE); - return $xml; - } - - /** - * 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) - { - if ($question_id < 1) return FALSE; - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - $question_type = SurveyQuestion::_getQuestionType($question_id); - if (strlen($question_type) == 0) return FALSE; - SurveyQuestion::_includeClass($question_type); - $question = new $question_type(); - $question->loadFromDb($question_id); - return $question; - } - - /** - * Locates the import directory and the xml file in a directory with an unzipped import file - * - * @return array An associative array containing "dir" (import directory) and "xml" (xml file) - * @access private - */ - function locateImportFiles($a_dir) - { - if (!is_dir($a_dir) || is_int(strpos($a_dir, ".."))) - { - return; - } - $importDirectory = ""; - $xmlFile = ""; - - $current_dir = opendir($a_dir); - $files = array(); - while($entryname = readdir($current_dir)) - { - $files[] = $entryname; - } - - foreach($files as $file) - { - if(is_dir($a_dir."/".$file) and ($file != "." and $file!="..")) - { - // found directory created by zip - $importDirectory = $a_dir."/".$file; - } - } - closedir($current_dir); - if (strlen($importDirectory)) - { - // find the xml file - $current_dir = opendir($importDirectory); - $files = array(); - while($entryname = readdir($current_dir)) - { - $files[] = $entryname; - } - foreach($files as $file) - { - if(@is_file($importDirectory."/".$file) && - ($file != "." && $file!="..") && - (preg_match("/^[0-9]{10}__[0-9]+__(svy_)*[0-9]+\.[A-Za-z]{1,3}$/", $file) || - preg_match("/^[0-9]{10}__[0-9]+__(survey__)*[0-9]+\.[A-Za-z]{1,3}$/", $file))) - { - // found xml file - $xmlFile = $importDirectory."/".$file; - } - } - } - return array("dir" => $importDirectory, "xml" => $xmlFile); - } - - /** - * Imports a survey from XML into the ILIAS database - * @param $file_info - * @param $svy_qpl_id - * @return string - * @throws ilFileUtilsException - * @throws ilInvalidSurveyImportFileException - */ - function importObject($file_info, $svy_qpl_id) - { - if ($svy_qpl_id < 1) $svy_qpl_id = -1; - // check if file was uploaded - $source = $file_info["tmp_name"]; - $error = ""; - if (($source == 'none') || (!$source) || $file_info["error"] > UPLOAD_ERR_OK) - { - $error = $this->lng->txt("import_no_file_selected"); - } - // check correct file type - $isXml = FALSE; - $isZip = FALSE; - if ((strcmp($file_info["type"], "text/xml") == 0) || (strcmp($file_info["type"], "application/xml") == 0)) - { - $this->log->debug("isXML"); - $isXml = TRUE; - } - // too many different mime-types, so we use the suffix - $suffix = pathinfo($file_info["name"]); - if (strcmp(strtolower($suffix["extension"]), "zip") == 0) - { - $this->log->debug("isZip"); - $isZip = TRUE; - } - if (!$isXml && !$isZip) - { - $error = $this->lng->txt("import_wrong_file_type"); - $this->log->debug("Survey: Import error. Filetype was \"" . $file_info["type"] ."\""); - } - if (strlen($error) == 0) - { - // import file as a survey - $import_dir = $this->getImportDirectory(); - $import_subdir = ""; - $importfile = ""; - if ($isZip) - { - $importfile = $import_dir."/".$file_info["name"]; - ilUtil::moveUploadedFile($source, $file_info["name"], $importfile); - ilUtil::unzip($importfile); - $found = $this->locateImportFiles($import_dir); - if (!((strlen($found["dir"]) > 0) && (strlen($found["xml"]) > 0))) - { - $error = $this->lng->txt("wrong_import_file_structure"); - return $error; - } - $importfile = $found["xml"]; - $import_subdir = $found["dir"]; - } - else - { - $importfile = tempnam($import_dir, "survey_import"); - ilUtil::moveUploadedFile($source, $file_info["name"], $importfile); - } - - $this->log->debug("Import file = $importfile"); - $this->log->debug("Import subdir = $import_subdir"); - - $fh = fopen($importfile, "r"); - if (!$fh) - { - $error = $this->lng->txt("import_error_opening_file"); - return $error; - } - $xml = fread($fh, filesize($importfile)); - $result = fclose($fh); - if (!$result) - { - $error = $this->lng->txt("import_error_closing_file"); - return $error; - } - - unset($_SESSION["import_mob_xhtml"]); - if (strpos($xml, "questestinterop")) - { - include_once("./Modules/Survey/exceptions/class.ilInvalidSurveyImportFileException.php"); - throw new ilInvalidSurveyImportFileException("Unsupported survey version (< 3.8) found."); - } - else - { - $this->log->debug("survey id = ".$this->getId()); - $this->log->debug("question pool id = ".$svy_qpl_id); - - include_once("./Services/Export/classes/class.ilImport.php"); - $imp = new ilImport(); - $config = $imp->getConfig("Modules/Survey"); - $config->setQuestionPoolID($svy_qpl_id); - $imp->getMapping()->addMapping("Modules/Survey", "svy", 0, $this->getId()); - $imp->importFromDirectory($import_subdir, "svy", "Modules/Survey"); - $this->log->debug("config(Modules/survey)->getQuestionPoolId =".$config->getQuestionPoolID()); - return ""; - - //old code - include_once "./Services/Survey/classes/class.SurveyImportParser.php"; - $import = new SurveyImportParser($svy_qpl_id, "", TRUE); - $import->setSurveyObject($this); - $import->setXMLContent($xml); - $import->startParsing(); - } - - if (is_array($_SESSION["import_mob_xhtml"])) - { - include_once "./Services/MediaObjects/classes/class.ilObjMediaObject.php"; - include_once "./Services/RTE/classes/class.ilRTE.php"; - include_once "./Modules/TestQuestionPool/classes/class.ilObjQuestionPool.php"; - foreach ($_SESSION["import_mob_xhtml"] as $mob) - { - $importfile = $import_subdir . "/" . $mob["uri"]; - if (file_exists($importfile)) - { - if (!$mob["type"]) - { - $mob["type"] = "svy:html"; - } - - $media_object = ilObjMediaObject::_saveTempFileAsMediaObject(basename($importfile), $importfile, FALSE); - - // survey mob - if ($mob["type"] == "svy:html") - { - ilObjMediaObject::_saveUsage($media_object->getId(), "svy:html", $this->getId()); - $this->setIntroduction(str_replace("src=\"" . $mob["mob"] . "\"", "src=\"" . "il_" . IL_INST_ID . "_mob_" . $media_object->getId() . "\"", $this->getIntroduction())); - $this->setOutro(str_replace("src=\"" . $mob["mob"] . "\"", "src=\"" . "il_" . IL_INST_ID . "_mob_" . $media_object->getId() . "\"", $this->getOutro())); - } - // question mob - else if($import->questions[$mob["id"]]) - { - $new_qid = $import->questions[$mob["id"]]; - ilObjMediaObject::_saveUsage($media_object->getId(), $mob["type"], $new_qid); - $new_question = SurveyQuestion::_instanciateQuestion($new_qid); - $qtext = $new_question->getQuestiontext(); - $qtext = ilRTE::_replaceMediaObjectImageSrc($qtext, 0); - $qtext = str_replace("src=\"" . $mob["mob"] . "\"", "src=\"" . "il_" . IL_INST_ID . "_mob_" . $media_object->getId() . "\"", $qtext); - $qtext = ilRTE::_replaceMediaObjectImageSrc($qtext, 1); - $new_question->setQuestiontext($qtext); - $new_question->saveToDb(); - - // also fix existing original in pool - if($new_question->getOriginalId()) - { - $pool_question = SurveyQuestion::_instanciateQuestion($new_question->getOriginalId()); - $pool_question->setQuestiontext($qtext); - $pool_question->saveToDb(); - } - } - } - else - { - $ilLog = $this->log; - $ilLog->write("Error: Could not open XHTML mob file for test introduction during test import. File $importfile does not exist!"); - } - } - $this->setIntroduction(ilRTE::_replaceMediaObjectImageSrc($this->getIntroduction(), 1)); - $this->setOutro(ilRTE::_replaceMediaObjectImageSrc($this->getOutro(), 1)); - $this->saveToDb(); - } - - // delete import directory - ilUtil::delDir($this->getImportDirectory()); - } - return $error; - } - - /** - * Clone object - * - * @access public - * @param int ref_id of target container - * @param int copy id - * @return object new svy object - */ - public function cloneObject($a_target_id,$a_copy_id = 0, $a_omit_tree = false) - { - $ilDB = $this->db; - - $this->loadFromDb(); - - //survey mode - $svy_type = $this->getMode(); - - // Copy settings - $newObj = parent::cloneObject($a_target_id,$a_copy_id, $a_omit_tree); - $this->cloneMetaData($newObj); - $newObj->updateMetaData(); - - $newObj->setAuthor($this->getAuthor()); - $newObj->setIntroduction($this->getIntroduction()); - $newObj->setOutro($this->getOutro()); - $newObj->setEvaluationAccess($this->getEvaluationAccess()); - $newObj->setStartDate($this->getStartDate()); - $newObj->setEndDate($this->getEndDate()); - $newObj->setInvitation($this->getInvitation()); - $newObj->setInvitationMode($this->getInvitationMode()); - $newObj->setAnonymize($this->getAnonymize()); - $newObj->setShowQuestionTitles($this->getShowQuestionTitles()); - $newObj->setTemplate($this->getTemplate()); - $newObj->setPoolUsage($this->getPoolUsage()); - $newObj->setViewOwnResults($this->hasViewOwnResults()); - $newObj->setMailOwnResults($this->hasMailOwnResults()); - $newObj->setMailConfirmation($this->hasMailConfirmation()); - $newObj->setAnonymousUserList($this->hasAnonymousUserList()); - - // #12661 - if($this->get360Mode()) - { - $newObj->setMode(ilObjSurvey::MODE_360); - $newObj->set360SelfEvaluation($this->get360SelfEvaluation()); - $newObj->set360SelfAppraisee($this->get360SelfAppraisee()); - $newObj->set360SelfRaters($this->get360SelfRaters()); - $newObj->set360Results($this->get360Results()); - $newObj->setSkillService($this->getSkillService()); - } - //svy mode self eval: skills + view results - if($svy_type == ilObjSurvey::MODE_SELF_EVAL) - { - $newObj->setMode(ilObjSurvey::MODE_SELF_EVAL); - $newObj->setSkillService($this->getSkillService()); - $newObj->setSelfEvaluationResults($this->getSelfEvaluationResults()); - } - - // reminder/notification - $newObj->setReminderStatus($this->getReminderStatus()); - $newObj->setReminderStart($this->getReminderStart()); - $newObj->setReminderEnd($this->getReminderEnd()); - $newObj->setReminderFrequency($this->getReminderFrequency()); - $newObj->setReminderTarget($this->getReminderTarget()); - $newObj->setReminderTemplate($this->getReminderTemplate()); - // reminder_last_sent must not be copied! - $newObj->setTutorNotificationStatus($this->getTutorNotificationStatus()); - $newObj->setTutorNotificationRecipients($this->getTutorNotificationRecipients()); - $newObj->setTutorNotificationTarget($this->getTutorNotificationTarget()); - - $newObj->setMailNotification($this->getMailNotification()); - $newObj->setMailAddresses($this->getMailAddresses()); - $newObj->setMailParticipantData($this->getMailParticipantData()); - - $question_pointer = array(); - // clone the questions - $mapping = array(); - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - - foreach ($this->questions as $key => $question_id) - { - $question = self::_instanciateQuestion($question_id); - if($question) // #10824 - { - $question->id = -1; - $original_id = SurveyQuestion::_getOriginalId($question_id, false); - $question->saveToDb($original_id); - $newObj->questions[$key] = $question->getId(); - $question_pointer[$question_id] = $question->getId(); - $mapping[$question_id] = $question->getId(); - } - } - - //copy online status if object is not the root copy object - $cp_options = ilCopyWizardOptions::_getInstance($a_copy_id); - - if(!$cp_options->isRootNode($this->getRefId())) - { - $newObj->setOfflineStatus($this->getOfflineStatus()); - } - - $newObj->saveToDb(); - $newObj->cloneTextblocks($mapping); - - // #14929 - if(($svy_type == ilObjSurvey::MODE_360 || $svy_type == ilObjSurvey::MODE_SELF_EVAL) && - $this->getSkillService()) - { - include_once "./Modules/Survey/classes/class.ilSurveySkill.php"; - $src_skills = new ilSurveySkill($this); - $tgt_skills = new ilSurveySkill($newObj); - - foreach($mapping as $src_qst_id => $tgt_qst_id) - { - $qst_skill = $src_skills->getSkillForQuestion($src_qst_id); - if($qst_skill) - { - $tgt_skills->addQuestionSkillAssignment($tgt_qst_id, $qst_skill["base_skill_id"], $qst_skill["tref_id"]); - } - } - } - - // clone the questionblocks - $questionblocks = array(); - $questionblock_questions = array(); - $result = $ilDB->queryF("SELECT * FROM svy_qblk_qst WHERE survey_fi = %s", - array('integer'), - array($this->getSurveyId()) - ); - if ($result->numRows() > 0) - { - while ($row = $ilDB->fetchAssoc($result)) - { - array_push($questionblock_questions, $row); - $questionblocks[$row["questionblock_fi"]] = $row["questionblock_fi"]; - } - } - // create new questionblocks - foreach ($questionblocks as $key => $value) - { - $questionblock = self::_getQuestionblock($key); - $questionblock_id = self::_addQuestionblock($questionblock["title"], $questionblock["owner_fi"], $questionblock["show_questiontext"], $questionblock["show_blocktitle"]); - $questionblocks[$key] = $questionblock_id; - } - // create new questionblock questions - foreach ($questionblock_questions as $key => $value) - { - if($questionblocks[$value["questionblock_fi"]] && - $question_pointer[$value["question_fi"]]) - { - $next_id = $ilDB->nextId('svy_qblk_qst'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qblk_qst (qblk_qst_id, survey_fi, questionblock_fi, question_fi) ". - "VALUES (%s, %s, %s, %s)", - array('integer','integer','integer','integer'), - array($next_id, $newObj->getSurveyId(), $questionblocks[$value["questionblock_fi"]], $question_pointer[$value["question_fi"]]) - ); - } - } - - // clone the constraints - $constraints = self::_getConstraints($this->getSurveyId()); - $newConstraints = array(); - foreach ($constraints as $key => $constraint) - { - if ($question_pointer[$constraint["for_question"]] && - $question_pointer[$constraint["question"]]) - { - if (!array_key_exists($constraint['id'], $newConstraints)) - { - $constraint_id = $newObj->addConstraint($question_pointer[$constraint["question"]], $constraint["relation_id"], $constraint["value"], $constraint['conjunction']); - $newConstraints[$constraint['id']] = $constraint_id; - } - $newObj->addConstraintToQuestion($question_pointer[$constraint["for_question"]], $newConstraints[$constraint['id']]); - } - } - - // #16210 - clone LP settings - include_once('./Services/Tracking/classes/class.ilLPObjSettings.php'); - $obj_settings = new ilLPObjSettings($this->getId()); - $obj_settings->cloneSettings($newObj->getId()); - unset($obj_settings); - - return $newObj; - } - - function getTextblock($question_id) - { - $ilDB = $this->db; - $result = $ilDB->queryF("SELECT * FROM svy_svy_qst WHERE question_fi = %s", - array('integer'), - array($question_id) - ); - if ($result->numRows()) - { - $row = $ilDB->fetchAssoc($result); - return $row["heading"]; - } - else - { - return ""; - } - } - - /** - * Clones the textblocks of survey questions - * - * @access public - */ - function cloneTextblocks($mapping) - { - foreach ($mapping as $original_id => $new_id) - { - $textblock = $this->getTextblock($original_id); - include_once "./Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php"; - $this->saveHeading(ilUtil::stripSlashes($textblock, TRUE, ilObjAdvancedEditing::_getUsedHTMLTagsAsString("survey")), $new_id); - } - } - - /** - * creates data directory for export files - * (data_dir/svy_data/svy_/export, depending on data - * directory that is set in ILIAS setup/ini) - * - * @throws ilSurveyException - */ - function createExportDirectory() - { - $svy_data_dir = ilUtil::getDataDir()."/svy_data"; - ilUtil::makeDir($svy_data_dir); - if(!is_writable($svy_data_dir)) - { - include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; - throw new ilSurveyException("Survey Data Directory (".$svy_data_dir.") not writeable."); - } - - // create learning module directory (data_dir/lm_data/lm_) - $svy_dir = $svy_data_dir."/svy_".$this->getId(); - ilUtil::makeDir($svy_dir); - if(!@is_dir($svy_dir)) - { - include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; - throw new ilSurveyException("Creation of Survey Directory failed."); - } - // create Export subdirectory (data_dir/lm_data/lm_/Export) - $export_dir = $svy_dir."/export"; - ilUtil::makeDir($export_dir); - if(!@is_dir($export_dir)) - { - include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; - throw new ilSurveyException("Creation of Export Directory failed."); - } - } - - /** - * get export directory of survey - */ - function getExportDirectory() - { - $export_dir = ilUtil::getDataDir()."/svy_data"."/svy_".$this->getId()."/export"; - - return $export_dir; - } - - /** - * creates data directory for import files - * (data_dir/svy_data/svy_/import, depending on data - * directory that is set in ILIAS setup/ini) - * - * @throws ilSurveyException - */ - function createImportDirectory() - { - $svy_data_dir = ilUtil::getDataDir()."/svy_data"; - ilUtil::makeDir($svy_data_dir); - - if(!is_writable($svy_data_dir)) - { - include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; - throw new ilSurveyException("Survey Data Directory (".$svy_data_dir.") not writeable."); - } - - // create test directory (data_dir/svy_data/svy_) - $svy_dir = $svy_data_dir."/svy_".$this->getId(); - ilUtil::makeDir($svy_dir); - if(!@is_dir($svy_dir)) - { - include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; - throw new ilSurveyException("Creation of Survey Directory failed."); - } - - // create import subdirectory (data_dir/svy_data/svy_/import) - $import_dir = $svy_dir."/import"; - ilUtil::makeDir($import_dir); - if(!@is_dir($import_dir)) - { - include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; - throw new ilSurveyException("Creation of Import Directory failed."); - } - } - - /** - * get import directory of survey - */ - function getImportDirectory() - { - $import_dir = ilUtil::getDataDir()."/svy_data". - "/svy_".$this->getId()."/import"; - if (!is_dir($import_dir)) - { - ilUtil::makeDirParents($import_dir); - } - if(@is_dir($import_dir)) - { - return $import_dir; - } - else - { - return false; - } - } - - function saveHeading($heading = "", $insertbefore) - { - $ilDB = $this->db; - if ($heading) - { - $affectedRows = $ilDB->manipulateF("UPDATE svy_svy_qst SET heading=%s WHERE survey_fi=%s AND question_fi=%s", - array('text','integer','integer'), - array($heading, $this->getSurveyId(), $insertbefore) - ); - } - else - { - $affectedRows = $ilDB->manipulateF("UPDATE svy_svy_qst SET heading=%s WHERE survey_fi=%s AND question_fi=%s", - array('text','integer','integer'), - array(NULL, $this->getSurveyId(), $insertbefore) - ); - } - } - - function isAnonymousKey($key) - { - $ilDB = $this->db; - - $result = $ilDB->queryF("SELECT anonymous_id FROM svy_anonymous WHERE survey_key = %s AND survey_fi = %s", - array('text','integer'), - array($key, $this->getSurveyId()) - ); - return ($result->numRows() == 1) ? true : false; - } - - function bindSurveyCodeToUser($user_id, $code) - { - $ilDB = $this->db; - - if($user_id == ANONYMOUS_USER_ID) - { - return; - } - - if($this->checkSurveyCode($code)) - { - $ilDB->manipulate("UPDATE svy_anonymous". - " SET user_key = ".$ilDB->quote(md5($user_id), "text"). - " WHERE survey_key = ".$ilDB->quote($code, "text")); - } - } - - function isAnonymizedParticipant($key) - { - $ilDB = $this->db; - - $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE anonymous_id = %s AND survey_fi = %s", - array('text','integer'), - array($key, $this->getSurveyId()) - ); - return ($result->numRows() == 1) ? true : false; - } - - function checkSurveyCode($code) - { - if ($this->isAnonymousKey($code)) - { - if ($this->isSurveyStarted("", $code) == 1) - { - return false; - } - else - { - return true; - } - } - else - { - return false; - } - } - - /** - * Returns a list of survey codes for file export - * - * @param array $a_array An array of all survey codes that should be exported - * @return string A comma separated list of survey codes an URLs for file export - * @access public - */ - function getSurveyCodesForExport(array $a_codes = null, array $a_ids = null) - { - $ilDB = $this->db; - $ilUser = $this->user; - $lng = $this->lng; - - include_once "./Services/Link/classes/class.ilLink.php"; - - $sql = "SELECT svy_anonymous.*, svy_finished.state". - " FROM svy_anonymous". - " LEFT JOIN svy_finished ON (svy_anonymous.survey_key = svy_finished.anonymous_id)". - " WHERE svy_anonymous.survey_fi = ".$ilDB->quote($this->getSurveyId(), "integer"). - " AND svy_anonymous.user_key IS NULL"; - - if($a_codes) - { - $sql .= " AND ".$ilDB->in("svy_anonymous.survey_key", $a_codes, "", "text"); - } - else if($a_ids) - { - $sql .= " AND ".$ilDB->in("svy_anonymous.anonymous_id", $a_ids, "", "text"); - } - - $export = array(); - - // #14905 - $titles = array(); - $titles[] = '"'.$lng->txt("survey_code").'"'; - $titles[] = '"'.$lng->txt("email").'"'; - $titles[] = '"'.$lng->txt("lastname").'"'; - $titles[] = '"'.$lng->txt("firstname").'"'; - $titles[] = '"'.$lng->txt("create_date").'"'; - $titles[] = '"'.$lng->txt("used").'"'; - $titles[] = '"'.$lng->txt("mail_sent_short").'"'; - $titles[] = '"'.$lng->txt("survey_code_url").'"'; - $export[] = implode(";", $titles); - - $result = $ilDB->query($sql); - $default_lang = $ilUser->getPref("survey_code_language"); - while ($row = $ilDB->fetchAssoc($result)) - { - $item = array(); - $item[] = $row["survey_key"]; - - if($row["externaldata"]) - { - $ext = unserialize($row["externaldata"]); - $item[] = $ext["email"]; - $item[] = $ext["lastname"]; - $item[] = $ext["firstname"]; - } - else - { - $item[] = ""; - $item[] = ""; - $item[] = ""; - } - - // No relative (today, tomorrow...) dates in export. - $date = new ilDateTime($row['tstamp'],IL_CAL_UNIX); - $item[] = $date->get(IL_CAL_DATETIME); - - $item[] = ($this->isSurveyCodeUsed($row["survey_key"])) ? 1 : 0; - $item[] = ($row["sent"]) ? 1 : 0; - - $params = array("accesscode" => $row["survey_key"]); - if ($default_lang) - { - $params["lang"] = $default_lang; - } - $item[] = ilLink::_getLink($this->getRefId(), "svy", $params); - - $export[] = '"'.implode('";"', $item).'"'; - } - return implode("\n", $export); - } - - /** - * Fetches the data for the survey codes table - * - * @param string $lang Language for the survey code URL - * @return array The requested data - * @access public - */ - public function getSurveyCodesTableData(array $ids = null, $lang = null) - { - $ilDB = $this->db; - - include_once "./Services/Link/classes/class.ilLink.php"; - - $codes = array(); - - $sql = "SELECT svy_anonymous.*, svy_finished.state". - " FROM svy_anonymous". - " LEFT JOIN svy_finished ON (svy_anonymous.survey_key = svy_finished.anonymous_id)". - " WHERE svy_anonymous.survey_fi = ".$ilDB->quote($this->getSurveyId(), "integer") /*. - " AND svy_anonymous.user_key IS NULL" */; // #15860 - - if($ids) - { - $sql .= " AND ".$ilDB->in("svy_anonymous.anonymous_id", $ids, "", "integer"); - } - - $sql .= " ORDER BY tstamp, survey_key ASC"; - $result = $ilDB->query($sql); - if ($result->numRows() > 0) - { - while ($row = $ilDB->fetchAssoc($result)) - { - $href = ""; - $used = false; - if ($this->isSurveyCodeUsed($row["survey_key"])) - { - $used = true; - } - else - { - $params = array("accesscode" => $row["survey_key"]); - if ($lang) - { - $params["lang"] = $lang; - } - $href = ilLink::_getLink($this->getRefId(), "svy", $params); - } - - - $item = array( - 'id' => $row["anonymous_id"], - 'code' => $row["survey_key"], - 'date' => $row["tstamp"], - 'used' => $used, - 'sent' => $row['sent'], - 'href' => $href, - 'email' => '', - 'last_name' => '', - 'first_name' => '' - ); - - if($row["externaldata"]) - { - $ext = unserialize($row["externaldata"]); - $item['email'] = $ext['email']; - $item['last_name'] = $ext['lastname']; - $item['first_name'] = $ext['firstname']; - } - - array_push($codes, $item); - } - } - return $codes; - } - - function isSurveyCodeUsed($code) - { - $ilDB = $this->db; - $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s AND anonymous_id = %s", - array('integer','text'), - array($this->getSurveyId(), $code) - ); - return ($result->numRows() > 0) ? true : false; - } - - function isSurveyCodeUnique($code) - { - $ilDB = $this->db; - $result = $ilDB->queryF("SELECT anonymous_id FROM svy_anonymous WHERE survey_fi = %s AND survey_key = %s", - array('integer','text'), - array($this->getSurveyId(), $code) - ); - return ($result->numRows() > 0) ? false : true; - } - - function createSurveyCodes($nrOfCodes) - { - $ilDB = $this->db; - - $res = array(); - - for ($i = 0; $i < $nrOfCodes; $i++) - { - $next_id = $ilDB->nextId('svy_anonymous'); - $ilDB->manipulateF("INSERT INTO svy_anonymous (anonymous_id, survey_key, survey_fi, tstamp) ". - "VALUES (%s, %s, %s, %s)", - array('integer','text','integer','integer'), - array($next_id, $this->createNewAccessCode(), $this->getSurveyId(), time()) - ); - $res[] = $next_id; - } - - return $res; - } - - function importSurveyCode($a_anonymize_key, $a_created, $a_data) - { - $ilDB = $this->db; - - $next_id = $ilDB->nextId('svy_anonymous'); - $ilDB->manipulateF("INSERT INTO svy_anonymous (anonymous_id, survey_key, survey_fi, externaldata, tstamp) ". - "VALUES (%s, %s, %s, %s, %s)", - array('integer','text','integer','text','integer'), - array($next_id, $a_anonymize_key, $this->getSurveyId(), serialize($a_data), $a_created) - ); - } - - function createSurveyCodesForExternalData($data) - { - $ilDB = $this->db; - - $ids = array(); - foreach ($data as $dataset) - { - $anonymize_key = $this->createNewAccessCode(); - $next_id = $ilDB->nextId('svy_anonymous'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_anonymous (anonymous_id, survey_key, survey_fi, externaldata, tstamp) ". - "VALUES (%s, %s, %s, %s, %s)", - array('integer','text','integer','text','integer'), - array($next_id, $anonymize_key, $this->getSurveyId(), serialize($dataset), time()) - ); - $ids[] = $next_id; - } - return $ids; - } - - function sendCodes($not_sent, $subject, $message, $lang) - { - global $DIC; - /* - * 0 = all - * 1 = not sent - * 2 = finished - * 3 = not finished - */ - $check_finished = ($not_sent > 1); - - include_once "./Services/Mail/classes/class.ilMail.php"; - include_once "./Services/Link/classes/class.ilLink.php"; - - #19956 - $user_id = $DIC->user()->getId(); - $mail = new ilMail($user_id); - $recipients = $this->getExternalCodeRecipients($check_finished); - foreach ($recipients as $data) - { - if($data['email'] && $data['code']) - { - $do_send = false; - switch ((int)$not_sent) - { - case 1: - $do_send = !(bool)$data['sent']; - break; - - case 2: - $do_send = $data['finished']; - break; - - case 3: - $do_send = !$data['finished']; - break; - - default: - $do_send = true; - break; - } - if ($do_send) - { - // build text - $messagetext = $message; - $url = ilLink::_getLink($this->getRefId(), "svy", - array( - "accesscode" => $data["code"], - "lang" => $lang - )); - $messagetext = str_replace('[url]', $url, $messagetext); - foreach ($data as $key => $value) - { - $messagetext = str_replace('[' . $key . ']', $value, $messagetext); - } - - // send mail - $mail->sendMail( - $data['email'], // to - "", // cc - "", // bcc - $subject, // subject - $messagetext, // message - array(), // attachments - array('normal') // type - ); - } - } - } - - $ilDB = $this->db; - $ilDB->manipulateF("UPDATE svy_anonymous SET sent = %s WHERE survey_fi = %s AND externaldata IS NOT NULL", - array('integer','integer'), - array(1, $this->getSurveyId()) - ); - } - - function getExternalCodeRecipients($a_check_finished = false) - { - $ilDB = $this->db; - $result = $ilDB->queryF("SELECT survey_key code, externaldata, sent FROM svy_anonymous WHERE survey_fi = %s", - array('integer'), - array($this->getSurveyId()) - ); - $res = array(); - while ($row = $ilDB->fetchAssoc($result)) - { - if(!$row['externaldata']) - { - continue; - } - - $externaldata = unserialize($row['externaldata']); - if(!$externaldata['email']) - { - continue; - } - - $externaldata['code'] = $row['code']; - $externaldata['sent'] = $row['sent']; - - if($a_check_finished) - { - #23294 - //$externaldata['finished'] = $this->isSurveyCodeUsed($row['code']); - $externaldata['finished'] = $this->isSurveyFinishedByCode($row['code']); - } - - array_push($res, $externaldata); - } - return $res; - } - - /** - * Get if survey is finished for an specific anonymous user code. - * @param $a_code anonymous user code - * @return bool - */ - function isSurveyFinishedByCode($a_code) - { - $result = $this->db->queryF("SELECT state FROM svy_finished WHERE survey_fi = %s AND anonymous_id = %s", - array('integer','text'), - array($this->getSurveyId(), $a_code)); - - $row = $this->db->fetchAssoc($result); - - return $row['state']; - } - - /** - * Deletes a given survey access code - * - * @param string $survey_code The survey code that should be deleted - */ - function deleteSurveyCode($survey_code) - { - $ilDB = $this->db; - - if (strlen($survey_code) > 0) - { - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_anonymous WHERE survey_fi = %s AND survey_key = %s", - array('integer', 'text'), - array($this->getSurveyId(), $survey_code) - ); - } - } - - /** - * Returns a survey access code that was saved for a registered user - * - * @param int $user_id The database id of the user - * @return string The survey access code of the user - */ - function getUserAccessCode($user_id) - { - $ilDB = $this->db; - $access_code = ""; - $result = $ilDB->queryF("SELECT survey_key FROM svy_anonymous WHERE survey_fi = %s AND user_key = %s", - array('integer','text'), - array($this->getSurveyId(), md5($user_id)) - ); - if ($result->numRows()) - { - $row = $ilDB->fetchAssoc($result); - $access_code = $row["survey_key"]; - } - return $access_code; - } - - /** - * Saves a survey access code for a registered user to the database - * - * @param int $user_id The database id of the user - * @param string $access_code The survey access code - */ - function saveUserAccessCode($user_id, $access_code) - { - $ilDB = $this->db; - - // not really sure what to do about ANONYMOUS_USER_ID - - $next_id = $ilDB->nextId('svy_anonymous'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_anonymous (anonymous_id, survey_key, survey_fi, user_key, tstamp) ". - "VALUES (%s, %s, %s, %s, %s)", - array('integer','text', 'integer', 'text', 'integer'), - array($next_id, $access_code, $this->getSurveyId(), md5($user_id), time()) - ); - } - - /** - * Returns a new, unused survey access code - * - * @return string A new survey access code - */ - function createNewAccessCode() - { - // create a 5 character code - $codestring = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; - mt_srand(); - $code = ""; - for ($i = 1; $i <=5; $i++) - { - $index = mt_rand(0, strlen($codestring)-1); - $code .= substr($codestring, $index, 1); - } - // verify it against the database - while (!$this->isSurveyCodeUnique($code)) - { - $code = $this->createNewAccessCode(); - } - return $code; - } - - function getLastAccess($finished_id) - { - $ilDB = $this->db; - - $result = $ilDB->queryF("SELECT tstamp FROM svy_answer WHERE active_fi = %s ORDER BY tstamp DESC", - array('integer'), - array($finished_id) - ); - if ($result->numRows()) - { - $row = $ilDB->fetchAssoc($result); - return $row["tstamp"]; - } - else - { - $result = $ilDB->queryF("SELECT tstamp FROM svy_finished WHERE finished_id = %s", - array('integer'), - array($finished_id) - ); - if ($result->numRows()) - { - $row = $ilDB->fetchAssoc($result); - return $row["tstamp"]; - } - } - return ""; - } - - /** - * 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) - { - return ilUtil::prepareTextareaOutput($txt_output, $prepare_for_latex_output); - } - - /** - * 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; - } - } - - /** - * 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, $attribs = NULL) - { - include_once "./Services/RTE/classes/class.ilRTE.php"; - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - - $a_xml_writer->xmlStartTag("material", $attribs); - $attrs = array( - "type" => "text/plain" - ); - if ($this->isHTML($a_material)) - { - $attrs["type"] = "text/xhtml"; - } - $mattext = ilRTE::_replaceMediaObjectImageSrc($a_material, 0); - $a_xml_writer->xmlElement("mattext", $attrs, $mattext); - - if ($add_mobs) - { - $mobs = ilObjMediaObject::_getMobsOfObject("svy:html", $this->getId()); - foreach ($mobs as $mob) - { - $mob_id = "il_" . IL_INST_ID . "_mob_" . $mob; - if (strpos($mattext, $mob_id) !== FALSE) - { - $mob_obj = new ilObjMediaObject($mob); - $imgattrs = array( - "label" => $mob_id, - "uri" => "objects/" . "il_" . IL_INST_ID . "_mob_" . $mob . "/" . $mob_obj->getTitle(), - "type" => "svy:html", - "id" => $this->getId() - ); - $a_xml_writer->xmlElement("matimage", $imgattrs, NULL); - } - } - } - if ($close_material_tag) $a_xml_writer->xmlEndTag("material"); - } - - /** - * Checks if the survey code can be exported with the survey evaluation. In some cases this may be - * necessary but usually you should prevent it because people who sent the survey codes could connect - * real people with the survey code in the evaluation and undermine the anonymity - * - * @return boolean TRUE if the survey is anonymized and the survey code may be shown in the export file - * @author Helmut Schottmüller - **/ - function canExportSurveyCode() - { - if ($this->getAnonymize() != self::ANONYMIZE_OFF) - { - if ($this->surveyCodeSecurity == FALSE) - { - return TRUE; - } - } - return FALSE; - } - - /** - * Convert a print output to XSL-FO - * - * @param string $print_output The print output - * @return string XSL-FO code - * @access public - */ - function processPrintoutput2FO($print_output) - { - if (extension_loaded("tidy")) - { - $config = array( - "indent" => false, - "output-xml" => true, - "numeric-entities" => true - ); - $tidy = new tidy(); - $tidy->parseString($print_output, $config, 'utf8'); - $tidy->cleanRepair(); - $print_output = tidy_get_output($tidy); - $print_output = preg_replace("/^.*?( $print_output, '/_xsl' => $xsl ); - $xh = xslt_create(); - $params = array(); - try - { - $output = xslt_process($xh, "arg:/_xml", "arg:/_xsl", null, $args, $params); - } - catch (Exception $e) - { - $this->log->error("Print XSLT failed:"); - $this->log->error("Content: ".$print_output); - $this->log->error("Xsl: ".$xsl); - throw ($e); - } - xslt_error($xh); - xslt_free($xh); - - return $output; - } - - /** - * Delivers a PDF file from a XSL-FO string - * - * @param string $fo The XSL-FO string - * @access public - */ - function deliverPDFfromFO($fo) - { - $ilLog = $this->log; - - $fo_file = ilUtil::ilTempnam() . ".fo"; - $fp = fopen($fo_file, "w"); fwrite($fp, $fo); fclose($fp); - - include_once './Services/WebServices/RPC/classes/class.ilRpcClientFactory.php'; - try - { - $pdf_base64 = ilRpcClientFactory::factory('RPCTransformationHandler')->ilFO2PDF($fo); - ilUtil::deliverData($pdf_base64->scalar, ilUtil::getASCIIFilename($this->getTitle()) . ".pdf", "application/pdf"); - return true; - } - catch(Exception $e) - { - $ilLog->write(__METHOD__.': '.$e->getMessage()); - return false; - } - } - - /** - * Checks whether or not a question plugin with a given name is active - * - * @param string $a_pname The plugin name - * @access public - */ - function isPluginActive($a_pname) - { - $ilPluginAdmin = $this->plugin_admin; - if ($ilPluginAdmin->isActive(IL_COMP_MODULE, "SurveyQuestionPool", "svyq", $a_pname)) - { - return TRUE; - } - else - { - return FALSE; - } - } - - /** - * Sets the survey id - * - * @param integer $survey_id The survey id - */ - public function setSurveyId($survey_id) - { - $this->survey_id = $survey_id; - } - - /** - * Returns a data of all users specified by id list - * - * @param $ids array of user id's - * @return array The user data "usr_id, login, lastname, firstname, clientip" of the users with id as key - */ - public function &getUserData($ids) - { - $ilDB = $this->db; - - if (!is_array($ids) || count($ids) ==0) return array(); - - $result = $ilDB->query("SELECT usr_id, login, lastname, firstname FROM usr_data WHERE " . $ilDB->in('usr_id', $ids, false, 'integer') . " ORDER BY login"); - $result_array = array(); - while ($row = $ilDB->fetchAssoc($result)) - { - $result_array[$row["usr_id"]]= $row; - } - return $result_array; - } - - function getMailNotification() - { - return $this->mailnotification; - } - - function setMailNotification($a_notification) - { - $this->mailnotification = ($a_notification) ? true : false; - } - - function getMailAddresses() - { - return $this->mailaddresses; - } - - function setMailAddresses($a_addresses) - { - $this->mailaddresses = $a_addresses; - } - - function getMailParticipantData() - { - return $this->mailparticipantdata; - } - - function setMailParticipantData($a_data) - { - $this->mailparticipantdata = $a_data; - } - - function setStartTime($finished_id, $first_question) - { - $ilDB = $this->db; - $time = time(); - //primary for table svy_times - $id = $ilDB->nextId('svy_times'); - $_SESSION['svy_entered_page'] = $time; - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_times (id, finished_fi, entered_page, left_page, first_question) VALUES (%s, %s, %s, %s,%s)", - array('integer','integer', 'integer', 'integer', 'integer'), - array($id, $finished_id, $time, NULL, $first_question) - ); - } - - function setEndTime($finished_id) - { - $ilDB = $this->db; - $time = time(); - $affectedRows = $ilDB->manipulateF("UPDATE svy_times SET left_page = %s WHERE finished_fi = %s AND entered_page = %s", - array('integer', 'integer', 'integer'), - array($time, $finished_id, $_SESSION['svy_entered_page']) - ); - unset($_SESSION['svy_entered_page']); - } - - function getWorkingtimeForParticipant($finished_id) - { - $ilDB = $this->db; - - $result = $ilDB->queryF("SELECT * FROM svy_times WHERE finished_fi = %s", - array('integer'), - array($finished_id) - ); - $total = 0; - while ($row = $ilDB->fetchAssoc($result)) - { - if ($row['left_page'] > 0 && $row['entered_page'] > 0) - $total += $row['left_page'] - $row['entered_page']; - } - return $total; - } - - function setTemplate($template_id) - { - $this->template_id = (int)$template_id; - } - - function getTemplate() - { - return $this->template_id; - } - - function updateOrder(array $a_order) - { - if(sizeof($this->questions) == sizeof($a_order)) - { - $this->questions = array_flip($a_order); - $this->saveQuestionsToDB(); - } - } - - function getPoolUsage() - { - return $this->pool_usage; - } - - function setPoolUsage($a_value) - { - $this->pool_usage = (bool)$a_value; - } - - /** - * Get current pool status - * - * @return bool - */ - function isPoolActive() - { - $use_pool = (bool)$this->getPoolUsage(); - $template_settings = $this->getTemplate(); - if($template_settings) - { - include_once "Services/Administration/classes/class.ilSettingsTemplate.php"; - $template_settings = new ilSettingsTemplate($template_settings); - $template_settings = $template_settings->getSettings(); - $template_settings = $template_settings["use_pool"]; - if($template_settings && $template_settings["hide"]) - { - $use_pool = (bool)$template_settings["value"]; - } - } - return $use_pool; - } - - /** - * Apply settings template - * - * @param int $template_id - */ - function applySettingsTemplate($template_id) - { - if(!$template_id) - { - return; - } - - include_once "Services/Administration/classes/class.ilSettingsTemplate.php"; - $template = new ilSettingsTemplate($template_id); - $template_settings = $template->getSettings(); - //ilUtil::dumpVar($template_settings); exit; - if($template_settings) - { - if($template_settings["show_question_titles"] !== NULL) - { - if($template_settings["show_question_titles"]["value"]) - { - $this->setShowQuestionTitles(true); - } - else - { - $this->setShowQuestionTitles(false); - } - } - - if($template_settings["use_pool"] !== NULL) - { - if($template_settings["use_pool"]["value"]) - { - $this->setPoolUsage(true); - } - else - { - $this->setPoolUsage(false); - } - } - - - /* see #0021719 - if($template_settings["anonymization_options"]["value"]) - { - $anon_map = array('personalized' => self::ANONYMIZE_OFF, - 'anonymize_with_code' => self::ANONYMIZE_ON, - 'anonymize_without_code' => self::ANONYMIZE_FREEACCESS); - $this->setAnonymize($anon_map[$template_settings["anonymization_options"]["value"]]); - }*/ - - // see #0021719 and ilObjectSurveyGUI::savePropertiesObject - $this->setEvaluationAccess($template_settings["evaluation_access"]["value"]); - $codes = (bool)$template_settings["acc_codes"]["value"]; - $anon = (bool)$template_settings["anonymization_options"]["value"]; - if (!$anon) - { - if (!$codes) - { - $this->setAnonymize(ilObjSurvey::ANONYMIZE_OFF); - } - else - { - $this->setAnonymize(ilObjSurvey::ANONYMIZE_CODE_ALL); - } - } - else - { - if ($codes) - { - $this->setAnonymize(ilObjSurvey::ANONYMIZE_ON); - } - else - { - $this->setAnonymize(ilObjSurvey::ANONYMIZE_FREEACCESS); - } - - $this->setAnonymousUserList($_POST["anon_list"]); - } - - - - /* other settings: not needed here - * - enabled_end_date - * - enabled_start_date - * - rte_switch - */ - } - - $this->setTemplate($template_id); - $this->saveToDb(); - } - - public function updateCode($a_id, $a_email, $a_last_name, $a_first_name, $a_sent) - { - $ilDB = $this->db; - - $a_email = trim($a_email); - - // :TODO: - if(($a_email && !ilUtil::is_email($a_email)) || $a_email == "") - { - return false; - } - - $data = array("email" => $a_email, - "lastname" => trim($a_last_name), - "firstname" => trim($a_first_name)); - - $fields = array( - "externaldata" => array("text", serialize($data)), - "sent" => array("integer", $a_sent) - ); - - $ilDB->update("svy_anonymous", $fields, - array("anonymous_id" => array("integer", $a_id))); - - return true; - } - - - // - // 360° - // - - public function get360Mode() - { - if($this->getMode() == ilObjSurvey::MODE_360){ - return true; - } - return false; - } - - public function set360SelfEvaluation($a_value) - { - $this->mode_360_self_eval = (bool)$a_value; - } - - public function get360SelfEvaluation() - { - return (bool)$this->mode_360_self_eval; - } - - public function set360SelfAppraisee($a_value) - { - $this->mode_360_self_appr = (bool)$a_value; - } - - public function get360SelfAppraisee() - { - return (bool)$this->mode_360_self_appr; - } - - public function set360SelfRaters($a_value) - { - $this->mode_360_self_rate = (bool)$a_value; - } - - public function get360SelfRaters() - { - return (bool)$this->mode_360_self_rate; - } - - public function set360Results($a_value) - { - $this->mode_360_results = (int)$a_value; - } - - public function get360Results() - { - return (int)$this->mode_360_results; - } - - public function addAppraisee($a_user_id) - { - global $DIC; - - $ilDB = $DIC->database(); - $access = $DIC->access(); - - if(!$this->isAppraisee($a_user_id) && - $a_user_id != ANONYMOUS_USER_ID) - { - $fields = array( - "obj_id" => array("integer", $this->getSurveyId()), - "user_id" => array("integer", $a_user_id) - ); - $ilDB->insert("svy_360_appr", $fields); - - // send notification and add to desktop - if ($access->checkAccessOfUser($a_user_id, "read", "", $this->getRefId())) - { - $this->sendAppraiseeNotification($a_user_id); - $type = ilObject::_lookupType($this->getRefId(), true); - ilObjUser::_addDesktopItem($a_user_id,$this->getRefId(),$type); - } - } - } - - /** - * Send appraisee notification - * - * @param int $a_user_id user id - */ - function sendAppraiseeNotification($a_user_id) - { - include_once "./Services/Notification/classes/class.ilSystemNotification.php"; - $ntf = new ilSystemNotification(); - $ntf->setLangModules(array("svy", "survey")); - $ntf->setRefId($this->getRefId()); - $ntf->setGotoLangId('url'); - - // user specific language - $lng = $ntf->getUserLanguage($a_user_id); - - $ntf->setIntroductionLangId("svy_user_added_360_appraisee_mail"); - $subject = str_replace("%1", $this->getTitle(), $lng->txt("svy_user_added_360_appraisee")); - - // #10044 - $mail = new ilMail(ANONYMOUS_USER_ID); - //$mail->enableSOAP(false); // #10410 - $mail->sendMail(ilObjUser::_lookupLogin($a_user_id), - null, - null, - $subject, - $ntf->composeAndGetMessage($a_user_id, null, "read", true), - null, - array("system")); - } - - /** - * Send appraisee notification - * - * @param int $a_user_id user id - */ - function sendAppraiseeCloseNotification($a_user_id) - { - include_once "./Services/Notification/classes/class.ilSystemNotification.php"; - $ntf = new ilSystemNotification(); - $ntf->setLangModules(array("svy", "survey")); - $ntf->setRefId($this->getRefId()); - $ntf->setGotoLangId('url'); - - // user specific language - $lng = $ntf->getUserLanguage($a_user_id); - - $ntf->setIntroductionLangId("svy_user_added_360_appraisee_close_mail"); - $subject = str_replace("%1", $this->getTitle(), $lng->txt("svy_user_added_360_appraisee")); - - // #10044 - $mail = new ilMail(ANONYMOUS_USER_ID); - //$mail->enableSOAP(false); // #10410 - $mail->sendMail(ilObjUser::_lookupLogin($a_user_id), - null, - null, - $subject, - $ntf->composeAndGetMessage($a_user_id, null, "read", true), - null, - array("system")); - } - - /** - * Send rater notification - * - * @param int $a_user_id user id - */ - function sendRaterNotification($a_user_id, $a_appraisee_id) - { - include_once "./Services/Notification/classes/class.ilSystemNotification.php"; - $ntf = new ilSystemNotification(); - $ntf->setLangModules(array("svy", "survey")); - $ntf->setRefId($this->getRefId()); - $ntf->setGotoLangId('url'); - - // user specific language - $lng = $ntf->getUserLanguage($a_user_id); - - $ntf->setIntroductionLangId("svy_user_added_360_rater_mail"); - $subject = str_replace("%1", $this->getTitle(), $lng->txt("svy_user_added_360_rater")); - $ntf->addAdditionalInfo("survey_360_appraisee", ilUserUtil::getNamePresentation($a_appraisee_id,false, false, "", true)); - - // #10044 - $mail = new ilMail(ANONYMOUS_USER_ID); - //$mail->enableSOAP(false); // #10410 - $mail->sendMail(ilObjUser::_lookupLogin($a_user_id), - null, - null, - $subject, - $ntf->composeAndGetMessage($a_user_id, null, "read", true), - null, - array("system")); - } - - public function isAppraisee($a_user_id) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT user_id". - " FROM svy_360_appr". - " WHERE obj_id = ".$ilDB->quote($this->getSurveyId(), "integer"). - " AND user_id = ".$ilDB->quote($a_user_id, "integer")); - return (bool)$ilDB->numRows($set); - } - - public function isAppraiseeClosed($a_user_id) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT has_closed". - " FROM svy_360_appr". - " WHERE obj_id = ".$ilDB->quote($this->getSurveyId(), "integer"). - " AND user_id = ".$ilDB->quote($a_user_id, "integer")); - $row = $ilDB->fetchAssoc($set); - return $row["has_closed"]; - } - - public function deleteAppraisee($a_user_id) - { - $ilDB = $this->db; - - $ilDB->manipulate("DELETE FROM svy_360_appr". - " WHERE obj_id = ".$ilDB->quote($this->getSurveyId(), "integer"). - " AND user_id = ".$ilDB->quote($a_user_id, "integer")); - - $set = $ilDB->query("SELECT user_id". - " FROM svy_360_rater". - " WHERE obj_id = ".$ilDB->quote($this->getSurveyId(), "integer"). - " AND appr_id = ".$ilDB->quote($a_user_id, "integer")); - while($row = $ilDB->fetchAssoc($set)) - { - $this->deleteRater($a_user_id, $row["user_id"]); - } - // appraisee will not be part of raters table - if($this->get360SelfEvaluation()) - { - $this->deleteRater($a_user_id, $a_user_id); - } - } - - public function getAppraiseesData() - { - $ilDB = $this->db; - - $res = array(); - - $set = $ilDB->query("SELECT * FROM svy_360_appr". - " WHERE obj_id = ".$ilDB->quote($this->getSurveyId(), "integer")); - while($row = $ilDB->fetchAssoc($set)) - { - $name = ilObjUser::_lookupName($row["user_id"]); - $name["email"] = ilObjUser::_lookupEmail($row["user_id"]); - $name["name"] = $name["lastname"].", ".$name["firstname"]; - $res[$row["user_id"]] = $name; - - $finished = 0; - $raters = $this->getRatersData($row["user_id"]); - foreach($raters as $rater) - { - if($rater["finished"]) - { - $finished++; - } - } - $res[$row["user_id"]]["finished"] = $finished."/".sizeof($raters); - $res[$row["user_id"]]["closed"] = $row["has_closed"]; - } - - return $res; - } - - public function addRater($a_appraisee_id, $a_user_id, $a_anonymous_id = 0) - { - global $DIC; - - $ilDB = $DIC->database(); - $access = $DIC->access(); - - if($this->isAppraisee($a_appraisee_id) && - !$this->isRater($a_appraisee_id, $a_user_id, $a_anonymous_id)) - { - $fields = array( - "obj_id" => array("integer", $this->getSurveyId()), - "appr_id" => array("integer", $a_appraisee_id), - "user_id" => array("integer", $a_user_id), - "anonymous_id" => array("integer", $a_anonymous_id) - ); - $ilDB->insert("svy_360_rater", $fields); - - // send notification and add to desktop - if ($access->checkAccessOfUser($a_user_id, "read", "", $this->getRefId())) - { - $this->sendRaterNotification($a_user_id, $a_appraisee_id); - $type = ilObject::_lookupType($this->getRefId(), true); - ilObjUser::_addDesktopItem($a_user_id,$this->getRefId(),$type); - } - - } - } - - public function isRater($a_appraisee_id, $a_user_id, $a_anonymous_id = 0) - { - $ilDB = $this->db; - - // user is rater if already appraisee and active self-evaluation - if($this->isAppraisee($a_user_id) && - $this->get360SelfEvaluation() && - (!$a_appraisee_id || $a_appraisee_id == $a_user_id)) - { - return true; - } - - // :TODO: should we get rid of code as well? - - $sql = "SELECT user_id". - " FROM svy_360_rater". - " WHERE obj_id = ".$ilDB->quote($this->getSurveyId(), "integer"). - " AND user_id = ".$ilDB->quote($a_user_id, "integer"). - " AND anonymous_id = ".$ilDB->quote($a_anonymous_id, "integer"); - if($a_appraisee_id) - { - $sql .= " AND appr_id = ".$ilDB->quote($a_appraisee_id, "integer"); - } - $set = $ilDB->query($sql); - return (bool)$ilDB->numRows($set); - } - - public function deleteRater($a_appraisee_id, $a_user_id, $a_anonymous_id = 0) - { - $ilDB = $this->db; - - $finished_id = $this->getFinishedIdForAppraiseeIdAndRaterId($a_appraisee_id, $a_user_id); - if($finished_id) - { - $this->removeSelectedSurveyResults(array($finished_id)); - } - - $ilDB->manipulate("DELETE FROM svy_360_rater". - " WHERE obj_id = ".$ilDB->quote($this->getSurveyId(), "integer"). - " AND appr_id = ".$ilDB->quote($a_appraisee_id, "integer"). - " AND user_id = ".$ilDB->quote($a_user_id, "integer"). - " AND anonymous_id = ".$ilDB->quote($a_anonymous_id, "integer")); - } - - public function getRatersData($a_appraisee_id) - { - $ilDB = $this->db; - - $res = $anonymous_ids = array(); - - $set = $ilDB->query("SELECT * FROM svy_360_rater". - " WHERE obj_id = ".$ilDB->quote($this->getSurveyId(), "integer"). - " AND appr_id = ".$ilDB->quote($a_appraisee_id, "integer")); - while($row = $ilDB->fetchAssoc($set)) - { - if($row["anonymous_id"]) - { - $res["a".$row["anonymous_id"]] = array( - "lastname" => "unknown code ".$row["anonymous_id"], - "sent" => $row["mail_sent"], - "finished" => null - ); - $anonymous_ids[] = $row["anonymous_id"]; - } - else - { - $name = ilObjUser::_lookupName($row["user_id"]); - $name["name"] = $name["lastname"].", ".$name["firstname"]; - $name["user_id"] = "u".$name["user_id"]; - $name["email"] = ilObjUser::_lookupEmail($row["user_id"]); - $name["sent"] = $row["mail_sent"]; - $name["finished"] = (bool)$this->is360SurveyStarted($a_appraisee_id, $row["user_id"]); - $res["u".$row["user_id"]] = $name; - } - } - - if(sizeof($anonymous_ids)) - { - $data = $this->getSurveyCodesTableData($anonymous_ids); - foreach($data as $item) - { - if(isset($res["a".$item["id"]])) - { - $res["a".$item["id"]] = array( - "user_id" => "a".$item["id"], - "lastname" => $item["last_name"], - "firstname" => $item["first_name"], - "name" => $item["last_name"].", ".$item["first_name"], - "login" => "", - "email" => $item["email"], - "code" => $item["code"], - "href" => $item["href"], - "sent" => $res["a".$item["id"]]["sent"], - "finished" => (bool)$this->is360SurveyStarted($a_appraisee_id, null, $item["code"]) - ); - } - } - } - - return $res; - } - - public function getAppraiseesToRate($a_user_id, $a_anonymous_id = null) - { - $ilDB = $this->db; - - $res = array(); - - $sql = "SELECT appr_id FROM svy_360_rater". - " WHERE obj_id = ".$ilDB->quote($this->getSurveyId(), "integer"); - - if($a_user_id) - { - $sql .= " AND user_id = ".$ilDB->quote($a_user_id, "integer"); - } - else - { - $sql .= " AND anonymous_id = ".$ilDB->quote($a_anonymous_id, "integer"); - } - - $set = $ilDB->query($sql); - while($row = $ilDB->fetchAssoc($set)) - { - $res[] = $row["appr_id"]; - } - - // user may evaluate himself if already appraisee - if($this->get360SelfEvaluation() && - $this->isAppraisee($a_user_id) && - !in_array($a_user_id, $res)) - { - $res[] = $a_user_id; - } - - return $res; - } - - public function getAnonymousIdByCode($a_code) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT anonymous_id FROM svy_anonymous". - " WHERE survey_fi = ".$ilDB->quote($this->getSurveyId(), "integer"). - " AND survey_key = ".$ilDB->quote($a_code, "text")); - $res = $ilDB->fetchAssoc($set); - return $res["anonymous_id"]; - } - - function is360SurveyStarted($appr_id, $user_id, $anonymous_code = null) - { - $ilDB = $this->db; - - $sql = "SELECT * FROM svy_finished". - " WHERE survey_fi =".$ilDB->quote($this->getSurveyId(), "integer"). - " AND appr_id = ".$ilDB->quote($appr_id, "integer"); - if ($user_id) - { - $sql .= " AND user_fi = ".$ilDB->quote($user_id, "integer"); - } - else - { - $sql .= " AND anonymous_id = ".$ilDB->quote($anonymous_code, "text"); - } - $result = $ilDB->query($sql); - if ($result->numRows() == 0) - { - return false; - } - else - { - $row = $ilDB->fetchAssoc($result); - return (int)$row["state"]; - } - } - - function getUserSurveyExecutionStatus($a_code = null) - { - $ilUser = $this->user; - $ilDB = $this->db; - - $user_id = $ilUser->getId(); - - // code is obligatory? - if(!$this->isAccessibleWithoutCode()) - { - if(!$a_code) - { - // registered raters do not need code - if($this->get360Mode() && - $user_id != ANONYMOUS_USER_ID && - $this->isRater(0, $user_id)) - { - // auto-generate code - $a_code = $this->createNewAccessCode(); - $this->saveUserAccessCode($user_id, $a_code); - } - else - { - return null; - } - } - } - else if($user_id == ANONYMOUS_USER_ID || - $this->getAnonymize() == self::ANONYMIZE_FREEACCESS) - { - if(!$a_code) - { - // auto-generate code - $a_code = $this->createNewAccessCode(); - $this->saveUserAccessCode($user_id, $a_code); - } - } - else - { - $a_code = null; - } - - $res = array(); - - $sql = "SELECT * FROM svy_finished". - " WHERE survey_fi = ".$ilDB->quote($this->getSurveyId(), "integer"); - // if proper user id is given, use it or current code - if($user_id != ANONYMOUS_USER_ID) - { - $sql .= " AND (user_fi = ".$ilDB->quote($user_id, "integer"). - " OR anonymous_id = ".$ilDB->quote($a_code, "text").")"; - } - // use anonymous code to find finished id(s) - else - { - $sql .= " AND anonymous_id = ".$ilDB->quote($a_code, "text"); - } - $set = $ilDB->query($sql); - while($row = $ilDB->fetchAssoc($set)) - { - $res[$row["finished_id"]] = array("appr_id" => $row["appr_id"], - "user_id" => $row["user_fi"], - "code" => $row["anonymous_id"], - "finished" => (bool)$row["state"]); - } - - return array("code"=>$a_code, "runs"=>$res); - } - - function findCodeForUser($a_user_id) - { - $ilDB = $this->db; - - if($a_user_id != ANONYMOUS_USER_ID) - { - $set = $ilDB->query("SELECT sf.anonymous_id FROM svy_finished sf". - " WHERE sf.survey_fi = ".$ilDB->quote($this->getSurveyId(), "integer"). - " AND sf.user_fi = ".$ilDB->quote($a_user_id, "integer")); - $a_code = $ilDB->fetchAssoc($set); - return $a_code["anonymous_id"]; - } - } - - function isUnusedCode($a_code, $a_user_id) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT user_fi FROM svy_finished". - " WHERE survey_fi = ".$ilDB->quote($this->getSurveyId(), "integer"). - " AND anonymous_id = ".$ilDB->quote($a_code, "text")); - $user_id = $ilDB->fetchAssoc($set); - $user_id = $user_id["user_fi"]; - - if($user_id && ($user_id != $a_user_id || $user_id == ANONYMOUS_USER_ID)) - { - return false; - } - return true; - } - - function getFinishedIdsForAppraiseeId($a_appr_id, $a_exclude_appraisee = false) - { - $ilDB = $this->db; - - $res = array(); - - $set = $ilDB->query("SELECT finished_id, user_fi FROM svy_finished". - " WHERE survey_fi = ".$ilDB->quote($this->getSurveyId(), "integer"). - " AND appr_id = ".$ilDB->quote($a_appr_id, "integer")); - while($row = $ilDB->fetchAssoc($set)) - { - if ($a_exclude_appraisee && $row["user_fi"] == $a_appr_id) - { - continue; - } - $res[] = $row["finished_id"]; - } - - return $res; - } - - /** - * Get finished id for an appraisee and a rater - * - * @param int $a_appraisee_id appraisee id - * @param int $a_rater_id rater id - * @return int finished id - */ - function getFinishedIdForAppraiseeIdAndRaterId($a_appr_id, $a_rat_id) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT finished_id, user_fi FROM svy_finished". - " WHERE survey_fi = ".$ilDB->quote($this->getSurveyId(), "integer"). - " AND appr_id = ".$ilDB->quote($a_appr_id, "integer"). - " AND user_fi = ".$ilDB->quote($a_rat_id, "integer")); - $row = $ilDB->fetchAssoc($set); - return $row["finished_id"]; - } - - - // 360° using competence/skill service - - /** - * Set skill service - * - * @param bool $a_val activate skill service - */ - function setSkillService($a_val) - { - $this->mode_skill_service = $a_val; - } - - /** - * Get skill service - * - * @return bool activate skill service - */ - function getSkillService() - { - return $this->mode_skill_service; - } - - function set360RaterSent($a_appraisee_id, $a_user_id, $a_anonymous_id, $a_tstamp = null) - { - $ilDB = $this->db; - - if(!$a_tstamp) - { - $a_tstamp = time(); - } - - $ilDB->manipulate("UPDATE svy_360_rater". - " SET mail_sent = ".$ilDB->quote($a_tstamp, "integer"). - " WHERE obj_id = ".$ilDB->quote($this->getSurveyId(), "integer"). - " AND appr_id = ".$ilDB->quote($a_appraisee_id, "integer"). - " AND user_id = ".$ilDB->quote($a_user_id, "integer"). - " AND anonymous_id = ".$ilDB->quote($a_anonymous_id, "integer")); - } - - function closeAppraisee($a_user_id) - { - global $DIC; - - $ilDB = $DIC->database(); - $user = $DIC->user(); - - // close the appraisee - $ilDB->manipulate("UPDATE svy_360_appr". - " SET has_closed = ".$ilDB->quote(time(), "integer"). - " WHERE obj_id = ".$ilDB->quote($this->getSurveyId(), "integer"). - " AND user_id = ".$ilDB->quote($a_user_id, "integer")); - - // write competences - include_once("./Services/Skill/classes/class.ilSkillManagementSettings.php"); - $skmg_set = new ilSkillManagementSettings(); - if ($this->getSkillService() && $skmg_set->isActivated()) - { - include_once("./Modules/Survey/classes/class.ilSurveySkill.php"); - $sskill = new ilSurveySkill($this); - $sskill->writeAppraiseeSkills($a_user_id); - } - - // send notification - if ($user->getId() != $a_user_id) - { - $this->sendAppraiseeCloseNotification($a_user_id); - } - } - - function openAllAppraisees() - { - $ilDB = $this->db; - - $ilDB->manipulate("UPDATE svy_360_appr". - " SET has_closed = ".$ilDB->quote(null, "integer"). - " WHERE obj_id = ".$ilDB->quote($this->getSurveyId(), "integer")); - } - - public static function validateExternalRaterCode($a_ref_id, $a_code) - { - if(!isset($_SESSION["360_extrtr"][$a_ref_id])) - { - $svy = new self($a_ref_id); - $svy->loadFromDB(); - - if($svy->canStartSurvey(null, true) && - $svy->get360Mode() && - $svy->isAnonymousKey($a_code)) - { - $anonymous_id = $svy->getAnonymousIdByCode($a_code); - if($anonymous_id) - { - if(sizeof($svy->getAppraiseesToRate(null, $anonymous_id))) - { - $_SESSION["360_extrtr"][$a_ref_id] = true; - return true; - } - } - } - - $_SESSION["360_extrtr"][$a_ref_id] = false; - return false; - } - - return $_SESSION["360_extrtr"][$a_ref_id]; - } - - - // - // reminder/notification - // - - public function getReminderStatus() - { - return (bool)$this->reminder_status; - } - - public function setReminderStatus($a_value) - { - $this->reminder_status = (bool)$a_value; - } - - public function getReminderStart() - { - return $this->reminder_start; - } - - public function setReminderStart(ilDate $a_value = null) - { - $this->reminder_start = $a_value; - } - - public function getReminderEnd() - { - return $this->reminder_end; - } - - public function setReminderEnd(ilDate $a_value = null) - { - $this->reminder_end = $a_value; - } - - public function getReminderFrequency() - { - return $this->reminder_frequency; - } - - public function setReminderFrequency($a_value) - { - $this->reminder_frequency = (int)$a_value; - } - - public function getReminderTarget() - { - return $this->reminder_target; - } - - public function setReminderTarget($a_value) - { - $this->reminder_target = (int)$a_value; - } - - public function getReminderLastSent() - { - return $this->reminder_last_sent; - } - - public function setReminderLastSent($a_value) - { - $this->reminder_last_sent = $a_value; - } - - /** - * @param bool $selectDefault - * @return mixed - */ - public function getReminderTemplate($selectDefault = false) - { - if ($selectDefault) { - $defaultTemplateId = 0; - $this->getReminderMailTemplates($defaultTemplateId); - - if ($defaultTemplateId > 0) { - return $defaultTemplateId; - } - } - - return $this->reminder_tmpl; - } - - public function setReminderTemplate($a_value) - { - $this->reminder_tmpl = $a_value; - } - - public function getTutorNotificationStatus() - { - return (bool)$this->tutor_ntf_status; - } - - public function setTutorNotificationStatus($a_value) - { - $this->tutor_ntf_status = (bool)$a_value; - } - - public function getTutorNotificationRecipients() - { - return $this->tutor_ntf_recipients; - } - - public function setTutorNotificationRecipients(array $a_value) - { - $this->tutor_ntf_recipients = $a_value; - } - - public function getTutorNotificationTarget() - { - return $this->tutor_ntf_target; - } - - public function setTutorNotificationTarget($a_value) - { - $this->tutor_ntf_target = (int)$a_value; - } - - protected function checkTutorNotification() - { - $ilDB = $this->db; - - if($this->getTutorNotificationStatus()) - { - $user_ids = $this->getNotificationTargetUserIds(($this->getTutorNotificationTarget() == self::NOTIFICATION_INVITED_USERS)); - if($user_ids) - { - $set = $ilDB->query("SELECT COUNT(*) numall FROM svy_finished". - " WHERE survey_fi = ".$ilDB->quote($this->getSurveyId(), "integer"). - " AND state = ".$ilDB->quote(1, "integer"). - " AND ".$ilDB->in("user_fi", $user_ids, "", "integer")); - $row = $ilDB->fetchAssoc($set); - if($row["numall"] == sizeof($user_ids)) - { - $this->sendTutorNotification(); - } - } - } - } - - /** - * Send 360 reminders - * - * @param - * @return - */ - function sent360Reminders() - { - global $DIC; - - $access = $DIC->access(); - - // collect all open ratings - $rater_ids = array(); - foreach ($this->getAppraiseesData() as $app) - { - $this->log->debug("Handle appraisee ".$app['user_id']); - - if (!$this->isAppraiseeClosed($app['user_id'])) - { - $this->log->debug("Check self evaluation, self: ".$this->get360SelfAppraisee().", target: ".$this->getReminderTarget()); - - // self evaluation? - if ($this->get360SelfEvaluation() && - in_array($this->getReminderTarget(), array(ilObjSurvey::NOTIFICATION_APPRAISEES, ilObjSurvey::NOTIFICATION_APPRAISEES_AND_RATERS))) - { - $this->log->debug("...1"); - // did user already finished self evaluation? - if (!$this->is360SurveyStarted($app['user_id'], $app['user_id'])) - { - $this->log->debug("...2"); - if (!is_array($rater_ids[$app['user_id']])) - { - $rater_ids[$app['user_id']] = array(); - } - if (!in_array($app["user_id"], $rater_ids[$app['user_id']])) - { - $rater_ids[$app['user_id']][] = $app["user_id"]; - } - } - } - - $this->log->debug("Check raters."); - - // should raters be notified? - if (in_array($this->getReminderTarget(), array(ilObjSurvey::NOTIFICATION_RATERS, ilObjSurvey::NOTIFICATION_APPRAISEES_AND_RATERS))) - { - foreach ($this->getRatersData($app['user_id']) as $rater) - { - // is rater not anonymous and did not rate yet? - if (!$rater["anonymous_id"] && !$rater["finished"]) - { - if (!is_array($rater_ids[$rater["user_id"]])) - { - $rater_ids[$rater["user_id"]] = array(); - } - if (!in_array($app["user_id"], $rater_ids[$rater["user_id"]])) - { - $rater_ids[$rater["user_id"]][] = $app["user_id"]; - } - } - } - } - } - } - - $this->log->debug("Found raters:".count($rater_ids)); - - foreach ($rater_ids as $id => $app) - { - if ($access->checkAccessOfUser($id, "read", "", $this->getRefId())) - { - $this->send360ReminderToUser($id, $app); - } - } - } - - /** - * Send rater notification - * - * @param int $a_user_id user id - */ - function send360ReminderToUser($a_user_id, $a_appraisee_ids) - { - $this->log->debug("Send mail to:".$a_user_id); - - include_once "./Services/Notification/classes/class.ilSystemNotification.php"; - $ntf = new ilSystemNotification(); - $ntf->setLangModules(array("svy", "survey")); - $ntf->setRefId($this->getRefId()); - $ntf->setGotoLangId('url'); - - // user specific language - $lng = $ntf->getUserLanguage($a_user_id); - - $ntf->setIntroductionLangId("svy_user_added_360_rater_reminder_mail"); - $subject = str_replace("%1", $this->getTitle(), $lng->txt("svy_user_added_360_rater")); - - foreach ($a_appraisee_ids as $appraisee_id) - { - $ntf->addAdditionalInfo("survey_360_appraisee", ilUserUtil::getNamePresentation($appraisee_id, false, false, "", true)); - } - - // #10044 - $mail = new ilMail(ANONYMOUS_USER_ID); - $mail->enableSOAP(false); // #10410 - $mail->sendMail(ilObjUser::_lookupLogin($a_user_id), - null, - null, - $subject, - $ntf->composeAndGetMessage($a_user_id, null, "read", true), - null, - array("system")); - } - - - public function getNotificationTargetUserIds($a_use_invited) - { - $tree = $this->tree; - - if ((bool)$a_use_invited) - { - $user_ids = $this->getInvitedUsers(); - } else - { - $parent_grp_ref_id = $tree->checkForParentType($this->getRefId(), "grp"); - if ($parent_grp_ref_id) - { - include_once "Modules/Group/classes/class.ilGroupParticipants.php"; - $part = new ilGroupParticipants(ilObject::_lookupObjId($parent_grp_ref_id)); - $user_ids = $part->getMembers(); - } else - { - $parent_crs_ref_id = $tree->checkForParentType($this->getRefId(), "crs"); - if ($parent_crs_ref_id) - { - include_once "Modules/Course/classes/class.ilCourseParticipants.php"; - $part = new ilCourseParticipants(ilObject::_lookupObjId($parent_crs_ref_id)); - $user_ids = $part->getMembers(); - } - } - } - return $user_ids; - } - - protected function sendTutorNotification() - { - include_once "./Services/Mail/classes/class.ilMail.php"; - include_once "./Services/User/classes/class.ilObjUser.php"; - include_once "./Services/Language/classes/class.ilLanguageFactory.php"; - include_once "./Services/User/classes/class.ilUserUtil.php"; - include_once "./Services/Link/classes/class.ilLink.php"; - $link = ilLink::_getStaticLink($this->getRefId(), "svy"); - - foreach($this->getTutorNotificationRecipients() as $user_id) - { - // use language of recipient to compose message - $ulng = ilLanguageFactory::_getLanguageOfUser($user_id); - $ulng->loadLanguageModule('survey'); - - $subject = sprintf($ulng->txt('survey_notification_tutor_subject'), $this->getTitle()); - $message = sprintf($ulng->txt('survey_notification_tutor_salutation'), ilObjUser::_lookupFullname($user_id))."\n\n"; - - $message .= $ulng->txt('survey_notification_tutor_body').":\n\n"; - $message .= $ulng->txt('obj_svy').": ". $this->getTitle()."\n"; - $message .= "\n".$ulng->txt('survey_notification_tutor_link').": ".$link; - - $mail_obj = new ilMail(ANONYMOUS_USER_ID); - $mail_obj->appendInstallationSignature(true); - $mail_obj->sendMail(ilObjUser::_lookupLogin($user_id), - "", "", $subject, $message, array(), array("system")); - } - } - - public function checkReminder() - { - $ilDB = $this->db; - $ilAccess = $this->access; - - $now = time(); - $now_with_format = date("YmdHis", $now); - $today = date("Y-m-d"); - - $this->log->debug("Check status and dates."); - - // object settings / participation period - if( - $this->getOfflineStatus() || - !$this->getReminderStatus() || - ($this->getStartDate() && $now_with_format < $this->getStartDate()) || - ($this->getEndDate() && $now_with_format > $this->getEndDate())) - { - return false; - } - - // reminder period - $start = $this->getReminderStart(); - if($start) - { - $start = $start->get(IL_CAL_DATE); - } - $end = $this->getReminderEnd(); - if($end) - { - $end = $end->get(IL_CAL_DATE); - } - if($today < $start || - ($end && $today > $end)) - { - return false; - } - - $this->log->debug("Check access period."); - - // object access period - include_once "Services/Object/classes/class.ilObjectActivation.php"; - $item_data = ilObjectActivation::getItem($this->getRefId()); - if($item_data["timing_type"] == ilObjectActivation::TIMINGS_ACTIVATION && - ($now < $item_data["timing_start"] || - $now > $item_data["timing_end"])) - { - return false; - } - - $this->log->debug("Check frequency."); - - // check frequency - $cut = new ilDate($today, IL_CAL_DATE); - $cut->increment(IL_CAL_DAY, $this->getReminderFrequency()*-1); - if(!$this->getReminderLastSent() || - $cut->get(IL_CAL_DATE) >= substr($this->getReminderLastSent(), 0, 10)) - { - $missing_ids = array(); - - if (!$this->get360Mode()) - { - $this->log->debug("Entering survey mode."); - - // #16871 - $user_ids = $this->getNotificationTargetUserIds(($this->getReminderTarget() == self::NOTIFICATION_INVITED_USERS)); - if ($user_ids) - { - // gather participants who already finished - $finished_ids = array(); - $set = $ilDB->query("SELECT user_fi FROM svy_finished" . - " WHERE survey_fi = " . $ilDB->quote($this->getSurveyId(), "integer") . - " AND state = " . $ilDB->quote(1, "text") . - " AND " . $ilDB->in("user_fi", $user_ids, "", "integer")); - while ($row = $ilDB->fetchAssoc($set)) - { - $finished_ids[] = $row["user_fi"]; - } - - // some users missing out? - $missing_ids = array_diff($user_ids, $finished_ids); - if ($missing_ids) - { - foreach ($missing_ids as $idx => $user_id) - { - // should be able to participate - if (!$ilAccess->checkAccessOfUser($user_id, "read", "", $this->getRefId(), "svy", $this->getId())) - { - unset($missing_ids[$idx]); - } - } - } - if ($missing_ids) - { - $this->sentReminder($missing_ids); - } - } - } - else - { - $this->log->debug("Entering 360 mode."); - - $this->sent360Reminders(); - } - - - $this->setReminderLastSent($today); - $this->saveToDb(); - - return sizeof($missing_ids); - } - - return false; - } - - protected function sentReminder(array $a_recipient_ids) - { - global $DIC; - - // use mail template - if($this->getReminderTemplate() && - array_key_exists($this->getReminderTemplate(), $this->getReminderMailTemplates())) - { - /** @var \ilMailTemplateService $templateService */ - $templateService = $DIC['mail.texttemplates.service']; - $tmpl = $templateService->loadTemplateForId((int)$this->getReminderTemplate()); - - $tmpl_params = array( - "ref_id" => $this->getRefId(), - "ts" => time() - ); - } - else - { - $tmpl = null; - - include_once "./Services/Link/classes/class.ilLink.php"; - $link = ilLink::_getStaticLink($this->getRefId(), "svy"); - - include_once "./Services/Language/classes/class.ilLanguageFactory.php"; - } - - foreach($a_recipient_ids as $user_id) - { - if($tmpl) - { - $subject = $tmpl->getSubject(); - $message = $this->sentReminderPlaceholders($tmpl->getMessage(), $user_id, $tmpl_params); - } - // use lng - else - { - // use language of recipient to compose message - $ulng = ilLanguageFactory::_getLanguageOfUser($user_id); - $ulng->loadLanguageModule('survey'); - - $subject = sprintf($ulng->txt('survey_reminder_subject'), $this->getTitle()); - $message = sprintf($ulng->txt('survey_reminder_salutation'), ilObjUser::_lookupFullname($user_id))."\n\n"; - - $message .= $ulng->txt('survey_reminder_body').":\n\n"; - $message .= $ulng->txt('obj_svy').": ". $this->getTitle()."\n"; - $message .= "\n".$ulng->txt('survey_reminder_link').": ".$link; - } - - $mail_obj = new ilMail(ANONYMOUS_USER_ID); - $mail_obj->appendInstallationSignature(true); - $mail_obj->sendMail(ilObjUser::_lookupLogin($user_id), - "", "", $subject, $message, array(), array("system")); - } - } - - function setActivationStartDate($starting_time = NULL) - { - $this->activation_starting_time = $starting_time; - } - - function setActivationEndDate($ending_time = NULL) - { - $this->activation_ending_time = $ending_time; - } - - function getActivationStartDate() - { - return (strlen($this->activation_starting_time)) ? $this->activation_starting_time : NULL; - } - - function getActivationEndDate() - { - return (strlen($this->activation_ending_time)) ? $this->activation_ending_time : NULL; - } - - function setViewOwnResults($a_value) - { - $this->view_own_results = (bool)$a_value; - } - - function hasViewOwnResults() - { - return $this->view_own_results; - } - - function setMailOwnResults($a_value) - { - $this->mail_own_results = (bool)$a_value; - } - - function hasMailOwnResults() - { - return $this->mail_own_results; - } - - function setMailConfirmation($a_value) - { - $this->mail_confirmation = (bool)$a_value; - } - - function hasMailConfirmation() - { - return $this->mail_confirmation; - } - - function setAnonymousUserList($a_value) - { - $this->anon_user_list = (bool)$a_value; - } - - function hasAnonymousUserList() - { - return $this->anon_user_list; - } - - public static function getSurveySkippedValue() - { - global $DIC; - - $lng = $DIC->language(); - - // #13541 - - include_once "./Services/Administration/classes/class.ilSetting.php"; - $surveySetting = new ilSetting("survey"); - if(!$surveySetting->get("skipped_is_custom", false)) - { - return $lng->txt("skipped"); - } - else - { - return $surveySetting->get("skipped_custom_value", ""); - } - } - - /** - * @param int $defaultTemplateId - * @return array - */ - public function getReminderMailTemplates(&$defaultTemplateId = null) - { - global $DIC; - - $res = array(); - - /** @var \ilMailTemplateService $templateService */ - $templateService = $DIC['mail.texttemplates.service']; - foreach ($templateService->loadTemplatesForContextId((string)ilSurveyMailTemplateReminderContext::ID) as $tmpl) { - $res[$tmpl->getTplId()] = $tmpl->getTitle(); - if (null !== $defaultTemplateId && $tmpl->isDefault()) { - $defaultTemplateId = $tmpl->getTplId(); - } - } - - return $res; - } - - protected function sentReminderPlaceholders($a_message, $a_user_id, array $a_context_params) - { - // see ilMail::replacePlaceholders() - try { - $context = \ilMailTemplateContextService::getTemplateContextById(ilSurveyMailTemplateReminderContext::ID); - - $user = new \ilObjUser($a_user_id); - - $processor = new \ilMailTemplatePlaceholderResolver($context, $a_message); - $a_message = $processor->resolve($user, \ilMailFormCall::getContextParameters()); - } catch (\Exception $e) { - ilLoggerFactory::getLogger('mail')->error(__METHOD__ . ' has been called with invalid context.'); - } - - return $a_message; - } - - public function setMode($a_value) - { - $this->mode = $a_value; - } - - public function getMode() - { - return $this->mode; - } - - public function setSelfEvaluationResults($a_value) - { - $this->mode_self_eval_results = $a_value; - } - - public function getSelfEvaluationResults() - { - return $this->mode_self_eval_results; - } - + $query_result = $ilDB->query("SELECT svy_qblk.*, svy_svy.obj_fi FROM svy_qblk , svy_qblk_qst, svy_svy WHERE " . + "svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi AND svy_svy.survey_id = svy_qblk_qst.survey_fi " . + "$where GROUP BY svy_qblk.questionblock_id, svy_qblk.title, svy_qblk.show_questiontext, svy_qblk.show_blocktitle, " . + "svy_qblk.owner_fi, svy_qblk.tstamp, svy_svy.obj_fi"); + $rows = array(); + if ($query_result->numRows()) { + $survey_ref_ids = ilUtil::_getObjectsByOperations("svy", "write"); + $surveytitles = array(); + foreach ($survey_ref_ids as $survey_ref_id) { + $survey_id = ilObject::_lookupObjId($survey_ref_id); + $surveytitles[$survey_id] = ilObject::_lookupTitle($survey_id); + } + while ($row = $ilDB->fetchAssoc($query_result)) { + $questions_array =&$this->getQuestionblockQuestions($row["questionblock_id"]); + $counter = 1; + foreach ($questions_array as $key => $value) { + $questions_array[$key] = "$counter. $value"; + $counter++; + } + if (strlen($surveytitles[$row["obj_fi"]])) { // only questionpools which are not in trash + $rows[$row["questionblock_id"]] = array( + "questionblock_id" => $row["questionblock_id"], + "title" => $row["title"], + "svy" => $surveytitles[$row["obj_fi"]], + "contains" => join($questions_array, ", "), + "owner" => $row["owner_fi"] + ); + } + } + } + return $rows; + } + + /** + * Returns a QTI xml representation of the survey + * + * @return string The QTI xml representation of the survey + * @access public + */ + public function toXML() + { + include_once("./Services/Xml/classes/class.ilXmlWriter.php"); + $a_xml_writer = new ilXmlWriter; + // set xml header + $a_xml_writer->xmlHeader(); + $attrs = array( + "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance", + "xsi:noNamespaceSchemaLocation" => "http://www.ilias.de/download/xsd/ilias_survey_4_2.xsd" + ); + $a_xml_writer->xmlStartTag("surveyobject", $attrs); + $attrs = array( + "id" => $this->getSurveyId(), + "title" => $this->getTitle() + ); + $a_xml_writer->xmlStartTag("survey", $attrs); + + $a_xml_writer->xmlElement("description", null, $this->getDescription()); + $a_xml_writer->xmlElement("author", null, $this->getAuthor()); + $a_xml_writer->xmlStartTag("objectives"); + $attrs = array( + "label" => "introduction" + ); + $this->addMaterialTag($a_xml_writer, $this->getIntroduction(), true, true, $attrs); + $attrs = array( + "label" => "outro" + ); + $this->addMaterialTag($a_xml_writer, $this->getOutro(), true, true, $attrs); + $a_xml_writer->xmlEndTag("objectives"); + + if ($this->getAnonymize()) { + $attribs = array("enabled" => "1"); + } else { + $attribs = array("enabled" => "0"); + } + $a_xml_writer->xmlElement("anonymisation", $attribs); + $a_xml_writer->xmlStartTag("restrictions"); + if ($this->getAnonymize() == 2) { + $attribs = array("type" => "free"); + } else { + $attribs = array("type" => "restricted"); + } + $a_xml_writer->xmlElement("access", $attribs); + if ($this->getStartDate()) { + $attrs = array("type" => "date"); + preg_match("/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/", $this->getStartDate(), $matches); + $a_xml_writer->xmlElement("startingtime", $attrs, sprintf("%04d-%02d-%02dT%02d:%02d:00", $matches[1], $matches[2], $matches[3], $matches[4], $matches[5], $matches[6])); + } + if ($this->getEndDate()) { + $attrs = array("type" => "date"); + preg_match("/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/", $this->getEndDate(), $matches); + $a_xml_writer->xmlElement("endingtime", $attrs, sprintf("%04d-%02d-%02dT%02d:%02d:00", $matches[1], $matches[2], $matches[3], $matches[4], $matches[5], $matches[6])); + } + $a_xml_writer->xmlEndTag("restrictions"); + + // constraints + $pages =&$this->getSurveyPages(); + $hasconstraints = false; + foreach ($pages as $question_array) { + foreach ($question_array as $question) { + if (count($question["constraints"])) { + $hasconstraints = true; + } + } + } + + if ($hasconstraints) { + $a_xml_writer->xmlStartTag("constraints"); + foreach ($pages as $question_array) { + foreach ($question_array as $question) { + if (count($question["constraints"])) { + // found constraints + foreach ($question["constraints"] as $constraint) { + $attribs = array( + "sourceref" => $question["question_id"], + "destref" => $constraint["question"], + "relation" => $constraint["short"], + "value" => $constraint["value"], + "conjunction" => $constraint["conjunction"] + ); + $a_xml_writer->xmlElement("constraint", $attribs); + } + } + } + } + $a_xml_writer->xmlEndTag("constraints"); + } + + // add the rest of the preferences in qtimetadata tags, because there is no correspondent definition in QTI + $a_xml_writer->xmlStartTag("metadata"); + + $custom_properties = array(); + $custom_properties["evaluation_access"] = $this->getEvaluationAccess(); + $custom_properties["status"] = !$this->getOfflineStatus(); + $custom_properties["display_question_titles"] = $this->getShowQuestionTitles(); + $custom_properties["pool_usage"] = (int) $this->getPoolUsage(); + + $custom_properties["own_results_view"] = (int) $this->hasViewOwnResults(); + $custom_properties["own_results_mail"] = (int) $this->hasMailOwnResults(); + $custom_properties["confirmation_mail"] = (int) $this->hasMailConfirmation(); + + $custom_properties["anon_user_list"] = (int) $this->hasAnonymousUserList(); + $custom_properties["mode"] = (int) $this->getMode(); + $custom_properties["mode_360_self_eval"] = (int) $this->get360SelfEvaluation(); + $custom_properties["mode_360_self_rate"] = (int) $this->get360SelfRaters(); + $custom_properties["mode_360_self_appr"] = (int) $this->get360SelfAppraisee(); + $custom_properties["mode_360_results"] = $this->get360Results(); + $custom_properties["mode_skill_service"] = (int) $this->getSkillService(); + $custom_properties["mode_self_eval_results"] = (int) $this->getSelfEvaluationResults(); + + + // :TODO: skills? + + // reminder/tutor notification are (currently?) not exportable + + foreach ($custom_properties as $label => $value) { + $a_xml_writer->xmlStartTag("metadatafield"); + $a_xml_writer->xmlElement("fieldlabel", null, $label); + $a_xml_writer->xmlElement("fieldentry", null, $value); + $a_xml_writer->xmlEndTag("metadatafield"); + } + + $a_xml_writer->xmlStartTag("metadatafield"); + $a_xml_writer->xmlElement("fieldlabel", null, "SCORM"); + include_once "./Services/MetaData/classes/class.ilMD.php"; + $md = new ilMD($this->getId(), 0, $this->getType()); + $writer = new ilXmlWriter(); + $md->toXml($writer); + $metadata = $writer->xmlDumpMem(); + $a_xml_writer->xmlElement("fieldentry", null, $metadata); + $a_xml_writer->xmlEndTag("metadatafield"); + + $a_xml_writer->xmlEndTag("metadata"); + $a_xml_writer->xmlEndTag("survey"); + + $attribs = array("id" => $this->getId()); + $a_xml_writer->xmlStartTag("surveyquestions", $attribs); + // add questionblock descriptions + foreach ($pages as $question_array) { + if (count($question_array) > 1) { + $attribs = array("id" => $question_array[0]["question_id"]); + $attribs = array("showQuestiontext" => $question_array[0]["questionblock_show_questiontext"], + "showBlocktitle" => $question_array[0]["questionblock_show_blocktitle"]); + $a_xml_writer->xmlStartTag("questionblock", $attribs); + if (strlen($question_array[0]["questionblock_title"])) { + $a_xml_writer->xmlElement("questionblocktitle", null, $question_array[0]["questionblock_title"]); + } + } + foreach ($question_array as $question) { + if (strlen($question["heading"])) { + $a_xml_writer->xmlElement("textblock", null, $question["heading"]); + } + $questionObject = self::_instanciateQuestion($question["question_id"]); + //questionObject contains all the fields from the database. (loadFromDb) + //we don't need the value from svy_qst_oblig table, we already have the values from svy_question table. + //if ($questionObject !== FALSE) $questionObject->insertXML($a_xml_writer, FALSE, $obligatory_states[$question["question_id"]]); + if ($questionObject !== false) { + $questionObject->insertXML($a_xml_writer, false); + } + } + if (count($question_array) > 1) { + $a_xml_writer->xmlEndTag("questionblock"); + } + } + + $a_xml_writer->xmlEndTag("surveyquestions"); + $a_xml_writer->xmlEndTag("surveyobject"); + $xml = $a_xml_writer->xmlDumpMem(false); + return $xml; + } + + /** + * 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) + { + if ($question_id < 1) { + return false; + } + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + $question_type = SurveyQuestion::_getQuestionType($question_id); + if (strlen($question_type) == 0) { + return false; + } + SurveyQuestion::_includeClass($question_type); + $question = new $question_type(); + $question->loadFromDb($question_id); + return $question; + } + + /** + * Locates the import directory and the xml file in a directory with an unzipped import file + * + * @return array An associative array containing "dir" (import directory) and "xml" (xml file) + * @access private + */ + public function locateImportFiles($a_dir) + { + if (!is_dir($a_dir) || is_int(strpos($a_dir, ".."))) { + return; + } + $importDirectory = ""; + $xmlFile = ""; + + $current_dir = opendir($a_dir); + $files = array(); + while ($entryname = readdir($current_dir)) { + $files[] = $entryname; + } + + foreach ($files as $file) { + if (is_dir($a_dir . "/" . $file) and ($file != "." and $file!="..")) { + // found directory created by zip + $importDirectory = $a_dir . "/" . $file; + } + } + closedir($current_dir); + if (strlen($importDirectory)) { + // find the xml file + $current_dir = opendir($importDirectory); + $files = array(); + while ($entryname = readdir($current_dir)) { + $files[] = $entryname; + } + foreach ($files as $file) { + if (@is_file($importDirectory . "/" . $file) && + ($file != "." && $file!="..") && + (preg_match("/^[0-9]{10}__[0-9]+__(svy_)*[0-9]+\.[A-Za-z]{1,3}$/", $file) || + preg_match("/^[0-9]{10}__[0-9]+__(survey__)*[0-9]+\.[A-Za-z]{1,3}$/", $file))) { + // found xml file + $xmlFile = $importDirectory . "/" . $file; + } + } + } + return array("dir" => $importDirectory, "xml" => $xmlFile); + } + + /** + * Imports a survey from XML into the ILIAS database + * @param $file_info + * @param $svy_qpl_id + * @return string + * @throws ilFileUtilsException + * @throws ilInvalidSurveyImportFileException + */ + public function importObject($file_info, $svy_qpl_id) + { + if ($svy_qpl_id < 1) { + $svy_qpl_id = -1; + } + // check if file was uploaded + $source = $file_info["tmp_name"]; + $error = ""; + if (($source == 'none') || (!$source) || $file_info["error"] > UPLOAD_ERR_OK) { + $error = $this->lng->txt("import_no_file_selected"); + } + // check correct file type + $isXml = false; + $isZip = false; + if ((strcmp($file_info["type"], "text/xml") == 0) || (strcmp($file_info["type"], "application/xml") == 0)) { + $this->log->debug("isXML"); + $isXml = true; + } + // too many different mime-types, so we use the suffix + $suffix = pathinfo($file_info["name"]); + if (strcmp(strtolower($suffix["extension"]), "zip") == 0) { + $this->log->debug("isZip"); + $isZip = true; + } + if (!$isXml && !$isZip) { + $error = $this->lng->txt("import_wrong_file_type"); + $this->log->debug("Survey: Import error. Filetype was \"" . $file_info["type"] . "\""); + } + if (strlen($error) == 0) { + // import file as a survey + $import_dir = $this->getImportDirectory(); + $import_subdir = ""; + $importfile = ""; + if ($isZip) { + $importfile = $import_dir . "/" . $file_info["name"]; + ilUtil::moveUploadedFile($source, $file_info["name"], $importfile); + ilUtil::unzip($importfile); + $found = $this->locateImportFiles($import_dir); + if (!((strlen($found["dir"]) > 0) && (strlen($found["xml"]) > 0))) { + $error = $this->lng->txt("wrong_import_file_structure"); + return $error; + } + $importfile = $found["xml"]; + $import_subdir = $found["dir"]; + } else { + $importfile = tempnam($import_dir, "survey_import"); + ilUtil::moveUploadedFile($source, $file_info["name"], $importfile); + } + + $this->log->debug("Import file = $importfile"); + $this->log->debug("Import subdir = $import_subdir"); + + $fh = fopen($importfile, "r"); + if (!$fh) { + $error = $this->lng->txt("import_error_opening_file"); + return $error; + } + $xml = fread($fh, filesize($importfile)); + $result = fclose($fh); + if (!$result) { + $error = $this->lng->txt("import_error_closing_file"); + return $error; + } + + unset($_SESSION["import_mob_xhtml"]); + if (strpos($xml, "questestinterop")) { + include_once("./Modules/Survey/exceptions/class.ilInvalidSurveyImportFileException.php"); + throw new ilInvalidSurveyImportFileException("Unsupported survey version (< 3.8) found."); + } else { + $this->log->debug("survey id = " . $this->getId()); + $this->log->debug("question pool id = " . $svy_qpl_id); + + include_once("./Services/Export/classes/class.ilImport.php"); + $imp = new ilImport(); + $config = $imp->getConfig("Modules/Survey"); + $config->setQuestionPoolID($svy_qpl_id); + $imp->getMapping()->addMapping("Modules/Survey", "svy", 0, $this->getId()); + $imp->importFromDirectory($import_subdir, "svy", "Modules/Survey"); + $this->log->debug("config(Modules/survey)->getQuestionPoolId =" . $config->getQuestionPoolID()); + return ""; + + //old code + include_once "./Services/Survey/classes/class.SurveyImportParser.php"; + $import = new SurveyImportParser($svy_qpl_id, "", true); + $import->setSurveyObject($this); + $import->setXMLContent($xml); + $import->startParsing(); + } + + if (is_array($_SESSION["import_mob_xhtml"])) { + include_once "./Services/MediaObjects/classes/class.ilObjMediaObject.php"; + include_once "./Services/RTE/classes/class.ilRTE.php"; + include_once "./Modules/TestQuestionPool/classes/class.ilObjQuestionPool.php"; + foreach ($_SESSION["import_mob_xhtml"] as $mob) { + $importfile = $import_subdir . "/" . $mob["uri"]; + if (file_exists($importfile)) { + if (!$mob["type"]) { + $mob["type"] = "svy:html"; + } + + $media_object = ilObjMediaObject::_saveTempFileAsMediaObject(basename($importfile), $importfile, false); + + // survey mob + if ($mob["type"] == "svy:html") { + ilObjMediaObject::_saveUsage($media_object->getId(), "svy:html", $this->getId()); + $this->setIntroduction(str_replace("src=\"" . $mob["mob"] . "\"", "src=\"" . "il_" . IL_INST_ID . "_mob_" . $media_object->getId() . "\"", $this->getIntroduction())); + $this->setOutro(str_replace("src=\"" . $mob["mob"] . "\"", "src=\"" . "il_" . IL_INST_ID . "_mob_" . $media_object->getId() . "\"", $this->getOutro())); + } + // question mob + elseif ($import->questions[$mob["id"]]) { + $new_qid = $import->questions[$mob["id"]]; + ilObjMediaObject::_saveUsage($media_object->getId(), $mob["type"], $new_qid); + $new_question = SurveyQuestion::_instanciateQuestion($new_qid); + $qtext = $new_question->getQuestiontext(); + $qtext = ilRTE::_replaceMediaObjectImageSrc($qtext, 0); + $qtext = str_replace("src=\"" . $mob["mob"] . "\"", "src=\"" . "il_" . IL_INST_ID . "_mob_" . $media_object->getId() . "\"", $qtext); + $qtext = ilRTE::_replaceMediaObjectImageSrc($qtext, 1); + $new_question->setQuestiontext($qtext); + $new_question->saveToDb(); + + // also fix existing original in pool + if ($new_question->getOriginalId()) { + $pool_question = SurveyQuestion::_instanciateQuestion($new_question->getOriginalId()); + $pool_question->setQuestiontext($qtext); + $pool_question->saveToDb(); + } + } + } else { + $ilLog = $this->log; + $ilLog->write("Error: Could not open XHTML mob file for test introduction during test import. File $importfile does not exist!"); + } + } + $this->setIntroduction(ilRTE::_replaceMediaObjectImageSrc($this->getIntroduction(), 1)); + $this->setOutro(ilRTE::_replaceMediaObjectImageSrc($this->getOutro(), 1)); + $this->saveToDb(); + } + + // delete import directory + ilUtil::delDir($this->getImportDirectory()); + } + return $error; + } + + /** + * Clone object + * + * @access public + * @param int ref_id of target container + * @param int copy id + * @return object new svy object + */ + public function cloneObject($a_target_id, $a_copy_id = 0, $a_omit_tree = false) + { + $ilDB = $this->db; + + $this->loadFromDb(); + + //survey mode + $svy_type = $this->getMode(); + + // Copy settings + $newObj = parent::cloneObject($a_target_id, $a_copy_id, $a_omit_tree); + $this->cloneMetaData($newObj); + $newObj->updateMetaData(); + + $newObj->setAuthor($this->getAuthor()); + $newObj->setIntroduction($this->getIntroduction()); + $newObj->setOutro($this->getOutro()); + $newObj->setEvaluationAccess($this->getEvaluationAccess()); + $newObj->setStartDate($this->getStartDate()); + $newObj->setEndDate($this->getEndDate()); + $newObj->setInvitation($this->getInvitation()); + $newObj->setInvitationMode($this->getInvitationMode()); + $newObj->setAnonymize($this->getAnonymize()); + $newObj->setShowQuestionTitles($this->getShowQuestionTitles()); + $newObj->setTemplate($this->getTemplate()); + $newObj->setPoolUsage($this->getPoolUsage()); + $newObj->setViewOwnResults($this->hasViewOwnResults()); + $newObj->setMailOwnResults($this->hasMailOwnResults()); + $newObj->setMailConfirmation($this->hasMailConfirmation()); + $newObj->setAnonymousUserList($this->hasAnonymousUserList()); + + // #12661 + if ($this->get360Mode()) { + $newObj->setMode(ilObjSurvey::MODE_360); + $newObj->set360SelfEvaluation($this->get360SelfEvaluation()); + $newObj->set360SelfAppraisee($this->get360SelfAppraisee()); + $newObj->set360SelfRaters($this->get360SelfRaters()); + $newObj->set360Results($this->get360Results()); + $newObj->setSkillService($this->getSkillService()); + } + //svy mode self eval: skills + view results + if ($svy_type == ilObjSurvey::MODE_SELF_EVAL) { + $newObj->setMode(ilObjSurvey::MODE_SELF_EVAL); + $newObj->setSkillService($this->getSkillService()); + $newObj->setSelfEvaluationResults($this->getSelfEvaluationResults()); + } + + // reminder/notification + $newObj->setReminderStatus($this->getReminderStatus()); + $newObj->setReminderStart($this->getReminderStart()); + $newObj->setReminderEnd($this->getReminderEnd()); + $newObj->setReminderFrequency($this->getReminderFrequency()); + $newObj->setReminderTarget($this->getReminderTarget()); + $newObj->setReminderTemplate($this->getReminderTemplate()); + // reminder_last_sent must not be copied! + $newObj->setTutorNotificationStatus($this->getTutorNotificationStatus()); + $newObj->setTutorNotificationRecipients($this->getTutorNotificationRecipients()); + $newObj->setTutorNotificationTarget($this->getTutorNotificationTarget()); + + $newObj->setMailNotification($this->getMailNotification()); + $newObj->setMailAddresses($this->getMailAddresses()); + $newObj->setMailParticipantData($this->getMailParticipantData()); + + $question_pointer = array(); + // clone the questions + $mapping = array(); + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + + foreach ($this->questions as $key => $question_id) { + $question = self::_instanciateQuestion($question_id); + if ($question) { // #10824 + $question->id = -1; + $original_id = SurveyQuestion::_getOriginalId($question_id, false); + $question->saveToDb($original_id); + $newObj->questions[$key] = $question->getId(); + $question_pointer[$question_id] = $question->getId(); + $mapping[$question_id] = $question->getId(); + } + } + + //copy online status if object is not the root copy object + $cp_options = ilCopyWizardOptions::_getInstance($a_copy_id); + + if (!$cp_options->isRootNode($this->getRefId())) { + $newObj->setOfflineStatus($this->getOfflineStatus()); + } + + $newObj->saveToDb(); + $newObj->cloneTextblocks($mapping); + + // #14929 + if (($svy_type == ilObjSurvey::MODE_360 || $svy_type == ilObjSurvey::MODE_SELF_EVAL) && + $this->getSkillService()) { + include_once "./Modules/Survey/classes/class.ilSurveySkill.php"; + $src_skills = new ilSurveySkill($this); + $tgt_skills = new ilSurveySkill($newObj); + + foreach ($mapping as $src_qst_id => $tgt_qst_id) { + $qst_skill = $src_skills->getSkillForQuestion($src_qst_id); + if ($qst_skill) { + $tgt_skills->addQuestionSkillAssignment($tgt_qst_id, $qst_skill["base_skill_id"], $qst_skill["tref_id"]); + } + } + } + + // clone the questionblocks + $questionblocks = array(); + $questionblock_questions = array(); + $result = $ilDB->queryF( + "SELECT * FROM svy_qblk_qst WHERE survey_fi = %s", + array('integer'), + array($this->getSurveyId()) + ); + if ($result->numRows() > 0) { + while ($row = $ilDB->fetchAssoc($result)) { + array_push($questionblock_questions, $row); + $questionblocks[$row["questionblock_fi"]] = $row["questionblock_fi"]; + } + } + // create new questionblocks + foreach ($questionblocks as $key => $value) { + $questionblock = self::_getQuestionblock($key); + $questionblock_id = self::_addQuestionblock($questionblock["title"], $questionblock["owner_fi"], $questionblock["show_questiontext"], $questionblock["show_blocktitle"]); + $questionblocks[$key] = $questionblock_id; + } + // create new questionblock questions + foreach ($questionblock_questions as $key => $value) { + if ($questionblocks[$value["questionblock_fi"]] && + $question_pointer[$value["question_fi"]]) { + $next_id = $ilDB->nextId('svy_qblk_qst'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_qblk_qst (qblk_qst_id, survey_fi, questionblock_fi, question_fi) " . + "VALUES (%s, %s, %s, %s)", + array('integer','integer','integer','integer'), + array($next_id, $newObj->getSurveyId(), $questionblocks[$value["questionblock_fi"]], $question_pointer[$value["question_fi"]]) + ); + } + } + + // clone the constraints + $constraints = self::_getConstraints($this->getSurveyId()); + $newConstraints = array(); + foreach ($constraints as $key => $constraint) { + if ($question_pointer[$constraint["for_question"]] && + $question_pointer[$constraint["question"]]) { + if (!array_key_exists($constraint['id'], $newConstraints)) { + $constraint_id = $newObj->addConstraint($question_pointer[$constraint["question"]], $constraint["relation_id"], $constraint["value"], $constraint['conjunction']); + $newConstraints[$constraint['id']] = $constraint_id; + } + $newObj->addConstraintToQuestion($question_pointer[$constraint["for_question"]], $newConstraints[$constraint['id']]); + } + } + + // #16210 - clone LP settings + include_once('./Services/Tracking/classes/class.ilLPObjSettings.php'); + $obj_settings = new ilLPObjSettings($this->getId()); + $obj_settings->cloneSettings($newObj->getId()); + unset($obj_settings); + + return $newObj; + } + + public function getTextblock($question_id) + { + $ilDB = $this->db; + $result = $ilDB->queryF( + "SELECT * FROM svy_svy_qst WHERE question_fi = %s", + array('integer'), + array($question_id) + ); + if ($result->numRows()) { + $row = $ilDB->fetchAssoc($result); + return $row["heading"]; + } else { + return ""; + } + } + + /** + * Clones the textblocks of survey questions + * + * @access public + */ + public function cloneTextblocks($mapping) + { + foreach ($mapping as $original_id => $new_id) { + $textblock = $this->getTextblock($original_id); + include_once "./Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php"; + $this->saveHeading(ilUtil::stripSlashes($textblock, true, ilObjAdvancedEditing::_getUsedHTMLTagsAsString("survey")), $new_id); + } + } + + /** + * creates data directory for export files + * (data_dir/svy_data/svy_/export, depending on data + * directory that is set in ILIAS setup/ini) + * + * @throws ilSurveyException + */ + public function createExportDirectory() + { + $svy_data_dir = ilUtil::getDataDir() . "/svy_data"; + ilUtil::makeDir($svy_data_dir); + if (!is_writable($svy_data_dir)) { + include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; + throw new ilSurveyException("Survey Data Directory (" . $svy_data_dir . ") not writeable."); + } + + // create learning module directory (data_dir/lm_data/lm_) + $svy_dir = $svy_data_dir . "/svy_" . $this->getId(); + ilUtil::makeDir($svy_dir); + if (!@is_dir($svy_dir)) { + include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; + throw new ilSurveyException("Creation of Survey Directory failed."); + } + // create Export subdirectory (data_dir/lm_data/lm_/Export) + $export_dir = $svy_dir . "/export"; + ilUtil::makeDir($export_dir); + if (!@is_dir($export_dir)) { + include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; + throw new ilSurveyException("Creation of Export Directory failed."); + } + } + + /** + * get export directory of survey + */ + public function getExportDirectory() + { + $export_dir = ilUtil::getDataDir() . "/svy_data" . "/svy_" . $this->getId() . "/export"; + + return $export_dir; + } + + /** + * creates data directory for import files + * (data_dir/svy_data/svy_/import, depending on data + * directory that is set in ILIAS setup/ini) + * + * @throws ilSurveyException + */ + public function createImportDirectory() + { + $svy_data_dir = ilUtil::getDataDir() . "/svy_data"; + ilUtil::makeDir($svy_data_dir); + + if (!is_writable($svy_data_dir)) { + include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; + throw new ilSurveyException("Survey Data Directory (" . $svy_data_dir . ") not writeable."); + } + + // create test directory (data_dir/svy_data/svy_) + $svy_dir = $svy_data_dir . "/svy_" . $this->getId(); + ilUtil::makeDir($svy_dir); + if (!@is_dir($svy_dir)) { + include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; + throw new ilSurveyException("Creation of Survey Directory failed."); + } + + // create import subdirectory (data_dir/svy_data/svy_/import) + $import_dir = $svy_dir . "/import"; + ilUtil::makeDir($import_dir); + if (!@is_dir($import_dir)) { + include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; + throw new ilSurveyException("Creation of Import Directory failed."); + } + } + + /** + * get import directory of survey + */ + public function getImportDirectory() + { + $import_dir = ilUtil::getDataDir() . "/svy_data" . + "/svy_" . $this->getId() . "/import"; + if (!is_dir($import_dir)) { + ilUtil::makeDirParents($import_dir); + } + if (@is_dir($import_dir)) { + return $import_dir; + } else { + return false; + } + } + + public function saveHeading($heading = "", $insertbefore) + { + $ilDB = $this->db; + if ($heading) { + $affectedRows = $ilDB->manipulateF( + "UPDATE svy_svy_qst SET heading=%s WHERE survey_fi=%s AND question_fi=%s", + array('text','integer','integer'), + array($heading, $this->getSurveyId(), $insertbefore) + ); + } else { + $affectedRows = $ilDB->manipulateF( + "UPDATE svy_svy_qst SET heading=%s WHERE survey_fi=%s AND question_fi=%s", + array('text','integer','integer'), + array(null, $this->getSurveyId(), $insertbefore) + ); + } + } + + public function isAnonymousKey($key) + { + $ilDB = $this->db; + + $result = $ilDB->queryF( + "SELECT anonymous_id FROM svy_anonymous WHERE survey_key = %s AND survey_fi = %s", + array('text','integer'), + array($key, $this->getSurveyId()) + ); + return ($result->numRows() == 1) ? true : false; + } + + public function bindSurveyCodeToUser($user_id, $code) + { + $ilDB = $this->db; + + if ($user_id == ANONYMOUS_USER_ID) { + return; + } + + if ($this->checkSurveyCode($code)) { + $ilDB->manipulate("UPDATE svy_anonymous" . + " SET user_key = " . $ilDB->quote(md5($user_id), "text") . + " WHERE survey_key = " . $ilDB->quote($code, "text")); + } + } + + public function isAnonymizedParticipant($key) + { + $ilDB = $this->db; + + $result = $ilDB->queryF( + "SELECT finished_id FROM svy_finished WHERE anonymous_id = %s AND survey_fi = %s", + array('text','integer'), + array($key, $this->getSurveyId()) + ); + return ($result->numRows() == 1) ? true : false; + } + + public function checkSurveyCode($code) + { + if ($this->isAnonymousKey($code)) { + if ($this->isSurveyStarted("", $code) == 1) { + return false; + } else { + return true; + } + } else { + return false; + } + } + + /** + * Returns a list of survey codes for file export + * + * @param array $a_array An array of all survey codes that should be exported + * @return string A comma separated list of survey codes an URLs for file export + * @access public + */ + public function getSurveyCodesForExport(array $a_codes = null, array $a_ids = null) + { + $ilDB = $this->db; + $ilUser = $this->user; + $lng = $this->lng; + + include_once "./Services/Link/classes/class.ilLink.php"; + + $sql = "SELECT svy_anonymous.*, svy_finished.state" . + " FROM svy_anonymous" . + " LEFT JOIN svy_finished ON (svy_anonymous.survey_key = svy_finished.anonymous_id)" . + " WHERE svy_anonymous.survey_fi = " . $ilDB->quote($this->getSurveyId(), "integer") . + " AND svy_anonymous.user_key IS NULL"; + + if ($a_codes) { + $sql .= " AND " . $ilDB->in("svy_anonymous.survey_key", $a_codes, "", "text"); + } elseif ($a_ids) { + $sql .= " AND " . $ilDB->in("svy_anonymous.anonymous_id", $a_ids, "", "text"); + } + + $export = array(); + + // #14905 + $titles = array(); + $titles[] = '"' . $lng->txt("survey_code") . '"'; + $titles[] = '"' . $lng->txt("email") . '"'; + $titles[] = '"' . $lng->txt("lastname") . '"'; + $titles[] = '"' . $lng->txt("firstname") . '"'; + $titles[] = '"' . $lng->txt("create_date") . '"'; + $titles[] = '"' . $lng->txt("used") . '"'; + $titles[] = '"' . $lng->txt("mail_sent_short") . '"'; + $titles[] = '"' . $lng->txt("survey_code_url") . '"'; + $export[] = implode(";", $titles); + + $result = $ilDB->query($sql); + $default_lang = $ilUser->getPref("survey_code_language"); + while ($row = $ilDB->fetchAssoc($result)) { + $item = array(); + $item[] = $row["survey_key"]; + + if ($row["externaldata"]) { + $ext = unserialize($row["externaldata"]); + $item[] = $ext["email"]; + $item[] = $ext["lastname"]; + $item[] = $ext["firstname"]; + } else { + $item[] = ""; + $item[] = ""; + $item[] = ""; + } + + // No relative (today, tomorrow...) dates in export. + $date = new ilDateTime($row['tstamp'], IL_CAL_UNIX); + $item[] = $date->get(IL_CAL_DATETIME); + + $item[] = ($this->isSurveyCodeUsed($row["survey_key"])) ? 1 : 0; + $item[] = ($row["sent"]) ? 1 : 0; + + $params = array("accesscode" => $row["survey_key"]); + if ($default_lang) { + $params["lang"] = $default_lang; + } + $item[] = ilLink::_getLink($this->getRefId(), "svy", $params); + + $export[] = '"' . implode('";"', $item) . '"'; + } + return implode("\n", $export); + } + + /** + * Fetches the data for the survey codes table + * + * @param string $lang Language for the survey code URL + * @return array The requested data + * @access public + */ + public function getSurveyCodesTableData(array $ids = null, $lang = null) + { + $ilDB = $this->db; + + include_once "./Services/Link/classes/class.ilLink.php"; + + $codes = array(); + + $sql = "SELECT svy_anonymous.*, svy_finished.state" . + " FROM svy_anonymous" . + " LEFT JOIN svy_finished ON (svy_anonymous.survey_key = svy_finished.anonymous_id)" . + " WHERE svy_anonymous.survey_fi = " . $ilDB->quote($this->getSurveyId(), "integer") /*. + " AND svy_anonymous.user_key IS NULL" */; // #15860 + + if ($ids) { + $sql .= " AND " . $ilDB->in("svy_anonymous.anonymous_id", $ids, "", "integer"); + } + + $sql .= " ORDER BY tstamp, survey_key ASC"; + $result = $ilDB->query($sql); + if ($result->numRows() > 0) { + while ($row = $ilDB->fetchAssoc($result)) { + $href = ""; + $used = false; + if ($this->isSurveyCodeUsed($row["survey_key"])) { + $used = true; + } else { + $params = array("accesscode" => $row["survey_key"]); + if ($lang) { + $params["lang"] = $lang; + } + $href = ilLink::_getLink($this->getRefId(), "svy", $params); + } + + + $item = array( + 'id' => $row["anonymous_id"], + 'code' => $row["survey_key"], + 'date' => $row["tstamp"], + 'used' => $used, + 'sent' => $row['sent'], + 'href' => $href, + 'email' => '', + 'last_name' => '', + 'first_name' => '' + ); + + if ($row["externaldata"]) { + $ext = unserialize($row["externaldata"]); + $item['email'] = $ext['email']; + $item['last_name'] = $ext['lastname']; + $item['first_name'] = $ext['firstname']; + } + + array_push($codes, $item); + } + } + return $codes; + } + + public function isSurveyCodeUsed($code) + { + $ilDB = $this->db; + $result = $ilDB->queryF( + "SELECT finished_id FROM svy_finished WHERE survey_fi = %s AND anonymous_id = %s", + array('integer','text'), + array($this->getSurveyId(), $code) + ); + return ($result->numRows() > 0) ? true : false; + } + + public function isSurveyCodeUnique($code) + { + $ilDB = $this->db; + $result = $ilDB->queryF( + "SELECT anonymous_id FROM svy_anonymous WHERE survey_fi = %s AND survey_key = %s", + array('integer','text'), + array($this->getSurveyId(), $code) + ); + return ($result->numRows() > 0) ? false : true; + } + + public function createSurveyCodes($nrOfCodes) + { + $ilDB = $this->db; + + $res = array(); + + for ($i = 0; $i < $nrOfCodes; $i++) { + $next_id = $ilDB->nextId('svy_anonymous'); + $ilDB->manipulateF( + "INSERT INTO svy_anonymous (anonymous_id, survey_key, survey_fi, tstamp) " . + "VALUES (%s, %s, %s, %s)", + array('integer','text','integer','integer'), + array($next_id, $this->createNewAccessCode(), $this->getSurveyId(), time()) + ); + $res[] = $next_id; + } + + return $res; + } + + public function importSurveyCode($a_anonymize_key, $a_created, $a_data) + { + $ilDB = $this->db; + + $next_id = $ilDB->nextId('svy_anonymous'); + $ilDB->manipulateF( + "INSERT INTO svy_anonymous (anonymous_id, survey_key, survey_fi, externaldata, tstamp) " . + "VALUES (%s, %s, %s, %s, %s)", + array('integer','text','integer','text','integer'), + array($next_id, $a_anonymize_key, $this->getSurveyId(), serialize($a_data), $a_created) + ); + } + + public function createSurveyCodesForExternalData($data) + { + $ilDB = $this->db; + + $ids = array(); + foreach ($data as $dataset) { + $anonymize_key = $this->createNewAccessCode(); + $next_id = $ilDB->nextId('svy_anonymous'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_anonymous (anonymous_id, survey_key, survey_fi, externaldata, tstamp) " . + "VALUES (%s, %s, %s, %s, %s)", + array('integer','text','integer','text','integer'), + array($next_id, $anonymize_key, $this->getSurveyId(), serialize($dataset), time()) + ); + $ids[] = $next_id; + } + return $ids; + } + + public function sendCodes($not_sent, $subject, $message, $lang) + { + global $DIC; + /* + * 0 = all + * 1 = not sent + * 2 = finished + * 3 = not finished + */ + $check_finished = ($not_sent > 1); + + include_once "./Services/Mail/classes/class.ilMail.php"; + include_once "./Services/Link/classes/class.ilLink.php"; + + #19956 + $user_id = $DIC->user()->getId(); + $mail = new ilMail($user_id); + $recipients = $this->getExternalCodeRecipients($check_finished); + foreach ($recipients as $data) { + if ($data['email'] && $data['code']) { + $do_send = false; + switch ((int) $not_sent) { + case 1: + $do_send = !(bool) $data['sent']; + break; + + case 2: + $do_send = $data['finished']; + break; + + case 3: + $do_send = !$data['finished']; + break; + + default: + $do_send = true; + break; + } + if ($do_send) { + // build text + $messagetext = $message; + $url = ilLink::_getLink( + $this->getRefId(), + "svy", + array( + "accesscode" => $data["code"], + "lang" => $lang + ) + ); + $messagetext = str_replace('[url]', $url, $messagetext); + foreach ($data as $key => $value) { + $messagetext = str_replace('[' . $key . ']', $value, $messagetext); + } + + // send mail + $mail->sendMail( + $data['email'], // to + "", // cc + "", // bcc + $subject, // subject + $messagetext, // message + array(), // attachments + array('normal') // type + ); + } + } + } + + $ilDB = $this->db; + $ilDB->manipulateF( + "UPDATE svy_anonymous SET sent = %s WHERE survey_fi = %s AND externaldata IS NOT NULL", + array('integer','integer'), + array(1, $this->getSurveyId()) + ); + } + + public function getExternalCodeRecipients($a_check_finished = false) + { + $ilDB = $this->db; + $result = $ilDB->queryF( + "SELECT survey_key code, externaldata, sent FROM svy_anonymous WHERE survey_fi = %s", + array('integer'), + array($this->getSurveyId()) + ); + $res = array(); + while ($row = $ilDB->fetchAssoc($result)) { + if (!$row['externaldata']) { + continue; + } + + $externaldata = unserialize($row['externaldata']); + if (!$externaldata['email']) { + continue; + } + + $externaldata['code'] = $row['code']; + $externaldata['sent'] = $row['sent']; + + if ($a_check_finished) { + #23294 + //$externaldata['finished'] = $this->isSurveyCodeUsed($row['code']); + $externaldata['finished'] = $this->isSurveyFinishedByCode($row['code']); + } + + array_push($res, $externaldata); + } + return $res; + } + + /** + * Get if survey is finished for an specific anonymous user code. + * @param $a_code anonymous user code + * @return bool + */ + public function isSurveyFinishedByCode($a_code) + { + $result = $this->db->queryF( + "SELECT state FROM svy_finished WHERE survey_fi = %s AND anonymous_id = %s", + array('integer','text'), + array($this->getSurveyId(), $a_code) + ); + + $row = $this->db->fetchAssoc($result); + + return $row['state']; + } + + /** + * Deletes a given survey access code + * + * @param string $survey_code The survey code that should be deleted + */ + public function deleteSurveyCode($survey_code) + { + $ilDB = $this->db; + + if (strlen($survey_code) > 0) { + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_anonymous WHERE survey_fi = %s AND survey_key = %s", + array('integer', 'text'), + array($this->getSurveyId(), $survey_code) + ); + } + } + + /** + * Returns a survey access code that was saved for a registered user + * + * @param int $user_id The database id of the user + * @return string The survey access code of the user + */ + public function getUserAccessCode($user_id) + { + $ilDB = $this->db; + $access_code = ""; + $result = $ilDB->queryF( + "SELECT survey_key FROM svy_anonymous WHERE survey_fi = %s AND user_key = %s", + array('integer','text'), + array($this->getSurveyId(), md5($user_id)) + ); + if ($result->numRows()) { + $row = $ilDB->fetchAssoc($result); + $access_code = $row["survey_key"]; + } + return $access_code; + } + + /** + * Saves a survey access code for a registered user to the database + * + * @param int $user_id The database id of the user + * @param string $access_code The survey access code + */ + public function saveUserAccessCode($user_id, $access_code) + { + $ilDB = $this->db; + + // not really sure what to do about ANONYMOUS_USER_ID + + $next_id = $ilDB->nextId('svy_anonymous'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_anonymous (anonymous_id, survey_key, survey_fi, user_key, tstamp) " . + "VALUES (%s, %s, %s, %s, %s)", + array('integer','text', 'integer', 'text', 'integer'), + array($next_id, $access_code, $this->getSurveyId(), md5($user_id), time()) + ); + } + + /** + * Returns a new, unused survey access code + * + * @return string A new survey access code + */ + public function createNewAccessCode() + { + // create a 5 character code + $codestring = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + mt_srand(); + $code = ""; + for ($i = 1; $i <=5; $i++) { + $index = mt_rand(0, strlen($codestring)-1); + $code .= substr($codestring, $index, 1); + } + // verify it against the database + while (!$this->isSurveyCodeUnique($code)) { + $code = $this->createNewAccessCode(); + } + return $code; + } + + public function getLastAccess($finished_id) + { + $ilDB = $this->db; + + $result = $ilDB->queryF( + "SELECT tstamp FROM svy_answer WHERE active_fi = %s ORDER BY tstamp DESC", + array('integer'), + array($finished_id) + ); + if ($result->numRows()) { + $row = $ilDB->fetchAssoc($result); + return $row["tstamp"]; + } else { + $result = $ilDB->queryF( + "SELECT tstamp FROM svy_finished WHERE finished_id = %s", + array('integer'), + array($finished_id) + ); + if ($result->numRows()) { + $row = $ilDB->fetchAssoc($result); + return $row["tstamp"]; + } + } + return ""; + } + + /** + * 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) + { + return ilUtil::prepareTextareaOutput($txt_output, $prepare_for_latex_output); + } + + /** + * 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; + } + } + + /** + * 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, $attribs = null) + { + include_once "./Services/RTE/classes/class.ilRTE.php"; + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + + $a_xml_writer->xmlStartTag("material", $attribs); + $attrs = array( + "type" => "text/plain" + ); + if ($this->isHTML($a_material)) { + $attrs["type"] = "text/xhtml"; + } + $mattext = ilRTE::_replaceMediaObjectImageSrc($a_material, 0); + $a_xml_writer->xmlElement("mattext", $attrs, $mattext); + + if ($add_mobs) { + $mobs = ilObjMediaObject::_getMobsOfObject("svy:html", $this->getId()); + foreach ($mobs as $mob) { + $mob_id = "il_" . IL_INST_ID . "_mob_" . $mob; + if (strpos($mattext, $mob_id) !== false) { + $mob_obj = new ilObjMediaObject($mob); + $imgattrs = array( + "label" => $mob_id, + "uri" => "objects/" . "il_" . IL_INST_ID . "_mob_" . $mob . "/" . $mob_obj->getTitle(), + "type" => "svy:html", + "id" => $this->getId() + ); + $a_xml_writer->xmlElement("matimage", $imgattrs, null); + } + } + } + if ($close_material_tag) { + $a_xml_writer->xmlEndTag("material"); + } + } + + /** + * Checks if the survey code can be exported with the survey evaluation. In some cases this may be + * necessary but usually you should prevent it because people who sent the survey codes could connect + * real people with the survey code in the evaluation and undermine the anonymity + * + * @return boolean TRUE if the survey is anonymized and the survey code may be shown in the export file + * @author Helmut Schottmüller + **/ + public function canExportSurveyCode() + { + if ($this->getAnonymize() != self::ANONYMIZE_OFF) { + if ($this->surveyCodeSecurity == false) { + return true; + } + } + return false; + } + + /** + * Convert a print output to XSL-FO + * + * @param string $print_output The print output + * @return string XSL-FO code + * @access public + */ + public function processPrintoutput2FO($print_output) + { + if (extension_loaded("tidy")) { + $config = array( + "indent" => false, + "output-xml" => true, + "numeric-entities" => true + ); + $tidy = new tidy(); + $tidy->parseString($print_output, $config, 'utf8'); + $tidy->cleanRepair(); + $print_output = tidy_get_output($tidy); + $print_output = preg_replace("/^.*?( $print_output, '/_xsl' => $xsl ); + $xh = xslt_create(); + $params = array(); + try { + $output = xslt_process($xh, "arg:/_xml", "arg:/_xsl", null, $args, $params); + } catch (Exception $e) { + $this->log->error("Print XSLT failed:"); + $this->log->error("Content: " . $print_output); + $this->log->error("Xsl: " . $xsl); + throw ($e); + } + xslt_error($xh); + xslt_free($xh); + + return $output; + } + + /** + * Delivers a PDF file from a XSL-FO string + * + * @param string $fo The XSL-FO string + * @access public + */ + public function deliverPDFfromFO($fo) + { + $ilLog = $this->log; + + $fo_file = ilUtil::ilTempnam() . ".fo"; + $fp = fopen($fo_file, "w"); + fwrite($fp, $fo); + fclose($fp); + + include_once './Services/WebServices/RPC/classes/class.ilRpcClientFactory.php'; + try { + $pdf_base64 = ilRpcClientFactory::factory('RPCTransformationHandler')->ilFO2PDF($fo); + ilUtil::deliverData($pdf_base64->scalar, ilUtil::getASCIIFilename($this->getTitle()) . ".pdf", "application/pdf"); + return true; + } catch (Exception $e) { + $ilLog->write(__METHOD__ . ': ' . $e->getMessage()); + return false; + } + } + + /** + * Checks whether or not a question plugin with a given name is active + * + * @param string $a_pname The plugin name + * @access public + */ + public function isPluginActive($a_pname) + { + $ilPluginAdmin = $this->plugin_admin; + if ($ilPluginAdmin->isActive(IL_COMP_MODULE, "SurveyQuestionPool", "svyq", $a_pname)) { + return true; + } else { + return false; + } + } + + /** + * Sets the survey id + * + * @param integer $survey_id The survey id + */ + public function setSurveyId($survey_id) + { + $this->survey_id = $survey_id; + } + + /** + * Returns a data of all users specified by id list + * + * @param $ids array of user id's + * @return array The user data "usr_id, login, lastname, firstname, clientip" of the users with id as key + */ + public function &getUserData($ids) + { + $ilDB = $this->db; + + if (!is_array($ids) || count($ids) ==0) { + return array(); + } + + $result = $ilDB->query("SELECT usr_id, login, lastname, firstname FROM usr_data WHERE " . $ilDB->in('usr_id', $ids, false, 'integer') . " ORDER BY login"); + $result_array = array(); + while ($row = $ilDB->fetchAssoc($result)) { + $result_array[$row["usr_id"]]= $row; + } + return $result_array; + } + + public function getMailNotification() + { + return $this->mailnotification; + } + + public function setMailNotification($a_notification) + { + $this->mailnotification = ($a_notification) ? true : false; + } + + public function getMailAddresses() + { + return $this->mailaddresses; + } + + public function setMailAddresses($a_addresses) + { + $this->mailaddresses = $a_addresses; + } + + public function getMailParticipantData() + { + return $this->mailparticipantdata; + } + + public function setMailParticipantData($a_data) + { + $this->mailparticipantdata = $a_data; + } + + public function setStartTime($finished_id, $first_question) + { + $ilDB = $this->db; + $time = time(); + //primary for table svy_times + $id = $ilDB->nextId('svy_times'); + $_SESSION['svy_entered_page'] = $time; + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_times (id, finished_fi, entered_page, left_page, first_question) VALUES (%s, %s, %s, %s,%s)", + array('integer','integer', 'integer', 'integer', 'integer'), + array($id, $finished_id, $time, null, $first_question) + ); + } + + public function setEndTime($finished_id) + { + $ilDB = $this->db; + $time = time(); + $affectedRows = $ilDB->manipulateF( + "UPDATE svy_times SET left_page = %s WHERE finished_fi = %s AND entered_page = %s", + array('integer', 'integer', 'integer'), + array($time, $finished_id, $_SESSION['svy_entered_page']) + ); + unset($_SESSION['svy_entered_page']); + } + + public function getWorkingtimeForParticipant($finished_id) + { + $ilDB = $this->db; + + $result = $ilDB->queryF( + "SELECT * FROM svy_times WHERE finished_fi = %s", + array('integer'), + array($finished_id) + ); + $total = 0; + while ($row = $ilDB->fetchAssoc($result)) { + if ($row['left_page'] > 0 && $row['entered_page'] > 0) { + $total += $row['left_page'] - $row['entered_page']; + } + } + return $total; + } + + public function setTemplate($template_id) + { + $this->template_id = (int) $template_id; + } + + public function getTemplate() + { + return $this->template_id; + } + + public function updateOrder(array $a_order) + { + if (sizeof($this->questions) == sizeof($a_order)) { + $this->questions = array_flip($a_order); + $this->saveQuestionsToDB(); + } + } + + public function getPoolUsage() + { + return $this->pool_usage; + } + + public function setPoolUsage($a_value) + { + $this->pool_usage = (bool) $a_value; + } + + /** + * Get current pool status + * + * @return bool + */ + public function isPoolActive() + { + $use_pool = (bool) $this->getPoolUsage(); + $template_settings = $this->getTemplate(); + if ($template_settings) { + include_once "Services/Administration/classes/class.ilSettingsTemplate.php"; + $template_settings = new ilSettingsTemplate($template_settings); + $template_settings = $template_settings->getSettings(); + $template_settings = $template_settings["use_pool"]; + if ($template_settings && $template_settings["hide"]) { + $use_pool = (bool) $template_settings["value"]; + } + } + return $use_pool; + } + + /** + * Apply settings template + * + * @param int $template_id + */ + public function applySettingsTemplate($template_id) + { + if (!$template_id) { + return; + } + + include_once "Services/Administration/classes/class.ilSettingsTemplate.php"; + $template = new ilSettingsTemplate($template_id); + $template_settings = $template->getSettings(); + //ilUtil::dumpVar($template_settings); exit; + if ($template_settings) { + if ($template_settings["show_question_titles"] !== null) { + if ($template_settings["show_question_titles"]["value"]) { + $this->setShowQuestionTitles(true); + } else { + $this->setShowQuestionTitles(false); + } + } + + if ($template_settings["use_pool"] !== null) { + if ($template_settings["use_pool"]["value"]) { + $this->setPoolUsage(true); + } else { + $this->setPoolUsage(false); + } + } + + + /* see #0021719 + if($template_settings["anonymization_options"]["value"]) + { + $anon_map = array('personalized' => self::ANONYMIZE_OFF, + 'anonymize_with_code' => self::ANONYMIZE_ON, + 'anonymize_without_code' => self::ANONYMIZE_FREEACCESS); + $this->setAnonymize($anon_map[$template_settings["anonymization_options"]["value"]]); + }*/ + + // see #0021719 and ilObjectSurveyGUI::savePropertiesObject + $this->setEvaluationAccess($template_settings["evaluation_access"]["value"]); + $codes = (bool) $template_settings["acc_codes"]["value"]; + $anon = (bool) $template_settings["anonymization_options"]["value"]; + if (!$anon) { + if (!$codes) { + $this->setAnonymize(ilObjSurvey::ANONYMIZE_OFF); + } else { + $this->setAnonymize(ilObjSurvey::ANONYMIZE_CODE_ALL); + } + } else { + if ($codes) { + $this->setAnonymize(ilObjSurvey::ANONYMIZE_ON); + } else { + $this->setAnonymize(ilObjSurvey::ANONYMIZE_FREEACCESS); + } + + $this->setAnonymousUserList($_POST["anon_list"]); + } + + + + /* other settings: not needed here + * - enabled_end_date + * - enabled_start_date + * - rte_switch + */ + } + + $this->setTemplate($template_id); + $this->saveToDb(); + } + + public function updateCode($a_id, $a_email, $a_last_name, $a_first_name, $a_sent) + { + $ilDB = $this->db; + + $a_email = trim($a_email); + + // :TODO: + if (($a_email && !ilUtil::is_email($a_email)) || $a_email == "") { + return false; + } + + $data = array("email" => $a_email, + "lastname" => trim($a_last_name), + "firstname" => trim($a_first_name)); + + $fields = array( + "externaldata" => array("text", serialize($data)), + "sent" => array("integer", $a_sent) + ); + + $ilDB->update( + "svy_anonymous", + $fields, + array("anonymous_id" => array("integer", $a_id)) + ); + + return true; + } + + + // + // 360° + // + + public function get360Mode() + { + if ($this->getMode() == ilObjSurvey::MODE_360) { + return true; + } + return false; + } + + public function set360SelfEvaluation($a_value) + { + $this->mode_360_self_eval = (bool) $a_value; + } + + public function get360SelfEvaluation() + { + return (bool) $this->mode_360_self_eval; + } + + public function set360SelfAppraisee($a_value) + { + $this->mode_360_self_appr = (bool) $a_value; + } + + public function get360SelfAppraisee() + { + return (bool) $this->mode_360_self_appr; + } + + public function set360SelfRaters($a_value) + { + $this->mode_360_self_rate = (bool) $a_value; + } + + public function get360SelfRaters() + { + return (bool) $this->mode_360_self_rate; + } + + public function set360Results($a_value) + { + $this->mode_360_results = (int) $a_value; + } + + public function get360Results() + { + return (int) $this->mode_360_results; + } + + public function addAppraisee($a_user_id) + { + global $DIC; + + $ilDB = $DIC->database(); + $access = $DIC->access(); + + if (!$this->isAppraisee($a_user_id) && + $a_user_id != ANONYMOUS_USER_ID) { + $fields = array( + "obj_id" => array("integer", $this->getSurveyId()), + "user_id" => array("integer", $a_user_id) + ); + $ilDB->insert("svy_360_appr", $fields); + + // send notification and add to desktop + if ($access->checkAccessOfUser($a_user_id, "read", "", $this->getRefId())) { + $this->sendAppraiseeNotification($a_user_id); + $type = ilObject::_lookupType($this->getRefId(), true); + ilObjUser::_addDesktopItem($a_user_id, $this->getRefId(), $type); + } + } + } + + /** + * Send appraisee notification + * + * @param int $a_user_id user id + */ + public function sendAppraiseeNotification($a_user_id) + { + include_once "./Services/Notification/classes/class.ilSystemNotification.php"; + $ntf = new ilSystemNotification(); + $ntf->setLangModules(array("svy", "survey")); + $ntf->setRefId($this->getRefId()); + $ntf->setGotoLangId('url'); + + // user specific language + $lng = $ntf->getUserLanguage($a_user_id); + + $ntf->setIntroductionLangId("svy_user_added_360_appraisee_mail"); + $subject = str_replace("%1", $this->getTitle(), $lng->txt("svy_user_added_360_appraisee")); + + // #10044 + $mail = new ilMail(ANONYMOUS_USER_ID); + //$mail->enableSOAP(false); // #10410 + $mail->sendMail( + ilObjUser::_lookupLogin($a_user_id), + null, + null, + $subject, + $ntf->composeAndGetMessage($a_user_id, null, "read", true), + null, + array("system") + ); + } + + /** + * Send appraisee notification + * + * @param int $a_user_id user id + */ + public function sendAppraiseeCloseNotification($a_user_id) + { + include_once "./Services/Notification/classes/class.ilSystemNotification.php"; + $ntf = new ilSystemNotification(); + $ntf->setLangModules(array("svy", "survey")); + $ntf->setRefId($this->getRefId()); + $ntf->setGotoLangId('url'); + + // user specific language + $lng = $ntf->getUserLanguage($a_user_id); + + $ntf->setIntroductionLangId("svy_user_added_360_appraisee_close_mail"); + $subject = str_replace("%1", $this->getTitle(), $lng->txt("svy_user_added_360_appraisee")); + + // #10044 + $mail = new ilMail(ANONYMOUS_USER_ID); + //$mail->enableSOAP(false); // #10410 + $mail->sendMail( + ilObjUser::_lookupLogin($a_user_id), + null, + null, + $subject, + $ntf->composeAndGetMessage($a_user_id, null, "read", true), + null, + array("system") + ); + } + + /** + * Send rater notification + * + * @param int $a_user_id user id + */ + public function sendRaterNotification($a_user_id, $a_appraisee_id) + { + include_once "./Services/Notification/classes/class.ilSystemNotification.php"; + $ntf = new ilSystemNotification(); + $ntf->setLangModules(array("svy", "survey")); + $ntf->setRefId($this->getRefId()); + $ntf->setGotoLangId('url'); + + // user specific language + $lng = $ntf->getUserLanguage($a_user_id); + + $ntf->setIntroductionLangId("svy_user_added_360_rater_mail"); + $subject = str_replace("%1", $this->getTitle(), $lng->txt("svy_user_added_360_rater")); + $ntf->addAdditionalInfo("survey_360_appraisee", ilUserUtil::getNamePresentation($a_appraisee_id, false, false, "", true)); + + // #10044 + $mail = new ilMail(ANONYMOUS_USER_ID); + //$mail->enableSOAP(false); // #10410 + $mail->sendMail( + ilObjUser::_lookupLogin($a_user_id), + null, + null, + $subject, + $ntf->composeAndGetMessage($a_user_id, null, "read", true), + null, + array("system") + ); + } + + public function isAppraisee($a_user_id) + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT user_id" . + " FROM svy_360_appr" . + " WHERE obj_id = " . $ilDB->quote($this->getSurveyId(), "integer") . + " AND user_id = " . $ilDB->quote($a_user_id, "integer")); + return (bool) $ilDB->numRows($set); + } + + public function isAppraiseeClosed($a_user_id) + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT has_closed" . + " FROM svy_360_appr" . + " WHERE obj_id = " . $ilDB->quote($this->getSurveyId(), "integer") . + " AND user_id = " . $ilDB->quote($a_user_id, "integer")); + $row = $ilDB->fetchAssoc($set); + return $row["has_closed"]; + } + + public function deleteAppraisee($a_user_id) + { + $ilDB = $this->db; + + $ilDB->manipulate("DELETE FROM svy_360_appr" . + " WHERE obj_id = " . $ilDB->quote($this->getSurveyId(), "integer") . + " AND user_id = " . $ilDB->quote($a_user_id, "integer")); + + $set = $ilDB->query("SELECT user_id" . + " FROM svy_360_rater" . + " WHERE obj_id = " . $ilDB->quote($this->getSurveyId(), "integer") . + " AND appr_id = " . $ilDB->quote($a_user_id, "integer")); + while ($row = $ilDB->fetchAssoc($set)) { + $this->deleteRater($a_user_id, $row["user_id"]); + } + // appraisee will not be part of raters table + if ($this->get360SelfEvaluation()) { + $this->deleteRater($a_user_id, $a_user_id); + } + } + + public function getAppraiseesData() + { + $ilDB = $this->db; + + $res = array(); + + $set = $ilDB->query("SELECT * FROM svy_360_appr" . + " WHERE obj_id = " . $ilDB->quote($this->getSurveyId(), "integer")); + while ($row = $ilDB->fetchAssoc($set)) { + $name = ilObjUser::_lookupName($row["user_id"]); + $name["email"] = ilObjUser::_lookupEmail($row["user_id"]); + $name["name"] = $name["lastname"] . ", " . $name["firstname"]; + $res[$row["user_id"]] = $name; + + $finished = 0; + $raters = $this->getRatersData($row["user_id"]); + foreach ($raters as $rater) { + if ($rater["finished"]) { + $finished++; + } + } + $res[$row["user_id"]]["finished"] = $finished . "/" . sizeof($raters); + $res[$row["user_id"]]["closed"] = $row["has_closed"]; + } + + return $res; + } + + public function addRater($a_appraisee_id, $a_user_id, $a_anonymous_id = 0) + { + global $DIC; + + $ilDB = $DIC->database(); + $access = $DIC->access(); + + if ($this->isAppraisee($a_appraisee_id) && + !$this->isRater($a_appraisee_id, $a_user_id, $a_anonymous_id)) { + $fields = array( + "obj_id" => array("integer", $this->getSurveyId()), + "appr_id" => array("integer", $a_appraisee_id), + "user_id" => array("integer", $a_user_id), + "anonymous_id" => array("integer", $a_anonymous_id) + ); + $ilDB->insert("svy_360_rater", $fields); + + // send notification and add to desktop + if ($access->checkAccessOfUser($a_user_id, "read", "", $this->getRefId())) { + $this->sendRaterNotification($a_user_id, $a_appraisee_id); + $type = ilObject::_lookupType($this->getRefId(), true); + ilObjUser::_addDesktopItem($a_user_id, $this->getRefId(), $type); + } + } + } + + public function isRater($a_appraisee_id, $a_user_id, $a_anonymous_id = 0) + { + $ilDB = $this->db; + + // user is rater if already appraisee and active self-evaluation + if ($this->isAppraisee($a_user_id) && + $this->get360SelfEvaluation() && + (!$a_appraisee_id || $a_appraisee_id == $a_user_id)) { + return true; + } + + // :TODO: should we get rid of code as well? + + $sql = "SELECT user_id" . + " FROM svy_360_rater" . + " WHERE obj_id = " . $ilDB->quote($this->getSurveyId(), "integer") . + " AND user_id = " . $ilDB->quote($a_user_id, "integer") . + " AND anonymous_id = " . $ilDB->quote($a_anonymous_id, "integer"); + if ($a_appraisee_id) { + $sql .= " AND appr_id = " . $ilDB->quote($a_appraisee_id, "integer"); + } + $set = $ilDB->query($sql); + return (bool) $ilDB->numRows($set); + } + + public function deleteRater($a_appraisee_id, $a_user_id, $a_anonymous_id = 0) + { + $ilDB = $this->db; + + $finished_id = $this->getFinishedIdForAppraiseeIdAndRaterId($a_appraisee_id, $a_user_id); + if ($finished_id) { + $this->removeSelectedSurveyResults(array($finished_id)); + } + + $ilDB->manipulate("DELETE FROM svy_360_rater" . + " WHERE obj_id = " . $ilDB->quote($this->getSurveyId(), "integer") . + " AND appr_id = " . $ilDB->quote($a_appraisee_id, "integer") . + " AND user_id = " . $ilDB->quote($a_user_id, "integer") . + " AND anonymous_id = " . $ilDB->quote($a_anonymous_id, "integer")); + } + + public function getRatersData($a_appraisee_id) + { + $ilDB = $this->db; + + $res = $anonymous_ids = array(); + + $set = $ilDB->query("SELECT * FROM svy_360_rater" . + " WHERE obj_id = " . $ilDB->quote($this->getSurveyId(), "integer") . + " AND appr_id = " . $ilDB->quote($a_appraisee_id, "integer")); + while ($row = $ilDB->fetchAssoc($set)) { + if ($row["anonymous_id"]) { + $res["a" . $row["anonymous_id"]] = array( + "lastname" => "unknown code " . $row["anonymous_id"], + "sent" => $row["mail_sent"], + "finished" => null + ); + $anonymous_ids[] = $row["anonymous_id"]; + } else { + $name = ilObjUser::_lookupName($row["user_id"]); + $name["name"] = $name["lastname"] . ", " . $name["firstname"]; + $name["user_id"] = "u" . $name["user_id"]; + $name["email"] = ilObjUser::_lookupEmail($row["user_id"]); + $name["sent"] = $row["mail_sent"]; + $name["finished"] = (bool) $this->is360SurveyStarted($a_appraisee_id, $row["user_id"]); + $res["u" . $row["user_id"]] = $name; + } + } + + if (sizeof($anonymous_ids)) { + $data = $this->getSurveyCodesTableData($anonymous_ids); + foreach ($data as $item) { + if (isset($res["a" . $item["id"]])) { + $res["a" . $item["id"]] = array( + "user_id" => "a" . $item["id"], + "lastname" => $item["last_name"], + "firstname" => $item["first_name"], + "name" => $item["last_name"] . ", " . $item["first_name"], + "login" => "", + "email" => $item["email"], + "code" => $item["code"], + "href" => $item["href"], + "sent" => $res["a" . $item["id"]]["sent"], + "finished" => (bool) $this->is360SurveyStarted($a_appraisee_id, null, $item["code"]) + ); + } + } + } + + return $res; + } + + public function getAppraiseesToRate($a_user_id, $a_anonymous_id = null) + { + $ilDB = $this->db; + + $res = array(); + + $sql = "SELECT appr_id FROM svy_360_rater" . + " WHERE obj_id = " . $ilDB->quote($this->getSurveyId(), "integer"); + + if ($a_user_id) { + $sql .= " AND user_id = " . $ilDB->quote($a_user_id, "integer"); + } else { + $sql .= " AND anonymous_id = " . $ilDB->quote($a_anonymous_id, "integer"); + } + + $set = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($set)) { + $res[] = $row["appr_id"]; + } + + // user may evaluate himself if already appraisee + if ($this->get360SelfEvaluation() && + $this->isAppraisee($a_user_id) && + !in_array($a_user_id, $res)) { + $res[] = $a_user_id; + } + + return $res; + } + + public function getAnonymousIdByCode($a_code) + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT anonymous_id FROM svy_anonymous" . + " WHERE survey_fi = " . $ilDB->quote($this->getSurveyId(), "integer") . + " AND survey_key = " . $ilDB->quote($a_code, "text")); + $res = $ilDB->fetchAssoc($set); + return $res["anonymous_id"]; + } + + public function is360SurveyStarted($appr_id, $user_id, $anonymous_code = null) + { + $ilDB = $this->db; + + $sql = "SELECT * FROM svy_finished" . + " WHERE survey_fi =" . $ilDB->quote($this->getSurveyId(), "integer") . + " AND appr_id = " . $ilDB->quote($appr_id, "integer"); + if ($user_id) { + $sql .= " AND user_fi = " . $ilDB->quote($user_id, "integer"); + } else { + $sql .= " AND anonymous_id = " . $ilDB->quote($anonymous_code, "text"); + } + $result = $ilDB->query($sql); + if ($result->numRows() == 0) { + return false; + } else { + $row = $ilDB->fetchAssoc($result); + return (int) $row["state"]; + } + } + + public function getUserSurveyExecutionStatus($a_code = null) + { + $ilUser = $this->user; + $ilDB = $this->db; + + $user_id = $ilUser->getId(); + + // code is obligatory? + if (!$this->isAccessibleWithoutCode()) { + if (!$a_code) { + // registered raters do not need code + if ($this->get360Mode() && + $user_id != ANONYMOUS_USER_ID && + $this->isRater(0, $user_id)) { + // auto-generate code + $a_code = $this->createNewAccessCode(); + $this->saveUserAccessCode($user_id, $a_code); + } else { + return null; + } + } + } elseif ($user_id == ANONYMOUS_USER_ID || + $this->getAnonymize() == self::ANONYMIZE_FREEACCESS) { + if (!$a_code) { + // auto-generate code + $a_code = $this->createNewAccessCode(); + $this->saveUserAccessCode($user_id, $a_code); + } + } else { + $a_code = null; + } + + $res = array(); + + $sql = "SELECT * FROM svy_finished" . + " WHERE survey_fi = " . $ilDB->quote($this->getSurveyId(), "integer"); + // if proper user id is given, use it or current code + if ($user_id != ANONYMOUS_USER_ID) { + $sql .= " AND (user_fi = " . $ilDB->quote($user_id, "integer") . + " OR anonymous_id = " . $ilDB->quote($a_code, "text") . ")"; + } + // use anonymous code to find finished id(s) + else { + $sql .= " AND anonymous_id = " . $ilDB->quote($a_code, "text"); + } + $set = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($set)) { + $res[$row["finished_id"]] = array("appr_id" => $row["appr_id"], + "user_id" => $row["user_fi"], + "code" => $row["anonymous_id"], + "finished" => (bool) $row["state"]); + } + + return array("code"=>$a_code, "runs"=>$res); + } + + public function findCodeForUser($a_user_id) + { + $ilDB = $this->db; + + if ($a_user_id != ANONYMOUS_USER_ID) { + $set = $ilDB->query("SELECT sf.anonymous_id FROM svy_finished sf" . + " WHERE sf.survey_fi = " . $ilDB->quote($this->getSurveyId(), "integer") . + " AND sf.user_fi = " . $ilDB->quote($a_user_id, "integer")); + $a_code = $ilDB->fetchAssoc($set); + return $a_code["anonymous_id"]; + } + } + + public function isUnusedCode($a_code, $a_user_id) + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT user_fi FROM svy_finished" . + " WHERE survey_fi = " . $ilDB->quote($this->getSurveyId(), "integer") . + " AND anonymous_id = " . $ilDB->quote($a_code, "text")); + $user_id = $ilDB->fetchAssoc($set); + $user_id = $user_id["user_fi"]; + + if ($user_id && ($user_id != $a_user_id || $user_id == ANONYMOUS_USER_ID)) { + return false; + } + return true; + } + + public function getFinishedIdsForAppraiseeId($a_appr_id, $a_exclude_appraisee = false) + { + $ilDB = $this->db; + + $res = array(); + + $set = $ilDB->query("SELECT finished_id, user_fi FROM svy_finished" . + " WHERE survey_fi = " . $ilDB->quote($this->getSurveyId(), "integer") . + " AND appr_id = " . $ilDB->quote($a_appr_id, "integer")); + while ($row = $ilDB->fetchAssoc($set)) { + if ($a_exclude_appraisee && $row["user_fi"] == $a_appr_id) { + continue; + } + $res[] = $row["finished_id"]; + } + + return $res; + } + + /** + * Get finished id for an appraisee and a rater + * + * @param int $a_appraisee_id appraisee id + * @param int $a_rater_id rater id + * @return int finished id + */ + public function getFinishedIdForAppraiseeIdAndRaterId($a_appr_id, $a_rat_id) + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT finished_id, user_fi FROM svy_finished" . + " WHERE survey_fi = " . $ilDB->quote($this->getSurveyId(), "integer") . + " AND appr_id = " . $ilDB->quote($a_appr_id, "integer") . + " AND user_fi = " . $ilDB->quote($a_rat_id, "integer")); + $row = $ilDB->fetchAssoc($set); + return $row["finished_id"]; + } + + + // 360° using competence/skill service + + /** + * Set skill service + * + * @param bool $a_val activate skill service + */ + public function setSkillService($a_val) + { + $this->mode_skill_service = $a_val; + } + + /** + * Get skill service + * + * @return bool activate skill service + */ + public function getSkillService() + { + return $this->mode_skill_service; + } + + public function set360RaterSent($a_appraisee_id, $a_user_id, $a_anonymous_id, $a_tstamp = null) + { + $ilDB = $this->db; + + if (!$a_tstamp) { + $a_tstamp = time(); + } + + $ilDB->manipulate("UPDATE svy_360_rater" . + " SET mail_sent = " . $ilDB->quote($a_tstamp, "integer") . + " WHERE obj_id = " . $ilDB->quote($this->getSurveyId(), "integer") . + " AND appr_id = " . $ilDB->quote($a_appraisee_id, "integer") . + " AND user_id = " . $ilDB->quote($a_user_id, "integer") . + " AND anonymous_id = " . $ilDB->quote($a_anonymous_id, "integer")); + } + + public function closeAppraisee($a_user_id) + { + global $DIC; + + $ilDB = $DIC->database(); + $user = $DIC->user(); + + // close the appraisee + $ilDB->manipulate("UPDATE svy_360_appr" . + " SET has_closed = " . $ilDB->quote(time(), "integer") . + " WHERE obj_id = " . $ilDB->quote($this->getSurveyId(), "integer") . + " AND user_id = " . $ilDB->quote($a_user_id, "integer")); + + // write competences + include_once("./Services/Skill/classes/class.ilSkillManagementSettings.php"); + $skmg_set = new ilSkillManagementSettings(); + if ($this->getSkillService() && $skmg_set->isActivated()) { + include_once("./Modules/Survey/classes/class.ilSurveySkill.php"); + $sskill = new ilSurveySkill($this); + $sskill->writeAppraiseeSkills($a_user_id); + } + + // send notification + if ($user->getId() != $a_user_id) { + $this->sendAppraiseeCloseNotification($a_user_id); + } + } + + public function openAllAppraisees() + { + $ilDB = $this->db; + + $ilDB->manipulate("UPDATE svy_360_appr" . + " SET has_closed = " . $ilDB->quote(null, "integer") . + " WHERE obj_id = " . $ilDB->quote($this->getSurveyId(), "integer")); + } + + public static function validateExternalRaterCode($a_ref_id, $a_code) + { + if (!isset($_SESSION["360_extrtr"][$a_ref_id])) { + $svy = new self($a_ref_id); + $svy->loadFromDB(); + + if ($svy->canStartSurvey(null, true) && + $svy->get360Mode() && + $svy->isAnonymousKey($a_code)) { + $anonymous_id = $svy->getAnonymousIdByCode($a_code); + if ($anonymous_id) { + if (sizeof($svy->getAppraiseesToRate(null, $anonymous_id))) { + $_SESSION["360_extrtr"][$a_ref_id] = true; + return true; + } + } + } + + $_SESSION["360_extrtr"][$a_ref_id] = false; + return false; + } + + return $_SESSION["360_extrtr"][$a_ref_id]; + } + + + // + // reminder/notification + // + + public function getReminderStatus() + { + return (bool) $this->reminder_status; + } + + public function setReminderStatus($a_value) + { + $this->reminder_status = (bool) $a_value; + } + + public function getReminderStart() + { + return $this->reminder_start; + } + + public function setReminderStart(ilDate $a_value = null) + { + $this->reminder_start = $a_value; + } + + public function getReminderEnd() + { + return $this->reminder_end; + } + + public function setReminderEnd(ilDate $a_value = null) + { + $this->reminder_end = $a_value; + } + + public function getReminderFrequency() + { + return $this->reminder_frequency; + } + + public function setReminderFrequency($a_value) + { + $this->reminder_frequency = (int) $a_value; + } + + public function getReminderTarget() + { + return $this->reminder_target; + } + + public function setReminderTarget($a_value) + { + $this->reminder_target = (int) $a_value; + } + + public function getReminderLastSent() + { + return $this->reminder_last_sent; + } + + public function setReminderLastSent($a_value) + { + $this->reminder_last_sent = $a_value; + } + + /** + * @param bool $selectDefault + * @return mixed + */ + public function getReminderTemplate($selectDefault = false) + { + if ($selectDefault) { + $defaultTemplateId = 0; + $this->getReminderMailTemplates($defaultTemplateId); + + if ($defaultTemplateId > 0) { + return $defaultTemplateId; + } + } + + return $this->reminder_tmpl; + } + + public function setReminderTemplate($a_value) + { + $this->reminder_tmpl = $a_value; + } + + public function getTutorNotificationStatus() + { + return (bool) $this->tutor_ntf_status; + } + + public function setTutorNotificationStatus($a_value) + { + $this->tutor_ntf_status = (bool) $a_value; + } + + public function getTutorNotificationRecipients() + { + return $this->tutor_ntf_recipients; + } + + public function setTutorNotificationRecipients(array $a_value) + { + $this->tutor_ntf_recipients = $a_value; + } + + public function getTutorNotificationTarget() + { + return $this->tutor_ntf_target; + } + + public function setTutorNotificationTarget($a_value) + { + $this->tutor_ntf_target = (int) $a_value; + } + + protected function checkTutorNotification() + { + $ilDB = $this->db; + + if ($this->getTutorNotificationStatus()) { + $user_ids = $this->getNotificationTargetUserIds(($this->getTutorNotificationTarget() == self::NOTIFICATION_INVITED_USERS)); + if ($user_ids) { + $set = $ilDB->query("SELECT COUNT(*) numall FROM svy_finished" . + " WHERE survey_fi = " . $ilDB->quote($this->getSurveyId(), "integer") . + " AND state = " . $ilDB->quote(1, "integer") . + " AND " . $ilDB->in("user_fi", $user_ids, "", "integer")); + $row = $ilDB->fetchAssoc($set); + if ($row["numall"] == sizeof($user_ids)) { + $this->sendTutorNotification(); + } + } + } + } + + /** + * Send 360 reminders + * + * @param + * @return + */ + public function sent360Reminders() + { + global $DIC; + + $access = $DIC->access(); + + // collect all open ratings + $rater_ids = array(); + foreach ($this->getAppraiseesData() as $app) { + $this->log->debug("Handle appraisee " . $app['user_id']); + + if (!$this->isAppraiseeClosed($app['user_id'])) { + $this->log->debug("Check self evaluation, self: " . $this->get360SelfAppraisee() . ", target: " . $this->getReminderTarget()); + + // self evaluation? + if ($this->get360SelfEvaluation() && + in_array($this->getReminderTarget(), array(ilObjSurvey::NOTIFICATION_APPRAISEES, ilObjSurvey::NOTIFICATION_APPRAISEES_AND_RATERS))) { + $this->log->debug("...1"); + // did user already finished self evaluation? + if (!$this->is360SurveyStarted($app['user_id'], $app['user_id'])) { + $this->log->debug("...2"); + if (!is_array($rater_ids[$app['user_id']])) { + $rater_ids[$app['user_id']] = array(); + } + if (!in_array($app["user_id"], $rater_ids[$app['user_id']])) { + $rater_ids[$app['user_id']][] = $app["user_id"]; + } + } + } + + $this->log->debug("Check raters."); + + // should raters be notified? + if (in_array($this->getReminderTarget(), array(ilObjSurvey::NOTIFICATION_RATERS, ilObjSurvey::NOTIFICATION_APPRAISEES_AND_RATERS))) { + foreach ($this->getRatersData($app['user_id']) as $rater) { + // is rater not anonymous and did not rate yet? + if (!$rater["anonymous_id"] && !$rater["finished"]) { + if (!is_array($rater_ids[$rater["user_id"]])) { + $rater_ids[$rater["user_id"]] = array(); + } + if (!in_array($app["user_id"], $rater_ids[$rater["user_id"]])) { + $rater_ids[$rater["user_id"]][] = $app["user_id"]; + } + } + } + } + } + } + + $this->log->debug("Found raters:" . count($rater_ids)); + + foreach ($rater_ids as $id => $app) { + if ($access->checkAccessOfUser($id, "read", "", $this->getRefId())) { + $this->send360ReminderToUser($id, $app); + } + } + } + + /** + * Send rater notification + * + * @param int $a_user_id user id + */ + public function send360ReminderToUser($a_user_id, $a_appraisee_ids) + { + $this->log->debug("Send mail to:" . $a_user_id); + + include_once "./Services/Notification/classes/class.ilSystemNotification.php"; + $ntf = new ilSystemNotification(); + $ntf->setLangModules(array("svy", "survey")); + $ntf->setRefId($this->getRefId()); + $ntf->setGotoLangId('url'); + + // user specific language + $lng = $ntf->getUserLanguage($a_user_id); + + $ntf->setIntroductionLangId("svy_user_added_360_rater_reminder_mail"); + $subject = str_replace("%1", $this->getTitle(), $lng->txt("svy_user_added_360_rater")); + + foreach ($a_appraisee_ids as $appraisee_id) { + $ntf->addAdditionalInfo("survey_360_appraisee", ilUserUtil::getNamePresentation($appraisee_id, false, false, "", true)); + } + + // #10044 + $mail = new ilMail(ANONYMOUS_USER_ID); + $mail->enableSOAP(false); // #10410 + $mail->sendMail( + ilObjUser::_lookupLogin($a_user_id), + null, + null, + $subject, + $ntf->composeAndGetMessage($a_user_id, null, "read", true), + null, + array("system") + ); + } + + + public function getNotificationTargetUserIds($a_use_invited) + { + $tree = $this->tree; + + if ((bool) $a_use_invited) { + $user_ids = $this->getInvitedUsers(); + } else { + $parent_grp_ref_id = $tree->checkForParentType($this->getRefId(), "grp"); + if ($parent_grp_ref_id) { + include_once "Modules/Group/classes/class.ilGroupParticipants.php"; + $part = new ilGroupParticipants(ilObject::_lookupObjId($parent_grp_ref_id)); + $user_ids = $part->getMembers(); + } else { + $parent_crs_ref_id = $tree->checkForParentType($this->getRefId(), "crs"); + if ($parent_crs_ref_id) { + include_once "Modules/Course/classes/class.ilCourseParticipants.php"; + $part = new ilCourseParticipants(ilObject::_lookupObjId($parent_crs_ref_id)); + $user_ids = $part->getMembers(); + } + } + } + return $user_ids; + } + + protected function sendTutorNotification() + { + include_once "./Services/Mail/classes/class.ilMail.php"; + include_once "./Services/User/classes/class.ilObjUser.php"; + include_once "./Services/Language/classes/class.ilLanguageFactory.php"; + include_once "./Services/User/classes/class.ilUserUtil.php"; + include_once "./Services/Link/classes/class.ilLink.php"; + $link = ilLink::_getStaticLink($this->getRefId(), "svy"); + + foreach ($this->getTutorNotificationRecipients() as $user_id) { + // use language of recipient to compose message + $ulng = ilLanguageFactory::_getLanguageOfUser($user_id); + $ulng->loadLanguageModule('survey'); + + $subject = sprintf($ulng->txt('survey_notification_tutor_subject'), $this->getTitle()); + $message = sprintf($ulng->txt('survey_notification_tutor_salutation'), ilObjUser::_lookupFullname($user_id)) . "\n\n"; + + $message .= $ulng->txt('survey_notification_tutor_body') . ":\n\n"; + $message .= $ulng->txt('obj_svy') . ": " . $this->getTitle() . "\n"; + $message .= "\n" . $ulng->txt('survey_notification_tutor_link') . ": " . $link; + + $mail_obj = new ilMail(ANONYMOUS_USER_ID); + $mail_obj->appendInstallationSignature(true); + $mail_obj->sendMail( + ilObjUser::_lookupLogin($user_id), + "", + "", + $subject, + $message, + array(), + array("system") + ); + } + } + + public function checkReminder() + { + $ilDB = $this->db; + $ilAccess = $this->access; + + $now = time(); + $now_with_format = date("YmdHis", $now); + $today = date("Y-m-d"); + + $this->log->debug("Check status and dates."); + + // object settings / participation period + if ( + $this->getOfflineStatus() || + !$this->getReminderStatus() || + ($this->getStartDate() && $now_with_format < $this->getStartDate()) || + ($this->getEndDate() && $now_with_format > $this->getEndDate())) { + return false; + } + + // reminder period + $start = $this->getReminderStart(); + if ($start) { + $start = $start->get(IL_CAL_DATE); + } + $end = $this->getReminderEnd(); + if ($end) { + $end = $end->get(IL_CAL_DATE); + } + if ($today < $start || + ($end && $today > $end)) { + return false; + } + + $this->log->debug("Check access period."); + + // object access period + include_once "Services/Object/classes/class.ilObjectActivation.php"; + $item_data = ilObjectActivation::getItem($this->getRefId()); + if ($item_data["timing_type"] == ilObjectActivation::TIMINGS_ACTIVATION && + ($now < $item_data["timing_start"] || + $now > $item_data["timing_end"])) { + return false; + } + + $this->log->debug("Check frequency."); + + // check frequency + $cut = new ilDate($today, IL_CAL_DATE); + $cut->increment(IL_CAL_DAY, $this->getReminderFrequency()*-1); + if (!$this->getReminderLastSent() || + $cut->get(IL_CAL_DATE) >= substr($this->getReminderLastSent(), 0, 10)) { + $missing_ids = array(); + + if (!$this->get360Mode()) { + $this->log->debug("Entering survey mode."); + + // #16871 + $user_ids = $this->getNotificationTargetUserIds(($this->getReminderTarget() == self::NOTIFICATION_INVITED_USERS)); + if ($user_ids) { + // gather participants who already finished + $finished_ids = array(); + $set = $ilDB->query("SELECT user_fi FROM svy_finished" . + " WHERE survey_fi = " . $ilDB->quote($this->getSurveyId(), "integer") . + " AND state = " . $ilDB->quote(1, "text") . + " AND " . $ilDB->in("user_fi", $user_ids, "", "integer")); + while ($row = $ilDB->fetchAssoc($set)) { + $finished_ids[] = $row["user_fi"]; + } + + // some users missing out? + $missing_ids = array_diff($user_ids, $finished_ids); + if ($missing_ids) { + foreach ($missing_ids as $idx => $user_id) { + // should be able to participate + if (!$ilAccess->checkAccessOfUser($user_id, "read", "", $this->getRefId(), "svy", $this->getId())) { + unset($missing_ids[$idx]); + } + } + } + if ($missing_ids) { + $this->sentReminder($missing_ids); + } + } + } else { + $this->log->debug("Entering 360 mode."); + + $this->sent360Reminders(); + } + + + $this->setReminderLastSent($today); + $this->saveToDb(); + + return sizeof($missing_ids); + } + + return false; + } + + protected function sentReminder(array $a_recipient_ids) + { + global $DIC; + + // use mail template + if ($this->getReminderTemplate() && + array_key_exists($this->getReminderTemplate(), $this->getReminderMailTemplates())) { + /** @var \ilMailTemplateService $templateService */ + $templateService = $DIC['mail.texttemplates.service']; + $tmpl = $templateService->loadTemplateForId((int) $this->getReminderTemplate()); + + $tmpl_params = array( + "ref_id" => $this->getRefId(), + "ts" => time() + ); + } else { + $tmpl = null; + + include_once "./Services/Link/classes/class.ilLink.php"; + $link = ilLink::_getStaticLink($this->getRefId(), "svy"); + + include_once "./Services/Language/classes/class.ilLanguageFactory.php"; + } + + foreach ($a_recipient_ids as $user_id) { + if ($tmpl) { + $subject = $tmpl->getSubject(); + $message = $this->sentReminderPlaceholders($tmpl->getMessage(), $user_id, $tmpl_params); + } + // use lng + else { + // use language of recipient to compose message + $ulng = ilLanguageFactory::_getLanguageOfUser($user_id); + $ulng->loadLanguageModule('survey'); + + $subject = sprintf($ulng->txt('survey_reminder_subject'), $this->getTitle()); + $message = sprintf($ulng->txt('survey_reminder_salutation'), ilObjUser::_lookupFullname($user_id)) . "\n\n"; + + $message .= $ulng->txt('survey_reminder_body') . ":\n\n"; + $message .= $ulng->txt('obj_svy') . ": " . $this->getTitle() . "\n"; + $message .= "\n" . $ulng->txt('survey_reminder_link') . ": " . $link; + } + + $mail_obj = new ilMail(ANONYMOUS_USER_ID); + $mail_obj->appendInstallationSignature(true); + $mail_obj->sendMail( + ilObjUser::_lookupLogin($user_id), + "", + "", + $subject, + $message, + array(), + array("system") + ); + } + } + + public function setActivationStartDate($starting_time = null) + { + $this->activation_starting_time = $starting_time; + } + + public function setActivationEndDate($ending_time = null) + { + $this->activation_ending_time = $ending_time; + } + + public function getActivationStartDate() + { + return (strlen($this->activation_starting_time)) ? $this->activation_starting_time : null; + } + + public function getActivationEndDate() + { + return (strlen($this->activation_ending_time)) ? $this->activation_ending_time : null; + } + + public function setViewOwnResults($a_value) + { + $this->view_own_results = (bool) $a_value; + } + + public function hasViewOwnResults() + { + return $this->view_own_results; + } + + public function setMailOwnResults($a_value) + { + $this->mail_own_results = (bool) $a_value; + } + + public function hasMailOwnResults() + { + return $this->mail_own_results; + } + + public function setMailConfirmation($a_value) + { + $this->mail_confirmation = (bool) $a_value; + } + + public function hasMailConfirmation() + { + return $this->mail_confirmation; + } + + public function setAnonymousUserList($a_value) + { + $this->anon_user_list = (bool) $a_value; + } + + public function hasAnonymousUserList() + { + return $this->anon_user_list; + } + + public static function getSurveySkippedValue() + { + global $DIC; + + $lng = $DIC->language(); + + // #13541 + + include_once "./Services/Administration/classes/class.ilSetting.php"; + $surveySetting = new ilSetting("survey"); + if (!$surveySetting->get("skipped_is_custom", false)) { + return $lng->txt("skipped"); + } else { + return $surveySetting->get("skipped_custom_value", ""); + } + } + + /** + * @param int $defaultTemplateId + * @return array + */ + public function getReminderMailTemplates(&$defaultTemplateId = null) + { + global $DIC; + + $res = array(); + + /** @var \ilMailTemplateService $templateService */ + $templateService = $DIC['mail.texttemplates.service']; + foreach ($templateService->loadTemplatesForContextId((string) ilSurveyMailTemplateReminderContext::ID) as $tmpl) { + $res[$tmpl->getTplId()] = $tmpl->getTitle(); + if (null !== $defaultTemplateId && $tmpl->isDefault()) { + $defaultTemplateId = $tmpl->getTplId(); + } + } + + return $res; + } + + protected function sentReminderPlaceholders($a_message, $a_user_id, array $a_context_params) + { + // see ilMail::replacePlaceholders() + try { + $context = \ilMailTemplateContextService::getTemplateContextById(ilSurveyMailTemplateReminderContext::ID); + + $user = new \ilObjUser($a_user_id); + + $processor = new \ilMailTemplatePlaceholderResolver($context, $a_message); + $a_message = $processor->resolve($user, \ilMailFormCall::getContextParameters()); + } catch (\Exception $e) { + ilLoggerFactory::getLogger('mail')->error(__METHOD__ . ' has been called with invalid context.'); + } + + return $a_message; + } + + public function setMode($a_value) + { + $this->mode = $a_value; + } + + public function getMode() + { + return $this->mode; + } + + public function setSelfEvaluationResults($a_value) + { + $this->mode_self_eval_results = $a_value; + } + + public function getSelfEvaluationResults() + { + return $this->mode_self_eval_results; + } } // END class.ilObjSurvey - -?> \ No newline at end of file diff --git a/Modules/Survey/classes/class.ilObjSurveyAccess.php b/Modules/Survey/classes/class.ilObjSurveyAccess.php index 1f45d22405ceaace09c66bd937f24b45d13a7704..b1a3af1e2e4211444a87a2fbfd2ad47d4fd0f508 100644 --- a/Modules/Survey/classes/class.ilObjSurveyAccess.php +++ b/Modules/Survey/classes/class.ilObjSurveyAccess.php @@ -1,24 +1,24 @@ user = $DIC->user(); - $this->lng = $DIC->language(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->access = $DIC->access(); - } - - - /** - * Get possible conditions operators - */ - public static function getConditionOperators() - { - include_once './Services/Conditions/classes/class.ilConditionHandler.php'; - return array( - ilConditionHandler::OPERATOR_FINISHED - ); - } - - - /** - * check condition - * @param type $a_svy_id - * @param type $a_operator - * @param type $a_value - * @param type $a_usr_id - * @return boolean - */ - public static function checkCondition($a_svy_id,$a_operator,$a_value,$a_usr_id) - { - switch($a_operator) - { - case ilConditionHandler::OPERATOR_FINISHED: - include_once("./Modules/Survey/classes/class.ilObjSurveyAccess.php"); - if (ilObjSurveyAccess::_lookupFinished($a_svy_id, $a_usr_id)) - { - return true; - } - else - { - return false; - } - break; - - default: - return true; - } - return true; - } - - /** - * Checks wether a user may invoke a command or not - * (this method is called by ilAccessHandler::checkAccess) - * - * Please do not check any preconditions handled by - * ilConditionHandler here. - * - * @param string $a_cmd command (not permission!) - * @param string $a_permission permission - * @param int $a_ref_id reference id - * @param int $a_obj_id object id - * @param int $a_user_id user id (if not provided, current user is taken) - * - * @return boolean true, if everything is ok - */ - function _checkAccess($a_cmd, $a_permission, $a_ref_id, $a_obj_id, $a_user_id = "") - { - $ilUser = $this->user; - $lng = $this->lng; - $rbacsystem = $this->rbacsystem; - $ilAccess = $this->access; - - if ($a_user_id == "") - { - $a_user_id = $ilUser->getId(); - } - - $is_admin = $rbacsystem->checkAccessOfUser($a_user_id,'write',$a_ref_id); - - switch ($a_permission) - { - case "visible": - case "read": - if (!ilObjSurveyAccess::_lookupCreationComplete($a_obj_id) && - !$is_admin) - { - $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("warning_survey_not_complete")); - return false; - } - break; - } - - switch ($a_cmd) - { - case "run": - if(!ilObjSurveyAccess::_lookupCreationComplete($a_obj_id)) - { - $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("warning_survey_not_complete")); - return false; - } - break; - - case "evaluation": - if (!ilObjSurveyAccess::_lookupCreationComplete($a_obj_id)) - { - $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("warning_survey_not_complete")); - return false; - } - if ($rbacsystem->checkAccess("write",$a_ref_id) || ilObjSurveyAccess::_hasEvaluationAccess($a_obj_id, $a_user_id)) - { - return true; - } - else - { - $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("status_no_permission")); - return false; - } - break; - } - - return true; - } - - - /** - * 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" => "infoScreen", "lang_var" => "svy_run", "default" => true), - array("permission" => "write", "cmd" => "questionsrepo", "lang_var" => "edit_questions"), - array("permission" => "write", "cmd" => "properties", "lang_var" => "settings"), - array("permission" => "read", "cmd" => "evaluation", "lang_var" => "svy_results") - ); - - return $commands; - } - - // - // object specific access related methods - // - - /** - * checks wether all necessary parts of the survey are given - */ - static function _lookupCreationComplete($a_obj_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $result = $ilDB->queryF("SELECT * FROM svy_svy WHERE obj_fi=%s", - array('integer'), - array($a_obj_id) - ); - - if ($result->numRows() == 1) - { - $row = $ilDB->fetchAssoc($result); - } - if (!$row["complete"]) - { - return false; - } - return true; - } - - /** - * get evaluation access - */ - static function _lookupEvaluationAccess($a_obj_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $result = $ilDB->queryF("SELECT * FROM svy_svy WHERE obj_fi=%s", - array('integer'), - array($a_obj_id) - ); - if ($result->numRows() == 1) - { - $row = $ilDB->fetchAssoc($result); - } - - return $row["evaluation_access"]; - } - - static function _isSurveyParticipant($user_id, $survey_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE user_fi = %s AND survey_fi = %s", - array('integer','integer'), - array($user_id, $survey_id) - ); - return ($result->numRows() == 1) ? true : false; - } - - static function _lookupAnonymize($a_obj_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $result = $ilDB->queryF("SELECT anonymize FROM svy_svy WHERE obj_fi = %s", - array('integer'), - array($a_obj_id) - ); - if ($result->numRows() == 1) - { - $row = $ilDB->fetchAssoc($result); - return $row["anonymize"]; - } - else - { - return 0; - } - } - - static function _hasEvaluationAccess($a_obj_id, $user_id) - { - $evaluation_access = ilObjSurveyAccess::_lookupEvaluationAccess($a_obj_id); - switch ($evaluation_access) - { - case 0: - // no evaluation access - return false; - break; - case 1: - // evaluation access for all registered users - if (($user_id > 0) && ($user_id != ANONYMOUS_USER_ID)) - { - return true; - } - else - { - return false; - } - break; - case 2: - $svy_mode = self::_lookupMode($a_obj_id); - switch($svy_mode) - { - case ilObjSurvey::MODE_360: - include_once "Modules/Survey/classes/class.ilObjSurvey.php"; - $svy = new ilObjSurvey($a_obj_id, false); - $svy->read(); - switch($svy->get360Results()) - { - case ilObjSurvey::RESULTS_360_NONE: - return false; - - case ilObjSurvey::RESULTS_360_OWN: - return $svy->isAppraiseeClosed($user_id); - - case ilObjSurvey::RESULTS_360_ALL: - return $svy->isAppraisee($user_id); - } - break; - - case ilObjSurvey::MODE_SELF_EVAL: - include_once "Modules/Survey/classes/class.ilObjSurvey.php"; - $svy = new ilObjSurvey($a_obj_id, false); - $svy->read(); - switch($svy->getSelfEvaluationResults()) - { - case ilObjSurvey::RESULTS_SELF_EVAL_NONE: - return false; - default: - return true; - } - break; - - default: - // evaluation access for participants - // check if the user with the given id is a survey participant - - // show the evaluation button for anonymized surveys for all users - // access is only granted with the survey access code - if (ilObjSurveyAccess::_lookupAnonymize($a_obj_id) == 1) return true; - - global $DIC; - - $ilDB = $DIC->database(); - $result = $ilDB->queryF("SELECT survey_id FROM svy_svy WHERE obj_fi = %s", - array('integer'), - array($a_obj_id) - ); - if ($result->numRows() == 1) - { - $row = $ilDB->fetchAssoc($result); - - if (ilObjSurveyAccess::_isSurveyParticipant($user_id, $row["survey_id"])) - { - return true; - } - } - return false; - break; - } - break; - } - } - - - /** - * get finished status - * - * @param int $a_obj_id survey id - */ - static function _lookupFinished($a_obj_id, $a_user_id = "") - { - global $DIC; - - $ilDB = $DIC->database(); - $ilUser = $DIC->user(); - - $finished = ""; - if (!strlen($a_user_id)) $a_user_id = $ilUser->getId(); - - $result = $ilDB->queryF("SELECT * FROM svy_svy WHERE obj_fi = %s", - array('integer'), - array($a_obj_id) - ); - if ($result->numRows() == 1) - { - $row = $ilDB->fetchObject($result); - if ($row->anonymize == 1) - { - $result = $ilDB->queryF("SELECT * FROM svy_finished, svy_anonymous WHERE svy_finished.survey_fi = %s ". - "AND svy_finished.survey_fi = svy_anonymous.survey_fi AND svy_anonymous.user_key = %s ". - "AND svy_anonymous.survey_key = svy_finished.anonymous_id", - array('integer','text'), - array($row->survey_id, md5($a_user_id)) - ); - } - else - { - $result = $ilDB->queryF("SELECT * FROM svy_finished WHERE survey_fi = %s AND user_fi = %s", - array('integer','integer'), - array($row->survey_id, $a_user_id) - ); - } - if ($result->numRows() == 1) - { - $foundrow = $ilDB->fetchAssoc($result); - $finished = (int)$foundrow["state"]; - } - } - - return $finished; - } - - /** - * Get survey mode. - * @param $a_obj_id - * @return int - */ - static function _lookupMode($a_obj_id) - { - global $DIC; - $ilDB = $DIC->database(); - - $result = $ilDB->queryF("SELECT mode FROM svy_svy". - " WHERE obj_fi = %s", - array('integer'), - array($a_obj_id) - ); - - if ($result->numRows() == 1) { - $row = $ilDB->fetchAssoc($result); - } - - return $row["mode"]; - } - - static function _lookup360Mode($a_obj_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $result = $ilDB->queryF("SELECT mode FROM svy_svy". - " WHERE obj_fi = %s AND mode = %s", - array('integer','integer'), - array($a_obj_id, ilObjSurvey::MODE_360) - ); - return (bool)$ilDB->numRows($result); - } - - /** - * check whether goto script will succeed - */ - static function _checkGoto($a_target) - { - global $DIC; - - $ilAccess = $DIC->access(); - - $t_arr = explode("_", $a_target); - - if ($t_arr[0] != "svy" || ((int) $t_arr[1]) <= 0) - { - return false; - } - - // 360° external raters - if ($_GET["accesscode"]) - { - include_once "Modules/Survey/classes/class.ilObjSurvey.php"; - if(ilObjSurvey::validateExternalRaterCode($t_arr[1], $_GET["accesscode"])) - { - return true; - } - } - - if ($ilAccess->checkAccess("visible", "", $t_arr[1]) || - $ilAccess->checkAccess("read", "", $t_arr[1])) - { - return true; - } - return false; - } + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilAccessHandler + */ + protected $access; + + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->user = $DIC->user(); + $this->lng = $DIC->language(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->access = $DIC->access(); + } + + + /** + * Get possible conditions operators + */ + public static function getConditionOperators() + { + include_once './Services/Conditions/classes/class.ilConditionHandler.php'; + return array( + ilConditionHandler::OPERATOR_FINISHED + ); + } + + + /** + * check condition + * @param type $a_svy_id + * @param type $a_operator + * @param type $a_value + * @param type $a_usr_id + * @return boolean + */ + public static function checkCondition($a_svy_id, $a_operator, $a_value, $a_usr_id) + { + switch ($a_operator) { + case ilConditionHandler::OPERATOR_FINISHED: + include_once("./Modules/Survey/classes/class.ilObjSurveyAccess.php"); + if (ilObjSurveyAccess::_lookupFinished($a_svy_id, $a_usr_id)) { + return true; + } else { + return false; + } + break; + + default: + return true; + } + return true; + } + + /** + * Checks wether a user may invoke a command or not + * (this method is called by ilAccessHandler::checkAccess) + * + * Please do not check any preconditions handled by + * ilConditionHandler here. + * + * @param string $a_cmd command (not permission!) + * @param string $a_permission permission + * @param int $a_ref_id reference id + * @param int $a_obj_id object id + * @param int $a_user_id user id (if not provided, current user is taken) + * + * @return boolean true, if everything is ok + */ + public function _checkAccess($a_cmd, $a_permission, $a_ref_id, $a_obj_id, $a_user_id = "") + { + $ilUser = $this->user; + $lng = $this->lng; + $rbacsystem = $this->rbacsystem; + $ilAccess = $this->access; + + if ($a_user_id == "") { + $a_user_id = $ilUser->getId(); + } + + $is_admin = $rbacsystem->checkAccessOfUser($a_user_id, 'write', $a_ref_id); + + switch ($a_permission) { + case "visible": + case "read": + if (!ilObjSurveyAccess::_lookupCreationComplete($a_obj_id) && + !$is_admin) { + $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("warning_survey_not_complete")); + return false; + } + break; + } + + switch ($a_cmd) { + case "run": + if (!ilObjSurveyAccess::_lookupCreationComplete($a_obj_id)) { + $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("warning_survey_not_complete")); + return false; + } + break; + + case "evaluation": + if (!ilObjSurveyAccess::_lookupCreationComplete($a_obj_id)) { + $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("warning_survey_not_complete")); + return false; + } + if ($rbacsystem->checkAccess("write", $a_ref_id) || ilObjSurveyAccess::_hasEvaluationAccess($a_obj_id, $a_user_id)) { + return true; + } else { + $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("status_no_permission")); + return false; + } + break; + } + + return true; + } + + + /** + * 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" => "infoScreen", "lang_var" => "svy_run", "default" => true), + array("permission" => "write", "cmd" => "questionsrepo", "lang_var" => "edit_questions"), + array("permission" => "write", "cmd" => "properties", "lang_var" => "settings"), + array("permission" => "read", "cmd" => "evaluation", "lang_var" => "svy_results") + ); + + return $commands; + } + + // + // object specific access related methods + // + + /** + * checks wether all necessary parts of the survey are given + */ + public static function _lookupCreationComplete($a_obj_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $result = $ilDB->queryF( + "SELECT * FROM svy_svy WHERE obj_fi=%s", + array('integer'), + array($a_obj_id) + ); + + if ($result->numRows() == 1) { + $row = $ilDB->fetchAssoc($result); + } + if (!$row["complete"]) { + return false; + } + return true; + } + + /** + * get evaluation access + */ + public static function _lookupEvaluationAccess($a_obj_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $result = $ilDB->queryF( + "SELECT * FROM svy_svy WHERE obj_fi=%s", + array('integer'), + array($a_obj_id) + ); + if ($result->numRows() == 1) { + $row = $ilDB->fetchAssoc($result); + } + + return $row["evaluation_access"]; + } + + public static function _isSurveyParticipant($user_id, $survey_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $result = $ilDB->queryF( + "SELECT finished_id FROM svy_finished WHERE user_fi = %s AND survey_fi = %s", + array('integer','integer'), + array($user_id, $survey_id) + ); + return ($result->numRows() == 1) ? true : false; + } + + public static function _lookupAnonymize($a_obj_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $result = $ilDB->queryF( + "SELECT anonymize FROM svy_svy WHERE obj_fi = %s", + array('integer'), + array($a_obj_id) + ); + if ($result->numRows() == 1) { + $row = $ilDB->fetchAssoc($result); + return $row["anonymize"]; + } else { + return 0; + } + } + + public static function _hasEvaluationAccess($a_obj_id, $user_id) + { + $evaluation_access = ilObjSurveyAccess::_lookupEvaluationAccess($a_obj_id); + switch ($evaluation_access) { + case 0: + // no evaluation access + return false; + break; + case 1: + // evaluation access for all registered users + if (($user_id > 0) && ($user_id != ANONYMOUS_USER_ID)) { + return true; + } else { + return false; + } + break; + case 2: + $svy_mode = self::_lookupMode($a_obj_id); + switch ($svy_mode) { + case ilObjSurvey::MODE_360: + include_once "Modules/Survey/classes/class.ilObjSurvey.php"; + $svy = new ilObjSurvey($a_obj_id, false); + $svy->read(); + switch ($svy->get360Results()) { + case ilObjSurvey::RESULTS_360_NONE: + return false; + + case ilObjSurvey::RESULTS_360_OWN: + return $svy->isAppraiseeClosed($user_id); + + case ilObjSurvey::RESULTS_360_ALL: + return $svy->isAppraisee($user_id); + } + break; + + case ilObjSurvey::MODE_SELF_EVAL: + include_once "Modules/Survey/classes/class.ilObjSurvey.php"; + $svy = new ilObjSurvey($a_obj_id, false); + $svy->read(); + switch ($svy->getSelfEvaluationResults()) { + case ilObjSurvey::RESULTS_SELF_EVAL_NONE: + return false; + default: + return true; + } + break; + + default: + // evaluation access for participants + // check if the user with the given id is a survey participant + + // show the evaluation button for anonymized surveys for all users + // access is only granted with the survey access code + if (ilObjSurveyAccess::_lookupAnonymize($a_obj_id) == 1) { + return true; + } + + global $DIC; + + $ilDB = $DIC->database(); + $result = $ilDB->queryF( + "SELECT survey_id FROM svy_svy WHERE obj_fi = %s", + array('integer'), + array($a_obj_id) + ); + if ($result->numRows() == 1) { + $row = $ilDB->fetchAssoc($result); + + if (ilObjSurveyAccess::_isSurveyParticipant($user_id, $row["survey_id"])) { + return true; + } + } + return false; + break; + } + break; + } + } + + + /** + * get finished status + * + * @param int $a_obj_id survey id + */ + public static function _lookupFinished($a_obj_id, $a_user_id = "") + { + global $DIC; + + $ilDB = $DIC->database(); + $ilUser = $DIC->user(); + + $finished = ""; + if (!strlen($a_user_id)) { + $a_user_id = $ilUser->getId(); + } + + $result = $ilDB->queryF( + "SELECT * FROM svy_svy WHERE obj_fi = %s", + array('integer'), + array($a_obj_id) + ); + if ($result->numRows() == 1) { + $row = $ilDB->fetchObject($result); + if ($row->anonymize == 1) { + $result = $ilDB->queryF( + "SELECT * FROM svy_finished, svy_anonymous WHERE svy_finished.survey_fi = %s " . + "AND svy_finished.survey_fi = svy_anonymous.survey_fi AND svy_anonymous.user_key = %s " . + "AND svy_anonymous.survey_key = svy_finished.anonymous_id", + array('integer','text'), + array($row->survey_id, md5($a_user_id)) + ); + } else { + $result = $ilDB->queryF( + "SELECT * FROM svy_finished WHERE survey_fi = %s AND user_fi = %s", + array('integer','integer'), + array($row->survey_id, $a_user_id) + ); + } + if ($result->numRows() == 1) { + $foundrow = $ilDB->fetchAssoc($result); + $finished = (int) $foundrow["state"]; + } + } + + return $finished; + } + + /** + * Get survey mode. + * @param $a_obj_id + * @return int + */ + public static function _lookupMode($a_obj_id) + { + global $DIC; + $ilDB = $DIC->database(); + + $result = $ilDB->queryF( + "SELECT mode FROM svy_svy" . + " WHERE obj_fi = %s", + array('integer'), + array($a_obj_id) + ); + + if ($result->numRows() == 1) { + $row = $ilDB->fetchAssoc($result); + } + + return $row["mode"]; + } + + public static function _lookup360Mode($a_obj_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $result = $ilDB->queryF( + "SELECT mode FROM svy_svy" . + " WHERE obj_fi = %s AND mode = %s", + array('integer','integer'), + array($a_obj_id, ilObjSurvey::MODE_360) + ); + return (bool) $ilDB->numRows($result); + } + + /** + * check whether goto script will succeed + */ + public static function _checkGoto($a_target) + { + global $DIC; + + $ilAccess = $DIC->access(); + + $t_arr = explode("_", $a_target); + + if ($t_arr[0] != "svy" || ((int) $t_arr[1]) <= 0) { + return false; + } + + // 360° external raters + if ($_GET["accesscode"]) { + include_once "Modules/Survey/classes/class.ilObjSurvey.php"; + if (ilObjSurvey::validateExternalRaterCode($t_arr[1], $_GET["accesscode"])) { + return true; + } + } + + if ($ilAccess->checkAccess("visible", "", $t_arr[1]) || + $ilAccess->checkAccess("read", "", $t_arr[1])) { + return true; + } + return false; + } } - -?> diff --git a/Modules/Survey/classes/class.ilObjSurveyAdministration.php b/Modules/Survey/classes/class.ilObjSurveyAdministration.php index 223bf6dd756e5552a0c57dd705aa81471855f993..7f315951887d11462abdf7b36554b8d44b2ccd6f 100644 --- a/Modules/Survey/classes/class.ilObjSurveyAdministration.php +++ b/Modules/Survey/classes/class.ilObjSurveyAdministration.php @@ -1,24 +1,24 @@ setting = new ilSetting("survey"); - $this->type = "svyf"; - parent::__construct($a_id,$a_call_by_reference); - } + public $setting; + + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + include_once "./Services/Administration/classes/class.ilSetting.php"; + $this->setting = new ilSetting("survey"); + $this->type = "svyf"; + parent::__construct($a_id, $a_call_by_reference); + } - /** - * update object data - * - * @access public - * @return boolean - */ - function update() - { - if (!parent::update()) - { - return false; - } + /** + * update object data + * + * @access public + * @return boolean + */ + public function update() + { + if (!parent::update()) { + return false; + } - // put here object specific stuff + // put here object specific stuff - return true; - } + return true; + } - /** - * delete object and all related data - * - * @access public - * @return boolean true if all object data were removed; false if only a references were removed - */ - function delete() - { - // always call parent delete function first!! - if (!parent::delete()) - { - return false; - } + /** + * delete object and all related data + * + * @access public + * @return boolean true if all object data were removed; false if only a references were removed + */ + public function delete() + { + // always call parent delete function first!! + if (!parent::delete()) { + return false; + } - //put here your module specific stuff + //put here your module specific stuff - return true; - } - - /* #7927: special users are deprecated - function addSpecialUsers($arr_user_id) - { - $surveySetting = new ilSetting("survey"); - $allowedUsers = strlen($surveySetting->get("multiple_survey_users")) ? explode(",",$surveySetting->get("multiple_survey_users")) : array(); - $arr = array_unique(array_merge($allowedUsers, $arr_user_id)); - $surveySetting->set("multiple_survey_users", implode(",", $arr)); - } - - function removeSpecialUsers($arr_user_id) - { - $surveySetting = new ilSetting("survey"); - $allowedUsers = strlen($surveySetting->get("multiple_survey_users")) ? explode(",",$surveySetting->get("multiple_survey_users")) : array(); - $arr = array_diff($allowedUsers, $arr_user_id); - $surveySetting->set("multiple_survey_users", implode(",", array_values($arr))); - } - - function getSpecialUsers() - { - $surveySetting = new ilSetting("survey"); - return strlen($surveySetting->get("multiple_survey_users")) ? explode(",",$surveySetting->get("multiple_survey_users")) : array(); - } - */ - + return true; + } + + /* #7927: special users are deprecated + function addSpecialUsers($arr_user_id) + { + $surveySetting = new ilSetting("survey"); + $allowedUsers = strlen($surveySetting->get("multiple_survey_users")) ? explode(",",$surveySetting->get("multiple_survey_users")) : array(); + $arr = array_unique(array_merge($allowedUsers, $arr_user_id)); + $surveySetting->set("multiple_survey_users", implode(",", $arr)); + } + + function removeSpecialUsers($arr_user_id) + { + $surveySetting = new ilSetting("survey"); + $allowedUsers = strlen($surveySetting->get("multiple_survey_users")) ? explode(",",$surveySetting->get("multiple_survey_users")) : array(); + $arr = array_diff($allowedUsers, $arr_user_id); + $surveySetting->set("multiple_survey_users", implode(",", array_values($arr))); + } + + function getSpecialUsers() + { + $surveySetting = new ilSetting("survey"); + return strlen($surveySetting->get("multiple_survey_users")) ? explode(",",$surveySetting->get("multiple_survey_users")) : array(); + } + */ } // END class.ilObjSurveyAdministration.php -?> diff --git a/Modules/Survey/classes/class.ilObjSurveyAdministrationAccess.php b/Modules/Survey/classes/class.ilObjSurveyAdministrationAccess.php index 084f139d0a2fab57f72e8f0e0d9639be0af1226f..9f59b5cad875640f4a99284f58440f4af6fed19c 100644 --- a/Modules/Survey/classes/class.ilObjSurveyAdministrationAccess.php +++ b/Modules/Survey/classes/class.ilObjSurveyAdministrationAccess.php @@ -1,24 +1,24 @@ * @version $Id$ * @ingroup ModulesSurvey -* +* * */ class ilObjSurveyAdministrationAccess extends ilObjectAccess { - - } - -?> diff --git a/Modules/Survey/classes/class.ilObjSurveyAdministrationGUI.php b/Modules/Survey/classes/class.ilObjSurveyAdministrationGUI.php index d3f93c638439d441f813cd9aa856a76ca4b8d4d1..72bfb5880d8d628a7392e5f71a3225dc0db939a1 100644 --- a/Modules/Survey/classes/class.ilObjSurveyAdministrationGUI.php +++ b/Modules/Survey/classes/class.ilObjSurveyAdministrationGUI.php @@ -1,24 +1,24 @@ * @version $Id$ -* +* * @ilCtrl_Calls ilObjSurveyAdministrationGUI: ilPermissionGUI, ilSettingsTemplateGUI * * @extends ilObjectGUI * @ingroup ModulesSurvey -* +* */ class ilObjSurveyAdministrationGUI extends ilObjectGUI { - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * Constructor - * @access public - */ - var $conditions; + /** + * @var ilTabsGUI + */ + protected $tabs; - function __construct($a_data,$a_id,$a_call_by_reference) - { - global $DIC; + /** + * Constructor + * @access public + */ + public $conditions; - $this->lng = $DIC->language(); - $this->tabs = $DIC->tabs(); - $this->tpl = $DIC["tpl"]; - $this->access = $DIC->access(); - $this->ctrl = $DIC->ctrl(); - $lng = $DIC->language(); + public function __construct($a_data, $a_id, $a_call_by_reference) + { + global $DIC; - $this->type = "svyf"; - $lng->loadLanguageModule("survey"); - parent::__construct($a_data,$a_id,$a_call_by_reference,false); - } - - function executeCommand() - { - $ilTabs = $this->tabs; + $this->lng = $DIC->language(); + $this->tabs = $DIC->tabs(); + $this->tpl = $DIC["tpl"]; + $this->access = $DIC->access(); + $this->ctrl = $DIC->ctrl(); + $lng = $DIC->language(); - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - $this->prepareOutput(); + $this->type = "svyf"; + $lng->loadLanguageModule("survey"); + parent::__construct($a_data, $a_id, $a_call_by_reference, false); + } + + public function executeCommand() + { + $ilTabs = $this->tabs; - switch($next_class) - { - case 'ilpermissiongui': - $ilTabs->activateTab("perm_settings"); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $ret =& $this->ctrl->forwardCommand($perm_gui); - break; + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + $this->prepareOutput(); - case 'ilsettingstemplategui': - $ilTabs->activateTab("templates"); - include_once("./Services/Administration/classes/class.ilSettingsTemplateGUI.php"); - $set_tpl_gui = new ilSettingsTemplateGUI($this->getSettingsTemplateConfig()); - $this->ctrl->forwardCommand($set_tpl_gui); - break; + switch ($next_class) { + case 'ilpermissiongui': + $ilTabs->activateTab("perm_settings"); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $ret =&$this->ctrl->forwardCommand($perm_gui); + break; - default: - if($cmd == "" || $cmd == "view") - { - $cmd = "settings"; - } - $cmd .= "Object"; - $this->$cmd(); + case 'ilsettingstemplategui': + $ilTabs->activateTab("templates"); + include_once("./Services/Administration/classes/class.ilSettingsTemplateGUI.php"); + $set_tpl_gui = new ilSettingsTemplateGUI($this->getSettingsTemplateConfig()); + $this->ctrl->forwardCommand($set_tpl_gui); + break; - break; - } - return true; - } + default: + if ($cmd == "" || $cmd == "view") { + $cmd = "settings"; + } + $cmd .= "Object"; + $this->$cmd(); + break; + } + return true; + } - /** - * display survey settings form - * - * Default settings tab for Survey settings - * - * @access public - */ - function settingsObject(ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - $ilTabs->activateTab("settings"); - - if(!$a_form) - { - $a_form = $this->initSettingsForm(); - } - - $tpl->setContent($a_form->getHTML()); - } - - protected function initSettingsForm() - { - $ilAccess = $this->access; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $surveySetting = new ilSetting("survey"); - $unlimited_invitation = array_key_exists("unlimited_invitation", $_GET) ? $_GET["unlimited_invitation"] : $surveySetting->get("unlimited_invitation"); - $use_anonymous_id = array_key_exists("use_anonymous_id", $_GET) ? $_GET["use_anonymous_id"] : $surveySetting->get("use_anonymous_id"); - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this)); - $form->setTitle($lng->txt("survey_defaults")); - - // unlimited invitation - $enable = new ilCheckboxInputGUI($lng->txt("survey_unlimited_invitation"), "unlimited_invitation"); - $enable->setChecked($unlimited_invitation); - $enable->setInfo($lng->txt("survey_unlimited_invitation_desc")); - $form->addItem($enable); - - // Survey Code - $code = new ilCheckboxInputGUI($lng->txt("use_anonymous_id"), "use_anonymous_id"); - $code->setChecked($use_anonymous_id); - $code->setInfo($lng->txt("use_anonymous_id_desc")); - $form->addItem($code); - - // Skipped - $eval_skipped = new ilRadioGroupInputGUI($lng->txt("svy_eval_skipped_value"), "skcust"); - $eval_skipped->setRequired(true); - $form->addItem($eval_skipped); - - $eval_skipped->setValue($surveySetting->get("skipped_is_custom", false) - ? "cust" - : "lng"); - - $skipped_lng = new ilRadioOption($lng->txt("svy_eval_skipped_value_lng"), "lng"); - $skipped_lng->setInfo(sprintf($lng->txt("svy_eval_skipped_value_lng_info"), $lng->txt("skipped"))); - $eval_skipped->addOption($skipped_lng); - $skipped_cust = new ilRadioOption($lng->txt("svy_eval_skipped_value_custom"), "cust"); - $skipped_cust->setInfo($lng->txt("svy_eval_skipped_value_custom_info")); - $eval_skipped->addOption($skipped_cust); - - $skipped_cust_value = new ilTextInputGUI($lng->txt("svy_eval_skipped_value_custom_value"), "cust_value"); - $skipped_cust_value->setSize(15); - $skipped_cust_value->setValue($surveySetting->get("skipped_custom_value", "")); - $skipped_cust->addSubItem($skipped_cust_value); - - $anon_part = new ilCheckboxInputGUI($lng->txt("svy_anonymous_participants"), "anon_part"); - $anon_part->setInfo($lng->txt("svy_anonymous_participants_info")); - $anon_part->setChecked($surveySetting->get("anonymous_participants", false)); - $form->addItem($anon_part); - - $anon_part_min = new ilNumberInputGUI($lng->txt("svy_anonymous_participants_min"), "anon_part_min"); - $anon_part_min->setInfo($lng->txt("svy_anonymous_participants_min_info")); - $anon_part_min->setSize(4); - $anon_part_min->setMinValue(1); - $anon_part_min->setValue($surveySetting->get("anonymous_participants_min", null)); - $anon_part->addSubItem($anon_part_min); + /** + * display survey settings form + * + * Default settings tab for Survey settings + * + * @access public + */ + public function settingsObject(ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + $ilTabs->activateTab("settings"); + + if (!$a_form) { + $a_form = $this->initSettingsForm(); + } + + $tpl->setContent($a_form->getHTML()); + } + + protected function initSettingsForm() + { + $ilAccess = $this->access; + $lng = $this->lng; + $ilCtrl = $this->ctrl; - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - $form->addCommandButton("saveSettings", $lng->txt("save")); - } - - return $form; - } - - /** - * Save survey settings - */ - function saveSettingsObject() - { - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - - if (!$ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - $ilCtrl->redirect($this, "settings"); - } - - $form = $this->initSettingsForm(); - if($form->checkInput()) - { - $surveySetting = new ilSetting("survey"); - $surveySetting->set("unlimited_invitation", ($_POST["unlimited_invitation"]) ? "1" : "0"); - $surveySetting->set("use_anonymous_id", ($_POST["use_anonymous_id"]) ? "1" : "0"); - $surveySetting->set("anonymous_participants", ($_POST["anon_part"]) ? "1" : "0"); - $surveySetting->set("anonymous_participants_min", (trim($_POST["anon_part_min"])) ? (int)$_POST["anon_part_min"] : null); + $surveySetting = new ilSetting("survey"); + $unlimited_invitation = array_key_exists("unlimited_invitation", $_GET) ? $_GET["unlimited_invitation"] : $surveySetting->get("unlimited_invitation"); + $use_anonymous_id = array_key_exists("use_anonymous_id", $_GET) ? $_GET["use_anonymous_id"] : $surveySetting->get("use_anonymous_id"); + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this)); + $form->setTitle($lng->txt("survey_defaults")); + + // unlimited invitation + $enable = new ilCheckboxInputGUI($lng->txt("survey_unlimited_invitation"), "unlimited_invitation"); + $enable->setChecked($unlimited_invitation); + $enable->setInfo($lng->txt("survey_unlimited_invitation_desc")); + $form->addItem($enable); + + // Survey Code + $code = new ilCheckboxInputGUI($lng->txt("use_anonymous_id"), "use_anonymous_id"); + $code->setChecked($use_anonymous_id); + $code->setInfo($lng->txt("use_anonymous_id_desc")); + $form->addItem($code); + + // Skipped + $eval_skipped = new ilRadioGroupInputGUI($lng->txt("svy_eval_skipped_value"), "skcust"); + $eval_skipped->setRequired(true); + $form->addItem($eval_skipped); + + $eval_skipped->setValue($surveySetting->get("skipped_is_custom", false) + ? "cust" + : "lng"); + + $skipped_lng = new ilRadioOption($lng->txt("svy_eval_skipped_value_lng"), "lng"); + $skipped_lng->setInfo(sprintf($lng->txt("svy_eval_skipped_value_lng_info"), $lng->txt("skipped"))); + $eval_skipped->addOption($skipped_lng); + $skipped_cust = new ilRadioOption($lng->txt("svy_eval_skipped_value_custom"), "cust"); + $skipped_cust->setInfo($lng->txt("svy_eval_skipped_value_custom_info")); + $eval_skipped->addOption($skipped_cust); + + $skipped_cust_value = new ilTextInputGUI($lng->txt("svy_eval_skipped_value_custom_value"), "cust_value"); + $skipped_cust_value->setSize(15); + $skipped_cust_value->setValue($surveySetting->get("skipped_custom_value", "")); + $skipped_cust->addSubItem($skipped_cust_value); + + $anon_part = new ilCheckboxInputGUI($lng->txt("svy_anonymous_participants"), "anon_part"); + $anon_part->setInfo($lng->txt("svy_anonymous_participants_info")); + $anon_part->setChecked($surveySetting->get("anonymous_participants", false)); + $form->addItem($anon_part); + + $anon_part_min = new ilNumberInputGUI($lng->txt("svy_anonymous_participants_min"), "anon_part_min"); + $anon_part_min->setInfo($lng->txt("svy_anonymous_participants_min_info")); + $anon_part_min->setSize(4); + $anon_part_min->setMinValue(1); + $anon_part_min->setValue($surveySetting->get("anonymous_participants_min", null)); + $anon_part->addSubItem($anon_part_min); - if($_POST["skcust"] == "lng") - { - $surveySetting->set("skipped_is_custom", false); - } - else - { - $surveySetting->set("skipped_is_custom", true); - $surveySetting->set("skipped_custom_value", trim($_POST["cust_value"])); - } + if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) { + $form->addCommandButton("saveSettings", $lng->txt("save")); + } + + return $form; + } + + /** + * Save survey settings + */ + public function saveSettingsObject() + { + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + + if (!$ilAccess->checkAccess("write", "", $this->object->getRefId())) { + $ilCtrl->redirect($this, "settings"); + } + + $form = $this->initSettingsForm(); + if ($form->checkInput()) { + $surveySetting = new ilSetting("survey"); + $surveySetting->set("unlimited_invitation", ($_POST["unlimited_invitation"]) ? "1" : "0"); + $surveySetting->set("use_anonymous_id", ($_POST["use_anonymous_id"]) ? "1" : "0"); + $surveySetting->set("anonymous_participants", ($_POST["anon_part"]) ? "1" : "0"); + $surveySetting->set("anonymous_participants_min", (trim($_POST["anon_part_min"])) ? (int) $_POST["anon_part_min"] : null); - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "settings"); - } - - $form->setValuesByPost(); - $this->settingsObject($form); - } - - function getAdminTabs() - { - $this->getTabs(); - } + if ($_POST["skcust"] == "lng") { + $surveySetting->set("skipped_is_custom", false); + } else { + $surveySetting->set("skipped_is_custom", true); + $surveySetting->set("skipped_custom_value", trim($_POST["cust_value"])); + } - /** - * get tabs - * @access public - * @param object tabs gui object - */ - function getTabs() - { - $lng = $this->lng; + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "settings"); + } + + $form->setValuesByPost(); + $this->settingsObject($form); + } + + public function getAdminTabs() + { + $this->getTabs(); + } - if ($this->checkPermissionBool("read")) - { - $this->tabs_gui->addTab("settings", - $lng->txt("settings"), - $this->ctrl->getLinkTarget($this, "settings")); + /** + * get tabs + * @access public + * @param object tabs gui object + */ + public function getTabs() + { + $lng = $this->lng; - // #7927: special users are deprecated - /* - $tabs_gui->addTab("specialusers", - $lng->txt("specialusers"), - $this->ctrl->getLinkTarget($this, "specialusers")); - */ + if ($this->checkPermissionBool("read")) { + $this->tabs_gui->addTab( + "settings", + $lng->txt("settings"), + $this->ctrl->getLinkTarget($this, "settings") + ); - if ($this->checkPermissionBool("write")) - { - $this->tabs_gui->addTab("templates", - $lng->txt("adm_settings_templates"), - $this->ctrl->getLinkTargetByClass("ilsettingstemplategui", "")); - } - } - if ($this->checkPermissionBool("edit_permission")) - { - $this->tabs_gui->addTab("perm_settings", - $lng->txt("perm_settings"), - $this->ctrl->getLinkTargetByClass('ilpermissiongui', "perm")); - } - } + // #7927: special users are deprecated + /* + $tabs_gui->addTab("specialusers", + $lng->txt("specialusers"), + $this->ctrl->getLinkTarget($this, "specialusers")); + */ - /** - * Get settings template configuration object - * - * @return object settings template configuration object - */ - private function getSettingsTemplateConfig() - { - $lng = $this->lng; + if ($this->checkPermissionBool("write")) { + $this->tabs_gui->addTab( + "templates", + $lng->txt("adm_settings_templates"), + $this->ctrl->getLinkTargetByClass("ilsettingstemplategui", "") + ); + } + } + if ($this->checkPermissionBool("edit_permission")) { + $this->tabs_gui->addTab( + "perm_settings", + $lng->txt("perm_settings"), + $this->ctrl->getLinkTargetByClass('ilpermissiongui', "perm") + ); + } + } - $lng->loadLanguageModule("survey"); - include_once "Modules/Survey/classes/class.ilObjSurvey.php"; + /** + * Get settings template configuration object + * + * @return object settings template configuration object + */ + private function getSettingsTemplateConfig() + { + $lng = $this->lng; - include_once("./Services/Administration/classes/class.ilSettingsTemplateConfig.php"); - $config = new ilSettingsTemplateConfig("svy"); + $lng->loadLanguageModule("survey"); + include_once "Modules/Survey/classes/class.ilObjSurvey.php"; - $config->addHidableTab("survey_question_editor", $lng->txt("survey_question_editor_settings_template")); - $config->addHidableTab("constraints", $lng->txt("constraints")); - $config->addHidableTab("invitation", $lng->txt("invitation")); - $config->addHidableTab("meta_data", $lng->txt("meta_data")); - $config->addHidableTab("export", $lng->txt("export")); + include_once("./Services/Administration/classes/class.ilSettingsTemplateConfig.php"); + $config = new ilSettingsTemplateConfig("svy"); - $config->addSetting( - "use_pool", - ilSettingsTemplateConfig::SELECT, - $lng->txt("survey_question_pool_usage"), - true, - 0, - array(1 => $this->lng->txt("survey_question_pool_usage_active"), - 0 => $this->lng->txt("survey_question_pool_usage_inactive")) - ); - - - $config->addSetting( - "enabled_start_date", - ilSettingsTemplateConfig::BOOL, - $lng->txt("start_date"), - true - ); + $config->addHidableTab("survey_question_editor", $lng->txt("survey_question_editor_settings_template")); + $config->addHidableTab("constraints", $lng->txt("constraints")); + $config->addHidableTab("invitation", $lng->txt("invitation")); + $config->addHidableTab("meta_data", $lng->txt("meta_data")); + $config->addHidableTab("export", $lng->txt("export")); - $config->addSetting( - "enabled_end_date", - ilSettingsTemplateConfig::BOOL, - $lng->txt("end_date"), - true - ); + $config->addSetting( + "use_pool", + ilSettingsTemplateConfig::SELECT, + $lng->txt("survey_question_pool_usage"), + true, + 0, + array(1 => $this->lng->txt("survey_question_pool_usage_active"), + 0 => $this->lng->txt("survey_question_pool_usage_inactive")) + ); + + + $config->addSetting( + "enabled_start_date", + ilSettingsTemplateConfig::BOOL, + $lng->txt("start_date"), + true + ); - $config->addSetting( - "show_question_titles", - ilSettingsTemplateConfig::BOOL, - $lng->txt("svy_show_questiontitles"), - true - ); + $config->addSetting( + "enabled_end_date", + ilSettingsTemplateConfig::BOOL, + $lng->txt("end_date"), + true + ); - - // #17585 - - $config->addSetting( - "acc_codes", - ilSettingsTemplateConfig::BOOL, - $lng->txt("survey_access_codes"), - true - ); - - $config->addSetting( - "evaluation_access", - ilSettingsTemplateConfig::SELECT, - $lng->txt("evaluation_access"), - true, - 0, - array(ilObjSurvey::EVALUATION_ACCESS_OFF => $this->lng->txt("evaluation_access_off"), - ilObjSurvey::EVALUATION_ACCESS_ALL => $this->lng->txt("evaluation_access_all"), - ilObjSurvey::EVALUATION_ACCESS_PARTICIPANTS => $this->lng->txt("evaluation_access_participants")) - ); - - $config->addSetting( - "anonymization_options", - ilSettingsTemplateConfig::SELECT, - $lng->txt("survey_results_anonymization"), - true, - 0, - array("statpers" => $this->lng->txt("survey_results_personalized"), - "statanon" => $this->lng->txt("survey_results_anonymized")) - ); - - /* - $config->addSetting( - "rte_switch", - ilSettingsTemplateConfig::SELECT, - $lng->txt("set_edit_mode"), - true, - 0, - array(0 => $this->lng->txt("rte_editor_disabled"), - 1 => $this->lng->txt("rte_editor_enabled")) - ); - */ - - return $config; - } + $config->addSetting( + "show_question_titles", + ilSettingsTemplateConfig::BOOL, + $lng->txt("svy_show_questiontitles"), + true + ); + + // #17585 + + $config->addSetting( + "acc_codes", + ilSettingsTemplateConfig::BOOL, + $lng->txt("survey_access_codes"), + true + ); + + $config->addSetting( + "evaluation_access", + ilSettingsTemplateConfig::SELECT, + $lng->txt("evaluation_access"), + true, + 0, + array(ilObjSurvey::EVALUATION_ACCESS_OFF => $this->lng->txt("evaluation_access_off"), + ilObjSurvey::EVALUATION_ACCESS_ALL => $this->lng->txt("evaluation_access_all"), + ilObjSurvey::EVALUATION_ACCESS_PARTICIPANTS => $this->lng->txt("evaluation_access_participants")) + ); + + $config->addSetting( + "anonymization_options", + ilSettingsTemplateConfig::SELECT, + $lng->txt("survey_results_anonymization"), + true, + 0, + array("statpers" => $this->lng->txt("survey_results_personalized"), + "statanon" => $this->lng->txt("survey_results_anonymized")) + ); + + /* + $config->addSetting( + "rte_switch", + ilSettingsTemplateConfig::SELECT, + $lng->txt("set_edit_mode"), + true, + 0, + array(0 => $this->lng->txt("rte_editor_disabled"), + 1 => $this->lng->txt("rte_editor_enabled")) + ); + */ + + return $config; + } } // END class.ilObjSurveyAdministrationGUI -?> \ No newline at end of file diff --git a/Modules/Survey/classes/class.ilObjSurveyGUI.php b/Modules/Survey/classes/class.ilObjSurveyGUI.php index 4134068bedb368ebb5e009379df9c36fa7028e1b..46ef76bfefb7dcb151417c381f49b41283540294 100755 --- a/Modules/Survey/classes/class.ilObjSurveyGUI.php +++ b/Modules/Survey/classes/class.ilObjSurveyGUI.php @@ -23,2488 +23,2287 @@ include_once "./Services/Object/classes/class.ilObjectGUI.php"; */ class ilObjSurveyGUI extends ilObjectGUI { - /** - * @var ilNavigationHistory - */ - protected $nav_history; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilHelpGUI - */ - protected $help; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilLogger - */ - protected $log; - - public function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - $this->nav_history = $DIC["ilNavigationHistory"]; - $this->tabs = $DIC->tabs(); - $this->user = $DIC->user(); - $this->help = $DIC["ilHelp"]; - $this->rbacsystem = $DIC->rbac()->system(); - $this->tree = $DIC->repositoryTree(); - $this->tpl = $DIC["tpl"]; - $this->toolbar = $DIC->toolbar(); - $this->access = $DIC->access(); - $this->locator = $DIC["ilLocator"]; - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - - $this->type = "svy"; - $lng->loadLanguageModule("survey"); - $lng->loadLanguageModule("svy"); - $this->ctrl = $ilCtrl; - $this->ctrl->saveParameter($this, "ref_id"); - - $this->log = ilLoggerFactory::getLogger("svy"); - - parent::__construct("", (int)$_GET["ref_id"], true, false); - } - - public function executeCommand() - { - $ilNavigationHistory = $this->nav_history; - $ilTabs = $this->tabs; - - $this->external_rater_360 = false; - if(!$this->creation_mode && - $this->object->get360Mode() && - $_SESSION["anonymous_id"][$this->object->getId()] && - ilObjSurvey::validateExternalRaterCode($this->object->getRefId(), - $_SESSION["anonymous_id"][$this->object->getId()])) - { - $this->external_rater_360 = true; - } - - if(!$this->external_rater_360) - { - if (!$this->checkPermissionBool("visible") && - !$this->checkPermissionBool("read")) - { - $this->checkPermission("read"); - } - - // add entry to navigation history - if (!$this->getCreationMode() && - $this->checkPermissionBool("read")) - { - $this->ctrl->setParameterByClass("ilobjsurveygui", "ref_id", $this->ref_id); - $link = $this->ctrl->getLinkTargetByClass("ilobjsurveygui", ""); - $ilNavigationHistory->addItem($this->ref_id, $link, "svy"); - } - } - - $cmd = $this->ctrl->getCmd("properties"); - - // workaround for bug #6288, needs better solution - if ($cmd == "saveTags") - { - $this->ctrl->setCmdClass("ilinfoscreengui"); - } - - // deep link from repository - "redirect" to page view - if(!$this->ctrl->getCmdClass() && $cmd == "questionsrepo") - { - $_REQUEST["pgov"] = 1; - $this->ctrl->setCmd("questions"); - $this->ctrl->setCmdClass("ilsurveyeditorgui"); - } - - $next_class = $this->ctrl->getNextClass($this); - $this->ctrl->setReturn($this, "properties"); - $this->tpl->addCss(ilUtil::getStyleSheetLocation("output", "survey.css", "Modules/Survey"), "screen"); - $this->prepareOutput(); - - $this->log->debug("next_class= $next_class"); - switch($next_class) - { - case 'illtiproviderobjectsettinggui': - $this->addSubTabs('settings'); - $ilTabs->activateTab("settings"); - $ilTabs->activateSubTab('lti_provider'); - $lti_gui = new ilLTIProviderObjectSettingGUI($this->object->getRefId()); - $lti_gui->setCustomRolesForSelection($GLOBALS['DIC']->rbac()->review()->getLocalRoles($this->object->getRefId())); - $lti_gui->offerLTIRolesForSelection(false); - $this->ctrl->forwardCommand($lti_gui); - break; - - - case "ilinfoscreengui": - if(!in_array($this->ctrl->getCmdClass(), - array('ilpublicuserprofilegui', 'ilobjportfoliogui'))) - { - $this->addHeaderAction(); - $this->infoScreen(); // forwards command - } - else - { - // #16891 - $ilTabs->clearTargets(); - include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); - $info = new ilInfoScreenGUI($this); - $this->ctrl->forwardCommand($info); - } - break; - - case 'ilobjectmetadatagui': - $this->checkPermission("write"); - $ilTabs->activateTab("meta_data"); - $this->addHeaderAction(); - include_once 'Services/Object/classes/class.ilObjectMetaDataGUI.php'; - $md_gui = new ilObjectMetaDataGUI($this->object); - $this->ctrl->forwardCommand($md_gui); - break; - - case "ilsurveyevaluationgui": - $ilTabs->activateTab("svy_results"); - $this->addHeaderAction(); - include_once("./Modules/Survey/classes/class.ilSurveyEvaluationGUI.php"); - $eval_gui = new ilSurveyEvaluationGUI($this->object); - $this->ctrl->forwardCommand($eval_gui); - break; - - case "ilsurveyexecutiongui": - $ilTabs->clearTargets(); - include_once("./Modules/Survey/classes/class.ilSurveyExecutionGUI.php"); - $exec_gui = new ilSurveyExecutionGUI($this->object); - $this->ctrl->forwardCommand($exec_gui); - break; - - case 'ilpermissiongui': - $ilTabs->activateTab("perm_settings"); - $this->addHeaderAction(); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $this->ctrl->forwardCommand($perm_gui); - break; - - case 'ilobjectcopygui': - include_once './Services/Object/classes/class.ilObjectCopyGUI.php'; - $cp = new ilObjectCopyGUI($this); - $cp->setType('svy'); - $this->ctrl->forwardCommand($cp); - break; - - case "ilcommonactiondispatchergui": - include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); - $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); - $this->ctrl->forwardCommand($gui); - break; - - // 360, skill service - case 'ilsurveyskillgui': - $ilTabs->activateTab("survey_competences"); - include_once("./Modules/Survey/classes/class.ilSurveySkillGUI.php"); - $gui = new ilSurveySkillGUI($this->object); - $this->ctrl->forwardCommand($gui); - break; - - case 'ilsurveyskilldeterminationgui': - $ilTabs->activateTab("maintenance"); - include_once("./Modules/Survey/classes/class.ilSurveySkillDeterminationGUI.php"); - $gui = new ilSurveySkillDeterminationGUI($this->object); - $this->ctrl->forwardCommand($gui); - break; - - case 'ilsurveyeditorgui': - $this->checkPermission("write"); - $ilTabs->activateTab("survey_questions"); - include_once("./Modules/Survey/classes/class.ilSurveyEditorGUI.php"); - $gui = new ilSurveyEditorGUI($this); - $this->ctrl->forwardCommand($gui); - break; - - case 'ilsurveyconstraintsgui': - $this->checkPermission("write"); - $ilTabs->activateTab("constraints"); - include_once("./Modules/Survey/classes/class.ilSurveyConstraintsGUI.php"); - $gui = new ilSurveyConstraintsGUI($this); - $this->ctrl->forwardCommand($gui); - break; - - case 'ilsurveyparticipantsgui': - if($this->object->getMode() == ilObjSurvey::MODE_STANDARD || $this->object->getMode() == ilObjSurvey::MODE_SELF_EVAL) - { - $ilTabs->activateTab("maintenance"); - } - else - { - $ilTabs->activateTab("survey_360_appraisees"); - } - include_once("./Modules/Survey/classes/class.ilSurveyParticipantsGUI.php"); - //$gui = new ilSurveyParticipantsGUI($this, $this->checkPermissionBool("write")); - $gui = new ilSurveyParticipantsGUI($this, $this->checkRbacOrPositionPermission('read_results', 'access_results')); - $this->ctrl->forwardCommand($gui); - break; - - case "illearningprogressgui": - $ilTabs->activateTab("learning_progress"); - include_once("./Services/Tracking/classes/class.ilLearningProgressGUI.php"); - $new_gui = new ilLearningProgressGUI(ilLearningProgressBaseGUI::LP_CONTEXT_REPOSITORY, - $this->object->getRefId()); - $this->ctrl->forwardCommand($new_gui); - break; - - case 'ilexportgui': - $ilTabs->activateTab("export"); - include_once("./Services/Export/classes/class.ilExportGUI.php"); - $exp_gui = new ilExportGUI($this); - $exp_gui->addFormat("xml"); - $this->ctrl->forwardCommand($exp_gui); - break; - - default: - $this->addHeaderAction(); - $cmd.= "Object"; - - $this->log->debug("Default cmd= $cmd"); - - $this->$cmd(); - break; - } - - if (strtolower($_GET["baseClass"]) != "iladministrationgui" && - $this->getCreationMode() != true) - { - $this->tpl->show(); - } - } - - /** - * Redirects the evaluation object call to the ilSurveyEvaluationGUI class - * - * Coming from ListGUI... - * - * @access private - */ - public function evaluationObject() - { - include_once("./Modules/Survey/classes/class.ilSurveyEvaluationGUI.php"); - $eval_gui = new ilSurveyEvaluationGUI($this->object); - $this->ctrl->setCmdClass(get_class($eval_gui)); - $this->ctrl->redirect($eval_gui, "evaluation"); - } - - protected function addDidacticTemplateOptions(array &$a_options) - { - include_once "Services/Administration/classes/class.ilSettingsTemplate.php"; - $templates = ilSettingsTemplate::getAllSettingsTemplates("svy"); - if($templates) - { - foreach($templates as $item) - { - $a_options["svytpl_".$item["id"]] = array($item["title"], - nl2br(trim($item["description"]))); - } - } - - // JF, 2013-06-10 - $a_options["svy360_1"] = array($this->lng->txt("survey_360_mode"), - $this->lng->txt("survey_360_mode_info")); - - //Self evaluation only - $a_options["svyselfeval_1"] = array($this->lng->txt("svy_self_ev_mode"), - $this->lng->txt("svy_self_ev_info")); - } - - /** - * save object - * @access public - */ - function afterSave(ilObject $a_new_object) - { - // #16446 - $a_new_object->loadFromDb(); - - $tpl = $this->getDidacticTemplateVar("svytpl"); - if($tpl) - { - $a_new_object->applySettingsTemplate($tpl); - } - else - { - //set the mode depending on didactic template - if($this->getDidacticTemplateVar("svy360")) - { - $a_new_object->setMode(ilObjSurvey::MODE_360); - } - elseif ($this->getDidacticTemplateVar("svyselfeval")) - { - $a_new_object->setMode(ilObjSurvey::MODE_SELF_EVAL); - } - } - - $svy_mode = $a_new_object->getMode(); - if($svy_mode == ilObjSurvey::MODE_360) - { - // this should rather be ilObjSurvey::ANONYMIZE_ON - see ilObjSurvey::getUserDataFromActiveId() - $a_new_object->setAnonymize(ilObjSurvey::ANONYMIZE_CODE_ALL); - $a_new_object->setEvaluationAccess(ilObjSurvey::EVALUATION_ACCESS_PARTICIPANTS); - } - elseif($svy_mode == ilObjSurvey::MODE_SELF_EVAL) - { - $a_new_object->setEvaluationAccess(ilObjSurvey::EVALUATION_ACCESS_PARTICIPANTS); - } - $a_new_object->saveToDB(); - - // always send a message - ilUtil::sendSuccess($this->lng->txt("object_added"),true); - ilUtil::redirect("ilias.php?baseClass=ilObjSurveyGUI&ref_id=". - $a_new_object->getRefId()."&cmd=properties"); - } - - /** - * adds tabs to tab gui object - * - * @param object $tabs_gui ilTabsGUI object - */ - function getTabs() - { - $ilUser = $this->user; - $ilHelp = $this->help; - - if($this->object instanceof ilObjSurveyQuestionPool) - { - return true; - } - - $ilHelp->setScreenIdComponent("svy"); - - $hidden_tabs = array(); - $template = $this->object->getTemplate(); - if($template) - { - include_once "Services/Administration/classes/class.ilSettingsTemplate.php"; - $template = new ilSettingsTemplate($template); - $hidden_tabs = $template->getHiddenTabs(); - } - - if ($this->checkPermissionBool("write")) - { - $this->tabs_gui->addTab("survey_questions", - $this->lng->txt("survey_questions"), - $this->ctrl->getLinkTargetByClass(array("ilsurveyeditorgui", "ilsurveypagegui"), "renderPage")); - } - - if ($this->checkPermissionBool("read")) - { - $this->tabs_gui->addTab("info_short", - $this->lng->txt("info_short"), - $this->ctrl->getLinkTarget($this,'infoScreen')); - } - - // properties - if ($this->checkPermissionBool("write")) - { - $this->tabs_gui->addTab("settings", - $this->lng->txt("settings"), - $this->ctrl->getLinkTarget($this,'properties')); - } - else if ($this->checkPermissionBool("read")) - { - if($this->object->get360Mode() && - $this->object->get360SelfRaters() && - $this->object->isAppraisee($ilUser->getId()) && - !$this->object->isAppraiseeClosed($ilUser->getId())) - { - $this->tabs_gui->addTab("survey_360_edit_raters", - $this->lng->txt("survey_360_edit_raters"), - $this->ctrl->getLinkTargetByClass('ilsurveyparticipantsgui','editRaters')); - - // :TODO: mail to raters - } - } - - // questions - if ($this->checkPermissionBool("write") && - !in_array("constraints", $hidden_tabs) && - $this->object->getMode() == ilObjSurvey::MODE_STANDARD) - { - // constraints (tab called routing) - $this->tabs_gui->addTab("constraints", - $this->lng->txt("constraints"), - $this->ctrl->getLinkTargetByClass("ilsurveyconstraintsgui", "constraints")); - } - - if ($this->checkPermissionBool("write")) - { - switch($this->object->getMode()) { - case ilObjSurvey::MODE_360: - // 360 mode + competence service - include_once("./Services/Skill/classes/class.ilSkillManagementSettings.php"); - $skmg_set = new ilSkillManagementSettings(); - if ($this->object->getSkillService() && $skmg_set->isActivated()) - { - $this->tabs_gui->addTab("survey_competences", - $this->lng->txt("survey_competences"), - $this->ctrl->getLinkTargetByClass("ilsurveyskillgui", "listQuestionAssignment")); - } - $this->tabs_gui->addTab("survey_360_appraisees", - $this->lng->txt("survey_360_appraisees"), - $this->ctrl->getLinkTargetByClass('ilsurveyparticipantsgui', 'listAppraisees')); - break; - - case ilObjSurvey::MODE_SELF_EVAL: - include_once("./Services/Skill/classes/class.ilSkillManagementSettings.php"); - $skmg_set = new ilSkillManagementSettings(); - if ($this->object->getSkillService() && $skmg_set->isActivated()) - { - $this->tabs_gui->addTab("survey_competences", - $this->lng->txt("survey_competences"), - $this->ctrl->getLinkTargetByClass("ilsurveyskillgui", "listQuestionAssignment")); - } - $this->tabs_gui->addTab( - "maintenance", - $this->lng->txt("maintenance"), - $this->ctrl->getLinkTargetByClass('ilsurveyparticipantsgui', 'maintenance')); - break; - - default: - // maintenance (tab called participants) - $this->tabs_gui->addTab( - "maintenance", - $this->lng->txt("maintenance"), - $this->ctrl->getLinkTargetByClass('ilsurveyparticipantsgui', 'maintenance')); - break; - } - } - - include_once "./Modules/Survey/classes/class.ilObjSurveyAccess.php"; - if( - $this->checkRbacOrPositionPermission('read_results','access_results') || - ilObjSurveyAccess::_hasEvaluationAccess($this->object->getId(), $ilUser->getId())) - { - // evaluation - $this->tabs_gui->addTab("svy_results", - $this->lng->txt("svy_results"), - $this->ctrl->getLinkTargetByClass("ilsurveyevaluationgui", "evaluation")); - } - - // learning progress - include_once "./Services/Tracking/classes/class.ilLearningProgressAccess.php"; - if(ilLearningProgressAccess::checkAccess($this->object->getRefId())) - { - $this->tabs_gui->addTarget("learning_progress", - $this->ctrl->getLinkTargetByClass(array("ilobjsurveygui", "illearningprogressgui"), ""), - "", - array("illplistofobjectsgui", "illplistofsettingsgui", "illearningprogressgui", "illplistofprogressgui")); - } - - if ($this->checkPermissionBool("write")) - { - if(!in_array("meta_data", $hidden_tabs)) - { - // meta data - include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php"; - $mdgui = new ilObjectMetaDataGUI($this->object); - $mdtab = $mdgui->getTab(); - if($mdtab) - { - $this->tabs_gui->addTab("meta_data", - $this->lng->txt("meta_data"), - $mdtab); - } - } - - if(!in_array("export", $hidden_tabs)) - { - // export - $this->tabs_gui->addTab("export", - $this->lng->txt("export"), - $this->ctrl->getLinkTargetByClass("ilexportgui", "")); - } - } - - if ($this->checkPermissionBool("edit_permission")) - { - // permissions - $this->tabs_gui->addTab("perm_settings", - $this->lng->txt("perm_settings"), - $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm")); - } - } - - - // - // SETTINGS - // - - /** - * Save the survey properties - * - * Save the survey properties - * - * @access private - */ - function savePropertiesObject() - { - $rbacsystem = $this->rbacsystem; - $obj_service = $this->object_service; - - $form = $this->initPropertiesForm(); - if ($form->checkInput()) - { - $valid = true; - - if(!$this->object->get360Mode()) - { - if($form->getInput("tut")) - { - // check if given "tutors" have write permission - $tut_ids =array(); - $tut_logins = $form->getInput("tut_ids"); - foreach($tut_logins as $tut_login) - { - $tut_id = ilObjUser::_lookupId($tut_login); - if($tut_id && $rbacsystem->checkAccessOfUser($tut_id, "write", $this->object->getRefId())) - { - $tut_ids[] = $tut_id; - } - } - if(!$tut_ids) - { - $tut_ids = $form->getItemByPostVar("tut_ids"); - $tut_ids->setAlert($this->lng->txt("survey_notification_tutor_recipients_invalid")); - $valid = false; - } - } - } - - if($valid) - { - if($form->getInput("rmd")) - { - $rmd_start = $form->getItemByPostVar("rmd_start")->getDate(); - $rmd_end = $form->getItemByPostVar("rmd_end")->getDate(); - if($rmd_end) - { - if($rmd_start->get(IL_CAL_UNIX) > $rmd_end->get(IL_CAL_UNIX)) - { - $tmp = $rmd_start; - $rmd_start = $rmd_end; - $rmd_end = $tmp; - } - } - $this->object->setReminderStatus(true); - $this->object->setReminderStart($rmd_start); - $this->object->setReminderEnd($rmd_end); - $this->object->setReminderFrequency($form->getInput("rmd_freq")); - if(!$this->object->get360Mode()) - { - $this->object->setReminderTarget($form->getInput("rmd_grp")); - $this->object->setReminderTemplate(($form->getInput("rmdt") > 0) - ? $form->getInput("rmdt") - : null); - } - else - { - if ($form->getInput("remind_appraisees") && $form->getInput("remind_raters")) - { - $this->object->setReminderTarget(ilObjSurvey::NOTIFICATION_APPRAISEES_AND_RATERS); - } - else if ($form->getInput("remind_appraisees")) - { - $this->object->setReminderTarget(ilObjSurvey::NOTIFICATION_APPRAISEES); - } - else if ($form->getInput("remind_raters")) - { - $this->object->setReminderTarget(ilObjSurvey::NOTIFICATION_RATERS); - } - else - { - $this->object->setReminderTarget(0); - } - } - } - else - { - $this->object->setReminderStatus(false); - } - - if(!$this->object->get360Mode()) - { - - if($form->getInput("tut")) - { - $this->object->setTutorNotificationStatus(true); - $this->object->setTutorNotificationRecipients($tut_ids); // see above - $this->object->setTutorNotificationTarget($form->getInput("tut_grp")); - } - else - { - $this->object->setTutorNotificationStatus(false); - } - } - - // #10055 - if ($_POST['online'] && count($this->object->questions) == 0) - { - $_POST['online'] = null; - ilUtil::sendFailure($this->lng->txt("cannot_switch_to_online_no_questions"), true); - } - - $template_settings = null; - $template = $this->object->getTemplate(); - if($template) - { - include_once "Services/Administration/classes/class.ilSettingsTemplate.php"; - $template = new ilSettingsTemplate($template); - $template_settings = $template->getSettings(); - } - - include_once 'Services/MetaData/classes/class.ilMD.php'; - $md_obj = new ilMD($this->object->getId(), 0, "svy"); - $md_section = $md_obj->getGeneral(); - - // title - $md_section->setTitle(ilUtil::stripSlashes($_POST['title'])); - $md_section->update(); - - // Description - $md_desc_ids = $md_section->getDescriptionIds(); - if($md_desc_ids) - { - $md_desc = $md_section->getDescription(array_pop($md_desc_ids)); - $md_desc->setDescription(ilUtil::stripSlashes($_POST['description'])); - $md_desc->update(); - } - - $this->object->setViewOwnResults($_POST["view_own"]); - $this->object->setMailOwnResults($_POST["mail_own"]); - $this->object->setMailConfirmation($_POST["mail_confirm"]); - - // both are saved in object, too - $this->object->setTitle(ilUtil::stripSlashes($_POST['title'])); - $this->object->setDescription(ilUtil::stripSlashes($_POST['description'])); - $this->object->setOfflineStatus((bool) !$_POST['online']); - $this->object->update(); - - // activation - $period = $form->getItemByPostVar("access_period"); - if($period->getStart() && $period->getEnd()) - { - $this->object->setActivationLimited(true); - $this->object->setActivationVisibility($_POST["access_visiblity"]); - $this->object->setActivationStartDate($period->getStart()->get(IL_CAL_UNIX)); - $this->object->setActivationEndDate($period->getEnd()->get(IL_CAL_UNIX)); - } - else - { - $this->object->setActivationLimited(false); - } - - // tile image - $obj_service->commonSettings()->legacyForm($form, $this->object)->saveTileImage(); - - - if(!$template_settings["enabled_start_date"]["hide"]) - { - $start = $form->getItemByPostVar("start_date"); - if($start->getDate()) - { - $datetime = explode(" ", $start->getDate()->get(IL_CAL_DATETIME)); - $this->object->setStartDateAndTime($datetime[0], $datetime[1]); - } - else - { - $this->object->setStartDate(null); - } - } - - if(!$template_settings["enabled_end_date"]["hide"]) - { - $end = $form->getItemByPostVar("end_date"); - if($end->getDate()) - { - $datetime = explode(" ", $end->getDate()->get(IL_CAL_DATETIME)); - $this->object->setEndDateAndTime($datetime[0], $datetime[1]); - } - else - { - $this->object->setEndDate(null); - } - } - - - include_once "./Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php"; - $introduction = $_POST["introduction"]; - $this->object->setIntroduction($introduction); - $outro = $_POST["outro"]; - $this->object->setOutro($outro); - - if(!$template_settings["show_question_titles"]["hide"]) - { - $this->object->setShowQuestionTitles($_POST["show_question_titles"]); - } - - if(!$template_settings["use_pool"]["hide"]) - { - $this->object->setPoolUsage($_POST["use_pool"]); - } - - $this->object->setMailNotification($_POST['mailnotification']); - $this->object->setMailAddresses($_POST['mailaddresses']); - $this->object->setMailParticipantData($_POST['mailparticipantdata']); - - switch ($this->object->getMode()){ - case ilObjSurvey::MODE_360: - $this->object->set360SelfEvaluation((bool)$_POST["self_eval"]); - $this->object->set360SelfAppraisee((bool)$_POST["self_appr"]); - $this->object->set360SelfRaters((bool)$_POST["self_rate"]); - $this->object->set360Results((int)$_POST["ts_res"]);; - $this->object->setSkillService((int)$_POST["skill_service"]); - break; - case ilObjSurvey::MODE_SELF_EVAL: - $this->object->setSelfEvaluationResults($_POST["self_eval_res"]); - $this->object->setSkillService((int)$_POST["skill_service"]); - break; - default: - if(!$template_settings["evaluation_access"]["hide"]) - { - $this->object->setEvaluationAccess($_POST["evaluation_access"]); - } - - $hasDatasets = ilObjSurvey::_hasDatasets($this->object->getSurveyId()); - if (!$hasDatasets) - { - $hide_codes = $template_settings["acc_codes"]["hide"]; - $hide_anon = $template_settings["anonymization_options"]["hide"]; - if(!$hide_codes || !$hide_anon) - { - $current = $this->object->getAnonymize(); - - // get current setting if property is hidden - if(!$hide_codes) - { - $codes = (bool)$_POST["acc_codes"]; - } - else - { - $codes = ($current == ilObjSurvey::ANONYMIZE_CODE_ALL || - $current == ilObjSurvey::ANONYMIZE_ON); - } - if(!$hide_anon) - { - $anon = ((string)$_POST["anonymization_options"] == "statanon"); - } - else - { - $anon = ($current == ilObjSurvey::ANONYMIZE_FREEACCESS || - $current == ilObjSurvey::ANONYMIZE_ON); - } - - // parse incoming values - if (!$anon) - { - if (!$codes) - { - $this->object->setAnonymize(ilObjSurvey::ANONYMIZE_OFF); - } - else - { - $this->object->setAnonymize(ilObjSurvey::ANONYMIZE_CODE_ALL); - } - } - else - { - if ($codes) - { - $this->object->setAnonymize(ilObjSurvey::ANONYMIZE_ON); - } - else - { - $this->object->setAnonymize(ilObjSurvey::ANONYMIZE_FREEACCESS); - } - - $this->object->setAnonymousUserList($_POST["anon_list"]); - } - - // if settings were changed get rid of existing code - unset($_SESSION["anonymous_id"][$this->object->getId()]); - } - } - break; - } - - $this->object->saveToDb(); - - ilObjectServiceSettingsGUI::updateServiceSettingsForm( - $this->object->getId(), - $form, - array( - ilObjectServiceSettingsGUI::ORGU_POSITION_ACCESS - ) - ); - - if (strcmp($_SESSION["info"], "") != 0) - { - ilUtil::sendSuccess($_SESSION["info"] . "
" . $this->lng->txt("settings_saved"), true); - } - else - { - ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); - } - $this->ctrl->redirect($this, "properties"); - } - else - { - // #16714 - ilUtil::sendFailure($this->lng->txt("form_input_not_valid")); - } - } - - $form->setValuesByPost(); - $this->propertiesObject($form); - } - - /** - * Init survey settings form - * - * @return ilPropertyFormGUI - */ - function initPropertiesForm() - { - $obj_service = $this->object_service; - - $template_settings = $hide_rte_switch = null; - $template = $this->object->getTemplate(); - if($template) - { - include_once "Services/Administration/classes/class.ilSettingsTemplate.php"; - $template = new ilSettingsTemplate($template); - - $template_settings = $template->getSettings(); - $hide_rte_switch = $template_settings["rte_switch"]["hide"]; - } - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - $form->setTableWidth("100%"); - $form->setId("survey_properties"); - - // general properties - $header = new ilFormSectionHeaderGUI(); - $header->setTitle($this->lng->txt("settings")); - $form->addItem($header); - - - // title & description (meta data) - - include_once 'Services/MetaData/classes/class.ilMD.php'; - $md_obj = new ilMD($this->object->getId(), 0, "svy"); - $md_section = $md_obj->getGeneral(); - - $title = new ilTextInputGUI($this->lng->txt("title"), "title"); - $title->setRequired(true); - $title->setValue($md_section->getTitle()); - $form->addItem($title); - - $ids = $md_section->getDescriptionIds(); - if($ids) - { - $desc_obj = $md_section->getDescription(array_pop($ids)); - - $desc = new ilTextAreaInputGUI($this->lng->txt("description"), "description"); - $desc->setCols(50); - $desc->setRows(4); - $desc->setValue($desc_obj->getDescription()); - $form->addItem($desc); - } - - // pool usage - $pool_usage = new ilRadioGroupInputGUI($this->lng->txt("survey_question_pool_usage"), "use_pool"); - $opt = new ilRadioOption($this->lng->txt("survey_question_pool_usage_active"), 1); - $opt->setInfo($this->lng->txt("survey_question_pool_usage_active_info")); - $pool_usage->addOption($opt); - $opt = new ilRadioOption($this->lng->txt("survey_question_pool_usage_inactive"), 0); - $opt->setInfo($this->lng->txt("survey_question_pool_usage_inactive_info")); - $pool_usage->addOption($opt); - $pool_usage->setValue($this->object->getPoolUsage()); - $form->addItem($pool_usage); - - // 360°: appraisees - if($this->object->get360Mode()) - { - $self_eval = new ilCheckboxInputGUI($this->lng->txt("survey_360_self_evaluation"), "self_eval"); - $self_eval->setInfo($this->lng->txt("survey_360_self_evaluation_info")); - $self_eval->setChecked($this->object->get360SelfEvaluation()); - $form->addItem($self_eval); - - $self_rate = new ilCheckboxInputGUI($this->lng->txt("survey_360_self_raters"), "self_rate"); - $self_rate->setInfo($this->lng->txt("survey_360_self_raters_info")); - $self_rate->setChecked($this->object->get360SelfRaters()); - $form->addItem($self_rate); - - $self_appr = new ilCheckboxInputGUI($this->lng->txt("survey_360_self_appraisee"), "self_appr"); - $self_appr->setInfo($this->lng->txt("survey_360_self_appraisee_info")); - $self_appr->setChecked($this->object->get360SelfAppraisee()); - $form->addItem($self_appr); - } - - - // activation - - include_once "Services/Object/classes/class.ilObjectActivation.php"; - $this->lng->loadLanguageModule('rep'); - - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($this->lng->txt('rep_activation_availability')); - $form->addItem($section); - - // additional info only with multiple references - $act_obj_info = $act_ref_info = ""; - if(sizeof(ilObject::_getAllReferences($this->object->getId())) > 1) - { - $act_obj_info = ' '.$this->lng->txt('rep_activation_online_object_info'); - $act_ref_info = $this->lng->txt('rep_activation_access_ref_info'); - } - - $online = new ilCheckboxInputGUI($this->lng->txt('rep_activation_online'),'online'); - $online->setInfo($this->lng->txt('svy_activation_online_info').$act_obj_info); - $online->setChecked(!$this->object->getOfflineStatus()); - $form->addItem($online); - - include_once "Services/Form/classes/class.ilDateDurationInputGUI.php"; - $dur = new ilDateDurationInputGUI($this->lng->txt('rep_visibility_until'), "access_period"); - $dur->setShowTime(true); - $date = $this->object->getActivationStartDate(); - $dur->setStart($date - ? new ilDateTime($date, IL_CAL_UNIX) - : null); - $date = $this->object->getActivationEndDate(); - $dur->setEnd($date - ? new ilDateTime($date, IL_CAL_UNIX) - : null); - $form->addItem($dur); - - $visible = new ilCheckboxInputGUI($this->lng->txt('rep_activation_limited_visibility'), 'access_visiblity'); - $visible->setInfo($this->lng->txt('svy_activation_limited_visibility_info')); - $visible->setChecked($this->object->getActivationVisibility()); - $dur->addSubItem($visible); - - // presentation - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($this->lng->txt('obj_presentation')); - $form->addItem($section); - - // tile image - $obj_service->commonSettings()->legacyForm($form, $this->object)->addTileImage(); - - // before start - - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($this->lng->txt('svy_settings_section_before_start')); - $form->addItem($section); - - // introduction - $intro = new ilTextAreaInputGUI($this->lng->txt("introduction"), "introduction"); - $intro->setValue($this->object->prepareTextareaOutput($this->object->getIntroduction())); - $intro->setRows(10); - $intro->setCols(80); - $intro->setUseRte(TRUE); - $intro->setInfo($this->lng->txt("survey_introduction_info")); - include_once "./Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php"; - $intro->setRteTags(ilObjAdvancedEditing::_getUsedHTMLTags("survey")); - $intro->addPlugin("latex"); - $intro->addButton("latex"); - $intro->addButton("pastelatex"); - $intro->setRTESupport($this->object->getId(), "svy", "survey", null, $hide_rte_switch); - $form->addItem($intro); - - - // access - - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($this->lng->txt('svy_settings_section_access')); - $form->addItem($section); - - // enable start date - $start = $this->object->getStartDate(); - // start date - $startingtime = new ilDateTimeInputGUI($this->lng->txt("start_date"), 'start_date'); - $startingtime->setShowTime(true); - if ($start) - { - $startingtime->setDate(new ilDate($start, IL_CAL_TIMESTAMP)); - } - $form->addItem($startingtime); - - // enable end date - $end = $this->object->getEndDate(); - // end date - $endingtime = new ilDateTimeInputGUI($this->lng->txt("end_date"), 'end_date'); - $endingtime->setShowTime(true); - if ($end) - { - $endingtime->setDate(new ilDate($end, IL_CAL_TIMESTAMP)); - } - $form->addItem($endingtime); - - // anonymization - if(!$this->object->get360Mode()) - { - $codes = new ilCheckboxInputGUI($this->lng->txt("survey_access_codes"), "acc_codes"); - $codes->setInfo($this->lng->txt("survey_access_codes_info")); - $codes->setChecked(!$this->object->isAccessibleWithoutCode()); - $form->addItem($codes); - - if (ilObjSurvey::_hasDatasets($this->object->getSurveyId())) - { - $codes->setDisabled(true); - } - } - - - // question behaviour - - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($this->lng->txt('svy_settings_section_question_behaviour')); - $form->addItem($section); - - // show question titles - $show_question_titles = new ilCheckboxInputGUI($this->lng->txt("svy_show_questiontitles"), "show_question_titles"); - $show_question_titles->setValue(1); - $show_question_titles->setChecked($this->object->getShowQuestionTitles()); - $form->addItem($show_question_titles); - - - // finishing - - $info = new ilFormSectionHeaderGUI(); - $info->setTitle($this->lng->txt("svy_settings_section_finishing")); - $form->addItem($info); - - $view_own = new ilCheckboxInputGUI($this->lng->txt("svy_results_view_own"), "view_own"); - $view_own->setInfo($this->lng->txt("svy_results_view_own_info")); - $view_own->setChecked($this->object->hasViewOwnResults()); - $form->addItem($view_own); - - $mail_confirm = new ilCheckboxInputGUI($this->lng->txt("svy_results_mail_confirm"), "mail_confirm"); - $mail_confirm->setInfo($this->lng->txt("svy_results_mail_confirm_info")); - $mail_confirm->setChecked($this->object->hasMailConfirmation()); - $form->addItem($mail_confirm); - - $mail_own = new ilCheckboxInputGUI($this->lng->txt("svy_results_mail_own"), "mail_own"); - $mail_own->setInfo($this->lng->txt("svy_results_mail_own_info")); - $mail_own->setChecked($this->object->hasMailOwnResults()); - $mail_confirm->addSubItem($mail_own); - - // final statement - $finalstatement = new ilTextAreaInputGUI($this->lng->txt("outro"), "outro"); - $finalstatement->setValue($this->object->prepareTextareaOutput($this->object->getOutro())); - $finalstatement->setRows(10); - $finalstatement->setCols(80); - $finalstatement->setUseRte(TRUE); - $finalstatement->setRteTags(ilObjAdvancedEditing::_getUsedHTMLTags("survey")); - $finalstatement->addPlugin("latex"); - $finalstatement->addButton("latex"); - $finalstatement->addButton("pastelatex"); - $finalstatement->setRTESupport($this->object->getId(), "svy", "survey", null, $hide_rte_switch); - $form->addItem($finalstatement); - - // mail notification - $mailnotification = new ilCheckboxInputGUI($this->lng->txt("mailnotification"), "mailnotification"); - // $mailnotification->setOptionTitle($this->lng->txt("activate")); - $mailnotification->setInfo($this->lng->txt("svy_result_mail_notification_info")); // #11762 - $mailnotification->setValue(1); - $mailnotification->setChecked($this->object->getMailNotification()); - - // addresses - $mailaddresses = new ilTextInputGUI($this->lng->txt("mailaddresses"), "mailaddresses"); - $mailaddresses->setValue($this->object->getMailAddresses()); - $mailaddresses->setSize(80); - $mailaddresses->setInfo($this->lng->txt('mailaddresses_info')); - $mailaddresses->setRequired(true); - - // participant data - $participantdata = new ilTextAreaInputGUI($this->lng->txt("mailparticipantdata"), "mailparticipantdata"); - $participantdata->setValue($this->object->getMailParticipantData()); - $participantdata->setRows(6); - $participantdata->setCols(80); - $participantdata->setUseRte(false); - $participantdata->setInfo($this->lng->txt("mailparticipantdata_info")); - - // #12755 - because of privacy concerns we restrict user data to a minimum - $placeholders = array( - "FIRST_NAME" => "firstname", - "LAST_NAME" => "lastname", - "LOGIN" => "login" - ); - $txt = array(); - foreach($placeholders as $placeholder => $caption) - { - $txt[] = "[".strtoupper($placeholder)."]: ".$this->lng->txt($caption); - } - $txt = implode("
", $txt); - $participantdatainfo = new ilNonEditableValueGUI($this->lng->txt("mailparticipantdata_placeholder"), "", true); - $participantdatainfo->setValue($txt); - - $mailnotification->addSubItem($mailaddresses); - $mailnotification->addSubItem($participantdata); - $mailnotification->addSubItem($participantdatainfo); - $form->addItem($mailnotification); - - // tutor notification - currently not available for 360° - if(!$this->object->get360Mode()) - { - // parent course? - $tree = $this->tree; - $has_parent = $tree->checkForParentType($this->object->getRefId(), "grp"); - if(!$has_parent) - { - $has_parent = $tree->checkForParentType($this->object->getRefId(), "crs"); - } - $num_inv = sizeof($this->object->getInvitedUsers()); - - // notification - $tut = new ilCheckboxInputGUI($this->lng->txt("survey_notification_tutor_setting"), "tut"); - $tut->setChecked($this->object->getTutorNotificationStatus()); - $form->addItem($tut); - - $tut_logins = array(); - $tuts = $this->object->getTutorNotificationRecipients(); - if($tuts) - { - foreach($tuts as $tut_id) - { - $tmp = ilObjUser::_lookupName($tut_id); - if($tmp["login"]) - { - $tut_logins[] = $tmp["login"]; - } - } - } - $tut_ids = new ilTextInputGUI($this->lng->txt("survey_notification_tutor_recipients"), "tut_ids"); - $tut_ids->setDataSource($this->ctrl->getLinkTarget($this, "doAutoComplete", "", true)); - $tut_ids->setRequired(true); - $tut_ids->setMulti(true); - $tut_ids->setMultiValues($tut_logins); - $tut_ids->setValue(array_shift($tut_logins)); - $tut->addSubItem($tut_ids); - - $tut_grp = new ilRadioGroupInputGUI($this->lng->txt("survey_notification_target_group"), "tut_grp"); - $tut_grp->setRequired(true); - $tut_grp->setValue($this->object->getTutorNotificationTarget()); - $tut->addSubItem($tut_grp); - - $tut_grp_crs = new ilRadioOption($this->lng->txt("survey_notification_target_group_parent_course"), - ilObjSurvey::NOTIFICATION_PARENT_COURSE); - if(!$has_parent) - { - $tut_grp_crs->setInfo($this->lng->txt("survey_notification_target_group_parent_course_inactive")); - } - else - { - $tut_grp_crs->setInfo(sprintf($this->lng->txt("survey_notification_target_group_invited_info"), - count($this->object->getNotificationTargetUserIds(false)))); - } - $tut_grp->addOption($tut_grp_crs); - - $tut_grp_inv = new ilRadioOption($this->lng->txt("survey_notification_target_group_invited"), - ilObjSurvey::NOTIFICATION_INVITED_USERS); - $tut_grp_inv->setInfo(sprintf($this->lng->txt("survey_notification_target_group_invited_info"), $num_inv)); - $tut_grp->addOption($tut_grp_inv); - } - - - // reminders - - $info = new ilFormSectionHeaderGUI(); - $info->setTitle($this->lng->txt("svy_settings_section_reminders")); - $form->addItem($info); - - $rmd = new ilCheckboxInputGUI($this->lng->txt("survey_reminder_setting"), "rmd"); - $rmd->setChecked($this->object->getReminderStatus()); - $form->addItem($rmd); - - $rmd_start = new ilDateTimeInputGUI($this->lng->txt("survey_reminder_start"), "rmd_start"); - $rmd_start->setRequired(true); - $start = $this->object->getReminderStart(); - if($start) - { - $rmd_start->setDate($start); - } - $rmd->addSubItem($rmd_start); - - $end = $this->object->getReminderEnd(); - $rmd_end = new ilDateTimeInputGUI($this->lng->txt("survey_reminder_end"), "rmd_end"); - if($end) - { - $rmd_end->setDate($end); - } - $rmd->addSubItem($rmd_end); - - $rmd_freq = new ilNumberInputGUI($this->lng->txt("survey_reminder_frequency"), "rmd_freq"); - $rmd_freq->setRequired(true); - $rmd_freq->setSize(3); - $rmd_freq->setSuffix($this->lng->txt("survey_reminder_frequency_days")); - $rmd_freq->setValue($this->object->getReminderFrequency()); - $rmd_freq->setMinValue(1); - $rmd->addSubItem($rmd_freq); - - - if (!$this->object->get360Mode()) - { - $rmd_grp = new ilRadioGroupInputGUI($this->lng->txt("survey_notification_target_group"), "rmd_grp"); - $rmd_grp->setRequired(true); - $rmd_grp->setValue($this->object->getReminderTarget()); - $rmd->addSubItem($rmd_grp); - - $rmd_grp_crs = new ilRadioOption($this->lng->txt("survey_notification_target_group_parent_course"), - ilObjSurvey::NOTIFICATION_PARENT_COURSE); - if (!$has_parent) - { - $rmd_grp_crs->setInfo($this->lng->txt("survey_notification_target_group_parent_course_inactive")); - } else - { - $rmd_grp_crs->setInfo(sprintf($this->lng->txt("survey_notification_target_group_invited_info"), - count($this->object->getNotificationTargetUserIds(false)))); - } - $rmd_grp->addOption($rmd_grp_crs); - - $rmd_grp_inv = new ilRadioOption($this->lng->txt("survey_notification_target_group_invited"), - ilObjSurvey::NOTIFICATION_INVITED_USERS); - $rmd_grp_inv->setInfo(sprintf($this->lng->txt("survey_notification_target_group_invited_info"), $num_inv)); - $rmd_grp->addOption($rmd_grp_inv); - - $mtmpl = $this->object->getReminderMailTemplates(); - if ($mtmpl) - { - $rmdt = new ilRadioGroupInputGUI($this->lng->txt("svy_reminder_mail_template"), "rmdt"); - $rmdt->setRequired(true); - $rmdt->addOption(new ilRadioOption($this->lng->txt("svy_reminder_mail_template_none"), -1)); - foreach ($mtmpl as $mtmpl_id => $mtmpl_caption) - { - $option = new ilRadioOption($mtmpl_caption, $mtmpl_id); - $rmdt->addOption($option); - } - - $reminderTemplateValue = -1; - if ($this->object->getReminderTemplate()) { - $reminderTemplateValue = $this->object->getReminderTemplate(); - } - $rmdt->setValue($reminderTemplateValue); - $rmd->addSubItem($rmdt); - } - } - else - { - // remind appraisees - $cb = new ilCheckboxInputGUI($this->lng->txt("survey_notification_target_group"), "remind_appraisees"); - $cb->setOptionTitle($this->lng->txt("survey_360_appraisees")); - $cb->setInfo($this->lng->txt("survey_360_appraisees_remind_info")); - $cb->setValue("1"); - $cb->setChecked(in_array($this->object->getReminderTarget(), - array(ilObjSurvey::NOTIFICATION_APPRAISEES, ilObjSurvey::NOTIFICATION_APPRAISEES_AND_RATERS))); - $rmd->addSubItem($cb); - - // remind raters - $cb = new ilCheckboxInputGUI("", "remind_raters"); - $cb->setOptionTitle($this->lng->txt("survey_360_raters")); - $cb->setInfo($this->lng->txt("survey_360_raters_remind_info")); - $cb->setValue("1"); - $cb->setChecked(in_array($this->object->getReminderTarget(), - array(ilObjSurvey::NOTIFICATION_RATERS, ilObjSurvey::NOTIFICATION_APPRAISEES_AND_RATERS))); - $rmd->addSubItem($cb); - } - - - // results - - $results = new ilFormSectionHeaderGUI(); - $results->setTitle($this->lng->txt("results")); - $form->addItem($results); - - // evaluation access - switch($this->object->getMode()) - { - case ilObjSurvey::MODE_360: - $ts_results = new ilRadioGroupInputGUI($this->lng->txt("survey_360_results"), "ts_res"); - $ts_results->setValue($this->object->get360Results()); - - $option = new ilRadioOption($this->lng->txt("survey_360_results_none"), ilObjSurvey::RESULTS_360_NONE); - $option->setInfo($this->lng->txt("survey_360_results_none_info")); - $ts_results->addOption($option); - - $option = new ilRadioOption($this->lng->txt("survey_360_results_own"), ilObjSurvey::RESULTS_360_OWN); - $option->setInfo($this->lng->txt("survey_360_results_own_info")); - $ts_results->addOption($option); - - $option = new ilRadioOption($this->lng->txt("survey_360_results_all"), ilObjSurvey::RESULTS_360_ALL); - $option->setInfo($this->lng->txt("survey_360_results_all_info")); - $ts_results->addOption($option); - - $form->addItem($ts_results); - break; - - case ilObjSurvey::MODE_SELF_EVAL: - //check the names of these vars - $evaluation_access = new ilRadioGroupInputGUI($this->lng->txt('evaluation_access'), "self_eval_res"); - $evaluation_access->setValue($this->object->getSelfEvaluationResults()); - - $option = new ilRadioOption($this->lng->txt("svy_self_ev_access_results_none"), ilObjSurvey::RESULTS_SELF_EVAL_NONE); - $evaluation_access->addOption($option); - - $option = new ilRadioOption($this->lng->txt("svy_self_ev_access_results_own"), ilObjSurvey::RESULTS_SELF_EVAL_OWN); - $evaluation_access->addOption($option); - - $option = new ilRadioOption($this->lng->txt("svy_self_ev_access_results_all"), ilObjSurvey::RESULTS_SELF_EVAL_ALL); - $evaluation_access->addOption($option); - - $form->addItem($evaluation_access); - break; - - default: - $evaluation_access = new ilRadioGroupInputGUI($this->lng->txt('evaluation_access'), "evaluation_access"); - - $option = new ilCheckboxOption($this->lng->txt("evaluation_access_off"), ilObjSurvey::EVALUATION_ACCESS_OFF, ''); - $option->setInfo($this->lng->txt("svy_evaluation_access_off_info")); - $evaluation_access->addOption($option); - - $option = new ilCheckboxOption($this->lng->txt("evaluation_access_all"), ilObjSurvey::EVALUATION_ACCESS_ALL, ''); - $option->setInfo($this->lng->txt("svy_evaluation_access_all_info")); - $evaluation_access->addOption($option); - - $option = new ilCheckboxOption($this->lng->txt("evaluation_access_participants"), ilObjSurvey::EVALUATION_ACCESS_PARTICIPANTS, ''); - $option->setInfo($this->lng->txt("svy_evaluation_access_participants_info")); - $evaluation_access->addOption($option); - - $evaluation_access->setValue($this->object->getEvaluationAccess()); - $form->addItem($evaluation_access); - - $anonymization_options = new ilRadioGroupInputGUI($this->lng->txt("survey_results_anonymization"), "anonymization_options"); - - $option = new ilCheckboxOption($this->lng->txt("survey_results_personalized"), "statpers"); - $option->setInfo($this->lng->txt("survey_results_personalized_info")); - $anonymization_options->addOption($option); - - $option = new ilCheckboxOption($this->lng->txt("survey_results_anonymized"), "statanon"); - $option->setInfo($this->lng->txt("survey_results_anonymized_info")); - $anonymization_options->addOption($option); - $anonymization_options->setValue($this->object->hasAnonymizedResults() - ? "statanon" - : "statpers"); - $form->addItem($anonymization_options); - - $surveySetting = new ilSetting("survey"); - if($surveySetting->get("anonymous_participants", false)) - { - $min = ""; - if($surveySetting->get("anonymous_participants_min", 0)) - { - $min = " (".$this->lng->txt("svy_anonymous_participants_min").": ". - $surveySetting->get("anonymous_participants_min").")"; - } - - $anon_list = new ilCheckboxInputGUI($this->lng->txt("svy_anonymous_participants_svy"), "anon_list"); - $anon_list->setInfo($this->lng->txt("svy_anonymous_participants_svy_info").$min); - $anon_list->setChecked($this->object->hasAnonymousUserList()); - $option->addSubItem($anon_list); - } - - if ($this->object->_hasDatasets($this->object->getSurveyId())) - { - $anonymization_options->setDisabled(true); - if($anon_list) - { - $anon_list->setDisabled(true); - } - } - break; - } - - // competence service activation for 360 mode - - include_once("./Services/Skill/classes/class.ilSkillManagementSettings.php"); - $skmg_set = new ilSkillManagementSettings(); - $svy_mode = $this->object->getMode(); - if(($svy_mode == ilObjSurvey::MODE_360 || $svy_mode == ilObjSurvey::MODE_SELF_EVAL) && $skmg_set->isActivated()) - { - $other = new ilFormSectionHeaderGUI(); - $other->setTitle($this->lng->txt("other")); - $form->addItem($other); - - $skill_service = new ilCheckboxInputGUI($this->lng->txt("survey_activate_skill_service"), "skill_service"); - $skill_service->setInfo($this->lng->txt("survey_activate_skill_service_info")); - $skill_service->setChecked($this->object->getSkillService()); - $form->addItem($skill_service); - } - - $position_settings = ilOrgUnitGlobalSettings::getInstance() - ->getObjectPositionSettingsByType($this->object->getType()); - - if($position_settings->isActive()) - { - // add additional feature section - $feat = new ilFormSectionHeaderGUI(); - $feat->setTitle($this->lng->txt('obj_features')); - $form->addItem($feat); - - // add orgunit settings - ilObjectServiceSettingsGUI::initServiceSettingsForm( - $this->object->getId(), - $form, - array( - ilObjectServiceSettingsGUI::ORGU_POSITION_ACCESS - ) - ); - } - - $form->addCommandButton("saveProperties", $this->lng->txt("save")); - - // remove items when using template - if($template_settings) - { - foreach($template_settings as $id => $item) - { - if($item["hide"]) - { - if ($id == "enabled_end_date") - { - $id = "end_date"; - } - if ($id == "enabled_start_date") - { - $id = "start_date"; - } - $form->removeItemByPostVar($id, true); - } - } - } - return $form; - } - - /** - * Add subtabs for tabs - * @param type $a_section - */ - function addSubTabs($a_section) - { - if($a_section == 'settings') - { - $this->tabs_gui->addSubTabTarget( - "settings", - $this->ctrl->getLinkTarget($this,'properties') - ); - - $lti_settings = new ilLTIProviderObjectSettingGUI($this->object->getRefId()); - if($lti_settings->hasSettingsAccess()) - { - $this->tabs_gui->addSubTabTarget( - 'lti_provider', - $this->ctrl->getLinkTargetByClass(ilLTIProviderObjectSettingGUI::class) - ); - } - } - } - - - /** - * Display and fill the properties form of the test - * - * @access public - */ - function propertiesObject(ilPropertyFormGUI $a_form = null) - { - $ilTabs = $this->tabs; - $ilHelp = $this->help; - - $this->checkPermission("write"); - - $this->addSubTabs('settings'); - $ilTabs->activateTab("settings"); - $ilTabs->activateSubTab('settings'); - - if ($this->object->get360Mode()) - { - $ilHelp->setScreenId("settings_360"); - } - - if(!$a_form) - { - $a_form = $this->initPropertiesForm(); - } - - // using template? - $message = ""; - if($this->object->getTemplate()) - { - $link = $this->ctrl->getLinkTarget($this, "confirmResetTemplate"); - $link = "".$this->lng->txt("survey_using_template_link").""; - $message = "
". - $this->tpl->getMessageHTML(sprintf($this->lng->txt("survey_using_template"), - ilSettingsTemplate::lookupTitle($this->object->getTemplate()), $link), "info"). // #10651 - "
"; - } - - $this->tpl->setContent($a_form->getHTML().$message); - } - - function doAutoCompleteObject() - { - $fields = array('login','firstname','lastname','email'); - - include_once './Services/User/classes/class.ilUserAutoComplete.php'; - $auto = new ilUserAutoComplete(); - $auto->setSearchFields($fields); - $auto->setResultField('login'); - $auto->enableFieldSearchableCheck(true); - $auto->setMoreLinkAvailable(true); - - if(($_REQUEST['fetchall'])) - { - $auto->setLimit(ilUserAutoComplete::MAX_ENTRIES); - } - - echo $auto->getList(ilUtil::stripSlashes($_REQUEST['term'])); - exit(); - } - - /** - * Enable all settings - Confirmation - */ - function confirmResetTemplateObject() - { - ilUtil::sendQuestion($this->lng->txt("survey_confirm_template_reset")); - $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.il_svy_svy_confirm_resettemplate.html", "Modules/Survey"); - $this->tpl->setCurrentBlock("adm_content"); - $this->tpl->setVariable("BTN_CONFIRM_REMOVE", $this->lng->txt("confirm")); - $this->tpl->setVariable("BTN_CANCEL_REMOVE", $this->lng->txt("cancel")); - $this->tpl->setVariable("FORM_ACTION", $this->ctrl->getFormAction($this, "resetTemplateObject")); - $this->tpl->parseCurrentBlock(); - } - - /** - * Enable all settings - remove template - */ - function resetTemplateObject() - { - $this->object->setTemplate(null); - $this->object->saveToDB(); - - ilUtil::sendSuccess($this->lng->txt("survey_template_reset"), true); - $this->ctrl->redirect($this, "properties"); - } - - - - // - // IMPORT/EXPORT - // - - protected function initImportForm($a_new_type) - { - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setTarget("_top"); - $form->setFormAction($this->ctrl->getFormAction($this)); - $form->setTitle($this->lng->txt("import_svy")); - - include_once("./Services/Form/classes/class.ilFileInputGUI.php"); - $fi = new ilFileInputGUI($this->lng->txt("import_file"), "importfile"); - $fi->setSuffixes(array("zip")); - $fi->setRequired(true); - $form->addItem($fi); - - include_once("./Modules/Survey/classes/class.ilObjSurvey.php"); - $svy = new ilObjSurvey(); - $questionspools = $svy->getAvailableQuestionpools(true, true, true); - - $pools = new ilSelectInputGUI($this->lng->txt("select_questionpool_short"), "spl"); - $pools->setOptions(array(""=>$this->lng->txt("dont_use_questionpool")) + $questionspools); - $pools->setRequired(false); - $form->addItem($pools); - - $form->addCommandButton("importSurvey", $this->lng->txt("import")); - $form->addCommandButton("cancel", $this->lng->txt("cancel")); - - return $form; - } - - /** - * form for new survey object import - */ - function importSurveyObject() - { - $tpl = $this->tpl; - - $parent_id = $_GET["ref_id"]; - $new_type = $_REQUEST["new_type"]; - - // create permission is already checked in createObject. This check here is done to prevent hacking attempts - $this->checkPermission("create", "", $new_type); - - $this->lng->loadLanguageModule($new_type); - $this->ctrl->setParameter($this, "new_type", $new_type); - - $form = $this->initImportForm($new_type); - if ($form->checkInput()) - { - include_once("./Modules/Survey/classes/class.ilObjSurvey.php"); - $newObj = new ilObjSurvey(); - $newObj->setType($new_type); - $newObj->setTitle("dummy"); - $newObj->create(true); - $this->putObjectInTree($newObj); - - // copy uploaded file to import directory - - $this->log->debug("form->getInput(spl) = ".$form->getInput("spl")); - - $error = $newObj->importObject($_FILES["importfile"], $form->getInput("spl")); - if (strlen($error)) - { - $newObj->delete(); - ilUtil::sendFailure($error); - return; - } - - ilUtil::sendSuccess($this->lng->txt("object_imported"),true); - ilUtil::redirect("ilias.php?ref_id=".$newObj->getRefId(). - "&baseClass=ilObjSurveyGUI"); - - // using template? - include_once "Services/Administration/classes/class.ilSettingsTemplate.php"; - $templates = ilSettingsTemplate::getAllSettingsTemplates("svy"); - if($templates) - { - $tpl = $this->tpl; - $tpl->addJavaScript("./Modules/Scorm2004/scripts/questions/jquery.js"); - // $tpl->addJavaScript("./Modules/Scorm2004/scripts/questions/jquery-ui-min.js"); - - $this->tpl->setCurrentBlock("template_option"); - $this->tpl->setVariable("VAL_TEMPLATE_OPTION", ""); - $this->tpl->setVariable("TXT_TEMPLATE_OPTION", $this->lng->txt("none")); - $this->tpl->parseCurrentBlock(); - - foreach($templates as $item) - { - $this->tpl->setCurrentBlock("template_option"); - $this->tpl->setVariable("VAL_TEMPLATE_OPTION", $item["id"]); - $this->tpl->setVariable("TXT_TEMPLATE_OPTION", $item["title"]); - $this->tpl->parseCurrentBlock(); - - $desc = str_replace("\n", "", nl2br($item["description"])); - $desc = str_replace("\r", "", $desc); - - $this->tpl->setCurrentBlock("js_data"); - $this->tpl->setVariable("JS_DATA_ID", $item["id"]); - $this->tpl->setVariable("JS_DATA_TEXT", $desc); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setCurrentBlock("templates"); - $this->tpl->setVariable("TXT_TEMPLATE", $this->lng->txt("svy_settings_template")); - $this->tpl->parseCurrentBlock(); - } - } - - // display form to correct errors - $form->setValuesByPost(); - $tpl->setContent($form->getHtml()); - } - - - // - // INFOSCREEN - // - - /** - * 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 infoScreenObject() - { - $this->ctrl->setCmd("showSummary"); - $this->ctrl->setCmdClass("ilinfoscreengui"); - $this->infoScreen(); - } - - /** - * show information screen - */ - function infoScreen() - { - $ilTabs = $this->tabs; - $ilUser = $this->user; - $ilToolbar = $this->toolbar; - $ilAccess = $this->access; - - if (!$this->external_rater_360) - { - if (!$this->checkPermissionBool("read")) - { - $this->checkPermission("visible"); - } - } - - $ilTabs->activateTab("info_short"); - - include_once "./Modules/Survey/classes/class.ilSurveyExecutionGUI.php"; - $output_gui = new ilSurveyExecutionGUI($this->object); - - include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); - $info = new ilInfoScreenGUI($this); - $info->enablePrivateNotes(); - - - $is_appraisee = false; - - // 360° - appraisee infos - if($this->object->get360Mode() && - $this->object->isAppraisee($ilUser->getId())) - { - $is_appraisee = true; - - $info->addSection($this->lng->txt("survey_360_appraisee_info")); - - $appr_data = $this->object->getAppraiseesData(); - $appr_data = $appr_data[$ilUser->getId()]; - $info->addProperty($this->lng->txt("survey_360_raters_status_info"), $appr_data["finished"]); - - if(!$appr_data["closed"]) - { - include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; - $button = ilLinkButton::getInstance(); - $button->setCaption("survey_360_appraisee_close_action"); - $button->setUrl($this->ctrl->getLinkTargetByClass("ilsurveyparticipantsgui", "confirmappraiseeclose")); - $close_button_360 = '
'.$button->render().'
'; - - $txt = "survey_360_appraisee_close_action_info"; - if($this->object->getSkillService()) - { - $txt .= "_skill"; - } - $info->addProperty($this->lng->txt("status"), - $close_button_360.$this->lng->txt($txt)); - } - else - { - ilDatePresentation::setUseRelativeDates(false); - - $dt = new ilDateTime($appr_data["closed"], IL_CAL_UNIX); - $info->addProperty($this->lng->txt("status"), - sprintf($this->lng->txt("survey_360_appraisee_close_action_status"), - ilDatePresentation::formatDate($dt))); - } - } - - - // handle (anonymous) code - - // validate incoming - $code_input = false; - $anonymous_code = $_POST["anonymous_id"]; - if ($anonymous_code) - { - $code_input = true; - // if(!$this->object->isUnusedCode($anonymous_code, $ilUser->getId())) - if(!$this->object->checkSurveyCode($anonymous_code)) // #15031 - valid as long survey is not finished - { - $anonymous_code = null; - } - else - { - // #15860 - $this->object->bindSurveyCodeToUser($ilUser->getId(), $anonymous_code); - } - } - if ($anonymous_code) - { - $_SESSION["anonymous_id"][$this->object->getId()] = $anonymous_code; - } - else - { - $anonymous_code = $_SESSION["anonymous_id"][$this->object->getId()]; - if($anonymous_code) - { - $code_input = true; - } - } - - // try to find code for current (registered) user from existing run - if($this->object->getAnonymize() && !$anonymous_code) - { - $anonymous_code = $this->object->findCodeForUser($ilUser->getId()); - } - - // get existing runs for current user, might generate code - $participant_status = $this->object->getUserSurveyExecutionStatus($anonymous_code); - if($participant_status) - { - $anonymous_code = $participant_status["code"]; - $participant_status = $participant_status["runs"]; - } - - // (final) check for proper anonymous code - if(!$this->object->isAccessibleWithoutCode() && - !$is_appraisee && - $code_input && // #11346 - (!$anonymous_code || !$this->object->isAnonymousKey($anonymous_code))) - { - $anonymous_code = null; - ilUtil::sendInfo($this->lng->txt("wrong_survey_code_used")); - } - - // :TODO: really save in session? - $_SESSION["anonymous_id"][$this->object->getId()] = $anonymous_code; - - if(ilObjSurvey::RESULTS_SELF_EVAL_ALL) { - $survey_started = $this->object->isSurveyStarted($ilUser->getId(), $anonymous_code, $ilUser->getId()); - } - else { - $survey_started = $this->object->isSurveyStarted($ilUser->getId(), $anonymous_code); - } - - $showButtons = $big_button = false; - - // already finished? - if(!$this->object->get360Mode() && - ($survey_started === 1 && // survey finished - !(!$this->object->isAccessibleWithoutCode() && !$anonymous_code && $ilUser->getId() == ANONYMOUS_USER_ID))) // not code accessible an no anonymous code and anonymous user (see #0020333) - { - ilUtil::sendInfo($this->lng->txt("already_completed_survey")); - - if($ilUser->getId() != ANONYMOUS_USER_ID) - { - if($this->object->hasViewOwnResults()) - { - include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; - $button = ilLinkButton::getInstance(); - $button->setCaption("svy_view_own_results"); - $button->setUrl($this->ctrl->getLinkTarget($this, "viewUserResults")); - $ilToolbar->addButtonInstance($button); - } - - // see ilSurveyExecutionGUI - if($this->object->hasMailConfirmation()) - { - if($this->object->hasViewOwnResults()) - { - $ilToolbar->addSeparator(); - } - - if($ilUser->getId() == ANONYMOUS_USER_ID || - !$ilUser->getEmail()) - { - require_once "Services/Form/classes/class.ilTextInputGUI.php"; - $mail = new ilTextInputGUI($this->lng->txt("email"), "mail"); - $mail->setSize(25); - $mail->setValue($ilUser->getEmail()); - $ilToolbar->addInputItem($mail, true); - } - - $ilToolbar->setFormAction($this->ctrl->getFormAction($this, "mailUserResults")); - - include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; - $button = ilSubmitButton::getInstance(); - $button->setCaption("svy_mail_send_confirmation"); - $button->setCommand("mailUserResults"); - $ilToolbar->addButtonInstance($button); - } - } - } - else - { - // "active" survey? - $canStart = $this->object->canStartSurvey(null, $this->external_rater_360); - - $showButtons = $canStart["result"]; - if (!$showButtons) - { - if($canStart["edit_settings"] && - $ilAccess->checkAccess("write", "", $this->ref_id)) - { - $canStart["messages"][] = "ctrl->getLinkTarget($this, "properties")."\">» ". - $this->lng->txt("survey_edit_settings").""; - } - ilUtil::sendInfo(implode("
", $canStart["messages"])); - } - } - - if ($showButtons) - { - // code is mandatory and not given yet - if(!$is_appraisee && - !$anonymous_code && - !$this->object->isAccessibleWithoutCode()) - { - $info->setFormAction($this->ctrl->getFormAction($this, "infoScreen")); - $info->addSection($this->lng->txt("anonymization")); - $info->addProperty("", $this->lng->txt("anonymize_anonymous_introduction")); - $info->addPropertyTextinput($this->lng->txt("enter_anonymous_id"), "anonymous_id", "", 8, "infoScreen", $this->lng->txt("submit"), true); - } - else - { - // trunk/default - if(!$this->object->get360Mode()) - { - if($anonymous_code) - { - $info->addHiddenElement("anonymous_id", $anonymous_code); - } - if ($survey_started === 0) - { - $big_button = array("resume", $this->lng->txt("resume_survey")); - } - elseif ($survey_started === FALSE) - { - $big_button = array("start", $this->lng->txt("start_survey")); - } - } - // 360° - else - { - $appr_ids = array(); - - // use given code (if proper external one) - if($anonymous_code) - { - $anonymous_id = $this->object->getAnonymousIdByCode($anonymous_code); - if($anonymous_id) - { - $appr_ids = $this->object->getAppraiseesToRate(0, $anonymous_id); - } - } - - // registered user - // if an auto-code was generated, we still have to check for the original user id - if(!$appr_ids && $ilUser->getId() != ANONYMOUS_USER_ID) - { - $appr_ids = $this->object->getAppraiseesToRate($ilUser->getId()); - } - - if(sizeof($appr_ids)) - { - // map existing runs to appraisees - $active_appraisees = array(); - if($participant_status) - { - foreach($participant_status as $item) - { - $active_appraisees[$item["appr_id"]] = $item["finished"]; - } - } - - $list = array(); - - foreach($appr_ids as $appr_id) - { - if($this->object->isAppraiseeClosed($appr_id)) - { - // closed - $list[$appr_id] = $this->lng->txt("survey_360_appraisee_is_closed"); - } - else if(array_key_exists($appr_id, $active_appraisees)) - { - // already done - if($active_appraisees[$appr_id]) - { - $list[$appr_id] = $this->lng->txt("already_completed_survey"); - } - // resume - else - { - $list[$appr_id] = array("resume", $this->lng->txt("resume_survey")); - } - } - else - { - // start - $list[$appr_id] = array("start", $this->lng->txt("start_survey")); - } - } - - $info->addSection($this->lng->txt("survey_360_rate_other_appraisees")); - - include_once "Services/User/classes/class.ilUserUtil.php"; - foreach($list as $appr_id => $item) - { - $appr_name = ilUserUtil::getNamePresentation($appr_id, false, false, "", true); - - if(!is_array($item)) - { - $info->addProperty($appr_name, $item); - } - else - { - $this->ctrl->setParameter($output_gui, "appr_id", $appr_id); - $href = $this->ctrl->getLinkTarget($output_gui, $item[0]); - $this->ctrl->setParameter($output_gui, "appr_id", ""); - - include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; - $button = ilLinkButton::getInstance(); - $button->setCaption($item[1], false); - $button->setUrl($href); - $big_button_360 = '
'.$button->render().'
'; - - $info->addProperty($appr_name, $big_button_360); - } - } - } - else if(!$is_appraisee) - { - ilUtil::sendFailure($this->lng->txt("survey_360_no_appraisees")); - } - } - } - - if($this->object->get360Mode() && - $this->object->get360SelfAppraisee() && - !$this->object->isAppraisee($ilUser->getId()) && - $ilUser->getId() != ANONYMOUS_USER_ID) // #14968 - { - $link = $this->ctrl->getLinkTargetByClass("ilsurveyparticipantsgui", "addSelfAppraisee"); - $link = ''.$this->lng->txt("survey_360_add_self_appraisee").''; - $info->addProperty(" ", $link); - } - } - - if($big_button) - { - $ilToolbar->setFormAction($this->ctrl->getFormAction($output_gui, "infoScreen")); - - include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; - $button = ilSubmitButton::getInstance(); - $button->setCaption($big_button[1], false); - $button->setCommand($big_button[0]); - $button->setPrimary(true); - $ilToolbar->addButtonInstance($button); - - $ilToolbar->setCloseFormTag(false); - $info->setOpenFormTag(false); - } - /* #12016 - else - { - $info->setFormAction($this->ctrl->getFormAction($output_gui, "infoScreen")); - } - */ - - if (strlen($this->object->getIntroduction())) - { - $introduction = $this->object->getIntroduction(); - $info->addSection($this->lng->txt("introduction")); - $info->addProperty("", $this->object->prepareTextareaOutput($introduction). - "
".$info->getHiddenToggleButton()); - } - else - { - $info->addSection(""); - $info->addProperty("", $info->getHiddenToggleButton()); - } - - $info->hideFurtherSections(false); - - if(!$this->object->get360Mode()) - { - $info->addSection($this->lng->txt("svy_general_properties")); - - $info->addProperty($this->lng->txt("survey_results_anonymization"), - !$this->object->hasAnonymizedResults() - ? $this->lng->txt("survey_results_personalized_info") - : $this->lng->txt("survey_results_anonymized_info")); - - include_once "./Modules/Survey/classes/class.ilObjSurveyAccess.php"; - if ($this->checkPermissionBool("write") || - ilObjSurveyAccess::_hasEvaluationAccess($this->object->getId(), $ilUser->getId())) - { - $info->addProperty($this->lng->txt("evaluation_access"), $this->lng->txt("evaluation_access_info")); - } - } - - $info->addMetaDataSections($this->object->getId(),0, $this->object->getType()); - - $this->ctrl->forwardCommand($info); - } - - function addLocatorItems() - { - $ilLocator = $this->locator; - switch ($this->ctrl->getCmd()) - { - case "next": - case "previous": - case "start": - case "resume": - case "redirectQuestion": - $ilLocator->addItem($this->object->getTitle(), $this->ctrl->getLinkTarget($this, "infoScreen"), "", $_GET["ref_id"]); - break; - case "evaluation": - case "checkEvaluationAccess": - case "evaluationdetails": - case "evaluationuser": - $ilLocator->addItem($this->object->getTitle(), $this->ctrl->getLinkTargetByClass("ilsurveyevaluationgui", "evaluation"), "", $_GET["ref_id"]); - break; - case "create": - case "save": - case "cancel": - case "importSurvey": - case "cloneAll": - break; - case "infoScreen": - $ilLocator->addItem($this->object->getTitle(), $this->ctrl->getLinkTarget($this, "infoScreen"), "", $_GET["ref_id"]); - break; - default: - $ilLocator->addItem($this->object->getTitle(), $this->ctrl->getLinkTarget($this, "infoScreen"), "", $_GET["ref_id"]); - - // this has to be done here because ilSurveyEditorGUI is called after finalizing the locator - if ((int)$_GET["q_id"] && !(int)$_REQUEST["new_for_survey"]) - { - // not on create - // see ilObjSurveyQuestionPool::addLocatorItems - $q_id = (int)$_GET["q_id"]; - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - $q_type = SurveyQuestion::_getQuestionType($q_id)."GUI"; - $this->ctrl->setParameterByClass($q_type, "q_id", $q_id); - $ilLocator->addItem(SurveyQuestion::_getTitle($q_id), - $this->ctrl->getLinkTargetByClass(array("ilSurveyEditorGUI", $q_type), "editQuestion")); - } - break; - } - } - + /** + * @var ilNavigationHistory + */ + protected $nav_history; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilLogger + */ + protected $log; + + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + $this->nav_history = $DIC["ilNavigationHistory"]; + $this->tabs = $DIC->tabs(); + $this->user = $DIC->user(); + $this->help = $DIC["ilHelp"]; + $this->rbacsystem = $DIC->rbac()->system(); + $this->tree = $DIC->repositoryTree(); + $this->tpl = $DIC["tpl"]; + $this->toolbar = $DIC->toolbar(); + $this->access = $DIC->access(); + $this->locator = $DIC["ilLocator"]; + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + + $this->type = "svy"; + $lng->loadLanguageModule("survey"); + $lng->loadLanguageModule("svy"); + $this->ctrl = $ilCtrl; + $this->ctrl->saveParameter($this, "ref_id"); + + $this->log = ilLoggerFactory::getLogger("svy"); + + parent::__construct("", (int) $_GET["ref_id"], true, false); + } + + public function executeCommand() + { + $ilNavigationHistory = $this->nav_history; + $ilTabs = $this->tabs; + + $this->external_rater_360 = false; + if (!$this->creation_mode && + $this->object->get360Mode() && + $_SESSION["anonymous_id"][$this->object->getId()] && + ilObjSurvey::validateExternalRaterCode( + $this->object->getRefId(), + $_SESSION["anonymous_id"][$this->object->getId()] + )) { + $this->external_rater_360 = true; + } + + if (!$this->external_rater_360) { + if (!$this->checkPermissionBool("visible") && + !$this->checkPermissionBool("read")) { + $this->checkPermission("read"); + } + + // add entry to navigation history + if (!$this->getCreationMode() && + $this->checkPermissionBool("read")) { + $this->ctrl->setParameterByClass("ilobjsurveygui", "ref_id", $this->ref_id); + $link = $this->ctrl->getLinkTargetByClass("ilobjsurveygui", ""); + $ilNavigationHistory->addItem($this->ref_id, $link, "svy"); + } + } + + $cmd = $this->ctrl->getCmd("properties"); + + // workaround for bug #6288, needs better solution + if ($cmd == "saveTags") { + $this->ctrl->setCmdClass("ilinfoscreengui"); + } + + // deep link from repository - "redirect" to page view + if (!$this->ctrl->getCmdClass() && $cmd == "questionsrepo") { + $_REQUEST["pgov"] = 1; + $this->ctrl->setCmd("questions"); + $this->ctrl->setCmdClass("ilsurveyeditorgui"); + } + + $next_class = $this->ctrl->getNextClass($this); + $this->ctrl->setReturn($this, "properties"); + $this->tpl->addCss(ilUtil::getStyleSheetLocation("output", "survey.css", "Modules/Survey"), "screen"); + $this->prepareOutput(); + + $this->log->debug("next_class= $next_class"); + switch ($next_class) { + case 'illtiproviderobjectsettinggui': + $this->addSubTabs('settings'); + $ilTabs->activateTab("settings"); + $ilTabs->activateSubTab('lti_provider'); + $lti_gui = new ilLTIProviderObjectSettingGUI($this->object->getRefId()); + $lti_gui->setCustomRolesForSelection($GLOBALS['DIC']->rbac()->review()->getLocalRoles($this->object->getRefId())); + $lti_gui->offerLTIRolesForSelection(false); + $this->ctrl->forwardCommand($lti_gui); + break; + + + case "ilinfoscreengui": + if (!in_array( + $this->ctrl->getCmdClass(), + array('ilpublicuserprofilegui', 'ilobjportfoliogui') + )) { + $this->addHeaderAction(); + $this->infoScreen(); // forwards command + } else { + // #16891 + $ilTabs->clearTargets(); + include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); + $info = new ilInfoScreenGUI($this); + $this->ctrl->forwardCommand($info); + } + break; + + case 'ilobjectmetadatagui': + $this->checkPermission("write"); + $ilTabs->activateTab("meta_data"); + $this->addHeaderAction(); + include_once 'Services/Object/classes/class.ilObjectMetaDataGUI.php'; + $md_gui = new ilObjectMetaDataGUI($this->object); + $this->ctrl->forwardCommand($md_gui); + break; + + case "ilsurveyevaluationgui": + $ilTabs->activateTab("svy_results"); + $this->addHeaderAction(); + include_once("./Modules/Survey/classes/class.ilSurveyEvaluationGUI.php"); + $eval_gui = new ilSurveyEvaluationGUI($this->object); + $this->ctrl->forwardCommand($eval_gui); + break; + + case "ilsurveyexecutiongui": + $ilTabs->clearTargets(); + include_once("./Modules/Survey/classes/class.ilSurveyExecutionGUI.php"); + $exec_gui = new ilSurveyExecutionGUI($this->object); + $this->ctrl->forwardCommand($exec_gui); + break; + + case 'ilpermissiongui': + $ilTabs->activateTab("perm_settings"); + $this->addHeaderAction(); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $this->ctrl->forwardCommand($perm_gui); + break; + + case 'ilobjectcopygui': + include_once './Services/Object/classes/class.ilObjectCopyGUI.php'; + $cp = new ilObjectCopyGUI($this); + $cp->setType('svy'); + $this->ctrl->forwardCommand($cp); + break; + + case "ilcommonactiondispatchergui": + include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); + $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); + $this->ctrl->forwardCommand($gui); + break; + + // 360, skill service + case 'ilsurveyskillgui': + $ilTabs->activateTab("survey_competences"); + include_once("./Modules/Survey/classes/class.ilSurveySkillGUI.php"); + $gui = new ilSurveySkillGUI($this->object); + $this->ctrl->forwardCommand($gui); + break; + + case 'ilsurveyskilldeterminationgui': + $ilTabs->activateTab("maintenance"); + include_once("./Modules/Survey/classes/class.ilSurveySkillDeterminationGUI.php"); + $gui = new ilSurveySkillDeterminationGUI($this->object); + $this->ctrl->forwardCommand($gui); + break; + + case 'ilsurveyeditorgui': + $this->checkPermission("write"); + $ilTabs->activateTab("survey_questions"); + include_once("./Modules/Survey/classes/class.ilSurveyEditorGUI.php"); + $gui = new ilSurveyEditorGUI($this); + $this->ctrl->forwardCommand($gui); + break; + + case 'ilsurveyconstraintsgui': + $this->checkPermission("write"); + $ilTabs->activateTab("constraints"); + include_once("./Modules/Survey/classes/class.ilSurveyConstraintsGUI.php"); + $gui = new ilSurveyConstraintsGUI($this); + $this->ctrl->forwardCommand($gui); + break; + + case 'ilsurveyparticipantsgui': + if ($this->object->getMode() == ilObjSurvey::MODE_STANDARD || $this->object->getMode() == ilObjSurvey::MODE_SELF_EVAL) { + $ilTabs->activateTab("maintenance"); + } else { + $ilTabs->activateTab("survey_360_appraisees"); + } + include_once("./Modules/Survey/classes/class.ilSurveyParticipantsGUI.php"); + //$gui = new ilSurveyParticipantsGUI($this, $this->checkPermissionBool("write")); + $gui = new ilSurveyParticipantsGUI($this, $this->checkRbacOrPositionPermission('read_results', 'access_results')); + $this->ctrl->forwardCommand($gui); + break; + + case "illearningprogressgui": + $ilTabs->activateTab("learning_progress"); + include_once("./Services/Tracking/classes/class.ilLearningProgressGUI.php"); + $new_gui = new ilLearningProgressGUI( + ilLearningProgressBaseGUI::LP_CONTEXT_REPOSITORY, + $this->object->getRefId() + ); + $this->ctrl->forwardCommand($new_gui); + break; + + case 'ilexportgui': + $ilTabs->activateTab("export"); + include_once("./Services/Export/classes/class.ilExportGUI.php"); + $exp_gui = new ilExportGUI($this); + $exp_gui->addFormat("xml"); + $this->ctrl->forwardCommand($exp_gui); + break; + + default: + $this->addHeaderAction(); + $cmd.= "Object"; + + $this->log->debug("Default cmd= $cmd"); + + $this->$cmd(); + break; + } + + if (strtolower($_GET["baseClass"]) != "iladministrationgui" && + $this->getCreationMode() != true) { + $this->tpl->show(); + } + } + + /** + * Redirects the evaluation object call to the ilSurveyEvaluationGUI class + * + * Coming from ListGUI... + * + * @access private + */ + public function evaluationObject() + { + include_once("./Modules/Survey/classes/class.ilSurveyEvaluationGUI.php"); + $eval_gui = new ilSurveyEvaluationGUI($this->object); + $this->ctrl->setCmdClass(get_class($eval_gui)); + $this->ctrl->redirect($eval_gui, "evaluation"); + } + + protected function addDidacticTemplateOptions(array &$a_options) + { + include_once "Services/Administration/classes/class.ilSettingsTemplate.php"; + $templates = ilSettingsTemplate::getAllSettingsTemplates("svy"); + if ($templates) { + foreach ($templates as $item) { + $a_options["svytpl_" . $item["id"]] = array($item["title"], + nl2br(trim($item["description"]))); + } + } + + // JF, 2013-06-10 + $a_options["svy360_1"] = array($this->lng->txt("survey_360_mode"), + $this->lng->txt("survey_360_mode_info")); + + //Self evaluation only + $a_options["svyselfeval_1"] = array($this->lng->txt("svy_self_ev_mode"), + $this->lng->txt("svy_self_ev_info")); + } + + /** + * save object + * @access public + */ + public function afterSave(ilObject $a_new_object) + { + // #16446 + $a_new_object->loadFromDb(); + + $tpl = $this->getDidacticTemplateVar("svytpl"); + if ($tpl) { + $a_new_object->applySettingsTemplate($tpl); + } else { + //set the mode depending on didactic template + if ($this->getDidacticTemplateVar("svy360")) { + $a_new_object->setMode(ilObjSurvey::MODE_360); + } elseif ($this->getDidacticTemplateVar("svyselfeval")) { + $a_new_object->setMode(ilObjSurvey::MODE_SELF_EVAL); + } + } + + $svy_mode = $a_new_object->getMode(); + if ($svy_mode == ilObjSurvey::MODE_360) { + // this should rather be ilObjSurvey::ANONYMIZE_ON - see ilObjSurvey::getUserDataFromActiveId() + $a_new_object->setAnonymize(ilObjSurvey::ANONYMIZE_CODE_ALL); + $a_new_object->setEvaluationAccess(ilObjSurvey::EVALUATION_ACCESS_PARTICIPANTS); + } elseif ($svy_mode == ilObjSurvey::MODE_SELF_EVAL) { + $a_new_object->setEvaluationAccess(ilObjSurvey::EVALUATION_ACCESS_PARTICIPANTS); + } + $a_new_object->saveToDB(); + + // always send a message + ilUtil::sendSuccess($this->lng->txt("object_added"), true); + ilUtil::redirect("ilias.php?baseClass=ilObjSurveyGUI&ref_id=" . + $a_new_object->getRefId() . "&cmd=properties"); + } + + /** + * adds tabs to tab gui object + * + * @param object $tabs_gui ilTabsGUI object + */ + public function getTabs() + { + $ilUser = $this->user; + $ilHelp = $this->help; + + if ($this->object instanceof ilObjSurveyQuestionPool) { + return true; + } + + $ilHelp->setScreenIdComponent("svy"); + + $hidden_tabs = array(); + $template = $this->object->getTemplate(); + if ($template) { + include_once "Services/Administration/classes/class.ilSettingsTemplate.php"; + $template = new ilSettingsTemplate($template); + $hidden_tabs = $template->getHiddenTabs(); + } + + if ($this->checkPermissionBool("write")) { + $this->tabs_gui->addTab( + "survey_questions", + $this->lng->txt("survey_questions"), + $this->ctrl->getLinkTargetByClass(array("ilsurveyeditorgui", "ilsurveypagegui"), "renderPage") + ); + } + + if ($this->checkPermissionBool("read")) { + $this->tabs_gui->addTab( + "info_short", + $this->lng->txt("info_short"), + $this->ctrl->getLinkTarget($this, 'infoScreen') + ); + } + + // properties + if ($this->checkPermissionBool("write")) { + $this->tabs_gui->addTab( + "settings", + $this->lng->txt("settings"), + $this->ctrl->getLinkTarget($this, 'properties') + ); + } elseif ($this->checkPermissionBool("read")) { + if ($this->object->get360Mode() && + $this->object->get360SelfRaters() && + $this->object->isAppraisee($ilUser->getId()) && + !$this->object->isAppraiseeClosed($ilUser->getId())) { + $this->tabs_gui->addTab( + "survey_360_edit_raters", + $this->lng->txt("survey_360_edit_raters"), + $this->ctrl->getLinkTargetByClass('ilsurveyparticipantsgui', 'editRaters') + ); + + // :TODO: mail to raters + } + } + + // questions + if ($this->checkPermissionBool("write") && + !in_array("constraints", $hidden_tabs) && + $this->object->getMode() == ilObjSurvey::MODE_STANDARD) { + // constraints (tab called routing) + $this->tabs_gui->addTab( + "constraints", + $this->lng->txt("constraints"), + $this->ctrl->getLinkTargetByClass("ilsurveyconstraintsgui", "constraints") + ); + } + + if ($this->checkPermissionBool("write")) { + switch ($this->object->getMode()) { + case ilObjSurvey::MODE_360: + // 360 mode + competence service + include_once("./Services/Skill/classes/class.ilSkillManagementSettings.php"); + $skmg_set = new ilSkillManagementSettings(); + if ($this->object->getSkillService() && $skmg_set->isActivated()) { + $this->tabs_gui->addTab( + "survey_competences", + $this->lng->txt("survey_competences"), + $this->ctrl->getLinkTargetByClass("ilsurveyskillgui", "listQuestionAssignment") + ); + } + $this->tabs_gui->addTab( + "survey_360_appraisees", + $this->lng->txt("survey_360_appraisees"), + $this->ctrl->getLinkTargetByClass('ilsurveyparticipantsgui', 'listAppraisees') + ); + break; + + case ilObjSurvey::MODE_SELF_EVAL: + include_once("./Services/Skill/classes/class.ilSkillManagementSettings.php"); + $skmg_set = new ilSkillManagementSettings(); + if ($this->object->getSkillService() && $skmg_set->isActivated()) { + $this->tabs_gui->addTab( + "survey_competences", + $this->lng->txt("survey_competences"), + $this->ctrl->getLinkTargetByClass("ilsurveyskillgui", "listQuestionAssignment") + ); + } + $this->tabs_gui->addTab( + "maintenance", + $this->lng->txt("maintenance"), + $this->ctrl->getLinkTargetByClass('ilsurveyparticipantsgui', 'maintenance') + ); + break; + + default: + // maintenance (tab called participants) + $this->tabs_gui->addTab( + "maintenance", + $this->lng->txt("maintenance"), + $this->ctrl->getLinkTargetByClass('ilsurveyparticipantsgui', 'maintenance') + ); + break; + } + } + + include_once "./Modules/Survey/classes/class.ilObjSurveyAccess.php"; + if ( + $this->checkRbacOrPositionPermission('read_results', 'access_results') || + ilObjSurveyAccess::_hasEvaluationAccess($this->object->getId(), $ilUser->getId())) { + // evaluation + $this->tabs_gui->addTab( + "svy_results", + $this->lng->txt("svy_results"), + $this->ctrl->getLinkTargetByClass("ilsurveyevaluationgui", "evaluation") + ); + } + + // learning progress + include_once "./Services/Tracking/classes/class.ilLearningProgressAccess.php"; + if (ilLearningProgressAccess::checkAccess($this->object->getRefId())) { + $this->tabs_gui->addTarget( + "learning_progress", + $this->ctrl->getLinkTargetByClass(array("ilobjsurveygui", "illearningprogressgui"), ""), + "", + array("illplistofobjectsgui", "illplistofsettingsgui", "illearningprogressgui", "illplistofprogressgui") + ); + } + + if ($this->checkPermissionBool("write")) { + if (!in_array("meta_data", $hidden_tabs)) { + // meta data + include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php"; + $mdgui = new ilObjectMetaDataGUI($this->object); + $mdtab = $mdgui->getTab(); + if ($mdtab) { + $this->tabs_gui->addTab( + "meta_data", + $this->lng->txt("meta_data"), + $mdtab + ); + } + } + + if (!in_array("export", $hidden_tabs)) { + // export + $this->tabs_gui->addTab( + "export", + $this->lng->txt("export"), + $this->ctrl->getLinkTargetByClass("ilexportgui", "") + ); + } + } + + if ($this->checkPermissionBool("edit_permission")) { + // permissions + $this->tabs_gui->addTab( + "perm_settings", + $this->lng->txt("perm_settings"), + $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm") + ); + } + } + + + // + // SETTINGS + // + + /** + * Save the survey properties + * + * Save the survey properties + * + * @access private + */ + public function savePropertiesObject() + { + $rbacsystem = $this->rbacsystem; + $obj_service = $this->object_service; + + $form = $this->initPropertiesForm(); + if ($form->checkInput()) { + $valid = true; + + if (!$this->object->get360Mode()) { + if ($form->getInput("tut")) { + // check if given "tutors" have write permission + $tut_ids =array(); + $tut_logins = $form->getInput("tut_ids"); + foreach ($tut_logins as $tut_login) { + $tut_id = ilObjUser::_lookupId($tut_login); + if ($tut_id && $rbacsystem->checkAccessOfUser($tut_id, "write", $this->object->getRefId())) { + $tut_ids[] = $tut_id; + } + } + if (!$tut_ids) { + $tut_ids = $form->getItemByPostVar("tut_ids"); + $tut_ids->setAlert($this->lng->txt("survey_notification_tutor_recipients_invalid")); + $valid = false; + } + } + } + + if ($valid) { + if ($form->getInput("rmd")) { + $rmd_start = $form->getItemByPostVar("rmd_start")->getDate(); + $rmd_end = $form->getItemByPostVar("rmd_end")->getDate(); + if ($rmd_end) { + if ($rmd_start->get(IL_CAL_UNIX) > $rmd_end->get(IL_CAL_UNIX)) { + $tmp = $rmd_start; + $rmd_start = $rmd_end; + $rmd_end = $tmp; + } + } + $this->object->setReminderStatus(true); + $this->object->setReminderStart($rmd_start); + $this->object->setReminderEnd($rmd_end); + $this->object->setReminderFrequency($form->getInput("rmd_freq")); + if (!$this->object->get360Mode()) { + $this->object->setReminderTarget($form->getInput("rmd_grp")); + $this->object->setReminderTemplate(($form->getInput("rmdt") > 0) + ? $form->getInput("rmdt") + : null); + } else { + if ($form->getInput("remind_appraisees") && $form->getInput("remind_raters")) { + $this->object->setReminderTarget(ilObjSurvey::NOTIFICATION_APPRAISEES_AND_RATERS); + } elseif ($form->getInput("remind_appraisees")) { + $this->object->setReminderTarget(ilObjSurvey::NOTIFICATION_APPRAISEES); + } elseif ($form->getInput("remind_raters")) { + $this->object->setReminderTarget(ilObjSurvey::NOTIFICATION_RATERS); + } else { + $this->object->setReminderTarget(0); + } + } + } else { + $this->object->setReminderStatus(false); + } + + if (!$this->object->get360Mode()) { + if ($form->getInput("tut")) { + $this->object->setTutorNotificationStatus(true); + $this->object->setTutorNotificationRecipients($tut_ids); // see above + $this->object->setTutorNotificationTarget($form->getInput("tut_grp")); + } else { + $this->object->setTutorNotificationStatus(false); + } + } + + // #10055 + if ($_POST['online'] && count($this->object->questions) == 0) { + $_POST['online'] = null; + ilUtil::sendFailure($this->lng->txt("cannot_switch_to_online_no_questions"), true); + } + + $template_settings = null; + $template = $this->object->getTemplate(); + if ($template) { + include_once "Services/Administration/classes/class.ilSettingsTemplate.php"; + $template = new ilSettingsTemplate($template); + $template_settings = $template->getSettings(); + } + + include_once 'Services/MetaData/classes/class.ilMD.php'; + $md_obj = new ilMD($this->object->getId(), 0, "svy"); + $md_section = $md_obj->getGeneral(); + + // title + $md_section->setTitle(ilUtil::stripSlashes($_POST['title'])); + $md_section->update(); + + // Description + $md_desc_ids = $md_section->getDescriptionIds(); + if ($md_desc_ids) { + $md_desc = $md_section->getDescription(array_pop($md_desc_ids)); + $md_desc->setDescription(ilUtil::stripSlashes($_POST['description'])); + $md_desc->update(); + } + + $this->object->setViewOwnResults($_POST["view_own"]); + $this->object->setMailOwnResults($_POST["mail_own"]); + $this->object->setMailConfirmation($_POST["mail_confirm"]); + + // both are saved in object, too + $this->object->setTitle(ilUtil::stripSlashes($_POST['title'])); + $this->object->setDescription(ilUtil::stripSlashes($_POST['description'])); + $this->object->setOfflineStatus((bool) !$_POST['online']); + $this->object->update(); + + // activation + $period = $form->getItemByPostVar("access_period"); + if ($period->getStart() && $period->getEnd()) { + $this->object->setActivationLimited(true); + $this->object->setActivationVisibility($_POST["access_visiblity"]); + $this->object->setActivationStartDate($period->getStart()->get(IL_CAL_UNIX)); + $this->object->setActivationEndDate($period->getEnd()->get(IL_CAL_UNIX)); + } else { + $this->object->setActivationLimited(false); + } + + // tile image + $obj_service->commonSettings()->legacyForm($form, $this->object)->saveTileImage(); + + + if (!$template_settings["enabled_start_date"]["hide"]) { + $start = $form->getItemByPostVar("start_date"); + if ($start->getDate()) { + $datetime = explode(" ", $start->getDate()->get(IL_CAL_DATETIME)); + $this->object->setStartDateAndTime($datetime[0], $datetime[1]); + } else { + $this->object->setStartDate(null); + } + } + + if (!$template_settings["enabled_end_date"]["hide"]) { + $end = $form->getItemByPostVar("end_date"); + if ($end->getDate()) { + $datetime = explode(" ", $end->getDate()->get(IL_CAL_DATETIME)); + $this->object->setEndDateAndTime($datetime[0], $datetime[1]); + } else { + $this->object->setEndDate(null); + } + } + + + include_once "./Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php"; + $introduction = $_POST["introduction"]; + $this->object->setIntroduction($introduction); + $outro = $_POST["outro"]; + $this->object->setOutro($outro); + + if (!$template_settings["show_question_titles"]["hide"]) { + $this->object->setShowQuestionTitles($_POST["show_question_titles"]); + } + + if (!$template_settings["use_pool"]["hide"]) { + $this->object->setPoolUsage($_POST["use_pool"]); + } + + $this->object->setMailNotification($_POST['mailnotification']); + $this->object->setMailAddresses($_POST['mailaddresses']); + $this->object->setMailParticipantData($_POST['mailparticipantdata']); + + switch ($this->object->getMode()) { + case ilObjSurvey::MODE_360: + $this->object->set360SelfEvaluation((bool) $_POST["self_eval"]); + $this->object->set360SelfAppraisee((bool) $_POST["self_appr"]); + $this->object->set360SelfRaters((bool) $_POST["self_rate"]); + $this->object->set360Results((int) $_POST["ts_res"]);; + $this->object->setSkillService((int) $_POST["skill_service"]); + break; + case ilObjSurvey::MODE_SELF_EVAL: + $this->object->setSelfEvaluationResults($_POST["self_eval_res"]); + $this->object->setSkillService((int) $_POST["skill_service"]); + break; + default: + if (!$template_settings["evaluation_access"]["hide"]) { + $this->object->setEvaluationAccess($_POST["evaluation_access"]); + } + + $hasDatasets = ilObjSurvey::_hasDatasets($this->object->getSurveyId()); + if (!$hasDatasets) { + $hide_codes = $template_settings["acc_codes"]["hide"]; + $hide_anon = $template_settings["anonymization_options"]["hide"]; + if (!$hide_codes || !$hide_anon) { + $current = $this->object->getAnonymize(); + + // get current setting if property is hidden + if (!$hide_codes) { + $codes = (bool) $_POST["acc_codes"]; + } else { + $codes = ($current == ilObjSurvey::ANONYMIZE_CODE_ALL || + $current == ilObjSurvey::ANONYMIZE_ON); + } + if (!$hide_anon) { + $anon = ((string) $_POST["anonymization_options"] == "statanon"); + } else { + $anon = ($current == ilObjSurvey::ANONYMIZE_FREEACCESS || + $current == ilObjSurvey::ANONYMIZE_ON); + } + + // parse incoming values + if (!$anon) { + if (!$codes) { + $this->object->setAnonymize(ilObjSurvey::ANONYMIZE_OFF); + } else { + $this->object->setAnonymize(ilObjSurvey::ANONYMIZE_CODE_ALL); + } + } else { + if ($codes) { + $this->object->setAnonymize(ilObjSurvey::ANONYMIZE_ON); + } else { + $this->object->setAnonymize(ilObjSurvey::ANONYMIZE_FREEACCESS); + } + + $this->object->setAnonymousUserList($_POST["anon_list"]); + } + + // if settings were changed get rid of existing code + unset($_SESSION["anonymous_id"][$this->object->getId()]); + } + } + break; + } + + $this->object->saveToDb(); + + ilObjectServiceSettingsGUI::updateServiceSettingsForm( + $this->object->getId(), + $form, + array( + ilObjectServiceSettingsGUI::ORGU_POSITION_ACCESS + ) + ); + + if (strcmp($_SESSION["info"], "") != 0) { + ilUtil::sendSuccess($_SESSION["info"] . "
" . $this->lng->txt("settings_saved"), true); + } else { + ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); + } + $this->ctrl->redirect($this, "properties"); + } else { + // #16714 + ilUtil::sendFailure($this->lng->txt("form_input_not_valid")); + } + } + + $form->setValuesByPost(); + $this->propertiesObject($form); + } + + /** + * Init survey settings form + * + * @return ilPropertyFormGUI + */ + public function initPropertiesForm() + { + $obj_service = $this->object_service; + + $template_settings = $hide_rte_switch = null; + $template = $this->object->getTemplate(); + if ($template) { + include_once "Services/Administration/classes/class.ilSettingsTemplate.php"; + $template = new ilSettingsTemplate($template); + + $template_settings = $template->getSettings(); + $hide_rte_switch = $template_settings["rte_switch"]["hide"]; + } + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this)); + $form->setTableWidth("100%"); + $form->setId("survey_properties"); + + // general properties + $header = new ilFormSectionHeaderGUI(); + $header->setTitle($this->lng->txt("settings")); + $form->addItem($header); + + + // title & description (meta data) + + include_once 'Services/MetaData/classes/class.ilMD.php'; + $md_obj = new ilMD($this->object->getId(), 0, "svy"); + $md_section = $md_obj->getGeneral(); + + $title = new ilTextInputGUI($this->lng->txt("title"), "title"); + $title->setRequired(true); + $title->setValue($md_section->getTitle()); + $form->addItem($title); + + $ids = $md_section->getDescriptionIds(); + if ($ids) { + $desc_obj = $md_section->getDescription(array_pop($ids)); + + $desc = new ilTextAreaInputGUI($this->lng->txt("description"), "description"); + $desc->setCols(50); + $desc->setRows(4); + $desc->setValue($desc_obj->getDescription()); + $form->addItem($desc); + } + + // pool usage + $pool_usage = new ilRadioGroupInputGUI($this->lng->txt("survey_question_pool_usage"), "use_pool"); + $opt = new ilRadioOption($this->lng->txt("survey_question_pool_usage_active"), 1); + $opt->setInfo($this->lng->txt("survey_question_pool_usage_active_info")); + $pool_usage->addOption($opt); + $opt = new ilRadioOption($this->lng->txt("survey_question_pool_usage_inactive"), 0); + $opt->setInfo($this->lng->txt("survey_question_pool_usage_inactive_info")); + $pool_usage->addOption($opt); + $pool_usage->setValue($this->object->getPoolUsage()); + $form->addItem($pool_usage); + + // 360°: appraisees + if ($this->object->get360Mode()) { + $self_eval = new ilCheckboxInputGUI($this->lng->txt("survey_360_self_evaluation"), "self_eval"); + $self_eval->setInfo($this->lng->txt("survey_360_self_evaluation_info")); + $self_eval->setChecked($this->object->get360SelfEvaluation()); + $form->addItem($self_eval); + + $self_rate = new ilCheckboxInputGUI($this->lng->txt("survey_360_self_raters"), "self_rate"); + $self_rate->setInfo($this->lng->txt("survey_360_self_raters_info")); + $self_rate->setChecked($this->object->get360SelfRaters()); + $form->addItem($self_rate); + + $self_appr = new ilCheckboxInputGUI($this->lng->txt("survey_360_self_appraisee"), "self_appr"); + $self_appr->setInfo($this->lng->txt("survey_360_self_appraisee_info")); + $self_appr->setChecked($this->object->get360SelfAppraisee()); + $form->addItem($self_appr); + } + + + // activation + + include_once "Services/Object/classes/class.ilObjectActivation.php"; + $this->lng->loadLanguageModule('rep'); + + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($this->lng->txt('rep_activation_availability')); + $form->addItem($section); + + // additional info only with multiple references + $act_obj_info = $act_ref_info = ""; + if (sizeof(ilObject::_getAllReferences($this->object->getId())) > 1) { + $act_obj_info = ' ' . $this->lng->txt('rep_activation_online_object_info'); + $act_ref_info = $this->lng->txt('rep_activation_access_ref_info'); + } + + $online = new ilCheckboxInputGUI($this->lng->txt('rep_activation_online'), 'online'); + $online->setInfo($this->lng->txt('svy_activation_online_info') . $act_obj_info); + $online->setChecked(!$this->object->getOfflineStatus()); + $form->addItem($online); + + include_once "Services/Form/classes/class.ilDateDurationInputGUI.php"; + $dur = new ilDateDurationInputGUI($this->lng->txt('rep_visibility_until'), "access_period"); + $dur->setShowTime(true); + $date = $this->object->getActivationStartDate(); + $dur->setStart($date + ? new ilDateTime($date, IL_CAL_UNIX) + : null); + $date = $this->object->getActivationEndDate(); + $dur->setEnd($date + ? new ilDateTime($date, IL_CAL_UNIX) + : null); + $form->addItem($dur); + + $visible = new ilCheckboxInputGUI($this->lng->txt('rep_activation_limited_visibility'), 'access_visiblity'); + $visible->setInfo($this->lng->txt('svy_activation_limited_visibility_info')); + $visible->setChecked($this->object->getActivationVisibility()); + $dur->addSubItem($visible); + + // presentation + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($this->lng->txt('obj_presentation')); + $form->addItem($section); + + // tile image + $obj_service->commonSettings()->legacyForm($form, $this->object)->addTileImage(); + + // before start + + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($this->lng->txt('svy_settings_section_before_start')); + $form->addItem($section); + + // introduction + $intro = new ilTextAreaInputGUI($this->lng->txt("introduction"), "introduction"); + $intro->setValue($this->object->prepareTextareaOutput($this->object->getIntroduction())); + $intro->setRows(10); + $intro->setCols(80); + $intro->setUseRte(true); + $intro->setInfo($this->lng->txt("survey_introduction_info")); + include_once "./Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php"; + $intro->setRteTags(ilObjAdvancedEditing::_getUsedHTMLTags("survey")); + $intro->addPlugin("latex"); + $intro->addButton("latex"); + $intro->addButton("pastelatex"); + $intro->setRTESupport($this->object->getId(), "svy", "survey", null, $hide_rte_switch); + $form->addItem($intro); + + + // access + + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($this->lng->txt('svy_settings_section_access')); + $form->addItem($section); + + // enable start date + $start = $this->object->getStartDate(); + // start date + $startingtime = new ilDateTimeInputGUI($this->lng->txt("start_date"), 'start_date'); + $startingtime->setShowTime(true); + if ($start) { + $startingtime->setDate(new ilDate($start, IL_CAL_TIMESTAMP)); + } + $form->addItem($startingtime); + + // enable end date + $end = $this->object->getEndDate(); + // end date + $endingtime = new ilDateTimeInputGUI($this->lng->txt("end_date"), 'end_date'); + $endingtime->setShowTime(true); + if ($end) { + $endingtime->setDate(new ilDate($end, IL_CAL_TIMESTAMP)); + } + $form->addItem($endingtime); + + // anonymization + if (!$this->object->get360Mode()) { + $codes = new ilCheckboxInputGUI($this->lng->txt("survey_access_codes"), "acc_codes"); + $codes->setInfo($this->lng->txt("survey_access_codes_info")); + $codes->setChecked(!$this->object->isAccessibleWithoutCode()); + $form->addItem($codes); + + if (ilObjSurvey::_hasDatasets($this->object->getSurveyId())) { + $codes->setDisabled(true); + } + } + + + // question behaviour + + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($this->lng->txt('svy_settings_section_question_behaviour')); + $form->addItem($section); + + // show question titles + $show_question_titles = new ilCheckboxInputGUI($this->lng->txt("svy_show_questiontitles"), "show_question_titles"); + $show_question_titles->setValue(1); + $show_question_titles->setChecked($this->object->getShowQuestionTitles()); + $form->addItem($show_question_titles); + + + // finishing + + $info = new ilFormSectionHeaderGUI(); + $info->setTitle($this->lng->txt("svy_settings_section_finishing")); + $form->addItem($info); + + $view_own = new ilCheckboxInputGUI($this->lng->txt("svy_results_view_own"), "view_own"); + $view_own->setInfo($this->lng->txt("svy_results_view_own_info")); + $view_own->setChecked($this->object->hasViewOwnResults()); + $form->addItem($view_own); + + $mail_confirm = new ilCheckboxInputGUI($this->lng->txt("svy_results_mail_confirm"), "mail_confirm"); + $mail_confirm->setInfo($this->lng->txt("svy_results_mail_confirm_info")); + $mail_confirm->setChecked($this->object->hasMailConfirmation()); + $form->addItem($mail_confirm); + + $mail_own = new ilCheckboxInputGUI($this->lng->txt("svy_results_mail_own"), "mail_own"); + $mail_own->setInfo($this->lng->txt("svy_results_mail_own_info")); + $mail_own->setChecked($this->object->hasMailOwnResults()); + $mail_confirm->addSubItem($mail_own); + + // final statement + $finalstatement = new ilTextAreaInputGUI($this->lng->txt("outro"), "outro"); + $finalstatement->setValue($this->object->prepareTextareaOutput($this->object->getOutro())); + $finalstatement->setRows(10); + $finalstatement->setCols(80); + $finalstatement->setUseRte(true); + $finalstatement->setRteTags(ilObjAdvancedEditing::_getUsedHTMLTags("survey")); + $finalstatement->addPlugin("latex"); + $finalstatement->addButton("latex"); + $finalstatement->addButton("pastelatex"); + $finalstatement->setRTESupport($this->object->getId(), "svy", "survey", null, $hide_rte_switch); + $form->addItem($finalstatement); + + // mail notification + $mailnotification = new ilCheckboxInputGUI($this->lng->txt("mailnotification"), "mailnotification"); + // $mailnotification->setOptionTitle($this->lng->txt("activate")); + $mailnotification->setInfo($this->lng->txt("svy_result_mail_notification_info")); // #11762 + $mailnotification->setValue(1); + $mailnotification->setChecked($this->object->getMailNotification()); + + // addresses + $mailaddresses = new ilTextInputGUI($this->lng->txt("mailaddresses"), "mailaddresses"); + $mailaddresses->setValue($this->object->getMailAddresses()); + $mailaddresses->setSize(80); + $mailaddresses->setInfo($this->lng->txt('mailaddresses_info')); + $mailaddresses->setRequired(true); + + // participant data + $participantdata = new ilTextAreaInputGUI($this->lng->txt("mailparticipantdata"), "mailparticipantdata"); + $participantdata->setValue($this->object->getMailParticipantData()); + $participantdata->setRows(6); + $participantdata->setCols(80); + $participantdata->setUseRte(false); + $participantdata->setInfo($this->lng->txt("mailparticipantdata_info")); + + // #12755 - because of privacy concerns we restrict user data to a minimum + $placeholders = array( + "FIRST_NAME" => "firstname", + "LAST_NAME" => "lastname", + "LOGIN" => "login" + ); + $txt = array(); + foreach ($placeholders as $placeholder => $caption) { + $txt[] = "[" . strtoupper($placeholder) . "]: " . $this->lng->txt($caption); + } + $txt = implode("
", $txt); + $participantdatainfo = new ilNonEditableValueGUI($this->lng->txt("mailparticipantdata_placeholder"), "", true); + $participantdatainfo->setValue($txt); + + $mailnotification->addSubItem($mailaddresses); + $mailnotification->addSubItem($participantdata); + $mailnotification->addSubItem($participantdatainfo); + $form->addItem($mailnotification); + + // tutor notification - currently not available for 360° + if (!$this->object->get360Mode()) { + // parent course? + $tree = $this->tree; + $has_parent = $tree->checkForParentType($this->object->getRefId(), "grp"); + if (!$has_parent) { + $has_parent = $tree->checkForParentType($this->object->getRefId(), "crs"); + } + $num_inv = sizeof($this->object->getInvitedUsers()); + + // notification + $tut = new ilCheckboxInputGUI($this->lng->txt("survey_notification_tutor_setting"), "tut"); + $tut->setChecked($this->object->getTutorNotificationStatus()); + $form->addItem($tut); + + $tut_logins = array(); + $tuts = $this->object->getTutorNotificationRecipients(); + if ($tuts) { + foreach ($tuts as $tut_id) { + $tmp = ilObjUser::_lookupName($tut_id); + if ($tmp["login"]) { + $tut_logins[] = $tmp["login"]; + } + } + } + $tut_ids = new ilTextInputGUI($this->lng->txt("survey_notification_tutor_recipients"), "tut_ids"); + $tut_ids->setDataSource($this->ctrl->getLinkTarget($this, "doAutoComplete", "", true)); + $tut_ids->setRequired(true); + $tut_ids->setMulti(true); + $tut_ids->setMultiValues($tut_logins); + $tut_ids->setValue(array_shift($tut_logins)); + $tut->addSubItem($tut_ids); + + $tut_grp = new ilRadioGroupInputGUI($this->lng->txt("survey_notification_target_group"), "tut_grp"); + $tut_grp->setRequired(true); + $tut_grp->setValue($this->object->getTutorNotificationTarget()); + $tut->addSubItem($tut_grp); + + $tut_grp_crs = new ilRadioOption( + $this->lng->txt("survey_notification_target_group_parent_course"), + ilObjSurvey::NOTIFICATION_PARENT_COURSE + ); + if (!$has_parent) { + $tut_grp_crs->setInfo($this->lng->txt("survey_notification_target_group_parent_course_inactive")); + } else { + $tut_grp_crs->setInfo(sprintf( + $this->lng->txt("survey_notification_target_group_invited_info"), + count($this->object->getNotificationTargetUserIds(false)) + )); + } + $tut_grp->addOption($tut_grp_crs); + + $tut_grp_inv = new ilRadioOption( + $this->lng->txt("survey_notification_target_group_invited"), + ilObjSurvey::NOTIFICATION_INVITED_USERS + ); + $tut_grp_inv->setInfo(sprintf($this->lng->txt("survey_notification_target_group_invited_info"), $num_inv)); + $tut_grp->addOption($tut_grp_inv); + } + + + // reminders + + $info = new ilFormSectionHeaderGUI(); + $info->setTitle($this->lng->txt("svy_settings_section_reminders")); + $form->addItem($info); + + $rmd = new ilCheckboxInputGUI($this->lng->txt("survey_reminder_setting"), "rmd"); + $rmd->setChecked($this->object->getReminderStatus()); + $form->addItem($rmd); + + $rmd_start = new ilDateTimeInputGUI($this->lng->txt("survey_reminder_start"), "rmd_start"); + $rmd_start->setRequired(true); + $start = $this->object->getReminderStart(); + if ($start) { + $rmd_start->setDate($start); + } + $rmd->addSubItem($rmd_start); + + $end = $this->object->getReminderEnd(); + $rmd_end = new ilDateTimeInputGUI($this->lng->txt("survey_reminder_end"), "rmd_end"); + if ($end) { + $rmd_end->setDate($end); + } + $rmd->addSubItem($rmd_end); + + $rmd_freq = new ilNumberInputGUI($this->lng->txt("survey_reminder_frequency"), "rmd_freq"); + $rmd_freq->setRequired(true); + $rmd_freq->setSize(3); + $rmd_freq->setSuffix($this->lng->txt("survey_reminder_frequency_days")); + $rmd_freq->setValue($this->object->getReminderFrequency()); + $rmd_freq->setMinValue(1); + $rmd->addSubItem($rmd_freq); + + + if (!$this->object->get360Mode()) { + $rmd_grp = new ilRadioGroupInputGUI($this->lng->txt("survey_notification_target_group"), "rmd_grp"); + $rmd_grp->setRequired(true); + $rmd_grp->setValue($this->object->getReminderTarget()); + $rmd->addSubItem($rmd_grp); + + $rmd_grp_crs = new ilRadioOption( + $this->lng->txt("survey_notification_target_group_parent_course"), + ilObjSurvey::NOTIFICATION_PARENT_COURSE + ); + if (!$has_parent) { + $rmd_grp_crs->setInfo($this->lng->txt("survey_notification_target_group_parent_course_inactive")); + } else { + $rmd_grp_crs->setInfo(sprintf( + $this->lng->txt("survey_notification_target_group_invited_info"), + count($this->object->getNotificationTargetUserIds(false)) + )); + } + $rmd_grp->addOption($rmd_grp_crs); + + $rmd_grp_inv = new ilRadioOption( + $this->lng->txt("survey_notification_target_group_invited"), + ilObjSurvey::NOTIFICATION_INVITED_USERS + ); + $rmd_grp_inv->setInfo(sprintf($this->lng->txt("survey_notification_target_group_invited_info"), $num_inv)); + $rmd_grp->addOption($rmd_grp_inv); + + $mtmpl = $this->object->getReminderMailTemplates(); + if ($mtmpl) { + $rmdt = new ilRadioGroupInputGUI($this->lng->txt("svy_reminder_mail_template"), "rmdt"); + $rmdt->setRequired(true); + $rmdt->addOption(new ilRadioOption($this->lng->txt("svy_reminder_mail_template_none"), -1)); + foreach ($mtmpl as $mtmpl_id => $mtmpl_caption) { + $option = new ilRadioOption($mtmpl_caption, $mtmpl_id); + $rmdt->addOption($option); + } + + $reminderTemplateValue = -1; + if ($this->object->getReminderTemplate()) { + $reminderTemplateValue = $this->object->getReminderTemplate(); + } + $rmdt->setValue($reminderTemplateValue); + $rmd->addSubItem($rmdt); + } + } else { + // remind appraisees + $cb = new ilCheckboxInputGUI($this->lng->txt("survey_notification_target_group"), "remind_appraisees"); + $cb->setOptionTitle($this->lng->txt("survey_360_appraisees")); + $cb->setInfo($this->lng->txt("survey_360_appraisees_remind_info")); + $cb->setValue("1"); + $cb->setChecked(in_array( + $this->object->getReminderTarget(), + array(ilObjSurvey::NOTIFICATION_APPRAISEES, ilObjSurvey::NOTIFICATION_APPRAISEES_AND_RATERS) + )); + $rmd->addSubItem($cb); + + // remind raters + $cb = new ilCheckboxInputGUI("", "remind_raters"); + $cb->setOptionTitle($this->lng->txt("survey_360_raters")); + $cb->setInfo($this->lng->txt("survey_360_raters_remind_info")); + $cb->setValue("1"); + $cb->setChecked(in_array( + $this->object->getReminderTarget(), + array(ilObjSurvey::NOTIFICATION_RATERS, ilObjSurvey::NOTIFICATION_APPRAISEES_AND_RATERS) + )); + $rmd->addSubItem($cb); + } + + + // results + + $results = new ilFormSectionHeaderGUI(); + $results->setTitle($this->lng->txt("results")); + $form->addItem($results); + + // evaluation access + switch ($this->object->getMode()) { + case ilObjSurvey::MODE_360: + $ts_results = new ilRadioGroupInputGUI($this->lng->txt("survey_360_results"), "ts_res"); + $ts_results->setValue($this->object->get360Results()); + + $option = new ilRadioOption($this->lng->txt("survey_360_results_none"), ilObjSurvey::RESULTS_360_NONE); + $option->setInfo($this->lng->txt("survey_360_results_none_info")); + $ts_results->addOption($option); + + $option = new ilRadioOption($this->lng->txt("survey_360_results_own"), ilObjSurvey::RESULTS_360_OWN); + $option->setInfo($this->lng->txt("survey_360_results_own_info")); + $ts_results->addOption($option); + + $option = new ilRadioOption($this->lng->txt("survey_360_results_all"), ilObjSurvey::RESULTS_360_ALL); + $option->setInfo($this->lng->txt("survey_360_results_all_info")); + $ts_results->addOption($option); + + $form->addItem($ts_results); + break; + + case ilObjSurvey::MODE_SELF_EVAL: + //check the names of these vars + $evaluation_access = new ilRadioGroupInputGUI($this->lng->txt('evaluation_access'), "self_eval_res"); + $evaluation_access->setValue($this->object->getSelfEvaluationResults()); + + $option = new ilRadioOption($this->lng->txt("svy_self_ev_access_results_none"), ilObjSurvey::RESULTS_SELF_EVAL_NONE); + $evaluation_access->addOption($option); + + $option = new ilRadioOption($this->lng->txt("svy_self_ev_access_results_own"), ilObjSurvey::RESULTS_SELF_EVAL_OWN); + $evaluation_access->addOption($option); + + $option = new ilRadioOption($this->lng->txt("svy_self_ev_access_results_all"), ilObjSurvey::RESULTS_SELF_EVAL_ALL); + $evaluation_access->addOption($option); + + $form->addItem($evaluation_access); + break; + + default: + $evaluation_access = new ilRadioGroupInputGUI($this->lng->txt('evaluation_access'), "evaluation_access"); + + $option = new ilCheckboxOption($this->lng->txt("evaluation_access_off"), ilObjSurvey::EVALUATION_ACCESS_OFF, ''); + $option->setInfo($this->lng->txt("svy_evaluation_access_off_info")); + $evaluation_access->addOption($option); + + $option = new ilCheckboxOption($this->lng->txt("evaluation_access_all"), ilObjSurvey::EVALUATION_ACCESS_ALL, ''); + $option->setInfo($this->lng->txt("svy_evaluation_access_all_info")); + $evaluation_access->addOption($option); + + $option = new ilCheckboxOption($this->lng->txt("evaluation_access_participants"), ilObjSurvey::EVALUATION_ACCESS_PARTICIPANTS, ''); + $option->setInfo($this->lng->txt("svy_evaluation_access_participants_info")); + $evaluation_access->addOption($option); + + $evaluation_access->setValue($this->object->getEvaluationAccess()); + $form->addItem($evaluation_access); + + $anonymization_options = new ilRadioGroupInputGUI($this->lng->txt("survey_results_anonymization"), "anonymization_options"); + + $option = new ilCheckboxOption($this->lng->txt("survey_results_personalized"), "statpers"); + $option->setInfo($this->lng->txt("survey_results_personalized_info")); + $anonymization_options->addOption($option); + + $option = new ilCheckboxOption($this->lng->txt("survey_results_anonymized"), "statanon"); + $option->setInfo($this->lng->txt("survey_results_anonymized_info")); + $anonymization_options->addOption($option); + $anonymization_options->setValue($this->object->hasAnonymizedResults() + ? "statanon" + : "statpers"); + $form->addItem($anonymization_options); + + $surveySetting = new ilSetting("survey"); + if ($surveySetting->get("anonymous_participants", false)) { + $min = ""; + if ($surveySetting->get("anonymous_participants_min", 0)) { + $min = " (" . $this->lng->txt("svy_anonymous_participants_min") . ": " . + $surveySetting->get("anonymous_participants_min") . ")"; + } + + $anon_list = new ilCheckboxInputGUI($this->lng->txt("svy_anonymous_participants_svy"), "anon_list"); + $anon_list->setInfo($this->lng->txt("svy_anonymous_participants_svy_info") . $min); + $anon_list->setChecked($this->object->hasAnonymousUserList()); + $option->addSubItem($anon_list); + } + + if ($this->object->_hasDatasets($this->object->getSurveyId())) { + $anonymization_options->setDisabled(true); + if ($anon_list) { + $anon_list->setDisabled(true); + } + } + break; + } + + // competence service activation for 360 mode + + include_once("./Services/Skill/classes/class.ilSkillManagementSettings.php"); + $skmg_set = new ilSkillManagementSettings(); + $svy_mode = $this->object->getMode(); + if (($svy_mode == ilObjSurvey::MODE_360 || $svy_mode == ilObjSurvey::MODE_SELF_EVAL) && $skmg_set->isActivated()) { + $other = new ilFormSectionHeaderGUI(); + $other->setTitle($this->lng->txt("other")); + $form->addItem($other); + + $skill_service = new ilCheckboxInputGUI($this->lng->txt("survey_activate_skill_service"), "skill_service"); + $skill_service->setInfo($this->lng->txt("survey_activate_skill_service_info")); + $skill_service->setChecked($this->object->getSkillService()); + $form->addItem($skill_service); + } + + $position_settings = ilOrgUnitGlobalSettings::getInstance() + ->getObjectPositionSettingsByType($this->object->getType()); + + if ($position_settings->isActive()) { + // add additional feature section + $feat = new ilFormSectionHeaderGUI(); + $feat->setTitle($this->lng->txt('obj_features')); + $form->addItem($feat); + + // add orgunit settings + ilObjectServiceSettingsGUI::initServiceSettingsForm( + $this->object->getId(), + $form, + array( + ilObjectServiceSettingsGUI::ORGU_POSITION_ACCESS + ) + ); + } + + $form->addCommandButton("saveProperties", $this->lng->txt("save")); + + // remove items when using template + if ($template_settings) { + foreach ($template_settings as $id => $item) { + if ($item["hide"]) { + if ($id == "enabled_end_date") { + $id = "end_date"; + } + if ($id == "enabled_start_date") { + $id = "start_date"; + } + $form->removeItemByPostVar($id, true); + } + } + } + return $form; + } + + /** + * Add subtabs for tabs + * @param type $a_section + */ + public function addSubTabs($a_section) + { + if ($a_section == 'settings') { + $this->tabs_gui->addSubTabTarget( + "settings", + $this->ctrl->getLinkTarget($this, 'properties') + ); + + $lti_settings = new ilLTIProviderObjectSettingGUI($this->object->getRefId()); + if ($lti_settings->hasSettingsAccess()) { + $this->tabs_gui->addSubTabTarget( + 'lti_provider', + $this->ctrl->getLinkTargetByClass(ilLTIProviderObjectSettingGUI::class) + ); + } + } + } + + + /** + * Display and fill the properties form of the test + * + * @access public + */ + public function propertiesObject(ilPropertyFormGUI $a_form = null) + { + $ilTabs = $this->tabs; + $ilHelp = $this->help; + + $this->checkPermission("write"); + + $this->addSubTabs('settings'); + $ilTabs->activateTab("settings"); + $ilTabs->activateSubTab('settings'); + + if ($this->object->get360Mode()) { + $ilHelp->setScreenId("settings_360"); + } + + if (!$a_form) { + $a_form = $this->initPropertiesForm(); + } + + // using template? + $message = ""; + if ($this->object->getTemplate()) { + $link = $this->ctrl->getLinkTarget($this, "confirmResetTemplate"); + $link = "" . $this->lng->txt("survey_using_template_link") . ""; + $message = "
" . + $this->tpl->getMessageHTML(sprintf( + $this->lng->txt("survey_using_template"), + ilSettingsTemplate::lookupTitle($this->object->getTemplate()), + $link + ), "info") . // #10651 + "
"; + } + + $this->tpl->setContent($a_form->getHTML() . $message); + } + + public function doAutoCompleteObject() + { + $fields = array('login','firstname','lastname','email'); + + include_once './Services/User/classes/class.ilUserAutoComplete.php'; + $auto = new ilUserAutoComplete(); + $auto->setSearchFields($fields); + $auto->setResultField('login'); + $auto->enableFieldSearchableCheck(true); + $auto->setMoreLinkAvailable(true); + + if (($_REQUEST['fetchall'])) { + $auto->setLimit(ilUserAutoComplete::MAX_ENTRIES); + } + + echo $auto->getList(ilUtil::stripSlashes($_REQUEST['term'])); + exit(); + } + + /** + * Enable all settings - Confirmation + */ + public function confirmResetTemplateObject() + { + ilUtil::sendQuestion($this->lng->txt("survey_confirm_template_reset")); + $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.il_svy_svy_confirm_resettemplate.html", "Modules/Survey"); + $this->tpl->setCurrentBlock("adm_content"); + $this->tpl->setVariable("BTN_CONFIRM_REMOVE", $this->lng->txt("confirm")); + $this->tpl->setVariable("BTN_CANCEL_REMOVE", $this->lng->txt("cancel")); + $this->tpl->setVariable("FORM_ACTION", $this->ctrl->getFormAction($this, "resetTemplateObject")); + $this->tpl->parseCurrentBlock(); + } + + /** + * Enable all settings - remove template + */ + public function resetTemplateObject() + { + $this->object->setTemplate(null); + $this->object->saveToDB(); + + ilUtil::sendSuccess($this->lng->txt("survey_template_reset"), true); + $this->ctrl->redirect($this, "properties"); + } + + + + // + // IMPORT/EXPORT + // + + protected function initImportForm($a_new_type) + { + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setTarget("_top"); + $form->setFormAction($this->ctrl->getFormAction($this)); + $form->setTitle($this->lng->txt("import_svy")); + + include_once("./Services/Form/classes/class.ilFileInputGUI.php"); + $fi = new ilFileInputGUI($this->lng->txt("import_file"), "importfile"); + $fi->setSuffixes(array("zip")); + $fi->setRequired(true); + $form->addItem($fi); + + include_once("./Modules/Survey/classes/class.ilObjSurvey.php"); + $svy = new ilObjSurvey(); + $questionspools = $svy->getAvailableQuestionpools(true, true, true); + + $pools = new ilSelectInputGUI($this->lng->txt("select_questionpool_short"), "spl"); + $pools->setOptions(array(""=>$this->lng->txt("dont_use_questionpool")) + $questionspools); + $pools->setRequired(false); + $form->addItem($pools); + + $form->addCommandButton("importSurvey", $this->lng->txt("import")); + $form->addCommandButton("cancel", $this->lng->txt("cancel")); + + return $form; + } + + /** + * form for new survey object import + */ + public function importSurveyObject() + { + $tpl = $this->tpl; + + $parent_id = $_GET["ref_id"]; + $new_type = $_REQUEST["new_type"]; + + // create permission is already checked in createObject. This check here is done to prevent hacking attempts + $this->checkPermission("create", "", $new_type); + + $this->lng->loadLanguageModule($new_type); + $this->ctrl->setParameter($this, "new_type", $new_type); + + $form = $this->initImportForm($new_type); + if ($form->checkInput()) { + include_once("./Modules/Survey/classes/class.ilObjSurvey.php"); + $newObj = new ilObjSurvey(); + $newObj->setType($new_type); + $newObj->setTitle("dummy"); + $newObj->create(true); + $this->putObjectInTree($newObj); + + // copy uploaded file to import directory + + $this->log->debug("form->getInput(spl) = " . $form->getInput("spl")); + + $error = $newObj->importObject($_FILES["importfile"], $form->getInput("spl")); + if (strlen($error)) { + $newObj->delete(); + ilUtil::sendFailure($error); + return; + } + + ilUtil::sendSuccess($this->lng->txt("object_imported"), true); + ilUtil::redirect("ilias.php?ref_id=" . $newObj->getRefId() . + "&baseClass=ilObjSurveyGUI"); + + // using template? + include_once "Services/Administration/classes/class.ilSettingsTemplate.php"; + $templates = ilSettingsTemplate::getAllSettingsTemplates("svy"); + if ($templates) { + $tpl = $this->tpl; + $tpl->addJavaScript("./Modules/Scorm2004/scripts/questions/jquery.js"); + // $tpl->addJavaScript("./Modules/Scorm2004/scripts/questions/jquery-ui-min.js"); + + $this->tpl->setCurrentBlock("template_option"); + $this->tpl->setVariable("VAL_TEMPLATE_OPTION", ""); + $this->tpl->setVariable("TXT_TEMPLATE_OPTION", $this->lng->txt("none")); + $this->tpl->parseCurrentBlock(); + + foreach ($templates as $item) { + $this->tpl->setCurrentBlock("template_option"); + $this->tpl->setVariable("VAL_TEMPLATE_OPTION", $item["id"]); + $this->tpl->setVariable("TXT_TEMPLATE_OPTION", $item["title"]); + $this->tpl->parseCurrentBlock(); + + $desc = str_replace("\n", "", nl2br($item["description"])); + $desc = str_replace("\r", "", $desc); + + $this->tpl->setCurrentBlock("js_data"); + $this->tpl->setVariable("JS_DATA_ID", $item["id"]); + $this->tpl->setVariable("JS_DATA_TEXT", $desc); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setCurrentBlock("templates"); + $this->tpl->setVariable("TXT_TEMPLATE", $this->lng->txt("svy_settings_template")); + $this->tpl->parseCurrentBlock(); + } + } + + // display form to correct errors + $form->setValuesByPost(); + $tpl->setContent($form->getHtml()); + } + + + // + // INFOSCREEN + // + + /** + * 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 infoScreenObject() + { + $this->ctrl->setCmd("showSummary"); + $this->ctrl->setCmdClass("ilinfoscreengui"); + $this->infoScreen(); + } + + /** + * show information screen + */ + public function infoScreen() + { + $ilTabs = $this->tabs; + $ilUser = $this->user; + $ilToolbar = $this->toolbar; + $ilAccess = $this->access; + + if (!$this->external_rater_360) { + if (!$this->checkPermissionBool("read")) { + $this->checkPermission("visible"); + } + } + + $ilTabs->activateTab("info_short"); + + include_once "./Modules/Survey/classes/class.ilSurveyExecutionGUI.php"; + $output_gui = new ilSurveyExecutionGUI($this->object); + + include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); + $info = new ilInfoScreenGUI($this); + $info->enablePrivateNotes(); + + + $is_appraisee = false; + + // 360° - appraisee infos + if ($this->object->get360Mode() && + $this->object->isAppraisee($ilUser->getId())) { + $is_appraisee = true; + + $info->addSection($this->lng->txt("survey_360_appraisee_info")); + + $appr_data = $this->object->getAppraiseesData(); + $appr_data = $appr_data[$ilUser->getId()]; + $info->addProperty($this->lng->txt("survey_360_raters_status_info"), $appr_data["finished"]); + + if (!$appr_data["closed"]) { + include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; + $button = ilLinkButton::getInstance(); + $button->setCaption("survey_360_appraisee_close_action"); + $button->setUrl($this->ctrl->getLinkTargetByClass("ilsurveyparticipantsgui", "confirmappraiseeclose")); + $close_button_360 = '
' . $button->render() . '
'; + + $txt = "survey_360_appraisee_close_action_info"; + if ($this->object->getSkillService()) { + $txt .= "_skill"; + } + $info->addProperty( + $this->lng->txt("status"), + $close_button_360 . $this->lng->txt($txt) + ); + } else { + ilDatePresentation::setUseRelativeDates(false); + + $dt = new ilDateTime($appr_data["closed"], IL_CAL_UNIX); + $info->addProperty( + $this->lng->txt("status"), + sprintf( + $this->lng->txt("survey_360_appraisee_close_action_status"), + ilDatePresentation::formatDate($dt) + ) + ); + } + } + + + // handle (anonymous) code + + // validate incoming + $code_input = false; + $anonymous_code = $_POST["anonymous_id"]; + if ($anonymous_code) { + $code_input = true; + // if(!$this->object->isUnusedCode($anonymous_code, $ilUser->getId())) + if (!$this->object->checkSurveyCode($anonymous_code)) { // #15031 - valid as long survey is not finished + $anonymous_code = null; + } else { + // #15860 + $this->object->bindSurveyCodeToUser($ilUser->getId(), $anonymous_code); + } + } + if ($anonymous_code) { + $_SESSION["anonymous_id"][$this->object->getId()] = $anonymous_code; + } else { + $anonymous_code = $_SESSION["anonymous_id"][$this->object->getId()]; + if ($anonymous_code) { + $code_input = true; + } + } + + // try to find code for current (registered) user from existing run + if ($this->object->getAnonymize() && !$anonymous_code) { + $anonymous_code = $this->object->findCodeForUser($ilUser->getId()); + } + + // get existing runs for current user, might generate code + $participant_status = $this->object->getUserSurveyExecutionStatus($anonymous_code); + if ($participant_status) { + $anonymous_code = $participant_status["code"]; + $participant_status = $participant_status["runs"]; + } + + // (final) check for proper anonymous code + if (!$this->object->isAccessibleWithoutCode() && + !$is_appraisee && + $code_input && // #11346 + (!$anonymous_code || !$this->object->isAnonymousKey($anonymous_code))) { + $anonymous_code = null; + ilUtil::sendInfo($this->lng->txt("wrong_survey_code_used")); + } + + // :TODO: really save in session? + $_SESSION["anonymous_id"][$this->object->getId()] = $anonymous_code; + + if (ilObjSurvey::RESULTS_SELF_EVAL_ALL) { + $survey_started = $this->object->isSurveyStarted($ilUser->getId(), $anonymous_code, $ilUser->getId()); + } else { + $survey_started = $this->object->isSurveyStarted($ilUser->getId(), $anonymous_code); + } + + $showButtons = $big_button = false; + + // already finished? + if (!$this->object->get360Mode() && + ($survey_started === 1 && // survey finished + !(!$this->object->isAccessibleWithoutCode() && !$anonymous_code && $ilUser->getId() == ANONYMOUS_USER_ID))) { // not code accessible an no anonymous code and anonymous user (see #0020333) + ilUtil::sendInfo($this->lng->txt("already_completed_survey")); + + if ($ilUser->getId() != ANONYMOUS_USER_ID) { + if ($this->object->hasViewOwnResults()) { + include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; + $button = ilLinkButton::getInstance(); + $button->setCaption("svy_view_own_results"); + $button->setUrl($this->ctrl->getLinkTarget($this, "viewUserResults")); + $ilToolbar->addButtonInstance($button); + } + + // see ilSurveyExecutionGUI + if ($this->object->hasMailConfirmation()) { + if ($this->object->hasViewOwnResults()) { + $ilToolbar->addSeparator(); + } + + if ($ilUser->getId() == ANONYMOUS_USER_ID || + !$ilUser->getEmail()) { + require_once "Services/Form/classes/class.ilTextInputGUI.php"; + $mail = new ilTextInputGUI($this->lng->txt("email"), "mail"); + $mail->setSize(25); + $mail->setValue($ilUser->getEmail()); + $ilToolbar->addInputItem($mail, true); + } + + $ilToolbar->setFormAction($this->ctrl->getFormAction($this, "mailUserResults")); + + include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; + $button = ilSubmitButton::getInstance(); + $button->setCaption("svy_mail_send_confirmation"); + $button->setCommand("mailUserResults"); + $ilToolbar->addButtonInstance($button); + } + } + } else { + // "active" survey? + $canStart = $this->object->canStartSurvey(null, $this->external_rater_360); + + $showButtons = $canStart["result"]; + if (!$showButtons) { + if ($canStart["edit_settings"] && + $ilAccess->checkAccess("write", "", $this->ref_id)) { + $canStart["messages"][] = "ctrl->getLinkTarget($this, "properties") . "\">» " . + $this->lng->txt("survey_edit_settings") . ""; + } + ilUtil::sendInfo(implode("
", $canStart["messages"])); + } + } + + if ($showButtons) { + // code is mandatory and not given yet + if (!$is_appraisee && + !$anonymous_code && + !$this->object->isAccessibleWithoutCode()) { + $info->setFormAction($this->ctrl->getFormAction($this, "infoScreen")); + $info->addSection($this->lng->txt("anonymization")); + $info->addProperty("", $this->lng->txt("anonymize_anonymous_introduction")); + $info->addPropertyTextinput($this->lng->txt("enter_anonymous_id"), "anonymous_id", "", 8, "infoScreen", $this->lng->txt("submit"), true); + } else { + // trunk/default + if (!$this->object->get360Mode()) { + if ($anonymous_code) { + $info->addHiddenElement("anonymous_id", $anonymous_code); + } + if ($survey_started === 0) { + $big_button = array("resume", $this->lng->txt("resume_survey")); + } elseif ($survey_started === false) { + $big_button = array("start", $this->lng->txt("start_survey")); + } + } + // 360° + else { + $appr_ids = array(); + + // use given code (if proper external one) + if ($anonymous_code) { + $anonymous_id = $this->object->getAnonymousIdByCode($anonymous_code); + if ($anonymous_id) { + $appr_ids = $this->object->getAppraiseesToRate(0, $anonymous_id); + } + } + + // registered user + // if an auto-code was generated, we still have to check for the original user id + if (!$appr_ids && $ilUser->getId() != ANONYMOUS_USER_ID) { + $appr_ids = $this->object->getAppraiseesToRate($ilUser->getId()); + } + + if (sizeof($appr_ids)) { + // map existing runs to appraisees + $active_appraisees = array(); + if ($participant_status) { + foreach ($participant_status as $item) { + $active_appraisees[$item["appr_id"]] = $item["finished"]; + } + } + + $list = array(); + + foreach ($appr_ids as $appr_id) { + if ($this->object->isAppraiseeClosed($appr_id)) { + // closed + $list[$appr_id] = $this->lng->txt("survey_360_appraisee_is_closed"); + } elseif (array_key_exists($appr_id, $active_appraisees)) { + // already done + if ($active_appraisees[$appr_id]) { + $list[$appr_id] = $this->lng->txt("already_completed_survey"); + } + // resume + else { + $list[$appr_id] = array("resume", $this->lng->txt("resume_survey")); + } + } else { + // start + $list[$appr_id] = array("start", $this->lng->txt("start_survey")); + } + } + + $info->addSection($this->lng->txt("survey_360_rate_other_appraisees")); + + include_once "Services/User/classes/class.ilUserUtil.php"; + foreach ($list as $appr_id => $item) { + $appr_name = ilUserUtil::getNamePresentation($appr_id, false, false, "", true); + + if (!is_array($item)) { + $info->addProperty($appr_name, $item); + } else { + $this->ctrl->setParameter($output_gui, "appr_id", $appr_id); + $href = $this->ctrl->getLinkTarget($output_gui, $item[0]); + $this->ctrl->setParameter($output_gui, "appr_id", ""); + + include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; + $button = ilLinkButton::getInstance(); + $button->setCaption($item[1], false); + $button->setUrl($href); + $big_button_360 = '
' . $button->render() . '
'; + + $info->addProperty($appr_name, $big_button_360); + } + } + } elseif (!$is_appraisee) { + ilUtil::sendFailure($this->lng->txt("survey_360_no_appraisees")); + } + } + } + + if ($this->object->get360Mode() && + $this->object->get360SelfAppraisee() && + !$this->object->isAppraisee($ilUser->getId()) && + $ilUser->getId() != ANONYMOUS_USER_ID) { // #14968 + $link = $this->ctrl->getLinkTargetByClass("ilsurveyparticipantsgui", "addSelfAppraisee"); + $link = '' . $this->lng->txt("survey_360_add_self_appraisee") . ''; + $info->addProperty(" ", $link); + } + } + + if ($big_button) { + $ilToolbar->setFormAction($this->ctrl->getFormAction($output_gui, "infoScreen")); + + include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; + $button = ilSubmitButton::getInstance(); + $button->setCaption($big_button[1], false); + $button->setCommand($big_button[0]); + $button->setPrimary(true); + $ilToolbar->addButtonInstance($button); + + $ilToolbar->setCloseFormTag(false); + $info->setOpenFormTag(false); + } + /* #12016 + else + { + $info->setFormAction($this->ctrl->getFormAction($output_gui, "infoScreen")); + } + */ + + if (strlen($this->object->getIntroduction())) { + $introduction = $this->object->getIntroduction(); + $info->addSection($this->lng->txt("introduction")); + $info->addProperty("", $this->object->prepareTextareaOutput($introduction) . + "
" . $info->getHiddenToggleButton()); + } else { + $info->addSection(""); + $info->addProperty("", $info->getHiddenToggleButton()); + } + + $info->hideFurtherSections(false); + + if (!$this->object->get360Mode()) { + $info->addSection($this->lng->txt("svy_general_properties")); + + $info->addProperty( + $this->lng->txt("survey_results_anonymization"), + !$this->object->hasAnonymizedResults() + ? $this->lng->txt("survey_results_personalized_info") + : $this->lng->txt("survey_results_anonymized_info") + ); + + include_once "./Modules/Survey/classes/class.ilObjSurveyAccess.php"; + if ($this->checkPermissionBool("write") || + ilObjSurveyAccess::_hasEvaluationAccess($this->object->getId(), $ilUser->getId())) { + $info->addProperty($this->lng->txt("evaluation_access"), $this->lng->txt("evaluation_access_info")); + } + } + + $info->addMetaDataSections($this->object->getId(), 0, $this->object->getType()); + + $this->ctrl->forwardCommand($info); + } + + public function addLocatorItems() + { + $ilLocator = $this->locator; + switch ($this->ctrl->getCmd()) { + case "next": + case "previous": + case "start": + case "resume": + case "redirectQuestion": + $ilLocator->addItem($this->object->getTitle(), $this->ctrl->getLinkTarget($this, "infoScreen"), "", $_GET["ref_id"]); + break; + case "evaluation": + case "checkEvaluationAccess": + case "evaluationdetails": + case "evaluationuser": + $ilLocator->addItem($this->object->getTitle(), $this->ctrl->getLinkTargetByClass("ilsurveyevaluationgui", "evaluation"), "", $_GET["ref_id"]); + break; + case "create": + case "save": + case "cancel": + case "importSurvey": + case "cloneAll": + break; + case "infoScreen": + $ilLocator->addItem($this->object->getTitle(), $this->ctrl->getLinkTarget($this, "infoScreen"), "", $_GET["ref_id"]); + break; + default: + $ilLocator->addItem($this->object->getTitle(), $this->ctrl->getLinkTarget($this, "infoScreen"), "", $_GET["ref_id"]); + + // this has to be done here because ilSurveyEditorGUI is called after finalizing the locator + if ((int) $_GET["q_id"] && !(int) $_REQUEST["new_for_survey"]) { + // not on create + // see ilObjSurveyQuestionPool::addLocatorItems + $q_id = (int) $_GET["q_id"]; + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + $q_type = SurveyQuestion::_getQuestionType($q_id) . "GUI"; + $this->ctrl->setParameterByClass($q_type, "q_id", $q_id); + $ilLocator->addItem( + SurveyQuestion::_getTitle($q_id), + $this->ctrl->getLinkTargetByClass(array("ilSurveyEditorGUI", $q_type), "editQuestion") + ); + } + break; + } + } + - /** - * redirect script - * - * @param string $a_target - */ - public static function _goto($a_target, $a_access_code = "") - { - global $DIC; - - $ilAccess = $DIC->access(); - $lng = $DIC->language(); - - // see ilObjSurveyAccess::_checkGoto() - if (strlen($a_access_code)) - { - $_SESSION["anonymous_id"][ilObject::_lookupObjId($a_target)] = $a_access_code; - $_GET["baseClass"] = "ilObjSurveyGUI"; - $_GET["cmd"] = "infoScreen"; - $_GET["ref_id"] = $a_target; - include("ilias.php"); - exit; - } - - if ($ilAccess->checkAccess("visible", "", $a_target) || - $ilAccess->checkAccess("read", "", $a_target)) - { - $_GET["baseClass"] = "ilObjSurveyGUI"; - $_GET["cmd"] = "infoScreen"; - $_GET["ref_id"] = $a_target; - include("ilias.php"); - exit; - } - else if ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) - { - ilUtil::sendFailure(sprintf($lng->txt("msg_no_perm_read_item"), - ilObject::_lookupTitle(ilObject::_lookupObjId($a_target))), true); - ilObjectGUI::_gotoRepositoryRoot(); - } - } - - public function getUserResultsTable($a_active_id) - { - $rtpl = new ilTemplate("tpl.svy_view_user_results.html", true, true, "Modules/Survey"); - - $show_titles = (bool)$this->object->getShowQuestionTitles(); - - foreach($this->object->getSurveyPages() as $page) - { - if(count($page) > 0) - { - // question block - if(count($page) > 1) - { - if((bool)$page[0]["questionblock_show_blocktitle"]) - { - $rtpl->setVariable("BLOCK_TITLE", trim($page[0]["questionblock_title"])); - } - } - - // questions - foreach($page as $question) - { - $question_gui = $this->object->getQuestionGUI($question["type_tag"], $question["question_id"]); - if(is_object($question_gui)) - { - $rtpl->setCurrentBlock("question_bl"); - - // heading - if(strlen($question["heading"])) - { - $rtpl->setVariable("HEADING", trim($question["heading"])); - } - - $rtpl->setVariable("QUESTION_DATA", - $question_gui->getPrintView( - $show_titles, - (bool)$question["questionblock_show_questiontext"], - $this->object->getId(), - $this->object->loadWorkingData($question["question_id"], $a_active_id) - ) - ); - - $rtpl->parseCurrentBlock(); - } - } - - $rtpl->setCurrentBlock("block_bl"); - $rtpl->parseCurrentBlock(); - } - } - - return $rtpl->get(); - } - - protected function viewUserResultsObject() - { - $ilUser = $this->user; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - $anonymous_code = $_SESSION["anonymous_id"][$this->object->getId()]; - $active_id = $this->object->getActiveID($ilUser->getId(), $anonymous_code, 0); - if($this->object->isSurveyStarted($ilUser->getId(), $anonymous_code) !== 1 || - !$active_id) - { - $this->ctrl->redirect($this, "infoScreen"); - } - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($this->lng->txt("btn_back"), - $this->ctrl->getLinkTarget($this, "infoScreen")); - - $html = $this->getUserResultsTable($active_id); - $tpl->setContent($html); - } - - protected function getUserResultsPlain($a_active_id) - { - $res = array(); - - $show_titles = (bool)$this->object->getShowQuestionTitles(); - - foreach($this->object->getSurveyPages() as $page) - { - if(count($page) > 0) - { - $res[] = "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; - - // question block - if(count($page) > 1) - { - if((bool)$page[0]["questionblock_show_blocktitle"]) - { - $res[$this->lng->txt("questionblock")] = trim($page[0]["questionblock_title"])."\n"; - } - } - - // questions - - $page_res = array(); - - foreach($page as $question) - { - $question_gui = $this->object->getQuestionGUI($question["type_tag"], $question["question_id"]); - if(is_object($question_gui)) - { - $question_parts = array(); - - // heading - if(strlen($question["heading"])) - { - $question_parts[$this->lng->txt("heading")] = trim($question["heading"]); - } - - if($show_titles) - { - $question_parts[$this->lng->txt("title")] = trim($question["title"]); - } - - if((bool)$question["questionblock_show_questiontext"]) - { - $question_parts[$this->lng->txt("question")] = trim(strip_tags($question_gui->object->getQuestionText())); - } - - $answers = $question_gui->getParsedAnswers( - $this->object->loadWorkingData($question["question_id"], $a_active_id), - true - ); - - if(sizeof($answers)) - { - $multiline = false; - if(sizeof($answers) > 1 || - get_class($question_gui) == "SurveyTextQuestionGUI") - { - $multiline = true; - } - - $parts = array(); - foreach($answers as $answer) - { - $text = null; - if($answer["textanswer"]) - { - $text = ' ("'.$answer["textanswer"].'")'; - } - if(!isset($answer["cols"])) - { - if(isset($answer["title"])) - { - $parts[] = $answer["title"].$text; - } - else if(isset($answer["value"])) - { - $parts[] = $answer["value"]; - } - else if($text) - { - $parts[] = substr($text, 2, -1); - } - } - // matrix - else - { - $tmp = array(); - foreach($answer["cols"] as $col) - { - $tmp[] = $col["title"]; - } - $parts[] = $answer["title"].": ".implode(", ", $tmp).$text; - } - - } - $question_parts[$this->lng->txt("answer")] = - ($multiline ? "\n" : "").implode("\n", $parts); - } - - $tmp = array(); - foreach($question_parts as $type => $value) - { - $tmp[] = $type.": ".$value; - } - $page_res[] = implode("\n", $tmp); - } - } - - $res[] = implode("\n\n-------------------------------\n\n", $page_res); - } - } - - $res[] = "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; - - return implode("\n", $res); - } - - public function sendUserResultsMail($a_active_id, $a_recipient) - { - $ilUser = $this->user; - - $finished = $this->object->getSurveyParticipants(array($a_active_id)); - $finished = array_pop($finished); - $finished = ilDatePresentation::formatDate(new ilDateTime($finished["finished_tstamp"], IL_CAL_UNIX)); - - require_once "Services/Mail/classes/class.ilMail.php"; - require_once "Services/Link/classes/class.ilLink.php"; - - $body = ilMail::getSalutation($ilUser->getId())."\n\n"; - $body .= $this->lng->txt("svy_mail_own_results_body")."\n"; - $body .= "\n".$this->lng->txt("obj_svy").": ".$this->object->getTitle()."\n"; - $body .= ilLink::_getLink($this->object->getRefId(), "svy")."\n"; - $body .= "\n".$this->lng->txt("survey_results_finished").": ".$finished."\n\n"; - - if($this->object->hasMailOwnResults()) - { - $subject = "svy_mail_own_results_subject"; - $body .= $this->getUserResultsPlain($a_active_id); - } - else - { - $subject = "svy_mail_confirmation_subject"; - } - - // $body .= ilMail::_getAutoGeneratedMessageString($this->lng); - $body .= ilMail::_getInstallationSignature(); - - require_once "Services/Mail/classes/class.ilMail.php"; - $mail = new ilMail(ANONYMOUS_USER_ID); - $mail->sendMimeMail( - $a_recipient, - null, - null, - sprintf($this->lng->txt($subject), $this->object->getTitle()), - $body, - null, - true - ); - } - - function mailUserResultsObject() - { - $ilUser = $this->user; - - $anonymous_code = $_SESSION["anonymous_id"][$this->object->getId()]; - $active_id = $this->object->getActiveID($ilUser->getId(), $anonymous_code, 0); - if($this->object->isSurveyStarted($ilUser->getId(), $anonymous_code) !== 1 || - !$active_id) - { - $this->ctrl->redirect($this, "infoScreen"); - } - - $recipient = $_POST["mail"]; - if(!$recipient) - { - $recipient = $ilUser->getEmail(); - } - if(!ilUtil::is_email($recipient)) - { - $this->ctrl->redirect($this, "infoScreen"); - } - - $this->sendUserResultsMail($active_id, $recipient); - - ilUtil::sendSuccess($this->lng->txt("mail_sent"), true); - $this->ctrl->redirect($this, "infoScreen"); - } - - /** - * Check rbac or position permission - * @param string $a_rbac_permission - * @param string $a_position_permission - * @return bool - */ - protected function checkRbacOrPositionPermission($a_rbac_permission, $a_position_permission) - { - $access = $GLOBALS['DIC']->access(); - return $access->checkRbacOrPositionPermissionAccess( - $a_rbac_permission, - $a_position_permission, - $this->object->getRefId() - ); - } -} - -?> \ No newline at end of file + /** + * redirect script + * + * @param string $a_target + */ + public static function _goto($a_target, $a_access_code = "") + { + global $DIC; + + $ilAccess = $DIC->access(); + $lng = $DIC->language(); + + // see ilObjSurveyAccess::_checkGoto() + if (strlen($a_access_code)) { + $_SESSION["anonymous_id"][ilObject::_lookupObjId($a_target)] = $a_access_code; + $_GET["baseClass"] = "ilObjSurveyGUI"; + $_GET["cmd"] = "infoScreen"; + $_GET["ref_id"] = $a_target; + include("ilias.php"); + exit; + } + + if ($ilAccess->checkAccess("visible", "", $a_target) || + $ilAccess->checkAccess("read", "", $a_target)) { + $_GET["baseClass"] = "ilObjSurveyGUI"; + $_GET["cmd"] = "infoScreen"; + $_GET["ref_id"] = $a_target; + include("ilias.php"); + exit; + } elseif ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) { + ilUtil::sendFailure(sprintf( + $lng->txt("msg_no_perm_read_item"), + ilObject::_lookupTitle(ilObject::_lookupObjId($a_target)) + ), true); + ilObjectGUI::_gotoRepositoryRoot(); + } + } + + public function getUserResultsTable($a_active_id) + { + $rtpl = new ilTemplate("tpl.svy_view_user_results.html", true, true, "Modules/Survey"); + + $show_titles = (bool) $this->object->getShowQuestionTitles(); + + foreach ($this->object->getSurveyPages() as $page) { + if (count($page) > 0) { + // question block + if (count($page) > 1) { + if ((bool) $page[0]["questionblock_show_blocktitle"]) { + $rtpl->setVariable("BLOCK_TITLE", trim($page[0]["questionblock_title"])); + } + } + + // questions + foreach ($page as $question) { + $question_gui = $this->object->getQuestionGUI($question["type_tag"], $question["question_id"]); + if (is_object($question_gui)) { + $rtpl->setCurrentBlock("question_bl"); + + // heading + if (strlen($question["heading"])) { + $rtpl->setVariable("HEADING", trim($question["heading"])); + } + + $rtpl->setVariable( + "QUESTION_DATA", + $question_gui->getPrintView( + $show_titles, + (bool) $question["questionblock_show_questiontext"], + $this->object->getId(), + $this->object->loadWorkingData($question["question_id"], $a_active_id) + ) + ); + + $rtpl->parseCurrentBlock(); + } + } + + $rtpl->setCurrentBlock("block_bl"); + $rtpl->parseCurrentBlock(); + } + } + + return $rtpl->get(); + } + + protected function viewUserResultsObject() + { + $ilUser = $this->user; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + $anonymous_code = $_SESSION["anonymous_id"][$this->object->getId()]; + $active_id = $this->object->getActiveID($ilUser->getId(), $anonymous_code, 0); + if ($this->object->isSurveyStarted($ilUser->getId(), $anonymous_code) !== 1 || + !$active_id) { + $this->ctrl->redirect($this, "infoScreen"); + } + + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $this->lng->txt("btn_back"), + $this->ctrl->getLinkTarget($this, "infoScreen") + ); + + $html = $this->getUserResultsTable($active_id); + $tpl->setContent($html); + } + + protected function getUserResultsPlain($a_active_id) + { + $res = array(); + + $show_titles = (bool) $this->object->getShowQuestionTitles(); + + foreach ($this->object->getSurveyPages() as $page) { + if (count($page) > 0) { + $res[] = "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; + + // question block + if (count($page) > 1) { + if ((bool) $page[0]["questionblock_show_blocktitle"]) { + $res[$this->lng->txt("questionblock")] = trim($page[0]["questionblock_title"]) . "\n"; + } + } + + // questions + + $page_res = array(); + + foreach ($page as $question) { + $question_gui = $this->object->getQuestionGUI($question["type_tag"], $question["question_id"]); + if (is_object($question_gui)) { + $question_parts = array(); + + // heading + if (strlen($question["heading"])) { + $question_parts[$this->lng->txt("heading")] = trim($question["heading"]); + } + + if ($show_titles) { + $question_parts[$this->lng->txt("title")] = trim($question["title"]); + } + + if ((bool) $question["questionblock_show_questiontext"]) { + $question_parts[$this->lng->txt("question")] = trim(strip_tags($question_gui->object->getQuestionText())); + } + + $answers = $question_gui->getParsedAnswers( + $this->object->loadWorkingData($question["question_id"], $a_active_id), + true + ); + + if (sizeof($answers)) { + $multiline = false; + if (sizeof($answers) > 1 || + get_class($question_gui) == "SurveyTextQuestionGUI") { + $multiline = true; + } + + $parts = array(); + foreach ($answers as $answer) { + $text = null; + if ($answer["textanswer"]) { + $text = ' ("' . $answer["textanswer"] . '")'; + } + if (!isset($answer["cols"])) { + if (isset($answer["title"])) { + $parts[] = $answer["title"] . $text; + } elseif (isset($answer["value"])) { + $parts[] = $answer["value"]; + } elseif ($text) { + $parts[] = substr($text, 2, -1); + } + } + // matrix + else { + $tmp = array(); + foreach ($answer["cols"] as $col) { + $tmp[] = $col["title"]; + } + $parts[] = $answer["title"] . ": " . implode(", ", $tmp) . $text; + } + } + $question_parts[$this->lng->txt("answer")] = + ($multiline ? "\n" : "") . implode("\n", $parts); + } + + $tmp = array(); + foreach ($question_parts as $type => $value) { + $tmp[] = $type . ": " . $value; + } + $page_res[] = implode("\n", $tmp); + } + } + + $res[] = implode("\n\n-------------------------------\n\n", $page_res); + } + } + + $res[] = "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; + + return implode("\n", $res); + } + + public function sendUserResultsMail($a_active_id, $a_recipient) + { + $ilUser = $this->user; + + $finished = $this->object->getSurveyParticipants(array($a_active_id)); + $finished = array_pop($finished); + $finished = ilDatePresentation::formatDate(new ilDateTime($finished["finished_tstamp"], IL_CAL_UNIX)); + + require_once "Services/Mail/classes/class.ilMail.php"; + require_once "Services/Link/classes/class.ilLink.php"; + + $body = ilMail::getSalutation($ilUser->getId()) . "\n\n"; + $body .= $this->lng->txt("svy_mail_own_results_body") . "\n"; + $body .= "\n" . $this->lng->txt("obj_svy") . ": " . $this->object->getTitle() . "\n"; + $body .= ilLink::_getLink($this->object->getRefId(), "svy") . "\n"; + $body .= "\n" . $this->lng->txt("survey_results_finished") . ": " . $finished . "\n\n"; + + if ($this->object->hasMailOwnResults()) { + $subject = "svy_mail_own_results_subject"; + $body .= $this->getUserResultsPlain($a_active_id); + } else { + $subject = "svy_mail_confirmation_subject"; + } + + // $body .= ilMail::_getAutoGeneratedMessageString($this->lng); + $body .= ilMail::_getInstallationSignature(); + + require_once "Services/Mail/classes/class.ilMail.php"; + $mail = new ilMail(ANONYMOUS_USER_ID); + $mail->sendMimeMail( + $a_recipient, + null, + null, + sprintf($this->lng->txt($subject), $this->object->getTitle()), + $body, + null, + true + ); + } + + public function mailUserResultsObject() + { + $ilUser = $this->user; + + $anonymous_code = $_SESSION["anonymous_id"][$this->object->getId()]; + $active_id = $this->object->getActiveID($ilUser->getId(), $anonymous_code, 0); + if ($this->object->isSurveyStarted($ilUser->getId(), $anonymous_code) !== 1 || + !$active_id) { + $this->ctrl->redirect($this, "infoScreen"); + } + + $recipient = $_POST["mail"]; + if (!$recipient) { + $recipient = $ilUser->getEmail(); + } + if (!ilUtil::is_email($recipient)) { + $this->ctrl->redirect($this, "infoScreen"); + } + + $this->sendUserResultsMail($active_id, $recipient); + + ilUtil::sendSuccess($this->lng->txt("mail_sent"), true); + $this->ctrl->redirect($this, "infoScreen"); + } + + /** + * Check rbac or position permission + * @param string $a_rbac_permission + * @param string $a_position_permission + * @return bool + */ + protected function checkRbacOrPositionPermission($a_rbac_permission, $a_position_permission) + { + $access = $GLOBALS['DIC']->access(); + return $access->checkRbacOrPositionPermissionAccess( + $a_rbac_permission, + $a_position_permission, + $this->object->getRefId() + ); + } +} diff --git a/Modules/Survey/classes/class.ilObjSurveyListGUI.php b/Modules/Survey/classes/class.ilObjSurveyListGUI.php index d8a5266c1b5d01da0f6ac770fa89bc0da69c9cc8..4d595227e022079e3c421fd50b9947d6d31bf358 100644 --- a/Modules/Survey/classes/class.ilObjSurveyListGUI.php +++ b/Modules/Survey/classes/class.ilObjSurveyListGUI.php @@ -1,24 +1,24 @@ lng = $DIC->language(); - $this->lng->loadLanguageModule("survey"); - $this->user = $DIC->user(); - $this->rbacsystem = $DIC->rbac()->system(); - parent::__construct(); - $this->info_screen_enabled = true; - } - - /** - * initialisation - */ - function init() - { - $this->static_link_enabled = true; - $this->delete_enabled = true; - $this->cut_enabled = true; - $this->copy_enabled = true; - $this->subscribe_enabled = true; - $this->link_enabled = true; - $this->type = "svy"; - $this->gui_class_name = "ilobjsurveygui"; - - // general commands array - include_once('./Modules/Survey/classes/class.ilObjSurveyAccess.php'); - $this->commands = ilObjSurveyAccess::_getCommands(); - } - - - /** - * inititialize new item - * - * @param int $a_ref_id reference id - * @param int $a_obj_id object id - * @param string $a_title title - * @param string $a_description description - */ - function initItem($a_ref_id, $a_obj_id, $a_title = "", $a_description = "") - { - parent::initItem($a_ref_id, $a_obj_id, $a_title, $a_description); - } - - - /** - * Get command target frame - * - * @param string $a_cmd command - * - * @return string command target frame - */ - function getCommandFrame($a_cmd) - { - switch($a_cmd) - { - case "": - case "infoScreen": - case "evaluation": - include_once "./Services/UICore/classes/class.ilFrameTargetInfo.php"; - $frame = ilFrameTargetInfo::_getFrame("MainContent"); - break; - - default: - } - - return $frame; - } - - - - /** - * Get item properties - * - * @return array array of property arrays: - * "alert" (boolean) => display as an alert property (usually in red) - * "property" (string) => property name - * "value" (string) => property value - */ - function getProperties() - { - $lng = $this->lng; - $ilUser = $this->user; - $rbacsystem = $this->rbacsystem; - - $props = []; - - if (!$rbacsystem->checkAccess("visible,read", $this->ref_id)) - { - return $props; - } - - $props = parent::getProperties(); - - include_once("./Modules/Survey/classes/class.ilObjSurveyAccess.php"); - if(!ilObject::lookupOfflineStatus($this->obj_id)) - { - // BEGIN Usability Distinguish between status and participation - if (!ilObjSurveyAccess::_lookupCreationComplete($this->obj_id)) - { - // no completion - $props[] = array("alert" => true, - "property" => $lng->txt("svy_participation"), - "value" => $lng->txt("svy_warning_survey_not_complete"), - 'propertyNameVisible' => false); - } - else - { - if ($ilUser->getId() != ANONYMOUS_USER_ID) - { - if(!ilObjSurveyAccess::_lookup360Mode($this->obj_id)) - { - $finished = ilObjSurveyAccess::_lookupFinished($this->obj_id, $ilUser->id); - - // finished - if ($finished === 1) - { - $stat = $this->lng->txt("svy_finished"); - } - // not finished - else if ($finished === 0) - { - $stat = $this->lng->txt("svy_not_finished"); - } - // not started - else - { - $stat = $this->lng->txt("svy_not_started"); - } - $props[] = array("alert" => false, "property" => $lng->txt("svy_participation"), - "value" => $stat, 'propertyNameVisible' => false); - } - else - { - $props[] = array("alert" => false, "property" => "", - "value" => $lng->txt("survey_360_list_title"), 'propertyNameVisible' => false); - } - } - } - // END Usability Distinguish between status and participation - } - - return $props; - } - - - /** - * Get command link url. - * - * @param int $a_ref_id reference id - * @param string $a_cmd command - * - */ - function getCommandLink($a_cmd) - { - $cmd_link = ""; - switch ($a_cmd) - { - default: - $cmd_link = "ilias.php?baseClass=ilObjSurveyGUI&ref_id=" . $this->ref_id . - "&cmd=$a_cmd"; - break; - } - // separate method for this line - return $cmd_link; - } - - - + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * constructor + * + */ + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + $this->lng->loadLanguageModule("survey"); + $this->user = $DIC->user(); + $this->rbacsystem = $DIC->rbac()->system(); + parent::__construct(); + $this->info_screen_enabled = true; + } + + /** + * initialisation + */ + public function init() + { + $this->static_link_enabled = true; + $this->delete_enabled = true; + $this->cut_enabled = true; + $this->copy_enabled = true; + $this->subscribe_enabled = true; + $this->link_enabled = true; + $this->type = "svy"; + $this->gui_class_name = "ilobjsurveygui"; + + // general commands array + include_once('./Modules/Survey/classes/class.ilObjSurveyAccess.php'); + $this->commands = ilObjSurveyAccess::_getCommands(); + } + + + /** + * inititialize new item + * + * @param int $a_ref_id reference id + * @param int $a_obj_id object id + * @param string $a_title title + * @param string $a_description description + */ + public function initItem($a_ref_id, $a_obj_id, $a_title = "", $a_description = "") + { + parent::initItem($a_ref_id, $a_obj_id, $a_title, $a_description); + } + + + /** + * Get command target frame + * + * @param string $a_cmd command + * + * @return string command target frame + */ + public function getCommandFrame($a_cmd) + { + switch ($a_cmd) { + case "": + case "infoScreen": + case "evaluation": + include_once "./Services/UICore/classes/class.ilFrameTargetInfo.php"; + $frame = ilFrameTargetInfo::_getFrame("MainContent"); + break; + + default: + } + + return $frame; + } + + + + /** + * Get item properties + * + * @return array array of property arrays: + * "alert" (boolean) => display as an alert property (usually in red) + * "property" (string) => property name + * "value" (string) => property value + */ + public function getProperties() + { + $lng = $this->lng; + $ilUser = $this->user; + $rbacsystem = $this->rbacsystem; + + $props = []; + + if (!$rbacsystem->checkAccess("visible,read", $this->ref_id)) { + return $props; + } + + $props = parent::getProperties(); + + include_once("./Modules/Survey/classes/class.ilObjSurveyAccess.php"); + if (!ilObject::lookupOfflineStatus($this->obj_id)) { + // BEGIN Usability Distinguish between status and participation + if (!ilObjSurveyAccess::_lookupCreationComplete($this->obj_id)) { + // no completion + $props[] = array("alert" => true, + "property" => $lng->txt("svy_participation"), + "value" => $lng->txt("svy_warning_survey_not_complete"), + 'propertyNameVisible' => false); + } else { + if ($ilUser->getId() != ANONYMOUS_USER_ID) { + if (!ilObjSurveyAccess::_lookup360Mode($this->obj_id)) { + $finished = ilObjSurveyAccess::_lookupFinished($this->obj_id, $ilUser->id); + + // finished + if ($finished === 1) { + $stat = $this->lng->txt("svy_finished"); + } + // not finished + elseif ($finished === 0) { + $stat = $this->lng->txt("svy_not_finished"); + } + // not started + else { + $stat = $this->lng->txt("svy_not_started"); + } + $props[] = array("alert" => false, "property" => $lng->txt("svy_participation"), + "value" => $stat, 'propertyNameVisible' => false); + } else { + $props[] = array("alert" => false, "property" => "", + "value" => $lng->txt("survey_360_list_title"), 'propertyNameVisible' => false); + } + } + } + // END Usability Distinguish between status and participation + } + + return $props; + } + + + /** + * Get command link url. + * + * @param int $a_ref_id reference id + * @param string $a_cmd command + * + */ + public function getCommandLink($a_cmd) + { + $cmd_link = ""; + switch ($a_cmd) { + default: + $cmd_link = "ilias.php?baseClass=ilObjSurveyGUI&ref_id=" . $this->ref_id . + "&cmd=$a_cmd"; + break; + } + // separate method for this line + return $cmd_link; + } } // END class.ilObjTestListGUI -?> diff --git a/Modules/Survey/classes/class.ilSurveyConstraintsGUI.php b/Modules/Survey/classes/class.ilSurveyConstraintsGUI.php index d9b550fc2957db5d256703b105c0807f3e3a11e8..c74934f288122f96caf88e9b762361c93d4781ae 100644 --- a/Modules/Survey/classes/class.ilSurveyConstraintsGUI.php +++ b/Modules/Survey/classes/class.ilSurveyConstraintsGUI.php @@ -1,433 +1,392 @@ - -* @version $Id: class.ilObjSurveyGUI.php 43670 2013-07-26 08:41:31Z jluetzen $ -* -* @ilCtrl_Calls ilSurveyConstraintsGUI: -* -* @ingroup ModulesSurvey -*/ -class ilSurveyConstraintsGUI -{ - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilAccessHandler - */ - protected $access; - - public function __construct(ilObjSurveyGUI $a_parent_gui) - { - global $DIC; - - $this->access = $DIC->access(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $tpl = $DIC["tpl"]; - - $this->parent_gui = $a_parent_gui; - $this->object = $this->parent_gui->object; - - $this->ctrl = $ilCtrl; - $this->lng = $lng; - $this->tpl = $tpl; - } - - public function executeCommand() - { - $ilCtrl = $this->ctrl; - - $cmd = $ilCtrl->getCmd("constraints"); - $cmd .= "Object"; - - $this->$cmd(); - } - - /** - * Administration page for survey constraints - */ - public function constraintsObject() - { - $step = 0; - if (array_key_exists("step", $_GET)) - { - $step = (int)$_GET["step"]; - } - switch ($step) - { - case 1: - $this->constraintStep1Object(); - return; - break; - case 2: - return; - break; - case 3: - return; - break; - } - - $hasDatasets = ilObjSurvey::_hasDatasets($this->object->getSurveyId()); - - include_once "Modules/Survey/classes/tables/class.SurveyConstraintsTableGUI.php"; - $tbl = new SurveyConstraintsTableGUI($this, "constraints", $this->object, $hasDatasets); - - $mess = ""; - if ($hasDatasets) - { - $mbox = new ilSurveyContainsDataMessageBoxGUI(); - $mess = $mbox->getHTML(); - } - else - { - $_SESSION["constraintstructure"] = $tbl->getStructure(); - } - - $this->tpl->setContent($mess.$tbl->getHTML()); - } - - /** - * Add a precondition for a survey question or question block - */ - public function constraintsAddObject() - { - if (strlen($_POST["v"]) == 0) - { - ilUtil::sendFailure($this->lng->txt("msg_enter_value_for_valid_constraint")); - return $this->constraintStep3Object(); - } - $survey_questions =& $this->object->getSurveyQuestions(); - $structure =& $_SESSION["constraintstructure"]; - $include_elements = $_SESSION["includeElements"]; - foreach ($include_elements as $elementCounter) - { - if (is_array($structure[$elementCounter])) - { - if (strlen($_GET["precondition"])) - { - $this->object->updateConstraint($_GET['precondition'], $_POST["q"], $_POST["r"], $_POST["v"], $_POST['c']); - } - else - { - $constraint_id = $this->object->addConstraint($_POST["q"], $_POST["r"], $_POST["v"], $_POST['c']); - foreach ($structure[$elementCounter] as $key => $question_id) - { - $this->object->addConstraintToQuestion($question_id, $constraint_id); - } - } - if (count($structure[$elementCounter]) > 1) - { - $this->object->updateConjunctionForQuestions($structure[$elementCounter], $_POST['c']); - } - } - } - unset($_SESSION["includeElements"]); - unset($_SESSION["constraintstructure"]); - $this->ctrl->redirect($this, "constraints"); - } - - /** - * Handles the first step of the precondition add action - */ - public function constraintStep1Object() - { - $survey_questions =& $this->object->getSurveyQuestions(); - $structure =& $_SESSION["constraintstructure"]; - $start = $_GET["start"]; - $option_questions = array(); - for ($i = 1; $i < $start; $i++) - { - if (is_array($structure[$i])) - { - foreach ($structure[$i] as $key => $question_id) - { - if ($survey_questions[$question_id]["usableForPrecondition"]) - { - array_push($option_questions, array("question_id" => $survey_questions[$question_id]["question_id"], "title" => $survey_questions[$question_id]["title"], "type_tag" => $survey_questions[$question_id]["type_tag"])); - } - } - } - } - if (count($option_questions) == 0) - { - unset($_SESSION["includeElements"]); - unset($_SESSION["constraintstructure"]); - ilUtil::sendInfo($this->lng->txt("constraints_no_nonessay_available"), true); - $this->ctrl->redirect($this, "constraints"); - } - $this->constraintForm(1, $_POST, $survey_questions, $option_questions); - } - - /** - * Handles the second step of the precondition add action - */ - public function constraintStep2Object() - { - $survey_questions =& $this->object->getSurveyQuestions(); - $option_questions = array(); - array_push($option_questions, array("question_id" => $_POST["q"], "title" => $survey_questions[$_POST["q"]]["title"], "type_tag" => $survey_questions[$_POST["q"]]["type_tag"])); - $this->constraintForm(2, $_POST, $survey_questions, $option_questions); - } - - /** - * Handles the third step of the precondition add action - */ - public function constraintStep3Object() - { - $survey_questions =& $this->object->getSurveyQuestions(); - $option_questions = array(); - if (strlen($_GET["precondition"])) - { - if(!$this->validateConstraintForEdit($_GET["precondition"])) - { - $this->ctrl->redirect($this, "constraints"); - } - - $pc = $this->object->getPrecondition($_GET["precondition"]); - $postvalues = array( - "c" => $pc["conjunction"], - "q" => $pc["question_fi"], - "r" => $pc["relation_id"], - "v" => $pc["value"] - ); - array_push($option_questions, array("question_id" => $pc["question_fi"], "title" => $survey_questions[$pc["question_fi"]]["title"], "type_tag" => $survey_questions[$pc["question_fi"]]["type_tag"])); - $this->constraintForm(3, $postvalues, $survey_questions, $option_questions); - } - else - { - array_push($option_questions, array("question_id" => $_POST["q"], "title" => $survey_questions[$_POST["q"]]["title"], "type_tag" => $survey_questions[$_POST["q"]]["type_tag"])); - $this->constraintForm(3, $_POST, $survey_questions, $option_questions); - } - } - - public function constraintForm($step, $postvalues, &$survey_questions, $questions = FALSE) - { - if (strlen($_GET["start"])) $this->ctrl->setParameter($this, "start", $_GET["start"]); - $this->ctrl->saveParameter($this, "precondition"); - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - $form->setTableWidth("100%"); - $form->setId("constraintsForm"); - - // #9366 - $title = array(); - $title_ids = $_SESSION["includeElements"]; - if(!$title_ids) - { - $title_ids = array($_GET["start"]); - } - foreach($title_ids as $title_id) - { - // question block - if ($survey_questions[$_SESSION["constraintstructure"][$title_id][0]]["questionblock_id"] > 0) - { - $title[] = $this->lng->txt("questionblock") . ": " . $survey_questions[$_SESSION["constraintstructure"][$title_id][0]]["questionblock_title"]; - } - // question - else - { - $title[] = $this->lng->txt($survey_questions[$_SESSION["constraintstructure"][$title_id][0]]["type_tag"]) . ": " . - $survey_questions[$_SESSION["constraintstructure"][$title_id][0]]["title"]; - } - } - $header = new ilFormSectionHeaderGUI(); - $header->setTitle(implode("
", $title)); - $form->addItem($header); - - $fulfilled = new ilRadioGroupInputGUI($this->lng->txt("constraint_fulfilled"), "c"); - $fulfilled->addOption(new ilRadioOption($this->lng->txt("conjunction_and"), '0', '')); - $fulfilled->addOption(new ilRadioOption($this->lng->txt("conjunction_or"), '1', '')); - $fulfilled->setValue((strlen($postvalues['c'])) ? $postvalues['c'] : 0); - $form->addItem($fulfilled); - - $step1 = new ilSelectInputGUI($this->lng->txt("step") . " 1: " . $this->lng->txt("select_prior_question"), "q"); - $options = array(); - if (is_array($questions)) - { - foreach ($questions as $question) - { - $options[$question["question_id"]] = $question["title"] . " (" . SurveyQuestion::_getQuestionTypeName($question["type_tag"]) . ")"; - } - } - $step1->setOptions($options); - $step1->setValue($postvalues["q"]); - $form->addItem($step1); - - if ($step > 1) - { - $relations = $this->object->getAllRelations(); - $step2 = new ilSelectInputGUI($this->lng->txt("step") . " 2: " . $this->lng->txt("select_relation"), "r"); - $options = array(); - foreach ($relations as $rel_id => $relation) - { - if (in_array($relation["short"], $survey_questions[$postvalues["q"]]["availableRelations"])) - { - $options[$rel_id] = $relation['short']; - } - } - $step2->setOptions($options); - $step2->setValue($postvalues["r"]); - $form->addItem($step2); - } - - if ($step > 2) - { - $variables =& $this->object->getVariables($postvalues["q"]); - $question_type = $survey_questions[$postvalues["q"]]["type_tag"]; - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - SurveyQuestion::_includeClass($question_type); - $question = new $question_type(); - $question->loadFromDb($postvalues["q"]); - - $step3 = $question->getPreconditionSelectValue($postvalues["v"], $this->lng->txt("step") . " 3: " . $this->lng->txt("select_value"), "v"); - $form->addItem($step3); - } - - switch ($step) - { - case 1: - $cmd_continue = "constraintStep2"; - $cmd_back = "constraints"; - break; - case 2: - $cmd_continue = "constraintStep3"; - $cmd_back = "constraintStep1"; - break; - case 3: - $cmd_continue = "constraintsAdd"; - $cmd_back = "constraintStep2"; - break; - } - $form->addCommandButton($cmd_back, $this->lng->txt("back")); - $form->addCommandButton($cmd_continue, $this->lng->txt("continue")); - - $this->tpl->setVariable("ADM_CONTENT", $form->getHTML()); - } - - /** - * Validate if given constraint id is part of current survey and there are sufficient permissions to edit+ - * - * @param int $a_id - * @return bool - */ - protected function validateConstraintForEdit($a_id) - { - $ilAccess = $this->access; - - if(ilObjSurvey::_hasDatasets($this->object->getSurveyId())) - { - return false; - } - if(!$ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - return false; - } - - return true; - } - - /** - * Delete constraint confirmation - */ - public function confirmDeleteConstraintsObject() - { - $id = (int)$_REQUEST["precondition"]; - if(!$this->validateConstraintForEdit($id)) - { - $this->ctrl->redirect($this, "constraints"); - } - - $constraint = $this->object->getPrecondition($id); - $questions = $this->object->getSurveyQuestions(); - $question = $questions[$constraint["question_fi"]]; - $relation = $questions[$constraint["ref_question_fi"]]; - $relation = $relation["title"]; - - // see ilSurveyConstraintsTableGUI - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - $question_type = SurveyQuestion::_getQuestionType($constraint["question_fi"]); - SurveyQuestion::_includeClass($question_type); - $question_obj = new $question_type(); - $question_obj->loadFromDb($constraint["question_fi"]); - $valueoutput = $question_obj->getPreconditionValueOutput($constraint["value"]); - - $title = $question["title"]." ".$constraint["shortname"]." ".$valueoutput; - - $this->ctrl->saveParameter($this, "precondition"); - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setHeaderText(sprintf($this->lng->txt("survey_sure_delete_constraint"), $title, $relation)); - - $cgui->setFormAction($this->ctrl->getFormAction($this, "deleteConstraints")); - $cgui->setCancel($this->lng->txt("cancel"), "constraints"); - $cgui->setConfirm($this->lng->txt("confirm"), "deleteConstraints"); - - $this->tpl->setContent($cgui->getHTML()); - } - - /** - * Delete constraints of a survey - */ - public function deleteConstraintsObject() - { - $id = (int)$_REQUEST["precondition"]; - if($this->validateConstraintForEdit($id)) - { - ilUtil::sendSuccess($this->lng->txt("survey_constraint_deleted"), true); - $this->object->deleteConstraint($id); - } - - $this->ctrl->redirect($this, "constraints"); - } - - function createConstraintsObject() - { - $include_elements = $_POST["includeElements"]; - if ((!is_array($include_elements)) || (count($include_elements) == 0)) - { - ilUtil::sendInfo($this->lng->txt("constraints_no_questions_or_questionblocks_selected"), true); - $this->ctrl->redirect($this, "constraints"); - } - else if (count($include_elements) >= 1) - { - $_SESSION["includeElements"] = $include_elements; - sort($include_elements, SORT_NUMERIC); - $_GET["start"] = $include_elements[0]; - $this->constraintStep1Object(); - } - } - - function editPreconditionObject() - { - if(!$this->validateConstraintForEdit($_GET["precondition"])) - { - $this->ctrl->redirect($this, "constraints"); - } - - $_SESSION["includeElements"] = array($_GET["start"]); - $this->ctrl->setParameter($this, "precondition", $_GET["precondition"]); - $this->ctrl->setParameter($this, "start", $_GET["start"]); - $this->ctrl->redirect($this, "constraintStep3"); - } -} - -?> \ No newline at end of file + +* @version $Id: class.ilObjSurveyGUI.php 43670 2013-07-26 08:41:31Z jluetzen $ +* +* @ilCtrl_Calls ilSurveyConstraintsGUI: +* +* @ingroup ModulesSurvey +*/ +class ilSurveyConstraintsGUI +{ + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilAccessHandler + */ + protected $access; + + public function __construct(ilObjSurveyGUI $a_parent_gui) + { + global $DIC; + + $this->access = $DIC->access(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $tpl = $DIC["tpl"]; + + $this->parent_gui = $a_parent_gui; + $this->object = $this->parent_gui->object; + + $this->ctrl = $ilCtrl; + $this->lng = $lng; + $this->tpl = $tpl; + } + + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $cmd = $ilCtrl->getCmd("constraints"); + $cmd .= "Object"; + + $this->$cmd(); + } + + /** + * Administration page for survey constraints + */ + public function constraintsObject() + { + $step = 0; + if (array_key_exists("step", $_GET)) { + $step = (int) $_GET["step"]; + } + switch ($step) { + case 1: + $this->constraintStep1Object(); + return; + break; + case 2: + return; + break; + case 3: + return; + break; + } + + $hasDatasets = ilObjSurvey::_hasDatasets($this->object->getSurveyId()); + + include_once "Modules/Survey/classes/tables/class.SurveyConstraintsTableGUI.php"; + $tbl = new SurveyConstraintsTableGUI($this, "constraints", $this->object, $hasDatasets); + + $mess = ""; + if ($hasDatasets) { + $mbox = new ilSurveyContainsDataMessageBoxGUI(); + $mess = $mbox->getHTML(); + } else { + $_SESSION["constraintstructure"] = $tbl->getStructure(); + } + + $this->tpl->setContent($mess . $tbl->getHTML()); + } + + /** + * Add a precondition for a survey question or question block + */ + public function constraintsAddObject() + { + if (strlen($_POST["v"]) == 0) { + ilUtil::sendFailure($this->lng->txt("msg_enter_value_for_valid_constraint")); + return $this->constraintStep3Object(); + } + $survey_questions =&$this->object->getSurveyQuestions(); + $structure =&$_SESSION["constraintstructure"]; + $include_elements = $_SESSION["includeElements"]; + foreach ($include_elements as $elementCounter) { + if (is_array($structure[$elementCounter])) { + if (strlen($_GET["precondition"])) { + $this->object->updateConstraint($_GET['precondition'], $_POST["q"], $_POST["r"], $_POST["v"], $_POST['c']); + } else { + $constraint_id = $this->object->addConstraint($_POST["q"], $_POST["r"], $_POST["v"], $_POST['c']); + foreach ($structure[$elementCounter] as $key => $question_id) { + $this->object->addConstraintToQuestion($question_id, $constraint_id); + } + } + if (count($structure[$elementCounter]) > 1) { + $this->object->updateConjunctionForQuestions($structure[$elementCounter], $_POST['c']); + } + } + } + unset($_SESSION["includeElements"]); + unset($_SESSION["constraintstructure"]); + $this->ctrl->redirect($this, "constraints"); + } + + /** + * Handles the first step of the precondition add action + */ + public function constraintStep1Object() + { + $survey_questions =&$this->object->getSurveyQuestions(); + $structure =&$_SESSION["constraintstructure"]; + $start = $_GET["start"]; + $option_questions = array(); + for ($i = 1; $i < $start; $i++) { + if (is_array($structure[$i])) { + foreach ($structure[$i] as $key => $question_id) { + if ($survey_questions[$question_id]["usableForPrecondition"]) { + array_push($option_questions, array("question_id" => $survey_questions[$question_id]["question_id"], "title" => $survey_questions[$question_id]["title"], "type_tag" => $survey_questions[$question_id]["type_tag"])); + } + } + } + } + if (count($option_questions) == 0) { + unset($_SESSION["includeElements"]); + unset($_SESSION["constraintstructure"]); + ilUtil::sendInfo($this->lng->txt("constraints_no_nonessay_available"), true); + $this->ctrl->redirect($this, "constraints"); + } + $this->constraintForm(1, $_POST, $survey_questions, $option_questions); + } + + /** + * Handles the second step of the precondition add action + */ + public function constraintStep2Object() + { + $survey_questions =&$this->object->getSurveyQuestions(); + $option_questions = array(); + array_push($option_questions, array("question_id" => $_POST["q"], "title" => $survey_questions[$_POST["q"]]["title"], "type_tag" => $survey_questions[$_POST["q"]]["type_tag"])); + $this->constraintForm(2, $_POST, $survey_questions, $option_questions); + } + + /** + * Handles the third step of the precondition add action + */ + public function constraintStep3Object() + { + $survey_questions =&$this->object->getSurveyQuestions(); + $option_questions = array(); + if (strlen($_GET["precondition"])) { + if (!$this->validateConstraintForEdit($_GET["precondition"])) { + $this->ctrl->redirect($this, "constraints"); + } + + $pc = $this->object->getPrecondition($_GET["precondition"]); + $postvalues = array( + "c" => $pc["conjunction"], + "q" => $pc["question_fi"], + "r" => $pc["relation_id"], + "v" => $pc["value"] + ); + array_push($option_questions, array("question_id" => $pc["question_fi"], "title" => $survey_questions[$pc["question_fi"]]["title"], "type_tag" => $survey_questions[$pc["question_fi"]]["type_tag"])); + $this->constraintForm(3, $postvalues, $survey_questions, $option_questions); + } else { + array_push($option_questions, array("question_id" => $_POST["q"], "title" => $survey_questions[$_POST["q"]]["title"], "type_tag" => $survey_questions[$_POST["q"]]["type_tag"])); + $this->constraintForm(3, $_POST, $survey_questions, $option_questions); + } + } + + public function constraintForm($step, $postvalues, &$survey_questions, $questions = false) + { + if (strlen($_GET["start"])) { + $this->ctrl->setParameter($this, "start", $_GET["start"]); + } + $this->ctrl->saveParameter($this, "precondition"); + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this)); + $form->setTableWidth("100%"); + $form->setId("constraintsForm"); + + // #9366 + $title = array(); + $title_ids = $_SESSION["includeElements"]; + if (!$title_ids) { + $title_ids = array($_GET["start"]); + } + foreach ($title_ids as $title_id) { + // question block + if ($survey_questions[$_SESSION["constraintstructure"][$title_id][0]]["questionblock_id"] > 0) { + $title[] = $this->lng->txt("questionblock") . ": " . $survey_questions[$_SESSION["constraintstructure"][$title_id][0]]["questionblock_title"]; + } + // question + else { + $title[] = $this->lng->txt($survey_questions[$_SESSION["constraintstructure"][$title_id][0]]["type_tag"]) . ": " . + $survey_questions[$_SESSION["constraintstructure"][$title_id][0]]["title"]; + } + } + $header = new ilFormSectionHeaderGUI(); + $header->setTitle(implode("
", $title)); + $form->addItem($header); + + $fulfilled = new ilRadioGroupInputGUI($this->lng->txt("constraint_fulfilled"), "c"); + $fulfilled->addOption(new ilRadioOption($this->lng->txt("conjunction_and"), '0', '')); + $fulfilled->addOption(new ilRadioOption($this->lng->txt("conjunction_or"), '1', '')); + $fulfilled->setValue((strlen($postvalues['c'])) ? $postvalues['c'] : 0); + $form->addItem($fulfilled); + + $step1 = new ilSelectInputGUI($this->lng->txt("step") . " 1: " . $this->lng->txt("select_prior_question"), "q"); + $options = array(); + if (is_array($questions)) { + foreach ($questions as $question) { + $options[$question["question_id"]] = $question["title"] . " (" . SurveyQuestion::_getQuestionTypeName($question["type_tag"]) . ")"; + } + } + $step1->setOptions($options); + $step1->setValue($postvalues["q"]); + $form->addItem($step1); + + if ($step > 1) { + $relations = $this->object->getAllRelations(); + $step2 = new ilSelectInputGUI($this->lng->txt("step") . " 2: " . $this->lng->txt("select_relation"), "r"); + $options = array(); + foreach ($relations as $rel_id => $relation) { + if (in_array($relation["short"], $survey_questions[$postvalues["q"]]["availableRelations"])) { + $options[$rel_id] = $relation['short']; + } + } + $step2->setOptions($options); + $step2->setValue($postvalues["r"]); + $form->addItem($step2); + } + + if ($step > 2) { + $variables =&$this->object->getVariables($postvalues["q"]); + $question_type = $survey_questions[$postvalues["q"]]["type_tag"]; + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + SurveyQuestion::_includeClass($question_type); + $question = new $question_type(); + $question->loadFromDb($postvalues["q"]); + + $step3 = $question->getPreconditionSelectValue($postvalues["v"], $this->lng->txt("step") . " 3: " . $this->lng->txt("select_value"), "v"); + $form->addItem($step3); + } + + switch ($step) { + case 1: + $cmd_continue = "constraintStep2"; + $cmd_back = "constraints"; + break; + case 2: + $cmd_continue = "constraintStep3"; + $cmd_back = "constraintStep1"; + break; + case 3: + $cmd_continue = "constraintsAdd"; + $cmd_back = "constraintStep2"; + break; + } + $form->addCommandButton($cmd_back, $this->lng->txt("back")); + $form->addCommandButton($cmd_continue, $this->lng->txt("continue")); + + $this->tpl->setVariable("ADM_CONTENT", $form->getHTML()); + } + + /** + * Validate if given constraint id is part of current survey and there are sufficient permissions to edit+ + * + * @param int $a_id + * @return bool + */ + protected function validateConstraintForEdit($a_id) + { + $ilAccess = $this->access; + + if (ilObjSurvey::_hasDatasets($this->object->getSurveyId())) { + return false; + } + if (!$ilAccess->checkAccess("write", "", $this->object->getRefId())) { + return false; + } + + return true; + } + + /** + * Delete constraint confirmation + */ + public function confirmDeleteConstraintsObject() + { + $id = (int) $_REQUEST["precondition"]; + if (!$this->validateConstraintForEdit($id)) { + $this->ctrl->redirect($this, "constraints"); + } + + $constraint = $this->object->getPrecondition($id); + $questions = $this->object->getSurveyQuestions(); + $question = $questions[$constraint["question_fi"]]; + $relation = $questions[$constraint["ref_question_fi"]]; + $relation = $relation["title"]; + + // see ilSurveyConstraintsTableGUI + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + $question_type = SurveyQuestion::_getQuestionType($constraint["question_fi"]); + SurveyQuestion::_includeClass($question_type); + $question_obj = new $question_type(); + $question_obj->loadFromDb($constraint["question_fi"]); + $valueoutput = $question_obj->getPreconditionValueOutput($constraint["value"]); + + $title = $question["title"] . " " . $constraint["shortname"] . " " . $valueoutput; + + $this->ctrl->saveParameter($this, "precondition"); + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setHeaderText(sprintf($this->lng->txt("survey_sure_delete_constraint"), $title, $relation)); + + $cgui->setFormAction($this->ctrl->getFormAction($this, "deleteConstraints")); + $cgui->setCancel($this->lng->txt("cancel"), "constraints"); + $cgui->setConfirm($this->lng->txt("confirm"), "deleteConstraints"); + + $this->tpl->setContent($cgui->getHTML()); + } + + /** + * Delete constraints of a survey + */ + public function deleteConstraintsObject() + { + $id = (int) $_REQUEST["precondition"]; + if ($this->validateConstraintForEdit($id)) { + ilUtil::sendSuccess($this->lng->txt("survey_constraint_deleted"), true); + $this->object->deleteConstraint($id); + } + + $this->ctrl->redirect($this, "constraints"); + } + + public function createConstraintsObject() + { + $include_elements = $_POST["includeElements"]; + if ((!is_array($include_elements)) || (count($include_elements) == 0)) { + ilUtil::sendInfo($this->lng->txt("constraints_no_questions_or_questionblocks_selected"), true); + $this->ctrl->redirect($this, "constraints"); + } elseif (count($include_elements) >= 1) { + $_SESSION["includeElements"] = $include_elements; + sort($include_elements, SORT_NUMERIC); + $_GET["start"] = $include_elements[0]; + $this->constraintStep1Object(); + } + } + + public function editPreconditionObject() + { + if (!$this->validateConstraintForEdit($_GET["precondition"])) { + $this->ctrl->redirect($this, "constraints"); + } + + $_SESSION["includeElements"] = array($_GET["start"]); + $this->ctrl->setParameter($this, "precondition", $_GET["precondition"]); + $this->ctrl->setParameter($this, "start", $_GET["start"]); + $this->ctrl->redirect($this, "constraintStep3"); + } +} diff --git a/Modules/Survey/classes/class.ilSurveyContainsDataMessageBoxGUI.php b/Modules/Survey/classes/class.ilSurveyContainsDataMessageBoxGUI.php index 4af8b68127ffd38463f64646691d88fe1e60c81b..86b83649992bd8e784923e7b3febc8bf6bd2aa0f 100644 --- a/Modules/Survey/classes/class.ilSurveyContainsDataMessageBoxGUI.php +++ b/Modules/Survey/classes/class.ilSurveyContainsDataMessageBoxGUI.php @@ -12,49 +12,50 @@ */ class ilSurveyContainsDataMessageBoxGUI { - /** - * @var \ILIAS\DI\UIServices - */ - protected $ui; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * Constructor - */ - public function __construct() - { - global $DIC; - - $this->ui = $DIC->ui(); - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - } - - /** - * Get HTML - * - * @return string - */ - public function getHTML() - { - $ctrl = $this->ctrl; - $lng = $this->lng; - $ui = $this->ui; - - $mbox = $ui->factory()->messageBox()->info($lng->txt("survey_has_datasets_warning_page_view")) - ->withLinks([$ui->factory()->link()->standard($lng->txt("survey_has_datasets_warning_page_view_link"), - $ctrl->getLinkTargetByClass(["ilObjSurveyGUI", "ilSurveyParticipantsGUI"], "maintenance"))]); - - return $ui->renderer()->render($mbox); - } - -} \ No newline at end of file + /** + * @var \ILIAS\DI\UIServices + */ + protected $ui; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->ui = $DIC->ui(); + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + } + + /** + * Get HTML + * + * @return string + */ + public function getHTML() + { + $ctrl = $this->ctrl; + $lng = $this->lng; + $ui = $this->ui; + + $mbox = $ui->factory()->messageBox()->info($lng->txt("survey_has_datasets_warning_page_view")) + ->withLinks([$ui->factory()->link()->standard( + $lng->txt("survey_has_datasets_warning_page_view_link"), + $ctrl->getLinkTargetByClass(["ilObjSurveyGUI", "ilSurveyParticipantsGUI"], "maintenance") + )]); + + return $ui->renderer()->render($mbox); + } +} diff --git a/Modules/Survey/classes/class.ilSurveyCronNotification.php b/Modules/Survey/classes/class.ilSurveyCronNotification.php index f71e4471f6008e808eda2ce4625f4b26ac12d355..e38407c1bc7aa39819965ee53605eb5063d807ad 100644 --- a/Modules/Survey/classes/class.ilSurveyCronNotification.php +++ b/Modules/Survey/classes/class.ilSurveyCronNotification.php @@ -1,115 +1,109 @@ - - * @ingroup Cron - */ -class ilSurveyCronNotification extends ilCronJob -{ - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTree - */ - protected $tree; - - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - if (isset($DIC["tree"])) - { - $this->tree = $DIC->repositoryTree(); - } - } - - public function getId() - { - return "survey_notification"; - } - - public function getTitle() - { - $lng = $this->lng; - - $lng->loadLanguageModule("survey"); - return $lng->txt("survey_reminder_setting"); - } - - public function getDescription() - { - $lng = $this->lng; - - $lng->loadLanguageModule("survey"); - return $lng->txt("survey_reminder_cron_info"); - } - - public function getDefaultScheduleType() - { - return self::SCHEDULE_TYPE_DAILY; - } - - public function getDefaultScheduleValue() - { - return; - } - - public function hasAutoActivation() - { - return true; - } - - public function hasFlexibleSchedule() - { - return false; - } - - public function run() - { - $tree = $this->tree; - - include_once "Modules/Survey/classes/class.ilObjSurvey.php"; - - $status = ilCronJobResult::STATUS_NO_ACTION; - $message = array(); - - $root = $tree->getNodeData(ROOT_FOLDER_ID); - foreach($tree->getSubTree($root, false, "svy") as $svy_ref_id) - { - $svy = new ilObjSurvey($svy_ref_id); - $num = $svy->checkReminder(); - if($num !== false) - { - $message[] = $svy_ref_id."(".$num.")"; - $status = ilCronJobResult::STATUS_OK; - } - } - - $result = new ilCronJobResult(); - $result->setStatus($status); - - if(sizeof($message)) - { - $result->setMessage("Ref-Ids: ".implode(", ", $message)); - $result->setCode("#".sizeof($message)); - } - - return $result; - } -} - -?> \ No newline at end of file + + * @ingroup Cron + */ +class ilSurveyCronNotification extends ilCronJob +{ + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTree + */ + protected $tree; + + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + if (isset($DIC["tree"])) { + $this->tree = $DIC->repositoryTree(); + } + } + + public function getId() + { + return "survey_notification"; + } + + public function getTitle() + { + $lng = $this->lng; + + $lng->loadLanguageModule("survey"); + return $lng->txt("survey_reminder_setting"); + } + + public function getDescription() + { + $lng = $this->lng; + + $lng->loadLanguageModule("survey"); + return $lng->txt("survey_reminder_cron_info"); + } + + public function getDefaultScheduleType() + { + return self::SCHEDULE_TYPE_DAILY; + } + + public function getDefaultScheduleValue() + { + return; + } + + public function hasAutoActivation() + { + return true; + } + + public function hasFlexibleSchedule() + { + return false; + } + + public function run() + { + $tree = $this->tree; + + include_once "Modules/Survey/classes/class.ilObjSurvey.php"; + + $status = ilCronJobResult::STATUS_NO_ACTION; + $message = array(); + + $root = $tree->getNodeData(ROOT_FOLDER_ID); + foreach ($tree->getSubTree($root, false, "svy") as $svy_ref_id) { + $svy = new ilObjSurvey($svy_ref_id); + $num = $svy->checkReminder(); + if ($num !== false) { + $message[] = $svy_ref_id . "(" . $num . ")"; + $status = ilCronJobResult::STATUS_OK; + } + } + + $result = new ilCronJobResult(); + $result->setStatus($status); + + if (sizeof($message)) { + $result->setMessage("Ref-Ids: " . implode(", ", $message)); + $result->setCode("#" . sizeof($message)); + } + + return $result; + } +} diff --git a/Modules/Survey/classes/class.ilSurveyDataSet.php b/Modules/Survey/classes/class.ilSurveyDataSet.php index 9dbfb7610cc0d93af11f9be7b838d314c1a2093a..56db7b0daee43e51d75ecf2662c41d28a0b9d2ed 100644 --- a/Modules/Survey/classes/class.ilSurveyDataSet.php +++ b/Modules/Survey/classes/class.ilSurveyDataSet.php @@ -5,7 +5,7 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); /** * Survey Data set class - * + * * Currently most of the survey export is still done "old school". * * The dataset part implements mostly the 360 extension: @@ -19,164 +19,150 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); */ class ilSurveyDataSet extends ilDataSet { - /** - * Get supported versions - * - * @return array of version strings - */ - public function getSupportedVersions() - { - return array("5.1.0"); - } - - /** - * Get xml namespace - * - * @param - * @return - */ - function getXmlNamespace($a_entity, $a_schema_version) - { - return "http://www.ilias.de/xml/Modules/Survey/".$a_entity; - } - - /** - * Get field types for entity - * - * @param string $a_entity entity - * @param string $a_version version - * @return array - */ - protected function getTypes($a_entity, $a_version) - { - if ($a_entity == "svy_quest_skill") - { - switch ($a_version) - { - case "5.1.0": - return array( - "QId" => "integer", - "SurveyId" => "integer", - "BaseSkillId" => "integer", - "TrefId" => "integer" - ); - } - } - if ($a_entity == "svy_skill_threshold") - { - switch ($a_version) - { - case "5.1.0": - return array( - "SurveyId" => "integer", - "BaseSkillId" => "integer", - "TrefId" => "integer", - "LevelId" => "integer", - "Treshold" => "integer" - ); - } - } - return array(); - } - - /** - * Read data - * - * @param string $a_entity entity - * @param string $a_version version - * @param array $a_ids ids - * @param string $a_field field - */ - function readData($a_entity, $a_version, $a_ids, $a_field = "") - { - $ilDB = $this->db; + /** + * Get supported versions + * + * @return array of version strings + */ + public function getSupportedVersions() + { + return array("5.1.0"); + } + + /** + * Get xml namespace + * + * @param + * @return + */ + public function getXmlNamespace($a_entity, $a_schema_version) + { + return "http://www.ilias.de/xml/Modules/Survey/" . $a_entity; + } + + /** + * Get field types for entity + * + * @param string $a_entity entity + * @param string $a_version version + * @return array + */ + protected function getTypes($a_entity, $a_version) + { + if ($a_entity == "svy_quest_skill") { + switch ($a_version) { + case "5.1.0": + return array( + "QId" => "integer", + "SurveyId" => "integer", + "BaseSkillId" => "integer", + "TrefId" => "integer" + ); + } + } + if ($a_entity == "svy_skill_threshold") { + switch ($a_version) { + case "5.1.0": + return array( + "SurveyId" => "integer", + "BaseSkillId" => "integer", + "TrefId" => "integer", + "LevelId" => "integer", + "Treshold" => "integer" + ); + } + } + return array(); + } - $this->data = array(); + /** + * Read data + * + * @param string $a_entity entity + * @param string $a_version version + * @param array $a_ids ids + * @param string $a_field field + */ + public function readData($a_entity, $a_version, $a_ids, $a_field = "") + { + $ilDB = $this->db; - if (!is_array($a_ids)) - { - $a_ids = array($a_ids); - } + $this->data = array(); - if ($a_entity == "svy_quest_skill") - { - switch ($a_version) - { - case "5.1.0": - $this->getDirectDataFromQuery("SELECT * ". - " FROM svy_quest_skill WHERE ". - $ilDB->in("survey_id", $a_ids, false, "integer")); - break; + if (!is_array($a_ids)) { + $a_ids = array($a_ids); + } - } - } + if ($a_entity == "svy_quest_skill") { + switch ($a_version) { + case "5.1.0": + $this->getDirectDataFromQuery("SELECT * " . + " FROM svy_quest_skill WHERE " . + $ilDB->in("survey_id", $a_ids, false, "integer")); + break; - if ($a_entity == "svy_skill_threshold") - { - switch ($a_version) - { - case "5.1.0": - $this->getDirectDataFromQuery("SELECT * ". - " FROM svy_skill_threshold WHERE ". - $ilDB->in("survey_id", $a_ids, false, "integer")); - break; + } + } - } - } + if ($a_entity == "svy_skill_threshold") { + switch ($a_version) { + case "5.1.0": + $this->getDirectDataFromQuery("SELECT * " . + " FROM svy_skill_threshold WHERE " . + $ilDB->in("survey_id", $a_ids, false, "integer")); + break; - } - - /** - * Determine the dependent sets of data - */ - protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) - { - $ilDB = $this->db; + } + } + } + + /** + * Determine the dependent sets of data + */ + protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) + { + $ilDB = $this->db; - /*switch ($a_entity) - { - case "svy_quest_skill": - $deps["svy_skill_treshold"]["ids"][] = $a_ids; - return $deps; - }*/ + /*switch ($a_entity) + { + case "svy_quest_skill": + $deps["svy_skill_treshold"]["ids"][] = $a_ids; + return $deps; + }*/ - return false; - } - - - /** - * Import record - * - * @param - * @return - */ - function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) - { - switch ($a_entity) - { - case "svy_quest_skill": - include_once("./Services/Skill/classes/class.ilBasicSkill.php"); - $skill_data = ilBasicSkill::getCommonSkillIdForImportId($this->getCurrentInstallationId(), $a_rec["BaseSkillId"], $a_rec["TrefId"]); - $q_id = $a_mapping->getMapping("Modules/Survey", "svy_q", $a_rec["QId"]); - if ($q_id > 0 && count($skill_data) > 0) - { - include_once("./Modules/Survey/classes/class.ilSurveySkill.php"); - $skill_survey = new ilSurveySkill($this->getImport()->getSurvey()); - $skill_survey->addQuestionSkillAssignment($q_id, $skill_data[0]["skill_id"], $skill_data[0]["tref_id"]); - } - break; + return false; + } + + + /** + * Import record + * + * @param + * @return + */ + public function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) + { + switch ($a_entity) { + case "svy_quest_skill": + include_once("./Services/Skill/classes/class.ilBasicSkill.php"); + $skill_data = ilBasicSkill::getCommonSkillIdForImportId($this->getCurrentInstallationId(), $a_rec["BaseSkillId"], $a_rec["TrefId"]); + $q_id = $a_mapping->getMapping("Modules/Survey", "svy_q", $a_rec["QId"]); + if ($q_id > 0 && count($skill_data) > 0) { + include_once("./Modules/Survey/classes/class.ilSurveySkill.php"); + $skill_survey = new ilSurveySkill($this->getImport()->getSurvey()); + $skill_survey->addQuestionSkillAssignment($q_id, $skill_data[0]["skill_id"], $skill_data[0]["tref_id"]); + } + break; - case "svy_skill_threshold": - $l = ilBasicSkill::getLevelIdForImportIdMatchSkill($this->getCurrentInstallationId(), $a_rec["LevelId"], $a_rec["BaseSkillId"], $a_rec["TrefId"]); - if (count($l) > 0) - { - include_once("./Modules/Survey/classes/class.ilSurveySkillThresholds.php"); - $skill_thres = new ilSurveySkillThresholds($this->getImport()->getSurvey()); - //echo "
".$l[0]["skill_id"]."-".$l[0]["tref_id"]."-".$l[0]["level_id"]."-".$a_rec["Threshold"]."-".$sid."-"; exit; - $skill_thres->writeThreshold($l[0]["skill_id"], $l[0]["tref_id"], $l[0]["level_id"], $a_rec["Threshold"]); - } - break; - } - } + case "svy_skill_threshold": + $l = ilBasicSkill::getLevelIdForImportIdMatchSkill($this->getCurrentInstallationId(), $a_rec["LevelId"], $a_rec["BaseSkillId"], $a_rec["TrefId"]); + if (count($l) > 0) { + include_once("./Modules/Survey/classes/class.ilSurveySkillThresholds.php"); + $skill_thres = new ilSurveySkillThresholds($this->getImport()->getSurvey()); + //echo "
".$l[0]["skill_id"]."-".$l[0]["tref_id"]."-".$l[0]["level_id"]."-".$a_rec["Threshold"]."-".$sid."-"; exit; + $skill_thres->writeThreshold($l[0]["skill_id"], $l[0]["tref_id"], $l[0]["level_id"], $a_rec["Threshold"]); + } + break; + } + } } -?> \ No newline at end of file diff --git a/Modules/Survey/classes/class.ilSurveyEditorGUI.php b/Modules/Survey/classes/class.ilSurveyEditorGUI.php index 512a3aecf8321ac2c0a0e49e2e259caaff7ae737..8e2c8a3a9a293e793543f2cff7d67d16b27f7d82 100644 --- a/Modules/Survey/classes/class.ilSurveyEditorGUI.php +++ b/Modules/Survey/classes/class.ilSurveyEditorGUI.php @@ -1,1463 +1,1319 @@ - -* @version $Id: class.ilObjSurveyGUI.php 43670 2013-07-26 08:41:31Z jluetzen $ -* -* @ilCtrl_Calls ilSurveyEditorGUI: SurveyMultipleChoiceQuestionGUI, SurveyMetricQuestionGUI -* @ilCtrl_Calls ilSurveyEditorGUI: SurveySingleChoiceQuestionGUI, SurveyTextQuestionGUI -* @ilCtrl_Calls ilSurveyEditorGUI: SurveyMatrixQuestionGUI, ilSurveyPageGUI -* -* @ingroup ModulesSurvey -*/ -class ilSurveyEditorGUI -{ - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilHelpGUI - */ - protected $help; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilTree - */ - protected $tree; - - protected $parent_gui; // [ilObjSurveyGUI] - protected $object; // [ilObjSurvey] - - /** - * @var array - */ - protected $print_options; - - public function __construct(ilObjSurveyGUI $a_parent_gui) - { - global $DIC; - - $this->tabs = $DIC->tabs(); - $this->help = $DIC["ilHelp"]; - $this->toolbar = $DIC->toolbar(); - $this->user = $DIC->user(); - $this->tree = $DIC->repositoryTree(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $tpl = $DIC["tpl"]; - - $this->parent_gui = $a_parent_gui; - $this->object = $this->parent_gui->object; - - $this->ctrl = $ilCtrl; - $this->lng = $lng; - $this->tpl = $tpl; - - $this->ctrl->saveParameter($this, array("pgov", "pgov_pos")); - - $this->print_options = array ( - //0 => $this->lng->txt('none'), - ilObjSurvey::PRINT_HIDE_LABELS => $this->lng->txt('svy_print_hide_labels'), - //2 => $this->lng->txt('svy_print_label_only'), - ilObjSurvey::PRINT_SHOW_LABELS => $this->lng->txt('svy_print_show_labels') - ); - - } - - public function executeCommand() - { - $ilTabs = $this->tabs; - - $cmd = $this->ctrl->getCmd("questions"); - - if($_REQUEST["pgov"]) - { - if($cmd == "questions") - { - $this->ctrl->setCmdClass("ilsurveypagegui"); - $this->ctrl->setCmd("renderpage"); - } - else if($cmd == "confirmRemoveQuestions") - { - // #14324 - $this->ctrl->setCmdClass("ilsurveypagegui"); - $this->ctrl->setCmd("confirmRemoveQuestions"); - } - } - - $next_class = $this->ctrl->getNextClass($this); - switch($next_class) - { - case 'ilsurveypagegui': - $this->questionsSubtabs("page"); - include_once './Modules/Survey/classes/class.ilSurveyPageGUI.php'; - $pg = new ilSurveyPageGUI($this->object, $this); - $this->ctrl->forwardCommand($pg); - break; - - default: - // question gui - if(stristr($next_class, "questiongui")) - { - $ilTabs->clearTargets(); - $this->ctrl->saveParameter($this, array("new_for_survey")); - - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php"; - $q_gui = SurveyQuestionGUI::_getQuestionGUI(null, $_REQUEST["q_id"]); - if (is_object($q_gui->object)) - { - $ilHelp = $this->help; - $ilHelp->setScreenIdComponent("spl_qt".$q_gui->object->getQuestionTypeId()); - } - // $q_gui->object->setObjId($this->object->getId()); - $q_gui->setBackUrl($this->ctrl->getLinkTarget($this, "questions")); - $q_gui->setQuestionTabs(); - $this->ctrl->forwardCommand($q_gui); - - if(!(int)$_REQUEST["new_for_survey"]) - { - // not on create - $this->tpl->setTitle($this->lng->txt("question").": ".$q_gui->object->getTitle()); - } - } - else - { - $cmd .= "Object"; - $this->$cmd(); - } - break; - } - } - - protected function questionsSubtabs($a_cmd) - { - $ilTabs = $this->tabs; - - if($a_cmd == "questions" && $_REQUEST["pgov"]) - { - $a_cmd = "page"; - } - - $hidden_tabs = array(); - $template = $this->object->getTemplate(); - if($template) - { - include_once "Services/Administration/classes/class.ilSettingsTemplate.php"; - $template = new ilSettingsTemplate($template); - $hidden_tabs = $template->getHiddenTabs(); - } - - $ilTabs->addSubTab("page", - $this->lng->txt("survey_per_page_view"), - $this->ctrl->getLinkTargetByClass("ilsurveypagegui", "renderPage")); - - if(!in_array("survey_question_editor", $hidden_tabs)) - { - $this->ctrl->setParameter($this, "pgov", ""); - $ilTabs->addSubTab("questions", - $this->lng->txt("survey_question_editor"), - $this->ctrl->getLinkTarget($this, "questions")); - $this->ctrl->setParameter($this, "pgov", $_REQUEST["pgov"]); - } - - $ilTabs->addSubTab("print", - $this->lng->txt("print_view"), - $this->ctrl->getLinkTarget($this, "printView")); - - if($this->object->getSurveyPages()) - { - if($a_cmd == "page") - { - $this->ctrl->setParameterByClass("ilsurveyexecutiongui", "pgov", max(1, $_REQUEST["pg"])); - } - $this->ctrl->setParameterByClass("ilsurveyexecutiongui", "prvw", 1); - $ilTabs->addSubTab("preview", - $this->lng->txt("preview"), - $this->ctrl->getLinkTargetByClass(array("ilobjsurveygui", "ilsurveyexecutiongui"), "preview")); - } - - $ilTabs->activateSubTab($a_cmd); - } - - - // - // QUESTIONS BROWSER INCL. MULTI-ACTIONS - // - - public function questionsObject() - { - $ilToolbar = $this->toolbar; - $ilUser = $this->user; - - // insert new questions? - if ($_GET["new_id"] > 0) - { - // add a question to the survey previous created in a questionpool - $existing = $this->object->getExistingQuestions(); - if (!in_array($_GET["new_id"], $existing)) - { - $inserted = $this->object->insertQuestion($_GET["new_id"]); - if (!$inserted) - { - ilUtil::sendFailure($this->lng->txt("survey_error_insert_incomplete_question")); - } - } - } - - $this->questionsSubtabs("questions"); - - $hasDatasets = ilObjSurvey::_hasDatasets($this->object->getSurveyId()); - $read_only = $hasDatasets; - - // toolbar - if (!$read_only) - { - $qtypes = array(); - include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"; - foreach (ilObjSurveyQuestionPool::_getQuestiontypes() as $translation => $data) - { - $qtypes[$data["type_tag"]] = $translation; - } - - $ilToolbar->setFormAction($this->ctrl->getFormAction($this)); - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $types = new ilSelectInputGUI($this->lng->txt("create_new"), "sel_question_types"); - $types->setOptions($qtypes); - $ilToolbar->addStickyItem($types, ""); - - include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; - include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; - - $button = ilSubmitButton::getInstance(); - $button->setCaption("svy_create_question"); - $button->setCommand("createQuestion"); - $ilToolbar->addStickyItem($button); - - if($this->object->isPoolActive()) - { - $ilToolbar->addSeparator(); - - $cmd = ($ilUser->getPref('svy_insert_type') == 1 || - strlen($ilUser->getPref('svy_insert_type')) == 0) - ? 'browseForQuestions' - : 'browseForQuestionblocks'; - - $button = ilLinkButton::getInstance(); - $button->setCaption("browse_for_questions"); - $button->setUrl($this->ctrl->getLinkTarget($this, $cmd)); - $ilToolbar->addStickyItem($button); - } - - $ilToolbar->addSeparator(); - - $button = ilLinkButton::getInstance(); - $button->setCaption("add_heading"); - $button->setUrl($this->ctrl->getLinkTarget($this, "addHeading")); - $ilToolbar->addInputItem($button); - } - $mess = ""; - if ($hasDatasets) - { - $mbox = new ilSurveyContainsDataMessageBoxGUI(); - $mess = $mbox->getHTML(); - } - - // table gui - - include_once "Modules/Survey/classes/class.ilSurveyQuestionTableGUI.php"; - $table = new ilSurveyQuestionTableGUI($this, "questions", $this->object, - $read_only); - $this->tpl->setContent($mess.$table->getHTML()); - } - - /** - * Gather (and filter) selected items from table gui - * - * @param bool $allow_blocks - * @param bool $allow_questions - * @param bool $allow_headings - * @param bool $allow_questions_in_blocks - * @return array (questions, blocks, headings) - */ - protected function gatherSelectedTableItems($allow_blocks = true, $allow_questions = true, $allow_headings = false, $allow_questions_in_blocks = false) - { - $block_map = array(); - foreach($this->object->getSurveyQuestions() as $item) - { - $block_map[$item["question_id"]] = $item["questionblock_id"]; - } - - $questions = $blocks = $headings = array(); - if($_POST["id"]) - { - foreach ($_POST["id"] as $key) - { - // questions - if ($allow_questions && preg_match("/cb_(\d+)/", $key, $matches)) - { - if(($allow_questions_in_blocks || !$block_map[$matches[1]]) && - !in_array($block_map[$matches[1]], $blocks)) - { - array_push($questions, $matches[1]); - } - } - // blocks - if ($allow_blocks && preg_match("/cb_qb_(\d+)/", $key, $matches)) - { - array_push($blocks, $matches[1]); - } - // headings - if ($allow_headings && preg_match("/cb_tb_(\d+)/", $key, $matches)) - { - array_push($headings, $matches[1]); - } - } - } - - return array("questions" => $questions, - "blocks" => $blocks, - "headings" => $headings); - } - - public function saveObligatoryObject() - { - if(isset($_POST["order"])) - { - $position = -1; - $order = array(); - asort($_POST["order"]); - foreach(array_keys($_POST["order"]) as $id) - { - // block items - if(substr($id, 0, 3) == "qb_") - { - $block_id = substr($id, 3); - $block = $_POST["block_order"][$block_id]; - asort($block); - foreach(array_keys($block) as $question_id) - { - $position++; - $order[$question_id] = $position; - } - } - else - { - $question_id = substr($id, 2); - $position++; - $order[$question_id] = $position; - } - } - $this->object->updateOrder($order); - } - - $obligatory = array(); - foreach ($_POST as $key => $value) - { - if (preg_match("/obligatory_(\d+)/", $key, $matches)) - { - $obligatory[$matches[1]] = 1; - } - } - $this->object->setObligatoryStates($obligatory); - ilUtil::sendSuccess($this->lng->txt('msg_obj_modified'), true); - $this->ctrl->redirect($this, "questions"); - } - - public function unfoldQuestionblockObject() - { - $items = $this->gatherSelectedTableItems(true, false, false, false); - if (count($items["blocks"])) - { - ilUtil::sendSuccess($this->lng->txt('msg_obj_modified'), true); - $this->object->unfoldQuestionblocks($items["blocks"]); - } - else - { - ilUtil::sendInfo($this->lng->txt("qpl_unfold_select_none"), true); - } - $this->ctrl->redirect($this, "questions"); - } - - public function moveQuestionsObject() - { - $items = $this->gatherSelectedTableItems(true, true, false, false); - - $move_questions = $items["questions"]; - foreach ($items["blocks"] as $block_id) - { - foreach ($this->object->getQuestionblockQuestionIds($block_id) as $qid) - { - array_push($move_questions, $qid); - } - } - if (count($move_questions) == 0) - { - ilUtil::sendInfo($this->lng->txt("no_question_selected_for_move"), true); - $this->ctrl->redirect($this, "questions"); - } - else - { - $_SESSION["move_questions"] = $move_questions; - ilUtil::sendInfo($this->lng->txt("select_target_position_for_move_question")); - $this->questionsObject(); - } - } - - public function insertQuestionsBeforeObject() - { - $this->insertQuestions(0); - } - - public function insertQuestionsAfterObject() - { - $this->insertQuestions(1); - } - - protected function insertQuestions($insert_mode) - { - $insert_id = null; - if($_POST["id"]) - { - $items = $this->gatherSelectedTableItems(true, true, false, false); - - // we are using POST id for original order - while(!$insert_id && sizeof($_POST["id"])) - { - $target = array_shift($_POST["id"]); - if (preg_match("/^cb_(\d+)$/", $target, $matches)) - { - // questions in blocks are not allowed - if(in_array($matches[1], $items["questions"])) - { - $insert_id = $matches[1]; - } - } - if (!$insert_id && preg_match("/^cb_qb_(\d+)$/", $target, $matches)) - { - $ids = $this->object->getQuestionblockQuestionIds($matches[1]); - if (count($ids)) - { - if ($insert_mode == 0) - { - $insert_id = $ids[0]; - } - else if ($insert_mode == 1) - { - $insert_id = $ids[count($ids)-1]; - } - } - } - } - } - - if(!$insert_id) - { - ilUtil::sendInfo($this->lng->txt("no_target_selected_for_move"), true); - } - else - { - ilUtil::sendSuccess($this->lng->txt('msg_obj_modified'), true); - $this->object->moveQuestions($_SESSION["move_questions"], $insert_id, $insert_mode); - unset($_SESSION["move_questions"]); - } - - $this->ctrl->redirect($this, "questions"); - } - - public function removeQuestionsObject() - { - $items = $this->gatherSelectedTableItems(true, true, true, true); - if (count($items["blocks"]) + count($items["questions"]) + count($items["headings"]) > 0) - { - ilUtil::sendQuestion($this->lng->txt("remove_questions")); - $this->removeQuestionsForm($items["blocks"], $items["questions"], $items["headings"]); - return; - } - else - { - ilUtil::sendInfo($this->lng->txt("no_question_selected_for_removal"), true); - $this->ctrl->redirect($this, "questions"); - } - } - - public function removeQuestionsForm($checked_questionblocks, $checked_questions, $checked_headings) - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setHeaderText($this->lng->txt("survey_sure_delete_questions")); - - $cgui->setFormAction($this->ctrl->getFormAction($this, "confirmRemoveQuestions")); - $cgui->setCancel($this->lng->txt("cancel"), "questions"); - $cgui->setConfirm($this->lng->txt("confirm"), "confirmRemoveQuestions"); - - $counter = 0; - $surveyquestions =& $this->object->getSurveyQuestions(); - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - foreach ($surveyquestions as $question_id => $data) - { - if (in_array($data["question_id"], $checked_questions)) - { - $type = SurveyQuestion::_getQuestionTypeName($data["type_tag"]); - - $cgui->addItem("id_".$data["question_id"], $data["question_id"], - $type.": ".$data["title"]); - } - else if((in_array($data["questionblock_id"], $checked_questionblocks))) - { - $type = SurveyQuestion::_getQuestionTypeName($data["type_tag"]); - - $cgui->addItem("id_qb_".$data["questionblock_id"], $data["questionblock_id"], - $data["questionblock_title"]." - ".$type.": ".$data["title"]); - } - else if (in_array($data["question_id"], $checked_headings)) - { - $cgui->addItem("id_tb_".$data["question_id"], $data["question_id"], - $data["heading"]); - } - } - - $this->tpl->setContent($cgui->getHTML()); - } - - public function confirmRemoveQuestionsObject() - { - $checked_questions = array(); - $checked_questionblocks = array(); - $checked_headings = array(); - foreach ($_POST as $key => $value) - { - if (preg_match("/id_(\d+)/", $key, $matches)) - { - array_push($checked_questions, $matches[1]); - } - if (preg_match("/id_qb_(\d+)/", $key, $matches)) - { - array_push($checked_questionblocks, $matches[1]); - } - if (preg_match("/id_tb_(\d+)/", $key, $matches)) - { - array_push($checked_headings, $matches[1]); - } - } - - if(sizeof($checked_questions) || sizeof($checked_questionblocks)) - { - $this->object->removeQuestions($checked_questions, $checked_questionblocks); - } - if($checked_headings) - { - foreach($checked_headings as $q_id) - { - $this->object->saveHeading("", $q_id); - } - } - $this->object->saveCompletionStatus(); - ilUtil::sendSuccess($this->lng->txt("questions_removed"), true); - $this->ctrl->redirect($this, "questions"); - } - - public function copyQuestionsToPoolObject() - { - $items = $this->gatherSelectedTableItems(true, true, false, true); - - // gather questions from blocks - $copy_questions = $items["questions"]; - foreach ($items["blocks"] as $block_id) - { - foreach ($this->object->getQuestionblockQuestionIds($block_id) as $qid) - { - array_push($copy_questions, $qid); - } - } - $copy_questions = array_unique($copy_questions); - - // only if not already in pool - if (count($copy_questions)) - { - foreach($copy_questions as $idx => $question_id) - { - $question = ilObjSurvey::_instanciateQuestion($question_id); - if($question->getOriginalId()) - { - unset($copy_questions[$idx]); - } - } - - } - if (count($copy_questions) == 0) - { - ilUtil::sendInfo($this->lng->txt("no_question_selected_for_copy_to_pool"), true); - $this->ctrl->redirect($this, "questions"); - } - else - { - $this->questionsSubtabs("questions"); - - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $form = new ilPropertyFormGUI(); - - $form->setFormAction($this->ctrl->getFormAction($this, "executeCreateQuestion")); - - $ids = new ilHiddenInputGUI("question_ids"); - $ids->setValue(implode(";", $copy_questions)); - $form->addItem($ids); - - $questionpools =& $this->object->getAvailableQuestionpools(false, false, true, "write"); - $pools = new ilSelectInputGUI($this->lng->txt("survey_copy_select_questionpool"), "sel_spl"); - $pools->setOptions($questionpools); - $form->addItem($pools); - - $form->addCommandButton("executeCopyQuestionsToPool", $this->lng->txt("submit")); - $form->addCommandButton("questions", $this->lng->txt("cancel")); - - return $this->tpl->setContent($form->getHTML()); - } - } - - public function executeCopyQuestionsToPoolObject() - { - $question_ids = explode(";", $_POST["question_ids"]); - $pool_id = ilObject::_lookupObjId($_POST["sel_spl"]); - - foreach($question_ids as $qid) - { - // create copy (== pool "original") - $new_question = ilObjSurvey::_instanciateQuestion($qid); - $new_question->setId(); - $new_question->setObjId($pool_id); - $new_question->saveToDb(); - - // link "source" (survey) to copy (pool) - SurveyQuestion::_changeOriginalId($qid, $new_question->getId(), $pool_id); - } - - ilUtil::sendSuccess($this->lng->txt("survey_copy_to_questionpool_success"), true); - $this->ctrl->redirect($this, "questions"); - } - - - // - // QUESTION CREATION - // - - public function createQuestionObject(ilPropertyFormGUI $a_form = null) - { - if(!$this->object->isPoolActive()) - { - $_POST["usage"] = 1; - $_GET["sel_question_types"] = $_POST["sel_question_types"]; - return $this->executeCreateQuestionObject(); - } - - if(!$a_form) - { - $this->questionsSubtabs("questions"); - - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $form = new ilPropertyFormGUI(); - - $sel_question_types = (strlen($_POST["sel_question_types"])) ? $_POST["sel_question_types"] : $_GET["sel_question_types"]; - $this->ctrl->setParameter($this, "sel_question_types", $sel_question_types); - $form->setFormAction($this->ctrl->getFormAction($this, "executeCreateQuestion")); - } - else - { - $form = $a_form; - } - - $usage = new ilRadioGroupInputGUI($this->lng->txt("survey_pool_selection"), "usage"); - $usage->setRequired(true); - $no_pool = new ilRadioOption($this->lng->txt("survey_no_pool"), 1); - $usage->addOption($no_pool); - $existing_pool = new ilRadioOption($this->lng->txt("survey_existing_pool"), 3); - $usage->addOption($existing_pool); - $new_pool = new ilRadioOption($this->lng->txt("survey_new_pool"), 2); - $usage->addOption($new_pool); - $form->addItem($usage); - - if(isset($_SESSION["svy_qpool_choice"])) - { - $usage->setValue($_SESSION["svy_qpool_choice"]); - } - else - { - // default: no pool - $usage->setValue(1); - } - - $questionpools =& $this->object->getAvailableQuestionpools(FALSE, TRUE, TRUE, "write"); - $pools = new ilSelectInputGUI($this->lng->txt("select_questionpool"), "sel_spl"); - $pools->setOptions($questionpools); - $existing_pool->addSubItem($pools); - - $name = new ilTextInputGUI($this->lng->txt("spl_new"), "name_spl"); // #11740 - $name->setSize(50); - $name->setMaxLength(50); - $new_pool->addSubItem($name); - - if($a_form) - { - return $a_form; - } - - $form->addCommandButton("executeCreateQuestion", $this->lng->txt("submit")); - $form->addCommandButton("questions", $this->lng->txt("cancel")); - - return $this->tpl->setContent($form->getHTML()); - } - - function executeCreateQuestionObject() - { - $_SESSION["svy_qpool_choice"] = $_POST["usage"]; - - $q_type = $_GET["sel_question_types"]; - - // no pool - if ($_POST["usage"] == 1) - { - $obj_id = $this->object->getId(); - } - // existing pool - else if ($_POST["usage"] == 3 && strlen($_POST["sel_spl"])) - { - $obj_id = ilObject::_lookupObjId($_POST["sel_spl"]); - } - // new pool - elseif ($_POST["usage"] == 2 && strlen($_POST["name_spl"])) - { - $obj_id = $this->createQuestionPool($_POST["name_spl"]); - } - else - { - if(!$_POST["usage"]) - { - ilUtil::sendFailure($this->lng->txt("select_one"), true); - } - else - { - ilUtil::sendFailure($this->lng->txt("err_no_pool_name"), true); - } - $this->ctrl->setParameter($this, "sel_question_types", $q_type); - $this->ctrl->redirect($this, "createQuestion"); - } - - - // create question and redirect to question form - - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php"; - $q_gui = SurveyQuestionGUI::_getQuestionGUI($q_type); - $q_gui->object->setObjId($obj_id); // survey/pool! - $q_gui->object->createNewQuestion(); - $q_gui_class = get_class($q_gui); - - if($_REQUEST["pgov"]) - { - $this->ctrl->setParameterByClass($q_gui_class, "pgov", $_REQUEST["pgov"]); - $this->ctrl->setParameterByClass($q_gui_class, "pgov_pos",$_REQUEST["pgov_pos"]); - } - - $this->ctrl->setParameterByClass($q_gui_class, "ref_id", $this->object->getRefId()); - $this->ctrl->setParameterByClass($q_gui_class, "new_for_survey", $this->object->getRefId()); - $this->ctrl->setParameterByClass($q_gui_class, "q_id", $q_gui->object->getId()); - $this->ctrl->setParameterByClass($q_gui_class, "sel_question_types", $q_gui->getQuestionType()); - $this->ctrl->redirectByClass($q_gui_class, "editQuestion"); - } - - protected function createQuestionPool($name = "dummy") - { - $tree = $this->tree; - - $parent_ref = $tree->getParentId($this->object->getRefId()); - - include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"; - $qpl = new ilObjSurveyQuestionPool(); - $qpl->setType("spl"); - $qpl->setTitle($name); - $qpl->setDescription(""); - $qpl->create(); - $qpl->createReference(); - $qpl->putInTree($parent_ref); - $qpl->setPermissions($parent_ref); - $qpl->setOnline(1); // must be online to be available - $qpl->saveToDb(); - - return $qpl->getId(); - } - - - // - // ADD FROM POOL - // - - protected function setBrowseForQuestionsSubtabs() - { - $ilTabs = $this->tabs; - $ilToolbar = $this->toolbar; - $ilUser = $this->user; - - if(!isset($_REQUEST["pgov"])) - { - $link = $this->ctrl->getLinkTarget($this, "questions"); - } - else - { - $link = $this->ctrl->getLinkTargetByClass("ilsurveypagegui", "renderpage"); - } - $ilTabs->setBackTarget($this->lng->txt("menubacktosurvey"), $link); - - // type selector - include_once "Services/Form/classes/class.ilSelectInputGUI.php"; - $types = new ilSelectInputGUI($this->lng->txt("display_all_available"), "datatype"); - $types->setOptions(array( - 1 => $this->lng->txt("questions"), - 2 => $this->lng->txt("questionblocks") - )); - $types->setValue($ilUser->getPref('svy_insert_type')); - $ilToolbar->addInputItem($types, true); - $ilToolbar->addFormButton($this->lng->txt("change"), "changeDatatype"); - $ilToolbar->setFormAction( $this->ctrl->getFormAction($this, "changeDatatype")); - } - - public function changeDatatypeObject() - { - $ilUser = $this->user; - - $ilUser->writePref('svy_insert_type', $_POST['datatype']); - - switch ($_POST["datatype"]) - { - case 2: - $this->ctrl->redirect($this, 'browseForQuestionblocks'); - break; - - case 1: - default: - $this->ctrl->redirect($this, 'browseForQuestions'); - break; - } - } - - public function browseForQuestionsObject() - { - $this->setBrowseForQuestionsSubtabs(); - - include_once "./Modules/Survey/classes/tables/class.ilSurveyQuestionbrowserTableGUI.php"; - $table_gui = new ilSurveyQuestionbrowserTableGUI($this, 'browseForQuestions', $this->object, true); - $table_gui->setEditable(true); - $this->tpl->setContent($table_gui->getHTML()); - } - - public function filterQuestionBrowserObject() - { - include_once "./Modules/Survey/classes/tables/class.ilSurveyQuestionbrowserTableGUI.php"; - $table_gui = new ilSurveyQuestionbrowserTableGUI($this, 'browseForQuestions', $this->object); - $table_gui->writeFilterToSession(); - $this->ctrl->redirect($this, 'browseForQuestions'); - } - - public function resetfilterQuestionBrowserObject() - { - include_once "./Modules/Survey/classes/tables/class.ilSurveyQuestionbrowserTableGUI.php"; - $table_gui = new ilSurveyQuestionbrowserTableGUI($this, 'browseForQuestions', $this->object); - $table_gui->resetFilter(); - $this->ctrl->redirect($this, 'browseForQuestions'); - } - - public function insertQuestionsObject() - { - $inserted_objects = 0; - if (is_array($_POST['q_id'])) - { - if($_REQUEST["pgov"]) - { - include_once "Modules/Survey/classes/class.ilSurveyPageGUI.php"; - $page_gui = new ilSurveyPageGUI($this->object, $this); - $page_gui->determineCurrentPage(); - - // as target position is predefined, insert in reverse order - $_POST['q_id'] = array_reverse($_POST['q_id']); - } - foreach ($_POST['q_id'] as $question_id) - { - if(!$_REQUEST["pgov"]) - { - $this->object->insertQuestion($question_id); - } - else - { - // target position (pgov pos) is processed there - $page_gui->insertNewQuestion($question_id); - } - $inserted_objects++; - } - } - if ($inserted_objects) - { - $this->object->saveCompletionStatus(); - ilUtil::sendSuccess($this->lng->txt("questions_inserted"), true); - if(!$_REQUEST["pgov"]) - { - $this->ctrl->redirect($this, "questions"); - } - else - { - $target_page = $_REQUEST["pgov"]; - if(substr($_REQUEST["pgov_pos"], -1) == "c") - { - // see ilSurveyPageGUI::insertNewQuestion() - if((int)$_REQUEST["pgov_pos"]) - { - $target_page++; - } - else - { - $target_page = 1; - } - } - $this->ctrl->setParameterByClass("ilsurveypagegui", "pgov", $target_page); - $this->ctrl->redirectByClass("ilsurveypagegui", "renderpage"); - } - } - else - { - ilUtil::sendInfo($this->lng->txt("insert_missing_question"), true); - $this->ctrl->redirect($this, 'browseForQuestions'); - } - } - - public function browseForQuestionblocksObject() - { - $this->setBrowseForQuestionsSubtabs(); - - include_once "./Modules/Survey/classes/tables/class.ilSurveyQuestionblockbrowserTableGUI.php"; - $table_gui = new ilSurveyQuestionblockbrowserTableGUI($this, 'browseForQuestionblocks', $this->object, true); - $table_gui->setEditable(true); - $this->tpl->setContent($table_gui->getHTML()); - } - - public function filterQuestionblockBrowserObject() - { - include_once "./Modules/Survey/classes/tables/class.ilSurveyQuestionblockbrowserTableGUI.php"; - $table_gui = new ilSurveyQuestionblockbrowserTableGUI($this, 'browseForQuestionblocks', $this->object); - $table_gui->writeFilterToSession(); - $this->ctrl->redirect($this, 'browseForQuestionblocks'); - } - - public function resetfilterQuestionblockBrowserObject() - { - include_once "./Modules/Survey/classes/tables/class.ilSurveyQuestionblockbrowserTableGUI.php"; - $table_gui = new ilSurveyQuestionblockbrowserTableGUI($this, 'browseForQuestionblocks', $this->object); - $table_gui->resetFilter(); - $this->ctrl->redirect($this, 'browseForQuestionblocks'); - } - - public function insertQuestionblocksObject() - { - $inserted_objects = 0; - if (is_array($_POST['cb'])) - { - if($_REQUEST["pgov"]) - { - include_once "Modules/Survey/classes/class.ilSurveyPageGUI.php"; - $page_gui = new ilSurveyPageGUI($this->object, $this); - $page_gui->determineCurrentPage(); - - // as target position is predefined, insert in reverse order - $_POST['cb'] = array_reverse($_POST['cb']); - } - foreach ($_POST['cb'] as $questionblock_id) - { - if(!$_REQUEST["pgov"]) - { - $this->object->insertQuestionblock($questionblock_id); - } - else - { - $page_gui->insertQuestionblock($questionblock_id); - } - $inserted_objects++; - } - } - if ($inserted_objects) - { - $this->object->saveCompletionStatus(); - ilUtil::sendSuccess(($inserted_objects == 1) ? $this->lng->txt("questionblock_inserted") : $this->lng->txt("questionblocks_inserted"), true); - if(!$_REQUEST["pgov"]) - { - $this->ctrl->redirect($this, "questions"); - } - else - { - $target_page = $_REQUEST["pgov"]; - if(substr($_REQUEST["pgov_pos"], -1) == "c") - { - $target_page++; - } - $this->ctrl->setParameterByClass("ilsurveypagegui", "pgov", $target_page); - $this->ctrl->redirectByClass("ilsurveypagegui", "renderpage"); - } - } - else - { - ilUtil::sendInfo($this->lng->txt("insert_missing_questionblock"), true); - $this->ctrl->redirect($this, 'browseForQuestionblocks'); - } - } - - - // - // BLOCKS - // - - public function editQuestionblockObject(ilPropertyFormGUI $a_form = null) - { - $block_id = (int)$_REQUEST["bl_id"]; - $this->ctrl->setParameter($this, "bl_id", $block_id); - - if(!$a_form) - { - $a_form = $this->initQuestionblockForm($block_id); - } - - $this->questionsSubtabs("questions"); - $this->tpl->setContent($a_form->getHTML()); - } - - public function createQuestionblockObject(ilPropertyFormGUI $a_form = null) - { - if(!$a_form) - { - // gather questions from table selected - $items = $this->gatherSelectedTableItems(false, true, false, false); - - if(is_array($_POST["qids"]) && sizeof($_POST["qids"])) - { - $items["questions"] = $_POST["qids"]; - } - if (count($items["questions"]) < 2) - { - ilUtil::sendInfo($this->lng->txt("qpl_define_questionblock_select_missing"), true); - $this->ctrl->redirect($this, "questions"); - } - - $a_form = $this->initQuestionblockForm(null, $items["questions"]); - } - - $this->questionsSubtabs("questions"); - $this->tpl->setContent($a_form->getHTML()); - } - - protected function initQuestionblockForm($a_block_id = null, $a_question_ids = null) - { - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this, "saveDefineQuestionblock")); - $form->setTitle($this->lng->txt("define_questionblock")); - - $title = new ilTextInputGUI($this->lng->txt("title"), "title"); - $title->setRequired(true); - $form->addItem($title); - - $toggle_blocktitle = new ilCheckboxInputGUI($this->lng->txt("survey_show_blocktitle"), "show_blocktitle"); - $toggle_blocktitle->setInfo($this->lng->txt("survey_show_blocktitle_description")); - $form->addItem($toggle_blocktitle); - - $toggle_questiontitle = new ilCheckboxInputGUI($this->lng->txt("show_questiontext"), "show_questiontext"); - $toggle_questiontitle->setInfo($this->lng->txt("show_questiontext_description")); - $form->addItem($toggle_questiontitle); - - if($a_block_id) - { - $questionblock = ilObjSurvey::_getQuestionblock($a_block_id); - $title->setValue($questionblock["title"]); - $toggle_blocktitle->setChecked($questionblock["show_blocktitle"]); - $toggle_questiontitle->setChecked($questionblock["show_questiontext"]); - } - else - { - $toggle_blocktitle->setChecked(true); - $toggle_questiontitle->setChecked(true); - } - - $form->addCommandButton("saveDefineQuestionblock", $this->lng->txt("save")); - $form->addCommandButton("questions", $this->lng->txt("cancel")); - - // reload? - if(!$a_question_ids && $_POST["qids"]) - { - $a_question_ids = $_POST["qids"]; - } - - if ($a_question_ids) - { - foreach ($a_question_ids as $q_id) - { - $hidden = new ilHiddenInputGUI("qids[]"); - $hidden->setValue($q_id); - $form->addItem($hidden); - } - } - - return $form; - } - - public function saveDefineQuestionblockObject() - { - $block_id = (int)$_REQUEST["bl_id"]; - $q_ids = $_POST["qids"]; - - $this->ctrl->setParameter($this, "bl_id", $block_id); - - if(!$block_id && !is_array($q_ids)) - { - $this->ctrl->redirect($this, "questions"); - } - - $form = $this->initQuestionblockForm($block_id); - if($form->checkInput()) - { - $title = $form->getInput("title"); - $show_questiontext = $form->getInput("show_questiontext"); - $show_blocktitle = $form->getInput("show_blocktitle") ; - if ($block_id) - { - - $this->object->modifyQuestionblock($block_id, $title, - $show_questiontext, $show_blocktitle); - } - else if($q_ids) - { - $this->object->createQuestionblock($title, $show_questiontext, - $show_blocktitle, $q_ids); - } - - ilUtil::sendSuccess($this->lng->txt('msg_obj_modified'), true); - $this->ctrl->redirect($this, "questions"); - } - - $form->setValuesByPost(); - $this->editQuestionblockObject($form); - } - - - // - // HEADING - // - - protected function initHeadingForm($a_question_id = null) - { - $survey_questions = $this->object->getSurveyQuestions(); - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this, "")); - - // heading - $heading = new ilTextAreaInputGUI($this->lng->txt("heading"), "heading"); - $heading->setRows(10); - $heading->setCols(80); - $heading->setUseRte(TRUE); - include_once "./Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php"; - $heading->setRteTags(ilObjAdvancedEditing::_getUsedHTMLTags("survey")); - $heading->removePlugin(ilRTE::ILIAS_IMG_MANAGER_PLUGIN); - $heading->setRTESupport($this->object->getId(), "svy", "survey"); - $heading->setRequired(true); - $form->addItem($heading); - - $insertbefore = new ilSelectInputGUI($this->lng->txt("insert"), "insertbefore"); - $options = array(); - foreach ($survey_questions as $key => $value) - { - $options[$key] = $this->lng->txt("before") . ": \"" . $value["title"] . "\""; - } - $insertbefore->setOptions($options); - $insertbefore->setRequired(true); - $form->addItem($insertbefore); - - $form->addCommandButton("saveHeading", $this->lng->txt("save")); - $form->addCommandButton("questions", $this->lng->txt("cancel")); - - if ($a_question_id) - { - $form->setTitle($this->lng->txt("edit_heading")); - - $heading->setValue($this->object->prepareTextareaOutput($survey_questions[$a_question_id]["heading"])); - $insertbefore->setValue($a_question_id); - $insertbefore->setDisabled(true); - } - else - { - $form->setTitle($this->lng->txt("add_heading")); - } - - return $form; - } - - public function addHeadingObject(ilPropertyFormGUI $a_form = null) - { - $q_id = $_REQUEST["q_id"]; - $this->ctrl->setParameter($this, "q_id", $q_id); - - $this->questionsSubtabs("questions"); - - if(!$a_form) - { - $a_form = $this->initHeadingForm($q_id); - } - - $this->tpl->setContent($a_form->getHTML()); - } - - public function editHeadingObject(ilPropertyFormGUI $a_form = null) - { - $q_id = $_REQUEST["q_id"]; - $this->ctrl->setParameter($this, "q_id", $q_id); - - $this->questionsSubtabs("questions"); - - if(!$a_form) - { - $a_form = $this->initHeadingForm($q_id); - } - - $this->tpl->setContent($a_form->getHTML()); - } - - public function saveHeadingObject() - { - // #15474 - $q_id = (int)$_REQUEST["q_id"]; - $this->ctrl->setParameter($this, "q_id", $q_id); - - $form = $this->initHeadingForm($q_id); - if ($form->checkInput()) - { - include_once "./Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php"; - $this->object->saveHeading(ilUtil::stripSlashes($form->getInput("heading"), - true, ilObjAdvancedEditing::_getUsedHTMLTagsAsString("survey")), - $form->getInput("insertbefore")); - $this->ctrl->redirect($this, "questions"); - } - - $form->setValuesByPost(); - $this->addHeadingObject($form); - } - - public function removeHeadingObject() - { - $q_id = (int)$_REQUEST["q_id"]; - $this->ctrl->setParameter($this, "q_id", $q_id); - - if(!$q_id) - { - $this->ctrl->redirect($this, "questions"); - } - - $this->questionsSubtabs("questions"); - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setHeaderText($this->lng->txt("confirm_remove_heading")); - - $cgui->setFormAction($this->ctrl->getFormAction($this, "confirmedRemoveHeading")); - $cgui->setCancel($this->lng->txt("cancel"), "questions"); - $cgui->setConfirm($this->lng->txt("confirm"), "confirmedRemoveHeading"); - - $this->tpl->setContent($cgui->getHTML()); - } - - public function confirmedRemoveHeadingObject() - { - $q_id = (int)$_REQUEST["q_id"]; - if(!$q_id) - { - $this->ctrl->redirect($this, "questions"); - } - - $this->object->saveHeading("", $q_id); - $this->ctrl->redirect($this, "questions"); - } - - /** - * Creates a print view of the survey questions - * - * @access public - */ - function printViewObject() - { - $ilToolbar = $this->toolbar; - - $this->questionsSubtabs("print"); - - #21023 and #19448 - if(!$current_title = (int) $_REQUEST['export_label']) { - $current_title = $this->object->getShowQuestionTitles(); - } - /*if(!isset($_POST["export_label"])) - {fir - $_POST["export_label"] = $this->object->getShowQuestionTitles(); - } - $current_title = (int)$_REQUEST["export_label"]; - */ - - include_once "Services/Form/classes/class.ilSelectInputGUI.php"; - $label = new ilSelectInputGUI($this->lng->txt("title")."/".$this->lng->txt("label"), "export_label"); - - #19448 comment none and label only options. - $label->setOptions($this->print_options); - $label->setValue($current_title); - - $ilToolbar->addStickyItem($label, true); - - $ilToolbar->setFormAction($this->ctrl->getFormAction($this, "printView")); - - include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; - $button = ilSubmitButton::getInstance(); - $button->setCaption("show"); - $button->setCommand("printView"); - $ilToolbar->addStickyItem($button); - - $ilToolbar->addSeparator(); - - include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; - $button = ilLinkButton::getInstance(); - $button->setCaption("print"); - $button->setOnClick("window.print(); return false;"); - $button->setOmitPreventDoubleSubmission(true); - $ilToolbar->addButtonInstance($button); - - include_once './Services/WebServices/RPC/classes/class.ilRPCServerSettings.php'; - if(ilRPCServerSettings::getInstance()->isEnabled()) - { - $this->ctrl->setParameter($this, "export_label", $current_title); - $this->ctrl->setParameter($this, "pdf", "1"); - $pdf_url = $this->ctrl->getLinkTarget($this, "printView"); - $this->ctrl->setParameter($this, "pdf", ""); - $this->ctrl->setParameter($this, "export_label", ""); - - $button = ilLinkButton::getInstance(); - $button->setCaption("pdf_export"); - $button->setUrl($pdf_url); - $button->setOmitPreventDoubleSubmission(true); - $ilToolbar->addButtonInstance($button); - } - - // defer rendering of tex to fo processing - if (array_key_exists("pdf", $_GET) && ($_GET["pdf"] == 1)) - { - require_once('Services/MathJax/classes/class.ilMathJax.php'); - ilMathJax::getInstance()->init(ilMathJax::PURPOSE_DEFERRED_PDF); - } - - $template = new ilTemplate("tpl.il_svy_svy_printview.html", TRUE, TRUE, "Modules/Survey"); - - $pages =& $this->object->getSurveyPages(); - $required = false; - foreach ($pages as $page) - { - if (count($page) > 0) - { - foreach ($page as $question) - { - $questionGUI = $this->object->getQuestionGUI($question["type_tag"], $question["question_id"]); - if (is_object($questionGUI)) - { - if (strlen($question["heading"])) - { - $template->setCurrentBlock("textblock"); - $template->setVariable("TEXTBLOCK", $question["heading"]); - $template->parseCurrentBlock(); - } - $template->setCurrentBlock("question"); - $template->setVariable("QUESTION_DATA", $questionGUI->getPrintView($current_title, $question["questionblock_show_questiontext"], $this->object->getSurveyId())); - $template->parseCurrentBlock(); - - if($question["obligatory"]) - { - $required = true; - } - } - } - if (count($page) > 1 && $page[0]["questionblock_show_blocktitle"]) - { - $template->setCurrentBlock("page"); - $template->setVariable("BLOCKTITLE", $page[0]["questionblock_title"]); - $template->parseCurrentBlock(); - } - else - { - $template->setCurrentBlock("page"); - $template->parseCurrentBlock(); - } - } - } - - // #6412 - if($required) - { - $template->setVariable("TEXT_REQUIRED", $this->lng->txt("required_field")); - } - - // $this->tpl->addCss("./Modules/Survey/templates/default/survey_print.css", "print"); - if (array_key_exists("pdf", $_GET) && ($_GET["pdf"] == 1)) - { - $printbody = new ilTemplate("tpl.il_as_tst_print_body.html", TRUE, TRUE, "Modules/Test"); - $printbody->setVariable("TITLE", sprintf($this->lng->txt("tst_result_user_name"), $uname)); - $printbody->setVariable("ADM_CONTENT", $template->get()); - $printoutput = $printbody->get(); - $printoutput = preg_replace("/href=\".*?\"/", "", $printoutput); - $fo = $this->object->processPrintoutput2FO($printoutput); - - // render tex as fo graphics - require_once('Services/MathJax/classes/class.ilMathJax.php'); - $fo = ilMathJax::getInstance() - ->init(ilMathJax::PURPOSE_PDF) - ->setRendering(ilMathJax::RENDER_PNG_AS_FO_FILE) - ->insertLatexImages($fo); - - // #11436 - if(!$fo || !$this->object->deliverPDFfromFO($fo)) - { - ilUtil::sendFailure($this->lng->txt("msg_failed"), true); - $this->ctrl->redirect($this, "printView"); - } - } - else - { - $this->tpl->setVariable("ADM_CONTENT", $template->get()); - } - } - -} - -?> \ No newline at end of file + +* @version $Id: class.ilObjSurveyGUI.php 43670 2013-07-26 08:41:31Z jluetzen $ +* +* @ilCtrl_Calls ilSurveyEditorGUI: SurveyMultipleChoiceQuestionGUI, SurveyMetricQuestionGUI +* @ilCtrl_Calls ilSurveyEditorGUI: SurveySingleChoiceQuestionGUI, SurveyTextQuestionGUI +* @ilCtrl_Calls ilSurveyEditorGUI: SurveyMatrixQuestionGUI, ilSurveyPageGUI +* +* @ingroup ModulesSurvey +*/ +class ilSurveyEditorGUI +{ + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilTree + */ + protected $tree; + + protected $parent_gui; // [ilObjSurveyGUI] + protected $object; // [ilObjSurvey] + + /** + * @var array + */ + protected $print_options; + + public function __construct(ilObjSurveyGUI $a_parent_gui) + { + global $DIC; + + $this->tabs = $DIC->tabs(); + $this->help = $DIC["ilHelp"]; + $this->toolbar = $DIC->toolbar(); + $this->user = $DIC->user(); + $this->tree = $DIC->repositoryTree(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $tpl = $DIC["tpl"]; + + $this->parent_gui = $a_parent_gui; + $this->object = $this->parent_gui->object; + + $this->ctrl = $ilCtrl; + $this->lng = $lng; + $this->tpl = $tpl; + + $this->ctrl->saveParameter($this, array("pgov", "pgov_pos")); + + $this->print_options = array( + //0 => $this->lng->txt('none'), + ilObjSurvey::PRINT_HIDE_LABELS => $this->lng->txt('svy_print_hide_labels'), + //2 => $this->lng->txt('svy_print_label_only'), + ilObjSurvey::PRINT_SHOW_LABELS => $this->lng->txt('svy_print_show_labels') + ); + } + + public function executeCommand() + { + $ilTabs = $this->tabs; + + $cmd = $this->ctrl->getCmd("questions"); + + if ($_REQUEST["pgov"]) { + if ($cmd == "questions") { + $this->ctrl->setCmdClass("ilsurveypagegui"); + $this->ctrl->setCmd("renderpage"); + } elseif ($cmd == "confirmRemoveQuestions") { + // #14324 + $this->ctrl->setCmdClass("ilsurveypagegui"); + $this->ctrl->setCmd("confirmRemoveQuestions"); + } + } + + $next_class = $this->ctrl->getNextClass($this); + switch ($next_class) { + case 'ilsurveypagegui': + $this->questionsSubtabs("page"); + include_once './Modules/Survey/classes/class.ilSurveyPageGUI.php'; + $pg = new ilSurveyPageGUI($this->object, $this); + $this->ctrl->forwardCommand($pg); + break; + + default: + // question gui + if (stristr($next_class, "questiongui")) { + $ilTabs->clearTargets(); + $this->ctrl->saveParameter($this, array("new_for_survey")); + + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php"; + $q_gui = SurveyQuestionGUI::_getQuestionGUI(null, $_REQUEST["q_id"]); + if (is_object($q_gui->object)) { + $ilHelp = $this->help; + $ilHelp->setScreenIdComponent("spl_qt" . $q_gui->object->getQuestionTypeId()); + } + // $q_gui->object->setObjId($this->object->getId()); + $q_gui->setBackUrl($this->ctrl->getLinkTarget($this, "questions")); + $q_gui->setQuestionTabs(); + $this->ctrl->forwardCommand($q_gui); + + if (!(int) $_REQUEST["new_for_survey"]) { + // not on create + $this->tpl->setTitle($this->lng->txt("question") . ": " . $q_gui->object->getTitle()); + } + } else { + $cmd .= "Object"; + $this->$cmd(); + } + break; + } + } + + protected function questionsSubtabs($a_cmd) + { + $ilTabs = $this->tabs; + + if ($a_cmd == "questions" && $_REQUEST["pgov"]) { + $a_cmd = "page"; + } + + $hidden_tabs = array(); + $template = $this->object->getTemplate(); + if ($template) { + include_once "Services/Administration/classes/class.ilSettingsTemplate.php"; + $template = new ilSettingsTemplate($template); + $hidden_tabs = $template->getHiddenTabs(); + } + + $ilTabs->addSubTab( + "page", + $this->lng->txt("survey_per_page_view"), + $this->ctrl->getLinkTargetByClass("ilsurveypagegui", "renderPage") + ); + + if (!in_array("survey_question_editor", $hidden_tabs)) { + $this->ctrl->setParameter($this, "pgov", ""); + $ilTabs->addSubTab( + "questions", + $this->lng->txt("survey_question_editor"), + $this->ctrl->getLinkTarget($this, "questions") + ); + $this->ctrl->setParameter($this, "pgov", $_REQUEST["pgov"]); + } + + $ilTabs->addSubTab( + "print", + $this->lng->txt("print_view"), + $this->ctrl->getLinkTarget($this, "printView") + ); + + if ($this->object->getSurveyPages()) { + if ($a_cmd == "page") { + $this->ctrl->setParameterByClass("ilsurveyexecutiongui", "pgov", max(1, $_REQUEST["pg"])); + } + $this->ctrl->setParameterByClass("ilsurveyexecutiongui", "prvw", 1); + $ilTabs->addSubTab( + "preview", + $this->lng->txt("preview"), + $this->ctrl->getLinkTargetByClass(array("ilobjsurveygui", "ilsurveyexecutiongui"), "preview") + ); + } + + $ilTabs->activateSubTab($a_cmd); + } + + + // + // QUESTIONS BROWSER INCL. MULTI-ACTIONS + // + + public function questionsObject() + { + $ilToolbar = $this->toolbar; + $ilUser = $this->user; + + // insert new questions? + if ($_GET["new_id"] > 0) { + // add a question to the survey previous created in a questionpool + $existing = $this->object->getExistingQuestions(); + if (!in_array($_GET["new_id"], $existing)) { + $inserted = $this->object->insertQuestion($_GET["new_id"]); + if (!$inserted) { + ilUtil::sendFailure($this->lng->txt("survey_error_insert_incomplete_question")); + } + } + } + + $this->questionsSubtabs("questions"); + + $hasDatasets = ilObjSurvey::_hasDatasets($this->object->getSurveyId()); + $read_only = $hasDatasets; + + // toolbar + if (!$read_only) { + $qtypes = array(); + include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"; + foreach (ilObjSurveyQuestionPool::_getQuestiontypes() as $translation => $data) { + $qtypes[$data["type_tag"]] = $translation; + } + + $ilToolbar->setFormAction($this->ctrl->getFormAction($this)); + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $types = new ilSelectInputGUI($this->lng->txt("create_new"), "sel_question_types"); + $types->setOptions($qtypes); + $ilToolbar->addStickyItem($types, ""); + + include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; + include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; + + $button = ilSubmitButton::getInstance(); + $button->setCaption("svy_create_question"); + $button->setCommand("createQuestion"); + $ilToolbar->addStickyItem($button); + + if ($this->object->isPoolActive()) { + $ilToolbar->addSeparator(); + + $cmd = ($ilUser->getPref('svy_insert_type') == 1 || + strlen($ilUser->getPref('svy_insert_type')) == 0) + ? 'browseForQuestions' + : 'browseForQuestionblocks'; + + $button = ilLinkButton::getInstance(); + $button->setCaption("browse_for_questions"); + $button->setUrl($this->ctrl->getLinkTarget($this, $cmd)); + $ilToolbar->addStickyItem($button); + } + + $ilToolbar->addSeparator(); + + $button = ilLinkButton::getInstance(); + $button->setCaption("add_heading"); + $button->setUrl($this->ctrl->getLinkTarget($this, "addHeading")); + $ilToolbar->addInputItem($button); + } + $mess = ""; + if ($hasDatasets) { + $mbox = new ilSurveyContainsDataMessageBoxGUI(); + $mess = $mbox->getHTML(); + } + + // table gui + + include_once "Modules/Survey/classes/class.ilSurveyQuestionTableGUI.php"; + $table = new ilSurveyQuestionTableGUI( + $this, + "questions", + $this->object, + $read_only + ); + $this->tpl->setContent($mess . $table->getHTML()); + } + + /** + * Gather (and filter) selected items from table gui + * + * @param bool $allow_blocks + * @param bool $allow_questions + * @param bool $allow_headings + * @param bool $allow_questions_in_blocks + * @return array (questions, blocks, headings) + */ + protected function gatherSelectedTableItems($allow_blocks = true, $allow_questions = true, $allow_headings = false, $allow_questions_in_blocks = false) + { + $block_map = array(); + foreach ($this->object->getSurveyQuestions() as $item) { + $block_map[$item["question_id"]] = $item["questionblock_id"]; + } + + $questions = $blocks = $headings = array(); + if ($_POST["id"]) { + foreach ($_POST["id"] as $key) { + // questions + if ($allow_questions && preg_match("/cb_(\d+)/", $key, $matches)) { + if (($allow_questions_in_blocks || !$block_map[$matches[1]]) && + !in_array($block_map[$matches[1]], $blocks)) { + array_push($questions, $matches[1]); + } + } + // blocks + if ($allow_blocks && preg_match("/cb_qb_(\d+)/", $key, $matches)) { + array_push($blocks, $matches[1]); + } + // headings + if ($allow_headings && preg_match("/cb_tb_(\d+)/", $key, $matches)) { + array_push($headings, $matches[1]); + } + } + } + + return array("questions" => $questions, + "blocks" => $blocks, + "headings" => $headings); + } + + public function saveObligatoryObject() + { + if (isset($_POST["order"])) { + $position = -1; + $order = array(); + asort($_POST["order"]); + foreach (array_keys($_POST["order"]) as $id) { + // block items + if (substr($id, 0, 3) == "qb_") { + $block_id = substr($id, 3); + $block = $_POST["block_order"][$block_id]; + asort($block); + foreach (array_keys($block) as $question_id) { + $position++; + $order[$question_id] = $position; + } + } else { + $question_id = substr($id, 2); + $position++; + $order[$question_id] = $position; + } + } + $this->object->updateOrder($order); + } + + $obligatory = array(); + foreach ($_POST as $key => $value) { + if (preg_match("/obligatory_(\d+)/", $key, $matches)) { + $obligatory[$matches[1]] = 1; + } + } + $this->object->setObligatoryStates($obligatory); + ilUtil::sendSuccess($this->lng->txt('msg_obj_modified'), true); + $this->ctrl->redirect($this, "questions"); + } + + public function unfoldQuestionblockObject() + { + $items = $this->gatherSelectedTableItems(true, false, false, false); + if (count($items["blocks"])) { + ilUtil::sendSuccess($this->lng->txt('msg_obj_modified'), true); + $this->object->unfoldQuestionblocks($items["blocks"]); + } else { + ilUtil::sendInfo($this->lng->txt("qpl_unfold_select_none"), true); + } + $this->ctrl->redirect($this, "questions"); + } + + public function moveQuestionsObject() + { + $items = $this->gatherSelectedTableItems(true, true, false, false); + + $move_questions = $items["questions"]; + foreach ($items["blocks"] as $block_id) { + foreach ($this->object->getQuestionblockQuestionIds($block_id) as $qid) { + array_push($move_questions, $qid); + } + } + if (count($move_questions) == 0) { + ilUtil::sendInfo($this->lng->txt("no_question_selected_for_move"), true); + $this->ctrl->redirect($this, "questions"); + } else { + $_SESSION["move_questions"] = $move_questions; + ilUtil::sendInfo($this->lng->txt("select_target_position_for_move_question")); + $this->questionsObject(); + } + } + + public function insertQuestionsBeforeObject() + { + $this->insertQuestions(0); + } + + public function insertQuestionsAfterObject() + { + $this->insertQuestions(1); + } + + protected function insertQuestions($insert_mode) + { + $insert_id = null; + if ($_POST["id"]) { + $items = $this->gatherSelectedTableItems(true, true, false, false); + + // we are using POST id for original order + while (!$insert_id && sizeof($_POST["id"])) { + $target = array_shift($_POST["id"]); + if (preg_match("/^cb_(\d+)$/", $target, $matches)) { + // questions in blocks are not allowed + if (in_array($matches[1], $items["questions"])) { + $insert_id = $matches[1]; + } + } + if (!$insert_id && preg_match("/^cb_qb_(\d+)$/", $target, $matches)) { + $ids = $this->object->getQuestionblockQuestionIds($matches[1]); + if (count($ids)) { + if ($insert_mode == 0) { + $insert_id = $ids[0]; + } elseif ($insert_mode == 1) { + $insert_id = $ids[count($ids)-1]; + } + } + } + } + } + + if (!$insert_id) { + ilUtil::sendInfo($this->lng->txt("no_target_selected_for_move"), true); + } else { + ilUtil::sendSuccess($this->lng->txt('msg_obj_modified'), true); + $this->object->moveQuestions($_SESSION["move_questions"], $insert_id, $insert_mode); + unset($_SESSION["move_questions"]); + } + + $this->ctrl->redirect($this, "questions"); + } + + public function removeQuestionsObject() + { + $items = $this->gatherSelectedTableItems(true, true, true, true); + if (count($items["blocks"]) + count($items["questions"]) + count($items["headings"]) > 0) { + ilUtil::sendQuestion($this->lng->txt("remove_questions")); + $this->removeQuestionsForm($items["blocks"], $items["questions"], $items["headings"]); + return; + } else { + ilUtil::sendInfo($this->lng->txt("no_question_selected_for_removal"), true); + $this->ctrl->redirect($this, "questions"); + } + } + + public function removeQuestionsForm($checked_questionblocks, $checked_questions, $checked_headings) + { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setHeaderText($this->lng->txt("survey_sure_delete_questions")); + + $cgui->setFormAction($this->ctrl->getFormAction($this, "confirmRemoveQuestions")); + $cgui->setCancel($this->lng->txt("cancel"), "questions"); + $cgui->setConfirm($this->lng->txt("confirm"), "confirmRemoveQuestions"); + + $counter = 0; + $surveyquestions =&$this->object->getSurveyQuestions(); + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + foreach ($surveyquestions as $question_id => $data) { + if (in_array($data["question_id"], $checked_questions)) { + $type = SurveyQuestion::_getQuestionTypeName($data["type_tag"]); + + $cgui->addItem( + "id_" . $data["question_id"], + $data["question_id"], + $type . ": " . $data["title"] + ); + } elseif ((in_array($data["questionblock_id"], $checked_questionblocks))) { + $type = SurveyQuestion::_getQuestionTypeName($data["type_tag"]); + + $cgui->addItem( + "id_qb_" . $data["questionblock_id"], + $data["questionblock_id"], + $data["questionblock_title"] . " - " . $type . ": " . $data["title"] + ); + } elseif (in_array($data["question_id"], $checked_headings)) { + $cgui->addItem( + "id_tb_" . $data["question_id"], + $data["question_id"], + $data["heading"] + ); + } + } + + $this->tpl->setContent($cgui->getHTML()); + } + + public function confirmRemoveQuestionsObject() + { + $checked_questions = array(); + $checked_questionblocks = array(); + $checked_headings = array(); + foreach ($_POST as $key => $value) { + if (preg_match("/id_(\d+)/", $key, $matches)) { + array_push($checked_questions, $matches[1]); + } + if (preg_match("/id_qb_(\d+)/", $key, $matches)) { + array_push($checked_questionblocks, $matches[1]); + } + if (preg_match("/id_tb_(\d+)/", $key, $matches)) { + array_push($checked_headings, $matches[1]); + } + } + + if (sizeof($checked_questions) || sizeof($checked_questionblocks)) { + $this->object->removeQuestions($checked_questions, $checked_questionblocks); + } + if ($checked_headings) { + foreach ($checked_headings as $q_id) { + $this->object->saveHeading("", $q_id); + } + } + $this->object->saveCompletionStatus(); + ilUtil::sendSuccess($this->lng->txt("questions_removed"), true); + $this->ctrl->redirect($this, "questions"); + } + + public function copyQuestionsToPoolObject() + { + $items = $this->gatherSelectedTableItems(true, true, false, true); + + // gather questions from blocks + $copy_questions = $items["questions"]; + foreach ($items["blocks"] as $block_id) { + foreach ($this->object->getQuestionblockQuestionIds($block_id) as $qid) { + array_push($copy_questions, $qid); + } + } + $copy_questions = array_unique($copy_questions); + + // only if not already in pool + if (count($copy_questions)) { + foreach ($copy_questions as $idx => $question_id) { + $question = ilObjSurvey::_instanciateQuestion($question_id); + if ($question->getOriginalId()) { + unset($copy_questions[$idx]); + } + } + } + if (count($copy_questions) == 0) { + ilUtil::sendInfo($this->lng->txt("no_question_selected_for_copy_to_pool"), true); + $this->ctrl->redirect($this, "questions"); + } else { + $this->questionsSubtabs("questions"); + + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $form = new ilPropertyFormGUI(); + + $form->setFormAction($this->ctrl->getFormAction($this, "executeCreateQuestion")); + + $ids = new ilHiddenInputGUI("question_ids"); + $ids->setValue(implode(";", $copy_questions)); + $form->addItem($ids); + + $questionpools =&$this->object->getAvailableQuestionpools(false, false, true, "write"); + $pools = new ilSelectInputGUI($this->lng->txt("survey_copy_select_questionpool"), "sel_spl"); + $pools->setOptions($questionpools); + $form->addItem($pools); + + $form->addCommandButton("executeCopyQuestionsToPool", $this->lng->txt("submit")); + $form->addCommandButton("questions", $this->lng->txt("cancel")); + + return $this->tpl->setContent($form->getHTML()); + } + } + + public function executeCopyQuestionsToPoolObject() + { + $question_ids = explode(";", $_POST["question_ids"]); + $pool_id = ilObject::_lookupObjId($_POST["sel_spl"]); + + foreach ($question_ids as $qid) { + // create copy (== pool "original") + $new_question = ilObjSurvey::_instanciateQuestion($qid); + $new_question->setId(); + $new_question->setObjId($pool_id); + $new_question->saveToDb(); + + // link "source" (survey) to copy (pool) + SurveyQuestion::_changeOriginalId($qid, $new_question->getId(), $pool_id); + } + + ilUtil::sendSuccess($this->lng->txt("survey_copy_to_questionpool_success"), true); + $this->ctrl->redirect($this, "questions"); + } + + + // + // QUESTION CREATION + // + + public function createQuestionObject(ilPropertyFormGUI $a_form = null) + { + if (!$this->object->isPoolActive()) { + $_POST["usage"] = 1; + $_GET["sel_question_types"] = $_POST["sel_question_types"]; + return $this->executeCreateQuestionObject(); + } + + if (!$a_form) { + $this->questionsSubtabs("questions"); + + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $form = new ilPropertyFormGUI(); + + $sel_question_types = (strlen($_POST["sel_question_types"])) ? $_POST["sel_question_types"] : $_GET["sel_question_types"]; + $this->ctrl->setParameter($this, "sel_question_types", $sel_question_types); + $form->setFormAction($this->ctrl->getFormAction($this, "executeCreateQuestion")); + } else { + $form = $a_form; + } + + $usage = new ilRadioGroupInputGUI($this->lng->txt("survey_pool_selection"), "usage"); + $usage->setRequired(true); + $no_pool = new ilRadioOption($this->lng->txt("survey_no_pool"), 1); + $usage->addOption($no_pool); + $existing_pool = new ilRadioOption($this->lng->txt("survey_existing_pool"), 3); + $usage->addOption($existing_pool); + $new_pool = new ilRadioOption($this->lng->txt("survey_new_pool"), 2); + $usage->addOption($new_pool); + $form->addItem($usage); + + if (isset($_SESSION["svy_qpool_choice"])) { + $usage->setValue($_SESSION["svy_qpool_choice"]); + } else { + // default: no pool + $usage->setValue(1); + } + + $questionpools =&$this->object->getAvailableQuestionpools(false, true, true, "write"); + $pools = new ilSelectInputGUI($this->lng->txt("select_questionpool"), "sel_spl"); + $pools->setOptions($questionpools); + $existing_pool->addSubItem($pools); + + $name = new ilTextInputGUI($this->lng->txt("spl_new"), "name_spl"); // #11740 + $name->setSize(50); + $name->setMaxLength(50); + $new_pool->addSubItem($name); + + if ($a_form) { + return $a_form; + } + + $form->addCommandButton("executeCreateQuestion", $this->lng->txt("submit")); + $form->addCommandButton("questions", $this->lng->txt("cancel")); + + return $this->tpl->setContent($form->getHTML()); + } + + public function executeCreateQuestionObject() + { + $_SESSION["svy_qpool_choice"] = $_POST["usage"]; + + $q_type = $_GET["sel_question_types"]; + + // no pool + if ($_POST["usage"] == 1) { + $obj_id = $this->object->getId(); + } + // existing pool + elseif ($_POST["usage"] == 3 && strlen($_POST["sel_spl"])) { + $obj_id = ilObject::_lookupObjId($_POST["sel_spl"]); + } + // new pool + elseif ($_POST["usage"] == 2 && strlen($_POST["name_spl"])) { + $obj_id = $this->createQuestionPool($_POST["name_spl"]); + } else { + if (!$_POST["usage"]) { + ilUtil::sendFailure($this->lng->txt("select_one"), true); + } else { + ilUtil::sendFailure($this->lng->txt("err_no_pool_name"), true); + } + $this->ctrl->setParameter($this, "sel_question_types", $q_type); + $this->ctrl->redirect($this, "createQuestion"); + } + + + // create question and redirect to question form + + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php"; + $q_gui = SurveyQuestionGUI::_getQuestionGUI($q_type); + $q_gui->object->setObjId($obj_id); // survey/pool! + $q_gui->object->createNewQuestion(); + $q_gui_class = get_class($q_gui); + + if ($_REQUEST["pgov"]) { + $this->ctrl->setParameterByClass($q_gui_class, "pgov", $_REQUEST["pgov"]); + $this->ctrl->setParameterByClass($q_gui_class, "pgov_pos", $_REQUEST["pgov_pos"]); + } + + $this->ctrl->setParameterByClass($q_gui_class, "ref_id", $this->object->getRefId()); + $this->ctrl->setParameterByClass($q_gui_class, "new_for_survey", $this->object->getRefId()); + $this->ctrl->setParameterByClass($q_gui_class, "q_id", $q_gui->object->getId()); + $this->ctrl->setParameterByClass($q_gui_class, "sel_question_types", $q_gui->getQuestionType()); + $this->ctrl->redirectByClass($q_gui_class, "editQuestion"); + } + + protected function createQuestionPool($name = "dummy") + { + $tree = $this->tree; + + $parent_ref = $tree->getParentId($this->object->getRefId()); + + include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"; + $qpl = new ilObjSurveyQuestionPool(); + $qpl->setType("spl"); + $qpl->setTitle($name); + $qpl->setDescription(""); + $qpl->create(); + $qpl->createReference(); + $qpl->putInTree($parent_ref); + $qpl->setPermissions($parent_ref); + $qpl->setOnline(1); // must be online to be available + $qpl->saveToDb(); + + return $qpl->getId(); + } + + + // + // ADD FROM POOL + // + + protected function setBrowseForQuestionsSubtabs() + { + $ilTabs = $this->tabs; + $ilToolbar = $this->toolbar; + $ilUser = $this->user; + + if (!isset($_REQUEST["pgov"])) { + $link = $this->ctrl->getLinkTarget($this, "questions"); + } else { + $link = $this->ctrl->getLinkTargetByClass("ilsurveypagegui", "renderpage"); + } + $ilTabs->setBackTarget($this->lng->txt("menubacktosurvey"), $link); + + // type selector + include_once "Services/Form/classes/class.ilSelectInputGUI.php"; + $types = new ilSelectInputGUI($this->lng->txt("display_all_available"), "datatype"); + $types->setOptions(array( + 1 => $this->lng->txt("questions"), + 2 => $this->lng->txt("questionblocks") + )); + $types->setValue($ilUser->getPref('svy_insert_type')); + $ilToolbar->addInputItem($types, true); + $ilToolbar->addFormButton($this->lng->txt("change"), "changeDatatype"); + $ilToolbar->setFormAction($this->ctrl->getFormAction($this, "changeDatatype")); + } + + public function changeDatatypeObject() + { + $ilUser = $this->user; + + $ilUser->writePref('svy_insert_type', $_POST['datatype']); + + switch ($_POST["datatype"]) { + case 2: + $this->ctrl->redirect($this, 'browseForQuestionblocks'); + break; + + case 1: + default: + $this->ctrl->redirect($this, 'browseForQuestions'); + break; + } + } + + public function browseForQuestionsObject() + { + $this->setBrowseForQuestionsSubtabs(); + + include_once "./Modules/Survey/classes/tables/class.ilSurveyQuestionbrowserTableGUI.php"; + $table_gui = new ilSurveyQuestionbrowserTableGUI($this, 'browseForQuestions', $this->object, true); + $table_gui->setEditable(true); + $this->tpl->setContent($table_gui->getHTML()); + } + + public function filterQuestionBrowserObject() + { + include_once "./Modules/Survey/classes/tables/class.ilSurveyQuestionbrowserTableGUI.php"; + $table_gui = new ilSurveyQuestionbrowserTableGUI($this, 'browseForQuestions', $this->object); + $table_gui->writeFilterToSession(); + $this->ctrl->redirect($this, 'browseForQuestions'); + } + + public function resetfilterQuestionBrowserObject() + { + include_once "./Modules/Survey/classes/tables/class.ilSurveyQuestionbrowserTableGUI.php"; + $table_gui = new ilSurveyQuestionbrowserTableGUI($this, 'browseForQuestions', $this->object); + $table_gui->resetFilter(); + $this->ctrl->redirect($this, 'browseForQuestions'); + } + + public function insertQuestionsObject() + { + $inserted_objects = 0; + if (is_array($_POST['q_id'])) { + if ($_REQUEST["pgov"]) { + include_once "Modules/Survey/classes/class.ilSurveyPageGUI.php"; + $page_gui = new ilSurveyPageGUI($this->object, $this); + $page_gui->determineCurrentPage(); + + // as target position is predefined, insert in reverse order + $_POST['q_id'] = array_reverse($_POST['q_id']); + } + foreach ($_POST['q_id'] as $question_id) { + if (!$_REQUEST["pgov"]) { + $this->object->insertQuestion($question_id); + } else { + // target position (pgov pos) is processed there + $page_gui->insertNewQuestion($question_id); + } + $inserted_objects++; + } + } + if ($inserted_objects) { + $this->object->saveCompletionStatus(); + ilUtil::sendSuccess($this->lng->txt("questions_inserted"), true); + if (!$_REQUEST["pgov"]) { + $this->ctrl->redirect($this, "questions"); + } else { + $target_page = $_REQUEST["pgov"]; + if (substr($_REQUEST["pgov_pos"], -1) == "c") { + // see ilSurveyPageGUI::insertNewQuestion() + if ((int) $_REQUEST["pgov_pos"]) { + $target_page++; + } else { + $target_page = 1; + } + } + $this->ctrl->setParameterByClass("ilsurveypagegui", "pgov", $target_page); + $this->ctrl->redirectByClass("ilsurveypagegui", "renderpage"); + } + } else { + ilUtil::sendInfo($this->lng->txt("insert_missing_question"), true); + $this->ctrl->redirect($this, 'browseForQuestions'); + } + } + + public function browseForQuestionblocksObject() + { + $this->setBrowseForQuestionsSubtabs(); + + include_once "./Modules/Survey/classes/tables/class.ilSurveyQuestionblockbrowserTableGUI.php"; + $table_gui = new ilSurveyQuestionblockbrowserTableGUI($this, 'browseForQuestionblocks', $this->object, true); + $table_gui->setEditable(true); + $this->tpl->setContent($table_gui->getHTML()); + } + + public function filterQuestionblockBrowserObject() + { + include_once "./Modules/Survey/classes/tables/class.ilSurveyQuestionblockbrowserTableGUI.php"; + $table_gui = new ilSurveyQuestionblockbrowserTableGUI($this, 'browseForQuestionblocks', $this->object); + $table_gui->writeFilterToSession(); + $this->ctrl->redirect($this, 'browseForQuestionblocks'); + } + + public function resetfilterQuestionblockBrowserObject() + { + include_once "./Modules/Survey/classes/tables/class.ilSurveyQuestionblockbrowserTableGUI.php"; + $table_gui = new ilSurveyQuestionblockbrowserTableGUI($this, 'browseForQuestionblocks', $this->object); + $table_gui->resetFilter(); + $this->ctrl->redirect($this, 'browseForQuestionblocks'); + } + + public function insertQuestionblocksObject() + { + $inserted_objects = 0; + if (is_array($_POST['cb'])) { + if ($_REQUEST["pgov"]) { + include_once "Modules/Survey/classes/class.ilSurveyPageGUI.php"; + $page_gui = new ilSurveyPageGUI($this->object, $this); + $page_gui->determineCurrentPage(); + + // as target position is predefined, insert in reverse order + $_POST['cb'] = array_reverse($_POST['cb']); + } + foreach ($_POST['cb'] as $questionblock_id) { + if (!$_REQUEST["pgov"]) { + $this->object->insertQuestionblock($questionblock_id); + } else { + $page_gui->insertQuestionblock($questionblock_id); + } + $inserted_objects++; + } + } + if ($inserted_objects) { + $this->object->saveCompletionStatus(); + ilUtil::sendSuccess(($inserted_objects == 1) ? $this->lng->txt("questionblock_inserted") : $this->lng->txt("questionblocks_inserted"), true); + if (!$_REQUEST["pgov"]) { + $this->ctrl->redirect($this, "questions"); + } else { + $target_page = $_REQUEST["pgov"]; + if (substr($_REQUEST["pgov_pos"], -1) == "c") { + $target_page++; + } + $this->ctrl->setParameterByClass("ilsurveypagegui", "pgov", $target_page); + $this->ctrl->redirectByClass("ilsurveypagegui", "renderpage"); + } + } else { + ilUtil::sendInfo($this->lng->txt("insert_missing_questionblock"), true); + $this->ctrl->redirect($this, 'browseForQuestionblocks'); + } + } + + + // + // BLOCKS + // + + public function editQuestionblockObject(ilPropertyFormGUI $a_form = null) + { + $block_id = (int) $_REQUEST["bl_id"]; + $this->ctrl->setParameter($this, "bl_id", $block_id); + + if (!$a_form) { + $a_form = $this->initQuestionblockForm($block_id); + } + + $this->questionsSubtabs("questions"); + $this->tpl->setContent($a_form->getHTML()); + } + + public function createQuestionblockObject(ilPropertyFormGUI $a_form = null) + { + if (!$a_form) { + // gather questions from table selected + $items = $this->gatherSelectedTableItems(false, true, false, false); + + if (is_array($_POST["qids"]) && sizeof($_POST["qids"])) { + $items["questions"] = $_POST["qids"]; + } + if (count($items["questions"]) < 2) { + ilUtil::sendInfo($this->lng->txt("qpl_define_questionblock_select_missing"), true); + $this->ctrl->redirect($this, "questions"); + } + + $a_form = $this->initQuestionblockForm(null, $items["questions"]); + } + + $this->questionsSubtabs("questions"); + $this->tpl->setContent($a_form->getHTML()); + } + + protected function initQuestionblockForm($a_block_id = null, $a_question_ids = null) + { + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this, "saveDefineQuestionblock")); + $form->setTitle($this->lng->txt("define_questionblock")); + + $title = new ilTextInputGUI($this->lng->txt("title"), "title"); + $title->setRequired(true); + $form->addItem($title); + + $toggle_blocktitle = new ilCheckboxInputGUI($this->lng->txt("survey_show_blocktitle"), "show_blocktitle"); + $toggle_blocktitle->setInfo($this->lng->txt("survey_show_blocktitle_description")); + $form->addItem($toggle_blocktitle); + + $toggle_questiontitle = new ilCheckboxInputGUI($this->lng->txt("show_questiontext"), "show_questiontext"); + $toggle_questiontitle->setInfo($this->lng->txt("show_questiontext_description")); + $form->addItem($toggle_questiontitle); + + if ($a_block_id) { + $questionblock = ilObjSurvey::_getQuestionblock($a_block_id); + $title->setValue($questionblock["title"]); + $toggle_blocktitle->setChecked($questionblock["show_blocktitle"]); + $toggle_questiontitle->setChecked($questionblock["show_questiontext"]); + } else { + $toggle_blocktitle->setChecked(true); + $toggle_questiontitle->setChecked(true); + } + + $form->addCommandButton("saveDefineQuestionblock", $this->lng->txt("save")); + $form->addCommandButton("questions", $this->lng->txt("cancel")); + + // reload? + if (!$a_question_ids && $_POST["qids"]) { + $a_question_ids = $_POST["qids"]; + } + + if ($a_question_ids) { + foreach ($a_question_ids as $q_id) { + $hidden = new ilHiddenInputGUI("qids[]"); + $hidden->setValue($q_id); + $form->addItem($hidden); + } + } + + return $form; + } + + public function saveDefineQuestionblockObject() + { + $block_id = (int) $_REQUEST["bl_id"]; + $q_ids = $_POST["qids"]; + + $this->ctrl->setParameter($this, "bl_id", $block_id); + + if (!$block_id && !is_array($q_ids)) { + $this->ctrl->redirect($this, "questions"); + } + + $form = $this->initQuestionblockForm($block_id); + if ($form->checkInput()) { + $title = $form->getInput("title"); + $show_questiontext = $form->getInput("show_questiontext"); + $show_blocktitle = $form->getInput("show_blocktitle") ; + if ($block_id) { + $this->object->modifyQuestionblock( + $block_id, + $title, + $show_questiontext, + $show_blocktitle + ); + } elseif ($q_ids) { + $this->object->createQuestionblock( + $title, + $show_questiontext, + $show_blocktitle, + $q_ids + ); + } + + ilUtil::sendSuccess($this->lng->txt('msg_obj_modified'), true); + $this->ctrl->redirect($this, "questions"); + } + + $form->setValuesByPost(); + $this->editQuestionblockObject($form); + } + + + // + // HEADING + // + + protected function initHeadingForm($a_question_id = null) + { + $survey_questions = $this->object->getSurveyQuestions(); + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this, "")); + + // heading + $heading = new ilTextAreaInputGUI($this->lng->txt("heading"), "heading"); + $heading->setRows(10); + $heading->setCols(80); + $heading->setUseRte(true); + include_once "./Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php"; + $heading->setRteTags(ilObjAdvancedEditing::_getUsedHTMLTags("survey")); + $heading->removePlugin(ilRTE::ILIAS_IMG_MANAGER_PLUGIN); + $heading->setRTESupport($this->object->getId(), "svy", "survey"); + $heading->setRequired(true); + $form->addItem($heading); + + $insertbefore = new ilSelectInputGUI($this->lng->txt("insert"), "insertbefore"); + $options = array(); + foreach ($survey_questions as $key => $value) { + $options[$key] = $this->lng->txt("before") . ": \"" . $value["title"] . "\""; + } + $insertbefore->setOptions($options); + $insertbefore->setRequired(true); + $form->addItem($insertbefore); + + $form->addCommandButton("saveHeading", $this->lng->txt("save")); + $form->addCommandButton("questions", $this->lng->txt("cancel")); + + if ($a_question_id) { + $form->setTitle($this->lng->txt("edit_heading")); + + $heading->setValue($this->object->prepareTextareaOutput($survey_questions[$a_question_id]["heading"])); + $insertbefore->setValue($a_question_id); + $insertbefore->setDisabled(true); + } else { + $form->setTitle($this->lng->txt("add_heading")); + } + + return $form; + } + + public function addHeadingObject(ilPropertyFormGUI $a_form = null) + { + $q_id = $_REQUEST["q_id"]; + $this->ctrl->setParameter($this, "q_id", $q_id); + + $this->questionsSubtabs("questions"); + + if (!$a_form) { + $a_form = $this->initHeadingForm($q_id); + } + + $this->tpl->setContent($a_form->getHTML()); + } + + public function editHeadingObject(ilPropertyFormGUI $a_form = null) + { + $q_id = $_REQUEST["q_id"]; + $this->ctrl->setParameter($this, "q_id", $q_id); + + $this->questionsSubtabs("questions"); + + if (!$a_form) { + $a_form = $this->initHeadingForm($q_id); + } + + $this->tpl->setContent($a_form->getHTML()); + } + + public function saveHeadingObject() + { + // #15474 + $q_id = (int) $_REQUEST["q_id"]; + $this->ctrl->setParameter($this, "q_id", $q_id); + + $form = $this->initHeadingForm($q_id); + if ($form->checkInput()) { + include_once "./Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php"; + $this->object->saveHeading( + ilUtil::stripSlashes( + $form->getInput("heading"), + true, + ilObjAdvancedEditing::_getUsedHTMLTagsAsString("survey") + ), + $form->getInput("insertbefore") + ); + $this->ctrl->redirect($this, "questions"); + } + + $form->setValuesByPost(); + $this->addHeadingObject($form); + } + + public function removeHeadingObject() + { + $q_id = (int) $_REQUEST["q_id"]; + $this->ctrl->setParameter($this, "q_id", $q_id); + + if (!$q_id) { + $this->ctrl->redirect($this, "questions"); + } + + $this->questionsSubtabs("questions"); + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setHeaderText($this->lng->txt("confirm_remove_heading")); + + $cgui->setFormAction($this->ctrl->getFormAction($this, "confirmedRemoveHeading")); + $cgui->setCancel($this->lng->txt("cancel"), "questions"); + $cgui->setConfirm($this->lng->txt("confirm"), "confirmedRemoveHeading"); + + $this->tpl->setContent($cgui->getHTML()); + } + + public function confirmedRemoveHeadingObject() + { + $q_id = (int) $_REQUEST["q_id"]; + if (!$q_id) { + $this->ctrl->redirect($this, "questions"); + } + + $this->object->saveHeading("", $q_id); + $this->ctrl->redirect($this, "questions"); + } + + /** + * Creates a print view of the survey questions + * + * @access public + */ + public function printViewObject() + { + $ilToolbar = $this->toolbar; + + $this->questionsSubtabs("print"); + + #21023 and #19448 + if (!$current_title = (int) $_REQUEST['export_label']) { + $current_title = $this->object->getShowQuestionTitles(); + } + /*if(!isset($_POST["export_label"])) + {fir + $_POST["export_label"] = $this->object->getShowQuestionTitles(); + } + $current_title = (int)$_REQUEST["export_label"]; + */ + + include_once "Services/Form/classes/class.ilSelectInputGUI.php"; + $label = new ilSelectInputGUI($this->lng->txt("title") . "/" . $this->lng->txt("label"), "export_label"); + + #19448 comment none and label only options. + $label->setOptions($this->print_options); + $label->setValue($current_title); + + $ilToolbar->addStickyItem($label, true); + + $ilToolbar->setFormAction($this->ctrl->getFormAction($this, "printView")); + + include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; + $button = ilSubmitButton::getInstance(); + $button->setCaption("show"); + $button->setCommand("printView"); + $ilToolbar->addStickyItem($button); + + $ilToolbar->addSeparator(); + + include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; + $button = ilLinkButton::getInstance(); + $button->setCaption("print"); + $button->setOnClick("window.print(); return false;"); + $button->setOmitPreventDoubleSubmission(true); + $ilToolbar->addButtonInstance($button); + + include_once './Services/WebServices/RPC/classes/class.ilRPCServerSettings.php'; + if (ilRPCServerSettings::getInstance()->isEnabled()) { + $this->ctrl->setParameter($this, "export_label", $current_title); + $this->ctrl->setParameter($this, "pdf", "1"); + $pdf_url = $this->ctrl->getLinkTarget($this, "printView"); + $this->ctrl->setParameter($this, "pdf", ""); + $this->ctrl->setParameter($this, "export_label", ""); + + $button = ilLinkButton::getInstance(); + $button->setCaption("pdf_export"); + $button->setUrl($pdf_url); + $button->setOmitPreventDoubleSubmission(true); + $ilToolbar->addButtonInstance($button); + } + + // defer rendering of tex to fo processing + if (array_key_exists("pdf", $_GET) && ($_GET["pdf"] == 1)) { + require_once('Services/MathJax/classes/class.ilMathJax.php'); + ilMathJax::getInstance()->init(ilMathJax::PURPOSE_DEFERRED_PDF); + } + + $template = new ilTemplate("tpl.il_svy_svy_printview.html", true, true, "Modules/Survey"); + + $pages =&$this->object->getSurveyPages(); + $required = false; + foreach ($pages as $page) { + if (count($page) > 0) { + foreach ($page as $question) { + $questionGUI = $this->object->getQuestionGUI($question["type_tag"], $question["question_id"]); + if (is_object($questionGUI)) { + if (strlen($question["heading"])) { + $template->setCurrentBlock("textblock"); + $template->setVariable("TEXTBLOCK", $question["heading"]); + $template->parseCurrentBlock(); + } + $template->setCurrentBlock("question"); + $template->setVariable("QUESTION_DATA", $questionGUI->getPrintView($current_title, $question["questionblock_show_questiontext"], $this->object->getSurveyId())); + $template->parseCurrentBlock(); + + if ($question["obligatory"]) { + $required = true; + } + } + } + if (count($page) > 1 && $page[0]["questionblock_show_blocktitle"]) { + $template->setCurrentBlock("page"); + $template->setVariable("BLOCKTITLE", $page[0]["questionblock_title"]); + $template->parseCurrentBlock(); + } else { + $template->setCurrentBlock("page"); + $template->parseCurrentBlock(); + } + } + } + + // #6412 + if ($required) { + $template->setVariable("TEXT_REQUIRED", $this->lng->txt("required_field")); + } + + // $this->tpl->addCss("./Modules/Survey/templates/default/survey_print.css", "print"); + if (array_key_exists("pdf", $_GET) && ($_GET["pdf"] == 1)) { + $printbody = new ilTemplate("tpl.il_as_tst_print_body.html", true, true, "Modules/Test"); + $printbody->setVariable("TITLE", sprintf($this->lng->txt("tst_result_user_name"), $uname)); + $printbody->setVariable("ADM_CONTENT", $template->get()); + $printoutput = $printbody->get(); + $printoutput = preg_replace("/href=\".*?\"/", "", $printoutput); + $fo = $this->object->processPrintoutput2FO($printoutput); + + // render tex as fo graphics + require_once('Services/MathJax/classes/class.ilMathJax.php'); + $fo = ilMathJax::getInstance() + ->init(ilMathJax::PURPOSE_PDF) + ->setRendering(ilMathJax::RENDER_PNG_AS_FO_FILE) + ->insertLatexImages($fo); + + // #11436 + if (!$fo || !$this->object->deliverPDFfromFO($fo)) { + ilUtil::sendFailure($this->lng->txt("msg_failed"), true); + $this->ctrl->redirect($this, "printView"); + } + } else { + $this->tpl->setVariable("ADM_CONTENT", $template->get()); + } + } +} diff --git a/Modules/Survey/classes/class.ilSurveyEvaluationGUI.php b/Modules/Survey/classes/class.ilSurveyEvaluationGUI.php index 3c14ab9a97bd586ca61be447ea17d4fc7d6ae9e6..31ad470113caa2cbb65d5a96b0aea439d7e34639 100644 --- a/Modules/Survey/classes/class.ilSurveyEvaluationGUI.php +++ b/Modules/Survey/classes/class.ilSurveyEvaluationGUI.php @@ -13,1829 +13,1641 @@ * @ingroup ModulesSurvey */ class ilSurveyEvaluationGUI -{ - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilTree - */ - protected $tree; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - const TYPE_XLS = "excel"; - const TYPE_SPSS = "csv"; - - const EXCEL_SUBTITLE = "DDDDDD"; - - var $object; - var $lng; - var $tpl; - var $ctrl; - var $appr_id = null; - - /** - * ilSurveyEvaluationGUI constructor - * - * The constructor takes possible arguments an creates an instance of the ilSurveyEvaluationGUI object. - * - * @param object $a_object Associated ilObjSurvey class - * @access public - */ - function __construct($a_object) - { - global $DIC; - - $this->tabs = $DIC->tabs(); - $this->access = $DIC->access(); - $this->user = $DIC->user(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->tree = $DIC->repositoryTree(); - $this->toolbar = $DIC->toolbar(); - $this->ui = $DIC->ui(); - $lng = $DIC->language(); - $tpl = $DIC["tpl"]; - $ilCtrl = $DIC->ctrl(); - - $this->lng = $lng; - $this->tpl = $tpl; - $this->ctrl = $ilCtrl; - $this->object = $a_object; - $this->log = ilLoggerFactory::getLogger("svy"); - $this->array_panels = array(); - - if ($this->object->get360Mode() || $this->object->getMode() == ilObjSurvey::MODE_SELF_EVAL) - { - $this->determineAppraiseeId(); - } - } - - /** - * execute command - */ - function executeCommand() - { - include_once("./Services/Skill/classes/class.ilSkillManagementSettings.php"); - $skmg_set = new ilSkillManagementSettings(); - if ($this->object->getSkillService() && $skmg_set->isActivated()) - { - $cmd = $this->ctrl->getCmd("competenceEval"); - } - else - { - $cmd = $this->ctrl->getCmd("evaluation"); - } - - $next_class = $this->ctrl->getNextClass($this); - - $cmd = $this->getCommand($cmd); - switch($next_class) - { - default: - $this->setEvalSubTabs(); - $ret =& $this->$cmd(); - break; - } - return $ret; - } - - function getCommand($cmd) - { - return $cmd; - } - - /** - * Set the tabs for the evaluation output - * - * @access private - */ - function setEvalSubtabs() - { - $ilTabs = $this->tabs; - $ilAccess = $this->access; - - include_once("./Services/Skill/classes/class.ilSkillManagementSettings.php"); - $skmg_set = new ilSkillManagementSettings(); - if ($this->object->getSkillService() && $skmg_set->isActivated()) - { - $ilTabs->addSubTabTarget( - "svy_eval_competences", - $this->ctrl->getLinkTarget($this, "competenceEval"), - array("competenceEval") - ); - } - - $ilTabs->addSubTabTarget( - "svy_eval_cumulated", - $this->ctrl->getLinkTarget($this, "evaluation"), - array("evaluation", "checkEvaluationAccess") - ); - - $ilTabs->addSubTabTarget( - "svy_eval_detail", - $this->ctrl->getLinkTarget($this, "evaluationdetails"), - array("evaluationdetails") - ); - - if($this->hasResultsAccess()) - { - $ilTabs->addSubTabTarget( - "svy_eval_user", - $this->ctrl->getLinkTarget($this, "evaluationuser"), - array("evaluationuser") - ); - } - } - - - /** - * Set appraisee id - * - * @param int $a_val appraisee id - */ - function setAppraiseeId($a_val) - { - $this->appr_id = $a_val; - } - - /** - * Get appraisee id - * - * @return int appraisee id - */ - function getAppraiseeId() - { - return $this->appr_id; - } - - /** - * Determine appraisee id - */ - function determineAppraiseeId() - { - $ilUser = $this->user; - $rbacsystem = $this->rbacsystem; - - $appr_id = ""; - - // always start with current user - if ($_REQUEST["appr_id"] == "") - { - $req_appr_id = $ilUser->getId(); - } - else - { - $req_appr_id = (int) $_REQUEST["appr_id"]; - } - - // write access? allow selection - if ($req_appr_id > 0 && $this->object->get360Mode()) - { - $all_appr = ($this->object->get360Results() == ilObjSurvey::RESULTS_360_ALL); - - $valid = array(); - foreach($this->object->getAppraiseesData() as $item) - { - if ($item["closed"] && - ($item["user_id"] == $ilUser->getId() || - $rbacsystem->checkAccess("write", $this->object->getRefId()) || - $all_appr)) - { - $valid[] = $item["user_id"]; - } - } - if(in_array($req_appr_id, $valid)) - { - $appr_id = $req_appr_id; - } - else - { - // current selection / user is not valid, use 1st valid instead - $appr_id = array_shift($valid); - } - } - else // SVY SELF EVALUATION MODE - { - $appr_id = $req_appr_id; - } - - $this->ctrl->setParameter($this, "appr_id", $appr_id); - $this->setAppraiseeId($appr_id); - } - - - /** - * Show the detailed evaluation - * - * Show the detailed evaluation - * - * @access private - */ - function checkAnonymizedEvaluationAccess() - { - $ilUser = $this->user; - - if($this->object->getAnonymize() == 1 && - $_SESSION["anon_evaluation_access"] == $_GET["ref_id"]) - { - return true; - } - - include_once "Modules/Survey/classes/class.ilObjSurveyAccess.php"; - if(ilObjSurveyAccess::_hasEvaluationAccess(ilObject::_lookupObjId($_GET["ref_id"]), $ilUser->getId())) - { - if($this->object->getAnonymize() == 1) - { - $_SESSION["anon_evaluation_access"] = $_GET["ref_id"]; - } - return true; - } - - if($this->object->getAnonymize() == 1) - { - // autocode - $surveycode = $this->object->getUserAccessCode($ilUser->getId()); - if ($this->object->isAnonymizedParticipant($surveycode)) - { - $_SESSION["anon_evaluation_access"] = $_GET["ref_id"]; - return true; - } - - /* try to find code for current (registered) user from existing run - if($this->object->findCodeForUser($ilUser->getId())) - { - $_SESSION["anon_evaluation_access"] = $_GET["ref_id"]; - return true; - } - */ - - // code needed - $this->tpl->setVariable("TABS", ""); - $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.il_svy_svy_evaluation_checkaccess.html", "Modules/Survey"); - $this->tpl->setCurrentBlock("adm_content"); - $this->tpl->setVariable("AUTHENTICATION_NEEDED", $this->lng->txt("svy_check_evaluation_authentication_needed")); - $this->tpl->setVariable("FORM_ACTION", $this->ctrl->getFormAction($this, "checkEvaluationAccess")); - $this->tpl->setVariable("EVALUATION_CHECKACCESS_INTRODUCTION", $this->lng->txt("svy_check_evaluation_access_introduction")); - $this->tpl->setVariable("VALUE_CHECK", $this->lng->txt("ok")); - $this->tpl->setVariable("VALUE_CANCEL", $this->lng->txt("cancel")); - $this->tpl->setVariable("TEXT_SURVEY_CODE", $this->lng->txt("survey_code")); - $this->tpl->parseCurrentBlock(); - } - - $_SESSION["anon_evaluation_access"] = null; - return false; - } - - /** - * Checks the evaluation access after entering the survey access code - * - * Checks the evaluation access after entering the survey access code - * - * @access private - */ - function checkEvaluationAccess() - { - $surveycode = $_POST["surveycode"]; - if ($this->object->isAnonymizedParticipant($surveycode)) - { - $_SESSION["anon_evaluation_access"] = $_GET["ref_id"]; - $this->evaluation(); - } - else - { - ilUtil::sendFailure($this->lng->txt("svy_check_evaluation_wrong_key", true)); - $this->cancelEvaluationAccess(); - } - } - - /** - * Cancels the input of the survey access code for evaluation access - * - * Cancels the input of the survey access code for evaluation access - * - * @access private - */ - function cancelEvaluationAccess() - { - $ilCtrl = $this->ctrl; - $tree = $this->tree; - $path = $tree->getPathFull($this->object->getRefID()); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", - $path[count($path) - 2]["child"]); - $ilCtrl->redirectByClass("ilrepositorygui", "frameset"); - } - - /** - * Show the detailed evaluation - * - * Show the detailed evaluation - * - * @access private - */ - function evaluationdetails() - { - $this->evaluation(1); - } - - function exportCumulatedResults($details = 0) - { - $finished_ids = null; - if($this->object->get360Mode()) - { - $appr_id = $_REQUEST["appr_id"]; - if(!$appr_id) - { - $this->ctrl->redirect($this, $details ? "evaluationdetails" : "evaluation"); - } - $finished_ids = $this->object->getFinishedIdsForAppraiseeId($appr_id); - if(!sizeof($finished_ids)) - { - $finished_ids = array(-1); - } - } - - // titles - $title_row = array(); - $do_title = $do_label = true; - switch ($_POST['export_label']) - { - case 'label_only': - $title_row[] = $this->lng->txt("label"); - $do_title = false; - break; - - case 'title_only': - $title_row[] = $this->lng->txt("title"); - $do_label = false; - break; - - default: - $title_row[] = $this->lng->txt("title"); - $title_row[] = $this->lng->txt("label"); - break; - } - $title_row[] = $this->lng->txt("question"); - $title_row[] = $this->lng->txt("question_type"); - $title_row[] = $this->lng->txt("users_answered"); - $title_row[] = $this->lng->txt("users_skipped"); - $title_row[] = $this->lng->txt("mode"); - $title_row[] = $this->lng->txt("mode_text"); - $title_row[] = $this->lng->txt("mode_nr_of_selections"); - $title_row[] = $this->lng->txt("median"); - $title_row[] = $this->lng->txt("arithmetic_mean"); - - // creating container - switch ($_POST["export_format"]) - { - case self::TYPE_XLS: - include_once "Services/Excel/classes/class.ilExcel.php"; - $excel = new ilExcel(); - $excel->addSheet($this->lng->txt("svy_eval_cumulated")); - $excel->setCellArray(array($title_row), "A1"); - $excel->setBold("A1:".$excel->getColumnCoord(sizeof($title_row)-1)."1"); - break; - - case self::TYPE_SPSS: - $csvfile = array($title_row); - break; - } - - - // parse answer data in evaluation results - $ov_row = 2; - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - foreach($this->object->getSurveyQuestions() as $qdata) - { - $q_eval = SurveyQuestion::_instanciateQuestionEvaluation($qdata["question_id"], $finished_ids); - $q_res = $q_eval->getResults(); - $ov_rows = $q_eval->exportResults($q_res, $do_title, $do_label); - - switch ($_POST["export_format"]) - { - case self::TYPE_XLS: - $excel->setActiveSheet(0); - foreach($ov_rows as $row) - { - foreach($row as $col => $value) - { - $excel->setCell($ov_row, $col, $value); - } - $ov_row++; - } - break; - - case self::TYPE_SPSS: - foreach($ov_rows as $row) - { - $csvfile[] = $row; - } - break; - } - - if ($details) - { - switch ($_POST["export_format"]) - { - case self::TYPE_XLS: - $this->exportResultsDetailsExcel($excel, $q_eval, $q_res, $do_title, $do_label); - break; - } - } - - } - - // #11179 - $type = !$details - ? $this->lng->txt("svy_eval_cumulated") - : $this->lng->txt("svy_eval_detail"); - - $surveyname = $this->object->getTitle()." ".$type." ".date("Y-m-d"); - $surveyname = preg_replace("/\s/", "_", trim($surveyname)); - $surveyname = ilUtil::getASCIIFilename($surveyname); - - // send to client - switch ($_POST["export_format"]) - { - case self::TYPE_XLS: - $excel->sendToClient($surveyname); - break; - - case self::TYPE_SPSS: - $csv = ""; - $separator = ";"; - foreach ($csvfile as $csvrow) - { - $csvrow = $this->processCSVRow($csvrow, TRUE, $separator); - $csv .= join($csvrow, $separator) . "\n"; - } - ilUtil::deliverData($csv, $surveyname.".csv"); - exit(); - break; - } - } - - /** - * Export details (excel only) - * - * @param ilExcel $a_excel - * @param SurveyQuestionEvaluation $a_eval - * @param ilSurveyEvaluationResults|array $a_results - * @param bool $a_do_title - * @param bool|array $a_do_label - */ - protected function exportResultsDetailsExcel(ilExcel $a_excel, SurveyQuestionEvaluation $a_eval, $a_results, $a_do_title, $a_do_label) - { - $question_res = $a_results; - $matrix = false; - if(is_array($question_res)) - { - $question_res = $question_res[0][1]; - $matrix = true; - } - $question = $question_res->getQuestion(); - - $a_excel->addSheet($question->getTitle()); - - - // question "overview" - - $kv = array(); - - if($a_do_title) - { - $kv[$this->lng->txt("title")] = $question->getTitle(); - } - if($a_do_label) - { - $kv[$this->lng->txt("label")] = $question->label; - } - - // question - $kv[$this->lng->txt("question")] = $question->getQuestiontext(); - - // question type - $kv[$this->lng->txt("question_type")] = SurveyQuestion::_getQuestionTypeName($question->getQuestionType()); - - // :TODO: present subtypes (hrz/vrt, mc/sc mtx, metric scale)? - - // answered and skipped users - $kv[$this->lng->txt("users_answered")] = (int)$question_res->getUsersAnswered(); - $kv[$this->lng->txt("users_skipped")] = (int)$question_res->getUsersSkipped(); // #0021671 - - $excel_row = 1; - - foreach($kv as $key => $value) - { - $a_excel->setCell($excel_row, 0, $key); - $a_excel->setCell($excel_row++, 1, $value); - } - - if(!$matrix) - { - $this->parseResultsToExcel( - $a_excel, - $question_res, - $excel_row, - $a_eval->getExportGrid($a_results), - $a_eval->getTextAnswers($a_results) - ); - } - else - { - // question - $this->parseResultsToExcel( - $a_excel, - $question_res, - $excel_row, - null, - null, - false - ); - - $texts = $a_eval->getTextAnswers($a_results); - - // "rows" - foreach($a_results as $row_results) - { - $row_title = $row_results[0]; - - $a_excel->setCell($excel_row, 0, $this->lng->txt("row")); - $a_excel->setCell($excel_row++, 1, $row_title); - - $this->parseResultsToExcel( - $a_excel, - $row_results[1], - $excel_row, - $a_eval->getExportGrid($row_results[1]), - is_array($texts[$row_title]) - ? array(""=>$texts[$row_title]) - : null - ); - } - } - - // matrix question: overview #21438 - if ($matrix) - { - $a_excel->setCell($excel_row++, 0, $this->lng->txt("overview")); - - // title row with variables - $counter = 0; - $cats = $question->getColumns(); - foreach ($cats->getCategories() as $cat) - { - $a_excel->setColors($a_excel->getCoordByColumnAndRow(1 + $counter, $excel_row), ilSurveyEvaluationGUI::EXCEL_SUBTITLE); - $a_excel->setCell($excel_row, 1 + $counter, $cat->title); - $counter++; - } - $excel_row++; - - foreach ($a_results as $row_results) - { - $row_title = $row_results[0]; - $counter = 0; - $a_excel->setCell($excel_row, 0, $row_title); - - $vars = $row_results[1]->getVariables(); - if($vars) - { - foreach($vars as $var) - { - $a_excel->setCell($excel_row, ++$counter, $var->abs); - } - } - $excel_row++; - } - } - - // 1st column is bold - $a_excel->setBold("A1:A".$excel_row); - } - - protected function parseResultsToExcel(ilExcel $a_excel, ilSurveyEvaluationResults $a_results, &$a_excel_row, array $a_grid = null, array $a_text_answers = null, $a_include_mode = true) - { - $kv = array(); - - if($a_include_mode) - { - if($a_results->getModeValue() !== null) - { - // :TODO: - $kv[$this->lng->txt("mode")] = is_array($a_results->getModeValue()) - ? implode(", ", $a_results->getModeValue()) - : $a_results->getModeValue(); - - $kv[$this->lng->txt("mode_text")] = $a_results->getModeValueAsText(); - $kv[$this->lng->txt("mode_nr_of_selections")] = (int)$a_results->getModeNrOfSelections(); - } - - if($a_results->getMedian() !== null) - { - $kv[$this->lng->txt("median")] = $a_results->getMedianAsText(); - } - - if($a_results->getMean() !== null) - { - $kv[$this->lng->txt("arithmetic_mean")] = $a_results->getMean(); - } - } - - foreach($kv as $key => $value) - { - $a_excel->setCell($a_excel_row, 0, $key); - $a_excel->setCell($a_excel_row++, 1, $value); - } - - // grid - if($a_grid) - { - // header - $a_excel->setColors("B".$a_excel_row.":E".$a_excel_row, ilSurveyEvaluationGUI::EXCEL_SUBTITLE); - $a_excel->setCell($a_excel_row, 0, $this->lng->txt("categories")); - foreach($a_grid["cols"] as $col_idx => $col) - { - $a_excel->setCell($a_excel_row, $col_idx+1, $col); - } - $a_excel_row++; - - // rows - foreach($a_grid["rows"] as $cols) - { - foreach($cols as $col_idx => $col) - { - $a_excel->setCell($a_excel_row, $col_idx+1, $col); - } - $a_excel_row++; - } - } - - // text answers - if($a_text_answers) - { - // "given_answers" ? - $a_excel->setCell($a_excel_row, 0, $this->lng->txt("freetext_answers")); - - // mc/sc - if(!is_array($a_text_answers[""])) - { - $a_excel->setColors("B".$a_excel_row.":C".$a_excel_row, ilSurveyEvaluationGUI::EXCEL_SUBTITLE); - $a_excel->setCell($a_excel_row, 1, $this->lng->txt("title")); - $a_excel->setCell($a_excel_row++, 2, $this->lng->txt("answer")); - } - // mtx (row), txt - else - { - $a_excel->setColors("B".$a_excel_row.":B".$a_excel_row, ilSurveyEvaluationGUI::EXCEL_SUBTITLE); - $a_excel->setCell($a_excel_row++, 1, $this->lng->txt("answer")); - } - - foreach($a_text_answers as $var => $items) - { - foreach($items as $item) - { - if(!is_array($a_text_answers[""])) - { - $a_excel->setCell($a_excel_row, 1, $var); - $a_excel->setCell($a_excel_row++, 2, $item); - } - else - { - $a_excel->setCell($a_excel_row++, 1, $item); - } - } - } - } - } - - public function exportData() - { - if (strlen($_POST["export_format"])) - { - $this->exportCumulatedResults(0); - return; - } - else - { - $this->ctrl->redirect($this, 'evaluation'); - } - } - - public function exportDetailData() - { - if (strlen($_POST["export_format"])) - { - $this->exportCumulatedResults(1); - return; - } - else - { - $this->ctrl->redirect($this, 'evaluation'); - } - } - - public function printEvaluation() - { - ilUtil::sendInfo($this->lng->txt('use_browser_print_function'), true); - $this->ctrl->redirect($this, 'evaluation'); - } - - protected function buildExportModal($a_id, $a_cmd) - { - $tpl = $this->tpl; - - $form_id = "svymdfrm"; - - // hide modal on form submit - $tpl->addOnLoadCode('$("#form_'.$form_id.'").submit(function() { $("#'.$a_id.'").modal("hide"); });'); - - include_once "Services/UIComponent/Modal/classes/class.ilModalGUI.php"; - $modal = ilModalGUI::getInstance(); - $modal->setId($a_id); - $modal->setHeading(($this->lng->txt("svy_export_format"))); - - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $form = new ilPropertyFormGUI(); - $form->setId($form_id); - $form->setFormAction($this->ctrl->getFormAction($this, $a_cmd)); - - $format = new ilSelectInputGUI($this->lng->txt("filetype"), "export_format"); - $format->setOptions(array( - self::TYPE_XLS => $this->lng->txt('exp_type_excel'), - self::TYPE_SPSS => $this->lng->txt('exp_type_csv') - )); - $form->addItem($format, true); - - $label = new ilSelectInputGUI($this->lng->txt("title"), "export_label"); - $label->setOptions(array( - 'label_only' => $this->lng->txt('export_label_only'), - 'title_only' => $this->lng->txt('export_title_only'), - 'title_label'=> $this->lng->txt('export_title_label') - )); - $form->addItem($label); - - $form->addCommandButton($a_cmd, $this->lng->txt("export")); - $form->setPreventDoubleSubmission(false); - - $modal->setBody($form->getHTML()); - - return $modal->getHTML(); - } - - function evaluation($details = 0) - { - $rbacsystem = $this->rbacsystem; - $ilToolbar = $this->toolbar; - $tree = $this->tree; - $ui = $this->ui; - - $ui_factory = $ui->factory(); - $ui_renderer = $ui->renderer(); - - // auth - if(!$this->hasResultsAccess()) - { - if(!$this->access->checkAccess('read','',$this->object->getRefId())) - { - ilUtil::sendFailure($this->lng->txt("permission_denied")); - return; - } - - switch ($this->object->getEvaluationAccess()) - { - case ilObjSurvey::EVALUATION_ACCESS_OFF: - ilUtil::sendFailure($this->lng->txt("permission_denied")); - return; - - case ilObjSurvey::EVALUATION_ACCESS_ALL: - case ilObjSurvey::EVALUATION_ACCESS_PARTICIPANTS: - if(!$this->checkAnonymizedEvaluationAccess()) - { - ilUtil::sendFailure($this->lng->txt("permission_denied")); - return; - } - break; - } - } - - $ilToolbar->setFormAction($this->ctrl->getFormAction($this)); - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - - $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.il_svy_svy_evaluation.html", "Modules/Survey"); - - if($this->object->get360Mode()) - { - $appr_id = $this->getAppraiseeId(); - $this->addApprSelectionToToolbar(); - } - - $results = array(); - if(!$this->object->get360Mode() || $appr_id) - { - if($details) - { - $captions = new ilSelectInputGUI($this->lng->txt("svy_eval_captions"), "cp"); - $captions->setOptions(array( - "ap" => $this->lng->txt("svy_eval_captions_abs_perc"), - "a" => $this->lng->txt("svy_eval_captions_abs"), - "p" => $this->lng->txt("svy_eval_captions_perc") - )); - $captions->setValue($_POST["cp"]); - $ilToolbar->addInputItem($captions, true); - - $view = new ilSelectInputGUI($this->lng->txt("svy_eval_view"), "vw"); - $view->setOptions(array( - "tc" => $this->lng->txt("svy_eval_view_tables_charts"), - "t" => $this->lng->txt("svy_eval_view_tables"), - "c" => $this->lng->txt("svy_eval_view_charts") - )); - $view->setValue($_POST["vw"]); - $ilToolbar->addInputItem($view, true); - - include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; - $button = ilSubmitButton::getInstance(); - $button->setCaption("ok"); - $button->setCommand("evaluationdetails"); - $button->setOmitPreventDoubleSubmission(true); - $ilToolbar->addButtonInstance($button); - - $ilToolbar->addSeparator(); - - //templates: results, table of contents - $dtmpl = new ilTemplate("tpl.il_svy_svy_results_details.html", true, true, "Modules/Survey"); - $toc_tpl = new ilTemplate("tpl.svy_results_table_contents.html", true, true, "Modules/Survey"); - $this->lng->loadLanguageModule("content"); - $toc_tpl->setVariable("TITLE_TOC", $this->lng->txt('cont_toc')); - } - - $modal_id = "svy_ev_exp"; - $modal = $this->buildExportModal($modal_id, $details - ? 'exportDetailData' - : 'exportData'); - - include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; - $button = ilLinkButton::getInstance(); - $button->setCaption("export"); - $button->setOnClick('$(\'#'.$modal_id.'\').modal(\'show\')'); - $ilToolbar->addButtonInstance($button); - - $ilToolbar->addSeparator(); - - include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; - $button = ilLinkButton::getInstance(); - $button->setCaption("print"); - $button->setOnClick("if(il.Accordion) { il.Accordion.preparePrint(); } window.print(); return false;"); - $button->setOmitPreventDoubleSubmission(true); - $ilToolbar->addButtonInstance($button); - - $finished_ids = null; - if($appr_id) - { - $finished_ids = $this->object->getFinishedIdsForAppraiseeId($appr_id); - if(!sizeof($finished_ids)) - { - $finished_ids = array(-1); - } - } - - $details_figure = $_POST["cp"] - ? $_POST["cp"] - : "ap"; - $details_view = $_POST["vw"] - ? $_POST["vw"] - : "tc"; - - // @todo - // filter finished ids - $finished_ids2 = $this->access->filterUserIdsByRbacOrPositionOfCurrentUser( - 'read_results', - 'access_results', - $this->object->getRefId(), - (array) $finished_ids - ); - - // parse answer data in evaluation results - include_once("./Services/UIComponent/NestedList/classes/class.ilNestedList.php"); - $list = new ilNestedList(); - - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - foreach($this->object->getSurveyQuestions() as $qdata) - { - $q_eval = SurveyQuestion::_instanciateQuestionEvaluation($qdata["question_id"], $finished_ids); - $q_res = $q_eval->getResults(); - $results[] = $q_res; - - if($details) - { - //$this->renderDetails($details_view, $details_figure, $dtmpl, $qdata, $q_eval, $q_res); - $this->renderDetails($details_view, $details_figure, $qdata, $q_eval, $q_res); - - // TABLE OF CONTENTS - if($qdata["questionblock_id"] && - $qdata["questionblock_id"] != $this->last_questionblock_id) - { - $qblock = ilObjSurvey::_getQuestionblock($qdata["questionblock_id"]); - if($qblock["show_blocktitle"]) - { - $list->addListNode($qdata["questionblock_title"], "q".$qdata["questionblock_id"]); - } - $this->last_questionblock_id = $qdata["questionblock_id"]; - } - $anchor_id = "svyrdq".$qdata["question_id"]; - $list->addListNode("".$qdata["title"]."", $qdata["question_id"], $qdata["questionblock_id"] ? - "q".$qdata["questionblock_id"] : 0); - } - } - - if($details) - { - $list->setListClass("il_Explorer"); - $toc_tpl->setVariable("LIST", $list->getHTML()); - - //TABLE OF CONTENTS - $panel_toc = $ui_factory->panel()->standard("", $ui_factory->legacy($toc_tpl->get())); - $render_toc = $ui_renderer->render($panel_toc); - $dtmpl->setVariable("PANEL_TOC", $render_toc); - - //REPORT - $report_title = ""; - $panel_report = $ui_factory->panel()->report($report_title, $this->array_panels); - $render_report = $ui_renderer->render($panel_report); - $dtmpl->setVariable("PANEL_REPORT",$render_report); - - //print the main template - $this->tpl->setVariable('DETAIL', $dtmpl->get()); - } - } - - $this->tpl->setVariable('MODAL', $modal); - if(!$details) - { - include_once "./Modules/Survey/classes/tables/class.ilSurveyResultsCumulatedTableGUI.php"; - $table_gui = new ilSurveyResultsCumulatedTableGUI($this, $details ? 'evaluationdetails' : 'evaluation', $results); - $this->tpl->setVariable('CUMULATED', $table_gui->getHTML()); - } - unset($dtmpl); - unset($table_gui); - unset($modal); - - - // print header - - $path = ""; - $path_full = $tree->getPathFull($this->object->getRefId()); - foreach($path_full as $data) - { - $path .= " » "; - $path .= $data['title']; - } - - ilDatePresentation::setUseRelativeDates(false); - include_once "Services/Link/classes/class.ilLink.php"; - - $props = array( - $this->lng->txt("link") => ilLink::_getStaticLink($this->object->getRefId()), - $this->lng->txt("path") => $path, - $this->lng->txt("svy_results") => !$details - ? $this->lng->txt("svy_eval_cumulated") - : $this->lng->txt("svy_eval_detail"), - $this->lng->txt("date") => ilDatePresentation::formatDate(new ilDateTime(time(), IL_CAL_UNIX)), - ); - - $this->tpl->setCurrentBlock("print_header_bl"); - foreach($props as $key => $value) - { - $this->tpl->setVariable("HEADER_PROP_KEY", $key); - $this->tpl->setVariable("HEADER_PROP_VALUE", $value); - $this->tpl->parseCurrentBlock(); - } - - // $this->tpl->addCss("./Modules/Survey/templates/default/survey_print.css", "print"); - } - - /** - * Render details - * - * @param string $a_details_parts - * @param string $a_details_figure - * @param___ ilTemplate $a_tpl - * @param array $a_qdata - * @param SurveyQuestionEvaluation $a_eval - * @param ilSurveyEvaluationResults|array $a_results - */ - //protected function renderDetails($a_details_parts, $a_details_figure, ilTemplate $a_tpl, array $a_qdata, SurveyQuestionEvaluation $a_eval, $a_results) - protected function renderDetails($a_details_parts, $a_details_figure, array $a_qdata, SurveyQuestionEvaluation $a_eval, $a_results) - { - $ui_factory = $this->ui->factory(); - $a_tpl = new ilTemplate("tpl.svy_results_details_panel.html", true, true, "Modules/Survey"); - - $question_res = $a_results; - $matrix = false; - if(is_array($question_res)) - { - $question_res = $question_res[0][1]; - $matrix = true; - } - $question = $question_res->getQuestion(); - - // question "overview" - - // :TODO: present subtypes (hrz/vrt, mc/sc mtx)? - - $a_tpl->setVariable("QTYPE", SurveyQuestion::_getQuestionTypeName($question->getQuestionType())); - - $kv = array(); - $kv["users_answered"] = $question_res->getUsersAnswered(); - $kv["users_skipped"] = $question_res->getUsersSkipped(); - - if(!$matrix) - { - if($question_res->getModeValue() !== null) - { - $kv["mode"] = wordwrap($question_res->getModeValueAsText(), 50, "
"); - $kv["mode_nr_of_selections"] = $question_res->getModeNrOfSelections(); - } - if($question_res->getMedian() !== null) - { - $kv["median"] = $question_res->getMedianAsText(); - } - if($question_res->getMean() !== null) - { - $kv["arithmetic_mean"] = $question_res->getMean(); - } - } - - $svy_type_title = SurveyQuestion::_getQuestionTypeName($question->getQuestionType()); - $qst_title = $question->getTitle(); - $svy_text = nl2br($question->getQuestiontext()); - $card_table_tpl = new ilTemplate("tpl.svy_results_details_card.html", true, true, "Modules/Survey"); - foreach($kv as $key => $value) - { - $card_table_tpl->setCurrentBlock("question_statistics_card"); - $card_table_tpl->setVariable("QUESTION_STATISTIC_KEY", $this->lng->txt($key)); - $card_table_tpl->setVariable("QUESTION_STATISTIC_VALUE", $value); - $card_table_tpl->parseCurrentBlock(); - } - //anchor in title. Used in TOC - $anchor_id = "svyrdq".$question->getId(); - $title = "$qst_title"; - $panel_qst_card = $ui_factory->panel()->sub($title, $ui_factory->legacy($svy_text)) - ->withCard($ui_factory->card()->standard($svy_type_title)->withSections(array($ui_factory->legacy($card_table_tpl->get())))); - array_push($this->array_panels, $panel_qst_card); - - // grid - if($a_details_parts == "t" || - $a_details_parts == "tc") - { - $grid = $a_eval->getGrid( - $a_results, - ($a_details_figure == "ap" || $a_details_figure == "a"), - ($a_details_figure == "ap" || $a_details_figure == "p") - ); - if($grid) - { - foreach($grid["cols"] as $col) - { - $a_tpl->setCurrentBlock("grid_col_header_bl"); - $a_tpl->setVariable("COL_HEADER", $col); - $a_tpl->parseCurrentBlock(); - } - foreach($grid["rows"] as $cols) - { - foreach($cols as $idx => $col) - { - if($idx > 0) - { - $a_tpl->touchBlock("grid_col_nowrap_bl"); - } - - $a_tpl->setCurrentBlock("grid_col_bl"); - $a_tpl->setVariable("COL_CAPTION", trim($col)); - $a_tpl->parseCurrentBlock(); - } - - $a_tpl->touchBlock("grid_row_bl"); - } - } - } - - // text answers - $texts = $a_eval->getTextAnswers($a_results); - if($texts) - { - if(array_key_exists("", $texts)) - { - $a_tpl->setVariable("TEXT_HEADING", $this->lng->txt("given_answers")); - foreach($texts[""] as $item) - { - $a_tpl->setCurrentBlock("text_direct_item_bl"); - $a_tpl->setVariable("TEXT_DIRECT", nl2br($item)); - $a_tpl->parseCurrentBlock(); - } - } - else - { - include_once "Services/Accordion/classes/class.ilAccordionGUI.php"; - $acc = new ilAccordionGUI(); - $acc->setId("svyevaltxt".$question->getId()); - - $a_tpl->setVariable("TEXT_HEADING", $this->lng->txt("freetext_answers")); - - foreach($texts as $var => $items) - { - $list = array("
    "); - foreach($items as $item) - { - $list[] = "
  • ".nl2br($item)."
  • "; - } - $list[] = "
"; - $acc->addItem($var, implode("\n", $list)); - } - - $a_tpl->setVariable("TEXT_ACC", $acc->getHTML()); - } - } - - // chart - if($a_details_parts == "c" || - $a_details_parts == "tc") - { - $chart = $a_eval->getChart($a_results); - if($chart) - { - if(is_array($chart)) - { - // legend - if(is_array($chart[1])) - { - foreach($chart[1] as $legend_item) - { - $r = hexdec(substr($legend_item[1], 1, 2)); - $g = hexdec(substr($legend_item[1], 3, 2)); - $b = hexdec(substr($legend_item[1], 5, 2)); - - $a_tpl->setCurrentBlock("legend_bl"); - $a_tpl->setVariable("LEGEND_CAPTION", $legend_item[0]); - $a_tpl->setVariable("LEGEND_COLOR", $legend_item[1]); - $a_tpl->setVariable("LEGEND_COLOR_SVG", $r.",".$g.",".$b); - $a_tpl->parseCurrentBlock(); - } - } - - $chart = $chart[0]; - } - $a_tpl->setVariable("CHART", $chart); - } - } - $panel = $ui_factory->panel()->sub("", $ui_factory->legacy($a_tpl->get())); - array_push($this->array_panels, $panel); - } - - /** - * Add appraisee selection to toolbar - * - * @param - * @return - */ - function addApprSelectionToToolbar() - { - $ilToolbar = $this->toolbar; - $rbacsystem = $this->rbacsystem; - - $svy_mode = $this->object->getMode(); - if($svy_mode == ilObjSurvey::MODE_360 || $svy_mode == ilObjSurvey::MODE_SELF_EVAL) - { - $appr_id = $this->getAppraiseeId(); - - $options = array(); - if(!$appr_id) - { - $options[""] = $this->lng->txt("please_select"); - } - - $no_appr = true; - if($this->object->get360Mode()) - { - foreach($this->object->getAppraiseesData() as $item) - { - if($item["closed"]) - { - $options[$item["user_id"]] = $item["login"]; - $no_appr = false; - } - } - } - else //self evaluation mode - { - foreach($this->object->getSurveyParticipants() as $item) - { - $options[ilObjUser::_lookupId($item['login'])] = $item['login']; - $no_appr = false; - } - } - - if(!$no_appr) - { - if ($rbacsystem->checkAccess("write", $this->object->getRefId()) || - $this->object->get360Results() == ilObjSurvey::RESULTS_360_ALL || - $this->object->getSelfEvaluationResults() == ilObjSurvey::RESULTS_SELF_EVAL_ALL) - { - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $appr = new ilSelectInputGUI($this->lng->txt("svy_participant"), "appr_id"); - $appr->setOptions($options); - $appr->setValue($this->getAppraiseeId()); - $ilToolbar->addInputItem($appr, true); - - include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; - $button = ilSubmitButton::getInstance(); - $button->setCaption("survey_360_select_appraisee"); - $button->setCommand($this->ctrl->getCmd()); - $ilToolbar->addButtonInstance($button); - - if($appr_id) - { - $ilToolbar->addSeparator(); - } - } - } - else - { - ilUtil::sendFailure($this->lng->txt("survey_360_no_closed_appraisees")); - } - } - } - - /** - * Processes an array as a CSV row and converts the array values to correct CSV - * values. The "converted" array is returned - * - * @param array $row The array containing the values for a CSV row - * @param string $quoteAll Indicates to quote every value (=TRUE) or only values containing quotes and separators (=FALSE, default) - * @param string $separator The value separator in the CSV row (used for quoting) (; = default) - * @return array The converted array ready for CSV use - * @access public - */ - function processCSVRow($row, $quoteAll = FALSE, $separator = ";") - { - $resultarray = array(); - foreach ($row as $rowindex => $entry) - { - if(is_array($entry)) - { - $entry = implode("/", $entry); - } - $surround = FALSE; - if ($quoteAll) - { - $surround = TRUE; - } - if (strpos($entry, "\"") !== FALSE) - { - $entry = str_replace("\"", "\"\"", $entry); - $surround = TRUE; - } - if (strpos($entry, $separator) !== FALSE) - { - $surround = TRUE; - } - // replace all CR LF with LF (for Excel for Windows compatibility - $entry = str_replace(chr(13).chr(10), chr(10), $entry); - if ($surround) - { - $resultarray[$rowindex] = utf8_decode("\"" . $entry . "\""); - } - else - { - $resultarray[$rowindex] = utf8_decode($entry); - } - } - return $resultarray; - } - - - function exportEvaluationUser() - { - // build title row(s) - - $title_row = $title_row2 = array(); - $title_row[] = $this->lng->txt("lastname"); // #12756 - $title_row[] = $this->lng->txt("firstname"); - $title_row[] = $this->lng->txt("login"); - $title_row[] = $this->lng->txt('workingtime'); // #13622 - $title_row[] = $this->lng->txt('survey_results_finished'); - $title_row2[] = ""; - $title_row2[] = ""; - $title_row2[] = ""; - $title_row2[] = ""; - $title_row2[] = ""; - if($this->object->canExportSurveyCode()) - { - $title_row[] = $this->lng->txt("codes"); - $title_row2[] = ""; - } - - $questions = array(); - - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - foreach($this->object->getSurveyQuestions() as $qdata) - { - $q_eval = SurveyQuestion::_instanciateQuestionEvaluation($qdata["question_id"], $finished_ids); - $q_res = $q_eval->getResults(); - - $questions[$qdata["question_id"]] = array($q_eval, $q_res); - - $question = is_array($q_res) - ? $q_res[0][1]->getQuestion() - : $q_res->getQuestion(); - - $do_title = $do_label = true; - switch($_POST['export_label']) - { - case "label_only": - $title_row[] = $question->label; - $title_row2[] = ""; - $do_title = false; - break; - - case "title_only": - $title_row[] = $question->getTitle(); - $title_row2[] = ""; - $do_label = false; - break; - - default: - $title_row[] = $question->getTitle(); - $title_row2[] = $question->label; - break; - } - - $q_eval->getUserSpecificVariableTitles($title_row, $title_row2, $do_title, $do_label); - } - - $rows = array(); - - // add title row(s) - $rows[] = $title_row; - if(implode("", $title_row2)) - { - $rows[] = $title_row2; - } - - // #13620 - ilDatePresentation::setUseRelativeDates(false); - - $finished_ids = null; - if($this->object->get360Mode()) - { - $appr_id = $_REQUEST["appr_id"]; - if(!$appr_id) - { - $this->ctrl->redirect($this, "evaluationuser"); - } - $finished_ids = $this->object->getFinishedIdsForAppraiseeId($appr_id); - if(!sizeof($finished_ids)) - { - $finished_ids = array(-1); - } - } - - //$participants = $this->object->getSurveyParticipants($finished_ids); - $participants = $this->filterSurveyParticipantsByAccess($finished_ids); - - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - foreach($participants as $user) - { - $user_id = $user["active_id"]; - - $row = array(); - $row[] = trim($user["lastname"]) - ? $user["lastname"] - : $user["name"]; // anonymous - $row[] = $user["firstname"]; - $row[] = $user["login"]; // #10579 - - if ($this->object->canExportSurveyCode()) - { - $row[] = $user_id; - } - - $row[] = $this->object->getWorkingtimeForParticipant($user_id); - - if((bool)$user["finished"]) - { - $dt = new ilDateTime($user["finished_tstamp"], IL_CAL_UNIX); - $row[] = ($_POST["export_format"] == self::TYPE_XLS) - ? $dt - : ilDatePresentation::formatDate($dt); - } - else - { - $row[] = "-"; // :TODO: - } - - foreach($questions as $item) - { - $q_eval = $item[0]; - $q_res = $item[1]; - - $q_eval->addUserSpecificResults($row, $user_id, $q_res); - } - - $rows[] = $row; - } - - // #11179 - $surveyname = $this->object->getTitle()." ".$this->lng->txt("svy_eval_user")." ".date("Y-m-d"); - $surveyname = preg_replace("/\s/", "_", trim($surveyname)); - $surveyname = ilUtil::getASCIIFilename($surveyname); - - switch ($_POST["export_format"]) - { - case self::TYPE_XLS: - include_once "Services/Excel/classes/class.ilExcel.php"; - $excel = new ilExcel(); - $excel->addSheet($this->lng->txt("svy_eval_user")); - - foreach($rows as $row_idx => $row) - { - foreach($row as $col_idx => $col) - { - $excel->setCell($row_idx+1, $col_idx, $col); - } - if(!$row_idx) - { - $excel->setBold("A1:".$excel->getColumnCoord(sizeof($row)-1)."1"); - } - } - $excel->sendToClient($surveyname); - - case self::TYPE_SPSS: - $csv = ""; - $separator = ";"; - foreach ($rows as $csvrow) - { - $csvrow = str_replace("\n", " ", $this->processCSVRow($csvrow, TRUE, $separator)); - $csv .= join($csvrow, $separator) . "\n"; - } - ilUtil::deliverData($csv, "$surveyname.csv"); - exit(); - } - } - - /** - * Print the survey evaluation for a selected user - * - * Print the survey evaluation for a selected user - * - * @access private - */ - function evaluationuser() - { - $ilAccess = $this->access; - $ilToolbar = $this->toolbar; - - if(!$this->hasResultsAccess() && - $this->object->getMode() != ilObjSurvey::MODE_SELF_EVAL) - { - ilUtil::sendFailure($this->lng->txt("no_permission"), TRUE); - $this->ctrl->redirectByClass("ilObjSurveyGUI", "infoScreen"); - } - - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $ilToolbar->setFormAction($this->ctrl->getFormAction($this, "evaluationuser")); - - if($this->object->get360Mode()) - { - $appr_id = $this->getAppraiseeId(); - $this->addApprSelectionToToolbar(); - } - - $tabledata = null; - if(!$this->object->get360Mode() || $appr_id) - { - $modal_id = "svy_ev_exp"; - $modal = $this->buildExportModal($modal_id, "exportevaluationuser"); - - include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; - $button = ilLinkButton::getInstance(); - $button->setCaption("export"); - $button->setOnClick('$(\'#'.$modal_id.'\').modal(\'show\')'); - $ilToolbar->addButtonInstance($button); - - $ilToolbar->addSeparator(); - - include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; - $button = ilLinkButton::getInstance(); - $button->setCaption("print"); - $button->setOnClick("window.print(); return false;"); - $button->setOmitPreventDoubleSubmission(true); - $ilToolbar->addButtonInstance($button); - - $finished_ids = null; - if($appr_id) - { - $finished_ids = $this->object->getFinishedIdsForAppraiseeId($appr_id); - if(!sizeof($finished_ids)) - { - $finished_ids = array(-1); - } - } - - $data = $this->parseUserSpecificResults($finished_ids); - } - - /* - $this->tpl->addCss("./Modules/Survey/templates/default/survey_print.css", "print"); - $this->tpl->setCurrentBlock("generic_css"); - $this->tpl->setVariable("LOCATION_GENERIC_STYLESHEET", "./Modules/Survey/templates/default/evaluation_print.css"); - $this->tpl->setVariable("MEDIA_GENERIC_STYLESHEET", "print"); - $this->tpl->parseCurrentBlock(); - */ - - include_once "./Modules/Survey/classes/tables/class.ilSurveyResultsUserTableGUI.php"; - $table_gui = new ilSurveyResultsUserTableGUI($this, 'evaluationuser', $this->object->hasAnonymizedResults()); - $table_gui->setData($data); - $this->tpl->setContent($table_gui->getHTML().$modal); - } - - protected function filterSurveyParticipantsByAccess($a_finished_ids) - { - $all_participants = $this->object->getSurveyParticipants($a_finished_ids); - $participant_ids = []; - foreach($all_participants as $participant) - { - $participant_ids[] = $participant['usr_id']; - } - - - $filtered_participant_ids = $this->access->filterUserIdsByRbacOrPositionOfCurrentUser( - 'read_results', - 'access_results', - $this->object->getRefId(), - $participant_ids - ); - $participants = []; - foreach($all_participants as $username => $user_data) - { - if(!$user_data['usr_id']) - { - $participants[$username] = $user_data; - } - if(in_array($user_data['usr_id'], $filtered_participant_ids)) - { - $participants[$username] = $user_data; - } - } - return $participants; - } - - - - protected function parseUserSpecificResults(array $a_finished_ids = null) - { - $data = array(); - - $participants = $this->filterSurveyParticipantsByAccess($a_finished_ids); - - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - foreach($this->object->getSurveyQuestions() as $qdata) - { - $q_eval = SurveyQuestion::_instanciateQuestionEvaluation($qdata["question_id"], $a_finished_ids); - $q_res = $q_eval->getResults(); - - $question = is_array($q_res) - ? $q_res[0][1]->getQuestion() - : $q_res->getQuestion(); - - foreach($participants as $user) - { - $user_id = $user["active_id"]; - - $parsed_results = $q_eval->parseUserSpecificResults($q_res, $user_id); - - if(!array_key_exists($user_id, $data)) - { - $wt = $this->object->getWorkingtimeForParticipant($user_id); - - $finished = $user["finished"] - ? $user["finished_tstamp"] - : false; - - $data[$user_id] = array( - "username" => $user["sortname"], - "question" => $question->getTitle(), - "results" => $parsed_results, - "workingtime" => $wt, - "finished" => $finished, - "subitems" => array() - ); - } - else - { - $data[$user_id]["subitems"][] = array( - "username" => " ", - "question" => $question->getTitle(), - "results" => $parsed_results, - "workingtime" => null, - "finished" => null - ); - } - } - } - - return $data; - } - - /** - * Competence Evaluation - * - * @param - * @return - */ - function competenceEval() - { - $ilUser = $this->user; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilToolbar = $this->toolbar; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - $survey = $this->object; - - $ilTabs->activateSubtab("svy_eval_competences"); - $ilTabs->activateTab("svy_results"); - - $ilToolbar->setFormAction($this->ctrl->getFormAction($this, "competenceEval")); - - if($this->object->get360Mode() || $survey->getMode() == ilObjSurvey::MODE_SELF_EVAL) - { - $appr_id = $this->getAppraiseeId(); - $this->addApprSelectionToToolbar(); - } - - if ($appr_id == 0) - { - return; - } - - // evaluation modes - $eval_modes = array(); - - // get all competences of survey - include_once("./Modules/Survey/classes/class.ilSurveySkill.php"); - $sskill = new ilSurveySkill($survey); - $opts = $sskill->getAllAssignedSkillsAsOptions(); - $skills = array(); - foreach ($opts as $id => $o) - { - $idarr = explode(":", $id); - $skills[$id] = array("id" => $id, "title" => $o, "profiles" => array(), - "base_skill" => $idarr[0], "tref_id" => $idarr[1]); - } -//var_dump($opts); - - // get matching user competence profiles - // -> add gap analysis to profile - include_once("./Services/Skill/classes/class.ilSkillProfile.php"); - $profiles = ilSkillProfile::getProfilesOfUser($appr_id); - foreach ($profiles as $p) - { - $prof = new ilSkillProfile($p["id"]); - $prof_levels = $prof->getSkillLevels(); - foreach ($prof_levels as $pl) - { - if (isset($skills[$pl["base_skill_id"].":".$pl["tref_id"]])) - { - $skills[$pl["base_skill_id"].":".$pl["tref_id"]]["profiles"][] = - $p["id"]; - - $eval_modes["gap_".$p["id"]] = - $lng->txt("svy_gap_analysis").": ".$prof->getTitle(); - } - } - } -//var_dump($skills); -//var_dump($eval_modes); - - // if one competence does not match any profiles - // -> add "competences of survey" alternative - reset($skills); - foreach ($skills as $sk) - { - if (count($sk["profiles"]) == 0) - { - $eval_modes["skills_of_survey"] = $lng->txt("svy_all_survey_competences"); - } - } - - // final determination of current evaluation mode - $comp_eval_mode = $_GET["comp_eval_mode"]; - if ($_POST["comp_eval_mode"] != "") - { - $comp_eval_mode = $_POST["comp_eval_mode"]; - } - - if (!isset($eval_modes[$comp_eval_mode])) - { - reset($eval_modes); - $comp_eval_mode = key($eval_modes); - $ilCtrl->setParameter($this, "comp_eval_mode", $comp_eval_mode); - } - - $ilCtrl->saveParameter($this, "comp_eval_mode"); - - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $mode_sel = new ilSelectInputGUI($lng->txt("svy_analysis"), "comp_eval_mode"); - $mode_sel->setOptions($eval_modes); - $mode_sel->setValue($comp_eval_mode); - $ilToolbar->addInputItem($mode_sel, true); - - $ilToolbar->addFormButton($lng->txt("select"), "competenceEval"); - - if (substr($comp_eval_mode, 0, 4) == "gap_") - { - // gap analysis - $profile_id = (int) substr($comp_eval_mode, 4); - - include_once("./Services/Skill/classes/class.ilPersonalSkillsGUI.php"); - $pskills_gui = new ilPersonalSkillsGUI(); - $pskills_gui->setProfileId($profile_id); - $pskills_gui->setGapAnalysisActualStatusModePerObject($survey->getId(), $lng->txt("skmg_eval_type_1")); - if ($survey->getFinishedIdForAppraiseeIdAndRaterId($appr_id, $appr_id) > 0) - { - $sskill = new ilSurveySkill($survey); - $self_levels = array(); - foreach ($sskill->determineSkillLevelsForAppraisee($appr_id, true) as $sl) - { - $self_levels[$sl["base_skill_id"]][$sl["tref_id"]] = $sl["new_level_id"]; - } - $pskills_gui->setGapAnalysisSelfEvalLevels($self_levels); - } - $html = $pskills_gui->getGapAnalysisHTML($appr_id); - - $tpl->setContent($html); - } - else // must be all survey competences - { - include_once("./Services/Skill/classes/class.ilPersonalSkillsGUI.php"); - $pskills_gui = new ilPersonalSkillsGUI(); - #23743 - if($survey->getMode() != ilObjSurvey::MODE_SELF_EVAL) { - $pskills_gui->setGapAnalysisActualStatusModePerObject($survey->getId(), $lng->txt("skmg_eval_type_1")); - } - if ($survey->getFinishedIdForAppraiseeIdAndRaterId($appr_id, $appr_id) > 0) - { - $sskill = new ilSurveySkill($survey); - $self_levels = array(); - foreach ($sskill->determineSkillLevelsForAppraisee($appr_id, true) as $sl) - { - $self_levels[$sl["base_skill_id"]][$sl["tref_id"]] = $sl["new_level_id"]; - } - $pskills_gui->setGapAnalysisSelfEvalLevels($self_levels); - } - $sk = array(); - foreach ($skills as $skill) - { - $sk[] = array( - "base_skill_id" => (int) $skill["base_skill"], - "tref_id" => (int) $skill["tref_id"] - ); - } - $html = $pskills_gui->getGapAnalysisHTML($appr_id, $sk); - - $tpl->setContent($html); - } - - } - - /** - * Check if user can view results granted by rbac or positions - */ - protected function hasResultsAccess() - { - return $this->access->checkRbacOrPositionPermissionAccess('read_results', 'access_results', $this->object->getRefId()); - } +{ + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilTree + */ + protected $tree; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + const TYPE_XLS = "excel"; + const TYPE_SPSS = "csv"; + + const EXCEL_SUBTITLE = "DDDDDD"; + + public $object; + public $lng; + public $tpl; + public $ctrl; + public $appr_id = null; + + /** + * ilSurveyEvaluationGUI constructor + * + * The constructor takes possible arguments an creates an instance of the ilSurveyEvaluationGUI object. + * + * @param object $a_object Associated ilObjSurvey class + * @access public + */ + public function __construct($a_object) + { + global $DIC; + + $this->tabs = $DIC->tabs(); + $this->access = $DIC->access(); + $this->user = $DIC->user(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->tree = $DIC->repositoryTree(); + $this->toolbar = $DIC->toolbar(); + $this->ui = $DIC->ui(); + $lng = $DIC->language(); + $tpl = $DIC["tpl"]; + $ilCtrl = $DIC->ctrl(); + + $this->lng = $lng; + $this->tpl = $tpl; + $this->ctrl = $ilCtrl; + $this->object = $a_object; + $this->log = ilLoggerFactory::getLogger("svy"); + $this->array_panels = array(); + + if ($this->object->get360Mode() || $this->object->getMode() == ilObjSurvey::MODE_SELF_EVAL) { + $this->determineAppraiseeId(); + } + } + + /** + * execute command + */ + public function executeCommand() + { + include_once("./Services/Skill/classes/class.ilSkillManagementSettings.php"); + $skmg_set = new ilSkillManagementSettings(); + if ($this->object->getSkillService() && $skmg_set->isActivated()) { + $cmd = $this->ctrl->getCmd("competenceEval"); + } else { + $cmd = $this->ctrl->getCmd("evaluation"); + } + + $next_class = $this->ctrl->getNextClass($this); + + $cmd = $this->getCommand($cmd); + switch ($next_class) { + default: + $this->setEvalSubTabs(); + $ret =&$this->$cmd(); + break; + } + return $ret; + } + + public function getCommand($cmd) + { + return $cmd; + } + + /** + * Set the tabs for the evaluation output + * + * @access private + */ + public function setEvalSubtabs() + { + $ilTabs = $this->tabs; + $ilAccess = $this->access; + + include_once("./Services/Skill/classes/class.ilSkillManagementSettings.php"); + $skmg_set = new ilSkillManagementSettings(); + if ($this->object->getSkillService() && $skmg_set->isActivated()) { + $ilTabs->addSubTabTarget( + "svy_eval_competences", + $this->ctrl->getLinkTarget($this, "competenceEval"), + array("competenceEval") + ); + } + + $ilTabs->addSubTabTarget( + "svy_eval_cumulated", + $this->ctrl->getLinkTarget($this, "evaluation"), + array("evaluation", "checkEvaluationAccess") + ); + + $ilTabs->addSubTabTarget( + "svy_eval_detail", + $this->ctrl->getLinkTarget($this, "evaluationdetails"), + array("evaluationdetails") + ); + + if ($this->hasResultsAccess()) { + $ilTabs->addSubTabTarget( + "svy_eval_user", + $this->ctrl->getLinkTarget($this, "evaluationuser"), + array("evaluationuser") + ); + } + } + + + /** + * Set appraisee id + * + * @param int $a_val appraisee id + */ + public function setAppraiseeId($a_val) + { + $this->appr_id = $a_val; + } + + /** + * Get appraisee id + * + * @return int appraisee id + */ + public function getAppraiseeId() + { + return $this->appr_id; + } + + /** + * Determine appraisee id + */ + public function determineAppraiseeId() + { + $ilUser = $this->user; + $rbacsystem = $this->rbacsystem; + + $appr_id = ""; + + // always start with current user + if ($_REQUEST["appr_id"] == "") { + $req_appr_id = $ilUser->getId(); + } else { + $req_appr_id = (int) $_REQUEST["appr_id"]; + } + + // write access? allow selection + if ($req_appr_id > 0 && $this->object->get360Mode()) { + $all_appr = ($this->object->get360Results() == ilObjSurvey::RESULTS_360_ALL); + + $valid = array(); + foreach ($this->object->getAppraiseesData() as $item) { + if ($item["closed"] && + ($item["user_id"] == $ilUser->getId() || + $rbacsystem->checkAccess("write", $this->object->getRefId()) || + $all_appr)) { + $valid[] = $item["user_id"]; + } + } + if (in_array($req_appr_id, $valid)) { + $appr_id = $req_appr_id; + } else { + // current selection / user is not valid, use 1st valid instead + $appr_id = array_shift($valid); + } + } else { // SVY SELF EVALUATION MODE + $appr_id = $req_appr_id; + } + + $this->ctrl->setParameter($this, "appr_id", $appr_id); + $this->setAppraiseeId($appr_id); + } + + + /** + * Show the detailed evaluation + * + * Show the detailed evaluation + * + * @access private + */ + public function checkAnonymizedEvaluationAccess() + { + $ilUser = $this->user; + + if ($this->object->getAnonymize() == 1 && + $_SESSION["anon_evaluation_access"] == $_GET["ref_id"]) { + return true; + } + + include_once "Modules/Survey/classes/class.ilObjSurveyAccess.php"; + if (ilObjSurveyAccess::_hasEvaluationAccess(ilObject::_lookupObjId($_GET["ref_id"]), $ilUser->getId())) { + if ($this->object->getAnonymize() == 1) { + $_SESSION["anon_evaluation_access"] = $_GET["ref_id"]; + } + return true; + } + + if ($this->object->getAnonymize() == 1) { + // autocode + $surveycode = $this->object->getUserAccessCode($ilUser->getId()); + if ($this->object->isAnonymizedParticipant($surveycode)) { + $_SESSION["anon_evaluation_access"] = $_GET["ref_id"]; + return true; + } + + /* try to find code for current (registered) user from existing run + if($this->object->findCodeForUser($ilUser->getId())) + { + $_SESSION["anon_evaluation_access"] = $_GET["ref_id"]; + return true; + } + */ + + // code needed + $this->tpl->setVariable("TABS", ""); + $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.il_svy_svy_evaluation_checkaccess.html", "Modules/Survey"); + $this->tpl->setCurrentBlock("adm_content"); + $this->tpl->setVariable("AUTHENTICATION_NEEDED", $this->lng->txt("svy_check_evaluation_authentication_needed")); + $this->tpl->setVariable("FORM_ACTION", $this->ctrl->getFormAction($this, "checkEvaluationAccess")); + $this->tpl->setVariable("EVALUATION_CHECKACCESS_INTRODUCTION", $this->lng->txt("svy_check_evaluation_access_introduction")); + $this->tpl->setVariable("VALUE_CHECK", $this->lng->txt("ok")); + $this->tpl->setVariable("VALUE_CANCEL", $this->lng->txt("cancel")); + $this->tpl->setVariable("TEXT_SURVEY_CODE", $this->lng->txt("survey_code")); + $this->tpl->parseCurrentBlock(); + } + + $_SESSION["anon_evaluation_access"] = null; + return false; + } + + /** + * Checks the evaluation access after entering the survey access code + * + * Checks the evaluation access after entering the survey access code + * + * @access private + */ + public function checkEvaluationAccess() + { + $surveycode = $_POST["surveycode"]; + if ($this->object->isAnonymizedParticipant($surveycode)) { + $_SESSION["anon_evaluation_access"] = $_GET["ref_id"]; + $this->evaluation(); + } else { + ilUtil::sendFailure($this->lng->txt("svy_check_evaluation_wrong_key", true)); + $this->cancelEvaluationAccess(); + } + } + + /** + * Cancels the input of the survey access code for evaluation access + * + * Cancels the input of the survey access code for evaluation access + * + * @access private + */ + public function cancelEvaluationAccess() + { + $ilCtrl = $this->ctrl; + $tree = $this->tree; + $path = $tree->getPathFull($this->object->getRefID()); + $ilCtrl->setParameterByClass( + "ilrepositorygui", + "ref_id", + $path[count($path) - 2]["child"] + ); + $ilCtrl->redirectByClass("ilrepositorygui", "frameset"); + } + + /** + * Show the detailed evaluation + * + * Show the detailed evaluation + * + * @access private + */ + public function evaluationdetails() + { + $this->evaluation(1); + } + + public function exportCumulatedResults($details = 0) + { + $finished_ids = null; + if ($this->object->get360Mode()) { + $appr_id = $_REQUEST["appr_id"]; + if (!$appr_id) { + $this->ctrl->redirect($this, $details ? "evaluationdetails" : "evaluation"); + } + $finished_ids = $this->object->getFinishedIdsForAppraiseeId($appr_id); + if (!sizeof($finished_ids)) { + $finished_ids = array(-1); + } + } + + // titles + $title_row = array(); + $do_title = $do_label = true; + switch ($_POST['export_label']) { + case 'label_only': + $title_row[] = $this->lng->txt("label"); + $do_title = false; + break; + + case 'title_only': + $title_row[] = $this->lng->txt("title"); + $do_label = false; + break; + + default: + $title_row[] = $this->lng->txt("title"); + $title_row[] = $this->lng->txt("label"); + break; + } + $title_row[] = $this->lng->txt("question"); + $title_row[] = $this->lng->txt("question_type"); + $title_row[] = $this->lng->txt("users_answered"); + $title_row[] = $this->lng->txt("users_skipped"); + $title_row[] = $this->lng->txt("mode"); + $title_row[] = $this->lng->txt("mode_text"); + $title_row[] = $this->lng->txt("mode_nr_of_selections"); + $title_row[] = $this->lng->txt("median"); + $title_row[] = $this->lng->txt("arithmetic_mean"); + + // creating container + switch ($_POST["export_format"]) { + case self::TYPE_XLS: + include_once "Services/Excel/classes/class.ilExcel.php"; + $excel = new ilExcel(); + $excel->addSheet($this->lng->txt("svy_eval_cumulated")); + $excel->setCellArray(array($title_row), "A1"); + $excel->setBold("A1:" . $excel->getColumnCoord(sizeof($title_row)-1) . "1"); + break; + + case self::TYPE_SPSS: + $csvfile = array($title_row); + break; + } + + + // parse answer data in evaluation results + $ov_row = 2; + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + foreach ($this->object->getSurveyQuestions() as $qdata) { + $q_eval = SurveyQuestion::_instanciateQuestionEvaluation($qdata["question_id"], $finished_ids); + $q_res = $q_eval->getResults(); + $ov_rows = $q_eval->exportResults($q_res, $do_title, $do_label); + + switch ($_POST["export_format"]) { + case self::TYPE_XLS: + $excel->setActiveSheet(0); + foreach ($ov_rows as $row) { + foreach ($row as $col => $value) { + $excel->setCell($ov_row, $col, $value); + } + $ov_row++; + } + break; + + case self::TYPE_SPSS: + foreach ($ov_rows as $row) { + $csvfile[] = $row; + } + break; + } + + if ($details) { + switch ($_POST["export_format"]) { + case self::TYPE_XLS: + $this->exportResultsDetailsExcel($excel, $q_eval, $q_res, $do_title, $do_label); + break; + } + } + } + + // #11179 + $type = !$details + ? $this->lng->txt("svy_eval_cumulated") + : $this->lng->txt("svy_eval_detail"); + + $surveyname = $this->object->getTitle() . " " . $type . " " . date("Y-m-d"); + $surveyname = preg_replace("/\s/", "_", trim($surveyname)); + $surveyname = ilUtil::getASCIIFilename($surveyname); + + // send to client + switch ($_POST["export_format"]) { + case self::TYPE_XLS: + $excel->sendToClient($surveyname); + break; + + case self::TYPE_SPSS: + $csv = ""; + $separator = ";"; + foreach ($csvfile as $csvrow) { + $csvrow = $this->processCSVRow($csvrow, true, $separator); + $csv .= join($csvrow, $separator) . "\n"; + } + ilUtil::deliverData($csv, $surveyname . ".csv"); + exit(); + break; + } + } + + /** + * Export details (excel only) + * + * @param ilExcel $a_excel + * @param SurveyQuestionEvaluation $a_eval + * @param ilSurveyEvaluationResults|array $a_results + * @param bool $a_do_title + * @param bool|array $a_do_label + */ + protected function exportResultsDetailsExcel(ilExcel $a_excel, SurveyQuestionEvaluation $a_eval, $a_results, $a_do_title, $a_do_label) + { + $question_res = $a_results; + $matrix = false; + if (is_array($question_res)) { + $question_res = $question_res[0][1]; + $matrix = true; + } + $question = $question_res->getQuestion(); + + $a_excel->addSheet($question->getTitle()); + + + // question "overview" + + $kv = array(); + + if ($a_do_title) { + $kv[$this->lng->txt("title")] = $question->getTitle(); + } + if ($a_do_label) { + $kv[$this->lng->txt("label")] = $question->label; + } + + // question + $kv[$this->lng->txt("question")] = $question->getQuestiontext(); + + // question type + $kv[$this->lng->txt("question_type")] = SurveyQuestion::_getQuestionTypeName($question->getQuestionType()); + + // :TODO: present subtypes (hrz/vrt, mc/sc mtx, metric scale)? + + // answered and skipped users + $kv[$this->lng->txt("users_answered")] = (int) $question_res->getUsersAnswered(); + $kv[$this->lng->txt("users_skipped")] = (int) $question_res->getUsersSkipped(); // #0021671 + + $excel_row = 1; + + foreach ($kv as $key => $value) { + $a_excel->setCell($excel_row, 0, $key); + $a_excel->setCell($excel_row++, 1, $value); + } + + if (!$matrix) { + $this->parseResultsToExcel( + $a_excel, + $question_res, + $excel_row, + $a_eval->getExportGrid($a_results), + $a_eval->getTextAnswers($a_results) + ); + } else { + // question + $this->parseResultsToExcel( + $a_excel, + $question_res, + $excel_row, + null, + null, + false + ); + + $texts = $a_eval->getTextAnswers($a_results); + + // "rows" + foreach ($a_results as $row_results) { + $row_title = $row_results[0]; + + $a_excel->setCell($excel_row, 0, $this->lng->txt("row")); + $a_excel->setCell($excel_row++, 1, $row_title); + + $this->parseResultsToExcel( + $a_excel, + $row_results[1], + $excel_row, + $a_eval->getExportGrid($row_results[1]), + is_array($texts[$row_title]) + ? array(""=>$texts[$row_title]) + : null + ); + } + } + + // matrix question: overview #21438 + if ($matrix) { + $a_excel->setCell($excel_row++, 0, $this->lng->txt("overview")); + + // title row with variables + $counter = 0; + $cats = $question->getColumns(); + foreach ($cats->getCategories() as $cat) { + $a_excel->setColors($a_excel->getCoordByColumnAndRow(1 + $counter, $excel_row), ilSurveyEvaluationGUI::EXCEL_SUBTITLE); + $a_excel->setCell($excel_row, 1 + $counter, $cat->title); + $counter++; + } + $excel_row++; + + foreach ($a_results as $row_results) { + $row_title = $row_results[0]; + $counter = 0; + $a_excel->setCell($excel_row, 0, $row_title); + + $vars = $row_results[1]->getVariables(); + if ($vars) { + foreach ($vars as $var) { + $a_excel->setCell($excel_row, ++$counter, $var->abs); + } + } + $excel_row++; + } + } + + // 1st column is bold + $a_excel->setBold("A1:A" . $excel_row); + } + + protected function parseResultsToExcel(ilExcel $a_excel, ilSurveyEvaluationResults $a_results, &$a_excel_row, array $a_grid = null, array $a_text_answers = null, $a_include_mode = true) + { + $kv = array(); + + if ($a_include_mode) { + if ($a_results->getModeValue() !== null) { + // :TODO: + $kv[$this->lng->txt("mode")] = is_array($a_results->getModeValue()) + ? implode(", ", $a_results->getModeValue()) + : $a_results->getModeValue(); + + $kv[$this->lng->txt("mode_text")] = $a_results->getModeValueAsText(); + $kv[$this->lng->txt("mode_nr_of_selections")] = (int) $a_results->getModeNrOfSelections(); + } + + if ($a_results->getMedian() !== null) { + $kv[$this->lng->txt("median")] = $a_results->getMedianAsText(); + } + + if ($a_results->getMean() !== null) { + $kv[$this->lng->txt("arithmetic_mean")] = $a_results->getMean(); + } + } + + foreach ($kv as $key => $value) { + $a_excel->setCell($a_excel_row, 0, $key); + $a_excel->setCell($a_excel_row++, 1, $value); + } + + // grid + if ($a_grid) { + // header + $a_excel->setColors("B" . $a_excel_row . ":E" . $a_excel_row, ilSurveyEvaluationGUI::EXCEL_SUBTITLE); + $a_excel->setCell($a_excel_row, 0, $this->lng->txt("categories")); + foreach ($a_grid["cols"] as $col_idx => $col) { + $a_excel->setCell($a_excel_row, $col_idx+1, $col); + } + $a_excel_row++; + + // rows + foreach ($a_grid["rows"] as $cols) { + foreach ($cols as $col_idx => $col) { + $a_excel->setCell($a_excel_row, $col_idx+1, $col); + } + $a_excel_row++; + } + } + + // text answers + if ($a_text_answers) { + // "given_answers" ? + $a_excel->setCell($a_excel_row, 0, $this->lng->txt("freetext_answers")); + + // mc/sc + if (!is_array($a_text_answers[""])) { + $a_excel->setColors("B" . $a_excel_row . ":C" . $a_excel_row, ilSurveyEvaluationGUI::EXCEL_SUBTITLE); + $a_excel->setCell($a_excel_row, 1, $this->lng->txt("title")); + $a_excel->setCell($a_excel_row++, 2, $this->lng->txt("answer")); + } + // mtx (row), txt + else { + $a_excel->setColors("B" . $a_excel_row . ":B" . $a_excel_row, ilSurveyEvaluationGUI::EXCEL_SUBTITLE); + $a_excel->setCell($a_excel_row++, 1, $this->lng->txt("answer")); + } + + foreach ($a_text_answers as $var => $items) { + foreach ($items as $item) { + if (!is_array($a_text_answers[""])) { + $a_excel->setCell($a_excel_row, 1, $var); + $a_excel->setCell($a_excel_row++, 2, $item); + } else { + $a_excel->setCell($a_excel_row++, 1, $item); + } + } + } + } + } + + public function exportData() + { + if (strlen($_POST["export_format"])) { + $this->exportCumulatedResults(0); + return; + } else { + $this->ctrl->redirect($this, 'evaluation'); + } + } + + public function exportDetailData() + { + if (strlen($_POST["export_format"])) { + $this->exportCumulatedResults(1); + return; + } else { + $this->ctrl->redirect($this, 'evaluation'); + } + } + + public function printEvaluation() + { + ilUtil::sendInfo($this->lng->txt('use_browser_print_function'), true); + $this->ctrl->redirect($this, 'evaluation'); + } + + protected function buildExportModal($a_id, $a_cmd) + { + $tpl = $this->tpl; + + $form_id = "svymdfrm"; + + // hide modal on form submit + $tpl->addOnLoadCode('$("#form_' . $form_id . '").submit(function() { $("#' . $a_id . '").modal("hide"); });'); + + include_once "Services/UIComponent/Modal/classes/class.ilModalGUI.php"; + $modal = ilModalGUI::getInstance(); + $modal->setId($a_id); + $modal->setHeading(($this->lng->txt("svy_export_format"))); + + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $form = new ilPropertyFormGUI(); + $form->setId($form_id); + $form->setFormAction($this->ctrl->getFormAction($this, $a_cmd)); + + $format = new ilSelectInputGUI($this->lng->txt("filetype"), "export_format"); + $format->setOptions(array( + self::TYPE_XLS => $this->lng->txt('exp_type_excel'), + self::TYPE_SPSS => $this->lng->txt('exp_type_csv') + )); + $form->addItem($format, true); + + $label = new ilSelectInputGUI($this->lng->txt("title"), "export_label"); + $label->setOptions(array( + 'label_only' => $this->lng->txt('export_label_only'), + 'title_only' => $this->lng->txt('export_title_only'), + 'title_label'=> $this->lng->txt('export_title_label') + )); + $form->addItem($label); + + $form->addCommandButton($a_cmd, $this->lng->txt("export")); + $form->setPreventDoubleSubmission(false); + + $modal->setBody($form->getHTML()); + + return $modal->getHTML(); + } + + public function evaluation($details = 0) + { + $rbacsystem = $this->rbacsystem; + $ilToolbar = $this->toolbar; + $tree = $this->tree; + $ui = $this->ui; + + $ui_factory = $ui->factory(); + $ui_renderer = $ui->renderer(); + + // auth + if (!$this->hasResultsAccess()) { + if (!$this->access->checkAccess('read', '', $this->object->getRefId())) { + ilUtil::sendFailure($this->lng->txt("permission_denied")); + return; + } + + switch ($this->object->getEvaluationAccess()) { + case ilObjSurvey::EVALUATION_ACCESS_OFF: + ilUtil::sendFailure($this->lng->txt("permission_denied")); + return; + + case ilObjSurvey::EVALUATION_ACCESS_ALL: + case ilObjSurvey::EVALUATION_ACCESS_PARTICIPANTS: + if (!$this->checkAnonymizedEvaluationAccess()) { + ilUtil::sendFailure($this->lng->txt("permission_denied")); + return; + } + break; + } + } + + $ilToolbar->setFormAction($this->ctrl->getFormAction($this)); + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + + $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.il_svy_svy_evaluation.html", "Modules/Survey"); + + if ($this->object->get360Mode()) { + $appr_id = $this->getAppraiseeId(); + $this->addApprSelectionToToolbar(); + } + + $results = array(); + if (!$this->object->get360Mode() || $appr_id) { + if ($details) { + $captions = new ilSelectInputGUI($this->lng->txt("svy_eval_captions"), "cp"); + $captions->setOptions(array( + "ap" => $this->lng->txt("svy_eval_captions_abs_perc"), + "a" => $this->lng->txt("svy_eval_captions_abs"), + "p" => $this->lng->txt("svy_eval_captions_perc") + )); + $captions->setValue($_POST["cp"]); + $ilToolbar->addInputItem($captions, true); + + $view = new ilSelectInputGUI($this->lng->txt("svy_eval_view"), "vw"); + $view->setOptions(array( + "tc" => $this->lng->txt("svy_eval_view_tables_charts"), + "t" => $this->lng->txt("svy_eval_view_tables"), + "c" => $this->lng->txt("svy_eval_view_charts") + )); + $view->setValue($_POST["vw"]); + $ilToolbar->addInputItem($view, true); + + include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; + $button = ilSubmitButton::getInstance(); + $button->setCaption("ok"); + $button->setCommand("evaluationdetails"); + $button->setOmitPreventDoubleSubmission(true); + $ilToolbar->addButtonInstance($button); + + $ilToolbar->addSeparator(); + + //templates: results, table of contents + $dtmpl = new ilTemplate("tpl.il_svy_svy_results_details.html", true, true, "Modules/Survey"); + $toc_tpl = new ilTemplate("tpl.svy_results_table_contents.html", true, true, "Modules/Survey"); + $this->lng->loadLanguageModule("content"); + $toc_tpl->setVariable("TITLE_TOC", $this->lng->txt('cont_toc')); + } + + $modal_id = "svy_ev_exp"; + $modal = $this->buildExportModal($modal_id, $details + ? 'exportDetailData' + : 'exportData'); + + include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; + $button = ilLinkButton::getInstance(); + $button->setCaption("export"); + $button->setOnClick('$(\'#' . $modal_id . '\').modal(\'show\')'); + $ilToolbar->addButtonInstance($button); + + $ilToolbar->addSeparator(); + + include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; + $button = ilLinkButton::getInstance(); + $button->setCaption("print"); + $button->setOnClick("if(il.Accordion) { il.Accordion.preparePrint(); } window.print(); return false;"); + $button->setOmitPreventDoubleSubmission(true); + $ilToolbar->addButtonInstance($button); + + $finished_ids = null; + if ($appr_id) { + $finished_ids = $this->object->getFinishedIdsForAppraiseeId($appr_id); + if (!sizeof($finished_ids)) { + $finished_ids = array(-1); + } + } + + $details_figure = $_POST["cp"] + ? $_POST["cp"] + : "ap"; + $details_view = $_POST["vw"] + ? $_POST["vw"] + : "tc"; + + // @todo + // filter finished ids + $finished_ids2 = $this->access->filterUserIdsByRbacOrPositionOfCurrentUser( + 'read_results', + 'access_results', + $this->object->getRefId(), + (array) $finished_ids + ); + + // parse answer data in evaluation results + include_once("./Services/UIComponent/NestedList/classes/class.ilNestedList.php"); + $list = new ilNestedList(); + + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + foreach ($this->object->getSurveyQuestions() as $qdata) { + $q_eval = SurveyQuestion::_instanciateQuestionEvaluation($qdata["question_id"], $finished_ids); + $q_res = $q_eval->getResults(); + $results[] = $q_res; + + if ($details) { + //$this->renderDetails($details_view, $details_figure, $dtmpl, $qdata, $q_eval, $q_res); + $this->renderDetails($details_view, $details_figure, $qdata, $q_eval, $q_res); + + // TABLE OF CONTENTS + if ($qdata["questionblock_id"] && + $qdata["questionblock_id"] != $this->last_questionblock_id) { + $qblock = ilObjSurvey::_getQuestionblock($qdata["questionblock_id"]); + if ($qblock["show_blocktitle"]) { + $list->addListNode($qdata["questionblock_title"], "q" . $qdata["questionblock_id"]); + } + $this->last_questionblock_id = $qdata["questionblock_id"]; + } + $anchor_id = "svyrdq" . $qdata["question_id"]; + $list->addListNode("" . $qdata["title"] . "", $qdata["question_id"], $qdata["questionblock_id"] ? + "q" . $qdata["questionblock_id"] : 0); + } + } + + if ($details) { + $list->setListClass("il_Explorer"); + $toc_tpl->setVariable("LIST", $list->getHTML()); + + //TABLE OF CONTENTS + $panel_toc = $ui_factory->panel()->standard("", $ui_factory->legacy($toc_tpl->get())); + $render_toc = $ui_renderer->render($panel_toc); + $dtmpl->setVariable("PANEL_TOC", $render_toc); + + //REPORT + $report_title = ""; + $panel_report = $ui_factory->panel()->report($report_title, $this->array_panels); + $render_report = $ui_renderer->render($panel_report); + $dtmpl->setVariable("PANEL_REPORT", $render_report); + + //print the main template + $this->tpl->setVariable('DETAIL', $dtmpl->get()); + } + } + + $this->tpl->setVariable('MODAL', $modal); + if (!$details) { + include_once "./Modules/Survey/classes/tables/class.ilSurveyResultsCumulatedTableGUI.php"; + $table_gui = new ilSurveyResultsCumulatedTableGUI($this, $details ? 'evaluationdetails' : 'evaluation', $results); + $this->tpl->setVariable('CUMULATED', $table_gui->getHTML()); + } + unset($dtmpl); + unset($table_gui); + unset($modal); + + + // print header + + $path = ""; + $path_full = $tree->getPathFull($this->object->getRefId()); + foreach ($path_full as $data) { + $path .= " » "; + $path .= $data['title']; + } + + ilDatePresentation::setUseRelativeDates(false); + include_once "Services/Link/classes/class.ilLink.php"; + + $props = array( + $this->lng->txt("link") => ilLink::_getStaticLink($this->object->getRefId()), + $this->lng->txt("path") => $path, + $this->lng->txt("svy_results") => !$details + ? $this->lng->txt("svy_eval_cumulated") + : $this->lng->txt("svy_eval_detail"), + $this->lng->txt("date") => ilDatePresentation::formatDate(new ilDateTime(time(), IL_CAL_UNIX)), + ); + + $this->tpl->setCurrentBlock("print_header_bl"); + foreach ($props as $key => $value) { + $this->tpl->setVariable("HEADER_PROP_KEY", $key); + $this->tpl->setVariable("HEADER_PROP_VALUE", $value); + $this->tpl->parseCurrentBlock(); + } + + // $this->tpl->addCss("./Modules/Survey/templates/default/survey_print.css", "print"); + } + + /** + * Render details + * + * @param string $a_details_parts + * @param string $a_details_figure + * @param___ ilTemplate $a_tpl + * @param array $a_qdata + * @param SurveyQuestionEvaluation $a_eval + * @param ilSurveyEvaluationResults|array $a_results + */ + //protected function renderDetails($a_details_parts, $a_details_figure, ilTemplate $a_tpl, array $a_qdata, SurveyQuestionEvaluation $a_eval, $a_results) + protected function renderDetails($a_details_parts, $a_details_figure, array $a_qdata, SurveyQuestionEvaluation $a_eval, $a_results) + { + $ui_factory = $this->ui->factory(); + $a_tpl = new ilTemplate("tpl.svy_results_details_panel.html", true, true, "Modules/Survey"); + + $question_res = $a_results; + $matrix = false; + if (is_array($question_res)) { + $question_res = $question_res[0][1]; + $matrix = true; + } + $question = $question_res->getQuestion(); + + // question "overview" + + // :TODO: present subtypes (hrz/vrt, mc/sc mtx)? + + $a_tpl->setVariable("QTYPE", SurveyQuestion::_getQuestionTypeName($question->getQuestionType())); + + $kv = array(); + $kv["users_answered"] = $question_res->getUsersAnswered(); + $kv["users_skipped"] = $question_res->getUsersSkipped(); + + if (!$matrix) { + if ($question_res->getModeValue() !== null) { + $kv["mode"] = wordwrap($question_res->getModeValueAsText(), 50, "
"); + $kv["mode_nr_of_selections"] = $question_res->getModeNrOfSelections(); + } + if ($question_res->getMedian() !== null) { + $kv["median"] = $question_res->getMedianAsText(); + } + if ($question_res->getMean() !== null) { + $kv["arithmetic_mean"] = $question_res->getMean(); + } + } + + $svy_type_title = SurveyQuestion::_getQuestionTypeName($question->getQuestionType()); + $qst_title = $question->getTitle(); + $svy_text = nl2br($question->getQuestiontext()); + $card_table_tpl = new ilTemplate("tpl.svy_results_details_card.html", true, true, "Modules/Survey"); + foreach ($kv as $key => $value) { + $card_table_tpl->setCurrentBlock("question_statistics_card"); + $card_table_tpl->setVariable("QUESTION_STATISTIC_KEY", $this->lng->txt($key)); + $card_table_tpl->setVariable("QUESTION_STATISTIC_VALUE", $value); + $card_table_tpl->parseCurrentBlock(); + } + //anchor in title. Used in TOC + $anchor_id = "svyrdq" . $question->getId(); + $title = "$qst_title"; + $panel_qst_card = $ui_factory->panel()->sub($title, $ui_factory->legacy($svy_text)) + ->withCard($ui_factory->card()->standard($svy_type_title)->withSections(array($ui_factory->legacy($card_table_tpl->get())))); + array_push($this->array_panels, $panel_qst_card); + + // grid + if ($a_details_parts == "t" || + $a_details_parts == "tc") { + $grid = $a_eval->getGrid( + $a_results, + ($a_details_figure == "ap" || $a_details_figure == "a"), + ($a_details_figure == "ap" || $a_details_figure == "p") + ); + if ($grid) { + foreach ($grid["cols"] as $col) { + $a_tpl->setCurrentBlock("grid_col_header_bl"); + $a_tpl->setVariable("COL_HEADER", $col); + $a_tpl->parseCurrentBlock(); + } + foreach ($grid["rows"] as $cols) { + foreach ($cols as $idx => $col) { + if ($idx > 0) { + $a_tpl->touchBlock("grid_col_nowrap_bl"); + } + + $a_tpl->setCurrentBlock("grid_col_bl"); + $a_tpl->setVariable("COL_CAPTION", trim($col)); + $a_tpl->parseCurrentBlock(); + } + + $a_tpl->touchBlock("grid_row_bl"); + } + } + } + + // text answers + $texts = $a_eval->getTextAnswers($a_results); + if ($texts) { + if (array_key_exists("", $texts)) { + $a_tpl->setVariable("TEXT_HEADING", $this->lng->txt("given_answers")); + foreach ($texts[""] as $item) { + $a_tpl->setCurrentBlock("text_direct_item_bl"); + $a_tpl->setVariable("TEXT_DIRECT", nl2br($item)); + $a_tpl->parseCurrentBlock(); + } + } else { + include_once "Services/Accordion/classes/class.ilAccordionGUI.php"; + $acc = new ilAccordionGUI(); + $acc->setId("svyevaltxt" . $question->getId()); + + $a_tpl->setVariable("TEXT_HEADING", $this->lng->txt("freetext_answers")); + + foreach ($texts as $var => $items) { + $list = array("
    "); + foreach ($items as $item) { + $list[] = "
  • " . nl2br($item) . "
  • "; + } + $list[] = "
"; + $acc->addItem($var, implode("\n", $list)); + } + + $a_tpl->setVariable("TEXT_ACC", $acc->getHTML()); + } + } + + // chart + if ($a_details_parts == "c" || + $a_details_parts == "tc") { + $chart = $a_eval->getChart($a_results); + if ($chart) { + if (is_array($chart)) { + // legend + if (is_array($chart[1])) { + foreach ($chart[1] as $legend_item) { + $r = hexdec(substr($legend_item[1], 1, 2)); + $g = hexdec(substr($legend_item[1], 3, 2)); + $b = hexdec(substr($legend_item[1], 5, 2)); + + $a_tpl->setCurrentBlock("legend_bl"); + $a_tpl->setVariable("LEGEND_CAPTION", $legend_item[0]); + $a_tpl->setVariable("LEGEND_COLOR", $legend_item[1]); + $a_tpl->setVariable("LEGEND_COLOR_SVG", $r . "," . $g . "," . $b); + $a_tpl->parseCurrentBlock(); + } + } + + $chart = $chart[0]; + } + $a_tpl->setVariable("CHART", $chart); + } + } + $panel = $ui_factory->panel()->sub("", $ui_factory->legacy($a_tpl->get())); + array_push($this->array_panels, $panel); + } + + /** + * Add appraisee selection to toolbar + * + * @param + * @return + */ + public function addApprSelectionToToolbar() + { + $ilToolbar = $this->toolbar; + $rbacsystem = $this->rbacsystem; + + $svy_mode = $this->object->getMode(); + if ($svy_mode == ilObjSurvey::MODE_360 || $svy_mode == ilObjSurvey::MODE_SELF_EVAL) { + $appr_id = $this->getAppraiseeId(); + + $options = array(); + if (!$appr_id) { + $options[""] = $this->lng->txt("please_select"); + } + + $no_appr = true; + if ($this->object->get360Mode()) { + foreach ($this->object->getAppraiseesData() as $item) { + if ($item["closed"]) { + $options[$item["user_id"]] = $item["login"]; + $no_appr = false; + } + } + } else { //self evaluation mode + foreach ($this->object->getSurveyParticipants() as $item) { + $options[ilObjUser::_lookupId($item['login'])] = $item['login']; + $no_appr = false; + } + } + + if (!$no_appr) { + if ($rbacsystem->checkAccess("write", $this->object->getRefId()) || + $this->object->get360Results() == ilObjSurvey::RESULTS_360_ALL || + $this->object->getSelfEvaluationResults() == ilObjSurvey::RESULTS_SELF_EVAL_ALL) { + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $appr = new ilSelectInputGUI($this->lng->txt("svy_participant"), "appr_id"); + $appr->setOptions($options); + $appr->setValue($this->getAppraiseeId()); + $ilToolbar->addInputItem($appr, true); + + include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; + $button = ilSubmitButton::getInstance(); + $button->setCaption("survey_360_select_appraisee"); + $button->setCommand($this->ctrl->getCmd()); + $ilToolbar->addButtonInstance($button); + + if ($appr_id) { + $ilToolbar->addSeparator(); + } + } + } else { + ilUtil::sendFailure($this->lng->txt("survey_360_no_closed_appraisees")); + } + } + } + + /** + * Processes an array as a CSV row and converts the array values to correct CSV + * values. The "converted" array is returned + * + * @param array $row The array containing the values for a CSV row + * @param string $quoteAll Indicates to quote every value (=TRUE) or only values containing quotes and separators (=FALSE, default) + * @param string $separator The value separator in the CSV row (used for quoting) (; = default) + * @return array The converted array ready for CSV use + * @access public + */ + public function processCSVRow($row, $quoteAll = false, $separator = ";") + { + $resultarray = array(); + foreach ($row as $rowindex => $entry) { + if (is_array($entry)) { + $entry = implode("/", $entry); + } + $surround = false; + if ($quoteAll) { + $surround = true; + } + if (strpos($entry, "\"") !== false) { + $entry = str_replace("\"", "\"\"", $entry); + $surround = true; + } + if (strpos($entry, $separator) !== false) { + $surround = true; + } + // replace all CR LF with LF (for Excel for Windows compatibility + $entry = str_replace(chr(13) . chr(10), chr(10), $entry); + if ($surround) { + $resultarray[$rowindex] = utf8_decode("\"" . $entry . "\""); + } else { + $resultarray[$rowindex] = utf8_decode($entry); + } + } + return $resultarray; + } + + + public function exportEvaluationUser() + { + // build title row(s) + + $title_row = $title_row2 = array(); + $title_row[] = $this->lng->txt("lastname"); // #12756 + $title_row[] = $this->lng->txt("firstname"); + $title_row[] = $this->lng->txt("login"); + $title_row[] = $this->lng->txt('workingtime'); // #13622 + $title_row[] = $this->lng->txt('survey_results_finished'); + $title_row2[] = ""; + $title_row2[] = ""; + $title_row2[] = ""; + $title_row2[] = ""; + $title_row2[] = ""; + if ($this->object->canExportSurveyCode()) { + $title_row[] = $this->lng->txt("codes"); + $title_row2[] = ""; + } + + $questions = array(); + + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + foreach ($this->object->getSurveyQuestions() as $qdata) { + $q_eval = SurveyQuestion::_instanciateQuestionEvaluation($qdata["question_id"], $finished_ids); + $q_res = $q_eval->getResults(); + + $questions[$qdata["question_id"]] = array($q_eval, $q_res); + + $question = is_array($q_res) + ? $q_res[0][1]->getQuestion() + : $q_res->getQuestion(); + + $do_title = $do_label = true; + switch ($_POST['export_label']) { + case "label_only": + $title_row[] = $question->label; + $title_row2[] = ""; + $do_title = false; + break; + + case "title_only": + $title_row[] = $question->getTitle(); + $title_row2[] = ""; + $do_label = false; + break; + + default: + $title_row[] = $question->getTitle(); + $title_row2[] = $question->label; + break; + } + + $q_eval->getUserSpecificVariableTitles($title_row, $title_row2, $do_title, $do_label); + } + + $rows = array(); + + // add title row(s) + $rows[] = $title_row; + if (implode("", $title_row2)) { + $rows[] = $title_row2; + } + + // #13620 + ilDatePresentation::setUseRelativeDates(false); + + $finished_ids = null; + if ($this->object->get360Mode()) { + $appr_id = $_REQUEST["appr_id"]; + if (!$appr_id) { + $this->ctrl->redirect($this, "evaluationuser"); + } + $finished_ids = $this->object->getFinishedIdsForAppraiseeId($appr_id); + if (!sizeof($finished_ids)) { + $finished_ids = array(-1); + } + } + + //$participants = $this->object->getSurveyParticipants($finished_ids); + $participants = $this->filterSurveyParticipantsByAccess($finished_ids); + + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + foreach ($participants as $user) { + $user_id = $user["active_id"]; + + $row = array(); + $row[] = trim($user["lastname"]) + ? $user["lastname"] + : $user["name"]; // anonymous + $row[] = $user["firstname"]; + $row[] = $user["login"]; // #10579 + + if ($this->object->canExportSurveyCode()) { + $row[] = $user_id; + } + + $row[] = $this->object->getWorkingtimeForParticipant($user_id); + + if ((bool) $user["finished"]) { + $dt = new ilDateTime($user["finished_tstamp"], IL_CAL_UNIX); + $row[] = ($_POST["export_format"] == self::TYPE_XLS) + ? $dt + : ilDatePresentation::formatDate($dt); + } else { + $row[] = "-"; // :TODO: + } + + foreach ($questions as $item) { + $q_eval = $item[0]; + $q_res = $item[1]; + + $q_eval->addUserSpecificResults($row, $user_id, $q_res); + } + + $rows[] = $row; + } + + // #11179 + $surveyname = $this->object->getTitle() . " " . $this->lng->txt("svy_eval_user") . " " . date("Y-m-d"); + $surveyname = preg_replace("/\s/", "_", trim($surveyname)); + $surveyname = ilUtil::getASCIIFilename($surveyname); + + switch ($_POST["export_format"]) { + case self::TYPE_XLS: + include_once "Services/Excel/classes/class.ilExcel.php"; + $excel = new ilExcel(); + $excel->addSheet($this->lng->txt("svy_eval_user")); + + foreach ($rows as $row_idx => $row) { + foreach ($row as $col_idx => $col) { + $excel->setCell($row_idx+1, $col_idx, $col); + } + if (!$row_idx) { + $excel->setBold("A1:" . $excel->getColumnCoord(sizeof($row)-1) . "1"); + } + } + $excel->sendToClient($surveyname); + + // no break + case self::TYPE_SPSS: + $csv = ""; + $separator = ";"; + foreach ($rows as $csvrow) { + $csvrow = str_replace("\n", " ", $this->processCSVRow($csvrow, true, $separator)); + $csv .= join($csvrow, $separator) . "\n"; + } + ilUtil::deliverData($csv, "$surveyname.csv"); + exit(); + } + } + + /** + * Print the survey evaluation for a selected user + * + * Print the survey evaluation for a selected user + * + * @access private + */ + public function evaluationuser() + { + $ilAccess = $this->access; + $ilToolbar = $this->toolbar; + + if (!$this->hasResultsAccess() && + $this->object->getMode() != ilObjSurvey::MODE_SELF_EVAL) { + ilUtil::sendFailure($this->lng->txt("no_permission"), true); + $this->ctrl->redirectByClass("ilObjSurveyGUI", "infoScreen"); + } + + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $ilToolbar->setFormAction($this->ctrl->getFormAction($this, "evaluationuser")); + + if ($this->object->get360Mode()) { + $appr_id = $this->getAppraiseeId(); + $this->addApprSelectionToToolbar(); + } + + $tabledata = null; + if (!$this->object->get360Mode() || $appr_id) { + $modal_id = "svy_ev_exp"; + $modal = $this->buildExportModal($modal_id, "exportevaluationuser"); + + include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; + $button = ilLinkButton::getInstance(); + $button->setCaption("export"); + $button->setOnClick('$(\'#' . $modal_id . '\').modal(\'show\')'); + $ilToolbar->addButtonInstance($button); + + $ilToolbar->addSeparator(); + + include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; + $button = ilLinkButton::getInstance(); + $button->setCaption("print"); + $button->setOnClick("window.print(); return false;"); + $button->setOmitPreventDoubleSubmission(true); + $ilToolbar->addButtonInstance($button); + + $finished_ids = null; + if ($appr_id) { + $finished_ids = $this->object->getFinishedIdsForAppraiseeId($appr_id); + if (!sizeof($finished_ids)) { + $finished_ids = array(-1); + } + } + + $data = $this->parseUserSpecificResults($finished_ids); + } + + /* + $this->tpl->addCss("./Modules/Survey/templates/default/survey_print.css", "print"); + $this->tpl->setCurrentBlock("generic_css"); + $this->tpl->setVariable("LOCATION_GENERIC_STYLESHEET", "./Modules/Survey/templates/default/evaluation_print.css"); + $this->tpl->setVariable("MEDIA_GENERIC_STYLESHEET", "print"); + $this->tpl->parseCurrentBlock(); + */ + + include_once "./Modules/Survey/classes/tables/class.ilSurveyResultsUserTableGUI.php"; + $table_gui = new ilSurveyResultsUserTableGUI($this, 'evaluationuser', $this->object->hasAnonymizedResults()); + $table_gui->setData($data); + $this->tpl->setContent($table_gui->getHTML() . $modal); + } + + protected function filterSurveyParticipantsByAccess($a_finished_ids) + { + $all_participants = $this->object->getSurveyParticipants($a_finished_ids); + $participant_ids = []; + foreach ($all_participants as $participant) { + $participant_ids[] = $participant['usr_id']; + } + + + $filtered_participant_ids = $this->access->filterUserIdsByRbacOrPositionOfCurrentUser( + 'read_results', + 'access_results', + $this->object->getRefId(), + $participant_ids + ); + $participants = []; + foreach ($all_participants as $username => $user_data) { + if (!$user_data['usr_id']) { + $participants[$username] = $user_data; + } + if (in_array($user_data['usr_id'], $filtered_participant_ids)) { + $participants[$username] = $user_data; + } + } + return $participants; + } + + + + protected function parseUserSpecificResults(array $a_finished_ids = null) + { + $data = array(); + + $participants = $this->filterSurveyParticipantsByAccess($a_finished_ids); + + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + foreach ($this->object->getSurveyQuestions() as $qdata) { + $q_eval = SurveyQuestion::_instanciateQuestionEvaluation($qdata["question_id"], $a_finished_ids); + $q_res = $q_eval->getResults(); + + $question = is_array($q_res) + ? $q_res[0][1]->getQuestion() + : $q_res->getQuestion(); + + foreach ($participants as $user) { + $user_id = $user["active_id"]; + + $parsed_results = $q_eval->parseUserSpecificResults($q_res, $user_id); + + if (!array_key_exists($user_id, $data)) { + $wt = $this->object->getWorkingtimeForParticipant($user_id); + + $finished = $user["finished"] + ? $user["finished_tstamp"] + : false; + + $data[$user_id] = array( + "username" => $user["sortname"], + "question" => $question->getTitle(), + "results" => $parsed_results, + "workingtime" => $wt, + "finished" => $finished, + "subitems" => array() + ); + } else { + $data[$user_id]["subitems"][] = array( + "username" => " ", + "question" => $question->getTitle(), + "results" => $parsed_results, + "workingtime" => null, + "finished" => null + ); + } + } + } + + return $data; + } + + /** + * Competence Evaluation + * + * @param + * @return + */ + public function competenceEval() + { + $ilUser = $this->user; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilToolbar = $this->toolbar; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + $survey = $this->object; + + $ilTabs->activateSubtab("svy_eval_competences"); + $ilTabs->activateTab("svy_results"); + + $ilToolbar->setFormAction($this->ctrl->getFormAction($this, "competenceEval")); + + if ($this->object->get360Mode() || $survey->getMode() == ilObjSurvey::MODE_SELF_EVAL) { + $appr_id = $this->getAppraiseeId(); + $this->addApprSelectionToToolbar(); + } + + if ($appr_id == 0) { + return; + } + + // evaluation modes + $eval_modes = array(); + + // get all competences of survey + include_once("./Modules/Survey/classes/class.ilSurveySkill.php"); + $sskill = new ilSurveySkill($survey); + $opts = $sskill->getAllAssignedSkillsAsOptions(); + $skills = array(); + foreach ($opts as $id => $o) { + $idarr = explode(":", $id); + $skills[$id] = array("id" => $id, "title" => $o, "profiles" => array(), + "base_skill" => $idarr[0], "tref_id" => $idarr[1]); + } + //var_dump($opts); + + // get matching user competence profiles + // -> add gap analysis to profile + include_once("./Services/Skill/classes/class.ilSkillProfile.php"); + $profiles = ilSkillProfile::getProfilesOfUser($appr_id); + foreach ($profiles as $p) { + $prof = new ilSkillProfile($p["id"]); + $prof_levels = $prof->getSkillLevels(); + foreach ($prof_levels as $pl) { + if (isset($skills[$pl["base_skill_id"] . ":" . $pl["tref_id"]])) { + $skills[$pl["base_skill_id"] . ":" . $pl["tref_id"]]["profiles"][] = + $p["id"]; + + $eval_modes["gap_" . $p["id"]] = + $lng->txt("svy_gap_analysis") . ": " . $prof->getTitle(); + } + } + } + //var_dump($skills); + //var_dump($eval_modes); + + // if one competence does not match any profiles + // -> add "competences of survey" alternative + reset($skills); + foreach ($skills as $sk) { + if (count($sk["profiles"]) == 0) { + $eval_modes["skills_of_survey"] = $lng->txt("svy_all_survey_competences"); + } + } + + // final determination of current evaluation mode + $comp_eval_mode = $_GET["comp_eval_mode"]; + if ($_POST["comp_eval_mode"] != "") { + $comp_eval_mode = $_POST["comp_eval_mode"]; + } + + if (!isset($eval_modes[$comp_eval_mode])) { + reset($eval_modes); + $comp_eval_mode = key($eval_modes); + $ilCtrl->setParameter($this, "comp_eval_mode", $comp_eval_mode); + } + + $ilCtrl->saveParameter($this, "comp_eval_mode"); + + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $mode_sel = new ilSelectInputGUI($lng->txt("svy_analysis"), "comp_eval_mode"); + $mode_sel->setOptions($eval_modes); + $mode_sel->setValue($comp_eval_mode); + $ilToolbar->addInputItem($mode_sel, true); + + $ilToolbar->addFormButton($lng->txt("select"), "competenceEval"); + + if (substr($comp_eval_mode, 0, 4) == "gap_") { + // gap analysis + $profile_id = (int) substr($comp_eval_mode, 4); + + include_once("./Services/Skill/classes/class.ilPersonalSkillsGUI.php"); + $pskills_gui = new ilPersonalSkillsGUI(); + $pskills_gui->setProfileId($profile_id); + $pskills_gui->setGapAnalysisActualStatusModePerObject($survey->getId(), $lng->txt("skmg_eval_type_1")); + if ($survey->getFinishedIdForAppraiseeIdAndRaterId($appr_id, $appr_id) > 0) { + $sskill = new ilSurveySkill($survey); + $self_levels = array(); + foreach ($sskill->determineSkillLevelsForAppraisee($appr_id, true) as $sl) { + $self_levels[$sl["base_skill_id"]][$sl["tref_id"]] = $sl["new_level_id"]; + } + $pskills_gui->setGapAnalysisSelfEvalLevels($self_levels); + } + $html = $pskills_gui->getGapAnalysisHTML($appr_id); + + $tpl->setContent($html); + } else { // must be all survey competences + include_once("./Services/Skill/classes/class.ilPersonalSkillsGUI.php"); + $pskills_gui = new ilPersonalSkillsGUI(); + #23743 + if ($survey->getMode() != ilObjSurvey::MODE_SELF_EVAL) { + $pskills_gui->setGapAnalysisActualStatusModePerObject($survey->getId(), $lng->txt("skmg_eval_type_1")); + } + if ($survey->getFinishedIdForAppraiseeIdAndRaterId($appr_id, $appr_id) > 0) { + $sskill = new ilSurveySkill($survey); + $self_levels = array(); + foreach ($sskill->determineSkillLevelsForAppraisee($appr_id, true) as $sl) { + $self_levels[$sl["base_skill_id"]][$sl["tref_id"]] = $sl["new_level_id"]; + } + $pskills_gui->setGapAnalysisSelfEvalLevels($self_levels); + } + $sk = array(); + foreach ($skills as $skill) { + $sk[] = array( + "base_skill_id" => (int) $skill["base_skill"], + "tref_id" => (int) $skill["tref_id"] + ); + } + $html = $pskills_gui->getGapAnalysisHTML($appr_id, $sk); + + $tpl->setContent($html); + } + } + + /** + * Check if user can view results granted by rbac or positions + */ + protected function hasResultsAccess() + { + return $this->access->checkRbacOrPositionPermissionAccess('read_results', 'access_results', $this->object->getRefId()); + } } - -?> \ No newline at end of file diff --git a/Modules/Survey/classes/class.ilSurveyEvaluationResults.php b/Modules/Survey/classes/class.ilSurveyEvaluationResults.php index 6fb98fc123c2c167fee1b1de57b0536ac83c564e..386db7d24e628a98e2921af238610c12a64d1a02 100644 --- a/Modules/Survey/classes/class.ilSurveyEvaluationResults.php +++ b/Modules/Survey/classes/class.ilSurveyEvaluationResults.php @@ -9,265 +9,241 @@ */ class ilSurveyEvaluationResults { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - protected $question; // [SurveyQuestion] - protected $users_answered; // [int] - protected $users_skipped; // [int] - protected $mode_value; // [int] - protected $mode_nr_of_selections; // [int] - protected $arithmetic_mean; // [float] - protected $median; // [string|float] - protected $variables = array(); // [array] - protected $answers = array(); // [array] - - public function __construct(SurveyQuestion $a_question) - { - global $DIC; + protected $question; // [SurveyQuestion] + protected $users_answered; // [int] + protected $users_skipped; // [int] + protected $mode_value; // [int] + protected $mode_nr_of_selections; // [int] + protected $arithmetic_mean; // [float] + protected $median; // [string|float] + protected $variables = array(); // [array] + protected $answers = array(); // [array] + + public function __construct(SurveyQuestion $a_question) + { + global $DIC; - $this->lng = $DIC->language(); - $this->question = $a_question; - } - - public function getQuestion() - { - return $this->question; - } - - public function setUsersAnswered($a_value) - { - $this->users_answered = (int)$a_value; - } - - public function getUsersAnswered() - { - return $this->users_answered; - } - - public function setUsersSkipped($a_value) - { - $this->users_skipped = (int)$a_value; - } - - public function getUsersSkipped() - { - return $this->users_skipped; - } - - public function setMode($a_value, $a_nr_of_selections) - { - $this->mode_value = is_array($a_value) - ? $a_value - : trim($a_value); - $this->mode_nr_of_selections = (int)$a_nr_of_selections; - } - - public function getModeValue() - { - return $this->mode_value; - } - - public function getModeValueAsText() - { - if($this->mode_value === null) - { - return; - } - - $res = array(); - - $mvalues = $this->mode_value; - if(!is_array($mvalues)) - { - $mvalues = array($mvalues); - } - sort($mvalues, SORT_NUMERIC); - foreach($mvalues as $value) - { - $res[] = $this->getScaleText($value); - } - - return implode(", ", $res); - } - - public function getModeNrOfSelections() - { - return $this->mode_nr_of_selections; - } - - public function setMean($a_mean) - { - $this->arithmetic_mean = (float)$a_mean; - } - - public function getMean() - { - return $this->arithmetic_mean; - } - - public function setMedian($a_value) - { - $this->median = is_array($a_value) - ? $a_value - : trim($a_value); - } - - public function getMedian() - { - return $this->median; - } - - public function getMedianAsText() - { - $lng = $this->lng; - - if($this->median === null) - { - return; - } - - if(!is_array($this->median)) - { - return $this->getScaleText($this->median); - } - else - { - return $lng->txt("median_between")." ". - $this->getScaleText($this->median[0])." ". - $lng->txt("and")." ". - $this->getScaleText($this->median[1]); - } - } - - public function addVariable(ilSurveyEvaluationResultsVariable $a_variable) - { - $this->variables[] = $a_variable; - } - - public function getVariables() - { - if(sizeof($this->variables)) - { - return $this->variables; - } - } - - public function addAnswer(ilSurveyEvaluationResultsAnswer $a_answer) - { - $this->answers[] = $a_answer; - } - - public function getAnswers() - { - if(sizeof($this->answers)) - { - return $this->answers; - } - } - - protected function getScaleText($a_value) - { - if(!sizeof($this->variables)) - { - return $a_value; - } - else - { - foreach($this->variables as $var) - { - if($var->cat->scale == $a_value) - { - return $var->cat->title." [".$a_value."]"; - } - } - } - } + $this->lng = $DIC->language(); + $this->question = $a_question; + } + + public function getQuestion() + { + return $this->question; + } + + public function setUsersAnswered($a_value) + { + $this->users_answered = (int) $a_value; + } + + public function getUsersAnswered() + { + return $this->users_answered; + } + + public function setUsersSkipped($a_value) + { + $this->users_skipped = (int) $a_value; + } + + public function getUsersSkipped() + { + return $this->users_skipped; + } + + public function setMode($a_value, $a_nr_of_selections) + { + $this->mode_value = is_array($a_value) + ? $a_value + : trim($a_value); + $this->mode_nr_of_selections = (int) $a_nr_of_selections; + } + + public function getModeValue() + { + return $this->mode_value; + } + + public function getModeValueAsText() + { + if ($this->mode_value === null) { + return; + } + + $res = array(); + + $mvalues = $this->mode_value; + if (!is_array($mvalues)) { + $mvalues = array($mvalues); + } + sort($mvalues, SORT_NUMERIC); + foreach ($mvalues as $value) { + $res[] = $this->getScaleText($value); + } + + return implode(", ", $res); + } + + public function getModeNrOfSelections() + { + return $this->mode_nr_of_selections; + } + + public function setMean($a_mean) + { + $this->arithmetic_mean = (float) $a_mean; + } + + public function getMean() + { + return $this->arithmetic_mean; + } + + public function setMedian($a_value) + { + $this->median = is_array($a_value) + ? $a_value + : trim($a_value); + } + + public function getMedian() + { + return $this->median; + } + + public function getMedianAsText() + { + $lng = $this->lng; + + if ($this->median === null) { + return; + } + + if (!is_array($this->median)) { + return $this->getScaleText($this->median); + } else { + return $lng->txt("median_between") . " " . + $this->getScaleText($this->median[0]) . " " . + $lng->txt("and") . " " . + $this->getScaleText($this->median[1]); + } + } + + public function addVariable(ilSurveyEvaluationResultsVariable $a_variable) + { + $this->variables[] = $a_variable; + } + + public function getVariables() + { + if (sizeof($this->variables)) { + return $this->variables; + } + } + + public function addAnswer(ilSurveyEvaluationResultsAnswer $a_answer) + { + $this->answers[] = $a_answer; + } + + public function getAnswers() + { + if (sizeof($this->answers)) { + return $this->answers; + } + } + + protected function getScaleText($a_value) + { + if (!sizeof($this->variables)) { + return $a_value; + } else { + foreach ($this->variables as $var) { + if ($var->cat->scale == $a_value) { + return $var->cat->title . " [" . $a_value . "]"; + } + } + } + } - protected function getCatTitle($a_value) - { - if(!sizeof($this->variables)) - { - return $a_value; - } - else - { - foreach($this->variables as $var) - { - if($var->cat->scale == $a_value) - { - return $var->cat->title; - } - } - } - } + protected function getCatTitle($a_value) + { + if (!sizeof($this->variables)) { + return $a_value; + } else { + foreach ($this->variables as $var) { + if ($var->cat->scale == $a_value) { + return $var->cat->title; + } + } + } + } - public function getMappedTextAnswers() - { - $res = array(); - - foreach($this->answers as $answer) - { - if($answer->text) - { - $res[$this->getScaleText($answer->value)][] = $answer->text; - } - } - - return $res; - } - - public function getUserResults($a_active_id) - { - $res = array(); - - $answers = $this->getAnswers(); - if($answers) - { - foreach($answers as $answer) - { - if($answer->active_id == $a_active_id) - { - $res[] = array( - $this->getScaleText($answer->value), - $answer->text, - $answer->value, - $this->getCatTitle($answer->value) - ); - } - } - } - - return $res; - } + public function getMappedTextAnswers() + { + $res = array(); + + foreach ($this->answers as $answer) { + if ($answer->text) { + $res[$this->getScaleText($answer->value)][] = $answer->text; + } + } + + return $res; + } + + public function getUserResults($a_active_id) + { + $res = array(); + + $answers = $this->getAnswers(); + if ($answers) { + foreach ($answers as $answer) { + if ($answer->active_id == $a_active_id) { + $res[] = array( + $this->getScaleText($answer->value), + $answer->text, + $answer->value, + $this->getCatTitle($answer->value) + ); + } + } + } + + return $res; + } } class ilSurveyEvaluationResultsVariable { - public $cat; // [SurveyCategory] - public $abs; // [int] - public $perc; // [float] - - public function __construct(ilSurveyCategory $a_cat, $a_abs, $a_perc) - { - $this->cat = $a_cat; - $this->abs = (int)$a_abs; - $this->perc = (float)$a_perc; - } + public $cat; // [SurveyCategory] + public $abs; // [int] + public $perc; // [float] + + public function __construct(ilSurveyCategory $a_cat, $a_abs, $a_perc) + { + $this->cat = $a_cat; + $this->abs = (int) $a_abs; + $this->perc = (float) $a_perc; + } } class ilSurveyEvaluationResultsAnswer { - public $active_id; // [int] - public $value; // [int|float] - public $text; // [string] - - public function __construct($a_active_id, $a_value, $a_text) - { - $this->active_id = (int)$a_active_id; - $this->value = $a_value; - $this->text = trim($a_text); - } -} \ No newline at end of file + public $active_id; // [int] + public $value; // [int|float] + public $text; // [string] + + public function __construct($a_active_id, $a_value, $a_text) + { + $this->active_id = (int) $a_active_id; + $this->value = $a_value; + $this->text = trim($a_text); + } +} diff --git a/Modules/Survey/classes/class.ilSurveyExecutionGUI.php b/Modules/Survey/classes/class.ilSurveyExecutionGUI.php index 6422d34dcf7f1c40ea050556661d84e84f0d8ce8..6597aeb18af1c2d210725306f3d420a12fd05ef9 100644 --- a/Modules/Survey/classes/class.ilSurveyExecutionGUI.php +++ b/Modules/Survey/classes/class.ilSurveyExecutionGUI.php @@ -34,999 +34,893 @@ */ class ilSurveyExecutionGUI { - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilHelpGUI - */ - protected $help; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - var $object; - var $lng; - var $tpl; - var $ctrl; - var $tree; - var $preview; - - /** - * @var ilLogger - */ - protected $log; - -/** -* ilSurveyExecutionGUI constructor -* -* The constructor takes possible arguments an creates an instance of the ilSurveyExecutionGUI object. -* -* @param object $a_object Associated ilObjSurvey class -* @access public -*/ - function __construct($a_object) - { - global $DIC; - - $this->rbacsystem = $DIC->rbac()->system(); - $this->user = $DIC->user(); - $this->help = $DIC["ilHelp"]; - $this->toolbar = $DIC->toolbar(); - $lng = $DIC->language(); - $tpl = $DIC["tpl"]; - $ilCtrl = $DIC->ctrl(); - $tree = $DIC->repositoryTree(); - - $this->lng = $lng; - $this->tpl = $tpl; - $this->ctrl = $ilCtrl; - $this->object = $a_object; - $this->tree = $tree; - - $this->external_rater_360 = false; - if($this->object->get360Mode() && - $_SESSION["anonymous_id"][$this->object->getId()] && - ilObjSurvey::validateExternalRaterCode($this->object->getRefId(), - $_SESSION["anonymous_id"][$this->object->getId()])) - { - $this->external_rater_360 = true; - } - - // stay in preview mode - $this->preview = (bool)$_REQUEST["prvw"]; - $this->ctrl->saveParameter($this, "prvw"); - $this->ctrl->saveParameter($this, "pgov"); - - $this->log = ilLoggerFactory::getLogger("svy"); - } - - /** - * execute command - */ - function executeCommand() - { - // record read event for lp - ilChangeEvent::_recordReadEvent( - 'svy', - $this->object->getRefId(), - $this->object->getId(), - $GLOBALS['DIC']->user()->getId() - ); - - $cmd = $this->ctrl->getCmd(); - $next_class = $this->ctrl->getNextClass($this); - - $cmd = $this->getCommand($cmd); - - $this->log->debug("- cmd= ".$cmd); - - if (strlen($cmd) == 0) - { - $this->ctrl->setParameter($this, "qid", $_GET["qid"]); - $this->ctrl->redirect($this, "gotoPage"); - } - switch($next_class) - { - default: - $ret =& $this->$cmd(); - break; - } - return $ret; - } - - protected function checkAuth($a_may_start = false, $a_ignore_status = false) - { - $rbacsystem = $this->rbacsystem; - $ilUser = $this->user; - - if($this->preview) - { - if(!$rbacsystem->checkAccess("write", $this->object->ref_id)) - { - // only with write access it is possible to preview the survey - include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; - throw new ilSurveyException($this->lng->txt("survey_cannot_preview_survey")); - } - - return true; - } - - if (!$this->external_rater_360 && - !$rbacsystem->checkAccess("read", $this->object->ref_id)) - { - // only with read access it is possible to run the test - include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; - throw new ilSurveyException($this->lng->txt("cannot_read_survey")); - } - - $user_id = $ilUser->getId(); - - // check existing code - // see ilObjSurveyGUI::infoScreen() - $anonymous_id = $anonymous_code = null; - if ($this->object->getAnonymize() || !$this->object->isAccessibleWithoutCode()) - { - $anonymous_code = $_SESSION["anonymous_id"][$this->object->getId()]; - $anonymous_id = $this->object->getAnonymousIdByCode($anonymous_code); - if(!$anonymous_id) - { - ilUtil::sendFailure(sprintf($this->lng->txt("error_retrieving_anonymous_survey"), $anonymous_code, true)); - $this->ctrl->redirectByClass("ilobjsurveygui", "infoScreen"); - } - } - - // appraisee validation - $appr_id = 0; - if($this->object->get360Mode()) - { - $appr_id = $_REQUEST["appr_id"]; - if(!$appr_id) - { - $appr_id = $_SESSION["appr_id"][$this->object->getId()]; - } - // check if appraisee is valid - if($anonymous_id) - { - $appraisees = $this->object->getAppraiseesToRate(0, $anonymous_id); - } - if(!$appraisees && $user_id != ANONYMOUS_USER_ID) - { - $appraisees = $this->object->getAppraiseesToRate($user_id); - } - if(!in_array($appr_id, $appraisees)) - { - ilUtil::sendFailure($this->lng->txt("survey_360_execution_invalid_appraisee"), true); - $this->ctrl->redirectByClass("ilobjsurveygui", "infoScreen"); - } - } - //Self evaluation mode - #23575 in self eval the appraisee is the current user. - if($this->object->getMode() == ilObjSurvey::MODE_SELF_EVAL) { - $appr_id = $ilUser->getId(); - } - - $_SESSION["appr_id"][$this->object->getId()] = $appr_id; - - if(!$a_ignore_status) - { - $status = $this->object->isSurveyStarted($user_id, $anonymous_code, $appr_id); - // completed - if($status === 1) - { - ilUtil::sendFailure($this->lng->txt("already_completed_survey"), true); - $this->ctrl->redirectByClass("ilobjsurveygui", "infoScreen"); - } - // starting - else if ($status === false) - { - if($a_may_start) - { - $_SESSION["finished_id"][$this->object->getId()] = - $this->object->startSurvey($user_id, $anonymous_code, $appr_id); - } - else - { - ilUtil::sendFailure($this->lng->txt("survey_use_start_button"), true); - $this->ctrl->redirectByClass("ilobjsurveygui", "infoScreen"); - } - } - // resuming - else - { - // nothing todo - } - } - - // validate finished id - if($this->object->getActiveID($user_id, $anonymous_code, $appr_id) != - $_SESSION["finished_id"][$this->object->getId()]) - { - ilUtil::sendFailure($this->lng->txt("cannot_read_survey"), true); - $this->ctrl->redirectByClass("ilobjsurveygui", "infoScreen"); - } - } - -/** -* Retrieves the ilCtrl command -* -* Retrieves the ilCtrl command -* -* @access public -*/ - function getCommand($cmd) - { - return $cmd; - } - -/** -* Resumes the survey -* -* Resumes the survey -* -* @access private -*/ - function resume() - { - $this->start(true); - } - -/** -* Starts the survey -* -* Starts the survey -* -* @access private -*/ - function start($resume = false) - { - if($this->preview) - { - unset($_SESSION["preview_data"]); - } - unset($_SESSION["svy_errors"]); - - $this->checkAuth(!$resume); - - $activepage = ""; - if ($resume) - { - $activepage = $this->object->getLastActivePage($_SESSION["finished_id"][$this->object->getId()]); - } - - if (strlen($activepage)) - { - $this->ctrl->setParameter($this, "qid", $activepage); - } - $this->ctrl->setParameter($this, "activecommand", "default"); - $this->ctrl->redirect($this, "redirectQuestion"); - } - - /** - * Called when a user answered a page to perform a redirect after POST. - * This is called for security reasons to prevent users sending a form twice. - * - * @access public - */ - function redirectQuestion() - { - switch ($_GET["activecommand"]) - { - case "next": - $this->outSurveyPage($_GET["qid"], $_GET["direction"]); - break; - case "previous": - $this->outSurveyPage($_GET["qid"], $_GET["direction"]); - break; - case "gotoPage": - $this->outSurveyPage($_GET["qid"], $_GET["direction"]); - break; - case "default": - $this->outSurveyPage($_GET["qid"]); - break; - default: - // don't save input, go to the first page - $this->outSurveyPage(); - break; - } - } - - function previousNoSave() - { - $this->previous(false); - } - -/** -* Navigates to the previous pages -* -* Navigates to the previous pages -* -* @access private -*/ - function previous($a_save_input = true) - { - if($a_save_input) - { - // #16209 - $has_error = $this->saveUserInput("previous"); - } - $this->ctrl->setParameter($this, "activecommand", "previous"); - $this->ctrl->setParameter($this, "qid", $_GET["qid"]); - if (strlen($has_error)) - { - $this->ctrl->setParameter($this, "direction", "0"); - } - else - { - $this->ctrl->setParameter($this, "direction", "-1"); - } - $this->ctrl->redirect($this, "redirectQuestion"); - } - -/** -* Navigates to the next pages -* -* @access private -*/ - function next() - { - $result = $this->saveUserInput("next"); - $this->ctrl->setParameter($this, "activecommand", "next"); - $this->ctrl->setParameter($this, "qid", $_GET["qid"]); - if (strlen($result)) - { - $this->ctrl->setParameter($this, "direction", "0"); - } - else - { - $this->ctrl->setParameter($this, "direction", "1"); - } - $this->ctrl->redirect($this, "redirectQuestion"); - } - - /** - * Go to a specific page without saving - * - * @access private - */ - function gotoPage() - { - $this->ctrl->setParameter($this, "activecommand", "gotoPage"); - $this->ctrl->setParameter($this, "qid", $_GET["qid"]); - $this->ctrl->setParameter($this, "direction", "0"); - $this->ctrl->redirect($this, "redirectQuestion"); - } - -/** -* Output of the active survey question to the screen -* -* Output of the active survey question to the screen -* -* @access private -*/ - function outSurveyPage($activepage = NULL, $direction = NULL) - { - $ilUser = $this->user; - - $this->checkAuth(); - - $page = $this->object->getNextPage($activepage, $direction); - $constraint_true = 0; - - // check for constraints - if (is_array($page[0]["constraints"]) && count($page[0]["constraints"])) - { - $this->log->debug("Page constraints= ", $page[0]["constraints"]); - - while (is_array($page) and ($constraint_true == 0) and (count($page[0]["constraints"]))) - { - $constraint_true = ($page[0]['constraints'][0]['conjunction'] == 0) ? true : false; - foreach ($page[0]["constraints"] as $constraint) - { - if(!$this->preview) - { - $working_data = $this->object->loadWorkingData($constraint["question"], $_SESSION["finished_id"][$this->object->getId()]); - } - else - { - $working_data = $_SESSION["preview_data"][$this->object->getId()][$constraint["question"]]; - } - if ($constraint['conjunction'] == 0) - { - // and - $constraint_true = $constraint_true & $this->object->checkConstraint($constraint, $working_data); - } - else - { - // or - $constraint_true = $constraint_true | $this->object->checkConstraint($constraint, $working_data); - } - } - if ($constraint_true == 0) - { - // #11047 - we are skipping the page, so we have to get rid of existing answers for that question(s) - foreach($page as $page_question) - { - $qid = $page_question["question_id"]; - - // see saveActiveQuestionData() - if(!$this->preview) - { - $this->object->deleteWorkingData($qid, $_SESSION["finished_id"][$this->object->getId()]); - } - else - { - $_SESSION["preview_data"][$this->object->getId()][$qid] = null; - } - } - - $page = $this->object->getNextPage($page[0]["question_id"], $direction); - } - } - } - - $first_question = -1; - if ($page === 0) - { - $this->ctrl->redirectByClass("ilobjsurveygui", "infoScreen"); - } - else if ($page === 1) - { - $state = $this->object->getUserSurveyExecutionStatus(); - if($this->preview || - !$state["runs"][$_SESSION["finished_id"][$this->object->getId()]]["finished"]) - { - $this->showFinishConfirmation(); - } - else - { - $this->runShowFinishedPage(); - } - return; - } - else - { - $ilHelp = $this->help; - $ilHelp->setScreenIdComponent("svy"); - $ilHelp->setScreenId("quest_presentation"); - - if($ilUser->getId() != ANONYMOUS_USER_ID) - { - include_once "Services/Tracking/classes/class.ilLearningProgress.php"; - ilLearningProgress::_tracProgress($ilUser->getId(), $this->object->getId(), $this->object->ref_id, "svy"); - } - - $required = false; - $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.il_svy_svy_content.html", "Modules/Survey"); - - if($this->object->get360Mode()) - { - $appr_id = $_SESSION["appr_id"][$this->object->getId()]; - - include_once "Services/User/classes/class.ilUserUtil.php"; - $this->tpl->setTitle($this->object->getTitle()." (". - $this->lng->txt("survey_360_appraisee").": ". - ilUserUtil::getNamePresentation($appr_id).")"); - } - - if (!($this->object->getAnonymize() && $this->object->isAccessibleWithoutCode() && ($ilUser->getId() == ANONYMOUS_USER_ID))) - { - $this->tpl->setCurrentBlock("suspend_survey"); - - if(!$this->preview) - { - $this->tpl->setVariable("TEXT_SUSPEND", $this->lng->txt("cancel_survey")); - $this->tpl->setVariable("HREF_SUSPEND", $this->ctrl->getLinkTargetByClass("ilObjSurveyGUI", "infoScreen")); - } - else - { - $this->ctrl->setParameterByClass("ilObjSurveyGUI", "pgov", $_REQUEST["pgov"]); - $this->tpl->setVariable("TEXT_SUSPEND", $this->lng->txt("survey_cancel_preview")); - $this->tpl->setVariable("HREF_SUSPEND", $this->ctrl->getLinkTargetByClass(array("ilObjSurveyGUI", "ilSurveyEditorGUI"), "questions")); - } - - $this->tpl->setVariable("ALT_IMG_SUSPEND", $this->lng->txt("cancel_survey")); - $this->tpl->setVariable("TITLE_IMG_SUSPEND", $this->lng->txt("cancel_survey")); - $this->tpl->parseCurrentBlock(); - } - $this->outNavigationButtons("top", $page); - - - $this->tpl->setCurrentBlock("percentage"); - - $percentage = (int)(($page[0]["position"])*100); - - include_once "Services/UIComponent/ProgressBar/classes/class.ilProgressBar.php"; - $pbar = ilProgressBar::getInstance(); - $pbar->setCurrent($percentage); - $this->tpl->setVariable("NEW_PBAR", $pbar->render()); - - $this->tpl->parseCurrentBlock(); - - - if (count($page) > 1 && $page[0]["questionblock_show_blocktitle"]) - { - $this->tpl->setCurrentBlock("questionblock_title"); - $this->tpl->setVariable("TEXT_QUESTIONBLOCK_TITLE", $page[0]["questionblock_title"]); - $this->tpl->parseCurrentBlock(); - } - foreach ($page as $data) - { - $this->tpl->setCurrentBlock("survey_content"); - if ($data["heading"]) - { - $this->tpl->setVariable("QUESTION_HEADING", $data["heading"]); - } - if ($first_question == -1) $first_question = $data["question_id"]; - $question_gui = $this->object->getQuestionGUI($data["type_tag"], $data["question_id"]); - if (is_array($_SESSION["svy_errors"])) - { - $working_data =& $question_gui->object->getWorkingDataFromUserInput($_SESSION["postdata"]); - } - else - { - $working_data = $this->object->loadWorkingData($data["question_id"], $_SESSION["finished_id"][$this->object->getId()]); - } - $question_gui->object->setObligatory($data["obligatory"]); - $error_messages = array(); - if (is_array($_SESSION["svy_errors"])) - { - $error_messages = $_SESSION["svy_errors"]; - } - $show_questiontext = ($data["questionblock_show_questiontext"]) ? 1 : 0; - $question_output = $question_gui->getWorkingForm($working_data, $this->object->getShowQuestionTitles(), $show_questiontext, $error_messages[$data["question_id"]], $this->object->getSurveyId()); - $this->tpl->setVariable("QUESTION_OUTPUT", $question_output); - $this->ctrl->setParameter($this, "qid", $data["question_id"]); - $this->tpl->parse("survey_content"); - if ($data["obligatory"]) $required = true; - } - if ($required) - { - $this->tpl->setCurrentBlock("required"); - $this->tpl->setVariable("TEXT_REQUIRED", $this->lng->txt("required_field")); - $this->tpl->parseCurrentBlock(); - } - - $this->outNavigationButtons("bottom", $page); - - $this->tpl->setVariable("FORM_ACTION", $this->ctrl->getFormAction($this, "redirectQuestion")); - } - - if(!$this->preview) - { - $this->object->setPage($_SESSION["finished_id"][$this->object->getId()], $page[0]['question_id']); - $this->object->setStartTime($_SESSION["finished_id"][$this->object->getId()], $first_question); - } - } - - /** - * Save the user's input - * - * @access private - */ - function saveUserInput($navigationDirection = "next") - { - if(!$this->preview) - { - $this->object->setEndTime($_SESSION["finished_id"][$this->object->getId()]); - } - - // check users input when it is a metric question - unset($_SESSION["svy_errors"]); - $_SESSION["postdata"] = $_POST; - $page_error = 0; - $page = $this->object->getNextPage($_GET["qid"], 0); - foreach ($page as $data) - { - $page_error += $this->saveActiveQuestionData($data); - } - if ($page_error && (strcmp($navigationDirection, "previous") != 0)) - { - if ($page_error == 1) - { - ilUtil::sendFailure($this->lng->txt("svy_page_error"), TRUE); - } - else - { - ilUtil::sendFailure($this->lng->txt("svy_page_errors"), TRUE); - } - } - else - { - $page_error = ""; - unset($_SESSION["svy_errors"]); - } - return $page_error; - } - -/** -* Survey navigation -* -* Survey navigation -* -* @access private -*/ - /* - function navigate($navigationDirection = "next") - { - // check users input when it is a metric question - unset($_SESSION["svy_errors"]); - $page_error = 0; - $page = $this->object->getNextPage($_GET["qid"], 0); - foreach ($page as $data) - { - $page_error += $this->saveActiveQuestionData($data); - } - if ($page_error && (strcmp($navigationDirection, "previous") != 0)) - { - if ($page_error == 1) - { - ilUtil::sendFailure($this->lng->txt("svy_page_error")); - } - else - { - ilUtil::sendFailure($this->lng->txt("svy_page_errors")); - } - } - else - { - $page_error = ""; - unset($_SESSION["svy_errors"]); - } - - $direction = 0; - switch ($navigationDirection) - { - case "next": - default: - $activepage = $_GET["qid"]; - if (!$page_error) - { - $direction = 1; - } - break; - case "previous": - $activepage = $_GET["qid"]; - if (!$page_error) - { - $direction = -1; - } - break; - } - $this->outSurveyPage($activepage, $direction); - } -*/ - -/** -* Saves the users input of the active page -* -* Saves the users input of the active page -* -* @access private -*/ - function saveActiveQuestionData(&$data) - { - $ilUser = $this->user; - - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - $question =& SurveyQuestion::_instanciateQuestion($data["question_id"]); - $error = $question->checkUserInput($_POST, $this->object->getSurveyId()); - if (strlen($error) == 0) - { - if(!$this->preview) - { - // delete old answers - $this->object->deleteWorkingData($data["question_id"], $_SESSION["finished_id"][$this->object->getId()]); - - $question->saveUserInput($_POST, $_SESSION["finished_id"][$this->object->getId()]); - } - else - { - $_SESSION["preview_data"][$this->object->getId()][$data["question_id"]] = - $question->saveUserInput($_POST, $_SESSION["finished_id"][$this->object->getId()], true); - } - return 0; - } - else - { - $_SESSION["svy_errors"][$question->getId()] = $error; - return 1; - } - } - -/** -* Called on cancel -* -* Called on cancel -* -* @access private + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + public $object; + public $lng; + public $tpl; + public $ctrl; + public $tree; + public $preview; + + /** + * @var ilLogger + */ + protected $log; + + /** + * ilSurveyExecutionGUI constructor + * + * The constructor takes possible arguments an creates an instance of the ilSurveyExecutionGUI object. + * + * @param object $a_object Associated ilObjSurvey class + * @access public + */ + public function __construct($a_object) + { + global $DIC; + + $this->rbacsystem = $DIC->rbac()->system(); + $this->user = $DIC->user(); + $this->help = $DIC["ilHelp"]; + $this->toolbar = $DIC->toolbar(); + $lng = $DIC->language(); + $tpl = $DIC["tpl"]; + $ilCtrl = $DIC->ctrl(); + $tree = $DIC->repositoryTree(); + + $this->lng = $lng; + $this->tpl = $tpl; + $this->ctrl = $ilCtrl; + $this->object = $a_object; + $this->tree = $tree; + + $this->external_rater_360 = false; + if ($this->object->get360Mode() && + $_SESSION["anonymous_id"][$this->object->getId()] && + ilObjSurvey::validateExternalRaterCode( + $this->object->getRefId(), + $_SESSION["anonymous_id"][$this->object->getId()] + )) { + $this->external_rater_360 = true; + } + + // stay in preview mode + $this->preview = (bool) $_REQUEST["prvw"]; + $this->ctrl->saveParameter($this, "prvw"); + $this->ctrl->saveParameter($this, "pgov"); + + $this->log = ilLoggerFactory::getLogger("svy"); + } + + /** + * execute command + */ + public function executeCommand() + { + // record read event for lp + ilChangeEvent::_recordReadEvent( + 'svy', + $this->object->getRefId(), + $this->object->getId(), + $GLOBALS['DIC']->user()->getId() + ); + + $cmd = $this->ctrl->getCmd(); + $next_class = $this->ctrl->getNextClass($this); + + $cmd = $this->getCommand($cmd); + + $this->log->debug("- cmd= " . $cmd); + + if (strlen($cmd) == 0) { + $this->ctrl->setParameter($this, "qid", $_GET["qid"]); + $this->ctrl->redirect($this, "gotoPage"); + } + switch ($next_class) { + default: + $ret =&$this->$cmd(); + break; + } + return $ret; + } + + protected function checkAuth($a_may_start = false, $a_ignore_status = false) + { + $rbacsystem = $this->rbacsystem; + $ilUser = $this->user; + + if ($this->preview) { + if (!$rbacsystem->checkAccess("write", $this->object->ref_id)) { + // only with write access it is possible to preview the survey + include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; + throw new ilSurveyException($this->lng->txt("survey_cannot_preview_survey")); + } + + return true; + } + + if (!$this->external_rater_360 && + !$rbacsystem->checkAccess("read", $this->object->ref_id)) { + // only with read access it is possible to run the test + include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; + throw new ilSurveyException($this->lng->txt("cannot_read_survey")); + } + + $user_id = $ilUser->getId(); + + // check existing code + // see ilObjSurveyGUI::infoScreen() + $anonymous_id = $anonymous_code = null; + if ($this->object->getAnonymize() || !$this->object->isAccessibleWithoutCode()) { + $anonymous_code = $_SESSION["anonymous_id"][$this->object->getId()]; + $anonymous_id = $this->object->getAnonymousIdByCode($anonymous_code); + if (!$anonymous_id) { + ilUtil::sendFailure(sprintf($this->lng->txt("error_retrieving_anonymous_survey"), $anonymous_code, true)); + $this->ctrl->redirectByClass("ilobjsurveygui", "infoScreen"); + } + } + + // appraisee validation + $appr_id = 0; + if ($this->object->get360Mode()) { + $appr_id = $_REQUEST["appr_id"]; + if (!$appr_id) { + $appr_id = $_SESSION["appr_id"][$this->object->getId()]; + } + // check if appraisee is valid + if ($anonymous_id) { + $appraisees = $this->object->getAppraiseesToRate(0, $anonymous_id); + } + if (!$appraisees && $user_id != ANONYMOUS_USER_ID) { + $appraisees = $this->object->getAppraiseesToRate($user_id); + } + if (!in_array($appr_id, $appraisees)) { + ilUtil::sendFailure($this->lng->txt("survey_360_execution_invalid_appraisee"), true); + $this->ctrl->redirectByClass("ilobjsurveygui", "infoScreen"); + } + } + //Self evaluation mode + #23575 in self eval the appraisee is the current user. + if ($this->object->getMode() == ilObjSurvey::MODE_SELF_EVAL) { + $appr_id = $ilUser->getId(); + } + + $_SESSION["appr_id"][$this->object->getId()] = $appr_id; + + if (!$a_ignore_status) { + $status = $this->object->isSurveyStarted($user_id, $anonymous_code, $appr_id); + // completed + if ($status === 1) { + ilUtil::sendFailure($this->lng->txt("already_completed_survey"), true); + $this->ctrl->redirectByClass("ilobjsurveygui", "infoScreen"); + } + // starting + elseif ($status === false) { + if ($a_may_start) { + $_SESSION["finished_id"][$this->object->getId()] = + $this->object->startSurvey($user_id, $anonymous_code, $appr_id); + } else { + ilUtil::sendFailure($this->lng->txt("survey_use_start_button"), true); + $this->ctrl->redirectByClass("ilobjsurveygui", "infoScreen"); + } + } + // resuming + else { + // nothing todo + } + } + + // validate finished id + if ($this->object->getActiveID($user_id, $anonymous_code, $appr_id) != + $_SESSION["finished_id"][$this->object->getId()]) { + ilUtil::sendFailure($this->lng->txt("cannot_read_survey"), true); + $this->ctrl->redirectByClass("ilobjsurveygui", "infoScreen"); + } + } + + /** + * Retrieves the ilCtrl command + * + * Retrieves the ilCtrl command + * + * @access public + */ + public function getCommand($cmd) + { + return $cmd; + } + + /** + * Resumes the survey + * + * Resumes the survey + * + * @access private + */ + public function resume() + { + $this->start(true); + } + + /** + * Starts the survey + * + * Starts the survey + * + * @access private + */ + public function start($resume = false) + { + if ($this->preview) { + unset($_SESSION["preview_data"]); + } + unset($_SESSION["svy_errors"]); + + $this->checkAuth(!$resume); + + $activepage = ""; + if ($resume) { + $activepage = $this->object->getLastActivePage($_SESSION["finished_id"][$this->object->getId()]); + } + + if (strlen($activepage)) { + $this->ctrl->setParameter($this, "qid", $activepage); + } + $this->ctrl->setParameter($this, "activecommand", "default"); + $this->ctrl->redirect($this, "redirectQuestion"); + } + + /** + * Called when a user answered a page to perform a redirect after POST. + * This is called for security reasons to prevent users sending a form twice. + * + * @access public + */ + public function redirectQuestion() + { + switch ($_GET["activecommand"]) { + case "next": + $this->outSurveyPage($_GET["qid"], $_GET["direction"]); + break; + case "previous": + $this->outSurveyPage($_GET["qid"], $_GET["direction"]); + break; + case "gotoPage": + $this->outSurveyPage($_GET["qid"], $_GET["direction"]); + break; + case "default": + $this->outSurveyPage($_GET["qid"]); + break; + default: + // don't save input, go to the first page + $this->outSurveyPage(); + break; + } + } + + public function previousNoSave() + { + $this->previous(false); + } + + /** + * Navigates to the previous pages + * + * Navigates to the previous pages + * + * @access private + */ + public function previous($a_save_input = true) + { + if ($a_save_input) { + // #16209 + $has_error = $this->saveUserInput("previous"); + } + $this->ctrl->setParameter($this, "activecommand", "previous"); + $this->ctrl->setParameter($this, "qid", $_GET["qid"]); + if (strlen($has_error)) { + $this->ctrl->setParameter($this, "direction", "0"); + } else { + $this->ctrl->setParameter($this, "direction", "-1"); + } + $this->ctrl->redirect($this, "redirectQuestion"); + } + + /** + * Navigates to the next pages + * + * @access private + */ + public function next() + { + $result = $this->saveUserInput("next"); + $this->ctrl->setParameter($this, "activecommand", "next"); + $this->ctrl->setParameter($this, "qid", $_GET["qid"]); + if (strlen($result)) { + $this->ctrl->setParameter($this, "direction", "0"); + } else { + $this->ctrl->setParameter($this, "direction", "1"); + } + $this->ctrl->redirect($this, "redirectQuestion"); + } + + /** + * Go to a specific page without saving + * + * @access private + */ + public function gotoPage() + { + $this->ctrl->setParameter($this, "activecommand", "gotoPage"); + $this->ctrl->setParameter($this, "qid", $_GET["qid"]); + $this->ctrl->setParameter($this, "direction", "0"); + $this->ctrl->redirect($this, "redirectQuestion"); + } + + /** + * Output of the active survey question to the screen + * + * Output of the active survey question to the screen + * + * @access private + */ + public function outSurveyPage($activepage = null, $direction = null) + { + $ilUser = $this->user; + + $this->checkAuth(); + + $page = $this->object->getNextPage($activepage, $direction); + $constraint_true = 0; + + // check for constraints + if (is_array($page[0]["constraints"]) && count($page[0]["constraints"])) { + $this->log->debug("Page constraints= ", $page[0]["constraints"]); + + while (is_array($page) and ($constraint_true == 0) and (count($page[0]["constraints"]))) { + $constraint_true = ($page[0]['constraints'][0]['conjunction'] == 0) ? true : false; + foreach ($page[0]["constraints"] as $constraint) { + if (!$this->preview) { + $working_data = $this->object->loadWorkingData($constraint["question"], $_SESSION["finished_id"][$this->object->getId()]); + } else { + $working_data = $_SESSION["preview_data"][$this->object->getId()][$constraint["question"]]; + } + if ($constraint['conjunction'] == 0) { + // and + $constraint_true = $constraint_true & $this->object->checkConstraint($constraint, $working_data); + } else { + // or + $constraint_true = $constraint_true | $this->object->checkConstraint($constraint, $working_data); + } + } + if ($constraint_true == 0) { + // #11047 - we are skipping the page, so we have to get rid of existing answers for that question(s) + foreach ($page as $page_question) { + $qid = $page_question["question_id"]; + + // see saveActiveQuestionData() + if (!$this->preview) { + $this->object->deleteWorkingData($qid, $_SESSION["finished_id"][$this->object->getId()]); + } else { + $_SESSION["preview_data"][$this->object->getId()][$qid] = null; + } + } + + $page = $this->object->getNextPage($page[0]["question_id"], $direction); + } + } + } + + $first_question = -1; + if ($page === 0) { + $this->ctrl->redirectByClass("ilobjsurveygui", "infoScreen"); + } elseif ($page === 1) { + $state = $this->object->getUserSurveyExecutionStatus(); + if ($this->preview || + !$state["runs"][$_SESSION["finished_id"][$this->object->getId()]]["finished"]) { + $this->showFinishConfirmation(); + } else { + $this->runShowFinishedPage(); + } + return; + } else { + $ilHelp = $this->help; + $ilHelp->setScreenIdComponent("svy"); + $ilHelp->setScreenId("quest_presentation"); + + if ($ilUser->getId() != ANONYMOUS_USER_ID) { + include_once "Services/Tracking/classes/class.ilLearningProgress.php"; + ilLearningProgress::_tracProgress($ilUser->getId(), $this->object->getId(), $this->object->ref_id, "svy"); + } + + $required = false; + $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.il_svy_svy_content.html", "Modules/Survey"); + + if ($this->object->get360Mode()) { + $appr_id = $_SESSION["appr_id"][$this->object->getId()]; + + include_once "Services/User/classes/class.ilUserUtil.php"; + $this->tpl->setTitle($this->object->getTitle() . " (" . + $this->lng->txt("survey_360_appraisee") . ": " . + ilUserUtil::getNamePresentation($appr_id) . ")"); + } + + if (!($this->object->getAnonymize() && $this->object->isAccessibleWithoutCode() && ($ilUser->getId() == ANONYMOUS_USER_ID))) { + $this->tpl->setCurrentBlock("suspend_survey"); + + if (!$this->preview) { + $this->tpl->setVariable("TEXT_SUSPEND", $this->lng->txt("cancel_survey")); + $this->tpl->setVariable("HREF_SUSPEND", $this->ctrl->getLinkTargetByClass("ilObjSurveyGUI", "infoScreen")); + } else { + $this->ctrl->setParameterByClass("ilObjSurveyGUI", "pgov", $_REQUEST["pgov"]); + $this->tpl->setVariable("TEXT_SUSPEND", $this->lng->txt("survey_cancel_preview")); + $this->tpl->setVariable("HREF_SUSPEND", $this->ctrl->getLinkTargetByClass(array("ilObjSurveyGUI", "ilSurveyEditorGUI"), "questions")); + } + + $this->tpl->setVariable("ALT_IMG_SUSPEND", $this->lng->txt("cancel_survey")); + $this->tpl->setVariable("TITLE_IMG_SUSPEND", $this->lng->txt("cancel_survey")); + $this->tpl->parseCurrentBlock(); + } + $this->outNavigationButtons("top", $page); + + + $this->tpl->setCurrentBlock("percentage"); + + $percentage = (int) (($page[0]["position"])*100); + + include_once "Services/UIComponent/ProgressBar/classes/class.ilProgressBar.php"; + $pbar = ilProgressBar::getInstance(); + $pbar->setCurrent($percentage); + $this->tpl->setVariable("NEW_PBAR", $pbar->render()); + + $this->tpl->parseCurrentBlock(); + + + if (count($page) > 1 && $page[0]["questionblock_show_blocktitle"]) { + $this->tpl->setCurrentBlock("questionblock_title"); + $this->tpl->setVariable("TEXT_QUESTIONBLOCK_TITLE", $page[0]["questionblock_title"]); + $this->tpl->parseCurrentBlock(); + } + foreach ($page as $data) { + $this->tpl->setCurrentBlock("survey_content"); + if ($data["heading"]) { + $this->tpl->setVariable("QUESTION_HEADING", $data["heading"]); + } + if ($first_question == -1) { + $first_question = $data["question_id"]; + } + $question_gui = $this->object->getQuestionGUI($data["type_tag"], $data["question_id"]); + if (is_array($_SESSION["svy_errors"])) { + $working_data =&$question_gui->object->getWorkingDataFromUserInput($_SESSION["postdata"]); + } else { + $working_data = $this->object->loadWorkingData($data["question_id"], $_SESSION["finished_id"][$this->object->getId()]); + } + $question_gui->object->setObligatory($data["obligatory"]); + $error_messages = array(); + if (is_array($_SESSION["svy_errors"])) { + $error_messages = $_SESSION["svy_errors"]; + } + $show_questiontext = ($data["questionblock_show_questiontext"]) ? 1 : 0; + $question_output = $question_gui->getWorkingForm($working_data, $this->object->getShowQuestionTitles(), $show_questiontext, $error_messages[$data["question_id"]], $this->object->getSurveyId()); + $this->tpl->setVariable("QUESTION_OUTPUT", $question_output); + $this->ctrl->setParameter($this, "qid", $data["question_id"]); + $this->tpl->parse("survey_content"); + if ($data["obligatory"]) { + $required = true; + } + } + if ($required) { + $this->tpl->setCurrentBlock("required"); + $this->tpl->setVariable("TEXT_REQUIRED", $this->lng->txt("required_field")); + $this->tpl->parseCurrentBlock(); + } + + $this->outNavigationButtons("bottom", $page); + + $this->tpl->setVariable("FORM_ACTION", $this->ctrl->getFormAction($this, "redirectQuestion")); + } + + if (!$this->preview) { + $this->object->setPage($_SESSION["finished_id"][$this->object->getId()], $page[0]['question_id']); + $this->object->setStartTime($_SESSION["finished_id"][$this->object->getId()], $first_question); + } + } + + /** + * Save the user's input + * + * @access private + */ + public function saveUserInput($navigationDirection = "next") + { + if (!$this->preview) { + $this->object->setEndTime($_SESSION["finished_id"][$this->object->getId()]); + } + + // check users input when it is a metric question + unset($_SESSION["svy_errors"]); + $_SESSION["postdata"] = $_POST; + $page_error = 0; + $page = $this->object->getNextPage($_GET["qid"], 0); + foreach ($page as $data) { + $page_error += $this->saveActiveQuestionData($data); + } + if ($page_error && (strcmp($navigationDirection, "previous") != 0)) { + if ($page_error == 1) { + ilUtil::sendFailure($this->lng->txt("svy_page_error"), true); + } else { + ilUtil::sendFailure($this->lng->txt("svy_page_errors"), true); + } + } else { + $page_error = ""; + unset($_SESSION["svy_errors"]); + } + return $page_error; + } + + /** + * Survey navigation + * + * Survey navigation + * + * @access private + */ + /* + function navigate($navigationDirection = "next") + { + // check users input when it is a metric question + unset($_SESSION["svy_errors"]); + $page_error = 0; + $page = $this->object->getNextPage($_GET["qid"], 0); + foreach ($page as $data) + { + $page_error += $this->saveActiveQuestionData($data); + } + if ($page_error && (strcmp($navigationDirection, "previous") != 0)) + { + if ($page_error == 1) + { + ilUtil::sendFailure($this->lng->txt("svy_page_error")); + } + else + { + ilUtil::sendFailure($this->lng->txt("svy_page_errors")); + } + } + else + { + $page_error = ""; + unset($_SESSION["svy_errors"]); + } + + $direction = 0; + switch ($navigationDirection) + { + case "next": + default: + $activepage = $_GET["qid"]; + if (!$page_error) + { + $direction = 1; + } + break; + case "previous": + $activepage = $_GET["qid"]; + if (!$page_error) + { + $direction = -1; + } + break; + } + $this->outSurveyPage($activepage, $direction); + } */ - function cancel() - { - $this->ctrl->redirectByClass("ilobjsurveygui", "infoScreen"); - } - -/** -* Creates the finished page for a running survey -* -* Creates the finished page for a running survey -* -* @access public -*/ - function runShowFinishedPage() - { - $ilToolbar = $this->toolbar; - $ilUser = $this->user; - - $has_button = false; - - include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; - - if(!$this->preview) - { - if($this->object->hasViewOwnResults()) - { - $button = ilLinkButton::getInstance(); - $button->setCaption("svy_view_own_results"); - $button->setUrl($this->ctrl->getLinkTarget($this, "viewUserResults")); - $ilToolbar->addButtonInstance($button); - - $has_button = true; - } - - if($this->object->hasMailConfirmation()) - { - if($has_button) - { - $ilToolbar->addSeparator(); - } - - if($ilUser->getId() == ANONYMOUS_USER_ID || - !$ilUser->getEmail()) - { - require_once "Services/Form/classes/class.ilTextInputGUI.php"; - $mail = new ilTextInputGUI($this->lng->txt("email"), "mail"); - $mail->setSize(25); - $ilToolbar->addInputItem($mail, true); - } - - $ilToolbar->setFormAction($this->ctrl->getFormAction($this, "mailUserResults")); - - include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; - $button = ilSubmitButton::getInstance(); - $button->setCaption("svy_mail_send_confirmation"); - $button->setCommand("mailUserResults"); - $ilToolbar->addButtonInstance($button); - - $has_button = true; - } - - // #6307 - include_once "Modules/Survey/classes/class.ilObjSurveyAccess.php"; - if(ilObjSurveyAccess::_hasEvaluationAccess($this->object->getId(), $ilUser->getId())) - { - $button = ilLinkButton::getInstance(); - $button->setCaption("svy_results"); - $button->setUrl($this->ctrl->getLinkTargetByClass("ilObjSurveyGUI", "evaluation")); - $ilToolbar->addButtonInstance($button); - - $has_button = true; - } - } - - if (!$has_button && - strlen($this->object->getOutro()) == 0) - { - $this->exitSurvey(); - } - else - { - if($has_button) - { - $ilToolbar->addSeparator(); - } - - $button = ilLinkButton::getInstance(); - $button->setCaption("survey_execution_exit"); - $button->setUrl($this->ctrl->getLinkTarget($this, "exitSurvey")); - $ilToolbar->addButtonInstance($button); - - if(strlen($this->object->getOutro())) - { - include_once "Services/UIComponent/Panel/classes/class.ilPanelGUI.php"; - $panel = ilPanelGUI::getInstance(); - $panel->setBody($this->object->prepareTextareaOutput($this->object->getOutro())); - $this->tpl->setContent($panel->getHTML()); - } - } - } - - function backToRepository() - { - $tree = $this->tree; - - // #14971 - if($this->object->get360Mode()) - { - $target_ref_id = $this->object->getRefId(); - } - else - { - // #11534 - $target_ref_id = $tree->getParentId($this->object->getRefId()); - } - - include_once "Services/Link/classes/class.ilLink.php"; - ilUtil::redirect(ilLink::_getLink($target_ref_id)); - } - -/** -* Exits the survey after finishing it -* -* Exits the survey after finishing it -* -* @access public -*/ - function exitSurvey() - { - if(!$this->preview) - { - $this->backToRepository(); - } - else - { - // #12841 - $this->ctrl->setParameterByClass("ilsurveyeditorgui", "pgov", $_REQUEST["pgov"]); - $this->ctrl->redirectByClass(array("ilobjsurveygui", "ilsurveyeditorgui"), "questions"); - } - } - -/** -* Creates the navigation buttons for a survey -* -* Creates the navigation buttons for a survey. -* Runs twice to generate a top and a bottom navigation to -* ease the use of long forms. -* -* @access public -*/ - function outNavigationButtons($navigationblock = "top", $page) - { - $prevpage = $this->object->getNextPage($page[0]["question_id"], -1); - $this->tpl->setCurrentBlock($navigationblock . "_prev"); - if ($prevpage === 0) - { - $this->tpl->setVariable("BTN_PREV", $this->lng->txt("survey_start")); - } - else - { - $this->tpl->setVariable("BTN_PREV", $this->lng->txt("survey_previous")); - } - $this->tpl->parseCurrentBlock(); - $nextpage = $this->object->getNextPage($page[0]["question_id"], 1); - $this->tpl->setCurrentBlock($navigationblock . "_next"); - if ($nextpage === 1) - { - $this->tpl->setVariable("BTN_NEXT", $this->lng->txt("survey_finish")); - } - else - { - $this->tpl->setVariable("BTN_NEXT", $this->lng->txt("survey_next")); - } - $this->tpl->parseCurrentBlock(); - } - - function preview() - { - $this->outSurveyPage(); - } - - function viewUserResults() - { - $ilToolbar = $this->toolbar; - - if(!$this->object->hasViewOwnResults()) - { - $this->backToRepository(); - } - - $this->checkAuth(false, true); - - include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; - $button = ilLinkButton::getInstance(); - $button->setCaption("btn_back"); - $button->setUrl($this->ctrl->getLinkTarget($this, "runShowFinishedPage")); - $ilToolbar->addButtonInstance($button); - - $survey_gui = new ilObjSurveyGUI(); - $html = $survey_gui->getUserResultsTable($_SESSION["finished_id"][$this->object->getId()]); - $this->tpl->setContent($html); - } - - function mailUserResults() - { - $ilUser = $this->user; - - if(!$this->object->hasMailConfirmation()) - { - $this->backToRepository(); - } - - $this->checkAuth(false, true); - - $recipient = $_POST["mail"]; - if(!$recipient) - { - $recipient = $ilUser->getEmail(); - } - if(!ilUtil::is_email($recipient)) - { - $this->ctrl->redirect($this, "runShowFinishedPage"); - } - - $survey_gui = new ilObjSurveyGUI(); - $survey_gui->sendUserResultsMail( - $_SESSION["finished_id"][$this->object->getId()], - $recipient - ); - - ilUtil::sendSuccess($this->lng->txt("mail_sent"), true); - $this->ctrl->redirect($this, "runShowFinishedPage"); - } - - function showFinishConfirmation() - { - $tpl = $this->tpl; - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setHeaderText($this->lng->txt("survey_execution_sure_finish")); - - $cgui->setFormAction($this->ctrl->getFormAction($this, "confirmedFinish")); - $cgui->setCancel($this->lng->txt("cancel"), "previousNoSave"); - $cgui->setConfirm($this->lng->txt("confirm"), "confirmedFinish"); - - $tpl->setContent($cgui->getHTML()); - } - - function confirmedFinish() - { - $ilUser = $this->user; - - if(!$this->preview) - { - $this->object->finishSurvey($_SESSION["finished_id"][$this->object->getId()]); - - if($ilUser->getId() != ANONYMOUS_USER_ID) - { - include_once "Services/Tracking/classes/class.ilLPStatusWrapper.php"; - ilLPStatusWrapper::_updateStatus($this->object->getId(), $ilUser->getId()); - } - - if ($this->object->getMailNotification()) - { - $this->object->sendNotificationMail($ilUser->getId(), - $_SESSION["anonymous_id"][$this->object->getId()], - $_SESSION["appr_id"][$this->object->getId()]); - } - } - - /* - unset($_SESSION["anonymous_id"][$this->object->getId()]); - unset($_SESSION["appr_id"][$this->object->getId()]); - unset($_SESSION["finished_id"][$this->object->getId()]); - */ - - $this->ctrl->redirect($this, "runShowFinishedPage"); - } + + /** + * Saves the users input of the active page + * + * Saves the users input of the active page + * + * @access private + */ + public function saveActiveQuestionData(&$data) + { + $ilUser = $this->user; + + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + $question =&SurveyQuestion::_instanciateQuestion($data["question_id"]); + $error = $question->checkUserInput($_POST, $this->object->getSurveyId()); + if (strlen($error) == 0) { + if (!$this->preview) { + // delete old answers + $this->object->deleteWorkingData($data["question_id"], $_SESSION["finished_id"][$this->object->getId()]); + + $question->saveUserInput($_POST, $_SESSION["finished_id"][$this->object->getId()]); + } else { + $_SESSION["preview_data"][$this->object->getId()][$data["question_id"]] = + $question->saveUserInput($_POST, $_SESSION["finished_id"][$this->object->getId()], true); + } + return 0; + } else { + $_SESSION["svy_errors"][$question->getId()] = $error; + return 1; + } + } + + /** + * Called on cancel + * + * Called on cancel + * + * @access private + */ + public function cancel() + { + $this->ctrl->redirectByClass("ilobjsurveygui", "infoScreen"); + } + + /** + * Creates the finished page for a running survey + * + * Creates the finished page for a running survey + * + * @access public + */ + public function runShowFinishedPage() + { + $ilToolbar = $this->toolbar; + $ilUser = $this->user; + + $has_button = false; + + include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; + + if (!$this->preview) { + if ($this->object->hasViewOwnResults()) { + $button = ilLinkButton::getInstance(); + $button->setCaption("svy_view_own_results"); + $button->setUrl($this->ctrl->getLinkTarget($this, "viewUserResults")); + $ilToolbar->addButtonInstance($button); + + $has_button = true; + } + + if ($this->object->hasMailConfirmation()) { + if ($has_button) { + $ilToolbar->addSeparator(); + } + + if ($ilUser->getId() == ANONYMOUS_USER_ID || + !$ilUser->getEmail()) { + require_once "Services/Form/classes/class.ilTextInputGUI.php"; + $mail = new ilTextInputGUI($this->lng->txt("email"), "mail"); + $mail->setSize(25); + $ilToolbar->addInputItem($mail, true); + } + + $ilToolbar->setFormAction($this->ctrl->getFormAction($this, "mailUserResults")); + + include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; + $button = ilSubmitButton::getInstance(); + $button->setCaption("svy_mail_send_confirmation"); + $button->setCommand("mailUserResults"); + $ilToolbar->addButtonInstance($button); + + $has_button = true; + } + + // #6307 + include_once "Modules/Survey/classes/class.ilObjSurveyAccess.php"; + if (ilObjSurveyAccess::_hasEvaluationAccess($this->object->getId(), $ilUser->getId())) { + $button = ilLinkButton::getInstance(); + $button->setCaption("svy_results"); + $button->setUrl($this->ctrl->getLinkTargetByClass("ilObjSurveyGUI", "evaluation")); + $ilToolbar->addButtonInstance($button); + + $has_button = true; + } + } + + if (!$has_button && + strlen($this->object->getOutro()) == 0) { + $this->exitSurvey(); + } else { + if ($has_button) { + $ilToolbar->addSeparator(); + } + + $button = ilLinkButton::getInstance(); + $button->setCaption("survey_execution_exit"); + $button->setUrl($this->ctrl->getLinkTarget($this, "exitSurvey")); + $ilToolbar->addButtonInstance($button); + + if (strlen($this->object->getOutro())) { + include_once "Services/UIComponent/Panel/classes/class.ilPanelGUI.php"; + $panel = ilPanelGUI::getInstance(); + $panel->setBody($this->object->prepareTextareaOutput($this->object->getOutro())); + $this->tpl->setContent($panel->getHTML()); + } + } + } + + public function backToRepository() + { + $tree = $this->tree; + + // #14971 + if ($this->object->get360Mode()) { + $target_ref_id = $this->object->getRefId(); + } else { + // #11534 + $target_ref_id = $tree->getParentId($this->object->getRefId()); + } + + include_once "Services/Link/classes/class.ilLink.php"; + ilUtil::redirect(ilLink::_getLink($target_ref_id)); + } + + /** + * Exits the survey after finishing it + * + * Exits the survey after finishing it + * + * @access public + */ + public function exitSurvey() + { + if (!$this->preview) { + $this->backToRepository(); + } else { + // #12841 + $this->ctrl->setParameterByClass("ilsurveyeditorgui", "pgov", $_REQUEST["pgov"]); + $this->ctrl->redirectByClass(array("ilobjsurveygui", "ilsurveyeditorgui"), "questions"); + } + } + + /** + * Creates the navigation buttons for a survey + * + * Creates the navigation buttons for a survey. + * Runs twice to generate a top and a bottom navigation to + * ease the use of long forms. + * + * @access public + */ + public function outNavigationButtons($navigationblock = "top", $page) + { + $prevpage = $this->object->getNextPage($page[0]["question_id"], -1); + $this->tpl->setCurrentBlock($navigationblock . "_prev"); + if ($prevpage === 0) { + $this->tpl->setVariable("BTN_PREV", $this->lng->txt("survey_start")); + } else { + $this->tpl->setVariable("BTN_PREV", $this->lng->txt("survey_previous")); + } + $this->tpl->parseCurrentBlock(); + $nextpage = $this->object->getNextPage($page[0]["question_id"], 1); + $this->tpl->setCurrentBlock($navigationblock . "_next"); + if ($nextpage === 1) { + $this->tpl->setVariable("BTN_NEXT", $this->lng->txt("survey_finish")); + } else { + $this->tpl->setVariable("BTN_NEXT", $this->lng->txt("survey_next")); + } + $this->tpl->parseCurrentBlock(); + } + + public function preview() + { + $this->outSurveyPage(); + } + + public function viewUserResults() + { + $ilToolbar = $this->toolbar; + + if (!$this->object->hasViewOwnResults()) { + $this->backToRepository(); + } + + $this->checkAuth(false, true); + + include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; + $button = ilLinkButton::getInstance(); + $button->setCaption("btn_back"); + $button->setUrl($this->ctrl->getLinkTarget($this, "runShowFinishedPage")); + $ilToolbar->addButtonInstance($button); + + $survey_gui = new ilObjSurveyGUI(); + $html = $survey_gui->getUserResultsTable($_SESSION["finished_id"][$this->object->getId()]); + $this->tpl->setContent($html); + } + + public function mailUserResults() + { + $ilUser = $this->user; + + if (!$this->object->hasMailConfirmation()) { + $this->backToRepository(); + } + + $this->checkAuth(false, true); + + $recipient = $_POST["mail"]; + if (!$recipient) { + $recipient = $ilUser->getEmail(); + } + if (!ilUtil::is_email($recipient)) { + $this->ctrl->redirect($this, "runShowFinishedPage"); + } + + $survey_gui = new ilObjSurveyGUI(); + $survey_gui->sendUserResultsMail( + $_SESSION["finished_id"][$this->object->getId()], + $recipient + ); + + ilUtil::sendSuccess($this->lng->txt("mail_sent"), true); + $this->ctrl->redirect($this, "runShowFinishedPage"); + } + + public function showFinishConfirmation() + { + $tpl = $this->tpl; + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setHeaderText($this->lng->txt("survey_execution_sure_finish")); + + $cgui->setFormAction($this->ctrl->getFormAction($this, "confirmedFinish")); + $cgui->setCancel($this->lng->txt("cancel"), "previousNoSave"); + $cgui->setConfirm($this->lng->txt("confirm"), "confirmedFinish"); + + $tpl->setContent($cgui->getHTML()); + } + + public function confirmedFinish() + { + $ilUser = $this->user; + + if (!$this->preview) { + $this->object->finishSurvey($_SESSION["finished_id"][$this->object->getId()]); + + if ($ilUser->getId() != ANONYMOUS_USER_ID) { + include_once "Services/Tracking/classes/class.ilLPStatusWrapper.php"; + ilLPStatusWrapper::_updateStatus($this->object->getId(), $ilUser->getId()); + } + + if ($this->object->getMailNotification()) { + $this->object->sendNotificationMail( + $ilUser->getId(), + $_SESSION["anonymous_id"][$this->object->getId()], + $_SESSION["appr_id"][$this->object->getId()] + ); + } + } + + /* + unset($_SESSION["anonymous_id"][$this->object->getId()]); + unset($_SESSION["appr_id"][$this->object->getId()]); + unset($_SESSION["finished_id"][$this->object->getId()]); + */ + + $this->ctrl->redirect($this, "runShowFinishedPage"); + } } -?> \ No newline at end of file diff --git a/Modules/Survey/classes/class.ilSurveyExport.php b/Modules/Survey/classes/class.ilSurveyExport.php index a0495a038324e92340b51dbc6e5775ef6191d1f0..9bf3942efb5578271dfac986abfe2da4b15e68b0 100755 --- a/Modules/Survey/classes/class.ilSurveyExport.php +++ b/Modules/Survey/classes/class.ilSurveyExport.php @@ -1,24 +1,24 @@ database(); - - $this->survey_obj = $a_survey_obj; - - $this->db = $ilDB; - $this->mode = $a_mode; - $this->inst_id = IL_INST_ID; - - $date = time(); - switch($this->mode) - { - default: - $this->export_dir = $this->survey_obj->getExportDirectory(); - $this->subdir = $date."__".$this->inst_id."__". - "svy"."_".$this->survey_obj->getId(); - $this->filename = $this->subdir.".xml"; - break; - } - } - - function getInstId() - { - return $this->inst_id; - } + public $db; // database object + public $survey_obj; // survey object + public $inst_id; // installation id + public $mode; + public $subdir; + public $filename; + public $export_dir; + + /** + * Constructor + * @access public + */ + public function __construct($a_survey_obj, $a_mode = "xml") + { + global $DIC; + + $ilDB = $DIC->database(); + + $this->survey_obj = $a_survey_obj; + + $this->db = $ilDB; + $this->mode = $a_mode; + $this->inst_id = IL_INST_ID; + + $date = time(); + switch ($this->mode) { + default: + $this->export_dir = $this->survey_obj->getExportDirectory(); + $this->subdir = $date . "__" . $this->inst_id . "__" . + "svy" . "_" . $this->survey_obj->getId(); + $this->filename = $this->subdir . ".xml"; + break; + } + } + + public function getInstId() + { + return $this->inst_id; + } /** @@ -78,83 +77,74 @@ class ilSurveyExport * @access public * @return */ - function buildExportFile() - { - switch ($this->mode) - { - default: - return $this->buildExportFileXML(); - break; - } - } - - /** - * build xml export file - */ - function buildExportFileXML() - { - - // create directories - $this->survey_obj->createExportDirectory(); - ilUtil::makeDir($this->export_dir."/".$this->subdir); - ilUtil::makeDir($this->export_dir."/".$this->subdir."/objects"); - - // get Log File - $expDir = $this->survey_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"); - - // write xml file - $xmlFile = fopen($this->export_dir."/".$this->subdir."/".$this->filename, "w"); - fwrite($xmlFile, $this->survey_obj->toXML()); - fclose($xmlFile); - - // add media objects which were added with tiny mce - $this->exportXHTMLMediaObjects($this->export_dir."/".$this->subdir); - - // zip the file - ilUtil::zip($this->export_dir."/".$this->subdir, $this->export_dir."/".$this->subdir.".zip"); - - if (@file_exists($this->export_dir."/".$this->subdir.".zip")) - { - // remove export directory and contents - if (@is_dir($this->export_dir."/".$this->subdir)) - { - ilUtil::delDir($this->export_dir."/".$this->subdir); - } - } - $expLog->write(date("[y-m-d H:i:s] ")."Finished Export"); - - return $this->export_dir."/".$this->subdir.".zip"; - } - - function exportXHTMLMediaObjects($a_export_dir) - { - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - - $mobs = ilObjMediaObject::_getMobsOfObject("svy:html", $this->survey_obj->getId()); - foreach ($mobs as $mob) - { - $mob_obj = new ilObjMediaObject($mob); - $mob_obj->exportFiles($a_export_dir); - unset($mob_obj); - } - // #14850 - foreach ($this->survey_obj->questions as $question_id) - { - $mobs = ilObjMediaObject::_getMobsOfObject("spl:html", $question_id); - foreach ($mobs as $mob) - { - $mob_obj = new ilObjMediaObject($mob); - $mob_obj->exportFiles($a_export_dir); - unset($mob_obj); - } - } - } + public function buildExportFile() + { + switch ($this->mode) { + default: + return $this->buildExportFileXML(); + break; + } + } + /** + * build xml export file + */ + public function buildExportFileXML() + { + + // create directories + $this->survey_obj->createExportDirectory(); + ilUtil::makeDir($this->export_dir . "/" . $this->subdir); + ilUtil::makeDir($this->export_dir . "/" . $this->subdir . "/objects"); + + // get Log File + $expDir = $this->survey_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"); + + // write xml file + $xmlFile = fopen($this->export_dir . "/" . $this->subdir . "/" . $this->filename, "w"); + fwrite($xmlFile, $this->survey_obj->toXML()); + fclose($xmlFile); + + // add media objects which were added with tiny mce + $this->exportXHTMLMediaObjects($this->export_dir . "/" . $this->subdir); + + // zip the file + ilUtil::zip($this->export_dir . "/" . $this->subdir, $this->export_dir . "/" . $this->subdir . ".zip"); + + if (@file_exists($this->export_dir . "/" . $this->subdir . ".zip")) { + // remove export directory and contents + if (@is_dir($this->export_dir . "/" . $this->subdir)) { + ilUtil::delDir($this->export_dir . "/" . $this->subdir); + } + } + $expLog->write(date("[y-m-d H:i:s] ") . "Finished Export"); + + return $this->export_dir . "/" . $this->subdir . ".zip"; + } + + public function exportXHTMLMediaObjects($a_export_dir) + { + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + + $mobs = ilObjMediaObject::_getMobsOfObject("svy:html", $this->survey_obj->getId()); + foreach ($mobs as $mob) { + $mob_obj = new ilObjMediaObject($mob); + $mob_obj->exportFiles($a_export_dir); + unset($mob_obj); + } + // #14850 + foreach ($this->survey_obj->questions as $question_id) { + $mobs = ilObjMediaObject::_getMobsOfObject("spl:html", $question_id); + foreach ($mobs as $mob) { + $mob_obj = new ilObjMediaObject($mob); + $mob_obj->exportFiles($a_export_dir); + unset($mob_obj); + } + } + } } - -?> diff --git a/Modules/Survey/classes/class.ilSurveyExporter.php b/Modules/Survey/classes/class.ilSurveyExporter.php index 894b190cdc6a67008a4f2e6d8f657820d9ab62ae..7ade59c64a109626fbbb2be73f93afff538abf97 100644 --- a/Modules/Survey/classes/class.ilSurveyExporter.php +++ b/Modules/Survey/classes/class.ilSurveyExporter.php @@ -12,118 +12,108 @@ include_once("./Services/Export/classes/class.ilXmlExporter.php"); */ class ilSurveyExporter extends ilXmlExporter { - /** - * @var ilSurveyDataSet - */ - private $ds; + /** + * @var ilSurveyDataSet + */ + private $ds; - /** - * Initialisation - */ - function init() - { - include_once("./Modules/Survey/classes/class.ilSurveyDataSet.php"); - $this->ds = new ilSurveyDataSet(); - $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); - $this->ds->setDSPrefix("ds"); - } + /** + * Initialisation + */ + public function init() + { + include_once("./Modules/Survey/classes/class.ilSurveyDataSet.php"); + $this->ds = new ilSurveyDataSet(); + $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); + $this->ds->setDSPrefix("ds"); + } - /** - * Get xml representation - * - * @param string $a_enitity entity - * @param string $a_target_release target release - * @param string $a_id id - * @return string xml string - */ - public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) - { - if ($a_entity == "svy") - { - include_once './Modules/Survey/classes/class.ilObjSurvey.php'; - $svy = new ilObjSurvey($a_id, false); - $svy->loadFromDb(); + /** + * Get xml representation + * + * @param string $a_enitity entity + * @param string $a_target_release target release + * @param string $a_id id + * @return string xml string + */ + public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) + { + if ($a_entity == "svy") { + include_once './Modules/Survey/classes/class.ilObjSurvey.php'; + $svy = new ilObjSurvey($a_id, false); + $svy->loadFromDb(); - include_once("./Modules/Survey/classes/class.ilSurveyExport.php"); - $svy_exp = new ilSurveyExport($svy, 'xml'); - $zip = $svy_exp->buildExportFile(); + include_once("./Modules/Survey/classes/class.ilSurveyExport.php"); + $svy_exp = new ilSurveyExport($svy, 'xml'); + $zip = $svy_exp->buildExportFile(); - // Unzip, since survey deletes this dir - ilUtil::unzip($zip); + // Unzip, since survey deletes this dir + ilUtil::unzip($zip); - $GLOBALS['ilLog']->write(__METHOD__ . ': Created zip file ' . $zip); - return ""; - } - else - { - return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); - } - } + $GLOBALS['ilLog']->write(__METHOD__ . ': Created zip file ' . $zip); + return ""; + } else { + return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); + } + } - /** - * Get tail dependencies - * - * @param string $a_enitity entity - * @param string $a_target_release target release - * @param array $a_ids ids - * @return array array of array with keys "component", entity", "ids" - */ - function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) - { - if ($a_entity == "svy") - { - return array ( - array( - "component" => "Modules/Survey", - "entity" => "svy_quest_skill", - "ids" => $a_ids), - array( - "component" => "Modules/Survey", - "entity" => "svy_skill_threshold", - "ids" => $a_ids), - array( - "component" => "Services/Object", - "entity" => "common", - "ids" => $a_ids) - ); + /** + * Get tail dependencies + * + * @param string $a_enitity entity + * @param string $a_target_release target release + * @param array $a_ids ids + * @return array array of array with keys "component", entity", "ids" + */ + public function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) + { + if ($a_entity == "svy") { + return array( + array( + "component" => "Modules/Survey", + "entity" => "svy_quest_skill", + "ids" => $a_ids), + array( + "component" => "Modules/Survey", + "entity" => "svy_skill_threshold", + "ids" => $a_ids), + array( + "component" => "Services/Object", + "entity" => "common", + "ids" => $a_ids) + ); + } + return array(); + } - } - return array(); - } - - /** - * Returns schema versions that the component can export to. - * ILIAS chooses the first one, that has min/max constraints which - * fit to the target release. Please put the newest on top. - * - * @return - */ - function getValidSchemaVersions($a_entity) - { - if ($a_entity == "svy") - { - return array( - "4.1.0" => array( - "namespace" => "http://www.ilias.de/Modules/Survey/htlm/4_1", - "xsd_file" => "ilias_svy_4_1.xsd", - "uses_dataset" => false, - "min" => "4.1.0", - "max" => "") - ); - } - else - { - return array( - "5.1.0" => array( - "namespace" => "http://www.ilias.de/Modules/Survey/svy/5_1", - "xsd_file" => "ilias_svy_5_1.xsd", - "uses_dataset" => true, - "min" => "5.1.0", - "max" => "") - ); - } - } + /** + * Returns schema versions that the component can export to. + * ILIAS chooses the first one, that has min/max constraints which + * fit to the target release. Please put the newest on top. + * + * @return + */ + public function getValidSchemaVersions($a_entity) + { + if ($a_entity == "svy") { + return array( + "4.1.0" => array( + "namespace" => "http://www.ilias.de/Modules/Survey/htlm/4_1", + "xsd_file" => "ilias_svy_4_1.xsd", + "uses_dataset" => false, + "min" => "4.1.0", + "max" => "") + ); + } else { + return array( + "5.1.0" => array( + "namespace" => "http://www.ilias.de/Modules/Survey/svy/5_1", + "xsd_file" => "ilias_svy_5_1.xsd", + "uses_dataset" => true, + "min" => "5.1.0", + "max" => "") + ); + } + } } - -?> \ No newline at end of file diff --git a/Modules/Survey/classes/class.ilSurveyImportConfig.php b/Modules/Survey/classes/class.ilSurveyImportConfig.php index 44e9e8360a5d7b17c2774eaa522344a5f2cd0abc..990ba14a055f9112a2203615b753b6cd2fd72e60 100644 --- a/Modules/Survey/classes/class.ilSurveyImportConfig.php +++ b/Modules/Survey/classes/class.ilSurveyImportConfig.php @@ -12,25 +12,23 @@ include_once("./Services/Export/classes/class.ilImportConfig.php"); */ class ilSurveyImportConfig extends ilImportConfig { - protected $svy_qpl_id = -1; + protected $svy_qpl_id = -1; - /** - * Set survey question pool id - * @param integer $a_svy_qpl_id - */ - function setQuestionPoolID($a_svy_qpl_id) - { - $this->svy_qpl_id = $a_svy_qpl_id; - } - - /** - * Get survey question pool id - * @return integer survey pool id - */ - function getQuestionPoolID() - { - return $this->svy_qpl_id; - } + /** + * Set survey question pool id + * @param integer $a_svy_qpl_id + */ + public function setQuestionPoolID($a_svy_qpl_id) + { + $this->svy_qpl_id = $a_svy_qpl_id; + } + /** + * Get survey question pool id + * @return integer survey pool id + */ + public function getQuestionPoolID() + { + return $this->svy_qpl_id; + } } -?> \ No newline at end of file diff --git a/Modules/Survey/classes/class.ilSurveyImporter.php b/Modules/Survey/classes/class.ilSurveyImporter.php index f49d20ca5b9ba88e7a4341aa22a06b29e21a05fe..65ea61c45ffe1447bd3c8b23b42ed91010087aa7 100644 --- a/Modules/Survey/classes/class.ilSurveyImporter.php +++ b/Modules/Survey/classes/class.ilSurveyImporter.php @@ -12,75 +12,75 @@ include_once("./Services/Export/classes/class.ilXmlImporter.php"); */ class ilSurveyImporter extends ilXmlImporter { - /** - * @var Logger - */ - protected $log; - - - /** - * Constructor - */ - function __construct() - { - parent::__construct(); - global $DIC; - - $this->log = $DIC["ilLog"]; - } - - /** - * @var ilObjSurvey - */ - protected static $survey; - - /** - * @var ilLogger - */ - protected $svy_log; - - /** - * Init - * - * @param - * @return - */ - function init() - { - include_once("./Modules/Survey/classes/class.ilSurveyDataSet.php"); - $this->ds = new ilSurveyDataSet(); - $this->ds->setDSPrefix("ds"); - $this->ds->setImport($this); - - $this->svy_log = ilLoggerFactory::getLogger("svy"); - } - - - /** - * Set current survey object (being imported). This is done statically, - * since the survey import uses multiple input files being processed for every survey - * and all of these need the current survey object (ilSurveyImporter is intantiated multiple times) - * - * @param ilObjSurvey $a_val survey - */ - function setSurvey(ilObjSurvey $a_val) - { - self::$survey = $a_val; - } - - /** - * Get current survey object - * - * @return ilObjSurvey survey - */ - function getSurvey() - { - return self::$survey; - } - - /** - * Import XML - * + /** + * @var Logger + */ + protected $log; + + + /** + * Constructor + */ + public function __construct() + { + parent::__construct(); + global $DIC; + + $this->log = $DIC["ilLog"]; + } + + /** + * @var ilObjSurvey + */ + protected static $survey; + + /** + * @var ilLogger + */ + protected $svy_log; + + /** + * Init + * + * @param + * @return + */ + public function init() + { + include_once("./Modules/Survey/classes/class.ilSurveyDataSet.php"); + $this->ds = new ilSurveyDataSet(); + $this->ds->setDSPrefix("ds"); + $this->ds->setImport($this); + + $this->svy_log = ilLoggerFactory::getLogger("svy"); + } + + + /** + * Set current survey object (being imported). This is done statically, + * since the survey import uses multiple input files being processed for every survey + * and all of these need the current survey object (ilSurveyImporter is intantiated multiple times) + * + * @param ilObjSurvey $a_val survey + */ + public function setSurvey(ilObjSurvey $a_val) + { + self::$survey = $a_val; + } + + /** + * Get current survey object + * + * @return ilObjSurvey survey + */ + public function getSurvey() + { + return self::$survey; + } + + /** + * Import XML + * * @param $a_entity * @param $a_id * @param $a_xml @@ -90,135 +90,121 @@ class ilSurveyImporter extends ilXmlImporter * @throws ilImportException * @throws ilObjectNotFoundException */ - function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) - { - if ($a_entity == "svy") - { - // Container import => test object already created - if ($new_id = $a_mapping->getMapping('Services/Container', 'objs', $a_id)) - { - $newObj = ilObjectFactory::getInstanceByObjId($new_id, false); - #$newObj->setImportDirectory(dirname(rtrim($this->getImportDirectory(),'/'))); - } else // case ii, non container - { - $new_id = $a_mapping->getMapping("Modules/Survey", "svy", 0); - $newObj = ilObjectFactory::getInstanceByObjId($new_id, false); - } - $this->setSurvey($newObj); - - include_once "./Services/Survey/classes/class.SurveyImportParser.php"; - - list($xml_file) = $this->parseXmlFileNames(); - - if (!@file_exists($xml_file)) - { - $GLOBALS['ilLog']->write(__METHOD__ . ': Cannot find xml definition: ' . $xml_file); - return false; - } - $GLOBALS['ilLog']->write("getQuestionPoolID = ".$this->getImport()->getConfig("Modules/Survey")->getQuestionPoolID()); - - $import = new SurveyImportParser($this->getImport()->getConfig("Modules/Survey")->getQuestionPoolID(), $xml_file, true, $a_mapping); - - $import->setSurveyObject($newObj); - $import->startParsing(); - - $this->svy_log->debug("is array import_mob_xml: -".is_array($_SESSION["import_mob_xhtml"])."-"); - - // this is "written" by Services/Survey/classes/class.ilSurveyImportParser - if (is_array($_SESSION["import_mob_xhtml"])) - { - include_once "./Services/MediaObjects/classes/class.ilObjMediaObject.php"; - include_once "./Services/RTE/classes/class.ilRTE.php"; - include_once "./Modules/TestQuestionPool/classes/class.ilObjQuestionPool.php"; - foreach ($_SESSION["import_mob_xhtml"] as $mob) - { - $this->svy_log->debug("import mob xhtml, type: ".$mob["type"].", id: ".$mob["mob"]); - - if (!$mob["type"]) - { - $mob["type"] = "svy:html"; - } - - $importfile = dirname($xml_file) . "/" . $mob["uri"]; - $this->svy_log->debug("import file: ".$importfile); - - if (file_exists($importfile)) - { - $media_object = ilObjMediaObject::_saveTempFileAsMediaObject(basename($importfile), $importfile, false); - - // survey mob - if ($mob["type"] == "svy:html") - { - ilObjMediaObject::_saveUsage($media_object->getId(), "svy:html", $newObj->getId()); - $this->svy_log->debug("old introduction: ".$newObj->getIntroduction()); - $newObj->setIntroduction(str_replace("src=\"" . $mob["mob"] . "\"", "src=\"" . "il_" . IL_INST_ID . "_mob_" . $media_object->getId() . "\"", $newObj->getIntroduction())); - $newObj->setOutro(str_replace("src=\"" . $mob["mob"] . "\"", "src=\"" . "il_" . IL_INST_ID . "_mob_" . $media_object->getId() . "\"", $newObj->getOutro())); - - $this->svy_log->debug("new introduction: ".$newObj->getIntroduction()); - } - else if($import->questions[$mob["id"]]) - { - $new_qid = $import->questions[$mob["id"]]; - ilObjMediaObject::_saveUsage($media_object->getId(), $mob["type"], $new_qid); - $new_question = SurveyQuestion::_instanciateQuestion($new_qid); - $qtext = $new_question->getQuestiontext(); - - $this->svy_log->debug("old question text: ".$qtext); - - $qtext = ilRTE::_replaceMediaObjectImageSrc($qtext, 0); - $qtext = str_replace("src=\"" . $mob["mob"] . "\"", "src=\"" . "il_" . IL_INST_ID . "_mob_" . $media_object->getId() . "\"", $qtext); - $qtext = ilRTE::_replaceMediaObjectImageSrc($qtext, 1); - $new_question->setQuestiontext($qtext); - $new_question->saveToDb(); - - $this->svy_log->debug("new question text: ".$qtext); - - // also fix existing original in pool - if($new_question->getOriginalId()) - { - $pool_question = SurveyQuestion::_instanciateQuestion($new_question->getOriginalId()); - $pool_question->setQuestiontext($qtext); - $pool_question->saveToDb(); - } - } - } - else - { - $this->svy_log->error("Error: Could not open XHTML mob file for test introduction during test import. File $importfile does not exist!"); - } - } - $newObj->setIntroduction(ilRTE::_replaceMediaObjectImageSrc($newObj->getIntroduction(), 1)); - $newObj->setOutro(ilRTE::_replaceMediaObjectImageSrc($newObj->getOutro(), 1)); - $newObj->saveToDb(); - } - $a_mapping->addMapping("Modules/Survey", "svy", (int) $a_id, (int) $newObj->getId()); - return $newObj->getId(); - } - else - { - include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); - $parser = new ilDataSetImportParser($a_entity, $this->getSchemaVersion(), - $a_xml, $this->ds, $a_mapping); - } - - return true; - - } - - - /** - * Create qti and xml file name - * @return array - */ - protected function parseXmlFileNames() - { - $GLOBALS['ilLog']->write(__METHOD__.': '.$this->getImportDirectory()); - - $basename = basename($this->getImportDirectory()); - $xml = $this->getImportDirectory().'/'.$basename.'.xml'; - - return array($xml); - } + public function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) + { + if ($a_entity == "svy") { + // Container import => test object already created + if ($new_id = $a_mapping->getMapping('Services/Container', 'objs', $a_id)) { + $newObj = ilObjectFactory::getInstanceByObjId($new_id, false); + #$newObj->setImportDirectory(dirname(rtrim($this->getImportDirectory(),'/'))); + } else { // case ii, non container + $new_id = $a_mapping->getMapping("Modules/Survey", "svy", 0); + $newObj = ilObjectFactory::getInstanceByObjId($new_id, false); + } + $this->setSurvey($newObj); + + include_once "./Services/Survey/classes/class.SurveyImportParser.php"; + + list($xml_file) = $this->parseXmlFileNames(); + + if (!@file_exists($xml_file)) { + $GLOBALS['ilLog']->write(__METHOD__ . ': Cannot find xml definition: ' . $xml_file); + return false; + } + $GLOBALS['ilLog']->write("getQuestionPoolID = " . $this->getImport()->getConfig("Modules/Survey")->getQuestionPoolID()); + + $import = new SurveyImportParser($this->getImport()->getConfig("Modules/Survey")->getQuestionPoolID(), $xml_file, true, $a_mapping); + + $import->setSurveyObject($newObj); + $import->startParsing(); + + $this->svy_log->debug("is array import_mob_xml: -" . is_array($_SESSION["import_mob_xhtml"]) . "-"); + + // this is "written" by Services/Survey/classes/class.ilSurveyImportParser + if (is_array($_SESSION["import_mob_xhtml"])) { + include_once "./Services/MediaObjects/classes/class.ilObjMediaObject.php"; + include_once "./Services/RTE/classes/class.ilRTE.php"; + include_once "./Modules/TestQuestionPool/classes/class.ilObjQuestionPool.php"; + foreach ($_SESSION["import_mob_xhtml"] as $mob) { + $this->svy_log->debug("import mob xhtml, type: " . $mob["type"] . ", id: " . $mob["mob"]); + + if (!$mob["type"]) { + $mob["type"] = "svy:html"; + } + + $importfile = dirname($xml_file) . "/" . $mob["uri"]; + $this->svy_log->debug("import file: " . $importfile); + + if (file_exists($importfile)) { + $media_object = ilObjMediaObject::_saveTempFileAsMediaObject(basename($importfile), $importfile, false); + + // survey mob + if ($mob["type"] == "svy:html") { + ilObjMediaObject::_saveUsage($media_object->getId(), "svy:html", $newObj->getId()); + $this->svy_log->debug("old introduction: " . $newObj->getIntroduction()); + $newObj->setIntroduction(str_replace("src=\"" . $mob["mob"] . "\"", "src=\"" . "il_" . IL_INST_ID . "_mob_" . $media_object->getId() . "\"", $newObj->getIntroduction())); + $newObj->setOutro(str_replace("src=\"" . $mob["mob"] . "\"", "src=\"" . "il_" . IL_INST_ID . "_mob_" . $media_object->getId() . "\"", $newObj->getOutro())); + + $this->svy_log->debug("new introduction: " . $newObj->getIntroduction()); + } elseif ($import->questions[$mob["id"]]) { + $new_qid = $import->questions[$mob["id"]]; + ilObjMediaObject::_saveUsage($media_object->getId(), $mob["type"], $new_qid); + $new_question = SurveyQuestion::_instanciateQuestion($new_qid); + $qtext = $new_question->getQuestiontext(); + + $this->svy_log->debug("old question text: " . $qtext); + + $qtext = ilRTE::_replaceMediaObjectImageSrc($qtext, 0); + $qtext = str_replace("src=\"" . $mob["mob"] . "\"", "src=\"" . "il_" . IL_INST_ID . "_mob_" . $media_object->getId() . "\"", $qtext); + $qtext = ilRTE::_replaceMediaObjectImageSrc($qtext, 1); + $new_question->setQuestiontext($qtext); + $new_question->saveToDb(); + + $this->svy_log->debug("new question text: " . $qtext); + + // also fix existing original in pool + if ($new_question->getOriginalId()) { + $pool_question = SurveyQuestion::_instanciateQuestion($new_question->getOriginalId()); + $pool_question->setQuestiontext($qtext); + $pool_question->saveToDb(); + } + } + } else { + $this->svy_log->error("Error: Could not open XHTML mob file for test introduction during test import. File $importfile does not exist!"); + } + } + $newObj->setIntroduction(ilRTE::_replaceMediaObjectImageSrc($newObj->getIntroduction(), 1)); + $newObj->setOutro(ilRTE::_replaceMediaObjectImageSrc($newObj->getOutro(), 1)); + $newObj->saveToDb(); + } + $a_mapping->addMapping("Modules/Survey", "svy", (int) $a_id, (int) $newObj->getId()); + return $newObj->getId(); + } else { + include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); + $parser = new ilDataSetImportParser( + $a_entity, + $this->getSchemaVersion(), + $a_xml, + $this->ds, + $a_mapping + ); + } + + return true; + } + + + /** + * Create qti and xml file name + * @return array + */ + protected function parseXmlFileNames() + { + $GLOBALS['ilLog']->write(__METHOD__ . ': ' . $this->getImportDirectory()); + + $basename = basename($this->getImportDirectory()); + $xml = $this->getImportDirectory() . '/' . $basename . '.xml'; + + return array($xml); + } } - -?> \ No newline at end of file diff --git a/Modules/Survey/classes/class.ilSurveyLP.php b/Modules/Survey/classes/class.ilSurveyLP.php index 39988386490a2d1c9394f1c20a67521f82146da1..416dbbcf68afbb58f2f3827703b216d31fdeb16c 100644 --- a/Modules/Survey/classes/class.ilSurveyLP.php +++ b/Modules/Survey/classes/class.ilSurveyLP.php @@ -5,59 +5,56 @@ include_once "Services/Object/classes/class.ilObjectLP.php"; /** * Survey to lp connector - * + * * @author Jörg Lützenkirchen * @version $Id: class.ilLPStatusPlugin.php 43734 2013-07-29 15:27:58Z jluetzen $ * @package ModulesSurvey */ class ilSurveyLP extends ilObjectLP { - public static function getDefaultModes($a_lp_active) - { - return array( - ilLPObjSettings::LP_MODE_DEACTIVATED, - ilLPObjSettings::LP_MODE_SURVEY_FINISHED - ); - } - - public function getDefaultMode() - { - return ilLPObjSettings::LP_MODE_DEACTIVATED; // :TODO: - } - - public function getValidModes() - { - return array( - ilLPObjSettings::LP_MODE_DEACTIVATED, - ilLPObjSettings::LP_MODE_SURVEY_FINISHED - ); - } - - public function isAnonymized() - { - include_once './Modules/Survey/classes/class.ilObjSurveyAccess.php'; - return (bool)ilObjSurveyAccess::_lookupAnonymize($this->obj_id); - } + public static function getDefaultModes($a_lp_active) + { + return array( + ilLPObjSettings::LP_MODE_DEACTIVATED, + ilLPObjSettings::LP_MODE_SURVEY_FINISHED + ); + } + + public function getDefaultMode() + { + return ilLPObjSettings::LP_MODE_DEACTIVATED; // :TODO: + } + + public function getValidModes() + { + return array( + ilLPObjSettings::LP_MODE_DEACTIVATED, + ilLPObjSettings::LP_MODE_SURVEY_FINISHED + ); + } + + public function isAnonymized() + { + include_once './Modules/Survey/classes/class.ilObjSurveyAccess.php'; + return (bool) ilObjSurveyAccess::_lookupAnonymize($this->obj_id); + } - protected static function isLPMember(array &$a_res, $a_usr_id, $a_obj_ids) - { - global $DIC; + protected static function isLPMember(array &$a_res, $a_usr_id, $a_obj_ids) + { + global $DIC; - $ilDB = $DIC->database(); - - // if active id - $set = $ilDB->query("SELECT ss.obj_fi". - " FROM svy_finished sf". - " JOIN svy_svy ss ON (ss.survey_id = sf.survey_fi)". - " WHERE ".$ilDB->in("ss.obj_fi", $a_obj_ids, "", "integer"). - " AND sf.user_fi = ".$ilDB->quote($a_usr_id, "integer")); - while($row = $ilDB->fetchAssoc($set)) - { - $a_res[$row["obj_fi"]] = true; - } - - return true; - } + $ilDB = $DIC->database(); + + // if active id + $set = $ilDB->query("SELECT ss.obj_fi" . + " FROM svy_finished sf" . + " JOIN svy_svy ss ON (ss.survey_id = sf.survey_fi)" . + " WHERE " . $ilDB->in("ss.obj_fi", $a_obj_ids, "", "integer") . + " AND sf.user_fi = " . $ilDB->quote($a_usr_id, "integer")); + while ($row = $ilDB->fetchAssoc($set)) { + $a_res[$row["obj_fi"]] = true; + } + + return true; + } } - -?> \ No newline at end of file diff --git a/Modules/Survey/classes/class.ilSurveyMailTemplateReminderContext.php b/Modules/Survey/classes/class.ilSurveyMailTemplateReminderContext.php index ef3d491db6cfae807b1c3ca62b036d7d514f9268..920c66836fecae48c59c40ea7f80a70d151c452b 100644 --- a/Modules/Survey/classes/class.ilSurveyMailTemplateReminderContext.php +++ b/Modules/Survey/classes/class.ilSurveyMailTemplateReminderContext.php @@ -5,119 +5,115 @@ include_once './Services/Mail/classes/class.ilMailTemplateContext.php'; /** * Handles survey reminder mail placeholders - * + * * @author Jörg Lützenkirchen * @package ModulesSurvey */ class ilSurveyMailTemplateReminderContext extends ilMailTemplateContext { - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilObjectDataCache - */ - protected $obj_data_cache; - - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - if (isset($DIC["ilObjDataCache"])) - { - $this->obj_data_cache = $DIC["ilObjDataCache"]; - } - } - - const ID = 'svy_context_rmd'; - - /** - * @return string - */ - public function getId() - { - return self::ID; - } - - /** - * @return string - */ - public function getTitle() - { - $lng = $this->lng; - - $lng->loadLanguageModule('survey'); - - return $lng->txt('svy_mail_context_reminder_title'); - } - - /** - * @return string - */ - public function getDescription() - { - $lng = $this->lng; - - $lng->loadLanguageModule('survey'); - - return $lng->txt('svy_mail_context_reminder_info'); - } - - /** - * Return an array of placeholders - * @return array - */ - public function getSpecificPlaceholders() - { - /** - * @var $lng ilLanguage - */ - $lng = $this->lng; - - $lng->loadLanguageModule('survey'); - - $placeholders = array(); - - $placeholders['svy_title'] = array( - 'placeholder' => 'SURVEY_TITLE', - 'label' => $lng->txt('svy_mail_context_reminder_survey_title') - ); - - $placeholders['svy_link'] = array( - 'placeholder' => 'SURVEY_LINK', - 'label' => $lng->txt('perma_link') - ); - - return $placeholders; - } - - /** - * {@inheritdoc} - */ - public function resolveSpecificPlaceholder($placeholder_id, array $context_parameters, ilObjUser $recipient = null, $html_markup = false) - { - /** - * @var $ilObjDataCache ilObjectDataCache - */ - $ilObjDataCache = $this->obj_data_cache; - - if('svy_title' == $placeholder_id) - { - return $ilObjDataCache->lookupTitle($ilObjDataCache->lookupObjId($context_parameters['ref_id'])); - } - else if('svy_link' == $placeholder_id) - { - require_once './Services/Link/classes/class.ilLink.php'; - return ilLink::_getLink($context_parameters['ref_id'], 'svy'); - } - - return ''; - } -} \ No newline at end of file + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilObjectDataCache + */ + protected $obj_data_cache; + + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + if (isset($DIC["ilObjDataCache"])) { + $this->obj_data_cache = $DIC["ilObjDataCache"]; + } + } + + const ID = 'svy_context_rmd'; + + /** + * @return string + */ + public function getId() + { + return self::ID; + } + + /** + * @return string + */ + public function getTitle() + { + $lng = $this->lng; + + $lng->loadLanguageModule('survey'); + + return $lng->txt('svy_mail_context_reminder_title'); + } + + /** + * @return string + */ + public function getDescription() + { + $lng = $this->lng; + + $lng->loadLanguageModule('survey'); + + return $lng->txt('svy_mail_context_reminder_info'); + } + + /** + * Return an array of placeholders + * @return array + */ + public function getSpecificPlaceholders() + { + /** + * @var $lng ilLanguage + */ + $lng = $this->lng; + + $lng->loadLanguageModule('survey'); + + $placeholders = array(); + + $placeholders['svy_title'] = array( + 'placeholder' => 'SURVEY_TITLE', + 'label' => $lng->txt('svy_mail_context_reminder_survey_title') + ); + + $placeholders['svy_link'] = array( + 'placeholder' => 'SURVEY_LINK', + 'label' => $lng->txt('perma_link') + ); + + return $placeholders; + } + + /** + * {@inheritdoc} + */ + public function resolveSpecificPlaceholder($placeholder_id, array $context_parameters, ilObjUser $recipient = null, $html_markup = false) + { + /** + * @var $ilObjDataCache ilObjectDataCache + */ + $ilObjDataCache = $this->obj_data_cache; + + if ('svy_title' == $placeholder_id) { + return $ilObjDataCache->lookupTitle($ilObjDataCache->lookupObjId($context_parameters['ref_id'])); + } elseif ('svy_link' == $placeholder_id) { + require_once './Services/Link/classes/class.ilLink.php'; + return ilLink::_getLink($context_parameters['ref_id'], 'svy'); + } + + return ''; + } +} diff --git a/Modules/Survey/classes/class.ilSurveyPageGUI.php b/Modules/Survey/classes/class.ilSurveyPageGUI.php index 6e7c3e9fe171eb5495ac0b59186be1689b9c981e..f2a33d9164e1fdb25830e76ca7a581886789ca4e 100644 --- a/Modules/Survey/classes/class.ilSurveyPageGUI.php +++ b/Modules/Survey/classes/class.ilSurveyPageGUI.php @@ -11,1921 +11,1760 @@ * * @ingroup ModulesSurvey */ -class ilSurveyPageGUI +class ilSurveyPageGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilDB - */ - protected $db; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilObjUser - */ - protected $user; - - protected $ref_id; // [int] - protected $lng; // [object] - protected $object; // [ilObjSurvey] - protected $editor_gui; // [ilSurveyEditorGUI] - protected $current_page; // [int] - protected $has_previous_page; // [bool] - protected $has_next_page; // [bool] - protected $has_datasets; // [bool] - protected $use_pool; // [bool] - - /** - * @var ilLogger - */ - protected $log; - - /** - * Constructor - * - * @param ilObjSurvey $a_survey - * @param ilSurveyEditorGUI $a_survey_editor_gui - */ - function __construct(ilObjSurvey $a_survey, ilSurveyEditorGUI $a_survey_editor_gui) - { - global $DIC; - - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->db = $DIC->database(); - $this->tabs = $DIC->tabs(); - $this->tpl = $DIC["tpl"]; - $this->toolbar = $DIC->toolbar(); - $this->user = $DIC->user(); - $this->editor_gui = $a_survey_editor_gui; - $this->ref_id = $a_survey->getRefId(); - $this->object = $a_survey; - $this->log = ilLoggerFactory::getLogger("svy"); - } - - /** - * Routing - */ - function executeCommand() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $rbacsystem = $this->rbacsystem; - - $cmd = $ilCtrl->getCmd("renderPage"); - $next_class = $ilCtrl->getNextClass($this); - - switch($next_class) - { - default: - $this->determineCurrentPage(); - - $has_content = false; - - if($rbacsystem->checkAccess("write", $this->ref_id)) - { - // add page? - if($_REQUEST["new_id"]) - { - $this->insertNewQuestion($_REQUEST["new_id"]); - } - - // subcommands - if($_REQUEST["il_hform_subcmd"]) - { - $subcmd = $_REQUEST["il_hform_subcmd"]; - - // make sure that it is set for current and next requests - $ilCtrl->setParameter($this->editor_gui, "pgov", $this->current_page); - $_REQUEST["pgov"] = $this->current_page; - - $id = explode("_", $_REQUEST["il_hform_node"]); - $id = (int)$id[1]; - - // multi operation - if(substr($_REQUEST["il_hform_subcmd"], 0, 5) == "multi") - { - if($_REQUEST["il_hform_multi"]) - { - // removing types as we only allow questions anyway - $id = array(); - foreach(explode(";", $_REQUEST["il_hform_multi"]) as $item) - { - $id[] = (int)array_pop(explode("_", $item)); - } - - if($subcmd == "multiDelete") - { - $subcmd = "deleteQuestion"; - } - } - else - { - // #9525 - if($subcmd == "multiDelete") - { - ilUtil::sendFailure($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "renderPage"); - } - else - { - ilUtil::sendFailure($lng->txt("no_checkbox")); - } - } - } - - if(substr($subcmd, 0, 11) == "addQuestion") - { - $type = explode("_", $subcmd); - $type = (int)$type[1]; - $has_content = $this->addQuestion($type, $this->object->isPoolActive(), $id, $_REQUEST["il_hform_node"]); - } - else - { - $has_content = $this->$subcmd($id, $_REQUEST["il_hform_node"]); - } - } - } - - if(!$has_content) - { - $this->$cmd(); - } - break; - } - } - - /** - * determine current page - */ - public function determineCurrentPage() - { - $current_page = (int)$_REQUEST["jump"]; - if(!$current_page) - { - $current_page = (int)$_REQUEST["pgov"]; - } - if(!$current_page) - { - $current_page = (int)$_REQUEST["pg"]; - } - if(!$current_page) - { - $current_page = 1; - } - $this->current_page = $current_page; - } - - /** + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilDB + */ + protected $db; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilObjUser + */ + protected $user; + + protected $ref_id; // [int] + protected $lng; // [object] + protected $object; // [ilObjSurvey] + protected $editor_gui; // [ilSurveyEditorGUI] + protected $current_page; // [int] + protected $has_previous_page; // [bool] + protected $has_next_page; // [bool] + protected $has_datasets; // [bool] + protected $use_pool; // [bool] + + /** + * @var ilLogger + */ + protected $log; + + /** + * Constructor + * + * @param ilObjSurvey $a_survey + * @param ilSurveyEditorGUI $a_survey_editor_gui + */ + public function __construct(ilObjSurvey $a_survey, ilSurveyEditorGUI $a_survey_editor_gui) + { + global $DIC; + + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->db = $DIC->database(); + $this->tabs = $DIC->tabs(); + $this->tpl = $DIC["tpl"]; + $this->toolbar = $DIC->toolbar(); + $this->user = $DIC->user(); + $this->editor_gui = $a_survey_editor_gui; + $this->ref_id = $a_survey->getRefId(); + $this->object = $a_survey; + $this->log = ilLoggerFactory::getLogger("svy"); + } + + /** + * Routing + */ + public function executeCommand() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $rbacsystem = $this->rbacsystem; + + $cmd = $ilCtrl->getCmd("renderPage"); + $next_class = $ilCtrl->getNextClass($this); + + switch ($next_class) { + default: + $this->determineCurrentPage(); + + $has_content = false; + + if ($rbacsystem->checkAccess("write", $this->ref_id)) { + // add page? + if ($_REQUEST["new_id"]) { + $this->insertNewQuestion($_REQUEST["new_id"]); + } + + // subcommands + if ($_REQUEST["il_hform_subcmd"]) { + $subcmd = $_REQUEST["il_hform_subcmd"]; + + // make sure that it is set for current and next requests + $ilCtrl->setParameter($this->editor_gui, "pgov", $this->current_page); + $_REQUEST["pgov"] = $this->current_page; + + $id = explode("_", $_REQUEST["il_hform_node"]); + $id = (int) $id[1]; + + // multi operation + if (substr($_REQUEST["il_hform_subcmd"], 0, 5) == "multi") { + if ($_REQUEST["il_hform_multi"]) { + // removing types as we only allow questions anyway + $id = array(); + foreach (explode(";", $_REQUEST["il_hform_multi"]) as $item) { + $id[] = (int) array_pop(explode("_", $item)); + } + + if ($subcmd == "multiDelete") { + $subcmd = "deleteQuestion"; + } + } else { + // #9525 + if ($subcmd == "multiDelete") { + ilUtil::sendFailure($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "renderPage"); + } else { + ilUtil::sendFailure($lng->txt("no_checkbox")); + } + } + } + + if (substr($subcmd, 0, 11) == "addQuestion") { + $type = explode("_", $subcmd); + $type = (int) $type[1]; + $has_content = $this->addQuestion($type, $this->object->isPoolActive(), $id, $_REQUEST["il_hform_node"]); + } else { + $has_content = $this->$subcmd($id, $_REQUEST["il_hform_node"]); + } + } + } + + if (!$has_content) { + $this->$cmd(); + } + break; + } + } + + /** + * determine current page + */ + public function determineCurrentPage() + { + $current_page = (int) $_REQUEST["jump"]; + if (!$current_page) { + $current_page = (int) $_REQUEST["pgov"]; + } + if (!$current_page) { + $current_page = (int) $_REQUEST["pg"]; + } + if (!$current_page) { + $current_page = 1; + } + $this->current_page = $current_page; + } + + /** * Add new question to survey (database part) - * - * @param int $a_new_id - * @param bool $a_duplicate - * @todo: move out of GUI class, see also ilObjSurvey->insertQuestion - */ - protected function appendNewQuestionToSurvey($a_new_id, $a_duplicate = true, $a_force_duplicate = false) - { - $ilDB = $this->db; - - $this->log->debug("append question, id: ".$a_new_id.", duplicate: ".$a_duplicate.", force: ".$a_force_duplicate); - - // get maximum sequence index in test - $result = $ilDB->queryF("SELECT survey_question_id FROM svy_svy_qst WHERE survey_fi = %s", - array('integer'), - array($this->object->getSurveyId()) - ); - $sequence = $result->numRows(); - - // create duplicate if pool question (or forced for question blocks copy) - if($a_duplicate) - { - // this does nothing if this is not a pool question and $a_force_duplicate is false - $survey_question_id = $this->object->duplicateQuestionForSurvey($a_new_id, $a_force_duplicate); - } - // used by copy & paste - else - { - $survey_question_id = $a_new_id; - } - - // check if question is not already in the survey, see #22018 - if ($this->object->isQuestionInSurvey($survey_question_id)) - { - return $survey_question_id; - } - - // append to survey - $next_id = $ilDB->nextId('svy_svy_qst'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_svy_qst (survey_question_id, survey_fi,". - "question_fi, sequence, tstamp) VALUES (%s, %s, %s, %s, %s)", - array('integer', 'integer', 'integer', 'integer', 'integer'), - array($next_id, $this->object->getSurveyId(), $survey_question_id, $sequence, time()) - ); - - $this->log->debug("insert svy_svy_qst, id: ".$next_id.", qfi: ".$survey_question_id.", seq: ".$sequence); - - return $survey_question_id; - } - - /** - * Add new question to survey - * - * @param int $a_new_id - */ - public function insertNewQuestion($a_new_id) - { - $rbacsystem = $this->rbacsystem; - $ilDB = $this->db; - $lng = $this->lng; - - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - if (!SurveyQuestion::_isComplete($a_new_id)) - { - ilUtil::sendFailure($lng->txt("survey_error_insert_incomplete_question")); - } - else - { - $a_new_id = $this->appendNewQuestionToSurvey($a_new_id); - $this->object->loadQuestionsFromDb(); - - $pos = $_REQUEST["pgov_pos"]; - - // a[fter]/b[efore] on same page - if(substr($pos, -1) != "c") - { - // block handling - $current = $this->object->getSurveyPages(); - $current = $current[$this->current_page-1]; - if(sizeof($current) == 1) - { - // as questions are moved to first block question - // always use existing as first - // the new question is moved later on (see below) - $this->object->createQuestionblock($this->getAutoBlockTitle(), true, false, - array((int)$pos, $a_new_id)); - } - else - { - $block_id = array_pop($current); - $block_id = $block_id["questionblock_id"]; - - $this->object->addQuestionToBlock($a_new_id, $block_id); - } - } - // c: as new page (from toolbar/pool) - else - { - // after given question - if((int)$pos) - { - $pos = (int)$pos."a"; - $this->current_page++; - } - // at the beginning - else - { - $first = $this->object->getSurveyPages(); - $first = $first[0]; - $first = array_shift($first); - $pos = $first["question_id"]."b"; - $this->current_page = 1; - } - } - - // move to target position - $this->object->moveQuestions(array($a_new_id), (int)$pos, - ((substr($pos, -1) == "a") ? 1 : 0)); - - $this->object->fixSequenceStructure(); - } - } - - /** - * Copy and insert questions from block - * - * @param int $a_block_id - */ - public function insertQuestionBlock($a_block_id) - { - $new_ids = array(); - $question_ids = $this->object->getQuestionblockQuestionIds($a_block_id); - foreach($question_ids as $qid) - { - $new_ids[] = $this->appendNewQuestionToSurvey($qid, true, true); - } - - if(sizeof($new_ids)) - { - $this->object->loadQuestionsFromDb(); - - $pos = $_REQUEST["pgov_pos"]; - - // a[fter]/b[efore] on same page - if(substr($pos, -1) != "c") - { - // block handling - $current = $this->object->getSurveyPages(); - $current = $current[$this->current_page-1]; - if(sizeof($current) == 1) - { - // as questions are moved to first block question - // always use existing as first - // the new question is moved later on (see below) - $this->object->createQuestionblock($this->getAutoBlockTitle(), true, false, - array((int)$pos)+$new_ids); - } - else - { - $block_id = array_pop($current); - $block_id = $block_id["questionblock_id"]; - - foreach($new_ids as $qid) - { - $this->object->addQuestionToBlock($qid, $block_id); - } - } - } - // c: as new page (from toolbar/pool) - else - { - // re-create block - $this->object->createQuestionblock($this->getAutoBlockTitle(), true, false, - $new_ids); - - // after given question - if((int)$pos) - { - $pos = (int)$pos."a"; - } - // at the beginning - else - { - $first = $this->object->getSurveyPages(); - $first = $first[0]; - $first = array_shift($first); - $pos = $first["question_id"]."b"; - } - } - - // move to target position - $this->object->moveQuestions($new_ids, (int)$pos, - ((substr($pos, -1) == "a") ? 1 : 0)); - } - } - - /** - * Call add question to survey form - * - * @param int $a_type question type - * @param bool $a_use_pool add question to pool - * @param int $a_pos target position - * @param string $a_special_position special positions (toolbar | page_end) - */ - protected function addQuestion($a_type, $a_use_pool, $a_pos, $a_special_position) - { - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - // get translated type - include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"; - $questiontypes = ilObjSurveyQuestionPool::_getQuestiontypes(); - foreach($questiontypes as $item) - { - if($item["questiontype_id"] == $a_type) - { - $type_trans = $item["type_tag"]; - } - } - - $id = $a_pos; - - // new page behind current (from toolbar) - if($a_special_position == "toolbar") - { - $id = $this->object->getSurveyPages(); - if($a_pos && $a_pos != "fst") - { - $id = $id[$a_pos-1]; - $id = array_pop($id); - $id = $id["question_id"]."c"; - } - else - { - $id = "0c"; - } - } - // append current page - else if($a_special_position == "page_end") - { - $id = $this->object->getSurveyPages(); - $id = $id[$this->current_page-1]; - $id = array_pop($id); - $id = $id["question_id"]."a"; - } - else - { - $id .= "b"; - } - - if($a_use_pool) - { - $_GET["sel_question_types"] = $type_trans; - $_REQUEST["pgov_pos"] = $id; - $ilCtrl->setParameter($this->editor_gui, "pgov_pos", $id); - if(!$_POST["usage"]) - { - $ilTabs->clearSubTabs(); // #17193 - $this->editor_gui->createQuestionObject(); - } - else - { - $this->editor_gui->executeCreateQuestionObject(); - } - return true; - } - else - { - // create question and redirect to question form - - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php"; - $q_gui = SurveyQuestionGUI::_getQuestionGUI($type_trans); - $q_gui->object->setObjId($this->object->getId()); - $q_gui->object->createNewQuestion(); - $q_gui_class = get_class($q_gui); - - // #12531 - $ilCtrl->setParameterByClass($q_gui_class, "pgov", $this->current_page); - $ilCtrl->setParameterByClass($q_gui_class, "pgov_pos",$id); - $ilCtrl->setParameterByClass($q_gui_class, "ref_id", $this->ref_id); - $ilCtrl->setParameterByClass($q_gui_class, "new_for_survey", $this->ref_id); - $ilCtrl->setParameterByClass($q_gui_class, "q_id", $q_gui->object->getId()); - $ilCtrl->setParameterByClass($q_gui_class, "sel_question_types", $q_gui->getQuestionType()); - $ilCtrl->redirectByClass($q_gui_class, "editQuestion"); - } - } - - /** - * Add question to be cut to clipboard - * - * @param int $a_id question id - */ - protected function cutQuestion($a_id) - { - $lng = $this->lng; - - ilUtil::sendSuccess($lng->txt("survey_questions_to_clipboard_cut")); - $this->suppress_clipboard_msg = true; - - $_SESSION["survey_page_view"][$this->ref_id]["clipboard"] = array( - "source" => $this->current_page, - "nodes" => array($a_id), - "mode" => "cut"); - } - - /** - * Add question to be copied to clipboard - * - * @param int $a_id question id - */ - protected function copyQuestion($a_id) - { - $lng = $this->lng; - - ilUtil::sendSuccess($lng->txt("survey_questions_to_clipboard_copy")); - $this->suppress_clipboard_msg = true; - - $_SESSION["survey_page_view"][$this->ref_id]["clipboard"] = array( - "source" => $this->current_page, - "nodes" => array($a_id), - "mode" => "copy"); - } - - /** - * Add questions to be cut to clipboard - * - * @param array $a_id question ids - */ - protected function multiCut($a_id) - { - $lng = $this->lng; - - if (is_array($a_id)) - { - ilUtil::sendSuccess($lng->txt("survey_questions_to_clipboard_cut")); - $this->suppress_clipboard_msg = true; - - $_SESSION["survey_page_view"][$this->ref_id]["clipboard"] = array( - "source" => $this->current_page, - "nodes" => $a_id, - "mode" => "cut"); - } - } - - /** - * Add questions to be copied to clipboard - * - * @param array $a_id question ids - */ - protected function multiCopy($a_id) - { - $lng = $this->lng; - - if (is_array($a_id)) - { - ilUtil::sendSuccess($lng->txt("survey_questions_to_clipboard_copy")); - $this->suppress_clipboard_msg = true; - - $_SESSION["survey_page_view"][$this->ref_id]["clipboard"] = array( - "source" => $this->current_page, - "nodes" => $a_id, - "mode" => "copy"); - } - } - - /** - * Empty clipboard - */ - protected function clearClipboard() - { - $_SESSION["survey_page_view"][$this->ref_id]["clipboard"] = null; - } - - /** - * Paste from clipboard - * - * @param int $a_id target position - */ - protected function paste($a_id) - { - $data = $_SESSION["survey_page_view"][$this->ref_id]["clipboard"]; - $pages = $this->object->getSurveyPages(); - $source = $pages[$data["source"]-1]; - $target = $pages[$this->current_page-1]; - - // #12558 - use order of source page - $nodes = array(); - foreach($source as $src_qst) - { - if(in_array($src_qst["question_id"], $data["nodes"])) - { - $nodes[] = $src_qst["question_id"]; - } - } - - // append to last position? - $pos = 0; - if($_REQUEST["il_hform_node"] == "page_end") - { - $a_id = $target; - $a_id = array_pop($a_id); - $a_id = $a_id["question_id"]; - $pos = 1; - } - - // cut - if($data["mode"] == "cut") - { - // special case: paste cut on same page (no block handling needed) - if($data["source"] == $this->current_page) - { - // re-order nodes in page - if(sizeof($nodes) <= sizeof($source)) - { - $this->object->moveQuestions($nodes, $a_id, $pos); - } - $this->clearClipboard(); - return; - } - else - { - // only if source has block - $source_block_id = false; - if(sizeof($source) > 1) - { - $source_block_id = $source; - $source_block_id = array_shift($source_block_id); - $source_block_id = $source_block_id["questionblock_id"]; - - // remove from block - if(sizeof($source) > sizeof($nodes)) - { - foreach($nodes as $qid) - { - $this->object->removeQuestionFromBlock($qid, $source_block_id); - } - } - // remove complete block - else - { - $this->object->unfoldQuestionblocks(array($source_block_id)); - } - } - - // page will be "deleted" by operation - if(sizeof($source) == sizeof($nodes) && $data["source"] < $this->current_page) - { - $this->current_page--; - } - } - } - - // copy - else if($data["mode"] == "copy") - { - $titles = array(); - foreach($this->object->getSurveyPages() as $page) - { - foreach($page as $question) - { - $titles[] = $question["title"]; - } - } - - // copy questions - $question_pointer = array(); - foreach($nodes as $qid) - { - // create new questions - $question = ilObjSurvey::_instanciateQuestion($qid); - - // handle exisiting copies - $title = $question->getTitle(); - $max = 0; - foreach($titles as $existing_title) - { - #21278 preg_quote with delimiter - if(preg_match("/".preg_quote($title, "/")." \(([0-9]+)\)$/", $existing_title, $match)) - { - $max = max($match[1], $max); - } - } - if($max) - { - $title .= " (".($max+1).")"; - } - else - { - $title .= " (2)"; - } - $titles[] = $title; - $question->setTitle($title); - - $question->id = -1; - $question->saveToDb(); - - $question_pointer[$qid] = $question->getId(); - $this->appendNewQuestionToSurvey($question->getId(), false); - } - - // copy textblocks - $this->object->cloneTextblocks($question_pointer); - - $this->object->loadQuestionsFromDb(); - - $nodes = array_values($question_pointer); - } - - - // paste - - // create new block - if(sizeof($target) == 1) - { - $nodes = array_merge(array($a_id), $nodes); - - // moveQuestions() is called within - $this->object->createQuestionblock($this->getAutoBlockTitle(), true, false, - $nodes); - } - // add to existing block - else - { - $target_block_id = $target; - $target_block_id = array_shift($target_block_id); - $target_block_id = $target_block_id["questionblock_id"]; - - foreach($nodes as $qid) - { - $this->object->addQuestionToBlock($qid, $target_block_id); - } - - // move to new position - $this->object->moveQuestions($nodes, $a_id, $pos); - } - - $this->clearClipboard(); - } - - /** - * Move questions in page - */ - protected function dnd() - { - $source_id = (int)array_pop(explode("_", $_REQUEST["il_hform_source"])); - if($_REQUEST["il_hform_target"] != "droparea_end") - { - $target_id = (int)array_pop(explode("_", $_REQUEST["il_hform_target"])); - $pos = 0; - } - else - { - $page = $this->object->getSurveyPages(); - $page = $page[$this->current_page-1]; - $last = array_pop($page); - $target_id = (int)$last["question_id"]; - $pos = 1; - } - if($source_id != $target_id) - { - $this->object->moveQuestions(array($source_id), $target_id, $pos); - } - } - - /** - * Confirm removing question block - * @param int $a_id - */ - protected function deleteBlock() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameter($this->editor_gui, "pgov", $this->current_page); - ilUtil::sendQuestion($lng->txt("remove_questions")); - - $page = $this->object->getSurveyPages(); - $page = $page[$this->current_page-1]; - - // #10567 - if($_REQUEST["csum"] != md5(print_r($page, true))) - { - $ilCtrl->redirect($this, "renderPage"); - } - - $page = array_shift($page); - $block_id = $page["questionblock_id"]; - if($block_id) - { - $this->editor_gui->removeQuestionsForm(array($block_id), array(), array()); - } - else - { - $this->editor_gui->removeQuestionsForm(array(), array($page["question_id"]), array()); - } - } - - /** - * Confirm removing question(s) from survey - * - * @param int|array $a_id - */ + * + * @param int $a_new_id + * @param bool $a_duplicate + * @todo: move out of GUI class, see also ilObjSurvey->insertQuestion + */ + protected function appendNewQuestionToSurvey($a_new_id, $a_duplicate = true, $a_force_duplicate = false) + { + $ilDB = $this->db; + + $this->log->debug("append question, id: " . $a_new_id . ", duplicate: " . $a_duplicate . ", force: " . $a_force_duplicate); + + // get maximum sequence index in test + $result = $ilDB->queryF( + "SELECT survey_question_id FROM svy_svy_qst WHERE survey_fi = %s", + array('integer'), + array($this->object->getSurveyId()) + ); + $sequence = $result->numRows(); + + // create duplicate if pool question (or forced for question blocks copy) + if ($a_duplicate) { + // this does nothing if this is not a pool question and $a_force_duplicate is false + $survey_question_id = $this->object->duplicateQuestionForSurvey($a_new_id, $a_force_duplicate); + } + // used by copy & paste + else { + $survey_question_id = $a_new_id; + } + + // check if question is not already in the survey, see #22018 + if ($this->object->isQuestionInSurvey($survey_question_id)) { + return $survey_question_id; + } + + // append to survey + $next_id = $ilDB->nextId('svy_svy_qst'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_svy_qst (survey_question_id, survey_fi," . + "question_fi, sequence, tstamp) VALUES (%s, %s, %s, %s, %s)", + array('integer', 'integer', 'integer', 'integer', 'integer'), + array($next_id, $this->object->getSurveyId(), $survey_question_id, $sequence, time()) + ); + + $this->log->debug("insert svy_svy_qst, id: " . $next_id . ", qfi: " . $survey_question_id . ", seq: " . $sequence); + + return $survey_question_id; + } + + /** + * Add new question to survey + * + * @param int $a_new_id + */ + public function insertNewQuestion($a_new_id) + { + $rbacsystem = $this->rbacsystem; + $ilDB = $this->db; + $lng = $this->lng; + + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + if (!SurveyQuestion::_isComplete($a_new_id)) { + ilUtil::sendFailure($lng->txt("survey_error_insert_incomplete_question")); + } else { + $a_new_id = $this->appendNewQuestionToSurvey($a_new_id); + $this->object->loadQuestionsFromDb(); + + $pos = $_REQUEST["pgov_pos"]; + + // a[fter]/b[efore] on same page + if (substr($pos, -1) != "c") { + // block handling + $current = $this->object->getSurveyPages(); + $current = $current[$this->current_page-1]; + if (sizeof($current) == 1) { + // as questions are moved to first block question + // always use existing as first + // the new question is moved later on (see below) + $this->object->createQuestionblock( + $this->getAutoBlockTitle(), + true, + false, + array((int) $pos, $a_new_id) + ); + } else { + $block_id = array_pop($current); + $block_id = $block_id["questionblock_id"]; + + $this->object->addQuestionToBlock($a_new_id, $block_id); + } + } + // c: as new page (from toolbar/pool) + else { + // after given question + if ((int) $pos) { + $pos = (int) $pos . "a"; + $this->current_page++; + } + // at the beginning + else { + $first = $this->object->getSurveyPages(); + $first = $first[0]; + $first = array_shift($first); + $pos = $first["question_id"] . "b"; + $this->current_page = 1; + } + } + + // move to target position + $this->object->moveQuestions( + array($a_new_id), + (int) $pos, + ((substr($pos, -1) == "a") ? 1 : 0) + ); + + $this->object->fixSequenceStructure(); + } + } + + /** + * Copy and insert questions from block + * + * @param int $a_block_id + */ + public function insertQuestionBlock($a_block_id) + { + $new_ids = array(); + $question_ids = $this->object->getQuestionblockQuestionIds($a_block_id); + foreach ($question_ids as $qid) { + $new_ids[] = $this->appendNewQuestionToSurvey($qid, true, true); + } + + if (sizeof($new_ids)) { + $this->object->loadQuestionsFromDb(); + + $pos = $_REQUEST["pgov_pos"]; + + // a[fter]/b[efore] on same page + if (substr($pos, -1) != "c") { + // block handling + $current = $this->object->getSurveyPages(); + $current = $current[$this->current_page-1]; + if (sizeof($current) == 1) { + // as questions are moved to first block question + // always use existing as first + // the new question is moved later on (see below) + $this->object->createQuestionblock( + $this->getAutoBlockTitle(), + true, + false, + array((int) $pos)+$new_ids + ); + } else { + $block_id = array_pop($current); + $block_id = $block_id["questionblock_id"]; + + foreach ($new_ids as $qid) { + $this->object->addQuestionToBlock($qid, $block_id); + } + } + } + // c: as new page (from toolbar/pool) + else { + // re-create block + $this->object->createQuestionblock( + $this->getAutoBlockTitle(), + true, + false, + $new_ids + ); + + // after given question + if ((int) $pos) { + $pos = (int) $pos . "a"; + } + // at the beginning + else { + $first = $this->object->getSurveyPages(); + $first = $first[0]; + $first = array_shift($first); + $pos = $first["question_id"] . "b"; + } + } + + // move to target position + $this->object->moveQuestions( + $new_ids, + (int) $pos, + ((substr($pos, -1) == "a") ? 1 : 0) + ); + } + } + + /** + * Call add question to survey form + * + * @param int $a_type question type + * @param bool $a_use_pool add question to pool + * @param int $a_pos target position + * @param string $a_special_position special positions (toolbar | page_end) + */ + protected function addQuestion($a_type, $a_use_pool, $a_pos, $a_special_position) + { + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + // get translated type + include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"; + $questiontypes = ilObjSurveyQuestionPool::_getQuestiontypes(); + foreach ($questiontypes as $item) { + if ($item["questiontype_id"] == $a_type) { + $type_trans = $item["type_tag"]; + } + } + + $id = $a_pos; + + // new page behind current (from toolbar) + if ($a_special_position == "toolbar") { + $id = $this->object->getSurveyPages(); + if ($a_pos && $a_pos != "fst") { + $id = $id[$a_pos-1]; + $id = array_pop($id); + $id = $id["question_id"] . "c"; + } else { + $id = "0c"; + } + } + // append current page + elseif ($a_special_position == "page_end") { + $id = $this->object->getSurveyPages(); + $id = $id[$this->current_page-1]; + $id = array_pop($id); + $id = $id["question_id"] . "a"; + } else { + $id .= "b"; + } + + if ($a_use_pool) { + $_GET["sel_question_types"] = $type_trans; + $_REQUEST["pgov_pos"] = $id; + $ilCtrl->setParameter($this->editor_gui, "pgov_pos", $id); + if (!$_POST["usage"]) { + $ilTabs->clearSubTabs(); // #17193 + $this->editor_gui->createQuestionObject(); + } else { + $this->editor_gui->executeCreateQuestionObject(); + } + return true; + } else { + // create question and redirect to question form + + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php"; + $q_gui = SurveyQuestionGUI::_getQuestionGUI($type_trans); + $q_gui->object->setObjId($this->object->getId()); + $q_gui->object->createNewQuestion(); + $q_gui_class = get_class($q_gui); + + // #12531 + $ilCtrl->setParameterByClass($q_gui_class, "pgov", $this->current_page); + $ilCtrl->setParameterByClass($q_gui_class, "pgov_pos", $id); + $ilCtrl->setParameterByClass($q_gui_class, "ref_id", $this->ref_id); + $ilCtrl->setParameterByClass($q_gui_class, "new_for_survey", $this->ref_id); + $ilCtrl->setParameterByClass($q_gui_class, "q_id", $q_gui->object->getId()); + $ilCtrl->setParameterByClass($q_gui_class, "sel_question_types", $q_gui->getQuestionType()); + $ilCtrl->redirectByClass($q_gui_class, "editQuestion"); + } + } + + /** + * Add question to be cut to clipboard + * + * @param int $a_id question id + */ + protected function cutQuestion($a_id) + { + $lng = $this->lng; + + ilUtil::sendSuccess($lng->txt("survey_questions_to_clipboard_cut")); + $this->suppress_clipboard_msg = true; + + $_SESSION["survey_page_view"][$this->ref_id]["clipboard"] = array( + "source" => $this->current_page, + "nodes" => array($a_id), + "mode" => "cut"); + } + + /** + * Add question to be copied to clipboard + * + * @param int $a_id question id + */ + protected function copyQuestion($a_id) + { + $lng = $this->lng; + + ilUtil::sendSuccess($lng->txt("survey_questions_to_clipboard_copy")); + $this->suppress_clipboard_msg = true; + + $_SESSION["survey_page_view"][$this->ref_id]["clipboard"] = array( + "source" => $this->current_page, + "nodes" => array($a_id), + "mode" => "copy"); + } + + /** + * Add questions to be cut to clipboard + * + * @param array $a_id question ids + */ + protected function multiCut($a_id) + { + $lng = $this->lng; + + if (is_array($a_id)) { + ilUtil::sendSuccess($lng->txt("survey_questions_to_clipboard_cut")); + $this->suppress_clipboard_msg = true; + + $_SESSION["survey_page_view"][$this->ref_id]["clipboard"] = array( + "source" => $this->current_page, + "nodes" => $a_id, + "mode" => "cut"); + } + } + + /** + * Add questions to be copied to clipboard + * + * @param array $a_id question ids + */ + protected function multiCopy($a_id) + { + $lng = $this->lng; + + if (is_array($a_id)) { + ilUtil::sendSuccess($lng->txt("survey_questions_to_clipboard_copy")); + $this->suppress_clipboard_msg = true; + + $_SESSION["survey_page_view"][$this->ref_id]["clipboard"] = array( + "source" => $this->current_page, + "nodes" => $a_id, + "mode" => "copy"); + } + } + + /** + * Empty clipboard + */ + protected function clearClipboard() + { + $_SESSION["survey_page_view"][$this->ref_id]["clipboard"] = null; + } + + /** + * Paste from clipboard + * + * @param int $a_id target position + */ + protected function paste($a_id) + { + $data = $_SESSION["survey_page_view"][$this->ref_id]["clipboard"]; + $pages = $this->object->getSurveyPages(); + $source = $pages[$data["source"]-1]; + $target = $pages[$this->current_page-1]; + + // #12558 - use order of source page + $nodes = array(); + foreach ($source as $src_qst) { + if (in_array($src_qst["question_id"], $data["nodes"])) { + $nodes[] = $src_qst["question_id"]; + } + } + + // append to last position? + $pos = 0; + if ($_REQUEST["il_hform_node"] == "page_end") { + $a_id = $target; + $a_id = array_pop($a_id); + $a_id = $a_id["question_id"]; + $pos = 1; + } + + // cut + if ($data["mode"] == "cut") { + // special case: paste cut on same page (no block handling needed) + if ($data["source"] == $this->current_page) { + // re-order nodes in page + if (sizeof($nodes) <= sizeof($source)) { + $this->object->moveQuestions($nodes, $a_id, $pos); + } + $this->clearClipboard(); + return; + } else { + // only if source has block + $source_block_id = false; + if (sizeof($source) > 1) { + $source_block_id = $source; + $source_block_id = array_shift($source_block_id); + $source_block_id = $source_block_id["questionblock_id"]; + + // remove from block + if (sizeof($source) > sizeof($nodes)) { + foreach ($nodes as $qid) { + $this->object->removeQuestionFromBlock($qid, $source_block_id); + } + } + // remove complete block + else { + $this->object->unfoldQuestionblocks(array($source_block_id)); + } + } + + // page will be "deleted" by operation + if (sizeof($source) == sizeof($nodes) && $data["source"] < $this->current_page) { + $this->current_page--; + } + } + } + + // copy + elseif ($data["mode"] == "copy") { + $titles = array(); + foreach ($this->object->getSurveyPages() as $page) { + foreach ($page as $question) { + $titles[] = $question["title"]; + } + } + + // copy questions + $question_pointer = array(); + foreach ($nodes as $qid) { + // create new questions + $question = ilObjSurvey::_instanciateQuestion($qid); + + // handle exisiting copies + $title = $question->getTitle(); + $max = 0; + foreach ($titles as $existing_title) { + #21278 preg_quote with delimiter + if (preg_match("/" . preg_quote($title, "/") . " \(([0-9]+)\)$/", $existing_title, $match)) { + $max = max($match[1], $max); + } + } + if ($max) { + $title .= " (" . ($max+1) . ")"; + } else { + $title .= " (2)"; + } + $titles[] = $title; + $question->setTitle($title); + + $question->id = -1; + $question->saveToDb(); + + $question_pointer[$qid] = $question->getId(); + $this->appendNewQuestionToSurvey($question->getId(), false); + } + + // copy textblocks + $this->object->cloneTextblocks($question_pointer); + + $this->object->loadQuestionsFromDb(); + + $nodes = array_values($question_pointer); + } + + + // paste + + // create new block + if (sizeof($target) == 1) { + $nodes = array_merge(array($a_id), $nodes); + + // moveQuestions() is called within + $this->object->createQuestionblock( + $this->getAutoBlockTitle(), + true, + false, + $nodes + ); + } + // add to existing block + else { + $target_block_id = $target; + $target_block_id = array_shift($target_block_id); + $target_block_id = $target_block_id["questionblock_id"]; + + foreach ($nodes as $qid) { + $this->object->addQuestionToBlock($qid, $target_block_id); + } + + // move to new position + $this->object->moveQuestions($nodes, $a_id, $pos); + } + + $this->clearClipboard(); + } + + /** + * Move questions in page + */ + protected function dnd() + { + $source_id = (int) array_pop(explode("_", $_REQUEST["il_hform_source"])); + if ($_REQUEST["il_hform_target"] != "droparea_end") { + $target_id = (int) array_pop(explode("_", $_REQUEST["il_hform_target"])); + $pos = 0; + } else { + $page = $this->object->getSurveyPages(); + $page = $page[$this->current_page-1]; + $last = array_pop($page); + $target_id = (int) $last["question_id"]; + $pos = 1; + } + if ($source_id != $target_id) { + $this->object->moveQuestions(array($source_id), $target_id, $pos); + } + } + + /** + * Confirm removing question block + * @param int $a_id + */ + protected function deleteBlock() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameter($this->editor_gui, "pgov", $this->current_page); + ilUtil::sendQuestion($lng->txt("remove_questions")); + + $page = $this->object->getSurveyPages(); + $page = $page[$this->current_page-1]; + + // #10567 + if ($_REQUEST["csum"] != md5(print_r($page, true))) { + $ilCtrl->redirect($this, "renderPage"); + } + + $page = array_shift($page); + $block_id = $page["questionblock_id"]; + if ($block_id) { + $this->editor_gui->removeQuestionsForm(array($block_id), array(), array()); + } else { + $this->editor_gui->removeQuestionsForm(array(), array($page["question_id"]), array()); + } + } + + /** + * Confirm removing question(s) from survey + * + * @param int|array $a_id + */ protected function deleteQuestion($a_id) - { - $ilCtrl = $this->ctrl; - - if(!is_array($a_id)) - { - $a_id = array($a_id); - } - - $ilCtrl->setParameter($this->editor_gui, "pgov", $this->current_page); - $this->editor_gui->removeQuestionsForm(array(), $a_id, array()); - return true; - } - - /** - * Remove question(s) from survey - */ - protected function confirmRemoveQuestions() - { - $ilCtrl = $this->ctrl; - - // gather ids - $ids = array(); - foreach ($_POST as $key => $value) - { - if (preg_match("/id_(\d+)/", $key, $matches)) - { - array_push($ids, $matches[1]); - } - } - - - $pages = $this->object->getSurveyPages(); - $source = $pages[$this->current_page-1]; - - $block_id = $source; - $block_id = array_shift($block_id); - $block_id = $block_id["questionblock_id"]; - - if(sizeof($ids) && sizeof($source) > sizeof($ids)) - { - // block is obsolete - if(sizeof($source)-sizeof($ids) == 1) - { - $this->object->unfoldQuestionblocks(array($block_id)); - } - // block will remain, remove question(s) from block - else - { - foreach($ids as $qid) - { - $this->object->removeQuestionFromBlock($qid, $block_id); - } - } - - $this->object->removeQuestions($ids, array()); - } - // all items on page - else - { - // remove complete block - if($block_id) - { - $this->object->removeQuestions(array(), array($block_id)); - } - // remove single question - else - { - $this->object->removeQuestions($ids, array()); - } - - // render previous page - if($this->current_page > 1) - { - $this->current_page--; - } - } - - $this->object->saveCompletionStatus(); - - // #10567 - $ilCtrl->setParameter($this, "pgov", $this->current_page); - $ilCtrl->redirect($this, "renderPage"); - } - - /** - * Edit question block - * - * @param int $a_id - */ - protected function editBlock($a_id) - { - $this->callEditor("editQuestionblockObject", "bl_id", $a_id); - return true; - } - - /** - * Add heading to question - * - * @param int $a_id - */ - protected function addHeading($a_id) - { - $this->callEditor("addHeadingObject", "q_id", $a_id); - return true; - } - - /** - * Edit question heading - * - * @param int $a_id - */ - protected function editHeading($a_id) - { - $this->callEditor("editHeadingObject", "q_id", $a_id); - return true; - } - - /** - * Delete question heading - * - * @param int $a_id - */ - protected function deleteHeading($a_id) - { - $this->callEditor("removeHeadingObject", "q_id", $a_id); - return true; - } - - protected function callEditor($a_cmd, $a_param, $a_value) - { - $ilTabs = $this->tabs; - - $ilTabs->clearSubTabs(); - $_REQUEST[$a_param] = $a_value; - - call_user_func(array($this->editor_gui, $a_cmd)); - } - - /** - * Split current page in 2 pages - * - * @param int $a_id - */ - protected function splitPage($a_id) - { - $pages = $this->object->getSurveyPages(); - $source = $pages[$this->current_page-1]; - - $block_questions = array(); - $add = $block_id = false; - foreach($source as $idx => $item) - { - if($item["question_id"] == $a_id) - { - $block_id = $item["questionblock_id"]; - $add = $idx; - } - if($add) - { - $block_questions[] = $item["question_id"]; - } - } - - // just 1 question left: block is obsolete - if($add == 1) - { - $this->object->unfoldQuestionblocks(array($block_id)); - } - // remove questions from block - else - { - foreach($block_questions as $qid) - { - $this->object->removeQuestionFromBlock($qid, $block_id); - } - } - - // more than 1 moved? - if(sizeof($block_questions) > 1) - { - // create new block and move target questions - $this->object->createQuestionblock($this->getAutoBlockTitle(), true, false, - $block_questions); - } - - $this->current_page++; - } - - /** - * Move question to next page - * - * @param int $a_id - */ - protected function moveNext($a_id) - { - $pages = $this->object->getSurveyPages(); - $source = $pages[$this->current_page-1]; - $target = $pages[$this->current_page]; - if(sizeof($target)) - { - $target_id = $target; - $target_id = array_shift($target_id); - $target_block_id = $target_id["questionblock_id"]; - $target_id = $target_id["question_id"]; - - // nothing to do if no block - if(sizeof($source) > 1) - { - $block_id = $source; - $block_id = array_shift($block_id); - $block_id = $block_id["questionblock_id"]; - - // source pages block is obsolete - if(sizeof($source) == 2) - { - // delete block - $this->object->unfoldQuestionblocks(array($block_id)); - } - else - { - // remove question from block - $this->object->removeQuestionFromBlock($a_id, $block_id); - } - } - - // move source question to target - $this->object->moveQuestions(array($a_id), $target_id, 0); - - // new page has no block yet - if(sizeof($target) < 2) - { - // create block and move target question and source into block - $this->object->createQuestionblock($this->getAutoBlockTitle(), true, false, - array($a_id, $target_id)); - } - else - { - // add source question to block - $this->object->addQuestionToBlock($a_id, $target_block_id); - } - - // only if current page is not "deleted" - if(sizeof($source) > 1) - { - $this->current_page++; - } - } - } - - /** - * Move question to previous page - * - * @param int $a_id - */ - protected function movePrevious($a_id) - { - $pages = $this->object->getSurveyPages(); - $source = $pages[$this->current_page-1]; - $target = $pages[$this->current_page-2]; - if(sizeof($target)) - { - $target_id = $target; - $target_id = array_pop($target_id); - $target_block_id = $target_id["questionblock_id"]; - $target_id = $target_id["question_id"]; - - // nothing to do if no block - if(sizeof($source) > 1) - { - $block_id = $source; - $block_id = array_shift($block_id); - $block_id = $block_id["questionblock_id"]; - - // source pages block is obsolete - if(sizeof($source) == 2) - { - // delete block - $this->object->unfoldQuestionblocks(array($block_id)); - } - else - { - // remove question from block - $this->object->removeQuestionFromBlock($a_id, $block_id); - } - } - - // move source question to target - $this->object->moveQuestions(array($a_id), $target_id, 1); - - // new page has no block yet - if(sizeof($target) < 2) - { - // create block and move target question and source into block - $this->object->createQuestionblock($this->getAutoBlockTitle(), true, false, - array($target_id, $a_id)); - } - else - { - // add source question to block - $this->object->addQuestionToBlock($a_id, $target_block_id); - } - - $this->current_page--; - } - } - - /** - * Edit question - * - * @param int $a_id - */ - protected function editQuestion($a_id) - { - $ilCtrl = $this->ctrl; - - $data = $this->object->getSurveyQuestions(); - $data = $data[$a_id]; - - $q_gui = $data["type_tag"]."GUI"; - $ilCtrl->setParameterByClass($q_gui, "pgov", $this->current_page); - $ilCtrl->setParameterByClass($q_gui, "q_id", $a_id); - - $ilCtrl->redirectByClass($q_gui, "editQuestion"); - } - - /** - * Add question to survey form (used in toolbar) - */ - protected function addQuestionToolbarForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this, "addQuestionToolbar")); - $form->setTitle($lng->txt("survey_add_new_question")); - - // question types - include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"; - $questiontypes = ilObjSurveyQuestionPool::_getQuestiontypes(); - $type_map = array(); - foreach($questiontypes as $trans => $item) - { - $type_map[$item["questiontype_id"]] = $trans; - } - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $si = new ilSelectInputGUI($lng->txt("question_type"), "qtype"); - $si->setOptions($type_map); - $form->addItem($si); - - $pages = $this->object->getSurveyPages(); - if($pages) - { - $pages_drop = array("fst"=>$lng->txt("survey_at_beginning")); - foreach($pages as $idx => $questions) - { - $question = array_shift($questions); - if($question["questionblock_id"]) - { - $pages_drop[$idx+1] = $lng->txt("survey_behind_page")." ".$question["questionblock_title"]; - } - else - { - $pages_drop[$idx+1] = $lng->txt("survey_behind_page")." ".strip_tags($question["title"]); - } - } - $pos = new ilSelectInputGUI($lng->txt("position"), "pgov"); - $pos->setOptions($pages_drop); - $form->addItem($pos); - - $pos->setValue($this->current_page); - } - else - { - // #9089: 1st page - $pos = new ilHiddenInputGUI("pgov"); - $pos->setValue("fst"); - $form->addItem($pos); - } - - if($this->object->isPoolActive()) - { - $this->editor_gui->createQuestionObject($form); - } - - $form->addCommandButton("addQuestionToolbar", $lng->txt("create")); - $form->addCommandButton("renderPage", $lng->txt("cancel")); - - return $tpl->setContent($form->getHTML()); - } - - /** - * Add question to survey action (used in toolbar) - */ - protected function addQuestionToolbar() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $pool_active = $this->object->isPoolActive(); - - if(!$_POST["usage"] && $pool_active) - { - ilUtil::sendFailure($lng->txt("select_one"), true); - return $this->addQuestionToolbarForm(); - } - - // make sure that it is set for current and next requests - $ilCtrl->setParameter($this->editor_gui, "pgov", $this->current_page); - - if(!$this->addQuestion($_POST["qtype"], $pool_active, $_POST["pgov"], "toolbar")) - { - $this->renderPage(); - } - } - - /** - * Move current page - */ - protected function movePageForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this, "movePage")); - $form->setTitle($lng->txt("survey_move_page")); - - $old_pos = new ilHiddenInputGUI("old_pos"); - $old_pos->setValue($this->current_page); - $form->addItem($old_pos); - - $pages = $this->object->getSurveyPages(); - if($pages) - { - $pages_drop = array(); - if($this->current_page != 1) - { - $pages_drop["fst"] = $lng->txt("survey_at_beginning"); - } - foreach($pages as $idx => $questions) - { - if(($idx+1) != $this->current_page && ($idx+2) != $this->current_page) - { - $question = array_shift($questions); - if($question["questionblock_id"]) - { - $pages_drop[$idx+1] = $lng->txt("survey_behind_page")." ".$question["questionblock_title"]; - } - else - { - $pages_drop[$idx+1] = $lng->txt("survey_behind_page")." ".strip_tags($question["title"]); - } - } - } - $pos = new ilSelectInputGUI($lng->txt("position"), "pgov"); - $pos->setOptions($pages_drop); - $form->addItem($pos); - } - - $form->addCommandButton("movePage", $lng->txt("submit")); - $form->addCommandButton("renderPage", $lng->txt("cancel")); - - return $tpl->setContent($form->getHTML()); - } - - /** - * Move current page to new position - * @todo this needs to be refactored outside of a GUI class, same with ilSurveyEditorGUI->insertQuestions - */ - protected function movePage() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - // current_page is already set to new position - $target_page = $this->current_page-1; - $source_page = $_REQUEST["old_pos"]-1; - - $pages = $this->object->getSurveyPages(); - foreach($pages[$source_page] as $question) - { - $questions[] = $question["question_id"]; - } - - // move to first position - $position = 0; - if($_REQUEST["pgov"] != "fst") - { - $position = 1; - } - - $target = $pages[$target_page]; - if ($position == 0) // before - { - $target = array_shift($target); // ... use always the first question of the page - } - else // after - { - $target = array_pop($target); // ... use always the last question of the page - } - $this->object->moveQuestions($questions, $target["question_id"], $position); - - if($target_page < $source_page && $position) - { - $this->current_page++; - } - - ilUtil::sendSuccess($lng->txt("survey_page_moved"), true); - $ilCtrl->setParameter($this, "pgov", $this->current_page); - $ilCtrl->redirect($this, "renderPage"); - } - - /** - * Render toolbar form - * - * @param array $a_pages - */ - protected function renderToolbar($a_pages) - { - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilUser = $this->user; - - include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; - - if(!$this->has_datasets) - { - $button = ilLinkButton::getInstance(); - $button->setCaption("survey_add_new_question"); - $button->setUrl($ilCtrl->getLinkTarget($this, "addQuestionToolbarForm")); - $ilToolbar->addStickyItem($button); - - if($this->object->isPoolActive()) - { - //$ilToolbar->addSeparator(); - - $last_on_page = 0; - if($a_pages && - is_array($a_pages[$this->current_page-1])) - { - $last_on_page = $a_pages[$this->current_page-1]; - $last_on_page = array_pop($last_on_page); - $last_on_page = $last_on_page["question_id"]; - } - - $ilCtrl->setParameter($this->editor_gui, "pgov", $this->current_page); - $ilCtrl->setParameter($this->editor_gui, "pgov_pos", $last_on_page."c"); - - $cmd = ($ilUser->getPref('svy_insert_type') == 1 || - strlen($ilUser->getPref('svy_insert_type')) == 0) - ? 'browseForQuestions' - : 'browseForQuestionblocks'; - - $button = ilLinkButton::getInstance(); - $button->setCaption("browse_for_questions"); - $button->setUrl($ilCtrl->getLinkTarget($this->editor_gui, $cmd)); - $ilToolbar->addStickyItem($button); - - $ilCtrl->setParameter($this->editor_gui, "pgov", ""); - $ilCtrl->setParameter($this->editor_gui, "pgov_pos", ""); - } - - if($a_pages) - { - $ilToolbar->addSeparator(); - } - } - - // parse data for pages drop-down - if($a_pages) - { - // previous/next - - $ilCtrl->setParameter($this, "pg", $this->current_page-1); - $button = ilLinkButton::getInstance(); - $button->setCaption("survey_prev_question"); - if($this->has_previous_page) - { - $button->setUrl($ilCtrl->getLinkTarget($this, "renderPage")); - } - $button->setDisabled(!$this->has_previous_page); - $ilToolbar->addStickyItem($button); - - $ilCtrl->setParameter($this, "pg", $this->current_page+1); - $button = ilLinkButton::getInstance(); - $button->setCaption("survey_next_question"); - if($this->has_next_page) - { - $button->setUrl($ilCtrl->getLinkTarget($this, "renderPage")); - } - $button->setDisabled(!$this->has_next_page); - $ilToolbar->addStickyItem($button); - - $ilCtrl->setParameter($this, "pg", $this->current_page); // #14615 - - foreach($a_pages as $idx => $questions) - { - $page = $questions; - $page = array_shift($page); - if($page["questionblock_id"]) - { - $pages_drop[$idx+1] = $page["questionblock_title"]; - - if(sizeof($questions) > 1) - { - foreach($questions as $question) - { - $pages_drop[($idx+1)."__".$question["question_id"]] = "- ".$question["title"]; - } - } - } - else - { - $pages_drop[$idx+1] = strip_tags($page["title"]); - } - } - } - - // jump to page - if(is_array($pages_drop) && count($pages_drop) > 1) - { - //$ilToolbar->addSeparator(); - - $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $si = new ilSelectInputGUI($lng->txt("survey_jump_to"), "jump"); - $si->addCustomAttribute("onChange=\"forms['ilToolbar'].submit();\""); - $si->setOptions($pages_drop); - $si->setValue($this->current_page); - $ilToolbar->addInputItem($si, true); - - // we need this to have to right cmd - $cmd = new ilHiddenInputGUI("cmd[renderPage]"); - $cmd->setValue("1"); - $ilToolbar->addInputItem($cmd); - - if(!$this->has_datasets) - { - $ilToolbar->addSeparator(); - - $ilCtrl->setParameter($this, "csum", md5(print_r($a_pages[$this->current_page-1], true))); - $url = $ilCtrl->getLinkTarget($this, "deleteBlock"); - $ilCtrl->setParameter($this, "csum", ""); - - $button = ilLinkButton::getInstance(); - $button->setCaption("survey_delete_page"); - $button->setUrl($url); - $ilToolbar->addButtonInstance($button); - - $ilToolbar->addSeparator(); - - $button = ilLinkButton::getInstance(); - $button->setCaption("survey_move_page"); - $button->setUrl($ilCtrl->getLinkTarget($this, "movePageForm")); - $ilToolbar->addButtonInstance($button); - } - } - } - - /** - * render questions per page - */ - protected function renderPage() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - $rbacsystem = $this->rbacsystem; - - $pages = $this->object->getSurveyPages(); - $this->has_next_page = ($this->current_page < sizeof($pages)); - $this->has_previous_page = ($this->current_page > 1); - $this->has_datasets = ilObjSurvey::_hasDatasets($this->object->getSurveyId()); - - $mess = ""; - if($this->has_datasets) - { - $mbox = new ilSurveyContainsDataMessageBoxGUI(); - $mess = $mbox->getHTML(); - } - - $ilCtrl->setParameter($this, "pg", $this->current_page); - $ilCtrl->setParameter($this, "pgov", ""); - - $this->renderToolbar($pages); - - if($pages) - { - $ttpl = new ilTemplate("tpl.il_svy_svy_page_view.html", true, true, "Modules/Survey"); - $ttpl->setVariable("FORM_ACTION", $ilCtrl->getFormAction($this)); - $lng->loadLanguageModule("form"); - - $read_only = ($this->has_datasets || !$rbacsystem->checkAccess("write", $this->ref_id)); - - $commands = $multi_commands = array(); - - if(!$read_only) - { - // clipboard is empty - if(!$_SESSION["survey_page_view"][$this->ref_id]["clipboard"]) - { - $multi_commands[] = array("cmd"=>"multiDelete", "text"=>$lng->txt("delete")); - $multi_commands[] = array("cmd"=>"multiCut", "text"=>$lng->txt("cut")); - $multi_commands[] = array("cmd"=>"multiCopy", "text"=>$lng->txt("copy")); - $multi_commands[] = array("cmd"=>"selectAll", "text"=>$lng->txt("select_all")); - } - else - { - if(!$this->suppress_clipboard_msg) - { - ilUtil::sendInfo($lng->txt("survey_clipboard_notice")); - } - $multi_commands[] = array("cmd"=>"clearClipboard", "text"=>$lng->txt("survey_dnd_clear_clipboard")); - } - - // help - see ilPageObjectGUI::insertHelp() - $lng->loadLanguageModule("content"); - $ttpl->setCurrentBlock("help_section"); - $ttpl->setVariable("TXT_ADD_EL", $lng->txt("cont_add_elements")); - include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); - $ttpl->setVariable("PLUS", ilGlyphGUI::get(ilGlyphGUI::ADD)); - $ttpl->setVariable("DRAG_ARROW", ilGlyphGUI::get(ilGlyphGUI::DRAG)); - $ttpl->setVariable("TXT_DRAG", $lng->txt("cont_drag_and_drop_elements")); - $ttpl->setVariable("TXT_SEL", $lng->txt("cont_double_click_to_delete")); - $ttpl->parseCurrentBlock(); - - $ttpl->setVariable("DND_INIT_JS", "initDragElements();"); - - - // tiny mce - - include_once "./Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php"; - $tags = ilObjAdvancedEditing::_getUsedHTMLTags("survey"); - - /** - * Alex Killing, 27 July 2018 - * I removed a line $tpl->addJavascript("./Services/RTE/tiny_mce_.../tiny_mce_src.js"); at the end - * of this function. Currently I have no idea when this tiny will be presented... - * Maybe a bug will come out of this during 5.4 testing - */ - include_once "./Services/RTE/classes/class.ilTinyMCE.php"; - $tiny = new ilTinyMCE(); - $ttpl->setVariable("WYSIWYG_BLOCKFORMATS", $tiny->_buildAdvancedBlockformatsFromHTMLTags($tags)); - $ttpl->setVariable("WYSIWYG_VALID_ELEMENTS", $tiny->_getValidElementsFromHTMLTags($tags)); - - $buttons_1 = $tiny->_buildAdvancedButtonsFromHTMLTags(1, $tags); - $buttons_2 = $tiny->_buildAdvancedButtonsFromHTMLTags(2, $tags).','. - $tiny->_buildAdvancedTableButtonsFromHTMLTags($tags). - ($tiny->getStyleSelect() ? ',styleselect' : ''); - $buttons_3 = $tiny->_buildAdvancedButtonsFromHTMLTags(3, $tags); - $ttpl->setVariable('WYSIWYG_BUTTONS_1', ilTinyMCE::removeRedundantSeparators($buttons_1)); - $ttpl->setVariable('WYSIWYG_BUTTONS_2', ilTinyMCE::removeRedundantSeparators($buttons_2)); - $ttpl->setVariable('WYSIWYG_BUTTONS_3', ilTinyMCE::removeRedundantSeparators($buttons_3)); - } - - // commands - if (count($multi_commands) > 0) - { - foreach($multi_commands as $cmd) - { - $ttpl->setCurrentBlock("multi_cmd"); - $ttpl->setVariable("ORG_CMD_MULTI", "renderPage"); - $ttpl->setVariable("MULTI_CMD", $cmd["cmd"]); - $ttpl->setVariable("MULTI_CMD_TXT", $cmd["text"]); - $ttpl->parseCurrentBlock(); - } - - $ttpl->setCurrentBlock("multi_cmds"); - $ttpl->setVariable("MCMD_ALT", $lng->txt("commands")); - $ttpl->setVariable("MCMD_IMG", ilUtil::getImagePath("arrow_downright.svg")); - $ttpl->parseCurrentBlock(); - } - - // nodes - $ttpl->setVariable("NODES", $this->getPageNodes($pages[$this->current_page-1], - $this->has_previous_page, $this->has_next_page, $read_only)); - - $tpl->setContent($mess.$ttpl->get()); - - // add js to template - include_once("./Services/YUI/classes/class.ilYuiUtil.php"); - ilYuiUtil::initDragDrop(); - $tpl->addJavascript("./Modules/Survey/js/SurveyPageView.js"); - } - } - - /** - * Get Form HTML - * - * @param array $questions - * @param bool $a_has_previous_page - * @param bool $a_has_next_page - * @param bool $a_readonly - * @return string - */ - function getPageNodes(array $a_questions, $a_has_previous_page = false, $a_has_next_page = false, $a_readonly = false) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $ttpl = new ilTemplate("tpl.il_svy_svy_page_view_nodes.html", true, true, "Modules/Survey"); - - $has_clipboard = (bool)$_SESSION["survey_page_view"][$this->ref_id]["clipboard"]; - - // question block ? - - $first_question = $a_questions; - $first_question = array_shift($first_question); - - if($first_question["questionblock_id"]) - { - $menu = array(); - - if(!$a_readonly && !$has_clipboard) - { - $menu[] = array("cmd" => "editBlock", "text" => $lng->txt("edit")); - } - - if($first_question["questionblock_show_blocktitle"]) - { - $block_status = $lng->txt("survey_block_visible"); - } - else - { - $block_status = $lng->txt("survey_block_hidden"); - } - - $this->renderPageNode($ttpl, "block", $first_question["questionblock_id"], - $first_question["questionblock_title"]." (".$block_status.")", $menu, false, false, $block_status); - } - - - // questions/headings - - include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"; - $questiontypes = ilObjSurveyQuestionPool::_getQuestiontypes(); - $questionpools = array_keys($this->object->getQuestionpoolTitles(true)); - - $counter = $question_count; - $block_done = null; - foreach($a_questions as $idx => $question) - { - // drop area - - $menu = array(); - - if(!$a_readonly) - { - if(!$has_clipboard) - { - foreach($questiontypes as $trans => $item) - { - $menu[] = array("cmd"=> "addQuestion_".$item["questiontype_id"], - "text"=> sprintf($lng->txt("svy_page_add_question"), $trans)); - } - - if($this->object->isPoolActive()) - { - $menu[] = array("cmd"=> "addPoolQuestion", - "text"=> $lng->txt("browse_for_questions")); - } - } - else - { - $menu[] = array("cmd" => "paste", "text" => $lng->txt("survey_dnd_paste")); - } - } - - $this->renderPageNode($ttpl, "droparea", $question["question_id"], null, $menu, true); - - // question - $question_gui = $this->object->getQuestionGUI($question["type_tag"], $question["question_id"]); - $question_form = $question_gui->getWorkingForm(array(), $this->object->getShowQuestionTitles(), - $question["questionblock_show_questiontext"], null, $this->object->getSurveyId()); - - $menu = array(); - - if(!$a_readonly && !$has_clipboard) - { - $menu[] = array("cmd" => "editQuestion", "text" => $lng->txt("edit")); - $menu[] = array("cmd" => "cutQuestion", "text" => $lng->txt("cut")); - $menu[] = array("cmd" => "copyQuestion", "text" => $lng->txt("copy")); - - if(sizeof($a_questions) > 1 && $idx > 0) - { - $menu[] = array("cmd" => "splitPage", "text" => $lng->txt("survey_dnd_split_page")); - } - if($a_has_next_page) - { - $menu[] = array("cmd" => "moveNext", "text" => $lng->txt("survey_dnd_move_next")); - } - if($a_has_previous_page) - { - $menu[] = array("cmd" => "movePrevious", "text" => $lng->txt("survey_dnd_move_previous")); - } - - $menu[] = array("cmd" => "deleteQuestion", "text" => $lng->txt("delete")); - - // heading - if($question["heading"]) - { - $menu[] = array("cmd" => "editHeading", "text" => $lng->txt("survey_edit_heading")); - $menu[] = array("cmd" => "deleteHeading", "text" => $lng->txt("survey_delete_heading")); - } - else - { - $menu[] = array("cmd" => "addHeading", "text" => $lng->txt("add_heading")); - } - } - - if($first_question["questionblock_show_questiontext"]) - { - $question_title_status = $lng->txt("survey_question_text_visible"); - } - else - { - $question_title_status = $lng->txt("survey_question_text_hidden"); - } - - $this->renderPageNode($ttpl, "question", $question["question_id"], $question_form, $menu, - false, $question["title"], $question_title_status, $question["heading"]); - - $ilCtrl->setParameter($this, "eqid", ""); - } - - - // last position (no question id) - - $menu = array(); - - if(!$a_readonly) - { - if(!$has_clipboard) - { - foreach($questiontypes as $trans => $item) - { - $menu[] = array("cmd"=> "addQuestion_".$item["questiontype_id"], - "text"=> sprintf($lng->txt("svy_page_add_question"), $trans)); - } - - if($this->object->isPoolActive()) - { - $menu[] = array("cmd"=> "addPoolQuestion", - "text"=> $lng->txt("browse_for_questions")); - } - } - else - { - $menu[] = array("cmd" => "paste", "text" => $lng->txt("survey_dnd_paste")); - } - } - - $this->renderPageNode($ttpl, "page", "end", null, $menu, true); - - return $ttpl->get(); - } - - /** - * Render single of dnd page view - * - * @param ilTemplate $a_tpl - * @param string $a_type - * @param int $a_id - * @param string $a_content - * @param array $a_menu - * @param bool $a_spacer - * @param string $a_subtitle - * @param string $a_heading - */ - function renderPageNode(ilTemplate $a_tpl, $a_type, $a_id, $a_content = null, array $a_menu = null, $a_spacer = false, $a_subtitle = false, $a_status = false, $a_heading = false) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $node_id = $a_type."_".$a_id; - - if($a_spacer) - { - if($a_menu) - { - // drop area menu - foreach($a_menu as $mcnt => $menu_item) - { - $ilCtrl->setParameter($this, "il_hform_node", $node_id); - $ilCtrl->setParameter($this, "il_hform_subcmd", $menu_item["cmd"]); - $url = $ilCtrl->getLinkTarget($this, "renderPage"); - $ilCtrl->setParameter($this, "il_hform_subcmd", ""); - $ilCtrl->setParameter($this, "il_hform_node", ""); - - $a_tpl->setCurrentBlock("menu_cmd"); - $a_tpl->setVariable("TXT_MENU_CMD", $menu_item["text"]); - $a_tpl->setVariable("URL_MENU_CMD", $url); - $a_tpl->parseCurrentBlock(); - } - } - - $a_tpl->setCurrentBlock("drop_area"); - include_once "Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"; - $a_tpl->setVariable("ICON_ADD", ilGlyphGUI::get(ilGlyphGUI::ADD)); - $a_tpl->setVariable("DROP_ID", $a_id); - $a_tpl->parseCurrentBlock(); - } - else if($a_menu) - { - // question action menu - foreach($a_menu as $mcnt => $menu_item) - { - $ilCtrl->setParameter($this, "il_hform_node", $node_id); - $ilCtrl->setParameter($this, "il_hform_subcmd", $menu_item["cmd"]); - $url = $ilCtrl->getLinkTarget($this, "renderPage"); - $ilCtrl->setParameter($this, "il_hform_subcmd", ""); - $ilCtrl->setParameter($this, "il_hform_node", ""); - - $a_tpl->setCurrentBlock("action_cmd"); - $a_tpl->setVariable("TXT_ACTION_CMD", $menu_item["text"]); - $a_tpl->setVariable("URL_ACTION_CMD", $url); - $a_tpl->parseCurrentBlock(); - } - } - - // add heading to content - if($a_content !== null && - $a_type == "question" && - $a_heading) - { - $a_content = "
".$a_heading."
". - $a_content; - } - - if($a_menu) - { - $a_tpl->setVariable("TXT_NODE_CONTENT_ACTIONS", $a_content); - } - else - { - $a_tpl->setVariable("TXT_NODE_CONTENT_NO_ACTIONS", $a_content); - } - - if($a_content !== null) - { - $drag = ""; - $selectable = false; - switch($a_type) - { - case "block": - $caption = $lng->txt("questionblock"); - break; - - case "question": - $caption = $lng->txt("question").": ".$a_subtitle; - $drag = "_drag"; - $selectable = true; - break; - - case "heading": - $caption = $lng->txt("heading"); - break; - - default: - return; - } - - if($a_status) - { - $caption .= " (".$a_status.")"; - } - - $a_tpl->setCurrentBlock("list_item"); - $a_tpl->setVariable("NODE_ID", $node_id); - $a_tpl->setVariable("NODE_DRAG", $drag); - $a_tpl->setVariable("TXT_NODE_TYPE", $caption); - if($selectable) - { - $a_tpl->setVariable("SELECTABLE", " selectable"); - } - $a_tpl->parseCurrentBlock(); - } - - $a_tpl->touchBlock("element"); - } - - /** - * Get name for newly created blocks - * - * @return string - */ - public function getAutoBlockTitle() - { - $lng = $this->lng; - - return $lng->txt("survey_auto_block_title"); - } - - public function addPoolQuestion($pos, $node) - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - if($node == "page_end") - { - $pos = $this->object->getSurveyPages(); - $pos = array_pop($pos[$this->current_page-1]); - $pos = $pos["question_id"]."a"; - } - else - { - $pos = $pos."b"; - } - - $ilCtrl->setParameter($this->editor_gui, "pgov", $this->current_page); - $ilCtrl->setParameter($this->editor_gui, "pgov_pos", $pos); - - $cmd = ($ilUser->getPref('svy_insert_type') == 1 || strlen($ilUser->getPref('svy_insert_type')) == 0) ? 'browseForQuestions' : 'browseForQuestionblocks'; - $ilCtrl->redirect($this->editor_gui, $cmd); - } + { + $ilCtrl = $this->ctrl; + + if (!is_array($a_id)) { + $a_id = array($a_id); + } + + $ilCtrl->setParameter($this->editor_gui, "pgov", $this->current_page); + $this->editor_gui->removeQuestionsForm(array(), $a_id, array()); + return true; + } + + /** + * Remove question(s) from survey + */ + protected function confirmRemoveQuestions() + { + $ilCtrl = $this->ctrl; + + // gather ids + $ids = array(); + foreach ($_POST as $key => $value) { + if (preg_match("/id_(\d+)/", $key, $matches)) { + array_push($ids, $matches[1]); + } + } + + + $pages = $this->object->getSurveyPages(); + $source = $pages[$this->current_page-1]; + + $block_id = $source; + $block_id = array_shift($block_id); + $block_id = $block_id["questionblock_id"]; + + if (sizeof($ids) && sizeof($source) > sizeof($ids)) { + // block is obsolete + if (sizeof($source)-sizeof($ids) == 1) { + $this->object->unfoldQuestionblocks(array($block_id)); + } + // block will remain, remove question(s) from block + else { + foreach ($ids as $qid) { + $this->object->removeQuestionFromBlock($qid, $block_id); + } + } + + $this->object->removeQuestions($ids, array()); + } + // all items on page + else { + // remove complete block + if ($block_id) { + $this->object->removeQuestions(array(), array($block_id)); + } + // remove single question + else { + $this->object->removeQuestions($ids, array()); + } + + // render previous page + if ($this->current_page > 1) { + $this->current_page--; + } + } + + $this->object->saveCompletionStatus(); + + // #10567 + $ilCtrl->setParameter($this, "pgov", $this->current_page); + $ilCtrl->redirect($this, "renderPage"); + } + + /** + * Edit question block + * + * @param int $a_id + */ + protected function editBlock($a_id) + { + $this->callEditor("editQuestionblockObject", "bl_id", $a_id); + return true; + } + + /** + * Add heading to question + * + * @param int $a_id + */ + protected function addHeading($a_id) + { + $this->callEditor("addHeadingObject", "q_id", $a_id); + return true; + } + + /** + * Edit question heading + * + * @param int $a_id + */ + protected function editHeading($a_id) + { + $this->callEditor("editHeadingObject", "q_id", $a_id); + return true; + } + + /** + * Delete question heading + * + * @param int $a_id + */ + protected function deleteHeading($a_id) + { + $this->callEditor("removeHeadingObject", "q_id", $a_id); + return true; + } + + protected function callEditor($a_cmd, $a_param, $a_value) + { + $ilTabs = $this->tabs; + + $ilTabs->clearSubTabs(); + $_REQUEST[$a_param] = $a_value; + + call_user_func(array($this->editor_gui, $a_cmd)); + } + + /** + * Split current page in 2 pages + * + * @param int $a_id + */ + protected function splitPage($a_id) + { + $pages = $this->object->getSurveyPages(); + $source = $pages[$this->current_page-1]; + + $block_questions = array(); + $add = $block_id = false; + foreach ($source as $idx => $item) { + if ($item["question_id"] == $a_id) { + $block_id = $item["questionblock_id"]; + $add = $idx; + } + if ($add) { + $block_questions[] = $item["question_id"]; + } + } + + // just 1 question left: block is obsolete + if ($add == 1) { + $this->object->unfoldQuestionblocks(array($block_id)); + } + // remove questions from block + else { + foreach ($block_questions as $qid) { + $this->object->removeQuestionFromBlock($qid, $block_id); + } + } + + // more than 1 moved? + if (sizeof($block_questions) > 1) { + // create new block and move target questions + $this->object->createQuestionblock( + $this->getAutoBlockTitle(), + true, + false, + $block_questions + ); + } + + $this->current_page++; + } + + /** + * Move question to next page + * + * @param int $a_id + */ + protected function moveNext($a_id) + { + $pages = $this->object->getSurveyPages(); + $source = $pages[$this->current_page-1]; + $target = $pages[$this->current_page]; + if (sizeof($target)) { + $target_id = $target; + $target_id = array_shift($target_id); + $target_block_id = $target_id["questionblock_id"]; + $target_id = $target_id["question_id"]; + + // nothing to do if no block + if (sizeof($source) > 1) { + $block_id = $source; + $block_id = array_shift($block_id); + $block_id = $block_id["questionblock_id"]; + + // source pages block is obsolete + if (sizeof($source) == 2) { + // delete block + $this->object->unfoldQuestionblocks(array($block_id)); + } else { + // remove question from block + $this->object->removeQuestionFromBlock($a_id, $block_id); + } + } + + // move source question to target + $this->object->moveQuestions(array($a_id), $target_id, 0); + + // new page has no block yet + if (sizeof($target) < 2) { + // create block and move target question and source into block + $this->object->createQuestionblock( + $this->getAutoBlockTitle(), + true, + false, + array($a_id, $target_id) + ); + } else { + // add source question to block + $this->object->addQuestionToBlock($a_id, $target_block_id); + } + + // only if current page is not "deleted" + if (sizeof($source) > 1) { + $this->current_page++; + } + } + } + + /** + * Move question to previous page + * + * @param int $a_id + */ + protected function movePrevious($a_id) + { + $pages = $this->object->getSurveyPages(); + $source = $pages[$this->current_page-1]; + $target = $pages[$this->current_page-2]; + if (sizeof($target)) { + $target_id = $target; + $target_id = array_pop($target_id); + $target_block_id = $target_id["questionblock_id"]; + $target_id = $target_id["question_id"]; + + // nothing to do if no block + if (sizeof($source) > 1) { + $block_id = $source; + $block_id = array_shift($block_id); + $block_id = $block_id["questionblock_id"]; + + // source pages block is obsolete + if (sizeof($source) == 2) { + // delete block + $this->object->unfoldQuestionblocks(array($block_id)); + } else { + // remove question from block + $this->object->removeQuestionFromBlock($a_id, $block_id); + } + } + + // move source question to target + $this->object->moveQuestions(array($a_id), $target_id, 1); + + // new page has no block yet + if (sizeof($target) < 2) { + // create block and move target question and source into block + $this->object->createQuestionblock( + $this->getAutoBlockTitle(), + true, + false, + array($target_id, $a_id) + ); + } else { + // add source question to block + $this->object->addQuestionToBlock($a_id, $target_block_id); + } + + $this->current_page--; + } + } + + /** + * Edit question + * + * @param int $a_id + */ + protected function editQuestion($a_id) + { + $ilCtrl = $this->ctrl; + + $data = $this->object->getSurveyQuestions(); + $data = $data[$a_id]; + + $q_gui = $data["type_tag"] . "GUI"; + $ilCtrl->setParameterByClass($q_gui, "pgov", $this->current_page); + $ilCtrl->setParameterByClass($q_gui, "q_id", $a_id); + + $ilCtrl->redirectByClass($q_gui, "editQuestion"); + } + + /** + * Add question to survey form (used in toolbar) + */ + protected function addQuestionToolbarForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this, "addQuestionToolbar")); + $form->setTitle($lng->txt("survey_add_new_question")); + + // question types + include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"; + $questiontypes = ilObjSurveyQuestionPool::_getQuestiontypes(); + $type_map = array(); + foreach ($questiontypes as $trans => $item) { + $type_map[$item["questiontype_id"]] = $trans; + } + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $si = new ilSelectInputGUI($lng->txt("question_type"), "qtype"); + $si->setOptions($type_map); + $form->addItem($si); + + $pages = $this->object->getSurveyPages(); + if ($pages) { + $pages_drop = array("fst"=>$lng->txt("survey_at_beginning")); + foreach ($pages as $idx => $questions) { + $question = array_shift($questions); + if ($question["questionblock_id"]) { + $pages_drop[$idx+1] = $lng->txt("survey_behind_page") . " " . $question["questionblock_title"]; + } else { + $pages_drop[$idx+1] = $lng->txt("survey_behind_page") . " " . strip_tags($question["title"]); + } + } + $pos = new ilSelectInputGUI($lng->txt("position"), "pgov"); + $pos->setOptions($pages_drop); + $form->addItem($pos); + + $pos->setValue($this->current_page); + } else { + // #9089: 1st page + $pos = new ilHiddenInputGUI("pgov"); + $pos->setValue("fst"); + $form->addItem($pos); + } + + if ($this->object->isPoolActive()) { + $this->editor_gui->createQuestionObject($form); + } + + $form->addCommandButton("addQuestionToolbar", $lng->txt("create")); + $form->addCommandButton("renderPage", $lng->txt("cancel")); + + return $tpl->setContent($form->getHTML()); + } + + /** + * Add question to survey action (used in toolbar) + */ + protected function addQuestionToolbar() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $pool_active = $this->object->isPoolActive(); + + if (!$_POST["usage"] && $pool_active) { + ilUtil::sendFailure($lng->txt("select_one"), true); + return $this->addQuestionToolbarForm(); + } + + // make sure that it is set for current and next requests + $ilCtrl->setParameter($this->editor_gui, "pgov", $this->current_page); + + if (!$this->addQuestion($_POST["qtype"], $pool_active, $_POST["pgov"], "toolbar")) { + $this->renderPage(); + } + } + + /** + * Move current page + */ + protected function movePageForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this, "movePage")); + $form->setTitle($lng->txt("survey_move_page")); + + $old_pos = new ilHiddenInputGUI("old_pos"); + $old_pos->setValue($this->current_page); + $form->addItem($old_pos); + + $pages = $this->object->getSurveyPages(); + if ($pages) { + $pages_drop = array(); + if ($this->current_page != 1) { + $pages_drop["fst"] = $lng->txt("survey_at_beginning"); + } + foreach ($pages as $idx => $questions) { + if (($idx+1) != $this->current_page && ($idx+2) != $this->current_page) { + $question = array_shift($questions); + if ($question["questionblock_id"]) { + $pages_drop[$idx+1] = $lng->txt("survey_behind_page") . " " . $question["questionblock_title"]; + } else { + $pages_drop[$idx+1] = $lng->txt("survey_behind_page") . " " . strip_tags($question["title"]); + } + } + } + $pos = new ilSelectInputGUI($lng->txt("position"), "pgov"); + $pos->setOptions($pages_drop); + $form->addItem($pos); + } + + $form->addCommandButton("movePage", $lng->txt("submit")); + $form->addCommandButton("renderPage", $lng->txt("cancel")); + + return $tpl->setContent($form->getHTML()); + } + + /** + * Move current page to new position + * @todo this needs to be refactored outside of a GUI class, same with ilSurveyEditorGUI->insertQuestions + */ + protected function movePage() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + // current_page is already set to new position + $target_page = $this->current_page-1; + $source_page = $_REQUEST["old_pos"]-1; + + $pages = $this->object->getSurveyPages(); + foreach ($pages[$source_page] as $question) { + $questions[] = $question["question_id"]; + } + + // move to first position + $position = 0; + if ($_REQUEST["pgov"] != "fst") { + $position = 1; + } + + $target = $pages[$target_page]; + if ($position == 0) { // before + $target = array_shift($target); // ... use always the first question of the page + } else { // after + $target = array_pop($target); // ... use always the last question of the page + } + $this->object->moveQuestions($questions, $target["question_id"], $position); + + if ($target_page < $source_page && $position) { + $this->current_page++; + } + + ilUtil::sendSuccess($lng->txt("survey_page_moved"), true); + $ilCtrl->setParameter($this, "pgov", $this->current_page); + $ilCtrl->redirect($this, "renderPage"); + } + + /** + * Render toolbar form + * + * @param array $a_pages + */ + protected function renderToolbar($a_pages) + { + $ilToolbar = $this->toolbar; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilUser = $this->user; + + include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; + + if (!$this->has_datasets) { + $button = ilLinkButton::getInstance(); + $button->setCaption("survey_add_new_question"); + $button->setUrl($ilCtrl->getLinkTarget($this, "addQuestionToolbarForm")); + $ilToolbar->addStickyItem($button); + + if ($this->object->isPoolActive()) { + //$ilToolbar->addSeparator(); + + $last_on_page = 0; + if ($a_pages && + is_array($a_pages[$this->current_page-1])) { + $last_on_page = $a_pages[$this->current_page-1]; + $last_on_page = array_pop($last_on_page); + $last_on_page = $last_on_page["question_id"]; + } + + $ilCtrl->setParameter($this->editor_gui, "pgov", $this->current_page); + $ilCtrl->setParameter($this->editor_gui, "pgov_pos", $last_on_page . "c"); + + $cmd = ($ilUser->getPref('svy_insert_type') == 1 || + strlen($ilUser->getPref('svy_insert_type')) == 0) + ? 'browseForQuestions' + : 'browseForQuestionblocks'; + + $button = ilLinkButton::getInstance(); + $button->setCaption("browse_for_questions"); + $button->setUrl($ilCtrl->getLinkTarget($this->editor_gui, $cmd)); + $ilToolbar->addStickyItem($button); + + $ilCtrl->setParameter($this->editor_gui, "pgov", ""); + $ilCtrl->setParameter($this->editor_gui, "pgov_pos", ""); + } + + if ($a_pages) { + $ilToolbar->addSeparator(); + } + } + + // parse data for pages drop-down + if ($a_pages) { + // previous/next + + $ilCtrl->setParameter($this, "pg", $this->current_page-1); + $button = ilLinkButton::getInstance(); + $button->setCaption("survey_prev_question"); + if ($this->has_previous_page) { + $button->setUrl($ilCtrl->getLinkTarget($this, "renderPage")); + } + $button->setDisabled(!$this->has_previous_page); + $ilToolbar->addStickyItem($button); + + $ilCtrl->setParameter($this, "pg", $this->current_page+1); + $button = ilLinkButton::getInstance(); + $button->setCaption("survey_next_question"); + if ($this->has_next_page) { + $button->setUrl($ilCtrl->getLinkTarget($this, "renderPage")); + } + $button->setDisabled(!$this->has_next_page); + $ilToolbar->addStickyItem($button); + + $ilCtrl->setParameter($this, "pg", $this->current_page); // #14615 + + foreach ($a_pages as $idx => $questions) { + $page = $questions; + $page = array_shift($page); + if ($page["questionblock_id"]) { + $pages_drop[$idx+1] = $page["questionblock_title"]; + + if (sizeof($questions) > 1) { + foreach ($questions as $question) { + $pages_drop[($idx+1) . "__" . $question["question_id"]] = "- " . $question["title"]; + } + } + } else { + $pages_drop[$idx+1] = strip_tags($page["title"]); + } + } + } + + // jump to page + if (is_array($pages_drop) && count($pages_drop) > 1) { + //$ilToolbar->addSeparator(); + + $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $si = new ilSelectInputGUI($lng->txt("survey_jump_to"), "jump"); + $si->addCustomAttribute("onChange=\"forms['ilToolbar'].submit();\""); + $si->setOptions($pages_drop); + $si->setValue($this->current_page); + $ilToolbar->addInputItem($si, true); + + // we need this to have to right cmd + $cmd = new ilHiddenInputGUI("cmd[renderPage]"); + $cmd->setValue("1"); + $ilToolbar->addInputItem($cmd); + + if (!$this->has_datasets) { + $ilToolbar->addSeparator(); + + $ilCtrl->setParameter($this, "csum", md5(print_r($a_pages[$this->current_page-1], true))); + $url = $ilCtrl->getLinkTarget($this, "deleteBlock"); + $ilCtrl->setParameter($this, "csum", ""); + + $button = ilLinkButton::getInstance(); + $button->setCaption("survey_delete_page"); + $button->setUrl($url); + $ilToolbar->addButtonInstance($button); + + $ilToolbar->addSeparator(); + + $button = ilLinkButton::getInstance(); + $button->setCaption("survey_move_page"); + $button->setUrl($ilCtrl->getLinkTarget($this, "movePageForm")); + $ilToolbar->addButtonInstance($button); + } + } + } + + /** + * render questions per page + */ + protected function renderPage() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + $rbacsystem = $this->rbacsystem; + + $pages = $this->object->getSurveyPages(); + $this->has_next_page = ($this->current_page < sizeof($pages)); + $this->has_previous_page = ($this->current_page > 1); + $this->has_datasets = ilObjSurvey::_hasDatasets($this->object->getSurveyId()); + + $mess = ""; + if ($this->has_datasets) { + $mbox = new ilSurveyContainsDataMessageBoxGUI(); + $mess = $mbox->getHTML(); + } + + $ilCtrl->setParameter($this, "pg", $this->current_page); + $ilCtrl->setParameter($this, "pgov", ""); + + $this->renderToolbar($pages); + + if ($pages) { + $ttpl = new ilTemplate("tpl.il_svy_svy_page_view.html", true, true, "Modules/Survey"); + $ttpl->setVariable("FORM_ACTION", $ilCtrl->getFormAction($this)); + $lng->loadLanguageModule("form"); + + $read_only = ($this->has_datasets || !$rbacsystem->checkAccess("write", $this->ref_id)); + + $commands = $multi_commands = array(); + + if (!$read_only) { + // clipboard is empty + if (!$_SESSION["survey_page_view"][$this->ref_id]["clipboard"]) { + $multi_commands[] = array("cmd"=>"multiDelete", "text"=>$lng->txt("delete")); + $multi_commands[] = array("cmd"=>"multiCut", "text"=>$lng->txt("cut")); + $multi_commands[] = array("cmd"=>"multiCopy", "text"=>$lng->txt("copy")); + $multi_commands[] = array("cmd"=>"selectAll", "text"=>$lng->txt("select_all")); + } else { + if (!$this->suppress_clipboard_msg) { + ilUtil::sendInfo($lng->txt("survey_clipboard_notice")); + } + $multi_commands[] = array("cmd"=>"clearClipboard", "text"=>$lng->txt("survey_dnd_clear_clipboard")); + } + + // help - see ilPageObjectGUI::insertHelp() + $lng->loadLanguageModule("content"); + $ttpl->setCurrentBlock("help_section"); + $ttpl->setVariable("TXT_ADD_EL", $lng->txt("cont_add_elements")); + include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); + $ttpl->setVariable("PLUS", ilGlyphGUI::get(ilGlyphGUI::ADD)); + $ttpl->setVariable("DRAG_ARROW", ilGlyphGUI::get(ilGlyphGUI::DRAG)); + $ttpl->setVariable("TXT_DRAG", $lng->txt("cont_drag_and_drop_elements")); + $ttpl->setVariable("TXT_SEL", $lng->txt("cont_double_click_to_delete")); + $ttpl->parseCurrentBlock(); + + $ttpl->setVariable("DND_INIT_JS", "initDragElements();"); + + + // tiny mce + + include_once "./Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php"; + $tags = ilObjAdvancedEditing::_getUsedHTMLTags("survey"); + + /** + * Alex Killing, 27 July 2018 + * I removed a line $tpl->addJavascript("./Services/RTE/tiny_mce_.../tiny_mce_src.js"); at the end + * of this function. Currently I have no idea when this tiny will be presented... + * Maybe a bug will come out of this during 5.4 testing + */ + include_once "./Services/RTE/classes/class.ilTinyMCE.php"; + $tiny = new ilTinyMCE(); + $ttpl->setVariable("WYSIWYG_BLOCKFORMATS", $tiny->_buildAdvancedBlockformatsFromHTMLTags($tags)); + $ttpl->setVariable("WYSIWYG_VALID_ELEMENTS", $tiny->_getValidElementsFromHTMLTags($tags)); + + $buttons_1 = $tiny->_buildAdvancedButtonsFromHTMLTags(1, $tags); + $buttons_2 = $tiny->_buildAdvancedButtonsFromHTMLTags(2, $tags) . ',' . + $tiny->_buildAdvancedTableButtonsFromHTMLTags($tags) . + ($tiny->getStyleSelect() ? ',styleselect' : ''); + $buttons_3 = $tiny->_buildAdvancedButtonsFromHTMLTags(3, $tags); + $ttpl->setVariable('WYSIWYG_BUTTONS_1', ilTinyMCE::removeRedundantSeparators($buttons_1)); + $ttpl->setVariable('WYSIWYG_BUTTONS_2', ilTinyMCE::removeRedundantSeparators($buttons_2)); + $ttpl->setVariable('WYSIWYG_BUTTONS_3', ilTinyMCE::removeRedundantSeparators($buttons_3)); + } + + // commands + if (count($multi_commands) > 0) { + foreach ($multi_commands as $cmd) { + $ttpl->setCurrentBlock("multi_cmd"); + $ttpl->setVariable("ORG_CMD_MULTI", "renderPage"); + $ttpl->setVariable("MULTI_CMD", $cmd["cmd"]); + $ttpl->setVariable("MULTI_CMD_TXT", $cmd["text"]); + $ttpl->parseCurrentBlock(); + } + + $ttpl->setCurrentBlock("multi_cmds"); + $ttpl->setVariable("MCMD_ALT", $lng->txt("commands")); + $ttpl->setVariable("MCMD_IMG", ilUtil::getImagePath("arrow_downright.svg")); + $ttpl->parseCurrentBlock(); + } + + // nodes + $ttpl->setVariable("NODES", $this->getPageNodes( + $pages[$this->current_page-1], + $this->has_previous_page, + $this->has_next_page, + $read_only + )); + + $tpl->setContent($mess . $ttpl->get()); + + // add js to template + include_once("./Services/YUI/classes/class.ilYuiUtil.php"); + ilYuiUtil::initDragDrop(); + $tpl->addJavascript("./Modules/Survey/js/SurveyPageView.js"); + } + } + + /** + * Get Form HTML + * + * @param array $questions + * @param bool $a_has_previous_page + * @param bool $a_has_next_page + * @param bool $a_readonly + * @return string + */ + public function getPageNodes(array $a_questions, $a_has_previous_page = false, $a_has_next_page = false, $a_readonly = false) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $ttpl = new ilTemplate("tpl.il_svy_svy_page_view_nodes.html", true, true, "Modules/Survey"); + + $has_clipboard = (bool) $_SESSION["survey_page_view"][$this->ref_id]["clipboard"]; + + // question block ? + + $first_question = $a_questions; + $first_question = array_shift($first_question); + + if ($first_question["questionblock_id"]) { + $menu = array(); + + if (!$a_readonly && !$has_clipboard) { + $menu[] = array("cmd" => "editBlock", "text" => $lng->txt("edit")); + } + + if ($first_question["questionblock_show_blocktitle"]) { + $block_status = $lng->txt("survey_block_visible"); + } else { + $block_status = $lng->txt("survey_block_hidden"); + } + + $this->renderPageNode( + $ttpl, + "block", + $first_question["questionblock_id"], + $first_question["questionblock_title"] . " (" . $block_status . ")", + $menu, + false, + false, + $block_status + ); + } + + + // questions/headings + + include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"; + $questiontypes = ilObjSurveyQuestionPool::_getQuestiontypes(); + $questionpools = array_keys($this->object->getQuestionpoolTitles(true)); + + $counter = $question_count; + $block_done = null; + foreach ($a_questions as $idx => $question) { + // drop area + + $menu = array(); + + if (!$a_readonly) { + if (!$has_clipboard) { + foreach ($questiontypes as $trans => $item) { + $menu[] = array("cmd"=> "addQuestion_" . $item["questiontype_id"], + "text"=> sprintf($lng->txt("svy_page_add_question"), $trans)); + } + + if ($this->object->isPoolActive()) { + $menu[] = array("cmd"=> "addPoolQuestion", + "text"=> $lng->txt("browse_for_questions")); + } + } else { + $menu[] = array("cmd" => "paste", "text" => $lng->txt("survey_dnd_paste")); + } + } + + $this->renderPageNode($ttpl, "droparea", $question["question_id"], null, $menu, true); + + // question + $question_gui = $this->object->getQuestionGUI($question["type_tag"], $question["question_id"]); + $question_form = $question_gui->getWorkingForm( + array(), + $this->object->getShowQuestionTitles(), + $question["questionblock_show_questiontext"], + null, + $this->object->getSurveyId() + ); + + $menu = array(); + + if (!$a_readonly && !$has_clipboard) { + $menu[] = array("cmd" => "editQuestion", "text" => $lng->txt("edit")); + $menu[] = array("cmd" => "cutQuestion", "text" => $lng->txt("cut")); + $menu[] = array("cmd" => "copyQuestion", "text" => $lng->txt("copy")); + + if (sizeof($a_questions) > 1 && $idx > 0) { + $menu[] = array("cmd" => "splitPage", "text" => $lng->txt("survey_dnd_split_page")); + } + if ($a_has_next_page) { + $menu[] = array("cmd" => "moveNext", "text" => $lng->txt("survey_dnd_move_next")); + } + if ($a_has_previous_page) { + $menu[] = array("cmd" => "movePrevious", "text" => $lng->txt("survey_dnd_move_previous")); + } + + $menu[] = array("cmd" => "deleteQuestion", "text" => $lng->txt("delete")); + + // heading + if ($question["heading"]) { + $menu[] = array("cmd" => "editHeading", "text" => $lng->txt("survey_edit_heading")); + $menu[] = array("cmd" => "deleteHeading", "text" => $lng->txt("survey_delete_heading")); + } else { + $menu[] = array("cmd" => "addHeading", "text" => $lng->txt("add_heading")); + } + } + + if ($first_question["questionblock_show_questiontext"]) { + $question_title_status = $lng->txt("survey_question_text_visible"); + } else { + $question_title_status = $lng->txt("survey_question_text_hidden"); + } + + $this->renderPageNode( + $ttpl, + "question", + $question["question_id"], + $question_form, + $menu, + false, + $question["title"], + $question_title_status, + $question["heading"] + ); + + $ilCtrl->setParameter($this, "eqid", ""); + } + + + // last position (no question id) + + $menu = array(); + + if (!$a_readonly) { + if (!$has_clipboard) { + foreach ($questiontypes as $trans => $item) { + $menu[] = array("cmd"=> "addQuestion_" . $item["questiontype_id"], + "text"=> sprintf($lng->txt("svy_page_add_question"), $trans)); + } + + if ($this->object->isPoolActive()) { + $menu[] = array("cmd"=> "addPoolQuestion", + "text"=> $lng->txt("browse_for_questions")); + } + } else { + $menu[] = array("cmd" => "paste", "text" => $lng->txt("survey_dnd_paste")); + } + } + + $this->renderPageNode($ttpl, "page", "end", null, $menu, true); + + return $ttpl->get(); + } + + /** + * Render single of dnd page view + * + * @param ilTemplate $a_tpl + * @param string $a_type + * @param int $a_id + * @param string $a_content + * @param array $a_menu + * @param bool $a_spacer + * @param string $a_subtitle + * @param string $a_heading + */ + public function renderPageNode(ilTemplate $a_tpl, $a_type, $a_id, $a_content = null, array $a_menu = null, $a_spacer = false, $a_subtitle = false, $a_status = false, $a_heading = false) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $node_id = $a_type . "_" . $a_id; + + if ($a_spacer) { + if ($a_menu) { + // drop area menu + foreach ($a_menu as $mcnt => $menu_item) { + $ilCtrl->setParameter($this, "il_hform_node", $node_id); + $ilCtrl->setParameter($this, "il_hform_subcmd", $menu_item["cmd"]); + $url = $ilCtrl->getLinkTarget($this, "renderPage"); + $ilCtrl->setParameter($this, "il_hform_subcmd", ""); + $ilCtrl->setParameter($this, "il_hform_node", ""); + + $a_tpl->setCurrentBlock("menu_cmd"); + $a_tpl->setVariable("TXT_MENU_CMD", $menu_item["text"]); + $a_tpl->setVariable("URL_MENU_CMD", $url); + $a_tpl->parseCurrentBlock(); + } + } + + $a_tpl->setCurrentBlock("drop_area"); + include_once "Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"; + $a_tpl->setVariable("ICON_ADD", ilGlyphGUI::get(ilGlyphGUI::ADD)); + $a_tpl->setVariable("DROP_ID", $a_id); + $a_tpl->parseCurrentBlock(); + } elseif ($a_menu) { + // question action menu + foreach ($a_menu as $mcnt => $menu_item) { + $ilCtrl->setParameter($this, "il_hform_node", $node_id); + $ilCtrl->setParameter($this, "il_hform_subcmd", $menu_item["cmd"]); + $url = $ilCtrl->getLinkTarget($this, "renderPage"); + $ilCtrl->setParameter($this, "il_hform_subcmd", ""); + $ilCtrl->setParameter($this, "il_hform_node", ""); + + $a_tpl->setCurrentBlock("action_cmd"); + $a_tpl->setVariable("TXT_ACTION_CMD", $menu_item["text"]); + $a_tpl->setVariable("URL_ACTION_CMD", $url); + $a_tpl->parseCurrentBlock(); + } + } + + // add heading to content + if ($a_content !== null && + $a_type == "question" && + $a_heading) { + $a_content = "
" . $a_heading . "
" . + $a_content; + } + + if ($a_menu) { + $a_tpl->setVariable("TXT_NODE_CONTENT_ACTIONS", $a_content); + } else { + $a_tpl->setVariable("TXT_NODE_CONTENT_NO_ACTIONS", $a_content); + } + + if ($a_content !== null) { + $drag = ""; + $selectable = false; + switch ($a_type) { + case "block": + $caption = $lng->txt("questionblock"); + break; + + case "question": + $caption = $lng->txt("question") . ": " . $a_subtitle; + $drag = "_drag"; + $selectable = true; + break; + + case "heading": + $caption = $lng->txt("heading"); + break; + + default: + return; + } + + if ($a_status) { + $caption .= " (" . $a_status . ")"; + } + + $a_tpl->setCurrentBlock("list_item"); + $a_tpl->setVariable("NODE_ID", $node_id); + $a_tpl->setVariable("NODE_DRAG", $drag); + $a_tpl->setVariable("TXT_NODE_TYPE", $caption); + if ($selectable) { + $a_tpl->setVariable("SELECTABLE", " selectable"); + } + $a_tpl->parseCurrentBlock(); + } + + $a_tpl->touchBlock("element"); + } + + /** + * Get name for newly created blocks + * + * @return string + */ + public function getAutoBlockTitle() + { + $lng = $this->lng; + + return $lng->txt("survey_auto_block_title"); + } + + public function addPoolQuestion($pos, $node) + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + if ($node == "page_end") { + $pos = $this->object->getSurveyPages(); + $pos = array_pop($pos[$this->current_page-1]); + $pos = $pos["question_id"] . "a"; + } else { + $pos = $pos . "b"; + } + + $ilCtrl->setParameter($this->editor_gui, "pgov", $this->current_page); + $ilCtrl->setParameter($this->editor_gui, "pgov_pos", $pos); + + $cmd = ($ilUser->getPref('svy_insert_type') == 1 || strlen($ilUser->getPref('svy_insert_type')) == 0) ? 'browseForQuestions' : 'browseForQuestionblocks'; + $ilCtrl->redirect($this->editor_gui, $cmd); + } } - -?> \ No newline at end of file diff --git a/Modules/Survey/classes/class.ilSurveyParticipantsGUI.php b/Modules/Survey/classes/class.ilSurveyParticipantsGUI.php index 081fec52bf31eacb6572f5403211aef3377a2f4b..6ed9bfce5ca044fbcd7c4b5271ef915f91621a84 100644 --- a/Modules/Survey/classes/class.ilSurveyParticipantsGUI.php +++ b/Modules/Survey/classes/class.ilSurveyParticipantsGUI.php @@ -1,2003 +1,1867 @@ - -* @version $Id: class.ilObjSurveyGUI.php 43670 2013-07-26 08:41:31Z jluetzen $ -* -* @ilCtrl_Calls ilSurveyParticipantsGUI: ilRepositorySearchGUI -* -* @ingroup ModulesSurvey -*/ -class ilSurveyParticipantsGUI -{ - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var Logger - */ - protected $log; - - protected $parent_gui; // [ilObjSurveyGUI] - protected $object; // [ilObjSurvey] - protected $ref_id; // [int] - protected $has_write; // [bool] - - public function __construct(ilObjSurveyGUI $a_parent_gui, $a_has_write_access) - { - global $DIC; - - $this->tabs = $DIC->tabs(); - $this->toolbar = $DIC->toolbar(); - $this->access = $DIC->access(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->user = $DIC->user(); - $this->log = $DIC["ilLog"]; - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $tpl = $DIC["tpl"]; - - $this->parent_gui = $a_parent_gui; - $this->object = $this->parent_gui->object; - $this->ref_id = $this->object->getRefId(); - $this->has_write = (bool)$a_has_write_access; - - $this->ctrl = $ilCtrl; - $this->lng = $lng; - $this->tpl = $tpl; - } - - protected function handleWriteAccess() - { - if(!$this->has_write) - { - include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; - throw new ilSurveyException("Permission denied"); - } - } - - public function executeCommand() - { - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - $cmd = $ilCtrl->getCmd("maintenance"); - $next_class = $this->ctrl->getNextClass($this); - - switch($next_class) - { - case 'ilrepositorysearchgui': - include_once('./Services/Search/classes/class.ilRepositorySearchGUI.php'); - $rep_search = new ilRepositorySearchGUI(); - - if(!$_REQUEST["appr360"] && !$_REQUEST["rate360"]) - { - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($this->lng->txt("btn_back"), - $this->ctrl->getLinkTarget($this, "invite")); - - $rep_search->setCallback($this, - 'inviteUserGroupObject', - array( - ) - ); - - // Set tabs - $this->ctrl->setReturn($this, 'invite'); - $this->ctrl->forwardCommand($rep_search); - $ilTabs->setTabActive('invitation'); - } - else if($_REQUEST["rate360"]) - { - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($this->lng->txt("btn_back"), - $this->ctrl->getLinkTarget($this, "listAppraisees")); - - $this->ctrl->setParameter($this, "rate360", 1); - $this->ctrl->saveParameter($this, "appr_id"); - - $rep_search->setCallback($this, - 'addRater', - array( - ) - ); - - // Set tabs - $this->ctrl->setReturn($this, 'editRaters'); - $this->ctrl->forwardCommand($rep_search); - } - else - { - $ilTabs->activateTab("survey_360_appraisees"); - $this->ctrl->setParameter($this, "appr360", 1); - - $rep_search->setCallback($this, - 'addAppraisee', - array( - ) - ); - - // Set tabs - $this->ctrl->setReturn($this, 'listAppraisees'); - $this->ctrl->forwardCommand($rep_search); - } - break; - - default: - $cmd .= "Object"; - $this->$cmd(); - break; - } - } - - protected function filterSurveyParticipantsByAccess($a_finished_ids = null) - { - $all_participants = $this->object->getSurveyParticipants($a_finished_ids); - $participant_ids = []; - foreach($all_participants as $participant) - { - $participant_ids[] = $participant['usr_id']; - } - - - $filtered_participant_ids = $this->access->filterUserIdsByRbacOrPositionOfCurrentUser( - 'read_results', - 'access_results', - $this->object->getRefId(), - $participant_ids - ); - $participants = []; - foreach($all_participants as $username => $user_data) - { - if(!$user_data['usr_id']) - { - $participants[$username] = $user_data; - } - if(in_array($user_data['usr_id'], $filtered_participant_ids)) - { - $participants[$username] = $user_data; - } - } - return $participants; - } - - - /** - * Participants maintenance - */ - public function maintenanceObject() - { - $ilToolbar = $this->toolbar; - - if($this->object->get360Mode()) - { - return $this->listAppraiseesObject(); - } - - //Btn Determine Competence Levels - if($this->object->getMode() == ilObjSurvey::MODE_SELF_EVAL) - { - include_once("./Services/Skill/classes/class.ilSkillManagementSettings.php"); - $skmg_set = new ilSkillManagementSettings(); - if ($this->object->getSkillService() && $skmg_set->isActivated()) - { - $ilToolbar->addButton($this->lng->txt("survey_calc_skills"), - $this->ctrl->getLinkTargetByClass("ilsurveyskilldeterminationgui"), ""); - } - } - - $this->handleWriteAccess(); - $this->setCodesSubtabs(); - - $ilToolbar->addButton($this->lng->txt('svy_delete_all_user_data'), - $this->ctrl->getLinkTarget($this, 'deleteAllUserData')); - - include_once "./Modules/Survey/classes/tables/class.ilSurveyMaintenanceTableGUI.php"; - $table_gui = new ilSurveyMaintenanceTableGUI($this, 'maintenance'); - - //$total =& $this->object->getSurveyParticipants(); - $total = $this->filterSurveyParticipantsByAccess(); - $data = array(); - foreach ($total as $user_data) - { - $finished = false; - if((bool)$user_data["finished"]) - { - $finished = $user_data["finished_tstamp"]; - } - $wt = $this->object->getWorkingtimeForParticipant($user_data["active_id"]); - $last_access = $this->object->getLastAccess($user_data["active_id"]); - array_push($data, array( - 'id' => $user_data["active_id"], - 'name' => $user_data["sortname"], - 'login' => $user_data["login"], - 'last_access' => $last_access, - 'workingtime' => $wt, - 'finished' => $finished - )); - } - $table_gui->setData($data); - $this->tpl->setVariable('ADM_CONTENT', $table_gui->getHTML()); - } - - protected function isAnonymousListActive() - { - $surveySetting = new ilSetting("survey"); - if($surveySetting->get("anonymous_participants", false)) - { - if($this->object->hasAnonymizedResults() && - $this->object->hasAnonymousUserList()) - { - $end = $this->object->getEndDate(); - if($end && $end < date("YmdHis")) - { - $min = $surveySetting->get("anonymous_participants_min", 0); - $total = $this->object->getSurveyParticipants(); - if(!$min || sizeof($total) >= $min) - { - return true; - } - } - } - } - return false; - } - - /** - * Set the tabs for the access codes section - * - * @access private - */ - function setCodesSubtabs() - { - $ilTabs = $this->tabs; - - // not used in 360° mode - - // maintenance - $ilTabs->addSubTabTarget("sub_tab_dashboard", - $this->ctrl->getLinkTarget($this,'maintenance'), - array("maintenance", "deleteAllUserData"), - ""); - - if($this->isAnonymousListActive()) - { - $ilTabs->addSubTabTarget("svy_anonymous_participants_svy", - $this->ctrl->getLinkTarget($this,'listParticipants'), - array("listParticipants"), - ""); - } - - if(!$this->object->isAccessibleWithoutCode()) - { - $ilTabs->addSubTabTarget("codes", - $this->ctrl->getLinkTarget($this,'codes'), - array("codes", "editCodes", "createSurveyCodes", "setCodeLanguage", "deleteCodes", "exportCodes", - "importExternalMailRecipientsFromFileForm", "importExternalMailRecipientsFromTextForm"), - "" - ); - } - - $hidden_tabs = array(); - $template = $this->object->getTemplate(); - if($template) - { - include_once "Services/Administration/classes/class.ilSettingsTemplate.php"; - $template = new ilSettingsTemplate($template); - $hidden_tabs = $template->getHiddenTabs(); - } - - // #12277 - invite - if(!in_array("invitation", $hidden_tabs)) - { - if($this->access->checkAccess('write', '', $this->object->getRefId())) - { - $ilTabs->addSubTabTarget("invitation", - $this->ctrl->getLinkTarget($this, 'invite'), - array("invite", "saveInvitationStatus", - "inviteUserGroup", "disinviteUserGroup"), - ""); - } - } - - $data = $this->object->getExternalCodeRecipients(); - if (count($data)) - { - $ilTabs->addSubTabTarget - ( - "mail_survey_codes", - $this->ctrl->getLinkTarget($this, "mailCodes"), - array("mailCodes", "sendCodesMail", "insertSavedMessage", "deleteSavedMessage"), - "" - ); - } - } - - /** - * Disinvite users or groups from a survey - */ - public function disinviteUserGroupObject() - { - // disinvite users - if (is_array($_POST["user_select"])) - { - foreach ($_POST["user_select"] as $user_id) - { - $this->object->disinviteUser($user_id); - } - } - ilUtil::sendSuccess($this->lng->txt('msg_users_disinvited'), true); - $this->ctrl->redirect($this, "invite"); - } - - /** - * Invite users or groups to a survey - */ - public function inviteUserGroupObject($a_user_ids = array()) - { - $invited = 0; - // add users to invitation - if (is_array($a_user_ids)) - { - foreach ($a_user_ids as $user_id) - { - $this->object->inviteUser($user_id); - $invited++; - } - } - if ($invited == 0) - { - ilUtil::sendFailure($this->lng->txt('no_user_invited'), TRUE); - return false; - } - else - { - ilUtil::sendSuccess(sprintf($this->lng->txt('users_invited'), $invited), TRUE); - return false; - } - $this->ctrl->redirect($this, "invite"); - } - - /** - * Saves the status of the invitation tab - */ - public function saveInvitationStatusObject() - { - $mode = $_POST['invitation']; - switch ($mode) - { - case 0: - $this->object->setInvitation(ilObjSurvey::INVITATION_OFF); - break; - case 1: - $this->object->setInvitationAndMode(ilObjSurvey::INVITATION_ON, ilObjSurvey::MODE_UNLIMITED); - break; - case 2: - $this->object->setInvitationAndMode(ilObjSurvey::INVITATION_ON, ilObjSurvey::MODE_PREDEFINED_USERS); - break; - } - $this->object->saveToDb(); - ilUtil::sendSuccess($this->lng->txt('msg_obj_modified'), true); - $this->ctrl->redirect($this, "invite"); - } - - /** - * Creates the output for user/group invitation to a survey - */ - public function inviteObject() - { - $ilAccess = $this->access; - $rbacsystem = $this->rbacsystem; - $ilToolbar = $this->toolbar; - $lng = $this->lng; - - $this->handleWriteAccess(); - $this->setCodesSubtabs(); - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - $form->setTableWidth("500"); - $form->setId("invite"); - - // invitation - $header = new ilFormSectionHeaderGUI(); - $header->setTitle($this->lng->txt("invitation")); - $form->addItem($header); - - // invitation mode - $invitation = new ilRadioGroupInputGUI($this->lng->txt('invitation_mode'), "invitation"); - $invitation->setInfo($this->lng->txt('invitation_mode_desc')); - $invitation->addOption(new ilRadioOption($this->lng->txt("invitation_off"), 0, '')); - $surveySetting = new ilSetting("survey"); - if ($surveySetting->get("unlimited_invitation")) - { - $invitation->addOption(new ilRadioOption($this->lng->txt("unlimited_users"), 1, '')); - } - $invitation->addOption(new ilRadioOption($this->lng->txt("predefined_users"), 2, '')); - $inv = 0; - if ($this->object->getInvitation()) - { - $inv = $this->object->getInvitationMode() + 1; - } - $invitation->setValue($inv); - $form->addItem($invitation); - - $form->addCommandButton("saveInvitationStatus", $this->lng->txt("save")); - - $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.il_svy_svy_invite.html", "Modules/Survey"); - $this->tpl->setVariable("INVITATION_TABLE", $form->getHTML()); - - if ($this->object->getInvitation() && $this->object->getInvitationMode() == 1) - { - // search button - include_once './Services/Search/classes/class.ilRepositorySearchGUI.php'; - ilRepositorySearchGUI::fillAutoCompleteToolbar( - $this, - $tb, - array( - 'auto_complete_name' => $lng->txt('user'), - 'submit_name' => $lng->txt('svy_invite_action') - ) - ); - - $ilToolbar->addSpacer(); - - $ilToolbar->addButton($this->lng->txt("svy_search_users"), - $this->ctrl->getLinkTargetByClass('ilRepositorySearchGUI','')); - - $this->tpl->setVariable("ADM_CONTENT", $form->getHTML()); - - $invited_users = $this->object->getUserData($this->object->getInvitedUsers()); - include_once "./Modules/Survey/classes/tables/class.ilSurveyInvitedUsersTableGUI.php"; - $table_gui = new ilSurveyInvitedUsersTableGUI($this, 'invite'); - $table_gui->setData($invited_users); - $this->tpl->setVariable('TBL_INVITED_USERS', $table_gui->getHTML()); - } - } - - /** - * Creates a confirmation form for delete all user data - */ - public function deleteAllUserDataObject() - { - include_once "Services/Utilities/classes/class.ilConfirmationGUI.php"; - $cgui = new ilConfirmationGUI(); - $cgui->setHeaderText($this->lng->txt("confirm_delete_all_user_data")); - $cgui->setFormAction($this->ctrl->getFormAction($this, "deleteAllUserData")); - $cgui->setCancel($this->lng->txt("cancel"), "cancelDeleteAllUserData"); - $cgui->setConfirm($this->lng->txt("confirm"), "confirmDeleteAllUserData"); - $this->tpl->setContent($cgui->getHTML()); - } - - /** - * Deletes all user data of the survey after confirmation - */ - public function confirmDeleteAllUserDataObject() - { - if($this->access->checkAccess('write', '', $this->object->getRefId())) - { - $this->object->deleteAllUserData(); - } - else - { - $participants = $this->filterSurveyParticipantsByAccess(); - foreach($participants as $something => $participant_data) - { - $this->object->removeSelectedSurveyResults([$participant_data['active_id']]); - } - } - - - - // #11558 - re-open closed appraisees - if($this->object->get360Mode()) - { - $this->object->openAllAppraisees(); - } - - ilUtil::sendSuccess($this->lng->txt("svy_all_user_data_deleted"), true); - $this->ctrl->redirect($this, "maintenance"); - } - - /** - * Cancels delete of all user data in maintenance - */ - public function cancelDeleteAllUserDataObject() - { - $this->ctrl->redirect($this, "maintenance"); - } - - /** - * Deletes all user data for the test object - */ - public function confirmDeleteSelectedUserDataObject() - { - $this->object->removeSelectedSurveyResults($_POST["chbUser"]); - ilUtil::sendSuccess($this->lng->txt("svy_selected_user_data_deleted"), true); - $this->ctrl->redirect($this, "maintenance"); - } - - /** - * Cancels the deletion of all user data for the test object - */ - public function cancelDeleteSelectedUserDataObject() - { - ilUtil::sendInfo($this->lng->txt('msg_cancel'), true); - $this->ctrl->redirect($this, "maintenance"); - } - - /** - * Asks for a confirmation to delete selected user data of the test object - */ - public function deleteSingleUserResultsObject() - { - $this->handleWriteAccess(); - - if (!is_array($_POST["chbUser"]) || count($_POST["chbUser"]) == 0) - { - ilUtil::sendInfo($this->lng->txt('no_checkbox'), true); - $this->ctrl->redirect($this, "maintenance"); - } - - ilUtil::sendQuestion($this->lng->txt("confirm_delete_single_user_data")); - include_once "./Modules/Survey/classes/tables/class.ilSurveyMaintenanceTableGUI.php"; - $table_gui = new ilSurveyMaintenanceTableGUI($this, 'maintenance', true); - $total =& $this->object->getSurveyParticipants(); - $data = array(); - foreach ($total as $user_data) - { - if (in_array($user_data['active_id'], $_POST['chbUser'])) - { - $last_access = $this->object->getLastAccess($user_data["active_id"]); - array_push($data, array( - 'id' => $user_data["active_id"], - 'name' => $user_data["sortname"], - 'login' => $user_data["login"], - 'last_access' => $last_access - )); - } - } - $table_gui->setData($data); - $this->tpl->setVariable('ADM_CONTENT', $table_gui->getHTML()); - } - - /** - * Change survey language for direct access URL's - */ - public function setCodeLanguageObject() - { - if (strcmp($_POST["lang"], "-1") != 0) - { - $ilUser = $this->user; - $ilUser->writePref("survey_code_language", $_POST["lang"]); - } - ilUtil::sendSuccess($this->lng->txt('language_changed'), true); - $this->ctrl->redirect($this, 'codes'); - } - - /** - * Display the survey access codes tab - */ - public function codesObject() - { - $ilUser = $this->user; - $ilToolbar = $this->toolbar; - - $this->handleWriteAccess(); - $this->setCodesSubtabs(); - - if ($this->object->isAccessibleWithoutCode()) - { - return ilUtil::sendInfo($this->lng->txt("survey_codes_no_anonymization")); - } - - $default_lang = $ilUser->getPref("survey_code_language"); - - // creation buttons - $ilToolbar->setFormAction($this->ctrl->getFormAction($this)); - - include_once("./Services/Form/classes/class.ilTextInputGUI.php"); - $si = new ilTextInputGUI($this->lng->txt("new_survey_codes"), "nrOfCodes"); - $si->setValue(1); - $si->setSize(3); - $ilToolbar->addInputItem($si, true); - - include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; - - $button = ilSubmitButton::getInstance(); - $button->setCaption("create"); - $button->setCommand("createSurveyCodes"); - $ilToolbar->addButtonInstance($button); - - $ilToolbar->addSeparator(); - - $button = ilSubmitButton::getInstance(); - $button->setCaption("import_from_file"); - $button->setCommand("importExternalMailRecipientsFromFileForm"); - $ilToolbar->addButtonInstance($button); - - $button = ilSubmitButton::getInstance(); - $button->setCaption("import_from_text"); - $button->setCommand("importExternalMailRecipientsFromTextForm"); - $ilToolbar->addButtonInstance($button); - - $ilToolbar->addSeparator(); - - $button = ilSubmitButton::getInstance(); - $button->setCaption("svy_import_codes"); - $button->setCommand("importAccessCodes"); - $ilToolbar->addButtonInstance($button); - - $ilToolbar->addSeparator(); - - $languages = $this->lng->getInstalledLanguages(); - $options = array(); - $this->lng->loadLanguageModule("meta"); - foreach ($languages as $lang) - { - $options[$lang] = $this->lng->txt("meta_l_".$lang); - } - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $si = new ilSelectInputGUI($this->lng->txt("survey_codes_lang"), "lang"); - $si->setOptions($options); - $si->setValue($default_lang); - $ilToolbar->addInputItem($si, true); - - $button = ilSubmitButton::getInstance(); - $button->setCaption("set"); - $button->setCommand("setCodeLanguage"); - $ilToolbar->addButtonInstance($button); - - include_once "./Modules/Survey/classes/tables/class.ilSurveyCodesTableGUI.php"; - $table_gui = new ilSurveyCodesTableGUI($this, 'codes'); - $survey_codes = $this->object->getSurveyCodesTableData(null, $default_lang); - $table_gui->setData($survey_codes); - $this->tpl->setContent($table_gui->getHTML()); - } - - public function editCodesObject() - { - if(isset($_GET["new_ids"])) - { - $ids = explode(";", $_GET["new_ids"]); - } - else - { - $ids = (array)$_POST["chb_code"]; - } - if(!$ids) - { - ilUtil::sendFailure($this->lng->txt('no_checkbox'), true); - $this->ctrl->redirect($this, 'codes'); - } - - $this->handleWriteAccess(); - $this->setCodesSubtabs(); - - include_once "./Modules/Survey/classes/tables/class.ilSurveyCodesEditTableGUI.php"; - $table_gui = new ilSurveyCodesEditTableGUI($this, 'editCodes'); - $table_gui->setData($this->object->getSurveyCodesTableData($ids)); - $this->tpl->setContent($table_gui->getHTML()); - } - - public function updateCodesObject() - { - if(!is_array($_POST["chb_code"])) - { - $this->ctrl->redirect($this, 'codes'); - } - - $errors = array(); - $error_message = ""; - foreach($_POST["chb_code"] as $id) - { - if(!$this->object->updateCode($id, - $_POST["chb_mail"][$id], - $_POST["chb_lname"][$id], - $_POST["chb_fname"][$id], - $_POST["chb_sent"][$id] - )) - { - array_push($errors, array($_POST["chb_mail"][$id], $_POST["chb_lname"][$id], $_POST["chb_fname"][$id])); - }; - } - if(empty($errors)) - { - ilUtil::sendSuccess($this->lng->txt('settings_saved'), true); - } - else - { - foreach ($errors as $error) - { - $error_message .= sprintf($this->lng->txt("error_save_code"), $error[0],$error[1],$error[2]); - } - ilUtil::sendFailure($error_message, true); - } - - $this->ctrl->redirect($this, 'codes'); - } - - public function deleteCodesConfirmObject() - { - if (is_array($_POST["chb_code"]) && (count($_POST["chb_code"]) > 0)) - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setHeaderText($this->lng->txt("survey_code_delete_sure")); - - $cgui->setFormAction($this->ctrl->getFormAction($this)); - $cgui->setCancel($this->lng->txt("cancel"), "codes"); - $cgui->setConfirm($this->lng->txt("confirm"), "deleteCodes"); - - $data = $this->object->getSurveyCodesTableData($_POST["chb_code"]); - - foreach ($data as $item) - { - if($item["used"]) - { - continue; - } - - $title = array($item["code"]); - $item["email"] ? $title[] = $item["email"] : null; - $item["last_name"] ? $title[] = $item["last_name"] : null; - $item["first_name"] ? $title[] = $item["first_name"] : null; - $title = implode(", ", $title); - - $cgui->addItem("chb_code[]", $item["code"], $title); - } - - $this->tpl->setContent($cgui->getHTML()); - } - else - { - ilUtil::sendFailure($this->lng->txt('no_checkbox'), true); - $this->ctrl->redirect($this, 'codes'); - } - } - - /** - * Delete a list of survey codes - */ - public function deleteCodesObject() - { - if (is_array($_POST["chb_code"]) && (count($_POST["chb_code"]) > 0)) - { - foreach ($_POST["chb_code"] as $survey_code) - { - $this->object->deleteSurveyCode($survey_code); - } - ilUtil::sendSuccess($this->lng->txt('codes_deleted'), true); - } - else - { - ilUtil::sendInfo($this->lng->txt('no_checkbox'), true); - } - $this->ctrl->redirect($this, 'codes'); - } - - /** - * Exports a list of survey codes - */ - public function exportCodesObject() - { - if (is_array($_POST["chb_code"]) && (count($_POST["chb_code"]) > 0)) - { - $export = $this->object->getSurveyCodesForExport(null, $_POST["chb_code"]); - ilUtil::deliverData($export, ilUtil::getASCIIFilename($this->object->getTitle() . ".csv")); - } - else - { - ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); - $this->ctrl->redirect($this, 'codes'); - } - } - - /** - * Exports all survey codes - */ - public function exportAllCodesObject() - { - $export = $this->object->getSurveyCodesForExport(); - ilUtil::deliverData($export, ilUtil::getASCIIFilename($this->object->getTitle() . ".csv")); - } - - /** - * Import codes from export codes file (upload form) - */ - protected function importAccessCodesObject() - { - $this->handleWriteAccess(); - $this->setCodesSubtabs(); - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form_import_file = new ilPropertyFormGUI(); - $form_import_file->setFormAction($this->ctrl->getFormAction($this)); - $form_import_file->setTableWidth("100%"); - $form_import_file->setId("codes_import_file"); - - $headerfile = new ilFormSectionHeaderGUI(); - $headerfile->setTitle($this->lng->txt("svy_import_codes")); - $form_import_file->addItem($headerfile); - - $export_file = new ilFileInputGUI($this->lng->txt("codes"), "codes"); - $export_file->setInfo(sprintf($this->lng->txt('svy_import_codes_info'), - $this->lng->txt("export_all_survey_codes"))); - $export_file->setSuffixes(array("csv")); - $export_file->setRequired(true); - $form_import_file->addItem($export_file); - - $form_import_file->addCommandButton("importAccessCodesAction", $this->lng->txt("import")); - $form_import_file->addCommandButton("codes", $this->lng->txt("cancel")); - - $this->tpl->setContent($form_import_file->getHTML()); - } - - /** - * Import codes from export codes file - */ - protected function importAccessCodesActionObject() - { - if(trim($_FILES['codes']['tmp_name'])) - { - $existing = array(); - foreach($this->object->getSurveyCodesTableData() as $item) - { - $existing[$item["code"]] = $item["id"]; - } - - include_once "./Services/Utilities/classes/class.ilCSVReader.php"; - $reader = new ilCSVReader(); - $reader->open($_FILES['codes']['tmp_name']); - foreach($reader->getDataArrayFromCSVFile() as $row) - { - // numeric check of used column due to #26176 - if(sizeof($row) == 8 && is_numeric($row[5])) - { - // used/sent/url are not relevant when importing - list($code, $email, $last_name, $first_name, $created, $used, $sent, $url) = $row; - - // unique code? - if(!array_key_exists($code, $existing)) - { - // could be date or datetime - if(strlen($created) == 10) - { - $created = new ilDate($created, IL_CAL_DATE); - } - else - { - $created = new ilDateTime($created, IL_CAL_DATETIME); - } - $created = $created->get(IL_CAL_UNIX); - - $user_data = array( - "email" => $email - ,"lastname" => $last_name - ,"firstname" => $first_name - ); - $this->object->importSurveyCode($code, $created, $user_data); - } - } - } - - ilUtil::sendSuccess($this->lng->txt('codes_created'), true); - } - - $this->ctrl->redirect($this, 'codes'); - } - - /** - * Create access codes for the survey - */ - public function createSurveyCodesObject() - { - if (is_numeric($_POST["nrOfCodes"])) - { - $ids = $this->object->createSurveyCodes($_POST["nrOfCodes"]); - ilUtil::sendSuccess($this->lng->txt('codes_created'), true); - $this->ctrl->setParameter($this, "new_ids", implode(";", $ids)); - $this->ctrl->redirect($this, 'editCodes'); - } - else - { - ilUtil::sendFailure($this->lng->txt("enter_valid_number_of_codes"), true); - $this->ctrl->redirect($this, 'codes'); - } - } - - public function insertSavedMessageObject() - { - $this->handleWriteAccess(); - $this->setCodesSubtabs(); - - include_once("./Modules/Survey/classes/forms/FormMailCodesGUI.php"); - $form_gui = new FormMailCodesGUI($this); - $form_gui->setValuesByPost(); - try - { - if ($form_gui->getSavedMessages()->getValue() > 0) - { - $ilUser = $this->user; - $settings = $this->object->getUserSettings($ilUser->getId(), 'savemessage'); - $form_gui->getMailMessage()->setValue($settings[$form_gui->getSavedMessages()->getValue()]['value']); - ilUtil::sendSuccess($this->lng->txt('msg_message_inserted')); - } - else - { - ilUtil::sendFailure($this->lng->txt('msg_no_message_inserted')); - } - } - catch (Exception $e) - { - $ilLog = $this->log; - $ilLog->write('Error: ' + $e->getMessage()); - } - $this->tpl->setVariable("ADM_CONTENT", $form_gui->getHTML()); - } - - public function deleteSavedMessageObject() - { - $this->handleWriteAccess(); - $this->setCodesSubtabs(); - - include_once("./Modules/Survey/classes/forms/FormMailCodesGUI.php"); - $form_gui = new FormMailCodesGUI($this); - $form_gui->setValuesByPost(); - try - { - if ($form_gui->getSavedMessages()->getValue() > 0) - { - $this->object->deleteUserSettings($form_gui->getSavedMessages()->getValue()); - $form_gui = new FormMailCodesGUI($this); - $form_gui->setValuesByPost(); - ilUtil::sendSuccess($this->lng->txt('msg_message_deleted')); - } - else - { - ilUtil::sendFailure($this->lng->txt('msg_no_message_deleted')); - } - } - catch (Exception $e) - { - $ilLog = $this->log; - $ilLog->write('Error: ' + $e->getMessage()); - } - $this->tpl->setVariable("ADM_CONTENT", $form_gui->getHTML()); - } - - public function mailCodesObject() - { - $this->handleWriteAccess(); - $this->setCodesSubtabs(); - - $mailData['m_subject'] = (array_key_exists('m_subject', $_POST)) ? $_POST['m_subject'] : sprintf($this->lng->txt('default_codes_mail_subject'), $this->object->getTitle()); - $mailData['m_message'] = (array_key_exists('m_message', $_POST)) ? $_POST['m_message'] : $this->lng->txt('default_codes_mail_message'); - $mailData['m_notsent'] = (array_key_exists('m_notsent', $_POST)) ? $_POST['m_notsent'] : '1'; - - include_once("./Modules/Survey/classes/forms/FormMailCodesGUI.php"); - $form_gui = new FormMailCodesGUI($this); - $form_gui->setValuesByArray($mailData); - $this->tpl->setVariable("ADM_CONTENT", $form_gui->getHTML()); - } - - public function sendCodesMailObject() - { - $ilUser = $this->user; - - $this->handleWriteAccess(); - $this->setCodesSubtabs(); - - include_once("./Modules/Survey/classes/forms/FormMailCodesGUI.php"); - $form_gui = new FormMailCodesGUI($this); - if ($form_gui->checkInput()) - { - $url_exists = strpos($_POST['m_message'], '[url]') !== FALSE; - if (!$url_exists) - { - ilUtil::sendFailure($this->lng->txt('please_enter_mail_url')); - $form_gui->setValuesByPost(); - } - else - { - if ($_POST['savemessage'] == 1) - { - $ilUser = $this->user; - $title = (strlen($_POST['savemessagetitle'])) ? $_POST['savemessagetitle'] : ilStr::substr($_POST['m_message'], 0, 40) . '...'; - $this->object->saveUserSettings($ilUser->getId(), 'savemessage', $title, $_POST['m_message']); - } - - $lang = $ilUser->getPref("survey_code_language"); - if(!$lang) - { - $lang = $this->lng->getDefaultLanguage(); - } - $this->object->sendCodes($_POST['m_notsent'], $_POST['m_subject'], nl2br($_POST['m_message']),$lang); - ilUtil::sendSuccess($this->lng->txt('mail_sent'), true); - $this->ctrl->redirect($this, 'mailCodes'); - } - } - else - { - $form_gui->setValuesByPost(); - } - $this->tpl->setVariable("ADM_CONTENT", $form_gui->getHTML()); - } - - public function importExternalRecipientsFromTextObject() - { - if (trim($_POST['externaltext'])) - { - $data = preg_split("/[\n\r]/", $_POST['externaltext']); - $fields = preg_split("/;/", array_shift($data)); - if (!in_array('email', $fields)) - { - $_SESSION['externaltext'] = $_POST['externaltext']; - ilUtil::sendFailure($this->lng->txt('err_external_rcp_no_email_column'), true); - $this->ctrl->redirect($this, 'importExternalMailRecipientsFromTextForm'); - } - $existingdata = $this->object->getExternalCodeRecipients(); - $existingcolumns = array(); - if (count($existingdata)) - { - $first = array_shift($existingdata); - foreach ($first as $key => $value) - { - array_push($existingcolumns, $key); - } - } - $founddata = array(); - foreach ($data as $datarow) - { - $row = preg_split("/;/", $datarow); - if (count($row) == count($fields)) - { - $dataset = array(); - foreach ($fields as $idx => $fieldname) - { - if (count($existingcolumns)) - { - if (array_key_exists($idx, $existingcolumns)) - { - $dataset[$fieldname] = $row[$idx]; - } - } - else - { - $dataset[$fieldname] = $row[$idx]; - } - } - if (strlen($dataset['email'])) - { - array_push($founddata, $dataset); - } - } - } - $this->object->createSurveyCodesForExternalData($founddata); - ilUtil::sendSuccess($this->lng->txt('external_recipients_imported'), true); - $this->ctrl->redirect($this, 'codes'); - } - - $this->ctrl->redirect($this, 'importExternalMailRecipientsFromTextForm'); - } - - // see ilBookmarkImportExport - protected function _convertCharset($a_string, $a_from_charset="", $a_to_charset="UTF-8") - { - if(extension_loaded("mbstring")) - { - if(!$a_from_charset) - { - mb_detect_order("UTF-8, ISO-8859-1, Windows-1252, ASCII"); - $a_from_charset = mb_detect_encoding($a_string); - } - if(strtoupper($a_from_charset) != $a_to_charset) - { - return @mb_convert_encoding($a_string, $a_to_charset, $a_from_charset); - } - } - return $a_string; - } - - protected function removeUTF8Bom($a_text) - { - $bom = pack('H*','EFBBBF'); - return preg_replace('/^'.$bom.'/', '', $a_text); - } - - public function importExternalRecipientsFromFileObject() - { - if (trim($_FILES['externalmails']['tmp_name'])) - { - include_once "./Services/Utilities/classes/class.ilCSVReader.php"; - $reader = new ilCSVReader(); - $reader->open($_FILES['externalmails']['tmp_name']); - $data = $reader->getDataArrayFromCSVFile(); - $fields = array_shift($data); - foreach($fields as $idx => $field) - { - $fields[$idx] = $this->removeUTF8Bom($field); - } - if (!in_array('email', $fields)) - { - $reader->close(); - ilUtil::sendFailure($this->lng->txt('err_external_rcp_no_email'), true); - $this->ctrl->redirect($this, 'codes'); - } - $existingdata = $this->object->getExternalCodeRecipients(); - $existingcolumns = array(); - if (count($existingdata)) - { - $first = array_shift($existingdata); - foreach ($first as $key => $value) - { - array_push($existingcolumns, $key); - } - } - - include_once "Services/Utilities/classes/class.ilStr.php"; - - $founddata = array(); - foreach ($data as $row) - { - if (count($row) == count($fields)) - { - $dataset = array(); - foreach ($fields as $idx => $fieldname) - { - // #14811 - $row[$idx] = $this->_convertCharset($row[$idx]); - - if (count($existingcolumns)) - { - if (array_key_exists($idx, $existingcolumns)) - { - $dataset[$fieldname] = $row[$idx]; - } - } - else - { - $dataset[$fieldname] = $row[$idx]; - } - } - if (strlen($dataset['email'])) - { - array_push($founddata, $dataset); - } - } - } - $reader->close(); - - if(sizeof($founddata)) - { - $this->object->createSurveyCodesForExternalData($founddata); - ilUtil::sendSuccess($this->lng->txt('external_recipients_imported'), true); - } - } - - $this->ctrl->redirect($this, 'codes'); - } - - function importExternalMailRecipientsFromFileFormObject() - { - $ilAccess = $this->access; - - $this->handleWriteAccess(); - $this->setCodesSubtabs(); - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form_import_file = new ilPropertyFormGUI(); - $form_import_file->setFormAction($this->ctrl->getFormAction($this)); - $form_import_file->setTableWidth("100%"); - $form_import_file->setId("codes_import_file"); - - $headerfile = new ilFormSectionHeaderGUI(); - $headerfile->setTitle($this->lng->txt("import_from_file")); - $form_import_file->addItem($headerfile); - - $externalmails = new ilFileInputGUI($this->lng->txt("externalmails"), "externalmails"); - $externalmails->setInfo($this->lng->txt('externalmails_info')); - $externalmails->setRequired(true); - $form_import_file->addItem($externalmails); - if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) $form_import_file->addCommandButton("importExternalRecipientsFromFile", $this->lng->txt("import")); - if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) $form_import_file->addCommandButton("codes", $this->lng->txt("cancel")); - - $this->tpl->setContent($form_import_file->getHTML()); - } - - function importExternalMailRecipientsFromTextFormObject() - { - $ilAccess = $this->access; - - $this->handleWriteAccess(); - $this->setCodesSubtabs(); - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form_import_text = new ilPropertyFormGUI(); - $form_import_text->setFormAction($this->ctrl->getFormAction($this)); - $form_import_text->setTableWidth("100%"); - $form_import_text->setId("codes_import_text"); - - $headertext = new ilFormSectionHeaderGUI(); - $headertext->setTitle($this->lng->txt("import_from_text")); - $form_import_text->addItem($headertext); - - $inp = new ilTextAreaInputGUI($this->lng->txt('externaltext'), 'externaltext'); - if (array_key_exists('externaltext', $_SESSION) && strlen($_SESSION['externaltext'])) - { - $inp->setValue($_SESSION['externaltext']); - } - else - { - // $this->lng->txt('mail_import_example1') #14897 - $inp->setValue("email;firstname;lastname\n" . $this->lng->txt('mail_import_example2') . "\n" . $this->lng->txt('mail_import_example3') . "\n"); - } - $inp->setRequired(true); - $inp->setCols(80); - $inp->setRows(10); - $inp->setInfo($this->lng->txt('externaltext_info')); - $form_import_text->addItem($inp); - unset($_SESSION['externaltext']); - - if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) $form_import_text->addCommandButton("importExternalRecipientsFromText", $this->lng->txt("import")); - if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) $form_import_text->addCommandButton("codes", $this->lng->txt("cancel")); - - $this->tpl->setContent($form_import_text->getHTML()); - } - - - - - - - - - - - // - // 360° - // - - - - - public function listAppraiseesObject() - { - $ilToolbar = $this->toolbar; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->handleWriteAccess(); - - $this->ctrl->setParameter($this, "appr360", 1); - - include_once './Services/Search/classes/class.ilRepositorySearchGUI.php'; - ilRepositorySearchGUI::fillAutoCompleteToolbar( - $this, - $ilToolbar, - array( - 'auto_complete_name' => $this->lng->txt('user'), - 'submit_name' => $this->lng->txt('add'), - 'add_search' => true, - 'add_from_container' => $this->ref_id - ) - ); - - // competence calculations - include_once("./Services/Skill/classes/class.ilSkillManagementSettings.php"); - $skmg_set = new ilSkillManagementSettings(); - if ($this->object->getSkillService() && $skmg_set->isActivated()) - { - $ilToolbar->addSeparator(); - $ilToolbar->addButton($lng->txt("survey_calc_skills"), - $ilCtrl->getLinkTargetByClass("ilsurveyskilldeterminationgui"), ""); - } - - $ilToolbar->addSeparator(); - $ilToolbar->addButton($this->lng->txt('svy_delete_all_user_data'), - $this->ctrl->getLinkTarget($this, 'deleteAllUserData')); - - $this->ctrl->setParameter($this, "appr360", ""); - - include_once "Modules/Survey/classes/tables/class.ilSurveyAppraiseesTableGUI.php"; - $tbl = new ilSurveyAppraiseesTableGUI($this, "listAppraisees"); - $tbl->setData($this->object->getAppraiseesData()); - $this->tpl->setContent($tbl->getHTML()); - } - - public function addAppraisee($a_user_ids) - { - if(sizeof($a_user_ids)) - { - // #13319 - foreach(array_unique($a_user_ids) as $user_id) - { - $this->object->addAppraisee($user_id); - } - - ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); - } - $this->ctrl->redirect($this, "listAppraisees"); - } - - public function confirmDeleteAppraiseesObject() - { - $ilTabs = $this->tabs; - - if(!sizeof($_POST["appr_id"])) - { - ilUtil::sendFailure($this->lng->txt("select_one"), true); - $this->ctrl->redirect($this, "listAppraisees"); - } - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($this->lng->txt("btn_back"), - $this->ctrl->getLinkTarget($this, "listAppraisees")); - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setHeaderText($this->lng->txt("survey_360_sure_delete_appraises")); - - $cgui->setFormAction($this->ctrl->getFormAction($this, "deleteAppraisees")); - $cgui->setCancel($this->lng->txt("cancel"), "listAppraisees"); - $cgui->setConfirm($this->lng->txt("confirm"), "deleteAppraisees"); - - $data = $this->object->getAppraiseesData(); - - $count = 0; - include_once "Services/User/classes/class.ilUserUtil.php"; - foreach ($_POST["appr_id"] as $id) - { - if(isset($data[$id]) && !$data[$id]["closed"]) - { - $cgui->addItem("appr_id[]", $id, ilUserUtil::getNamePresentation($id)); - $count++; - } - } - - if(!$count) - { - ilUtil::sendFailure($this->lng->txt("select_one"), true); - $this->ctrl->redirect($this, "listAppraisees"); - } - - $this->tpl->setContent($cgui->getHTML()); - } - - public function deleteAppraiseesObject() - { - if(sizeof($_POST["appr_id"])) - { - $data = $this->object->getAppraiseesData(); - - foreach ($_POST["appr_id"] as $id) - { - // #11285 - if(isset($data[$id]) && !$data[$id]["closed"]) - { - $this->object->deleteAppraisee($id); - } - } - - ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); - } - - $this->ctrl->redirect($this, "listAppraisees"); - } - - function handleRatersAccess() - { - $ilAccess = $this->access; - $ilUser = $this->user; - - if ($ilAccess->checkAccess("write", "", $this->ref_id)) - { - $appr_id = $_REQUEST["appr_id"]; - if(!$appr_id) - { - $this->ctrl->redirect($this, "listAppraisees"); - } - return $appr_id; - } - else if($this->object->get360Mode() && - $this->object->get360SelfRaters() && - $this->object->isAppraisee($ilUser->getId()) && - !$this->object->isAppraiseeClosed($ilUser->getId())) - { - return $ilUser->getId(); - } - $this->ctrl->redirect($this->parent_gui, "infoScreen"); - } - - public function editRatersObject() - { - $ilTabs = $this->tabs; - $ilToolbar = $this->toolbar; - $ilAccess = $this->access; - - $appr_id = $_REQUEST["appr_id"] = $this->handleRatersAccess(); - - $has_write = $ilAccess->checkAccess("write", "", $this->ref_id); - if($has_write) - { - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($this->lng->txt("btn_back"), - $this->ctrl->getLinkTarget($this, "listAppraisees")); - } - - $this->ctrl->setParameter($this, "appr_id", $appr_id); - $this->ctrl->setParameter($this, "rate360", 1); - - include_once './Services/Search/classes/class.ilRepositorySearchGUI.php'; - ilRepositorySearchGUI::fillAutoCompleteToolbar( - $this, - $ilToolbar, - array( - 'auto_complete_name' => $this->lng->txt('user'), - 'submit_name' => $this->lng->txt('add'), - 'add_search' => true, - 'add_from_container' => $this->ref_id - ) - ); - - $this->ctrl->setParameter($this, "rate360", ""); - - $ilToolbar->addSeparator(); - - $ilToolbar->addButton($this->lng->txt("survey_360_add_external_rater"), - $this->ctrl->getLinkTarget($this, "addExternalRaterForm")); - - // #13320 - require_once "Services/Link/classes/class.ilLink.php"; - $url = ilLink::_getStaticLink($this->object->getRefId()); - - include_once "Modules/Survey/classes/tables/class.ilSurveyAppraiseesTableGUI.php"; - $tbl = new ilSurveyAppraiseesTableGUI($this, "editRaters", true, !$this->object->isAppraiseeClosed($appr_id), $url); // #11285 - $tbl->setData($this->object->getRatersData($appr_id)); - $this->tpl->setContent($tbl->getHTML()); - } - - public function addExternalRaterFormObject(ilPropertyFormGUI $a_form = null) - { - $ilTabs = $this->tabs; - $ilAccess = $this->access; - - $appr_id = $this->handleRatersAccess(); - $this->ctrl->setParameter($this, "appr_id", $appr_id); - - $has_write = $ilAccess->checkAccess("write", "", $this->ref_id); - if($has_write) - { - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($this->lng->txt("btn_back"), - $this->ctrl->getLinkTarget($this, "editRaters")); - } - - if(!$a_form) - { - $a_form = $this->initExternalRaterForm($appr_id); - } - - $this->tpl->setContent($a_form->getHTML()); - } - - protected function initExternalRaterForm($appr_id) - { - include_once "Services/User/classes/class.ilUserUtil.php"; - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this, "addExternalRater")); - $form->setTitle($this->lng->txt("survey_360_add_external_rater"). - ": ".ilUserUtil::getNamePresentation($appr_id)); - - $email = new ilEmailInputGUI($this->lng->txt("email"), "email"); - $email->setRequired(true); - $form->addItem($email); - - $lname = new ilTextInputGUI($this->lng->txt("lastname"), "lname"); - $lname->setSize(30); - $form->addItem($lname); - - $fname = new ilTextInputGUI($this->lng->txt("firstname"), "fname"); - $fname->setSize(30); - $form->addItem($fname); - - $form->addCommandButton("addExternalRater", $this->lng->txt("save")); - $form->addCommandButton("editRaters", $this->lng->txt("cancel")); - - return $form; - } - - public function addExternalRaterObject() - { - $appr_id = $_REQUEST["appr_id"]; - if(!$appr_id) - { - $this->ctrl->redirect($this, "listAppraisees"); - } - - $this->ctrl->setParameter($this, "appr_id", $appr_id); - - $form = $this->initExternalRaterForm($appr_id); - if($form->checkInput()) - { - $data = array( - "email" => $form->getInput("email"), - "lastname" => $form->getInput("lname"), - "firstname" => $form->getInput("fname") - ); - $anonymous_id = $this->object->createSurveyCodesForExternalData(array($data)); - $anonymous_id = array_pop($anonymous_id); - - $this->object->addRater($appr_id, 0, $anonymous_id); - - ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); - $this->ctrl->setParameter($this, "appr_id", $appr_id); - $this->ctrl->redirect($this, "editRaters"); - } - - $form->setValuesByPost(); - $this->addExternalRaterFormObject($form); - } - - public function addRater($a_user_ids) - { - $ilAccess = $this->access; - $ilUser = $this->user; - - $appr_id = $this->handleRatersAccess(); - - if(sizeof($a_user_ids)) - { - // #13319 - foreach(array_unique($a_user_ids) as $user_id) - { - if($ilAccess->checkAccess("write", "", $this->ref_id) || - $this->object->get360SelfEvaluation() || - $user_id != $ilUser->getId()) - { - if ($appr_id != $user_id) - { - $this->object->addRater($appr_id, $user_id); - ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); - } - else - { - ilUtil::sendFailure($this->lng->txt("svy_appraisses_cannot_be_raters"), true); - } - } - } - } - - $this->ctrl->setParameter($this, "appr_id", $appr_id); - $this->ctrl->redirect($this, "editRaters"); - } - - public function confirmDeleteRatersObject() - { - $ilTabs = $this->tabs; - - $appr_id = $this->handleRatersAccess(); - $this->ctrl->setParameter($this, "appr_id", $appr_id); - if(!sizeof($_POST["rtr_id"])) - { - ilUtil::sendFailure($this->lng->txt("select_one"), true); - $this->ctrl->redirect($this, "editRaters"); - } - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($this->lng->txt("btn_back"), - $this->ctrl->getLinkTarget($this, "editRaters")); - - include_once "Services/User/classes/class.ilUserUtil.php"; - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setHeaderText(sprintf($this->lng->txt("survey_360_sure_delete_raters"), - ilUserUtil::getNamePresentation($appr_id))); - - $cgui->setFormAction($this->ctrl->getFormAction($this, "deleteRaters")); - $cgui->setCancel($this->lng->txt("cancel"), "editRaters"); - $cgui->setConfirm($this->lng->txt("confirm"), "deleteRaters"); - - $data = $this->object->getRatersData($appr_id); - - foreach ($_POST["rtr_id"] as $id) - { - if(isset($data[$id])) - { - $cgui->addItem("rtr_id[]", $id, $data[$id]["lastname"].", ". - $data[$id]["firstname"]." (".$data[$id]["email"].")"); - } - } - - $this->tpl->setContent($cgui->getHTML()); - } - - public function deleteRatersObject() - { - $appr_id = $this->handleRatersAccess(); - $this->ctrl->setParameter($this, "appr_id", $appr_id); - - if(sizeof($_POST["rtr_id"])) - { - $data = $this->object->getRatersData($appr_id); - - foreach ($_POST["rtr_id"] as $id) - { - if(isset($data[$id])) - { - if(substr($id, 0, 1) == "u") - { - $this->object->deleteRater($appr_id, substr($id, 1)); - } - else - { - $this->object->deleteRater($appr_id, 0, substr($id, 1)); - } - } - } - - ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); - } - - $this->ctrl->redirect($this, "editRaters"); - } - - function addSelfAppraiseeObject() - { - $ilUser = $this->user; - - if($this->object->get360SelfAppraisee() && - !$this->object->isAppraisee($ilUser->getId())) - { - $this->object->addAppraisee($ilUser->getId()); - } - - $this->ctrl->redirect($this->parent_gui, "infoScreen"); - } - - function initMailRatersForm($appr_id, array $rec_ids) - { - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this, "mailRatersAction")); - $form->setTitle($this->lng->txt('compose')); - - $all_data = $this->object->getRatersData($appr_id); - $rec_data = array(); - foreach($rec_ids as $rec_id) - { - if(isset($all_data[$rec_id])) - { - $rec_data[] = $all_data[$rec_id]["lastname"].", ". - $all_data[$rec_id]["firstname"]. - " (".$all_data[$rec_id]["email"].")"; - } - } - sort($rec_data); - $rec = new ilCustomInputGUI($this->lng->txt('recipients')); - $rec->setHTML(implode("
", $rec_data)); - $form->addItem($rec); - - $subject = new ilTextInputGUI($this->lng->txt('subject'), 'subject'); - $subject->setSize(50); - $subject->setRequired(true); - $form->addItem($subject); - - $existingdata = $this->object->getExternalCodeRecipients(); - $existingcolumns = array(); - if (count($existingdata)) - { - $first = array_shift($existingdata); - foreach ($first as $key => $value) - { - if (strcmp($key, 'code') != 0 && strcmp($key, 'email') != 0 && strcmp($key, 'sent') != 0) array_push($existingcolumns, '[' . $key . ']'); - } - } - - $mailmessage_u = new ilTextAreaInputGUI($this->lng->txt('survey_360_rater_message_content_registered'), 'message_u'); - $mailmessage_u->setRequired(true); - $mailmessage_u->setCols(80); - $mailmessage_u->setRows(10); - $form->addItem($mailmessage_u); - - $mailmessage_a = new ilTextAreaInputGUI($this->lng->txt('survey_360_rater_message_content_anonymous'), 'message_a'); - $mailmessage_a->setRequired(true); - $mailmessage_a->setCols(80); - $mailmessage_a->setRows(10); - $mailmessage_a->setInfo(sprintf($this->lng->txt('message_content_info'), join($existingcolumns, ', '))); - $form->addItem($mailmessage_a); - - $recf = new ilHiddenInputGUI("rtr_id"); - $recf->setValue(implode(";", $rec_ids)); - $form->addItem($recf); - - $form->addCommandButton("mailRatersAction", $this->lng->txt("send")); - $form->addCommandButton("editRaters", $this->lng->txt("cancel")); - - $subject->setValue(sprintf($this->lng->txt('survey_360_rater_subject_default'), $this->object->getTitle())); - $mailmessage_u->setValue($this->lng->txt('survey_360_rater_message_content_registered_default')); - $mailmessage_a->setValue($this->lng->txt('survey_360_rater_message_content_anonymous_default')); - - return $form; - } - - function mailRatersObject(ilPropertyFormGUI $a_form = null) - { - $ilTabs = $this->tabs; - - if(!$a_form) - { - $appr_id = $this->handleRatersAccess(); - $this->ctrl->setParameter($this, "appr_id", $appr_id); - - if(!sizeof($_POST["rtr_id"])) - { - ilUtil::sendFailure($this->lng->txt("select_one"), true); - $this->ctrl->redirect($this, "editRaters"); - } - - $a_form = $this->initMailRatersForm($appr_id, $_POST["rtr_id"]); - } - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($this->lng->txt("btn_back"), - $this->ctrl->getLinkTarget($this, "editRaters")); - - $this->tpl->setContent($a_form->getHTML()); - } - - function mailRatersActionObject() - { - $ilUser = $this->user; - - $appr_id = $this->handleRatersAccess(); - $this->ctrl->setParameter($this, "appr_id", $appr_id); - - $rec_ids = explode(";", $_POST["rtr_id"]); - if(!sizeof($rec_ids)) - { - $this->ctrl->redirect($this, "editRaters"); - } - - $form = $this->initMailRatersForm($appr_id, $rec_ids); - if($form->checkInput()) - { - $txt_u = $form->getInput("message_u"); - $txt_a = $form->getInput("message_a"); - $subj = $form->getInput("subject"); - - // #12743 - $sender_id = (trim($ilUser->getEmail())) - ? $ilUser->getId() - : ANONYMOUS_USER_ID; - - include_once "./Services/Mail/classes/class.ilMail.php"; - - $all_data = $this->object->getRatersData($appr_id); - foreach($rec_ids as $rec_id) - { - if(isset($all_data[$rec_id])) - { - - $user = $all_data[$rec_id]; - - // anonymous - if(substr($rec_id, 0, 1) == "a") - { - $mytxt = $txt_a; - $url = $user["href"]; - $rcp = $user["email"]; - } - // reg - else - { - $mytxt = $txt_u; - $user["code"] = $this->lng->txt("survey_code_mail_on_demand"); - $url = ilLink::_getStaticLink($this->object->getRefId()); - $rcp = $user["login"]; // #15141 - } - - $mytxt = str_replace("[lastname]", $user["lastname"], $mytxt); - $mytxt = str_replace("[firstname]", $user["firstname"], $mytxt); - $mytxt = str_replace("[url]", $url, $mytxt); - $mytxt = str_replace("[code]", $user["code"], $mytxt); - - $mail = new ilMail($sender_id); - $mail->sendMail( - $rcp, // to - "", // cc - "", // bcc - $subj, // subject - $mytxt, // message - array(), // attachments - array('normal') // type - ); - - $this->object->set360RaterSent($appr_id, - (substr($rec_id, 0, 1) == "a") ? 0 : (int)substr($rec_id, 1), - (substr($rec_id, 0, 1) == "u") ? 0 : (int)substr($rec_id, 1)); - } - } - - ilUtil::sendSuccess($this->lng->txt("mail_sent"), true); - $this->ctrl->redirect($this, "editRaters"); - } - - $form->setValuesByPost(); - $this->mailRatersObject($form); - } - - function confirmAppraiseeCloseObject() - { - $ilUser = $this->user; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($this->lng->txt("menuback"), - $this->ctrl->getLinkTarget($this->parent_gui, "infoScreen")); - - if(!$this->object->isAppraisee($ilUser->getId())) - { - $this->ctrl->redirect($this->parent_gui, "infoScreen"); - } - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setHeaderText($this->lng->txt("survey_360_sure_appraisee_close")); - - $cgui->setFormAction($this->ctrl->getFormAction($this, "appraiseeClose")); - $cgui->setCancel($this->lng->txt("cancel"), "confirmAppraiseeCloseCancel"); - $cgui->setConfirm($this->lng->txt("confirm"), "appraiseeClose"); - - $tpl->setContent($cgui->getHTML()); - } - - function confirmAppraiseeCloseCancelObject() - { - $this->ctrl->redirect($this->parent_gui, "infoScreen"); - } - - function appraiseeCloseObject() - { - $ilUser = $this->user; - - if(!$this->object->isAppraisee($ilUser->getId())) - { - $this->ctrl->redirect($this->parent_gui, "infoScreen"); - } - - $this->object->closeAppraisee($ilUser->getId()); - ilUtil::sendSuccess($this->lng->txt("survey_360_appraisee_close_action_success"), true); - $this->ctrl->redirect($this->parent_gui, "infoScreen"); - } - - function confirmAdminAppraiseesCloseObject() - { - $tpl = $this->tpl; - - $this->handleWriteAccess(); - - $appr_ids = $_POST["appr_id"]; - - if(!sizeof($appr_ids)) - { - ilUtil::sendFailure($this->lng->txt("select_one"), true); - $this->ctrl->redirect($this, "listAppraisees"); - } - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setHeaderText($this->lng->txt("survey_360_sure_appraisee_close_admin")); - - $cgui->setFormAction($this->ctrl->getFormAction($this, "adminAppraiseesClose")); - $cgui->setCancel($this->lng->txt("cancel"), "listAppraisees"); - $cgui->setConfirm($this->lng->txt("confirm"), "adminAppraiseesClose"); - - include_once "Services/User/classes/class.ilUserUtil.php"; - foreach($appr_ids as $appr_id) - { - $cgui->addItem("appr_id[]", $appr_id, ilUserUtil::getNamePresentation($appr_id)); - } - - $tpl->setContent($cgui->getHTML()); - } - - function adminAppraiseesCloseObject() - { - $this->handleWriteAccess(); - - $appr_ids = $_POST["appr_id"]; - - if(!sizeof($appr_ids)) - { - ilUtil::sendFailure($this->lng->txt("select_one"), true); - $this->ctrl->redirect($this, "listAppraisees"); - } - - $appr_data = $this->object->getAppraiseesData(); - foreach($appr_ids as $appr_id) - { - if(isset($appr_data[$appr_id]) && !$appr_data[$appr_id]["closed"]) - { - $this->object->closeAppraisee($appr_id); - } - } - - ilUtil::sendSuccess($this->lng->txt("survey_360_appraisee_close_action_success_admin"), true); - $this->ctrl->redirect($this, "listAppraisees"); - } - - protected function listParticipantsObject() - { - $ilToolbar = $this->toolbar; - - if(!$this->isAnonymousListActive()) - { - $this->ctrl->redirect($this, "maintenance"); - } - - $this->handleWriteAccess(); - $this->setCodesSubtabs(); - - include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; - $button = ilLinkButton::getInstance(); - $button->setCaption("print"); - $button->setOnClick("window.print(); return false;"); - $button->setOmitPreventDoubleSubmission(true); - $ilToolbar->addButtonInstance($button); - - include_once "Modules/Survey/classes/tables/class.ilSurveyParticipantsTableGUI.php"; - $tbl = new ilSurveyParticipantsTableGUI($this, "listParticipants", $this->object); - $this->tpl->setContent($tbl->getHTML()); - } - - public function getObject() - { - return $this->object; - } -} - -?> + +* @version $Id: class.ilObjSurveyGUI.php 43670 2013-07-26 08:41:31Z jluetzen $ +* +* @ilCtrl_Calls ilSurveyParticipantsGUI: ilRepositorySearchGUI +* +* @ingroup ModulesSurvey +*/ +class ilSurveyParticipantsGUI +{ + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var Logger + */ + protected $log; + + protected $parent_gui; // [ilObjSurveyGUI] + protected $object; // [ilObjSurvey] + protected $ref_id; // [int] + protected $has_write; // [bool] + + public function __construct(ilObjSurveyGUI $a_parent_gui, $a_has_write_access) + { + global $DIC; + + $this->tabs = $DIC->tabs(); + $this->toolbar = $DIC->toolbar(); + $this->access = $DIC->access(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->user = $DIC->user(); + $this->log = $DIC["ilLog"]; + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $tpl = $DIC["tpl"]; + + $this->parent_gui = $a_parent_gui; + $this->object = $this->parent_gui->object; + $this->ref_id = $this->object->getRefId(); + $this->has_write = (bool) $a_has_write_access; + + $this->ctrl = $ilCtrl; + $this->lng = $lng; + $this->tpl = $tpl; + } + + protected function handleWriteAccess() + { + if (!$this->has_write) { + include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; + throw new ilSurveyException("Permission denied"); + } + } + + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + $cmd = $ilCtrl->getCmd("maintenance"); + $next_class = $this->ctrl->getNextClass($this); + + switch ($next_class) { + case 'ilrepositorysearchgui': + include_once('./Services/Search/classes/class.ilRepositorySearchGUI.php'); + $rep_search = new ilRepositorySearchGUI(); + + if (!$_REQUEST["appr360"] && !$_REQUEST["rate360"]) { + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $this->lng->txt("btn_back"), + $this->ctrl->getLinkTarget($this, "invite") + ); + + $rep_search->setCallback( + $this, + 'inviteUserGroupObject', + array( + ) + ); + + // Set tabs + $this->ctrl->setReturn($this, 'invite'); + $this->ctrl->forwardCommand($rep_search); + $ilTabs->setTabActive('invitation'); + } elseif ($_REQUEST["rate360"]) { + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $this->lng->txt("btn_back"), + $this->ctrl->getLinkTarget($this, "listAppraisees") + ); + + $this->ctrl->setParameter($this, "rate360", 1); + $this->ctrl->saveParameter($this, "appr_id"); + + $rep_search->setCallback( + $this, + 'addRater', + array( + ) + ); + + // Set tabs + $this->ctrl->setReturn($this, 'editRaters'); + $this->ctrl->forwardCommand($rep_search); + } else { + $ilTabs->activateTab("survey_360_appraisees"); + $this->ctrl->setParameter($this, "appr360", 1); + + $rep_search->setCallback( + $this, + 'addAppraisee', + array( + ) + ); + + // Set tabs + $this->ctrl->setReturn($this, 'listAppraisees'); + $this->ctrl->forwardCommand($rep_search); + } + break; + + default: + $cmd .= "Object"; + $this->$cmd(); + break; + } + } + + protected function filterSurveyParticipantsByAccess($a_finished_ids = null) + { + $all_participants = $this->object->getSurveyParticipants($a_finished_ids); + $participant_ids = []; + foreach ($all_participants as $participant) { + $participant_ids[] = $participant['usr_id']; + } + + + $filtered_participant_ids = $this->access->filterUserIdsByRbacOrPositionOfCurrentUser( + 'read_results', + 'access_results', + $this->object->getRefId(), + $participant_ids + ); + $participants = []; + foreach ($all_participants as $username => $user_data) { + if (!$user_data['usr_id']) { + $participants[$username] = $user_data; + } + if (in_array($user_data['usr_id'], $filtered_participant_ids)) { + $participants[$username] = $user_data; + } + } + return $participants; + } + + + /** + * Participants maintenance + */ + public function maintenanceObject() + { + $ilToolbar = $this->toolbar; + + if ($this->object->get360Mode()) { + return $this->listAppraiseesObject(); + } + + //Btn Determine Competence Levels + if ($this->object->getMode() == ilObjSurvey::MODE_SELF_EVAL) { + include_once("./Services/Skill/classes/class.ilSkillManagementSettings.php"); + $skmg_set = new ilSkillManagementSettings(); + if ($this->object->getSkillService() && $skmg_set->isActivated()) { + $ilToolbar->addButton( + $this->lng->txt("survey_calc_skills"), + $this->ctrl->getLinkTargetByClass("ilsurveyskilldeterminationgui"), + "" + ); + } + } + + $this->handleWriteAccess(); + $this->setCodesSubtabs(); + + $ilToolbar->addButton( + $this->lng->txt('svy_delete_all_user_data'), + $this->ctrl->getLinkTarget($this, 'deleteAllUserData') + ); + + include_once "./Modules/Survey/classes/tables/class.ilSurveyMaintenanceTableGUI.php"; + $table_gui = new ilSurveyMaintenanceTableGUI($this, 'maintenance'); + + //$total =& $this->object->getSurveyParticipants(); + $total = $this->filterSurveyParticipantsByAccess(); + $data = array(); + foreach ($total as $user_data) { + $finished = false; + if ((bool) $user_data["finished"]) { + $finished = $user_data["finished_tstamp"]; + } + $wt = $this->object->getWorkingtimeForParticipant($user_data["active_id"]); + $last_access = $this->object->getLastAccess($user_data["active_id"]); + array_push($data, array( + 'id' => $user_data["active_id"], + 'name' => $user_data["sortname"], + 'login' => $user_data["login"], + 'last_access' => $last_access, + 'workingtime' => $wt, + 'finished' => $finished + )); + } + $table_gui->setData($data); + $this->tpl->setVariable('ADM_CONTENT', $table_gui->getHTML()); + } + + protected function isAnonymousListActive() + { + $surveySetting = new ilSetting("survey"); + if ($surveySetting->get("anonymous_participants", false)) { + if ($this->object->hasAnonymizedResults() && + $this->object->hasAnonymousUserList()) { + $end = $this->object->getEndDate(); + if ($end && $end < date("YmdHis")) { + $min = $surveySetting->get("anonymous_participants_min", 0); + $total = $this->object->getSurveyParticipants(); + if (!$min || sizeof($total) >= $min) { + return true; + } + } + } + } + return false; + } + + /** + * Set the tabs for the access codes section + * + * @access private + */ + public function setCodesSubtabs() + { + $ilTabs = $this->tabs; + + // not used in 360° mode + + // maintenance + $ilTabs->addSubTabTarget( + "sub_tab_dashboard", + $this->ctrl->getLinkTarget($this, 'maintenance'), + array("maintenance", "deleteAllUserData"), + "" + ); + + if ($this->isAnonymousListActive()) { + $ilTabs->addSubTabTarget( + "svy_anonymous_participants_svy", + $this->ctrl->getLinkTarget($this, 'listParticipants'), + array("listParticipants"), + "" + ); + } + + if (!$this->object->isAccessibleWithoutCode()) { + $ilTabs->addSubTabTarget( + "codes", + $this->ctrl->getLinkTarget($this, 'codes'), + array("codes", "editCodes", "createSurveyCodes", "setCodeLanguage", "deleteCodes", "exportCodes", + "importExternalMailRecipientsFromFileForm", "importExternalMailRecipientsFromTextForm"), + "" + ); + } + + $hidden_tabs = array(); + $template = $this->object->getTemplate(); + if ($template) { + include_once "Services/Administration/classes/class.ilSettingsTemplate.php"; + $template = new ilSettingsTemplate($template); + $hidden_tabs = $template->getHiddenTabs(); + } + + // #12277 - invite + if (!in_array("invitation", $hidden_tabs)) { + if ($this->access->checkAccess('write', '', $this->object->getRefId())) { + $ilTabs->addSubTabTarget( + "invitation", + $this->ctrl->getLinkTarget($this, 'invite'), + array("invite", "saveInvitationStatus", + "inviteUserGroup", "disinviteUserGroup"), + "" + ); + } + } + + $data = $this->object->getExternalCodeRecipients(); + if (count($data)) { + $ilTabs->addSubTabTarget( + "mail_survey_codes", + $this->ctrl->getLinkTarget($this, "mailCodes"), + array("mailCodes", "sendCodesMail", "insertSavedMessage", "deleteSavedMessage"), + "" + ); + } + } + + /** + * Disinvite users or groups from a survey + */ + public function disinviteUserGroupObject() + { + // disinvite users + if (is_array($_POST["user_select"])) { + foreach ($_POST["user_select"] as $user_id) { + $this->object->disinviteUser($user_id); + } + } + ilUtil::sendSuccess($this->lng->txt('msg_users_disinvited'), true); + $this->ctrl->redirect($this, "invite"); + } + + /** + * Invite users or groups to a survey + */ + public function inviteUserGroupObject($a_user_ids = array()) + { + $invited = 0; + // add users to invitation + if (is_array($a_user_ids)) { + foreach ($a_user_ids as $user_id) { + $this->object->inviteUser($user_id); + $invited++; + } + } + if ($invited == 0) { + ilUtil::sendFailure($this->lng->txt('no_user_invited'), true); + return false; + } else { + ilUtil::sendSuccess(sprintf($this->lng->txt('users_invited'), $invited), true); + return false; + } + $this->ctrl->redirect($this, "invite"); + } + + /** + * Saves the status of the invitation tab + */ + public function saveInvitationStatusObject() + { + $mode = $_POST['invitation']; + switch ($mode) { + case 0: + $this->object->setInvitation(ilObjSurvey::INVITATION_OFF); + break; + case 1: + $this->object->setInvitationAndMode(ilObjSurvey::INVITATION_ON, ilObjSurvey::MODE_UNLIMITED); + break; + case 2: + $this->object->setInvitationAndMode(ilObjSurvey::INVITATION_ON, ilObjSurvey::MODE_PREDEFINED_USERS); + break; + } + $this->object->saveToDb(); + ilUtil::sendSuccess($this->lng->txt('msg_obj_modified'), true); + $this->ctrl->redirect($this, "invite"); + } + + /** + * Creates the output for user/group invitation to a survey + */ + public function inviteObject() + { + $ilAccess = $this->access; + $rbacsystem = $this->rbacsystem; + $ilToolbar = $this->toolbar; + $lng = $this->lng; + + $this->handleWriteAccess(); + $this->setCodesSubtabs(); + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this)); + $form->setTableWidth("500"); + $form->setId("invite"); + + // invitation + $header = new ilFormSectionHeaderGUI(); + $header->setTitle($this->lng->txt("invitation")); + $form->addItem($header); + + // invitation mode + $invitation = new ilRadioGroupInputGUI($this->lng->txt('invitation_mode'), "invitation"); + $invitation->setInfo($this->lng->txt('invitation_mode_desc')); + $invitation->addOption(new ilRadioOption($this->lng->txt("invitation_off"), 0, '')); + $surveySetting = new ilSetting("survey"); + if ($surveySetting->get("unlimited_invitation")) { + $invitation->addOption(new ilRadioOption($this->lng->txt("unlimited_users"), 1, '')); + } + $invitation->addOption(new ilRadioOption($this->lng->txt("predefined_users"), 2, '')); + $inv = 0; + if ($this->object->getInvitation()) { + $inv = $this->object->getInvitationMode() + 1; + } + $invitation->setValue($inv); + $form->addItem($invitation); + + $form->addCommandButton("saveInvitationStatus", $this->lng->txt("save")); + + $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.il_svy_svy_invite.html", "Modules/Survey"); + $this->tpl->setVariable("INVITATION_TABLE", $form->getHTML()); + + if ($this->object->getInvitation() && $this->object->getInvitationMode() == 1) { + // search button + include_once './Services/Search/classes/class.ilRepositorySearchGUI.php'; + ilRepositorySearchGUI::fillAutoCompleteToolbar( + $this, + $tb, + array( + 'auto_complete_name' => $lng->txt('user'), + 'submit_name' => $lng->txt('svy_invite_action') + ) + ); + + $ilToolbar->addSpacer(); + + $ilToolbar->addButton( + $this->lng->txt("svy_search_users"), + $this->ctrl->getLinkTargetByClass('ilRepositorySearchGUI', '') + ); + + $this->tpl->setVariable("ADM_CONTENT", $form->getHTML()); + + $invited_users = $this->object->getUserData($this->object->getInvitedUsers()); + include_once "./Modules/Survey/classes/tables/class.ilSurveyInvitedUsersTableGUI.php"; + $table_gui = new ilSurveyInvitedUsersTableGUI($this, 'invite'); + $table_gui->setData($invited_users); + $this->tpl->setVariable('TBL_INVITED_USERS', $table_gui->getHTML()); + } + } + + /** + * Creates a confirmation form for delete all user data + */ + public function deleteAllUserDataObject() + { + include_once "Services/Utilities/classes/class.ilConfirmationGUI.php"; + $cgui = new ilConfirmationGUI(); + $cgui->setHeaderText($this->lng->txt("confirm_delete_all_user_data")); + $cgui->setFormAction($this->ctrl->getFormAction($this, "deleteAllUserData")); + $cgui->setCancel($this->lng->txt("cancel"), "cancelDeleteAllUserData"); + $cgui->setConfirm($this->lng->txt("confirm"), "confirmDeleteAllUserData"); + $this->tpl->setContent($cgui->getHTML()); + } + + /** + * Deletes all user data of the survey after confirmation + */ + public function confirmDeleteAllUserDataObject() + { + if ($this->access->checkAccess('write', '', $this->object->getRefId())) { + $this->object->deleteAllUserData(); + } else { + $participants = $this->filterSurveyParticipantsByAccess(); + foreach ($participants as $something => $participant_data) { + $this->object->removeSelectedSurveyResults([$participant_data['active_id']]); + } + } + + + + // #11558 - re-open closed appraisees + if ($this->object->get360Mode()) { + $this->object->openAllAppraisees(); + } + + ilUtil::sendSuccess($this->lng->txt("svy_all_user_data_deleted"), true); + $this->ctrl->redirect($this, "maintenance"); + } + + /** + * Cancels delete of all user data in maintenance + */ + public function cancelDeleteAllUserDataObject() + { + $this->ctrl->redirect($this, "maintenance"); + } + + /** + * Deletes all user data for the test object + */ + public function confirmDeleteSelectedUserDataObject() + { + $this->object->removeSelectedSurveyResults($_POST["chbUser"]); + ilUtil::sendSuccess($this->lng->txt("svy_selected_user_data_deleted"), true); + $this->ctrl->redirect($this, "maintenance"); + } + + /** + * Cancels the deletion of all user data for the test object + */ + public function cancelDeleteSelectedUserDataObject() + { + ilUtil::sendInfo($this->lng->txt('msg_cancel'), true); + $this->ctrl->redirect($this, "maintenance"); + } + + /** + * Asks for a confirmation to delete selected user data of the test object + */ + public function deleteSingleUserResultsObject() + { + $this->handleWriteAccess(); + + if (!is_array($_POST["chbUser"]) || count($_POST["chbUser"]) == 0) { + ilUtil::sendInfo($this->lng->txt('no_checkbox'), true); + $this->ctrl->redirect($this, "maintenance"); + } + + ilUtil::sendQuestion($this->lng->txt("confirm_delete_single_user_data")); + include_once "./Modules/Survey/classes/tables/class.ilSurveyMaintenanceTableGUI.php"; + $table_gui = new ilSurveyMaintenanceTableGUI($this, 'maintenance', true); + $total =&$this->object->getSurveyParticipants(); + $data = array(); + foreach ($total as $user_data) { + if (in_array($user_data['active_id'], $_POST['chbUser'])) { + $last_access = $this->object->getLastAccess($user_data["active_id"]); + array_push($data, array( + 'id' => $user_data["active_id"], + 'name' => $user_data["sortname"], + 'login' => $user_data["login"], + 'last_access' => $last_access + )); + } + } + $table_gui->setData($data); + $this->tpl->setVariable('ADM_CONTENT', $table_gui->getHTML()); + } + + /** + * Change survey language for direct access URL's + */ + public function setCodeLanguageObject() + { + if (strcmp($_POST["lang"], "-1") != 0) { + $ilUser = $this->user; + $ilUser->writePref("survey_code_language", $_POST["lang"]); + } + ilUtil::sendSuccess($this->lng->txt('language_changed'), true); + $this->ctrl->redirect($this, 'codes'); + } + + /** + * Display the survey access codes tab + */ + public function codesObject() + { + $ilUser = $this->user; + $ilToolbar = $this->toolbar; + + $this->handleWriteAccess(); + $this->setCodesSubtabs(); + + if ($this->object->isAccessibleWithoutCode()) { + return ilUtil::sendInfo($this->lng->txt("survey_codes_no_anonymization")); + } + + $default_lang = $ilUser->getPref("survey_code_language"); + + // creation buttons + $ilToolbar->setFormAction($this->ctrl->getFormAction($this)); + + include_once("./Services/Form/classes/class.ilTextInputGUI.php"); + $si = new ilTextInputGUI($this->lng->txt("new_survey_codes"), "nrOfCodes"); + $si->setValue(1); + $si->setSize(3); + $ilToolbar->addInputItem($si, true); + + include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; + + $button = ilSubmitButton::getInstance(); + $button->setCaption("create"); + $button->setCommand("createSurveyCodes"); + $ilToolbar->addButtonInstance($button); + + $ilToolbar->addSeparator(); + + $button = ilSubmitButton::getInstance(); + $button->setCaption("import_from_file"); + $button->setCommand("importExternalMailRecipientsFromFileForm"); + $ilToolbar->addButtonInstance($button); + + $button = ilSubmitButton::getInstance(); + $button->setCaption("import_from_text"); + $button->setCommand("importExternalMailRecipientsFromTextForm"); + $ilToolbar->addButtonInstance($button); + + $ilToolbar->addSeparator(); + + $button = ilSubmitButton::getInstance(); + $button->setCaption("svy_import_codes"); + $button->setCommand("importAccessCodes"); + $ilToolbar->addButtonInstance($button); + + $ilToolbar->addSeparator(); + + $languages = $this->lng->getInstalledLanguages(); + $options = array(); + $this->lng->loadLanguageModule("meta"); + foreach ($languages as $lang) { + $options[$lang] = $this->lng->txt("meta_l_" . $lang); + } + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $si = new ilSelectInputGUI($this->lng->txt("survey_codes_lang"), "lang"); + $si->setOptions($options); + $si->setValue($default_lang); + $ilToolbar->addInputItem($si, true); + + $button = ilSubmitButton::getInstance(); + $button->setCaption("set"); + $button->setCommand("setCodeLanguage"); + $ilToolbar->addButtonInstance($button); + + include_once "./Modules/Survey/classes/tables/class.ilSurveyCodesTableGUI.php"; + $table_gui = new ilSurveyCodesTableGUI($this, 'codes'); + $survey_codes = $this->object->getSurveyCodesTableData(null, $default_lang); + $table_gui->setData($survey_codes); + $this->tpl->setContent($table_gui->getHTML()); + } + + public function editCodesObject() + { + if (isset($_GET["new_ids"])) { + $ids = explode(";", $_GET["new_ids"]); + } else { + $ids = (array) $_POST["chb_code"]; + } + if (!$ids) { + ilUtil::sendFailure($this->lng->txt('no_checkbox'), true); + $this->ctrl->redirect($this, 'codes'); + } + + $this->handleWriteAccess(); + $this->setCodesSubtabs(); + + include_once "./Modules/Survey/classes/tables/class.ilSurveyCodesEditTableGUI.php"; + $table_gui = new ilSurveyCodesEditTableGUI($this, 'editCodes'); + $table_gui->setData($this->object->getSurveyCodesTableData($ids)); + $this->tpl->setContent($table_gui->getHTML()); + } + + public function updateCodesObject() + { + if (!is_array($_POST["chb_code"])) { + $this->ctrl->redirect($this, 'codes'); + } + + $errors = array(); + $error_message = ""; + foreach ($_POST["chb_code"] as $id) { + if (!$this->object->updateCode( + $id, + $_POST["chb_mail"][$id], + $_POST["chb_lname"][$id], + $_POST["chb_fname"][$id], + $_POST["chb_sent"][$id] + )) { + array_push($errors, array($_POST["chb_mail"][$id], $_POST["chb_lname"][$id], $_POST["chb_fname"][$id])); + }; + } + if (empty($errors)) { + ilUtil::sendSuccess($this->lng->txt('settings_saved'), true); + } else { + foreach ($errors as $error) { + $error_message .= sprintf($this->lng->txt("error_save_code"), $error[0], $error[1], $error[2]); + } + ilUtil::sendFailure($error_message, true); + } + + $this->ctrl->redirect($this, 'codes'); + } + + public function deleteCodesConfirmObject() + { + if (is_array($_POST["chb_code"]) && (count($_POST["chb_code"]) > 0)) { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setHeaderText($this->lng->txt("survey_code_delete_sure")); + + $cgui->setFormAction($this->ctrl->getFormAction($this)); + $cgui->setCancel($this->lng->txt("cancel"), "codes"); + $cgui->setConfirm($this->lng->txt("confirm"), "deleteCodes"); + + $data = $this->object->getSurveyCodesTableData($_POST["chb_code"]); + + foreach ($data as $item) { + if ($item["used"]) { + continue; + } + + $title = array($item["code"]); + $item["email"] ? $title[] = $item["email"] : null; + $item["last_name"] ? $title[] = $item["last_name"] : null; + $item["first_name"] ? $title[] = $item["first_name"] : null; + $title = implode(", ", $title); + + $cgui->addItem("chb_code[]", $item["code"], $title); + } + + $this->tpl->setContent($cgui->getHTML()); + } else { + ilUtil::sendFailure($this->lng->txt('no_checkbox'), true); + $this->ctrl->redirect($this, 'codes'); + } + } + + /** + * Delete a list of survey codes + */ + public function deleteCodesObject() + { + if (is_array($_POST["chb_code"]) && (count($_POST["chb_code"]) > 0)) { + foreach ($_POST["chb_code"] as $survey_code) { + $this->object->deleteSurveyCode($survey_code); + } + ilUtil::sendSuccess($this->lng->txt('codes_deleted'), true); + } else { + ilUtil::sendInfo($this->lng->txt('no_checkbox'), true); + } + $this->ctrl->redirect($this, 'codes'); + } + + /** + * Exports a list of survey codes + */ + public function exportCodesObject() + { + if (is_array($_POST["chb_code"]) && (count($_POST["chb_code"]) > 0)) { + $export = $this->object->getSurveyCodesForExport(null, $_POST["chb_code"]); + ilUtil::deliverData($export, ilUtil::getASCIIFilename($this->object->getTitle() . ".csv")); + } else { + ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); + $this->ctrl->redirect($this, 'codes'); + } + } + + /** + * Exports all survey codes + */ + public function exportAllCodesObject() + { + $export = $this->object->getSurveyCodesForExport(); + ilUtil::deliverData($export, ilUtil::getASCIIFilename($this->object->getTitle() . ".csv")); + } + + /** + * Import codes from export codes file (upload form) + */ + protected function importAccessCodesObject() + { + $this->handleWriteAccess(); + $this->setCodesSubtabs(); + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form_import_file = new ilPropertyFormGUI(); + $form_import_file->setFormAction($this->ctrl->getFormAction($this)); + $form_import_file->setTableWidth("100%"); + $form_import_file->setId("codes_import_file"); + + $headerfile = new ilFormSectionHeaderGUI(); + $headerfile->setTitle($this->lng->txt("svy_import_codes")); + $form_import_file->addItem($headerfile); + + $export_file = new ilFileInputGUI($this->lng->txt("codes"), "codes"); + $export_file->setInfo(sprintf( + $this->lng->txt('svy_import_codes_info'), + $this->lng->txt("export_all_survey_codes") + )); + $export_file->setSuffixes(array("csv")); + $export_file->setRequired(true); + $form_import_file->addItem($export_file); + + $form_import_file->addCommandButton("importAccessCodesAction", $this->lng->txt("import")); + $form_import_file->addCommandButton("codes", $this->lng->txt("cancel")); + + $this->tpl->setContent($form_import_file->getHTML()); + } + + /** + * Import codes from export codes file + */ + protected function importAccessCodesActionObject() + { + if (trim($_FILES['codes']['tmp_name'])) { + $existing = array(); + foreach ($this->object->getSurveyCodesTableData() as $item) { + $existing[$item["code"]] = $item["id"]; + } + + include_once "./Services/Utilities/classes/class.ilCSVReader.php"; + $reader = new ilCSVReader(); + $reader->open($_FILES['codes']['tmp_name']); + foreach ($reader->getDataArrayFromCSVFile() as $row) { + // numeric check of used column due to #26176 + if (sizeof($row) == 8 && is_numeric($row[5])) { + // used/sent/url are not relevant when importing + list($code, $email, $last_name, $first_name, $created, $used, $sent, $url) = $row; + + // unique code? + if (!array_key_exists($code, $existing)) { + // could be date or datetime + if (strlen($created) == 10) { + $created = new ilDate($created, IL_CAL_DATE); + } else { + $created = new ilDateTime($created, IL_CAL_DATETIME); + } + $created = $created->get(IL_CAL_UNIX); + + $user_data = array( + "email" => $email + ,"lastname" => $last_name + ,"firstname" => $first_name + ); + $this->object->importSurveyCode($code, $created, $user_data); + } + } + } + + ilUtil::sendSuccess($this->lng->txt('codes_created'), true); + } + + $this->ctrl->redirect($this, 'codes'); + } + + /** + * Create access codes for the survey + */ + public function createSurveyCodesObject() + { + if (is_numeric($_POST["nrOfCodes"])) { + $ids = $this->object->createSurveyCodes($_POST["nrOfCodes"]); + ilUtil::sendSuccess($this->lng->txt('codes_created'), true); + $this->ctrl->setParameter($this, "new_ids", implode(";", $ids)); + $this->ctrl->redirect($this, 'editCodes'); + } else { + ilUtil::sendFailure($this->lng->txt("enter_valid_number_of_codes"), true); + $this->ctrl->redirect($this, 'codes'); + } + } + + public function insertSavedMessageObject() + { + $this->handleWriteAccess(); + $this->setCodesSubtabs(); + + include_once("./Modules/Survey/classes/forms/FormMailCodesGUI.php"); + $form_gui = new FormMailCodesGUI($this); + $form_gui->setValuesByPost(); + try { + if ($form_gui->getSavedMessages()->getValue() > 0) { + $ilUser = $this->user; + $settings = $this->object->getUserSettings($ilUser->getId(), 'savemessage'); + $form_gui->getMailMessage()->setValue($settings[$form_gui->getSavedMessages()->getValue()]['value']); + ilUtil::sendSuccess($this->lng->txt('msg_message_inserted')); + } else { + ilUtil::sendFailure($this->lng->txt('msg_no_message_inserted')); + } + } catch (Exception $e) { + $ilLog = $this->log; + $ilLog->write('Error: ' + $e->getMessage()); + } + $this->tpl->setVariable("ADM_CONTENT", $form_gui->getHTML()); + } + + public function deleteSavedMessageObject() + { + $this->handleWriteAccess(); + $this->setCodesSubtabs(); + + include_once("./Modules/Survey/classes/forms/FormMailCodesGUI.php"); + $form_gui = new FormMailCodesGUI($this); + $form_gui->setValuesByPost(); + try { + if ($form_gui->getSavedMessages()->getValue() > 0) { + $this->object->deleteUserSettings($form_gui->getSavedMessages()->getValue()); + $form_gui = new FormMailCodesGUI($this); + $form_gui->setValuesByPost(); + ilUtil::sendSuccess($this->lng->txt('msg_message_deleted')); + } else { + ilUtil::sendFailure($this->lng->txt('msg_no_message_deleted')); + } + } catch (Exception $e) { + $ilLog = $this->log; + $ilLog->write('Error: ' + $e->getMessage()); + } + $this->tpl->setVariable("ADM_CONTENT", $form_gui->getHTML()); + } + + public function mailCodesObject() + { + $this->handleWriteAccess(); + $this->setCodesSubtabs(); + + $mailData['m_subject'] = (array_key_exists('m_subject', $_POST)) ? $_POST['m_subject'] : sprintf($this->lng->txt('default_codes_mail_subject'), $this->object->getTitle()); + $mailData['m_message'] = (array_key_exists('m_message', $_POST)) ? $_POST['m_message'] : $this->lng->txt('default_codes_mail_message'); + $mailData['m_notsent'] = (array_key_exists('m_notsent', $_POST)) ? $_POST['m_notsent'] : '1'; + + include_once("./Modules/Survey/classes/forms/FormMailCodesGUI.php"); + $form_gui = new FormMailCodesGUI($this); + $form_gui->setValuesByArray($mailData); + $this->tpl->setVariable("ADM_CONTENT", $form_gui->getHTML()); + } + + public function sendCodesMailObject() + { + $ilUser = $this->user; + + $this->handleWriteAccess(); + $this->setCodesSubtabs(); + + include_once("./Modules/Survey/classes/forms/FormMailCodesGUI.php"); + $form_gui = new FormMailCodesGUI($this); + if ($form_gui->checkInput()) { + $url_exists = strpos($_POST['m_message'], '[url]') !== false; + if (!$url_exists) { + ilUtil::sendFailure($this->lng->txt('please_enter_mail_url')); + $form_gui->setValuesByPost(); + } else { + if ($_POST['savemessage'] == 1) { + $ilUser = $this->user; + $title = (strlen($_POST['savemessagetitle'])) ? $_POST['savemessagetitle'] : ilStr::substr($_POST['m_message'], 0, 40) . '...'; + $this->object->saveUserSettings($ilUser->getId(), 'savemessage', $title, $_POST['m_message']); + } + + $lang = $ilUser->getPref("survey_code_language"); + if (!$lang) { + $lang = $this->lng->getDefaultLanguage(); + } + $this->object->sendCodes($_POST['m_notsent'], $_POST['m_subject'], nl2br($_POST['m_message']), $lang); + ilUtil::sendSuccess($this->lng->txt('mail_sent'), true); + $this->ctrl->redirect($this, 'mailCodes'); + } + } else { + $form_gui->setValuesByPost(); + } + $this->tpl->setVariable("ADM_CONTENT", $form_gui->getHTML()); + } + + public function importExternalRecipientsFromTextObject() + { + if (trim($_POST['externaltext'])) { + $data = preg_split("/[\n\r]/", $_POST['externaltext']); + $fields = preg_split("/;/", array_shift($data)); + if (!in_array('email', $fields)) { + $_SESSION['externaltext'] = $_POST['externaltext']; + ilUtil::sendFailure($this->lng->txt('err_external_rcp_no_email_column'), true); + $this->ctrl->redirect($this, 'importExternalMailRecipientsFromTextForm'); + } + $existingdata = $this->object->getExternalCodeRecipients(); + $existingcolumns = array(); + if (count($existingdata)) { + $first = array_shift($existingdata); + foreach ($first as $key => $value) { + array_push($existingcolumns, $key); + } + } + $founddata = array(); + foreach ($data as $datarow) { + $row = preg_split("/;/", $datarow); + if (count($row) == count($fields)) { + $dataset = array(); + foreach ($fields as $idx => $fieldname) { + if (count($existingcolumns)) { + if (array_key_exists($idx, $existingcolumns)) { + $dataset[$fieldname] = $row[$idx]; + } + } else { + $dataset[$fieldname] = $row[$idx]; + } + } + if (strlen($dataset['email'])) { + array_push($founddata, $dataset); + } + } + } + $this->object->createSurveyCodesForExternalData($founddata); + ilUtil::sendSuccess($this->lng->txt('external_recipients_imported'), true); + $this->ctrl->redirect($this, 'codes'); + } + + $this->ctrl->redirect($this, 'importExternalMailRecipientsFromTextForm'); + } + + // see ilBookmarkImportExport + protected function _convertCharset($a_string, $a_from_charset="", $a_to_charset="UTF-8") + { + if (extension_loaded("mbstring")) { + if (!$a_from_charset) { + mb_detect_order("UTF-8, ISO-8859-1, Windows-1252, ASCII"); + $a_from_charset = mb_detect_encoding($a_string); + } + if (strtoupper($a_from_charset) != $a_to_charset) { + return @mb_convert_encoding($a_string, $a_to_charset, $a_from_charset); + } + } + return $a_string; + } + + protected function removeUTF8Bom($a_text) + { + $bom = pack('H*', 'EFBBBF'); + return preg_replace('/^' . $bom . '/', '', $a_text); + } + + public function importExternalRecipientsFromFileObject() + { + if (trim($_FILES['externalmails']['tmp_name'])) { + include_once "./Services/Utilities/classes/class.ilCSVReader.php"; + $reader = new ilCSVReader(); + $reader->open($_FILES['externalmails']['tmp_name']); + $data = $reader->getDataArrayFromCSVFile(); + $fields = array_shift($data); + foreach ($fields as $idx => $field) { + $fields[$idx] = $this->removeUTF8Bom($field); + } + if (!in_array('email', $fields)) { + $reader->close(); + ilUtil::sendFailure($this->lng->txt('err_external_rcp_no_email'), true); + $this->ctrl->redirect($this, 'codes'); + } + $existingdata = $this->object->getExternalCodeRecipients(); + $existingcolumns = array(); + if (count($existingdata)) { + $first = array_shift($existingdata); + foreach ($first as $key => $value) { + array_push($existingcolumns, $key); + } + } + + include_once "Services/Utilities/classes/class.ilStr.php"; + + $founddata = array(); + foreach ($data as $row) { + if (count($row) == count($fields)) { + $dataset = array(); + foreach ($fields as $idx => $fieldname) { + // #14811 + $row[$idx] = $this->_convertCharset($row[$idx]); + + if (count($existingcolumns)) { + if (array_key_exists($idx, $existingcolumns)) { + $dataset[$fieldname] = $row[$idx]; + } + } else { + $dataset[$fieldname] = $row[$idx]; + } + } + if (strlen($dataset['email'])) { + array_push($founddata, $dataset); + } + } + } + $reader->close(); + + if (sizeof($founddata)) { + $this->object->createSurveyCodesForExternalData($founddata); + ilUtil::sendSuccess($this->lng->txt('external_recipients_imported'), true); + } + } + + $this->ctrl->redirect($this, 'codes'); + } + + public function importExternalMailRecipientsFromFileFormObject() + { + $ilAccess = $this->access; + + $this->handleWriteAccess(); + $this->setCodesSubtabs(); + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form_import_file = new ilPropertyFormGUI(); + $form_import_file->setFormAction($this->ctrl->getFormAction($this)); + $form_import_file->setTableWidth("100%"); + $form_import_file->setId("codes_import_file"); + + $headerfile = new ilFormSectionHeaderGUI(); + $headerfile->setTitle($this->lng->txt("import_from_file")); + $form_import_file->addItem($headerfile); + + $externalmails = new ilFileInputGUI($this->lng->txt("externalmails"), "externalmails"); + $externalmails->setInfo($this->lng->txt('externalmails_info')); + $externalmails->setRequired(true); + $form_import_file->addItem($externalmails); + if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) { + $form_import_file->addCommandButton("importExternalRecipientsFromFile", $this->lng->txt("import")); + } + if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) { + $form_import_file->addCommandButton("codes", $this->lng->txt("cancel")); + } + + $this->tpl->setContent($form_import_file->getHTML()); + } + + public function importExternalMailRecipientsFromTextFormObject() + { + $ilAccess = $this->access; + + $this->handleWriteAccess(); + $this->setCodesSubtabs(); + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form_import_text = new ilPropertyFormGUI(); + $form_import_text->setFormAction($this->ctrl->getFormAction($this)); + $form_import_text->setTableWidth("100%"); + $form_import_text->setId("codes_import_text"); + + $headertext = new ilFormSectionHeaderGUI(); + $headertext->setTitle($this->lng->txt("import_from_text")); + $form_import_text->addItem($headertext); + + $inp = new ilTextAreaInputGUI($this->lng->txt('externaltext'), 'externaltext'); + if (array_key_exists('externaltext', $_SESSION) && strlen($_SESSION['externaltext'])) { + $inp->setValue($_SESSION['externaltext']); + } else { + // $this->lng->txt('mail_import_example1') #14897 + $inp->setValue("email;firstname;lastname\n" . $this->lng->txt('mail_import_example2') . "\n" . $this->lng->txt('mail_import_example3') . "\n"); + } + $inp->setRequired(true); + $inp->setCols(80); + $inp->setRows(10); + $inp->setInfo($this->lng->txt('externaltext_info')); + $form_import_text->addItem($inp); + unset($_SESSION['externaltext']); + + if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) { + $form_import_text->addCommandButton("importExternalRecipientsFromText", $this->lng->txt("import")); + } + if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) { + $form_import_text->addCommandButton("codes", $this->lng->txt("cancel")); + } + + $this->tpl->setContent($form_import_text->getHTML()); + } + + + + + + + + + + + // + // 360° + // + + + + + public function listAppraiseesObject() + { + $ilToolbar = $this->toolbar; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $this->handleWriteAccess(); + + $this->ctrl->setParameter($this, "appr360", 1); + + include_once './Services/Search/classes/class.ilRepositorySearchGUI.php'; + ilRepositorySearchGUI::fillAutoCompleteToolbar( + $this, + $ilToolbar, + array( + 'auto_complete_name' => $this->lng->txt('user'), + 'submit_name' => $this->lng->txt('add'), + 'add_search' => true, + 'add_from_container' => $this->ref_id + ) + ); + + // competence calculations + include_once("./Services/Skill/classes/class.ilSkillManagementSettings.php"); + $skmg_set = new ilSkillManagementSettings(); + if ($this->object->getSkillService() && $skmg_set->isActivated()) { + $ilToolbar->addSeparator(); + $ilToolbar->addButton( + $lng->txt("survey_calc_skills"), + $ilCtrl->getLinkTargetByClass("ilsurveyskilldeterminationgui"), + "" + ); + } + + $ilToolbar->addSeparator(); + $ilToolbar->addButton( + $this->lng->txt('svy_delete_all_user_data'), + $this->ctrl->getLinkTarget($this, 'deleteAllUserData') + ); + + $this->ctrl->setParameter($this, "appr360", ""); + + include_once "Modules/Survey/classes/tables/class.ilSurveyAppraiseesTableGUI.php"; + $tbl = new ilSurveyAppraiseesTableGUI($this, "listAppraisees"); + $tbl->setData($this->object->getAppraiseesData()); + $this->tpl->setContent($tbl->getHTML()); + } + + public function addAppraisee($a_user_ids) + { + if (sizeof($a_user_ids)) { + // #13319 + foreach (array_unique($a_user_ids) as $user_id) { + $this->object->addAppraisee($user_id); + } + + ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); + } + $this->ctrl->redirect($this, "listAppraisees"); + } + + public function confirmDeleteAppraiseesObject() + { + $ilTabs = $this->tabs; + + if (!sizeof($_POST["appr_id"])) { + ilUtil::sendFailure($this->lng->txt("select_one"), true); + $this->ctrl->redirect($this, "listAppraisees"); + } + + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $this->lng->txt("btn_back"), + $this->ctrl->getLinkTarget($this, "listAppraisees") + ); + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setHeaderText($this->lng->txt("survey_360_sure_delete_appraises")); + + $cgui->setFormAction($this->ctrl->getFormAction($this, "deleteAppraisees")); + $cgui->setCancel($this->lng->txt("cancel"), "listAppraisees"); + $cgui->setConfirm($this->lng->txt("confirm"), "deleteAppraisees"); + + $data = $this->object->getAppraiseesData(); + + $count = 0; + include_once "Services/User/classes/class.ilUserUtil.php"; + foreach ($_POST["appr_id"] as $id) { + if (isset($data[$id]) && !$data[$id]["closed"]) { + $cgui->addItem("appr_id[]", $id, ilUserUtil::getNamePresentation($id)); + $count++; + } + } + + if (!$count) { + ilUtil::sendFailure($this->lng->txt("select_one"), true); + $this->ctrl->redirect($this, "listAppraisees"); + } + + $this->tpl->setContent($cgui->getHTML()); + } + + public function deleteAppraiseesObject() + { + if (sizeof($_POST["appr_id"])) { + $data = $this->object->getAppraiseesData(); + + foreach ($_POST["appr_id"] as $id) { + // #11285 + if (isset($data[$id]) && !$data[$id]["closed"]) { + $this->object->deleteAppraisee($id); + } + } + + ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); + } + + $this->ctrl->redirect($this, "listAppraisees"); + } + + public function handleRatersAccess() + { + $ilAccess = $this->access; + $ilUser = $this->user; + + if ($ilAccess->checkAccess("write", "", $this->ref_id)) { + $appr_id = $_REQUEST["appr_id"]; + if (!$appr_id) { + $this->ctrl->redirect($this, "listAppraisees"); + } + return $appr_id; + } elseif ($this->object->get360Mode() && + $this->object->get360SelfRaters() && + $this->object->isAppraisee($ilUser->getId()) && + !$this->object->isAppraiseeClosed($ilUser->getId())) { + return $ilUser->getId(); + } + $this->ctrl->redirect($this->parent_gui, "infoScreen"); + } + + public function editRatersObject() + { + $ilTabs = $this->tabs; + $ilToolbar = $this->toolbar; + $ilAccess = $this->access; + + $appr_id = $_REQUEST["appr_id"] = $this->handleRatersAccess(); + + $has_write = $ilAccess->checkAccess("write", "", $this->ref_id); + if ($has_write) { + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $this->lng->txt("btn_back"), + $this->ctrl->getLinkTarget($this, "listAppraisees") + ); + } + + $this->ctrl->setParameter($this, "appr_id", $appr_id); + $this->ctrl->setParameter($this, "rate360", 1); + + include_once './Services/Search/classes/class.ilRepositorySearchGUI.php'; + ilRepositorySearchGUI::fillAutoCompleteToolbar( + $this, + $ilToolbar, + array( + 'auto_complete_name' => $this->lng->txt('user'), + 'submit_name' => $this->lng->txt('add'), + 'add_search' => true, + 'add_from_container' => $this->ref_id + ) + ); + + $this->ctrl->setParameter($this, "rate360", ""); + + $ilToolbar->addSeparator(); + + $ilToolbar->addButton( + $this->lng->txt("survey_360_add_external_rater"), + $this->ctrl->getLinkTarget($this, "addExternalRaterForm") + ); + + // #13320 + require_once "Services/Link/classes/class.ilLink.php"; + $url = ilLink::_getStaticLink($this->object->getRefId()); + + include_once "Modules/Survey/classes/tables/class.ilSurveyAppraiseesTableGUI.php"; + $tbl = new ilSurveyAppraiseesTableGUI($this, "editRaters", true, !$this->object->isAppraiseeClosed($appr_id), $url); // #11285 + $tbl->setData($this->object->getRatersData($appr_id)); + $this->tpl->setContent($tbl->getHTML()); + } + + public function addExternalRaterFormObject(ilPropertyFormGUI $a_form = null) + { + $ilTabs = $this->tabs; + $ilAccess = $this->access; + + $appr_id = $this->handleRatersAccess(); + $this->ctrl->setParameter($this, "appr_id", $appr_id); + + $has_write = $ilAccess->checkAccess("write", "", $this->ref_id); + if ($has_write) { + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $this->lng->txt("btn_back"), + $this->ctrl->getLinkTarget($this, "editRaters") + ); + } + + if (!$a_form) { + $a_form = $this->initExternalRaterForm($appr_id); + } + + $this->tpl->setContent($a_form->getHTML()); + } + + protected function initExternalRaterForm($appr_id) + { + include_once "Services/User/classes/class.ilUserUtil.php"; + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this, "addExternalRater")); + $form->setTitle($this->lng->txt("survey_360_add_external_rater") . + ": " . ilUserUtil::getNamePresentation($appr_id)); + + $email = new ilEmailInputGUI($this->lng->txt("email"), "email"); + $email->setRequired(true); + $form->addItem($email); + + $lname = new ilTextInputGUI($this->lng->txt("lastname"), "lname"); + $lname->setSize(30); + $form->addItem($lname); + + $fname = new ilTextInputGUI($this->lng->txt("firstname"), "fname"); + $fname->setSize(30); + $form->addItem($fname); + + $form->addCommandButton("addExternalRater", $this->lng->txt("save")); + $form->addCommandButton("editRaters", $this->lng->txt("cancel")); + + return $form; + } + + public function addExternalRaterObject() + { + $appr_id = $_REQUEST["appr_id"]; + if (!$appr_id) { + $this->ctrl->redirect($this, "listAppraisees"); + } + + $this->ctrl->setParameter($this, "appr_id", $appr_id); + + $form = $this->initExternalRaterForm($appr_id); + if ($form->checkInput()) { + $data = array( + "email" => $form->getInput("email"), + "lastname" => $form->getInput("lname"), + "firstname" => $form->getInput("fname") + ); + $anonymous_id = $this->object->createSurveyCodesForExternalData(array($data)); + $anonymous_id = array_pop($anonymous_id); + + $this->object->addRater($appr_id, 0, $anonymous_id); + + ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); + $this->ctrl->setParameter($this, "appr_id", $appr_id); + $this->ctrl->redirect($this, "editRaters"); + } + + $form->setValuesByPost(); + $this->addExternalRaterFormObject($form); + } + + public function addRater($a_user_ids) + { + $ilAccess = $this->access; + $ilUser = $this->user; + + $appr_id = $this->handleRatersAccess(); + + if (sizeof($a_user_ids)) { + // #13319 + foreach (array_unique($a_user_ids) as $user_id) { + if ($ilAccess->checkAccess("write", "", $this->ref_id) || + $this->object->get360SelfEvaluation() || + $user_id != $ilUser->getId()) { + if ($appr_id != $user_id) { + $this->object->addRater($appr_id, $user_id); + ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); + } else { + ilUtil::sendFailure($this->lng->txt("svy_appraisses_cannot_be_raters"), true); + } + } + } + } + + $this->ctrl->setParameter($this, "appr_id", $appr_id); + $this->ctrl->redirect($this, "editRaters"); + } + + public function confirmDeleteRatersObject() + { + $ilTabs = $this->tabs; + + $appr_id = $this->handleRatersAccess(); + $this->ctrl->setParameter($this, "appr_id", $appr_id); + if (!sizeof($_POST["rtr_id"])) { + ilUtil::sendFailure($this->lng->txt("select_one"), true); + $this->ctrl->redirect($this, "editRaters"); + } + + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $this->lng->txt("btn_back"), + $this->ctrl->getLinkTarget($this, "editRaters") + ); + + include_once "Services/User/classes/class.ilUserUtil.php"; + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setHeaderText(sprintf( + $this->lng->txt("survey_360_sure_delete_raters"), + ilUserUtil::getNamePresentation($appr_id) + )); + + $cgui->setFormAction($this->ctrl->getFormAction($this, "deleteRaters")); + $cgui->setCancel($this->lng->txt("cancel"), "editRaters"); + $cgui->setConfirm($this->lng->txt("confirm"), "deleteRaters"); + + $data = $this->object->getRatersData($appr_id); + + foreach ($_POST["rtr_id"] as $id) { + if (isset($data[$id])) { + $cgui->addItem("rtr_id[]", $id, $data[$id]["lastname"] . ", " . + $data[$id]["firstname"] . " (" . $data[$id]["email"] . ")"); + } + } + + $this->tpl->setContent($cgui->getHTML()); + } + + public function deleteRatersObject() + { + $appr_id = $this->handleRatersAccess(); + $this->ctrl->setParameter($this, "appr_id", $appr_id); + + if (sizeof($_POST["rtr_id"])) { + $data = $this->object->getRatersData($appr_id); + + foreach ($_POST["rtr_id"] as $id) { + if (isset($data[$id])) { + if (substr($id, 0, 1) == "u") { + $this->object->deleteRater($appr_id, substr($id, 1)); + } else { + $this->object->deleteRater($appr_id, 0, substr($id, 1)); + } + } + } + + ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); + } + + $this->ctrl->redirect($this, "editRaters"); + } + + public function addSelfAppraiseeObject() + { + $ilUser = $this->user; + + if ($this->object->get360SelfAppraisee() && + !$this->object->isAppraisee($ilUser->getId())) { + $this->object->addAppraisee($ilUser->getId()); + } + + $this->ctrl->redirect($this->parent_gui, "infoScreen"); + } + + public function initMailRatersForm($appr_id, array $rec_ids) + { + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this, "mailRatersAction")); + $form->setTitle($this->lng->txt('compose')); + + $all_data = $this->object->getRatersData($appr_id); + $rec_data = array(); + foreach ($rec_ids as $rec_id) { + if (isset($all_data[$rec_id])) { + $rec_data[] = $all_data[$rec_id]["lastname"] . ", " . + $all_data[$rec_id]["firstname"] . + " (" . $all_data[$rec_id]["email"] . ")"; + } + } + sort($rec_data); + $rec = new ilCustomInputGUI($this->lng->txt('recipients')); + $rec->setHTML(implode("
", $rec_data)); + $form->addItem($rec); + + $subject = new ilTextInputGUI($this->lng->txt('subject'), 'subject'); + $subject->setSize(50); + $subject->setRequired(true); + $form->addItem($subject); + + $existingdata = $this->object->getExternalCodeRecipients(); + $existingcolumns = array(); + if (count($existingdata)) { + $first = array_shift($existingdata); + foreach ($first as $key => $value) { + if (strcmp($key, 'code') != 0 && strcmp($key, 'email') != 0 && strcmp($key, 'sent') != 0) { + array_push($existingcolumns, '[' . $key . ']'); + } + } + } + + $mailmessage_u = new ilTextAreaInputGUI($this->lng->txt('survey_360_rater_message_content_registered'), 'message_u'); + $mailmessage_u->setRequired(true); + $mailmessage_u->setCols(80); + $mailmessage_u->setRows(10); + $form->addItem($mailmessage_u); + + $mailmessage_a = new ilTextAreaInputGUI($this->lng->txt('survey_360_rater_message_content_anonymous'), 'message_a'); + $mailmessage_a->setRequired(true); + $mailmessage_a->setCols(80); + $mailmessage_a->setRows(10); + $mailmessage_a->setInfo(sprintf($this->lng->txt('message_content_info'), join($existingcolumns, ', '))); + $form->addItem($mailmessage_a); + + $recf = new ilHiddenInputGUI("rtr_id"); + $recf->setValue(implode(";", $rec_ids)); + $form->addItem($recf); + + $form->addCommandButton("mailRatersAction", $this->lng->txt("send")); + $form->addCommandButton("editRaters", $this->lng->txt("cancel")); + + $subject->setValue(sprintf($this->lng->txt('survey_360_rater_subject_default'), $this->object->getTitle())); + $mailmessage_u->setValue($this->lng->txt('survey_360_rater_message_content_registered_default')); + $mailmessage_a->setValue($this->lng->txt('survey_360_rater_message_content_anonymous_default')); + + return $form; + } + + public function mailRatersObject(ilPropertyFormGUI $a_form = null) + { + $ilTabs = $this->tabs; + + if (!$a_form) { + $appr_id = $this->handleRatersAccess(); + $this->ctrl->setParameter($this, "appr_id", $appr_id); + + if (!sizeof($_POST["rtr_id"])) { + ilUtil::sendFailure($this->lng->txt("select_one"), true); + $this->ctrl->redirect($this, "editRaters"); + } + + $a_form = $this->initMailRatersForm($appr_id, $_POST["rtr_id"]); + } + + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $this->lng->txt("btn_back"), + $this->ctrl->getLinkTarget($this, "editRaters") + ); + + $this->tpl->setContent($a_form->getHTML()); + } + + public function mailRatersActionObject() + { + $ilUser = $this->user; + + $appr_id = $this->handleRatersAccess(); + $this->ctrl->setParameter($this, "appr_id", $appr_id); + + $rec_ids = explode(";", $_POST["rtr_id"]); + if (!sizeof($rec_ids)) { + $this->ctrl->redirect($this, "editRaters"); + } + + $form = $this->initMailRatersForm($appr_id, $rec_ids); + if ($form->checkInput()) { + $txt_u = $form->getInput("message_u"); + $txt_a = $form->getInput("message_a"); + $subj = $form->getInput("subject"); + + // #12743 + $sender_id = (trim($ilUser->getEmail())) + ? $ilUser->getId() + : ANONYMOUS_USER_ID; + + include_once "./Services/Mail/classes/class.ilMail.php"; + + $all_data = $this->object->getRatersData($appr_id); + foreach ($rec_ids as $rec_id) { + if (isset($all_data[$rec_id])) { + $user = $all_data[$rec_id]; + + // anonymous + if (substr($rec_id, 0, 1) == "a") { + $mytxt = $txt_a; + $url = $user["href"]; + $rcp = $user["email"]; + } + // reg + else { + $mytxt = $txt_u; + $user["code"] = $this->lng->txt("survey_code_mail_on_demand"); + $url = ilLink::_getStaticLink($this->object->getRefId()); + $rcp = $user["login"]; // #15141 + } + + $mytxt = str_replace("[lastname]", $user["lastname"], $mytxt); + $mytxt = str_replace("[firstname]", $user["firstname"], $mytxt); + $mytxt = str_replace("[url]", $url, $mytxt); + $mytxt = str_replace("[code]", $user["code"], $mytxt); + + $mail = new ilMail($sender_id); + $mail->sendMail( + $rcp, // to + "", // cc + "", // bcc + $subj, // subject + $mytxt, // message + array(), // attachments + array('normal') // type + ); + + $this->object->set360RaterSent( + $appr_id, + (substr($rec_id, 0, 1) == "a") ? 0 : (int) substr($rec_id, 1), + (substr($rec_id, 0, 1) == "u") ? 0 : (int) substr($rec_id, 1) + ); + } + } + + ilUtil::sendSuccess($this->lng->txt("mail_sent"), true); + $this->ctrl->redirect($this, "editRaters"); + } + + $form->setValuesByPost(); + $this->mailRatersObject($form); + } + + public function confirmAppraiseeCloseObject() + { + $ilUser = $this->user; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $this->lng->txt("menuback"), + $this->ctrl->getLinkTarget($this->parent_gui, "infoScreen") + ); + + if (!$this->object->isAppraisee($ilUser->getId())) { + $this->ctrl->redirect($this->parent_gui, "infoScreen"); + } + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setHeaderText($this->lng->txt("survey_360_sure_appraisee_close")); + + $cgui->setFormAction($this->ctrl->getFormAction($this, "appraiseeClose")); + $cgui->setCancel($this->lng->txt("cancel"), "confirmAppraiseeCloseCancel"); + $cgui->setConfirm($this->lng->txt("confirm"), "appraiseeClose"); + + $tpl->setContent($cgui->getHTML()); + } + + public function confirmAppraiseeCloseCancelObject() + { + $this->ctrl->redirect($this->parent_gui, "infoScreen"); + } + + public function appraiseeCloseObject() + { + $ilUser = $this->user; + + if (!$this->object->isAppraisee($ilUser->getId())) { + $this->ctrl->redirect($this->parent_gui, "infoScreen"); + } + + $this->object->closeAppraisee($ilUser->getId()); + ilUtil::sendSuccess($this->lng->txt("survey_360_appraisee_close_action_success"), true); + $this->ctrl->redirect($this->parent_gui, "infoScreen"); + } + + public function confirmAdminAppraiseesCloseObject() + { + $tpl = $this->tpl; + + $this->handleWriteAccess(); + + $appr_ids = $_POST["appr_id"]; + + if (!sizeof($appr_ids)) { + ilUtil::sendFailure($this->lng->txt("select_one"), true); + $this->ctrl->redirect($this, "listAppraisees"); + } + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setHeaderText($this->lng->txt("survey_360_sure_appraisee_close_admin")); + + $cgui->setFormAction($this->ctrl->getFormAction($this, "adminAppraiseesClose")); + $cgui->setCancel($this->lng->txt("cancel"), "listAppraisees"); + $cgui->setConfirm($this->lng->txt("confirm"), "adminAppraiseesClose"); + + include_once "Services/User/classes/class.ilUserUtil.php"; + foreach ($appr_ids as $appr_id) { + $cgui->addItem("appr_id[]", $appr_id, ilUserUtil::getNamePresentation($appr_id)); + } + + $tpl->setContent($cgui->getHTML()); + } + + public function adminAppraiseesCloseObject() + { + $this->handleWriteAccess(); + + $appr_ids = $_POST["appr_id"]; + + if (!sizeof($appr_ids)) { + ilUtil::sendFailure($this->lng->txt("select_one"), true); + $this->ctrl->redirect($this, "listAppraisees"); + } + + $appr_data = $this->object->getAppraiseesData(); + foreach ($appr_ids as $appr_id) { + if (isset($appr_data[$appr_id]) && !$appr_data[$appr_id]["closed"]) { + $this->object->closeAppraisee($appr_id); + } + } + + ilUtil::sendSuccess($this->lng->txt("survey_360_appraisee_close_action_success_admin"), true); + $this->ctrl->redirect($this, "listAppraisees"); + } + + protected function listParticipantsObject() + { + $ilToolbar = $this->toolbar; + + if (!$this->isAnonymousListActive()) { + $this->ctrl->redirect($this, "maintenance"); + } + + $this->handleWriteAccess(); + $this->setCodesSubtabs(); + + include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; + $button = ilLinkButton::getInstance(); + $button->setCaption("print"); + $button->setOnClick("window.print(); return false;"); + $button->setOmitPreventDoubleSubmission(true); + $ilToolbar->addButtonInstance($button); + + include_once "Modules/Survey/classes/tables/class.ilSurveyParticipantsTableGUI.php"; + $tbl = new ilSurveyParticipantsTableGUI($this, "listParticipants", $this->object); + $this->tpl->setContent($tbl->getHTML()); + } + + public function getObject() + { + return $this->object; + } +} diff --git a/Modules/Survey/classes/class.ilSurveyQuestionTableGUI.php b/Modules/Survey/classes/class.ilSurveyQuestionTableGUI.php index 13c14bb390479cf562928bd631721b02dec32234..1f9c711b4435dceaab6dcfd99ed175363ca18ed5 100644 --- a/Modules/Survey/classes/class.ilSurveyQuestionTableGUI.php +++ b/Modules/Survey/classes/class.ilSurveyQuestionTableGUI.php @@ -1,384 +1,343 @@ - - * @version $Id$ - * - * @ingroup ModulesSurvey - */ -class ilSurveyQuestionTableGUI extends ilTable2GUI -{ - protected $object; - protected $read_only; - - /** - * Constructor - * - * @param object $a_parent_obj parent gui object - * @param string $a_parent_cmd parent default command - */ - function __construct($a_parent_obj, $a_parent_cmd, ilObjSurvey $a_survey_obj, $a_read_only = false) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->object = $a_survey_obj; - $this->read_only = (bool)$a_read_only; - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setId("il_svy_qst"); - $this->setLimit(9999); - - // $this->setTitle($lng->txt("survey_questions")); - - if(!$this->read_only) - { - // command dropdown - if(!array_key_exists("move_questions", $_SESSION)) - { - $this->addMultiCommand("createQuestionblock", $lng->txt("define_questionblock")); - $this->addMultiCommand("unfoldQuestionblock", $lng->txt("unfold")); - $this->addMultiCommand("removeQuestions", $lng->txt("remove_question")); - $this->addMultiCommand("moveQuestions", $lng->txt("move")); - $this->addMultiCommand("copyQuestionsToPool", $lng->txt("survey_copy_questions_to_pool")); - } - else - { - $this->addMultiCommand("insertQuestionsBefore", $lng->txt("insert_before")); - $this->addMultiCommand("insertQuestionsAfter", $lng->txt("insert_after")); - } - - // right side - $this->addCommandButton("saveObligatory", $lng->txt("save_obligatory_state")); - - $this->setSelectAllCheckbox("id[]"); - $this->addColumn("", ""); - $this->addColumn($lng->txt("survey_order"), ""); - } - - $this->addColumn($lng->txt("title"), ""); - $this->addColumn($lng->txt("obligatory"), ""); - $this->addColumn($lng->txt("description"), ""); - $this->addColumn($lng->txt("type"), ""); - $this->addColumn($lng->txt("author"), ""); - $this->addColumn($lng->txt("survey_question_pool"), ""); - - if(!$this->read_only) - { - $this->addColumn("", ""); - } - - $this->setDefaultOrderField("order"); - $this->setDefaultOrderDirection("asc"); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.il_svy_svy_question_table.html", "Modules/Survey"); - - $this->setShowRowsSelector(true); - - $this->importData(); - } - - /** - * Import data from DB - */ - protected function importData() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $survey_questions = $this->object->getSurveyQuestions(); - if (count($survey_questions) > 0) - { - include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"; - $questiontypes = ilObjSurveyQuestionPool::_getQuestiontypes(); - - $questionpools = $this->object->getQuestionpoolTitles(true); - - $table_data = array(); - $last_questionblock_id = $position = $block_position = 0; - foreach ($survey_questions as $question_id => $data) - { - // question block - if ($data["questionblock_id"] > 0 && - $data["questionblock_id"] != $last_questionblock_id) - { - $id = "qb_" . $data["questionblock_id"]; - - $table_data[$id] = array("id" => $id, - "type" => "block", - "title" => $data["questionblock_title"]); - - if (!$this->read_only) - { - // order - if(sizeof($survey_questions) > 1) - { - $position += 10; - $table_data[$id]["position"] = $position; - } - - $ilCtrl->setParameter($this->parent_obj, "bl_id", $data["questionblock_id"]); - $table_data[$id]["url"] = $ilCtrl->getLinkTarget($this->parent_obj, "editQuestionblock"); - $ilCtrl->setParameter($this->parent_obj, "bl_id", ""); - } - - $block_position = 0; - } - - // question - - $id = $data["question_id"]; - - $table_data[$id] = array("id" => $id, - "type" => "question", - "heading" => $data["heading"], - "title" => $data["title"], - "description" => $data["description"], - "author" => $data["author"], - "block_id" => $data["questionblock_id"], - "obligatory" => (bool)$data["obligatory"]); - - // question type - foreach ($questiontypes as $trans => $typedata) - { - if (strcmp($typedata["type_tag"], $data["type_tag"]) == 0) - { - $table_data[$id]["question_type"] = $trans; - } - } - - // pool title - if($data["original_id"]) - { - $original_fi = SurveyQuestion::lookupObjFi($data["original_id"]); - if(isset($questionpools[$original_fi])) - { - $table_data[$id]["pool"] = $questionpools[$original_fi]; - } - else - { - // #11186 - $table_data[$id]["pool"] = $this->lng->txt("status_no_permission"); - } - } - - if (!$this->read_only) - { - if ($data["obj_fi"] > 0) - { - // edit url - $q_gui = $data["type_tag"]."GUI"; - $ilCtrl->setParameterByClass($q_gui, "q_id", $id); - $table_data[$id]["url"] = $ilCtrl->getLinkTargetByClass($q_gui, "editQuestion") . - $ilCtrl->setParameterByClass($q_gui, "q_id", ""); - } - - // order - if(sizeof($survey_questions) > 1) - { - if (!$data["questionblock_id"]) - { - $position += 10; - $table_data[$id]["position"] = $position; - } - else - { - $block_position += 10; - $table_data[$id]["position"] = $block_position; - } - } - } - - $last_questionblock_id = $data["questionblock_id"]; - } - } - - $this->setData($table_data); - } - - /** - * Fill table row - * - * @param array $a_set data array - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - switch($a_set["type"]) - { - case "block": - if(!$this->read_only) - { - // checkbox - $this->tpl->setCurrentBlock("checkable"); - $this->tpl->setVariable("QUESTION_ID", $a_set["id"]); - $this->tpl->parseCurrentBlock(); - - // order - if($a_set["position"]) - { - $this->tpl->setCurrentBlock("order"); - $this->tpl->setVariable("ORDER_NAME", "order[".$a_set["id"]."]"); - $this->tpl->setVariable("ORDER_VALUE", $a_set["position"]); - $this->tpl->parseCurrentBlock(); - } - } - - $this->tpl->setVariable("TYPE", $lng->txt("questionblock")); - break; - - case "question": - $this->tpl->setVariable("DESCRIPTION", $a_set["description"]); - $this->tpl->setVariable("TYPE", $a_set["question_type"]); - $this->tpl->setVariable("AUTHOR", $a_set["author"]); - $this->tpl->setVariable("POOL", $a_set["pool"]); - - if($a_set["heading"]) - { - $this->tpl->setCurrentBlock("heading"); - $this->tpl->setVariable("TXT_HEADING", $a_set["heading"]); - $this->tpl->parseCurrentBlock(); - } - - if($a_set["block_id"]) - { - $this->tpl->setVariable("TITLE_INDENT", " style=\"padding-left:30px\""); - } - - if(!$this->read_only) - { - // checkbox - $this->tpl->setCurrentBlock("checkable"); - $this->tpl->setVariable("QUESTION_ID", $a_set["id"]); - $this->tpl->parseCurrentBlock(); - - if($a_set["block_id"]) - { - $this->tpl->setVariable("CHECKABLE_INDENT", " style=\"padding-left:30px\""); - } - - // order - if($a_set["position"]) - { - $this->tpl->setCurrentBlock("order"); - if(!$a_set["block_id"]) - { - $this->tpl->setVariable("ORDER_NAME", "order[q_".$a_set["id"]."]"); - } - else - { - $this->tpl->setVariable("ORDER_NAME", "block_order[".$a_set["block_id"]."][".$a_set["id"]."]"); - } - $this->tpl->setVariable("ORDER_VALUE", $a_set["position"]); - $this->tpl->parseCurrentBlock(); - if($a_set["block_id"]) - { - $this->tpl->setVariable("ORDER_INDENT", " style=\"padding-left:30px\""); - } - } - - // obligatory - $checked = $a_set["obligatory"] ? " checked=\"checked\"" : ""; - $obligatory = ""; - } - else if($a_set["obligatory"]) - { - $obligatory = "\"".$lng-txt("question_obligatory"). - "\" title=\"".$lng->txt("question_obligatory")."\" />"; - } - $this->tpl->setVariable("OBLIGATORY", $obligatory); - break; - - case "heading": - if(!$this->read_only) - { - // checkbox - $this->tpl->setCurrentBlock("checkable"); - $this->tpl->setVariable("QUESTION_ID", $a_set["id"]); - $this->tpl->parseCurrentBlock(); - if($a_set["in_block"]) - { - $this->tpl->setVariable("CHECKABLE_INDENT", " style=\"padding-left:30px\""); - $this->tpl->setVariable("TITLE_INDENT", " style=\"padding-left:30px\""); - } - } - - $this->tpl->setVariable("TYPE", $lng->txt("heading")); - break; - } - - if(!$this->read_only) - { - $this->tpl->setCurrentBlock("actions"); - - $ilCtrl->setParameter($this->parent_obj, "q_id", $a_set["id"]); - - include_once "Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"; - $list = new ilAdvancedSelectionListGUI(); - $list->setId($a_set["id"]); - $list->setListTitle($lng->txt("actions")); - if($a_set["url"]) - { - $list->addItem($lng->txt("edit"), "", $a_set["url"]); - } - - if($a_set["heading"]) - { - $list->addItem($lng->txt("survey_edit_heading"), "", - $ilCtrl->getLinkTarget($this->parent_obj, "editheading")); - - $list->addItem($lng->txt("survey_delete_heading"), "", - $ilCtrl->getLinkTarget($this->parent_obj, "removeheading")); - } - else if($a_set["type"] == "question") - { - $list->addItem($lng->txt("add_heading"), "", - $ilCtrl->getLinkTarget($this->parent_obj, "addHeading")); - } - - $this->tpl->setVariable("ACTION", $list->getHTML()); - - $ilCtrl->setParameter($this->parent_obj, "q_id", ""); - - $this->tpl->parseCurrentBlock(); - - // #11186 - if($a_set["url"]) - { - $this->tpl->setCurrentBlock("title_edit"); - $this->tpl->setVariable("TITLE", $a_set["title"]); - $this->tpl->setVariable("URL_TITLE", $a_set["url"]); - $this->tpl->parseCurrentBlock(); - } - else - { - $this->tpl->setCurrentBlock("title_static"); - $this->tpl->setVariable("TITLE", $a_set["title"]); - $this->tpl->parseCurrentBlock(); - } - } - else - { - $this->tpl->setCurrentBlock("title_static"); - $this->tpl->setVariable("TITLE", $a_set["title"]); - $this->tpl->parseCurrentBlock(); - } - } -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @ingroup ModulesSurvey + */ +class ilSurveyQuestionTableGUI extends ilTable2GUI +{ + protected $object; + protected $read_only; + + /** + * Constructor + * + * @param object $a_parent_obj parent gui object + * @param string $a_parent_cmd parent default command + */ + public function __construct($a_parent_obj, $a_parent_cmd, ilObjSurvey $a_survey_obj, $a_read_only = false) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->object = $a_survey_obj; + $this->read_only = (bool) $a_read_only; + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setId("il_svy_qst"); + $this->setLimit(9999); + + // $this->setTitle($lng->txt("survey_questions")); + + if (!$this->read_only) { + // command dropdown + if (!array_key_exists("move_questions", $_SESSION)) { + $this->addMultiCommand("createQuestionblock", $lng->txt("define_questionblock")); + $this->addMultiCommand("unfoldQuestionblock", $lng->txt("unfold")); + $this->addMultiCommand("removeQuestions", $lng->txt("remove_question")); + $this->addMultiCommand("moveQuestions", $lng->txt("move")); + $this->addMultiCommand("copyQuestionsToPool", $lng->txt("survey_copy_questions_to_pool")); + } else { + $this->addMultiCommand("insertQuestionsBefore", $lng->txt("insert_before")); + $this->addMultiCommand("insertQuestionsAfter", $lng->txt("insert_after")); + } + + // right side + $this->addCommandButton("saveObligatory", $lng->txt("save_obligatory_state")); + + $this->setSelectAllCheckbox("id[]"); + $this->addColumn("", ""); + $this->addColumn($lng->txt("survey_order"), ""); + } + + $this->addColumn($lng->txt("title"), ""); + $this->addColumn($lng->txt("obligatory"), ""); + $this->addColumn($lng->txt("description"), ""); + $this->addColumn($lng->txt("type"), ""); + $this->addColumn($lng->txt("author"), ""); + $this->addColumn($lng->txt("survey_question_pool"), ""); + + if (!$this->read_only) { + $this->addColumn("", ""); + } + + $this->setDefaultOrderField("order"); + $this->setDefaultOrderDirection("asc"); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.il_svy_svy_question_table.html", "Modules/Survey"); + + $this->setShowRowsSelector(true); + + $this->importData(); + } + + /** + * Import data from DB + */ + protected function importData() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $survey_questions = $this->object->getSurveyQuestions(); + if (count($survey_questions) > 0) { + include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"; + $questiontypes = ilObjSurveyQuestionPool::_getQuestiontypes(); + + $questionpools = $this->object->getQuestionpoolTitles(true); + + $table_data = array(); + $last_questionblock_id = $position = $block_position = 0; + foreach ($survey_questions as $question_id => $data) { + // question block + if ($data["questionblock_id"] > 0 && + $data["questionblock_id"] != $last_questionblock_id) { + $id = "qb_" . $data["questionblock_id"]; + + $table_data[$id] = array("id" => $id, + "type" => "block", + "title" => $data["questionblock_title"]); + + if (!$this->read_only) { + // order + if (sizeof($survey_questions) > 1) { + $position += 10; + $table_data[$id]["position"] = $position; + } + + $ilCtrl->setParameter($this->parent_obj, "bl_id", $data["questionblock_id"]); + $table_data[$id]["url"] = $ilCtrl->getLinkTarget($this->parent_obj, "editQuestionblock"); + $ilCtrl->setParameter($this->parent_obj, "bl_id", ""); + } + + $block_position = 0; + } + + // question + + $id = $data["question_id"]; + + $table_data[$id] = array("id" => $id, + "type" => "question", + "heading" => $data["heading"], + "title" => $data["title"], + "description" => $data["description"], + "author" => $data["author"], + "block_id" => $data["questionblock_id"], + "obligatory" => (bool) $data["obligatory"]); + + // question type + foreach ($questiontypes as $trans => $typedata) { + if (strcmp($typedata["type_tag"], $data["type_tag"]) == 0) { + $table_data[$id]["question_type"] = $trans; + } + } + + // pool title + if ($data["original_id"]) { + $original_fi = SurveyQuestion::lookupObjFi($data["original_id"]); + if (isset($questionpools[$original_fi])) { + $table_data[$id]["pool"] = $questionpools[$original_fi]; + } else { + // #11186 + $table_data[$id]["pool"] = $this->lng->txt("status_no_permission"); + } + } + + if (!$this->read_only) { + if ($data["obj_fi"] > 0) { + // edit url + $q_gui = $data["type_tag"] . "GUI"; + $ilCtrl->setParameterByClass($q_gui, "q_id", $id); + $table_data[$id]["url"] = $ilCtrl->getLinkTargetByClass($q_gui, "editQuestion") . + $ilCtrl->setParameterByClass($q_gui, "q_id", ""); + } + + // order + if (sizeof($survey_questions) > 1) { + if (!$data["questionblock_id"]) { + $position += 10; + $table_data[$id]["position"] = $position; + } else { + $block_position += 10; + $table_data[$id]["position"] = $block_position; + } + } + } + + $last_questionblock_id = $data["questionblock_id"]; + } + } + + $this->setData($table_data); + } + + /** + * Fill table row + * + * @param array $a_set data array + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + switch ($a_set["type"]) { + case "block": + if (!$this->read_only) { + // checkbox + $this->tpl->setCurrentBlock("checkable"); + $this->tpl->setVariable("QUESTION_ID", $a_set["id"]); + $this->tpl->parseCurrentBlock(); + + // order + if ($a_set["position"]) { + $this->tpl->setCurrentBlock("order"); + $this->tpl->setVariable("ORDER_NAME", "order[" . $a_set["id"] . "]"); + $this->tpl->setVariable("ORDER_VALUE", $a_set["position"]); + $this->tpl->parseCurrentBlock(); + } + } + + $this->tpl->setVariable("TYPE", $lng->txt("questionblock")); + break; + + case "question": + $this->tpl->setVariable("DESCRIPTION", $a_set["description"]); + $this->tpl->setVariable("TYPE", $a_set["question_type"]); + $this->tpl->setVariable("AUTHOR", $a_set["author"]); + $this->tpl->setVariable("POOL", $a_set["pool"]); + + if ($a_set["heading"]) { + $this->tpl->setCurrentBlock("heading"); + $this->tpl->setVariable("TXT_HEADING", $a_set["heading"]); + $this->tpl->parseCurrentBlock(); + } + + if ($a_set["block_id"]) { + $this->tpl->setVariable("TITLE_INDENT", " style=\"padding-left:30px\""); + } + + if (!$this->read_only) { + // checkbox + $this->tpl->setCurrentBlock("checkable"); + $this->tpl->setVariable("QUESTION_ID", $a_set["id"]); + $this->tpl->parseCurrentBlock(); + + if ($a_set["block_id"]) { + $this->tpl->setVariable("CHECKABLE_INDENT", " style=\"padding-left:30px\""); + } + + // order + if ($a_set["position"]) { + $this->tpl->setCurrentBlock("order"); + if (!$a_set["block_id"]) { + $this->tpl->setVariable("ORDER_NAME", "order[q_" . $a_set["id"] . "]"); + } else { + $this->tpl->setVariable("ORDER_NAME", "block_order[" . $a_set["block_id"] . "][" . $a_set["id"] . "]"); + } + $this->tpl->setVariable("ORDER_VALUE", $a_set["position"]); + $this->tpl->parseCurrentBlock(); + if ($a_set["block_id"]) { + $this->tpl->setVariable("ORDER_INDENT", " style=\"padding-left:30px\""); + } + } + + // obligatory + $checked = $a_set["obligatory"] ? " checked=\"checked\"" : ""; + $obligatory = ""; + } elseif ($a_set["obligatory"]) { + $obligatory = "\""txt("question_obligatory") . + "\" title=\"" . $lng->txt("question_obligatory") . "\" />"; + } + $this->tpl->setVariable("OBLIGATORY", $obligatory); + break; + + case "heading": + if (!$this->read_only) { + // checkbox + $this->tpl->setCurrentBlock("checkable"); + $this->tpl->setVariable("QUESTION_ID", $a_set["id"]); + $this->tpl->parseCurrentBlock(); + if ($a_set["in_block"]) { + $this->tpl->setVariable("CHECKABLE_INDENT", " style=\"padding-left:30px\""); + $this->tpl->setVariable("TITLE_INDENT", " style=\"padding-left:30px\""); + } + } + + $this->tpl->setVariable("TYPE", $lng->txt("heading")); + break; + } + + if (!$this->read_only) { + $this->tpl->setCurrentBlock("actions"); + + $ilCtrl->setParameter($this->parent_obj, "q_id", $a_set["id"]); + + include_once "Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"; + $list = new ilAdvancedSelectionListGUI(); + $list->setId($a_set["id"]); + $list->setListTitle($lng->txt("actions")); + if ($a_set["url"]) { + $list->addItem($lng->txt("edit"), "", $a_set["url"]); + } + + if ($a_set["heading"]) { + $list->addItem( + $lng->txt("survey_edit_heading"), + "", + $ilCtrl->getLinkTarget($this->parent_obj, "editheading") + ); + + $list->addItem( + $lng->txt("survey_delete_heading"), + "", + $ilCtrl->getLinkTarget($this->parent_obj, "removeheading") + ); + } elseif ($a_set["type"] == "question") { + $list->addItem( + $lng->txt("add_heading"), + "", + $ilCtrl->getLinkTarget($this->parent_obj, "addHeading") + ); + } + + $this->tpl->setVariable("ACTION", $list->getHTML()); + + $ilCtrl->setParameter($this->parent_obj, "q_id", ""); + + $this->tpl->parseCurrentBlock(); + + // #11186 + if ($a_set["url"]) { + $this->tpl->setCurrentBlock("title_edit"); + $this->tpl->setVariable("TITLE", $a_set["title"]); + $this->tpl->setVariable("URL_TITLE", $a_set["url"]); + $this->tpl->parseCurrentBlock(); + } else { + $this->tpl->setCurrentBlock("title_static"); + $this->tpl->setVariable("TITLE", $a_set["title"]); + $this->tpl->parseCurrentBlock(); + } + } else { + $this->tpl->setCurrentBlock("title_static"); + $this->tpl->setVariable("TITLE", $a_set["title"]); + $this->tpl->parseCurrentBlock(); + } + } +} diff --git a/Modules/Survey/classes/class.ilSurveySkill.php b/Modules/Survey/classes/class.ilSurveySkill.php index a83b45413ec7fb33b6785444ef24001ced215a00..2f052a3763c5d93ed0157349787470f7c48950ab 100644 --- a/Modules/Survey/classes/class.ilSurveySkill.php +++ b/Modules/Survey/classes/class.ilSurveySkill.php @@ -7,433 +7,411 @@ * * @author Alex Killing * @version $Id$ - * @ingroup + * @ingroup */ class ilSurveySkill { - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; - protected $q_skill = array(); // key: question id, value: - // array("base_skill_id" =>..., "tref_id" =>... ) - /** - * @var ilLogger - */ - protected $log; + protected $q_skill = array(); // key: question id, value: + // array("base_skill_id" =>..., "tref_id" =>... ) + /** + * @var ilLogger + */ + protected $log; - /** - * Constructor - * - * @param - * @return - */ - function __construct(ilObjSurvey $a_survey) - { - global $DIC; + /** + * Constructor + * + * @param + * @return + */ + public function __construct(ilObjSurvey $a_survey) + { + global $DIC; - $this->db = $DIC->database(); - $this->survey = $a_survey; - $this->read(); - $this->log = ilLoggerFactory::getLogger("svy"); - } - - /** - * Read - * - * @param - * @return - */ - function read() - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT * FROM svy_quest_skill ". - " WHERE survey_id = ".$ilDB->quote($this->survey->getId(), "integer") - ); - - include_once("./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"); - - while ($rec = $ilDB->fetchAssoc($set)) - { - if (SurveyQuestion::_questionExists($rec["q_id"])) - { - $this->q_skill[$rec["q_id"]] = array("q_id" => $rec["q_id"], - "base_skill_id" => $rec["base_skill_id"], - "tref_id" => $rec["tref_id"]); - } - } - } - - /** - * Get skill for question - * - * @param int $a_question_id question id - * @return array skill array - */ - function getSkillForQuestion($a_question_id) - { - if (isset($this->q_skill[$a_question_id])) - { - return $this->q_skill[$a_question_id]; - } - return false; - } - - /** - * Get questions for skill - * - * @param - * @return - */ - function getQuestionsForSkill($a_base_skill_id, $a_tref_id) - { - $q_ids = array(); - foreach ($this->q_skill as $q_id => $s) - { - if ($s["base_skill_id"] == $a_base_skill_id && - $s["tref_id"] == $a_tref_id) - { - $q_ids[] = $q_id; - } - } - return $q_ids; - } - - - /** - * Add survey question to skill assignment - * - * @param int $a_question_id question id - * @param int $a_base_skill_id base skill id - * @param int $a_tref_id skill template reference id (0, if no template involved) - */ - function addQuestionSkillAssignment($a_question_id, $a_base_skill_id, $a_tref_id) - { - $ilDB = $this->db; - - $ilDB->replace("svy_quest_skill", - array("q_id" => array("integer", $a_question_id)), - array( - "survey_id" => array("integer", $this->survey->getId()), - "base_skill_id" => array("integer", $a_base_skill_id), - "tref_id" => array("integer", $a_tref_id) - ) - ); - $this->q_skill[$a_question_id] = array("q_id" => $a_question_id, - "base_skill_id" => $a_base_skill_id, - "tref_id" => $a_tref_id); - - // add usage - include_once("./Services/Skill/classes/class.ilSkillUsage.php"); - ilSkillUsage::setUsage($this->survey->getId(), $a_base_skill_id, $a_tref_id); + $this->db = $DIC->database(); + $this->survey = $a_survey; + $this->read(); + $this->log = ilLoggerFactory::getLogger("svy"); + } + + /** + * Read + * + * @param + * @return + */ + public function read() + { + $ilDB = $this->db; + + $set = $ilDB->query( + "SELECT * FROM svy_quest_skill " . + " WHERE survey_id = " . $ilDB->quote($this->survey->getId(), "integer") + ); + + include_once("./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"); + + while ($rec = $ilDB->fetchAssoc($set)) { + if (SurveyQuestion::_questionExists($rec["q_id"])) { + $this->q_skill[$rec["q_id"]] = array("q_id" => $rec["q_id"], + "base_skill_id" => $rec["base_skill_id"], + "tref_id" => $rec["tref_id"]); + } + } + } + + /** + * Get skill for question + * + * @param int $a_question_id question id + * @return array skill array + */ + public function getSkillForQuestion($a_question_id) + { + if (isset($this->q_skill[$a_question_id])) { + return $this->q_skill[$a_question_id]; + } + return false; + } + + /** + * Get questions for skill + * + * @param + * @return + */ + public function getQuestionsForSkill($a_base_skill_id, $a_tref_id) + { + $q_ids = array(); + foreach ($this->q_skill as $q_id => $s) { + if ($s["base_skill_id"] == $a_base_skill_id && + $s["tref_id"] == $a_tref_id) { + $q_ids[] = $q_id; + } + } + return $q_ids; + } + + + /** + * Add survey question to skill assignment + * + * @param int $a_question_id question id + * @param int $a_base_skill_id base skill id + * @param int $a_tref_id skill template reference id (0, if no template involved) + */ + public function addQuestionSkillAssignment($a_question_id, $a_base_skill_id, $a_tref_id) + { + $ilDB = $this->db; + + $ilDB->replace( + "svy_quest_skill", + array("q_id" => array("integer", $a_question_id)), + array( + "survey_id" => array("integer", $this->survey->getId()), + "base_skill_id" => array("integer", $a_base_skill_id), + "tref_id" => array("integer", $a_tref_id) + ) + ); + $this->q_skill[$a_question_id] = array("q_id" => $a_question_id, + "base_skill_id" => $a_base_skill_id, + "tref_id" => $a_tref_id); + + // add usage + include_once("./Services/Skill/classes/class.ilSkillUsage.php"); + ilSkillUsage::setUsage($this->survey->getId(), $a_base_skill_id, $a_tref_id); + } + + /** + * Remove question skill assignment + * + * @param int $a_question_id question id + */ + public function removeQuestionSkillAssignment($a_question_id) + { + $ilDB = $this->db; + + // read skills that are assigned to the quesiton + $set = $ilDB->query( + "SELECT * FROM svy_quest_skill " . + " WHERE q_id = " . $ilDB->quote($a_question_id, "integer") + ); + $skills = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $skills[] = array("skill_id" => $rec["base_skill_id"], + "tref_id" => $rec["tref_id"]); + } + + // remove assignment of question + $ilDB->manipulate( + "DELETE FROM svy_quest_skill WHERE " . + " q_id = " . $ilDB->quote($a_question_id, "integer") + ); + unset($this->q_skill[$a_question_id]); + + $this->removeUsagesOfSkills($skills); + } - } - - /** - * Remove question skill assignment - * - * @param int $a_question_id question id - */ - function removeQuestionSkillAssignment($a_question_id) - { - $ilDB = $this->db; - - // read skills that are assigned to the quesiton - $set = $ilDB->query("SELECT * FROM svy_quest_skill ". - " WHERE q_id = ".$ilDB->quote($a_question_id, "integer") - ); - $skills = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $skills[] = array("skill_id" => $rec["base_skill_id"], - "tref_id" => $rec["tref_id"]); - } - - // remove assignment of question - $ilDB->manipulate("DELETE FROM svy_quest_skill WHERE ". - " q_id = ".$ilDB->quote($a_question_id, "integer") - ); - unset($this->q_skill[$a_question_id]); - - $this->removeUsagesOfSkills($skills); - } + /** + * Remove question skill assignment + * + * @param int $a_question_id question id + */ + public static function handleQuestionDeletion($a_question_id, $a_obj_id) + { + global $DIC; - /** - * Remove question skill assignment - * - * @param int $a_question_id question id - */ - static function handleQuestionDeletion($a_question_id, $a_obj_id) - { - global $DIC; + $ilDB = $DIC->database(); + if (ilObject::_lookupType($a_obj_id) == "svy") { + // mantis 11691 + include_once './Modules/Survey/classes/class.ilObjSurvey.php'; + $svy = new ilObjSurvey($a_obj_id, false); + $svy_skill = new ilSurveySkill($svy); + $svy_skill->removeQuestionSkillAssignment($a_question_id); + } + } + + /** + * Remove usages of skills + * + * This function checks, if the skills are really not in use anymore + * @param array array of arrays with keys "skill_id" and "tref_id" + */ + public function removeUsagesOfSkills($a_skills) + { + $used_skills = array(); + foreach ($a_skills as $skill) { + if ($this->isSkillAssignedToQuestion($skill["skill_id"], $skill["tref_id"])) { + $used_skills[] = $skill["skill_id"] . ":" . $skill["tref_id"]; + } + } + reset($a_skills); + + // now remove all usages that have been confirmed + include_once("./Services/Skill/classes/class.ilSkillUsage.php"); + //var_dump($a_skills); + //var_dump($used_skills); exit; + foreach ($a_skills as $skill) { + if (!in_array($skill["skill_id"] . ":" . $skill["tref_id"], $used_skills)) { + ilSkillUsage::setUsage($this->survey->getId(), $skill["skill_id"], $skill["tref_id"], false); + } + } + } + + /** + * Is skill assigned to any question? + * + * @param + * @return + */ + public function isSkillAssignedToQuestion($a_skill_id, $a_tref_id) + { + $ilDB = $this->db; + + $set = $ilDB->query( + "SELECT * FROM svy_quest_skill " . + " WHERE base_skill_id = " . $ilDB->quote($a_skill_id, "integer") . + " AND tref_id = " . $ilDB->quote($a_tref_id, "integer") . + " AND survey_id = " . $ilDB->quote($this->survey->getId(), "integer") + ); + if ($rec = $ilDB->fetchAssoc($set)) { + return true; + } + return false; + } + - $ilDB = $DIC->database(); - if (ilObject::_lookupType($a_obj_id) == "svy") - { - // mantis 11691 - include_once './Modules/Survey/classes/class.ilObjSurvey.php'; - $svy = new ilObjSurvey($a_obj_id, false); - $svy_skill = new ilSurveySkill($svy); - $svy_skill->removeQuestionSkillAssignment($a_question_id); - } - } - - /** - * Remove usages of skills - * - * This function checks, if the skills are really not in use anymore - * @param array array of arrays with keys "skill_id" and "tref_id" - */ - function removeUsagesOfSkills($a_skills) - { - $used_skills = array(); - foreach ($a_skills as $skill) - { - if ($this->isSkillAssignedToQuestion($skill["skill_id"], $skill["tref_id"])) - { - $used_skills[] = $skill["skill_id"].":".$skill["tref_id"]; - } - } - reset($a_skills); - - // now remove all usages that have been confirmed - include_once("./Services/Skill/classes/class.ilSkillUsage.php"); -//var_dump($a_skills); -//var_dump($used_skills); exit; - foreach ($a_skills as $skill) - { - if (!in_array($skill["skill_id"].":".$skill["tref_id"], $used_skills)) - { - ilSkillUsage::setUsage($this->survey->getId(), $skill["skill_id"], $skill["tref_id"], false); - } - } - } - - /** - * Is skill assigned to any question? - * - * @param - * @return - */ - function isSkillAssignedToQuestion($a_skill_id, $a_tref_id) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT * FROM svy_quest_skill ". - " WHERE base_skill_id = ".$ilDB->quote($a_skill_id, "integer"). - " AND tref_id = ".$ilDB->quote($a_tref_id, "integer"). - " AND survey_id = ".$ilDB->quote($this->survey->getId(), "integer") - ); - if ($rec = $ilDB->fetchAssoc($set)) - { - return true; - } - return false; - } - + /** + * Get skill for question + * + * @param int $a_question_id question id + * @return array skill array + */ + public function getAllAssignedSkillsAsOptions() + { + $skills = array(); + include_once("./Services/Skill/classes/class.ilBasicSkill.php"); + foreach ($this->q_skill as $sk) { + $skills[$sk["base_skill_id"] . ":" . $sk["tref_id"]] = + ilBasicSkill::_lookupTitle($sk["base_skill_id"]); + } + return $skills; + } - /** - * Get skill for question - * - * @param int $a_question_id question id - * @return array skill array - */ - function getAllAssignedSkillsAsOptions() - { - $skills = array(); - include_once("./Services/Skill/classes/class.ilBasicSkill.php"); - foreach ($this->q_skill as $sk) - { - $skills[$sk["base_skill_id"].":".$sk["tref_id"]] = - ilBasicSkill::_lookupTitle($sk["base_skill_id"]); - } - return $skills; - } + /** + * Determine skill levels for appraisee + * + * @param $a_appraisee_id int user id of appraisee + * @return array array with lots of information + */ + public function determineSkillLevelsForAppraisee($a_appraisee_id, $a_self_eval = false) + { + $skills = array(); - /** - * Determine skill levels for appraisee - * - * @param $a_appraisee_id int user id of appraisee - * @return array array with lots of information - */ - function determineSkillLevelsForAppraisee($a_appraisee_id, $a_self_eval = false) - { - $skills = array(); + // get all skills + $opts = $this->getAllAssignedSkillsAsOptions(); + foreach ($opts as $k => $title) { + $k = explode(":", $k); + + $bs = new ilBasicSkill((int) $k[0]); + $ld = $bs->getLevelData(); + + $skills[] = array( + "base_skill_id" => (int) $k[0], + "tref_id" => (int) $k[1], + "skill_title" => $title, + "level_data" => $ld + ); + } - // get all skills - $opts = $this->getAllAssignedSkillsAsOptions(); - foreach ($opts as $k => $title) - { - $k = explode(":", $k); - - $bs = new ilBasicSkill((int) $k[0]); - $ld = $bs->getLevelData(); - - $skills[] = array( - "base_skill_id" => (int) $k[0], - "tref_id" => (int) $k[1], - "skill_title" => $title, - "level_data" => $ld - ); - } + if (!$a_self_eval) { + $finished_ids = $this->survey->getFinishedIdsForAppraiseeId($a_appraisee_id, true); + } else { + $finished_id = $this->survey->getFinishedIdForAppraiseeIdAndRaterId($a_appraisee_id, $a_appraisee_id); + if ($finished_id > 0) { + $finished_ids = array($finished_id); + } + } + + if (!sizeof($finished_ids)) { + $finished_ids = array(-1); + } - if (!$a_self_eval) - { - $finished_ids = $this->survey->getFinishedIdsForAppraiseeId($a_appraisee_id, true); - } - else - { - $finished_id = $this->survey->getFinishedIdForAppraiseeIdAndRaterId($a_appraisee_id, $a_appraisee_id); - if ($finished_id > 0) - { - $finished_ids = array($finished_id); - } - } - - if(!sizeof($finished_ids)) - { - $finished_ids = array(-1); - } + $results = $this->survey->getUserSpecificResults($finished_ids); + $this->log->debug("Finished IDS: " . print_r($finished_ids, true)); + foreach ($skills as $k => $s) { + $q_ids = $this->getQuestionsForSkill($s["base_skill_id"], $s["tref_id"]); + $this->log->debug("Skill: " . $s["base_skill_id"] . ":" . $s["tref_id"] . ", Questions: " . implode(",", $q_ids)); + $mean_sum = 0; + foreach ($q_ids as $q_id) { + $qmean = 0; + if (is_array($results[$q_id])) { + $cnt = 0; + $sum = 0; + foreach ($results[$q_id] as $uid => $answer) { // answer of user $uid for question $q_id + // $answer has the scale values as keys and the answer texts as values. + // In case of single choice this is an array with one key => value pair. + // For multiple choice questions (currently not supported for being used for competences) + // multiple elements may be in the array (in the future). + $scale_values = array_keys($answer); // scale values of the answer + $this->log->debug("User answer (scale values): " . print_r($scale_values, true)); + $sum += array_sum($scale_values); + $cnt += sizeof($scale_values); // nr of answers (always one in the case of single choice) + } + if ($cnt > 0) { + $qmean = $sum/$cnt; + } + $this->log->debug("MEAN: " . $qmean); + } + $mean_sum += $qmean; + $this->log->debug("MEAN SUM: " . $mean_sum); + } + $skills[$k]["mean_sum"] = $mean_sum; + + include_once("./Modules/Survey/classes/class.ilSurveySkillThresholds.php"); + $skthr = new ilSurveySkillThresholds($this->survey); + $thresholds = $skthr->getThresholds(); + foreach ($skills[$k]["level_data"] as $l) { + $t = $thresholds[$l["id"]][$s["tref_id"]]; + if ($t > 0 && $mean_sum >= $t) { + $skills[$k]["new_level"] = $l["title"]; + $skills[$k]["new_level_id"] = $l["id"]; + } + } + } + return $skills; + } + + + /** + * Determine max scales and questions + * + * @param + * @return + */ + public function determineMaxScale($a_base_skill, $a_tref_id = 0) + { + include_once("./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"); + include_once("./Modules/Survey/classes/class.ilSurveySkill.php"); + $ssk = new ilSurveySkill($this->survey); + $question_ids = $ssk->getQuestionsForSkill($a_base_skill, $a_tref_id); + $scale_sum = 0; + foreach ($question_ids as $q_id) { + $q = SurveyQuestion::_instanciateQuestion($q_id); + if (!is_object($q)) { + continue; + } + $cats = $q->getCategories(); + $max_scale = 0; + for ($i = 0; $i<= $cats->getCategoryCount(); $i++) { + $c = $cats->getCategory($i); + $n = $c->neutral; + $s = $c->scale; + if (!$c->neutral) { + if ($c->scale > $max_scale) { + $max_scale = $c->scale; + } + } + } + $scale_sum+= $max_scale; + } + + return $scale_sum; + } - $results = $this->survey->getUserSpecificResults($finished_ids); - $this->log->debug("Finished IDS: ".print_r($finished_ids, true)); - foreach ($skills as $k => $s) - { - $q_ids = $this->getQuestionsForSkill($s["base_skill_id"], $s["tref_id"]); - $this->log->debug("Skill: ".$s["base_skill_id"].":".$s["tref_id"].", Questions: ".implode(",",$q_ids)); - $mean_sum = 0; - foreach ($q_ids as $q_id) - { - $qmean = 0; - if (is_array($results[$q_id])) - { - $cnt = 0; - $sum = 0; - foreach ($results[$q_id] as $uid => $answer) // answer of user $uid for question $q_id - { - // $answer has the scale values as keys and the answer texts as values. - // In case of single choice this is an array with one key => value pair. - // For multiple choice questions (currently not supported for being used for competences) - // multiple elements may be in the array (in the future). - $scale_values = array_keys($answer); // scale values of the answer - $this->log->debug("User answer (scale values): ".print_r($scale_values, true)); - $sum += array_sum($scale_values); - $cnt += sizeof($scale_values); // nr of answers (always one in the case of single choice) - } - if ($cnt > 0) - { - $qmean = $sum/$cnt; - } - $this->log->debug("MEAN: ".$qmean); - } - $mean_sum += $qmean; - $this->log->debug("MEAN SUM: ".$mean_sum); - } - $skills[$k]["mean_sum"] = $mean_sum; - - include_once("./Modules/Survey/classes/class.ilSurveySkillThresholds.php"); - $skthr = new ilSurveySkillThresholds($this->survey); - $thresholds = $skthr->getThresholds(); - foreach ($skills[$k]["level_data"] as $l) - { - $t = $thresholds[$l["id"]][$s["tref_id"]]; - if ($t > 0 && $mean_sum >= $t) - { - $skills[$k]["new_level"] = $l["title"]; - $skills[$k]["new_level_id"] = $l["id"]; - } - } - } - return $skills; - } - - - /** - * Determine max scales and questions - * - * @param - * @return - */ - function determineMaxScale($a_base_skill, $a_tref_id = 0) - { - include_once("./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"); - include_once("./Modules/Survey/classes/class.ilSurveySkill.php"); - $ssk = new ilSurveySkill($this->survey); - $question_ids = $ssk->getQuestionsForSkill($a_base_skill, $a_tref_id); - $scale_sum = 0; - foreach ($question_ids as $q_id) - { - $q = SurveyQuestion::_instanciateQuestion($q_id); - if(!is_object($q)) - { - continue; - } - $cats = $q->getCategories(); - $max_scale = 0; - for($i = 0; $i<= $cats->getCategoryCount(); $i++) - { - $c = $cats->getCategory($i); - $n = $c->neutral; - $s = $c->scale; - if (!$c->neutral) - { - if ($c->scale > $max_scale) - { - $max_scale = $c->scale; - } - } - } - $scale_sum+= $max_scale; - } - - return $scale_sum; - } + /** + * Write appraisee skills + * + * @param int $user_id + */ + public function writeAppraiseeSkills($a_app_id) + { + // write raters evaluation + $new_levels = $this->determineSkillLevelsForAppraisee($a_app_id); + foreach ($new_levels as $nl) { + if ($nl["new_level_id"] > 0) { + ilBasicSkill::writeUserSkillLevelStatus( + $nl["new_level_id"], + $a_app_id, + $this->survey->getRefId(), + $nl["tref_id"], + ilBasicSkill::ACHIEVED, + true + ); + } + } - /** - * Write appraisee skills - * - * @param int $user_id - */ - function writeAppraiseeSkills($a_app_id) - { - // write raters evaluation - $new_levels = $this->determineSkillLevelsForAppraisee($a_app_id); - foreach ($new_levels as $nl) - { - if ($nl["new_level_id"] > 0) - { - ilBasicSkill::writeUserSkillLevelStatus($nl["new_level_id"], - $a_app_id, $this->survey->getRefId(), $nl["tref_id"], ilBasicSkill::ACHIEVED, true); - } - } - - // write self evaluation - $this->writeSelfEvalSkills($a_app_id); - } - - /** - * Write skills on self evaluation - * - * @param int $user_id - */ - public function writeSelfEvalSkills(int $user_id) - { - if ($user_id > 0 && in_array($this->survey->getMode(), [ilObjSurvey::MODE_SELF_EVAL, ilObjSurvey::MODE_360])) - { - $new_levels = $this->determineSkillLevelsForAppraisee($user_id, true); - foreach ($new_levels as $nl) - { - if ($nl["new_level_id"] > 0) - { - ilBasicSkill::writeUserSkillLevelStatus($nl["new_level_id"], - $user_id, $this->survey->getRefId(), $nl["tref_id"], ilBasicSkill::ACHIEVED, true, 1); - } - } - } - } + // write self evaluation + $this->writeSelfEvalSkills($a_app_id); + } + /** + * Write skills on self evaluation + * + * @param int $user_id + */ + public function writeSelfEvalSkills(int $user_id) + { + if ($user_id > 0 && in_array($this->survey->getMode(), [ilObjSurvey::MODE_SELF_EVAL, ilObjSurvey::MODE_360])) { + $new_levels = $this->determineSkillLevelsForAppraisee($user_id, true); + foreach ($new_levels as $nl) { + if ($nl["new_level_id"] > 0) { + ilBasicSkill::writeUserSkillLevelStatus( + $nl["new_level_id"], + $user_id, + $this->survey->getRefId(), + $nl["tref_id"], + ilBasicSkill::ACHIEVED, + true, + 1 + ); + } + } + } + } } - -?> diff --git a/Modules/Survey/classes/class.ilSurveySkillAssignmentTableGUI.php b/Modules/Survey/classes/class.ilSurveySkillAssignmentTableGUI.php index 9c3af9c460371b6489c6be99740ecd9b51696158..8ecbfadb34cf210eed410f42b44db4f49b2da4b0 100644 --- a/Modules/Survey/classes/class.ilSurveySkillAssignmentTableGUI.php +++ b/Modules/Survey/classes/class.ilSurveySkillAssignmentTableGUI.php @@ -14,152 +14,149 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilSurveySkillAssignmentTableGUI extends ilTable2GUI { - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_survey) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_survey) + { + 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->object = $a_survey; - include_once("./Modules/Survey/classes/class.ilSurveySkill.php"); - $this->skill_survey = new ilSurveySkill($a_survey); - - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $this->skill_tree = new ilSkillTree(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->getQuestions(); - //$this->setTitle($lng->txt("survey_questions_to_skill_ass")); - - $this->addColumn($this->lng->txt("question")); - $this->addColumn($this->lng->txt("survey_skill")); - $this->addColumn($this->lng->txt("actions")); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.svy_skill_ass_row.html", "Modules/Survey"); + $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->object = $a_survey; + include_once("./Modules/Survey/classes/class.ilSurveySkill.php"); + $this->skill_survey = new ilSurveySkill($a_survey); + + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $this->skill_tree = new ilSkillTree(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->getQuestions(); + //$this->setTitle($lng->txt("survey_questions_to_skill_ass")); + + $this->addColumn($this->lng->txt("question")); + $this->addColumn($this->lng->txt("survey_skill")); + $this->addColumn($this->lng->txt("actions")); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.svy_skill_ass_row.html", "Modules/Survey"); -// $this->addMultiCommand("", $lng->txt("")); + // $this->addMultiCommand("", $lng->txt("")); // $this->addCommandButton("", $lng->txt("")); - } - - /** - * Get questions - * - * @param - * @return - */ - function getQuestions() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $survey_questions = $this->object->getSurveyQuestions(); + } + + /** + * Get questions + * + * @param + * @return + */ + public function getQuestions() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $survey_questions = $this->object->getSurveyQuestions(); - if (count($survey_questions) > 0) - { - $table_data = array(); - $last_questionblock_id = $position = $block_position = 0; - foreach ($survey_questions as $question_id => $data) - { - // it is only possible to assign to a subset - // of question types: single choice(2) - $supported = false; - if (in_array($data["questiontype_fi"], array(2))) - { - $supported = true; - } + if (count($survey_questions) > 0) { + $table_data = array(); + $last_questionblock_id = $position = $block_position = 0; + foreach ($survey_questions as $question_id => $data) { + // it is only possible to assign to a subset + // of question types: single choice(2) + $supported = false; + if (in_array($data["questiontype_fi"], array(2))) { + $supported = true; + } - $id = $data["question_id"]; - - $table_data[$id] = array("id" => $id, - "type" => "question", - "supported" => $supported, - "heading" => $data["heading"], - "title" => $data["title"], - "description" => $data["description"], - "author" => $data["author"], - "obligatory" => (bool)$data["obligatory"]); + $id = $data["question_id"]; + + $table_data[$id] = array("id" => $id, + "type" => "question", + "supported" => $supported, + "heading" => $data["heading"], + "title" => $data["title"], + "description" => $data["description"], + "author" => $data["author"], + "obligatory" => (bool) $data["obligatory"]); + } + } + $this->setData($table_data); + } + + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; - } - } - $this->setData($table_data); - } - - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; + $ilCtrl->setParameter($this->parent_obj, "q_id", $a_set["id"]); - $ilCtrl->setParameter($this->parent_obj, "q_id", $a_set["id"]); - - if ($a_set["supported"]) - { - $this->tpl->setCurrentBlock("cmd"); - $this->tpl->setVariable("HREF_CMD", - $ilCtrl->getLinkTarget($this->parent_obj, - "assignSkillToQuestion")); - $this->tpl->setVariable("TXT_CMD", $lng->txt("survey_assign_competence")); - $this->tpl->parseCurrentBlock(); - - if ($s = $this->skill_survey->getSkillForQuestion($a_set["id"])) - { - $this->tpl->setCurrentBlock("cmd"); - $this->tpl->setVariable("HREF_CMD", - $ilCtrl->getLinkTarget($this->parent_obj, - "removeSkillFromQuestion")); - $this->tpl->setVariable("TXT_CMD", $lng->txt("survey_remove_competence")); - $this->tpl->parseCurrentBlock(); - - include_once("./Services/Skill/classes/class.ilBasicSkill.php"); - $this->tpl->setVariable("COMPETENCE", - ilBasicSkill::_lookupTitle($s["base_skill_id"], $s["tref_id"])); - - //var_dump($a_set); - $path = $this->skill_tree->getSkillTreePath($s["base_skill_id"], $s["tref_id"]); - $path_nodes = array(); - foreach ($path as $p) - { - if ($p["child"] > 1 && $p["skill_id"] != $s["base_skill_id"]) - { - $path_nodes[] = ilBasicSkill::_lookupTitle($p["skill_id"], $p["tref_id"]); - } - } - $this->tpl->setVariable("PATH", implode($path_nodes, " > ")); - $this->tpl->setVariable("COMP_ID", "comp_".$a_set["id"]); - - /*include_once("./Services/UIComponent/Tooltip/classes/class.ilTooltipGUI.php"); - ilTooltipGUI::addTooltip("comp_".$a_set["id"], - ilBasicSkill::_lookupDescription($s["base_skill_id"]));*/ - } - } - else - { - $this->tpl->setVariable("NOT_SUPPORTED", $lng->txt("svy_skl_comp_assignm_not_supported")); - } - - $this->tpl->setVariable("QUESTION_TITLE", $a_set["title"]); - - $ilCtrl->setParameter($this->parent_obj, "q_id", ""); - - } + if ($a_set["supported"]) { + $this->tpl->setCurrentBlock("cmd"); + $this->tpl->setVariable( + "HREF_CMD", + $ilCtrl->getLinkTarget( + $this->parent_obj, + "assignSkillToQuestion" + ) + ); + $this->tpl->setVariable("TXT_CMD", $lng->txt("survey_assign_competence")); + $this->tpl->parseCurrentBlock(); + + if ($s = $this->skill_survey->getSkillForQuestion($a_set["id"])) { + $this->tpl->setCurrentBlock("cmd"); + $this->tpl->setVariable( + "HREF_CMD", + $ilCtrl->getLinkTarget( + $this->parent_obj, + "removeSkillFromQuestion" + ) + ); + $this->tpl->setVariable("TXT_CMD", $lng->txt("survey_remove_competence")); + $this->tpl->parseCurrentBlock(); + + include_once("./Services/Skill/classes/class.ilBasicSkill.php"); + $this->tpl->setVariable( + "COMPETENCE", + ilBasicSkill::_lookupTitle($s["base_skill_id"], $s["tref_id"]) + ); + //var_dump($a_set); + $path = $this->skill_tree->getSkillTreePath($s["base_skill_id"], $s["tref_id"]); + $path_nodes = array(); + foreach ($path as $p) { + if ($p["child"] > 1 && $p["skill_id"] != $s["base_skill_id"]) { + $path_nodes[] = ilBasicSkill::_lookupTitle($p["skill_id"], $p["tref_id"]); + } + } + $this->tpl->setVariable("PATH", implode($path_nodes, " > ")); + $this->tpl->setVariable("COMP_ID", "comp_" . $a_set["id"]); + + /*include_once("./Services/UIComponent/Tooltip/classes/class.ilTooltipGUI.php"); + ilTooltipGUI::addTooltip("comp_".$a_set["id"], + ilBasicSkill::_lookupDescription($s["base_skill_id"]));*/ + } + } else { + $this->tpl->setVariable("NOT_SUPPORTED", $lng->txt("svy_skl_comp_assignm_not_supported")); + } + + $this->tpl->setVariable("QUESTION_TITLE", $a_set["title"]); + + $ilCtrl->setParameter($this->parent_obj, "q_id", ""); + } } -?> diff --git a/Modules/Survey/classes/class.ilSurveySkillChangesTableGUI.php b/Modules/Survey/classes/class.ilSurveySkillChangesTableGUI.php index 8f796a16ddd118211231207795c1249f9ffe3d5d..44a4f61db51870a82e8f55683a121a43af9e4095 100644 --- a/Modules/Survey/classes/class.ilSurveySkillChangesTableGUI.php +++ b/Modules/Survey/classes/class.ilSurveySkillChangesTableGUI.php @@ -16,77 +16,72 @@ include_once("./Services/Skill/classes/class.ilBasicSkill.php"); */ class ilSurveySkillChangesTableGUI extends ilTable2GUI { - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_survey, $a_appraisee) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_survey, $a_appraisee) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->survey = $a_survey; - $this->appraisee = $a_appraisee; - - include_once("./Modules/Survey/classes/class.ilSurveySkill.php"); - include_once("./Modules/Survey/classes/class.ilSurveySkillThresholds.php"); - $this->survey_skill = new ilSurveySkill($a_survey); - $this->thresholds = new ilSurveySkillThresholds($a_survey); - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->getSkillLevelsForAppraisee(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->survey = $a_survey; + $this->appraisee = $a_appraisee; + + include_once("./Modules/Survey/classes/class.ilSurveySkill.php"); + include_once("./Modules/Survey/classes/class.ilSurveySkillThresholds.php"); + $this->survey_skill = new ilSurveySkill($a_survey); + $this->thresholds = new ilSurveySkillThresholds($a_survey); + + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->getSkillLevelsForAppraisee(); - $this->setTitle($lng->txt("")); - $this->setLimit(9999); - $this->disable("footer"); + $this->setTitle($lng->txt("")); + $this->setLimit(9999); + $this->disable("footer"); - $this->addColumn($this->lng->txt("survey_skill")); - $this->addColumn($this->lng->txt("survey_sum_of_means")); - $this->addColumn($this->lng->txt("survey_reached_level")); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.survey_skill_change.html", "Modules/Survey"); + $this->addColumn($this->lng->txt("survey_skill")); + $this->addColumn($this->lng->txt("survey_sum_of_means")); + $this->addColumn($this->lng->txt("survey_reached_level")); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.survey_skill_change.html", "Modules/Survey"); - //$this->addMultiCommand("", $lng->txt("")); - //$this->addCommandButton("", $lng->txt("")); - } - - /** - * Get Skills - * - * @param - * @return - */ - function getSkillLevelsForAppraisee() - { - $sskill = new ilSurveySkill($this->survey); + //$this->addMultiCommand("", $lng->txt("")); + //$this->addCommandButton("", $lng->txt("")); + } + + /** + * Get Skills + * + * @param + * @return + */ + public function getSkillLevelsForAppraisee() + { + $sskill = new ilSurveySkill($this->survey); - if($this->survey->get360Mode()) - { - $new_levels = $sskill->determineSkillLevelsForAppraisee($this->appraisee["user_id"]); - } - else //Svy self evaluation mode. - { - $new_levels = $sskill->determineSkillLevelsForAppraisee(ilObjUser::getUserIdByLogin($this->appraisee["login"]), true); - } - - $this->setData($new_levels); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; -//var_dump($a_set); - $this->tpl->setVariable("SKILL", $a_set["skill_title"]); - $this->tpl->setVariable("MEAN_SUM", $a_set["mean_sum"]); - $this->tpl->setVariable("NEW_LEVEL", $a_set["new_level"]); - } + if ($this->survey->get360Mode()) { + $new_levels = $sskill->determineSkillLevelsForAppraisee($this->appraisee["user_id"]); + } else { //Svy self evaluation mode. + $new_levels = $sskill->determineSkillLevelsForAppraisee(ilObjUser::getUserIdByLogin($this->appraisee["login"]), true); + } + $this->setData($new_levels); + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + //var_dump($a_set); + $this->tpl->setVariable("SKILL", $a_set["skill_title"]); + $this->tpl->setVariable("MEAN_SUM", $a_set["mean_sum"]); + $this->tpl->setVariable("NEW_LEVEL", $a_set["new_level"]); + } } -?> diff --git a/Modules/Survey/classes/class.ilSurveySkillDeterminationGUI.php b/Modules/Survey/classes/class.ilSurveySkillDeterminationGUI.php index 6ad57bb5d96755ee23cd32e6ae2776bfee9e302d..9f3483bc8f9944d3bc570edc849dc64065b5ea92 100644 --- a/Modules/Survey/classes/class.ilSurveySkillDeterminationGUI.php +++ b/Modules/Survey/classes/class.ilSurveySkillDeterminationGUI.php @@ -12,130 +12,128 @@ */ class ilSurveySkillDeterminationGUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilTemplate + */ + protected $tpl; - /** - * @var ilToolbarGUI - */ - protected $toolbar; + /** + * @var ilToolbarGUI + */ + protected $toolbar; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * Constructor - * - * @param object $a_survey - */ - function __construct(ilObjSurvey $a_survey) - { - global $DIC; + /** + * Constructor + * + * @param object $a_survey + */ + public function __construct(ilObjSurvey $a_survey) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->tpl = $DIC["tpl"]; - $this->toolbar = $DIC->toolbar(); - $this->lng = $DIC->language(); - $this->survey = $a_survey; - } - - /** - * Execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - - $cmd = $ilCtrl->getCmd("listSkillChanges"); - - //$ilCtrl->saveParameter($this, array("sk_id", "tref_id")); - - if (in_array($cmd, array("listSkillChanges", "writeSkills"))) - { - $this->$cmd(); - } - } - - /** - * List skill changes - */ - function listSkillChanges() - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $lng = $this->lng; - $ilCtrl = $this->ctrl; + $this->ctrl = $DIC->ctrl(); + $this->tpl = $DIC["tpl"]; + $this->toolbar = $DIC->toolbar(); + $this->lng = $DIC->language(); + $this->survey = $a_survey; + } + + /** + * Execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $cmd = $ilCtrl->getCmd("listSkillChanges"); + + //$ilCtrl->saveParameter($this, array("sk_id", "tref_id")); + + if (in_array($cmd, array("listSkillChanges", "writeSkills"))) { + $this->$cmd(); + } + } + + /** + * List skill changes + */ + public function listSkillChanges() + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $lng = $this->lng; + $ilCtrl = $this->ctrl; - include_once("./Modules/Survey/classes/class.ilSurveySkillChangesTableGUI.php"); + include_once("./Modules/Survey/classes/class.ilSurveySkillChangesTableGUI.php"); -// $ilToolbar->addButton($lng->txt("survey_write_skills"), -// $ilCtrl->getLinkTarget($this, "writeSkills")); - if($this->survey->get360Mode()) - { - $apps = $this->survey->getAppraiseesData(); - } - else // Mode self evaluation, No Appraisee and Rater involved. - { - $apps = $this->survey->getSurveyParticipants(); - } - $ctpl = new ilTemplate("tpl.svy_skill_list_changes.html", true, true, "Modules/Survey"); - foreach ($apps as $app) - { - $changes_table = new ilSurveySkillChangesTableGUI($this, "listSkillChanges", - $this->survey, $app); - - $ctpl->setCurrentBlock("appraisee"); - $ctpl->setVariable("LASTNAME", $app["lastname"]); - $ctpl->setVariable("FIRSTNAME", $app["firstname"]); - - $ctpl->setVariable("CHANGES_TABLE", $changes_table->getHTML()); - - $ctpl->parseCurrentBlock(); - } - - $tpl->setContent($ctpl->get()); - } - - /** - * Write skills - * - * @param - * @return - */ - function writeSkills() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; -return; - include_once("./Modules/Survey/classes/class.ilSurveySkill.php"); - $sskill = new ilSurveySkill($this->survey); - $apps = $this->survey->getAppraiseesData(); - $ctpl = new ilTemplate("tpl.svy_skill_list_changes.html", true, true, "Modules/Survey"); - foreach ($apps as $app) - { - $new_levels = $sskill->determineSkillLevelsForAppraisee($app["user_id"]); - foreach ($new_levels as $nl) - { - if ($nl["new_level_id"] > 0) - { - ilBasicSkill::writeUserSkillLevelStatus($nl["new_level_id"], - $app["user_id"], $this->survey->getRefId(), $nl["tref_id"], ilBasicSkill::ACHIEVED); - } - } - } - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "listSkillChanges"); - } - + // $ilToolbar->addButton($lng->txt("survey_write_skills"), + // $ilCtrl->getLinkTarget($this, "writeSkills")); + if ($this->survey->get360Mode()) { + $apps = $this->survey->getAppraiseesData(); + } else { // Mode self evaluation, No Appraisee and Rater involved. + $apps = $this->survey->getSurveyParticipants(); + } + $ctpl = new ilTemplate("tpl.svy_skill_list_changes.html", true, true, "Modules/Survey"); + foreach ($apps as $app) { + $changes_table = new ilSurveySkillChangesTableGUI( + $this, + "listSkillChanges", + $this->survey, + $app + ); + + $ctpl->setCurrentBlock("appraisee"); + $ctpl->setVariable("LASTNAME", $app["lastname"]); + $ctpl->setVariable("FIRSTNAME", $app["firstname"]); + + $ctpl->setVariable("CHANGES_TABLE", $changes_table->getHTML()); + + $ctpl->parseCurrentBlock(); + } + + $tpl->setContent($ctpl->get()); + } + + /** + * Write skills + * + * @param + * @return + */ + public function writeSkills() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + return; + include_once("./Modules/Survey/classes/class.ilSurveySkill.php"); + $sskill = new ilSurveySkill($this->survey); + $apps = $this->survey->getAppraiseesData(); + $ctpl = new ilTemplate("tpl.svy_skill_list_changes.html", true, true, "Modules/Survey"); + foreach ($apps as $app) { + $new_levels = $sskill->determineSkillLevelsForAppraisee($app["user_id"]); + foreach ($new_levels as $nl) { + if ($nl["new_level_id"] > 0) { + ilBasicSkill::writeUserSkillLevelStatus( + $nl["new_level_id"], + $app["user_id"], + $this->survey->getRefId(), + $nl["tref_id"], + ilBasicSkill::ACHIEVED + ); + } + } + } + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "listSkillChanges"); + } } - -?> diff --git a/Modules/Survey/classes/class.ilSurveySkillExplorer.php b/Modules/Survey/classes/class.ilSurveySkillExplorer.php index 037c304a12eb3cefe73e818fa1cc3f0acc6fe0aa..59dc3c124d5b82a0d33d740f315a94f0d33bceb4 100644 --- a/Modules/Survey/classes/class.ilSurveySkillExplorer.php +++ b/Modules/Survey/classes/class.ilSurveySkillExplorer.php @@ -16,238 +16,231 @@ require_once("./Services/UIComponent/Explorer/classes/class.ilExplorer.php"); class ilSurveySkillExplorer extends ilExplorer { - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * id of root folder - * @var int root folder id - * @access private - */ - var $root_id; - var $slm_obj; - var $output; - - /** - * Constructor - * @access public - * @param string scriptname - * @param int user_id - */ - function __construct($a_target, $a_templates = false) - { - global $DIC; - - $this->user = $DIC->user(); - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->templates = $a_templates; - - parent::__construct($a_target); - - $this->setFilterMode(IL_FM_POSITIVE); - $this->addFilter("skrt"); - $this->addFilter("skll"); - $this->addFilter("scat"); -// $this->addFilter("sktr"); - $this->setTitleLength(999); - - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $this->tree = new ilSkillTree(); - $this->root_id = $this->tree->readRootId(); - - $this->setSessionExpandVariable("skpexpand"); - $this->checkPermissions(false); - $this->setPostSort(false); - - $this->setOrderColumn("order_nr"); -// $this->textwidth = 200; - - $this->force_open_path = array(); - - $this->all_nodes = $this->tree->getSubTree($this->tree->getNodeData($this->root_id)); - foreach ($this->all_nodes as $n) - { - $this->node[$n["child"]] = $n; - $this->child_nodes[$n["parent"]][] = $n; - $this->parent[$n["child"]] = $n["parent"]; -//echo "-$k-"; var_dump($n); - } - -// $this->buildSelectableTree($this->root_id); - } - - /** - * Build selectable tree - * - * @param - * @return - */ -/* - function buildSelectableTree($a_node_id) - { - if (ilSkillTreeNode::_lookupSelfEvaluation($a_node_id)) - { - $this->selectable[$a_node_id] = true; - $this->selectable[$this->parent[$a_node_id]] = true; - } - foreach ($this->getOriginalChildsOfNode($a_node_id) as $n) - { - $this->buildSelectableTree($n["child"]); - } - if ($this->selectable[$a_node_id] && - !ilSkillTreeNode::_lookupDraft($a_node_id)) - { - $this->selectable_child_nodes[$this->node[$a_node_id]["parent"]][] = - $this->node[$a_node_id]; - } - }*/ - - - /** - * set force open path - */ - function setForceOpenPath($a_path) - { - $this->force_open_path = $a_path; - } - - - /** - * check if links for certain object type are activated - * - * @param string $a_type object type - * - * @return boolean true if linking is activated - */ - function isClickable($a_type, $a_obj_id = 0) - { - $ilUser = $this->user; - if ($a_type == "skll") - { - return true; - } - return false; - } - - /** - * build link target - */ - function buildLinkTarget($a_node_id, $a_type) - { - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameterByClass("ilsurveyskillgui", "obj_id", $a_node_id); - $ret = $ilCtrl->getLinkTargetByClass("ilsurveyskillgui", "selectSkillForQuestion"); - $ilCtrl->setParameterByClass("ilsurveyskillgui", "obj_id", $_GET["obj_id"]); - - return $ret; - } - - /** - * standard implementation for title, may be overwritten by derived classes - */ - function buildTitle($a_title, $a_id, $a_type) - { - $lng = $this->lng; - - if ($a_type == "sktr") - { - include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); - $tid = ilSkillTemplateReference::_lookupTemplateId($a_id); -// $a_title.= " (".ilSkillTreeNode::_lookupTitle($tid).")"; - } - -/* if (ilSkillTreeNode::_lookupSelfEvaluation($a_id)) - { - $a_title.= " [".$lng->txt("add")."]"; - }*/ - - return $a_title; - } - - /** - * force expansion of node - */ - function forceExpanded($a_obj_id) - { - if (in_array($a_obj_id, $this->force_open_path)) - { - return true; - } - return false; - } - - /** - * Get frame target - */ - function buildFrameTarget($a_type, $a_child = 0, $a_obj_id = 0) - { - return ""; - } - - /** - * Get maximum tree depth - * - * @param - * @return - */ -/* function getMaximumTreeDepth() - { - $this->tree->getMaximumDepth(); - }*/ - - /** - * Get childs of node (selectable tree) - * - * @param int $a_parent_id parent id - * @return array childs - */ -/* - function getChildsOfNode($a_parent_id) - { - if (is_array($this->selectable_child_nodes[$a_parent_id])) - { - $childs = $this->selectable_child_nodes[$a_parent_id]; - $childs = ilUtil::sortArray($childs, "order_nr", "asc", true); - return $childs; - } - return array(); - }*/ - - /** - * Get original childs of node (whole tree) - * - * @param int $a_parent_id parent id - * @return array childs - */ -/* function getOriginalChildsOfNode($a_parent_id) - { - if (is_array($this->child_nodes[$a_parent_id])) - { - return $this->child_nodes[$a_parent_id]; - } - return array(); - }*/ - - /** - * get image path (may be overwritten by derived classes) - */ - function getImage($a_name, $a_type = "", $a_obj_id = "") - { - if (in_array($a_type, array("sktr"))) - { - return ilUtil::getImagePath("icon_skll_s.gif"); - } - return ilUtil::getImagePath($a_name); - } - + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * id of root folder + * @var int root folder id + * @access private + */ + public $root_id; + public $slm_obj; + public $output; + + /** + * Constructor + * @access public + * @param string scriptname + * @param int user_id + */ + public function __construct($a_target, $a_templates = false) + { + global $DIC; + + $this->user = $DIC->user(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->templates = $a_templates; + + parent::__construct($a_target); + + $this->setFilterMode(IL_FM_POSITIVE); + $this->addFilter("skrt"); + $this->addFilter("skll"); + $this->addFilter("scat"); + // $this->addFilter("sktr"); + $this->setTitleLength(999); + + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $this->tree = new ilSkillTree(); + $this->root_id = $this->tree->readRootId(); + + $this->setSessionExpandVariable("skpexpand"); + $this->checkPermissions(false); + $this->setPostSort(false); + + $this->setOrderColumn("order_nr"); + // $this->textwidth = 200; + + $this->force_open_path = array(); + + $this->all_nodes = $this->tree->getSubTree($this->tree->getNodeData($this->root_id)); + foreach ($this->all_nodes as $n) { + $this->node[$n["child"]] = $n; + $this->child_nodes[$n["parent"]][] = $n; + $this->parent[$n["child"]] = $n["parent"]; + //echo "-$k-"; var_dump($n); + } + + // $this->buildSelectableTree($this->root_id); + } + + /** + * Build selectable tree + * + * @param + * @return + */ + /* + function buildSelectableTree($a_node_id) + { + if (ilSkillTreeNode::_lookupSelfEvaluation($a_node_id)) + { + $this->selectable[$a_node_id] = true; + $this->selectable[$this->parent[$a_node_id]] = true; + } + foreach ($this->getOriginalChildsOfNode($a_node_id) as $n) + { + $this->buildSelectableTree($n["child"]); + } + if ($this->selectable[$a_node_id] && + !ilSkillTreeNode::_lookupDraft($a_node_id)) + { + $this->selectable_child_nodes[$this->node[$a_node_id]["parent"]][] = + $this->node[$a_node_id]; + } + }*/ + + + /** + * set force open path + */ + public function setForceOpenPath($a_path) + { + $this->force_open_path = $a_path; + } + + + /** + * check if links for certain object type are activated + * + * @param string $a_type object type + * + * @return boolean true if linking is activated + */ + public function isClickable($a_type, $a_obj_id = 0) + { + $ilUser = $this->user; + if ($a_type == "skll") { + return true; + } + return false; + } + + /** + * build link target + */ + public function buildLinkTarget($a_node_id, $a_type) + { + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameterByClass("ilsurveyskillgui", "obj_id", $a_node_id); + $ret = $ilCtrl->getLinkTargetByClass("ilsurveyskillgui", "selectSkillForQuestion"); + $ilCtrl->setParameterByClass("ilsurveyskillgui", "obj_id", $_GET["obj_id"]); + + return $ret; + } + + /** + * standard implementation for title, may be overwritten by derived classes + */ + public function buildTitle($a_title, $a_id, $a_type) + { + $lng = $this->lng; + + if ($a_type == "sktr") { + include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); + $tid = ilSkillTemplateReference::_lookupTemplateId($a_id); + // $a_title.= " (".ilSkillTreeNode::_lookupTitle($tid).")"; + } + + /* if (ilSkillTreeNode::_lookupSelfEvaluation($a_id)) + { + $a_title.= " [".$lng->txt("add")."]"; + }*/ + + return $a_title; + } + + /** + * force expansion of node + */ + public function forceExpanded($a_obj_id) + { + if (in_array($a_obj_id, $this->force_open_path)) { + return true; + } + return false; + } + + /** + * Get frame target + */ + public function buildFrameTarget($a_type, $a_child = 0, $a_obj_id = 0) + { + return ""; + } + + /** + * Get maximum tree depth + * + * @param + * @return + */ + /* function getMaximumTreeDepth() + { + $this->tree->getMaximumDepth(); + }*/ + + /** + * Get childs of node (selectable tree) + * + * @param int $a_parent_id parent id + * @return array childs + */ + /* + function getChildsOfNode($a_parent_id) + { + if (is_array($this->selectable_child_nodes[$a_parent_id])) + { + $childs = $this->selectable_child_nodes[$a_parent_id]; + $childs = ilUtil::sortArray($childs, "order_nr", "asc", true); + return $childs; + } + return array(); + }*/ + + /** + * Get original childs of node (whole tree) + * + * @param int $a_parent_id parent id + * @return array childs + */ + /* function getOriginalChildsOfNode($a_parent_id) + { + if (is_array($this->child_nodes[$a_parent_id])) + { + return $this->child_nodes[$a_parent_id]; + } + return array(); + }*/ + + /** + * get image path (may be overwritten by derived classes) + */ + public function getImage($a_name, $a_type = "", $a_obj_id = "") + { + if (in_array($a_type, array("sktr"))) { + return ilUtil::getImagePath("icon_skll_s.gif"); + } + return ilUtil::getImagePath($a_name); + } } -?> diff --git a/Modules/Survey/classes/class.ilSurveySkillGUI.php b/Modules/Survey/classes/class.ilSurveySkillGUI.php index 565a26a72f5ab44c3896b47f8f10c10d20e603ea..42cb8986e63c4a6a2e9b366e62f0409bb766dff5 100644 --- a/Modules/Survey/classes/class.ilSurveySkillGUI.php +++ b/Modules/Survey/classes/class.ilSurveySkillGUI.php @@ -12,203 +12,207 @@ */ class ilSurveySkillGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * Constructor - * - * @param object $a_survey - */ - function __construct(ilObjSurvey $a_survey) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->tpl = $DIC["tpl"]; - $this->user = $DIC->user(); - $this->lng = $DIC->language(); - $this->tabs = $DIC->tabs(); - $this->survey = $a_survey; - } - - /** - * Execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - - $cmd = $ilCtrl->getCmd(); - $next_class = $ilCtrl->getNextClass(); - - switch ($next_class) - { - case 'ilsurveyskillthresholdsgui': - $this->setSubTabs("skill_thresholds"); - include_once("./Modules/Survey/classes/class.ilSurveySkillThresholdsGUI.php"); - $gui = new ilSurveySkillThresholdsGUI($this->survey); - $ilCtrl->forwardCommand($gui); - break; - - default: - if (in_array($cmd, array("listQuestionAssignment", - "assignSkillToQuestion", "selectSkillForQuestion", - "removeSkillFromQuestion"))) - { - $this->setSubTabs("survey_skill_assign"); - $this->$cmd(); - } - break; - } - } - - /** - * List question to skill assignment - */ - function listQuestionAssignment() - { - $tpl = $this->tpl; - - include_once("./Modules/Survey/classes/class.ilSurveySkillAssignmentTableGUI.php"); - $tab = new ilSurveySkillAssignmentTableGUI($this, "listQuestionAssignment", - $this->survey); - $tpl->setContent($tab->getHTML()); - } - - /** - * Assign skill to question - */ - function assignSkillToQuestion() - { - $ilUser = $this->user; - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilTabs = $this->tabs; - - $ilCtrl->saveParameter($this, "q_id"); - - - include_once("./Services/Skill/classes/class.ilSkillSelectorGUI.php"); - $sel = new ilSkillSelectorGUI($this, "assignSkillToQuestion", $this, "selectSkillForQuestion"); - if (!$sel->handleCommand()) - { - $tpl->setContent($sel->getHTML()); - } - -return; - /* - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $skill_tree = new ilSkillTree(); - - require_once ("./Modules/Survey/classes/class.ilSurveySkillExplorer.php"); - $exp = new ilSurveySkillExplorer($ilCtrl->getLinkTarget($this, "assignSkillToQuestion")); - $exp->setTargetGet("obj_id"); - - $exp->setExpandTarget($ilCtrl->getLinkTarget($this, "assignSkillToQuestion")); - - if ($_GET["skpexpand"] == "") - { - $expanded = $skill_tree->readRootId(); - } - else - { - $expanded = $_GET["skpexpand"]; - } - - $exp->setExpand($expanded); - // build html-output - $exp->setOutput(0); - $output = $exp->getOutput(); - - // asynchronous output - if ($ilCtrl->isAsynch()) - { - echo $output; exit; - } - - $tpl->setContent($output); */ - } - - /** - * Select skill for question - */ - function selectSkillForQuestion() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - include_once("./Modules/Survey/classes/class.ilSurveySkill.php"); - $skill_survey = new ilSurveySkill($this->survey); - $skill_id_parts = explode(":", $_GET["selected_skill"]); - $skill_survey->addQuestionSkillAssignment((int) $_GET["q_id"], - (int) $skill_id_parts[0], (int) $skill_id_parts[1]); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - - $ilCtrl->redirect($this, "listQuestionAssignment"); - } - - /** - * Remove skill from question - */ - function removeSkillFromQuestion() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - include_once("./Modules/Survey/classes/class.ilSurveySkill.php"); - $skill_survey = new ilSurveySkill($this->survey); - $skill_survey->removeQuestionSkillAssignment((int) $_GET["q_id"]); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - - $ilCtrl->redirect($this, "listQuestionAssignment"); - } - - /** - * Set subtabs - * - * @param string $a_activate activate sub tab (ID) - */ - function setSubTabs($a_activate) - { - $ilTabs = $this->tabs; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $ilTabs->addSubtab("survey_skill_assign", - $lng->txt("survey_skill_assign"), - $ilCtrl->getLinkTargetByClass("ilsurveyskillgui", "listQuestionAssignment")); - - $ilTabs->addSubTab("skill_thresholds", - $lng->txt("survey_skill_thresholds"), - $ilCtrl->getLinkTargetByClass("ilsurveyskillthresholdsgui", "listCompetences")); - - $ilTabs->activateSubtab($a_activate); - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * Constructor + * + * @param object $a_survey + */ + public function __construct(ilObjSurvey $a_survey) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->tpl = $DIC["tpl"]; + $this->user = $DIC->user(); + $this->lng = $DIC->language(); + $this->tabs = $DIC->tabs(); + $this->survey = $a_survey; + } + + /** + * Execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $cmd = $ilCtrl->getCmd(); + $next_class = $ilCtrl->getNextClass(); + + switch ($next_class) { + case 'ilsurveyskillthresholdsgui': + $this->setSubTabs("skill_thresholds"); + include_once("./Modules/Survey/classes/class.ilSurveySkillThresholdsGUI.php"); + $gui = new ilSurveySkillThresholdsGUI($this->survey); + $ilCtrl->forwardCommand($gui); + break; + + default: + if (in_array($cmd, array("listQuestionAssignment", + "assignSkillToQuestion", "selectSkillForQuestion", + "removeSkillFromQuestion"))) { + $this->setSubTabs("survey_skill_assign"); + $this->$cmd(); + } + break; + } + } + + /** + * List question to skill assignment + */ + public function listQuestionAssignment() + { + $tpl = $this->tpl; + + include_once("./Modules/Survey/classes/class.ilSurveySkillAssignmentTableGUI.php"); + $tab = new ilSurveySkillAssignmentTableGUI( + $this, + "listQuestionAssignment", + $this->survey + ); + $tpl->setContent($tab->getHTML()); + } + + /** + * Assign skill to question + */ + public function assignSkillToQuestion() + { + $ilUser = $this->user; + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilTabs = $this->tabs; + + $ilCtrl->saveParameter($this, "q_id"); + + + include_once("./Services/Skill/classes/class.ilSkillSelectorGUI.php"); + $sel = new ilSkillSelectorGUI($this, "assignSkillToQuestion", $this, "selectSkillForQuestion"); + if (!$sel->handleCommand()) { + $tpl->setContent($sel->getHTML()); + } + + return; + /* + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $skill_tree = new ilSkillTree(); + + require_once ("./Modules/Survey/classes/class.ilSurveySkillExplorer.php"); + $exp = new ilSurveySkillExplorer($ilCtrl->getLinkTarget($this, "assignSkillToQuestion")); + $exp->setTargetGet("obj_id"); + + $exp->setExpandTarget($ilCtrl->getLinkTarget($this, "assignSkillToQuestion")); + + if ($_GET["skpexpand"] == "") + { + $expanded = $skill_tree->readRootId(); + } + else + { + $expanded = $_GET["skpexpand"]; + } + + $exp->setExpand($expanded); + // build html-output + $exp->setOutput(0); + $output = $exp->getOutput(); + + // asynchronous output + if ($ilCtrl->isAsynch()) + { + echo $output; exit; + } + + $tpl->setContent($output); */ + } + + /** + * Select skill for question + */ + public function selectSkillForQuestion() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + include_once("./Modules/Survey/classes/class.ilSurveySkill.php"); + $skill_survey = new ilSurveySkill($this->survey); + $skill_id_parts = explode(":", $_GET["selected_skill"]); + $skill_survey->addQuestionSkillAssignment( + (int) $_GET["q_id"], + (int) $skill_id_parts[0], + (int) $skill_id_parts[1] + ); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + + $ilCtrl->redirect($this, "listQuestionAssignment"); + } + + /** + * Remove skill from question + */ + public function removeSkillFromQuestion() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + include_once("./Modules/Survey/classes/class.ilSurveySkill.php"); + $skill_survey = new ilSurveySkill($this->survey); + $skill_survey->removeQuestionSkillAssignment((int) $_GET["q_id"]); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + + $ilCtrl->redirect($this, "listQuestionAssignment"); + } + + /** + * Set subtabs + * + * @param string $a_activate activate sub tab (ID) + */ + public function setSubTabs($a_activate) + { + $ilTabs = $this->tabs; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $ilTabs->addSubtab( + "survey_skill_assign", + $lng->txt("survey_skill_assign"), + $ilCtrl->getLinkTargetByClass("ilsurveyskillgui", "listQuestionAssignment") + ); + + $ilTabs->addSubTab( + "skill_thresholds", + $lng->txt("survey_skill_thresholds"), + $ilCtrl->getLinkTargetByClass("ilsurveyskillthresholdsgui", "listCompetences") + ); + + $ilTabs->activateSubtab($a_activate); + } } - -?> diff --git a/Modules/Survey/classes/class.ilSurveySkillTableGUI.php b/Modules/Survey/classes/class.ilSurveySkillTableGUI.php index eff3a00aeb6669cc339e44c0e0e7104ce31bfc79..1041ecc49a4e6bfbbcfe389879ab17bb89871c46 100644 --- a/Modules/Survey/classes/class.ilSurveySkillTableGUI.php +++ b/Modules/Survey/classes/class.ilSurveySkillTableGUI.php @@ -14,126 +14,119 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilSurveySkillTableGUI extends ilTable2GUI { - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_survey) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->survey = $a_survey; - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->getSkills(); - $this->setTitle($lng->txt("survey_competences")); - - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $this->skill_tree = new ilSkillTree(); - - include_once("./Modules/Survey/classes/class.ilSurveySkillThresholds.php"); - $this->skill_thres = new ilSurveySkillThresholds($a_survey); - $this->thresholds = $this->skill_thres->getThresholds(); - - $this->addColumn($this->lng->txt("survey_skill")); - $this->addColumn($this->lng->txt("survey_skill_nr_q")); - $this->addColumn($this->lng->txt("survey_skill_max_scale_points")); - $this->addColumn($this->lng->txt("survey_up_to_x_points")); - $this->addColumn($this->lng->txt("actions")); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.svy_skill_row.html", "Modules/Survey"); - - //$this->addMultiCommand("", $lng->txt("")); - //$this->addCommandButton("", $lng->txt("")); - } - - /** - * Get skills - * - * @param - * @return - */ - function getSkills() - { - include_once("./Modules/Survey/classes/class.ilSurveySkill.php"); - $sskill = new ilSurveySkill($this->survey); - $opts = $sskill->getAllAssignedSkillsAsOptions(); - $data = array(); - foreach ($opts as $k => $o) - { - $v = explode(":", $k); - - $question_ids = $sskill->getQuestionsForSkill($v[0], $v[1]); - $scale_sum = $sskill->determineMaxScale($v[0], $v[1]); - - $data[] = array("title" => ilBasicSkill::_lookupTitle($v[0], $v[1]), - "base_skill" => $v[0], - "tref_id" => $v[1], - "nr_of_q" => count($question_ids), - "scale_sum" => $scale_sum - ); - } - - $this->setData($data); - } - - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameter($this->parent_obj, "sk_id", $a_set["base_skill"]); - $ilCtrl->setParameter($this->parent_obj, "tref_id", $a_set["tref_id"]); - - $this->tpl->setVariable("COMPETENCE", - ilBasicSkill::_lookupTitle($a_set["base_skill"], $a_set["tref_id"])); - $path = $this->skill_tree->getSkillTreePath($a_set["base_skill"], $a_set["tref_id"]); - $path_nodes = array(); - foreach ($path as $p) - { - if ($p["child"] > 1 && $p["skill_id"] != $a_set["base_skill"]) - { - $path_nodes[] = ilBasicSkill::_lookupTitle($p["skill_id"], $p["tref_id"]); - } - } - $this->tpl->setVariable("PATH", implode($path_nodes, " > ")); - - - - $this->tpl->setVariable("NR_OF_QUESTIONS", $a_set["nr_of_q"]); - $this->tpl->setVariable("MAX_SCALE_POINTS", $a_set["scale_sum"]); - $this->tpl->setVariable("CMD", $ilCtrl->getLinkTarget($this->parent_obj, "listSkillThresholds")); - $this->tpl->setVariable("ACTION", $lng->txt("edit")); - - include_once("./Services/Skill/classes/class.ilBasicSkill.php"); - $bs = new ilBasicSkill($a_set["base_skill"]); - $ld = $bs->getLevelData(); - foreach ($ld as $l) - { - $this->tpl->setCurrentBlock("points"); - $this->tpl->setVariable("LEV", $l["title"]); - - $tr = $this->thresholds[$l["id"]][$a_set["tref_id"]]; - if ((int) $tr != 0) - { - $this->tpl->setVariable("THRESHOLD", (int) $tr); - } - else - { - $this->tpl->setVariable("THRESHOLD", ""); - } - $this->tpl->parseCurrentBlock(); - } - } - + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_survey) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->survey = $a_survey; + + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->getSkills(); + $this->setTitle($lng->txt("survey_competences")); + + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $this->skill_tree = new ilSkillTree(); + + include_once("./Modules/Survey/classes/class.ilSurveySkillThresholds.php"); + $this->skill_thres = new ilSurveySkillThresholds($a_survey); + $this->thresholds = $this->skill_thres->getThresholds(); + + $this->addColumn($this->lng->txt("survey_skill")); + $this->addColumn($this->lng->txt("survey_skill_nr_q")); + $this->addColumn($this->lng->txt("survey_skill_max_scale_points")); + $this->addColumn($this->lng->txt("survey_up_to_x_points")); + $this->addColumn($this->lng->txt("actions")); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.svy_skill_row.html", "Modules/Survey"); + + //$this->addMultiCommand("", $lng->txt("")); + //$this->addCommandButton("", $lng->txt("")); + } + + /** + * Get skills + * + * @param + * @return + */ + public function getSkills() + { + include_once("./Modules/Survey/classes/class.ilSurveySkill.php"); + $sskill = new ilSurveySkill($this->survey); + $opts = $sskill->getAllAssignedSkillsAsOptions(); + $data = array(); + foreach ($opts as $k => $o) { + $v = explode(":", $k); + + $question_ids = $sskill->getQuestionsForSkill($v[0], $v[1]); + $scale_sum = $sskill->determineMaxScale($v[0], $v[1]); + + $data[] = array("title" => ilBasicSkill::_lookupTitle($v[0], $v[1]), + "base_skill" => $v[0], + "tref_id" => $v[1], + "nr_of_q" => count($question_ids), + "scale_sum" => $scale_sum + ); + } + + $this->setData($data); + } + + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameter($this->parent_obj, "sk_id", $a_set["base_skill"]); + $ilCtrl->setParameter($this->parent_obj, "tref_id", $a_set["tref_id"]); + + $this->tpl->setVariable( + "COMPETENCE", + ilBasicSkill::_lookupTitle($a_set["base_skill"], $a_set["tref_id"]) + ); + $path = $this->skill_tree->getSkillTreePath($a_set["base_skill"], $a_set["tref_id"]); + $path_nodes = array(); + foreach ($path as $p) { + if ($p["child"] > 1 && $p["skill_id"] != $a_set["base_skill"]) { + $path_nodes[] = ilBasicSkill::_lookupTitle($p["skill_id"], $p["tref_id"]); + } + } + $this->tpl->setVariable("PATH", implode($path_nodes, " > ")); + + + + $this->tpl->setVariable("NR_OF_QUESTIONS", $a_set["nr_of_q"]); + $this->tpl->setVariable("MAX_SCALE_POINTS", $a_set["scale_sum"]); + $this->tpl->setVariable("CMD", $ilCtrl->getLinkTarget($this->parent_obj, "listSkillThresholds")); + $this->tpl->setVariable("ACTION", $lng->txt("edit")); + + include_once("./Services/Skill/classes/class.ilBasicSkill.php"); + $bs = new ilBasicSkill($a_set["base_skill"]); + $ld = $bs->getLevelData(); + foreach ($ld as $l) { + $this->tpl->setCurrentBlock("points"); + $this->tpl->setVariable("LEV", $l["title"]); + + $tr = $this->thresholds[$l["id"]][$a_set["tref_id"]]; + if ((int) $tr != 0) { + $this->tpl->setVariable("THRESHOLD", (int) $tr); + } else { + $this->tpl->setVariable("THRESHOLD", ""); + } + $this->tpl->parseCurrentBlock(); + } + } } -?> diff --git a/Modules/Survey/classes/class.ilSurveySkillThresholds.php b/Modules/Survey/classes/class.ilSurveySkillThresholds.php index c771b922a88ce92e0dfeae3001cb07922c9c9257..726a37618114f40b72a2d252b95491511cb11013 100644 --- a/Modules/Survey/classes/class.ilSurveySkillThresholds.php +++ b/Modules/Survey/classes/class.ilSurveySkillThresholds.php @@ -11,78 +11,76 @@ */ class ilSurveySkillThresholds { - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; - - /** - * Constructor - * - * @param - * @return - */ - function __construct(ilObjSurvey $a_survey) - { - global $DIC; + + /** + * Constructor + * + * @param + * @return + */ + public function __construct(ilObjSurvey $a_survey) + { + global $DIC; - $this->db = $DIC->database(); - $this->survey = $a_survey; - $this->read(); - } - - /** - * Read - * - * @param - * @return - */ - function read() - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT * FROM svy_skill_threshold ". - " WHERE survey_id = ".$ilDB->quote($this->survey->getId(), "integer") - ); - while ($rec = $ilDB->fetchAssoc($set)) - { - $this->threshold[$rec['level_id']][$rec['tref_id']] = - $rec['threshold']; - } - } + $this->db = $DIC->database(); + $this->survey = $a_survey; + $this->read(); + } + + /** + * Read + * + * @param + * @return + */ + public function read() + { + $ilDB = $this->db; + + $set = $ilDB->query( + "SELECT * FROM svy_skill_threshold " . + " WHERE survey_id = " . $ilDB->quote($this->survey->getId(), "integer") + ); + while ($rec = $ilDB->fetchAssoc($set)) { + $this->threshold[$rec['level_id']][$rec['tref_id']] = + $rec['threshold']; + } + } - /** - * Get thresholds - * - * @param - * @return - */ - function getThresholds() - { - return $this->threshold; - } - - /** - * Write threshold - * - * @param - * @return - */ - function writeThreshold($a_base_skill_id, $a_tref_id, $a_level_id, $a_threshold) - { - $ilDB = $this->db; - - $ilDB->replace("svy_skill_threshold", - array("survey_id" => array("integer", $this->survey->getId()), - "base_skill_id" => array("integer", (int) $a_base_skill_id), - "tref_id" => array("integer", (int) $a_tref_id), - "level_id" => array("integer", (int) $a_level_id) - ), - array("threshold" => array("integer", (int) $a_threshold)) - ); - } - + /** + * Get thresholds + * + * @param + * @return + */ + public function getThresholds() + { + return $this->threshold; + } + + /** + * Write threshold + * + * @param + * @return + */ + public function writeThreshold($a_base_skill_id, $a_tref_id, $a_level_id, $a_threshold) + { + $ilDB = $this->db; + + $ilDB->replace( + "svy_skill_threshold", + array("survey_id" => array("integer", $this->survey->getId()), + "base_skill_id" => array("integer", (int) $a_base_skill_id), + "tref_id" => array("integer", (int) $a_tref_id), + "level_id" => array("integer", (int) $a_level_id) + ), + array("threshold" => array("integer", (int) $a_threshold)) + ); + } } - -?> diff --git a/Modules/Survey/classes/class.ilSurveySkillThresholdsGUI.php b/Modules/Survey/classes/class.ilSurveySkillThresholdsGUI.php index 43615cd9987acdd8189d888dddffa093c00bb202..40d4b16c3687b70498ed36f722d0a1bfc8659a16 100644 --- a/Modules/Survey/classes/class.ilSurveySkillThresholdsGUI.php +++ b/Modules/Survey/classes/class.ilSurveySkillThresholdsGUI.php @@ -12,146 +12,151 @@ */ class ilSurveySkillThresholdsGUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilTemplate + */ + protected $tpl; - /** - * @var ilToolbarGUI - */ - protected $toolbar; + /** + * @var ilToolbarGUI + */ + protected $toolbar; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilTabsGUI - */ - protected $tabs; + /** + * @var ilTabsGUI + */ + protected $tabs; - /** - * Constructor - * - * @param object $a_survey - */ - function __construct(ilObjSurvey $a_survey) - { - global $DIC; + /** + * Constructor + * + * @param object $a_survey + */ + public function __construct(ilObjSurvey $a_survey) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->tpl = $DIC["tpl"]; - $this->toolbar = $DIC->toolbar(); - $this->lng = $DIC->language(); - $this->tabs = $DIC->tabs(); - $this->survey = $a_survey; - } - - /** - * Execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - - $cmd = $ilCtrl->getCmd(); - - $ilCtrl->saveParameter($this, array("sk_id", "tref_id")); - - if (in_array($cmd, array("listCompetences", "listSkillThresholds", "selectSkill", - "saveThresholds"))) - { - $this->$cmd(); - } - } - - /** - * List competences - * - * @param - * @return - */ - function listCompetences() - { - $tpl = $this->tpl; - - include_once("./Modules/Survey/classes/class.ilSurveySkillTableGUI.php"); - $tab = new ilSurveySkillTableGUI($this, "listCompetences", $this->survey); - $tpl->setContent($tab->getHTML()); - } - - - /** - * List skill thresholds - */ - function listSkillThresholds() - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($lng->txt("svy_back"), - $ilCtrl->getLinkTarget($this, "listCompetences")); - - include_once("./Modules/Survey/classes/class.ilSurveySkillThresholdsTableGUI.php"); - $tab = new ilSurveySkillThresholdsTableGUI($this, "listSkillThresholds", - $this->survey, (int) $_GET["sk_id"], (int) $_GET["tref_id"]); - $tpl->setContent($tab->getHTML()); - } - - /** - * Select skill - * - * @param - * @return - */ - function selectSkill() - { - $ilCtrl = $this->ctrl; - - $o = explode(":", $_POST["skill"]); - $ilCtrl->setParameter($this, "sk_id", (int) $o[0]); - $ilCtrl->setParameter($this, "tref_id", (int) $o[1]); - $ilCtrl->redirect($this, "listSkillThresholds"); - } - - /** - * Save Thresholds - * - * @param - * @return - */ - function saveThresholds() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - include_once("./Modules/Survey/classes/class.ilSurveySkillThresholds.php"); - $thres = new ilSurveySkillThresholds($this->survey); + $this->ctrl = $DIC->ctrl(); + $this->tpl = $DIC["tpl"]; + $this->toolbar = $DIC->toolbar(); + $this->lng = $DIC->language(); + $this->tabs = $DIC->tabs(); + $this->survey = $a_survey; + } + + /** + * Execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $cmd = $ilCtrl->getCmd(); + + $ilCtrl->saveParameter($this, array("sk_id", "tref_id")); + + if (in_array($cmd, array("listCompetences", "listSkillThresholds", "selectSkill", + "saveThresholds"))) { + $this->$cmd(); + } + } + + /** + * List competences + * + * @param + * @return + */ + public function listCompetences() + { + $tpl = $this->tpl; + + include_once("./Modules/Survey/classes/class.ilSurveySkillTableGUI.php"); + $tab = new ilSurveySkillTableGUI($this, "listCompetences", $this->survey); + $tpl->setContent($tab->getHTML()); + } + + + /** + * List skill thresholds + */ + public function listSkillThresholds() + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $lng->txt("svy_back"), + $ilCtrl->getLinkTarget($this, "listCompetences") + ); + + include_once("./Modules/Survey/classes/class.ilSurveySkillThresholdsTableGUI.php"); + $tab = new ilSurveySkillThresholdsTableGUI( + $this, + "listSkillThresholds", + $this->survey, + (int) $_GET["sk_id"], + (int) $_GET["tref_id"] + ); + $tpl->setContent($tab->getHTML()); + } + + /** + * Select skill + * + * @param + * @return + */ + public function selectSkill() + { + $ilCtrl = $this->ctrl; + + $o = explode(":", $_POST["skill"]); + $ilCtrl->setParameter($this, "sk_id", (int) $o[0]); + $ilCtrl->setParameter($this, "tref_id", (int) $o[1]); + $ilCtrl->redirect($this, "listSkillThresholds"); + } + + /** + * Save Thresholds + * + * @param + * @return + */ + public function saveThresholds() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + include_once("./Modules/Survey/classes/class.ilSurveySkillThresholds.php"); + $thres = new ilSurveySkillThresholds($this->survey); - if (is_array($_POST["threshold"])) - { - foreach ($_POST["threshold"] as $l => $t) - { - $thres->writeThreshold((int) $_GET["sk_id"], - (int) $_GET["tref_id"], (int) $l, (int) $t); - } - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), 1); - } - - $ilCtrl->redirect($this, "listSkillThresholds"); - } - + if (is_array($_POST["threshold"])) { + foreach ($_POST["threshold"] as $l => $t) { + $thres->writeThreshold( + (int) $_GET["sk_id"], + (int) $_GET["tref_id"], + (int) $l, + (int) $t + ); + } + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), 1); + } + + $ilCtrl->redirect($this, "listSkillThresholds"); + } } - -?> diff --git a/Modules/Survey/classes/class.ilSurveySkillThresholdsTableGUI.php b/Modules/Survey/classes/class.ilSurveySkillThresholdsTableGUI.php index 9b342d943d2bde7d1c8fefb72c9d6c284c063768..272015eadb07ce3f3937ca40e84d87c4e90aa1ea 100644 --- a/Modules/Survey/classes/class.ilSurveySkillThresholdsTableGUI.php +++ b/Modules/Survey/classes/class.ilSurveySkillThresholdsTableGUI.php @@ -14,104 +14,108 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilSurveySkillThresholdsTableGUI extends ilTable2GUI { - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_survey, - $a_base_skill_id, $a_tref_id) - { - global $DIC; + /** + * Constructor + */ + public function __construct( + $a_parent_obj, + $a_parent_cmd, + $a_survey, + $a_base_skill_id, + $a_tref_id + ) { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->object = $a_survey; - $this->base_skill_id = $a_base_skill_id; - $this->tref_id = $a_tref_id; - - - $this->determineMaxScalesAndQuestions(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->object = $a_survey; + $this->base_skill_id = $a_base_skill_id; + $this->tref_id = $a_tref_id; + + + $this->determineMaxScalesAndQuestions(); - ilUtil::sendInfo( - $lng->txt("survey_skill_nr_q").": ".count($this->question_ids). - ", ".$lng->txt("survey_skill_max_scale_points").": ".$this->scale_sum); - - include_once("./Modules/Survey/classes/class.ilSurveySkillThresholds.php"); - $this->skill_thres = new ilSurveySkillThresholds($this->object); - $this->thresholds = $this->skill_thres->getThresholds(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - - include_once("./Modules/Survey/classes/class.ilSurveySkill.php"); - $this->skill_survey = new ilSurveySkill($a_survey); - $this->setData($this->getLevels()); - $this->setTitle(ilBasicSkill::_lookupTitle($this->base_skill_id, $this->tref_id)); - - $this->addColumn($this->lng->txt("survey_skill_level")); - $this->addColumn($this->lng->txt("survey_up_to_x_points")); - - $this->setRowTemplate("tpl.svy_skill_threshold_row.html", "Modules/Survey"); - -// $this->addMultiCommand("saveThresholds", $lng->txt("save")); - $this->addCommandButton("saveThresholds", $lng->txt("save")); - $this->setFormAction($ilCtrl->getFormAction($this->parent_obj)); - } - - /** - * Determine max scales and questions - * - * @param - * @return - */ - function determineMaxScalesAndQuestions() - { - include_once("./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"); - include_once("./Modules/Survey/classes/class.ilSurveySkill.php"); - $ssk = new ilSurveySkill($this->object); - $this->question_ids = $ssk->getQuestionsForSkill($this->base_skill_id, - $this->tref_id); - $this->scale_sum = $ssk->determineMaxScale($this->base_skill_id, - $this->tref_id); - } - - - /** - * Get levels - * - * @param - * @return - */ - function getLevels() - { - include_once("./Services/Skill/classes/class.ilBasicSkill.php"); - $bs = new ilBasicSkill($this->base_skill_id); - return $bs->getLevelData(); - } - - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->tpl->setVariable("LEVEL", $a_set["title"]); - $this->tpl->setVariable("LEVEL_ID", $a_set["id"]); - - $tr = $this->thresholds[$a_set["id"]][$this->tref_id]; - if ((int) $tr != 0) - { - $this->tpl->setVariable("THRESHOLD", (int) $tr); - } - else - { - $this->tpl->setVariable("THRESHOLD", ""); - } - } + ilUtil::sendInfo( + $lng->txt("survey_skill_nr_q") . ": " . count($this->question_ids) . + ", " . $lng->txt("survey_skill_max_scale_points") . ": " . $this->scale_sum + ); + + include_once("./Modules/Survey/classes/class.ilSurveySkillThresholds.php"); + $this->skill_thres = new ilSurveySkillThresholds($this->object); + $this->thresholds = $this->skill_thres->getThresholds(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + + include_once("./Modules/Survey/classes/class.ilSurveySkill.php"); + $this->skill_survey = new ilSurveySkill($a_survey); + $this->setData($this->getLevels()); + $this->setTitle(ilBasicSkill::_lookupTitle($this->base_skill_id, $this->tref_id)); + + $this->addColumn($this->lng->txt("survey_skill_level")); + $this->addColumn($this->lng->txt("survey_up_to_x_points")); + $this->setRowTemplate("tpl.svy_skill_threshold_row.html", "Modules/Survey"); + + // $this->addMultiCommand("saveThresholds", $lng->txt("save")); + $this->addCommandButton("saveThresholds", $lng->txt("save")); + $this->setFormAction($ilCtrl->getFormAction($this->parent_obj)); + } + + /** + * Determine max scales and questions + * + * @param + * @return + */ + public function determineMaxScalesAndQuestions() + { + include_once("./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"); + include_once("./Modules/Survey/classes/class.ilSurveySkill.php"); + $ssk = new ilSurveySkill($this->object); + $this->question_ids = $ssk->getQuestionsForSkill( + $this->base_skill_id, + $this->tref_id + ); + $this->scale_sum = $ssk->determineMaxScale( + $this->base_skill_id, + $this->tref_id + ); + } + + + /** + * Get levels + * + * @param + * @return + */ + public function getLevels() + { + include_once("./Services/Skill/classes/class.ilBasicSkill.php"); + $bs = new ilBasicSkill($this->base_skill_id); + return $bs->getLevelData(); + } + + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $this->tpl->setVariable("LEVEL", $a_set["title"]); + $this->tpl->setVariable("LEVEL_ID", $a_set["id"]); + + $tr = $this->thresholds[$a_set["id"]][$this->tref_id]; + if ((int) $tr != 0) { + $this->tpl->setVariable("THRESHOLD", (int) $tr); + } else { + $this->tpl->setVariable("THRESHOLD", ""); + } + } } -?> diff --git a/Modules/Survey/classes/forms/FormMailCodesGUI.php b/Modules/Survey/classes/forms/FormMailCodesGUI.php index f062b5b671ecbba6ec26d2b4f41b2c1ec492b4f4..bdd96bf56d47d0f0b6897d7b10e53aa02864545e 100644 --- a/Modules/Survey/classes/forms/FormMailCodesGUI.php +++ b/Modules/Survey/classes/forms/FormMailCodesGUI.php @@ -1,24 +1,24 @@ access(); - $ilSetting = $DIC->settings(); - $ilUser = $DIC->user(); - $rbacsystem = $DIC->rbac()->system(); - - $lng = $this->lng; - - $this->guiclass = $guiclass; - - $this->setFormAction($this->ctrl->getFormAction($this->guiclass)); - $this->setTitle($this->lng->txt('compose')); - - $this->subject = new ilTextInputGUI($this->lng->txt('subject'), 'm_subject'); - $this->subject->setSize(50); - $this->subject->setRequired(true); - $this->addItem($this->subject); - - $this->sendtype = new ilRadioGroupInputGUI($this->lng->txt('recipients'), "m_notsent"); - $this->sendtype->addOption(new ilCheckboxOption($this->lng->txt("send_to_all"), 0, '')); - $this->sendtype->addOption(new ilCheckboxOption($this->lng->txt("not_sent_only"), 1, '')); - $this->sendtype->addOption(new ilCheckboxOption($this->lng->txt("send_to_unanswered"), 3, '')); - $this->sendtype->addOption(new ilCheckboxOption($this->lng->txt("send_to_answered"), 2, '')); - $this->addItem($this->sendtype); - - $existingdata = $this->guiclass->getObject()->getExternalCodeRecipients(); - - $existingcolumns = array(); - if (count($existingdata)) - { - $first = array_shift($existingdata); - foreach ($first as $key => $value) - { - if (strcmp($key, 'code') != 0 && strcmp($key, 'email') != 0 && strcmp($key, 'sent') != 0) array_push($existingcolumns, '[' . $key . ']'); - } - } - - $settings = $this->guiclass->getObject()->getUserSettings($ilUser->getId(), 'savemessage'); - if (count($settings)) - { - $options = array(0 => $this->lng->txt('please_select')); - foreach ($settings as $setting) - { - $options[$setting['settings_id']] = $setting['title']; - } - $this->savedmessages = new ilSelectInputGUI($this->lng->txt("saved_messages"), "savedmessage"); - $this->savedmessages->setOptions($options); - $this->addItem($this->savedmessages); - } - - $this->mailmessage = new ilTextAreaInputGUI($this->lng->txt('message_content'), 'm_message'); - $this->mailmessage->setRequired(true); - $this->mailmessage->setCols(80); - $this->mailmessage->setRows(10); - $this->mailmessage->setInfo(sprintf($this->lng->txt('message_content_info'), join($existingcolumns, ', '))); - $this->addItem($this->mailmessage); - - // save message - $this->savemessage = new ilCheckboxInputGUI('', "savemessage"); - $this->savemessage->setOptionTitle($this->lng->txt("save_reuse_message")); - $this->savemessage->setValue(1); - - $this->savemessagetitle = new ilTextInputGUI($this->lng->txt('save_reuse_title'), 'savemessagetitle'); - $this->savemessagetitle->setSize(60); - $this->savemessage->addSubItem($this->savemessagetitle); - - $this->addItem($this->savemessage); - - if (count($settings)) - { - if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) $this->addCommandButton("deleteSavedMessage", $this->lng->txt("delete_saved_message")); - if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) $this->addCommandButton("insertSavedMessage", $this->lng->txt("insert_saved_message")); - } - - if ($ilAccess->checkAccess("write", "", $_GET["ref_id"]) && $rbacsystem->checkAccess('smtp_mail', ilMailGlobalServices::getMailObjectRefId())) - { - if((int)$ilSetting->get('mail_allow_external')) - { - $this->addCommandButton("sendCodesMail", $this->lng->txt("send")); - } - else - { - ilUtil::sendInfo($lng->txt("cant_send_email_smtp_disabled")); - } - } - else - { - ilUtil::sendInfo($lng->txt("cannot_send_emails")); - - } - } - - public function getSavedMessages() - { - return $this->savedmessages; - } - - public function getMailMessage() - { - return $this->mailmessage; - } + protected $guiclass; + protected $subject; + protected $sendtype; + protected $savedmessages; + protected $mailmessage; + protected $savemessage; + protected $savemessagetitle; + + public function __construct($guiclass) + { + global $DIC; + + parent::__construct(); + + $ilAccess = $DIC->access(); + $ilSetting = $DIC->settings(); + $ilUser = $DIC->user(); + $rbacsystem = $DIC->rbac()->system(); + + $lng = $this->lng; + + $this->guiclass = $guiclass; + + $this->setFormAction($this->ctrl->getFormAction($this->guiclass)); + $this->setTitle($this->lng->txt('compose')); + + $this->subject = new ilTextInputGUI($this->lng->txt('subject'), 'm_subject'); + $this->subject->setSize(50); + $this->subject->setRequired(true); + $this->addItem($this->subject); + + $this->sendtype = new ilRadioGroupInputGUI($this->lng->txt('recipients'), "m_notsent"); + $this->sendtype->addOption(new ilCheckboxOption($this->lng->txt("send_to_all"), 0, '')); + $this->sendtype->addOption(new ilCheckboxOption($this->lng->txt("not_sent_only"), 1, '')); + $this->sendtype->addOption(new ilCheckboxOption($this->lng->txt("send_to_unanswered"), 3, '')); + $this->sendtype->addOption(new ilCheckboxOption($this->lng->txt("send_to_answered"), 2, '')); + $this->addItem($this->sendtype); + + $existingdata = $this->guiclass->getObject()->getExternalCodeRecipients(); + + $existingcolumns = array(); + if (count($existingdata)) { + $first = array_shift($existingdata); + foreach ($first as $key => $value) { + if (strcmp($key, 'code') != 0 && strcmp($key, 'email') != 0 && strcmp($key, 'sent') != 0) { + array_push($existingcolumns, '[' . $key . ']'); + } + } + } + + $settings = $this->guiclass->getObject()->getUserSettings($ilUser->getId(), 'savemessage'); + if (count($settings)) { + $options = array(0 => $this->lng->txt('please_select')); + foreach ($settings as $setting) { + $options[$setting['settings_id']] = $setting['title']; + } + $this->savedmessages = new ilSelectInputGUI($this->lng->txt("saved_messages"), "savedmessage"); + $this->savedmessages->setOptions($options); + $this->addItem($this->savedmessages); + } + + $this->mailmessage = new ilTextAreaInputGUI($this->lng->txt('message_content'), 'm_message'); + $this->mailmessage->setRequired(true); + $this->mailmessage->setCols(80); + $this->mailmessage->setRows(10); + $this->mailmessage->setInfo(sprintf($this->lng->txt('message_content_info'), join($existingcolumns, ', '))); + $this->addItem($this->mailmessage); + + // save message + $this->savemessage = new ilCheckboxInputGUI('', "savemessage"); + $this->savemessage->setOptionTitle($this->lng->txt("save_reuse_message")); + $this->savemessage->setValue(1); + + $this->savemessagetitle = new ilTextInputGUI($this->lng->txt('save_reuse_title'), 'savemessagetitle'); + $this->savemessagetitle->setSize(60); + $this->savemessage->addSubItem($this->savemessagetitle); + + $this->addItem($this->savemessage); + + if (count($settings)) { + if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) { + $this->addCommandButton("deleteSavedMessage", $this->lng->txt("delete_saved_message")); + } + if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) { + $this->addCommandButton("insertSavedMessage", $this->lng->txt("insert_saved_message")); + } + } + + if ($ilAccess->checkAccess("write", "", $_GET["ref_id"]) && $rbacsystem->checkAccess('smtp_mail', ilMailGlobalServices::getMailObjectRefId())) { + if ((int) $ilSetting->get('mail_allow_external')) { + $this->addCommandButton("sendCodesMail", $this->lng->txt("send")); + } else { + ilUtil::sendInfo($lng->txt("cant_send_email_smtp_disabled")); + } + } else { + ilUtil::sendInfo($lng->txt("cannot_send_emails")); + } + } + + public function getSavedMessages() + { + return $this->savedmessages; + } + + public function getMailMessage() + { + return $this->mailmessage; + } } - -?> \ No newline at end of file diff --git a/Modules/Survey/classes/tables/class.SurveyConstraintsTableGUI.php b/Modules/Survey/classes/tables/class.SurveyConstraintsTableGUI.php index 2c7802445e23733e5f9dcf9b5cc7641b788e8010..5a31835239a065cac1dd0f649c9463ac48c2fd17 100644 --- a/Modules/Survey/classes/tables/class.SurveyConstraintsTableGUI.php +++ b/Modules/Survey/classes/tables/class.SurveyConstraintsTableGUI.php @@ -1,223 +1,195 @@ - -* @version $Id: class.ilFoundUsersTableGUI.php 20638 2009-07-19 08:14:34Z hschottm $ -* -* @ingroup ModulesSurvey -*/ -class SurveyConstraintsTableGUI extends ilTable2GUI -{ - protected $read_only; // [bool] - protected $structure; // [array] - - function __construct($a_parent_obj, $a_parent_cmd = "", ilObjSurvey $a_survey, $a_read_only) - { - global $DIC; +ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->read_only = (bool)$a_read_only; - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setLimit(9999); - $this->disable("numinfo"); - - $this->setDescription($lng->txt("constraints_introduction")); - - if(!$this->read_only) - { - $this->addColumn("", "", 1); - } - - $this->addColumn("", "", 1); - $this->addColumn($lng->txt("constraints_list_of_entities"), ""); - $this->addColumn($lng->txt("existing_constraints"), ""); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.svy_constraints_row.html", "Modules/Survey"); - - if(!$this->read_only) - { - $this->addMultiCommand("createConstraints", $lng->txt("constraint_add")); - $this->setSelectAllCheckbox("includeElements"); - } - - $this->initItems($a_survey); - } - - protected function initItems(ilObjSurvey $a_survey) - { - $lng = $this->lng; - - $this->structure = array(); - $tbl_data = array(); - - $survey_questions = $a_survey->getSurveyQuestions(); - - $last_questionblock_id = 0; - $counter = 1; - foreach ($survey_questions as $data) - { - $title = $data["title"]; - $show = true; - if ($data["questionblock_id"] > 0) - { - $title = $data["questionblock_title"]; - $type = $lng->txt("questionblock"); - if ($data["questionblock_id"] != $last_questionblock_id) - { - $last_questionblock_id = $data["questionblock_id"]; - $this->structure[$counter] = array(); - array_push($this->structure[$counter], $data["question_id"]); - } - else - { - array_push($this->structure[$counter-1], $data["question_id"]); - $show = false; - } - } - else - { - $this->structure[$counter] = array($data["question_id"]); - $type = $lng->txt("question"); - } - if ($show) - { - $id = $content = $parsed = $conjunction = null; - - if ($counter == 1) - { - $content = $lng->txt("constraints_first_question_description"); - } - else - { - $constraints = $a_survey->getConstraints($data["question_id"]); - if (count($constraints)) - { - $parsed = array(); - - foreach ($constraints as $constraint) - { - $parsed[] = array( - "id" => $constraint["id"], - "title" => $survey_questions[$constraint["question"]]["title"] . " " . - $constraint["short"] . " " . - $constraint["valueoutput"] - ); - } - - if (count($constraints) > 1) - { - $conjunction = ($constraints[0]['conjunction']) - ? $lng->txt('conjunction_or_title') - : $lng->txt('conjunction_and_title'); - } - } - } - if ($counter != 1) - { - $id = $counter; - } - - $icontype = "question.png"; - if ($data["questionblock_id"] > 0) - { - $icontype = "questionblock.png"; - } - - $tbl_data[] = array( - "counter" => $counter, - "id" => $id, - "title" => $title, - "type" => $type, - "icon" => ilUtil::getImagePath($icontype, "Modules/Survey"), - "content" => $content, - "constraints" => $parsed, - "conjunction" => $conjunction - ); - - $counter++; - } - } - - $this->setData($tbl_data); - } - - public function getStructure() - { - return $this->structure; - } - - protected function fillRow($a_set) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - // $ilCtrl->setParameterByClass("ilObjSurveyAdministrationGUI", "item_id", $a_set["usr_id"]); - - if(!$this->read_only) - { - if($a_set["id"]) - { - $this->tpl->setVariable("ID", $a_set["id"]); - } - else - { - $this->tpl->touchBlock("checkbox"); - } - } - - $this->tpl->setVariable("COUNTER", $a_set["counter"]); - $this->tpl->setVariable("TITLE", $a_set["title"]); - $this->tpl->setVariable("TYPE", $a_set["type"]); - $this->tpl->setVariable("ICON_HREF", $a_set["icon"]); - $this->tpl->setVariable("ICON_ALT", $a_set["type"]); - $this->tpl->setVariable("CONTENT", $a_set["content"]); - - if(is_array($a_set["constraints"])) - { - foreach($a_set["constraints"] as $constraint) - { - if(!$this->read_only) - { - $ilCtrl->setParameter($this->getParentObject(), "precondition", $constraint["id"]); - $ilCtrl->setParameter($this->getParentObject(), "start", $a_set["counter"]); - $url = $ilCtrl->getLinkTarget($this->getParentObject(), "editPrecondition"); - $ilCtrl->setParameter($this->getParentObject(), "precondition", ""); - $ilCtrl->setParameter($this->getParentObject(), "start", ""); - $this->tpl->setVariable("TEXT_EDIT_PRECONDITION", $lng->txt("edit")); - $this->tpl->setVariable("EDIT_PRECONDITION", $url); - - $ilCtrl->setParameter($this->getParentObject(), "precondition", $constraint["id"]); - $url = $ilCtrl->getLinkTarget($this->getParentObject(), "confirmDeleteConstraints"); - $ilCtrl->setParameter($this->getParentObject(), "precondition", ""); - $this->tpl->setVariable("TEXT_DELETE_PRECONDITION", $lng->txt("delete")); - $this->tpl->setVariable("DELETE_PRECONDITION", $url); - } - - $this->tpl->setCurrentBlock("constraint"); - $this->tpl->setVariable("CONSTRAINT_TEXT", $constraint["title"]); - $this->tpl->parseCurrentBlock(); - } - - if($a_set["conjunction"]) - { - $this->tpl->setCurrentBlock("conjunction"); - $this->tpl->setVariable("TEXT_CONJUNCTION", $a_set["conjunction"]); - $this->tpl->parseCurrentBlock(); - } - } - } - -} -?> +include_once("./Services/Table/classes/class.ilTable2GUI.php"); + +/** +* TableGUI class for survey constraints +* +* @author Jörg Lützenkirchen +* @version $Id: class.ilFoundUsersTableGUI.php 20638 2009-07-19 08:14:34Z hschottm $ +* +* @ingroup ModulesSurvey +*/ +class SurveyConstraintsTableGUI extends ilTable2GUI +{ + protected $read_only; // [bool] + protected $structure; // [array] + + public function __construct($a_parent_obj, $a_parent_cmd = "", ilObjSurvey $a_survey, $a_read_only) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->read_only = (bool) $a_read_only; + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setLimit(9999); + $this->disable("numinfo"); + + $this->setDescription($lng->txt("constraints_introduction")); + + if (!$this->read_only) { + $this->addColumn("", "", 1); + } + + $this->addColumn("", "", 1); + $this->addColumn($lng->txt("constraints_list_of_entities"), ""); + $this->addColumn($lng->txt("existing_constraints"), ""); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.svy_constraints_row.html", "Modules/Survey"); + + if (!$this->read_only) { + $this->addMultiCommand("createConstraints", $lng->txt("constraint_add")); + $this->setSelectAllCheckbox("includeElements"); + } + + $this->initItems($a_survey); + } + + protected function initItems(ilObjSurvey $a_survey) + { + $lng = $this->lng; + + $this->structure = array(); + $tbl_data = array(); + + $survey_questions = $a_survey->getSurveyQuestions(); + + $last_questionblock_id = 0; + $counter = 1; + foreach ($survey_questions as $data) { + $title = $data["title"]; + $show = true; + if ($data["questionblock_id"] > 0) { + $title = $data["questionblock_title"]; + $type = $lng->txt("questionblock"); + if ($data["questionblock_id"] != $last_questionblock_id) { + $last_questionblock_id = $data["questionblock_id"]; + $this->structure[$counter] = array(); + array_push($this->structure[$counter], $data["question_id"]); + } else { + array_push($this->structure[$counter-1], $data["question_id"]); + $show = false; + } + } else { + $this->structure[$counter] = array($data["question_id"]); + $type = $lng->txt("question"); + } + if ($show) { + $id = $content = $parsed = $conjunction = null; + + if ($counter == 1) { + $content = $lng->txt("constraints_first_question_description"); + } else { + $constraints = $a_survey->getConstraints($data["question_id"]); + if (count($constraints)) { + $parsed = array(); + + foreach ($constraints as $constraint) { + $parsed[] = array( + "id" => $constraint["id"], + "title" => $survey_questions[$constraint["question"]]["title"] . " " . + $constraint["short"] . " " . + $constraint["valueoutput"] + ); + } + + if (count($constraints) > 1) { + $conjunction = ($constraints[0]['conjunction']) + ? $lng->txt('conjunction_or_title') + : $lng->txt('conjunction_and_title'); + } + } + } + if ($counter != 1) { + $id = $counter; + } + + $icontype = "question.png"; + if ($data["questionblock_id"] > 0) { + $icontype = "questionblock.png"; + } + + $tbl_data[] = array( + "counter" => $counter, + "id" => $id, + "title" => $title, + "type" => $type, + "icon" => ilUtil::getImagePath($icontype, "Modules/Survey"), + "content" => $content, + "constraints" => $parsed, + "conjunction" => $conjunction + ); + + $counter++; + } + } + + $this->setData($tbl_data); + } + + public function getStructure() + { + return $this->structure; + } + + protected function fillRow($a_set) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + // $ilCtrl->setParameterByClass("ilObjSurveyAdministrationGUI", "item_id", $a_set["usr_id"]); + + if (!$this->read_only) { + if ($a_set["id"]) { + $this->tpl->setVariable("ID", $a_set["id"]); + } else { + $this->tpl->touchBlock("checkbox"); + } + } + + $this->tpl->setVariable("COUNTER", $a_set["counter"]); + $this->tpl->setVariable("TITLE", $a_set["title"]); + $this->tpl->setVariable("TYPE", $a_set["type"]); + $this->tpl->setVariable("ICON_HREF", $a_set["icon"]); + $this->tpl->setVariable("ICON_ALT", $a_set["type"]); + $this->tpl->setVariable("CONTENT", $a_set["content"]); + + if (is_array($a_set["constraints"])) { + foreach ($a_set["constraints"] as $constraint) { + if (!$this->read_only) { + $ilCtrl->setParameter($this->getParentObject(), "precondition", $constraint["id"]); + $ilCtrl->setParameter($this->getParentObject(), "start", $a_set["counter"]); + $url = $ilCtrl->getLinkTarget($this->getParentObject(), "editPrecondition"); + $ilCtrl->setParameter($this->getParentObject(), "precondition", ""); + $ilCtrl->setParameter($this->getParentObject(), "start", ""); + $this->tpl->setVariable("TEXT_EDIT_PRECONDITION", $lng->txt("edit")); + $this->tpl->setVariable("EDIT_PRECONDITION", $url); + + $ilCtrl->setParameter($this->getParentObject(), "precondition", $constraint["id"]); + $url = $ilCtrl->getLinkTarget($this->getParentObject(), "confirmDeleteConstraints"); + $ilCtrl->setParameter($this->getParentObject(), "precondition", ""); + $this->tpl->setVariable("TEXT_DELETE_PRECONDITION", $lng->txt("delete")); + $this->tpl->setVariable("DELETE_PRECONDITION", $url); + } + + $this->tpl->setCurrentBlock("constraint"); + $this->tpl->setVariable("CONSTRAINT_TEXT", $constraint["title"]); + $this->tpl->parseCurrentBlock(); + } + + if ($a_set["conjunction"]) { + $this->tpl->setCurrentBlock("conjunction"); + $this->tpl->setVariable("TEXT_CONJUNCTION", $a_set["conjunction"]); + $this->tpl->parseCurrentBlock(); + } + } + } +} diff --git a/Modules/Survey/classes/tables/class.ilFoundUsersTableGUI.php b/Modules/Survey/classes/tables/class.ilFoundUsersTableGUI.php index 5ee1d25dd71d8a566bc1c25f1e09a5674febdda6..da7fa8124ffc52f623d064f26f622763bbfc746e 100644 --- a/Modules/Survey/classes/tables/class.ilFoundUsersTableGUI.php +++ b/Modules/Survey/classes/tables/class.ilFoundUsersTableGUI.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->addColumn("", "f", "1"); - $this->addColumn($lng->txt("login"), "", "33%"); - $this->addColumn($lng->txt("firstname"), "", "33%"); - $this->addColumn($lng->txt("lastname"), "", "33%"); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.table_found_users_row.html", "Modules/Survey"); - $this->setDefaultOrderField("lastname"); - $this->setDefaultOrderDirection("asc"); - } - - /** - * Standard Version of Fill Row. Most likely to - * be overwritten by derived class. - */ - protected function fillRow($a_set) - { - $ilCtrl = $this->ctrl; - $ilCtrl->setParameterByClass("ilObjSurveyAdministrationGUI", "item_id", $a_set["usr_id"]); - $this->tpl->setVariable("USER_ID", $a_set["usr_id"]); - $this->tpl->setVariable("LOGIN", $a_set["login"]); - $this->tpl->setVariable("FIRSTNAME", $a_set["firstname"]); - $this->tpl->setVariable("LASTNAME", $a_set["lastname"]); - } - + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->addColumn("", "f", "1"); + $this->addColumn($lng->txt("login"), "", "33%"); + $this->addColumn($lng->txt("firstname"), "", "33%"); + $this->addColumn($lng->txt("lastname"), "", "33%"); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.table_found_users_row.html", "Modules/Survey"); + $this->setDefaultOrderField("lastname"); + $this->setDefaultOrderDirection("asc"); + } + + /** + * Standard Version of Fill Row. Most likely to + * be overwritten by derived class. + */ + protected function fillRow($a_set) + { + $ilCtrl = $this->ctrl; + $ilCtrl->setParameterByClass("ilObjSurveyAdministrationGUI", "item_id", $a_set["usr_id"]); + $this->tpl->setVariable("USER_ID", $a_set["usr_id"]); + $this->tpl->setVariable("LOGIN", $a_set["login"]); + $this->tpl->setVariable("FIRSTNAME", $a_set["firstname"]); + $this->tpl->setVariable("LASTNAME", $a_set["lastname"]); + } } -?> diff --git a/Modules/Survey/classes/tables/class.ilSpecialUsersTableGUI.php b/Modules/Survey/classes/tables/class.ilSpecialUsersTableGUI.php index 93a5fb9b71a56108c794f4add1dd30b191ebd559..0f425ce5d0b5185a04711fd0f85dbf080586a863 100644 --- a/Modules/Survey/classes/tables/class.ilSpecialUsersTableGUI.php +++ b/Modules/Survey/classes/tables/class.ilSpecialUsersTableGUI.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->addColumn("", "f", "1"); - $this->addColumn($lng->txt("login"), "", "33%"); - $this->addColumn($lng->txt("firstname"), "", "33%"); - $this->addColumn($lng->txt("lastname"), "", "33%"); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.table_special_users_row.html", "Modules/Survey"); - $this->setDefaultOrderField("lastname"); - $this->setDefaultOrderDirection("asc"); - } - - /** - * Standard Version of Fill Row. Most likely to - * be overwritten by derived class. - */ - protected function fillRow($a_set) - { - $ilCtrl = $this->ctrl; - include_once "./Services/User/classes/class.ilObjUser.php"; - $user = ilObjUser::_lookupFields($a_set); - $ilCtrl->setParameterByClass("ilObjSurveyAdministrationGUI", "item_id", $user["usr_id"]); - $this->tpl->setVariable("USER_ID", $user["usr_id"]); - $this->tpl->setVariable("LOGIN", $user["login"]); - $this->tpl->setVariable("FIRSTNAME", $user["firstname"]); - $this->tpl->setVariable("LASTNAME", $user["lastname"]); - } - + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->addColumn("", "f", "1"); + $this->addColumn($lng->txt("login"), "", "33%"); + $this->addColumn($lng->txt("firstname"), "", "33%"); + $this->addColumn($lng->txt("lastname"), "", "33%"); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.table_special_users_row.html", "Modules/Survey"); + $this->setDefaultOrderField("lastname"); + $this->setDefaultOrderDirection("asc"); + } + + /** + * Standard Version of Fill Row. Most likely to + * be overwritten by derived class. + */ + protected function fillRow($a_set) + { + $ilCtrl = $this->ctrl; + include_once "./Services/User/classes/class.ilObjUser.php"; + $user = ilObjUser::_lookupFields($a_set); + $ilCtrl->setParameterByClass("ilObjSurveyAdministrationGUI", "item_id", $user["usr_id"]); + $this->tpl->setVariable("USER_ID", $user["usr_id"]); + $this->tpl->setVariable("LOGIN", $user["login"]); + $this->tpl->setVariable("FIRSTNAME", $user["firstname"]); + $this->tpl->setVariable("LASTNAME", $user["lastname"]); + } } -?> diff --git a/Modules/Survey/classes/tables/class.ilSurveyAppraiseesTableGUI.php b/Modules/Survey/classes/tables/class.ilSurveyAppraiseesTableGUI.php index ea6fc1db60e784b51262dcd8c0b549b80deb258b..ff215b596ae7ec9fc784cb876e8250991d13b2ce 100644 --- a/Modules/Survey/classes/tables/class.ilSurveyAppraiseesTableGUI.php +++ b/Modules/Survey/classes/tables/class.ilSurveyAppraiseesTableGUI.php @@ -32,152 +32,129 @@ include_once('./Services/Table/classes/class.ilTable2GUI.php'); */ class ilSurveyAppraiseesTableGUI extends ilTable2GUI -{ - protected $raters_mode; // [bool] - protected $fallback_url; // [string] - - /** - * Constructor - * - * @access public - * @param - * @return - */ - public function __construct($a_parent_obj, $a_parent_cmd, $a_raters_mode = false, $a_may_delete_rater = false, $a_fallback_url = null) - { - global $DIC; +{ + protected $raters_mode; // [bool] + protected $fallback_url; // [string] + + /** + * Constructor + * + * @access public + * @param + * @return + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_raters_mode = false, $a_may_delete_rater = false, $a_fallback_url = null) + { + global $DIC; - parent::__construct($a_parent_obj, $a_parent_cmd); + parent::__construct($a_parent_obj, $a_parent_cmd); - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - - $this->raters_mode = (bool)$a_raters_mode; - $this->fallback_url = trim($a_fallback_url); + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + + $this->raters_mode = (bool) $a_raters_mode; + $this->fallback_url = trim($a_fallback_url); - $this->lng = $lng; - $this->ctrl = $ilCtrl; - - $this->setFormName('apprform'); - - $this->addColumn('','','1%'); - $this->addColumn($this->lng->txt("name"),'name', ''); - $this->addColumn($this->lng->txt("login"),'login', ''); - $this->addColumn($this->lng->txt("email"),'email', ''); - - if(!$this->raters_mode) - { - $this->addColumn($this->lng->txt("survey_360_raters_finished"), "finished"); - $this->addColumn($this->lng->txt("survey_360_appraisee_close_table"), "closed"); - $this->addColumn($this->lng->txt("actions")); - - $this->setTitle($this->lng->txt("survey_360_appraisees")); - } - else - { - $this->addColumn($this->lng->txt("survey_360_rater_finished"), "finished"); - $this->addColumn($this->lng->txt("survey_code_url")); - $this->addColumn($this->lng->txt("survey_360_rater_mail_sent"), "sent"); - - include_once "Services/User/classes/class.ilUserUtil.php"; - $this->setTitle($this->lng->txt("survey_360_edit_raters")." : ". - ilUserUtil::getNamePresentation($_REQUEST["appr_id"])); - } - - $this->setRowTemplate("tpl.il_svy_svy_appraisees_row.html", "Modules/Survey"); - - $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); + $this->lng = $lng; + $this->ctrl = $ilCtrl; + + $this->setFormName('apprform'); + + $this->addColumn('', '', '1%'); + $this->addColumn($this->lng->txt("name"), 'name', ''); + $this->addColumn($this->lng->txt("login"), 'login', ''); + $this->addColumn($this->lng->txt("email"), 'email', ''); + + if (!$this->raters_mode) { + $this->addColumn($this->lng->txt("survey_360_raters_finished"), "finished"); + $this->addColumn($this->lng->txt("survey_360_appraisee_close_table"), "closed"); + $this->addColumn($this->lng->txt("actions")); + + $this->setTitle($this->lng->txt("survey_360_appraisees")); + } else { + $this->addColumn($this->lng->txt("survey_360_rater_finished"), "finished"); + $this->addColumn($this->lng->txt("survey_code_url")); + $this->addColumn($this->lng->txt("survey_360_rater_mail_sent"), "sent"); + + include_once "Services/User/classes/class.ilUserUtil.php"; + $this->setTitle($this->lng->txt("survey_360_edit_raters") . " : " . + ilUserUtil::getNamePresentation($_REQUEST["appr_id"])); + } + + $this->setRowTemplate("tpl.il_svy_svy_appraisees_row.html", "Modules/Survey"); + + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); - $this->setDefaultOrderField("last_name"); - $this->setDefaultOrderDirection("asc"); - - if(!$this->raters_mode) - { - $this->addMultiCommand('confirmAdminAppraiseesClose', $this->lng->txt('survey_360_appraisee_close_action')); - $this->addMultiCommand('confirmDeleteAppraisees', $this->lng->txt('survey_360_remove_appraisees')); - $this->setPrefix('appr_id'); - $this->setSelectAllCheckbox('appr_id'); - } - else - { - $this->addMultiCommand('mailRaters', $this->lng->txt('mail')); - if($a_may_delete_rater) - { - $this->addMultiCommand('confirmDeleteRaters', $this->lng->txt('remove')); - } - $this->setPrefix('rtr_id'); - $this->setSelectAllCheckbox('rtr_id'); - } - } + $this->setDefaultOrderField("last_name"); + $this->setDefaultOrderDirection("asc"); + + if (!$this->raters_mode) { + $this->addMultiCommand('confirmAdminAppraiseesClose', $this->lng->txt('survey_360_appraisee_close_action')); + $this->addMultiCommand('confirmDeleteAppraisees', $this->lng->txt('survey_360_remove_appraisees')); + $this->setPrefix('appr_id'); + $this->setSelectAllCheckbox('appr_id'); + } else { + $this->addMultiCommand('mailRaters', $this->lng->txt('mail')); + if ($a_may_delete_rater) { + $this->addMultiCommand('confirmDeleteRaters', $this->lng->txt('remove')); + } + $this->setPrefix('rtr_id'); + $this->setSelectAllCheckbox('rtr_id'); + } + } - /** - * fill row - * - * @access public - * @param - * @return - */ - public function fillRow($data) - { - $lng = $this->lng; - - if(!$this->raters_mode) - { + /** + * fill row + * + * @access public + * @param + * @return + */ + public function fillRow($data) + { + $lng = $this->lng; + + if (!$this->raters_mode) { + if ($data['closed']) { + $this->tpl->setVariable("CLOSED", ilDatePresentation::formatDate(new ilDateTime($data['closed'], IL_CAL_UNIX))); + } else { + $this->tpl->setCurrentBlock("cb"); + $this->tpl->setVariable('MODE', $this->raters_mode ? "rtr" : "appr"); + $this->tpl->setVariable('ID', $data['user_id']); + $this->tpl->parseCurrentBlock(); + $this->tpl->setVariable("CLOSED", ""); + } - if($data['closed']) - { - $this->tpl->setVariable("CLOSED",ilDatePresentation::formatDate(new ilDateTime($data['closed'], IL_CAL_UNIX))); - } - else - { - $this->tpl->setCurrentBlock("cb"); - $this->tpl->setVariable('MODE', $this->raters_mode ? "rtr" : "appr"); - $this->tpl->setVariable('ID', $data['user_id']); - $this->tpl->parseCurrentBlock(); - $this->tpl->setVariable("CLOSED",""); - } + $this->tpl->setVariable("FINISHED", $data['finished']); - $this->tpl->setVariable("FINISHED", $data['finished']); + $this->ctrl->setParameter($this->getParentObject(), "appr_id", $data["user_id"]); + $this->tpl->setVariable("URL", $lng->txt("survey_360_edit_raters")); + $this->tpl->setVariable("HREF", $this->ctrl->getLinkTarget($this->getParentObject(), "editRaters")); + $this->ctrl->setParameter($this->getParentObject(), "appr_id", ""); + } else { + $this->tpl->setVariable('MODE', $this->raters_mode ? "rtr" : "appr"); + $this->tpl->setVariable('ID', $data['user_id']); + $this->tpl->setVariable("FINISHED", $data['finished'] ? $lng->txt("yes") : $lng->txt("no")); + + $sent = ""; + if ($data["sent"]) { + $sent = ilDatePresentation::formatDate(new ilDateTime($data["sent"], IL_CAL_UNIX)); + } + $this->tpl->setVariable("MAIL_SENT", $sent); + + if ($data["href"] || $this->fallback_url) { + if ($data["href"]) { + $this->tpl->setVariable("DIRECT_HREF", $data["href"]); + } else { + $this->tpl->setVariable("DIRECT_HREF", $this->fallback_url); + } + } else { + $this->tpl->setVariable("NO_HREF", ""); + } + } - $this->ctrl->setParameter($this->getParentObject(), "appr_id", $data["user_id"]); - $this->tpl->setVariable("URL", $lng->txt("survey_360_edit_raters")); - $this->tpl->setVariable("HREF", $this->ctrl->getLinkTarget($this->getParentObject(), "editRaters")); - $this->ctrl->setParameter($this->getParentObject(), "appr_id", ""); - } - else - { - $this->tpl->setVariable('MODE', $this->raters_mode ? "rtr" : "appr"); - $this->tpl->setVariable('ID', $data['user_id']); - $this->tpl->setVariable("FINISHED", $data['finished'] ? $lng->txt("yes") : $lng->txt("no")); - - $sent = ""; - if($data["sent"]) - { - $sent = ilDatePresentation::formatDate(new ilDateTime($data["sent"], IL_CAL_UNIX)); - } - $this->tpl->setVariable("MAIL_SENT", $sent); - - if($data["href"] || $this->fallback_url) - { - if($data["href"]) - { - $this->tpl->setVariable("DIRECT_HREF", $data["href"]); - } - else - { - $this->tpl->setVariable("DIRECT_HREF", $this->fallback_url); - } - } - else - { - $this->tpl->setVariable("NO_HREF", ""); - } - } - - $this->tpl->setVariable("LOGIN", $data['login']); - $this->tpl->setVariable("EMAIL", $data['email']); - $this->tpl->setVariable("NAME", $data['name']); - - } + $this->tpl->setVariable("LOGIN", $data['login']); + $this->tpl->setVariable("EMAIL", $data['email']); + $this->tpl->setVariable("NAME", $data['name']); + } } -?> \ No newline at end of file diff --git a/Modules/Survey/classes/tables/class.ilSurveyCodesEditTableGUI.php b/Modules/Survey/classes/tables/class.ilSurveyCodesEditTableGUI.php index d721166d8d2c46db3c675124396cdc3009bbf279..c14e59da6fcf6715a4c44f19290c84d212f12a85 100644 --- a/Modules/Survey/classes/tables/class.ilSurveyCodesEditTableGUI.php +++ b/Modules/Survey/classes/tables/class.ilSurveyCodesEditTableGUI.php @@ -32,51 +32,50 @@ include_once('./Services/Table/classes/class.ilTable2GUI.php'); */ class ilSurveyCodesEditTableGUI extends ilTable2GUI -{ - /** - * Constructor - * - * @access public - * @param - * @return - */ - public function __construct($a_parent_obj, $a_parent_cmd) - { - global $DIC; +{ + /** + * Constructor + * + * @access public + * @param + * @return + */ + public function __construct($a_parent_obj, $a_parent_cmd) + { + global $DIC; - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->lng = $lng; - $this->ctrl = $ilCtrl; - - $this->addColumn($this->lng->txt("survey_code"),'code', ''); - $this->addColumn($this->lng->txt("email"),'email', ''); - $this->addColumn($this->lng->txt("lastname"),'last_name', ''); - $this->addColumn($this->lng->txt("firstname"),'first_name', ''); - $this->addColumn($this->lng->txt("mail_sent_short"),'sent', ''); - - $this->setRowTemplate("tpl.il_svy_svy_codes_edit_row.html", "Modules/Survey"); + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->lng = $lng; + $this->ctrl = $ilCtrl; + + $this->addColumn($this->lng->txt("survey_code"), 'code', ''); + $this->addColumn($this->lng->txt("email"), 'email', ''); + $this->addColumn($this->lng->txt("lastname"), 'last_name', ''); + $this->addColumn($this->lng->txt("firstname"), 'first_name', ''); + $this->addColumn($this->lng->txt("mail_sent_short"), 'sent', ''); + + $this->setRowTemplate("tpl.il_svy_svy_codes_edit_row.html", "Modules/Survey"); - $this->addCommandButton('updateCodes', $this->lng->txt('save')); - $this->addCommandButton('codes', $this->lng->txt('cancel')); + $this->addCommandButton('updateCodes', $this->lng->txt('save')); + $this->addCommandButton('codes', $this->lng->txt('cancel')); - $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); - $this->setDefaultOrderField("code"); - $this->setDefaultOrderDirection("asc"); - } + $this->setDefaultOrderField("code"); + $this->setDefaultOrderDirection("asc"); + } - public function fillRow($data) - { - $this->tpl->setVariable('ID', $data["id"]); - $this->tpl->setVariable("SENT", ($data['sent']) ? ' checked="checked"' : ''); - $this->tpl->setVariable("CODE", $data['code']); - $this->tpl->setVariable("EMAIL", $data['email']); - $this->tpl->setVariable("LAST_NAME", $data['last_name']); - $this->tpl->setVariable("FIRST_NAME", $data['first_name']); - } + public function fillRow($data) + { + $this->tpl->setVariable('ID', $data["id"]); + $this->tpl->setVariable("SENT", ($data['sent']) ? ' checked="checked"' : ''); + $this->tpl->setVariable("CODE", $data['code']); + $this->tpl->setVariable("EMAIL", $data['email']); + $this->tpl->setVariable("LAST_NAME", $data['last_name']); + $this->tpl->setVariable("FIRST_NAME", $data['first_name']); + } } -?> \ No newline at end of file diff --git a/Modules/Survey/classes/tables/class.ilSurveyCodesTableGUI.php b/Modules/Survey/classes/tables/class.ilSurveyCodesTableGUI.php index e64171766008a2c788113346fbe4bcca268e69a1..3551b75e33a0687384fea70e05e52ec41fffbe10 100644 --- a/Modules/Survey/classes/tables/class.ilSurveyCodesTableGUI.php +++ b/Modules/Survey/classes/tables/class.ilSurveyCodesTableGUI.php @@ -32,90 +32,88 @@ include_once('./Services/Table/classes/class.ilTable2GUI.php'); */ class ilSurveyCodesTableGUI extends ilTable2GUI -{ - /** - * Constructor - * - * @access public - * @param - * @return - */ - public function __construct($a_parent_obj, $a_parent_cmd) - { - global $DIC; +{ + /** + * Constructor + * + * @access public + * @param + * @return + */ + public function __construct($a_parent_obj, $a_parent_cmd) + { + global $DIC; - parent::__construct($a_parent_obj, $a_parent_cmd); + parent::__construct($a_parent_obj, $a_parent_cmd); - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); - $this->lng = $lng; - $this->ctrl = $ilCtrl; - - $this->setFormName('codesform'); - - $this->addColumn('','','1%'); - $this->addColumn($this->lng->txt("survey_code"),'code', ''); - $this->addColumn($this->lng->txt("email"),'email', ''); - $this->addColumn($this->lng->txt("lastname"),'last_name', ''); - $this->addColumn($this->lng->txt("firstname"),'first_name', ''); - $this->addColumn($this->lng->txt("create_date"),'date', ''); - $this->addColumn($this->lng->txt("survey_code_used"),'used', ''); - $this->addColumn($this->lng->txt("mail_sent_short"),'sent', ''); - $this->addColumn($this->lng->txt("survey_code_url")); - - $this->setRowTemplate("tpl.il_svy_svy_codes_row.html", "Modules/Survey"); + $this->lng = $lng; + $this->ctrl = $ilCtrl; + + $this->setFormName('codesform'); + + $this->addColumn('', '', '1%'); + $this->addColumn($this->lng->txt("survey_code"), 'code', ''); + $this->addColumn($this->lng->txt("email"), 'email', ''); + $this->addColumn($this->lng->txt("lastname"), 'last_name', ''); + $this->addColumn($this->lng->txt("firstname"), 'first_name', ''); + $this->addColumn($this->lng->txt("create_date"), 'date', ''); + $this->addColumn($this->lng->txt("survey_code_used"), 'used', ''); + $this->addColumn($this->lng->txt("mail_sent_short"), 'sent', ''); + $this->addColumn($this->lng->txt("survey_code_url")); + + $this->setRowTemplate("tpl.il_svy_svy_codes_row.html", "Modules/Survey"); - $this->addMultiCommand('editCodes', $this->lng->txt('edit')); - $this->addMultiCommand('exportCodes', $this->lng->txt('export')); - $this->addMultiCommand('deleteCodesConfirm', $this->lng->txt('delete')); - - $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); + $this->addMultiCommand('editCodes', $this->lng->txt('edit')); + $this->addMultiCommand('exportCodes', $this->lng->txt('export')); + $this->addMultiCommand('deleteCodesConfirm', $this->lng->txt('delete')); + + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); - include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; - $button = ilSubmitButton::getInstance(); - $button->setCaption("export_all_survey_codes"); - $button->setCommand("exportAllCodes"); - $button->setOmitPreventDoubleSubmission(true); - $this->addCommandButtonInstance($button); - - $this->setDefaultOrderField("code"); - $this->setDefaultOrderDirection("asc"); + include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; + $button = ilSubmitButton::getInstance(); + $button->setCaption("export_all_survey_codes"); + $button->setCommand("exportAllCodes"); + $button->setOmitPreventDoubleSubmission(true); + $this->addCommandButtonInstance($button); + + $this->setDefaultOrderField("code"); + $this->setDefaultOrderDirection("asc"); - $this->setPrefix('chb_code'); - $this->setSelectAllCheckbox('chb_code'); - } + $this->setPrefix('chb_code'); + $this->setSelectAllCheckbox('chb_code'); + } - /** - * fill row - * - * @access public - * @param - * @return - */ - public function fillRow($data) - { - $lng = $this->lng; - - $this->tpl->setVariable('CB_CODE', $data['id']); - - // :TODO: see permalink gui - if (strlen($data['href'])) - { - $this->tpl->setCurrentBlock('url'); - $this->tpl->setVariable("URL", $lng->txt("survey_code_url_name")); - $this->tpl->setVariable("HREF", $data['href']); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setVariable("USED", ($data['used']) ? $lng->txt("used") : $lng->txt("not_used")); - $this->tpl->setVariable("SENT", ($data['sent']) ? '✓' : ''); - $this->tpl->setVariable("USED_CLASS", ($data['used']) ? ' smallgreen' : ' smallred'); - $this->tpl->setVariable("DATE", ilDatePresentation::formatDate(new ilDateTime($data['date'], IL_CAL_UNIX))); - $this->tpl->setVariable("CODE", $data['code']); - $this->tpl->setVariable("EMAIL", $data['email']); - $this->tpl->setVariable("LAST_NAME", $data['last_name']); - $this->tpl->setVariable("FIRST_NAME", $data['first_name']); - } + /** + * fill row + * + * @access public + * @param + * @return + */ + public function fillRow($data) + { + $lng = $this->lng; + + $this->tpl->setVariable('CB_CODE', $data['id']); + + // :TODO: see permalink gui + if (strlen($data['href'])) { + $this->tpl->setCurrentBlock('url'); + $this->tpl->setVariable("URL", $lng->txt("survey_code_url_name")); + $this->tpl->setVariable("HREF", $data['href']); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setVariable("USED", ($data['used']) ? $lng->txt("used") : $lng->txt("not_used")); + $this->tpl->setVariable("SENT", ($data['sent']) ? '✓' : ''); + $this->tpl->setVariable("USED_CLASS", ($data['used']) ? ' smallgreen' : ' smallred'); + $this->tpl->setVariable("DATE", ilDatePresentation::formatDate(new ilDateTime($data['date'], IL_CAL_UNIX))); + $this->tpl->setVariable("CODE", $data['code']); + $this->tpl->setVariable("EMAIL", $data['email']); + $this->tpl->setVariable("LAST_NAME", $data['last_name']); + $this->tpl->setVariable("FIRST_NAME", $data['first_name']); + } } -?> \ No newline at end of file diff --git a/Modules/Survey/classes/tables/class.ilSurveyInvitedUsersTableGUI.php b/Modules/Survey/classes/tables/class.ilSurveyInvitedUsersTableGUI.php index 65dbc6f2206313987467e409d3d7a73dbb356078..75a2ac0c908c3a39308546138fbf2a6071ac711f 100644 --- a/Modules/Survey/classes/tables/class.ilSurveyInvitedUsersTableGUI.php +++ b/Modules/Survey/classes/tables/class.ilSurveyInvitedUsersTableGUI.php @@ -33,65 +33,64 @@ include_once('./Services/Table/classes/class.ilTable2GUI.php'); class ilSurveyInvitedUsersTableGUI extends ilTable2GUI { - /** - * Constructor - * - * @access public - * @param - * @return - */ - public function __construct($a_parent_obj, $a_parent_cmd) - { - global $DIC; + /** + * Constructor + * + * @access public + * @param + * @return + */ + public function __construct($a_parent_obj, $a_parent_cmd) + { + global $DIC; - parent::__construct($a_parent_obj, $a_parent_cmd); + parent::__construct($a_parent_obj, $a_parent_cmd); - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); - $this->lng = $lng; - $this->ctrl = $ilCtrl; - $this->counter = 1; - - $this->setFormName('invitedusers'); - $this->setStyle('table', 'fullwidth'); + $this->lng = $lng; + $this->ctrl = $ilCtrl; + $this->counter = 1; + + $this->setFormName('invitedusers'); + $this->setStyle('table', 'fullwidth'); - $this->addColumn('','f','1%'); - $this->addColumn($this->lng->txt("login"),'login', ''); - $this->addColumn($this->lng->txt("firstname"),'firstname', ''); - $this->addColumn($this->lng->txt("lastname"),'lastname', ''); - - $this->setTitle($this->lng->txt('invited_users'), 'icon_usr.svg', $this->lng->txt('usr')); - - $this->setRowTemplate("tpl.il_svy_svy_invite_users_row.html", "Modules/Survey"); + $this->addColumn('', 'f', '1%'); + $this->addColumn($this->lng->txt("login"), 'login', ''); + $this->addColumn($this->lng->txt("firstname"), 'firstname', ''); + $this->addColumn($this->lng->txt("lastname"), 'lastname', ''); + + $this->setTitle($this->lng->txt('invited_users'), 'icon_usr.svg', $this->lng->txt('usr')); + + $this->setRowTemplate("tpl.il_svy_svy_invite_users_row.html", "Modules/Survey"); - $this->addMultiCommand('disinviteUserGroup', $this->lng->txt('disinvite')); + $this->addMultiCommand('disinviteUserGroup', $this->lng->txt('disinvite')); - $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); - $this->setDefaultOrderField("login"); - $this->setDefaultOrderDirection("asc"); - $this->setPrefix('user_select'); - $this->setSelectAllCheckbox('user_select'); - - $this->enable('header'); - $this->disable('sort'); - $this->enable('select_all'); - } + $this->setDefaultOrderField("login"); + $this->setDefaultOrderDirection("asc"); + $this->setPrefix('user_select'); + $this->setSelectAllCheckbox('user_select'); + + $this->enable('header'); + $this->disable('sort'); + $this->enable('select_all'); + } - /** - * fill row - * - * @access public - * @param - * @return - */ - public function fillRow($data) - { - $this->tpl->setVariable("USER_ID", $data['usr_id']); - $this->tpl->setVariable("LOGIN", $data['login']); - $this->tpl->setVariable("FIRSTNAME", $data['firstname']); - $this->tpl->setVariable("LASTNAME", $data['lastname']); - } + /** + * fill row + * + * @access public + * @param + * @return + */ + public function fillRow($data) + { + $this->tpl->setVariable("USER_ID", $data['usr_id']); + $this->tpl->setVariable("LOGIN", $data['login']); + $this->tpl->setVariable("FIRSTNAME", $data['firstname']); + $this->tpl->setVariable("LASTNAME", $data['lastname']); + } } -?> \ No newline at end of file diff --git a/Modules/Survey/classes/tables/class.ilSurveyMaintenanceTableGUI.php b/Modules/Survey/classes/tables/class.ilSurveyMaintenanceTableGUI.php index 491e92663d4e1b74fef44e527e1efa4ebe633ae8..395fd701cd789bb48df9bbe642be8228842366a8 100644 --- a/Modules/Survey/classes/tables/class.ilSurveyMaintenanceTableGUI.php +++ b/Modules/Survey/classes/tables/class.ilSurveyMaintenanceTableGUI.php @@ -33,137 +33,116 @@ include_once('./Services/Table/classes/class.ilTable2GUI.php'); class ilSurveyMaintenanceTableGUI extends ilTable2GUI { - protected $counter; - protected $confirmdelete; - - /** - * Constructor - * - * @access public - * @param - * @return - */ - public function __construct($a_parent_obj, $a_parent_cmd, $confirmdelete = false) - { - global $DIC; + protected $counter; + protected $confirmdelete; + + /** + * Constructor + * + * @access public + * @param + * @return + */ + public function __construct($a_parent_obj, $a_parent_cmd, $confirmdelete = false) + { + global $DIC; - parent::__construct($a_parent_obj, $a_parent_cmd); + parent::__construct($a_parent_obj, $a_parent_cmd); - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); - $this->lng = $lng; - $this->ctrl = $ilCtrl; - $this->counter = 1; - $this->confirmdelete = $confirmdelete; - - $this->setFormName('maintenanceform'); - $this->setStyle('table', 'fullwidth'); + $this->lng = $lng; + $this->ctrl = $ilCtrl; + $this->counter = 1; + $this->confirmdelete = $confirmdelete; + + $this->setFormName('maintenanceform'); + $this->setStyle('table', 'fullwidth'); - if (!$confirmdelete) - { - $this->addColumn('','','1%', true); - } - $this->addColumn($this->lng->txt("name"),'name', ''); - $this->addColumn($this->lng->txt("login"),'login', ''); - $this->addColumn($this->lng->txt("last_access"),'last_access', ''); - $this->addColumn($this->lng->txt("workingtime"),'workingtime', ''); - $this->addColumn($this->lng->txt("survey_results_finished"),'finished', ''); - - $this->setRowTemplate("tpl.il_svy_svy_maintenance_row.html", "Modules/Survey"); + if (!$confirmdelete) { + $this->addColumn('', '', '1%', true); + } + $this->addColumn($this->lng->txt("name"), 'name', ''); + $this->addColumn($this->lng->txt("login"), 'login', ''); + $this->addColumn($this->lng->txt("last_access"), 'last_access', ''); + $this->addColumn($this->lng->txt("workingtime"), 'workingtime', ''); + $this->addColumn($this->lng->txt("survey_results_finished"), 'finished', ''); + + $this->setRowTemplate("tpl.il_svy_svy_maintenance_row.html", "Modules/Survey"); - if ($confirmdelete) - { - $this->addCommandButton('confirmDeleteSelectedUserData', $this->lng->txt('confirm')); - $this->addCommandButton('cancelDeleteSelectedUserData', $this->lng->txt('cancel')); - } - else - { - $this->addMultiCommand('deleteSingleUserResults', $this->lng->txt('delete_user_data')); - } + if ($confirmdelete) { + $this->addCommandButton('confirmDeleteSelectedUserData', $this->lng->txt('confirm')); + $this->addCommandButton('cancelDeleteSelectedUserData', $this->lng->txt('cancel')); + } else { + $this->addMultiCommand('deleteSingleUserResults', $this->lng->txt('delete_user_data')); + } - $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); - $this->setDefaultOrderField("name"); - $this->setDefaultOrderDirection("asc"); - - $this->setShowRowsSelector(true); - - if ($confirmdelete) - { - $this->disable('sort'); - $this->disable('select_all'); - } - else - { - $this->setPrefix('chbUser'); - $this->setSelectAllCheckbox('chbUser'); - $this->enable('sort'); - $this->enable('select_all'); - } - $this->enable('header'); - } + $this->setDefaultOrderField("name"); + $this->setDefaultOrderDirection("asc"); + + $this->setShowRowsSelector(true); + + if ($confirmdelete) { + $this->disable('sort'); + $this->disable('select_all'); + } else { + $this->setPrefix('chbUser'); + $this->setSelectAllCheckbox('chbUser'); + $this->enable('sort'); + $this->enable('select_all'); + } + $this->enable('header'); + } - /** - * fill row - * - * @access public - * @param - * @return - */ - public function fillRow($data) - { - if (!$this->confirmdelete) - { - $this->tpl->setCurrentBlock('checkbox'); - $this->tpl->setVariable("CB_USER_ID", $data['id']); - $this->tpl->parseCurrentBlock(); - } - else - { - $this->tpl->setCurrentBlock('hidden'); - $this->tpl->setVariable('HIDDEN_USER_ID', $data["id"]); - $this->tpl->parseCurrentBlock(); - } - $this->tpl->setVariable("USER_ID", $data["id"]); - $this->tpl->setVariable("VALUE_USER_NAME", $data['name']); - $this->tpl->setVariable("VALUE_USER_LOGIN", $data['login']); - $this->tpl->setVariable("LAST_ACCESS", ilDatePresentation::formatDate(new ilDateTime($data['last_access'],IL_CAL_UNIX))); - $this->tpl->setVariable("WORKINGTIME", $this->formatTime($data['workingtime'])); - - if($data["finished"] !== null) - { - if($data["finished"] !== false) - { - $finished .= ilDatePresentation::formatDate(new ilDateTime($data["finished"], IL_CAL_UNIX)); - } - else - { - $finished = "-"; - } - $this->tpl->setVariable("FINISHED", $finished); - } - else - { - $this->tpl->setVariable("FINISHED", " "); - } - } - - protected function formatTime($timeinseconds) - { - if (is_null($timeinseconds)) - { - return " "; - } - else if ($timeinseconds == 0) - { - return $this->lng->txt('not_available'); - } - else - { - return sprintf("%02d:%02d:%02d", ($timeinseconds / 3600), ($timeinseconds / 60) % 60, $timeinseconds % 60); - } - } + /** + * fill row + * + * @access public + * @param + * @return + */ + public function fillRow($data) + { + if (!$this->confirmdelete) { + $this->tpl->setCurrentBlock('checkbox'); + $this->tpl->setVariable("CB_USER_ID", $data['id']); + $this->tpl->parseCurrentBlock(); + } else { + $this->tpl->setCurrentBlock('hidden'); + $this->tpl->setVariable('HIDDEN_USER_ID', $data["id"]); + $this->tpl->parseCurrentBlock(); + } + $this->tpl->setVariable("USER_ID", $data["id"]); + $this->tpl->setVariable("VALUE_USER_NAME", $data['name']); + $this->tpl->setVariable("VALUE_USER_LOGIN", $data['login']); + $this->tpl->setVariable("LAST_ACCESS", ilDatePresentation::formatDate(new ilDateTime($data['last_access'], IL_CAL_UNIX))); + $this->tpl->setVariable("WORKINGTIME", $this->formatTime($data['workingtime'])); + + if ($data["finished"] !== null) { + if ($data["finished"] !== false) { + $finished .= ilDatePresentation::formatDate(new ilDateTime($data["finished"], IL_CAL_UNIX)); + } else { + $finished = "-"; + } + $this->tpl->setVariable("FINISHED", $finished); + } else { + $this->tpl->setVariable("FINISHED", " "); + } + } + + protected function formatTime($timeinseconds) + { + if (is_null($timeinseconds)) { + return " "; + } elseif ($timeinseconds == 0) { + return $this->lng->txt('not_available'); + } else { + return sprintf("%02d:%02d:%02d", ($timeinseconds / 3600), ($timeinseconds / 60) % 60, $timeinseconds % 60); + } + } /** * @access public @@ -172,8 +151,7 @@ class ilSurveyMaintenanceTableGUI extends ilTable2GUI */ public function numericOrdering($a_field) { - switch($a_field) - { + switch ($a_field) { case 'workingtime': return true; @@ -182,4 +160,3 @@ class ilSurveyMaintenanceTableGUI extends ilTable2GUI } } } -?> \ No newline at end of file diff --git a/Modules/Survey/classes/tables/class.ilSurveyParticipantsTableGUI.php b/Modules/Survey/classes/tables/class.ilSurveyParticipantsTableGUI.php index 3b8a6e469ef9d2bd2b9681e347a8a10bcfd81009..4f5ab2b90b5fe6b83df6580696d9541b058b737a 100644 --- a/Modules/Survey/classes/tables/class.ilSurveyParticipantsTableGUI.php +++ b/Modules/Survey/classes/tables/class.ilSurveyParticipantsTableGUI.php @@ -12,76 +12,70 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilSurveyParticipantsTableGUI extends ilTable2GUI { - public function __construct($a_parent_obj, $a_parent_cmd, ilObjSurvey $a_svy) - { - global $DIC; + public function __construct($a_parent_obj, $a_parent_cmd, ilObjSurvey $a_svy) + { + global $DIC; - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setTitle($lng->txt("svy_anonymous_participants_svy")); - - $this->addColumn($this->lng->txt("name"), "name"); - $this->addColumn($this->lng->txt("login"), "login"); - // $this->addColumn($this->lng->txt("gender"), "gender"); - $this->addColumn($this->lng->txt("status"), "status"); - - $this->setRowTemplate("tpl.il_svy_svy_participants_row.html", "Modules/Survey"); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd)); - $this->setDefaultOrderField("name"); - - $this->getItems($a_svy); - } - - protected function getItems(ilObjSurvey $a_svy) - { - $lng = $this->lng; - - $data = array(); - - foreach($a_svy->getSurveyParticipants(null, true) as $user) - { - if($user["finished"]) - { - $status = $lng->txt("survey_results_finished"); - } - else - { - $status = $lng->txt("survey_results_started"); - } - - $data[$user["login"]] = array( - "name" => $user["sortname"], - "login" => $user["login"], - "status" => $status - ); - } - - foreach($a_svy->getInvitedUsers() as $user_id) - { - $user = ilObjUser::_lookupName($user_id); - if($user["login"] && - !array_key_exists($user["login"], $data)) - { - $data[$user["login"]] = array( - "name" => $user["lastname"].", ".$user["firstname"], - "login" => $user["login"], - "status" => $lng->txt("survey_results_not_started") - ); - } - } - - $this->setData($data); - } + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setTitle($lng->txt("svy_anonymous_participants_svy")); + + $this->addColumn($this->lng->txt("name"), "name"); + $this->addColumn($this->lng->txt("login"), "login"); + // $this->addColumn($this->lng->txt("gender"), "gender"); + $this->addColumn($this->lng->txt("status"), "status"); + + $this->setRowTemplate("tpl.il_svy_svy_participants_row.html", "Modules/Survey"); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd)); + $this->setDefaultOrderField("name"); + + $this->getItems($a_svy); + } + + protected function getItems(ilObjSurvey $a_svy) + { + $lng = $this->lng; + + $data = array(); + + foreach ($a_svy->getSurveyParticipants(null, true) as $user) { + if ($user["finished"]) { + $status = $lng->txt("survey_results_finished"); + } else { + $status = $lng->txt("survey_results_started"); + } + + $data[$user["login"]] = array( + "name" => $user["sortname"], + "login" => $user["login"], + "status" => $status + ); + } + + foreach ($a_svy->getInvitedUsers() as $user_id) { + $user = ilObjUser::_lookupName($user_id); + if ($user["login"] && + !array_key_exists($user["login"], $data)) { + $data[$user["login"]] = array( + "name" => $user["lastname"] . ", " . $user["firstname"], + "login" => $user["login"], + "status" => $lng->txt("survey_results_not_started") + ); + } + } + + $this->setData($data); + } - public function fillRow($a_set) - { - $this->tpl->setVariable("NAME", $a_set["name"]); - $this->tpl->setVariable("LOGIN", $a_set["login"]); - $this->tpl->setVariable("STATUS", $a_set["status"]); - } + public function fillRow($a_set) + { + $this->tpl->setVariable("NAME", $a_set["name"]); + $this->tpl->setVariable("LOGIN", $a_set["login"]); + $this->tpl->setVariable("STATUS", $a_set["status"]); + } } diff --git a/Modules/Survey/classes/tables/class.ilSurveyQuestionblockbrowserTableGUI.php b/Modules/Survey/classes/tables/class.ilSurveyQuestionblockbrowserTableGUI.php index b7431f1f836501def8f0d5d02bf2c16321aac636..a7a0e30e80187fbad104a9ab6faf5ca02021f79f 100644 --- a/Modules/Survey/classes/tables/class.ilSurveyQuestionblockbrowserTableGUI.php +++ b/Modules/Survey/classes/tables/class.ilSurveyQuestionblockbrowserTableGUI.php @@ -33,148 +33,145 @@ include_once('./Services/Table/classes/class.ilTable2GUI.php'); class ilSurveyQuestionblockbrowserTableGUI extends ilTable2GUI { - /** - * @var ilRbacReview - */ - protected $rbacreview; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilAccessHandler - */ - protected $access; - - protected $editable = true; - protected $writeAccess = false; - protected $browsercolumns = array(); - - /** - * Constructor - * - * @access public - * @param - * @return - */ - public function __construct($a_parent_obj, $a_parent_cmd, $a_object, $a_write_access = false) - { - global $DIC; - - $this->rbacreview = $DIC->rbac()->review(); - $this->user = $DIC->user(); - $this->access = $DIC->access(); - parent::__construct($a_parent_obj, $a_parent_cmd); - - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - - $this->lng = $lng; - $this->ctrl = $ilCtrl; - - $this->setWriteAccess($a_write_access); - - $this->setFormName('surveyquestionblockbrowser'); - $this->setStyle('table', 'fullwidth'); - $this->addColumn('','f','1%'); - $this->addColumn($this->lng->txt("title"),'title', ''); - $this->addColumn($this->lng->txt("contains"),'contains', ''); - $this->addColumn($this->lng->txt("obj_svy"),'svy', ''); - - $this->setPrefix('cb'); - $this->setSelectAllCheckbox('cb'); - - $this->addMultiCommand('insertQuestionblocks', $this->lng->txt('insert')); - - $this->setRowTemplate("tpl.il_svy_svy_questionblockbrowser_row.html", "Modules/Survey"); - - $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); - $this->setDefaultOrderField("title"); - $this->setDefaultOrderDirection("asc"); - - $this->enable('sort'); - $this->enable('header'); - $this->enable('select_all'); - $this->setFilterCommand('filterQuestionblockBrowser'); - $this->setResetCommand('resetfilterQuestionblockBrowser'); - - $this->initFilter(); - $this->initData($a_object); - } - - function initData($a_object) - { - $arrFilter = array(); - foreach ($this->getFilterItems() as $item) - { - if ($item->getValue() !== false) - { - $arrFilter[$item->getPostVar()] = $item->getValue(); - } - } - $data = $a_object->getQuestionblocksTable($arrFilter); - - $this->setData($data); - } - - /** - * Init filter - */ - function initFilter() - { - $lng = $this->lng; - $rbacreview = $this->rbacreview; - $ilUser = $this->user; - - // title - include_once("./Services/Form/classes/class.ilTextInputGUI.php"); - $ti = new ilTextInputGUI($lng->txt("title"), "title"); - $ti->setMaxLength(64); - $ti->setSize(20); - $ti->setValidationRegexp('/^[^%]+$/is'); - $this->addFilterItem($ti); - $ti->readFromSession(); - $this->filter["title"] = $ti->getValue(); - } - - /** - * fill row - * - * @access public - * @param - * @return - */ - public function fillRow($data) - { - $ilUser = $this->user; - $ilAccess = $this->access; - - $this->tpl->setVariable('QUESTIONBLOCK_ID', $data["questionblock_id"]); - $this->tpl->setVariable("TITLE", ilUtil::prepareFormOutput($data["title"])); - $this->tpl->setVariable("CONTAINS", ilUtil::prepareFormOutput($data["contains"])); - $this->tpl->setVariable("SVY", ilUtil::prepareFormOutput($data['svy'])); - } - - public function setEditable($value) - { - $this->editable = $value; - } - - public function getEditable() - { - return $this->editable; - } - - public function setWriteAccess($value) - { - $this->writeAccess = $value; - } - - public function getWriteAccess() - { - return $this->writeAccess; - } + /** + * @var ilRbacReview + */ + protected $rbacreview; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilAccessHandler + */ + protected $access; + + protected $editable = true; + protected $writeAccess = false; + protected $browsercolumns = array(); + + /** + * Constructor + * + * @access public + * @param + * @return + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_object, $a_write_access = false) + { + global $DIC; + + $this->rbacreview = $DIC->rbac()->review(); + $this->user = $DIC->user(); + $this->access = $DIC->access(); + parent::__construct($a_parent_obj, $a_parent_cmd); + + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + + $this->lng = $lng; + $this->ctrl = $ilCtrl; + + $this->setWriteAccess($a_write_access); + + $this->setFormName('surveyquestionblockbrowser'); + $this->setStyle('table', 'fullwidth'); + $this->addColumn('', 'f', '1%'); + $this->addColumn($this->lng->txt("title"), 'title', ''); + $this->addColumn($this->lng->txt("contains"), 'contains', ''); + $this->addColumn($this->lng->txt("obj_svy"), 'svy', ''); + + $this->setPrefix('cb'); + $this->setSelectAllCheckbox('cb'); + + $this->addMultiCommand('insertQuestionblocks', $this->lng->txt('insert')); + + $this->setRowTemplate("tpl.il_svy_svy_questionblockbrowser_row.html", "Modules/Survey"); + + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); + $this->setDefaultOrderField("title"); + $this->setDefaultOrderDirection("asc"); + + $this->enable('sort'); + $this->enable('header'); + $this->enable('select_all'); + $this->setFilterCommand('filterQuestionblockBrowser'); + $this->setResetCommand('resetfilterQuestionblockBrowser'); + + $this->initFilter(); + $this->initData($a_object); + } + + public function initData($a_object) + { + $arrFilter = array(); + foreach ($this->getFilterItems() as $item) { + if ($item->getValue() !== false) { + $arrFilter[$item->getPostVar()] = $item->getValue(); + } + } + $data = $a_object->getQuestionblocksTable($arrFilter); + + $this->setData($data); + } + + /** + * Init filter + */ + public function initFilter() + { + $lng = $this->lng; + $rbacreview = $this->rbacreview; + $ilUser = $this->user; + + // title + include_once("./Services/Form/classes/class.ilTextInputGUI.php"); + $ti = new ilTextInputGUI($lng->txt("title"), "title"); + $ti->setMaxLength(64); + $ti->setSize(20); + $ti->setValidationRegexp('/^[^%]+$/is'); + $this->addFilterItem($ti); + $ti->readFromSession(); + $this->filter["title"] = $ti->getValue(); + } + + /** + * fill row + * + * @access public + * @param + * @return + */ + public function fillRow($data) + { + $ilUser = $this->user; + $ilAccess = $this->access; + + $this->tpl->setVariable('QUESTIONBLOCK_ID', $data["questionblock_id"]); + $this->tpl->setVariable("TITLE", ilUtil::prepareFormOutput($data["title"])); + $this->tpl->setVariable("CONTAINS", ilUtil::prepareFormOutput($data["contains"])); + $this->tpl->setVariable("SVY", ilUtil::prepareFormOutput($data['svy'])); + } + + public function setEditable($value) + { + $this->editable = $value; + } + + public function getEditable() + { + return $this->editable; + } + + public function setWriteAccess($value) + { + $this->writeAccess = $value; + } + + public function getWriteAccess() + { + return $this->writeAccess; + } } -?> \ No newline at end of file diff --git a/Modules/Survey/classes/tables/class.ilSurveyQuestionbrowserTableGUI.php b/Modules/Survey/classes/tables/class.ilSurveyQuestionbrowserTableGUI.php index 39bfc58c72738e83b2d3c8e59d714b3981426253..93d818951a70fce131ab11537665134184c9ba1d 100644 --- a/Modules/Survey/classes/tables/class.ilSurveyQuestionbrowserTableGUI.php +++ b/Modules/Survey/classes/tables/class.ilSurveyQuestionbrowserTableGUI.php @@ -33,239 +33,232 @@ include_once('./Services/Table/classes/class.ilTable2GUI.php'); class ilSurveyQuestionbrowserTableGUI extends ilTable2GUI { - /** - * @var ilRbacReview - */ - protected $rbacreview; + /** + * @var ilRbacReview + */ + protected $rbacreview; - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - protected $editable = true; - protected $writeAccess = false; - protected $browsercolumns = array(); - protected $questionpools = null; - - /** - * Constructor - * - * @access public - * @param - * @return - */ - public function __construct($a_parent_obj, $a_parent_cmd, $a_object, $a_write_access = false) - { - global $DIC; + protected $editable = true; + protected $writeAccess = false; + protected $browsercolumns = array(); + protected $questionpools = null; + + /** + * Constructor + * + * @access public + * @param + * @return + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_object, $a_write_access = false) + { + global $DIC; - $this->rbacreview = $DIC->rbac()->review(); - $this->user = $DIC->user(); - $this->access = $DIC->access(); - parent::__construct($a_parent_obj, $a_parent_cmd); + $this->rbacreview = $DIC->rbac()->review(); + $this->user = $DIC->user(); + $this->access = $DIC->access(); + parent::__construct($a_parent_obj, $a_parent_cmd); - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); - $this->lng = $lng; - $this->ctrl = $ilCtrl; - - $this->setWriteAccess($a_write_access); + $this->lng = $lng; + $this->ctrl = $ilCtrl; + + $this->setWriteAccess($a_write_access); - $this->setFormName('surveyquestionbrowser'); - $this->setStyle('table', 'fullwidth'); - $this->addColumn('','f','1%'); - $this->addColumn($this->lng->txt("title"),'title', ''); - $this->addColumn('','preview', ''); - $this->addColumn($this->lng->txt("description"),'description', ''); - $this->addColumn($this->lng->txt("question_type"),'ttype', ''); - $this->addColumn($this->lng->txt("author"),'author', ''); - $this->addColumn($this->lng->txt("create_date"),'created', ''); - $this->addColumn($this->lng->txt("last_update"),'updated', ''); - $this->addColumn($this->lng->txt("obj_spl"),'spl', ''); + $this->setFormName('surveyquestionbrowser'); + $this->setStyle('table', 'fullwidth'); + $this->addColumn('', 'f', '1%'); + $this->addColumn($this->lng->txt("title"), 'title', ''); + $this->addColumn('', 'preview', ''); + $this->addColumn($this->lng->txt("description"), 'description', ''); + $this->addColumn($this->lng->txt("question_type"), 'ttype', ''); + $this->addColumn($this->lng->txt("author"), 'author', ''); + $this->addColumn($this->lng->txt("create_date"), 'created', ''); + $this->addColumn($this->lng->txt("last_update"), 'updated', ''); + $this->addColumn($this->lng->txt("obj_spl"), 'spl', ''); - $this->setPrefix('q_id'); - $this->setSelectAllCheckbox('q_id'); - - $this->addMultiCommand('insertQuestions', $this->lng->txt('insert')); + $this->setPrefix('q_id'); + $this->setSelectAllCheckbox('q_id'); + + $this->addMultiCommand('insertQuestions', $this->lng->txt('insert')); - $this->setRowTemplate("tpl.il_svy_svy_questionbrowser_row.html", "Modules/Survey"); + $this->setRowTemplate("tpl.il_svy_svy_questionbrowser_row.html", "Modules/Survey"); - $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); - $this->setDefaultOrderField("title"); - $this->setDefaultOrderDirection("asc"); - include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"; - $this->questionpools = ilObjSurveyQuestionPool::_getAvailableQuestionpools(true, false, true); - - $this->enable('sort'); - $this->enable('header'); - $this->enable('select_all'); - $this->setFilterCommand('filterQuestionBrowser'); - $this->setResetCommand('resetfilterQuestionBrowser'); + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); + $this->setDefaultOrderField("title"); + $this->setDefaultOrderDirection("asc"); + include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"; + $this->questionpools = ilObjSurveyQuestionPool::_getAvailableQuestionpools(true, false, true); + + $this->enable('sort'); + $this->enable('header'); + $this->enable('select_all'); + $this->setFilterCommand('filterQuestionBrowser'); + $this->setResetCommand('resetfilterQuestionBrowser'); - $this->initFilter(); - $this->initData($a_object); - } - - function initData($a_object) - { - $arrFilter = array(); - foreach ($this->getFilterItems() as $item) - { - if ($item->getValue() !== false) - { - $arrFilter[$item->getPostVar()] = $item->getValue(); - } - } - $data = $a_object->getQuestionsTable($arrFilter); - - // translate pools for proper sorting - if(sizeof($data)) - { - $pools = $this->getQuestionPools(); - foreach($data as $idx => $row) - { - $data[$idx]["spl"] = $pools[$row["obj_fi"]]; - } - } - - $this->setData($data); - } - - function getQuestionPools() - { - return $this->questionpools; - } + $this->initFilter(); + $this->initData($a_object); + } + + public function initData($a_object) + { + $arrFilter = array(); + foreach ($this->getFilterItems() as $item) { + if ($item->getValue() !== false) { + $arrFilter[$item->getPostVar()] = $item->getValue(); + } + } + $data = $a_object->getQuestionsTable($arrFilter); + + // translate pools for proper sorting + if (sizeof($data)) { + $pools = $this->getQuestionPools(); + foreach ($data as $idx => $row) { + $data[$idx]["spl"] = $pools[$row["obj_fi"]]; + } + } + + $this->setData($data); + } + + public function getQuestionPools() + { + return $this->questionpools; + } - /** - * Init filter - */ - function initFilter() - { - $lng = $this->lng; - $rbacreview = $this->rbacreview; - $ilUser = $this->user; - - // title - include_once("./Services/Form/classes/class.ilTextInputGUI.php"); - $ti = new ilTextInputGUI($lng->txt("survey_question_title"), "title"); - $ti->setMaxLength(64); - $ti->setValidationRegexp('/^[^%]+$/is'); - $ti->setSize(20); - $this->addFilterItem($ti); - $ti->readFromSession(); - $this->filter["title"] = $ti->getValue(); - - // description - $ti = new ilTextInputGUI($lng->txt("description"), "description"); - $ti->setMaxLength(64); - $ti->setValidationRegexp('/^[^%]+$/is'); - $ti->setSize(20); - $this->addFilterItem($ti); - $ti->readFromSession(); - $this->filter["description"] = $ti->getValue(); - - // author - $ti = new ilTextInputGUI($lng->txt("author"), "author"); - $ti->setMaxLength(64); - $ti->setValidationRegexp('/^[^%]+$/is'); - $ti->setSize(20); - $this->addFilterItem($ti); - $ti->readFromSession(); - $this->filter["author"] = $ti->getValue(); - - // questiontype - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - include_once("./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"); - $types = ilObjSurveyQuestionPool::_getQuestionTypes(); - $options = array(); - $options[""] = $lng->txt('filter_all_question_types'); - foreach ($types as $translation => $row) - { - $options[$row['type_tag']] = $translation; - } + /** + * Init filter + */ + public function initFilter() + { + $lng = $this->lng; + $rbacreview = $this->rbacreview; + $ilUser = $this->user; + + // title + include_once("./Services/Form/classes/class.ilTextInputGUI.php"); + $ti = new ilTextInputGUI($lng->txt("survey_question_title"), "title"); + $ti->setMaxLength(64); + $ti->setValidationRegexp('/^[^%]+$/is'); + $ti->setSize(20); + $this->addFilterItem($ti); + $ti->readFromSession(); + $this->filter["title"] = $ti->getValue(); + + // description + $ti = new ilTextInputGUI($lng->txt("description"), "description"); + $ti->setMaxLength(64); + $ti->setValidationRegexp('/^[^%]+$/is'); + $ti->setSize(20); + $this->addFilterItem($ti); + $ti->readFromSession(); + $this->filter["description"] = $ti->getValue(); + + // author + $ti = new ilTextInputGUI($lng->txt("author"), "author"); + $ti->setMaxLength(64); + $ti->setValidationRegexp('/^[^%]+$/is'); + $ti->setSize(20); + $this->addFilterItem($ti); + $ti->readFromSession(); + $this->filter["author"] = $ti->getValue(); + + // questiontype + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + include_once("./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"); + $types = ilObjSurveyQuestionPool::_getQuestionTypes(); + $options = array(); + $options[""] = $lng->txt('filter_all_question_types'); + foreach ($types as $translation => $row) { + $options[$row['type_tag']] = $translation; + } - $si = new ilSelectInputGUI($this->lng->txt("question_type"), "type"); - $si->setOptions($options); - $this->addFilterItem($si); - $si->readFromSession(); - $this->filter["type"] = $si->getValue(); - - - // questionpool text - $ti = new ilTextInputGUI($lng->txt("survey_question_pool_title"), "spl_txt"); - $ti->setMaxLength(64); - $ti->setSize(20); - $this->addFilterItem($ti); - $ti->readFromSession(); - $this->filter["spl_txt"] = $ti->getValue(); - - // questionpool select - $options = array(); - $options[""] = $lng->txt('filter_all_questionpools'); - natcasesort($this->questionpools); - foreach ($this->questionpools as $obj_id => $title) - { - $options[$obj_id] = $title; - } - $si = new ilSelectInputGUI($this->lng->txt("survey_available_question_pools"), "spl"); - $si->setOptions($options); - $this->addFilterItem($si); - $si->readFromSession(); - $this->filter["type"] = $si->getValue(); - } - - /** - * fill row - * - * @access public - * @param - * @return - */ - public function fillRow($data) - { - $ilUser = $this->user; - $ilAccess = $this->access; - - $this->tpl->setVariable('QUESTION_ID', $data["question_id"]); - $this->tpl->setVariable("QUESTION_TITLE", ilUtil::prepareFormOutput($data["title"])); + $si = new ilSelectInputGUI($this->lng->txt("question_type"), "type"); + $si->setOptions($options); + $this->addFilterItem($si); + $si->readFromSession(); + $this->filter["type"] = $si->getValue(); + + + // questionpool text + $ti = new ilTextInputGUI($lng->txt("survey_question_pool_title"), "spl_txt"); + $ti->setMaxLength(64); + $ti->setSize(20); + $this->addFilterItem($ti); + $ti->readFromSession(); + $this->filter["spl_txt"] = $ti->getValue(); + + // questionpool select + $options = array(); + $options[""] = $lng->txt('filter_all_questionpools'); + natcasesort($this->questionpools); + foreach ($this->questionpools as $obj_id => $title) { + $options[$obj_id] = $title; + } + $si = new ilSelectInputGUI($this->lng->txt("survey_available_question_pools"), "spl"); + $si->setOptions($options); + $this->addFilterItem($si); + $si->readFromSession(); + $this->filter["type"] = $si->getValue(); + } + + /** + * fill row + * + * @access public + * @param + * @return + */ + public function fillRow($data) + { + $ilUser = $this->user; + $ilAccess = $this->access; + + $this->tpl->setVariable('QUESTION_ID', $data["question_id"]); + $this->tpl->setVariable("QUESTION_TITLE", ilUtil::prepareFormOutput($data["title"])); - $this->tpl->setVariable("TXT_PREVIEW", $this->lng->txt("preview")); - $guiclass = strtolower($data['type_tag']) . "gui"; - $this->ctrl->setParameterByClass($guiclass, "q_id", $data["question_id"]); - $this->tpl->setVariable("LINK_PREVIEW", "ilias.php?baseClass=ilObjSurveyQuestionPoolGUI&ref_id=" . $data["ref_id"] . "&cmd=preview&preview=" . $data["question_id"]); + $this->tpl->setVariable("TXT_PREVIEW", $this->lng->txt("preview")); + $guiclass = strtolower($data['type_tag']) . "gui"; + $this->ctrl->setParameterByClass($guiclass, "q_id", $data["question_id"]); + $this->tpl->setVariable("LINK_PREVIEW", "ilias.php?baseClass=ilObjSurveyQuestionPoolGUI&ref_id=" . $data["ref_id"] . "&cmd=preview&preview=" . $data["question_id"]); - $this->tpl->setVariable("QUESTION_DESCRIPTION", ilUtil::prepareFormOutput((strlen($data["description"])) ? $data["description"] : "")); - $this->tpl->setVariable("QUESTION_TYPE", $data["ttype"]); - $this->tpl->setVariable("QUESTION_AUTHOR", ilUtil::prepareFormOutput($data["author"])); - $this->tpl->setVariable("QUESTION_CREATED", ilDatePresentation::formatDate(new ilDate($data['created'],IL_CAL_UNIX))); - $this->tpl->setVariable("QUESTION_UPDATED", ilDatePresentation::formatDate(new ilDate($data["tstamp"],IL_CAL_UNIX))); - $this->tpl->setVariable("QPL", ilUtil::prepareFormOutput($data["spl"])); - } - - public function setEditable($value) - { - $this->editable = $value; - } - - public function getEditable() - { - return $this->editable; - } + $this->tpl->setVariable("QUESTION_DESCRIPTION", ilUtil::prepareFormOutput((strlen($data["description"])) ? $data["description"] : "")); + $this->tpl->setVariable("QUESTION_TYPE", $data["ttype"]); + $this->tpl->setVariable("QUESTION_AUTHOR", ilUtil::prepareFormOutput($data["author"])); + $this->tpl->setVariable("QUESTION_CREATED", ilDatePresentation::formatDate(new ilDate($data['created'], IL_CAL_UNIX))); + $this->tpl->setVariable("QUESTION_UPDATED", ilDatePresentation::formatDate(new ilDate($data["tstamp"], IL_CAL_UNIX))); + $this->tpl->setVariable("QPL", ilUtil::prepareFormOutput($data["spl"])); + } + + public function setEditable($value) + { + $this->editable = $value; + } + + public function getEditable() + { + return $this->editable; + } - public function setWriteAccess($value) - { - $this->writeAccess = $value; - } - - public function getWriteAccess() - { - return $this->writeAccess; - } + public function setWriteAccess($value) + { + $this->writeAccess = $value; + } + + public function getWriteAccess() + { + return $this->writeAccess; + } } -?> \ No newline at end of file diff --git a/Modules/Survey/classes/tables/class.ilSurveyResultsCumulatedTableGUI.php b/Modules/Survey/classes/tables/class.ilSurveyResultsCumulatedTableGUI.php index 95bc605b7460ab7707d641fda9c98b3181c9669c..19877da725ff7298854f4059544e99b44677db93 100644 --- a/Modules/Survey/classes/tables/class.ilSurveyResultsCumulatedTableGUI.php +++ b/Modules/Survey/classes/tables/class.ilSurveyResultsCumulatedTableGUI.php @@ -33,236 +33,237 @@ include_once('./Services/Table/classes/class.ilTable2GUI.php'); class ilSurveyResultsCumulatedTableGUI extends ilTable2GUI { - /** - * Constructor - * - * @access public - * @param - * @return - */ - public function __construct($a_parent_obj, $a_parent_cmd, array $a_results) - { - global $DIC; + /** + * Constructor + * + * @access public + * @param + * @return + */ + public function __construct($a_parent_obj, $a_parent_cmd, array $a_results) + { + global $DIC; - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); - $this->setId("svy_cum"); - parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setId("svy_cum"); + parent::__construct($a_parent_obj, $a_parent_cmd); - $this->lng = $lng; - $this->ctrl = $ilCtrl; - - $this->addColumn($this->lng->txt("title")); - foreach ($this->getSelectedColumns() as $c) - { - if (strcmp($c, 'question') == 0) $this->addColumn($this->lng->txt("question")); - if (strcmp($c, 'question_type') == 0) $this->addColumn($this->lng->txt("question_type")); - if (strcmp($c, 'users_answered') == 0) $this->addColumn($this->lng->txt("users_answered")); - if (strcmp($c, 'users_skipped') == 0) $this->addColumn($this->lng->txt("users_skipped")); - if (strcmp($c, 'mode') == 0) $this->addColumn($this->lng->txt("mode")); - if (strcmp($c, 'mode_nr_of_selections') == 0) $this->addColumn($this->lng->txt("mode_nr_of_selections")); - if (strcmp($c, 'median') == 0) $this->addColumn($this->lng->txt("median")); - if (strcmp($c, 'arithmetic_mean') == 0) $this->addColumn($this->lng->txt("arithmetic_mean")); - } - - $this->setRowTemplate("tpl.il_svy_svy_results_cumulated_row.html", "Modules/Survey"); - $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); - $this->setShowRowsSelector(false); + $this->lng = $lng; + $this->ctrl = $ilCtrl; + + $this->addColumn($this->lng->txt("title")); + foreach ($this->getSelectedColumns() as $c) { + if (strcmp($c, 'question') == 0) { + $this->addColumn($this->lng->txt("question")); + } + if (strcmp($c, 'question_type') == 0) { + $this->addColumn($this->lng->txt("question_type")); + } + if (strcmp($c, 'users_answered') == 0) { + $this->addColumn($this->lng->txt("users_answered")); + } + if (strcmp($c, 'users_skipped') == 0) { + $this->addColumn($this->lng->txt("users_skipped")); + } + if (strcmp($c, 'mode') == 0) { + $this->addColumn($this->lng->txt("mode")); + } + if (strcmp($c, 'mode_nr_of_selections') == 0) { + $this->addColumn($this->lng->txt("mode_nr_of_selections")); + } + if (strcmp($c, 'median') == 0) { + $this->addColumn($this->lng->txt("median")); + } + if (strcmp($c, 'arithmetic_mean') == 0) { + $this->addColumn($this->lng->txt("arithmetic_mean")); + } + } + + $this->setRowTemplate("tpl.il_svy_svy_results_cumulated_row.html", "Modules/Survey"); + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); + $this->setShowRowsSelector(false); - $this->getItems($a_results); - } + $this->getItems($a_results); + } - function getSelectableColumns() - { - $lng = $this->lng; - $cols["question"] = array( - "txt" => $lng->txt("question"), - "default" => true - ); - $cols["question_type"] = array( - "txt" => $lng->txt("question_type"), - "default" => true - ); - $cols["users_answered"] = array( - "txt" => $lng->txt("users_answered"), - "default" => true - ); - $cols["users_skipped"] = array( - "txt" => $lng->txt("users_skipped"), - "default" => true - ); - $cols["mode"] = array( - "txt" => $lng->txt("mode"), - "default" => false - ); - $cols["mode_nr_of_selections"] = array( - "txt" => $lng->txt("mode_nr_of_selections"), - "default" => false - ); - $cols["median"] = array( - "txt" => $lng->txt("median"), - "default" => true - ); - $cols["arithmetic_mean"] = array( - "txt" => $lng->txt("arithmetic_mean"), - "default" => true - ); - return $cols; - } - - protected function getItems(array $a_results) - { - $data = array(); - - foreach($a_results as $question_res) - { - /* :TODO: - $maxlen = 75; - include_once "./Services/Utilities/classes/class.ilStr.php"; - if (ilStr::strlen($questiontext) > $maxlen + 3) - { - $questiontext = ilStr::substr($questiontext, 0, $maxlen) . "..."; - } - */ - - if(!is_array($question_res)) - { - $question = $question_res->getQuestion(); - - $data[] = array( - "title" => $question->getTitle(), - "question" => strip_tags($question->getQuestiontext()), - "question_type" => SurveyQuestion::_getQuestionTypeName($question->getQuestionType()), - "users_answered" => $question_res->getUsersAnswered(), - "users_skipped" => $question_res->getUsersSkipped(), - "mode" => $question_res->getModeValueAsText(), - "mode_nr_of_selections" => $question_res->getModeNrOfSelections(), - "median" => $question_res->getMedianAsText(), - "arithmetic_mean" => $question_res->getMean() - ); - } - // matrix - else - { - // :TODO: $question->getQuestiontext() ? - // :TODO: should there be overall figures? - - foreach($question_res as $idx => $item) - { - $row_title = $item[0]; - $row_res = $item[1]; - $question = $row_res->getQuestion(); - - $data[] = array( - "title" => $question->getTitle(), - "question" => $row_title, - "question_type" => SurveyQuestion::_getQuestionTypeName($question->getQuestionType()), - "users_answered" => $row_res->getUsersAnswered(), - "users_skipped" => $row_res->getUsersSkipped(), - "mode" => $row_res->getModeValueAsText(), - "mode_nr_of_selections" => $row_res->getModeNrOfSelections(), - "median" => $row_res->getMedianAsText(), - "arithmetic_mean" => $row_res->getMean() - ); - } - } - } - - $this->setData($data); - } - - public function numericOrdering($a_field) - { - return !in_array($a_field, array("question", "question_type")); - } + public function getSelectableColumns() + { + $lng = $this->lng; + $cols["question"] = array( + "txt" => $lng->txt("question"), + "default" => true + ); + $cols["question_type"] = array( + "txt" => $lng->txt("question_type"), + "default" => true + ); + $cols["users_answered"] = array( + "txt" => $lng->txt("users_answered"), + "default" => true + ); + $cols["users_skipped"] = array( + "txt" => $lng->txt("users_skipped"), + "default" => true + ); + $cols["mode"] = array( + "txt" => $lng->txt("mode"), + "default" => false + ); + $cols["mode_nr_of_selections"] = array( + "txt" => $lng->txt("mode_nr_of_selections"), + "default" => false + ); + $cols["median"] = array( + "txt" => $lng->txt("median"), + "default" => true + ); + $cols["arithmetic_mean"] = array( + "txt" => $lng->txt("arithmetic_mean"), + "default" => true + ); + return $cols; + } + + protected function getItems(array $a_results) + { + $data = array(); + + foreach ($a_results as $question_res) { + /* :TODO: + $maxlen = 75; + include_once "./Services/Utilities/classes/class.ilStr.php"; + if (ilStr::strlen($questiontext) > $maxlen + 3) + { + $questiontext = ilStr::substr($questiontext, 0, $maxlen) . "..."; + } + */ + + if (!is_array($question_res)) { + $question = $question_res->getQuestion(); + + $data[] = array( + "title" => $question->getTitle(), + "question" => strip_tags($question->getQuestiontext()), + "question_type" => SurveyQuestion::_getQuestionTypeName($question->getQuestionType()), + "users_answered" => $question_res->getUsersAnswered(), + "users_skipped" => $question_res->getUsersSkipped(), + "mode" => $question_res->getModeValueAsText(), + "mode_nr_of_selections" => $question_res->getModeNrOfSelections(), + "median" => $question_res->getMedianAsText(), + "arithmetic_mean" => $question_res->getMean() + ); + } + // matrix + else { + // :TODO: $question->getQuestiontext() ? + // :TODO: should there be overall figures? + + foreach ($question_res as $idx => $item) { + $row_title = $item[0]; + $row_res = $item[1]; + $question = $row_res->getQuestion(); + + $data[] = array( + "title" => $question->getTitle(), + "question" => $row_title, + "question_type" => SurveyQuestion::_getQuestionTypeName($question->getQuestionType()), + "users_answered" => $row_res->getUsersAnswered(), + "users_skipped" => $row_res->getUsersSkipped(), + "mode" => $row_res->getModeValueAsText(), + "mode_nr_of_selections" => $row_res->getModeNrOfSelections(), + "median" => $row_res->getMedianAsText(), + "arithmetic_mean" => $row_res->getMean() + ); + } + } + } + + $this->setData($data); + } + + public function numericOrdering($a_field) + { + return !in_array($a_field, array("question", "question_type")); + } - /** - * fill row - * - * @access public - * @param - * @return - */ - public function fillRow($data) - { - $this->tpl->setVariable("TITLE", $data['title']); - - foreach ($this->getSelectedColumns() as $c) - { - if (strcmp($c, 'question') == 0) - { - $this->tpl->setCurrentBlock('question'); - $this->tpl->setVariable("QUESTION", $data['question']); - $this->tpl->parseCurrentBlock(); - } - if (strcmp($c, 'question_type') == 0) - { - $this->tpl->setCurrentBlock('question_type'); - $this->tpl->setVariable("QUESTION_TYPE", trim($data['question_type'])); - $this->tpl->parseCurrentBlock(); - } - if (strcmp($c, 'users_answered') == 0) - { - $this->tpl->setCurrentBlock('users_answered'); - $this->tpl->setVariable("USERS_ANSWERED", trim($data['users_answered'])); - $this->tpl->parseCurrentBlock(); - } - if (strcmp($c, 'users_skipped') == 0) - { - $this->tpl->setCurrentBlock('users_skipped'); - $this->tpl->setVariable("USERS_SKIPPED", trim($data['users_skipped'])); - $this->tpl->parseCurrentBlock(); - } - if (strcmp($c, 'mode') == 0) - { - $this->tpl->setCurrentBlock('mode'); - $this->tpl->setVariable("MODE", trim($data['mode'])); - // : $this->lng->txt("survey_not_available") - $this->tpl->parseCurrentBlock(); - } - if (strcmp($c, 'mode_nr_of_selections') == 0) - { - $this->tpl->setCurrentBlock('mode_nr_of_selections'); - $this->tpl->setVariable("MODE_NR_OF_SELECTIONS", trim($data['mode_nr_of_selections'])); - // : $this->lng->txt("survey_not_available") - $this->tpl->parseCurrentBlock(); - } - if (strcmp($c, 'median') == 0) - { - $this->tpl->setCurrentBlock('median'); - $this->tpl->setVariable("MEDIAN", trim($data['median'])); - // : $this->lng->txt("survey_not_available") - $this->tpl->parseCurrentBlock(); - } - if (strcmp($c, 'arithmetic_mean') == 0) - { - $this->tpl->setCurrentBlock('arithmetic_mean'); - $this->tpl->setVariable("ARITHMETIC_MEAN", trim($data['arithmetic_mean'])); - // : $this->lng->txt("survey_not_available"); - $this->tpl->parseCurrentBlock(); - } - } - - /* - if($data["subitems"]) - { - $this->tpl->setCurrentBlock("tbl_content"); - $this->tpl->parseCurrentBlock(); - - foreach($data["subitems"] as $subitem) - { - $this->fillRow($subitem); - - $this->tpl->setCurrentBlock("tbl_content"); - $this->css_row = ($this->css_row != "tblrow1") - ? "tblrow1" - : "tblrow2"; - $this->tpl->setVariable("CSS_ROW", $this->css_row); - $this->tpl->parseCurrentBlock(); - } - } - */ - } + /** + * fill row + * + * @access public + * @param + * @return + */ + public function fillRow($data) + { + $this->tpl->setVariable("TITLE", $data['title']); + + foreach ($this->getSelectedColumns() as $c) { + if (strcmp($c, 'question') == 0) { + $this->tpl->setCurrentBlock('question'); + $this->tpl->setVariable("QUESTION", $data['question']); + $this->tpl->parseCurrentBlock(); + } + if (strcmp($c, 'question_type') == 0) { + $this->tpl->setCurrentBlock('question_type'); + $this->tpl->setVariable("QUESTION_TYPE", trim($data['question_type'])); + $this->tpl->parseCurrentBlock(); + } + if (strcmp($c, 'users_answered') == 0) { + $this->tpl->setCurrentBlock('users_answered'); + $this->tpl->setVariable("USERS_ANSWERED", trim($data['users_answered'])); + $this->tpl->parseCurrentBlock(); + } + if (strcmp($c, 'users_skipped') == 0) { + $this->tpl->setCurrentBlock('users_skipped'); + $this->tpl->setVariable("USERS_SKIPPED", trim($data['users_skipped'])); + $this->tpl->parseCurrentBlock(); + } + if (strcmp($c, 'mode') == 0) { + $this->tpl->setCurrentBlock('mode'); + $this->tpl->setVariable("MODE", trim($data['mode'])); + // : $this->lng->txt("survey_not_available") + $this->tpl->parseCurrentBlock(); + } + if (strcmp($c, 'mode_nr_of_selections') == 0) { + $this->tpl->setCurrentBlock('mode_nr_of_selections'); + $this->tpl->setVariable("MODE_NR_OF_SELECTIONS", trim($data['mode_nr_of_selections'])); + // : $this->lng->txt("survey_not_available") + $this->tpl->parseCurrentBlock(); + } + if (strcmp($c, 'median') == 0) { + $this->tpl->setCurrentBlock('median'); + $this->tpl->setVariable("MEDIAN", trim($data['median'])); + // : $this->lng->txt("survey_not_available") + $this->tpl->parseCurrentBlock(); + } + if (strcmp($c, 'arithmetic_mean') == 0) { + $this->tpl->setCurrentBlock('arithmetic_mean'); + $this->tpl->setVariable("ARITHMETIC_MEAN", trim($data['arithmetic_mean'])); + // : $this->lng->txt("survey_not_available"); + $this->tpl->parseCurrentBlock(); + } + } + + /* + if($data["subitems"]) + { + $this->tpl->setCurrentBlock("tbl_content"); + $this->tpl->parseCurrentBlock(); + + foreach($data["subitems"] as $subitem) + { + $this->fillRow($subitem); + + $this->tpl->setCurrentBlock("tbl_content"); + $this->css_row = ($this->css_row != "tblrow1") + ? "tblrow1" + : "tblrow2"; + $this->tpl->setVariable("CSS_ROW", $this->css_row); + $this->tpl->parseCurrentBlock(); + } + } + */ + } } -?> \ No newline at end of file diff --git a/Modules/Survey/classes/tables/class.ilSurveyResultsUserTableGUI.php b/Modules/Survey/classes/tables/class.ilSurveyResultsUserTableGUI.php index a9a7f83df840a28e716d76c419586035922fdb0b..09b56c5f3c3fad180890d29994e4ffa557395a93 100644 --- a/Modules/Survey/classes/tables/class.ilSurveyResultsUserTableGUI.php +++ b/Modules/Survey/classes/tables/class.ilSurveyResultsUserTableGUI.php @@ -33,117 +33,103 @@ include_once('./Services/Table/classes/class.ilTable2GUI.php'); class ilSurveyResultsUserTableGUI extends ilTable2GUI { - private $is_anonymized; - - /** - * Constructor - * - * @access public - * @param - * @return - */ - public function __construct($a_parent_obj, $a_parent_cmd, $is_anonymized) - { - global $DIC; + private $is_anonymized; + + /** + * Constructor + * + * @access public + * @param + * @return + */ + public function __construct($a_parent_obj, $a_parent_cmd, $is_anonymized) + { + global $DIC; - $this->setId("svy_usr"); - parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setId("svy_usr"); + parent::__construct($a_parent_obj, $a_parent_cmd); - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); - $this->is_anonymized = $is_anonymized; - $this->lng = $lng; - $this->ctrl = $ilCtrl; - $this->counter = 1; - - $this->setFormName('invitegroups'); - $this->setStyle('table', 'fullwidth'); + $this->is_anonymized = $is_anonymized; + $this->lng = $lng; + $this->ctrl = $ilCtrl; + $this->counter = 1; + + $this->setFormName('invitegroups'); + $this->setStyle('table', 'fullwidth'); - $this->addColumn($this->lng->txt("username"),'username', ''); - $this->addColumn($this->lng->txt("question"),'', ''); - $this->addColumn($this->lng->txt("results"),'', ''); - $this->addColumn($this->lng->txt("workingtime"),'workingtime', ''); - $this->addColumn($this->lng->txt("survey_results_finished"),'finished', ''); - - $this->setRowTemplate("tpl.il_svy_svy_results_user_row.html", "Modules/Survey"); + $this->addColumn($this->lng->txt("username"), 'username', ''); + $this->addColumn($this->lng->txt("question"), '', ''); + $this->addColumn($this->lng->txt("results"), '', ''); + $this->addColumn($this->lng->txt("workingtime"), 'workingtime', ''); + $this->addColumn($this->lng->txt("survey_results_finished"), 'finished', ''); + + $this->setRowTemplate("tpl.il_svy_svy_results_user_row.html", "Modules/Survey"); - $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); - - $this->setDefaultOrderField('username'); - - $this->setShowRowsSelector(true); + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); + + $this->setDefaultOrderField('username'); + + $this->setShowRowsSelector(true); - $this->enable('header'); - $this->disable('select_all'); - } - - protected function formatTime($timeinseconds) - { - if (is_null($timeinseconds)) - { - return " "; - } - else if ($timeinseconds == 0) - { - return $this->lng->txt('not_available'); - } - else - { - return sprintf("%02d:%02d:%02d", ($timeinseconds / 3600), ($timeinseconds / 60) % 60, $timeinseconds % 60); - } - } + $this->enable('header'); + $this->disable('select_all'); + } + + protected function formatTime($timeinseconds) + { + if (is_null($timeinseconds)) { + return " "; + } elseif ($timeinseconds == 0) { + return $this->lng->txt('not_available'); + } else { + return sprintf("%02d:%02d:%02d", ($timeinseconds / 3600), ($timeinseconds / 60) % 60, $timeinseconds % 60); + } + } - /** - * fill row - * - * @access public - * @param - * @return - */ - public function fillRow($data) - { - $this->tpl->setVariable("USERNAME", $data['username']); - $this->tpl->setVariable("QUESTION", $data['question']); - $this->tpl->setVariable("RESULTS", $data['results'] - ? implode("
", $data['results']) - : ilObjSurvey::getSurveySkippedValue()); - $this->tpl->setVariable("WORKINGTIME", $this->formatTime($data['workingtime'])); - - if($data["finished"] !== null) - { - if($data["finished"] !== false) - { - $finished .= ilDatePresentation::formatDate(new ilDateTime($data["finished"], IL_CAL_UNIX)); - } - else - { - $finished = "-"; - } - $this->tpl->setVariable("FINISHED", $finished); - } - else - { - $this->tpl->setVariable("FINISHED", " "); - } - - if($data["subitems"]) - { - $this->tpl->setCurrentBlock("tbl_content"); - $this->tpl->parseCurrentBlock(); - - foreach($data["subitems"] as $subitem) - { - $this->fillRow($subitem); - - $this->tpl->setCurrentBlock("tbl_content"); - $this->css_row = ($this->css_row != "tblrow1") - ? "tblrow1" - : "tblrow2"; - $this->tpl->setVariable("CSS_ROW", $this->css_row); - $this->tpl->parseCurrentBlock(); - } - } - } + /** + * fill row + * + * @access public + * @param + * @return + */ + public function fillRow($data) + { + $this->tpl->setVariable("USERNAME", $data['username']); + $this->tpl->setVariable("QUESTION", $data['question']); + $this->tpl->setVariable("RESULTS", $data['results'] + ? implode("
", $data['results']) + : ilObjSurvey::getSurveySkippedValue()); + $this->tpl->setVariable("WORKINGTIME", $this->formatTime($data['workingtime'])); + + if ($data["finished"] !== null) { + if ($data["finished"] !== false) { + $finished .= ilDatePresentation::formatDate(new ilDateTime($data["finished"], IL_CAL_UNIX)); + } else { + $finished = "-"; + } + $this->tpl->setVariable("FINISHED", $finished); + } else { + $this->tpl->setVariable("FINISHED", " "); + } + + if ($data["subitems"]) { + $this->tpl->setCurrentBlock("tbl_content"); + $this->tpl->parseCurrentBlock(); + + foreach ($data["subitems"] as $subitem) { + $this->fillRow($subitem); + + $this->tpl->setCurrentBlock("tbl_content"); + $this->css_row = ($this->css_row != "tblrow1") + ? "tblrow1" + : "tblrow2"; + $this->tpl->setVariable("CSS_ROW", $this->css_row); + $this->tpl->parseCurrentBlock(); + } + } + } } -?> \ No newline at end of file diff --git a/Modules/Survey/exceptions/class.ilInvalidSurveyImportFileException.php b/Modules/Survey/exceptions/class.ilInvalidSurveyImportFileException.php index e37317a7af2a2c465f168f9dd68f28fdc274c06f..6b18a249a0e0e9d9927217724fb19e13a2405a65 100644 --- a/Modules/Survey/exceptions/class.ilInvalidSurveyImportFileException.php +++ b/Modules/Survey/exceptions/class.ilInvalidSurveyImportFileException.php @@ -11,5 +11,4 @@ include_once './Services/Exceptions/classes/class.ilException.php'; */ class ilInvalidSurveyImportFileException extends ilException { - } diff --git a/Modules/Survey/exceptions/class.ilSurveyException.php b/Modules/Survey/exceptions/class.ilSurveyException.php index 9abc671ec0419dad469aaafc84a19421bab99507..fc8222b7daf0a21f7844bf165a752ea3f23c7906 100644 --- a/Modules/Survey/exceptions/class.ilSurveyException.php +++ b/Modules/Survey/exceptions/class.ilSurveyException.php @@ -1,15 +1,14 @@ - * @version $Id$ + * @version $Id$ */ class ilSurveyException extends ilException { - -} \ No newline at end of file +} diff --git a/Modules/SurveyQuestionPool/classes/class.SurveyCategories.php b/Modules/SurveyQuestionPool/classes/class.SurveyCategories.php index 6cd42d561896e31330eaf3cf825888a251ea4c32..8ee41b582f7f0c59ada06d091dd43450c8f4d083 100644 --- a/Modules/SurveyQuestionPool/classes/class.SurveyCategories.php +++ b/Modules/SurveyQuestionPool/classes/class.SurveyCategories.php @@ -1,30 +1,30 @@ * @version $Id$ * @@ -34,299 +34,279 @@ include_once "Modules/SurveyQuestionPool/classes/class.ilSurveyCategory.php"; class SurveyCategories { - /** - * @var ilLogger - */ - protected $log; + /** + * @var ilLogger + */ + protected $log; - /** - * Category container - * - * An array containing the categories of a nominal or - * ordinal question object - * - * @var array - */ - var $categories; + /** + * Category container + * + * An array containing the categories of a nominal or + * ordinal question object + * + * @var array + */ + public $categories; - /** - * Constructor - * @access public - */ - function __construct() - { - $this->categories = array(); - $this->log = ilLoggerFactory::getLogger("svy"); - } + /** + * Constructor + * @access public + */ + public function __construct() + { + $this->categories = array(); + $this->log = ilLoggerFactory::getLogger("svy"); + } -/** -* Returns the number of categories -* -* Returns the number of categories -* -* @return integer The number of contained categories -* @access public -* @see $categories -*/ - function getCategoryCount() - { - return count($this->categories); - } + /** + * Returns the number of categories + * + * Returns the number of categories + * + * @return integer The number of contained categories + * @access public + * @see $categories + */ + public function getCategoryCount() + { + return count($this->categories); + } -/** -* Adds a category at a given position -* -* Adds a category at a given position -* -* @param string $categoryname The name of the category -* @param integer $position The position of the category (starting with index 0) -* @access public -* @see $categories -*/ - function addCategoryAtPosition($categoryname, $position, $other = 0, $neutral = 0, $label = null) - { - if (array_key_exists($position, $this->categories)) - { - $head = array_slice($this->categories, 0, $position); - $tail = array_slice($this->categories, $position); - $this->categories = array_merge($head, array(new ilSurveyCategory($categoryname, $other, $neutral, $label)), $tail); - } - else - { - array_push($this->categories, new ilSurveyCategory($categoryname, $other, $neutral, $label)); - } - } - - function moveCategoryUp($index) - { - if ($index > 0) - { - $temp = $this->categories[$index-1]; - $this->categories[$index - 1] = $this->categories[$index]; - $this->categories[$index] = $temp; - } - } - - function moveCategoryDown($index) - { - if ($index < (count($this->categories)-1)) - { - $temp = $this->categories[$index+1]; - $this->categories[$index + 1] = $this->categories[$index]; - $this->categories[$index] = $temp; - } - } + /** + * Adds a category at a given position + * + * Adds a category at a given position + * + * @param string $categoryname The name of the category + * @param integer $position The position of the category (starting with index 0) + * @access public + * @see $categories + */ + public function addCategoryAtPosition($categoryname, $position, $other = 0, $neutral = 0, $label = null) + { + if (array_key_exists($position, $this->categories)) { + $head = array_slice($this->categories, 0, $position); + $tail = array_slice($this->categories, $position); + $this->categories = array_merge($head, array(new ilSurveyCategory($categoryname, $other, $neutral, $label)), $tail); + } else { + array_push($this->categories, new ilSurveyCategory($categoryname, $other, $neutral, $label)); + } + } + + public function moveCategoryUp($index) + { + if ($index > 0) { + $temp = $this->categories[$index-1]; + $this->categories[$index - 1] = $this->categories[$index]; + $this->categories[$index] = $temp; + } + } + + public function moveCategoryDown($index) + { + if ($index < (count($this->categories)-1)) { + $temp = $this->categories[$index+1]; + $this->categories[$index + 1] = $this->categories[$index]; + $this->categories[$index] = $temp; + } + } -/** -* Adds a category -* -* Adds a category -* -* @param integer $categoryname The name of the category -* @access public -* @see $categories -*/ - function addCategory($categoryname, $other = 0, $neutral = 0, $label = null, $scale = null) - { - array_push($this->categories, new ilSurveyCategory($categoryname, $other, $neutral, $label, $scale)); - } - -/** -* Adds a category array -* -* Adds a category array -* -* @param array $categories An array with categories -* @access public -* @see $categories -*/ - function addCategoryArray($categories) - { - $this->categories = array_merge($this->categories, $categories); - } - -/** -* Removes a category from the list of categories -* -* Removes a category from the list of categories -* -* @param integer $index The index of the category to be removed -* @access public -* @see $categories -*/ - function removeCategory($index) - { - unset($this->categories[$index]); - $this->categories = array_values($this->categories); - } + /** + * Adds a category + * + * Adds a category + * + * @param integer $categoryname The name of the category + * @access public + * @see $categories + */ + public function addCategory($categoryname, $other = 0, $neutral = 0, $label = null, $scale = null) + { + array_push($this->categories, new ilSurveyCategory($categoryname, $other, $neutral, $label, $scale)); + } + + /** + * Adds a category array + * + * Adds a category array + * + * @param array $categories An array with categories + * @access public + * @see $categories + */ + public function addCategoryArray($categories) + { + $this->categories = array_merge($this->categories, $categories); + } + + /** + * Removes a category from the list of categories + * + * Removes a category from the list of categories + * + * @param integer $index The index of the category to be removed + * @access public + * @see $categories + */ + public function removeCategory($index) + { + unset($this->categories[$index]); + $this->categories = array_values($this->categories); + } -/** -* Removes many categories from the list of categories -* -* Removes many categories from the list of categories -* -* @param array $array An array containing the index positions of the categories to be removed -* @access public -* @see $categories -*/ - function removeCategories($array) - { - foreach ($array as $index) - { - unset($this->categories[$index]); - } - $this->categories = array_values($this->categories); - } - -/** -* Removes a category from the list of categories -* -* Removes a category from the list of categories -* -* @param string $name The name of the category to be removed -* @access public -* @see $categories -*/ - function removeCategoryWithName($name) - { - foreach ($this->categories as $index => $category) - { - if (strcmp($category->title, $name) == 0) - { - $this->removeCategory($index); - return; - } - } - } - -/** -* Returns the name of a category for a given index -* -* Returns the name of a category for a given index -* -* @param integer $index The index of the category -* @result string Category name -* @access public -* @see $categories -*/ - function getCategory($index) - { - if (array_key_exists($index, $this->categories)) - { - return $this->categories[$index]; - } - else - { - return ""; - } - } + /** + * Removes many categories from the list of categories + * + * Removes many categories from the list of categories + * + * @param array $array An array containing the index positions of the categories to be removed + * @access public + * @see $categories + */ + public function removeCategories($array) + { + foreach ($array as $index) { + unset($this->categories[$index]); + } + $this->categories = array_values($this->categories); + } - /** - * Returns the name of a category for a given index - * - * @param integer $scale The scale of the category - * @return string Category object - */ - public function getCategoryForScale($scale) - { - foreach ($this->categories as $cat) - { - if ($cat->scale == $scale) return $cat; - } - return null; - } + /** + * Removes a category from the list of categories + * + * Removes a category from the list of categories + * + * @param string $name The name of the category to be removed + * @access public + * @see $categories + */ + public function removeCategoryWithName($name) + { + foreach ($this->categories as $index => $category) { + if (strcmp($category->title, $name) == 0) { + $this->removeCategory($index); + return; + } + } + } + + /** + * Returns the name of a category for a given index + * + * Returns the name of a category for a given index + * + * @param integer $index The index of the category + * @result string Category name + * @access public + * @see $categories + */ + public function getCategory($index) + { + if (array_key_exists($index, $this->categories)) { + return $this->categories[$index]; + } else { + return ""; + } + } -/** -* Returns the index of a category with a given name. -* -* @param string $name The name of the category -* @access public -* @see $categories -*/ - function getCategoryIndex($name) - { - foreach ($this->categories as $index => $category) - { - if (strcmp($category->title, $name) == 0) - { - return $index; - } - } - return null; - } + /** + * Returns the name of a category for a given index + * + * @param integer $scale The scale of the category + * @return string Category object + */ + public function getCategoryForScale($scale) + { + foreach ($this->categories as $cat) { + if ($cat->scale == $scale) { + return $cat; + } + } + return null; + } - /** - * Returns the index of a category - * - * @param string $category The category object - * @access public - * @see $categories - */ - function getIndex($category) - { - foreach ($this->categories as $index => $cat) - { - if ($cat == $category) - { - return $index; - } - } - return null; - } - - public function getNewScale() - { - $max = 0; - foreach ($this->categories as $index => $category) - { - if (is_object($category) && $category->scale > 0) - { - if ($category->scale > $max) $max = $category->scale; - } - } - return $max+1; - } - - function getScale($index) - { - $obj = $this->categories[$index]; - if (is_object($obj) && $obj->scale > 0) - { - $this->log->debug("getScale has scale =". $obj->scale); - return $obj->scale; - } - else - { - $obj->scale = $this->getNewScale(); - $this->log->debug("getScale needed new scale, scale =". $obj->scale); - return $obj->scale; - } - } - -/** -* Empties the categories list -* -* Empties the categories list -* -* @access public -* @see $categories -*/ - function flushCategories() - { - $this->categories = array(); - } + /** + * Returns the index of a category with a given name. + * + * @param string $name The name of the category + * @access public + * @see $categories + */ + public function getCategoryIndex($name) + { + foreach ($this->categories as $index => $category) { + if (strcmp($category->title, $name) == 0) { + return $index; + } + } + return null; + } - /** - * Get categories - * - * @param - * @return - */ - function getCategories() - { - return $this->categories; - } + /** + * Returns the index of a category + * + * @param string $category The category object + * @access public + * @see $categories + */ + public function getIndex($category) + { + foreach ($this->categories as $index => $cat) { + if ($cat == $category) { + return $index; + } + } + return null; + } + + public function getNewScale() + { + $max = 0; + foreach ($this->categories as $index => $category) { + if (is_object($category) && $category->scale > 0) { + if ($category->scale > $max) { + $max = $category->scale; + } + } + } + return $max+1; + } + + public function getScale($index) + { + $obj = $this->categories[$index]; + if (is_object($obj) && $obj->scale > 0) { + $this->log->debug("getScale has scale =" . $obj->scale); + return $obj->scale; + } else { + $obj->scale = $this->getNewScale(); + $this->log->debug("getScale needed new scale, scale =" . $obj->scale); + return $obj->scale; + } + } + + /** + * Empties the categories list + * + * Empties the categories list + * + * @access public + * @see $categories + */ + public function flushCategories() + { + $this->categories = array(); + } - + /** + * Get categories + * + * @param + * @return + */ + public function getCategories() + { + return $this->categories; + } } -?> diff --git a/Modules/SurveyQuestionPool/classes/class.SurveyMatrixQuestion.php b/Modules/SurveyQuestionPool/classes/class.SurveyMatrixQuestion.php index a40b1ac91d4ec882f61e0615bd1143a683deb42b..8f42e2066e1f5c2d70ad3d4eca7a77ee07e770e4 100755 --- a/Modules/SurveyQuestionPool/classes/class.SurveyMatrixQuestion.php +++ b/Modules/SurveyQuestionPool/classes/class.SurveyMatrixQuestion.php @@ -32,1626 +32,1550 @@ include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; * @extends SurveyQuestion * @ingroup ModulesSurveyQuestionPool */ -class SurveyMatrixQuestion extends SurveyQuestion +class SurveyMatrixQuestion extends SurveyQuestion { - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; -/** -* Columns contained in this question -* -* @var array -*/ - var $columns; - -/** -* Rows contained in this question -* -* @var array -*/ - var $rows; + /** + * Columns contained in this question + * + * @var array + */ + public $columns; + + /** + * Rows contained in this question + * + * @var array + */ + public $rows; -/** -* First bipolar adjective for ordinal matrix questions -* -* @var string -*/ - var $bipolar_adjective1; - -/** -* Second bipolar adjective for ordinal matrix questions -* -* @var string -*/ - var $bipolar_adjective2; - -/** -* Enable state of separators for matrix columns -* 1 if separators are enabled for matrix columns, 0 otherwise -* -* @var integer -*/ - var $columnSeparators; - -/** -* Enable state of separators for matrix rows -* 1 if separators are enabled for matrix rows, 0 otherwise -* -* @var integer -*/ - var $rowSeparators; + /** + * First bipolar adjective for ordinal matrix questions + * + * @var string + */ + public $bipolar_adjective1; + + /** + * Second bipolar adjective for ordinal matrix questions + * + * @var string + */ + public $bipolar_adjective2; + + /** + * Enable state of separators for matrix columns + * 1 if separators are enabled for matrix columns, 0 otherwise + * + * @var integer + */ + public $columnSeparators; + + /** + * Enable state of separators for matrix rows + * 1 if separators are enabled for matrix rows, 0 otherwise + * + * @var integer + */ + public $rowSeparators; -/** -* Enable state of a separator for the neutral column -* 1 if a separator is enabled for the neutral column, 0 otherwise -* -* @var integer -*/ - var $neutralColumnSeparator; - - /* - * Layout of the matrix question - * - * @var array - */ - var $layout; - - /* - * Use placeholders for the column titles - * - * @var boolean - */ - var $columnPlaceholders; - - /* - * Show a legend - * - * @var boolean - */ - var $legend; - - var $singleLineRowCaption; - - var $repeatColumnHeader; - - var $columnHeaderPosition; - - /* - * Use random order for rows - * - * @var boolean - */ - var $randomRows; - - var $columnOrder; - - var $columnImages; - - var $rowImages; - - var $openRows; - - -/** -* Matrix question subtype -* -* Matrix question subtype: -* 0 = Single choice -* 1 = Multiple choice -* 2 = Text -* 3 = Integer -* 4 = Double -* 5 = Date -* 6 = Time -* -* @var integer -*/ - var $subtype; + /** + * Enable state of a separator for the neutral column + * 1 if a separator is enabled for the neutral column, 0 otherwise + * + * @var integer + */ + public $neutralColumnSeparator; + + /* + * Layout of the matrix question + * + * @var array + */ + public $layout; + + /* + * Use placeholders for the column titles + * + * @var boolean + */ + public $columnPlaceholders; + + /* + * Show a legend + * + * @var boolean + */ + public $legend; + + public $singleLineRowCaption; + + public $repeatColumnHeader; + + public $columnHeaderPosition; + + /* + * Use random order for rows + * + * @var boolean + */ + public $randomRows; + + public $columnOrder; + + public $columnImages; + + public $rowImages; + + public $openRows; + + + /** + * Matrix question subtype + * + * Matrix question subtype: + * 0 = Single choice + * 1 = Multiple choice + * 2 = Text + * 3 = Integer + * 4 = Double + * 5 = Date + * 6 = Time + * + * @var integer + */ + public $subtype; -/** -* SurveyMatrixQuestion constructor -* The constructor takes possible arguments an creates an instance of the SurveyMatrixQuestion 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; + /** + * SurveyMatrixQuestion constructor + * The constructor takes possible arguments an creates an instance of the SurveyMatrixQuestion 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(); - parent::__construct($title, $description, $author, $questiontext, $owner); - - $this->subtype = 0; - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyCategories.php"; - $this->columns = new SurveyCategories(); - $this->rows = new SurveyCategories(); - $this->bipolar_adjective1 = ""; - $this->bipolar_adjective2 = ""; - $this->rowSeparators = 0; - $this->columnSeparators = 0; - $this->neutralColumnSeparator = 1; - } - -/** -* Returns the number of columns -* -* @return integer The number of contained columns -* @access public -* @see $columns -*/ - function getColumnCount() - { - return $this->columns->getCategoryCount(); - } - -/** -* Removes a column from the list of columns -* -* @param integer $index The index of the column to be removed -* @access public -* @see $columns -*/ - function removeColumn($index) - { - $this->columns->removeCategory($index); - } + $this->user = $DIC->user(); + $this->db = $DIC->database(); + parent::__construct($title, $description, $author, $questiontext, $owner); + + $this->subtype = 0; + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyCategories.php"; + $this->columns = new SurveyCategories(); + $this->rows = new SurveyCategories(); + $this->bipolar_adjective1 = ""; + $this->bipolar_adjective2 = ""; + $this->rowSeparators = 0; + $this->columnSeparators = 0; + $this->neutralColumnSeparator = 1; + } + + /** + * Returns the number of columns + * + * @return integer The number of contained columns + * @access public + * @see $columns + */ + public function getColumnCount() + { + return $this->columns->getCategoryCount(); + } + + /** + * Removes a column from the list of columns + * + * @param integer $index The index of the column to be removed + * @access public + * @see $columns + */ + public function removeColumn($index) + { + $this->columns->removeCategory($index); + } -/** -* Removes many columns from the list of columns -* -* @param array $array An array containing the index positions of the columns to be removed -* @access public -* @see $columns -*/ - function removeColumns($array) - { - $this->columns->removeCategories($array); - } + /** + * Removes many columns from the list of columns + * + * @param array $array An array containing the index positions of the columns to be removed + * @access public + * @see $columns + */ + public function removeColumns($array) + { + $this->columns->removeCategories($array); + } -/** -* Removes a column from the list of columns -* -* @param string $name The name of the column to be removed -* @access public -* @see $columns -*/ - function removeColumnWithName($name) - { - $this->columns->removeCategoryWithName($name); - } - - /** - * Return the columns - */ - public function getColumns() - { - return $this->columns; - } - -/** -* Returns the name of a column for a given index -* -* @param integer $index The index of the column -* @result array column -* @access public -* @see $columns -*/ - function getColumn($index) - { - return $this->columns->getCategory($index); - } - - function getColumnForScale($scale) - { - return $this->columns->getCategoryForScale($scale); - } + /** + * Removes a column from the list of columns + * + * @param string $name The name of the column to be removed + * @access public + * @see $columns + */ + public function removeColumnWithName($name) + { + $this->columns->removeCategoryWithName($name); + } + + /** + * Return the columns + */ + public function getColumns() + { + return $this->columns; + } + + /** + * Returns the name of a column for a given index + * + * @param integer $index The index of the column + * @result array column + * @access public + * @see $columns + */ + public function getColumn($index) + { + return $this->columns->getCategory($index); + } + + public function getColumnForScale($scale) + { + return $this->columns->getCategoryForScale($scale); + } -/** -* Returns the index of a column with a given name. -* -* @param string $name The name of the column -* @access public -* @see $columns -*/ - function getColumnIndex($name) - { - return $this->columns->getCategoryIndex($name); - } - - -/** -* Empties the columns list -* -* @access public -* @see $columns -*/ - function flushColumns() - { - $this->columns->flushCategories(); - } - -/** -* Returns the number of rows in the question -* -* @result integer The number of rows -* @access public -*/ - function getRowCount() - { - return $this->rows->getCategoryCount(); - } + /** + * Returns the index of a column with a given name. + * + * @param string $name The name of the column + * @access public + * @see $columns + */ + public function getColumnIndex($name) + { + return $this->columns->getCategoryIndex($name); + } + + + /** + * Empties the columns list + * + * @access public + * @see $columns + */ + public function flushColumns() + { + $this->columns->flushCategories(); + } + + /** + * Returns the number of rows in the question + * + * @result integer The number of rows + * @access public + */ + public function getRowCount() + { + return $this->rows->getCategoryCount(); + } -/** -* Adds a row to the question -* -* @param string $a_text The text of the row -*/ - function addRow($a_text, $a_other, $a_label) - { - $this->rows->addCategory($a_text, $a_other, 0, $a_label); - } - - /** - * Adds a row at a given position - * - * @param string $a_text The text of the row - * @param integer $a_position The row position - */ - function addRowAtPosition($a_text, $a_other, $a_position) - { - $this->rows->addCategoryAtPosition($a_text, $a_position, $a_other); - } + /** + * Adds a row to the question + * + * @param string $a_text The text of the row + */ + public function addRow($a_text, $a_other, $a_label) + { + $this->rows->addCategory($a_text, $a_other, 0, $a_label); + } + + /** + * Adds a row at a given position + * + * @param string $a_text The text of the row + * @param integer $a_position The row position + */ + public function addRowAtPosition($a_text, $a_other, $a_position) + { + $this->rows->addCategoryAtPosition($a_text, $a_position, $a_other); + } -/** -* Empties the row list -* -* @access public -* @see $rows -*/ - function flushRows() - { - $this->rows = new SurveyCategories(); - } - -/** -* Returns a specific row -* -* @param integer $a_index The index position of the row -* @access public -*/ - function getRow($a_index) - { - return $this->rows->getCategory($a_index); - } + /** + * Empties the row list + * + * @access public + * @see $rows + */ + public function flushRows() + { + $this->rows = new SurveyCategories(); + } + + /** + * Returns a specific row + * + * @param integer $a_index The index position of the row + * @access public + */ + public function getRow($a_index) + { + return $this->rows->getCategory($a_index); + } - function moveRowUp($index) - { - $this->rows->moveCategoryUp($index); - } - - function moveRowDown($index) - { - $this->rows->moveCategoryDown($index); - } - -/** -* Removes rows from the question -* -* @param array $array An array containing the index positions of the rows to be removed -* @access public -* @see $rows -*/ - function removeRows($array) - { - $this->rows->removeCategories($array); - } + public function moveRowUp($index) + { + $this->rows->moveCategoryUp($index); + } + + public function moveRowDown($index) + { + $this->rows->moveCategoryDown($index); + } + + /** + * Removes rows from the question + * + * @param array $array An array containing the index positions of the rows to be removed + * @access public + * @see $rows + */ + public function removeRows($array) + { + $this->rows->removeCategories($array); + } - /** - * Removes a row - * - * @param integer $index The index of the row to be removed - */ - public function removeRow($index) - { - $this->rows->removeCategory($index); - } + /** + * Removes a row + * + * @param integer $index The index of the row to be removed + */ + public function removeRow($index) + { + $this->rows->removeCategory($index); + } -/** -* Returns one of the bipolar adjectives -* -* @param integer $a_index The number of the bipolar adjective (0 for the first and 1 for the second adjective) -* @result string The text of the bipolar adjective -* @access public -*/ - function getBipolarAdjective($a_index) - { - switch ($a_index) - { - case 1: - return (strlen($this->bipolar_adjective2)) ? $this->bipolar_adjective2 : NULL; - break; - case 0: - default: - return (strlen($this->bipolar_adjective1)) ? $this->bipolar_adjective1 : NULL; - break; - } - return NULL; - } + /** + * Returns one of the bipolar adjectives + * + * @param integer $a_index The number of the bipolar adjective (0 for the first and 1 for the second adjective) + * @result string The text of the bipolar adjective + * @access public + */ + public function getBipolarAdjective($a_index) + { + switch ($a_index) { + case 1: + return (strlen($this->bipolar_adjective2)) ? $this->bipolar_adjective2 : null; + break; + case 0: + default: + return (strlen($this->bipolar_adjective1)) ? $this->bipolar_adjective1 : null; + break; + } + return null; + } -/** -* Sets one of the bipolar adjectives -* -* @param integer $a_index The number of the bipolar adjective (0 for the first and 1 for the second adjective) -* @param string $a_value The text of the bipolar adjective -* @access public -*/ - function setBipolarAdjective($a_index, $a_value) - { - switch ($a_index) - { - case 1: - $this->bipolar_adjective2 = $a_value; - break; - case 0: - default: - $this->bipolar_adjective1 = $a_value; - break; - } - } - -/** -* Adds a phrase to the question -* -* @param integer $phrase_id The database id of the given phrase -* @access public -*/ - function addPhrase($phrase_id) - { - $ilUser = $this->user; - $ilDB = $this->db; + /** + * Sets one of the bipolar adjectives + * + * @param integer $a_index The number of the bipolar adjective (0 for the first and 1 for the second adjective) + * @param string $a_value The text of the bipolar adjective + * @access public + */ + public function setBipolarAdjective($a_index, $a_value) + { + switch ($a_index) { + case 1: + $this->bipolar_adjective2 = $a_value; + break; + case 0: + default: + $this->bipolar_adjective1 = $a_value; + break; + } + } + + /** + * Adds a phrase to the question + * + * @param integer $phrase_id The database id of the given phrase + * @access public + */ + public function addPhrase($phrase_id) + { + $ilUser = $this->user; + $ilDB = $this->db; - $result = $ilDB->queryF("SELECT svy_category.* FROM svy_category, svy_phrase_cat WHERE svy_phrase_cat.category_fi = svy_category.category_id AND svy_phrase_cat.phrase_fi = %s AND (svy_category.owner_fi = %s OR svy_category.owner_fi = %s) ORDER BY svy_phrase_cat.sequence", - array('integer', 'integer', 'integer'), - array($phrase_id, 0, $ilUser->getId()) - ); - while ($row = $ilDB->fetchAssoc($result)) - { - $neutral = $row["neutral"]; - if (($row["defaultvalue"] == 1) && ($row["owner_fi"] == 0)) - { - $this->columns->addCategory($this->lng->txt($row["title"]), 0, $neutral); - } - else - { - $this->columns->addCategory($row["title"], 0, $neutral); - } - } - } - - /** - * 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 SurveyMatrixQuestion object from the database -* -* @param integer $id The database id of the matrix 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->setSubtype($data["subtype"]); - $this->setRowSeparators($data["row_separators"]); - $this->setNeutralColumnSeparator($data["neutral_column_separator"]); - $this->setColumnSeparators($data["column_separators"]); - $this->setColumnPlaceholders($data["column_placeholders"]); - $this->setLegend($data["legend"]); - $this->setSingleLineRowCaption($data["singleline_row_caption"]); - $this->setRepeatColumnHeader($data["repeat_column_header"]); - $this->setColumnHeaderPosition($data["column_header_position"]); - $this->setRandomRows($data["random_rows"]); - $this->setColumnOrder($data["column_order"]); - $this->setColumnImages($data["column_images"]); - $this->setRowImages($data["row_images"]); - $this->setBipolarAdjective(0, $data["bipolar_adjective1"]); - $this->setBipolarAdjective(1, $data["bipolar_adjective2"]); - $this->setLayout($data["layout"]); - $this->flushColumns(); + $result = $ilDB->queryF( + "SELECT svy_category.* FROM svy_category, svy_phrase_cat WHERE svy_phrase_cat.category_fi = svy_category.category_id AND svy_phrase_cat.phrase_fi = %s AND (svy_category.owner_fi = %s OR svy_category.owner_fi = %s) ORDER BY svy_phrase_cat.sequence", + array('integer', 'integer', 'integer'), + array($phrase_id, 0, $ilUser->getId()) + ); + while ($row = $ilDB->fetchAssoc($result)) { + $neutral = $row["neutral"]; + if (($row["defaultvalue"] == 1) && ($row["owner_fi"] == 0)) { + $this->columns->addCategory($this->lng->txt($row["title"]), 0, $neutral); + } else { + $this->columns->addCategory($row["title"], 0, $neutral); + } + } + } + + /** + * 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 SurveyMatrixQuestion object from the database + * + * @param integer $id The database id of the matrix 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->setSubtype($data["subtype"]); + $this->setRowSeparators($data["row_separators"]); + $this->setNeutralColumnSeparator($data["neutral_column_separator"]); + $this->setColumnSeparators($data["column_separators"]); + $this->setColumnPlaceholders($data["column_placeholders"]); + $this->setLegend($data["legend"]); + $this->setSingleLineRowCaption($data["singleline_row_caption"]); + $this->setRepeatColumnHeader($data["repeat_column_header"]); + $this->setColumnHeaderPosition($data["column_header_position"]); + $this->setRandomRows($data["random_rows"]); + $this->setColumnOrder($data["column_order"]); + $this->setColumnImages($data["column_images"]); + $this->setRowImages($data["row_images"]); + $this->setBipolarAdjective(0, $data["bipolar_adjective1"]); + $this->setBipolarAdjective(1, $data["bipolar_adjective2"]); + $this->setLayout($data["layout"]); + $this->flushColumns(); - $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->columns->addCategory($data["title"], $data["other"], $data["neutral"], null, ($data['scale']) ? $data['scale'] : ($data['sequence'] + 1)); - } - } - - $result = $ilDB->queryF("SELECT * FROM svy_qst_matrixrows WHERE question_fi = %s ORDER BY sequence", - array('integer'), - array($id) - ); - while ($row = $ilDB->fetchAssoc($result)) - { - $this->addRow($row["title"], $row['other'], $row['label']); - } - } - parent::loadFromDb($id); - } + $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->columns->addCategory($data["title"], $data["other"], $data["neutral"], null, ($data['scale']) ? $data['scale'] : ($data['sequence'] + 1)); + } + } + + $result = $ilDB->queryF( + "SELECT * FROM svy_qst_matrixrows WHERE question_fi = %s ORDER BY sequence", + array('integer'), + array($id) + ); + while ($row = $ilDB->fetchAssoc($result)) { + $this->addRow($row["title"], $row['other'], $row['label']); + } + } + parent::loadFromDb($id); + } -/** -* Returns 1 if the question is complete for use -* -* @result integer 1 if the question is complete for use, otherwise 0 -* @access public -*/ - function isComplete() - { - if ( - strlen($this->getTitle()) && - strlen($this->getAuthor()) && - strlen($this->getQuestiontext()) && - $this->getColumnCount() && - $this->getRowCount() - ) - { - return 1; - } - else - { - return 0; - } - } - -/** -* Saves a SurveyMatrixQuestion object to a database -* -* @access public -*/ - function saveToDb($original_id = NULL, $withanswers = true) - { - $ilDB = $this->db; + /** + * Returns 1 if the question is complete for use + * + * @result integer 1 if the question is complete for use, otherwise 0 + * @access public + */ + public function isComplete() + { + if ( + strlen($this->getTitle()) && + strlen($this->getAuthor()) && + strlen($this->getQuestiontext()) && + $this->getColumnCount() && + $this->getRowCount() + ) { + return 1; + } else { + return 0; + } + } + + /** + * Saves a SurveyMatrixQuestion object to a database + * + * @access public + */ + public function saveToDb($original_id = null, $withanswers = true) + { + $ilDB = $this->db; - $affectedRows = parent::saveToDb($original_id); + $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() . " ( + 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, column_separators, row_separators, neutral_column_separator,column_placeholders, legend, singleline_row_caption, repeat_column_header, column_header_position, random_rows, column_order, column_images, row_images, bipolar_adjective1, bipolar_adjective2, layout, tstamp) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", - array( - 'integer', 'integer', 'text', 'text', 'text', 'integer', 'text', 'text', 'text', - 'text', 'text', 'text', 'text', 'text', 'text', 'text', 'text', 'integer' - ), - array( - $this->getId(), - $this->getSubtype(), - $this->getColumnSeparators(), - $this->getRowSeparators(), - $this->getNeutralColumnSeparator(), - $this->getColumnPlaceholders(), - $this->getLegend(), - $this->getSingleLineRowCaption(), - $this->getRepeatColumnHeader(), - $this->getColumnHeaderPosition(), - $this->getRandomRows(), - $this->getColumnOrder(), - $this->getColumnImages(), - $this->getRowImages(), - $this->getBipolarAdjective(0), - $this->getBipolarAdjective(1), - serialize($this->getLayout()), - time() - ) - ); + array( + 'integer', 'integer', 'text', 'text', 'text', 'integer', 'text', 'text', 'text', + 'text', 'text', 'text', 'text', 'text', 'text', 'text', 'text', 'integer' + ), + array( + $this->getId(), + $this->getSubtype(), + $this->getColumnSeparators(), + $this->getRowSeparators(), + $this->getNeutralColumnSeparator(), + $this->getColumnPlaceholders(), + $this->getLegend(), + $this->getSingleLineRowCaption(), + $this->getRepeatColumnHeader(), + $this->getColumnHeaderPosition(), + $this->getRandomRows(), + $this->getColumnOrder(), + $this->getColumnImages(), + $this->getRowImages(), + $this->getBipolarAdjective(0), + $this->getBipolarAdjective(1), + serialize($this->getLayout()), + time() + ) + ); - // saving material uris in the database - $this->saveMaterial(); + // saving material uris in the database + $this->saveMaterial(); - $this->saveColumnsToDb(); - $this->saveRowsToDb(); - } - } - - function saveBipolarAdjectives($adjective1, $adjective2) - { - $ilDB = $this->db; - - $affectedRows = $ilDB->manipulateF("UPDATE " . $this->getAdditionalTableName() . " SET bipolar_adjective1 = %s, bipolar_adjective2 = %s WHERE question_fi = %s", - array('text', 'text', 'integer'), - array((strlen($adjective1)) ? $adjective1 : NULL, (strlen($adjective2)) ? $adjective2 : NULL, $this->getId()) - ); - } + $this->saveColumnsToDb(); + $this->saveRowsToDb(); + } + } + + public function saveBipolarAdjectives($adjective1, $adjective2) + { + $ilDB = $this->db; + + $affectedRows = $ilDB->manipulateF( + "UPDATE " . $this->getAdditionalTableName() . " SET bipolar_adjective1 = %s, bipolar_adjective2 = %s WHERE question_fi = %s", + array('text', 'text', 'integer'), + array((strlen($adjective1)) ? $adjective1 : null, (strlen($adjective2)) ? $adjective2 : null, $this->getId()) + ); + } -/** -* Saves a column to the database -* -* @param string $columntext The text of the column -* @result integer The database ID of the column -* @access public -* @see $columns -*/ - function saveColumnToDb($columntext, $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($columntext, $neutral, $ilUser->getId()) - ); - $insert = FALSE; - $returnvalue = ""; - if ($result->numRows()) - { - $insert = TRUE; - while ($row = $ilDB->fetchAssoc($result)) - { - if (strcmp($row["title"], $columntext) == 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, defaultvalue, owner_fi, neutral, tstamp) VALUES (%s, %s, %s, %s, %s, %s)", - array('integer', 'text', 'text', 'integer', 'text', 'integer'), - array($next_id, $columntext, 0, $ilUser->getId(), $neutral, time()) - ); - $returnvalue = $next_id; - } - return $returnvalue; - } + /** + * Saves a column to the database + * + * @param string $columntext The text of the column + * @result integer The database ID of the column + * @access public + * @see $columns + */ + public function saveColumnToDb($columntext, $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($columntext, $neutral, $ilUser->getId()) + ); + $insert = false; + $returnvalue = ""; + if ($result->numRows()) { + $insert = true; + while ($row = $ilDB->fetchAssoc($result)) { + if (strcmp($row["title"], $columntext) == 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, defaultvalue, owner_fi, neutral, tstamp) VALUES (%s, %s, %s, %s, %s, %s)", + array('integer', 'text', 'text', 'integer', 'text', 'integer'), + array($next_id, $columntext, 0, $ilUser->getId(), $neutral, time()) + ); + $returnvalue = $next_id; + } + return $returnvalue; + } - function saveColumnsToDb($original_id = "") - { - $ilDB = $this->db; - - // save columns - $question_id = $this->getId(); - if (strlen($original_id)) - { - $question_id = $original_id; - } - - // delete existing column relations - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_variable WHERE question_fi = %s", - array('integer'), - array($question_id) - ); - // create new column relations - for ($i = 0; $i < $this->getColumnCount(); $i++) - { - $cat = $this->getColumn($i); - $column_id = $this->saveColumnToDb($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, $column_id, $question_id, ($i + 1), $cat->other, $i, ($cat->scale > 0) ? $cat->scale : null, time()) - ); - } - $this->saveCompletionStatus($original_id); - } + public function saveColumnsToDb($original_id = "") + { + $ilDB = $this->db; + + // save columns + $question_id = $this->getId(); + if (strlen($original_id)) { + $question_id = $original_id; + } + + // delete existing column relations + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_variable WHERE question_fi = %s", + array('integer'), + array($question_id) + ); + // create new column relations + for ($i = 0; $i < $this->getColumnCount(); $i++) { + $cat = $this->getColumn($i); + $column_id = $this->saveColumnToDb($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, $column_id, $question_id, ($i + 1), $cat->other, $i, ($cat->scale > 0) ? $cat->scale : null, time()) + ); + } + $this->saveCompletionStatus($original_id); + } - function saveRowsToDb($original_id = "") - { - $ilDB = $this->db; - - // save rows - $question_id = $this->getId(); - if (strlen($original_id)) - { - $question_id = $original_id; - } + public function saveRowsToDb($original_id = "") + { + $ilDB = $this->db; + + // save rows + $question_id = $this->getId(); + if (strlen($original_id)) { + $question_id = $original_id; + } - // delete existing rows - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qst_matrixrows WHERE question_fi = %s", - array('integer'), - array($question_id) - ); - // create new rows - for ($i = 0; $i < $this->getRowCount(); $i++) - { - $row = $this->getRow($i); - $next_id = $ilDB->nextId('svy_qst_matrixrows'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qst_matrixrows (id_svy_qst_matrixrows, title, label, other, sequence, question_fi) VALUES (%s, %s, %s, %s, %s, %s)", - array('integer','text','text','integer','integer','integer'), - array($next_id, $row->title, $row->label, ($row->other) ? 1 : 0, $i, $question_id) - ); - } - $this->saveCompletionStatus($original_id); - } + // delete existing rows + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_qst_matrixrows WHERE question_fi = %s", + array('integer'), + array($question_id) + ); + // create new rows + for ($i = 0; $i < $this->getRowCount(); $i++) { + $row = $this->getRow($i); + $next_id = $ilDB->nextId('svy_qst_matrixrows'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_qst_matrixrows (id_svy_qst_matrixrows, title, label, other, sequence, question_fi) VALUES (%s, %s, %s, %s, %s, %s)", + array('integer','text','text','integer','integer','integer'), + array($next_id, $row->title, $row->label, ($row->other) ? 1 : 0, $i, $question_id) + ); + } + $this->saveCompletionStatus($original_id); + } - /** - * 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"); + /** + * 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("matrix"); - $a_xml_writer->xmlStartTag("matrixrows"); - for ($i = 0; $i < $this->getRowCount(); $i++) - { - $attrs = array( - "id" => $i - ); - if (strlen($this->getRow($i)->label)) - { - $attrs['label'] = $this->getRow($i)->label; - } - if ($this->getRow($i)->other) - { - $attrs['other'] = 1; - } - $a_xml_writer->xmlStartTag("matrixrow", $attrs); - $this->addMaterialTag($a_xml_writer, $this->getRow($i)->title); - $a_xml_writer->xmlEndTag("matrixrow"); - } - $a_xml_writer->xmlEndTag("matrixrows"); - - $a_xml_writer->xmlStartTag("responses"); - if (strlen($this->getBipolarAdjective(0)) && (strlen($this->getBipolarAdjective(1)))) - { - $a_xml_writer->xmlStartTag("bipolar_adjectives"); - $attribs = array( - "label" => "0" - ); - $a_xml_writer->xmlElement("adjective", $attribs, $this->getBipolarAdjective(0)); - $attribs = array( - "label" => "1" - ); - $a_xml_writer->xmlElement("adjective", $attribs, $this->getBipolarAdjective(1)); - $a_xml_writer->xmlEndTag("bipolar_adjectives"); - } - for ($i = 0; $i < $this->getColumnCount(); $i++) - { - $attrs = array( - "id" => $i - ); - if ($this->getColumn($i)->neutral) - { - $attrs['label'] = 'neutral'; - } - switch ($this->getSubtype()) - { - case 0: - $a_xml_writer->xmlStartTag("response_single", $attrs); - break; - case 1: - $a_xml_writer->xmlStartTag("response_multiple", $attrs); - break; - } - $this->addMaterialTag($a_xml_writer, $this->getColumn($i)->title); - switch ($this->getSubtype()) - { - case 0: - $a_xml_writer->xmlEndTag("response_single"); - break; - case 1: - $a_xml_writer->xmlEndTag("response_multiple"); - break; - } - } + $a_xml_writer->xmlStartTag("matrix"); + $a_xml_writer->xmlStartTag("matrixrows"); + for ($i = 0; $i < $this->getRowCount(); $i++) { + $attrs = array( + "id" => $i + ); + if (strlen($this->getRow($i)->label)) { + $attrs['label'] = $this->getRow($i)->label; + } + if ($this->getRow($i)->other) { + $attrs['other'] = 1; + } + $a_xml_writer->xmlStartTag("matrixrow", $attrs); + $this->addMaterialTag($a_xml_writer, $this->getRow($i)->title); + $a_xml_writer->xmlEndTag("matrixrow"); + } + $a_xml_writer->xmlEndTag("matrixrows"); + + $a_xml_writer->xmlStartTag("responses"); + if (strlen($this->getBipolarAdjective(0)) && (strlen($this->getBipolarAdjective(1)))) { + $a_xml_writer->xmlStartTag("bipolar_adjectives"); + $attribs = array( + "label" => "0" + ); + $a_xml_writer->xmlElement("adjective", $attribs, $this->getBipolarAdjective(0)); + $attribs = array( + "label" => "1" + ); + $a_xml_writer->xmlElement("adjective", $attribs, $this->getBipolarAdjective(1)); + $a_xml_writer->xmlEndTag("bipolar_adjectives"); + } + for ($i = 0; $i < $this->getColumnCount(); $i++) { + $attrs = array( + "id" => $i + ); + if ($this->getColumn($i)->neutral) { + $attrs['label'] = 'neutral'; + } + switch ($this->getSubtype()) { + case 0: + $a_xml_writer->xmlStartTag("response_single", $attrs); + break; + case 1: + $a_xml_writer->xmlStartTag("response_multiple", $attrs); + break; + } + $this->addMaterialTag($a_xml_writer, $this->getColumn($i)->title); + switch ($this->getSubtype()) { + case 0: + $a_xml_writer->xmlEndTag("response_single"); + break; + case 1: + $a_xml_writer->xmlEndTag("response_multiple"); + break; + } + } - $a_xml_writer->xmlEndTag("responses"); - $a_xml_writer->xmlEndTag("matrix"); + $a_xml_writer->xmlEndTag("responses"); + $a_xml_writer->xmlEndTag("matrix"); - 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"); - } - } + 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, "column_separators"); - $a_xml_writer->xmlElement("fieldentry", NULL, $this->getColumnSeparators()); - $a_xml_writer->xmlEndTag("metadatafield"); + $a_xml_writer->xmlStartTag("metadata"); + $a_xml_writer->xmlStartTag("metadatafield"); + $a_xml_writer->xmlElement("fieldlabel", null, "column_separators"); + $a_xml_writer->xmlElement("fieldentry", null, $this->getColumnSeparators()); + $a_xml_writer->xmlEndTag("metadatafield"); - $a_xml_writer->xmlStartTag("metadatafield"); - $a_xml_writer->xmlElement("fieldlabel", NULL, "row_separators"); - $a_xml_writer->xmlElement("fieldentry", NULL, $this->getRowSeparators()); - $a_xml_writer->xmlEndTag("metadatafield"); + $a_xml_writer->xmlStartTag("metadatafield"); + $a_xml_writer->xmlElement("fieldlabel", null, "row_separators"); + $a_xml_writer->xmlElement("fieldentry", null, $this->getRowSeparators()); + $a_xml_writer->xmlEndTag("metadatafield"); - $a_xml_writer->xmlStartTag("metadatafield"); - $a_xml_writer->xmlElement("fieldlabel", NULL, "neutral_column_separator"); - $a_xml_writer->xmlElement("fieldentry", NULL, $this->getNeutralColumnSeparator()); - $a_xml_writer->xmlEndTag("metadatafield"); + $a_xml_writer->xmlStartTag("metadatafield"); + $a_xml_writer->xmlElement("fieldlabel", null, "neutral_column_separator"); + $a_xml_writer->xmlElement("fieldentry", null, $this->getNeutralColumnSeparator()); + $a_xml_writer->xmlEndTag("metadatafield"); - $a_xml_writer->xmlStartTag("metadatafield"); - $a_xml_writer->xmlElement("fieldlabel", NULL, "layout"); - $a_xml_writer->xmlElement("fieldentry", NULL, serialize($this->getLayout())); - $a_xml_writer->xmlEndTag("metadatafield"); + $a_xml_writer->xmlStartTag("metadatafield"); + $a_xml_writer->xmlElement("fieldlabel", null, "layout"); + $a_xml_writer->xmlElement("fieldentry", null, serialize($this->getLayout())); + $a_xml_writer->xmlEndTag("metadatafield"); - $a_xml_writer->xmlEndTag("metadata"); - - $a_xml_writer->xmlEndTag("question"); - } + $a_xml_writer->xmlEndTag("metadata"); + + $a_xml_writer->xmlEndTag("question"); + } - function syncWithOriginal() - { - if ($this->getOriginalId()) - { - parent::syncWithOriginal(); - $this->saveColumnsToDb($this->getOriginalId()); - $this->saveRowsToDb($this->getOriginalId()); - } - } + public function syncWithOriginal() + { + if ($this->getOriginalId()) { + parent::syncWithOriginal(); + $this->saveColumnsToDb($this->getOriginalId()); + $this->saveRowsToDb($this->getOriginalId()); + } + } -/** -* Adds standard numbers as columns -* -* @param integer $lower_limit The lower limit -* @param integer $upper_limit The upper limit -* @access public -*/ - function addStandardNumbers($lower_limit, $upper_limit) - { - for ($i = $lower_limit; $i <= $upper_limit; $i++) - { - $this->columns->addCategory($i); - } - } + /** + * Adds standard numbers as columns + * + * @param integer $lower_limit The lower limit + * @param integer $upper_limit The upper limit + * @access public + */ + public function addStandardNumbers($lower_limit, $upper_limit) + { + for ($i = $lower_limit; $i <= $upper_limit; $i++) { + $this->columns->addCategory($i); + } + } -/** -* Saves a set of columns to a default phrase -* -* @param array $phrases The database ids of the seleted phrases -* @param string $title The title of the default phrase -* @access public -*/ - function savePhrase($title) - { - $ilUser = $this->user; - $ilDB = $this->db; + /** + * Saves a set of columns to a default phrase + * + * @param array $phrases The database ids of the seleted phrases + * @param string $title The title of the default phrase + * @access public + */ + public function savePhrase($title) + { + $ilUser = $this->user; + $ilDB = $this->db; - $next_id = $ilDB->nextId('svy_phrase'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_phrase (phrase_id, title, defaultvalue, owner_fi, tstamp) VALUES (%s, %s, %s, %s, %s)", - array('integer','text','text','integer','integer'), - array($next_id, $title, 1, $ilUser->getId(), time()) - ); - $phrase_id = $next_id; - - $counter = 1; - foreach ($_SESSION['save_phrase_data'] as $data) - { - $next_id = $ilDB->nextId('svy_category'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_category (category_id, title, defaultvalue, owner_fi, tstamp, neutral) VALUES (%s, %s, %s, %s, %s, %s)", - array('integer','text','text','integer','integer','text'), - array($next_id, $data['answer'], 1, $ilUser->getId(), time(), $data['neutral']) - ); - $category_id = $next_id; - $next_id = $ilDB->nextId('svy_phrase_cat'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_phrase_cat (phrase_category_id, phrase_fi, category_fi, sequence, other, scale) VALUES (%s, %s, %s, %s, %s, %s)", - array('integer', 'integer', 'integer','integer', 'integer', 'integer'), - array($next_id, $phrase_id, $category_id, $counter, ($data['other']) ? 1 : 0, $data['scale']) - ); - $counter++; - } - } - - /** - * Returns the question type of the question - * - * @return integer The question type of the question - * @access public - */ - function getQuestionType() - { - return "SurveyMatrixQuestion"; - } + $next_id = $ilDB->nextId('svy_phrase'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_phrase (phrase_id, title, defaultvalue, owner_fi, tstamp) VALUES (%s, %s, %s, %s, %s)", + array('integer','text','text','integer','integer'), + array($next_id, $title, 1, $ilUser->getId(), time()) + ); + $phrase_id = $next_id; + + $counter = 1; + foreach ($_SESSION['save_phrase_data'] as $data) { + $next_id = $ilDB->nextId('svy_category'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_category (category_id, title, defaultvalue, owner_fi, tstamp, neutral) VALUES (%s, %s, %s, %s, %s, %s)", + array('integer','text','text','integer','integer','text'), + array($next_id, $data['answer'], 1, $ilUser->getId(), time(), $data['neutral']) + ); + $category_id = $next_id; + $next_id = $ilDB->nextId('svy_phrase_cat'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_phrase_cat (phrase_category_id, phrase_fi, category_fi, sequence, other, scale) VALUES (%s, %s, %s, %s, %s, %s)", + array('integer', 'integer', 'integer','integer', 'integer', 'integer'), + array($next_id, $phrase_id, $category_id, $counter, ($data['other']) ? 1 : 0, $data['scale']) + ); + $counter++; + } + } + + /** + * Returns the question type of the question + * + * @return integer The question type of the question + * @access public + */ + public function getQuestionType() + { + return "SurveyMatrixQuestion"; + } - /** - * 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_matrix"; - } - - /** - * 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) - { - $data = array(); - foreach ($post_data as $key => $value) - { - switch ($this->getSubtype()) - { - case 0: - if (preg_match("/matrix_" . $this->getId() . "_(\d+)/", $key, $matches)) - { - if (is_array($value)) - { - foreach ($value as $val) - { - array_push($data, array("value" => $val, "rowvalue" => $matches[1], "textanswer" => $post_data['matrix_other_' . $this->getId() . '_' . $matches[1]])); - } - } - else - { - array_push($data, array("value" => $value, "rowvalue" => $matches[1], "textanswer" => $post_data['matrix_other_' . $this->getId() . '_' . $matches[1]])); - } - } - break; - case 1: - if (preg_match("/matrix_" . $this->getId() . "_(\d+)/", $key, $matches)) - { - if (is_array($value)) - { - foreach ($value as $val) - { - array_push($data, array("value" => $val, "rowvalue" => $matches[1], "textanswer" => $post_data['matrix_other_' . $this->getId() . '_' . $matches[1]])); - } - } - else - { - array_push($data, array("value" => $value, "rowvalue" => $matches[1], "textanswer" => $post_data['matrix_other_' . $this->getId() . '_' . $matches[1]])); - } - } - break; - } - } - 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) - { - if (!$this->getObligatory($survey_id)) return ""; - switch ($this->getSubtype()) - { - case 0: - $counter = 0; - foreach ($post_data as $key => $value) - { - if (preg_match("/matrix_" . $this->getId() . "_(\d+)/", $key, $matches)) - { - if (array_key_exists('matrix_other_' . $this->getId() . "_" . $matches[1], $post_data) && strlen($post_data['matrix_other_' . $this->getId() . "_" . $matches[1]]) == 0) - { - return $this->lng->txt("question_mr_no_other_answer"); - } - $counter++; - } - } - if ($counter != $this->getRowCount()) return $this->lng->txt("matrix_question_radio_button_not_checked"); - break; - case 1: - $counter = 0; - foreach ($post_data as $key => $value) - { - if (preg_match("/matrix_" . $this->getId() . "_(\d+)/", $key, $matches)) - { - if (array_key_exists('matrix_other_' . $this->getId() . "_" . $matches[1], $post_data) && strlen($post_data['matrix_other_' . $this->getId() . "_" . $matches[1]]) == 0) - { - return $this->lng->txt("question_mr_no_other_answer"); - } - $counter++; - if ((!is_array($value)) || (count($value) < 1)) - { - return $this->lng->txt("matrix_question_checkbox_not_checked"); - } - } - } - if ($counter != $this->getRowCount()) return $this->lng->txt("matrix_question_checkbox_not_checked"); - break; - } - return ""; - } + /** + * 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_matrix"; + } + + /** + * 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) + { + $data = array(); + foreach ($post_data as $key => $value) { + switch ($this->getSubtype()) { + case 0: + if (preg_match("/matrix_" . $this->getId() . "_(\d+)/", $key, $matches)) { + if (is_array($value)) { + foreach ($value as $val) { + array_push($data, array("value" => $val, "rowvalue" => $matches[1], "textanswer" => $post_data['matrix_other_' . $this->getId() . '_' . $matches[1]])); + } + } else { + array_push($data, array("value" => $value, "rowvalue" => $matches[1], "textanswer" => $post_data['matrix_other_' . $this->getId() . '_' . $matches[1]])); + } + } + break; + case 1: + if (preg_match("/matrix_" . $this->getId() . "_(\d+)/", $key, $matches)) { + if (is_array($value)) { + foreach ($value as $val) { + array_push($data, array("value" => $val, "rowvalue" => $matches[1], "textanswer" => $post_data['matrix_other_' . $this->getId() . '_' . $matches[1]])); + } + } else { + array_push($data, array("value" => $value, "rowvalue" => $matches[1], "textanswer" => $post_data['matrix_other_' . $this->getId() . '_' . $matches[1]])); + } + } + break; + } + } + 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) + { + if (!$this->getObligatory($survey_id)) { + return ""; + } + switch ($this->getSubtype()) { + case 0: + $counter = 0; + foreach ($post_data as $key => $value) { + if (preg_match("/matrix_" . $this->getId() . "_(\d+)/", $key, $matches)) { + if (array_key_exists('matrix_other_' . $this->getId() . "_" . $matches[1], $post_data) && strlen($post_data['matrix_other_' . $this->getId() . "_" . $matches[1]]) == 0) { + return $this->lng->txt("question_mr_no_other_answer"); + } + $counter++; + } + } + if ($counter != $this->getRowCount()) { + return $this->lng->txt("matrix_question_radio_button_not_checked"); + } + break; + case 1: + $counter = 0; + foreach ($post_data as $key => $value) { + if (preg_match("/matrix_" . $this->getId() . "_(\d+)/", $key, $matches)) { + if (array_key_exists('matrix_other_' . $this->getId() . "_" . $matches[1], $post_data) && strlen($post_data['matrix_other_' . $this->getId() . "_" . $matches[1]]) == 0) { + return $this->lng->txt("question_mr_no_other_answer"); + } + $counter++; + if ((!is_array($value)) || (count($value) < 1)) { + return $this->lng->txt("matrix_question_checkbox_not_checked"); + } + } + } + if ($counter != $this->getRowCount()) { + return $this->lng->txt("matrix_question_checkbox_not_checked"); + } + break; + } + return ""; + } - function saveUserInput($post_data, $active_id, $a_return = false) - { - $ilDB = $this->db; - - $answer_data = array(); + public function saveUserInput($post_data, $active_id, $a_return = false) + { + $ilDB = $this->db; + + $answer_data = array(); - // gather data - switch ($this->getSubtype()) - { - case 0: - foreach ($post_data as $key => $value) - { - if (preg_match("/matrix_" . $this->getId() . "_(\d+)/", $key, $matches)) - { - if(strlen($value)) - { - $other_value = (array_key_exists('matrix_other_' . $this->getId() . '_' . $matches[1], $post_data)) - ? ($post_data['matrix_other_' . $this->getId() . '_' . $matches[1]]) - : null; - $answer_data[] = array("value"=>$value, - "textanswer"=>$other_value, - "rowvalue"=>$matches[1]); - } - } - } - break; - - case 1: - foreach ($post_data as $key => $value) - { - if (preg_match("/matrix_" . $this->getId() . "_(\d+)/", $key, $matches)) - { - $other_value = (array_key_exists('matrix_other_' . $this->getId() . '_' . $matches[1], $post_data)) - ? ($post_data['matrix_other_' . $this->getId() . '_' . $matches[1]]) - : null; - foreach ($value as $checked) - { - $answer_data[] = array("value"=>$checked, - "textanswer"=>$other_value, - "rowvalue"=>$matches[1]); - } - } - } - break; - } - - if ($a_return) - { - return $answer_data; - } - - // #16387 - only if any input - if(sizeof($answer_data)) - { - // save data - foreach ($answer_data as $item) - { - $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", $item['value']); - $fields['textanswer'] = array("clob", $item['textanswer']); - $fields['rowvalue'] = array("integer", $item['rowvalue']); - $fields['tstamp'] = array("integer", time()); + // gather data + switch ($this->getSubtype()) { + case 0: + foreach ($post_data as $key => $value) { + if (preg_match("/matrix_" . $this->getId() . "_(\d+)/", $key, $matches)) { + if (strlen($value)) { + $other_value = (array_key_exists('matrix_other_' . $this->getId() . '_' . $matches[1], $post_data)) + ? ($post_data['matrix_other_' . $this->getId() . '_' . $matches[1]]) + : null; + $answer_data[] = array("value"=>$value, + "textanswer"=>$other_value, + "rowvalue"=>$matches[1]); + } + } + } + break; + + case 1: + foreach ($post_data as $key => $value) { + if (preg_match("/matrix_" . $this->getId() . "_(\d+)/", $key, $matches)) { + $other_value = (array_key_exists('matrix_other_' . $this->getId() . '_' . $matches[1], $post_data)) + ? ($post_data['matrix_other_' . $this->getId() . '_' . $matches[1]]) + : null; + foreach ($value as $checked) { + $answer_data[] = array("value"=>$checked, + "textanswer"=>$other_value, + "rowvalue"=>$matches[1]); + } + } + } + break; + } + + if ($a_return) { + return $answer_data; + } + + // #16387 - only if any input + if (sizeof($answer_data)) { + // save data + foreach ($answer_data as $item) { + $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", $item['value']); + $fields['textanswer'] = array("clob", $item['textanswer']); + $fields['rowvalue'] = array("integer", $item['rowvalue']); + $fields['tstamp'] = array("integer", time()); - $affectedRows = $ilDB->insert("svy_answer", $fields); + $affectedRows = $ilDB->insert("svy_answer", $fields); + } + } + } - } - } - } + /** + * 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) + { + parent::deleteAdditionalTableData($question_id); + + $ilDB = $this->db; + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_qst_matrixrows WHERE question_fi = %s", + array('integer'), + array($question_id) + ); + } - /** - * 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) - { - parent::deleteAdditionalTableData($question_id); - - $ilDB = $this->db; - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qst_matrixrows WHERE question_fi = %s", - array('integer'), - array($question_id) - ); - } + /** + * Returns the subtype of the matrix question + * + * @return integer The subtype of the matrix question + * @access public + */ + public function getSubtype() + { + return $this->subtype; + } - /** - * Returns the subtype of the matrix question - * - * @return integer The subtype of the matrix question - * @access public - */ - function getSubtype() - { - return $this->subtype; - } + /** + * Sets the subtype of the matrix question + * + * @return integer $a_subtype The subtype of the matrix question + * @access public + */ + public function setSubtype($a_subtype = 0) + { + switch ($a_subtype) { + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + $this->subtype = $a_subtype; + break; + case 0: + default: + $this->subtype = 0; + break; + } + } + + /** + * Enables/Disables separators for the matrix columns + * + * @param integer $enable 1 if the separators should be enabled, 0 otherwise + * @access public + */ + public function setColumnSeparators($enable = 0) + { + switch ($enable) { + case 1: + $this->columnSeparators = 1; + break; + case 0: + default: + $this->columnSeparators = 0; + break; + } + } + + /** + * Gets the separators enable state for the matrix columns + * + * @return integer 1 if the separators are enabled, 0 otherwise + * @access public + */ + public function getColumnSeparators() + { + return ($this->columnSeparators) ? 1 : 0; + } + + /** + * Enables/Disables separators for the matrix rows + * + * @param integer $enable 1 if the separators should be enabled, 0 otherwise + * @access public + */ + public function setRowSeparators($enable = 0) + { + switch ($enable) { + case 1: + $this->rowSeparators = 1; + break; + case 0: + default: + $this->rowSeparators = 0; + break; + } + } + + /** + * Gets the separators enable state for the matrix rows + * + * @return integer 1 if the separators are enabled, 0 otherwise + * @access public + */ + public function getRowSeparators() + { + return ($this->rowSeparators) ? 1 : 0; + } - /** - * Sets the subtype of the matrix question - * - * @return integer $a_subtype The subtype of the matrix question - * @access public - */ - function setSubtype($a_subtype = 0) - { - switch ($a_subtype) - { - case 1: - case 2: - case 3: - case 4: - case 5: - case 6: - $this->subtype = $a_subtype; - break; - case 0: - default: - $this->subtype = 0; - break; - } - } - - /** - * Enables/Disables separators for the matrix columns - * - * @param integer $enable 1 if the separators should be enabled, 0 otherwise - * @access public - */ - function setColumnSeparators($enable = 0) - { - switch ($enable) - { - case 1: - $this->columnSeparators = 1; - break; - case 0: - default: - $this->columnSeparators = 0; - break; - } - } - - /** - * Gets the separators enable state for the matrix columns - * - * @return integer 1 if the separators are enabled, 0 otherwise - * @access public - */ - function getColumnSeparators() - { - return ($this->columnSeparators) ? 1 : 0; - } - - /** - * Enables/Disables separators for the matrix rows - * - * @param integer $enable 1 if the separators should be enabled, 0 otherwise - * @access public - */ - function setRowSeparators($enable = 0) - { - switch ($enable) - { - case 1: - $this->rowSeparators = 1; - break; - case 0: - default: - $this->rowSeparators = 0; - break; - } - } - - /** - * Gets the separators enable state for the matrix rows - * - * @return integer 1 if the separators are enabled, 0 otherwise - * @access public - */ - function getRowSeparators() - { - return ($this->rowSeparators) ? 1 : 0; - } + /** + * Enables/Disables a separator for the neutral column + * + * @param integer $enable 1 if the separator should be enabled, 0 otherwise + * @access public + */ + public function setNeutralColumnSeparator($enable = 0) + { + switch ($enable) { + case 1: + $this->neutralColumnSeparator = 1; + break; + case 0: + default: + $this->neutralColumnSeparator = 0; + break; + } + } + + /** + * Gets the separator enable state for the neutral column + * + * @return integer 1 if the separator is enabled, 0 otherwise + * @access public + */ + public function getNeutralColumnSeparator() + { + return ($this->neutralColumnSeparator) ? 1 : 0; + } - /** - * Enables/Disables a separator for the neutral column - * - * @param integer $enable 1 if the separator should be enabled, 0 otherwise - * @access public - */ - function setNeutralColumnSeparator($enable = 0) - { - switch ($enable) - { - case 1: - $this->neutralColumnSeparator = 1; - break; - case 0: - default: - $this->neutralColumnSeparator = 0; - break; - } - } - - /** - * Gets the separator enable state for the neutral column - * - * @return integer 1 if the separator is enabled, 0 otherwise - * @access public - */ - function getNeutralColumnSeparator() - { - return ($this->neutralColumnSeparator) ? 1 : 0; - } + /** + * 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 "column_separators": + $this->setColumnSeparators($value["entry"]); + break; + case "row_separators": + $this->setRowSeparators($value["entry"]); + break; + case "layout": + $this->setLayout($value["entry"]); + break; + case "neutral_column_separator": + $this->setNeutralColumnSeparator($value["entry"]); + break; + } + } + } - /** - * 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 "column_separators": - $this->setColumnSeparators($value["entry"]); - break; - case "row_separators": - $this->setRowSeparators($value["entry"]); - break; - case "layout": - $this->setLayout($value["entry"]); - break; - case "neutral_column_separator": - $this->setNeutralColumnSeparator($value["entry"]); - break; - } - } - } + /** + * Import bipolar adjectives from the question import file + * + * @return array $a_data Array containing the adjectives + * @access public + */ + public function importAdjectives($a_data) + { + $i = 0; + foreach ($a_data as $adjective) { + if (is_numeric($adjective["label"])) { + $this->setBipolarAdjective($adjective["label"], $adjective["text"]); + } else { + $this->setBipolarAdjective($i, $adjective["text"]); + } + $i++; + } + } - /** - * Import bipolar adjectives from the question import file - * - * @return array $a_data Array containing the adjectives - * @access public - */ - function importAdjectives($a_data) - { - $i = 0; - foreach ($a_data as $adjective) - { - if (is_numeric($adjective["label"])) - { - $this->setBipolarAdjective($adjective["label"], $adjective["text"]); - } - else - { - $this->setBipolarAdjective($i, $adjective["text"]); - } - $i++; - } - } + /** + * Import matrix rows from the question import file + * + * @return array $a_data Array containing the matrix rows + * @access public + */ + public function importMatrix($a_data) + { + foreach ($a_data as $row) { + $this->addRow($row['title'], $row['other'], $row['label']); + } + } + + /** + * 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) { + $column = ""; + foreach ($data["material"] as $material) { + $column .= $material["text"]; + } + $this->columns->addCategory($column, null, (strcmp($data["label"], "neutral") == 0) ? true : false); + } + } - /** - * Import matrix rows from the question import file - * - * @return array $a_data Array containing the matrix rows - * @access public - */ - function importMatrix($a_data) - { - foreach ($a_data as $row) - { - $this->addRow($row['title'], $row['other'], $row['label']); - } - } - - /** - * 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) - { - $column = ""; - foreach ($data["material"] as $material) - { - $column .= $material["text"]; - } - $this->columns->addCategory($column, null, (strcmp($data["label"], "neutral") == 0) ? true : 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 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 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) + { + return $value; + } - /** - * 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) - { - return $value; - } + /** + * 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; + } + + /** + * Saves the layout of a matrix question + * + * @param double $percent_row The width in percent for the matrix rows + * @param double $percent_columns The width in percent for the matrix columns + * @param double $percent_bipolar_adjective1 The width in percent for the first bipolar adjective + * @param double $percent_bipolar_adjective2 The width in percent for the second bipolar adjective + * @return void + **/ + public function saveLayout($percent_row, $percent_columns, $percent_bipolar_adjective1 = "", $percent_bipolar_adjective2 = "", $percent_neutral) + { + $ilDB = $this->db; + + $layout = array( + "percent_row" => $percent_row, + "percent_columns" => $percent_columns, + "percent_bipolar_adjective1" => $percent_bipolar_adjective1, + "percent_bipolar_adjective2" => $percent_bipolar_adjective2, + "percent_neutral" => $percent_neutral + ); + $affectedRows = $ilDB->manipulateF( + "UPDATE " . $this->getAdditionalTableName() . " SET layout = %s WHERE question_fi = %s", + array('text', 'integer'), + array(serialize($layout), $this->getId()) + ); + } - /** - * 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; - } - -/** - * Saves the layout of a matrix question - * - * @param double $percent_row The width in percent for the matrix rows - * @param double $percent_columns The width in percent for the matrix columns - * @param double $percent_bipolar_adjective1 The width in percent for the first bipolar adjective - * @param double $percent_bipolar_adjective2 The width in percent for the second bipolar adjective - * @return void - **/ - function saveLayout($percent_row, $percent_columns, $percent_bipolar_adjective1 = "", $percent_bipolar_adjective2 = "", $percent_neutral) - { - $ilDB = $this->db; - - $layout = array( - "percent_row" => $percent_row, - "percent_columns" => $percent_columns, - "percent_bipolar_adjective1" => $percent_bipolar_adjective1, - "percent_bipolar_adjective2" => $percent_bipolar_adjective2, - "percent_neutral" => $percent_neutral - ); - $affectedRows = $ilDB->manipulateF("UPDATE " . $this->getAdditionalTableName() . " SET layout = %s WHERE question_fi = %s", - array('text', 'integer'), - array(serialize($layout), $this->getId()) - ); - } + public function getLayout() + { + if (!is_array($this->layout) || count($this->layout) == 0) { + if ($this->hasBipolarAdjectives() && $this->hasNeutralColumn()) { + $this->layout = array( + "percent_row" => 30, + "percent_columns" => 40, + "percent_bipolar_adjective1" => 10, + "percent_bipolar_adjective2" => 10, + "percent_neutral" => 10 + ); + } elseif ($this->hasBipolarAdjectives()) { + $this->layout = array( + "percent_row" => 30, + "percent_columns" => 50, + "percent_bipolar_adjective1" => 10, + "percent_bipolar_adjective2" => 10, + "percent_neutral" => 0 + ); + } elseif ($this->hasNeutralColumn()) { + $this->layout = array( + "percent_row" => 30, + "percent_columns" => 50, + "percent_bipolar_adjective1" => 0, + "percent_bipolar_adjective2" => 0, + "percent_neutral" => 20 + ); + } else { + $this->layout = array( + "percent_row" => 30, + "percent_columns" => 70, + "percent_bipolar_adjective1" => 0, + "percent_bipolar_adjective2" => 0, + "percent_neutral" => 0 + ); + } + } + return $this->layout; + } + + public function setLayout($layout) + { + if (is_array($layout)) { + $this->layout = $layout; + } else { + $this->layout = unserialize($layout); + } + } + + /** + * Returns TRUE if bipolar adjectives exist + * + * @return boolean TRUE if bipolar adjectives exist, FALSE otherwise + **/ + public function hasBipolarAdjectives() + { + if ((strlen($this->getBipolarAdjective(0))) && (strlen($this->getBipolarAdjective(1)))) { + return true; + } else { + return false; + } + } + + /** + * Returns TRUE if a neutral column exists + * + * @return boolean TRUE if a neutral column exists, FALSE otherwise + **/ + public function hasNeutralColumn() + { + for ($i = 0; $i < $this->getColumnCount(); $i++) { + $column = $this->getColumn($i); + if ($column->neutral && strlen($column->title)) { + return true; + } + } + return false; + } + + /** + * Set whether placeholders should be used for the column titles or not + * + * @param integer $a_value 1 for placeholders, 0 otherwise + */ + public function setColumnPlaceholders($a_value = 0) + { + $this->columnPlaceholders = ($a_value) ? 1 : 0; + } + + /** + * Get whether placeholders should be used for the column titles or not + * + * @return integer 1 for placeholders, 0 otherwise + */ + public function getColumnPlaceholders() + { + return ($this->columnPlaceholders) ? 1 : 0; + } - function getLayout() - { - if (!is_array($this->layout) || count($this->layout) == 0) - { - if ($this->hasBipolarAdjectives() && $this->hasNeutralColumn()) - { - $this->layout = array( - "percent_row" => 30, - "percent_columns" => 40, - "percent_bipolar_adjective1" => 10, - "percent_bipolar_adjective2" => 10, - "percent_neutral" => 10 - ); - } - elseif ($this->hasBipolarAdjectives()) - { - $this->layout = array( - "percent_row" => 30, - "percent_columns" => 50, - "percent_bipolar_adjective1" => 10, - "percent_bipolar_adjective2" => 10, - "percent_neutral" => 0 - ); - } - elseif ($this->hasNeutralColumn()) - { - $this->layout = array( - "percent_row" => 30, - "percent_columns" => 50, - "percent_bipolar_adjective1" => 0, - "percent_bipolar_adjective2" => 0, - "percent_neutral" => 20 - ); - } - else - { - $this->layout = array( - "percent_row" => 30, - "percent_columns" => 70, - "percent_bipolar_adjective1" => 0, - "percent_bipolar_adjective2" => 0, - "percent_neutral" => 0 - ); - } - } - return $this->layout; - } - - function setLayout($layout) - { - if (is_array($layout)) - { - $this->layout = $layout; - } - else - { - $this->layout = unserialize($layout); - } - } - - /** - * Returns TRUE if bipolar adjectives exist - * - * @return boolean TRUE if bipolar adjectives exist, FALSE otherwise - **/ - function hasBipolarAdjectives() - { - if ((strlen($this->getBipolarAdjective(0))) && (strlen($this->getBipolarAdjective(1)))) - { - return TRUE; - } - else - { - return FALSE; - } - } - - /** - * Returns TRUE if a neutral column exists - * - * @return boolean TRUE if a neutral column exists, FALSE otherwise - **/ - function hasNeutralColumn() - { - for ($i = 0; $i < $this->getColumnCount(); $i++) - { - $column = $this->getColumn($i); - if ($column->neutral && strlen($column->title)) return true; - } - return FALSE; - } - - /** - * Set whether placeholders should be used for the column titles or not - * - * @param integer $a_value 1 for placeholders, 0 otherwise - */ - function setColumnPlaceholders($a_value = 0) - { - $this->columnPlaceholders = ($a_value) ? 1 : 0; - } - - /** - * Get whether placeholders should be used for the column titles or not - * - * @return integer 1 for placeholders, 0 otherwise - */ - function getColumnPlaceholders() - { - return ($this->columnPlaceholders) ? 1 : 0; - } + /** + * Set whether the legend should be shown or not + * + * @param integer $a_value Show legend + */ + public function setLegend($a_value = 0) + { + $this->legend = ($a_value) ? 1 : 0; + } + + /** + * Get whether the legend should be shown or not + * + * @return integer Show legend + */ + public function getLegend() + { + return ($this->legend) ? 1 : 0; + } + + public function setSingleLineRowCaption($a_value = 0) + { + $this->singleLineRowCaption = ($a_value) ? 1 : 0; + } + + public function getSingleLineRowCaption() + { + return ($this->singleLineRowCaption) ? 1 : 0; + } + + public function setRepeatColumnHeader($a_value = 0) + { + $this->repeatColumnHeader = ($a_value) ? 1 : 0; + } + + public function getRepeatColumnHeader() + { + return ($this->repeatColumnHeader) ? 1 : 0; + } + + public function setColumnHeaderPosition($a_value) + { + $this->columnHeaderPosition = $a_value; + } + + public function getColumnHeaderPosition() + { + return ($this->columnHeaderPosition) ? $this->columnHeaderPosition : 0; + } + + public function setRandomRows($a_value = 0) + { + $this->randomRows = ($a_value) ? 1 : 0; + } + + public function getRandomRows() + { + return ($this->randomRows) ? 1 : 0; + } + + public function setColumnOrder($a_value) + { + $this->columnOrder = $a_value; + } + + public function getColumnOrder() + { + return ($this->columnOrder) ? $this->columnOrder : 0; + } + + public function setColumnImages($a_value = 0) + { + $this->columnImages = ($a_value) ? 1 : 0; + } + + public function getColumnImages() + { + return ($this->columnImages) ? 1 : 0; + } + + public function setRowImages($a_value = 0) + { + $this->rowImages = ($a_value) ? 1 : 0; + } + + public function getRowImages() + { + return ($this->rowImages) ? 1 : 0; + } - /** - * Set whether the legend should be shown or not - * - * @param integer $a_value Show legend - */ - function setLegend($a_value = 0) - { - $this->legend = ($a_value) ? 1 : 0; - } - - /** - * Get whether the legend should be shown or not - * - * @return integer Show legend - */ - function getLegend() - { - return ($this->legend) ? 1 : 0; - } - - function setSingleLineRowCaption($a_value = 0) - { - $this->singleLineRowCaption = ($a_value) ? 1 : 0; - } - - function getSingleLineRowCaption() - { - return ($this->singleLineRowCaption) ? 1 : 0; - } - - function setRepeatColumnHeader($a_value = 0) - { - $this->repeatColumnHeader = ($a_value) ? 1 : 0; - } - - function getRepeatColumnHeader() - { - return ($this->repeatColumnHeader) ? 1 : 0; - } - - function setColumnHeaderPosition($a_value) - { - $this->columnHeaderPosition = $a_value; - } - - function getColumnHeaderPosition() - { - return ($this->columnHeaderPosition) ? $this->columnHeaderPosition : 0; - } - - function setRandomRows($a_value = 0) - { - $this->randomRows = ($a_value) ? 1 : 0; - } - - function getRandomRows() - { - return ($this->randomRows) ? 1 : 0; - } - - function setColumnOrder($a_value) - { - $this->columnOrder = $a_value; - } - - function getColumnOrder() - { - return ($this->columnOrder) ? $this->columnOrder : 0; - } - - function setColumnImages($a_value = 0) - { - $this->columnImages = ($a_value) ? 1 : 0; - } - - function getColumnImages() - { - return ($this->columnImages) ? 1 : 0; - } - - function setRowImages($a_value = 0) - { - $this->rowImages = ($a_value) ? 1 : 0; - } - - function getRowImages() - { - return ($this->rowImages) ? 1 : 0; - } - - public function getRows() - { - return $this->rows; - } + public function getRows() + { + return $this->rows; + } } - -?> \ No newline at end of file diff --git a/Modules/SurveyQuestionPool/classes/class.SurveyMatrixQuestionEvaluation.php b/Modules/SurveyQuestionPool/classes/class.SurveyMatrixQuestionEvaluation.php index 6ac876591c7ffde0ddf48f9a6bd6047221eb77ec..5a7c5444a20945469659a1a4b9d879a542b71130 100644 --- a/Modules/SurveyQuestionPool/classes/class.SurveyMatrixQuestionEvaluation.php +++ b/Modules/SurveyQuestionPool/classes/class.SurveyMatrixQuestionEvaluation.php @@ -4,423 +4,369 @@ include_once "Modules/SurveyQuestionPool/classes/class.SurveyQuestionEvaluation.php"; /** - * Survey matrix evaluation + * Survey matrix evaluation * * @author Jörg Lützenkirchen * @ingroup ModulesSurveyQuestionPool */ class SurveyMatrixQuestionEvaluation extends SurveyQuestionEvaluation { - // - // RESULTS - // - - public function getResults() - { - $results = array(); - - $answers = $this->getAnswerData(); - - // parse rows - for ($r = 0; $r < $this->question->getRowCount(); $r++) - { - $row_results = new ilSurveyEvaluationResults($this->question); - - $this->parseResults( - $row_results, - (array)$answers[$r], - $this->question->getColumns() - ); - - $results[] = array( - $this->question->getRow($r)->title, - $row_results - ); - } - - return $results; - } - - - // - // DETAILS - // - - - public function getGrid($a_results, $a_abs = true, $a_perc = true) - { - $lng = $this->lng; - - $res = array( - "cols" => array(), - "rows" => array() - ); - - $tmp = $a_results; - $tmp = array_shift($tmp); - $vars = $tmp[1]->getVariables(); - if($vars) - { - foreach($vars as $var) - { - $res["cols"][] = $var->cat->title; - } - } - $q_counter = 0; - foreach($a_results as $results_row) - { - #20363 - $parsed_row = array( - ++$q_counter.". ".$results_row[0] - ); + // + // RESULTS + // + + public function getResults() + { + $results = array(); + + $answers = $this->getAnswerData(); + + // parse rows + for ($r = 0; $r < $this->question->getRowCount(); $r++) { + $row_results = new ilSurveyEvaluationResults($this->question); + + $this->parseResults( + $row_results, + (array) $answers[$r], + $this->question->getColumns() + ); + + $results[] = array( + $this->question->getRow($r)->title, + $row_results + ); + } + + return $results; + } + + + // + // DETAILS + // + + + public function getGrid($a_results, $a_abs = true, $a_perc = true) + { + $lng = $this->lng; + + $res = array( + "cols" => array(), + "rows" => array() + ); + + $tmp = $a_results; + $tmp = array_shift($tmp); + $vars = $tmp[1]->getVariables(); + if ($vars) { + foreach ($vars as $var) { + $res["cols"][] = $var->cat->title; + } + } + $q_counter = 0; + foreach ($a_results as $results_row) { + #20363 + $parsed_row = array( + ++$q_counter . ". " . $results_row[0] + ); - $vars = $results_row[1]->getVariables(); - if($vars) - { - foreach($vars as $var) - { - $perc = $var->perc - ? sprintf("%.2f", $var->perc*100)."%" - : "0%"; - - if((bool)$a_abs && (bool)$a_perc) - { - $parsed_row[] = $var->abs." / ".$perc; - } - else if((bool)$a_abs) - { - $parsed_row[] = $var->abs; - } - else - { - $parsed_row[] = $perc; - } - } - } - - $res["rows"][] = $parsed_row; - } - return $res; - } - - public function getTextAnswers($a_results) - { - $res = array(); - - foreach($a_results as $results_row) - { - $texts = $results_row[1]->getMappedTextAnswers(); - if($texts) - { - $idx = $results_row[0]; - foreach($texts as $answers) - { - foreach($answers as $answer) - { - $res[$idx][] = $answer; - } - } - } - } - - return $res; - } - - public function getChart($a_results) - { - $lng = $this->lng; - - include_once "Services/Chart/classes/class.ilChart.php"; - $chart = ilChart::getInstanceByType(ilChart::TYPE_GRID, $a_results[0][1]->getQuestion()->getId()); - $chart->setXAxisToInteger(true); - $chart->setStacked(true); - - $colors = $this->getChartColors(); - $chart->setColors($colors); + $vars = $results_row[1]->getVariables(); + if ($vars) { + foreach ($vars as $var) { + $perc = $var->perc + ? sprintf("%.2f", $var->perc*100) . "%" + : "0%"; + + if ((bool) $a_abs && (bool) $a_perc) { + $parsed_row[] = $var->abs . " / " . $perc; + } elseif ((bool) $a_abs) { + $parsed_row[] = $var->abs; + } else { + $parsed_row[] = $perc; + } + } + } + + $res["rows"][] = $parsed_row; + } + return $res; + } + + public function getTextAnswers($a_results) + { + $res = array(); + + foreach ($a_results as $results_row) { + $texts = $results_row[1]->getMappedTextAnswers(); + if ($texts) { + $idx = $results_row[0]; + foreach ($texts as $answers) { + foreach ($answers as $answer) { + $res[$idx][] = $answer; + } + } + } + } + + return $res; + } + + public function getChart($a_results) + { + $lng = $this->lng; + + include_once "Services/Chart/classes/class.ilChart.php"; + $chart = ilChart::getInstanceByType(ilChart::TYPE_GRID, $a_results[0][1]->getQuestion()->getId()); + $chart->setXAxisToInteger(true); + $chart->setStacked(true); + + $colors = $this->getChartColors(); + $chart->setColors($colors); - // :TODO: - //$chart->setsize($this->chart_width, $this->chart_height); - - $data = $labels = $legend = array(); - - $row_idx = sizeof($a_results); + // :TODO: + //$chart->setsize($this->chart_width, $this->chart_height); + + $data = $labels = $legend = array(); + + $row_idx = sizeof($a_results); - $row_counter = 0; - $text_shortened = false; - foreach($a_results as $row) - { - $row_idx--; + $row_counter = 0; + $text_shortened = false; + foreach ($a_results as $row) { + $row_idx--; - $row_title = $row[0]; - $row_results = $row[1]; + $row_title = $row[0]; + $row_results = $row[1]; - #20363 - $row_title = ++$row_counter.". ".$row_title; - $labels[$row_idx] = ilUtil::shortenText($row_title, 50, true); - if($labels[$row_idx] != $row_title) { - $text_shortened = true; - } - //$labels[$row_idx] = wordwrap(ilUtil::shortenText($row_title, 50, true), 30, "
"); - - $vars = $row_results->getVariables(); - if($vars) - { - foreach($vars as $idx => $var) - { - if(!array_key_exists($idx, $data)) - { - $data[$idx] = $chart->getDataInstance(ilChartGrid::DATA_BARS); - $data[$idx]->setLabel($var->cat->title); - $data[$idx]->setBarOptions(0.5, "center", true); - $data[$idx]->setFill(1); - - $legend[] = array( - $var->cat->title, - $colors[$idx] - ); - } - - $data[$idx]->addPoint($var->abs, $row_idx); - } - } - } + #20363 + $row_title = ++$row_counter . ". " . $row_title; + $labels[$row_idx] = ilUtil::shortenText($row_title, 50, true); + if ($labels[$row_idx] != $row_title) { + $text_shortened = true; + } + //$labels[$row_idx] = wordwrap(ilUtil::shortenText($row_title, 50, true), 30, "
"); + + $vars = $row_results->getVariables(); + if ($vars) { + foreach ($vars as $idx => $var) { + if (!array_key_exists($idx, $data)) { + $data[$idx] = $chart->getDataInstance(ilChartGrid::DATA_BARS); + $data[$idx]->setLabel($var->cat->title); + $data[$idx]->setBarOptions(0.5, "center", true); + $data[$idx]->setFill(1); + + $legend[] = array( + $var->cat->title, + $colors[$idx] + ); + } + + $data[$idx]->addPoint($var->abs, $row_idx); + } + } + } - //Chart height depending on the number of questions. Not fixed anymore. - $this->chart_height = count($a_results)*40; - //Chart width 500px if one or + question string are longer than 60 char. Otherwise the default width still aplied. - if($text_shortened) { - $this->chart_width = 500; - } - $chart->setSize($this->chart_width, $this->chart_height); + //Chart height depending on the number of questions. Not fixed anymore. + $this->chart_height = count($a_results)*40; + //Chart width 500px if one or + question string are longer than 60 char. Otherwise the default width still aplied. + if ($text_shortened) { + $this->chart_width = 500; + } + $chart->setSize($this->chart_width, $this->chart_height); - foreach($data as $var) - { - $chart->addData($var); - } - - $chart->setTicks(false, $labels, true); - - return array( - $chart->getHTML(), - $legend - ); - } - + foreach ($data as $var) { + $chart->addData($var); + } + + $chart->setTicks(false, $labels, true); + + return array( + $chart->getHTML(), + $legend + ); + } + - - // - // EXPORT - // - - public function exportResults($a_results, $a_do_title, $a_do_label) - { - $question = $a_results[0][1]->getQuestion(); - - $rows = array(); - $row = array(); - - if($a_do_title) - { - $row[] = $question->getTitle(); - } - if($a_do_label) - { - $row[] = $question->label; - } - - $row[] = $question->getQuestiontext(); - $row[] = SurveyQuestion::_getQuestionTypeName($question->getQuestionType()); - - $row[] = (int)$a_results[0][1]->getUsersAnswered(); - $row[] = (int)$a_results[0][1]->getUsersSkipped(); - $row[] = null; - $row[] = null; - $row[] = null; - $row[] = null; - $row[] = null; - - $rows[] = $row; - - foreach($a_results as $row_result) - { - $row_title = $row_result[0]; - $row_res = $row_result[1]; - - $row = array(); - - if($a_do_title) - { - $row[] = null; - } - if($a_do_label) - { - $row[] = null; - } + + // + // EXPORT + // + + public function exportResults($a_results, $a_do_title, $a_do_label) + { + $question = $a_results[0][1]->getQuestion(); + + $rows = array(); + $row = array(); + + if ($a_do_title) { + $row[] = $question->getTitle(); + } + if ($a_do_label) { + $row[] = $question->label; + } + + $row[] = $question->getQuestiontext(); + $row[] = SurveyQuestion::_getQuestionTypeName($question->getQuestionType()); + + $row[] = (int) $a_results[0][1]->getUsersAnswered(); + $row[] = (int) $a_results[0][1]->getUsersSkipped(); + $row[] = null; + $row[] = null; + $row[] = null; + $row[] = null; + $row[] = null; + + $rows[] = $row; + + foreach ($a_results as $row_result) { + $row_title = $row_result[0]; + $row_res = $row_result[1]; + + $row = array(); + + if ($a_do_title) { + $row[] = null; + } + if ($a_do_label) { + $row[] = null; + } - $row[] = $row_title; - $row[] = null; + $row[] = $row_title; + $row[] = null; - $row[] = null; - $row[] = null; - - // :TODO: - $row[] = is_array($row_res->getModeValue()) - ? implode(", ", $row_res->getModeValue()) - : $row_res->getModeValue(); - - $row[] = $row_res->getModeValueAsText(); - $row[] = (int)$row_res->getModeNrOfSelections(); + $row[] = null; + $row[] = null; + + // :TODO: + $row[] = is_array($row_res->getModeValue()) + ? implode(", ", $row_res->getModeValue()) + : $row_res->getModeValue(); + + $row[] = $row_res->getModeValueAsText(); + $row[] = (int) $row_res->getModeNrOfSelections(); - // :TODO: - $row[] = $row_res->getMedianAsText(); + // :TODO: + $row[] = $row_res->getMedianAsText(); - $row[] = $row_res->getMean(); - - $rows[] = $row; - } - return $rows; - } - - public function getUserSpecificVariableTitles(array &$a_title_row, array &$a_title_row2, $a_do_title, $a_do_label) - { - $lng = $this->lng; - - for ($i = 0; $i < $this->question->getRowCount(); $i++) - { - // create row title according label, add 'other column' - $row = $this->question->getRow($i); - - if($a_do_title && $a_do_label) - { - $a_title_row[] = $row->title; - $a_title_row2[] = $row->label; + $row[] = $row_res->getMean(); + + $rows[] = $row; + } + return $rows; + } + + public function getUserSpecificVariableTitles(array &$a_title_row, array &$a_title_row2, $a_do_title, $a_do_label) + { + $lng = $this->lng; + + for ($i = 0; $i < $this->question->getRowCount(); $i++) { + // create row title according label, add 'other column' + $row = $this->question->getRow($i); + + if ($a_do_title && $a_do_label) { + $a_title_row[] = $row->title; + $a_title_row2[] = $row->label; - if($this->question->getSubtype() == 0) - { - $a_title_row[] = $row->title; // see #20646 - $a_title_row2[] = $row->label; // see #20646 - } + if ($this->question->getSubtype() == 0) { + $a_title_row[] = $row->title; // see #20646 + $a_title_row2[] = $row->label; // see #20646 + } - if ($row->other) - { - $a_title_row[] = $row->title; - $a_title_row2[] = $lng->txt('other'); - } - } - else if($a_do_title) - { - $a_title_row[] = $row->title; - $a_title_row2[] = ""; + if ($row->other) { + $a_title_row[] = $row->title; + $a_title_row2[] = $lng->txt('other'); + } + } elseif ($a_do_title) { + $a_title_row[] = $row->title; + $a_title_row2[] = ""; - if($this->question->getSubtype() == 0) - { - $a_title_row[] = $row->title; // see #20646 - $a_title_row2[] = ""; // see #20646 - } + if ($this->question->getSubtype() == 0) { + $a_title_row[] = $row->title; // see #20646 + $a_title_row2[] = ""; // see #20646 + } - if ($row->other) - { - $a_title_row[] = $row->title; - $a_title_row2[] = $lng->txt('other'); - } - } - else - { - $a_title_row[] = $row->label; - $a_title_row2[] = ""; + if ($row->other) { + $a_title_row[] = $row->title; + $a_title_row2[] = $lng->txt('other'); + } + } else { + $a_title_row[] = $row->label; + $a_title_row2[] = ""; - if($this->question->getSubtype() == 0) - { - $a_title_row[] = $row->label; // see #20646 - $a_title_row2[] = ""; // see #20646 - } + if ($this->question->getSubtype() == 0) { + $a_title_row[] = $row->label; // see #20646 + $a_title_row2[] = ""; // see #20646 + } - if ($row->other) - { - $a_title_row[] = $row->label; - $a_title_row2[] = $lng->txt('other'); - } - } - - // mc - if($this->question->getSubtype() == 1) - { - for($index = 0; $index < $this->question->getColumnCount(); $index++) - { - $col = $this->question->getColumn($index); - - $a_title_row[] = $col->title." [".$col->scale."]"; - $a_title_row2[] = ""; - } - } - } - } - - public function addUserSpecificResults(array &$a_row, $a_user_id, $a_results) - { - $answer_map = array(); - foreach($a_results as $row_results) - { - $row_title = $row_results[0]; - $row_result = $row_results[1]; - - $answers = $row_result->getUserResults($a_user_id); - if($answers !== null) - { - foreach($answers as $answer) - { - // mc - if($this->question->getSubtype() == 1) - { - $answer_map[$row_title."|".$answer[2]] = $answer[2]; - } - else - { - $answer_map[$row_title] = $answer[3]; - $answer_map[$row_title."|scale"] = $answer[2]; // see #20646 - } - if($answer[1]) - { - $answer_map[$row_title."|txt"] = $answer[1]; - } - } - } - } - - if(!sizeof($answer_map)) - { - $a_row[] = $this->getSkippedValue(); - } - else - { - $a_row[] = ""; - } - - for ($i = 0; $i < $this->question->getRowCount(); $i++) - { - $row = $this->question->getRow($i); - $row_title = $row->title; - - $a_row[] = $answer_map[$row_title]; - if($this->question->getSubtype() == 0) - { - $a_row[] = $answer_map[$row_title . "|scale"]; // see #20646 - } - - if($row->other) - { - $a_row[] = $answer_map[$row_title."|txt"]; - } - - // mc - if($this->question->getSubtype() == 1) - { - for($index = 0; $index < $this->question->getColumnCount(); $index++) - { - $col = $this->question->getColumn($index); - $a_row[] = $answer_map[$row_title."|".$col->scale]; - } - } - } - } + if ($row->other) { + $a_title_row[] = $row->label; + $a_title_row2[] = $lng->txt('other'); + } + } + + // mc + if ($this->question->getSubtype() == 1) { + for ($index = 0; $index < $this->question->getColumnCount(); $index++) { + $col = $this->question->getColumn($index); + + $a_title_row[] = $col->title . " [" . $col->scale . "]"; + $a_title_row2[] = ""; + } + } + } + } + + public function addUserSpecificResults(array &$a_row, $a_user_id, $a_results) + { + $answer_map = array(); + foreach ($a_results as $row_results) { + $row_title = $row_results[0]; + $row_result = $row_results[1]; + + $answers = $row_result->getUserResults($a_user_id); + if ($answers !== null) { + foreach ($answers as $answer) { + // mc + if ($this->question->getSubtype() == 1) { + $answer_map[$row_title . "|" . $answer[2]] = $answer[2]; + } else { + $answer_map[$row_title] = $answer[3]; + $answer_map[$row_title . "|scale"] = $answer[2]; // see #20646 + } + if ($answer[1]) { + $answer_map[$row_title . "|txt"] = $answer[1]; + } + } + } + } + + if (!sizeof($answer_map)) { + $a_row[] = $this->getSkippedValue(); + } else { + $a_row[] = ""; + } + + for ($i = 0; $i < $this->question->getRowCount(); $i++) { + $row = $this->question->getRow($i); + $row_title = $row->title; + + $a_row[] = $answer_map[$row_title]; + if ($this->question->getSubtype() == 0) { + $a_row[] = $answer_map[$row_title . "|scale"]; // see #20646 + } + + if ($row->other) { + $a_row[] = $answer_map[$row_title . "|txt"]; + } + + // mc + if ($this->question->getSubtype() == 1) { + for ($index = 0; $index < $this->question->getColumnCount(); $index++) { + $col = $this->question->getColumn($index); + $a_row[] = $answer_map[$row_title . "|" . $col->scale]; + } + } + } + } } diff --git a/Modules/SurveyQuestionPool/classes/class.SurveyMatrixQuestionGUI.php b/Modules/SurveyQuestionPool/classes/class.SurveyMatrixQuestionGUI.php index ab8c9f444ca04805300ab493839d4b60471e7a72..b5b4d3c91b9456a29b2d50c02abffb2b3ecc25e9 100755 --- a/Modules/SurveyQuestionPool/classes/class.SurveyMatrixQuestionGUI.php +++ b/Modules/SurveyQuestionPool/classes/class.SurveyMatrixQuestionGUI.php @@ -34,914 +34,789 @@ include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php"; * @extends SurveyQuestionGUI * @ingroup ModulesSurveyQuestionPool */ -class SurveyMatrixQuestionGUI extends SurveyQuestionGUI +class SurveyMatrixQuestionGUI extends SurveyQuestionGUI { - protected $show_layout_row; - - protected function initObject() - { - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyMatrixQuestion.php"; - $this->object = new SurveyMatrixQuestion(); - } + protected $show_layout_row; + + protected function initObject() + { + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyMatrixQuestion.php"; + $this->object = new SurveyMatrixQuestion(); + } - - // - // EDITOR - // - - public function setQuestionTabs() - { - $this->setQuestionTabsForClass("surveymatrixquestiongui"); - } + + // + // EDITOR + // + + public function setQuestionTabs() + { + $this->setQuestionTabsForClass("surveymatrixquestiongui"); + } - protected function addFieldsToEditForm(ilPropertyFormGUI $a_form) - { - // subtype - $subtype = new ilRadioGroupInputGUI($this->lng->txt("subtype"), "type"); - $subtype->setRequired(false); - $subtypes = array( - "0" => "matrix_subtype_sr", - "1" => "matrix_subtype_mr", - //"2" => "matrix_subtype_text", - //"3" => "matrix_subtype_integer", - //"4" => "matrix_subtype_double", - //"5" => "matrix_subtype_date", - //"6" => "matrix_subtype_time" - ); - foreach ($subtypes as $idx => $st) - { - $subtype->addOption(new ilRadioOption($this->lng->txt($st), $idx)); - } - $a_form->addItem($subtype); + protected function addFieldsToEditForm(ilPropertyFormGUI $a_form) + { + // subtype + $subtype = new ilRadioGroupInputGUI($this->lng->txt("subtype"), "type"); + $subtype->setRequired(false); + $subtypes = array( + "0" => "matrix_subtype_sr", + "1" => "matrix_subtype_mr", + //"2" => "matrix_subtype_text", + //"3" => "matrix_subtype_integer", + //"4" => "matrix_subtype_double", + //"5" => "matrix_subtype_date", + //"6" => "matrix_subtype_time" + ); + foreach ($subtypes as $idx => $st) { + $subtype->addOption(new ilRadioOption($this->lng->txt($st), $idx)); + } + $a_form->addItem($subtype); - - $header = new ilFormSectionHeaderGUI(); - $header->setTitle($this->lng->txt("matrix_appearance")); - $a_form->addItem($header); - - // column separators - $column_separators = new ilCheckboxInputGUI($this->lng->txt("matrix_column_separators"), "column_separators"); - $column_separators->setValue(1); - $column_separators->setInfo($this->lng->txt("matrix_column_separators_description")); - $column_separators->setRequired(false); - $a_form->addItem($column_separators); + + $header = new ilFormSectionHeaderGUI(); + $header->setTitle($this->lng->txt("matrix_appearance")); + $a_form->addItem($header); + + // column separators + $column_separators = new ilCheckboxInputGUI($this->lng->txt("matrix_column_separators"), "column_separators"); + $column_separators->setValue(1); + $column_separators->setInfo($this->lng->txt("matrix_column_separators_description")); + $column_separators->setRequired(false); + $a_form->addItem($column_separators); - // row separators - $row_separators = new ilCheckboxInputGUI($this->lng->txt("matrix_row_separators"), "row_separators"); - $row_separators->setValue(1); - $row_separators->setInfo($this->lng->txt("matrix_row_separators_description")); - $row_separators->setRequired(false); - $a_form->addItem($row_separators); + // row separators + $row_separators = new ilCheckboxInputGUI($this->lng->txt("matrix_row_separators"), "row_separators"); + $row_separators->setValue(1); + $row_separators->setInfo($this->lng->txt("matrix_row_separators_description")); + $row_separators->setRequired(false); + $a_form->addItem($row_separators); - // neutral column separators - $neutral_column_separator = new ilCheckboxInputGUI($this->lng->txt("matrix_neutral_column_separator"), "neutral_column_separator"); - $neutral_column_separator->setValue(1); - $neutral_column_separator->setInfo($this->lng->txt("matrix_neutral_column_separator_description")); - $neutral_column_separator->setRequired(false); - $a_form->addItem($neutral_column_separator); + // neutral column separators + $neutral_column_separator = new ilCheckboxInputGUI($this->lng->txt("matrix_neutral_column_separator"), "neutral_column_separator"); + $neutral_column_separator->setValue(1); + $neutral_column_separator->setInfo($this->lng->txt("matrix_neutral_column_separator_description")); + $neutral_column_separator->setRequired(false); + $a_form->addItem($neutral_column_separator); - - $header = new ilFormSectionHeaderGUI(); - $header->setTitle($this->lng->txt("matrix_columns")); - $a_form->addItem($header); - - // Answers - include_once "./Modules/SurveyQuestionPool/classes/class.ilCategoryWizardInputGUI.php"; - $columns = new ilCategoryWizardInputGUI("", "columns"); - $columns->setRequired(false); - $columns->setAllowMove(true); - $columns->setShowWizard(true); - $columns->setShowNeutralCategory(true); - $columns->setDisabledScale(false); - $columns->setNeutralCategoryTitle($this->lng->txt('matrix_neutral_answer')); - $columns->setCategoryText($this->lng->txt('matrix_standard_answers')); - $columns->setShowSavePhrase(true); - $a_form->addItem($columns); - - - $header = new ilFormSectionHeaderGUI(); - $header->setTitle($this->lng->txt("matrix_column_settings")); - $a_form->addItem($header); - - // bipolar adjectives - $bipolar = new ilCustomInputGUI($this->lng->txt("matrix_bipolar_adjectives")); - $bipolar->setInfo($this->lng->txt("matrix_bipolar_adjectives_description")); - - // left pole - $bipolar1 = new ilTextInputGUI($this->lng->txt("matrix_left_pole"), "bipolar1"); - $bipolar1->setRequired(false); - $bipolar->addSubItem($bipolar1); - - // right pole - $bipolar2 = new ilTextInputGUI($this->lng->txt("matrix_right_pole"), "bipolar2"); - $bipolar2->setRequired(false); - $bipolar->addSubItem($bipolar2); + + $header = new ilFormSectionHeaderGUI(); + $header->setTitle($this->lng->txt("matrix_columns")); + $a_form->addItem($header); + + // Answers + include_once "./Modules/SurveyQuestionPool/classes/class.ilCategoryWizardInputGUI.php"; + $columns = new ilCategoryWizardInputGUI("", "columns"); + $columns->setRequired(false); + $columns->setAllowMove(true); + $columns->setShowWizard(true); + $columns->setShowNeutralCategory(true); + $columns->setDisabledScale(false); + $columns->setNeutralCategoryTitle($this->lng->txt('matrix_neutral_answer')); + $columns->setCategoryText($this->lng->txt('matrix_standard_answers')); + $columns->setShowSavePhrase(true); + $a_form->addItem($columns); + + + $header = new ilFormSectionHeaderGUI(); + $header->setTitle($this->lng->txt("matrix_column_settings")); + $a_form->addItem($header); + + // bipolar adjectives + $bipolar = new ilCustomInputGUI($this->lng->txt("matrix_bipolar_adjectives")); + $bipolar->setInfo($this->lng->txt("matrix_bipolar_adjectives_description")); + + // left pole + $bipolar1 = new ilTextInputGUI($this->lng->txt("matrix_left_pole"), "bipolar1"); + $bipolar1->setRequired(false); + $bipolar->addSubItem($bipolar1); + + // right pole + $bipolar2 = new ilTextInputGUI($this->lng->txt("matrix_right_pole"), "bipolar2"); + $bipolar2->setRequired(false); + $bipolar->addSubItem($bipolar2); - $a_form->addItem($bipolar); - + $a_form->addItem($bipolar); + - $header = new ilFormSectionHeaderGUI(); - $header->setTitle($this->lng->txt("matrix_rows")); - $a_form->addItem($header); + $header = new ilFormSectionHeaderGUI(); + $header->setTitle($this->lng->txt("matrix_rows")); + $a_form->addItem($header); - // matrix rows - include_once "./Modules/SurveyQuestionPool/classes/class.ilMatrixRowWizardInputGUI.php"; - $rows = new ilMatrixRowWizardInputGUI("", "rows"); - $rows->setRequired(false); - $rows->setAllowMove(true); - $rows->setLabelText($this->lng->txt('label')); - $rows->setUseOtherAnswer(true); - $a_form->addItem($rows); - - - // values - $subtype->setValue($this->object->getSubtype()); - $column_separators->setChecked($this->object->getColumnSeparators()); - $row_separators->setChecked($this->object->getRowSeparators()); - $neutral_column_separator->setChecked($this->object->getNeutralColumnSeparator()); - - if (!$this->object->getColumnCount()) - { - $this->object->columns->addCategory(""); - } - $columns->setValues($this->object->getColumns()); - - $bipolar1->setValue($this->object->getBipolarAdjective(0)); - $bipolar2->setValue($this->object->getBipolarAdjective(1)); - - if ($this->object->getRowCount() == 0) - { - $this->object->getRows()->addCategory(""); - } - $rows->setValues($this->object->getRows()); - } - - protected function importEditFormValues(ilPropertyFormGUI $a_form) - { - $this->object->setSubtype($a_form->getInput("type")); - $this->object->setRowSeparators($a_form->getInput("row_separators") ? 1 : 0); - $this->object->setColumnSeparators($a_form->getInput("column_separators") ? 1 : 0); - $this->object->setNeutralColumnSeparator($a_form->getInput("neutral_column_separator") ? 1 : 0); - - // Set bipolar adjectives - $this->object->setBipolarAdjective(0, $a_form->getInput("bipolar1")); - $this->object->setBipolarAdjective(1, $a_form->getInput("bipolar2")); - - // set columns - $this->object->flushColumns(); - - foreach ($_POST['columns']['answer'] as $key => $value) - { - if (strlen($value)) $this->object->getColumns()->addCategory($value, $_POST['columns']['other'][$key], 0, null, $_POST['columns']['scale'][$key]); - } - if (strlen($_POST["columns"]["neutral"])) - { - $this->object->getColumns()->addCategory($_POST['columns']['neutral'], 0, 1, null, $_POST['columns_neutral_scale']); - } - - // set rows - $this->object->flushRows(); - foreach ($_POST['rows']['answer'] as $key => $value) - { - if (strlen($value)) $this->object->getRows()->addCategory($value, $_POST['rows']['other'][$key], 0, $_POST['rows']['label'][$key]); - } - } - - 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->getRowCount(); $i++) - { - $rowobj = $this->object->getRow($i); - - $text = null; - - $cols = array(); - for ($j = 0; $j < $this->object->getColumnCount(); $j++) - { - $cat = $this->object->getColumn($j); - $value = ($cat->scale) ? ($cat->scale - 1) : $j; - - $checked = "unchecked"; - if(is_array($a_working_data)) - { - foreach($user_answers as $user_answer) - { - if($user_answer["rowvalue"] == $i && - $user_answer["value"] == $value) - { - $checked = "checked"; - if($user_answer["textanswer"]) - { - $text = $user_answer["textanswer"]; - } - } - } - } - - if(!$a_only_user_anwers || $checked == "checked") - { - $cols[$value] = array( - "title" => trim($cat->title) - ,"neutral" => (bool)$cat->neutral - ,"checked" => $checked - ); - } - } - - if($a_only_user_anwers || sizeof($cols) || $text) - { - $row_idx = $i; - $options[$row_idx] = array( - "title" => trim($rowobj->title) - ,"other" => (bool)$rowobj->other - ,"textanswer" => $text - ,"cols" => $cols - ); - } - } - - return $options; - } - - /** - * Creates a HTML representation of the question - * - * @access private - */ - function getPrintView($question_title = 1, $show_questiontext = 1, $survey_id = null, array $a_working_data = null) - { - $options = $this->getParsedAnswers($a_working_data); - - $layout = $this->object->getLayout(); - $neutralstyle = "3px solid #808080"; - $bordercolor = "#808080"; - $template = new ilTemplate("tpl.il_svy_qpl_matrix_printview.html", TRUE, TRUE, "Modules/SurveyQuestionPool"); + // matrix rows + include_once "./Modules/SurveyQuestionPool/classes/class.ilMatrixRowWizardInputGUI.php"; + $rows = new ilMatrixRowWizardInputGUI("", "rows"); + $rows->setRequired(false); + $rows->setAllowMove(true); + $rows->setLabelText($this->lng->txt('label')); + $rows->setUseOtherAnswer(true); + $a_form->addItem($rows); + + + // values + $subtype->setValue($this->object->getSubtype()); + $column_separators->setChecked($this->object->getColumnSeparators()); + $row_separators->setChecked($this->object->getRowSeparators()); + $neutral_column_separator->setChecked($this->object->getNeutralColumnSeparator()); + + if (!$this->object->getColumnCount()) { + $this->object->columns->addCategory(""); + } + $columns->setValues($this->object->getColumns()); + + $bipolar1->setValue($this->object->getBipolarAdjective(0)); + $bipolar2->setValue($this->object->getBipolarAdjective(1)); + + if ($this->object->getRowCount() == 0) { + $this->object->getRows()->addCategory(""); + } + $rows->setValues($this->object->getRows()); + } + + protected function importEditFormValues(ilPropertyFormGUI $a_form) + { + $this->object->setSubtype($a_form->getInput("type")); + $this->object->setRowSeparators($a_form->getInput("row_separators") ? 1 : 0); + $this->object->setColumnSeparators($a_form->getInput("column_separators") ? 1 : 0); + $this->object->setNeutralColumnSeparator($a_form->getInput("neutral_column_separator") ? 1 : 0); + + // Set bipolar adjectives + $this->object->setBipolarAdjective(0, $a_form->getInput("bipolar1")); + $this->object->setBipolarAdjective(1, $a_form->getInput("bipolar2")); + + // set columns + $this->object->flushColumns(); + + foreach ($_POST['columns']['answer'] as $key => $value) { + if (strlen($value)) { + $this->object->getColumns()->addCategory($value, $_POST['columns']['other'][$key], 0, null, $_POST['columns']['scale'][$key]); + } + } + if (strlen($_POST["columns"]["neutral"])) { + $this->object->getColumns()->addCategory($_POST['columns']['neutral'], 0, 1, null, $_POST['columns_neutral_scale']); + } + + // set rows + $this->object->flushRows(); + foreach ($_POST['rows']['answer'] as $key => $value) { + if (strlen($value)) { + $this->object->getRows()->addCategory($value, $_POST['rows']['other'][$key], 0, $_POST['rows']['label'][$key]); + } + } + } + + 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->getRowCount(); $i++) { + $rowobj = $this->object->getRow($i); + + $text = null; + + $cols = array(); + for ($j = 0; $j < $this->object->getColumnCount(); $j++) { + $cat = $this->object->getColumn($j); + $value = ($cat->scale) ? ($cat->scale - 1) : $j; + + $checked = "unchecked"; + if (is_array($a_working_data)) { + foreach ($user_answers as $user_answer) { + if ($user_answer["rowvalue"] == $i && + $user_answer["value"] == $value) { + $checked = "checked"; + if ($user_answer["textanswer"]) { + $text = $user_answer["textanswer"]; + } + } + } + } + + if (!$a_only_user_anwers || $checked == "checked") { + $cols[$value] = array( + "title" => trim($cat->title) + ,"neutral" => (bool) $cat->neutral + ,"checked" => $checked + ); + } + } + + if ($a_only_user_anwers || sizeof($cols) || $text) { + $row_idx = $i; + $options[$row_idx] = array( + "title" => trim($rowobj->title) + ,"other" => (bool) $rowobj->other + ,"textanswer" => $text + ,"cols" => $cols + ); + } + } + + return $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); + + $layout = $this->object->getLayout(); + $neutralstyle = "3px solid #808080"; + $bordercolor = "#808080"; + $template = new ilTemplate("tpl.il_svy_qpl_matrix_printview.html", true, true, "Modules/SurveyQuestionPool"); - if ($this->show_layout_row) - { - $layout_row = $this->getLayoutRow(); - $template->setCurrentBlock("matrix_row"); - $template->setVariable("ROW", $layout_row); - $template->parseCurrentBlock(); - } - - $tplheaders = new ilTemplate("tpl.il_svy_out_matrix_columnheaders.html", TRUE, TRUE, "Modules/SurveyQuestionPool"); - if ((strlen($this->object->getBipolarAdjective(0))) && (strlen($this->object->getBipolarAdjective(1)))) - { - $tplheaders->setCurrentBlock("bipolar_start"); - $style = array(); - array_push($style, sprintf("width: %.2F%s!important", $layout["percent_bipolar_adjective1"], "%")); - if (count($style) > 0) - { - $tplheaders->setVariable("STYLE", " style=\"" . implode(";", $style) . "\""); - } - $tplheaders->parseCurrentBlock(); - } - // column headers - for ($i = 0; $i < $this->object->getColumnCount(); $i++) - { - $cat = $this->object->getColumn($i); - if ($cat->neutral) - { - $tplheaders->setCurrentBlock("neutral_column_header"); - $tplheaders->setVariable("TEXT", ilUtil::prepareFormOutput($cat->title)); - $tplheaders->setVariable("CLASS", "rsep"); - $style = array(); - array_push($style, sprintf("width: %.2F%s!important", $layout["percent_neutral"], "%")); - if ($this->object->getNeutralColumnSeparator()) - { - array_push($style, "border-left: $neutralstyle!important;"); - } - if (count($style) > 0) - { - $tplheaders->setVariable("STYLE", " style=\"" . implode(";", $style) . "\""); - } - $tplheaders->parseCurrentBlock(); - } - else - { - $style = array(); - if ($this->object->getColumnSeparators() == 1) - { - if (($i < $this->object->getColumnCount() - 1)) - { - array_push($style, "border-right: 1px solid $bordercolor!important"); - } - } - array_push($style, sprintf("width: %.2F%s!important", $layout["percent_columns"] / $this->object->getColumnCount(), "%")); - $tplheaders->setCurrentBlock("column_header"); - $tplheaders->setVariable("TEXT", ilUtil::prepareFormOutput($cat->title)); - $tplheaders->setVariable("CLASS", "center"); - if (count($style) > 0) - { - $tplheaders->setVariable("STYLE", " style=\"" . implode(";", $style) . "\""); - } - $tplheaders->parseCurrentBlock(); - } - } + if ($this->show_layout_row) { + $layout_row = $this->getLayoutRow(); + $template->setCurrentBlock("matrix_row"); + $template->setVariable("ROW", $layout_row); + $template->parseCurrentBlock(); + } + + $tplheaders = new ilTemplate("tpl.il_svy_out_matrix_columnheaders.html", true, true, "Modules/SurveyQuestionPool"); + if ((strlen($this->object->getBipolarAdjective(0))) && (strlen($this->object->getBipolarAdjective(1)))) { + $tplheaders->setCurrentBlock("bipolar_start"); + $style = array(); + array_push($style, sprintf("width: %.2F%s!important", $layout["percent_bipolar_adjective1"], "%")); + if (count($style) > 0) { + $tplheaders->setVariable("STYLE", " style=\"" . implode(";", $style) . "\""); + } + $tplheaders->parseCurrentBlock(); + } + // column headers + for ($i = 0; $i < $this->object->getColumnCount(); $i++) { + $cat = $this->object->getColumn($i); + if ($cat->neutral) { + $tplheaders->setCurrentBlock("neutral_column_header"); + $tplheaders->setVariable("TEXT", ilUtil::prepareFormOutput($cat->title)); + $tplheaders->setVariable("CLASS", "rsep"); + $style = array(); + array_push($style, sprintf("width: %.2F%s!important", $layout["percent_neutral"], "%")); + if ($this->object->getNeutralColumnSeparator()) { + array_push($style, "border-left: $neutralstyle!important;"); + } + if (count($style) > 0) { + $tplheaders->setVariable("STYLE", " style=\"" . implode(";", $style) . "\""); + } + $tplheaders->parseCurrentBlock(); + } else { + $style = array(); + if ($this->object->getColumnSeparators() == 1) { + if (($i < $this->object->getColumnCount() - 1)) { + array_push($style, "border-right: 1px solid $bordercolor!important"); + } + } + array_push($style, sprintf("width: %.2F%s!important", $layout["percent_columns"] / $this->object->getColumnCount(), "%")); + $tplheaders->setCurrentBlock("column_header"); + $tplheaders->setVariable("TEXT", ilUtil::prepareFormOutput($cat->title)); + $tplheaders->setVariable("CLASS", "center"); + if (count($style) > 0) { + $tplheaders->setVariable("STYLE", " style=\"" . implode(";", $style) . "\""); + } + $tplheaders->parseCurrentBlock(); + } + } - if ((strlen($this->object->getBipolarAdjective(0))) && (strlen($this->object->getBipolarAdjective(1)))) - { - $tplheaders->setCurrentBlock("bipolar_end"); - $style = array(); - array_push($style, sprintf("width: %.2F%s!important", $layout["percent_bipolar_adjective2"], "%")); - if (count($style) > 0) - { - $tplheaders->setVariable("STYLE", " style=\"" . implode(";", $style) . "\""); - } - $tplheaders->parseCurrentBlock(); - } + if ((strlen($this->object->getBipolarAdjective(0))) && (strlen($this->object->getBipolarAdjective(1)))) { + $tplheaders->setCurrentBlock("bipolar_end"); + $style = array(); + array_push($style, sprintf("width: %.2F%s!important", $layout["percent_bipolar_adjective2"], "%")); + if (count($style) > 0) { + $tplheaders->setVariable("STYLE", " style=\"" . implode(";", $style) . "\""); + } + $tplheaders->parseCurrentBlock(); + } - $style = array(); - array_push($style, sprintf("width: %.2F%s!important", $layout["percent_row"], "%")); - if (count($style) > 0) - { - $tplheaders->setVariable("STYLE", " style=\"" . implode(";", $style) . "\""); - } - - $template->setCurrentBlock("matrix_row"); - $template->setVariable("ROW", $tplheaders->get()); - $template->parseCurrentBlock(); + $style = array(); + array_push($style, sprintf("width: %.2F%s!important", $layout["percent_row"], "%")); + if (count($style) > 0) { + $tplheaders->setVariable("STYLE", " style=\"" . implode(";", $style) . "\""); + } + + $template->setCurrentBlock("matrix_row"); + $template->setVariable("ROW", $tplheaders->get()); + $template->parseCurrentBlock(); - $rowclass = array("tblrow1", "tblrow2"); - - for ($i = 0; $i < $this->object->getRowCount(); $i++) - { - $rowobj = $this->object->getRow($i); - $tplrow = new ilTemplate("tpl.il_svy_qpl_matrix_printview_row.html", TRUE, TRUE, "Modules/SurveyQuestionPool"); - for ($j = 0; $j < $this->object->getColumnCount(); $j++) - { - $cat = $this->object->getColumn($j); - if (($i == 0) && ($j == 0)) - { - if ((strlen($this->object->getBipolarAdjective(0))) && (strlen($this->object->getBipolarAdjective(1)))) - { - $tplrow->setCurrentBlock("bipolar_start"); - $tplrow->setVariable("TEXT_BIPOLAR_START", ilUtil::prepareFormOutput($this->object->getBipolarAdjective(0))); - $tplrow->setVariable("ROWSPAN", $this->object->getRowCount()); - $tplrow->parseCurrentBlock(); - } - } - if (($i == 0) && ($j == $this->object->getColumnCount()-1)) - { - if ((strlen($this->object->getBipolarAdjective(0))) && (strlen($this->object->getBipolarAdjective(1)))) - { - $tplrow->setCurrentBlock("bipolar_end"); - $tplrow->setVariable("TEXT_BIPOLAR_END", ilUtil::prepareFormOutput($this->object->getBipolarAdjective(1))); - $tplrow->setVariable("ROWSPAN", $this->object->getRowCount()); - $tplrow->parseCurrentBlock(); - } - } - - $value = ($cat->scale) ? ($cat->scale - 1) : $j; - $col = $options[$i]["cols"][$value]; - - switch ($this->object->getSubtype()) - { - case 0: - if ($cat->neutral) - { - $tplrow->setCurrentBlock("neutral_radiobutton"); - $tplrow->setVariable("IMAGE_RADIO", ilUtil::getHtmlPath(ilUtil::getImagePath("radiobutton_".$col["checked"].".png"))); - $tplrow->setVariable("ALT_RADIO", $this->lng->txt($col["checked"])); - $tplrow->setVariable("TITLE_RADIO", $this->lng->txt($col["checked"])); - $tplrow->parseCurrentBlock(); - } - else - { - $tplrow->setCurrentBlock("radiobutton"); - $tplrow->setVariable("IMAGE_RADIO", ilUtil::getHtmlPath(ilUtil::getImagePath("radiobutton_".$col["checked"].".png"))); - $tplrow->setVariable("ALT_RADIO", $this->lng->txt($col["checked"])); - $tplrow->setVariable("TITLE_RADIO", $this->lng->txt($col["checked"])); - $tplrow->parseCurrentBlock(); - } - break; - case 1: - if ($cat->neutral) - { - $tplrow->setCurrentBlock("neutral_checkbox"); - $tplrow->setVariable("IMAGE_CHECKBOX", ilUtil::getHtmlPath(ilUtil::getImagePath("checkbox_".$col["checked"].".png"))); - $tplrow->setVariable("ALT_CHECKBOX", $this->lng->txt($col["checked"])); - $tplrow->setVariable("TITLE_CHECKBOX", $this->lng->txt($col["checked"])); - $tplrow->parseCurrentBlock(); - } - else - { - $tplrow->setCurrentBlock("checkbox"); - $tplrow->setVariable("IMAGE_CHECKBOX", ilUtil::getHtmlPath(ilUtil::getImagePath("checkbox_".$col["checked"].".png"))); - $tplrow->setVariable("ALT_CHECKBOX", $this->lng->txt($col["checked"])); - $tplrow->setVariable("TITLE_CHECKBOX", $this->lng->txt($col["checked"])); - $tplrow->parseCurrentBlock(); - } - break; - } - if ($cat->neutral) - { - $tplrow->setCurrentBlock("neutral_answer"); - $style = array(); - if ($this->object->getNeutralColumnSeparator()) - { - array_push($style, "border-left: $neutralstyle!important"); - } - if ($this->object->getColumnSeparators() == 1) - { - if ($j < $this->object->getColumnCount() - 1) - { - array_push($style, "border-right: 1px solid $bordercolor!important"); - } - } + $rowclass = array("tblrow1", "tblrow2"); + + for ($i = 0; $i < $this->object->getRowCount(); $i++) { + $rowobj = $this->object->getRow($i); + $tplrow = new ilTemplate("tpl.il_svy_qpl_matrix_printview_row.html", true, true, "Modules/SurveyQuestionPool"); + for ($j = 0; $j < $this->object->getColumnCount(); $j++) { + $cat = $this->object->getColumn($j); + if (($i == 0) && ($j == 0)) { + if ((strlen($this->object->getBipolarAdjective(0))) && (strlen($this->object->getBipolarAdjective(1)))) { + $tplrow->setCurrentBlock("bipolar_start"); + $tplrow->setVariable("TEXT_BIPOLAR_START", ilUtil::prepareFormOutput($this->object->getBipolarAdjective(0))); + $tplrow->setVariable("ROWSPAN", $this->object->getRowCount()); + $tplrow->parseCurrentBlock(); + } + } + if (($i == 0) && ($j == $this->object->getColumnCount()-1)) { + if ((strlen($this->object->getBipolarAdjective(0))) && (strlen($this->object->getBipolarAdjective(1)))) { + $tplrow->setCurrentBlock("bipolar_end"); + $tplrow->setVariable("TEXT_BIPOLAR_END", ilUtil::prepareFormOutput($this->object->getBipolarAdjective(1))); + $tplrow->setVariable("ROWSPAN", $this->object->getRowCount()); + $tplrow->parseCurrentBlock(); + } + } + + $value = ($cat->scale) ? ($cat->scale - 1) : $j; + $col = $options[$i]["cols"][$value]; + + switch ($this->object->getSubtype()) { + case 0: + if ($cat->neutral) { + $tplrow->setCurrentBlock("neutral_radiobutton"); + $tplrow->setVariable("IMAGE_RADIO", ilUtil::getHtmlPath(ilUtil::getImagePath("radiobutton_" . $col["checked"] . ".png"))); + $tplrow->setVariable("ALT_RADIO", $this->lng->txt($col["checked"])); + $tplrow->setVariable("TITLE_RADIO", $this->lng->txt($col["checked"])); + $tplrow->parseCurrentBlock(); + } else { + $tplrow->setCurrentBlock("radiobutton"); + $tplrow->setVariable("IMAGE_RADIO", ilUtil::getHtmlPath(ilUtil::getImagePath("radiobutton_" . $col["checked"] . ".png"))); + $tplrow->setVariable("ALT_RADIO", $this->lng->txt($col["checked"])); + $tplrow->setVariable("TITLE_RADIO", $this->lng->txt($col["checked"])); + $tplrow->parseCurrentBlock(); + } + break; + case 1: + if ($cat->neutral) { + $tplrow->setCurrentBlock("neutral_checkbox"); + $tplrow->setVariable("IMAGE_CHECKBOX", ilUtil::getHtmlPath(ilUtil::getImagePath("checkbox_" . $col["checked"] . ".png"))); + $tplrow->setVariable("ALT_CHECKBOX", $this->lng->txt($col["checked"])); + $tplrow->setVariable("TITLE_CHECKBOX", $this->lng->txt($col["checked"])); + $tplrow->parseCurrentBlock(); + } else { + $tplrow->setCurrentBlock("checkbox"); + $tplrow->setVariable("IMAGE_CHECKBOX", ilUtil::getHtmlPath(ilUtil::getImagePath("checkbox_" . $col["checked"] . ".png"))); + $tplrow->setVariable("ALT_CHECKBOX", $this->lng->txt($col["checked"])); + $tplrow->setVariable("TITLE_CHECKBOX", $this->lng->txt($col["checked"])); + $tplrow->parseCurrentBlock(); + } + break; + } + if ($cat->neutral) { + $tplrow->setCurrentBlock("neutral_answer"); + $style = array(); + if ($this->object->getNeutralColumnSeparator()) { + array_push($style, "border-left: $neutralstyle!important"); + } + if ($this->object->getColumnSeparators() == 1) { + if ($j < $this->object->getColumnCount() - 1) { + array_push($style, "border-right: 1px solid $bordercolor!important"); + } + } - if ($this->object->getRowSeparators() == 1) - { - if ($i < $this->object->getRowCount() - 1) - { - array_push($style, "border-bottom: 1px solid $bordercolor!important"); - } - } - if (count($style)) - { - $tplrow->setVariable("STYLE", " style=\"" . implode(";", $style) . "\""); - } - $tplrow->parseCurrentBlock(); - } - else - { - $tplrow->setCurrentBlock("answer"); - $style = array(); + if ($this->object->getRowSeparators() == 1) { + if ($i < $this->object->getRowCount() - 1) { + array_push($style, "border-bottom: 1px solid $bordercolor!important"); + } + } + if (count($style)) { + $tplrow->setVariable("STYLE", " style=\"" . implode(";", $style) . "\""); + } + $tplrow->parseCurrentBlock(); + } else { + $tplrow->setCurrentBlock("answer"); + $style = array(); - if ($this->object->getColumnSeparators() == 1) - { - if ($j < $this->object->getColumnCount() - 1) - { - array_push($style, "border-right: 1px solid $bordercolor!important"); - } - } + if ($this->object->getColumnSeparators() == 1) { + if ($j < $this->object->getColumnCount() - 1) { + array_push($style, "border-right: 1px solid $bordercolor!important"); + } + } - if ($this->object->getRowSeparators() == 1) - { - if ($i < $this->object->getRowCount() - 1) - { - array_push($style, "border-bottom: 1px solid $bordercolor!important"); - } - } - if (count($style)) - { - $tplrow->setVariable("STYLE", " style=\"" . implode(";", $style) . "\""); - } - $tplrow->parseCurrentBlock(); - } - } + if ($this->object->getRowSeparators() == 1) { + if ($i < $this->object->getRowCount() - 1) { + array_push($style, "border-bottom: 1px solid $bordercolor!important"); + } + } + if (count($style)) { + $tplrow->setVariable("STYLE", " style=\"" . implode(";", $style) . "\""); + } + $tplrow->parseCurrentBlock(); + } + } - if ($rowobj->other) - { - $text = $options[$i]["textanswer"]; - $tplrow->setCurrentBlock("text_other"); - $tplrow->setVariable("TEXT_OTHER", $text - ? $text - : "             "); - $tplrow->parseCurrentBlock(); - } + if ($rowobj->other) { + $text = $options[$i]["textanswer"]; + $tplrow->setCurrentBlock("text_other"); + $tplrow->setVariable("TEXT_OTHER", $text + ? $text + : "             "); + $tplrow->parseCurrentBlock(); + } - #force to have always the title - #22526 - $row_title = ilUtil::prepareFormOutput($rowobj->title); - if($question_title == 3) - { - if(trim($rowobj->label)) - { - $row_title .= ' ('.ilUtil::prepareFormOutput($rowobj->label).')'; - } - } + #force to have always the title + #22526 + $row_title = ilUtil::prepareFormOutput($rowobj->title); + if ($question_title == 3) { + if (trim($rowobj->label)) { + $row_title .= ' (' . ilUtil::prepareFormOutput($rowobj->label) . ')'; + } + } - $tplrow->setVariable("TEXT_ROW", $row_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", $this->getPrintViewQuestionTitle($question_title)); - } - $template->setCurrentBlock(); - if ($show_questiontext) - { - $this->outQuestionText($template); - } - $template->parseCurrentBlock(); - return $template->get(); - } + $tplrow->setVariable("TEXT_ROW", $row_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", $this->getPrintViewQuestionTitle($question_title)); + } + $template->setCurrentBlock(); + if ($show_questiontext) { + $this->outQuestionText($template); + } + $template->parseCurrentBlock(); + return $template->get(); + } - - // - // LAYOUT - // + + // + // LAYOUT + // - /** - * Creates a layout view of the question - * - * @access public - */ - function layout() - { - $ilTabs = $this->tabs; - - $ilTabs->activateTab("layout"); - - $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.il_svy_qpl_layout.html", "Modules/SurveyQuestionPool"); - $this->show_layout_row = TRUE; - $question_output = $this->getWorkingForm(); - $this->tpl->setVariable("QUESTION_OUTPUT", $question_output); - $this->tpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this, "saveLayout")); - $this->tpl->setVariable("SAVE", $this->lng->txt("save")); - } - - /** - * Saves the layout for the matrix question - * - * @return void - **/ - function saveLayout() - { - $percent_values = array( - "percent_row" => (int)$_POST["percent_row"], - "percent_columns" => (int)$_POST["percent_columns"], - "percent_bipolar_adjective1" => (int)$_POST['percent_bipolar_adjective1'], - "percent_bipolar_adjective2" => (int)$_POST['percent_bipolar_adjective2'], - "percent_neutral" => (int)$_POST["percent_neutral"] - ); - $this->object->setLayout($percent_values); - - // #9364 - if(array_sum($percent_values) == 100) - { - $this->object->saveLayout($percent_values["percent_row"], - $percent_values['percent_columns'], - $percent_values['percent_bipolar_adjective1'], - $percent_values['percent_bipolar_adjective2'], - $percent_values["percent_neutral"]); - ilUtil::sendSuccess($this->lng->txt("settings_saved")); - } - else - { - ilUtil::sendFailure($this->lng->txt("svy_matrix_layout_percentages_sum_invalid")); - } - $this->layout(); - } + /** + * Creates a layout view of the question + * + * @access public + */ + public function layout() + { + $ilTabs = $this->tabs; + + $ilTabs->activateTab("layout"); + + $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.il_svy_qpl_layout.html", "Modules/SurveyQuestionPool"); + $this->show_layout_row = true; + $question_output = $this->getWorkingForm(); + $this->tpl->setVariable("QUESTION_OUTPUT", $question_output); + $this->tpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this, "saveLayout")); + $this->tpl->setVariable("SAVE", $this->lng->txt("save")); + } + + /** + * Saves the layout for the matrix question + * + * @return void + **/ + public function saveLayout() + { + $percent_values = array( + "percent_row" => (int) $_POST["percent_row"], + "percent_columns" => (int) $_POST["percent_columns"], + "percent_bipolar_adjective1" => (int) $_POST['percent_bipolar_adjective1'], + "percent_bipolar_adjective2" => (int) $_POST['percent_bipolar_adjective2'], + "percent_neutral" => (int) $_POST["percent_neutral"] + ); + $this->object->setLayout($percent_values); + + // #9364 + if (array_sum($percent_values) == 100) { + $this->object->saveLayout( + $percent_values["percent_row"], + $percent_values['percent_columns'], + $percent_values['percent_bipolar_adjective1'], + $percent_values['percent_bipolar_adjective2'], + $percent_values["percent_neutral"] + ); + ilUtil::sendSuccess($this->lng->txt("settings_saved")); + } else { + ilUtil::sendFailure($this->lng->txt("svy_matrix_layout_percentages_sum_invalid")); + } + $this->layout(); + } - /** - * Creates a row to define the matrix question layout with percentage values - * - * @access public - */ - function getLayoutRow() - { - $percent_values = $this->object->getLayout(); - $template = new ilTemplate("tpl.il_svy_out_matrix_layout.html", TRUE, TRUE, "Modules/SurveyQuestionPool"); - if (strlen($this->object->getBipolarAdjective(0)) && strlen($this->object->getBipolarAdjective(1))) - { - $template->setCurrentBlock("bipolar_start"); - $template->setVariable("VALUE_PERCENT_BIPOLAR_ADJECTIVE1", " value=\"" . $percent_values["percent_bipolar_adjective1"] . "\""); - $template->setVariable("STYLE", " style=\"width:" . $percent_values["percent_bipolar_adjective1"] . "%\""); - $template->parseCurrentBlock(); - $template->setCurrentBlock("bipolar_end"); - $template->setVariable("VALUE_PERCENT_BIPOLAR_ADJECTIVE2", " value=\"" . $percent_values["percent_bipolar_adjective2"] . "\""); - $template->setVariable("STYLE", " style=\"width:" . $percent_values["percent_bipolar_adjective2"] . "%\""); - $template->parseCurrentBlock(); - } - $counter = $this->object->getColumnCount(); - if (strlen($this->object->hasNeutralColumn())) - { - $template->setCurrentBlock("neutral_start"); - $template->setVariable("VALUE_PERCENT_NEUTRAL", " value=\"" . $percent_values["percent_neutral"] . "\""); - $template->setVariable("STYLE_NEUTRAL", " style=\"width:" . $percent_values["percent_neutral"] . "%\""); - $template->parseCurrentBlock(); - $counter--; - } - $template->setVariable("VALUE_PERCENT_ROW", " value=\"" . $percent_values["percent_row"] . "\""); - $template->setVariable("STYLE_ROW", " style=\"width:" . $percent_values["percent_row"] . "%\""); - $template->setVariable("COLSPAN_COLUMNS", $counter); - $template->setVariable("VALUE_PERCENT_COLUMNS", " value=\"" . $percent_values["percent_columns"] . "\""); - $template->setVariable("STYLE_COLUMNS", " style=\"width:" . $percent_values["percent_columns"] . "%\""); - return $template->get(); - } - - - // - // EXECUTION - // - - /** - * Creates the question output form for the learner - * - * @access public - */ - function getWorkingForm($working_data = "", $question_title = 1, $show_questiontext = 1, $error_message = "", $survey_id = null) - { - $layout = $this->object->getLayout(); - $neutralstyle = "3px solid #808080"; - $bordercolor = "#808080"; - $template = new ilTemplate("tpl.il_svy_out_matrix.html", TRUE, TRUE, "Modules/SurveyQuestionPool"); - $template->setCurrentBlock("material_matrix"); - $template->setVariable("TEXT_MATERIAL", $this->getMaterialOutput()); - $template->parseCurrentBlock(); - - if ($this->show_layout_row) - { - $layout_row = $this->getLayoutRow(); - $template->setCurrentBlock("matrix_row"); - $template->setVariable("ROW", $layout_row); - $template->parseCurrentBlock(); - } - - $tplheaders = new ilTemplate("tpl.il_svy_out_matrix_columnheaders.html", TRUE, TRUE, "Modules/SurveyQuestionPool"); - if ((strlen($this->object->getBipolarAdjective(0))) && (strlen($this->object->getBipolarAdjective(1)))) - { - $tplheaders->setCurrentBlock("bipolar_start"); - $style = array(); - array_push($style, sprintf("width: %.2f%s!important", $layout["percent_bipolar_adjective1"], "%")); - if (count($style) > 0) - { - $tplheaders->setVariable("STYLE", " style=\"" . implode(";", $style) . "\""); - } - $tplheaders->parseCurrentBlock(); - } - // column headers - for ($i = 0; $i < $this->object->getColumnCount(); $i++) - { - $style = array(); - $col = $this->object->getColumn($i); - if ($col->neutral) - { - $tplheaders->setCurrentBlock("neutral_column_header"); - $tplheaders->setVariable("TEXT", ilUtil::prepareFormOutput($col->title)); - $tplheaders->setVariable("CLASS", "rsep"); - $style = array(); - array_push($style, sprintf("width: %.2f%s!important", $layout["percent_neutral"], "%")); - if ($this->object->getNeutralColumnSeparator()) - { - array_push($style, "border-left: $neutralstyle!important;"); - } - if (count($style) > 0) - { - $tplheaders->setVariable("STYLE", " style=\"" . implode(";", $style) . "\""); - } - $tplheaders->parseCurrentBlock(); - } - else - { - if ($this->object->getColumnSeparators() == 1) - { - if (($i < $this->object->getColumnCount() - 1)) - { - array_push($style, "border-right: 1px solid $bordercolor!important"); - } - } - array_push($style, sprintf("width: %.2f%s!important", $layout["percent_columns"] / $this->object->getColumnCount(), "%")); - $tplheaders->setCurrentBlock("column_header"); - $tplheaders->setVariable("TEXT", ilUtil::prepareFormOutput($col->title)); - $tplheaders->setVariable("CLASS", "center"); - if (count($style) > 0) - { - $tplheaders->setVariable("STYLE", " style=\"" . implode(";", $style) . "\""); - } - $tplheaders->parseCurrentBlock(); - } - } - if ((strlen($this->object->getBipolarAdjective(0))) && (strlen($this->object->getBipolarAdjective(1)))) - { - $tplheaders->setCurrentBlock("bipolar_end"); - $style = array(); - array_push($style, sprintf("width: %.2f%s!important", $layout["percent_bipolar_adjective2"], "%")); - if (count($style) > 0) - { - $tplheaders->setVariable("STYLE", " style=\"" . implode(";", $style) . "\""); - } - $tplheaders->parseCurrentBlock(); - } + /** + * Creates a row to define the matrix question layout with percentage values + * + * @access public + */ + public function getLayoutRow() + { + $percent_values = $this->object->getLayout(); + $template = new ilTemplate("tpl.il_svy_out_matrix_layout.html", true, true, "Modules/SurveyQuestionPool"); + if (strlen($this->object->getBipolarAdjective(0)) && strlen($this->object->getBipolarAdjective(1))) { + $template->setCurrentBlock("bipolar_start"); + $template->setVariable("VALUE_PERCENT_BIPOLAR_ADJECTIVE1", " value=\"" . $percent_values["percent_bipolar_adjective1"] . "\""); + $template->setVariable("STYLE", " style=\"width:" . $percent_values["percent_bipolar_adjective1"] . "%\""); + $template->parseCurrentBlock(); + $template->setCurrentBlock("bipolar_end"); + $template->setVariable("VALUE_PERCENT_BIPOLAR_ADJECTIVE2", " value=\"" . $percent_values["percent_bipolar_adjective2"] . "\""); + $template->setVariable("STYLE", " style=\"width:" . $percent_values["percent_bipolar_adjective2"] . "%\""); + $template->parseCurrentBlock(); + } + $counter = $this->object->getColumnCount(); + if (strlen($this->object->hasNeutralColumn())) { + $template->setCurrentBlock("neutral_start"); + $template->setVariable("VALUE_PERCENT_NEUTRAL", " value=\"" . $percent_values["percent_neutral"] . "\""); + $template->setVariable("STYLE_NEUTRAL", " style=\"width:" . $percent_values["percent_neutral"] . "%\""); + $template->parseCurrentBlock(); + $counter--; + } + $template->setVariable("VALUE_PERCENT_ROW", " value=\"" . $percent_values["percent_row"] . "\""); + $template->setVariable("STYLE_ROW", " style=\"width:" . $percent_values["percent_row"] . "%\""); + $template->setVariable("COLSPAN_COLUMNS", $counter); + $template->setVariable("VALUE_PERCENT_COLUMNS", " value=\"" . $percent_values["percent_columns"] . "\""); + $template->setVariable("STYLE_COLUMNS", " style=\"width:" . $percent_values["percent_columns"] . "%\""); + 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) + { + $layout = $this->object->getLayout(); + $neutralstyle = "3px solid #808080"; + $bordercolor = "#808080"; + $template = new ilTemplate("tpl.il_svy_out_matrix.html", true, true, "Modules/SurveyQuestionPool"); + $template->setCurrentBlock("material_matrix"); + $template->setVariable("TEXT_MATERIAL", $this->getMaterialOutput()); + $template->parseCurrentBlock(); + + if ($this->show_layout_row) { + $layout_row = $this->getLayoutRow(); + $template->setCurrentBlock("matrix_row"); + $template->setVariable("ROW", $layout_row); + $template->parseCurrentBlock(); + } + + $tplheaders = new ilTemplate("tpl.il_svy_out_matrix_columnheaders.html", true, true, "Modules/SurveyQuestionPool"); + if ((strlen($this->object->getBipolarAdjective(0))) && (strlen($this->object->getBipolarAdjective(1)))) { + $tplheaders->setCurrentBlock("bipolar_start"); + $style = array(); + array_push($style, sprintf("width: %.2f%s!important", $layout["percent_bipolar_adjective1"], "%")); + if (count($style) > 0) { + $tplheaders->setVariable("STYLE", " style=\"" . implode(";", $style) . "\""); + } + $tplheaders->parseCurrentBlock(); + } + // column headers + for ($i = 0; $i < $this->object->getColumnCount(); $i++) { + $style = array(); + $col = $this->object->getColumn($i); + if ($col->neutral) { + $tplheaders->setCurrentBlock("neutral_column_header"); + $tplheaders->setVariable("TEXT", ilUtil::prepareFormOutput($col->title)); + $tplheaders->setVariable("CLASS", "rsep"); + $style = array(); + array_push($style, sprintf("width: %.2f%s!important", $layout["percent_neutral"], "%")); + if ($this->object->getNeutralColumnSeparator()) { + array_push($style, "border-left: $neutralstyle!important;"); + } + if (count($style) > 0) { + $tplheaders->setVariable("STYLE", " style=\"" . implode(";", $style) . "\""); + } + $tplheaders->parseCurrentBlock(); + } else { + if ($this->object->getColumnSeparators() == 1) { + if (($i < $this->object->getColumnCount() - 1)) { + array_push($style, "border-right: 1px solid $bordercolor!important"); + } + } + array_push($style, sprintf("width: %.2f%s!important", $layout["percent_columns"] / $this->object->getColumnCount(), "%")); + $tplheaders->setCurrentBlock("column_header"); + $tplheaders->setVariable("TEXT", ilUtil::prepareFormOutput($col->title)); + $tplheaders->setVariable("CLASS", "center"); + if (count($style) > 0) { + $tplheaders->setVariable("STYLE", " style=\"" . implode(";", $style) . "\""); + } + $tplheaders->parseCurrentBlock(); + } + } + if ((strlen($this->object->getBipolarAdjective(0))) && (strlen($this->object->getBipolarAdjective(1)))) { + $tplheaders->setCurrentBlock("bipolar_end"); + $style = array(); + array_push($style, sprintf("width: %.2f%s!important", $layout["percent_bipolar_adjective2"], "%")); + if (count($style) > 0) { + $tplheaders->setVariable("STYLE", " style=\"" . implode(";", $style) . "\""); + } + $tplheaders->parseCurrentBlock(); + } - $style = array(); - array_push($style, sprintf("width: %.2f%s!important", $layout["percent_row"], "%")); - if (count($style) > 0) - { - $tplheaders->setVariable("STYLE", " style=\"" . implode(";", $style) . "\""); - } - - $template->setCurrentBlock("matrix_row"); - $template->setVariable("ROW", $tplheaders->get()); - $template->parseCurrentBlock(); + $style = array(); + array_push($style, sprintf("width: %.2f%s!important", $layout["percent_row"], "%")); + if (count($style) > 0) { + $tplheaders->setVariable("STYLE", " style=\"" . implode(";", $style) . "\""); + } + + $template->setCurrentBlock("matrix_row"); + $template->setVariable("ROW", $tplheaders->get()); + $template->parseCurrentBlock(); - $rowclass = array("tblrow1", "tblrow2"); - for ($i = 0; $i < $this->object->getRowCount(); $i++) - { - $rowobj = $this->object->getRow($i); - $tplrow = new ilTemplate("tpl.il_svy_out_matrix_row.html", TRUE, TRUE, "Modules/SurveyQuestionPool"); - for ($j = 0; $j < $this->object->getColumnCount(); $j++) - { - $cat = $this->object->getColumn($j); - if (($i == 0) && ($j == 0)) - { - if ((strlen($this->object->getBipolarAdjective(0))) && (strlen($this->object->getBipolarAdjective(1)))) - { - $tplrow->setCurrentBlock("bipolar_start"); - $tplrow->setVariable("TEXT_BIPOLAR_START", ilUtil::prepareFormOutput($this->object->getBipolarAdjective(0))); - $tplrow->setVariable("ROWSPAN", $this->object->getRowCount()); - $tplrow->parseCurrentBlock(); - } - } - if (($i == 0) && ($j == $this->object->getColumnCount()-1)) - { - if ((strlen($this->object->getBipolarAdjective(0))) && (strlen($this->object->getBipolarAdjective(1)))) - { - $tplrow->setCurrentBlock("bipolar_end"); - $tplrow->setVariable("TEXT_BIPOLAR_END", ilUtil::prepareFormOutput($this->object->getBipolarAdjective(1))); - $tplrow->setVariable("ROWSPAN", $this->object->getRowCount()); - $tplrow->parseCurrentBlock(); - } - } - switch ($this->object->getSubtype()) - { - case 0: - if ($cat->neutral) - { - $tplrow->setCurrentBlock("neutral_radiobutton"); - $tplrow->setVariable("QUESTION_ID", $this->object->getId()); - $tplrow->setVariable("ROW", $i); - $tplrow->setVariable("VALUE", ($cat->scale) ? ($cat->scale - 1) : $j); - if (is_array($working_data)) - { - foreach ($working_data as $data) - { - if (($data["value"] == $cat->scale-1) && ($data["rowvalue"] == $i)) - { - $tplrow->setVariable("CHECKED_RADIOBUTTON", " checked=\"checked\""); - } - } - } - $tplrow->parseCurrentBlock(); - } - else - { - $tplrow->setCurrentBlock("radiobutton"); - $tplrow->setVariable("QUESTION_ID", $this->object->getId()); - $tplrow->setVariable("ROW", $i); - $tplrow->setVariable("VALUE", ($cat->scale) ? ($cat->scale - 1) : $j); - if (is_array($working_data)) - { - foreach ($working_data as $data) - { - if (($data["value"] == $cat->scale-1) && ($data["rowvalue"] == $i)) - { - $tplrow->setVariable("CHECKED_RADIOBUTTON", " checked=\"checked\""); - } - } - } - $tplrow->parseCurrentBlock(); - } - break; - case 1: - if ($cat->neutral) - { - $tplrow->setCurrentBlock("neutral_checkbox"); - $tplrow->setVariable("QUESTION_ID", $this->object->getId()); - $tplrow->setVariable("ROW", $i); - $tplrow->setVariable("VALUE", ($cat->scale) ? ($cat->scale - 1) : $j); - if (is_array($working_data)) - { - foreach ($working_data as $data) - { - if (($data["value"] == $cat->scale-1) && ($data["rowvalue"] == $i)) - { - $tplrow->setVariable("CHECKED_CHECKBOX", " checked=\"checked\""); - } - } - } - $tplrow->parseCurrentBlock(); - } - else - { - $tplrow->setCurrentBlock("checkbox"); - $tplrow->setVariable("QUESTION_ID", $this->object->getId()); - $tplrow->setVariable("ROW", $i); - $tplrow->setVariable("VALUE", ($cat->scale) ? ($cat->scale - 1) : $j); - if (is_array($working_data)) - { - foreach ($working_data as $data) - { - if (($data["value"] == $cat->scale-1) && ($data["rowvalue"] == $i)) - { - $tplrow->setVariable("CHECKED_CHECKBOX", " checked=\"checked\""); - } - } - } - $tplrow->parseCurrentBlock(); - } - break; - } - if ($cat->neutral) - { - $tplrow->setCurrentBlock("neutral_answer"); - $style = array(); - if ($this->object->getNeutralColumnSeparator()) - { - array_push($style, "border-left: $neutralstyle!important"); - } - if ($this->object->getColumnSeparators() == 1) - { - if ($j < $this->object->getColumnCount() - 1) - { - array_push($style, "border-right: 1px solid $bordercolor!important"); - } - } - } - else - { - $tplrow->setCurrentBlock("answer"); - $style = array(); + $rowclass = array("tblrow1", "tblrow2"); + for ($i = 0; $i < $this->object->getRowCount(); $i++) { + $rowobj = $this->object->getRow($i); + $tplrow = new ilTemplate("tpl.il_svy_out_matrix_row.html", true, true, "Modules/SurveyQuestionPool"); + for ($j = 0; $j < $this->object->getColumnCount(); $j++) { + $cat = $this->object->getColumn($j); + if (($i == 0) && ($j == 0)) { + if ((strlen($this->object->getBipolarAdjective(0))) && (strlen($this->object->getBipolarAdjective(1)))) { + $tplrow->setCurrentBlock("bipolar_start"); + $tplrow->setVariable("TEXT_BIPOLAR_START", ilUtil::prepareFormOutput($this->object->getBipolarAdjective(0))); + $tplrow->setVariable("ROWSPAN", $this->object->getRowCount()); + $tplrow->parseCurrentBlock(); + } + } + if (($i == 0) && ($j == $this->object->getColumnCount()-1)) { + if ((strlen($this->object->getBipolarAdjective(0))) && (strlen($this->object->getBipolarAdjective(1)))) { + $tplrow->setCurrentBlock("bipolar_end"); + $tplrow->setVariable("TEXT_BIPOLAR_END", ilUtil::prepareFormOutput($this->object->getBipolarAdjective(1))); + $tplrow->setVariable("ROWSPAN", $this->object->getRowCount()); + $tplrow->parseCurrentBlock(); + } + } + switch ($this->object->getSubtype()) { + case 0: + if ($cat->neutral) { + $tplrow->setCurrentBlock("neutral_radiobutton"); + $tplrow->setVariable("QUESTION_ID", $this->object->getId()); + $tplrow->setVariable("ROW", $i); + $tplrow->setVariable("VALUE", ($cat->scale) ? ($cat->scale - 1) : $j); + if (is_array($working_data)) { + foreach ($working_data as $data) { + if (($data["value"] == $cat->scale-1) && ($data["rowvalue"] == $i)) { + $tplrow->setVariable("CHECKED_RADIOBUTTON", " checked=\"checked\""); + } + } + } + $tplrow->parseCurrentBlock(); + } else { + $tplrow->setCurrentBlock("radiobutton"); + $tplrow->setVariable("QUESTION_ID", $this->object->getId()); + $tplrow->setVariable("ROW", $i); + $tplrow->setVariable("VALUE", ($cat->scale) ? ($cat->scale - 1) : $j); + if (is_array($working_data)) { + foreach ($working_data as $data) { + if (($data["value"] == $cat->scale-1) && ($data["rowvalue"] == $i)) { + $tplrow->setVariable("CHECKED_RADIOBUTTON", " checked=\"checked\""); + } + } + } + $tplrow->parseCurrentBlock(); + } + break; + case 1: + if ($cat->neutral) { + $tplrow->setCurrentBlock("neutral_checkbox"); + $tplrow->setVariable("QUESTION_ID", $this->object->getId()); + $tplrow->setVariable("ROW", $i); + $tplrow->setVariable("VALUE", ($cat->scale) ? ($cat->scale - 1) : $j); + if (is_array($working_data)) { + foreach ($working_data as $data) { + if (($data["value"] == $cat->scale-1) && ($data["rowvalue"] == $i)) { + $tplrow->setVariable("CHECKED_CHECKBOX", " checked=\"checked\""); + } + } + } + $tplrow->parseCurrentBlock(); + } else { + $tplrow->setCurrentBlock("checkbox"); + $tplrow->setVariable("QUESTION_ID", $this->object->getId()); + $tplrow->setVariable("ROW", $i); + $tplrow->setVariable("VALUE", ($cat->scale) ? ($cat->scale - 1) : $j); + if (is_array($working_data)) { + foreach ($working_data as $data) { + if (($data["value"] == $cat->scale-1) && ($data["rowvalue"] == $i)) { + $tplrow->setVariable("CHECKED_CHECKBOX", " checked=\"checked\""); + } + } + } + $tplrow->parseCurrentBlock(); + } + break; + } + if ($cat->neutral) { + $tplrow->setCurrentBlock("neutral_answer"); + $style = array(); + if ($this->object->getNeutralColumnSeparator()) { + array_push($style, "border-left: $neutralstyle!important"); + } + if ($this->object->getColumnSeparators() == 1) { + if ($j < $this->object->getColumnCount() - 1) { + array_push($style, "border-right: 1px solid $bordercolor!important"); + } + } + } else { + $tplrow->setCurrentBlock("answer"); + $style = array(); - if ($this->object->getColumnSeparators() == 1) - { - if ($j < $this->object->getColumnCount() - 1) - { - array_push($style, "border-right: 1px solid $bordercolor!important"); - } - } - } - if ($this->object->getRowSeparators() == 1) - { - if ($i < $this->object->getRowCount() - 1) - { - array_push($style, "border-bottom: 1px solid $bordercolor!important"); - } - } - if (count($style)) - { - $tplrow->setVariable("STYLE", " style=\"" . implode(";", $style) . "\""); - } - $tplrow->parseCurrentBlock(); - } + if ($this->object->getColumnSeparators() == 1) { + if ($j < $this->object->getColumnCount() - 1) { + array_push($style, "border-right: 1px solid $bordercolor!important"); + } + } + } + if ($this->object->getRowSeparators() == 1) { + if ($i < $this->object->getRowCount() - 1) { + array_push($style, "border-bottom: 1px solid $bordercolor!important"); + } + } + if (count($style)) { + $tplrow->setVariable("STYLE", " style=\"" . implode(";", $style) . "\""); + } + $tplrow->parseCurrentBlock(); + } - 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(); - } + 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 * @ingroup ModulesSurveyQuestionPool */ class SurveyMetricQuestionEvaluation extends SurveyQuestionEvaluation { - // - // RESULTS - // - - protected function parseResults(ilSurveyEvaluationResults $a_results, array $a_answers, SurveyCategories $a_categories = null) - { - parent::parseResults($a_results, $a_answers); - - // add arithmetic mean - $total = $sum = 0; - foreach($a_answers as $answers) - { - foreach($answers as $answer) - { - $total++; - $sum += $answer["value"]; - } - } - if($total > 0) - { - $a_results->setMean($sum/$total); - } - } - - - // - // DETAILS - // - - public function getGrid($a_results, $a_abs = true, $a_perc = true) - { - $lng = $this->lng; - - if((bool)$a_abs && (bool)$a_perc) - { - $cols = array( - $lng->txt("category_nr_selected"), - $lng->txt("svy_fraction_of_selections") - ); - } - else if((bool)$a_abs) - { - $cols = array( - $lng->txt("category_nr_selected") - ); - } - else - { - $cols = array( - $lng->txt("svy_fraction_of_selections") - ); - } - - $res = array( - "cols" => $cols, - "rows" => array() - ); - - // as we have no variables build rows from answers directly - $total = sizeof($a_results->getAnswers()); - if($total > 0) - { - $cumulated = array(); - foreach($a_results->getAnswers() as $answer) - { - $cumulated[$answer->value]++; - } - foreach($cumulated as $value => $count) - { - $perc = sprintf("%.2f", $count/$total*100)."%"; - if((bool)$a_abs && (bool)$a_perc) - { - $res["rows"][] = array( - $value, - $count, - $perc - ); - } - else if((bool)$a_abs) - { - $res["rows"][] = array( - $value, - $count - ); - } - else - { - $res["rows"][] = array( - $value, - $perc - ); - } - } - } - - return $res; - } - - public function getChart($a_results) - { - $lng = $this->lng; - - include_once "Services/Chart/classes/class.ilChart.php"; - $chart = ilChart::getInstanceByType(ilChart::TYPE_GRID, $a_results->getQuestion()->getId()); - $chart->setYAxisToInteger(true); - - $colors = $this->getChartColors(); - $chart->setColors($colors); + // + // RESULTS + // + + protected function parseResults(ilSurveyEvaluationResults $a_results, array $a_answers, SurveyCategories $a_categories = null) + { + parent::parseResults($a_results, $a_answers); + + // add arithmetic mean + $total = $sum = 0; + foreach ($a_answers as $answers) { + foreach ($answers as $answer) { + $total++; + $sum += $answer["value"]; + } + } + if ($total > 0) { + $a_results->setMean($sum/$total); + } + } + + + // + // DETAILS + // + + public function getGrid($a_results, $a_abs = true, $a_perc = true) + { + $lng = $this->lng; + + if ((bool) $a_abs && (bool) $a_perc) { + $cols = array( + $lng->txt("category_nr_selected"), + $lng->txt("svy_fraction_of_selections") + ); + } elseif ((bool) $a_abs) { + $cols = array( + $lng->txt("category_nr_selected") + ); + } else { + $cols = array( + $lng->txt("svy_fraction_of_selections") + ); + } + + $res = array( + "cols" => $cols, + "rows" => array() + ); + + // as we have no variables build rows from answers directly + $total = sizeof($a_results->getAnswers()); + if ($total > 0) { + $cumulated = array(); + foreach ($a_results->getAnswers() as $answer) { + $cumulated[$answer->value]++; + } + foreach ($cumulated as $value => $count) { + $perc = sprintf("%.2f", $count/$total*100) . "%"; + if ((bool) $a_abs && (bool) $a_perc) { + $res["rows"][] = array( + $value, + $count, + $perc + ); + } elseif ((bool) $a_abs) { + $res["rows"][] = array( + $value, + $count + ); + } else { + $res["rows"][] = array( + $value, + $perc + ); + } + } + } + + return $res; + } + + public function getChart($a_results) + { + $lng = $this->lng; + + include_once "Services/Chart/classes/class.ilChart.php"; + $chart = ilChart::getInstanceByType(ilChart::TYPE_GRID, $a_results->getQuestion()->getId()); + $chart->setYAxisToInteger(true); + + $colors = $this->getChartColors(); + $chart->setColors($colors); - // :TODO: - $chart->setsize($this->chart_width, $this->chart_height); - - $data = $chart->getDataInstance(ilChartGrid::DATA_BARS); - $data->setLabel($lng->txt("category_nr_selected")); - $data->setBarOptions(0.5, "center"); - $data->setFill(1); - - $total = sizeof($a_results->getAnswers()); - if($total > 0) - { - $cumulated = array(); - foreach($a_results->getAnswers() as $answer) - { - $cumulated[$answer->value]++; - } - - $labels = array(); - foreach($cumulated as $value => $count) - { - $data->addPoint($value, $count); - $labels[$value] = $value; - } - $chart->addData($data); + // :TODO: + $chart->setsize($this->chart_width, $this->chart_height); + + $data = $chart->getDataInstance(ilChartGrid::DATA_BARS); + $data->setLabel($lng->txt("category_nr_selected")); + $data->setBarOptions(0.5, "center"); + $data->setFill(1); + + $total = sizeof($a_results->getAnswers()); + if ($total > 0) { + $cumulated = array(); + foreach ($a_results->getAnswers() as $answer) { + $cumulated[$answer->value]++; + } + + $labels = array(); + foreach ($cumulated as $value => $count) { + $data->addPoint($value, $count); + $labels[$value] = $value; + } + $chart->addData($data); - $chart->setTicks($labels, false, true); - - return $chart->getHTML(); - } - } + $chart->setTicks($labels, false, true); + + return $chart->getHTML(); + } + } - - // - // EXPORT - // - - /** - * Get grid data - * - * @param ilSurveyEvaluationResults|array $a_results - * @return array - */ - public function getExportGrid($a_results) - { - $lng = $this->lng; - - $res = array( - "cols" => array( - $lng->txt("value"), - $lng->txt("category_nr_selected"), - $lng->txt("svy_fraction_of_selections") - ), - "rows" => array() - ); - - // as we have no variables build rows from answers directly - $total = sizeof($a_results->getAnswers()); - if($total > 0) - { - $cumulated = array(); - foreach($a_results->getAnswers() as $answer) - { - $cumulated[$answer->value]++; - } - foreach($cumulated as $value => $count) - { - $res["rows"][] = array( - $value, - $count, - sprintf("%.2f", $count/$total*100)."%" - ); - } - } - - return $res; - } - - public function addUserSpecificResults(array &$a_row, $a_user_id, $a_results) - { - $answer = $a_results->getUserResults($a_user_id); - if($answer === null) - { - $a_row[] = $this->getSkippedValue(); - } - else - { - $a_row[] = $answer[0][0]; - } - } -} \ No newline at end of file + + // + // EXPORT + // + + /** + * Get grid data + * + * @param ilSurveyEvaluationResults|array $a_results + * @return array + */ + public function getExportGrid($a_results) + { + $lng = $this->lng; + + $res = array( + "cols" => array( + $lng->txt("value"), + $lng->txt("category_nr_selected"), + $lng->txt("svy_fraction_of_selections") + ), + "rows" => array() + ); + + // as we have no variables build rows from answers directly + $total = sizeof($a_results->getAnswers()); + if ($total > 0) { + $cumulated = array(); + foreach ($a_results->getAnswers() as $answer) { + $cumulated[$answer->value]++; + } + foreach ($cumulated as $value => $count) { + $res["rows"][] = array( + $value, + $count, + sprintf("%.2f", $count/$total*100) . "%" + ); + } + } + + return $res; + } + + public function addUserSpecificResults(array &$a_row, $a_user_id, $a_results) + { + $answer = $a_results->getUserResults($a_user_id); + if ($answer === null) { + $a_row[] = $this->getSkippedValue(); + } else { + $a_row[] = $answer[0][0]; + } + } +} diff --git a/Modules/SurveyQuestionPool/classes/class.SurveyMetricQuestionGUI.php b/Modules/SurveyQuestionPool/classes/class.SurveyMetricQuestionGUI.php index bb6fd2fbacc4f7ff32a37c1c2b5ca399003c7432..8bda5a3d1c10311544dd91fd442e0ab5d34aba8a 100755 --- a/Modules/SurveyQuestionPool/classes/class.SurveyMetricQuestionGUI.php +++ b/Modules/SurveyQuestionPool/classes/class.SurveyMetricQuestionGUI.php @@ -34,230 +34,218 @@ include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php"; * @extends SurveyQuestionGUI * @ingroup ModulesSurveyQuestionPool */ -class SurveyMetricQuestionGUI extends SurveyQuestionGUI +class SurveyMetricQuestionGUI extends SurveyQuestionGUI { - protected function initObject() - { - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyMetricQuestion.php"; - $this->object = new SurveyMetricQuestion(); - } + protected function initObject() + { + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyMetricQuestion.php"; + $this->object = new SurveyMetricQuestion(); + } - - // - // EDITOR - // - - public function setQuestionTabs() - { - $this->setQuestionTabsForClass("surveymetricquestiongui"); - } - - protected function addFieldsToEditForm(ilPropertyFormGUI $a_form) - { - // subtype - $subtype = new ilRadioGroupInputGUI($this->lng->txt("subtype"), "type"); - $subtype->setRequired(true); - $a_form->addItem($subtype); - - // #10652 - $opt = new ilRadioOption($this->lng->txt('non_ratio'), SurveyMetricQuestion::SUBTYPE_NON_RATIO, $this->lng->txt("metric_subtype_description_interval")); - $subtype->addOption($opt); - - // minimum value - $minimum1 = new ilNumberInputGUI($this->lng->txt("minimum"), "minimum3"); - $minimum1->setRequired(false); - $minimum1->setSize(6); - $opt->addSubItem($minimum1); - - // maximum value - $maximum1 = new ilNumberInputGUI($this->lng->txt("maximum"), "maximum3"); - $maximum1->setRequired(false); - $maximum1->setSize(6); - $opt->addSubItem($maximum1); - - $opt = new ilRadioOption($this->lng->txt('ratio_non_absolute'), SurveyMetricQuestion::SUBTYPE_RATIO_NON_ABSOLUTE, $this->lng->txt("metric_subtype_description_rationonabsolute")); - $subtype->addOption($opt); - - // minimum value - $minimum2 = new ilNumberInputGUI($this->lng->txt("minimum"), "minimum4"); - $minimum2->setRequired(false); - $minimum2->setSize(6); - $minimum2->setMinValue(0); - $opt->addSubItem($minimum2); - - // maximum value - $maximum2 = new ilNumberInputGUI($this->lng->txt("maximum"), "maximum4"); - $maximum2->setRequired(false); - $maximum2->setSize(6); - $opt->addSubItem($maximum2); - - $opt = new ilRadioOption($this->lng->txt('ratio_absolute'), SurveyMetricQuestion::SUBTYPE_RATIO_ABSOLUTE, $this->lng->txt("metric_subtype_description_ratioabsolute")); - $subtype->addOption($opt); - - // minimum value - $minimum3 = new ilNumberInputGUI($this->lng->txt("minimum"), "minimum5"); - $minimum3->setRequired(false); - $minimum3->setSize(6); - $minimum3->setMinValue(0); - $minimum3->setDecimals(0); - $opt->addSubItem($minimum3); - - // maximum value - $maximum3 = new ilNumberInputGUI($this->lng->txt("maximum"), "maximum5"); - $maximum3->setDecimals(0); - $maximum3->setRequired(false); - $maximum3->setSize(6); - $opt->addSubItem($maximum3); - - - // values - $subtype->setValue($this->object->getSubtype()); - - switch($this->object->getSubtype()) - { - case SurveyMetricQuestion::SUBTYPE_NON_RATIO: - $minimum1->setValue($this->object->getMinimum()); - $maximum1->setValue($this->object->getMaximum()); - break; - - case SurveyMetricQuestion::SUBTYPE_RATIO_NON_ABSOLUTE: - $minimum2->setValue($this->object->getMinimum()); - $maximum2->setValue($this->object->getMaximum()); - break; - - case SurveyMetricQuestion::SUBTYPE_RATIO_ABSOLUTE: - $minimum3->setValue($this->object->getMinimum()); - $maximum3->setValue($this->object->getMaximum()); - break; - } - } - - protected function importEditFormValues(ilPropertyFormGUI $a_form) - { - $type = (int)$a_form->getInput("type"); - $this->object->setOrientation($a_form->getInput("orientation")); - $this->object->setSubtype($type); - $this->object->setMinimum($a_form->getInput("minimum".$type)); - $this->object->setMaximum($a_form->getInput("maximum".$type)); - } - - public function getParsedAnswers(array $a_working_data = null, $a_only_user_anwers = false) - { - $res = array(); - - if(is_array($a_working_data)) - { - $res[] = array("value" => $a_working_data[0]["value"]); - } - - return $res; - } - - /** - * Creates a HTML representation of the question - * - * Creates a HTML representation of the question - * - * @access private - */ - function getPrintView($question_title = 1, $show_questiontext = 1, $survey_id = null, array $a_working_data = null) - { - $user_answer = null; - if($a_working_data) - { - $user_answer = $this->getParsedAnswers($a_working_data); - $user_answer = $user_answer[0]["value"]; - } - - $template = new ilTemplate("tpl.il_svy_qpl_metric_printview.html", TRUE, TRUE, "Modules/SurveyQuestionPool"); - $template->setVariable("MIN_MAX", $this->object->getMinMaxText()); + + // + // EDITOR + // + + public function setQuestionTabs() + { + $this->setQuestionTabsForClass("surveymetricquestiongui"); + } + + protected function addFieldsToEditForm(ilPropertyFormGUI $a_form) + { + // subtype + $subtype = new ilRadioGroupInputGUI($this->lng->txt("subtype"), "type"); + $subtype->setRequired(true); + $a_form->addItem($subtype); + + // #10652 + $opt = new ilRadioOption($this->lng->txt('non_ratio'), SurveyMetricQuestion::SUBTYPE_NON_RATIO, $this->lng->txt("metric_subtype_description_interval")); + $subtype->addOption($opt); + + // minimum value + $minimum1 = new ilNumberInputGUI($this->lng->txt("minimum"), "minimum3"); + $minimum1->setRequired(false); + $minimum1->setSize(6); + $opt->addSubItem($minimum1); + + // maximum value + $maximum1 = new ilNumberInputGUI($this->lng->txt("maximum"), "maximum3"); + $maximum1->setRequired(false); + $maximum1->setSize(6); + $opt->addSubItem($maximum1); + + $opt = new ilRadioOption($this->lng->txt('ratio_non_absolute'), SurveyMetricQuestion::SUBTYPE_RATIO_NON_ABSOLUTE, $this->lng->txt("metric_subtype_description_rationonabsolute")); + $subtype->addOption($opt); + + // minimum value + $minimum2 = new ilNumberInputGUI($this->lng->txt("minimum"), "minimum4"); + $minimum2->setRequired(false); + $minimum2->setSize(6); + $minimum2->setMinValue(0); + $opt->addSubItem($minimum2); + + // maximum value + $maximum2 = new ilNumberInputGUI($this->lng->txt("maximum"), "maximum4"); + $maximum2->setRequired(false); + $maximum2->setSize(6); + $opt->addSubItem($maximum2); + + $opt = new ilRadioOption($this->lng->txt('ratio_absolute'), SurveyMetricQuestion::SUBTYPE_RATIO_ABSOLUTE, $this->lng->txt("metric_subtype_description_ratioabsolute")); + $subtype->addOption($opt); + + // minimum value + $minimum3 = new ilNumberInputGUI($this->lng->txt("minimum"), "minimum5"); + $minimum3->setRequired(false); + $minimum3->setSize(6); + $minimum3->setMinValue(0); + $minimum3->setDecimals(0); + $opt->addSubItem($minimum3); + + // maximum value + $maximum3 = new ilNumberInputGUI($this->lng->txt("maximum"), "maximum5"); + $maximum3->setDecimals(0); + $maximum3->setRequired(false); + $maximum3->setSize(6); + $opt->addSubItem($maximum3); + + + // values + $subtype->setValue($this->object->getSubtype()); + + switch ($this->object->getSubtype()) { + case SurveyMetricQuestion::SUBTYPE_NON_RATIO: + $minimum1->setValue($this->object->getMinimum()); + $maximum1->setValue($this->object->getMaximum()); + break; + + case SurveyMetricQuestion::SUBTYPE_RATIO_NON_ABSOLUTE: + $minimum2->setValue($this->object->getMinimum()); + $maximum2->setValue($this->object->getMaximum()); + break; + + case SurveyMetricQuestion::SUBTYPE_RATIO_ABSOLUTE: + $minimum3->setValue($this->object->getMinimum()); + $maximum3->setValue($this->object->getMaximum()); + break; + } + } + + protected function importEditFormValues(ilPropertyFormGUI $a_form) + { + $type = (int) $a_form->getInput("type"); + $this->object->setOrientation($a_form->getInput("orientation")); + $this->object->setSubtype($type); + $this->object->setMinimum($a_form->getInput("minimum" . $type)); + $this->object->setMaximum($a_form->getInput("maximum" . $type)); + } + + public function getParsedAnswers(array $a_working_data = null, $a_only_user_anwers = false) + { + $res = array(); + + if (is_array($a_working_data)) { + $res[] = array("value" => $a_working_data[0]["value"]); + } + + return $res; + } + + /** + * Creates a HTML representation of the question + * + * 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) + { + $user_answer = null; + if ($a_working_data) { + $user_answer = $this->getParsedAnswers($a_working_data); + $user_answer = $user_answer[0]["value"]; + } + + $template = new ilTemplate("tpl.il_svy_qpl_metric_printview.html", true, true, "Modules/SurveyQuestionPool"); + $template->setVariable("MIN_MAX", $this->object->getMinMaxText()); - if ($show_questiontext) - { - $this->outQuestionText($template); - } - if ($question_title) - { - $template->setVariable("QUESTION_TITLE", $this->getPrintViewQuestionTitle($question_title)); - } - $template->setVariable("TEXT_ANSWER", $this->lng->txt("answer")); - $template->setVariable("QUESTION_ID", $this->object->getId()); + if ($show_questiontext) { + $this->outQuestionText($template); + } + if ($question_title) { + $template->setVariable("QUESTION_TITLE", $this->getPrintViewQuestionTitle($question_title)); + } + $template->setVariable("TEXT_ANSWER", $this->lng->txt("answer")); + $template->setVariable("QUESTION_ID", $this->object->getId()); - if(!is_array($a_working_data) || !trim($user_answer)) - { - $solution_text = ""; - $len = 10; - for ($i = 0; $i < 10; $i++) $solution_text .= " "; - } - else - { - $solution_text = $user_answer; - } - $template->setVariable("TEXT_SOLUTION", $solution_text); + if (!is_array($a_working_data) || !trim($user_answer)) { + $solution_text = ""; + $len = 10; + for ($i = 0; $i < 10; $i++) { + $solution_text .= " "; + } + } else { + $solution_text = $user_answer; + } + $template->setVariable("TEXT_SOLUTION", $solution_text); - $template->parseCurrentBlock(); - return $template->get(); - } - - - // - // EXECUTION - // + $template->parseCurrentBlock(); + return $template->get(); + } + + + // + // EXECUTION + // - /** - * Creates the question output form for the learner - * - * Creates the question output form for the learner - * - * @access public - */ - function getWorkingForm($working_data = "", $question_title = 1, $show_questiontext = 1, $error_message = "", $survey_id = null) - { - $template = new ilTemplate("tpl.il_svy_out_metric.html", TRUE, TRUE, "Modules/SurveyQuestionPool"); - $template->setCurrentBlock("material_metric"); - $template->setVariable("TEXT_MATERIAL", $this->getMaterialOutput()); - $template->parseCurrentBlock(); - $template->setVariable("MIN_MAX", $this->object->getMinMaxText()); - /*if (strlen($this->object->getMinimum())) - { - $template->setCurrentBlock("minimum"); - $template->setVariable("TEXT_MINIMUM", $this->lng->txt("minimum")); - $template->setVariable("VALUE_MINIMUM", $this->object->getMinimum()); - $template->parseCurrentBlock(); - } - if (strlen($this->object->getMaximum())) - { - $template->setCurrentBlock("maximum"); - $template->setVariable("TEXT_MAXIMUM", $this->lng->txt("maximum")); - $template->setVariable("VALUE_MAXIMUM", $this->object->getMaximum()); - $template->parseCurrentBlock(); - }*/ + /** + * Creates the question output form for the learner + * + * 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_metric.html", true, true, "Modules/SurveyQuestionPool"); + $template->setCurrentBlock("material_metric"); + $template->setVariable("TEXT_MATERIAL", $this->getMaterialOutput()); + $template->parseCurrentBlock(); + $template->setVariable("MIN_MAX", $this->object->getMinMaxText()); + /*if (strlen($this->object->getMinimum())) + { + $template->setCurrentBlock("minimum"); + $template->setVariable("TEXT_MINIMUM", $this->lng->txt("minimum")); + $template->setVariable("VALUE_MINIMUM", $this->object->getMinimum()); + $template->parseCurrentBlock(); + } + if (strlen($this->object->getMaximum())) + { + $template->setCurrentBlock("maximum"); + $template->setVariable("TEXT_MAXIMUM", $this->lng->txt("maximum")); + $template->setVariable("VALUE_MAXIMUM", $this->object->getMaximum()); + $template->parseCurrentBlock(); + }*/ - $template->setVariable("QUESTIONTEXT", $this->object->prepareTextareaOutput($questiontext, TRUE)); - 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("QUESTION_ID", $this->object->getId()); - if (is_array($working_data)) - { - $template->setVariable("VALUE_METRIC", $working_data[0]["value"]); - } + $template->setVariable("QUESTIONTEXT", $this->object->prepareTextareaOutput($questiontext, true)); + 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("QUESTION_ID", $this->object->getId()); + if (is_array($working_data)) { + $template->setVariable("VALUE_METRIC", $working_data[0]["value"]); + } - $template->setVariable("INPUT_SIZE", 10); + $template->setVariable("INPUT_SIZE", 10); - if (strcmp($error_message, "") != 0) - { - $template->setVariable("ERROR_MESSAGE", "

$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 * @ingroup ModulesSurveyQuestionPool */ class SurveyMultipleChoiceQuestionEvaluation extends SurveyQuestionEvaluation { - - // - // EXPORT - // - - public function getUserSpecificVariableTitles(array &$a_title_row, array &$a_title_row2, $a_do_title, $a_do_label) - { - $lng = $this->lng; - - $categories = $this->question->getCategories(); - for ($i = 0; $i < $categories->getCategoryCount(); $i++) - { - $cat = $categories->getCategory($i); - - $a_title_row[] = $cat->title." [".$cat->scale."]"; - $a_title_row2[] = ""; - - if ($cat->other) - { - $a_title_row[] = $cat->title." [".$cat->scale."]"; - $a_title_row2[] = $lng->txt('other'); - } - } - } - - public function addUserSpecificResults(array &$a_row, $a_user_id, $a_results) - { - $categories = $this->question->getCategories(); - - $answers = $a_results->getUserResults($a_user_id); - if($answers === null) - { - $a_row[] = $this->getSkippedValue(); - - for ($i = 0; $i < $categories->getCategoryCount(); $i++) - { - $cat = $categories->getCategory($i); - $a_row[] = ""; - - if($cat->other) - { - $a_row[] = ""; - } - } - } - else - { - $a_row[] = ""; - - for ($i = 0; $i < $categories->getCategoryCount(); $i++) - { - $cat = $categories->getCategory($i); - $found = false; - foreach($answers as $answer) - { - if($answer[2] == $cat->scale) - { - $a_row[] = $answer[2]; - if ($cat->other) - { - $a_row[] = $answer[1]; - } - $found = true; - } - } - if(!$found) - { - $a_row[] = ""; // "0" ?! - if ($cat->other) - { - $a_row[] = ""; - } - } - } - } - } -} \ No newline at end of file + + // + // EXPORT + // + + public function getUserSpecificVariableTitles(array &$a_title_row, array &$a_title_row2, $a_do_title, $a_do_label) + { + $lng = $this->lng; + + $categories = $this->question->getCategories(); + for ($i = 0; $i < $categories->getCategoryCount(); $i++) { + $cat = $categories->getCategory($i); + + $a_title_row[] = $cat->title . " [" . $cat->scale . "]"; + $a_title_row2[] = ""; + + if ($cat->other) { + $a_title_row[] = $cat->title . " [" . $cat->scale . "]"; + $a_title_row2[] = $lng->txt('other'); + } + } + } + + public function addUserSpecificResults(array &$a_row, $a_user_id, $a_results) + { + $categories = $this->question->getCategories(); + + $answers = $a_results->getUserResults($a_user_id); + if ($answers === null) { + $a_row[] = $this->getSkippedValue(); + + for ($i = 0; $i < $categories->getCategoryCount(); $i++) { + $cat = $categories->getCategory($i); + $a_row[] = ""; + + if ($cat->other) { + $a_row[] = ""; + } + } + } else { + $a_row[] = ""; + + for ($i = 0; $i < $categories->getCategoryCount(); $i++) { + $cat = $categories->getCategory($i); + $found = false; + foreach ($answers as $answer) { + if ($answer[2] == $cat->scale) { + $a_row[] = $answer[2]; + if ($cat->other) { + $a_row[] = $answer[1]; + } + $found = true; + } + } + if (!$found) { + $a_row[] = ""; // "0" ?! + if ($cat->other) { + $a_row[] = ""; + } + } + } + } + } +} diff --git a/Modules/SurveyQuestionPool/classes/class.SurveyMultipleChoiceQuestionGUI.php b/Modules/SurveyQuestionPool/classes/class.SurveyMultipleChoiceQuestionGUI.php index c32833dc700b81e516acf9b4e3c2504f24b5447f..a1710e921433aa470689f1eade975f19bce6a2ed 100755 --- a/Modules/SurveyQuestionPool/classes/class.SurveyMultipleChoiceQuestionGUI.php +++ b/Modules/SurveyQuestionPool/classes/class.SurveyMultipleChoiceQuestionGUI.php @@ -34,483 +34,415 @@ include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php"; * @extends SurveyQuestionGUI * @ingroup ModulesSurveyQuestionPool */ -class SurveyMultipleChoiceQuestionGUI extends SurveyQuestionGUI +class SurveyMultipleChoiceQuestionGUI extends SurveyQuestionGUI { - protected function initObject( ) - { - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyMultipleChoiceQuestion.php"; - $this->object = new SurveyMultipleChoiceQuestion(); - } + protected function initObject() + { + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyMultipleChoiceQuestion.php"; + $this->object = new SurveyMultipleChoiceQuestion(); + } - // - // EDITOR - // - - public function setQuestionTabs() - { - $this->setQuestionTabsForClass("surveymultiplechoicequestiongui"); - } - - protected function addFieldsToEditForm(ilPropertyFormGUI $a_form) - { - // orientation - $orientation = new ilRadioGroupInputGUI($this->lng->txt("orientation"), "orientation"); - $orientation->setRequired(false); - $orientation->addOption(new ilRadioOption($this->lng->txt('vertical'), 0)); - $orientation->addOption(new ilRadioOption($this->lng->txt('horizontal'), 1)); - $a_form->addItem($orientation); + // + // EDITOR + // + + public function setQuestionTabs() + { + $this->setQuestionTabsForClass("surveymultiplechoicequestiongui"); + } + + protected function addFieldsToEditForm(ilPropertyFormGUI $a_form) + { + // orientation + $orientation = new ilRadioGroupInputGUI($this->lng->txt("orientation"), "orientation"); + $orientation->setRequired(false); + $orientation->addOption(new ilRadioOption($this->lng->txt('vertical'), 0)); + $orientation->addOption(new ilRadioOption($this->lng->txt('horizontal'), 1)); + $a_form->addItem($orientation); - // minimum answers - $minanswers = new ilCheckboxInputGUI($this->lng->txt("use_min_answers"), "use_min_answers"); - $minanswers->setValue(1); - $minanswers->setOptionTitle($this->lng->txt("use_min_answers_option")); - $minanswers->setRequired(FALSE); - - $nranswers = new ilNumberInputGUI($this->lng->txt("nr_min_answers"), "nr_min_answers"); - $nranswers->setSize(5); - $nranswers->setDecimals(0); - $nranswers->setRequired(false); - $nranswers->setMinValue(1); - $minanswers->addSubItem($nranswers); - - $nrmaxanswers = new ilNumberInputGUI($this->lng->txt("nr_max_answers"), "nr_max_answers"); - $nrmaxanswers->setSize(5); - $nrmaxanswers->setDecimals(0); - $nrmaxanswers->setRequired(false); - $nrmaxanswers->setMinValue(1); - $minanswers->addSubItem($nrmaxanswers); - - $a_form->addItem($minanswers); + // minimum answers + $minanswers = new ilCheckboxInputGUI($this->lng->txt("use_min_answers"), "use_min_answers"); + $minanswers->setValue(1); + $minanswers->setOptionTitle($this->lng->txt("use_min_answers_option")); + $minanswers->setRequired(false); + + $nranswers = new ilNumberInputGUI($this->lng->txt("nr_min_answers"), "nr_min_answers"); + $nranswers->setSize(5); + $nranswers->setDecimals(0); + $nranswers->setRequired(false); + $nranswers->setMinValue(1); + $minanswers->addSubItem($nranswers); + + $nrmaxanswers = new ilNumberInputGUI($this->lng->txt("nr_max_answers"), "nr_max_answers"); + $nrmaxanswers->setSize(5); + $nrmaxanswers->setDecimals(0); + $nrmaxanswers->setRequired(false); + $nrmaxanswers->setMinValue(1); + $minanswers->addSubItem($nrmaxanswers); + + $a_form->addItem($minanswers); - // Answers - include_once "./Modules/SurveyQuestionPool/classes/class.ilCategoryWizardInputGUI.php"; - $answers = new ilCategoryWizardInputGUI($this->lng->txt("answers"), "answers"); - $answers->setRequired(false); - $answers->setAllowMove(true); - $answers->setShowWizard(false); - $answers->setShowSavePhrase(false); - $answers->setUseOtherAnswer(true); - $answers->setShowNeutralCategory(true); - $answers->setNeutralCategoryTitle($this->lng->txt('svy_neutral_answer')); - $answers->setDisabledScale(false); - $a_form->addItem($answers); - - - // values - $orientation->setValue($this->object->getOrientation()); - $minanswers->setChecked($this->object->use_min_answers); - $nranswers->setValue($this->object->nr_min_answers); - $nrmaxanswers->setValue($this->object->nr_max_answers); - if (!$this->object->getCategories()->getCategoryCount()) - { - $this->object->getCategories()->addCategory(""); - } - $answers->setValues($this->object->getCategories()); - } - - protected function validateEditForm(ilPropertyFormGUI $a_form) - { - if($a_form->getInput("use_min_answers")) - { - // #13927 - see importEditFormValues() - $cnt_answers = 0; - foreach ($_POST['answers']['answer'] as $key => $value) - { - if (strlen($value)) - { - $cnt_answers++; - } - } - if (strlen($_POST['answers']['neutral'])) - { - $cnt_answers++; - } - /* this would be the DB-values - $cnt_answers = $a_form->getItemByPostVar("answers"); - $cnt_answers = $cnt_answers->getCategoryCount(); - */ - $min_anwers = $a_form->getInput("nr_min_answers"); - $max_anwers = $a_form->getInput("nr_max_answers"); - - if ($min_anwers && - $min_anwers > $cnt_answers) - { - $a_form->getItemByPostVar("nr_min_answers")->setAlert($this->lng->txt('err_minvalueganswers')); - $errors = true; - } - if ($max_anwers > 0 && - ($max_anwers > $cnt_answers || $max_anwers < $min_anwers)) - { - $a_form->getItemByPostVar("nr_max_answers")->setAlert($this->lng->txt('err_maxvaluegeminvalue')); - $errors = true; - } - } - - ilUtil::sendFailure($this->lng->txt('form_input_not_valid')); - return !$errors; - } - - protected function importEditFormValues(ilPropertyFormGUI $a_form) - { - $this->object->setOrientation($a_form->getInput("orientation")); - $this->object->use_other_answer = ($a_form->getInput('use_other_answer')) ? 1 : 0; - $this->object->other_answer_label = $this->object->use_other_answer ? $a_form->getInput('other_answer_label') : null; - $this->object->use_min_answers = ($a_form->getInput('use_min_answers')) ? true : false; - $this->object->nr_min_answers = ($a_form->getInput('nr_min_answers') > 0) ? $a_form->getInput('nr_min_answers') : null; - $this->object->nr_max_answers = ($a_form->getInput('nr_max_answers') > 0) ? $a_form->getInput('nr_max_answers') : null; - $this->object->label = $a_form->getInput('label'); + // Answers + include_once "./Modules/SurveyQuestionPool/classes/class.ilCategoryWizardInputGUI.php"; + $answers = new ilCategoryWizardInputGUI($this->lng->txt("answers"), "answers"); + $answers->setRequired(false); + $answers->setAllowMove(true); + $answers->setShowWizard(false); + $answers->setShowSavePhrase(false); + $answers->setUseOtherAnswer(true); + $answers->setShowNeutralCategory(true); + $answers->setNeutralCategoryTitle($this->lng->txt('svy_neutral_answer')); + $answers->setDisabledScale(false); + $a_form->addItem($answers); + + + // values + $orientation->setValue($this->object->getOrientation()); + $minanswers->setChecked($this->object->use_min_answers); + $nranswers->setValue($this->object->nr_min_answers); + $nrmaxanswers->setValue($this->object->nr_max_answers); + if (!$this->object->getCategories()->getCategoryCount()) { + $this->object->getCategories()->addCategory(""); + } + $answers->setValues($this->object->getCategories()); + } + + protected function validateEditForm(ilPropertyFormGUI $a_form) + { + if ($a_form->getInput("use_min_answers")) { + // #13927 - see importEditFormValues() + $cnt_answers = 0; + foreach ($_POST['answers']['answer'] as $key => $value) { + if (strlen($value)) { + $cnt_answers++; + } + } + if (strlen($_POST['answers']['neutral'])) { + $cnt_answers++; + } + /* this would be the DB-values + $cnt_answers = $a_form->getItemByPostVar("answers"); + $cnt_answers = $cnt_answers->getCategoryCount(); + */ + $min_anwers = $a_form->getInput("nr_min_answers"); + $max_anwers = $a_form->getInput("nr_max_answers"); + + if ($min_anwers && + $min_anwers > $cnt_answers) { + $a_form->getItemByPostVar("nr_min_answers")->setAlert($this->lng->txt('err_minvalueganswers')); + $errors = true; + } + if ($max_anwers > 0 && + ($max_anwers > $cnt_answers || $max_anwers < $min_anwers)) { + $a_form->getItemByPostVar("nr_max_answers")->setAlert($this->lng->txt('err_maxvaluegeminvalue')); + $errors = true; + } + } + + ilUtil::sendFailure($this->lng->txt('form_input_not_valid')); + return !$errors; + } + + protected function importEditFormValues(ilPropertyFormGUI $a_form) + { + $this->object->setOrientation($a_form->getInput("orientation")); + $this->object->use_other_answer = ($a_form->getInput('use_other_answer')) ? 1 : 0; + $this->object->other_answer_label = $this->object->use_other_answer ? $a_form->getInput('other_answer_label') : null; + $this->object->use_min_answers = ($a_form->getInput('use_min_answers')) ? true : false; + $this->object->nr_min_answers = ($a_form->getInput('nr_min_answers') > 0) ? $a_form->getInput('nr_min_answers') : null; + $this->object->nr_max_answers = ($a_form->getInput('nr_max_answers') > 0) ? $a_form->getInput('nr_max_answers') : null; + $this->object->label = $a_form->getInput('label'); - $this->object->categories->flushCategories(); + $this->object->categories->flushCategories(); - 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 - */ - 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)); - } - else if ($this->object->nr_min_answers > 0) - { - $template->setVariable('MIN_MAX_MSG', sprintf($this->lng->txt('msg_min_nr_answers'), $this->object->nr_min_answers)); - } - else if ($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 - */ - 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)); - } - } - else if ($this->object->nr_min_answers > 0) - { - $template->setVariable('MIN_MAX_MSG', sprintf($this->lng->txt('msg_min_nr_answers'), $this->object->nr_min_answers)); - } - else if ($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(); - } + 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 * @ingroup ModulesSurveyQuestionPool */ abstract class SurveyQuestionEvaluation { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; - protected $question; // [SurveyQuestion] - protected $finished_ids; // [array] - protected $chart_width = 400; - protected $chart_height = 300; - - /** - * Constructor - * - * @param SurveyQuestion $a_question - * @param array $a_finished_ids - * @return self - */ - public function __construct(SurveyQuestion $a_question, array $a_finished_ids = null) - { - global $DIC; + protected $question; // [SurveyQuestion] + protected $finished_ids; // [array] + protected $chart_width = 400; + protected $chart_height = 300; + + /** + * Constructor + * + * @param SurveyQuestion $a_question + * @param array $a_finished_ids + * @return self + */ + public function __construct(SurveyQuestion $a_question, array $a_finished_ids = null) + { + global $DIC; - $this->lng = $DIC->language(); - $this->db = $DIC->database(); - $this->question = $a_question; - $this->finished_ids = $a_finished_ids; - } - - - // - // RESULTS - // - - /** - * Get results - * - * @return ilSurveyEvaluationResults|array - */ - public function getResults() - { - $results = new ilSurveyEvaluationResults($this->question); - $answers = $this->getAnswerData(); - - $this->parseResults( - $results, - (array)$answers[0], - method_exists($this->question, "getCategories") - ? $this->question->getCategories() - : null - ); - - return $results; - } - - /** - * Parse answer data into results instance - * - * @param ilSurveyEvaluationResults $a_results - * @param array $a_answers - * @param SurveyCategories $a_categories - */ - protected function parseResults(ilSurveyEvaluationResults $a_results, array $a_answers, SurveyCategories $a_categories = null) - { - $num_users_answered = sizeof($a_answers); + $this->lng = $DIC->language(); + $this->db = $DIC->database(); + $this->question = $a_question; + $this->finished_ids = $a_finished_ids; + } + + + // + // RESULTS + // + + /** + * Get results + * + * @return ilSurveyEvaluationResults|array + */ + public function getResults() + { + $results = new ilSurveyEvaluationResults($this->question); + $answers = $this->getAnswerData(); + + $this->parseResults( + $results, + (array) $answers[0], + method_exists($this->question, "getCategories") + ? $this->question->getCategories() + : null + ); + + return $results; + } + + /** + * Parse answer data into results instance + * + * @param ilSurveyEvaluationResults $a_results + * @param array $a_answers + * @param SurveyCategories $a_categories + */ + protected function parseResults(ilSurveyEvaluationResults $a_results, array $a_answers, SurveyCategories $a_categories = null) + { + $num_users_answered = sizeof($a_answers); - $a_results->setUsersAnswered($num_users_answered); - $a_results->setUsersSkipped($this->getNrOfParticipants()-$num_users_answered); - - // parse answers - $has_multi = false; - $selections = array(); - foreach($a_answers as $active_id => $answers) - { - // :TODO: - if(sizeof($answers) > 1) - { - $has_multi = true; - } - foreach($answers as $answer) - { - // map selection value to scale/category - if($a_categories && - $answer["value"] != "") - { - $scale = $a_categories->getCategoryForScale($answer["value"]+1); - if($scale instanceof ilSurveyCategory) - { - $answer["value"] = $scale->scale; - } - } - - $parsed = new ilSurveyEvaluationResultsAnswer( - $active_id, - $answer["value"], - $answer["text"] - ); - $a_results->addAnswer($parsed); + $a_results->setUsersAnswered($num_users_answered); + $a_results->setUsersSkipped($this->getNrOfParticipants()-$num_users_answered); + + // parse answers + $has_multi = false; + $selections = array(); + foreach ($a_answers as $active_id => $answers) { + // :TODO: + if (sizeof($answers) > 1) { + $has_multi = true; + } + foreach ($answers as $answer) { + // map selection value to scale/category + if ($a_categories && + $answer["value"] != "") { + $scale = $a_categories->getCategoryForScale($answer["value"]+1); + if ($scale instanceof ilSurveyCategory) { + $answer["value"] = $scale->scale; + } + } + + $parsed = new ilSurveyEvaluationResultsAnswer( + $active_id, + $answer["value"], + $answer["text"] + ); + $a_results->addAnswer($parsed); - if($answer["value"] != "") - { - $selections[$answer["value"]]++; - } - } - } - - $total = array_sum($selections); + if ($answer["value"] != "") { + $selections[$answer["value"]]++; + } + } + } + + $total = array_sum($selections); - if($total) - { - // mode - $mode_nr = max($selections); - $tmp_mode = $selections; - asort($tmp_mode, SORT_NUMERIC); - $mode = array_keys($tmp_mode, $mode_nr); - $a_results->setMode($mode, $mode_nr); - - if(!$has_multi) - { - // median - ksort($selections, SORT_NUMERIC); - $median = array(); - foreach($selections as $value => $count) - { - for($i = 0; $i < $count; $i++) - { - $median[] = $value; - } - } - if($total % 2 == 0) - { - $lower = $median[($total/2)-1]; - $upper = $median[($total/2)]; - $median_value = 0.5 * ($lower + $upper); - if($a_categories && - round($median_value) != $median_value) - { - // mapping calculated value to scale values - $median_value = array($lower, $upper); - } - } - else - { - $median_value = $median[(($total+1)/2)-1]; - } - $a_results->setMedian($median_value); - } - } - - if($a_categories) - { - // selections by category - for ($c = 0; $c < $a_categories->getCategoryCount(); $c++) - { - $cat = $a_categories->getCategory($c); - $scale = $cat->scale; + if ($total) { + // mode + $mode_nr = max($selections); + $tmp_mode = $selections; + asort($tmp_mode, SORT_NUMERIC); + $mode = array_keys($tmp_mode, $mode_nr); + $a_results->setMode($mode, $mode_nr); + + if (!$has_multi) { + // median + ksort($selections, SORT_NUMERIC); + $median = array(); + foreach ($selections as $value => $count) { + for ($i = 0; $i < $count; $i++) { + $median[] = $value; + } + } + if ($total % 2 == 0) { + $lower = $median[($total/2)-1]; + $upper = $median[($total/2)]; + $median_value = 0.5 * ($lower + $upper); + if ($a_categories && + round($median_value) != $median_value) { + // mapping calculated value to scale values + $median_value = array($lower, $upper); + } + } else { + $median_value = $median[(($total+1)/2)-1]; + } + $a_results->setMedian($median_value); + } + } + + if ($a_categories) { + // selections by category + for ($c = 0; $c < $a_categories->getCategoryCount(); $c++) { + $cat = $a_categories->getCategory($c); + $scale = $cat->scale; - $var = new ilSurveyEvaluationResultsVariable( - $cat, - $selections[$scale], - $total - ? $selections[$scale]/$total - : null - ); - $a_results->addVariable($var); - } - } - } - - public function parseUserSpecificResults($a_qres, $a_user_id) - { - $parsed_results = array(); - - if(is_array($a_qres)) - { - foreach($a_qres as $row_idx => $row_results) - { - $row_title = $row_results[0]; - $user_results = $row_results[1]->getUserResults($a_user_id); - if($user_results) - { - foreach($user_results as $item) - { - // :TODO: layout - $tmp = $row_title.": "; - if($item[0] !== "") - { - $tmp .= $item[0]; - } - if($item[1] && $item[0]) - { - $tmp .= ", \"".nl2br($item[1])."\""; - } - else if($item[1]) - { - $tmp .= "\"".nl2br($item[1])."\""; - } - $parsed_results[$row_idx."-".$item[2]] = $tmp; - } - } - } + $var = new ilSurveyEvaluationResultsVariable( + $cat, + $selections[$scale], + $total + ? $selections[$scale]/$total + : null + ); + $a_results->addVariable($var); + } + } + } + + public function parseUserSpecificResults($a_qres, $a_user_id) + { + $parsed_results = array(); + + if (is_array($a_qres)) { + foreach ($a_qres as $row_idx => $row_results) { + $row_title = $row_results[0]; + $user_results = $row_results[1]->getUserResults($a_user_id); + if ($user_results) { + foreach ($user_results as $item) { + // :TODO: layout + $tmp = $row_title . ": "; + if ($item[0] !== "") { + $tmp .= $item[0]; + } + if ($item[1] && $item[0]) { + $tmp .= ", \"" . nl2br($item[1]) . "\""; + } elseif ($item[1]) { + $tmp .= "\"" . nl2br($item[1]) . "\""; + } + $parsed_results[$row_idx . "-" . $item[2]] = $tmp; + } + } + } + } else { + $user_results = $a_qres->getUserResults($a_user_id); + if ($user_results) { + foreach ($user_results as $item) { + // :TODO: layout + if ($item[0] !== "") { + $tmp = $item[0]; + } + if ($item[1] && $item[0]) { + $tmp .= ", \"" . nl2br($item[1]) . "\""; + } elseif ($item[1]) { + $tmp = "\"" . nl2br($item[1]) . "\""; + } + $parsed_results[$item[2]] = $tmp; + } + } + } + + return $parsed_results; + } + + + // + // DETAILS + // + + /** + * Get grid data + * + * @param ilSurveyEvaluationResults|array $a_results + * @param bool $a_abs + * @param bool $a_perc + * @return array + */ + public function getGrid($a_results, $a_abs = true, $a_perc = true) + { + $lng = $this->lng; + + if ((bool) $a_abs && (bool) $a_perc) { + $cols = array( + $lng->txt("category_nr_selected"), + $lng->txt("svy_fraction_of_selections") + ); + } elseif ((bool) $a_abs) { + $cols = array( + $lng->txt("category_nr_selected") + ); + } else { + $cols = array( + $lng->txt("svy_fraction_of_selections") + ); + } + + $res = array( + "cols" => $cols, + "rows" => array() + ); + + $vars = $a_results->getVariables(); + if ($vars) { + foreach ($vars as $var) { + $perc = $var->perc + ? sprintf("%.2f", $var->perc*100) . "%" + : "0%"; + + if ((bool) $a_abs && (bool) $a_perc) { + $res["rows"][] = array( + $var->cat->title, + $var->abs, + $perc + ); + } elseif ((bool) $a_abs) { + $res["rows"][] = array( + $var->cat->title, + $var->abs + ); + } else { + $res["rows"][] = array( + $var->cat->title, + $perc + ); + } + } + } + + return $res; + } + + /** + * Get text answers + * + * @param ilSurveyEvaluationResults|array $a_results + * @return array + */ + public function getTextAnswers($a_results) + { + return $a_results->getMappedTextAnswers(); + } + + protected function getChartColors() + { + return array( + // flot "default" theme + "#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed", + // http://godsnotwheregodsnot.blogspot.de/2012/09/color-distribution-methodology.html + "#1CE6FF", "#FF34FF", "#FF4A46", "#008941", "#006FA6", "#A30059", + "#FFDBE5", "#7A4900", "#0000A6", "#63FFAC", "#B79762", "#004D43", "#8FB0FF", "#997D87", + "#5A0007", "#809693", "#FEFFE6", "#1B4400", "#4FC601", "#3B5DFF", "#4A3B53", "#FF2F80", + "#61615A", "#BA0900", "#6B7900", "#00C2A0", "#FFAA92", "#FF90C9", "#B903AA", "#D16100", + "#DDEFFF", "#000035", "#7B4F4B", "#A1C299", "#300018", "#0AA6D8", "#013349", "#00846F", + "#372101", "#FFB500", "#C2FFED", "#A079BF", "#CC0744", "#C0B9B2", "#C2FF99", "#001E09", + "#00489C", "#6F0062", "#0CBD66", "#EEC3FF", "#456D75", "#B77B68", "#7A87A1", "#788D66", + "#885578", "#FAD09F", "#FF8A9A", "#D157A0", "#BEC459", "#456648", "#0086ED", "#886F4C", + "#34362D", "#B4A8BD", "#00A6AA", "#452C2C", "#636375", "#A3C8C9", "#FF913F", "#938A81", + "#575329", "#00FECF", "#B05B6F", "#8CD0FF", "#3B9700", "#04F757", "#C8A1A1", "#1E6E00", + "#7900D7", "#A77500", "#6367A9", "#A05837", "#6B002C", "#772600", "#D790FF", "#9B9700", + "#549E79", "#FFF69F", "#201625", "#72418F", "#BC23FF", "#99ADC0", "#3A2465", "#922329", + "#5B4534", "#FDE8DC", "#404E55", "#0089A3", "#CB7E98", "#A4E804", "#324E72", "#6A3A4C" + ); + } + + /** + * Get chart + * + * @param ilSurveyEvaluationResults|array $a_results + * @return array + */ + public function getChart($a_results) + { + include_once "Services/Chart/classes/class.ilChart.php"; + $chart = ilChart::getInstanceByType(ilChart::TYPE_GRID, $a_results->getQuestion()->getId()); + $chart->setYAxisToInteger(true); - } - else - { - $user_results = $a_qres->getUserResults($a_user_id); - if($user_results) - { - foreach($user_results as $item) - { - // :TODO: layout - if($item[0] !== "") - { - $tmp = $item[0]; - } - if($item[1] && $item[0]) - { - $tmp .= ", \"".nl2br($item[1])."\""; - } - else if($item[1]) - { - $tmp = "\"".nl2br($item[1])."\""; - } - $parsed_results[$item[2]] = $tmp; - } - } - } - - return $parsed_results; - } - - - // - // DETAILS - // - - /** - * Get grid data - * - * @param ilSurveyEvaluationResults|array $a_results - * @param bool $a_abs - * @param bool $a_perc - * @return array - */ - public function getGrid($a_results, $a_abs = true, $a_perc = true) - { - $lng = $this->lng; - - if((bool)$a_abs && (bool)$a_perc) - { - $cols = array( - $lng->txt("category_nr_selected"), - $lng->txt("svy_fraction_of_selections") - ); - } - else if((bool)$a_abs) - { - $cols = array( - $lng->txt("category_nr_selected") - ); - } - else - { - $cols = array( - $lng->txt("svy_fraction_of_selections") - ); - } - - $res = array( - "cols" => $cols, - "rows" => array() - ); - - $vars = $a_results->getVariables(); - if($vars) - { - foreach($vars as $var) - { - $perc = $var->perc - ? sprintf("%.2f", $var->perc*100)."%" - : "0%"; - - if((bool)$a_abs && (bool)$a_perc) - { - $res["rows"][] = array( - $var->cat->title, - $var->abs, - $perc - ); - } - else if((bool)$a_abs) - { - $res["rows"][] = array( - $var->cat->title, - $var->abs - ); - } - else - { - $res["rows"][] = array( - $var->cat->title, - $perc - ); - } - } - } - - return $res; - } - - /** - * Get text answers - * - * @param ilSurveyEvaluationResults|array $a_results - * @return array - */ - public function getTextAnswers($a_results) - { - return $a_results->getMappedTextAnswers(); - } - - protected function getChartColors() - { - return array( - // flot "default" theme - "#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed", - // http://godsnotwheregodsnot.blogspot.de/2012/09/color-distribution-methodology.html - "#1CE6FF", "#FF34FF", "#FF4A46", "#008941", "#006FA6", "#A30059", - "#FFDBE5", "#7A4900", "#0000A6", "#63FFAC", "#B79762", "#004D43", "#8FB0FF", "#997D87", - "#5A0007", "#809693", "#FEFFE6", "#1B4400", "#4FC601", "#3B5DFF", "#4A3B53", "#FF2F80", - "#61615A", "#BA0900", "#6B7900", "#00C2A0", "#FFAA92", "#FF90C9", "#B903AA", "#D16100", - "#DDEFFF", "#000035", "#7B4F4B", "#A1C299", "#300018", "#0AA6D8", "#013349", "#00846F", - "#372101", "#FFB500", "#C2FFED", "#A079BF", "#CC0744", "#C0B9B2", "#C2FF99", "#001E09", - "#00489C", "#6F0062", "#0CBD66", "#EEC3FF", "#456D75", "#B77B68", "#7A87A1", "#788D66", - "#885578", "#FAD09F", "#FF8A9A", "#D157A0", "#BEC459", "#456648", "#0086ED", "#886F4C", - "#34362D", "#B4A8BD", "#00A6AA", "#452C2C", "#636375", "#A3C8C9", "#FF913F", "#938A81", - "#575329", "#00FECF", "#B05B6F", "#8CD0FF", "#3B9700", "#04F757", "#C8A1A1", "#1E6E00", - "#7900D7", "#A77500", "#6367A9", "#A05837", "#6B002C", "#772600", "#D790FF", "#9B9700", - "#549E79", "#FFF69F", "#201625", "#72418F", "#BC23FF", "#99ADC0", "#3A2465", "#922329", - "#5B4534", "#FDE8DC", "#404E55", "#0089A3", "#CB7E98", "#A4E804", "#324E72", "#6A3A4C" - ); - } - - /** - * Get chart - * - * @param ilSurveyEvaluationResults|array $a_results - * @return array - */ - public function getChart($a_results) - { - include_once "Services/Chart/classes/class.ilChart.php"; - $chart = ilChart::getInstanceByType(ilChart::TYPE_GRID, $a_results->getQuestion()->getId()); - $chart->setYAxisToInteger(true); + $colors = $this->getChartColors(); + $chart->setColors($colors); + + // :TODO: + $chart->setsize($this->chart_width, $this->chart_height); + + $vars = $a_results->getVariables(); + + $legend = $labels = array(); + foreach ($vars as $idx => $var) { + $data = $chart->getDataInstance(ilChartGrid::DATA_BARS); + $data->setBarOptions(0.5, "center"); + $data->setFill(1); + $chart->addData($data); + + // labels + $labels[$idx] = ""; + $legend[] = array( + $var->cat->title, + $colors[$idx] + ); + $data->setLabel($var->cat->title); + + $data->addPoint($idx, $var->abs); + } + + $chart->setTicks($labels, false, true); - $colors = $this->getChartColors(); - $chart->setColors($colors); - - // :TODO: - $chart->setsize($this->chart_width, $this->chart_height); - - $vars = $a_results->getVariables(); - - $legend = $labels = array(); - foreach($vars as $idx => $var) - { - $data = $chart->getDataInstance(ilChartGrid::DATA_BARS); - $data->setBarOptions(0.5, "center"); - $data->setFill(1); - $chart->addData($data); - - // labels - $labels[$idx] = ""; - $legend[] = array( - $var->cat->title, - $colors[$idx] - ); - $data->setLabel($var->cat->title); - - $data->addPoint($idx, $var->abs); - } - - $chart->setTicks($labels, false, true); - - return array( - $chart->getHTML(), - $legend - ); - } - - - // - // USER-SPECIFIC - // - - /** - * Get caption for skipped value - * - * @return string - */ - public function getSkippedValue() - { - include_once "Modules/Survey/classes/class.ilObjSurvey.php"; - return ilObjSurvey::getSurveySkippedValue(); - } - - - // - // HELPER - // - - protected function getSurveyId() - { - $ilDB = $this->db; - - // #18968 - $set = $ilDB->query("SELECT survey_fi". - " FROM svy_svy_qst". - " WHERE question_fi = ".$ilDB->quote($this->question->getId(), "integer")); - $row = $ilDB->fetchAssoc($set); - return $row["survey_fi"]; - } - - - /** - * Returns the number of participants for a survey - * - * @return integer The number of participants - */ - protected function getNrOfParticipants() - { - $ilDB = $this->db; - - if(is_array($this->finished_ids)) - { - return sizeof($this->finished_ids); - } - - $set = $ilDB->query("SELECT finished_id FROM svy_finished". - " WHERE survey_fi = ".$ilDB->quote($this->getSurveyId(), "integer")); - return $set->numRows(); - } - - protected function getAnswerData() - { - $ilDB = $this->db; - - $res = array(); - - $sql = "SELECT svy_answer.* FROM svy_answer". - " JOIN svy_finished ON (svy_finished.finished_id = svy_answer.active_fi)". - " WHERE svy_answer.question_fi = ".$ilDB->quote($this->question->getId(), "integer"). - " AND svy_finished.survey_fi = ".$ilDB->quote($this->getSurveyId(), "integer"); - if(is_array($this->finished_ids)) - { - $sql .= " AND ".$ilDB->in("svy_finished.finished_id", $this->finished_ids, "", "integer"); - } - $set = $ilDB->query($sql); - while($row = $ilDB->fetchAssoc($set)) - { - $res[(int)$row["rowvalue"]][(int)$row["active_fi"]][] = array( - "value" => $row["value"], - "text" => $row["textanswer"] - ); - } - - return $res; - } - - - // - // EXPORT - // - - public function exportResults($a_results, $a_do_title, $a_do_label) - { - $question = $a_results->getQuestion(); - - $res = array(); - - if($a_do_title) - { - $res[] = $question->getTitle(); - } - if($a_do_label) - { - $res[] = $question->label; - } - - $res[] = $question->getQuestiontext(); - $res[] = SurveyQuestion::_getQuestionTypeName($question->getQuestionType()); - - $res[] = (int)$a_results->getUsersAnswered(); - $res[] = (int)$a_results->getUsersSkipped(); - - // :TODO: - $res[] = is_array($a_results->getModeValue()) - ? implode(", ", $a_results->getModeValue()) - : $a_results->getModeValue(); - - $res[] = $a_results->getModeValueAsText(); - $res[] = (int)$a_results->getModeNrOfSelections(); - - // :TODO: - $res[] = $a_results->getMedianAsText(); - - $res[] = $a_results->getMean(); - - return array($res); - } - - /** - * Get grid data - * - * @param ilSurveyEvaluationResults|array $a_results - * @return array - */ - public function getExportGrid($a_results) - { - $lng = $this->lng; - - $res = array( - "cols" => array( - $lng->txt("title"), - $lng->txt("value"), - $lng->txt("category_nr_selected"), - $lng->txt("svy_fraction_of_selections") - ), - "rows" => array() - ); - - $vars = $a_results->getVariables(); - if($vars) - { - foreach($vars as $var) - { - $res["rows"][] = array( - $var->cat->title, - $var->cat->scale, - $var->abs, - $var->perc - ? sprintf("%.2f", $var->perc*100)."%" - : "0%" - ); - } - } - - return $res; - } - - /** - * Get title columns for user-specific export - * - * @param array $a_title_row - * @param array $a_title_row2 - * @param bool $a_do_title - * @param bool $a_do_label - */ - public function getUserSpecificVariableTitles(array &$a_title_row, array &$a_title_row2, $a_do_title, $a_do_label) - { - // type-specific - } - - /** - * - * - * @param array $a_row - * @param int $a_user_id - * @param ilSurveyEvaluationResults|array $a_results - */ - abstract public function addUserSpecificResults(array &$a_row, $a_user_id, $a_results); -} \ No newline at end of file + return array( + $chart->getHTML(), + $legend + ); + } + + + // + // USER-SPECIFIC + // + + /** + * Get caption for skipped value + * + * @return string + */ + public function getSkippedValue() + { + include_once "Modules/Survey/classes/class.ilObjSurvey.php"; + return ilObjSurvey::getSurveySkippedValue(); + } + + + // + // HELPER + // + + protected function getSurveyId() + { + $ilDB = $this->db; + + // #18968 + $set = $ilDB->query("SELECT survey_fi" . + " FROM svy_svy_qst" . + " WHERE question_fi = " . $ilDB->quote($this->question->getId(), "integer")); + $row = $ilDB->fetchAssoc($set); + return $row["survey_fi"]; + } + + + /** + * Returns the number of participants for a survey + * + * @return integer The number of participants + */ + protected function getNrOfParticipants() + { + $ilDB = $this->db; + + if (is_array($this->finished_ids)) { + return sizeof($this->finished_ids); + } + + $set = $ilDB->query("SELECT finished_id FROM svy_finished" . + " WHERE survey_fi = " . $ilDB->quote($this->getSurveyId(), "integer")); + return $set->numRows(); + } + + protected function getAnswerData() + { + $ilDB = $this->db; + + $res = array(); + + $sql = "SELECT svy_answer.* FROM svy_answer" . + " JOIN svy_finished ON (svy_finished.finished_id = svy_answer.active_fi)" . + " WHERE svy_answer.question_fi = " . $ilDB->quote($this->question->getId(), "integer") . + " AND svy_finished.survey_fi = " . $ilDB->quote($this->getSurveyId(), "integer"); + if (is_array($this->finished_ids)) { + $sql .= " AND " . $ilDB->in("svy_finished.finished_id", $this->finished_ids, "", "integer"); + } + $set = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($set)) { + $res[(int) $row["rowvalue"]][(int) $row["active_fi"]][] = array( + "value" => $row["value"], + "text" => $row["textanswer"] + ); + } + + return $res; + } + + + // + // EXPORT + // + + public function exportResults($a_results, $a_do_title, $a_do_label) + { + $question = $a_results->getQuestion(); + + $res = array(); + + if ($a_do_title) { + $res[] = $question->getTitle(); + } + if ($a_do_label) { + $res[] = $question->label; + } + + $res[] = $question->getQuestiontext(); + $res[] = SurveyQuestion::_getQuestionTypeName($question->getQuestionType()); + + $res[] = (int) $a_results->getUsersAnswered(); + $res[] = (int) $a_results->getUsersSkipped(); + + // :TODO: + $res[] = is_array($a_results->getModeValue()) + ? implode(", ", $a_results->getModeValue()) + : $a_results->getModeValue(); + + $res[] = $a_results->getModeValueAsText(); + $res[] = (int) $a_results->getModeNrOfSelections(); + + // :TODO: + $res[] = $a_results->getMedianAsText(); + + $res[] = $a_results->getMean(); + + return array($res); + } + + /** + * Get grid data + * + * @param ilSurveyEvaluationResults|array $a_results + * @return array + */ + public function getExportGrid($a_results) + { + $lng = $this->lng; + + $res = array( + "cols" => array( + $lng->txt("title"), + $lng->txt("value"), + $lng->txt("category_nr_selected"), + $lng->txt("svy_fraction_of_selections") + ), + "rows" => array() + ); + + $vars = $a_results->getVariables(); + if ($vars) { + foreach ($vars as $var) { + $res["rows"][] = array( + $var->cat->title, + $var->cat->scale, + $var->abs, + $var->perc + ? sprintf("%.2f", $var->perc*100) . "%" + : "0%" + ); + } + } + + return $res; + } + + /** + * Get title columns for user-specific export + * + * @param array $a_title_row + * @param array $a_title_row2 + * @param bool $a_do_title + * @param bool $a_do_label + */ + public function getUserSpecificVariableTitles(array &$a_title_row, array &$a_title_row2, $a_do_title, $a_do_label) + { + // type-specific + } + + /** + * + * + * @param array $a_row + * @param int $a_user_id + * @param ilSurveyEvaluationResults|array $a_results + */ + abstract public function addUserSpecificResults(array &$a_row, $a_user_id, $a_results); +} diff --git a/Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php b/Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php index 595ba5bfc0b0fd22aa9132f3a9b271476814a20f..4ebb4d98f5d900b6a858a1663e7775856e70e416 100755 --- a/Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php +++ b/Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php @@ -31,1189 +31,1100 @@ * @version $Id$ * @ingroup ModulesSurveyQuestionPool */ -abstract class SurveyQuestionGUI +abstract class SurveyQuestionGUI { - /** - * @var ilRbacSystem - */ - protected $rbacsystem; + /** + * @var ilRbacSystem + */ + protected $rbacsystem; - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * @var ilTree - */ - protected $tree; + /** + * @var ilTree + */ + protected $tree; - /** - * @var ilToolbarGUI - */ - protected $toolbar; + /** + * @var ilToolbarGUI + */ + protected $toolbar; - /** - * @var ilTabsGUI - */ - protected $tabs; + /** + * @var ilTabsGUI + */ + protected $tabs; - protected $tpl; - protected $lng; - protected $ctrl; - protected $cumulated; // [array] - protected $parent_url; + protected $tpl; + protected $lng; + protected $ctrl; + protected $cumulated; // [array] + protected $parent_url; /** * @var ilLogger */ protected $log; - - public $object; - - public function __construct($a_id = -1) - { - global $DIC; + + public $object; + + public function __construct($a_id = -1) + { + global $DIC; - $this->rbacsystem = $DIC->rbac()->system(); - $this->user = $DIC->user(); - $this->access = $DIC->access(); - $this->tree = $DIC->repositoryTree(); - $this->toolbar = $DIC->toolbar(); - $lng = $DIC->language(); - $tpl = $DIC["tpl"]; - $ilCtrl = $DIC->ctrl(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->user = $DIC->user(); + $this->access = $DIC->access(); + $this->tree = $DIC->repositoryTree(); + $this->toolbar = $DIC->toolbar(); + $lng = $DIC->language(); + $tpl = $DIC["tpl"]; + $ilCtrl = $DIC->ctrl(); - $this->lng = $lng; - $this->tpl = $tpl; - $this->ctrl = $ilCtrl; - $this->ctrl->saveParameter($this, "q_id"); - $this->ctrl->setParameterByClass($_GET["cmdClass"], "sel_question_types", $_GET["sel_question_types"]); - $this->cumulated = array(); - $this->tabs = $DIC->tabs(); - - $this->initObject(); - - if($a_id > 0) - { - $this->object->loadFromDb($a_id); - } + $this->lng = $lng; + $this->tpl = $tpl; + $this->ctrl = $ilCtrl; + $this->ctrl->saveParameter($this, "q_id"); + $this->ctrl->setParameterByClass($_GET["cmdClass"], "sel_question_types", $_GET["sel_question_types"]); + $this->cumulated = array(); + $this->tabs = $DIC->tabs(); + + $this->initObject(); + + if ($a_id > 0) { + $this->object->loadFromDb($a_id); + } $this->log = ilLoggerFactory::getLogger('svy'); - } - - abstract protected function initObject(); - abstract public function setQuestionTabs(); - - public function &executeCommand() - { - $cmd = $this->ctrl->getCmd(); - $next_class = $this->ctrl->getNextClass($this); - switch($next_class) - { - default: - $ret =& $this->$cmd(); - break; - } - return $ret; - } + + abstract protected function initObject(); + abstract public function setQuestionTabs(); + + public function &executeCommand() + { + $cmd = $this->ctrl->getCmd(); + $next_class = $this->ctrl->getNextClass($this); + switch ($next_class) { + default: + $ret =&$this->$cmd(); + break; + } + return $ret; + } - /** - * Creates a question gui representation - * - * Creates a question gui representation and returns the alias to the question gui - * note: please do not use $this inside this method to allow static calls - * - * @param string $question_type The question type as it is used in the language database - * @param integer $question_id The database ID of an existing question to load it into ASS_QuestionGUI - * @return object The alias to the question object - * @access public - */ - static function _getQuestionGUI($questiontype, $question_id = -1) - { - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - if ((!$questiontype) and ($question_id > 0)) - { - $questiontype = SurveyQuestion::_getQuestiontype($question_id); - } - SurveyQuestion::_includeClass($questiontype, 1); - $question_type_gui = $questiontype . "GUI"; - $question = new $question_type_gui($question_id); - return $question; - } - - static function _getGUIClassNameForId($a_q_id) - { - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php"; - $q_type = SurveyQuestion::_getQuestiontype($a_q_id); - $class_name = SurveyQuestionGUI::_getClassNameForQType($q_type); - return $class_name; - } + /** + * Creates a question gui representation + * + * Creates a question gui representation and returns the alias to the question gui + * note: please do not use $this inside this method to allow static calls + * + * @param string $question_type The question type as it is used in the language database + * @param integer $question_id The database ID of an existing question to load it into ASS_QuestionGUI + * @return object The alias to the question object + * @access public + */ + public static function _getQuestionGUI($questiontype, $question_id = -1) + { + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + if ((!$questiontype) and ($question_id > 0)) { + $questiontype = SurveyQuestion::_getQuestiontype($question_id); + } + SurveyQuestion::_includeClass($questiontype, 1); + $question_type_gui = $questiontype . "GUI"; + $question = new $question_type_gui($question_id); + return $question; + } + + public static function _getGUIClassNameForId($a_q_id) + { + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php"; + $q_type = SurveyQuestion::_getQuestiontype($a_q_id); + $class_name = SurveyQuestionGUI::_getClassNameForQType($q_type); + return $class_name; + } - static function _getClassNameForQType($q_type) - { - return $q_type; - } - - /** - * Returns the question type string - * - * @result string The question type string - * @access public - */ - function getQuestionType() - { - return $this->object->getQuestionType(); - } - - protected function outQuestionText($template) - { - $questiontext = $this->object->getQuestiontext(); - if (preg_match("/^<.[\\>]?>(.*?)<\\/.[\\>]*?>$/", $questiontext, $matches)) - { - $questiontext = $matches[1]; - } - $template->setVariable("QUESTIONTEXT", $this->object->prepareTextareaOutput($questiontext, TRUE)); - if ($this->object->getObligatory($survey_id)) - { - $template->setVariable("OBLIGATORY_TEXT", ' *'); - } - } - - public function setBackUrl($a_url) - { - $this->parent_url = $a_url; - } - - function setQuestionTabsForClass($guiclass) - { - $rbacsystem = $this->rbacsystem; - $ilTabs = $this->tabs; - - $this->ctrl->setParameterByClass($guiclass, "sel_question_types", $this->getQuestionType()); - $this->ctrl->setParameterByClass($guiclass, "q_id", $_GET["q_id"]); - - if ($this->parent_url) - { - $addurl = ""; - if (strlen($_GET["new_for_survey"])) - { - $addurl = "&new_id=" . $_GET["q_id"]; - } - $ilTabs->setBackTarget($this->lng->txt("menubacktosurvey"), $this->parent_url . $addurl); - } - else - { - $this->ctrl->setParameterByClass("ilObjSurveyQuestionPoolGUI", "q_id_table_nav", $_SESSION['q_id_table_nav']); - $ilTabs->setBackTarget($this->lng->txt("spl"), $this->ctrl->getLinkTargetByClass("ilObjSurveyQuestionPoolGUI", "questions")); - } - if ($_GET["q_id"]) - { - $ilTabs->addNonTabbedLink("preview", - $this->lng->txt("preview"), - $this->ctrl->getLinkTargetByClass($guiclass, "preview")); - } - - if ($rbacsystem->checkAccess('edit', $_GET["ref_id"])) - { - $ilTabs->addTab("edit_properties", - $this->lng->txt("properties"), - $this->ctrl->getLinkTargetByClass($guiclass, "editQuestion")); - - if(stristr($guiclass, "matrix")) - { - $ilTabs->addTab("layout", - $this->lng->txt("layout"), - $this->ctrl->getLinkTargetByClass($guiclass, "layout")); - } - } - if ($_GET["q_id"]) - { - $ilTabs->addTab("material", - $this->lng->txt("material"), - $this->ctrl->getLinkTargetByClass($guiclass, "material")); - } + public static function _getClassNameForQType($q_type) + { + return $q_type; + } + + /** + * Returns the question type string + * + * @result string The question type string + * @access public + */ + public function getQuestionType() + { + return $this->object->getQuestionType(); + } + + protected function outQuestionText($template) + { + $questiontext = $this->object->getQuestiontext(); + if (preg_match("/^<.[\\>]?>(.*?)<\\/.[\\>]*?>$/", $questiontext, $matches)) { + $questiontext = $matches[1]; + } + $template->setVariable("QUESTIONTEXT", $this->object->prepareTextareaOutput($questiontext, true)); + if ($this->object->getObligatory($survey_id)) { + $template->setVariable("OBLIGATORY_TEXT", ' *'); + } + } + + public function setBackUrl($a_url) + { + $this->parent_url = $a_url; + } + + public function setQuestionTabsForClass($guiclass) + { + $rbacsystem = $this->rbacsystem; + $ilTabs = $this->tabs; + + $this->ctrl->setParameterByClass($guiclass, "sel_question_types", $this->getQuestionType()); + $this->ctrl->setParameterByClass($guiclass, "q_id", $_GET["q_id"]); + + if ($this->parent_url) { + $addurl = ""; + if (strlen($_GET["new_for_survey"])) { + $addurl = "&new_id=" . $_GET["q_id"]; + } + $ilTabs->setBackTarget($this->lng->txt("menubacktosurvey"), $this->parent_url . $addurl); + } else { + $this->ctrl->setParameterByClass("ilObjSurveyQuestionPoolGUI", "q_id_table_nav", $_SESSION['q_id_table_nav']); + $ilTabs->setBackTarget($this->lng->txt("spl"), $this->ctrl->getLinkTargetByClass("ilObjSurveyQuestionPoolGUI", "questions")); + } + if ($_GET["q_id"]) { + $ilTabs->addNonTabbedLink( + "preview", + $this->lng->txt("preview"), + $this->ctrl->getLinkTargetByClass($guiclass, "preview") + ); + } + + if ($rbacsystem->checkAccess('edit', $_GET["ref_id"])) { + $ilTabs->addTab( + "edit_properties", + $this->lng->txt("properties"), + $this->ctrl->getLinkTargetByClass($guiclass, "editQuestion") + ); + + if (stristr($guiclass, "matrix")) { + $ilTabs->addTab( + "layout", + $this->lng->txt("layout"), + $this->ctrl->getLinkTargetByClass($guiclass, "layout") + ); + } + } + if ($_GET["q_id"]) { + $ilTabs->addTab( + "material", + $this->lng->txt("material"), + $this->ctrl->getLinkTargetByClass($guiclass, "material") + ); + } - if ($this->object->getId() > 0) - { - $title = $this->lng->txt("edit") . " "" . $this->object->getTitle() . """; - } - else - { - $title = $this->lng->txt("create_new") . " " . $this->lng->txt($this->getQuestionType()); - } + if ($this->object->getId() > 0) { + $title = $this->lng->txt("edit") . " "" . $this->object->getTitle() . """; + } else { + $title = $this->lng->txt("create_new") . " " . $this->lng->txt($this->getQuestionType()); + } - $this->tpl->setVariable("HEADER", $title); - } + $this->tpl->setVariable("HEADER", $title); + } - - // - // EDITOR - // - - protected function initEditForm() - { - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this, "save")); - $form->setTitle($this->lng->txt($this->getQuestionType())); - $form->setMultipart(FALSE); - $form->setTableWidth("100%"); - // $form->setId("essay"); + + // + // EDITOR + // + + protected function initEditForm() + { + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this, "save")); + $form->setTitle($this->lng->txt($this->getQuestionType())); + $form->setMultipart(false); + $form->setTableWidth("100%"); + // $form->setId("essay"); - // title - $title = new ilTextInputGUI($this->lng->txt("title"), "title"); - $title->setRequired(TRUE); - $form->addItem($title); - - // label - $label = new ilTextInputGUI($this->lng->txt("label"), "label"); - $label->setInfo($this->lng->txt("label_info")); - $label->setRequired(false); - $form->addItem($label); + // title + $title = new ilTextInputGUI($this->lng->txt("title"), "title"); + $title->setRequired(true); + $form->addItem($title); + + // label + $label = new ilTextInputGUI($this->lng->txt("label"), "label"); + $label->setInfo($this->lng->txt("label_info")); + $label->setRequired(false); + $form->addItem($label); - // author - $author = new ilTextInputGUI($this->lng->txt("author"), "author"); - $author->setRequired(TRUE); - $form->addItem($author); - - // description - $description = new ilTextInputGUI($this->lng->txt("description"), "description"); - $description->setRequired(FALSE); - $form->addItem($description); - - // questiontext - $question = new ilTextAreaInputGUI($this->lng->txt("question"), "question"); - $question->setRequired(TRUE); - $question->setRows(10); - $question->setCols(80); - $question->setUseRte(TRUE); - include_once "./Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php"; - $question->setRteTags(ilObjAdvancedEditing::_getUsedHTMLTags("survey")); - $question->addPlugin("latex"); - $question->addButton("latex"); - $question->addButton("pastelatex"); - $question->setRTESupport($this->object->getId(), "spl", "survey"); - $form->addItem($question); - - // obligatory - $shuffle = new ilCheckboxInputGUI($this->lng->txt("obligatory"), "obligatory"); - $shuffle->setValue(1); - $shuffle->setRequired(FALSE); - $form->addItem($shuffle); - - $this->addFieldsToEditForm($form); - - $this->addCommandButtons($form); - - // values - $title->setValue($this->object->getTitle()); - $label->setValue($this->object->label); - $author->setValue($this->object->getAuthor()); - $description->setValue($this->object->getDescription()); - $question->setValue($this->object->prepareTextareaOutput($this->object->getQuestiontext())); - $shuffle->setChecked($this->object->getObligatory()); - - return $form; - } - - protected function addCommandButtons($a_form) - { - $a_form->addCommandButton("saveReturn", $this->lng->txt("save_return")); - $a_form->addCommandButton("save", $this->lng->txt("save")); - - // pool question? - if(ilObject::_lookupType($this->object->getObjId()) == "spl") - { - if($this->object->hasCopies()) - { - $a_form->addCommandButton("saveSync", $this->lng->txt("svy_save_sync")); - } - } - } - - protected function editQuestion(ilPropertyFormGUI $a_form = null) - { - $ilTabs = $this->tabs; - - $ilTabs->activateTab("edit_properties"); - - if(!$a_form) - { - $a_form = $this->initEditForm(); - } - $this->tpl->setContent($a_form->getHTML()); - } - - protected function saveSync() - { - $this->save($_REQUEST["rtrn"], true); - } + // author + $author = new ilTextInputGUI($this->lng->txt("author"), "author"); + $author->setRequired(true); + $form->addItem($author); + + // description + $description = new ilTextInputGUI($this->lng->txt("description"), "description"); + $description->setRequired(false); + $form->addItem($description); + + // questiontext + $question = new ilTextAreaInputGUI($this->lng->txt("question"), "question"); + $question->setRequired(true); + $question->setRows(10); + $question->setCols(80); + $question->setUseRte(true); + include_once "./Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php"; + $question->setRteTags(ilObjAdvancedEditing::_getUsedHTMLTags("survey")); + $question->addPlugin("latex"); + $question->addButton("latex"); + $question->addButton("pastelatex"); + $question->setRTESupport($this->object->getId(), "spl", "survey"); + $form->addItem($question); + + // obligatory + $shuffle = new ilCheckboxInputGUI($this->lng->txt("obligatory"), "obligatory"); + $shuffle->setValue(1); + $shuffle->setRequired(false); + $form->addItem($shuffle); + + $this->addFieldsToEditForm($form); + + $this->addCommandButtons($form); + + // values + $title->setValue($this->object->getTitle()); + $label->setValue($this->object->label); + $author->setValue($this->object->getAuthor()); + $description->setValue($this->object->getDescription()); + $question->setValue($this->object->prepareTextareaOutput($this->object->getQuestiontext())); + $shuffle->setChecked($this->object->getObligatory()); + + return $form; + } + + protected function addCommandButtons($a_form) + { + $a_form->addCommandButton("saveReturn", $this->lng->txt("save_return")); + $a_form->addCommandButton("save", $this->lng->txt("save")); + + // pool question? + if (ilObject::_lookupType($this->object->getObjId()) == "spl") { + if ($this->object->hasCopies()) { + $a_form->addCommandButton("saveSync", $this->lng->txt("svy_save_sync")); + } + } + } + + protected function editQuestion(ilPropertyFormGUI $a_form = null) + { + $ilTabs = $this->tabs; + + $ilTabs->activateTab("edit_properties"); + + if (!$a_form) { + $a_form = $this->initEditForm(); + } + $this->tpl->setContent($a_form->getHTML()); + } + + protected function saveSync() + { + $this->save($_REQUEST["rtrn"], true); + } - protected function saveReturn() - { - $this->save(true); - } - - protected function saveForm() - { - $form = $this->initEditForm(); - if($form->checkInput()) - { - if ($this->validateEditForm($form)) - { - $this->object->setTitle($form->getInput("title")); - $this->object->label = ($form->getInput("label")); - $this->object->setAuthor($form->getInput("author")); - $this->object->setDescription($form->getInput("description")); - $this->object->setQuestiontext($form->getInput("question")); - $this->object->setObligatory($form->getInput("obligatory")); - - $this->importEditFormValues($form); - - // will save both core and extended data - $this->object->saveToDb(); - - return true; - } - } - - $form->setValuesByPost(); - $this->editQuestion($form); - return false; - } - - protected function save($a_return = false, $a_sync = false) - { - $ilUser = $this->user; - - if($this->saveForm()) - { - // #13784 - if ($a_return && - !SurveyQuestion::_isComplete($this->object->getId())) - { - ilUtil::sendFailure($this->lng->txt("survey_error_insert_incomplete_question")); - return $this->editQuestion(); - } - - $ilUser->setPref("svy_lastquestiontype", $this->object->getQuestionType()); - $ilUser->writePref("svy_lastquestiontype", $this->object->getQuestionType()); + protected function saveReturn() + { + $this->save(true); + } + + protected function saveForm() + { + $form = $this->initEditForm(); + if ($form->checkInput()) { + if ($this->validateEditForm($form)) { + $this->object->setTitle($form->getInput("title")); + $this->object->label = ($form->getInput("label")); + $this->object->setAuthor($form->getInput("author")); + $this->object->setDescription($form->getInput("description")); + $this->object->setQuestiontext($form->getInput("question")); + $this->object->setObligatory($form->getInput("obligatory")); + + $this->importEditFormValues($form); + + // will save both core and extended data + $this->object->saveToDb(); + + return true; + } + } + + $form->setValuesByPost(); + $this->editQuestion($form); + return false; + } + + protected function save($a_return = false, $a_sync = false) + { + $ilUser = $this->user; + + if ($this->saveForm()) { + // #13784 + if ($a_return && + !SurveyQuestion::_isComplete($this->object->getId())) { + ilUtil::sendFailure($this->lng->txt("survey_error_insert_incomplete_question")); + return $this->editQuestion(); + } + + $ilUser->setPref("svy_lastquestiontype", $this->object->getQuestionType()); + $ilUser->writePref("svy_lastquestiontype", $this->object->getQuestionType()); - $originalexists = SurveyQuestion::_questionExists($this->object->original_id); - $this->ctrl->setParameter($this, "q_id", $this->object->getId()); - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + $originalexists = SurveyQuestion::_questionExists($this->object->original_id); + $this->ctrl->setParameter($this, "q_id", $this->object->getId()); + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - // pool question? - if($a_sync) - { - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, 'copySyncForm'); - } - else - { - // form: update original pool question, too? - if ($originalexists && - SurveyQuestion::_isWriteable($this->object->original_id, $ilUser->getId())) - { - if($a_return) - { - $this->ctrl->setParameter($this, 'rtrn', 1); - } - $this->ctrl->redirect($this, 'originalSyncForm'); - } - } + // pool question? + if ($a_sync) { + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, 'copySyncForm'); + } else { + // form: update original pool question, too? + if ($originalexists && + SurveyQuestion::_isWriteable($this->object->original_id, $ilUser->getId())) { + if ($a_return) { + $this->ctrl->setParameter($this, 'rtrn', 1); + } + $this->ctrl->redirect($this, 'originalSyncForm'); + } + } - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->redirectAfterSaving($a_return); - } - } - - protected function copySyncForm() - { - $ilTabs = $this->tabs; - - $ilTabs->activateTab("edit_properties"); - - include_once "Modules/SurveyQuestionPool/classes/class.ilSurveySyncTableGUI.php"; - $tbl = new ilSurveySyncTableGUI($this, "copySyncForm", $this->object); - - $this->tpl->setContent($tbl->getHTML()); - } - - protected function syncCopies() - { - $lng = $this->lng; - $ilAccess = $this->access; - - if(!sizeof($_POST["qid"])) - { - ilUtil::sendFailure($lng->txt("select_one")); - return $this->copySyncForm(); - } - - foreach($this->object->getCopyIds(true) as $survey_id => $questions) - { - // check permissions for "parent" survey - $can_write = false; - $ref_ids = ilObject::_getAllReferences($survey_id); - foreach($ref_ids as $ref_id) - { - if($ilAccess->checkAccess("edit", "", $ref_id)) - { - $can_write = true; - break; - } - } - - if($can_write) - { - foreach($questions as $qid) - { - if(in_array($qid, $_POST["qid"])) - { - $id = $this->object->getId(); - - $this->object->setId($qid); - $this->object->setOriginalId($id); - $this->object->saveToDb(); - - $this->object->setId($id); - $this->object->setOriginalId(null); - - // see: SurveyQuestion::syncWithOriginal() - // what about material? - } - } - } - } - - ilUtil::sendSuccess($lng->txt("survey_sync_success"), true); - $this->redirectAfterSaving($_REQUEST["rtrn"]); - } - - protected function originalSyncForm() - { - $ilTabs = $this->tabs; - - $ilTabs->activateTab("edit_properties"); - - $this->ctrl->saveParameter($this, "rtrn"); - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setHeaderText($this->lng->txt("confirm_sync_questions")); + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->redirectAfterSaving($a_return); + } + } + + protected function copySyncForm() + { + $ilTabs = $this->tabs; + + $ilTabs->activateTab("edit_properties"); + + include_once "Modules/SurveyQuestionPool/classes/class.ilSurveySyncTableGUI.php"; + $tbl = new ilSurveySyncTableGUI($this, "copySyncForm", $this->object); + + $this->tpl->setContent($tbl->getHTML()); + } + + protected function syncCopies() + { + $lng = $this->lng; + $ilAccess = $this->access; + + if (!sizeof($_POST["qid"])) { + ilUtil::sendFailure($lng->txt("select_one")); + return $this->copySyncForm(); + } + + foreach ($this->object->getCopyIds(true) as $survey_id => $questions) { + // check permissions for "parent" survey + $can_write = false; + $ref_ids = ilObject::_getAllReferences($survey_id); + foreach ($ref_ids as $ref_id) { + if ($ilAccess->checkAccess("edit", "", $ref_id)) { + $can_write = true; + break; + } + } + + if ($can_write) { + foreach ($questions as $qid) { + if (in_array($qid, $_POST["qid"])) { + $id = $this->object->getId(); + + $this->object->setId($qid); + $this->object->setOriginalId($id); + $this->object->saveToDb(); + + $this->object->setId($id); + $this->object->setOriginalId(null); + + // see: SurveyQuestion::syncWithOriginal() + // what about material? + } + } + } + } + + ilUtil::sendSuccess($lng->txt("survey_sync_success"), true); + $this->redirectAfterSaving($_REQUEST["rtrn"]); + } + + protected function originalSyncForm() + { + $ilTabs = $this->tabs; + + $ilTabs->activateTab("edit_properties"); + + $this->ctrl->saveParameter($this, "rtrn"); + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setHeaderText($this->lng->txt("confirm_sync_questions")); - $cgui->setFormAction($this->ctrl->getFormAction($this, "confirmRemoveQuestions")); - $cgui->setCancel($this->lng->txt("no"), "cancelSync"); - $cgui->setConfirm($this->lng->txt("yes"), "sync"); + $cgui->setFormAction($this->ctrl->getFormAction($this, "confirmRemoveQuestions")); + $cgui->setCancel($this->lng->txt("no"), "cancelSync"); + $cgui->setConfirm($this->lng->txt("yes"), "sync"); - $this->tpl->setContent($cgui->getHTML()); - } - - protected function sync() - { - $original_id = $this->object->original_id; - if ($original_id) - { - $this->object->syncWithOriginal(); - } + $this->tpl->setContent($cgui->getHTML()); + } + + protected function sync() + { + $original_id = $this->object->original_id; + if ($original_id) { + $this->object->syncWithOriginal(); + } - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->redirectAfterSaving($_REQUEST["rtrn"]); - } + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->redirectAfterSaving($_REQUEST["rtrn"]); + } - protected function cancelSync() - { - ilUtil::sendInfo($this->lng->txt("question_changed_in_survey_only"), true); - $this->redirectAfterSaving($_REQUEST["rtrn"]); - } - - /** - * Redirect to calling survey or to edit form - * - * @param bool $a_return - */ - protected function redirectAfterSaving($a_return = false) - { - // return? - if($a_return) - { - // to calling survey - if($this->parent_url) - { - $addurl = ""; - if (strlen($_GET["new_for_survey"])) - { - $addurl = "&new_id=" . $_GET["q_id"]; - } - ilUtil::redirect(str_replace("&", "&", $this->parent_url) . $addurl); - } - // to pool - else - { - $this->ctrl->setParameterByClass("ilObjSurveyQuestionPoolGUI", "q_id_table_nav", $_SESSION['q_id_table_nav']); - $this->ctrl->redirectByClass("ilObjSurveyQuestionPoolGUI", "questions"); - } - } - // stay in form - else - { - $this->ctrl->setParameterByClass($_GET["cmdClass"], "q_id", $this->object->getId()); - $this->ctrl->setParameterByClass($_GET["cmdClass"], "sel_question_types", $_GET["sel_question_types"]); - $this->ctrl->setParameterByClass($_GET["cmdClass"], "new_for_survey", $_GET["new_for_survey"]); - $this->ctrl->redirectByClass($_GET["cmdClass"], "editQuestion"); - } - } - - protected function cancel() - { - if ($this->parent_url) - { - ilUtil::redirect($this->parent_url); - } - else - { - $this->ctrl->redirectByClass("ilobjsurveyquestionpoolgui", "questions"); - } - } - - protected function validateEditForm(ilPropertyFormGUI $a_form) - { - return true; - } - - abstract protected function addFieldsToEditForm(ilPropertyFormGUI $a_form); - abstract protected function importEditFormValues(ilPropertyFormGUI $a_form); - - abstract public function getPrintView($question_title = 1, $show_questiontext = 1); - - protected function getPrintViewQuestionTitle($question_title = 1) - { - switch ($question_title) - { - case ilObjSurvey::PRINT_HIDE_LABELS: - $title = ilUtil::prepareFormOutput($this->object->getTitle()); - break; + protected function cancelSync() + { + ilUtil::sendInfo($this->lng->txt("question_changed_in_survey_only"), true); + $this->redirectAfterSaving($_REQUEST["rtrn"]); + } + + /** + * Redirect to calling survey or to edit form + * + * @param bool $a_return + */ + protected function redirectAfterSaving($a_return = false) + { + // return? + if ($a_return) { + // to calling survey + if ($this->parent_url) { + $addurl = ""; + if (strlen($_GET["new_for_survey"])) { + $addurl = "&new_id=" . $_GET["q_id"]; + } + ilUtil::redirect(str_replace("&", "&", $this->parent_url) . $addurl); + } + // to pool + else { + $this->ctrl->setParameterByClass("ilObjSurveyQuestionPoolGUI", "q_id_table_nav", $_SESSION['q_id_table_nav']); + $this->ctrl->redirectByClass("ilObjSurveyQuestionPoolGUI", "questions"); + } + } + // stay in form + else { + $this->ctrl->setParameterByClass($_GET["cmdClass"], "q_id", $this->object->getId()); + $this->ctrl->setParameterByClass($_GET["cmdClass"], "sel_question_types", $_GET["sel_question_types"]); + $this->ctrl->setParameterByClass($_GET["cmdClass"], "new_for_survey", $_GET["new_for_survey"]); + $this->ctrl->redirectByClass($_GET["cmdClass"], "editQuestion"); + } + } + + protected function cancel() + { + if ($this->parent_url) { + ilUtil::redirect($this->parent_url); + } else { + $this->ctrl->redirectByClass("ilobjsurveyquestionpoolgui", "questions"); + } + } + + protected function validateEditForm(ilPropertyFormGUI $a_form) + { + return true; + } + + abstract protected function addFieldsToEditForm(ilPropertyFormGUI $a_form); + abstract protected function importEditFormValues(ilPropertyFormGUI $a_form); + + abstract public function getPrintView($question_title = 1, $show_questiontext = 1); + + protected function getPrintViewQuestionTitle($question_title = 1) + { + switch ($question_title) { + case ilObjSurvey::PRINT_HIDE_LABELS: + $title = ilUtil::prepareFormOutput($this->object->getTitle()); + break; - #19448 get rid of showing only the label without title - //case 2: - // $title = ilUtil::prepareFormOutput($this->object->getLabel()); - // break; + #19448 get rid of showing only the label without title + //case 2: + // $title = ilUtil::prepareFormOutput($this->object->getLabel()); + // break; - case ilObjSurvey::PRINT_SHOW_LABELS: - $title = ilUtil::prepareFormOutput($this->object->getTitle()); - if(trim($this->object->getLabel())) - { - $title .= ' ('.ilUtil::prepareFormOutput($this->object->getLabel()).')'; - } - break; - } - return $title; - } - - /** - * Creates a preview of the question - * - * @access private - */ - function preview() - { - $ilTabs = $this->tabs; - - $ilTabs->activateTab("preview"); - - $tpl = new ilTemplate("tpl.il_svy_qpl_preview.html", true, true, "Modules/SurveyQuestionPool"); - - if ($this->object->getObligatory()) - { - $tpl->setCurrentBlock("required"); - $tpl->setVariable("TEXT_REQUIRED", $this->lng->txt("required_field")); - $tpl->parseCurrentBlock(); - } - - $tpl->setVariable("QUESTION_OUTPUT", $this->getWorkingForm()); - - include_once "Services/UIComponent/Panel/classes/class.ilPanelGUI.php"; - $panel = ilPanelGUI::getInstance(); - $panel->setBody($tpl->get()); - - $this->tpl->setContent($panel->getHTML()); - } - - - // - // EXECUTION - // - - abstract public function getWorkingForm($working_data = "", $question_title = 1, $show_questiontext = 1, $error_message = "", $survey_id = null); - - /** - * Creates the HTML output of the question material(s) - */ - protected function getMaterialOutput() - { - if (count($this->object->getMaterial())) - { - $template = new ilTemplate("tpl.il_svy_qpl_material.html", TRUE, TRUE, "Modules/SurveyQuestionPool"); - foreach ($this->object->getMaterial() as $material) - { - $template->setCurrentBlock('material'); - switch ($material->type) - { - case 0: - $href = SurveyQuestion::_getInternalLinkHref($material->internal_link, $_GET['ref_id']); - $template->setVariable('MATERIAL_TYPE', 'internallink'); - $template->setVariable('MATERIAL_HREF', $href); - break; - } - $template->setVariable('MATERIAL_TITLE', (strlen($material->title)) ? ilUtil::prepareFormOutput($material->title) : $this->lng->txt('material')); - $template->setVariable('TEXT_AVAILABLE_MATERIALS', $this->lng->txt('material')); - $template->parseCurrentBlock(); - } - return $template->get(); - } - return ""; - } - - // - // MATERIAL - // - - /** - * Material tab of the survey questions - */ - public function material($checkonly = FALSE) - { - $rbacsystem = $this->rbacsystem; - $ilTabs = $this->tabs; - - $ilTabs->activateTab("material"); + case ilObjSurvey::PRINT_SHOW_LABELS: + $title = ilUtil::prepareFormOutput($this->object->getTitle()); + if (trim($this->object->getLabel())) { + $title .= ' (' . ilUtil::prepareFormOutput($this->object->getLabel()) . ')'; + } + break; + } + return $title; + } + + /** + * Creates a preview of the question + * + * @access private + */ + public function preview() + { + $ilTabs = $this->tabs; + + $ilTabs->activateTab("preview"); + + $tpl = new ilTemplate("tpl.il_svy_qpl_preview.html", true, true, "Modules/SurveyQuestionPool"); + + if ($this->object->getObligatory()) { + $tpl->setCurrentBlock("required"); + $tpl->setVariable("TEXT_REQUIRED", $this->lng->txt("required_field")); + $tpl->parseCurrentBlock(); + } + + $tpl->setVariable("QUESTION_OUTPUT", $this->getWorkingForm()); + + include_once "Services/UIComponent/Panel/classes/class.ilPanelGUI.php"; + $panel = ilPanelGUI::getInstance(); + $panel->setBody($tpl->get()); + + $this->tpl->setContent($panel->getHTML()); + } + + + // + // EXECUTION + // + + abstract public function getWorkingForm($working_data = "", $question_title = 1, $show_questiontext = 1, $error_message = "", $survey_id = null); + + /** + * Creates the HTML output of the question material(s) + */ + protected function getMaterialOutput() + { + if (count($this->object->getMaterial())) { + $template = new ilTemplate("tpl.il_svy_qpl_material.html", true, true, "Modules/SurveyQuestionPool"); + foreach ($this->object->getMaterial() as $material) { + $template->setCurrentBlock('material'); + switch ($material->type) { + case 0: + $href = SurveyQuestion::_getInternalLinkHref($material->internal_link, $_GET['ref_id']); + $template->setVariable('MATERIAL_TYPE', 'internallink'); + $template->setVariable('MATERIAL_HREF', $href); + break; + } + $template->setVariable('MATERIAL_TITLE', (strlen($material->title)) ? ilUtil::prepareFormOutput($material->title) : $this->lng->txt('material')); + $template->setVariable('TEXT_AVAILABLE_MATERIALS', $this->lng->txt('material')); + $template->parseCurrentBlock(); + } + return $template->get(); + } + return ""; + } + + // + // MATERIAL + // + + /** + * Material tab of the survey questions + */ + public function material($checkonly = false) + { + $rbacsystem = $this->rbacsystem; + $ilTabs = $this->tabs; + + $ilTabs->activateTab("material"); - $add_html = ''; - if ($rbacsystem->checkAccess('write', $_GET['ref_id'])) - { - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - $form->setTitle($this->lng->txt('add_material')); - $form->setMultipart(FALSE); - $form->setTableWidth("100%"); - $form->setId("material"); + $add_html = ''; + if ($rbacsystem->checkAccess('write', $_GET['ref_id'])) { + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this)); + $form->setTitle($this->lng->txt('add_material')); + $form->setMultipart(false); + $form->setTableWidth("100%"); + $form->setId("material"); - // material - $material = new ilRadioGroupInputGUI($this->lng->txt("material"), "internalLinkType"); - $material->setRequired(true); - $material->addOption(new ilRadioOption($this->lng->txt('obj_lm'), "lm")); - $material->addOption(new ilRadioOption($this->lng->txt('obj_st'), "st")); - $material->addOption(new ilRadioOption($this->lng->txt('obj_pg'), "pg")); - $material->addOption(new ilRadioOption($this->lng->txt('glossary_term'), "glo")); - $form->addItem($material); + // material + $material = new ilRadioGroupInputGUI($this->lng->txt("material"), "internalLinkType"); + $material->setRequired(true); + $material->addOption(new ilRadioOption($this->lng->txt('obj_lm'), "lm")); + $material->addOption(new ilRadioOption($this->lng->txt('obj_st'), "st")); + $material->addOption(new ilRadioOption($this->lng->txt('obj_pg'), "pg")); + $material->addOption(new ilRadioOption($this->lng->txt('glossary_term'), "glo")); + $form->addItem($material); - $form->addCommandButton("addMaterial", $this->lng->txt("add")); + $form->addCommandButton("addMaterial", $this->lng->txt("add")); - $errors = false; + $errors = false; - if ($checkonly) - { - $form->setValuesByPost(); - $errors = !$form->checkInput(); - if ($errors) $checkonly = false; - } - $add_html = $form->getHTML(); - } + if ($checkonly) { + $form->setValuesByPost(); + $errors = !$form->checkInput(); + if ($errors) { + $checkonly = false; + } + } + $add_html = $form->getHTML(); + } - $mat_html = ""; - if (count($this->object->getMaterial())) - { - include_once "./Modules/SurveyQuestionPool/classes/tables/class.ilSurveyMaterialsTableGUI.php"; - $table_gui = new ilSurveyMaterialsTableGUI($this, 'material', (($rbacsystem->checkAccess('write', $_GET['ref_id']) ? true : false))); - $data = array(); - foreach ($this->object->getMaterial() as $material) - { - switch ($material->type) - { - case 0: - $href = SurveyQuestion::_getInternalLinkHref($material->internal_link, $_GET['ref_id']); - $type = $this->lng->txt('internal_link'); - break; - } - $title = (strlen($material->title)) ? ilUtil::prepareFormOutput($material->title) : $this->lng->txt('material'); - array_push($data, array('href' => $href, 'title' => $title, 'type' => $type)); - } - $table_gui->setData($data); - $mat_html = $table_gui->getHTML(); - } + $mat_html = ""; + if (count($this->object->getMaterial())) { + include_once "./Modules/SurveyQuestionPool/classes/tables/class.ilSurveyMaterialsTableGUI.php"; + $table_gui = new ilSurveyMaterialsTableGUI($this, 'material', (($rbacsystem->checkAccess('write', $_GET['ref_id']) ? true : false))); + $data = array(); + foreach ($this->object->getMaterial() as $material) { + switch ($material->type) { + case 0: + $href = SurveyQuestion::_getInternalLinkHref($material->internal_link, $_GET['ref_id']); + $type = $this->lng->txt('internal_link'); + break; + } + $title = (strlen($material->title)) ? ilUtil::prepareFormOutput($material->title) : $this->lng->txt('material'); + array_push($data, array('href' => $href, 'title' => $title, 'type' => $type)); + } + $table_gui->setData($data); + $mat_html = $table_gui->getHTML(); + } - if (!$checkonly) $this->tpl->setVariable("ADM_CONTENT", $add_html . $mat_html); - return $errors; - } - - public function deleteMaterial() - { - if (is_array($_POST['idx'])) - { - $this->object->deleteMaterials($_POST['idx']); - ilUtil::sendSuccess($this->lng->txt('materials_deleted'), true); - } - else - { - ilUtil::sendFailure($this->lng->txt('no_checkbox'), true); - } - $this->ctrl->redirect($this, 'material'); - } + if (!$checkonly) { + $this->tpl->setVariable("ADM_CONTENT", $add_html . $mat_html); + } + return $errors; + } + + public function deleteMaterial() + { + if (is_array($_POST['idx'])) { + $this->object->deleteMaterials($_POST['idx']); + ilUtil::sendSuccess($this->lng->txt('materials_deleted'), true); + } else { + ilUtil::sendFailure($this->lng->txt('no_checkbox'), true); + } + $this->ctrl->redirect($this, 'material'); + } - /** - * Add materials to a question - */ - public function addMaterial() - { - $tree = $this->tree; - $ilTabs = $this->tabs; - $ilToolbar = $this->toolbar; - - $ilTabs->activateTab("material"); - - $ilToolbar->addButton($this->lng->txt("cancel"), - $this->ctrl->getLinkTarget($this, "material")); - - if (strlen($_SESSION["link_new_type"]) || !$this->material(true)) - { - include_once("./Modules/SurveyQuestionPool/classes/class.ilMaterialExplorer.php"); - switch ($_POST["internalLinkType"]) - { - case "lm": - $_SESSION["link_new_type"] = "lm"; - $_SESSION["search_link_type"] = "lm"; - break; - case "glo": - $_SESSION["link_new_type"] = "glo"; - $_SESSION["search_link_type"] = "glo"; - break; - case "st": - $_SESSION["link_new_type"] = "lm"; - $_SESSION["search_link_type"] = "st"; - break; - case "pg": - $_SESSION["link_new_type"] = "lm"; - $_SESSION["search_link_type"] = "pg"; - break; - } + /** + * Add materials to a question + */ + public function addMaterial() + { + $tree = $this->tree; + $ilTabs = $this->tabs; + $ilToolbar = $this->toolbar; + + $ilTabs->activateTab("material"); + + $ilToolbar->addButton( + $this->lng->txt("cancel"), + $this->ctrl->getLinkTarget($this, "material") + ); + + if (strlen($_SESSION["link_new_type"]) || !$this->material(true)) { + include_once("./Modules/SurveyQuestionPool/classes/class.ilMaterialExplorer.php"); + switch ($_POST["internalLinkType"]) { + case "lm": + $_SESSION["link_new_type"] = "lm"; + $_SESSION["search_link_type"] = "lm"; + break; + case "glo": + $_SESSION["link_new_type"] = "glo"; + $_SESSION["search_link_type"] = "glo"; + break; + case "st": + $_SESSION["link_new_type"] = "lm"; + $_SESSION["search_link_type"] = "st"; + break; + case "pg": + $_SESSION["link_new_type"] = "lm"; + $_SESSION["search_link_type"] = "pg"; + break; + } - $exp = new ilMaterialExplorer($this, 'addMaterial', $_SESSION["link_new_type"]); - $exp->setPathOpen((int)$_GET["ref_id"]); - if (!$exp->handleCommand()) - { - include_once "Services/UIComponent/Panel/classes/class.ilPanelGUI.php"; - $panel = ilPanelGUI::getInstance(); - $panel->setHeading($this->lng->txt("select_object_to_link")); - $panel->setBody($exp->getHTML()); + $exp = new ilMaterialExplorer($this, 'addMaterial', $_SESSION["link_new_type"]); + $exp->setPathOpen((int) $_GET["ref_id"]); + if (!$exp->handleCommand()) { + include_once "Services/UIComponent/Panel/classes/class.ilPanelGUI.php"; + $panel = ilPanelGUI::getInstance(); + $panel->setHeading($this->lng->txt("select_object_to_link")); + $panel->setBody($exp->getHTML()); - $this->tpl->setContent($panel->getHTML()); - } - } - } - - function removeMaterial() - { - $this->object->material = array(); - $this->object->saveToDb(); - $this->editQuestion(); - } - - function cancelExplorer() - { - unset($_SESSION["link_new_type"]); - ilUtil::sendInfo($this->lng->txt("msg_cancel"), true); - $this->ctrl->redirect($this, 'material'); - } - - function addPG() - { - $this->object->addInternalLink("il__pg_" . $_GET["pg"]); - unset($_SESSION["link_new_type"]); - unset($_SESSION["search_link_type"]); - ilUtil::sendSuccess($this->lng->txt("material_added_successfully"), true); - $this->ctrl->redirect($this, "material"); - } - - function addST() - { - $this->object->addInternalLink("il__st_" . $_GET["st"]); - unset($_SESSION["link_new_type"]); - unset($_SESSION["search_link_type"]); - ilUtil::sendSuccess($this->lng->txt("material_added_successfully"), true); - $this->ctrl->redirect($this, "material"); - } + $this->tpl->setContent($panel->getHTML()); + } + } + } + + public function removeMaterial() + { + $this->object->material = array(); + $this->object->saveToDb(); + $this->editQuestion(); + } + + public function cancelExplorer() + { + unset($_SESSION["link_new_type"]); + ilUtil::sendInfo($this->lng->txt("msg_cancel"), true); + $this->ctrl->redirect($this, 'material'); + } + + public function addPG() + { + $this->object->addInternalLink("il__pg_" . $_GET["pg"]); + unset($_SESSION["link_new_type"]); + unset($_SESSION["search_link_type"]); + ilUtil::sendSuccess($this->lng->txt("material_added_successfully"), true); + $this->ctrl->redirect($this, "material"); + } + + public function addST() + { + $this->object->addInternalLink("il__st_" . $_GET["st"]); + unset($_SESSION["link_new_type"]); + unset($_SESSION["search_link_type"]); + ilUtil::sendSuccess($this->lng->txt("material_added_successfully"), true); + $this->ctrl->redirect($this, "material"); + } - function addGIT() - { - $this->object->addInternalLink("il__git_" . $_GET["git"]); - unset($_SESSION["link_new_type"]); - unset($_SESSION["search_link_type"]); - ilUtil::sendSuccess($this->lng->txt("material_added_successfully"), true); - $this->ctrl->redirect($this, "material"); - } - - function linkChilds() - { - $ilTabs = $this->tabs; - - $selectable_items = array(); - - $source_id = $_GET["source_id"]; - - switch ($_SESSION["search_link_type"]) - { - case "pg": - include_once "./Modules/LearningModule/classes/class.ilLMPageObject.php"; - include_once("./Modules/LearningModule/classes/class.ilObjContentObjectGUI.php"); - $cont_obj_gui = new ilObjContentObjectGUI("", $source_id, true); - $cont_obj = $cont_obj_gui->object; - $pages = ilLMPageObject::getPageList($cont_obj->getId()); - foreach($pages as $page) - { - if($page["type"] == $_SESSION["search_link_type"]) - { - $selectable_items[] = array( - "item_type" => $page["type"] - ,"item_id" => $page["obj_id"] - ,"title" => $page["title"] - ); - } - } - break; - - case "st": - include_once("./Modules/LearningModule/classes/class.ilObjContentObjectGUI.php"); - $cont_obj_gui = new ilObjContentObjectGUI("", $source_id, true); - $cont_obj = $cont_obj_gui->object; - // get all chapters - $ctree =& $cont_obj->getLMTree(); - $nodes = $ctree->getSubtree($ctree->getNodeData($ctree->getRootId())); - foreach($nodes as $node) - { - if($node["type"] == $_SESSION["search_link_type"]) - { - $selectable_items[] = array( - "item_type" => $node["type"] - ,"item_id" => $node["obj_id"] - ,"title" => $node["title"] - ); - } - } - break; - - case "glo": - include_once "./Modules/Glossary/classes/class.ilObjGlossary.php"; - $glossary = new ilObjGlossary($source_id, true); - // get all glossary items - $terms = $glossary->getTermList(); - foreach($terms as $term) - { - $selectable_items[] = array( - "item_type" => "GIT" - ,"item_id" => $term["id"] - ,"title" => $term["term"] - ); - } - break; - - case "lm": - $this->object->addInternalLink("il__lm_" . $source_id); - break; - } - - if(sizeof($selectable_items)) - { - $ilTabs->activateTab("material"); - $this->ctrl->setParameter($this, "q_id", $this->object->getId()); - $this->ctrl->setParameter($this, "source_id", $source_id); - - include_once "Modules/SurveyQuestionPool/classes/tables/class.SurveyMaterialsSourceTableGUI.php"; - $tbl = new SurveyMaterialsSourceTableGUI($this, "linkChilds", "addMaterial"); - $tbl->setData($selectable_items); - $this->tpl->setContent($tbl->getHTML()); - } - else - { - if($_SESSION["search_link_type"] == "lm") - { - ilUtil::sendSuccess($this->lng->txt("material_added_successfully"), true); - - unset($_SESSION["link_new_type"]); - unset($_SESSION["search_link_type"]); - $this->ctrl->redirect($this, "material"); - } - else - { - ilUtil::sendFailure($this->lng->txt("material_added_empty"), true); - $this->ctrl->redirect($this, "addMaterial"); - } - } - } - - - // - // PHRASES (see SurveyMatrixQuestionGUI) - // - - protected function initPhrasesForm() - { - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this, "addSelectedPhrase")); - $form->setTitle($this->lng->txt("add_phrase")); - // $form->setDescription($this->lng->txt("add_phrase_introduction")); - - $group = new ilRadioGroupInputGUI($this->lng->txt("phrase"), "phrases"); - $group->setRequired(true); - $form->addItem($group); - - include_once "./Modules/SurveyQuestionPool/classes/class.ilSurveyPhrases.php"; - foreach (ilSurveyPhrases::_getAvailablePhrases() as $phrase_id => $phrase_array) - { - $categories = ilSurveyPhrases::_getCategoriesForPhrase($phrase_id); - - $opt = new ilRadioOption($phrase_array["title"], $phrase_id); - $opt->setInfo(join($categories, ",")); - $group->addOption($opt); - - if($phrase_array["org_title"] == "dp_standard_numbers") - { - $min = new ilNumberInputGUI($this->lng->txt("lower_limit"), "lower_limit"); - $min->setRequired(true); - $min->setSize(5); - $opt->addSubItem($min); + public function addGIT() + { + $this->object->addInternalLink("il__git_" . $_GET["git"]); + unset($_SESSION["link_new_type"]); + unset($_SESSION["search_link_type"]); + ilUtil::sendSuccess($this->lng->txt("material_added_successfully"), true); + $this->ctrl->redirect($this, "material"); + } + + public function linkChilds() + { + $ilTabs = $this->tabs; + + $selectable_items = array(); + + $source_id = $_GET["source_id"]; + + switch ($_SESSION["search_link_type"]) { + case "pg": + include_once "./Modules/LearningModule/classes/class.ilLMPageObject.php"; + include_once("./Modules/LearningModule/classes/class.ilObjContentObjectGUI.php"); + $cont_obj_gui = new ilObjContentObjectGUI("", $source_id, true); + $cont_obj = $cont_obj_gui->object; + $pages = ilLMPageObject::getPageList($cont_obj->getId()); + foreach ($pages as $page) { + if ($page["type"] == $_SESSION["search_link_type"]) { + $selectable_items[] = array( + "item_type" => $page["type"] + ,"item_id" => $page["obj_id"] + ,"title" => $page["title"] + ); + } + } + break; + + case "st": + include_once("./Modules/LearningModule/classes/class.ilObjContentObjectGUI.php"); + $cont_obj_gui = new ilObjContentObjectGUI("", $source_id, true); + $cont_obj = $cont_obj_gui->object; + // get all chapters + $ctree =&$cont_obj->getLMTree(); + $nodes = $ctree->getSubtree($ctree->getNodeData($ctree->getRootId())); + foreach ($nodes as $node) { + if ($node["type"] == $_SESSION["search_link_type"]) { + $selectable_items[] = array( + "item_type" => $node["type"] + ,"item_id" => $node["obj_id"] + ,"title" => $node["title"] + ); + } + } + break; + + case "glo": + include_once "./Modules/Glossary/classes/class.ilObjGlossary.php"; + $glossary = new ilObjGlossary($source_id, true); + // get all glossary items + $terms = $glossary->getTermList(); + foreach ($terms as $term) { + $selectable_items[] = array( + "item_type" => "GIT" + ,"item_id" => $term["id"] + ,"title" => $term["term"] + ); + } + break; + + case "lm": + $this->object->addInternalLink("il__lm_" . $source_id); + break; + } + + if (sizeof($selectable_items)) { + $ilTabs->activateTab("material"); + $this->ctrl->setParameter($this, "q_id", $this->object->getId()); + $this->ctrl->setParameter($this, "source_id", $source_id); + + include_once "Modules/SurveyQuestionPool/classes/tables/class.SurveyMaterialsSourceTableGUI.php"; + $tbl = new SurveyMaterialsSourceTableGUI($this, "linkChilds", "addMaterial"); + $tbl->setData($selectable_items); + $this->tpl->setContent($tbl->getHTML()); + } else { + if ($_SESSION["search_link_type"] == "lm") { + ilUtil::sendSuccess($this->lng->txt("material_added_successfully"), true); + + unset($_SESSION["link_new_type"]); + unset($_SESSION["search_link_type"]); + $this->ctrl->redirect($this, "material"); + } else { + ilUtil::sendFailure($this->lng->txt("material_added_empty"), true); + $this->ctrl->redirect($this, "addMaterial"); + } + } + } + + + // + // PHRASES (see SurveyMatrixQuestionGUI) + // + + protected function initPhrasesForm() + { + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this, "addSelectedPhrase")); + $form->setTitle($this->lng->txt("add_phrase")); + // $form->setDescription($this->lng->txt("add_phrase_introduction")); + + $group = new ilRadioGroupInputGUI($this->lng->txt("phrase"), "phrases"); + $group->setRequired(true); + $form->addItem($group); + + include_once "./Modules/SurveyQuestionPool/classes/class.ilSurveyPhrases.php"; + foreach (ilSurveyPhrases::_getAvailablePhrases() as $phrase_id => $phrase_array) { + $categories = ilSurveyPhrases::_getCategoriesForPhrase($phrase_id); + + $opt = new ilRadioOption($phrase_array["title"], $phrase_id); + $opt->setInfo(join($categories, ",")); + $group->addOption($opt); + + if ($phrase_array["org_title"] == "dp_standard_numbers") { + $min = new ilNumberInputGUI($this->lng->txt("lower_limit"), "lower_limit"); + $min->setRequired(true); + $min->setSize(5); + $opt->addSubItem($min); - $max = new ilNumberInputGUI($this->lng->txt("upper_limit"), "upper_limit"); - $max->setRequired(true); - $max->setSize(5); - $opt->addSubItem($max); - } - } - - $form->addCommandButton("addSelectedPhrase", $this->lng->txt("add_phrase")); - $form->addCommandButton("editQuestion", $this->lng->txt("cancel")); - - return $form; - } - - /** - * Creates an output for the addition of phrases - */ - protected function addPhrase(ilPropertyFormGUI $a_form = null) - { - $ilTabs = $this->tabs; - - $ilTabs->activateTab("edit_properties"); - - if(!$a_form) - { - $result = $this->saveForm(); - if($result) - { - $this->object->saveToDb(); - } - - $a_form = $this->initPhrasesForm(); - } - - $this->tpl->setContent($a_form->getHTML()); - } + $max = new ilNumberInputGUI($this->lng->txt("upper_limit"), "upper_limit"); + $max->setRequired(true); + $max->setSize(5); + $opt->addSubItem($max); + } + } + + $form->addCommandButton("addSelectedPhrase", $this->lng->txt("add_phrase")); + $form->addCommandButton("editQuestion", $this->lng->txt("cancel")); + + return $form; + } + + /** + * Creates an output for the addition of phrases + */ + protected function addPhrase(ilPropertyFormGUI $a_form = null) + { + $ilTabs = $this->tabs; + + $ilTabs->activateTab("edit_properties"); + + if (!$a_form) { + $result = $this->saveForm(); + if ($result) { + $this->object->saveToDb(); + } + + $a_form = $this->initPhrasesForm(); + } + + $this->tpl->setContent($a_form->getHTML()); + } - protected function addSelectedPhrase() - { - $form = $this->initPhrasesForm(); - if($form->checkInput()) - { - $phrase_id = $form->getInput("phrases"); - - $valid = true; - if (strcmp($this->object->getPhrase($phrase_id), "dp_standard_numbers") != 0) - { - $this->object->addPhrase($phrase_id); - } - else - { - $min = $form->getInput("lower_limit"); - $max = $form->getInput("upper_limit"); + protected function addSelectedPhrase() + { + $form = $this->initPhrasesForm(); + if ($form->checkInput()) { + $phrase_id = $form->getInput("phrases"); + + $valid = true; + if (strcmp($this->object->getPhrase($phrase_id), "dp_standard_numbers") != 0) { + $this->object->addPhrase($phrase_id); + } else { + $min = $form->getInput("lower_limit"); + $max = $form->getInput("upper_limit"); - if($max <= $min) - { - $max_field = $form->getItemByPostVar("upper_limit"); - $max_field->setAlert($this->lng->txt("upper_limit_must_be_greater")); - $valid = false; - } - else - { - $this->object->addStandardNumbers($min, $max); - } - } - - if($valid) - { - $this->object->saveToDb(); - - ilUtil::sendSuccess($this->lng->txt('phrase_added'), true); - $this->ctrl->redirect($this, 'editQuestion'); - } - } - - $form->setValuesByPost(); - $this->addPhrase($form); - } - - /** - * Creates an output to save the current answers as a phrase - * - * @access public - */ - function savePhrase($a_reload = false) - { - $ilTabs = $this->tabs; - $ilToolbar = $this->toolbar; - - $ilTabs->activateTab("edit_properties"); - - if (!$a_reload) - { - $result = $this->saveForm(); - if ($result) - { - $this->object->saveToDb(); - } - } - - include_once("./Services/Form/classes/class.ilTextInputGUI.php"); - $txt = new ilTextInputGUI($this->lng->txt("enter_phrase_title"), "phrase_title"); - $ilToolbar->addInputItem($txt, true); - $ilToolbar->addFormButton($this->lng->txt("confirm"), "confirmSavePhrase"); - $ilToolbar->setFormAction($this->ctrl->getFormAction($this)); - - include_once "./Modules/SurveyQuestionPool/classes/tables/class.ilSurveySavePhraseTableGUI.php"; - $table_gui = new ilSurveySavePhraseTableGUI($this, 'editQuestion'); - $table_gui->setDescription($this->lng->txt("save_phrase_introduction")); - - // matrix? - if(method_exists($this->object, "getCategories")) - { - $categories = $this->object->getCategories(); - } - else - { - $categories = $this->object->getColumns(); - } + if ($max <= $min) { + $max_field = $form->getItemByPostVar("upper_limit"); + $max_field->setAlert($this->lng->txt("upper_limit_must_be_greater")); + $valid = false; + } else { + $this->object->addStandardNumbers($min, $max); + } + } + + if ($valid) { + $this->object->saveToDb(); + + ilUtil::sendSuccess($this->lng->txt('phrase_added'), true); + $this->ctrl->redirect($this, 'editQuestion'); + } + } + + $form->setValuesByPost(); + $this->addPhrase($form); + } + + /** + * Creates an output to save the current answers as a phrase + * + * @access public + */ + public function savePhrase($a_reload = false) + { + $ilTabs = $this->tabs; + $ilToolbar = $this->toolbar; + + $ilTabs->activateTab("edit_properties"); + + if (!$a_reload) { + $result = $this->saveForm(); + if ($result) { + $this->object->saveToDb(); + } + } + + include_once("./Services/Form/classes/class.ilTextInputGUI.php"); + $txt = new ilTextInputGUI($this->lng->txt("enter_phrase_title"), "phrase_title"); + $ilToolbar->addInputItem($txt, true); + $ilToolbar->addFormButton($this->lng->txt("confirm"), "confirmSavePhrase"); + $ilToolbar->setFormAction($this->ctrl->getFormAction($this)); + + include_once "./Modules/SurveyQuestionPool/classes/tables/class.ilSurveySavePhraseTableGUI.php"; + $table_gui = new ilSurveySavePhraseTableGUI($this, 'editQuestion'); + $table_gui->setDescription($this->lng->txt("save_phrase_introduction")); + + // matrix? + if (method_exists($this->object, "getCategories")) { + $categories = $this->object->getCategories(); + } else { + $categories = $this->object->getColumns(); + } - $data = array(); - for ($i = 0; $i < $categories->getCategoryCount(); $i++) - { - $cat = $categories->getCategory($i); - - $data[] = array( - "answer" => $cat->title, - "other" => $cat->other, - "scale" => $cat->scale, - "neutral" => $cat->neutral - ); - } - $table_gui->setData($data); - $_SESSION['save_phrase_data'] = $data; // :TODO: see savePhrase() - - $this->tpl->setContent($table_gui->getHTML()); - } + $data = array(); + for ($i = 0; $i < $categories->getCategoryCount(); $i++) { + $cat = $categories->getCategory($i); + + $data[] = array( + "answer" => $cat->title, + "other" => $cat->other, + "scale" => $cat->scale, + "neutral" => $cat->neutral + ); + } + $table_gui->setData($data); + $_SESSION['save_phrase_data'] = $data; // :TODO: see savePhrase() + + $this->tpl->setContent($table_gui->getHTML()); + } - /** - * Save a new phrase to the database - * - * @access public - */ - function confirmSavePhrase() - { - $title = $_POST["phrase_title"]; - - $valid = true; - if (!trim($title)) - { - ilUtil::sendFailure($this->lng->txt("qpl_savephrase_empty")); - $valid = false; - } - else if ($this->object->phraseExists($title)) - { - ilUtil::sendFailure($this->lng->txt("qpl_savephrase_exists")); - $valid = false; - } - - if($valid) - { - $this->object->savePhrase($title); + /** + * Save a new phrase to the database + * + * @access public + */ + public function confirmSavePhrase() + { + $title = $_POST["phrase_title"]; + + $valid = true; + if (!trim($title)) { + ilUtil::sendFailure($this->lng->txt("qpl_savephrase_empty")); + $valid = false; + } elseif ($this->object->phraseExists($title)) { + ilUtil::sendFailure($this->lng->txt("qpl_savephrase_exists")); + $valid = false; + } + + if ($valid) { + $this->object->savePhrase($title); - ilUtil::sendSuccess($this->lng->txt("phrase_saved"), true); - $this->ctrl->redirect($this, "editQuestion"); - } - - $this->savePhrase(true); - } - - protected function renderStatisticsDetailsTable(array $a_head, array $a_rows, array $a_foot = null) - { - $html = array(); - $html[] = '
'; - $html[] = ''; + ilUtil::sendSuccess($this->lng->txt("phrase_saved"), true); + $this->ctrl->redirect($this, "editQuestion"); + } + + $this->savePhrase(true); + } + + protected function renderStatisticsDetailsTable(array $a_head, array $a_rows, array $a_foot = null) + { + $html = array(); + $html[] = '
'; + $html[] = '
'; - $html[] = ""; - $html[] = ""; - foreach($a_head as $col) - { - $col = trim($col); - $html[] = ""; - } - $html[] = ""; - $html[] = ""; + $html[] = ""; + $html[] = ""; + foreach ($a_head as $col) { + $col = trim($col); + $html[] = ""; + } + $html[] = ""; + $html[] = ""; - $html[] = ""; - foreach($a_rows as $row) - { - $html[] = ""; - foreach($row as $col) - { - $col = trim($col); - $html[] = ""; - } - $html[] = ""; - } - $html[] = ""; - - if($a_foot) - { - $html[] = ""; - $html[] = ""; - foreach($a_foot as $col) - { - $col = trim($col); - $html[] = ""; - } - $html[] = ""; - $html[] = ""; - } - - $html[] = "
"; - $html[] = ($col != "") ? $col : " "; - $html[] = "
"; + $html[] = ($col != "") ? $col : " "; + $html[] = "
"; - $html[] = ($col != "") ? $col : " "; - $html[] = "
"; - $html[] = ($col != "") ? $col : " "; - $html[] = "
"; - $html[] = "
"; - return implode("\n", $html); - } + $html[] = ""; + foreach ($a_rows as $row) { + $html[] = ""; + foreach ($row as $col) { + $col = trim($col); + $html[] = ""; + $html[] = ($col != "") ? $col : " "; + $html[] = ""; + } + $html[] = ""; + } + $html[] = ""; + + if ($a_foot) { + $html[] = ""; + $html[] = ""; + foreach ($a_foot as $col) { + $col = trim($col); + $html[] = ""; + $html[] = ($col != "") ? $col : " "; + $html[] = ""; + } + $html[] = ""; + $html[] = ""; + } + + $html[] = ""; + $html[] = "
"; + return implode("\n", $html); + } } - -?> \ No newline at end of file diff --git a/Modules/SurveyQuestionPool/classes/class.SurveySingleChoiceQuestion.php b/Modules/SurveyQuestionPool/classes/class.SurveySingleChoiceQuestion.php index 0168d31f026945e24b7962d34c956370c835b445..25af2d49ebc44a1a7135efa093a7982d0f0026a6 100755 --- a/Modules/SurveyQuestionPool/classes/class.SurveySingleChoiceQuestion.php +++ b/Modules/SurveyQuestionPool/classes/class.SurveySingleChoiceQuestion.php @@ -34,653 +34,630 @@ include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; * @extends SurveyQuestion * @ingroup ModulesSurveyQuestionPool */ -class SurveySingleChoiceQuestion extends SurveyQuestion +class SurveySingleChoiceQuestion extends SurveyQuestion { - /** - * Categories contained in this question - * - * @var array - */ - var $categories; - - /** - * SurveySingleChoiceQuestion constructor - * - * The constructor takes possible arguments an creates an instance of the SurveySingleChoiceQuestion 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 = 1) - { - global $DIC; - - $this->db = $DIC->database(); - $this->user = $DIC->user(); - $this->lng = $DIC->language(); - parent::__construct($title, $description, $author, $questiontext, $owner); - - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyCategories.php"; - $this->orientation = $orientation; - $this->categories = new SurveyCategories(); - } - - /** - * Gets the available categories for a given phrase - * - * @param integer $phrase_id The database id of the given phrase - * @result array All available categories - * @access public - */ - function &getCategoriesForPhrase($phrase_id) - { - $ilDB = $this->db; - $categories = array(); - $result = $ilDB->queryF("SELECT svy_category.* FROM svy_category, svy_phrase_cat WHERE svy_phrase_cat.category_fi = svy_category.category_id AND svy_phrase_cat.phrase_fi = %s ORDER BY svy_phrase_cat.sequence", - array('integer'), - array($phrase_id) - ); - while ($row = $ilDB->fetchAssoc($result)) - { - if (($row["defaultvalue"] == 1) and ($row["owner_fi"] == 0)) - { - $categories[$row["category_id"]] = $this->lng->txt($row["title"]); - } - else - { - $categories[$row["category_id"]] = $row["title"]; - } - } - return $categories; - } - - /** - * Adds a phrase to the question - * - * @param integer $phrase_id The database id of the given phrase - * @access public - */ - function addPhrase($phrase_id) - { - $ilUser = $this->user; - $ilDB = $this->db; - - $result = $ilDB->queryF("SELECT svy_category.* FROM svy_category, svy_phrase_cat WHERE svy_phrase_cat.category_fi = svy_category.category_id AND svy_phrase_cat.phrase_fi = %s AND (svy_category.owner_fi = 0 OR svy_category.owner_fi = %s) ORDER BY svy_phrase_cat.sequence", - array('integer', 'integer'), - array($phrase_id, $ilUser->getId()) - ); - while ($row = $ilDB->fetchAssoc($result)) - { - $neutral = $row["neutral"]; - if (($row["defaultvalue"] == 1) and ($row["owner_fi"] == 0)) - { - $this->categories->addCategory($this->lng->txt($row["title"]), 0, $neutral); - } - else - { - $this->categories->addCategory($row["title"], 0, $neutral); - } - } - } - - /** - * 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 SurveySingleChoiceQuestion object from the database - * - * @param integer $id The database id of the single 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->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 SurveySingleChoiceQuestion object to a database - * - * @access public - */ - function saveToDb($original_id = "") - { - $ilDB = $this->db; - - $affectedRows = parent::saveToDb($original_id); - if ($affectedRows == 1) - { - $this->log->debug("Before save Category-> DELETE from svy_qst_sc WHERE question_fi = ".$this->getId()." AND INSERT again the same id and orientation in svy_qst_sc"); - $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) VALUES (%s, %s)", - array('integer', 'text'), - array( - $this->getId(), - $this->getOrientation() - ) - ); - - $this->saveMaterial(); - $this->saveCategoriesToDb(); - } - } - - function saveCategoriesToDb() - { - $ilDB = $this->db; - - $this->log->debug("DELETE from svy_variable before the INSERT into svy_variable. if scale > 0 we get scale value else we get null"); - - $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()) - ); - - $debug_scale = ($cat->scale > 0) ? $cat->scale : null; - $this->log->debug("INSERT INTO svy_variable category_fi= ".$category_id." question_fi= ".$this->getId()." value1= ".($i + 1)." other= ".$cat->other." sequence= ".$i." scale =".$debug_scale); - } - $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_single", $attrs); - $this->addMaterialTag($a_xml_writer, $this->categories->getCategory($i)->title); - $a_xml_writer->xmlEndTag("response_single"); - } - - $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->xmlEndTag("metadata"); - - $a_xml_writer->xmlEndTag("question"); - } - - /** - * 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; - } - } - } - - /** - * Adds standard numbers as categories - * - * @param integer $lower_limit The lower limit - * @param integer $upper_limit The upper limit - * @access public - */ - function addStandardNumbers($lower_limit, $upper_limit) - { - for ($i = $lower_limit; $i <= $upper_limit; $i++) - { - $this->categories->addCategory($i); - } - } - - /** - * Saves a set of categories to a default phrase - * - * @param array $phrases The database ids of the seleted phrases - * @param string $title The title of the default phrase - * @access public - */ - function savePhrase($title) - { - $ilUser = $this->user; - $ilDB = $this->db; - - $next_id = $ilDB->nextId('svy_phrase'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_phrase (phrase_id, title, defaultvalue, owner_fi, tstamp) VALUES (%s, %s, %s, %s, %s)", - array('integer','text','text','integer','integer'), - array($next_id, $title, 1, $ilUser->getId(), time()) - ); - $phrase_id = $next_id; - - $counter = 1; - foreach ($_SESSION['save_phrase_data'] as $data) - { - $next_id = $ilDB->nextId('svy_category'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_category (category_id, title, defaultvalue, owner_fi, tstamp, neutral) VALUES (%s, %s, %s, %s, %s, %s)", - array('integer','text','text','integer','integer','text'), - array($next_id, $data['answer'], 1, $ilUser->getId(), time(), $data['neutral']) - ); - $category_id = $next_id; - $next_id = $ilDB->nextId('svy_phrase_cat'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_phrase_cat (phrase_category_id, phrase_fi, category_fi, sequence, other, scale) VALUES (%s, %s, %s, %s, %s, %s)", - array('integer', 'integer', 'integer','integer', 'integer', 'integer'), - array($next_id, $phrase_id, $category_id, $counter, ($data['other']) ? 1 : 0, $data['scale']) - ); - $counter++; - } - } - - /** - * Returns the question type of the question - * - * @return integer The question type of the question - * @access public - */ - function getQuestionType() - { - return "SurveySingleChoiceQuestion"; - } - - /** - * 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_sc"; - } - - /** - * 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 (strlen($entered_value)) - { - array_push($data, array("value" => $entered_value, "textanswer" => $post_data[$this->getId() . '_' . $entered_value . '_other'])); - } - for ($i = 0; $i < $this->categories->getCategoryCount(); $i++) - { - $cat = $this->categories->getCategory($i); - if ($cat->other) - { - if ($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"]; - - $this->log->debug("Entered value = ".$entered_value); - - if ((!$this->getObligatory($survey_id)) && (strlen($entered_value) == 0)) return ""; - - if (strlen($entered_value) == 0) return $this->lng->txt("question_not_checked"); - - for ($i = 0; $i < $this->categories->getCategoryCount(); $i++) - { - $cat = $this->categories->getCategory($i); - if ($cat->other) - { - if ($i == $entered_value) - { - if (array_key_exists($this->getId() . "_" . $entered_value . "_other", $post_data) && !strlen($post_data[$this->getId() . "_" . $entered_value . "_other"])) - { - return $this->lng->txt("question_mr_no_other_answer"); - } - } - else - { - if (strlen($post_data[$this->getId() . "_" . $i . "_other"])) - { - return $this->lng->txt("question_sr_no_other_answer_checked"); - } - } - } - } - - return ""; - } - - function saveUserInput($post_data, $active_id, $a_return = false) - { - $ilDB = $this->db; - - $entered_value = $post_data[$this->getId() . "_value"]; - - if($a_return) - { - return array(array("value"=>$entered_value, - "textanswer"=>$post_data[$this->getId() . "_" . $entered_value . "_other"])); - } - 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", ($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); - - $debug_value = (strlen($entered_value)) ? $entered_value : "NULL"; - $debug_answer = ($post_data[$this->getId() . "_" . $entered_value . "_other"]) ? $post_data[$this->getId() . "_" . $entered_value . "_other"] : "NULL"; - $this->log->debug("INSERT svy_answer answer_id=".$next_id." question_fi=".$this->getId()." active_fi=".$active_id." value=".$debug_value. " textanswer=".$debug_answer); - } - - /** - * 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; - } - + /** + * Categories contained in this question + * + * @var array + */ + public $categories; + + /** + * SurveySingleChoiceQuestion constructor + * + * The constructor takes possible arguments an creates an instance of the SurveySingleChoiceQuestion 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 = 1) + { + global $DIC; + + $this->db = $DIC->database(); + $this->user = $DIC->user(); + $this->lng = $DIC->language(); + parent::__construct($title, $description, $author, $questiontext, $owner); + + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyCategories.php"; + $this->orientation = $orientation; + $this->categories = new SurveyCategories(); + } + + /** + * Gets the available categories for a given phrase + * + * @param integer $phrase_id The database id of the given phrase + * @result array All available categories + * @access public + */ + public function &getCategoriesForPhrase($phrase_id) + { + $ilDB = $this->db; + $categories = array(); + $result = $ilDB->queryF( + "SELECT svy_category.* FROM svy_category, svy_phrase_cat WHERE svy_phrase_cat.category_fi = svy_category.category_id AND svy_phrase_cat.phrase_fi = %s ORDER BY svy_phrase_cat.sequence", + array('integer'), + array($phrase_id) + ); + while ($row = $ilDB->fetchAssoc($result)) { + if (($row["defaultvalue"] == 1) and ($row["owner_fi"] == 0)) { + $categories[$row["category_id"]] = $this->lng->txt($row["title"]); + } else { + $categories[$row["category_id"]] = $row["title"]; + } + } + return $categories; + } + + /** + * Adds a phrase to the question + * + * @param integer $phrase_id The database id of the given phrase + * @access public + */ + public function addPhrase($phrase_id) + { + $ilUser = $this->user; + $ilDB = $this->db; + + $result = $ilDB->queryF( + "SELECT svy_category.* FROM svy_category, svy_phrase_cat WHERE svy_phrase_cat.category_fi = svy_category.category_id AND svy_phrase_cat.phrase_fi = %s AND (svy_category.owner_fi = 0 OR svy_category.owner_fi = %s) ORDER BY svy_phrase_cat.sequence", + array('integer', 'integer'), + array($phrase_id, $ilUser->getId()) + ); + while ($row = $ilDB->fetchAssoc($result)) { + $neutral = $row["neutral"]; + if (($row["defaultvalue"] == 1) and ($row["owner_fi"] == 0)) { + $this->categories->addCategory($this->lng->txt($row["title"]), 0, $neutral); + } else { + $this->categories->addCategory($row["title"], 0, $neutral); + } + } + } + + /** + * 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 SurveySingleChoiceQuestion object from the database + * + * @param integer $id The database id of the single 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->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 SurveySingleChoiceQuestion object to a database + * + * @access public + */ + public function saveToDb($original_id = "") + { + $ilDB = $this->db; + + $affectedRows = parent::saveToDb($original_id); + if ($affectedRows == 1) { + $this->log->debug("Before save Category-> DELETE from svy_qst_sc WHERE question_fi = " . $this->getId() . " AND INSERT again the same id and orientation in svy_qst_sc"); + $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) VALUES (%s, %s)", + array('integer', 'text'), + array( + $this->getId(), + $this->getOrientation() + ) + ); + + $this->saveMaterial(); + $this->saveCategoriesToDb(); + } + } + + public function saveCategoriesToDb() + { + $ilDB = $this->db; + + $this->log->debug("DELETE from svy_variable before the INSERT into svy_variable. if scale > 0 we get scale value else we get null"); + + $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()) + ); + + $debug_scale = ($cat->scale > 0) ? $cat->scale : null; + $this->log->debug("INSERT INTO svy_variable category_fi= " . $category_id . " question_fi= " . $this->getId() . " value1= " . ($i + 1) . " other= " . $cat->other . " sequence= " . $i . " scale =" . $debug_scale); + } + $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_single", $attrs); + $this->addMaterialTag($a_xml_writer, $this->categories->getCategory($i)->title); + $a_xml_writer->xmlEndTag("response_single"); + } + + $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->xmlEndTag("metadata"); + + $a_xml_writer->xmlEndTag("question"); + } + + /** + * 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; + } + } + } + + /** + * Adds standard numbers as categories + * + * @param integer $lower_limit The lower limit + * @param integer $upper_limit The upper limit + * @access public + */ + public function addStandardNumbers($lower_limit, $upper_limit) + { + for ($i = $lower_limit; $i <= $upper_limit; $i++) { + $this->categories->addCategory($i); + } + } + + /** + * Saves a set of categories to a default phrase + * + * @param array $phrases The database ids of the seleted phrases + * @param string $title The title of the default phrase + * @access public + */ + public function savePhrase($title) + { + $ilUser = $this->user; + $ilDB = $this->db; + + $next_id = $ilDB->nextId('svy_phrase'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_phrase (phrase_id, title, defaultvalue, owner_fi, tstamp) VALUES (%s, %s, %s, %s, %s)", + array('integer','text','text','integer','integer'), + array($next_id, $title, 1, $ilUser->getId(), time()) + ); + $phrase_id = $next_id; + + $counter = 1; + foreach ($_SESSION['save_phrase_data'] as $data) { + $next_id = $ilDB->nextId('svy_category'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_category (category_id, title, defaultvalue, owner_fi, tstamp, neutral) VALUES (%s, %s, %s, %s, %s, %s)", + array('integer','text','text','integer','integer','text'), + array($next_id, $data['answer'], 1, $ilUser->getId(), time(), $data['neutral']) + ); + $category_id = $next_id; + $next_id = $ilDB->nextId('svy_phrase_cat'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_phrase_cat (phrase_category_id, phrase_fi, category_fi, sequence, other, scale) VALUES (%s, %s, %s, %s, %s, %s)", + array('integer', 'integer', 'integer','integer', 'integer', 'integer'), + array($next_id, $phrase_id, $category_id, $counter, ($data['other']) ? 1 : 0, $data['scale']) + ); + $counter++; + } + } + + /** + * Returns the question type of the question + * + * @return integer The question type of the question + * @access public + */ + public function getQuestionType() + { + return "SurveySingleChoiceQuestion"; + } + + /** + * 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_sc"; + } + + /** + * 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 (strlen($entered_value)) { + array_push($data, array("value" => $entered_value, "textanswer" => $post_data[$this->getId() . '_' . $entered_value . '_other'])); + } + for ($i = 0; $i < $this->categories->getCategoryCount(); $i++) { + $cat = $this->categories->getCategory($i); + if ($cat->other) { + if ($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"]; + + $this->log->debug("Entered value = " . $entered_value); + + if ((!$this->getObligatory($survey_id)) && (strlen($entered_value) == 0)) { + return ""; + } + + if (strlen($entered_value) == 0) { + return $this->lng->txt("question_not_checked"); + } + + for ($i = 0; $i < $this->categories->getCategoryCount(); $i++) { + $cat = $this->categories->getCategory($i); + if ($cat->other) { + if ($i == $entered_value) { + if (array_key_exists($this->getId() . "_" . $entered_value . "_other", $post_data) && !strlen($post_data[$this->getId() . "_" . $entered_value . "_other"])) { + return $this->lng->txt("question_mr_no_other_answer"); + } + } else { + if (strlen($post_data[$this->getId() . "_" . $i . "_other"])) { + return $this->lng->txt("question_sr_no_other_answer_checked"); + } + } + } + } + + return ""; + } + + public function saveUserInput($post_data, $active_id, $a_return = false) + { + $ilDB = $this->db; + + $entered_value = $post_data[$this->getId() . "_value"]; + + if ($a_return) { + return array(array("value"=>$entered_value, + "textanswer"=>$post_data[$this->getId() . "_" . $entered_value . "_other"])); + } + 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", ($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); + + $debug_value = (strlen($entered_value)) ? $entered_value : "NULL"; + $debug_answer = ($post_data[$this->getId() . "_" . $entered_value . "_other"]) ? $post_data[$this->getId() . "_" . $entered_value . "_other"] : "NULL"; + $this->log->debug("INSERT svy_answer answer_id=" . $next_id . " question_fi=" . $this->getId() . " active_fi=" . $active_id . " value=" . $debug_value . " textanswer=" . $debug_answer); + } + + /** + * 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.SurveySingleChoiceQuestionEvaluation.php b/Modules/SurveyQuestionPool/classes/class.SurveySingleChoiceQuestionEvaluation.php index 33ff887525ebfc2df39bce905de6f8ad56358e20..4bd8f736ead7755b0fe7dbc43164322585801766 100644 --- a/Modules/SurveyQuestionPool/classes/class.SurveySingleChoiceQuestionEvaluation.php +++ b/Modules/SurveyQuestionPool/classes/class.SurveySingleChoiceQuestionEvaluation.php @@ -4,80 +4,68 @@ include_once "Modules/SurveyQuestionPool/classes/class.SurveyQuestionEvaluation.php"; /** - * Survey sc evaluation + * Survey sc evaluation * * @author Jörg Lützenkirchen * @ingroup ModulesSurveyQuestionPool */ class SurveySingleChoiceQuestionEvaluation extends SurveyQuestionEvaluation { - // - // EXPORT - // - - public function getUserSpecificVariableTitles(array &$a_title_row, array &$a_title_row2, $a_do_title, $a_do_label) - { - $lng = $this->lng; + // + // EXPORT + // + + public function getUserSpecificVariableTitles(array &$a_title_row, array &$a_title_row2, $a_do_title, $a_do_label) + { + $lng = $this->lng; - // this is for the separation of title and scale, see #20646 - $a_title_row[] = $a_title_row[count($a_title_row) - 1]; - $a_title_row2[] = $a_title_row2[count($a_title_row2) - 1]; + // this is for the separation of title and scale, see #20646 + $a_title_row[] = $a_title_row[count($a_title_row) - 1]; + $a_title_row2[] = $a_title_row2[count($a_title_row2) - 1]; - $categories = $this->question->getCategories(); - for ($i = 0; $i < $categories->getCategoryCount(); $i++) - { - $cat = $categories->getCategory($i); - if ($cat->other) - { - $a_title_row[] = $cat->title." [".$cat->scale."]"; - $a_title_row2[] = $lng->txt('other'); - } - } - } - - public function addUserSpecificResults(array &$a_row, $a_user_id, $a_results) - { - // check if text answer column is needed - $other = array(); - $categories = $this->question->getCategories(); - for ($i = 0; $i < $categories->getCategoryCount(); $i++) - { - $cat = $categories->getCategory($i); - if ($cat->other) - { - $other[] = $cat->scale; - // outcommented due to #0021525 + $categories = $this->question->getCategories(); + for ($i = 0; $i < $categories->getCategoryCount(); $i++) { + $cat = $categories->getCategory($i); + if ($cat->other) { + $a_title_row[] = $cat->title . " [" . $cat->scale . "]"; + $a_title_row2[] = $lng->txt('other'); + } + } + } + + public function addUserSpecificResults(array &$a_row, $a_user_id, $a_results) + { + // check if text answer column is needed + $other = array(); + $categories = $this->question->getCategories(); + for ($i = 0; $i < $categories->getCategoryCount(); $i++) { + $cat = $categories->getCategory($i); + if ($cat->other) { + $other[] = $cat->scale; + // outcommented due to #0021525 // break; - } - } - - $answer = $a_results->getUserResults($a_user_id); - if($answer === null) - { - $a_row[] = $this->getSkippedValue(); - $a_row[] = ""; // see #20646 - foreach($other as $dummy) - { - $a_row[] = ""; - } - } - else - { - //$a_row[] = $answer[0][0]; // see #20646 - $a_row[] = $answer[0][3]; // see #20646 - $a_row[] = $answer[0][2]; // see #20646 + } + } + + $answer = $a_results->getUserResults($a_user_id); + if ($answer === null) { + $a_row[] = $this->getSkippedValue(); + $a_row[] = ""; // see #20646 + foreach ($other as $dummy) { + $a_row[] = ""; + } + } else { + //$a_row[] = $answer[0][0]; // see #20646 + $a_row[] = $answer[0][3]; // see #20646 + $a_row[] = $answer[0][2]; // see #20646 - foreach($other as $scale) - { - if($scale == $answer[0][2]) - { - $a_row[] = $answer[0][1]; - } - else - { - $a_row[] = ""; - } - } - } - } -} \ No newline at end of file + foreach ($other as $scale) { + if ($scale == $answer[0][2]) { + $a_row[] = $answer[0][1]; + } else { + $a_row[] = ""; + } + } + } + } +} diff --git a/Modules/SurveyQuestionPool/classes/class.SurveySingleChoiceQuestionGUI.php b/Modules/SurveyQuestionPool/classes/class.SurveySingleChoiceQuestionGUI.php index 59195e2e7bb0e642773bbaffd794f07cc727d91d..55c8ce8bf1a9909860d810a55dda868cdfb263f6 100755 --- a/Modules/SurveyQuestionPool/classes/class.SurveySingleChoiceQuestionGUI.php +++ b/Modules/SurveyQuestionPool/classes/class.SurveySingleChoiceQuestionGUI.php @@ -34,427 +34,373 @@ include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php"; * @extends SurveyQuestionGUI * @ingroup ModulesSurveyQuestionPool */ -class SurveySingleChoiceQuestionGUI extends SurveyQuestionGUI +class SurveySingleChoiceQuestionGUI extends SurveyQuestionGUI { - protected function initObject() - { - include_once "./Modules/SurveyQuestionPool/classes/class.SurveySingleChoiceQuestion.php"; - $this->object = new SurveySingleChoiceQuestion(); - } - - - // - // EDITOR - // - - public function setQuestionTabs() - { - $this->setQuestionTabsForClass("surveysinglechoicequestiongui"); - } - - protected function addFieldsToEditForm(ilPropertyFormGUI $a_form) - { - // orientation - $orientation = new ilRadioGroupInputGUI($this->lng->txt("orientation"), "orientation"); - $orientation->setRequired(false); - $orientation->addOption(new ilRadioOption($this->lng->txt('vertical'), 0)); - $orientation->addOption(new ilRadioOption($this->lng->txt('horizontal'), 1)); - $orientation->addOption(new ilRadioOption($this->lng->txt('combobox'), 2)); - $a_form->addItem($orientation); + protected function initObject() + { + include_once "./Modules/SurveyQuestionPool/classes/class.SurveySingleChoiceQuestion.php"; + $this->object = new SurveySingleChoiceQuestion(); + } + + + // + // EDITOR + // + + public function setQuestionTabs() + { + $this->setQuestionTabsForClass("surveysinglechoicequestiongui"); + } + + protected function addFieldsToEditForm(ilPropertyFormGUI $a_form) + { + // orientation + $orientation = new ilRadioGroupInputGUI($this->lng->txt("orientation"), "orientation"); + $orientation->setRequired(false); + $orientation->addOption(new ilRadioOption($this->lng->txt('vertical'), 0)); + $orientation->addOption(new ilRadioOption($this->lng->txt('horizontal'), 1)); + $orientation->addOption(new ilRadioOption($this->lng->txt('combobox'), 2)); + $a_form->addItem($orientation); - // Answers - include_once "./Modules/SurveyQuestionPool/classes/class.ilCategoryWizardInputGUI.php"; - $answers = new ilCategoryWizardInputGUI($this->lng->txt("answers"), "answers"); - $answers->setRequired(false); - $answers->setAllowMove(true); - $answers->setShowWizard(true); - $answers->setShowSavePhrase(true); - $answers->setUseOtherAnswer(true); - $answers->setShowNeutralCategory(true); - $answers->setNeutralCategoryTitle($this->lng->txt('svy_neutral_answer')); - $answers->setDisabledScale(false); - $a_form->addItem($answers); - - // values - $orientation->setValue($this->object->getOrientation()); - if (!$this->object->getCategories()->getCategoryCount()) - { - $this->object->getCategories()->addCategory(""); - } - $answers->setValues($this->object->getCategories()); - } - - protected function importEditFormValues(ilPropertyFormGUI $a_form) - { - $this->log->debug("importing edit values"); + // Answers + include_once "./Modules/SurveyQuestionPool/classes/class.ilCategoryWizardInputGUI.php"; + $answers = new ilCategoryWizardInputGUI($this->lng->txt("answers"), "answers"); + $answers->setRequired(false); + $answers->setAllowMove(true); + $answers->setShowWizard(true); + $answers->setShowSavePhrase(true); + $answers->setUseOtherAnswer(true); + $answers->setShowNeutralCategory(true); + $answers->setNeutralCategoryTitle($this->lng->txt('svy_neutral_answer')); + $answers->setDisabledScale(false); + $a_form->addItem($answers); + + // values + $orientation->setValue($this->object->getOrientation()); + if (!$this->object->getCategories()->getCategoryCount()) { + $this->object->getCategories()->addCategory(""); + } + $answers->setValues($this->object->getCategories()); + } + + protected function importEditFormValues(ilPropertyFormGUI $a_form) + { + $this->log->debug("importing edit values"); - $this->object->setOrientation($a_form->getInput("orientation")); - - $this->object->categories->flushCategories(); - 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_answer = $a_working_data[0]; - } - - $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) && - is_array($user_answer)) - { - if($value == $user_answer["value"]) - { - $checked = "checked"; - if($user_answer["textanswer"]) - { - $text = $user_answer["textanswer"]; - } - } - } - - // "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 - */ - function getPrintView($question_title = 1, $show_questiontext = 1, $survey_id = null, array $a_working_data = null) - { - $options = $this->getParsedAnswers($a_working_data); - - // rendering - - $template = new ilTemplate("tpl.il_svy_qpl_sc_printview.html", TRUE, TRUE, "Modules/SurveyQuestionPool"); - switch ($this->object->orientation) - { - case 0: - // vertical orientation - foreach($options as $option) - { - if ($option["other"]) - { - $template->setCurrentBlock("other_row"); - $template->setVariable("IMAGE_RADIO", ilUtil::getHtmlPath(ilUtil::getImagePath("radiobutton_".$option["checked"].".png"))); - $template->setVariable("ALT_RADIO", $this->lng->txt($option["checked"])); - $template->setVariable("TITLE_RADIO", $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("row"); - $template->setVariable("IMAGE_RADIO", ilUtil::getHtmlPath(ilUtil::getImagePath("radiobutton_".$option["checked"].".png"))); - $template->setVariable("ALT_RADIO", $this->lng->txt($option["checked"])); - $template->setVariable("TITLE_RADIO", $this->lng->txt($option["checked"])); - $template->setVariable("TEXT_SC", ilUtil::prepareFormOutput($option["title"])); - $template->parseCurrentBlock(); - } - } - break; - case 1: - // horizontal orientation - foreach($options as $option) - { - $template->setCurrentBlock("radio_col"); - $template->setVariable("IMAGE_RADIO", ilUtil::getHtmlPath(ilUtil::getImagePath("radiobutton_".$option["checked"].".png"))); - $template->setVariable("ALT_RADIO", $this->lng->txt($option["checked"])); - $template->setVariable("TITLE_RADIO", $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_SC", ilUtil::prepareFormOutput($option["title"])); - $template->parseCurrentBlock(); - } - } - break; - case 2: - foreach($options as $option) - { - $template->setCurrentBlock("comborow"); - $template->setVariable("TEXT_SC", ilUtil::prepareFormOutput($option["title"])); - $template->setVariable("VALUE_SC", $option["value"]); - if($option["checked"] == "checked") - { - $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->getPrintViewQuestionTitle($question_title)); - } - if ($show_questiontext) - { - $this->outQuestionText($template); - } - $template->parseCurrentBlock(); - return $template->get(); - } - - - // - // EXECUTION - // + $this->object->setOrientation($a_form->getInput("orientation")); + + $this->object->categories->flushCategories(); + 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_answer = $a_working_data[0]; + } + + $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) && + is_array($user_answer)) { + if ($value == $user_answer["value"]) { + $checked = "checked"; + if ($user_answer["textanswer"]) { + $text = $user_answer["textanswer"]; + } + } + } + + // "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); + + // rendering + + $template = new ilTemplate("tpl.il_svy_qpl_sc_printview.html", true, true, "Modules/SurveyQuestionPool"); + switch ($this->object->orientation) { + case 0: + // vertical orientation + foreach ($options as $option) { + if ($option["other"]) { + $template->setCurrentBlock("other_row"); + $template->setVariable("IMAGE_RADIO", ilUtil::getHtmlPath(ilUtil::getImagePath("radiobutton_" . $option["checked"] . ".png"))); + $template->setVariable("ALT_RADIO", $this->lng->txt($option["checked"])); + $template->setVariable("TITLE_RADIO", $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("row"); + $template->setVariable("IMAGE_RADIO", ilUtil::getHtmlPath(ilUtil::getImagePath("radiobutton_" . $option["checked"] . ".png"))); + $template->setVariable("ALT_RADIO", $this->lng->txt($option["checked"])); + $template->setVariable("TITLE_RADIO", $this->lng->txt($option["checked"])); + $template->setVariable("TEXT_SC", ilUtil::prepareFormOutput($option["title"])); + $template->parseCurrentBlock(); + } + } + break; + case 1: + // horizontal orientation + foreach ($options as $option) { + $template->setCurrentBlock("radio_col"); + $template->setVariable("IMAGE_RADIO", ilUtil::getHtmlPath(ilUtil::getImagePath("radiobutton_" . $option["checked"] . ".png"))); + $template->setVariable("ALT_RADIO", $this->lng->txt($option["checked"])); + $template->setVariable("TITLE_RADIO", $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_SC", ilUtil::prepareFormOutput($option["title"])); + $template->parseCurrentBlock(); + } + } + break; + case 2: + foreach ($options as $option) { + $template->setCurrentBlock("comborow"); + $template->setVariable("TEXT_SC", ilUtil::prepareFormOutput($option["title"])); + $template->setVariable("VALUE_SC", $option["value"]); + if ($option["checked"] == "checked") { + $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->getPrintViewQuestionTitle($question_title)); + } + if ($show_questiontext) { + $this->outQuestionText($template); + } + $template->parseCurrentBlock(); + return $template->get(); + } + + + // + // EXECUTION + // - /** - * Creates the question output form for the learner - * - * @access public - */ - function getWorkingForm($working_data = "", $question_title = 1, $show_questiontext = 1, $error_message = "", $survey_id = null) - { - $template = new ilTemplate("tpl.il_svy_out_sc.html", TRUE, TRUE, "Modules/SurveyQuestionPool"); - $template->setCurrentBlock("material"); - $template->setVariable("TEXT_MATERIAL", $this->getMaterialOutput()); - $template->parseCurrentBlock(); - switch ($this->object->orientation) - { - case 0: - // vertical orientation - for ($i = 0; $i < $this->object->categories->getCategoryCount(); $i++) - { - $cat = $this->object->categories->getCategory($i); + /** + * 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_sc.html", true, true, "Modules/SurveyQuestionPool"); + $template->setCurrentBlock("material"); + $template->setVariable("TEXT_MATERIAL", $this->getMaterialOutput()); + $template->parseCurrentBlock(); + switch ($this->object->orientation) { + case 0: + // vertical orientation + for ($i = 0; $i < $this->object->categories->getCategoryCount(); $i++) { + $cat = $this->object->categories->getCategory($i); - $debug_scale = ($cat->scale) ? ($cat->scale - 1) : $i; - $this->log->debug("Vertical orientation - Original scale = ".$cat->scale." If(scale) scale -1 else i. The new scale value is = ".$debug_scale); + $debug_scale = ($cat->scale) ? ($cat->scale - 1) : $i; + $this->log->debug("Vertical orientation - Original scale = " . $cat->scale . " If(scale) scale -1 else i. The new scale value is = " . $debug_scale); - if ($cat->other) - { - $template->setCurrentBlock("other_row"); - if (strlen($cat->title)) - { - $template->setVariable("OTHER_LABEL", $cat->title); - } - $template->setVariable("VALUE_SC", ($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 (strlen($value['textanswer'])) $template->setVariable("OTHER_VALUE", ' value="' . ilUtil::prepareFormOutput($value['textanswer']) . '"'); - if (!$value['uncheck']) - { - $template->setVariable("CHECKED_SC", " checked=\"checked\""); - } - } - } - } - } - $template->parseCurrentBlock(); - } - else - { - $template->setCurrentBlock("row"); - if ($cat->neutral) $template->setVariable('ROWCLASS', ' class="neutral"'); - $template->setVariable("TEXT_SC", ilUtil::prepareFormOutput($cat->title)); - $template->setVariable("VALUE_SC", ($cat->scale) ? ($cat->scale - 1) : $i); - $template->setVariable("QUESTION_ID", $this->object->getId()); - if (is_array($working_data)) - { - foreach ($working_data as $value) - { - if (strcmp($value["value"], "") != 0) - { - if ($value["value"] == $cat->scale-1) - { - if (!$value['uncheck']) - { - $template->setVariable("CHECKED_SC", " checked=\"checked\""); - } - } - } - } - } - $template->parseCurrentBlock(); - } - $template->touchBlock('outer_row'); - } - break; - case 1: - // horizontal 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_SC", ($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 (strlen($value['textanswer'])) { + $template->setVariable("OTHER_VALUE", ' value="' . ilUtil::prepareFormOutput($value['textanswer']) . '"'); + } + if (!$value['uncheck']) { + $template->setVariable("CHECKED_SC", " checked=\"checked\""); + } + } + } + } + } + $template->parseCurrentBlock(); + } else { + $template->setCurrentBlock("row"); + if ($cat->neutral) { + $template->setVariable('ROWCLASS', ' class="neutral"'); + } + $template->setVariable("TEXT_SC", ilUtil::prepareFormOutput($cat->title)); + $template->setVariable("VALUE_SC", ($cat->scale) ? ($cat->scale - 1) : $i); + $template->setVariable("QUESTION_ID", $this->object->getId()); + if (is_array($working_data)) { + foreach ($working_data as $value) { + if (strcmp($value["value"], "") != 0) { + if ($value["value"] == $cat->scale-1) { + if (!$value['uncheck']) { + $template->setVariable("CHECKED_SC", " checked=\"checked\""); + } + } + } + } + } + $template->parseCurrentBlock(); + } + $template->touchBlock('outer_row'); + } + break; + case 1: + // horizontal orientation + for ($i = 0; $i < $this->object->categories->getCategoryCount(); $i++) { + $cat = $this->object->categories->getCategory($i); - $debug_scale = ($cat->scale) ? ($cat->scale - 1) : $i; - $this->log->debug("Horizontal orientation - Original NEUTRAL scale = ".$cat->scale." If(scale) scale -1 else i. The new scale value is = ".$debug_scale); + $debug_scale = ($cat->scale) ? ($cat->scale - 1) : $i; + $this->log->debug("Horizontal orientation - Original NEUTRAL scale = " . $cat->scale . " If(scale) scale -1 else i. The new scale value is = " . $debug_scale); - $template->setCurrentBlock("radio_col"); - if ($cat->neutral) $template->setVariable('COLCLASS', ' neutral'); - $template->setVariable("VALUE_SC", ($cat->scale) ? ($cat->scale - 1) : $i); - $template->setVariable("QUESTION_ID", $this->object->getId()); - if (is_array($working_data)) - { - foreach ($working_data as $value) - { - if (strcmp($value["value"], "") != 0) - { - if ($value["value"] == $cat->scale-1) - { - if (!$value['uncheck']) - { - $template->setVariable("CHECKED_SC", " checked=\"checked\""); - } - } - } - } - } - $template->parseCurrentBlock(); - } - for ($i = 0; $i < $this->object->categories->getCategoryCount(); $i++) - { - $cat = $this->object->categories->getCategory($i); + $template->setCurrentBlock("radio_col"); + if ($cat->neutral) { + $template->setVariable('COLCLASS', ' neutral'); + } + $template->setVariable("VALUE_SC", ($cat->scale) ? ($cat->scale - 1) : $i); + $template->setVariable("QUESTION_ID", $this->object->getId()); + if (is_array($working_data)) { + foreach ($working_data as $value) { + if (strcmp($value["value"], "") != 0) { + if ($value["value"] == $cat->scale-1) { + if (!$value['uncheck']) { + $template->setVariable("CHECKED_SC", " checked=\"checked\""); + } + } + } + } + } + $template->parseCurrentBlock(); + } + for ($i = 0; $i < $this->object->categories->getCategoryCount(); $i++) { + $cat = $this->object->categories->getCategory($i); - $debug_scale = ($cat->scale) ? ($cat->scale - 1) : $i; - $this->log->debug("Horizontal orientation - Original scale = ".$cat->scale." If(scale) scale -1 else i. The new scale value is = ".$debug_scale); + $debug_scale = ($cat->scale) ? ($cat->scale - 1) : $i; + $this->log->debug("Horizontal orientation - Original scale = " . $cat->scale . " If(scale) scale -1 else i. The new scale value is = " . $debug_scale); - if ($cat->other) - { - $template->setCurrentBlock("text_other_col"); - $template->setVariable("VALUE_SC", ($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 && strlen($value['textanswer'])) - { - $template->setVariable("OTHER_VALUE", ' value="' . ilUtil::prepareFormOutput($value['textanswer']) . '"'); - } - } - } - } - $template->parseCurrentBlock(); - } - else - { - $template->setCurrentBlock("text_col"); - if ($cat->neutral) $template->setVariable('COLCLASS', ' neutral'); - $template->setVariable("VALUE_SC", ($cat->scale) ? ($cat->scale - 1) : $i); - $template->setVariable("TEXT_SC", ilUtil::prepareFormOutput($cat->title)); - $template->setVariable("QUESTION_ID", $this->object->getId()); - $template->parseCurrentBlock(); - } - $template->touchBlock('text_outer_col'); - } - break; - case 2: - // combobox output - for ($i = 0; $i < $this->object->categories->getCategoryCount(); $i++) - { - $cat = $this->object->categories->getCategory($i); + if ($cat->other) { + $template->setCurrentBlock("text_other_col"); + $template->setVariable("VALUE_SC", ($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 && strlen($value['textanswer'])) { + $template->setVariable("OTHER_VALUE", ' value="' . ilUtil::prepareFormOutput($value['textanswer']) . '"'); + } + } + } + } + $template->parseCurrentBlock(); + } else { + $template->setCurrentBlock("text_col"); + if ($cat->neutral) { + $template->setVariable('COLCLASS', ' neutral'); + } + $template->setVariable("VALUE_SC", ($cat->scale) ? ($cat->scale - 1) : $i); + $template->setVariable("TEXT_SC", ilUtil::prepareFormOutput($cat->title)); + $template->setVariable("QUESTION_ID", $this->object->getId()); + $template->parseCurrentBlock(); + } + $template->touchBlock('text_outer_col'); + } + break; + case 2: + // combobox output + for ($i = 0; $i < $this->object->categories->getCategoryCount(); $i++) { + $cat = $this->object->categories->getCategory($i); - $debug_scale = ($cat->scale) ? ($cat->scale - 1) : $i; - $this->log->debug("Combobox - Original scale = ".$cat->scale." If(scale) scale -1 else i. The new scale value is = ".$debug_scale); + $debug_scale = ($cat->scale) ? ($cat->scale - 1) : $i; + $this->log->debug("Combobox - Original scale = " . $cat->scale . " If(scale) scale -1 else i. The new scale value is = " . $debug_scale); - $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(); - } + $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 * @ingroup ModulesSurveyQuestionPool */ class SurveyTextQuestionEvaluation extends SurveyQuestionEvaluation -{ - // - // DETAILS - // - - public function getGrid($a_results, $a_abs = true, $a_perc = true) - { - - } - - public function getChart($a_results) - { - - } - +{ + // + // DETAILS + // + + public function getGrid($a_results, $a_abs = true, $a_perc = true) + { + } + + public function getChart($a_results) + { + } + - // - // EXPORT - // - - public function getExportGrid($a_results) - { - - } - - public function addUserSpecificResults(array &$a_row, $a_user_id, $a_results) - { - $answer = $a_results->getUserResults($a_user_id); - if($answer === null) - { - $a_row[] = $this->getSkippedValue(); - } - else - { - $a_row[] = $answer[0][1]; - } - } -} \ No newline at end of file + // + // EXPORT + // + + public function getExportGrid($a_results) + { + } + + public function addUserSpecificResults(array &$a_row, $a_user_id, $a_results) + { + $answer = $a_results->getUserResults($a_user_id); + if ($answer === null) { + $a_row[] = $this->getSkippedValue(); + } else { + $a_row[] = $answer[0][1]; + } + } +} diff --git a/Modules/SurveyQuestionPool/classes/class.SurveyTextQuestionGUI.php b/Modules/SurveyQuestionPool/classes/class.SurveyTextQuestionGUI.php index d81692c3051e7afad1815baf5d0703f4c4d14a19..e288738fd333381c0242af709efdadc328ad11f8 100755 --- a/Modules/SurveyQuestionPool/classes/class.SurveyTextQuestionGUI.php +++ b/Modules/SurveyQuestionPool/classes/class.SurveyTextQuestionGUI.php @@ -34,184 +34,162 @@ include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php"; * @extends SurveyQuestionGUI * @ingroup ModulesSurveyQuestionPool */ -class SurveyTextQuestionGUI extends SurveyQuestionGUI -{ - protected function initObject() - { - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyTextQuestion.php"; - $this->object = new SurveyTextQuestion(); - } - - - // - // EDITOR - // - - public function setQuestionTabs() - { - $this->setQuestionTabsForClass("surveytextquestiongui"); - } +class SurveyTextQuestionGUI extends SurveyQuestionGUI +{ + protected function initObject() + { + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyTextQuestion.php"; + $this->object = new SurveyTextQuestion(); + } + + + // + // EDITOR + // + + public function setQuestionTabs() + { + $this->setQuestionTabsForClass("surveytextquestiongui"); + } - protected function addFieldsToEditForm(ilPropertyFormGUI $a_form) - { - // maximum number of characters - $maxchars = new ilNumberInputGUI($this->lng->txt("maxchars"), "maxchars"); - $maxchars->setRequired(false); - $maxchars->setSize(5); - $maxchars->setDecimals(0); - $a_form->addItem($maxchars); - - // textwidth - $textwidth = new ilNumberInputGUI($this->lng->txt("width"), "textwidth"); - $textwidth->setRequired(true); - $textwidth->setSize(3); - $textwidth->setDecimals(0); - $textwidth->setMinValue(10, true); - $a_form->addItem($textwidth); - - // textheight - $textheight = new ilNumberInputGUI($this->lng->txt("height"), "textheight"); - $textheight->setRequired(true); - $textheight->setSize(3); - - $textheight->setDecimals(0); - $textheight->setMinValue(1); - $a_form->addItem($textheight); - - // values - if ($this->object->getMaxChars() > 0) - { - $maxchars->setValue($this->object->getMaxChars()); - } - $textwidth->setValue($this->object->getTextWidth()); - $textheight->setValue($this->object->getTextHeight()); - } - - protected function importEditFormValues(ilPropertyFormGUI $a_form) - { - $max = $a_form->getInput("maxchars"); - $this->object->setMaxChars(strlen($max) ? $max : null); - $this->object->setTextWidth($a_form->getInput("textwidth")); - $this->object->setTextHeight($a_form->getInput("textheight")); - } - - public function getParsedAnswers(array $a_working_data = null, $a_only_user_anwers = false) - { - $res = array(); - - if(is_array($a_working_data)) - { - $res[] = array("textanswer"=>trim($a_working_data[0]["textanswer"])); - } - - return $res; - } - - public function getPrintView($question_title = 1, $show_questiontext = 1, $survey_id = null, array $a_working_data = null) - { - $user_answer = null; - if($a_working_data) - { - $user_answer = $this->getParsedAnswers($a_working_data); - $user_answer = $user_answer[0]["textanswer"]; - } - - $template = new ilTemplate("tpl.il_svy_qpl_text_printview.html", TRUE, TRUE, "Modules/SurveyQuestionPool"); - if ($show_questiontext) - { - $this->outQuestionText($template); - } - if ($question_title) - { - $template->setVariable("QUESTION_TITLE", $this->getPrintViewQuestionTitle($question_title)); - } - $template->setVariable("QUESTION_ID", $this->object->getId()); - $template->setVariable("TEXT_ANSWER", $this->lng->txt("answer")); - if(is_array($a_working_data) && trim($user_answer)) - { - $template->setVariable("TEXT", nl2br($user_answer)); - } - else - { - $template->setVariable("TEXTBOX_IMAGE", ilUtil::getHtmlPath(ilUtil::getImagePath("textbox.png"))); - $template->setVariable("TEXTBOX", $this->lng->txt("textbox")); - $template->setVariable("TEXTBOX_WIDTH", $this->object->getTextWidth()*16); - $template->setVariable("TEXTBOX_HEIGHT", $this->object->getTextHeight()*16); - } - if ($this->object->getMaxChars()) - { - $template->setVariable("TEXT_MAXCHARS", sprintf($this->lng->txt("text_maximum_chars_allowed"), $this->object->getMaxChars())); - } - return $template->get(); - } - - - // - // EXECUTION - // + protected function addFieldsToEditForm(ilPropertyFormGUI $a_form) + { + // maximum number of characters + $maxchars = new ilNumberInputGUI($this->lng->txt("maxchars"), "maxchars"); + $maxchars->setRequired(false); + $maxchars->setSize(5); + $maxchars->setDecimals(0); + $a_form->addItem($maxchars); + + // textwidth + $textwidth = new ilNumberInputGUI($this->lng->txt("width"), "textwidth"); + $textwidth->setRequired(true); + $textwidth->setSize(3); + $textwidth->setDecimals(0); + $textwidth->setMinValue(10, true); + $a_form->addItem($textwidth); + + // textheight + $textheight = new ilNumberInputGUI($this->lng->txt("height"), "textheight"); + $textheight->setRequired(true); + $textheight->setSize(3); + + $textheight->setDecimals(0); + $textheight->setMinValue(1); + $a_form->addItem($textheight); + + // values + if ($this->object->getMaxChars() > 0) { + $maxchars->setValue($this->object->getMaxChars()); + } + $textwidth->setValue($this->object->getTextWidth()); + $textheight->setValue($this->object->getTextHeight()); + } + + protected function importEditFormValues(ilPropertyFormGUI $a_form) + { + $max = $a_form->getInput("maxchars"); + $this->object->setMaxChars(strlen($max) ? $max : null); + $this->object->setTextWidth($a_form->getInput("textwidth")); + $this->object->setTextHeight($a_form->getInput("textheight")); + } + + public function getParsedAnswers(array $a_working_data = null, $a_only_user_anwers = false) + { + $res = array(); + + if (is_array($a_working_data)) { + $res[] = array("textanswer"=>trim($a_working_data[0]["textanswer"])); + } + + return $res; + } + + public function getPrintView($question_title = 1, $show_questiontext = 1, $survey_id = null, array $a_working_data = null) + { + $user_answer = null; + if ($a_working_data) { + $user_answer = $this->getParsedAnswers($a_working_data); + $user_answer = $user_answer[0]["textanswer"]; + } + + $template = new ilTemplate("tpl.il_svy_qpl_text_printview.html", true, true, "Modules/SurveyQuestionPool"); + if ($show_questiontext) { + $this->outQuestionText($template); + } + if ($question_title) { + $template->setVariable("QUESTION_TITLE", $this->getPrintViewQuestionTitle($question_title)); + } + $template->setVariable("QUESTION_ID", $this->object->getId()); + $template->setVariable("TEXT_ANSWER", $this->lng->txt("answer")); + if (is_array($a_working_data) && trim($user_answer)) { + $template->setVariable("TEXT", nl2br($user_answer)); + } else { + $template->setVariable("TEXTBOX_IMAGE", ilUtil::getHtmlPath(ilUtil::getImagePath("textbox.png"))); + $template->setVariable("TEXTBOX", $this->lng->txt("textbox")); + $template->setVariable("TEXTBOX_WIDTH", $this->object->getTextWidth()*16); + $template->setVariable("TEXTBOX_HEIGHT", $this->object->getTextHeight()*16); + } + if ($this->object->getMaxChars()) { + $template->setVariable("TEXT_MAXCHARS", sprintf($this->lng->txt("text_maximum_chars_allowed"), $this->object->getMaxChars())); + } + return $template->get(); + } + + + // + // EXECUTION + // - /** - * Creates the question output form for the learner - */ - public function getWorkingForm($working_data = "", $question_title = 1, $show_questiontext = 1, $error_message = "", $survey_id = null) - { - $template = new ilTemplate("tpl.il_svy_out_text.html", TRUE, TRUE, "Modules/SurveyQuestionPool"); - $template->setCurrentBlock("material_text"); - $template->setVariable("TEXT_MATERIAL", $this->getMaterialOutput()); - $template->parseCurrentBlock(); + /** + * Creates the question output form for the learner + */ + public function getWorkingForm($working_data = "", $question_title = 1, $show_questiontext = 1, $error_message = "", $survey_id = null) + { + $template = new ilTemplate("tpl.il_svy_out_text.html", true, true, "Modules/SurveyQuestionPool"); + $template->setCurrentBlock("material_text"); + $template->setVariable("TEXT_MATERIAL", $this->getMaterialOutput()); + $template->parseCurrentBlock(); - 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(); - } + 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 * @version $Id$ * @ingroup ServicesForm */ class ilCategoryWizardInputGUI extends ilTextInputGUI { - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilTemplate + */ + protected $tpl; - protected $values = array(); - protected $allowMove = false; - protected $disabled_scale = true; - protected $show_wizard = false; - protected $show_save_phrase = false; - protected $categorytext; - protected $show_neutral_category = false; - protected $neutral_category_title; - protected $use_other_answer; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + protected $values = array(); + protected $allowMove = false; + protected $disabled_scale = true; + protected $show_wizard = false; + protected $show_save_phrase = false; + protected $categorytext; + protected $show_neutral_category = false; + protected $neutral_category_title; + protected $use_other_answer; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - $lng = $DIC->language(); - - parent::__construct($a_title, $a_postvar); - - $this->show_wizard = false; - $this->show_save_phrase = false; - $this->categorytext = $lng->txt('answer'); - $this->use_other_answer = false; - - $this->setMaxLength(1000); // #6218 - } - - public function getUseOtherAnswer() - { - return $this->use_other_answer; - } - - public function setUseOtherAnswer($a_value) - { - $this->use_other_answer = ($a_value) ? true : false; - } - - public function getCategoryCount() - { - if (!is_object($this->values)) return 0; - return $this->values->getCategoryCount(); - } - - protected function calcNeutralCategoryScale() - { - if (is_object($this->values)) - { - $scale = 0; - for ($i = 0; $i < $this->values->getCategoryCount(); $i++) - { - $cat = $this->values->getCategory($i); - if ($cat->neutral == 0) $scale += 1; - } - return $scale+1; - } - else - { - return 99; - } - } - - public function setShowNeutralCategory($a_value) - { - $this->show_neutral_category = $a_value; - } - - public function getShowNeutralCategory() - { - return $this->show_neutral_category; - } - - public function setNeutralCategoryTitle($a_title) - { - $this->neutral_category_title = $a_title; - } - - public function getNeutralCategoryTitle() - { - return $this->neutral_category_title; - } + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + $lng = $DIC->language(); + + parent::__construct($a_title, $a_postvar); + + $this->show_wizard = false; + $this->show_save_phrase = false; + $this->categorytext = $lng->txt('answer'); + $this->use_other_answer = false; + + $this->setMaxLength(1000); // #6218 + } + + public function getUseOtherAnswer() + { + return $this->use_other_answer; + } + + public function setUseOtherAnswer($a_value) + { + $this->use_other_answer = ($a_value) ? true : false; + } + + public function getCategoryCount() + { + if (!is_object($this->values)) { + return 0; + } + return $this->values->getCategoryCount(); + } + + protected function calcNeutralCategoryScale() + { + if (is_object($this->values)) { + $scale = 0; + for ($i = 0; $i < $this->values->getCategoryCount(); $i++) { + $cat = $this->values->getCategory($i); + if ($cat->neutral == 0) { + $scale += 1; + } + } + return $scale+1; + } else { + return 99; + } + } + + public function setShowNeutralCategory($a_value) + { + $this->show_neutral_category = $a_value; + } + + public function getShowNeutralCategory() + { + return $this->show_neutral_category; + } + + public function setNeutralCategoryTitle($a_title) + { + $this->neutral_category_title = $a_title; + } + + public function getNeutralCategoryTitle() + { + return $this->neutral_category_title; + } - /** - * Set Value. - * - * @param string $a_value Value - */ - function setValue($a_value) - { - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyCategories.php"; - $this->values = new SurveyCategories(); - if (is_array($a_value)) - { - if (is_array($a_value['answer'])) - { - foreach ($a_value['answer'] as $index => $value) - { - $this->values->addCategory($value, $a_value['other'][$index], null, null, $a_value['scale'][$index]); - } - } - } - if (array_key_exists('neutral', $a_value)) - { - $this->values->addCategory($a_value['neutral'], 0, 1, null, $_POST[$this->postvar . '_neutral_scale']); - } - } + /** + * Set Value. + * + * @param string $a_value Value + */ + public function setValue($a_value) + { + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyCategories.php"; + $this->values = new SurveyCategories(); + if (is_array($a_value)) { + if (is_array($a_value['answer'])) { + foreach ($a_value['answer'] as $index => $value) { + $this->values->addCategory($value, $a_value['other'][$index], null, null, $a_value['scale'][$index]); + } + } + } + if (array_key_exists('neutral', $a_value)) { + $this->values->addCategory($a_value['neutral'], 0, 1, null, $_POST[$this->postvar . '_neutral_scale']); + } + } - /** - * Set Values - * - * @param array $a_value Value - */ - function setValues($a_values) - { - $this->values = $a_values; - } + /** + * Set Values + * + * @param array $a_value Value + */ + public function setValues($a_values) + { + $this->values = $a_values; + } - /** - * Get Values - * - * @return array Values - */ - function getValues() - { - return $this->values; - } + /** + * Get Values + * + * @return array Values + */ + public function getValues() + { + return $this->values; + } - /** - * Set allow move - * - * @param boolean $a_allow_move Allow move - */ - function setAllowMove($a_allow_move) - { - $this->allowMove = $a_allow_move; - } + /** + * Set allow move + * + * @param boolean $a_allow_move Allow move + */ + public function setAllowMove($a_allow_move) + { + $this->allowMove = $a_allow_move; + } - /** - * Get allow move - * - * @return boolean Allow move - */ - function getAllowMove() - { - return $this->allowMove; - } - - function setShowWizard($a_value) - { - $this->show_wizard = $a_value; - } - - function getShowWizard() - { - return $this->show_wizard; - } - - public function setCategoryText($a_text) - { - $this->categorytext = $a_text; - } - - public function getCategoryText() - { - return $this->categorytext; - } - - function setShowSavePhrase($a_value) - { - $this->show_save_phrase = $a_value; - } - - function getShowSavePhrase() - { - return $this->show_save_phrase; - } - - function getDisabledScale() - { - return $this->disabled_scale; - } - - function setDisabledScale($a_value) - { - $this->disabled_scale = $a_value; - } + /** + * Get allow move + * + * @return boolean Allow move + */ + public function getAllowMove() + { + return $this->allowMove; + } + + public function setShowWizard($a_value) + { + $this->show_wizard = $a_value; + } + + public function getShowWizard() + { + return $this->show_wizard; + } + + public function setCategoryText($a_text) + { + $this->categorytext = $a_text; + } + + public function getCategoryText() + { + return $this->categorytext; + } + + public function setShowSavePhrase($a_value) + { + $this->show_save_phrase = $a_value; + } + + public function getShowSavePhrase() + { + return $this->show_save_phrase; + } + + public function getDisabledScale() + { + return $this->disabled_scale; + } + + public function setDisabledScale($a_value) + { + $this->disabled_scale = $a_value; + } - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - if (is_array($_POST[$this->getPostVar()])) $_POST[$this->getPostVar()] = ilUtil::stripSlashesRecursive($_POST[$this->getPostVar()]); - $foundvalues = $_POST[$this->getPostVar()]; - if (is_array($foundvalues)) - { - // check answers - if (is_array($foundvalues['answer'])) - { - foreach ($foundvalues['answer'] as $idx => $answervalue) - { - if (((strlen($answervalue)) == 0) && ($this->getRequired() && (!$foundvalues['other'][$idx]))) - { - $this->setAlert($lng->txt("msg_input_is_required")); - return FALSE; - } - } - } - // check neutral column - if (array_key_exists('neutral', $foundvalues)) - { - if ((strlen($foundvalues['neutral']) == 0) && ($this->getRequired)) - { - $this->setAlert($lng->txt("msg_input_is_required")); - return false; - } - } - // check scales - if (is_array($foundvalues['scale'])) - { - foreach ($foundvalues['scale'] as $scale) - { + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + if (is_array($_POST[$this->getPostVar()])) { + $_POST[$this->getPostVar()] = ilUtil::stripSlashesRecursive($_POST[$this->getPostVar()]); + } + $foundvalues = $_POST[$this->getPostVar()]; + if (is_array($foundvalues)) { + // check answers + if (is_array($foundvalues['answer'])) { + foreach ($foundvalues['answer'] as $idx => $answervalue) { + if (((strlen($answervalue)) == 0) && ($this->getRequired() && (!$foundvalues['other'][$idx]))) { + $this->setAlert($lng->txt("msg_input_is_required")); + return false; + } + } + } + // check neutral column + if (array_key_exists('neutral', $foundvalues)) { + if ((strlen($foundvalues['neutral']) == 0) && ($this->getRequired)) { + $this->setAlert($lng->txt("msg_input_is_required")); + return false; + } + } + // check scales + if (is_array($foundvalues['scale'])) { + foreach ($foundvalues['scale'] as $scale) { //scales required - if ((strlen($scale)) == 0) - { - $this->setAlert($lng->txt("msg_input_is_required")); - return FALSE; - } + if ((strlen($scale)) == 0) { + $this->setAlert($lng->txt("msg_input_is_required")); + return false; + } //scales positive number - if (!ctype_digit($scale) || $scale <= 0) - { + if (!ctype_digit($scale) || $scale <= 0) { $this->setAlert($lng->txt("msg_input_only_positive_numbers")); - return FALSE; + return false; } - } + } //scales no duplicates. - if (count(array_unique($foundvalues['scale'])) != count($foundvalues['scale'])) - { + if (count(array_unique($foundvalues['scale'])) != count($foundvalues['scale'])) { $this->setAlert($lng->txt("msg_duplicate_scale")); - return FALSE; + return false; } - } + } - // check neutral column scale - if (strlen($_POST[$this->postvar . '_neutral_scale'])) - { - if (is_array($foundvalues['scale'])) - { - if (in_array($_POST[$this->postvar . '_neutral_scale'], $foundvalues['scale'])) - { - $this->setAlert($lng->txt("msg_duplicate_scale")); - return FALSE; - } - } - } - } - else - { - $this->setAlert($lng->txt("msg_input_is_required")); - return FALSE; - } - return $this->checkSubItemsInput(); - } + // check neutral column scale + if (strlen($_POST[$this->postvar . '_neutral_scale'])) { + if (is_array($foundvalues['scale'])) { + if (in_array($_POST[$this->postvar . '_neutral_scale'], $foundvalues['scale'])) { + $this->setAlert($lng->txt("msg_duplicate_scale")); + return false; + } + } + } + } else { + $this->setAlert($lng->txt("msg_input_is_required")); + return false; + } + return $this->checkSubItemsInput(); + } - /** - * Insert property html - * - * @return int Size - */ - function insert($a_tpl) - { - $lng = $this->lng; - - $neutral_category = null; - $tpl = new ilTemplate("tpl.prop_categorywizardinput.html", true, true, "Modules/SurveyQuestionPool"); - $i = 0; - if (is_object($this->values)) - { - for ($i = 0; $i < $this->values->getCategoryCount(); $i++) - { - $cat = $this->values->getCategory($i); - if (!$cat->neutral) - { - $tpl->setCurrentBlock("prop_text_propval"); - $tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($cat->title)); - $tpl->parseCurrentBlock(); - $tpl->setCurrentBlock("prop_scale_propval"); - $tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($this->values->getScale($i))); - $tpl->parseCurrentBlock(); + /** + * Insert property html + * + * @return int Size + */ + public function insert($a_tpl) + { + $lng = $this->lng; + + $neutral_category = null; + $tpl = new ilTemplate("tpl.prop_categorywizardinput.html", true, true, "Modules/SurveyQuestionPool"); + $i = 0; + if (is_object($this->values)) { + for ($i = 0; $i < $this->values->getCategoryCount(); $i++) { + $cat = $this->values->getCategory($i); + if (!$cat->neutral) { + $tpl->setCurrentBlock("prop_text_propval"); + $tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($cat->title)); + $tpl->parseCurrentBlock(); + $tpl->setCurrentBlock("prop_scale_propval"); + $tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($this->values->getScale($i))); + $tpl->parseCurrentBlock(); - if ($this->getUseOtherAnswer()) - { - $tpl->setCurrentBlock("other_answer_checkbox"); - $tpl->setVariable("POST_VAR", $this->getPostVar()); - $tpl->setVariable("OTHER_ID", $this->getPostVar() . "[other][$i]"); - $tpl->setVariable("ROW_NUMBER", $i); - if ($cat->other) - { - $tpl->setVariable("CHECKED_OTHER", ' checked="checked"'); - } - $tpl->parseCurrentBlock(); - } + if ($this->getUseOtherAnswer()) { + $tpl->setCurrentBlock("other_answer_checkbox"); + $tpl->setVariable("POST_VAR", $this->getPostVar()); + $tpl->setVariable("OTHER_ID", $this->getPostVar() . "[other][$i]"); + $tpl->setVariable("ROW_NUMBER", $i); + if ($cat->other) { + $tpl->setVariable("CHECKED_OTHER", ' checked="checked"'); + } + $tpl->parseCurrentBlock(); + } - if ($this->getAllowMove()) - { - $tpl->setCurrentBlock("move"); - $tpl->setVariable("CMD_UP", "cmd[up" . $this->getFieldId() . "][$i]"); - $tpl->setVariable("CMD_DOWN", "cmd[down" . $this->getFieldId() . "][$i]"); - $tpl->setVariable("ID", $this->getPostVar() . "[$i]"); - include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); - $tpl->setVariable("UP_BUTTON", ilGlyphGUI::get(ilGlyphGUI::UP)); - $tpl->setVariable("DOWN_BUTTON", ilGlyphGUI::get(ilGlyphGUI::DOWN)); - $tpl->parseCurrentBlock(); - } - - $tpl->setCurrentBlock("row"); - $tpl->setVariable("POST_VAR", $this->getPostVar()); - $tpl->setVariable("ROW_NUMBER", $i); - $tpl->setVariable("ID", $this->getPostVar() . "[answer][$i]"); - $tpl->setVariable("SIZE", $this->getSize()); - $tpl->setVariable("MAXLENGTH", $this->getMaxLength()); - if ($this->getDisabled()) - { - $tpl->setVariable("DISABLED", " disabled=\"disabled\""); - } + if ($this->getAllowMove()) { + $tpl->setCurrentBlock("move"); + $tpl->setVariable("CMD_UP", "cmd[up" . $this->getFieldId() . "][$i]"); + $tpl->setVariable("CMD_DOWN", "cmd[down" . $this->getFieldId() . "][$i]"); + $tpl->setVariable("ID", $this->getPostVar() . "[$i]"); + include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); + $tpl->setVariable("UP_BUTTON", ilGlyphGUI::get(ilGlyphGUI::UP)); + $tpl->setVariable("DOWN_BUTTON", ilGlyphGUI::get(ilGlyphGUI::DOWN)); + $tpl->parseCurrentBlock(); + } + + $tpl->setCurrentBlock("row"); + $tpl->setVariable("POST_VAR", $this->getPostVar()); + $tpl->setVariable("ROW_NUMBER", $i); + $tpl->setVariable("ID", $this->getPostVar() . "[answer][$i]"); + $tpl->setVariable("SIZE", $this->getSize()); + $tpl->setVariable("MAXLENGTH", $this->getMaxLength()); + if ($this->getDisabled()) { + $tpl->setVariable("DISABLED", " disabled=\"disabled\""); + } - $tpl->setVariable("SCALE_ID", $this->getPostVar() . "[scale][$i]"); - if ($this->getDisabledScale()) - { - $tpl->setVariable("DISABLED_SCALE", " disabled=\"disabled\""); - } + $tpl->setVariable("SCALE_ID", $this->getPostVar() . "[scale][$i]"); + if ($this->getDisabledScale()) { + $tpl->setVariable("DISABLED_SCALE", " disabled=\"disabled\""); + } - $tpl->setVariable("CMD_ADD", "cmd[add" . $this->getFieldId() . "][$i]"); - $tpl->setVariable("CMD_REMOVE", "cmd[remove" . $this->getFieldId() . "][$i]"); - include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); - $tpl->setVariable("ADD_BUTTON", ilGlyphGUI::get(ilGlyphGUI::ADD)); - $tpl->setVariable("REMOVE_BUTTON", ilGlyphGUI::get(ilGlyphGUI::REMOVE)); - $tpl->parseCurrentBlock(); - } - else - { - $neutral_category = $cat; - } - } - } + $tpl->setVariable("CMD_ADD", "cmd[add" . $this->getFieldId() . "][$i]"); + $tpl->setVariable("CMD_REMOVE", "cmd[remove" . $this->getFieldId() . "][$i]"); + include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); + $tpl->setVariable("ADD_BUTTON", ilGlyphGUI::get(ilGlyphGUI::ADD)); + $tpl->setVariable("REMOVE_BUTTON", ilGlyphGUI::get(ilGlyphGUI::REMOVE)); + $tpl->parseCurrentBlock(); + } else { + $neutral_category = $cat; + } + } + } - if ($this->getShowWizard()) - { - $tpl->setCurrentBlock("wizard"); - $tpl->setVariable("CMD_WIZARD", 'cmd[addPhrase]'); - $tpl->setVariable("WIZARD_BUTTON", ilUtil::getImagePath('wizard.svg')); - $tpl->setVariable("WIZARD_TEXT", $lng->txt('add_phrase')); - $tpl->parseCurrentBlock(); - } - - if ($this->getShowSavePhrase()) - { - $tpl->setCurrentBlock('savephrase'); - $tpl->setVariable("POST_VAR", $this->getPostVar()); - $tpl->setVariable("VALUE_SAVE_PHRASE", $lng->txt('save_phrase')); - $tpl->parseCurrentBlock(); - } - - if ($this->getShowNeutralCategory()) - { - if (is_object($neutral_category) && strlen($neutral_category->title)) - { - $tpl->setCurrentBlock("prop_text_neutral_propval"); - $tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($neutral_category->title)); - $tpl->parseCurrentBlock(); - } - if (strlen($this->getNeutralCategoryTitle())) - { - $tpl->setCurrentBlock("neutral_category_title"); - $tpl->setVariable("NEUTRAL_COLS", ($this->getUseOtherAnswer()) ? 4 : 3); - $tpl->setVariable("CATEGORY_TITLE", ilUtil::prepareFormOutput($this->getNeutralCategoryTitle())); - $tpl->parseCurrentBlock(); - } - $tpl->setCurrentBlock("prop_scale_neutral_propval"); - $scale = ($neutral_category->scale > 0) ? $neutral_category->scale : $this->values->getNewScale(); - $tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($scale)); - $tpl->parseCurrentBlock(); + if ($this->getShowWizard()) { + $tpl->setCurrentBlock("wizard"); + $tpl->setVariable("CMD_WIZARD", 'cmd[addPhrase]'); + $tpl->setVariable("WIZARD_BUTTON", ilUtil::getImagePath('wizard.svg')); + $tpl->setVariable("WIZARD_TEXT", $lng->txt('add_phrase')); + $tpl->parseCurrentBlock(); + } + + if ($this->getShowSavePhrase()) { + $tpl->setCurrentBlock('savephrase'); + $tpl->setVariable("POST_VAR", $this->getPostVar()); + $tpl->setVariable("VALUE_SAVE_PHRASE", $lng->txt('save_phrase')); + $tpl->parseCurrentBlock(); + } + + if ($this->getShowNeutralCategory()) { + if (is_object($neutral_category) && strlen($neutral_category->title)) { + $tpl->setCurrentBlock("prop_text_neutral_propval"); + $tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($neutral_category->title)); + $tpl->parseCurrentBlock(); + } + if (strlen($this->getNeutralCategoryTitle())) { + $tpl->setCurrentBlock("neutral_category_title"); + $tpl->setVariable("NEUTRAL_COLS", ($this->getUseOtherAnswer()) ? 4 : 3); + $tpl->setVariable("CATEGORY_TITLE", ilUtil::prepareFormOutput($this->getNeutralCategoryTitle())); + $tpl->parseCurrentBlock(); + } + $tpl->setCurrentBlock("prop_scale_neutral_propval"); + $scale = ($neutral_category->scale > 0) ? $neutral_category->scale : $this->values->getNewScale(); + $tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($scale)); + $tpl->parseCurrentBlock(); - if ($this->getUseOtherAnswer()) - { - $tpl->touchBlock('other_answer_neutral'); - } + if ($this->getUseOtherAnswer()) { + $tpl->touchBlock('other_answer_neutral'); + } - $tpl->setCurrentBlock('neutral_row'); - $tpl->setVariable("POST_VAR", $this->getPostVar()); - $tpl->setVariable("ID", $this->getPostVar() . "_neutral"); - $tpl->setVariable("SIZE", $this->getSize()); - $tpl->setVariable("MAXLENGTH", $this->getMaxLength()); - if ($this->getDisabled()) - { - $tpl->setVariable("DISABLED", " disabled=\"disabled\""); - } - $tpl->setVariable("SCALE_ID", $this->getPostVar() . "_neutral_scale"); - if ($this->getDisabledScale()) - { - $tpl->setVariable("DISABLED_SCALE", " disabled=\"disabled\""); - } - $tpl->parseCurrentBlock(); - } + $tpl->setCurrentBlock('neutral_row'); + $tpl->setVariable("POST_VAR", $this->getPostVar()); + $tpl->setVariable("ID", $this->getPostVar() . "_neutral"); + $tpl->setVariable("SIZE", $this->getSize()); + $tpl->setVariable("MAXLENGTH", $this->getMaxLength()); + if ($this->getDisabled()) { + $tpl->setVariable("DISABLED", " disabled=\"disabled\""); + } + $tpl->setVariable("SCALE_ID", $this->getPostVar() . "_neutral_scale"); + if ($this->getDisabledScale()) { + $tpl->setVariable("DISABLED_SCALE", " disabled=\"disabled\""); + } + $tpl->parseCurrentBlock(); + } - if ($this->getUseOtherAnswer()) - { - $tpl->setCurrentBlock('other_answer_title'); - $tpl->setVariable("OTHER_TEXT", $lng->txt('use_other_answer')); - $tpl->parseCurrentBlock(); - } + if ($this->getUseOtherAnswer()) { + $tpl->setCurrentBlock('other_answer_title'); + $tpl->setVariable("OTHER_TEXT", $lng->txt('use_other_answer')); + $tpl->parseCurrentBlock(); + } - $tpl->setVariable("ELEMENT_ID", $this->getPostVar()); - $tpl->setVariable("ANSWER_TEXT", $this->getCategoryText()); - $tpl->setVariable("SCALE_TEXT", $lng->txt('scale')); - $tpl->setVariable("ACTIONS_TEXT", $lng->txt('actions')); - - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $tpl->get()); - $a_tpl->parseCurrentBlock(); - - $tpl = $this->tpl; - $tpl->addJavascript("./Services/Form/js/ServiceFormWizardInput.js"); - $tpl->addJavascript("./Modules/SurveyQuestionPool/templates/default/categorywizard.js"); - } + $tpl->setVariable("ELEMENT_ID", $this->getPostVar()); + $tpl->setVariable("ANSWER_TEXT", $this->getCategoryText()); + $tpl->setVariable("SCALE_TEXT", $lng->txt('scale')); + $tpl->setVariable("ACTIONS_TEXT", $lng->txt('actions')); + + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $tpl->get()); + $a_tpl->parseCurrentBlock(); + + $tpl = $this->tpl; + $tpl->addJavascript("./Services/Form/js/ServiceFormWizardInput.js"); + $tpl->addJavascript("./Modules/SurveyQuestionPool/templates/default/categorywizard.js"); + } } diff --git a/Modules/SurveyQuestionPool/classes/class.ilMaterialExplorer.php b/Modules/SurveyQuestionPool/classes/class.ilMaterialExplorer.php index 74252795b8c8ed318157a99b91d77755564f1b14..72e399204067c75654cda0c2e1fd2b2422281baf 100644 --- a/Modules/SurveyQuestionPool/classes/class.ilMaterialExplorer.php +++ b/Modules/SurveyQuestionPool/classes/class.ilMaterialExplorer.php @@ -1,24 +1,24 @@ tree = $DIC->repositoryTree(); - $this->ctrl = $DIC->ctrl(); - $tree = $DIC->repositoryTree(); - - parent::__construct("rep_exp", $a_parent_obj, $a_parent_cmd, $tree); - - $this->current_type = $a_selectable_type; - - $this->setTypeWhiteList(array("root", "cat", "grp", "fold", "crs", $this->current_type)); - $this->setSkipRootNode(true); - $this->setAjax(true); - } - - function getNodeContent($a_node) - { - return $a_node["title"]; - } - - function getNodeIcon($a_node) - { - $obj_id = ilObject::_lookupObjId($a_node["child"]); - return ilObject::_getIcon($obj_id, "tiny", $a_node["type"]); - } - - function getNodeHref($a_node) - { - $ilCtrl = $this->ctrl; + $this->tree = $DIC->repositoryTree(); + $this->ctrl = $DIC->ctrl(); + $tree = $DIC->repositoryTree(); + + parent::__construct("rep_exp", $a_parent_obj, $a_parent_cmd, $tree); + + $this->current_type = $a_selectable_type; + + $this->setTypeWhiteList(array("root", "cat", "grp", "fold", "crs", $this->current_type)); + $this->setSkipRootNode(true); + $this->setAjax(true); + } + + public function getNodeContent($a_node) + { + return $a_node["title"]; + } + + public function getNodeIcon($a_node) + { + $obj_id = ilObject::_lookupObjId($a_node["child"]); + return ilObject::_getIcon($obj_id, "tiny", $a_node["type"]); + } + + public function getNodeHref($a_node) + { + $ilCtrl = $this->ctrl; - $ilCtrl->setParameter($this->parent_obj, 'source_id', $a_node["child"]); - return $ilCtrl->getLinkTarget($this->parent_obj, 'linkChilds'); - } - - function isNodeClickable($a_node) - { - return ($a_node["type"] == $this->current_type); - } -} - -?> \ No newline at end of file + $ilCtrl->setParameter($this->parent_obj, 'source_id', $a_node["child"]); + return $ilCtrl->getLinkTarget($this->parent_obj, 'linkChilds'); + } + + public function isNodeClickable($a_node) + { + return ($a_node["type"] == $this->current_type); + } +} diff --git a/Modules/SurveyQuestionPool/classes/class.ilMatrixRowWizardInputGUI.php b/Modules/SurveyQuestionPool/classes/class.ilMatrixRowWizardInputGUI.php index 2910b79f61e446f40af924d03cb5349eedcabb5e..53e0b2d2a60e14a0e236df9535ff8400e17a8585 100644 --- a/Modules/SurveyQuestionPool/classes/class.ilMatrixRowWizardInputGUI.php +++ b/Modules/SurveyQuestionPool/classes/class.ilMatrixRowWizardInputGUI.php @@ -1,323 +1,307 @@ +* @author Helmut Schottmüller * @version $Id: class.ilMatrixRowWizardInputGUI.php 23642 2010-04-26 12:31:50Z hschottm $ * @ingroup ServicesForm */ class ilMatrixRowWizardInputGUI extends ilTextInputGUI { - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilTemplate + */ + protected $tpl; - protected $values = array(); - protected $allowMove = false; - protected $show_wizard = false; - protected $show_save_phrase = false; - protected $categorytext; - protected $labeltext; - protected $use_other_answer; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + protected $values = array(); + protected $allowMove = false; + protected $show_wizard = false; + protected $show_save_phrase = false; + protected $categorytext; + protected $labeltext; + protected $use_other_answer; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - $lng = $DIC->language(); - - parent::__construct($a_title, $a_postvar); - - $this->show_wizard = false; - $this->show_save_phrase = false; - $this->categorytext = $lng->txt('row_text'); - $this->use_other_answer = false; - - $this->setMaxLength(1000); // #6803 - } - - public function getUseOtherAnswer() - { - return $this->use_other_answer; - } - - public function setUseOtherAnswer($a_value) - { - $this->use_other_answer = ($a_value) ? true : false; - } - - /** - * Set Value. - * - * @param string $a_value Value - */ - function setValue($a_value) - { - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyCategories.php"; - $this->values = new SurveyCategories(); - if (is_array($a_value)) - { - if (is_array($a_value['answer'])) - { - foreach ($a_value['answer'] as $index => $value) - { - $this->values->addCategory($value, $a_value['other'][$index]); - } - } - } - } + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + $lng = $DIC->language(); + + parent::__construct($a_title, $a_postvar); + + $this->show_wizard = false; + $this->show_save_phrase = false; + $this->categorytext = $lng->txt('row_text'); + $this->use_other_answer = false; + + $this->setMaxLength(1000); // #6803 + } + + public function getUseOtherAnswer() + { + return $this->use_other_answer; + } + + public function setUseOtherAnswer($a_value) + { + $this->use_other_answer = ($a_value) ? true : false; + } + + /** + * Set Value. + * + * @param string $a_value Value + */ + public function setValue($a_value) + { + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyCategories.php"; + $this->values = new SurveyCategories(); + if (is_array($a_value)) { + if (is_array($a_value['answer'])) { + foreach ($a_value['answer'] as $index => $value) { + $this->values->addCategory($value, $a_value['other'][$index]); + } + } + } + } - /** - * Set Values - * - * @param array $a_value Value - */ - function setValues($a_values) - { - $this->values = $a_values; - } + /** + * Set Values + * + * @param array $a_value Value + */ + public function setValues($a_values) + { + $this->values = $a_values; + } - /** - * Get Values - * - * @return array Values - */ - function getValues() - { - return $this->values; - } + /** + * Get Values + * + * @return array Values + */ + public function getValues() + { + return $this->values; + } - /** - * Set allow move - * - * @param boolean $a_allow_move Allow move - */ - function setAllowMove($a_allow_move) - { - $this->allowMove = $a_allow_move; - } + /** + * Set allow move + * + * @param boolean $a_allow_move Allow move + */ + public function setAllowMove($a_allow_move) + { + $this->allowMove = $a_allow_move; + } - /** - * Get allow move - * - * @return boolean Allow move - */ - function getAllowMove() - { - return $this->allowMove; - } - - function setShowWizard($a_value) - { - $this->show_wizard = $a_value; - } - - function getShowWizard() - { - return $this->show_wizard; - } - - public function setCategoryText($a_text) - { - $this->categorytext = $a_text; - } - - public function getCategoryText() - { - return $this->categorytext; - } - - public function setLabelText($a_text) - { - $this->labeltext = $a_text; - } - - public function getLabelText() - { - return $this->labeltext; - } - - function setShowSavePhrase($a_value) - { - $this->show_save_phrase = $a_value; - } - - function getShowSavePhrase() - { - return $this->show_save_phrase; - } - - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - if (is_array($_POST[$this->getPostVar()])) $_POST[$this->getPostVar()] = ilUtil::stripSlashesRecursive($_POST[$this->getPostVar()]); - $foundvalues = $_POST[$this->getPostVar()]; - if (is_array($foundvalues)) - { - // check answers - if (is_array($foundvalues['answer'])) - { - foreach ($foundvalues['answer'] as $idx => $answervalue) - { - if (((strlen($answervalue)) == 0) && ($this->getRequired() && (!$foundvalues['other'][$idx]))) - { - $this->setAlert($lng->txt("msg_input_is_required")); - return FALSE; - } - } - } - } - else - { - $this->setAlert($lng->txt("msg_input_is_required")); - return FALSE; - } - - return $this->checkSubItemsInput(); - } + /** + * Get allow move + * + * @return boolean Allow move + */ + public function getAllowMove() + { + return $this->allowMove; + } + + public function setShowWizard($a_value) + { + $this->show_wizard = $a_value; + } + + public function getShowWizard() + { + return $this->show_wizard; + } + + public function setCategoryText($a_text) + { + $this->categorytext = $a_text; + } + + public function getCategoryText() + { + return $this->categorytext; + } + + public function setLabelText($a_text) + { + $this->labeltext = $a_text; + } + + public function getLabelText() + { + return $this->labeltext; + } + + public function setShowSavePhrase($a_value) + { + $this->show_save_phrase = $a_value; + } + + public function getShowSavePhrase() + { + return $this->show_save_phrase; + } + + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + if (is_array($_POST[$this->getPostVar()])) { + $_POST[$this->getPostVar()] = ilUtil::stripSlashesRecursive($_POST[$this->getPostVar()]); + } + $foundvalues = $_POST[$this->getPostVar()]; + if (is_array($foundvalues)) { + // check answers + if (is_array($foundvalues['answer'])) { + foreach ($foundvalues['answer'] as $idx => $answervalue) { + if (((strlen($answervalue)) == 0) && ($this->getRequired() && (!$foundvalues['other'][$idx]))) { + $this->setAlert($lng->txt("msg_input_is_required")); + return false; + } + } + } + } else { + $this->setAlert($lng->txt("msg_input_is_required")); + return false; + } + + return $this->checkSubItemsInput(); + } - /** - * Insert property html - * - * @return int Size - */ - function insert($a_tpl) - { - $lng = $this->lng; - - $tpl = new ilTemplate("tpl.prop_matrixrowwizardinput.html", true, true, "Modules/SurveyQuestionPool"); - $i = 0; - if (is_object($this->values)) - { - for ($i = 0; $i < $this->values->getCategoryCount(); $i++) - { - $cat = $this->values->getCategory($i); - $tpl->setCurrentBlock("prop_text_propval"); - $tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($cat->title)); - $tpl->parseCurrentBlock(); - $tpl->setCurrentBlock("prop_label_propval"); - $tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($cat->label)); - $tpl->parseCurrentBlock(); + /** + * Insert property html + * + * @return int Size + */ + public function insert($a_tpl) + { + $lng = $this->lng; + + $tpl = new ilTemplate("tpl.prop_matrixrowwizardinput.html", true, true, "Modules/SurveyQuestionPool"); + $i = 0; + if (is_object($this->values)) { + for ($i = 0; $i < $this->values->getCategoryCount(); $i++) { + $cat = $this->values->getCategory($i); + $tpl->setCurrentBlock("prop_text_propval"); + $tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($cat->title)); + $tpl->parseCurrentBlock(); + $tpl->setCurrentBlock("prop_label_propval"); + $tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($cat->label)); + $tpl->parseCurrentBlock(); - if ($this->getUseOtherAnswer()) - { - $tpl->setCurrentBlock("other_answer_checkbox"); - $tpl->setVariable("POST_VAR", $this->getPostVar()); - $tpl->setVariable("OTHER_ID", $this->getPostVar() . "[other][$i]"); - $tpl->setVariable("ROW_NUMBER", $i); - if ($cat->other) - { - $tpl->setVariable("CHECKED_OTHER", ' checked="checked"'); - } - $tpl->parseCurrentBlock(); - } + if ($this->getUseOtherAnswer()) { + $tpl->setCurrentBlock("other_answer_checkbox"); + $tpl->setVariable("POST_VAR", $this->getPostVar()); + $tpl->setVariable("OTHER_ID", $this->getPostVar() . "[other][$i]"); + $tpl->setVariable("ROW_NUMBER", $i); + if ($cat->other) { + $tpl->setVariable("CHECKED_OTHER", ' checked="checked"'); + } + $tpl->parseCurrentBlock(); + } - if ($this->getAllowMove()) - { - $tpl->setCurrentBlock("move"); - $tpl->setVariable("CMD_UP", "cmd[up" . $this->getFieldId() . "][$i]"); - $tpl->setVariable("CMD_DOWN", "cmd[down" . $this->getFieldId() . "][$i]"); - $tpl->setVariable("ID", $this->getPostVar() . "[$i]"); - include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); - $tpl->setVariable("UP_BUTTON", ilGlyphGUI::get(ilGlyphGUI::UP)); - $tpl->setVariable("DOWN_BUTTON", ilGlyphGUI::get(ilGlyphGUI::DOWN)); - $tpl->parseCurrentBlock(); - } - - $tpl->setCurrentBlock("row"); - $tpl->setVariable("POST_VAR", $this->getPostVar()); - $tpl->setVariable("ROW_NUMBER", $i); - $tpl->setVariable("ID", $this->getPostVar() . "[answer][$i]"); - $tpl->setVariable("ID_LABEL", $this->getPostVar() . "[label][$i]"); - $tpl->setVariable("SIZE", $this->getSize()); - $tpl->setVariable("SIZE_LABEL", 15); - $tpl->setVariable("MAXLENGTH", $this->getMaxLength()); - if ($this->getDisabled()) - { - $tpl->setVariable("DISABLED", " disabled=\"disabled\""); - $tpl->setVariable("DISABLED_LABEL", " disabled=\"disabled\""); - } + if ($this->getAllowMove()) { + $tpl->setCurrentBlock("move"); + $tpl->setVariable("CMD_UP", "cmd[up" . $this->getFieldId() . "][$i]"); + $tpl->setVariable("CMD_DOWN", "cmd[down" . $this->getFieldId() . "][$i]"); + $tpl->setVariable("ID", $this->getPostVar() . "[$i]"); + include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); + $tpl->setVariable("UP_BUTTON", ilGlyphGUI::get(ilGlyphGUI::UP)); + $tpl->setVariable("DOWN_BUTTON", ilGlyphGUI::get(ilGlyphGUI::DOWN)); + $tpl->parseCurrentBlock(); + } + + $tpl->setCurrentBlock("row"); + $tpl->setVariable("POST_VAR", $this->getPostVar()); + $tpl->setVariable("ROW_NUMBER", $i); + $tpl->setVariable("ID", $this->getPostVar() . "[answer][$i]"); + $tpl->setVariable("ID_LABEL", $this->getPostVar() . "[label][$i]"); + $tpl->setVariable("SIZE", $this->getSize()); + $tpl->setVariable("SIZE_LABEL", 15); + $tpl->setVariable("MAXLENGTH", $this->getMaxLength()); + if ($this->getDisabled()) { + $tpl->setVariable("DISABLED", " disabled=\"disabled\""); + $tpl->setVariable("DISABLED_LABEL", " disabled=\"disabled\""); + } - $tpl->setVariable("CMD_ADD", "cmd[add" . $this->getFieldId() . "][$i]"); - $tpl->setVariable("CMD_REMOVE", "cmd[remove" . $this->getFieldId() . "][$i]"); - include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); - $tpl->setVariable("ADD_BUTTON", ilGlyphGUI::get(ilGlyphGUI::ADD)); - $tpl->setVariable("REMOVE_BUTTON", ilGlyphGUI::get(ilGlyphGUI::REMOVE)); - $tpl->parseCurrentBlock(); - } - } + $tpl->setVariable("CMD_ADD", "cmd[add" . $this->getFieldId() . "][$i]"); + $tpl->setVariable("CMD_REMOVE", "cmd[remove" . $this->getFieldId() . "][$i]"); + include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); + $tpl->setVariable("ADD_BUTTON", ilGlyphGUI::get(ilGlyphGUI::ADD)); + $tpl->setVariable("REMOVE_BUTTON", ilGlyphGUI::get(ilGlyphGUI::REMOVE)); + $tpl->parseCurrentBlock(); + } + } - if ($this->getShowWizard()) - { - $tpl->setCurrentBlock("wizard"); - $tpl->setVariable("CMD_WIZARD", 'cmd[wizard' . $this->getFieldId() . ']'); - $tpl->setVariable("WIZARD_BUTTON", ilUtil::getImagePath('wizard.svg')); - $tpl->setVariable("WIZARD_TEXT", $lng->txt('add_phrase')); - $tpl->parseCurrentBlock(); - } - - if ($this->getShowSavePhrase()) - { - $tpl->setCurrentBlock('savephrase'); - $tpl->setVariable("POST_VAR", $this->getPostVar()); - $tpl->setVariable("VALUE_SAVE_PHRASE", $lng->txt('save_phrase')); - $tpl->parseCurrentBlock(); - } - - if ($this->getUseOtherAnswer()) - { - $tpl->setCurrentBlock('other_answer_title'); - $tpl->setVariable("OTHER_TEXT", $lng->txt('use_other_answer')); - $tpl->parseCurrentBlock(); - } + if ($this->getShowWizard()) { + $tpl->setCurrentBlock("wizard"); + $tpl->setVariable("CMD_WIZARD", 'cmd[wizard' . $this->getFieldId() . ']'); + $tpl->setVariable("WIZARD_BUTTON", ilUtil::getImagePath('wizard.svg')); + $tpl->setVariable("WIZARD_TEXT", $lng->txt('add_phrase')); + $tpl->parseCurrentBlock(); + } + + if ($this->getShowSavePhrase()) { + $tpl->setCurrentBlock('savephrase'); + $tpl->setVariable("POST_VAR", $this->getPostVar()); + $tpl->setVariable("VALUE_SAVE_PHRASE", $lng->txt('save_phrase')); + $tpl->parseCurrentBlock(); + } + + if ($this->getUseOtherAnswer()) { + $tpl->setCurrentBlock('other_answer_title'); + $tpl->setVariable("OTHER_TEXT", $lng->txt('use_other_answer')); + $tpl->parseCurrentBlock(); + } - $tpl->setVariable("ELEMENT_ID", $this->getPostVar()); - $tpl->setVariable("ANSWER_TEXT", $this->getCategoryText()); - $tpl->setVariable("LABEL_TEXT", $this->getLabelText()); - $tpl->setVariable("ACTIONS_TEXT", $lng->txt('actions')); - - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $tpl->get()); - $a_tpl->parseCurrentBlock(); - - $tpl = $this->tpl; - $tpl->addJavascript("./Services/Form/js/ServiceFormWizardInput.js"); - $tpl->addJavascript("./Modules/SurveyQuestionPool/templates/default/matrixrowwizard.js"); - } + $tpl->setVariable("ELEMENT_ID", $this->getPostVar()); + $tpl->setVariable("ANSWER_TEXT", $this->getCategoryText()); + $tpl->setVariable("LABEL_TEXT", $this->getLabelText()); + $tpl->setVariable("ACTIONS_TEXT", $lng->txt('actions')); + + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $tpl->get()); + $a_tpl->parseCurrentBlock(); + + $tpl = $this->tpl; + $tpl->addJavascript("./Services/Form/js/ServiceFormWizardInput.js"); + $tpl->addJavascript("./Modules/SurveyQuestionPool/templates/default/matrixrowwizard.js"); + } } diff --git a/Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php b/Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php index 72d6a3211cb1ecc03e8b94f304ce22331e1e0166..71ed347daad6424a98301d5c2293f3fbc6a4e8ed 100755 --- a/Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php +++ b/Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php @@ -1,29 +1,29 @@ * @version $Id$ * @@ -35,1164 +35,1072 @@ include_once "./Services/Object/classes/class.ilObject.php"; class ilObjSurveyQuestionPool extends ilObject { - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilPluginAdmin - */ - protected $plugin_admin; - - /** - * Online status of questionpool - * - * @var string - */ - var $online; - - /** - * Constructor - * @access public - * @param integer reference_id or object_id - * @param boolean treat the id as reference_id (true) or object_id (false) - */ - function __construct($a_id = 0,$a_call_by_reference = true) - { - global $DIC; - - $this->log = $DIC["ilLog"]; - $this->db = $DIC->database(); - $this->user = $DIC->user(); - $this->plugin_admin = $DIC["ilPluginAdmin"]; - $this->type = "spl"; - parent::__construct($a_id,$a_call_by_reference); - } - - /** - * create question pool object - */ - function create($a_upload = false) - { - parent::create(); - if(!$a_upload) - { - $this->createMetaData(); - } - } - - /** - * update object data - * - * @access public - * @return boolean - */ - function update() - { - $this->updateMetaData(); - if (!parent::update()) - { - return false; - } - - // put here object specific stuff - - return true; - } - -/** - * read object data from db into object - * @access public - */ - public function read() - { - parent::read(); - $this->loadFromDb(); - } - - /** - * Creates a 1:1 copy of the object and places the copy in a given repository - * - * @access public - */ - function cloneObject($a_target_id,$a_copy_id = 0, $a_omit_tree = false) - { - $ilLog = $this->log; - $newObj = parent::cloneObject($a_target_id,$a_copy_id, $a_omit_tree); - - //copy online status if object is not the root copy object - $cp_options = ilCopyWizardOptions::_getInstance($a_copy_id); - - if(!$cp_options->isRootNode($this->getRefId())) - { - $newObj->setOnline($this->getOnline()); - } - - $newObj->saveToDb(); - // clone the questions in the question pool - $questions =& $this->getQuestions(); - foreach ($questions as $question_id) - { - $newObj->copyQuestion($question_id, $newObj->getId()); - } - - // clone meta data - include_once "./Services/MetaData/classes/class.ilMD.php"; - $md = new ilMD($this->getId(),0,$this->getType()); - $new_md =& $md->cloneMD($newObj->getId(),0,$newObj->getType()); - - // update the metadata with the new title of the question pool - $newObj->updateMetaData(); - return $newObj; - } - - function &createQuestion($question_type, $question_id = -1) - { - if ((!$question_type) and ($question_id > 0)) - { - $question_type = $this->getQuestiontype($question_id); - } - - include_once "./Modules/SurveyQuestionPool/classes/class.".$question_type."GUI.php"; - $question_type_gui = $question_type . "GUI"; - $question = new $question_type_gui(); - - if ($question_id > 0) - { - $question->object->loadFromDb($question_id); - } - - return $question; - } - - /** - * Copies a question into another question pool - * - * @param integer $question_id Database id of the question - * @param integer $questionpool_to Database id of the target questionpool - * @access public - */ - function copyQuestion($question_id, $questionpool_to) - { - $question_gui =& $this->createQuestion("", $question_id); - if ($question_gui->object->getObjId() == $questionpool_to) - { - // the question is copied into the same question pool - $this->duplicateQuestion($question_id); - } - else - { - // the question is copied into another question pool - $newtitle = $question_gui->object->getTitle(); - if ($question_gui->object->questionTitleExists($question_gui->object->getTitle(), $questionpool_to)) - { - $counter = 2; - while ($question_gui->object->questionTitleExists($question_gui->object->getTitle() . " ($counter)", $questionpool_to)) - { - $counter++; - } - $newtitle = $question_gui->object->getTitle() . " ($counter)"; - } - $question_gui->object->copyObject($this->getId(), $newtitle); - } - } - - /** - * Loads a ilObjQuestionpool object from a database - * - * @access public - */ - function loadFromDb() - { - $ilDB = $this->db; - - $result = $ilDB->queryF("SELECT * FROM svy_qpl WHERE obj_fi = %s", - array('integer'), - array($this->getId()) - ); - if ($result->numRows() == 1) - { - $row = $ilDB->fetchAssoc($result); - $this->setOnline($row["isonline"]); - } - } - -/** -* Saves a ilObjSurveyQuestionPool object to a database -* -* @access public -*/ - function saveToDb() - { - $ilDB = $this->db; - - parent::update(); - - $result = $ilDB->queryF("SELECT * FROM svy_qpl WHERE obj_fi = %s", - array('integer'), - array($this->getId()) - ); - if ($result->numRows() == 1) - { - $affectedRows = $ilDB->manipulateF("UPDATE svy_qpl SET isonline = %s, tstamp = %s WHERE obj_fi = %s", - array('text','integer','integer'), - array($this->getOnline(), time(), $this->getId()) - ); - } - else - { - $next_id = $ilDB->nextId('svy_qpl'); - $query = $ilDB->manipulateF("INSERT INTO svy_qpl (id_questionpool, isonline, obj_fi, tstamp) VALUES (%s, %s, %s, %s)", - array('integer', 'text', 'integer', 'integer'), - array($next_id, $this->getOnline(), $this->getId(), time()) - ); - } - } - - /** - * delete object and all related data - * - * @access public - * @return boolean true if all object data were removed; false if only a references were removed - */ - function delete() - { - $remove = parent::delete(); - // always call parent delete function first!! - if (!$remove) - { - return false; - } - - // delete all related questions - $this->deleteAllData(); - - // delete meta data - $this->deleteMetaData(); - - return true; - } - - function deleteAllData() - { - $ilDB = $this->db; - $result = $ilDB->queryF("SELECT question_id FROM svy_question WHERE obj_fi = %s AND original_id IS NULL", - array('integer'), - array($this->getId()) - ); - $found_questions = array(); - while ($row = $ilDB->fetchAssoc($result)) - { - $this->removeQuestion($row["question_id"]); - } - - // delete export files - $spl_data_dir = ilUtil::getDataDir()."/spl_data"; - $directory = $spl_data_dir."/spl_".$this->getId(); - if (is_dir($directory)) - { - ilUtil::delDir($directory); - } - } - -/** -* Removes a question from the question pool -* -* @param integer $question_id The database id of the question -* @access private -*/ - function removeQuestion($question_id) - { - if ($question_id < 1) return; - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - $question =& SurveyQuestion::_instanciateQuestion($question_id); - $question->delete($question_id); - } - - /** - * 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 -*/ - function getQuestiontype($question_id) - { - $ilDB = $this->db; - if ($question_id < 1) return; - $result = $ilDB->queryF("SELECT svy_qtype.type_tag FROM svy_question, svy_qtype WHERE svy_question.questiontype_fi = svy_qtype.questiontype_id AND svy_question.question_id = %s", - array('integer'), - array($question_id) - ); - if ($result->numRows() == 1) - { - $data = $ilDB->fetchAssoc($result); - return $data["type_tag"]; - } - else - { - return; - } - } - -/** -* Checks if a question is in use by a survey -* -* @param integer $question_id The database id of the question -* @result mixed An array of the surveys which use the question, when the question is in use by at least one survey, otherwise false -* @access public -*/ - function isInUse($question_id) - { - $ilDB = $this->db; - // check out the already answered questions - $result = $ilDB->queryF("SELECT answer_id FROM svy_answer WHERE question_fi = %s", - array('integer'), - array($question_id) - ); - $answered = $result->numRows(); - - // check out the questions inserted in surveys - $result = $ilDB->queryF("SELECT svy_svy.* FROM svy_svy, svy_svy_qst WHERE svy_svy_qst.survey_fi = svy_svy.survey_id AND svy_svy_qst.question_fi = %s", - array('integer'), - array($question_id) - ); - $inserted = $result->numRows(); - if (($inserted + $answered) == 0) - { - return false; - } - $result_array = array(); - while ($row = $ilDB->fetchObject($result)) - { - array_push($result_array, $row); - } - return $result_array; - } - -/** -* Pastes a question in the question pool -* -* @param integer $question_id The database id of the question -* @access public -*/ - function paste($question_id) - { - $this->duplicateQuestion($question_id, $this->getId()); - } - -/** -* Retrieves the datase entries for questions from a given array -* -* @param array $question_array An array containing the id's of the questions -* @result array An array containing the database rows of the given question id's -* @access public + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilPluginAdmin + */ + protected $plugin_admin; + + /** + * Online status of questionpool + * + * @var string + */ + public $online; + + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + global $DIC; + + $this->log = $DIC["ilLog"]; + $this->db = $DIC->database(); + $this->user = $DIC->user(); + $this->plugin_admin = $DIC["ilPluginAdmin"]; + $this->type = "spl"; + parent::__construct($a_id, $a_call_by_reference); + } + + /** + * create question pool object + */ + public function create($a_upload = false) + { + parent::create(); + if (!$a_upload) { + $this->createMetaData(); + } + } + + /** + * update object data + * + * @access public + * @return boolean + */ + public function update() + { + $this->updateMetaData(); + if (!parent::update()) { + return false; + } + + // put here object specific stuff + + return true; + } + + /** + * read object data from db into object + * @access public + */ + public function read() + { + parent::read(); + $this->loadFromDb(); + } + + /** + * Creates a 1:1 copy of the object and places the copy in a given repository + * + * @access public + */ + public function cloneObject($a_target_id, $a_copy_id = 0, $a_omit_tree = false) + { + $ilLog = $this->log; + $newObj = parent::cloneObject($a_target_id, $a_copy_id, $a_omit_tree); + + //copy online status if object is not the root copy object + $cp_options = ilCopyWizardOptions::_getInstance($a_copy_id); + + if (!$cp_options->isRootNode($this->getRefId())) { + $newObj->setOnline($this->getOnline()); + } + + $newObj->saveToDb(); + // clone the questions in the question pool + $questions =&$this->getQuestions(); + foreach ($questions as $question_id) { + $newObj->copyQuestion($question_id, $newObj->getId()); + } + + // clone meta data + include_once "./Services/MetaData/classes/class.ilMD.php"; + $md = new ilMD($this->getId(), 0, $this->getType()); + $new_md =&$md->cloneMD($newObj->getId(), 0, $newObj->getType()); + + // update the metadata with the new title of the question pool + $newObj->updateMetaData(); + return $newObj; + } + + public function &createQuestion($question_type, $question_id = -1) + { + if ((!$question_type) and ($question_id > 0)) { + $question_type = $this->getQuestiontype($question_id); + } + + include_once "./Modules/SurveyQuestionPool/classes/class." . $question_type . "GUI.php"; + $question_type_gui = $question_type . "GUI"; + $question = new $question_type_gui(); + + if ($question_id > 0) { + $question->object->loadFromDb($question_id); + } + + return $question; + } + + /** + * Copies a question into another question pool + * + * @param integer $question_id Database id of the question + * @param integer $questionpool_to Database id of the target questionpool + * @access public + */ + public function copyQuestion($question_id, $questionpool_to) + { + $question_gui =&$this->createQuestion("", $question_id); + if ($question_gui->object->getObjId() == $questionpool_to) { + // the question is copied into the same question pool + $this->duplicateQuestion($question_id); + } else { + // the question is copied into another question pool + $newtitle = $question_gui->object->getTitle(); + if ($question_gui->object->questionTitleExists($question_gui->object->getTitle(), $questionpool_to)) { + $counter = 2; + while ($question_gui->object->questionTitleExists($question_gui->object->getTitle() . " ($counter)", $questionpool_to)) { + $counter++; + } + $newtitle = $question_gui->object->getTitle() . " ($counter)"; + } + $question_gui->object->copyObject($this->getId(), $newtitle); + } + } + + /** + * Loads a ilObjQuestionpool object from a database + * + * @access public + */ + public function loadFromDb() + { + $ilDB = $this->db; + + $result = $ilDB->queryF( + "SELECT * FROM svy_qpl WHERE obj_fi = %s", + array('integer'), + array($this->getId()) + ); + if ($result->numRows() == 1) { + $row = $ilDB->fetchAssoc($result); + $this->setOnline($row["isonline"]); + } + } + + /** + * Saves a ilObjSurveyQuestionPool object to a database + * + * @access public + */ + public function saveToDb() + { + $ilDB = $this->db; + + parent::update(); + + $result = $ilDB->queryF( + "SELECT * FROM svy_qpl WHERE obj_fi = %s", + array('integer'), + array($this->getId()) + ); + if ($result->numRows() == 1) { + $affectedRows = $ilDB->manipulateF( + "UPDATE svy_qpl SET isonline = %s, tstamp = %s WHERE obj_fi = %s", + array('text','integer','integer'), + array($this->getOnline(), time(), $this->getId()) + ); + } else { + $next_id = $ilDB->nextId('svy_qpl'); + $query = $ilDB->manipulateF( + "INSERT INTO svy_qpl (id_questionpool, isonline, obj_fi, tstamp) VALUES (%s, %s, %s, %s)", + array('integer', 'text', 'integer', 'integer'), + array($next_id, $this->getOnline(), $this->getId(), time()) + ); + } + } + + /** + * delete object and all related data + * + * @access public + * @return boolean true if all object data were removed; false if only a references were removed + */ + public function delete() + { + $remove = parent::delete(); + // always call parent delete function first!! + if (!$remove) { + return false; + } + + // delete all related questions + $this->deleteAllData(); + + // delete meta data + $this->deleteMetaData(); + + return true; + } + + public function deleteAllData() + { + $ilDB = $this->db; + $result = $ilDB->queryF( + "SELECT question_id FROM svy_question WHERE obj_fi = %s AND original_id IS NULL", + array('integer'), + array($this->getId()) + ); + $found_questions = array(); + while ($row = $ilDB->fetchAssoc($result)) { + $this->removeQuestion($row["question_id"]); + } + + // delete export files + $spl_data_dir = ilUtil::getDataDir() . "/spl_data"; + $directory = $spl_data_dir . "/spl_" . $this->getId(); + if (is_dir($directory)) { + ilUtil::delDir($directory); + } + } + + /** + * Removes a question from the question pool + * + * @param integer $question_id The database id of the question + * @access private + */ + public function removeQuestion($question_id) + { + if ($question_id < 1) { + return; + } + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + $question =&SurveyQuestion::_instanciateQuestion($question_id); + $question->delete($question_id); + } + + /** + * 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 */ - function &getQuestionsInfo($question_array) - { - $ilDB = $this->db; - $result_array = array(); - $result = $ilDB->query("SELECT svy_question.*, svy_qtype.type_tag, svy_qtype.plugin FROM svy_question, svy_qtype WHERE svy_question.questiontype_fi = svy_qtype.questiontype_id AND svy_question.tstamp > 0 AND " . $ilDB->in('svy_question.question_id', $question_array, false, 'integer')); - while ($row = $ilDB->fetchAssoc($result)) - { - if ($row["plugin"]) - { - if ($this->isPluginActive($row["type_tag"])) - { - array_push($result_array, $row); - } - } - else - { - array_push($result_array, $row); - } - } - return $result_array; - } - - /** - * Duplicates a question for a questionpool - * - * @param integer $question_id The database id of the question - * @access public - */ - function duplicateQuestion($question_id, $obj_id = "") - { - $ilUser = $this->user; - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - $question = SurveyQuestion::_instanciateQuestion($question_id); - $suffix = ""; - $counter = 1; - while ($question->questionTitleExists($question->getTitle().$suffix, $obj_id)) - { - $counter++; - if ($counter > 1) $suffix = " ($counter)"; - } - if ($obj_id) - { - $question->setObjId($obj_id); - } - $question->duplicate(false, $question->getTitle() . $suffix, $ilUser->fullname, $ilUser->id); - } - - /** - * Calculates the data for the output of the questionpool - * - * @access public - */ - function getQuestionsData($arrFilter) - { - $ilUser = $this->user; - $ilDB = $this->db; - $where = ""; - if (is_array($arrFilter)) - { - foreach ($arrFilter as $key => $value) - { - $arrFilter[$key] = str_replace('%', '', $arrFilter[$key]); - } - if (array_key_exists('title', $arrFilter) && strlen($arrFilter['title'])) - { - $where .= " AND " . $ilDB->like('svy_question.title', 'text', "%%" . $arrFilter['title'] . "%%"); - } - if (array_key_exists('description', $arrFilter) && strlen($arrFilter['description'])) - { - $where .= " AND " . $ilDB->like('svy_question.description', 'text', "%%" . $arrFilter['description'] . "%%"); - } - if (array_key_exists('author', $arrFilter) && strlen($arrFilter['author'])) - { - $where .= " AND " . $ilDB->like('svy_question.author', 'text', "%%" . $arrFilter['author'] . "%%"); - } - if (array_key_exists('type', $arrFilter) && strlen($arrFilter['type'])) - { - $where .= " AND svy_qtype.type_tag = " . $ilDB->quote($arrFilter['type'], 'text'); - } - } - $query_result = $ilDB->queryF("SELECT svy_question.*, svy_qtype.type_tag, svy_qtype.plugin FROM svy_question, svy_qtype WHERE svy_question.original_id IS NULL AND svy_question.tstamp > 0 AND svy_question.questiontype_fi = svy_qtype.questiontype_id AND svy_question.obj_fi = %s" . $where, - array('integer'), - array($this->getId()) - ); - $rows = array(); - if ($query_result->numRows()) - { - while ($row = $ilDB->fetchAssoc($query_result)) - { - if ($row["plugin"]) - { - if ($this->isPluginActive($row["type_tag"])) - { - array_push($rows, $row); - } - } - else - { - array_push($rows, $row); - } - } - } - return $rows; - } - - /** - * creates data directory for export files - * (data_dir/spl_data/spl_/export, depending on data - * directory that is set in ILIAS setup/ini) - * - * @throws ilSurveyException - */ - function createExportDirectory() - { - $spl_data_dir = ilUtil::getDataDir()."/spl_data"; - ilUtil::makeDir($spl_data_dir); - if(!is_writable($spl_data_dir)) - { - include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; - throw new ilSurveyException("Survey Questionpool Data Directory (".$spl_data_dir.") not writeable."); - } - - // create learning module directory (data_dir/lm_data/lm_) - $spl_dir = $spl_data_dir."/spl_".$this->getId(); - ilUtil::makeDir($spl_dir); - if(!@is_dir($spl_dir)) - { - include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; - throw new ilSurveyException("Creation of Survey Questionpool Directory failed."); - } - // create Export subdirectory (data_dir/lm_data/lm_/Export) - $export_dir = $spl_dir."/export"; - ilUtil::makeDir($export_dir); - if(!@is_dir($export_dir)) - { - include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; - throw new ilSurveyException("Creation of Survey Questionpool Export Directory failed."); - } - } - - /** - * get export directory of survey - */ - function getExportDirectory() - { - $export_dir = ilUtil::getDataDir()."/spl_data"."/spl_".$this->getId()."/export"; - return $export_dir; - } - - /** - * get export files - */ - function getExportFiles($dir) - { - // quit if import dir not available - if (!@is_dir($dir) or - !is_writeable($dir)) - { - return array(); - } - - // open directory - $dir = dir($dir); - - // initialize array - $file = array(); - - // get files and save the in the array - while ($entry = $dir->read()) - { - if ($entry != "." && - $entry != ".." && - preg_match("/^[0-9]{10}__[0-9]+__(spl_)*[0-9]+\.[A-Za-z]{3}$/", $entry)) - { - $file[] = $entry; - } - } - - // close import directory - $dir->close(); - // sort files - sort ($file); - reset ($file); - - return $file; - } - - /** - * creates data directory for import files - * (data_dir/spl_data/spl_/import, depending on data - * directory that is set in ILIAS setup/ini) - * - * @throws ilSurveyException - */ - function createImportDirectory() - { - $spl_data_dir = ilUtil::getDataDir()."/spl_data"; - ilUtil::makeDir($spl_data_dir); - - if(!is_writable($spl_data_dir)) - { - include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; - throw new ilSurveyException("Survey Questionpool Data Directory (".$spl_data_dir.") not writeable."); - } - - // create test directory (data_dir/spl_data/spl_) - $spl_dir = $spl_data_dir."/spl_".$this->getId(); - ilUtil::makeDir($spl_dir); - if(!@is_dir($spl_dir)) - { - include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; - throw new ilSurveyException("Creation of Survey Questionpool Directory failed."); - } - - // create import subdirectory (data_dir/spl_data/spl_/import) - $import_dir = $spl_dir."/import"; - ilUtil::makeDir($import_dir); - if(!@is_dir($import_dir)) - { - include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; - throw new ilSurveyException("Creation of Survey Questionpool Import Directory failed."); - } - } - - /** - * get import directory of survey - */ - function getImportDirectory() - { - $import_dir = ilUtil::getDataDir()."/spl_data". - "/spl_".$this->getId()."/import"; - if(@is_dir($import_dir)) - { - return $import_dir; - } - else - { - return false; - } - } - - /** - * export questions to xml - */ - function toXML($questions) - { - if (!is_array($questions)) - { - $questions =& $this->getQuestions(); - } - if (count($questions) == 0) - { - $questions =& $this->getQuestions(); - } - $xml = ""; - - include_once("./Services/Xml/classes/class.ilXmlWriter.php"); - $a_xml_writer = new ilXmlWriter; - // set xml header - $a_xml_writer->xmlHeader(); - $attrs = array( - "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance", - "xsi:noNamespaceSchemaLocation" => "http://www.ilias.de/download/xsd/ilias_survey_4_2.xsd" - ); - $a_xml_writer->xmlStartTag("surveyobject", $attrs); - $attrs = array( - "id" => "qpl_" . $this->getId(), - "label" => $this->getTitle(), - "online" => $this->getOnline() - ); - $a_xml_writer->xmlStartTag("surveyquestions", $attrs); - $a_xml_writer->xmlElement("dummy", NULL, "dummy"); - // add ILIAS specific metadata - $a_xml_writer->xmlStartTag("metadata"); - $a_xml_writer->xmlStartTag("metadatafield"); - $a_xml_writer->xmlElement("fieldlabel", NULL, "SCORM"); - include_once "./Services/MetaData/classes/class.ilMD.php"; - $md = new ilMD($this->getId(),0, $this->getType()); - $writer = new ilXmlWriter(); - $md->toXml($writer); - $metadata = $writer->xmlDumpMem(); - $a_xml_writer->xmlElement("fieldentry", NULL, $metadata); - $a_xml_writer->xmlEndTag("metadatafield"); - $a_xml_writer->xmlEndTag("metadata"); - - $a_xml_writer->xmlEndTag("surveyquestions"); - $a_xml_writer->xmlEndTag("surveyobject"); - - $xml = $a_xml_writer->xmlDumpMem(FALSE); - - $questionxml = ""; - foreach ($questions as $key => $value) - { - $questiontype = $this->getQuestiontype($value); - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - SurveyQuestion::_includeClass($questiontype); - $question = new $questiontype(); - $question->loadFromDb($value); - $questionxml .= $question->toXML(false); - } - - $xml = str_replace("dummy", $questionxml, $xml); - return $xml; - } - - function &getQuestions() - { - $ilDB = $this->db; - $questions = array(); - $result = $ilDB->queryF("SELECT question_id FROM svy_question WHERE obj_fi = %s AND svy_question.tstamp > 0 AND original_id IS NULL", - array('integer'), - array($this->getId()) - ); - if ($result->numRows()) - { - while ($row = $ilDB->fetchAssoc($result)) - { - array_push($questions, $row["question_id"]); - } - } - return $questions; - } - - /** - * Imports survey questions into ILIAS - * - * @param string $source The filename of an XML import file - * @access public - */ - function importObject($source, $spl_exists = FALSE) - { - if (is_file($source)) - { - $isZip = (strcmp(strtolower(substr($source, -3)), 'zip') == 0); - if ($isZip) - { - // unzip file - ilUtil::unzip($source); - - // determine filenames of xml files - $subdir = basename($source, ".zip"); - $source = dirname($source)."/".$subdir."/".$subdir.".xml"; - } - - $fh = fopen($source, "r") or die(""); - $xml = fread($fh, filesize($source)); - fclose($fh) or die(""); - if ($isZip) - { - $subdir = basename($source, ".zip"); - if (@is_dir(dirname($source)."/".$subdir)) - { - ilUtil::delDir(dirname($source)."/".$subdir); - } - } - if (strpos($xml, "questestinterop") > 0) - { - include_once("./Modules/Survey/exceptions/class.ilInvalidSurveyImportFileException.php"); - throw new ilInvalidSurveyImportFileException("Unsupported survey version (< 3.8) found."); - } - else - { - // survey questions for ILIAS >= 3.8 - include_once "./Services/Survey/classes/class.SurveyImportParser.php"; - $import = new SurveyImportParser($this->getId(), "", $spl_exists); - $import->setXMLContent($xml); - $import->startParsing(); - } - } - } - - public static function _setOnline($a_obj_id, $a_online_status) - { - global $DIC; - - $ilDB = $DIC->database(); - - $status = "0"; - switch ($a_online_status) - { - case 0: - case 1: - $status = "$a_online_status"; - break; - } - $affectedRows = $ilDB->manipulateF("UPDATE svy_qpl SET isonline = %s WHERE obj_fi = %s", - array('text','integer'), - array($status, $a_obj_id) - ); - } - - /** - * Sets the questionpool online status - * - * @param integer $a_online_status Online status of the questionpool - * @see online - * @access public - */ - function setOnline($a_online_status) - { - switch ($a_online_status) - { - case 0: - case 1: - $this->online = $a_online_status; - break; - default: - $this->online = 0; - break; - } - } - - function getOnline() - { - if (strcmp($this->online, "") == 0) $this->online = "0"; - return $this->online; - } - - static function _lookupOnline($a_obj_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $result = $ilDB->queryF("SELECT isonline FROM svy_qpl WHERE obj_fi = %s", - array('integer'), - array($a_obj_id) - ); - if ($result->numRows() == 1) - { - $row = $ilDB->fetchAssoc($result); - return $row["isonline"]; - } - return 0; - } - - /** - * Returns true, if the question pool is writeable by a given user - * - * @param integer $object_id The object id of the question pool - * @param integer $user_id The database id of the user - * @access public - */ - static function _isWriteable($object_id, $user_id) - { - global $DIC; - - $rbacsystem = $DIC->rbac()->system(); - global $DIC; - - $ilDB = $DIC->database(); - - $refs = ilObject::_getAllReferences($object_id); - $result = false; - foreach ($refs as $ref) - { - if ($rbacsystem->checkAccess("write", $ref) && (ilObject::_hasUntrashedReference($object_id))) - { - $result = true; - } - } - return $result; - } - - /** - * Creates a list of all available question types - * - * @return array An array containing the available questiontypes - * @access public - */ - static function _getQuestiontypes() - { - global $DIC; - - $ilDB = $DIC->database(); - global $DIC; - - $lng = $DIC->language(); - - $lng->loadLanguageModule("survey"); - $types = array(); - $query_result = $ilDB->query("SELECT * FROM svy_qtype ORDER BY type_tag"); - while ($row = $ilDB->fetchAssoc($query_result)) - { - //array_push($questiontypes, $row["type_tag"]); - if ($row["plugin"] == 0) - { - $types[$lng->txt($row["type_tag"])] = $row; - } - 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(), $row["type_tag"]) == 0) - { - $types[$pl->getQuestionTypeTranslation()] = $row; - } - } - } - } - ksort($types); - - - // #14263 - default sorting - - $default_sorting = array_flip(array( - "SurveySingleChoiceQuestion", - "SurveyMultipleChoiceQuestion", - "SurveyMatrixQuestion", - "SurveyMetricQuestion", - "SurveyTextQuestion" - )); + public function getQuestiontype($question_id) + { + $ilDB = $this->db; + if ($question_id < 1) { + return; + } + $result = $ilDB->queryF( + "SELECT svy_qtype.type_tag FROM svy_question, svy_qtype WHERE svy_question.questiontype_fi = svy_qtype.questiontype_id AND svy_question.question_id = %s", + array('integer'), + array($question_id) + ); + if ($result->numRows() == 1) { + $data = $ilDB->fetchAssoc($result); + return $data["type_tag"]; + } else { + return; + } + } + + /** + * Checks if a question is in use by a survey + * + * @param integer $question_id The database id of the question + * @result mixed An array of the surveys which use the question, when the question is in use by at least one survey, otherwise false + * @access public + */ + public function isInUse($question_id) + { + $ilDB = $this->db; + // check out the already answered questions + $result = $ilDB->queryF( + "SELECT answer_id FROM svy_answer WHERE question_fi = %s", + array('integer'), + array($question_id) + ); + $answered = $result->numRows(); + + // check out the questions inserted in surveys + $result = $ilDB->queryF( + "SELECT svy_svy.* FROM svy_svy, svy_svy_qst WHERE svy_svy_qst.survey_fi = svy_svy.survey_id AND svy_svy_qst.question_fi = %s", + array('integer'), + array($question_id) + ); + $inserted = $result->numRows(); + if (($inserted + $answered) == 0) { + return false; + } + $result_array = array(); + while ($row = $ilDB->fetchObject($result)) { + array_push($result_array, $row); + } + return $result_array; + } + + /** + * Pastes a question in the question pool + * + * @param integer $question_id The database id of the question + * @access public + */ + public function paste($question_id) + { + $this->duplicateQuestion($question_id, $this->getId()); + } + + /** + * Retrieves the datase entries for questions from a given array + * + * @param array $question_array An array containing the id's of the questions + * @result array An array containing the database rows of the given question id's + * @access public + */ + public function &getQuestionsInfo($question_array) + { + $ilDB = $this->db; + $result_array = array(); + $result = $ilDB->query("SELECT svy_question.*, svy_qtype.type_tag, svy_qtype.plugin FROM svy_question, svy_qtype WHERE svy_question.questiontype_fi = svy_qtype.questiontype_id AND svy_question.tstamp > 0 AND " . $ilDB->in('svy_question.question_id', $question_array, false, 'integer')); + while ($row = $ilDB->fetchAssoc($result)) { + if ($row["plugin"]) { + if ($this->isPluginActive($row["type_tag"])) { + array_push($result_array, $row); + } + } else { + array_push($result_array, $row); + } + } + return $result_array; + } + + /** + * Duplicates a question for a questionpool + * + * @param integer $question_id The database id of the question + * @access public + */ + public function duplicateQuestion($question_id, $obj_id = "") + { + $ilUser = $this->user; + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + $question = SurveyQuestion::_instanciateQuestion($question_id); + $suffix = ""; + $counter = 1; + while ($question->questionTitleExists($question->getTitle() . $suffix, $obj_id)) { + $counter++; + if ($counter > 1) { + $suffix = " ($counter)"; + } + } + if ($obj_id) { + $question->setObjId($obj_id); + } + $question->duplicate(false, $question->getTitle() . $suffix, $ilUser->fullname, $ilUser->id); + } + + /** + * Calculates the data for the output of the questionpool + * + * @access public + */ + public function getQuestionsData($arrFilter) + { + $ilUser = $this->user; + $ilDB = $this->db; + $where = ""; + if (is_array($arrFilter)) { + foreach ($arrFilter as $key => $value) { + $arrFilter[$key] = str_replace('%', '', $arrFilter[$key]); + } + if (array_key_exists('title', $arrFilter) && strlen($arrFilter['title'])) { + $where .= " AND " . $ilDB->like('svy_question.title', 'text', "%%" . $arrFilter['title'] . "%%"); + } + if (array_key_exists('description', $arrFilter) && strlen($arrFilter['description'])) { + $where .= " AND " . $ilDB->like('svy_question.description', 'text', "%%" . $arrFilter['description'] . "%%"); + } + if (array_key_exists('author', $arrFilter) && strlen($arrFilter['author'])) { + $where .= " AND " . $ilDB->like('svy_question.author', 'text', "%%" . $arrFilter['author'] . "%%"); + } + if (array_key_exists('type', $arrFilter) && strlen($arrFilter['type'])) { + $where .= " AND svy_qtype.type_tag = " . $ilDB->quote($arrFilter['type'], 'text'); + } + } + $query_result = $ilDB->queryF( + "SELECT svy_question.*, svy_qtype.type_tag, svy_qtype.plugin FROM svy_question, svy_qtype WHERE svy_question.original_id IS NULL AND svy_question.tstamp > 0 AND svy_question.questiontype_fi = svy_qtype.questiontype_id AND svy_question.obj_fi = %s" . $where, + array('integer'), + array($this->getId()) + ); + $rows = array(); + if ($query_result->numRows()) { + while ($row = $ilDB->fetchAssoc($query_result)) { + if ($row["plugin"]) { + if ($this->isPluginActive($row["type_tag"])) { + array_push($rows, $row); + } + } else { + array_push($rows, $row); + } + } + } + return $rows; + } + + /** + * creates data directory for export files + * (data_dir/spl_data/spl_/export, depending on data + * directory that is set in ILIAS setup/ini) + * + * @throws ilSurveyException + */ + public function createExportDirectory() + { + $spl_data_dir = ilUtil::getDataDir() . "/spl_data"; + ilUtil::makeDir($spl_data_dir); + if (!is_writable($spl_data_dir)) { + include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; + throw new ilSurveyException("Survey Questionpool Data Directory (" . $spl_data_dir . ") not writeable."); + } + + // create learning module directory (data_dir/lm_data/lm_) + $spl_dir = $spl_data_dir . "/spl_" . $this->getId(); + ilUtil::makeDir($spl_dir); + if (!@is_dir($spl_dir)) { + include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; + throw new ilSurveyException("Creation of Survey Questionpool Directory failed."); + } + // create Export subdirectory (data_dir/lm_data/lm_/Export) + $export_dir = $spl_dir . "/export"; + ilUtil::makeDir($export_dir); + if (!@is_dir($export_dir)) { + include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; + throw new ilSurveyException("Creation of Survey Questionpool Export Directory failed."); + } + } + + /** + * get export directory of survey + */ + public function getExportDirectory() + { + $export_dir = ilUtil::getDataDir() . "/spl_data" . "/spl_" . $this->getId() . "/export"; + return $export_dir; + } + + /** + * get export files + */ + public function getExportFiles($dir) + { + // quit if import dir not available + if (!@is_dir($dir) or + !is_writeable($dir)) { + return array(); + } + + // open directory + $dir = dir($dir); + + // initialize array + $file = array(); + + // get files and save the in the array + while ($entry = $dir->read()) { + if ($entry != "." && + $entry != ".." && + preg_match("/^[0-9]{10}__[0-9]+__(spl_)*[0-9]+\.[A-Za-z]{3}$/", $entry)) { + $file[] = $entry; + } + } + + // close import directory + $dir->close(); + // sort files + sort($file); + reset($file); + + return $file; + } + + /** + * creates data directory for import files + * (data_dir/spl_data/spl_/import, depending on data + * directory that is set in ILIAS setup/ini) + * + * @throws ilSurveyException + */ + public function createImportDirectory() + { + $spl_data_dir = ilUtil::getDataDir() . "/spl_data"; + ilUtil::makeDir($spl_data_dir); + + if (!is_writable($spl_data_dir)) { + include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; + throw new ilSurveyException("Survey Questionpool Data Directory (" . $spl_data_dir . ") not writeable."); + } + + // create test directory (data_dir/spl_data/spl_) + $spl_dir = $spl_data_dir . "/spl_" . $this->getId(); + ilUtil::makeDir($spl_dir); + if (!@is_dir($spl_dir)) { + include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; + throw new ilSurveyException("Creation of Survey Questionpool Directory failed."); + } + + // create import subdirectory (data_dir/spl_data/spl_/import) + $import_dir = $spl_dir . "/import"; + ilUtil::makeDir($import_dir); + if (!@is_dir($import_dir)) { + include_once "Modules/Survey/exceptions/class.ilSurveyException.php"; + throw new ilSurveyException("Creation of Survey Questionpool Import Directory failed."); + } + } + + /** + * get import directory of survey + */ + public function getImportDirectory() + { + $import_dir = ilUtil::getDataDir() . "/spl_data" . + "/spl_" . $this->getId() . "/import"; + if (@is_dir($import_dir)) { + return $import_dir; + } else { + return false; + } + } + + /** + * export questions to xml + */ + public function toXML($questions) + { + if (!is_array($questions)) { + $questions =&$this->getQuestions(); + } + if (count($questions) == 0) { + $questions =&$this->getQuestions(); + } + $xml = ""; + + include_once("./Services/Xml/classes/class.ilXmlWriter.php"); + $a_xml_writer = new ilXmlWriter; + // set xml header + $a_xml_writer->xmlHeader(); + $attrs = array( + "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance", + "xsi:noNamespaceSchemaLocation" => "http://www.ilias.de/download/xsd/ilias_survey_4_2.xsd" + ); + $a_xml_writer->xmlStartTag("surveyobject", $attrs); + $attrs = array( + "id" => "qpl_" . $this->getId(), + "label" => $this->getTitle(), + "online" => $this->getOnline() + ); + $a_xml_writer->xmlStartTag("surveyquestions", $attrs); + $a_xml_writer->xmlElement("dummy", null, "dummy"); + // add ILIAS specific metadata + $a_xml_writer->xmlStartTag("metadata"); + $a_xml_writer->xmlStartTag("metadatafield"); + $a_xml_writer->xmlElement("fieldlabel", null, "SCORM"); + include_once "./Services/MetaData/classes/class.ilMD.php"; + $md = new ilMD($this->getId(), 0, $this->getType()); + $writer = new ilXmlWriter(); + $md->toXml($writer); + $metadata = $writer->xmlDumpMem(); + $a_xml_writer->xmlElement("fieldentry", null, $metadata); + $a_xml_writer->xmlEndTag("metadatafield"); + $a_xml_writer->xmlEndTag("metadata"); + + $a_xml_writer->xmlEndTag("surveyquestions"); + $a_xml_writer->xmlEndTag("surveyobject"); + + $xml = $a_xml_writer->xmlDumpMem(false); + + $questionxml = ""; + foreach ($questions as $key => $value) { + $questiontype = $this->getQuestiontype($value); + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + SurveyQuestion::_includeClass($questiontype); + $question = new $questiontype(); + $question->loadFromDb($value); + $questionxml .= $question->toXML(false); + } + + $xml = str_replace("dummy", $questionxml, $xml); + return $xml; + } + + public function &getQuestions() + { + $ilDB = $this->db; + $questions = array(); + $result = $ilDB->queryF( + "SELECT question_id FROM svy_question WHERE obj_fi = %s AND svy_question.tstamp > 0 AND original_id IS NULL", + array('integer'), + array($this->getId()) + ); + if ($result->numRows()) { + while ($row = $ilDB->fetchAssoc($result)) { + array_push($questions, $row["question_id"]); + } + } + return $questions; + } + + /** + * Imports survey questions into ILIAS + * + * @param string $source The filename of an XML import file + * @access public + */ + public function importObject($source, $spl_exists = false) + { + if (is_file($source)) { + $isZip = (strcmp(strtolower(substr($source, -3)), 'zip') == 0); + if ($isZip) { + // unzip file + ilUtil::unzip($source); + + // determine filenames of xml files + $subdir = basename($source, ".zip"); + $source = dirname($source) . "/" . $subdir . "/" . $subdir . ".xml"; + } + + $fh = fopen($source, "r") or die(""); + $xml = fread($fh, filesize($source)); + fclose($fh) or die(""); + if ($isZip) { + $subdir = basename($source, ".zip"); + if (@is_dir(dirname($source) . "/" . $subdir)) { + ilUtil::delDir(dirname($source) . "/" . $subdir); + } + } + if (strpos($xml, "questestinterop") > 0) { + include_once("./Modules/Survey/exceptions/class.ilInvalidSurveyImportFileException.php"); + throw new ilInvalidSurveyImportFileException("Unsupported survey version (< 3.8) found."); + } else { + // survey questions for ILIAS >= 3.8 + include_once "./Services/Survey/classes/class.SurveyImportParser.php"; + $import = new SurveyImportParser($this->getId(), "", $spl_exists); + $import->setXMLContent($xml); + $import->startParsing(); + } + } + } + + public static function _setOnline($a_obj_id, $a_online_status) + { + global $DIC; + + $ilDB = $DIC->database(); + + $status = "0"; + switch ($a_online_status) { + case 0: + case 1: + $status = "$a_online_status"; + break; + } + $affectedRows = $ilDB->manipulateF( + "UPDATE svy_qpl SET isonline = %s WHERE obj_fi = %s", + array('text','integer'), + array($status, $a_obj_id) + ); + } + + /** + * Sets the questionpool online status + * + * @param integer $a_online_status Online status of the questionpool + * @see online + * @access public + */ + public function setOnline($a_online_status) + { + switch ($a_online_status) { + case 0: + case 1: + $this->online = $a_online_status; + break; + default: + $this->online = 0; + break; + } + } + + public function getOnline() + { + if (strcmp($this->online, "") == 0) { + $this->online = "0"; + } + return $this->online; + } + + public static function _lookupOnline($a_obj_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $result = $ilDB->queryF( + "SELECT isonline FROM svy_qpl WHERE obj_fi = %s", + array('integer'), + array($a_obj_id) + ); + if ($result->numRows() == 1) { + $row = $ilDB->fetchAssoc($result); + return $row["isonline"]; + } + return 0; + } + + /** + * Returns true, if the question pool is writeable by a given user + * + * @param integer $object_id The object id of the question pool + * @param integer $user_id The database id of the user + * @access public + */ + public static function _isWriteable($object_id, $user_id) + { + global $DIC; + + $rbacsystem = $DIC->rbac()->system(); + global $DIC; + + $ilDB = $DIC->database(); + + $refs = ilObject::_getAllReferences($object_id); + $result = false; + foreach ($refs as $ref) { + if ($rbacsystem->checkAccess("write", $ref) && (ilObject::_hasUntrashedReference($object_id))) { + $result = true; + } + } + return $result; + } + + /** + * Creates a list of all available question types + * + * @return array An array containing the available questiontypes + * @access public + */ + public static function _getQuestiontypes() + { + global $DIC; + + $ilDB = $DIC->database(); + global $DIC; + + $lng = $DIC->language(); + + $lng->loadLanguageModule("survey"); + $types = array(); + $query_result = $ilDB->query("SELECT * FROM svy_qtype ORDER BY type_tag"); + while ($row = $ilDB->fetchAssoc($query_result)) { + //array_push($questiontypes, $row["type_tag"]); + if ($row["plugin"] == 0) { + $types[$lng->txt($row["type_tag"])] = $row; + } 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(), $row["type_tag"]) == 0) { + $types[$pl->getQuestionTypeTranslation()] = $row; + } + } + } + } + ksort($types); + + + // #14263 - default sorting + + $default_sorting = array_flip(array( + "SurveySingleChoiceQuestion", + "SurveyMultipleChoiceQuestion", + "SurveyMatrixQuestion", + "SurveyMetricQuestion", + "SurveyTextQuestion" + )); - $sorted = array(); - $idx = sizeof($default_sorting); - foreach($types as $caption => $item) - { - $type = $item["type_tag"]; - $item["caption"] = $caption; - - // default - if(array_key_exists($type, $default_sorting)) - { - $sorted[$default_sorting[$type]] = $item; - } - // plugin (append alphabetically sorted) - else - { - $sorted[$idx] = $item; - $idx++; - } - } - ksort($sorted); - - // redo captions as index - $types = array(); - foreach($sorted as $item) - { - $types[$item["caption"]] = $item; - } - - return $types; - } - - public static function _getQuestionTypeTranslations() - { - global $DIC; - - $ilDB = $DIC->database(); - global $DIC; - - $lng = $DIC->language(); - global $DIC; - - $ilLog = $DIC["ilLog"]; - global $DIC; - - $ilPluginAdmin = $DIC["ilPluginAdmin"]; - - $lng->loadLanguageModule("survey"); - $result = $ilDB->query("SELECT * FROM svy_qtype"); - $types = array(); - while ($row = $ilDB->fetchAssoc($result)) - { - if ($row["plugin"] == 0) - { - $types[$row['type_tag']] = $lng->txt($row["type_tag"]); - } - else - { - $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(), $row["type_tag"]) == 0) - { - $types[$row['type_tag']] = $pl->getQuestionTypeTranslation(); - } - } - } - } - ksort($types); - return $types; - } - - /** - * Returns the available question pools for the active user - * - * @return array The available question pools - * @access public - */ - static function _getAvailableQuestionpools($use_object_id = FALSE, $could_be_offline = FALSE, $showPath = FALSE, $permission = "read") - { - global $DIC; - - $ilUser = $DIC->user(); - global $DIC; - - $ilDB = $DIC->database(); - - $result_array = array(); - $qpls = ilUtil::_getObjectsByOperations("spl", $permission, $ilUser->getId(), -1); - $titles = ilObject::_prepareCloneSelection($qpls, "spl", $showPath); - $allqpls = array(); - $result = $ilDB->query("SELECT obj_fi, isonline FROM svy_qpl"); - while ($row = $ilDB->fetchAssoc($result)) - { - $allqpls[$row['obj_fi']] = $row['isonline']; - } - foreach ($qpls as $ref_id) - { - $obj_id = ilObject::_lookupObjectId($ref_id); - if ($could_be_offline || $allqpls[$obj_id] == 1) - { - if ($use_object_id) - { - $result_array[$obj_id] = $titles[$ref_id]; - } - else - { - $result_array[$ref_id] = $titles[$ref_id]; - } - } - } - return $result_array; - } - - /** - * Checks whether or not a question plugin with a given name is active - * - * @param string $a_pname The plugin name - * @access public - */ - function isPluginActive($a_pname) - { - $ilPluginAdmin = $this->plugin_admin; - if ($ilPluginAdmin->isActive(IL_COMP_MODULE, "SurveyQuestionPool", "svyq", $a_pname)) - { - return TRUE; - } - else - { - return FALSE; - } - } - - /** - * Returns title, description and type for an array of question id's - * - * @param array $question_ids An array of question id's - * @return array Array of associated arrays with title, description, type_tag - */ - public function getQuestionInfos($question_ids) - { - $ilDB = $this->db; - - $found = array(); - $query_result = $ilDB->query("SELECT svy_question.*, svy_qtype.type_tag FROM svy_question, svy_qtype " . - "WHERE svy_question.questiontype_fi = svy_qtype.questiontype_id " . - "AND svy_question.tstamp > 0 AND " . $ilDB->in('svy_question.question_id', $question_ids, false, 'integer') . " " . - "ORDER BY svy_question.title"); - if ($query_result->numRows() > 0) - { - while ($data = $ilDB->fetchAssoc($query_result)) - { - if (in_array($data["question_id"], $question_ids)) - { - array_push($found, array('id' => $data["question_id"], - 'title' => $data["title"], - 'description' => $data["description"], - 'type_tag' => $data["type_tag"])); - } - } - } - return $found; - } - - /* - * Remove all questions with tstamp = 0 - */ - public function purgeQuestions() - { - $ilDB = $this->db; - $ilUser = $this->user; - - $result = $ilDB->queryF("SELECT question_id FROM svy_question WHERE owner_fi = %s AND tstamp = %s", - array("integer", "integer"), - array($ilUser->getId(), 0) - ); - while ($data = $ilDB->fetchAssoc($result)) - { - $this->removeQuestion($data["question_id"]); - } - } - - /** - * Copies a question to the clipboard - * - * @param integer $question_id Object id of the question - */ - public function copyToClipboard($question_id) - { - if (!array_key_exists("spl_clipboard", $_SESSION)) - { - $_SESSION["spl_clipboard"] = array(); - } - $_SESSION["spl_clipboard"][$question_id] = array("question_id" => $question_id, "action" => "copy"); - } - - /** - * Moves a question to the clipboard - * - * @param integer $question_id Object id of the question - */ - public function moveToClipboard($question_id) - { - if (!array_key_exists("spl_clipboard", $_SESSION)) - { - $_SESSION["spl_clipboard"] = array(); - } - $_SESSION["spl_clipboard"][$question_id] = array("question_id" => $question_id, "action" => "move"); - } - - /** - * Copies/Moves a question from the clipboard - */ - public function pasteFromClipboard() - { - $ilDB = $this->db; - - if (array_key_exists("spl_clipboard", $_SESSION)) - { - foreach ($_SESSION["spl_clipboard"] as $question_object) - { - if (strcmp($question_object["action"], "move") == 0) - { - $result = $ilDB->queryF("SELECT obj_fi FROM svy_question WHERE question_id = %s", - array('integer'), - array($question_object["question_id"]) - ); - if ($result->numRows() == 1) - { - $row = $ilDB->fetchAssoc($result); - $source_questionpool = $row["obj_fi"]; - if ($this->getId() != $source_questionpool) - { - // change the questionpool id in the qpl_questions table - $affectedRows = $ilDB->manipulateF("UPDATE svy_question SET obj_fi = %s WHERE question_id = %s", - array('integer','integer'), - array($this->getId(), $question_object["question_id"]) - ); - - // move question data to the new target directory - $source_path = CLIENT_WEB_DIR . "/survey/" . $source_questionpool . "/" . $question_object["question_id"] . "/"; - if (@is_dir($source_path)) - { - $target_path = CLIENT_WEB_DIR . "/survey/" . $this->getId() . "/"; - if (!@is_dir($target_path)) - { - ilUtil::makeDirParents($target_path); - } - @rename($source_path, $target_path . $question_object["question_id"]); - } - } - else - { - ilUtil::sendFailure($this->lng->txt("spl_move_same_pool"), true); - return; - } - } - } - else - { - $this->copyQuestion($question_object["question_id"], $this->getId()); - } - } - } - ilUtil::sendSuccess($this->lng->txt("spl_paste_success"), true); - unset($_SESSION["spl_clipboard"]); - } - - /** - * Sets the obligatory states for questions in a survey from the questions form - * - * @param array $obligatory_questions The questions which should be set obligatory from the questions form, the remaining questions should be setted not obligatory - * @access public - */ - function setObligatoryStates($obligatory_questions) - { - $ilDB = $this->db; - - foreach($this->getQuestions() as $question_id) - { - $status = (int)(in_array($question_id, $obligatory_questions)); - - $ilDB->manipulate("UPDATE svy_question". - " SET obligatory = ".$ilDB->quote($status, "integer"). - " WHERE question_id = ".$ilDB->quote($question_id, "integer")); - } - } + $sorted = array(); + $idx = sizeof($default_sorting); + foreach ($types as $caption => $item) { + $type = $item["type_tag"]; + $item["caption"] = $caption; + + // default + if (array_key_exists($type, $default_sorting)) { + $sorted[$default_sorting[$type]] = $item; + } + // plugin (append alphabetically sorted) + else { + $sorted[$idx] = $item; + $idx++; + } + } + ksort($sorted); + + // redo captions as index + $types = array(); + foreach ($sorted as $item) { + $types[$item["caption"]] = $item; + } + + return $types; + } + + public static function _getQuestionTypeTranslations() + { + global $DIC; + + $ilDB = $DIC->database(); + global $DIC; + + $lng = $DIC->language(); + global $DIC; + + $ilLog = $DIC["ilLog"]; + global $DIC; + + $ilPluginAdmin = $DIC["ilPluginAdmin"]; + + $lng->loadLanguageModule("survey"); + $result = $ilDB->query("SELECT * FROM svy_qtype"); + $types = array(); + while ($row = $ilDB->fetchAssoc($result)) { + if ($row["plugin"] == 0) { + $types[$row['type_tag']] = $lng->txt($row["type_tag"]); + } else { + $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(), $row["type_tag"]) == 0) { + $types[$row['type_tag']] = $pl->getQuestionTypeTranslation(); + } + } + } + } + ksort($types); + return $types; + } + + /** + * Returns the available question pools for the active user + * + * @return array The available question pools + * @access public + */ + public static function _getAvailableQuestionpools($use_object_id = false, $could_be_offline = false, $showPath = false, $permission = "read") + { + global $DIC; + + $ilUser = $DIC->user(); + global $DIC; + + $ilDB = $DIC->database(); + + $result_array = array(); + $qpls = ilUtil::_getObjectsByOperations("spl", $permission, $ilUser->getId(), -1); + $titles = ilObject::_prepareCloneSelection($qpls, "spl", $showPath); + $allqpls = array(); + $result = $ilDB->query("SELECT obj_fi, isonline FROM svy_qpl"); + while ($row = $ilDB->fetchAssoc($result)) { + $allqpls[$row['obj_fi']] = $row['isonline']; + } + foreach ($qpls as $ref_id) { + $obj_id = ilObject::_lookupObjectId($ref_id); + if ($could_be_offline || $allqpls[$obj_id] == 1) { + if ($use_object_id) { + $result_array[$obj_id] = $titles[$ref_id]; + } else { + $result_array[$ref_id] = $titles[$ref_id]; + } + } + } + return $result_array; + } + + /** + * Checks whether or not a question plugin with a given name is active + * + * @param string $a_pname The plugin name + * @access public + */ + public function isPluginActive($a_pname) + { + $ilPluginAdmin = $this->plugin_admin; + if ($ilPluginAdmin->isActive(IL_COMP_MODULE, "SurveyQuestionPool", "svyq", $a_pname)) { + return true; + } else { + return false; + } + } + + /** + * Returns title, description and type for an array of question id's + * + * @param array $question_ids An array of question id's + * @return array Array of associated arrays with title, description, type_tag + */ + public function getQuestionInfos($question_ids) + { + $ilDB = $this->db; + + $found = array(); + $query_result = $ilDB->query("SELECT svy_question.*, svy_qtype.type_tag FROM svy_question, svy_qtype " . + "WHERE svy_question.questiontype_fi = svy_qtype.questiontype_id " . + "AND svy_question.tstamp > 0 AND " . $ilDB->in('svy_question.question_id', $question_ids, false, 'integer') . " " . + "ORDER BY svy_question.title"); + if ($query_result->numRows() > 0) { + while ($data = $ilDB->fetchAssoc($query_result)) { + if (in_array($data["question_id"], $question_ids)) { + array_push($found, array('id' => $data["question_id"], + 'title' => $data["title"], + 'description' => $data["description"], + 'type_tag' => $data["type_tag"])); + } + } + } + return $found; + } + + /* + * Remove all questions with tstamp = 0 + */ + public function purgeQuestions() + { + $ilDB = $this->db; + $ilUser = $this->user; + + $result = $ilDB->queryF( + "SELECT question_id FROM svy_question WHERE owner_fi = %s AND tstamp = %s", + array("integer", "integer"), + array($ilUser->getId(), 0) + ); + while ($data = $ilDB->fetchAssoc($result)) { + $this->removeQuestion($data["question_id"]); + } + } + + /** + * Copies a question to the clipboard + * + * @param integer $question_id Object id of the question + */ + public function copyToClipboard($question_id) + { + if (!array_key_exists("spl_clipboard", $_SESSION)) { + $_SESSION["spl_clipboard"] = array(); + } + $_SESSION["spl_clipboard"][$question_id] = array("question_id" => $question_id, "action" => "copy"); + } + + /** + * Moves a question to the clipboard + * + * @param integer $question_id Object id of the question + */ + public function moveToClipboard($question_id) + { + if (!array_key_exists("spl_clipboard", $_SESSION)) { + $_SESSION["spl_clipboard"] = array(); + } + $_SESSION["spl_clipboard"][$question_id] = array("question_id" => $question_id, "action" => "move"); + } + + /** + * Copies/Moves a question from the clipboard + */ + public function pasteFromClipboard() + { + $ilDB = $this->db; + + if (array_key_exists("spl_clipboard", $_SESSION)) { + foreach ($_SESSION["spl_clipboard"] as $question_object) { + if (strcmp($question_object["action"], "move") == 0) { + $result = $ilDB->queryF( + "SELECT obj_fi FROM svy_question WHERE question_id = %s", + array('integer'), + array($question_object["question_id"]) + ); + if ($result->numRows() == 1) { + $row = $ilDB->fetchAssoc($result); + $source_questionpool = $row["obj_fi"]; + if ($this->getId() != $source_questionpool) { + // change the questionpool id in the qpl_questions table + $affectedRows = $ilDB->manipulateF( + "UPDATE svy_question SET obj_fi = %s WHERE question_id = %s", + array('integer','integer'), + array($this->getId(), $question_object["question_id"]) + ); + + // move question data to the new target directory + $source_path = CLIENT_WEB_DIR . "/survey/" . $source_questionpool . "/" . $question_object["question_id"] . "/"; + if (@is_dir($source_path)) { + $target_path = CLIENT_WEB_DIR . "/survey/" . $this->getId() . "/"; + if (!@is_dir($target_path)) { + ilUtil::makeDirParents($target_path); + } + @rename($source_path, $target_path . $question_object["question_id"]); + } + } else { + ilUtil::sendFailure($this->lng->txt("spl_move_same_pool"), true); + return; + } + } + } else { + $this->copyQuestion($question_object["question_id"], $this->getId()); + } + } + } + ilUtil::sendSuccess($this->lng->txt("spl_paste_success"), true); + unset($_SESSION["spl_clipboard"]); + } + + /** + * Sets the obligatory states for questions in a survey from the questions form + * + * @param array $obligatory_questions The questions which should be set obligatory from the questions form, the remaining questions should be setted not obligatory + * @access public + */ + public function setObligatoryStates($obligatory_questions) + { + $ilDB = $this->db; + + foreach ($this->getQuestions() as $question_id) { + $status = (int) (in_array($question_id, $obligatory_questions)); + + $ilDB->manipulate("UPDATE svy_question" . + " SET obligatory = " . $ilDB->quote($status, "integer") . + " WHERE question_id = " . $ilDB->quote($question_id, "integer")); + } + } } // END class.ilSurveyObjQuestionPool -?> diff --git a/Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPoolAccess.php b/Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPoolAccess.php index f1d46c1e494108a7f04df020bb505cd5ef07ab60..ee18e10c1c909873dd30902c215dbc597b520546 100644 --- a/Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPoolAccess.php +++ b/Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPoolAccess.php @@ -1,24 +1,24 @@ "read", "cmd" => "view", "lang_var" => "show", - * "default" => true), - * array("permission" => "write", "cmd" => "edit", "lang_var" => "edit"), - * ); - */ - static function _getCommands() - { - $commands = array - ( - array("permission" => "read", "cmd" => "questions", "lang_var" => "edit_questions", - "default" => true), - array("permission" => "write", "cmd" => "questions", "lang_var" => "edit_questions"), - array("permission" => "write", "cmd" => "properties", "lang_var" => "settings") - ); - - return $commands; - } + /** + * get commands + * + * this method returns an array of all possible commands/permission combinations + * + * example: + * $commands = array + * ( + * array("permission" => "read", "cmd" => "view", "lang_var" => "show", + * "default" => true), + * array("permission" => "write", "cmd" => "edit", "lang_var" => "edit"), + * ); + */ + public static function _getCommands() + { + $commands = array( + array("permission" => "read", "cmd" => "questions", "lang_var" => "edit_questions", + "default" => true), + array("permission" => "write", "cmd" => "questions", "lang_var" => "edit_questions"), + array("permission" => "write", "cmd" => "properties", "lang_var" => "settings") + ); + + return $commands; + } - static function _checkGoto($a_target) - { - global $DIC; + public static function _checkGoto($a_target) + { + global $DIC; - $ilAccess = $DIC->access(); - - $t_arr = explode("_", $a_target); + $ilAccess = $DIC->access(); + + $t_arr = explode("_", $a_target); - if ($ilAccess->checkAccess("visible", "", $t_arr[1]) || - $ilAccess->checkAccess("read", "", $t_arr[1])) - { - return true; - } - return false; - } + if ($ilAccess->checkAccess("visible", "", $t_arr[1]) || + $ilAccess->checkAccess("read", "", $t_arr[1])) { + return true; + } + return false; + } } - -?> diff --git a/Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPoolGUI.php b/Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPoolGUI.php index 5e136328a1709df8ada1bd8173127237e4baea17..f70acef31156a799fdad857dfe2ac6f15318c292 100755 --- a/Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPoolGUI.php +++ b/Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPoolGUI.php @@ -1,24 +1,24 @@ lng = $DIC->language(); - $this->nav_history = $DIC["ilNavigationHistory"]; - $this->tpl = $DIC["tpl"]; - $this->user = $DIC->user(); - $this->toolbar = $DIC->toolbar(); - $this->error = $DIC["ilErr"]; - $this->locator = $DIC["ilLocator"]; - $this->help = $DIC["ilHelp"]; - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - - $this->type = "spl"; - $lng->loadLanguageModule("survey"); - $this->ctrl = $ilCtrl; - $this->ctrl->saveParameter($this, array("ref_id")); - - parent::__construct("", $_GET["ref_id"], true, false); - - $this->log = ilLoggerFactory::getLogger('svy'); - } - - /** - * execute command - */ - public function executeCommand() - { - $ilNavigationHistory = $this->nav_history; - - if (!$this->checkPermissionBool("visible") && - !$this->checkPermissionBool("read")) - { - $this->checkPermission("read"); - } - - // add entry to navigation history - if (!$this->getCreationMode() && - $this->checkPermissionBool("read")) - { - $ilNavigationHistory->addItem($this->ref_id, - "ilias.php?baseClass=ilObjSurveyQuestionPoolGUI&cmd=questions&ref_id=".$this->ref_id, "spl"); - } - - $this->tpl->addCss(ilUtil::getStyleSheetLocation("output", "survey.css", "Modules/Survey"), "screen"); - $this->prepareOutput(); - - $cmd = $this->ctrl->getCmd("questions"); - $next_class = $this->ctrl->getNextClass($this); - $this->ctrl->setReturn($this, "questions"); - if ($_GET["q_id"] < 1) - { - $q_type = ($_POST["sel_question_types"] != "") - ? $_POST["sel_question_types"] - : $_GET["sel_question_types"]; - } - - $this->log->debug("- cmd=".$cmd." next_class=".$next_class); - switch($next_class) - { - case 'ilobjectmetadatagui': - $this->checkPermission('write'); - include_once 'Services/Object/classes/class.ilObjectMetaDataGUI.php'; - $md_gui = new ilObjectMetaDataGUI($this->object); - $this->ctrl->forwardCommand($md_gui); - break; - - case 'ilpermissiongui': - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $ret =& $this->ctrl->forwardCommand($perm_gui); - break; - - case "ilsurveyphrasesgui": - include_once("./Modules/SurveyQuestionPool/classes/class.ilSurveyPhrasesGUI.php"); - $phrases_gui = new ilSurveyPhrasesGUI($this); - $ret =& $this->ctrl->forwardCommand($phrases_gui); - break; - - case 'ilobjectcopygui': - include_once './Services/Object/classes/class.ilObjectCopyGUI.php'; - $cp = new ilObjectCopyGUI($this); - $cp->setType('spl'); - $this->ctrl->forwardCommand($cp); - break; - - case 'ilinfoscreengui': - $this->infoScreenForward(); - break; - - case "ilcommonactiondispatchergui": - include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); - $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); - $this->ctrl->forwardCommand($gui); - break; - - case "": - $cmd.= "Object"; - $ret =& $this->$cmd(); - break; - - default: - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php"; - $q_gui = SurveyQuestionGUI::_getQuestionGUI($q_type, $_GET["q_id"]); - $this->log->debug("- This is the switch/case default, going to question id =".$_GET["q_id"]); - // $q_gui->object->setObjId($this->object->getId()); - $q_gui->setQuestionTabs(); - $ret =& $this->ctrl->forwardCommand($q_gui); - - // not on create - if($q_gui->object->isComplete()) - { - $this->tpl->setTitle($this->lng->txt("question").": ".$q_gui->object->getTitle()); - } - break; - } - if (strtolower($_GET["baseClass"]) != "iladministrationgui" && - $this->getCreationMode() != true) - { - $this->tpl->show(); - } - } - - protected function initEditForm() - { - $obj_service = $this->object_service; - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this, 'properties')); - $form->setTitle($this->lng->txt("properties")); - $form->setMultipart(false); - $form->setId("properties"); - - // title - $title = new ilTextInputGUI($this->lng->txt('title'),'title'); - $title->setSubmitFormOnEnter(true); - $title->setValue($this->object->getTitle()); - $title->setSize(min(40, ilObject::TITLE_LENGTH)); - $title->setMaxLength(ilObject::TITLE_LENGTH); - $title->setRequired(true); - $form->addItem($title); - - // desc - $desc = new ilTextAreaInputGUI($this->lng->txt('description'),'desc'); - $desc->setValue($this->object->getLongDescription()); - $desc->setRows(2); - $desc->setCols(40); - $form->addItem($desc); - - // online - $online = new ilCheckboxInputGUI($this->lng->txt("spl_online_property"), "online"); - $online->setInfo($this->lng->txt("spl_online_property_description")); - $online->setChecked($this->object->getOnline()); - $form->addItem($online); - - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($this->lng->txt('obj_presentation')); - $form->addItem($section); - - // tile image - $obj_service->commonSettings()->legacyForm($form, $this->object)->addTileImage(); - - - $form->addCommandButton("saveProperties", $this->lng->txt("save")); - - return $form; - } - - /** - * Questionpool properties - */ - public function propertiesObject(ilPropertyFormGUI $a_form = null) - { - if(!$a_form) - { - $a_form = $this->initEditForm(); - } - - $this->tpl->setVariable("ADM_CONTENT", $a_form->getHTML()); - } - - /** - * Save questionpool properties - */ - public function savePropertiesObject() - { - $obj_service = $this->object_service; - $form = $this->initEditForm(); - if($form->checkInput()) - { - $this->object->setTitle($form->getInput("title")); - $this->object->setDescription($form->getInput("desc")); - $this->object->setOnline((int)$form->getInput("online")); - - $this->object->saveToDb(); - - // tile image - $obj_service->commonSettings()->legacyForm($form, $this->object)->saveTileImage(); - - - ilUtil::sendSuccess($this->lng->txt("saved_successfully"), true); - $this->ctrl->redirect($this, "properties"); - } - - $form->setValuesByPost(); - $this->propertiesObject($form); - } - - - /** - * Copies checked questions in the questionpool to a clipboard - */ - public function copyObject() - { - if (count($_POST["q_id"]) > 0) - { - foreach ($_POST["q_id"] as $key => $value) - { - $this->object->copyToClipboard($value); - } - ilUtil::sendInfo($this->lng->txt("spl_copy_insert_clipboard"), true); - } - else - { - ilUtil::sendInfo($this->lng->txt("spl_copy_select_none"), true); - } - $this->ctrl->redirect($this, "questions"); - } - - /** - * mark one or more question objects for moving - */ - public function moveObject() - { - if (count($_POST["q_id"]) > 0) - { - foreach ($_POST["q_id"] as $key => $value) - { - $this->object->moveToClipboard($value); - } - ilUtil::sendInfo($this->lng->txt("spl_move_insert_clipboard"), true); - } - else - { - ilUtil::sendInfo($this->lng->txt("spl_move_select_none"), true); - } - $this->ctrl->redirect($this, "questions"); - } - - /** - * export a question - */ - public function exportQuestionObject() - { - if (is_array($_POST['q_id']) && count($_POST['q_id']) > 0) - { - $this->createExportFileObject($_POST['q_id']); - } - else - { - ilUtil::sendInfo($this->lng->txt("qpl_export_select_none")); - $this->questionsObject(); - } - } - - /** - * Creates a confirmation form to delete questions from the question pool - */ - public function deleteQuestionsObject() - { - $this->checkPermission('write'); - - // create an array of all checked checkboxes - $checked_questions = $_POST['q_id']; - if (count($checked_questions) == 0) - { - ilUtil::sendInfo($this->lng->txt("qpl_delete_select_none")); - $this->questionsObject(); - return; - } - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setHeaderText($this->lng->txt("qpl_confirm_delete_questions")); - - $cgui->setFormAction($this->ctrl->getFormAction($this)); - $cgui->setCancel($this->lng->txt("cancel"), "cancelDeleteQuestions"); - $cgui->setConfirm($this->lng->txt("confirm"), "confirmDeleteQuestions"); - - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - $infos = $this->object->getQuestionInfos($checked_questions); - foreach ($infos as $data) - { - $txt = $data["title"]." (". - SurveyQuestion::_getQuestionTypeName($data["type_tag"]).")"; - if($data["description"]) - { - $txt .= "
".$data["description"]."
"; - } - - $cgui->addItem("q_id[]", $data["id"], $txt); - } - - $this->tpl->setContent($cgui->getHTML()); - } - - /** - * delete questions - */ - public function confirmDeleteQuestionsObject() - { - // delete questions after confirmation - ilUtil::sendSuccess($this->lng->txt("qpl_questions_deleted"), true); - foreach ($_POST['q_id'] as $q_id) - { - $this->object->removeQuestion($q_id); - } - $this->ctrl->redirect($this, "questions"); - } - - /** - * cancel delete questions - */ - public function cancelDeleteQuestionsObject() - { - // delete questions after confirmation - $this->ctrl->redirect($this, "questions"); - } - - /** - * paste questios from the clipboard into the question pool - */ - public function pasteObject() - { - if (array_key_exists("spl_clipboard", $_SESSION)) - { - $this->object->pasteFromClipboard(); - } - else - { - ilUtil::sendInfo($this->lng->txt("spl_paste_no_objects"), true); - } - $this->ctrl->redirect($this, "questions"); - } - - /** - * display the import form to import questions into the questionpool - */ - public function importQuestionsObject() - { - $tpl = $this->tpl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this, "uploadQuestions")); - $form->setTitle($this->lng->txt("import_question")); - - include_once("./Services/Form/classes/class.ilFileInputGUI.php"); - $fi = new ilFileInputGUI($this->lng->txt("select_file"), "qtidoc"); - $fi->setSuffixes(array("xml", "zip")); - $fi->setRequired(true); - $form->addItem($fi); - - $form->addCommandButton("uploadQuestions", $this->lng->txt("import")); - $form->addCommandButton("questions", $this->lng->txt("cancel")); - - $tpl->setContent($form->getHTML()); - } - - /** - * imports question(s) into the questionpool - */ - public function uploadQuestionsObject() - { - // check if file was uploaded - $source = $_FILES["qtidoc"]["tmp_name"]; - $error = 0; - if (($source == 'none') || (!$source) || $_FILES["qtidoc"]["error"] > UPLOAD_ERR_OK) - { - $error = 1; - } - // check correct file type - if (!$error && strpos("xml", $_FILES["qtidoc"]["type"]) !== FALSE) - { - $error = 1; - } - if (!$error) - { - // import file into questionpool - // create import directory - $this->object->createImportDirectory(); - - // copy uploaded file to import directory - $full_path = $this->object->getImportDirectory()."/".$_FILES["qtidoc"]["name"]; - - ilUtil::moveUploadedFile($_FILES["qtidoc"]["tmp_name"], - $_FILES["qtidoc"]["name"], $full_path); - $source = $full_path; - $this->object->importObject($source, TRUE); - unlink($source); - } - $this->ctrl->redirect($this, "questions"); - } - - public function filterQuestionBrowserObject() - { - include_once "./Modules/SurveyQuestionPool/classes/tables/class.ilSurveyQuestionsTableGUI.php"; - $table_gui = new ilSurveyQuestionsTableGUI($this, 'questions'); - $table_gui->writeFilterToSession(); - $this->ctrl->redirect($this, 'questions'); - } - - public function resetfilterQuestionBrowserObject() - { - include_once "./Modules/SurveyQuestionPool/classes/tables/class.ilSurveyQuestionsTableGUI.php"; - $table_gui = new ilSurveyQuestionsTableGUI($this, 'questions'); - $table_gui->resetFilter(); - $this->ctrl->redirect($this, 'questions'); - } - - /** - * list questions of question pool - */ - public function questionsObject($arrFilter = null) - { - $ilUser = $this->user; - $ilToolbar = $this->toolbar; - - $this->object->purgeQuestions(); - - $_SESSION['q_id_table_nav'] = $_GET['q_id_table_nav']; - - if ($this->checkPermissionBool('write')) - { - include_once "Services/Form/classes/class.ilSelectInputGUI.php"; - $qtypes = new ilSelectInputGUI("", "sel_question_types"); - $qtypes->setValue($ilUser->getPref("svy_lastquestiontype")); - $ilToolbar->addInputItem($qtypes); - - $options = array(); - foreach (ilObjSurveyQuestionPool::_getQuestionTypes() as $translation => $data) - { - $options[$data["type_tag"]] = $translation; - } - $qtypes->setOptions($options); - - $ilToolbar->setFormAction($this->ctrl->getFormAction($this)); - - include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; - $button = ilSubmitButton::getInstance(); - $button->setCaption("svy_create_question"); - $button->setCommand("createQuestion"); - $ilToolbar->addButtonInstance($button); - - $ilToolbar->addSeparator(); - - $button = ilSubmitButton::getInstance(); - $button->setCaption("import"); - $button->setCommand("importQuestions"); - $ilToolbar->addButtonInstance($button); - } - - include_once "./Modules/SurveyQuestionPool/classes/tables/class.ilSurveyQuestionsTableGUI.php"; - $table_gui = new ilSurveyQuestionsTableGUI($this, 'questions', (($this->checkPermissionBool('write') ? true : false))); - $table_gui->setEditable($this->checkPermissionBool('write')); - $arrFilter = array(); - foreach ($table_gui->getFilterItems() as $item) - { - if ($item->getValue() !== false) - { - $arrFilter[$item->getPostVar()] = $item->getValue(); - } - } - $table_gui->setData($this->object->getQuestionsData($arrFilter)); - $this->tpl->setContent($table_gui->getHTML()); - } - - public function updateObject() - { - $this->update = $this->object->update(); - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - } - - public function afterSave(ilObject $a_new_object) - { - // always send a message - ilUtil::sendSuccess($this->lng->txt("object_added"),true); - - ilUtil::redirect("ilias.php?ref_id=".$a_new_object->getRefId(). - "&baseClass=ilObjSurveyQuestionPoolGUI"); - } - - /* - * list all export files - */ - public function exportObject() - { - $ilToolbar = $this->toolbar; - - $ilToolbar->addButton($this->lng->txt('create_export_file'), - $this->ctrl->getLinkTarget($this, 'createExportFile')); - - include_once "./Modules/SurveyQuestionPool/classes/tables/class.ilSurveyQuestionPoolExportTableGUI.php"; - $table_gui = new ilSurveyQuestionPoolExportTableGUI($this, 'export'); - $export_dir = $this->object->getExportDirectory(); - $export_files = $this->object->getExportFiles($export_dir); - $data = array(); - foreach ($export_files as $exp_file) - { - $file_arr = explode("__", $exp_file); - array_push($data, array('file' => $exp_file, 'date' => ilDatePresentation::formatDate(new ilDateTime($file_arr[0], IL_CAL_UNIX)), 'size' => filesize($export_dir."/".$exp_file))); - } - $table_gui->setData($data); - $this->tpl->setContent($table_gui->getHTML()); - } - - /** - * create export file - */ - public function createExportFileObject($questions = null) - { - $this->checkPermission("write"); - - include_once("./Modules/SurveyQuestionPool/classes/class.ilSurveyQuestionpoolExport.php"); - $survey_exp = new ilSurveyQuestionpoolExport($this->object); - $survey_exp->buildExportFile($questions); - $this->ctrl->redirect($this, "export"); - } - - /** - * download export file - */ - public function downloadExportFileObject() - { - if(!isset($_POST["file"])) - { - ilUtil::sendInfo($this->lng->txt("no_checkbox"), true); - $this->ctrl->redirect($this, "export"); - } - - if (count($_POST["file"]) > 1) - { - ilUtil::sendInfo($this->lng->txt("select_max_one_item"),true); - $this->ctrl->redirect($this, "export"); - } - - - $export_dir = $this->object->getExportDirectory(); - - $file = basename($_POST["file"][0]); - - ilUtil::deliverFile($export_dir."/".$file, $file); - } - - /** - * confirmation screen for export file deletion - */ - public function confirmDeleteExportFileObject() - { - if(!isset($_POST["file"])) - { - ilUtil::sendInfo($this->lng->txt("no_checkbox"),true); - $this->ctrl->redirect($this, "export"); - } - - ilUtil::sendQuestion($this->lng->txt("info_delete_sure")); - include_once "./Modules/SurveyQuestionPool/classes/tables/class.ilSurveyQuestionPoolExportTableGUI.php"; - $table_gui = new ilSurveyQuestionPoolExportTableGUI($this, 'export', true); - $export_dir = $this->object->getExportDirectory(); - $data = array(); - foreach ($_POST['file'] as $exp_file) - { - $file_arr = explode("__", $exp_file); - array_push($data, array('file' => $exp_file, 'date' => ilDatePresentation::formatDate(new ilDateTime($file_arr[0], IL_CAL_UNIX)), 'size' => filesize($export_dir."/".$exp_file))); - } - $table_gui->setData($data); - $this->tpl->setVariable('ADM_CONTENT', $table_gui->getHTML()); - } - - - /** - * cancel deletion of export files - */ - public function cancelDeleteExportFileObject() - { - ilSession::clear("ilExportFiles"); - $this->ctrl->redirect($this, "export"); - } - - /** - * delete export files - */ - public function deleteExportFileObject() - { - $export_dir = $this->object->getExportDirectory(); - foreach($_POST['file'] as $file) - { - $file = basename($file); - - $exp_file = $export_dir."/".$file; - $exp_dir = $export_dir."/".substr($file, 0, strlen($file) - 4); - if (@is_file($exp_file)) - { - unlink($exp_file); - } - if (@is_dir($exp_dir)) - { - ilUtil::delDir($exp_dir); - } - } - $this->ctrl->redirect($this, "export"); - } - - protected function initImportForm($a_new_type) - { - $form = parent::initImportForm($a_new_type); - $form->getItemByPostVar('importfile')->setSuffixes(array("zip", "xml")); - - return $form; - } - - protected function initCreationForms($a_new_type) - { - $form = $this->initImportForm($a_new_type); - - $forms = array(self::CFORM_NEW => $this->initCreateForm($a_new_type), - self::CFORM_IMPORT => $form); - - return $forms; - } - - /** - * form for new survey object import - */ - public function importFileObject($parent_id = null, $a_catch_errors = true) - { - $tpl = $this->tpl; - $ilErr = $this->error; - - if(!$parent_id) - { - $parent_id = $_GET["ref_id"]; - } - $new_type = $_REQUEST["new_type"]; - - // create permission is already checked in createObject. This check here is done to prevent hacking attempts - if (!$this->checkPermissionBool("create", "", $new_type)) - { - $ilErr->raiseError($this->lng->txt("no_create_permission")); - } - - $this->lng->loadLanguageModule($new_type); - $this->ctrl->setParameter($this, "new_type", $new_type); - - $form = $this->initImportForm($new_type); - if ($form->checkInput()) - { - include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"; - $newObj = new ilObjSurveyQuestionPool(); - $newObj->setType($new_type); - $newObj->setTitle("dummy"); - $newObj->create(true); - $this->putObjectInTree($newObj); - - $newObj->createImportDirectory(); - - // copy uploaded file to import directory - $upload = $_FILES["importfile"]; - $file = pathinfo($upload["name"]); - $full_path = $newObj->getImportDirectory()."/".$upload["name"]; - ilUtil::moveUploadedFile($upload["tmp_name"], $upload["name"], - $full_path); - - // import qti data - $qtiresult = $newObj->importObject($full_path); - - ilUtil::sendSuccess($this->lng->txt("object_imported"),true); - ilUtil::redirect("ilias.php?ref_id=".$newObj->getRefId(). - "&baseClass=ilObjSurveyQuestionPoolGUI"); - } - - // display form to correct errors - $form->setValuesByPost(); - $tpl->setContent($form->getHtml()); - } - - /** - * create new question - */ - public function &createQuestionObject() - { - $ilUser = $this->user; - - $ilUser->writePref("svy_lastquestiontype", $_POST["sel_question_types"]); - - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php"; - $q_gui =& SurveyQuestionGUI::_getQuestionGUI($_POST["sel_question_types"]); - $q_gui->object->setObjId($this->object->getId()); - $q_gui->object->createNewQuestion(); - - $this->ctrl->setParameterByClass(get_class($q_gui), "q_id", $q_gui->object->getId()); - $this->ctrl->setParameterByClass(get_class($q_gui), "sel_question_types", $_POST["sel_question_types"]); - $this->ctrl->redirectByClass(get_class($q_gui), "editQuestion"); - } - - /** - * create preview of object - */ - public function &previewObject() - { - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php"; - $q_gui =& SurveyQuestionGUI::_getQuestionGUI("", $_GET["preview"]); - $this->ctrl->setParameterByClass(get_class($q_gui), "sel_question_types", $q_gui->getQuestionType()); - $this->ctrl->setParameterByClass(get_class($q_gui), "q_id", $_GET["preview"]); - $this->ctrl->redirectByClass(get_class($q_gui), "preview"); - } - - /** - * 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 infoScreenObject() - { - $this->ctrl->setCmd("showSummary"); - $this->ctrl->setCmdClass("ilinfoscreengui"); - $this->infoScreenForward(); - } - - /** - * show information screen - */ - function infoScreenForward() - { - if (!$this->checkPermissionBool("read")) - { - $this->checkPermission("visible"); - } - - include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); - $info = new ilInfoScreenGUI($this); - $info->enablePrivateNotes(); - - // standard meta data - $info->addMetaDataSections($this->object->getId(), 0, $this->object->getType()); - - $this->ctrl->forwardCommand($info); - } - - public function addLocatorItems() - { - $ilLocator = $this->locator; - switch ($this->ctrl->getCmd()) - { - case "create": - case "importFile": - case "cancel": - break; - default: - $ilLocator->addItem($this->object->getTitle(), $this->ctrl->getLinkTarget($this, ""), "", $_GET["ref_id"]); - break; - } - if ((int)$_GET["q_id"]) - { - $q_id = (int)$_GET["q_id"]; - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - $q_type = SurveyQuestion::_getQuestionType($q_id) . "GUI"; - $q_title = SurveyQuestion::_getTitle($q_id); - if($q_title) - { - // not on create - $this->ctrl->setParameterByClass($q_type, "q_id", $q_id); - $ilLocator->addItem($q_title, - $this->ctrl->getLinkTargetByClass($q_type, "editQuestion")); - } - } - } - - /** - * adds tabs to tab gui object - * - * @param object $tabs_gui ilTabsGUI object - */ - public function getTabs() - { - $ilHelp = $this->help; - - $ilHelp->setScreenIdComponent("spl"); - - $next_class = $this->ctrl->getNextClass($this); - switch ($next_class) - { - case "": - case "ilpermissiongui": - case "ilobjectmetadatagui": - case "ilsurveyphrasesgui": - break; - default: - return; - break; - } - - // questions - $force_active = (($this->ctrl->getCmdClass() == "" && - $this->ctrl->getCmd() != "properties" && $this->ctrl->getCmd() != "infoScreen") || - $this->ctrl->getCmd() == "") - ? true - : false; - if (!$force_active) - { - if (is_array($_GET["sort"])) - { - $force_active = true; - } - } - - if ($this->checkPermissionBool("read")) - { - $this->tabs_gui->addTarget("survey_questions", - $this->ctrl->getLinkTarget($this,'questions'), - array("questions", "filterQuestionBrowser", "filter", "reset", "createQuestion", - "importQuestions", "deleteQuestions", "copy", "paste", - "exportQuestions", "confirmDeleteQuestions", "cancelDeleteQuestions", - "confirmPasteQuestions", "cancelPasteQuestions", "uploadQuestions", - "editQuestion", "addMaterial", "removeMaterial", "save", "cancel", - "cancelExplorer", "linkChilds", "addGIT", "addST", "addPG", "preview", - "moveCategory", "deleteCategory", "addPhrase", "addCategory", "savePhrase", - "addSelectedPhrase", "cancelViewPhrase", "confirmSavePhrase", "cancelSavePhrase", - "insertBeforeCategory", "insertAfterCategory", "confirmDeleteCategory", - "cancelDeleteCategory", "categories", "saveCategories", - "savePhrase", "addPhrase" - ), - array("ilobjsurveyquestionpoolgui", "ilsurveyphrasesgui"), "", $force_active); - - $this->tabs_gui->addTarget("info_short", - $this->ctrl->getLinkTarget($this, "infoScreen"), - array("infoScreen", "showSummary")); - } - - if ($this->checkPermissionBool('write')) - { - // properties - $this->tabs_gui->addTarget("settings", - $this->ctrl->getLinkTarget($this,'properties'), - array("properties", "saveProperties"), - "", ""); - - // manage phrases - $this->tabs_gui->addTarget("manage_phrases", - $this->ctrl->getLinkTargetByClass("ilsurveyphrasesgui", "phrases"), - array("phrases", "deletePhrase", "confirmDeletePhrase", "cancelDeletePhrase", "editPhrase", "newPhrase", "saveEditPhrase", "phraseEditor"), - "ilsurveyphrasesgui", ""); - - // meta data - include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php"; - $mdgui = new ilObjectMetaDataGUI($this->object); - $mdtab = $mdgui->getTab(); - if($mdtab) - { - $this->tabs_gui->addTarget("meta_data", - $mdtab, - "", "ilmdeditorgui"); - } - - // export - $this->tabs_gui->addTarget("export", - $this->ctrl->getLinkTarget($this,'export'), - array("export", "createExportFile", "confirmDeleteExportFile", - "downloadExportFile", "cancelDeleteExportFile", "deleteExportFile"), - "", ""); - } - - if ($this->checkPermissionBool("edit_permission")) - { - $this->tabs_gui->addTarget("perm_settings", - $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm"), array("perm","info","owner"), 'ilpermissiongui'); - } - } - - /** - * Save obligatory states - */ - public function saveObligatoryObject() - { - $obligatory = array(); - foreach ($_POST as $key => $value) - { - if (preg_match("/obligatory_(\d+)/", $key, $matches)) - { - $obligatory[]= $matches[1]; - } - } - $this->object->setObligatoryStates($obligatory); - - ilUtil::sendSuccess($this->lng->txt('msg_obj_modified'), true); - $this->ctrl->redirect($this, "questions"); - } - - /** - * Redirect script to call a survey question pool reference id - * - * @param integer $a_target The reference id of the question pool - * @access public - */ - public static function _goto($a_target) - { - global $DIC; - - $ilAccess = $DIC->access(); - $lng = $DIC->language(); - - if ($ilAccess->checkAccess("visible", "", $a_target) || - $ilAccess->checkAccess("read", "", $a_target)) - { - $_GET["baseClass"] = "ilObjSurveyQuestionPoolGUI"; - $_GET["cmd"] = "infoScreen"; - $_GET["ref_id"] = $a_target; - include_once("ilias.php"); - exit; - } - else if ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) - { - ilUtil::sendFailure(sprintf($lng->txt("msg_no_perm_read_item"), - ilObject::_lookupTitle(ilObject::_lookupObjId($a_target))), true); - ilObjectGUI::_gotoRepositoryRoot(); - } - } + /** + * @var ilNavigationHistory + */ + protected $nav_history; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var ilLogger + */ + protected $log; + + public $defaultscript; + + /** + * Constructor + * @access public + */ + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + $this->nav_history = $DIC["ilNavigationHistory"]; + $this->tpl = $DIC["tpl"]; + $this->user = $DIC->user(); + $this->toolbar = $DIC->toolbar(); + $this->error = $DIC["ilErr"]; + $this->locator = $DIC["ilLocator"]; + $this->help = $DIC["ilHelp"]; + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + + $this->type = "spl"; + $lng->loadLanguageModule("survey"); + $this->ctrl = $ilCtrl; + $this->ctrl->saveParameter($this, array("ref_id")); + + parent::__construct("", $_GET["ref_id"], true, false); + + $this->log = ilLoggerFactory::getLogger('svy'); + } + + /** + * execute command + */ + public function executeCommand() + { + $ilNavigationHistory = $this->nav_history; + + if (!$this->checkPermissionBool("visible") && + !$this->checkPermissionBool("read")) { + $this->checkPermission("read"); + } + + // add entry to navigation history + if (!$this->getCreationMode() && + $this->checkPermissionBool("read")) { + $ilNavigationHistory->addItem( + $this->ref_id, + "ilias.php?baseClass=ilObjSurveyQuestionPoolGUI&cmd=questions&ref_id=" . $this->ref_id, + "spl" + ); + } + + $this->tpl->addCss(ilUtil::getStyleSheetLocation("output", "survey.css", "Modules/Survey"), "screen"); + $this->prepareOutput(); + + $cmd = $this->ctrl->getCmd("questions"); + $next_class = $this->ctrl->getNextClass($this); + $this->ctrl->setReturn($this, "questions"); + if ($_GET["q_id"] < 1) { + $q_type = ($_POST["sel_question_types"] != "") + ? $_POST["sel_question_types"] + : $_GET["sel_question_types"]; + } + + $this->log->debug("- cmd=" . $cmd . " next_class=" . $next_class); + switch ($next_class) { + case 'ilobjectmetadatagui': + $this->checkPermission('write'); + include_once 'Services/Object/classes/class.ilObjectMetaDataGUI.php'; + $md_gui = new ilObjectMetaDataGUI($this->object); + $this->ctrl->forwardCommand($md_gui); + break; + + case 'ilpermissiongui': + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $ret =&$this->ctrl->forwardCommand($perm_gui); + break; + + case "ilsurveyphrasesgui": + include_once("./Modules/SurveyQuestionPool/classes/class.ilSurveyPhrasesGUI.php"); + $phrases_gui = new ilSurveyPhrasesGUI($this); + $ret =&$this->ctrl->forwardCommand($phrases_gui); + break; + + case 'ilobjectcopygui': + include_once './Services/Object/classes/class.ilObjectCopyGUI.php'; + $cp = new ilObjectCopyGUI($this); + $cp->setType('spl'); + $this->ctrl->forwardCommand($cp); + break; + + case 'ilinfoscreengui': + $this->infoScreenForward(); + break; + + case "ilcommonactiondispatchergui": + include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); + $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); + $this->ctrl->forwardCommand($gui); + break; + + case "": + $cmd.= "Object"; + $ret =&$this->$cmd(); + break; + + default: + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php"; + $q_gui = SurveyQuestionGUI::_getQuestionGUI($q_type, $_GET["q_id"]); + $this->log->debug("- This is the switch/case default, going to question id =" . $_GET["q_id"]); + // $q_gui->object->setObjId($this->object->getId()); + $q_gui->setQuestionTabs(); + $ret =&$this->ctrl->forwardCommand($q_gui); + + // not on create + if ($q_gui->object->isComplete()) { + $this->tpl->setTitle($this->lng->txt("question") . ": " . $q_gui->object->getTitle()); + } + break; + } + if (strtolower($_GET["baseClass"]) != "iladministrationgui" && + $this->getCreationMode() != true) { + $this->tpl->show(); + } + } + + protected function initEditForm() + { + $obj_service = $this->object_service; + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this, 'properties')); + $form->setTitle($this->lng->txt("properties")); + $form->setMultipart(false); + $form->setId("properties"); + + // title + $title = new ilTextInputGUI($this->lng->txt('title'), 'title'); + $title->setSubmitFormOnEnter(true); + $title->setValue($this->object->getTitle()); + $title->setSize(min(40, ilObject::TITLE_LENGTH)); + $title->setMaxLength(ilObject::TITLE_LENGTH); + $title->setRequired(true); + $form->addItem($title); + + // desc + $desc = new ilTextAreaInputGUI($this->lng->txt('description'), 'desc'); + $desc->setValue($this->object->getLongDescription()); + $desc->setRows(2); + $desc->setCols(40); + $form->addItem($desc); + + // online + $online = new ilCheckboxInputGUI($this->lng->txt("spl_online_property"), "online"); + $online->setInfo($this->lng->txt("spl_online_property_description")); + $online->setChecked($this->object->getOnline()); + $form->addItem($online); + + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($this->lng->txt('obj_presentation')); + $form->addItem($section); + + // tile image + $obj_service->commonSettings()->legacyForm($form, $this->object)->addTileImage(); + + + $form->addCommandButton("saveProperties", $this->lng->txt("save")); + + return $form; + } + + /** + * Questionpool properties + */ + public function propertiesObject(ilPropertyFormGUI $a_form = null) + { + if (!$a_form) { + $a_form = $this->initEditForm(); + } + + $this->tpl->setVariable("ADM_CONTENT", $a_form->getHTML()); + } + + /** + * Save questionpool properties + */ + public function savePropertiesObject() + { + $obj_service = $this->object_service; + $form = $this->initEditForm(); + if ($form->checkInput()) { + $this->object->setTitle($form->getInput("title")); + $this->object->setDescription($form->getInput("desc")); + $this->object->setOnline((int) $form->getInput("online")); + + $this->object->saveToDb(); + + // tile image + $obj_service->commonSettings()->legacyForm($form, $this->object)->saveTileImage(); + + + ilUtil::sendSuccess($this->lng->txt("saved_successfully"), true); + $this->ctrl->redirect($this, "properties"); + } + + $form->setValuesByPost(); + $this->propertiesObject($form); + } + + + /** + * Copies checked questions in the questionpool to a clipboard + */ + public function copyObject() + { + if (count($_POST["q_id"]) > 0) { + foreach ($_POST["q_id"] as $key => $value) { + $this->object->copyToClipboard($value); + } + ilUtil::sendInfo($this->lng->txt("spl_copy_insert_clipboard"), true); + } else { + ilUtil::sendInfo($this->lng->txt("spl_copy_select_none"), true); + } + $this->ctrl->redirect($this, "questions"); + } + + /** + * mark one or more question objects for moving + */ + public function moveObject() + { + if (count($_POST["q_id"]) > 0) { + foreach ($_POST["q_id"] as $key => $value) { + $this->object->moveToClipboard($value); + } + ilUtil::sendInfo($this->lng->txt("spl_move_insert_clipboard"), true); + } else { + ilUtil::sendInfo($this->lng->txt("spl_move_select_none"), true); + } + $this->ctrl->redirect($this, "questions"); + } + + /** + * export a question + */ + public function exportQuestionObject() + { + if (is_array($_POST['q_id']) && count($_POST['q_id']) > 0) { + $this->createExportFileObject($_POST['q_id']); + } else { + ilUtil::sendInfo($this->lng->txt("qpl_export_select_none")); + $this->questionsObject(); + } + } + + /** + * Creates a confirmation form to delete questions from the question pool + */ + public function deleteQuestionsObject() + { + $this->checkPermission('write'); + + // create an array of all checked checkboxes + $checked_questions = $_POST['q_id']; + if (count($checked_questions) == 0) { + ilUtil::sendInfo($this->lng->txt("qpl_delete_select_none")); + $this->questionsObject(); + return; + } + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setHeaderText($this->lng->txt("qpl_confirm_delete_questions")); + + $cgui->setFormAction($this->ctrl->getFormAction($this)); + $cgui->setCancel($this->lng->txt("cancel"), "cancelDeleteQuestions"); + $cgui->setConfirm($this->lng->txt("confirm"), "confirmDeleteQuestions"); + + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + $infos = $this->object->getQuestionInfos($checked_questions); + foreach ($infos as $data) { + $txt = $data["title"] . " (" . + SurveyQuestion::_getQuestionTypeName($data["type_tag"]) . ")"; + if ($data["description"]) { + $txt .= "
" . $data["description"] . "
"; + } + + $cgui->addItem("q_id[]", $data["id"], $txt); + } + + $this->tpl->setContent($cgui->getHTML()); + } + + /** + * delete questions + */ + public function confirmDeleteQuestionsObject() + { + // delete questions after confirmation + ilUtil::sendSuccess($this->lng->txt("qpl_questions_deleted"), true); + foreach ($_POST['q_id'] as $q_id) { + $this->object->removeQuestion($q_id); + } + $this->ctrl->redirect($this, "questions"); + } + + /** + * cancel delete questions + */ + public function cancelDeleteQuestionsObject() + { + // delete questions after confirmation + $this->ctrl->redirect($this, "questions"); + } + + /** + * paste questios from the clipboard into the question pool + */ + public function pasteObject() + { + if (array_key_exists("spl_clipboard", $_SESSION)) { + $this->object->pasteFromClipboard(); + } else { + ilUtil::sendInfo($this->lng->txt("spl_paste_no_objects"), true); + } + $this->ctrl->redirect($this, "questions"); + } + + /** + * display the import form to import questions into the questionpool + */ + public function importQuestionsObject() + { + $tpl = $this->tpl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this, "uploadQuestions")); + $form->setTitle($this->lng->txt("import_question")); + + include_once("./Services/Form/classes/class.ilFileInputGUI.php"); + $fi = new ilFileInputGUI($this->lng->txt("select_file"), "qtidoc"); + $fi->setSuffixes(array("xml", "zip")); + $fi->setRequired(true); + $form->addItem($fi); + + $form->addCommandButton("uploadQuestions", $this->lng->txt("import")); + $form->addCommandButton("questions", $this->lng->txt("cancel")); + + $tpl->setContent($form->getHTML()); + } + + /** + * imports question(s) into the questionpool + */ + public function uploadQuestionsObject() + { + // check if file was uploaded + $source = $_FILES["qtidoc"]["tmp_name"]; + $error = 0; + if (($source == 'none') || (!$source) || $_FILES["qtidoc"]["error"] > UPLOAD_ERR_OK) { + $error = 1; + } + // check correct file type + if (!$error && strpos("xml", $_FILES["qtidoc"]["type"]) !== false) { + $error = 1; + } + if (!$error) { + // import file into questionpool + // create import directory + $this->object->createImportDirectory(); + + // copy uploaded file to import directory + $full_path = $this->object->getImportDirectory() . "/" . $_FILES["qtidoc"]["name"]; + + ilUtil::moveUploadedFile( + $_FILES["qtidoc"]["tmp_name"], + $_FILES["qtidoc"]["name"], + $full_path + ); + $source = $full_path; + $this->object->importObject($source, true); + unlink($source); + } + $this->ctrl->redirect($this, "questions"); + } + + public function filterQuestionBrowserObject() + { + include_once "./Modules/SurveyQuestionPool/classes/tables/class.ilSurveyQuestionsTableGUI.php"; + $table_gui = new ilSurveyQuestionsTableGUI($this, 'questions'); + $table_gui->writeFilterToSession(); + $this->ctrl->redirect($this, 'questions'); + } + + public function resetfilterQuestionBrowserObject() + { + include_once "./Modules/SurveyQuestionPool/classes/tables/class.ilSurveyQuestionsTableGUI.php"; + $table_gui = new ilSurveyQuestionsTableGUI($this, 'questions'); + $table_gui->resetFilter(); + $this->ctrl->redirect($this, 'questions'); + } + + /** + * list questions of question pool + */ + public function questionsObject($arrFilter = null) + { + $ilUser = $this->user; + $ilToolbar = $this->toolbar; + + $this->object->purgeQuestions(); + + $_SESSION['q_id_table_nav'] = $_GET['q_id_table_nav']; + + if ($this->checkPermissionBool('write')) { + include_once "Services/Form/classes/class.ilSelectInputGUI.php"; + $qtypes = new ilSelectInputGUI("", "sel_question_types"); + $qtypes->setValue($ilUser->getPref("svy_lastquestiontype")); + $ilToolbar->addInputItem($qtypes); + + $options = array(); + foreach (ilObjSurveyQuestionPool::_getQuestionTypes() as $translation => $data) { + $options[$data["type_tag"]] = $translation; + } + $qtypes->setOptions($options); + + $ilToolbar->setFormAction($this->ctrl->getFormAction($this)); + + include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; + $button = ilSubmitButton::getInstance(); + $button->setCaption("svy_create_question"); + $button->setCommand("createQuestion"); + $ilToolbar->addButtonInstance($button); + + $ilToolbar->addSeparator(); + + $button = ilSubmitButton::getInstance(); + $button->setCaption("import"); + $button->setCommand("importQuestions"); + $ilToolbar->addButtonInstance($button); + } + + include_once "./Modules/SurveyQuestionPool/classes/tables/class.ilSurveyQuestionsTableGUI.php"; + $table_gui = new ilSurveyQuestionsTableGUI($this, 'questions', (($this->checkPermissionBool('write') ? true : false))); + $table_gui->setEditable($this->checkPermissionBool('write')); + $arrFilter = array(); + foreach ($table_gui->getFilterItems() as $item) { + if ($item->getValue() !== false) { + $arrFilter[$item->getPostVar()] = $item->getValue(); + } + } + $table_gui->setData($this->object->getQuestionsData($arrFilter)); + $this->tpl->setContent($table_gui->getHTML()); + } + + public function updateObject() + { + $this->update = $this->object->update(); + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + } + + public function afterSave(ilObject $a_new_object) + { + // always send a message + ilUtil::sendSuccess($this->lng->txt("object_added"), true); + + ilUtil::redirect("ilias.php?ref_id=" . $a_new_object->getRefId() . + "&baseClass=ilObjSurveyQuestionPoolGUI"); + } + + /* + * list all export files + */ + public function exportObject() + { + $ilToolbar = $this->toolbar; + + $ilToolbar->addButton( + $this->lng->txt('create_export_file'), + $this->ctrl->getLinkTarget($this, 'createExportFile') + ); + + include_once "./Modules/SurveyQuestionPool/classes/tables/class.ilSurveyQuestionPoolExportTableGUI.php"; + $table_gui = new ilSurveyQuestionPoolExportTableGUI($this, 'export'); + $export_dir = $this->object->getExportDirectory(); + $export_files = $this->object->getExportFiles($export_dir); + $data = array(); + foreach ($export_files as $exp_file) { + $file_arr = explode("__", $exp_file); + array_push($data, array('file' => $exp_file, 'date' => ilDatePresentation::formatDate(new ilDateTime($file_arr[0], IL_CAL_UNIX)), 'size' => filesize($export_dir . "/" . $exp_file))); + } + $table_gui->setData($data); + $this->tpl->setContent($table_gui->getHTML()); + } + + /** + * create export file + */ + public function createExportFileObject($questions = null) + { + $this->checkPermission("write"); + + include_once("./Modules/SurveyQuestionPool/classes/class.ilSurveyQuestionpoolExport.php"); + $survey_exp = new ilSurveyQuestionpoolExport($this->object); + $survey_exp->buildExportFile($questions); + $this->ctrl->redirect($this, "export"); + } + + /** + * download export file + */ + public function downloadExportFileObject() + { + if (!isset($_POST["file"])) { + ilUtil::sendInfo($this->lng->txt("no_checkbox"), true); + $this->ctrl->redirect($this, "export"); + } + + if (count($_POST["file"]) > 1) { + ilUtil::sendInfo($this->lng->txt("select_max_one_item"), true); + $this->ctrl->redirect($this, "export"); + } + + + $export_dir = $this->object->getExportDirectory(); + + $file = basename($_POST["file"][0]); + + ilUtil::deliverFile($export_dir . "/" . $file, $file); + } + + /** + * confirmation screen for export file deletion + */ + public function confirmDeleteExportFileObject() + { + if (!isset($_POST["file"])) { + ilUtil::sendInfo($this->lng->txt("no_checkbox"), true); + $this->ctrl->redirect($this, "export"); + } + + ilUtil::sendQuestion($this->lng->txt("info_delete_sure")); + include_once "./Modules/SurveyQuestionPool/classes/tables/class.ilSurveyQuestionPoolExportTableGUI.php"; + $table_gui = new ilSurveyQuestionPoolExportTableGUI($this, 'export', true); + $export_dir = $this->object->getExportDirectory(); + $data = array(); + foreach ($_POST['file'] as $exp_file) { + $file_arr = explode("__", $exp_file); + array_push($data, array('file' => $exp_file, 'date' => ilDatePresentation::formatDate(new ilDateTime($file_arr[0], IL_CAL_UNIX)), 'size' => filesize($export_dir . "/" . $exp_file))); + } + $table_gui->setData($data); + $this->tpl->setVariable('ADM_CONTENT', $table_gui->getHTML()); + } + + + /** + * cancel deletion of export files + */ + public function cancelDeleteExportFileObject() + { + ilSession::clear("ilExportFiles"); + $this->ctrl->redirect($this, "export"); + } + + /** + * delete export files + */ + public function deleteExportFileObject() + { + $export_dir = $this->object->getExportDirectory(); + foreach ($_POST['file'] as $file) { + $file = basename($file); + + $exp_file = $export_dir . "/" . $file; + $exp_dir = $export_dir . "/" . substr($file, 0, strlen($file) - 4); + if (@is_file($exp_file)) { + unlink($exp_file); + } + if (@is_dir($exp_dir)) { + ilUtil::delDir($exp_dir); + } + } + $this->ctrl->redirect($this, "export"); + } + + protected function initImportForm($a_new_type) + { + $form = parent::initImportForm($a_new_type); + $form->getItemByPostVar('importfile')->setSuffixes(array("zip", "xml")); + + return $form; + } + + protected function initCreationForms($a_new_type) + { + $form = $this->initImportForm($a_new_type); + + $forms = array(self::CFORM_NEW => $this->initCreateForm($a_new_type), + self::CFORM_IMPORT => $form); + + return $forms; + } + + /** + * form for new survey object import + */ + public function importFileObject($parent_id = null, $a_catch_errors = true) + { + $tpl = $this->tpl; + $ilErr = $this->error; + + if (!$parent_id) { + $parent_id = $_GET["ref_id"]; + } + $new_type = $_REQUEST["new_type"]; + + // create permission is already checked in createObject. This check here is done to prevent hacking attempts + if (!$this->checkPermissionBool("create", "", $new_type)) { + $ilErr->raiseError($this->lng->txt("no_create_permission")); + } + + $this->lng->loadLanguageModule($new_type); + $this->ctrl->setParameter($this, "new_type", $new_type); + + $form = $this->initImportForm($new_type); + if ($form->checkInput()) { + include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"; + $newObj = new ilObjSurveyQuestionPool(); + $newObj->setType($new_type); + $newObj->setTitle("dummy"); + $newObj->create(true); + $this->putObjectInTree($newObj); + + $newObj->createImportDirectory(); + + // copy uploaded file to import directory + $upload = $_FILES["importfile"]; + $file = pathinfo($upload["name"]); + $full_path = $newObj->getImportDirectory() . "/" . $upload["name"]; + ilUtil::moveUploadedFile( + $upload["tmp_name"], + $upload["name"], + $full_path + ); + + // import qti data + $qtiresult = $newObj->importObject($full_path); + + ilUtil::sendSuccess($this->lng->txt("object_imported"), true); + ilUtil::redirect("ilias.php?ref_id=" . $newObj->getRefId() . + "&baseClass=ilObjSurveyQuestionPoolGUI"); + } + + // display form to correct errors + $form->setValuesByPost(); + $tpl->setContent($form->getHtml()); + } + + /** + * create new question + */ + public function &createQuestionObject() + { + $ilUser = $this->user; + + $ilUser->writePref("svy_lastquestiontype", $_POST["sel_question_types"]); + + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php"; + $q_gui =&SurveyQuestionGUI::_getQuestionGUI($_POST["sel_question_types"]); + $q_gui->object->setObjId($this->object->getId()); + $q_gui->object->createNewQuestion(); + + $this->ctrl->setParameterByClass(get_class($q_gui), "q_id", $q_gui->object->getId()); + $this->ctrl->setParameterByClass(get_class($q_gui), "sel_question_types", $_POST["sel_question_types"]); + $this->ctrl->redirectByClass(get_class($q_gui), "editQuestion"); + } + + /** + * create preview of object + */ + public function &previewObject() + { + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php"; + $q_gui =&SurveyQuestionGUI::_getQuestionGUI("", $_GET["preview"]); + $this->ctrl->setParameterByClass(get_class($q_gui), "sel_question_types", $q_gui->getQuestionType()); + $this->ctrl->setParameterByClass(get_class($q_gui), "q_id", $_GET["preview"]); + $this->ctrl->redirectByClass(get_class($q_gui), "preview"); + } + + /** + * 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 infoScreenObject() + { + $this->ctrl->setCmd("showSummary"); + $this->ctrl->setCmdClass("ilinfoscreengui"); + $this->infoScreenForward(); + } + + /** + * show information screen + */ + public function infoScreenForward() + { + if (!$this->checkPermissionBool("read")) { + $this->checkPermission("visible"); + } + + include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); + $info = new ilInfoScreenGUI($this); + $info->enablePrivateNotes(); + + // standard meta data + $info->addMetaDataSections($this->object->getId(), 0, $this->object->getType()); + + $this->ctrl->forwardCommand($info); + } + + public function addLocatorItems() + { + $ilLocator = $this->locator; + switch ($this->ctrl->getCmd()) { + case "create": + case "importFile": + case "cancel": + break; + default: + $ilLocator->addItem($this->object->getTitle(), $this->ctrl->getLinkTarget($this, ""), "", $_GET["ref_id"]); + break; + } + if ((int) $_GET["q_id"]) { + $q_id = (int) $_GET["q_id"]; + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + $q_type = SurveyQuestion::_getQuestionType($q_id) . "GUI"; + $q_title = SurveyQuestion::_getTitle($q_id); + if ($q_title) { + // not on create + $this->ctrl->setParameterByClass($q_type, "q_id", $q_id); + $ilLocator->addItem( + $q_title, + $this->ctrl->getLinkTargetByClass($q_type, "editQuestion") + ); + } + } + } + + /** + * adds tabs to tab gui object + * + * @param object $tabs_gui ilTabsGUI object + */ + public function getTabs() + { + $ilHelp = $this->help; + + $ilHelp->setScreenIdComponent("spl"); + + $next_class = $this->ctrl->getNextClass($this); + switch ($next_class) { + case "": + case "ilpermissiongui": + case "ilobjectmetadatagui": + case "ilsurveyphrasesgui": + break; + default: + return; + break; + } + + // questions + $force_active = (($this->ctrl->getCmdClass() == "" && + $this->ctrl->getCmd() != "properties" && $this->ctrl->getCmd() != "infoScreen") || + $this->ctrl->getCmd() == "") + ? true + : false; + if (!$force_active) { + if (is_array($_GET["sort"])) { + $force_active = true; + } + } + + if ($this->checkPermissionBool("read")) { + $this->tabs_gui->addTarget( + "survey_questions", + $this->ctrl->getLinkTarget($this, 'questions'), + array("questions", "filterQuestionBrowser", "filter", "reset", "createQuestion", + "importQuestions", "deleteQuestions", "copy", "paste", + "exportQuestions", "confirmDeleteQuestions", "cancelDeleteQuestions", + "confirmPasteQuestions", "cancelPasteQuestions", "uploadQuestions", + "editQuestion", "addMaterial", "removeMaterial", "save", "cancel", + "cancelExplorer", "linkChilds", "addGIT", "addST", "addPG", "preview", + "moveCategory", "deleteCategory", "addPhrase", "addCategory", "savePhrase", + "addSelectedPhrase", "cancelViewPhrase", "confirmSavePhrase", "cancelSavePhrase", + "insertBeforeCategory", "insertAfterCategory", "confirmDeleteCategory", + "cancelDeleteCategory", "categories", "saveCategories", + "savePhrase", "addPhrase" + ), + array("ilobjsurveyquestionpoolgui", "ilsurveyphrasesgui"), + "", + $force_active + ); + + $this->tabs_gui->addTarget( + "info_short", + $this->ctrl->getLinkTarget($this, "infoScreen"), + array("infoScreen", "showSummary") + ); + } + + if ($this->checkPermissionBool('write')) { + // properties + $this->tabs_gui->addTarget( + "settings", + $this->ctrl->getLinkTarget($this, 'properties'), + array("properties", "saveProperties"), + "", + "" + ); + + // manage phrases + $this->tabs_gui->addTarget( + "manage_phrases", + $this->ctrl->getLinkTargetByClass("ilsurveyphrasesgui", "phrases"), + array("phrases", "deletePhrase", "confirmDeletePhrase", "cancelDeletePhrase", "editPhrase", "newPhrase", "saveEditPhrase", "phraseEditor"), + "ilsurveyphrasesgui", + "" + ); + + // meta data + include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php"; + $mdgui = new ilObjectMetaDataGUI($this->object); + $mdtab = $mdgui->getTab(); + if ($mdtab) { + $this->tabs_gui->addTarget( + "meta_data", + $mdtab, + "", + "ilmdeditorgui" + ); + } + + // export + $this->tabs_gui->addTarget( + "export", + $this->ctrl->getLinkTarget($this, 'export'), + array("export", "createExportFile", "confirmDeleteExportFile", + "downloadExportFile", "cancelDeleteExportFile", "deleteExportFile"), + "", + "" + ); + } + + if ($this->checkPermissionBool("edit_permission")) { + $this->tabs_gui->addTarget( + "perm_settings", + $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm"), + array("perm","info","owner"), + 'ilpermissiongui' + ); + } + } + + /** + * Save obligatory states + */ + public function saveObligatoryObject() + { + $obligatory = array(); + foreach ($_POST as $key => $value) { + if (preg_match("/obligatory_(\d+)/", $key, $matches)) { + $obligatory[]= $matches[1]; + } + } + $this->object->setObligatoryStates($obligatory); + + ilUtil::sendSuccess($this->lng->txt('msg_obj_modified'), true); + $this->ctrl->redirect($this, "questions"); + } + + /** + * Redirect script to call a survey question pool reference id + * + * @param integer $a_target The reference id of the question pool + * @access public + */ + public static function _goto($a_target) + { + global $DIC; + + $ilAccess = $DIC->access(); + $lng = $DIC->language(); + + if ($ilAccess->checkAccess("visible", "", $a_target) || + $ilAccess->checkAccess("read", "", $a_target)) { + $_GET["baseClass"] = "ilObjSurveyQuestionPoolGUI"; + $_GET["cmd"] = "infoScreen"; + $_GET["ref_id"] = $a_target; + include_once("ilias.php"); + exit; + } elseif ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) { + ilUtil::sendFailure(sprintf( + $lng->txt("msg_no_perm_read_item"), + ilObject::_lookupTitle(ilObject::_lookupObjId($a_target)) + ), true); + ilObjectGUI::_gotoRepositoryRoot(); + } + } } // END class.ilObjSurveyQuestionPoolGUI -?> diff --git a/Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPoolListGUI.php b/Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPoolListGUI.php index 0f415fd28fe9d6857d4d2de62c6c677d1781855e..4ed7551bc52b8b43e88ce8a27092432ebfc015c8 100644 --- a/Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPoolListGUI.php +++ b/Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPoolListGUI.php @@ -1,24 +1,24 @@ delete_enabled = true; - $this->cut_enabled = true; - $this->copy_enabled = true; - $this->subscribe_enabled = true; - $this->link_enabled = true; - $this->info_screen_enabled = true; - $this->type = "spl"; - $this->gui_class_name = "ilobjsurveyquestionpoolgui"; - - // general commands array - include_once("./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPoolAccess.php"); - $this->commands = ilObjSurveyQUestionPoolAccess::_getCommands(); - } - - - /** - * inititialize new item - * - * @param int $a_ref_id reference id - * @param int $a_obj_id object id - * @param string $a_title title - * @param string $a_description description - */ - function initItem($a_ref_id, $a_obj_id, $a_title = "", $a_description = "") - { - parent::initItem($a_ref_id, $a_obj_id, $a_title, $a_description); - } - - - /** - * Get command target frame - * - * @param string $a_cmd command - * - * @return string command target frame - */ - function getCommandFrame($a_cmd) - { - switch($a_cmd) - { - case "": - case "questions": - include_once "./Services/UICore/classes/class.ilFrameTargetInfo.php"; - $frame = ilFrameTargetInfo::_getFrame("MainContent"); - break; - - default: - } - - return $frame; - } - - - - /** - * Get item properties - * - * @return array array of property arrays: - * "alert" (boolean) => display as an alert property (usually in red) - * "property" (string) => property name - * "value" (string) => property value - */ - function getProperties() - { - $lng = $this->lng; - $ilUser = $this->user; - - $props = array(); - - include_once("./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"); - if (!ilObjSurveyQuestionPool::_lookupOnline($this->obj_id)) - { - $props[] = array("alert" => true, "property" => $lng->txt("status"), - "value" => $lng->txt("offline")); - } - return $props; - } - - - /** - * Get command link url. - * - * @param int $a_ref_id reference id - * @param string $a_cmd command - * - */ - function getCommandLink($a_cmd) - { - // separate method for this line - $cmd_link = "ilias.php?baseClass=ilObjSurveyQuestionPoolGUI&ref_id=" . $this->ref_id . "&cmd=$a_cmd"; - - return $cmd_link; - } - - - + /** + * initialisation + */ + public function init() + { + $this->delete_enabled = true; + $this->cut_enabled = true; + $this->copy_enabled = true; + $this->subscribe_enabled = true; + $this->link_enabled = true; + $this->info_screen_enabled = true; + $this->type = "spl"; + $this->gui_class_name = "ilobjsurveyquestionpoolgui"; + + // general commands array + include_once("./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPoolAccess.php"); + $this->commands = ilObjSurveyQUestionPoolAccess::_getCommands(); + } + + + /** + * inititialize new item + * + * @param int $a_ref_id reference id + * @param int $a_obj_id object id + * @param string $a_title title + * @param string $a_description description + */ + public function initItem($a_ref_id, $a_obj_id, $a_title = "", $a_description = "") + { + parent::initItem($a_ref_id, $a_obj_id, $a_title, $a_description); + } + + + /** + * Get command target frame + * + * @param string $a_cmd command + * + * @return string command target frame + */ + public function getCommandFrame($a_cmd) + { + switch ($a_cmd) { + case "": + case "questions": + include_once "./Services/UICore/classes/class.ilFrameTargetInfo.php"; + $frame = ilFrameTargetInfo::_getFrame("MainContent"); + break; + + default: + } + + return $frame; + } + + + + /** + * Get item properties + * + * @return array array of property arrays: + * "alert" (boolean) => display as an alert property (usually in red) + * "property" (string) => property name + * "value" (string) => property value + */ + public function getProperties() + { + $lng = $this->lng; + $ilUser = $this->user; + + $props = array(); + + include_once("./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"); + if (!ilObjSurveyQuestionPool::_lookupOnline($this->obj_id)) { + $props[] = array("alert" => true, "property" => $lng->txt("status"), + "value" => $lng->txt("offline")); + } + return $props; + } + + + /** + * Get command link url. + * + * @param int $a_ref_id reference id + * @param string $a_cmd command + * + */ + public function getCommandLink($a_cmd) + { + // separate method for this line + $cmd_link = "ilias.php?baseClass=ilObjSurveyQuestionPoolGUI&ref_id=" . $this->ref_id . "&cmd=$a_cmd"; + + return $cmd_link; + } } // END class.ilObjTestListGUI -?> diff --git a/Modules/SurveyQuestionPool/classes/class.ilSurveyCategory.php b/Modules/SurveyQuestionPool/classes/class.ilSurveyCategory.php index 15944ec8826280f5c87c20d11e82bdd72c886390..807642674204124fc6c9eb06c34851cb8f935ab7 100644 --- a/Modules/SurveyQuestionPool/classes/class.ilSurveyCategory.php +++ b/Modules/SurveyQuestionPool/classes/class.ilSurveyCategory.php @@ -30,59 +30,53 @@ * @version $Id$ * @ingroup ModulesSurveyQuestionPool */ -class ilSurveyCategory +class ilSurveyCategory { - private $arrData; - - /** - * ilSurveyPhrases constructor - */ - function __construct($title = null, $other = 0, $neutral = 0, $label = null, $scale = null ) - { - $this->arrData = array( - "title" => $title, - "other" => $other, - "neutral" => $neutral, - "label" => $label, - "scale" => $scale - ); - } - - /** - * Object getter - */ - public function __get($value) - { - switch ($value) - { - case 'other': - case 'neutral': - return ($this->arrData[$value]) ? 1 : 0; - break; - default: - if (array_key_exists($value, $this->arrData)) - { - return $this->arrData[$value]; - } - else - { - return null; - } - break; - } - } + private $arrData; + + /** + * ilSurveyPhrases constructor + */ + public function __construct($title = null, $other = 0, $neutral = 0, $label = null, $scale = null) + { + $this->arrData = array( + "title" => $title, + "other" => $other, + "neutral" => $neutral, + "label" => $label, + "scale" => $scale + ); + } + + /** + * Object getter + */ + public function __get($value) + { + switch ($value) { + case 'other': + case 'neutral': + return ($this->arrData[$value]) ? 1 : 0; + break; + 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; - } - } + /** + * Object setter + */ + public function __set($key, $value) + { + switch ($key) { + default: + $this->arrData[$key] = $value; + break; + } + } } -?> diff --git a/Modules/SurveyQuestionPool/classes/class.ilSurveyMaterial.php b/Modules/SurveyQuestionPool/classes/class.ilSurveyMaterial.php index 5090458de478f6b1a62cfc63268440ee53d677a5..90c3c5392d49494afb1a43b908d4e3a6e8f0a2e4 100644 --- a/Modules/SurveyQuestionPool/classes/class.ilSurveyMaterial.php +++ b/Modules/SurveyQuestionPool/classes/class.ilSurveyMaterial.php @@ -28,53 +28,49 @@ * @version $Id$ * @ingroup ModulesSurveyQuestionPool */ -class ilSurveyMaterial +class ilSurveyMaterial { - const MATERIAL_TYPE_INTERNALLINK = 0; - const MATERIAL_TYPE_URL = 1; - const MATERIAL_TYPE_FILE = 2; - - protected $data; + const MATERIAL_TYPE_INTERNALLINK = 0; + const MATERIAL_TYPE_URL = 1; + const MATERIAL_TYPE_FILE = 2; + + protected $data; - /** - * ilSurveyMaterial constructor - */ - function __construct() - { - $this->data = array( - 'type' => self::MATERIAL_TYPE_INTERNALLINK, - 'internal_link' => '', - 'title' => '', - 'url' => '', - 'filename' => '' - ); - } + /** + * ilSurveyMaterial constructor + */ + public function __construct() + { + $this->data = array( + 'type' => self::MATERIAL_TYPE_INTERNALLINK, + 'internal_link' => '', + 'title' => '', + 'url' => '', + 'filename' => '' + ); + } - public function __set($name, $value) - { - $this->data[$name] = $value; - } + public function __set($name, $value) + { + $this->data[$name] = $value; + } - public function __get($name) - { - if (array_key_exists($name, $this->data)) - { - switch ($name) - { - case 'internal_link': - case 'import_id': - case 'material_title': - case 'text_material': - case 'file_material': - case 'external_link': - return (strlen($this->data[$name])) ? $this->data[$name] : NULL; - break; - default: - return $this->data[$name]; - } - } - return null; - } + public function __get($name) + { + if (array_key_exists($name, $this->data)) { + switch ($name) { + case 'internal_link': + case 'import_id': + case 'material_title': + case 'text_material': + case 'file_material': + case 'external_link': + return (strlen($this->data[$name])) ? $this->data[$name] : null; + break; + default: + return $this->data[$name]; + } + } + return null; + } } - -?> diff --git a/Modules/SurveyQuestionPool/classes/class.ilSurveyPhrases.php b/Modules/SurveyQuestionPool/classes/class.ilSurveyPhrases.php index a36f9eb6b98ca1053314e5330954f884d368401e..4e7a9b049d43de969533f7fa14f2436499a53193 100755 --- a/Modules/SurveyQuestionPool/classes/class.ilSurveyPhrases.php +++ b/Modules/SurveyQuestionPool/classes/class.ilSurveyPhrases.php @@ -31,238 +31,228 @@ * @version $Id$ * @ingroup ModulesSurveyQuestionPool */ -class ilSurveyPhrases +class ilSurveyPhrases { - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - protected $arrData; - - /** - * ilSurveyPhrases constructor - */ - function __construct() - { - global $DIC; + protected $arrData; + + /** + * ilSurveyPhrases constructor + */ + public function __construct() + { + global $DIC; - $this->db = $DIC->database(); - $this->user = $DIC->user(); - $this->arrData = array(); - } - - /** - * Gets the available phrases from the database - * - * @param boolean $useronly Returns only the user defined phrases if set to true. The default is false. - * @return array All available phrases as key/value pairs - */ - public static function _getAvailablePhrases($useronly = 0) - { - global $DIC; + $this->db = $DIC->database(); + $this->user = $DIC->user(); + $this->arrData = array(); + } + + /** + * Gets the available phrases from the database + * + * @param boolean $useronly Returns only the user defined phrases if set to true. The default is false. + * @return array All available phrases as key/value pairs + */ + public static function _getAvailablePhrases($useronly = 0) + { + global $DIC; - $ilUser = $DIC->user(); - global $DIC; + $ilUser = $DIC->user(); + global $DIC; - $ilDB = $DIC->database(); - global $DIC; + $ilDB = $DIC->database(); + global $DIC; - $lng = $DIC->language(); - - $phrases = array(); - $result = $ilDB->queryF("SELECT * FROM svy_phrase WHERE defaultvalue = %s OR owner_fi = %s ORDER BY title", - array('text', 'integer'), - array('1', $ilUser->getId()) - ); - while ($row = $ilDB->fetchObject($result)) - { - if (($row->defaultvalue == 1) and ($row->owner_fi == 0)) - { - if (!$useronly) - { - $phrases[$row->phrase_id] = array( - "title" => $lng->txt($row->title), - "owner" => $row->owner_fi, - "org_title" => $row->title - ); - } - } - else - { - if ($ilUser->getId() == $row->owner_fi) - { - $phrases[$row->phrase_id] = array( - "title" => $row->title, - "owner" => $row->owner_fi - ); - } - } - } - return $phrases; - } - - /** - * Gets the available categories for a given phrase - * - * @param integer $phrase_id The database id of the given phrase - * @return array All available categories - */ - public static function _getCategoriesForPhrase($phrase_id) - { - global $DIC; + $lng = $DIC->language(); + + $phrases = array(); + $result = $ilDB->queryF( + "SELECT * FROM svy_phrase WHERE defaultvalue = %s OR owner_fi = %s ORDER BY title", + array('text', 'integer'), + array('1', $ilUser->getId()) + ); + while ($row = $ilDB->fetchObject($result)) { + if (($row->defaultvalue == 1) and ($row->owner_fi == 0)) { + if (!$useronly) { + $phrases[$row->phrase_id] = array( + "title" => $lng->txt($row->title), + "owner" => $row->owner_fi, + "org_title" => $row->title + ); + } + } else { + if ($ilUser->getId() == $row->owner_fi) { + $phrases[$row->phrase_id] = array( + "title" => $row->title, + "owner" => $row->owner_fi + ); + } + } + } + return $phrases; + } + + /** + * Gets the available categories for a given phrase + * + * @param integer $phrase_id The database id of the given phrase + * @return array All available categories + */ + public static function _getCategoriesForPhrase($phrase_id) + { + global $DIC; - $ilDB = $DIC->database(); - global $DIC; + $ilDB = $DIC->database(); + global $DIC; - $lng = $DIC->language(); - - $categories = array(); - $result = $ilDB->queryF("SELECT svy_category.* FROM svy_category, svy_phrase_cat WHERE svy_phrase_cat.category_fi = svy_category.category_id AND svy_phrase_cat.phrase_fi = %s ORDER BY svy_phrase_cat.sequence", - array('integer'), - array($phrase_id) - ); - while ($row = $ilDB->fetchObject($result)) - { - if (($row->defaultvalue == 1) and ($row->owner_fi == 0)) - { - $categories[$row->category_id] = $lng->txt($row->title); - } - else - { - $categories[$row->category_id] = $row->title; - } - } - return $categories; - } - - /** - * Delete phrases from the database - * - * @param array $phrase_array An array containing phrase id's to delete - */ - function deletePhrases($phrase_array) - { - $ilDB = $this->db; - - if ((is_array($phrase_array)) && (count($phrase_array))) - { - $affectedRows = $ilDB->manipulate("DELETE FROM svy_phrase WHERE " . $ilDB->in('phrase_id', $phrase_array, false, 'integer')); - $affectedRows = $ilDB->manipulate("DELETE FROM svy_phrase_cat WHERE " . $ilDB->in('phrase_fi', $phrase_array, false, 'integer')); - } - } - - /** - * Saves a set of categories to a default phrase - * - * @param array $phrases The database ids of the seleted phrases - * @param string $title The title of the default phrase - * @access public - */ - function updatePhrase($phrase_id) - { - $ilUser = $this->user; - $ilDB = $this->db; + $lng = $DIC->language(); + + $categories = array(); + $result = $ilDB->queryF( + "SELECT svy_category.* FROM svy_category, svy_phrase_cat WHERE svy_phrase_cat.category_fi = svy_category.category_id AND svy_phrase_cat.phrase_fi = %s ORDER BY svy_phrase_cat.sequence", + array('integer'), + array($phrase_id) + ); + while ($row = $ilDB->fetchObject($result)) { + if (($row->defaultvalue == 1) and ($row->owner_fi == 0)) { + $categories[$row->category_id] = $lng->txt($row->title); + } else { + $categories[$row->category_id] = $row->title; + } + } + return $categories; + } + + /** + * Delete phrases from the database + * + * @param array $phrase_array An array containing phrase id's to delete + */ + public function deletePhrases($phrase_array) + { + $ilDB = $this->db; + + if ((is_array($phrase_array)) && (count($phrase_array))) { + $affectedRows = $ilDB->manipulate("DELETE FROM svy_phrase WHERE " . $ilDB->in('phrase_id', $phrase_array, false, 'integer')); + $affectedRows = $ilDB->manipulate("DELETE FROM svy_phrase_cat WHERE " . $ilDB->in('phrase_fi', $phrase_array, false, 'integer')); + } + } + + /** + * Saves a set of categories to a default phrase + * + * @param array $phrases The database ids of the seleted phrases + * @param string $title The title of the default phrase + * @access public + */ + public function updatePhrase($phrase_id) + { + $ilUser = $this->user; + $ilDB = $this->db; - $affectedRows = $ilDB->manipulateF("UPDATE svy_phrase SET title = %s, tstamp = %s WHERE phrase_id = %s", - array('text','integer','integer'), - array($this->title, time(), $phrase_id) - ); + $affectedRows = $ilDB->manipulateF( + "UPDATE svy_phrase SET title = %s, tstamp = %s WHERE phrase_id = %s", + array('text','integer','integer'), + array($this->title, time(), $phrase_id) + ); - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_phrase_cat WHERE phrase_fi = %s", - array('integer'), - array($phrase_id) - ); + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_phrase_cat WHERE phrase_fi = %s", + array('integer'), + array($phrase_id) + ); - $counter = 1; - for ($i = 0; $i < $this->categories->getCategoryCount(); $i++) - { - $cat = $this->categories->getCategory($i); - $next_id = $ilDB->nextId('svy_category'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_category (category_id, title, defaultvalue, owner_fi, tstamp, neutral) VALUES (%s, %s, %s, %s, %s, %s)", - array('integer','text','text','integer','integer','text'), - array($next_id, $cat->title, 1, $ilUser->getId(), time(), $cat->neutral) - ); - $category_id = $next_id; - $next_id = $ilDB->nextId('svy_phrase_cat'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_phrase_cat (phrase_category_id, phrase_fi, category_fi, sequence) VALUES (%s, %s, %s, %s)", - array('integer', 'integer', 'integer','integer'), - array($next_id, $phrase_id, $category_id, $counter) - ); - $counter++; - } - } - - /** - * Saves a set of categories to a default phrase - */ - public function savePhrase() - { - $ilUser = $this->user; - $ilDB = $this->db; + $counter = 1; + for ($i = 0; $i < $this->categories->getCategoryCount(); $i++) { + $cat = $this->categories->getCategory($i); + $next_id = $ilDB->nextId('svy_category'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_category (category_id, title, defaultvalue, owner_fi, tstamp, neutral) VALUES (%s, %s, %s, %s, %s, %s)", + array('integer','text','text','integer','integer','text'), + array($next_id, $cat->title, 1, $ilUser->getId(), time(), $cat->neutral) + ); + $category_id = $next_id; + $next_id = $ilDB->nextId('svy_phrase_cat'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_phrase_cat (phrase_category_id, phrase_fi, category_fi, sequence) VALUES (%s, %s, %s, %s)", + array('integer', 'integer', 'integer','integer'), + array($next_id, $phrase_id, $category_id, $counter) + ); + $counter++; + } + } + + /** + * Saves a set of categories to a default phrase + */ + public function savePhrase() + { + $ilUser = $this->user; + $ilDB = $this->db; - $next_id = $ilDB->nextId('svy_phrase'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_phrase (phrase_id, title, defaultvalue, owner_fi, tstamp) VALUES (%s, %s, %s, %s, %s)", - array('integer','text','text','integer','integer'), - array($next_id, $this->title, 1, $ilUser->getId(), time()) - ); - $phrase_id = $next_id; + $next_id = $ilDB->nextId('svy_phrase'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_phrase (phrase_id, title, defaultvalue, owner_fi, tstamp) VALUES (%s, %s, %s, %s, %s)", + array('integer','text','text','integer','integer'), + array($next_id, $this->title, 1, $ilUser->getId(), time()) + ); + $phrase_id = $next_id; - $counter = 1; - for ($i = 0; $i < $this->categories->getCategoryCount(); $i++) - { - $cat = $this->categories->getCategory($i); - $next_id = $ilDB->nextId('svy_category'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_category (category_id, title, defaultvalue, owner_fi, tstamp, neutral) VALUES (%s, %s, %s, %s, %s, %s)", - array('integer','text','text','integer','integer','text'), - array($next_id, $cat->title, 1, $ilUser->getId(), time(), $cat->neutral) - ); - $category_id = $next_id; - $next_id = $ilDB->nextId('svy_phrase_cat'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_phrase_cat (phrase_category_id, phrase_fi, category_fi, sequence) VALUES (%s, %s, %s, %s)", - array('integer', 'integer', 'integer','integer'), - array($next_id, $phrase_id, $category_id, $counter) - ); - $counter++; - } - } - - /** - * Object getter - */ - public function __get($value) - { - switch ($value) - { - default: - if (array_key_exists($value, $this->arrData)) - { - return $this->arrData[$value]; - } - else - { - return null; - } - break; - } - } + $counter = 1; + for ($i = 0; $i < $this->categories->getCategoryCount(); $i++) { + $cat = $this->categories->getCategory($i); + $next_id = $ilDB->nextId('svy_category'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_category (category_id, title, defaultvalue, owner_fi, tstamp, neutral) VALUES (%s, %s, %s, %s, %s, %s)", + array('integer','text','text','integer','integer','text'), + array($next_id, $cat->title, 1, $ilUser->getId(), time(), $cat->neutral) + ); + $category_id = $next_id; + $next_id = $ilDB->nextId('svy_phrase_cat'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_phrase_cat (phrase_category_id, phrase_fi, category_fi, sequence) VALUES (%s, %s, %s, %s)", + array('integer', 'integer', 'integer','integer'), + array($next_id, $phrase_id, $category_id, $counter) + ); + $counter++; + } + } + + /** + * 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; - } - } + /** + * Object setter + */ + public function __set($key, $value) + { + switch ($key) { + default: + $this->arrData[$key] = $value; + break; + } + } } -?> diff --git a/Modules/SurveyQuestionPool/classes/class.ilSurveyPhrasesGUI.php b/Modules/SurveyQuestionPool/classes/class.ilSurveyPhrasesGUI.php index 791c33044b67c02495a48577867bedf64575ab8b..d52dff09a822856d3e0a7b6e3face2ddd96207cb 100755 --- a/Modules/SurveyQuestionPool/classes/class.ilSurveyPhrasesGUI.php +++ b/Modules/SurveyQuestionPool/classes/class.ilSurveyPhrasesGUI.php @@ -24,7 +24,7 @@ /** * Survey phrases GUI class * -* The ilSurveyPhrases GUI class creates the GUI output for +* The ilSurveyPhrases GUI class creates the GUI output for * survey phrases (collections of survey categories) * of ordinal survey question types. * @@ -34,355 +34,335 @@ */ class ilSurveyPhrasesGUI { - /** - * @var ilRbacSystem - */ - protected $rbacsystem; + /** + * @var ilRbacSystem + */ + protected $rbacsystem; - /** - * @var ilToolbarGUI - */ - protected $toolbar; + /** + * @var ilToolbarGUI + */ + protected $toolbar; - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; - var $object; - var $gui_object; - var $lng; - var $tpl; - var $ctrl; - var $tree; - var $ref_id; - - /** - * ilSurveyPhrasesGUI constructor - * - */ - function __construct($a_object) - { - global $DIC; + public $object; + public $gui_object; + public $lng; + public $tpl; + public $ctrl; + public $tree; + public $ref_id; + + /** + * ilSurveyPhrasesGUI constructor + * + */ + public function __construct($a_object) + { + global $DIC; - $this->rbacsystem = $DIC->rbac()->system(); - $this->toolbar = $DIC->toolbar(); - $this->db = $DIC->database(); - $lng = $DIC->language(); - $tpl = $DIC["tpl"]; - $ilCtrl = $DIC->ctrl(); - $tree = $DIC->repositoryTree(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->toolbar = $DIC->toolbar(); + $this->db = $DIC->database(); + $lng = $DIC->language(); + $tpl = $DIC["tpl"]; + $ilCtrl = $DIC->ctrl(); + $tree = $DIC->repositoryTree(); - include_once "./Modules/SurveyQuestionPool/classes/class.ilSurveyPhrases.php"; - $this->lng = $lng; - $this->tpl = $tpl; - $this->ctrl = $ilCtrl; - $this->gui_object = $a_object; - $this->object = new ilSurveyPhrases(); - $this->tree = $tree; - $this->ref_id = $a_object->ref_id; - $this->ctrl->saveParameter($this, "p_id"); - } - - /** - * execute command - */ - public function executeCommand() - { - $cmd = $this->ctrl->getCmd(); - $next_class = $this->ctrl->getNextClass($this); + include_once "./Modules/SurveyQuestionPool/classes/class.ilSurveyPhrases.php"; + $this->lng = $lng; + $this->tpl = $tpl; + $this->ctrl = $ilCtrl; + $this->gui_object = $a_object; + $this->object = new ilSurveyPhrases(); + $this->tree = $tree; + $this->ref_id = $a_object->ref_id; + $this->ctrl->saveParameter($this, "p_id"); + } + + /** + * execute command + */ + public function executeCommand() + { + $cmd = $this->ctrl->getCmd(); + $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->getCommand($cmd); - switch($next_class) - { - default: - $ret =& $this->$cmd(); - break; - } - return $ret; - } + $cmd = $this->getCommand($cmd); + switch ($next_class) { + default: + $ret =&$this->$cmd(); + break; + } + return $ret; + } - /** - * Retrieves the ilCtrl command - */ - public function getCommand($cmd) - { - return $cmd; - } - - /** - * Creates a confirmation form to delete personal phases from the database - */ - public function deletePhrase() - { - ilUtil::sendInfo(); + /** + * Retrieves the ilCtrl command + */ + public function getCommand($cmd) + { + return $cmd; + } + + /** + * Creates a confirmation form to delete personal phases from the database + */ + public function deletePhrase() + { + ilUtil::sendInfo(); - $checked_phrases = $_POST['phrase']; - if (count($checked_phrases)) - { - ilUtil::sendQuestion($this->lng->txt("qpl_confirm_delete_phrases")); - $this->deletePhrasesForm($checked_phrases); - return; - } - else - { - ilUtil::sendInfo($this->lng->txt("qpl_delete_phrase_select_none")); - $this->phrases(); - return; - } - } + $checked_phrases = $_POST['phrase']; + if (count($checked_phrases)) { + ilUtil::sendQuestion($this->lng->txt("qpl_confirm_delete_phrases")); + $this->deletePhrasesForm($checked_phrases); + return; + } else { + ilUtil::sendInfo($this->lng->txt("qpl_delete_phrase_select_none")); + $this->phrases(); + return; + } + } - /** - * Displays a form to manage the user created phrases - * - * @access public - */ - public function phrases() - { - $rbacsystem = $this->rbacsystem; - $ilToolbar = $this->toolbar; - - $this->ctrl->setParameter($this, "p_id", ""); - - if ($rbacsystem->checkAccess("write", $this->ref_id)) - { - include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; - $button = ilLinkButton::getInstance(); - $button->setCaption("phrase_new"); - $button->setUrl($this->ctrl->getLinkTarget($this, "newPhrase")); - $ilToolbar->addButtonInstance($button); - - include_once "./Modules/SurveyQuestionPool/classes/tables/class.ilSurveyPhrasesTableGUI.php"; - $table_gui = new ilSurveyPhrasesTableGUI($this, 'phrases'); - $phrases =& ilSurveyPhrases::_getAvailablePhrases(1); - $data = array(); - foreach ($phrases as $phrase_id => $phrase_array) - { - $categories =& ilSurveyPhrases::_getCategoriesForPhrase($phrase_id); - array_push($data, array('phrase_id' => $phrase_id, 'phrase' => $phrase_array["title"], 'answers' => join($categories, ", "))); - } - $table_gui->setData($data); - $this->tpl->setContent($table_gui->getHTML()); - } - else - { - ilUtil::sendInfo($this->lng->txt("cannot_manage_phrases")); - } - } + /** + * Displays a form to manage the user created phrases + * + * @access public + */ + public function phrases() + { + $rbacsystem = $this->rbacsystem; + $ilToolbar = $this->toolbar; + + $this->ctrl->setParameter($this, "p_id", ""); + + if ($rbacsystem->checkAccess("write", $this->ref_id)) { + include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; + $button = ilLinkButton::getInstance(); + $button->setCaption("phrase_new"); + $button->setUrl($this->ctrl->getLinkTarget($this, "newPhrase")); + $ilToolbar->addButtonInstance($button); + + include_once "./Modules/SurveyQuestionPool/classes/tables/class.ilSurveyPhrasesTableGUI.php"; + $table_gui = new ilSurveyPhrasesTableGUI($this, 'phrases'); + $phrases =&ilSurveyPhrases::_getAvailablePhrases(1); + $data = array(); + foreach ($phrases as $phrase_id => $phrase_array) { + $categories =&ilSurveyPhrases::_getCategoriesForPhrase($phrase_id); + array_push($data, array('phrase_id' => $phrase_id, 'phrase' => $phrase_array["title"], 'answers' => join($categories, ", "))); + } + $table_gui->setData($data); + $this->tpl->setContent($table_gui->getHTML()); + } else { + ilUtil::sendInfo($this->lng->txt("cannot_manage_phrases")); + } + } - /** - * cancel delete phrases - */ - public function cancelDeletePhrase() - { - $this->ctrl->redirect($this, "phrases"); - } - - /** - * confirm delete phrases - */ - public function confirmDeletePhrase() - { - $phrases = $_POST['phrase']; - $this->object->deletePhrases($phrases); - ilUtil::sendSuccess($this->lng->txt("qpl_phrases_deleted"), true); - $this->ctrl->redirect($this, "phrases"); - } + /** + * cancel delete phrases + */ + public function cancelDeletePhrase() + { + $this->ctrl->redirect($this, "phrases"); + } + + /** + * confirm delete phrases + */ + public function confirmDeletePhrase() + { + $phrases = $_POST['phrase']; + $this->object->deletePhrases($phrases); + ilUtil::sendSuccess($this->lng->txt("qpl_phrases_deleted"), true); + $this->ctrl->redirect($this, "phrases"); + } - protected function getCategoriesForPhrase($phrase_id) - { - $ilDB = $this->db; - - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyCategories.php"; - $categories = new SurveyCategories(); - $result = $ilDB->queryF("SELECT svy_category.title, svy_category.neutral, svy_phrase_cat.sequence FROM svy_phrase_cat, svy_category WHERE svy_phrase_cat.phrase_fi = %s AND svy_phrase_cat.category_fi = svy_category.category_id ORDER BY svy_phrase_cat.sequence ASC", - array('integer'), - array($phrase_id) - ); - if ($result->numRows() > 0) - { - while ($data = $ilDB->fetchAssoc($result)) - { - $categories->addCategory($data["title"], 0, $data["neutral"], null, $data['sequence']); - } - } - return $categories; - } - - protected function getPhraseTitle($phrase_id) - { - $ilDB = $this->db; - - $result = $ilDB->queryF("SELECT svy_phrase.title FROM svy_phrase WHERE svy_phrase.phrase_id = %s", - array('integer'), - array($phrase_id) - ); - if ($result->numRows() > 0) - { - $row = $ilDB->fetchAssoc($result); - return $row['title']; - } - return null; - } - - /** - * Creates a confirmation form to delete personal phases from the database - * - * @param array $checked_phrases An array with the id's of the phrases checked for deletion - */ - public function deletePhrasesForm($checked_phrases) - { - include_once "./Modules/SurveyQuestionPool/classes/tables/class.ilSurveyPhrasesTableGUI.php"; - $table_gui = new ilSurveyPhrasesTableGUI($this, 'phrases', true); - $phrases =& ilSurveyPhrases::_getAvailablePhrases(1); - $data = array(); - foreach ($checked_phrases as $phrase_id) - { - $phrase_array = $phrases[$phrase_id]; - $categories =& ilSurveyPhrases::_getCategoriesForPhrase($phrase_id); - array_push($data, array('phrase_id' => $phrase_id, 'phrase' => $phrase_array["title"], 'answers' => join($categories, ", "))); - } - $table_gui->setData($data); - $this->tpl->setVariable('ADM_CONTENT', $table_gui->getHTML()); - } - - public function cancelEditPhrase() - { - $this->ctrl->redirect($this, 'phrases'); - } - - public function saveEditPhrase() - { - $result = $this->writePostData(); - if ($result == 0) - { - if ($_GET['p_id']) - { - $this->object->updatePhrase($_GET['p_id']); - ilUtil::sendSuccess($this->lng->txt('phrase_saved'), true); - } - else - { - $this->object->savePhrase(); - ilUtil::sendSuccess($this->lng->txt('phrase_added'), true); - } - $this->ctrl->redirect($this, 'phrases'); - } - } + protected function getCategoriesForPhrase($phrase_id) + { + $ilDB = $this->db; + + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyCategories.php"; + $categories = new SurveyCategories(); + $result = $ilDB->queryF( + "SELECT svy_category.title, svy_category.neutral, svy_phrase_cat.sequence FROM svy_phrase_cat, svy_category WHERE svy_phrase_cat.phrase_fi = %s AND svy_phrase_cat.category_fi = svy_category.category_id ORDER BY svy_phrase_cat.sequence ASC", + array('integer'), + array($phrase_id) + ); + if ($result->numRows() > 0) { + while ($data = $ilDB->fetchAssoc($result)) { + $categories->addCategory($data["title"], 0, $data["neutral"], null, $data['sequence']); + } + } + return $categories; + } + + protected function getPhraseTitle($phrase_id) + { + $ilDB = $this->db; + + $result = $ilDB->queryF( + "SELECT svy_phrase.title FROM svy_phrase WHERE svy_phrase.phrase_id = %s", + array('integer'), + array($phrase_id) + ); + if ($result->numRows() > 0) { + $row = $ilDB->fetchAssoc($result); + return $row['title']; + } + return null; + } + + /** + * Creates a confirmation form to delete personal phases from the database + * + * @param array $checked_phrases An array with the id's of the phrases checked for deletion + */ + public function deletePhrasesForm($checked_phrases) + { + include_once "./Modules/SurveyQuestionPool/classes/tables/class.ilSurveyPhrasesTableGUI.php"; + $table_gui = new ilSurveyPhrasesTableGUI($this, 'phrases', true); + $phrases =&ilSurveyPhrases::_getAvailablePhrases(1); + $data = array(); + foreach ($checked_phrases as $phrase_id) { + $phrase_array = $phrases[$phrase_id]; + $categories =&ilSurveyPhrases::_getCategoriesForPhrase($phrase_id); + array_push($data, array('phrase_id' => $phrase_id, 'phrase' => $phrase_array["title"], 'answers' => join($categories, ", "))); + } + $table_gui->setData($data); + $this->tpl->setVariable('ADM_CONTENT', $table_gui->getHTML()); + } + + public function cancelEditPhrase() + { + $this->ctrl->redirect($this, 'phrases'); + } + + public function saveEditPhrase() + { + $result = $this->writePostData(); + if ($result == 0) { + if ($_GET['p_id']) { + $this->object->updatePhrase($_GET['p_id']); + ilUtil::sendSuccess($this->lng->txt('phrase_saved'), true); + } else { + $this->object->savePhrase(); + ilUtil::sendSuccess($this->lng->txt('phrase_added'), true); + } + $this->ctrl->redirect($this, 'phrases'); + } + } - /** - * Evaluates a posted edit form and writes the form data in the question object - * - * @return integer A positive value, if one of the required fields wasn't set, else 0 - * @access private - */ - function writePostData($always = false) - { - $ilDB = $this->db; - $hasErrors = (!$always) ? $this->phraseEditor(true) : false; - if (!$hasErrors) - { - $this->object->title = $_POST["title"]; - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyCategories.php"; - $categories = new SurveyCategories(); - foreach ($_POST['answers']['answer'] as $key => $value) - { - if (strlen($value)) $categories->addCategory($value, $_POST['answers']['other'][$key], 0, null, $_POST['answers']['scale'][$key]); - } - if (strlen($_POST['answers']['neutral'])) - { - $categories->addCategory($_POST['answers']['neutral'], 0, 1, null, $_POST['answers_neutral_scale']); - } - $this->object->categories = $categories; - return 0; - } - else - { - return 1; - } - } - - public function newPhrase() - { - $this->ctrl->redirect($this, 'phraseEditor'); - } - - public function editPhrase() - { - if (!array_key_exists('phrase', $_POST)) - { - ilUtil::sendFailure($this->lng->txt('no_phrase_selected'), true); - $this->ctrl->redirect($this, 'phrases'); - } - if ((array_key_exists('phrase', $_POST)) && count($_POST['phrase']) > 1) - { - ilUtil::sendFailure($this->lng->txt('select_max_one_item'), true); - $this->ctrl->redirect($this, 'phrases'); - } - $phrase_id = (array_key_exists('phrase', $_POST)) ? $_POST['phrase'][key($_POST['phrase'])] : null; - if ($phrase_id) - { - $this->ctrl->setParameter($this, 'p_id', $phrase_id); - } - $this->ctrl->redirect($this, 'phraseEditor'); - } + /** + * Evaluates a posted edit form and writes the form data in the question object + * + * @return integer A positive value, if one of the required fields wasn't set, else 0 + * @access private + */ + public function writePostData($always = false) + { + $ilDB = $this->db; + $hasErrors = (!$always) ? $this->phraseEditor(true) : false; + if (!$hasErrors) { + $this->object->title = $_POST["title"]; + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyCategories.php"; + $categories = new SurveyCategories(); + foreach ($_POST['answers']['answer'] as $key => $value) { + if (strlen($value)) { + $categories->addCategory($value, $_POST['answers']['other'][$key], 0, null, $_POST['answers']['scale'][$key]); + } + } + if (strlen($_POST['answers']['neutral'])) { + $categories->addCategory($_POST['answers']['neutral'], 0, 1, null, $_POST['answers_neutral_scale']); + } + $this->object->categories = $categories; + return 0; + } else { + return 1; + } + } + + public function newPhrase() + { + $this->ctrl->redirect($this, 'phraseEditor'); + } + + public function editPhrase() + { + if (!array_key_exists('phrase', $_POST)) { + ilUtil::sendFailure($this->lng->txt('no_phrase_selected'), true); + $this->ctrl->redirect($this, 'phrases'); + } + if ((array_key_exists('phrase', $_POST)) && count($_POST['phrase']) > 1) { + ilUtil::sendFailure($this->lng->txt('select_max_one_item'), true); + $this->ctrl->redirect($this, 'phrases'); + } + $phrase_id = (array_key_exists('phrase', $_POST)) ? $_POST['phrase'][key($_POST['phrase'])] : null; + if ($phrase_id) { + $this->ctrl->setParameter($this, 'p_id', $phrase_id); + } + $this->ctrl->redirect($this, 'phraseEditor'); + } - public function phraseEditor($checkonly = FALSE) - { - $save = (strcmp($this->ctrl->getCmd(), "saveEditPhrase") == 0) ? TRUE : FALSE; + public function phraseEditor($checkonly = false) + { + $save = (strcmp($this->ctrl->getCmd(), "saveEditPhrase") == 0) ? true : false; - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this, 'phraseEditor')); - $form->setTitle($this->lng->txt('edit_phrase')); - $form->setMultipart(FALSE); - $form->setTableWidth("100%"); - $form->setId("phraseeditor"); + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this, 'phraseEditor')); + $form->setTitle($this->lng->txt('edit_phrase')); + $form->setMultipart(false); + $form->setTableWidth("100%"); + $form->setId("phraseeditor"); - $phrase_id = $_GET['p_id']; + $phrase_id = $_GET['p_id']; - // title - $title = new ilTextInputGUI($this->lng->txt("title"), "title"); - $title->setValue($this->getPhraseTitle($phrase_id)); - $title->setRequired(TRUE); - $form->addItem($title); + // title + $title = new ilTextInputGUI($this->lng->txt("title"), "title"); + $title->setValue($this->getPhraseTitle($phrase_id)); + $title->setRequired(true); + $form->addItem($title); - // Answers - include_once "./Modules/SurveyQuestionPool/classes/class.ilCategoryWizardInputGUI.php"; - $answers = new ilCategoryWizardInputGUI($this->lng->txt("answers"), "answers"); - $answers->setRequired(true); - $answers->setAllowMove(true); - $answers->setShowWizard(false ); - $answers->setShowSavePhrase(false); - $answers->setUseOtherAnswer(false); - $answers->setShowNeutralCategory(true); - $answers->setNeutralCategoryTitle($this->lng->txt('matrix_neutral_answer')); - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyCategories.php"; - $categories =& $this->getCategoriesForPhrase($phrase_id); - if (!$categories->getCategoryCount()) - { - $categories->addCategory(""); - } - $answers->setValues($categories); - $answers->setDisabledScale(true); - $form->addItem($answers); + // Answers + include_once "./Modules/SurveyQuestionPool/classes/class.ilCategoryWizardInputGUI.php"; + $answers = new ilCategoryWizardInputGUI($this->lng->txt("answers"), "answers"); + $answers->setRequired(true); + $answers->setAllowMove(true); + $answers->setShowWizard(false); + $answers->setShowSavePhrase(false); + $answers->setUseOtherAnswer(false); + $answers->setShowNeutralCategory(true); + $answers->setNeutralCategoryTitle($this->lng->txt('matrix_neutral_answer')); + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyCategories.php"; + $categories =&$this->getCategoriesForPhrase($phrase_id); + if (!$categories->getCategoryCount()) { + $categories->addCategory(""); + } + $answers->setValues($categories); + $answers->setDisabledScale(true); + $form->addItem($answers); - $form->addCommandButton("saveEditPhrase", $this->lng->txt("save")); - $form->addCommandButton("cancelEditPhrase", $this->lng->txt("cancel")); + $form->addCommandButton("saveEditPhrase", $this->lng->txt("save")); + $form->addCommandButton("cancelEditPhrase", $this->lng->txt("cancel")); - $errors = false; + $errors = false; - if ($save) - { - $form->setValuesByPost(); - $errors = !$form->checkInput(); - $form->setValuesByPost(); // again, because checkInput now performs the whole stripSlashes handling and we need this if we don't want to have duplication of backslashes - if ($errors) $checkonly = false; - } - - if (!$checkonly) $this->tpl->setVariable("ADM_CONTENT", $form->getHTML()); - return $errors; - } + if ($save) { + $form->setValuesByPost(); + $errors = !$form->checkInput(); + $form->setValuesByPost(); // again, because checkInput now performs the whole stripSlashes handling and we need this if we don't want to have duplication of backslashes + if ($errors) { + $checkonly = false; + } + } + if (!$checkonly) { + $this->tpl->setVariable("ADM_CONTENT", $form->getHTML()); + } + return $errors; + } } -?> diff --git a/Modules/SurveyQuestionPool/classes/class.ilSurveyQuestionPoolExporter.php b/Modules/SurveyQuestionPool/classes/class.ilSurveyQuestionPoolExporter.php index fea97a3892e786e232a201b3c858f8ebe6f011bc..e5f2e1ba4b84ac5b31a06a45398a53298934235f 100644 --- a/Modules/SurveyQuestionPool/classes/class.ilSurveyQuestionPoolExporter.php +++ b/Modules/SurveyQuestionPool/classes/class.ilSurveyQuestionPoolExporter.php @@ -12,38 +12,38 @@ include_once("./Services/Export/classes/class.ilXmlExporter.php"); */ class ilSurveyQuestionPoolExporter extends ilXmlExporter { - private $ds; + private $ds; - /** - * Initialisation - */ - function init() - { - } + /** + * Initialisation + */ + public function init() + { + } - /** - * Get xml representation - * - * @param string entity - * @param string target release - * @param string id - * @return string xml string - */ - public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) - { - $refs = ilObject::_getAllReferences($a_id); - $sql_ref_id = current($refs); - - include_once './Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php'; - $spl = new ilObjSurveyQuestionPool($a_id,false); - $spl->loadFromDb(); - - include_once("./Modules/SurveyQuestionPool/classes/class.ilSurveyQuestionpoolExport.php"); - $spl_exp = new ilSurveyQuestionpoolExport($spl, 'xml'); - $zip = $spl_exp->buildExportFile(); - $GLOBALS['ilLog']->write(__METHOD__.': Created zip file '.$zip); - } + /** + * Get xml representation + * + * @param string entity + * @param string target release + * @param string id + * @return string xml string + */ + public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) + { + $refs = ilObject::_getAllReferences($a_id); + $sql_ref_id = current($refs); + + include_once './Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php'; + $spl = new ilObjSurveyQuestionPool($a_id, false); + $spl->loadFromDb(); + + include_once("./Modules/SurveyQuestionPool/classes/class.ilSurveyQuestionpoolExport.php"); + $spl_exp = new ilSurveyQuestionpoolExport($spl, 'xml'); + $zip = $spl_exp->buildExportFile(); + $GLOBALS['ilLog']->write(__METHOD__ . ': Created zip file ' . $zip); + } /** * Get tail dependencies @@ -53,7 +53,7 @@ class ilSurveyQuestionPoolExporter extends ilXmlExporter * @param array ids * @return array array of array with keys "component", entity", "ids" */ - function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) + public function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) { $deps = []; @@ -69,23 +69,21 @@ class ilSurveyQuestionPoolExporter extends ilXmlExporter /** - * Returns schema versions that the component can export to. - * ILIAS chooses the first one, that has min/max constraints which - * fit to the target release. Please put the newest on top. - * - * @return - */ - function getValidSchemaVersions($a_entity) - { - return array ( - "4.1.0" => array( - "namespace" => "http://www.ilias.de/Modules/SurveyQuestionPool/htlm/4_1", - "xsd_file" => "ilias_spl_4_1.xsd", - "uses_dataset" => false, - "min" => "4.1.0", - "max" => "") - ); - } + * Returns schema versions that the component can export to. + * ILIAS chooses the first one, that has min/max constraints which + * fit to the target release. Please put the newest on top. + * + * @return + */ + public function getValidSchemaVersions($a_entity) + { + return array( + "4.1.0" => array( + "namespace" => "http://www.ilias.de/Modules/SurveyQuestionPool/htlm/4_1", + "xsd_file" => "ilias_spl_4_1.xsd", + "uses_dataset" => false, + "min" => "4.1.0", + "max" => "") + ); + } } - -?> \ No newline at end of file diff --git a/Modules/SurveyQuestionPool/classes/class.ilSurveyQuestionPoolImporter.php b/Modules/SurveyQuestionPool/classes/class.ilSurveyQuestionPoolImporter.php index 4719cbb46d89ab3c1024600dfd728939258bc479..16c56590bdd85d7981ecfb764a7812b7292eaabd 100644 --- a/Modules/SurveyQuestionPool/classes/class.ilSurveyQuestionPoolImporter.php +++ b/Modules/SurveyQuestionPool/classes/class.ilSurveyQuestionPoolImporter.php @@ -12,60 +12,54 @@ include_once("./Services/Export/classes/class.ilXmlImporter.php"); */ class ilSurveyQuestionPoolImporter extends ilXmlImporter { - /** - * Import XML - * - * @param - * @return - */ - function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) - { - // Container import => test object already created - if($new_id = $a_mapping->getMapping('Services/Container','objs',$a_id)) - { - $newObj = ilObjectFactory::getInstanceByObjId($new_id,false); - #$newObj->setImportDirectory(dirname(rtrim($this->getImportDirectory(),'/'))); - } - else // case ii, non container - { - // Shouldn't happen - $GLOBALS['ilLog']->write(__METHOD__.': Called in non container mode'); - return false; - } - - - include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"; - - list($xml_file) = $this->parseXmlFileNames(); + /** + * Import XML + * + * @param + * @return + */ + public function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) + { + // Container import => test object already created + if ($new_id = $a_mapping->getMapping('Services/Container', 'objs', $a_id)) { + $newObj = ilObjectFactory::getInstanceByObjId($new_id, false); + #$newObj->setImportDirectory(dirname(rtrim($this->getImportDirectory(),'/'))); + } else { // case ii, non container + // Shouldn't happen + $GLOBALS['ilLog']->write(__METHOD__ . ': Called in non container mode'); + return false; + } + + + include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"; + + list($xml_file) = $this->parseXmlFileNames(); - if(!@file_exists($xml_file)) - { - $GLOBALS['ilLog']->write(__METHOD__.': Cannot find xml definition: '. $xml_file); - return false; - } + if (!@file_exists($xml_file)) { + $GLOBALS['ilLog']->write(__METHOD__ . ': Cannot find xml definition: ' . $xml_file); + return false; + } - // import qti data - $qtiresult = $newObj->importObject($xml_file); + // import qti data + $qtiresult = $newObj->importObject($xml_file); - $a_mapping->addMapping("Modules/SurveyQuestionPool", "spl", $a_id, $newObj->getId()); + $a_mapping->addMapping("Modules/SurveyQuestionPool", "spl", $a_id, $newObj->getId()); - return true; - } - - - /** - * Create qti and xml file name - * @return array - */ - protected function parseXmlFileNames() - { - $GLOBALS['ilLog']->write(__METHOD__.': '.$this->getImportDirectory()); - - $basename = basename($this->getImportDirectory()); - $xml = $this->getImportDirectory().'/'.$basename.'.xml'; - - return array($xml); - } + return true; + } + + + /** + * Create qti and xml file name + * @return array + */ + protected function parseXmlFileNames() + { + $GLOBALS['ilLog']->write(__METHOD__ . ': ' . $this->getImportDirectory()); + + $basename = basename($this->getImportDirectory()); + $xml = $this->getImportDirectory() . '/' . $basename . '.xml'; + + return array($xml); + } } - -?> \ No newline at end of file diff --git a/Modules/SurveyQuestionPool/classes/class.ilSurveyQuestionPoolModule.php b/Modules/SurveyQuestionPool/classes/class.ilSurveyQuestionPoolModule.php index bcea4989838048ee05b4981879ad0542298d5557..66ac6d156120761cae51f8824bb3549215cb3f3e 100644 --- a/Modules/SurveyQuestionPool/classes/class.ilSurveyQuestionPoolModule.php +++ b/Modules/SurveyQuestionPool/classes/class.ilSurveyQuestionPoolModule.php @@ -1,24 +1,24 @@ diff --git a/Modules/SurveyQuestionPool/classes/class.ilSurveyQuestionpoolExport.php b/Modules/SurveyQuestionPool/classes/class.ilSurveyQuestionpoolExport.php index 2bbbf7689dc43def2be12cbc147285d13bca43bc..91cfc9bdae524155ea21f271920880279f21aec7 100755 --- a/Modules/SurveyQuestionPool/classes/class.ilSurveyQuestionpoolExport.php +++ b/Modules/SurveyQuestionPool/classes/class.ilSurveyQuestionpoolExport.php @@ -1,24 +1,24 @@ database(); + $ilDB = $DIC->database(); - $this->spl_obj = $a_spl_obj; - - $this->db = $ilDB; - $this->mode = $a_mode; - - $this->inst_id = IL_INST_ID; + $this->spl_obj = $a_spl_obj; + + $this->db = $ilDB; + $this->mode = $a_mode; + + $this->inst_id = IL_INST_ID; - $date = time(); - switch($this->mode) - { - default: - $this->export_dir = $this->spl_obj->getExportDirectory(); - $this->subdir = $date."__".$this->inst_id."__". - "spl"."_".$this->spl_obj->getId(); - $this->filename = $this->subdir.".xml"; - break; - } - } + $date = time(); + switch ($this->mode) { + default: + $this->export_dir = $this->spl_obj->getExportDirectory(); + $this->subdir = $date . "__" . $this->inst_id . "__" . + "spl" . "_" . $this->spl_obj->getId(); + $this->filename = $this->subdir . ".xml"; + break; + } + } - function getInstId() - { - return $this->inst_id; - } + public function getInstId() + { + return $this->inst_id; + } - /** - * build export file (complete zip file) - * - * @access public - * @return - */ - function buildExportFile($questions = null) - { - switch ($this->mode) - { - default: - return $this->buildExportFileXML($questions); - break; - } - } + /** + * build export file (complete zip file) + * + * @access public + * @return + */ + public function buildExportFile($questions = null) + { + switch ($this->mode) { + default: + return $this->buildExportFileXML($questions); + break; + } + } - /** - * build xml export file - */ - function buildExportFileXML($questions = null) - { - // create directories - $this->spl_obj->createExportDirectory(); - ilUtil::makeDir($this->export_dir."/".$this->subdir); + /** + * build xml export file + */ + public function buildExportFileXML($questions = null) + { + // create directories + $this->spl_obj->createExportDirectory(); + ilUtil::makeDir($this->export_dir . "/" . $this->subdir); - // get Log File - include_once "./Services/Logging/classes/class.ilLog.php"; - $expLog = new ilLog($this->spl_obj->getExportDirectory(), "export.log"); - $expLog->delete(); - $expLog->setLogFormat(""); - $expLog->write(date("[y-m-d H:i:s] ")."Start Export"); - // write qti file - $qti_file = fopen($this->export_dir."/".$this->subdir."/". $this->filename, "w"); - fwrite($qti_file, $this->spl_obj->toXML($questions)); - fclose($qti_file); - // destroy writer object - $this->xml->_XmlWriter; + // get Log File + include_once "./Services/Logging/classes/class.ilLog.php"; + $expLog = new ilLog($this->spl_obj->getExportDirectory(), "export.log"); + $expLog->delete(); + $expLog->setLogFormat(""); + $expLog->write(date("[y-m-d H:i:s] ") . "Start Export"); + // write qti file + $qti_file = fopen($this->export_dir . "/" . $this->subdir . "/" . $this->filename, "w"); + fwrite($qti_file, $this->spl_obj->toXML($questions)); + fclose($qti_file); + // destroy writer object + $this->xml->_XmlWriter; - ilUtil::zip($this->export_dir."/".$this->subdir, - $this->export_dir."/".$this->subdir.".zip"); + ilUtil::zip( + $this->export_dir . "/" . $this->subdir, + $this->export_dir . "/" . $this->subdir . ".zip" + ); - $expLog->write(date("[y-m-d H:i:s] ")."Finished Export"); + $expLog->write(date("[y-m-d H:i:s] ") . "Finished Export"); - return $this->export_dir."/".$this->subdir.".zip"; - } + return $this->export_dir . "/" . $this->subdir . ".zip"; + } } - -?> \ No newline at end of file diff --git a/Modules/SurveyQuestionPool/classes/class.ilSurveyQuestionsPlugin.php b/Modules/SurveyQuestionPool/classes/class.ilSurveyQuestionsPlugin.php index 96bc0b9f404ff4954e80cedeca8f50ae0d7f54f2..4f082d93255c4cca1ebde80ec12df97c78704c90 100644 --- a/Modules/SurveyQuestionPool/classes/class.ilSurveyQuestionsPlugin.php +++ b/Modules/SurveyQuestionPool/classes/class.ilSurveyQuestionsPlugin.php @@ -1,5 +1,5 @@ \ No newline at end of file diff --git a/Modules/SurveyQuestionPool/classes/class.ilSurveySyncTableGUI.php b/Modules/SurveyQuestionPool/classes/class.ilSurveySyncTableGUI.php index 2fbcd37af99531a7b72654389a5cc46cb225fe21..5b6b76ba3cc7050d0a77b9503316cd95931c892b 100644 --- a/Modules/SurveyQuestionPool/classes/class.ilSurveySyncTableGUI.php +++ b/Modules/SurveyQuestionPool/classes/class.ilSurveySyncTableGUI.php @@ -1,219 +1,198 @@ - - * @version $Id$ - * - * @ingroup ModulesSurveyQuestionPool - */ -class ilSurveySyncTableGUI extends ilTable2GUI -{ - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilTree - */ - protected $tree; - - /** - * Constructor - * - * @param object $a_parent_obj parent gui object - * @param string $a_parent_cmd parent default command - * @param ilSurveyQuestion $a_question - */ - function __construct($a_parent_obj, $a_parent_cmd, SurveyQuestion $a_question) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $this->tree = $DIC->repositoryTree(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->question = $a_question; - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setId("il_svy_spl_sync"); - - $this->setTitle($this->question->getTitle()); - $this->setDescription($lng->txt("survey_sync_question_copies_info")); - - $this->addCommandButton("synccopies", $lng->txt("survey_sync_question_copies")); - $this->addCommandButton("cancelsync", $lng->txt("cancel")); - - // $this->setSelectAllCheckbox("id[]"); - $this->addColumn("", "", 1); - $this->addColumn($lng->txt("title"), ""); - - $this->setDefaultOrderField("title"); - $this->setDefaultOrderDirection("asc"); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.il_svy_qpl_sync.html", "Modules/SurveyQuestionPool"); - - $this->importData(); - } - - /** - * Import data from DB - */ - protected function importData() - { - $ilAccess = $this->access; - $lng = $this->lng; - - include_once "Modules/Survey/classes/class.ilObjSurvey.php"; - - $table_data = array(); - foreach($this->question->getCopyIds(true) as $survey_obj_id => $questions) - { - $survey_id = new ilObjSurvey($survey_obj_id, false); - $survey_id->loadFromDB(); - $survey_id = $survey_id->getSurveyId(); - - $ref_ids = ilObject::_getAllReferences($survey_obj_id); - $message = ""; - - // check permissions for "parent" survey - $can_write = false; - if(!ilObjSurvey::_hasDatasets($survey_id)) - { - foreach($ref_ids as $ref_id) - { - if($ilAccess->checkAccess("edit", "", $ref_id)) - { - $can_write = true; - break; - } - } - - if(!$can_write) - { - $message = $lng->txt("survey_sync_insufficient_permissions"); - } - } - else - { - $message = $lng->txt("survey_has_datasets_warning"); - } - - $survey_title = ilObject::_lookupTitle($survey_obj_id); - $survey_path = $this->buildPath($ref_ids); - - foreach($questions as $question_id) - { - $title = SurveyQuestion::_getTitle($question_id); - - if(!$can_write) - { - $question_id = null; - } - - $table_data[] = array( - "id" => $question_id, - "title" => $title, - "path" => $survey_path, - "message" => $message - ); - } - } - - $this->setData($table_data); - } - - /** - * Fill table row - * - * @param array $a_set data array - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->tpl->setVariable("TXT_PATH", $lng->txt("path")); - - if($a_set["message"]) - { - $this->tpl->setCurrentBlock("message"); - $this->tpl->setVariable("TXT_MESSAGE", $a_set["message"]); - $this->tpl->parseCurrentBlock(); - } - - // question - if($a_set["id"]) - { - $this->tpl->setCurrentBlock("checkbox"); - $this->tpl->setVariable("ID", $a_set["id"]); - $this->tpl->parseCurrentBlock(); - } - - - $this->tpl->setVariable("TITLE", $a_set["title"]); - $this->tpl->setVariable("VALUE_PATH", implode("
", $a_set["path"])); - } - - /** - * Build path with deep-link - * - * @param array $ref_ids - * @return array - */ - protected function buildPath($ref_ids) - { - $tree = $this->tree; - $ilCtrl = $this->ctrl; - - include_once './Services/Link/classes/class.ilLink.php'; - - if(!count($ref_ids)) - { - return false; - } - foreach($ref_ids as $ref_id) - { - $path = "..."; - - $counter = 0; - $path_full = $tree->getPathFull($ref_id); - if(sizeof($path_full)) - { - foreach($path_full as $data) - { - if(++$counter < (count($path_full)-1)) - { - continue; - } - $path .= " » "; - if($ref_id != $data['ref_id']) - { - $path .= $data['title']; - } - else - { - $path .= (''. - $data['title'].''); - } - } - } - - $result[] = $path; - } - return $result; - } -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @ingroup ModulesSurveyQuestionPool + */ +class ilSurveySyncTableGUI extends ilTable2GUI +{ + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilTree + */ + protected $tree; + + /** + * Constructor + * + * @param object $a_parent_obj parent gui object + * @param string $a_parent_cmd parent default command + * @param ilSurveyQuestion $a_question + */ + public function __construct($a_parent_obj, $a_parent_cmd, SurveyQuestion $a_question) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->tree = $DIC->repositoryTree(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->question = $a_question; + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setId("il_svy_spl_sync"); + + $this->setTitle($this->question->getTitle()); + $this->setDescription($lng->txt("survey_sync_question_copies_info")); + + $this->addCommandButton("synccopies", $lng->txt("survey_sync_question_copies")); + $this->addCommandButton("cancelsync", $lng->txt("cancel")); + + // $this->setSelectAllCheckbox("id[]"); + $this->addColumn("", "", 1); + $this->addColumn($lng->txt("title"), ""); + + $this->setDefaultOrderField("title"); + $this->setDefaultOrderDirection("asc"); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.il_svy_qpl_sync.html", "Modules/SurveyQuestionPool"); + + $this->importData(); + } + + /** + * Import data from DB + */ + protected function importData() + { + $ilAccess = $this->access; + $lng = $this->lng; + + include_once "Modules/Survey/classes/class.ilObjSurvey.php"; + + $table_data = array(); + foreach ($this->question->getCopyIds(true) as $survey_obj_id => $questions) { + $survey_id = new ilObjSurvey($survey_obj_id, false); + $survey_id->loadFromDB(); + $survey_id = $survey_id->getSurveyId(); + + $ref_ids = ilObject::_getAllReferences($survey_obj_id); + $message = ""; + + // check permissions for "parent" survey + $can_write = false; + if (!ilObjSurvey::_hasDatasets($survey_id)) { + foreach ($ref_ids as $ref_id) { + if ($ilAccess->checkAccess("edit", "", $ref_id)) { + $can_write = true; + break; + } + } + + if (!$can_write) { + $message = $lng->txt("survey_sync_insufficient_permissions"); + } + } else { + $message = $lng->txt("survey_has_datasets_warning"); + } + + $survey_title = ilObject::_lookupTitle($survey_obj_id); + $survey_path = $this->buildPath($ref_ids); + + foreach ($questions as $question_id) { + $title = SurveyQuestion::_getTitle($question_id); + + if (!$can_write) { + $question_id = null; + } + + $table_data[] = array( + "id" => $question_id, + "title" => $title, + "path" => $survey_path, + "message" => $message + ); + } + } + + $this->setData($table_data); + } + + /** + * Fill table row + * + * @param array $a_set data array + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $this->tpl->setVariable("TXT_PATH", $lng->txt("path")); + + if ($a_set["message"]) { + $this->tpl->setCurrentBlock("message"); + $this->tpl->setVariable("TXT_MESSAGE", $a_set["message"]); + $this->tpl->parseCurrentBlock(); + } + + // question + if ($a_set["id"]) { + $this->tpl->setCurrentBlock("checkbox"); + $this->tpl->setVariable("ID", $a_set["id"]); + $this->tpl->parseCurrentBlock(); + } + + + $this->tpl->setVariable("TITLE", $a_set["title"]); + $this->tpl->setVariable("VALUE_PATH", implode("
", $a_set["path"])); + } + + /** + * Build path with deep-link + * + * @param array $ref_ids + * @return array + */ + protected function buildPath($ref_ids) + { + $tree = $this->tree; + $ilCtrl = $this->ctrl; + + include_once './Services/Link/classes/class.ilLink.php'; + + if (!count($ref_ids)) { + return false; + } + foreach ($ref_ids as $ref_id) { + $path = "..."; + + $counter = 0; + $path_full = $tree->getPathFull($ref_id); + if (sizeof($path_full)) { + foreach ($path_full as $data) { + if (++$counter < (count($path_full)-1)) { + continue; + } + $path .= " » "; + if ($ref_id != $data['ref_id']) { + $path .= $data['title']; + } else { + $path .= ('' . + $data['title'] . ''); + } + } + } + + $result[] = $path; + } + return $result; + } +} diff --git a/Modules/SurveyQuestionPool/classes/tables/class.SurveyMaterialsSourceTableGUI.php b/Modules/SurveyQuestionPool/classes/tables/class.SurveyMaterialsSourceTableGUI.php index 3323d45c3f30f89a063e9664b5e5d7553d31a31e..025d60ece614f915a6ac6e93e2878ac54a8c8302 100644 --- a/Modules/SurveyQuestionPool/classes/tables/class.SurveyMaterialsSourceTableGUI.php +++ b/Modules/SurveyQuestionPool/classes/tables/class.SurveyMaterialsSourceTableGUI.php @@ -1,84 +1,83 @@ - -* @version $Id: class.ilSurveyMaterialsTableGUI.php 26013 2010-10-12 16:01:03Z hschottm $ -* -* @ingroup ModulesSurveyQuestionPool -* -*/ -class SurveyMaterialsSourceTableGUI extends ilTable2GUI -{ - public function __construct($a_parent_obj, $a_parent_cmd, $a_cancel_cmd) - { - global $DIC; +ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->addColumn($lng->txt("title"), "title"); - $this->addColumn($lng->txt("action"), ""); - $this->setTitle($this->lng->txt('select_object_to_link')); - - $this->setLimit(9999); - $this->disable("numinfo"); - - $this->setRowTemplate("tpl.il_svy_qpl_material_source_row.html", "Modules/SurveyQuestionPool"); - - $this->setFormAction($ilCtrl->getFormAction($this->getParentObject(), $this->getParentCmd())); - $this->addCommandButton($a_cancel_cmd, $this->lng->txt('cancel')); - - $this->setDefaultOrderField("title"); - $this->setDefaultOrderDirection("asc"); - } - - /** - * Fill data row - */ - protected function fillRow($data) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $url_cmd = "add".strtoupper($data["item_type"]); - $url_type = strtolower($data["item_type"]); - - $ilCtrl->setParameter($this->getParentObject(), $url_type, $data["item_id"]); - $url = $ilCtrl->getLinkTarget($this->getParentObject(), $url_cmd). - $ilCtrl->setParameter($this->getParentObject(), $url_type, ""); - - $this->tpl->setVariable("TITLE", $data['title']); - $this->tpl->setVariable("URL_ADD", $url); - $this->tpl->setVariable("TXT_ADD", $lng->txt("add")); - } -} -?> +include_once("./Services/Table/classes/class.ilTable2GUI.php"); + +/** +* TableGUI class for survey question source materials +* +* @author Jörg Lützenkirchen +* @version $Id: class.ilSurveyMaterialsTableGUI.php 26013 2010-10-12 16:01:03Z hschottm $ +* +* @ingroup ModulesSurveyQuestionPool +* +*/ +class SurveyMaterialsSourceTableGUI extends ilTable2GUI +{ + public function __construct($a_parent_obj, $a_parent_cmd, $a_cancel_cmd) + { + 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->addColumn($lng->txt("title"), "title"); + $this->addColumn($lng->txt("action"), ""); + $this->setTitle($this->lng->txt('select_object_to_link')); + + $this->setLimit(9999); + $this->disable("numinfo"); + + $this->setRowTemplate("tpl.il_svy_qpl_material_source_row.html", "Modules/SurveyQuestionPool"); + + $this->setFormAction($ilCtrl->getFormAction($this->getParentObject(), $this->getParentCmd())); + $this->addCommandButton($a_cancel_cmd, $this->lng->txt('cancel')); + + $this->setDefaultOrderField("title"); + $this->setDefaultOrderDirection("asc"); + } + + /** + * Fill data row + */ + protected function fillRow($data) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $url_cmd = "add" . strtoupper($data["item_type"]); + $url_type = strtolower($data["item_type"]); + + $ilCtrl->setParameter($this->getParentObject(), $url_type, $data["item_id"]); + $url = $ilCtrl->getLinkTarget($this->getParentObject(), $url_cmd) . + $ilCtrl->setParameter($this->getParentObject(), $url_type, ""); + + $this->tpl->setVariable("TITLE", $data['title']); + $this->tpl->setVariable("URL_ADD", $url); + $this->tpl->setVariable("TXT_ADD", $lng->txt("add")); + } +} diff --git a/Modules/SurveyQuestionPool/classes/tables/class.ilSurveyMaterialsTableGUI.php b/Modules/SurveyQuestionPool/classes/tables/class.ilSurveyMaterialsTableGUI.php index c8f4d2a03c1b4ad6a0553db3054ee6d4e6476666..20bbb767d466239a24a174eb06c6a16ae0e12ff8 100644 --- a/Modules/SurveyQuestionPool/classes/tables/class.ilSurveyMaterialsTableGUI.php +++ b/Modules/SurveyQuestionPool/classes/tables/class.ilSurveyMaterialsTableGUI.php @@ -1,24 +1,24 @@ ctrl(); - $lng = $DIC->language(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->write_access = $a_write_access; - $this->counter = 1; - $this->lng = $lng; - $this->ctrl = $ilCtrl; - $this->setFormName('evaluation_all'); - $this->setStyle('table', 'fullwidth'); - $this->addColumn('','f','1%'); - $this->addColumn($lng->txt("type"), "type", ""); - $this->addColumn($lng->txt("material"), "material", ""); - $this->setTitle($this->lng->txt('materials')); - - $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); - $this->setRowTemplate("tpl.il_svy_qpl_material_row.html", "Modules/SurveyQuestionPool"); - $this->setPrefix('idx'); - $this->setSelectAllCheckbox('idx'); - $this->disable('sort'); - $this->enable('header'); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->write_access = $a_write_access; + $this->counter = 1; + $this->lng = $lng; + $this->ctrl = $ilCtrl; + $this->setFormName('evaluation_all'); + $this->setStyle('table', 'fullwidth'); + $this->addColumn('', 'f', '1%'); + $this->addColumn($lng->txt("type"), "type", ""); + $this->addColumn($lng->txt("material"), "material", ""); + $this->setTitle($this->lng->txt('materials')); + + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); + $this->setRowTemplate("tpl.il_svy_qpl_material_row.html", "Modules/SurveyQuestionPool"); + $this->setPrefix('idx'); + $this->setSelectAllCheckbox('idx'); + $this->disable('sort'); + $this->enable('header'); - if ($this->write_access) - { - $this->addMultiCommand('deleteMaterial', $this->lng->txt('remove')); - } - } - - /** - * Fill data row - */ - protected function fillRow($data) - { - $this->tpl->setVariable("TYPE", $data['type']); - $this->tpl->setVariable("TITLE", $data['title']); - $this->tpl->setVariable("HREF", $data['href']); - $this->tpl->setVariable("CHECKBOX_VALUE", $this->counter-1); - $this->tpl->setVariable("COUNTER", $this->counter++); - } + if ($this->write_access) { + $this->addMultiCommand('deleteMaterial', $this->lng->txt('remove')); + } + } + + /** + * Fill data row + */ + protected function fillRow($data) + { + $this->tpl->setVariable("TYPE", $data['type']); + $this->tpl->setVariable("TITLE", $data['title']); + $this->tpl->setVariable("HREF", $data['href']); + $this->tpl->setVariable("CHECKBOX_VALUE", $this->counter-1); + $this->tpl->setVariable("COUNTER", $this->counter++); + } } -?> diff --git a/Modules/SurveyQuestionPool/classes/tables/class.ilSurveyPhrasesTableGUI.php b/Modules/SurveyQuestionPool/classes/tables/class.ilSurveyPhrasesTableGUI.php index 9ec7051ab0275f3bd62b84b1114c4d9601e3c325..7cd00e490f3d56b4088682bc670f989578a0bd17 100644 --- a/Modules/SurveyQuestionPool/classes/tables/class.ilSurveyPhrasesTableGUI.php +++ b/Modules/SurveyQuestionPool/classes/tables/class.ilSurveyPhrasesTableGUI.php @@ -33,93 +33,82 @@ include_once('./Services/Table/classes/class.ilTable2GUI.php'); class ilSurveyPhrasesTableGUI extends ilTable2GUI { - protected $confirmdelete; - - /** - * Constructor - * - * @access public - * @param - * @return - */ - public function __construct($a_parent_obj, $a_parent_cmd, $confirmdelete = false) - { - global $DIC; + protected $confirmdelete; + + /** + * Constructor + * + * @access public + * @param + * @return + */ + public function __construct($a_parent_obj, $a_parent_cmd, $confirmdelete = false) + { + global $DIC; - parent::__construct($a_parent_obj, $a_parent_cmd); + parent::__construct($a_parent_obj, $a_parent_cmd); - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); - $this->lng = $lng; - $this->ctrl = $ilCtrl; - $this->confirmdelete = $confirmdelete; - - $this->setFormName('phrases'); - $this->setStyle('table', 'fullwidth'); - if (!$confirmdelete) - { - $this->addColumn('','f','1%'); - } - $this->addColumn($this->lng->txt("phrase"),'phrase', ''); - $this->addColumn($this->lng->txt("answers"),'answers', ''); + $this->lng = $lng; + $this->ctrl = $ilCtrl; + $this->confirmdelete = $confirmdelete; + + $this->setFormName('phrases'); + $this->setStyle('table', 'fullwidth'); + if (!$confirmdelete) { + $this->addColumn('', 'f', '1%'); + } + $this->addColumn($this->lng->txt("phrase"), 'phrase', ''); + $this->addColumn($this->lng->txt("answers"), 'answers', ''); - if ($confirmdelete) - { - $this->addCommandButton('confirmDeletePhrase', $this->lng->txt('confirm')); - $this->addCommandButton('cancelDeletePhrase', $this->lng->txt('cancel')); - } - else - { - $this->addMultiCommand('editPhrase', $this->lng->txt('edit')); - $this->addMultiCommand('deletePhrase', $this->lng->txt('delete')); - } + if ($confirmdelete) { + $this->addCommandButton('confirmDeletePhrase', $this->lng->txt('confirm')); + $this->addCommandButton('cancelDeletePhrase', $this->lng->txt('cancel')); + } else { + $this->addMultiCommand('editPhrase', $this->lng->txt('edit')); + $this->addMultiCommand('deletePhrase', $this->lng->txt('delete')); + } - $this->setRowTemplate("tpl.il_svy_qpl_phrase_row.html", "Modules/SurveyQuestionPool"); + $this->setRowTemplate("tpl.il_svy_qpl_phrase_row.html", "Modules/SurveyQuestionPool"); - $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); - $this->setDefaultOrderField("phrase"); - $this->setDefaultOrderDirection("asc"); - - if ($confirmdelete) - { - $this->disable('sort'); - $this->disable('select_all'); - } - else - { - $this->setPrefix('phrase'); - $this->setSelectAllCheckbox('phrase'); - $this->enable('sort'); - $this->enable('select_all'); - } - $this->enable('header'); - } + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); + $this->setDefaultOrderField("phrase"); + $this->setDefaultOrderDirection("asc"); + + if ($confirmdelete) { + $this->disable('sort'); + $this->disable('select_all'); + } else { + $this->setPrefix('phrase'); + $this->setSelectAllCheckbox('phrase'); + $this->enable('sort'); + $this->enable('select_all'); + } + $this->enable('header'); + } - /** - * fill row - * - * @access public - * @param - * @return - */ - public function fillRow($data) - { - if (!$this->confirmdelete) - { - $this->tpl->setCurrentBlock('checkbox'); - $this->tpl->setVariable('CB_PHRASE_ID', $data["phrase_id"]); - $this->tpl->parseCurrentBlock(); - } - else - { - $this->tpl->setCurrentBlock('hidden'); - $this->tpl->setVariable('HIDDEN_PHRASE_ID', $data["phrase_id"]); - $this->tpl->parseCurrentBlock(); - } - $this->tpl->setVariable('PHRASE_ID', $data["phrase_id"]); - $this->tpl->setVariable("PHRASE", $data["phrase"]); - $this->tpl->setVariable("ANSWERS", $data["answers"]); - } + /** + * fill row + * + * @access public + * @param + * @return + */ + public function fillRow($data) + { + if (!$this->confirmdelete) { + $this->tpl->setCurrentBlock('checkbox'); + $this->tpl->setVariable('CB_PHRASE_ID', $data["phrase_id"]); + $this->tpl->parseCurrentBlock(); + } else { + $this->tpl->setCurrentBlock('hidden'); + $this->tpl->setVariable('HIDDEN_PHRASE_ID', $data["phrase_id"]); + $this->tpl->parseCurrentBlock(); + } + $this->tpl->setVariable('PHRASE_ID', $data["phrase_id"]); + $this->tpl->setVariable("PHRASE", $data["phrase"]); + $this->tpl->setVariable("ANSWERS", $data["answers"]); + } } -?> \ No newline at end of file diff --git a/Modules/SurveyQuestionPool/classes/tables/class.ilSurveyQuestionPoolExportTableGUI.php b/Modules/SurveyQuestionPool/classes/tables/class.ilSurveyQuestionPoolExportTableGUI.php index dbbb9d1652d39e99a9a3a2844bc53155bdcecf3f..81640576b250b06b014aaaf9a502cd154d758acc 100644 --- a/Modules/SurveyQuestionPool/classes/tables/class.ilSurveyQuestionPoolExportTableGUI.php +++ b/Modules/SurveyQuestionPool/classes/tables/class.ilSurveyQuestionPoolExportTableGUI.php @@ -33,101 +33,90 @@ include_once('./Services/Table/classes/class.ilTable2GUI.php'); class ilSurveyQuestionPoolExportTableGUI extends ilTable2GUI { - protected $confirmdelete; - protected $counter; - - /** - * Constructor - * - * @access public - * @param - * @return - */ - public function __construct($a_parent_obj, $a_parent_cmd, $confirmdelete = false) - { - global $DIC; + protected $confirmdelete; + protected $counter; + + /** + * Constructor + * + * @access public + * @param + * @return + */ + public function __construct($a_parent_obj, $a_parent_cmd, $confirmdelete = false) + { + global $DIC; - parent::__construct($a_parent_obj, $a_parent_cmd); + parent::__construct($a_parent_obj, $a_parent_cmd); - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); - $this->lng = $lng; - $this->ctrl = $ilCtrl; - $this->confirmdelete = $confirmdelete; - $this->counter = 0; - - $this->setFormName('phrases'); - $this->setTitle($this->lng->txt('svy_export_files')); - $this->setStyle('table', 'fullwidth'); - if (!$confirmdelete) - { - $this->addColumn('','f','1%'); - } - $this->addColumn($this->lng->txt("file"),'file', ''); - $this->addColumn($this->lng->txt("size"),'size', ''); - $this->addColumn($this->lng->txt("date"),'date', ''); + $this->lng = $lng; + $this->ctrl = $ilCtrl; + $this->confirmdelete = $confirmdelete; + $this->counter = 0; + + $this->setFormName('phrases'); + $this->setTitle($this->lng->txt('svy_export_files')); + $this->setStyle('table', 'fullwidth'); + if (!$confirmdelete) { + $this->addColumn('', 'f', '1%'); + } + $this->addColumn($this->lng->txt("file"), 'file', ''); + $this->addColumn($this->lng->txt("size"), 'size', ''); + $this->addColumn($this->lng->txt("date"), 'date', ''); - if ($confirmdelete) - { - $this->addCommandButton('deleteExportFile', $this->lng->txt('confirm')); - $this->addCommandButton('cancelDeleteExportFile', $this->lng->txt('cancel')); - } - else - { - $this->addMultiCommand('downloadExportFile', $this->lng->txt('download')); - $this->addMultiCommand('confirmDeleteExportFile', $this->lng->txt('delete')); - } + if ($confirmdelete) { + $this->addCommandButton('deleteExportFile', $this->lng->txt('confirm')); + $this->addCommandButton('cancelDeleteExportFile', $this->lng->txt('cancel')); + } else { + $this->addMultiCommand('downloadExportFile', $this->lng->txt('download')); + $this->addMultiCommand('confirmDeleteExportFile', $this->lng->txt('delete')); + } - $this->setRowTemplate("tpl.il_svy_qpl_export_row.html", "Modules/SurveyQuestionPool"); + $this->setRowTemplate("tpl.il_svy_qpl_export_row.html", "Modules/SurveyQuestionPool"); - $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); - $this->setDefaultOrderField("file"); - $this->setDefaultOrderDirection("asc"); - - if ($confirmdelete) - { - $this->disable('sort'); - $this->disable('select_all'); - } - else - { - $this->setPrefix('file'); - $this->setSelectAllCheckbox('file'); - $this->enable('sort'); - $this->enable('select_all'); - } - $this->enable('header'); - } + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); + $this->setDefaultOrderField("file"); + $this->setDefaultOrderDirection("asc"); + + if ($confirmdelete) { + $this->disable('sort'); + $this->disable('select_all'); + } else { + $this->setPrefix('file'); + $this->setSelectAllCheckbox('file'); + $this->enable('sort'); + $this->enable('select_all'); + } + $this->enable('header'); + } - /** - * fill row - * - * @access public - * @param - * @return - */ - public function fillRow($data) - { - if (!$this->confirmdelete) - { - $this->tpl->setCurrentBlock('checkbox'); - $this->tpl->setVariable('CB_ID', $this->counter); - $this->tpl->setVariable('CB_FILENAME', ilUtil::prepareFormOutput($data['file'])); - $this->tpl->parseCurrentBlock(); - } - else - { - $this->tpl->setCurrentBlock('hidden'); - $this->tpl->setVariable('HIDDEN_FILENAME', ilUtil::prepareFormOutput($data['file'])); - $this->tpl->parseCurrentBlock(); - } - $this->tpl->setVariable('CB_ID', $this->counter); - $this->tpl->setVariable("PHRASE", $data["phrase"]); - $this->tpl->setVariable("FILENAME", ilUtil::prepareFormOutput($data['file'])); - $this->tpl->setVariable("SIZE", $data["size"]); - $this->tpl->setVariable("DATE", $data["date"]); - $this->counter++; - } + /** + * fill row + * + * @access public + * @param + * @return + */ + public function fillRow($data) + { + if (!$this->confirmdelete) { + $this->tpl->setCurrentBlock('checkbox'); + $this->tpl->setVariable('CB_ID', $this->counter); + $this->tpl->setVariable('CB_FILENAME', ilUtil::prepareFormOutput($data['file'])); + $this->tpl->parseCurrentBlock(); + } else { + $this->tpl->setCurrentBlock('hidden'); + $this->tpl->setVariable('HIDDEN_FILENAME', ilUtil::prepareFormOutput($data['file'])); + $this->tpl->parseCurrentBlock(); + } + $this->tpl->setVariable('CB_ID', $this->counter); + $this->tpl->setVariable("PHRASE", $data["phrase"]); + $this->tpl->setVariable("FILENAME", ilUtil::prepareFormOutput($data['file'])); + $this->tpl->setVariable("SIZE", $data["size"]); + $this->tpl->setVariable("DATE", $data["date"]); + $this->counter++; + } } -?> \ No newline at end of file diff --git a/Modules/SurveyQuestionPool/classes/tables/class.ilSurveyQuestionsTableGUI.php b/Modules/SurveyQuestionPool/classes/tables/class.ilSurveyQuestionsTableGUI.php index ed1cbdc2f3d1f66e0e4710c1d36c073fa0969f7c..23ad0d0396fc168d1bbb4288dfe8b6c214d8daed 100644 --- a/Modules/SurveyQuestionPool/classes/tables/class.ilSurveyQuestionsTableGUI.php +++ b/Modules/SurveyQuestionPool/classes/tables/class.ilSurveyQuestionsTableGUI.php @@ -33,313 +33,301 @@ include_once('./Services/Table/classes/class.ilTable2GUI.php'); class ilSurveyQuestionsTableGUI extends ilTable2GUI { - /** - * @var ilRbacReview - */ - protected $rbacreview; + /** + * @var ilRbacReview + */ + protected $rbacreview; - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - protected $editable = true; - protected $writeAccess = false; - - /** - * Constructor - * - * @access public - * @param - * @return - */ - public function __construct($a_parent_obj, $a_parent_cmd, $a_write_access = false) - { - global $DIC; + protected $editable = true; + protected $writeAccess = false; + + /** + * Constructor + * + * @access public + * @param + * @return + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_write_access = false) + { + global $DIC; - $this->rbacreview = $DIC->rbac()->review(); - $this->user = $DIC->user(); - $this->setId("spl"); - $this->setPrefix('q_id'); // #16982 - - parent::__construct($a_parent_obj, $a_parent_cmd); + $this->rbacreview = $DIC->rbac()->review(); + $this->user = $DIC->user(); + $this->setId("spl"); + $this->setPrefix('q_id'); // #16982 + + parent::__construct($a_parent_obj, $a_parent_cmd); - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); - $this->lng = $lng; - $this->ctrl = $ilCtrl; - - $this->setWriteAccess($a_write_access); + $this->lng = $lng; + $this->ctrl = $ilCtrl; + + $this->setWriteAccess($a_write_access); - //$qplSetting = new ilSetting("spl"); - - //$this->setFormName('questionbrowser'); - //$this->setStyle('table', 'fullwidth'); - - if ($this->getWriteAccess()) - { - $this->addColumn('','','1%'); - } - - $this->addColumn($this->lng->txt("title"),'title', ''); - $this->addColumn($this->lng->txt("obligatory"), ""); - - foreach ($this->getSelectedColumns() as $c) - { - if (strcmp($c, 'description') == 0) $this->addColumn($this->lng->txt("description"),'description', ''); - if (strcmp($c, 'type') == 0) $this->addColumn($this->lng->txt("question_type"),'type', ''); - if (strcmp($c, 'author') == 0) $this->addColumn($this->lng->txt("author"),'author', ''); - if (strcmp($c, 'created') == 0) $this->addColumn($this->lng->txt("create_date"),'created', ''); - if (strcmp($c, 'updated') == 0) $this->addColumn($this->lng->txt("last_update"),'tstamp', ''); - } - - $this->addColumn("", ""); - - if ($this->getWriteAccess()) - { - $this->setSelectAllCheckbox('q_id'); - - $this->addMultiCommand('copy', $this->lng->txt('copy')); - $this->addMultiCommand('move', $this->lng->txt('move')); - $this->addMultiCommand('exportQuestion', $this->lng->txt('export')); - $this->addMultiCommand('deleteQuestions', $this->lng->txt('delete')); - - if (array_key_exists("spl_clipboard", $_SESSION)) - { - $this->addCommandButton('paste', $this->lng->txt('paste')); - } - - $this->addCommandButton("saveObligatory", $this->lng->txt("spl_save_obligatory_state")); - } + //$qplSetting = new ilSetting("spl"); + + //$this->setFormName('questionbrowser'); + //$this->setStyle('table', 'fullwidth'); + + if ($this->getWriteAccess()) { + $this->addColumn('', '', '1%'); + } + + $this->addColumn($this->lng->txt("title"), 'title', ''); + $this->addColumn($this->lng->txt("obligatory"), ""); + + foreach ($this->getSelectedColumns() as $c) { + if (strcmp($c, 'description') == 0) { + $this->addColumn($this->lng->txt("description"), 'description', ''); + } + if (strcmp($c, 'type') == 0) { + $this->addColumn($this->lng->txt("question_type"), 'type', ''); + } + if (strcmp($c, 'author') == 0) { + $this->addColumn($this->lng->txt("author"), 'author', ''); + } + if (strcmp($c, 'created') == 0) { + $this->addColumn($this->lng->txt("create_date"), 'created', ''); + } + if (strcmp($c, 'updated') == 0) { + $this->addColumn($this->lng->txt("last_update"), 'tstamp', ''); + } + } + + $this->addColumn("", ""); + + if ($this->getWriteAccess()) { + $this->setSelectAllCheckbox('q_id'); + + $this->addMultiCommand('copy', $this->lng->txt('copy')); + $this->addMultiCommand('move', $this->lng->txt('move')); + $this->addMultiCommand('exportQuestion', $this->lng->txt('export')); + $this->addMultiCommand('deleteQuestions', $this->lng->txt('delete')); + + if (array_key_exists("spl_clipboard", $_SESSION)) { + $this->addCommandButton('paste', $this->lng->txt('paste')); + } + + $this->addCommandButton("saveObligatory", $this->lng->txt("spl_save_obligatory_state")); + } - $this->setRowTemplate("tpl.il_svy_qpl_questions_row.html", "Modules/SurveyQuestionPool"); + $this->setRowTemplate("tpl.il_svy_qpl_questions_row.html", "Modules/SurveyQuestionPool"); - $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); - $this->setDefaultOrderField("title"); - $this->setDefaultOrderDirection("asc"); - - $this->setShowRowsSelector(true); - - //$this->enable('sort'); - //$this->enable('header'); - //$this->enable('select_all'); - $this->setFilterCommand('filterQuestionBrowser'); - $this->setResetCommand('resetfilterQuestionBrowser'); - - $this->initFilter(); - } + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); + $this->setDefaultOrderField("title"); + $this->setDefaultOrderDirection("asc"); + + $this->setShowRowsSelector(true); + + //$this->enable('sort'); + //$this->enable('header'); + //$this->enable('select_all'); + $this->setFilterCommand('filterQuestionBrowser'); + $this->setResetCommand('resetfilterQuestionBrowser'); + + $this->initFilter(); + } - /** - * Init filter - */ - function initFilter() - { - $lng = $this->lng; - $rbacreview = $this->rbacreview; - $ilUser = $this->user; - - // title - include_once("./Services/Form/classes/class.ilTextInputGUI.php"); - $ti = new ilTextInputGUI($lng->txt("title"), "title"); - $ti->setMaxLength(64); - $ti->setSize(20); - $ti->setValidationRegexp('/^[^%]+$/is'); - $this->addFilterItem($ti); - $ti->readFromSession(); - $this->filter["title"] = $ti->getValue(); - - // description - $ti = new ilTextInputGUI($lng->txt("description"), "description"); - $ti->setMaxLength(64); - $ti->setSize(20); - $ti->setValidationRegexp('/^[^%]+$/is'); - $this->addFilterItem($ti); - $ti->readFromSession(); - $this->filter["description"] = $ti->getValue(); - - // author - $ti = new ilTextInputGUI($lng->txt("author"), "author"); - $ti->setMaxLength(64); - $ti->setSize(20); - $ti->setValidationRegexp('/^[^%]+$/is'); - $this->addFilterItem($ti); - $ti->readFromSession(); - $this->filter["author"] = $ti->getValue(); - - // questiontype - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - include_once("./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"); - $types = ilObjSurveyQuestionPool::_getQuestionTypes(); - $options = array(); - $options[""] = $lng->txt('filter_all_question_types'); - foreach ($types as $translation => $row) - { - $options[$row['type_tag']] = $translation; - } + /** + * Init filter + */ + public function initFilter() + { + $lng = $this->lng; + $rbacreview = $this->rbacreview; + $ilUser = $this->user; + + // title + include_once("./Services/Form/classes/class.ilTextInputGUI.php"); + $ti = new ilTextInputGUI($lng->txt("title"), "title"); + $ti->setMaxLength(64); + $ti->setSize(20); + $ti->setValidationRegexp('/^[^%]+$/is'); + $this->addFilterItem($ti); + $ti->readFromSession(); + $this->filter["title"] = $ti->getValue(); + + // description + $ti = new ilTextInputGUI($lng->txt("description"), "description"); + $ti->setMaxLength(64); + $ti->setSize(20); + $ti->setValidationRegexp('/^[^%]+$/is'); + $this->addFilterItem($ti); + $ti->readFromSession(); + $this->filter["description"] = $ti->getValue(); + + // author + $ti = new ilTextInputGUI($lng->txt("author"), "author"); + $ti->setMaxLength(64); + $ti->setSize(20); + $ti->setValidationRegexp('/^[^%]+$/is'); + $this->addFilterItem($ti); + $ti->readFromSession(); + $this->filter["author"] = $ti->getValue(); + + // questiontype + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + include_once("./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"); + $types = ilObjSurveyQuestionPool::_getQuestionTypes(); + $options = array(); + $options[""] = $lng->txt('filter_all_question_types'); + foreach ($types as $translation => $row) { + $options[$row['type_tag']] = $translation; + } - $si = new ilSelectInputGUI($this->lng->txt("question_type"), "type"); - $si->setOptions($options); - $this->addFilterItem($si); - $si->readFromSession(); - $this->filter["type"] = $si->getValue(); - - } + $si = new ilSelectInputGUI($this->lng->txt("question_type"), "type"); + $si->setOptions($options); + $this->addFilterItem($si); + $si->readFromSession(); + $this->filter["type"] = $si->getValue(); + } - function getSelectableColumns() - { - $lng = $this->lng; - $cols["description"] = array( - "txt" => $lng->txt("description"), - "default" => true - ); - $cols["type"] = array( - "txt" => $lng->txt("question_type"), - "default" => true - ); - $cols["author"] = array( - "txt" => $lng->txt("author"), - "default" => true - ); - $cols["created"] = array( - "txt" => $lng->txt("create_date"), - "default" => true - ); - $cols["updated"] = array( - "txt" => $lng->txt("last_update"), - "default" => true - ); - return $cols; - } + public function getSelectableColumns() + { + $lng = $this->lng; + $cols["description"] = array( + "txt" => $lng->txt("description"), + "default" => true + ); + $cols["type"] = array( + "txt" => $lng->txt("question_type"), + "default" => true + ); + $cols["author"] = array( + "txt" => $lng->txt("author"), + "default" => true + ); + $cols["created"] = array( + "txt" => $lng->txt("create_date"), + "default" => true + ); + $cols["updated"] = array( + "txt" => $lng->txt("last_update"), + "default" => true + ); + return $cols; + } - /** - * fill row - * - * @access public - * @param - * @return - */ - public function fillRow($data) - { - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php"; - $class = strtolower(SurveyQuestionGUI::_getGUIClassNameForId($data["question_id"])); - $guiclass = $class . "GUI"; - $this->ctrl->setParameterByClass(strtolower($guiclass), "q_id", $data["question_id"]); - - if ($this->getEditable()) - { - $url_edit = $this->ctrl->getLinkTargetByClass(strtolower($guiclass), "editQuestion"); - - $this->tpl->setCurrentBlock("title_link_bl"); - $this->tpl->setVariable("QUESTION_TITLE_LINK", $data["title"]); - $this->tpl->setVariable("URL_TITLE", $url_edit); - $this->tpl->parseCurrentBlock(); - } - else - { - $this->tpl->setCurrentBlock("title_nolink_bl"); - $this->tpl->setVariable("QUESTION_TITLE", $data["title"]); - $this->tpl->parseCurrentBlock(); - } - - if ($data["complete"] == 0) - { - $this->tpl->setCurrentBlock("qpl_warning"); - $this->tpl->setVariable("IMAGE_WARNING", ilUtil::getImagePath("icon_alert.svg")); - $this->tpl->setVariable("ALT_WARNING", $this->lng->txt("warning_question_not_complete")); - $this->tpl->setVariable("TITLE_WARNING", $this->lng->txt("warning_question_not_complete")); - $this->tpl->parseCurrentBlock(); - } - - foreach ($this->getSelectedColumns() as $c) - { - if (strcmp($c, 'description') == 0) - { - $this->tpl->setCurrentBlock('description'); - $this->tpl->setVariable("QUESTION_COMMENT", (strlen($data["description"])) ? $data["description"] : " "); - $this->tpl->parseCurrentBlock(); - } - if (strcmp($c, 'type') == 0) - { - $this->tpl->setCurrentBlock('type'); - $this->tpl->setVariable("QUESTION_TYPE", SurveyQuestion::_getQuestionTypeName($data["type_tag"])); - $this->tpl->parseCurrentBlock(); - } - if (strcmp($c, 'author') == 0) - { - $this->tpl->setCurrentBlock('author'); - $this->tpl->setVariable("QUESTION_AUTHOR", $data["author"]); - $this->tpl->parseCurrentBlock(); - } - if (strcmp($c, 'created') == 0) - { - $this->tpl->setCurrentBlock('created'); - $this->tpl->setVariable("QUESTION_CREATED", ilDatePresentation::formatDate(new ilDate($data['created'],IL_CAL_UNIX))); - $this->tpl->parseCurrentBlock(); - } - if (strcmp($c, 'updated') == 0) - { - $this->tpl->setCurrentBlock('updated'); - $this->tpl->setVariable("QUESTION_UPDATED", ilDatePresentation::formatDate(new ilDate($data["tstamp"],IL_CAL_UNIX))); - $this->tpl->parseCurrentBlock(); - } - } - - // actions - include_once "Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"; - $list = new ilAdvancedSelectionListGUI(); - $list->setId($data["question_id"]); - $list->setListTitle($this->lng->txt("actions")); - if ($url_edit) - { - $list->addItem($this->lng->txt("edit"), "", $url_edit); - } - $list->addItem($this->lng->txt("preview"), "", $this->ctrl->getLinkTargetByClass(strtolower($guiclass), "preview")); - $this->tpl->setVariable("ACTION", $list->getHTML()); - $this->tpl->parseCurrentBlock(); - - // obligatory - if ($this->getEditable()) - { - $checked = $data["obligatory"] ? " checked=\"checked\"" : ""; - $obligatory = ""; - } - else if($data["obligatory"]) - { - $obligatory = "\"".$this-lng->txt("question_obligatory"). - "\" title=\"".$this->lng->txt("question_obligatory")."\" />"; - } - $this->tpl->setVariable("OBLIGATORY", $obligatory); - - if ($this->getWriteAccess()) - { - $this->tpl->setVariable('CBOX_ID', $data["question_id"]); - } - $this->tpl->setVariable('QUESTION_ID', $data["question_id"]); - } - - public function setEditable($value) - { - $this->editable = $value; - } - - public function getEditable() - { - return $this->editable; - } + /** + * fill row + * + * @access public + * @param + * @return + */ + public function fillRow($data) + { + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php"; + $class = strtolower(SurveyQuestionGUI::_getGUIClassNameForId($data["question_id"])); + $guiclass = $class . "GUI"; + $this->ctrl->setParameterByClass(strtolower($guiclass), "q_id", $data["question_id"]); + + if ($this->getEditable()) { + $url_edit = $this->ctrl->getLinkTargetByClass(strtolower($guiclass), "editQuestion"); + + $this->tpl->setCurrentBlock("title_link_bl"); + $this->tpl->setVariable("QUESTION_TITLE_LINK", $data["title"]); + $this->tpl->setVariable("URL_TITLE", $url_edit); + $this->tpl->parseCurrentBlock(); + } else { + $this->tpl->setCurrentBlock("title_nolink_bl"); + $this->tpl->setVariable("QUESTION_TITLE", $data["title"]); + $this->tpl->parseCurrentBlock(); + } + + if ($data["complete"] == 0) { + $this->tpl->setCurrentBlock("qpl_warning"); + $this->tpl->setVariable("IMAGE_WARNING", ilUtil::getImagePath("icon_alert.svg")); + $this->tpl->setVariable("ALT_WARNING", $this->lng->txt("warning_question_not_complete")); + $this->tpl->setVariable("TITLE_WARNING", $this->lng->txt("warning_question_not_complete")); + $this->tpl->parseCurrentBlock(); + } + + foreach ($this->getSelectedColumns() as $c) { + if (strcmp($c, 'description') == 0) { + $this->tpl->setCurrentBlock('description'); + $this->tpl->setVariable("QUESTION_COMMENT", (strlen($data["description"])) ? $data["description"] : " "); + $this->tpl->parseCurrentBlock(); + } + if (strcmp($c, 'type') == 0) { + $this->tpl->setCurrentBlock('type'); + $this->tpl->setVariable("QUESTION_TYPE", SurveyQuestion::_getQuestionTypeName($data["type_tag"])); + $this->tpl->parseCurrentBlock(); + } + if (strcmp($c, 'author') == 0) { + $this->tpl->setCurrentBlock('author'); + $this->tpl->setVariable("QUESTION_AUTHOR", $data["author"]); + $this->tpl->parseCurrentBlock(); + } + if (strcmp($c, 'created') == 0) { + $this->tpl->setCurrentBlock('created'); + $this->tpl->setVariable("QUESTION_CREATED", ilDatePresentation::formatDate(new ilDate($data['created'], IL_CAL_UNIX))); + $this->tpl->parseCurrentBlock(); + } + if (strcmp($c, 'updated') == 0) { + $this->tpl->setCurrentBlock('updated'); + $this->tpl->setVariable("QUESTION_UPDATED", ilDatePresentation::formatDate(new ilDate($data["tstamp"], IL_CAL_UNIX))); + $this->tpl->parseCurrentBlock(); + } + } + + // actions + include_once "Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"; + $list = new ilAdvancedSelectionListGUI(); + $list->setId($data["question_id"]); + $list->setListTitle($this->lng->txt("actions")); + if ($url_edit) { + $list->addItem($this->lng->txt("edit"), "", $url_edit); + } + $list->addItem($this->lng->txt("preview"), "", $this->ctrl->getLinkTargetByClass(strtolower($guiclass), "preview")); + $this->tpl->setVariable("ACTION", $list->getHTML()); + $this->tpl->parseCurrentBlock(); + + // obligatory + if ($this->getEditable()) { + $checked = $data["obligatory"] ? " checked=\"checked\"" : ""; + $obligatory = ""; + } elseif ($data["obligatory"]) { + $obligatory = "\""lng->txt("question_obligatory") . + "\" title=\"" . $this->lng->txt("question_obligatory") . "\" />"; + } + $this->tpl->setVariable("OBLIGATORY", $obligatory); + + if ($this->getWriteAccess()) { + $this->tpl->setVariable('CBOX_ID', $data["question_id"]); + } + $this->tpl->setVariable('QUESTION_ID', $data["question_id"]); + } + + public function setEditable($value) + { + $this->editable = $value; + } + + public function getEditable() + { + return $this->editable; + } - public function setWriteAccess($value) - { - $this->writeAccess = $value; - } - - public function getWriteAccess() - { - return $this->writeAccess; - } + public function setWriteAccess($value) + { + $this->writeAccess = $value; + } + + public function getWriteAccess() + { + return $this->writeAccess; + } } -?> \ No newline at end of file diff --git a/Modules/SurveyQuestionPool/classes/tables/class.ilSurveySavePhraseTableGUI.php b/Modules/SurveyQuestionPool/classes/tables/class.ilSurveySavePhraseTableGUI.php index f2333fa3ece17dcabd074f9ee6a0492ba3410b4e..9725fc9504d149a9499bd63c3ddd34c1665e0653 100644 --- a/Modules/SurveyQuestionPool/classes/tables/class.ilSurveySavePhraseTableGUI.php +++ b/Modules/SurveyQuestionPool/classes/tables/class.ilSurveySavePhraseTableGUI.php @@ -33,55 +33,54 @@ include_once('./Services/Table/classes/class.ilTable2GUI.php'); class ilSurveySavePhraseTableGUI extends ilTable2GUI { - protected $confirmdelete; - - /** - * Constructor - * - * @access public - * @param - * @return - */ - public function __construct($a_parent_obj, $a_parent_cmd) - { - global $DIC; + protected $confirmdelete; + + /** + * Constructor + * + * @access public + * @param + * @return + */ + public function __construct($a_parent_obj, $a_parent_cmd) + { + global $DIC; - parent::__construct($a_parent_obj, $a_parent_cmd); + parent::__construct($a_parent_obj, $a_parent_cmd); - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); - $this->lng = $lng; - $this->ctrl = $ilCtrl; - $this->confirmdelete = $confirmdelete; - - $this->setFormName('phrases'); - $this->setStyle('table', 'fullwidth'); + $this->lng = $lng; + $this->ctrl = $ilCtrl; + $this->confirmdelete = $confirmdelete; + + $this->setFormName('phrases'); + $this->setStyle('table', 'fullwidth'); - $this->addColumn($this->lng->txt("answer"),'', ''); - $this->addColumn($this->lng->txt("use_other_answer"),'', ''); - $this->addColumn($this->lng->txt("scale"),'', ''); + $this->addColumn($this->lng->txt("answer"), '', ''); + $this->addColumn($this->lng->txt("use_other_answer"), '', ''); + $this->addColumn($this->lng->txt("scale"), '', ''); - $this->setRowTemplate("tpl.il_svy_qpl_phrase_save_row.html", "Modules/SurveyQuestionPool"); + $this->setRowTemplate("tpl.il_svy_qpl_phrase_save_row.html", "Modules/SurveyQuestionPool"); - $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); - $this->disable('sort'); - $this->disable('select_all'); - $this->enable('header'); - } + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); + $this->disable('sort'); + $this->disable('select_all'); + $this->enable('header'); + } - /** - * fill row - * - * @access public - * @param - * @return - */ - public function fillRow($data) - { - $this->tpl->setVariable("ANSWER", $data["answer"]); - $this->tpl->setVariable("OPEN_ANSWER", ($data["other"]) ? $this->lng->txt('yes') : $this->lng->txt('no')); - $this->tpl->setVariable("SCALE", $data["scale"]); - } + /** + * fill row + * + * @access public + * @param + * @return + */ + public function fillRow($data) + { + $this->tpl->setVariable("ANSWER", $data["answer"]); + $this->tpl->setVariable("OPEN_ANSWER", ($data["other"]) ? $this->lng->txt('yes') : $this->lng->txt('no')); + $this->tpl->setVariable("SCALE", $data["scale"]); + } } -?> diff --git a/Modules/SystemFolder/classes/class.ilBenchmarkTableGUI.php b/Modules/SystemFolder/classes/class.ilBenchmarkTableGUI.php index 1f1581d25ed88eddc7ef5a64dd1a6fa2221b005a..c1de00fb91b94b7bfd11208b1c55dd018333817b 100644 --- a/Modules/SystemFolder/classes/class.ilBenchmarkTableGUI.php +++ b/Modules/SystemFolder/classes/class.ilBenchmarkTableGUI.php @@ -13,178 +13,165 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilBenchmarkTableGUI extends ilTable2GUI { - /** - * @var ilAccessHandler - */ - protected $access; - - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_records, $a_mode = "chronological") - { - 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(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setLimit(9999); - $this->mode = $a_mode; - - switch ($this->mode) - { - case "slowest_first": - $this->setData(ilUtil::sortArray($a_records, "time", "desc", true)); - $this->setTitle($lng->txt("adm_db_bench_slowest_first")); - $this->addColumn($this->lng->txt("adm_time")); - $this->addColumn($this->lng->txt("adm_sql")); - break; - - case "sorted_by_sql": - $this->setData(ilUtil::sortArray($a_records, "sql", "asc")); - $this->setTitle($lng->txt("adm_db_bench_sorted_by_sql")); - $this->addColumn($this->lng->txt("adm_time")); - $this->addColumn($this->lng->txt("adm_sql")); - break; - - case "by_first_table": - $this->setData($this->getDataByFirstTable($a_records)); - $this->setTitle($lng->txt("adm_db_bench_by_first_table")); - $this->addColumn($this->lng->txt("adm_time")); - $this->addColumn($this->lng->txt("adm_nr_statements")); - $this->addColumn($this->lng->txt("adm_table")); - break; - - default: - $this->setData($a_records); - $this->setTitle($lng->txt("adm_db_bench_chronological")); - $this->addColumn($this->lng->txt("adm_time")); - $this->addColumn($this->lng->txt("adm_sql")); - break; - - } - - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.db_bench.html", "Modules/SystemFolder"); - $this->disable("footer"); - $this->setEnableTitle(true); - -// $this->addMultiCommand("", $lng->txt("")); + /** + * @var ilAccessHandler + */ + protected $access; + + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_records, $a_mode = "chronological") + { + 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(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setLimit(9999); + $this->mode = $a_mode; + + switch ($this->mode) { + case "slowest_first": + $this->setData(ilUtil::sortArray($a_records, "time", "desc", true)); + $this->setTitle($lng->txt("adm_db_bench_slowest_first")); + $this->addColumn($this->lng->txt("adm_time")); + $this->addColumn($this->lng->txt("adm_sql")); + break; + + case "sorted_by_sql": + $this->setData(ilUtil::sortArray($a_records, "sql", "asc")); + $this->setTitle($lng->txt("adm_db_bench_sorted_by_sql")); + $this->addColumn($this->lng->txt("adm_time")); + $this->addColumn($this->lng->txt("adm_sql")); + break; + + case "by_first_table": + $this->setData($this->getDataByFirstTable($a_records)); + $this->setTitle($lng->txt("adm_db_bench_by_first_table")); + $this->addColumn($this->lng->txt("adm_time")); + $this->addColumn($this->lng->txt("adm_nr_statements")); + $this->addColumn($this->lng->txt("adm_table")); + break; + + default: + $this->setData($a_records); + $this->setTitle($lng->txt("adm_db_bench_chronological")); + $this->addColumn($this->lng->txt("adm_time")); + $this->addColumn($this->lng->txt("adm_sql")); + break; + + } + + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.db_bench.html", "Modules/SystemFolder"); + $this->disable("footer"); + $this->setEnableTitle(true); + + // $this->addMultiCommand("", $lng->txt("")); // $this->addCommandButton("", $lng->txt("")); - } - - /** - * Get first occurence of string - * - * @param - * @return - */ - function getFirst($a_str, $a_needles) - { - $pos = 0; - foreach ($a_needles as $needle) - { - $pos2 = strpos($a_str, $needle); - - if ($pos2 > 0 && ($pos2 < $pos || $pos == 0)) - { - $pos = $pos2; - } - } - - return $pos; - } - - /** - * Extract first table from sql - * - * @param - * @return - */ - function extractFirstTableFromSQL($a_sql) - { - $pos1 = $this->getFirst(strtolower($a_sql), array("from ", "from\n", "from\t", "from\r")); - - $table = ""; - if ($pos1 > 0) - { - $tablef = substr(strtolower($a_sql), $pos1+5); - $pos2 = $this->getFirst($tablef, array(" ", "\n", "\t", "\r")); - if ($pos2 > 0) - { - $table =substr($tablef, 0, $pos2); - } - else - { - $table = $tablef; - } - } - if (trim($table) != "") - { - return $table; - } - - return ""; - } - - - /** - * Get data by first table - * - * @param - * @return - */ - function getDataByFirstTable($a_records) - { - $data = array(); - foreach ($a_records as $r) - { - $table = $this->extractFirstTableFromSQL($r["sql"]); - $data[$table]["table"] = $table; - $data[$table]["cnt"]++; - $data[$table]["time"] += $r["time"]; - } - if (count($data) > 0) - { - $data = ilUtil::sortArray($data, "time", "desc", true); - } - - return $data; - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - - switch ($this->mode) - { - case "by_first_table": - $this->tpl->setCurrentBlock("td"); - $this->tpl->setVariable("VAL", $a_set["table"]); - $this->tpl->parseCurrentBlock(); - $this->tpl->setVariable("VAL1", $a_set["time"]); - $this->tpl->setVariable("VAL2", $a_set["cnt"]); - break; - - case "slowest_first": - case "sorted_by_sql": - default: - $this->tpl->setVariable("VAL1", $a_set["time"]); - $this->tpl->setVariable("VAL2", $a_set["sql"]); - break; - } - } - + } + + /** + * Get first occurence of string + * + * @param + * @return + */ + public function getFirst($a_str, $a_needles) + { + $pos = 0; + foreach ($a_needles as $needle) { + $pos2 = strpos($a_str, $needle); + + if ($pos2 > 0 && ($pos2 < $pos || $pos == 0)) { + $pos = $pos2; + } + } + + return $pos; + } + + /** + * Extract first table from sql + * + * @param + * @return + */ + public function extractFirstTableFromSQL($a_sql) + { + $pos1 = $this->getFirst(strtolower($a_sql), array("from ", "from\n", "from\t", "from\r")); + + $table = ""; + if ($pos1 > 0) { + $tablef = substr(strtolower($a_sql), $pos1+5); + $pos2 = $this->getFirst($tablef, array(" ", "\n", "\t", "\r")); + if ($pos2 > 0) { + $table =substr($tablef, 0, $pos2); + } else { + $table = $tablef; + } + } + if (trim($table) != "") { + return $table; + } + + return ""; + } + + + /** + * Get data by first table + * + * @param + * @return + */ + public function getDataByFirstTable($a_records) + { + $data = array(); + foreach ($a_records as $r) { + $table = $this->extractFirstTableFromSQL($r["sql"]); + $data[$table]["table"] = $table; + $data[$table]["cnt"]++; + $data[$table]["time"] += $r["time"]; + } + if (count($data) > 0) { + $data = ilUtil::sortArray($data, "time", "desc", true); + } + + return $data; + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + + switch ($this->mode) { + case "by_first_table": + $this->tpl->setCurrentBlock("td"); + $this->tpl->setVariable("VAL", $a_set["table"]); + $this->tpl->parseCurrentBlock(); + $this->tpl->setVariable("VAL1", $a_set["time"]); + $this->tpl->setVariable("VAL2", $a_set["cnt"]); + break; + + case "slowest_first": + case "sorted_by_sql": + default: + $this->tpl->setVariable("VAL1", $a_set["time"]); + $this->tpl->setVariable("VAL2", $a_set["sql"]); + break; + } + } } -?> diff --git a/Modules/SystemFolder/classes/class.ilObjSystemFolder.php b/Modules/SystemFolder/classes/class.ilObjSystemFolder.php index fc36485614491d1582625663e0b3ce0b915719cb..ec4751a38521bb4789d7a4f87fb017364dff3298 100755 --- a/Modules/SystemFolder/classes/class.ilObjSystemFolder.php +++ b/Modules/SystemFolder/classes/class.ilObjSystemFolder.php @@ -1,33 +1,33 @@ +* +* @author Stefan Meyer * @version $Id$ -* +* * @extends ilObject */ @@ -35,194 +35,188 @@ require_once "./Services/Object/classes/class.ilObject.php"; class ilObjSystemFolder extends ilObject { - /** - * @var ilObjUser - */ - protected $user; - - /** - * Constructor - * @access public - * @param integer reference_id or object_id - * @param boolean treat the id as reference_id (true) or object_id (false) - */ - function __construct($a_id,$a_call_by_reference = true) - { - global $DIC; - - $this->db = $DIC->database(); - $this->user = $DIC->user(); - $this->type = "adm"; - parent::__construct($a_id,$a_call_by_reference); - } - - - /** - * delete systemfolder and all related data - * DISABLED - * @access public - * @return boolean true if all object data were removed; false if only a references were removed - */ - function delete() - { - // DISABLED - return false; - - // always call parent delete function first!! - if (!parent::delete()) - { - return false; - } - - // put here systemfolder specific stuff - - // always call parent delete function at the end!! - return true; - } - - /** - * get all translations for header title - * - * @access public - * @return array - */ - function getHeaderTitleTranslations() - { - /** - * @var $ilDB ilDB - */ - $ilDB = $this->db; - - $q = "SELECT * FROM object_translation WHERE obj_id = ". - $ilDB->quote($this->getId(),'integer')." ORDER BY lang_default DESC"; - $r = $ilDB->query($q); - - $num = 0; - - while ($row = $ilDB->fetchObject($r)) - { - $data["Fobject"][$num]= array("title" => $row->title, - "desc" => ilUtil::shortenText($row->description,ilObject::DESC_LENGTH,true), - "lang" => $row->lang_code - ); - $num++; - } - - // first entry is always the default language - $data["default_language"] = 0; - - return $data ? $data : array(); - } - - // remove all Translations of current category - function removeHeaderTitleTranslations() - { - $ilDB = $this->db; - - $query = "DELETE FROM object_translation WHERE obj_id= ". - $ilDB->quote($this->getId(),'integer'); - $res = $ilDB->manipulate($query); - } - - // add a new translation to current category - function addHeaderTitleTranslation($a_title,$a_desc,$a_lang,$a_lang_default) - { - $ilDB = $this->db; - - $query = "INSERT INTO object_translation ". - "(obj_id,title,description,lang_code,lang_default) ". - "VALUES ". - "(".$ilDB->quote($this->getId(),'integer').",". - $ilDB->quote($a_title,'text').",". - $ilDB->quote($a_desc,'text').",". - $ilDB->quote($a_lang,'text').",". - $ilDB->quote($a_lang_default,'integer').")"; - $res = $ilDB->manipulate($query); - - return true; - } - - static function _getId() - { - /** - * @var $ilDB ilDB - */ - global $DIC; - - $ilDB = $DIC->database(); - - $q = "SELECT obj_id FROM object_data WHERE type = " . $ilDB->quote('adm', 'text'); - $r = $ilDB->query($q); - $row = $ilDB->fetchObject($r); - - return $row->obj_id; - } - - static function _getHeaderTitle() - { - /** - * @var $ilDB ilDB - * @var $ilUser ilObjUser - */ - global $DIC; - - $ilDB = $DIC->database(); - $ilUser = $DIC->user(); - - $id = ilObjSystemFolder::_getId(); - - $q = "SELECT title,description FROM object_translation ". - "WHERE obj_id = ".$ilDB->quote($id,'integer')." ". - "AND lang_default = 1"; - $r = $ilDB->query($q); - $row = $ilDB->fetchObject($r); - $title = $row->title; - - $q = "SELECT title,description FROM object_translation ". - "WHERE obj_id = ".$ilDB->quote($id,'integer')." ". - "AND lang_code = ". - $ilDB->quote($ilUser->getCurrentLanguage(),'text')." ". - "AND NOT lang_default = 1"; - $r = $ilDB->query($q); - $row = $ilDB->fetchObject($r); - - if ($row) - { - $title = $row->title; - } - - return $title; - } - - function _getHeaderTitleDescription() - { - $ilDB = $this->db; - $ilUser = $this->user; - - $id = ilObjSystemFolder::_getId(); - - $q = "SELECT title,description FROM object_translation ". - "WHERE obj_id = ".$ilDB->quote($id,'integer')." ". - "AND lang_default = 1"; - $r = $ilDB->query($q); - $row = $ilDB->fetchObject($r); - $description = $row->description; - - $q = "SELECT title,description FROM object_translation ". - "WHERE obj_id = ".$ilDB->quote($id,'integer')." ". - "AND lang_code = ". - $ilDB->quote($ilUser->getPref("language"),'text')." ". - "AND NOT lang_default = 1"; - $r = $ilDB->query($q); - $row = $ilDB->fetchObject($r); - - if ($row) - { - $description = ilUtil::shortenText($row->description,ilObject::DESC_LENGTH,true); - } - - return $description; - } - + /** + * @var ilObjUser + */ + protected $user; + + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id, $a_call_by_reference = true) + { + global $DIC; + + $this->db = $DIC->database(); + $this->user = $DIC->user(); + $this->type = "adm"; + parent::__construct($a_id, $a_call_by_reference); + } + + + /** + * delete systemfolder and all related data + * DISABLED + * @access public + * @return boolean true if all object data were removed; false if only a references were removed + */ + public function delete() + { + // DISABLED + return false; + + // always call parent delete function first!! + if (!parent::delete()) { + return false; + } + + // put here systemfolder specific stuff + + // always call parent delete function at the end!! + return true; + } + + /** + * get all translations for header title + * + * @access public + * @return array + */ + public function getHeaderTitleTranslations() + { + /** + * @var $ilDB ilDB + */ + $ilDB = $this->db; + + $q = "SELECT * FROM object_translation WHERE obj_id = " . + $ilDB->quote($this->getId(), 'integer') . " ORDER BY lang_default DESC"; + $r = $ilDB->query($q); + + $num = 0; + + while ($row = $ilDB->fetchObject($r)) { + $data["Fobject"][$num]= array("title" => $row->title, + "desc" => ilUtil::shortenText($row->description, ilObject::DESC_LENGTH, true), + "lang" => $row->lang_code + ); + $num++; + } + + // first entry is always the default language + $data["default_language"] = 0; + + return $data ? $data : array(); + } + + // remove all Translations of current category + public function removeHeaderTitleTranslations() + { + $ilDB = $this->db; + + $query = "DELETE FROM object_translation WHERE obj_id= " . + $ilDB->quote($this->getId(), 'integer'); + $res = $ilDB->manipulate($query); + } + + // add a new translation to current category + public function addHeaderTitleTranslation($a_title, $a_desc, $a_lang, $a_lang_default) + { + $ilDB = $this->db; + + $query = "INSERT INTO object_translation " . + "(obj_id,title,description,lang_code,lang_default) " . + "VALUES " . + "(" . $ilDB->quote($this->getId(), 'integer') . "," . + $ilDB->quote($a_title, 'text') . "," . + $ilDB->quote($a_desc, 'text') . "," . + $ilDB->quote($a_lang, 'text') . "," . + $ilDB->quote($a_lang_default, 'integer') . ")"; + $res = $ilDB->manipulate($query); + + return true; + } + + public static function _getId() + { + /** + * @var $ilDB ilDB + */ + global $DIC; + + $ilDB = $DIC->database(); + + $q = "SELECT obj_id FROM object_data WHERE type = " . $ilDB->quote('adm', 'text'); + $r = $ilDB->query($q); + $row = $ilDB->fetchObject($r); + + return $row->obj_id; + } + + public static function _getHeaderTitle() + { + /** + * @var $ilDB ilDB + * @var $ilUser ilObjUser + */ + global $DIC; + + $ilDB = $DIC->database(); + $ilUser = $DIC->user(); + + $id = ilObjSystemFolder::_getId(); + + $q = "SELECT title,description FROM object_translation " . + "WHERE obj_id = " . $ilDB->quote($id, 'integer') . " " . + "AND lang_default = 1"; + $r = $ilDB->query($q); + $row = $ilDB->fetchObject($r); + $title = $row->title; + + $q = "SELECT title,description FROM object_translation " . + "WHERE obj_id = " . $ilDB->quote($id, 'integer') . " " . + "AND lang_code = " . + $ilDB->quote($ilUser->getCurrentLanguage(), 'text') . " " . + "AND NOT lang_default = 1"; + $r = $ilDB->query($q); + $row = $ilDB->fetchObject($r); + + if ($row) { + $title = $row->title; + } + + return $title; + } + + public function _getHeaderTitleDescription() + { + $ilDB = $this->db; + $ilUser = $this->user; + + $id = ilObjSystemFolder::_getId(); + + $q = "SELECT title,description FROM object_translation " . + "WHERE obj_id = " . $ilDB->quote($id, 'integer') . " " . + "AND lang_default = 1"; + $r = $ilDB->query($q); + $row = $ilDB->fetchObject($r); + $description = $row->description; + + $q = "SELECT title,description FROM object_translation " . + "WHERE obj_id = " . $ilDB->quote($id, 'integer') . " " . + "AND lang_code = " . + $ilDB->quote($ilUser->getPref("language"), 'text') . " " . + "AND NOT lang_default = 1"; + $r = $ilDB->query($q); + $row = $ilDB->fetchObject($r); + + if ($row) { + $description = ilUtil::shortenText($row->description, ilObject::DESC_LENGTH, true); + } + + return $description; + } } // END class.ilObjSystemFolder -?> diff --git a/Modules/SystemFolder/classes/class.ilObjSystemFolderAccess.php b/Modules/SystemFolder/classes/class.ilObjSystemFolderAccess.php index 04ece556eadb3db75b74b07a9ad9e97e06ae876d..df3baae27d1b61cadaa559526254123bee27d24d 100644 --- a/Modules/SystemFolder/classes/class.ilObjSystemFolderAccess.php +++ b/Modules/SystemFolder/classes/class.ilObjSystemFolderAccess.php @@ -1,24 +1,24 @@ access(); + $ilAccess = $DIC->access(); - $a_target = SYSTEM_FOLDER_ID; - - if ($ilAccess->checkAccess("read", "", $a_target)) - { - return true; - } - return false; - } + $a_target = SYSTEM_FOLDER_ID; + if ($ilAccess->checkAccess("read", "", $a_target)) { + return true; + } + return false; + } } - -?> diff --git a/Modules/SystemFolder/classes/class.ilObjSystemFolderGUI.php b/Modules/SystemFolder/classes/class.ilObjSystemFolderGUI.php index a80e67c68c17a89ebbbdd70c6e441bcf353746c4..dc5fe32ba4b98b5110b625abf0f3c7658840dcc4 100755 --- a/Modules/SystemFolder/classes/class.ilObjSystemFolderGUI.php +++ b/Modules/SystemFolder/classes/class.ilObjSystemFolderGUI.php @@ -17,2328 +17,2267 @@ require_once('./Services/Repository/classes/class.ilObjectPlugin.php'); */ class ilObjSystemFolderGUI extends ilObjectGUI { - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilObjectDefinition - */ - protected $obj_definition; - - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * @var ilDB - */ - protected $db; - - /** - * @var ilStyleDefinition - */ - protected $style_definition; - - /** - * @var ilHelpGUI - */ - protected $help; - - /** - * @var ilIniFile - */ - protected $client_ini; - - /** - * @var ilBenchmark - */ - protected $bench; - - /** - * ILIAS3 object type abbreviation - * @var string - * @access public - */ - var $type; - - /** - * Constructor - * @access public - */ - function __construct($a_data,$a_id,$a_call_by_reference) - { - global $DIC; - - $this->tabs = $DIC->tabs(); - $this->access = $DIC->access(); - $this->ctrl = $DIC->ctrl(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->user = $DIC->user(); - $this->obj_definition = $DIC["objDefinition"]; - $this->settings = $DIC->settings(); - $this->error = $DIC["ilErr"]; - $this->db = $DIC->database(); - $this->style_definition = $DIC["styleDefinition"]; - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - $this->help = $DIC["ilHelp"]; - $this->toolbar = $DIC->toolbar(); - $this->client_ini = $DIC["ilClientIniFile"]; - $this->type = "adm"; - $this->bench = $DIC["ilBench"]; - parent::__construct($a_data,$a_id,$a_call_by_reference, false); - - $this->lng->loadLanguageModule("administration"); - $this->lng->loadLanguageModule("adm"); - } - - function executeCommand() - { - $ilTabs = $this->tabs; - - $next_class = $this->ctrl->getNextClass($this); - $this->prepareOutput(); - - switch($next_class) - { - case 'ilpermissiongui': - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $ret =& $this->ctrl->forwardCommand($perm_gui); - break; - - case 'ilimprintgui': - // page editor will set its own tabs - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($this->lng->txt("back"), - $this->ctrl->getLinkTarget($this, "")); - - include_once("./Services/Imprint/classes/class.ilImprintGUI.php"); - $igui = new ilImprintGUI(); - - // needed for editor - $igui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId(0, "impr")); - - if(!$this->checkPermissionBool("write")) - { - $igui->setEnableEditing(false); - } - - $ret = $this->ctrl->forwardCommand($igui); - if ($ret != "") - { - $this->tpl->setContent($ret); - } - break; - - case "ilobjectownershipmanagementgui": - $this->setSystemCheckSubTabs("no_owner"); - include_once("Services/Object/classes/class.ilObjectOwnershipManagementGUI.php"); - $gui = new ilObjectOwnershipManagementGUI(0); - $this->ctrl->forwardCommand($gui); - break; - - case "ilcronmanagergui": - $ilTabs->activateTab("cron_jobs"); - include_once("Services/Cron/classes/class.ilCronManagerGUI.php"); - $gui = new ilCronManagerGUI(); - $this->ctrl->forwardCommand($gui); - break; - - default: + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilObjectDefinition + */ + protected $obj_definition; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilDB + */ + protected $db; + + /** + * @var ilStyleDefinition + */ + protected $style_definition; + + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var ilIniFile + */ + protected $client_ini; + + /** + * @var ilBenchmark + */ + protected $bench; + + /** + * ILIAS3 object type abbreviation + * @var string + * @access public + */ + public $type; + + /** + * Constructor + * @access public + */ + public function __construct($a_data, $a_id, $a_call_by_reference) + { + global $DIC; + + $this->tabs = $DIC->tabs(); + $this->access = $DIC->access(); + $this->ctrl = $DIC->ctrl(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->user = $DIC->user(); + $this->obj_definition = $DIC["objDefinition"]; + $this->settings = $DIC->settings(); + $this->error = $DIC["ilErr"]; + $this->db = $DIC->database(); + $this->style_definition = $DIC["styleDefinition"]; + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + $this->help = $DIC["ilHelp"]; + $this->toolbar = $DIC->toolbar(); + $this->client_ini = $DIC["ilClientIniFile"]; + $this->type = "adm"; + $this->bench = $DIC["ilBench"]; + parent::__construct($a_data, $a_id, $a_call_by_reference, false); + + $this->lng->loadLanguageModule("administration"); + $this->lng->loadLanguageModule("adm"); + } + + public function executeCommand() + { + $ilTabs = $this->tabs; + + $next_class = $this->ctrl->getNextClass($this); + $this->prepareOutput(); + + switch ($next_class) { + case 'ilpermissiongui': + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $ret =&$this->ctrl->forwardCommand($perm_gui); + break; + + case 'ilimprintgui': + // page editor will set its own tabs + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $this->lng->txt("back"), + $this->ctrl->getLinkTarget($this, "") + ); + + include_once("./Services/Imprint/classes/class.ilImprintGUI.php"); + $igui = new ilImprintGUI(); + + // needed for editor + $igui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId(0, "impr")); + + if (!$this->checkPermissionBool("write")) { + $igui->setEnableEditing(false); + } + + $ret = $this->ctrl->forwardCommand($igui); + if ($ret != "") { + $this->tpl->setContent($ret); + } + break; + + case "ilobjectownershipmanagementgui": + $this->setSystemCheckSubTabs("no_owner"); + include_once("Services/Object/classes/class.ilObjectOwnershipManagementGUI.php"); + $gui = new ilObjectOwnershipManagementGUI(0); + $this->ctrl->forwardCommand($gui); + break; + + case "ilcronmanagergui": + $ilTabs->activateTab("cron_jobs"); + include_once("Services/Cron/classes/class.ilCronManagerGUI.php"); + $gui = new ilCronManagerGUI(); + $this->ctrl->forwardCommand($gui); + break; + + default: //var_dump($_POST); - $cmd = $this->ctrl->getCmd("view"); - - $cmd .= "Object"; - $this->$cmd(); - - break; - } - - return true; - } - - /** - * show admin subpanels and basic settings form - * - * @access public - */ - function viewObject() - { - $ilAccess = $this->access; - - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - return $this->showBasicSettingsObject(); - } - return $this->showServerInfoObject(); - } - - function viewScanLogObject() - { - return $this->viewScanLog(); - } - - /** - * Set sub tabs for general settings - */ - function setSystemCheckSubTabs($a_activate) - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - - $ilTabs->addSubTab("system_check_sub", $this->lng->txt("system_check"), - $ilCtrl->getLinkTarget($this, "check")); - $ilTabs->addSubTab("no_owner", $this->lng->txt("system_check_no_owner"), - $ilCtrl->getLinkTargetByClass("ilObjectOwnershipManagementGUI")); - - $ilTabs->setSubTabActive($a_activate); - $ilTabs->setTabActive("system_check"); - } - - /** - * displays system check menu - * - * @access public - */ - function checkObject() - { - $rbacsystem = $this->rbacsystem; - $ilUser = $this->user; - $objDefinition = $this->obj_definition; - $ilSetting = $this->settings; - $ilErr = $this->error; - - $this->setSystemCheckSubTabs("system_check_sub"); - - if (!$rbacsystem->checkAccess("visible,read",$this->object->getRefId())) - { - $ilErr->raiseError($this->lng->txt("permission_denied"),$ilErr->MESSAGE); - } -//echo "1"; - - if ($_POST['count_limit'] !== null || $_POST['age_limit'] !== null || $_POST['type_limit'] !== null) - { - $ilUser->writePref('systemcheck_count_limit', - (is_numeric($_POST['count_limit']) && $_POST['count_limit'] > 0) ? $_POST['count_limit'] : '' - ); - $ilUser->writePref('systemcheck_age_limit', - (is_numeric($_POST['age_limit']) && $_POST['age_limit'] > 0) ? $_POST['age_limit'] : ''); - $ilUser->writePref('systemcheck_type_limit', trim($_POST['type_limit'])); - } - - if ($_POST["mode"]) - { -//echo "3"; - $this->writeCheckParams(); - $this->startValidator($_POST["mode"],$_POST["log_scan"]); - } - else - { -//echo "4"; - include_once "./Services/Repository/classes/class.ilValidator.php"; - $validator = new ilValidator(); - $hasScanLog = $validator->hasScanLog(); - - $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.adm_check.html", - "Modules/SystemFolder"); - - if ($hasScanLog) - { - $this->tpl->setVariable("TXT_VIEW_LOG", $this->lng->txt("view_last_log")); - } - - $this->tpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this)); - $this->tpl->setVariable("TXT_TITLE", $this->lng->txt("systemcheck")); - $this->tpl->setVariable("COLSPAN", 3); - $this->tpl->setVariable("TXT_ANALYZE_TITLE", $this->lng->txt("analyze_data")); - $this->tpl->setVariable("TXT_ANALYSIS_OPTIONS", $this->lng->txt("analysis_options")); - $this->tpl->setVariable("TXT_REPAIR_OPTIONS", $this->lng->txt("repair_options")); - $this->tpl->setVariable("TXT_OUTPUT_OPTIONS", $this->lng->txt("output_options")); - $this->tpl->setVariable("TXT_SCAN", $this->lng->txt("scan")); - $this->tpl->setVariable("TXT_SCAN_DESC", $this->lng->txt("scan_desc")); - $this->tpl->setVariable("TXT_DUMP_TREE", $this->lng->txt("dump_tree")); - $this->tpl->setVariable("TXT_DUMP_TREE_DESC", $this->lng->txt("dump_tree_desc")); - $this->tpl->setVariable("TXT_CLEAN", $this->lng->txt("clean")); - $this->tpl->setVariable("TXT_CLEAN_DESC", $this->lng->txt("clean_desc")); - $this->tpl->setVariable("TXT_RESTORE", $this->lng->txt("restore_missing")); - $this->tpl->setVariable("TXT_RESTORE_DESC", $this->lng->txt("restore_missing_desc")); - $this->tpl->setVariable("TXT_PURGE", $this->lng->txt("purge_missing")); - $this->tpl->setVariable("TXT_PURGE_DESC", $this->lng->txt("purge_missing_desc")); - $this->tpl->setVariable("TXT_RESTORE_TRASH", $this->lng->txt("restore_trash")); - $this->tpl->setVariable("TXT_RESTORE_TRASH_DESC", $this->lng->txt("restore_trash_desc")); - $this->tpl->setVariable("TXT_PURGE_TRASH", $this->lng->txt("purge_trash")); - $this->tpl->setVariable("TXT_PURGE_TRASH_DESC", $this->lng->txt("purge_trash_desc")); - $this->tpl->setVariable("TXT_COUNT_LIMIT", $this->lng->txt("purge_count_limit")); - $this->tpl->setVariable("TXT_COUNT_LIMIT_DESC", $this->lng->txt("purge_count_limit_desc")); - $this->tpl->setVariable("COUNT_LIMIT_VALUE", $ilUser->getPref("systemcheck_count_limit")); - $this->tpl->setVariable("TXT_AGE_LIMIT", $this->lng->txt("purge_age_limit")); - $this->tpl->setVariable("TXT_AGE_LIMIT_DESC", $this->lng->txt("purge_age_limit_desc")); - $this->tpl->setVariable("AGE_LIMIT_VALUE", $ilUser->getPref("systemcheck_age_limit")); - $this->tpl->setVariable("TXT_TYPE_LIMIT", $this->lng->txt("purge_type_limit")); - $this->tpl->setVariable("TXT_TYPE_LIMIT_DESC", $this->lng->txt("purge_type_limit_desc")); - - if($ilUser->getPref('systemcheck_mode_scan')) - $this->tpl->touchBlock('mode_scan_checked'); - if($ilUser->getPref('systemcheck_mode_dump_tree')) - $this->tpl->touchBlock('mode_dump_tree_checked'); - if($ilUser->getPref('systemcheck_mode_clean')) - $this->tpl->touchBlock('mode_clean_checked'); - if($ilUser->getPref('systemcheck_mode_restore')) - { - $this->tpl->touchBlock('mode_restore_checked'); - $this->tpl->touchBlock('mode_purge_disabled'); - } - elseif($ilUser->getPref('systemcheck_mode_purge')) - { - $this->tpl->touchBlock('mode_purge_checked'); - $this->tpl->touchBlock('mode_restore_disabled'); - } - if($ilUser->getPref('systemcheck_mode_restore_trash')) - { - $this->tpl->touchBlock('mode_restore_trash_checked'); - $this->tpl->touchBlock('mode_purge_trash_disabled'); - } - elseif($ilUser->getPref('systemcheck_mode_purge_trash')) - { - $this->tpl->touchBlock('mode_purge_trash_checked'); - $this->tpl->touchBlock('mode_restore_trash_disabled'); - } - if($ilUser->getPref('systemcheck_log_scan')) - $this->tpl->touchBlock('log_scan_checked'); - - - // #9520 - restrict to types which can be found in tree - - $obj_types_in_tree = array(); - - $ilDB = $this->db; - $set = $ilDB->query('SELECT type FROM object_data od'. - ' JOIN object_reference ref ON (od.obj_id = ref.obj_id)'. - ' JOIN tree ON (tree.child = ref.ref_id)'. - ' WHERE tree.tree < 1'. - ' GROUP BY type'); - while($row = $ilDB->fetchAssoc($set)) - { - $obj_types_in_tree[] = $row['type']; - } - - $types = $objDefinition->getAllObjects(); - $ts = array("" => ""); - foreach ($types as $t) - { - if ($t != "" && !$objDefinition->isSystemObject($t) && $t != "root" && - in_array($t, $obj_types_in_tree)) - { - if ($objDefinition->isPlugin($t)) - { - $pl = ilObjectPlugin::getPluginObjectByType($t); - $ts[$t] = $pl->txt("obj_".$t); - } - else - { - $ts[$t] = $this->lng->txt("obj_".$t); - } - } - } - asort($ts); - $this->tpl->setVariable("TYPE_LIMIT_CHOICE", - ilUtil::formSelect( - $ilUser->getPref("systemcheck_type_limit"), - 'type_limit', - $ts, false, true - ) - ); - $this->tpl->setVariable("TXT_LOG_SCAN", $this->lng->txt("log_scan")); - $this->tpl->setVariable("TXT_LOG_SCAN_DESC", $this->lng->txt("log_scan_desc")); - $this->tpl->setVariable("TXT_SUBMIT", $this->lng->txt("start_scan")); - - $this->tpl->setVariable("TXT_SAVE", $this->lng->txt("save_params_for_cron")); - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - - $cron_form = new ilPropertyFormGUI(); - $cron_form->setFormAction($this->ctrl->getFormAction($this)); - $cron_form->setTitle($this->lng->txt('systemcheck_cronform')); - - $radio_group = new ilRadioGroupInputGUI($this->lng->txt('systemcheck_cron'), 'cronjob' ); - $radio_group->setValue( $ilSetting->get('systemcheck_cron') ); - - $radio_opt = new ilRadioOption($this->lng->txt('disabled'),0); - $radio_group->addOption($radio_opt); - - $radio_opt = new ilRadioOption($this->lng->txt('enabled'),1); - $radio_group->addOption($radio_opt); - - $cron_form->addItem($radio_group); - - $cron_form->addCommandButton('saveCheckCron',$this->lng->txt('save')); - - $this->tpl->setVariable('CRON_FORM',$cron_form->getHTML()); - } - } - - private function saveCheckParamsObject() - { - $this->writeCheckParams(); - unset($_POST['mode']); - return $this->checkObject(); - } - - private function writeCheckParams() - { - include_once "./Services/Repository/classes/class.ilValidator.php"; - $validator = new ilValidator(); - $modes = $validator->getPossibleModes(); - - $prefs = array(); - foreach($modes as $mode) - { - if( isset($_POST['mode'][$mode]) ) $value = (int)$_POST['mode'][$mode]; - else $value = 0; - $prefs[ 'systemcheck_mode_'.$mode ] = $value; - } - - if( isset($_POST['log_scan']) ) $value = (int)$_POST['log_scan']; - else $value = 0; - $prefs['systemcheck_log_scan'] = $value; - - $ilUser = $this->user; - foreach($prefs as $key => $val) - { - $ilUser->writePref($key,$val); - } - } - - private function saveCheckCronObject() - { - $ilSetting = $this->settings; - - $systemcheck_cron = ($_POST['cronjob'] ? 1 : 0); - $ilSetting->set('systemcheck_cron',$systemcheck_cron); - - unset($_POST['mode']); - return $this->checkObject(); - } - - /** - * edit header title form - * - * @access private - */ - function changeHeaderTitleObject() - { - $rbacsystem = $this->rbacsystem; - $styleDefinition = $this->style_definition; - - $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.header_title_edit.html", - "Modules/SystemFolder"); - - $array_push = true; - - if ($_SESSION["error_post_vars"]) - { - $_SESSION["translation_post"] = $_SESSION["error_post_vars"]; - $_GET["mode"] = "session"; - $array_push = false; - } - - // load from db if edit category is called the first time - if (($_GET["mode"] != "session")) - { - $data = $this->object->getHeaderTitleTranslations(); - $_SESSION["translation_post"] = $data; - $array_push = false; - } // remove a translation from session - elseif ($_GET["entry"] != 0) - { - array_splice($_SESSION["translation_post"]["Fobject"],$_GET["entry"],1,array()); - - if ($_GET["entry"] == $_SESSION["translation_post"]["default_language"]) - { - $_SESSION["translation_post"]["default_language"] = ""; - } - } - - $data = $_SESSION["translation_post"]; - - // add additional translation form - if (!$_GET["entry"] and $array_push) - { - $count = array_push($data["Fobject"],array("title" => "","desc" => "")); - } - else - { - $count = count($data["Fobject"]); - } - - // stripslashes in form? - $strip = isset($_SESSION["translation_post"]) ? true : false; - - foreach ($data["Fobject"] as $key => $val) - { - // add translation button - if ($key == $count -1) - { - $this->tpl->setCurrentBlock("addTranslation"); - $this->tpl->setVariable("TXT_ADD_TRANSLATION",$this->lng->txt("add_translation")." >>"); - $this->tpl->parseCurrentBlock(); - } - - // remove translation button - if ($key != 0) - { - $this->tpl->setCurrentBlock("removeTranslation"); - $this->tpl->setVariable("TXT_REMOVE_TRANSLATION",$this->lng->txt("remove_translation")); - $this->ctrl->setParameter($this, "entry", $key); - $this->ctrl->setParameter($this, "mode", "edit"); - $this->tpl->setVariable("LINK_REMOVE_TRANSLATION", - $this->ctrl->getLinkTarget($this, "removeTranslation")); - $this->tpl->parseCurrentBlock(); - } - - // lang selection - $this->tpl->addBlockFile("SEL_LANGUAGE", "sel_language", "tpl.lang_selection.html", - "Services/MetaData"); - $this->tpl->setVariable("SEL_NAME", "Fobject[".$key."][lang]"); - - include_once('Services/MetaData/classes/class.ilMDLanguageItem.php'); - - $languages = ilMDLanguageItem::_getLanguages(); - - foreach ($languages as $code => $language) - { - $this->tpl->setCurrentBlock("lg_option"); - $this->tpl->setVariable("VAL_LG", $code); - $this->tpl->setVariable("TXT_LG", $language); - - if ($code == $val["lang"]) - { - $this->tpl->setVariable("SELECTED", "selected=\"selected\""); - } - - $this->tpl->parseCurrentBlock(); - } - - // object data - $this->tpl->setCurrentBlock("obj_form"); - - if ($key == 0) - { - $this->tpl->setVariable("TXT_HEADER", $this->lng->txt("change_header_title")); - } - else - { - $this->tpl->setVariable("TXT_HEADER", $this->lng->txt("translation")." ".$key); - } - - if ($key == $data["default_language"]) - { - $this->tpl->setVariable("CHECKED", "checked=\"checked\""); - } - - $this->tpl->setVariable("TXT_TITLE", $this->lng->txt("title")); - $this->tpl->setVariable("TXT_DESC", $this->lng->txt("desc")); - $this->tpl->setVariable("TXT_DEFAULT", $this->lng->txt("default")); - $this->tpl->setVariable("TXT_LANGUAGE", $this->lng->txt("language")); - $this->tpl->setVariable("TITLE", ilUtil::prepareFormOutput($val["title"],$strip)); - $this->tpl->setVariable("DESC", ilUtil::stripSlashes($val["desc"])); - $this->tpl->setVariable("NUM", $key); - $this->tpl->parseCurrentBlock(); - } - - // global - $this->tpl->setCurrentBlock("adm_content"); - - $this->tpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this)); - $this->tpl->setVariable("TXT_CANCEL", $this->lng->txt("cancel")); - $this->tpl->setVariable("TXT_SUBMIT", $this->lng->txt("save")); - $this->tpl->setVariable("CMD_SUBMIT", "saveHeaderTitle"); - $this->tpl->setVariable("TXT_REQUIRED_FLD", $this->lng->txt("required_field")); - } - - /** - * save header title - */ - function saveHeaderTitleObject() - { - $ilErr = $this->error; - - $data = $_POST; - - // default language set? - if (!isset($data["default_language"])) - { - $ilErr->raiseError($this->lng->txt("msg_no_default_language"),$ilErr->MESSAGE); - } - - // prepare array fro further checks - foreach ($data["Fobject"] as $key => $val) - { - $langs[$key] = $val["lang"]; - } - - $langs = array_count_values($langs); - - // all languages set? - if (array_key_exists("",$langs)) - { - $ilErr->raiseError($this->lng->txt("msg_no_language_selected"),$ilErr->MESSAGE); - } - - // no single language is selected more than once? - if (array_sum($langs) > count($langs)) - { - $ilErr->raiseError($this->lng->txt("msg_multi_language_selected"),$ilErr->MESSAGE); - } - - // copy default translation to variable for object data entry - $_POST["Fobject"]["title"] = $_POST["Fobject"][$_POST["default_language"]]["title"]; - $_POST["Fobject"]["desc"] = $_POST["Fobject"][$_POST["default_language"]]["desc"]; - - // first delete all translation entries... - $this->object->removeHeaderTitleTranslations(); - - // ...and write new translations to object_translation - foreach ($data["Fobject"] as $key => $val) - { - if ($key == $data["default_language"]) - { - $default = 1; - } - else - { - $default = 0; - } - - $this->object->addHeaderTitleTranslation(ilUtil::stripSlashes($val["title"]),ilUtil::stripSlashes($val["desc"]),$val["lang"],$default); - } - - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"),true); - - $this->ctrl->redirect($this); - } - - function cancelObject() - { - $this->ctrl->redirect($this, "view"); - } - - /** - * adds a translation form & save post vars to session - * - * @access public - */ - function addHeaderTitleTranslationObject() - { - $_SESSION["translation_post"] = $_POST; - - $this->ctrl->setParameter($this, "mode", "session"); - $this->ctrl->setParameter($this, "entry", "0"); - $this->ctrl->redirect($this, "changeHeaderTitle"); - } - - /** - * removes a translation form & save post vars to session - * - * @access public - */ - function removeTranslationObject() - { - $this->ctrl->setParameter($this, "entry", $_GET["entry"]); - $this->ctrl->setParameter($this, "mode", "session"); - $this->ctrl->redirect($this, "changeHeaderTitle"); - } - - - function startValidator($a_mode,$a_log) - { - $rbacsystem = $this->rbacsystem; - $ilErr = $this->error; - - if (!$rbacsystem->checkAccess("visible,read",$this->object->getRefId())) - { - $ilErr->raiseError($this->lng->txt("permission_denied"),$ilErr->MESSAGE); - } - - $logging = ($a_log) ? true : false; - include_once "./Services/Repository/classes/class.ilValidator.php"; - $validator = new ilValidator($logging); - $validator->setMode("all",false); - - $modes = array(); - foreach ($a_mode as $mode => $value) - { - $validator->setMode($mode,(bool) $value); - $modes[] = $mode.'='.$value; - } - - $scan_log = $validator->validate(); - - $mode = $this->lng->txt("scan_modes").": ".implode(', ',$modes); - - // output - $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.adm_scan.html", - "Modules/SystemFolder"); - - $this->tpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this)); - $this->tpl->setVariable("TXT_TITLE", $this->lng->txt("scanning_system")); - $this->tpl->setVariable("COLSPAN", 3); - $this->tpl->setVariable("TXT_SCAN_LOG", $scan_log); - $this->tpl->setVariable("TXT_MODE", $mode); - - if ($logging === true) - { - $this->tpl->setVariable("TXT_VIEW_LOG", $this->lng->txt("view_log")); - } - - $this->tpl->setVariable("TXT_DONE", $this->lng->txt("done")); - - $validator->writeScanLogLine($mode); - } - - function viewScanLog() - { - include_once "./Services/Repository/classes/class.ilValidator.php"; - $validator = new IlValidator(); - $scan_log =& $validator->readScanLog(); - - if (is_array($scan_log)) - { - $scan_log = '
'.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'), "
'".ILIAS_HTTP_PATH."/webservice/soap/server.php?wsdl'")); - $wsdl->setValue((string)$ilSetting->get('soap_wsdl_path')); - $wsdl->setSize(60); - $wsdl->setMaxLength(255); - $this->form->addItem($wsdl); - - // response timeout - $ctime = new ilNumberInputGUI($this->lng->txt('soap_connect_timeout'), 'ctimeout'); - $ctime->setMinValue(1); - $ctime->setSize(2); - $ctime->setMaxLength(3); - include_once './Services/WebServices/SOAP/classes/class.ilSoapClient.php'; - $ctime->setValue((int) $ilSetting->get('soap_connect_timeout', ilSoapClient::DEFAULT_CONNECT_TIMEOUT)); - $ctime->setInfo($this->lng->txt('soap_connect_timeout_info')); - $this->form->addItem($ctime); - - $this->form->addCommandButton("saveWebServices", $lng->txt("save")); - - $this->form->setTitle($lng->txt("webservices")); - $this->form->setFormAction($this->ctrl->getFormAction($this)); - - } - - /** - * Save web services form - * - */ - public function saveWebServicesObject() - { - $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->initWebServicesForm(); - if ($this->form->checkInput()) - { - $ilSetting->set('soap_user_administration', $this->form->getInput('soap_user_administration')); - $ilSetting->set('soap_wsdl_path', trim($this->form->getInput('soap_wsdl_path'))); - $ilSetting->set('soap_connect_timeout',$this->form->getInput('ctimeout')); - - ilUtil::sendSuccess($lng->txt('msg_obj_modified'), true); - $ilCtrl->redirect($this, 'showWebServices'); - } - else - { - $this->setGeneralSettingsSubTabs("webservices"); - $this->form->setValuesByPost(); - $tpl->setContent($this->form->getHtml()); - } - } - - // - // - // Java Server - // - // - - /** - * Show Java Server Settings - */ - function showJavaServerObject() - { - $tpl = $this->tpl; - - $tpl->addBlockFile('ADM_CONTENT','adm_content','tpl.java_settings.html','Modules/SystemFolder'); - - $GLOBALS['lng']->loadLanguageModule('search'); - - include_once './Services/UIComponent/Toolbar/classes/class.ilToolbarGUI.php'; - $toolbar = new ilToolbarGUI(); - $toolbar->addButton($this->lng->txt('lucene_create_ini'), - $this->ctrl->getLinkTarget($this,'createJavaServerIni')); - $tpl->setVariable('ACTION_BUTTONS',$toolbar->getHTML()); - - $this->initJavaServerForm(); - $this->setServerInfoSubTabs("java_server"); - $tpl->setVariable('SETTINGS_TABLE',$this->form->getHTML()); - } - - /** - * Create a server ini file - * @return - */ - public function createJavaServerIniObject() - { - $this->setGeneralSettingsSubTabs('java_server'); - $this->initJavaServerIniForm(); - $this->tpl->setContent($this->form->getHTML()); - } - - protected function initJavaServerIniForm() - { - include_once './Services/Form/classes/class.ilPropertyFormGUI.php'; - - $this->form = new ilPropertyFormGUI(); - - $GLOBALS['lng']->loadLanguageModule('search'); - - $this->form->setTitle($this->lng->txt('lucene_tbl_create_ini')); - $this->form->setFormAction($this->ctrl->getFormAction($this,'createJavaServerIni')); - $this->form->addCommandButton('downloadJavaServerIni',$this->lng->txt('lucene_download_ini')); - $this->form->addCommandButton('showJavaServer', $this->lng->txt('cancel')); - - // Host - $ip = new ilTextInputGUI($this->lng->txt('lucene_host'),'ho'); - $ip->setInfo($this->lng->txt('lucene_host_info')); - $ip->setMaxLength(128); - $ip->setSize(32); - $ip->setRequired(true); - $this->form->addItem($ip); - - // Port - $port = new ilNumberInputGUI($this->lng->txt('lucene_port'),'po'); - $port->setSize(5); - $port->setMinValue(1); - $port->setMaxValue(65535); - $port->setRequired(true); - $this->form->addItem($port); - - // Index Path - $path = new ilTextInputGUI($this->lng->txt('lucene_index_path'),'in'); - $path->setSize(80); - $path->setMaxLength(1024); - $path->setInfo($this->lng->txt('lucene_index_path_info')); - $path->setRequired(true); - $this->form->addItem($path); - - // Logging - $log = new ilTextInputGUI($this->lng->txt('lucene_log'),'lo'); - $log->setSize(80); - $log->setMaxLength(1024); - $log->setInfo($this->lng->txt('lucene_log_info')); - $log->setRequired(true); - $this->form->addItem($log); - - // Level - $lev = new ilSelectInputGUI($this->lng->txt('lucene_level'),'le'); - $lev->setOptions(array( - 'DEBUG' => 'DEBUG', - 'INFO' => 'INFO', - 'WARN' => 'WARN', - 'ERROR' => 'ERROR', - 'FATAL' => 'FATAL')); - $lev->setValue('INFO'); - $lev->setRequired(true); - $this->form->addItem($lev); - - // CPU - $cpu = new ilNumberInputGUI($this->lng->txt('lucene_cpu'),'cp'); - $cpu->setValue(1); - $cpu->setSize(1); - $cpu->setMaxLength(2); - $cpu->setMinValue(1); - $cpu->setRequired(true); - $this->form->addItem($cpu); - - // Max file size - $fs = new ilNumberInputGUI($this->lng->txt('lucene_max_fs'), 'fs'); - $fs->setInfo($this->lng->txt('lucene_max_fs_info')); - $fs->setValue(500); - $fs->setSize(4); - $fs->setMaxLength(4); - $fs->setMinValue(1); - $fs->setRequired(true); - $this->form->addItem($fs); - - return true; - } - - /** - * Create and offer server ini file for download - * @return - */ - protected function downloadJavaServerIniObject() - { - $this->initJavaServerIniForm(); - if($this->form->checkInput()) - { - include_once './Services/WebServices/RPC/classes/class.ilRpcIniFileWriter.php'; - $ini = new ilRpcIniFileWriter(); - $ini->setHost($this->form->getInput('ho')); - $ini->setPort($this->form->getInput('po')); - $ini->setIndexPath($this->form->getInput('in')); - $ini->setLogPath($this->form->getInput('lo')); - $ini->setLogLevel($this->form->getInput('le')); - $ini->setNumThreads($this->form->getInput('cp')); - $ini->setMaxFileSize($this->form->getInput('fs')); - - $ini->write(); - ilUtil::deliverData($ini->getIniString(),'ilServer.ini','text/plain','utf-8'); - return true; - } - - $this->form->setValuesByPost(); - ilUtil::sendFailure($this->lng->txt('err_check_input')); - $this->setGeneralSettingsSubTabs('java_server'); - $this->tpl->setContent($this->form->getHTML()); - return true; - } - - /** - * Init java server form. - */ - public function initJavaServerForm() - { - $lng = $this->lng; - $ilSetting = $this->settings; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - // host - $ti = new ilTextInputGUI($this->lng->txt("java_server_host"), "rpc_server_host"); - $ti->setMaxLength(64); - $ti->setSize(32); - $ti->setValue($ilSetting->get("rpc_server_host")); - $this->form->addItem($ti); - - // port - $ti = new ilNumberInputGUI($this->lng->txt("java_server_port"), "rpc_server_port"); - $ti->setMaxLength(5); - $ti->setSize(5); - $ti->setValue($ilSetting->get("rpc_server_port")); - $this->form->addItem($ti); - - // pdf fonts - $pdf = new ilFormSectionHeaderGUI(); - $pdf->setTitle($this->lng->txt('rpc_pdf_generation')); - $this->form->addItem($pdf); - - $pdf_font = new ilTextInputGUI($this->lng->txt('rpc_pdf_font'), 'rpc_pdf_font'); - $pdf_font->setInfo($this->lng->txt('rpc_pdf_font_info')); - $pdf_font->setSize(64); - $pdf_font->setMaxLength(1024); - $pdf_font->setRequired(true); - $pdf_font->setValue( - $ilSetting->get('rpc_pdf_font','Helvetica, unifont')); - $this->form->addItem($pdf_font); - - - // save and cancel commands - $this->form->addCommandButton("saveJavaServer", $lng->txt("save")); - - $this->form->setTitle($lng->txt("java_server")); - $this->form->setDescription($lng->txt("java_server_info"). - '
'. - $lng->txt("java_server_readme").''); - $this->form->setFormAction($this->ctrl->getFormAction($this)); - - } - - /** - * Save java server form - * - */ - public function saveJavaServerObject() - { - $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->initJavaServerForm(); - if ($this->form->checkInput()) - { - $ilSetting->set("rpc_server_host", trim($_POST["rpc_server_host"])); - $ilSetting->set("rpc_server_port", trim($_POST["rpc_server_port"])); - $ilSetting->set('rpc_pdf_font',ilUtil::stripSlashes($_POST['rpc_pdf_font'])); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "showJavaServer"); - - // TODO check settings, ping server - } - else - { - $this->setGeneralSettingsSubTabs("java_server"); - $this->form->setValuesByPost(); - $tpl->setContent($this->form->getHtml()); - } - } - - /** - * - * Show proxy settings - * - * @access public - * - */ - public function showProxyObject() - { - $tpl = $this->tpl; - $ilAccess = $this->access; - $ilErr = $this->error; - - if(!$ilAccess->checkAccess('write', '', $this->object->getRefId())) - { - $ilErr->raiseError($this->lng->txt('permission_denied'), $ilErr->MESSAGE); - } - - require_once './Services/Http/classes/class.ilProxySettings.php'; - - $this->initProxyForm(); - $this->form->setValuesByArray(array( - 'proxy_status' => ilProxySettings::_getInstance()->isActive(), - 'proxy_host' => ilProxySettings::_getInstance()->getHost(), - 'proxy_port' => ilProxySettings::_getInstance()->getPort() - )); - if(ilProxySettings::_getInstance()->isActive()) - { - $this->printProxyStatus(); - } - - $tpl->setContent($this->form->getHTML()); - } - - /** - * - * Print proxy settings - * - * @access private - * - */ - private function printProxyStatus() - { - try - { - ilProxySettings::_getInstance()->checkConnection(); - $this->form->getItemByPostVar('proxy_availability')->setHTML( - ' '. - $this->lng->txt('proxy_connectable') - ); - } - catch(ilProxyException $e) - { - $this->form->getItemByPostVar('proxy_availability')->setHTML( - ' '. - $this->lng->txt('proxy_not_connectable') - ); - ilUtil::sendFailure(sprintf($this->lng->txt('proxy_socket_error'), $e->getMessage())); - } - } - - /** - * - * Save proxy settings - * - * @access public - * - */ - public function saveProxyObject() - { - $tpl = $this->tpl; - $ilAccess = $this->access; - $ilErr = $this->error; - $lng = $this->lng; - - if(!$ilAccess->checkAccess('write', '', $this->object->getRefId())) - { - $ilErr->raiseError($lng->txt('permission_denied'), $ilErr->MESSAGE); - } - - require_once './Services/Http/classes/class.ilProxySettings.php'; - - $this->initProxyForm(); - $isFormValid = $this->form->checkInput(); - ilProxySettings::_getInstance()->isActive((int)$this->form->getInput('proxy_status')) - ->setHost(trim($this->form->getInput('proxy_host'))) - ->setPort(trim($this->form->getInput('proxy_port'))); - if($isFormValid) - { - if(ilProxySettings::_getInstance()->isActive()) - { - if(!strlen(ilProxySettings::_getInstance()->getHost())) - { - $isFormValid = false; - $this->form->getItemByPostVar('proxy_host')->setAlert($lng->txt('msg_input_is_required')); - } - if(!strlen(ilProxySettings::_getInstance()->getPort())) - { - $isFormValid = false; - $this->form->getItemByPostVar('proxy_port')->setAlert($lng->txt('msg_input_is_required')); - } - if(!preg_match('/[0-9]{1,}/', ilProxySettings::_getInstance()->getPort()) || - ilProxySettings::_getInstance()->getPort() < 0 || - ilProxySettings::_getInstance()->getPort() > 65535) - { - $isFormValid = false; - $this->form->getItemByPostVar('proxy_port')->setAlert($lng->txt('proxy_port_numeric')); - } - } - - if($isFormValid) - { - ilProxySettings::_getInstance()->save(); - ilUtil::sendSuccess($lng->txt('saved_successfully')); - if(ilProxySettings::_getInstance()->isActive()) - { - $this->printProxyStatus(); - } - } - else - { - ilUtil::sendFailure($lng->txt('form_input_not_valid')); - } - } - - $this->form->setValuesByPost(); - $tpl->setContent($this->form->getHTML()); - } - - /** - * - * Initialize proxy settings form - * - * @access public - * - */ - private function initProxyForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->setServerInfoSubTabs('proxy'); - - include_once('Services/Form/classes/class.ilPropertyFormGUI.php'); - $this->form = new ilPropertyFormGUI(); - $this->form->setFormAction($ilCtrl->getFormAction($this, 'saveProxy')); - - // Proxy status - $proxs = new ilCheckboxInputGUI($lng->txt('proxy_status'), 'proxy_status'); - $proxs->setInfo($lng->txt('proxy_status_info')); - $proxs->setValue(1); - $this->form->addItem($proxs); - - // Proxy availability - $proxa = new ilCustomInputGUI('', 'proxy_availability'); - $proxs->addSubItem($proxa); - - // Proxy - $prox = new ilTextInputGUI($lng->txt('proxy_host'), 'proxy_host'); - $prox->setInfo($lng->txt('proxy_host_info')); - $proxs->addSubItem($prox); - - // Proxy Port - $proxp = new ilTextInputGUI($lng->txt('proxy_port'), 'proxy_port'); - $proxp->setInfo($lng->txt('proxy_port_info')); - $proxp->setSize(10); - $proxp->setMaxLength(10); - $proxs->addSubItem($proxp); - - // save and cancel commands - $this->form->addCommandButton('saveProxy', $lng->txt('save')); - } - - public function showHTTPSObject() - { - $tpl = $this->tpl; - $ilAccess = $this->access; - $ilErr = $this->error; - - if(!$ilAccess->checkAccess('write', '', $this->object->getRefId())) - { - $ilErr->raiseError($this->lng->txt('permission_denied'), $ilErr->MESSAGE); - } - - $form = $this->initHTTPSForm(); - $tpl->setContent($form->getHTML()); - } - - public function saveHTTPSObject() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $form = $this->initHTTPSForm(); - if($form->checkInput()) - { - $security = ilSecuritySettings::_getInstance(); - - // ilias https handling settings - $security->setHTTPSEnabled($_POST["https_enabled"]); - - if($security->validate($form)) - { - $security->save(); - - ilUtil::sendSuccess($lng->txt('saved_successfully'), true); - $ilCtrl->redirect($this, "showHTTPS"); - } - } - - $form->setValuesByPost(); - $tpl->setContent($form->getHTML()); - } - - private function initHTTPSForm() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->setServerInfoSubTabs('adm_https'); - - $lng->loadLanguageModule('ps'); - - include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php'); - $security = ilSecuritySettings::_getInstance(); - - include_once('Services/Form/classes/class.ilPropertyFormGUI.php'); - $form = new ilPropertyFormGUI(); - $form->setTitle($lng->txt("adm_https")); - $form->setFormAction($ilCtrl->getFormAction($this, 'saveHTTPS')); - - $check2 = new ilCheckboxInputGUI($lng->txt('activate_https'),'https_enabled'); - $check2->setChecked($security->isHTTPSEnabled() ? 1 : 0); - $check2->setValue(1); - $form->addItem($check2); - - // save and cancel commands - $form->addCommandButton('saveHTTPS', $lng->txt('save')); - - return $form; - } - - public function addToExternalSettingsForm($a_form_id) - { - switch($a_form_id) - { - case ilAdministrationSettingsFormHandler::FORM_SECURITY: - - include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php'); - $security = ilSecuritySettings::_getInstance(); - - $subitems = null; - - $fields['activate_https'] = - array($security->isHTTPSEnabled(), ilAdministrationSettingsFormHandler::VALUE_BOOL); - - return array("general_settings" => array("showHTTPS", $fields)); - } - } - - /** - * goto target group - */ - public static function _goto() - { - global $DIC; - - $ilAccess = $DIC->access(); - $ilErr = $DIC["ilErr"]; - $lng = $DIC->language(); - - $a_target = SYSTEM_FOLDER_ID; - - if ($ilAccess->checkAccess("read", "", $a_target)) - { - ilUtil::redirect("ilias.php?baseClass=ilAdministrationGUI"); - exit; - } - else - { - if ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) - { - ilUtil::sendFailure(sprintf($lng->txt("msg_no_perm_read_item"), - ilObject::_lookupTitle(ilObject::_lookupObjId($a_target))), true); - ilObjectGUI::_gotoRepositoryRoot(); - } - } - $ilErr->raiseError($lng->txt("msg_no_perm_read"), $ilErr->FATAL); - } - - /** - * - */ - protected function showVcsInformationObject() - { - $vc_info = array(); - - require_once 'Services/Administration/classes/class.ilSubversionInformation.php'; - require_once 'Services/Administration/classes/class.ilGitInformation.php'; - - foreach(array(new ilSubversionInformation(), new ilGitInformation()) as $vc) - { - $html = $vc->getInformationAsHtml(); - if($html) - { - $vc_info[] = $html; - } - } - - if($vc_info) - { - ilUtil::sendInfo(implode("
", $vc_info)); - } - else - { - ilUtil::sendInfo($this->lng->txt('vc_information_not_determined')); - } - - $this->showServerInfoObject(); - } + $cmd = $this->ctrl->getCmd("view"); + + $cmd .= "Object"; + $this->$cmd(); + + break; + } + + return true; + } + + /** + * show admin subpanels and basic settings form + * + * @access public + */ + public function viewObject() + { + $ilAccess = $this->access; + + if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) { + return $this->showBasicSettingsObject(); + } + return $this->showServerInfoObject(); + } + + public function viewScanLogObject() + { + return $this->viewScanLog(); + } + + /** + * Set sub tabs for general settings + */ + public function setSystemCheckSubTabs($a_activate) + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + + $ilTabs->addSubTab( + "system_check_sub", + $this->lng->txt("system_check"), + $ilCtrl->getLinkTarget($this, "check") + ); + $ilTabs->addSubTab( + "no_owner", + $this->lng->txt("system_check_no_owner"), + $ilCtrl->getLinkTargetByClass("ilObjectOwnershipManagementGUI") + ); + + $ilTabs->setSubTabActive($a_activate); + $ilTabs->setTabActive("system_check"); + } + + /** + * displays system check menu + * + * @access public + */ + public function checkObject() + { + $rbacsystem = $this->rbacsystem; + $ilUser = $this->user; + $objDefinition = $this->obj_definition; + $ilSetting = $this->settings; + $ilErr = $this->error; + + $this->setSystemCheckSubTabs("system_check_sub"); + + if (!$rbacsystem->checkAccess("visible,read", $this->object->getRefId())) { + $ilErr->raiseError($this->lng->txt("permission_denied"), $ilErr->MESSAGE); + } + //echo "1"; + + if ($_POST['count_limit'] !== null || $_POST['age_limit'] !== null || $_POST['type_limit'] !== null) { + $ilUser->writePref( + 'systemcheck_count_limit', + (is_numeric($_POST['count_limit']) && $_POST['count_limit'] > 0) ? $_POST['count_limit'] : '' + ); + $ilUser->writePref( + 'systemcheck_age_limit', + (is_numeric($_POST['age_limit']) && $_POST['age_limit'] > 0) ? $_POST['age_limit'] : '' + ); + $ilUser->writePref('systemcheck_type_limit', trim($_POST['type_limit'])); + } + + if ($_POST["mode"]) { + //echo "3"; + $this->writeCheckParams(); + $this->startValidator($_POST["mode"], $_POST["log_scan"]); + } else { + //echo "4"; + include_once "./Services/Repository/classes/class.ilValidator.php"; + $validator = new ilValidator(); + $hasScanLog = $validator->hasScanLog(); + + $this->tpl->addBlockFile( + "ADM_CONTENT", + "adm_content", + "tpl.adm_check.html", + "Modules/SystemFolder" + ); + + if ($hasScanLog) { + $this->tpl->setVariable("TXT_VIEW_LOG", $this->lng->txt("view_last_log")); + } + + $this->tpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this)); + $this->tpl->setVariable("TXT_TITLE", $this->lng->txt("systemcheck")); + $this->tpl->setVariable("COLSPAN", 3); + $this->tpl->setVariable("TXT_ANALYZE_TITLE", $this->lng->txt("analyze_data")); + $this->tpl->setVariable("TXT_ANALYSIS_OPTIONS", $this->lng->txt("analysis_options")); + $this->tpl->setVariable("TXT_REPAIR_OPTIONS", $this->lng->txt("repair_options")); + $this->tpl->setVariable("TXT_OUTPUT_OPTIONS", $this->lng->txt("output_options")); + $this->tpl->setVariable("TXT_SCAN", $this->lng->txt("scan")); + $this->tpl->setVariable("TXT_SCAN_DESC", $this->lng->txt("scan_desc")); + $this->tpl->setVariable("TXT_DUMP_TREE", $this->lng->txt("dump_tree")); + $this->tpl->setVariable("TXT_DUMP_TREE_DESC", $this->lng->txt("dump_tree_desc")); + $this->tpl->setVariable("TXT_CLEAN", $this->lng->txt("clean")); + $this->tpl->setVariable("TXT_CLEAN_DESC", $this->lng->txt("clean_desc")); + $this->tpl->setVariable("TXT_RESTORE", $this->lng->txt("restore_missing")); + $this->tpl->setVariable("TXT_RESTORE_DESC", $this->lng->txt("restore_missing_desc")); + $this->tpl->setVariable("TXT_PURGE", $this->lng->txt("purge_missing")); + $this->tpl->setVariable("TXT_PURGE_DESC", $this->lng->txt("purge_missing_desc")); + $this->tpl->setVariable("TXT_RESTORE_TRASH", $this->lng->txt("restore_trash")); + $this->tpl->setVariable("TXT_RESTORE_TRASH_DESC", $this->lng->txt("restore_trash_desc")); + $this->tpl->setVariable("TXT_PURGE_TRASH", $this->lng->txt("purge_trash")); + $this->tpl->setVariable("TXT_PURGE_TRASH_DESC", $this->lng->txt("purge_trash_desc")); + $this->tpl->setVariable("TXT_COUNT_LIMIT", $this->lng->txt("purge_count_limit")); + $this->tpl->setVariable("TXT_COUNT_LIMIT_DESC", $this->lng->txt("purge_count_limit_desc")); + $this->tpl->setVariable("COUNT_LIMIT_VALUE", $ilUser->getPref("systemcheck_count_limit")); + $this->tpl->setVariable("TXT_AGE_LIMIT", $this->lng->txt("purge_age_limit")); + $this->tpl->setVariable("TXT_AGE_LIMIT_DESC", $this->lng->txt("purge_age_limit_desc")); + $this->tpl->setVariable("AGE_LIMIT_VALUE", $ilUser->getPref("systemcheck_age_limit")); + $this->tpl->setVariable("TXT_TYPE_LIMIT", $this->lng->txt("purge_type_limit")); + $this->tpl->setVariable("TXT_TYPE_LIMIT_DESC", $this->lng->txt("purge_type_limit_desc")); + + if ($ilUser->getPref('systemcheck_mode_scan')) { + $this->tpl->touchBlock('mode_scan_checked'); + } + if ($ilUser->getPref('systemcheck_mode_dump_tree')) { + $this->tpl->touchBlock('mode_dump_tree_checked'); + } + if ($ilUser->getPref('systemcheck_mode_clean')) { + $this->tpl->touchBlock('mode_clean_checked'); + } + if ($ilUser->getPref('systemcheck_mode_restore')) { + $this->tpl->touchBlock('mode_restore_checked'); + $this->tpl->touchBlock('mode_purge_disabled'); + } elseif ($ilUser->getPref('systemcheck_mode_purge')) { + $this->tpl->touchBlock('mode_purge_checked'); + $this->tpl->touchBlock('mode_restore_disabled'); + } + if ($ilUser->getPref('systemcheck_mode_restore_trash')) { + $this->tpl->touchBlock('mode_restore_trash_checked'); + $this->tpl->touchBlock('mode_purge_trash_disabled'); + } elseif ($ilUser->getPref('systemcheck_mode_purge_trash')) { + $this->tpl->touchBlock('mode_purge_trash_checked'); + $this->tpl->touchBlock('mode_restore_trash_disabled'); + } + if ($ilUser->getPref('systemcheck_log_scan')) { + $this->tpl->touchBlock('log_scan_checked'); + } + + + // #9520 - restrict to types which can be found in tree + + $obj_types_in_tree = array(); + + $ilDB = $this->db; + $set = $ilDB->query('SELECT type FROM object_data od' . + ' JOIN object_reference ref ON (od.obj_id = ref.obj_id)' . + ' JOIN tree ON (tree.child = ref.ref_id)' . + ' WHERE tree.tree < 1' . + ' GROUP BY type'); + while ($row = $ilDB->fetchAssoc($set)) { + $obj_types_in_tree[] = $row['type']; + } + + $types = $objDefinition->getAllObjects(); + $ts = array("" => ""); + foreach ($types as $t) { + if ($t != "" && !$objDefinition->isSystemObject($t) && $t != "root" && + in_array($t, $obj_types_in_tree)) { + if ($objDefinition->isPlugin($t)) { + $pl = ilObjectPlugin::getPluginObjectByType($t); + $ts[$t] = $pl->txt("obj_" . $t); + } else { + $ts[$t] = $this->lng->txt("obj_" . $t); + } + } + } + asort($ts); + $this->tpl->setVariable( + "TYPE_LIMIT_CHOICE", + ilUtil::formSelect( + $ilUser->getPref("systemcheck_type_limit"), + 'type_limit', + $ts, + false, + true + ) + ); + $this->tpl->setVariable("TXT_LOG_SCAN", $this->lng->txt("log_scan")); + $this->tpl->setVariable("TXT_LOG_SCAN_DESC", $this->lng->txt("log_scan_desc")); + $this->tpl->setVariable("TXT_SUBMIT", $this->lng->txt("start_scan")); + + $this->tpl->setVariable("TXT_SAVE", $this->lng->txt("save_params_for_cron")); + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + + $cron_form = new ilPropertyFormGUI(); + $cron_form->setFormAction($this->ctrl->getFormAction($this)); + $cron_form->setTitle($this->lng->txt('systemcheck_cronform')); + + $radio_group = new ilRadioGroupInputGUI($this->lng->txt('systemcheck_cron'), 'cronjob'); + $radio_group->setValue($ilSetting->get('systemcheck_cron')); + + $radio_opt = new ilRadioOption($this->lng->txt('disabled'), 0); + $radio_group->addOption($radio_opt); + + $radio_opt = new ilRadioOption($this->lng->txt('enabled'), 1); + $radio_group->addOption($radio_opt); + + $cron_form->addItem($radio_group); + + $cron_form->addCommandButton('saveCheckCron', $this->lng->txt('save')); + + $this->tpl->setVariable('CRON_FORM', $cron_form->getHTML()); + } + } + + private function saveCheckParamsObject() + { + $this->writeCheckParams(); + unset($_POST['mode']); + return $this->checkObject(); + } + + private function writeCheckParams() + { + include_once "./Services/Repository/classes/class.ilValidator.php"; + $validator = new ilValidator(); + $modes = $validator->getPossibleModes(); + + $prefs = array(); + foreach ($modes as $mode) { + if (isset($_POST['mode'][$mode])) { + $value = (int) $_POST['mode'][$mode]; + } else { + $value = 0; + } + $prefs[ 'systemcheck_mode_' . $mode ] = $value; + } + + if (isset($_POST['log_scan'])) { + $value = (int) $_POST['log_scan']; + } else { + $value = 0; + } + $prefs['systemcheck_log_scan'] = $value; + + $ilUser = $this->user; + foreach ($prefs as $key => $val) { + $ilUser->writePref($key, $val); + } + } + + private function saveCheckCronObject() + { + $ilSetting = $this->settings; + + $systemcheck_cron = ($_POST['cronjob'] ? 1 : 0); + $ilSetting->set('systemcheck_cron', $systemcheck_cron); + + unset($_POST['mode']); + return $this->checkObject(); + } + + /** + * edit header title form + * + * @access private + */ + public function changeHeaderTitleObject() + { + $rbacsystem = $this->rbacsystem; + $styleDefinition = $this->style_definition; + + $this->tpl->addBlockFile( + "ADM_CONTENT", + "adm_content", + "tpl.header_title_edit.html", + "Modules/SystemFolder" + ); + + $array_push = true; + + if ($_SESSION["error_post_vars"]) { + $_SESSION["translation_post"] = $_SESSION["error_post_vars"]; + $_GET["mode"] = "session"; + $array_push = false; + } + + // load from db if edit category is called the first time + if (($_GET["mode"] != "session")) { + $data = $this->object->getHeaderTitleTranslations(); + $_SESSION["translation_post"] = $data; + $array_push = false; + } // remove a translation from session + elseif ($_GET["entry"] != 0) { + array_splice($_SESSION["translation_post"]["Fobject"], $_GET["entry"], 1, array()); + + if ($_GET["entry"] == $_SESSION["translation_post"]["default_language"]) { + $_SESSION["translation_post"]["default_language"] = ""; + } + } + + $data = $_SESSION["translation_post"]; + + // add additional translation form + if (!$_GET["entry"] and $array_push) { + $count = array_push($data["Fobject"], array("title" => "","desc" => "")); + } else { + $count = count($data["Fobject"]); + } + + // stripslashes in form? + $strip = isset($_SESSION["translation_post"]) ? true : false; + + foreach ($data["Fobject"] as $key => $val) { + // add translation button + if ($key == $count -1) { + $this->tpl->setCurrentBlock("addTranslation"); + $this->tpl->setVariable("TXT_ADD_TRANSLATION", $this->lng->txt("add_translation") . " >>"); + $this->tpl->parseCurrentBlock(); + } + + // remove translation button + if ($key != 0) { + $this->tpl->setCurrentBlock("removeTranslation"); + $this->tpl->setVariable("TXT_REMOVE_TRANSLATION", $this->lng->txt("remove_translation")); + $this->ctrl->setParameter($this, "entry", $key); + $this->ctrl->setParameter($this, "mode", "edit"); + $this->tpl->setVariable( + "LINK_REMOVE_TRANSLATION", + $this->ctrl->getLinkTarget($this, "removeTranslation") + ); + $this->tpl->parseCurrentBlock(); + } + + // lang selection + $this->tpl->addBlockFile( + "SEL_LANGUAGE", + "sel_language", + "tpl.lang_selection.html", + "Services/MetaData" + ); + $this->tpl->setVariable("SEL_NAME", "Fobject[" . $key . "][lang]"); + + include_once('Services/MetaData/classes/class.ilMDLanguageItem.php'); + + $languages = ilMDLanguageItem::_getLanguages(); + + foreach ($languages as $code => $language) { + $this->tpl->setCurrentBlock("lg_option"); + $this->tpl->setVariable("VAL_LG", $code); + $this->tpl->setVariable("TXT_LG", $language); + + if ($code == $val["lang"]) { + $this->tpl->setVariable("SELECTED", "selected=\"selected\""); + } + + $this->tpl->parseCurrentBlock(); + } + + // object data + $this->tpl->setCurrentBlock("obj_form"); + + if ($key == 0) { + $this->tpl->setVariable("TXT_HEADER", $this->lng->txt("change_header_title")); + } else { + $this->tpl->setVariable("TXT_HEADER", $this->lng->txt("translation") . " " . $key); + } + + if ($key == $data["default_language"]) { + $this->tpl->setVariable("CHECKED", "checked=\"checked\""); + } + + $this->tpl->setVariable("TXT_TITLE", $this->lng->txt("title")); + $this->tpl->setVariable("TXT_DESC", $this->lng->txt("desc")); + $this->tpl->setVariable("TXT_DEFAULT", $this->lng->txt("default")); + $this->tpl->setVariable("TXT_LANGUAGE", $this->lng->txt("language")); + $this->tpl->setVariable("TITLE", ilUtil::prepareFormOutput($val["title"], $strip)); + $this->tpl->setVariable("DESC", ilUtil::stripSlashes($val["desc"])); + $this->tpl->setVariable("NUM", $key); + $this->tpl->parseCurrentBlock(); + } + + // global + $this->tpl->setCurrentBlock("adm_content"); + + $this->tpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this)); + $this->tpl->setVariable("TXT_CANCEL", $this->lng->txt("cancel")); + $this->tpl->setVariable("TXT_SUBMIT", $this->lng->txt("save")); + $this->tpl->setVariable("CMD_SUBMIT", "saveHeaderTitle"); + $this->tpl->setVariable("TXT_REQUIRED_FLD", $this->lng->txt("required_field")); + } + + /** + * save header title + */ + public function saveHeaderTitleObject() + { + $ilErr = $this->error; + + $data = $_POST; + + // default language set? + if (!isset($data["default_language"])) { + $ilErr->raiseError($this->lng->txt("msg_no_default_language"), $ilErr->MESSAGE); + } + + // prepare array fro further checks + foreach ($data["Fobject"] as $key => $val) { + $langs[$key] = $val["lang"]; + } + + $langs = array_count_values($langs); + + // all languages set? + if (array_key_exists("", $langs)) { + $ilErr->raiseError($this->lng->txt("msg_no_language_selected"), $ilErr->MESSAGE); + } + + // no single language is selected more than once? + if (array_sum($langs) > count($langs)) { + $ilErr->raiseError($this->lng->txt("msg_multi_language_selected"), $ilErr->MESSAGE); + } + + // copy default translation to variable for object data entry + $_POST["Fobject"]["title"] = $_POST["Fobject"][$_POST["default_language"]]["title"]; + $_POST["Fobject"]["desc"] = $_POST["Fobject"][$_POST["default_language"]]["desc"]; + + // first delete all translation entries... + $this->object->removeHeaderTitleTranslations(); + + // ...and write new translations to object_translation + foreach ($data["Fobject"] as $key => $val) { + if ($key == $data["default_language"]) { + $default = 1; + } else { + $default = 0; + } + + $this->object->addHeaderTitleTranslation(ilUtil::stripSlashes($val["title"]), ilUtil::stripSlashes($val["desc"]), $val["lang"], $default); + } + + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + + $this->ctrl->redirect($this); + } + + public function cancelObject() + { + $this->ctrl->redirect($this, "view"); + } + + /** + * adds a translation form & save post vars to session + * + * @access public + */ + public function addHeaderTitleTranslationObject() + { + $_SESSION["translation_post"] = $_POST; + + $this->ctrl->setParameter($this, "mode", "session"); + $this->ctrl->setParameter($this, "entry", "0"); + $this->ctrl->redirect($this, "changeHeaderTitle"); + } + + /** + * removes a translation form & save post vars to session + * + * @access public + */ + public function removeTranslationObject() + { + $this->ctrl->setParameter($this, "entry", $_GET["entry"]); + $this->ctrl->setParameter($this, "mode", "session"); + $this->ctrl->redirect($this, "changeHeaderTitle"); + } + + + public function startValidator($a_mode, $a_log) + { + $rbacsystem = $this->rbacsystem; + $ilErr = $this->error; + + if (!$rbacsystem->checkAccess("visible,read", $this->object->getRefId())) { + $ilErr->raiseError($this->lng->txt("permission_denied"), $ilErr->MESSAGE); + } + + $logging = ($a_log) ? true : false; + include_once "./Services/Repository/classes/class.ilValidator.php"; + $validator = new ilValidator($logging); + $validator->setMode("all", false); + + $modes = array(); + foreach ($a_mode as $mode => $value) { + $validator->setMode($mode, (bool) $value); + $modes[] = $mode . '=' . $value; + } + + $scan_log = $validator->validate(); + + $mode = $this->lng->txt("scan_modes") . ": " . implode(', ', $modes); + + // output + $this->tpl->addBlockFile( + "ADM_CONTENT", + "adm_content", + "tpl.adm_scan.html", + "Modules/SystemFolder" + ); + + $this->tpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this)); + $this->tpl->setVariable("TXT_TITLE", $this->lng->txt("scanning_system")); + $this->tpl->setVariable("COLSPAN", 3); + $this->tpl->setVariable("TXT_SCAN_LOG", $scan_log); + $this->tpl->setVariable("TXT_MODE", $mode); + + if ($logging === true) { + $this->tpl->setVariable("TXT_VIEW_LOG", $this->lng->txt("view_log")); + } + + $this->tpl->setVariable("TXT_DONE", $this->lng->txt("done")); + + $validator->writeScanLogLine($mode); + } + + public function viewScanLog() + { + include_once "./Services/Repository/classes/class.ilValidator.php"; + $validator = new IlValidator(); + $scan_log =&$validator->readScanLog(); + + if (is_array($scan_log)) { + $scan_log = '
' . 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'), "
'" . ILIAS_HTTP_PATH . "/webservice/soap/server.php?wsdl'")); + $wsdl->setValue((string) $ilSetting->get('soap_wsdl_path')); + $wsdl->setSize(60); + $wsdl->setMaxLength(255); + $this->form->addItem($wsdl); + + // response timeout + $ctime = new ilNumberInputGUI($this->lng->txt('soap_connect_timeout'), 'ctimeout'); + $ctime->setMinValue(1); + $ctime->setSize(2); + $ctime->setMaxLength(3); + include_once './Services/WebServices/SOAP/classes/class.ilSoapClient.php'; + $ctime->setValue((int) $ilSetting->get('soap_connect_timeout', ilSoapClient::DEFAULT_CONNECT_TIMEOUT)); + $ctime->setInfo($this->lng->txt('soap_connect_timeout_info')); + $this->form->addItem($ctime); + + $this->form->addCommandButton("saveWebServices", $lng->txt("save")); + + $this->form->setTitle($lng->txt("webservices")); + $this->form->setFormAction($this->ctrl->getFormAction($this)); + } + + /** + * Save web services form + * + */ + public function saveWebServicesObject() + { + $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->initWebServicesForm(); + if ($this->form->checkInput()) { + $ilSetting->set('soap_user_administration', $this->form->getInput('soap_user_administration')); + $ilSetting->set('soap_wsdl_path', trim($this->form->getInput('soap_wsdl_path'))); + $ilSetting->set('soap_connect_timeout', $this->form->getInput('ctimeout')); + + ilUtil::sendSuccess($lng->txt('msg_obj_modified'), true); + $ilCtrl->redirect($this, 'showWebServices'); + } else { + $this->setGeneralSettingsSubTabs("webservices"); + $this->form->setValuesByPost(); + $tpl->setContent($this->form->getHtml()); + } + } + + // + // + // Java Server + // + // + + /** + * Show Java Server Settings + */ + public function showJavaServerObject() + { + $tpl = $this->tpl; + + $tpl->addBlockFile('ADM_CONTENT', 'adm_content', 'tpl.java_settings.html', 'Modules/SystemFolder'); + + $GLOBALS['lng']->loadLanguageModule('search'); + + include_once './Services/UIComponent/Toolbar/classes/class.ilToolbarGUI.php'; + $toolbar = new ilToolbarGUI(); + $toolbar->addButton( + $this->lng->txt('lucene_create_ini'), + $this->ctrl->getLinkTarget($this, 'createJavaServerIni') + ); + $tpl->setVariable('ACTION_BUTTONS', $toolbar->getHTML()); + + $this->initJavaServerForm(); + $this->setServerInfoSubTabs("java_server"); + $tpl->setVariable('SETTINGS_TABLE', $this->form->getHTML()); + } + + /** + * Create a server ini file + * @return + */ + public function createJavaServerIniObject() + { + $this->setGeneralSettingsSubTabs('java_server'); + $this->initJavaServerIniForm(); + $this->tpl->setContent($this->form->getHTML()); + } + + protected function initJavaServerIniForm() + { + include_once './Services/Form/classes/class.ilPropertyFormGUI.php'; + + $this->form = new ilPropertyFormGUI(); + + $GLOBALS['lng']->loadLanguageModule('search'); + + $this->form->setTitle($this->lng->txt('lucene_tbl_create_ini')); + $this->form->setFormAction($this->ctrl->getFormAction($this, 'createJavaServerIni')); + $this->form->addCommandButton('downloadJavaServerIni', $this->lng->txt('lucene_download_ini')); + $this->form->addCommandButton('showJavaServer', $this->lng->txt('cancel')); + + // Host + $ip = new ilTextInputGUI($this->lng->txt('lucene_host'), 'ho'); + $ip->setInfo($this->lng->txt('lucene_host_info')); + $ip->setMaxLength(128); + $ip->setSize(32); + $ip->setRequired(true); + $this->form->addItem($ip); + + // Port + $port = new ilNumberInputGUI($this->lng->txt('lucene_port'), 'po'); + $port->setSize(5); + $port->setMinValue(1); + $port->setMaxValue(65535); + $port->setRequired(true); + $this->form->addItem($port); + + // Index Path + $path = new ilTextInputGUI($this->lng->txt('lucene_index_path'), 'in'); + $path->setSize(80); + $path->setMaxLength(1024); + $path->setInfo($this->lng->txt('lucene_index_path_info')); + $path->setRequired(true); + $this->form->addItem($path); + + // Logging + $log = new ilTextInputGUI($this->lng->txt('lucene_log'), 'lo'); + $log->setSize(80); + $log->setMaxLength(1024); + $log->setInfo($this->lng->txt('lucene_log_info')); + $log->setRequired(true); + $this->form->addItem($log); + + // Level + $lev = new ilSelectInputGUI($this->lng->txt('lucene_level'), 'le'); + $lev->setOptions(array( + 'DEBUG' => 'DEBUG', + 'INFO' => 'INFO', + 'WARN' => 'WARN', + 'ERROR' => 'ERROR', + 'FATAL' => 'FATAL')); + $lev->setValue('INFO'); + $lev->setRequired(true); + $this->form->addItem($lev); + + // CPU + $cpu = new ilNumberInputGUI($this->lng->txt('lucene_cpu'), 'cp'); + $cpu->setValue(1); + $cpu->setSize(1); + $cpu->setMaxLength(2); + $cpu->setMinValue(1); + $cpu->setRequired(true); + $this->form->addItem($cpu); + + // Max file size + $fs = new ilNumberInputGUI($this->lng->txt('lucene_max_fs'), 'fs'); + $fs->setInfo($this->lng->txt('lucene_max_fs_info')); + $fs->setValue(500); + $fs->setSize(4); + $fs->setMaxLength(4); + $fs->setMinValue(1); + $fs->setRequired(true); + $this->form->addItem($fs); + + return true; + } + + /** + * Create and offer server ini file for download + * @return + */ + protected function downloadJavaServerIniObject() + { + $this->initJavaServerIniForm(); + if ($this->form->checkInput()) { + include_once './Services/WebServices/RPC/classes/class.ilRpcIniFileWriter.php'; + $ini = new ilRpcIniFileWriter(); + $ini->setHost($this->form->getInput('ho')); + $ini->setPort($this->form->getInput('po')); + $ini->setIndexPath($this->form->getInput('in')); + $ini->setLogPath($this->form->getInput('lo')); + $ini->setLogLevel($this->form->getInput('le')); + $ini->setNumThreads($this->form->getInput('cp')); + $ini->setMaxFileSize($this->form->getInput('fs')); + + $ini->write(); + ilUtil::deliverData($ini->getIniString(), 'ilServer.ini', 'text/plain', 'utf-8'); + return true; + } + + $this->form->setValuesByPost(); + ilUtil::sendFailure($this->lng->txt('err_check_input')); + $this->setGeneralSettingsSubTabs('java_server'); + $this->tpl->setContent($this->form->getHTML()); + return true; + } + + /** + * Init java server form. + */ + public function initJavaServerForm() + { + $lng = $this->lng; + $ilSetting = $this->settings; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + // host + $ti = new ilTextInputGUI($this->lng->txt("java_server_host"), "rpc_server_host"); + $ti->setMaxLength(64); + $ti->setSize(32); + $ti->setValue($ilSetting->get("rpc_server_host")); + $this->form->addItem($ti); + + // port + $ti = new ilNumberInputGUI($this->lng->txt("java_server_port"), "rpc_server_port"); + $ti->setMaxLength(5); + $ti->setSize(5); + $ti->setValue($ilSetting->get("rpc_server_port")); + $this->form->addItem($ti); + + // pdf fonts + $pdf = new ilFormSectionHeaderGUI(); + $pdf->setTitle($this->lng->txt('rpc_pdf_generation')); + $this->form->addItem($pdf); + + $pdf_font = new ilTextInputGUI($this->lng->txt('rpc_pdf_font'), 'rpc_pdf_font'); + $pdf_font->setInfo($this->lng->txt('rpc_pdf_font_info')); + $pdf_font->setSize(64); + $pdf_font->setMaxLength(1024); + $pdf_font->setRequired(true); + $pdf_font->setValue( + $ilSetting->get('rpc_pdf_font', 'Helvetica, unifont') + ); + $this->form->addItem($pdf_font); + + + // save and cancel commands + $this->form->addCommandButton("saveJavaServer", $lng->txt("save")); + + $this->form->setTitle($lng->txt("java_server")); + $this->form->setDescription($lng->txt("java_server_info") . + '
' . + $lng->txt("java_server_readme") . ''); + $this->form->setFormAction($this->ctrl->getFormAction($this)); + } + + /** + * Save java server form + * + */ + public function saveJavaServerObject() + { + $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->initJavaServerForm(); + if ($this->form->checkInput()) { + $ilSetting->set("rpc_server_host", trim($_POST["rpc_server_host"])); + $ilSetting->set("rpc_server_port", trim($_POST["rpc_server_port"])); + $ilSetting->set('rpc_pdf_font', ilUtil::stripSlashes($_POST['rpc_pdf_font'])); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "showJavaServer"); + + // TODO check settings, ping server + } else { + $this->setGeneralSettingsSubTabs("java_server"); + $this->form->setValuesByPost(); + $tpl->setContent($this->form->getHtml()); + } + } + + /** + * + * Show proxy settings + * + * @access public + * + */ + public function showProxyObject() + { + $tpl = $this->tpl; + $ilAccess = $this->access; + $ilErr = $this->error; + + if (!$ilAccess->checkAccess('write', '', $this->object->getRefId())) { + $ilErr->raiseError($this->lng->txt('permission_denied'), $ilErr->MESSAGE); + } + + require_once './Services/Http/classes/class.ilProxySettings.php'; + + $this->initProxyForm(); + $this->form->setValuesByArray(array( + 'proxy_status' => ilProxySettings::_getInstance()->isActive(), + 'proxy_host' => ilProxySettings::_getInstance()->getHost(), + 'proxy_port' => ilProxySettings::_getInstance()->getPort() + )); + if (ilProxySettings::_getInstance()->isActive()) { + $this->printProxyStatus(); + } + + $tpl->setContent($this->form->getHTML()); + } + + /** + * + * Print proxy settings + * + * @access private + * + */ + private function printProxyStatus() + { + try { + ilProxySettings::_getInstance()->checkConnection(); + $this->form->getItemByPostVar('proxy_availability')->setHTML( + ' ' . + $this->lng->txt('proxy_connectable') + ); + } catch (ilProxyException $e) { + $this->form->getItemByPostVar('proxy_availability')->setHTML( + ' ' . + $this->lng->txt('proxy_not_connectable') + ); + ilUtil::sendFailure(sprintf($this->lng->txt('proxy_socket_error'), $e->getMessage())); + } + } + + /** + * + * Save proxy settings + * + * @access public + * + */ + public function saveProxyObject() + { + $tpl = $this->tpl; + $ilAccess = $this->access; + $ilErr = $this->error; + $lng = $this->lng; + + if (!$ilAccess->checkAccess('write', '', $this->object->getRefId())) { + $ilErr->raiseError($lng->txt('permission_denied'), $ilErr->MESSAGE); + } + + require_once './Services/Http/classes/class.ilProxySettings.php'; + + $this->initProxyForm(); + $isFormValid = $this->form->checkInput(); + ilProxySettings::_getInstance()->isActive((int) $this->form->getInput('proxy_status')) + ->setHost(trim($this->form->getInput('proxy_host'))) + ->setPort(trim($this->form->getInput('proxy_port'))); + if ($isFormValid) { + if (ilProxySettings::_getInstance()->isActive()) { + if (!strlen(ilProxySettings::_getInstance()->getHost())) { + $isFormValid = false; + $this->form->getItemByPostVar('proxy_host')->setAlert($lng->txt('msg_input_is_required')); + } + if (!strlen(ilProxySettings::_getInstance()->getPort())) { + $isFormValid = false; + $this->form->getItemByPostVar('proxy_port')->setAlert($lng->txt('msg_input_is_required')); + } + if (!preg_match('/[0-9]{1,}/', ilProxySettings::_getInstance()->getPort()) || + ilProxySettings::_getInstance()->getPort() < 0 || + ilProxySettings::_getInstance()->getPort() > 65535) { + $isFormValid = false; + $this->form->getItemByPostVar('proxy_port')->setAlert($lng->txt('proxy_port_numeric')); + } + } + + if ($isFormValid) { + ilProxySettings::_getInstance()->save(); + ilUtil::sendSuccess($lng->txt('saved_successfully')); + if (ilProxySettings::_getInstance()->isActive()) { + $this->printProxyStatus(); + } + } else { + ilUtil::sendFailure($lng->txt('form_input_not_valid')); + } + } + + $this->form->setValuesByPost(); + $tpl->setContent($this->form->getHTML()); + } + + /** + * + * Initialize proxy settings form + * + * @access public + * + */ + private function initProxyForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $this->setServerInfoSubTabs('proxy'); + + include_once('Services/Form/classes/class.ilPropertyFormGUI.php'); + $this->form = new ilPropertyFormGUI(); + $this->form->setFormAction($ilCtrl->getFormAction($this, 'saveProxy')); + + // Proxy status + $proxs = new ilCheckboxInputGUI($lng->txt('proxy_status'), 'proxy_status'); + $proxs->setInfo($lng->txt('proxy_status_info')); + $proxs->setValue(1); + $this->form->addItem($proxs); + + // Proxy availability + $proxa = new ilCustomInputGUI('', 'proxy_availability'); + $proxs->addSubItem($proxa); + + // Proxy + $prox = new ilTextInputGUI($lng->txt('proxy_host'), 'proxy_host'); + $prox->setInfo($lng->txt('proxy_host_info')); + $proxs->addSubItem($prox); + + // Proxy Port + $proxp = new ilTextInputGUI($lng->txt('proxy_port'), 'proxy_port'); + $proxp->setInfo($lng->txt('proxy_port_info')); + $proxp->setSize(10); + $proxp->setMaxLength(10); + $proxs->addSubItem($proxp); + + // save and cancel commands + $this->form->addCommandButton('saveProxy', $lng->txt('save')); + } + + public function showHTTPSObject() + { + $tpl = $this->tpl; + $ilAccess = $this->access; + $ilErr = $this->error; + + if (!$ilAccess->checkAccess('write', '', $this->object->getRefId())) { + $ilErr->raiseError($this->lng->txt('permission_denied'), $ilErr->MESSAGE); + } + + $form = $this->initHTTPSForm(); + $tpl->setContent($form->getHTML()); + } + + public function saveHTTPSObject() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $form = $this->initHTTPSForm(); + if ($form->checkInput()) { + $security = ilSecuritySettings::_getInstance(); + + // ilias https handling settings + $security->setHTTPSEnabled($_POST["https_enabled"]); + + if ($security->validate($form)) { + $security->save(); + + ilUtil::sendSuccess($lng->txt('saved_successfully'), true); + $ilCtrl->redirect($this, "showHTTPS"); + } + } + + $form->setValuesByPost(); + $tpl->setContent($form->getHTML()); + } + + private function initHTTPSForm() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->setServerInfoSubTabs('adm_https'); + + $lng->loadLanguageModule('ps'); + + include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php'); + $security = ilSecuritySettings::_getInstance(); + + include_once('Services/Form/classes/class.ilPropertyFormGUI.php'); + $form = new ilPropertyFormGUI(); + $form->setTitle($lng->txt("adm_https")); + $form->setFormAction($ilCtrl->getFormAction($this, 'saveHTTPS')); + + $check2 = new ilCheckboxInputGUI($lng->txt('activate_https'), 'https_enabled'); + $check2->setChecked($security->isHTTPSEnabled() ? 1 : 0); + $check2->setValue(1); + $form->addItem($check2); + + // save and cancel commands + $form->addCommandButton('saveHTTPS', $lng->txt('save')); + + return $form; + } + + public function addToExternalSettingsForm($a_form_id) + { + switch ($a_form_id) { + case ilAdministrationSettingsFormHandler::FORM_SECURITY: + + include_once('./Services/PrivacySecurity/classes/class.ilSecuritySettings.php'); + $security = ilSecuritySettings::_getInstance(); + + $subitems = null; + + $fields['activate_https'] = + array($security->isHTTPSEnabled(), ilAdministrationSettingsFormHandler::VALUE_BOOL); + + return array("general_settings" => array("showHTTPS", $fields)); + } + } + + /** + * goto target group + */ + public static function _goto() + { + global $DIC; + + $ilAccess = $DIC->access(); + $ilErr = $DIC["ilErr"]; + $lng = $DIC->language(); + + $a_target = SYSTEM_FOLDER_ID; + + if ($ilAccess->checkAccess("read", "", $a_target)) { + ilUtil::redirect("ilias.php?baseClass=ilAdministrationGUI"); + exit; + } else { + if ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) { + ilUtil::sendFailure(sprintf( + $lng->txt("msg_no_perm_read_item"), + ilObject::_lookupTitle(ilObject::_lookupObjId($a_target)) + ), true); + ilObjectGUI::_gotoRepositoryRoot(); + } + } + $ilErr->raiseError($lng->txt("msg_no_perm_read"), $ilErr->FATAL); + } + + /** + * + */ + protected function showVcsInformationObject() + { + $vc_info = array(); + + require_once 'Services/Administration/classes/class.ilSubversionInformation.php'; + require_once 'Services/Administration/classes/class.ilGitInformation.php'; + + foreach (array(new ilSubversionInformation(), new ilGitInformation()) as $vc) { + $html = $vc->getInformationAsHtml(); + if ($html) { + $vc_info[] = $html; + } + } + + if ($vc_info) { + ilUtil::sendInfo(implode("
", $vc_info)); + } else { + ilUtil::sendInfo($this->lng->txt('vc_information_not_determined')); + } + + $this->showServerInfoObject(); + } } diff --git a/Modules/SystemFolder/classes/class.ilSystemSupportContacts.php b/Modules/SystemFolder/classes/class.ilSystemSupportContacts.php index 5837d6af1bca409784d95f74d29274e72fc80885..e958e645d14321bdade130296f4c7a6178038e30 100644 --- a/Modules/SystemFolder/classes/class.ilSystemSupportContacts.php +++ b/Modules/SystemFolder/classes/class.ilSystemSupportContacts.php @@ -11,75 +11,69 @@ */ class ilSystemSupportContacts { - /** - * Get list - * - * @return string comma separated list of contacts - */ - static function getList() - { - global $DIC; + /** + * Get list + * + * @return string comma separated list of contacts + */ + public static function getList() + { + global $DIC; - $ilSetting = $DIC->settings(); + $ilSetting = $DIC->settings(); - return $ilSetting->get("adm_support_contacts"); - } - - /** - * Set list - * - * @param string $a_list comma separated list of contacts - */ - static function setList($a_list) - { - global $DIC; + return $ilSetting->get("adm_support_contacts"); + } + + /** + * Set list + * + * @param string $a_list comma separated list of contacts + */ + public static function setList($a_list) + { + global $DIC; - $ilSetting = $DIC->settings(); + $ilSetting = $DIC->settings(); - $list = explode(",", $a_list); - $accounts = array(); - foreach ($list as $l) - { - if (ilObjUser::_lookupId(trim($l)) > 0) - { - $accounts[] = trim($l); - } - } + $list = explode(",", $a_list); + $accounts = array(); + foreach ($list as $l) { + if (ilObjUser::_lookupId(trim($l)) > 0) { + $accounts[] = trim($l); + } + } - return $ilSetting->set("adm_support_contacts", implode(",", $accounts)); - } + return $ilSetting->set("adm_support_contacts", implode(",", $accounts)); + } - /** - * Get valid support contacts - * - * @return array array of user IDs - */ - static function getValidSupportContactIds() - { - $list = self::getList(); - $list = explode(",", $list); + /** + * Get valid support contacts + * + * @return array array of user IDs + */ + public static function getValidSupportContactIds() + { + $list = self::getList(); + $list = explode(",", $list); - return ilObjUser::_lookupId($list); - } + return ilObjUser::_lookupId($list); + } - /** - * Get mailto: email - * - * @param - * @return - */ - static function getMailToAddress() - { - $emails = array(); - foreach (self::getValidSupportContactIds() as $id) - { - if (($e = ilObjUser::_lookupEmail($id)) != "") - { - return $e; - } - } - return ""; - } + /** + * Get mailto: email + * + * @param + * @return + */ + public static function getMailToAddress() + { + $emails = array(); + foreach (self::getValidSupportContactIds() as $id) { + if (($e = ilObjUser::_lookupEmail($id)) != "") { + return $e; + } + } + return ""; + } } - -?> \ No newline at end of file diff --git a/Modules/SystemFolder/classes/class.ilSystemSupportContactsGUI.php b/Modules/SystemFolder/classes/class.ilSystemSupportContactsGUI.php index 5a1465e876966696fdf507a13e44ee733fd29787..43d584d9a432a63d2b1c22f090ccceb9355f8b80 100644 --- a/Modules/SystemFolder/classes/class.ilSystemSupportContactsGUI.php +++ b/Modules/SystemFolder/classes/class.ilSystemSupportContactsGUI.php @@ -11,134 +11,123 @@ */ class ilSystemSupportContactsGUI { - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilLanguage - */ - protected $lng; - - protected $ctrl; - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $ilCtrl = $DIC->ctrl(); - $tpl = $DIC["tpl"]; - $lng = $DIC->language(); - - $this->ctrl = $ilCtrl; - $this->tpl = $tpl; - $this->lng = $lng; - } - - - /** - * Execute command - */ - function executeCommand() - { - $cmd = $this->ctrl->getCmd("showContacts"); - if (in_array($cmd, array("showContacts"))) - { - $this->$cmd(); - } - } - - /** - * Show contacts - */ - function showContacts() - { - $this->lng->loadLanguageModule("adm"); - $this->tpl->getStandardTemplate(); - $this->tpl->setTitle($this->lng->txt("adm_support_contacts")); - include_once("./Services/UIComponent/Panel/classes/class.ilPanelGUI.php"); - $panel = ilPanelGUI::getInstance(); - $panel->setPanelStyle(ilPanelGUI::PANEL_STYLE_PRIMARY); - - $html = ""; - include_once("./Modules/SystemFolder/classes/class.ilSystemSupportContacts.php"); - foreach (ilSystemSupportContacts::getValidSupportContactIds() as $c) - { - include_once("./Services/User/classes/class.ilPublicUserProfileGUI.php"); - $pgui = new ilPublicUserProfileGUI($c); - //$pgui->setBackUrl($this->ctrl->getLinkTargetByClass("ilinfoscreengui")); - $pgui->setEmbedded(true); - $html.= $pgui->getHTML(); - } - - $panel->setBody($html); - - $this->tpl->setContent($panel->getHTML()); - $this->tpl->show(); - } - - - /** - * Get footer link - * - * @return string footer link - */ - static function getFooterLink() - { - global $DIC; - - $ilCtrl = $DIC->ctrl(); - $ilUser = $DIC->user(); - - include_once("./Modules/SystemFolder/classes/class.ilSystemSupportContacts.php"); - - $users = ilSystemSupportContacts::getValidSupportContactIds(); - if (count($users) > 0) - { - // #17847 - we cannot use a proper GUI on the login screen - if(!$ilUser->getId()) - { - foreach($users as $user) - { - $mail = ilObjUser::_lookupEmail($user); - if(trim($mail)) - { - return "mailto:".$mail; - } - } - } - else - { - return $ilCtrl->getLinkTargetByClass("ilsystemsupportcontactsgui", "", "", false, false); - } - } - - - /*$m = ilUtil::prepareFormOutput(ilSystemSupportContacts::getMailToAddress()); - if ($m != "") - { - return "mailto:".$m; - }*/ - return ""; - } - - /** - * Get footer text - * - * @return string footer text - */ - static function getFooterText() - { - global $DIC; - - $lng = $DIC->language(); - return $lng->txt("contact_sysadmin"); - } - + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilLanguage + */ + protected $lng; + + protected $ctrl; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $ilCtrl = $DIC->ctrl(); + $tpl = $DIC["tpl"]; + $lng = $DIC->language(); + + $this->ctrl = $ilCtrl; + $this->tpl = $tpl; + $this->lng = $lng; + } + + + /** + * Execute command + */ + public function executeCommand() + { + $cmd = $this->ctrl->getCmd("showContacts"); + if (in_array($cmd, array("showContacts"))) { + $this->$cmd(); + } + } + + /** + * Show contacts + */ + public function showContacts() + { + $this->lng->loadLanguageModule("adm"); + $this->tpl->getStandardTemplate(); + $this->tpl->setTitle($this->lng->txt("adm_support_contacts")); + include_once("./Services/UIComponent/Panel/classes/class.ilPanelGUI.php"); + $panel = ilPanelGUI::getInstance(); + $panel->setPanelStyle(ilPanelGUI::PANEL_STYLE_PRIMARY); + + $html = ""; + include_once("./Modules/SystemFolder/classes/class.ilSystemSupportContacts.php"); + foreach (ilSystemSupportContacts::getValidSupportContactIds() as $c) { + include_once("./Services/User/classes/class.ilPublicUserProfileGUI.php"); + $pgui = new ilPublicUserProfileGUI($c); + //$pgui->setBackUrl($this->ctrl->getLinkTargetByClass("ilinfoscreengui")); + $pgui->setEmbedded(true); + $html.= $pgui->getHTML(); + } + + $panel->setBody($html); + + $this->tpl->setContent($panel->getHTML()); + $this->tpl->show(); + } + + + /** + * Get footer link + * + * @return string footer link + */ + public static function getFooterLink() + { + global $DIC; + + $ilCtrl = $DIC->ctrl(); + $ilUser = $DIC->user(); + + include_once("./Modules/SystemFolder/classes/class.ilSystemSupportContacts.php"); + + $users = ilSystemSupportContacts::getValidSupportContactIds(); + if (count($users) > 0) { + // #17847 - we cannot use a proper GUI on the login screen + if (!$ilUser->getId()) { + foreach ($users as $user) { + $mail = ilObjUser::_lookupEmail($user); + if (trim($mail)) { + return "mailto:" . $mail; + } + } + } else { + return $ilCtrl->getLinkTargetByClass("ilsystemsupportcontactsgui", "", "", false, false); + } + } + + + /*$m = ilUtil::prepareFormOutput(ilSystemSupportContacts::getMailToAddress()); + if ($m != "") + { + return "mailto:".$m; + }*/ + return ""; + } + + /** + * Get footer text + * + * @return string footer text + */ + public static function getFooterText() + { + global $DIC; + + $lng = $DIC->language(); + return $lng->txt("contact_sysadmin"); + } } - -?> \ No newline at end of file diff --git a/Modules/Wiki/classes/class.ilECSWikiSettings.php b/Modules/Wiki/classes/class.ilECSWikiSettings.php index 96056f5c6e401e83bfed3c6c27b617f09e575f88..2f362cea9f500649cc81f906398d06091f44fdd8 100644 --- a/Modules/Wiki/classes/class.ilECSWikiSettings.php +++ b/Modules/Wiki/classes/class.ilECSWikiSettings.php @@ -1,32 +1,30 @@ - -* $Id: class.ilObjCourseGUI.php 31646 2011-11-14 11:39:37Z jluetzen $ -* -* @ingroup Modules/Wiki -*/ -class ilECSWikiSettings extends ilECSObjectSettings -{ - protected function getECSObjectType() - { - return '/campusconnect/wikis'; - } - - protected function buildJson(ilECSSetting $a_server) - { - $json = $this->getJsonCore('application/ecs-wiki'); - - $json->availability = $this->content_obj->getOnline() ? 'online' : 'offline'; - - return $json; - } -} - -?> \ No newline at end of file + +* $Id: class.ilObjCourseGUI.php 31646 2011-11-14 11:39:37Z jluetzen $ +* +* @ingroup Modules/Wiki +*/ +class ilECSWikiSettings extends ilECSObjectSettings +{ + protected function getECSObjectType() + { + return '/campusconnect/wikis'; + } + + protected function buildJson(ilECSSetting $a_server) + { + $json = $this->getJsonCore('application/ecs-wiki'); + + $json->availability = $this->content_obj->getOnline() ? 'online' : 'offline'; + + return $json; + } +} diff --git a/Modules/Wiki/classes/class.ilImportantPagesTableGUI.php b/Modules/Wiki/classes/class.ilImportantPagesTableGUI.php index b9c635f47bab1911e56bf5a5c1157a11e2f4c969..cb61627389b86679683733e0b0b62678c54cda4b 100644 --- a/Modules/Wiki/classes/class.ilImportantPagesTableGUI.php +++ b/Modules/Wiki/classes/class.ilImportantPagesTableGUI.php @@ -13,84 +13,92 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilImportantPagesTableGUI extends ilTable2GUI { - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd) - { - global $DIC; + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd) + { + 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(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - $data = array("page_id" => 0) + - ilObjWiki::_lookupImportantPagesList($a_parent_obj->object->getId()); - $this->setData($data); - $this->setTitle($lng->txt("")); - $this->setLimit(9999); - - $this->addColumn("", "", "1", true); - $this->addColumn($this->lng->txt("wiki_ordering"), "order"); - $this->addColumn($this->lng->txt("wiki_indentation")); - $this->addColumn($this->lng->txt("wiki_page")); - $this->addColumn($this->lng->txt("wiki_purpose")); - - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.imp_pages_row.html", "Modules/Wiki"); - //$this->disable("footer"); - $this->setEnableTitle(true); - - $this->addMultiCommand("confirmRemoveImportantPages", $lng->txt("remove")); - $this->addMultiCommand("setAsStartPage", $lng->txt("wiki_set_as_start_page")); - $this->addCommandButton("saveOrderingAndIndent", $lng->txt("wiki_save_ordering_and_indent")); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; + $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); + $data = array("page_id" => 0) + + ilObjWiki::_lookupImportantPagesList($a_parent_obj->object->getId()); + $this->setData($data); + $this->setTitle($lng->txt("")); + $this->setLimit(9999); + + $this->addColumn("", "", "1", true); + $this->addColumn($this->lng->txt("wiki_ordering"), "order"); + $this->addColumn($this->lng->txt("wiki_indentation")); + $this->addColumn($this->lng->txt("wiki_page")); + $this->addColumn($this->lng->txt("wiki_purpose")); + + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.imp_pages_row.html", "Modules/Wiki"); + //$this->disable("footer"); + $this->setEnableTitle(true); + + $this->addMultiCommand("confirmRemoveImportantPages", $lng->txt("remove")); + $this->addMultiCommand("setAsStartPage", $lng->txt("wiki_set_as_start_page")); + $this->addCommandButton("saveOrderingAndIndent", $lng->txt("wiki_save_ordering_and_indent")); + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; - if ($a_set["page_id"] > 0) - { - $this->tpl->setCurrentBlock("cb"); - $this->tpl->setVariable("PAGE_ID", $a_set["page_id"]); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setCurrentBlock("ord"); - $this->tpl->setVariable("PAGE_ID_ORD", $a_set["page_id"]); - $this->tpl->setVariable("VAL_ORD", $a_set["ord"]); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setVariable("PAGE_TITLE", - ilWikiPage::lookupTitle($a_set["page_id"])); - $this->tpl->setVariable("SEL_INDENT", - ilUtil::formSelect($a_set["indent"], "indent[".$a_set["page_id"]."]", - array(0 => "0", 1 => "1", 2 => "2"), false, true)); - } - else - { - $this->tpl->setVariable("PAGE_TITLE", - ($this->getParentObject()->object->getStartPage())); + if ($a_set["page_id"] > 0) { + $this->tpl->setCurrentBlock("cb"); + $this->tpl->setVariable("PAGE_ID", $a_set["page_id"]); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setCurrentBlock("ord"); + $this->tpl->setVariable("PAGE_ID_ORD", $a_set["page_id"]); + $this->tpl->setVariable("VAL_ORD", $a_set["ord"]); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setVariable( + "PAGE_TITLE", + ilWikiPage::lookupTitle($a_set["page_id"]) + ); + $this->tpl->setVariable( + "SEL_INDENT", + ilUtil::formSelect( + $a_set["indent"], + "indent[" . $a_set["page_id"] . "]", + array(0 => "0", 1 => "1", 2 => "2"), + false, + true + ) + ); + } else { + $this->tpl->setVariable( + "PAGE_TITLE", + ($this->getParentObject()->object->getStartPage()) + ); - $this->tpl->setVariable("PURPOSE", - $lng->txt("wiki_start_page")); - } - } - + $this->tpl->setVariable( + "PURPOSE", + $lng->txt("wiki_start_page") + ); + } + } } -?> diff --git a/Modules/Wiki/classes/class.ilMediaWikiAdapter.php b/Modules/Wiki/classes/class.ilMediaWikiAdapter.php index b9bdaee415e9d67e6e39874645261bfbfc66ef53..2a7005b8f22d82881dca5fc85201bf76105affb9 100755 --- a/Modules/Wiki/classes/class.ilMediaWikiAdapter.php +++ b/Modules/Wiki/classes/class.ilMediaWikiAdapter.php @@ -1,24 +1,24 @@ diff --git a/Modules/Wiki/classes/class.ilObjWiki.php b/Modules/Wiki/classes/class.ilObjWiki.php index a71842e1a27da961d22581574cf703acecffd1de..8cef461add22e2a4d10809c7820ac008ed7d4f3d 100755 --- a/Modules/Wiki/classes/class.ilObjWiki.php +++ b/Modules/Wiki/classes/class.ilObjWiki.php @@ -19,1173 +19,1138 @@ include_once "./Services/AdvancedMetaData/interfaces/interface.ilAdvancedMetaDat */ class ilObjWiki extends ilObject implements ilAdvancedMetaDataSubItems { - /** - * @var ilObjUser - */ - protected $user; - - protected $online = false; - protected $public_notes = true; - protected $empty_page_templ = true; - protected $link_md_values = false; - - /** - * Constructor - * @access public - * @param integer reference_id or object_id - * @param boolean treat the id as reference_id (true) or object_id (false) - */ - function __construct($a_id = 0,$a_call_by_reference = true) - { - global $DIC; - - $this->db = $DIC->database(); - $this->user = $DIC->user(); - $this->type = "wiki"; - parent::__construct($a_id,$a_call_by_reference); - } - - /** - * Set Online. - * - * @param boolean $a_online Online - */ - function setOnline($a_online) - { - $this->online = $a_online; - } - - /** - * Get Online. - * - * @return boolean Online - */ - function getOnline() - { - return $this->online; - } - - /** - * Set Enable Rating For Object. - * - * @param boolean $a_rating Enable Rating - */ - function setRatingOverall($a_rating) - { - $this->rating_overall = (bool)$a_rating; - } - - /** - * Get Enable Rating For Object. - * - * @return boolean Enable Rating - */ - function getRatingOverall() - { - return $this->rating_overall; - } - - /** - * Set Enable Rating. - * - * @param boolean $a_rating Enable Rating - */ - function setRating($a_rating) - { - $this->rating = (bool)$a_rating; - } - - /** - * Get Enable Rating. - * - * @return boolean Enable Rating - */ - function getRating() - { - return $this->rating; - } - - /** - * Set Enable Rating Side Block. - * - * @param boolean $a_rating - */ - function setRatingAsBlock($a_rating) - { - $this->rating_block = (bool)$a_rating; - } - - /** - * Get Enable Rating Side Block. - * - * @return boolean - */ - function getRatingAsBlock() - { - return $this->rating_block; - } - - /** - * Set Enable Rating For New Pages. - * - * @param boolean $a_rating - */ - function setRatingForNewPages($a_rating) - { - $this->rating_new_pages = (bool)$a_rating; - } - - /** - * Get Enable Rating For New Pages. - * - * @return boolean - */ - function getRatingForNewPages() - { - return $this->rating_new_pages; - } - - /** - * Set Enable Rating Categories. - * - * @param boolean $a_rating - */ - function setRatingCategories($a_rating) - { - $this->rating_categories = (bool)$a_rating; - } - - /** - * Get Enable Rating Categories. - * - * @return boolean - */ - function getRatingCategories() - { - return $this->rating_categories; - } - - /** - * Set public notes - */ - public function setPublicNotes($a_val) - { - $this->public_notes = $a_val; - } - - /** - * Get public notes - */ - public function getPublicNotes() - { - return $this->public_notes; - } - - /** - * Set important pages - * - * @param boolean $a_val important pages - */ - public function setImportantPages($a_val) - { - $this->imp_pages = $a_val; - } - - /** - * Get important pages - * - * @return boolean important pages - */ - public function getImportantPages() - { - return $this->imp_pages; - } - - /** - * Set Start Page. - * - * @param string $a_startpage Start Page - */ - function setStartPage($a_startpage) - { - $this->startpage = ilWikiUtil::makeDbTitle($a_startpage); - } - - /** - * Get Start Page. - * - * @return string Start Page - */ - function getStartPage() - { - return $this->startpage; - } - - /** - * Set ShortTitle. - * - * @param string $a_shorttitle ShortTitle - */ - function setShortTitle($a_shorttitle) - { - $this->shorttitle = $a_shorttitle; - } - - /** - * Get ShortTitle. - * - * @return string ShortTitle - */ - function getShortTitle() - { - return $this->shorttitle; - } - - /** - * Set Introduction. - * - * @param string $a_introduction Introduction - */ - function setIntroduction($a_introduction) - { - $this->introduction = $a_introduction; - } - - /** - * Get Introduction. - * - * @return string Introduction - */ - function getIntroduction() - { - return $this->introduction; - } - - /** - * get ID of assigned style sheet object - */ - function getStyleSheetId() - { - return $this->style_id; - } - - /** - * set ID of assigned style sheet object - */ - function setStyleSheetId($a_style_id) - { - $this->style_id = $a_style_id; - } - - /** - * Set page toc - * - * @param boolean $a_val page toc - */ - public function setPageToc($a_val) - { - $this->page_toc = $a_val; - } - - /** - * Get page toc - * - * @return boolean page toc - */ - public function getPageToc() - { - return $this->page_toc; - } - - /** - * Set empty page template - * - * @param boolean $a_val empty page template - */ - function setEmptyPageTemplate($a_val) - { - $this->empty_page_templ = $a_val; - } - - /** - * Get empty page template - * - * @return boolean empty page template - */ - function getEmptyPageTemplate() - { - return $this->empty_page_templ; - } - - /** - * Set link md values - * - * @param bool $a_val link metadata values - */ - function setLinkMetadataValues($a_val) - { - $this->link_md_values = $a_val; - } - - /** - * Get link md values - * - * @return bool link metadata values - */ - function getLinkMetadataValues() - { - return $this->link_md_values; - } - - /** - * Is wiki an online help wiki? - * - * @return boolean true, if current wiki is an online help wiki - */ - static function isOnlineHelpWiki($a_ref_id) - { - if ($a_ref_id > 0 && $a_ref_id == OH_REF_ID) - { -// return true; - } - return false; - } - - /** - * Create new wiki - */ - function create($a_prevent_start_page_creation = false) - { - $ilDB = $this->db; - - parent::create(); - - $ilDB->insert("il_wiki_data", array( - "id" => array("integer", $this->getId()), - "is_online" => array("integer", (int) $this->getOnline()), - "startpage" => array("text", $this->getStartPage()), - "short" => array("text", $this->getShortTitle()), - "rating" => array("integer", (int) $this->getRating()), - "public_notes" => array("integer", (int) $this->getPublicNotes()), - "introduction" => array("clob", $this->getIntroduction()), - "empty_page_templ" => array("integer", (int) $this->getEmptyPageTemplate()), - )); - - // create start page - if ($this->getStartPage() != "" && !$a_prevent_start_page_creation) - { - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $start_page = new ilWikiPage(); - $start_page->setWikiId($this->getId()); - $start_page->setTitle($this->getStartPage()); - $start_page->create(); - } - - if (((int) $this->getStyleSheetId()) > 0) - { - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - ilObjStyleSheet::writeStyleUsage($this->getId(), $this->getStyleSheetId()); - } - } - - /** - * update object data - * - * @access public - * @return boolean - */ - function update($a_prevent_start_page_creation = false) - { - $ilDB = $this->db; - - if (!parent::update()) - { - return false; - } - - $ilDB->update("il_wiki_data", array( - "is_online" => array("integer", $this->getOnline()), - "startpage" => array("text", $this->getStartPage()), - "short" => array("text", $this->getShortTitle()), - "rating_overall" => array("integer", $this->getRatingOverall()), - "rating" => array("integer", $this->getRating()), - "rating_side" => array("integer", (bool)$this->getRatingAsBlock()), // #13455 - "rating_new" => array("integer", $this->getRatingForNewPages()), - "rating_ext" => array("integer", $this->getRatingCategories()), - "public_notes" => array("integer", $this->getPublicNotes()), - "introduction" => array("clob", $this->getIntroduction()), - "imp_pages" => array("integer", $this->getImportantPages()), - "page_toc" => array("integer", $this->getPageToc()), - "link_md_values" => array("integer", $this->getLinkMetadataValues()), - "empty_page_templ" => array("integer", $this->getEmptyPageTemplate()) - ), array( - "id" => array("integer", $this->getId()) - )); - - // check whether start page exists - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - if (!ilWikiPage::exists($this->getId(), $this->getStartPage()) - && !$a_prevent_start_page_creation) - { - $start_page = new ilWikiPage(); - $start_page->setWikiId($this->getId()); - $start_page->setTitle($this->getStartPage()); - $start_page->create(); - } - - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - ilObjStyleSheet::writeStyleUsage($this->getId(), $this->getStyleSheetId()); - - return true; - } - - /** - * Read wiki data - */ - function read() - { - $ilDB = $this->db; - - parent::read(); - - $query = "SELECT * FROM il_wiki_data WHERE id = ". - $ilDB->quote($this->getId(), "integer"); - $set = $ilDB->query($query); - $rec = $ilDB->fetchAssoc($set); - - $this->setOnline($rec["is_online"]); - $this->setStartPage($rec["startpage"]); - $this->setShortTitle($rec["short"]); - $this->setRatingOverall($rec["rating_overall"]); - $this->setRating($rec["rating"]); - $this->setRatingAsBlock($rec["rating_side"]); - $this->setRatingForNewPages($rec["rating_new"]); - $this->setRatingCategories($rec["rating_ext"]); - $this->setPublicNotes($rec["public_notes"]); - $this->setIntroduction($rec["introduction"]); - $this->setImportantPages($rec["imp_pages"]); - $this->setPageToc($rec["page_toc"]); - $this->setEmptyPageTemplate($rec["empty_page_templ"]); - $this->setLinkMetadataValues($rec["link_md_values"]); - - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $this->setStyleSheetId((int) ilObjStyleSheet::lookupObjectStyle($this->getId())); - - } - - - /** - * delete object and all related data - * - * @access public - * @return boolean true if all object data were removed; false if only a references were removed - */ - function delete() - { - $ilDB = $this->db; - - // always call parent delete function first!! - if (!parent::delete()) - { - return false; - } - - // delete record of table il_wiki_data - $query = "DELETE FROM il_wiki_data". - " WHERE id = ".$ilDB->quote($this->getId(), "integer"); - $ilDB->manipulate($query); - - // remove all notifications - include_once "./Services/Notification/classes/class.ilNotification.php"; - ilNotification::removeForObject(ilNotification::TYPE_WIKI, $this->getId()); - - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - ilWikiPage::deleteAllPagesOfWiki($this->getId()); - - return true; - } - - /** - * Check availability of short title - */ - static function checkShortTitleAvailability($a_short_title) - { - global $DIC; - - $ilDB = $DIC->database(); - - $res = $ilDB->queryF("SELECT id FROM il_wiki_data WHERE short = %s", - array("text"), array($a_short_title)); - if ($ilDB->fetchAssoc($res)) - { - return false; - } - - return true; - } - - /** - * Lookup whether rating is activated for whole object. - * - * @param int $a_wiki_id Wiki ID - * - * @return boolean Rating activated? - */ - static function _lookupRatingOverall($a_wiki_id) - { - return ilObjWiki::_lookup($a_wiki_id, "rating_overall"); - } - - /** - * Lookup whether rating is activated. - * - * @param int $a_wiki_id Wiki ID - * - * @return boolean Rating activated? - */ - static function _lookupRating($a_wiki_id) - { - return ilObjWiki::_lookup($a_wiki_id, "rating"); - } - - /** - * Lookup whether rating categories are activated. - * - * @param int $a_wiki_id Wiki ID - * - * @return boolean Rating categories activated? - */ - static function _lookupRatingCategories($a_wiki_id) - { - return ilObjWiki::_lookup($a_wiki_id, "rating_ext"); - } - - /** - * Lookup whether rating side block is activated. - * - * @param int $a_wiki_id Wiki ID - * - * @return boolean Rating side block activated? - */ - static function _lookupRatingAsBlock($a_wiki_id) - { - return ilObjWiki::_lookup($a_wiki_id, "rating_side"); - } - - /** - * Lookup whether public notes are activated - * - * @param int $a_wiki_id Wiki ID - * - * @return boolean public notes activated? - */ - static function _lookupPublicNotes($a_wiki_id) - { - return ilObjWiki::_lookup($a_wiki_id, "public_notes"); - } - - /** - * Lookup whether metadata should be auto linked - * - * @param int $a_wiki_id Wiki ID - * - * @return boolean auto linking activated? - */ - static function _lookupLinkMetadataValues($a_wiki_id) - { - return ilObjWiki::_lookup($a_wiki_id, "link_md_values"); - } - - /** - * Lookup a data field - * - * @param int $a_wiki_id Wiki ID - * @param string $a_field Field Name - * - * @return mixed field value - */ - private static function _lookup($a_wiki_id, $a_field) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT $a_field FROM il_wiki_data WHERE id = ". - $ilDB->quote($a_wiki_id, "integer"); - $set = $ilDB->query($query); - $rec = $ilDB->fetchAssoc($set); - return $rec[$a_field]; - } - - /** - * Lookup start page - * - * @param int $a_wiki_id Wiki ID - * - * @return boolean - */ - static function _lookupStartPage($a_wiki_id) - { - return ilObjWiki::_lookup($a_wiki_id, "startpage"); - } - - /** - * Write start page - */ - static function writeStartPage($a_id, $a_name) - { - global $DIC; - - $ilDB = $DIC->database(); - - include_once("./Modules/Wiki/classes/class.ilWikiUtil.php"); - $ilDB->manipulate("UPDATE il_wiki_data SET ". - " startpage = ".$ilDB->quote(ilWikiUtil::makeDbTitle($a_name), "text"). - " WHERE id = ".$ilDB->quote($a_id, "integer") - ); - } - - /** - * Search in Wiki - */ - static function _performSearch($a_wiki_id, $a_searchterm) - { - // query parser - include_once 'Services/Search/classes/class.ilQueryParser.php'; - - $query_parser = new ilQueryParser($a_searchterm); - $query_parser->setCombination("or"); - $query_parser->parse(); - - include_once 'Services/Search/classes/class.ilSearchResult.php'; - $search_result = new ilSearchResult(); - if($query_parser->validate()) - { - - include_once 'Services/Search/classes/class.ilObjectSearchFactory.php'; - $wiki_search = ilObjectSearchFactory::_getWikiContentSearchInstance($query_parser); - $wiki_search->setFilter(array('wpg')); - $search_result->mergeEntries($wiki_search->performSearch()); - } - - $entries = $search_result->getEntries(); - - $found_pages = array(); - foreach($entries as $entry) - { - if ($entry["obj_id"] == $a_wiki_id && is_array($entry["child"])) - { - foreach($entry["child"] as $child) - { - $found_pages[] = array("page_id" => $child); - } - } - } - - return $found_pages; - } - - // - // Important pages - // - - /** - * Lookup whether important pages are activated. - * - * @param int $a_wiki_id Wiki ID - * - * @return boolean Important pages activated? - */ - static function _lookupImportantPages($a_wiki_id) - { - return ilObjWiki::_lookup($a_wiki_id, "imp_pages"); - } - - /** - * Get important pages list - * - * @param - * @return - */ - static function _lookupImportantPagesList($a_wiki_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT * FROM il_wiki_imp_pages WHERE ". - " wiki_id = ".$ilDB->quote($a_wiki_id, "integer")." ORDER BY ord ASC " - ); - - $imp_pages = array(); - - while ($rec = $ilDB->fetchAssoc($set)) - { - $imp_pages[] = $rec; - } - return $imp_pages; - } - - /** - * Get important pages list - * - * @param - * @return - */ - static function _lookupMaxOrdNrImportantPages($a_wiki_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT MAX(ord) as m FROM il_wiki_imp_pages WHERE ". - " wiki_id = ".$ilDB->quote($a_wiki_id, "integer") - ); - - $rec = $ilDB->fetchAssoc($set); - return (int) $rec["m"]; - } - - - /** - * Add important page - * - * @param int page id - */ - function addImportantPage($a_page_id, $a_nr = 0, $a_indent = 0) - { - $ilDB = $this->db; - - if (!$this->isImportantPage($a_page_id)) - { - if ($a_nr == 0) - { - $a_nr = ilObjWiki::_lookupMaxOrdNrImportantPages($this->getId()) + 10; - } - - $ilDB->manipulate("INSERT INTO il_wiki_imp_pages ". - "(wiki_id, ord, indent, page_id) VALUES (". - $ilDB->quote($this->getId(), "integer").",". - $ilDB->quote($a_nr, "integer").",". - $ilDB->quote($a_indent, "integer").",". - $ilDB->quote($a_page_id, "integer"). - ")"); - } - } - - /** - * Is page an important page? - * - * @param - * @return - */ - function isImportantPage($a_page_id) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT * FROM il_wiki_imp_pages WHERE ". - " wiki_id = ".$ilDB->quote($this->getId(), "integer")." AND ". - " page_id = ".$ilDB->quote($a_page_id, "integer") - ); - if ($rec = $ilDB->fetchAssoc($set)) - { - return true; - } - return false; - } - - /** - * Remove important page - * - * @param int page id - */ - function removeImportantPage($a_id) - { - $ilDB = $this->db; - - $ilDB->manipulate("DELETE FROM il_wiki_imp_pages WHERE " - ." wiki_id = ".$ilDB->quote($this->getId(), "integer") - ." AND page_id = ".$ilDB->quote($a_id, "integer") - ); - - $this->fixImportantPagesNumbering(); - } - - /** - * Save ordering and indentation - * - * @param - * @return - */ - function saveOrderingAndIndentation($a_ord, $a_indent) - { - $ilDB = $this->db; - - $ipages = ilObjWiki::_lookupImportantPagesList($this->getId()); - - foreach ($ipages as $k => $v) - { - if (isset($a_ord[$v["page_id"]])) - { - $ipages[$k]["ord"] = (int) $a_ord[$v["page_id"]]; - } - if (isset($a_indent[$v["page_id"]])) - { - $ipages[$k]["indent"] = (int) $a_indent[$v["page_id"]]; - } - } - $ipages = ilUtil::sortArray($ipages, "ord", "asc", true); - - // fix indentation: no 2 is allowed after a 0 - $c_indent = 0; - $fixed = false; - foreach ($ipages as $k => $v) - { - if ($ipages[$k]["indent"] == 2 && $c_indent == 0) - { - $ipages[$k]["indent"] = 1; - $fixed = true; - } - $c_indent = $ipages[$k]["indent"]; - } - - $ord = 10; - reset($ipages); - foreach ($ipages as $k => $v) - { - $ilDB->manipulate($q = "UPDATE il_wiki_imp_pages SET ". - " ord = ".$ilDB->quote($ord, "integer").",". - " indent = ".$ilDB->quote($v["indent"], "integer"). - " WHERE wiki_id = ".$ilDB->quote($v["wiki_id"], "integer"). - " AND page_id = ".$ilDB->quote($v["page_id"], "integer") - ); - $ord+=10; - } - - return $fixed; - } - - /** - * Fix important pages numbering - */ - function fixImportantPagesNumbering() - { - $ilDB = $this->db; - - $ipages = ilObjWiki::_lookupImportantPagesList($this->getId()); - - // fix indentation: no 2 is allowed after a 0 - $c_indent = 0; - $fixed = false; - foreach ($ipages as $k => $v) - { - if ($ipages[$k]["indent"] == 2 && $c_indent == 0) - { - $ipages[$k]["indent"] = 1; - $fixed = true; - } - $c_indent = $ipages[$k]["indent"]; - } - - $ord = 10; - foreach ($ipages as $k => $v) - { - $ilDB->manipulate($q = "UPDATE il_wiki_imp_pages SET ". - " ord = ".$ilDB->quote($ord, "integer"). - ", indent = ".$ilDB->quote($v["indent"], "integer"). - " WHERE wiki_id = ".$ilDB->quote($v["wiki_id"], "integer"). - " AND page_id = ".$ilDB->quote($v["page_id"], "integer") - ); - $ord+=10; - } - - } - - // - // Page TOC - // - - /** - * Lookup whether important pages are activated. - * - * @param int $a_wiki_id Wiki ID - * - * @return boolean Important pages activated? - */ - static function _lookupPageToc($a_wiki_id) - { - return ilObjWiki::_lookup($a_wiki_id, "page_toc"); - } - - /** - * Clone wiki - * - * @param int target ref_id - * @param int copy id - */ - public function cloneObject($a_target_id,$a_copy_id = 0, $a_omit_tree = false) - { - $new_obj = parent::cloneObject($a_target_id,$a_copy_id, $a_omit_tree); - - //copy online status if object is not the root copy object - $cp_options = ilCopyWizardOptions::_getInstance($a_copy_id); - - if(!$cp_options->isRootNode($this->getRefId())) - { - $new_obj->setOnline($this->getOnline()); - } - - //$new_obj->setTitle($this->getTitle()); // see #20074 - $new_obj->setStartPage($this->getStartPage()); - $new_obj->setShortTitle($this->getShortTitle()); - $new_obj->setRatingOverall($this->getRatingOverall()); - $new_obj->setRating($this->getRating()); - $new_obj->setRatingAsBlock($this->getRatingAsBlock()); - $new_obj->setRatingForNewPages($this->getRatingForNewPages()); - $new_obj->setRatingCategories($this->getRatingCategories()); - $new_obj->setPublicNotes($this->getPublicNotes()); - $new_obj->setIntroduction($this->getIntroduction()); - $new_obj->setImportantPages($this->getImportantPages()); - $new_obj->setPageToc($this->getPageToc()); - $new_obj->update(); - - // set/copy stylesheet - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $style_id = $this->getStyleSheetId(); - if ($style_id > 0 && !ilObjStyleSheet::_lookupStandard($style_id)) - { - $style_obj = ilObjectFactory::getInstanceByObjId($style_id); - $new_id = $style_obj->ilClone(); - $new_obj->setStyleSheetId($new_id); - $new_obj->update(); - } - - // copy content - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $pages = ilWikiPage::getAllWikiPages($this->getId()); - if (count($pages) > 0) - { - // if we have any pages, delete the start page first - $pg_id = ilWikiPage::getPageIdForTitle($new_obj->getId(), $new_obj->getStartPage()); - $start_page = new ilWikiPage($pg_id); - $start_page->delete(); - } - $map = array(); - foreach ($pages as $p) - { - $page = new ilWikiPage($p["id"]); - $new_page = new ilWikiPage(); - $new_page->setTitle($page->getTitle()); - $new_page->setWikiId($new_obj->getId()); - $new_page->setTitle($page->getTitle()); - $new_page->setBlocked($page->getBlocked()); - $new_page->setRating($page->getRating()); - $new_page->hideAdvancedMetadata($page->isAdvancedMetadataHidden()); - $new_page->create(); - - $page->copy($new_page->getId(), "", 0, true); - //$new_page->setXMLContent($page->copyXMLContent(true)); - //$new_page->buildDom(true); - //$new_page->update(); - $map[$p["id"]] = $new_page->getId(); - } - - // copy important pages - foreach (ilObjWiki::_lookupImportantPagesList($this->getId()) as $ip) - { - $new_obj->addImportantPage($map[$ip["page_id"]], $ip["ord"], $ip["indent"]); - } - - // copy rating categories - include_once("./Services/Rating/classes/class.ilRatingCategory.php"); - foreach (ilRatingCategory::getAllForObject($this->getId()) as $rc) - { - $new_rc = new ilRatingCategory(); - $new_rc->setParentId($new_obj->getId()); - $new_rc->setTitle($rc["title"]); - $new_rc->setDescription($rc["description"]); - $new_rc->save(); - } - - return $new_obj; - } - - /** - * Get template selection on creation? If more than one template (including empty page template) - * is activated -> return true - * - * @return boolean true, if manual template selection needed - */ - function getTemplateSelectionOnCreation() - { - $num = (int) $this->getEmptyPageTemplate(); - include_once("./Modules/Wiki/classes/class.ilWikiPageTemplate.php"); - $wt = new ilWikiPageTemplate($this->getId()); - $ts = $wt->getAllInfo(ilWikiPageTemplate::TYPE_NEW_PAGES); - $num += count($ts); - if ($num > 1) - { - return true; - } - return false; - } - - /** - * Create new wiki page - * - * @param string $a_page_title page title - * @param int $a_template_page template page id - * @return ilWikiPage new wiki page - */ - function createWikiPage($a_page_title, $a_template_page = 0) - { - // check if template has to be used - if ($a_template_page == 0) - { - if (!$this->getEmptyPageTemplate()) - { - include_once("./Modules/Wiki/classes/class.ilWikiPageTemplate.php"); - $wt = new ilWikiPageTemplate($this->getId()); - $ts = $wt->getAllInfo(ilWikiPageTemplate::TYPE_NEW_PAGES); - if (count($ts) == 1) - { - $t = current($ts); - $a_template_page = $t["wpage_id"]; - } - } - } - - // create the page - $page = new ilWikiPage(); - $page->setWikiId($this->getId()); - $page->setTitle(ilWikiUtil::makeDbTitle($a_page_title)); - if($this->getRating() && $this->getRatingForNewPages()) - { - $page->setRating(true); - } - - // needed for notification - $page->setWikiRefId($this->getRefId()); - $page->create(); - - // copy template into new page - if ($a_template_page > 0) - { - $orig = new ilWikiPage($a_template_page); - $orig->copy($page->getId()); - - // #15718 - include_once "Services/AdvancedMetaData/classes/class.ilAdvancedMDValues.php"; - ilAdvancedMDValues::_cloneValues( - $this->getId(), - $this->getId(), - "wpg", - $a_template_page, - $page->getId() - ); - } - - return $page; - } - - public static function getAdvMDSubItemTitle($a_obj_id, $a_sub_type, $a_sub_id) - { - global $DIC; - - $lng = $DIC->language(); - - if($a_sub_type == "wpg") - { - $lng->loadLanguageModule("wiki"); - include_once "./Modules/Wiki/classes/class.ilWikiPage.php"; - return $lng->txt("wiki_wpg").' "'.ilWikiPage::lookupTitle($a_sub_id).'"'; - } - } - - /** - * Init user html export - * - * @param - * @return - */ - function initUserHTMLExport() - { - $ilDB = $this->db; - $ilUser = $this->user; - - include_once("./Modules/Wiki/classes/class.ilWikiUserHTMLExport.php"); - - $user_export = new ilWikiUserHTMLExport($this, $ilDB, $ilUser); - $user_export->initUserHTMLExport(); - } - - /** - * Start user html export - * - * @param - * @return - */ - function startUserHTMLExport() - { - $ilDB = $this->db; - $ilUser = $this->user; - - include_once("./Modules/Wiki/classes/class.ilWikiUserHTMLExport.php"); - - $user_export = new ilWikiUserHTMLExport($this, $ilDB, $ilUser); - $user_export->startUserHTMLExport(); - } - - /** - * Get user html export progress - * - * @return array progress info - */ - function getUserHTMLExportProgress() - { - $ilDB = $this->db; - $ilUser = $this->user; - - include_once("./Modules/Wiki/classes/class.ilWikiUserHTMLExport.php"); - - $user_export = new ilWikiUserHTMLExport($this, $ilDB, $ilUser); - return $user_export->getProgress(); - } - - /** - * Send user html export file - */ - function deliverUserHTMLExport() - { - $ilDB = $this->db; - $ilUser = $this->user; - - include_once("./Modules/Wiki/classes/class.ilWikiUserHTMLExport.php"); - - $user_export = new ilWikiUserHTMLExport($this, $ilDB, $ilUser); - return $user_export->deliverFile(); - } - - - /** - * Decorate adv md value - * - * @param string $a_value value - * @return string decorated value (includes HTML) - */ - public function decorateAdvMDValue($a_value) - { - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - if (ilWikiPage::_wikiPageExists($this->getId(), $a_value)) - { - $url = ilObjWikiGUI::getGotoLink($this->getRefId(), $a_value); - return "".$a_value.""; - } - - return $a_value; - } - - - + /** + * @var ilObjUser + */ + protected $user; + + protected $online = false; + protected $public_notes = true; + protected $empty_page_templ = true; + protected $link_md_values = false; + + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + global $DIC; + + $this->db = $DIC->database(); + $this->user = $DIC->user(); + $this->type = "wiki"; + parent::__construct($a_id, $a_call_by_reference); + } + + /** + * Set Online. + * + * @param boolean $a_online Online + */ + public function setOnline($a_online) + { + $this->online = $a_online; + } + + /** + * Get Online. + * + * @return boolean Online + */ + public function getOnline() + { + return $this->online; + } + + /** + * Set Enable Rating For Object. + * + * @param boolean $a_rating Enable Rating + */ + public function setRatingOverall($a_rating) + { + $this->rating_overall = (bool) $a_rating; + } + + /** + * Get Enable Rating For Object. + * + * @return boolean Enable Rating + */ + public function getRatingOverall() + { + return $this->rating_overall; + } + + /** + * Set Enable Rating. + * + * @param boolean $a_rating Enable Rating + */ + public function setRating($a_rating) + { + $this->rating = (bool) $a_rating; + } + + /** + * Get Enable Rating. + * + * @return boolean Enable Rating + */ + public function getRating() + { + return $this->rating; + } + + /** + * Set Enable Rating Side Block. + * + * @param boolean $a_rating + */ + public function setRatingAsBlock($a_rating) + { + $this->rating_block = (bool) $a_rating; + } + + /** + * Get Enable Rating Side Block. + * + * @return boolean + */ + public function getRatingAsBlock() + { + return $this->rating_block; + } + + /** + * Set Enable Rating For New Pages. + * + * @param boolean $a_rating + */ + public function setRatingForNewPages($a_rating) + { + $this->rating_new_pages = (bool) $a_rating; + } + + /** + * Get Enable Rating For New Pages. + * + * @return boolean + */ + public function getRatingForNewPages() + { + return $this->rating_new_pages; + } + + /** + * Set Enable Rating Categories. + * + * @param boolean $a_rating + */ + public function setRatingCategories($a_rating) + { + $this->rating_categories = (bool) $a_rating; + } + + /** + * Get Enable Rating Categories. + * + * @return boolean + */ + public function getRatingCategories() + { + return $this->rating_categories; + } + + /** + * Set public notes + */ + public function setPublicNotes($a_val) + { + $this->public_notes = $a_val; + } + + /** + * Get public notes + */ + public function getPublicNotes() + { + return $this->public_notes; + } + + /** + * Set important pages + * + * @param boolean $a_val important pages + */ + public function setImportantPages($a_val) + { + $this->imp_pages = $a_val; + } + + /** + * Get important pages + * + * @return boolean important pages + */ + public function getImportantPages() + { + return $this->imp_pages; + } + + /** + * Set Start Page. + * + * @param string $a_startpage Start Page + */ + public function setStartPage($a_startpage) + { + $this->startpage = ilWikiUtil::makeDbTitle($a_startpage); + } + + /** + * Get Start Page. + * + * @return string Start Page + */ + public function getStartPage() + { + return $this->startpage; + } + + /** + * Set ShortTitle. + * + * @param string $a_shorttitle ShortTitle + */ + public function setShortTitle($a_shorttitle) + { + $this->shorttitle = $a_shorttitle; + } + + /** + * Get ShortTitle. + * + * @return string ShortTitle + */ + public function getShortTitle() + { + return $this->shorttitle; + } + + /** + * Set Introduction. + * + * @param string $a_introduction Introduction + */ + public function setIntroduction($a_introduction) + { + $this->introduction = $a_introduction; + } + + /** + * Get Introduction. + * + * @return string Introduction + */ + public function getIntroduction() + { + return $this->introduction; + } + + /** + * get ID of assigned style sheet object + */ + public function getStyleSheetId() + { + return $this->style_id; + } + + /** + * set ID of assigned style sheet object + */ + public function setStyleSheetId($a_style_id) + { + $this->style_id = $a_style_id; + } + + /** + * Set page toc + * + * @param boolean $a_val page toc + */ + public function setPageToc($a_val) + { + $this->page_toc = $a_val; + } + + /** + * Get page toc + * + * @return boolean page toc + */ + public function getPageToc() + { + return $this->page_toc; + } + + /** + * Set empty page template + * + * @param boolean $a_val empty page template + */ + public function setEmptyPageTemplate($a_val) + { + $this->empty_page_templ = $a_val; + } + + /** + * Get empty page template + * + * @return boolean empty page template + */ + public function getEmptyPageTemplate() + { + return $this->empty_page_templ; + } + + /** + * Set link md values + * + * @param bool $a_val link metadata values + */ + public function setLinkMetadataValues($a_val) + { + $this->link_md_values = $a_val; + } + + /** + * Get link md values + * + * @return bool link metadata values + */ + public function getLinkMetadataValues() + { + return $this->link_md_values; + } + + /** + * Is wiki an online help wiki? + * + * @return boolean true, if current wiki is an online help wiki + */ + public static function isOnlineHelpWiki($a_ref_id) + { + if ($a_ref_id > 0 && $a_ref_id == OH_REF_ID) { + // return true; + } + return false; + } + + /** + * Create new wiki + */ + public function create($a_prevent_start_page_creation = false) + { + $ilDB = $this->db; + + parent::create(); + + $ilDB->insert("il_wiki_data", array( + "id" => array("integer", $this->getId()), + "is_online" => array("integer", (int) $this->getOnline()), + "startpage" => array("text", $this->getStartPage()), + "short" => array("text", $this->getShortTitle()), + "rating" => array("integer", (int) $this->getRating()), + "public_notes" => array("integer", (int) $this->getPublicNotes()), + "introduction" => array("clob", $this->getIntroduction()), + "empty_page_templ" => array("integer", (int) $this->getEmptyPageTemplate()), + )); + + // create start page + if ($this->getStartPage() != "" && !$a_prevent_start_page_creation) { + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + $start_page = new ilWikiPage(); + $start_page->setWikiId($this->getId()); + $start_page->setTitle($this->getStartPage()); + $start_page->create(); + } + + if (((int) $this->getStyleSheetId()) > 0) { + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + ilObjStyleSheet::writeStyleUsage($this->getId(), $this->getStyleSheetId()); + } + } + + /** + * update object data + * + * @access public + * @return boolean + */ + public function update($a_prevent_start_page_creation = false) + { + $ilDB = $this->db; + + if (!parent::update()) { + return false; + } + + $ilDB->update("il_wiki_data", array( + "is_online" => array("integer", $this->getOnline()), + "startpage" => array("text", $this->getStartPage()), + "short" => array("text", $this->getShortTitle()), + "rating_overall" => array("integer", $this->getRatingOverall()), + "rating" => array("integer", $this->getRating()), + "rating_side" => array("integer", (bool) $this->getRatingAsBlock()), // #13455 + "rating_new" => array("integer", $this->getRatingForNewPages()), + "rating_ext" => array("integer", $this->getRatingCategories()), + "public_notes" => array("integer", $this->getPublicNotes()), + "introduction" => array("clob", $this->getIntroduction()), + "imp_pages" => array("integer", $this->getImportantPages()), + "page_toc" => array("integer", $this->getPageToc()), + "link_md_values" => array("integer", $this->getLinkMetadataValues()), + "empty_page_templ" => array("integer", $this->getEmptyPageTemplate()) + ), array( + "id" => array("integer", $this->getId()) + )); + + // check whether start page exists + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + if (!ilWikiPage::exists($this->getId(), $this->getStartPage()) + && !$a_prevent_start_page_creation) { + $start_page = new ilWikiPage(); + $start_page->setWikiId($this->getId()); + $start_page->setTitle($this->getStartPage()); + $start_page->create(); + } + + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + ilObjStyleSheet::writeStyleUsage($this->getId(), $this->getStyleSheetId()); + + return true; + } + + /** + * Read wiki data + */ + public function read() + { + $ilDB = $this->db; + + parent::read(); + + $query = "SELECT * FROM il_wiki_data WHERE id = " . + $ilDB->quote($this->getId(), "integer"); + $set = $ilDB->query($query); + $rec = $ilDB->fetchAssoc($set); + + $this->setOnline($rec["is_online"]); + $this->setStartPage($rec["startpage"]); + $this->setShortTitle($rec["short"]); + $this->setRatingOverall($rec["rating_overall"]); + $this->setRating($rec["rating"]); + $this->setRatingAsBlock($rec["rating_side"]); + $this->setRatingForNewPages($rec["rating_new"]); + $this->setRatingCategories($rec["rating_ext"]); + $this->setPublicNotes($rec["public_notes"]); + $this->setIntroduction($rec["introduction"]); + $this->setImportantPages($rec["imp_pages"]); + $this->setPageToc($rec["page_toc"]); + $this->setEmptyPageTemplate($rec["empty_page_templ"]); + $this->setLinkMetadataValues($rec["link_md_values"]); + + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $this->setStyleSheetId((int) ilObjStyleSheet::lookupObjectStyle($this->getId())); + } + + + /** + * delete object and all related data + * + * @access public + * @return boolean true if all object data were removed; false if only a references were removed + */ + public function delete() + { + $ilDB = $this->db; + + // always call parent delete function first!! + if (!parent::delete()) { + return false; + } + + // delete record of table il_wiki_data + $query = "DELETE FROM il_wiki_data" . + " WHERE id = " . $ilDB->quote($this->getId(), "integer"); + $ilDB->manipulate($query); + + // remove all notifications + include_once "./Services/Notification/classes/class.ilNotification.php"; + ilNotification::removeForObject(ilNotification::TYPE_WIKI, $this->getId()); + + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + ilWikiPage::deleteAllPagesOfWiki($this->getId()); + + return true; + } + + /** + * Check availability of short title + */ + public static function checkShortTitleAvailability($a_short_title) + { + global $DIC; + + $ilDB = $DIC->database(); + + $res = $ilDB->queryF( + "SELECT id FROM il_wiki_data WHERE short = %s", + array("text"), + array($a_short_title) + ); + if ($ilDB->fetchAssoc($res)) { + return false; + } + + return true; + } + + /** + * Lookup whether rating is activated for whole object. + * + * @param int $a_wiki_id Wiki ID + * + * @return boolean Rating activated? + */ + public static function _lookupRatingOverall($a_wiki_id) + { + return ilObjWiki::_lookup($a_wiki_id, "rating_overall"); + } + + /** + * Lookup whether rating is activated. + * + * @param int $a_wiki_id Wiki ID + * + * @return boolean Rating activated? + */ + public static function _lookupRating($a_wiki_id) + { + return ilObjWiki::_lookup($a_wiki_id, "rating"); + } + + /** + * Lookup whether rating categories are activated. + * + * @param int $a_wiki_id Wiki ID + * + * @return boolean Rating categories activated? + */ + public static function _lookupRatingCategories($a_wiki_id) + { + return ilObjWiki::_lookup($a_wiki_id, "rating_ext"); + } + + /** + * Lookup whether rating side block is activated. + * + * @param int $a_wiki_id Wiki ID + * + * @return boolean Rating side block activated? + */ + public static function _lookupRatingAsBlock($a_wiki_id) + { + return ilObjWiki::_lookup($a_wiki_id, "rating_side"); + } + + /** + * Lookup whether public notes are activated + * + * @param int $a_wiki_id Wiki ID + * + * @return boolean public notes activated? + */ + public static function _lookupPublicNotes($a_wiki_id) + { + return ilObjWiki::_lookup($a_wiki_id, "public_notes"); + } + + /** + * Lookup whether metadata should be auto linked + * + * @param int $a_wiki_id Wiki ID + * + * @return boolean auto linking activated? + */ + public static function _lookupLinkMetadataValues($a_wiki_id) + { + return ilObjWiki::_lookup($a_wiki_id, "link_md_values"); + } + + /** + * Lookup a data field + * + * @param int $a_wiki_id Wiki ID + * @param string $a_field Field Name + * + * @return mixed field value + */ + private static function _lookup($a_wiki_id, $a_field) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT $a_field FROM il_wiki_data WHERE id = " . + $ilDB->quote($a_wiki_id, "integer"); + $set = $ilDB->query($query); + $rec = $ilDB->fetchAssoc($set); + return $rec[$a_field]; + } + + /** + * Lookup start page + * + * @param int $a_wiki_id Wiki ID + * + * @return boolean + */ + public static function _lookupStartPage($a_wiki_id) + { + return ilObjWiki::_lookup($a_wiki_id, "startpage"); + } + + /** + * Write start page + */ + public static function writeStartPage($a_id, $a_name) + { + global $DIC; + + $ilDB = $DIC->database(); + + include_once("./Modules/Wiki/classes/class.ilWikiUtil.php"); + $ilDB->manipulate( + "UPDATE il_wiki_data SET " . + " startpage = " . $ilDB->quote(ilWikiUtil::makeDbTitle($a_name), "text") . + " WHERE id = " . $ilDB->quote($a_id, "integer") + ); + } + + /** + * Search in Wiki + */ + public static function _performSearch($a_wiki_id, $a_searchterm) + { + // query parser + include_once 'Services/Search/classes/class.ilQueryParser.php'; + + $query_parser = new ilQueryParser($a_searchterm); + $query_parser->setCombination("or"); + $query_parser->parse(); + + include_once 'Services/Search/classes/class.ilSearchResult.php'; + $search_result = new ilSearchResult(); + if ($query_parser->validate()) { + include_once 'Services/Search/classes/class.ilObjectSearchFactory.php'; + $wiki_search = ilObjectSearchFactory::_getWikiContentSearchInstance($query_parser); + $wiki_search->setFilter(array('wpg')); + $search_result->mergeEntries($wiki_search->performSearch()); + } + + $entries = $search_result->getEntries(); + + $found_pages = array(); + foreach ($entries as $entry) { + if ($entry["obj_id"] == $a_wiki_id && is_array($entry["child"])) { + foreach ($entry["child"] as $child) { + $found_pages[] = array("page_id" => $child); + } + } + } + + return $found_pages; + } + + // + // Important pages + // + + /** + * Lookup whether important pages are activated. + * + * @param int $a_wiki_id Wiki ID + * + * @return boolean Important pages activated? + */ + public static function _lookupImportantPages($a_wiki_id) + { + return ilObjWiki::_lookup($a_wiki_id, "imp_pages"); + } + + /** + * Get important pages list + * + * @param + * @return + */ + public static function _lookupImportantPagesList($a_wiki_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT * FROM il_wiki_imp_pages WHERE " . + " wiki_id = " . $ilDB->quote($a_wiki_id, "integer") . " ORDER BY ord ASC " + ); + + $imp_pages = array(); + + while ($rec = $ilDB->fetchAssoc($set)) { + $imp_pages[] = $rec; + } + return $imp_pages; + } + + /** + * Get important pages list + * + * @param + * @return + */ + public static function _lookupMaxOrdNrImportantPages($a_wiki_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT MAX(ord) as m FROM il_wiki_imp_pages WHERE " . + " wiki_id = " . $ilDB->quote($a_wiki_id, "integer") + ); + + $rec = $ilDB->fetchAssoc($set); + return (int) $rec["m"]; + } + + + /** + * Add important page + * + * @param int page id + */ + public function addImportantPage($a_page_id, $a_nr = 0, $a_indent = 0) + { + $ilDB = $this->db; + + if (!$this->isImportantPage($a_page_id)) { + if ($a_nr == 0) { + $a_nr = ilObjWiki::_lookupMaxOrdNrImportantPages($this->getId()) + 10; + } + + $ilDB->manipulate("INSERT INTO il_wiki_imp_pages " . + "(wiki_id, ord, indent, page_id) VALUES (" . + $ilDB->quote($this->getId(), "integer") . "," . + $ilDB->quote($a_nr, "integer") . "," . + $ilDB->quote($a_indent, "integer") . "," . + $ilDB->quote($a_page_id, "integer") . + ")"); + } + } + + /** + * Is page an important page? + * + * @param + * @return + */ + public function isImportantPage($a_page_id) + { + $ilDB = $this->db; + + $set = $ilDB->query( + "SELECT * FROM il_wiki_imp_pages WHERE " . + " wiki_id = " . $ilDB->quote($this->getId(), "integer") . " AND " . + " page_id = " . $ilDB->quote($a_page_id, "integer") + ); + if ($rec = $ilDB->fetchAssoc($set)) { + return true; + } + return false; + } + + /** + * Remove important page + * + * @param int page id + */ + public function removeImportantPage($a_id) + { + $ilDB = $this->db; + + $ilDB->manipulate( + "DELETE FROM il_wiki_imp_pages WHERE " + . " wiki_id = " . $ilDB->quote($this->getId(), "integer") + . " AND page_id = " . $ilDB->quote($a_id, "integer") + ); + + $this->fixImportantPagesNumbering(); + } + + /** + * Save ordering and indentation + * + * @param + * @return + */ + public function saveOrderingAndIndentation($a_ord, $a_indent) + { + $ilDB = $this->db; + + $ipages = ilObjWiki::_lookupImportantPagesList($this->getId()); + + foreach ($ipages as $k => $v) { + if (isset($a_ord[$v["page_id"]])) { + $ipages[$k]["ord"] = (int) $a_ord[$v["page_id"]]; + } + if (isset($a_indent[$v["page_id"]])) { + $ipages[$k]["indent"] = (int) $a_indent[$v["page_id"]]; + } + } + $ipages = ilUtil::sortArray($ipages, "ord", "asc", true); + + // fix indentation: no 2 is allowed after a 0 + $c_indent = 0; + $fixed = false; + foreach ($ipages as $k => $v) { + if ($ipages[$k]["indent"] == 2 && $c_indent == 0) { + $ipages[$k]["indent"] = 1; + $fixed = true; + } + $c_indent = $ipages[$k]["indent"]; + } + + $ord = 10; + reset($ipages); + foreach ($ipages as $k => $v) { + $ilDB->manipulate( + $q = "UPDATE il_wiki_imp_pages SET " . + " ord = " . $ilDB->quote($ord, "integer") . "," . + " indent = " . $ilDB->quote($v["indent"], "integer") . + " WHERE wiki_id = " . $ilDB->quote($v["wiki_id"], "integer") . + " AND page_id = " . $ilDB->quote($v["page_id"], "integer") + ); + $ord+=10; + } + + return $fixed; + } + + /** + * Fix important pages numbering + */ + public function fixImportantPagesNumbering() + { + $ilDB = $this->db; + + $ipages = ilObjWiki::_lookupImportantPagesList($this->getId()); + + // fix indentation: no 2 is allowed after a 0 + $c_indent = 0; + $fixed = false; + foreach ($ipages as $k => $v) { + if ($ipages[$k]["indent"] == 2 && $c_indent == 0) { + $ipages[$k]["indent"] = 1; + $fixed = true; + } + $c_indent = $ipages[$k]["indent"]; + } + + $ord = 10; + foreach ($ipages as $k => $v) { + $ilDB->manipulate( + $q = "UPDATE il_wiki_imp_pages SET " . + " ord = " . $ilDB->quote($ord, "integer") . + ", indent = " . $ilDB->quote($v["indent"], "integer") . + " WHERE wiki_id = " . $ilDB->quote($v["wiki_id"], "integer") . + " AND page_id = " . $ilDB->quote($v["page_id"], "integer") + ); + $ord+=10; + } + } + + // + // Page TOC + // + + /** + * Lookup whether important pages are activated. + * + * @param int $a_wiki_id Wiki ID + * + * @return boolean Important pages activated? + */ + public static function _lookupPageToc($a_wiki_id) + { + return ilObjWiki::_lookup($a_wiki_id, "page_toc"); + } + + /** + * Clone wiki + * + * @param int target ref_id + * @param int copy id + */ + public function cloneObject($a_target_id, $a_copy_id = 0, $a_omit_tree = false) + { + $new_obj = parent::cloneObject($a_target_id, $a_copy_id, $a_omit_tree); + + //copy online status if object is not the root copy object + $cp_options = ilCopyWizardOptions::_getInstance($a_copy_id); + + if (!$cp_options->isRootNode($this->getRefId())) { + $new_obj->setOnline($this->getOnline()); + } + + //$new_obj->setTitle($this->getTitle()); // see #20074 + $new_obj->setStartPage($this->getStartPage()); + $new_obj->setShortTitle($this->getShortTitle()); + $new_obj->setRatingOverall($this->getRatingOverall()); + $new_obj->setRating($this->getRating()); + $new_obj->setRatingAsBlock($this->getRatingAsBlock()); + $new_obj->setRatingForNewPages($this->getRatingForNewPages()); + $new_obj->setRatingCategories($this->getRatingCategories()); + $new_obj->setPublicNotes($this->getPublicNotes()); + $new_obj->setIntroduction($this->getIntroduction()); + $new_obj->setImportantPages($this->getImportantPages()); + $new_obj->setPageToc($this->getPageToc()); + $new_obj->update(); + + // set/copy stylesheet + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $style_id = $this->getStyleSheetId(); + if ($style_id > 0 && !ilObjStyleSheet::_lookupStandard($style_id)) { + $style_obj = ilObjectFactory::getInstanceByObjId($style_id); + $new_id = $style_obj->ilClone(); + $new_obj->setStyleSheetId($new_id); + $new_obj->update(); + } + + // copy content + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + $pages = ilWikiPage::getAllWikiPages($this->getId()); + if (count($pages) > 0) { + // if we have any pages, delete the start page first + $pg_id = ilWikiPage::getPageIdForTitle($new_obj->getId(), $new_obj->getStartPage()); + $start_page = new ilWikiPage($pg_id); + $start_page->delete(); + } + $map = array(); + foreach ($pages as $p) { + $page = new ilWikiPage($p["id"]); + $new_page = new ilWikiPage(); + $new_page->setTitle($page->getTitle()); + $new_page->setWikiId($new_obj->getId()); + $new_page->setTitle($page->getTitle()); + $new_page->setBlocked($page->getBlocked()); + $new_page->setRating($page->getRating()); + $new_page->hideAdvancedMetadata($page->isAdvancedMetadataHidden()); + $new_page->create(); + + $page->copy($new_page->getId(), "", 0, true); + //$new_page->setXMLContent($page->copyXMLContent(true)); + //$new_page->buildDom(true); + //$new_page->update(); + $map[$p["id"]] = $new_page->getId(); + } + + // copy important pages + foreach (ilObjWiki::_lookupImportantPagesList($this->getId()) as $ip) { + $new_obj->addImportantPage($map[$ip["page_id"]], $ip["ord"], $ip["indent"]); + } + + // copy rating categories + include_once("./Services/Rating/classes/class.ilRatingCategory.php"); + foreach (ilRatingCategory::getAllForObject($this->getId()) as $rc) { + $new_rc = new ilRatingCategory(); + $new_rc->setParentId($new_obj->getId()); + $new_rc->setTitle($rc["title"]); + $new_rc->setDescription($rc["description"]); + $new_rc->save(); + } + + return $new_obj; + } + + /** + * Get template selection on creation? If more than one template (including empty page template) + * is activated -> return true + * + * @return boolean true, if manual template selection needed + */ + public function getTemplateSelectionOnCreation() + { + $num = (int) $this->getEmptyPageTemplate(); + include_once("./Modules/Wiki/classes/class.ilWikiPageTemplate.php"); + $wt = new ilWikiPageTemplate($this->getId()); + $ts = $wt->getAllInfo(ilWikiPageTemplate::TYPE_NEW_PAGES); + $num += count($ts); + if ($num > 1) { + return true; + } + return false; + } + + /** + * Create new wiki page + * + * @param string $a_page_title page title + * @param int $a_template_page template page id + * @return ilWikiPage new wiki page + */ + public function createWikiPage($a_page_title, $a_template_page = 0) + { + // check if template has to be used + if ($a_template_page == 0) { + if (!$this->getEmptyPageTemplate()) { + include_once("./Modules/Wiki/classes/class.ilWikiPageTemplate.php"); + $wt = new ilWikiPageTemplate($this->getId()); + $ts = $wt->getAllInfo(ilWikiPageTemplate::TYPE_NEW_PAGES); + if (count($ts) == 1) { + $t = current($ts); + $a_template_page = $t["wpage_id"]; + } + } + } + + // create the page + $page = new ilWikiPage(); + $page->setWikiId($this->getId()); + $page->setTitle(ilWikiUtil::makeDbTitle($a_page_title)); + if ($this->getRating() && $this->getRatingForNewPages()) { + $page->setRating(true); + } + + // needed for notification + $page->setWikiRefId($this->getRefId()); + $page->create(); + + // copy template into new page + if ($a_template_page > 0) { + $orig = new ilWikiPage($a_template_page); + $orig->copy($page->getId()); + + // #15718 + include_once "Services/AdvancedMetaData/classes/class.ilAdvancedMDValues.php"; + ilAdvancedMDValues::_cloneValues( + $this->getId(), + $this->getId(), + "wpg", + $a_template_page, + $page->getId() + ); + } + + return $page; + } + + public static function getAdvMDSubItemTitle($a_obj_id, $a_sub_type, $a_sub_id) + { + global $DIC; + + $lng = $DIC->language(); + + if ($a_sub_type == "wpg") { + $lng->loadLanguageModule("wiki"); + include_once "./Modules/Wiki/classes/class.ilWikiPage.php"; + return $lng->txt("wiki_wpg") . ' "' . ilWikiPage::lookupTitle($a_sub_id) . '"'; + } + } + + /** + * Init user html export + * + * @param + * @return + */ + public function initUserHTMLExport() + { + $ilDB = $this->db; + $ilUser = $this->user; + + include_once("./Modules/Wiki/classes/class.ilWikiUserHTMLExport.php"); + + $user_export = new ilWikiUserHTMLExport($this, $ilDB, $ilUser); + $user_export->initUserHTMLExport(); + } + + /** + * Start user html export + * + * @param + * @return + */ + public function startUserHTMLExport() + { + $ilDB = $this->db; + $ilUser = $this->user; + + include_once("./Modules/Wiki/classes/class.ilWikiUserHTMLExport.php"); + + $user_export = new ilWikiUserHTMLExport($this, $ilDB, $ilUser); + $user_export->startUserHTMLExport(); + } + + /** + * Get user html export progress + * + * @return array progress info + */ + public function getUserHTMLExportProgress() + { + $ilDB = $this->db; + $ilUser = $this->user; + + include_once("./Modules/Wiki/classes/class.ilWikiUserHTMLExport.php"); + + $user_export = new ilWikiUserHTMLExport($this, $ilDB, $ilUser); + return $user_export->getProgress(); + } + + /** + * Send user html export file + */ + public function deliverUserHTMLExport() + { + $ilDB = $this->db; + $ilUser = $this->user; + + include_once("./Modules/Wiki/classes/class.ilWikiUserHTMLExport.php"); + + $user_export = new ilWikiUserHTMLExport($this, $ilDB, $ilUser); + return $user_export->deliverFile(); + } + + + /** + * Decorate adv md value + * + * @param string $a_value value + * @return string decorated value (includes HTML) + */ + public function decorateAdvMDValue($a_value) + { + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + if (ilWikiPage::_wikiPageExists($this->getId(), $a_value)) { + $url = ilObjWikiGUI::getGotoLink($this->getRefId(), $a_value); + return "" . $a_value . ""; + } + + return $a_value; + } } -?> diff --git a/Modules/Wiki/classes/class.ilObjWikiAccess.php b/Modules/Wiki/classes/class.ilObjWikiAccess.php index 172d18896b4abca7e8d9e1c758c43e5c58e2e9f6..30fbc2ac171bef1f3fcc4fd5a4255e2090082f3d 100755 --- a/Modules/Wiki/classes/class.ilObjWikiAccess.php +++ b/Modules/Wiki/classes/class.ilObjWikiAccess.php @@ -14,220 +14,198 @@ include_once("./Services/Object/classes/class.ilObjectAccess.php"); */ class ilObjWikiAccess extends ilObjectAccess { - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilAccessHandler - */ - protected $access; - - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->user = $DIC->user(); - $this->lng = $DIC->language(); - $this->rbacsystem = $DIC->rbac()->system(); - $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" => "view", "lang_var" => "show", - "default" => true), - array("permission" => "write", "cmd" => "editSettings", "lang_var" => "settings") - ); - - return $commands; - } - - /** - * checks wether a user may invoke a command or not - * (this method is called by ilAccessHandler::checkAccess) - * - * @param string $a_cmd command (not permission!) - * @param string $a_permission permission - * @param int $a_ref_id reference id - * @param int $a_obj_id object id - * @param int $a_user_id user id (if not provided, current user is taken) - * - * @return boolean true, if everything is ok - */ - function _checkAccess($a_cmd, $a_permission, $a_ref_id, $a_obj_id, $a_user_id = "") - { - $ilUser = $this->user; - $lng = $this->lng; - $rbacsystem = $this->rbacsystem; - $ilAccess = $this->access; - - if ($a_user_id == "") - { - $a_user_id = $ilUser->getId(); - } - - switch ($a_cmd) - { - case "view": - - if(!ilObjWikiAccess::_lookupOnline($a_obj_id) - && !$rbacsystem->checkAccessOfUser($a_user_id,'write',$a_ref_id)) - { - $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("offline")); - return false; - } - break; - - // for permission query feature - case "infoScreen": - if(!ilObjWikiAccess::_lookupOnline($a_obj_id)) - { - $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("offline")); - } - else - { - $ilAccess->addInfoItem(IL_STATUS_MESSAGE, $lng->txt("online")); - } - break; - - } - switch ($a_permission) - { - case "read": - case "visible": - if (!ilObjWikiAccess::_lookupOnline($a_obj_id) && - (!$rbacsystem->checkAccessOfUser($a_user_id, 'write', $a_ref_id))) - { - $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("offline")); - return false; - } - - include_once("./Modules/Exercise/RepoObjectAssignment/classes/class.ilExcRepoObjAssignment.php"); - $info = ilExcRepoObjAssignment::getInstance()->getAccessInfo($a_ref_id, $a_user_id); - if (!$info->isGranted()) - { - $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, implode(" / ", $info->getNotGrantedReasons())); - return false; - } - break; - } - - return true; - } - - /** - * check whether goto script will succeed - */ - static function _checkGoto($a_target) - { - global $DIC; - - $ilAccess = $DIC->access(); -// echo "-".$a_target."-"; exit; - $t_arr = explode("_", $a_target); - - if ($t_arr[0] != "wiki" || (((int) $t_arr[1]) <= 0) && $t_arr[1] != "wpage") - { - return false; - } - - if ($t_arr[1] == "wpage") - { - $wpg_id = (int) $t_arr[2]; - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $w_id = ilWikiPage::lookupWikiId($wpg_id); - if ((int) $t_arr[3] > 0) - { - $refs = array((int) $t_arr[3]); - } - else - { - $refs = ilObject::_getAllReferences($w_id); - } - foreach ($refs as $r) - { - if ($ilAccess->checkAccess("read", "", $r)) - { - return true; - } - } - } - else if ($ilAccess->checkAccess("read", "", $t_arr[1])) - { - return true; - } - return false; - } - - /** - * Check wether wiki cast is online - * - * @param int $a_id wiki id - */ - static function _lookupOnline($a_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "SELECT * FROM il_wiki_data WHERE id = ". - $ilDB->quote($a_id, "integer"); - $wk_set = $ilDB->query($q); - $wk_rec = $ilDB->fetchAssoc($wk_set); - - return $wk_rec["is_online"]; - } - - /** - * Check wether files should be public - * - * @param int $a_id wiki id - */ - static function _lookupPublicFiles($a_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "SELECT * FROM il_wiki_data WHERE id = ". - $ilDB->quote($a_id, "integer"); - $wk_set = $ilDB->query($q); - $wk_rec = $ilDB->fetchAssoc($wk_set); - - return $wk_rec["public_files"]; - } - + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilAccessHandler + */ + protected $access; + + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->user = $DIC->user(); + $this->lng = $DIC->language(); + $this->rbacsystem = $DIC->rbac()->system(); + $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"), + * ); + */ + public static function _getCommands() + { + $commands = array( + array("permission" => "read", "cmd" => "view", "lang_var" => "show", + "default" => true), + array("permission" => "write", "cmd" => "editSettings", "lang_var" => "settings") + ); + + return $commands; + } + + /** + * checks wether a user may invoke a command or not + * (this method is called by ilAccessHandler::checkAccess) + * + * @param string $a_cmd command (not permission!) + * @param string $a_permission permission + * @param int $a_ref_id reference id + * @param int $a_obj_id object id + * @param int $a_user_id user id (if not provided, current user is taken) + * + * @return boolean true, if everything is ok + */ + public function _checkAccess($a_cmd, $a_permission, $a_ref_id, $a_obj_id, $a_user_id = "") + { + $ilUser = $this->user; + $lng = $this->lng; + $rbacsystem = $this->rbacsystem; + $ilAccess = $this->access; + + if ($a_user_id == "") { + $a_user_id = $ilUser->getId(); + } + + switch ($a_cmd) { + case "view": + + if (!ilObjWikiAccess::_lookupOnline($a_obj_id) + && !$rbacsystem->checkAccessOfUser($a_user_id, 'write', $a_ref_id)) { + $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("offline")); + return false; + } + break; + + // for permission query feature + case "infoScreen": + if (!ilObjWikiAccess::_lookupOnline($a_obj_id)) { + $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("offline")); + } else { + $ilAccess->addInfoItem(IL_STATUS_MESSAGE, $lng->txt("online")); + } + break; + + } + switch ($a_permission) { + case "read": + case "visible": + if (!ilObjWikiAccess::_lookupOnline($a_obj_id) && + (!$rbacsystem->checkAccessOfUser($a_user_id, 'write', $a_ref_id))) { + $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $lng->txt("offline")); + return false; + } + + include_once("./Modules/Exercise/RepoObjectAssignment/classes/class.ilExcRepoObjAssignment.php"); + $info = ilExcRepoObjAssignment::getInstance()->getAccessInfo($a_ref_id, $a_user_id); + if (!$info->isGranted()) { + $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, implode(" / ", $info->getNotGrantedReasons())); + return false; + } + break; + } + + return true; + } + + /** + * check whether goto script will succeed + */ + public static function _checkGoto($a_target) + { + global $DIC; + + $ilAccess = $DIC->access(); + // echo "-".$a_target."-"; exit; + $t_arr = explode("_", $a_target); + + if ($t_arr[0] != "wiki" || (((int) $t_arr[1]) <= 0) && $t_arr[1] != "wpage") { + return false; + } + + if ($t_arr[1] == "wpage") { + $wpg_id = (int) $t_arr[2]; + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + $w_id = ilWikiPage::lookupWikiId($wpg_id); + if ((int) $t_arr[3] > 0) { + $refs = array((int) $t_arr[3]); + } else { + $refs = ilObject::_getAllReferences($w_id); + } + foreach ($refs as $r) { + if ($ilAccess->checkAccess("read", "", $r)) { + return true; + } + } + } elseif ($ilAccess->checkAccess("read", "", $t_arr[1])) { + return true; + } + return false; + } + + /** + * Check wether wiki cast is online + * + * @param int $a_id wiki id + */ + public static function _lookupOnline($a_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "SELECT * FROM il_wiki_data WHERE id = " . + $ilDB->quote($a_id, "integer"); + $wk_set = $ilDB->query($q); + $wk_rec = $ilDB->fetchAssoc($wk_set); + + return $wk_rec["is_online"]; + } + + /** + * Check wether files should be public + * + * @param int $a_id wiki id + */ + public static function _lookupPublicFiles($a_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "SELECT * FROM il_wiki_data WHERE id = " . + $ilDB->quote($a_id, "integer"); + $wk_set = $ilDB->query($q); + $wk_rec = $ilDB->fetchAssoc($wk_set); + + return $wk_rec["public_files"]; + } } - -?> diff --git a/Modules/Wiki/classes/class.ilObjWikiGUI.php b/Modules/Wiki/classes/class.ilObjWikiGUI.php index 84746cd5f01414afa6c1ccc760add06ee526d1b1..d4fb643ddc3d41e4696d7579a38f08a8d96f35d4 100755 --- a/Modules/Wiki/classes/class.ilObjWikiGUI.php +++ b/Modules/Wiki/classes/class.ilObjWikiGUI.php @@ -8,9 +8,9 @@ require_once "./Modules/Wiki/classes/class.ilObjWiki.php"; /** * Class ilObjWikiGUI * -* @author Alex Killing +* @author Alex Killing * @version $Id$ -* +* * @ilCtrl_Calls ilObjWikiGUI: ilPermissionGUI, ilInfoScreenGUI, ilWikiPageGUI * @ilCtrl_IsCalledBy ilObjWikiGUI: ilRepositoryGUI, ilAdministrationGUI * @ilCtrl_Calls ilObjWikiGUI: ilPublicUserProfileGUI, ilObjStyleSheetGUI @@ -22,2266 +22,2258 @@ require_once "./Modules/Wiki/classes/class.ilObjWiki.php"; */ class ilObjWikiGUI extends ilObjectGUI { - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * @var ilHelpGUI - */ - protected $help; - - - /** - * @var ilLogger - */ - protected $log; - - /** - * Constructor - * @access public - */ - function __construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output = true) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - $this->tpl = $DIC["tpl"]; - $this->tabs = $DIC->tabs(); - $this->access = $DIC->access(); - $this->error = $DIC["ilErr"]; - $this->settings = $DIC->settings(); - $this->help = $DIC["ilHelp"]; - $this->locator = $DIC["ilLocator"]; - $this->toolbar = $DIC->toolbar(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->type = "wiki"; - - $this->log = ilLoggerFactory::getLogger('wiki'); - - parent::__construct($a_data,$a_id,$a_call_by_reference,$a_prepare_output); - $lng->loadLanguageModule("obj"); - $lng->loadLanguageModule("wiki"); - - if ($_GET["page"] != "") - { - $ilCtrl->setParameter($this, "page", ilWikiUtil::makeUrlTitle($_GET["page"])); - } - } - - function executeCommand() - { - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - $ilAccess = $this->access; + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilHelpGUI + */ + protected $help; + + + /** + * @var ilLogger + */ + protected $log; + + /** + * Constructor + * @access public + */ + public function __construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output = true) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + $this->tpl = $DIC["tpl"]; + $this->tabs = $DIC->tabs(); + $this->access = $DIC->access(); + $this->error = $DIC["ilErr"]; + $this->settings = $DIC->settings(); + $this->help = $DIC["ilHelp"]; + $this->locator = $DIC["ilLocator"]; + $this->toolbar = $DIC->toolbar(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->type = "wiki"; + + $this->log = ilLoggerFactory::getLogger('wiki'); + + parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); + $lng->loadLanguageModule("obj"); + $lng->loadLanguageModule("wiki"); + + if ($_GET["page"] != "") { + $ilCtrl->setParameter($this, "page", ilWikiUtil::makeUrlTitle($_GET["page"])); + } + } + + public function executeCommand() + { + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + $ilAccess = $this->access; - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - $this->prepareOutput(); - - // see ilWikiPageGUI::printViewOrderList() - // printView() and pdfExport() cannot be in ilWikiPageGUI because of stylesheet confusion - if($cmd == "printView" || $cmd == "pdfExport") - { - $next_class = null; - } - - switch($next_class) - { - case "ilinfoscreengui": - $this->checkPermission("visible"); - $this->addHeaderAction(); - $this->infoScreen(); // forwards command - break; - - case 'ilpermissiongui': - $this->addHeaderAction(); - $ilTabs->activateTab("perm_settings"); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $ret = $this->ctrl->forwardCommand($perm_gui); - break; - - case 'ilsettingspermissiongui': - $this->checkPermission("write"); - $this->addHeaderAction(); - $ilTabs->activateTab("settings"); - $this->setSettingsSubTabs("permission_settings"); - include_once("Services/AccessControl/classes/class.ilSettingsPermissionGUI.php"); - $perm_gui = new ilSettingsPermissionGUI($this); - $perm_gui->setPermissions(array("edit_wiki_navigation", "delete_wiki_pages", "activate_wiki_protection", - "wiki_html_export")); - $perm_gui->setRoleRequiredPermissions(array("edit_content")); - $perm_gui->setRoleProhibitedPermissions(array("write")); - $ret = $this->ctrl->forwardCommand($perm_gui); - break; - - case 'ilwikipagegui': - $this->checkPermission("read"); - include_once("./Modules/Wiki/classes/class.ilWikiPageGUI.php"); - $wpage_gui = ilWikiPageGUI::getGUIForTitle($this->object->getId(), - ilWikiUtil::makeDbTitle($_GET["page"]), $_GET["old_nr"], $this->object->getRefId()); - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $wpage_gui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId( - $this->object->getStyleSheetId(), "wiki")); - $this->setContentStyleSheet(); - if (!$ilAccess->checkAccess("write", "", $this->object->getRefId()) && - (!$ilAccess->checkAccess("edit_content", "", $this->object->getRefId()) || - $wpage_gui->getPageObject()->getBlocked() - )) - { - $wpage_gui->setEnableEditing(false); - } - - // alter title and description + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + $this->prepareOutput(); + + // see ilWikiPageGUI::printViewOrderList() + // printView() and pdfExport() cannot be in ilWikiPageGUI because of stylesheet confusion + if ($cmd == "printView" || $cmd == "pdfExport") { + $next_class = null; + } + + switch ($next_class) { + case "ilinfoscreengui": + $this->checkPermission("visible"); + $this->addHeaderAction(); + $this->infoScreen(); // forwards command + break; + + case 'ilpermissiongui': + $this->addHeaderAction(); + $ilTabs->activateTab("perm_settings"); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $ret = $this->ctrl->forwardCommand($perm_gui); + break; + + case 'ilsettingspermissiongui': + $this->checkPermission("write"); + $this->addHeaderAction(); + $ilTabs->activateTab("settings"); + $this->setSettingsSubTabs("permission_settings"); + include_once("Services/AccessControl/classes/class.ilSettingsPermissionGUI.php"); + $perm_gui = new ilSettingsPermissionGUI($this); + $perm_gui->setPermissions(array("edit_wiki_navigation", "delete_wiki_pages", "activate_wiki_protection", + "wiki_html_export")); + $perm_gui->setRoleRequiredPermissions(array("edit_content")); + $perm_gui->setRoleProhibitedPermissions(array("write")); + $ret = $this->ctrl->forwardCommand($perm_gui); + break; + + case 'ilwikipagegui': + $this->checkPermission("read"); + include_once("./Modules/Wiki/classes/class.ilWikiPageGUI.php"); + $wpage_gui = ilWikiPageGUI::getGUIForTitle( + $this->object->getId(), + ilWikiUtil::makeDbTitle($_GET["page"]), + $_GET["old_nr"], + $this->object->getRefId() + ); + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $wpage_gui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId( + $this->object->getStyleSheetId(), + "wiki" + )); + $this->setContentStyleSheet(); + if (!$ilAccess->checkAccess("write", "", $this->object->getRefId()) && + ( + !$ilAccess->checkAccess("edit_content", "", $this->object->getRefId()) || + $wpage_gui->getPageObject()->getBlocked() + )) { + $wpage_gui->setEnableEditing(false); + } + + // alter title and description // $tpl->setTitle($wpage_gui->getPageObject()->getTitle()); // $tpl->setDescription($this->object->getTitle()); - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - $wpage_gui->activateMetaDataEditor($this->object, "wpg", $wpage_gui->getId()); - } - - $ret = $this->ctrl->forwardCommand($wpage_gui); - if ($ret != "") - { - $tpl->setContent($ret); - } - break; - - case 'ilobjectcopygui': - include_once './Services/Object/classes/class.ilObjectCopyGUI.php'; - $cp = new ilObjectCopyGUI($this); - $cp->setType('wiki'); - $this->ctrl->forwardCommand($cp); - break; - - case 'ilpublicuserprofilegui': - require_once './Services/User/classes/class.ilPublicUserProfileGUI.php'; - $profile_gui = new ilPublicUserProfileGUI($_GET["user"]); - $ret = $this->ctrl->forwardCommand($profile_gui); - $tpl->setContent($ret); - 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" || $_GET["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 "ilexportgui": + if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) { + $wpage_gui->activateMetaDataEditor($this->object, "wpg", $wpage_gui->getId()); + } + + $ret = $this->ctrl->forwardCommand($wpage_gui); + if ($ret != "") { + $tpl->setContent($ret); + } + break; + + case 'ilobjectcopygui': + include_once './Services/Object/classes/class.ilObjectCopyGUI.php'; + $cp = new ilObjectCopyGUI($this); + $cp->setType('wiki'); + $this->ctrl->forwardCommand($cp); + break; + + case 'ilpublicuserprofilegui': + require_once './Services/User/classes/class.ilPublicUserProfileGUI.php'; + $profile_gui = new ilPublicUserProfileGUI($_GET["user"]); + $ret = $this->ctrl->forwardCommand($profile_gui); + $tpl->setContent($ret); + 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" || $_GET["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 "ilexportgui": // $this->prepareOutput(); - $this->addHeaderAction(); - $ilTabs->activateTab("export"); - include_once("./Services/Export/classes/class.ilExportGUI.php"); - $exp_gui = new ilExportGUI($this); - $exp_gui->addFormat("xml"); - $exp_gui->addFormat("html", "", $this, "exportHTML"); - $ret = $this->ctrl->forwardCommand($exp_gui); + $this->addHeaderAction(); + $ilTabs->activateTab("export"); + include_once("./Services/Export/classes/class.ilExportGUI.php"); + $exp_gui = new ilExportGUI($this); + $exp_gui->addFormat("xml"); + $exp_gui->addFormat("html", "", $this, "exportHTML"); + $ret = $this->ctrl->forwardCommand($exp_gui); // $this->tpl->show(); - break; - - case "ilcommonactiondispatchergui": - include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); - $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); - $this->ctrl->forwardCommand($gui); - break; - - case "ilratinggui": - // for rating category editing - $this->checkPermission("write"); - $this->addHeaderAction(); - $ilTabs->activateTab("settings"); - $this->setSettingsSubTabs("rating_categories"); - include_once("Services/Rating/classes/class.ilRatingGUI.php"); - $gui = new ilRatingGUI(); - $gui->setObject($this->object->getId(), $this->object->getType()); - $gui->setExportCallback(array($this, "getSubObjectTitle"), $this->lng->txt("page")); - $this->ctrl->forwardCommand($gui); - break; - - case "ilwikistatgui": - $this->checkPermission("statistics_read"); - - $this->addHeaderAction(); - $ilTabs->activateTab("statistics"); - - include_once "Modules/Wiki/classes/class.ilWikiStatGUI.php"; - $gui = new ilWikiStatGUI($this->object->getId()); - $this->ctrl->forwardCommand($gui); - break; - - case "ilwikipagetemplategui": - $this->checkPermission("write"); - $this->addHeaderAction(); - $ilTabs->activateTab("settings"); - $this->setSettingsSubTabs("page_templates"); - include_once("./Modules/Wiki/classes/class.ilWikiPageTemplateGUI.php"); - $wptgui = new ilWikiPageTemplateGUI($this); - $this->ctrl->forwardCommand($wptgui); - break; - - case 'ilobjectmetadatagui'; - $this->checkPermission("write"); - $this->addHeaderAction(); - $ilTabs->activateTab("advmd"); - include_once 'Services/Object/classes/class.ilObjectMetaDataGUI.php'; - $md_gui = new ilObjectMetaDataGUI($this->object, "wpg"); - $this->ctrl->forwardCommand($md_gui); - break; - - case 'ilrepositoryobjectsearchgui': - $this->addHeaderAction(); - $this->setSideBlock(); - $ilTabs->setTabActive("wiki_search_results"); - $ilCtrl->setReturn($this,'view'); - include_once './Services/Search/classes/class.ilRepositoryObjectSearchGUI.php'; - $search_gui = new ilRepositoryObjectSearchGUI( - $this->object->getRefId(), - $this, - 'view' - ); - $ilCtrl->forwardCommand($search_gui); - break; - - case 'ilobjnotificationsettingsgui': - $this->addHeaderAction(); - $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: - $this->addHeaderAction(); - if(!$cmd) - { - $cmd = "infoScreen"; - } - $cmd .= "Object"; - if ($cmd != "cancelObject") - { - if ($cmd != "infoScreenObject") - { - if (!in_array($cmd, array("createObject", "saveObject", "importFileObject"))) - { - $this->checkPermission("read"); - } - } else - { - $this->checkPermission("visible"); - } - } - $this->$cmd(); - break; - } + break; + + case "ilcommonactiondispatchergui": + include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); + $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); + $this->ctrl->forwardCommand($gui); + break; + + case "ilratinggui": + // for rating category editing + $this->checkPermission("write"); + $this->addHeaderAction(); + $ilTabs->activateTab("settings"); + $this->setSettingsSubTabs("rating_categories"); + include_once("Services/Rating/classes/class.ilRatingGUI.php"); + $gui = new ilRatingGUI(); + $gui->setObject($this->object->getId(), $this->object->getType()); + $gui->setExportCallback(array($this, "getSubObjectTitle"), $this->lng->txt("page")); + $this->ctrl->forwardCommand($gui); + break; + + case "ilwikistatgui": + $this->checkPermission("statistics_read"); + + $this->addHeaderAction(); + $ilTabs->activateTab("statistics"); + + include_once "Modules/Wiki/classes/class.ilWikiStatGUI.php"; + $gui = new ilWikiStatGUI($this->object->getId()); + $this->ctrl->forwardCommand($gui); + break; + + case "ilwikipagetemplategui": + $this->checkPermission("write"); + $this->addHeaderAction(); + $ilTabs->activateTab("settings"); + $this->setSettingsSubTabs("page_templates"); + include_once("./Modules/Wiki/classes/class.ilWikiPageTemplateGUI.php"); + $wptgui = new ilWikiPageTemplateGUI($this); + $this->ctrl->forwardCommand($wptgui); + break; + + case 'ilobjectmetadatagui': + $this->checkPermission("write"); + $this->addHeaderAction(); + $ilTabs->activateTab("advmd"); + include_once 'Services/Object/classes/class.ilObjectMetaDataGUI.php'; + $md_gui = new ilObjectMetaDataGUI($this->object, "wpg"); + $this->ctrl->forwardCommand($md_gui); + break; + + case 'ilrepositoryobjectsearchgui': + $this->addHeaderAction(); + $this->setSideBlock(); + $ilTabs->setTabActive("wiki_search_results"); + $ilCtrl->setReturn($this, 'view'); + include_once './Services/Search/classes/class.ilRepositoryObjectSearchGUI.php'; + $search_gui = new ilRepositoryObjectSearchGUI( + $this->object->getRefId(), + $this, + 'view' + ); + $ilCtrl->forwardCommand($search_gui); + break; + + case 'ilobjnotificationsettingsgui': + $this->addHeaderAction(); + $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: + $this->addHeaderAction(); + if (!$cmd) { + $cmd = "infoScreen"; + } + $cmd .= "Object"; + if ($cmd != "cancelObject") { + if ($cmd != "infoScreenObject") { + if (!in_array($cmd, array("createObject", "saveObject", "importFileObject"))) { + $this->checkPermission("read"); + } + } else { + $this->checkPermission("visible"); + } + } + $this->$cmd(); + break; + } - return $ret; - } - - /** - * Is wiki an online help wiki? - * - * @return boolean true, if current wiki is an online help wiki - */ - function isOnlineHelpWiki() - { - if (is_object($this->object)) - { - return ilObjWiki::isOnlineHelpWiki($this->object->getRefId()); - } - return false; - } - - /** - * Start page - */ - function viewObject() - { - $this->checkPermission("read"); - $this->gotoStartPageObject(); - } - - protected function initCreationForms($a_new_type) - { - $this->initSettingsForm("create"); - $this->getSettingsFormValues("create"); - - $forms = array(self::CFORM_NEW => $this->form_gui, - self::CFORM_IMPORT => $this->initImportForm($a_new_type), - self::CFORM_CLONE => $this->fillCloneTemplate(null, $a_new_type)); - - return $forms; - } - - /** - * save object - * @access public - */ - function saveObject() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilErr = $this->error; - - if (!$this->checkPermissionBool("create", "", "wiki", $_GET["ref_id"])) - { - $ilErr->raiseError($this->lng->txt("permission_denied"),$ilErr->MESSAGE); - } - - $this->initSettingsForm("create"); - if ($this->form_gui->checkInput()) - { - if (!ilObjWiki::checkShortTitleAvailability($this->form_gui->getInput("shorttitle"))) - { - $short_item = $this->form_gui->getItemByPostVar("shorttitle"); - $short_item->setAlert($lng->txt("wiki_short_title_already_in_use")); - } - else - { - // create and insert forum in objecttree - $_POST["title"] = $this->form_gui->getInput("title"); - $_POST["desc"] = $this->form_gui->getInput("description"); - return parent::saveObject(); - } - } - - $this->form_gui->setValuesByPost(); - $tpl->setContent($this->form_gui->getHtml()); - } - - /** - * save object - * @access public - */ - function afterSave(ilObject $newObj) - { - $ilSetting = $this->settings; - - $newObj->setTitle($this->form_gui->getInput("title")); - $newObj->setDescription($this->form_gui->getInput("description")); - $newObj->setIntroduction($this->form_gui->getInput("intro")); - $newObj->setStartPage($this->form_gui->getInput("startpage")); - $newObj->setShortTitle($this->form_gui->getInput("shorttitle")); - $newObj->setRating($this->form_gui->getInput("rating")); - // $newObj->setRatingAsBlock($this->form_gui->getInput("rating_side")); - $newObj->setRatingForNewPages($this->form_gui->getInput("rating_new")); - $newObj->setRatingCategories($this->form_gui->getInput("rating_ext")); - - $newObj->setRatingOverall($this->form_gui->getInput("rating_overall")); - $newObj->setPageToc($this->form_gui->getInput("page_toc")); - - - - if (!$ilSetting->get("disable_comments")) - { - $newObj->setPublicNotes($this->form_gui->getInput("public_notes")); - } - $newObj->setOnline($this->form_gui->getInput("online")); - $newObj->update(); - - // always send a message - ilUtil::sendSuccess($this->lng->txt("object_added"),true); - ilUtil::redirect(ilObjWikiGUI::getGotoLink($newObj->getRefId())); - } - - /** - * 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 infoScreenObject() - { - $this->checkPermission("visible"); - $this->ctrl->setCmd("showSummary"); - $this->ctrl->setCmdClass("ilinfoscreengui"); - $this->infoScreen(); - } - - /** - * show information screen - */ - function infoScreen() - { - $ilAccess = $this->access; - $ilUser = $this->user; - $ilTabs = $this->tabs; - $lng = $this->lng; - $ilErr = $this->error; - - $ilTabs->activateTab("info_short"); - - if (!$ilAccess->checkAccess("visible", "", $this->object->getRefId())) - { - $ilErr->raiseError($this->lng->txt("msg_no_perm_read"),$ilErr->MESSAGE); - } - - include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); - $info = new ilInfoScreenGUI($this); - $info->enablePrivateNotes(); - if (trim($this->object->getIntroduction()) != "") - { - $info->addSection($lng->txt("wiki_introduction")); - $info->addProperty("", nl2br($this->object->getIntroduction())); - } - - // feedback from tutor; mark, status, comment - include_once("./Modules/Wiki/classes/class.ilWikiContributor.php"); - include_once("./Services/Tracking/classes/class.ilLPMarks.php"); - $lpcomment = ilLPMarks::_lookupComment($ilUser->getId(), $this->object->getId()); - $mark = ilLPMarks::_lookupMark($ilUser->getId(), $this->object->getId()); - $status = ilWikiContributor::_lookupStatus($this->object->getId(), $ilUser->getId()); - if ($lpcomment != "" || $mark != "" || $status != ilWikiContributor::STATUS_NOT_GRADED) - { - $info->addSection($this->lng->txt("wiki_feedback_from_tutor")); - if ($lpcomment != "") - { - $info->addProperty($this->lng->txt("wiki_comment"), - $lpcomment); - } - if ($mark != "") - { - $info->addProperty($this->lng->txt("wiki_mark"), - $mark); - } - - if ($status == ilWikiContributor::STATUS_PASSED) - { - $info->addProperty($this->lng->txt("status"), - $this->lng->txt("wiki_passed")); - } - if ($status == ilWikiContributor::STATUS_FAILED) - { - $info->addProperty($this->lng->txt("status"), - $this->lng->txt("wiki_failed")); - } - } - - /* - $info->enableNews(); - if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) - { - //$info->enableNewsEditing(); - $info->setBlockProperty("news", "settings", true); - }*/ - - if ($ilAccess->checkAccess("read", "", $this->object->getRefId())) - { - $info->addButton($lng->txt("wiki_start_page"), ilObjWikiGUI::getGotoLink($this->object->getRefId())); - } - - // general information - $this->lng->loadLanguageModule("meta"); - $this->lng->loadLanguageModule("wiki"); - - //$info->addSection($this->lng->txt("meta_general")); - //$info->addProperty($this->lng->txt("mcst_nr_items"), - // (int) count($med_items)); - - // forward the command - $this->ctrl->forwardCommand($info); - - if ($ilAccess->checkAccess("read", "", $this->object->getRefId())) - { -// $this->setSideBlock(); - } - } - - /** - * Go to start page - */ - function gotoStartPageObject() - { - $ilCtrl = $this->ctrl; - - ilUtil::redirect(ilObjWikiGUI::getGotoLink($this->object->getRefId())); - } - - /** - * Add Page Tabs - */ - function addPageTabs() - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $ilCtrl->setParameter($this, "wpg_id", - ilWikiPage::getPageIdForTitle($this->object->getId(), ilWikiUtil::makeDbTitle($_GET["page"]))); - $ilCtrl->setParameter($this, "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("ilwikipagegui", - "printViewSelection"), "printViewSelection"); - } - - /** - * Add Pages SubTabs - */ - function addPagesSubTabs() - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - - $ilTabs->activateTab("wiki_pages"); - - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $ilCtrl->setParameter($this, "wpg_id", - ilWikiPage::getPageIdForTitle($this->object->getId(), - ilWikiUtil::makeDbTitle($_GET["page"]))); - $ilCtrl->setParameter($this, "page", ilWikiUtil::makeUrlTitle($_GET["page"])); - $ilTabs->addSubTabTarget("wiki_all_pages", - $this->ctrl->getLinkTarget($this, "allPages"), "allPages"); - $ilTabs->addSubTabTarget("wiki_recent_changes", - $this->ctrl->getLinkTarget($this, "recentChanges"), "recentChanges"); - $ilTabs->addSubTabTarget("wiki_new_pages", - $this->ctrl->getLinkTarget($this, "newPages"), "newPages"); - $ilTabs->addSubTabTarget("wiki_popular_pages", - $this->ctrl->getLinkTarget($this, "popularPages"), "popularPages"); - $ilTabs->addSubTabTarget("wiki_orphaned_pages", - $this->ctrl->getLinkTarget($this, "orphanedPages"), "orphanedPages"); - } - - /** - * get tabs - * @access public - * @param object tabs gui object - */ - function getTabs() - { - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - $lng = $this->lng; - $ilHelp = $this->help; - - $ilHelp->setScreenIdComponent("wiki"); - - // wiki tabs - if (in_array($ilCtrl->getCmdClass(), array("", "ilobjwikigui", - "ilinfoscreengui", "ilpermissiongui", "ilexportgui", "ilratingcategorygui", "ilobjnotificationsettingsgui", "iltaxmdgui", - "ilwikistatgui", "ilwikipagetemplategui", "iladvancedmdsettingsgui", "ilsettingspermissiongui", 'ilrepositoryobjectsearchgui' - )) || (in_array($ilCtrl->getNextClass(), array("ilpermissiongui")))) - { - if ($_GET["page"] != "") - { - $this->tabs_gui->setBackTarget($lng->txt("wiki_last_visited_page"), - $this->getGotoLink($_GET["ref_id"], - ilWikiUtil::makeDbTitle($_GET["page"]))); - } - - // pages - if ($ilAccess->checkAccess('read', "", $this->object->getRefId())) - { - $this->tabs_gui->addTab("wiki_pages", - $lng->txt("wiki_pages"), - $this->ctrl->getLinkTarget($this, "allPages")); - } - - // info screen - if ($ilAccess->checkAccess('visible', "", $this->object->getRefId())) - { - $this->tabs_gui->addTab("info_short", - $lng->txt("info_short"), - $this->ctrl->getLinkTargetByClass("ilinfoscreengui", "showSummary")); - } - - // settings - if ($ilAccess->checkAccess('write', "", $this->object->getRefId())) - { - $this->tabs_gui->addTab("settings", - $lng->txt("settings"), - $this->ctrl->getLinkTarget($this, "editSettings")); - - // metadata - include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php"; - $mdgui = new ilObjectMetaDataGUI($this->object, "wpg"); - $mdtab = $mdgui->getTab(); - if($mdtab) - { - $this->tabs_gui->addTab("advmd", - $this->lng->txt("meta_data"), - $mdtab); - } - } - - // contributors - if ($ilAccess->checkAccess('write', "", $this->object->getRefId())) - { - $this->tabs_gui->addTab("wiki_contributors", - $lng->txt("wiki_contributors"), - $this->ctrl->getLinkTarget($this, "listContributors")); - } - - // statistics - if ($ilAccess->checkAccess('statistics_read', "", $this->object->getRefId())) - { - $this->tabs_gui->addTab("statistics", - $lng->txt("statistics"), - $this->ctrl->getLinkTargetByClass("ilWikiStatGUI", "initial")); - } - - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - $this->tabs_gui->addTab("export", - $lng->txt("export"), - $this->ctrl->getLinkTargetByClass("ilexportgui", "")); - } - - // edit permissions - if ($ilAccess->checkAccess('edit_permission', "", $this->object->getRefId())) - { - $this->tabs_gui->addTab("perm_settings", - $lng->txt("perm_settings"), - $this->ctrl->getLinkTargetByClass("ilpermissiongui", "perm")); - } - } - } - - /** - * Set sub tabs - */ - function setSettingsSubTabs($a_active) - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilAccess = $this->access; - - if (in_array($a_active, - array("general_settings", "style", "imp_pages", "rating_categories", - "page_templates", "advmd", "permission_settings", "notifications"))) - { - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - // general properties - $ilTabs->addSubTab("general_settings", - $lng->txt("wiki_general_settings"), - $ilCtrl->getLinkTarget($this, 'editSettings')); - - // permission settings - $ilTabs->addSubTab("permission_settings", - $lng->txt("obj_permission_settings"), - $this->ctrl->getLinkTargetByClass("ilsettingspermissiongui", "")); - - // style properties - $ilTabs->addSubTab("style", - $lng->txt("wiki_style"), - $ilCtrl->getLinkTarget($this, 'editStyleProperties')); - } - - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - // important pages - $ilTabs->addSubTab("imp_pages", - $lng->txt("wiki_navigation"), - $ilCtrl->getLinkTarget($this, 'editImportantPages')); - } - - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - // page templates - $ilTabs->addSubTab("page_templates", - $lng->txt("wiki_page_templates"), - $ilCtrl->getLinkTargetByClass("ilwikipagetemplategui", "")); - - // rating categories - if ($this->object->getRating() && $this->object->getRatingCategories()) - { - $lng->loadLanguageModule("rating"); - $ilTabs->addSubTab("rating_categories", - $lng->txt("rating_categories"), - $ilCtrl->getLinkTargetByClass(array('ilratinggui', 'ilratingcategorygui'), '')); - } - - $ilTabs->addSubTab('notifications', - $lng->txt("notifications"), - $ilCtrl->getLinkTargetByClass("ilobjnotificationsettingsgui", '')); - - } - - $ilTabs->activateSubTab($a_active); - } - } - - /** - * Edit settings - */ - function editSettingsObject() - { - $tpl = $this->tpl; - - $this->checkPermission("write"); - - $this->setSettingsSubTabs("general_settings"); - - $this->initSettingsForm(); - $this->getSettingsFormValues(); - - // Edit ecs export settings - include_once 'Modules/Wiki/classes/class.ilECSWikiSettings.php'; - $ecs = new ilECSWikiSettings($this->object); - $ecs->addSettingsToForm($this->form_gui, 'wiki'); - - $tpl->setContent($this->form_gui->getHtml()); - $this->setSideBlock(); - } - - /** - * Init Settings Form - */ - function initSettingsForm($a_mode = "edit") - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - $ilSetting = $this->settings; - $obj_service = $this->object_service; - - $lng->loadLanguageModule("wiki"); - $ilTabs->activateTab("settings"); - - require_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form_gui = new ilPropertyFormGUI(); - - // Title - $tit = new ilTextInputGUI($lng->txt("title"), "title"); - $tit->setRequired(true); - $this->form_gui->addItem($tit); - - // Short Title - // The problem with the short title is, that it is per object - // and can't be a substitute for a ref id in the permanent link -/* - $stit = new ilRegExpInputGUI($lng->txt("wiki_short_title"), "shorttitle"); - $stit->setPattern("/^[^0-9][^ _\&]+$/"); - $stit->setRequired(false); - $stit->setNoMatchMessage($lng->txt("wiki_msg_short_name_regexp")." & _"); - $stit->setSize(20); - $stit->setMaxLength(20); - $stit->setInfo($lng->txt("wiki_short_title_desc2")); - $this->form_gui->addItem($stit); -*/ - - // Description - $des = new ilTextAreaInputGUI($lng->txt("description"), "description"); - $this->form_gui->addItem($des); - - // Introduction - $intro = new ilTextAreaInputGUI($lng->txt("wiki_introduction"), "intro"); - $intro->setCols(40); - $intro->setRows(4); - $this->form_gui->addItem($intro); - - // Start Page - if ($a_mode == "edit") - { - $pages = ilWikiPage::getAllWikiPages($this->object->getId()); - foreach ($pages as $p) - { - $options[$p["id"]] = ilUtil::shortenText($p["title"], 60, true); - } - $si = new ilSelectInputGUI($lng->txt("wiki_start_page"), "startpage_id"); - $si->setOptions($options); - $this->form_gui->addItem($si); - } - else - { - $sp = new ilTextInputGUI($lng->txt("wiki_start_page"), "startpage"); - if ($a_mode == "edit") - { - $sp->setInfo($lng->txt("wiki_start_page_info")); - } - $sp->setMaxLength(200); - $sp->setRequired(true); - $this->form_gui->addItem($sp); - } - - // Online - $online = new ilCheckboxInputGUI($lng->txt("online"), "online"); - $this->form_gui->addItem($online); - - - // rating - - $lng->loadLanguageModule('rating'); - $rate = new ilCheckboxInputGUI($lng->txt('rating_activate_rating'), 'rating_overall'); - $rate->setInfo($lng->txt('rating_activate_rating_info')); - $this->form_gui->addItem($rate); - - $rating = new ilCheckboxInputGUI($lng->txt("wiki_activate_rating"), "rating"); - $this->form_gui->addItem($rating); - - /* always active - $side = new ilCheckboxInputGUI($lng->txt("wiki_activate_sideblock_rating"), "rating_side"); - $rating->addSubItem($side); - */ - - $new = new ilCheckboxInputGUI($lng->txt("wiki_activate_new_page_rating"), "rating_new"); - $rating->addSubItem($new); - - $extended = new ilCheckboxInputGUI($lng->txt("wiki_activate_extended_rating"), "rating_ext"); - $rating->addSubItem($extended); - - - // public comments - if (!$ilSetting->get("disable_comments")) - { - $comments = new ilCheckboxInputGUI($lng->txt("wiki_public_comments"), "public_notes"); - $this->form_gui->addItem($comments); - } - - // important pages -// $imp_pages = new ilCheckboxInputGUI($lng->txt("wiki_important_pages"), "imp_pages"); -// $this->form_gui->addItem($imp_pages); - - // page toc - $page_toc = new ilCheckboxInputGUI($lng->txt("wiki_page_toc"), "page_toc"); - $page_toc->setInfo($lng->txt("wiki_page_toc_info")); - $this->form_gui->addItem($page_toc); - - if($a_mode == "edit") - { - // advanced metadata auto-linking - include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecord.php'); - if(count(ilAdvancedMDRecord::_getSelectedRecordsByObject("wiki", $this->object->getRefId(), "wpg")) > 0) - { - $link_md = new ilCheckboxInputGUI($lng->txt("wiki_link_md_values"), "link_md_values"); - $link_md->setInfo($lng->txt("wiki_link_md_values_info")); - $this->form_gui->addItem($link_md); - } - - - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($this->lng->txt('obj_presentation')); - $this->form_gui->addItem($section); - - // tile image - $obj_service->commonSettings()->legacyForm($this->form_gui, $this->object)->addTileImage(); - - - // additional features - $feat = new ilFormSectionHeaderGUI(); - $feat->setTitle($this->lng->txt('obj_features')); - $this->form_gui->addItem($feat); - - include_once './Services/Container/classes/class.ilContainer.php'; - include_once './Services/Object/classes/class.ilObjectServiceSettingsGUI.php'; - ilObjectServiceSettingsGUI::initServiceSettingsForm( - $this->object->getId(), - $this->form_gui, - array( - ilObjectServiceSettingsGUI::CUSTOM_METADATA - ) - ); - } - - // :TODO: sorting - - // Form action and save button - $this->form_gui->setTitleIcon(ilUtil::getImagePath("icon_wiki.svg")); - if ($a_mode != "create") - { - $this->form_gui->setTitle($lng->txt("wiki_settings")); - $this->form_gui->addCommandButton("saveSettings", $lng->txt("save")); - } - else - { - $this->form_gui->setTitle($lng->txt("wiki_new")); - $this->form_gui->addCommandButton("save", $lng->txt("wiki_add")); - $this->form_gui->addCommandButton("cancel", $lng->txt("cancel")); - } - - // set values - if ($a_mode == "create") - { - $ilCtrl->setParameter($this, "new_type", "wiki"); - } - - $this->form_gui->setFormAction($ilCtrl->getFormAction($this, "saveSettings")); - } - - function getSettingsFormValues($a_mode = "edit") - { - $lng = $this->lng; - $ilUser = $this->user; - - // set values - if ($a_mode == "create") - { - //$values["startpage"] = $lng->txt("wiki_main_page"); - $values["rating_new"] = true; - - $values["rating_overall"] = ilObject::hasAutoRating("wiki", $_GET["ref_id"]); - - $this->form_gui->setValuesByArray($values); - } - else - { - $values["online"] = $this->object->getOnline(); - $values["title"] = $this->object->getTitle(); - //$values["startpage"] = $this->object->getStartPage(); - $values["startpage_id"] = ilWikiPage::_getPageIdForWikiTitle($this->object->getId(), $this->object->getStartPage()); - $values["shorttitle"] = $this->object->getShortTitle(); - $values["description"] = $this->object->getLongDescription(); - $values["rating_overall"] = $this->object->getRatingOverall(); - $values["rating"] = $this->object->getRating(); - // $values["rating_side"] = $this->object->getRatingAsBlock(); - $values["rating_new"] = $this->object->getRatingForNewPages(); - $values["rating_ext"] = $this->object->getRatingCategories(); - $values["public_notes"] = $this->object->getPublicNotes(); - $values["intro"] = $this->object->getIntroduction(); -// $values["imp_pages"] = $this->object->getImportantPages(); - $values["page_toc"] = $this->object->getPageToc(); - $values["link_md_values"] = $this->object->getLinkMetadataValues(); - - // only set given values (because of adv. metadata) - $this->form_gui->setValuesByArray($values, true); - } - } - - - /** - * Save Settings - */ - function saveSettingsObject() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilUser = $this->user; - $ilSetting = $this->settings; - $obj_service = $this->object_service; - - $this->checkPermission("write"); - - $this->initSettingsForm(); - - if ($this->form_gui->checkInput()) - { - if (!ilObjWiki::checkShortTitleAvailability($this->form_gui->getInput("shorttitle")) && - $this->form_gui->getInput("shorttitle") != $this->object->getShortTitle()) - { - $short_item = $this->form_gui->getItemByPostVar("shorttitle"); - $short_item->setAlert($lng->txt("wiki_short_title_already_in_use")); - } - else - { - $this->object->setTitle($this->form_gui->getInput("title")); - $this->object->setDescription($this->form_gui->getInput("description")); - $this->object->setOnline($this->form_gui->getInput("online")); - $this->object->setStartPage(ilWikiPage::lookupTitle($this->form_gui->getInput("startpage_id"))); - $this->object->setShortTitle($this->form_gui->getInput("shorttitle")); - $this->object->setRatingOverall($this->form_gui->getInput("rating_overall")); - $this->object->setRating($this->form_gui->getInput("rating")); - // $this->object->setRatingAsBlock($this->form_gui->getInput("rating_side")); - $this->object->setRatingForNewPages($this->form_gui->getInput("rating_new")); - $this->object->setRatingCategories($this->form_gui->getInput("rating_ext")); - - if (!$ilSetting->get("disable_comments")) - { - $this->object->setPublicNotes($this->form_gui->getInput("public_notes")); - } - $this->object->setIntroduction($this->form_gui->getInput("intro")); -// $this->object->setImportantPages($this->form_gui->getInput("imp_pages")); - $this->object->setPageToc($this->form_gui->getInput("page_toc")); - $this->object->setLinkMetadataValues($this->form_gui->getInput("link_md_values")); - $this->object->update(); - - // tile image - $obj_service->commonSettings()->legacyForm($this->form_gui, $this->object)->saveTileImage(); - - - include_once './Services/Object/classes/class.ilObjectServiceSettingsGUI.php'; - ilObjectServiceSettingsGUI::updateServiceSettingsForm( - $this->object->getId(), - $this->form_gui, - array( - ilObjectServiceSettingsGUI::CUSTOM_METADATA - ) - ); - - // Update ecs export settings - include_once 'Modules/Wiki/classes/class.ilECSWikiSettings.php'; - $ecs = new ilECSWikiSettings($this->object); - if($ecs->handleSettingsUpdate()) - { - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"),true); - $ilCtrl->redirect($this, "editSettings"); - } - } - } - - $this->form_gui->setValuesByPost(); - $this->tpl->setContent($this->form_gui->getHTML()); - } - - /** - * List all contributors - */ - function listContributorsObject() - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - $this->checkPermission("write"); - $ilTabs->activateTab("wiki_contributors"); - - include_once("./Modules/Wiki/classes/class.ilWikiContributorsTableGUI.php"); - - $table_gui = new ilWikiContributorsTableGUI($this, "listContributors", - $this->object->getId()); - - $tpl->setContent($table_gui->getHTML()); - - $this->setSideBlock(); - } - - /** - * Save grading - */ - function saveGradingObject() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->checkPermission("write"); - - $users = (is_array($_POST["user_id"]) - ? $_POST["user_id"] - : array()); - - include_once("./Modules/Wiki/classes/class.ilWikiContributor.php"); - include_once("./Services/Tracking/classes/class.ilLPMarks.php"); - $saved = false; - foreach($users as $user_id) - { - if ($user_id != "") - { - $marks_obj = new ilLPMarks($this->object->getId(),$user_id); - $new_mark = ilUtil::stripSlashes($_POST['mark'][$user_id]); - $new_comment = ilUtil::stripSlashes($_POST['lcomment'][$user_id]); - $new_status = ilUtil::stripSlashes($_POST["status"][$user_id]); - - if ($marks_obj->getMark() != $new_mark || - $marks_obj->getComment() != $new_comment || - ilWikiContributor::_lookupStatus($this->object->getId(), $user_id) != $new_status) - { - ilWikiContributor::_writeStatus($this->object->getId(), $user_id, $new_status); - $marks_obj->setMark($new_mark); - $marks_obj->setComment($new_comment); - $marks_obj->update(); - $saved = true; - } - } - } - if ($saved) - { - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - } - - $ilCtrl->redirect($this, "listContributors"); - } - - // add wiki to locator - function addLocatorItems() - { - $ilLocator = $this->locator; - - if (is_object($this->object)) - { - $ilLocator->addItem($this->object->getTitle(), - $this->getGotoLink($this->object->getRefId()), "", $_GET["ref_id"]); - } - } - - public static function _goto($a_target) - { - global $DIC; - - $ilAccess = $DIC->access(); - $ilErr = $DIC["ilErr"]; - $lng = $DIC->language(); - $ilNavigationHistory = $DIC["ilNavigationHistory"]; - - $i = strpos($a_target, "_"); - if ($i > 0) - { - $a_page = substr($a_target, $i+1); - $a_target = substr($a_target, 0, $i); - } - - if ($a_target == "wpage") - { - $a_page_arr = explode("_", $a_page); - $wpg_id = (int) $a_page_arr[0]; - $ref_id = (int) $a_page_arr[1]; - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $w_id = ilWikiPage::lookupWikiId($wpg_id); - if ($ref_id > 0) - { - $refs = array($ref_id); - } - else - { - $refs = ilObject::_getAllReferences($w_id); - } - foreach ($refs as $r) - { - if ($ilAccess->checkAccess("read", "", $r)) - { - $a_target = $r; - $a_page = ilWikiPage::lookupTitle($wpg_id); - } - } - } - - if ($ilAccess->checkAccess("read", "", $a_target)) - { - $_GET["cmd"] = "viewPage"; - $_GET["ref_id"] = $a_target; - $_GET["page"] = $a_page; - $_GET["baseClass"] = "ilwikihandlergui"; - $_GET["cmdClass"] = "ilobjwikigui"; -/* if ($a_page != "") - { - $add = "&page=".rawurlencode($_GET["page"]); - $ilNavigationHistory->addItem($_GET["ref_id"], - "./goto.php?target=wiki_".$_GET["ref_id"].$add, "wiki"); - }*/ - include("ilias.php"); - exit; - } - else if ($ilAccess->checkAccess("visible", "", $a_target)) - { - ilObjectGUI::_gotoRepositoryNode($a_target, "infoScreen"); - } - else if ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) - { - ilUtil::sendFailure(sprintf($lng->txt("msg_no_perm_read_item"), - ilObject::_lookupTitle(ilObject::_lookupObjId($a_target))), true); - ilObjectGUI::_gotoRepositoryRoot(); - } - - $ilErr->raiseError($lng->txt("msg_no_perm_read"), $ilErr->FATAL); - } - - /** - * Get goto link - */ - static function getGotoLink($a_ref_id, $a_page = "") - { - if ($a_page == "") - { - $a_page = ilObjWiki::_lookupStartPage(ilObject::_lookupObjId($a_ref_id)); - } - - $goto = "goto.php?target=wiki_".$a_ref_id."_". - ilWikiUtil::makeUrlTitle($a_page); - - return $goto; - } - - /** - * view wiki page - */ - function viewPageObject() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - $ilAccess = $this->access; - - $this->checkPermission("read"); - - $ilTabs->clearTargets(); - $tpl->setHeaderActionMenu(null); - - $page = ($_GET["page"] != "") - ? $_GET["page"] - : $this->object->getStartPage(); - $_GET["page"] = $page; - - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - if (!ilWikiPage::exists($this->object->getId(), $page)) - { - $page = $this->object->getStartPage(); - } - - if (!ilWikiPage::exists($this->object->getId(), $page)) - { - ilUtil::sendInfo($lng->txt("wiki_no_start_page"), true); - $ilCtrl->redirect($this, "infoScreen"); - return; - } - - // page exists, show it ! - $ilCtrl->setParameter($this, "page", ilWikiUtil::makeUrlTitle($page)); - - include_once("./Modules/Wiki/classes/class.ilWikiPageGUI.php"); - $wpage_gui = ilWikiPageGUI::getGUIForTitle($this->object->getId(), - ilWikiUtil::makeDbTitle($page), 0, $this->object->getRefId()); - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $wpage_gui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId( - $this->object->getStyleSheetId(), "wiki")); - - $this->setContentStyleSheet(); - //$wpage_gui->setOutputMode(IL_PAGE_PREVIEW); - - //$wpage_gui->setSideBlock(); - $ilCtrl->setCmdClass("ilwikipagegui"); - $ilCtrl->setCmd("preview"); - if (!$ilAccess->checkAccess("write", "", $this->object->getRefId()) && - (!$ilAccess->checkAccess("edit_content", "", $this->object->getRefId()) || - $wpage_gui->getPageObject()->getBlocked() - )) - { - $wpage_gui->setEnableEditing(false); - } - - // alter title and description - //$tpl->setTitle($wpage_gui->getPageObject()->getTitle()); - //$tpl->setDescription($this->object->getTitle()); - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - $wpage_gui->activateMetaDataEditor($this->object, "wpg", $wpage_gui->getId()); - } - - - $html = $ilCtrl->forwardCommand($wpage_gui); - //$this->addPageTabs(); - - $tpl->setContent($html); - } - - /** - * All pages of wiki - */ - function allPagesObject() - { - $tpl = $this->tpl; - - $this->checkPermission("read"); - - include_once("./Modules/Wiki/classes/class.ilWikiPagesTableGUI.php"); - - $this->addPagesSubTabs(); - - $table_gui = new ilWikiPagesTableGUI($this, "allPages", - $this->object->getId(), IL_WIKI_ALL_PAGES); - - $this->setSideBlock(); - $tpl->setContent($table_gui->getHTML()); - } - - /** - * Popular pages - */ - function popularPagesObject() - { - $tpl = $this->tpl; - - $this->checkPermission("read"); - - include_once("./Modules/Wiki/classes/class.ilWikiPagesTableGUI.php"); - - $this->addPagesSubTabs(); - - $table_gui = new ilWikiPagesTableGUI($this, "popularPages", - $this->object->getId(), IL_WIKI_POPULAR_PAGES); - - $this->setSideBlock(); - $tpl->setContent($table_gui->getHTML()); - } - - /** - * Orphaned pages - */ - function orphanedPagesObject() - { - $tpl = $this->tpl; - - $this->checkPermission("read"); - - include_once("./Modules/Wiki/classes/class.ilWikiPagesTableGUI.php"); - - $this->addPagesSubTabs(); - - $table_gui = new ilWikiPagesTableGUI($this, "orphanedPages", - $this->object->getId(), IL_WIKI_ORPHANED_PAGES); - - $this->setSideBlock(); - $tpl->setContent($table_gui->getHTML()); - } - - /** - * Go to specific page - * - * @param string $a_page page title - */ - function gotoPageObject($a_page = "") - { - $ilCtrl = $this->ctrl; - - if ($a_page == "") - { - $a_page = $_GET["page"]; - } - - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - if (ilWikiPage::_wikiPageExists($this->object->getId(), - ilWikiUtil::makeDbTitle($a_page))) - { - // to do: get rid of this redirect - ilUtil::redirect(ilObjWikiGUI::getGotoLink($this->object->getRefId(), $a_page)); - } - else - { - if (!$this->object->getTemplateSelectionOnCreation()) - { - // check length - include_once("./Services/Utilities/classes/class.ilStr.php"); - if (ilStr::strLen(ilWikiUtil::makeDbTitle($a_page)) > 200) - { - ilUtil::sendFailure($this->lng->txt("wiki_page_title_too_long")." (".$a_page.")", true); - $ilCtrl->setParameterByClass("ilwikipagegui", "page", ilWikiUtil::makeUrlTitle($_GET["from_page"])); - $ilCtrl->redirectByClass("ilwikipagegui", "preview"); - } - $this->object->createWikiPage($a_page); - - // redirect to newly created page - $ilCtrl->setParameterByClass("ilwikipagegui", "page", ilWikiUtil::makeUrlTitle(($a_page))); - $ilCtrl->redirectByClass("ilwikipagegui", "edit"); - } - else - { - $ilCtrl->setParameter($this, "page", ilWikiUtil::makeUrlTitle($_GET["page"])); - $ilCtrl->setParameter($this, "from_page", ilWikiUtil::makeUrlTitle($_GET["from_page"])); - $ilCtrl->redirect($this, "showTemplateSelection"); - } - } - } - - /** - * Go to random page - * - * @param string $a_page page title - */ - function randomPageObject() - { - $this->checkPermission("read"); - - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $page = ilWikiPage::getRandomPage($this->object->getId()); - $this->gotoPageObject($page); - } - - /** - * Recent Changes - */ - function recentChangesObject() - { - $tpl = $this->tpl; - - $this->checkPermission("read"); - - include_once("./Modules/Wiki/classes/class.ilWikiRecentChangesTableGUI.php"); - - $this->addPagesSubTabs(); - - $table_gui = new ilWikiRecentChangesTableGUI($this, "recentChanges", - $this->object->getId()); - - $this->setSideBlock(); - $tpl->setContent($table_gui->getHTML()); - } - - /** - * Side column - */ - function setSideBlock($a_wpg_id = 0) - { - ilObjWikiGUI::renderSideBlock($a_wpg_id, $this->object->getRefId()); - } - - - /** - * Side column - */ - static function renderSideBlock($a_wpg_id, $a_wiki_ref_id, $a_wp = null) - { - global $DIC; - - $tpl = $DIC["tpl"]; - $lng = $DIC->language(); - $ilAccess = $DIC->access(); - $ilCtrl = $DIC->ctrl(); - - $tpl->addJavaScript("./Modules/Wiki/js/WikiPres.js"); - - // setting asynch to false fixes #0019457, since otherwise ilBlockGUI would act on asynch and output html when side blocks - // being processed during the export. This is a flaw in ilCtrl and/or ilBlockGUI. - $tpl->addOnLoadCode("il.Wiki.Pres.init('".$ilCtrl->getLinkTargetByClass("ilobjwikigui", "", "", false, false)."');"); - - if ($a_wpg_id > 0 && !$a_wp) - { - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $a_wp = ilWikiPage($a_wpg_id); - } - - // search block - include_once './Services/Search/classes/class.ilRepositoryObjectSearchGUI.php'; - $rcontent = ilRepositoryObjectSearchGUI::getSearchBlockHTML($lng->txt('wiki_search')); - - #include_once("./Modules/Wiki/classes/class.ilWikiSearchBlockGUI.php"); - #$wiki_search_block = new ilWikiSearchBlockGUI(); - #$rcontent = $wiki_search_block->getHTML(); - - // quick navigation - if ($a_wpg_id > 0) - { -// include_once("./Modules/Wiki/classes/class.ilWikiSideBlockGUI.php"); -// $wiki_side_block = new ilWikiSideBlockGUI(); -// $wiki_side_block->setPageObject($a_wp); -// $rcontent.= $wiki_side_block->getHTML(); - - // rating - $wiki_id =ilObject::_lookupObjId($a_wiki_ref_id); - if(ilObjWiki::_lookupRating($wiki_id) && - // ilObjWiki::_lookupRatingAsBlock($wiki_id) && - $a_wp->getRating()) - { - include_once("./Services/Rating/classes/class.ilRatingGUI.php"); - $rgui = new ilRatingGUI(); - $rgui->setObject($wiki_id, "wiki", $a_wpg_id, "wpg"); - $rgui->enableCategories(ilObjWiki::_lookupRatingCategories($wiki_id)); - $rgui->setYourRatingText("#"); - $rcontent .= $rgui->getBlockHTML($lng->txt("wiki_rate_page")); - } - - // advanced metadata - if(!ilWikiPage::lookupAdvancedMetadataHidden($a_wpg_id)) - { - $cmd = null; - if($ilAccess->checkAccess("write", "", $a_wiki_ref_id) || - $ilAccess->checkAccess("edit_page_meta", "", $a_wiki_ref_id)) - { - $cmd = array( - "edit" => $ilCtrl->getLinkTargetByClass("ilwikipagegui", "editAdvancedMetaData"), - "hide" => $ilCtrl->getLinkTargetByClass("ilwikipagegui", "hideAdvancedMetaData") - ); - } - include_once("./Services/Object/classes/class.ilObjectMetaDataGUI.php"); - $wiki = new ilObjWiki($a_wiki_ref_id); - $callback = $wiki->getLinkMetadataValues() - ? array($wiki, "decorateAdvMDValue") - : null; - $mdgui = new ilObjectMetaDataGUI($wiki, "wpg", $a_wpg_id); - $rcontent .= $mdgui->getBlockHTML($cmd, $callback); // #17291 - } - } - - // important pages -// if (ilObjWiki::_lookupImportantPages(ilObject::_lookupObjId($a_wiki_ref_id))) -// { - include_once("./Modules/Wiki/classes/class.ilWikiImportantPagesBlockGUI.php"); - $imp_pages_block = new ilWikiImportantPagesBlockGUI(); - $rcontent.= $imp_pages_block->getHTML(); -// } - - // wiki functions block - if ($a_wpg_id > 0) - { - include_once("./Modules/Wiki/classes/class.ilWikiFunctionsBlockGUI.php"); - $wiki_functions_block = new ilWikiFunctionsBlockGUI(); - $wiki_functions_block->setPageObject($a_wp); - $rcontent .= $wiki_functions_block->getHTML(); - } - - $tpl->setRightContent($rcontent); - } - - /** - * Latest pages - */ - function newPagesObject() - { - $tpl = $this->tpl; - - $this->checkPermission("read"); - - include_once("./Modules/Wiki/classes/class.ilWikiPagesTableGUI.php"); - - $this->addPagesSubTabs(); - - $table_gui = new ilWikiPagesTableGUI($this, "newPages", - $this->object->getId(), IL_WIKI_NEW_PAGES); - - $this->setSideBlock(); - $tpl->setContent($table_gui->getHTML()); - } - - protected function getPrintPageIds() - { - // multiple ordered page ids - if(is_array($_POST["wordr"])) - { - asort($_POST["wordr"]); - $page_ids = array_keys($_POST["wordr"]); - } - // single page - else if((int)$_GET["wpg_id"]) - { - $page_ids = array((int)$_GET["wpg_id"]); - } - - return $page_ids; - } - - public function printViewObject($a_pdf_export = false) - { - $tpl = $this->tpl; - - $page_ids = $this->getPrintPageIds(); - if(!$page_ids) - { - $this->ctrl->redirect($this, ""); - } - - $tpl = new ilTemplate("tpl.main.html", true, true); - $tpl->setVariable("LOCATION_STYLESHEET", ilObjStyleSheet::getContentPrintStyle()); - $this->setContentStyleSheet($tpl); - - // syntax style - $tpl->setCurrentBlock("SyntaxStyle"); - $tpl->setVariable("LOCATION_SYNTAX_STYLESHEET", - ilObjStyleSheet::getSyntaxStylePath()); - $tpl->parseCurrentBlock(); - - - // determine target frames for internal links - - include_once("./Modules/Wiki/classes/class.ilWikiPageGUI.php"); - - $page_content = ""; - - foreach ($page_ids as $p_id) - { - $page_gui = new ilWikiPageGUI($p_id); - $page_gui->setWiki($this->object); - $page_gui->setOutputMode("print"); - $page_content.= $page_gui->showPage(); - - if($a_pdf_export) - { - $page_content .= '

'; - } - } - - $page_content = '
'.$page_content.'
'; - - if(!$a_pdf_export) - { - $page_content .= ''; - } - - $tpl->setVariable("CONTENT", $page_content); - - if(!$a_pdf_export) - { - $tpl->show(false); - exit; - } - else - { - return $tpl->get("DEFAULT", false, false, false, true, false, false); - } - } - - public function pdfExportObject() - { - - // prepare generation before contents are processed (for mathjax) - ilPDFGeneratorUtils::prepareGenerationRequest("Wiki", "ContentExport"); - - $html = $this->printViewObject(true); - - // :TODO: fixing css dummy parameters - $html = preg_replace("/\?dummy\=[0-9]+/", "", $html); - $html = preg_replace("/\?vers\=[0-9A-Za-z\-]+/", "", $html); - - if (false) - { - include_once "Services/PDFGeneration/classes/class.ilPDFGeneration.php"; - include_once "Services/PDFGeneration/classes/class.ilPDFGenerationJob.php"; - - $job = new ilPDFGenerationJob(); - $job->setAutoPageBreak(true) - ->setMarginLeft("10") - ->setMarginRight("10") - ->setMarginTop("10") - ->setMarginBottom("10") - ->setOutputMode("D")// download - ->setFilename("wiki.pdf")// :TODO: - ->setCreator("ILIAS Wiki")// :TODO: - ->setImageScale(1.25)// complete content scaling ?! - ->addPage($html); - - ilPDFGeneration::doJob($job); - } - else - { - $html = preg_replace("/src=\"\\.\\//ims", "src=\"" . ILIAS_HTTP_PATH . "/", $html); - $html = preg_replace("/href=\"\\.\\//ims", "href=\"" . ILIAS_HTTP_PATH . "/", $html); - $pdf_factory = new ilHtmlToPdfTransformerFactory(); - $pdf_factory->deliverPDFFromHTMLString($html, "wiki.pdf", ilHtmlToPdfTransformerFactory::PDF_OUTPUT_DOWNLOAD, "Wiki", "ContentExport"); - } - - } - - /** - * Search - */ - function performSearchObject() - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->checkPermission("read"); - - include_once("./Modules/Wiki/classes/class.ilWikiSearchResultsTableGUI.php"); - - $ilTabs->setTabActive("wiki_search_results"); - - if (trim($_POST["search_term"]) == "") - { - ilUtil::sendFailure($lng->txt("wiki_please_enter_search_term"), true); - $ilCtrl->redirectByClass("ilwikipagegui", "preview"); - } - - $search_results = ilObjWiki::_performSearch($this->object->getId(), - ilUtil::stripSlashes($_POST["search_term"])); - $table_gui = new ilWikiSearchResultsTableGUI($this, "performSearch", - $this->object->getId(), $search_results, $_POST["search_term"]); - - $this->setSideBlock(); - $tpl->setContent($table_gui->getHTML()); - } - - /** - * Set content style sheet - */ - 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(); - - } - - - /** - * Edit style properties - */ - function editStylePropertiesObject() - { - $ilTabs = $this->tabs; - $tpl = $this->tpl; - - $this->checkPermission("write"); - - $this->initStylePropertiesForm(); - $tpl->setContent($this->form->getHTML()); - - $ilTabs->activateTab("settings"); - $this->setSettingsSubTabs("style"); - - $this->setSideBlock(); - } - - /** - * Init style properties form - */ - function initStylePropertiesForm() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilTabs = $this->tabs; - $ilSetting = $this->settings; - - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $lng->loadLanguageModule("style"); - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - $fixed_style = $ilSetting->get("fixed_content_style_id"); - $style_id = $this->object->getStyleSheetId(); - - if ($fixed_style > 0) - { - $st = new ilNonEditableValueGUI($lng->txt("style_current_style")); - $st->setValue(ilObject::_lookupTitle($fixed_style)." (". - $this->lng->txt("global_fixed").")"); - $this->form->addItem($st); - } - else - { - $st_styles = ilObjStyleSheet::_getStandardStyles(true, false, - $_GET["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($lng->txt("style_current_style")); - $st->setValue(ilObject::_lookupTitle($style_id)); - $this->form->addItem($st); - -//$this->ctrl->getLinkTargetByClass("ilObjStyleSheetGUI", "edit")); - - // delete command - $this->form->addCommandButton("editStyle", - $lng->txt("style_edit_style")); - $this->form->addCommandButton("deleteStyle", - $lng->txt("style_delete_style")); -//$this->ctrl->getLinkTargetByClass("ilObjStyleSheetGUI", "delete")); - } - } - - if ($style_id <= 0 || ilObjStyleSheet::_lookupStandard($style_id)) - { - $style_sel = ilUtil::formSelect ($style_id, "style_id", - $st_styles, false, true); - $style_sel = new ilSelectInputGUI($lng->txt("style_current_style"), "style_id"); - $style_sel->setOptions($st_styles); - $style_sel->setValue($style_id); - $this->form->addItem($style_sel); -//$this->ctrl->getLinkTargetByClass("ilObjStyleSheetGUI", "create")); - $this->form->addCommandButton("saveStyleSettings", - $lng->txt("save")); - $this->form->addCommandButton("createStyle", - $lng->txt("sty_create_ind_style")); - } - } - $this->form->setTitle($lng->txt("wiki_style")); - $this->form->setFormAction($ilCtrl->getFormAction($this)); - } - - /** - * Create Style - */ - function createStyleObject() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirectByClass("ilobjstylesheetgui", "create"); - } - - /** - * Edit Style - */ - function editStyleObject() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirectByClass("ilobjstylesheetgui", "edit"); - } - - /** - * Delete Style - */ - function deleteStyleObject() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirectByClass("ilobjstylesheetgui", "delete"); - } - - /** - * Save style settings - */ - function saveStyleSettingsObject() - { - $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(ilUtil::stripSlashes($_POST["style_id"])); - $this->object->update(); - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - } - $this->ctrl->redirect($this, "editStyleProperties"); - } - - // - // Important pages - // - - /** - * List important pages - */ - function editImportantPagesObject() - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $ilTabs = $this->tabs; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->checkPermission("edit_wiki_navigation"); - - ilUtil::sendInfo($lng->txt("wiki_navigation_info")); - - $ipages = ilObjWiki::_lookupImportantPagesList($this->object->getId()); - $ipages_ids = array(); - foreach ($ipages as $i) - { - $ipages_ids[] = $i["page_id"]; - } - - // list pages - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $pages = ilWikiPage::getAllWikiPages($this->object->getId()); - $options = array("" => $lng->txt("please_select")); - foreach ($pages as $p) - { - if (!in_array($p["id"], $ipages_ids)) - { - $options[$p["id"]] = ilUtil::shortenText($p["title"], 60, true); - } - } - if (count($options) > 0) - { - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $si = new ilSelectInputGUI($lng->txt("wiki_pages"), "imp_page_id"); - $si->setOptions($options); - $si->setInfo($lng->txt("")); - $ilToolbar->addInputItem($si); - $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); - $ilToolbar->addFormButton($lng->txt("add"), "addImportantPage"); - } - - - $ilTabs->activateTab("settings"); - $this->setSettingsSubTabs("imp_pages"); - - include_once("./Modules/Wiki/classes/class.ilImportantPagesTableGUI.php"); - $imp_table = new ilImportantPagesTableGUI($this, "editImportantPages"); - - $tpl->setContent($imp_table->getHTML()); - } - - /** - * Add important pages - * - * @param - * @return - */ - function addImportantPageObject() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->checkPermission("edit_wiki_navigation"); - - if ($_POST["imp_page_id"] > 0) - { - $this->object->addImportantPage((int) $_POST["imp_page_id"]); - ilUtil::sendSuccess($lng->txt("wiki_imp_page_added"), true); - } - $ilCtrl->redirect($this, "editImportantPages"); - } - - /** - * Confirm important pages deletion - */ - function confirmRemoveImportantPagesObject() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - if (!is_array($_POST["imp_page_id"]) || count($_POST["imp_page_id"]) == 0) - { - ilUtil::sendInfo($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "editImportantPages"); - } - else - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("wiki_sure_remove_imp_pages")); - $cgui->setCancel($lng->txt("cancel"), "editImportantPages"); - $cgui->setConfirm($lng->txt("remove"), "removeImportantPages"); - - foreach ($_POST["imp_page_id"] as $i) - { - $cgui->addItem("imp_page_id[]", $i, ilWikiPage::lookupTitle((int) $i)); - } - - $tpl->setContent($cgui->getHTML()); - } - } - - /** - * Remove important pages - * - * @param - * @return - */ - function removeImportantPagesObject() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->checkPermission("edit_wiki_navigation"); - - if (is_array($_POST["imp_page_id"])) - { - foreach ($_POST["imp_page_id"] as $i) - { - $this->object->removeImportantPage((int) $i); - } - } - ilUtil::sendSuccess($lng->txt("wiki_removed_imp_pages"), true); - $ilCtrl->redirect($this, "editImportantPages"); - } - - /** - * Save important pages ordering and indentation - */ - function saveOrderingAndIndentObject() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->checkPermission("edit_wiki_navigation"); - - $this->object->saveOrderingAndIndentation($_POST["ord"], $_POST["indent"]); - ilUtil::sendSuccess($lng->txt("wiki_ordering_and_indent_saved"), true); - $ilCtrl->redirect($this, "editImportantPages"); - } - - /** - * Confirm important pages deletion - */ - function setAsStartPageObject() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->checkPermission("edit_wiki_navigation"); - - if (!is_array($_POST["imp_page_id"]) || count($_POST["imp_page_id"]) != 1) - { - ilUtil::sendInfo($lng->txt("wiki_select_one_item"), true); - } - else - { - $this->object->removeImportantPage((int) $_POST["imp_page_id"][0]); - $this->object->setStartPage(ilWikiPage::lookupTitle((int) $_POST["imp_page_id"][0])); - $this->object->update(); - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"),true); - } - $ilCtrl->redirect($this, "editImportantPages"); - } - - - /** - * Create html package - */ - function exportHTML() - { - require_once("./Modules/Wiki/classes/class.ilWikiHTMLExport.php"); - $cont_exp = new ilWikiHTMLExport($this->object); - $cont_exp->buildExportFile(); - } - - /** - * Get title for wiki page (used in ilNotesGUI) - * - * @param int $a_wiki_id - * @param int $a_page_id - * @return string - */ - static function lookupSubObjectTitle($a_wiki_id, $a_page_id) - { - include_once "Modules/Wiki/classes/class.ilWikiPage.php"; - $page = new ilWikiPage($a_page_id); - if($page->getWikiId() == $a_wiki_id) - { - return $page->getTitle(); - } - } - - /** - * Used for rating export - * - * @param int $a_id - * @param string $a_type - * @return string - */ - function getSubObjectTitle($a_id, $a_type) - { - include_once "Modules/Wiki/classes/class.ilWikiPage.php"; - return ilWikiPage::lookupTitle($a_id); - } - - /** - * Show template selection - */ - function showTemplateSelectionObject() - { - $lng = $this->lng; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - - - $ilCtrl->setParameterByClass("ilobjwikigui", "from_page", ilWikiUtil::makeUrlTitle($_GET["from_page"])); - $ilTabs->clearTargets(); - ilUtil::sendInfo($lng->txt("wiki_page_not_exist_select_templ")); - - $form = $this->initTemplateSelectionForm(); - $tpl->setContent($form->getHTML()); - } - - /** - * Init template selection form. - */ - public function initTemplateSelectionForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - - // page name - $hi = new ilHiddenInputGUI("page"); - $hi->setValue($_GET["page"]); - $form->addItem($hi); - - // page template - $radg = new ilRadioGroupInputGUI($lng->txt("wiki_page_template"), "page_templ"); - $radg->setRequired(true); - - if ($this->object->getEmptyPageTemplate()) - { - $op1 = new ilRadioOption($lng->txt("wiki_empty_page"), 0); - $radg->addOption($op1); - } - - include_once("./Modules/Wiki/classes/class.ilWikiPageTemplate.php"); - $wt = new ilWikiPageTemplate($this->object->getId()); - $ts = $wt->getAllInfo(ilWikiPageTemplate::TYPE_NEW_PAGES); - foreach ($ts as $t) - { - $op = new ilRadioOption($t["title"], $t["wpage_id"]); - $radg->addOption($op); - } - - $form->addItem($radg); - - // save and cancel commands - $form->addCommandButton("createPageUsingTemplate", $lng->txt("wiki_create_page")); - $form->addCommandButton("cancelCreationPageUsingTemplate", $lng->txt("cancel")); - - $form->setTitle($lng->txt("wiki_new_page").": ".$_GET["page"]); - $form->setFormAction($ilCtrl->getFormAction($this)); - - return $form; - } - - /** - * Save creation with template form - */ - public function createPageUsingTemplateObject() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $form = $this->initTemplateSelectionForm(); - if ($form->checkInput()) - { - $a_page = $_POST["page"]; - $this->object->createWikiPage($a_page, (int) $_POST["page_templ"]); - - // redirect to newly created page - $ilCtrl->setParameterByClass("ilwikipagegui", "page", ilWikiUtil::makeUrlTitle(($a_page))); - $ilCtrl->redirectByClass("ilwikipagegui", "edit"); - - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, ""); - } - else - { - $form->setValuesByPost(); - $tpl->setContent($form->getHtml()); - } - } - - /** - * Cancel page creation using a template - */ - function cancelCreationPageUsingTemplateObject() - { - $ilCtrl = $this->ctrl; - - // redirect to newly created page - $ilCtrl->setParameterByClass("ilwikipagegui", "page", ilWikiUtil::makeUrlTitle(($_GET["from_page"]))); - $ilCtrl->redirectByClass("ilwikipagegui", "preview"); - } - - /** - * Check permission - * - * @param string $a_perm - * @param string $a_cmd - * @param string $a_type - * @param int $a_ref_id - * @return bool - */ - protected function checkPermissionBool($a_perm, $a_cmd = "", $a_type = "", $a_ref_id = null) - { - if($a_perm == "create") - { - return parent::checkPermissionBool($a_perm, $a_cmd, $a_type, $a_ref_id); - } - else - { - if (!$a_ref_id) - { - $a_ref_id = $this->object->getRefId(); - } - include_once("./Modules/Wiki/classes/class.ilWikiPerm.php"); - return ilWikiPerm::check($a_perm, $a_ref_id, $a_cmd); - } - } - - - // - // User HTML Export - // - - /** - * Export html (as user) - */ - function initUserHTMLExportObject() - { - $this->log->debug("init"); - $this->checkPermission("wiki_html_export"); - $this->object->initUserHTMLExport(); - } - - /** - * Export html (as user) - */ - function startUserHTMLExportObject() - { - $this->log->debug("start"); - $this->checkPermission("wiki_html_export"); - $this->object->startUserHTMLExport(); - } - - /** - * Get user html export progress - */ - function getUserHTMLExportProgressObject() - { - $this->log->debug("get progress"); - $this->checkPermission("wiki_html_export"); - $p = $this->object->getUserHTMLExportProgress(); - - include_once("./Services/UIComponent/ProgressBar/classes/class.ilProgressBar.php"); - $pb = ilProgressBar::getInstance(); - $pb->setCurrent($p["progress"]); - - $r = new stdClass(); - $r->progressBar = $pb->render(); - $r->status = $p["status"]; - include_once("./Services/JSON/classes/class.ilJsonUtil.php"); - $this->log->debug("status: ".$r->status); - echo (ilJsonUtil::encode($r)); - exit; - } - - /** - * Download user html export file - */ - function downloadUserHTMLExportObject() - { - $this->log->debug("download"); - $this->checkPermission("wiki_html_export"); - $this->object->deliverUserHTMLExport(); - } - - + } + + $tpl->setVariable("CONTENT", $page_content); + + if (!$a_pdf_export) { + $tpl->show(false); + exit; + } else { + return $tpl->get("DEFAULT", false, false, false, true, false, false); + } + } + + public function pdfExportObject() + { + + // prepare generation before contents are processed (for mathjax) + ilPDFGeneratorUtils::prepareGenerationRequest("Wiki", "ContentExport"); + + $html = $this->printViewObject(true); + + // :TODO: fixing css dummy parameters + $html = preg_replace("/\?dummy\=[0-9]+/", "", $html); + $html = preg_replace("/\?vers\=[0-9A-Za-z\-]+/", "", $html); + + if (false) { + include_once "Services/PDFGeneration/classes/class.ilPDFGeneration.php"; + include_once "Services/PDFGeneration/classes/class.ilPDFGenerationJob.php"; + + $job = new ilPDFGenerationJob(); + $job->setAutoPageBreak(true) + ->setMarginLeft("10") + ->setMarginRight("10") + ->setMarginTop("10") + ->setMarginBottom("10") + ->setOutputMode("D")// download + ->setFilename("wiki.pdf")// :TODO: + ->setCreator("ILIAS Wiki")// :TODO: + ->setImageScale(1.25)// complete content scaling ?! + ->addPage($html); + + ilPDFGeneration::doJob($job); + } else { + $html = preg_replace("/src=\"\\.\\//ims", "src=\"" . ILIAS_HTTP_PATH . "/", $html); + $html = preg_replace("/href=\"\\.\\//ims", "href=\"" . ILIAS_HTTP_PATH . "/", $html); + $pdf_factory = new ilHtmlToPdfTransformerFactory(); + $pdf_factory->deliverPDFFromHTMLString($html, "wiki.pdf", ilHtmlToPdfTransformerFactory::PDF_OUTPUT_DOWNLOAD, "Wiki", "ContentExport"); + } + } + + /** + * Search + */ + public function performSearchObject() + { + $tpl = $this->tpl; + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->checkPermission("read"); + + include_once("./Modules/Wiki/classes/class.ilWikiSearchResultsTableGUI.php"); + + $ilTabs->setTabActive("wiki_search_results"); + + if (trim($_POST["search_term"]) == "") { + ilUtil::sendFailure($lng->txt("wiki_please_enter_search_term"), true); + $ilCtrl->redirectByClass("ilwikipagegui", "preview"); + } + + $search_results = ilObjWiki::_performSearch( + $this->object->getId(), + ilUtil::stripSlashes($_POST["search_term"]) + ); + $table_gui = new ilWikiSearchResultsTableGUI( + $this, + "performSearch", + $this->object->getId(), + $search_results, + $_POST["search_term"] + ); + + $this->setSideBlock(); + $tpl->setContent($table_gui->getHTML()); + } + + /** + * Set content style sheet + */ + 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(); + } + + + /** + * Edit style properties + */ + public function editStylePropertiesObject() + { + $ilTabs = $this->tabs; + $tpl = $this->tpl; + + $this->checkPermission("write"); + + $this->initStylePropertiesForm(); + $tpl->setContent($this->form->getHTML()); + + $ilTabs->activateTab("settings"); + $this->setSettingsSubTabs("style"); + + $this->setSideBlock(); + } + + /** + * Init style properties form + */ + public function initStylePropertiesForm() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilTabs = $this->tabs; + $ilSetting = $this->settings; + + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $lng->loadLanguageModule("style"); + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + $fixed_style = $ilSetting->get("fixed_content_style_id"); + $style_id = $this->object->getStyleSheetId(); + + if ($fixed_style > 0) { + $st = new ilNonEditableValueGUI($lng->txt("style_current_style")); + $st->setValue(ilObject::_lookupTitle($fixed_style) . " (" . + $this->lng->txt("global_fixed") . ")"); + $this->form->addItem($st); + } else { + $st_styles = ilObjStyleSheet::_getStandardStyles( + true, + false, + $_GET["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($lng->txt("style_current_style")); + $st->setValue(ilObject::_lookupTitle($style_id)); + $this->form->addItem($st); + + //$this->ctrl->getLinkTargetByClass("ilObjStyleSheetGUI", "edit")); + + // delete command + $this->form->addCommandButton( + "editStyle", + $lng->txt("style_edit_style") + ); + $this->form->addCommandButton( + "deleteStyle", + $lng->txt("style_delete_style") + ); + //$this->ctrl->getLinkTargetByClass("ilObjStyleSheetGUI", "delete")); + } + } + + if ($style_id <= 0 || ilObjStyleSheet::_lookupStandard($style_id)) { + $style_sel = ilUtil::formSelect( + $style_id, + "style_id", + $st_styles, + false, + true + ); + $style_sel = new ilSelectInputGUI($lng->txt("style_current_style"), "style_id"); + $style_sel->setOptions($st_styles); + $style_sel->setValue($style_id); + $this->form->addItem($style_sel); + //$this->ctrl->getLinkTargetByClass("ilObjStyleSheetGUI", "create")); + $this->form->addCommandButton( + "saveStyleSettings", + $lng->txt("save") + ); + $this->form->addCommandButton( + "createStyle", + $lng->txt("sty_create_ind_style") + ); + } + } + $this->form->setTitle($lng->txt("wiki_style")); + $this->form->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * Create Style + */ + public function createStyleObject() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirectByClass("ilobjstylesheetgui", "create"); + } + + /** + * Edit Style + */ + public function editStyleObject() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirectByClass("ilobjstylesheetgui", "edit"); + } + + /** + * Delete Style + */ + public function deleteStyleObject() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirectByClass("ilobjstylesheetgui", "delete"); + } + + /** + * Save style settings + */ + public function saveStyleSettingsObject() + { + $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(ilUtil::stripSlashes($_POST["style_id"])); + $this->object->update(); + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + } + $this->ctrl->redirect($this, "editStyleProperties"); + } + + // + // Important pages + // + + /** + * List important pages + */ + public function editImportantPagesObject() + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $ilTabs = $this->tabs; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $this->checkPermission("edit_wiki_navigation"); + + ilUtil::sendInfo($lng->txt("wiki_navigation_info")); + + $ipages = ilObjWiki::_lookupImportantPagesList($this->object->getId()); + $ipages_ids = array(); + foreach ($ipages as $i) { + $ipages_ids[] = $i["page_id"]; + } + + // list pages + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + $pages = ilWikiPage::getAllWikiPages($this->object->getId()); + $options = array("" => $lng->txt("please_select")); + foreach ($pages as $p) { + if (!in_array($p["id"], $ipages_ids)) { + $options[$p["id"]] = ilUtil::shortenText($p["title"], 60, true); + } + } + if (count($options) > 0) { + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $si = new ilSelectInputGUI($lng->txt("wiki_pages"), "imp_page_id"); + $si->setOptions($options); + $si->setInfo($lng->txt("")); + $ilToolbar->addInputItem($si); + $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); + $ilToolbar->addFormButton($lng->txt("add"), "addImportantPage"); + } + + + $ilTabs->activateTab("settings"); + $this->setSettingsSubTabs("imp_pages"); + + include_once("./Modules/Wiki/classes/class.ilImportantPagesTableGUI.php"); + $imp_table = new ilImportantPagesTableGUI($this, "editImportantPages"); + + $tpl->setContent($imp_table->getHTML()); + } + + /** + * Add important pages + * + * @param + * @return + */ + public function addImportantPageObject() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->checkPermission("edit_wiki_navigation"); + + if ($_POST["imp_page_id"] > 0) { + $this->object->addImportantPage((int) $_POST["imp_page_id"]); + ilUtil::sendSuccess($lng->txt("wiki_imp_page_added"), true); + } + $ilCtrl->redirect($this, "editImportantPages"); + } + + /** + * Confirm important pages deletion + */ + public function confirmRemoveImportantPagesObject() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + if (!is_array($_POST["imp_page_id"]) || count($_POST["imp_page_id"]) == 0) { + ilUtil::sendInfo($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "editImportantPages"); + } else { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("wiki_sure_remove_imp_pages")); + $cgui->setCancel($lng->txt("cancel"), "editImportantPages"); + $cgui->setConfirm($lng->txt("remove"), "removeImportantPages"); + + foreach ($_POST["imp_page_id"] as $i) { + $cgui->addItem("imp_page_id[]", $i, ilWikiPage::lookupTitle((int) $i)); + } + + $tpl->setContent($cgui->getHTML()); + } + } + + /** + * Remove important pages + * + * @param + * @return + */ + public function removeImportantPagesObject() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->checkPermission("edit_wiki_navigation"); + + if (is_array($_POST["imp_page_id"])) { + foreach ($_POST["imp_page_id"] as $i) { + $this->object->removeImportantPage((int) $i); + } + } + ilUtil::sendSuccess($lng->txt("wiki_removed_imp_pages"), true); + $ilCtrl->redirect($this, "editImportantPages"); + } + + /** + * Save important pages ordering and indentation + */ + public function saveOrderingAndIndentObject() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->checkPermission("edit_wiki_navigation"); + + $this->object->saveOrderingAndIndentation($_POST["ord"], $_POST["indent"]); + ilUtil::sendSuccess($lng->txt("wiki_ordering_and_indent_saved"), true); + $ilCtrl->redirect($this, "editImportantPages"); + } + + /** + * Confirm important pages deletion + */ + public function setAsStartPageObject() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->checkPermission("edit_wiki_navigation"); + + if (!is_array($_POST["imp_page_id"]) || count($_POST["imp_page_id"]) != 1) { + ilUtil::sendInfo($lng->txt("wiki_select_one_item"), true); + } else { + $this->object->removeImportantPage((int) $_POST["imp_page_id"][0]); + $this->object->setStartPage(ilWikiPage::lookupTitle((int) $_POST["imp_page_id"][0])); + $this->object->update(); + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + } + $ilCtrl->redirect($this, "editImportantPages"); + } + + + /** + * Create html package + */ + public function exportHTML() + { + require_once("./Modules/Wiki/classes/class.ilWikiHTMLExport.php"); + $cont_exp = new ilWikiHTMLExport($this->object); + $cont_exp->buildExportFile(); + } + + /** + * Get title for wiki page (used in ilNotesGUI) + * + * @param int $a_wiki_id + * @param int $a_page_id + * @return string + */ + public static function lookupSubObjectTitle($a_wiki_id, $a_page_id) + { + include_once "Modules/Wiki/classes/class.ilWikiPage.php"; + $page = new ilWikiPage($a_page_id); + if ($page->getWikiId() == $a_wiki_id) { + return $page->getTitle(); + } + } + + /** + * Used for rating export + * + * @param int $a_id + * @param string $a_type + * @return string + */ + public function getSubObjectTitle($a_id, $a_type) + { + include_once "Modules/Wiki/classes/class.ilWikiPage.php"; + return ilWikiPage::lookupTitle($a_id); + } + + /** + * Show template selection + */ + public function showTemplateSelectionObject() + { + $lng = $this->lng; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + + + $ilCtrl->setParameterByClass("ilobjwikigui", "from_page", ilWikiUtil::makeUrlTitle($_GET["from_page"])); + $ilTabs->clearTargets(); + ilUtil::sendInfo($lng->txt("wiki_page_not_exist_select_templ")); + + $form = $this->initTemplateSelectionForm(); + $tpl->setContent($form->getHTML()); + } + + /** + * Init template selection form. + */ + public function initTemplateSelectionForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + + // page name + $hi = new ilHiddenInputGUI("page"); + $hi->setValue($_GET["page"]); + $form->addItem($hi); + + // page template + $radg = new ilRadioGroupInputGUI($lng->txt("wiki_page_template"), "page_templ"); + $radg->setRequired(true); + + if ($this->object->getEmptyPageTemplate()) { + $op1 = new ilRadioOption($lng->txt("wiki_empty_page"), 0); + $radg->addOption($op1); + } + + include_once("./Modules/Wiki/classes/class.ilWikiPageTemplate.php"); + $wt = new ilWikiPageTemplate($this->object->getId()); + $ts = $wt->getAllInfo(ilWikiPageTemplate::TYPE_NEW_PAGES); + foreach ($ts as $t) { + $op = new ilRadioOption($t["title"], $t["wpage_id"]); + $radg->addOption($op); + } + + $form->addItem($radg); + + // save and cancel commands + $form->addCommandButton("createPageUsingTemplate", $lng->txt("wiki_create_page")); + $form->addCommandButton("cancelCreationPageUsingTemplate", $lng->txt("cancel")); + + $form->setTitle($lng->txt("wiki_new_page") . ": " . $_GET["page"]); + $form->setFormAction($ilCtrl->getFormAction($this)); + + return $form; + } + + /** + * Save creation with template form + */ + public function createPageUsingTemplateObject() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $form = $this->initTemplateSelectionForm(); + if ($form->checkInput()) { + $a_page = $_POST["page"]; + $this->object->createWikiPage($a_page, (int) $_POST["page_templ"]); + + // redirect to newly created page + $ilCtrl->setParameterByClass("ilwikipagegui", "page", ilWikiUtil::makeUrlTitle(($a_page))); + $ilCtrl->redirectByClass("ilwikipagegui", "edit"); + + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, ""); + } else { + $form->setValuesByPost(); + $tpl->setContent($form->getHtml()); + } + } + + /** + * Cancel page creation using a template + */ + public function cancelCreationPageUsingTemplateObject() + { + $ilCtrl = $this->ctrl; + + // redirect to newly created page + $ilCtrl->setParameterByClass("ilwikipagegui", "page", ilWikiUtil::makeUrlTitle(($_GET["from_page"]))); + $ilCtrl->redirectByClass("ilwikipagegui", "preview"); + } + + /** + * Check permission + * + * @param string $a_perm + * @param string $a_cmd + * @param string $a_type + * @param int $a_ref_id + * @return bool + */ + protected function checkPermissionBool($a_perm, $a_cmd = "", $a_type = "", $a_ref_id = null) + { + if ($a_perm == "create") { + return parent::checkPermissionBool($a_perm, $a_cmd, $a_type, $a_ref_id); + } else { + if (!$a_ref_id) { + $a_ref_id = $this->object->getRefId(); + } + include_once("./Modules/Wiki/classes/class.ilWikiPerm.php"); + return ilWikiPerm::check($a_perm, $a_ref_id, $a_cmd); + } + } + + + // + // User HTML Export + // + + /** + * Export html (as user) + */ + public function initUserHTMLExportObject() + { + $this->log->debug("init"); + $this->checkPermission("wiki_html_export"); + $this->object->initUserHTMLExport(); + } + + /** + * Export html (as user) + */ + public function startUserHTMLExportObject() + { + $this->log->debug("start"); + $this->checkPermission("wiki_html_export"); + $this->object->startUserHTMLExport(); + } + + /** + * Get user html export progress + */ + public function getUserHTMLExportProgressObject() + { + $this->log->debug("get progress"); + $this->checkPermission("wiki_html_export"); + $p = $this->object->getUserHTMLExportProgress(); + + include_once("./Services/UIComponent/ProgressBar/classes/class.ilProgressBar.php"); + $pb = ilProgressBar::getInstance(); + $pb->setCurrent($p["progress"]); + + $r = new stdClass(); + $r->progressBar = $pb->render(); + $r->status = $p["status"]; + include_once("./Services/JSON/classes/class.ilJsonUtil.php"); + $this->log->debug("status: " . $r->status); + echo(ilJsonUtil::encode($r)); + exit; + } + + /** + * Download user html export file + */ + public function downloadUserHTMLExportObject() + { + $this->log->debug("download"); + $this->checkPermission("wiki_html_export"); + $this->object->deliverUserHTMLExport(); + } } - -?> diff --git a/Modules/Wiki/classes/class.ilObjWikiListGUI.php b/Modules/Wiki/classes/class.ilObjWikiListGUI.php index 2e651b1d248522e6429b106f72853e1bc7810825..1026e5f84000430ed896dcca51b0462368e0f7f8 100755 --- a/Modules/Wiki/classes/class.ilObjWikiListGUI.php +++ b/Modules/Wiki/classes/class.ilObjWikiListGUI.php @@ -15,143 +15,135 @@ include_once "Services/Object/classes/class.ilObjectListGUI.php"; */ class ilObjWikiListGUI 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; - $this->info_screen_enabled = true; - $this->type = "wiki"; - $this->gui_class_name = "ilobjwikigui"; - - // general commands array - include_once('./Modules/Wiki/classes/class.ilObjWikiAccess.php'); - $this->commands = ilObjWikiAccess::_getCommands(); - } - - - /** - * inititialize new item - * - * @param int $a_ref_id reference id - * @param int $a_obj_id object id - * @param string $a_title title - * @param string $a_description description - */ - function initItem($a_ref_id, $a_obj_id, $a_title = "", $a_description = "") - { - parent::initItem($a_ref_id, $a_obj_id, $a_title, $a_description); - } - - - /** - * Get command target frame - * - * @param string $a_cmd command - * - * @return string command target frame - */ - function getCommandFrame($a_cmd) - { - switch($a_cmd) - { - default: - $frame = ilFrameTargetInfo::_getFrame("MainContent"); - break; - } - - return $frame; - } - - - - /** - * Get item properties - * - * @return array array of property arrays: - * "alert" (boolean) => display as an alert property (usually in red) - * "property" (string) => property name - * "value" (string) => property value - */ - function getProperties() - { - $lng = $this->lng; - - $props = array(); - - include_once("./Modules/Wiki/classes/class.ilObjWikiAccess.php"); - - if (!ilObjWikiAccess::_lookupOnline($this->obj_id)) - { - $props[] = array("alert" => true, "property" => $lng->txt("status"), - "value" => $lng->txt("offline")); - } - - $lng->loadLanguageModule("wiki"); - include_once("./Modules/Exercise/RepoObjectAssignment/classes/class.ilExcRepoObjAssignment.php"); - $info = ilExcRepoObjAssignment::getInstance()->getAssignmentInfoOfObj($this->ref_id, $this->user->getId()); - if (count($info) > 0) - { - $sub = ilExSubmission::getSubmissionsForFilename($this->ref_id, array(ilExAssignment::TYPE_WIKI_TEAM)); - foreach ($sub as $s) - { - $team = new ilExAssignmentTeam($s["team_id"]); - $mem = array_map (function ($id) { - $name = ilObjUser::_lookupName($id); - return $name["firstname"]." ".$name["lastname"]; - }, $team->getMembers()); - $props[] = array("alert" => false, "property" => $lng->txt("wiki_team_members"), - "value" => implode(", ", $mem)); - } - } - - - return $props; - } - - - /** - * Get command link url. - * - * @param int $a_ref_id reference id - * @param string $a_cmd command - * - */ - function getCommandLink($a_cmd) - { - switch($a_cmd) - { - case 'downloadFile': - $cmd_link = "ilias.php?baseClass=ilWikiHandlerGUI". - "&cmdClass=ilwikipagegui&ref_id=".$this->ref_id. - "&cmd=downloadFile&file_id=".$this->getChildId(); - break; - - default: - // separate method for this line - $cmd_link = "ilias.php?baseClass=ilWikiHandlerGUI&ref_id=".$this->ref_id."&cmd=$a_cmd"; - break; - - } - - - return $cmd_link; - } - - function setChildId($a_child_id) - { - $this->child_id = $a_child_id; - } - function getChildId() - { - return $this->child_id; - } - - + /** + * initialisation + */ + public function init() + { + $this->copy_enabled = true; + $this->delete_enabled = true; + $this->cut_enabled = true; + $this->subscribe_enabled = true; + $this->link_enabled = true; + $this->info_screen_enabled = true; + $this->type = "wiki"; + $this->gui_class_name = "ilobjwikigui"; + + // general commands array + include_once('./Modules/Wiki/classes/class.ilObjWikiAccess.php'); + $this->commands = ilObjWikiAccess::_getCommands(); + } + + + /** + * inititialize new item + * + * @param int $a_ref_id reference id + * @param int $a_obj_id object id + * @param string $a_title title + * @param string $a_description description + */ + public function initItem($a_ref_id, $a_obj_id, $a_title = "", $a_description = "") + { + parent::initItem($a_ref_id, $a_obj_id, $a_title, $a_description); + } + + + /** + * Get command target frame + * + * @param string $a_cmd command + * + * @return string command target frame + */ + public function getCommandFrame($a_cmd) + { + switch ($a_cmd) { + default: + $frame = ilFrameTargetInfo::_getFrame("MainContent"); + break; + } + + return $frame; + } + + + + /** + * Get item properties + * + * @return array array of property arrays: + * "alert" (boolean) => display as an alert property (usually in red) + * "property" (string) => property name + * "value" (string) => property value + */ + public function getProperties() + { + $lng = $this->lng; + + $props = array(); + + include_once("./Modules/Wiki/classes/class.ilObjWikiAccess.php"); + + if (!ilObjWikiAccess::_lookupOnline($this->obj_id)) { + $props[] = array("alert" => true, "property" => $lng->txt("status"), + "value" => $lng->txt("offline")); + } + + $lng->loadLanguageModule("wiki"); + include_once("./Modules/Exercise/RepoObjectAssignment/classes/class.ilExcRepoObjAssignment.php"); + $info = ilExcRepoObjAssignment::getInstance()->getAssignmentInfoOfObj($this->ref_id, $this->user->getId()); + if (count($info) > 0) { + $sub = ilExSubmission::getSubmissionsForFilename($this->ref_id, array(ilExAssignment::TYPE_WIKI_TEAM)); + foreach ($sub as $s) { + $team = new ilExAssignmentTeam($s["team_id"]); + $mem = array_map(function ($id) { + $name = ilObjUser::_lookupName($id); + return $name["firstname"] . " " . $name["lastname"]; + }, $team->getMembers()); + $props[] = array("alert" => false, "property" => $lng->txt("wiki_team_members"), + "value" => implode(", ", $mem)); + } + } + + + return $props; + } + + + /** + * Get command link url. + * + * @param int $a_ref_id reference id + * @param string $a_cmd command + * + */ + public function getCommandLink($a_cmd) + { + switch ($a_cmd) { + case 'downloadFile': + $cmd_link = "ilias.php?baseClass=ilWikiHandlerGUI" . + "&cmdClass=ilwikipagegui&ref_id=" . $this->ref_id . + "&cmd=downloadFile&file_id=" . $this->getChildId(); + break; + + default: + // separate method for this line + $cmd_link = "ilias.php?baseClass=ilWikiHandlerGUI&ref_id=" . $this->ref_id . "&cmd=$a_cmd"; + break; + + } + + + return $cmd_link; + } + + public function setChildId($a_child_id) + { + $this->child_id = $a_child_id; + } + public function getChildId() + { + return $this->child_id; + } } // END class.ilObjWikiListGUI -?> diff --git a/Modules/Wiki/classes/class.ilObjWikiSearchResultTableGUI.php b/Modules/Wiki/classes/class.ilObjWikiSearchResultTableGUI.php index 9bd0792f0ade685f76f3e67955d3057fdcf11896..dca1a2e81f01ca67653febf48c679f7391cc1c5d 100644 --- a/Modules/Wiki/classes/class.ilObjWikiSearchResultTableGUI.php +++ b/Modules/Wiki/classes/class.ilObjWikiSearchResultTableGUI.php @@ -5,62 +5,58 @@ include_once './Services/Search/classes/class.ilRepositoryObjectSearchResultTabl /** * Wiki search result table - * + * * * @author Stefan Meyer * @version $Id$ - * + * * @package ModulesWiki */ class ilObjWikiSearchResultTableGUI extends ilRepositoryObjectSearchResultTableGUI { - /** - * Parse results and call setDatea - */ - public function parse() - { - $ilCtrl = $this->ctrl; - - $rows = array(); - foreach($this->getResults()->getResults() as $result_set) - { - $row = array(); - include_once './Modules/Wiki/classes/class.ilWikiPage.php'; - $row['title'] = ilWikiPage::lookupTitle($result_set['item_id']); - - $ilCtrl->setParameterByClass( - 'ilwikipagegui', - 'page', - ilWikiUtil::makeUrlTitle($row['title']) - ); - $row['link'] = $ilCtrl->getLinkTargetByClass('ilwikipagegui','preview'); - - $row['relevance'] = $result_set['relevance']; - $row['content'] = $result_set['content']; - - $rows[] = $row; - } - - $this->setData($rows); - } - - /** - * Fill result row - * @param type $a_set - */ - public function fillRow($a_set) - { - $this->tpl->setVariable('HREF_ITEM', $a_set['link']); - $this->tpl->setVariable('TXT_ITEM_TITLE',$a_set['title']); - - if($this->getSettings()->enabledLucene()) - { - $this->tpl->setVariable('RELEVANCE', $this->getRelevanceHTML($a_set['relevance'])); - } - if(strlen($a_set['content'])) - { - $this->tpl->setVariable('HIGHLIGHT_CONTENT',$a_set['content']); - } - } + /** + * Parse results and call setDatea + */ + public function parse() + { + $ilCtrl = $this->ctrl; + + $rows = array(); + foreach ($this->getResults()->getResults() as $result_set) { + $row = array(); + include_once './Modules/Wiki/classes/class.ilWikiPage.php'; + $row['title'] = ilWikiPage::lookupTitle($result_set['item_id']); + + $ilCtrl->setParameterByClass( + 'ilwikipagegui', + 'page', + ilWikiUtil::makeUrlTitle($row['title']) + ); + $row['link'] = $ilCtrl->getLinkTargetByClass('ilwikipagegui', 'preview'); + + $row['relevance'] = $result_set['relevance']; + $row['content'] = $result_set['content']; + + $rows[] = $row; + } + + $this->setData($rows); + } + + /** + * Fill result row + * @param type $a_set + */ + public function fillRow($a_set) + { + $this->tpl->setVariable('HREF_ITEM', $a_set['link']); + $this->tpl->setVariable('TXT_ITEM_TITLE', $a_set['title']); + + if ($this->getSettings()->enabledLucene()) { + $this->tpl->setVariable('RELEVANCE', $this->getRelevanceHTML($a_set['relevance'])); + } + if (strlen($a_set['content'])) { + $this->tpl->setVariable('HIGHLIGHT_CONTENT', $a_set['content']); + } + } } -?> \ No newline at end of file diff --git a/Modules/Wiki/classes/class.ilObjWikiSettings.php b/Modules/Wiki/classes/class.ilObjWikiSettings.php index bc3aa747358eea098ec49454e6d74c6f1a23ee12..1700d9fa5d82141cdfe73e670048edcee7a0500f 100644 --- a/Modules/Wiki/classes/class.ilObjWikiSettings.php +++ b/Modules/Wiki/classes/class.ilObjWikiSettings.php @@ -6,24 +6,22 @@ require_once "./Services/Object/classes/class.ilObject2.php"; /** * Wiki settings application class - * - * @author Alex Killing + * + * @author Alex Killing * @version $Id$ * * @ingroup ModulesWiki */ class ilObjWikiSettings extends ilObject2 { - /** - * Get type - * - * @param - * @return - */ - function initType() - { - $this->type = "wiks"; - } - + /** + * Get type + * + * @param + * @return + */ + public function initType() + { + $this->type = "wiks"; + } } -?> diff --git a/Modules/Wiki/classes/class.ilObjWikiSettingsAccess.php b/Modules/Wiki/classes/class.ilObjWikiSettingsAccess.php index 0df76f3b57d0ccf430efd8f3d49807666d7549b3..3a2664575a2ad85bd06e1e605b2afec41cd975d7 100755 --- a/Modules/Wiki/classes/class.ilObjWikiSettingsAccess.php +++ b/Modules/Wiki/classes/class.ilObjWikiSettingsAccess.php @@ -15,8 +15,4 @@ include_once("./Services/Object/classes/class.ilObjectAccess.php"); */ class ilObjWikiSettingsAccess extends ilObjectAccess { - - } - -?> diff --git a/Modules/Wiki/classes/class.ilObjWikiSettingsGUI.php b/Modules/Wiki/classes/class.ilObjWikiSettingsGUI.php index 1283eed5d1d7220dea36051a1e705fb171752f9e..9cd7423d3c5019566fc4ffe12cb2b682465cbe83 100644 --- a/Modules/Wiki/classes/class.ilObjWikiSettingsGUI.php +++ b/Modules/Wiki/classes/class.ilObjWikiSettingsGUI.php @@ -16,239 +16,228 @@ include_once("./Services/Object/classes/class.ilObject2GUI.php"); */ class ilObjWikiSettingsGUI extends ilObject2GUI { - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - - /** - * Constructor - */ - function __construct($a_id = 0, $a_id_type = self::REPOSITORY_NODE_ID, $a_parent_node_id = 0) - { - parent::__construct($a_id, $a_id_type, $a_parent_node_id); - global $DIC; - - $this->rbacsystem = $DIC->rbac()->system(); - $this->error = $DIC["ilErr"]; - $this->access = $DIC->access(); - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $this->tabs = $DIC->tabs(); - $this->toolbar = $DIC->toolbar(); - $this->tpl = $DIC["tpl"]; - } - - - /** - * Get type - * - * @param - * @return - */ - function getType() - { - return "wiks"; - } - - - /** - * Execute command - * - * @access public - * - */ - public function executeCommand() - { - $rbacsystem = $this->rbacsystem; - $ilErr = $this->error; - $ilAccess = $this->access; - $lng = $this->lng; - - $lng->loadLanguageModule("wiki"); - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - $this->prepareOutput(); - - if (!$ilAccess->checkAccess('read','',$this->object->getRefId())) - { - $ilErr->raiseError($this->lng->txt('no_permission'),$ilErr->WARNING); - } - - switch($next_class) - { - case 'ilpermissiongui': - $this->tabs_gui->setTabActive('perm_settings'); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $ret = $this->ctrl->forwardCommand($perm_gui); - break; - - default: - if(!$cmd || $cmd == 'view') - { - $cmd = "editSettings"; - } - - $this->$cmd(); - break; - } - return true; - } - - /** - * @param ilPropertyFormGUI $form - */ - protected function editSettings(ilPropertyFormGUI $form = null) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilTabs = $this->tabs; - $ilToolbar = $this->toolbar; - $tpl = $this->tpl; - - $ilTabs->activateTab("settings"); - - if ($this->checkPermissionBool("read")) - { - if(!$form) - { - $form = $this->initForm(); - $this->populateWithCurrentSettings($form); - } - $tpl->setContent($form->getHTML()); - } - } - - /** - * @param ilPropertyFormGUI $form - */ - protected function populateWithCurrentSettings(ilPropertyFormGUI $form) - { - require_once 'Services/Captcha/classes/class.ilCaptchaUtil.php'; - - $form->setValuesByArray(array( - 'activate_captcha_anonym' => ilCaptchaUtil::isActiveForWiki() - )); - } - - /** - * @param string $a_mode - * @return ilPropertyFormGUI - */ - public function initForm($a_mode = "edit") - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - - require_once 'Services/Captcha/classes/class.ilCaptchaUtil.php'; - $cap = new ilCheckboxInputGUI($this->lng->txt('adm_captcha_anonymous_short'), 'activate_captcha_anonym'); - $cap->setInfo($this->lng->txt('adm_captcha_anonymous_wiki')); - $cap->setValue(1); - if(!ilCaptchaUtil::checkFreetype()) - { - $cap->setAlert(ilCaptchaUtil::getPreconditionsMessage()); - } - $form->addItem($cap); - - if ($this->checkPermissionBool("write")) - { - $form->addCommandButton("saveSettings", $lng->txt("save")); - } - - $form->setTitle($lng->txt("settings")); - $form->setFormAction($ilCtrl->getFormAction($this)); - - return $form; - } - - /** - * Save settings - */ - protected function saveSettings() - { - /** - * @var $lng ilLanguage - * @var $ilCtrl ilCtrl - */ - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if(!$this->checkPermissionBool("write")) - { - $this->editSettings(); - return; - } - - $form = $this->initForm(); - if(!$form->checkInput()) - { - $form->setValuesByPost(); - $this->editSettings($form); - return; - } - - require_once 'Services/Captcha/classes/class.ilCaptchaUtil.php'; - ilCaptchaUtil::setActiveForWiki((bool)$form->getInput('activate_captcha_anonym')); - - ilUtil::sendSuccess($lng->txt('msg_obj_modified'), true); - $ilCtrl->redirect($this, 'editSettings'); - } - - /** - * administration tabs show only permissions and trash folder - */ - function getAdminTabs() - { - if ($this->checkPermissionBool("visible,read")) - { - $this->tabs_gui->addTab("settings", - $this->lng->txt("settings"), - $this->ctrl->getLinkTarget($this, "editSettings")); - - } - - if ($this->checkPermissionBool("edit_permission")) - { - $this->tabs_gui->addTab("perm_settings", - $this->lng->txt("perm_settings"), - $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm") - ); - } - } - - /** - * @param string $a_form_id - * @return array - */ - public function addToExternalSettingsForm($a_form_id) - { - switch($a_form_id) - { - case ilAdministrationSettingsFormHandler::FORM_ACCESSIBILITY: - require_once 'Services/Captcha/classes/class.ilCaptchaUtil.php'; - $fields = array( - 'adm_captcha_anonymous_short' => array(ilCaptchaUtil::isActiveForWiki(), ilAdministrationSettingsFormHandler::VALUE_BOOL) - ); - - return array('obj_wiks' => array('editSettings', $fields)); - } - } + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + + /** + * Constructor + */ + public function __construct($a_id = 0, $a_id_type = self::REPOSITORY_NODE_ID, $a_parent_node_id = 0) + { + parent::__construct($a_id, $a_id_type, $a_parent_node_id); + global $DIC; + + $this->rbacsystem = $DIC->rbac()->system(); + $this->error = $DIC["ilErr"]; + $this->access = $DIC->access(); + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->tabs = $DIC->tabs(); + $this->toolbar = $DIC->toolbar(); + $this->tpl = $DIC["tpl"]; + } + + + /** + * Get type + * + * @param + * @return + */ + public function getType() + { + return "wiks"; + } + + + /** + * Execute command + * + * @access public + * + */ + public function executeCommand() + { + $rbacsystem = $this->rbacsystem; + $ilErr = $this->error; + $ilAccess = $this->access; + $lng = $this->lng; + + $lng->loadLanguageModule("wiki"); + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + $this->prepareOutput(); + + if (!$ilAccess->checkAccess('read', '', $this->object->getRefId())) { + $ilErr->raiseError($this->lng->txt('no_permission'), $ilErr->WARNING); + } + + switch ($next_class) { + case 'ilpermissiongui': + $this->tabs_gui->setTabActive('perm_settings'); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $ret = $this->ctrl->forwardCommand($perm_gui); + break; + + default: + if (!$cmd || $cmd == 'view') { + $cmd = "editSettings"; + } + + $this->$cmd(); + break; + } + return true; + } + + /** + * @param ilPropertyFormGUI $form + */ + protected function editSettings(ilPropertyFormGUI $form = null) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilTabs = $this->tabs; + $ilToolbar = $this->toolbar; + $tpl = $this->tpl; + + $ilTabs->activateTab("settings"); + + if ($this->checkPermissionBool("read")) { + if (!$form) { + $form = $this->initForm(); + $this->populateWithCurrentSettings($form); + } + $tpl->setContent($form->getHTML()); + } + } + + /** + * @param ilPropertyFormGUI $form + */ + protected function populateWithCurrentSettings(ilPropertyFormGUI $form) + { + require_once 'Services/Captcha/classes/class.ilCaptchaUtil.php'; + + $form->setValuesByArray(array( + 'activate_captcha_anonym' => ilCaptchaUtil::isActiveForWiki() + )); + } + + /** + * @param string $a_mode + * @return ilPropertyFormGUI + */ + public function initForm($a_mode = "edit") + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + + require_once 'Services/Captcha/classes/class.ilCaptchaUtil.php'; + $cap = new ilCheckboxInputGUI($this->lng->txt('adm_captcha_anonymous_short'), 'activate_captcha_anonym'); + $cap->setInfo($this->lng->txt('adm_captcha_anonymous_wiki')); + $cap->setValue(1); + if (!ilCaptchaUtil::checkFreetype()) { + $cap->setAlert(ilCaptchaUtil::getPreconditionsMessage()); + } + $form->addItem($cap); + + if ($this->checkPermissionBool("write")) { + $form->addCommandButton("saveSettings", $lng->txt("save")); + } + + $form->setTitle($lng->txt("settings")); + $form->setFormAction($ilCtrl->getFormAction($this)); + + return $form; + } + + /** + * Save settings + */ + protected function saveSettings() + { + /** + * @var $lng ilLanguage + * @var $ilCtrl ilCtrl + */ + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if (!$this->checkPermissionBool("write")) { + $this->editSettings(); + return; + } + + $form = $this->initForm(); + if (!$form->checkInput()) { + $form->setValuesByPost(); + $this->editSettings($form); + return; + } + + require_once 'Services/Captcha/classes/class.ilCaptchaUtil.php'; + ilCaptchaUtil::setActiveForWiki((bool) $form->getInput('activate_captcha_anonym')); + + ilUtil::sendSuccess($lng->txt('msg_obj_modified'), true); + $ilCtrl->redirect($this, 'editSettings'); + } + + /** + * administration tabs show only permissions and trash folder + */ + public function getAdminTabs() + { + if ($this->checkPermissionBool("visible,read")) { + $this->tabs_gui->addTab( + "settings", + $this->lng->txt("settings"), + $this->ctrl->getLinkTarget($this, "editSettings") + ); + } + + if ($this->checkPermissionBool("edit_permission")) { + $this->tabs_gui->addTab( + "perm_settings", + $this->lng->txt("perm_settings"), + $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm") + ); + } + } + + /** + * @param string $a_form_id + * @return array + */ + public function addToExternalSettingsForm($a_form_id) + { + switch ($a_form_id) { + case ilAdministrationSettingsFormHandler::FORM_ACCESSIBILITY: + require_once 'Services/Captcha/classes/class.ilCaptchaUtil.php'; + $fields = array( + 'adm_captcha_anonymous_short' => array(ilCaptchaUtil::isActiveForWiki(), ilAdministrationSettingsFormHandler::VALUE_BOOL) + ); + + return array('obj_wiks' => array('editSettings', $fields)); + } + } } -?> \ No newline at end of file diff --git a/Modules/Wiki/classes/class.ilObjWikiSubItemListGUI.php b/Modules/Wiki/classes/class.ilObjWikiSubItemListGUI.php index e9c1c9274b6ce968f9d019a96a6194e0d29d6c4d..948aad316db2913017f79609f249bab48aa8ae78 100644 --- a/Modules/Wiki/classes/class.ilObjWikiSubItemListGUI.php +++ b/Modules/Wiki/classes/class.ilObjWikiSubItemListGUI.php @@ -1,24 +1,24 @@ * @version $Id$ -* +* * * @ingroup ModulesWiki */ class ilObjWikiSubItemListGUI extends ilSubItemListGUI { - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - /** - * Constructor - */ - function __construct($a_cmd_class) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_cmd_class) + { + global $DIC; - parent::__construct($a_cmd_class); - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - } + parent::__construct($a_cmd_class); + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + } - /** - * get html - * @return - */ - public function getHTML() - { - $lng = $this->lng; - $ilUser = $this->user; - - $lng->loadLanguageModule('content'); - foreach($this->getSubItemIds(true) as $sub_item) - { - if(is_object($this->getHighlighter()) and strlen($this->getHighlighter()->getContent($this->getObjId(),$sub_item))) - { - $this->tpl->setCurrentBlock('sea_fragment'); - $this->tpl->setVariable('TXT_FRAGMENT',$this->getHighlighter()->getContent($this->getObjId(),$sub_item)); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setCurrentBlock('subitem'); - - // TODO: subitem type must returned from lucene - if(($title = ilWikiPage::lookupTitle($sub_item)) !== false) - { - // Page - $this->tpl->setVariable('SUBITEM_TYPE',$lng->txt('obj_pg')); - $this->tpl->setVariable('SEPERATOR',':'); + /** + * get html + * @return + */ + public function getHTML() + { + $lng = $this->lng; + $ilUser = $this->user; + + $lng->loadLanguageModule('content'); + foreach ($this->getSubItemIds(true) as $sub_item) { + if (is_object($this->getHighlighter()) and strlen($this->getHighlighter()->getContent($this->getObjId(), $sub_item))) { + $this->tpl->setCurrentBlock('sea_fragment'); + $this->tpl->setVariable('TXT_FRAGMENT', $this->getHighlighter()->getContent($this->getObjId(), $sub_item)); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setCurrentBlock('subitem'); + + // TODO: subitem type must returned from lucene + if (($title = ilWikiPage::lookupTitle($sub_item)) !== false) { + // Page + $this->tpl->setVariable('SUBITEM_TYPE', $lng->txt('obj_pg')); + $this->tpl->setVariable('SEPERATOR', ':'); - include_once './Services/Search/classes/class.ilUserSearchCache.php'; - $link = '&srcstring=1'; - $link = ilObjWikiGUI::getGotoLink($this->getRefId(),$title).$link; - - $this->tpl->setVariable('LINK',$link); - $this->tpl->setVariable('TARGET',$this->getItemListGUI()->getCommandFrame('')); - $this->tpl->setVariable('TITLE',$title); - $this->tpl->parseCurrentBlock(); - } - else - { - $this->tpl->setVariable('SUBITEM_TYPE',$lng->txt('obj_file')); - $this->tpl->setVariable('SEPERATOR',':'); + include_once './Services/Search/classes/class.ilUserSearchCache.php'; + $link = '&srcstring=1'; + $link = ilObjWikiGUI::getGotoLink($this->getRefId(), $title) . $link; + + $this->tpl->setVariable('LINK', $link); + $this->tpl->setVariable('TARGET', $this->getItemListGUI()->getCommandFrame('')); + $this->tpl->setVariable('TITLE', $title); + $this->tpl->parseCurrentBlock(); + } else { + $this->tpl->setVariable('SUBITEM_TYPE', $lng->txt('obj_file')); + $this->tpl->setVariable('SEPERATOR', ':'); - // File - $this->getItemListGUI()->setChildId('il__file_'.$sub_item); - $link = $this->getItemListGUI()->getCommandLink('downloadFile'); - $this->tpl->setVariable('LINK',$link); - $this->tpl->setVariable('TITLE',ilObject::_lookupTitle($sub_item)); - $this->tpl->parseCurrentBlock(); - } + // File + $this->getItemListGUI()->setChildId('il__file_' . $sub_item); + $link = $this->getItemListGUI()->getCommandLink('downloadFile'); + $this->tpl->setVariable('LINK', $link); + $this->tpl->setVariable('TITLE', ilObject::_lookupTitle($sub_item)); + $this->tpl->parseCurrentBlock(); + } - if(count($this->getSubItemIds(true)) > 1) - { - $this->parseRelevance($sub_item); - } - - $this->tpl->parseCurrentBlock(); - } - - $this->showDetailsLink(); - - return $this->tpl->get(); - } + if (count($this->getSubItemIds(true)) > 1) { + $this->parseRelevance($sub_item); + } + + $this->tpl->parseCurrentBlock(); + } + + $this->showDetailsLink(); + + return $this->tpl->get(); + } } -?> \ No newline at end of file diff --git a/Modules/Wiki/classes/class.ilPCAMDPageList.php b/Modules/Wiki/classes/class.ilPCAMDPageList.php index b55cb7dcbc2d7caa500820e65f1e90dcd449350c..610d2730046cab1c5075377a69c297360cb06b28 100644 --- a/Modules/Wiki/classes/class.ilPCAMDPageList.php +++ b/Modules/Wiki/classes/class.ilPCAMDPageList.php @@ -1,356 +1,321 @@ - -* @version $Id: class.ilPCListItem.php 22210 2009-10-26 09:46:06Z akill $ -* -* @ingroup ModulesWiki -*/ -class ilPCAMDPageList extends ilPageContent -{ - /** - * @var ilDB - */ - protected $db; - - /** - * @var ilLanguage - */ - protected $lng; - - var $dom; - - /** - * Init page content component. - */ - function init() - { - global $DIC; - - $this->db = $DIC->database(); - $this->lng = $DIC->language(); - $this->setType("amdpl"); - - $this->ref_id = (int) $_GET["ref_id"]; - } - - /** - * Get lang vars needed for editing - * @return array array of lang var keys - */ - static function getLangVars() - { - return array("ed_insert_amd_page_list", "pc_amdpl"); - } - - /** - * Set node - */ - function setNode($a_node) - { - parent::setNode($a_node); // this is the PageContent node - $this->amdpl_node = $a_node->first_child(); // this is the courses node - } - - /** - * Create list node in xml. - * - * @param object $a_pg_obj Page Object - * @param string $a_hier_id Hierarchical ID - */ - 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->amdpl_node = $this->dom->create_element("AMDPageList"); - $this->amdpl_node = $this->node->append_child($this->amdpl_node); - } - - /** - * Set list settings - */ - function setData(array $a_fields_data, $a_mode = null) - { - $ilDB = $this->db; - - $data_id = $this->amdpl_node->get_attribute("Id"); - if($data_id) - { - $ilDB->manipulate("DELETE FROM pg_amd_page_list". - " WHERE id = ".$ilDB->quote($data_id, "integer")); - } - else - { - $data_id = $ilDB->nextId("pg_amd_page_list"); - $this->amdpl_node->set_attribute("Id", $data_id); - }; - - $this->amdpl_node->set_attribute("Mode", (int)$a_mode); - - foreach($a_fields_data as $field_id => $field_data) - { - $fields = array( - "id" => array("integer", $data_id) - ,"field_id" => array("integer", $field_id) - ,"data" => array("text", serialize($field_data)) - ); - $ilDB->insert("pg_amd_page_list", $fields); - } - } - - function getMode() - { - if (is_object($this->amdpl_node)) - { - return (int)$this->amdpl_node->get_attribute("Mode"); - } - } - - /** - * Get filter field values - * - * @param int $a_data_id - * @return string - */ - function getFieldValues($a_data_id = null) - { - $ilDB = $this->db; - - $res = array(); - - if(!$a_data_id) - { - if (is_object($this->amdpl_node)) - { - $a_data_id = $this->amdpl_node->get_attribute("Id"); - } - } - - if($a_data_id) - { - $set = $ilDB->query("SELECT * FROM pg_amd_page_list". - " WHERE id = ".$ilDB->quote($a_data_id, "integer")); - while($row = $ilDB->fetchAssoc($set)) - { - $res[$row["field_id"]] = unserialize($row["data"]); - } - } - - return $res; - } - - static function handleCopiedContent(DOMDocument $a_domdoc, $a_self_ass = true, $a_clone_mobs = false) - { - global $DIC; - - $ilDB = $DIC->database(); - - // #15688 - - $xpath = new DOMXPath($a_domdoc); - $nodes = $xpath->query("//AMDPageList"); - foreach($nodes as $node) - { - $old_id = $node->getAttribute("Id"); - break; - } - - if($old_id) - { - $new_id = $ilDB->nextId("pg_amd_page_list"); - - $set = $ilDB->query("SELECT * FROM pg_amd_page_list". - " WHERE id = ".$ilDB->quote($old_id, "integer")); - while($row = $ilDB->fetchAssoc($set)) - { - $fields = array( - "id" => array("integer", $new_id) - ,"field_id" => array("integer", $row["field_id"]) - ,"data" => array("text", $row["data"]) - ); - $ilDB->insert("pg_amd_page_list", $fields); - } - - $node->setAttribute("Id", $new_id); - } - } - - - // - // presentation - // - - protected function findPages($a_list_id) - { - $ilDB = $this->db; - - $list_values = $this->getFieldValues($a_list_id); - $wiki_id = $this->getPage()->getWikiId(); - - $found_result = array(); - - // only search in active fields - $found_ids = null; - $recs = ilAdvancedMDRecord::_getSelectedRecordsByObject("wiki", $this->ref_id, "wpg"); - foreach($recs as $record) - { - foreach(ilAdvancedMDFieldDefinition::getInstancesByRecordId($record->getRecordId(), true) as $field) - { - if(isset($list_values[$field->getFieldId()])) - { - $field_form = ilADTFactory::getInstance()->getSearchBridgeForDefinitionInstance($field->getADTDefinition(), true, false); - $field->setSearchValueSerialized($field_form, $list_values[$field->getFieldId()]); - $found_pages = $field->searchSubObjects($field_form, $wiki_id, "wpg"); - if(is_array($found_ids)) - { - $found_ids = array_intersect($found_ids, $found_pages); - } - else - { - $found_ids = $found_pages; - } - } - } - } - - if(is_array($found_ids) && count($found_ids) > 0) - { - $sql = "SELECT id,title FROM il_wiki_page". - " WHERE ".$ilDB->in("id", $found_ids, "", "integer"). - " ORDER BY title"; - $set = $ilDB->query($sql); - while($row = $ilDB->fetchAssoc($set)) - { - $found_result[$row["id"]] = $row["title"]; - } - } - - return $found_result; - } - - function modifyPageContentPostXsl($a_html, $a_mode) - { - $lng = $this->lng; - - if($this->getPage()->getParentType() != "wpg") - { - return $a_html; - } - - include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecord.php'); - include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDFieldDefinition.php'); - include_once('Modules/Wiki/classes/class.ilWikiUtil.php'); - - $wiki_id = $this->getPage()->getWikiId(); - - $c_pos = 0; - $start = strpos($a_html, "[[[[[AMDPageList;"); - if (is_int($start)) - { - $end = strpos($a_html, "]]]]]", $start); - } - $i = 1; - while ($end > 0) - { - $parts = explode(";", substr($a_html, $start + 17, $end - $start - 17)); - - $list_id = (int)$parts[0]; - $list_mode = (sizeof($parts) == 2) - ? (int)$parts[1] - : 0; - - $ltpl = new ilTemplate("tpl.wiki_amd_page_list.html", true, true, "Modules/Wiki"); - - $pages = $this->findPages($list_id); - if(sizeof($pages)) - { - $ltpl->setCurrentBlock("page_bl"); - foreach($pages as $page_id => $page_title) - { - // see ilWikiUtil::makeLink() - $frag = new stdClass; - $frag->mFragment = null; - $frag->mTextform = $page_title; - - $ltpl->setVariable("PAGE", ilWikiUtil::makeLink($frag, $wiki_id, $page_title)); - $ltpl->parseCurrentBlock(); - } - } - else - { - $ltpl->touchBlock("no_hits_bl"); - } - - $ltpl->setVariable("LIST_MODE", $list_mode ? "ol" : "ul"); - - $a_html = substr($a_html, 0, $start). - $ltpl->get(). - substr($a_html, $end + 5); - - $start = strpos($a_html, "[[[[[AMDPageList;", $start + 5); - $end = 0; - if (is_int($start)) - { - $end = strpos($a_html, "]]]]]", $start); - } - } - - return $a_html; - } - - /** - * Migrate search/filter values on advmd change - * - * @param int $a_obj_id - * @param int $a_field_id - * @param string $old_option - * @param string $new_option - * @param bool $a_is_multi - */ - public static function migrateField($a_obj_id, $a_field_id, $old_option, $new_option, $a_is_multi = false) - { - global $DIC; - - $ilDB = $DIC->database(); - - // this does only work for select and select multi - - $set = $ilDB->query("SELECT * FROM pg_amd_page_list". - " WHERE field_id = ".$ilDB->quote($a_field_id, "integer")); - while($row = $ilDB->fetchAssoc($set)) - { - $data = unserialize(unserialize($row["data"])); - if(is_array($data) && - in_array($old_option, $data)) - { - $idx = array_search($old_option, $data); - if($new_option) - { - $data[$idx] = $new_option; - } - else - { - unset($data[$idx]); - } - - $fields = array( - "data" => array("text", serialize(serialize($data))) - ); - $primary = array( - "id" => array("integer", $row["id"]), - "field_id" => array("integer", $row["field_id"]) - ); - $ilDB->update("pg_amd_page_list", $fields, $primary); - } - } - } -} - -?> \ No newline at end of file + +* @version $Id: class.ilPCListItem.php 22210 2009-10-26 09:46:06Z akill $ +* +* @ingroup ModulesWiki +*/ +class ilPCAMDPageList extends ilPageContent +{ + /** + * @var ilDB + */ + protected $db; + + /** + * @var ilLanguage + */ + protected $lng; + + public $dom; + + /** + * Init page content component. + */ + public function init() + { + global $DIC; + + $this->db = $DIC->database(); + $this->lng = $DIC->language(); + $this->setType("amdpl"); + + $this->ref_id = (int) $_GET["ref_id"]; + } + + /** + * Get lang vars needed for editing + * @return array array of lang var keys + */ + public static function getLangVars() + { + return array("ed_insert_amd_page_list", "pc_amdpl"); + } + + /** + * Set node + */ + public function setNode($a_node) + { + parent::setNode($a_node); // this is the PageContent node + $this->amdpl_node = $a_node->first_child(); // this is the courses node + } + + /** + * Create list node in xml. + * + * @param object $a_pg_obj Page Object + * @param string $a_hier_id Hierarchical ID + */ + public 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->amdpl_node = $this->dom->create_element("AMDPageList"); + $this->amdpl_node = $this->node->append_child($this->amdpl_node); + } + + /** + * Set list settings + */ + public function setData(array $a_fields_data, $a_mode = null) + { + $ilDB = $this->db; + + $data_id = $this->amdpl_node->get_attribute("Id"); + if ($data_id) { + $ilDB->manipulate("DELETE FROM pg_amd_page_list" . + " WHERE id = " . $ilDB->quote($data_id, "integer")); + } else { + $data_id = $ilDB->nextId("pg_amd_page_list"); + $this->amdpl_node->set_attribute("Id", $data_id); + }; + + $this->amdpl_node->set_attribute("Mode", (int) $a_mode); + + foreach ($a_fields_data as $field_id => $field_data) { + $fields = array( + "id" => array("integer", $data_id) + ,"field_id" => array("integer", $field_id) + ,"data" => array("text", serialize($field_data)) + ); + $ilDB->insert("pg_amd_page_list", $fields); + } + } + + public function getMode() + { + if (is_object($this->amdpl_node)) { + return (int) $this->amdpl_node->get_attribute("Mode"); + } + } + + /** + * Get filter field values + * + * @param int $a_data_id + * @return string + */ + public function getFieldValues($a_data_id = null) + { + $ilDB = $this->db; + + $res = array(); + + if (!$a_data_id) { + if (is_object($this->amdpl_node)) { + $a_data_id = $this->amdpl_node->get_attribute("Id"); + } + } + + if ($a_data_id) { + $set = $ilDB->query("SELECT * FROM pg_amd_page_list" . + " WHERE id = " . $ilDB->quote($a_data_id, "integer")); + while ($row = $ilDB->fetchAssoc($set)) { + $res[$row["field_id"]] = unserialize($row["data"]); + } + } + + return $res; + } + + public static function handleCopiedContent(DOMDocument $a_domdoc, $a_self_ass = true, $a_clone_mobs = false) + { + global $DIC; + + $ilDB = $DIC->database(); + + // #15688 + + $xpath = new DOMXPath($a_domdoc); + $nodes = $xpath->query("//AMDPageList"); + foreach ($nodes as $node) { + $old_id = $node->getAttribute("Id"); + break; + } + + if ($old_id) { + $new_id = $ilDB->nextId("pg_amd_page_list"); + + $set = $ilDB->query("SELECT * FROM pg_amd_page_list" . + " WHERE id = " . $ilDB->quote($old_id, "integer")); + while ($row = $ilDB->fetchAssoc($set)) { + $fields = array( + "id" => array("integer", $new_id) + ,"field_id" => array("integer", $row["field_id"]) + ,"data" => array("text", $row["data"]) + ); + $ilDB->insert("pg_amd_page_list", $fields); + } + + $node->setAttribute("Id", $new_id); + } + } + + + // + // presentation + // + + protected function findPages($a_list_id) + { + $ilDB = $this->db; + + $list_values = $this->getFieldValues($a_list_id); + $wiki_id = $this->getPage()->getWikiId(); + + $found_result = array(); + + // only search in active fields + $found_ids = null; + $recs = ilAdvancedMDRecord::_getSelectedRecordsByObject("wiki", $this->ref_id, "wpg"); + foreach ($recs as $record) { + foreach (ilAdvancedMDFieldDefinition::getInstancesByRecordId($record->getRecordId(), true) as $field) { + if (isset($list_values[$field->getFieldId()])) { + $field_form = ilADTFactory::getInstance()->getSearchBridgeForDefinitionInstance($field->getADTDefinition(), true, false); + $field->setSearchValueSerialized($field_form, $list_values[$field->getFieldId()]); + $found_pages = $field->searchSubObjects($field_form, $wiki_id, "wpg"); + if (is_array($found_ids)) { + $found_ids = array_intersect($found_ids, $found_pages); + } else { + $found_ids = $found_pages; + } + } + } + } + + if (is_array($found_ids) && count($found_ids) > 0) { + $sql = "SELECT id,title FROM il_wiki_page" . + " WHERE " . $ilDB->in("id", $found_ids, "", "integer") . + " ORDER BY title"; + $set = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($set)) { + $found_result[$row["id"]] = $row["title"]; + } + } + + return $found_result; + } + + public function modifyPageContentPostXsl($a_html, $a_mode) + { + $lng = $this->lng; + + if ($this->getPage()->getParentType() != "wpg") { + return $a_html; + } + + include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecord.php'); + include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDFieldDefinition.php'); + include_once('Modules/Wiki/classes/class.ilWikiUtil.php'); + + $wiki_id = $this->getPage()->getWikiId(); + + $c_pos = 0; + $start = strpos($a_html, "[[[[[AMDPageList;"); + if (is_int($start)) { + $end = strpos($a_html, "]]]]]", $start); + } + $i = 1; + while ($end > 0) { + $parts = explode(";", substr($a_html, $start + 17, $end - $start - 17)); + + $list_id = (int) $parts[0]; + $list_mode = (sizeof($parts) == 2) + ? (int) $parts[1] + : 0; + + $ltpl = new ilTemplate("tpl.wiki_amd_page_list.html", true, true, "Modules/Wiki"); + + $pages = $this->findPages($list_id); + if (sizeof($pages)) { + $ltpl->setCurrentBlock("page_bl"); + foreach ($pages as $page_id => $page_title) { + // see ilWikiUtil::makeLink() + $frag = new stdClass; + $frag->mFragment = null; + $frag->mTextform = $page_title; + + $ltpl->setVariable("PAGE", ilWikiUtil::makeLink($frag, $wiki_id, $page_title)); + $ltpl->parseCurrentBlock(); + } + } else { + $ltpl->touchBlock("no_hits_bl"); + } + + $ltpl->setVariable("LIST_MODE", $list_mode ? "ol" : "ul"); + + $a_html = substr($a_html, 0, $start) . + $ltpl->get() . + substr($a_html, $end + 5); + + $start = strpos($a_html, "[[[[[AMDPageList;", $start + 5); + $end = 0; + if (is_int($start)) { + $end = strpos($a_html, "]]]]]", $start); + } + } + + return $a_html; + } + + /** + * Migrate search/filter values on advmd change + * + * @param int $a_obj_id + * @param int $a_field_id + * @param string $old_option + * @param string $new_option + * @param bool $a_is_multi + */ + public static function migrateField($a_obj_id, $a_field_id, $old_option, $new_option, $a_is_multi = false) + { + global $DIC; + + $ilDB = $DIC->database(); + + // this does only work for select and select multi + + $set = $ilDB->query("SELECT * FROM pg_amd_page_list" . + " WHERE field_id = " . $ilDB->quote($a_field_id, "integer")); + while ($row = $ilDB->fetchAssoc($set)) { + $data = unserialize(unserialize($row["data"])); + if (is_array($data) && + in_array($old_option, $data)) { + $idx = array_search($old_option, $data); + if ($new_option) { + $data[$idx] = $new_option; + } else { + unset($data[$idx]); + } + + $fields = array( + "data" => array("text", serialize(serialize($data))) + ); + $primary = array( + "id" => array("integer", $row["id"]), + "field_id" => array("integer", $row["field_id"]) + ); + $ilDB->update("pg_amd_page_list", $fields, $primary); + } + } + } +} diff --git a/Modules/Wiki/classes/class.ilPCAMDPageListGUI.php b/Modules/Wiki/classes/class.ilPCAMDPageListGUI.php index 64f3d39c671e5f90ac1972aa6ce4ce39b9a6c046..e95d28aba4ab234b1c7ff1cf22d33ffa9a53df0d 100644 --- a/Modules/Wiki/classes/class.ilPCAMDPageListGUI.php +++ b/Modules/Wiki/classes/class.ilPCAMDPageListGUI.php @@ -1,211 +1,190 @@ - -* @version $I$ -* -* @ingroup ModulesWiki -*/ -class ilPCAMDPageListGUI extends ilPageContentGUI -{ - /** - * Constructor - * @access 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(); - 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 courses form - * - * @param ilPropertyFormGUI $a_form - */ - function insert(ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - - $this->displayValidationError(); - - if(!$a_form) - { - $a_form = $this->initForm(true); - } - $tpl->setContent($a_form->getHTML()); - } - - /** - * Edit courses form - * - * @param ilPropertyFormGUI $a_form - */ - function edit(ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - - $this->displayValidationError(); - - if(!$a_form) - { - $a_form = $this->initForm(); - } - $tpl->setContent($a_form->getHTML()); - } - - /** - * Init courses form - * - * @param bool $a_insert - * @return ilPropertyFormGUI - */ - protected function initForm($a_insert = false) - { - $ilCtrl = $this->ctrl; - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this)); - if ($a_insert) - { - $form->setTitle($this->lng->txt("cont_insert_amd_page_list")); - } - else - { - $form->setTitle($this->lng->txt("cont_update_amd_page_list")); - } - $form->setDescription($this->lng->txt("wiki_page_list_form_info")); - - $mode = new ilSelectInputGUI($this->lng->txt("wiki_page_list_mode"), "mode"); - $mode->setOptions(array( - 0 => $this->lng->txt("wiki_page_list_mode_unordered"), - 1 => $this->lng->txt("wiki_page_list_mode_ordered") - )); - $mode->setRequired(true); - $form->addItem($mode); - - include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecordGUI.php'); - $this->record_gui = new ilAdvancedMDRecordGUI(ilAdvancedMDRecordGUI::MODE_SEARCH,'wiki',$this->getPage()->getWikiId(),'wpg',$this->getPage()->getId()); - $this->record_gui->setPropertyForm($form); - - if (!$a_insert) - { - $mode->setValue($this->content_obj->getMode()); - $this->record_gui->setSearchFormValues($this->content_obj->getFieldValues()); - } - - $this->record_gui->parse(); - - $no_fields = (count($form->getItems()) == 1); - if ($no_fields) - { - ilUtil::sendFailure($this->lng->txt("wiki_pg_list_no_search_fields")); - } - - if ($a_insert) - { - if (!$no_fields) - { - $form->addCommandButton("create_amd_page_list", $this->lng->txt("select")); - } - $form->addCommandButton("cancelCreate", $this->lng->txt("cancel")); - } - else - { - if (!$no_fields) - { - $form->addCommandButton("update", $this->lng->txt("select")); - } - $form->addCommandButton("cancelUpdate", $this->lng->txt("cancel")); - } - - return $form; - } - - /** - * Create new courses - */ - function create() - { - $form = $this->initForm(true); - if($form->checkInput()) - { - $elements = $this->record_gui->importSearchForm(); - if(is_array($elements)) - { - $this->content_obj = new ilPCAMDPageList($this->getPage()); - $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); - $this->content_obj->setData($elements, $form->getInput("mode")); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - } - } - - // $form->setValuesByPost(); - return $this->insert($form); - } - - /** - * Update courses - */ - function update() - { - $form = $this->initForm(); - if($form->checkInput()) - { - $elements = $this->record_gui->importSearchForm(); - if(is_array($elements)) - { - $this->content_obj->setData($elements, $form->getInput("mode")); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - } - } - - $this->pg_obj->addHierIDs(); - // $form->setValuesByPost(); - return $this->edit($form); - } -} - -?> \ No newline at end of file + +* @version $I$ +* +* @ingroup ModulesWiki +*/ +class ilPCAMDPageListGUI extends ilPageContentGUI +{ + /** + * Constructor + * @access public + */ + 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(); + 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 courses form + * + * @param ilPropertyFormGUI $a_form + */ + public function insert(ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + + $this->displayValidationError(); + + if (!$a_form) { + $a_form = $this->initForm(true); + } + $tpl->setContent($a_form->getHTML()); + } + + /** + * Edit courses form + * + * @param ilPropertyFormGUI $a_form + */ + public function edit(ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + + $this->displayValidationError(); + + if (!$a_form) { + $a_form = $this->initForm(); + } + $tpl->setContent($a_form->getHTML()); + } + + /** + * Init courses form + * + * @param bool $a_insert + * @return ilPropertyFormGUI + */ + protected function initForm($a_insert = false) + { + $ilCtrl = $this->ctrl; + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this)); + if ($a_insert) { + $form->setTitle($this->lng->txt("cont_insert_amd_page_list")); + } else { + $form->setTitle($this->lng->txt("cont_update_amd_page_list")); + } + $form->setDescription($this->lng->txt("wiki_page_list_form_info")); + + $mode = new ilSelectInputGUI($this->lng->txt("wiki_page_list_mode"), "mode"); + $mode->setOptions(array( + 0 => $this->lng->txt("wiki_page_list_mode_unordered"), + 1 => $this->lng->txt("wiki_page_list_mode_ordered") + )); + $mode->setRequired(true); + $form->addItem($mode); + + include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecordGUI.php'); + $this->record_gui = new ilAdvancedMDRecordGUI(ilAdvancedMDRecordGUI::MODE_SEARCH, 'wiki', $this->getPage()->getWikiId(), 'wpg', $this->getPage()->getId()); + $this->record_gui->setPropertyForm($form); + + if (!$a_insert) { + $mode->setValue($this->content_obj->getMode()); + $this->record_gui->setSearchFormValues($this->content_obj->getFieldValues()); + } + + $this->record_gui->parse(); + + $no_fields = (count($form->getItems()) == 1); + if ($no_fields) { + ilUtil::sendFailure($this->lng->txt("wiki_pg_list_no_search_fields")); + } + + if ($a_insert) { + if (!$no_fields) { + $form->addCommandButton("create_amd_page_list", $this->lng->txt("select")); + } + $form->addCommandButton("cancelCreate", $this->lng->txt("cancel")); + } else { + if (!$no_fields) { + $form->addCommandButton("update", $this->lng->txt("select")); + } + $form->addCommandButton("cancelUpdate", $this->lng->txt("cancel")); + } + + return $form; + } + + /** + * Create new courses + */ + public function create() + { + $form = $this->initForm(true); + if ($form->checkInput()) { + $elements = $this->record_gui->importSearchForm(); + if (is_array($elements)) { + $this->content_obj = new ilPCAMDPageList($this->getPage()); + $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); + $this->content_obj->setData($elements, $form->getInput("mode")); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + } + } + + // $form->setValuesByPost(); + return $this->insert($form); + } + + /** + * Update courses + */ + public function update() + { + $form = $this->initForm(); + if ($form->checkInput()) { + $elements = $this->record_gui->importSearchForm(); + if (is_array($elements)) { + $this->content_obj->setData($elements, $form->getInput("mode")); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + } + } + + $this->pg_obj->addHierIDs(); + // $form->setValuesByPost(); + return $this->edit($form); + } +} diff --git a/Modules/Wiki/classes/class.ilWikiContributor.php b/Modules/Wiki/classes/class.ilWikiContributor.php index b584b2fb9d4990cb7ec4cf9aa38999bccc9fa40d..8e7a3f1b0930c20177542ae1e572646fcb4ddd22 100755 --- a/Modules/Wiki/classes/class.ilWikiContributor.php +++ b/Modules/Wiki/classes/class.ilWikiContributor.php @@ -1,24 +1,24 @@ database(); + $ilDB = $DIC->database(); - $set = $ilDB->queryF("SELECT status FROM il_wiki_contributor ". - "WHERE wiki_id = %s and user_id = %s", - array("integer", "integer"), - array($a_obj_id, $a_user_id)); - if($row = $ilDB->fetchAssoc($set)) - { - return $row["status"]; - } - return false; - } + $set = $ilDB->queryF( + "SELECT status FROM il_wiki_contributor " . + "WHERE wiki_id = %s and user_id = %s", + array("integer", "integer"), + array($a_obj_id, $a_user_id) + ); + if ($row = $ilDB->fetchAssoc($set)) { + return $row["status"]; + } + return false; + } - /** - * Lookup last change in mark or success status - * - * @param int $a_obj_id exercise id - * @param int $a_user_id member id - * @return mixed false (if user is no member) or notgraded|passed|failed - */ - static function _lookupStatusTime($a_obj_id, $a_user_id) - { - global $DIC; + /** + * Lookup last change in mark or success status + * + * @param int $a_obj_id exercise id + * @param int $a_user_id member id + * @return mixed false (if user is no member) or notgraded|passed|failed + */ + public static function _lookupStatusTime($a_obj_id, $a_user_id) + { + global $DIC; - $ilDB = $DIC->database(); + $ilDB = $DIC->database(); - $set = $ilDB->queryF("SELECT status_time FROM il_wiki_contributor ". - "WHERE wiki_id = %s and user_id = %s", - array("integer", "integer"), - array($a_obj_id, $a_user_id)); - if($row = $ilDB->fetchAssoc($set)) - { - return $row["status_time"]; - } - return false; - } + $set = $ilDB->queryF( + "SELECT status_time FROM il_wiki_contributor " . + "WHERE wiki_id = %s and user_id = %s", + array("integer", "integer"), + array($a_obj_id, $a_user_id) + ); + if ($row = $ilDB->fetchAssoc($set)) { + return $row["status_time"]; + } + return false; + } - /** - * Write success status - * - * @param int $a_obj_id exercise id - * @param int $a_user_id member id - * @param int $status status: STATUS_NOT_GRADED|STATUS_PASSED|STATUS_FAILED - * - * @return int number of affected rows - */ - static function _writeStatus($a_obj_id, $a_user_id, $a_status) - { - global $DIC; + /** + * Write success status + * + * @param int $a_obj_id exercise id + * @param int $a_user_id member id + * @param int $status status: STATUS_NOT_GRADED|STATUS_PASSED|STATUS_FAILED + * + * @return int number of affected rows + */ + public static function _writeStatus($a_obj_id, $a_user_id, $a_status) + { + global $DIC; - $ilDB = $DIC->database(); + $ilDB = $DIC->database(); - $ilDB->manipulate("DELETE FROM il_wiki_contributor WHERE ". - " wiki_id = ".$ilDB->quote($a_obj_id, "integer"). - " AND user_id = ".$ilDB->quote($a_user_id, "integer")); - - $ilDB->manipulateF("INSERT INTO il_wiki_contributor (status, wiki_id, user_id, status_time) ". - "VALUES (%s,%s,%s,%s)", - array("integer", "integer", "integer", "timestamp"), - array($a_status, $a_obj_id, $a_user_id, ilUtil::now())); - } + $ilDB->manipulate("DELETE FROM il_wiki_contributor WHERE " . + " wiki_id = " . $ilDB->quote($a_obj_id, "integer") . + " AND user_id = " . $ilDB->quote($a_user_id, "integer")); + $ilDB->manipulateF( + "INSERT INTO il_wiki_contributor (status, wiki_id, user_id, status_time) " . + "VALUES (%s,%s,%s,%s)", + array("integer", "integer", "integer", "timestamp"), + array($a_status, $a_obj_id, $a_user_id, ilUtil::now()) + ); + } } -?> diff --git a/Modules/Wiki/classes/class.ilWikiContributorsTableGUI.php b/Modules/Wiki/classes/class.ilWikiContributorsTableGUI.php index 3fb05cbd4ad626c4d506805396f2f752de45a97a..c4e0f0c038161a9026ddf481fa29cb6a11c5471a 100755 --- a/Modules/Wiki/classes/class.ilWikiContributorsTableGUI.php +++ b/Modules/Wiki/classes/class.ilWikiContributorsTableGUI.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("", "", "1"); + //$this->addColumn("", "", "1"); + $this->addColumn($lng->txt("wiki_contributor"), "", "33%"); + $this->addColumn($lng->txt("wiki_page_changes"), "", "33%"); + $this->addColumn($lng->txt("wiki_grading"), "", "33%"); + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate( + "tpl.table_row_contributors.html", + "Modules/Wiki" + ); + $this->getContributors(); + $this->setFormAction($ilCtrl->getFormAction($this->getParentObject(), "saveGrading")); + $this->addCommandButton("saveGrading", $lng->txt("save")); + //$this->addMultiCommand("saveGrading", $lng->txt("save")); + + $this->setShowRowsSelector(true); + + $this->setTitle($lng->txt("wiki_contributors")); + } + + /** + * Get contributors of wiki + */ + public function getContributors() + { + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + $contributors = ilWikiPage::getWikiContributors($this->wiki_id); + $this->setDefaultOrderField("lastname"); + $this->setDefaultOrderDirection("asc"); + $this->setData($contributors); + } + + /** + * Standard Version of Fill Row. Most likely to + * be overwritten by derived class. + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + include_once("./Services/Tracking/classes/class.ilLPMarks.php"); + include_once("./Modules/Wiki/classes/class.ilWikiContributor.php"); - $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("", "", "1"); - //$this->addColumn("", "", "1"); - $this->addColumn($lng->txt("wiki_contributor"), "", "33%"); - $this->addColumn($lng->txt("wiki_page_changes"), "", "33%"); - $this->addColumn($lng->txt("wiki_grading"), "", "33%"); - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.table_row_contributors.html", - "Modules/Wiki"); - $this->getContributors(); - $this->setFormAction($ilCtrl->getFormAction($this->getParentObject(), "saveGrading")); - $this->addCommandButton("saveGrading", $lng->txt("save")); - //$this->addMultiCommand("saveGrading", $lng->txt("save")); - - $this->setShowRowsSelector(true); - - $this->setTitle($lng->txt("wiki_contributors")); - } - - /** - * Get contributors of wiki - */ - function getContributors() - { - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $contributors = ilWikiPage::getWikiContributors($this->wiki_id); - $this->setDefaultOrderField("lastname"); - $this->setDefaultOrderDirection("asc"); - $this->setData($contributors); - } - - /** - * Standard Version of Fill Row. Most likely to - * be overwritten by derived class. - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - include_once("./Services/Tracking/classes/class.ilLPMarks.php"); - include_once("./Modules/Wiki/classes/class.ilWikiContributor.php"); + if (ilObject::_exists($a_set["user_id"])) { + arsort($a_set["pages"]); - if (ilObject::_exists($a_set["user_id"])) - { - arsort($a_set["pages"]); + // pages + foreach ($a_set["pages"] as $page_id => $cnt) { + if ($page_id > 0) { + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + $title = ilWikiPage::lookupTitle($page_id); + $this->tpl->setCurrentBlock("page"); + $this->tpl->setVariable("PAGE", $title); + $this->tpl->setVariable("CNT", $cnt); + $this->tpl->parseCurrentBlock(); + } + } + + $this->tpl->setVariable( + "TXT_LINKED_USER", + $user["lastname"] . ", " . $user["firstname"] . " [" . $login . "]" + ); + + // profile link + //$ilCtrl->setParameterByClass("ilpublicuserprofilegui", "user", $a_set["user"]); + //$ilCtrl->setParameterByClass("ilpublicuserprofilegui", "back_url", + // rawurlencode($ilCtrl->getLinkTarget($this->getParentObject(), $this->getParentCmd()))); + //$this->tpl->setVariable("USER_LINK", + // $ilCtrl->getLinkTargetByClass("ilpublicuserprofilegui", "getHTML")); + $img = ilObjUser::_getPersonalPicturePath($a_set["user_id"], "xsmall"); + $this->tpl->setVariable("IMG_USER", $img); + $this->tpl->setVariable( + "TXT_NAME", + htmlspecialchars($a_set["lastname"] . ", " . $a_set["firstname"]) + ); + $this->tpl->setVariable("USER_ID", $a_set["user_id"]); + + // comment for learner + $this->tpl->setVariable("TXT_LCOMMENT", $lng->txt("wiki_comment_for_learner")); + $this->tpl->setVariable( + "NAME_LCOMMENT", + "lcomment[" . $a_set["user_id"] . "]" + ); + $lpcomment = ilLPMarks::_lookupComment( + $a_set["user_id"], + $this->parent_obj->object->getId() + ); + $this->tpl->setVariable( + "VAL_LCOMMENT", + ilUtil::prepareFormOutput($lpcomment) + ); - // pages - foreach ($a_set["pages"] as $page_id => $cnt) - { - if ($page_id > 0) - { - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $title = ilWikiPage::lookupTitle($page_id); - $this->tpl->setCurrentBlock("page"); - $this->tpl->setVariable("PAGE", $title); - $this->tpl->setVariable("CNT", $cnt); - $this->tpl->parseCurrentBlock(); - } - } - - $this->tpl->setVariable("TXT_LINKED_USER", - $user["lastname"].", ".$user["firstname"]." [".$login."]"); - - // profile link - //$ilCtrl->setParameterByClass("ilpublicuserprofilegui", "user", $a_set["user"]); - //$ilCtrl->setParameterByClass("ilpublicuserprofilegui", "back_url", - // rawurlencode($ilCtrl->getLinkTarget($this->getParentObject(), $this->getParentCmd()))); - //$this->tpl->setVariable("USER_LINK", - // $ilCtrl->getLinkTargetByClass("ilpublicuserprofilegui", "getHTML")); - $img = ilObjUser::_getPersonalPicturePath($a_set["user_id"], "xsmall"); - $this->tpl->setVariable("IMG_USER", $img); - $this->tpl->setVariable("TXT_NAME", - htmlspecialchars($a_set["lastname"].", ".$a_set["firstname"])); - $this->tpl->setVariable("USER_ID", $a_set["user_id"]); - - // comment for learner - $this->tpl->setVariable("TXT_LCOMMENT", $lng->txt("wiki_comment_for_learner")); - $this->tpl->setVariable("NAME_LCOMMENT", - "lcomment[".$a_set["user_id"]."]"); - $lpcomment = ilLPMarks::_lookupComment($a_set["user_id"], - $this->parent_obj->object->getId()); - $this->tpl->setVariable("VAL_LCOMMENT", - ilUtil::prepareFormOutput($lpcomment)); - - // status - //$status = ilExerciseMembers::_lookupStatus($this->object->getId(), $member_id); - $status = ilWikiContributor::_lookupStatus($this->parent_obj->object->getId(), $a_set["user_id"]); - $this->tpl->setVariable("SEL_".$status, ' selected="selected" '); - $this->tpl->setVariable("TXT_NOTGRADED", $lng->txt("wiki_notgraded")); - $this->tpl->setVariable("TXT_PASSED", $lng->txt("wiki_passed")); - $this->tpl->setVariable("TXT_FAILED", $lng->txt("wiki_failed")); - $this->tpl->setVariable("VAL_NOTGRADED", ilWikiContributor::STATUS_NOT_GRADED); - $this->tpl->setVariable("VAL_PASSED", ilWikiContributor::STATUS_PASSED); - $this->tpl->setVariable("VAL_FAILED", ilWikiContributor::STATUS_FAILED); - if (($sd = ilWikiContributor::_lookupStatusTime($this->parent_obj->object->getId(), $a_set["user_id"])) > 0) - { - $this->tpl->setCurrentBlock("status_date"); - $this->tpl->setVariable("TXT_LAST_CHANGE", $lng->txt("last_change")); - $this->tpl->setVariable("VAL_STATUS_DATE", - ilDatePresentation::formatDate(new ilDateTime($sd,IL_CAL_DATETIME))); - $this->tpl->parseCurrentBlock(); - } - switch($status) - { - case ilWikiContributor::STATUS_PASSED: $pic = "scorm/passed.svg"; break; - case ilWikiContributor::STATUS_FAILED: $pic = "scorm/failed.svg"; break; - default: $pic = "scorm/not_attempted.svg"; break; - } - $this->tpl->setVariable("IMG_STATUS", ilUtil::getImagePath($pic)); - $this->tpl->setVariable("ALT_STATUS", $lng->txt("wiki_".$status)); - - // mark - $this->tpl->setVariable("TXT_MARK", $lng->txt("wiki_mark")); - $this->tpl->setVariable("NAME_MARK", - "mark[".$a_set["user_id"]."]"); - $mark = ilLPMarks::_lookupMark($a_set["user_id"], $this->parent_obj->object->getId()); - - $this->tpl->setVariable("VAL_MARK", - ilUtil::prepareFormOutput($mark)); - - } - - } + // status + //$status = ilExerciseMembers::_lookupStatus($this->object->getId(), $member_id); + $status = ilWikiContributor::_lookupStatus($this->parent_obj->object->getId(), $a_set["user_id"]); + $this->tpl->setVariable("SEL_" . $status, ' selected="selected" '); + $this->tpl->setVariable("TXT_NOTGRADED", $lng->txt("wiki_notgraded")); + $this->tpl->setVariable("TXT_PASSED", $lng->txt("wiki_passed")); + $this->tpl->setVariable("TXT_FAILED", $lng->txt("wiki_failed")); + $this->tpl->setVariable("VAL_NOTGRADED", ilWikiContributor::STATUS_NOT_GRADED); + $this->tpl->setVariable("VAL_PASSED", ilWikiContributor::STATUS_PASSED); + $this->tpl->setVariable("VAL_FAILED", ilWikiContributor::STATUS_FAILED); + if (($sd = ilWikiContributor::_lookupStatusTime($this->parent_obj->object->getId(), $a_set["user_id"])) > 0) { + $this->tpl->setCurrentBlock("status_date"); + $this->tpl->setVariable("TXT_LAST_CHANGE", $lng->txt("last_change")); + $this->tpl->setVariable( + "VAL_STATUS_DATE", + ilDatePresentation::formatDate(new ilDateTime($sd, IL_CAL_DATETIME)) + ); + $this->tpl->parseCurrentBlock(); + } + switch ($status) { + case ilWikiContributor::STATUS_PASSED: $pic = "scorm/passed.svg"; break; + case ilWikiContributor::STATUS_FAILED: $pic = "scorm/failed.svg"; break; + default: $pic = "scorm/not_attempted.svg"; break; + } + $this->tpl->setVariable("IMG_STATUS", ilUtil::getImagePath($pic)); + $this->tpl->setVariable("ALT_STATUS", $lng->txt("wiki_" . $status)); + + // mark + $this->tpl->setVariable("TXT_MARK", $lng->txt("wiki_mark")); + $this->tpl->setVariable( + "NAME_MARK", + "mark[" . $a_set["user_id"] . "]" + ); + $mark = ilLPMarks::_lookupMark($a_set["user_id"], $this->parent_obj->object->getId()); + $this->tpl->setVariable( + "VAL_MARK", + ilUtil::prepareFormOutput($mark) + ); + } + } } -?> diff --git a/Modules/Wiki/classes/class.ilWikiDataSet.php b/Modules/Wiki/classes/class.ilWikiDataSet.php index dd620c71ae9b6277a18c842116279b8ff074a4cc..a400a667dff5f018f42bf1cc268a0431bba89754 100644 --- a/Modules/Wiki/classes/class.ilWikiDataSet.php +++ b/Modules/Wiki/classes/class.ilWikiDataSet.php @@ -5,7 +5,7 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); /** * Wiki Data set class - * + * * This class implements the following entities: * - wiki: data from il_wiki_data * - wpg: data from il_wiki_page @@ -16,351 +16,329 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); */ class ilWikiDataSet extends ilDataSet { - /** - * @var ilLogger - */ - protected $wiki_log; + /** + * @var ilLogger + */ + protected $wiki_log; - /** - * construct - * - * @param - * @return - */ - function __construct() - { - global $DIC; + /** + * construct + * + * @param + * @return + */ + public function __construct() + { + global $DIC; - $this->db = $DIC->database(); - parent::__construct(); - $this->wiki_log = ilLoggerFactory::getLogger('wiki'); - } + $this->db = $DIC->database(); + parent::__construct(); + $this->wiki_log = ilLoggerFactory::getLogger('wiki'); + } - /** - * Get supported versions - * - * @param - * @return - */ - public function getSupportedVersions() - { - return array("4.1.0", "4.3.0", "4.4.0", "5.1.0"); - } - - /** - * Get xml namespace - * - * @param - * @return - */ - function getXmlNamespace($a_entity, $a_schema_version) - { - return "http://www.ilias.de/xml/Modules/Wiki/".$a_entity; - } - - /** - * Get field types for entity - * - * @param - * @return - */ - protected function getTypes($a_entity, $a_version) - { - if ($a_entity == "wiki") - { - switch ($a_version) - { - case "4.1.0": - return array( - "Id" => "integer", - "Title" => "text", - "Description" => "text", - "StartPage" => "text", - "Short" => "text", - "Introduction" => "text", - "Rating" => "integer"); - - case "4.3.0": - return array( - "Id" => "integer", - "Title" => "text", - "Description" => "text", - "StartPage" => "text", - "Short" => "text", - "Introduction" => "text", - "Rating" => "integer", - "PublicNotes" => "integer", - // "ImpPages" => "integer", - "PageToc" => "integer", - "RatingSide" => "integer", - "RatingNew" => "integer", - "RatingExt" => "integer"); - - case "4.4.0": - return array( - "Id" => "integer", - "Title" => "text", - "Description" => "text", - "StartPage" => "text", - "Short" => "text", - "Introduction" => "text", - "Rating" => "integer", - "PublicNotes" => "integer", - // "ImpPages" => "integer", - "PageToc" => "integer", - "RatingSide" => "integer", - "RatingNew" => "integer", - "RatingExt" => "integer", - "RatingOverall" => "integer"); + /** + * Get supported versions + * + * @param + * @return + */ + public function getSupportedVersions() + { + return array("4.1.0", "4.3.0", "4.4.0", "5.1.0"); + } + + /** + * Get xml namespace + * + * @param + * @return + */ + public function getXmlNamespace($a_entity, $a_schema_version) + { + return "http://www.ilias.de/xml/Modules/Wiki/" . $a_entity; + } + + /** + * Get field types for entity + * + * @param + * @return + */ + protected function getTypes($a_entity, $a_version) + { + if ($a_entity == "wiki") { + switch ($a_version) { + case "4.1.0": + return array( + "Id" => "integer", + "Title" => "text", + "Description" => "text", + "StartPage" => "text", + "Short" => "text", + "Introduction" => "text", + "Rating" => "integer"); + + case "4.3.0": + return array( + "Id" => "integer", + "Title" => "text", + "Description" => "text", + "StartPage" => "text", + "Short" => "text", + "Introduction" => "text", + "Rating" => "integer", + "PublicNotes" => "integer", + // "ImpPages" => "integer", + "PageToc" => "integer", + "RatingSide" => "integer", + "RatingNew" => "integer", + "RatingExt" => "integer"); + + case "4.4.0": + return array( + "Id" => "integer", + "Title" => "text", + "Description" => "text", + "StartPage" => "text", + "Short" => "text", + "Introduction" => "text", + "Rating" => "integer", + "PublicNotes" => "integer", + // "ImpPages" => "integer", + "PageToc" => "integer", + "RatingSide" => "integer", + "RatingNew" => "integer", + "RatingExt" => "integer", + "RatingOverall" => "integer"); - case "5.1.0": - return array( - "Id" => "integer", - "Title" => "text", - "Description" => "text", - "StartPage" => "text", - "Short" => "text", - "Introduction" => "text", - "Rating" => "integer", - "PublicNotes" => "integer", - // "ImpPages" => "integer", - "PageToc" => "integer", - "RatingSide" => "integer", - "RatingNew" => "integer", - "RatingExt" => "integer", - "RatingOverall" => "integer", - "LinkMdValues" => "integer" - ); - } - } + case "5.1.0": + return array( + "Id" => "integer", + "Title" => "text", + "Description" => "text", + "StartPage" => "text", + "Short" => "text", + "Introduction" => "text", + "Rating" => "integer", + "PublicNotes" => "integer", + // "ImpPages" => "integer", + "PageToc" => "integer", + "RatingSide" => "integer", + "RatingNew" => "integer", + "RatingExt" => "integer", + "RatingOverall" => "integer", + "LinkMdValues" => "integer" + ); + } + } - if ($a_entity == "wpg") - { - switch ($a_version) - { - case "4.1.0": - return array( - "Id" => "integer", - "Title" => "text", - "WikiId" => "integer"); - - case "4.3.0": - case "4.4.0": - case "5.1.0": - return array( - "Id" => "integer", - "Title" => "text", - "WikiId" => "integer", - "Blocked" => "integer", - "Rating" => "integer"); - } - } + if ($a_entity == "wpg") { + switch ($a_version) { + case "4.1.0": + return array( + "Id" => "integer", + "Title" => "text", + "WikiId" => "integer"); + + case "4.3.0": + case "4.4.0": + case "5.1.0": + return array( + "Id" => "integer", + "Title" => "text", + "WikiId" => "integer", + "Blocked" => "integer", + "Rating" => "integer"); + } + } - if ($a_entity == "wiki_imp_page") - { - switch ($a_version) - { - case "5.1.0": - return array( - "WikiId" => "integer", - "PageId" => "integer", - "Ord" => "integer", - "Indent" => "integer"); - } - } - return array(); - } + if ($a_entity == "wiki_imp_page") { + switch ($a_version) { + case "5.1.0": + return array( + "WikiId" => "integer", + "PageId" => "integer", + "Ord" => "integer", + "Indent" => "integer"); + } + } + return array(); + } - /** - * 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 == "wiki") - { - switch ($a_version) - { - case "4.1.0": - $this->getDirectDataFromQuery("SELECT id, title, description,". - " startpage start_page, short, rating, introduction". - " FROM il_wiki_data JOIN object_data ON (il_wiki_data.id = object_data.obj_id)". - " WHERE ".$ilDB->in("id", $a_ids, false, "integer")); - break; - - case "4.3.0": - $this->getDirectDataFromQuery("SELECT id, title, description,". - " startpage start_page, short, rating, introduction,". // imp_pages, - " public_notes, page_toc, rating_side, rating_new, rating_ext". - " FROM il_wiki_data JOIN object_data ON (il_wiki_data.id = object_data.obj_id)". - " WHERE ".$ilDB->in("id", $a_ids, false, "integer")); - break; - - case "4.4.0": - $this->getDirectDataFromQuery("SELECT id, title, description,". - " startpage start_page, short, rating, rating_overall, introduction,". // imp_pages, - " public_notes, page_toc, rating_side, rating_new, rating_ext". - " FROM il_wiki_data JOIN object_data ON (il_wiki_data.id = object_data.obj_id)". - " WHERE ".$ilDB->in("id", $a_ids, false, "integer")); - break; + if (!is_array($a_ids)) { + $a_ids = array($a_ids); + } + + if ($a_entity == "wiki") { + switch ($a_version) { + case "4.1.0": + $this->getDirectDataFromQuery("SELECT id, title, description," . + " startpage start_page, short, rating, introduction" . + " FROM il_wiki_data JOIN object_data ON (il_wiki_data.id = object_data.obj_id)" . + " WHERE " . $ilDB->in("id", $a_ids, false, "integer")); + break; + + case "4.3.0": + $this->getDirectDataFromQuery("SELECT id, title, description," . + " startpage start_page, short, rating, introduction," . // imp_pages, + " public_notes, page_toc, rating_side, rating_new, rating_ext" . + " FROM il_wiki_data JOIN object_data ON (il_wiki_data.id = object_data.obj_id)" . + " WHERE " . $ilDB->in("id", $a_ids, false, "integer")); + break; + + case "4.4.0": + $this->getDirectDataFromQuery("SELECT id, title, description," . + " startpage start_page, short, rating, rating_overall, introduction," . // imp_pages, + " public_notes, page_toc, rating_side, rating_new, rating_ext" . + " FROM il_wiki_data JOIN object_data ON (il_wiki_data.id = object_data.obj_id)" . + " WHERE " . $ilDB->in("id", $a_ids, false, "integer")); + break; - case "5.1.0": - $this->getDirectDataFromQuery("SELECT id, title, description,". - " startpage start_page, short, rating, rating_overall, introduction,". // imp_pages, - " public_notes, page_toc, rating_side, rating_new, rating_ext, link_md_values". - " FROM il_wiki_data JOIN object_data ON (il_wiki_data.id = object_data.obj_id)". - " WHERE ".$ilDB->in("id", $a_ids, false, "integer")); - break; - } - } + case "5.1.0": + $this->getDirectDataFromQuery("SELECT id, title, description," . + " startpage start_page, short, rating, rating_overall, introduction," . // imp_pages, + " public_notes, page_toc, rating_side, rating_new, rating_ext, link_md_values" . + " FROM il_wiki_data JOIN object_data ON (il_wiki_data.id = object_data.obj_id)" . + " WHERE " . $ilDB->in("id", $a_ids, false, "integer")); + break; + } + } - if ($a_entity == "wpg") - { - switch ($a_version) - { - case "4.1.0": - $this->getDirectDataFromQuery("SELECT id, title, wiki_id". - " FROM il_wiki_page". - " WHERE ".$ilDB->in("wiki_id", $a_ids, false, "integer")); - break; - - case "4.3.0": - case "4.4.0": - case "5.1.0": - $this->getDirectDataFromQuery("SELECT id, title, wiki_id,". - " blocked, rating". - " FROM il_wiki_page". - " WHERE ".$ilDB->in("wiki_id", $a_ids, false, "integer")); - break; - } - } + if ($a_entity == "wpg") { + switch ($a_version) { + case "4.1.0": + $this->getDirectDataFromQuery("SELECT id, title, wiki_id" . + " FROM il_wiki_page" . + " WHERE " . $ilDB->in("wiki_id", $a_ids, false, "integer")); + break; + + case "4.3.0": + case "4.4.0": + case "5.1.0": + $this->getDirectDataFromQuery("SELECT id, title, wiki_id," . + " blocked, rating" . + " FROM il_wiki_page" . + " WHERE " . $ilDB->in("wiki_id", $a_ids, false, "integer")); + break; + } + } - if ($a_entity == "wiki_imp_page") - { - switch ($a_version) - { - case "5.1.0": - $this->getDirectDataFromQuery("SELECT wiki_id, page_id, ord, indent ". - " FROM il_wiki_imp_pages ". - " WHERE ".$ilDB->in("wiki_id", $a_ids, false, "integer")); - break; - } - } - } - - /** - * Determine the dependent sets of data - */ - protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) - { - switch ($a_entity) - { - case "wiki": - return array ( - "wpg" => array("ids" => $a_rec["Id"]), - "wiki_imp_page" => array("ids" => $a_rec["Id"]) - ); - } + if ($a_entity == "wiki_imp_page") { + switch ($a_version) { + case "5.1.0": + $this->getDirectDataFromQuery("SELECT wiki_id, page_id, ord, indent " . + " FROM il_wiki_imp_pages " . + " WHERE " . $ilDB->in("wiki_id", $a_ids, false, "integer")); + break; + } + } + } + + /** + * Determine the dependent sets of data + */ + protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) + { + switch ($a_entity) { + case "wiki": + return array( + "wpg" => array("ids" => $a_rec["Id"]), + "wiki_imp_page" => array("ids" => $a_rec["Id"]) + ); + } - return false; - } - - - /** - * Import record - * - * @param - * @return - */ - function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) - { -//echo $a_entity; -//var_dump($a_rec); + return false; + } + + + /** + * Import record + * + * @param + * @return + */ + public function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) + { + //echo $a_entity; + //var_dump($a_rec); - switch ($a_entity) - { - case "wiki": - - include_once("./Modules/Wiki/classes/class.ilObjWiki.php"); - if($new_id = $a_mapping->getMapping('Services/Container','objs',$a_rec['Id'])) - { - $newObj = ilObjectFactory::getInstanceByObjId($new_id,false); - } - else - { - $newObj = new ilObjWiki(); - $newObj->setType("wiki"); - $newObj->create(true); - } - - $newObj->setTitle($a_rec["Title"]); - $newObj->setDescription($a_rec["Description"]); - $newObj->setShortTitle($a_rec["Short"]); - $newObj->setStartPage($a_rec["StartPage"]); - $newObj->setRatingOverall($a_rec["RatingOverall"]); - $newObj->setRating($a_rec["Rating"]); - $newObj->setIntroduction($a_rec["Introduction"]); - $newObj->setPublicNotes($a_rec["PublicNotes"]); - - // >= 4.3 - if(isset($a_rec["PageToc"])) - { - // $newObj->setImportantPages($a_rec["ImpPages"]); - $newObj->setPageToc($a_rec["PageToc"]); - $newObj->setRatingAsBlock($a_rec["RatingSide"]); - $newObj->setRatingForNewPages($a_rec["RatingNew"]); - $newObj->setRatingCategories($a_rec["RatingExt"]); - } - $newObj->setLinkMetadataValues($a_rec["LinkMdValues"]); - - $newObj->update(true); - $this->current_obj = $newObj; - $a_mapping->addMapping("Modules/Wiki", "wiki", $a_rec["Id"], $newObj->getId()); - $a_mapping->addMapping("Services/Object", "obj", $a_rec["Id"], $newObj->getId()); - $a_mapping->addMapping("Services/Rating", "rating_category_parent_id", $a_rec["Id"], $newObj->getId()); - $a_mapping->addMapping("Services/AdvancedMetaData", "parent", $a_rec["Id"], $newObj->getId()); - break; + switch ($a_entity) { + case "wiki": + + include_once("./Modules/Wiki/classes/class.ilObjWiki.php"); + if ($new_id = $a_mapping->getMapping('Services/Container', 'objs', $a_rec['Id'])) { + $newObj = ilObjectFactory::getInstanceByObjId($new_id, false); + } else { + $newObj = new ilObjWiki(); + $newObj->setType("wiki"); + $newObj->create(true); + } + + $newObj->setTitle($a_rec["Title"]); + $newObj->setDescription($a_rec["Description"]); + $newObj->setShortTitle($a_rec["Short"]); + $newObj->setStartPage($a_rec["StartPage"]); + $newObj->setRatingOverall($a_rec["RatingOverall"]); + $newObj->setRating($a_rec["Rating"]); + $newObj->setIntroduction($a_rec["Introduction"]); + $newObj->setPublicNotes($a_rec["PublicNotes"]); + + // >= 4.3 + if (isset($a_rec["PageToc"])) { + // $newObj->setImportantPages($a_rec["ImpPages"]); + $newObj->setPageToc($a_rec["PageToc"]); + $newObj->setRatingAsBlock($a_rec["RatingSide"]); + $newObj->setRatingForNewPages($a_rec["RatingNew"]); + $newObj->setRatingCategories($a_rec["RatingExt"]); + } + $newObj->setLinkMetadataValues($a_rec["LinkMdValues"]); + + $newObj->update(true); + $this->current_obj = $newObj; + $a_mapping->addMapping("Modules/Wiki", "wiki", $a_rec["Id"], $newObj->getId()); + $a_mapping->addMapping("Services/Object", "obj", $a_rec["Id"], $newObj->getId()); + $a_mapping->addMapping("Services/Rating", "rating_category_parent_id", $a_rec["Id"], $newObj->getId()); + $a_mapping->addMapping("Services/AdvancedMetaData", "parent", $a_rec["Id"], $newObj->getId()); + break; - case "wpg": - $wiki_id = $a_mapping->getMapping("Modules/Wiki", "wiki", $a_rec["WikiId"]); - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $wpage = new ilWikiPage(); - $wpage->setWikiId($wiki_id); - $wpage->setTitle($a_rec["Title"]); - - // >= 4.3 - if(isset($a_rec["Blocked"])) - { - $wpage->setBlocked($a_rec["Blocked"]); - $wpage->setRating($a_rec["Rating"]); - } - - $wpage->create(true); - - $a_mapping->addMapping("Modules/Wiki", "wpg", $a_rec["Id"], $wpage->getId()); - $a_mapping->addMapping("Services/COPage", "pg", "wpg:".$a_rec["Id"], "wpg:".$wpage->getId()); - $a_mapping->addMapping("Services/AdvancedMetaData", "advmd_sub_item", "advmd:wpg:".$a_rec["Id"], $wpage->getId()); - break; + case "wpg": + $wiki_id = $a_mapping->getMapping("Modules/Wiki", "wiki", $a_rec["WikiId"]); + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + $wpage = new ilWikiPage(); + $wpage->setWikiId($wiki_id); + $wpage->setTitle($a_rec["Title"]); + + // >= 4.3 + if (isset($a_rec["Blocked"])) { + $wpage->setBlocked($a_rec["Blocked"]); + $wpage->setRating($a_rec["Rating"]); + } + + $wpage->create(true); + + $a_mapping->addMapping("Modules/Wiki", "wpg", $a_rec["Id"], $wpage->getId()); + $a_mapping->addMapping("Services/COPage", "pg", "wpg:" . $a_rec["Id"], "wpg:" . $wpage->getId()); + $a_mapping->addMapping("Services/AdvancedMetaData", "advmd_sub_item", "advmd:wpg:" . $a_rec["Id"], $wpage->getId()); + break; - case "wiki_imp_page": - $wiki_id = $a_mapping->getMapping("Modules/Wiki", "wiki", $a_rec["WikiId"]); - $page_id = $a_mapping->getMapping("Modules/Wiki", "wpg", $a_rec["PageId"]); - if ($wiki_id > 0 && $page_id > 0 && is_object($this->current_obj) && $this->current_obj->getId() == $wiki_id) - { - $this->current_obj->addImportantPage($page_id, $a_rec["Ord"], $a_rec["Indent"]); - } - break; - } - } + case "wiki_imp_page": + $wiki_id = $a_mapping->getMapping("Modules/Wiki", "wiki", $a_rec["WikiId"]); + $page_id = $a_mapping->getMapping("Modules/Wiki", "wpg", $a_rec["PageId"]); + if ($wiki_id > 0 && $page_id > 0 && is_object($this->current_obj) && $this->current_obj->getId() == $wiki_id) { + $this->current_obj->addImportantPage($page_id, $a_rec["Ord"], $a_rec["Indent"]); + } + break; + } + } } -?> \ No newline at end of file diff --git a/Modules/Wiki/classes/class.ilWikiExportOrderTableGUI.php b/Modules/Wiki/classes/class.ilWikiExportOrderTableGUI.php index 6ff569de20f6db006449d90720e782f2621528cb..159e7c26c527bfcb163ca9e2ba51515f160dc3c3 100644 --- a/Modules/Wiki/classes/class.ilWikiExportOrderTableGUI.php +++ b/Modules/Wiki/classes/class.ilWikiExportOrderTableGUI.php @@ -1,103 +1,97 @@ - - * @version $Id$ - * - * @ingroup ModulesWiki - */ -class ilWikiExportOrderTableGUI extends ilTable2GUI -{ - protected $order; // [int] - - /** - * Constructor - * - * @param object $a_parent_obj - * @param string $a_parent_cmd - * @param bool $a_pdf_export - * @param array &$a_all_pages - * @param array $a_page_ids - */ - public function __construct($a_parent_obj, $a_parent_cmd = "", $a_pdf_export, array &$a_all_pages, array $a_page_ids) - { - global $DIC; +ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - - if(!(bool)$a_pdf_export) - { - $title = "wiki_show_print_view"; - $cmd = "printView"; - } - else - { - $title = "wiki_show_pdf_export"; - $cmd = "pdfExport"; - } - - $this->setTitle($lng->txt($title)); - - $this->addColumn($lng->txt("wiki_ordering"), "", "1"); - $this->addColumn($lng->txt("wiki_page")); - - $this->setFormAction($ilCtrl->getFormAction($this->getParentObject(), $this->getParentCmd())); - $this->addCommandButton($this->getParentCmd(), $lng->txt("refresh")); - - include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; - $button = ilSubmitButton::getInstance(); - $button->setOmitPreventDoubleSubmission((bool)$a_pdf_export); - $button->setCaption("continue"); - $button->setCommand($cmd); - $this->addCommandButtonInstance($button); - - $this->setRowTemplate("tpl.table_row_export_order.html", "Modules/Wiki"); - $this->setLimit(9999); - - $this->getItems($a_all_pages, $a_page_ids); - } - - /** - * Get contributors of wiki - */ - protected function getItems(array &$a_all_pages, array $a_page_ids) - { - $data = array(); - - foreach ($a_page_ids as $page_id) - { - $data[] = array( - "id" => $page_id, - "title" => $a_all_pages[$page_id]["title"] - ); - } - - $this->setData($data); - } - - /** - * Standard Version of Fill Row. Most likely to - * be overwritten by derived class. - */ - protected function fillRow($a_set) - { - $this->order += 10; - - $this->tpl->setVariable("PAGE_ID", $a_set["id"]); - $this->tpl->setVariable("TITLE", $a_set["title"]); - $this->tpl->setVariable("ORDER", $this->order); - - } - -} \ No newline at end of file +/* Copyright (c) 1998-2009 ILIAS open source, Extended GPL, see docs/LICENSE */ + +include_once("Services/Table/classes/class.ilTable2GUI.php"); + +/** + * TableGUI class for ordering pages to be printed/exported + * + * @author Jörg Lützenkirchen + * @version $Id$ + * + * @ingroup ModulesWiki + */ +class ilWikiExportOrderTableGUI extends ilTable2GUI +{ + protected $order; // [int] + + /** + * Constructor + * + * @param object $a_parent_obj + * @param string $a_parent_cmd + * @param bool $a_pdf_export + * @param array &$a_all_pages + * @param array $a_page_ids + */ + public function __construct($a_parent_obj, $a_parent_cmd = "", $a_pdf_export, array &$a_all_pages, array $a_page_ids) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + + if (!(bool) $a_pdf_export) { + $title = "wiki_show_print_view"; + $cmd = "printView"; + } else { + $title = "wiki_show_pdf_export"; + $cmd = "pdfExport"; + } + + $this->setTitle($lng->txt($title)); + + $this->addColumn($lng->txt("wiki_ordering"), "", "1"); + $this->addColumn($lng->txt("wiki_page")); + + $this->setFormAction($ilCtrl->getFormAction($this->getParentObject(), $this->getParentCmd())); + $this->addCommandButton($this->getParentCmd(), $lng->txt("refresh")); + + include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; + $button = ilSubmitButton::getInstance(); + $button->setOmitPreventDoubleSubmission((bool) $a_pdf_export); + $button->setCaption("continue"); + $button->setCommand($cmd); + $this->addCommandButtonInstance($button); + + $this->setRowTemplate("tpl.table_row_export_order.html", "Modules/Wiki"); + $this->setLimit(9999); + + $this->getItems($a_all_pages, $a_page_ids); + } + + /** + * Get contributors of wiki + */ + protected function getItems(array &$a_all_pages, array $a_page_ids) + { + $data = array(); + + foreach ($a_page_ids as $page_id) { + $data[] = array( + "id" => $page_id, + "title" => $a_all_pages[$page_id]["title"] + ); + } + + $this->setData($data); + } + + /** + * Standard Version of Fill Row. Most likely to + * be overwritten by derived class. + */ + protected function fillRow($a_set) + { + $this->order += 10; + + $this->tpl->setVariable("PAGE_ID", $a_set["id"]); + $this->tpl->setVariable("TITLE", $a_set["title"]); + $this->tpl->setVariable("ORDER", $this->order); + } +} diff --git a/Modules/Wiki/classes/class.ilWikiExporter.php b/Modules/Wiki/classes/class.ilWikiExporter.php index d021ceb88e97c488514b94a31b4d4909de10778c..950f49106ec49cb541a005245aeaa5c7bee53bc7 100644 --- a/Modules/Wiki/classes/class.ilWikiExporter.php +++ b/Modules/Wiki/classes/class.ilWikiExporter.php @@ -12,179 +12,167 @@ include_once("./Services/Export/classes/class.ilXmlExporter.php"); */ class ilWikiExporter extends ilXmlExporter { - private $ds; - - /** - * @var ilLogger - */ - protected $wiki_log; - - - /** - * Initialisation - */ - function init() - { - include_once("./Modules/Wiki/classes/class.ilWikiDataSet.php"); - $this->ds = new ilWikiDataSet(); - $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); - $this->ds->setDSPrefix("ds"); - - $this->wiki_log = ilLoggerFactory::getLogger('wiki'); - } - - - /** - * Get tail dependencies - * - * @param string entity - * @param string target release - * @param array ids - * @return array array of array with keys "component", entity", "ids" - */ - function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) - { - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $pg_ids = array(); - foreach ($a_ids as $id) - { - $pages = ilWikiPage::getAllWikiPages($id); - foreach ($pages as $p) - { - if (ilWikiPage::_exists("wpg", $p["id"])) - { - $pg_ids[] = "wpg:".$p["id"]; - } - } - } - - $deps = array ( - array( - "component" => "Services/COPage", - "entity" => "pg", - "ids" => $pg_ids), - array( - "component" => "Services/Rating", - "entity" => "rating_category", - "ids" => $a_ids - ) - ); - - $advmd_ids = array(); - foreach($a_ids as $id) - { - $rec_ids = $this->getActiveAdvMDRecords($id); - $this->wiki_log->debug("advmd rec ids: wiki id:".$id.", adv rec ids".print_r($rec_ids, true)); - if(sizeof($rec_ids)) - { - foreach($rec_ids as $rec_id) - { - $advmd_ids[] = $id.":".$rec_id; - } - } - } - - $this->wiki_log->debug("advmd ids: ".print_r($advmd_ids, true)); - - if(sizeof($advmd_ids)) - { - $deps[] = array( - "component" => "Services/AdvancedMetaData", - "entity" => "advmd", - "ids" => $advmd_ids - ); - } - - // style - $obj_ids = (is_array($a_ids)) - ? $a_ids - : array($a_ids); - $deps[] = array( - "component" => "Services/Style", - "entity" => "object_style", - "ids" => $obj_ids - ); - - // service settings - $deps[] = array( - "component" => "Services/Object", - "entity" => "common", - "ids" => $a_ids); - - return $deps; - } - - protected function getActiveAdvMDRecords($a_id) - { - include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecord.php'); - $active = array(); - // selected globals - $sel_globals = ilAdvancedMDRecord::getObjRecSelection($a_id, "wpg"); - - foreach(ilAdvancedMDRecord::_getActivatedRecordsByObjectType("wiki", "wpg") as $record_obj) - { - // local ones and globally activated for the object - if ($record_obj->getParentObject() == $a_id || in_array($record_obj->getRecordId(), $sel_globals)) - { - $active[] = $record_obj->getRecordId(); - } - } - - $this->wiki_log->debug("active md rec: ".print_r($active, true)); - - return $active; - } - - /** - * Get xml representation - * - * @param string entity - * @param string target release - * @param string id - * @return string xml string - */ - public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) - { - return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); - } - - /** - * Returns schema versions that the component can export to. - * ILIAS chooses the first one, that has min/max constraints which - * fit to the target release. Please put the newest on top. - * - * @return - */ - function getValidSchemaVersions($a_entity) - { - return array ( - "4.1.0" => array( - "namespace" => "http://www.ilias.de/Modules/Wiki/wiki/4_1", - "xsd_file" => "ilias_wiki_4_1.xsd", - "uses_dataset" => true, - "min" => "4.1.0", - "max" => "4.2.99"), - "4.3.0" => array( - "namespace" => "http://www.ilias.de/Modules/Wiki/wiki/4_3", - "xsd_file" => "ilias_wiki_4_3.xsd", - "uses_dataset" => true, - "min" => "4.3.0", - "max" => "4.3.99"), - "4.4.0" => array( - "namespace" => "http://www.ilias.de/Modules/Wiki/wiki/4_4", - "xsd_file" => "ilias_wiki_4_4.xsd", - "uses_dataset" => true, - "min" => "4.4.0", - "max" => "5.0.99"), - "5.1.0" => array( - "namespace" => "http://www.ilias.de/Modules/Wiki/wiki/5_1", - "xsd_file" => "ilias_wiki_5_1.xsd", - "uses_dataset" => true, - "min" => "5.1.0", - "max" => "") - ); - } - + private $ds; + + /** + * @var ilLogger + */ + protected $wiki_log; + + + /** + * Initialisation + */ + public function init() + { + include_once("./Modules/Wiki/classes/class.ilWikiDataSet.php"); + $this->ds = new ilWikiDataSet(); + $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); + $this->ds->setDSPrefix("ds"); + + $this->wiki_log = ilLoggerFactory::getLogger('wiki'); + } + + + /** + * Get tail dependencies + * + * @param string entity + * @param string target release + * @param array ids + * @return array array of array with keys "component", entity", "ids" + */ + public function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) + { + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + $pg_ids = array(); + foreach ($a_ids as $id) { + $pages = ilWikiPage::getAllWikiPages($id); + foreach ($pages as $p) { + if (ilWikiPage::_exists("wpg", $p["id"])) { + $pg_ids[] = "wpg:" . $p["id"]; + } + } + } + + $deps = array( + array( + "component" => "Services/COPage", + "entity" => "pg", + "ids" => $pg_ids), + array( + "component" => "Services/Rating", + "entity" => "rating_category", + "ids" => $a_ids + ) + ); + + $advmd_ids = array(); + foreach ($a_ids as $id) { + $rec_ids = $this->getActiveAdvMDRecords($id); + $this->wiki_log->debug("advmd rec ids: wiki id:" . $id . ", adv rec ids" . print_r($rec_ids, true)); + if (sizeof($rec_ids)) { + foreach ($rec_ids as $rec_id) { + $advmd_ids[] = $id . ":" . $rec_id; + } + } + } + + $this->wiki_log->debug("advmd ids: " . print_r($advmd_ids, true)); + + if (sizeof($advmd_ids)) { + $deps[] = array( + "component" => "Services/AdvancedMetaData", + "entity" => "advmd", + "ids" => $advmd_ids + ); + } + + // style + $obj_ids = (is_array($a_ids)) + ? $a_ids + : array($a_ids); + $deps[] = array( + "component" => "Services/Style", + "entity" => "object_style", + "ids" => $obj_ids + ); + + // service settings + $deps[] = array( + "component" => "Services/Object", + "entity" => "common", + "ids" => $a_ids); + + return $deps; + } + + protected function getActiveAdvMDRecords($a_id) + { + include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecord.php'); + $active = array(); + // selected globals + $sel_globals = ilAdvancedMDRecord::getObjRecSelection($a_id, "wpg"); + + foreach (ilAdvancedMDRecord::_getActivatedRecordsByObjectType("wiki", "wpg") as $record_obj) { + // local ones and globally activated for the object + if ($record_obj->getParentObject() == $a_id || in_array($record_obj->getRecordId(), $sel_globals)) { + $active[] = $record_obj->getRecordId(); + } + } + + $this->wiki_log->debug("active md rec: " . print_r($active, true)); + + return $active; + } + + /** + * Get xml representation + * + * @param string entity + * @param string target release + * @param string id + * @return string xml string + */ + public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) + { + return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); + } + + /** + * Returns schema versions that the component can export to. + * ILIAS chooses the first one, that has min/max constraints which + * fit to the target release. Please put the newest on top. + * + * @return + */ + public function getValidSchemaVersions($a_entity) + { + return array( + "4.1.0" => array( + "namespace" => "http://www.ilias.de/Modules/Wiki/wiki/4_1", + "xsd_file" => "ilias_wiki_4_1.xsd", + "uses_dataset" => true, + "min" => "4.1.0", + "max" => "4.2.99"), + "4.3.0" => array( + "namespace" => "http://www.ilias.de/Modules/Wiki/wiki/4_3", + "xsd_file" => "ilias_wiki_4_3.xsd", + "uses_dataset" => true, + "min" => "4.3.0", + "max" => "4.3.99"), + "4.4.0" => array( + "namespace" => "http://www.ilias.de/Modules/Wiki/wiki/4_4", + "xsd_file" => "ilias_wiki_4_4.xsd", + "uses_dataset" => true, + "min" => "4.4.0", + "max" => "5.0.99"), + "5.1.0" => array( + "namespace" => "http://www.ilias.de/Modules/Wiki/wiki/5_1", + "xsd_file" => "ilias_wiki_5_1.xsd", + "uses_dataset" => true, + "min" => "5.1.0", + "max" => "") + ); + } } - -?> \ No newline at end of file diff --git a/Modules/Wiki/classes/class.ilWikiFunctionsBlockGUI.php b/Modules/Wiki/classes/class.ilWikiFunctionsBlockGUI.php index efc3ce13697036b9757a1b19bc013eb036ee0116..a501bf814196a660d42fa370e7a1642f6d75276d 100644 --- a/Modules/Wiki/classes/class.ilWikiFunctionsBlockGUI.php +++ b/Modules/Wiki/classes/class.ilWikiFunctionsBlockGUI.php @@ -13,348 +13,347 @@ include_once("Services/Block/classes/class.ilBlockGUI.php"); */ class ilWikiFunctionsBlockGUI 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_functions")); - $this->allow_moving = false; - - $this->ref_id = (int) $_GET["ref_id"]; - } - - /** - * @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(); - - // info - $actions[] = array( - "txt" => $lng->txt("info_short"), - "href" => $ilCtrl->getLinkTargetByClass("ilobjwikigui", "infoScreen") - ); - - // 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"); - } - - - $actions = array(); - - // 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") - ); - - - // page lists - include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"); - $list = new ilAdvancedSelectionListGUI(); - $list->setListTitle($lng->txt("wiki_page_lists")); - $list->setStyle(ilAdvancedSelectionListGUI::STYLE_LINK); - $list->setId("wiki_pglists"); - - foreach ($actions as $a) - { - $list->addItem($a["txt"], "", - $a["href"]); - } - $tpl->setCurrentBlock("plain"); - $tpl->setVariable("PLAIN", $list->getHTML()); - $tpl->parseCurrentBlock(); - $tpl->touchBlock("item"); - - - // page actions - $list = new ilAdvancedSelectionListGUI(); - $list->setStyle(ilAdvancedSelectionListGUI::STYLE_LINK); - $list->setListTitle($lng->txt("wiki_page_actions")); - $list->setId("wiki_pgactions"); - - if ($ilAccess->checkAccess("write", "", $this->ref_id)) - { - // rating - if (ilObjWiki::_lookupRating($this->getPageObject()->getWikiId())) - { - if (!$this->getPageObject()->getRating()) - { - $list->addItem($lng->txt("wiki_activate_page_rating"), "", - $ilCtrl->getLinkTargetByClass("ilwikipagegui", "activateWikiPageRating")); - } else - { - $list->addItem($lng->txt("wiki_deactivate_page_rating"), "", - $ilCtrl->getLinkTargetByClass("ilwikipagegui", "deactivateWikiPageRating")); - } - } - } - - if ($ilAccess->checkAccess("write", "", $this->ref_id) || - $ilAccess->checkAccess("edit_page_meta", "", $this->ref_id)) - { - // unhide advmd? - include_once 'Services/AdvancedMetaData/classes/class.ilAdvancedMDRecord.php'; - if((bool)sizeof(ilAdvancedMDRecord::_getSelectedRecordsByObject("wiki", $this->ref_id, "wpg")) && - ilWikiPage::lookupAdvancedMetadataHidden($this->getPageObject()->getId())) - { - $list->addItem($lng->txt("wiki_unhide_meta_adv_records"), "", - $ilCtrl->getLinkTargetByClass("ilwikipagegui", "unhideAdvancedMetaData")); - } - } - - if (($ilAccess->checkAccess("edit_content", "", $this->ref_id) && !$this->getPageObject()->getBlocked()) - || $ilAccess->checkAccess("write", "", $this->ref_id)) - { - // rename - $list->addItem($lng->txt("wiki_rename_page"), "", - $ilCtrl->getLinkTargetByClass("ilwikipagegui", "renameWikiPage")); - } - - include_once("./Modules/Wiki/classes/class.ilWikiPerm.php"); - if (ilWikiPerm::check("activate_wiki_protection", $this->ref_id)) - { - // block/unblock - if ($this->getPageObject()->getBlocked()) - { - $list->addItem($lng->txt("wiki_unblock_page"), "", - $ilCtrl->getLinkTargetByClass("ilwikipagegui", "unblockWikiPage")); - } - else - { - $list->addItem($lng->txt("wiki_block_page"), "", - $ilCtrl->getLinkTargetByClass("ilwikipagegui", "blockWikiPage")); - } - } - - include_once("./Modules/Wiki/classes/class.ilWikiPerm.php"); - if (ilWikiPerm::check("delete_wiki_pages", $this->ref_id)) - { - // delete page - $st_page = ilObjWiki::_lookupStartPage($this->getPageObject()->getParentId()); - if ($st_page != $this->getPageObject()->getTitle()) - { - $list->addItem($lng->txt("wiki_delete_page"), "", - $ilCtrl->getLinkTargetByClass("ilwikipagegui", "deleteWikiPageConfirmationScreen")); - } - } - - if ($ilAccess->checkAccess("write", "", $this->ref_id)) - { - - include_once "Modules/Wiki/classes/class.ilWikiPageTemplate.php"; - $wpt = new ilWikiPageTemplate($this->getPageObject()->getParentId()); - if(!$wpt->isPageTemplate($this->getPageObject()->getId())) - { - $list->addItem($lng->txt("wiki_add_template"), "", - $ilCtrl->getLinkTargetByClass("ilwikipagetemplategui", "addPageTemplateFromPageAction")); - } - else - { - $list->addItem($lng->txt("wiki_remove_template_status"), "", - $ilCtrl->getLinkTargetByClass("ilwikipagetemplategui", "removePageTemplateFromPageAction")); - } - } - - if ($ilAccess->checkAccess("write", "", $this->ref_id) || - $ilAccess->checkAccess("read", "", $this->ref_id)) - { - $tpl->setCurrentBlock("plain"); - $tpl->setVariable("PLAIN", $list->getHTML()); - $tpl->parseCurrentBlock(); - $tpl->touchBlock("item"); - } - - // permissions -// if ($ilAccess->checkAccess('edit_permission', "", $this->ref_id)) -// { -// $actions[] = array( -// "txt" => $lng->txt("perm_settings"), -// "href" => $ilCtrl->getLinkTargetByClass(array("ilobjwikigui", "ilpermissiongui"), "perm") -// ); -// } - - $actions = array(); - - // settings - if ($ilAccess->checkAccess('write', "", $this->ref_id)) - { - $actions[] = array( - "txt" => $lng->txt("wiki_contributors"), - "href" => $ilCtrl->getLinkTargetByClass("ilobjwikigui", "listContributors") - ); - } - - // manage - if (ilWikiPerm::check("wiki_html_export", $this->ref_id)) - { - $actions[] = array( - "txt" => $lng->txt("wiki_html_export"), - "id" => "il_wiki_user_export", - "href" => $ilCtrl->getLinkTargetByClass("ilobjwikigui", "initUserHTMLExport") - ); - } - - // manage - if ($ilAccess->checkAccess('write', "", $this->ref_id)) - { - $actions[] = array( - "txt" => $lng->txt("settings"), - "href" => $ilCtrl->getLinkTargetByClass("ilobjwikigui", "editSettings") - ); - } - else if ($ilAccess->checkAccess('statistics_read', "", $this->ref_id)) - { - $actions[] = array( - "txt" => $lng->txt("statistics"), - "href" => $ilCtrl->getLinkTargetByClass(array("ilobjwikigui", "ilwikistatgui"), "initial") - ); - } - - foreach ($actions as $a) - { - $tpl->setCurrentBlock("action"); - $tpl->setVariable("HREF", $a["href"]); - $tpl->setVariable("TXT", $a["txt"]); - if ($a["id"] != "") - { - $tpl->setVariable("ACT_ID", "id='".$a["id"]."'"); - } - $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_functions")); + $this->allow_moving = false; + + $this->ref_id = (int) $_GET["ref_id"]; + } + + /** + * @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(); + + // info + $actions[] = array( + "txt" => $lng->txt("info_short"), + "href" => $ilCtrl->getLinkTargetByClass("ilobjwikigui", "infoScreen") + ); + + // 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"); + } + + + $actions = array(); + + // 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") + ); + + + // page lists + include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"); + $list = new ilAdvancedSelectionListGUI(); + $list->setListTitle($lng->txt("wiki_page_lists")); + $list->setStyle(ilAdvancedSelectionListGUI::STYLE_LINK); + $list->setId("wiki_pglists"); + + foreach ($actions as $a) { + $list->addItem( + $a["txt"], + "", + $a["href"] + ); + } + $tpl->setCurrentBlock("plain"); + $tpl->setVariable("PLAIN", $list->getHTML()); + $tpl->parseCurrentBlock(); + $tpl->touchBlock("item"); + + + // page actions + $list = new ilAdvancedSelectionListGUI(); + $list->setStyle(ilAdvancedSelectionListGUI::STYLE_LINK); + $list->setListTitle($lng->txt("wiki_page_actions")); + $list->setId("wiki_pgactions"); + + if ($ilAccess->checkAccess("write", "", $this->ref_id)) { + // rating + if (ilObjWiki::_lookupRating($this->getPageObject()->getWikiId())) { + if (!$this->getPageObject()->getRating()) { + $list->addItem( + $lng->txt("wiki_activate_page_rating"), + "", + $ilCtrl->getLinkTargetByClass("ilwikipagegui", "activateWikiPageRating") + ); + } else { + $list->addItem( + $lng->txt("wiki_deactivate_page_rating"), + "", + $ilCtrl->getLinkTargetByClass("ilwikipagegui", "deactivateWikiPageRating") + ); + } + } + } + + if ($ilAccess->checkAccess("write", "", $this->ref_id) || + $ilAccess->checkAccess("edit_page_meta", "", $this->ref_id)) { + // unhide advmd? + include_once 'Services/AdvancedMetaData/classes/class.ilAdvancedMDRecord.php'; + if ((bool) sizeof(ilAdvancedMDRecord::_getSelectedRecordsByObject("wiki", $this->ref_id, "wpg")) && + ilWikiPage::lookupAdvancedMetadataHidden($this->getPageObject()->getId())) { + $list->addItem( + $lng->txt("wiki_unhide_meta_adv_records"), + "", + $ilCtrl->getLinkTargetByClass("ilwikipagegui", "unhideAdvancedMetaData") + ); + } + } + + if (($ilAccess->checkAccess("edit_content", "", $this->ref_id) && !$this->getPageObject()->getBlocked()) + || $ilAccess->checkAccess("write", "", $this->ref_id)) { + // rename + $list->addItem( + $lng->txt("wiki_rename_page"), + "", + $ilCtrl->getLinkTargetByClass("ilwikipagegui", "renameWikiPage") + ); + } + + include_once("./Modules/Wiki/classes/class.ilWikiPerm.php"); + if (ilWikiPerm::check("activate_wiki_protection", $this->ref_id)) { + // block/unblock + if ($this->getPageObject()->getBlocked()) { + $list->addItem( + $lng->txt("wiki_unblock_page"), + "", + $ilCtrl->getLinkTargetByClass("ilwikipagegui", "unblockWikiPage") + ); + } else { + $list->addItem( + $lng->txt("wiki_block_page"), + "", + $ilCtrl->getLinkTargetByClass("ilwikipagegui", "blockWikiPage") + ); + } + } + + include_once("./Modules/Wiki/classes/class.ilWikiPerm.php"); + if (ilWikiPerm::check("delete_wiki_pages", $this->ref_id)) { + // delete page + $st_page = ilObjWiki::_lookupStartPage($this->getPageObject()->getParentId()); + if ($st_page != $this->getPageObject()->getTitle()) { + $list->addItem( + $lng->txt("wiki_delete_page"), + "", + $ilCtrl->getLinkTargetByClass("ilwikipagegui", "deleteWikiPageConfirmationScreen") + ); + } + } + + if ($ilAccess->checkAccess("write", "", $this->ref_id)) { + include_once "Modules/Wiki/classes/class.ilWikiPageTemplate.php"; + $wpt = new ilWikiPageTemplate($this->getPageObject()->getParentId()); + if (!$wpt->isPageTemplate($this->getPageObject()->getId())) { + $list->addItem( + $lng->txt("wiki_add_template"), + "", + $ilCtrl->getLinkTargetByClass("ilwikipagetemplategui", "addPageTemplateFromPageAction") + ); + } else { + $list->addItem( + $lng->txt("wiki_remove_template_status"), + "", + $ilCtrl->getLinkTargetByClass("ilwikipagetemplategui", "removePageTemplateFromPageAction") + ); + } + } + + if ($ilAccess->checkAccess("write", "", $this->ref_id) || + $ilAccess->checkAccess("read", "", $this->ref_id)) { + $tpl->setCurrentBlock("plain"); + $tpl->setVariable("PLAIN", $list->getHTML()); + $tpl->parseCurrentBlock(); + $tpl->touchBlock("item"); + } + + // permissions + // if ($ilAccess->checkAccess('edit_permission', "", $this->ref_id)) + // { + // $actions[] = array( + // "txt" => $lng->txt("perm_settings"), + // "href" => $ilCtrl->getLinkTargetByClass(array("ilobjwikigui", "ilpermissiongui"), "perm") + // ); + // } + + $actions = array(); + + // settings + if ($ilAccess->checkAccess('write', "", $this->ref_id)) { + $actions[] = array( + "txt" => $lng->txt("wiki_contributors"), + "href" => $ilCtrl->getLinkTargetByClass("ilobjwikigui", "listContributors") + ); + } + + // manage + if (ilWikiPerm::check("wiki_html_export", $this->ref_id)) { + $actions[] = array( + "txt" => $lng->txt("wiki_html_export"), + "id" => "il_wiki_user_export", + "href" => $ilCtrl->getLinkTargetByClass("ilobjwikigui", "initUserHTMLExport") + ); + } + + // manage + if ($ilAccess->checkAccess('write', "", $this->ref_id)) { + $actions[] = array( + "txt" => $lng->txt("settings"), + "href" => $ilCtrl->getLinkTargetByClass("ilobjwikigui", "editSettings") + ); + } elseif ($ilAccess->checkAccess('statistics_read', "", $this->ref_id)) { + $actions[] = array( + "txt" => $lng->txt("statistics"), + "href" => $ilCtrl->getLinkTargetByClass(array("ilobjwikigui", "ilwikistatgui"), "initial") + ); + } + + foreach ($actions as $a) { + $tpl->setCurrentBlock("action"); + $tpl->setVariable("HREF", $a["href"]); + $tpl->setVariable("TXT", $a["txt"]); + if ($a["id"] != "") { + $tpl->setVariable("ACT_ID", "id='" . $a["id"] . "'"); + } + $tpl->parseCurrentBlock(); + + $tpl->touchBlock("item"); + } + + + $this->setDataSection($tpl->get()); + } } - -?> diff --git a/Modules/Wiki/classes/class.ilWikiHTMLExport.php b/Modules/Wiki/classes/class.ilWikiHTMLExport.php index 06fcceaaa2ef7551c02045db351fcd714948521a..25a6b82f3f72297811250fed7b60256125e7d319 100644 --- a/Modules/Wiki/classes/class.ilWikiHTMLExport.php +++ b/Modules/Wiki/classes/class.ilWikiHTMLExport.php @@ -10,311 +10,306 @@ */ class ilWikiHTMLExport { - /** - * @var ilDB - */ - protected $db; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - protected $wiki; - const MODE_DEFAULT = "html"; - const MODE_USER = "user_html"; - protected $mode = self::MODE_DEFAULT; - - /** - * @var ilLogger - */ - protected $log; - - /** - * Constructor - * - * @param - * @return - */ - function __construct($a_wiki) - { - global $DIC; - - $this->db = $DIC->database(); - $this->user = $DIC->user(); - $this->lng = $DIC->language(); - $this->tabs = $DIC->tabs(); - $this->wiki = $a_wiki; - $this->log = ilLoggerFactory::getLogger('wiki'); - } - - /** - * Set mode - * - * @param int $a_val MODE_DEFAULT|MODE_USER - */ - function setMode($a_val) - { - $this->mode = $a_val; - } - - /** - * Get mode - * - * @return int MODE_DEFAULT|MODE_USER - */ - function getMode() - { - return $this->mode; - } - - /** - * Build export file - * - * @param - * @return string - */ - function buildExportFile() - { - $this->log->debug("buildExportFile..."); + /** + * @var ilDB + */ + protected $db; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + protected $wiki; + const MODE_DEFAULT = "html"; + const MODE_USER = "user_html"; + protected $mode = self::MODE_DEFAULT; + + /** + * @var ilLogger + */ + protected $log; + + /** + * Constructor + * + * @param + * @return + */ + public function __construct($a_wiki) + { + global $DIC; + + $this->db = $DIC->database(); + $this->user = $DIC->user(); + $this->lng = $DIC->language(); + $this->tabs = $DIC->tabs(); + $this->wiki = $a_wiki; + $this->log = ilLoggerFactory::getLogger('wiki'); + } + + /** + * Set mode + * + * @param int $a_val MODE_DEFAULT|MODE_USER + */ + public function setMode($a_val) + { + $this->mode = $a_val; + } + + /** + * Get mode + * + * @return int MODE_DEFAULT|MODE_USER + */ + public function getMode() + { + return $this->mode; + } + + /** + * Build export file + * + * @param + * @return string + */ + public function buildExportFile() + { + $this->log->debug("buildExportFile..."); //init the mathjax rendering for HTML export - include_once './Services/MathJax/classes/class.ilMathJax.php'; - ilMathJax::getInstance()->init(ilMathJax::PURPOSE_EXPORT); - - if ($this->getMode() == self::MODE_USER) - { - $ilDB = $this->db; - $ilUser = $this->user; - include_once("./Modules/Wiki/classes/class.ilWikiUserHTMLExport.php"); - $this->user_html_exp = new ilWikiUserHTMLExport($this->wiki, $ilDB, $ilUser); - } - - $ascii_name = str_replace(" ", "_", ilUtil::getASCIIFilename($this->wiki->getTitle())); - - // create export file - include_once("./Services/Export/classes/class.ilExport.php"); - ilExport::_createExportDirectory($this->wiki->getId(), $this->getMode(), "wiki"); - $exp_dir = - ilExport::_getExportDirectory($this->wiki->getId(), $this->getMode(), "wiki"); - - if ($this->getMode() == self::MODE_USER) - { - ilUtil::delDir($exp_dir, true); - } - - if ($this->getMode() == self::MODE_USER) - { - $this->subdir = $ascii_name; - } - else - { - $this->subdir = $this->wiki->getType()."_".$this->wiki->getId(); - } - $this->export_dir = $exp_dir."/".$this->subdir; -//echo "+".$this->export_dir."+"; - // initialize temporary target directory - ilUtil::delDir($this->export_dir); - ilUtil::makeDir($this->export_dir); - - $this->log->debug("export directory: ".$this->export_dir); - - // system style html exporter - include_once("./Services/Style/System/classes/class.ilSystemStyleHTMLExport.php"); - $this->sys_style_html_export = new ilSystemStyleHTMLExport($this->export_dir); - $this->sys_style_html_export->addImage("icon_wiki.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($this->export_dir); - $this->co_page_html_export->setContentStyleId( - $this->wiki->getStyleSheetId()); - $this->co_page_html_export->createDirectories(); - $this->co_page_html_export->exportStyles(); - $this->co_page_html_export->exportSupportScripts(); - - // export pages - $this->log->debug("export pages"); - $this->exportHTMLPages(); - - $date = time(); - $zip_file_name = ($this->getMode() == self::MODE_USER) - ? $ascii_name.".zip" - : $date."__".IL_INST_ID."__".$this->wiki->getType()."_".$this->wiki->getId().".zip"; - - // zip everything - if (true) - { - // zip it all - $zip_file = ilExport::_getExportDirectory($this->wiki->getId(), $this->getMode(), "wiki"). - "/".$zip_file_name; - $this->log->debug("zip: ".$zip_file); - ilUtil::zip($this->export_dir, $zip_file); - ilUtil::delDir($this->export_dir); - } - return $zip_file; - } - - /** - * Export all pages - */ - function exportHTMLPages() - { - $pages = ilWikiPage::getAllWikiPages($this->wiki->getId()); - - include_once("./Services/COPage/classes/class.ilPageContentUsage.php"); - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $cnt = 0; - foreach ($pages as $page) - { - $this->log->debug("page: ".$page["id"]); - if (ilWikiPage::_exists("wpg", $page["id"])) - { - $this->log->debug("export page"); - $this->exportPageHTML($page["id"]); - $this->log->debug("collect page elements"); - $this->co_page_html_export->collectPageElements("wpg:pg", $page["id"]); - } - - if ($this->getMode() == self::MODE_USER) - { - $cnt++; - $this->log->debug("update status: ".$cnt); - $this->user_html_exp->updateStatus((int) (50 / count($pages) * $cnt) ,ilWikiUserHTMLExport::RUNNING); - } - - } - $this->co_page_html_export->exportPageElements($this->updateUserHTMLStatusForPageElements); - } - - /** - * Callback for updating the export status during elements export (media objects, files, ...) - * - * @param - */ - function updateUserHTMLStatusForPageElements($a_total, $a_cnt) - { - if ($this->getMode() == self::MODE_USER) - { - $this->user_html_exp->updateStatus((int) 50 + (50 / count($a_total) * $a_cnt) ,ilWikiUserHTMLExport::RUNNING); - } - } - - - /** - * Export page html - */ - function exportPageHTML($a_page_id) - { - $ilUser = $this->user; - $lng = $this->lng; - $ilTabs = $this->tabs; - - $ilTabs->clearTargets(); - - $this->tpl = $this->co_page_html_export->getPreparedMainTemplate(); - - $this->tpl->getStandardTemplate(); - $file = $this->export_dir."/wpg_".$a_page_id.".html"; - // return if file is already existing - if (@is_file($file)) - { - $this->log->debug("file already exists"); - return; - } - - // page - $this->log->debug("init page gui"); - include_once("./Modules/Wiki/classes/class.ilWikiPageGUI.php"); - $wpg_gui = new ilWikiPageGUI($a_page_id); - $wpg_gui->setOutputMode("offline"); - $page_content = $wpg_gui->showPage(); - - // export template: page content - $this->log->debug("init page gui"); - $ep_tpl = new ilTemplate("tpl.export_page.html", true, true, - "Modules/Wiki"); - $ep_tpl->setVariable("PAGE_CONTENT", $page_content); - - // export template: right content - include_once("./Modules/Wiki/classes/class.ilWikiImportantPagesBlockGUI.php"); - $bl = new ilWikiImportantPagesBlockGUI(); - $ep_tpl->setVariable("RIGHT_CONTENT", $bl->getHTML(true)); - - // workaround -// $this->tpl->setVariable("MAINMENU", "
"); - $this->tpl->setVariable("MAINMENU", ""); - - $this->log->debug("set title"); - $this->tpl->setTitle($this->wiki->getTitle()); - $this->tpl->setTitleIcon("./images/icon_wiki.svg", - $lng->txt("obj_wiki")); - - $this->tpl->setContent($ep_tpl->get()); - //$this->tpl->fillMainContent(); - $content = $this->tpl->get("DEFAULT", false, false, false, - true, true, true); - -//echo htmlentities($content); exit; - // open file - $this->log->debug("write file: ".$file); - if (!($fp = @fopen($file,"w+"))) - { - $this->log->error("Could not open ".$file." for writing."); - include_once("./Modules/Wiki/exceptions/class.ilWikiExportException.php"); - throw new ilWikiExportException("Could not open \"".$file."\" for writing."); - } - - // set file permissions - $this->log->debug("set permissions"); - chmod($file, 0770); - - // write xml data into the file - fwrite($fp, $content); - - // close file - fclose($fp); - - if ($this->wiki->getStartPage() == $wpg_gui->getPageObject()->getTitle()) - { - copy($file, $this->export_dir."/index.html"); - } - } - - /** - * Get user export file - * - * @param - * @return - */ - function getUserExportFile() - { - include_once("./Services/Export/classes/class.ilExport.php"); - $exp_dir = - ilExport::_getExportDirectory($this->wiki->getId(), $this->getMode(), "wiki"); - $this->log->debug("dir: ".$exp_dir); - foreach (new DirectoryIterator($exp_dir) as $fileInfo) - { - $this->log->debug("file: ".$fileInfo->getFilename()); - if (pathinfo($fileInfo->getFilename(),PATHINFO_EXTENSION) == "zip") - { - $this->log->debug("return: ".$exp_dir."/".$fileInfo->getFilename()); - return $exp_dir."/".$fileInfo->getFilename(); - } - } - return false; - } - - + include_once './Services/MathJax/classes/class.ilMathJax.php'; + ilMathJax::getInstance()->init(ilMathJax::PURPOSE_EXPORT); + + if ($this->getMode() == self::MODE_USER) { + $ilDB = $this->db; + $ilUser = $this->user; + include_once("./Modules/Wiki/classes/class.ilWikiUserHTMLExport.php"); + $this->user_html_exp = new ilWikiUserHTMLExport($this->wiki, $ilDB, $ilUser); + } + + $ascii_name = str_replace(" ", "_", ilUtil::getASCIIFilename($this->wiki->getTitle())); + + // create export file + include_once("./Services/Export/classes/class.ilExport.php"); + ilExport::_createExportDirectory($this->wiki->getId(), $this->getMode(), "wiki"); + $exp_dir = + ilExport::_getExportDirectory($this->wiki->getId(), $this->getMode(), "wiki"); + + if ($this->getMode() == self::MODE_USER) { + ilUtil::delDir($exp_dir, true); + } + + if ($this->getMode() == self::MODE_USER) { + $this->subdir = $ascii_name; + } else { + $this->subdir = $this->wiki->getType() . "_" . $this->wiki->getId(); + } + $this->export_dir = $exp_dir . "/" . $this->subdir; + //echo "+".$this->export_dir."+"; + // initialize temporary target directory + ilUtil::delDir($this->export_dir); + ilUtil::makeDir($this->export_dir); + + $this->log->debug("export directory: " . $this->export_dir); + + // system style html exporter + include_once("./Services/Style/System/classes/class.ilSystemStyleHTMLExport.php"); + $this->sys_style_html_export = new ilSystemStyleHTMLExport($this->export_dir); + $this->sys_style_html_export->addImage("icon_wiki.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($this->export_dir); + $this->co_page_html_export->setContentStyleId( + $this->wiki->getStyleSheetId() + ); + $this->co_page_html_export->createDirectories(); + $this->co_page_html_export->exportStyles(); + $this->co_page_html_export->exportSupportScripts(); + + // export pages + $this->log->debug("export pages"); + $this->exportHTMLPages(); + + $date = time(); + $zip_file_name = ($this->getMode() == self::MODE_USER) + ? $ascii_name . ".zip" + : $date . "__" . IL_INST_ID . "__" . $this->wiki->getType() . "_" . $this->wiki->getId() . ".zip"; + + // zip everything + if (true) { + // zip it all + $zip_file = ilExport::_getExportDirectory($this->wiki->getId(), $this->getMode(), "wiki") . + "/" . $zip_file_name; + $this->log->debug("zip: " . $zip_file); + ilUtil::zip($this->export_dir, $zip_file); + ilUtil::delDir($this->export_dir); + } + return $zip_file; + } + + /** + * Export all pages + */ + public function exportHTMLPages() + { + $pages = ilWikiPage::getAllWikiPages($this->wiki->getId()); + + include_once("./Services/COPage/classes/class.ilPageContentUsage.php"); + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $cnt = 0; + foreach ($pages as $page) { + $this->log->debug("page: " . $page["id"]); + if (ilWikiPage::_exists("wpg", $page["id"])) { + $this->log->debug("export page"); + $this->exportPageHTML($page["id"]); + $this->log->debug("collect page elements"); + $this->co_page_html_export->collectPageElements("wpg:pg", $page["id"]); + } + + if ($this->getMode() == self::MODE_USER) { + $cnt++; + $this->log->debug("update status: " . $cnt); + $this->user_html_exp->updateStatus((int) (50 / count($pages) * $cnt), ilWikiUserHTMLExport::RUNNING); + } + } + $this->co_page_html_export->exportPageElements($this->updateUserHTMLStatusForPageElements); + } + + /** + * Callback for updating the export status during elements export (media objects, files, ...) + * + * @param + */ + public function updateUserHTMLStatusForPageElements($a_total, $a_cnt) + { + if ($this->getMode() == self::MODE_USER) { + $this->user_html_exp->updateStatus((int) 50 + (50 / count($a_total) * $a_cnt), ilWikiUserHTMLExport::RUNNING); + } + } + + + /** + * Export page html + */ + public function exportPageHTML($a_page_id) + { + $ilUser = $this->user; + $lng = $this->lng; + $ilTabs = $this->tabs; + + $ilTabs->clearTargets(); + + $this->tpl = $this->co_page_html_export->getPreparedMainTemplate(); + + $this->tpl->getStandardTemplate(); + $file = $this->export_dir . "/wpg_" . $a_page_id . ".html"; + // return if file is already existing + if (@is_file($file)) { + $this->log->debug("file already exists"); + return; + } + + // page + $this->log->debug("init page gui"); + include_once("./Modules/Wiki/classes/class.ilWikiPageGUI.php"); + $wpg_gui = new ilWikiPageGUI($a_page_id); + $wpg_gui->setOutputMode("offline"); + $page_content = $wpg_gui->showPage(); + + // export template: page content + $this->log->debug("init page gui"); + $ep_tpl = new ilTemplate( + "tpl.export_page.html", + true, + true, + "Modules/Wiki" + ); + $ep_tpl->setVariable("PAGE_CONTENT", $page_content); + + // export template: right content + include_once("./Modules/Wiki/classes/class.ilWikiImportantPagesBlockGUI.php"); + $bl = new ilWikiImportantPagesBlockGUI(); + $ep_tpl->setVariable("RIGHT_CONTENT", $bl->getHTML(true)); + + // workaround + // $this->tpl->setVariable("MAINMENU", "
"); + $this->tpl->setVariable("MAINMENU", ""); + + $this->log->debug("set title"); + $this->tpl->setTitle($this->wiki->getTitle()); + $this->tpl->setTitleIcon( + "./images/icon_wiki.svg", + $lng->txt("obj_wiki") + ); + + $this->tpl->setContent($ep_tpl->get()); + //$this->tpl->fillMainContent(); + $content = $this->tpl->get( + "DEFAULT", + false, + false, + false, + true, + true, + true + ); + + //echo htmlentities($content); exit; + // open file + $this->log->debug("write file: " . $file); + if (!($fp = @fopen($file, "w+"))) { + $this->log->error("Could not open " . $file . " for writing."); + include_once("./Modules/Wiki/exceptions/class.ilWikiExportException.php"); + throw new ilWikiExportException("Could not open \"" . $file . "\" for writing."); + } + + // set file permissions + $this->log->debug("set permissions"); + chmod($file, 0770); + + // write xml data into the file + fwrite($fp, $content); + + // close file + fclose($fp); + + if ($this->wiki->getStartPage() == $wpg_gui->getPageObject()->getTitle()) { + copy($file, $this->export_dir . "/index.html"); + } + } + + /** + * Get user export file + * + * @param + * @return + */ + public function getUserExportFile() + { + include_once("./Services/Export/classes/class.ilExport.php"); + $exp_dir = + ilExport::_getExportDirectory($this->wiki->getId(), $this->getMode(), "wiki"); + $this->log->debug("dir: " . $exp_dir); + foreach (new DirectoryIterator($exp_dir) as $fileInfo) { + $this->log->debug("file: " . $fileInfo->getFilename()); + if (pathinfo($fileInfo->getFilename(), PATHINFO_EXTENSION) == "zip") { + $this->log->debug("return: " . $exp_dir . "/" . $fileInfo->getFilename()); + return $exp_dir . "/" . $fileInfo->getFilename(); + } + } + return false; + } } -?> diff --git a/Modules/Wiki/classes/class.ilWikiHandlerGUI.php b/Modules/Wiki/classes/class.ilWikiHandlerGUI.php index c3c6f02655825d6ccbf186ce39502f9d149089c0..da76d41b9952e59f4bded07e2c8ebd5c28cc9cdf 100755 --- a/Modules/Wiki/classes/class.ilWikiHandlerGUI.php +++ b/Modules/Wiki/classes/class.ilWikiHandlerGUI.php @@ -1,24 +1,24 @@ lng = $DIC->language(); - $this->access = $DIC->access(); - $this->tpl = $DIC["tpl"]; - $this->nav_history = $DIC["ilNavigationHistory"]; - $ilCtrl = $DIC->ctrl(); - - // initialisation stuff - $this->ctrl = $ilCtrl; - - } - - /** - * execute command - */ - function executeCommand() - { - $lng = $this->lng; - $ilAccess = $this->access; - $tpl = $this->tpl; - $ilNavigationHistory = $this->nav_history; - - $cmd = $this->ctrl->getCmd(); - $next_class = $this->ctrl->getNextClass($this); - if ($next_class == "") - { - $this->ctrl->setCmdClass("ilobjwikigui"); - $next_class = $this->ctrl->getNextClass($this); - } - - // add entry to navigation history - if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - $obj_id = ilObject::_lookupObjId($_GET["ref_id"]); - $title = ilObject::_lookupTitle($obj_id); - - if ($_GET["page"] != "") - { - $page = $_GET["page"]; - } - else - { - include_once("./Modules/Wiki/classes/class.ilObjWiki.php"); - $page = ilObjWiki::_lookupStartPage($obj_id); - } - - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - if (ilWikiPage::exists($obj_id, $page)) - { - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - - $add = "_".rawurlencode($page); - - $page_id = ilWikiPage::getPageIdForTitle($obj_id, $page); - $ptitle = ilWikiPage::lookupTitle($page_id); - - $title.= ": ".$ptitle; - - $append = ($_GET["page"] != "") - ? "_".ilWikiUtil::makeUrlTitle($page) - : ""; - include_once('./Services/Link/classes/class.ilLink.php'); - $goto = ilLink::_getStaticLink($_GET["ref_id"], "wiki", - true, $append); -//var_dump($goto); - $ilNavigationHistory->addItem($_GET["ref_id"], - "./goto.php?target=wiki_".$_GET["ref_id"].$add, "wiki", - $title, $page_id, $goto); - } - } - - switch ($next_class) - { - case 'ilobjwikigui': - require_once "./Modules/Wiki/classes/class.ilObjWikiGUI.php"; - $mc_gui = new ilObjWikiGUI("", (int) $_GET["ref_id"], true, false); - $this->ctrl->forwardCommand($mc_gui); - break; - } - - $tpl->show(); - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilNavigationHistory + */ + protected $nav_history; + + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->tpl = $DIC["tpl"]; + $this->nav_history = $DIC["ilNavigationHistory"]; + $ilCtrl = $DIC->ctrl(); + + // initialisation stuff + $this->ctrl = $ilCtrl; + } + + /** + * execute command + */ + public function executeCommand() + { + $lng = $this->lng; + $ilAccess = $this->access; + $tpl = $this->tpl; + $ilNavigationHistory = $this->nav_history; + + $cmd = $this->ctrl->getCmd(); + $next_class = $this->ctrl->getNextClass($this); + if ($next_class == "") { + $this->ctrl->setCmdClass("ilobjwikigui"); + $next_class = $this->ctrl->getNextClass($this); + } + + // add entry to navigation history + if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) { + $obj_id = ilObject::_lookupObjId($_GET["ref_id"]); + $title = ilObject::_lookupTitle($obj_id); + + if ($_GET["page"] != "") { + $page = $_GET["page"]; + } else { + include_once("./Modules/Wiki/classes/class.ilObjWiki.php"); + $page = ilObjWiki::_lookupStartPage($obj_id); + } + + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + if (ilWikiPage::exists($obj_id, $page)) { + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + + $add = "_" . rawurlencode($page); + + $page_id = ilWikiPage::getPageIdForTitle($obj_id, $page); + $ptitle = ilWikiPage::lookupTitle($page_id); + + $title.= ": " . $ptitle; + + $append = ($_GET["page"] != "") + ? "_" . ilWikiUtil::makeUrlTitle($page) + : ""; + include_once('./Services/Link/classes/class.ilLink.php'); + $goto = ilLink::_getStaticLink( + $_GET["ref_id"], + "wiki", + true, + $append + ); + //var_dump($goto); + $ilNavigationHistory->addItem( + $_GET["ref_id"], + "./goto.php?target=wiki_" . $_GET["ref_id"] . $add, + "wiki", + $title, + $page_id, + $goto + ); + } + } + + switch ($next_class) { + case 'ilobjwikigui': + require_once "./Modules/Wiki/classes/class.ilObjWikiGUI.php"; + $mc_gui = new ilObjWikiGUI("", (int) $_GET["ref_id"], true, false); + $this->ctrl->forwardCommand($mc_gui); + break; + } + + $tpl->show(); + } } diff --git a/Modules/Wiki/classes/class.ilWikiImportantPagesBlockGUI.php b/Modules/Wiki/classes/class.ilWikiImportantPagesBlockGUI.php index c3bbb51013ab171e1c3656f728a779c1d6c3f9e7..f95ffafb7a7bf93407dcf0564ce3d1b3ae7224bd 100644 --- a/Modules/Wiki/classes/class.ilWikiImportantPagesBlockGUI.php +++ b/Modules/Wiki/classes/class.ilWikiImportantPagesBlockGUI.php @@ -14,151 +14,142 @@ include_once("Services/Block/classes/class.ilBlockGUI.php"); */ class ilWikiImportantPagesBlockGUI extends ilBlockGUI { - static $block_type = "wikiimppages"; - static $st_data; - protected $export = false; - - /** - * Constructor - */ - function __construct() - { - global $DIC; + public static $block_type = "wikiimppages"; + public static $st_data; + protected $export = false; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - parent::__construct(); - - $lng->loadLanguageModule("wiki"); - $this->setEnableNumInfo(false); - - $this->setTitle($lng->txt("wiki_navigation")); - $this->allow_moving = false; - } + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + parent::__construct(); + + $lng->loadLanguageModule("wiki"); + $this->setEnableNumInfo(false); + + $this->setTitle($lng->txt("wiki_navigation")); + $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($a_export = false) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; + /** + * Get bloch HTML code. + */ + public function getHTML($a_export = false) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; - $this->export = $a_export; + $this->export = $a_export; - include_once './Modules/Wiki/classes/class.ilWikiPerm.php'; - if (!$this->export && ilWikiPerm::check("edit_wiki_navigation", $_GET["ref_id"])) - { - $this->addBlockCommand( - $ilCtrl->getLinkTargetByClass("ilobjwikigui", "editImportantPages"), - $lng->txt("edit"), "_top"); - } - - return parent::getHTML(); - } + include_once './Modules/Wiki/classes/class.ilWikiPerm.php'; + if (!$this->export && ilWikiPerm::check("edit_wiki_navigation", $_GET["ref_id"])) { + $this->addBlockCommand( + $ilCtrl->getLinkTargetByClass("ilobjwikigui", "editImportantPages"), + $lng->txt("edit"), + "_top" + ); + } + + return parent::getHTML(); + } - /** - * Fill data section - */ - function fillDataSection() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilAccess = $this->access; - - $tpl = new ilTemplate("tpl.wiki_imp_pages_block.html", true, true, "Modules/Wiki"); + /** + * Fill data section + */ + public function fillDataSection() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilAccess = $this->access; + + $tpl = new ilTemplate("tpl.wiki_imp_pages_block.html", true, true, "Modules/Wiki"); - $cpar[0] = $cpar[1] = 0; - include_once("./Services/UIComponent/NestedList/classes/class.ilNestedList.php"); - - $list = new ilNestedList(); - $list->setItemClass("ilWikiBlockItem"); - $list->setListClass("ilWikiBlockList"); - $list->setListClass("ilWikiBlockListNoIndent", 1); - - $cnt = 1; - $title = ilObjWiki::_lookupStartPage(ilObject::_lookupObjId($_GET["ref_id"])); - if (!$this->export) - { - $list->addListNode("

".$title."

", 1, 0); - } - else - { - $list->addListNode("

".$title."

", 1, 0); - } - $cpar[0] = 1; - - $ipages = ilObjWiki::_lookupImportantPagesList(ilObject::_lookupObjId($_GET["ref_id"])); - foreach ($ipages as $p) - { - $cnt++; - $title = ilWikiPage::lookupTitle($p["page_id"]); - if (!$this->export) - { - $list->addListNode("

".$title."

", $cnt, (int) $cpar[$p["indent"] - 1]); - } - else - { - $list->addListNode("

".$title."

", $cnt, (int) $cpar[$p["indent"] - 1]); - } - $cpar[$p["indent"]] = $cnt; - } - - $this->setDataSection($list->getHTML()); - } + $cpar[0] = $cpar[1] = 0; + include_once("./Services/UIComponent/NestedList/classes/class.ilNestedList.php"); + + $list = new ilNestedList(); + $list->setItemClass("ilWikiBlockItem"); + $list->setListClass("ilWikiBlockList"); + $list->setListClass("ilWikiBlockListNoIndent", 1); + + $cnt = 1; + $title = ilObjWiki::_lookupStartPage(ilObject::_lookupObjId($_GET["ref_id"])); + if (!$this->export) { + $list->addListNode("

" . $title . "

", 1, 0); + } else { + $list->addListNode("

" . $title . "

", 1, 0); + } + $cpar[0] = 1; + + $ipages = ilObjWiki::_lookupImportantPagesList(ilObject::_lookupObjId($_GET["ref_id"])); + foreach ($ipages as $p) { + $cnt++; + $title = ilWikiPage::lookupTitle($p["page_id"]); + if (!$this->export) { + $list->addListNode("

" . $title . "

", $cnt, (int) $cpar[$p["indent"] - 1]); + } else { + $list->addListNode("

" . $title . "

", $cnt, (int) $cpar[$p["indent"] - 1]); + } + $cpar[$p["indent"]] = $cnt; + } + + $this->setDataSection($list->getHTML()); + } } - -?> diff --git a/Modules/Wiki/classes/class.ilWikiImporter.php b/Modules/Wiki/classes/class.ilWikiImporter.php index 95a6d4a005bda0f150e434de7146f22fb376cdac..9f94637de632d627e6f65de89b42855967daa1e3 100644 --- a/Modules/Wiki/classes/class.ilWikiImporter.php +++ b/Modules/Wiki/classes/class.ilWikiImporter.php @@ -13,47 +13,48 @@ include_once("./Services/Export/classes/class.ilXmlImporter.php"); class ilWikiImporter extends ilXmlImporter { - /** - * Initialisation - */ - function init() - { - include_once("./Modules/Wiki/classes/class.ilWikiDataSet.php"); - $this->ds = new ilWikiDataSet(); - $this->ds->setDSPrefix("ds"); - } - - - /** - * Import XML - * - * @param - * @return - */ - function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) - { - 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) - { - $wpg_map = $a_mapping->getMappingsOfEntity("Modules/Wiki", "wpg"); - - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - foreach ($wpg_map as $wpg_id) - { - $wiki_id = ilWikiPage::lookupWikiId($wpg_id); - ilWikiPage::_writeParentId("wpg", $wpg_id, $wiki_id); - } - } - + /** + * Initialisation + */ + public function init() + { + include_once("./Modules/Wiki/classes/class.ilWikiDataSet.php"); + $this->ds = new ilWikiDataSet(); + $this->ds->setDSPrefix("ds"); + } + + + /** + * Import XML + * + * @param + * @return + */ + public function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) + { + 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) + { + $wpg_map = $a_mapping->getMappingsOfEntity("Modules/Wiki", "wpg"); + + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + foreach ($wpg_map as $wpg_id) { + $wiki_id = ilWikiPage::lookupWikiId($wpg_id); + ilWikiPage::_writeParentId("wpg", $wpg_id, $wiki_id); + } + } } - -?> \ No newline at end of file diff --git a/Modules/Wiki/classes/class.ilWikiNewsRendererGUI.php b/Modules/Wiki/classes/class.ilWikiNewsRendererGUI.php index e3d912eada24db499e029eb6a30d278b3711ce34..ce6ce65506601ac4f92975af7ab0b847eafaf039 100644 --- a/Modules/Wiki/classes/class.ilWikiNewsRendererGUI.php +++ b/Modules/Wiki/classes/class.ilWikiNewsRendererGUI.php @@ -12,29 +12,24 @@ include_once("./Services/News/classes/class.ilNewsDefaultRendererGUI.php"); */ class ilWikiNewsRendererGUI extends ilNewsDefaultRendererGUI { - /** - * Get object link - * - * @return string link href url - */ - function getObjectLink() - { - include_once("./Services/Link/classes/class.ilLink.php"); - $n = $this->getNewsItem(); - if ($n->getContextSubObjType() == "wpg" - && $n->getContextSubObjId() > 0) - { - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $wptitle = ilWikiPage::lookupTitle($n->getContextSubObjId()); - if ($wptitle != "") - { - $add = "_".ilWikiUtil::makeUrlTitle($wptitle); - } - } - - 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(); + if ($n->getContextSubObjType() == "wpg" + && $n->getContextSubObjId() > 0) { + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + $wptitle = ilWikiPage::lookupTitle($n->getContextSubObjId()); + if ($wptitle != "") { + $add = "_" . ilWikiUtil::makeUrlTitle($wptitle); + } + } + return ilLink::_getLink($this->getNewsRefId(), "", array(), $add); + } } - -?> \ No newline at end of file diff --git a/Modules/Wiki/classes/class.ilWikiPage.php b/Modules/Wiki/classes/class.ilWikiPage.php index 7156007626c12f5fa79291222003eb869201fde7..5ba2efd0f6979b9648974774906aaf86b0c4b7a9 100755 --- a/Modules/Wiki/classes/class.ilWikiPage.php +++ b/Modules/Wiki/classes/class.ilWikiPage.php @@ -5,1134 +5,1128 @@ include_once("./Services/COPage/classes/class.ilPageObject.php"); include_once("./Modules/Wiki/classes/class.ilWikiUtil.php"); /** * Class ilWikiPage -* -* @author Alex Killing +* +* @author Alex Killing * @version $Id$ * * @ingroup ModulesWiki */ class ilWikiPage extends ilPageObject { - protected $blocked = false; - protected $rating = false; // [boo,] - protected $hide_adv_md = false; // [bool] - - /** - * Get parent type - * - * @return string parent type - */ - function getParentType() - { - return "wpg"; - } - - /** - * After constructor - * - * @param - * @return - */ - function afterConstructor() - { - $this->getPageConfig()->configureByObjectId($this->getParentId()); - } - - /** - * Set Title. - * - * @param string $a_title Title - */ - function setTitle($a_title) - { - $this->title = ilWikiUtil::makeDbTitle($a_title); - } - - /** - * Get Title. - * - * @return string Title - */ - function getTitle() - { - return $this->title; - } - - /** - * Set Wiki Object Id. - * - * @param int $a_wikiid Wiki Object Id - */ - function setWikiId($a_wikiid) - { - $this->setParentId($a_wikiid); - } - - /** - * Get Wiki Object Id. - * - * @return int Wiki Object Id - */ - function getWikiId() - { - return $this->getParentId(); - } - - /** - * Set Wiki Ref Id. - * - * @param int $a_wiki_ref_id Wiki Ref Id - */ - function setWikiRefId($a_wiki_ref_id) - { - $this->parent_ref_id = $a_wiki_ref_id; - } - - /** - * Get Wiki Ref Id. - * - * @return int Wiki Ref Id - */ - function getWikiRefId() - { - return $this->parent_ref_id; - } - - /** - * Set blocked - * - * @param boolean $a_val blocked - */ - public function setBlocked($a_val) - { - $this->blocked = $a_val; - } - - /** - * Get blocked - * - * @return boolean blocked - */ - public function getBlocked() - { - return $this->blocked; - } - - /** - * Set rating - * - * @param boolean $a_val - */ - public function setRating($a_val) - { - $this->rating = (bool)$a_val; - } - - /** - * Get rating - * - * @return boolean - */ - public function getRating() - { - return $this->rating; - } - - /** - * Toggle adv md visibility - * - * @param boolean $a_val - */ - public function hideAdvancedMetadata($a_val) - { - $this->hide_adv_md = (bool)$a_val; - } - - /** - * Get adv md visibility status - * - * @return boolean - */ - public function isAdvancedMetadataHidden() - { - return $this->hide_adv_md; - } - - /** - * Create page from xml - */ - function createFromXML() - { - $ilDB = $this->db; - - // ilWikiDataset creates wiki pages without copage objects - // (see create function in this class, parameter $a_prevent_page_creation) - // The ilCOPageImporter will call createFromXML without running through the read - // method -> we will miss the important wiki id, thus we read it now - // see also bug #12224 - $set = $ilDB->query("SELECT id FROM il_wiki_page ". - " WHERE id = ".$ilDB->quote($this->getId(), "integer") - ); - if ($rec = $ilDB->fetchAssoc($set)) - { - $this->read(true); - } - - parent::createFromXML(); - } - - /** - * Create new wiki page - */ - function create($a_prevent_page_creation = false) - { - $ilDB = $this->db; - - $id = $ilDB->nextId("il_wiki_page"); - $this->setId($id); - $query = "INSERT INTO il_wiki_page (". - "id". - ", title". - ", wiki_id". - ", blocked". - ", rating". - ", hide_adv_md". - " ) VALUES (". - $ilDB->quote($this->getId(), "integer") - .",".$ilDB->quote($this->getTitle(), "text") - .",".$ilDB->quote((int) $this->getWikiId(), "integer") - .",".$ilDB->quote((int) $this->getBlocked(), "integer") - .",".$ilDB->quote((int) $this->getRating(), "integer") - .",".$ilDB->quote((int) $this->isAdvancedMetadataHidden(), "integer") - .")"; - $ilDB->manipulate($query); - - // create page object - if (!$a_prevent_page_creation) - { - parent::create(); - $this->saveInternalLinks($this->getDomDoc()); - - include_once "./Modules/Wiki/classes/class.ilWikiStat.php"; - ilWikiStat::handleEvent(ilWikiStat::EVENT_PAGE_CREATED, $this); - - include_once "./Services/Notification/classes/class.ilNotification.php"; - ilWikiUtil::sendNotification("new", ilNotification::TYPE_WIKI, $this->getWikiRefId(), $this->getId()); - } - - $this->updateNews(); - } - - public function afterUpdate($a_domdoc = null, $a_xml = "") - { - // internal == wiki links - include_once "Modules/Wiki/classes/class.ilWikiUtil.php"; - $int_links = sizeof(ilWikiUtil::collectInternalLinks($a_xml, $this->getWikiId(), true)); - - $xpath = new DOMXPath($a_domdoc); - - // external = internal + external links - $ext_links = sizeof($xpath->query('//IntLink')); - $ext_links += sizeof($xpath->query('//ExtLink')); - - $footnotes = sizeof($xpath->query('//Footnote')); - - - // words/characters (xml) - - $xml = strip_tags($a_xml); - - include_once "Services/Utilities/classes/class.ilStr.php"; - $num_chars = ilStr::strLen($xml); - $num_words = sizeof(explode(" ", $xml)); - - $page_data = array( - "int_links" => $int_links, - "ext_links" => $ext_links, - "footnotes" => $footnotes, - "num_words" => $num_words, - "num_chars" => $num_chars - ); - - include_once "./Modules/Wiki/classes/class.ilWikiStat.php"; - ilWikiStat::handleEvent(ilWikiStat::EVENT_PAGE_UPDATED, $this, null, $page_data); - } - - /** - * update object data - * - * @access public - * @return boolean - */ - function update($a_validate = true, $a_no_history = false) - { - $ilDB = $this->db; - - // update wiki page data - $query = "UPDATE il_wiki_page SET ". - " title = ".$ilDB->quote($this->getTitle(), "text"). - ",wiki_id = ".$ilDB->quote((int) $this->getWikiId(), "integer"). - ",blocked = ".$ilDB->quote((int) $this->getBlocked(), "integer"). - ",rating = ".$ilDB->quote((int) $this->getRating(), "integer"). - ",hide_adv_md = ".$ilDB->quote((int) $this->isAdvancedMetadataHidden(), "integer"). - " WHERE id = ".$ilDB->quote($this->getId(), "integer"); - $ilDB->manipulate($query); - $updated = parent::update($a_validate, $a_no_history); - - if ($updated === true) - { - include_once "./Services/Notification/classes/class.ilNotification.php"; - ilWikiUtil::sendNotification("update", ilNotification::TYPE_WIKI_PAGE, $this->getWikiRefId(), $this->getId()); - - $this->updateNews(true); - } - else - { - return $updated; - } - - return true; - } - - /** - * Read wiki data - */ - function read($a_omit_page_read = false) - { - $ilDB = $this->db; - - $query = "SELECT * FROM il_wiki_page WHERE id = ". - $ilDB->quote($this->getId(), "integer"); - $set = $ilDB->query($query); - $rec = $ilDB->fetchAssoc($set); - - $this->setTitle($rec["title"]); - $this->setWikiId($rec["wiki_id"]); - $this->setBlocked($rec["blocked"]); - $this->setRating($rec["rating"]); - $this->hideAdvancedMetadata($rec["hide_adv_md"]); - - // get co page - if (!$a_omit_page_read) - { - parent::read(); - } - } - - - /** - * delete wiki page and al related data - * - * @access public - */ - function delete() - { - $ilDB = $this->db; - - // get other pages that link to this page - $linking_pages = ilWikiPage::getLinksToPage($this->getWikiId(), - $this->getId()); - - // delete internal links information to this page - include_once("./Services/Link/classes/class.ilInternalLink.php"); - ilInternalLink::_deleteAllLinksToTarget("wpg", $this->getId()); - - include_once "./Modules/Wiki/classes/class.ilWikiStat.php"; - ilWikiStat::handleEvent(ilWikiStat::EVENT_PAGE_DELETED, $this); - - include_once "./Services/Notification/classes/class.ilNotification.php"; - ilWikiUtil::sendNotification("delete", ilNotification::TYPE_WIKI_PAGE, $this->getWikiRefId(), $this->getId()); - - // remove all notifications - include_once "./Services/Notification/classes/class.ilNotification.php"; - ilNotification::removeForObject(ilNotification::TYPE_WIKI_PAGE, $this->getId()); - - // delete record of table il_wiki_data - $query = "DELETE FROM il_wiki_page". - " WHERE id = ".$ilDB->quote($this->getId(), "integer"); - $ilDB->manipulate($query); - - // delete co page - parent::delete(); - - // make links of other pages to this page a missing link - foreach($linking_pages as $lp) - { - $ilDB->manipulateF("DELETE FROM il_wiki_missing_page ". - " WHERE wiki_id = %s AND source_id = %s AND target_name = %s ", - array("integer", "integer", "text"), - array($this->getWikiId(), $lp["id"], $this->getTitle())); - $ilDB->manipulateF("INSERT INTO il_wiki_missing_page ". - "(wiki_id, source_id, target_name) VALUES ". - "(%s,%s,%s)", - array("integer", "integer", "text"), - array($this->getWikiId(), $lp["id"], $this->getTitle())); - } - - return true; - } - - /** - * delete wiki page and al related data - * - * @access public - */ - static function deleteAllPagesOfWiki($a_wiki_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - // delete record of table il_wiki_data - $query = "SELECT * FROM il_wiki_page". - " WHERE wiki_id = ".$ilDB->quote($a_wiki_id, "integer"); - $set = $ilDB->query($query); - - while($rec = $ilDB->fetchAssoc($set)) - { - $wiki_page = new ilWikiPage($rec["id"]); - $wiki_page->delete(); - - - } - } - - /** - * Checks whether a page with given title exists - */ - static function exists($a_wiki_id, $a_title) - { - global $DIC; - - $ilDB = $DIC->database(); - - $a_title = ilWikiUtil::makeDbTitle($a_title); - - $query = "SELECT id FROM il_wiki_page". - " WHERE wiki_id = ".$ilDB->quote($a_wiki_id, "integer"). - " AND title = ".$ilDB->quote($a_title, "text"); - $set = $ilDB->query($query); - if($rec = $ilDB->fetchAssoc($set)) - { - return true; - } - - return false; - } - - /** - * Checks whether a page with given title exists - */ - static function getIdForPageTitle($a_wiki_id, $a_title) - { - global $DIC; - - $ilDB = $DIC->database(); - - $a_title = ilWikiUtil::makeDbTitle($a_title); - - $query = "SELECT id FROM il_wiki_page". - " WHERE wiki_id = ".$ilDB->quote($a_wiki_id, "integer"). - " AND title = ".$ilDB->quote($a_title, "text"); - $set = $ilDB->query($query); - if($rec = $ilDB->fetchAssoc($set)) - { - return $rec["id"]; - } - - return false; - } - - /** - * Get wiki page object for id and title - */ - static function getPageIdForTitle($a_wiki_id, $a_title) - { - global $DIC; - - $ilDB = $DIC->database(); - - $a_title = ilWikiUtil::makeDbTitle($a_title); - - $query = "SELECT * FROM il_wiki_page". - " WHERE wiki_id = ".$ilDB->quote($a_wiki_id, "integer"). - " AND title = ".$ilDB->quote($a_title, "text"); - $set = $ilDB->query($query); - if($rec = $ilDB->fetchAssoc($set)) - { - return $rec["id"]; - } - - return false; - } - - /** - * Checks whether a page with given title exists - */ - static function lookupTitle($a_page_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT * FROM il_wiki_page". - " WHERE id = ".$ilDB->quote($a_page_id, "integer"); - $set = $ilDB->query($query); - if($rec = $ilDB->fetchAssoc($set)) - { - return $rec["title"]; - } - - return false; - } - - /** - * Lookup wiki id - */ - static function lookupWikiId($a_page_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT wiki_id FROM il_wiki_page". - " WHERE id = ".$ilDB->quote($a_page_id, "integer"); - $set = $ilDB->query($query); - if ($rec = $ilDB->fetchAssoc($set)) - { - return $rec["wiki_id"]; - } - - return false; - } - - /** - * Get all pages of wiki - * - * @access public - */ - static function getAllWikiPages($a_wiki_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $pages = parent::getAllPages("wpg", $a_wiki_id); - - $query = "SELECT * FROM il_wiki_page". - " WHERE wiki_id = ".$ilDB->quote($a_wiki_id, "integer"). - " ORDER BY title"; - $set = $ilDB->query($query); - - $pg = array(); - while($rec = $ilDB->fetchAssoc($set)) - { - if (isset($pages[$rec["id"]])) - { - $pg[$rec["id"]] = $pages[$rec["id"]]; - $pg[$rec["id"]]["title"] = $rec["title"]; - } - } - - return $pg; - } - - /** - * Get links to a page - */ - static function getLinksToPage($a_wiki_id, $a_page_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - include_once("./Services/Link/classes/class.ilInternalLink.php"); - $sources = ilInternalLink::_getSourcesOfTarget("wpg", $a_page_id, 0); - - $ids = array(); - foreach ($sources as $source) - { - if ($source["type"] == "wpg:pg") - { - $ids[] = $source["id"]; - } - } - // get wiki page record - $query = "SELECT * FROM il_wiki_page wp, page_object p". - " WHERE ".$ilDB->in("wp.id", $ids, false, "integer"). - " AND wp.id = p.page_id AND p.parent_type = ".$ilDB->quote("wpg", "text"). - " AND wp.wiki_id = ".$ilDB->quote($a_wiki_id, "integer"). - " ORDER BY title"; - $set = $ilDB->query($query); - - $pages = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $pages[] = array_merge($rec, array("user" => $rec["last_change_user"], - "date" => $rec["last_change"])); - } - - return $pages; - } - - /** - * Get orphaned pages of wiki - * - * @access public - */ - static function getOrphanedPages($a_wiki_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $pages = ilWikiPage::getAllWikiPages($a_wiki_id); - - include_once("./Services/Link/classes/class.ilInternalLink.php"); - - $orphaned = array(); - foreach ($pages as $k => $page) - { - $sources = ilInternalLink::_getSourcesOfTarget("wpg", $page["id"], 0); - - $ids = array(); - foreach ($sources as $source) - { - if ($source["type"] == "wpg:pg") - { - $ids[] = $source["id"]; - } - } - $query = "SELECT count(*) cnt FROM il_wiki_page". - " WHERE ".$ilDB->in("id", $ids, false, "integer"). - " AND wiki_id = ".$ilDB->quote($a_wiki_id, "integer"). - " GROUP BY wiki_id"; - $set = $ilDB->query($query); - $rec = $ilDB->fetchAssoc($set); - if ($rec["cnt"] == 0 && - ilObjWiki::_lookupStartPage($a_wiki_id) != $page["title"]) - { - $orphaned[] = $page; - } - } - - return $orphaned; - } - - /** - * Check whether page exists for wiki or not - * - * @access public - */ - static function _wikiPageExists($a_wiki_id, $a_title) - { - global $DIC; - - $ilDB = $DIC->database(); - - $a_title = ilWikiUtil::makeDbTitle($a_title); - - $query = "SELECT id FROM il_wiki_page". - " WHERE wiki_id = ".$ilDB->quote($a_wiki_id, "integer"). - " AND title = ".$ilDB->quote($a_title, "text"); - $set = $ilDB->query($query); - - $pages = array(); - if ($rec = $ilDB->fetchAssoc($set)) - { - return true; - } - - return false; - } - - /** - * Get all contributors of wiki - * - * @access public - */ - static function getWikiContributors($a_wiki_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $contributors = parent::getParentObjectContributors("wpg", $a_wiki_id); - - return $contributors; - } - - /** - * Get all contributors of wiki - * - * @access public - */ - static function getWikiPageContributors($a_page_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $contributors = parent::getPageContributors("wpg", $a_page_id); - - return $contributors; - } - - - /** - * save internal links of page - * - * @param string xml page code - */ - function saveInternalLinks($a_domdoc) - { - $ilDB = $this->db; - - - // *** STEP 1: Standard Processing *** - - parent::saveInternalLinks($a_domdoc); - - - // *** STEP 2: Other Pages -> This Page *** - - // Check, whether ANOTHER page links to this page as a "missing" page - // (this is the case, when this page is created newly) - $set = $ilDB->queryF("SELECT * FROM il_wiki_missing_page WHERE ". - " wiki_id = %s AND target_name = %s", - array("integer", "text"), - array($this->getWikiId(), ilWikiUtil::makeDbTitle($this->getTitle()))); - while ($anmiss = $ilDB->fetchAssoc($set)) // insert internal links instead - { + protected $blocked = false; + protected $rating = false; // [boo,] + protected $hide_adv_md = false; // [bool] + + /** + * Get parent type + * + * @return string parent type + */ + public function getParentType() + { + return "wpg"; + } + + /** + * After constructor + * + * @param + * @return + */ + public function afterConstructor() + { + $this->getPageConfig()->configureByObjectId($this->getParentId()); + } + + /** + * Set Title. + * + * @param string $a_title Title + */ + public function setTitle($a_title) + { + $this->title = ilWikiUtil::makeDbTitle($a_title); + } + + /** + * Get Title. + * + * @return string Title + */ + public function getTitle() + { + return $this->title; + } + + /** + * Set Wiki Object Id. + * + * @param int $a_wikiid Wiki Object Id + */ + public function setWikiId($a_wikiid) + { + $this->setParentId($a_wikiid); + } + + /** + * Get Wiki Object Id. + * + * @return int Wiki Object Id + */ + public function getWikiId() + { + return $this->getParentId(); + } + + /** + * Set Wiki Ref Id. + * + * @param int $a_wiki_ref_id Wiki Ref Id + */ + public function setWikiRefId($a_wiki_ref_id) + { + $this->parent_ref_id = $a_wiki_ref_id; + } + + /** + * Get Wiki Ref Id. + * + * @return int Wiki Ref Id + */ + public function getWikiRefId() + { + return $this->parent_ref_id; + } + + /** + * Set blocked + * + * @param boolean $a_val blocked + */ + public function setBlocked($a_val) + { + $this->blocked = $a_val; + } + + /** + * Get blocked + * + * @return boolean blocked + */ + public function getBlocked() + { + return $this->blocked; + } + + /** + * Set rating + * + * @param boolean $a_val + */ + public function setRating($a_val) + { + $this->rating = (bool) $a_val; + } + + /** + * Get rating + * + * @return boolean + */ + public function getRating() + { + return $this->rating; + } + + /** + * Toggle adv md visibility + * + * @param boolean $a_val + */ + public function hideAdvancedMetadata($a_val) + { + $this->hide_adv_md = (bool) $a_val; + } + + /** + * Get adv md visibility status + * + * @return boolean + */ + public function isAdvancedMetadataHidden() + { + return $this->hide_adv_md; + } + + /** + * Create page from xml + */ + public function createFromXML() + { + $ilDB = $this->db; + + // ilWikiDataset creates wiki pages without copage objects + // (see create function in this class, parameter $a_prevent_page_creation) + // The ilCOPageImporter will call createFromXML without running through the read + // method -> we will miss the important wiki id, thus we read it now + // see also bug #12224 + $set = $ilDB->query( + "SELECT id FROM il_wiki_page " . + " WHERE id = " . $ilDB->quote($this->getId(), "integer") + ); + if ($rec = $ilDB->fetchAssoc($set)) { + $this->read(true); + } + + parent::createFromXML(); + } + + /** + * Create new wiki page + */ + public function create($a_prevent_page_creation = false) + { + $ilDB = $this->db; + + $id = $ilDB->nextId("il_wiki_page"); + $this->setId($id); + $query = "INSERT INTO il_wiki_page (" . + "id" . + ", title" . + ", wiki_id" . + ", blocked" . + ", rating" . + ", hide_adv_md" . + " ) VALUES (" . + $ilDB->quote($this->getId(), "integer") + . "," . $ilDB->quote($this->getTitle(), "text") + . "," . $ilDB->quote((int) $this->getWikiId(), "integer") + . "," . $ilDB->quote((int) $this->getBlocked(), "integer") + . "," . $ilDB->quote((int) $this->getRating(), "integer") + . "," . $ilDB->quote((int) $this->isAdvancedMetadataHidden(), "integer") + . ")"; + $ilDB->manipulate($query); + + // create page object + if (!$a_prevent_page_creation) { + parent::create(); + $this->saveInternalLinks($this->getDomDoc()); + + include_once "./Modules/Wiki/classes/class.ilWikiStat.php"; + ilWikiStat::handleEvent(ilWikiStat::EVENT_PAGE_CREATED, $this); + + include_once "./Services/Notification/classes/class.ilNotification.php"; + ilWikiUtil::sendNotification("new", ilNotification::TYPE_WIKI, $this->getWikiRefId(), $this->getId()); + } + + $this->updateNews(); + } + + public function afterUpdate($a_domdoc = null, $a_xml = "") + { + // internal == wiki links + include_once "Modules/Wiki/classes/class.ilWikiUtil.php"; + $int_links = sizeof(ilWikiUtil::collectInternalLinks($a_xml, $this->getWikiId(), true)); + + $xpath = new DOMXPath($a_domdoc); + + // external = internal + external links + $ext_links = sizeof($xpath->query('//IntLink')); + $ext_links += sizeof($xpath->query('//ExtLink')); + + $footnotes = sizeof($xpath->query('//Footnote')); + + + // words/characters (xml) + + $xml = strip_tags($a_xml); + + include_once "Services/Utilities/classes/class.ilStr.php"; + $num_chars = ilStr::strLen($xml); + $num_words = sizeof(explode(" ", $xml)); + + $page_data = array( + "int_links" => $int_links, + "ext_links" => $ext_links, + "footnotes" => $footnotes, + "num_words" => $num_words, + "num_chars" => $num_chars + ); + + include_once "./Modules/Wiki/classes/class.ilWikiStat.php"; + ilWikiStat::handleEvent(ilWikiStat::EVENT_PAGE_UPDATED, $this, null, $page_data); + } + + /** + * update object data + * + * @access public + * @return boolean + */ + public function update($a_validate = true, $a_no_history = false) + { + $ilDB = $this->db; + + // update wiki page data + $query = "UPDATE il_wiki_page SET " . + " title = " . $ilDB->quote($this->getTitle(), "text") . + ",wiki_id = " . $ilDB->quote((int) $this->getWikiId(), "integer") . + ",blocked = " . $ilDB->quote((int) $this->getBlocked(), "integer") . + ",rating = " . $ilDB->quote((int) $this->getRating(), "integer") . + ",hide_adv_md = " . $ilDB->quote((int) $this->isAdvancedMetadataHidden(), "integer") . + " WHERE id = " . $ilDB->quote($this->getId(), "integer"); + $ilDB->manipulate($query); + $updated = parent::update($a_validate, $a_no_history); + + if ($updated === true) { + include_once "./Services/Notification/classes/class.ilNotification.php"; + ilWikiUtil::sendNotification("update", ilNotification::TYPE_WIKI_PAGE, $this->getWikiRefId(), $this->getId()); + + $this->updateNews(true); + } else { + return $updated; + } + + return true; + } + + /** + * Read wiki data + */ + public function read($a_omit_page_read = false) + { + $ilDB = $this->db; + + $query = "SELECT * FROM il_wiki_page WHERE id = " . + $ilDB->quote($this->getId(), "integer"); + $set = $ilDB->query($query); + $rec = $ilDB->fetchAssoc($set); + + $this->setTitle($rec["title"]); + $this->setWikiId($rec["wiki_id"]); + $this->setBlocked($rec["blocked"]); + $this->setRating($rec["rating"]); + $this->hideAdvancedMetadata($rec["hide_adv_md"]); + + // get co page + if (!$a_omit_page_read) { + parent::read(); + } + } + + + /** + * delete wiki page and al related data + * + * @access public + */ + public function delete() + { + $ilDB = $this->db; + + // get other pages that link to this page + $linking_pages = ilWikiPage::getLinksToPage( + $this->getWikiId(), + $this->getId() + ); + + // delete internal links information to this page + include_once("./Services/Link/classes/class.ilInternalLink.php"); + ilInternalLink::_deleteAllLinksToTarget("wpg", $this->getId()); + + include_once "./Modules/Wiki/classes/class.ilWikiStat.php"; + ilWikiStat::handleEvent(ilWikiStat::EVENT_PAGE_DELETED, $this); + + include_once "./Services/Notification/classes/class.ilNotification.php"; + ilWikiUtil::sendNotification("delete", ilNotification::TYPE_WIKI_PAGE, $this->getWikiRefId(), $this->getId()); + + // remove all notifications + include_once "./Services/Notification/classes/class.ilNotification.php"; + ilNotification::removeForObject(ilNotification::TYPE_WIKI_PAGE, $this->getId()); + + // delete record of table il_wiki_data + $query = "DELETE FROM il_wiki_page" . + " WHERE id = " . $ilDB->quote($this->getId(), "integer"); + $ilDB->manipulate($query); + + // delete co page + parent::delete(); + + // make links of other pages to this page a missing link + foreach ($linking_pages as $lp) { + $ilDB->manipulateF( + "DELETE FROM il_wiki_missing_page " . + " WHERE wiki_id = %s AND source_id = %s AND target_name = %s ", + array("integer", "integer", "text"), + array($this->getWikiId(), $lp["id"], $this->getTitle()) + ); + $ilDB->manipulateF( + "INSERT INTO il_wiki_missing_page " . + "(wiki_id, source_id, target_name) VALUES " . + "(%s,%s,%s)", + array("integer", "integer", "text"), + array($this->getWikiId(), $lp["id"], $this->getTitle()) + ); + } + + return true; + } + + /** + * delete wiki page and al related data + * + * @access public + */ + public static function deleteAllPagesOfWiki($a_wiki_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + // delete record of table il_wiki_data + $query = "SELECT * FROM il_wiki_page" . + " WHERE wiki_id = " . $ilDB->quote($a_wiki_id, "integer"); + $set = $ilDB->query($query); + + while ($rec = $ilDB->fetchAssoc($set)) { + $wiki_page = new ilWikiPage($rec["id"]); + $wiki_page->delete(); + } + } + + /** + * Checks whether a page with given title exists + */ + public static function exists($a_wiki_id, $a_title) + { + global $DIC; + + $ilDB = $DIC->database(); + + $a_title = ilWikiUtil::makeDbTitle($a_title); + + $query = "SELECT id FROM il_wiki_page" . + " WHERE wiki_id = " . $ilDB->quote($a_wiki_id, "integer") . + " AND title = " . $ilDB->quote($a_title, "text"); + $set = $ilDB->query($query); + if ($rec = $ilDB->fetchAssoc($set)) { + return true; + } + + return false; + } + + /** + * Checks whether a page with given title exists + */ + public static function getIdForPageTitle($a_wiki_id, $a_title) + { + global $DIC; + + $ilDB = $DIC->database(); + + $a_title = ilWikiUtil::makeDbTitle($a_title); + + $query = "SELECT id FROM il_wiki_page" . + " WHERE wiki_id = " . $ilDB->quote($a_wiki_id, "integer") . + " AND title = " . $ilDB->quote($a_title, "text"); + $set = $ilDB->query($query); + if ($rec = $ilDB->fetchAssoc($set)) { + return $rec["id"]; + } + + return false; + } + + /** + * Get wiki page object for id and title + */ + public static function getPageIdForTitle($a_wiki_id, $a_title) + { + global $DIC; + + $ilDB = $DIC->database(); + + $a_title = ilWikiUtil::makeDbTitle($a_title); + + $query = "SELECT * FROM il_wiki_page" . + " WHERE wiki_id = " . $ilDB->quote($a_wiki_id, "integer") . + " AND title = " . $ilDB->quote($a_title, "text"); + $set = $ilDB->query($query); + if ($rec = $ilDB->fetchAssoc($set)) { + return $rec["id"]; + } + + return false; + } + + /** + * Checks whether a page with given title exists + */ + public static function lookupTitle($a_page_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT * FROM il_wiki_page" . + " WHERE id = " . $ilDB->quote($a_page_id, "integer"); + $set = $ilDB->query($query); + if ($rec = $ilDB->fetchAssoc($set)) { + return $rec["title"]; + } + + return false; + } + + /** + * Lookup wiki id + */ + public static function lookupWikiId($a_page_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT wiki_id FROM il_wiki_page" . + " WHERE id = " . $ilDB->quote($a_page_id, "integer"); + $set = $ilDB->query($query); + if ($rec = $ilDB->fetchAssoc($set)) { + return $rec["wiki_id"]; + } + + return false; + } + + /** + * Get all pages of wiki + * + * @access public + */ + public static function getAllWikiPages($a_wiki_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $pages = parent::getAllPages("wpg", $a_wiki_id); + + $query = "SELECT * FROM il_wiki_page" . + " WHERE wiki_id = " . $ilDB->quote($a_wiki_id, "integer") . + " ORDER BY title"; + $set = $ilDB->query($query); + + $pg = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + if (isset($pages[$rec["id"]])) { + $pg[$rec["id"]] = $pages[$rec["id"]]; + $pg[$rec["id"]]["title"] = $rec["title"]; + } + } + + return $pg; + } + + /** + * Get links to a page + */ + public static function getLinksToPage($a_wiki_id, $a_page_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + include_once("./Services/Link/classes/class.ilInternalLink.php"); + $sources = ilInternalLink::_getSourcesOfTarget("wpg", $a_page_id, 0); + + $ids = array(); + foreach ($sources as $source) { + if ($source["type"] == "wpg:pg") { + $ids[] = $source["id"]; + } + } + // get wiki page record + $query = "SELECT * FROM il_wiki_page wp, page_object p" . + " WHERE " . $ilDB->in("wp.id", $ids, false, "integer") . + " AND wp.id = p.page_id AND p.parent_type = " . $ilDB->quote("wpg", "text") . + " AND wp.wiki_id = " . $ilDB->quote($a_wiki_id, "integer") . + " ORDER BY title"; + $set = $ilDB->query($query); + + $pages = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $pages[] = array_merge($rec, array("user" => $rec["last_change_user"], + "date" => $rec["last_change"])); + } + + return $pages; + } + + /** + * Get orphaned pages of wiki + * + * @access public + */ + public static function getOrphanedPages($a_wiki_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $pages = ilWikiPage::getAllWikiPages($a_wiki_id); + + include_once("./Services/Link/classes/class.ilInternalLink.php"); + + $orphaned = array(); + foreach ($pages as $k => $page) { + $sources = ilInternalLink::_getSourcesOfTarget("wpg", $page["id"], 0); + + $ids = array(); + foreach ($sources as $source) { + if ($source["type"] == "wpg:pg") { + $ids[] = $source["id"]; + } + } + $query = "SELECT count(*) cnt FROM il_wiki_page" . + " WHERE " . $ilDB->in("id", $ids, false, "integer") . + " AND wiki_id = " . $ilDB->quote($a_wiki_id, "integer") . + " GROUP BY wiki_id"; + $set = $ilDB->query($query); + $rec = $ilDB->fetchAssoc($set); + if ($rec["cnt"] == 0 && + ilObjWiki::_lookupStartPage($a_wiki_id) != $page["title"]) { + $orphaned[] = $page; + } + } + + return $orphaned; + } + + /** + * Check whether page exists for wiki or not + * + * @access public + */ + public static function _wikiPageExists($a_wiki_id, $a_title) + { + global $DIC; + + $ilDB = $DIC->database(); + + $a_title = ilWikiUtil::makeDbTitle($a_title); + + $query = "SELECT id FROM il_wiki_page" . + " WHERE wiki_id = " . $ilDB->quote($a_wiki_id, "integer") . + " AND title = " . $ilDB->quote($a_title, "text"); + $set = $ilDB->query($query); + + $pages = array(); + if ($rec = $ilDB->fetchAssoc($set)) { + return true; + } + + return false; + } + + /** + * Get all contributors of wiki + * + * @access public + */ + public static function getWikiContributors($a_wiki_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $contributors = parent::getParentObjectContributors("wpg", $a_wiki_id); + + return $contributors; + } + + /** + * Get all contributors of wiki + * + * @access public + */ + public static function getWikiPageContributors($a_page_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $contributors = parent::getPageContributors("wpg", $a_page_id); + + return $contributors; + } + + + /** + * save internal links of page + * + * @param string xml page code + */ + public function saveInternalLinks($a_domdoc) + { + $ilDB = $this->db; + + + // *** STEP 1: Standard Processing *** + + parent::saveInternalLinks($a_domdoc); + + + // *** STEP 2: Other Pages -> This Page *** + + // Check, whether ANOTHER page links to this page as a "missing" page + // (this is the case, when this page is created newly) + $set = $ilDB->queryF( + "SELECT * FROM il_wiki_missing_page WHERE " . + " wiki_id = %s AND target_name = %s", + array("integer", "text"), + array($this->getWikiId(), ilWikiUtil::makeDbTitle($this->getTitle())) + ); + while ($anmiss = $ilDB->fetchAssoc($set)) { // insert internal links instead //echo "adding link"; - ilInternalLink::_saveLink("wpg:pg", $anmiss["source_id"], "wpg", - $this->getId(), 0); - } -//exit; - // now remove the missing page entries - $ilDB->manipulateF("DELETE FROM il_wiki_missing_page WHERE ". - " wiki_id = %s AND target_name = %s", - array("integer", "text"), - array($this->getWikiId(), $this->getTitle())); - - - // *** STEP 3: This Page -> Other Pages *** - - // remove the exising "missing page" links for THIS page (they will be re-inserted below) - $ilDB->manipulateF("DELETE FROM il_wiki_missing_page WHERE ". - " wiki_id = %s AND source_id = %s", - array("integer", "integer"), - array($this->getWikiId(), $this->getId())); - - // collect the wiki links of the page - include_once("./Modules/Wiki/classes/class.ilWikiUtil.php"); - $xml = $a_domdoc->saveXML(); - $int_wiki_links = ilWikiUtil::collectInternalLinks($xml, $this->getWikiId(), true); - foreach($int_wiki_links as $wlink) - { - $page_id = ilWikiPage::_getPageIdForWikiTitle($this->getWikiId(), $wlink); - - if ($page_id > 0) // save internal link for existing page - { - ilInternalLink::_saveLink("wpg:pg", $this->getId(), "wpg", - $page_id, 0); - } - else // save missing link for non-existing page - { - $ilDB->manipulateF("DELETE FROM il_wiki_missing_page WHERE". - " wiki_id = %s AND source_id = %s AND target_name = %s", - array("integer", "integer", "text"), - array($this->getWikiId(), $this->getId(), $wlink)); - $ilDB->manipulateF("INSERT INTO il_wiki_missing_page (wiki_id, source_id, target_name)". - " VALUES (%s,%s,%s)", - array("integer", "integer", "text"), - array($this->getWikiId(), $this->getId(), $wlink)); - } - } - } - - /** - * Checks whether a page with given title exists - */ - static function _getPageIdForWikiTitle($a_wiki_id, $a_title) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT id FROM il_wiki_page". - " WHERE wiki_id = ".$ilDB->quote($a_wiki_id, "integer"). - " AND title = ".$ilDB->quote($a_title, "text"); - $set = $ilDB->query($query); - if($rec = $ilDB->fetchAssoc($set)) - { - return $rec["id"]; - } - - return false; - } - - /** - * Get popular pages of wiki - * - * @access public - */ - static function getPopularPages($a_wiki_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT wp.*, po.view_cnt as cnt FROM il_wiki_page wp, page_object po". - " WHERE wp.wiki_id = ".$ilDB->quote($a_wiki_id, "integer"). - " AND wp.id = po.page_id ". - " AND po.parent_type = ".$ilDB->quote("wpg", "text")." ". - " ORDER BY po.view_cnt"; - $set = $ilDB->query($query); - - $pages = array(); - while($rec = $ilDB->fetchAssoc($set)) - { - $pages[] = $rec; - } - - return $pages; - } - - /** - * Count pages of wiki - * - * @param int $a_wiki_id Wiki ID - */ - static function countPages($a_wiki_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - // delete record of table il_wiki_data - $query = "SELECT count(*) as cnt FROM il_wiki_page". - " WHERE wiki_id = ".$ilDB->quote($a_wiki_id, "integer"); - $s = $ilDB->query($query); - $r = $ilDB->fetchAssoc($s); - - return $r["cnt"]; - } - - /** - * Get a random page - * - * @param int $a_wiki_id Wiki ID - */ - static function getRandomPage($a_wiki_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $cnt = ilWikiPage::countPages($a_wiki_id); - - if ($cnt < 1) - { - return ""; - } - - $rand = rand(1, $cnt); - - // delete record of table il_wiki_data - $ilDB->setLimit(1, $rand); - $query = "SELECT title FROM il_wiki_page". - " WHERE wiki_id = ".$ilDB->quote($a_wiki_id, "integer"); - $s = $ilDB->query($query); - $r = $ilDB->fetchAssoc($s); - - return $r["title"]; - } - - /** - * Get all pages of wiki - * - * @access public - */ - static function getNewWikiPages($a_wiki_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $pages = parent::getNewPages("wpg", $a_wiki_id); - - foreach($pages as $k => $page) - { - $pages[$k]["title"] = ilWikiPage::lookupTitle($page["id"]); - } - - return $pages; - } - - - /** - * returns the wiki/object id to a given page id - * - * @param $a_page_id - * @return int the object id - */ - public static function lookupObjIdByPage($a_page_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT wiki_id FROM il_wiki_page". - " WHERE id = ".$ilDB->quote($a_page_id, "integer"); - $set = $ilDB->query($query); - if($rec = $ilDB->fetchAssoc($set)) - { - return $rec["wiki_id"]; - } - - return false; - } - - /** - * Rename page - */ - function rename($a_new_name) - { - $ilDB = $this->db; - - // replace unallowed characters - $a_new_name = str_replace(array("<", ">"), '', $a_new_name); - - // replace multiple whitespace characters by one single space - $a_new_name = trim(preg_replace('!\s+!', ' ', $a_new_name)); - - $page_title = ilWikiUtil::makeDbTitle($a_new_name); - $pg_id = ilWikiPage::_getPageIdForWikiTitle($this->getWikiId(), $page_title); - - $xml_new_name = str_replace("&", "&", $a_new_name); - - if ($pg_id == 0 || $pg_id == $this->getId()) - { - include_once("./Services/Link/classes/class.ilInternalLink.php"); - $sources = ilInternalLink::_getSourcesOfTarget("wpg", $this->getId(), 0); - - foreach ($sources as $s) - { - if ($s["type"] == "wpg:pg" && ilPageObject::_exists("wpg", $s["id"])) - { - $wpage = new ilWikiPage($s["id"]); - - $col = ilWikiUtil::processInternalLinks($wpage->getXmlContent(), 0, - IL_WIKI_MODE_EXT_COLLECT); - $new_content = $wpage->getXmlContent(); - foreach ($col as $c) - { - - // this complicated procedure is needed due to the fact - // that depending on the collation e = é is true - // in the (mysql) database - // see bug http://www.ilias.de/mantis/view.php?id=11227 - $t1 = ilWikiUtil::makeDbTitle($c["nt"]->mTextform); - $t2 = ilWikiUtil::makeDbTitle($this->getTitle()); - - // this one replaces C2A0 ( ) by a usual space - // otherwise the comparision will fail, since you - // get these characters from tiny if more than one - // space is repeated in a string. This may not be - // 100% but we do not store $t1 anywhere and only - // modify it for the comparison - $t1 = preg_replace('/\xC2\xA0/', ' ', $t1); - $t2 = preg_replace('/\xC2\xA0/', ' ', $t2); - - $set = $ilDB->query($q = "SELECT ".$ilDB->quote($t1, "text")." = ".$ilDB->quote($t2, "text")." isequal"); - $rec = $ilDB->fetchAssoc($set); - - if ($rec["isequal"]) - { - $new_content = - str_replace("[[".$c["nt"]->mTextform."]]", - "[[".$xml_new_name."]]", $new_content); - if ($c["text"] != "") - { - $new_content = - str_replace("[[".$c["text"]."]]", - "[[".$xml_new_name."]]", $new_content); - } - $add = ($c["text"] != "") - ? "|".$c["text"] - : ""; - $new_content = - str_replace("[[".$c["nt"]->mTextform.$add."]]", - "[[".$xml_new_name.$add."]]", $new_content); - } - } - $wpage->setXmlContent($new_content); -//echo htmlentities($new_content); - $wpage->update(); - } - } - - include_once("./Modules/Wiki/classes/class.ilObjWiki.php"); - if (ilObjWiki::_lookupStartPage($this->getWikiId()) == $this->getTitle()) - { - ilObjWiki::writeStartPage($this->getWikiId(), $a_new_name); - } - - $this->setTitle($a_new_name); - - $this->update(); - } - - return $a_new_name; - } - - - /** - * Create - */ - function updateNews($a_update = false) - { - $ilUser = $this->user; - - $news_set = new ilSetting("news"); - $default_visibility = ($news_set->get("default_visibility") != "") - ? $news_set->get("default_visibility") - : "users"; - - include_once("./Services/News/classes/class.ilNewsItem.php"); - if (!$a_update) - { - $news_item = new ilNewsItem(); - $news_item->setContext( - $this->getWikiId(), "wiki", - $this->getId(), "wpg"); - $news_item->setPriority(NEWS_NOTICE); - $news_item->setTitle($this->getTitle()); - $news_item->setContentTextIsLangVar(true); - $news_item->setContent("wiki_news_page_created"); - $news_item->setUserId($ilUser->getId()); - $news_item->setVisibility($default_visibility); - $news_item->create(); - } - else - { - // get last news item of the day (if existing) - $news_id = ilNewsItem::getLastNewsIdForContext( - $this->getWikiId(), "wiki", - $this->getId(), "wpg", true); - - if ($news_id > 0) - { - $news_item = new ilNewsItem($news_id); - $news_item->setContent("wiki_news_page_changed"); - $news_item->setUserId($ilUser->getId()); - $news_item->setTitle($this->getTitle()); - $news_item->setContentTextIsLangVar(true); - $news_item->update(true); - } - else - { - $news_item = new ilNewsItem(); - $news_item->setContext( - $this->getWikiId(), "wiki", - $this->getId(), "wpg"); - $news_item->setPriority(NEWS_NOTICE); - $news_item->setTitle($this->getTitle()); - $news_item->setContentTextIsLangVar(true); - $news_item->setContent("wiki_news_page_changed"); - $news_item->setUserId($ilUser->getId()); - $news_item->setVisibility($default_visibility); - $news_item->create(); - } - } - } - - /** - * Get content for a wiki news item - */ - function getNewsContent() - { - return "12.1.1: Test User, Max"; - } - - /** - * Get goto href for internal wiki page link target - * - * @param - * @return - */ - static function getGotoForWikiPageTarget($a_target, $a_offline = false) - { - if (!$a_offline) - { - $href = "./goto.php?target=wiki_wpage_".$a_target; - } - else - { - $href = ILIAS_HTTP_PATH."/goto.php?target=wiki_wpage_".$a_target; - } - return $href; - } - - - /** - * Get content templates - * - * @return array array of arrays with "id" => page id (int), "parent_type" => parent type (string), "title" => title (string) - */ - function getContentTemplates() - { - include_once("./Modules/Wiki/classes/class.ilWikiPageTemplate.php"); - $wt = new ilWikiPageTemplate($this->getWikiId()); - $templates = array(); - foreach ($wt->getAllInfo(ilWikiPageTemplate::TYPE_ADD_TO_PAGE) as $t) - { - $templates[] = array("id" => $t["wpage_id"], "parent_type" => "wpg", "title" => $t["title"]); - } - return $templates; - } - - /** - * Get pages for search - * - * @param - * @return - */ - static function getPagesForSearch($a_wiki_id, $a_term) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT DISTINCT title FROM il_wiki_page". - " WHERE wiki_id = ".$ilDB->quote($a_wiki_id, "integer"). - " AND ".$ilDB->like("title", "text", "%".$a_term."%"). - " ORDER by title"); - $res = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $res[] = $rec["title"]; - } - - return $res; - } - - public static function lookupAdvancedMetadataHidden($a_page_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT * FROM il_wiki_page". - " WHERE id = ".$ilDB->quote($a_page_id, "integer"); - $set = $ilDB->query($query); - if($rec = $ilDB->fetchAssoc($set)) - { - return (bool)$rec["hide_adv_md"]; - } - - return false; - } + ilInternalLink::_saveLink( + "wpg:pg", + $anmiss["source_id"], + "wpg", + $this->getId(), + 0 + ); + } + //exit; + // now remove the missing page entries + $ilDB->manipulateF( + "DELETE FROM il_wiki_missing_page WHERE " . + " wiki_id = %s AND target_name = %s", + array("integer", "text"), + array($this->getWikiId(), $this->getTitle()) + ); + + + // *** STEP 3: This Page -> Other Pages *** + + // remove the exising "missing page" links for THIS page (they will be re-inserted below) + $ilDB->manipulateF( + "DELETE FROM il_wiki_missing_page WHERE " . + " wiki_id = %s AND source_id = %s", + array("integer", "integer"), + array($this->getWikiId(), $this->getId()) + ); + + // collect the wiki links of the page + include_once("./Modules/Wiki/classes/class.ilWikiUtil.php"); + $xml = $a_domdoc->saveXML(); + $int_wiki_links = ilWikiUtil::collectInternalLinks($xml, $this->getWikiId(), true); + foreach ($int_wiki_links as $wlink) { + $page_id = ilWikiPage::_getPageIdForWikiTitle($this->getWikiId(), $wlink); + + if ($page_id > 0) { // save internal link for existing page + ilInternalLink::_saveLink( + "wpg:pg", + $this->getId(), + "wpg", + $page_id, + 0 + ); + } else { // save missing link for non-existing page + $ilDB->manipulateF( + "DELETE FROM il_wiki_missing_page WHERE" . + " wiki_id = %s AND source_id = %s AND target_name = %s", + array("integer", "integer", "text"), + array($this->getWikiId(), $this->getId(), $wlink) + ); + $ilDB->manipulateF( + "INSERT INTO il_wiki_missing_page (wiki_id, source_id, target_name)" . + " VALUES (%s,%s,%s)", + array("integer", "integer", "text"), + array($this->getWikiId(), $this->getId(), $wlink) + ); + } + } + } + + /** + * Checks whether a page with given title exists + */ + public static function _getPageIdForWikiTitle($a_wiki_id, $a_title) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT id FROM il_wiki_page" . + " WHERE wiki_id = " . $ilDB->quote($a_wiki_id, "integer") . + " AND title = " . $ilDB->quote($a_title, "text"); + $set = $ilDB->query($query); + if ($rec = $ilDB->fetchAssoc($set)) { + return $rec["id"]; + } + + return false; + } + + /** + * Get popular pages of wiki + * + * @access public + */ + public static function getPopularPages($a_wiki_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT wp.*, po.view_cnt as cnt FROM il_wiki_page wp, page_object po" . + " WHERE wp.wiki_id = " . $ilDB->quote($a_wiki_id, "integer") . + " AND wp.id = po.page_id " . + " AND po.parent_type = " . $ilDB->quote("wpg", "text") . " " . + " ORDER BY po.view_cnt"; + $set = $ilDB->query($query); + + $pages = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $pages[] = $rec; + } + + return $pages; + } + + /** + * Count pages of wiki + * + * @param int $a_wiki_id Wiki ID + */ + public static function countPages($a_wiki_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + // delete record of table il_wiki_data + $query = "SELECT count(*) as cnt FROM il_wiki_page" . + " WHERE wiki_id = " . $ilDB->quote($a_wiki_id, "integer"); + $s = $ilDB->query($query); + $r = $ilDB->fetchAssoc($s); + + return $r["cnt"]; + } + + /** + * Get a random page + * + * @param int $a_wiki_id Wiki ID + */ + public static function getRandomPage($a_wiki_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $cnt = ilWikiPage::countPages($a_wiki_id); + + if ($cnt < 1) { + return ""; + } + + $rand = rand(1, $cnt); + + // delete record of table il_wiki_data + $ilDB->setLimit(1, $rand); + $query = "SELECT title FROM il_wiki_page" . + " WHERE wiki_id = " . $ilDB->quote($a_wiki_id, "integer"); + $s = $ilDB->query($query); + $r = $ilDB->fetchAssoc($s); + + return $r["title"]; + } + + /** + * Get all pages of wiki + * + * @access public + */ + public static function getNewWikiPages($a_wiki_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $pages = parent::getNewPages("wpg", $a_wiki_id); + + foreach ($pages as $k => $page) { + $pages[$k]["title"] = ilWikiPage::lookupTitle($page["id"]); + } + + return $pages; + } + + + /** + * returns the wiki/object id to a given page id + * + * @param $a_page_id + * @return int the object id + */ + public static function lookupObjIdByPage($a_page_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT wiki_id FROM il_wiki_page" . + " WHERE id = " . $ilDB->quote($a_page_id, "integer"); + $set = $ilDB->query($query); + if ($rec = $ilDB->fetchAssoc($set)) { + return $rec["wiki_id"]; + } + + return false; + } + + /** + * Rename page + */ + public function rename($a_new_name) + { + $ilDB = $this->db; + + // replace unallowed characters + $a_new_name = str_replace(array("<", ">"), '', $a_new_name); + + // replace multiple whitespace characters by one single space + $a_new_name = trim(preg_replace('!\s+!', ' ', $a_new_name)); + + $page_title = ilWikiUtil::makeDbTitle($a_new_name); + $pg_id = ilWikiPage::_getPageIdForWikiTitle($this->getWikiId(), $page_title); + + $xml_new_name = str_replace("&", "&", $a_new_name); + + if ($pg_id == 0 || $pg_id == $this->getId()) { + include_once("./Services/Link/classes/class.ilInternalLink.php"); + $sources = ilInternalLink::_getSourcesOfTarget("wpg", $this->getId(), 0); + + foreach ($sources as $s) { + if ($s["type"] == "wpg:pg" && ilPageObject::_exists("wpg", $s["id"])) { + $wpage = new ilWikiPage($s["id"]); + + $col = ilWikiUtil::processInternalLinks( + $wpage->getXmlContent(), + 0, + IL_WIKI_MODE_EXT_COLLECT + ); + $new_content = $wpage->getXmlContent(); + foreach ($col as $c) { + + // this complicated procedure is needed due to the fact + // that depending on the collation e = é is true + // in the (mysql) database + // see bug http://www.ilias.de/mantis/view.php?id=11227 + $t1 = ilWikiUtil::makeDbTitle($c["nt"]->mTextform); + $t2 = ilWikiUtil::makeDbTitle($this->getTitle()); + + // this one replaces C2A0 ( ) by a usual space + // otherwise the comparision will fail, since you + // get these characters from tiny if more than one + // space is repeated in a string. This may not be + // 100% but we do not store $t1 anywhere and only + // modify it for the comparison + $t1 = preg_replace('/\xC2\xA0/', ' ', $t1); + $t2 = preg_replace('/\xC2\xA0/', ' ', $t2); + + $set = $ilDB->query($q = "SELECT " . $ilDB->quote($t1, "text") . " = " . $ilDB->quote($t2, "text") . " isequal"); + $rec = $ilDB->fetchAssoc($set); + + if ($rec["isequal"]) { + $new_content = + str_replace( + "[[" . $c["nt"]->mTextform . "]]", + "[[" . $xml_new_name . "]]", + $new_content + ); + if ($c["text"] != "") { + $new_content = + str_replace( + "[[" . $c["text"] . "]]", + "[[" . $xml_new_name . "]]", + $new_content + ); + } + $add = ($c["text"] != "") + ? "|" . $c["text"] + : ""; + $new_content = + str_replace( + "[[" . $c["nt"]->mTextform . $add . "]]", + "[[" . $xml_new_name . $add . "]]", + $new_content + ); + } + } + $wpage->setXmlContent($new_content); + //echo htmlentities($new_content); + $wpage->update(); + } + } + + include_once("./Modules/Wiki/classes/class.ilObjWiki.php"); + if (ilObjWiki::_lookupStartPage($this->getWikiId()) == $this->getTitle()) { + ilObjWiki::writeStartPage($this->getWikiId(), $a_new_name); + } + + $this->setTitle($a_new_name); + + $this->update(); + } + + return $a_new_name; + } + + + /** + * Create + */ + public function updateNews($a_update = false) + { + $ilUser = $this->user; + + $news_set = new ilSetting("news"); + $default_visibility = ($news_set->get("default_visibility") != "") + ? $news_set->get("default_visibility") + : "users"; + + include_once("./Services/News/classes/class.ilNewsItem.php"); + if (!$a_update) { + $news_item = new ilNewsItem(); + $news_item->setContext( + $this->getWikiId(), + "wiki", + $this->getId(), + "wpg" + ); + $news_item->setPriority(NEWS_NOTICE); + $news_item->setTitle($this->getTitle()); + $news_item->setContentTextIsLangVar(true); + $news_item->setContent("wiki_news_page_created"); + $news_item->setUserId($ilUser->getId()); + $news_item->setVisibility($default_visibility); + $news_item->create(); + } else { + // get last news item of the day (if existing) + $news_id = ilNewsItem::getLastNewsIdForContext( + $this->getWikiId(), + "wiki", + $this->getId(), + "wpg", + true + ); + + if ($news_id > 0) { + $news_item = new ilNewsItem($news_id); + $news_item->setContent("wiki_news_page_changed"); + $news_item->setUserId($ilUser->getId()); + $news_item->setTitle($this->getTitle()); + $news_item->setContentTextIsLangVar(true); + $news_item->update(true); + } else { + $news_item = new ilNewsItem(); + $news_item->setContext( + $this->getWikiId(), + "wiki", + $this->getId(), + "wpg" + ); + $news_item->setPriority(NEWS_NOTICE); + $news_item->setTitle($this->getTitle()); + $news_item->setContentTextIsLangVar(true); + $news_item->setContent("wiki_news_page_changed"); + $news_item->setUserId($ilUser->getId()); + $news_item->setVisibility($default_visibility); + $news_item->create(); + } + } + } + + /** + * Get content for a wiki news item + */ + public function getNewsContent() + { + return "12.1.1: Test User, Max"; + } + + /** + * Get goto href for internal wiki page link target + * + * @param + * @return + */ + public static function getGotoForWikiPageTarget($a_target, $a_offline = false) + { + if (!$a_offline) { + $href = "./goto.php?target=wiki_wpage_" . $a_target; + } else { + $href = ILIAS_HTTP_PATH . "/goto.php?target=wiki_wpage_" . $a_target; + } + return $href; + } + + + /** + * Get content templates + * + * @return array array of arrays with "id" => page id (int), "parent_type" => parent type (string), "title" => title (string) + */ + public function getContentTemplates() + { + include_once("./Modules/Wiki/classes/class.ilWikiPageTemplate.php"); + $wt = new ilWikiPageTemplate($this->getWikiId()); + $templates = array(); + foreach ($wt->getAllInfo(ilWikiPageTemplate::TYPE_ADD_TO_PAGE) as $t) { + $templates[] = array("id" => $t["wpage_id"], "parent_type" => "wpg", "title" => $t["title"]); + } + return $templates; + } + + /** + * Get pages for search + * + * @param + * @return + */ + public static function getPagesForSearch($a_wiki_id, $a_term) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query("SELECT DISTINCT title FROM il_wiki_page" . + " WHERE wiki_id = " . $ilDB->quote($a_wiki_id, "integer") . + " AND " . $ilDB->like("title", "text", "%" . $a_term . "%") . + " ORDER by title"); + $res = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $res[] = $rec["title"]; + } + + return $res; + } + + public static function lookupAdvancedMetadataHidden($a_page_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT * FROM il_wiki_page" . + " WHERE id = " . $ilDB->quote($a_page_id, "integer"); + $set = $ilDB->query($query); + if ($rec = $ilDB->fetchAssoc($set)) { + return (bool) $rec["hide_adv_md"]; + } + + return false; + } } -?> diff --git a/Modules/Wiki/classes/class.ilWikiPageConfig.php b/Modules/Wiki/classes/class.ilWikiPageConfig.php index 525aa0580aa1c6b8c0ae95b1d1749876b62fc9db..7a4a20285d848f8ba29f439a687e02062b10d013 100644 --- a/Modules/Wiki/classes/class.ilWikiPageConfig.php +++ b/Modules/Wiki/classes/class.ilWikiPageConfig.php @@ -5,7 +5,7 @@ include_once("./Services/COPage/classes/class.ilPageConfig.php"); /** - * Wiki page configuration + * Wiki page configuration * * @author Alex Killing * @version $Id$ @@ -13,39 +13,35 @@ include_once("./Services/COPage/classes/class.ilPageConfig.php"); */ class ilWikiPageConfig extends ilPageConfig { - /** - * Init - */ - function init() - { - $this->setEnablePCType("Map", true); - $this->setEnablePCType("Tabs", true); - $this->setPreventHTMLUnmasking(true); - $this->setEnableInternalLinks(true); - $this->setEnableAnchors(true); - $this->setEnableWikiLinks(true); - $this->setIntLinkFilterWhiteList(true); - $this->addIntLinkFilter("RepositoryItem"); - $this->addIntLinkFilter("WikiPage"); - $this->addIntLinkFilter("User"); - $this->setIntLinkHelpDefaultType("RepositoryItem"); - $this->setEnablePCType("AMDPageList", true); - } - - /** - * Object specific configuration - * - * @param int $a_obj_id object id - */ - function configureByObjectId($a_obj_id) - { - if ($a_obj_id > 0) - { - include_once("./Modules/Wiki/classes/class.ilObjWiki.php"); - $this->setEnablePageToc(ilObjWiki::_lookupPageToc($a_obj_id)); - } - } - + /** + * Init + */ + public function init() + { + $this->setEnablePCType("Map", true); + $this->setEnablePCType("Tabs", true); + $this->setPreventHTMLUnmasking(true); + $this->setEnableInternalLinks(true); + $this->setEnableAnchors(true); + $this->setEnableWikiLinks(true); + $this->setIntLinkFilterWhiteList(true); + $this->addIntLinkFilter("RepositoryItem"); + $this->addIntLinkFilter("WikiPage"); + $this->addIntLinkFilter("User"); + $this->setIntLinkHelpDefaultType("RepositoryItem"); + $this->setEnablePCType("AMDPageList", true); + } + + /** + * Object specific configuration + * + * @param int $a_obj_id object id + */ + public function configureByObjectId($a_obj_id) + { + if ($a_obj_id > 0) { + include_once("./Modules/Wiki/classes/class.ilObjWiki.php"); + $this->setEnablePageToc(ilObjWiki::_lookupPageToc($a_obj_id)); + } + } } - -?> diff --git a/Modules/Wiki/classes/class.ilWikiPageGUI.php b/Modules/Wiki/classes/class.ilWikiPageGUI.php index cabea1dc701b28afefc0c3e9831e97d404ce5e53..5ae8b2bbab82535e6a65df149d60cfd7f67ffc5b 100755 --- a/Modules/Wiki/classes/class.ilWikiPageGUI.php +++ b/Modules/Wiki/classes/class.ilWikiPageGUI.php @@ -6,8 +6,8 @@ include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); /** * Class ilWikiPage GUI class -* -* @author Alex Killing +* +* @author Alex Killing * @version $Id$ * * @ilCtrl_Calls ilWikiPageGUI: ilPageEditorGUI, ilEditClipboardGUI, ilMediaPoolTargetSelector @@ -19,1433 +19,1445 @@ include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); */ class ilWikiPageGUI extends ilPageObjectGUI { - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilSetting - */ - protected $settings; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilObjWiki - */ - protected $wiki; - - /** - * @var \ILIAS\DI\UIServices - */ - protected $ui; - - /** - * Constructor - */ - function __construct($a_id = 0, $a_old_nr = 0, $a_wiki_ref_id = 0) - { - global $DIC; - - $this->tpl = $DIC["tpl"]; - $this->help = $DIC["ilHelp"]; - $this->ctrl = $DIC->ctrl(); - $this->tabs = $DIC->tabs(); - $this->user = $DIC->user(); - $this->access = $DIC->access(); - $this->lng = $DIC->language(); - $this->settings = $DIC->settings(); - $this->toolbar = $DIC->toolbar(); - $tpl = $DIC["tpl"]; - $this->ui = $DIC->ui(); - - // needed for notifications - $this->setWikiRefId($a_wiki_ref_id); - - parent::__construct("wpg", $a_id, $a_old_nr); - $this->getPageObject()->setWikiRefId($this->getWikiRefId()); - - // content style - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - - $tpl->setCurrentBlock("SyntaxStyle"); - $tpl->setVariable("LOCATION_SYNTAX_STYLESHEET", - ilObjStyleSheet::getSyntaxStylePath()); - $tpl->parseCurrentBlock(); - } - - /** - * Set screen id component - * - * @param - * @return - */ - function setScreenIdComponent() - { - $ilHelp = $this->help; - - $ilHelp->setScreenIdComponent("copgwpg"); - } - - function setWikiRefId($a_ref_id) + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilObjWiki + */ + protected $wiki; + + /** + * @var \ILIAS\DI\UIServices + */ + protected $ui; + + /** + * Constructor + */ + public function __construct($a_id = 0, $a_old_nr = 0, $a_wiki_ref_id = 0) + { + global $DIC; + + $this->tpl = $DIC["tpl"]; + $this->help = $DIC["ilHelp"]; + $this->ctrl = $DIC->ctrl(); + $this->tabs = $DIC->tabs(); + $this->user = $DIC->user(); + $this->access = $DIC->access(); + $this->lng = $DIC->language(); + $this->settings = $DIC->settings(); + $this->toolbar = $DIC->toolbar(); + $tpl = $DIC["tpl"]; + $this->ui = $DIC->ui(); + + // needed for notifications + $this->setWikiRefId($a_wiki_ref_id); + + parent::__construct("wpg", $a_id, $a_old_nr); + $this->getPageObject()->setWikiRefId($this->getWikiRefId()); + + // content style + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + + $tpl->setCurrentBlock("SyntaxStyle"); + $tpl->setVariable( + "LOCATION_SYNTAX_STYLESHEET", + ilObjStyleSheet::getSyntaxStylePath() + ); + $tpl->parseCurrentBlock(); + } + + /** + * Set screen id component + * + * @param + * @return + */ + public function setScreenIdComponent() { - $this->wiki_ref_id = $a_ref_id; - } + $ilHelp = $this->help; + + $ilHelp->setScreenIdComponent("copgwpg"); + } - function getWikiRefId() + public function setWikiRefId($a_ref_id) { - return $this->wiki_ref_id; - } - - /** - * Set wiki - * - * @param ilObjWiki $a_val wiki - */ - function setWiki($a_val) - { - $this->wiki = $a_val; - } - - /** - * Get wiki - * - * @return ilObjWiki wiki - */ - function getWiki() - { - return $this->wiki; - } - - /** - * execute command - */ - 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 - */ - function setWikiPage($a_wikipage) - { - $this->setPageObject($a_wikipage); - } - - /** - * Get Wiki Page Object. - * - * @return object Wiki Page Object - */ - function getWikiPage() - { - return $this->getPageObject(); - } - - /** - * Get wiki page gui for id and title - */ - 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; - } - - function setSideBlock() - { - ilObjWikiGUI::renderSideBlock($this->getWikiPage()->getId(), - $this->wiki_ref_id, $this->getWikiPage()); - } - - 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(); - } - } - - function redrawHeaderAction() - { - echo $this->addHeaderAction(true); - exit; - } - - /** - * View wiki page. - */ - 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 .= "
".sprintf($lng->txt("wiki_exercise_submitted_info"), - ilDatePresentation::formatDate(new ilDateTime($submitted["ts"], IL_CAL_DATETIME))); - - ilDatePresentation::setUseRelativeDates($rel); - $buttons[] = $ui->factory()->button()->standard($lng->txt("wiki_download_submission"), $dl_link); - } - - - $mbox = $ui->factory()->messageBox()->info($info) - ->withLinks($links) - ->withButtons($buttons); - - $message = $ui->renderer()->render($mbox); - - //ilUtil::sendInfo($info); - } - - - $this->increaseViewCount(); - - $this->addHeaderAction(); - - // content - $this->setSideBlock(); - - $wtpl = new ilTemplate("tpl.wiki_page_view_main_column.html", - true, true, "Modules/Wiki"); - - $callback = array($this, "observeNoteAction"); - - // notes - if (!$ilSetting->get("disable_comments") && - ilObjWiki::_lookupPublicNotes($this->getPageObject()->getParentId())) - { - $may_delete = ($ilSetting->get("comments_del_tutor", 1) && - $ilAccess->checkAccess("write", "", $_GET["ref_id"])); - $wtpl->setVariable("NOTES", $this->getNotesHTML($this->getPageObject(), - true, ilObjWiki::_lookupPublicNotes($this->getPageObject()->getParentId()), - $may_delete, $callback)); - } - - - // page content - $this->setOutputMode(IL_PAGE_PRESENTATION); - $this->setRenderPageContainer(true); - $wtpl->setVariable("PAGE", $this->showPage()); - - $tpl->setLoginTargetPar("wiki_".$_GET["ref_id"].$append); - - // last edited info - include_once("./Services/User/classes/class.ilUserUtil.php"); - $wtpl->setVariable("LAST_EDITED_INFO", - $lng->txt("wiki_last_edited").": ". - ilDatePresentation::formatDate( - new ilDateTime($this->getPageObject()->getLastChange(),IL_CAL_DATETIME)).", ". - ilUserUtil::getNamePresentation($this->getPageObject()->getLastChangeUser(), - false, true, $ilCtrl->getLinkTarget($this, "preview"))); - - $tpl->setLoginTargetPar("wiki_".$_GET["ref_id"].$append); - - //highlighting - if ($_GET["srcstring"] != "") - { - include_once './Services/Search/classes/class.ilUserSearchCache.php'; - $cache = ilUserSearchCache::_getInstance($ilUser->getId()); - $cache->switchSearchType(ilUserSearchCache::LAST_QUERY); - $search_string = $cache->getQuery(); - - // advanced search? - if(is_array($search_string)) - { - $search_string = $search_string["lom_content"]; - } - - include_once("./Services/UIComponent/TextHighlighter/classes/class.ilTextHighlighterGUI.php"); - include_once("./Services/Search/classes/class.ilQueryParser.php"); - $p = new ilQueryParser($search_string); - $p->parse(); - - $words = $p->getQuotedWords(); - if (is_array($words)) - { - foreach ($words as $w) - { - ilTextHighlighterGUI::highlight("ilCOPageContent", $w, $tpl); - } - } - $this->fill_on_load_code = true; - } - - return $message.$wtpl->get(); - } - - function showPage() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - - // content style -/* include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $tpl->setCurrentBlock("ContentStyle"); - $tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath(0)); - $tpl->parseCurrentBlock(); -*/ - $this->setTemplateOutput(false); - - if(!$this->getAbstractOnly()) - { - $this->setPresentationTitle($this->getWikiPage()->getTitle()); - - // wiki stats clean up - // $this->increaseViewCount(); - } - - return parent::showPage(); - } - - protected function increaseViewCount() - { - $ilUser = $this->user; - - $this->getWikiPage()->increaseViewCnt(); - - // enable object statistics - require_once('Services/Tracking/classes/class.ilChangeEvent.php'); - ilChangeEvent::_recordReadEvent("wiki", $this->getWikiPage()->getWikiRefId(), - $this->getWikiPage()->getWikiId(), $ilUser->getId()); - - include_once "./Modules/Wiki/classes/class.ilWikiStat.php"; - ilWikiStat::handleEvent(ilWikiStat::EVENT_PAGE_READ, $this->getWikiPage()); - } - - /** - * Finalizing output processing. - */ - function postOutputProcessing($a_output) - { - $ilCtrl = $this->ctrl; - -//echo htmlentities($a_output); - include_once("./Modules/Wiki/classes/class.ilWikiUtil.php"); - - $ilCtrl->setParameterByClass("ilobjwikigui", "from_page", ilWikiUtil::makeUrlTitle($_GET["page"])); - $output = ilWikiUtil::replaceInternalLinks($a_output, - $this->getWikiPage()->getWikiId(), - ($this->getOutputMode() == "offline")); - $ilCtrl->setParameterByClass("ilobjwikigui", "from_page", $_GET["from_page"]); - - - // metadata in print view - if ($this->getOutputMode() == "print" && $this->wiki instanceof ilObjWiki) - { - include_once("./Services/Object/classes/class.ilObjectMetaDataGUI.php"); - $mdgui = new ilObjectMetaDataGUI($this->wiki, "wpg", $this->getId()); - $md = $mdgui->getKeyValueList(); - if ($md != "") - { - $output = str_replace("", "

" . $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 .= "
" . sprintf( + $lng->txt("wiki_exercise_submitted_info"), + ilDatePresentation::formatDate(new ilDateTime($submitted["ts"], IL_CAL_DATETIME)) + ); + + ilDatePresentation::setUseRelativeDates($rel); + $buttons[] = $ui->factory()->button()->standard($lng->txt("wiki_download_submission"), $dl_link); + } + + + $mbox = $ui->factory()->messageBox()->info($info) + ->withLinks($links) + ->withButtons($buttons); + + $message = $ui->renderer()->render($mbox); + + //ilUtil::sendInfo($info); + } + + + $this->increaseViewCount(); + + $this->addHeaderAction(); + + // content + $this->setSideBlock(); + + $wtpl = new ilTemplate( + "tpl.wiki_page_view_main_column.html", + true, + true, + "Modules/Wiki" + ); + + $callback = array($this, "observeNoteAction"); + + // notes + if (!$ilSetting->get("disable_comments") && + ilObjWiki::_lookupPublicNotes($this->getPageObject()->getParentId())) { + $may_delete = ($ilSetting->get("comments_del_tutor", 1) && + $ilAccess->checkAccess("write", "", $_GET["ref_id"])); + $wtpl->setVariable("NOTES", $this->getNotesHTML( + $this->getPageObject(), + true, + ilObjWiki::_lookupPublicNotes($this->getPageObject()->getParentId()), + $may_delete, + $callback + )); + } + + + // page content + $this->setOutputMode(IL_PAGE_PRESENTATION); + $this->setRenderPageContainer(true); + $wtpl->setVariable("PAGE", $this->showPage()); + + $tpl->setLoginTargetPar("wiki_" . $_GET["ref_id"] . $append); + + // last edited info + include_once("./Services/User/classes/class.ilUserUtil.php"); + $wtpl->setVariable( + "LAST_EDITED_INFO", + $lng->txt("wiki_last_edited") . ": " . + ilDatePresentation::formatDate( + new ilDateTime($this->getPageObject()->getLastChange(), IL_CAL_DATETIME) + ) . ", " . + ilUserUtil::getNamePresentation( + $this->getPageObject()->getLastChangeUser(), + false, + true, + $ilCtrl->getLinkTarget($this, "preview") + ) + ); + + $tpl->setLoginTargetPar("wiki_" . $_GET["ref_id"] . $append); + + //highlighting + if ($_GET["srcstring"] != "") { + include_once './Services/Search/classes/class.ilUserSearchCache.php'; + $cache = ilUserSearchCache::_getInstance($ilUser->getId()); + $cache->switchSearchType(ilUserSearchCache::LAST_QUERY); + $search_string = $cache->getQuery(); + + // advanced search? + if (is_array($search_string)) { + $search_string = $search_string["lom_content"]; + } + + include_once("./Services/UIComponent/TextHighlighter/classes/class.ilTextHighlighterGUI.php"); + include_once("./Services/Search/classes/class.ilQueryParser.php"); + $p = new ilQueryParser($search_string); + $p->parse(); + + $words = $p->getQuotedWords(); + if (is_array($words)) { + foreach ($words as $w) { + ilTextHighlighterGUI::highlight("ilCOPageContent", $w, $tpl); + } + } + $this->fill_on_load_code = true; + } + + return $message . $wtpl->get(); + } + + public function showPage() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + + // content style + /* include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $tpl->setCurrentBlock("ContentStyle"); + $tpl->setVariable("LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath(0)); + $tpl->parseCurrentBlock(); + */ + $this->setTemplateOutput(false); + + if (!$this->getAbstractOnly()) { + $this->setPresentationTitle($this->getWikiPage()->getTitle()); + + // wiki stats clean up + // $this->increaseViewCount(); + } + + return parent::showPage(); + } + + protected function increaseViewCount() + { + $ilUser = $this->user; + + $this->getWikiPage()->increaseViewCnt(); + + // enable object statistics + require_once('Services/Tracking/classes/class.ilChangeEvent.php'); + ilChangeEvent::_recordReadEvent( + "wiki", + $this->getWikiPage()->getWikiRefId(), + $this->getWikiPage()->getWikiId(), + $ilUser->getId() + ); + + include_once "./Modules/Wiki/classes/class.ilWikiStat.php"; + ilWikiStat::handleEvent(ilWikiStat::EVENT_PAGE_READ, $this->getWikiPage()); + } + + /** + * Finalizing output processing. + */ + public function postOutputProcessing($a_output) + { + $ilCtrl = $this->ctrl; + + //echo htmlentities($a_output); + include_once("./Modules/Wiki/classes/class.ilWikiUtil.php"); + + $ilCtrl->setParameterByClass("ilobjwikigui", "from_page", ilWikiUtil::makeUrlTitle($_GET["page"])); + $output = ilWikiUtil::replaceInternalLinks( + $a_output, + $this->getWikiPage()->getWikiId(), + ($this->getOutputMode() == "offline") + ); + $ilCtrl->setParameterByClass("ilobjwikigui", "from_page", $_GET["from_page"]); + + + // metadata in print view + if ($this->getOutputMode() == "print" && $this->wiki instanceof ilObjWiki) { + include_once("./Services/Object/classes/class.ilObjectMetaDataGUI.php"); + $mdgui = new ilObjectMetaDataGUI($this->wiki, "wpg", $this->getId()); + $md = $mdgui->getKeyValueList(); + if ($md != "") { + $output = str_replace("", "

" . $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 * @version $Id$ - * @ingroup + * @ingroup */ class ilWikiUserHTMLExport { - const PROCESS_OTHER_USER = 0; // another user has started a running export - const PROCESS_STARTED = 1; // export has been started by current user - const PROCESS_UPTODATE = 2; // no export necessary, current export is up-to-date - - - const NOT_RUNNING = 0; - const RUNNING = 1; - - protected $data; - - /** - * @var ilDBInterface - */ - protected $db; - - /** - * @var ilObjWiki - */ - protected $wiki; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilLogger - */ - protected $log; - - /** - * Construct - * - * @param - * @return - */ - function __construct(ilObjWiki $a_wiki, ilDBInterface $a_db, ilObjUser $a_user) - { - $this->db = $a_db; - $this->wiki = $a_wiki; - $this->user = $a_user; - $this->read(); - $this->log = ilLoggerFactory::getLogger('wiki'); - } - - /** - * Read - * - * @param - * @return - */ - protected function read() - { - $set = $this->db->query("SELECT * FROM wiki_user_html_export ". - " WHERE wiki_id = ".$this->db->quote($this->wiki->getId(), "integer") - ); - if (!$this->data = $this->db->fetchAssoc($set)) - { - $this->data = array(); - } - } - - /** - * Get process - * - * @param - * @return - */ - protected function getProcess() - { - $this->log->debug("getProcess"); - $last_change = ilPageObject::getLastChangeByParent("wpg", $this->wiki->getId()); - - $ilAtomQuery = $this->db->buildAtomQuery(); - $ilAtomQuery->addTableLock('wiki_user_html_export'); - - $ilAtomQuery->addQueryCallable(function(ilDBInterface $ilDB) use ($last_change, &$ret){ - - $this->log->debug("atom query start"); - - $this->read(); - $ts = ilUtil::now(); - - if ($this->data["start_ts"] != "" && - $this->data["start_ts"] > $last_change) - { - $ret = self::PROCESS_UPTODATE; - $this->log->debug("return: ".self::PROCESS_UPTODATE); - return; - } - - if (!isset($this->data["wiki_id"])) - { - $this->log->debug("insert, wiki id: ".$this->wiki->getId().", user id: ".$this->user->getId().", ts: ".$ts); - $ilDB->manipulate("INSERT INTO wiki_user_html_export ". - "(wiki_id, usr_id, progress, start_ts, status) VALUES (". - $ilDB->quote($this->wiki->getId(), "integer").",". - $ilDB->quote($this->user->getId(), "integer").",". - $ilDB->quote(0, "integer").",". - $ilDB->quote($ts, "timestamp").",". - $ilDB->quote(self::RUNNING, "integer"). - ")"); - } - else - { - $this->log->debug("update, wiki id: ".$this->wiki->getId().", user id: ".$this->user->getId().", ts: ".$ts); - $ilDB->manipulate("UPDATE wiki_user_html_export SET ". - " start_ts = ".$ilDB->quote($ts, "timestamp").",". - " usr_id = ".$ilDB->quote($this->user->getId(), "integer").",". - " progress = ".$ilDB->quote(0, "integer").",". - " status = ".$ilDB->quote(self::RUNNING, "integer"). - " WHERE status = ".$ilDB->quote(self::NOT_RUNNING, "integer"). - " AND wiki_id = ".$ilDB->quote($this->wiki->getId(), "integer") - ); - $this->read(); - } - - if ($this->data["start_ts"] == $ts && $this->data["usr_id"] == $this->user->getId()) - { - // we started the process - $ret = self::PROCESS_STARTED; - $this->log->debug("return: ".self::PROCESS_STARTED); - return; - } - - // process was already running - $ret = self::PROCESS_OTHER_USER; - $this->log->debug("return: ".self::PROCESS_OTHER_USER); - }); - - $ilAtomQuery->run(); - - $this->log->debug("outer return: ".$ret); - - return $ret; - } - - /** - * Update status - * - * @param - * @return - */ - public function updateStatus($a_progress, $a_status) - { - $this->db->manipulate("UPDATE wiki_user_html_export SET ". - " progress = ".$this->db->quote((int) $a_progress, "integer").",". - " status = ".$this->db->quote((int) $a_status, "integer"). - " WHERE wiki_id = ".$this->db->quote($this->wiki->getId(), "integer"). - " AND usr_id = ".$this->db->quote($this->user->getId(), "integer") - ); - - $this->read(); - } - - /** - * Get Progress - * - * @param - * @return - */ - function getProgress() - { - $set = $this->db->query("SELECT progress, status FROM wiki_user_html_export ". - " WHERE wiki_id = ".$this->db->quote($this->wiki->getId(), "integer") - ); - $rec = $this->db->fetchAssoc($set); - - return array("progress" => (int) $rec["progress"], "status" => (int) $rec["status"]); - } - - - /** - * Init user html export - * - * @param - * @return - */ - public function initUserHTMLExport() - { - // get process, if not already running or export is up-to-date, return corresponding status - echo $this->getProcess(); - exit; - } - - /** - * Start user html export - */ - function startUserHTMLExport() - { - ignore_user_abort(true); - // do the export - include_once("./Modules/Wiki/classes/class.ilWikiHTMLExport.php"); - $exp = new ilWikiHTMLExport($this->wiki); - $exp->setMode(ilWikiHTMLExport::MODE_USER); - $exp->buildExportFile(); - // reset user export status - $this->updateStatus(100, self::NOT_RUNNING); - exit; - } - - /** - * Deliver file - */ - function deliverFile() - { - $this->log->debug("deliver"); - include_once("./Modules/Wiki/classes/class.ilWikiHTMLExport.php"); - $exp = new ilWikiHTMLExport($this->wiki); - $exp->setMode(ilWikiHTMLExport::MODE_USER); - $file = $exp->getUserExportFile(); - $this->log->debug("file: ".$file); - ilUtil::deliverFile($file, pathinfo($file, PATHINFO_BASENAME)); - } - - + const PROCESS_OTHER_USER = 0; // another user has started a running export + const PROCESS_STARTED = 1; // export has been started by current user + const PROCESS_UPTODATE = 2; // no export necessary, current export is up-to-date + + + const NOT_RUNNING = 0; + const RUNNING = 1; + + protected $data; + + /** + * @var ilDBInterface + */ + protected $db; + + /** + * @var ilObjWiki + */ + protected $wiki; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilLogger + */ + protected $log; + + /** + * Construct + * + * @param + * @return + */ + public function __construct(ilObjWiki $a_wiki, ilDBInterface $a_db, ilObjUser $a_user) + { + $this->db = $a_db; + $this->wiki = $a_wiki; + $this->user = $a_user; + $this->read(); + $this->log = ilLoggerFactory::getLogger('wiki'); + } + + /** + * Read + * + * @param + * @return + */ + protected function read() + { + $set = $this->db->query( + "SELECT * FROM wiki_user_html_export " . + " WHERE wiki_id = " . $this->db->quote($this->wiki->getId(), "integer") + ); + if (!$this->data = $this->db->fetchAssoc($set)) { + $this->data = array(); + } + } + + /** + * Get process + * + * @param + * @return + */ + protected function getProcess() + { + $this->log->debug("getProcess"); + $last_change = ilPageObject::getLastChangeByParent("wpg", $this->wiki->getId()); + + $ilAtomQuery = $this->db->buildAtomQuery(); + $ilAtomQuery->addTableLock('wiki_user_html_export'); + + $ilAtomQuery->addQueryCallable(function (ilDBInterface $ilDB) use ($last_change, &$ret) { + $this->log->debug("atom query start"); + + $this->read(); + $ts = ilUtil::now(); + + if ($this->data["start_ts"] != "" && + $this->data["start_ts"] > $last_change) { + $ret = self::PROCESS_UPTODATE; + $this->log->debug("return: " . self::PROCESS_UPTODATE); + return; + } + + if (!isset($this->data["wiki_id"])) { + $this->log->debug("insert, wiki id: " . $this->wiki->getId() . ", user id: " . $this->user->getId() . ", ts: " . $ts); + $ilDB->manipulate("INSERT INTO wiki_user_html_export " . + "(wiki_id, usr_id, progress, start_ts, status) VALUES (" . + $ilDB->quote($this->wiki->getId(), "integer") . "," . + $ilDB->quote($this->user->getId(), "integer") . "," . + $ilDB->quote(0, "integer") . "," . + $ilDB->quote($ts, "timestamp") . "," . + $ilDB->quote(self::RUNNING, "integer") . + ")"); + } else { + $this->log->debug("update, wiki id: " . $this->wiki->getId() . ", user id: " . $this->user->getId() . ", ts: " . $ts); + $ilDB->manipulate( + "UPDATE wiki_user_html_export SET " . + " start_ts = " . $ilDB->quote($ts, "timestamp") . "," . + " usr_id = " . $ilDB->quote($this->user->getId(), "integer") . "," . + " progress = " . $ilDB->quote(0, "integer") . "," . + " status = " . $ilDB->quote(self::RUNNING, "integer") . + " WHERE status = " . $ilDB->quote(self::NOT_RUNNING, "integer") . + " AND wiki_id = " . $ilDB->quote($this->wiki->getId(), "integer") + ); + $this->read(); + } + + if ($this->data["start_ts"] == $ts && $this->data["usr_id"] == $this->user->getId()) { + // we started the process + $ret = self::PROCESS_STARTED; + $this->log->debug("return: " . self::PROCESS_STARTED); + return; + } + + // process was already running + $ret = self::PROCESS_OTHER_USER; + $this->log->debug("return: " . self::PROCESS_OTHER_USER); + }); + + $ilAtomQuery->run(); + + $this->log->debug("outer return: " . $ret); + + return $ret; + } + + /** + * Update status + * + * @param + * @return + */ + public function updateStatus($a_progress, $a_status) + { + $this->db->manipulate( + "UPDATE wiki_user_html_export SET " . + " progress = " . $this->db->quote((int) $a_progress, "integer") . "," . + " status = " . $this->db->quote((int) $a_status, "integer") . + " WHERE wiki_id = " . $this->db->quote($this->wiki->getId(), "integer") . + " AND usr_id = " . $this->db->quote($this->user->getId(), "integer") + ); + + $this->read(); + } + + /** + * Get Progress + * + * @param + * @return + */ + public function getProgress() + { + $set = $this->db->query( + "SELECT progress, status FROM wiki_user_html_export " . + " WHERE wiki_id = " . $this->db->quote($this->wiki->getId(), "integer") + ); + $rec = $this->db->fetchAssoc($set); + + return array("progress" => (int) $rec["progress"], "status" => (int) $rec["status"]); + } + + + /** + * Init user html export + * + * @param + * @return + */ + public function initUserHTMLExport() + { + // get process, if not already running or export is up-to-date, return corresponding status + echo $this->getProcess(); + exit; + } + + /** + * Start user html export + */ + public function startUserHTMLExport() + { + ignore_user_abort(true); + // do the export + include_once("./Modules/Wiki/classes/class.ilWikiHTMLExport.php"); + $exp = new ilWikiHTMLExport($this->wiki); + $exp->setMode(ilWikiHTMLExport::MODE_USER); + $exp->buildExportFile(); + // reset user export status + $this->updateStatus(100, self::NOT_RUNNING); + exit; + } + + /** + * Deliver file + */ + public function deliverFile() + { + $this->log->debug("deliver"); + include_once("./Modules/Wiki/classes/class.ilWikiHTMLExport.php"); + $exp = new ilWikiHTMLExport($this->wiki); + $exp->setMode(ilWikiHTMLExport::MODE_USER); + $file = $exp->getUserExportFile(); + $this->log->debug("file: " . $file); + ilUtil::deliverFile($file, pathinfo($file, PATHINFO_BASENAME)); + } } - -?> \ No newline at end of file diff --git a/Modules/Wiki/classes/class.ilWikiUtil.php b/Modules/Wiki/classes/class.ilWikiUtil.php index 171c5fa327e09ead681b308af2cfcac2856766c5..10d9d746e531d98cf9c9b786c60cd550934f8eeb 100755 --- a/Modules/Wiki/classes/class.ilWikiUtil.php +++ b/Modules/Wiki/classes/class.ilWikiUtil.php @@ -15,9 +15,9 @@ * the ilWikiUtil::makeUrlTitle($mTextform) ("_" for " ")for embedding things in URLs. * */ -define ("IL_WIKI_MODE_REPLACE", "replace"); -define ("IL_WIKI_MODE_COLLECT", "collect"); -define ("IL_WIKI_MODE_EXT_COLLECT", "ext_collect"); +define("IL_WIKI_MODE_REPLACE", "replace"); +define("IL_WIKI_MODE_COLLECT", "collect"); +define("IL_WIKI_MODE_EXT_COLLECT", "ext_collect"); /** * Utility class for wiki. @@ -30,752 +30,734 @@ define ("IL_WIKI_MODE_EXT_COLLECT", "ext_collect"); class ilWikiUtil { - /** - * This one is based on Mediawiki Parser->replaceInternalLinks - * since we display images in another way, only text links are processed - * - * @param string input string - * @param string input string - * - * @return string output string - */ - static function replaceInternalLinks($s, $a_wiki_id, $a_offline = false) - { - return ilWikiUtil::processInternalLinks($s, $a_wiki_id, - IL_WIKI_MODE_REPLACE, false, $a_offline); - } - - /** - * Collect internal wiki links of a string - * - * @param string input string - * @return string output string - */ - static function collectInternalLinks($s, $a_wiki_id, $a_collect_non_ex = false) - { - return ilWikiUtil::processInternalLinks($s, $a_wiki_id, IL_WIKI_MODE_COLLECT, - $a_collect_non_ex); - } - - /** - * Process internal links - * - * string $s string that includes internal wiki links - * int $a_wiki_id wiki id - * mode - */ - static function processInternalLinks($s, $a_wiki_id, - $a_mode = IL_WIKI_MODE_REPLACE, $a_collect_non_ex = false, - $a_offline = false) - { - $collect = array(); - // both from mediawiki DefaulSettings.php - $wgLegalTitleChars = " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z~\\x80-\\xFF+"; - - // Adapter for media wiki classes - include_once("./Modules/Wiki/classes/class.ilMediaWikiAdapter.php"); - $GLOBALS["wgContLang"] = new ilMediaWikiAdapter(); - $GLOBALS["wgInterWikiCache"] = false; - - # the % is needed to support urlencoded titles as well - //$tc = Title::legalChars().'#%'; - $tc = $wgLegalTitleChars.'#%'; - - //$sk = $this->mOptions->getSkin(); - - #split the entire text string on occurences of [[ - $a = explode( '[[', ' ' . $s ); - #get the first element (all text up to first [[), and remove the space we added - $s = array_shift( $a ); - $s = substr( $s, 1 ); - - # Match a link having the form [[namespace:link|alternate]]trail - $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; - - # Match cases where there is no "]]", which might still be images -// static $e1_img = FALSE; -// if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; } - - # Match the end of a line for a word that's not followed by whitespace, - # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched -// $e2 = wfMsgForContent( 'linkprefix' ); - -/* $useLinkPrefixExtension = $wgContLang->linkPrefixExtension(); - if( is_null( $this->mTitle ) ) { - throw new MWException( __METHOD__.": \$this->mTitle is null\n" ); - } - $nottalk = !$this->mTitle->isTalkPage();*/ - $nottalk = true; - -/* if ( $useLinkPrefixExtension ) { - $m = array(); - if ( preg_match( $e2, $s, $m ) ) { - $first_prefix = $m[2]; - } else { - $first_prefix = false; - } - } else {*/ - $prefix = ''; -// } - - $useSubpages = false; - - # Loop for each link - for ($k = 0; isset( $a[$k] ); $k++) - { - $line = $a[$k]; - - - $might_be_img = false; - - //wfProfileIn( "$fname-e1" ); - if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt - $text = $m[2]; - # If we get a ] at the beginning of $m[3] that means we have a link that's something like: - # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up, - # the real problem is with the $e1 regex - # See bug 1300. - # - # Still some problems for cases where the ] is meant to be outside punctuation, - # and no image is in sight. See bug 2095. - # - if( $text !== '' && - substr( $m[3], 0, 1 ) === ']' && - strpos($text, '[') !== false - ) - { - $text .= ']'; # so that replaceExternalLinks($text) works later - $m[3] = substr( $m[3], 1 ); - } - # fix up urlencoded title texts - if( strpos( $m[1], '%' ) !== false ) { - # Should anchors '#' also be rejected? - $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) ); - } - $trail = $m[3]; -/* } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption - $might_be_img = true; - $text = $m[2]; - if ( strpos( $m[1], '%' ) !== false ) { - $m[1] = urldecode($m[1]); - } - $trail = "";*/ - } else { # Invalid form; output directly - $s .= $prefix . '[[' . $line ; - //wfProfileOut( "$fname-e1" ); - continue; - } - //wfProfileOut( "$fname-e1" ); - //wfProfileIn( "$fname-misc" ); - - # Don't allow internal links to pages containing - # PROTO: where PROTO is a valid URL protocol; these - # should be external links. - if (preg_match('/^\b(?:' . ilWikiUtil::wfUrlProtocols() . ')/', $m[1])) { - $s .= $prefix . '[[' . $line ; - continue; - } - - # Make subpage if necessary -/* if( $useSubpages ) { - $link = $this->maybeDoSubpageLink( $m[1], $text ); - } else {*/ - $link = $m[1]; -// } - - $noforce = (substr($m[1], 0, 1) != ':'); - if (!$noforce) { - # Strip off leading ':' - $link = substr($link, 1); - } - -// wfProfileOut( "$fname-misc" ); -// wfProfileIn( "$fname-title" ); - - // todo - include_once("./Modules/Wiki/mediawiki/Title.php"); - include_once("./Services/Utilities/classes/Sanitizer.php"); - //$nt = Title::newFromText( $this->mStripState->unstripNoWiki($link) ); - - // todo: check step by step -//echo "
".htmlentities($link)."---"; - $nt = Title::newFromText($link); - - if( !$nt ) { - $s .= $prefix . '[[' . $line; - //wfProfileOut( "$fname-title" ); - continue; - } - -/* $ns = $nt->getNamespace(); - $iw = $nt->getInterWiki(); - wfProfileOut( "$fname-title" ); - -/* if ($might_be_img) { # if this is actually an invalid link - wfProfileIn( "$fname-might_be_img" ); - if ($ns == NS_IMAGE && $noforce) { #but might be an image - $found = false; - while (isset ($a[$k+1]) ) { - #look at the next 'line' to see if we can close it there - $spliced = array_splice( $a, $k + 1, 1 ); - $next_line = array_shift( $spliced ); - $m = explode( ']]', $next_line, 3 ); - if ( count( $m ) == 3 ) { - # the first ]] closes the inner link, the second the image - $found = true; - $text .= "[[{$m[0]}]]{$m[1]}"; - $trail = $m[2]; - break; - } elseif ( count( $m ) == 2 ) { - #if there's exactly one ]] that's fine, we'll keep looking - $text .= "[[{$m[0]}]]{$m[1]}"; - } else { - #if $next_line is invalid too, we need look no further - $text .= '[[' . $next_line; - break; - } - } - if ( !$found ) { - # we couldn't find the end of this imageLink, so output it raw - #but don't ignore what might be perfectly normal links in the text we've examined - $text = $this->replaceInternalLinks($text); - $s .= "{$prefix}[[$link|$text"; - # note: no $trail, because without an end, there *is* no trail - wfProfileOut( "$fname-might_be_img" ); - continue; - } - } else { #it's not an image, so output it raw - $s .= "{$prefix}[[$link|$text"; - # note: no $trail, because without an end, there *is* no trail - wfProfileOut( "$fname-might_be_img" ); - continue; - } - wfProfileOut( "$fname-might_be_img" ); - } -*/ - - $wasblank = ( '' == $text ); - if( $wasblank ) $text = $link; - - # Link not escaped by : , create the various objects - if( $noforce ) { - # Interwikis - /*wfProfileIn( "$fname-interwiki" ); - if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) { - $this->mOutput->addLanguageLink( $nt->getFullText() ); - $s = rtrim($s . $prefix); - $s .= trim($trail, "\n") == '' ? '': $prefix . $trail; - wfProfileOut( "$fname-interwiki" ); - continue; - } - wfProfileOut( "$fname-interwiki" );*/ + /** + * This one is based on Mediawiki Parser->replaceInternalLinks + * since we display images in another way, only text links are processed + * + * @param string input string + * @param string input string + * + * @return string output string + */ + public static function replaceInternalLinks($s, $a_wiki_id, $a_offline = false) + { + return ilWikiUtil::processInternalLinks( + $s, + $a_wiki_id, + IL_WIKI_MODE_REPLACE, + false, + $a_offline + ); + } + + /** + * Collect internal wiki links of a string + * + * @param string input string + * @return string output string + */ + public static function collectInternalLinks($s, $a_wiki_id, $a_collect_non_ex = false) + { + return ilWikiUtil::processInternalLinks( + $s, + $a_wiki_id, + IL_WIKI_MODE_COLLECT, + $a_collect_non_ex + ); + } + + /** + * Process internal links + * + * string $s string that includes internal wiki links + * int $a_wiki_id wiki id + * mode + */ + public static function processInternalLinks( + $s, + $a_wiki_id, + $a_mode = IL_WIKI_MODE_REPLACE, + $a_collect_non_ex = false, + $a_offline = false + ) { + $collect = array(); + // both from mediawiki DefaulSettings.php + $wgLegalTitleChars = " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z~\\x80-\\xFF+"; + + // Adapter for media wiki classes + include_once("./Modules/Wiki/classes/class.ilMediaWikiAdapter.php"); + $GLOBALS["wgContLang"] = new ilMediaWikiAdapter(); + $GLOBALS["wgInterWikiCache"] = false; + + # the % is needed to support urlencoded titles as well + //$tc = Title::legalChars().'#%'; + $tc = $wgLegalTitleChars . '#%'; + + //$sk = $this->mOptions->getSkin(); + + #split the entire text string on occurences of [[ + $a = explode('[[', ' ' . $s); + #get the first element (all text up to first [[), and remove the space we added + $s = array_shift($a); + $s = substr($s, 1); + + # Match a link having the form [[namespace:link|alternate]]trail + $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; + + # Match cases where there is no "]]", which might still be images + // static $e1_img = FALSE; + // if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; } + + # Match the end of a line for a word that's not followed by whitespace, + # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched + // $e2 = wfMsgForContent( 'linkprefix' ); + + /* $useLinkPrefixExtension = $wgContLang->linkPrefixExtension(); + if( is_null( $this->mTitle ) ) { + throw new MWException( __METHOD__.": \$this->mTitle is null\n" ); + } + $nottalk = !$this->mTitle->isTalkPage();*/ + $nottalk = true; + + /* if ( $useLinkPrefixExtension ) { + $m = array(); + if ( preg_match( $e2, $s, $m ) ) { + $first_prefix = $m[2]; + } else { + $first_prefix = false; + } + } else {*/ + $prefix = ''; + // } + + $useSubpages = false; + + # Loop for each link + for ($k = 0; isset($a[$k]); $k++) { + $line = $a[$k]; + + + $might_be_img = false; + + //wfProfileIn( "$fname-e1" ); + if (preg_match($e1, $line, $m)) { # page with normal text or alt + $text = $m[2]; + # If we get a ] at the beginning of $m[3] that means we have a link that's something like: + # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up, + # the real problem is with the $e1 regex + # See bug 1300. + # + # Still some problems for cases where the ] is meant to be outside punctuation, + # and no image is in sight. See bug 2095. + # + if ($text !== '' && + substr($m[3], 0, 1) === ']' && + strpos($text, '[') !== false + ) { + $text .= ']'; # so that replaceExternalLinks($text) works later + $m[3] = substr($m[3], 1); + } + # fix up urlencoded title texts + if (strpos($m[1], '%') !== false) { + # Should anchors '#' also be rejected? + $m[1] = str_replace(array('<', '>'), array('<', '>'), urldecode($m[1])); + } + $trail = $m[3]; + /* } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption + $might_be_img = true; + $text = $m[2]; + if ( strpos( $m[1], '%' ) !== false ) { + $m[1] = urldecode($m[1]); + } + $trail = "";*/ + } else { # Invalid form; output directly + $s .= $prefix . '[[' . $line ; + //wfProfileOut( "$fname-e1" ); + continue; + } + //wfProfileOut( "$fname-e1" ); + //wfProfileIn( "$fname-misc" ); + + # Don't allow internal links to pages containing + # PROTO: where PROTO is a valid URL protocol; these + # should be external links. + if (preg_match('/^\b(?:' . ilWikiUtil::wfUrlProtocols() . ')/', $m[1])) { + $s .= $prefix . '[[' . $line ; + continue; + } + + # Make subpage if necessary + /* if( $useSubpages ) { + $link = $this->maybeDoSubpageLink( $m[1], $text ); + } else {*/ + $link = $m[1]; + // } + + $noforce = (substr($m[1], 0, 1) != ':'); + if (!$noforce) { + # Strip off leading ':' + $link = substr($link, 1); + } + + // wfProfileOut( "$fname-misc" ); + // wfProfileIn( "$fname-title" ); + + // todo + include_once("./Modules/Wiki/mediawiki/Title.php"); + include_once("./Services/Utilities/classes/Sanitizer.php"); + //$nt = Title::newFromText( $this->mStripState->unstripNoWiki($link) ); + + // todo: check step by step + //echo "
".htmlentities($link)."---"; + $nt = Title::newFromText($link); + + if (!$nt) { + $s .= $prefix . '[[' . $line; + //wfProfileOut( "$fname-title" ); + continue; + } + + /* $ns = $nt->getNamespace(); + $iw = $nt->getInterWiki(); + wfProfileOut( "$fname-title" ); + + /* if ($might_be_img) { # if this is actually an invalid link + wfProfileIn( "$fname-might_be_img" ); + if ($ns == NS_IMAGE && $noforce) { #but might be an image + $found = false; + while (isset ($a[$k+1]) ) { + #look at the next 'line' to see if we can close it there + $spliced = array_splice( $a, $k + 1, 1 ); + $next_line = array_shift( $spliced ); + $m = explode( ']]', $next_line, 3 ); + if ( count( $m ) == 3 ) { + # the first ]] closes the inner link, the second the image + $found = true; + $text .= "[[{$m[0]}]]{$m[1]}"; + $trail = $m[2]; + break; + } elseif ( count( $m ) == 2 ) { + #if there's exactly one ]] that's fine, we'll keep looking + $text .= "[[{$m[0]}]]{$m[1]}"; + } else { + #if $next_line is invalid too, we need look no further + $text .= '[[' . $next_line; + break; + } + } + if ( !$found ) { + # we couldn't find the end of this imageLink, so output it raw + #but don't ignore what might be perfectly normal links in the text we've examined + $text = $this->replaceInternalLinks($text); + $s .= "{$prefix}[[$link|$text"; + # note: no $trail, because without an end, there *is* no trail + wfProfileOut( "$fname-might_be_img" ); + continue; + } + } else { #it's not an image, so output it raw + $s .= "{$prefix}[[$link|$text"; + # note: no $trail, because without an end, there *is* no trail + wfProfileOut( "$fname-might_be_img" ); + continue; + } + wfProfileOut( "$fname-might_be_img" ); + } + */ + + $wasblank = ('' == $text); + if ($wasblank) { + $text = $link; + } + + # Link not escaped by : , create the various objects + if ($noforce) { + # Interwikis + /*wfProfileIn( "$fname-interwiki" ); + if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) { + $this->mOutput->addLanguageLink( $nt->getFullText() ); + $s = rtrim($s . $prefix); + $s .= trim($trail, "\n") == '' ? '': $prefix . $trail; + wfProfileOut( "$fname-interwiki" ); + continue; + } + wfProfileOut( "$fname-interwiki" );*/ /* if ( $ns == NS_IMAGE ) { - wfProfileIn( "$fname-image" ); - if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) { - # recursively parse links inside the image caption - # actually, this will parse them in any other parameters, too, - # but it might be hard to fix that, and it doesn't matter ATM - $text = $this->replaceExternalLinks($text); - $text = $this->replaceInternalLinks($text); - - # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them - $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail; - $this->mOutput->addImage( $nt->getDBkey() ); - - wfProfileOut( "$fname-image" ); - continue; - } else { - # We still need to record the image's presence on the page - $this->mOutput->addImage( $nt->getDBkey() ); - } - wfProfileOut( "$fname-image" ); - - } + wfProfileIn( "$fname-image" ); + if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) { + # recursively parse links inside the image caption + # actually, this will parse them in any other parameters, too, + # but it might be hard to fix that, and it doesn't matter ATM + $text = $this->replaceExternalLinks($text); + $text = $this->replaceInternalLinks($text); + + # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them + $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail; + $this->mOutput->addImage( $nt->getDBkey() ); + + wfProfileOut( "$fname-image" ); + continue; + } else { + # We still need to record the image's presence on the page + $this->mOutput->addImage( $nt->getDBkey() ); + } + wfProfileOut( "$fname-image" ); + + } */ /* if ( $ns == NS_CATEGORY ) { - wfProfileIn( "$fname-category" ); - $s = rtrim($s . "\n"); # bug 87 - - if ( $wasblank ) { - $sortkey = $this->getDefaultSort(); - } else { - $sortkey = $text; - } - $sortkey = Sanitizer::decodeCharReferences( $sortkey ); - $sortkey = str_replace( "\n", '', $sortkey ); - $sortkey = $wgContLang->convertCategoryKey( $sortkey ); - $this->mOutput->addCategory( $nt->getDBkey(), $sortkey ); + wfProfileIn( "$fname-category" ); + $s = rtrim($s . "\n"); # bug 87 + + if ( $wasblank ) { + $sortkey = $this->getDefaultSort(); + } else { + $sortkey = $text; + } + $sortkey = Sanitizer::decodeCharReferences( $sortkey ); + $sortkey = str_replace( "\n", '', $sortkey ); + $sortkey = $wgContLang->convertCategoryKey( $sortkey ); + $this->mOutput->addCategory( $nt->getDBkey(), $sortkey ); */ - /** - * Strip the whitespace Category links produce, see bug 87 - * @todo We might want to use trim($tmp, "\n") here. - */ + /** + * Strip the whitespace Category links produce, see bug 87 + * @todo We might want to use trim($tmp, "\n") here. + */ // $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail; // wfProfileOut( "$fname-category" ); // continue; // } - } - - # Self-link checking -/* if( $nt->getFragment() === '' ) { - if( in_array( $nt->getPrefixedText(), $selflink, true ) ) { - $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail ); - continue; - } - }*/ - - # Special and Media are pseudo-namespaces; no pages actually exist in them -/* if( $ns == NS_MEDIA ) { - $link = $sk->makeMediaLinkObj( $nt, $text ); - # Cloak with NOPARSE to avoid replacement in replaceExternalLinks - $s .= $prefix . $this->armorLinks( $link ) . $trail; - $this->mOutput->addImage( $nt->getDBkey() ); - continue; - } elseif( $ns == NS_SPECIAL ) { - $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix ); - continue; - } elseif( $ns == NS_IMAGE ) { - $img = new Image( $nt ); - if( $img->exists() ) { - // Force a blue link if the file exists; may be a remote - // upload on the shared repository, and we want to see its - // auto-generated page. - $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix ); - $this->mOutput->addLink( $nt ); - continue; - } - }*/ - - // Media wiki performs an intermediate step here (Parser->makeLinkHolder) - if ($a_mode == IL_WIKI_MODE_REPLACE) - { - $s .= ilWikiUtil::makeLink($nt, $a_wiki_id, $text, '', $trail, $prefix, - $a_offline); -//echo "
-".htmlentities($s)."-"; - } - if ($a_mode == IL_WIKI_MODE_EXT_COLLECT) - { - if (is_object($nt)) - { - $url_title = ilWikiUtil::makeUrlTitle($nt->mTextform); - $db_title = ilWikiUtil::makeDbTitle($nt->mTextform); - list( $inside, $trail ) = ilWikiUtil::splitTrail( $trail ); - $collect[] = array("nt" => $nt, "text" => $text, - "trail" => $trail, "db_title" => $db_title, - "url_title" => $url_title); - } - } - else - { - $url_title = ilWikiUtil::makeUrlTitle($nt->mTextform); - $db_title = ilWikiUtil::makeDbTitle($nt->mTextform); - - //$s .= ilWikiUtil::makeLink($nt, $a_wiki_id, $text, '', $trail, $prefix); - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - if ((ilWikiPage::_wikiPageExists($a_wiki_id, $db_title) || - $a_collect_non_ex) - && - !in_array($db_title, $collect)) - { - $collect[] = $db_title; - } - } - } - - //wfProfileOut( $fname ); - - if ($a_mode == IL_WIKI_MODE_COLLECT || - $a_mode == IL_WIKI_MODE_EXT_COLLECT) - { - return $collect; - } - else - { - return $s; - } - } - - /** - * See class.ilInitialisation.php - */ - static function removeUnsafeCharacters($a_str) - { - return str_replace(array("\x00", "\n", "\r", "\\", "'", '"', "\x1a"), "", $a_str); - } - - /** - * Make a wiki link, the following formats are supported: - * - * [[Page Title]] - * [[Page Title|Presentation Text]] - * [[Page Title#Anchor]] - * [[Page Title#Anchor|Presentation Text]] - * [[#Anchor|Presentation Text]] (link to anchor on same wiki page) - */ - static function makeLink( &$nt, $a_wiki_id, $text = '', $query = '', $trail = '', $prefix = '', - $a_offline = false) - { - global $DIC; - - $ilCtrl = $DIC->ctrl(); - - //wfProfileIn( __METHOD__ ); - if ( ! is_object($nt) ) { - # Fail gracefully - $retVal = "{$prefix}{$text}{$trail}"; - } else { - -//var_dump($trail); -//var_dump($nt); - - // remove anchor from text, define anchor - $anc = ""; - if ($nt->mFragment != "") - { - if (substr($text, strlen($text) - strlen("#".$nt->mFragment)) - == "#".$nt->mFragment) - { - $text = substr($text, 0, strlen($text) - strlen("#".$nt->mFragment)); - $anc = "#".$nt->mFragment; - } - else - { - $anc = "#".$nt->mFragment; - } - } - - # Separate the link trail from the rest of the link - // outcommented due to bug #14590 -// list( $inside, $trail ) = ilWikiUtil::splitTrail( $trail ); - - $retVal = '***'.$text."***".$trail; - $url_title = ilWikiUtil::makeUrlTitle($nt->mTextform); - $db_title = ilWikiUtil::makeDbTitle($nt->mTextform); - if ($db_title != "") - { - $pg_exists = ilWikiPage::_wikiPageExists($a_wiki_id, $db_title); - } - else - { - // links on same page (only anchor used) - $pg_exists = true; - } - -//var_dump($nt); -//var_dump($inside); + } + + # Self-link checking + /* if( $nt->getFragment() === '' ) { + if( in_array( $nt->getPrefixedText(), $selflink, true ) ) { + $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail ); + continue; + } + }*/ + + # Special and Media are pseudo-namespaces; no pages actually exist in them + /* if( $ns == NS_MEDIA ) { + $link = $sk->makeMediaLinkObj( $nt, $text ); + # Cloak with NOPARSE to avoid replacement in replaceExternalLinks + $s .= $prefix . $this->armorLinks( $link ) . $trail; + $this->mOutput->addImage( $nt->getDBkey() ); + continue; + } elseif( $ns == NS_SPECIAL ) { + $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix ); + continue; + } elseif( $ns == NS_IMAGE ) { + $img = new Image( $nt ); + if( $img->exists() ) { + // Force a blue link if the file exists; may be a remote + // upload on the shared repository, and we want to see its + // auto-generated page. + $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix ); + $this->mOutput->addLink( $nt ); + continue; + } + }*/ + + // Media wiki performs an intermediate step here (Parser->makeLinkHolder) + if ($a_mode == IL_WIKI_MODE_REPLACE) { + $s .= ilWikiUtil::makeLink( + $nt, + $a_wiki_id, + $text, + '', + $trail, + $prefix, + $a_offline + ); + //echo "
-".htmlentities($s)."-"; + } + if ($a_mode == IL_WIKI_MODE_EXT_COLLECT) { + if (is_object($nt)) { + $url_title = ilWikiUtil::makeUrlTitle($nt->mTextform); + $db_title = ilWikiUtil::makeDbTitle($nt->mTextform); + list($inside, $trail) = ilWikiUtil::splitTrail($trail); + $collect[] = array("nt" => $nt, "text" => $text, + "trail" => $trail, "db_title" => $db_title, + "url_title" => $url_title); + } + } else { + $url_title = ilWikiUtil::makeUrlTitle($nt->mTextform); + $db_title = ilWikiUtil::makeDbTitle($nt->mTextform); + + //$s .= ilWikiUtil::makeLink($nt, $a_wiki_id, $text, '', $trail, $prefix); + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + if ((ilWikiPage::_wikiPageExists($a_wiki_id, $db_title) || + $a_collect_non_ex) + && + !in_array($db_title, $collect)) { + $collect[] = $db_title; + } + } + } + + //wfProfileOut( $fname ); + + if ($a_mode == IL_WIKI_MODE_COLLECT || + $a_mode == IL_WIKI_MODE_EXT_COLLECT) { + return $collect; + } else { + return $s; + } + } + + /** + * See class.ilInitialisation.php + */ + public static function removeUnsafeCharacters($a_str) + { + return str_replace(array("\x00", "\n", "\r", "\\", "'", '"', "\x1a"), "", $a_str); + } + + /** + * Make a wiki link, the following formats are supported: + * + * [[Page Title]] + * [[Page Title|Presentation Text]] + * [[Page Title#Anchor]] + * [[Page Title#Anchor|Presentation Text]] + * [[#Anchor|Presentation Text]] (link to anchor on same wiki page) + */ + public static function makeLink( + &$nt, + $a_wiki_id, + $text = '', + $query = '', + $trail = '', + $prefix = '', + $a_offline = false + ) { + global $DIC; + + $ilCtrl = $DIC->ctrl(); + + //wfProfileIn( __METHOD__ ); + if (!is_object($nt)) { + # Fail gracefully + $retVal = "{$prefix}{$text}{$trail}"; + } else { + //var_dump($trail); - $wiki_link_class = (!$pg_exists) - ? ' class="ilc_link_IntLink ilWikiPageMissing" ' - : ' class="ilc_link_IntLink" '; - - if (!$a_offline) - { - if ($url_title != "") - { - $ilCtrl->setParameterByClass("ilobjwikigui", "page", $url_title); - $retVal = ''.$text.''.$trail; - $ilCtrl->setParameterByClass("ilobjwikigui", "page", $_GET["page"]); - } - else - { - $retVal = ''.$text.''.$trail; - } - } - else - { - if ($pg_exists) - { - if ($db_title != "") - { - $pg_id = ilWikiPage::getIdForPageTitle($a_wiki_id, $db_title); - $retVal = ''.$text.''.$trail; - } - else - { - $retVal = ''.$text.''.$trail; - } - } - else - { - $retVal = $text.$trail; - } - } - -/* if ( $nt->isExternal() ) { - $nr = array_push( $this->mInterwikiLinkHolders['texts'], $prefix.$text.$inside ); - $this->mInterwikiLinkHolders['titles'][] = $nt; - $retVal = '{$trail}"; - } else { - $nr = array_push( $this->mLinkHolders['namespaces'], $nt->getNamespace() ); - $this->mLinkHolders['dbkeys'][] = $nt->getDBkey(); - $this->mLinkHolders['queries'][] = $query; - $this->mLinkHolders['texts'][] = $prefix.$text.$inside; - $this->mLinkHolders['titles'][] = $nt; - - $retVal = '{$trail}"; - } -*/ - } - //wfProfileOut( __METHOD__ ); -//echo "
".$retVal; exit; - return $retVal; - } - - /** - * From mediawiki GlobalFunctions.php - */ - static function wfUrlProtocols() - { - $wgUrlProtocols = array( - 'http://', - 'https://', - 'ftp://', - 'irc://', - 'gopher://', - 'telnet://', // Well if we're going to support the above.. -ævar - 'nntp://', // @bug 3808 RFC 1738 - 'worldwind://', - 'mailto:', - 'news:' - ); - - // Support old-style $wgUrlProtocols strings, for backwards compatibility - // with LocalSettings files from 1.5 - if ( is_array( $wgUrlProtocols ) ) { - $protocols = array(); - foreach ($wgUrlProtocols as $protocol) - $protocols[] = preg_quote( $protocol, '/' ); - - return implode( '|', $protocols ); - } else { - return $wgUrlProtocols; - } - } - - /** - * From GlobalFunctions.php - */ - public static function wfUrlencode ( $s ) - { - $s = urlencode( $s ); -// $s = preg_replace( '/%3[Aa]/', ':', $s ); -// $s = preg_replace( '/%2[Ff]/', '/', $s ); - - return $s; - } - - - /** - * Handle page GET parameter - */ - static function makeDbTitle($a_par) - { - $a_par = ilWikiUtil::removeUnsafeCharacters($a_par); - return str_replace("_", " ", $a_par); - } - - /** - * Set page parameter for Url Embedding - */ - static function makeUrlTitle($a_par) - { - $a_par = ilWikiUtil::removeUnsafeCharacters($a_par); - $a_par = str_replace(" ", "_", $a_par); - return ilWikiUtil::wfUrlencode($a_par); - } - - // from Linker.php - static function splitTrail( $trail ) - { - $regex = '/^([a-z]+)(.*)$/sD'; - - $inside = ''; - if ( '' != $trail ) { - $m = array(); - - if ( preg_match( $regex, $trail, $m ) ) { - $inside = $m[1]; - $trail = $m[2]; - } - } - - return array( $inside, $trail ); - } - - static function sendNotification($a_action, $a_type, $a_wiki_ref_id, $a_page_id, $a_comment = null) - { - global $DIC; - - $ilUser = $DIC->user(); - $ilObjDataCache = $DIC["ilObjDataCache"]; - $ilAccess = $DIC->access(); - - include_once "./Services/Notification/classes/class.ilNotification.php"; - include_once "./Modules/Wiki/classes/class.ilObjWiki.php"; - include_once "./Modules/Wiki/classes/class.ilWikiPage.php"; - - $wiki_id = $ilObjDataCache->lookupObjId($a_wiki_ref_id); - $wiki = new ilObjWiki($a_wiki_ref_id, true); - $page = new ilWikiPage($a_page_id); - - // #11138 - $ignore_threshold = ($a_action == "comment"); - - // 1st update will be converted to new - see below - if($a_action == "new") - { - return; - } - - if($a_type == ilNotification::TYPE_WIKI_PAGE) - { - $users = ilNotification::getNotificationsForObject($a_type, $a_page_id, null, $ignore_threshold); - $wiki_users = ilNotification::getNotificationsForObject(ilNotification::TYPE_WIKI, $wiki_id, $a_page_id, $ignore_threshold); - $users = array_merge($users, $wiki_users); - if(!sizeof($users)) - { - return; - } - - ilNotification::updateNotificationTime(ilNotification::TYPE_WIKI_PAGE, $a_page_id, $users); - } - else - { - $users = ilNotification::getNotificationsForObject(ilNotification::TYPE_WIKI, $wiki_id, $a_page_id, $ignore_threshold); - if(!sizeof($users)) - { - return; - } - } - - ilNotification::updateNotificationTime(ilNotification::TYPE_WIKI, $wiki_id, $users, $a_page_id); - - // #15192 - should always be present - include_once "./Services/Link/classes/class.ilLink.php"; - if($a_page_id) - { - // #18804 - see ilWikiPageGUI::preview() - $link = ilLink::_getLink("", "wiki", null, "wpage_".$a_page_id."_".$a_wiki_ref_id); - } - else - { - - $link = ilLink::_getLink($a_wiki_ref_id); - } - - include_once "./Services/Mail/classes/class.ilMail.php"; - include_once "./Services/User/classes/class.ilObjUser.php"; - include_once "./Services/Language/classes/class.ilLanguageFactory.php"; - include_once("./Services/User/classes/class.ilUserUtil.php"); - - - // see ilBlogPostingGUI::getSnippet() - // see ilBlogPosting::getNotificationAbstract() - - include_once "Modules/Wiki/classes/class.ilWikiPageGUI.php"; - $pgui = new ilWikiPageGUI($page->getId()); - $pgui->setRawPageContent(true); - $pgui->setAbstractOnly(true); - $pgui->setFileDownloadLink("."); - $pgui->setFullscreenLink("."); - $pgui->setSourcecodeDownloadScript("."); - $snippet = $pgui->showPage(); - $snippet = ilPageObject::truncateHTML($snippet, 500, "..."); - - // making things more readable - $snippet = str_replace('
', "\n", $snippet); - $snippet = str_replace('
', "\n", $snippet); - $snippet = str_replace('

', "\n", $snippet); - $snippet = str_replace('
', "\n", $snippet); - - $snippet = trim(strip_tags($snippet)); - - // "fake" new (to enable snippet - if any) - $current_version = array_shift($page->getHistoryEntries()); - $current_version = $current_version["nr"]; - if(!$current_version) - { - $a_type = ilNotification::TYPE_WIKI; - $a_action = "new"; - } - - - foreach(array_unique($users) as $idx => $user_id) - { - if($user_id != $ilUser->getId() && - $ilAccess->checkAccessOfUser($user_id, 'read', '', $a_wiki_ref_id)) - { - // use language of recipient to compose message - $ulng = ilLanguageFactory::_getLanguageOfUser($user_id); - $ulng->loadLanguageModule('wiki'); - - $subject = sprintf($ulng->txt('wiki_change_notification_subject'), $wiki->getTitle(), $page->getTitle()); - $message = sprintf($ulng->txt('wiki_change_notification_salutation'), ilObjUser::_lookupFullname($user_id))."\n\n"; - - if($a_type == ilNotification::TYPE_WIKI_PAGE) - { - // update/delete - $message .= $ulng->txt('wiki_change_notification_page_body_'.$a_action).":\n\n"; - $message .= $ulng->txt('wiki').": ".$wiki->getTitle()."\n"; - $message .= $ulng->txt('page').": ".$page->getTitle()."\n"; - $message .= $ulng->txt('wiki_changed_by').": ".ilUserUtil::getNamePresentation($ilUser->getId())."\n"; - - if($snippet) - { - $message .= "\n".$ulng->txt('content')."\n". - "----------------------------------------\n". - $snippet."\n". - "----------------------------------------\n"; - } - - // include comment/note text - if($a_comment) - { - $message .= "\n".$ulng->txt('comment').":\n\"".trim($a_comment)."\"\n"; - } - - $message .= "\n".$ulng->txt('wiki_change_notification_page_link').": ".$link; - } - else - { - // new - $message .= $ulng->txt('wiki_change_notification_body_'.$a_action).":\n\n"; - $message .= $ulng->txt('wiki').": ".$wiki->getTitle()."\n"; - $message .= $ulng->txt('page').": ".$page->getTitle()."\n"; - $message .= $ulng->txt('wiki_changed_by').": ".ilUserUtil::getNamePresentation($ilUser->getId())."\n\n"; - - if($snippet) - { - $message .= $ulng->txt('content')."\n". - "----------------------------------------\n". - $snippet."\n". - "----------------------------------------\n\n"; - } - - $message .= $ulng->txt('wiki_change_notification_link').": ".$link; - } - - $mail_obj = new ilMail(ANONYMOUS_USER_ID); - $mail_obj->appendInstallationSignature(true); - $mail_obj->sendMail(ilObjUser::_lookupLogin($user_id), - "", "", $subject, $message, array(), array("system")); - } - else - { - unset($users[$idx]); - } - } - } + //var_dump($nt); + + // remove anchor from text, define anchor + $anc = ""; + if ($nt->mFragment != "") { + if (substr($text, strlen($text) - strlen("#" . $nt->mFragment)) + == "#" . $nt->mFragment) { + $text = substr($text, 0, strlen($text) - strlen("#" . $nt->mFragment)); + $anc = "#" . $nt->mFragment; + } else { + $anc = "#" . $nt->mFragment; + } + } + + # Separate the link trail from the rest of the link + // outcommented due to bug #14590 + // list( $inside, $trail ) = ilWikiUtil::splitTrail( $trail ); + + $retVal = '***' . $text . "***" . $trail; + $url_title = ilWikiUtil::makeUrlTitle($nt->mTextform); + $db_title = ilWikiUtil::makeDbTitle($nt->mTextform); + if ($db_title != "") { + $pg_exists = ilWikiPage::_wikiPageExists($a_wiki_id, $db_title); + } else { + // links on same page (only anchor used) + $pg_exists = true; + } + + //var_dump($nt); + //var_dump($inside); + //var_dump($trail); + $wiki_link_class = (!$pg_exists) + ? ' class="ilc_link_IntLink ilWikiPageMissing" ' + : ' class="ilc_link_IntLink" '; + + if (!$a_offline) { + if ($url_title != "") { + $ilCtrl->setParameterByClass("ilobjwikigui", "page", $url_title); + $retVal = '' . $text . '' . $trail; + $ilCtrl->setParameterByClass("ilobjwikigui", "page", $_GET["page"]); + } else { + $retVal = '' . $text . '' . $trail; + } + } else { + if ($pg_exists) { + if ($db_title != "") { + $pg_id = ilWikiPage::getIdForPageTitle($a_wiki_id, $db_title); + $retVal = '' . $text . '' . $trail; + } else { + $retVal = '' . $text . '' . $trail; + } + } else { + $retVal = $text . $trail; + } + } + + /* if ( $nt->isExternal() ) { + $nr = array_push( $this->mInterwikiLinkHolders['texts'], $prefix.$text.$inside ); + $this->mInterwikiLinkHolders['titles'][] = $nt; + $retVal = '{$trail}"; + } else { + $nr = array_push( $this->mLinkHolders['namespaces'], $nt->getNamespace() ); + $this->mLinkHolders['dbkeys'][] = $nt->getDBkey(); + $this->mLinkHolders['queries'][] = $query; + $this->mLinkHolders['texts'][] = $prefix.$text.$inside; + $this->mLinkHolders['titles'][] = $nt; + + $retVal = '{$trail}"; + } + */ + } + //wfProfileOut( __METHOD__ ); + //echo "
".$retVal; exit; + return $retVal; + } + + /** + * From mediawiki GlobalFunctions.php + */ + public static function wfUrlProtocols() + { + $wgUrlProtocols = array( + 'http://', + 'https://', + 'ftp://', + 'irc://', + 'gopher://', + 'telnet://', // Well if we're going to support the above.. -ævar + 'nntp://', // @bug 3808 RFC 1738 + 'worldwind://', + 'mailto:', + 'news:' + ); + + // Support old-style $wgUrlProtocols strings, for backwards compatibility + // with LocalSettings files from 1.5 + if (is_array($wgUrlProtocols)) { + $protocols = array(); + foreach ($wgUrlProtocols as $protocol) { + $protocols[] = preg_quote($protocol, '/'); + } + + return implode('|', $protocols); + } else { + return $wgUrlProtocols; + } + } + + /** + * From GlobalFunctions.php + */ + public static function wfUrlencode($s) + { + $s = urlencode($s); + // $s = preg_replace( '/%3[Aa]/', ':', $s ); + // $s = preg_replace( '/%2[Ff]/', '/', $s ); + + return $s; + } + + + /** + * Handle page GET parameter + */ + public static function makeDbTitle($a_par) + { + $a_par = ilWikiUtil::removeUnsafeCharacters($a_par); + return str_replace("_", " ", $a_par); + } + + /** + * Set page parameter for Url Embedding + */ + public static function makeUrlTitle($a_par) + { + $a_par = ilWikiUtil::removeUnsafeCharacters($a_par); + $a_par = str_replace(" ", "_", $a_par); + return ilWikiUtil::wfUrlencode($a_par); + } + + // from Linker.php + public static function splitTrail($trail) + { + $regex = '/^([a-z]+)(.*)$/sD'; + + $inside = ''; + if ('' != $trail) { + $m = array(); + + if (preg_match($regex, $trail, $m)) { + $inside = $m[1]; + $trail = $m[2]; + } + } + + return array( $inside, $trail ); + } + + public static function sendNotification($a_action, $a_type, $a_wiki_ref_id, $a_page_id, $a_comment = null) + { + global $DIC; + + $ilUser = $DIC->user(); + $ilObjDataCache = $DIC["ilObjDataCache"]; + $ilAccess = $DIC->access(); + + include_once "./Services/Notification/classes/class.ilNotification.php"; + include_once "./Modules/Wiki/classes/class.ilObjWiki.php"; + include_once "./Modules/Wiki/classes/class.ilWikiPage.php"; + + $wiki_id = $ilObjDataCache->lookupObjId($a_wiki_ref_id); + $wiki = new ilObjWiki($a_wiki_ref_id, true); + $page = new ilWikiPage($a_page_id); + + // #11138 + $ignore_threshold = ($a_action == "comment"); + + // 1st update will be converted to new - see below + if ($a_action == "new") { + return; + } + + if ($a_type == ilNotification::TYPE_WIKI_PAGE) { + $users = ilNotification::getNotificationsForObject($a_type, $a_page_id, null, $ignore_threshold); + $wiki_users = ilNotification::getNotificationsForObject(ilNotification::TYPE_WIKI, $wiki_id, $a_page_id, $ignore_threshold); + $users = array_merge($users, $wiki_users); + if (!sizeof($users)) { + return; + } + + ilNotification::updateNotificationTime(ilNotification::TYPE_WIKI_PAGE, $a_page_id, $users); + } else { + $users = ilNotification::getNotificationsForObject(ilNotification::TYPE_WIKI, $wiki_id, $a_page_id, $ignore_threshold); + if (!sizeof($users)) { + return; + } + } + + ilNotification::updateNotificationTime(ilNotification::TYPE_WIKI, $wiki_id, $users, $a_page_id); + + // #15192 - should always be present + include_once "./Services/Link/classes/class.ilLink.php"; + if ($a_page_id) { + // #18804 - see ilWikiPageGUI::preview() + $link = ilLink::_getLink("", "wiki", null, "wpage_" . $a_page_id . "_" . $a_wiki_ref_id); + } else { + $link = ilLink::_getLink($a_wiki_ref_id); + } + + include_once "./Services/Mail/classes/class.ilMail.php"; + include_once "./Services/User/classes/class.ilObjUser.php"; + include_once "./Services/Language/classes/class.ilLanguageFactory.php"; + include_once("./Services/User/classes/class.ilUserUtil.php"); + + + // see ilBlogPostingGUI::getSnippet() + // see ilBlogPosting::getNotificationAbstract() + + include_once "Modules/Wiki/classes/class.ilWikiPageGUI.php"; + $pgui = new ilWikiPageGUI($page->getId()); + $pgui->setRawPageContent(true); + $pgui->setAbstractOnly(true); + $pgui->setFileDownloadLink("."); + $pgui->setFullscreenLink("."); + $pgui->setSourcecodeDownloadScript("."); + $snippet = $pgui->showPage(); + $snippet = ilPageObject::truncateHTML($snippet, 500, "..."); + + // making things more readable + $snippet = str_replace('
', "\n", $snippet); + $snippet = str_replace('
', "\n", $snippet); + $snippet = str_replace('

', "\n", $snippet); + $snippet = str_replace('', "\n", $snippet); + + $snippet = trim(strip_tags($snippet)); + + // "fake" new (to enable snippet - if any) + $current_version = array_shift($page->getHistoryEntries()); + $current_version = $current_version["nr"]; + if (!$current_version) { + $a_type = ilNotification::TYPE_WIKI; + $a_action = "new"; + } + + + foreach (array_unique($users) as $idx => $user_id) { + if ($user_id != $ilUser->getId() && + $ilAccess->checkAccessOfUser($user_id, 'read', '', $a_wiki_ref_id)) { + // use language of recipient to compose message + $ulng = ilLanguageFactory::_getLanguageOfUser($user_id); + $ulng->loadLanguageModule('wiki'); + + $subject = sprintf($ulng->txt('wiki_change_notification_subject'), $wiki->getTitle(), $page->getTitle()); + $message = sprintf($ulng->txt('wiki_change_notification_salutation'), ilObjUser::_lookupFullname($user_id)) . "\n\n"; + + if ($a_type == ilNotification::TYPE_WIKI_PAGE) { + // update/delete + $message .= $ulng->txt('wiki_change_notification_page_body_' . $a_action) . ":\n\n"; + $message .= $ulng->txt('wiki') . ": " . $wiki->getTitle() . "\n"; + $message .= $ulng->txt('page') . ": " . $page->getTitle() . "\n"; + $message .= $ulng->txt('wiki_changed_by') . ": " . ilUserUtil::getNamePresentation($ilUser->getId()) . "\n"; + + if ($snippet) { + $message .= "\n" . $ulng->txt('content') . "\n" . + "----------------------------------------\n" . + $snippet . "\n" . + "----------------------------------------\n"; + } + + // include comment/note text + if ($a_comment) { + $message .= "\n" . $ulng->txt('comment') . ":\n\"" . trim($a_comment) . "\"\n"; + } + + $message .= "\n" . $ulng->txt('wiki_change_notification_page_link') . ": " . $link; + } else { + // new + $message .= $ulng->txt('wiki_change_notification_body_' . $a_action) . ":\n\n"; + $message .= $ulng->txt('wiki') . ": " . $wiki->getTitle() . "\n"; + $message .= $ulng->txt('page') . ": " . $page->getTitle() . "\n"; + $message .= $ulng->txt('wiki_changed_by') . ": " . ilUserUtil::getNamePresentation($ilUser->getId()) . "\n\n"; + + if ($snippet) { + $message .= $ulng->txt('content') . "\n" . + "----------------------------------------\n" . + $snippet . "\n" . + "----------------------------------------\n\n"; + } + + $message .= $ulng->txt('wiki_change_notification_link') . ": " . $link; + } + + $mail_obj = new ilMail(ANONYMOUS_USER_ID); + $mail_obj->appendInstallationSignature(true); + $mail_obj->sendMail( + ilObjUser::_lookupLogin($user_id), + "", + "", + $subject, + $message, + array(), + array("system") + ); + } else { + unset($users[$idx]); + } + } + } } - -?> diff --git a/Modules/Wiki/exceptions/class.ilWikiException.php b/Modules/Wiki/exceptions/class.ilWikiException.php index 3c6d31d7e03488f48453abab9be01055a282ca0e..f350d1a5afb086424db2dd66bab68c40fbec4670 100644 --- a/Modules/Wiki/exceptions/class.ilWikiException.php +++ b/Modules/Wiki/exceptions/class.ilWikiException.php @@ -12,6 +12,4 @@ require_once 'Services/Exceptions/classes/class.ilException.php'; */ class ilWikiException extends ilException { - } -?> \ No newline at end of file diff --git a/Modules/Wiki/exceptions/class.ilWikiExportException.php b/Modules/Wiki/exceptions/class.ilWikiExportException.php index 00a28cdbfc6fa45f9e883ccf9156eba77c47f551..b8ac110abceb386aee3af4c59bc0fba04c9d16f4 100644 --- a/Modules/Wiki/exceptions/class.ilWikiExportException.php +++ b/Modules/Wiki/exceptions/class.ilWikiExportException.php @@ -12,6 +12,4 @@ require_once 'Modules/Wiki/exceptions/class.ilWikiException.php'; */ class ilWikiExportException extends ilWikiException { - } -?> \ No newline at end of file diff --git a/Modules/Wiki/mediawiki/Title.php b/Modules/Wiki/mediawiki/Title.php index a580567b81f6a7920a77046d6c9d3a75940afde1..8f1b589c541a87507e6b9d518742a342b261f4fe 100644 --- a/Modules/Wiki/mediawiki/Title.php +++ b/Modules/Wiki/mediawiki/Title.php @@ -5,27 +5,27 @@ */ /** */ -if ( !class_exists( 'UtfNormal' ) ) { - require_once( 'include/Unicode/UtfNormal.php' ); +if (!class_exists('UtfNormal')) { + require_once('include/Unicode/UtfNormal.php'); } // patched: alex, 30.4.2019: Added missing defines -define ( 'NS_MAIN', "nsmain"); -define ( 'NS_SPECIAL', "nsspecial"); +define('NS_MAIN', "nsmain"); +define('NS_SPECIAL', "nsspecial"); -define ( 'GAID_FOR_UPDATE', 1 ); +define('GAID_FOR_UPDATE', 1); # Title::newFromTitle maintains a cache to avoid # expensive re-normalization of commonly used titles. # On a batch operation this can become a memory leak # if not bounded. After hitting this many titles, # reset the cache. -define( 'MW_TITLECACHE_MAX', 1000 ); +define('MW_TITLECACHE_MAX', 1000); # Constants for pr_cascade bitfield -define( 'CASCADE', 1 ); +define('CASCADE', 1); /** * Title class @@ -33,1864 +33,2006 @@ define( 'CASCADE', 1 ); * - Can fetch various kinds of data from the database, albeit inefficiently. * */ -class Title { - /** - * Static cache variables - */ - static private $titleCache=array(); - static private $interwikiCache=array(); - - - /** - * All member variables should be considered private - * Please use the accessor functions - */ - - /**#@+ - * @private - */ - - var $mTextform; # Text form (spaces not underscores) of the main part - var $mUrlform; # URL-encoded form of the main part - var $mDbkeyform; # Main part with underscores - var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants - var $mInterwiki; # Interwiki prefix (or null string) - var $mFragment; # Title fragment (i.e. the bit after the #) - var $mArticleID; # Article ID, fetched from the link cache on demand - var $mLatestID; # ID of most recent revision - var $mRestrictions; # Array of groups allowed to edit this article - var $mCascadeRestriction; # Cascade restrictions on this page to included templates and images? - var $mRestrictionsExpiry; # When do the restrictions on this page expire? - var $mHasCascadingRestrictions; # Are cascading restrictions in effect on this page? - var $mCascadeRestrictionSources;# Where are the cascading restrictions coming from on this page? - var $mRestrictionsLoaded; # Boolean for initialisation on demand - var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand - var $mDefaultNamespace; # Namespace index when there is no namespace - # Zero except in {{transclusion}} tags - var $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching() - /**#@-*/ - - - /** - * Constructor - * @private - */ - /* private */ function __construct() { - $this->mInterwiki = $this->mUrlform = - $this->mTextform = $this->mDbkeyform = ''; - $this->mArticleID = -1; - $this->mNamespace = NS_MAIN; - $this->mRestrictionsLoaded = false; - $this->mRestrictions = array(); - # Dont change the following, NS_MAIN is hardcoded in several place - # See bug #696 - $this->mDefaultNamespace = NS_MAIN; - $this->mWatched = NULL; - $this->mLatestID = false; - $this->mOldRestrictions = false; - } - - /** - * Create a new Title from a prefixed DB key - * @param string $key The database key, which has underscores - * instead of spaces, possibly including namespace and - * interwiki prefixes - * @return Title the new object, or NULL on an error - */ - public static function newFromDBkey( $key ) { - $t = new Title(); - $t->mDbkeyform = $key; - if( $t->secureAndSplit() ) - return $t; - else - return NULL; - } - - /** - * Create a new Title from text, such as what one would - * find in a link. Decodes any HTML entities in the text. - * - * @param string $text the link text; spaces, prefixes, - * and an initial ':' indicating the main namespace - * are accepted - * @param int $defaultNamespace the namespace to use if - * none is specified by a prefix - * @return Title the new object, or NULL on an error - */ - public static function newFromText( $text, $defaultNamespace = NS_MAIN ) { - if( is_object( $text ) ) { - throw new MWException( 'Title::newFromText given an object' ); - } - - /** - * Wiki pages often contain multiple links to the same page. - * Title normalization and parsing can become expensive on - * pages with many links, so we can save a little time by - * caching them. - * - * In theory these are value objects and won't get changed... - */ - if( $defaultNamespace == NS_MAIN && isset( Title::$titleCache[$text] ) ) { - return Title::$titleCache[$text]; - } - - /** - * Convert things like é ā or 〗 into real text... - */ - $filteredText = Sanitizer::decodeCharReferences( $text ); - - $t = new Title(); - $t->mDbkeyform = str_replace( ' ', '_', $filteredText ); - $t->mDefaultNamespace = $defaultNamespace; - - static $cachedcount = 0 ; - if( $t->secureAndSplit() ) { - if( $defaultNamespace == NS_MAIN ) { - if( $cachedcount >= MW_TITLECACHE_MAX ) { - # Avoid memory leaks on mass operations... - Title::$titleCache = array(); - $cachedcount=0; - } - $cachedcount++; - Title::$titleCache[$text] =& $t; - } - return $t; - } else { - $ret = NULL; - return $ret; - } - } - - /** - * Create a new Title from URL-encoded text. Ensures that - * the given title's length does not exceed the maximum. - * @param string $url the title, as might be taken from a URL - * @return Title the new object, or NULL on an error - */ - public static function newFromURL( $url ) { - global $wgLegalTitleChars; - $t = new Title(); - - # For compatibility with old buggy URLs. "+" is usually not valid in titles, - # but some URLs used it as a space replacement and they still come - # from some external search tools. - if ( strpos( $wgLegalTitleChars, '+' ) === false ) { - $url = str_replace( '+', ' ', $url ); - } - - $t->mDbkeyform = str_replace( ' ', '_', $url ); - if( $t->secureAndSplit() ) { - return $t; - } else { - return NULL; - } - } - - /** - * Create a new Title from an article ID - * - * @todo This is inefficiently implemented, the page row is requested - * but not used for anything else - * - * @param int $id the page_id corresponding to the Title to create - * @return Title the new object, or NULL on an error - */ - public static function newFromID( $id ) { - $fname = 'Title::newFromID'; - $dbr = wfGetDB( DB_SLAVE ); - $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ), - array( 'page_id' => $id ), $fname ); - if ( $row !== false ) { - $title = Title::makeTitle( $row->page_namespace, $row->page_title ); - } else { - $title = NULL; - } - return $title; - } - - /** - * Make an array of titles from an array of IDs - */ - public static function newFromIDs( $ids ) { - $dbr = wfGetDB( DB_SLAVE ); - $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ), - 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__ ); - - $titles = array(); - while ( $row = $dbr->fetchObject( $res ) ) { - $titles[] = Title::makeTitle( $row->page_namespace, $row->page_title ); - } - return $titles; - } - - /** - * Create a new Title from a namespace index and a DB key. - * It's assumed that $ns and $title are *valid*, for instance when - * they came directly from the database or a special page name. - * For convenience, spaces are converted to underscores so that - * eg user_text fields can be used directly. - * - * @param int $ns the namespace of the article - * @param string $title the unprefixed database key form - * @return Title the new object - */ - public static function &makeTitle( $ns, $title ) { - $t = new Title(); - $t->mInterwiki = ''; - $t->mFragment = ''; - $t->mNamespace = intval( $ns ); - $t->mDbkeyform = str_replace( ' ', '_', $title ); - $t->mArticleID = ( $ns >= 0 ) ? -1 : 0; - $t->mUrlform = wfUrlencode( $t->mDbkeyform ); - $t->mTextform = str_replace( '_', ' ', $title ); - return $t; - } - - /** - * Create a new Title from a namespace index and a DB key. - * The parameters will be checked for validity, which is a bit slower - * than makeTitle() but safer for user-provided data. - * - * @param int $ns the namespace of the article - * @param string $title the database key form - * @return Title the new object, or NULL on an error - */ - public static function makeTitleSafe( $ns, $title ) { - $t = new Title(); - $t->mDbkeyform = Title::makeName( $ns, $title ); - if( $t->secureAndSplit() ) { - return $t; - } else { - return NULL; - } - } - - /** - * Create a new Title for the Main Page - * @return Title the new object - */ - public static function newMainPage() { - return Title::newFromText( wfMsgForContent( 'mainpage' ) ); - } - - /** - * Create a new Title for a redirect - * @param string $text the redirect title text - * @return Title the new object, or NULL if the text is not a - * valid redirect - */ - public static function newFromRedirect( $text ) { - $mwRedir = MagicWord::get( 'redirect' ); - $rt = NULL; - if ( $mwRedir->matchStart( $text ) ) { - $m = array(); - if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) { - # categories are escaped using : for example one can enter: - # #REDIRECT [[:Category:Music]]. Need to remove it. - if ( substr($m[1],0,1) == ':') { - # We don't want to keep the ':' - $m[1] = substr( $m[1], 1 ); - } - - $rt = Title::newFromText( $m[1] ); - # Disallow redirects to Special:Userlogout - if ( !is_null($rt) && $rt->isSpecial( 'Userlogout' ) ) { - $rt = NULL; - } - } - } - return $rt; - } - -#---------------------------------------------------------------------------- -# Static functions -#---------------------------------------------------------------------------- - - /** - * Get the prefixed DB key associated with an ID - * @param int $id the page_id of the article - * @return Title an object representing the article, or NULL - * if no such article was found - * @static - * @access public - */ - function nameOf( $id ) { - $fname = 'Title::nameOf'; - $dbr = wfGetDB( DB_SLAVE ); - - $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname ); - if ( $s === false ) { return NULL; } - - $n = Title::makeName( $s->page_namespace, $s->page_title ); - return $n; - } - - /** - * Get a regex character class describing the legal characters in a link - * @return string the list of characters, not delimited - */ - public static function legalChars() { - global $wgLegalTitleChars; - - $wgLegalTitleChars = " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z~\\x80-\\xFF+"; - - return $wgLegalTitleChars; - } - - /** - * Get a string representation of a title suitable for - * including in a search index - * - * @param int $ns a namespace index - * @param string $title text-form main part - * @return string a stripped-down title string ready for the - * search index - */ - public static function indexTitle( $ns, $title ) { - global $wgContLang; - - $lc = SearchEngine::legalSearchChars() . '&#;'; - $t = $wgContLang->stripForSearch( $title ); - $t = preg_replace( "/[^{$lc}]+/", ' ', $t ); - $t = $wgContLang->lc( $t ); - - # Handle 's, s' - $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t ); - $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t ); - - $t = preg_replace( "/\\s+/", ' ', $t ); - - if ( $ns == NS_IMAGE ) { - $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t ); - } - return trim( $t ); - } - - /* - * Make a prefixed DB key from a DB key and a namespace index - * @param int $ns numerical representation of the namespace - * @param string $title the DB key form the title - * @return string the prefixed form of the title - */ - public static function makeName( $ns, $title ) { - global $wgContLang; - - $n = $wgContLang->getNsText( $ns ); - return $n == '' ? $title : "$n:$title"; - } - - /** - * Returns the URL associated with an interwiki prefix - * @param string $key the interwiki prefix (e.g. "MeatBall") - * @return the associated URL, containing "$1", which should be - * replaced by an article title - * @static (arguably) - */ - public function getInterwikiLink( $key ) { - global $wgMemc, $wgInterwikiExpiry; - global $wgInterwikiCache, $wgContLang; - -return ""; // changed. alex - - $fname = 'Title::getInterwikiLink'; - - $key = $wgContLang->lc( $key ); - - $k = wfMemcKey( 'interwiki', $key ); - if( array_key_exists( $k, Title::$interwikiCache ) ) { - return Title::$interwikiCache[$k]->iw_url; - } - - if ($wgInterwikiCache) { - return Title::getInterwikiCached( $key ); - } - - $s = $wgMemc->get( $k ); - # Ignore old keys with no iw_local - if( $s && isset( $s->iw_local ) && isset($s->iw_trans)) { - Title::$interwikiCache[$k] = $s; - return $s->iw_url; - } - - $dbr = wfGetDB( DB_SLAVE ); - $res = $dbr->select( 'interwiki', - array( 'iw_url', 'iw_local', 'iw_trans' ), - array( 'iw_prefix' => $key ), $fname ); - if( !$res ) { - return ''; - } - - $s = $dbr->fetchObject( $res ); - if( !$s ) { - # Cache non-existence: create a blank object and save it to memcached - $s = (object)false; - $s->iw_url = ''; - $s->iw_local = 0; - $s->iw_trans = 0; - } - $wgMemc->set( $k, $s, $wgInterwikiExpiry ); - Title::$interwikiCache[$k] = $s; - - return $s->iw_url; - } - - /** - * Fetch interwiki prefix data from local cache in constant database - * - * More logic is explained in DefaultSettings - * - * @return string URL of interwiki site - */ - public static function getInterwikiCached( $key ) { - global $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite; - static $db, $site; - - if (!$db) - $db=dba_open($wgInterwikiCache,'r','cdb'); - /* Resolve site name */ - if ($wgInterwikiScopes>=3 and !$site) { - $site = dba_fetch('__sites:' . wfWikiID(), $db); - if ($site=="") - $site = $wgInterwikiFallbackSite; - } - $value = dba_fetch( wfMemcKey( $key ), $db); - if ($value=='' and $wgInterwikiScopes>=3) { - /* try site-level */ - $value = dba_fetch("_{$site}:{$key}", $db); - } - if ($value=='' and $wgInterwikiScopes>=2) { - /* try globals */ - $value = dba_fetch("__global:{$key}", $db); - } - if ($value=='undef') - $value=''; - $s = (object)false; - $s->iw_url = ''; - $s->iw_local = 0; - $s->iw_trans = 0; - if ($value!='') { - list($local,$url)=explode(' ',$value,2); - $s->iw_url=$url; - $s->iw_local=(int)$local; - } - Title::$interwikiCache[wfMemcKey( 'interwiki', $key )] = $s; - return $s->iw_url; - } - /** - * Determine whether the object refers to a page within - * this project. - * - * @return bool TRUE if this is an in-project interwiki link - * or a wikilink, FALSE otherwise - */ - public function isLocal() { - if ( $this->mInterwiki != '' ) { - # Make sure key is loaded into cache - $this->getInterwikiLink( $this->mInterwiki ); - $k = wfMemcKey( 'interwiki', $this->mInterwiki ); - return (bool)(Title::$interwikiCache[$k]->iw_local); - } else { - return true; - } - } - - /** - * Determine whether the object refers to a page within - * this project and is transcludable. - * - * @return bool TRUE if this is transcludable - */ - public function isTrans() { - if ($this->mInterwiki == '') - return false; - # Make sure key is loaded into cache - $this->getInterwikiLink( $this->mInterwiki ); - $k = wfMemcKey( 'interwiki', $this->mInterwiki ); - return (bool)(Title::$interwikiCache[$k]->iw_trans); - } - - /** - * Escape a text fragment, say from a link, for a URL - */ - static function escapeFragmentForURL( $fragment ) { - $fragment = str_replace( ' ', '_', $fragment ); - $fragment = urlencode( Sanitizer::decodeCharReferences( $fragment ) ); - $replaceArray = array( - '%3A' => ':', - '%' => '.' - ); - return strtr( $fragment, $replaceArray ); - } - -#---------------------------------------------------------------------------- -# Other stuff -#---------------------------------------------------------------------------- - - /** Simple accessors */ - /** - * Get the text form (spaces not underscores) of the main part - * @return string - */ - public function getText() { return $this->mTextform; } - /** - * Get the URL-encoded form of the main part - * @return string - */ - public function getPartialURL() { return $this->mUrlform; } - /** - * Get the main part with underscores - * @return string - */ - public function getDBkey() { return $this->mDbkeyform; } - /** - * Get the namespace index, i.e. one of the NS_xxxx constants - * @return int - */ - public function getNamespace() { return $this->mNamespace; } - /** - * Get the namespace text - * @return string - */ - public function getNsText() { - global $wgContLang, $wgCanonicalNamespaceNames; - - if ( '' != $this->mInterwiki ) { - // This probably shouldn't even happen. ohh man, oh yuck. - // But for interwiki transclusion it sometimes does. - // Shit. Shit shit shit. - // - // Use the canonical namespaces if possible to try to - // resolve a foreign namespace. - if( isset( $wgCanonicalNamespaceNames[$this->mNamespace] ) ) { - return $wgCanonicalNamespaceNames[$this->mNamespace]; - } - } - return $wgContLang->getNsText( $this->mNamespace ); - } - /** - * Get the namespace text of the subject (rather than talk) page - * @return string - */ -/* public function getSubjectNsText() { - global $wgContLang; - return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace ) ); - }*/ - - /** - * Get the namespace text of the talk page - * @return string - */ -/* public function getTalkNsText() { - global $wgContLang; - return( $wgContLang->getNsText( Namespace::getTalk( $this->mNamespace ) ) ); - }*/ - - /** - * Could this title have a corresponding talk page? - * @return bool - */ -/* public function canTalk() { - return( Namespace::canTalk( $this->mNamespace ) ); - }*/ - - /** - * Get the interwiki prefix (or null string) - * @return string - */ - public function getInterwiki() { return $this->mInterwiki; } - /** - * Get the Title fragment (i.e. the bit after the #) in text form - * @return string - */ - public function getFragment() { return $this->mFragment; } - /** - * Get the fragment in URL form, including the "#" character if there is one - * @return string - */ - public function getFragmentForURL() { - if ( $this->mFragment == '' ) { - return ''; - } else { - return '#' . Title::escapeFragmentForURL( $this->mFragment ); - } - } - /** - * Get the default namespace index, for when there is no namespace - * @return int - */ - public function getDefaultNamespace() { return $this->mDefaultNamespace; } - - /** - * Get title for search index - * @return string a stripped-down title string ready for the - * search index - */ - public function getIndexTitle() { - return Title::indexTitle( $this->mNamespace, $this->mTextform ); - } - - /** - * Get the prefixed database key form - * @return string the prefixed title, with underscores and - * any interwiki and namespace prefixes - */ - public function getPrefixedDBkey() { - $s = $this->prefix( $this->mDbkeyform ); - $s = str_replace( ' ', '_', $s ); - return $s; - } - - /** - * Get the prefixed title with spaces. - * This is the form usually used for display - * @return string the prefixed title, with spaces - */ - public function getPrefixedText() { - if ( empty( $this->mPrefixedText ) ) { // FIXME: bad usage of empty() ? - $s = $this->prefix( $this->mTextform ); - $s = str_replace( '_', ' ', $s ); - $this->mPrefixedText = $s; - } - return $this->mPrefixedText; - } - - /** - * Get the prefixed title with spaces, plus any fragment - * (part beginning with '#') - * @return string the prefixed title, with spaces and - * the fragment, including '#' - */ - public function getFullText() { - $text = $this->getPrefixedText(); - if( '' != $this->mFragment ) { - $text .= '#' . $this->mFragment; - } - return $text; - } - - /** - * Get the base name, i.e. the leftmost parts before the / - * @return string Base name - */ - public function getBaseText() { - global $wgNamespacesWithSubpages; - if( isset( $wgNamespacesWithSubpages[ $this->mNamespace ] ) && $wgNamespacesWithSubpages[ $this->mNamespace ] ) { - $parts = explode( '/', $this->getText() ); - # Don't discard the real title if there's no subpage involved - if( count( $parts ) > 1 ) - unset( $parts[ count( $parts ) - 1 ] ); - return implode( '/', $parts ); - } else { - return $this->getText(); - } - } - - /** - * Get the lowest-level subpage name, i.e. the rightmost part after / - * @return string Subpage name - */ - public function getSubpageText() { - global $wgNamespacesWithSubpages; - if( isset( $wgNamespacesWithSubpages[ $this->mNamespace ] ) && $wgNamespacesWithSubpages[ $this->mNamespace ] ) { - $parts = explode( '/', $this->mTextform ); - return( $parts[ count( $parts ) - 1 ] ); - } else { - return( $this->mTextform ); - } - } - - /** - * Get a URL-encoded form of the subpage text - * @return string URL-encoded subpage name - */ - public function getSubpageUrlForm() { - $text = $this->getSubpageText(); - $text = wfUrlencode( str_replace( ' ', '_', $text ) ); - $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe - return( $text ); - } - - /** - * Get a URL-encoded title (not an actual URL) including interwiki - * @return string the URL-encoded form - */ - public function getPrefixedURL() { - $s = $this->prefix( $this->mDbkeyform ); - $s = str_replace( ' ', '_', $s ); - - $s = wfUrlencode ( $s ) ; - - # Cleaning up URL to make it look nice -- is this safe? - $s = str_replace( '%28', '(', $s ); - $s = str_replace( '%29', ')', $s ); - - return $s; - } - - /** - * Get a real URL referring to this title, with interwiki link and - * fragment - * - * @param string $query an optional query string, not used - * for interwiki links - * @param string $variant language variant of url (for sr, zh..) - * @return string the URL - */ - public function getFullURL( $query = '', $variant = false ) { - global $wgContLang, $wgServer, $wgRequest; - - if ( '' == $this->mInterwiki ) { - $url = $this->getLocalUrl( $query, $variant ); - - // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc) - // Correct fix would be to move the prepending elsewhere. - if ($wgRequest->getVal('action') != 'render') { - $url = $wgServer . $url; - } - } else { - $baseUrl = $this->getInterwikiLink( $this->mInterwiki ); - - $namespace = wfUrlencode( $this->getNsText() ); - if ( '' != $namespace ) { - # Can this actually happen? Interwikis shouldn't be parsed. - # Yes! It can in interwiki transclusion. But... it probably shouldn't. - $namespace .= ':'; - } - $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl ); - $url = wfAppendQuery( $url, $query ); - } - - # Finally, add the fragment. - $url .= $this->getFragmentForURL(); - - wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) ); - return $url; - } - - /** - * Get a URL with no fragment or server name. If this page is generated - * with action=render, $wgServer is prepended. - * @param string $query an optional query string; if not specified, - * $wgArticlePath will be used. - * @param string $variant language variant of url (for sr, zh..) - * @return string the URL - */ - public function getLocalURL( $query = '', $variant = false ) { - global $wgArticlePath, $wgScript, $wgServer, $wgRequest; - global $wgVariantArticlePath, $wgContLang, $wgUser; - - // internal links should point to same variant as current page (only anonymous users) - if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){ - $pref = $wgContLang->getPreferredVariant(false); - if($pref != $wgContLang->getCode()) - $variant = $pref; - } - - if ( $this->isExternal() ) { - $url = $this->getFullURL(); - if ( $query ) { - // This is currently only used for edit section links in the - // context of interwiki transclusion. In theory we should - // append the query to the end of any existing query string, - // but interwiki transclusion is already broken in that case. - $url .= "?$query"; - } - } else { - $dbkey = wfUrlencode( $this->getPrefixedDBkey() ); - if ( $query == '' ) { - if($variant!=false && $wgContLang->hasVariants()){ - if($wgVariantArticlePath==false) { - $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default - } else { - $variantArticlePath = $wgVariantArticlePath; - } - $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath ); - $url = str_replace( '$1', $dbkey, $url ); - } - else { - $url = str_replace( '$1', $dbkey, $wgArticlePath ); - } - } else { - global $wgActionPaths; - $url = false; - $matches = array(); - if( !empty( $wgActionPaths ) && - preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) ) - { - $action = urldecode( $matches[2] ); - if( isset( $wgActionPaths[$action] ) ) { - $query = $matches[1]; - if( isset( $matches[4] ) ) $query .= $matches[4]; - $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] ); - if( $query != '' ) $url .= '?' . $query; - } - } - if ( $url === false ) { - if ( $query == '-' ) { - $query = ''; - } - $url = "{$wgScript}?title={$dbkey}&{$query}"; - } - } - - // FIXME: this causes breakage in various places when we - // actually expected a local URL and end up with dupe prefixes. - if ($wgRequest->getVal('action') == 'render') { - $url = $wgServer . $url; - } - } - wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) ); - return $url; - } - - /** - * Get an HTML-escaped version of the URL form, suitable for - * using in a link, without a server name or fragment - * @param string $query an optional query string - * @return string the URL - */ - public function escapeLocalURL( $query = '' ) { - return htmlspecialchars( $this->getLocalURL( $query ) ); - } - - /** - * Get an HTML-escaped version of the URL form, suitable for - * using in a link, including the server name and fragment - * - * @return string the URL - * @param string $query an optional query string - */ - public function escapeFullURL( $query = '' ) { - return htmlspecialchars( $this->getFullURL( $query ) ); - } - - /** - * Get the URL form for an internal link. - * - Used in various Squid-related code, in case we have a different - * internal hostname for the server from the exposed one. - * - * @param string $query an optional query string - * @param string $variant language variant of url (for sr, zh..) - * @return string the URL - */ - public function getInternalURL( $query = '', $variant = false ) { - global $wgInternalServer; - $url = $wgInternalServer . $this->getLocalURL( $query, $variant ); - wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) ); - return $url; - } - - /** - * Get the edit URL for this Title - * @return string the URL, or a null string if this is an - * interwiki link - */ - public function getEditURL() { - if ( '' != $this->mInterwiki ) { return ''; } - $s = $this->getLocalURL( 'action=edit' ); - - return $s; - } - - /** - * Get the HTML-escaped displayable text form. - * Used for the title field in tags. - * @return string the text, including any prefixes - */ - public function getEscapedText() { - return htmlspecialchars( $this->getPrefixedText() ); - } - - /** - * Is this Title interwiki? - * @return boolean - */ - public function isExternal() { return ( '' != $this->mInterwiki ); } - - /** - * Is this page "semi-protected" - the *only* protection is autoconfirm? - * - * @param string Action to check (default: edit) - * @return bool - */ - public function isSemiProtected( $action = 'edit' ) { - if( $this->exists() ) { - $restrictions = $this->getRestrictions( $action ); - if( count( $restrictions ) > 0 ) { - foreach( $restrictions as $restriction ) { - if( strtolower( $restriction ) != 'autoconfirmed' ) - return false; - } - } else { - # Not protected - return false; - } - return true; - } else { - # If it doesn't exist, it can't be protected - return false; - } - } - - /** - * Does the title correspond to a protected article? - * @param string $what the action the page is protected from, - * by default checks move and edit - * @return boolean - */ - public function isProtected( $action = '' ) { - global $wgRestrictionLevels; - - # Special pages have inherent protection - if( $this->getNamespace() == NS_SPECIAL ) - return true; - - # Check regular protection levels - if( $action == 'edit' || $action == '' ) { - $r = $this->getRestrictions( 'edit' ); - foreach( $wgRestrictionLevels as $level ) { - if( in_array( $level, $r ) && $level != '' ) { - return( true ); - } - } - } - - if( $action == 'move' || $action == '' ) { - $r = $this->getRestrictions( 'move' ); - foreach( $wgRestrictionLevels as $level ) { - if( in_array( $level, $r ) && $level != '' ) { - return( true ); - } - } - } - - return false; - } - - /** - * Is $wgUser is watching this page? - * @return boolean - */ - public function userIsWatching() { - global $wgUser; - - if ( is_null( $this->mWatched ) ) { - if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn()) { - $this->mWatched = false; - } else { - $this->mWatched = $wgUser->isWatched( $this ); - } - } - return $this->mWatched; - } - - /** - * Can $wgUser perform $action on this page? - * This skips potentially expensive cascading permission checks. - * - * Suitable for use for nonessential UI controls in common cases, but - * _not_ for functional access control. - * - * May provide false positives, but should never provide a false negative. - * - * @param string $action action that permission needs to be checked for - * @return boolean - */ - public function quickUserCan( $action ) { - return $this->userCan( $action, false ); - } - - /** - * Can $wgUser perform $action on this page? - * @param string $action action that permission needs to be checked for - * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries. - * @return boolean - */ - public function userCan( $action, $doExpensiveQueries = true ) { - $fname = 'Title::userCan'; - wfProfileIn( $fname ); - - global $wgUser, $wgNamespaceProtection; - - $result = null; - wfRunHooks( 'userCan', array( &$this, &$wgUser, $action, &$result ) ); - if ( $result !== null ) { - wfProfileOut( $fname ); - return $result; - } - - if( NS_SPECIAL == $this->mNamespace ) { - wfProfileOut( $fname ); - return false; - } - - if ( array_key_exists( $this->mNamespace, $wgNamespaceProtection ) ) { - $nsProt = $wgNamespaceProtection[ $this->mNamespace ]; - if ( !is_array($nsProt) ) $nsProt = array($nsProt); - foreach( $nsProt as $right ) { - if( '' != $right && !$wgUser->isAllowed( $right ) ) { - wfProfileOut( $fname ); - return false; - } - } - } - - if( $this->mDbkeyform == '_' ) { - # FIXME: Is this necessary? Shouldn't be allowed anyway... - wfProfileOut( $fname ); - return false; - } - - # protect css/js subpages of user pages - # XXX: this might be better using restrictions - # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working - if( $this->isCssJsSubpage() - && !$wgUser->isAllowed('editinterface') - && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) ) { - wfProfileOut( $fname ); - return false; - } - - if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) { - # We /could/ use the protection level on the source page, but it's fairly ugly - # as we have to establish a precedence hierarchy for pages included by multiple - # cascade-protected pages. So just restrict it to people with 'protect' permission, - # as they could remove the protection anyway. - list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources(); - # Cascading protection depends on more than this page... - # Several cascading protected pages may include this page... - # Check each cascading level - # This is only for protection restrictions, not for all actions - if( $cascadingSources > 0 && isset($restrictions[$action]) ) { - foreach( $restrictions[$action] as $right ) { - $right = ( $right == 'sysop' ) ? 'protect' : $right; - if( '' != $right && !$wgUser->isAllowed( $right ) ) { - wfProfileOut( $fname ); - return false; - } - } - } - } - - foreach( $this->getRestrictions($action) as $right ) { - // Backwards compatibility, rewrite sysop -> protect - if ( $right == 'sysop' ) { - $right = 'protect'; - } - if( '' != $right && !$wgUser->isAllowed( $right ) ) { - wfProfileOut( $fname ); - return false; - } - } - - if( $action == 'move' && - !( $this->isMovable() && $wgUser->isAllowed( 'move' ) ) ) { - wfProfileOut( $fname ); - return false; - } - - if( $action == 'create' ) { - if( ( $this->isTalkPage() && !$wgUser->isAllowed( 'createtalk' ) ) || - ( !$this->isTalkPage() && !$wgUser->isAllowed( 'createpage' ) ) ) { - wfProfileOut( $fname ); - return false; - } - } - - wfProfileOut( $fname ); - return true; - } - - /** - * Can $wgUser edit this page? - * @return boolean - * @deprecated use userCan('edit') - */ - public function userCanEdit( $doExpensiveQueries = true ) { - return $this->userCan( 'edit', $doExpensiveQueries ); - } - - /** - * Can $wgUser create this page? - * @return boolean - * @deprecated use userCan('create') - */ - public function userCanCreate( $doExpensiveQueries = true ) { - return $this->userCan( 'create', $doExpensiveQueries ); - } - - /** - * Can $wgUser move this page? - * @return boolean - * @deprecated use userCan('move') - */ - public function userCanMove( $doExpensiveQueries = true ) { - return $this->userCan( 'move', $doExpensiveQueries ); - } - - /** - * Would anybody with sufficient privileges be able to move this page? - * Some pages just aren't movable. - * - * @return boolean - */ -/* public function isMovable() { - return Namespace::isMovable( $this->getNamespace() ) - && $this->getInterwiki() == ''; - }*/ - - /** - * Can $wgUser read this page? - * @return boolean - * @todo fold these checks into userCan() - */ - public function userCanRead() { - global $wgUser; - - $result = null; - wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) ); - if ( $result !== null ) { - return $result; - } - - if( $wgUser->isAllowed('read') ) { - return true; - } else { - global $wgWhitelistRead; - - /** - * Always grant access to the login page. - * Even anons need to be able to log in. - */ - if( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) { - return true; - } - - /** some pages are explicitly allowed */ - $name = $this->getPrefixedText(); - if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) { - return true; - } - - # Compatibility with old settings - if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN ) { - if( in_array( ':' . $name, $wgWhitelistRead ) ) { - return true; - } - } - } - return false; - } - - /** - * Is this a talk page of some sort? - * @return bool - */ -/* public function isTalkPage() { - return Namespace::isTalk( $this->getNamespace() ); - }*/ - - /** - * Is this a subpage? - * @return bool - */ - public function isSubpage() { - global $wgNamespacesWithSubpages; - - if( isset( $wgNamespacesWithSubpages[ $this->mNamespace ] ) ) { - return ( strpos( $this->getText(), '/' ) !== false && $wgNamespacesWithSubpages[ $this->mNamespace ] == true ); - } else { - return false; - } - } - - /** - * Is this a .css or .js subpage of a user page? - * @return bool - */ - public function isCssJsSubpage() { - return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform ) ); - } - /** - * Is this a *valid* .css or .js subpage of a user page? - * Check that the corresponding skin exists - */ - public function isValidCssJsSubpage() { - if ( $this->isCssJsSubpage() ) { - $skinNames = Skin::getSkinNames(); - return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames ); - } else { - return false; - } - } - /** - * Trim down a .css or .js subpage title to get the corresponding skin name - */ - public function getSkinFromCssJsSubpage() { - $subpage = explode( '/', $this->mTextform ); - $subpage = $subpage[ count( $subpage ) - 1 ]; - return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) ); - } - /** - * Is this a .css subpage of a user page? - * @return bool - */ - public function isCssSubpage() { - return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.css$/", $this->mTextform ) ); - } - /** - * Is this a .js subpage of a user page? - * @return bool - */ - public function isJsSubpage() { - return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.js$/", $this->mTextform ) ); - } - /** - * Protect css/js subpages of user pages: can $wgUser edit - * this page? - * - * @return boolean - * @todo XXX: this might be better using restrictions - */ - public function userCanEditCssJsSubpage() { - global $wgUser; - return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) ); - } - - /** - * Cascading protection: Return true if cascading restrictions apply to this page, false if not. - * - * @return bool If the page is subject to cascading restrictions. - */ - public function isCascadeProtected() { - list( $sources, $restrictions ) = $this->getCascadeProtectionSources( false ); - return ( $sources > 0 ); - } - - /** - * Cascading protection: Get the source of any cascading restrictions on this page. - * - * @param $get_pages bool Whether or not to retrieve the actual pages that the restrictions have come from. - * @return array( mixed title array, restriction array) - * Array of the Title objects of the pages from which cascading restrictions have come, false for none, or true if such restrictions exist, but $get_pages was not set. - * The restriction array is an array of each type, each of which contains an array of unique groups - */ - public function getCascadeProtectionSources( $get_pages = true ) { - global $wgEnableCascadingProtection, $wgRestrictionTypes; - - # Define our dimension of restrictions types - $pagerestrictions = array(); - foreach( $wgRestrictionTypes as $action ) - $pagerestrictions[$action] = array(); - - if (!$wgEnableCascadingProtection) - return array( false, $pagerestrictions ); - - if ( isset( $this->mCascadeSources ) && $get_pages ) { - return array( $this->mCascadeSources, $this->mCascadingRestrictions ); - } else if ( isset( $this->mHasCascadingRestrictions ) && !$get_pages ) { - return array( $this->mHasCascadingRestrictions, $pagerestrictions ); - } - - wfProfileIn( __METHOD__ ); - - $dbr = wfGetDb( DB_SLAVE ); - - if ( $this->getNamespace() == NS_IMAGE ) { - $tables = array ('imagelinks', 'page_restrictions'); - $where_clauses = array( - 'il_to' => $this->getDBkey(), - 'il_from=pr_page', - 'pr_cascade' => 1 ); - } else { - $tables = array ('templatelinks', 'page_restrictions'); - $where_clauses = array( - 'tl_namespace' => $this->getNamespace(), - 'tl_title' => $this->getDBkey(), - 'tl_from=pr_page', - 'pr_cascade' => 1 ); - } - - if ( $get_pages ) { - $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' ); - $where_clauses[] = 'page_id=pr_page'; - $tables[] = 'page'; - } else { - $cols = array( 'pr_expiry' ); - } - - $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ ); - - $sources = $get_pages ? array() : false; - $now = wfTimestampNow(); - $purgeExpired = false; - - while( $row = $dbr->fetchObject( $res ) ) { - $expiry = Block::decodeExpiry( $row->pr_expiry ); - if( $expiry > $now ) { - if ($get_pages) { - $page_id = $row->pr_page; - $page_ns = $row->page_namespace; - $page_title = $row->page_title; - $sources[$page_id] = Title::makeTitle($page_ns, $page_title); - # Add groups needed for each restriction type if its not already there - # Make sure this restriction type still exists - if ( isset($pagerestrictions[$row->pr_type]) && !in_array($row->pr_level, $pagerestrictions[$row->pr_type]) ) { - $pagerestrictions[$row->pr_type][]=$row->pr_level; - } - } else { - $sources = true; - } - } else { - // Trigger lazy purge of expired restrictions from the db - $purgeExpired = true; - } - } - if( $purgeExpired ) { - Title::purgeExpiredRestrictions(); - } - - wfProfileOut( __METHOD__ ); - - if ( $get_pages ) { - $this->mCascadeSources = $sources; - $this->mCascadingRestrictions = $pagerestrictions; - } else { - $this->mHasCascadingRestrictions = $sources; - } - - return array( $sources, $pagerestrictions ); - } - - function areRestrictionsCascading() { - if (!$this->mRestrictionsLoaded) { - $this->loadRestrictions(); - } - - return $this->mCascadeRestriction; - } - - /** - * Loads a string into mRestrictions array - * @param resource $res restrictions as an SQL result. - */ - private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) { - $dbr = wfGetDb( DB_SLAVE ); - - $this->mRestrictions['edit'] = array(); - $this->mRestrictions['move'] = array(); - - # Backwards-compatibility: also load the restrictions from the page record (old format). - - if ( $oldFashionedRestrictions == NULL ) { - $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions', array( 'page_id' => $this->getArticleId() ), __METHOD__ ); - } - - if ($oldFashionedRestrictions != '') { - - foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) { - $temp = explode( '=', trim( $restrict ) ); - if(count($temp) == 1) { - // old old format should be treated as edit/move restriction - $this->mRestrictions["edit"] = explode( ',', trim( $temp[0] ) ); - $this->mRestrictions["move"] = explode( ',', trim( $temp[0] ) ); - } else { - $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) ); - } - } - - $this->mOldRestrictions = true; - $this->mCascadeRestriction = false; - $this->mRestrictionsExpiry = Block::decodeExpiry(''); - - } - - if( $dbr->numRows( $res ) ) { - # Current system - load second to make them override. - $now = wfTimestampNow(); - $purgeExpired = false; - - while ($row = $dbr->fetchObject( $res ) ) { - # Cycle through all the restrictions. - - // This code should be refactored, now that it's being used more generally, - // But I don't really see any harm in leaving it in Block for now -werdna - $expiry = Block::decodeExpiry( $row->pr_expiry ); - - // Only apply the restrictions if they haven't expired! - if ( !$expiry || $expiry > $now ) { - $this->mRestrictionsExpiry = $expiry; - $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) ); - - $this->mCascadeRestriction |= $row->pr_cascade; - } else { - // Trigger a lazy purge of expired restrictions - $purgeExpired = true; - } - } - - if( $purgeExpired ) { - Title::purgeExpiredRestrictions(); - } - } - - $this->mRestrictionsLoaded = true; - } - - public function loadRestrictions( $oldFashionedRestrictions = NULL ) { - if( !$this->mRestrictionsLoaded ) { - $dbr = wfGetDB( DB_SLAVE ); - - $res = $dbr->select( 'page_restrictions', '*', - array ( 'pr_page' => $this->getArticleId() ), __METHOD__ ); - - $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions ); - } - } - - /** - * Purge expired restrictions from the page_restrictions table - */ - static function purgeExpiredRestrictions() { - $dbw = wfGetDB( DB_MASTER ); - $dbw->delete( 'page_restrictions', - array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), - __METHOD__ ); - } - - /** - * Accessor/initialisation for mRestrictions - * - * @param string $action action that permission needs to be checked for - * @return array the array of groups allowed to edit this article - */ - public function getRestrictions( $action ) { - if( $this->exists() ) { - if( !$this->mRestrictionsLoaded ) { - $this->loadRestrictions(); - } - return isset( $this->mRestrictions[$action] ) - ? $this->mRestrictions[$action] - : array(); - } else { - return array(); - } - } - - /** - * Is there a version of this page in the deletion archive? - * @return int the number of archived revisions - */ - public function isDeleted() { - $fname = 'Title::isDeleted'; - if ( $this->getNamespace() < 0 ) { - $n = 0; - } else { - $dbr = wfGetDB( DB_SLAVE ); - $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(), - 'ar_title' => $this->getDBkey() ), $fname ); - if( $this->getNamespace() == NS_IMAGE ) { - $n += $dbr->selectField( 'filearchive', 'COUNT(*)', - array( 'fa_name' => $this->getDBkey() ), $fname ); - } - } - return (int)$n; - } - - /** - * Get the article ID for this Title from the link cache, - * adding it if necessary - * @param int $flags a bit field; may be GAID_FOR_UPDATE to select - * for update - * @return int the ID - */ - public function getArticleID( $flags = 0 ) { - $linkCache =& LinkCache::singleton(); - if ( $flags & GAID_FOR_UPDATE ) { - $oldUpdate = $linkCache->forUpdate( true ); - $this->mArticleID = $linkCache->addLinkObj( $this ); - $linkCache->forUpdate( $oldUpdate ); - } else { - if ( -1 == $this->mArticleID ) { - $this->mArticleID = $linkCache->addLinkObj( $this ); - } - } - return $this->mArticleID; - } - - public function getLatestRevID() { - if ($this->mLatestID !== false) - return $this->mLatestID; - - $db = wfGetDB(DB_SLAVE); - return $this->mLatestID = $db->selectField( 'revision', - "max(rev_id)", - array('rev_page' => $this->getArticleID()), - 'Title::getLatestRevID' ); - } - - /** - * This clears some fields in this object, and clears any associated - * keys in the "bad links" section of the link cache. - * - * - This is called from Article::insertNewArticle() to allow - * loading of the new page_id. It's also called from - * Article::doDeleteArticle() - * - * @param int $newid the new Article ID - */ - public function resetArticleID( $newid ) { - $linkCache =& LinkCache::singleton(); - $linkCache->clearBadLink( $this->getPrefixedDBkey() ); - - if ( 0 == $newid ) { $this->mArticleID = -1; } - else { $this->mArticleID = $newid; } - $this->mRestrictionsLoaded = false; - $this->mRestrictions = array(); - } - - /** - * Updates page_touched for this page; called from LinksUpdate.php - * @return bool true if the update succeded - */ - public function invalidateCache() { - global $wgUseFileCache; - - if ( wfReadOnly() ) { - return; - } - - $dbw = wfGetDB( DB_MASTER ); - $success = $dbw->update( 'page', - array( /* SET */ - 'page_touched' => $dbw->timestamp() - ), array( /* WHERE */ - 'page_namespace' => $this->getNamespace() , - 'page_title' => $this->getDBkey() - ), 'Title::invalidateCache' - ); - - if ($wgUseFileCache) { - $cache = new HTMLFileCache($this); - @unlink($cache->fileCacheName()); - } - - return $success; - } - - /** - * Prefix some arbitrary text with the namespace or interwiki prefix - * of this object - * - * @param string $name the text - * @return string the prefixed text - * @private - */ - /* private */ function prefix( $name ) { - $p = ''; - if ( '' != $this->mInterwiki ) { - $p = $this->mInterwiki . ':'; - } - if ( 0 != $this->mNamespace ) { - $p .= $this->getNsText() . ':'; - } - return $p . $name; - } - - /** - * Secure and split - main initialisation function for this object - * - * Assumes that mDbkeyform has been set, and is urldecoded - * and uses underscores, but not otherwise munged. This function - * removes illegal characters, splits off the interwiki and - * namespace prefixes, sets the other forms, and canonicalizes - * everything. - * @return bool true on success - */ - private function secureAndSplit() { - global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks; - - # Initialisation - static $rxTc = false; - if( !$rxTc ) { - # % is needed as well - $rxTc = '/[^' . Title::legalChars() . ']|%[0-9A-Fa-f]{2}/S'; - } - - $this->mInterwiki = $this->mFragment = ''; - $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN - - $dbkey = $this->mDbkeyform; - - # Strip Unicode bidi override characters. - # Sometimes they slip into cut-n-pasted page titles, where the - # override chars get included in list displays. - $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK - $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK - - # Clean up whitespace - # - $dbkey = preg_replace( '/[ _]+/', '_', $dbkey ); - $dbkey = trim( $dbkey, '_' ); - - if ( '' == $dbkey ) { - return false; - } - - if( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) { - # Contained illegal UTF-8 sequences or forbidden Unicode chars. - return false; - } - - $this->mDbkeyform = $dbkey; - - # Initial colon indicates main namespace rather than specified default - # but should not create invalid {ns,title} pairs such as {0,Project:Foo} - if ( ':' == $dbkey{0} ) { - $this->mNamespace = NS_MAIN; - $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing - $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace - } - - # Namespace or interwiki prefix - $firstPass = true; - do { - $m = array(); - if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) { - $p = $m[1]; - if ( $ns = $wgContLang->getNsIndex( $p )) { - # Ordinary namespace - $dbkey = $m[2]; - $this->mNamespace = $ns; - } elseif( $this->getInterwikiLink( $p ) ) { - if( !$firstPass ) { - # Can't make a local interwiki link to an interwiki link. - # That's just crazy! - return false; - } - - # Interwiki link - $dbkey = $m[2]; - $this->mInterwiki = $wgContLang->lc( $p ); - - # Redundant interwiki prefix to the local wiki - if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) { - if( $dbkey == '' ) { - # Can't have an empty self-link - return false; - } - $this->mInterwiki = ''; - $firstPass = false; - # Do another namespace split... - continue; - } - - # If there's an initial colon after the interwiki, that also - # resets the default namespace - if ( $dbkey !== '' && $dbkey[0] == ':' ) { - $this->mNamespace = NS_MAIN; - $dbkey = substr( $dbkey, 1 ); - } - } - # If there's no recognized interwiki or namespace, - # then let the colon expression be part of the title. - } - break; - } while( true ); - - # We already know that some pages won't be in the database! - # - if ( '' != $this->mInterwiki || NS_SPECIAL == $this->mNamespace ) { - $this->mArticleID = 0; - } - $fragment = strstr( $dbkey, '#' ); - if ( false !== $fragment ) { - $this->setFragment( $fragment ); - $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) ); - # remove whitespace again: prevents "Foo_bar_#" - # becoming "Foo_bar_" - $dbkey = preg_replace( '/_*$/', '', $dbkey ); - } - - # Reject illegal characters. - # - if( preg_match( $rxTc, $dbkey ) ) { - return false; - } - - /** - * Pages with "/./" or "/../" appearing in the URLs will - * often be unreachable due to the way web browsers deal - * with 'relative' URLs. Forbid them explicitly. - */ - if ( strpos( $dbkey, '.' ) !== false && - ( $dbkey === '.' || $dbkey === '..' || - strpos( $dbkey, './' ) === 0 || - strpos( $dbkey, '../' ) === 0 || - strpos( $dbkey, '/./' ) !== false || - strpos( $dbkey, '/../' ) !== false ) ) - { - return false; - } - - /** - * Magic tilde sequences? Nu-uh! - */ - if( strpos( $dbkey, '~~~' ) !== false ) { - return false; - } - - /** - * Limit the size of titles to 255 bytes. - * This is typically the size of the underlying database field. - * We make an exception for special pages, which don't need to be stored - * in the database, and may edge over 255 bytes due to subpage syntax - * for long titles, e.g. [[Special:Block/Long name]] - */ - if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) || - strlen( $dbkey ) > 512 ) - { - return false; - } - - /** - * Normally, all wiki links are forced to have - * an initial capital letter so [[foo]] and [[Foo]] - * point to the same place. - * - * Don't force it for interwikis, since the other - * site might be case-sensitive. - */ - if( $wgCapitalLinks && $this->mInterwiki == '') { - $dbkey = $wgContLang->ucfirst( $dbkey ); - } - - /** - * Can't make a link to a namespace alone... - * "empty" local links can only be self-links - * with a fragment identifier. - */ - if( $dbkey == '' && - $this->mInterwiki == '' && - $this->mNamespace != NS_MAIN ) { - return false; - } - - // Any remaining initial :s are illegal. - if ( $dbkey !== '' && ':' == $dbkey{0} ) { - return false; - } - - # Fill fields - $this->mDbkeyform = $dbkey; - $this->mUrlform = ilWikiUtil::wfUrlencode( $dbkey ); - - $this->mTextform = str_replace( '_', ' ', $dbkey ); - - return true; - } - - /** - * Set the fragment for this title - * This is kind of bad, since except for this rarely-used function, Title objects - * are immutable. The reason this is here is because it's better than setting the - * members directly, which is what Linker::formatComment was doing previously. - * - * @param string $fragment text - * @todo clarify whether access is supposed to be public (was marked as "kind of public") - */ - public function setFragment( $fragment ) { - $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) ); - } - - /** - * Get a Title object associated with the talk page of this article - * @return Title the object for the talk page - */ -/* public function getTalkPage() { - return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() ); - }*/ - - /** - * Get a title object associated with the subject page of this - * talk page - * - * @return Title the object for the subject page - */ -/* public function getSubjectPage() { - return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() ); - }*/ - - /** - * Get an array of Title objects linking to this Title - * Also stores the IDs in the link cache. - * - * WARNING: do not use this function on arbitrary user-supplied titles! - * On heavily-used templates it will max out the memory. - * - * @param string $options may be FOR UPDATE - * @return array the Title objects linking here - */ - public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) { - $linkCache =& LinkCache::singleton(); - - if ( $options ) { - $db = wfGetDB( DB_MASTER ); - } else { - $db = wfGetDB( DB_SLAVE ); - } - - $res = $db->select( array( 'page', $table ), - array( 'page_namespace', 'page_title', 'page_id' ), - array( - "{$prefix}_from=page_id", - "{$prefix}_namespace" => $this->getNamespace(), - "{$prefix}_title" => $this->getDbKey() ), - 'Title::getLinksTo', - $options ); - - $retVal = array(); - if ( $db->numRows( $res ) ) { - while ( $row = $db->fetchObject( $res ) ) { - if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) { - $linkCache->addGoodLinkObj( $row->page_id, $titleObj ); - $retVal[] = $titleObj; - } - } - } - $db->freeResult( $res ); - return $retVal; - } - - /** - * Get an array of Title objects using this Title as a template - * Also stores the IDs in the link cache. - * - * WARNING: do not use this function on arbitrary user-supplied titles! - * On heavily-used templates it will max out the memory. - * - * @param string $options may be FOR UPDATE - * @return array the Title objects linking here - */ - public function getTemplateLinksTo( $options = '' ) { - return $this->getLinksTo( $options, 'templatelinks', 'tl' ); - } - - /** - * Get an array of Title objects referring to non-existent articles linked from this page - * - * @param string $options may be FOR UPDATE - * @return array the Title objects - */ - public function getBrokenLinksFrom( $options = '' ) { - if ( $options ) { - $db = wfGetDB( DB_MASTER ); - } else { - $db = wfGetDB( DB_SLAVE ); - } - - $res = $db->safeQuery( - "SELECT pl_namespace, pl_title +class Title +{ + /** + * Static cache variables + */ + private static $titleCache=array(); + private static $interwikiCache=array(); + + + /** + * All member variables should be considered private + * Please use the accessor functions + */ + + /**#@+ + * @private + */ + + public $mTextform; # Text form (spaces not underscores) of the main part + public $mUrlform; # URL-encoded form of the main part + public $mDbkeyform; # Main part with underscores + public $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants + public $mInterwiki; # Interwiki prefix (or null string) + public $mFragment; # Title fragment (i.e. the bit after the #) + public $mArticleID; # Article ID, fetched from the link cache on demand + public $mLatestID; # ID of most recent revision + public $mRestrictions; # Array of groups allowed to edit this article + public $mCascadeRestriction; # Cascade restrictions on this page to included templates and images? + public $mRestrictionsExpiry; # When do the restrictions on this page expire? + public $mHasCascadingRestrictions; # Are cascading restrictions in effect on this page? + public $mCascadeRestrictionSources;# Where are the cascading restrictions coming from on this page? + public $mRestrictionsLoaded; # Boolean for initialisation on demand + public $mPrefixedText; # Text form including namespace/interwiki, initialised on demand + public $mDefaultNamespace; # Namespace index when there is no namespace + # Zero except in {{transclusion}} tags + public $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching() + /**#@-*/ + + + /** + * Constructor + * @private + */ + /* private */ public function __construct() + { + $this->mInterwiki = $this->mUrlform = + $this->mTextform = $this->mDbkeyform = ''; + $this->mArticleID = -1; + $this->mNamespace = NS_MAIN; + $this->mRestrictionsLoaded = false; + $this->mRestrictions = array(); + # Dont change the following, NS_MAIN is hardcoded in several place + # See bug #696 + $this->mDefaultNamespace = NS_MAIN; + $this->mWatched = null; + $this->mLatestID = false; + $this->mOldRestrictions = false; + } + + /** + * Create a new Title from a prefixed DB key + * @param string $key The database key, which has underscores + * instead of spaces, possibly including namespace and + * interwiki prefixes + * @return Title the new object, or NULL on an error + */ + public static function newFromDBkey($key) + { + $t = new Title(); + $t->mDbkeyform = $key; + if ($t->secureAndSplit()) { + return $t; + } else { + return null; + } + } + + /** + * Create a new Title from text, such as what one would + * find in a link. Decodes any HTML entities in the text. + * + * @param string $text the link text; spaces, prefixes, + * and an initial ':' indicating the main namespace + * are accepted + * @param int $defaultNamespace the namespace to use if + * none is specified by a prefix + * @return Title the new object, or NULL on an error + */ + public static function newFromText($text, $defaultNamespace = NS_MAIN) + { + if (is_object($text)) { + throw new MWException('Title::newFromText given an object'); + } + + /** + * Wiki pages often contain multiple links to the same page. + * Title normalization and parsing can become expensive on + * pages with many links, so we can save a little time by + * caching them. + * + * In theory these are value objects and won't get changed... + */ + if ($defaultNamespace == NS_MAIN && isset(Title::$titleCache[$text])) { + return Title::$titleCache[$text]; + } + + /** + * Convert things like é ā or 〗 into real text... + */ + $filteredText = Sanitizer::decodeCharReferences($text); + + $t = new Title(); + $t->mDbkeyform = str_replace(' ', '_', $filteredText); + $t->mDefaultNamespace = $defaultNamespace; + + static $cachedcount = 0 ; + if ($t->secureAndSplit()) { + if ($defaultNamespace == NS_MAIN) { + if ($cachedcount >= MW_TITLECACHE_MAX) { + # Avoid memory leaks on mass operations... + Title::$titleCache = array(); + $cachedcount=0; + } + $cachedcount++; + Title::$titleCache[$text] =&$t; + } + return $t; + } else { + $ret = null; + return $ret; + } + } + + /** + * Create a new Title from URL-encoded text. Ensures that + * the given title's length does not exceed the maximum. + * @param string $url the title, as might be taken from a URL + * @return Title the new object, or NULL on an error + */ + public static function newFromURL($url) + { + global $wgLegalTitleChars; + $t = new Title(); + + # For compatibility with old buggy URLs. "+" is usually not valid in titles, + # but some URLs used it as a space replacement and they still come + # from some external search tools. + if (strpos($wgLegalTitleChars, '+') === false) { + $url = str_replace('+', ' ', $url); + } + + $t->mDbkeyform = str_replace(' ', '_', $url); + if ($t->secureAndSplit()) { + return $t; + } else { + return null; + } + } + + /** + * Create a new Title from an article ID + * + * @todo This is inefficiently implemented, the page row is requested + * but not used for anything else + * + * @param int $id the page_id corresponding to the Title to create + * @return Title the new object, or NULL on an error + */ + public static function newFromID($id) + { + $fname = 'Title::newFromID'; + $dbr = wfGetDB(DB_SLAVE); + $row = $dbr->selectRow( + 'page', + array( 'page_namespace', 'page_title' ), + array( 'page_id' => $id ), + $fname + ); + if ($row !== false) { + $title = Title::makeTitle($row->page_namespace, $row->page_title); + } else { + $title = null; + } + return $title; + } + + /** + * Make an array of titles from an array of IDs + */ + public static function newFromIDs($ids) + { + $dbr = wfGetDB(DB_SLAVE); + $res = $dbr->select( + 'page', + array( 'page_namespace', 'page_title' ), + 'page_id IN (' . $dbr->makeList($ids) . ')', + __METHOD__ + ); + + $titles = array(); + while ($row = $dbr->fetchObject($res)) { + $titles[] = Title::makeTitle($row->page_namespace, $row->page_title); + } + return $titles; + } + + /** + * Create a new Title from a namespace index and a DB key. + * It's assumed that $ns and $title are *valid*, for instance when + * they came directly from the database or a special page name. + * For convenience, spaces are converted to underscores so that + * eg user_text fields can be used directly. + * + * @param int $ns the namespace of the article + * @param string $title the unprefixed database key form + * @return Title the new object + */ + public static function &makeTitle($ns, $title) + { + $t = new Title(); + $t->mInterwiki = ''; + $t->mFragment = ''; + $t->mNamespace = intval($ns); + $t->mDbkeyform = str_replace(' ', '_', $title); + $t->mArticleID = ($ns >= 0) ? -1 : 0; + $t->mUrlform = wfUrlencode($t->mDbkeyform); + $t->mTextform = str_replace('_', ' ', $title); + return $t; + } + + /** + * Create a new Title from a namespace index and a DB key. + * The parameters will be checked for validity, which is a bit slower + * than makeTitle() but safer for user-provided data. + * + * @param int $ns the namespace of the article + * @param string $title the database key form + * @return Title the new object, or NULL on an error + */ + public static function makeTitleSafe($ns, $title) + { + $t = new Title(); + $t->mDbkeyform = Title::makeName($ns, $title); + if ($t->secureAndSplit()) { + return $t; + } else { + return null; + } + } + + /** + * Create a new Title for the Main Page + * @return Title the new object + */ + public static function newMainPage() + { + return Title::newFromText(wfMsgForContent('mainpage')); + } + + /** + * Create a new Title for a redirect + * @param string $text the redirect title text + * @return Title the new object, or NULL if the text is not a + * valid redirect + */ + public static function newFromRedirect($text) + { + $mwRedir = MagicWord::get('redirect'); + $rt = null; + if ($mwRedir->matchStart($text)) { + $m = array(); + if (preg_match('/\[{2}(.*?)(?:\||\]{2})/', $text, $m)) { + # categories are escaped using : for example one can enter: + # #REDIRECT [[:Category:Music]]. Need to remove it. + if (substr($m[1], 0, 1) == ':') { + # We don't want to keep the ':' + $m[1] = substr($m[1], 1); + } + + $rt = Title::newFromText($m[1]); + # Disallow redirects to Special:Userlogout + if (!is_null($rt) && $rt->isSpecial('Userlogout')) { + $rt = null; + } + } + } + return $rt; + } + + #---------------------------------------------------------------------------- + # Static functions + #---------------------------------------------------------------------------- + + /** + * Get the prefixed DB key associated with an ID + * @param int $id the page_id of the article + * @return Title an object representing the article, or NULL + * if no such article was found + * @static + * @access public + */ + public function nameOf($id) + { + $fname = 'Title::nameOf'; + $dbr = wfGetDB(DB_SLAVE); + + $s = $dbr->selectRow('page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname); + if ($s === false) { + return null; + } + + $n = Title::makeName($s->page_namespace, $s->page_title); + return $n; + } + + /** + * Get a regex character class describing the legal characters in a link + * @return string the list of characters, not delimited + */ + public static function legalChars() + { + global $wgLegalTitleChars; + + $wgLegalTitleChars = " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z~\\x80-\\xFF+"; + + return $wgLegalTitleChars; + } + + /** + * Get a string representation of a title suitable for + * including in a search index + * + * @param int $ns a namespace index + * @param string $title text-form main part + * @return string a stripped-down title string ready for the + * search index + */ + public static function indexTitle($ns, $title) + { + global $wgContLang; + + $lc = SearchEngine::legalSearchChars() . '&#;'; + $t = $wgContLang->stripForSearch($title); + $t = preg_replace("/[^{$lc}]+/", ' ', $t); + $t = $wgContLang->lc($t); + + # Handle 's, s' + $t = preg_replace("/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t); + $t = preg_replace("/([{$lc}]+)s'( |$)/", "\\1s ", $t); + + $t = preg_replace("/\\s+/", ' ', $t); + + if ($ns == NS_IMAGE) { + $t = preg_replace("/ (png|gif|jpg|jpeg|ogg)$/", "", $t); + } + return trim($t); + } + + /* + * Make a prefixed DB key from a DB key and a namespace index + * @param int $ns numerical representation of the namespace + * @param string $title the DB key form the title + * @return string the prefixed form of the title + */ + public static function makeName($ns, $title) + { + global $wgContLang; + + $n = $wgContLang->getNsText($ns); + return $n == '' ? $title : "$n:$title"; + } + + /** + * Returns the URL associated with an interwiki prefix + * @param string $key the interwiki prefix (e.g. "MeatBall") + * @return the associated URL, containing "$1", which should be + * replaced by an article title + * @static (arguably) + */ + public function getInterwikiLink($key) + { + global $wgMemc, $wgInterwikiExpiry; + global $wgInterwikiCache, $wgContLang; + + return ""; // changed. alex + + $fname = 'Title::getInterwikiLink'; + + $key = $wgContLang->lc($key); + + $k = wfMemcKey('interwiki', $key); + if (array_key_exists($k, Title::$interwikiCache)) { + return Title::$interwikiCache[$k]->iw_url; + } + + if ($wgInterwikiCache) { + return Title::getInterwikiCached($key); + } + + $s = $wgMemc->get($k); + # Ignore old keys with no iw_local + if ($s && isset($s->iw_local) && isset($s->iw_trans)) { + Title::$interwikiCache[$k] = $s; + return $s->iw_url; + } + + $dbr = wfGetDB(DB_SLAVE); + $res = $dbr->select( + 'interwiki', + array( 'iw_url', 'iw_local', 'iw_trans' ), + array( 'iw_prefix' => $key ), + $fname + ); + if (!$res) { + return ''; + } + + $s = $dbr->fetchObject($res); + if (!$s) { + # Cache non-existence: create a blank object and save it to memcached + $s = (object) false; + $s->iw_url = ''; + $s->iw_local = 0; + $s->iw_trans = 0; + } + $wgMemc->set($k, $s, $wgInterwikiExpiry); + Title::$interwikiCache[$k] = $s; + + return $s->iw_url; + } + + /** + * Fetch interwiki prefix data from local cache in constant database + * + * More logic is explained in DefaultSettings + * + * @return string URL of interwiki site + */ + public static function getInterwikiCached($key) + { + global $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite; + static $db, $site; + + if (!$db) { + $db=dba_open($wgInterwikiCache, 'r', 'cdb'); + } + /* Resolve site name */ + if ($wgInterwikiScopes>=3 and !$site) { + $site = dba_fetch('__sites:' . wfWikiID(), $db); + if ($site=="") { + $site = $wgInterwikiFallbackSite; + } + } + $value = dba_fetch(wfMemcKey($key), $db); + if ($value=='' and $wgInterwikiScopes>=3) { + /* try site-level */ + $value = dba_fetch("_{$site}:{$key}", $db); + } + if ($value=='' and $wgInterwikiScopes>=2) { + /* try globals */ + $value = dba_fetch("__global:{$key}", $db); + } + if ($value=='undef') { + $value=''; + } + $s = (object) false; + $s->iw_url = ''; + $s->iw_local = 0; + $s->iw_trans = 0; + if ($value!='') { + list($local, $url)=explode(' ', $value, 2); + $s->iw_url=$url; + $s->iw_local=(int) $local; + } + Title::$interwikiCache[wfMemcKey('interwiki', $key)] = $s; + return $s->iw_url; + } + /** + * Determine whether the object refers to a page within + * this project. + * + * @return bool TRUE if this is an in-project interwiki link + * or a wikilink, FALSE otherwise + */ + public function isLocal() + { + if ($this->mInterwiki != '') { + # Make sure key is loaded into cache + $this->getInterwikiLink($this->mInterwiki); + $k = wfMemcKey('interwiki', $this->mInterwiki); + return (bool) (Title::$interwikiCache[$k]->iw_local); + } else { + return true; + } + } + + /** + * Determine whether the object refers to a page within + * this project and is transcludable. + * + * @return bool TRUE if this is transcludable + */ + public function isTrans() + { + if ($this->mInterwiki == '') { + return false; + } + # Make sure key is loaded into cache + $this->getInterwikiLink($this->mInterwiki); + $k = wfMemcKey('interwiki', $this->mInterwiki); + return (bool) (Title::$interwikiCache[$k]->iw_trans); + } + + /** + * Escape a text fragment, say from a link, for a URL + */ + public static function escapeFragmentForURL($fragment) + { + $fragment = str_replace(' ', '_', $fragment); + $fragment = urlencode(Sanitizer::decodeCharReferences($fragment)); + $replaceArray = array( + '%3A' => ':', + '%' => '.' + ); + return strtr($fragment, $replaceArray); + } + + #---------------------------------------------------------------------------- + # Other stuff + #---------------------------------------------------------------------------- + + /** Simple accessors */ + /** + * Get the text form (spaces not underscores) of the main part + * @return string + */ + public function getText() + { + return $this->mTextform; + } + /** + * Get the URL-encoded form of the main part + * @return string + */ + public function getPartialURL() + { + return $this->mUrlform; + } + /** + * Get the main part with underscores + * @return string + */ + public function getDBkey() + { + return $this->mDbkeyform; + } + /** + * Get the namespace index, i.e. one of the NS_xxxx constants + * @return int + */ + public function getNamespace() + { + return $this->mNamespace; + } + /** + * Get the namespace text + * @return string + */ + public function getNsText() + { + global $wgContLang, $wgCanonicalNamespaceNames; + + if ('' != $this->mInterwiki) { + // This probably shouldn't even happen. ohh man, oh yuck. + // But for interwiki transclusion it sometimes does. + // Shit. Shit shit shit. + // + // Use the canonical namespaces if possible to try to + // resolve a foreign namespace. + if (isset($wgCanonicalNamespaceNames[$this->mNamespace])) { + return $wgCanonicalNamespaceNames[$this->mNamespace]; + } + } + return $wgContLang->getNsText($this->mNamespace); + } + /** + * Get the namespace text of the subject (rather than talk) page + * @return string + */ + /* public function getSubjectNsText() { + global $wgContLang; + return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace ) ); + }*/ + + /** + * Get the namespace text of the talk page + * @return string + */ + /* public function getTalkNsText() { + global $wgContLang; + return( $wgContLang->getNsText( Namespace::getTalk( $this->mNamespace ) ) ); + }*/ + + /** + * Could this title have a corresponding talk page? + * @return bool + */ + /* public function canTalk() { + return( Namespace::canTalk( $this->mNamespace ) ); + }*/ + + /** + * Get the interwiki prefix (or null string) + * @return string + */ + public function getInterwiki() + { + return $this->mInterwiki; + } + /** + * Get the Title fragment (i.e. the bit after the #) in text form + * @return string + */ + public function getFragment() + { + return $this->mFragment; + } + /** + * Get the fragment in URL form, including the "#" character if there is one + * @return string + */ + public function getFragmentForURL() + { + if ($this->mFragment == '') { + return ''; + } else { + return '#' . Title::escapeFragmentForURL($this->mFragment); + } + } + /** + * Get the default namespace index, for when there is no namespace + * @return int + */ + public function getDefaultNamespace() + { + return $this->mDefaultNamespace; + } + + /** + * Get title for search index + * @return string a stripped-down title string ready for the + * search index + */ + public function getIndexTitle() + { + return Title::indexTitle($this->mNamespace, $this->mTextform); + } + + /** + * Get the prefixed database key form + * @return string the prefixed title, with underscores and + * any interwiki and namespace prefixes + */ + public function getPrefixedDBkey() + { + $s = $this->prefix($this->mDbkeyform); + $s = str_replace(' ', '_', $s); + return $s; + } + + /** + * Get the prefixed title with spaces. + * This is the form usually used for display + * @return string the prefixed title, with spaces + */ + public function getPrefixedText() + { + if (empty($this->mPrefixedText)) { // FIXME: bad usage of empty() ? + $s = $this->prefix($this->mTextform); + $s = str_replace('_', ' ', $s); + $this->mPrefixedText = $s; + } + return $this->mPrefixedText; + } + + /** + * Get the prefixed title with spaces, plus any fragment + * (part beginning with '#') + * @return string the prefixed title, with spaces and + * the fragment, including '#' + */ + public function getFullText() + { + $text = $this->getPrefixedText(); + if ('' != $this->mFragment) { + $text .= '#' . $this->mFragment; + } + return $text; + } + + /** + * Get the base name, i.e. the leftmost parts before the / + * @return string Base name + */ + public function getBaseText() + { + global $wgNamespacesWithSubpages; + if (isset($wgNamespacesWithSubpages[ $this->mNamespace ]) && $wgNamespacesWithSubpages[ $this->mNamespace ]) { + $parts = explode('/', $this->getText()); + # Don't discard the real title if there's no subpage involved + if (count($parts) > 1) { + unset($parts[ count($parts) - 1 ]); + } + return implode('/', $parts); + } else { + return $this->getText(); + } + } + + /** + * Get the lowest-level subpage name, i.e. the rightmost part after / + * @return string Subpage name + */ + public function getSubpageText() + { + global $wgNamespacesWithSubpages; + if (isset($wgNamespacesWithSubpages[ $this->mNamespace ]) && $wgNamespacesWithSubpages[ $this->mNamespace ]) { + $parts = explode('/', $this->mTextform); + return($parts[ count($parts) - 1 ]); + } else { + return($this->mTextform); + } + } + + /** + * Get a URL-encoded form of the subpage text + * @return string URL-encoded subpage name + */ + public function getSubpageUrlForm() + { + $text = $this->getSubpageText(); + $text = wfUrlencode(str_replace(' ', '_', $text)); + $text = str_replace('%28', '(', str_replace('%29', ')', $text)); # Clean up the URL; per below, this might not be safe + return($text); + } + + /** + * Get a URL-encoded title (not an actual URL) including interwiki + * @return string the URL-encoded form + */ + public function getPrefixedURL() + { + $s = $this->prefix($this->mDbkeyform); + $s = str_replace(' ', '_', $s); + + $s = wfUrlencode($s) ; + + # Cleaning up URL to make it look nice -- is this safe? + $s = str_replace('%28', '(', $s); + $s = str_replace('%29', ')', $s); + + return $s; + } + + /** + * Get a real URL referring to this title, with interwiki link and + * fragment + * + * @param string $query an optional query string, not used + * for interwiki links + * @param string $variant language variant of url (for sr, zh..) + * @return string the URL + */ + public function getFullURL($query = '', $variant = false) + { + global $wgContLang, $wgServer, $wgRequest; + + if ('' == $this->mInterwiki) { + $url = $this->getLocalUrl($query, $variant); + + // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc) + // Correct fix would be to move the prepending elsewhere. + if ($wgRequest->getVal('action') != 'render') { + $url = $wgServer . $url; + } + } else { + $baseUrl = $this->getInterwikiLink($this->mInterwiki); + + $namespace = wfUrlencode($this->getNsText()); + if ('' != $namespace) { + # Can this actually happen? Interwikis shouldn't be parsed. + # Yes! It can in interwiki transclusion. But... it probably shouldn't. + $namespace .= ':'; + } + $url = str_replace('$1', $namespace . $this->mUrlform, $baseUrl); + $url = wfAppendQuery($url, $query); + } + + # Finally, add the fragment. + $url .= $this->getFragmentForURL(); + + wfRunHooks('GetFullURL', array( &$this, &$url, $query )); + return $url; + } + + /** + * Get a URL with no fragment or server name. If this page is generated + * with action=render, $wgServer is prepended. + * @param string $query an optional query string; if not specified, + * $wgArticlePath will be used. + * @param string $variant language variant of url (for sr, zh..) + * @return string the URL + */ + public function getLocalURL($query = '', $variant = false) + { + global $wgArticlePath, $wgScript, $wgServer, $wgRequest; + global $wgVariantArticlePath, $wgContLang, $wgUser; + + // internal links should point to same variant as current page (only anonymous users) + if ($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()) { + $pref = $wgContLang->getPreferredVariant(false); + if ($pref != $wgContLang->getCode()) { + $variant = $pref; + } + } + + if ($this->isExternal()) { + $url = $this->getFullURL(); + if ($query) { + // This is currently only used for edit section links in the + // context of interwiki transclusion. In theory we should + // append the query to the end of any existing query string, + // but interwiki transclusion is already broken in that case. + $url .= "?$query"; + } + } else { + $dbkey = wfUrlencode($this->getPrefixedDBkey()); + if ($query == '') { + if ($variant!=false && $wgContLang->hasVariants()) { + if ($wgVariantArticlePath==false) { + $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default + } else { + $variantArticlePath = $wgVariantArticlePath; + } + $url = str_replace('$2', urlencode($variant), $variantArticlePath); + $url = str_replace('$1', $dbkey, $url); + } else { + $url = str_replace('$1', $dbkey, $wgArticlePath); + } + } else { + global $wgActionPaths; + $url = false; + $matches = array(); + if (!empty($wgActionPaths) && + preg_match('/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches)) { + $action = urldecode($matches[2]); + if (isset($wgActionPaths[$action])) { + $query = $matches[1]; + if (isset($matches[4])) { + $query .= $matches[4]; + } + $url = str_replace('$1', $dbkey, $wgActionPaths[$action]); + if ($query != '') { + $url .= '?' . $query; + } + } + } + if ($url === false) { + if ($query == '-') { + $query = ''; + } + $url = "{$wgScript}?title={$dbkey}&{$query}"; + } + } + + // FIXME: this causes breakage in various places when we + // actually expected a local URL and end up with dupe prefixes. + if ($wgRequest->getVal('action') == 'render') { + $url = $wgServer . $url; + } + } + wfRunHooks('GetLocalURL', array( &$this, &$url, $query )); + return $url; + } + + /** + * Get an HTML-escaped version of the URL form, suitable for + * using in a link, without a server name or fragment + * @param string $query an optional query string + * @return string the URL + */ + public function escapeLocalURL($query = '') + { + return htmlspecialchars($this->getLocalURL($query)); + } + + /** + * Get an HTML-escaped version of the URL form, suitable for + * using in a link, including the server name and fragment + * + * @return string the URL + * @param string $query an optional query string + */ + public function escapeFullURL($query = '') + { + return htmlspecialchars($this->getFullURL($query)); + } + + /** + * Get the URL form for an internal link. + * - Used in various Squid-related code, in case we have a different + * internal hostname for the server from the exposed one. + * + * @param string $query an optional query string + * @param string $variant language variant of url (for sr, zh..) + * @return string the URL + */ + public function getInternalURL($query = '', $variant = false) + { + global $wgInternalServer; + $url = $wgInternalServer . $this->getLocalURL($query, $variant); + wfRunHooks('GetInternalURL', array( &$this, &$url, $query )); + return $url; + } + + /** + * Get the edit URL for this Title + * @return string the URL, or a null string if this is an + * interwiki link + */ + public function getEditURL() + { + if ('' != $this->mInterwiki) { + return ''; + } + $s = $this->getLocalURL('action=edit'); + + return $s; + } + + /** + * Get the HTML-escaped displayable text form. + * Used for the title field in tags. + * @return string the text, including any prefixes + */ + public function getEscapedText() + { + return htmlspecialchars($this->getPrefixedText()); + } + + /** + * Is this Title interwiki? + * @return boolean + */ + public function isExternal() + { + return ('' != $this->mInterwiki); + } + + /** + * Is this page "semi-protected" - the *only* protection is autoconfirm? + * + * @param string Action to check (default: edit) + * @return bool + */ + public function isSemiProtected($action = 'edit') + { + if ($this->exists()) { + $restrictions = $this->getRestrictions($action); + if (count($restrictions) > 0) { + foreach ($restrictions as $restriction) { + if (strtolower($restriction) != 'autoconfirmed') { + return false; + } + } + } else { + # Not protected + return false; + } + return true; + } else { + # If it doesn't exist, it can't be protected + return false; + } + } + + /** + * Does the title correspond to a protected article? + * @param string $what the action the page is protected from, + * by default checks move and edit + * @return boolean + */ + public function isProtected($action = '') + { + global $wgRestrictionLevels; + + # Special pages have inherent protection + if ($this->getNamespace() == NS_SPECIAL) { + return true; + } + + # Check regular protection levels + if ($action == 'edit' || $action == '') { + $r = $this->getRestrictions('edit'); + foreach ($wgRestrictionLevels as $level) { + if (in_array($level, $r) && $level != '') { + return(true); + } + } + } + + if ($action == 'move' || $action == '') { + $r = $this->getRestrictions('move'); + foreach ($wgRestrictionLevels as $level) { + if (in_array($level, $r) && $level != '') { + return(true); + } + } + } + + return false; + } + + /** + * Is $wgUser is watching this page? + * @return boolean + */ + public function userIsWatching() + { + global $wgUser; + + if (is_null($this->mWatched)) { + if (NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn()) { + $this->mWatched = false; + } else { + $this->mWatched = $wgUser->isWatched($this); + } + } + return $this->mWatched; + } + + /** + * Can $wgUser perform $action on this page? + * This skips potentially expensive cascading permission checks. + * + * Suitable for use for nonessential UI controls in common cases, but + * _not_ for functional access control. + * + * May provide false positives, but should never provide a false negative. + * + * @param string $action action that permission needs to be checked for + * @return boolean + */ + public function quickUserCan($action) + { + return $this->userCan($action, false); + } + + /** + * Can $wgUser perform $action on this page? + * @param string $action action that permission needs to be checked for + * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries. + * @return boolean + */ + public function userCan($action, $doExpensiveQueries = true) + { + $fname = 'Title::userCan'; + wfProfileIn($fname); + + global $wgUser, $wgNamespaceProtection; + + $result = null; + wfRunHooks('userCan', array( &$this, &$wgUser, $action, &$result )); + if ($result !== null) { + wfProfileOut($fname); + return $result; + } + + if (NS_SPECIAL == $this->mNamespace) { + wfProfileOut($fname); + return false; + } + + if (array_key_exists($this->mNamespace, $wgNamespaceProtection)) { + $nsProt = $wgNamespaceProtection[ $this->mNamespace ]; + if (!is_array($nsProt)) { + $nsProt = array($nsProt); + } + foreach ($nsProt as $right) { + if ('' != $right && !$wgUser->isAllowed($right)) { + wfProfileOut($fname); + return false; + } + } + } + + if ($this->mDbkeyform == '_') { + # FIXME: Is this necessary? Shouldn't be allowed anyway... + wfProfileOut($fname); + return false; + } + + # protect css/js subpages of user pages + # XXX: this might be better using restrictions + # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working + if ($this->isCssJsSubpage() + && !$wgUser->isAllowed('editinterface') + && !preg_match('/^' . preg_quote($wgUser->getName(), '/') . '\//', $this->mTextform)) { + wfProfileOut($fname); + return false; + } + + if ($doExpensiveQueries && !$this->isCssJsSubpage()) { + # We /could/ use the protection level on the source page, but it's fairly ugly + # as we have to establish a precedence hierarchy for pages included by multiple + # cascade-protected pages. So just restrict it to people with 'protect' permission, + # as they could remove the protection anyway. + list($cascadingSources, $restrictions) = $this->getCascadeProtectionSources(); + # Cascading protection depends on more than this page... + # Several cascading protected pages may include this page... + # Check each cascading level + # This is only for protection restrictions, not for all actions + if ($cascadingSources > 0 && isset($restrictions[$action])) { + foreach ($restrictions[$action] as $right) { + $right = ($right == 'sysop') ? 'protect' : $right; + if ('' != $right && !$wgUser->isAllowed($right)) { + wfProfileOut($fname); + return false; + } + } + } + } + + foreach ($this->getRestrictions($action) as $right) { + // Backwards compatibility, rewrite sysop -> protect + if ($right == 'sysop') { + $right = 'protect'; + } + if ('' != $right && !$wgUser->isAllowed($right)) { + wfProfileOut($fname); + return false; + } + } + + if ($action == 'move' && + !($this->isMovable() && $wgUser->isAllowed('move'))) { + wfProfileOut($fname); + return false; + } + + if ($action == 'create') { + if (($this->isTalkPage() && !$wgUser->isAllowed('createtalk')) || + (!$this->isTalkPage() && !$wgUser->isAllowed('createpage'))) { + wfProfileOut($fname); + return false; + } + } + + wfProfileOut($fname); + return true; + } + + /** + * Can $wgUser edit this page? + * @return boolean + * @deprecated use userCan('edit') + */ + public function userCanEdit($doExpensiveQueries = true) + { + return $this->userCan('edit', $doExpensiveQueries); + } + + /** + * Can $wgUser create this page? + * @return boolean + * @deprecated use userCan('create') + */ + public function userCanCreate($doExpensiveQueries = true) + { + return $this->userCan('create', $doExpensiveQueries); + } + + /** + * Can $wgUser move this page? + * @return boolean + * @deprecated use userCan('move') + */ + public function userCanMove($doExpensiveQueries = true) + { + return $this->userCan('move', $doExpensiveQueries); + } + + /** + * Would anybody with sufficient privileges be able to move this page? + * Some pages just aren't movable. + * + * @return boolean + */ + /* public function isMovable() { + return Namespace::isMovable( $this->getNamespace() ) + && $this->getInterwiki() == ''; + }*/ + + /** + * Can $wgUser read this page? + * @return boolean + * @todo fold these checks into userCan() + */ + public function userCanRead() + { + global $wgUser; + + $result = null; + wfRunHooks('userCan', array( &$this, &$wgUser, 'read', &$result )); + if ($result !== null) { + return $result; + } + + if ($wgUser->isAllowed('read')) { + return true; + } else { + global $wgWhitelistRead; + + /** + * Always grant access to the login page. + * Even anons need to be able to log in. + */ + if ($this->isSpecial('Userlogin') || $this->isSpecial('Resetpass')) { + return true; + } + + /** some pages are explicitly allowed */ + $name = $this->getPrefixedText(); + if ($wgWhitelistRead && in_array($name, $wgWhitelistRead)) { + return true; + } + + # Compatibility with old settings + if ($wgWhitelistRead && $this->getNamespace() == NS_MAIN) { + if (in_array(':' . $name, $wgWhitelistRead)) { + return true; + } + } + } + return false; + } + + /** + * Is this a talk page of some sort? + * @return bool + */ + /* public function isTalkPage() { + return Namespace::isTalk( $this->getNamespace() ); + }*/ + + /** + * Is this a subpage? + * @return bool + */ + public function isSubpage() + { + global $wgNamespacesWithSubpages; + + if (isset($wgNamespacesWithSubpages[ $this->mNamespace ])) { + return (strpos($this->getText(), '/') !== false && $wgNamespacesWithSubpages[ $this->mNamespace ] == true); + } else { + return false; + } + } + + /** + * Is this a .css or .js subpage of a user page? + * @return bool + */ + public function isCssJsSubpage() + { + return (NS_USER == $this->mNamespace and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform)); + } + /** + * Is this a *valid* .css or .js subpage of a user page? + * Check that the corresponding skin exists + */ + public function isValidCssJsSubpage() + { + if ($this->isCssJsSubpage()) { + $skinNames = Skin::getSkinNames(); + return array_key_exists($this->getSkinFromCssJsSubpage(), $skinNames); + } else { + return false; + } + } + /** + * Trim down a .css or .js subpage title to get the corresponding skin name + */ + public function getSkinFromCssJsSubpage() + { + $subpage = explode('/', $this->mTextform); + $subpage = $subpage[ count($subpage) - 1 ]; + return(str_replace(array( '.css', '.js' ), array( '', '' ), $subpage)); + } + /** + * Is this a .css subpage of a user page? + * @return bool + */ + public function isCssSubpage() + { + return (NS_USER == $this->mNamespace and preg_match("/\\/.*\\.css$/", $this->mTextform)); + } + /** + * Is this a .js subpage of a user page? + * @return bool + */ + public function isJsSubpage() + { + return (NS_USER == $this->mNamespace and preg_match("/\\/.*\\.js$/", $this->mTextform)); + } + /** + * Protect css/js subpages of user pages: can $wgUser edit + * this page? + * + * @return boolean + * @todo XXX: this might be better using restrictions + */ + public function userCanEditCssJsSubpage() + { + global $wgUser; + return ($wgUser->isAllowed('editinterface') or preg_match('/^' . preg_quote($wgUser->getName(), '/') . '\//', $this->mTextform)); + } + + /** + * Cascading protection: Return true if cascading restrictions apply to this page, false if not. + * + * @return bool If the page is subject to cascading restrictions. + */ + public function isCascadeProtected() + { + list($sources, $restrictions) = $this->getCascadeProtectionSources(false); + return ($sources > 0); + } + + /** + * Cascading protection: Get the source of any cascading restrictions on this page. + * + * @param $get_pages bool Whether or not to retrieve the actual pages that the restrictions have come from. + * @return array( mixed title array, restriction array) + * Array of the Title objects of the pages from which cascading restrictions have come, false for none, or true if such restrictions exist, but $get_pages was not set. + * The restriction array is an array of each type, each of which contains an array of unique groups + */ + public function getCascadeProtectionSources($get_pages = true) + { + global $wgEnableCascadingProtection, $wgRestrictionTypes; + + # Define our dimension of restrictions types + $pagerestrictions = array(); + foreach ($wgRestrictionTypes as $action) { + $pagerestrictions[$action] = array(); + } + + if (!$wgEnableCascadingProtection) { + return array( false, $pagerestrictions ); + } + + if (isset($this->mCascadeSources) && $get_pages) { + return array( $this->mCascadeSources, $this->mCascadingRestrictions ); + } elseif (isset($this->mHasCascadingRestrictions) && !$get_pages) { + return array( $this->mHasCascadingRestrictions, $pagerestrictions ); + } + + wfProfileIn(__METHOD__); + + $dbr = wfGetDb(DB_SLAVE); + + if ($this->getNamespace() == NS_IMAGE) { + $tables = array('imagelinks', 'page_restrictions'); + $where_clauses = array( + 'il_to' => $this->getDBkey(), + 'il_from=pr_page', + 'pr_cascade' => 1 ); + } else { + $tables = array('templatelinks', 'page_restrictions'); + $where_clauses = array( + 'tl_namespace' => $this->getNamespace(), + 'tl_title' => $this->getDBkey(), + 'tl_from=pr_page', + 'pr_cascade' => 1 ); + } + + if ($get_pages) { + $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' ); + $where_clauses[] = 'page_id=pr_page'; + $tables[] = 'page'; + } else { + $cols = array( 'pr_expiry' ); + } + + $res = $dbr->select($tables, $cols, $where_clauses, __METHOD__); + + $sources = $get_pages ? array() : false; + $now = wfTimestampNow(); + $purgeExpired = false; + + while ($row = $dbr->fetchObject($res)) { + $expiry = Block::decodeExpiry($row->pr_expiry); + if ($expiry > $now) { + if ($get_pages) { + $page_id = $row->pr_page; + $page_ns = $row->page_namespace; + $page_title = $row->page_title; + $sources[$page_id] = Title::makeTitle($page_ns, $page_title); + # Add groups needed for each restriction type if its not already there + # Make sure this restriction type still exists + if (isset($pagerestrictions[$row->pr_type]) && !in_array($row->pr_level, $pagerestrictions[$row->pr_type])) { + $pagerestrictions[$row->pr_type][]=$row->pr_level; + } + } else { + $sources = true; + } + } else { + // Trigger lazy purge of expired restrictions from the db + $purgeExpired = true; + } + } + if ($purgeExpired) { + Title::purgeExpiredRestrictions(); + } + + wfProfileOut(__METHOD__); + + if ($get_pages) { + $this->mCascadeSources = $sources; + $this->mCascadingRestrictions = $pagerestrictions; + } else { + $this->mHasCascadingRestrictions = $sources; + } + + return array( $sources, $pagerestrictions ); + } + + public function areRestrictionsCascading() + { + if (!$this->mRestrictionsLoaded) { + $this->loadRestrictions(); + } + + return $this->mCascadeRestriction; + } + + /** + * Loads a string into mRestrictions array + * @param resource $res restrictions as an SQL result. + */ + private function loadRestrictionsFromRow($res, $oldFashionedRestrictions = null) + { + $dbr = wfGetDb(DB_SLAVE); + + $this->mRestrictions['edit'] = array(); + $this->mRestrictions['move'] = array(); + + # Backwards-compatibility: also load the restrictions from the page record (old format). + + if ($oldFashionedRestrictions == null) { + $oldFashionedRestrictions = $dbr->selectField('page', 'page_restrictions', array( 'page_id' => $this->getArticleId() ), __METHOD__); + } + + if ($oldFashionedRestrictions != '') { + foreach (explode(':', trim($oldFashionedRestrictions)) as $restrict) { + $temp = explode('=', trim($restrict)); + if (count($temp) == 1) { + // old old format should be treated as edit/move restriction + $this->mRestrictions["edit"] = explode(',', trim($temp[0])); + $this->mRestrictions["move"] = explode(',', trim($temp[0])); + } else { + $this->mRestrictions[$temp[0]] = explode(',', trim($temp[1])); + } + } + + $this->mOldRestrictions = true; + $this->mCascadeRestriction = false; + $this->mRestrictionsExpiry = Block::decodeExpiry(''); + } + + if ($dbr->numRows($res)) { + # Current system - load second to make them override. + $now = wfTimestampNow(); + $purgeExpired = false; + + while ($row = $dbr->fetchObject($res)) { + # Cycle through all the restrictions. + + // This code should be refactored, now that it's being used more generally, + // But I don't really see any harm in leaving it in Block for now -werdna + $expiry = Block::decodeExpiry($row->pr_expiry); + + // Only apply the restrictions if they haven't expired! + if (!$expiry || $expiry > $now) { + $this->mRestrictionsExpiry = $expiry; + $this->mRestrictions[$row->pr_type] = explode(',', trim($row->pr_level)); + + $this->mCascadeRestriction |= $row->pr_cascade; + } else { + // Trigger a lazy purge of expired restrictions + $purgeExpired = true; + } + } + + if ($purgeExpired) { + Title::purgeExpiredRestrictions(); + } + } + + $this->mRestrictionsLoaded = true; + } + + public function loadRestrictions($oldFashionedRestrictions = null) + { + if (!$this->mRestrictionsLoaded) { + $dbr = wfGetDB(DB_SLAVE); + + $res = $dbr->select( + 'page_restrictions', + '*', + array( 'pr_page' => $this->getArticleId() ), + __METHOD__ + ); + + $this->loadRestrictionsFromRow($res, $oldFashionedRestrictions); + } + } + + /** + * Purge expired restrictions from the page_restrictions table + */ + public static function purgeExpiredRestrictions() + { + $dbw = wfGetDB(DB_MASTER); + $dbw->delete( + 'page_restrictions', + array( 'pr_expiry < ' . $dbw->addQuotes($dbw->timestamp()) ), + __METHOD__ + ); + } + + /** + * Accessor/initialisation for mRestrictions + * + * @param string $action action that permission needs to be checked for + * @return array the array of groups allowed to edit this article + */ + public function getRestrictions($action) + { + if ($this->exists()) { + if (!$this->mRestrictionsLoaded) { + $this->loadRestrictions(); + } + return isset($this->mRestrictions[$action]) + ? $this->mRestrictions[$action] + : array(); + } else { + return array(); + } + } + + /** + * Is there a version of this page in the deletion archive? + * @return int the number of archived revisions + */ + public function isDeleted() + { + $fname = 'Title::isDeleted'; + if ($this->getNamespace() < 0) { + $n = 0; + } else { + $dbr = wfGetDB(DB_SLAVE); + $n = $dbr->selectField('archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(), + 'ar_title' => $this->getDBkey() ), $fname); + if ($this->getNamespace() == NS_IMAGE) { + $n += $dbr->selectField( + 'filearchive', + 'COUNT(*)', + array( 'fa_name' => $this->getDBkey() ), + $fname + ); + } + } + return (int) $n; + } + + /** + * Get the article ID for this Title from the link cache, + * adding it if necessary + * @param int $flags a bit field; may be GAID_FOR_UPDATE to select + * for update + * @return int the ID + */ + public function getArticleID($flags = 0) + { + $linkCache =&LinkCache::singleton(); + if ($flags & GAID_FOR_UPDATE) { + $oldUpdate = $linkCache->forUpdate(true); + $this->mArticleID = $linkCache->addLinkObj($this); + $linkCache->forUpdate($oldUpdate); + } else { + if (-1 == $this->mArticleID) { + $this->mArticleID = $linkCache->addLinkObj($this); + } + } + return $this->mArticleID; + } + + public function getLatestRevID() + { + if ($this->mLatestID !== false) { + return $this->mLatestID; + } + + $db = wfGetDB(DB_SLAVE); + return $this->mLatestID = $db->selectField( + 'revision', + "max(rev_id)", + array('rev_page' => $this->getArticleID()), + 'Title::getLatestRevID' + ); + } + + /** + * This clears some fields in this object, and clears any associated + * keys in the "bad links" section of the link cache. + * + * - This is called from Article::insertNewArticle() to allow + * loading of the new page_id. It's also called from + * Article::doDeleteArticle() + * + * @param int $newid the new Article ID + */ + public function resetArticleID($newid) + { + $linkCache =&LinkCache::singleton(); + $linkCache->clearBadLink($this->getPrefixedDBkey()); + + if (0 == $newid) { + $this->mArticleID = -1; + } else { + $this->mArticleID = $newid; + } + $this->mRestrictionsLoaded = false; + $this->mRestrictions = array(); + } + + /** + * Updates page_touched for this page; called from LinksUpdate.php + * @return bool true if the update succeded + */ + public function invalidateCache() + { + global $wgUseFileCache; + + if (wfReadOnly()) { + return; + } + + $dbw = wfGetDB(DB_MASTER); + $success = $dbw->update( + 'page', + array( /* SET */ + 'page_touched' => $dbw->timestamp() + ), + array( /* WHERE */ + 'page_namespace' => $this->getNamespace() , + 'page_title' => $this->getDBkey() + ), + 'Title::invalidateCache' + ); + + if ($wgUseFileCache) { + $cache = new HTMLFileCache($this); + @unlink($cache->fileCacheName()); + } + + return $success; + } + + /** + * Prefix some arbitrary text with the namespace or interwiki prefix + * of this object + * + * @param string $name the text + * @return string the prefixed text + * @private + */ + /* private */ public function prefix($name) + { + $p = ''; + if ('' != $this->mInterwiki) { + $p = $this->mInterwiki . ':'; + } + if (0 != $this->mNamespace) { + $p .= $this->getNsText() . ':'; + } + return $p . $name; + } + + /** + * Secure and split - main initialisation function for this object + * + * Assumes that mDbkeyform has been set, and is urldecoded + * and uses underscores, but not otherwise munged. This function + * removes illegal characters, splits off the interwiki and + * namespace prefixes, sets the other forms, and canonicalizes + * everything. + * @return bool true on success + */ + private function secureAndSplit() + { + global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks; + + # Initialisation + static $rxTc = false; + if (!$rxTc) { + # % is needed as well + $rxTc = '/[^' . Title::legalChars() . ']|%[0-9A-Fa-f]{2}/S'; + } + + $this->mInterwiki = $this->mFragment = ''; + $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN + + $dbkey = $this->mDbkeyform; + + # Strip Unicode bidi override characters. + # Sometimes they slip into cut-n-pasted page titles, where the + # override chars get included in list displays. + $dbkey = str_replace("\xE2\x80\x8E", '', $dbkey); // 200E LEFT-TO-RIGHT MARK + $dbkey = str_replace("\xE2\x80\x8F", '', $dbkey); // 200F RIGHT-TO-LEFT MARK + + # Clean up whitespace + # + $dbkey = preg_replace('/[ _]+/', '_', $dbkey); + $dbkey = trim($dbkey, '_'); + + if ('' == $dbkey) { + return false; + } + + if (false !== strpos($dbkey, UTF8_REPLACEMENT)) { + # Contained illegal UTF-8 sequences or forbidden Unicode chars. + return false; + } + + $this->mDbkeyform = $dbkey; + + # Initial colon indicates main namespace rather than specified default + # but should not create invalid {ns,title} pairs such as {0,Project:Foo} + if (':' == $dbkey{0}) { + $this->mNamespace = NS_MAIN; + $dbkey = substr($dbkey, 1); # remove the colon but continue processing + $dbkey = trim($dbkey, '_'); # remove any subsequent whitespace + } + + # Namespace or interwiki prefix + $firstPass = true; + do { + $m = array(); + if (preg_match("/^(.+?)_*:_*(.*)$/S", $dbkey, $m)) { + $p = $m[1]; + if ($ns = $wgContLang->getNsIndex($p)) { + # Ordinary namespace + $dbkey = $m[2]; + $this->mNamespace = $ns; + } elseif ($this->getInterwikiLink($p)) { + if (!$firstPass) { + # Can't make a local interwiki link to an interwiki link. + # That's just crazy! + return false; + } + + # Interwiki link + $dbkey = $m[2]; + $this->mInterwiki = $wgContLang->lc($p); + + # Redundant interwiki prefix to the local wiki + if (0 == strcasecmp($this->mInterwiki, $wgLocalInterwiki)) { + if ($dbkey == '') { + # Can't have an empty self-link + return false; + } + $this->mInterwiki = ''; + $firstPass = false; + # Do another namespace split... + continue; + } + + # If there's an initial colon after the interwiki, that also + # resets the default namespace + if ($dbkey !== '' && $dbkey[0] == ':') { + $this->mNamespace = NS_MAIN; + $dbkey = substr($dbkey, 1); + } + } + # If there's no recognized interwiki or namespace, + # then let the colon expression be part of the title. + } + break; + } while (true); + + # We already know that some pages won't be in the database! + # + if ('' != $this->mInterwiki || NS_SPECIAL == $this->mNamespace) { + $this->mArticleID = 0; + } + $fragment = strstr($dbkey, '#'); + if (false !== $fragment) { + $this->setFragment($fragment); + $dbkey = substr($dbkey, 0, strlen($dbkey) - strlen($fragment)); + # remove whitespace again: prevents "Foo_bar_#" + # becoming "Foo_bar_" + $dbkey = preg_replace('/_*$/', '', $dbkey); + } + + # Reject illegal characters. + # + if (preg_match($rxTc, $dbkey)) { + return false; + } + + /** + * Pages with "/./" or "/../" appearing in the URLs will + * often be unreachable due to the way web browsers deal + * with 'relative' URLs. Forbid them explicitly. + */ + if (strpos($dbkey, '.') !== false && + ($dbkey === '.' || $dbkey === '..' || + strpos($dbkey, './') === 0 || + strpos($dbkey, '../') === 0 || + strpos($dbkey, '/./') !== false || + strpos($dbkey, '/../') !== false)) { + return false; + } + + /** + * Magic tilde sequences? Nu-uh! + */ + if (strpos($dbkey, '~~~') !== false) { + return false; + } + + /** + * Limit the size of titles to 255 bytes. + * This is typically the size of the underlying database field. + * We make an exception for special pages, which don't need to be stored + * in the database, and may edge over 255 bytes due to subpage syntax + * for long titles, e.g. [[Special:Block/Long name]] + */ + if (($this->mNamespace != NS_SPECIAL && strlen($dbkey) > 255) || + strlen($dbkey) > 512) { + return false; + } + + /** + * Normally, all wiki links are forced to have + * an initial capital letter so [[foo]] and [[Foo]] + * point to the same place. + * + * Don't force it for interwikis, since the other + * site might be case-sensitive. + */ + if ($wgCapitalLinks && $this->mInterwiki == '') { + $dbkey = $wgContLang->ucfirst($dbkey); + } + + /** + * Can't make a link to a namespace alone... + * "empty" local links can only be self-links + * with a fragment identifier. + */ + if ($dbkey == '' && + $this->mInterwiki == '' && + $this->mNamespace != NS_MAIN) { + return false; + } + + // Any remaining initial :s are illegal. + if ($dbkey !== '' && ':' == $dbkey{0}) { + return false; + } + + # Fill fields + $this->mDbkeyform = $dbkey; + $this->mUrlform = ilWikiUtil::wfUrlencode($dbkey); + + $this->mTextform = str_replace('_', ' ', $dbkey); + + return true; + } + + /** + * Set the fragment for this title + * This is kind of bad, since except for this rarely-used function, Title objects + * are immutable. The reason this is here is because it's better than setting the + * members directly, which is what Linker::formatComment was doing previously. + * + * @param string $fragment text + * @todo clarify whether access is supposed to be public (was marked as "kind of public") + */ + public function setFragment($fragment) + { + $this->mFragment = str_replace('_', ' ', substr($fragment, 1)); + } + + /** + * Get a Title object associated with the talk page of this article + * @return Title the object for the talk page + */ + /* public function getTalkPage() { + return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() ); + }*/ + + /** + * Get a title object associated with the subject page of this + * talk page + * + * @return Title the object for the subject page + */ + /* public function getSubjectPage() { + return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() ); + }*/ + + /** + * Get an array of Title objects linking to this Title + * Also stores the IDs in the link cache. + * + * WARNING: do not use this function on arbitrary user-supplied titles! + * On heavily-used templates it will max out the memory. + * + * @param string $options may be FOR UPDATE + * @return array the Title objects linking here + */ + public function getLinksTo($options = '', $table = 'pagelinks', $prefix = 'pl') + { + $linkCache =&LinkCache::singleton(); + + if ($options) { + $db = wfGetDB(DB_MASTER); + } else { + $db = wfGetDB(DB_SLAVE); + } + + $res = $db->select( + array( 'page', $table ), + array( 'page_namespace', 'page_title', 'page_id' ), + array( + "{$prefix}_from=page_id", + "{$prefix}_namespace" => $this->getNamespace(), + "{$prefix}_title" => $this->getDbKey() ), + 'Title::getLinksTo', + $options + ); + + $retVal = array(); + if ($db->numRows($res)) { + while ($row = $db->fetchObject($res)) { + if ($titleObj = Title::makeTitle($row->page_namespace, $row->page_title)) { + $linkCache->addGoodLinkObj($row->page_id, $titleObj); + $retVal[] = $titleObj; + } + } + } + $db->freeResult($res); + return $retVal; + } + + /** + * Get an array of Title objects using this Title as a template + * Also stores the IDs in the link cache. + * + * WARNING: do not use this function on arbitrary user-supplied titles! + * On heavily-used templates it will max out the memory. + * + * @param string $options may be FOR UPDATE + * @return array the Title objects linking here + */ + public function getTemplateLinksTo($options = '') + { + return $this->getLinksTo($options, 'templatelinks', 'tl'); + } + + /** + * Get an array of Title objects referring to non-existent articles linked from this page + * + * @param string $options may be FOR UPDATE + * @return array the Title objects + */ + public function getBrokenLinksFrom($options = '') + { + if ($options) { + $db = wfGetDB(DB_MASTER); + } else { + $db = wfGetDB(DB_SLAVE); + } + + $res = $db->safeQuery( + "SELECT pl_namespace, pl_title FROM ! LEFT JOIN ! ON pl_namespace=page_namespace @@ -1898,576 +2040,630 @@ return ""; // changed. alex WHERE pl_from=? AND page_namespace IS NULL !", - $db->tableName( 'pagelinks' ), - $db->tableName( 'page' ), - $this->getArticleId(), - $options ); - - $retVal = array(); - if ( $db->numRows( $res ) ) { - while ( $row = $db->fetchObject( $res ) ) { - $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title ); - } - } - $db->freeResult( $res ); - return $retVal; - } - - - /** - * Get a list of URLs to purge from the Squid cache when this - * page changes - * - * @return array the URLs - */ - public function getSquidURLs() { - global $wgContLang; - - $urls = array( - $this->getInternalURL(), - $this->getInternalURL( 'action=history' ) - ); - - // purge variant urls as well - if($wgContLang->hasVariants()){ - $variants = $wgContLang->getVariants(); - foreach($variants as $vCode){ - if($vCode==$wgContLang->getCode()) continue; // we don't want default variant - $urls[] = $this->getInternalURL('',$vCode); - } - } - - return $urls; - } - - public function purgeSquid() { - global $wgUseSquid; - if ( $wgUseSquid ) { - $urls = $this->getSquidURLs(); - $u = new SquidUpdate( $urls ); - $u->doUpdate(); - } - } - - /** - * Move this page without authentication - * @param Title &$nt the new page Title - */ - public function moveNoAuth( &$nt ) { - return $this->moveTo( $nt, false ); - } - - /** - * Check whether a given move operation would be valid. - * Returns true if ok, or a message key string for an error message - * if invalid. (Scarrrrry ugly interface this.) - * @param Title &$nt the new title - * @param bool $auth indicates whether $wgUser's permissions - * should be checked - * @return mixed true on success, message name on failure - */ - public function isValidMoveOperation( &$nt, $auth = true ) { - if( !$this or !$nt ) { - return 'badtitletext'; - } - if( $this->equals( $nt ) ) { - return 'selfmove'; - } - if( !$this->isMovable() || !$nt->isMovable() ) { - return 'immobile_namespace'; - } - - $oldid = $this->getArticleID(); - $newid = $nt->getArticleID(); - - if ( strlen( $nt->getDBkey() ) < 1 ) { - return 'articleexists'; - } - if ( ( '' == $this->getDBkey() ) || - ( !$oldid ) || - ( '' == $nt->getDBkey() ) ) { - return 'badarticleerror'; - } - - if ( $auth && ( - !$this->userCan( 'edit' ) || !$nt->userCan( 'edit' ) || - !$this->userCan( 'move' ) || !$nt->userCan( 'move' ) ) ) { - return 'protectedpage'; - } - - # The move is allowed only if (1) the target doesn't exist, or - # (2) the target is a redirect to the source, and has no history - # (so we can undo bad moves right after they're done). - - if ( 0 != $newid ) { # Target exists; check for validity - if ( ! $this->isValidMoveTarget( $nt ) ) { - return 'articleexists'; - } - } - return true; - } - - /** - * Move a title to a new location - * @param Title &$nt the new title - * @param bool $auth indicates whether $wgUser's permissions - * should be checked - * @return mixed true on success, message name on failure - */ - public function moveTo( &$nt, $auth = true, $reason = '' ) { - $err = $this->isValidMoveOperation( $nt, $auth ); - if( is_string( $err ) ) { - return $err; - } - - $pageid = $this->getArticleID(); - if( $nt->exists() ) { - $this->moveOverExistingRedirect( $nt, $reason ); - $pageCountChange = 0; - } else { # Target didn't exist, do normal move. - $this->moveToNewTitle( $nt, $reason ); - $pageCountChange = 1; - } - $redirid = $this->getArticleID(); - - # Fixing category links (those without piped 'alternate' names) to be sorted under the new title - $dbw = wfGetDB( DB_MASTER ); - $categorylinks = $dbw->tableName( 'categorylinks' ); - $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) . - " WHERE cl_from=" . $dbw->addQuotes( $pageid ) . - " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() ); - $dbw->query( $sql, 'SpecialMovepage::doSubmit' ); - - # Update watchlists - - $oldnamespace = $this->getNamespace() & ~1; - $newnamespace = $nt->getNamespace() & ~1; - $oldtitle = $this->getDBkey(); - $newtitle = $nt->getDBkey(); - - if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) { - WatchedItem::duplicateEntries( $this, $nt ); - } - - # Update search engine - $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() ); - $u->doUpdate(); - $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' ); - $u->doUpdate(); - - # Update site_stats - if( $this->isContentPage() && !$nt->isContentPage() ) { - # No longer a content page - # Not viewed, edited, removing - $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange ); - } elseif( !$this->isContentPage() && $nt->isContentPage() ) { - # Now a content page - # Not viewed, edited, adding - $u = new SiteStatsUpdate( 0, 1, +1, $pageCountChange ); - } elseif( $pageCountChange ) { - # Redirect added - $u = new SiteStatsUpdate( 0, 0, 0, 1 ); - } else { - # Nothing special - $u = false; - } - if( $u ) - $u->doUpdate(); - - global $wgUser; - wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) ); - return true; - } - - /** - * Move page to a title which is at present a redirect to the - * source page - * - * @param Title &$nt the page to move to, which should currently - * be a redirect - */ - private function moveOverExistingRedirect( &$nt, $reason = '' ) { - global $wgUseSquid; - $fname = 'Title::moveOverExistingRedirect'; - $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() ); - - if ( $reason ) { - $comment .= ": $reason"; - } - - $now = wfTimestampNow(); - $newid = $nt->getArticleID(); - $oldid = $this->getArticleID(); - $dbw = wfGetDB( DB_MASTER ); - $linkCache =& LinkCache::singleton(); - - # Delete the old redirect. We don't save it to history since - # by definition if we've got here it's rather uninteresting. - # We have to remove it so that the next step doesn't trigger - # a conflict on the unique namespace+title index... - $dbw->delete( 'page', array( 'page_id' => $newid ), $fname ); - - # Save a null revision in the page's history notifying of the move - $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true ); - $nullRevId = $nullRevision->insertOn( $dbw ); - - # Change the name of the target page: - $dbw->update( 'page', - /* SET */ array( - 'page_touched' => $dbw->timestamp($now), - 'page_namespace' => $nt->getNamespace(), - 'page_title' => $nt->getDBkey(), - 'page_latest' => $nullRevId, - ), - /* WHERE */ array( 'page_id' => $oldid ), - $fname - ); - $linkCache->clearLink( $nt->getPrefixedDBkey() ); - - # Recreate the redirect, this time in the other direction. - $mwRedir = MagicWord::get( 'redirect' ); - $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n"; - $redirectArticle = new Article( $this ); - $newid = $redirectArticle->insertOn( $dbw ); - $redirectRevision = new Revision( array( - 'page' => $newid, - 'comment' => $comment, - 'text' => $redirectText ) ); - $redirectRevision->insertOn( $dbw ); - $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 ); - $linkCache->clearLink( $this->getPrefixedDBkey() ); - - # Log the move - $log = new LogPage( 'move' ); - $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) ); - - # Now, we record the link from the redirect to the new title. - # It should have no other outgoing links... - $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname ); - $dbw->insert( 'pagelinks', - array( - 'pl_from' => $newid, - 'pl_namespace' => $nt->getNamespace(), - 'pl_title' => $nt->getDbKey() ), - $fname ); - - # Purge squid - if ( $wgUseSquid ) { - $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() ); - $u = new SquidUpdate( $urls ); - $u->doUpdate(); - } - } - - /** - * Move page to non-existing title. - * @param Title &$nt the new Title - */ - private function moveToNewTitle( &$nt, $reason = '' ) { - global $wgUseSquid; - $fname = 'MovePageForm::moveToNewTitle'; - $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ); - if ( $reason ) { - $comment .= ": $reason"; - } - - $newid = $nt->getArticleID(); - $oldid = $this->getArticleID(); - $dbw = wfGetDB( DB_MASTER ); - $now = $dbw->timestamp(); - $linkCache =& LinkCache::singleton(); - - # Save a null revision in the page's history notifying of the move - $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true ); - $nullRevId = $nullRevision->insertOn( $dbw ); - - # Rename cur entry - $dbw->update( 'page', - /* SET */ array( - 'page_touched' => $now, - 'page_namespace' => $nt->getNamespace(), - 'page_title' => $nt->getDBkey(), - 'page_latest' => $nullRevId, - ), - /* WHERE */ array( 'page_id' => $oldid ), - $fname - ); - - $linkCache->clearLink( $nt->getPrefixedDBkey() ); - - # Insert redirect - $mwRedir = MagicWord::get( 'redirect' ); - $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n"; - $redirectArticle = new Article( $this ); - $newid = $redirectArticle->insertOn( $dbw ); - $redirectRevision = new Revision( array( - 'page' => $newid, - 'comment' => $comment, - 'text' => $redirectText ) ); - $redirectRevision->insertOn( $dbw ); - $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 ); - $linkCache->clearLink( $this->getPrefixedDBkey() ); - - # Log the move - $log = new LogPage( 'move' ); - $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) ); - - # Purge caches as per article creation - Article::onArticleCreate( $nt ); - - # Record the just-created redirect's linking to the page - $dbw->insert( 'pagelinks', - array( - 'pl_from' => $newid, - 'pl_namespace' => $nt->getNamespace(), - 'pl_title' => $nt->getDBkey() ), - $fname ); - - # Purge old title from squid - # The new title, and links to the new title, are purged in Article::onArticleCreate() - $this->purgeSquid(); - } - - /** - * Checks if $this can be moved to a given Title - * - Selects for update, so don't call it unless you mean business - * - * @param Title &$nt the new title to check - */ - public function isValidMoveTarget( $nt ) { - - $fname = 'Title::isValidMoveTarget'; - $dbw = wfGetDB( DB_MASTER ); - - # Is it a redirect? - $id = $nt->getArticleID(); - $obj = $dbw->selectRow( array( 'page', 'revision', 'text'), - array( 'page_is_redirect','old_text','old_flags' ), - array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ), - $fname, 'FOR UPDATE' ); - - if ( !$obj || 0 == $obj->page_is_redirect ) { - # Not a redirect - wfDebug( __METHOD__ . ": not a redirect\n" ); - return false; - } - $text = Revision::getRevisionText( $obj ); - - # Does the redirect point to the source? - # Or is it a broken self-redirect, usually caused by namespace collisions? - $m = array(); - if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) { - $redirTitle = Title::newFromText( $m[1] ); - if( !is_object( $redirTitle ) || - ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() && - $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) { - wfDebug( __METHOD__ . ": redirect points to other page\n" ); - return false; - } - } else { - # Fail safe - wfDebug( __METHOD__ . ": failsafe\n" ); - return false; - } - - # Does the article have a history? - $row = $dbw->selectRow( array( 'page', 'revision'), - array( 'rev_id' ), - array( 'page_namespace' => $nt->getNamespace(), - 'page_title' => $nt->getDBkey(), - 'page_id=rev_page AND page_latest != rev_id' - ), $fname, 'FOR UPDATE' - ); - - # Return true if there was no history - return $row === false; - } - - /** - * Get categories to which this Title belongs and return an array of - * categories' names. - * - * @return array an array of parents in the form: - * $parent => $currentarticle - */ - public function getParentCategories() { - global $wgContLang; - - $titlekey = $this->getArticleId(); - $dbr = wfGetDB( DB_SLAVE ); - $categorylinks = $dbr->tableName( 'categorylinks' ); - - # NEW SQL - $sql = "SELECT * FROM $categorylinks" - ." WHERE cl_from='$titlekey'" - ." AND cl_from <> '0'" - ." ORDER BY cl_sortkey"; - - $res = $dbr->query ( $sql ) ; - - if($dbr->numRows($res) > 0) { - while ( $x = $dbr->fetchObject ( $res ) ) - //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to); - $data[$wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText(); - $dbr->freeResult ( $res ) ; - } else { - $data = ''; - } - return $data; - } - - /** - * Get a tree of parent categories - * @param array $children an array with the children in the keys, to check for circular refs - * @return array - */ - public function getParentCategoryTree( $children = array() ) { - $parents = $this->getParentCategories(); - - if($parents != '') { - foreach($parents as $parent => $current) { - if ( array_key_exists( $parent, $children ) ) { - # Circular reference - $stack[$parent] = array(); - } else { - $nt = Title::newFromText($parent); - if ( $nt ) { - $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) ); - } - } - } - return $stack; - } else { - return array(); - } - } - - - /** - * Get an associative array for selecting this title from - * the "page" table - * - * @return array - */ - public function pageCond() { - return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform ); - } - - /** - * Get the revision ID of the previous revision - * - * @param integer $revision Revision ID. Get the revision that was before this one. - * @return integer $oldrevision|false - */ - public function getPreviousRevisionID( $revision ) { - $dbr = wfGetDB( DB_SLAVE ); - return $dbr->selectField( 'revision', 'rev_id', - 'rev_page=' . intval( $this->getArticleId() ) . - ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' ); - } - - /** - * Get the revision ID of the next revision - * - * @param integer $revision Revision ID. Get the revision that was after this one. - * @return integer $oldrevision|false - */ - public function getNextRevisionID( $revision ) { - $dbr = wfGetDB( DB_SLAVE ); - return $dbr->selectField( 'revision', 'rev_id', - 'rev_page=' . intval( $this->getArticleId() ) . - ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' ); - } - - /** - * Get the number of revisions between the given revision IDs. - * - * @param integer $old Revision ID. - * @param integer $new Revision ID. - * @return integer Number of revisions between these IDs. - */ - public function countRevisionsBetween( $old, $new ) { - $dbr = wfGetDB( DB_SLAVE ); - return $dbr->selectField( 'revision', 'count(*)', - 'rev_page = ' . intval( $this->getArticleId() ) . - ' AND rev_id > ' . intval( $old ) . - ' AND rev_id < ' . intval( $new ) ); - } - - /** - * Compare with another title. - * - * @param Title $title - * @return bool - */ - public function equals( $title ) { - // Note: === is necessary for proper matching of number-like titles. - return $this->getInterwiki() === $title->getInterwiki() - && $this->getNamespace() == $title->getNamespace() - && $this->getDbkey() === $title->getDbkey(); - } - - /** - * Check if page exists - * @return bool - */ - public function exists() { - return $this->getArticleId() != 0; - } - - /** - * Should a link should be displayed as a known link, just based on its title? - * - * Currently, a self-link with a fragment and special pages are in - * this category. Special pages never exist in the database. - */ - public function isAlwaysKnown() { - return $this->isExternal() || ( 0 == $this->mNamespace && "" == $this->mDbkeyform ) - || NS_SPECIAL == $this->mNamespace; - } - - /** - * Update page_touched timestamps and send squid purge messages for - * pages linking to this title. May be sent to the job queue depending - * on the number of links. Typically called on create and delete. - */ - public function touchLinks() { - $u = new HTMLCacheUpdate( $this, 'pagelinks' ); - $u->doUpdate(); - - if ( $this->getNamespace() == NS_CATEGORY ) { - $u = new HTMLCacheUpdate( $this, 'categorylinks' ); - $u->doUpdate(); - } - } - - /** - * Get the last touched timestamp - */ - public function getTouched() { - $dbr = wfGetDB( DB_SLAVE ); - $touched = $dbr->selectField( 'page', 'page_touched', - array( - 'page_namespace' => $this->getNamespace(), - 'page_title' => $this->getDBkey() - ), __METHOD__ - ); - return $touched; - } - - public function trackbackURL() { - global $wgTitle, $wgScriptPath, $wgServer; - - return "$wgServer$wgScriptPath/trackback.php?article=" - . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey())); - } - - public function trackbackRDF() { - $url = htmlspecialchars($this->getFullURL()); - $title = htmlspecialchars($this->getText()); - $tburl = $this->trackbackURL(); - - return " + $db->tableName('pagelinks'), + $db->tableName('page'), + $this->getArticleId(), + $options + ); + + $retVal = array(); + if ($db->numRows($res)) { + while ($row = $db->fetchObject($res)) { + $retVal[] = Title::makeTitle($row->pl_namespace, $row->pl_title); + } + } + $db->freeResult($res); + return $retVal; + } + + + /** + * Get a list of URLs to purge from the Squid cache when this + * page changes + * + * @return array the URLs + */ + public function getSquidURLs() + { + global $wgContLang; + + $urls = array( + $this->getInternalURL(), + $this->getInternalURL('action=history') + ); + + // purge variant urls as well + if ($wgContLang->hasVariants()) { + $variants = $wgContLang->getVariants(); + foreach ($variants as $vCode) { + if ($vCode==$wgContLang->getCode()) { + continue; + } // we don't want default variant + $urls[] = $this->getInternalURL('', $vCode); + } + } + + return $urls; + } + + public function purgeSquid() + { + global $wgUseSquid; + if ($wgUseSquid) { + $urls = $this->getSquidURLs(); + $u = new SquidUpdate($urls); + $u->doUpdate(); + } + } + + /** + * Move this page without authentication + * @param Title &$nt the new page Title + */ + public function moveNoAuth(&$nt) + { + return $this->moveTo($nt, false); + } + + /** + * Check whether a given move operation would be valid. + * Returns true if ok, or a message key string for an error message + * if invalid. (Scarrrrry ugly interface this.) + * @param Title &$nt the new title + * @param bool $auth indicates whether $wgUser's permissions + * should be checked + * @return mixed true on success, message name on failure + */ + public function isValidMoveOperation(&$nt, $auth = true) + { + if (!$this or !$nt) { + return 'badtitletext'; + } + if ($this->equals($nt)) { + return 'selfmove'; + } + if (!$this->isMovable() || !$nt->isMovable()) { + return 'immobile_namespace'; + } + + $oldid = $this->getArticleID(); + $newid = $nt->getArticleID(); + + if (strlen($nt->getDBkey()) < 1) { + return 'articleexists'; + } + if (('' == $this->getDBkey()) || + (!$oldid) || + ('' == $nt->getDBkey())) { + return 'badarticleerror'; + } + + if ($auth && ( + !$this->userCan('edit') || !$nt->userCan('edit') || + !$this->userCan('move') || !$nt->userCan('move') + )) { + return 'protectedpage'; + } + + # The move is allowed only if (1) the target doesn't exist, or + # (2) the target is a redirect to the source, and has no history + # (so we can undo bad moves right after they're done). + + if (0 != $newid) { # Target exists; check for validity + if (!$this->isValidMoveTarget($nt)) { + return 'articleexists'; + } + } + return true; + } + + /** + * Move a title to a new location + * @param Title &$nt the new title + * @param bool $auth indicates whether $wgUser's permissions + * should be checked + * @return mixed true on success, message name on failure + */ + public function moveTo(&$nt, $auth = true, $reason = '') + { + $err = $this->isValidMoveOperation($nt, $auth); + if (is_string($err)) { + return $err; + } + + $pageid = $this->getArticleID(); + if ($nt->exists()) { + $this->moveOverExistingRedirect($nt, $reason); + $pageCountChange = 0; + } else { # Target didn't exist, do normal move. + $this->moveToNewTitle($nt, $reason); + $pageCountChange = 1; + } + $redirid = $this->getArticleID(); + + # Fixing category links (those without piped 'alternate' names) to be sorted under the new title + $dbw = wfGetDB(DB_MASTER); + $categorylinks = $dbw->tableName('categorylinks'); + $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes($nt->getPrefixedText()) . + " WHERE cl_from=" . $dbw->addQuotes($pageid) . + " AND cl_sortkey=" . $dbw->addQuotes($this->getPrefixedText()); + $dbw->query($sql, 'SpecialMovepage::doSubmit'); + + # Update watchlists + + $oldnamespace = $this->getNamespace() & ~1; + $newnamespace = $nt->getNamespace() & ~1; + $oldtitle = $this->getDBkey(); + $newtitle = $nt->getDBkey(); + + if ($oldnamespace != $newnamespace || $oldtitle != $newtitle) { + WatchedItem::duplicateEntries($this, $nt); + } + + # Update search engine + $u = new SearchUpdate($pageid, $nt->getPrefixedDBkey()); + $u->doUpdate(); + $u = new SearchUpdate($redirid, $this->getPrefixedDBkey(), ''); + $u->doUpdate(); + + # Update site_stats + if ($this->isContentPage() && !$nt->isContentPage()) { + # No longer a content page + # Not viewed, edited, removing + $u = new SiteStatsUpdate(0, 1, -1, $pageCountChange); + } elseif (!$this->isContentPage() && $nt->isContentPage()) { + # Now a content page + # Not viewed, edited, adding + $u = new SiteStatsUpdate(0, 1, +1, $pageCountChange); + } elseif ($pageCountChange) { + # Redirect added + $u = new SiteStatsUpdate(0, 0, 0, 1); + } else { + # Nothing special + $u = false; + } + if ($u) { + $u->doUpdate(); + } + + global $wgUser; + wfRunHooks('TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid )); + return true; + } + + /** + * Move page to a title which is at present a redirect to the + * source page + * + * @param Title &$nt the page to move to, which should currently + * be a redirect + */ + private function moveOverExistingRedirect(&$nt, $reason = '') + { + global $wgUseSquid; + $fname = 'Title::moveOverExistingRedirect'; + $comment = wfMsgForContent('1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText()); + + if ($reason) { + $comment .= ": $reason"; + } + + $now = wfTimestampNow(); + $newid = $nt->getArticleID(); + $oldid = $this->getArticleID(); + $dbw = wfGetDB(DB_MASTER); + $linkCache =&LinkCache::singleton(); + + # Delete the old redirect. We don't save it to history since + # by definition if we've got here it's rather uninteresting. + # We have to remove it so that the next step doesn't trigger + # a conflict on the unique namespace+title index... + $dbw->delete('page', array( 'page_id' => $newid ), $fname); + + # Save a null revision in the page's history notifying of the move + $nullRevision = Revision::newNullRevision($dbw, $oldid, $comment, true); + $nullRevId = $nullRevision->insertOn($dbw); + + # Change the name of the target page: + $dbw->update( + 'page', + /* SET */ + array( + 'page_touched' => $dbw->timestamp($now), + 'page_namespace' => $nt->getNamespace(), + 'page_title' => $nt->getDBkey(), + 'page_latest' => $nullRevId, + ), + /* WHERE */ + array( 'page_id' => $oldid ), + $fname + ); + $linkCache->clearLink($nt->getPrefixedDBkey()); + + # Recreate the redirect, this time in the other direction. + $mwRedir = MagicWord::get('redirect'); + $redirectText = $mwRedir->getSynonym(0) . ' [[' . $nt->getPrefixedText() . "]]\n"; + $redirectArticle = new Article($this); + $newid = $redirectArticle->insertOn($dbw); + $redirectRevision = new Revision(array( + 'page' => $newid, + 'comment' => $comment, + 'text' => $redirectText )); + $redirectRevision->insertOn($dbw); + $redirectArticle->updateRevisionOn($dbw, $redirectRevision, 0); + $linkCache->clearLink($this->getPrefixedDBkey()); + + # Log the move + $log = new LogPage('move'); + $log->addEntry('move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() )); + + # Now, we record the link from the redirect to the new title. + # It should have no other outgoing links... + $dbw->delete('pagelinks', array( 'pl_from' => $newid ), $fname); + $dbw->insert( + 'pagelinks', + array( + 'pl_from' => $newid, + 'pl_namespace' => $nt->getNamespace(), + 'pl_title' => $nt->getDbKey() ), + $fname + ); + + # Purge squid + if ($wgUseSquid) { + $urls = array_merge($nt->getSquidURLs(), $this->getSquidURLs()); + $u = new SquidUpdate($urls); + $u->doUpdate(); + } + } + + /** + * Move page to non-existing title. + * @param Title &$nt the new Title + */ + private function moveToNewTitle(&$nt, $reason = '') + { + global $wgUseSquid; + $fname = 'MovePageForm::moveToNewTitle'; + $comment = wfMsgForContent('1movedto2', $this->getPrefixedText(), $nt->getPrefixedText()); + if ($reason) { + $comment .= ": $reason"; + } + + $newid = $nt->getArticleID(); + $oldid = $this->getArticleID(); + $dbw = wfGetDB(DB_MASTER); + $now = $dbw->timestamp(); + $linkCache =&LinkCache::singleton(); + + # Save a null revision in the page's history notifying of the move + $nullRevision = Revision::newNullRevision($dbw, $oldid, $comment, true); + $nullRevId = $nullRevision->insertOn($dbw); + + # Rename cur entry + $dbw->update( + 'page', + /* SET */ + array( + 'page_touched' => $now, + 'page_namespace' => $nt->getNamespace(), + 'page_title' => $nt->getDBkey(), + 'page_latest' => $nullRevId, + ), + /* WHERE */ + array( 'page_id' => $oldid ), + $fname + ); + + $linkCache->clearLink($nt->getPrefixedDBkey()); + + # Insert redirect + $mwRedir = MagicWord::get('redirect'); + $redirectText = $mwRedir->getSynonym(0) . ' [[' . $nt->getPrefixedText() . "]]\n"; + $redirectArticle = new Article($this); + $newid = $redirectArticle->insertOn($dbw); + $redirectRevision = new Revision(array( + 'page' => $newid, + 'comment' => $comment, + 'text' => $redirectText )); + $redirectRevision->insertOn($dbw); + $redirectArticle->updateRevisionOn($dbw, $redirectRevision, 0); + $linkCache->clearLink($this->getPrefixedDBkey()); + + # Log the move + $log = new LogPage('move'); + $log->addEntry('move', $this, $reason, array( 1 => $nt->getPrefixedText())); + + # Purge caches as per article creation + Article::onArticleCreate($nt); + + # Record the just-created redirect's linking to the page + $dbw->insert( + 'pagelinks', + array( + 'pl_from' => $newid, + 'pl_namespace' => $nt->getNamespace(), + 'pl_title' => $nt->getDBkey() ), + $fname + ); + + # Purge old title from squid + # The new title, and links to the new title, are purged in Article::onArticleCreate() + $this->purgeSquid(); + } + + /** + * Checks if $this can be moved to a given Title + * - Selects for update, so don't call it unless you mean business + * + * @param Title &$nt the new title to check + */ + public function isValidMoveTarget($nt) + { + $fname = 'Title::isValidMoveTarget'; + $dbw = wfGetDB(DB_MASTER); + + # Is it a redirect? + $id = $nt->getArticleID(); + $obj = $dbw->selectRow( + array( 'page', 'revision', 'text'), + array( 'page_is_redirect','old_text','old_flags' ), + array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ), + $fname, + 'FOR UPDATE' + ); + + if (!$obj || 0 == $obj->page_is_redirect) { + # Not a redirect + wfDebug(__METHOD__ . ": not a redirect\n"); + return false; + } + $text = Revision::getRevisionText($obj); + + # Does the redirect point to the source? + # Or is it a broken self-redirect, usually caused by namespace collisions? + $m = array(); + if (preg_match("/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m)) { + $redirTitle = Title::newFromText($m[1]); + if (!is_object($redirTitle) || + ($redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() && + $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey())) { + wfDebug(__METHOD__ . ": redirect points to other page\n"); + return false; + } + } else { + # Fail safe + wfDebug(__METHOD__ . ": failsafe\n"); + return false; + } + + # Does the article have a history? + $row = $dbw->selectRow( + array( 'page', 'revision'), + array( 'rev_id' ), + array( 'page_namespace' => $nt->getNamespace(), + 'page_title' => $nt->getDBkey(), + 'page_id=rev_page AND page_latest != rev_id' + ), + $fname, + 'FOR UPDATE' + ); + + # Return true if there was no history + return $row === false; + } + + /** + * Get categories to which this Title belongs and return an array of + * categories' names. + * + * @return array an array of parents in the form: + * $parent => $currentarticle + */ + public function getParentCategories() + { + global $wgContLang; + + $titlekey = $this->getArticleId(); + $dbr = wfGetDB(DB_SLAVE); + $categorylinks = $dbr->tableName('categorylinks'); + + # NEW SQL + $sql = "SELECT * FROM $categorylinks" + . " WHERE cl_from='$titlekey'" + . " AND cl_from <> '0'" + . " ORDER BY cl_sortkey"; + + $res = $dbr->query($sql) ; + + if ($dbr->numRows($res) > 0) { + while ($x = $dbr->fetchObject($res)) { + //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to); + $data[$wgContLang->getNSText(NS_CATEGORY) . ':' . $x->cl_to] = $this->getFullText(); + } + $dbr->freeResult($res) ; + } else { + $data = ''; + } + return $data; + } + + /** + * Get a tree of parent categories + * @param array $children an array with the children in the keys, to check for circular refs + * @return array + */ + public function getParentCategoryTree($children = array()) + { + $parents = $this->getParentCategories(); + + if ($parents != '') { + foreach ($parents as $parent => $current) { + if (array_key_exists($parent, $children)) { + # Circular reference + $stack[$parent] = array(); + } else { + $nt = Title::newFromText($parent); + if ($nt) { + $stack[$parent] = $nt->getParentCategoryTree($children + array($parent => 1)); + } + } + } + return $stack; + } else { + return array(); + } + } + + + /** + * Get an associative array for selecting this title from + * the "page" table + * + * @return array + */ + public function pageCond() + { + return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform ); + } + + /** + * Get the revision ID of the previous revision + * + * @param integer $revision Revision ID. Get the revision that was before this one. + * @return integer $oldrevision|false + */ + public function getPreviousRevisionID($revision) + { + $dbr = wfGetDB(DB_SLAVE); + return $dbr->selectField( + 'revision', + 'rev_id', + 'rev_page=' . intval($this->getArticleId()) . + ' AND rev_id<' . intval($revision) . ' ORDER BY rev_id DESC' + ); + } + + /** + * Get the revision ID of the next revision + * + * @param integer $revision Revision ID. Get the revision that was after this one. + * @return integer $oldrevision|false + */ + public function getNextRevisionID($revision) + { + $dbr = wfGetDB(DB_SLAVE); + return $dbr->selectField( + 'revision', + 'rev_id', + 'rev_page=' . intval($this->getArticleId()) . + ' AND rev_id>' . intval($revision) . ' ORDER BY rev_id' + ); + } + + /** + * Get the number of revisions between the given revision IDs. + * + * @param integer $old Revision ID. + * @param integer $new Revision ID. + * @return integer Number of revisions between these IDs. + */ + public function countRevisionsBetween($old, $new) + { + $dbr = wfGetDB(DB_SLAVE); + return $dbr->selectField( + 'revision', + 'count(*)', + 'rev_page = ' . intval($this->getArticleId()) . + ' AND rev_id > ' . intval($old) . + ' AND rev_id < ' . intval($new) + ); + } + + /** + * Compare with another title. + * + * @param Title $title + * @return bool + */ + public function equals($title) + { + // Note: === is necessary for proper matching of number-like titles. + return $this->getInterwiki() === $title->getInterwiki() + && $this->getNamespace() == $title->getNamespace() + && $this->getDbkey() === $title->getDbkey(); + } + + /** + * Check if page exists + * @return bool + */ + public function exists() + { + return $this->getArticleId() != 0; + } + + /** + * Should a link should be displayed as a known link, just based on its title? + * + * Currently, a self-link with a fragment and special pages are in + * this category. Special pages never exist in the database. + */ + public function isAlwaysKnown() + { + return $this->isExternal() || (0 == $this->mNamespace && "" == $this->mDbkeyform) + || NS_SPECIAL == $this->mNamespace; + } + + /** + * Update page_touched timestamps and send squid purge messages for + * pages linking to this title. May be sent to the job queue depending + * on the number of links. Typically called on create and delete. + */ + public function touchLinks() + { + $u = new HTMLCacheUpdate($this, 'pagelinks'); + $u->doUpdate(); + + if ($this->getNamespace() == NS_CATEGORY) { + $u = new HTMLCacheUpdate($this, 'categorylinks'); + $u->doUpdate(); + } + } + + /** + * Get the last touched timestamp + */ + public function getTouched() + { + $dbr = wfGetDB(DB_SLAVE); + $touched = $dbr->selectField( + 'page', + 'page_touched', + array( + 'page_namespace' => $this->getNamespace(), + 'page_title' => $this->getDBkey() + ), + __METHOD__ + ); + return $touched; + } + + public function trackbackURL() + { + global $wgTitle, $wgScriptPath, $wgServer; + + return "$wgServer$wgScriptPath/trackback.php?article=" + . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey())); + } + + public function trackbackRDF() + { + $url = htmlspecialchars($this->getFullURL()); + $title = htmlspecialchars($this->getText()); + $tburl = $this->trackbackURL(); + + return " @@ -2477,90 +2673,90 @@ return ""; // changed. alex dc:title=\"$title\" trackback:ping=\"$tburl\" /> "; - } - - /** - * Generate strings used for xml 'id' names in monobook tabs - * @return string - */ - public function getNamespaceKey() { - global $wgContLang; - switch ($this->getNamespace()) { - case NS_MAIN: - case NS_TALK: - return 'nstab-main'; - case NS_USER: - case NS_USER_TALK: - return 'nstab-user'; - case NS_MEDIA: - return 'nstab-media'; - case NS_SPECIAL: - return 'nstab-special'; - case NS_PROJECT: - case NS_PROJECT_TALK: - return 'nstab-project'; - case NS_IMAGE: - case NS_IMAGE_TALK: - return 'nstab-image'; - case NS_MEDIAWIKI: - case NS_MEDIAWIKI_TALK: - return 'nstab-mediawiki'; - case NS_TEMPLATE: - case NS_TEMPLATE_TALK: - return 'nstab-template'; - case NS_HELP: - case NS_HELP_TALK: - return 'nstab-help'; - case NS_CATEGORY: - case NS_CATEGORY_TALK: - return 'nstab-category'; - default: - return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() ); - } - } - - /** - * Returns true if this title resolves to the named special page - * @param string $name The special page name - */ - public function isSpecial( $name ) { - if ( $this->getNamespace() == NS_SPECIAL ) { - list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() ); - if ( $name == $thisName ) { - return true; - } - } - return false; - } - - /** - * If the Title refers to a special page alias which is not the local default, - * returns a new Title which points to the local default. Otherwise, returns $this. - */ - public function fixSpecialName() { - if ( $this->getNamespace() == NS_SPECIAL ) { - $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform ); - if ( $canonicalName ) { - $localName = SpecialPage::getLocalNameFor( $canonicalName ); - if ( $localName != $this->mDbkeyform ) { - return Title::makeTitle( NS_SPECIAL, $localName ); - } - } - } - return $this; - } - - /** - * Is this Title in a namespace which contains content? - * In other words, is this a content page, for the purposes of calculating - * statistics, etc? - * - * @return bool - */ + } + + /** + * Generate strings used for xml 'id' names in monobook tabs + * @return string + */ + public function getNamespaceKey() + { + global $wgContLang; + switch ($this->getNamespace()) { + case NS_MAIN: + case NS_TALK: + return 'nstab-main'; + case NS_USER: + case NS_USER_TALK: + return 'nstab-user'; + case NS_MEDIA: + return 'nstab-media'; + case NS_SPECIAL: + return 'nstab-special'; + case NS_PROJECT: + case NS_PROJECT_TALK: + return 'nstab-project'; + case NS_IMAGE: + case NS_IMAGE_TALK: + return 'nstab-image'; + case NS_MEDIAWIKI: + case NS_MEDIAWIKI_TALK: + return 'nstab-mediawiki'; + case NS_TEMPLATE: + case NS_TEMPLATE_TALK: + return 'nstab-template'; + case NS_HELP: + case NS_HELP_TALK: + return 'nstab-help'; + case NS_CATEGORY: + case NS_CATEGORY_TALK: + return 'nstab-category'; + default: + return 'nstab-' . $wgContLang->lc($this->getSubjectNsText()); + } + } + + /** + * Returns true if this title resolves to the named special page + * @param string $name The special page name + */ + public function isSpecial($name) + { + if ($this->getNamespace() == NS_SPECIAL) { + list($thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage($this->getDBkey()); + if ($name == $thisName) { + return true; + } + } + return false; + } + + /** + * If the Title refers to a special page alias which is not the local default, + * returns a new Title which points to the local default. Otherwise, returns $this. + */ + public function fixSpecialName() + { + if ($this->getNamespace() == NS_SPECIAL) { + $canonicalName = SpecialPage::resolveAlias($this->mDbkeyform); + if ($canonicalName) { + $localName = SpecialPage::getLocalNameFor($canonicalName); + if ($localName != $this->mDbkeyform) { + return Title::makeTitle(NS_SPECIAL, $localName); + } + } + } + return $this; + } + + /** + * Is this Title in a namespace which contains content? + * In other words, is this a content page, for the purposes of calculating + * statistics, etc? + * + * @return bool + */ /* public function isContentPage() { - return Namespace::isContent( $this->getNamespace() ); - }*/ - + return Namespace::isContent( $this->getNamespace() ); + }*/ } - -?> diff --git a/Modules/WorkspaceFolder/classes/class.ilObjWorkspaceFolder.php b/Modules/WorkspaceFolder/classes/class.ilObjWorkspaceFolder.php index ea3bb5efa8be6c2876763dbb0868b3cff68db936..955462391d1c1dcc0098a932c38eacd3ee644de2 100644 --- a/Modules/WorkspaceFolder/classes/class.ilObjWorkspaceFolder.php +++ b/Modules/WorkspaceFolder/classes/class.ilObjWorkspaceFolder.php @@ -14,61 +14,55 @@ require_once "Services/Object/classes/class.ilObject2.php"; */ class ilObjWorkspaceFolder extends ilObject2 { - var $folder_tree; - - function initType() - { - $this->type = "wfld"; - } + public $folder_tree; + + public function initType() + { + $this->type = "wfld"; + } - function setFolderTree($a_tree) - { - $this->folder_tree =& $a_tree; - } - - /** - * Clone folder - * - * @access public - * @param object clone - * @param int target id - * @param int copy id - */ - public function doCloneObject($a_new_object, $a_target_id, $a_copy_id = 0) - { - - } + public function setFolderTree($a_tree) + { + $this->folder_tree =&$a_tree; + } + + /** + * Clone folder + * + * @access public + * @param object clone + * @param int target id + * @param int copy id + */ + public function doCloneObject($a_new_object, $a_target_id, $a_copy_id = 0) + { + } - /** - * Clone object dependencies (crs items, preconditions) - * - * @access public - * @param int target ref id of new course - * @param int copy id - * - */ - public function cloneDependencies($a_target_id,$a_copy_id) - { - - } + /** + * Clone object dependencies (crs items, preconditions) + * + * @access public + * @param int target ref id of new course + * @param int copy id + * + */ + public function cloneDependencies($a_target_id, $a_copy_id) + { + } - /** - * Get container view mode - */ - function getViewMode() - { - return ilContainer::VIEW_BY_TYPE; - } + /** + * Get container view mode + */ + public function getViewMode() + { + return ilContainer::VIEW_BY_TYPE; + } - /** - * Add additional information to sub item, e.g. used in - * courses for timings information etc. - */ - function addAdditionalSubItemInformation(&$a_item_data) - { - - } - -} - -?> \ No newline at end of file + /** + * Add additional information to sub item, e.g. used in + * courses for timings information etc. + */ + public function addAdditionalSubItemInformation(&$a_item_data) + { + } +} diff --git a/Modules/WorkspaceFolder/classes/class.ilObjWorkspaceFolderAccess.php b/Modules/WorkspaceFolder/classes/class.ilObjWorkspaceFolderAccess.php index 0ac86719b94b570337360163e9ea97533e369628..91901637e44bf745927cd1b1e42817feb5222a19 100644 --- a/Modules/WorkspaceFolder/classes/class.ilObjWorkspaceFolderAccess.php +++ b/Modules/WorkspaceFolder/classes/class.ilObjWorkspaceFolderAccess.php @@ -14,36 +14,34 @@ include_once("./Services/Object/classes/class.ilObjectAccess.php"); */ class ilObjWorkspaceFolderAccess extends ilObjectAccess { - private static $folderSettings; + private static $folderSettings; - private static function getFolderSettings() { - if (is_null (ilObjWorkspaceFolderAccess::$folderSettings)) - { - ilObjWorkspaceFolderAccess::$folderSettings = new ilSetting('fold'); + private static function getFolderSettings() + { + if (is_null(ilObjWorkspaceFolderAccess::$folderSettings)) { + ilObjWorkspaceFolderAccess::$folderSettings = new ilSetting('fold'); } return ilObjWorkspaceFolderAccess::$folderSettings; } - /** - * 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(); - $commands[] = array("permission" => "read", "cmd" => "view", "lang_var" => "show", "default" => true); - $commands[] = array("permission" => "write", "cmd" => "edit", "lang_var" => "edit"); - return $commands; - } + /** + * 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(); + $commands[] = array("permission" => "read", "cmd" => "view", "lang_var" => "show", "default" => true); + $commands[] = array("permission" => "write", "cmd" => "edit", "lang_var" => "edit"); + return $commands; + } } - -?> diff --git a/Modules/WorkspaceFolder/classes/class.ilObjWorkspaceFolderGUI.php b/Modules/WorkspaceFolder/classes/class.ilObjWorkspaceFolderGUI.php index df95a0507612a676d37bff5b5f6b0bffba78075a..941cd370470ff45f3aa3905c0855d0d0f7bed1b0 100644 --- a/Modules/WorkspaceFolder/classes/class.ilObjWorkspaceFolderGUI.php +++ b/Modules/WorkspaceFolder/classes/class.ilObjWorkspaceFolderGUI.php @@ -17,750 +17,724 @@ require_once "./Services/Object/classes/class.ilObject2GUI.php"; */ class ilObjWorkspaceFolderGUI extends ilObject2GUI { - /** - * @var ilHelpGUI - */ - protected $help; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - - /** - * Constructor - */ - function __construct($a_id = 0, $a_id_type = self::REPOSITORY_NODE_ID, $a_parent_node_id = 0) - { - global $DIC; - parent::__construct($a_id, $a_id_type, $a_parent_node_id); - - $this->lng = $DIC->language(); - $this->help = $DIC["ilHelp"]; - $this->tpl = $DIC["tpl"]; - $this->user = $DIC->user(); - $this->tabs = $DIC->tabs(); - $this->ctrl = $DIC->ctrl(); - } - - function getType() - { - return "wfld"; - } - - function setTabs($a_show_settings = true) - { - $lng = $this->lng; - $ilHelp = $this->help; - - $ilHelp->setScreenIdComponent("wfld"); - - $this->ctrl->setParameter($this,"wsp_id",$this->node_id); - - $this->tabs_gui->addTab("wsp", $lng->txt("wsp_tab_personal"), - $this->ctrl->getLinkTarget($this, "")); - - $this->ctrl->setParameterByClass("ilObjWorkspaceRootFolderGUI", "wsp_id", - $this->getAccessHandler()->getTree()->getRootId()); - - $this->tabs_gui->addTab("share", $lng->txt("wsp_tab_shared"), - $this->ctrl->getLinkTargetByClass("ilObjWorkspaceRootFolderGUI", "shareFilter")); - - $this->tabs_gui->addTab("ownership", $lng->txt("wsp_tab_ownership"), - $this->ctrl->getLinkTargetByClass(array("ilObjWorkspaceRootFolderGUI", "ilObjectOwnershipManagementGUI"), "listObjects")); - - if(!$this->ctrl->getNextClass($this)) - { - if(stristr($this->ctrl->getCmd(), "share")) - { - $this->tabs_gui->activateTab("share"); - } - else - { - $this->tabs_gui->activateTab("wsp"); - - if($a_show_settings) - { - if ($this->checkPermissionBool("read")) - { - $this->tabs_gui->addSubTab("content", - $lng->txt("content"), - $this->ctrl->getLinkTarget($this, "")); - } - - if ($this->checkPermissionBool("write")) - { - $this->tabs_gui->addSubTab("settings", - $lng->txt("settings"), - $this->ctrl->getLinkTarget($this, "edit")); - } - } - } - } - } - - function executeCommand() - { - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - switch($next_class) - { - case "ilcommonactiondispatchergui": - include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); - $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); - $this->ctrl->forwardCommand($gui); - break; - - case "ilobjectownershipmanagementgui": - $this->prepareOutput(); - $this->tabs_gui->activateTab("ownership"); - include_once("Services/Object/classes/class.ilObjectOwnershipManagementGUI.php"); - $gui = new ilObjectOwnershipManagementGUI(); - $this->ctrl->forwardCommand($gui); - break; - - default: - $this->prepareOutput(); - if($this->type != "wsrt") - { - $this->addHeaderAction(); - } - if(!$cmd) - { - $cmd = "render"; - } - $this->$cmd(); - break; - } - - return true; - } - - protected function initCreationForms($a_new_type) - { - $forms = array( - self::CFORM_NEW => $this->initCreateForm($a_new_type) - ); - - return $forms; - } - - /** - * Render folder - */ - function render() - { - $tpl = $this->tpl; - $ilUser = $this->user; - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - - unset($_SESSION['clipboard']['wsp2repo']); - - // add new item - include_once "Services/Object/classes/class.ilObjectAddNewItemGUI.php"; - $gui = new ilObjectAddNewItemGUI($this->node_id); - $gui->setMode(ilObjectDefinition::MODE_WORKSPACE); - $gui->setCreationUrl($ilCtrl->getLinkTarget($this, "create")); - $gui->render(); - - include_once "Services/Object/classes/class.ilObjectListGUI.php"; - ilObjectListGUI::prepareJsLinks("", - $this->ctrl->getLinkTargetByClass(array("ilcommonactiondispatchergui", "ilnotegui"), "", "", true, false), - $this->ctrl->getLinkTargetByClass(array("ilcommonactiondispatchergui", "iltagginggui"), "", "", true, false)); - - include_once "Modules/WorkspaceFolder/classes/class.ilObjWorkspaceFolderTableGUI.php"; - $table = new ilObjWorkspaceFolderTableGUI($this, "render", $this->node_id, $this->getAccessHandler()); - $tpl->setContent($table->getHTML()); - - include_once("./Services/PersonalWorkspace/classes/class.ilWorkspaceExplorerGUI.php"); - $exp = new ilWorkspaceExplorerGUI($ilUser->getId(), $this, "render", $this, "", "wsp_id"); - $exp->setTypeWhiteList(array("wsrt", "wfld")); - $exp->setSelectableTypes(array("wsrt", "wfld")); - $exp->setLinkToNodeClass(true); - $exp->setActivateHighlighting(true); - if ($exp->handleCommand()) - { - return; - } - $left = $exp->getHTML(); - - $tpl->setLeftNavContent($left); - } - - function edit() - { - parent::edit(); - - $this->tabs_gui->activateTab("wsp"); - $this->tabs_gui->activateSubTab("settings"); - } - - function update() - { - parent::update(); - - $this->tabs_gui->activateTab("wsp"); - $this->tabs_gui->activateSubTab("settings"); - } - - /** - * Move node preparation - * - * cut object(s) out from a container and write the information to clipboard - */ - function cut() - { - if (!$_REQUEST["item_ref_id"]) - { - ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); - $this->ctrl->redirect($this); - } - - $current_node = $_REQUEST["item_ref_id"]; - $parent_node = $this->tree->getParentId($current_node); - - // on cancel or fail we return to parent node - $this->ctrl->setParameter($this, "wsp_id", $parent_node); - - // check permission - $no_cut = array(); - foreach ($this->tree->getSubTree($this->tree->getNodeData($current_node)) as $node) - { - if (!$this->checkPermissionBool("delete", "", "", $node["wsp_id"])) - { - $obj = ilObjectFactory::getInstanceByObjId($node["obj_id"]); - $no_cut[$node["wsp_id"]] = $obj->getTitle(); - unset($obj); - } - } - if (count($no_cut)) - { - ilUtil::sendFailure($this->lng->txt("msg_no_perm_cut")." ".implode(',', $no_cut), true); - $this->ctrl->redirect($this); - } - - // open current position - // using the explorer session storage directly is basically a hack - // as we do not use setExpanded() [see below] - $_SESSION['paste_cut_wspexpand'] = array(); - foreach((array)$this->tree->getPathId($parent_node) as $node_id) - { - $_SESSION['paste_cut_wspexpand'][] = $node_id; - } - - // remember source node - $_SESSION['clipboard']['source_id'] = $current_node; - $_SESSION['clipboard']['cmd'] = 'cut'; - - return $this->showMoveIntoObjectTree(); - } - - /** - * Move node preparation (to repository) - * - * cut object(s) out from a container and write the information to clipboard - */ - function cut_for_repository() - { - $_SESSION['clipboard']['wsp2repo'] = true; - $this->cut(); - } - - /** - * Copy node preparation - * - * cioy object(s) out from a container and write the information to clipboard - */ - function copy() - { - $ilUser = $this->user; - - if (!$_REQUEST["item_ref_id"]) - { - ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); - $this->ctrl->redirect($this); - } - - $current_node = $_REQUEST["item_ref_id"]; - $owner = $this->tree->lookupOwner($current_node); - if($owner == $ilUser->getId()) - { - $parent_node = $this->tree->getParentId($current_node); - - // on cancel or fail we return to parent node - $this->ctrl->setParameter($this, "wsp_id", $parent_node); - - // open current position - // using the explorer session storage directly is basically a hack - // as we do not use setExpanded() [see below] - $_SESSION['paste_copy_wspexpand'] = array(); - foreach((array)$this->tree->getPathId($parent_node) as $node_id) - { - $_SESSION['paste_copy_wspexpand'][] = $node_id; - } - } - else - { - // see copyShared() - ilUtil::sendFailure($this->lng->txt('permission_denied'), true); - $this->ctrl->redirect($this); - } - - // remember source node - $_SESSION['clipboard']['source_id'] = $current_node; - $_SESSION['clipboard']['cmd'] = 'copy'; - - return $this->showMoveIntoObjectTree(); - } - - function copyShared() - { - if (!$_REQUEST["item_ref_id"]) - { - $this->ctrl->redirect($this, "share"); - } - - $current_node = $_REQUEST["item_ref_id"]; - $handler = $this->getAccessHandler(); - - // see ilSharedRessourceGUI::hasAccess() - if($handler->checkAccess("read", "", $current_node)) - { - // remember source node - $_SESSION['clipboard']['source_id'] = $current_node; - $_SESSION['clipboard']['cmd'] = 'copy'; - $_SESSION['clipboard']['shared'] = true; - - return $this->showMoveIntoObjectTree(); - } - else - { - $perms = $handler->getPermissions($current_node); - if(in_array(ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD, $perms)) - { - return $this->passwordForm($current_node); - } - } - - ilUtil::sendFailure($this->lng->txt('permission_denied'), true); - $this->ctrl->redirect($this, "share"); - } - - /** - * Copy node preparation (to repository) - * - * copy object(s) out from a container and write the information to clipboard - */ - function copy_to_repository() - { - $_SESSION['clipboard']['wsp2repo'] = true; - $this->copy(); - } - - /** - * Move node: select target (via explorer) - */ - function showMoveIntoObjectTree() - { - $ilTabs = $this->tabs; - $tree = $this->tree; - - $ilTabs->clearTargets(); - - if(!$_SESSION['clipboard']['shared']) - { - $ilTabs->setBackTarget($this->lng->txt('back'), - $this->ctrl->getLinkTarget($this)); - } - else - { - $ilTabs->setBackTarget($this->lng->txt('back'), - $this->ctrl->getLinkTarget($this, 'share')); - } - - $mode = $_SESSION['clipboard']['cmd']; - - ilUtil::sendInfo($this->lng->txt('msg_'.$mode.'_clipboard')); - - $this->tpl->addBlockfile('ADM_CONTENT', 'adm_content', - 'tpl.paste_into_multiple_objects.html', "Services/Object"); - - // move/copy in personal workspace - if(!$_SESSION['clipboard']['wsp2repo']) - { - include_once("./Services/PersonalWorkspace/classes/class.ilWorkspaceExplorerGUI.php"); - $exp = new ilWorkspaceExplorerGUI($this->user->getId(), $this, "showMoveIntoObjectTree", $this, ""); - $exp->setTypeWhiteList(array("wsrt", "wfld")); - $exp->setSelectableTypes(array("wsrt", "wfld")); - $exp->setSelectMode("node", false); - if ($exp->handleCommand()) - { - return; - } - $this->tpl->setVariable('OBJECT_TREE', $exp->getHTML()); - } - // move/copy to repository - else - { - require_once './Services/Object/classes/class.ilPasteIntoMultipleItemsExplorer.php'; - $exp = new ilPasteIntoMultipleItemsExplorer(ilPasteIntoMultipleItemsExplorer::SEL_TYPE_RADIO, - '', 'paste_'.$mode.'_repexpand'); - $exp->setTargetGet('ref_id'); - - if($_GET['paste_'.$mode.'_repexpand'] == '') - { - $expanded = $tree->readRootId(); - } - else - { - $expanded = $_GET['paste_'.$mode.'_repexpand']; - } - $exp->setCheckedItems(array((int)$_POST['node'])); - $exp->setExpandTarget($this->ctrl->getLinkTarget($this, 'showMoveIntoObjectTree')); - $exp->setPostVar('node'); - $exp->setExpand($expanded); - $exp->setOutput(0); - $this->tpl->setVariable('OBJECT_TREE', $exp->getOutput()); - } - - - unset($exp); - - $this->tpl->setVariable('FORM_TARGET', '_top'); - $this->tpl->setVariable('FORM_ACTION', - $this->ctrl->getFormAction($this, 'performPasteIntoMultipleObjects')); - - $this->tpl->setVariable('CMD_SUBMIT', 'performPasteIntoMultipleObjects'); - $this->tpl->setVariable('TXT_SUBMIT', $this->lng->txt('paste')); - } - - /** - * Move node: target has been selected, execute - */ - function performPasteIntoMultipleObjects() - { - $ilUser = $this->user; - - $mode = $_SESSION['clipboard']['cmd']; - $source_node_id = $_SESSION['clipboard']['source_id']; - $target_node_id = $_REQUEST['node']; - - if(!$source_node_id) - { - ilUtil::sendFailure($this->lng->txt('select_at_least_one_object'), true); - $this->ctrl->redirect($this); - } - if(!$target_node_id) - { - ilUtil::sendFailure($this->lng->txt('select_at_least_one_object'), true); - $this->ctrl->redirect($this, "showMoveIntoObjectTree"); - } - - // object instances - $source_obj_id = $this->tree->lookupObjectId($source_node_id); - $source_object = ilObjectFactory::getInstanceByObjId($source_obj_id); - - if(!$_SESSION['clipboard']['wsp2repo']) - { - $target_obj_id = $this->tree->lookupObjectId($target_node_id); - } - else - { - $target_obj_id = ilObject::_lookupObjId($target_node_id); - } - $target_object = ilObjectFactory::getInstanceByObjId($target_obj_id); - - - // sanity checks - - $fail = array(); - - if($source_node_id == $target_node_id) - { - $fail[] = sprintf($this->lng->txt('msg_obj_exists_in_folder'), - $source_object->getTitle(), $target_object->getTitle()); - } - - if(!in_array($source_object->getType(), array_keys($target_object->getPossibleSubObjects()))) - { - $fail[] = sprintf($this->lng->txt('msg_obj_may_not_contain_objects_of_type'), - $target_object->getTitle(), $source_object->getType()); - } - - // if object is shared permission to copy has been checked above - $owner = $this->tree->lookupOwner($source_node_id); - if($mode == "copy" && $ilUser->getId() == $owner && !$this->checkPermissionBool('copy', '', '', $source_node_id)) - { - $fail[] = $this->lng->txt('permission_denied'); - } - - if(!$_SESSION['clipboard']['wsp2repo']) - { - if($mode == "cut" && $this->tree->isGrandChild($source_node_id, $target_node_id)) - { - $fail[] = sprintf($this->lng->txt('msg_paste_object_not_in_itself'), - $source_object->getTitle()); - } - } - - if ($_SESSION['clipboard']['wsp2repo'] == true) // see #22959 - { - global $ilAccess; - if (!$ilAccess->checkAccess("create", "", $target_node_id, $source_object->getType())) - { - $fail[] = sprintf($this->lng->txt('msg_no_perm_paste_object_in_folder'), - $source_object->getTitle(), $target_object->getTitle()); - } - } - else - { - if (!$this->checkPermissionBool('create', '', $source_object->getType(), $target_node_id)) - { - $fail[] = sprintf($this->lng->txt('msg_no_perm_paste_object_in_folder'), - $source_object->getTitle(), $target_object->getTitle()); - } - } - - if(sizeof($fail)) - { - ilUtil::sendFailure(implode("
", $fail), true); - $this->ctrl->redirect($this); - } - - - // move the node - if($mode == "cut") - { - if(!$_SESSION['clipboard']['wsp2repo']) - { - $this->tree->moveTree($source_node_id, $target_node_id); - } - else - { - $parent_id = $this->tree->getParentId($source_node_id); - - // remove from personal workspace - $this->getAccessHandler()->removePermission($source_node_id); - $this->tree->deleteReference($source_node_id); - $source_node = $this->tree->getNodeData($source_node_id); - $this->tree->deleteTree($source_node); - - // add to repository - $source_object->createReference(); - $source_object->putInTree($target_node_id); - $source_object->setPermissions($target_node_id); - - $source_node_id = $parent_id; - } - } - // copy the node - else if($mode == "copy") - { - include_once('Services/CopyWizard/classes/class.ilCopyWizardOptions.php'); - $copy_id = ilCopyWizardOptions::_allocateCopyId(); - $wizard_options = ilCopyWizardOptions::_getInstance($copy_id); - - if(!$_SESSION['clipboard']['wsp2repo']) - { - $wizard_options->disableTreeCopy(); - } - $wizard_options->saveOwner($ilUser->getId()); - $wizard_options->saveRoot($source_node_id); - $wizard_options->read(); - - $new_obj = $source_object->cloneObject($target_node_id, $copy_id); - - // insert into workspace tree - if($new_obj && !$_SESSION['clipboard']['wsp2repo']) - { - $new_obj_node_id = $this->tree->insertObject($target_node_id, $new_obj->getId()); - $this->getAccessHandler()->setPermissions($target_node_id, $new_obj_node_id); - } + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + + /** + * Constructor + */ + public function __construct($a_id = 0, $a_id_type = self::REPOSITORY_NODE_ID, $a_parent_node_id = 0) + { + global $DIC; + parent::__construct($a_id, $a_id_type, $a_parent_node_id); + + $this->lng = $DIC->language(); + $this->help = $DIC["ilHelp"]; + $this->tpl = $DIC["tpl"]; + $this->user = $DIC->user(); + $this->tabs = $DIC->tabs(); + $this->ctrl = $DIC->ctrl(); + } + + public function getType() + { + return "wfld"; + } + + public function setTabs($a_show_settings = true) + { + $lng = $this->lng; + $ilHelp = $this->help; + + $ilHelp->setScreenIdComponent("wfld"); + + $this->ctrl->setParameter($this, "wsp_id", $this->node_id); + + $this->tabs_gui->addTab( + "wsp", + $lng->txt("wsp_tab_personal"), + $this->ctrl->getLinkTarget($this, "") + ); + + $this->ctrl->setParameterByClass( + "ilObjWorkspaceRootFolderGUI", + "wsp_id", + $this->getAccessHandler()->getTree()->getRootId() + ); + + $this->tabs_gui->addTab( + "share", + $lng->txt("wsp_tab_shared"), + $this->ctrl->getLinkTargetByClass("ilObjWorkspaceRootFolderGUI", "shareFilter") + ); + + $this->tabs_gui->addTab( + "ownership", + $lng->txt("wsp_tab_ownership"), + $this->ctrl->getLinkTargetByClass(array("ilObjWorkspaceRootFolderGUI", "ilObjectOwnershipManagementGUI"), "listObjects") + ); + + if (!$this->ctrl->getNextClass($this)) { + if (stristr($this->ctrl->getCmd(), "share")) { + $this->tabs_gui->activateTab("share"); + } else { + $this->tabs_gui->activateTab("wsp"); + + if ($a_show_settings) { + if ($this->checkPermissionBool("read")) { + $this->tabs_gui->addSubTab( + "content", + $lng->txt("content"), + $this->ctrl->getLinkTarget($this, "") + ); + } + + if ($this->checkPermissionBool("write")) { + $this->tabs_gui->addSubTab( + "settings", + $lng->txt("settings"), + $this->ctrl->getLinkTarget($this, "edit") + ); + } + } + } + } + } + + public function executeCommand() + { + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + switch ($next_class) { + case "ilcommonactiondispatchergui": + include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); + $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); + $this->ctrl->forwardCommand($gui); + break; + + case "ilobjectownershipmanagementgui": + $this->prepareOutput(); + $this->tabs_gui->activateTab("ownership"); + include_once("Services/Object/classes/class.ilObjectOwnershipManagementGUI.php"); + $gui = new ilObjectOwnershipManagementGUI(); + $this->ctrl->forwardCommand($gui); + break; + + default: + $this->prepareOutput(); + if ($this->type != "wsrt") { + $this->addHeaderAction(); + } + if (!$cmd) { + $cmd = "render"; + } + $this->$cmd(); + break; + } + + return true; + } + + protected function initCreationForms($a_new_type) + { + $forms = array( + self::CFORM_NEW => $this->initCreateForm($a_new_type) + ); + + return $forms; + } + + /** + * Render folder + */ + public function render() + { + $tpl = $this->tpl; + $ilUser = $this->user; + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + + unset($_SESSION['clipboard']['wsp2repo']); + + // add new item + include_once "Services/Object/classes/class.ilObjectAddNewItemGUI.php"; + $gui = new ilObjectAddNewItemGUI($this->node_id); + $gui->setMode(ilObjectDefinition::MODE_WORKSPACE); + $gui->setCreationUrl($ilCtrl->getLinkTarget($this, "create")); + $gui->render(); + + include_once "Services/Object/classes/class.ilObjectListGUI.php"; + ilObjectListGUI::prepareJsLinks( + "", + $this->ctrl->getLinkTargetByClass(array("ilcommonactiondispatchergui", "ilnotegui"), "", "", true, false), + $this->ctrl->getLinkTargetByClass(array("ilcommonactiondispatchergui", "iltagginggui"), "", "", true, false) + ); + + include_once "Modules/WorkspaceFolder/classes/class.ilObjWorkspaceFolderTableGUI.php"; + $table = new ilObjWorkspaceFolderTableGUI($this, "render", $this->node_id, $this->getAccessHandler()); + $tpl->setContent($table->getHTML()); + + include_once("./Services/PersonalWorkspace/classes/class.ilWorkspaceExplorerGUI.php"); + $exp = new ilWorkspaceExplorerGUI($ilUser->getId(), $this, "render", $this, "", "wsp_id"); + $exp->setTypeWhiteList(array("wsrt", "wfld")); + $exp->setSelectableTypes(array("wsrt", "wfld")); + $exp->setLinkToNodeClass(true); + $exp->setActivateHighlighting(true); + if ($exp->handleCommand()) { + return; + } + $left = $exp->getHTML(); + + $tpl->setLeftNavContent($left); + } + + public function edit() + { + parent::edit(); + + $this->tabs_gui->activateTab("wsp"); + $this->tabs_gui->activateSubTab("settings"); + } + + public function update() + { + parent::update(); + + $this->tabs_gui->activateTab("wsp"); + $this->tabs_gui->activateSubTab("settings"); + } + + /** + * Move node preparation + * + * cut object(s) out from a container and write the information to clipboard + */ + public function cut() + { + if (!$_REQUEST["item_ref_id"]) { + ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); + $this->ctrl->redirect($this); + } + + $current_node = $_REQUEST["item_ref_id"]; + $parent_node = $this->tree->getParentId($current_node); + + // on cancel or fail we return to parent node + $this->ctrl->setParameter($this, "wsp_id", $parent_node); + + // check permission + $no_cut = array(); + foreach ($this->tree->getSubTree($this->tree->getNodeData($current_node)) as $node) { + if (!$this->checkPermissionBool("delete", "", "", $node["wsp_id"])) { + $obj = ilObjectFactory::getInstanceByObjId($node["obj_id"]); + $no_cut[$node["wsp_id"]] = $obj->getTitle(); + unset($obj); + } + } + if (count($no_cut)) { + ilUtil::sendFailure($this->lng->txt("msg_no_perm_cut") . " " . implode(',', $no_cut), true); + $this->ctrl->redirect($this); + } + + // open current position + // using the explorer session storage directly is basically a hack + // as we do not use setExpanded() [see below] + $_SESSION['paste_cut_wspexpand'] = array(); + foreach ((array) $this->tree->getPathId($parent_node) as $node_id) { + $_SESSION['paste_cut_wspexpand'][] = $node_id; + } + + // remember source node + $_SESSION['clipboard']['source_id'] = $current_node; + $_SESSION['clipboard']['cmd'] = 'cut'; + + return $this->showMoveIntoObjectTree(); + } + + /** + * Move node preparation (to repository) + * + * cut object(s) out from a container and write the information to clipboard + */ + public function cut_for_repository() + { + $_SESSION['clipboard']['wsp2repo'] = true; + $this->cut(); + } + + /** + * Copy node preparation + * + * cioy object(s) out from a container and write the information to clipboard + */ + public function copy() + { + $ilUser = $this->user; + + if (!$_REQUEST["item_ref_id"]) { + ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); + $this->ctrl->redirect($this); + } + + $current_node = $_REQUEST["item_ref_id"]; + $owner = $this->tree->lookupOwner($current_node); + if ($owner == $ilUser->getId()) { + $parent_node = $this->tree->getParentId($current_node); + + // on cancel or fail we return to parent node + $this->ctrl->setParameter($this, "wsp_id", $parent_node); + + // open current position + // using the explorer session storage directly is basically a hack + // as we do not use setExpanded() [see below] + $_SESSION['paste_copy_wspexpand'] = array(); + foreach ((array) $this->tree->getPathId($parent_node) as $node_id) { + $_SESSION['paste_copy_wspexpand'][] = $node_id; + } + } else { + // see copyShared() + ilUtil::sendFailure($this->lng->txt('permission_denied'), true); + $this->ctrl->redirect($this); + } + + // remember source node + $_SESSION['clipboard']['source_id'] = $current_node; + $_SESSION['clipboard']['cmd'] = 'copy'; + + return $this->showMoveIntoObjectTree(); + } + + public function copyShared() + { + if (!$_REQUEST["item_ref_id"]) { + $this->ctrl->redirect($this, "share"); + } + + $current_node = $_REQUEST["item_ref_id"]; + $handler = $this->getAccessHandler(); + + // see ilSharedRessourceGUI::hasAccess() + if ($handler->checkAccess("read", "", $current_node)) { + // remember source node + $_SESSION['clipboard']['source_id'] = $current_node; + $_SESSION['clipboard']['cmd'] = 'copy'; + $_SESSION['clipboard']['shared'] = true; + + return $this->showMoveIntoObjectTree(); + } else { + $perms = $handler->getPermissions($current_node); + if (in_array(ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD, $perms)) { + return $this->passwordForm($current_node); + } + } + + ilUtil::sendFailure($this->lng->txt('permission_denied'), true); + $this->ctrl->redirect($this, "share"); + } + + /** + * Copy node preparation (to repository) + * + * copy object(s) out from a container and write the information to clipboard + */ + public function copy_to_repository() + { + $_SESSION['clipboard']['wsp2repo'] = true; + $this->copy(); + } + + /** + * Move node: select target (via explorer) + */ + public function showMoveIntoObjectTree() + { + $ilTabs = $this->tabs; + $tree = $this->tree; + + $ilTabs->clearTargets(); + + if (!$_SESSION['clipboard']['shared']) { + $ilTabs->setBackTarget( + $this->lng->txt('back'), + $this->ctrl->getLinkTarget($this) + ); + } else { + $ilTabs->setBackTarget( + $this->lng->txt('back'), + $this->ctrl->getLinkTarget($this, 'share') + ); + } + + $mode = $_SESSION['clipboard']['cmd']; + + ilUtil::sendInfo($this->lng->txt('msg_' . $mode . '_clipboard')); + + $this->tpl->addBlockfile( + 'ADM_CONTENT', + 'adm_content', + 'tpl.paste_into_multiple_objects.html', + "Services/Object" + ); + + // move/copy in personal workspace + if (!$_SESSION['clipboard']['wsp2repo']) { + include_once("./Services/PersonalWorkspace/classes/class.ilWorkspaceExplorerGUI.php"); + $exp = new ilWorkspaceExplorerGUI($this->user->getId(), $this, "showMoveIntoObjectTree", $this, ""); + $exp->setTypeWhiteList(array("wsrt", "wfld")); + $exp->setSelectableTypes(array("wsrt", "wfld")); + $exp->setSelectMode("node", false); + if ($exp->handleCommand()) { + return; + } + $this->tpl->setVariable('OBJECT_TREE', $exp->getHTML()); + } + // move/copy to repository + else { + require_once './Services/Object/classes/class.ilPasteIntoMultipleItemsExplorer.php'; + $exp = new ilPasteIntoMultipleItemsExplorer( + ilPasteIntoMultipleItemsExplorer::SEL_TYPE_RADIO, + '', + 'paste_' . $mode . '_repexpand' + ); + $exp->setTargetGet('ref_id'); + + if ($_GET['paste_' . $mode . '_repexpand'] == '') { + $expanded = $tree->readRootId(); + } else { + $expanded = $_GET['paste_' . $mode . '_repexpand']; + } + $exp->setCheckedItems(array((int) $_POST['node'])); + $exp->setExpandTarget($this->ctrl->getLinkTarget($this, 'showMoveIntoObjectTree')); + $exp->setPostVar('node'); + $exp->setExpand($expanded); + $exp->setOutput(0); + $this->tpl->setVariable('OBJECT_TREE', $exp->getOutput()); + } + + + unset($exp); + + $this->tpl->setVariable('FORM_TARGET', '_top'); + $this->tpl->setVariable( + 'FORM_ACTION', + $this->ctrl->getFormAction($this, 'performPasteIntoMultipleObjects') + ); + + $this->tpl->setVariable('CMD_SUBMIT', 'performPasteIntoMultipleObjects'); + $this->tpl->setVariable('TXT_SUBMIT', $this->lng->txt('paste')); + } + + /** + * Move node: target has been selected, execute + */ + public function performPasteIntoMultipleObjects() + { + $ilUser = $this->user; + + $mode = $_SESSION['clipboard']['cmd']; + $source_node_id = $_SESSION['clipboard']['source_id']; + $target_node_id = $_REQUEST['node']; + + if (!$source_node_id) { + ilUtil::sendFailure($this->lng->txt('select_at_least_one_object'), true); + $this->ctrl->redirect($this); + } + if (!$target_node_id) { + ilUtil::sendFailure($this->lng->txt('select_at_least_one_object'), true); + $this->ctrl->redirect($this, "showMoveIntoObjectTree"); + } + + // object instances + $source_obj_id = $this->tree->lookupObjectId($source_node_id); + $source_object = ilObjectFactory::getInstanceByObjId($source_obj_id); + + if (!$_SESSION['clipboard']['wsp2repo']) { + $target_obj_id = $this->tree->lookupObjectId($target_node_id); + } else { + $target_obj_id = ilObject::_lookupObjId($target_node_id); + } + $target_object = ilObjectFactory::getInstanceByObjId($target_obj_id); + + + // sanity checks + + $fail = array(); + + if ($source_node_id == $target_node_id) { + $fail[] = sprintf( + $this->lng->txt('msg_obj_exists_in_folder'), + $source_object->getTitle(), + $target_object->getTitle() + ); + } + + if (!in_array($source_object->getType(), array_keys($target_object->getPossibleSubObjects()))) { + $fail[] = sprintf( + $this->lng->txt('msg_obj_may_not_contain_objects_of_type'), + $target_object->getTitle(), + $source_object->getType() + ); + } + + // if object is shared permission to copy has been checked above + $owner = $this->tree->lookupOwner($source_node_id); + if ($mode == "copy" && $ilUser->getId() == $owner && !$this->checkPermissionBool('copy', '', '', $source_node_id)) { + $fail[] = $this->lng->txt('permission_denied'); + } + + if (!$_SESSION['clipboard']['wsp2repo']) { + if ($mode == "cut" && $this->tree->isGrandChild($source_node_id, $target_node_id)) { + $fail[] = sprintf( + $this->lng->txt('msg_paste_object_not_in_itself'), + $source_object->getTitle() + ); + } + } + + if ($_SESSION['clipboard']['wsp2repo'] == true) { // see #22959 + global $ilAccess; + if (!$ilAccess->checkAccess("create", "", $target_node_id, $source_object->getType())) { + $fail[] = sprintf( + $this->lng->txt('msg_no_perm_paste_object_in_folder'), + $source_object->getTitle(), + $target_object->getTitle() + ); + } + } else { + if (!$this->checkPermissionBool('create', '', $source_object->getType(), $target_node_id)) { + $fail[] = sprintf( + $this->lng->txt('msg_no_perm_paste_object_in_folder'), + $source_object->getTitle(), + $target_object->getTitle() + ); + } + } + + if (sizeof($fail)) { + ilUtil::sendFailure(implode("
", $fail), true); + $this->ctrl->redirect($this); + } + + + // move the node + if ($mode == "cut") { + if (!$_SESSION['clipboard']['wsp2repo']) { + $this->tree->moveTree($source_node_id, $target_node_id); + } else { + $parent_id = $this->tree->getParentId($source_node_id); + + // remove from personal workspace + $this->getAccessHandler()->removePermission($source_node_id); + $this->tree->deleteReference($source_node_id); + $source_node = $this->tree->getNodeData($source_node_id); + $this->tree->deleteTree($source_node); + + // add to repository + $source_object->createReference(); + $source_object->putInTree($target_node_id); + $source_object->setPermissions($target_node_id); + + $source_node_id = $parent_id; + } + } + // copy the node + elseif ($mode == "copy") { + include_once('Services/CopyWizard/classes/class.ilCopyWizardOptions.php'); + $copy_id = ilCopyWizardOptions::_allocateCopyId(); + $wizard_options = ilCopyWizardOptions::_getInstance($copy_id); + + if (!$_SESSION['clipboard']['wsp2repo']) { + $wizard_options->disableTreeCopy(); + } + $wizard_options->saveOwner($ilUser->getId()); + $wizard_options->saveRoot($source_node_id); + $wizard_options->read(); + + $new_obj = $source_object->cloneObject($target_node_id, $copy_id); + + // insert into workspace tree + if ($new_obj && !$_SESSION['clipboard']['wsp2repo']) { + $new_obj_node_id = $this->tree->insertObject($target_node_id, $new_obj->getId()); + $this->getAccessHandler()->setPermissions($target_node_id, $new_obj_node_id); + } - $wizard_options->deleteAll(); - } - - // redirect to target if not repository - if(!$_SESSION['clipboard']['wsp2repo']) - { - $redirect_node = $target_node_id; - } - else - { - // reload current folder - $redirect_node = $this->node_id; - } - - unset($_SESSION['clipboard']['cmd']); - unset($_SESSION['clipboard']['source_id']); - unset($_SESSION['clipboard']['wsp2repo']); - unset($_SESSION['clipboard']['shared']); - - // #17746 - if($mode == 'cut') - { - ilUtil::sendSuccess($this->lng->txt('msg_cut_copied'), true); - } - else - { - ilUtil::sendSuccess($this->lng->txt('msg_cloned'), true); - } - - $this->ctrl->setParameter($this, "wsp_id", $redirect_node); - $this->ctrl->redirect($this); - } - - function shareFilter() - { - $this->share(false); - } - - function share($a_load_data = true) - { - $tpl = $this->tpl; - - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceShareTableGUI.php"; - $tbl = new ilWorkspaceShareTableGUI($this, "share", $this->getAccessHandler(), $this->node_id, $a_load_data); - $tpl->setContent($tbl->getHTML()); - } - - function applyShareFilter() - { - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceShareTableGUI.php"; - $tbl = new ilWorkspaceShareTableGUI($this, "share", $this->getAccessHandler(), $this->node_id); - $tbl->resetOffset(); - $tbl->writeFilterToSession(); - - $this->share(); - } - - function resetShareFilter() - { - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceShareTableGUI.php"; - $tbl = new ilWorkspaceShareTableGUI($this, "share", $this->getAccessHandler(), $this->node_id); - $tbl->resetOffset(); - $tbl->resetFilter(); - - $this->shareFilter(); - } - - protected function passwordForm($a_node_id, $form = null) - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilTabs = $this->tabs; - - $tpl->setTitle($lng->txt("wsp_password_protected_resource")); - $tpl->setDescription($lng->txt("wsp_password_protected_resource_info")); - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($lng->txt("back"), - $this->ctrl->getLinkTarget($this, "share")); - - if(!$form) - { - $form = $this->initPasswordForm($a_node_id); - } - - $tpl->setContent($form->getHTML()); - } - - protected function initPasswordForm($a_node_id) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->ctrl->setParameter($this, "item_ref_id", $a_node_id); - - $object_data = $this->getAccessHandler()->getObjectDataFromNode($a_node_id); - - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this, "checkPassword")); - $form->setTitle($lng->txt("wsp_password_for").": ".$object_data["title"]); - - $password = new ilPasswordInputGUI($lng->txt("password"), "password"); - $password->setRetype(false); - $password->setRequired(true); - $password->setSkipSyntaxCheck(true); - $form->addItem($password); - - $form->addCommandButton("checkPassword", $lng->txt("submit")); - $form->addCommandButton("share", $lng->txt("cancel")); - - return $form; - } - - protected function checkPassword() - { - $lng = $this->lng; - - $node_id = $_REQUEST["item_ref_id"]; - if(!$node_id) - { - $this->ctrl->redirect($this, "share"); - } - - $form = $this->initPasswordForm($node_id); - if($form->checkInput()) - { - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; - $password = ilWorkspaceAccessHandler::getSharedNodePassword($node_id); - $input = md5($form->getInput("password")); - if($input == $password) - { - // we save password and start over - ilWorkspaceAccessHandler::keepSharedSessionPassword($node_id, $input); - - $this->ctrl->setParameter($this, "item_ref_id", $node_id); - $this->ctrl->redirect($this, "copyShared"); - } - else - { - $item = $form->getItemByPostVar("password"); - $item->setAlert($lng->txt("wsp_invalid_password")); - ilUtil::sendFailure($lng->txt("form_input_not_valid")); - } - } - - $form->setValuesByPost(); - $this->passwordForm($node_id, $form); - } - - /** - * Deep link - * - * @param string $a_target - */ - public static function _goto($a_target) - { - $id = explode("_", $a_target); - - $_GET["baseClass"] = "ilsharedresourceGUI"; - $_GET["wsp_id"] = $id[0]; - include("ilias.php"); - exit; - } - - /** - * Entry point for awareness tool - */ - function listSharedResourcesOfOtherUser() - { - $ilCtrl = $this->ctrl; - - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceShareTableGUI.php"; - $tbl = new ilWorkspaceShareTableGUI($this, "share", $this->getAccessHandler(), $this->node_id); - $tbl->resetOffset(); - $tbl->resetFilter(); - $_POST["user"] = $_GET["user"]; - $tbl->writeFilterToSession(); - $this->share(); - } - + $wizard_options->deleteAll(); + } + + // redirect to target if not repository + if (!$_SESSION['clipboard']['wsp2repo']) { + $redirect_node = $target_node_id; + } else { + // reload current folder + $redirect_node = $this->node_id; + } + + unset($_SESSION['clipboard']['cmd']); + unset($_SESSION['clipboard']['source_id']); + unset($_SESSION['clipboard']['wsp2repo']); + unset($_SESSION['clipboard']['shared']); + + // #17746 + if ($mode == 'cut') { + ilUtil::sendSuccess($this->lng->txt('msg_cut_copied'), true); + } else { + ilUtil::sendSuccess($this->lng->txt('msg_cloned'), true); + } + + $this->ctrl->setParameter($this, "wsp_id", $redirect_node); + $this->ctrl->redirect($this); + } + + public function shareFilter() + { + $this->share(false); + } + + public function share($a_load_data = true) + { + $tpl = $this->tpl; + + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceShareTableGUI.php"; + $tbl = new ilWorkspaceShareTableGUI($this, "share", $this->getAccessHandler(), $this->node_id, $a_load_data); + $tpl->setContent($tbl->getHTML()); + } + + public function applyShareFilter() + { + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceShareTableGUI.php"; + $tbl = new ilWorkspaceShareTableGUI($this, "share", $this->getAccessHandler(), $this->node_id); + $tbl->resetOffset(); + $tbl->writeFilterToSession(); + + $this->share(); + } + + public function resetShareFilter() + { + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceShareTableGUI.php"; + $tbl = new ilWorkspaceShareTableGUI($this, "share", $this->getAccessHandler(), $this->node_id); + $tbl->resetOffset(); + $tbl->resetFilter(); + + $this->shareFilter(); + } + + protected function passwordForm($a_node_id, $form = null) + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilTabs = $this->tabs; + + $tpl->setTitle($lng->txt("wsp_password_protected_resource")); + $tpl->setDescription($lng->txt("wsp_password_protected_resource_info")); + + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $lng->txt("back"), + $this->ctrl->getLinkTarget($this, "share") + ); + + if (!$form) { + $form = $this->initPasswordForm($a_node_id); + } + + $tpl->setContent($form->getHTML()); + } + + protected function initPasswordForm($a_node_id) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->ctrl->setParameter($this, "item_ref_id", $a_node_id); + + $object_data = $this->getAccessHandler()->getObjectDataFromNode($a_node_id); + + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this, "checkPassword")); + $form->setTitle($lng->txt("wsp_password_for") . ": " . $object_data["title"]); + + $password = new ilPasswordInputGUI($lng->txt("password"), "password"); + $password->setRetype(false); + $password->setRequired(true); + $password->setSkipSyntaxCheck(true); + $form->addItem($password); + + $form->addCommandButton("checkPassword", $lng->txt("submit")); + $form->addCommandButton("share", $lng->txt("cancel")); + + return $form; + } + + protected function checkPassword() + { + $lng = $this->lng; + + $node_id = $_REQUEST["item_ref_id"]; + if (!$node_id) { + $this->ctrl->redirect($this, "share"); + } + + $form = $this->initPasswordForm($node_id); + if ($form->checkInput()) { + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; + $password = ilWorkspaceAccessHandler::getSharedNodePassword($node_id); + $input = md5($form->getInput("password")); + if ($input == $password) { + // we save password and start over + ilWorkspaceAccessHandler::keepSharedSessionPassword($node_id, $input); + + $this->ctrl->setParameter($this, "item_ref_id", $node_id); + $this->ctrl->redirect($this, "copyShared"); + } else { + $item = $form->getItemByPostVar("password"); + $item->setAlert($lng->txt("wsp_invalid_password")); + ilUtil::sendFailure($lng->txt("form_input_not_valid")); + } + } + + $form->setValuesByPost(); + $this->passwordForm($node_id, $form); + } + + /** + * Deep link + * + * @param string $a_target + */ + public static function _goto($a_target) + { + $id = explode("_", $a_target); + + $_GET["baseClass"] = "ilsharedresourceGUI"; + $_GET["wsp_id"] = $id[0]; + include("ilias.php"); + exit; + } + + /** + * Entry point for awareness tool + */ + public function listSharedResourcesOfOtherUser() + { + $ilCtrl = $this->ctrl; + + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceShareTableGUI.php"; + $tbl = new ilWorkspaceShareTableGUI($this, "share", $this->getAccessHandler(), $this->node_id); + $tbl->resetOffset(); + $tbl->resetFilter(); + $_POST["user"] = $_GET["user"]; + $tbl->writeFilterToSession(); + $this->share(); + } } - -?> \ No newline at end of file diff --git a/Modules/WorkspaceFolder/classes/class.ilObjWorkspaceFolderListGUI.php b/Modules/WorkspaceFolder/classes/class.ilObjWorkspaceFolderListGUI.php index 289ee50d4e3b0264549ab7f1d8b6ff11d17eabc7..b5ee503b1aa9a231cb2a2374c2e986fece5f8ead 100644 --- a/Modules/WorkspaceFolder/classes/class.ilObjWorkspaceFolderListGUI.php +++ b/Modules/WorkspaceFolder/classes/class.ilObjWorkspaceFolderListGUI.php @@ -15,24 +15,22 @@ include_once "Services/Object/classes/class.ilObjectListGUI.php"; class ilObjWorkspaceFolderListGUI extends ilObjectListGUI { - /** - * initialisation - */ - function init() - { - $this->delete_enabled = true; - $this->cut_enabled = true; - $this->copy_enabled = true; - $this->subscribe_enabled = false; - $this->link_enabled = false; - $this->info_screen_enabled = false; - $this->type = "wfld"; - $this->gui_class_name = "ilobjworkspacefoldergui"; + /** + * initialisation + */ + public function init() + { + $this->delete_enabled = true; + $this->cut_enabled = true; + $this->copy_enabled = true; + $this->subscribe_enabled = false; + $this->link_enabled = false; + $this->info_screen_enabled = false; + $this->type = "wfld"; + $this->gui_class_name = "ilobjworkspacefoldergui"; - // general commands array - include_once('./Modules/WorkspaceFolder/classes/class.ilObjWorkspaceFolderAccess.php'); - $this->commands = ilObjWorkspaceFolderAccess::_getCommands(); - } - + // general commands array + include_once('./Modules/WorkspaceFolder/classes/class.ilObjWorkspaceFolderAccess.php'); + $this->commands = ilObjWorkspaceFolderAccess::_getCommands(); + } } // END class.ilObjFolderListGUI -?> diff --git a/Modules/WorkspaceFolder/classes/class.ilObjWorkspaceFolderTableGUI.php b/Modules/WorkspaceFolder/classes/class.ilObjWorkspaceFolderTableGUI.php index 0e79071325f03c22db8e9b842d1f4d204ec9da6f..99a5f097118a5c0204c80c4b5ecefa5d78813911 100644 --- a/Modules/WorkspaceFolder/classes/class.ilObjWorkspaceFolderTableGUI.php +++ b/Modules/WorkspaceFolder/classes/class.ilObjWorkspaceFolderTableGUI.php @@ -15,128 +15,123 @@ include_once "Services/Table/classes/class.ilTable2GUI.php"; class ilObjWorkspaceFolderTableGUI extends ilTable2GUI { - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilObjectDefinition - */ - protected $obj_definition; - - function __construct($a_parent_obj, $a_parent_cmd, $a_node_id, $a_access_handler) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->user = $DIC->user(); - $this->obj_definition = $DIC["objDefinition"]; - $ilCtrl = $DIC->ctrl(); - - $this->node_id = $a_node_id; - $this->setId("tbl_wfld"); - $this->access_handler = $a_access_handler; - - parent::__construct($a_parent_obj, $a_parent_cmd); - - // $this->setTitle(":TODO:"); - $this->setLimit(999); - - $this->addColumn($this->lng->txt("content")); - - // $this->setEnableHeader(true); - // $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.list_row.html", "Modules/WorkspaceFolder"); - //$this->disable("footer"); - // $this->setEnableTitle(true); - $this->setEnableNumInfo(false); - - $this->getItems(); - } - - protected function getItems() - { - $ilUser = $this->user; - - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - $tree = new ilWorkspaceTree($ilUser->getId()); - $nodes = $tree->getChilds($this->node_id, "title"); - - if(sizeof($nodes)) - { - include_once("./Services/Object/classes/class.ilObjectListGUIPreloader.php"); - $preloader = new ilObjectListGUIPreloader(ilObjectListGUI::CONTEXT_WORKSPACE); - foreach($nodes as $node) - { - $preloader->addItem($node["obj_id"], $node["type"]); - } - $preloader->preload(); - unset($preloader); - } - - $this->shared_objects = $this->access_handler->getObjectsIShare(); - - $this->setData($nodes); - } - - protected function fillRow($node) - { - $objDefinition = $this->obj_definition; - $ilCtrl = $this->ctrl; - - $class = $objDefinition->getClassName($node["type"]); - $location = $objDefinition->getLocation($node["type"]); - $full_class = "ilObj".$class."ListGUI"; - - include_once($location."/class.".$full_class.".php"); - $item_list_gui = new $full_class(ilObjectListGUI::CONTEXT_WORKSPACE); - - $item_list_gui->setDetailsLevel(ilObjectListGUI::DETAILS_ALL); - $item_list_gui->enableDelete(true); - $item_list_gui->enableCut(true); - $item_list_gui->enableSubscribe(false); - $item_list_gui->enableLink(false); - $item_list_gui->enablePath(false); - $item_list_gui->enableLinkedPath(false); - $item_list_gui->enableSearchFragments(true); - $item_list_gui->enableRelevance(false); - $item_list_gui->enableIcon(true); - $item_list_gui->enableTimings(false); - // $item_list_gui->enableCheckbox(false); - // $item_list_gui->setSeparateCommands(true); - - $item_list_gui->enableNotes(true); - $item_list_gui->enableCopy($objDefinition->allowCopy($node["type"])); - - if($node["type"] == "file") - { - $item_list_gui->enableRepositoryTransfer(true); - } - - $item_list_gui->setContainerObject($this->parent_obj); - - if(in_array($node["type"], array("file", "blog"))) - { - // add "share" link - $ilCtrl->setParameterByClass("ilworkspaceaccessgui", "wsp_id", $node["wsp_id"]); - $share_link = $ilCtrl->getLinkTargetByClass(array("ilObj".$class."GUI", "ilworkspaceaccessgui"), "share"); - $item_list_gui->addCustomCommand($share_link, "wsp_permissions"); - - // show "shared" status - if(in_array($node["obj_id"], $this->shared_objects)) - { - $item_list_gui->addCustomProperty($this->lng->txt("status"), $this->lng->txt("wsp_status_shared"), true, true); - } - } - - if($html = $item_list_gui->getListItemHTML($node["wsp_id"], $node["obj_id"], - $node["title"], $node["description"])) - { - $this->tpl->setVariable("ITEM_LIST_NODE", $html); - } - } - + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilObjectDefinition + */ + protected $obj_definition; + + public function __construct($a_parent_obj, $a_parent_cmd, $a_node_id, $a_access_handler) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->user = $DIC->user(); + $this->obj_definition = $DIC["objDefinition"]; + $ilCtrl = $DIC->ctrl(); + + $this->node_id = $a_node_id; + $this->setId("tbl_wfld"); + $this->access_handler = $a_access_handler; + + parent::__construct($a_parent_obj, $a_parent_cmd); + + // $this->setTitle(":TODO:"); + $this->setLimit(999); + + $this->addColumn($this->lng->txt("content")); + + // $this->setEnableHeader(true); + // $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.list_row.html", "Modules/WorkspaceFolder"); + //$this->disable("footer"); + // $this->setEnableTitle(true); + $this->setEnableNumInfo(false); + + $this->getItems(); + } + + protected function getItems() + { + $ilUser = $this->user; + + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + $tree = new ilWorkspaceTree($ilUser->getId()); + $nodes = $tree->getChilds($this->node_id, "title"); + + if (sizeof($nodes)) { + include_once("./Services/Object/classes/class.ilObjectListGUIPreloader.php"); + $preloader = new ilObjectListGUIPreloader(ilObjectListGUI::CONTEXT_WORKSPACE); + foreach ($nodes as $node) { + $preloader->addItem($node["obj_id"], $node["type"]); + } + $preloader->preload(); + unset($preloader); + } + + $this->shared_objects = $this->access_handler->getObjectsIShare(); + + $this->setData($nodes); + } + + protected function fillRow($node) + { + $objDefinition = $this->obj_definition; + $ilCtrl = $this->ctrl; + + $class = $objDefinition->getClassName($node["type"]); + $location = $objDefinition->getLocation($node["type"]); + $full_class = "ilObj" . $class . "ListGUI"; + + include_once($location . "/class." . $full_class . ".php"); + $item_list_gui = new $full_class(ilObjectListGUI::CONTEXT_WORKSPACE); + + $item_list_gui->setDetailsLevel(ilObjectListGUI::DETAILS_ALL); + $item_list_gui->enableDelete(true); + $item_list_gui->enableCut(true); + $item_list_gui->enableSubscribe(false); + $item_list_gui->enableLink(false); + $item_list_gui->enablePath(false); + $item_list_gui->enableLinkedPath(false); + $item_list_gui->enableSearchFragments(true); + $item_list_gui->enableRelevance(false); + $item_list_gui->enableIcon(true); + $item_list_gui->enableTimings(false); + // $item_list_gui->enableCheckbox(false); + // $item_list_gui->setSeparateCommands(true); + + $item_list_gui->enableNotes(true); + $item_list_gui->enableCopy($objDefinition->allowCopy($node["type"])); + + if ($node["type"] == "file") { + $item_list_gui->enableRepositoryTransfer(true); + } + + $item_list_gui->setContainerObject($this->parent_obj); + + if (in_array($node["type"], array("file", "blog"))) { + // add "share" link + $ilCtrl->setParameterByClass("ilworkspaceaccessgui", "wsp_id", $node["wsp_id"]); + $share_link = $ilCtrl->getLinkTargetByClass(array("ilObj" . $class . "GUI", "ilworkspaceaccessgui"), "share"); + $item_list_gui->addCustomCommand($share_link, "wsp_permissions"); + + // show "shared" status + if (in_array($node["obj_id"], $this->shared_objects)) { + $item_list_gui->addCustomProperty($this->lng->txt("status"), $this->lng->txt("wsp_status_shared"), true, true); + } + } + + if ($html = $item_list_gui->getListItemHTML( + $node["wsp_id"], + $node["obj_id"], + $node["title"], + $node["description"] + )) { + $this->tpl->setVariable("ITEM_LIST_NODE", $html); + } + } } - -?> \ No newline at end of file diff --git a/Modules/WorkspaceFolder/classes/class.ilWorkspaceFolderExplorer.php b/Modules/WorkspaceFolder/classes/class.ilWorkspaceFolderExplorer.php index ff243d35824f96c5483891e3968365a08b4f8a3d..845dd1821dcafb08e63b9a700d8304337d02359c 100644 --- a/Modules/WorkspaceFolder/classes/class.ilWorkspaceFolderExplorer.php +++ b/Modules/WorkspaceFolder/classes/class.ilWorkspaceFolderExplorer.php @@ -1,338 +1,316 @@ - -* @version $Id: class.ilBookmarkExplorer.php 23354 2010-03-24 13:25:09Z akill $ -* -*/ - -include_once("./Services/UIComponent/Explorer/classes/class.ilExplorer.php"); -include_once("Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"); - -class ilWorkspaceFolderExplorer extends ilExplorer -{ - /** - * @var ilCtrl - */ - protected $ctrl; + +* @version $Id: class.ilBookmarkExplorer.php 23354 2010-03-24 13:25:09Z akill $ +* +*/ - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $this->tpl = $DIC["tpl"]; - parent::__construct($a_target); - $this->tree = new ilWorkspaceTree($a_user_id); - $this->root_id = $this->tree->readRootId(); - $this->user_id = $a_user_id; - $this->allowed_types= array ('wfld', 'wsrt'); - $this->enablesmallmode = false; - } - - /** - * Set Enable Small Mode. - * - * @param boolean $a_enablesmallmode Enable Small Mode - */ - function setEnableSmallMode($a_enablesmallmode) - { - $this->enablesmallmode = $a_enablesmallmode; - } - - /** - * Get Enable Small Mode. - * - * @return boolean Enable Small Mode - */ - function getEnableSmallMode() - { - return $this->enablesmallmode; - } - - - /** - * Overwritten method from class.Explorer.php to avoid checkAccess selects - * recursive method - * @access public - * @param integer parent_node_id where to start from (default=0, 'root') - * @param integer depth level where to start (default=1) - * @return string - */ - function setOutput($a_parent, $a_depth = 1, $a_obj_id = 0, $a_highlighted_subtree = false) - { - $lng = $this->lng; - static $counter = 0; - - if ($objects = $this->tree->getChilds($a_parent,"type DESC,title")) - { - $tab = ++$a_depth - 2; - - foreach ($objects as $key => $object) - { - if (!in_array($object["type"],$this->allowed_types)) - { - continue; - } - - //ask for FILTER - if ($object["child"] != $this->root_id) - { - //$data = $this->tree->getParentNodeData($object["child"]); - $parent_index = $this->getIndex($object); - } - - $this->format_options["$counter"]["parent"] = $object["parent"]; - $this->format_options["$counter"]["child"] = $object["child"]; - $this->format_options["$counter"]["title"] = $object["title"]; - $this->format_options["$counter"]["description"] = $object["description"]; - $this->format_options["$counter"]["type"] = $object["type"]; - $this->format_options["$counter"]["depth"] = $tab; - $this->format_options["$counter"]["container"] = false; - $this->format_options["$counter"]["visible"] = true; - - // Create prefix array - for ($i = 0; $i < $tab; ++$i) - { - $this->format_options["$counter"]["tab"][] = 'blank'; - } - // only if parent is expanded and visible, object is visible - if ($object["child"] != $this->root_id and (!in_array($object["parent"],$this->expanded) - or !$this->format_options["$parent_index"]["visible"])) - { - $this->format_options["$counter"]["visible"] = false; - } - - // if object exists parent is container - if ($object["child"] != $this->root_id) - { - $this->format_options["$parent_index"]["container"] = true; - - if (in_array($object["parent"],$this->expanded)) - { - $this->format_options["$parent_index"]["tab"][($tab-2)] = 'minus'; - } - else - { - $this->format_options["$parent_index"]["tab"][($tab-2)] = 'plus'; - } - } - - ++$counter; - - // Recursive - $this->setOutput($object["child"],$a_depth); - } //foreach - } //if - } //function - - /** - * overwritten method from base class - * @access public - * @param integer obj_id - * @param integer array options - * @return string - */ - function formatHeader($tpl, $a_obj_id, $a_option) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $title = $lng->txt("wsp_personal_workspace"); - - $tpl->setCurrentBlock("icon"); - $tpl->setVariable("ICON_IMAGE", ilUtil::getImagePath("icon_wsrt.svg")); - $tpl->setVariable("TXT_ALT_IMG", $title); - $tpl->parseCurrentBlock(); - - $tpl->setCurrentBlock("link"); - $tpl->setVariable("LINK_TARGET", $this->buildLinkTarget($this->root_id, "wsrt")); - $tpl->setVariable("TITLE", $title); - - // highlighting - $style_class = $this->getNodeStyleClass($this->root_id, "wsrt"); - if ($style_class != "") - { - $tpl->setVariable("A_CLASS", ' class="'.$style_class.'" ' ); - } - - $tpl->parseCurrentBlock(); - } - - /** - * set the expand option - * this value is stored in a SESSION variable to save it different view (lo view, frm view,...) - * @access private - * @param string pipe-separated integer - */ - function setExpand($a_node_id) - { - if ($a_node_id == "") - { - $a_node_id = $this->root_id; - } - - // IF ISN'T SET CREATE SESSION VARIABLE - if(!is_array($_SESSION[$this->expand_variable])) - { - $_SESSION[$this->expand_variable] = array(); - } - // IF $_GET["expand"] is positive => expand this node - if($a_node_id > 0 && !in_array($a_node_id,$_SESSION[$this->expand_variable])) - { - array_push($_SESSION[$this->expand_variable],$a_node_id); - } - // IF $_GET["expand"] is negative => compress this node - if($a_node_id < 0) - { - $key = array_keys($_SESSION[$this->expand_variable],-(int) $a_node_id); - unset($_SESSION[$this->expand_variable][$key[0]]); - } - $this->expanded = $_SESSION[$this->expand_variable]; - } - /** - * overwritten method from base class - * get link target - */ - function buildLinkTarget($a_node_id, $a_type) - { - $ilCtrl = $this->ctrl; - - switch ($a_type) - { - case "wsrt": - $ilCtrl->setParameterByClass("ilobjworkspacerootfoldergui", "wsp_id", $a_node_id); - return $ilCtrl->getLinkTargetByClass("ilobjworkspacerootfoldergui", ""); - - case "wfld": - $ilCtrl->setParameterByClass("ilobjworkspacefoldergui", "wsp_id", $a_node_id); - return $ilCtrl->getLinkTargetByClass("ilobjworkspacefoldergui", ""); - - default: - return; - } - } - /** - * overwritten method from base class - * buid link target - */ - function buildFrameTarget($a_type, $a_child = 0, $a_obj_id = 0) - { - return ''; - } - - /** - * set the alowed object types - * @access private - * @param array arraye of object types - */ - function setAllowedTypes($a_types) - { - $this->allowed_types = $a_types; - } - /** - * set details mode - * @access public - * @param string y or n - */ - function setShowDetails($s_details) - { - $this->show_details = $s_details; - } - - /** - * overwritten method from base class - * buid decription - */ - function buildDescription($a_desc, $a_id, $a_type) - { - if ($this->show_details=='y' && !empty($a_desc)) - { - return $a_desc; - - } - else - { - return ""; - } - } - - function getImageAlt($a_def, $a_type = "", $a_obj_id = "") - { - $lng = $this->lng; - - return $lng->txt("icon")." ".$lng->txt($a_type); - } - - function hasFolders($a_node_id) - { - return sizeof($this->tree->getChildsByType($a_node_id, "wfld")); - } - - function getParentNode($a_node_id) - { - return $this->tree->getParentId($a_node_id); - } - - function getOutput() - { - $tpl = $this->tpl; - - $html = parent::getOutput(); - $tpl->setBodyClass("std"); - return $html; - } -} - -?> \ No newline at end of file +include_once("./Services/UIComponent/Explorer/classes/class.ilExplorer.php"); +include_once("Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"); + +class ilWorkspaceFolderExplorer extends ilExplorer +{ + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * user_id + * @var int uid + * @access private + */ + public $user_id; + + /** + * id of root folder + * @var int root folder id + * @access private + */ + public $root_id; + + /** + * allowed object types + * @var array object types + * @access private + */ + public $allowed_types; + + /** + * Constructor + * @access public + * @param string scriptname + * @param int user_id + */ + public function __construct($a_target, $a_user_id) + { + global $DIC; + + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->tpl = $DIC["tpl"]; + parent::__construct($a_target); + $this->tree = new ilWorkspaceTree($a_user_id); + $this->root_id = $this->tree->readRootId(); + $this->user_id = $a_user_id; + $this->allowed_types= array('wfld', 'wsrt'); + $this->enablesmallmode = false; + } + + /** + * Set Enable Small Mode. + * + * @param boolean $a_enablesmallmode Enable Small Mode + */ + public function setEnableSmallMode($a_enablesmallmode) + { + $this->enablesmallmode = $a_enablesmallmode; + } + + /** + * Get Enable Small Mode. + * + * @return boolean Enable Small Mode + */ + public function getEnableSmallMode() + { + return $this->enablesmallmode; + } + + + /** + * Overwritten method from class.Explorer.php to avoid checkAccess selects + * recursive method + * @access public + * @param integer parent_node_id where to start from (default=0, 'root') + * @param integer depth level where to start (default=1) + * @return string + */ + public function setOutput($a_parent, $a_depth = 1, $a_obj_id = 0, $a_highlighted_subtree = false) + { + $lng = $this->lng; + static $counter = 0; + + if ($objects = $this->tree->getChilds($a_parent, "type DESC,title")) { + $tab = ++$a_depth - 2; + + foreach ($objects as $key => $object) { + if (!in_array($object["type"], $this->allowed_types)) { + continue; + } + + //ask for FILTER + if ($object["child"] != $this->root_id) { + //$data = $this->tree->getParentNodeData($object["child"]); + $parent_index = $this->getIndex($object); + } + + $this->format_options["$counter"]["parent"] = $object["parent"]; + $this->format_options["$counter"]["child"] = $object["child"]; + $this->format_options["$counter"]["title"] = $object["title"]; + $this->format_options["$counter"]["description"] = $object["description"]; + $this->format_options["$counter"]["type"] = $object["type"]; + $this->format_options["$counter"]["depth"] = $tab; + $this->format_options["$counter"]["container"] = false; + $this->format_options["$counter"]["visible"] = true; + + // Create prefix array + for ($i = 0; $i < $tab; ++$i) { + $this->format_options["$counter"]["tab"][] = 'blank'; + } + // only if parent is expanded and visible, object is visible + if ($object["child"] != $this->root_id and (!in_array($object["parent"], $this->expanded) + or !$this->format_options["$parent_index"]["visible"])) { + $this->format_options["$counter"]["visible"] = false; + } + + // if object exists parent is container + if ($object["child"] != $this->root_id) { + $this->format_options["$parent_index"]["container"] = true; + + if (in_array($object["parent"], $this->expanded)) { + $this->format_options["$parent_index"]["tab"][($tab-2)] = 'minus'; + } else { + $this->format_options["$parent_index"]["tab"][($tab-2)] = 'plus'; + } + } + + ++$counter; + + // Recursive + $this->setOutput($object["child"], $a_depth); + } //foreach + } //if + } //function + + /** + * overwritten method from base class + * @access public + * @param integer obj_id + * @param integer array options + * @return string + */ + public function formatHeader($tpl, $a_obj_id, $a_option) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $title = $lng->txt("wsp_personal_workspace"); + + $tpl->setCurrentBlock("icon"); + $tpl->setVariable("ICON_IMAGE", ilUtil::getImagePath("icon_wsrt.svg")); + $tpl->setVariable("TXT_ALT_IMG", $title); + $tpl->parseCurrentBlock(); + + $tpl->setCurrentBlock("link"); + $tpl->setVariable("LINK_TARGET", $this->buildLinkTarget($this->root_id, "wsrt")); + $tpl->setVariable("TITLE", $title); + + // highlighting + $style_class = $this->getNodeStyleClass($this->root_id, "wsrt"); + if ($style_class != "") { + $tpl->setVariable("A_CLASS", ' class="' . $style_class . '" '); + } + + $tpl->parseCurrentBlock(); + } + + /** + * set the expand option + * this value is stored in a SESSION variable to save it different view (lo view, frm view,...) + * @access private + * @param string pipe-separated integer + */ + public function setExpand($a_node_id) + { + if ($a_node_id == "") { + $a_node_id = $this->root_id; + } + + // IF ISN'T SET CREATE SESSION VARIABLE + if (!is_array($_SESSION[$this->expand_variable])) { + $_SESSION[$this->expand_variable] = array(); + } + // IF $_GET["expand"] is positive => expand this node + if ($a_node_id > 0 && !in_array($a_node_id, $_SESSION[$this->expand_variable])) { + array_push($_SESSION[$this->expand_variable], $a_node_id); + } + // IF $_GET["expand"] is negative => compress this node + if ($a_node_id < 0) { + $key = array_keys($_SESSION[$this->expand_variable], -(int) $a_node_id); + unset($_SESSION[$this->expand_variable][$key[0]]); + } + $this->expanded = $_SESSION[$this->expand_variable]; + } + /** + * overwritten method from base class + * get link target + */ + public function buildLinkTarget($a_node_id, $a_type) + { + $ilCtrl = $this->ctrl; + + switch ($a_type) { + case "wsrt": + $ilCtrl->setParameterByClass("ilobjworkspacerootfoldergui", "wsp_id", $a_node_id); + return $ilCtrl->getLinkTargetByClass("ilobjworkspacerootfoldergui", ""); + + case "wfld": + $ilCtrl->setParameterByClass("ilobjworkspacefoldergui", "wsp_id", $a_node_id); + return $ilCtrl->getLinkTargetByClass("ilobjworkspacefoldergui", ""); + + default: + return; + } + } + /** + * overwritten method from base class + * buid link target + */ + public function buildFrameTarget($a_type, $a_child = 0, $a_obj_id = 0) + { + return ''; + } + + /** + * set the alowed object types + * @access private + * @param array arraye of object types + */ + public function setAllowedTypes($a_types) + { + $this->allowed_types = $a_types; + } + /** + * set details mode + * @access public + * @param string y or n + */ + public function setShowDetails($s_details) + { + $this->show_details = $s_details; + } + + /** + * overwritten method from base class + * buid decription + */ + public function buildDescription($a_desc, $a_id, $a_type) + { + if ($this->show_details=='y' && !empty($a_desc)) { + return $a_desc; + } else { + return ""; + } + } + + public function getImageAlt($a_def, $a_type = "", $a_obj_id = "") + { + $lng = $this->lng; + + return $lng->txt("icon") . " " . $lng->txt($a_type); + } + + public function hasFolders($a_node_id) + { + return sizeof($this->tree->getChildsByType($a_node_id, "wfld")); + } + + public function getParentNode($a_node_id) + { + return $this->tree->getParentId($a_node_id); + } + + public function getOutput() + { + $tpl = $this->tpl; + + $html = parent::getOutput(); + $tpl->setBodyClass("std"); + return $html; + } +} diff --git a/Modules/WorkspaceRootFolder/classes/class.ilObjWorkspaceRootFolder.php b/Modules/WorkspaceRootFolder/classes/class.ilObjWorkspaceRootFolder.php index 986afef17b8f68b86d5e1e11828310bec79f4fb4..a3adb009aa04bca1d92ccf95976fc99b175b5eff 100644 --- a/Modules/WorkspaceRootFolder/classes/class.ilObjWorkspaceRootFolder.php +++ b/Modules/WorkspaceRootFolder/classes/class.ilObjWorkspaceRootFolder.php @@ -15,85 +15,81 @@ require_once "Services/Object/classes/class.ilObject2.php"; class ilObjWorkspaceRootFolder extends ilObject2 { - /** - * Constructor - */ - function __construct($a_id = 0, $a_reference = true) - { - global $DIC; - parent::__construct($a_id, $a_reference); - - $this->db = $DIC->database(); - } - - function initType() - { - $this->type = "wsrt"; - } - - /** - * get all translations from this category - * - * @access public - * @return array - */ - function getTranslations() - { - $ilDB = $this->db; - - $q = "SELECT * FROM object_translation WHERE obj_id = ". - $ilDB->quote($this->getId(),'integer')." ORDER BY lang_default DESC"; - $r = $ilDB->query($q); - - $num = 0; - - $data["Fobject"] = array(); - while ($row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - $data["Fobject"][$num]= array("title" => $row->title, - "desc" => $row->description, - "lang" => $row->lang_code - ); - $num++; - } - - // first entry is always the default language - $data["default_language"] = 0; - - return $data ? $data : array(); - } - - // remove all Translations of current category - function removeTranslations() - { - $ilDB = $this->db; - - $query = "DELETE FROM object_translation WHERE obj_id= ". - $ilDB->quote($this->getId(),'integer'); - $res = $ilDB->manipulate($query); - } - - // add a new translation to current category - function addTranslation($a_title,$a_desc,$a_lang,$a_lang_default) - { - $ilDB = $this->db; - - if (empty($a_title)) - { - $a_title = "NO TITLE"; - } - - $query = "INSERT INTO object_translation ". - "(obj_id,title,description,lang_code,lang_default) ". - "VALUES ". - "(".$ilDB->quote($this->getId(),'integer').",". - $ilDB->quote($a_title,'text').",". - $ilDB->quote($a_desc,'text').",". - $ilDB->quote($a_lang,'text').",". - $ilDB->quote($a_lang_default,'integer').")"; - $res = $ilDB->manipulate($query); - return true; - } - + /** + * Constructor + */ + public function __construct($a_id = 0, $a_reference = true) + { + global $DIC; + parent::__construct($a_id, $a_reference); + + $this->db = $DIC->database(); + } + + public function initType() + { + $this->type = "wsrt"; + } + + /** + * get all translations from this category + * + * @access public + * @return array + */ + public function getTranslations() + { + $ilDB = $this->db; + + $q = "SELECT * FROM object_translation WHERE obj_id = " . + $ilDB->quote($this->getId(), 'integer') . " ORDER BY lang_default DESC"; + $r = $ilDB->query($q); + + $num = 0; + + $data["Fobject"] = array(); + while ($row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + $data["Fobject"][$num]= array("title" => $row->title, + "desc" => $row->description, + "lang" => $row->lang_code + ); + $num++; + } + + // first entry is always the default language + $data["default_language"] = 0; + + return $data ? $data : array(); + } + + // remove all Translations of current category + public function removeTranslations() + { + $ilDB = $this->db; + + $query = "DELETE FROM object_translation WHERE obj_id= " . + $ilDB->quote($this->getId(), 'integer'); + $res = $ilDB->manipulate($query); + } + + // add a new translation to current category + public function addTranslation($a_title, $a_desc, $a_lang, $a_lang_default) + { + $ilDB = $this->db; + + if (empty($a_title)) { + $a_title = "NO TITLE"; + } + + $query = "INSERT INTO object_translation " . + "(obj_id,title,description,lang_code,lang_default) " . + "VALUES " . + "(" . $ilDB->quote($this->getId(), 'integer') . "," . + $ilDB->quote($a_title, 'text') . "," . + $ilDB->quote($a_desc, 'text') . "," . + $ilDB->quote($a_lang, 'text') . "," . + $ilDB->quote($a_lang_default, 'integer') . ")"; + $res = $ilDB->manipulate($query); + return true; + } } // END class.ObjRootFolder -?> diff --git a/Modules/WorkspaceRootFolder/classes/class.ilObjWorkspaceRootFolderAccess.php b/Modules/WorkspaceRootFolder/classes/class.ilObjWorkspaceRootFolderAccess.php index 52422248568a039ef86d4b776fb4c2b40d211f2f..20059f4b080c150fc24181dcf475598b9b6e2901 100644 --- a/Modules/WorkspaceRootFolder/classes/class.ilObjWorkspaceRootFolderAccess.php +++ b/Modules/WorkspaceRootFolder/classes/class.ilObjWorkspaceRootFolderAccess.php @@ -14,30 +14,26 @@ include_once("./Services/Object/classes/class.ilObjectAccess.php"); */ class ilObjWorkspaceRootFolderAccess extends ilObjectAccess { - /** - * 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" => "render", "lang_var" => "show", - "default" => true), - array("permission" => "write", "cmd" => "edit", "lang_var" => "edit"), - ); - - return $commands; - } - + /** + * 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" => "render", "lang_var" => "show", + "default" => true), + array("permission" => "write", "cmd" => "edit", "lang_var" => "edit"), + ); + + return $commands; + } } - -?> diff --git a/Modules/WorkspaceRootFolder/classes/class.ilObjWorkspaceRootFolderGUI.php b/Modules/WorkspaceRootFolder/classes/class.ilObjWorkspaceRootFolderGUI.php index 4cfdbdeb9c5ff14744a64f8938bdad4e936c0aaf..f8d4c0e02120e8b637fe06ad7ab55bc2d764c2c1 100644 --- a/Modules/WorkspaceRootFolder/classes/class.ilObjWorkspaceRootFolderGUI.php +++ b/Modules/WorkspaceRootFolder/classes/class.ilObjWorkspaceRootFolderGUI.php @@ -11,47 +11,45 @@ require_once "Modules/WorkspaceFolder/classes/class.ilObjWorkspaceFolderGUI.php" * @version $Id: class.ilObjRootFolderGUI.php 27165 2011-01-04 13:48:35Z jluetzen $Id: class.ilObjRootFolderGUI.php,v 1.13 2006/03/10 09:22:58 akill Exp $ * * @ilCtrl_Calls ilObjWorkspaceRootFolderGUI: ilCommonActionDispatcherGUI, ilObjectOwnershipManagementGUI -* +* * @extends ilObject2GUI */ class ilObjWorkspaceRootFolderGUI extends ilObjWorkspaceFolderGUI { - /** - * Constructor - */ - function __construct($a_id = 0, $a_id_type = self::REPOSITORY_NODE_ID, $a_parent_node_id = 0) - { - parent::__construct($a_id, $a_id_type, $a_parent_node_id); - global $DIC; - - $this->help = $DIC["ilHelp"]; - $this->tpl = $DIC["tpl"]; - $this->lng = $DIC->language(); - } - - function getType() - { - return "wsrt"; - } - - function setTabs($a_show_settings = false) - { - $ilHelp = $this->help; - - parent::setTabs(false); - $ilHelp->setScreenIdComponent("wsrt"); - } - - protected function setTitleAndDescription() - { - $tpl = $this->tpl; - $lng = $this->lng; - - $tpl->setTitle($lng->txt("wsp_personal_workspace")); - $tpl->setTitleIcon(ilUtil::getImagePath("icon_wsrt.svg"), $title); - $tpl->setDescription($lng->txt("wsp_personal_workspace_description")); - } + /** + * Constructor + */ + public function __construct($a_id = 0, $a_id_type = self::REPOSITORY_NODE_ID, $a_parent_node_id = 0) + { + parent::__construct($a_id, $a_id_type, $a_parent_node_id); + global $DIC; + + $this->help = $DIC["ilHelp"]; + $this->tpl = $DIC["tpl"]; + $this->lng = $DIC->language(); + } + + public function getType() + { + return "wsrt"; + } + + public function setTabs($a_show_settings = false) + { + $ilHelp = $this->help; + + parent::setTabs(false); + $ilHelp->setScreenIdComponent("wsrt"); + } + + protected function setTitleAndDescription() + { + $tpl = $this->tpl; + $lng = $this->lng; + + $tpl->setTitle($lng->txt("wsp_personal_workspace")); + $tpl->setTitleIcon(ilUtil::getImagePath("icon_wsrt.svg"), $title); + $tpl->setDescription($lng->txt("wsp_personal_workspace_description")); + } } - -?> \ No newline at end of file diff --git a/Modules/WorkspaceRootFolder/classes/class.ilObjWorkspaceRootFolderListGUI.php b/Modules/WorkspaceRootFolder/classes/class.ilObjWorkspaceRootFolderListGUI.php index 1581e26063c7ef07da0182afcae0ec9de7bffb9f..eeb925bb91ab60b5de8bf0bec5fecf758da90273 100644 --- a/Modules/WorkspaceRootFolder/classes/class.ilObjWorkspaceRootFolderListGUI.php +++ b/Modules/WorkspaceRootFolder/classes/class.ilObjWorkspaceRootFolderListGUI.php @@ -14,43 +14,40 @@ include_once "Services/Object/classes/class.ilObjectListGUI.php"; */ class ilObjWorkspaceRootFolderListGUI extends ilObjectListGUI { - /** - * initialisation - */ - function init() - { - $this->copy_enabled = false; - $this->delete_enabled = false; - $this->cut_enabled = false; - $this->subscribe_enabled = false; - $this->link_enabled = false; - $this->type = "root"; - $this->gui_class_name = "ilobjworkspacerootfoldergui"; - - // general commands array - include_once('./Modules/WorkspaceRootFolder/classes/class.ilObjWorkspaceRootFolderAccess.php'); - $this->commands = ilObjWorkspaceRootFolderAccess::_getCommands(); - } - - /** - * Get command link url. - * - * @param int $a_ref_id reference id - * @param string $a_cmd command - * - */ - function getCommandLink($a_cmd) - { - $ilCtrl = $this->ctrl; - - // does this make any sense!? - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $this->ref_id); - $cmd_link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", $a_cmd); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - - return $cmd_link; - } - - + /** + * initialisation + */ + public function init() + { + $this->copy_enabled = false; + $this->delete_enabled = false; + $this->cut_enabled = false; + $this->subscribe_enabled = false; + $this->link_enabled = false; + $this->type = "root"; + $this->gui_class_name = "ilobjworkspacerootfoldergui"; + + // general commands array + include_once('./Modules/WorkspaceRootFolder/classes/class.ilObjWorkspaceRootFolderAccess.php'); + $this->commands = ilObjWorkspaceRootFolderAccess::_getCommands(); + } + + /** + * Get command link url. + * + * @param int $a_ref_id reference id + * @param string $a_cmd command + * + */ + public function getCommandLink($a_cmd) + { + $ilCtrl = $this->ctrl; + + // does this make any sense!? + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $this->ref_id); + $cmd_link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", $a_cmd); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + + return $cmd_link; + } } // END class.ilObjWorkspaceRootFolderGUI -?> diff --git a/Services/AccessControl/classes/class.ilStartingPoint.php b/Services/AccessControl/classes/class.ilStartingPoint.php index 183fe0044364a499cfe4346c5551e9447b9d83b1..7ca5bb0b80b6c95162c3ad172b265d3a511dcac7 100644 --- a/Services/AccessControl/classes/class.ilStartingPoint.php +++ b/Services/AccessControl/classes/class.ilStartingPoint.php @@ -363,20 +363,14 @@ class ilStartingPoint */ public static function reArrangePositions($a_items) { - //first and last items doesn't have order position, are fixed. - $ord_const = 10; + $ord_const = 0; + $rearranged = []; foreach ($a_items as $k => $v) { - if($k > 0) - { - $item = $v; - $item['starting_position'] = $ord_const; - unset($a_items[$k]); - $a_items[$ord_const] = $item; + $v['starting_position'] = $ord_const; + $rearranged[$ord_const] = $v; $ord_const = $ord_const + 10; - } } - - return $a_items; + return $rearranged; } /** diff --git a/Services/Accessibility/classes/class.ilAccessKey.php b/Services/Accessibility/classes/class.ilAccessKey.php index 671966f23b72078c71c429039bfbe72435f7e227..288cd81b6e0a500efc98f646ea0c86d618d8037c 100644 --- a/Services/Accessibility/classes/class.ilAccessKey.php +++ b/Services/Accessibility/classes/class.ilAccessKey.php @@ -10,185 +10,180 @@ */ class ilAccessKey { - // function id constants - const NEXT = 1; - const PREVIOUS = 2; - const DELETE = 3; - const LAST_VISITED = 4; - const TREE_ON = 5; - const TREE_OFF = 6; - const REPLY = 7; - const FORWARD_MAIL = 8; - const MARK_ALL_READ = 9; - const PERSONAL_DESKTOP = 10; - - public static $func_def = array( - ilAccessKey::NEXT => array( - "component" => array("global"), - "lang" => "acc_next"), - ilAccessKey::PREVIOUS => array( - "component" => array("global"), - "lang" => "acc_previous"), - ilAccessKey::DELETE => array( - "component" => array("global"), - "lang" => "acc_delete"), - ilAccessKey::LAST_VISITED => array( - "component" => array("global"), - "lang" => "acc_last_rep_visited"), - ilAccessKey::TREE_ON => array( - "component" => array("global"), - "lang" => "acc_tree_on"), - ilAccessKey::TREE_OFF => array( - "component" => array("global"), - "lang" => "acc_tree_off"), - ilAccessKey::REPLY => array( - "component" => array("mail"), - "lang" => "acc_reply"), - ilAccessKey::FORWARD_MAIL => array( - "component" => array("mail"), - "lang" => "acc_forward_mail"), - ilAccessKey::MARK_ALL_READ => array( - "component" => array("frm"), - "lang" => "acc_mark_all_read"), - ilAccessKey::PERSONAL_DESKTOP => array( - "component" => array("global"), - "lang" => "acc_personal_desktop") - ); - - /** - * Get all function ids with empty keys - * - * @return array function id => empty string - */ - private static function getAllKeysEmpty() - { - $empty_keys = array(); - foreach (self::$func_def as $f => $c) - { - $empty_keys[$f] = ""; - } - - return $empty_keys; - } - - /** - * Get Function Name - */ - static function getFunctionName($a_func_id) - { - global $DIC; + // function id constants + const NEXT = 1; + const PREVIOUS = 2; + const DELETE = 3; + const LAST_VISITED = 4; + const TREE_ON = 5; + const TREE_OFF = 6; + const REPLY = 7; + const FORWARD_MAIL = 8; + const MARK_ALL_READ = 9; + const PERSONAL_DESKTOP = 10; + + public static $func_def = array( + ilAccessKey::NEXT => array( + "component" => array("global"), + "lang" => "acc_next"), + ilAccessKey::PREVIOUS => array( + "component" => array("global"), + "lang" => "acc_previous"), + ilAccessKey::DELETE => array( + "component" => array("global"), + "lang" => "acc_delete"), + ilAccessKey::LAST_VISITED => array( + "component" => array("global"), + "lang" => "acc_last_rep_visited"), + ilAccessKey::TREE_ON => array( + "component" => array("global"), + "lang" => "acc_tree_on"), + ilAccessKey::TREE_OFF => array( + "component" => array("global"), + "lang" => "acc_tree_off"), + ilAccessKey::REPLY => array( + "component" => array("mail"), + "lang" => "acc_reply"), + ilAccessKey::FORWARD_MAIL => array( + "component" => array("mail"), + "lang" => "acc_forward_mail"), + ilAccessKey::MARK_ALL_READ => array( + "component" => array("frm"), + "lang" => "acc_mark_all_read"), + ilAccessKey::PERSONAL_DESKTOP => array( + "component" => array("global"), + "lang" => "acc_personal_desktop") + ); + + /** + * Get all function ids with empty keys + * + * @return array function id => empty string + */ + private static function getAllKeysEmpty() + { + $empty_keys = array(); + foreach (self::$func_def as $f => $c) { + $empty_keys[$f] = ""; + } + + return $empty_keys; + } + + /** + * Get Function Name + */ + public static function getFunctionName($a_func_id) + { + global $DIC; - $lng = $DIC->language(); + $lng = $DIC->language(); - return $lng->txt(self::$func_def[$a_func_id]["lang"]); - } - - /** - * Get Component Names - */ - static function getComponentNames($a_func_id) - { - global $DIC; + return $lng->txt(self::$func_def[$a_func_id]["lang"]); + } + + /** + * Get Component Names + */ + public static function getComponentNames($a_func_id) + { + global $DIC; - $lng = $DIC->language(); + $lng = $DIC->language(); - $c_str = $lim = ""; - foreach (self::$func_def[$a_func_id]["component"] as $c) - { - $c_str.= $lim.$lng->txt("acc_comp_".$c); - $lim = ", "; - } - return $c_str; - } + $c_str = $lim = ""; + foreach (self::$func_def[$a_func_id]["component"] as $c) { + $c_str.= $lim . $lng->txt("acc_comp_" . $c); + $lim = ", "; + } + return $c_str; + } - - /** - * Get access keys for language. - * - * @param string lang key, "0" means default values - */ - static function getKeys($lang_key = "0", $a_ignore_default = false) - { - global $DIC; + + /** + * Get access keys for language. + * + * @param string lang key, "0" means default values + */ + public static function getKeys($lang_key = "0", $a_ignore_default = false) + { + global $DIC; - $ilDB = $DIC->database(); - - $keys = ilAccessKey::getAllKeysEmpty(); - - // get defaults - if ($lang_key != "0" && !$a_ignore_default) - { - $keys = ilAccessKey::getKeys(); - } - - // get keys of selected language - $set = $ilDB->query("SELECT * FROM acc_access_key ". - " WHERE lang_key = ".$ilDB->quote($lang_key, "text") - ); - while ($rec = $ilDB->fetchAssoc($set)) - { - $keys[$rec["function_id"]] = $rec["access_key"]; - } - - return $keys; - } - - /** - * Get single access key. - * - * @param string lang key, "0" means default values - */ - static function getKey($a_func_id, $lang_key = "0", $a_ignore_default = false) - { - global $DIC; + $ilDB = $DIC->database(); + + $keys = ilAccessKey::getAllKeysEmpty(); + + // get defaults + if ($lang_key != "0" && !$a_ignore_default) { + $keys = ilAccessKey::getKeys(); + } + + // get keys of selected language + $set = $ilDB->query( + "SELECT * FROM acc_access_key " . + " WHERE lang_key = " . $ilDB->quote($lang_key, "text") + ); + while ($rec = $ilDB->fetchAssoc($set)) { + $keys[$rec["function_id"]] = $rec["access_key"]; + } + + return $keys; + } + + /** + * Get single access key. + * + * @param string lang key, "0" means default values + */ + public static function getKey($a_func_id, $lang_key = "0", $a_ignore_default = false) + { + global $DIC; - $ilDB = $DIC->database(); - - $key = ""; - - // get defaults - if ($lang_key != "0" && !$a_ignore_default) - { - $key = ilAccessKey::getKey($a_func_id); - } - - // get keys of selected language - $set = $ilDB->query("SELECT * FROM acc_access_key ". - " WHERE lang_key = ".$ilDB->quote($lang_key, "text"). - " AND function_id = ".$ilDB->quote($a_func_id, "integer") - ); - if ($rec = $ilDB->fetchAssoc($set)) - { - $key = $rec["access_key"]; - } - - return $key; - } + $ilDB = $DIC->database(); + + $key = ""; + + // get defaults + if ($lang_key != "0" && !$a_ignore_default) { + $key = ilAccessKey::getKey($a_func_id); + } + + // get keys of selected language + $set = $ilDB->query( + "SELECT * FROM acc_access_key " . + " WHERE lang_key = " . $ilDB->quote($lang_key, "text") . + " AND function_id = " . $ilDB->quote($a_func_id, "integer") + ); + if ($rec = $ilDB->fetchAssoc($set)) { + $key = $rec["access_key"]; + } + + return $key; + } - /** - * Write keys - * - * @param array function ids => keys - */ - static function writeKeys($a_keys, $a_lang_key = "0") - { - global $DIC; + /** + * Write keys + * + * @param array function ids => keys + */ + public static function writeKeys($a_keys, $a_lang_key = "0") + { + global $DIC; - $ilDB = $DIC->database(); - - $ilDB->manipulate("DELETE FROM acc_access_key WHERE ". - "lang_key = ".$ilDB->quote($a_lang_key, "text") - ); - - foreach ($a_keys as $func_id => $acc_key) - { - $ilDB->manipulate("INSERT INTO acc_access_key ". - "(lang_key, function_id, access_key) VALUES (". - $ilDB->quote($a_lang_key, "text").",". - $ilDB->quote($func_id, "integer").",". - $ilDB->quote(strtolower(trim($acc_key)), "text"). - ")"); - } - } - + $ilDB = $DIC->database(); + + $ilDB->manipulate( + "DELETE FROM acc_access_key WHERE " . + "lang_key = " . $ilDB->quote($a_lang_key, "text") + ); + + foreach ($a_keys as $func_id => $acc_key) { + $ilDB->manipulate("INSERT INTO acc_access_key " . + "(lang_key, function_id, access_key) VALUES (" . + $ilDB->quote($a_lang_key, "text") . "," . + $ilDB->quote($func_id, "integer") . "," . + $ilDB->quote(strtolower(trim($acc_key)), "text") . + ")"); + } + } } diff --git a/Services/Accessibility/classes/class.ilAccessKeyGUI.php b/Services/Accessibility/classes/class.ilAccessKeyGUI.php index c916d945005a1833448175a153d750c4bc0c32fc..7c51d3b811022f160282cf00aba2c40d41434a28 100644 --- a/Services/Accessibility/classes/class.ilAccessKeyGUI.php +++ b/Services/Accessibility/classes/class.ilAccessKeyGUI.php @@ -11,21 +11,20 @@ include_once("./Services/Accessibility/classes/class.ilAccessKey.php"); */ class ilAccessKeyGUI { - /** - * Get accesskey HTML attribute - * @static - * @param int $a_func_id - * @return string - */ - public static function getAttribute($a_func_id) - { - $key = ilAccessKey::getKey($a_func_id); + /** + * Get accesskey HTML attribute + * @static + * @param int $a_func_id + * @return string + */ + public static function getAttribute($a_func_id) + { + $key = ilAccessKey::getKey($a_func_id); - if($key != "") - { - return 'accesskey="' . $key . '"'; - } + if ($key != "") { + return 'accesskey="' . $key . '"'; + } - return ""; - } + return ""; + } } diff --git a/Services/Accessibility/classes/class.ilAccessKeyTableGUI.php b/Services/Accessibility/classes/class.ilAccessKeyTableGUI.php index fdada37e9f563925fb0a732c70d218bf9852bcba..e36266c2f934a5edbb0ff71a2a3e05fd4213c864 100644 --- a/Services/Accessibility/classes/class.ilAccessKeyTableGUI.php +++ b/Services/Accessibility/classes/class.ilAccessKeyTableGUI.php @@ -13,76 +13,72 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilAccessKeyTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd) - { - global $DIC; + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd) + { + 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(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - - // get keys - include_once("./Services/Accessibility/classes/class.ilAccessKey.php"); - - $keys = ilAccessKey::getKeys(); - $data = array(); - foreach ($keys as $f => $k) - { - $data[] = array("func_id" => $f, "access_key" => $k); - } - $this->setData($data); - $this->setTitle($lng->txt("acc_access_keys")); - $this->setLimit(9999); - - $this->addColumn($this->lng->txt("acc_component"), "", ""); - $this->addColumn($this->lng->txt("acc_function"), "", ""); - $this->addColumn($this->lng->txt("acc_access_key"), "", ""); - - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.access_key_row.html", "Services/Accessibility"); - $this->disable("footer"); - $this->setEnableTitle(true); + $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); + + // get keys + include_once("./Services/Accessibility/classes/class.ilAccessKey.php"); + + $keys = ilAccessKey::getKeys(); + $data = array(); + foreach ($keys as $f => $k) { + $data[] = array("func_id" => $f, "access_key" => $k); + } + $this->setData($data); + $this->setTitle($lng->txt("acc_access_keys")); + $this->setLimit(9999); + + $this->addColumn($this->lng->txt("acc_component"), "", ""); + $this->addColumn($this->lng->txt("acc_function"), "", ""); + $this->addColumn($this->lng->txt("acc_access_key"), "", ""); + + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.access_key_row.html", "Services/Accessibility"); + $this->disable("footer"); + $this->setEnableTitle(true); -// $this->addMultiCommand("", $lng->txt("")); - if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) - { - $this->addCommandButton("saveAccessKeys", $lng->txt("save")); - } - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - - $this->tpl->setVariable("VAL_COMPONENT", ilAccessKey::getComponentNames($a_set["func_id"])); - $this->tpl->setVariable("VAL_FUNCTION", ilAccessKey::getFunctionName($a_set["func_id"])); - $this->tpl->setVariable("FUNC_ID", $a_set["func_id"]); - $this->tpl->setVariable("VAL_ACC_KEY", ilUtil::prepareFormOutput($a_set["access_key"])); - } + // $this->addMultiCommand("", $lng->txt("")); + if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) { + $this->addCommandButton("saveAccessKeys", $lng->txt("save")); + } + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $this->tpl->setVariable("VAL_COMPONENT", ilAccessKey::getComponentNames($a_set["func_id"])); + $this->tpl->setVariable("VAL_FUNCTION", ilAccessKey::getFunctionName($a_set["func_id"])); + $this->tpl->setVariable("FUNC_ID", $a_set["func_id"]); + $this->tpl->setVariable("VAL_ACC_KEY", ilUtil::prepareFormOutput($a_set["access_key"])); + } } -?> diff --git a/Services/Accessibility/classes/class.ilObjAccessibilitySettings.php b/Services/Accessibility/classes/class.ilObjAccessibilitySettings.php index 3c4e3f68d666ad986fd237dd3bdb65d889408bf1..fd65dbc9c7b0d4df437b7257048b122aa5a61d90 100755 --- a/Services/Accessibility/classes/class.ilObjAccessibilitySettings.php +++ b/Services/Accessibility/classes/class.ilObjAccessibilitySettings.php @@ -5,85 +5,81 @@ require_once "./Services/Object/classes/class.ilObject.php"; /** * Class ilObjAccessibilitySettings -* -* @author Alex Killing +* +* @author Alex Killing * @version $Id$ * * @ingroup ServicesAccessibility */ class ilObjAccessibilitySettings extends ilObject { - /** - * @var ilDB - */ - protected $db; - - - /** - * Constructor - * @access public - * @param integer reference_id or object_id - * @param boolean treat the id as reference_id (true) or object_id (false) - */ - function __construct($a_id = 0,$a_call_by_reference = true) - { - global $DIC; + /** + * @var ilDB + */ + protected $db; - $this->db = $DIC->database(); - $this->type = "accs"; - parent::__construct($a_id,$a_call_by_reference); - } + + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + global $DIC; - /** - * update object data - * - * @access public - * @return boolean - */ - function update() - { - $ilDB = $this->db; - - if (!parent::update()) - { - return false; - } + $this->db = $DIC->database(); + $this->type = "accs"; + parent::__construct($a_id, $a_call_by_reference); + } - return true; - } - - /** - * read - */ - function read() - { - $ilDB = $this->db; + /** + * update object data + * + * @access public + * @return boolean + */ + public function update() + { + $ilDB = $this->db; + + if (!parent::update()) { + return false; + } - parent::read(); + return true; + } + + /** + * read + */ + public function read() + { + $ilDB = $this->db; - } - + parent::read(); + } + - - + + - /** - * delete object and all related data - * - * @access public - * @return boolean true if all object data were removed; false if only a references were removed - */ - function delete() - { - // always call parent delete function first!! - if (!parent::delete()) - { - return false; - } - - //put here your module specific stuff - - return true; - } + /** + * delete object and all related data + * + * @access public + * @return boolean true if all object data were removed; false if only a references were removed + */ + public function delete() + { + // always call parent delete function first!! + if (!parent::delete()) { + return false; + } + + //put here your module specific stuff + + return true; + } } -?> diff --git a/Services/Accessibility/classes/class.ilObjAccessibilitySettingsAccess.php b/Services/Accessibility/classes/class.ilObjAccessibilitySettingsAccess.php index eaba151d733f9414737a366bc9594e5e11a4ad57..c03f0c65c3a77e785b44a150c66582ca8366f24a 100755 --- a/Services/Accessibility/classes/class.ilObjAccessibilitySettingsAccess.php +++ b/Services/Accessibility/classes/class.ilObjAccessibilitySettingsAccess.php @@ -13,8 +13,4 @@ include_once("./Services/Object/classes/class.ilObjectAccess.php"); */ class ilObjAccessibilitySettingsAccess extends ilObjectAccess { - - } - -?> diff --git a/Services/Accessibility/classes/class.ilObjAccessibilitySettingsGUI.php b/Services/Accessibility/classes/class.ilObjAccessibilitySettingsGUI.php index 0cb53d1ca27e10c07e5dd14a6fb3c8f1d4cff51c..0d86bfb30af0f8bece0df7fb1c8b6920204460d2 100755 --- a/Services/Accessibility/classes/class.ilObjAccessibilitySettingsGUI.php +++ b/Services/Accessibility/classes/class.ilObjAccessibilitySettingsGUI.php @@ -16,186 +16,183 @@ include_once("./Services/Object/classes/class.ilObjectGUI.php"); */ class ilObjAccessibilitySettingsGUI extends ilObjectGUI { - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * Contructor - * - * @access public - */ - public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) - { - global $DIC; - - $this->rbacsystem = $DIC->rbac()->system(); - $this->error = $DIC["ilErr"]; - $this->access = $DIC->access(); - $this->tabs = $DIC->tabs(); - $this->tpl = $DIC["tpl"]; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->type = 'accs'; - parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); - - $this->lng->loadLanguageModule('acc'); - } - - /** - * Execute command - * - * @access public - * - */ - public function executeCommand() - { - $rbacsystem = $this->rbacsystem; - $ilErr = $this->error; - $ilAccess = $this->access; - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - $this->prepareOutput(); - - if(!$rbacsystem->checkAccess('read',$this->object->getRefId())) - { - $ilErr->raiseError($this->lng->txt('no_permission'),$ilErr->WARNING); - } - - switch($next_class) - { - case 'ilpermissiongui': - $this->tabs_gui->setTabActive('perm_settings'); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $ret = $this->ctrl->forwardCommand($perm_gui); - break; - - default: - if(!$cmd || $cmd == 'view') - { - $cmd = "editAccessibilitySettings"; - } - - $this->$cmd(); - break; - } - return true; - } - - /** - * @return ilPropertyFormGUI - */ - protected function getSettingsForm() - { - require_once 'Services/Form/classes/class.ilPropertyFormGUI.php'; - $form = new ilPropertyFormGUI(); - $form->setTitle($this->lng->txt('settings')); - - require_once 'Services/Administration/classes/class.ilAdministrationSettingsFormHandler.php'; - ilAdministrationSettingsFormHandler::addFieldsToForm( - ilAdministrationSettingsFormHandler::FORM_ACCESSIBILITY, - $form, - $this - ); - - return $form; - } - - /** - * @param ilPropertyFormGUI $form - */ - protected function editAccessibilitySettings(ilPropertyFormGUI $form = null) - { - $this->tabs_gui->setTabActive('acc_settings'); - if(!$form) - { - $form = $this->getSettingsForm(); - } - - $this->tpl->setContent($form->getHTML()); - } - - /** - * Get tabs - * - * @access public - * - */ - public function getAdminTabs() - { - $rbacsystem = $this->rbacsystem; - $ilAccess = $this->access; - $ilTabs = $this->tabs; - - if ($rbacsystem->checkAccess("read", $this->object->getRefId())) - { - $ilTabs->addTab('acc_settings', $this->lng->txt('settings'), $this->ctrl->getLinkTarget($this, 'editAccessibilitySettings')); - } - - if ($rbacsystem->checkAccess("read", $this->object->getRefId())) - { - $ilTabs->addTarget("acc_access_keys", - $this->ctrl->getLinkTarget($this, "editAccessKeys"), - array("editAccessKeys", "view")); - } - - if ($rbacsystem->checkAccess("edit_permission", $this->object->getRefId())) - { - $ilTabs->addTarget("perm_settings", - $this->ctrl->getLinkTargetByClass('ilpermissiongui',"perm"), - array(),'ilpermissiongui'); - } - } - - /** - * Edit access keys - */ - function editAccessKeys() - { - $tpl = $this->tpl; - - $this->tabs_gui->setTabActive('acc_access_keys'); - - include_once("./Services/Accessibility/classes/class.ilAccessKeyTableGUI.php"); - $table = new ilAccessKeyTableGUI($this, "editAccessKeys"); - - $tpl->setContent($table->getHTML()); - } - - /** - * Save access keys - */ - function saveAccessKeys() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilAccess = $this->access; - - if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) - { - include_once("./Services/Accessibility/classes/class.ilAccessKey.php"); - ilAccessKey::writeKeys(ilUtil::stripSlashesArray($_POST["acckey"])); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - } - $ilCtrl->redirect($this, "editAccessKeys"); - } -} \ No newline at end of file + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * Contructor + * + * @access public + */ + public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) + { + global $DIC; + + $this->rbacsystem = $DIC->rbac()->system(); + $this->error = $DIC["ilErr"]; + $this->access = $DIC->access(); + $this->tabs = $DIC->tabs(); + $this->tpl = $DIC["tpl"]; + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->type = 'accs'; + parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); + + $this->lng->loadLanguageModule('acc'); + } + + /** + * Execute command + * + * @access public + * + */ + public function executeCommand() + { + $rbacsystem = $this->rbacsystem; + $ilErr = $this->error; + $ilAccess = $this->access; + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + $this->prepareOutput(); + + if (!$rbacsystem->checkAccess('read', $this->object->getRefId())) { + $ilErr->raiseError($this->lng->txt('no_permission'), $ilErr->WARNING); + } + + switch ($next_class) { + case 'ilpermissiongui': + $this->tabs_gui->setTabActive('perm_settings'); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $ret = $this->ctrl->forwardCommand($perm_gui); + break; + + default: + if (!$cmd || $cmd == 'view') { + $cmd = "editAccessibilitySettings"; + } + + $this->$cmd(); + break; + } + return true; + } + + /** + * @return ilPropertyFormGUI + */ + protected function getSettingsForm() + { + require_once 'Services/Form/classes/class.ilPropertyFormGUI.php'; + $form = new ilPropertyFormGUI(); + $form->setTitle($this->lng->txt('settings')); + + require_once 'Services/Administration/classes/class.ilAdministrationSettingsFormHandler.php'; + ilAdministrationSettingsFormHandler::addFieldsToForm( + ilAdministrationSettingsFormHandler::FORM_ACCESSIBILITY, + $form, + $this + ); + + return $form; + } + + /** + * @param ilPropertyFormGUI $form + */ + protected function editAccessibilitySettings(ilPropertyFormGUI $form = null) + { + $this->tabs_gui->setTabActive('acc_settings'); + if (!$form) { + $form = $this->getSettingsForm(); + } + + $this->tpl->setContent($form->getHTML()); + } + + /** + * Get tabs + * + * @access public + * + */ + public function getAdminTabs() + { + $rbacsystem = $this->rbacsystem; + $ilAccess = $this->access; + $ilTabs = $this->tabs; + + if ($rbacsystem->checkAccess("read", $this->object->getRefId())) { + $ilTabs->addTab('acc_settings', $this->lng->txt('settings'), $this->ctrl->getLinkTarget($this, 'editAccessibilitySettings')); + } + + if ($rbacsystem->checkAccess("read", $this->object->getRefId())) { + $ilTabs->addTarget( + "acc_access_keys", + $this->ctrl->getLinkTarget($this, "editAccessKeys"), + array("editAccessKeys", "view") + ); + } + + if ($rbacsystem->checkAccess("edit_permission", $this->object->getRefId())) { + $ilTabs->addTarget( + "perm_settings", + $this->ctrl->getLinkTargetByClass('ilpermissiongui', "perm"), + array(), + 'ilpermissiongui' + ); + } + } + + /** + * Edit access keys + */ + public function editAccessKeys() + { + $tpl = $this->tpl; + + $this->tabs_gui->setTabActive('acc_access_keys'); + + include_once("./Services/Accessibility/classes/class.ilAccessKeyTableGUI.php"); + $table = new ilAccessKeyTableGUI($this, "editAccessKeys"); + + $tpl->setContent($table->getHTML()); + } + + /** + * Save access keys + */ + public function saveAccessKeys() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilAccess = $this->access; + + if ($ilAccess->checkAccess("write", "", $_GET["ref_id"])) { + include_once("./Services/Accessibility/classes/class.ilAccessKey.php"); + ilAccessKey::writeKeys(ilUtil::stripSlashesArray($_POST["acckey"])); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + } + $ilCtrl->redirect($this, "editAccessKeys"); + } +} diff --git a/Services/Accordion/classes/class.ilAccordionGUI.php b/Services/Accordion/classes/class.ilAccordionGUI.php index 394e4bb4021400c70d8675565c00e3838026946c..65393b28ce533c1ae43fe5731b07169370b6ecc3 100755 --- a/Services/Accordion/classes/class.ilAccordionGUI.php +++ b/Services/Accordion/classes/class.ilAccordionGUI.php @@ -10,563 +10,536 @@ */ class ilAccordionGUI { - /** - * @var ilObjUser - */ - protected $user; - - protected $items = array(); - protected $force_open = array(); - protected static $accordion_cnt = 0; - protected $use_session_storage = false; - protected $allow_multi_opened = false; - protected $show_all_element = null; - protected $hide_all_element = null; - - const VERTICAL = "vertical"; - const HORIZONTAL = "horizontal"; - const FORCE_ALL_OPEN = "ForceAllOpen"; - const FIRST_OPEN = "FirstOpen"; - const ALL_CLOSED = "AllClosed"; - - static $owl_path = "./libs/bower/bower_components/owl.carousel/dist"; - static $owl_js_path = "/owl.carousel.js"; - static $owl_css_path = "/assets/owl.carousel.css"; - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->user = $DIC->user(); - $this->setOrientation(ilAccordionGUI::VERTICAL); - } - - /** - * Set id - * - * @param string id - */ - function setId($a_val) - { - $this->id = $a_val; - } - - /** - * Get id - * - * @return string id - */ - function getId() - { - return $this->id; - } - - /** - * Set Orientation. - * - * @param string $a_orientation Orientation - */ - function setOrientation($a_orientation) - { - if (in_array($a_orientation, - array(ilAccordionGUI::VERTICAL, ilAccordionGUI::HORIZONTAL))) - { - $this->orientation = $a_orientation; - } - } - - /** - * Get Orientation. - * - * @return string Orientation - */ - function getOrientation() - { - return $this->orientation; - } - - /** - * Set Container CSS Class. - * - * @param string $a_containerclass Container CSS Class - */ - function setContainerClass($a_containerclass) - { - $this->containerclass = $a_containerclass; - } - - /** - * Get Container CSS Class. - * - * @return string Container CSS Class - */ - function getContainerClass() - { - return $this->containerclass; - } - - /** - * Set inner Container CSS Class. - * - * @param string $a_containerclass Container CSS Class - */ - function setInnerContainerClass($a_containerclass) - { - $this->icontainerclass = $a_containerclass; - } - - /** - * Get inner Container CSS Class. - * - * @return string Container CSS Class - */ - function getInnerContainerClass() - { - return $this->icontainerclass; - } - - /** - * Set Header CSS Class. - * - * @param string $a_headerclass Header CSS Class - */ - function setHeaderClass($a_headerclass) - { - $this->headerclass = $a_headerclass; - } - - /** - * Get Header CSS Class. - * - * @return string Header CSS Class - */ - function getHeaderClass() - { - return $this->headerclass; - } - - /** - * Set active header class - * - * @param string $a_h_class Active Header CSS Class - */ - function setActiveHeaderClass($a_h_class) - { - $this->active_headerclass = $a_h_class; - } - - /** - * Get active Header CSS Class. - * - * @return string Active header CSS Class - */ - function getActiveHeaderClass() - { - return $this->active_headerclass; - } - - /** - * Set Content CSS Class. - * - * @param string $a_contentclass Content CSS Class - */ - function setContentClass($a_contentclass) - { - $this->contentclass = $a_contentclass; - } - - /** - * Get Content CSS Class. - * - * @return string Content CSS Class - */ - function getContentClass() - { - return $this->contentclass; - } - - /** - * Set ContentWidth. - * - * @param integer $a_contentwidth ContentWidth - */ - function setContentWidth($a_contentwidth) - { - $this->contentwidth = $a_contentwidth; - } - - /** - * Get ContentWidth. - * - * @return integer ContentWidth - */ - function getContentWidth() - { - return $this->contentwidth; - } - - /** - * Set ContentHeight. - * - * @param integer $a_contentheight ContentHeight - */ - function setContentHeight($a_contentheight) - { - $this->contentheight = $a_contentheight; - } - - /** - * Get ContentHeight. - * - * @return integer ContentHeight - */ - function getContentHeight() - { - return $this->contentheight; - } - - /** - * Set behaviour "ForceAllOpen" | "FirstOpen" | "AllClosed" - * - * @param string behaviour - */ - function setBehaviour($a_val) - { - $this->behaviour = $a_val; - } - - /** - * Get behaviour - * - * @return - */ - function getBehaviour() - { - return $this->behaviour; - } - - /** - * Set use session storage - * - * @param bool $a_val use session storage - */ - function setUseSessionStorage($a_val) - { - $this->use_session_storage = $a_val; - } - - /** - * Get use session storage - * - * @return bool use session storage - */ - function getUseSessionStorage() - { - return $this->use_session_storage; - } - - /** - * Set allow multi opened - * - * @param bool $a_val allow multiple accordions being opened - */ - function setAllowMultiOpened($a_val) - { - $this->allow_multi_opened = $a_val; - } - - /** - * Get allow multi opened - * - * @return bool allow multiple accordions being opened - */ - function getAllowMultiOpened() - { - return $this->allow_multi_opened; - } - - /** - * Set show all element - * - * @param string $a_val ID of show all html element - */ - function setShowAllElement($a_val) - { - $this->show_all_element = $a_val; - } - - /** - * Get show all element - * - * @return string ID of show all html element - */ - function getShowAllElement() - { - return $this->show_all_element; - } - - /** - * Set hide all element - * - * @param string $a_val ID of hide all html element - */ - function setHideAllElement($a_val) - { - $this->hide_all_element = $a_val; - } - - /** - * Get hide all element - * - * @return string ID of hide all html element - */ - function getHideAllElement() - { - return $this->hide_all_element; - } - - /** - * Add javascript files that are necessary to run accordion - */ - static function addJavaScript(ilTemplate $main_tpl = null) - { - global $DIC; - - if ($main_tpl != null) - { - $tpl = $main_tpl; - } - else - { - $tpl = $DIC["tpl"]; - } - - include_once("./Services/YUI/classes/class.ilYuiUtil.php"); - ilYuiUtil::initConnection($tpl); - - include_once("./Services/jQuery/classes/class.iljQueryUtil.php"); - iljQueryUtil::initjQueryUI($tpl); - - foreach (self::getLocalJavascriptFiles() as $f) - { - $tpl->addJavaScript($f, true, 3); - } - } - - /** - * Add required css - */ - static function addCss() - { - global $DIC; - - $tpl = $DIC["tpl"]; - - foreach (self::getLocalCssFiles() as $f) - { - $tpl->addCss($f); - } - } - - /** - * @return array - */ - static function getLocalJavascriptFiles() - { - return array( - "./Services/Accordion/js/accordion.js", - self::$owl_path.self::$owl_js_path - ); - } - - /** - * @return array - */ - static function getLocalCssFiles() - { - return array( - "./Services/Accordion/css/accordion.css", - self::$owl_path.self::$owl_css_path - ); - } - - /** - * Add item - */ - function addItem($a_header, $a_content, $a_force_open = false) - { - $this->items[] = array("header" => $a_header, - "content" => $a_content, "force_open" => $a_force_open); - - if($a_force_open) - { - $this->force_open[] = sizeof($this->items); - } - } - - /** - * Get all items - */ - function getItems() - { - return $this->items; - } - - /** - * Get accordion html - */ - function getHTML() - { - $ilUser = $this->user; - - self::$accordion_cnt++; - - $or_short = ($this->getOrientation() == ilAccordionGUI::HORIZONTAL) - ? "H" - : "V"; - - $width = (int) $this->getContentWidth(); - $height = (int) $this->getContentHeight(); - if ($this->getOrientation() == ilAccordionGUI::HORIZONTAL) - { - if ($width == 0) - { - $width = 200; - } - if ($height == 0) - { - $height = 100; - } - } - - $this->addJavascript(); - $this->addCss(); - - $tpl = new ilTemplate("tpl.accordion.html", true, true, "Services/Accordion"); - foreach ($this->getItems() as $item) - { - $tpl->setCurrentBlock("item"); - $tpl->setVariable("HEADER", $item["header"]); - $tpl->setVariable("CONTENT", $item["content"]); - $tpl->setVariable("HEADER_CLASS", $this->getHeaderClass() - ? $this->getHeaderClass() : "il_".$or_short."AccordionHead"); - $tpl->setVariable("CONTENT_CLASS", $this->getContentClass() - ? $this->getContentClass() : "il_".$or_short."AccordionContent"); - - if ($this->getBehaviour() != self::FORCE_ALL_OPEN) - { - $tpl->setVariable("HIDE_CONTENT_CLASS", "ilAccHideContent"); - } - - $tpl->setVariable("OR_SHORT", $or_short); - - $tpl->setVariable("INNER_CONTAINER_CLASS", $this->getInnerContainerClass() - ? $this->getInnerContainerClass() : "il_".$or_short."AccordionInnerContainer"); - - - if ($height > 0) - { - $tpl->setVariable("HEIGHT", "height:".$height."px;"); - } - if ($height > 0 && $this->getOrientation() == ilAccordionGUI::HORIZONTAL) - { - $tpl->setVariable("HHEIGHT", "height:".$height."px;"); - } - $tpl->parseCurrentBlock(); - } - - $tpl->setVariable("CONTAINER_CLASS", $this->getContainerClass() - ? $this->getContainerClass() : "il_".$or_short."AccordionContainer"); - - $options["orientation"] = $this->getOrientation(); - $options["int_id"] = $this->getId(); - - if ($this->getUseSessionStorage() && $this->getId() != "") - { - include_once("./Services/Accordion/classes/class.ilAccordionPropertiesStorage.php"); - $stor = new ilAccordionPropertiesStorage(); - - $ctab = $stor->getProperty($this->getId(), $ilUser->getId(), - "opened"); - $ctab_arr = explode(";", $ctab); - - foreach ($this->force_open as $fo) - { - if (!in_array($fo, $ctab_arr)) - { - $ctab_arr[] = $fo; - } - } - $ctab = implode(";", $ctab_arr); - - if ($ctab == "0") { - $ctab = ""; - } - - $options["initial_opened"] = $ctab; - $options["save_url"] = "./ilias.php?baseClass=ilaccordionpropertiesstorage&cmd=setOpenedTab". - "&accordion_id=".$this->getId()."&user_id=".$ilUser->getId(); - } - - $options["behaviour"] = $this->getBehaviour(); - if ($this->getOrientation() == ilAccordionGUI::HORIZONTAL) - { - $options["toggle_class"] = 'il_HAccordionToggleDef'; - $options["toggle_act_class"] = 'il_HAccordionToggleActiveDef'; - $options["content_class"] = 'il_HAccordionContentDef'; - } - else - { - $options["toggle_class"] = 'il_VAccordionToggleDef'; - $options["toggle_act_class"] = 'il_VAccordionToggleActiveDef'; - $options["content_class"] = 'il_VAccordionContentDef'; - } - - - if ($width > 0) - { - $options["width"] = $width; - } - else - { - $options["width"] = null; - } - if ($width > 0 && $this->getOrientation() == ilAccordionGUI::VERTICAL) - { - $tpl->setVariable("CWIDTH", 'style="width:'.$width.'px;"'); - } - - if ($this->head_class_set) - { - $options["active_head_class"] = $this->getActiveHeaderClass(); - } - else - { - if ($this->getOrientation() == ilAccordionGUI::VERTICAL) - { - $options["active_head_class"] = "il_HAccordionHeadActive"; - } - else - { - $options["active_head_class"] = "il_VAccordionHeadActive"; - } - } - - $options["height"] = null; - $options["id"] = 'accordion_'.$this->getId().'_'.self::$accordion_cnt; - $options["multi"] = (bool) $this->getAllowMultiOpened(); - $options["show_all_element"] = $this->getShowAllElement(); - $options["hide_all_element"] = $this->getHideAllElement(); - - include_once("./Services/JSON/classes/class.ilJsonUtil.php"); - $tpl->setVariable("OPTIONS", $str = ilJsonUtil::encode($options)); - $tpl->setVariable("ACC_ID", $options["id"]); -//echo "





".$str; - return $tpl->get(); - } - + /** + * @var ilObjUser + */ + protected $user; + + protected $items = array(); + protected $force_open = array(); + protected static $accordion_cnt = 0; + protected $use_session_storage = false; + protected $allow_multi_opened = false; + protected $show_all_element = null; + protected $hide_all_element = null; + + const VERTICAL = "vertical"; + const HORIZONTAL = "horizontal"; + const FORCE_ALL_OPEN = "ForceAllOpen"; + const FIRST_OPEN = "FirstOpen"; + const ALL_CLOSED = "AllClosed"; + + public static $owl_path = "./libs/bower/bower_components/owl.carousel/dist"; + public static $owl_js_path = "/owl.carousel.js"; + public static $owl_css_path = "/assets/owl.carousel.css"; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->user = $DIC->user(); + $this->setOrientation(ilAccordionGUI::VERTICAL); + } + + /** + * Set id + * + * @param string id + */ + public function setId($a_val) + { + $this->id = $a_val; + } + + /** + * Get id + * + * @return string id + */ + public function getId() + { + return $this->id; + } + + /** + * Set Orientation. + * + * @param string $a_orientation Orientation + */ + public function setOrientation($a_orientation) + { + if (in_array( + $a_orientation, + array(ilAccordionGUI::VERTICAL, ilAccordionGUI::HORIZONTAL) + )) { + $this->orientation = $a_orientation; + } + } + + /** + * Get Orientation. + * + * @return string Orientation + */ + public function getOrientation() + { + return $this->orientation; + } + + /** + * Set Container CSS Class. + * + * @param string $a_containerclass Container CSS Class + */ + public function setContainerClass($a_containerclass) + { + $this->containerclass = $a_containerclass; + } + + /** + * Get Container CSS Class. + * + * @return string Container CSS Class + */ + public function getContainerClass() + { + return $this->containerclass; + } + + /** + * Set inner Container CSS Class. + * + * @param string $a_containerclass Container CSS Class + */ + public function setInnerContainerClass($a_containerclass) + { + $this->icontainerclass = $a_containerclass; + } + + /** + * Get inner Container CSS Class. + * + * @return string Container CSS Class + */ + public function getInnerContainerClass() + { + return $this->icontainerclass; + } + + /** + * Set Header CSS Class. + * + * @param string $a_headerclass Header CSS Class + */ + public function setHeaderClass($a_headerclass) + { + $this->headerclass = $a_headerclass; + } + + /** + * Get Header CSS Class. + * + * @return string Header CSS Class + */ + public function getHeaderClass() + { + return $this->headerclass; + } + + /** + * Set active header class + * + * @param string $a_h_class Active Header CSS Class + */ + public function setActiveHeaderClass($a_h_class) + { + $this->active_headerclass = $a_h_class; + } + + /** + * Get active Header CSS Class. + * + * @return string Active header CSS Class + */ + public function getActiveHeaderClass() + { + return $this->active_headerclass; + } + + /** + * Set Content CSS Class. + * + * @param string $a_contentclass Content CSS Class + */ + public function setContentClass($a_contentclass) + { + $this->contentclass = $a_contentclass; + } + + /** + * Get Content CSS Class. + * + * @return string Content CSS Class + */ + public function getContentClass() + { + return $this->contentclass; + } + + /** + * Set ContentWidth. + * + * @param integer $a_contentwidth ContentWidth + */ + public function setContentWidth($a_contentwidth) + { + $this->contentwidth = $a_contentwidth; + } + + /** + * Get ContentWidth. + * + * @return integer ContentWidth + */ + public function getContentWidth() + { + return $this->contentwidth; + } + + /** + * Set ContentHeight. + * + * @param integer $a_contentheight ContentHeight + */ + public function setContentHeight($a_contentheight) + { + $this->contentheight = $a_contentheight; + } + + /** + * Get ContentHeight. + * + * @return integer ContentHeight + */ + public function getContentHeight() + { + return $this->contentheight; + } + + /** + * Set behaviour "ForceAllOpen" | "FirstOpen" | "AllClosed" + * + * @param string behaviour + */ + public function setBehaviour($a_val) + { + $this->behaviour = $a_val; + } + + /** + * Get behaviour + * + * @return + */ + public function getBehaviour() + { + return $this->behaviour; + } + + /** + * Set use session storage + * + * @param bool $a_val use session storage + */ + public function setUseSessionStorage($a_val) + { + $this->use_session_storage = $a_val; + } + + /** + * Get use session storage + * + * @return bool use session storage + */ + public function getUseSessionStorage() + { + return $this->use_session_storage; + } + + /** + * Set allow multi opened + * + * @param bool $a_val allow multiple accordions being opened + */ + public function setAllowMultiOpened($a_val) + { + $this->allow_multi_opened = $a_val; + } + + /** + * Get allow multi opened + * + * @return bool allow multiple accordions being opened + */ + public function getAllowMultiOpened() + { + return $this->allow_multi_opened; + } + + /** + * Set show all element + * + * @param string $a_val ID of show all html element + */ + public function setShowAllElement($a_val) + { + $this->show_all_element = $a_val; + } + + /** + * Get show all element + * + * @return string ID of show all html element + */ + public function getShowAllElement() + { + return $this->show_all_element; + } + + /** + * Set hide all element + * + * @param string $a_val ID of hide all html element + */ + public function setHideAllElement($a_val) + { + $this->hide_all_element = $a_val; + } + + /** + * Get hide all element + * + * @return string ID of hide all html element + */ + public function getHideAllElement() + { + return $this->hide_all_element; + } + + /** + * Add javascript files that are necessary to run accordion + */ + public static function addJavaScript(ilTemplate $main_tpl = null) + { + global $DIC; + + if ($main_tpl != null) { + $tpl = $main_tpl; + } else { + $tpl = $DIC["tpl"]; + } + + include_once("./Services/YUI/classes/class.ilYuiUtil.php"); + ilYuiUtil::initConnection($tpl); + + include_once("./Services/jQuery/classes/class.iljQueryUtil.php"); + iljQueryUtil::initjQueryUI($tpl); + + foreach (self::getLocalJavascriptFiles() as $f) { + $tpl->addJavaScript($f, true, 3); + } + } + + /** + * Add required css + */ + public static function addCss() + { + global $DIC; + + $tpl = $DIC["tpl"]; + + foreach (self::getLocalCssFiles() as $f) { + $tpl->addCss($f); + } + } + + /** + * @return array + */ + public static function getLocalJavascriptFiles() + { + return array( + "./Services/Accordion/js/accordion.js", + self::$owl_path . self::$owl_js_path + ); + } + + /** + * @return array + */ + public static function getLocalCssFiles() + { + return array( + "./Services/Accordion/css/accordion.css", + self::$owl_path . self::$owl_css_path + ); + } + + /** + * Add item + */ + public function addItem($a_header, $a_content, $a_force_open = false) + { + $this->items[] = array("header" => $a_header, + "content" => $a_content, "force_open" => $a_force_open); + + if ($a_force_open) { + $this->force_open[] = sizeof($this->items); + } + } + + /** + * Get all items + */ + public function getItems() + { + return $this->items; + } + + /** + * Get accordion html + */ + public function getHTML() + { + $ilUser = $this->user; + + self::$accordion_cnt++; + + $or_short = ($this->getOrientation() == ilAccordionGUI::HORIZONTAL) + ? "H" + : "V"; + + $width = (int) $this->getContentWidth(); + $height = (int) $this->getContentHeight(); + if ($this->getOrientation() == ilAccordionGUI::HORIZONTAL) { + if ($width == 0) { + $width = 200; + } + if ($height == 0) { + $height = 100; + } + } + + $this->addJavascript(); + $this->addCss(); + + $tpl = new ilTemplate("tpl.accordion.html", true, true, "Services/Accordion"); + foreach ($this->getItems() as $item) { + $tpl->setCurrentBlock("item"); + $tpl->setVariable("HEADER", $item["header"]); + $tpl->setVariable("CONTENT", $item["content"]); + $tpl->setVariable("HEADER_CLASS", $this->getHeaderClass() + ? $this->getHeaderClass() : "il_" . $or_short . "AccordionHead"); + $tpl->setVariable("CONTENT_CLASS", $this->getContentClass() + ? $this->getContentClass() : "il_" . $or_short . "AccordionContent"); + + if ($this->getBehaviour() != self::FORCE_ALL_OPEN) { + $tpl->setVariable("HIDE_CONTENT_CLASS", "ilAccHideContent"); + } + + $tpl->setVariable("OR_SHORT", $or_short); + + $tpl->setVariable("INNER_CONTAINER_CLASS", $this->getInnerContainerClass() + ? $this->getInnerContainerClass() : "il_" . $or_short . "AccordionInnerContainer"); + + + if ($height > 0) { + $tpl->setVariable("HEIGHT", "height:" . $height . "px;"); + } + if ($height > 0 && $this->getOrientation() == ilAccordionGUI::HORIZONTAL) { + $tpl->setVariable("HHEIGHT", "height:" . $height . "px;"); + } + $tpl->parseCurrentBlock(); + } + + $tpl->setVariable("CONTAINER_CLASS", $this->getContainerClass() + ? $this->getContainerClass() : "il_" . $or_short . "AccordionContainer"); + + $options["orientation"] = $this->getOrientation(); + $options["int_id"] = $this->getId(); + + if ($this->getUseSessionStorage() && $this->getId() != "") { + include_once("./Services/Accordion/classes/class.ilAccordionPropertiesStorage.php"); + $stor = new ilAccordionPropertiesStorage(); + + $ctab = $stor->getProperty( + $this->getId(), + $ilUser->getId(), + "opened" + ); + $ctab_arr = explode(";", $ctab); + + foreach ($this->force_open as $fo) { + if (!in_array($fo, $ctab_arr)) { + $ctab_arr[] = $fo; + } + } + $ctab = implode(";", $ctab_arr); + + if ($ctab == "0") { + $ctab = ""; + } + + $options["initial_opened"] = $ctab; + $options["save_url"] = "./ilias.php?baseClass=ilaccordionpropertiesstorage&cmd=setOpenedTab" . + "&accordion_id=" . $this->getId() . "&user_id=" . $ilUser->getId(); + } + + $options["behaviour"] = $this->getBehaviour(); + if ($this->getOrientation() == ilAccordionGUI::HORIZONTAL) { + $options["toggle_class"] = 'il_HAccordionToggleDef'; + $options["toggle_act_class"] = 'il_HAccordionToggleActiveDef'; + $options["content_class"] = 'il_HAccordionContentDef'; + } else { + $options["toggle_class"] = 'il_VAccordionToggleDef'; + $options["toggle_act_class"] = 'il_VAccordionToggleActiveDef'; + $options["content_class"] = 'il_VAccordionContentDef'; + } + + + if ($width > 0) { + $options["width"] = $width; + } else { + $options["width"] = null; + } + if ($width > 0 && $this->getOrientation() == ilAccordionGUI::VERTICAL) { + $tpl->setVariable("CWIDTH", 'style="width:' . $width . 'px;"'); + } + + if ($this->head_class_set) { + $options["active_head_class"] = $this->getActiveHeaderClass(); + } else { + if ($this->getOrientation() == ilAccordionGUI::VERTICAL) { + $options["active_head_class"] = "il_HAccordionHeadActive"; + } else { + $options["active_head_class"] = "il_VAccordionHeadActive"; + } + } + + $options["height"] = null; + $options["id"] = 'accordion_' . $this->getId() . '_' . self::$accordion_cnt; + $options["multi"] = (bool) $this->getAllowMultiOpened(); + $options["show_all_element"] = $this->getShowAllElement(); + $options["hide_all_element"] = $this->getHideAllElement(); + + include_once("./Services/JSON/classes/class.ilJsonUtil.php"); + $tpl->setVariable("OPTIONS", $str = ilJsonUtil::encode($options)); + $tpl->setVariable("ACC_ID", $options["id"]); + //echo "





".$str; + return $tpl->get(); + } } -?> diff --git a/Services/Accordion/classes/class.ilAccordionPropertiesStorage.php b/Services/Accordion/classes/class.ilAccordionPropertiesStorage.php index d247e4ed6dd7930407719868c4ff8cbc70f36537..df88317b340bf58dacdf1c119154211cbf0e64c6 100644 --- a/Services/Accordion/classes/class.ilAccordionPropertiesStorage.php +++ b/Services/Accordion/classes/class.ilAccordionPropertiesStorage.php @@ -3,7 +3,7 @@ /** * Saves (mostly asynchronously) user properties of accordions -* +* * @author Alex Killing * @version $Id$ * @ingroup ServicesAccordion @@ -11,158 +11,175 @@ */ class ilAccordionPropertiesStorage { - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; - /** - * Constructor - */ - function __construct() - { - global $DIC; + /** + * Constructor + */ + public function __construct() + { + global $DIC; - $this->user = $DIC->user(); - $this->ctrl = $DIC->ctrl(); - $this->db = $DIC->database(); - } + $this->user = $DIC->user(); + $this->ctrl = $DIC->ctrl(); + $this->db = $DIC->database(); + } - var $properties = array ( - "opened" => array("storage" => "session") - ); - - /** - * execute command - */ - function &executeCommand() - { - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - - $cmd = $ilCtrl->getCmd(); -// $next_class = $this->ctrl->getNextClass($this); + public $properties = array( + "opened" => array("storage" => "session") + ); + + /** + * execute command + */ + public function &executeCommand() + { + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + + $cmd = $ilCtrl->getCmd(); + // $next_class = $this->ctrl->getNextClass($this); - $this->$cmd(); - } - - /** - * Show Filter - */ - function setOpenedTab() - { - $ilUser = $this->user; - - if ($_GET["user_id"] == $ilUser->getId()) - { - switch ($_GET["act"]) - { + $this->$cmd(); + } + + /** + * Show Filter + */ + public function setOpenedTab() + { + $ilUser = $this->user; + + if ($_GET["user_id"] == $ilUser->getId()) { + switch ($_GET["act"]) { - case "add": - $cur = $this->getProperty($_GET["accordion_id"], (int) $_GET["user_id"], - "opened"); - $cur_arr = explode(";", $cur); - if (!in_array((int) $_GET["tab_nr"], $cur_arr)) - { - $cur_arr[] = (int) $_GET["tab_nr"]; - } - $this->storeProperty($_GET["accordion_id"], (int) $_GET["user_id"], - "opened", implode($cur_arr, ";")); - break; + case "add": + $cur = $this->getProperty( + $_GET["accordion_id"], + (int) $_GET["user_id"], + "opened" + ); + $cur_arr = explode(";", $cur); + if (!in_array((int) $_GET["tab_nr"], $cur_arr)) { + $cur_arr[] = (int) $_GET["tab_nr"]; + } + $this->storeProperty( + $_GET["accordion_id"], + (int) $_GET["user_id"], + "opened", + implode($cur_arr, ";") + ); + break; - case "rem": - $cur = $this->getProperty($_GET["accordion_id"], (int) $_GET["user_id"], - "opened"); - $cur_arr = explode(";", $cur); - if(($key = array_search((int) $_GET["tab_nr"], $cur_arr)) !== false) { - unset($cur_arr[$key]); - } - $this->storeProperty($_GET["accordion_id"], (int) $_GET["user_id"], - "opened", implode($cur_arr, ";")); - break; + case "rem": + $cur = $this->getProperty( + $_GET["accordion_id"], + (int) $_GET["user_id"], + "opened" + ); + $cur_arr = explode(";", $cur); + if (($key = array_search((int) $_GET["tab_nr"], $cur_arr)) !== false) { + unset($cur_arr[$key]); + } + $this->storeProperty( + $_GET["accordion_id"], + (int) $_GET["user_id"], + "opened", + implode($cur_arr, ";") + ); + break; - case "clear": - $this->storeProperty($_GET["accordion_id"], (int) $_GET["user_id"], - "opened", ""); - break; + case "clear": + $this->storeProperty( + $_GET["accordion_id"], + (int) $_GET["user_id"], + "opened", + "" + ); + break; - case "set": - default: - $this->storeProperty($_GET["accordion_id"], (int) $_GET["user_id"], - "opened", $_GET["tab_nr"]); - break; - } - } - } - - /** - * Store property in session or db - */ - function storeProperty($a_table_id, $a_user_id, $a_property, - $a_value) - { - $ilDB = $this->db; + case "set": + default: + $this->storeProperty( + $_GET["accordion_id"], + (int) $_GET["user_id"], + "opened", + $_GET["tab_nr"] + ); + break; + } + } + } + + /** + * Store property in session or db + */ + public function storeProperty( + $a_table_id, + $a_user_id, + $a_property, + $a_value + ) { + $ilDB = $this->db; - switch ($this->properties[$a_property]["storage"]) - { - case "session": - $_SESSION["accordion"][$a_table_id][$a_user_id][$a_property] - = $a_value; - break; - - case "db": + switch ($this->properties[$a_property]["storage"]) { + case "session": + $_SESSION["accordion"][$a_table_id][$a_user_id][$a_property] + = $a_value; + break; + + case "db": /* - $ilDB->replace("table_properties", array( - "table_id" => array("text", $a_table_id), - "user_id" => array("integer", $a_user_id), - "property" => array("text", $a_property)), - array( - "value" => array("text", $a_value) - )); + $ilDB->replace("table_properties", array( + "table_id" => array("text", $a_table_id), + "user_id" => array("integer", $a_user_id), + "property" => array("text", $a_property)), + array( + "value" => array("text", $a_value) + )); */ - } - } - - /** - * Get property in session or db - */ - function getProperty($a_table_id, $a_user_id, $a_property) - { - $ilDB = $this->db; + } + } + + /** + * Get property in session or db + */ + public function getProperty($a_table_id, $a_user_id, $a_property) + { + $ilDB = $this->db; - switch ($this->properties[$a_property]["storage"]) - { - case "session": - $r = $_SESSION["accordion"][$a_table_id][$a_user_id][$a_property]; + switch ($this->properties[$a_property]["storage"]) { + case "session": + $r = $_SESSION["accordion"][$a_table_id][$a_user_id][$a_property]; //echo "







get-".$r; - return $r; - break; - - case "db": + return $r; + break; + + case "db": /* - $set = $ilDB->query("SELECT value FROM table_properties ". - " WHERE table_id = ".$ilDB->quote($a_table_id, "text"). - " AND user_id = ".$ilDB->quote($a_user_id, "integer"). - " AND property = ".$ilDB->quote($a_property, "text") - ); - $rec = $ilDB->fetchAssoc($set); - return $rec["value"]; - break; + $set = $ilDB->query("SELECT value FROM table_properties ". + " WHERE table_id = ".$ilDB->quote($a_table_id, "text"). + " AND user_id = ".$ilDB->quote($a_user_id, "integer"). + " AND property = ".$ilDB->quote($a_property, "text") + ); + $rec = $ilDB->fetchAssoc($set); + return $rec["value"]; + break; */ - } - } - - + } + } } -?> diff --git a/Services/Administration/classes/class.ilAdmGlobalScreenProvider.php b/Services/Administration/classes/class.ilAdmGlobalScreenProvider.php index 462f2cda73c355e29b15a3c716cfbe4b0de2f21e..b028908d7b800be977f79db3effeaf734b4402ab 100644 --- a/Services/Administration/classes/class.ilAdmGlobalScreenProvider.php +++ b/Services/Administration/classes/class.ilAdmGlobalScreenProvider.php @@ -8,70 +8,77 @@ use ILIAS\GlobalScreen\Scope\MainMenu\Provider\AbstractStaticMainMenuProvider; * * @author Fabian Schmid */ -class ilAdmGlobalScreenProvider extends AbstractStaticMainMenuProvider { +class ilAdmGlobalScreenProvider extends AbstractStaticMainMenuProvider +{ - /** - * @var IdentificationInterface - */ - protected $top_item; + /** + * @var IdentificationInterface + */ + protected $top_item; - public function __construct(\ILIAS\DI\Container $dic) { - parent::__construct($dic); - $this->top_item = $this->if->identifier('adm'); - } + public function __construct(\ILIAS\DI\Container $dic) + { + parent::__construct($dic); + $this->top_item = $this->if->identifier('adm'); + } - /** - * Some other components want to provide Items for the main menu which are - * located at the PD TopTitem by default. Therefore we have to provide our - * TopTitem Identification for others - * - * @return IdentificationInterface - */ - public function getTopItem(): IdentificationInterface { - return $this->top_item; - } + /** + * Some other components want to provide Items for the main menu which are + * located at the PD TopTitem by default. Therefore we have to provide our + * TopTitem Identification for others + * + * @return IdentificationInterface + */ + public function getTopItem() : IdentificationInterface + { + return $this->top_item; + } - /** - * @inheritDoc - */ - public function getStaticTopItems(): array { - $dic = $this->dic; + /** + * @inheritDoc + */ + public function getStaticTopItems() : array + { + $dic = $this->dic; - return [$this->mainmenu->topParentItem($this->getTopItem()) - ->withTitle($this->dic->language()->txt("administration")) - ->withPosition(3) - ->withVisibilityCallable( - function () use ($dic) { return (bool)($dic->access()->checkAccess('visible', '', SYSTEM_FOLDER_ID)); } - )]; - } + return [$this->mainmenu->topParentItem($this->getTopItem()) + ->withTitle($this->dic->language()->txt("administration")) + ->withPosition(3) + ->withVisibilityCallable( + function () use ($dic) { + return (bool) ($dic->access()->checkAccess('visible', '', SYSTEM_FOLDER_ID)); + } + )]; + } - /** - * @inheritDoc - */ - public function getStaticSubItems(): array { - $dic = $this->dic; + /** + * @inheritDoc + */ + public function getStaticSubItems() : array + { + $dic = $this->dic; - $entries[] = $this->globalScreen() - ->mainmenu() - ->complex($this->if->identifier('adm_content')) - ->withAsyncContentURL("ilias.php?baseClass=ilAdministrationGUI&cmd=getDropDown&cmdMode=asynch") - ->withParent($this->getTopItem()) - ->withAlwaysAvailable(true) - ->withNonAvailableReason($this->dic->ui()->factory()->legacy("{$this->dic->language()->txt('item_must_be_always_active')}")) - ->withVisibilityCallable( - function () use ($dic) { - return (bool)($dic->rbac()->system()->checkAccess("visible", SYSTEM_FOLDER_ID)); - } - )->withAvailableCallable( - function () use ($dic) { - return ($dic->user()->getId() != ANONYMOUS_USER_ID); - } - ); + $entries[] = $this->globalScreen() + ->mainmenu() + ->complex($this->if->identifier('adm_content')) + ->withAsyncContentURL("ilias.php?baseClass=ilAdministrationGUI&cmd=getDropDown&cmdMode=asynch") + ->withParent($this->getTopItem()) + ->withAlwaysAvailable(true) + ->withNonAvailableReason($this->dic->ui()->factory()->legacy("{$this->dic->language()->txt('item_must_be_always_active')}")) + ->withVisibilityCallable( + function () use ($dic) { + return (bool) ($dic->rbac()->system()->checkAccess("visible", SYSTEM_FOLDER_ID)); + } + )->withAvailableCallable( + function () use ($dic) { + return ($dic->user()->getId() != ANONYMOUS_USER_ID); + } + ); - return $entries; - } + return $entries; + } } diff --git a/Services/Administration/classes/class.ilAdministrationCommandGUI.php b/Services/Administration/classes/class.ilAdministrationCommandGUI.php index 53c38a4b81dacd26b7a79310141ced9725fdbe8b..0457b091a82b493c6e9331436e114e5886e8d289 100644 --- a/Services/Administration/classes/class.ilAdministrationCommandGUI.php +++ b/Services/Administration/classes/class.ilAdministrationCommandGUI.php @@ -1,290 +1,283 @@ * @version $Id$ -* +* * * @ingroup ServicesAdministration */ -class ilAdministrationCommandGUI +class ilAdministrationCommandGUI { - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilSetting - */ - protected $settings; - - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * @var ilTree - */ - protected $tree; - - /** - * @var ilObjectDefinition - */ - protected $obj_definition; - - protected $ctrl = null; - protected $lng = null; - private $container = null; - - /** - * Constructor - */ - public function __construct($a_container) - { - global $DIC; - - $this->tpl = $DIC["tpl"]; - $this->settings = $DIC->settings(); - $this->error = $DIC["ilErr"]; - $this->tree = $DIC->repositoryTree(); - $this->obj_definition = $DIC["objDefinition"]; - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->container = $a_container; - $this->ctrl = $ilCtrl; - $this->lng = $lng; - } - - /** - * Get container object - */ - public function getContainer() - { - return $this->container; - } - - /** - * Show delete confirmation - */ - public function delete() - { - $tpl = $this->tpl; - $ilSetting = $this->settings; - $ilErr = $this->error; - - $this->ctrl->setReturnByClass(get_class($this->getContainer()), ''); - - $to_delete = array (); - if ((int) $_GET['item_ref_id']) - { - $to_delete = array ( - (int) $_GET['item_ref_id'] - ); - } - - if (isset ($_POST['id']) and is_array($_POST['id'])) - { - $to_delete = $_POST['id']; - } - - if(!$to_delete) - { - $ilErr->raiseError($this->lng->txt('no_checkbox'),$ilErr->MESSAGE); - } - - include_once ('./Services/Utilities/classes/class.ilConfirmationGUI.php'); - $confirm = new ilConfirmationGUI(); - $confirm->setFormAction($this->ctrl->getFormActionByClass(get_class($this->getContainer()), 'cancel')); - $confirm->setHeaderText(''); - $confirm->setCancel($this->lng->txt('cancel'), 'cancelDelete'); - $confirm->setConfirm($this->lng->txt('delete'), 'performDelete'); - - foreach ($to_delete as $delete) - { - $obj_id = ilObject :: _lookupObjId($delete); - $type = ilObject :: _lookupType($obj_id); - - $confirm->addItem( - 'id[]', - $delete, - call_user_func(array(ilObjectFactory::getClassByType($type),'_lookupTitle'),$obj_id), - ilUtil :: getTypeIconPath($type, $obj_id) - ); - } - - $msg = $this->lng->txt("info_delete_sure"); - - if(!$ilSetting->get('enable_trash')) - { - $msg .= "
".$this->lng->txt("info_delete_warning_no_trash"); - } - ilUtil::sendQuestion($msg); - - $tpl->setContent($confirm->getHTML()); - } - - /** - * Perform delete - */ - public function performDelete() - { - $this->ctrl->setReturnByClass(get_class($this->getContainer()), ''); - - include_once './Services/Object/classes/class.ilObjectGUI.php'; - $_SESSION['saved_post'] = $_POST['id']; - $object = new ilObjectGUI(array (), 0, false, false); - $object->confirmedDeleteObject(); - return true; - } - - /** - * Cut object - */ - public function cut() - { - $tree = $this->tree; - - $this->ctrl->setReturnByClass(get_class($this->getContainer()), ''); - - $_GET['ref_id'] = $tree->getParentId((int) $_GET['item_ref_id']); - - include_once './Services/Container/classes/class.ilContainerGUI.php'; - $container = new ilContainerGUI(array (), 0, false, false); - $container->cutObject(); - return true; - } - - /** - * Show target selection - * @return - */ - public function showMoveIntoObjectTree() - { - $objDefinition = $this->obj_definition; - - $this->ctrl->setReturnByClass(get_class($this->getContainer()), ''); - - $obj_id = ilObject :: _lookupObjId((int) $_GET['ref_id']); - $type = ilObject :: _lookupType($obj_id); - - $location = $objDefinition->getLocation($type); - $class_name = "ilObj" . $objDefinition->getClassName($type) . 'GUI'; - - // create instance - include_once ($location . "/class." . $class_name . ".php"); - $container = new $class_name (array (), (int) $_GET['ref_id'], true, false); - $container->showMoveIntoObjectTreeObject(); - return true; - - } - - /** - * Target selection - * @return - */ - public function showLinkIntoMultipleObjectsTree() - { - $objDefinition = $this->obj_definition; - - $this->ctrl->setReturnByClass(get_class($this->getContainer()), ''); - - $obj_id = ilObject :: _lookupObjId((int) $_GET['ref_id']); - $type = ilObject :: _lookupType($obj_id); - - $location = $objDefinition->getLocation($type); - $class_name = "ilObj" . $objDefinition->getClassName($type) . 'GUI'; - - // create instance - include_once ($location . "/class." . $class_name . ".php"); - $container = new $class_name (array (), (int) $_GET['ref_id'], true, false); - $container->showLinkIntoMultipleObjectsTreeObject(); - return true; - } - - /** - * Start linking object - */ - public function link() - { - $tree = $this->tree; - - $this->ctrl->setReturnByClass(get_class($this->getContainer()), ''); - - $_GET['ref_id'] = $tree->getParentId((int) $_GET['item_ref_id']); - - include_once './Services/Container/classes/class.ilContainerGUI.php'; - $container = new ilContainerGUI(array (), 0, false, false); - $container->linkObject(); - return true; - } - - /** - * Paste object - */ - public function paste() - { - $objDefinition = $this->obj_definition; - - $this->ctrl->setReturnByClass(get_class($this->getContainer()), ''); - $_GET['ref_id'] = (int) $_GET['item_ref_id']; - - $obj_id = ilObject :: _lookupObjId((int) $_GET['item_ref_id']); - $type = ilObject :: _lookupType($obj_id); - - $location = $objDefinition->getLocation($type); - $class_name = "ilObj" . $objDefinition->getClassName($type) . 'GUI'; - - // create instance - include_once ($location . "/class." . $class_name . ".php"); - $container = new $class_name (array (), (int) $_GET['item_ref_id'], true, false); - $container->pasteObject(); - return true; - } - - public function performPasteIntoMultipleObjects() - { - $objDefinition = $this->obj_definition; - - $this->ctrl->setReturnByClass(get_class($this->getContainer()), ''); - - $obj_id = ilObject :: _lookupObjId((int) $_GET['ref_id']); - $type = ilObject :: _lookupType($obj_id); - - $location = $objDefinition->getLocation($type); - $class_name = "ilObj" . $objDefinition->getClassName($type) . 'GUI'; - - // create instance - include_once ($location . "/class." . $class_name . ".php"); - $container = new $class_name (array (), (int) $_GET['ref_id'], true, false); - $container->performPasteIntoMultipleObjectsObject(); - return true; - } + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilTree + */ + protected $tree; + + /** + * @var ilObjectDefinition + */ + protected $obj_definition; + + protected $ctrl = null; + protected $lng = null; + private $container = null; + + /** + * Constructor + */ + public function __construct($a_container) + { + global $DIC; + + $this->tpl = $DIC["tpl"]; + $this->settings = $DIC->settings(); + $this->error = $DIC["ilErr"]; + $this->tree = $DIC->repositoryTree(); + $this->obj_definition = $DIC["objDefinition"]; + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->container = $a_container; + $this->ctrl = $ilCtrl; + $this->lng = $lng; + } + + /** + * Get container object + */ + public function getContainer() + { + return $this->container; + } + + /** + * Show delete confirmation + */ + public function delete() + { + $tpl = $this->tpl; + $ilSetting = $this->settings; + $ilErr = $this->error; + + $this->ctrl->setReturnByClass(get_class($this->getContainer()), ''); + + $to_delete = array(); + if ((int) $_GET['item_ref_id']) { + $to_delete = array( + (int) $_GET['item_ref_id'] + ); + } + + if (isset($_POST['id']) and is_array($_POST['id'])) { + $to_delete = $_POST['id']; + } + + if (!$to_delete) { + $ilErr->raiseError($this->lng->txt('no_checkbox'), $ilErr->MESSAGE); + } + + include_once('./Services/Utilities/classes/class.ilConfirmationGUI.php'); + $confirm = new ilConfirmationGUI(); + $confirm->setFormAction($this->ctrl->getFormActionByClass(get_class($this->getContainer()), 'cancel')); + $confirm->setHeaderText(''); + $confirm->setCancel($this->lng->txt('cancel'), 'cancelDelete'); + $confirm->setConfirm($this->lng->txt('delete'), 'performDelete'); + + foreach ($to_delete as $delete) { + $obj_id = ilObject :: _lookupObjId($delete); + $type = ilObject :: _lookupType($obj_id); + + $confirm->addItem( + 'id[]', + $delete, + call_user_func(array(ilObjectFactory::getClassByType($type),'_lookupTitle'), $obj_id), + ilUtil :: getTypeIconPath($type, $obj_id) + ); + } + + $msg = $this->lng->txt("info_delete_sure"); + + if (!$ilSetting->get('enable_trash')) { + $msg .= "
" . $this->lng->txt("info_delete_warning_no_trash"); + } + ilUtil::sendQuestion($msg); + + $tpl->setContent($confirm->getHTML()); + } + + /** + * Perform delete + */ + public function performDelete() + { + $this->ctrl->setReturnByClass(get_class($this->getContainer()), ''); + + include_once './Services/Object/classes/class.ilObjectGUI.php'; + $_SESSION['saved_post'] = $_POST['id']; + $object = new ilObjectGUI(array(), 0, false, false); + $object->confirmedDeleteObject(); + return true; + } + + /** + * Cut object + */ + public function cut() + { + $tree = $this->tree; + + $this->ctrl->setReturnByClass(get_class($this->getContainer()), ''); + + $_GET['ref_id'] = $tree->getParentId((int) $_GET['item_ref_id']); + + include_once './Services/Container/classes/class.ilContainerGUI.php'; + $container = new ilContainerGUI(array(), 0, false, false); + $container->cutObject(); + return true; + } + + /** + * Show target selection + * @return + */ + public function showMoveIntoObjectTree() + { + $objDefinition = $this->obj_definition; + + $this->ctrl->setReturnByClass(get_class($this->getContainer()), ''); + + $obj_id = ilObject :: _lookupObjId((int) $_GET['ref_id']); + $type = ilObject :: _lookupType($obj_id); + + $location = $objDefinition->getLocation($type); + $class_name = "ilObj" . $objDefinition->getClassName($type) . 'GUI'; + + // create instance + include_once($location . "/class." . $class_name . ".php"); + $container = new $class_name(array(), (int) $_GET['ref_id'], true, false); + $container->showMoveIntoObjectTreeObject(); + return true; + } + + /** + * Target selection + * @return + */ + public function showLinkIntoMultipleObjectsTree() + { + $objDefinition = $this->obj_definition; + + $this->ctrl->setReturnByClass(get_class($this->getContainer()), ''); + + $obj_id = ilObject :: _lookupObjId((int) $_GET['ref_id']); + $type = ilObject :: _lookupType($obj_id); + + $location = $objDefinition->getLocation($type); + $class_name = "ilObj" . $objDefinition->getClassName($type) . 'GUI'; + + // create instance + include_once($location . "/class." . $class_name . ".php"); + $container = new $class_name(array(), (int) $_GET['ref_id'], true, false); + $container->showLinkIntoMultipleObjectsTreeObject(); + return true; + } + + /** + * Start linking object + */ + public function link() + { + $tree = $this->tree; + + $this->ctrl->setReturnByClass(get_class($this->getContainer()), ''); + + $_GET['ref_id'] = $tree->getParentId((int) $_GET['item_ref_id']); + + include_once './Services/Container/classes/class.ilContainerGUI.php'; + $container = new ilContainerGUI(array(), 0, false, false); + $container->linkObject(); + return true; + } + + /** + * Paste object + */ + public function paste() + { + $objDefinition = $this->obj_definition; + + $this->ctrl->setReturnByClass(get_class($this->getContainer()), ''); + $_GET['ref_id'] = (int) $_GET['item_ref_id']; + + $obj_id = ilObject :: _lookupObjId((int) $_GET['item_ref_id']); + $type = ilObject :: _lookupType($obj_id); + + $location = $objDefinition->getLocation($type); + $class_name = "ilObj" . $objDefinition->getClassName($type) . 'GUI'; + + // create instance + include_once($location . "/class." . $class_name . ".php"); + $container = new $class_name(array(), (int) $_GET['item_ref_id'], true, false); + $container->pasteObject(); + return true; + } + + public function performPasteIntoMultipleObjects() + { + $objDefinition = $this->obj_definition; + + $this->ctrl->setReturnByClass(get_class($this->getContainer()), ''); + + $obj_id = ilObject :: _lookupObjId((int) $_GET['ref_id']); + $type = ilObject :: _lookupType($obj_id); + + $location = $objDefinition->getLocation($type); + $class_name = "ilObj" . $objDefinition->getClassName($type) . 'GUI'; + + // create instance + include_once($location . "/class." . $class_name . ".php"); + $container = new $class_name(array(), (int) $_GET['ref_id'], true, false); + $container->performPasteIntoMultipleObjectsObject(); + return true; + } } -?> diff --git a/Services/Administration/classes/class.ilAdministrationExplorerGUI.php b/Services/Administration/classes/class.ilAdministrationExplorerGUI.php index 02910fe57944337657cb8ccd34dbb2c6a71606f8..2cbd59f77adf96ad0bfe273c1af45b16b7fdf78c 100644 --- a/Services/Administration/classes/class.ilAdministrationExplorerGUI.php +++ b/Services/Administration/classes/class.ilAdministrationExplorerGUI.php @@ -15,309 +15,285 @@ include_once("./Services/UIComponent/Explorer2/classes/class.ilTreeExplorerGUI.p */ class ilAdministrationExplorerGUI extends ilTreeExplorerGUI { - /** - * @var ilSetting - */ - protected $settings; + /** + * @var ilSetting + */ + protected $settings; - /** - * @var ilObjectDefinition - */ - protected $obj_definition; + /** + * @var ilObjectDefinition + */ + protected $obj_definition; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilRbacSystem - */ - protected $rbacsystem; + /** + * @var ilRbacSystem + */ + protected $rbacsystem; - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - protected $type_grps = array(); - protected $session_materials = array(); - - /** - * Constructor - */ - public function __construct($a_parent_obj, $a_parent_cmd) - { - global $DIC; + protected $type_grps = array(); + protected $session_materials = array(); + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd) + { + global $DIC; - $this->tree = $DIC->repositoryTree(); - $this->settings = $DIC->settings(); - $this->obj_definition = $DIC["objDefinition"]; - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->db = $DIC->database(); - $this->user = $DIC->user(); - $this->access = $DIC->access(); - $tree = $DIC->repositoryTree(); - $ilSetting = $DIC->settings(); - $objDefinition = $DIC["objDefinition"]; + $this->tree = $DIC->repositoryTree(); + $this->settings = $DIC->settings(); + $this->obj_definition = $DIC["objDefinition"]; + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->db = $DIC->database(); + $this->user = $DIC->user(); + $this->access = $DIC->access(); + $tree = $DIC->repositoryTree(); + $ilSetting = $DIC->settings(); + $objDefinition = $DIC["objDefinition"]; - $this->cur_ref_id = (int) $_GET["ref_id"]; - - $this->top_node_id = 0; - parent::__construct("adm_exp", $a_parent_obj, $a_parent_cmd, $tree); + $this->cur_ref_id = (int) $_GET["ref_id"]; + + $this->top_node_id = 0; + parent::__construct("adm_exp", $a_parent_obj, $a_parent_cmd, $tree); - $this->setSkipRootNode(false); - $this->setAjax(true); - $this->setOrderField("title"); + $this->setSkipRootNode(false); + $this->setAjax(true); + $this->setOrderField("title"); - $white = array(); - foreach ($objDefinition->getSubObjectsRecursively("root") as $rtype) - { - if ($rtype["name"] != "itgr" && !$objDefinition->isSideBlock($rtype["name"])) - { - $white[] = $rtype["name"]; - } - } - $this->setTypeWhiteList($white); + $white = array(); + foreach ($objDefinition->getSubObjectsRecursively("root") as $rtype) { + if ($rtype["name"] != "itgr" && !$objDefinition->isSideBlock($rtype["name"])) { + $white[] = $rtype["name"]; + } + } + $this->setTypeWhiteList($white); - if ((int) $_GET["ref_id"] > 0) - { - $this->setPathOpen((int) $_GET["ref_id"]); - } - } + if ((int) $_GET["ref_id"] > 0) { + $this->setPathOpen((int) $_GET["ref_id"]); + } + } - /** - * Get node content - * - * @param array - * @return - */ - function getNodeContent($a_node) - { - $lng = $this->lng; - - $title = $a_node["title"]; - if ($a_node["child"] == $this->getNodeId($this->getRootNode())) - { - if ($title == "ILIAS") - { - $title = $lng->txt("repository"); - } - } + /** + * Get node content + * + * @param array + * @return + */ + public function getNodeContent($a_node) + { + $lng = $this->lng; + + $title = $a_node["title"]; + if ($a_node["child"] == $this->getNodeId($this->getRootNode())) { + if ($title == "ILIAS") { + $title = $lng->txt("repository"); + } + } - return $title; - } - - /** - * Get node icon - * - * @param array - * @return - */ - function getNodeIcon($a_node) - { - $obj_id = ilObject::_lookupObjId($a_node["child"]); - return ilObject::_getIcon($obj_id, "tiny", $a_node["type"]); - } + return $title; + } + + /** + * Get node icon + * + * @param array + * @return + */ + public function getNodeIcon($a_node) + { + $obj_id = ilObject::_lookupObjId($a_node["child"]); + return ilObject::_getIcon($obj_id, "tiny", $a_node["type"]); + } - /** - * Get node icon alt text - * - * @param array node array - * @return string alt text - */ - function getNodeIconAlt($a_node) - { - $lng = $this->lng; + /** + * Get node icon alt text + * + * @param array node array + * @return string alt text + */ + public function getNodeIconAlt($a_node) + { + $lng = $this->lng; - if ($a_node["child"] == $this->getNodeId($this->getRootNode())) - { - $title = $a_node["title"]; - if ($title == "ILIAS") - { - $title = $lng->txt("repository"); - } - return $lng->txt("icon")." ".$title; - } + if ($a_node["child"] == $this->getNodeId($this->getRootNode())) { + $title = $a_node["title"]; + if ($title == "ILIAS") { + $title = $lng->txt("repository"); + } + return $lng->txt("icon") . " " . $title; + } - - return parent::getNodeIconAlt($a_node); - } - - /** - * Is node highlighted? - * - * @param mixed $a_node node object/array - * @return boolean node visible true/false - */ - function isNodeHighlighted($a_node) - { - if ($a_node["child"] == $_GET["ref_id"] || - ($_GET["ref_id"] == "" && $a_node["child"] == $this->getNodeId($this->getRootNode()))) - { - return true; - } - return false; - } - - /** - * Get href for node - * - * @param mixed $a_node node object/array - * @return string href attribute - */ - function getNodeHref($a_node) - { - $ilCtrl = $this->ctrl; - $objDefinition = $this->obj_definition; - - $class_name = $objDefinition->getClassName($a_node["type"]); - $class = strtolower("ilObj".$class_name."GUI"); - $ilCtrl->setParameterByClass($class, "ref_id", $a_node["child"]); - $link = $ilCtrl->getLinkTargetByClass($class, "view"); - $ilCtrl->setParameterByClass($class, "ref_id", $_GET["ref_id"]); - - return $link; - } + + return parent::getNodeIconAlt($a_node); + } + + /** + * Is node highlighted? + * + * @param mixed $a_node node object/array + * @return boolean node visible true/false + */ + public function isNodeHighlighted($a_node) + { + if ($a_node["child"] == $_GET["ref_id"] || + ($_GET["ref_id"] == "" && $a_node["child"] == $this->getNodeId($this->getRootNode()))) { + return true; + } + return false; + } + + /** + * Get href for node + * + * @param mixed $a_node node object/array + * @return string href attribute + */ + public function getNodeHref($a_node) + { + $ilCtrl = $this->ctrl; + $objDefinition = $this->obj_definition; + + $class_name = $objDefinition->getClassName($a_node["type"]); + $class = strtolower("ilObj" . $class_name . "GUI"); + $ilCtrl->setParameterByClass($class, "ref_id", $a_node["child"]); + $link = $ilCtrl->getLinkTargetByClass($class, "view"); + $ilCtrl->setParameterByClass($class, "ref_id", $_GET["ref_id"]); + + return $link; + } - /** - * Is node visible - * - * @param - * @return - */ - function isNodeVisible($a_node) - { - $rbacsystem = $this->rbacsystem; + /** + * Is node visible + * + * @param + * @return + */ + public function isNodeVisible($a_node) + { + $rbacsystem = $this->rbacsystem; - $visible = $rbacsystem->checkAccess('visible', $a_node["child"]); - if ($a_node["type"] == "rolf" && $a_node["child"] != ROLE_FOLDER_ID) - { - return false; - } - return $visible; - } - - /** - * Sort childs - * - * @param array $a_childs array of child nodes - * @param mixed $a_parent_node parent node - * - * @return array array of childs nodes - */ - function sortChilds($a_childs, $a_parent_node_id) - { - $objDefinition = $this->obj_definition; + $visible = $rbacsystem->checkAccess('visible', $a_node["child"]); + if ($a_node["type"] == "rolf" && $a_node["child"] != ROLE_FOLDER_ID) { + return false; + } + return $visible; + } + + /** + * Sort childs + * + * @param array $a_childs array of child nodes + * @param mixed $a_parent_node parent node + * + * @return array array of childs nodes + */ + public function sortChilds($a_childs, $a_parent_node_id) + { + $objDefinition = $this->obj_definition; - $parent_obj_id = ilObject::_lookupObjId($a_parent_node_id); - - if ($parent_obj_id > 0) - { - $parent_type = ilObject::_lookupType($parent_obj_id); - } - else - { - $parent_type = "dummy"; - $this->type_grps["dummy"] = array("root" => "dummy"); - } + $parent_obj_id = ilObject::_lookupObjId($a_parent_node_id); + + if ($parent_obj_id > 0) { + $parent_type = ilObject::_lookupType($parent_obj_id); + } else { + $parent_type = "dummy"; + $this->type_grps["dummy"] = array("root" => "dummy"); + } - if (empty($this->type_grps[$parent_type])) - { - $this->type_grps[$parent_type] = - $objDefinition->getGroupedRepositoryObjectTypes($parent_type); - } - $group = array(); - - foreach ($a_childs as $child) - { - $g = $objDefinition->getGroupOfObj($child["type"]); - if ($g == "") - { - $g = $child["type"]; - } - $group[$g][] = $child; - } + if (empty($this->type_grps[$parent_type])) { + $this->type_grps[$parent_type] = + $objDefinition->getGroupedRepositoryObjectTypes($parent_type); + } + $group = array(); + + foreach ($a_childs as $child) { + $g = $objDefinition->getGroupOfObj($child["type"]); + if ($g == "") { + $g = $child["type"]; + } + $group[$g][] = $child; + } - $childs = array(); - foreach ($this->type_grps[$parent_type] as $t => $g) - { - if (is_array($group[$t])) - { - // do we have to sort this group?? - include_once("./Services/Container/classes/class.ilContainer.php"); - include_once("./Services/Container/classes/class.ilContainerSorting.php"); - $sort = ilContainerSorting::_getInstance($parent_obj_id); - $group = $sort->sortItems($group); - - // need extra session sorting here - if ($t == "sess") - { + $childs = array(); + foreach ($this->type_grps[$parent_type] as $t => $g) { + if (is_array($group[$t])) { + // do we have to sort this group?? + include_once("./Services/Container/classes/class.ilContainer.php"); + include_once("./Services/Container/classes/class.ilContainerSorting.php"); + $sort = ilContainerSorting::_getInstance($parent_obj_id); + $group = $sort->sortItems($group); + + // need extra session sorting here + if ($t == "sess") { + } + + foreach ($group[$t] as $k => $item) { + $childs[] = $item; + } + } + } + + return $childs; + } - } - - foreach ($group[$t] as $k => $item) - { - $childs[] = $item; - } - } - } - - return $childs; - } - - /** - * Get childs of node - * - * @param - * @return - */ - function getChildsOfNode($a_parent_node_id) - { - $rbacsystem = $this->rbacsystem; - - if (!$rbacsystem->checkAccess("read", $a_parent_node_id)) - { - return array(); - } - - return parent::getChildsOfNode($a_parent_node_id); - } - - /** - * Is node clickable? - * - * @param mixed $a_node node object/array - * @return boolean node clickable true/false - */ - function isNodeClickable($a_node) - { - $rbacsystem = $this->rbacsystem; - $tree = $this->tree; - $ilDB = $this->db; - $ilUser = $this->user; - $ilAccess = $this->access; - - return $rbacsystem->checkAccess('read', $a_node["child"]); - } + /** + * Get childs of node + * + * @param + * @return + */ + public function getChildsOfNode($a_parent_node_id) + { + $rbacsystem = $this->rbacsystem; + + if (!$rbacsystem->checkAccess("read", $a_parent_node_id)) { + return array(); + } + return parent::getChildsOfNode($a_parent_node_id); + } + + /** + * Is node clickable? + * + * @param mixed $a_node node object/array + * @return boolean node clickable true/false + */ + public function isNodeClickable($a_node) + { + $rbacsystem = $this->rbacsystem; + $tree = $this->tree; + $ilDB = $this->db; + $ilUser = $this->user; + $ilAccess = $this->access; + + return $rbacsystem->checkAccess('read', $a_node["child"]); + } } - -?> diff --git a/Services/Administration/classes/class.ilAdministrationGUI.php b/Services/Administration/classes/class.ilAdministrationGUI.php index 46e17358032357fa6fb0a5be464e824d5802d168..8f7ab38c54ad3696ae5ce715fcafd080ffcf2e0f 100755 --- a/Services/Administration/classes/class.ilAdministrationGUI.php +++ b/Services/Administration/classes/class.ilAdministrationGUI.php @@ -42,578 +42,515 @@ include_once("./Services/Table/classes/class.ilTableGUI.php"); */ class ilAdministrationGUI { - /** - * @var ilObjectDefinition - */ - protected $objDefinition; - - /** - * @var ilMainMenuGUI - */ - protected $main_menu; - - /** - * @var ilHelpGUI - */ - protected $help; - - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * @var ilDB - */ - protected $db; - - var $lng; - var $tpl; - var $tree; - var $rbacsystem; - var $cur_ref_id; - var $cmd; - var $mode; - var $ctrl; - - /** - * Constructor - * @access public - */ - function __construct() - { - global $DIC; - - $this->main_menu = $DIC["ilMainMenu"]; - $this->help = $DIC["ilHelp"]; - $this->error = $DIC["ilErr"]; - $this->db = $DIC->database(); - $lng = $DIC->language(); - $tpl = $DIC["tpl"]; - $tree = $DIC->repositoryTree(); - $rbacsystem = $DIC->rbac()->system(); - $objDefinition = $DIC["objDefinition"]; - $ilCtrl = $DIC->ctrl(); - $ilMainMenu = $DIC["ilMainMenu"]; - - $this->lng = $lng; - $this->lng->loadLanguageModule('administration'); - $this->tpl = $tpl; - $this->tree = $tree; - $this->rbacsystem = $rbacsystem; - $this->objDefinition = $objDefinition; - $this->ctrl = $ilCtrl; - - $ilMainMenu->setActive("administration"); - - $this->creation_mode = false; - - $this->ctrl->saveParameter($this, array("ref_id", "admin_mode")); - - if ($_GET["admin_mode"] != "repository") - { - $_GET["admin_mode"] = "settings"; - } - - if (!ilUtil::isAPICall()) - $this->ctrl->setReturn($this,""); - - // determine current ref id and mode - if (!empty($_GET["ref_id"]) && $tree->isInTree($_GET["ref_id"])) - { - $this->cur_ref_id = $_GET["ref_id"]; - } - else - { - //$this->cur_ref_id = $this->tree->getRootId(); - $_POST = array(); - if ($_GET["cmd"] != "getDropDown") - { - $_GET["cmd"] = ""; - } - } - } - - - /** - * execute command - */ - function executeCommand() - { - $rbacsystem = $this->rbacsystem; - $objDefinition = $this->objDefinition; - $ilHelp = $this->help; - $ilErr = $this->error; - $ilDB = $this->db; - - // permission checks - include_once './Services/MainMenu/classes/class.ilMainMenuGUI.php'; - if(!$rbacsystem->checkAccess("visible", SYSTEM_FOLDER_ID) && - !$rbacsystem->checkAccess("read", SYSTEM_FOLDER_ID)) - { - $ilErr->raiseError($this->lng->txt('permission_denied'),$ilErr->WARNING); - } - - // check creation mode - // determined by "new_type" parameter - $new_type = $_POST["new_type"] - ? $_POST["new_type"] - : $_GET["new_type"]; - if ($new_type != "") - { - $this->creation_mode = true; - } - - // determine next class - if ($this->creation_mode) - { - $obj_type = $new_type; - $class_name = $this->objDefinition->getClassName($obj_type); - $next_class = strtolower("ilObj".$class_name."GUI"); - $this->ctrl->setCmdClass($next_class); - } - // set next_class directly for page translations - // (no cmdNode is given in translation link) - elseif ($this->ctrl->getCmdClass() == "ilobjlanguageextgui") - { - $next_class = "ilobjlanguageextgui"; - } - else - { - $next_class = $this->ctrl->getNextClass($this); - - } - - if (($next_class == "iladministrationgui" || $next_class == "" - ) && ($this->ctrl->getCmd() == "return")) - { - // get GUI of current object - $obj_type = ilObject::_lookupType($this->cur_ref_id,true); - $class_name = $this->objDefinition->getClassName($obj_type); - $next_class = strtolower("ilObj".$class_name."GUI"); - $this->ctrl->setCmdClass($next_class); - $this->ctrl->setCmd("view"); - } - - $cmd = $this->ctrl->getCmd("forward"); - -//echo "
cmd:$cmd:nextclass:$next_class:-".$_GET["cmdClass"]."-".$_GET["cmd"]."-"; - switch ($next_class) - { - default: - - // forward all other classes to gui commands - if ($next_class != "" && $next_class != "iladministrationgui") - { - // check db update - include_once ("./Services/Database/classes/class.ilDBUpdate.php"); - $dbupdate = new ilDBUpdate($ilDB); - if (!$dbupdate->getDBVersionStatus()) - { - ilUtil::sendFailure($this->lng->txt("db_need_update")); - } - else if ($dbupdate->hotfixAvailable()) - { - ilUtil::sendFailure($this->lng->txt("db_need_hotfix")); - } - - $class_path = $this->ctrl->lookupClassPath($next_class); - // get gui class instance - include_once($class_path); - $class_name = $this->ctrl->getClassForClasspath($class_path); - if (($next_class == "ilobjrolegui" || $next_class == "ilobjusergui" - || $next_class == "ilobjroletemplategui")) - { - if ($_GET["obj_id"] != "") - { - $this->gui_obj = new $class_name("", $_GET["obj_id"], false, false); - $this->gui_obj->setCreationMode(false); - } - else - { - $this->gui_obj = new $class_name("", $this->cur_ref_id, true, false); - $this->gui_obj->setCreationMode(true); - } - } - else - { - if ($objDefinition->isPlugin(ilObject::_lookupType($this->cur_ref_id,true))) - { - $this->gui_obj = new $class_name($this->cur_ref_id); - } - else - { - if (!$this->creation_mode) - { - if(is_subclass_of($class_name, "ilObject2GUI")) - { - $this->gui_obj = new $class_name($this->cur_ref_id, ilObject2GUI::REPOSITORY_NODE_ID); - } - else - { - $this->gui_obj = new $class_name("", $this->cur_ref_id, true, false); - } - } - else - { - if(is_subclass_of($class_name, "ilObject2GUI")) - { - $this->gui_obj = new $class_name(null, ilObject2GUI::REPOSITORY_NODE_ID, $this->cur_ref_id); - } - else - { - $this->gui_obj = new $class_name("", 0, true, false); - } - } - } - $this->gui_obj->setCreationMode($this->creation_mode); - } - $tabs_out = ($new_type == "") - ? true - : false; - - // set standard screen id -// if (strtolower($next_class) == strtolower($this->ctrl->getCmdClass()) || -// "ilpermissiongui" == strtolower($this->ctrl->getCmdClass())) -// { - $ilHelp->setScreenIdComponent(ilObject::_lookupType($this->cur_ref_id,true)); -// } - $this->showTree(); - - $this->ctrl->setReturn($this, "return"); - $ret = $this->ctrl->forwardCommand($this->gui_obj); - $html = $this->gui_obj->getHTML(); - - if ($html != "") - { - $this->tpl->setVariable("OBJECTS", $html); - } - $this->tpl->show(); - } - else // - { - $cmd = $this->ctrl->getCmd("forward"); - $this->$cmd(); - } - break; - } - } - - /** - * Forward to class/command - */ - function forward() - { - $ilErr = $this->error; - - if ($_GET["admin_mode"] != "repository") // settings - { - if ($_GET["ref_id"] == USER_FOLDER_ID) - { - $this->ctrl->setParameter($this, "ref_id", USER_FOLDER_ID); - $this->ctrl->setParameterByClass("iladministrationgui", "admin_mode", "settings"); - if (((int) $_GET["jmpToUser"]) > 0 && ilObject::_lookupType((int)$_GET["jmpToUser"]) == "usr") - { - $this->ctrl->setParameterByClass("ilobjuserfoldergui", "jmpToUser", - (int)$_GET["jmpToUser"]); - $this->ctrl->redirectByClass("ilobjuserfoldergui", "jumpToUser"); - } - else - { - $this->ctrl->redirectByClass("ilobjuserfoldergui", "view"); - } - } - else - { - $this->ctrl->setParameter($this, "ref_id", SYSTEM_FOLDER_ID); - $this->ctrl->setParameterByClass("iladministrationgui", "admin_mode", "settings"); - - if($_GET['fr']) - { - // Security check: We do only allow relative urls - $url_parts = parse_url(base64_decode(rawurldecode($_GET['fr']))); - if($url_parts['http'] || $url_parts['host']) - { - $ilErr->raiseError($this->lng->txt('permission_denied'), $ilErr->MESSAGE); - } - - $fs_gui->setMainFrameSource( - base64_decode(rawurldecode($_GET['fr']))); - ilUtil::redirect(ILIAS_HTTP_PATH.'/'.base64_decode(rawurldecode($_GET['fr']))); + /** + * @var ilObjectDefinition + */ + protected $objDefinition; + + /** + * @var ilMainMenuGUI + */ + protected $main_menu; + + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilDB + */ + protected $db; + + public $lng; + public $tpl; + public $tree; + public $rbacsystem; + public $cur_ref_id; + public $cmd; + public $mode; + public $ctrl; + + /** + * Constructor + * @access public + */ + public function __construct() + { + global $DIC; + + $this->main_menu = $DIC["ilMainMenu"]; + $this->help = $DIC["ilHelp"]; + $this->error = $DIC["ilErr"]; + $this->db = $DIC->database(); + $lng = $DIC->language(); + $tpl = $DIC["tpl"]; + $tree = $DIC->repositoryTree(); + $rbacsystem = $DIC->rbac()->system(); + $objDefinition = $DIC["objDefinition"]; + $ilCtrl = $DIC->ctrl(); + $ilMainMenu = $DIC["ilMainMenu"]; + + $this->lng = $lng; + $this->lng->loadLanguageModule('administration'); + $this->tpl = $tpl; + $this->tree = $tree; + $this->rbacsystem = $rbacsystem; + $this->objDefinition = $objDefinition; + $this->ctrl = $ilCtrl; + + $ilMainMenu->setActive("administration"); + + $this->creation_mode = false; + + $this->ctrl->saveParameter($this, array("ref_id", "admin_mode")); + + if ($_GET["admin_mode"] != "repository") { + $_GET["admin_mode"] = "settings"; + } + + if (!ilUtil::isAPICall()) { + $this->ctrl->setReturn($this, ""); + } + + // determine current ref id and mode + if (!empty($_GET["ref_id"]) && $tree->isInTree($_GET["ref_id"])) { + $this->cur_ref_id = $_GET["ref_id"]; + } else { + //$this->cur_ref_id = $this->tree->getRootId(); + $_POST = array(); + if ($_GET["cmd"] != "getDropDown") { + $_GET["cmd"] = ""; + } + } + } + + + /** + * execute command + */ + public function executeCommand() + { + $rbacsystem = $this->rbacsystem; + $objDefinition = $this->objDefinition; + $ilHelp = $this->help; + $ilErr = $this->error; + $ilDB = $this->db; + + // permission checks + include_once './Services/MainMenu/classes/class.ilMainMenuGUI.php'; + if (!$rbacsystem->checkAccess("visible", SYSTEM_FOLDER_ID) && + !$rbacsystem->checkAccess("read", SYSTEM_FOLDER_ID)) { + $ilErr->raiseError($this->lng->txt('permission_denied'), $ilErr->WARNING); + } + + // check creation mode + // determined by "new_type" parameter + $new_type = $_POST["new_type"] + ? $_POST["new_type"] + : $_GET["new_type"]; + if ($new_type != "") { + $this->creation_mode = true; + } + + // determine next class + if ($this->creation_mode) { + $obj_type = $new_type; + $class_name = $this->objDefinition->getClassName($obj_type); + $next_class = strtolower("ilObj" . $class_name . "GUI"); + $this->ctrl->setCmdClass($next_class); + } + // set next_class directly for page translations + // (no cmdNode is given in translation link) + elseif ($this->ctrl->getCmdClass() == "ilobjlanguageextgui") { + $next_class = "ilobjlanguageextgui"; + } else { + $next_class = $this->ctrl->getNextClass($this); + } + + if (( + $next_class == "iladministrationgui" || $next_class == "" + ) && ($this->ctrl->getCmd() == "return")) { + // get GUI of current object + $obj_type = ilObject::_lookupType($this->cur_ref_id, true); + $class_name = $this->objDefinition->getClassName($obj_type); + $next_class = strtolower("ilObj" . $class_name . "GUI"); + $this->ctrl->setCmdClass($next_class); + $this->ctrl->setCmd("view"); + } + + $cmd = $this->ctrl->getCmd("forward"); + + //echo "
cmd:$cmd:nextclass:$next_class:-".$_GET["cmdClass"]."-".$_GET["cmd"]."-"; + switch ($next_class) { + default: + + // forward all other classes to gui commands + if ($next_class != "" && $next_class != "iladministrationgui") { + // check db update + include_once("./Services/Database/classes/class.ilDBUpdate.php"); + $dbupdate = new ilDBUpdate($ilDB); + if (!$dbupdate->getDBVersionStatus()) { + ilUtil::sendFailure($this->lng->txt("db_need_update")); + } elseif ($dbupdate->hotfixAvailable()) { + ilUtil::sendFailure($this->lng->txt("db_need_hotfix")); + } + + $class_path = $this->ctrl->lookupClassPath($next_class); + // get gui class instance + include_once($class_path); + $class_name = $this->ctrl->getClassForClasspath($class_path); + if (($next_class == "ilobjrolegui" || $next_class == "ilobjusergui" + || $next_class == "ilobjroletemplategui")) { + if ($_GET["obj_id"] != "") { + $this->gui_obj = new $class_name("", $_GET["obj_id"], false, false); + $this->gui_obj->setCreationMode(false); + } else { + $this->gui_obj = new $class_name("", $this->cur_ref_id, true, false); + $this->gui_obj->setCreationMode(true); + } + } else { + if ($objDefinition->isPlugin(ilObject::_lookupType($this->cur_ref_id, true))) { + $this->gui_obj = new $class_name($this->cur_ref_id); + } else { + if (!$this->creation_mode) { + if (is_subclass_of($class_name, "ilObject2GUI")) { + $this->gui_obj = new $class_name($this->cur_ref_id, ilObject2GUI::REPOSITORY_NODE_ID); + } else { + $this->gui_obj = new $class_name("", $this->cur_ref_id, true, false); + } + } else { + if (is_subclass_of($class_name, "ilObject2GUI")) { + $this->gui_obj = new $class_name(null, ilObject2GUI::REPOSITORY_NODE_ID, $this->cur_ref_id); + } else { + $this->gui_obj = new $class_name("", 0, true, false); + } + } + } + $this->gui_obj->setCreationMode($this->creation_mode); + } + $tabs_out = ($new_type == "") + ? true + : false; + + // set standard screen id + // if (strtolower($next_class) == strtolower($this->ctrl->getCmdClass()) || + // "ilpermissiongui" == strtolower($this->ctrl->getCmdClass())) + // { + $ilHelp->setScreenIdComponent(ilObject::_lookupType($this->cur_ref_id, true)); + // } + $this->showTree(); + + $this->ctrl->setReturn($this, "return"); + $ret = $this->ctrl->forwardCommand($this->gui_obj); + $html = $this->gui_obj->getHTML(); + + if ($html != "") { + $this->tpl->setVariable("OBJECTS", $html); + } + $this->tpl->show(); + } else { // + $cmd = $this->ctrl->getCmd("forward"); + $this->$cmd(); + } + break; + } + } + + /** + * Forward to class/command + */ + public function forward() + { + $ilErr = $this->error; + + if ($_GET["admin_mode"] != "repository") { // settings + if ($_GET["ref_id"] == USER_FOLDER_ID) { + $this->ctrl->setParameter($this, "ref_id", USER_FOLDER_ID); + $this->ctrl->setParameterByClass("iladministrationgui", "admin_mode", "settings"); + if (((int) $_GET["jmpToUser"]) > 0 && ilObject::_lookupType((int) $_GET["jmpToUser"]) == "usr") { + $this->ctrl->setParameterByClass( + "ilobjuserfoldergui", + "jmpToUser", + (int) $_GET["jmpToUser"] + ); + $this->ctrl->redirectByClass("ilobjuserfoldergui", "jumpToUser"); + } else { + $this->ctrl->redirectByClass("ilobjuserfoldergui", "view"); } - else - { + } else { + $this->ctrl->setParameter($this, "ref_id", SYSTEM_FOLDER_ID); + $this->ctrl->setParameterByClass("iladministrationgui", "admin_mode", "settings"); + + if ($_GET['fr']) { + // Security check: We do only allow relative urls + $url_parts = parse_url(base64_decode(rawurldecode($_GET['fr']))); + if ($url_parts['http'] || $url_parts['host']) { + $ilErr->raiseError($this->lng->txt('permission_denied'), $ilErr->MESSAGE); + } + + $fs_gui->setMainFrameSource( + base64_decode(rawurldecode($_GET['fr'])) + ); + ilUtil::redirect(ILIAS_HTTP_PATH . '/' . base64_decode(rawurldecode($_GET['fr']))); + } else { $fs_gui->setMainFrameSource( - $this->ctrl->getLinkTargetByClass("ilobjsystemfoldergui", "view")); + $this->ctrl->getLinkTargetByClass("ilobjsystemfoldergui", "view") + ); $this->ctrl->redirectByClass("ilobjsystemfoldergui", "view"); } - } - } - else - { - $this->ctrl->setParameter($this, "ref_id", ROOT_FOLDER_ID); - $this->ctrl->setParameterByClass("iladministrationgui", "admin_mode", "repository"); - $this->ctrl->redirectByClass("ilobjrootfoldergui", "view"); - } - } - - /** - * display tree view - */ - function showTree() - { - $tpl = $this->tpl; - $tree = $this->tree; - $lng = $this->lng; - - if ($_GET["admin_mode"] != "repository") - { - return; - } - - include_once("./Services/Administration/classes/class.ilAdministrationExplorerGUI.php"); - $exp = new ilAdministrationExplorerGUI($this, "showTree"); - if (!$exp->handleCommand()) - { - $tpl->setLeftNavContent($exp->getHTML()); - } - } - - /** - * Special jump to plugin slot after ilCtrl has been reloaded - */ - function jumpToPluginSlot() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameterByClass("ilobjcomponentsettingsgui", "ctype", $_GET["ctype"]); - $ilCtrl->setParameterByClass("ilobjcomponentsettingsgui", "cname", $_GET["cname"]); - $ilCtrl->setParameterByClass("ilobjcomponentsettingsgui", "slot_id", $_GET["slot_id"]); - - if($_GET["plugin_id"]) - { - $ilCtrl->setParameter($this, "plugin_id", $_GET["plugin_id"]); - $ilCtrl->redirectByClass("ilobjcomponentsettingsgui", "showPlugin"); - } - else - { - $ilCtrl->redirectByClass("ilobjcomponentsettingsgui", "listPlugins"); - } - } - - /** - * Get drop down - */ - function getDropDown() - { - $tree = $this->tree; - $rbacsystem = $this->rbacsystem; - $lng = $this->lng; - - $objects = $tree->getChilds(SYSTEM_FOLDER_ID); - - foreach($objects as $object) - { - $new_objects[$object["title"].":".$object["child"]] - = $object; - // have to set it manually as translation type of main node cannot be "sys" as this type is a orgu itself. - if($object["type"] == "orgu") - $new_objects[$object["title"].":".$object["child"]]["title"] = $lng->txt("objs_orgu"); - } - - // add entry for switching to repository admin - // note: please see showChilds methods which prevents infinite look - $new_objects[$lng->txt("repository_admin").":".ROOT_FOLDER_ID] = - array( - "tree" => 1, - "child" => ROOT_FOLDER_ID, - "ref_id" => ROOT_FOLDER_ID, - "depth" => 3, - "type" => "root", - "title" => $lng->txt("repository_admin"), - "description" => $lng->txt("repository_admin_desc"), - "desc" => $lng->txt("repository_admin_desc"), - ); - - $new_objects[$lng->txt("general_settings").":".SYSTEM_FOLDER_ID] = - array( - "tree" => 1, - "child" => SYSTEM_FOLDER_ID, - "ref_id" => SYSTEM_FOLDER_ID, - "depth" => 2, - "type" => "adm", - "title" => $lng->txt("general_settings"), - ); - ksort($new_objects); - - // determine items to show - $items = array(); - foreach ($new_objects as $c) - { - // check visibility - if ($tree->getParentId($c["ref_id"]) == ROOT_FOLDER_ID && $c["type"] != "adm" && - $_GET["admin_mode"] != "repository") - { - continue; - } - // these objects may exist due to test cases that didnt clear - // data properly - if ($c["type"] == "" || $c["type"] == "objf" || - $c["type"] == "xxx") - { - continue; - } - $accessible = $rbacsystem->checkAccess('visible,read', $c["ref_id"]); - if (!$accessible) - { - continue; - } - if ($c["ref_id"] == ROOT_FOLDER_ID && - !$rbacsystem->checkAccess('write', $c["ref_id"])) - { - continue; - } - if ($c["type"] == "rolf" && $c["ref_id"] != ROLE_FOLDER_ID) - { - continue; - } - $items[] = $c; - } - - $titems = array(); - foreach ($items as $i) - { - $titems[$i["type"]] = $i; - } - - // admin menu layout - $layout = array( - 1 => array( - "basic" => - array("adm", "mme", "stys", "adve", "lngf", "hlps", "accs", "cmps", "extt", "wfe"), - "user_administration" => - array("usrf", 'tos', "rolf", "orgu", "auth", "ps"), - "learning_outcomes" => - array("skmg", "bdga", "cert", "trac") - ), - 2 => array( - "user_services" => - array("pdts", "prfa", "nwss", "awra", "cadm", "cals", "mail"), - "content_services" => - array("seas", "mds", "tags", "taxs", 'ecss', "ltis", "otpl", "pdfg"), - "maintenance" => - array('logs', 'sysc', "recf", "root") - ), - 3 => array( - "container" => - array("reps", "crss", "grps", "prgs"), - "content_objects" => - array("bibs", "blga", "chta", "excs", "facs", "frma", - "lrss", "mcts", "mobs", "svyf", "assf", "wbrs", "wiks") - ) - ); - - // now get all items and groups that are accessible - $groups = array(); - for ($i = 1; $i <= 3; $i++) - { - $groups[$i] = array(); - foreach ($layout[$i] as $group => $entries) - { - $groups[$i][$group] = array(); - $entries_since_last_sep = false; - foreach ($entries as $e) - { - if ($e == "---" || $titems[$e]["type"] != "") - { - if ($e == "---" && $entries_since_last_sep) - { - $groups[$i][$group][] = $e; - $entries_since_last_sep = false; - } - else if ($e != "---") - { - $groups[$i][$group][] = $e; - $entries_since_last_sep = true; - } - } - } - } - } - - include_once("./Services/UIComponent/GroupedList/classes/class.ilGroupedListGUI.php"); - $gl = new ilGroupedListGUI(); - $gl->setAsDropDown(true); - - for ($i = 1; $i <= 3; $i++) - { - if ($i > 1) - { - $gl->nextColumn(); - } - foreach ($groups[$i] as $group => $entries) - { - if (count($entries) > 0) - { - $gl->addGroupHeader($lng->txt("adm_".$group)); - - foreach ($entries as $e) - { - if ($e == "---") - { - $gl->addSeparator(); - } - else - { - $path = ilObject::_getIcon("", "tiny", $titems[$e]["type"]); - $icon = ($path != "") - ? ilUtil::img($path)." " - : ""; - - if ($_GET["admin_mode"] == "settings" && $titems[$e]["ref_id"] == ROOT_FOLDER_ID) - { - $gl->addEntry($icon.$titems[$e]["title"], - "ilias.php?baseClass=ilAdministrationGUI&ref_id=". - $titems[$e]["ref_id"]."&admin_mode=repository", - "_top", "", "", "mm_adm_rep", - ilHelp::getMainMenuTooltip("mm_adm_rep"), - "bottom center", "top center", false); - } - else - { - $gl->addEntry($icon.$titems[$e]["title"], - "ilias.php?baseClass=ilAdministrationGUI&ref_id=". - $titems[$e]["ref_id"]."&cmd=jump", - "_top", "", "", "mm_adm_".$titems[$e]["type"], - ilHelp::getMainMenuTooltip("mm_adm_".$titems[$e]["type"]), - "bottom center", "top center", false); - } - } - } - } - } - } - - echo $gl->getHTML(); - exit; - } - - /** - * Jump to node - */ - function jump() - { - $ilCtrl = $this->ctrl; - $objDefinition = $this->objDefinition; - - $ref_id = (int) $_GET["ref_id"]; - $obj_id = ilObject::_lookupObjId($ref_id); - $obj_type = ilObject::_lookupType($obj_id); - $class_name = $objDefinition->getClassName($obj_type); - $class = strtolower("ilObj".$class_name."GUI"); - $ilCtrl->setParameterByClass($class, "ref_id", $ref_id); - $ilCtrl->redirectByClass($class, "view"); - } + } + } else { + $this->ctrl->setParameter($this, "ref_id", ROOT_FOLDER_ID); + $this->ctrl->setParameterByClass("iladministrationgui", "admin_mode", "repository"); + $this->ctrl->redirectByClass("ilobjrootfoldergui", "view"); + } + } + + /** + * display tree view + */ + public function showTree() + { + $tpl = $this->tpl; + $tree = $this->tree; + $lng = $this->lng; + + if ($_GET["admin_mode"] != "repository") { + return; + } + + include_once("./Services/Administration/classes/class.ilAdministrationExplorerGUI.php"); + $exp = new ilAdministrationExplorerGUI($this, "showTree"); + if (!$exp->handleCommand()) { + $tpl->setLeftNavContent($exp->getHTML()); + } + } + + /** + * Special jump to plugin slot after ilCtrl has been reloaded + */ + public function jumpToPluginSlot() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameterByClass("ilobjcomponentsettingsgui", "ctype", $_GET["ctype"]); + $ilCtrl->setParameterByClass("ilobjcomponentsettingsgui", "cname", $_GET["cname"]); + $ilCtrl->setParameterByClass("ilobjcomponentsettingsgui", "slot_id", $_GET["slot_id"]); + + if ($_GET["plugin_id"]) { + $ilCtrl->setParameter($this, "plugin_id", $_GET["plugin_id"]); + $ilCtrl->redirectByClass("ilobjcomponentsettingsgui", "showPlugin"); + } else { + $ilCtrl->redirectByClass("ilobjcomponentsettingsgui", "listPlugins"); + } + } + + /** + * Get drop down + */ + public function getDropDown() + { + $tree = $this->tree; + $rbacsystem = $this->rbacsystem; + $lng = $this->lng; + + $objects = $tree->getChilds(SYSTEM_FOLDER_ID); + + foreach ($objects as $object) { + $new_objects[$object["title"] . ":" . $object["child"]] + = $object; + // have to set it manually as translation type of main node cannot be "sys" as this type is a orgu itself. + if ($object["type"] == "orgu") { + $new_objects[$object["title"] . ":" . $object["child"]]["title"] = $lng->txt("objs_orgu"); + } + } + + // add entry for switching to repository admin + // note: please see showChilds methods which prevents infinite look + $new_objects[$lng->txt("repository_admin") . ":" . ROOT_FOLDER_ID] = + array( + "tree" => 1, + "child" => ROOT_FOLDER_ID, + "ref_id" => ROOT_FOLDER_ID, + "depth" => 3, + "type" => "root", + "title" => $lng->txt("repository_admin"), + "description" => $lng->txt("repository_admin_desc"), + "desc" => $lng->txt("repository_admin_desc"), + ); + + $new_objects[$lng->txt("general_settings") . ":" . SYSTEM_FOLDER_ID] = + array( + "tree" => 1, + "child" => SYSTEM_FOLDER_ID, + "ref_id" => SYSTEM_FOLDER_ID, + "depth" => 2, + "type" => "adm", + "title" => $lng->txt("general_settings"), + ); + ksort($new_objects); + + // determine items to show + $items = array(); + foreach ($new_objects as $c) { + // check visibility + if ($tree->getParentId($c["ref_id"]) == ROOT_FOLDER_ID && $c["type"] != "adm" && + $_GET["admin_mode"] != "repository") { + continue; + } + // these objects may exist due to test cases that didnt clear + // data properly + if ($c["type"] == "" || $c["type"] == "objf" || + $c["type"] == "xxx") { + continue; + } + $accessible = $rbacsystem->checkAccess('visible,read', $c["ref_id"]); + if (!$accessible) { + continue; + } + if ($c["ref_id"] == ROOT_FOLDER_ID && + !$rbacsystem->checkAccess('write', $c["ref_id"])) { + continue; + } + if ($c["type"] == "rolf" && $c["ref_id"] != ROLE_FOLDER_ID) { + continue; + } + $items[] = $c; + } + + $titems = array(); + foreach ($items as $i) { + $titems[$i["type"]] = $i; + } + + // admin menu layout + $layout = array( + 1 => array( + "basic" => + array("adm", "mme", "stys", "adve", "lngf", "hlps", "accs", "cmps", "extt", "wfe"), + "user_administration" => + array("usrf", 'tos', "rolf", "orgu", "auth", "ps"), + "learning_outcomes" => + array("skmg", "bdga", "cert", "trac") + ), + 2 => array( + "user_services" => + array("pdts", "prfa", "nwss", "awra", "cadm", "cals", "mail"), + "content_services" => + array("seas", "mds", "tags", "taxs", 'ecss', "ltis", "otpl", "pdfg"), + "maintenance" => + array('logs', 'sysc', "recf", "root") + ), + 3 => array( + "container" => + array("reps", "crss", "grps", "prgs"), + "content_objects" => + array("bibs", "blga", "chta", "excs", "facs", "frma", + "lrss", "mcts", "mobs", "svyf", "assf", "wbrs", "wiks") + ) + ); + + // now get all items and groups that are accessible + $groups = array(); + for ($i = 1; $i <= 3; $i++) { + $groups[$i] = array(); + foreach ($layout[$i] as $group => $entries) { + $groups[$i][$group] = array(); + $entries_since_last_sep = false; + foreach ($entries as $e) { + if ($e == "---" || $titems[$e]["type"] != "") { + if ($e == "---" && $entries_since_last_sep) { + $groups[$i][$group][] = $e; + $entries_since_last_sep = false; + } elseif ($e != "---") { + $groups[$i][$group][] = $e; + $entries_since_last_sep = true; + } + } + } + } + } + + include_once("./Services/UIComponent/GroupedList/classes/class.ilGroupedListGUI.php"); + $gl = new ilGroupedListGUI(); + $gl->setAsDropDown(true); + + for ($i = 1; $i <= 3; $i++) { + if ($i > 1) { + $gl->nextColumn(); + } + foreach ($groups[$i] as $group => $entries) { + if (count($entries) > 0) { + $gl->addGroupHeader($lng->txt("adm_" . $group)); + + foreach ($entries as $e) { + if ($e == "---") { + $gl->addSeparator(); + } else { + $path = ilObject::_getIcon("", "tiny", $titems[$e]["type"]); + $icon = ($path != "") + ? ilUtil::img($path) . " " + : ""; + + if ($_GET["admin_mode"] == "settings" && $titems[$e]["ref_id"] == ROOT_FOLDER_ID) { + $gl->addEntry( + $icon . $titems[$e]["title"], + "ilias.php?baseClass=ilAdministrationGUI&ref_id=" . + $titems[$e]["ref_id"] . "&admin_mode=repository", + "_top", + "", + "", + "mm_adm_rep", + ilHelp::getMainMenuTooltip("mm_adm_rep"), + "bottom center", + "top center", + false + ); + } else { + $gl->addEntry( + $icon . $titems[$e]["title"], + "ilias.php?baseClass=ilAdministrationGUI&ref_id=" . + $titems[$e]["ref_id"] . "&cmd=jump", + "_top", + "", + "", + "mm_adm_" . $titems[$e]["type"], + ilHelp::getMainMenuTooltip("mm_adm_" . $titems[$e]["type"]), + "bottom center", + "top center", + false + ); + } + } + } + } + } + } + + echo $gl->getHTML(); + exit; + } + + /** + * Jump to node + */ + public function jump() + { + $ilCtrl = $this->ctrl; + $objDefinition = $this->objDefinition; + + $ref_id = (int) $_GET["ref_id"]; + $obj_id = ilObject::_lookupObjId($ref_id); + $obj_type = ilObject::_lookupType($obj_id); + $class_name = $objDefinition->getClassName($obj_type); + $class = strtolower("ilObj" . $class_name . "GUI"); + $ilCtrl->setParameterByClass($class, "ref_id", $ref_id); + $ilCtrl->redirectByClass($class, "view"); + } } - -?> diff --git a/Services/Administration/classes/class.ilAdministrationSettingsFormHandler.php b/Services/Administration/classes/class.ilAdministrationSettingsFormHandler.php index 633466f995067a4362241d7ea9794f6517568512..a87c04228f3c7cd8589fa00487d1ea4af18e9f8c 100644 --- a/Services/Administration/classes/class.ilAdministrationSettingsFormHandler.php +++ b/Services/Administration/classes/class.ilAdministrationSettingsFormHandler.php @@ -1,312 +1,283 @@ - - * @version $Id: class.ilAdministrationGUI.php 43022 2013-06-26 13:32:48Z tamstutz $ - */ -class ilAdministrationSettingsFormHandler -{ - protected static $OBJ_MAP; - - const FORM_PRIVACY = 1; - const FORM_SECURITY = 2; - const FORM_FILES_QUOTA = 3; - const FORM_LP = 4; - const FORM_MAIL = 5; - const FORM_COURSE = 6; - const FORM_GROUP = 7; - const FORM_REPOSITORY = 8; - const FORM_LDAP = 9; - const FORM_FORUM = 10; - const FORM_ACCESSIBILITY = 11; - const FORM_WSP = 12; - const FORM_TAGGING = 13; - const FORM_CERTIFICATE = 14; - const FORM_META_COPYRIGHT = 15; - - - const SETTINGS_USER = "usrf"; - const SETTINGS_GENERAL = "adm"; - const SETTINGS_FILE = "facs"; - const SETTINGS_ROLE = "rolf"; - const SETTINGS_FORUM = "frma"; - const SETTINGS_LRES = "lrss"; - const SETTINGS_REPOSITORY = "reps"; - const SETTINGS_PD = "pdts"; - const SETTINGS_COURSE = "crss"; - const SETTINGS_GROUP = "grps"; - const SETTINGS_PRIVACY_SECURITY = "ps"; - const SETTINGS_CALENDAR = "cals"; - const SETTINGS_AUTH = "auth"; - const SETTINGS_WIKI = "wiks"; - const SETTINGS_PORTFOLIO = "prfa"; - const SETTINGS_LP_COMPLETION_STATUS = "trac"; - - const VALUE_BOOL = "bool"; - - protected static function initObjectMap() - { - global $DIC; - - $tree = $DIC->repositoryTree(); - - $map = array("adm" => SYSTEM_FOLDER_ID); - foreach($tree->getChilds(SYSTEM_FOLDER_ID) as $obj) - { - $map[$obj["type"]] = $obj["ref_id"]; - } - - self::$OBJ_MAP = $map; - } - - protected static function getRefId($a_obj_type) - { - if(!is_array(self::$OBJ_MAP)) - { - self::initObjectMap(); - } - return self::$OBJ_MAP[$a_obj_type]; - } - - public static function getSettingsGUIInstance($a_settings_obj_type) - { - global $DIC; - - $objDefinition = $DIC["objDefinition"]; - $ilCtrl = $DIC->ctrl(); - - $ref_id = self::getRefId($a_settings_obj_type); - $obj_type = ilObject::_lookupType($ref_id, true); - - $class_name = $objDefinition->getClassName($obj_type); - $class_name = "ilObj".$class_name."GUI"; - - $class_path = $ilCtrl->lookupClassPath($class_name); - include_once($class_path); - - if(is_subclass_of($class_name, "ilObject2GUI")) - { - $gui_obj = new $class_name($ref_id, ilObject2GUI::REPOSITORY_NODE_ID); - } - else - { - $gui_obj = new $class_name("", $ref_id, true, false); - } - - $gui_obj->setCreationMode(true); - - return $gui_obj; - } - - public static function addFieldsToForm($a_form_id, ilPropertyFormGUI $a_form, ilObjectGUI $a_parent_gui) - { - switch($a_form_id) - { - case self::FORM_SECURITY: - $types = array(self::SETTINGS_GENERAL, self::SETTINGS_USER, self::SETTINGS_FILE, self::SETTINGS_ROLE); - break; - - case self::FORM_PRIVACY: - $types = array(self::SETTINGS_ROLE, self::SETTINGS_FORUM, self::SETTINGS_LRES); - break; - - case self::FORM_FILES_QUOTA: - $types = array(self::SETTINGS_PD); - break; - - case self::FORM_LP: - $types = array(self::SETTINGS_REPOSITORY); - break; - - case self::FORM_ACCESSIBILITY: - $types = array(self::SETTINGS_FORUM, self::SETTINGS_AUTH, self::SETTINGS_WIKI); - break; - - case self::FORM_MAIL: - $types = array(self::SETTINGS_COURSE, self::SETTINGS_GROUP); - break; - - case self::FORM_COURSE: - case self::FORM_GROUP: - $types = array(self::SETTINGS_PRIVACY_SECURITY, self::SETTINGS_CALENDAR, self::SETTINGS_GENERAL); - break; - - case self::FORM_WSP: - $types = array(self::SETTINGS_PORTFOLIO); - break; - - case self::FORM_TAGGING: - $types = array(self::SETTINGS_REPOSITORY); - break; - - case self::FORM_CERTIFICATE: - $types = array(self::SETTINGS_LP_COMPLETION_STATUS); - break; - - default: - $types = null; - break; - } - - if(is_array($types)) - { - foreach($types as $type) - { - $gui = self::getSettingsGUIInstance($type); - if($gui && method_exists($gui, "addToExternalSettingsForm")) - { - $data = $gui->addToExternalSettingsForm($a_form_id); - if(is_array($data)) - { - self::parseFieldDefinition($type, $a_form, $gui, $data); - } - } - } - } - - // cron jobs - special handling - - include_once "Modules/SystemFolder/classes/class.ilObjSystemFolderGUI.php"; - $parent_gui = new ilObjSystemFolderGUI(null, SYSTEM_FOLDER_ID, true); - $parent_gui->setCreationMode(true); - - include_once "Services/Cron/classes/class.ilCronManagerGUI.php"; - $gui = new ilCronManagerGUI(); - $data = $gui->addToExternalSettingsForm($a_form_id); - if(is_array($data) && sizeof($data)) - { - self::parseFieldDefinition("cron", $a_form, $parent_gui, $data); - } - } - - protected static function parseFieldValue($a_field_type, &$a_field_value) - { - global $DIC; - - $lng = $DIC->language(); - - switch($a_field_type) - { - case self::VALUE_BOOL: - $a_field_value = (bool)$a_field_value ? - $lng->txt("enabled") : - $lng->txt("disabled"); - return $a_field_value; - } - - if(!is_numeric($a_field_value) && - $a_field_value !== null && !trim($a_field_value)) - { - $a_field_value = "-"; - } - - if(is_numeric($a_field_value) || $a_field_value !== "") - { - return true; - } - return false; - } - - protected static function parseFieldDefinition($a_type, ilPropertyFormGUI $a_form, ilObjectGUI $a_gui, $a_data) - { - global $DIC; - - $lng = $DIC->language(); - $rbacsystem = $DIC->rbac()->system(); - $ilCtrl = $DIC->ctrl(); - $ilAccess = $DIC->access(); - - if(!is_array($a_data)) - { - return; - } - - // write permission for current gui? - $has_write = $ilAccess->checkAccess("write", "", (int)$_REQUEST["ref_id"]); - - foreach($a_data as $area_caption => $fields) - { - if(is_numeric($area_caption) || !trim($area_caption)) - { - $area_caption = "obj_".$a_type; - } - - if(is_array($fields) && sizeof($fields) == 2) - { - $cmd = $fields[0]; - $fields = $fields[1]; - if(is_array($fields)) - { - $ftpl = new ilTemplate("tpl.external_settings.html", true, true, "Services/Administration"); - - - $stack = array(); - foreach($fields as $field_caption_id => $field_value) - { - $field_type = $subitems = null; - if(is_array($field_value)) - { - $field_type = $field_value[1]; - $subitems = $field_value[2]; - $field_value = $field_value[0]; - } - - if(self::parseFieldValue($field_type, $field_value)) - { - $ftpl->setCurrentBlock("value_bl"); - $ftpl->setVariable("VALUE", $field_value); - $ftpl->parseCurrentBlock(); - } - - if(is_array($subitems)) - { - $ftpl->setCurrentBlock("subitem_bl"); - foreach($subitems as $sub_caption_id => $sub_value) - { - $sub_type = null; - if(is_array($sub_value)) - { - $sub_type = $sub_value[1]; - $sub_value = $sub_value[0]; - } - self::parseFieldValue($sub_type, $sub_value); - - $ftpl->setVariable("SUBKEY", $lng->txt($sub_caption_id)); - $ftpl->setVariable("SUBVALUE", $sub_value); - $ftpl->parseCurrentBlock(); - } - } - - $ftpl->setCurrentBlock("row_bl"); - $ftpl->setVariable("KEY", $lng->txt($field_caption_id)); - $ftpl->parseCurrentBlock(); - } - - if ($has_write && - $rbacsystem->checkAccess("visible,read", $a_gui->object->getRefId())) - { - if(!$cmd) - { - $cmd = "view"; - } - $ilCtrl->setParameter($a_gui, "ref_id", $a_gui->object->getRefId()); - - $ftpl->setCurrentBlock("edit_bl"); - $ftpl->setVariable("URL_EDIT", $ilCtrl->getLinkTargetByClass(array("ilAdministrationGUI", get_class($a_gui)), $cmd)); - $ftpl->setVariable("TXT_EDIT", $lng->txt("adm_external_setting_edit")); - $ftpl->parseCurrentBlock(); - } - - $ext = new ilCustomInputGUI($lng->txt($area_caption)); - $ext->setHtml($ftpl->get()); - $a_form->addItem($ext); - } - } - } - } -} - -?> + + * @version $Id: class.ilAdministrationGUI.php 43022 2013-06-26 13:32:48Z tamstutz $ + */ +class ilAdministrationSettingsFormHandler +{ + protected static $OBJ_MAP; + + const FORM_PRIVACY = 1; + const FORM_SECURITY = 2; + const FORM_FILES_QUOTA = 3; + const FORM_LP = 4; + const FORM_MAIL = 5; + const FORM_COURSE = 6; + const FORM_GROUP = 7; + const FORM_REPOSITORY = 8; + const FORM_LDAP = 9; + const FORM_FORUM = 10; + const FORM_ACCESSIBILITY = 11; + const FORM_WSP = 12; + const FORM_TAGGING = 13; + const FORM_CERTIFICATE = 14; + const FORM_META_COPYRIGHT = 15; + + + const SETTINGS_USER = "usrf"; + const SETTINGS_GENERAL = "adm"; + const SETTINGS_FILE = "facs"; + const SETTINGS_ROLE = "rolf"; + const SETTINGS_FORUM = "frma"; + const SETTINGS_LRES = "lrss"; + const SETTINGS_REPOSITORY = "reps"; + const SETTINGS_PD = "pdts"; + const SETTINGS_COURSE = "crss"; + const SETTINGS_GROUP = "grps"; + const SETTINGS_PRIVACY_SECURITY = "ps"; + const SETTINGS_CALENDAR = "cals"; + const SETTINGS_AUTH = "auth"; + const SETTINGS_WIKI = "wiks"; + const SETTINGS_PORTFOLIO = "prfa"; + const SETTINGS_LP_COMPLETION_STATUS = "trac"; + + const VALUE_BOOL = "bool"; + + protected static function initObjectMap() + { + global $DIC; + + $tree = $DIC->repositoryTree(); + + $map = array("adm" => SYSTEM_FOLDER_ID); + foreach ($tree->getChilds(SYSTEM_FOLDER_ID) as $obj) { + $map[$obj["type"]] = $obj["ref_id"]; + } + + self::$OBJ_MAP = $map; + } + + protected static function getRefId($a_obj_type) + { + if (!is_array(self::$OBJ_MAP)) { + self::initObjectMap(); + } + return self::$OBJ_MAP[$a_obj_type]; + } + + public static function getSettingsGUIInstance($a_settings_obj_type) + { + global $DIC; + + $objDefinition = $DIC["objDefinition"]; + $ilCtrl = $DIC->ctrl(); + + $ref_id = self::getRefId($a_settings_obj_type); + $obj_type = ilObject::_lookupType($ref_id, true); + + $class_name = $objDefinition->getClassName($obj_type); + $class_name = "ilObj" . $class_name . "GUI"; + + $class_path = $ilCtrl->lookupClassPath($class_name); + include_once($class_path); + + if (is_subclass_of($class_name, "ilObject2GUI")) { + $gui_obj = new $class_name($ref_id, ilObject2GUI::REPOSITORY_NODE_ID); + } else { + $gui_obj = new $class_name("", $ref_id, true, false); + } + + $gui_obj->setCreationMode(true); + + return $gui_obj; + } + + public static function addFieldsToForm($a_form_id, ilPropertyFormGUI $a_form, ilObjectGUI $a_parent_gui) + { + switch ($a_form_id) { + case self::FORM_SECURITY: + $types = array(self::SETTINGS_GENERAL, self::SETTINGS_USER, self::SETTINGS_FILE, self::SETTINGS_ROLE); + break; + + case self::FORM_PRIVACY: + $types = array(self::SETTINGS_ROLE, self::SETTINGS_FORUM, self::SETTINGS_LRES); + break; + + case self::FORM_FILES_QUOTA: + $types = array(self::SETTINGS_PD); + break; + + case self::FORM_LP: + $types = array(self::SETTINGS_REPOSITORY); + break; + + case self::FORM_ACCESSIBILITY: + $types = array(self::SETTINGS_FORUM, self::SETTINGS_AUTH, self::SETTINGS_WIKI); + break; + + case self::FORM_MAIL: + $types = array(self::SETTINGS_COURSE, self::SETTINGS_GROUP); + break; + + case self::FORM_COURSE: + case self::FORM_GROUP: + $types = array(self::SETTINGS_PRIVACY_SECURITY, self::SETTINGS_CALENDAR, self::SETTINGS_GENERAL); + break; + + case self::FORM_WSP: + $types = array(self::SETTINGS_PORTFOLIO); + break; + + case self::FORM_TAGGING: + $types = array(self::SETTINGS_REPOSITORY); + break; + + case self::FORM_CERTIFICATE: + $types = array(self::SETTINGS_LP_COMPLETION_STATUS); + break; + + default: + $types = null; + break; + } + + if (is_array($types)) { + foreach ($types as $type) { + $gui = self::getSettingsGUIInstance($type); + if ($gui && method_exists($gui, "addToExternalSettingsForm")) { + $data = $gui->addToExternalSettingsForm($a_form_id); + if (is_array($data)) { + self::parseFieldDefinition($type, $a_form, $gui, $data); + } + } + } + } + + // cron jobs - special handling + + include_once "Modules/SystemFolder/classes/class.ilObjSystemFolderGUI.php"; + $parent_gui = new ilObjSystemFolderGUI(null, SYSTEM_FOLDER_ID, true); + $parent_gui->setCreationMode(true); + + include_once "Services/Cron/classes/class.ilCronManagerGUI.php"; + $gui = new ilCronManagerGUI(); + $data = $gui->addToExternalSettingsForm($a_form_id); + if (is_array($data) && sizeof($data)) { + self::parseFieldDefinition("cron", $a_form, $parent_gui, $data); + } + } + + protected static function parseFieldValue($a_field_type, &$a_field_value) + { + global $DIC; + + $lng = $DIC->language(); + + switch ($a_field_type) { + case self::VALUE_BOOL: + $a_field_value = (bool) $a_field_value ? + $lng->txt("enabled") : + $lng->txt("disabled"); + return $a_field_value; + } + + if (!is_numeric($a_field_value) && + $a_field_value !== null && !trim($a_field_value)) { + $a_field_value = "-"; + } + + if (is_numeric($a_field_value) || $a_field_value !== "") { + return true; + } + return false; + } + + protected static function parseFieldDefinition($a_type, ilPropertyFormGUI $a_form, ilObjectGUI $a_gui, $a_data) + { + global $DIC; + + $lng = $DIC->language(); + $rbacsystem = $DIC->rbac()->system(); + $ilCtrl = $DIC->ctrl(); + $ilAccess = $DIC->access(); + + if (!is_array($a_data)) { + return; + } + + // write permission for current gui? + $has_write = $ilAccess->checkAccess("write", "", (int) $_REQUEST["ref_id"]); + + foreach ($a_data as $area_caption => $fields) { + if (is_numeric($area_caption) || !trim($area_caption)) { + $area_caption = "obj_" . $a_type; + } + + if (is_array($fields) && sizeof($fields) == 2) { + $cmd = $fields[0]; + $fields = $fields[1]; + if (is_array($fields)) { + $ftpl = new ilTemplate("tpl.external_settings.html", true, true, "Services/Administration"); + + + $stack = array(); + foreach ($fields as $field_caption_id => $field_value) { + $field_type = $subitems = null; + if (is_array($field_value)) { + $field_type = $field_value[1]; + $subitems = $field_value[2]; + $field_value = $field_value[0]; + } + + if (self::parseFieldValue($field_type, $field_value)) { + $ftpl->setCurrentBlock("value_bl"); + $ftpl->setVariable("VALUE", $field_value); + $ftpl->parseCurrentBlock(); + } + + if (is_array($subitems)) { + $ftpl->setCurrentBlock("subitem_bl"); + foreach ($subitems as $sub_caption_id => $sub_value) { + $sub_type = null; + if (is_array($sub_value)) { + $sub_type = $sub_value[1]; + $sub_value = $sub_value[0]; + } + self::parseFieldValue($sub_type, $sub_value); + + $ftpl->setVariable("SUBKEY", $lng->txt($sub_caption_id)); + $ftpl->setVariable("SUBVALUE", $sub_value); + $ftpl->parseCurrentBlock(); + } + } + + $ftpl->setCurrentBlock("row_bl"); + $ftpl->setVariable("KEY", $lng->txt($field_caption_id)); + $ftpl->parseCurrentBlock(); + } + + if ($has_write && + $rbacsystem->checkAccess("visible,read", $a_gui->object->getRefId())) { + if (!$cmd) { + $cmd = "view"; + } + $ilCtrl->setParameter($a_gui, "ref_id", $a_gui->object->getRefId()); + + $ftpl->setCurrentBlock("edit_bl"); + $ftpl->setVariable("URL_EDIT", $ilCtrl->getLinkTargetByClass(array("ilAdministrationGUI", get_class($a_gui)), $cmd)); + $ftpl->setVariable("TXT_EDIT", $lng->txt("adm_external_setting_edit")); + $ftpl->parseCurrentBlock(); + } + + $ext = new ilCustomInputGUI($lng->txt($area_caption)); + $ext->setHtml($ftpl->get()); + $a_form->addItem($ext); + } + } + } + } +} diff --git a/Services/Administration/classes/class.ilGitInformation.php b/Services/Administration/classes/class.ilGitInformation.php index eefbb76ede3217cd98c45a864e15deccc00f7f9d..796b5eeae9b3d058638b7b145bf704b63759da83 100644 --- a/Services/Administration/classes/class.ilGitInformation.php +++ b/Services/Administration/classes/class.ilGitInformation.php @@ -9,80 +9,70 @@ require_once 'Services/Administration/interfaces/interface.ilVersionControlInfor */ class ilGitInformation implements ilVersionControlInformation { - /** - * @var string - */ - private static $revision_information = null; - - /** - * - */ - private static function detect() - { - global $DIC; - - $lng = $DIC->language(); - - if(null !== self::$revision_information) - { - return self::$revision_information; - } - - $info = array(); - - if(!ilUtil::isWindows()) - { - $version_mini_hash = ilUtil::execQuoted('git rev-parse --short HEAD'); - $version_number = ilUtil::execQuoted('git rev-list --count HEAD'); - $line = ilUtil::execQuoted('git log -1'); - - if($version_number[0]) - { - $version_number = $version_number[0]; - } - - if($version_mini_hash[0]) - { - $version_mini_hash = $version_mini_hash[0]; - } - - if($line && array_filter($line)) - { - $line = implode(' | ', array_filter($line)); - } - } - else - { - $version_mini_hash = trim(exec('git rev-parse --short HEAD')); - $version_number = exec('git rev-list --count HEAD'); - $line = trim(exec('git log -1')); - } - - if($version_number) - { - $info[] = sprintf($lng->txt('git_revision'), $version_number); - } - - if($version_mini_hash) - { - $info[] = sprintf($lng->txt('git_hash_short'), $version_mini_hash); - } - - if($line) - { - $info[] = sprintf($lng->txt('git_last_commit'), $line); - } - - self::$revision_information = $info; - } - - /** - * @return string - */ - public function getInformationAsHtml() - { - self::detect(); - - return implode("
", self::$revision_information); - } + /** + * @var string + */ + private static $revision_information = null; + + /** + * + */ + private static function detect() + { + global $DIC; + + $lng = $DIC->language(); + + if (null !== self::$revision_information) { + return self::$revision_information; + } + + $info = array(); + + if (!ilUtil::isWindows()) { + $version_mini_hash = ilUtil::execQuoted('git rev-parse --short HEAD'); + $version_number = ilUtil::execQuoted('git rev-list --count HEAD'); + $line = ilUtil::execQuoted('git log -1'); + + if ($version_number[0]) { + $version_number = $version_number[0]; + } + + if ($version_mini_hash[0]) { + $version_mini_hash = $version_mini_hash[0]; + } + + if ($line && array_filter($line)) { + $line = implode(' | ', array_filter($line)); + } + } else { + $version_mini_hash = trim(exec('git rev-parse --short HEAD')); + $version_number = exec('git rev-list --count HEAD'); + $line = trim(exec('git log -1')); + } + + if ($version_number) { + $info[] = sprintf($lng->txt('git_revision'), $version_number); + } + + if ($version_mini_hash) { + $info[] = sprintf($lng->txt('git_hash_short'), $version_mini_hash); + } + + if ($line) { + $info[] = sprintf($lng->txt('git_last_commit'), $line); + } + + self::$revision_information = $info; + } + + /** + * @return string + */ + public function getInformationAsHtml() + { + self::detect(); + + return implode("
", self::$revision_information); + } } diff --git a/Services/Administration/classes/class.ilObjExternalToolsSettings.php b/Services/Administration/classes/class.ilObjExternalToolsSettings.php index 7e477fc28fedb706faed9d5547e50823fa6d1d55..cd9a1b45e7d13031e491e33900309ca98e7e96b9 100644 --- a/Services/Administration/classes/class.ilObjExternalToolsSettings.php +++ b/Services/Administration/classes/class.ilObjExternalToolsSettings.php @@ -1,86 +1,83 @@ +* +* @author Sascha Hofmann * @version $Id$ * * @extends ilObject */ class ilObjExternalToolsSettings extends ilObject { - /** - * Constructor - * @access public - * @param integer reference_id or object_id - * @param boolean treat the id as reference_id (true) or object_id (false) - */ - function __construct($a_id = 0,$a_call_by_reference = true) - { - $this->type = "extt"; - parent::__construct($a_id,$a_call_by_reference); - } + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + $this->type = "extt"; + parent::__construct($a_id, $a_call_by_reference); + } - /** - * update object data - * - * @access public - * @return boolean - */ - function update() - { - if (!parent::update()) - { - return false; - } + /** + * update object data + * + * @access public + * @return boolean + */ + public function update() + { + if (!parent::update()) { + return false; + } - // put here object specific stuff - - return true; - } - + // put here object specific stuff + + return true; + } + - /** - * delete object and all related data - * - * @access public - * @return boolean true if all object data were removed; false if only a references were removed - */ - function delete() - { - // always call parent delete function first!! - if (!parent::delete()) - { - return false; - } - - //put here your module specific stuff - - return true; - } + /** + * delete object and all related data + * + * @access public + * @return boolean true if all object data were removed; false if only a references were removed + */ + public function delete() + { + // always call parent delete function first!! + if (!parent::delete()) { + return false; + } + + //put here your module specific stuff + + return true; + } } // END class.ilObjExternalToolsSettings -?> diff --git a/Services/Administration/classes/class.ilObjExternalToolsSettingsAccess.php b/Services/Administration/classes/class.ilObjExternalToolsSettingsAccess.php index 6270ee8f671b58c9e9e9512b720da9e8480228f1..dff123fcb6074dc6667faca1b44f88860af93d12 100644 --- a/Services/Administration/classes/class.ilObjExternalToolsSettingsAccess.php +++ b/Services/Administration/classes/class.ilObjExternalToolsSettingsAccess.php @@ -1,24 +1,24 @@ diff --git a/Services/Administration/classes/class.ilObjExternalToolsSettingsGUI.php b/Services/Administration/classes/class.ilObjExternalToolsSettingsGUI.php index 3cb886533dd065b76c6d02d975824a19d63e4651..3bcb0083766ddee6150cd237a897f7132fa0fc32 100644 --- a/Services/Administration/classes/class.ilObjExternalToolsSettingsGUI.php +++ b/Services/Administration/classes/class.ilObjExternalToolsSettingsGUI.php @@ -8,407 +8,417 @@ require_once "./Services/Object/classes/class.ilObjectGUI.php"; /** * Class ilObjExternalToolsSettingsGUI * -* @author Sascha Hofmann +* @author Sascha Hofmann * @version $Id$ -* +* * @ilCtrl_Calls ilObjExternalToolsSettingsGUI: ilPermissionGUI -* +* * @extends ilObjectGUI */ class ilObjExternalToolsSettingsGUI extends ilObjectGUI { - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilRbacReview - */ - protected $rbacreview; - - /** - * Constructor - * @access public - */ - function __construct($a_data,$a_id,$a_call_by_reference,$a_prepare_output = true) - { - global $DIC; - - $this->lng = $DIC->language(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->access = $DIC->access(); - $this->rbacreview = $DIC->rbac()->review(); - $this->ctrl = $DIC->ctrl(); - $this->tpl = $DIC["tpl"]; - $lng = $DIC->language(); - - $this->type = "extt"; - parent::__construct($a_data,$a_id,$a_call_by_reference,false); - - $lng->loadLanguageModule("delic"); - $lng->loadLanguageModule("maps"); - $lng->loadLanguageModule("mathjax"); - } - - function getAdminTabs() - { - $this->getTabs(); - } - - /** - * get tabs - * @access public - * @param object tabs gui object - */ - function getTabs() - { - $rbacsystem = $this->rbacsystem; - - $this->ctrl->setParameter($this,"ref_id",$this->object->getRefId()); - - if ($rbacsystem->checkAccess("visible,read",$this->object->getRefId())) - { - $this->tabs_gui->addTarget("settings", - $this->ctrl->getLinkTarget($this, "view"), - array("editMaps", "editMathJax", ""), "", ""); - $this->lng->loadLanguageModule('ecs'); - } - - 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'); - } - } - - /** - * Configure MathJax settings - */ - function editMathJaxObject() - { - $ilAccess = $this->access; - $rbacreview = $this->rbacreview; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - - $mathJaxSetting = new ilSetting("MathJax"); - $path_to_mathjax = $mathJaxSetting->get("path_to_mathjax"); - - $this->__initSubTabs("editMathJax"); - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this)); - $form->setTitle($lng->txt("mathjax_settings")); - - // Enable MathJax - $enable = new ilCheckboxInputGUI($lng->txt("mathjax_enable_client"), "enable"); - $enable->setChecked($mathJaxSetting->get("enable")); - $enable->setInfo($lng->txt("mathjax_enable_mathjax_info")."
" - .$lng->txt("mathjax_home_link").""); - $form->addItem($enable); - - // Path to mathjax - $text_prop = new ilTextInputGUI($lng->txt("mathjax_path_to_mathjax"), "path_to_mathjax"); - $text_prop->setInfo($lng->txt("mathjax_path_to_mathjax_desc")); - $text_prop->setValue($path_to_mathjax); - $text_prop->setRequired(true); - $text_prop->setMaxLength(400); - $text_prop->setSize(100); - $enable->addSubItem($text_prop); - - // mathjax limiter - $options = array( - 0 => '\​(...\​)', - 1 => '[tex]...[/tex]', - 2 => '<span class="math">...</span>' - ); - $si = new ilSelectInputGUI($this->lng->txt("mathjax_limiter"), "limiter"); - $si->setOptions($options); - $si->setValue($mathJaxSetting->get("limiter")); - $si->setInfo($this->lng->txt("mathjax_limiter_info")); - $enable->addSubItem($si); - - include_once './Services/MathJax/classes/class.ilMathJax.php'; - $install_link = ' ' - .$lng->txt("mathjax_server_installation").''; - $clear_cache_link = ' ' - .$lng->txt("mathjax_server_clear_cache").''; - - // Enable Server MathJax - $server = new ilCheckboxInputGUI($lng->txt("mathjax_enable_server"), "enable_server"); - $server->setChecked($mathJaxSetting->get("enable_server")); - $server->setInfo($lng->txt("mathjax_enable_server_info").$install_link); - - $form->addItem($server); - - // Path to Server MathJax - $text_prop = new ilTextInputGUI($lng->txt("mathjax_server_address"), "server_address"); - $text_prop->setInfo($lng->txt("mathjax_server_address_info")); - $text_prop->setValue($mathJaxSetting->get("server_address")); - $text_prop->setRequired(true); - $text_prop->setMaxLength(400); - $text_prop->setSize(100); - $server->addSubItem($text_prop); - - // Server Timeout - $number_prop = new ilNumberInputGUI($lng->txt("mathjax_server_timeout"), "server_timeout"); - $number_prop->setInfo($lng->txt("mathjax_server_timeout_info")); - $number_prop->setValue($mathJaxSetting->get("server_timeout") ? (int) $mathJaxSetting->get("server_timeout") : 5); - $number_prop->setRequired(true); - $number_prop->setSize(3); - $server->addSubItem($number_prop); - - // Server for Browser - $checkbox = new ilCheckboxInputGUI($lng->txt("mathjax_server_for_browser"),"server_for_browser"); - $checkbox->setInfo($lng->txt("mathjax_server_for_browser_info")); - $checkbox->setChecked((bool) $mathJaxSetting->get("server_for_browser")); - $server->addSubItem($checkbox); - - // Server for HTML Export - $checkbox = new ilCheckboxInputGUI($lng->txt("mathjax_server_for_export"),"server_for_export"); - $checkbox->setInfo($lng->txt("mathjax_server_for_export_info")); - $checkbox->setChecked((bool) $mathJaxSetting->get("server_for_export")); - $server->addSubItem($checkbox); - - // Server for PDF - $checkbox = new ilCheckboxInputGUI($lng->txt("mathjax_server_for_pdf"),"server_for_pdf"); - $checkbox->setInfo($lng->txt("mathjax_server_for_pdf_info")); - $checkbox->setChecked((bool) $mathJaxSetting->get("server_for_pdf")); - $server->addSubItem($checkbox); - - // Cache Size / Clear Cache - $size = new ilNonEditableValueGUI($lng->txt("mathjax_server_cache_size")); - $size->setInfo($lng->txt("mathjax_server_cache_size_info") . $clear_cache_link); - $size->setValue(ilMathJax::getInstance()->getCacheSize()); - $server->addSubItem($size); - - // Test expression - $test = new ilCustomInputGUI($lng->txt("mathjax_test_expression")); - include_once './Services/MathJax/classes/class.ilMathJax.php'; - $html = ilMathJax::getInstance()->insertLatexImages('[tex]f(x)=\int_{-\infty}^x e^{-t^2}dt[/tex]'); - $test->setHtml($html); - $test->setInfo($lng->txt('mathjax_test_expression_info')); - $form->addItem($test); - - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - $form->addCommandButton("saveMathJax", $lng->txt("save")); - } - - $tpl->setVariable("ADM_CONTENT", $form->getHTML()); - } - - /** - * Save MathJax Setttings - */ - function saveMathJaxObject() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilAccess = $this->access; - - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - $mathJaxSetting = new ilSetting("MathJax"); - // Client settings - $path_to_mathjax = ilUtil::stripSlashes($_POST["path_to_mathjax"]); - if ($_POST["enable"]) - { - $mathJaxSetting->set("path_to_mathjax", $path_to_mathjax); - $mathJaxSetting->set("limiter", (int) $_POST["limiter"]); - } - $mathJaxSetting->set("enable", ilUtil::stripSlashes($_POST["enable"])); - - // Server settings - if ($_POST["enable_server"]) - { - $mathJaxSetting->set("server_address",ilUtil::stripSlashes($_POST["server_address"])); - $mathJaxSetting->set("server_timeout", (int) ilUtil::stripSlashes($_POST["server_timeout"])); - $mathJaxSetting->set("server_for_browser", (bool) ilUtil::stripSlashes($_POST["server_for_browser"])); - $mathJaxSetting->set("server_for_export", (bool) ilUtil::stripSlashes($_POST["server_for_export"])); - $mathJaxSetting->set("server_for_pdf", (bool) ilUtil::stripSlashes($_POST["server_for_pdf"])); - } - $mathJaxSetting->set("enable_server", (bool) ilUtil::stripSlashes($_POST["enable_server"])); - - ilUtil::sendInfo($lng->txt("msg_obj_modified")); - } - $ilCtrl->redirect($this, "editMathJax"); - } - - /** - * Clear the directory with cached LaTeX graphics - */ - function clearMathJaxCacheObject() - { - $lng = $this->lng; - - include_once './Services/MathJax/classes/class.ilMathJax.php'; - ilMathJax::getInstance()->clearCache(); - - ilUtil::sendSuccess($lng->txt('mathjax_server_cache_cleared'), true); - $this->ctrl->redirect($this, 'editMathJax'); - } - - /** - * Configure maps settings - * - * @access public - */ - function editMapsObject() - { - require_once("Services/Maps/classes/class.ilMapUtil.php"); - - $ilAccess = $this->access; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - - $this->__initSubTabs("editMaps"); - $std_latitude = ilMapUtil::getStdLatitude(); - $std_longitude = ilMapUtil::getStdLongitude(); - $std_zoom = ilMapUtil::getStdZoom(); - $type = ilMapUtil::getType(); - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - include_once("./Services/Form/classes/class.ilCheckboxOption.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this)); - $form->setTitle($lng->txt("maps_settings")); - - // Enable Maps - $enable = new ilCheckboxInputGUI($lng->txt("maps_enable_maps"), "enable"); - $enable->setChecked(ilMapUtil::isActivated()); - $enable->setInfo($lng->txt("maps_enable_maps_info")); - $form->addItem($enable); - - // Select type - $types = new ilSelectInputGUI($lng->txt("maps_map_type"), "type"); - $types->setOptions(ilMapUtil::getAvailableMapTypes()); - $types->setValue($type); - $form->addItem($types); - - // map data server property - if($type == "openlayers") { - $tile = new ilTextInputGUI($lng->txt("maps_tile_server"),"tile"); - $tile->setValue(ilMapUtil::getStdTileServers()); - $tile->setInfo(sprintf($lng->txt("maps_custom_tile_server_info"),ilMapUtil::DEFAULT_TILE)); - $geolocation = new ilTextInputGUI($lng->txt("maps_geolocation_server"),"geolocation"); - $geolocation->setValue(ilMapUtil::getStdGeolocationServer()); - $geolocation->setInfo($lng->txt("maps_custom_geolocation_server_info")); - - $form->addItem($tile); - $form->addItem($geolocation); - } else { - // api key for google - $key = new ilTextInputGUI("Google API Key", "api_key"); - $key->setMaxLength(200); - $key->setValue(ilMapUtil::getApiKey()); - $form->addItem($key); - } - - // location property - $loc_prop = new ilLocationInputGUI($lng->txt("maps_std_location"), - "std_location"); - - $loc_prop->setLatitude($std_latitude); - $loc_prop->setLongitude($std_longitude); - $loc_prop->setZoom($std_zoom); - $form->addItem($loc_prop); - - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - $form->addCommandButton("saveMaps", $lng->txt("save")); - $form->addCommandButton("view", $lng->txt("cancel")); - } - - $tpl->setVariable("ADM_CONTENT", $form->getHTML()); - } - - - /** - * Save Maps Setttings - */ - function saveMapsObject() - { - require_once("Services/Maps/classes/class.ilMapUtil.php"); - - $ilCtrl = $this->ctrl; - if(ilUtil::stripSlashes($_POST["type"]) == 'openlayers' && 'openlayers' == ilMapUtil::getType()) { - ilMapUtil::setStdTileServers(ilUtil::stripSlashes($_POST["tile"])); - ilMapUtil::setStdGeolocationServer(ilUtil::stripSlashes($_POST["geolocation"])); - } else { - ilMapUtil::setApiKey(ilUtil::stripSlashes(trim($_POST["api_key"]))); - } - - ilMapUtil::setActivated(ilUtil::stripSlashes($_POST["enable"]) == "1"); - ilMapUtil::setType(ilUtil::stripSlashes($_POST["type"])); - ilMapUtil::setStdLatitude(ilUtil::stripSlashes($_POST["std_location"]["latitude"])); - ilMapUtil::setStdLongitude(ilUtil::stripSlashes($_POST["std_location"]["longitude"])); - ilMapUtil::setStdZoom(ilUtil::stripSlashes($_POST["std_location"]["zoom"])); - $ilCtrl->redirect($this, "editMaps"); - } - - // init sub tabs - function __initSubTabs($a_cmd) - { - $maps = ($a_cmd == 'editMaps') ? true : false; - $mathjax = ($a_cmd == 'editMathJax') ? true : false; - - $this->tabs_gui->addSubTabTarget("maps_extt_maps", $this->ctrl->getLinkTarget($this, "editMaps"), - "", "", "", $maps); - $this->tabs_gui->addSubTabTarget("mathjax_mathjax", $this->ctrl->getLinkTarget($this, "editMathJax"), - "", "", "", $mathjax); - } - - function executeCommand() - { - $ilAccess = $this->access; - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - $this->prepareOutput(); - - if (!$ilAccess->checkAccess("read", "", $this->object->getRefId())) - { - $this->ilias->raiseError($this->lng->txt("permission_denied"),$this->ilias->error_obj->MESSAGE); - } - - switch($next_class) - { - case 'ilecssettingsgui': - $this->tabs_gui->setTabActive('ecs_server_settings'); - include_once('./Services/WebServices/ECS/classes/class.ilECSSettingsGUI.php'); - $this->ctrl->forwardCommand(new ilECSSettingsGUI()); - break; - - case 'ilpermissiongui': - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $ret =& $this->ctrl->forwardCommand($perm_gui); - $this->tabs_gui->setTabActive('perm_settings'); - break; - - default: - $this->tabs_gui->setTabActive('settings'); - if(!$cmd || $cmd == 'view') - { - $cmd = "editMaps"; - } - $cmd .= "Object"; - $this->$cmd(); - - break; - } - return true; - } - + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilRbacReview + */ + protected $rbacreview; + + /** + * Constructor + * @access public + */ + public function __construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output = true) + { + global $DIC; + + $this->lng = $DIC->language(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->access = $DIC->access(); + $this->rbacreview = $DIC->rbac()->review(); + $this->ctrl = $DIC->ctrl(); + $this->tpl = $DIC["tpl"]; + $lng = $DIC->language(); + + $this->type = "extt"; + parent::__construct($a_data, $a_id, $a_call_by_reference, false); + + $lng->loadLanguageModule("delic"); + $lng->loadLanguageModule("maps"); + $lng->loadLanguageModule("mathjax"); + } + + public function getAdminTabs() + { + $this->getTabs(); + } + + /** + * get tabs + * @access public + * @param object tabs gui object + */ + public function getTabs() + { + $rbacsystem = $this->rbacsystem; + + $this->ctrl->setParameter($this, "ref_id", $this->object->getRefId()); + + if ($rbacsystem->checkAccess("visible,read", $this->object->getRefId())) { + $this->tabs_gui->addTarget( + "settings", + $this->ctrl->getLinkTarget($this, "view"), + array("editMaps", "editMathJax", ""), + "", + "" + ); + $this->lng->loadLanguageModule('ecs'); + } + + 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' + ); + } + } + + /** + * Configure MathJax settings + */ + public function editMathJaxObject() + { + $ilAccess = $this->access; + $rbacreview = $this->rbacreview; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + + $mathJaxSetting = new ilSetting("MathJax"); + $path_to_mathjax = $mathJaxSetting->get("path_to_mathjax"); + + $this->__initSubTabs("editMathJax"); + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this)); + $form->setTitle($lng->txt("mathjax_settings")); + + // Enable MathJax + $enable = new ilCheckboxInputGUI($lng->txt("mathjax_enable_client"), "enable"); + $enable->setChecked($mathJaxSetting->get("enable")); + $enable->setInfo($lng->txt("mathjax_enable_mathjax_info") . " " + . $lng->txt("mathjax_home_link") . ""); + $form->addItem($enable); + + // Path to mathjax + $text_prop = new ilTextInputGUI($lng->txt("mathjax_path_to_mathjax"), "path_to_mathjax"); + $text_prop->setInfo($lng->txt("mathjax_path_to_mathjax_desc")); + $text_prop->setValue($path_to_mathjax); + $text_prop->setRequired(true); + $text_prop->setMaxLength(400); + $text_prop->setSize(100); + $enable->addSubItem($text_prop); + + // mathjax limiter + $options = array( + 0 => '\​(...\​)', + 1 => '[tex]...[/tex]', + 2 => '<span class="math">...</span>' + ); + $si = new ilSelectInputGUI($this->lng->txt("mathjax_limiter"), "limiter"); + $si->setOptions($options); + $si->setValue($mathJaxSetting->get("limiter")); + $si->setInfo($this->lng->txt("mathjax_limiter_info")); + $enable->addSubItem($si); + + include_once './Services/MathJax/classes/class.ilMathJax.php'; + $install_link = ' ' + . $lng->txt("mathjax_server_installation") . ''; + $clear_cache_link = ' ' + . $lng->txt("mathjax_server_clear_cache") . ''; + + // Enable Server MathJax + $server = new ilCheckboxInputGUI($lng->txt("mathjax_enable_server"), "enable_server"); + $server->setChecked($mathJaxSetting->get("enable_server")); + $server->setInfo($lng->txt("mathjax_enable_server_info") . $install_link); + + $form->addItem($server); + + // Path to Server MathJax + $text_prop = new ilTextInputGUI($lng->txt("mathjax_server_address"), "server_address"); + $text_prop->setInfo($lng->txt("mathjax_server_address_info")); + $text_prop->setValue($mathJaxSetting->get("server_address")); + $text_prop->setRequired(true); + $text_prop->setMaxLength(400); + $text_prop->setSize(100); + $server->addSubItem($text_prop); + + // Server Timeout + $number_prop = new ilNumberInputGUI($lng->txt("mathjax_server_timeout"), "server_timeout"); + $number_prop->setInfo($lng->txt("mathjax_server_timeout_info")); + $number_prop->setValue($mathJaxSetting->get("server_timeout") ? (int) $mathJaxSetting->get("server_timeout") : 5); + $number_prop->setRequired(true); + $number_prop->setSize(3); + $server->addSubItem($number_prop); + + // Server for Browser + $checkbox = new ilCheckboxInputGUI($lng->txt("mathjax_server_for_browser"), "server_for_browser"); + $checkbox->setInfo($lng->txt("mathjax_server_for_browser_info")); + $checkbox->setChecked((bool) $mathJaxSetting->get("server_for_browser")); + $server->addSubItem($checkbox); + + // Server for HTML Export + $checkbox = new ilCheckboxInputGUI($lng->txt("mathjax_server_for_export"), "server_for_export"); + $checkbox->setInfo($lng->txt("mathjax_server_for_export_info")); + $checkbox->setChecked((bool) $mathJaxSetting->get("server_for_export")); + $server->addSubItem($checkbox); + + // Server for PDF + $checkbox = new ilCheckboxInputGUI($lng->txt("mathjax_server_for_pdf"), "server_for_pdf"); + $checkbox->setInfo($lng->txt("mathjax_server_for_pdf_info")); + $checkbox->setChecked((bool) $mathJaxSetting->get("server_for_pdf")); + $server->addSubItem($checkbox); + + // Cache Size / Clear Cache + $size = new ilNonEditableValueGUI($lng->txt("mathjax_server_cache_size")); + $size->setInfo($lng->txt("mathjax_server_cache_size_info") . $clear_cache_link); + $size->setValue(ilMathJax::getInstance()->getCacheSize()); + $server->addSubItem($size); + + // Test expression + $test = new ilCustomInputGUI($lng->txt("mathjax_test_expression")); + include_once './Services/MathJax/classes/class.ilMathJax.php'; + $html = ilMathJax::getInstance()->insertLatexImages('[tex]f(x)=\int_{-\infty}^x e^{-t^2}dt[/tex]'); + $test->setHtml($html); + $test->setInfo($lng->txt('mathjax_test_expression_info')); + $form->addItem($test); + + if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) { + $form->addCommandButton("saveMathJax", $lng->txt("save")); + } + + $tpl->setVariable("ADM_CONTENT", $form->getHTML()); + } + + /** + * Save MathJax Setttings + */ + public function saveMathJaxObject() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilAccess = $this->access; + + if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) { + $mathJaxSetting = new ilSetting("MathJax"); + // Client settings + $path_to_mathjax = ilUtil::stripSlashes($_POST["path_to_mathjax"]); + if ($_POST["enable"]) { + $mathJaxSetting->set("path_to_mathjax", $path_to_mathjax); + $mathJaxSetting->set("limiter", (int) $_POST["limiter"]); + } + $mathJaxSetting->set("enable", ilUtil::stripSlashes($_POST["enable"])); + + // Server settings + if ($_POST["enable_server"]) { + $mathJaxSetting->set("server_address", ilUtil::stripSlashes($_POST["server_address"])); + $mathJaxSetting->set("server_timeout", (int) ilUtil::stripSlashes($_POST["server_timeout"])); + $mathJaxSetting->set("server_for_browser", (bool) ilUtil::stripSlashes($_POST["server_for_browser"])); + $mathJaxSetting->set("server_for_export", (bool) ilUtil::stripSlashes($_POST["server_for_export"])); + $mathJaxSetting->set("server_for_pdf", (bool) ilUtil::stripSlashes($_POST["server_for_pdf"])); + } + $mathJaxSetting->set("enable_server", (bool) ilUtil::stripSlashes($_POST["enable_server"])); + + ilUtil::sendInfo($lng->txt("msg_obj_modified")); + } + $ilCtrl->redirect($this, "editMathJax"); + } + + /** + * Clear the directory with cached LaTeX graphics + */ + public function clearMathJaxCacheObject() + { + $lng = $this->lng; + + include_once './Services/MathJax/classes/class.ilMathJax.php'; + ilMathJax::getInstance()->clearCache(); + + ilUtil::sendSuccess($lng->txt('mathjax_server_cache_cleared'), true); + $this->ctrl->redirect($this, 'editMathJax'); + } + + /** + * Configure maps settings + * + * @access public + */ + public function editMapsObject() + { + require_once("Services/Maps/classes/class.ilMapUtil.php"); + + $ilAccess = $this->access; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + + $this->__initSubTabs("editMaps"); + $std_latitude = ilMapUtil::getStdLatitude(); + $std_longitude = ilMapUtil::getStdLongitude(); + $std_zoom = ilMapUtil::getStdZoom(); + $type = ilMapUtil::getType(); + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + include_once("./Services/Form/classes/class.ilCheckboxOption.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this)); + $form->setTitle($lng->txt("maps_settings")); + + // Enable Maps + $enable = new ilCheckboxInputGUI($lng->txt("maps_enable_maps"), "enable"); + $enable->setChecked(ilMapUtil::isActivated()); + $enable->setInfo($lng->txt("maps_enable_maps_info")); + $form->addItem($enable); + + // Select type + $types = new ilSelectInputGUI($lng->txt("maps_map_type"), "type"); + $types->setOptions(ilMapUtil::getAvailableMapTypes()); + $types->setValue($type); + $form->addItem($types); + + // map data server property + if ($type == "openlayers") { + $tile = new ilTextInputGUI($lng->txt("maps_tile_server"), "tile"); + $tile->setValue(ilMapUtil::getStdTileServers()); + $tile->setInfo(sprintf($lng->txt("maps_custom_tile_server_info"), ilMapUtil::DEFAULT_TILE)); + $geolocation = new ilTextInputGUI($lng->txt("maps_geolocation_server"), "geolocation"); + $geolocation->setValue(ilMapUtil::getStdGeolocationServer()); + $geolocation->setInfo($lng->txt("maps_custom_geolocation_server_info")); + + $form->addItem($tile); + $form->addItem($geolocation); + } else { + // api key for google + $key = new ilTextInputGUI("Google API Key", "api_key"); + $key->setMaxLength(200); + $key->setValue(ilMapUtil::getApiKey()); + $form->addItem($key); + } + + // location property + $loc_prop = new ilLocationInputGUI( + $lng->txt("maps_std_location"), + "std_location" + ); + + $loc_prop->setLatitude($std_latitude); + $loc_prop->setLongitude($std_longitude); + $loc_prop->setZoom($std_zoom); + $form->addItem($loc_prop); + + if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) { + $form->addCommandButton("saveMaps", $lng->txt("save")); + $form->addCommandButton("view", $lng->txt("cancel")); + } + + $tpl->setVariable("ADM_CONTENT", $form->getHTML()); + } + + + /** + * Save Maps Setttings + */ + public function saveMapsObject() + { + require_once("Services/Maps/classes/class.ilMapUtil.php"); + + $ilCtrl = $this->ctrl; + if (ilUtil::stripSlashes($_POST["type"]) == 'openlayers' && 'openlayers' == ilMapUtil::getType()) { + ilMapUtil::setStdTileServers(ilUtil::stripSlashes($_POST["tile"])); + ilMapUtil::setStdGeolocationServer(ilUtil::stripSlashes($_POST["geolocation"])); + } else { + ilMapUtil::setApiKey(ilUtil::stripSlashes(trim($_POST["api_key"]))); + } + + ilMapUtil::setActivated(ilUtil::stripSlashes($_POST["enable"]) == "1"); + ilMapUtil::setType(ilUtil::stripSlashes($_POST["type"])); + ilMapUtil::setStdLatitude(ilUtil::stripSlashes($_POST["std_location"]["latitude"])); + ilMapUtil::setStdLongitude(ilUtil::stripSlashes($_POST["std_location"]["longitude"])); + ilMapUtil::setStdZoom(ilUtil::stripSlashes($_POST["std_location"]["zoom"])); + $ilCtrl->redirect($this, "editMaps"); + } + + // init sub tabs + public function __initSubTabs($a_cmd) + { + $maps = ($a_cmd == 'editMaps') ? true : false; + $mathjax = ($a_cmd == 'editMathJax') ? true : false; + + $this->tabs_gui->addSubTabTarget( + "maps_extt_maps", + $this->ctrl->getLinkTarget($this, "editMaps"), + "", + "", + "", + $maps + ); + $this->tabs_gui->addSubTabTarget( + "mathjax_mathjax", + $this->ctrl->getLinkTarget($this, "editMathJax"), + "", + "", + "", + $mathjax + ); + } + + public function executeCommand() + { + $ilAccess = $this->access; + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + $this->prepareOutput(); + + if (!$ilAccess->checkAccess("read", "", $this->object->getRefId())) { + $this->ilias->raiseError($this->lng->txt("permission_denied"), $this->ilias->error_obj->MESSAGE); + } + + switch ($next_class) { + case 'ilecssettingsgui': + $this->tabs_gui->setTabActive('ecs_server_settings'); + include_once('./Services/WebServices/ECS/classes/class.ilECSSettingsGUI.php'); + $this->ctrl->forwardCommand(new ilECSSettingsGUI()); + break; + + case 'ilpermissiongui': + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $ret =&$this->ctrl->forwardCommand($perm_gui); + $this->tabs_gui->setTabActive('perm_settings'); + break; + + default: + $this->tabs_gui->setTabActive('settings'); + if (!$cmd || $cmd == 'view') { + $cmd = "editMaps"; + } + $cmd .= "Object"; + $this->$cmd(); + + break; + } + return true; + } } // END class.ilObjExternalToolsSettingsGUI -?> diff --git a/Services/Administration/classes/class.ilObjRecoveryFolder.php b/Services/Administration/classes/class.ilObjRecoveryFolder.php index d6762cdd025214919a1b3042099a4a1c46f1c27a..03a2b4c1217d99e034a299c18515182a91fe6a85 100755 --- a/Services/Administration/classes/class.ilObjRecoveryFolder.php +++ b/Services/Administration/classes/class.ilObjRecoveryFolder.php @@ -1,24 +1,24 @@ +* +* @author Sascha Hofmann * @version $Id$ * * @extends ilObject */ class ilObjRecoveryFolder extends ilObject { - /** - * Constructor - * @access public - * @param integer reference_id or object_id - * @param boolean treat the id as reference_id (true) or object_id (false) - */ - function __construct($a_id = 0,$a_call_by_reference = true) - { - $this->type = "recf"; - parent::__construct($a_id,$a_call_by_reference); - } - - /** - * update object data - * - * @access public - * @return boolean - */ - function update() - { - if (!parent::update()) - { - return false; - } + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + $this->type = "recf"; + parent::__construct($a_id, $a_call_by_reference); + } - // put here object specific stuff - - return true; - } - + /** + * update object data + * + * @access public + * @return boolean + */ + public function update() + { + if (!parent::update()) { + return false; + } - /** - * delete object and all related data - * - * @access public - * @return boolean true if all object data were removed; false if only a references were removed - */ - function delete() - { - // always call parent delete function first!! - if (!parent::delete()) - { - return false; - } - - //put here your module specific stuff - - return true; - } + // put here object specific stuff + + return true; + } + + /** + * delete object and all related data + * + * @access public + * @return boolean true if all object data were removed; false if only a references were removed + */ + public function delete() + { + // always call parent delete function first!! + if (!parent::delete()) { + return false; + } + + //put here your module specific stuff + + return true; + } } // END class.ilObjRecoveryFolder -?> diff --git a/Services/Administration/classes/class.ilObjRecoveryFolderAccess.php b/Services/Administration/classes/class.ilObjRecoveryFolderAccess.php index 429428b14645f035253dd1ee67afbf900d53e864..7886bd9420db1fcaaa0f1bc7ec94eed8b6d348cf 100644 --- a/Services/Administration/classes/class.ilObjRecoveryFolderAccess.php +++ b/Services/Administration/classes/class.ilObjRecoveryFolderAccess.php @@ -1,24 +1,24 @@ diff --git a/Services/Administration/classes/class.ilObjRecoveryFolderGUI.php b/Services/Administration/classes/class.ilObjRecoveryFolderGUI.php index 58dc64673bfb2040ace82c3d3a9aeaa390b71e8d..e200e144a5a39f0019a485290eb601ee71dddf0a 100755 --- a/Services/Administration/classes/class.ilObjRecoveryFolderGUI.php +++ b/Services/Administration/classes/class.ilObjRecoveryFolderGUI.php @@ -1,24 +1,24 @@ +* @author Sascha Hofmann * @version $Id$ * * @ilCtrl_Calls ilObjRecoveryFolderGUI: ilPermissionGUI @@ -35,103 +35,99 @@ require_once "./Services/Container/classes/class.ilContainerGUI.php"; */ class ilObjRecoveryFolderGUI extends ilContainerGUI { - /** - * @var ilRbacAdmin - */ - protected $rbacadmin; + /** + * @var ilRbacAdmin + */ + protected $rbacadmin; - /** - * @var ilRbacSystem - */ - protected $rbacsystem; + /** + * @var ilRbacSystem + */ + protected $rbacsystem; - /** - * Constructor - * @access public - */ - function __construct($a_data,$a_id,$a_call_by_reference) - { - global $DIC; + /** + * Constructor + * @access public + */ + public function __construct($a_data, $a_id, $a_call_by_reference) + { + global $DIC; - $this->rbacadmin = $DIC->rbac()->admin(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->type = "recf"; - parent::__construct($a_data,$a_id,$a_call_by_reference,false); - } - - /** - * save object - * @access public - */ - function saveObject() - { - $rbacadmin = $this->rbacadmin; + $this->rbacadmin = $DIC->rbac()->admin(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->type = "recf"; + parent::__construct($a_data, $a_id, $a_call_by_reference, false); + } + + /** + * save object + * @access public + */ + public function saveObject() + { + $rbacadmin = $this->rbacadmin; - // create and insert forum in objecttree - $newObj = parent::saveObject(); + // create and insert forum in objecttree + $newObj = parent::saveObject(); - // put here object specific stuff - - // always send a message - ilUtil::sendSuccess($this->lng->txt("object_added"),true); - exit(); - } + // put here object specific stuff + + // always send a message + ilUtil::sendSuccess($this->lng->txt("object_added"), true); + exit(); + } - function removeFromSystemObject() - { - $rbacsystem = $this->rbacsystem; - - include_once("./Services/Repository/classes/class.ilRepUtilGUI.php"); - $ru = new ilRepUtilGUI($this); - $ru->removeObjectsFromSystem($_POST["id"], true); - $this->ctrl->redirect($this, "view"); - } - - function executeCommand() - { - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - $this->prepareOutput(); + public function removeFromSystemObject() + { + $rbacsystem = $this->rbacsystem; + + include_once("./Services/Repository/classes/class.ilRepUtilGUI.php"); + $ru = new ilRepUtilGUI($this); + $ru->removeObjectsFromSystem($_POST["id"], true); + $this->ctrl->redirect($this, "view"); + } + + public function executeCommand() + { + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + $this->prepareOutput(); - switch($next_class) - { - case 'ilpermissiongui': - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $ret =& $this->ctrl->forwardCommand($perm_gui); - break; + switch ($next_class) { + case 'ilpermissiongui': + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $ret =&$this->ctrl->forwardCommand($perm_gui); + break; - default: - if(!$cmd) - { - $cmd = "view"; - } - $cmd .= "Object"; - $this->$cmd(); + default: + if (!$cmd) { + $cmd = "view"; + } + $cmd .= "Object"; + $this->$cmd(); - break; - } - return true; - } - - - function showPossibleSubObjects() - { - $this->sub_objects = ""; - } - - /** - * Get Actions - */ - function getActions() - { - // standard actions for container - return array( - "cut" => array("name" => "cut", "lng" => "cut"), - "clear" => array("name" => "clear", "lng" => "clear"), - "removeFromSystem" => array("name" => "removeFromSystem", "lng" => "btn_remove_system") - ); - } + break; + } + return true; + } + + public function showPossibleSubObjects() + { + $this->sub_objects = ""; + } + + /** + * Get Actions + */ + public function getActions() + { + // standard actions for container + return array( + "cut" => array("name" => "cut", "lng" => "cut"), + "clear" => array("name" => "clear", "lng" => "clear"), + "removeFromSystem" => array("name" => "removeFromSystem", "lng" => "btn_remove_system") + ); + } } // END class.ilObjRecoveryFolderGUI -?> diff --git a/Services/Administration/classes/class.ilSetting.php b/Services/Administration/classes/class.ilSetting.php index 4b2313dcfcfb01155d7883f3757301b5b089f841..145ec7317d3ca6989740f8a95ea3a53a4e404bb0 100644 --- a/Services/Administration/classes/class.ilSetting.php +++ b/Services/Administration/classes/class.ilSetting.php @@ -1,24 +1,24 @@ db = $DIC->database(); - $ilDB = $DIC->database(); - - $this->cache_disabled = $a_disabled_cache; - $this->module = $a_module; - // check whether ini file object exists - if (!is_object($ilDB)) - { - die ("Fatal Error: ilSettings object instantiated without DB initialisation."); - } - $this->read(); - } - - /** - * Get currernt module - */ - public function getModule() - { - return $this->module; - } - - /** - * Read settings data - */ - function read() - { - $ilDB = $this->db; - - // get the settings from the cache if they exist. - // The setting array of the class is a reference to the cache. - // So changing settings in one instance will change them in all. - // This is the same behaviour as if the are read from the DB. - if (!$this->cache_disabled) - { - if (isset(self::$settings_cache[$this->module])) - { - $this->setting =& self::$settings_cache[$this->module]; - return; - } - else - { - $this->setting = array(); - self::$settings_cache[$this->module] =& $this->setting; - } - } - - $query = "SELECT * FROM settings WHERE module=".$ilDB->quote($this->module, "text"); - $res = $ilDB->query($query); - - while ($row = $ilDB->fetchAssoc($res)) - { - $this->setting[$row["keyword"]] = $row["value"]; - } - - } - - /** - * get setting - * - * @access public - * - * @param string keyword - * @param string default_value This value is returned, when no setting has + /** + * @var ilDB + */ + protected $db; + + /** + * cache for the read settings + * ilSetting is instantiated more than once per request for some modules + * The cache avoids reading them from the DB with each instance + */ + private static $settings_cache = array(); + + /** + * the type of settings value field in database + * This is determined in the set method to get a correct DB insert + * Don't set the value type to force a detection at first access + */ + private static $value_type = null; + + + public $setting = array(); + public $module = ""; + + /** + * Initialize settings + */ + public function __construct($a_module = "common", $a_disabled_cache = false) + { + global $DIC; + + $this->db = $DIC->database(); + $ilDB = $DIC->database(); + + $this->cache_disabled = $a_disabled_cache; + $this->module = $a_module; + // check whether ini file object exists + if (!is_object($ilDB)) { + die("Fatal Error: ilSettings object instantiated without DB initialisation."); + } + $this->read(); + } + + /** + * Get currernt module + */ + public function getModule() + { + return $this->module; + } + + /** + * Read settings data + */ + public function read() + { + $ilDB = $this->db; + + // get the settings from the cache if they exist. + // The setting array of the class is a reference to the cache. + // So changing settings in one instance will change them in all. + // This is the same behaviour as if the are read from the DB. + if (!$this->cache_disabled) { + if (isset(self::$settings_cache[$this->module])) { + $this->setting =&self::$settings_cache[$this->module]; + return; + } else { + $this->setting = array(); + self::$settings_cache[$this->module] =&$this->setting; + } + } + + $query = "SELECT * FROM settings WHERE module=" . $ilDB->quote($this->module, "text"); + $res = $ilDB->query($query); + + while ($row = $ilDB->fetchAssoc($res)) { + $this->setting[$row["keyword"]] = $row["value"]; + } + } + + /** + * get setting + * + * @access public + * + * @param string keyword + * @param string default_value This value is returned, when no setting has * been found for the keyword. - * @return string value - */ - function get($a_keyword, $a_default_value = false) - { - if ($a_keyword == "ilias_version") - { - return ILIAS_VERSION; - } - - if (isset($this->setting[$a_keyword])) - { - return $this->setting[$a_keyword]; - } - else - { - return $a_default_value; - } - } - - /** - * Delete all settings of a current module - * - * @access public - * - */ - public function deleteAll() - { - $ilDB = $this->db; - - $query = "DELETE FROM settings WHERE module = ".$ilDB->quote($this->module, "text"); - $ilDB->manipulate($query); - - $this->setting = array(); - - return true; - } - - /** - * Delete all settings corresponding to a like string - * - * @access public - * - */ - public function deleteLike($a_like) - { - $ilDB = $this->db; - - $query = "SELECT keyword FROM settings". - " WHERE module = ".$ilDB->quote($this->module, "text"). - " AND ".$ilDB->like("keyword", "text", $a_like); - $res = $ilDB->query($query); - while($row = $ilDB->fetchAssoc($res)) - { - $this->delete($row["keyword"]); - } - - return true; - } - - /** - * delete one value from settingstable - * @access public - * @param string keyword - * @return string value - */ - function delete($a_keyword) - { - $ilDB = $this->db; - - $st = $ilDB->manipulate("DELETE FROM settings WHERE keyword = ". - $ilDB->quote($a_keyword, "text")." AND module = ". - $ilDB->quote($this->module, "text")); - - unset($this->setting[$a_keyword]); - - return true; - } - - - - /** - * read all values from settingstable - * @access public - * @return array keyword/value pairs - */ - function getAll() - { - return $this->setting; - } - - /** - * write one value to db-table settings - * @access public - * @param string keyword - * @param string value - * @return boolean true on success - */ - function set($a_key, $a_val) - { - global $DIC; - - $lng = $DIC["lng"]; - $ilDB = $this->db; - - $this->delete($a_key); - - if (!isset(self::$value_type)) - { - self::$value_type = self::_getValueType(); - } - - if (self::$value_type == 'text' and strlen($a_val) >= 4000) - { - ilUtil::sendFailure($lng->txt('setting_value_truncated'), true); - $a_val = substr($a_val, 0, 4000); - } - - $ilDB->insert("settings", array( - "module" => array("text", $this->module), - "keyword" => array("text", $a_key), - "value" => array(self::$value_type, $a_val))); - - $this->setting[$a_key] = $a_val; - - return true; - } - - function setScormDebug($a_key, $a_val) - { - $ilDB = $this->db; - if ($a_val != "1") { - $ilDB->query("UPDATE sahs_lm SET debug = 'n'"); - } - $setreturn = ilSetting::set($a_key, $a_val); - return $setreturn; - } - - public static function _lookupValue($a_module, $a_keyword) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT value FROM settings WHERE module = %s AND keyword = %s"; - $res = $ilDB->queryF($query, array('text', 'text'), array($a_module, $a_keyword)); - $data = $ilDB->fetchAssoc($res); - return $data['value']; - } - - /** - * Get the type of the value column in the database - * - * @return string 'text' or 'clob' - * @throws ilDatabaseException - */ - public static function _getValueType() - { - include_once ('./Services/Database/classes/class.ilDBAnalyzer.php'); - $analyzer = new ilDBAnalyzer(); - $info = $analyzer->getFieldInformation('settings'); - - if ($info['value']['type'] == 'clob') - { - return 'clob'; - } - else - { - return 'text'; - } - } - - - /** - * change the type of the value column in the database - * - * @param string 'text' or 'clob' - * @return bolean type changed or not - */ + * @return string value + */ + public function get($a_keyword, $a_default_value = false) + { + if ($a_keyword == "ilias_version") { + return ILIAS_VERSION; + } + + if (isset($this->setting[$a_keyword])) { + return $this->setting[$a_keyword]; + } else { + return $a_default_value; + } + } + + /** + * Delete all settings of a current module + * + * @access public + * + */ + public function deleteAll() + { + $ilDB = $this->db; + + $query = "DELETE FROM settings WHERE module = " . $ilDB->quote($this->module, "text"); + $ilDB->manipulate($query); + + $this->setting = array(); + + return true; + } + + /** + * Delete all settings corresponding to a like string + * + * @access public + * + */ + public function deleteLike($a_like) + { + $ilDB = $this->db; + + $query = "SELECT keyword FROM settings" . + " WHERE module = " . $ilDB->quote($this->module, "text") . + " AND " . $ilDB->like("keyword", "text", $a_like); + $res = $ilDB->query($query); + while ($row = $ilDB->fetchAssoc($res)) { + $this->delete($row["keyword"]); + } + + return true; + } + + /** + * delete one value from settingstable + * @access public + * @param string keyword + * @return string value + */ + public function delete($a_keyword) + { + $ilDB = $this->db; + + $st = $ilDB->manipulate("DELETE FROM settings WHERE keyword = " . + $ilDB->quote($a_keyword, "text") . " AND module = " . + $ilDB->quote($this->module, "text")); + + unset($this->setting[$a_keyword]); + + return true; + } + + + + /** + * read all values from settingstable + * @access public + * @return array keyword/value pairs + */ + public function getAll() + { + return $this->setting; + } + + /** + * write one value to db-table settings + * @access public + * @param string keyword + * @param string value + * @return boolean true on success + */ + public function set($a_key, $a_val) + { + global $DIC; + + $lng = $DIC["lng"]; + $ilDB = $this->db; + + $this->delete($a_key); + + if (!isset(self::$value_type)) { + self::$value_type = self::_getValueType(); + } + + if (self::$value_type == 'text' and strlen($a_val) >= 4000) { + ilUtil::sendFailure($lng->txt('setting_value_truncated'), true); + $a_val = substr($a_val, 0, 4000); + } + + $ilDB->insert("settings", array( + "module" => array("text", $this->module), + "keyword" => array("text", $a_key), + "value" => array(self::$value_type, $a_val))); + + $this->setting[$a_key] = $a_val; + + return true; + } + + public function setScormDebug($a_key, $a_val) + { + $ilDB = $this->db; + if ($a_val != "1") { + $ilDB->query("UPDATE sahs_lm SET debug = 'n'"); + } + $setreturn = ilSetting::set($a_key, $a_val); + return $setreturn; + } + + public static function _lookupValue($a_module, $a_keyword) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT value FROM settings WHERE module = %s AND keyword = %s"; + $res = $ilDB->queryF($query, array('text', 'text'), array($a_module, $a_keyword)); + $data = $ilDB->fetchAssoc($res); + return $data['value']; + } + + /** + * Get the type of the value column in the database + * + * @return string 'text' or 'clob' + * @throws ilDatabaseException + */ + public static function _getValueType() + { + include_once('./Services/Database/classes/class.ilDBAnalyzer.php'); + $analyzer = new ilDBAnalyzer(); + $info = $analyzer->getFieldInformation('settings'); + + if ($info['value']['type'] == 'clob') { + return 'clob'; + } else { + return 'text'; + } + } + + + /** + * change the type of the value column in the database + * + * @param string 'text' or 'clob' + * @return bolean type changed or not + */ public static function _changeValueType($a_new_type = 'text') - { - global $DIC; - - $ilDB = $DIC->database(); - - $old_type = self::_getValueType(); - - if ($a_new_type == $old_type) - { - return false; - } - elseif ($a_new_type == 'clob') - { - $ilDB->addTableColumn('settings','value2', - array( "type" => "clob", - "notnull" => false, - "default" => NULL)); - - $ilDB->query("UPDATE settings SET value2 = value"); - $ilDB->dropTableColumn('settings','value'); - $ilDB->renameTableColumn('settings','value2','value'); - - return true; - } - elseif ($a_new_type == 'text') - { - $ilDB->addTableColumn('settings','value2', - array( "type" => "text", - "length" => 4000, - "notnull" => false, - "default" => NULL)); - - $ilDB->query("UPDATE settings SET value2 = value"); - $ilDB->dropTableColumn('settings','value'); - $ilDB->renameTableColumn('settings','value2','value'); - - return true; - } - else - { - return false; - } - } - - - /** - * get a list of setting records with values loger than a limit - * - * @param int character limit (default: 4000) - * @return array records with longer values - */ + { + global $DIC; + + $ilDB = $DIC->database(); + + $old_type = self::_getValueType(); + + if ($a_new_type == $old_type) { + return false; + } elseif ($a_new_type == 'clob') { + $ilDB->addTableColumn( + 'settings', + 'value2', + array( "type" => "clob", + "notnull" => false, + "default" => null) + ); + + $ilDB->query("UPDATE settings SET value2 = value"); + $ilDB->dropTableColumn('settings', 'value'); + $ilDB->renameTableColumn('settings', 'value2', 'value'); + + return true; + } elseif ($a_new_type == 'text') { + $ilDB->addTableColumn( + 'settings', + 'value2', + array( "type" => "text", + "length" => 4000, + "notnull" => false, + "default" => null) + ); + + $ilDB->query("UPDATE settings SET value2 = value"); + $ilDB->dropTableColumn('settings', 'value'); + $ilDB->renameTableColumn('settings', 'value2', 'value'); + + return true; + } else { + return false; + } + } + + + /** + * get a list of setting records with values loger than a limit + * + * @param int character limit (default: 4000) + * @return array records with longer values + */ public static function _getLongerSettings($a_limit = '4000') - { - global $DIC; + { + global $DIC; - $ilDB = $DIC->database(); + $ilDB = $DIC->database(); - $settings = array(); + $settings = array(); - $query = "SELECT * FROM settings WHERE LENGTH(value) > " - . $ilDB->quote($a_limit, 'integer'); + $query = "SELECT * FROM settings WHERE LENGTH(value) > " + . $ilDB->quote($a_limit, 'integer'); - $result = $ilDB->query($query); + $result = $ilDB->query($query); - while ($row = $ilDB->fetchAssoc($result)) - { - $settings[] = $row; - } + while ($row = $ilDB->fetchAssoc($result)) { + $settings[] = $row; + } - return $settings; - } + return $settings; + } } -?> diff --git a/Services/Administration/classes/class.ilSettingsTemplate.php b/Services/Administration/classes/class.ilSettingsTemplate.php index 5b90a9c250c6ec8d3e941a54ee20b472cf80f573..7e70353d699f3fa3840353b7d7a3b9ebf6c04f05 100644 --- a/Services/Administration/classes/class.ilSettingsTemplate.php +++ b/Services/Administration/classes/class.ilSettingsTemplate.php @@ -10,487 +10,491 @@ */ class ilSettingsTemplate { - /** - * @var ilDB - */ - protected $db; - - private $id; - private $type; - private $title; - private $description; - private $setting = array(); - private $hidden_tab = array(); - - // begin-patch loc - private $auto_generated = false; - // end-patch loc - - /** - * - * @var ilSettingsTemplateConfig - */ - private $config; - - /** - * Constructor - * - * @param - */ - function __construct($a_id = 0, $config = null) - { - global $DIC; - - $this->db = $DIC->database(); - if ($a_id > 0) - { - if ($config) - $this->setConfig($config); - $this->setId($a_id); - $this->read(); - } - } - - /** - * Set id - * - * @param integer id - */ - function setId($a_val) - { - $this->id = $a_val; - } - - /** - * Get id - * - * @return integer id - */ - function getId() - { - return $this->id; - } - - // begin-patch lok - /** - * Set auto generated status - * @param type $a_status - */ - public function setAutoGenerated($a_status) - { - $this->auto_generated = $a_status; - } - - /** - * Get auto generated status - * @return type - */ - public function getAutoGenerated() - { - return $this->auto_generated; - } - // end-patch lok - - /** - * Set title - * - * @param string title - */ - function setTitle($a_val) - { - $this->title = $a_val; - } - - /** - * Get title - * - * @return string title - */ - function getTitle() - { - return $this->title; - } - - /** - * Set type - * - * @param string $a_val type - */ - public function setType($a_val) - { - $this->type = $a_val; - } - - /** - * Get type - * - * @return string type - */ - public function getType() - { - return $this->type; - } - - /** - * Set description - * - * @param string $a_val description - */ - public function setDescription($a_val) - { - $this->description = $a_val; - } - - /** - * Get description - * - * @return string description - */ - public function getDescription() - { - return $this->description; - } - - /** - * Set setting - * - * @param string setting - * @param mixed value - * @param boolean hide the setting? - */ - function setSetting($a_setting, $a_value, $a_hide = false) - { - if ($this->getConfig()) { - $settings = $this->getConfig()->getSettings(); - - if ($settings[$a_setting]['type'] == ilSettingsTemplateConfig::CHECKBOX) { - if (is_array($a_value)) - $a_value = serialize($a_value); - else - $a_value = unserialize($a_value); - } + /** + * @var ilDB + */ + protected $db; + + private $id; + private $type; + private $title; + private $description; + private $setting = array(); + private $hidden_tab = array(); + + // begin-patch loc + private $auto_generated = false; + // end-patch loc + + /** + * + * @var ilSettingsTemplateConfig + */ + private $config; + + /** + * Constructor + * + * @param + */ + public function __construct($a_id = 0, $config = null) + { + global $DIC; + + $this->db = $DIC->database(); + if ($a_id > 0) { + if ($config) { + $this->setConfig($config); + } + $this->setId($a_id); + $this->read(); + } + } + + /** + * Set id + * + * @param integer id + */ + public function setId($a_val) + { + $this->id = $a_val; + } + + /** + * Get id + * + * @return integer id + */ + public function getId() + { + return $this->id; + } + + // begin-patch lok + /** + * Set auto generated status + * @param type $a_status + */ + public function setAutoGenerated($a_status) + { + $this->auto_generated = $a_status; + } + + /** + * Get auto generated status + * @return type + */ + public function getAutoGenerated() + { + return $this->auto_generated; + } + // end-patch lok + + /** + * Set title + * + * @param string title + */ + public function setTitle($a_val) + { + $this->title = $a_val; + } + + /** + * Get title + * + * @return string title + */ + public function getTitle() + { + return $this->title; + } + + /** + * Set type + * + * @param string $a_val type + */ + public function setType($a_val) + { + $this->type = $a_val; + } + + /** + * Get type + * + * @return string type + */ + public function getType() + { + return $this->type; + } + + /** + * Set description + * + * @param string $a_val description + */ + public function setDescription($a_val) + { + $this->description = $a_val; + } + + /** + * Get description + * + * @return string description + */ + public function getDescription() + { + return $this->description; + } + + /** + * Set setting + * + * @param string setting + * @param mixed value + * @param boolean hide the setting? + */ + public function setSetting($a_setting, $a_value, $a_hide = false) + { + if ($this->getConfig()) { + $settings = $this->getConfig()->getSettings(); + + if ($settings[$a_setting]['type'] == ilSettingsTemplateConfig::CHECKBOX) { + if (is_array($a_value)) { + $a_value = serialize($a_value); + } else { + $a_value = unserialize($a_value); } - - $this->setting[$a_setting] = array( - "value" => $a_value, - "hide" => $a_hide - ); - } - - /** - * Remove setting - * - * @param string setting - */ - function removeSetting($a_setting) - { - unset($this->setting[$a_setting]); - } - - /** - * Remove all settings - */ - function removeAllSettings() - { - $this->setting = array(); - } - - /** - * Get settings - */ - function getSettings() - { - return $this->setting; - } - - /** - * Add hidden tab - * - * @param string tab id - * @return - */ - function addHiddenTab($a_tab_id) - { - $this->hidden_tab[$a_tab_id] = $a_tab_id; - } - - /** - * Remove all hidden tabs - */ - function removeAllHiddenTabs() - { - $this->hidden_tab = array(); - } - - /** - * Get hidden tabs - */ - function getHiddenTabs() - { - return $this->hidden_tab; - } - - /** - * Returns the template config associated with this template or NULL if - * none is given. - * - * @return ilSettingsTemplateConfig - */ - public function getConfig() { - return $this->config; + } } - /** - * Sets the template config for this template - * - * @param ilSettingsTemplateConfig $config - */ - public function setConfig(ilSettingsTemplateConfig $config) { - $this->config = $config; + $this->setting[$a_setting] = array( + "value" => $a_value, + "hide" => $a_hide + ); + } + + /** + * Remove setting + * + * @param string setting + */ + public function removeSetting($a_setting) + { + unset($this->setting[$a_setting]); + } + + /** + * Remove all settings + */ + public function removeAllSettings() + { + $this->setting = array(); + } + + /** + * Get settings + */ + public function getSettings() + { + return $this->setting; + } + + /** + * Add hidden tab + * + * @param string tab id + * @return + */ + public function addHiddenTab($a_tab_id) + { + $this->hidden_tab[$a_tab_id] = $a_tab_id; + } + + /** + * Remove all hidden tabs + */ + public function removeAllHiddenTabs() + { + $this->hidden_tab = array(); + } + + /** + * Get hidden tabs + */ + public function getHiddenTabs() + { + return $this->hidden_tab; + } + + /** + * Returns the template config associated with this template or NULL if + * none is given. + * + * @return ilSettingsTemplateConfig + */ + public function getConfig() + { + return $this->config; + } + + /** + * Sets the template config for this template + * + * @param ilSettingsTemplateConfig $config + */ + public function setConfig(ilSettingsTemplateConfig $config) + { + $this->config = $config; + } + + + /** + * Read + * + * @param + * @return + */ + public function read() + { + $ilDB = $this->db; + + // read template + $set = $ilDB->query( + "SELECT * FROM adm_settings_template WHERE " . + " id = " . $ilDB->quote($this->getId(), "integer") + ); + $rec = $ilDB->fetchAssoc($set); + $this->setTitle($rec["title"]); + $this->setType($rec["type"]); + $this->setDescription($rec["description"]); + // begin-patch lok + $this->setAutoGenerated($rec['auto_generated']); + // end-patch lok + + // read template setttings + $set = $ilDB->query( + "SELECT * FROM adm_set_templ_value WHERE " . + " template_id = " . $ilDB->quote($this->getId(), "integer") + ); + while ($rec = $ilDB->fetchAssoc($set)) { + $this->setSetting( + $rec["setting"], + $rec["value"], + $rec["hide"] + ); } + // read hidden tabs + $set = $ilDB->query( + "SELECT * FROM adm_set_templ_hide_tab WHERE " . + " template_id = " . $ilDB->quote($this->getId(), "integer") + ); + while ($rec = $ilDB->fetchAssoc($set)) { + $this->addHiddenTab($rec["tab_id"]); + } + } + + /** + * Create settings template + */ + public function create() + { + $ilDB = $this->db; + + $this->setId($ilDB->nextId("adm_settings_template")); + + // write template + $ilDB->insert("adm_settings_template", array( + "id" => array("integer", $this->getId()), + "title" => array("text", $this->getTitle()), + "type" => array("text", $this->getType()), + // begin-patch lok + "description" => array("clob", $this->getDescription()), + 'auto_generated' => array('integer',$this->getAutoGenerated()) + // end-patch lok + )); + + // write settings + $this->insertSettings(); + + // write hidden tabs + $this->insertHiddenTabs(); + } + + /** + * Update settings template + */ + public function update() + { + $ilDB = $this->db; + + // update template + $ilDB->update("adm_settings_template", array( + "title" => array("text", $this->getTitle()), + "type" => array("text", $this->getType()), + // begin-patch lok + "description" => array("clob", $this->getDescription()), + 'auto_generated' => array('integer',$this->getAutoGenerated()) + ), array( + "id" => array("integer", $this->getId()), + )); + + // delete settings and hidden tabs + $ilDB->manipulate( + "DELETE FROM adm_set_templ_value WHERE " + . " template_id = " . $ilDB->quote($this->getId(), "integer") + ); + $ilDB->manipulate( + "DELETE FROM adm_set_templ_hide_tab WHERE " + . " template_id = " . $ilDB->quote($this->getId(), "integer") + ); + + // insert settings and hidden tabs + $this->insertSettings(); + $this->insertHiddenTabs(); + } + + /** + * Insert settings to db + */ + private function insertSettings() + { + $ilDB = $this->db; + + foreach ($this->getSettings() as $s => $set) { + $ilDB->manipulate("INSERT INTO adm_set_templ_value " . + "(template_id, setting, value, hide) VALUES (" . + $ilDB->quote($this->getId(), "integer") . "," . + $ilDB->quote($s, "text") . "," . + $ilDB->quote($set["value"], "text") . "," . + $ilDB->quote($set["hide"], "integer") . + ")"); + } + } + + /** + * Insert hidden tabs + */ + public function insertHiddenTabs() + { + $ilDB = $this->db; + + foreach ($this->getHiddenTabs() as $tab_id) { + $ilDB->manipulate("INSERT INTO adm_set_templ_hide_tab " . + "(template_id, tab_id) VALUES (" . + $ilDB->quote($this->getId(), "integer") . "," . + $ilDB->quote($tab_id, "text") . + ")"); + } + } + + /** + * Delete settings template + */ + public function delete() + { + $ilDB = $this->db; + + $ilDB->manipulate( + "DELETE FROM adm_settings_template WHERE " + . " id = " . $ilDB->quote($this->getId(), "integer") + ); + $ilDB->manipulate( + "DELETE FROM adm_set_templ_value WHERE " + . " template_id = " . $ilDB->quote($this->getId(), "integer") + ); + $ilDB->manipulate( + "DELETE FROM adm_set_templ_hide_tab WHERE " + . " template_id = " . $ilDB->quote($this->getId(), "integer") + ); + } + + /** + * Get all settings templates of type + * + * @param string $a_type object type + */ + public static function getAllSettingsTemplates($a_type, $a_include_auto_generated = false) + { + global $DIC; + + $ilDB = $DIC->database(); + + // begin-patch lok + if ($a_include_auto_generated) { + $set = $ilDB->query("SELECT * FROM adm_settings_template " . + " WHERE type = " . $ilDB->quote($a_type, "text") . + " ORDER BY title"); + } else { + $set = $ilDB->query("SELECT * FROM adm_settings_template " . + " WHERE type = " . $ilDB->quote($a_type, "text") . + 'AND auto_generated = ' . $ilDB->quote(0, 'integer') . ' ' . + " ORDER BY title"); + } + // end-patch lok + - /** - * Read - * - * @param - * @return - */ - function read() - { - $ilDB = $this->db; - - // read template - $set = $ilDB->query("SELECT * FROM adm_settings_template WHERE ". - " id = ".$ilDB->quote($this->getId(), "integer") - ); - $rec = $ilDB->fetchAssoc($set); - $this->setTitle($rec["title"]); - $this->setType($rec["type"]); - $this->setDescription($rec["description"]); - // begin-patch lok - $this->setAutoGenerated($rec['auto_generated']); - // end-patch lok - - // read template setttings - $set = $ilDB->query("SELECT * FROM adm_set_templ_value WHERE ". - " template_id = ".$ilDB->quote($this->getId(), "integer") - ); - while ($rec = $ilDB->fetchAssoc($set)) - { - $this->setSetting($rec["setting"], - $rec["value"], $rec["hide"]); - } - - // read hidden tabs - $set = $ilDB->query("SELECT * FROM adm_set_templ_hide_tab WHERE ". - " template_id = ".$ilDB->quote($this->getId(), "integer") - ); - while ($rec = $ilDB->fetchAssoc($set)) - { - $this->addHiddenTab($rec["tab_id"]); - } - } - - /** - * Create settings template - */ - function create() - { - $ilDB = $this->db; - - $this->setId($ilDB->nextId("adm_settings_template")); - - // write template - $ilDB->insert("adm_settings_template", array( - "id" => array("integer", $this->getId()), - "title" => array("text", $this->getTitle()), - "type" => array("text", $this->getType()), - // begin-patch lok - "description" => array("clob", $this->getDescription()), - 'auto_generated' => array('integer',$this->getAutoGenerated()) - // end-patch lok - )); - - // write settings - $this->insertSettings(); - - // write hidden tabs - $this->insertHiddenTabs(); - } - - /** - * Update settings template - */ - public function update() - { - $ilDB = $this->db; - - // update template - $ilDB->update("adm_settings_template", array( - "title" => array("text", $this->getTitle()), - "type" => array("text", $this->getType()), - // begin-patch lok - "description" => array("clob", $this->getDescription()), - 'auto_generated' => array('integer',$this->getAutoGenerated()) - ), array( - "id" => array("integer", $this->getId()), - )); - - // delete settings and hidden tabs - $ilDB->manipulate("DELETE FROM adm_set_templ_value WHERE " - ." template_id = ".$ilDB->quote($this->getId(), "integer") - ); - $ilDB->manipulate("DELETE FROM adm_set_templ_hide_tab WHERE " - ." template_id = ".$ilDB->quote($this->getId(), "integer") - ); - - // insert settings and hidden tabs - $this->insertSettings(); - $this->insertHiddenTabs(); - - } - - /** - * Insert settings to db - */ - private function insertSettings() - { - $ilDB = $this->db; - - foreach ($this->getSettings() as $s => $set) - { - $ilDB->manipulate("INSERT INTO adm_set_templ_value ". - "(template_id, setting, value, hide) VALUES (". - $ilDB->quote($this->getId(), "integer").",". - $ilDB->quote($s, "text").",". - $ilDB->quote($set["value"], "text").",". - $ilDB->quote($set["hide"], "integer"). - ")"); - } - } - - /** - * Insert hidden tabs - */ - function insertHiddenTabs() - { - $ilDB = $this->db; - - foreach ($this->getHiddenTabs() as $tab_id) - { - $ilDB->manipulate("INSERT INTO adm_set_templ_hide_tab ". - "(template_id, tab_id) VALUES (". - $ilDB->quote($this->getId(), "integer").",". - $ilDB->quote($tab_id, "text"). - ")"); - } - } - - /** - * Delete settings template - */ - function delete() - { - $ilDB = $this->db; - - $ilDB->manipulate("DELETE FROM adm_settings_template WHERE " - ." id = ".$ilDB->quote($this->getId(), "integer") - ); - $ilDB->manipulate("DELETE FROM adm_set_templ_value WHERE " - ." template_id = ".$ilDB->quote($this->getId(), "integer") - ); - $ilDB->manipulate("DELETE FROM adm_set_templ_hide_tab WHERE " - ." template_id = ".$ilDB->quote($this->getId(), "integer") - ); - } - - /** - * Get all settings templates of type - * - * @param string $a_type object type - */ - static function getAllSettingsTemplates($a_type, $a_include_auto_generated = false) - { - global $DIC; - - $ilDB = $DIC->database(); - - // begin-patch lok - if($a_include_auto_generated) - { - $set = $ilDB->query("SELECT * FROM adm_settings_template ". - " WHERE type = ".$ilDB->quote($a_type, "text"). - " ORDER BY title"); - } - else - { - $set = $ilDB->query("SELECT * FROM adm_settings_template ". - " WHERE type = ".$ilDB->quote($a_type, "text"). - 'AND auto_generated = '.$ilDB->quote(0,'integer').' '. - " ORDER BY title"); - } - // end-patch lok - - - $settings_template = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $settings_template[] = $rec; - } - return $settings_template; - } - - /** - * Lookup property - * - * @param id level id - * @return mixed property value - */ - protected static function lookupProperty($a_id, $a_prop) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT $a_prop FROM adm_settings_template WHERE ". - " id = ".$ilDB->quote($a_id, "integer") - ); - $rec = $ilDB->fetchAssoc($set); - return $rec[$a_prop]; - } - - // begin-patch lok - /** - * Lookup title - * - * @param - * @return - */ - static function lookupTitle($a_id) - { - return self::lookupProperty($a_id, 'title'); - } - /** - * Lookup title - * - * @param - * @return - */ - static function lookupDescription($a_id) - { - return self::lookupProperty($a_id, 'description'); - } - - // begin-patch lok - public static function translate($a_title_desc) - { - if(substr($a_title_desc, 0, 3) == 'il_') - { - return $GLOBALS['lng']->txt($a_title_desc); - } - return $a_title_desc; - } - // end-patch lok + $settings_template = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $settings_template[] = $rec; + } + return $settings_template; + } + + /** + * Lookup property + * + * @param id level id + * @return mixed property value + */ + protected static function lookupProperty($a_id, $a_prop) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT $a_prop FROM adm_settings_template WHERE " . + " id = " . $ilDB->quote($a_id, "integer") + ); + $rec = $ilDB->fetchAssoc($set); + return $rec[$a_prop]; + } + + // begin-patch lok + /** + * Lookup title + * + * @param + * @return + */ + public static function lookupTitle($a_id) + { + return self::lookupProperty($a_id, 'title'); + } + /** + * Lookup title + * + * @param + * @return + */ + public static function lookupDescription($a_id) + { + return self::lookupProperty($a_id, 'description'); + } + + // begin-patch lok + public static function translate($a_title_desc) + { + if (substr($a_title_desc, 0, 3) == 'il_') { + return $GLOBALS['lng']->txt($a_title_desc); + } + return $a_title_desc; + } + // end-patch lok } -?> diff --git a/Services/Administration/classes/class.ilSettingsTemplateConfig.php b/Services/Administration/classes/class.ilSettingsTemplateConfig.php index dc57609cd20dc5bf82e0bdc31cc541711bd407dd..5c9ff7ccfcd940190039f415e437108fad33a829 100644 --- a/Services/Administration/classes/class.ilSettingsTemplateConfig.php +++ b/Services/Administration/classes/class.ilSettingsTemplateConfig.php @@ -10,93 +10,91 @@ */ class ilSettingsTemplateConfig { - private $type; - private $tab = array(); - private $setting = array(); + private $type; + private $tab = array(); + private $setting = array(); - const TEXT = "text"; - const SELECT = "select"; - const BOOL = "bool"; - const CHECKBOX = "check"; + const TEXT = "text"; + const SELECT = "select"; + const BOOL = "bool"; + const CHECKBOX = "check"; - /** - * Constructor - * - * @param string object type - */ - function __construct($a_obj_type) - { - $this->setType($a_obj_type); - } + /** + * Constructor + * + * @param string object type + */ + public function __construct($a_obj_type) + { + $this->setType($a_obj_type); + } - /** - * Set type - * - * @param string $a_val type - */ - public function setType($a_val) - { - $this->type = $a_val; - } + /** + * Set type + * + * @param string $a_val type + */ + public function setType($a_val) + { + $this->type = $a_val; + } - /** - * Get type - * - * @return string type - */ - public function getType() - { - return $this->type; - } + /** + * Get type + * + * @return string type + */ + public function getType() + { + return $this->type; + } - /** - * Add hidable tabs - * - * @param int tab id - * @param string tab text - */ - function addHidableTab($a_tab_id, $a_text) - { - $this->tabs[$a_tab_id] = array( - "id" => $a_tab_id, - "text" => $a_text - ); - } + /** + * Add hidable tabs + * + * @param int tab id + * @param string tab text + */ + public function addHidableTab($a_tab_id, $a_text) + { + $this->tabs[$a_tab_id] = array( + "id" => $a_tab_id, + "text" => $a_text + ); + } - /** - * Get hidable tabs - */ - function getHidableTabs() - { - return $this->tabs; - } + /** + * Get hidable tabs + */ + public function getHidableTabs() + { + return $this->tabs; + } - /** - * Add setting - * - * @param - * @return - */ - function addSetting($a_id, $a_type, $a_text, $a_hidable, $a_length = 0, $a_options = array()) - { - $this->setting[$a_id] = array( - "id" => $a_id, - "type" => $a_type, - "text" => $a_text, - "hidable" => $a_hidable, - "length" => $a_length, - "options" => $a_options - ); - } + /** + * Add setting + * + * @param + * @return + */ + public function addSetting($a_id, $a_type, $a_text, $a_hidable, $a_length = 0, $a_options = array()) + { + $this->setting[$a_id] = array( + "id" => $a_id, + "type" => $a_type, + "text" => $a_text, + "hidable" => $a_hidable, + "length" => $a_length, + "options" => $a_options + ); + } - /** - * Get settings - * @return - */ - function getSettings() - { - return $this->setting; - } + /** + * Get settings + * @return + */ + public function getSettings() + { + return $this->setting; + } } - -?> diff --git a/Services/Administration/classes/class.ilSettingsTemplateGUI.php b/Services/Administration/classes/class.ilSettingsTemplateGUI.php index aeb60c08419b9445494e6b479f6a05b618a3d8ed..e091379489b7acacc70b8974fe19988438674d42 100644 --- a/Services/Administration/classes/class.ilSettingsTemplateGUI.php +++ b/Services/Administration/classes/class.ilSettingsTemplateGUI.php @@ -12,445 +12,423 @@ include_once("./Services/Administration/classes/class.ilSettingsTemplate.php"); */ class ilSettingsTemplateGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilLanguage - */ - protected $lng; - - private $config; - - /** - * Constructor - * - * @param - * @return - */ - function __construct($a_config) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->tpl = $DIC["tpl"]; - $this->toolbar = $DIC->toolbar(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - - $ilCtrl->saveParameter($this, array("templ_id")); - - $this->setConfig($a_config); - - $this->readSettingsTemplate(); - } - - /** - * Execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - - $cmd = $ilCtrl->getCmd("listSettingsTemplates"); - $this->$cmd(); - } - - /** - * Set config object - * - * @param object $a_val config object - */ - public function setConfig($a_val) - { - $this->config = $a_val; - } - - /** - * Get config object - * - * @return object config object - */ - public function getConfig() - { - return $this->config; - } - - /** - * Read settings template - * - * @param - * @return - */ - function readSettingsTemplate() - { - if ($this->getConfig()) { - $this->settings_template = new ilSettingsTemplate((int) $_GET["templ_id"], $this->getConfig()); - } - else { - $this->settings_template = new ilSettingsTemplate((int) $_GET["templ_id"]); - } - } - - /** - * List all settings template - * - * @param - * @return - */ - function listSettingsTemplates() - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $ilToolbar->addButton($lng->txt("adm_add_settings_template"), - $ilCtrl->getLinkTarget($this, "addSettingsTemplate")); - - include_once("./Services/Administration/classes/class.ilSettingsTemplateTableGUI.php"); - $table = new ilSettingsTemplateTableGUI($this, "listSettingsTemplates", - $this->getConfig()->getType()); - - $tpl->setContent($table->getHTML()); - } - - /** - * Add settings template - */ - function addSettingsTemplate() - { - $tpl = $this->tpl; - - $this->initSettingsTemplateForm("create"); - $tpl->setContent($this->form->getHTML()); - } - - /** - * Edit settings template - */ - function editSettingsTemplate() - { - $tpl = $this->tpl; - - $this->initSettingsTemplateForm("edit"); - $this->getSettingsTemplateValues(); - $tpl->setContent($this->form->getHTML()); - } - - /** - * Init settings template form. - * - * @param int $a_mode Edit Mode - */ - public function initSettingsTemplateForm($a_mode = "edit") - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - // title - $ti = new ilTextInputGUI($lng->txt("title"), "title"); - $ti->setMaxLength(200); - $ti->setRequired(true); - // begin-patch lok - if($this->settings_template->getAutoGenerated()) - { - $ti->setDisabled(true); - } - // end-patch lok - $this->form->addItem($ti); - - // description - $ti = new ilTextAreaInputGUI($lng->txt("description"), "description"); - // begin-patch lok - if($this->settings_template->getAutoGenerated()) - { - $ti->setDisabled(true); - } - $this->form->addItem($ti); - - // hidable tabs - $tabs = $this->getConfig()->getHidableTabs(); - if (is_array($tabs) && count($tabs) > 0) - { - $sec = new ilFormSectionHeaderGUI(); - $sec->setTitle($lng->txt("adm_hide_tabs")); - $this->form->addItem($sec); - - foreach($tabs as $t) - { - // hide tab $t? - $cb = new ilCheckboxInputGUI($t["text"], "tab_".$t["id"]); - $this->form->addItem($cb); - } - } - - // settings - $settings = $this->getConfig()->getSettings(); - if (is_array($settings) && count($settings) > 0) - { - $sec = new ilFormSectionHeaderGUI(); - $sec->setTitle($lng->txt("adm_predefined_settings")); - $this->form->addItem($sec); - - foreach($settings as $s) - { - // setting - $cb = new ilCheckboxInputGUI($s["text"], "set_".$s["id"]); - $this->form->addItem($cb); - - switch ($s["type"]) - { - case ilSettingsTemplateConfig::TEXT: - - $ti = new ilTextInputGUI($lng->txt("adm_value"), "value_".$s["id"]); - //$ti->setMaxLength(); - //$ti->setSize(); - $cb->addSubItem($ti); - break; - - case ilSettingsTemplateConfig::BOOL: - $cb2 = new ilCheckboxInputGUI($lng->txt("adm_value"), "value_".$s["id"]); - $cb->addSubItem($cb2); - break; - - case ilSettingsTemplateConfig::SELECT: - $si = new ilSelectInputGUI($lng->txt("adm_value"), "value_".$s["id"]); - $si->setOptions($s["options"]); - $cb->addSubItem($si); - break; + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilLanguage + */ + protected $lng; + + private $config; + + /** + * Constructor + * + * @param + * @return + */ + public function __construct($a_config) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->tpl = $DIC["tpl"]; + $this->toolbar = $DIC->toolbar(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + + $ilCtrl->saveParameter($this, array("templ_id")); + + $this->setConfig($a_config); + + $this->readSettingsTemplate(); + } + + /** + * Execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $cmd = $ilCtrl->getCmd("listSettingsTemplates"); + $this->$cmd(); + } + + /** + * Set config object + * + * @param object $a_val config object + */ + public function setConfig($a_val) + { + $this->config = $a_val; + } + + /** + * Get config object + * + * @return object config object + */ + public function getConfig() + { + return $this->config; + } + + /** + * Read settings template + * + * @param + * @return + */ + public function readSettingsTemplate() + { + if ($this->getConfig()) { + $this->settings_template = new ilSettingsTemplate((int) $_GET["templ_id"], $this->getConfig()); + } else { + $this->settings_template = new ilSettingsTemplate((int) $_GET["templ_id"]); + } + } + + /** + * List all settings template + * + * @param + * @return + */ + public function listSettingsTemplates() + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $ilToolbar->addButton( + $lng->txt("adm_add_settings_template"), + $ilCtrl->getLinkTarget($this, "addSettingsTemplate") + ); + + include_once("./Services/Administration/classes/class.ilSettingsTemplateTableGUI.php"); + $table = new ilSettingsTemplateTableGUI( + $this, + "listSettingsTemplates", + $this->getConfig()->getType() + ); + + $tpl->setContent($table->getHTML()); + } + + /** + * Add settings template + */ + public function addSettingsTemplate() + { + $tpl = $this->tpl; + + $this->initSettingsTemplateForm("create"); + $tpl->setContent($this->form->getHTML()); + } + + /** + * Edit settings template + */ + public function editSettingsTemplate() + { + $tpl = $this->tpl; + + $this->initSettingsTemplateForm("edit"); + $this->getSettingsTemplateValues(); + $tpl->setContent($this->form->getHTML()); + } + + /** + * Init settings template form. + * + * @param int $a_mode Edit Mode + */ + public function initSettingsTemplateForm($a_mode = "edit") + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + // title + $ti = new ilTextInputGUI($lng->txt("title"), "title"); + $ti->setMaxLength(200); + $ti->setRequired(true); + // begin-patch lok + if ($this->settings_template->getAutoGenerated()) { + $ti->setDisabled(true); + } + // end-patch lok + $this->form->addItem($ti); + + // description + $ti = new ilTextAreaInputGUI($lng->txt("description"), "description"); + // begin-patch lok + if ($this->settings_template->getAutoGenerated()) { + $ti->setDisabled(true); + } + $this->form->addItem($ti); + + // hidable tabs + $tabs = $this->getConfig()->getHidableTabs(); + if (is_array($tabs) && count($tabs) > 0) { + $sec = new ilFormSectionHeaderGUI(); + $sec->setTitle($lng->txt("adm_hide_tabs")); + $this->form->addItem($sec); + + foreach ($tabs as $t) { + // hide tab $t? + $cb = new ilCheckboxInputGUI($t["text"], "tab_" . $t["id"]); + $this->form->addItem($cb); + } + } + + // settings + $settings = $this->getConfig()->getSettings(); + if (is_array($settings) && count($settings) > 0) { + $sec = new ilFormSectionHeaderGUI(); + $sec->setTitle($lng->txt("adm_predefined_settings")); + $this->form->addItem($sec); + + foreach ($settings as $s) { + // setting + $cb = new ilCheckboxInputGUI($s["text"], "set_" . $s["id"]); + $this->form->addItem($cb); + + switch ($s["type"]) { + case ilSettingsTemplateConfig::TEXT: + + $ti = new ilTextInputGUI($lng->txt("adm_value"), "value_" . $s["id"]); + //$ti->setMaxLength(); + //$ti->setSize(); + $cb->addSubItem($ti); + break; + + case ilSettingsTemplateConfig::BOOL: + $cb2 = new ilCheckboxInputGUI($lng->txt("adm_value"), "value_" . $s["id"]); + $cb->addSubItem($cb2); + break; + + case ilSettingsTemplateConfig::SELECT: + $si = new ilSelectInputGUI($lng->txt("adm_value"), "value_" . $s["id"]); + $si->setOptions($s["options"]); + $cb->addSubItem($si); + break; case ilSettingsTemplateConfig::CHECKBOX: - $chbs = new ilCheckboxGroupInputGUI($lng->txt("adm_value"), "value_".$s["id"]); - foreach($s['options'] as $key => $value) { + $chbs = new ilCheckboxGroupInputGUI($lng->txt("adm_value"), "value_" . $s["id"]); + foreach ($s['options'] as $key => $value) { $chbs->addOption($c = new ilCheckboxInputGUI($value, $key)); $c->setValue($key); } $cb->addSubItem($chbs); break; - } - - if ($s['hidable']) { - // hide setting - $cb_hide = new ilCheckboxInputGUI($lng->txt("adm_hide"), "hide_".$s["id"]); - $cb->addSubItem($cb_hide); - } - } - } - - // save and cancel commands - if ($a_mode == "create") - { - $this->form->addCommandButton("saveSettingsTemplate", $lng->txt("save")); - $this->form->addCommandButton("listSettingsTemplates", $lng->txt("cancel")); - $this->form->setTitle($lng->txt("adm_add_settings_template")); - } - else - { - $this->form->addCommandButton("updateSettingsTemplate", $lng->txt("save")); - $this->form->addCommandButton("listSettingsTemplates", $lng->txt("cancel")); - $this->form->setTitle($lng->txt("adm_edit_settings_template")); - } - - $this->form->setFormAction($ilCtrl->getFormAction($this)); - } - - /** - * Get current values for settings template from - */ - public function getSettingsTemplateValues() - { - $values = array(); - - $values["title"] = $this->settings_template->getTitle(); - $values["description"] = $this->settings_template->getDescription(); - - // save tabs to be hidden - $tabs = $this->settings_template->getHiddenTabs(); - foreach ($tabs as $t) - { - $values["tab_".$t] = true; - } - - // save settings values - $set = $this->settings_template->getSettings(); - foreach($this->getConfig()->getSettings() as $s) - { - if (isset($set[$s["id"]])) - { - $values["set_".$s["id"]] = true; - - if ($s['type'] == ilSettingsTemplateConfig::CHECKBOX) { - if (!is_array($set[$s["id"]]["value"])) - $ar = @unserialize($set[$s["id"]]["value"]); - else - $ar = $set[$s["id"]]["value"]; - $values["value_".$s["id"]] = is_array($ar) ? $ar : array(); - } - else { - $values["value_".$s["id"]] = $set[$s["id"]]["value"]; - } + } + + if ($s['hidable']) { + // hide setting + $cb_hide = new ilCheckboxInputGUI($lng->txt("adm_hide"), "hide_" . $s["id"]); + $cb->addSubItem($cb_hide); + } + } + } + + // save and cancel commands + if ($a_mode == "create") { + $this->form->addCommandButton("saveSettingsTemplate", $lng->txt("save")); + $this->form->addCommandButton("listSettingsTemplates", $lng->txt("cancel")); + $this->form->setTitle($lng->txt("adm_add_settings_template")); + } else { + $this->form->addCommandButton("updateSettingsTemplate", $lng->txt("save")); + $this->form->addCommandButton("listSettingsTemplates", $lng->txt("cancel")); + $this->form->setTitle($lng->txt("adm_edit_settings_template")); + } + + $this->form->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * Get current values for settings template from + */ + public function getSettingsTemplateValues() + { + $values = array(); + + $values["title"] = $this->settings_template->getTitle(); + $values["description"] = $this->settings_template->getDescription(); + + // save tabs to be hidden + $tabs = $this->settings_template->getHiddenTabs(); + foreach ($tabs as $t) { + $values["tab_" . $t] = true; + } + + // save settings values + $set = $this->settings_template->getSettings(); + foreach ($this->getConfig()->getSettings() as $s) { + if (isset($set[$s["id"]])) { + $values["set_" . $s["id"]] = true; + + if ($s['type'] == ilSettingsTemplateConfig::CHECKBOX) { + if (!is_array($set[$s["id"]]["value"])) { + $ar = @unserialize($set[$s["id"]]["value"]); + } else { + $ar = $set[$s["id"]]["value"]; + } + $values["value_" . $s["id"]] = is_array($ar) ? $ar : array(); + } else { + $values["value_" . $s["id"]] = $set[$s["id"]]["value"]; + } - $values["hide_".$s["id"]] = $set[$s["id"]]["hide"]; - } - } - $this->form->setValuesByArray($values); - } - - /** - * Save settings template form - */ - public function saveSettingsTemplate() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->initSettingsTemplateForm("create"); - if ($this->form->checkInput()) - { - $settings_template = new ilSettingsTemplate(); - $settings_template->setType($this->getConfig()->getType()); - - $this->setValuesFromForm($settings_template); - $settings_template->create(); - - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "listSettingsTemplates"); - } - - $this->form->setValuesByPost(); - $tpl->setContent($this->form->getHtml()); - } - - /** - * Update settings template - */ - function updateSettingsTemplate() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - - $this->initSettingsTemplateForm("edit"); - if ($this->form->checkInput()) - { - $this->setValuesFromForm($this->settings_template); - $this->settings_template->update(); - - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "listSettingsTemplates"); - } - - $this->form->setValuesByPost(); - $tpl->setContent($this->form->getHtml()); - } - - /** - * Set values from form - * - * @param - * @return - */ - function setValuesFromForm($a_set_templ) - { - // perform update - $a_set_templ->setTitle($_POST["title"]); - $a_set_templ->setDescription($_POST["description"]); - - // save tabs to be hidden - $a_set_templ->removeAllHiddenTabs(); - foreach ($this->getConfig()->getHidableTabs() as $t) - { - if ($_POST["tab_".$t["id"]]) - { - $a_set_templ->addHiddenTab($t["id"]); - } - } - - // save settings values - $a_set_templ->removeAllSettings(); - foreach($this->getConfig()->getSettings() as $s) - { - if ($_POST["set_".$s["id"]]) - { - $a_set_templ->setSetting( - $s["id"], $_POST["value_".$s["id"]], - $_POST["hide_".$s["id"]]); - } - } - } - - /** - * Confirm settings template deletion - */ - function confirmSettingsTemplateDeletion() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - if (!is_array($_POST["tid"]) || count($_POST["tid"]) == 0) - { - ilUtil::sendInfo($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "listSettingsTemplates"); - } - else - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("adm_sure_delete_settings_template")); - $cgui->setCancel($lng->txt("cancel"), "listSettingsTemplates"); - $cgui->setConfirm($lng->txt("delete"), "deleteSettingsTemplate"); - - foreach ($_POST["tid"] as $i) - { - $cgui->addItem("tid[]", $i, ilSettingsTemplate::lookupTitle($i)); - } - - $tpl->setContent($cgui->getHTML()); - } - } - - /** - * Delete settings template - * - * @param - * @return - */ - function deleteSettingsTemplate() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if (is_array($_POST["tid"])) - { - foreach ($_POST["tid"] as $i) - { - $templ = new ilSettingsTemplate($i); - $templ->delete(); - } - } - ilUtil::sendSuccess("msg_obj_modified"); - $ilCtrl->redirect($this, "listSettingsTemplates"); - } - + $values["hide_" . $s["id"]] = $set[$s["id"]]["hide"]; + } + } + $this->form->setValuesByArray($values); + } + + /** + * Save settings template form + */ + public function saveSettingsTemplate() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $this->initSettingsTemplateForm("create"); + if ($this->form->checkInput()) { + $settings_template = new ilSettingsTemplate(); + $settings_template->setType($this->getConfig()->getType()); + + $this->setValuesFromForm($settings_template); + $settings_template->create(); + + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "listSettingsTemplates"); + } + + $this->form->setValuesByPost(); + $tpl->setContent($this->form->getHtml()); + } + + /** + * Update settings template + */ + public function updateSettingsTemplate() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + + $this->initSettingsTemplateForm("edit"); + if ($this->form->checkInput()) { + $this->setValuesFromForm($this->settings_template); + $this->settings_template->update(); + + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "listSettingsTemplates"); + } + + $this->form->setValuesByPost(); + $tpl->setContent($this->form->getHtml()); + } + + /** + * Set values from form + * + * @param + * @return + */ + public function setValuesFromForm($a_set_templ) + { + // perform update + $a_set_templ->setTitle($_POST["title"]); + $a_set_templ->setDescription($_POST["description"]); + + // save tabs to be hidden + $a_set_templ->removeAllHiddenTabs(); + foreach ($this->getConfig()->getHidableTabs() as $t) { + if ($_POST["tab_" . $t["id"]]) { + $a_set_templ->addHiddenTab($t["id"]); + } + } + + // save settings values + $a_set_templ->removeAllSettings(); + foreach ($this->getConfig()->getSettings() as $s) { + if ($_POST["set_" . $s["id"]]) { + $a_set_templ->setSetting( + $s["id"], + $_POST["value_" . $s["id"]], + $_POST["hide_" . $s["id"]] + ); + } + } + } + + /** + * Confirm settings template deletion + */ + public function confirmSettingsTemplateDeletion() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + if (!is_array($_POST["tid"]) || count($_POST["tid"]) == 0) { + ilUtil::sendInfo($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "listSettingsTemplates"); + } else { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("adm_sure_delete_settings_template")); + $cgui->setCancel($lng->txt("cancel"), "listSettingsTemplates"); + $cgui->setConfirm($lng->txt("delete"), "deleteSettingsTemplate"); + + foreach ($_POST["tid"] as $i) { + $cgui->addItem("tid[]", $i, ilSettingsTemplate::lookupTitle($i)); + } + + $tpl->setContent($cgui->getHTML()); + } + } + + /** + * Delete settings template + * + * @param + * @return + */ + public function deleteSettingsTemplate() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if (is_array($_POST["tid"])) { + foreach ($_POST["tid"] as $i) { + $templ = new ilSettingsTemplate($i); + $templ->delete(); + } + } + ilUtil::sendSuccess("msg_obj_modified"); + $ilCtrl->redirect($this, "listSettingsTemplates"); + } } - -?> diff --git a/Services/Administration/classes/class.ilSettingsTemplateTableGUI.php b/Services/Administration/classes/class.ilSettingsTemplateTableGUI.php index af2fa8f3a0893fe0a1543b5a0ef3224cbdc3b2da..722c823801b5a58960f9cb3a86077ed6b2be726b 100644 --- a/Services/Administration/classes/class.ilSettingsTemplateTableGUI.php +++ b/Services/Administration/classes/class.ilSettingsTemplateTableGUI.php @@ -13,73 +13,75 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilSettingsTemplateTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_type) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_type) + { + 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("admsettemp".$a_type); + $this->setId("admsettemp" . $a_type); - parent::__construct($a_parent_obj, $a_parent_cmd); + parent::__construct($a_parent_obj, $a_parent_cmd); - include_once("./Services/Administration/classes/class.ilSettingsTemplate.php"); - $this->setData(ilSettingsTemplate::getAllSettingsTemplates($a_type,true)); - $this->setTitle($lng->txt("adm_settings_templates")." - ". - $lng->txt("obj_".$a_type)); + include_once("./Services/Administration/classes/class.ilSettingsTemplate.php"); + $this->setData(ilSettingsTemplate::getAllSettingsTemplates($a_type, true)); + $this->setTitle($lng->txt("adm_settings_templates") . " - " . + $lng->txt("obj_" . $a_type)); - $this->addColumn("", "", "1", true); - $this->addColumn($this->lng->txt("title"), "title"); - $this->addColumn($this->lng->txt("description")); - $this->addColumn($this->lng->txt("actions")); + $this->addColumn("", "", "1", true); + $this->addColumn($this->lng->txt("title"), "title"); + $this->addColumn($this->lng->txt("description")); + $this->addColumn($this->lng->txt("actions")); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.settings_template_row.html", - "Services/Administration"); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate( + "tpl.settings_template_row.html", + "Services/Administration" + ); - $this->addMultiCommand("confirmSettingsTemplateDeletion", $lng->txt("delete")); - //$this->addCommandButton("", $lng->txt("")); - } + $this->addMultiCommand("confirmSettingsTemplateDeletion", $lng->txt("delete")); + //$this->addCommandButton("", $lng->txt("")); + } - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameter($this->parent_obj, "templ_id", $a_set["id"]); - $this->tpl->setVariable("VAL_ID", $a_set["id"]); - // begin-patch lok - $this->tpl->setVariable("VAL_TITLE", ilSettingsTemplate::translate($a_set["title"])); - $this->tpl->setVariable("VAL_DESCRIPTION", ilSettingsTemplate::translate($a_set["description"])); - // end-patch lok - $this->tpl->setVariable("TXT_EDIT", $lng->txt("edit")); - $this->tpl->setVariable("HREF_EDIT", - $ilCtrl->getLinkTarget($this->parent_obj, "editSettingsTemplate")); - $ilCtrl->setParameter($this->parent_obj, "templ_id", ""); - } + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilCtrl->setParameter($this->parent_obj, "templ_id", $a_set["id"]); + $this->tpl->setVariable("VAL_ID", $a_set["id"]); + // begin-patch lok + $this->tpl->setVariable("VAL_TITLE", ilSettingsTemplate::translate($a_set["title"])); + $this->tpl->setVariable("VAL_DESCRIPTION", ilSettingsTemplate::translate($a_set["description"])); + // end-patch lok + $this->tpl->setVariable("TXT_EDIT", $lng->txt("edit")); + $this->tpl->setVariable( + "HREF_EDIT", + $ilCtrl->getLinkTarget($this->parent_obj, "editSettingsTemplate") + ); + $ilCtrl->setParameter($this->parent_obj, "templ_id", ""); + } } -?> diff --git a/Services/Administration/classes/class.ilSubversionInformation.php b/Services/Administration/classes/class.ilSubversionInformation.php index b00149e5104b9fd8e06a8a98e21d24c9114e0ff4..e7286379f51f4c25f7be5e183a2b0e2cdb9622b8 100644 --- a/Services/Administration/classes/class.ilSubversionInformation.php +++ b/Services/Administration/classes/class.ilSubversionInformation.php @@ -9,154 +9,133 @@ require_once 'Services/Administration/interfaces/interface.ilVersionControlInfor */ class ilSubversionInformation implements ilVersionControlInformation { - /** - * @var string - */ - const SVN_GET_17_FILE = '.svn/wc.db'; - - /** - * @var string - */ - const SVN_LT_17_FILE = '.svn/entries'; - - /** - * @var string - */ - private static $revision_information = null; - - /** - * @param $revision - * @return bool - */ - private static function isSvnRevision($revision) - { - return (bool)preg_match('/^\d+(:\d+)*[MSP]*$/', $revision); - } - - /** - * @return bool - */ - private static function isProbablySubversion17() - { - return file_exists(self::SVN_GET_17_FILE) && is_file(self::SVN_GET_17_FILE) && is_readable(self::SVN_GET_17_FILE); - } - - /** - * @return bool - */ - private static function isProbablySubversionLower17() - { - return file_exists(self::SVN_LT_17_FILE) && is_file(self::SVN_LT_17_FILE) && is_readable(self::SVN_LT_17_FILE); - } - - /** - * - */ - private static function detect() - { - global $DIC; - - $lng = $DIC->language(); - - if(null !== self::$revision_information) - { - return self::$revision_information; - } - - $info = array(); - - if(self::isProbablySubversion17()) - { - if(extension_loaded('PDO') && extension_loaded('pdo_sqlite')) - { - try - { - $wcdb = new PDO('sqlite:' . self::SVN_GET_17_FILE); - - $result = $wcdb->query('SELECT MAX("revision") current_rev FROM "NODES"'); - if($result) - { - foreach($result as $row) - { - $revision = $row['current_rev']; - if(self::isSvnRevision($revision)) - { - $info[] = sprintf($lng->txt('svn_revision_current'), $revision); - } - break; - } - } - - $result = $wcdb->query('SELECT "changed_revision" last_changed_revision FROM "NODES" ORDER BY changed_revision DESC LIMIT 1'); - if($result) - { - foreach($result as $row) - { - $revision = $row['last_changed_revision']; - if(self::isSvnRevision($revision)) - { - $info[] = sprintf($lng->txt('svn_revision_last_change'), $revision); - } - break; - } - } - - $result = $wcdb->query('SELECT * FROM REPOSITORY '); - if($result) - { - foreach($result as $row) - { - $info[] = sprintf($lng->txt('svn_root'), $row['root']); - } - } - - $result = $wcdb->query('SELECT * FROM "NODES" WHERE local_relpath LIKE "%inc.ilias_version.php"'); - if($result) - { - foreach($result as $row) - { - $path = dirname(dirname($row['repos_path'])); - if($path) - { - $info[] = sprintf($lng->txt('svn_path'), $path); - } - } - } - } - catch(Exception $e) {} - } - } - else - { - if(function_exists('shell_exec') && is_callable('shell_exec')) - { - $revision = trim(shell_exec('svnversion ' . realpath(getcwd()))); - if(self::isSvnRevision($revision)) - { - $info[] = sprintf($lng->txt('svn_revision_current'), $revision); - } - } - if(self::isProbablySubversionLower17()) - { - $svnfile = file(self::SVN_LT_17_FILE); - $revision = $svnfile[3]; - if(self::isSvnRevision($revision)) - { - $info[] = sprintf($lng->txt('svn_revision_last_change'), $revision); - } - } - } - - self::$revision_information = $info; - } - - /** - * @return string - */ - public function getInformationAsHtml() - { - self::detect(); - - return implode("
", self::$revision_information); - } + /** + * @var string + */ + const SVN_GET_17_FILE = '.svn/wc.db'; + + /** + * @var string + */ + const SVN_LT_17_FILE = '.svn/entries'; + + /** + * @var string + */ + private static $revision_information = null; + + /** + * @param $revision + * @return bool + */ + private static function isSvnRevision($revision) + { + return (bool) preg_match('/^\d+(:\d+)*[MSP]*$/', $revision); + } + + /** + * @return bool + */ + private static function isProbablySubversion17() + { + return file_exists(self::SVN_GET_17_FILE) && is_file(self::SVN_GET_17_FILE) && is_readable(self::SVN_GET_17_FILE); + } + + /** + * @return bool + */ + private static function isProbablySubversionLower17() + { + return file_exists(self::SVN_LT_17_FILE) && is_file(self::SVN_LT_17_FILE) && is_readable(self::SVN_LT_17_FILE); + } + + /** + * + */ + private static function detect() + { + global $DIC; + + $lng = $DIC->language(); + + if (null !== self::$revision_information) { + return self::$revision_information; + } + + $info = array(); + + if (self::isProbablySubversion17()) { + if (extension_loaded('PDO') && extension_loaded('pdo_sqlite')) { + try { + $wcdb = new PDO('sqlite:' . self::SVN_GET_17_FILE); + + $result = $wcdb->query('SELECT MAX("revision") current_rev FROM "NODES"'); + if ($result) { + foreach ($result as $row) { + $revision = $row['current_rev']; + if (self::isSvnRevision($revision)) { + $info[] = sprintf($lng->txt('svn_revision_current'), $revision); + } + break; + } + } + + $result = $wcdb->query('SELECT "changed_revision" last_changed_revision FROM "NODES" ORDER BY changed_revision DESC LIMIT 1'); + if ($result) { + foreach ($result as $row) { + $revision = $row['last_changed_revision']; + if (self::isSvnRevision($revision)) { + $info[] = sprintf($lng->txt('svn_revision_last_change'), $revision); + } + break; + } + } + + $result = $wcdb->query('SELECT * FROM REPOSITORY '); + if ($result) { + foreach ($result as $row) { + $info[] = sprintf($lng->txt('svn_root'), $row['root']); + } + } + + $result = $wcdb->query('SELECT * FROM "NODES" WHERE local_relpath LIKE "%inc.ilias_version.php"'); + if ($result) { + foreach ($result as $row) { + $path = dirname(dirname($row['repos_path'])); + if ($path) { + $info[] = sprintf($lng->txt('svn_path'), $path); + } + } + } + } catch (Exception $e) { + } + } + } else { + if (function_exists('shell_exec') && is_callable('shell_exec')) { + $revision = trim(shell_exec('svnversion ' . realpath(getcwd()))); + if (self::isSvnRevision($revision)) { + $info[] = sprintf($lng->txt('svn_revision_current'), $revision); + } + } + if (self::isProbablySubversionLower17()) { + $svnfile = file(self::SVN_LT_17_FILE); + $revision = $svnfile[3]; + if (self::isSvnRevision($revision)) { + $info[] = sprintf($lng->txt('svn_revision_last_change'), $revision); + } + } + } + + self::$revision_information = $info; + } + + /** + * @return string + */ + public function getInformationAsHtml() + { + self::detect(); + + return implode("
", self::$revision_information); + } } diff --git a/Services/Administration/interfaces/interface.ilAdministrationCommandHandling.php b/Services/Administration/interfaces/interface.ilAdministrationCommandHandling.php index 303fa0317db64b2ccb2f56f839f2588ec46ed17f..a335e50ea30f0d8f99b8b2cabdb97058b6ffab0f 100644 --- a/Services/Administration/interfaces/interface.ilAdministrationCommandHandling.php +++ b/Services/Administration/interfaces/interface.ilAdministrationCommandHandling.php @@ -1,107 +1,104 @@ * @version $Id$ -* +* * * @ingroup ServicesAdministration */ interface ilAdministrationCommandHandling { - - /** - * Show delete confirmation - */ - public function delete(); - - /** - * Cancel delete - */ - public function cancelDelete(); - - /** - * Perform Delete - */ - public function performDelete(); - - /** - * Cut object - */ - public function cut(); - - /** - * Target selection link - * @return - */ - public function showLinkIntoMultipleObjectsTree(); - - /** - * Target selection cut - * @return - */ - public function showMoveIntoObjectTree(); - - /** - * Perform paste into multiple objects - * @return - */ - public function performPasteIntoMultipleObjects(); - - /** - * Paste - */ - public function paste(); - - /** - * clear clipboard - */ - public function clear(); - - /** - * Enable administration panel - */ - public function enableAdministrationPanel(); - - /** - * Disable administration panel - */ - public function disableAdministrationPanel(); - - /** - * Cancel move/link - */ - public function cancelMoveLinkObject(); - - /** - * cancel action but keep objects in clipboard - * @return void - */ - public function keepObjectsInClipboardObject(); + + /** + * Show delete confirmation + */ + public function delete(); + + /** + * Cancel delete + */ + public function cancelDelete(); + + /** + * Perform Delete + */ + public function performDelete(); + + /** + * Cut object + */ + public function cut(); + + /** + * Target selection link + * @return + */ + public function showLinkIntoMultipleObjectsTree(); + + /** + * Target selection cut + * @return + */ + public function showMoveIntoObjectTree(); + + /** + * Perform paste into multiple objects + * @return + */ + public function performPasteIntoMultipleObjects(); + + /** + * Paste + */ + public function paste(); + + /** + * clear clipboard + */ + public function clear(); + + /** + * Enable administration panel + */ + public function enableAdministrationPanel(); + + /** + * Disable administration panel + */ + public function disableAdministrationPanel(); + + /** + * Cancel move/link + */ + public function cancelMoveLinkObject(); - + /** + * cancel action but keep objects in clipboard + * @return void + */ + public function keepObjectsInClipboardObject(); } -?> diff --git a/Services/Administration/interfaces/interface.ilVersionControlInformation.php b/Services/Administration/interfaces/interface.ilVersionControlInformation.php index bd4dd884902692f73279dd76f196c4371fb25c3d..34f5b2db1d3807f3f6f05b0d0ddd5dc45046f33a 100644 --- a/Services/Administration/interfaces/interface.ilVersionControlInformation.php +++ b/Services/Administration/interfaces/interface.ilVersionControlInformation.php @@ -7,8 +7,8 @@ */ interface ilVersionControlInformation { - /** - * @return string - */ - public function getInformationAsHtml(); -} + /** + * @return string + */ + public function getInformationAsHtml(); +} diff --git a/Services/Administration/test/ilServicesAdministrationSuite.php b/Services/Administration/test/ilServicesAdministrationSuite.php index 72ebc0a71ea4ae1708018ff71f01452235f0c8d8..91fbd903af70a0903448ef6164ab868d974e74e1 100644 --- a/Services/Administration/test/ilServicesAdministrationSuite.php +++ b/Services/Administration/test/ilServicesAdministrationSuite.php @@ -5,12 +5,11 @@ class ilServicesAdministrationSuite extends PHPUnit_Framework_TestSuite { public static function suite() { - $suite = new ilServicesAdministrationSuite(); - - include_once("./Services/Administration/test/ilSettingTest.php"); - $suite->addTestSuite("ilSettingTest"); - - return $suite; + $suite = new ilServicesAdministrationSuite(); + + include_once("./Services/Administration/test/ilSettingTest.php"); + $suite->addTestSuite("ilSettingTest"); + + return $suite; } } -?> diff --git a/Services/Administration/test/ilSettingTest.php b/Services/Administration/test/ilSettingTest.php index 67a11e4cadd88acafeb1febf7db0d755a7b06369..35d037200b3bc1aaedfe509d5ee6c12a8d1c005c 100644 --- a/Services/Administration/test/ilSettingTest.php +++ b/Services/Administration/test/ilSettingTest.php @@ -1,90 +1,88 @@ set("foo", "bar"); - $value = $set->get("foo"); - - $this->assertEquals("bar", $value); - } + /** + * @group IL_Init + */ + public function testSetGetSettings() + { + $set = new ilSetting("test_module"); + $set->set("foo", "bar"); + $value = $set->get("foo"); + + $this->assertEquals("bar", $value); + } - /** - * @group IL_Init - */ - public function testDeletion() - { - // set two things for two modules - $set = new ilSetting("test_module"); - $set->set("foo", "bar"); - $set = new ilSetting("test_module2"); - $set->set("foo2", "bar2"); - $set = new ilSetting("test_module"); - $set->deleteAll(); + /** + * @group IL_Init + */ + public function testDeletion() + { + // set two things for two modules + $set = new ilSetting("test_module"); + $set->set("foo", "bar"); + $set = new ilSetting("test_module2"); + $set->set("foo2", "bar2"); + $set = new ilSetting("test_module"); + $set->deleteAll(); - $value = $set->get("foo", false, true)."-"; // should be "-" now - - $set = new ilSetting("test_module2"); - $value.= $set->get("foo2"); // should be "-bar2" now - - $this->assertEquals("-bar2", $value); - } - - /** - * @group IL_Init - */ - public function testLikeDeletion() - { - $set = new ilSetting("test_module3"); - $set->set("foo", "plus"); - $set->set("fooplus", "bar"); - $set->set("barplus", "foo"); - $set->deleteLike("foo%"); - - $value = $set->get("foo")."-". - $set->get("fooplus")."-". - $set->get("barplus"); - - $this->assertEquals("--foo", $value); - } + $value = $set->get("foo", false, true) . "-"; // should be "-" now + + $set = new ilSetting("test_module2"); + $value.= $set->get("foo2"); // should be "-bar2" now + + $this->assertEquals("-bar2", $value); + } + /** + * @group IL_Init + */ + public function testLikeDeletion() + { + $set = new ilSetting("test_module3"); + $set->set("foo", "plus"); + $set->set("fooplus", "bar"); + $set->set("barplus", "foo"); + $set->deleteLike("foo%"); + + $value = $set->get("foo") . "-" . + $set->get("fooplus") . "-" . + $set->get("barplus"); + + $this->assertEquals("--foo", $value); + } } -?> diff --git a/Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php b/Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php index 66086e4e10df58c0d9627c118f741bf49b7ba436..65f7d831eb66327e3e10a580b6737aff135a0a03 100644 --- a/Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php +++ b/Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php @@ -1,24 +1,24 @@ lng = $DIC->language(); - include_once "./Services/Administration/classes/class.ilSetting.php"; - $this->setting = new ilSetting("advanced_editing"); - $this->type = "adve"; - parent::__construct($a_id,$a_call_by_reference); - } + $this->lng = $DIC->language(); + include_once "./Services/Administration/classes/class.ilSetting.php"; + $this->setting = new ilSetting("advanced_editing"); + $this->type = "adve"; + parent::__construct($a_id, $a_call_by_reference); + } - /** - * update object data - * - * @access public - * @return boolean - */ - function update() - { - if (!parent::update()) - { - return false; - } + /** + * update object data + * + * @access public + * @return boolean + */ + public function update() + { + if (!parent::update()) { + return false; + } - // put here object specific stuff + // put here object specific stuff - return true; - } + return true; + } - /** - * delete object and all related data - * - * @access public - * @return boolean true if all object data were removed; false if only a references were removed - */ - function delete() - { - // always call parent delete function first!! - if (!parent::delete()) - { - return false; - } + /** + * delete object and all related data + * + * @access public + * @return boolean true if all object data were removed; false if only a references were removed + */ + public function delete() + { + // always call parent delete function first!! + if (!parent::delete()) { + return false; + } - //put here your module specific stuff + //put here your module specific stuff - return true; - } + return true; + } - /** - * Returns an array of all allowed HTML tags for text editing - * - * Returns an array of all allowed HTML tags for text editing - * - * @param string $a_module Name of the module or object which uses the tags - * @return array HTML tags - */ - public static function _getUsedHTMLTags($a_module = "") - { - $usedtags = array(); - include_once "./Services/Administration/classes/class.ilSetting.php"; - $setting = new ilSetting("advanced_editing"); - $tags = $setting->get("advanced_editing_used_html_tags_" . $a_module); - if (strlen($tags)) - { - $usedtags = unserialize($tags); - } - else - { - if($a_module == 'frm_post' || $a_module == 'exc_ass') - { - $usedtags = array( - "a", - "blockquote", - "br", - "code", - "div", - "em", - "img", - "li", - "ol", - "p", - "strong", - "u", - "ul", - "span" - ); - } - else - { - // default: everything but tables - $usedtags = array( - "a", - "blockquote", - "br", - "cite", - "code", - "dd", - "div", - "dl", - "dt", - "em", - "h1", - "h2", - "h3", - "h4", - "h5", - "h6", - "hr", - "img", - "li", - "ol", - "p", - "pre", - "span", - "strike", - "strong", - "sub", - "sup", - "u", - "ul" - ); - } - } - - // frm_posts need blockquote and div urgently - if($a_module === 'frm_post') - { - if(!in_array('div', $usedtags)) - { - $usedtags[] = 'div'; - } - - if(!in_array('blockquote', $usedtags)) - { - $usedtags[] = 'blockquote'; - } - } - - return $usedtags; - } + /** + * Returns an array of all allowed HTML tags for text editing + * + * Returns an array of all allowed HTML tags for text editing + * + * @param string $a_module Name of the module or object which uses the tags + * @return array HTML tags + */ + public static function _getUsedHTMLTags($a_module = "") + { + $usedtags = array(); + include_once "./Services/Administration/classes/class.ilSetting.php"; + $setting = new ilSetting("advanced_editing"); + $tags = $setting->get("advanced_editing_used_html_tags_" . $a_module); + if (strlen($tags)) { + $usedtags = unserialize($tags); + } else { + if ($a_module == 'frm_post' || $a_module == 'exc_ass') { + $usedtags = array( + "a", + "blockquote", + "br", + "code", + "div", + "em", + "img", + "li", + "ol", + "p", + "strong", + "u", + "ul", + "span" + ); + } else { + // default: everything but tables + $usedtags = array( + "a", + "blockquote", + "br", + "cite", + "code", + "dd", + "div", + "dl", + "dt", + "em", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "hr", + "img", + "li", + "ol", + "p", + "pre", + "span", + "strike", + "strong", + "sub", + "sup", + "u", + "ul" + ); + } + } + + // frm_posts need blockquote and div urgently + if ($a_module === 'frm_post') { + if (!in_array('div', $usedtags)) { + $usedtags[] = 'div'; + } + + if (!in_array('blockquote', $usedtags)) { + $usedtags[] = 'blockquote'; + } + } + + return $usedtags; + } - /** - * Returns a string of all allowed HTML tags for text editing - * - * Returns a string of all allowed HTML tags for text editing - * - * @param string $a_module Name of the module or object which uses the tags - * @return string Used HTML tags - */ - public static function _getUsedHTMLTagsAsString($a_module = "") - { - $result = ""; - $tags = ilObjAdvancedEditing::_getUsedHTMLTags($a_module); - foreach ($tags as $tag) - { - $result .= "<$tag>"; - } - return $result; - } - - /** - * Returns the identifier for the Rich Text Editor - * - * Returns the identifier for the Rich Text Editor - * - * @return string Identifier for the Rich Text Editor - */ - static function _getRichTextEditor() - { - include_once "./Services/Administration/classes/class.ilSetting.php"; - $setting = new ilSetting("advanced_editing"); - $js = $setting->get("advanced_editing_javascript_editor"); - return $js; - } - - /** - * Sets wheather a Rich Text Editor should be used or not - * - * Sets wheather a Rich Text Editor should be used or not - * - * @param boolean $a_js_editor A boolean indicating if the JS editor should be used or not - */ - function setRichTextEditor($a_js_editor) - { - include_once "./Services/Administration/classes/class.ilSetting.php"; - $setting = new ilSetting("advanced_editing"); - $setting->set("advanced_editing_javascript_editor", $a_js_editor); - } - - /** - * Writes an array with allowed HTML tags to the ILIAS settings - * - * Writes an array with allowed HTML tags to the ILIAS settings - * - * @param array $a_html_tags An array containing the allowed HTML tags - * @param string $a_module The name of the module or object which uses the tags - * @throws ilAdvancedEditingRequiredTagsException - * - */ - function setUsedHTMLTags($a_html_tags, $a_module) - { - $lng = $this->lng; - - if (strlen($a_module)) - { - $auto_added_tags = array(); - - // frm_posts need blockquote and div urgently - if($a_module == 'frm_post') - { - if(!in_array('div', $a_html_tags)) - { - $auto_added_tags[] = 'div'; - } - - if(!in_array('blockquote', $a_html_tags)) - { - $auto_added_tags[] = 'blockquote'; - } - } - - include_once "./Services/Administration/classes/class.ilSetting.php"; - $setting = new ilSetting("advanced_editing"); - $setting->set("advanced_editing_used_html_tags_" . $a_module, serialize(array_merge((array)$a_html_tags, $auto_added_tags))); - - if(count($auto_added_tags)) - { - require_once 'Services/AdvancedEditing/exceptions/class.ilAdvancedEditingRequiredTagsException.php'; - throw new ilAdvancedEditingRequiredTagsException( - sprintf( - $lng->txt('advanced_editing_required_tags'), - implode(', ', $auto_added_tags) - ) - ); - } - } - } - - /** - * Returns an array of all possible HTML tags for text editing - * - * Returns an array of all possible HTML tags for text editing - * - * @return array HTML tags - */ - function &getHTMLTags() - { - $tags = array( - "a", - "blockquote", - "br", - "cite", - "code", - "dd", - "div", - "dl", - "dt", - "em", - "h1", - "h2", - "h3", - "h4", - "h5", - "h6", - "hr", - "img", - "li", - "object", - "ol", - "p", - "param", - "pre", - "span", - "strike", - "strong", - "sub", - "sup", - "table", - "td", - "tr", - "u", - "ul", - "ruby", // Ruby Annotation XHTML module - "rbc", - "rtc", - "rb", - "rt", - "rp" - ); - return $tags; - } + /** + * Returns a string of all allowed HTML tags for text editing + * + * Returns a string of all allowed HTML tags for text editing + * + * @param string $a_module Name of the module or object which uses the tags + * @return string Used HTML tags + */ + public static function _getUsedHTMLTagsAsString($a_module = "") + { + $result = ""; + $tags = ilObjAdvancedEditing::_getUsedHTMLTags($a_module); + foreach ($tags as $tag) { + $result .= "<$tag>"; + } + return $result; + } + + /** + * Returns the identifier for the Rich Text Editor + * + * Returns the identifier for the Rich Text Editor + * + * @return string Identifier for the Rich Text Editor + */ + public static function _getRichTextEditor() + { + include_once "./Services/Administration/classes/class.ilSetting.php"; + $setting = new ilSetting("advanced_editing"); + $js = $setting->get("advanced_editing_javascript_editor"); + return $js; + } + + /** + * Sets wheather a Rich Text Editor should be used or not + * + * Sets wheather a Rich Text Editor should be used or not + * + * @param boolean $a_js_editor A boolean indicating if the JS editor should be used or not + */ + public function setRichTextEditor($a_js_editor) + { + include_once "./Services/Administration/classes/class.ilSetting.php"; + $setting = new ilSetting("advanced_editing"); + $setting->set("advanced_editing_javascript_editor", $a_js_editor); + } + + /** + * Writes an array with allowed HTML tags to the ILIAS settings + * + * Writes an array with allowed HTML tags to the ILIAS settings + * + * @param array $a_html_tags An array containing the allowed HTML tags + * @param string $a_module The name of the module or object which uses the tags + * @throws ilAdvancedEditingRequiredTagsException + * + */ + public function setUsedHTMLTags($a_html_tags, $a_module) + { + $lng = $this->lng; + + if (strlen($a_module)) { + $auto_added_tags = array(); + + // frm_posts need blockquote and div urgently + if ($a_module == 'frm_post') { + if (!in_array('div', $a_html_tags)) { + $auto_added_tags[] = 'div'; + } + + if (!in_array('blockquote', $a_html_tags)) { + $auto_added_tags[] = 'blockquote'; + } + } + + include_once "./Services/Administration/classes/class.ilSetting.php"; + $setting = new ilSetting("advanced_editing"); + $setting->set("advanced_editing_used_html_tags_" . $a_module, serialize(array_merge((array) $a_html_tags, $auto_added_tags))); + + if (count($auto_added_tags)) { + require_once 'Services/AdvancedEditing/exceptions/class.ilAdvancedEditingRequiredTagsException.php'; + throw new ilAdvancedEditingRequiredTagsException( + sprintf( + $lng->txt('advanced_editing_required_tags'), + implode(', ', $auto_added_tags) + ) + ); + } + } + } + + /** + * Returns an array of all possible HTML tags for text editing + * + * Returns an array of all possible HTML tags for text editing + * + * @return array HTML tags + */ + public function &getHTMLTags() + { + $tags = array( + "a", + "blockquote", + "br", + "cite", + "code", + "dd", + "div", + "dl", + "dt", + "em", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "hr", + "img", + "li", + "object", + "ol", + "p", + "param", + "pre", + "span", + "strike", + "strong", + "sub", + "sup", + "table", + "td", + "tr", + "u", + "ul", + "ruby", // Ruby Annotation XHTML module + "rbc", + "rtc", + "rb", + "rt", + "rp" + ); + return $tags; + } - /** - * Returns an array of all possible HTML tags for text editing - * - * Returns an array of all possible HTML tags for text editing - * - * @return array HTML tags - */ - public static function _getAllHTMLTags() - { - $tags = array( - "a", - "abbr", - "acronym", - "address", - "applet", - "area", - "b", - "base", - "basefont", - "bdo", - "big", - "blockquote", - "br", - "button", - "caption", - "center", - "cite", - "code", - "col", - "colgroup", - "dd", - "del", - "dfn", - "dir", - "div", - "dl", - "dt", - "em", - "fieldset", - "font", - "form", - "h1", - "h2", - "h3", - "h4", - "h5", - "h6", - "hr", - "i", - "iframe", - "img", - "input", - "ins", - "isindex", - "kbd", - "label", - "legend", - "li", - "link", - "map", - "menu", - "object", - "ol", - "optgroup", - "option", - "p", - "param", - "pre", - "q", - "s", - "samp", - "select", - "small", - "span", - "strike", - "strong", - "sub", - "sup", - "table", - "tbody", - "td", - "textarea", - "tfoot", - "th", - "thead", - "tr", - "tt", - "u", - "ul", - "var", - "ruby", // Ruby Annotation XHTML module - "rbc", - "rtc", - "rb", - "rt", - "rp" - ); - return $tags; - } + /** + * Returns an array of all possible HTML tags for text editing + * + * Returns an array of all possible HTML tags for text editing + * + * @return array HTML tags + */ + public static function _getAllHTMLTags() + { + $tags = array( + "a", + "abbr", + "acronym", + "address", + "applet", + "area", + "b", + "base", + "basefont", + "bdo", + "big", + "blockquote", + "br", + "button", + "caption", + "center", + "cite", + "code", + "col", + "colgroup", + "dd", + "del", + "dfn", + "dir", + "div", + "dl", + "dt", + "em", + "fieldset", + "font", + "form", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "hr", + "i", + "iframe", + "img", + "input", + "ins", + "isindex", + "kbd", + "label", + "legend", + "li", + "link", + "map", + "menu", + "object", + "ol", + "optgroup", + "option", + "p", + "param", + "pre", + "q", + "s", + "samp", + "select", + "small", + "span", + "strike", + "strong", + "sub", + "sup", + "table", + "tbody", + "td", + "textarea", + "tfoot", + "th", + "thead", + "tr", + "tt", + "u", + "ul", + "var", + "ruby", // Ruby Annotation XHTML module + "rbc", + "rtc", + "rb", + "rt", + "rp" + ); + return $tags; + } - /** - * Sets the state of the rich text editor visibility for the current user - * - * Sets the state of the rich text editor visibility for the current user - * @static - * @param integer $a_state 0 if the RTE should be disabled, 1 otherwise - */ - public static function _setRichTextEditorUserState($a_state) - { - global $DIC; + /** + * Sets the state of the rich text editor visibility for the current user + * + * Sets the state of the rich text editor visibility for the current user + * @static + * @param integer $a_state 0 if the RTE should be disabled, 1 otherwise + */ + public static function _setRichTextEditorUserState($a_state) + { + global $DIC; - $ilUser = $DIC->user(); - $ilUser->writePref("show_rte", $a_state); - } + $ilUser = $DIC->user(); + $ilUser->writePref("show_rte", $a_state); + } - /** - * Gets the state of the rich text editor visibility for the current user - * - * Gets the state of the rich text editor visibility for the current user - * - * @static - * @return integer 0 if the RTE should be disabled, 1 otherwise - */ - public static function _getRichTextEditorUserState() - { - global $DIC; + /** + * Gets the state of the rich text editor visibility for the current user + * + * Gets the state of the rich text editor visibility for the current user + * + * @static + * @return integer 0 if the RTE should be disabled, 1 otherwise + */ + public static function _getRichTextEditorUserState() + { + global $DIC; - $ilUser = $DIC->user(); - if (strlen($ilUser->getPref("show_rte")) > 0) - { - return $ilUser->getPref("show_rte"); - } - return 1; - } - + $ilUser = $DIC->user(); + if (strlen($ilUser->getPref("show_rte")) > 0) { + return $ilUser->getPref("show_rte"); + } + return 1; + } } // END class.ilObjAdvancedEditing -?> diff --git a/Services/AdvancedEditing/classes/class.ilObjAdvancedEditingAccess.php b/Services/AdvancedEditing/classes/class.ilObjAdvancedEditingAccess.php index 495549a7c32113ff4aeda6d958496a08c6e59681..6534b2ffe1dd6ad29d6c52ea55a5cc26c58cd9ba 100644 --- a/Services/AdvancedEditing/classes/class.ilObjAdvancedEditingAccess.php +++ b/Services/AdvancedEditing/classes/class.ilObjAdvancedEditingAccess.php @@ -1,24 +1,24 @@ diff --git a/Services/AdvancedEditing/classes/class.ilObjAdvancedEditingGUI.php b/Services/AdvancedEditing/classes/class.ilObjAdvancedEditingGUI.php index 155a24c75565aa5669249aba3f485b7f53f53c67..22d4ea1173b6fefefe495b00fa6bcb05daa4d902 100644 --- a/Services/AdvancedEditing/classes/class.ilObjAdvancedEditingGUI.php +++ b/Services/AdvancedEditing/classes/class.ilObjAdvancedEditingGUI.php @@ -9,693 +9,696 @@ include_once "./Services/Object/classes/class.ilObjectGUI.php"; * * @author Helmut Schottmüller * @version $Id$ - * + * * @ilCtrl_Calls ilObjAdvancedEditingGUI: ilPermissionGUI * * @ingroup ServicesAdvancedEditing */ class ilObjAdvancedEditingGUI extends ilObjectGUI { - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilRbacAdmin - */ - protected $rbacadmin; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilSetting - */ - protected $settings; - - var $conditions; - - /** - * Constructor - */ - function __construct($a_data,$a_id,$a_call_by_reference) - { - global $DIC; - - $this->rbacsystem = $DIC->rbac()->system(); - $this->rbacadmin = $DIC->rbac()->admin(); - $this->ctrl = $DIC->ctrl(); - $this->tabs = $DIC->tabs(); - $this->tpl = $DIC["tpl"]; - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $this->settings = $DIC->settings(); - $rbacsystem = $DIC->rbac()->system(); - - $this->type = "adve"; - parent::__construct($a_data,$a_id,$a_call_by_reference,false); - $this->lng->loadLanguageModule('adve'); - $this->lng->loadLanguageModule('meta'); - - if (!$rbacsystem->checkAccess('read',$this->object->getRefId())) - { - $this->ilias->raiseError($this->lng->txt("msg_no_perm_read_adve"),$this->ilias->error_obj->WARNING); - } - } - - function executeCommand() - { - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - $this->prepareOutput(); - - switch($next_class) - { - - case 'ilpermissiongui': - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $ret =& $this->ctrl->forwardCommand($perm_gui); - break; - - default: - if($cmd == "" || $cmd == "view") - { - $cmd = "showGeneralPageEditorSettings"; - } - $cmd .= "Object"; - $this->$cmd(); - - break; - } - return true; - } - - /** - * save object - * @access public - */ - function saveObject() - { - $this->checkPermission("write"); - - parent::saveObject(); - - // always send a message - ilUtil::sendSuccess($this->lng->txt("object_added"),true); - $this->ctrl->redirect($this); - } - - function getAdminTabs() - { - $this->getTabs(); - } - - /** - * Add rte subtabs - */ - function addSubtabs() - { - $ilCtrl = $this->ctrl; - - if ($ilCtrl->getNextClass() != "ilpermissiongui" && - !in_array($ilCtrl->getCmd(), array("showPageEditorSettings", - "showGeneralPageEditorSettings", "showCharSelectorSettings", "", "view"))) - { - $this->tabs_gui->addSubTabTarget("adve_general_settings", - $this->ctrl->getLinkTarget($this, "settings"), - array("settings", "saveSettings"), - "", ""); - $this->tabs_gui->addSubTabTarget("adve_assessment_settings", - $this->ctrl->getLinkTarget($this, "assessment"), - array("assessment", "saveAssessmentSettings"), - "", ""); - $this->tabs_gui->addSubTabTarget("adve_survey_settings", - $this->ctrl->getLinkTarget($this, "survey"), - array("survey", "saveSurveySettings"), - "", ""); - $this->tabs_gui->addSubTabTarget("adve_frm_post_settings", - $this->ctrl->getLinkTarget($this, "frmPost"), - array("frmPost", "saveFrmPostSettings"), - "", ""); - $this->tabs_gui->addSubTabTarget("adve_excass_settings", - $this->ctrl->getLinkTarget($this, "excass"), - array("excass", "saveExcAssSettings"), - "", ""); - } - } - - /** - * Show page editor settings subtabs - */ - function addPageEditorSettingsSubtabs() - { - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - $ilTabs->addSubTabTarget("adve_pe_general", - $ilCtrl->getLinkTarget($this, "showGeneralPageEditorSettings"), - array("showGeneralPageEditorSettings", "", "view")); - - include_once("./Services/COPage/classes/class.ilPageEditorSettings.php"); - $grps = ilPageEditorSettings::getGroups(); - - foreach ($grps as $g => $types) - { - $ilCtrl->setParameter($this, "grp", $g); - $ilTabs->addSubTabTarget("adve_grp_".$g, - $ilCtrl->getLinkTarget($this, "showPageEditorSettings"), - array("showPageEditorSettings")); - } - $ilCtrl->setParameter($this, "grp", $_GET["grp"]); - } - - /** - * get tabs - * @access public - * @param object tabs gui object - */ - function getTabs() - { - $rbacsystem = $this->rbacsystem; - - if ($rbacsystem->checkAccess("visible,read",$this->object->getRefId())) - { - $this->tabs_gui->addTarget("adve_page_editor_settings", - $this->ctrl->getLinkTarget($this, "showGeneralPageEditorSettings"), - array("showPageEditorSettings", "","view")); - - $this->tabs_gui->addTarget("adve_rte_settings", - $this->ctrl->getLinkTarget($this, "settings"), - array("settings","assessment", "survey", "frmPost", "excass"), "", ""); - - $this->tabs_gui->addTarget("adve_char_selector_settings", - $this->ctrl->getLinkTarget($this, "showCharSelectorSettings"), - array("showCharSelectorSettings", "","view")); - } - - 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'); - } - $this->addSubtabs($this->tabs_gui); - } - - - /** - * Display assessment folder settings form - */ - function settingsObject() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $editor = $this->object->_getRichTextEditor(); - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - $this->form->setFormAction($ilCtrl->getFormAction($this)); - $this->form->setTitle($lng->txt("adve_activation")); - $cb = new ilCheckboxInputGUI($this->lng->txt("adve_use_tiny_mce"), "use_tiny"); - if ($editor == "tinymce") - { - $cb->setChecked(true); - } - $this->form->addItem($cb); - if ($this->checkPermissionBool("write")) - { - $this->form->addCommandButton("saveSettings", $lng->txt("save")); - } - - $tpl->setContent($this->form->getHTML()); - } - - /** - * Save Assessment settings - */ - function saveSettingsObject() - { - $this->checkPermission("write"); - - if ($_POST["use_tiny"]) - { - $this->object->setRichTextEditor("tinymce"); - } - else - { - $this->object->setRichTextEditor(""); - } - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"),true); - - $this->ctrl->redirect($this,'settings'); - } - - - /** - * Display settings for test and assessment. - */ - function assessmentObject() - { - $form = $this->initTagsForm("assessment", "saveAssessmentSettings", - "advanced_editing_assessment_settings"); - - $this->tpl->setContent($form->getHTML()); - } - - function saveAssessmentSettingsObject() - { - $this->saveTags("assessment", "assessment"); - } - - - /** - * Display settings for surveys. - */ - function surveyObject() - { - $form = $this->initTagsForm("survey", "saveSurveySettings", - "advanced_editing_survey_settings"); - - $this->tpl->setContent($form->getHTML()); - } - - function saveSurveySettingsObject() - { - $this->saveTags("survey", "survey"); - } - - - /** - * Display settings for forums. - */ - public function frmPostObject() - { - $form = $this->initTagsForm("frm_post", "saveFrmPostSettings", - "advanced_editing_frm_post_settings"); - - $this->tpl->setContent($form->getHTML()); - } - - public function saveFrmPostSettingsObject() - { - $this->saveTags("frm_post", "frmPost"); - } - - - /** - * Display settings for exercise assignments. - */ - public function excAssObject() - { - $form = $this->initTagsForm("exc_ass", "saveExcAssSettings", - "advanced_editing_excass_settings"); - - $this->tpl->setContent($form->getHTML()); - } - - public function saveExcAssSettingsObject() - { - $this->saveTags("exc_ass", "excAss"); - } - - - protected function initTagsForm($a_id, $a_cmd, $a_title) - { - $ilAccess = $this->access; - - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this, $a_cmd)); - $form->setTitle($this->lng->txt($a_title)); - - $alltags = $this->object->getHTMLTags(); - $alltags = array_combine($alltags, $alltags); - - include_once "Services/Form/classes/class.ilMultiSelectInputGUI.php"; - $tags = new ilMultiSelectInputGUI($this->lng->txt("advanced_editing_allow_html_tags"), "html_tags"); - $tags->setHeight(400); - $tags->enableSelectAll(true); - $tags->enableSelectedFirst(true); - $tags->setOptions($alltags); - $tags->setValue(ilObjAdvancedEditing::_getUsedHTMLTags($a_id)); - $form->addItem($tags); - - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - $form->addCommandButton($a_cmd, $this->lng->txt("save")); - } - - return $form; - } - - protected function saveTags($a_id, $a_cmd) - { - $this->checkPermission("write"); - try - { - // get rid of select all - if(is_array($_POST['html_tags']) && $_POST['html_tags'][0] == "") - { - unset($_POST['html_tags'][0]); - } - - $this->object->setUsedHTMLTags((array)$_POST['html_tags'], $a_id); - ilUtil::sendSuccess($this->lng->txt('msg_obj_modified'), true); - } - catch(ilAdvancedEditingRequiredTagsException $e) - { - ilUtil::sendInfo($e->getMessage(), true); - } - - $this->ctrl->redirect($this, $a_cmd); - } - - - /** - * Show page editor settings - */ - function showPageEditorSettingsObject() - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - - $this->addPageEditorSettingsSubTabs(); - - include_once("./Services/COPage/classes/class.ilPageEditorSettings.php"); - $grps = ilPageEditorSettings::getGroups(); - - $this->cgrp = $_GET["grp"]; - if ($this->cgrp == "") - { - $this->cgrp = key($grps); - } - - $ilCtrl->setParameter($this, "grp", $this->cgrp); - $ilTabs->setSubTabActive("adve_grp_".$this->cgrp); - - $this->initPageEditorForm(); - $tpl->setContent($this->form->getHtml()); - } - - /** - * Init page editor form. - * - * @param int $a_mode Edit Mode - */ - public function initPageEditorForm($a_mode = "edit") - { - $lng = $this->lng; - $ilSetting = $this->settings; - - $lng->loadLanguageModule("content"); - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - if( $this->cgrp == "test" ) - { - require_once 'Modules/Test/classes/class.ilObjAssessmentFolder.php'; - - $this->form->setTitle($lng->txt("adve_activation")); - $cb = new ilCheckboxInputGUI($this->lng->txt("advanced_editing_tst_editing"), "tst_page_edit"); - $cb->setInfo($this->lng->txt("advanced_editing_tst_editing_desc")); - if ($ilSetting->get("enable_tst_page_edit", ilObjAssessmentFolder::ADDITIONAL_QUESTION_CONTENT_EDITING_MODE_PAGE_OBJECT_DISABLED)) - { - $cb->setChecked(true); - } - $this->form->addItem($cb); - - $sh = new ilFormSectionHeaderGUI(); - $sh->setTitle($lng->txt("adve_text_content_features")); - $this->form->addItem($sh); - } - elseif ($this->cgrp == "rep") - { - $this->form->setTitle($lng->txt("adve_activation")); - $cb = new ilCheckboxInputGUI($this->lng->txt("advanced_editing_rep_page_editing"), "cat_page_edit"); - $cb->setInfo($this->lng->txt("advanced_editing_rep_page_editing_desc")); - if ($ilSetting->get("enable_cat_page_edit")) - { - $cb->setChecked(true); - } - $this->form->addItem($cb); - - $sh = new ilFormSectionHeaderGUI(); - $sh->setTitle($lng->txt("adve_text_content_features")); - $this->form->addItem($sh); - } - else - { - $this->form->setTitle($lng->txt("adve_text_content_features")); - } - - - include_once("./Services/COPage/classes/class.ilPageEditorSettings.php"); - - include_once("./Services/COPage/classes/class.ilPageContentGUI.php"); - $buttons = ilPageContentGUI::_getCommonBBButtons(); - foreach ($buttons as $b => $t) - { - // command button activation - $cb = new ilCheckboxInputGUI(str_replace(":", "", $this->lng->txt("cont_text_".$b)), "active_".$b); - $cb->setChecked(ilPageEditorSettings::lookupSetting($this->cgrp, "active_".$b, true)); - $this->form->addItem($cb); - } - - // save and cancel commands - if ($this->checkPermissionBool("write")) - { - $this->form->addCommandButton("savePageEditorSettings", $lng->txt("save")); - } - - $this->form->setFormAction($this->ctrl->getFormAction($this)); - - } - - /** - * Save page editor settings form - * - */ - public function savePageEditorSettingsObject() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilSetting = $this->settings; - - $this->checkPermission("write"); - - $this->initPageEditorForm(); - if ($this->form->checkInput()) - { - include_once("./Services/COPage/classes/class.ilPageEditorSettings.php"); - include_once("./Services/COPage/classes/class.ilPageContentGUI.php"); - $buttons = ilPageContentGUI::_getCommonBBButtons(); - foreach ($buttons as $b => $t) - { - ilPageEditorSettings::writeSetting($_GET["grp"], "active_".$b, - $this->form->getInput("active_".$b)); - } - - if ($_GET["grp"] == "test") - { - $ilSetting->set("enable_tst_page_edit", (int) $_POST["tst_page_edit"]); - } - elseif ($_GET["grp"] == "rep") - { - $ilSetting->set("enable_cat_page_edit", (int) $_POST["cat_page_edit"]); - } - - ilUtil::sendInfo($lng->txt("msg_obj_modified"), true); - } - - $ilCtrl->setParameter($this, "grp", $_GET["grp"]); - $ilCtrl->redirect($this, "showPageEditorSettings"); - } - - - /** - * Show general page editor settings - */ - function showGeneralPageEditorSettingsObject() - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - $this->addPageEditorSettingsSubTabs(); - $ilTabs->activateTab("adve_page_editor_settings"); - - $form = $this->initGeneralPageSettingsForm(); - $tpl->setContent($form->getHTML()); - } - - /** - * Init general page editor settings form. - */ - public function initGeneralPageSettingsForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - - $aset = new ilSetting("adve"); - - // use physical character styles - $cb = new ilCheckboxInputGUI($this->lng->txt("adve_use_physical"), "use_physical"); - $cb->setInfo($this->lng->txt("adve_use_physical_info")); - $cb->setChecked($aset->get("use_physical")); - $form->addItem($cb); - - // blocking mode - $cb = new ilCheckboxInputGUI($this->lng->txt("adve_blocking_mode"), "block_mode_act"); - $cb->setChecked($aset->get("block_mode_minutes") > 0); - $form->addItem($cb); - - // number of minutes - $ni = new ilNumberInputGUI($this->lng->txt("adve_minutes"), "block_mode_minutes"); - $ni->setMinValue(2); - $ni->setMaxLength(5); - $ni->setSize(5); - $ni->setRequired(true); - $ni->setInfo($this->lng->txt("adve_minutes_info")); - $ni->setValue($aset->get("block_mode_minutes")); - $cb->addSubItem($ni); - - // auto url linking - $cb = new ilCheckboxInputGUI($this->lng->txt("adve_auto_url_linking"), "auto_url_linking"); - $cb->setChecked($aset->get("auto_url_linking")); - $cb->setInfo($this->lng->txt("adve_auto_url_linking_info")); - $form->addItem($cb); - - if ($this->checkPermissionBool("write")) - { - $form->addCommandButton("saveGeneralPageSettings", $lng->txt("save")); - } - - $form->setTitle($lng->txt("adve_pe_general")); - $form->setFormAction($ilCtrl->getFormAction($this)); - - return $form; - } - - /** - * Save general page settings - */ - function saveGeneralPageSettingsObject() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - - $this->checkPermission("write"); - - $form = $this->initGeneralPageSettingsForm(); - if ($form->checkInput()) - { - $aset = new ilSetting("adve"); - $aset->set("use_physical", $_POST["use_physical"]); - if ($_POST["block_mode_act"]) - { - $aset->set("block_mode_minutes", (int) $_POST["block_mode_minutes"]); - } - else - { - $aset->set("block_mode_minutes", 0); - } - $aset->set("auto_url_linking", $_POST["auto_url_linking"]); - - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "showGeneralPageEditorSettings"); - } - - $form->setValuesByPost(); - $tpl->setContent($form->getHTML()); - } - - /** - * Init the settings form for the selector of unicode characters - */ - public function initCharSelectorSettingsForm(ilCharSelectorGUI $char_selector) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setTitle($lng->txt('settings')); - $form->setFormAction($ilCtrl->getFormAction($this)); - if ($this->checkPermissionBool("write")) - { - $form->addCommandButton("saveCharSelectorSettings", $lng->txt("save")); - } - $char_selector->addFormProperties($form); - - return $form; - } - - - /** - * Show the settings for the selector of unicode characters - */ - function showCharSelectorSettingsObject() - { - $ilTabs = $this->tabs; - $ilSetting = $this->settings; - $tpl = $this->tpl; - - $ilTabs->activateTab("adve_char_selector_settings"); - - require_once 'Services/UIComponent/CharSelector/classes/class.ilCharSelectorGUI.php'; - $char_selector = new ilCharSelectorGUI(ilCharSelectorConfig::CONTEXT_ADMIN); - $char_selector->getConfig()->setAvailability($ilSetting->get('char_selector_availability')); - $char_selector->getConfig()->setDefinition($ilSetting->get('char_selector_definition')); - $form = $this->initCharSelectorSettingsForm($char_selector); - $char_selector->setFormValues($form); - $tpl->setContent($form->getHTML()); - } - - - /** - * Save the settings for the selector of unicode characters - */ - function saveCharSelectorSettingsObject() - { - $ilSetting = $this->settings; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - - $this->checkPermission("write"); - - require_once 'Services/UIComponent/CharSelector/classes/class.ilCharSelectorGUI.php'; - $char_selector = new ilCharSelectorGUI(ilCharSelectorConfig::CONTEXT_ADMIN); - $form = $this->initCharSelectorSettingsForm($char_selector); - if ($form->checkInput()) - { - $char_selector->getFormValues($form); - - $ilSetting->set('char_selector_availability', $char_selector->getConfig()->getAvailability()); - $ilSetting->set('char_selector_definition', $char_selector->getConfig()->getDefinition()); - - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "showCharSelectorSettings"); + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilRbacAdmin + */ + protected $rbacadmin; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilSetting + */ + protected $settings; + + public $conditions; + + /** + * Constructor + */ + public function __construct($a_data, $a_id, $a_call_by_reference) + { + global $DIC; + + $this->rbacsystem = $DIC->rbac()->system(); + $this->rbacadmin = $DIC->rbac()->admin(); + $this->ctrl = $DIC->ctrl(); + $this->tabs = $DIC->tabs(); + $this->tpl = $DIC["tpl"]; + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->settings = $DIC->settings(); + $rbacsystem = $DIC->rbac()->system(); + + $this->type = "adve"; + parent::__construct($a_data, $a_id, $a_call_by_reference, false); + $this->lng->loadLanguageModule('adve'); + $this->lng->loadLanguageModule('meta'); + + if (!$rbacsystem->checkAccess('read', $this->object->getRefId())) { + $this->ilias->raiseError($this->lng->txt("msg_no_perm_read_adve"), $this->ilias->error_obj->WARNING); + } + } + + public function executeCommand() + { + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + $this->prepareOutput(); + + switch ($next_class) { + + case 'ilpermissiongui': + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $ret =&$this->ctrl->forwardCommand($perm_gui); + break; + + default: + if ($cmd == "" || $cmd == "view") { + $cmd = "showGeneralPageEditorSettings"; + } + $cmd .= "Object"; + $this->$cmd(); + + break; + } + return true; + } + + /** + * save object + * @access public + */ + public function saveObject() + { + $this->checkPermission("write"); + + parent::saveObject(); + + // always send a message + ilUtil::sendSuccess($this->lng->txt("object_added"), true); + $this->ctrl->redirect($this); + } + + public function getAdminTabs() + { + $this->getTabs(); + } + + /** + * Add rte subtabs + */ + public function addSubtabs() + { + $ilCtrl = $this->ctrl; + + if ($ilCtrl->getNextClass() != "ilpermissiongui" && + !in_array($ilCtrl->getCmd(), array("showPageEditorSettings", + "showGeneralPageEditorSettings", "showCharSelectorSettings", "", "view"))) { + $this->tabs_gui->addSubTabTarget( + "adve_general_settings", + $this->ctrl->getLinkTarget($this, "settings"), + array("settings", "saveSettings"), + "", + "" + ); + $this->tabs_gui->addSubTabTarget( + "adve_assessment_settings", + $this->ctrl->getLinkTarget($this, "assessment"), + array("assessment", "saveAssessmentSettings"), + "", + "" + ); + $this->tabs_gui->addSubTabTarget( + "adve_survey_settings", + $this->ctrl->getLinkTarget($this, "survey"), + array("survey", "saveSurveySettings"), + "", + "" + ); + $this->tabs_gui->addSubTabTarget( + "adve_frm_post_settings", + $this->ctrl->getLinkTarget($this, "frmPost"), + array("frmPost", "saveFrmPostSettings"), + "", + "" + ); + $this->tabs_gui->addSubTabTarget( + "adve_excass_settings", + $this->ctrl->getLinkTarget($this, "excass"), + array("excass", "saveExcAssSettings"), + "", + "" + ); + } + } + + /** + * Show page editor settings subtabs + */ + public function addPageEditorSettingsSubtabs() + { + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + $ilTabs->addSubTabTarget( + "adve_pe_general", + $ilCtrl->getLinkTarget($this, "showGeneralPageEditorSettings"), + array("showGeneralPageEditorSettings", "", "view") + ); + + include_once("./Services/COPage/classes/class.ilPageEditorSettings.php"); + $grps = ilPageEditorSettings::getGroups(); + + foreach ($grps as $g => $types) { + $ilCtrl->setParameter($this, "grp", $g); + $ilTabs->addSubTabTarget( + "adve_grp_" . $g, + $ilCtrl->getLinkTarget($this, "showPageEditorSettings"), + array("showPageEditorSettings") + ); + } + $ilCtrl->setParameter($this, "grp", $_GET["grp"]); + } + + /** + * get tabs + * @access public + * @param object tabs gui object + */ + public function getTabs() + { + $rbacsystem = $this->rbacsystem; + + if ($rbacsystem->checkAccess("visible,read", $this->object->getRefId())) { + $this->tabs_gui->addTarget( + "adve_page_editor_settings", + $this->ctrl->getLinkTarget($this, "showGeneralPageEditorSettings"), + array("showPageEditorSettings", "","view") + ); + + $this->tabs_gui->addTarget( + "adve_rte_settings", + $this->ctrl->getLinkTarget($this, "settings"), + array("settings","assessment", "survey", "frmPost", "excass"), + "", + "" + ); + + $this->tabs_gui->addTarget( + "adve_char_selector_settings", + $this->ctrl->getLinkTarget($this, "showCharSelectorSettings"), + array("showCharSelectorSettings", "","view") + ); + } + + 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' + ); + } + $this->addSubtabs($this->tabs_gui); + } + + + /** + * Display assessment folder settings form + */ + public function settingsObject() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $editor = $this->object->_getRichTextEditor(); + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + $this->form->setFormAction($ilCtrl->getFormAction($this)); + $this->form->setTitle($lng->txt("adve_activation")); + $cb = new ilCheckboxInputGUI($this->lng->txt("adve_use_tiny_mce"), "use_tiny"); + if ($editor == "tinymce") { + $cb->setChecked(true); + } + $this->form->addItem($cb); + if ($this->checkPermissionBool("write")) { + $this->form->addCommandButton("saveSettings", $lng->txt("save")); + } + + $tpl->setContent($this->form->getHTML()); + } + + /** + * Save Assessment settings + */ + public function saveSettingsObject() + { + $this->checkPermission("write"); + + if ($_POST["use_tiny"]) { + $this->object->setRichTextEditor("tinymce"); + } else { + $this->object->setRichTextEditor(""); + } + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + + $this->ctrl->redirect($this, 'settings'); + } + + + /** + * Display settings for test and assessment. + */ + public function assessmentObject() + { + $form = $this->initTagsForm( + "assessment", + "saveAssessmentSettings", + "advanced_editing_assessment_settings" + ); + + $this->tpl->setContent($form->getHTML()); + } + + public function saveAssessmentSettingsObject() + { + $this->saveTags("assessment", "assessment"); + } + + + /** + * Display settings for surveys. + */ + public function surveyObject() + { + $form = $this->initTagsForm( + "survey", + "saveSurveySettings", + "advanced_editing_survey_settings" + ); + + $this->tpl->setContent($form->getHTML()); + } + + public function saveSurveySettingsObject() + { + $this->saveTags("survey", "survey"); + } + + + /** + * Display settings for forums. + */ + public function frmPostObject() + { + $form = $this->initTagsForm( + "frm_post", + "saveFrmPostSettings", + "advanced_editing_frm_post_settings" + ); + + $this->tpl->setContent($form->getHTML()); + } + + public function saveFrmPostSettingsObject() + { + $this->saveTags("frm_post", "frmPost"); + } + + + /** + * Display settings for exercise assignments. + */ + public function excAssObject() + { + $form = $this->initTagsForm( + "exc_ass", + "saveExcAssSettings", + "advanced_editing_excass_settings" + ); + + $this->tpl->setContent($form->getHTML()); + } + + public function saveExcAssSettingsObject() + { + $this->saveTags("exc_ass", "excAss"); + } + + + protected function initTagsForm($a_id, $a_cmd, $a_title) + { + $ilAccess = $this->access; + + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this, $a_cmd)); + $form->setTitle($this->lng->txt($a_title)); + + $alltags = $this->object->getHTMLTags(); + $alltags = array_combine($alltags, $alltags); + + include_once "Services/Form/classes/class.ilMultiSelectInputGUI.php"; + $tags = new ilMultiSelectInputGUI($this->lng->txt("advanced_editing_allow_html_tags"), "html_tags"); + $tags->setHeight(400); + $tags->enableSelectAll(true); + $tags->enableSelectedFirst(true); + $tags->setOptions($alltags); + $tags->setValue(ilObjAdvancedEditing::_getUsedHTMLTags($a_id)); + $form->addItem($tags); + + if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) { + $form->addCommandButton($a_cmd, $this->lng->txt("save")); + } + + return $form; + } + + protected function saveTags($a_id, $a_cmd) + { + $this->checkPermission("write"); + try { + // get rid of select all + if (is_array($_POST['html_tags']) && $_POST['html_tags'][0] == "") { + unset($_POST['html_tags'][0]); + } + + $this->object->setUsedHTMLTags((array) $_POST['html_tags'], $a_id); + ilUtil::sendSuccess($this->lng->txt('msg_obj_modified'), true); + } catch (ilAdvancedEditingRequiredTagsException $e) { + ilUtil::sendInfo($e->getMessage(), true); + } + + $this->ctrl->redirect($this, $a_cmd); + } + + + /** + * Show page editor settings + */ + public function showPageEditorSettingsObject() + { + $tpl = $this->tpl; + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + + $this->addPageEditorSettingsSubTabs(); + + include_once("./Services/COPage/classes/class.ilPageEditorSettings.php"); + $grps = ilPageEditorSettings::getGroups(); + + $this->cgrp = $_GET["grp"]; + if ($this->cgrp == "") { + $this->cgrp = key($grps); + } + + $ilCtrl->setParameter($this, "grp", $this->cgrp); + $ilTabs->setSubTabActive("adve_grp_" . $this->cgrp); + + $this->initPageEditorForm(); + $tpl->setContent($this->form->getHtml()); + } + + /** + * Init page editor form. + * + * @param int $a_mode Edit Mode + */ + public function initPageEditorForm($a_mode = "edit") + { + $lng = $this->lng; + $ilSetting = $this->settings; + + $lng->loadLanguageModule("content"); + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + if ($this->cgrp == "test") { + require_once 'Modules/Test/classes/class.ilObjAssessmentFolder.php'; + + $this->form->setTitle($lng->txt("adve_activation")); + $cb = new ilCheckboxInputGUI($this->lng->txt("advanced_editing_tst_editing"), "tst_page_edit"); + $cb->setInfo($this->lng->txt("advanced_editing_tst_editing_desc")); + if ($ilSetting->get("enable_tst_page_edit", ilObjAssessmentFolder::ADDITIONAL_QUESTION_CONTENT_EDITING_MODE_PAGE_OBJECT_DISABLED)) { + $cb->setChecked(true); + } + $this->form->addItem($cb); + + $sh = new ilFormSectionHeaderGUI(); + $sh->setTitle($lng->txt("adve_text_content_features")); + $this->form->addItem($sh); + } elseif ($this->cgrp == "rep") { + $this->form->setTitle($lng->txt("adve_activation")); + $cb = new ilCheckboxInputGUI($this->lng->txt("advanced_editing_rep_page_editing"), "cat_page_edit"); + $cb->setInfo($this->lng->txt("advanced_editing_rep_page_editing_desc")); + if ($ilSetting->get("enable_cat_page_edit")) { + $cb->setChecked(true); + } + $this->form->addItem($cb); + + $sh = new ilFormSectionHeaderGUI(); + $sh->setTitle($lng->txt("adve_text_content_features")); + $this->form->addItem($sh); + } else { + $this->form->setTitle($lng->txt("adve_text_content_features")); + } + + + include_once("./Services/COPage/classes/class.ilPageEditorSettings.php"); + + include_once("./Services/COPage/classes/class.ilPageContentGUI.php"); + $buttons = ilPageContentGUI::_getCommonBBButtons(); + foreach ($buttons as $b => $t) { + // command button activation + $cb = new ilCheckboxInputGUI(str_replace(":", "", $this->lng->txt("cont_text_" . $b)), "active_" . $b); + $cb->setChecked(ilPageEditorSettings::lookupSetting($this->cgrp, "active_" . $b, true)); + $this->form->addItem($cb); + } + + // save and cancel commands + if ($this->checkPermissionBool("write")) { + $this->form->addCommandButton("savePageEditorSettings", $lng->txt("save")); + } + + $this->form->setFormAction($this->ctrl->getFormAction($this)); + } + + /** + * Save page editor settings form + * + */ + public function savePageEditorSettingsObject() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilSetting = $this->settings; + + $this->checkPermission("write"); + + $this->initPageEditorForm(); + if ($this->form->checkInput()) { + include_once("./Services/COPage/classes/class.ilPageEditorSettings.php"); + include_once("./Services/COPage/classes/class.ilPageContentGUI.php"); + $buttons = ilPageContentGUI::_getCommonBBButtons(); + foreach ($buttons as $b => $t) { + ilPageEditorSettings::writeSetting( + $_GET["grp"], + "active_" . $b, + $this->form->getInput("active_" . $b) + ); + } + + if ($_GET["grp"] == "test") { + $ilSetting->set("enable_tst_page_edit", (int) $_POST["tst_page_edit"]); + } elseif ($_GET["grp"] == "rep") { + $ilSetting->set("enable_cat_page_edit", (int) $_POST["cat_page_edit"]); + } + + ilUtil::sendInfo($lng->txt("msg_obj_modified"), true); + } + + $ilCtrl->setParameter($this, "grp", $_GET["grp"]); + $ilCtrl->redirect($this, "showPageEditorSettings"); + } + + + /** + * Show general page editor settings + */ + public function showGeneralPageEditorSettingsObject() + { + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + $this->addPageEditorSettingsSubTabs(); + $ilTabs->activateTab("adve_page_editor_settings"); + + $form = $this->initGeneralPageSettingsForm(); + $tpl->setContent($form->getHTML()); + } + + /** + * Init general page editor settings form. + */ + public function initGeneralPageSettingsForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + + $aset = new ilSetting("adve"); + + // use physical character styles + $cb = new ilCheckboxInputGUI($this->lng->txt("adve_use_physical"), "use_physical"); + $cb->setInfo($this->lng->txt("adve_use_physical_info")); + $cb->setChecked($aset->get("use_physical")); + $form->addItem($cb); + + // blocking mode + $cb = new ilCheckboxInputGUI($this->lng->txt("adve_blocking_mode"), "block_mode_act"); + $cb->setChecked($aset->get("block_mode_minutes") > 0); + $form->addItem($cb); + + // number of minutes + $ni = new ilNumberInputGUI($this->lng->txt("adve_minutes"), "block_mode_minutes"); + $ni->setMinValue(2); + $ni->setMaxLength(5); + $ni->setSize(5); + $ni->setRequired(true); + $ni->setInfo($this->lng->txt("adve_minutes_info")); + $ni->setValue($aset->get("block_mode_minutes")); + $cb->addSubItem($ni); + + // auto url linking + $cb = new ilCheckboxInputGUI($this->lng->txt("adve_auto_url_linking"), "auto_url_linking"); + $cb->setChecked($aset->get("auto_url_linking")); + $cb->setInfo($this->lng->txt("adve_auto_url_linking_info")); + $form->addItem($cb); + + if ($this->checkPermissionBool("write")) { + $form->addCommandButton("saveGeneralPageSettings", $lng->txt("save")); } + + $form->setTitle($lng->txt("adve_pe_general")); + $form->setFormAction($ilCtrl->getFormAction($this)); + + return $form; + } + + /** + * Save general page settings + */ + public function saveGeneralPageSettingsObject() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + + $this->checkPermission("write"); + + $form = $this->initGeneralPageSettingsForm(); + if ($form->checkInput()) { + $aset = new ilSetting("adve"); + $aset->set("use_physical", $_POST["use_physical"]); + if ($_POST["block_mode_act"]) { + $aset->set("block_mode_minutes", (int) $_POST["block_mode_minutes"]); + } else { + $aset->set("block_mode_minutes", 0); + } + $aset->set("auto_url_linking", $_POST["auto_url_linking"]); + + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "showGeneralPageEditorSettings"); + } + $form->setValuesByPost(); $tpl->setContent($form->getHTML()); - } - - + } + + /** + * Init the settings form for the selector of unicode characters + */ + public function initCharSelectorSettingsForm(ilCharSelectorGUI $char_selector) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setTitle($lng->txt('settings')); + $form->setFormAction($ilCtrl->getFormAction($this)); + if ($this->checkPermissionBool("write")) { + $form->addCommandButton("saveCharSelectorSettings", $lng->txt("save")); + } + $char_selector->addFormProperties($form); + + return $form; + } + + + /** + * Show the settings for the selector of unicode characters + */ + public function showCharSelectorSettingsObject() + { + $ilTabs = $this->tabs; + $ilSetting = $this->settings; + $tpl = $this->tpl; + + $ilTabs->activateTab("adve_char_selector_settings"); + + require_once 'Services/UIComponent/CharSelector/classes/class.ilCharSelectorGUI.php'; + $char_selector = new ilCharSelectorGUI(ilCharSelectorConfig::CONTEXT_ADMIN); + $char_selector->getConfig()->setAvailability($ilSetting->get('char_selector_availability')); + $char_selector->getConfig()->setDefinition($ilSetting->get('char_selector_definition')); + $form = $this->initCharSelectorSettingsForm($char_selector); + $char_selector->setFormValues($form); + $tpl->setContent($form->getHTML()); + } + + + /** + * Save the settings for the selector of unicode characters + */ + public function saveCharSelectorSettingsObject() + { + $ilSetting = $this->settings; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + + $this->checkPermission("write"); + + require_once 'Services/UIComponent/CharSelector/classes/class.ilCharSelectorGUI.php'; + $char_selector = new ilCharSelectorGUI(ilCharSelectorConfig::CONTEXT_ADMIN); + $form = $this->initCharSelectorSettingsForm($char_selector); + if ($form->checkInput()) { + $char_selector->getFormValues($form); + + $ilSetting->set('char_selector_availability', $char_selector->getConfig()->getAvailability()); + $ilSetting->set('char_selector_definition', $char_selector->getConfig()->getDefinition()); + + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "showCharSelectorSettings"); + } + $form->setValuesByPost(); + $tpl->setContent($form->getHTML()); + } } // END class.ilObjAdvancedEditingGUI -?> diff --git a/Services/AdvancedEditing/exceptions/class.ilAdvancedEditingException.php b/Services/AdvancedEditing/exceptions/class.ilAdvancedEditingException.php index f37b98c8f903d7a1704cdf35dbac3c703f151605..38dbc6bcbe3a3a9e13ff24129b9ee435ab2f594e 100644 --- a/Services/AdvancedEditing/exceptions/class.ilAdvancedEditingException.php +++ b/Services/AdvancedEditing/exceptions/class.ilAdvancedEditingException.php @@ -1,29 +1,28 @@ -* @version $Id$ -* +* @version $Id$ +* */ class ilAdvancedEditingException extends ilException { - /** - * Constructor - * - * A message is not optional as in build in class Exception - * - * @access public - * @param string $a_message message - * - */ - public function __construct($a_message) - { - parent::__construct($a_message); - } + /** + * Constructor + * + * A message is not optional as in build in class Exception + * + * @access public + * @param string $a_message message + * + */ + public function __construct($a_message) + { + parent::__construct($a_message); + } } -?> \ No newline at end of file diff --git a/Services/AdvancedEditing/exceptions/class.ilAdvancedEditingRequiredTagsException.php b/Services/AdvancedEditing/exceptions/class.ilAdvancedEditingRequiredTagsException.php index 075d3e5ad2a2a24a934d94110371dd5339c19eb1..a4df6a68fc987e34b90b86260a40290279297eff 100644 --- a/Services/AdvancedEditing/exceptions/class.ilAdvancedEditingRequiredTagsException.php +++ b/Services/AdvancedEditing/exceptions/class.ilAdvancedEditingRequiredTagsException.php @@ -1,29 +1,28 @@ -* @version $Id$ -* +* @version $Id$ +* */ class ilAdvancedEditingRequiredTagsException extends ilAdvancedEditingException { - /** - * Constructor - * - * A message is not optional as in build in class Exception - * - * @access public - * @param string $a_message message - * - */ - public function __construct($a_message) - { - parent::__construct($a_message); - } + /** + * Constructor + * + * A message is not optional as in build in class Exception + * + * @access public + * @param string $a_message message + * + */ + public function __construct($a_message) + { + parent::__construct($a_message); + } } -?> \ No newline at end of file diff --git a/Services/Awareness/classes/class.ilAwarenessAct.php b/Services/Awareness/classes/class.ilAwarenessAct.php index 6f9121b1f1ac4e463acd79d903a9ff760cf51aad..41bf66140a8d4b919536ea047b05cd3f28e419f8 100644 --- a/Services/Awareness/classes/class.ilAwarenessAct.php +++ b/Services/Awareness/classes/class.ilAwarenessAct.php @@ -11,159 +11,149 @@ */ class ilAwarenessAct { - /** - * @var ilLanguage - */ - protected $lng; - - protected static $instances = array(); - protected $user_id; - protected $ref_id = 0; - protected static $collector; - - /** - * Constructor - * - * @param int $a_user_id user ud - */ - protected function __construct($a_user_id) - { - global $DIC; - - $this->lng = $DIC->language(); - $this->user_id = $a_user_id; - } - - /** - * Set ref id - * - * @param int $a_val ref id - */ - function setRefId($a_val) - { - $this->ref_id = $a_val; - } - - /** - * Get ref id - * - * @return int ref id - */ - function getRefId() - { - return $this->ref_id; - } - - /** - * Get instance (for a user) - * - * @param int $a_user_id user id - * @return ilAwarenessAct actor class - */ - static function getInstance($a_user_id) - { - if (!isset(self::$instances[$a_user_id])) - { - self::$instances[$a_user_id] = new ilAwarenessAct($a_user_id); - } - - return self::$instances[$a_user_id]; - } - - /** - * Get awareness data - * - * @return ilAwarenessData awareness data - */ - function getAwarenessData($a_filter) - { - include_once("./Services/Awareness/classes/class.ilAwarenessData.php"); - $data = ilAwarenessData::getInstance($this->user_id); - $data->setRefId($this->getRefId()); - $data->setFilter($a_filter); - return $data->getData(); - } - - /** - * Get awareness data - * - * @return ilAwarenessData awareness data - */ - function getAwarenessUserCounter() - { - include_once("./Services/Awareness/classes/class.ilAwarenessData.php"); - $data = ilAwarenessData::getInstance($this->user_id); - $data->setRefId($this->getRefId()); - return $data->getUserCounter(); - } - - /** - * Send OSD notification on new users - */ - function notifyOnNewOnlineContacts() - { - $lng = $this->lng; - - $awrn_set = new ilSetting("awrn"); - if (!$awrn_set->get("use_osd", true)) - { - return; - } - - $ts = ilSession::get("awr_online_user_ts"); - - $data = ilAwarenessData::getInstance($this->user_id); - $data->setRefId($this->getRefId()); - $d = $data->getOnlineUserData($ts); - - $new_online_users = array(); - $no_ids = array(); - foreach ($d as $u) - { - $uname = "[".$u->login."]"; - if ($u->public_profile) - { - $uname = "".$u->lastname.", ".$u->firstname." ".$uname.""; - } - if (!in_array($u->id, $no_ids)) - { - $new_online_users[] = $uname; - $no_ids[] = $u->id; - } - } - - if (count($new_online_users) == 0) - { - return; - } -//var_dump($d); exit; - $lng->loadLanguageModule('mail'); - - include_once("./Services/Object/classes/class.ilObjectFactory.php"); - //$recipient = ilObjectFactory::getInstanceByObjId($this->user_id); - $bodyParams = array( - 'online_user_names' => implode("
", $new_online_users) - ); -//var_dump($bodyParams); exit; - require_once 'Services/Notifications/classes/class.ilNotificationConfig.php'; - $notification = new ilNotificationConfig('osd_main'); - $notification->setTitleVar('awareness_now_online', $bodyParams, 'awrn'); - $notification->setShortDescriptionVar('awareness_now_online_users', $bodyParams, 'awrn'); - $notification->setLongDescriptionVar('', $bodyParams, ''); - $notification->setAutoDisable(false); - //$notification->setLink(); - $notification->setIconPath('templates/default/images/icon_usr.svg'); - $notification->setValidForSeconds(ilNotificationConfig::TTL_SHORT); - $notification->setVisibleForSeconds(ilNotificationConfig::DEFAULT_TTS); - - //$notification->setHandlerParam('mail.sender', $sender_id); - - ilSession::set("awr_online_user_ts", date("Y-m-d H:i:s", time())); - - $notification->notifyByUsers(array($this->user_id)); - } - - + /** + * @var ilLanguage + */ + protected $lng; + + protected static $instances = array(); + protected $user_id; + protected $ref_id = 0; + protected static $collector; + + /** + * Constructor + * + * @param int $a_user_id user ud + */ + protected function __construct($a_user_id) + { + global $DIC; + + $this->lng = $DIC->language(); + $this->user_id = $a_user_id; + } + + /** + * Set ref id + * + * @param int $a_val ref id + */ + public function setRefId($a_val) + { + $this->ref_id = $a_val; + } + + /** + * Get ref id + * + * @return int ref id + */ + public function getRefId() + { + return $this->ref_id; + } + + /** + * Get instance (for a user) + * + * @param int $a_user_id user id + * @return ilAwarenessAct actor class + */ + public static function getInstance($a_user_id) + { + if (!isset(self::$instances[$a_user_id])) { + self::$instances[$a_user_id] = new ilAwarenessAct($a_user_id); + } + + return self::$instances[$a_user_id]; + } + + /** + * Get awareness data + * + * @return ilAwarenessData awareness data + */ + public function getAwarenessData($a_filter) + { + include_once("./Services/Awareness/classes/class.ilAwarenessData.php"); + $data = ilAwarenessData::getInstance($this->user_id); + $data->setRefId($this->getRefId()); + $data->setFilter($a_filter); + return $data->getData(); + } + + /** + * Get awareness data + * + * @return ilAwarenessData awareness data + */ + public function getAwarenessUserCounter() + { + include_once("./Services/Awareness/classes/class.ilAwarenessData.php"); + $data = ilAwarenessData::getInstance($this->user_id); + $data->setRefId($this->getRefId()); + return $data->getUserCounter(); + } + + /** + * Send OSD notification on new users + */ + public function notifyOnNewOnlineContacts() + { + $lng = $this->lng; + + $awrn_set = new ilSetting("awrn"); + if (!$awrn_set->get("use_osd", true)) { + return; + } + + $ts = ilSession::get("awr_online_user_ts"); + + $data = ilAwarenessData::getInstance($this->user_id); + $data->setRefId($this->getRefId()); + $d = $data->getOnlineUserData($ts); + + $new_online_users = array(); + $no_ids = array(); + foreach ($d as $u) { + $uname = "[" . $u->login . "]"; + if ($u->public_profile) { + $uname = "" . $u->lastname . ", " . $u->firstname . " " . $uname . ""; + } + if (!in_array($u->id, $no_ids)) { + $new_online_users[] = $uname; + $no_ids[] = $u->id; + } + } + + if (count($new_online_users) == 0) { + return; + } + //var_dump($d); exit; + $lng->loadLanguageModule('mail'); + + include_once("./Services/Object/classes/class.ilObjectFactory.php"); + //$recipient = ilObjectFactory::getInstanceByObjId($this->user_id); + $bodyParams = array( + 'online_user_names' => implode("
", $new_online_users) + ); + //var_dump($bodyParams); exit; + require_once 'Services/Notifications/classes/class.ilNotificationConfig.php'; + $notification = new ilNotificationConfig('osd_main'); + $notification->setTitleVar('awareness_now_online', $bodyParams, 'awrn'); + $notification->setShortDescriptionVar('awareness_now_online_users', $bodyParams, 'awrn'); + $notification->setLongDescriptionVar('', $bodyParams, ''); + $notification->setAutoDisable(false); + //$notification->setLink(); + $notification->setIconPath('templates/default/images/icon_usr.svg'); + $notification->setValidForSeconds(ilNotificationConfig::TTL_SHORT); + $notification->setVisibleForSeconds(ilNotificationConfig::DEFAULT_TTS); + + //$notification->setHandlerParam('mail.sender', $sender_id); + + ilSession::set("awr_online_user_ts", date("Y-m-d H:i:s", time())); + + $notification->notifyByUsers(array($this->user_id)); + } } - -?> \ No newline at end of file diff --git a/Services/Awareness/classes/class.ilAwarenessData.php b/Services/Awareness/classes/class.ilAwarenessData.php index a9ce34a2a5cb073567d8af42ab282a07c9fd944e..b7405983f94877693d05851bd477caa87a53c4cc 100644 --- a/Services/Awareness/classes/class.ilAwarenessData.php +++ b/Services/Awareness/classes/class.ilAwarenessData.php @@ -3,7 +3,7 @@ /* Copyright (c) 1998-2014 ILIAS open source, Extended GPL, see docs/LICENSE */ /** - * + * * * @author Alex Killing * @version $Id$ @@ -11,359 +11,339 @@ */ class ilAwarenessData { - protected $user_id; - protected $ref_id = 0; - protected $user_collector; - protected $action_collector; - protected $user_collection; - protected $data = null; - protected $online_user_data = null; - static protected $instances = array(); - protected $filter = ""; - - /** - * Constructor - * - * @param - * @return - */ - protected function __construct($a_user_id) - { - $this->user_id = $a_user_id; - - include_once("./Services/Awareness/classes/class.ilAwarenessUserCollector.php"); - $this->user_collector = ilAwarenessUserCollector::getInstance($a_user_id); - include_once("./Services/User/Actions/classes/class.ilUserActionCollector.php"); - include_once("./Services/Awareness/classes/class.ilAwarenessUserActionContext.php"); - $this->action_collector = ilUserActionCollector::getInstance($a_user_id, new ilAwarenessUserActionContext()); - } - - /** - * Set ref id - * - * @param int $a_val ref id - */ - function setRefId($a_val) - { - $this->ref_id = $a_val; - } - - /** - * Get ref id - * - * @return int ref id - */ - function getRefId() - { - return $this->ref_id; - } - - /** - * Set filter - * - * @param string $a_val filter string - */ - function setFilter($a_val) - { - $this->filter = $a_val; - } - - /** - * Get filter - * - * @return string filter string - */ - function getFilter() - { - return $this->filter; - } - - /** - * Maximum for online user data - */ - function getMaxOnlineUserCnt() - { - return 20; - } - - - /** - * Get instance (for a user) - * - * @param int $a_user_id user id - * @return ilAwarenessData actor class - */ - static function getInstance($a_user_id) - { - if (!isset(self::$instances[$a_user_id])) - { - self::$instances[$a_user_id] = new ilAwarenessData($a_user_id); - } - - return self::$instances[$a_user_id]; - } - - - - /** - * Get user collections - * - * @param bool $a_online_only true, if only online users should be collected - * @return array array of collections - */ - function getUserCollections($a_online_only = false) - { - if (!isset($this->user_collections[(int) $a_online_only])) - { - $this->user_collector->setRefId($this->getRefId()); - $this->user_collections[(int) $a_online_only] = $this->user_collector->collectUsers($a_online_only); - } - - return $this->user_collections[(int) $a_online_only]; - } - - /** - * Get user counter - */ - function getUserCounter() - { - $all_user_ids = array(); - $hall_user_ids = array(); - - $user_collections = $this->getUserCollections(); - - foreach ($user_collections as $uc) - { - $user_collection = $uc["collection"]; - $user_ids = $user_collection->getUsers(); - - foreach ($user_ids as $uid) - { - if (!in_array($uid, $all_user_ids)) - { - if ($uc["highlighted"]) - { - $hall_user_ids[] = $uid; - } - else - { - $all_user_ids[] = $uid; - } - } - } - } - - return count($all_user_ids).":".count($hall_user_ids); - } - - /** - * Get online user data - * - * @param string $a_ts timestamp - * @return array array of data objects - */ - function getOnlineUserData($a_ts = "") - { - $online_user_data = array(); - $online_users = ilAwarenessUserCollector::getOnlineUsers(); - $user_collections = $this->getUserCollections(true); // get user collections with online users only - $all_online_user_ids = array(); - - foreach ($user_collections as $uc) - { - $user_collection = $uc["collection"]; - $user_ids = $user_collection->getUsers(); - foreach ($user_ids as $u) - { - if (!in_array($u, $all_online_user_ids)) - { - // check timestamp and limit the max number of user data records received - if (($a_ts == "" || $online_users[$u]["last_login"] > $a_ts) - && count($all_online_user_ids) < $this->getMaxOnlineUserCnt()) - { - $all_online_user_ids[] = $u; - } - } - } - } - - include_once("./Services/User/classes/class.ilUserUtil.php"); - $names = ilUserUtil::getNamePresentation($all_online_user_ids, true, - false, "", false, false, true, true); - - // sort and add online information - foreach ($names as $k => $n) - { - $names[$k]["online"] = true; - $names[$k]["last_login"] = $online_users[$n["id"]]["last_login"]; - $sort_str = ""; - if ($n["public_profile"]) - { - $sort_str.= $n["lastname"]." ".$n["firstname"]; - } - else - { - $sort_str.= $n["login"]; - } - $names[$k]["sort_str"] = $sort_str; - } - - $names = ilUtil::sortArray($names, "sort_str", "asc", false, true); - - foreach ($names as $n) - { - $obj = new stdClass; - $obj->lastname = $n["lastname"]; - $obj->firstname = $n["firstname"]; - $obj->login = $n["login"]; - $obj->id = $n["id"]; - $obj->public_profile = $n["public_profile"]; - $obj->online = $n["online"]; - $obj->last_login = $n["last_login"];; - - $online_user_data[] = $obj; - } - - return $online_user_data; - } - - /** - * Get data - * - * @return array array of data objects - */ - function getData() - { - $awrn_set = new ilSetting("awrn"); - $max = $awrn_set->get("max_nr_entries"); - - $all_user_ids = array(); - $hall_user_ids = array(); - - if ($this->data == null) - { - $online_users = ilAwarenessUserCollector::getOnlineUsers(); - - $user_collections = $this->getUserCollections(); - - $this->data = array(); - - foreach ($user_collections as $uc) - { - - // limit part 1 - if (count($this->data) >= $max) - { - continue; - } - - $user_collection = $uc["collection"]; - $user_ids = $user_collection->getUsers(); - - foreach ($user_ids as $uid) - { - if (!in_array($uid, $all_user_ids)) - { - if ($uc["highlighted"]) - { - $hall_user_ids[] = $uid; - } - else - { - $all_user_ids[] = $uid; - } - } - } - - include_once("./Services/User/classes/class.ilUserUtil.php"); - $names = ilUserUtil::getNamePresentation($user_ids, true, - false, "", false, false, true, true); - - // sort and add online information - foreach ($names as $k => $n) - { - if (isset($online_users[$n["id"]])) - { - $names[$k]["online"] = true; - $names[$k]["last_login"] = $online_users[$n["id"]]["last_login"]; - $sort_str = "1"; - } - else - { - $names[$k]["online"] = false; - $names[$k]["last_login"] = ""; - $sort_str = "2"; - } - if ($n["public_profile"]) - { - $sort_str.= $n["lastname"]." ".$n["firstname"]; - } - else - { - $sort_str.= $n["login"]; - } - $names[$k]["sort_str"] = $sort_str; - } - - $names = ilUtil::sortArray($names, "sort_str", "asc", false, true); - - foreach ($names as $n) - { - // limit part 2 - if (count($this->data) >= $max) - { - continue; - } - - // filter - $filter = trim($this->getFilter()); - if ($filter != "" && - !is_int(stripos($n["login"], $filter)) && - (!$n["public_profile"] || ( - !is_int(stripos($n["firstname"], $filter)) && - !is_int(stripos($n["lastname"], $filter)) - ) - ) - ) - { - continue; - } - - $obj = new stdClass; - $obj->lastname = $n["lastname"]; - $obj->firstname = $n["firstname"]; - $obj->login = $n["login"]; - $obj->id = $n["id"]; - $obj->collector = $uc["uc_title"]; - $obj->highlighted = $uc["highlighted"]; - - //$obj->img = $n["img"]; - $obj->img = ilObjUser::_getPersonalPicturePath($n["id"], "xsmall"); - $obj->public_profile = $n["public_profile"]; - - $obj->online = $n["online"]; - $obj->last_login = $n["last_login"];; - - // get actions - $action_collection = $this->action_collector->getActionsForTargetUser($n["id"]); - $obj->actions = array(); - foreach ($action_collection->getActions() as $action) - { - $f = new stdClass; - $f->text = $action->getText(); - $f->href = $action->getHref(); - $f->data = $action->getData(); - $obj->actions[] = $f; - } - - $this->data[] = $obj; - } - } - } - - return array("data" => $this->data, "cnt" => count($all_user_ids).":".count($hall_user_ids)); - } - + protected $user_id; + protected $ref_id = 0; + protected $user_collector; + protected $action_collector; + protected $user_collection; + protected $data = null; + protected $online_user_data = null; + protected static $instances = array(); + protected $filter = ""; + + /** + * Constructor + * + * @param + * @return + */ + protected function __construct($a_user_id) + { + $this->user_id = $a_user_id; + + include_once("./Services/Awareness/classes/class.ilAwarenessUserCollector.php"); + $this->user_collector = ilAwarenessUserCollector::getInstance($a_user_id); + include_once("./Services/User/Actions/classes/class.ilUserActionCollector.php"); + include_once("./Services/Awareness/classes/class.ilAwarenessUserActionContext.php"); + $this->action_collector = ilUserActionCollector::getInstance($a_user_id, new ilAwarenessUserActionContext()); + } + + /** + * Set ref id + * + * @param int $a_val ref id + */ + public function setRefId($a_val) + { + $this->ref_id = $a_val; + } + + /** + * Get ref id + * + * @return int ref id + */ + public function getRefId() + { + return $this->ref_id; + } + + /** + * Set filter + * + * @param string $a_val filter string + */ + public function setFilter($a_val) + { + $this->filter = $a_val; + } + + /** + * Get filter + * + * @return string filter string + */ + public function getFilter() + { + return $this->filter; + } + + /** + * Maximum for online user data + */ + public function getMaxOnlineUserCnt() + { + return 20; + } + + + /** + * Get instance (for a user) + * + * @param int $a_user_id user id + * @return ilAwarenessData actor class + */ + public static function getInstance($a_user_id) + { + if (!isset(self::$instances[$a_user_id])) { + self::$instances[$a_user_id] = new ilAwarenessData($a_user_id); + } + + return self::$instances[$a_user_id]; + } + + + + /** + * Get user collections + * + * @param bool $a_online_only true, if only online users should be collected + * @return array array of collections + */ + public function getUserCollections($a_online_only = false) + { + if (!isset($this->user_collections[(int) $a_online_only])) { + $this->user_collector->setRefId($this->getRefId()); + $this->user_collections[(int) $a_online_only] = $this->user_collector->collectUsers($a_online_only); + } + + return $this->user_collections[(int) $a_online_only]; + } + + /** + * Get user counter + */ + public function getUserCounter() + { + $all_user_ids = array(); + $hall_user_ids = array(); + + $user_collections = $this->getUserCollections(); + + foreach ($user_collections as $uc) { + $user_collection = $uc["collection"]; + $user_ids = $user_collection->getUsers(); + + foreach ($user_ids as $uid) { + if (!in_array($uid, $all_user_ids)) { + if ($uc["highlighted"]) { + $hall_user_ids[] = $uid; + } else { + $all_user_ids[] = $uid; + } + } + } + } + + return count($all_user_ids) . ":" . count($hall_user_ids); + } + + /** + * Get online user data + * + * @param string $a_ts timestamp + * @return array array of data objects + */ + public function getOnlineUserData($a_ts = "") + { + $online_user_data = array(); + $online_users = ilAwarenessUserCollector::getOnlineUsers(); + $user_collections = $this->getUserCollections(true); // get user collections with online users only + $all_online_user_ids = array(); + + foreach ($user_collections as $uc) { + $user_collection = $uc["collection"]; + $user_ids = $user_collection->getUsers(); + foreach ($user_ids as $u) { + if (!in_array($u, $all_online_user_ids)) { + // check timestamp and limit the max number of user data records received + if (($a_ts == "" || $online_users[$u]["last_login"] > $a_ts) + && count($all_online_user_ids) < $this->getMaxOnlineUserCnt()) { + $all_online_user_ids[] = $u; + } + } + } + } + + include_once("./Services/User/classes/class.ilUserUtil.php"); + $names = ilUserUtil::getNamePresentation( + $all_online_user_ids, + true, + false, + "", + false, + false, + true, + true + ); + + // sort and add online information + foreach ($names as $k => $n) { + $names[$k]["online"] = true; + $names[$k]["last_login"] = $online_users[$n["id"]]["last_login"]; + $sort_str = ""; + if ($n["public_profile"]) { + $sort_str.= $n["lastname"] . " " . $n["firstname"]; + } else { + $sort_str.= $n["login"]; + } + $names[$k]["sort_str"] = $sort_str; + } + + $names = ilUtil::sortArray($names, "sort_str", "asc", false, true); + + foreach ($names as $n) { + $obj = new stdClass; + $obj->lastname = $n["lastname"]; + $obj->firstname = $n["firstname"]; + $obj->login = $n["login"]; + $obj->id = $n["id"]; + $obj->public_profile = $n["public_profile"]; + $obj->online = $n["online"]; + $obj->last_login = $n["last_login"]; + ; + + $online_user_data[] = $obj; + } + + return $online_user_data; + } + + /** + * Get data + * + * @return array array of data objects + */ + public function getData() + { + $awrn_set = new ilSetting("awrn"); + $max = $awrn_set->get("max_nr_entries"); + + $all_user_ids = array(); + $hall_user_ids = array(); + + if ($this->data == null) { + $online_users = ilAwarenessUserCollector::getOnlineUsers(); + + $user_collections = $this->getUserCollections(); + + $this->data = array(); + + foreach ($user_collections as $uc) { + + // limit part 1 + if (count($this->data) >= $max) { + continue; + } + + $user_collection = $uc["collection"]; + $user_ids = $user_collection->getUsers(); + + foreach ($user_ids as $uid) { + if (!in_array($uid, $all_user_ids)) { + if ($uc["highlighted"]) { + $hall_user_ids[] = $uid; + } else { + $all_user_ids[] = $uid; + } + } + } + + include_once("./Services/User/classes/class.ilUserUtil.php"); + $names = ilUserUtil::getNamePresentation( + $user_ids, + true, + false, + "", + false, + false, + true, + true + ); + + // sort and add online information + foreach ($names as $k => $n) { + if (isset($online_users[$n["id"]])) { + $names[$k]["online"] = true; + $names[$k]["last_login"] = $online_users[$n["id"]]["last_login"]; + $sort_str = "1"; + } else { + $names[$k]["online"] = false; + $names[$k]["last_login"] = ""; + $sort_str = "2"; + } + if ($n["public_profile"]) { + $sort_str.= $n["lastname"] . " " . $n["firstname"]; + } else { + $sort_str.= $n["login"]; + } + $names[$k]["sort_str"] = $sort_str; + } + + $names = ilUtil::sortArray($names, "sort_str", "asc", false, true); + + foreach ($names as $n) { + // limit part 2 + if (count($this->data) >= $max) { + continue; + } + + // filter + $filter = trim($this->getFilter()); + if ($filter != "" && + !is_int(stripos($n["login"], $filter)) && + ( + !$n["public_profile"] || ( + !is_int(stripos($n["firstname"], $filter)) && + !is_int(stripos($n["lastname"], $filter)) + ) + ) + ) { + continue; + } + + $obj = new stdClass; + $obj->lastname = $n["lastname"]; + $obj->firstname = $n["firstname"]; + $obj->login = $n["login"]; + $obj->id = $n["id"]; + $obj->collector = $uc["uc_title"]; + $obj->highlighted = $uc["highlighted"]; + + //$obj->img = $n["img"]; + $obj->img = ilObjUser::_getPersonalPicturePath($n["id"], "xsmall"); + $obj->public_profile = $n["public_profile"]; + + $obj->online = $n["online"]; + $obj->last_login = $n["last_login"]; + ; + + // get actions + $action_collection = $this->action_collector->getActionsForTargetUser($n["id"]); + $obj->actions = array(); + foreach ($action_collection->getActions() as $action) { + $f = new stdClass; + $f->text = $action->getText(); + $f->href = $action->getHref(); + $f->data = $action->getData(); + $obj->actions[] = $f; + } + + $this->data[] = $obj; + } + } + } + + return array("data" => $this->data, "cnt" => count($all_user_ids) . ":" . count($hall_user_ids)); + } } - -?> \ No newline at end of file diff --git a/Services/Awareness/classes/class.ilAwarenessGUI.php b/Services/Awareness/classes/class.ilAwarenessGUI.php index 75fe241bf06a657ba51666c5ff505d37ed237df1..22338854246a716caa6d5219afcd1ccec3e664c4 100644 --- a/Services/Awareness/classes/class.ilAwarenessGUI.php +++ b/Services/Awareness/classes/class.ilAwarenessGUI.php @@ -11,275 +11,259 @@ */ class ilAwarenessGUI { - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var \ILIAS\DI\UIServices - */ - protected $ui; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->user = $DIC->user(); - global $DIC; - $this->ui = $DIC->ui(); - - $this->ref_id = (int) $_GET["ref_id"]; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->lng->loadLanguageModule("awrn"); - } - - /** - * Execute command - */ - function executeCommand() - { - $cmd = $this->ctrl->getCmd(); - - if (in_array($cmd, array("getAwarenessList"))) - { - $this->$cmd(); - } - } - - - /** - * Get instance - * - * @return ilAwarenessGUI awareness gui object - */ - static function getInstance() - { - return new ilAwarenessGUI(); - } - - /** - * Get main menu html - */ - function getMainMenuHTML() - { - $ilUser = $this->user; - - $awrn_set = new ilSetting("awrn"); - if (!$awrn_set->get("awrn_enabled", false) || ANONYMOUS_USER_ID == $ilUser->getId()) - { - return ""; - } - - $cache_period = (int) $awrn_set->get("caching_period"); - $last_update = ilSession::get("awrn_last_update"); - $now = time(); - - // init js - $GLOBALS["tpl"]->addJavascript("./Services/Awareness/js/Awareness.js"); - $this->ctrl->setParameter($this, "ref_id", $this->ref_id); - $GLOBALS["tpl"]->addOnloadCode("il.Awareness.setBaseUrl('".$this->ctrl->getLinkTarget($this, - "", "", true, false)."');"); - $GLOBALS["tpl"]->addOnloadCode("il.Awareness.setLoaderSrc('".ilUtil::getImagePath("loader.svg")."');"); - $GLOBALS["tpl"]->addOnloadCode("il.Awareness.init();"); - - // include user action js - include_once("./Services/User/Actions/classes/class.ilUserActionGUI.php"); - include_once("./Services/Awareness/classes/class.ilAwarenessUserActionContext.php"); - $ua_gui = ilUserActionGUI::getInstance(new ilAwarenessUserActionContext(), $GLOBALS["tpl"], $ilUser->getId()); - $ua_gui->init(); - - $tpl = new ilTemplate("tpl.awareness.html", true, true, "Services/Awareness"); - - include_once("./Services/Awareness/classes/class.ilAwarenessAct.php"); - $act = ilAwarenessAct::getInstance($ilUser->getId()); - $act->setRefId($this->ref_id); - - if ($last_update == "" || ($now - $last_update) >= $cache_period) - { - $cnt = explode(":", $act->getAwarenessUserCounter()); - $hcnt = $cnt[1]; - $cnt = $cnt[0]; - $act->notifyOnNewOnlineContacts(); - ilSession::set("awrn_last_update", $now); - ilSession::set("awrn_nr_users", $cnt); - ilSession::set("awrn_nr_husers", $hcnt); - } - else - { - $cnt = (int) ilSession::get("awrn_nr_users"); - $hcnt = (int) ilSession::get("awrn_nr_husers"); - } - - if ($hcnt > 0 || $cnt > 0) - { - /* - $tpl->setCurrentBlock("status_text"); - $tpl->setVariable("STATUS_TXT", $cnt); - if ($cnt == 0) - { - $tpl->setVariable("HIDDEN", "ilAwrnBadgeHidden"); - } - $tpl->parseCurrentBlock(); - $tpl->setCurrentBlock("h_status_text"); - $tpl->setVariable("H_STATUS_TXT", $hcnt); - if ($hcnt == 0) - { - $tpl->setVariable("H_HIDDEN", "ilAwrnBadgeHidden"); - } - $tpl->parseCurrentBlock(); - $tpl->setVariable("HSP", " ");*/ - - $f = $this->ui->factory(); - $renderer = $this->ui->renderer(); - - $glyph = $f->glyph()->user("#"); - if ($cnt > 0) - { - $glyph = $glyph->withCounter($f->counter()->status((int) $cnt)); - } - if ($hcnt > 0) - { - $glyph =$glyph->withCounter($f->counter()->novelty((int) $hcnt)); - } - $glyph_html = $renderer->render($glyph); - $tpl->setVariable("GLYPH", $glyph_html); - - - - $tpl->setVariable("LOADER", ilUtil::getImagePath("loader.svg")); - - return $tpl->get(); - } - - return ""; - } - - /** - * Get awareness list (ajax) - */ - function getAwarenessList() - { - $ilUser = $this->user; - - $filter = $_GET["filter"]; - - $tpl = new ilTemplate("tpl.awareness_list.html", true, true, "Services/Awareness"); - - include_once("./Services/Awareness/classes/class.ilAwarenessAct.php"); - $act = ilAwarenessAct::getInstance($ilUser->getId()); - $act->setRefId($this->ref_id); - - $ad = $act->getAwarenessData($filter); - - // update counter - $now = time(); - $cnt = explode(":",$ad["cnt"]); - $hcnt = $cnt[1]; - $cnt = $cnt[0]; - ilSession::set("awrn_last_update", $now); - ilSession::set("awrn_nr_users", $cnt); - ilSession::set("awrn_nr_husers", $hcnt); - - - $users = $ad["data"]; - - $ucnt = 0; - $last_uc_title = ""; - foreach ($users as $u) - { - if ($u->collector != $last_uc_title) - { - if ($u->highlighted) - { - $tpl->touchBlock("highlighted"); - } - $tpl->setCurrentBlock("uc_title"); - $tpl->setVariable("UC_TITLE", $u->collector); - $tpl->parseCurrentBlock(); - $tpl->setCurrentBlock("item"); - $tpl->parseCurrentBlock(); - } - $last_uc_title = $u->collector; - - $ucnt++; - - $fcnt = 0; - foreach ($u->actions as $act) - { - $fcnt++; - if ($fcnt == 1) - { - $tpl->touchBlock("arrow"); - //$tpl->setCurrentBlock("arrow"); - //$tpl->parseCurrentBlock(); - } - if (is_array($act->data) && count($act->data) > 0) - { - foreach ($act->data as $k => $v) - { - $tpl->setCurrentBlock("f_data"); - $tpl->setVariable("DATA_KEY", $k); - $tpl->setVariable("DATA_VAL", ilUtil::prepareFormOutput($v)); - $tpl->parseCurrentBlock(); - } - } - $tpl->setCurrentBlock("feature"); - $tpl->setVariable("FEATURE_HREF", $act->href); - $tpl->setVariable("FEATURE_TEXT", $act->text); - $tpl->parseCurrentBlock(); - } - - if ($u->online) - { - $tpl->touchBlock("uonline"); - $tpl->setCurrentBlock("uonline_text"); - $tpl->setVariable("TXT_ONLINE", $this->lng->txt("awrn_online")); - $tpl->parseCurrentBlock(); - } - - $tpl->setCurrentBlock("user"); - if ($u->public_profile) - { - $tpl->setVariable("UNAME", $u->lastname.", ".$u->firstname); - } - else - { - $tpl->setVariable("UNAME", " "); - } - $tpl->setVariable("UACCOUNT", $u->login); - - $tpl->setVariable("USERIMAGE", $u->img); - $tpl->setVariable("CNT", $ucnt); - $tpl->parseCurrentBlock(); - $tpl->setCurrentBlock("item"); - $tpl->parseCurrentBlock(); - } - - include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); - $tpl->setCurrentBlock("filter"); - $tpl->setVariable("GL_FILTER", ilGlyphGUI::get(ilGlyphGUI::FILTER)); - $tpl->setVariable("VAL_FILTER", ilUtil::prepareFormOutput($filter)); - $tpl->parseCurrentBlock(); - - echo json_encode(array("html" => $tpl->get(), - "cnt" => $ad["cnt"])); - exit; - } - + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var \ILIAS\DI\UIServices + */ + protected $ui; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->user = $DIC->user(); + global $DIC; + $this->ui = $DIC->ui(); + + $this->ref_id = (int) $_GET["ref_id"]; + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->lng->loadLanguageModule("awrn"); + } + + /** + * Execute command + */ + public function executeCommand() + { + $cmd = $this->ctrl->getCmd(); + + if (in_array($cmd, array("getAwarenessList"))) { + $this->$cmd(); + } + } + + + /** + * Get instance + * + * @return ilAwarenessGUI awareness gui object + */ + public static function getInstance() + { + return new ilAwarenessGUI(); + } + + /** + * Get main menu html + */ + public function getMainMenuHTML() + { + $ilUser = $this->user; + + $awrn_set = new ilSetting("awrn"); + if (!$awrn_set->get("awrn_enabled", false) || ANONYMOUS_USER_ID == $ilUser->getId()) { + return ""; + } + + $cache_period = (int) $awrn_set->get("caching_period"); + $last_update = ilSession::get("awrn_last_update"); + $now = time(); + + // init js + $GLOBALS["tpl"]->addJavascript("./Services/Awareness/js/Awareness.js"); + $this->ctrl->setParameter($this, "ref_id", $this->ref_id); + $GLOBALS["tpl"]->addOnloadCode("il.Awareness.setBaseUrl('" . $this->ctrl->getLinkTarget( + $this, + "", + "", + true, + false + ) . "');"); + $GLOBALS["tpl"]->addOnloadCode("il.Awareness.setLoaderSrc('" . ilUtil::getImagePath("loader.svg") . "');"); + $GLOBALS["tpl"]->addOnloadCode("il.Awareness.init();"); + + // include user action js + include_once("./Services/User/Actions/classes/class.ilUserActionGUI.php"); + include_once("./Services/Awareness/classes/class.ilAwarenessUserActionContext.php"); + $ua_gui = ilUserActionGUI::getInstance(new ilAwarenessUserActionContext(), $GLOBALS["tpl"], $ilUser->getId()); + $ua_gui->init(); + + $tpl = new ilTemplate("tpl.awareness.html", true, true, "Services/Awareness"); + + include_once("./Services/Awareness/classes/class.ilAwarenessAct.php"); + $act = ilAwarenessAct::getInstance($ilUser->getId()); + $act->setRefId($this->ref_id); + + if ($last_update == "" || ($now - $last_update) >= $cache_period) { + $cnt = explode(":", $act->getAwarenessUserCounter()); + $hcnt = $cnt[1]; + $cnt = $cnt[0]; + $act->notifyOnNewOnlineContacts(); + ilSession::set("awrn_last_update", $now); + ilSession::set("awrn_nr_users", $cnt); + ilSession::set("awrn_nr_husers", $hcnt); + } else { + $cnt = (int) ilSession::get("awrn_nr_users"); + $hcnt = (int) ilSession::get("awrn_nr_husers"); + } + + if ($hcnt > 0 || $cnt > 0) { + /* + $tpl->setCurrentBlock("status_text"); + $tpl->setVariable("STATUS_TXT", $cnt); + if ($cnt == 0) + { + $tpl->setVariable("HIDDEN", "ilAwrnBadgeHidden"); + } + $tpl->parseCurrentBlock(); + $tpl->setCurrentBlock("h_status_text"); + $tpl->setVariable("H_STATUS_TXT", $hcnt); + if ($hcnt == 0) + { + $tpl->setVariable("H_HIDDEN", "ilAwrnBadgeHidden"); + } + $tpl->parseCurrentBlock(); + $tpl->setVariable("HSP", " ");*/ + + $f = $this->ui->factory(); + $renderer = $this->ui->renderer(); + + $glyph = $f->glyph()->user("#"); + if ($cnt > 0) { + $glyph = $glyph->withCounter($f->counter()->status((int) $cnt)); + } + if ($hcnt > 0) { + $glyph =$glyph->withCounter($f->counter()->novelty((int) $hcnt)); + } + $glyph_html = $renderer->render($glyph); + $tpl->setVariable("GLYPH", $glyph_html); + + + + $tpl->setVariable("LOADER", ilUtil::getImagePath("loader.svg")); + + return $tpl->get(); + } + + return ""; + } + + /** + * Get awareness list (ajax) + */ + public function getAwarenessList() + { + $ilUser = $this->user; + + $filter = $_GET["filter"]; + + $tpl = new ilTemplate("tpl.awareness_list.html", true, true, "Services/Awareness"); + + include_once("./Services/Awareness/classes/class.ilAwarenessAct.php"); + $act = ilAwarenessAct::getInstance($ilUser->getId()); + $act->setRefId($this->ref_id); + + $ad = $act->getAwarenessData($filter); + + // update counter + $now = time(); + $cnt = explode(":", $ad["cnt"]); + $hcnt = $cnt[1]; + $cnt = $cnt[0]; + ilSession::set("awrn_last_update", $now); + ilSession::set("awrn_nr_users", $cnt); + ilSession::set("awrn_nr_husers", $hcnt); + + + $users = $ad["data"]; + + $ucnt = 0; + $last_uc_title = ""; + foreach ($users as $u) { + if ($u->collector != $last_uc_title) { + if ($u->highlighted) { + $tpl->touchBlock("highlighted"); + } + $tpl->setCurrentBlock("uc_title"); + $tpl->setVariable("UC_TITLE", $u->collector); + $tpl->parseCurrentBlock(); + $tpl->setCurrentBlock("item"); + $tpl->parseCurrentBlock(); + } + $last_uc_title = $u->collector; + + $ucnt++; + + $fcnt = 0; + foreach ($u->actions as $act) { + $fcnt++; + if ($fcnt == 1) { + $tpl->touchBlock("arrow"); + //$tpl->setCurrentBlock("arrow"); + //$tpl->parseCurrentBlock(); + } + if (is_array($act->data) && count($act->data) > 0) { + foreach ($act->data as $k => $v) { + $tpl->setCurrentBlock("f_data"); + $tpl->setVariable("DATA_KEY", $k); + $tpl->setVariable("DATA_VAL", ilUtil::prepareFormOutput($v)); + $tpl->parseCurrentBlock(); + } + } + $tpl->setCurrentBlock("feature"); + $tpl->setVariable("FEATURE_HREF", $act->href); + $tpl->setVariable("FEATURE_TEXT", $act->text); + $tpl->parseCurrentBlock(); + } + + if ($u->online) { + $tpl->touchBlock("uonline"); + $tpl->setCurrentBlock("uonline_text"); + $tpl->setVariable("TXT_ONLINE", $this->lng->txt("awrn_online")); + $tpl->parseCurrentBlock(); + } + + $tpl->setCurrentBlock("user"); + if ($u->public_profile) { + $tpl->setVariable("UNAME", $u->lastname . ", " . $u->firstname); + } else { + $tpl->setVariable("UNAME", " "); + } + $tpl->setVariable("UACCOUNT", $u->login); + + $tpl->setVariable("USERIMAGE", $u->img); + $tpl->setVariable("CNT", $ucnt); + $tpl->parseCurrentBlock(); + $tpl->setCurrentBlock("item"); + $tpl->parseCurrentBlock(); + } + + include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); + $tpl->setCurrentBlock("filter"); + $tpl->setVariable("GL_FILTER", ilGlyphGUI::get(ilGlyphGUI::FILTER)); + $tpl->setVariable("VAL_FILTER", ilUtil::prepareFormOutput($filter)); + $tpl->parseCurrentBlock(); + + echo json_encode(array("html" => $tpl->get(), + "cnt" => $ad["cnt"])); + exit; + } } -?> \ No newline at end of file diff --git a/Services/Awareness/classes/class.ilAwarenessUserActionContext.php b/Services/Awareness/classes/class.ilAwarenessUserActionContext.php index aed06e8595375e073e00f1037994a360e21aa323..948bc61eaa6232233dce154817cee418f2f38259 100644 --- a/Services/Awareness/classes/class.ilAwarenessUserActionContext.php +++ b/Services/Awareness/classes/class.ilAwarenessUserActionContext.php @@ -13,22 +13,19 @@ include_once("./Services/User/Actions/Contexts/classes/class.ilUserActionContext */ class ilAwarenessUserActionContext extends ilUserActionContext { - /** - * @inheritdoc - */ - function getComponentId() - { - return "awrn"; - } - - /** - * @inheritdoc - */ - function getContextId() - { - return "toplist"; - } + /** + * @inheritdoc + */ + public function getComponentId() + { + return "awrn"; + } + /** + * @inheritdoc + */ + public function getContextId() + { + return "toplist"; + } } - -?> \ No newline at end of file diff --git a/Services/Awareness/classes/class.ilAwarenessUserCollection.php b/Services/Awareness/classes/class.ilAwarenessUserCollection.php index fb683fe2f47e9d8d363045b844e7114241497866..2f796192995b2cc4fe4fa7db6b893720c8c04675 100644 --- a/Services/Awareness/classes/class.ilAwarenessUserCollection.php +++ b/Services/Awareness/classes/class.ilAwarenessUserCollection.php @@ -11,58 +11,55 @@ */ class ilAwarenessUserCollection implements \Countable { - protected $users = array(); + protected $users = array(); - /** - * Get instance - * - * @return ilAwarenessUserCollection user collection - */ - static function getInstance() - { - return new ilAwarenessUserCollection(); - } + /** + * Get instance + * + * @return ilAwarenessUserCollection user collection + */ + public static function getInstance() + { + return new ilAwarenessUserCollection(); + } - /** - * Add user - * - * @param integer $a_id user id - */ - function addUser($a_id) - { - $this->users[$a_id] = $a_id; - } + /** + * Add user + * + * @param integer $a_id user id + */ + public function addUser($a_id) + { + $this->users[$a_id] = $a_id; + } - /** - * Remove user - * - * @param integer $a_id user id - */ - function removeUser($a_id) - { - if (isset($this->users[$a_id])) - { - unset($this->users[$a_id]); - } - } + /** + * Remove user + * + * @param integer $a_id user id + */ + public function removeUser($a_id) + { + if (isset($this->users[$a_id])) { + unset($this->users[$a_id]); + } + } - /** - * Get users - * - * @return array array of user ids (integer) - */ - function getUsers() - { - return $this->users; - } + /** + * Get users + * + * @return array array of user ids (integer) + */ + public function getUsers() + { + return $this->users; + } - /** - * @inheritdoc - */ - public function count() - { - return count($this->users); - } + /** + * @inheritdoc + */ + public function count() + { + return count($this->users); + } } - -?> \ No newline at end of file diff --git a/Services/Awareness/classes/class.ilAwarenessUserCollector.php b/Services/Awareness/classes/class.ilAwarenessUserCollector.php index 676e57ca40a44bd9981675ab2196785c063a8c67..47e05faa936ed17351389a439ffc6ead75a171d8 100644 --- a/Services/Awareness/classes/class.ilAwarenessUserCollector.php +++ b/Services/Awareness/classes/class.ilAwarenessUserCollector.php @@ -11,206 +11,186 @@ */ class ilAwarenessUserCollector { - protected static $instances = array(); - protected static $online_users = false; - protected static $online_user_ids = array(); - - /** - * @var ilAwarenessUserCollection - */ - protected $collection; - protected $collections; - protected $user_id; - protected $ref_id; - - /** - * Constructor - * - * @param int $a_user_id user id - */ - protected function __construct($a_user_id) - { - $this->user_id = $a_user_id; - } - - /** - * Set ref id - * - * @param int $a_val ref id - */ - function setRefId($a_val) - { - $this->ref_id = $a_val; - } - - /** - * Get ref id - * - * @return int ref id - */ - function getRefId() - { - return $this->ref_id; - } - - /** - * Get instance (for a user) - * - * @param int $a_user_id user id - * @return ilAwarenessAct actor class - */ - static function getInstance($a_user_id) - { - if (!isset(self::$instances[$a_user_id])) - { - self::$instances[$a_user_id] = new ilAwarenessUserCollector($a_user_id); - } - - return self::$instances[$a_user_id]; - } - - /** - * Get online users - * - * @param - * @return - */ - static function getOnlineUsers() - { - if (self::$online_users === false) - { - self::$online_user_ids = array(); - self::$online_users = array(); - include_once("./Services/User/classes/class.ilObjUser.php"); - foreach (ilObjUser::_getUsersOnline() as $u) - { - // ask context $u["context"] if it supports pushMessages - if ($u["context"] && - ilContext::directCall($u["context"], "supportsPushMessages")) - { - self::$online_users[$u["user_id"]] = $u; - self::$online_user_ids[] = $u["user_id"]; - } - } - } - return self::$online_users; - } - - - /** - * Collect users - * - * @return ilAwarenessUserCollection user collection - */ - public function collectUsers($a_online_only = false) - { - global $rbacreview; - - $this->collections = array(); - - $awrn_logger = ilLoggerFactory::getLogger('awrn'); - - $awrn_logger->debug("Start, Online Only: ".$a_online_only.", Current User: ".$this->user_id); - - self::getOnlineUsers(); - include_once("./Services/Awareness/classes/class.ilAwarenessUserProviderFactory.php"); - $all_users = array(); - foreach (ilAwarenessUserProviderFactory::getAllProviders() as $prov) - { - $awrn_logger->debug("Provider: ".$prov->getProviderId().", Activation Mode: ".$prov->getActivationMode().", Current User: ".$this->user_id); - - // overall collection of users - include_once("./Services/Awareness/classes/class.ilAwarenessUserCollection.php"); - $collection = ilAwarenessUserCollection::getInstance(); - - if ($prov->getActivationMode() != ilAwarenessUserProvider::MODE_INACTIVE) - { - $prov->setUserId($this->user_id); - $prov->setRefId($this->ref_id); - $prov->setOnlineUserFilter(false); - if ($prov->getActivationMode() == ilAwarenessUserProvider::MODE_ONLINE_ONLY || $a_online_only) - { - $awrn_logger->debug("Provider: ".$prov->getProviderId().", Online Filter Users: ".count(self::$online_user_ids).", Current User: ".$this->user_id); - $prov->setOnlineUserFilter(self::$online_user_ids); - } - - $coll = $prov->collectUsers(); - $awrn_logger->debug("Provider: ".$prov->getProviderId().", Collected Users: ".count($coll).", Current User: ".$this->user_id); - - foreach ($coll->getUsers() as $user_id) - { - // filter out the anonymous user - if ($user_id == ANONYMOUS_USER_ID) - { - continue; - } - - $awrn_logger->debug("Current User: ".$this->user_id.", ". - "Provider: ".$prov->getProviderId().", Collected User: ".$user_id); - - // cross check online, filter out offline users (if necessary) - if ((!$a_online_only && $prov->getActivationMode() == ilAwarenessUserProvider::MODE_INCL_OFFLINE) - || in_array($user_id, self::$online_user_ids)) - { - $collection->addUser($user_id); - if (!in_array($user_id, $all_users)) - { - $all_users[] = $user_id; - } - } - } - } - $this->collections[] = array( - "uc_title" => $prov->getTitle(), - "highlighted" => $prov->isHighlighted(), - "collection" => $collection - ); - } - - $remove_users = array(); - - // remove all users that hide their online status - foreach (ilObjUser::getUserSubsetByPreferenceValue($all_users, "hide_own_online_status", "y") as $u) - { - $remove_users[] = $u; - } - - // remove all users that have not accepted the terms of service yet - require_once 'Services/TermsOfService/classes/class.ilTermsOfServiceHelper.php'; - if (ilTermsOfServiceHelper::isEnabled()) - { - foreach (ilObjUser::getUsersAgreed(false, $all_users) as $u) - { - if ($u != SYSTEM_USER_ID && !$rbacreview->isAssigned($u, SYSTEM_ROLE_ID)) - //if ($u != SYSTEM_USER_ID) - { - $remove_users[] = $u; - } - } - } - - $this->removeUsersFromCollections($remove_users); - - return $this->collections; - } - - /** - * Remove users from collection - * - * @param array $a_remove_users array of user IDs - */ - protected function removeUsersFromCollections($a_remove_users) - { - foreach ($this->collections as $c) - { - reset($a_remove_users); - foreach ($a_remove_users as $u) - { - $c["collection"]->removeUser($u); - } - } - } - + protected static $instances = array(); + protected static $online_users = false; + protected static $online_user_ids = array(); + + /** + * @var ilAwarenessUserCollection + */ + protected $collection; + protected $collections; + protected $user_id; + protected $ref_id; + + /** + * Constructor + * + * @param int $a_user_id user id + */ + protected function __construct($a_user_id) + { + $this->user_id = $a_user_id; + } + + /** + * Set ref id + * + * @param int $a_val ref id + */ + public function setRefId($a_val) + { + $this->ref_id = $a_val; + } + + /** + * Get ref id + * + * @return int ref id + */ + public function getRefId() + { + return $this->ref_id; + } + + /** + * Get instance (for a user) + * + * @param int $a_user_id user id + * @return ilAwarenessAct actor class + */ + public static function getInstance($a_user_id) + { + if (!isset(self::$instances[$a_user_id])) { + self::$instances[$a_user_id] = new ilAwarenessUserCollector($a_user_id); + } + + return self::$instances[$a_user_id]; + } + + /** + * Get online users + * + * @param + * @return + */ + public static function getOnlineUsers() + { + if (self::$online_users === false) { + self::$online_user_ids = array(); + self::$online_users = array(); + include_once("./Services/User/classes/class.ilObjUser.php"); + foreach (ilObjUser::_getUsersOnline() as $u) { + // ask context $u["context"] if it supports pushMessages + if ($u["context"] && + ilContext::directCall($u["context"], "supportsPushMessages")) { + self::$online_users[$u["user_id"]] = $u; + self::$online_user_ids[] = $u["user_id"]; + } + } + } + return self::$online_users; + } + + + /** + * Collect users + * + * @return ilAwarenessUserCollection user collection + */ + public function collectUsers($a_online_only = false) + { + global $rbacreview; + + $this->collections = array(); + + $awrn_logger = ilLoggerFactory::getLogger('awrn'); + + $awrn_logger->debug("Start, Online Only: " . $a_online_only . ", Current User: " . $this->user_id); + + self::getOnlineUsers(); + include_once("./Services/Awareness/classes/class.ilAwarenessUserProviderFactory.php"); + $all_users = array(); + foreach (ilAwarenessUserProviderFactory::getAllProviders() as $prov) { + $awrn_logger->debug("Provider: " . $prov->getProviderId() . ", Activation Mode: " . $prov->getActivationMode() . ", Current User: " . $this->user_id); + + // overall collection of users + include_once("./Services/Awareness/classes/class.ilAwarenessUserCollection.php"); + $collection = ilAwarenessUserCollection::getInstance(); + + if ($prov->getActivationMode() != ilAwarenessUserProvider::MODE_INACTIVE) { + $prov->setUserId($this->user_id); + $prov->setRefId($this->ref_id); + $prov->setOnlineUserFilter(false); + if ($prov->getActivationMode() == ilAwarenessUserProvider::MODE_ONLINE_ONLY || $a_online_only) { + $awrn_logger->debug("Provider: " . $prov->getProviderId() . ", Online Filter Users: " . count(self::$online_user_ids) . ", Current User: " . $this->user_id); + $prov->setOnlineUserFilter(self::$online_user_ids); + } + + $coll = $prov->collectUsers(); + $awrn_logger->debug("Provider: " . $prov->getProviderId() . ", Collected Users: " . count($coll) . ", Current User: " . $this->user_id); + + foreach ($coll->getUsers() as $user_id) { + // filter out the anonymous user + if ($user_id == ANONYMOUS_USER_ID) { + continue; + } + + $awrn_logger->debug("Current User: " . $this->user_id . ", " . + "Provider: " . $prov->getProviderId() . ", Collected User: " . $user_id); + + // cross check online, filter out offline users (if necessary) + if ((!$a_online_only && $prov->getActivationMode() == ilAwarenessUserProvider::MODE_INCL_OFFLINE) + || in_array($user_id, self::$online_user_ids)) { + $collection->addUser($user_id); + if (!in_array($user_id, $all_users)) { + $all_users[] = $user_id; + } + } + } + } + $this->collections[] = array( + "uc_title" => $prov->getTitle(), + "highlighted" => $prov->isHighlighted(), + "collection" => $collection + ); + } + + $remove_users = array(); + + // remove all users that hide their online status + foreach (ilObjUser::getUserSubsetByPreferenceValue($all_users, "hide_own_online_status", "y") as $u) { + $remove_users[] = $u; + } + + // remove all users that have not accepted the terms of service yet + require_once 'Services/TermsOfService/classes/class.ilTermsOfServiceHelper.php'; + if (ilTermsOfServiceHelper::isEnabled()) { + foreach (ilObjUser::getUsersAgreed(false, $all_users) as $u) { + if ($u != SYSTEM_USER_ID && !$rbacreview->isAssigned($u, SYSTEM_ROLE_ID)) { + //if ($u != SYSTEM_USER_ID) + $remove_users[] = $u; + } + } + } + + $this->removeUsersFromCollections($remove_users); + + return $this->collections; + } + + /** + * Remove users from collection + * + * @param array $a_remove_users array of user IDs + */ + protected function removeUsersFromCollections($a_remove_users) + { + foreach ($this->collections as $c) { + reset($a_remove_users); + foreach ($a_remove_users as $u) { + $c["collection"]->removeUser($u); + } + } + } } - -?> \ No newline at end of file diff --git a/Services/Awareness/classes/class.ilAwarenessUserProvider.php b/Services/Awareness/classes/class.ilAwarenessUserProvider.php index ccedf14eb6246139a88d05f133f513c4b78023a3..d1946f62f81a5dba4f0228c1ea851c0d8e63280e 100644 --- a/Services/Awareness/classes/class.ilAwarenessUserProvider.php +++ b/Services/Awareness/classes/class.ilAwarenessUserProvider.php @@ -11,189 +11,184 @@ */ abstract class ilAwarenessUserProvider { - const MODE_INACTIVE = 0; - const MODE_ONLINE_ONLY = 1; - const MODE_INCL_OFFLINE = 2; - - protected $user_id; - protected $ref_id; - protected $lng; - protected $db; - protected $online_user_filter = false; - - /** - * @var ilLogger - */ - protected $log; - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $lng = $DIC->language(); - $ilDB = $DIC->database(); - - $this->lng = $lng; - $this->db = $ilDB; - $this->settings = new ilSetting("awrn"); - $this->log = ilLoggerFactory::getLogger('awrn'); - } - - /** - * Activate provider - * - * @param boolean $a_val activate provider - */ - function setActivationMode($a_val) - { - $this->settings->set("up_act_".$this->getProviderId(), (int) $a_val); - } - - /** - * Get Activate provider - * - * @return boolean activate provider - */ - function getActivationMode() - { - return (int) $this->settings->get("up_act_".$this->getProviderId()); - } - - /** - * Set user id - * - * @param int $a_val user id - */ - function setUserId($a_val) - { - $this->user_id = $a_val; - } - - /** - * Get user id - * - * @return int user id - */ - function getUserId() - { - return $this->user_id; - } - - /** - * Set ref id - * - * @param int $a_val ref id - */ - function setRefId($a_val) - { - $this->ref_id = $a_val; - } - - /** - * Get ref id - * - * @return int ref id - */ - function getRefId() - { - return $this->ref_id; - } - - /** - * Set online user filter - * - * @param array $a_val array of user IDs | false if online status is not relevant - */ - function setOnlineUserFilter($a_val) - { - $this->online_user_filter = $a_val; - } - - /** - * Get online user filter - * - * @return array array of user IDs | false if online status is not relevant - */ - function getOnlineUserFilter() - { - return $this->online_user_filter; - } - - /** - * This should return a unique id for the provider - * The ID should start with the service/module id, separated by "_" and a second part - * that is unique within the module/service, e.g. "user_all" - * - * @return string provider id - */ - abstract function getProviderId(); - - /** - * Provider title (used in awareness overlay and in administration settings) - * - * @return string provider title - */ - abstract function getTitle(); - - /** - * Provider info (used in administration settings) - * - * @return string provider info text - */ - abstract function getInfo(); - - /** - * Get initial set of users - * - * @return array array of user IDs - */ - abstract function getInitialUserSet(); - - /** - * Collect all users - * - * @return \ilAwarenessUserCollection - */ - function collectUsers(): \ilAwarenessUserCollection - { - $coll = ilAwarenessUserCollection::getInstance(); - - foreach ($this->getInitialUserSet() as $u) - { - $this->addUserToCollection($u, $coll); - } - - return $coll; - } - - /** - * Add user to collection - * - * @param int $a_user_id user id - * @param ilAwarenessUserCollection $a_collection collection - */ - protected function addUserToCollection($a_user_id, ilAwarenessUserCollection $a_collection) - { - $ou = $this->getOnlineUserFilter(); - if ($this->getUserId() != $a_user_id && ($ou === false || in_array($a_user_id, $ou))) - { - $a_collection->addUser($a_user_id); - } - } - - /** - * Is highlighted - * - * @return bool return true, if user group should be highlighted (using extra highlighted number) - */ - function isHighlighted() - { - return false; - } - + const MODE_INACTIVE = 0; + const MODE_ONLINE_ONLY = 1; + const MODE_INCL_OFFLINE = 2; + + protected $user_id; + protected $ref_id; + protected $lng; + protected $db; + protected $online_user_filter = false; + + /** + * @var ilLogger + */ + protected $log; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $lng = $DIC->language(); + $ilDB = $DIC->database(); + + $this->lng = $lng; + $this->db = $ilDB; + $this->settings = new ilSetting("awrn"); + $this->log = ilLoggerFactory::getLogger('awrn'); + } + + /** + * Activate provider + * + * @param boolean $a_val activate provider + */ + public function setActivationMode($a_val) + { + $this->settings->set("up_act_" . $this->getProviderId(), (int) $a_val); + } + + /** + * Get Activate provider + * + * @return boolean activate provider + */ + public function getActivationMode() + { + return (int) $this->settings->get("up_act_" . $this->getProviderId()); + } + + /** + * Set user id + * + * @param int $a_val user id + */ + public function setUserId($a_val) + { + $this->user_id = $a_val; + } + + /** + * Get user id + * + * @return int user id + */ + public function getUserId() + { + return $this->user_id; + } + + /** + * Set ref id + * + * @param int $a_val ref id + */ + public function setRefId($a_val) + { + $this->ref_id = $a_val; + } + + /** + * Get ref id + * + * @return int ref id + */ + public function getRefId() + { + return $this->ref_id; + } + + /** + * Set online user filter + * + * @param array $a_val array of user IDs | false if online status is not relevant + */ + public function setOnlineUserFilter($a_val) + { + $this->online_user_filter = $a_val; + } + + /** + * Get online user filter + * + * @return array array of user IDs | false if online status is not relevant + */ + public function getOnlineUserFilter() + { + return $this->online_user_filter; + } + + /** + * This should return a unique id for the provider + * The ID should start with the service/module id, separated by "_" and a second part + * that is unique within the module/service, e.g. "user_all" + * + * @return string provider id + */ + abstract public function getProviderId(); + + /** + * Provider title (used in awareness overlay and in administration settings) + * + * @return string provider title + */ + abstract public function getTitle(); + + /** + * Provider info (used in administration settings) + * + * @return string provider info text + */ + abstract public function getInfo(); + + /** + * Get initial set of users + * + * @return array array of user IDs + */ + abstract public function getInitialUserSet(); + + /** + * Collect all users + * + * @return \ilAwarenessUserCollection + */ + public function collectUsers() : \ilAwarenessUserCollection + { + $coll = ilAwarenessUserCollection::getInstance(); + + foreach ($this->getInitialUserSet() as $u) { + $this->addUserToCollection($u, $coll); + } + + return $coll; + } + + /** + * Add user to collection + * + * @param int $a_user_id user id + * @param ilAwarenessUserCollection $a_collection collection + */ + protected function addUserToCollection($a_user_id, ilAwarenessUserCollection $a_collection) + { + $ou = $this->getOnlineUserFilter(); + if ($this->getUserId() != $a_user_id && ($ou === false || in_array($a_user_id, $ou))) { + $a_collection->addUser($a_user_id); + } + } + + /** + * Is highlighted + * + * @return bool return true, if user group should be highlighted (using extra highlighted number) + */ + public function isHighlighted() + { + return false; + } } - -?> \ No newline at end of file diff --git a/Services/Awareness/classes/class.ilAwarenessUserProviderAllUsers.php b/Services/Awareness/classes/class.ilAwarenessUserProviderAllUsers.php index 0547209cfd75ad2f3e46e077ff73dbcea4408252..871eed201919255441b5505234ca691e91281d26 100644 --- a/Services/Awareness/classes/class.ilAwarenessUserProviderAllUsers.php +++ b/Services/Awareness/classes/class.ilAwarenessUserProviderAllUsers.php @@ -14,78 +14,71 @@ include_once("./Services/Awareness/classes/class.ilAwarenessUserProvider.php"); class ilAwarenessUserProviderAllUsers extends ilAwarenessUserProvider { - /** - * Constructor - */ - function __construct() - { - global $DIC; + /** + * Constructor + */ + public function __construct() + { + global $DIC; - parent::__construct(); + parent::__construct(); - $this->db = $DIC->database(); - } + $this->db = $DIC->database(); + } - /** - * Get provider id - * - * @return string provider id - */ - function getProviderId() - { - return "user_all"; - } + /** + * Get provider id + * + * @return string provider id + */ + public function getProviderId() + { + return "user_all"; + } - /** - * Provider title (used in awareness overlay and in administration settings) - * - * @return string provider title - */ - function getTitle() - { - $this->lng->loadLanguageModule("user"); - return $this->lng->txt("user_awrn_all_users"); - } + /** + * Provider title (used in awareness overlay and in administration settings) + * + * @return string provider title + */ + public function getTitle() + { + $this->lng->loadLanguageModule("user"); + return $this->lng->txt("user_awrn_all_users"); + } - /** - * Provider info (used in administration settings) - * - * @return string provider info text - */ - function getInfo() - { - $this->lng->loadLanguageModule("user"); - return $this->lng->txt("user_awrn_all_users_info"); - } + /** + * Provider info (used in administration settings) + * + * @return string provider info text + */ + public function getInfo() + { + $this->lng->loadLanguageModule("user"); + return $this->lng->txt("user_awrn_all_users_info"); + } - /** - * Get initial set of users - * - * @return array array of user IDs - */ - function getInitialUserSet() - { - $ilDB = $this->db; - - $ub = array(); - // all online users - if ($this->getOnlineUserFilter() !== false) - { - foreach ($this->getOnlineUserFilter() as $u) - { - $ub[] = $u; - } - } - else // all users - { - $set = $ilDB->query("SELECT usr_id FROM usr_data "); - while ($rec = $ilDB->fetchAssoc($set)) - { - $ub[] = $rec["usr_id"]; - } - } - return $ub; - } + /** + * Get initial set of users + * + * @return array array of user IDs + */ + public function getInitialUserSet() + { + $ilDB = $this->db; + $ub = array(); + // all online users + if ($this->getOnlineUserFilter() !== false) { + foreach ($this->getOnlineUserFilter() as $u) { + $ub[] = $u; + } + } else { // all users + $set = $ilDB->query("SELECT usr_id FROM usr_data "); + while ($rec = $ilDB->fetchAssoc($set)) { + $ub[] = $rec["usr_id"]; + } + } + return $ub; + } } -?> \ No newline at end of file diff --git a/Services/Awareness/classes/class.ilAwarenessUserProviderCourseContacts.php b/Services/Awareness/classes/class.ilAwarenessUserProviderCourseContacts.php index d3c0ee6512a0803e1f45a98bf1351adb486f9dce..ac33db4edaae464378779ee42ccdd02a82998045 100644 --- a/Services/Awareness/classes/class.ilAwarenessUserProviderCourseContacts.php +++ b/Services/Awareness/classes/class.ilAwarenessUserProviderCourseContacts.php @@ -13,53 +13,51 @@ include_once("./Services/Awareness/classes/class.ilAwarenessUserProvider.php"); */ class ilAwarenessUserProviderCourseContacts extends ilAwarenessUserProvider { - /** - * Get provider id - * - * @return string provider id - */ - function getProviderId() - { - return "crs_contacts"; - } + /** + * Get provider id + * + * @return string provider id + */ + public function getProviderId() + { + return "crs_contacts"; + } - /** - * Provider title (used in awareness overlay and in administration settings) - * - * @return string provider title - */ - function getTitle() - { - $this->lng->loadLanguageModule("crs"); - return $this->lng->txt("crs_awrn_support_contacts"); - } + /** + * Provider title (used in awareness overlay and in administration settings) + * + * @return string provider title + */ + public function getTitle() + { + $this->lng->loadLanguageModule("crs"); + return $this->lng->txt("crs_awrn_support_contacts"); + } - /** - * Provider info (used in administration settings) - * - * @return string provider info text - */ - function getInfo() - { - $this->lng->loadLanguageModule("crs"); - return $this->lng->txt("crs_awrn_support_contacts_info"); - } + /** + * Provider info (used in administration settings) + * + * @return string provider info text + */ + public function getInfo() + { + $this->lng->loadLanguageModule("crs"); + return $this->lng->txt("crs_awrn_support_contacts_info"); + } - /** - * Get initial set of users - * - * @return array array of user IDs - */ - function getInitialUserSet() - { - include_once("./Services/Membership/classes/class.ilParticipants.php"); - $ub = array(); - $support_contacts = ilParticipants::_getAllSupportContactsOfUser($this->getUserId(), "crs"); - foreach ($support_contacts as $c) - { - $ub[] = $c["usr_id"]; - } - return $ub; - } + /** + * Get initial set of users + * + * @return array array of user IDs + */ + public function getInitialUserSet() + { + include_once("./Services/Membership/classes/class.ilParticipants.php"); + $ub = array(); + $support_contacts = ilParticipants::_getAllSupportContactsOfUser($this->getUserId(), "crs"); + foreach ($support_contacts as $c) { + $ub[] = $c["usr_id"]; + } + return $ub; + } } -?> \ No newline at end of file diff --git a/Services/Awareness/classes/class.ilAwarenessUserProviderCurrentCourse.php b/Services/Awareness/classes/class.ilAwarenessUserProviderCurrentCourse.php index 5843ec8692e5ebf292ba9b3cce96ecbdea16bdf6..aca9e7c0bf76eddcb646d2f915de4f98ee07ceb6 100644 --- a/Services/Awareness/classes/class.ilAwarenessUserProviderCurrentCourse.php +++ b/Services/Awareness/classes/class.ilAwarenessUserProviderCurrentCourse.php @@ -13,111 +13,105 @@ include_once("./Services/Awareness/classes/class.ilAwarenessUserProvider.php"); */ class ilAwarenessUserProviderCurrentCourse extends ilAwarenessUserProvider { - /** - * @var ilTree - */ - protected $tree; - - /** - * @var ilAccessHandler - */ - protected $access; - - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - parent::__construct(); - - $this->db = $DIC->database(); - $this->tree = $DIC->repositoryTree(); - $this->access = $DIC->access(); - $this->rbac = $DIC->rbac(); - } - - /** - * Get provider id - * - * @return string provider id - */ - function getProviderId() - { - return "crs_current"; - } - - /** - * Provider title (used in awareness overlay and in administration settings) - * - * @return string provider title - */ - function getTitle() - { - $this->lng->loadLanguageModule("crs"); - return $this->lng->txt("crs_awrn_current_course"); - } - - /** - * Provider info (used in administration settings) - * - * @return string provider info text - */ - function getInfo() - { - $this->lng->loadLanguageModule("crs"); - return $this->lng->txt("crs_awrn_current_course_info"); - } - - /** - * Get initial set of users - * - * @return array array of user IDs - */ - function getInitialUserSet() - { - $ilDB = $this->db; - $tree = $this->tree; - $ilAccess = $this->access; - $rbacreview = $this->rbac->review(); - - $ub = array(); - - $awrn_logger = ilLoggerFactory::getLogger('awrn'); - - if ($this->getRefId() > 0) - { - $path = $tree->getPathFull($this->getRefId()); - if (is_array($path)) - { - foreach ($path as $p) - { - include_once("./Modules/Course/classes/class.ilObjCourse.php"); - if ($p["type"] == "crs" && - ($ilAccess->checkAccess("write", "", $p["child"]) || - (ilObjCourse::lookupShowMembersEnabled($p["obj_id"]) && $ilAccess->checkAccess("read", "", $p["child"])))) - { - $lrol = $rbacreview->getRolesOfRoleFolder($p["child"],false); - $set = $ilDB->query('SELECT DISTINCT(usr_id) FROM rbac_ua '. - 'WHERE '.$ilDB->in('rol_id', $lrol, false, 'integer')); - - //$set = $ilDB->query($q = "SELECT DISTINCT usr_id FROM obj_members ". - // " WHERE obj_id = ".$ilDB->quote($p["obj_id"], "integer")); - $ub = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $ub[] = $rec["usr_id"]; - - $awrn_logger->debug("ilAwarenessUserProviderCurrentCourse: obj_id: ".$p["obj_id"].", ". - "Collected User: ".$rec["usr_id"]); - } - } - } - } - } - return $ub; - } + /** + * @var ilTree + */ + protected $tree; + + /** + * @var ilAccessHandler + */ + protected $access; + + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + parent::__construct(); + + $this->db = $DIC->database(); + $this->tree = $DIC->repositoryTree(); + $this->access = $DIC->access(); + $this->rbac = $DIC->rbac(); + } + + /** + * Get provider id + * + * @return string provider id + */ + public function getProviderId() + { + return "crs_current"; + } + + /** + * Provider title (used in awareness overlay and in administration settings) + * + * @return string provider title + */ + public function getTitle() + { + $this->lng->loadLanguageModule("crs"); + return $this->lng->txt("crs_awrn_current_course"); + } + + /** + * Provider info (used in administration settings) + * + * @return string provider info text + */ + public function getInfo() + { + $this->lng->loadLanguageModule("crs"); + return $this->lng->txt("crs_awrn_current_course_info"); + } + + /** + * Get initial set of users + * + * @return array array of user IDs + */ + public function getInitialUserSet() + { + $ilDB = $this->db; + $tree = $this->tree; + $ilAccess = $this->access; + $rbacreview = $this->rbac->review(); + + $ub = array(); + + $awrn_logger = ilLoggerFactory::getLogger('awrn'); + + if ($this->getRefId() > 0) { + $path = $tree->getPathFull($this->getRefId()); + if (is_array($path)) { + foreach ($path as $p) { + include_once("./Modules/Course/classes/class.ilObjCourse.php"); + if ($p["type"] == "crs" && + ($ilAccess->checkAccess("write", "", $p["child"]) || + (ilObjCourse::lookupShowMembersEnabled($p["obj_id"]) && $ilAccess->checkAccess("read", "", $p["child"])))) { + $lrol = $rbacreview->getRolesOfRoleFolder($p["child"], false); + $set = $ilDB->query('SELECT DISTINCT(usr_id) FROM rbac_ua ' . + 'WHERE ' . $ilDB->in('rol_id', $lrol, false, 'integer')); + + //$set = $ilDB->query($q = "SELECT DISTINCT usr_id FROM obj_members ". + // " WHERE obj_id = ".$ilDB->quote($p["obj_id"], "integer")); + $ub = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $ub[] = $rec["usr_id"]; + + $awrn_logger->debug("ilAwarenessUserProviderCurrentCourse: obj_id: " . $p["obj_id"] . ", " . + "Collected User: " . $rec["usr_id"]); + } + } + } + } + } + return $ub; + } } -?> \ No newline at end of file diff --git a/Services/Awareness/classes/class.ilAwarenessUserProviderFactory.php b/Services/Awareness/classes/class.ilAwarenessUserProviderFactory.php index 5c99ea60223356cf566b9400a57d14b88315a1d4..02ce17a5f9b1d0f97224d16ab06dcc4f54c20799 100644 --- a/Services/Awareness/classes/class.ilAwarenessUserProviderFactory.php +++ b/Services/Awareness/classes/class.ilAwarenessUserProviderFactory.php @@ -11,65 +11,61 @@ */ class ilAwarenessUserProviderFactory { - protected static $providers = array( - array ( - "component" => "Services/Contact/BuddySystem", - "class" => "ilAwarenessUserProviderContactRequests" - ), - array ( - "component" => "Services/Awareness", - "class" => "ilAwarenessUserProviderSystemContacts" - ), - array ( - "component" => "Services/Awareness", - "class" => "ilAwarenessUserProviderCourseContacts" - ), - array ( - "component" => "Services/Awareness", - "class" => "ilAwarenessUserProviderCurrentCourse" - ), - array ( - "component" => "Services/Contact/BuddySystem", - "class" => "ilAwarenessUserProviderApprovedContacts" - ), - array ( - "component" => "Services/Awareness", - "class" => "ilAwarenessUserProviderMemberships" - ), - array ( - "component" => "Services/Awareness", - "class" => "ilAwarenessUserProviderAllUsers" - ) - ); + protected static $providers = array( + array( + "component" => "Services/Contact/BuddySystem", + "class" => "ilAwarenessUserProviderContactRequests" + ), + array( + "component" => "Services/Awareness", + "class" => "ilAwarenessUserProviderSystemContacts" + ), + array( + "component" => "Services/Awareness", + "class" => "ilAwarenessUserProviderCourseContacts" + ), + array( + "component" => "Services/Awareness", + "class" => "ilAwarenessUserProviderCurrentCourse" + ), + array( + "component" => "Services/Contact/BuddySystem", + "class" => "ilAwarenessUserProviderApprovedContacts" + ), + array( + "component" => "Services/Awareness", + "class" => "ilAwarenessUserProviderMemberships" + ), + array( + "component" => "Services/Awareness", + "class" => "ilAwarenessUserProviderAllUsers" + ) + ); - /*protected static $providers = array( - array ( - "component" => "Services/Awareness", - "class" => "ilAwarenessUserProviderCourseContacts" - ) - );*/ + /*protected static $providers = array( + array ( + "component" => "Services/Awareness", + "class" => "ilAwarenessUserProviderCourseContacts" + ) + );*/ - /** - * Get all awareness providers - * - * @return \ilAwarenessUserProvider[] array of ilAwarenessProvider all providers - */ - static function getAllProviders(): array - { - $providers = array(); + /** + * Get all awareness providers + * + * @return \ilAwarenessUserProvider[] array of ilAwarenessProvider all providers + */ + public static function getAllProviders() : array + { + $providers = array(); - foreach (self::$providers as $p) - { - $dir = (isset($p["dir"])) - ? $p["dir"] - : "classes"; - include_once("./".$p["component"]."/".$dir."/class.".$p["class"].".php"); - $providers[] = new $p["class"](); - } - - return $providers; - } + foreach (self::$providers as $p) { + $dir = (isset($p["dir"])) + ? $p["dir"] + : "classes"; + include_once("./" . $p["component"] . "/" . $dir . "/class." . $p["class"] . ".php"); + $providers[] = new $p["class"](); + } + return $providers; + } } - -?> \ No newline at end of file diff --git a/Services/Awareness/classes/class.ilAwarenessUserProviderMemberships.php b/Services/Awareness/classes/class.ilAwarenessUserProviderMemberships.php index bb55f2f146b4b65f391d762319603c13ba1b8e1a..ca378193c3a22a5da1caa781ad8cd12de0ea944f 100644 --- a/Services/Awareness/classes/class.ilAwarenessUserProviderMemberships.php +++ b/Services/Awareness/classes/class.ilAwarenessUserProviderMemberships.php @@ -14,96 +14,92 @@ include_once("./Services/Awareness/classes/class.ilAwarenessUserProvider.php"); class ilAwarenessUserProviderMemberships extends ilAwarenessUserProvider { - /** - * Constructor - */ - function __construct() - { - global $DIC; + /** + * Constructor + */ + public function __construct() + { + global $DIC; - parent::__construct(); - - $this->db = $DIC->database(); - } + parent::__construct(); + + $this->db = $DIC->database(); + } - /** - * Get provider id - * - * @return string provider id - */ - function getProviderId() - { - return "mmbr_user_grpcrs"; - } + /** + * Get provider id + * + * @return string provider id + */ + public function getProviderId() + { + return "mmbr_user_grpcrs"; + } - /** - * Provider title (used in awareness overlay and in administration settings) - * - * @return string provider title - */ - function getTitle() - { - $this->lng->loadLanguageModule("mmbr"); - return $this->lng->txt("mmbr_awrn_my_groups_courses"); - } + /** + * Provider title (used in awareness overlay and in administration settings) + * + * @return string provider title + */ + public function getTitle() + { + $this->lng->loadLanguageModule("mmbr"); + return $this->lng->txt("mmbr_awrn_my_groups_courses"); + } - /** - * Provider info (used in administration settings) - * - * @return string provider info text - */ - function getInfo() - { - $this->lng->loadLanguageModule("crs"); - return $this->lng->txt("mmbr_awrn_my_groups_courses_info"); - } + /** + * Provider info (used in administration settings) + * + * @return string provider info text + */ + public function getInfo() + { + $this->lng->loadLanguageModule("crs"); + return $this->lng->txt("mmbr_awrn_my_groups_courses_info"); + } - /** - * Get initial set of users - * - * @return array array of user IDs - */ - function getInitialUserSet() - { - $ilDB = $this->db; + /** + * Get initial set of users + * + * @return array array of user IDs + */ + public function getInitialUserSet() + { + $ilDB = $this->db; - include_once("./Services/Membership/classes/class.ilParticipants.php"); - $groups_and_courses_of_user = ilParticipants::_getMembershipByType($this->getUserId(), array("grp", "crs")); - $this->log->debug("user: ".$this->getUserId().", courses and groups: ".implode(",", $groups_and_courses_of_user)); + include_once("./Services/Membership/classes/class.ilParticipants.php"); + $groups_and_courses_of_user = ilParticipants::_getMembershipByType($this->getUserId(), array("grp", "crs")); + $this->log->debug("user: " . $this->getUserId() . ", courses and groups: " . implode(",", $groups_and_courses_of_user)); - $set = $ilDB->query("SELECT DISTINCT usr_id, obj_id FROM obj_members ". - " WHERE ".$ilDB->in("obj_id", $groups_and_courses_of_user, false, "integer").' '. - 'AND (admin > '.$ilDB->quote(0,'integer').' '. - 'OR tutor > '.$ilDB->quote(0,'integer').' '. - 'OR member > '.$ilDB->quote(0,'integer').")" - ); - $ub = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - if (!in_array($rec["usr_id"], $ub)) - { - $ub[] = $rec["usr_id"]; - if ($this->log->isHandling(ilLogLevel::DEBUG)) - { - // cross-check if user is in course - include_once("./Services/Membership/classes/class.ilParticipants.php"); - $ref_ids = ilObject::_getAllReferences($rec["obj_id"]); - $ref_id = current($ref_ids); - $this->log->debug("Cross-checking all members..."); - if (!ilParticipants::_isParticipant($ref_id, $rec["usr_id"])) - { - $this->log->debug("ERROR: obj_members has entry for user id: ".$rec["usr_id"]. - ", user : ".ilObject::_lookupTitle($rec["usr_id"]).", course ref: ".$ref_id.", course: ". - ilObject::_lookupTitle($rec["obj_id"]).", but ilParticipants does not list this user as a member."); - } - } - } - } + $set = $ilDB->query( + "SELECT DISTINCT usr_id, obj_id FROM obj_members " . + " WHERE " . $ilDB->in("obj_id", $groups_and_courses_of_user, false, "integer") . ' ' . + 'AND (admin > ' . $ilDB->quote(0, 'integer') . ' ' . + 'OR tutor > ' . $ilDB->quote(0, 'integer') . ' ' . + 'OR member > ' . $ilDB->quote(0, 'integer') . ")" + ); + $ub = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + if (!in_array($rec["usr_id"], $ub)) { + $ub[] = $rec["usr_id"]; + if ($this->log->isHandling(ilLogLevel::DEBUG)) { + // cross-check if user is in course + include_once("./Services/Membership/classes/class.ilParticipants.php"); + $ref_ids = ilObject::_getAllReferences($rec["obj_id"]); + $ref_id = current($ref_ids); + $this->log->debug("Cross-checking all members..."); + if (!ilParticipants::_isParticipant($ref_id, $rec["usr_id"])) { + $this->log->debug("ERROR: obj_members has entry for user id: " . $rec["usr_id"] . + ", user : " . ilObject::_lookupTitle($rec["usr_id"]) . ", course ref: " . $ref_id . ", course: " . + ilObject::_lookupTitle($rec["obj_id"]) . ", but ilParticipants does not list this user as a member."); + } + } + } + } - $this->log->debug("Got ".count($ub)." distinct members."); + $this->log->debug("Got " . count($ub) . " distinct members."); - return $ub; - } + return $ub; + } } -?> \ No newline at end of file diff --git a/Services/Awareness/classes/class.ilAwarenessUserProviderSystemContacts.php b/Services/Awareness/classes/class.ilAwarenessUserProviderSystemContacts.php index 9fbfe7227b7d0072df97b2c6e46ce4b8b4027e3d..ecd4fc9f47f2e58d2734e9c6771a3f8607b09f5c 100644 --- a/Services/Awareness/classes/class.ilAwarenessUserProviderSystemContacts.php +++ b/Services/Awareness/classes/class.ilAwarenessUserProviderSystemContacts.php @@ -13,47 +13,46 @@ include_once("./Services/Awareness/classes/class.ilAwarenessUserProvider.php"); */ class ilAwarenessUserProviderSystemContacts extends ilAwarenessUserProvider { - /** - * Get provider id - * - * @return string provider id - */ - function getProviderId() - { - return "adm_contacts"; - } + /** + * Get provider id + * + * @return string provider id + */ + public function getProviderId() + { + return "adm_contacts"; + } - /** - * Provider title (used in awareness overlay and in administration settings) - * - * @return string provider title - */ - function getTitle() - { - $this->lng->loadLanguageModule("adm"); - return $this->lng->txt("adm_support_contacts"); - } + /** + * Provider title (used in awareness overlay and in administration settings) + * + * @return string provider title + */ + public function getTitle() + { + $this->lng->loadLanguageModule("adm"); + return $this->lng->txt("adm_support_contacts"); + } - /** - * Provider info (used in administration settings) - * - * @return string provider info text - */ - function getInfo() - { - $this->lng->loadLanguageModule("adm"); - return $this->lng->txt("adm_awrn_support_contacts_info"); - } + /** + * Provider info (used in administration settings) + * + * @return string provider info text + */ + public function getInfo() + { + $this->lng->loadLanguageModule("adm"); + return $this->lng->txt("adm_awrn_support_contacts_info"); + } - /** - * Get initial set of users - * - * @return array array of user IDs - */ - function getInitialUserSet() - { - include_once("./Modules/SystemFolder/classes/class.ilSystemSupportContacts.php"); - return ilSystemSupportContacts::getValidSupportContactIds(); - } + /** + * Get initial set of users + * + * @return array array of user IDs + */ + public function getInitialUserSet() + { + include_once("./Modules/SystemFolder/classes/class.ilSystemSupportContacts.php"); + return ilSystemSupportContacts::getValidSupportContactIds(); + } } -?> \ No newline at end of file diff --git a/Services/Awareness/classes/class.ilObjAwarenessAdministration.php b/Services/Awareness/classes/class.ilObjAwarenessAdministration.php index 470170dc7022f3987d80e04c4f88564debc066a8..c2b945b8eced5059400902ea54fd8ed549ecafea 100644 --- a/Services/Awareness/classes/class.ilObjAwarenessAdministration.php +++ b/Services/Awareness/classes/class.ilObjAwarenessAdministration.php @@ -14,36 +14,33 @@ require_once "./Services/Object/classes/class.ilObject.php"; */ class ilObjAwarenessAdministration extends ilObject { - /** - * Constructor - * - * @param integer reference_id or object_id - * @param boolean treat the id as reference_id (true) or object_id (false) - */ - public function __construct($a_id = 0,$a_call_by_reference = true) - { - $this->type = "awra"; - parent::__construct($a_id,$a_call_by_reference); + /** + * Constructor + * + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + $this->type = "awra"; + parent::__construct($a_id, $a_call_by_reference); - $this->lng->loadLanguageModule("awrn"); - } + $this->lng->loadLanguageModule("awrn"); + } - /** - * update object data - * - * @return boolean - */ - public function update() - { - if (!parent::update()) - { - return false; - } + /** + * update object data + * + * @return boolean + */ + public function update() + { + if (!parent::update()) { + return false; + } - // put here object specific stuff - - return true; - } - -} -?> + // put here object specific stuff + + return true; + } +} diff --git a/Services/Awareness/classes/class.ilObjAwarenessAdministrationAccess.php b/Services/Awareness/classes/class.ilObjAwarenessAdministrationAccess.php index edef6f9496494ba29dfdd73a91b34b9402d4d9c5..e212910d1c3efd5ec14e8659971f5ceddcf91fa4 100644 --- a/Services/Awareness/classes/class.ilObjAwarenessAdministrationAccess.php +++ b/Services/Awareness/classes/class.ilObjAwarenessAdministrationAccess.php @@ -13,8 +13,4 @@ include_once("./Services/Object/classes/class.ilObjectAccess.php"); */ class ilObjAwarenessAdministrationAccess extends ilObjectAccess { - - } - -?> diff --git a/Services/Awareness/classes/class.ilObjAwarenessAdministrationGUI.php b/Services/Awareness/classes/class.ilObjAwarenessAdministrationGUI.php index fcd176f178834953a1347b2f6f92dfbf697e4c79..cd898e46c9a059864707e12fb113fbdc23c1dca9 100644 --- a/Services/Awareness/classes/class.ilObjAwarenessAdministrationGUI.php +++ b/Services/Awareness/classes/class.ilObjAwarenessAdministrationGUI.php @@ -15,270 +15,268 @@ include_once("./Services/Object/classes/class.ilObjectGUI.php"); */ class ilObjAwarenessAdministrationGUI extends ilObjectGUI { - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * Contructor - * - * @access public - */ - public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) - { - global $DIC; - - $this->rbacsystem = $DIC->rbac()->system(); - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->type = "awra"; - parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); - - $this->lng->loadLanguageModule("awrn"); - $this->lng->loadLanguageModule("pd"); - $this->lng->loadLanguageModule("usr"); - } - - /** - * Execute command - * - * @access public - * - */ - public function executeCommand() - { - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - $this->prepareOutput(); - - switch($next_class) - { - case 'iluseractionadmingui': - include_once("./Services/User/Actions/classes/class.ilUserActionAdminGUI.php"); - include_once("./Services/Awareness/classes/class.ilAwarenessUserActionContext.php"); - $gui = new ilUserActionAdminGUI(); - $gui->setActionContext(new ilAwarenessUserActionContext()); - $this->tabs_gui->setTabActive('settings'); - $this->setSubTabs("actions"); - $this->ctrl->forwardCommand($gui); - break; - - case 'ilpermissiongui': - $this->tabs_gui->setTabActive('perm_settings'); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $this->ctrl->forwardCommand($perm_gui); - break; - - default: - if(!$cmd || $cmd == 'view') - { - $cmd = "editSettings"; - } - - $this->$cmd(); - break; - } - return true; - } - - /** - * Get tabs - */ - public function getAdminTabs() - { - $rbacsystem = $this->rbacsystem; - - if ($rbacsystem->checkAccess("visible,read",$this->object->getRefId())) - { - $this->tabs_gui->addTab("settings", - $this->lng->txt("settings"), - $this->ctrl->getLinkTarget($this, "editSettings")); - } - - if ($rbacsystem->checkAccess('edit_permission',$this->object->getRefId())) - { - $this->tabs_gui->addTab("perm_settings", - $this->lng->txt("perm_settings"), - $this->ctrl->getLinkTargetByClass('ilpermissiongui',"perm")); - } - } - - /** - * Set sub tabs - * - * @param - * @return - */ - function setSubTabs($a_id) - { - $this->tabs_gui->addSubTab("settings", - $this->lng->txt("settings"), - $this->ctrl->getLinkTarget($this, "editSettings")); - - $this->tabs_gui->addSubTab("actions", - $this->lng->txt("user_actions"), - $this->ctrl->getLinkTargetByClass("iluseractionadmingui")); - - $this->tabs_gui->activateSubTab($a_id); - } - - - /** - * Edit settings. - */ - public function editSettings($a_form = null) - { - $this->tabs_gui->setTabActive('settings'); - $this->setSubTabs("settings"); - - if(!$a_form) - { - $a_form = $this->initFormSettings(); - } - $this->tpl->setContent($a_form->getHTML()); - return true; - } - - /** - * Save settings - */ - public function saveSettings() - { - $ilCtrl = $this->ctrl; - - $this->checkPermission("write"); - - $form = $this->initFormSettings(); - if($form->checkInput()) - { - $awrn_set = new ilSetting("awrn"); - $awrn_set->set("awrn_enabled", (bool) $form->getInput("enable_awareness")); - - $p = (int) $form->getInput("caching_period"); - if ($p < 0) - { - $p = 0; - } - $awrn_set->set("caching_period", $p); - - $awrn_set->set("max_nr_entries", (int) $form->getInput("max_nr_entries")); - $awrn_set->set("use_osd", (int) $form->getInput("use_osd")); - - $pd_set = new ilSetting("pd"); - $pd_set->set("user_activity_time", (int) $_POST["time_removal"]); - - include_once("./Services/Awareness/classes/class.ilAwarenessUserProviderFactory.php"); - $prov = ilAwarenessUserProviderFactory::getAllProviders(); - foreach ($prov as $p) - { - $p->setActivationMode($form->getInput("up_act_mode_".$p->getProviderId())); - } - - ilUtil::sendSuccess($this->lng->txt("settings_saved"),true); - $ilCtrl->redirect($this, "editSettings"); - } - - $form->setValuesByPost(); - $this->editSettings($form); - } - - /** - * Save settings - */ - public function cancel() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirect($this, "view"); - } - - /** - * Init settings property form - * - * @access protected - */ - protected function initFormSettings() - { - $lng = $this->lng; - - include_once('Services/Form/classes/class.ilPropertyFormGUI.php'); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - $form->setTitle($this->lng->txt('awareness_settings')); - - if ($this->checkPermissionBool("write")) - { - $form->addCommandButton('saveSettings', $this->lng->txt('save')); - $form->addCommandButton('cancel', $this->lng->txt('cancel')); - } - - $en = new ilCheckboxInputGUI($lng->txt("awrn_enable"), "enable_awareness"); - $form->addItem($en); - - $awrn_set = new ilSetting("awrn"); - $en->setChecked($awrn_set->get("awrn_enabled", false)); - - // caching period - $ti = new ilNumberInputGUI($this->lng->txt("awrn_caching_period"), "caching_period"); - $ti->setInfo($this->lng->txt("awrn_caching_period_info")); - $ti->setSuffix($this->lng->txt("awrn_seconds")); - $ti->setSize(6); - $ti->setMaxLength(6); - $ti->setValue($awrn_set->get("caching_period")); - $en->addSubItem($ti); - - // limit number of entries - $ti = new ilNumberInputGUI($this->lng->txt("awrn_max_nr_entries"), "max_nr_entries"); - $ti->setInfo($this->lng->txt("awrn_max_nr_entries_info")); - $ti->setSize(3); - $ti->setMaxLength(3); - $ti->setMinValue(5); - $ti->setMaxValue(200); - $ti->setValue($awrn_set->get("max_nr_entries")); - $en->addSubItem($ti); - - // maximum inactivity time - $pd_set = new ilSetting("pd"); // under pd settings due to historical reasons - $ti_prop = new ilNumberInputGUI($lng->txt("awrn_max_inactivity"), - "time_removal"); - $ti_prop->setSuffix($this->lng->txt("awrn_minutes")); - if ($pd_set->get("user_activity_time") > 0) - { - $ti_prop->setValue($pd_set->get("user_activity_time")); - } - $ti_prop->setInfo($lng->txt("awrn_max_inactivity_info")); - $ti_prop->setMaxLength(3); - $ti_prop->setSize(3); - $en->addSubItem($ti_prop); - - // activate osd - $osd = new ilCheckboxInputGUI($this->lng->txt("awrn_use_osd"), "use_osd"); - $osd->setInfo($this->lng->txt("awrn_use_osd_info")); - $osd->setChecked($awrn_set->get("use_osd", true)); - $en->addSubItem($osd); - - - include_once("./Services/Awareness/classes/class.ilAwarenessUserProviderFactory.php"); - $prov = ilAwarenessUserProviderFactory::getAllProviders(); - foreach ($prov as $p) - { - // activation mode - $options = array( - ilAwarenessUserProvider::MODE_INACTIVE => $lng->txt("awrn_inactive"), - ilAwarenessUserProvider::MODE_ONLINE_ONLY => $lng->txt("awrn_online_only"), - ilAwarenessUserProvider::MODE_INCL_OFFLINE => $lng->txt("awrn_incl_offline") - ); - $si = new ilSelectInputGUI($p->getTitle(), "up_act_mode_".$p->getProviderId()); - $si->setOptions($options); - $si->setInfo($p->getInfo()); - $si->setValue($p->getActivationMode()); - $en->addSubItem($si); - } - - return $form; - } + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * Contructor + * + * @access public + */ + public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) + { + global $DIC; + + $this->rbacsystem = $DIC->rbac()->system(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->type = "awra"; + parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); + + $this->lng->loadLanguageModule("awrn"); + $this->lng->loadLanguageModule("pd"); + $this->lng->loadLanguageModule("usr"); + } + + /** + * Execute command + * + * @access public + * + */ + public function executeCommand() + { + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + $this->prepareOutput(); + + switch ($next_class) { + case 'iluseractionadmingui': + include_once("./Services/User/Actions/classes/class.ilUserActionAdminGUI.php"); + include_once("./Services/Awareness/classes/class.ilAwarenessUserActionContext.php"); + $gui = new ilUserActionAdminGUI(); + $gui->setActionContext(new ilAwarenessUserActionContext()); + $this->tabs_gui->setTabActive('settings'); + $this->setSubTabs("actions"); + $this->ctrl->forwardCommand($gui); + break; + + case 'ilpermissiongui': + $this->tabs_gui->setTabActive('perm_settings'); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $this->ctrl->forwardCommand($perm_gui); + break; + + default: + if (!$cmd || $cmd == 'view') { + $cmd = "editSettings"; + } + + $this->$cmd(); + break; + } + return true; + } + + /** + * Get tabs + */ + public function getAdminTabs() + { + $rbacsystem = $this->rbacsystem; + + if ($rbacsystem->checkAccess("visible,read", $this->object->getRefId())) { + $this->tabs_gui->addTab( + "settings", + $this->lng->txt("settings"), + $this->ctrl->getLinkTarget($this, "editSettings") + ); + } + + if ($rbacsystem->checkAccess('edit_permission', $this->object->getRefId())) { + $this->tabs_gui->addTab( + "perm_settings", + $this->lng->txt("perm_settings"), + $this->ctrl->getLinkTargetByClass('ilpermissiongui', "perm") + ); + } + } + + /** + * Set sub tabs + * + * @param + * @return + */ + public function setSubTabs($a_id) + { + $this->tabs_gui->addSubTab( + "settings", + $this->lng->txt("settings"), + $this->ctrl->getLinkTarget($this, "editSettings") + ); + + $this->tabs_gui->addSubTab( + "actions", + $this->lng->txt("user_actions"), + $this->ctrl->getLinkTargetByClass("iluseractionadmingui") + ); + + $this->tabs_gui->activateSubTab($a_id); + } + + + /** + * Edit settings. + */ + public function editSettings($a_form = null) + { + $this->tabs_gui->setTabActive('settings'); + $this->setSubTabs("settings"); + + if (!$a_form) { + $a_form = $this->initFormSettings(); + } + $this->tpl->setContent($a_form->getHTML()); + return true; + } + + /** + * Save settings + */ + public function saveSettings() + { + $ilCtrl = $this->ctrl; + + $this->checkPermission("write"); + + $form = $this->initFormSettings(); + if ($form->checkInput()) { + $awrn_set = new ilSetting("awrn"); + $awrn_set->set("awrn_enabled", (bool) $form->getInput("enable_awareness")); + + $p = (int) $form->getInput("caching_period"); + if ($p < 0) { + $p = 0; + } + $awrn_set->set("caching_period", $p); + + $awrn_set->set("max_nr_entries", (int) $form->getInput("max_nr_entries")); + $awrn_set->set("use_osd", (int) $form->getInput("use_osd")); + + $pd_set = new ilSetting("pd"); + $pd_set->set("user_activity_time", (int) $_POST["time_removal"]); + + include_once("./Services/Awareness/classes/class.ilAwarenessUserProviderFactory.php"); + $prov = ilAwarenessUserProviderFactory::getAllProviders(); + foreach ($prov as $p) { + $p->setActivationMode($form->getInput("up_act_mode_" . $p->getProviderId())); + } + + ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "editSettings"); + } + + $form->setValuesByPost(); + $this->editSettings($form); + } + + /** + * Save settings + */ + public function cancel() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirect($this, "view"); + } + + /** + * Init settings property form + * + * @access protected + */ + protected function initFormSettings() + { + $lng = $this->lng; + + include_once('Services/Form/classes/class.ilPropertyFormGUI.php'); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this)); + $form->setTitle($this->lng->txt('awareness_settings')); + + if ($this->checkPermissionBool("write")) { + $form->addCommandButton('saveSettings', $this->lng->txt('save')); + $form->addCommandButton('cancel', $this->lng->txt('cancel')); + } + + $en = new ilCheckboxInputGUI($lng->txt("awrn_enable"), "enable_awareness"); + $form->addItem($en); + + $awrn_set = new ilSetting("awrn"); + $en->setChecked($awrn_set->get("awrn_enabled", false)); + + // caching period + $ti = new ilNumberInputGUI($this->lng->txt("awrn_caching_period"), "caching_period"); + $ti->setInfo($this->lng->txt("awrn_caching_period_info")); + $ti->setSuffix($this->lng->txt("awrn_seconds")); + $ti->setSize(6); + $ti->setMaxLength(6); + $ti->setValue($awrn_set->get("caching_period")); + $en->addSubItem($ti); + + // limit number of entries + $ti = new ilNumberInputGUI($this->lng->txt("awrn_max_nr_entries"), "max_nr_entries"); + $ti->setInfo($this->lng->txt("awrn_max_nr_entries_info")); + $ti->setSize(3); + $ti->setMaxLength(3); + $ti->setMinValue(5); + $ti->setMaxValue(200); + $ti->setValue($awrn_set->get("max_nr_entries")); + $en->addSubItem($ti); + + // maximum inactivity time + $pd_set = new ilSetting("pd"); // under pd settings due to historical reasons + $ti_prop = new ilNumberInputGUI( + $lng->txt("awrn_max_inactivity"), + "time_removal" + ); + $ti_prop->setSuffix($this->lng->txt("awrn_minutes")); + if ($pd_set->get("user_activity_time") > 0) { + $ti_prop->setValue($pd_set->get("user_activity_time")); + } + $ti_prop->setInfo($lng->txt("awrn_max_inactivity_info")); + $ti_prop->setMaxLength(3); + $ti_prop->setSize(3); + $en->addSubItem($ti_prop); + + // activate osd + $osd = new ilCheckboxInputGUI($this->lng->txt("awrn_use_osd"), "use_osd"); + $osd->setInfo($this->lng->txt("awrn_use_osd_info")); + $osd->setChecked($awrn_set->get("use_osd", true)); + $en->addSubItem($osd); + + + include_once("./Services/Awareness/classes/class.ilAwarenessUserProviderFactory.php"); + $prov = ilAwarenessUserProviderFactory::getAllProviders(); + foreach ($prov as $p) { + // activation mode + $options = array( + ilAwarenessUserProvider::MODE_INACTIVE => $lng->txt("awrn_inactive"), + ilAwarenessUserProvider::MODE_ONLINE_ONLY => $lng->txt("awrn_online_only"), + ilAwarenessUserProvider::MODE_INCL_OFFLINE => $lng->txt("awrn_incl_offline") + ); + $si = new ilSelectInputGUI($p->getTitle(), "up_act_mode_" . $p->getProviderId()); + $si->setOptions($options); + $si->setInfo($p->getInfo()); + $si->setValue($p->getActivationMode()); + $en->addSubItem($si); + } + + return $form; + } } -?> \ No newline at end of file diff --git a/Services/Badge/LearningHistory/classes/class.ilBadgeLearningHistoryProvider.php b/Services/Badge/LearningHistory/classes/class.ilBadgeLearningHistoryProvider.php index 211364335d40d9403af05306893841c6303d10a4..4372b36c341c03686c7b54663aa84d42d6cf1a76 100644 --- a/Services/Badge/LearningHistory/classes/class.ilBadgeLearningHistoryProvider.php +++ b/Services/Badge/LearningHistory/classes/class.ilBadgeLearningHistoryProvider.php @@ -10,97 +10,96 @@ */ class ilBadgeLearningHistoryProvider extends ilAbstractLearningHistoryProvider implements ilLearningHistoryProviderInterface { - /** - * @var ilObjUser - */ - protected $current_user; + /** + * @var ilObjUser + */ + protected $current_user; - /** - * @var \ILIAS\DI\UIServices - */ - protected $ui; + /** + * @var \ILIAS\DI\UIServices + */ + protected $ui; - /** - * Constructor - * @param int $user_id - * @param ilLearningHistoryFactory $factory - * @param ilLanguage $lng - * @param ilTemplate|null $template - */ - public function __construct( - $user_id, - ilLearningHistoryFactory $factory, - ilLanguage $lng, - ilTemplate $template = null, - ilObjUser $current_user = null, - \ILIAS\DI\UIServices $ui = null - ) { - global $DIC; + /** + * Constructor + * @param int $user_id + * @param ilLearningHistoryFactory $factory + * @param ilLanguage $lng + * @param ilTemplate|null $template + */ + public function __construct( + $user_id, + ilLearningHistoryFactory $factory, + ilLanguage $lng, + ilTemplate $template = null, + ilObjUser $current_user = null, + \ILIAS\DI\UIServices $ui = null + ) { + global $DIC; - parent::__construct($user_id, $factory, $lng, $template); + parent::__construct($user_id, $factory, $lng, $template); - if (is_null($current_user)) - { - $current_user = $DIC->user(); - } - $this->current_user = $current_user; + if (is_null($current_user)) { + $current_user = $DIC->user(); + } + $this->current_user = $current_user; - if (is_null($ui)) - { - $ui = $DIC->ui(); - } - $this->ui = $ui; - } + if (is_null($ui)) { + $ui = $DIC->ui(); + } + $this->ui = $ui; + } - /** - * @inheritdoc - */ - public function isActive() - { - require_once 'Services/Badge/classes/class.ilBadgeHandler.php'; - if(ilBadgeHandler::getInstance()->isActive()) - { - return true; - } - return false; - } + /** + * @inheritdoc + */ + public function isActive() + { + require_once 'Services/Badge/classes/class.ilBadgeHandler.php'; + if (ilBadgeHandler::getInstance()->isActive()) { + return true; + } + return false; + } - /** - * @inheritdoc - */ - public function getEntries($ts_start, $ts_end) - { - $lng = $this->getLanguage(); - $lng->loadLanguageModule("badge"); - $completions = ilBadgeAssignment::getBadgesForUser($this->getUserId(), $ts_start, $ts_end); + /** + * @inheritdoc + */ + public function getEntries($ts_start, $ts_end) + { + $lng = $this->getLanguage(); + $lng->loadLanguageModule("badge"); + $completions = ilBadgeAssignment::getBadgesForUser($this->getUserId(), $ts_start, $ts_end); - $entries = []; - foreach ($completions as $c) - { - $title = $this->getEmphasizedTitle($c["title"]); - if ($this->current_user->getId() == $this->getUserId()) - { - $title = $this->ui->renderer()->render($this->ui->factory()->link()->standard($title, - $url = ilLink::_getLink($this->getUserId(), "usr", array(), "_bdg"))); - } - $text1 = str_replace("$3$", $title, $lng->txt("badge_lhist_badge_completed")); - $text2 = str_replace("$3$", $title, $lng->txt("badge_lhist_badge_completed_in")); - $entries[] = $this->getFactory()->entry($text1, $text2, - ilUtil::getImagePath("icon_bdga.svg"), - $c["tstamp"], - $c["parent_id"]); - } - return $entries; - } + $entries = []; + foreach ($completions as $c) { + $title = $this->getEmphasizedTitle($c["title"]); + if ($this->current_user->getId() == $this->getUserId()) { + $title = $this->ui->renderer()->render($this->ui->factory()->link()->standard( + $title, + $url = ilLink::_getLink($this->getUserId(), "usr", array(), "_bdg") + )); + } + $text1 = str_replace("$3$", $title, $lng->txt("badge_lhist_badge_completed")); + $text2 = str_replace("$3$", $title, $lng->txt("badge_lhist_badge_completed_in")); + $entries[] = $this->getFactory()->entry( + $text1, + $text2, + ilUtil::getImagePath("icon_bdga.svg"), + $c["tstamp"], + $c["parent_id"] + ); + } + return $entries; + } - /** - * @inheritdoc - */ - public function getName(): string - { - $lng = $this->getLanguage(); + /** + * @inheritdoc + */ + public function getName() : string + { + $lng = $this->getLanguage(); - return $lng->txt("obj_bdga"); - } - -} \ No newline at end of file + return $lng->txt("obj_bdga"); + } +} diff --git a/Services/Badge/classes/class.ilBadge.php b/Services/Badge/classes/class.ilBadge.php index 12a89631f6a200d2edd0c43725c38e563c863da6..96003ada57ff8184ad698b3148a8b905719889a9 100644 --- a/Services/Badge/classes/class.ilBadge.php +++ b/Services/Badge/classes/class.ilBadge.php @@ -3,7 +3,7 @@ /** * Class ilBadge - * + * * @author Jörg Lützenkirchen * @version $Id:$ * @@ -11,577 +11,542 @@ */ class ilBadge { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; - protected $id; // [int] - protected $parent_id; // [int] - protected $type_id; // [string] - protected $active; // [bool] - protected $title; // [string] - protected $desc; // [string] - protected $image; // [string] - protected $valid; // [string] - protected $config; // [array] - protected $criteria; // [string] - - /** - * Constructor - * - * @param int $a_id - * @return self - */ - public function __construct($a_id = null) - { - global $DIC; + protected $id; // [int] + protected $parent_id; // [int] + protected $type_id; // [string] + protected $active; // [bool] + protected $title; // [string] + protected $desc; // [string] + protected $image; // [string] + protected $valid; // [string] + protected $config; // [array] + protected $criteria; // [string] + + /** + * Constructor + * + * @param int $a_id + * @return self + */ + public function __construct($a_id = null) + { + global $DIC; - $this->lng = $DIC->language(); - $this->db = $DIC->database(); - if($a_id) - { - $this->read($a_id); - } - } - - public static function getInstancesByParentId($a_parent_id, array $a_filter = null) - { - global $DIC; + $this->lng = $DIC->language(); + $this->db = $DIC->database(); + if ($a_id) { + $this->read($a_id); + } + } + + public static function getInstancesByParentId($a_parent_id, array $a_filter = null) + { + global $DIC; - $ilDB = $DIC->database(); - - $res = array(); - - $sql = "SELECT * FROM badge_badge". - " WHERE parent_id = ".$ilDB->quote($a_parent_id); - - if($a_filter) - { - if($a_filter["title"]) - { - $sql .= " AND ".$ilDB->like("title", "text", "%".trim($a_filter["title"])."%"); - } - if($a_filter["type"]) - { - $sql .= " AND type_id = ".$ilDB->quote($a_filter["type"], "integer"); - } - } - - $set = $ilDB->query($sql. - " ORDER BY title"); - while($row = $ilDB->fetchAssoc($set)) - { - $obj = new self(); - $obj->importDBRow($row); - $res[] = $obj; - } - - return $res; - } - - public static function getInstancesByType($a_type_id) - { - global $DIC; + $ilDB = $DIC->database(); + + $res = array(); + + $sql = "SELECT * FROM badge_badge" . + " WHERE parent_id = " . $ilDB->quote($a_parent_id); + + if ($a_filter) { + if ($a_filter["title"]) { + $sql .= " AND " . $ilDB->like("title", "text", "%" . trim($a_filter["title"]) . "%"); + } + if ($a_filter["type"]) { + $sql .= " AND type_id = " . $ilDB->quote($a_filter["type"], "integer"); + } + } + + $set = $ilDB->query($sql . + " ORDER BY title"); + while ($row = $ilDB->fetchAssoc($set)) { + $obj = new self(); + $obj->importDBRow($row); + $res[] = $obj; + } + + return $res; + } + + public static function getInstancesByType($a_type_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $res = array(); - - $set = $ilDB->query("SELECT * FROM badge_badge". - " WHERE type_id = ".$ilDB->quote($a_type_id). - " ORDER BY title"); - while($row = $ilDB->fetchAssoc($set)) - { - $obj = new self(); - $obj->importDBRow($row); - $res[] = $obj; - } - - return $res; - } - - public function getTypeInstance() - { - if($this->getTypeId()) - { - include_once "./Services/Badge/classes/class.ilBadgeHandler.php"; - $handler = ilBadgeHandler::getInstance(); - return $handler->getTypeInstanceByUniqueId($this->getTypeId()); - } - } - - public function copy($a_new_parent_id) - { - $lng = $this->lng; - - $this->setTitle($this->getTitle()." ".$lng->txt("copy_of_suffix")); - $this->setParentId($a_new_parent_id); - $this->setActive(false); - - if($this->getId()) - { - $img = $this->getImagePath(); - - $this->setId(null); - $this->create(); + $ilDB = $DIC->database(); + + $res = array(); + + $set = $ilDB->query("SELECT * FROM badge_badge" . + " WHERE type_id = " . $ilDB->quote($a_type_id) . + " ORDER BY title"); + while ($row = $ilDB->fetchAssoc($set)) { + $obj = new self(); + $obj->importDBRow($row); + $res[] = $obj; + } + + return $res; + } + + public function getTypeInstance() + { + if ($this->getTypeId()) { + include_once "./Services/Badge/classes/class.ilBadgeHandler.php"; + $handler = ilBadgeHandler::getInstance(); + return $handler->getTypeInstanceByUniqueId($this->getTypeId()); + } + } + + public function copy($a_new_parent_id) + { + $lng = $this->lng; + + $this->setTitle($this->getTitle() . " " . $lng->txt("copy_of_suffix")); + $this->setParentId($a_new_parent_id); + $this->setActive(false); + + if ($this->getId()) { + $img = $this->getImagePath(); + + $this->setId(null); + $this->create(); - if($img) - { - // see uploadImage() - copy($img, $this->getImagePath()); - } - } - } - - public static function getObjectInstances(array $a_filter = null) - { - global $DIC; + if ($img) { + // see uploadImage() + copy($img, $this->getImagePath()); + } + } + } + + public static function getObjectInstances(array $a_filter = null) + { + global $DIC; - $ilDB = $DIC->database(); - - $res = $raw = array(); - - $where = ""; - - if($a_filter["type"]) - { - $where .= " AND bb.type_id = ".$ilDB->quote($a_filter["type"], "text"); - } - if($a_filter["title"]) - { - $where .= " AND ".$ilDB->like("bb.title", "text", "%".$a_filter["title"]."%"); - } - if($a_filter["object"]) - { - $where .= " AND ".$ilDB->like("od.title", "text", "%".$a_filter["object"]."%"); - } - - $set = $ilDB->query("SELECT bb.*, od.title parent_title, od.type parent_type". - " FROM badge_badge bb". - " JOIN object_data od ON (bb.parent_id = od.obj_id)". - " WHERE od.type <> ".$ilDB->quote("bdga", "text"). - $where); - while($row = $ilDB->fetchAssoc($set)) - { - $raw[] = $row; - } - - $set = $ilDB->query("SELECT bb.*, od.title parent_title, od.type parent_type". - " FROM badge_badge bb". - " JOIN object_data_del od ON (bb.parent_id = od.obj_id)". - " WHERE od.type <> ".$ilDB->quote("bdga", "text"). - $where); - while($row = $ilDB->fetchAssoc($set)) - { - $row["deleted"] = true; - $raw[] = $row; - } - - foreach($raw as $row) - { - // :TODO: - - $res[] = $row; - } - - return $res; - } - - - // - // setter/getter - // - - protected function setId($a_id) - { - $this->id = (int)$a_id; - } - - public function getId() - { - return $this->id; - } - - public function setParentId($a_id) - { - $this->parent_id = (int)$a_id; - } - - public function getParentId() - { - return $this->parent_id; - } - - public function setTypeId($a_id) - { - $this->type_id = trim($a_id); - } - - public function getTypeId() - { - return $this->type_id; - } - - public function setActive($a_value) - { - $this->active = (bool)$a_value; - } - - public function isActive() - { - return $this->active; - } - - public function setTitle($a_value) - { - $this->title = trim($a_value); - } - - public function getTitle() - { - return $this->title; - } - - public function setDescription($a_value) - { - $this->desc = trim($a_value); - } - - public function getDescription() - { - return $this->desc; - } - - public function setCriteria($a_value) - { - $this->criteria = trim($a_value); - } - - public function getCriteria() - { - return $this->criteria; - } - - public function setValid($a_value) - { - $this->valid = trim($a_value); - } - - public function getValid() - { - return $this->valid; - } - - public function setConfiguration(array $a_value = null) - { - if(is_array($a_value) && - !sizeof($a_value)) - { - $a_value = null; - } - $this->config = $a_value; - } - - public function getConfiguration() - { - return $this->config; - } - - protected function setImage($a_value) - { - $this->image = trim($a_value); - } - - public function getImage() - { - return $this->image; - } + $ilDB = $DIC->database(); + + $res = $raw = array(); + + $where = ""; + + if ($a_filter["type"]) { + $where .= " AND bb.type_id = " . $ilDB->quote($a_filter["type"], "text"); + } + if ($a_filter["title"]) { + $where .= " AND " . $ilDB->like("bb.title", "text", "%" . $a_filter["title"] . "%"); + } + if ($a_filter["object"]) { + $where .= " AND " . $ilDB->like("od.title", "text", "%" . $a_filter["object"] . "%"); + } + + $set = $ilDB->query("SELECT bb.*, od.title parent_title, od.type parent_type" . + " FROM badge_badge bb" . + " JOIN object_data od ON (bb.parent_id = od.obj_id)" . + " WHERE od.type <> " . $ilDB->quote("bdga", "text") . + $where); + while ($row = $ilDB->fetchAssoc($set)) { + $raw[] = $row; + } + + $set = $ilDB->query("SELECT bb.*, od.title parent_title, od.type parent_type" . + " FROM badge_badge bb" . + " JOIN object_data_del od ON (bb.parent_id = od.obj_id)" . + " WHERE od.type <> " . $ilDB->quote("bdga", "text") . + $where); + while ($row = $ilDB->fetchAssoc($set)) { + $row["deleted"] = true; + $raw[] = $row; + } + + foreach ($raw as $row) { + // :TODO: + + $res[] = $row; + } + + return $res; + } + + + // + // setter/getter + // + + protected function setId($a_id) + { + $this->id = (int) $a_id; + } + + public function getId() + { + return $this->id; + } + + public function setParentId($a_id) + { + $this->parent_id = (int) $a_id; + } + + public function getParentId() + { + return $this->parent_id; + } + + public function setTypeId($a_id) + { + $this->type_id = trim($a_id); + } + + public function getTypeId() + { + return $this->type_id; + } + + public function setActive($a_value) + { + $this->active = (bool) $a_value; + } + + public function isActive() + { + return $this->active; + } + + public function setTitle($a_value) + { + $this->title = trim($a_value); + } + + public function getTitle() + { + return $this->title; + } + + public function setDescription($a_value) + { + $this->desc = trim($a_value); + } + + public function getDescription() + { + return $this->desc; + } + + public function setCriteria($a_value) + { + $this->criteria = trim($a_value); + } + + public function getCriteria() + { + return $this->criteria; + } + + public function setValid($a_value) + { + $this->valid = trim($a_value); + } + + public function getValid() + { + return $this->valid; + } + + public function setConfiguration(array $a_value = null) + { + if (is_array($a_value) && + !sizeof($a_value)) { + $a_value = null; + } + $this->config = $a_value; + } + + public function getConfiguration() + { + return $this->config; + } + + protected function setImage($a_value) + { + $this->image = trim($a_value); + } + + public function getImage() + { + return $this->image; + } - /** - * @param array $a_upload_meta - * @throws ilFileUtilsException - */ - public function uploadImage(array $a_upload_meta) - { - if($this->getId() && - $a_upload_meta["tmp_name"]) - { - $this->setImage($a_upload_meta["name"]); - $path = $this->getImagePath(); + /** + * @param array $a_upload_meta + * @throws ilFileUtilsException + */ + public function uploadImage(array $a_upload_meta) + { + if ($this->getId() && + $a_upload_meta["tmp_name"]) { + $this->setImage($a_upload_meta["name"]); + $path = $this->getImagePath(); - if (ilUtil::moveUploadedFile($a_upload_meta["tmp_name"], $this->getImagePath(false), $path)) - { - $this->update(); - } - } - } - - public function importImage($a_name, $a_file) - { - if(file_exists($a_file)) - { - $this->setImage($a_name); - copy($a_file, $this->getImagePath()); // #18280 - - $this->update(); - } - } - - public function getImagePath($a_full_path = true) - { - if($this->getId()) - { - $suffix = strtolower(array_pop(explode(".", $this->getImage()))); - if ($a_full_path) - { - return $this->getFilePath($this->getId()) . "img" . $this->getId() . "." . $suffix; - } - else - { - return "img" . $this->getId() . "." . $suffix; - } - } - } - - /** - * Init file system storage - * - * @param type $a_id - * @param type $a_subdir - * @return string - */ - protected function getFilePath($a_id, $a_subdir = null) - { - include_once "Services/Badge/classes/class.ilFSStorageBadge.php"; - $storage = new ilFSStorageBadge($a_id); - $storage->create(); - - $path = $storage->getAbsolutePath()."/"; - - if($a_subdir) - { - $path .= $a_subdir."/"; - - if(!is_dir($path)) - { - mkdir($path); - } - } - - return $path; - } - - - // - // crud - // - - protected function read($a_id) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT * FROM badge_badge". - " WHERE id = ".$ilDB->quote($a_id, "integer")); - if($ilDB->numRows($set)) - { - $row = $ilDB->fetchAssoc($set); - $this->importDBRow($row); - } - } - - protected function importDBRow(array $a_row) - { - $this->setId($a_row["id"]); - $this->setParentId($a_row["parent_id"]); - $this->setTypeId($a_row["type_id"]); - $this->setActive($a_row["active"]); - $this->setTitle($a_row["title"]); - $this->setDescription($a_row["descr"]); - $this->setCriteria($a_row["crit"]); - $this->setImage($a_row["image"]); - $this->setValid($a_row["valid"]); - $this->setConfiguration($a_row["conf"] - ? unserialize($a_row["conf"]) - : null); - } - - public function create() - { - $ilDB = $this->db; - - if($this->getId()) - { - return $this->update(); - } - - $id = $ilDB->nextId("badge_badge"); - $this->setId($id); - - $fields = $this->getPropertiesForStorage(); - - $fields["id"] = array("integer", $id); - $fields["parent_id"] = array("integer", $this->getParentId()); - $fields["type_id"] = array("text", $this->getTypeId()); - - $ilDB->insert("badge_badge", $fields); - } - - public function update() - { - $ilDB = $this->db; - - if(!$this->getId()) - { - return $this->create(); - } - - $fields = $this->getPropertiesForStorage(); - - $ilDB->update("badge_badge", $fields, - array("id"=>array("integer", $this->getId())) - ); - } - - public function delete() - { - $ilDB = $this->db; - - if(!$this->getId()) - { - return; - } - - if(file_exists($this->getImagePath())) - { - unlink($this->getImagePath()); - } - - $this->deleteStaticFiles(); - - include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; - ilBadgeAssignment::deleteByBadgeId($this->getId()); - - $ilDB->manipulate("DELETE FROM badge_badge". - " WHERE id = ".$ilDB->quote($this->getId(), "integer")); - } - - protected function getPropertiesForStorage() - { - return array( - "active" => array("integer", $this->isActive()), - "title" => array("text", $this->getTitle()), - "descr" => array("text", $this->getDescription()), - "crit" => array("text", $this->getCriteria()), - "image" => array("text", $this->getImage()), - "valid" => array("text", $this->getValid()), - "conf" => array("text", $this->getConfiguration() - ? serialize($this->getConfiguration()) - : null) - ); - } - - - // - // helper - // - - public function getParentMeta() - { - $parent_type = ilObject::_lookupType($this->getParentId()); - if($parent_type) - { - $parent_title = ilObject::_lookupTitle($this->getParentId()); - $deleted = false; - } - else - { - // already deleted? - include_once "Services/Object/classes/class.ilObjectDataDeletionLog.php"; - $parent = ilObjectDataDeletionLog::get($this->getParentId()); - if($parent["type"]) - { - $parent_type = $parent["type"]; - $parent_title = $parent["title"]; - } - $deleted = true; - } - - return array( - "id" => $this->getParentId(), - "type" => $parent_type, - "title" => $parent_title, - "deleted" => $deleted - ); - } - - - // - // PUBLISHING - // - - protected function prepareJson($a_base_url, $a_img_suffix) - { - $json = new stdClass(); - $json->{"@context"} = "https://w3id.org/openbadges/v1"; - $json->type = "BadgeClass"; - $json->id = $a_base_url."class.json"; - $json->name = $this->getTitle(); - $json->description = $this->getDescription(); - $json->image = $a_base_url."image.".$a_img_suffix; - $json->criteria = $a_base_url."criteria.txt"; - $json->issuer = ilBadgeHandler::getInstance()->getIssuerStaticUrl(); - - return $json; - } - - public function getStaticUrl() - { - $path = ilBadgeHandler::getInstance()->getBadgePath($this); - - $base_url = ILIAS_HTTP_PATH.substr($path, 1); - - if(!file_exists($path."class.json")) - { - $img_suffix = array_pop(explode(".", $this->getImage())); - - $json = json_encode($this->prepareJson($base_url, $img_suffix)); - file_put_contents($path."class.json", $json); - - // :TODO: scale? - copy($this->getImagePath(), $path."image.".$img_suffix); - - file_put_contents($path."criteria.txt", $this->getCriteria()); - } - - return $base_url."class.json"; - } + if (ilUtil::moveUploadedFile($a_upload_meta["tmp_name"], $this->getImagePath(false), $path)) { + $this->update(); + } + } + } + + public function importImage($a_name, $a_file) + { + if (file_exists($a_file)) { + $this->setImage($a_name); + copy($a_file, $this->getImagePath()); // #18280 + + $this->update(); + } + } + + public function getImagePath($a_full_path = true) + { + if ($this->getId()) { + $suffix = strtolower(array_pop(explode(".", $this->getImage()))); + if ($a_full_path) { + return $this->getFilePath($this->getId()) . "img" . $this->getId() . "." . $suffix; + } else { + return "img" . $this->getId() . "." . $suffix; + } + } + } + + /** + * Init file system storage + * + * @param type $a_id + * @param type $a_subdir + * @return string + */ + protected function getFilePath($a_id, $a_subdir = null) + { + include_once "Services/Badge/classes/class.ilFSStorageBadge.php"; + $storage = new ilFSStorageBadge($a_id); + $storage->create(); + + $path = $storage->getAbsolutePath() . "/"; + + if ($a_subdir) { + $path .= $a_subdir . "/"; + + if (!is_dir($path)) { + mkdir($path); + } + } + + return $path; + } + + + // + // crud + // + + protected function read($a_id) + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT * FROM badge_badge" . + " WHERE id = " . $ilDB->quote($a_id, "integer")); + if ($ilDB->numRows($set)) { + $row = $ilDB->fetchAssoc($set); + $this->importDBRow($row); + } + } + + protected function importDBRow(array $a_row) + { + $this->setId($a_row["id"]); + $this->setParentId($a_row["parent_id"]); + $this->setTypeId($a_row["type_id"]); + $this->setActive($a_row["active"]); + $this->setTitle($a_row["title"]); + $this->setDescription($a_row["descr"]); + $this->setCriteria($a_row["crit"]); + $this->setImage($a_row["image"]); + $this->setValid($a_row["valid"]); + $this->setConfiguration($a_row["conf"] + ? unserialize($a_row["conf"]) + : null); + } + + public function create() + { + $ilDB = $this->db; + + if ($this->getId()) { + return $this->update(); + } + + $id = $ilDB->nextId("badge_badge"); + $this->setId($id); + + $fields = $this->getPropertiesForStorage(); + + $fields["id"] = array("integer", $id); + $fields["parent_id"] = array("integer", $this->getParentId()); + $fields["type_id"] = array("text", $this->getTypeId()); + + $ilDB->insert("badge_badge", $fields); + } + + public function update() + { + $ilDB = $this->db; + + if (!$this->getId()) { + return $this->create(); + } + + $fields = $this->getPropertiesForStorage(); + + $ilDB->update( + "badge_badge", + $fields, + array("id"=>array("integer", $this->getId())) + ); + } + + public function delete() + { + $ilDB = $this->db; + + if (!$this->getId()) { + return; + } + + if (file_exists($this->getImagePath())) { + unlink($this->getImagePath()); + } + + $this->deleteStaticFiles(); + + include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; + ilBadgeAssignment::deleteByBadgeId($this->getId()); + + $ilDB->manipulate("DELETE FROM badge_badge" . + " WHERE id = " . $ilDB->quote($this->getId(), "integer")); + } + + protected function getPropertiesForStorage() + { + return array( + "active" => array("integer", $this->isActive()), + "title" => array("text", $this->getTitle()), + "descr" => array("text", $this->getDescription()), + "crit" => array("text", $this->getCriteria()), + "image" => array("text", $this->getImage()), + "valid" => array("text", $this->getValid()), + "conf" => array("text", $this->getConfiguration() + ? serialize($this->getConfiguration()) + : null) + ); + } + + + // + // helper + // + + public function getParentMeta() + { + $parent_type = ilObject::_lookupType($this->getParentId()); + if ($parent_type) { + $parent_title = ilObject::_lookupTitle($this->getParentId()); + $deleted = false; + } else { + // already deleted? + include_once "Services/Object/classes/class.ilObjectDataDeletionLog.php"; + $parent = ilObjectDataDeletionLog::get($this->getParentId()); + if ($parent["type"]) { + $parent_type = $parent["type"]; + $parent_title = $parent["title"]; + } + $deleted = true; + } + + return array( + "id" => $this->getParentId(), + "type" => $parent_type, + "title" => $parent_title, + "deleted" => $deleted + ); + } + + + // + // PUBLISHING + // + + protected function prepareJson($a_base_url, $a_img_suffix) + { + $json = new stdClass(); + $json->{"@context"} = "https://w3id.org/openbadges/v1"; + $json->type = "BadgeClass"; + $json->id = $a_base_url . "class.json"; + $json->name = $this->getTitle(); + $json->description = $this->getDescription(); + $json->image = $a_base_url . "image." . $a_img_suffix; + $json->criteria = $a_base_url . "criteria.txt"; + $json->issuer = ilBadgeHandler::getInstance()->getIssuerStaticUrl(); + + return $json; + } + + public function getStaticUrl() + { + $path = ilBadgeHandler::getInstance()->getBadgePath($this); + + $base_url = ILIAS_HTTP_PATH . substr($path, 1); + + if (!file_exists($path . "class.json")) { + $img_suffix = array_pop(explode(".", $this->getImage())); + + $json = json_encode($this->prepareJson($base_url, $img_suffix)); + file_put_contents($path . "class.json", $json); + + // :TODO: scale? + copy($this->getImagePath(), $path . "image." . $img_suffix); + + file_put_contents($path . "criteria.txt", $this->getCriteria()); + } + + return $base_url . "class.json"; + } - public function deleteStaticFiles() - { - // remove instance files - $path = ilBadgeHandler::getInstance()->getBadgePath($this); - if(is_dir($path)) - { - ilUtil::delDir($path); - } - } - - public static function getExtendedTypeCaption(ilBadgeType $a_type) - { - global $DIC; + public function deleteStaticFiles() + { + // remove instance files + $path = ilBadgeHandler::getInstance()->getBadgePath($this); + if (is_dir($path)) { + ilUtil::delDir($path); + } + } + + public static function getExtendedTypeCaption(ilBadgeType $a_type) + { + global $DIC; - $lng = $DIC->language(); - - return $a_type->getCaption()." (". - ($a_type instanceof ilBadgeAuto - ? $lng->txt("badge_subtype_auto") - : $lng->txt("badge_subtype_manual")).")"; - } + $lng = $DIC->language(); + + return $a_type->getCaption() . " (" . + ($a_type instanceof ilBadgeAuto + ? $lng->txt("badge_subtype_auto") + : $lng->txt("badge_subtype_manual")) . ")"; + } } - diff --git a/Services/Badge/classes/class.ilBadgeAppEventListener.php b/Services/Badge/classes/class.ilBadgeAppEventListener.php index 96ae2b214385a57b9b63465f8d93fbc9538fb7c7..05bb3fd1dae939968604a8fbcc3c17ba179c7bc5 100644 --- a/Services/Badge/classes/class.ilBadgeAppEventListener.php +++ b/Services/Badge/classes/class.ilBadgeAppEventListener.php @@ -4,49 +4,45 @@ include_once './Services/EventHandling/interfaces/interface.ilAppEventListener.php'; include_once './Services/Badge/classes/class.ilBadgeHandler.php'; -/** +/** * Trigger activity badges from events - * + * * @author Jörg Lützenkirchen * @version $Id$ * * @ingroup ServicesBadge */ class ilBadgeAppEventListener implements ilAppEventListener -{ - public static function handleEvent($a_component, $a_event, $a_params) - { - switch($a_component) - { - case 'Services/User': - switch($a_event) - { - case 'afterUpdate': - $user_obj = $a_params['user_obj']; - ilBadgeHandler::getInstance()->triggerEvaluation( - 'user/profile', - $user_obj->getId() - ); - break; - } - break; - - case 'Services/Tracking': - switch($a_event) - { - case 'updateStatus': - if($a_params['status'] == ilLPStatus::LP_STATUS_COMPLETED_NUM) - { - ilBadgeHandler::getInstance()->triggerEvaluation( - 'crs/course_lp', - $a_params['usr_id'], - array('obj_id' => $a_params['obj_id']) - ); - } - break; - } - break; - - } - } -} \ No newline at end of file +{ + public static function handleEvent($a_component, $a_event, $a_params) + { + switch ($a_component) { + case 'Services/User': + switch ($a_event) { + case 'afterUpdate': + $user_obj = $a_params['user_obj']; + ilBadgeHandler::getInstance()->triggerEvaluation( + 'user/profile', + $user_obj->getId() + ); + break; + } + break; + + case 'Services/Tracking': + switch ($a_event) { + case 'updateStatus': + if ($a_params['status'] == ilLPStatus::LP_STATUS_COMPLETED_NUM) { + ilBadgeHandler::getInstance()->triggerEvaluation( + 'crs/course_lp', + $a_params['usr_id'], + array('obj_id' => $a_params['obj_id']) + ); + } + break; + } + break; + + } + } +} diff --git a/Services/Badge/classes/class.ilBadgeAssignment.php b/Services/Badge/classes/class.ilBadgeAssignment.php index a35321b83c2178b29e2bb9ee0b9727a2f7aec978..be560b66d1b0013fc3411f99f06184585a467b83 100644 --- a/Services/Badge/classes/class.ilBadgeAssignment.php +++ b/Services/Badge/classes/class.ilBadgeAssignment.php @@ -3,7 +3,7 @@ /** * Class ilBadgeAssignment - * + * * @author Jörg Lützenkirchen * @version $Id:$ * @@ -11,483 +11,451 @@ */ class ilBadgeAssignment { - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; - protected $badge_id; // [int] - protected $user_id; // [int] - protected $tstamp; // [timestamp] - protected $awarded_by; // [int] - protected $pos; // [int] - protected $stored; // [bool] - - public function __construct($a_badge_id = null, $a_user_id = null) - { - global $DIC; + protected $badge_id; // [int] + protected $user_id; // [int] + protected $tstamp; // [timestamp] + protected $awarded_by; // [int] + protected $pos; // [int] + protected $stored; // [bool] + + public function __construct($a_badge_id = null, $a_user_id = null) + { + global $DIC; - $this->db = $DIC->database(); - if($a_badge_id && - $a_user_id) - { - $this->setBadgeId($a_badge_id); - $this->setUserId($a_user_id); - - $this->read($a_badge_id, $a_user_id); - } - } - - public static function getInstancesByUserId($a_user_id) - { - global $DIC; + $this->db = $DIC->database(); + if ($a_badge_id && + $a_user_id) { + $this->setBadgeId($a_badge_id); + $this->setUserId($a_user_id); + + $this->read($a_badge_id, $a_user_id); + } + } + + public static function getInstancesByUserId($a_user_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $res = array(); - - $set = $ilDB->query("SELECT * FROM badge_user_badge". - " WHERE user_id = ".$ilDB->quote($a_user_id, "integer"). - " ORDER BY pos"); - while($row = $ilDB->fetchAssoc($set)) - { - $obj = new self(); - $obj->importDBRow($row); - $res[] = $obj; - } - - return $res; - } - - public static function getInstancesByBadgeId($a_badge_id) - { - global $DIC; + $ilDB = $DIC->database(); + + $res = array(); + + $set = $ilDB->query("SELECT * FROM badge_user_badge" . + " WHERE user_id = " . $ilDB->quote($a_user_id, "integer") . + " ORDER BY pos"); + while ($row = $ilDB->fetchAssoc($set)) { + $obj = new self(); + $obj->importDBRow($row); + $res[] = $obj; + } + + return $res; + } + + public static function getInstancesByBadgeId($a_badge_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $res = array(); - - $set = $ilDB->query("SELECT * FROM badge_user_badge". - " WHERE badge_id = ".$ilDB->quote($a_badge_id, "integer")); - while($row = $ilDB->fetchAssoc($set)) - { - $obj = new self(); - $obj->importDBRow($row); - $res[] = $obj; - } - - return $res; - } - - public static function getInstancesByParentId($a_parent_obj_id) - { - global $DIC; + $ilDB = $DIC->database(); + + $res = array(); + + $set = $ilDB->query("SELECT * FROM badge_user_badge" . + " WHERE badge_id = " . $ilDB->quote($a_badge_id, "integer")); + while ($row = $ilDB->fetchAssoc($set)) { + $obj = new self(); + $obj->importDBRow($row); + $res[] = $obj; + } + + return $res; + } + + public static function getInstancesByParentId($a_parent_obj_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $res = array(); - - $badge_ids = array(); - foreach(ilBadge::getInstancesByParentId($a_parent_obj_id) as $badge) - { - $badge_ids[] = $badge->getId(); - } - if(sizeof($badge_ids)) - { - $set = $ilDB->query("SELECT * FROM badge_user_badge". - " WHERE ".$ilDB->in("badge_id", $badge_ids, "", "integer")); - while($row = $ilDB->fetchAssoc($set)) - { - $obj = new self(); - $obj->importDBRow($row); - $res[] = $obj; - } - } - - return $res; - } - - public static function getAssignedUsers($a_badge_id) - { - $res = array(); - - foreach(self::getInstancesByBadgeId($a_badge_id) as $ass) - { - $res[] = $ass->getUserId(); - } - - return $res; - } - - public static function exists($a_badge_id, $a_user_id) - { - $obj = new self($a_badge_id, $a_user_id); - return $obj->stored; - } - - - // - // setter/getter - // - - protected function setBadgeId($a_value) - { - $this->badge_id = (int)$a_value; - } - - public function getBadgeId() - { - return $this->badge_id; - } - - protected function setUserId($a_value) - { - $this->user_id = (int)$a_value; - } - - public function getUserId() - { - return $this->user_id; - } - - protected function setTimestamp($a_value) - { - $this->tstamp = (int)$a_value; - } - - public function getTimestamp() - { - return $this->tstamp; - } - - public function setAwardedBy($a_id) - { - $this->awarded_by = (int)$a_id; - } - - public function getAwardedBy() - { - return $this->awarded_by; - } - - public function setPosition($a_value) - { - if($a_value !== null) - { - $a_value = (int)$a_value; - } - $this->pos = $a_value; - } - - public function getPosition() - { - return $this->pos; - } - - - // - // crud - // - - protected function importDBRow(array $a_row) - { - $this->stored = true; - $this->setBadgeId($a_row["badge_id"]); - $this->setUserId($a_row["user_id"]); - $this->setTimestamp($a_row["tstamp"]); - $this->setAwardedBy($a_row["awarded_by"]); - $this->setPosition($a_row["pos"]); - } - - protected function read($a_badge_id, $a_user_id) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT * FROM badge_user_badge". - " WHERE badge_id = ".$ilDB->quote($a_badge_id, "integer"). - " AND user_id = ".$ilDB->quote($a_user_id, "integer")); - $row = $ilDB->fetchAssoc($set); - if($row["user_id"]) - { - $this->importDBRow($row); - } - } - - protected function getPropertiesForStorage() - { - return array( - "tstamp" => array("integer", (bool)$this->stored ? $this->getTimestamp() : time()), - "awarded_by" => array("integer", $this->getAwardedBy()), - "pos" => array("integer", $this->getPosition()) - ); - } - - public function store() - { - $ilDB = $this->db; - - if(!$this->getBadgeId() || - !$this->getUserId()) - { - return; - } - - $keys = array( - "badge_id" => array("integer", $this->getBadgeId()), - "user_id" => array("integer", $this->getUserId()) - ); - $fields = $this->getPropertiesForStorage(); - - if(!(bool)$this->stored) - { - $ilDB->insert("badge_user_badge", $fields + $keys); - } - else - { - $ilDB->update("badge_user_badge", $fields, $keys); - } - } - - public function delete() - { - $ilDB = $this->db; - - if(!$this->getBadgeId() || - !$this->getUserId()) - { - return; - } - - $this->deleteStaticFiles(); - - $ilDB->manipulate("DELETE FROM badge_user_badge". - " WHERE badge_id = ".$ilDB->quote($this->getBadgeId(), "integer"). - " AND user_id = ".$ilDB->quote($this->getUserId(), "integer")); - } - - public static function deleteByUserId($a_user_id) - { - foreach(self::getInstancesByUserId($a_user_id) as $ass) - { - $ass->delete(); - } - } - - public static function deleteByBadgeId($a_badge_id) - { - foreach(self::getInstancesByBadgeId($a_badge_id) as $ass) - { - $ass->delete(); - } - } - - public static function deleteByParentId($a_parent_obj_id) - { - foreach(self::getInstancesByParentId($a_parent_obj_id) as $ass) - { - $ass->delete(); - } - } - - public static function updatePositions($a_user_id, array $a_positions) - { - $existing = array(); - include_once "Services/Badge/classes/class.ilBadge.php"; - foreach(self::getInstancesByUserId($a_user_id) as $ass) - { - $badge = new ilBadge($ass->getBadgeId()); - $existing[$badge->getId()] = array($badge->getTitle(), $ass); - } - - $new_pos = 0; - foreach($a_positions as $title) - { - foreach($existing as $id => $item) - { - if($title == $item[0]) - { - $item[1]->setPosition(++$new_pos); - $item[1]->store(); - unset($existing[$id]); - } - } - } - } - - /** - * Get badges for user - * @param int $a_user_id - * @param int $a_ts_from - * @param int $a_ts_to - * @return array - */ - public static function getBadgesForUser($a_user_id, $a_ts_from, $a_ts_to) - { - global $DIC; - - $db = $DIC->database(); - - $set = $db->queryF("SELECT bdg.parent_id, ub.tstamp, bdg.title FROM badge_user_badge ub JOIN badge_badge bdg". - " ON (ub.badge_id = bdg.id) ". - " WHERE ub.user_id = %s AND ub.tstamp >= %s AND ub.tstamp <= %s", - array("integer","integer","integer"), - array($a_user_id, $a_ts_from, $a_ts_to) - ); - $res = []; - while ($rec = $db->fetchAssoc($set)) - { - $res[] = $rec; - } - return $res; - } - - - // - // PUBLISHING - // - - protected function prepareJson($a_url) - { - $verify = new stdClass(); - $verify->type = "hosted"; - $verify->url = $a_url; - - $recipient = new stdClass(); - $recipient->type = "email"; - $recipient->hashed = true; - $recipient->salt = ilBadgeHandler::getInstance()->getObiSalt(); - - // https://github.com/mozilla/openbadges-backpack/wiki/How-to-hash-&-salt-in-various-languages. - include_once "Services/Badge/classes/class.ilBadgeProfileGUI.php"; - $user = new ilObjUser($this->getUserId()); - $mail = $user->getPref(ilBadgeProfileGUI::BACKPACK_EMAIL); - if(!$mail) - { - $mail = $user->getEmail(); - } - $recipient->identity = 'sha256$'.hash('sha256', $mail.$recipient->salt); - - // spec: should be locally unique - $unique_id = md5($this->getBadgeId()."-".$this->getUserId()); - - $json = new stdClass(); - $json->{"@context"} = "https://w3id.org/openbadges/v1"; - $json->type = "Assertion"; - $json->id = $a_url; - $json->uid = $unique_id; - $json->recipient = $recipient; - - include_once "Services/Badge/classes/class.ilBadge.php"; - $badge = new ilBadge($this->getBadgeId()); - $badge_url = $badge->getStaticUrl(); - - // created baked image - $baked_image = $this->getImagePath($badge); - if($this->bakeImage($baked_image, $badge->getImagePath(), $a_url)) - { - // path to url - $parts = explode("/", $a_url); - array_pop($parts); - $parts[] = basename($baked_image); - $json->image = implode("/", $parts); - } - - $json->issuedOn = $this->getTimestamp(); - $json->badge = $badge_url; - $json->verify = $verify; - - return $json; - } - - public function getImagePath(ilBadge $a_badge) - { - $json_path = ilBadgeHandler::getInstance()->getInstancePath($this); - $baked_path = dirname($json_path); - $baked_file = array_shift(explode(".", basename($json_path))); - - // get correct suffix from badge image - $suffix = strtolower(array_pop(explode(".", basename($a_badge->getImagePath())))); - return $baked_path."/".$baked_file.".".$suffix; - } - - protected function bakeImage($a_baked_image_path, $a_badge_image_path, $a_assertion_url) - { - $suffix = strtolower(array_pop(explode(".", basename($a_badge_image_path)))); - if($suffix == "png") - { - // using chamilo baker lib - include_once "Services/Badge/lib/baker.lib.php"; - $png = new PNGImageBaker(file_get_contents($a_badge_image_path)); - - // add payload - if($png->checkChunks("tEXt", "openbadges")) - { - $baked = $png->addChunk("tEXt", "openbadges", $a_assertion_url); - } - - // create baked file - if(!file_exists($a_baked_image_path)) - { - file_put_contents($a_baked_image_path, $baked); - } - - // verify file - $verify = $png->extractBadgeInfo(file_get_contents($a_baked_image_path)); - if(is_array($verify)) - { - return true; - } - } - else if($suffix == "svg") - { - // :TODO: not really sure if this is correct - $svg = simplexml_load_file($a_badge_image_path); - $ass = $svg->addChild("openbadges:assertion", "", "http://openbadges.org"); - $ass->addAttribute("verify", $a_assertion_url); - $baked = $svg->asXML(); - - // create baked file - if(!file_exists($a_baked_image_path)) - { - file_put_contents($a_baked_image_path, $baked); - } - - return true; - } - - return false; - } - - public function getStaticUrl() - { - include_once("./Services/Badge/classes/class.ilBadgeHandler.php"); - $path = ilBadgeHandler::getInstance()->getInstancePath($this); - - $url = ILIAS_HTTP_PATH.substr($path, 1); - - if(!file_exists($path)) - { - $json = json_encode($this->prepareJson($url)); - file_put_contents($path, $json); - } - - return $url; - } - - public function deleteStaticFiles() - { - // remove instance files - include_once("./Services/Badge/classes/class.ilBadgeHandler.php"); - $path = ilBadgeHandler::getInstance()->getInstancePath($this); - $path = str_replace(".json", ".*", $path); - array_map("unlink", glob($path)); - } - - public static function clearBadgeCache($a_user_id) - { - foreach(self::getInstancesByUserId($a_user_id) as $ass) - { - $ass->deleteStaticFiles(); - } - } -} \ No newline at end of file + $ilDB = $DIC->database(); + + $res = array(); + + $badge_ids = array(); + foreach (ilBadge::getInstancesByParentId($a_parent_obj_id) as $badge) { + $badge_ids[] = $badge->getId(); + } + if (sizeof($badge_ids)) { + $set = $ilDB->query("SELECT * FROM badge_user_badge" . + " WHERE " . $ilDB->in("badge_id", $badge_ids, "", "integer")); + while ($row = $ilDB->fetchAssoc($set)) { + $obj = new self(); + $obj->importDBRow($row); + $res[] = $obj; + } + } + + return $res; + } + + public static function getAssignedUsers($a_badge_id) + { + $res = array(); + + foreach (self::getInstancesByBadgeId($a_badge_id) as $ass) { + $res[] = $ass->getUserId(); + } + + return $res; + } + + public static function exists($a_badge_id, $a_user_id) + { + $obj = new self($a_badge_id, $a_user_id); + return $obj->stored; + } + + + // + // setter/getter + // + + protected function setBadgeId($a_value) + { + $this->badge_id = (int) $a_value; + } + + public function getBadgeId() + { + return $this->badge_id; + } + + protected function setUserId($a_value) + { + $this->user_id = (int) $a_value; + } + + public function getUserId() + { + return $this->user_id; + } + + protected function setTimestamp($a_value) + { + $this->tstamp = (int) $a_value; + } + + public function getTimestamp() + { + return $this->tstamp; + } + + public function setAwardedBy($a_id) + { + $this->awarded_by = (int) $a_id; + } + + public function getAwardedBy() + { + return $this->awarded_by; + } + + public function setPosition($a_value) + { + if ($a_value !== null) { + $a_value = (int) $a_value; + } + $this->pos = $a_value; + } + + public function getPosition() + { + return $this->pos; + } + + + // + // crud + // + + protected function importDBRow(array $a_row) + { + $this->stored = true; + $this->setBadgeId($a_row["badge_id"]); + $this->setUserId($a_row["user_id"]); + $this->setTimestamp($a_row["tstamp"]); + $this->setAwardedBy($a_row["awarded_by"]); + $this->setPosition($a_row["pos"]); + } + + protected function read($a_badge_id, $a_user_id) + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT * FROM badge_user_badge" . + " WHERE badge_id = " . $ilDB->quote($a_badge_id, "integer") . + " AND user_id = " . $ilDB->quote($a_user_id, "integer")); + $row = $ilDB->fetchAssoc($set); + if ($row["user_id"]) { + $this->importDBRow($row); + } + } + + protected function getPropertiesForStorage() + { + return array( + "tstamp" => array("integer", (bool) $this->stored ? $this->getTimestamp() : time()), + "awarded_by" => array("integer", $this->getAwardedBy()), + "pos" => array("integer", $this->getPosition()) + ); + } + + public function store() + { + $ilDB = $this->db; + + if (!$this->getBadgeId() || + !$this->getUserId()) { + return; + } + + $keys = array( + "badge_id" => array("integer", $this->getBadgeId()), + "user_id" => array("integer", $this->getUserId()) + ); + $fields = $this->getPropertiesForStorage(); + + if (!(bool) $this->stored) { + $ilDB->insert("badge_user_badge", $fields + $keys); + } else { + $ilDB->update("badge_user_badge", $fields, $keys); + } + } + + public function delete() + { + $ilDB = $this->db; + + if (!$this->getBadgeId() || + !$this->getUserId()) { + return; + } + + $this->deleteStaticFiles(); + + $ilDB->manipulate("DELETE FROM badge_user_badge" . + " WHERE badge_id = " . $ilDB->quote($this->getBadgeId(), "integer") . + " AND user_id = " . $ilDB->quote($this->getUserId(), "integer")); + } + + public static function deleteByUserId($a_user_id) + { + foreach (self::getInstancesByUserId($a_user_id) as $ass) { + $ass->delete(); + } + } + + public static function deleteByBadgeId($a_badge_id) + { + foreach (self::getInstancesByBadgeId($a_badge_id) as $ass) { + $ass->delete(); + } + } + + public static function deleteByParentId($a_parent_obj_id) + { + foreach (self::getInstancesByParentId($a_parent_obj_id) as $ass) { + $ass->delete(); + } + } + + public static function updatePositions($a_user_id, array $a_positions) + { + $existing = array(); + include_once "Services/Badge/classes/class.ilBadge.php"; + foreach (self::getInstancesByUserId($a_user_id) as $ass) { + $badge = new ilBadge($ass->getBadgeId()); + $existing[$badge->getId()] = array($badge->getTitle(), $ass); + } + + $new_pos = 0; + foreach ($a_positions as $title) { + foreach ($existing as $id => $item) { + if ($title == $item[0]) { + $item[1]->setPosition(++$new_pos); + $item[1]->store(); + unset($existing[$id]); + } + } + } + } + + /** + * Get badges for user + * @param int $a_user_id + * @param int $a_ts_from + * @param int $a_ts_to + * @return array + */ + public static function getBadgesForUser($a_user_id, $a_ts_from, $a_ts_to) + { + global $DIC; + + $db = $DIC->database(); + + $set = $db->queryF( + "SELECT bdg.parent_id, ub.tstamp, bdg.title FROM badge_user_badge ub JOIN badge_badge bdg" . + " ON (ub.badge_id = bdg.id) " . + " WHERE ub.user_id = %s AND ub.tstamp >= %s AND ub.tstamp <= %s", + array("integer","integer","integer"), + array($a_user_id, $a_ts_from, $a_ts_to) + ); + $res = []; + while ($rec = $db->fetchAssoc($set)) { + $res[] = $rec; + } + return $res; + } + + + // + // PUBLISHING + // + + protected function prepareJson($a_url) + { + $verify = new stdClass(); + $verify->type = "hosted"; + $verify->url = $a_url; + + $recipient = new stdClass(); + $recipient->type = "email"; + $recipient->hashed = true; + $recipient->salt = ilBadgeHandler::getInstance()->getObiSalt(); + + // https://github.com/mozilla/openbadges-backpack/wiki/How-to-hash-&-salt-in-various-languages. + include_once "Services/Badge/classes/class.ilBadgeProfileGUI.php"; + $user = new ilObjUser($this->getUserId()); + $mail = $user->getPref(ilBadgeProfileGUI::BACKPACK_EMAIL); + if (!$mail) { + $mail = $user->getEmail(); + } + $recipient->identity = 'sha256$' . hash('sha256', $mail . $recipient->salt); + + // spec: should be locally unique + $unique_id = md5($this->getBadgeId() . "-" . $this->getUserId()); + + $json = new stdClass(); + $json->{"@context"} = "https://w3id.org/openbadges/v1"; + $json->type = "Assertion"; + $json->id = $a_url; + $json->uid = $unique_id; + $json->recipient = $recipient; + + include_once "Services/Badge/classes/class.ilBadge.php"; + $badge = new ilBadge($this->getBadgeId()); + $badge_url = $badge->getStaticUrl(); + + // created baked image + $baked_image = $this->getImagePath($badge); + if ($this->bakeImage($baked_image, $badge->getImagePath(), $a_url)) { + // path to url + $parts = explode("/", $a_url); + array_pop($parts); + $parts[] = basename($baked_image); + $json->image = implode("/", $parts); + } + + $json->issuedOn = $this->getTimestamp(); + $json->badge = $badge_url; + $json->verify = $verify; + + return $json; + } + + public function getImagePath(ilBadge $a_badge) + { + $json_path = ilBadgeHandler::getInstance()->getInstancePath($this); + $baked_path = dirname($json_path); + $baked_file = array_shift(explode(".", basename($json_path))); + + // get correct suffix from badge image + $suffix = strtolower(array_pop(explode(".", basename($a_badge->getImagePath())))); + return $baked_path . "/" . $baked_file . "." . $suffix; + } + + protected function bakeImage($a_baked_image_path, $a_badge_image_path, $a_assertion_url) + { + $suffix = strtolower(array_pop(explode(".", basename($a_badge_image_path)))); + if ($suffix == "png") { + // using chamilo baker lib + include_once "Services/Badge/lib/baker.lib.php"; + $png = new PNGImageBaker(file_get_contents($a_badge_image_path)); + + // add payload + if ($png->checkChunks("tEXt", "openbadges")) { + $baked = $png->addChunk("tEXt", "openbadges", $a_assertion_url); + } + + // create baked file + if (!file_exists($a_baked_image_path)) { + file_put_contents($a_baked_image_path, $baked); + } + + // verify file + $verify = $png->extractBadgeInfo(file_get_contents($a_baked_image_path)); + if (is_array($verify)) { + return true; + } + } elseif ($suffix == "svg") { + // :TODO: not really sure if this is correct + $svg = simplexml_load_file($a_badge_image_path); + $ass = $svg->addChild("openbadges:assertion", "", "http://openbadges.org"); + $ass->addAttribute("verify", $a_assertion_url); + $baked = $svg->asXML(); + + // create baked file + if (!file_exists($a_baked_image_path)) { + file_put_contents($a_baked_image_path, $baked); + } + + return true; + } + + return false; + } + + public function getStaticUrl() + { + include_once("./Services/Badge/classes/class.ilBadgeHandler.php"); + $path = ilBadgeHandler::getInstance()->getInstancePath($this); + + $url = ILIAS_HTTP_PATH . substr($path, 1); + + if (!file_exists($path)) { + $json = json_encode($this->prepareJson($url)); + file_put_contents($path, $json); + } + + return $url; + } + + public function deleteStaticFiles() + { + // remove instance files + include_once("./Services/Badge/classes/class.ilBadgeHandler.php"); + $path = ilBadgeHandler::getInstance()->getInstancePath($this); + $path = str_replace(".json", ".*", $path); + array_map("unlink", glob($path)); + } + + public static function clearBadgeCache($a_user_id) + { + foreach (self::getInstancesByUserId($a_user_id) as $ass) { + $ass->deleteStaticFiles(); + } + } +} diff --git a/Services/Badge/classes/class.ilBadgeBackpack.php b/Services/Badge/classes/class.ilBadgeBackpack.php index 8d42c6dafaae09170971fd2b6c870e6b00d030f8..8f18dc22119a0d310b5516438a8f3648296fd71b 100644 --- a/Services/Badge/classes/class.ilBadgeBackpack.php +++ b/Services/Badge/classes/class.ilBadgeBackpack.php @@ -3,7 +3,7 @@ /** * Class ilBadgeBackpack - * + * * @author Jörg Lützenkirchen * @version $Id:$ * @@ -11,147 +11,133 @@ */ class ilBadgeBackpack { - protected $email; // [string] - protected $uid; // [int] - - const URL_DISPLAYER = "https://backpack.openbadges.org/displayer/"; - - public function __construct($a_email) - { - $this->email = $a_email; - } - - protected function authenticate() - { - $json = $this->sendRequest( - self::URL_DISPLAYER."convert/email", - array("email"=>$this->email), - true - ); - - if(!isset($json->status) || - $json->status != "okay") - { - return false; - } - - $this->uid = $json->userId; - return true; - } - - public function getGroups() - { - if($this->authenticate()) - { - $json = $this->sendRequest( - self::URL_DISPLAYER.$this->uid."/groups.json" - ); - - $result = array(); - - foreach($json->groups as $group) - { - $result[$group->groupId] = array( - "title" => $group->name, - "size" => $group->badges - ); - } - - return $result; - } - } - - public function getBadges($a_group_id) - { - if($this->authenticate()) - { - $json = $this->sendRequest( - self::URL_DISPLAYER.$this->uid."/group/".$a_group_id.".json" - ); - - if($json->status && - $json->status == "missing") - { - return false; - } - - $result = array(); - - foreach($json->badges as $raw) - { - $badge = $raw->assertion->badge; - - // :TODO: not sure if this works reliably - $issued_on = is_numeric($raw->assertion->issued_on) - ? $raw->assertion->issued_on - : strtotime($raw->assertion->issued_on); - - $result[] = array( - "title" => $badge->name, - "description" => $badge->description, - "image_url" => $badge->image, - "criteria_url" => $badge->criteria, - "issuer_name" => $badge->issuer->name, - "issuer_url" => $badge->issuer->origin, - "issued_on" => new ilDate($issued_on, IL_CAL_UNIX) - ); - } - - return $result; - } - } - - protected function sendRequest($a_url, array $a_param = array(), $a_is_post = false) - { - try - { - include_once "Services/WebServices/Curl/classes/class.ilCurlConnection.php"; - $curl = new ilCurlConnection(); - $curl->init(); - - $curl->setOpt(CURLOPT_FRESH_CONNECT, true); - $curl->setOpt(CURLOPT_RETURNTRANSFER, true); - $curl->setOpt(CURLOPT_FORBID_REUSE, true); - $curl->setOpt(CURLOPT_HEADER, 0); - $curl->setOpt(CURLOPT_CONNECTTIMEOUT, 3); - $curl->setOpt(CURLOPT_POSTREDIR, 3); - - // :TODO: SSL problems on test server - $curl->setOpt(CURLOPT_SSL_VERIFYPEER, false); + protected $email; // [string] + protected $uid; // [int] + + const URL_DISPLAYER = "https://backpack.openbadges.org/displayer/"; + + public function __construct($a_email) + { + $this->email = $a_email; + } + + protected function authenticate() + { + $json = $this->sendRequest( + self::URL_DISPLAYER . "convert/email", + array("email"=>$this->email), + true + ); + + if (!isset($json->status) || + $json->status != "okay") { + return false; + } + + $this->uid = $json->userId; + return true; + } + + public function getGroups() + { + if ($this->authenticate()) { + $json = $this->sendRequest( + self::URL_DISPLAYER . $this->uid . "/groups.json" + ); + + $result = array(); + + foreach ($json->groups as $group) { + $result[$group->groupId] = array( + "title" => $group->name, + "size" => $group->badges + ); + } + + return $result; + } + } + + public function getBadges($a_group_id) + { + if ($this->authenticate()) { + $json = $this->sendRequest( + self::URL_DISPLAYER . $this->uid . "/group/" . $a_group_id . ".json" + ); + + if ($json->status && + $json->status == "missing") { + return false; + } + + $result = array(); + + foreach ($json->badges as $raw) { + $badge = $raw->assertion->badge; + + // :TODO: not sure if this works reliably + $issued_on = is_numeric($raw->assertion->issued_on) + ? $raw->assertion->issued_on + : strtotime($raw->assertion->issued_on); + + $result[] = array( + "title" => $badge->name, + "description" => $badge->description, + "image_url" => $badge->image, + "criteria_url" => $badge->criteria, + "issuer_name" => $badge->issuer->name, + "issuer_url" => $badge->issuer->origin, + "issued_on" => new ilDate($issued_on, IL_CAL_UNIX) + ); + } + + return $result; + } + } + + protected function sendRequest($a_url, array $a_param = array(), $a_is_post = false) + { + try { + include_once "Services/WebServices/Curl/classes/class.ilCurlConnection.php"; + $curl = new ilCurlConnection(); + $curl->init(); + + $curl->setOpt(CURLOPT_FRESH_CONNECT, true); + $curl->setOpt(CURLOPT_RETURNTRANSFER, true); + $curl->setOpt(CURLOPT_FORBID_REUSE, true); + $curl->setOpt(CURLOPT_HEADER, 0); + $curl->setOpt(CURLOPT_CONNECTTIMEOUT, 3); + $curl->setOpt(CURLOPT_POSTREDIR, 3); + + // :TODO: SSL problems on test server + $curl->setOpt(CURLOPT_SSL_VERIFYPEER, false); - $curl->setOpt(CURLOPT_HTTPHEADER, array( - "Accept: application/json", - "Expect:" - )); + $curl->setOpt(CURLOPT_HTTPHEADER, array( + "Accept: application/json", + "Expect:" + )); - if((bool)$a_is_post) - { - $curl->setOpt(CURLOPT_POST, 1); - if(sizeof($a_param)) - { - $curl->setOpt(CURLOPT_POSTFIELDS, http_build_query($a_param)); - } - } - else - { - $curl->setOpt(CURLOPT_HTTPGET, 1); - if(sizeof($a_param)) - { - $a_url = $a_url. - (strpos($a_url, "?") === false ? "?" : ""). - http_build_query($a_param); - } - } - $curl->setOpt(CURLOPT_URL, $a_url); + if ((bool) $a_is_post) { + $curl->setOpt(CURLOPT_POST, 1); + if (sizeof($a_param)) { + $curl->setOpt(CURLOPT_POSTFIELDS, http_build_query($a_param)); + } + } else { + $curl->setOpt(CURLOPT_HTTPGET, 1); + if (sizeof($a_param)) { + $a_url = $a_url . + (strpos($a_url, "?") === false ? "?" : "") . + http_build_query($a_param); + } + } + $curl->setOpt(CURLOPT_URL, $a_url); - $answer = $curl->exec(); - } - catch (Exception $ex) - { - ilUtil::sendFailure($ex->getMessage()); - return; - } - - return json_decode($answer); - } -} \ No newline at end of file + $answer = $curl->exec(); + } catch (Exception $ex) { + ilUtil::sendFailure($ex->getMessage()); + return; + } + + return json_decode($answer); + } +} diff --git a/Services/Badge/classes/class.ilBadgeGlobalScreenProvider.php b/Services/Badge/classes/class.ilBadgeGlobalScreenProvider.php index cc46c5580781831c6da7d6f886e8f606ad233955..2345db467f27f2c1f95099d815e6fa9fc91168c6 100644 --- a/Services/Badge/classes/class.ilBadgeGlobalScreenProvider.php +++ b/Services/Badge/classes/class.ilBadgeGlobalScreenProvider.php @@ -8,55 +8,60 @@ use ILIAS\GlobalScreen\Scope\MainMenu\Provider\AbstractStaticMainMenuProvider; * * @author Fabian Schmid */ -class ilBadgeGlobalScreenProvider extends AbstractStaticMainMenuProvider { - - /** - * @var IdentificationInterface - */ - protected $top_item; - - - public function __construct(\ILIAS\DI\Container $dic) { - parent::__construct($dic); - $this->top_item = (new ilPDGlobalScreenProvider($dic))->getTopItem(); - } - - - /** - * Some other components want to provide Items for the main menu which are - * located at the PD TopTitem by default. Therefore we have to provide our - * TopTitem Identification for others - * - * @return IdentificationInterface - */ - public function getTopItem(): IdentificationInterface { - return $this->top_item; - } - - - /** - * @inheritDoc - */ - public function getStaticTopItems(): array { - return []; - } - - - /** - * @inheritDoc - */ - public function getStaticSubItems(): array { - return []; - /* - return [$this->mainmenu->link($this->if->identifier('mm_pd_badges')) - ->withTitle($this->dic->language()->txt("obj_bdga")) - ->withAction("ilias.php?baseClass=ilPersonalDesktopGUI&cmd=jumpToBadges") - ->withParent($this->getTopItem()) - ->withNonAvailableReason($this->dic->ui()->factory()->legacy("{$this->dic->language()->txt('component_not_active')}")) - ->withAvailableCallable( - function () { - return (bool)(ilBadgeHandler::getInstance()->isActive()); - } - )];*/ - } +class ilBadgeGlobalScreenProvider extends AbstractStaticMainMenuProvider +{ + + /** + * @var IdentificationInterface + */ + protected $top_item; + + + public function __construct(\ILIAS\DI\Container $dic) + { + parent::__construct($dic); + $this->top_item = (new ilPDGlobalScreenProvider($dic))->getTopItem(); + } + + + /** + * Some other components want to provide Items for the main menu which are + * located at the PD TopTitem by default. Therefore we have to provide our + * TopTitem Identification for others + * + * @return IdentificationInterface + */ + public function getTopItem() : IdentificationInterface + { + return $this->top_item; + } + + + /** + * @inheritDoc + */ + public function getStaticTopItems() : array + { + return []; + } + + + /** + * @inheritDoc + */ + public function getStaticSubItems() : array + { + return []; + /* + return [$this->mainmenu->link($this->if->identifier('mm_pd_badges')) + ->withTitle($this->dic->language()->txt("obj_bdga")) + ->withAction("ilias.php?baseClass=ilPersonalDesktopGUI&cmd=jumpToBadges") + ->withParent($this->getTopItem()) + ->withNonAvailableReason($this->dic->ui()->factory()->legacy("{$this->dic->language()->txt('component_not_active')}")) + ->withAvailableCallable( + function () { + return (bool)(ilBadgeHandler::getInstance()->isActive()); + } + )];*/ + } } diff --git a/Services/Badge/classes/class.ilBadgeHandler.php b/Services/Badge/classes/class.ilBadgeHandler.php index 78b1653f3269e5d0a7e30adf5aa4934317913a95..0c97439aa31c4cc85018922165a0ff95b0261731 100644 --- a/Services/Badge/classes/class.ilBadgeHandler.php +++ b/Services/Badge/classes/class.ilBadgeHandler.php @@ -3,7 +3,7 @@ /** * Class ilBadgeHandler - * + * * @author Jörg Lützenkirchen * @version $Id:$ * @@ -11,675 +11,623 @@ */ class ilBadgeHandler { - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; - /** - * @var ilTree - */ - protected $tree; + /** + * @var ilTree + */ + protected $tree; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - protected $settings; // [ilSetting] - - protected static $instance; // [ilBadgeHandler] - - /** - * Constructor - * - * @return self - */ - protected function __construct() - { - global $DIC; + protected $settings; // [ilSetting] + + protected static $instance; // [ilBadgeHandler] + + /** + * Constructor + * + * @return self + */ + protected function __construct() + { + global $DIC; - $this->db = $DIC->database(); - if (isset($DIC["tree"])) - { - $this->tree = $DIC->repositoryTree(); - } - $this->settings = new ilSetting("bdga"); - } - - /** - * Constructor - * - * @return self - */ - public static function getInstance() - { - if(!self::$instance) - { - self::$instance = new self(); - } - return self::$instance; - } - - - // - // setter/getter - // - - public function isActive() - { - return $this->settings->get("active", false); - } - - public function setActive($a_value) - { - $this->settings->set("active", (bool)$a_value); - } - - public function isObiActive() - { - // see bug #20124 - return false; + $this->db = $DIC->database(); + if (isset($DIC["tree"])) { + $this->tree = $DIC->repositoryTree(); + } + $this->settings = new ilSetting("bdga"); + } + + /** + * Constructor + * + * @return self + */ + public static function getInstance() + { + if (!self::$instance) { + self::$instance = new self(); + } + return self::$instance; + } + + + // + // setter/getter + // + + public function isActive() + { + return $this->settings->get("active", false); + } + + public function setActive($a_value) + { + $this->settings->set("active", (bool) $a_value); + } + + public function isObiActive() + { + // see bug #20124 + return false; - return $this->settings->get("obi_active", false); - } - - public function setObiActive($a_value) - { - $this->settings->set("obi_active", (bool)$a_value); - } - - public function getObiOrganistation() - { - return $this->settings->get("obi_organisation", null); - } - - public function setObiOrganisation($a_value) - { - $this->settings->set("obi_organisation", trim($a_value)); - } - - public function getObiContact() - { - return $this->settings->get("obi_contact", null); - } - - public function setObiContact($a_value) - { - $this->settings->set("obi_contact", trim($a_value)); - } - - public function getObiSalt() - { - return $this->settings->get("obi_salt", null); - } - - public function setObiSalt($a_value) - { - $this->settings->set("obi_salt", trim($a_value)); - } - - public function getComponents() - { - $components = $this->settings->get("components", null); - if($components) - { - return unserialize($components); - } - return array(); - } - - public function setComponents(array $a_components = null) - { - if(is_array($a_components) && - !sizeof($a_components)) - { - $a_components = null; - } - $this->settings->set("components", $a_components !== null - ? serialize(array_unique($a_components)) - : null); - } - - - // - // component handling - // - - protected function getComponent($a_id) - { - $ilDB = $this->db; - - // see ilCtrl - $set = $ilDB->query("SELECT * FROM il_component". - " WHERE id = ".$ilDB->quote($a_id, "text")); - $rec = $ilDB->fetchAssoc($set); - if($rec["type"]) - { - return $rec; - } - } - - /** - * Get provider instance - * - * @param string $a_component_id - * @return ilBadgeProvider - */ - public function getProviderInstance($a_component_id) - { - $comp = $this->getComponent($a_component_id); - if($comp) - { - $class = "il".$comp["name"]."BadgeProvider"; - $file = $comp["type"]."/".$comp["name"]."/classes/class.".$class.".php"; - if(file_exists($file)) - { - include_once $file; - $obj = new $class; - if($obj instanceof ilBadgeProvider) - { - return $obj; - } - } - } - } - - public function getComponentCaption($a_component_id) - { - $comp = $this->getComponent($a_component_id); - if($comp) - { - return $comp["type"]."/".$comp["name"]; - } - } - - // - // types - // - - public function getUniqueTypeId($a_component_id, ilBadgeType $a_badge) - { - return $a_component_id."/".$a_badge->getId(); - } - - /** - * Get type instance by unique id (component, type) - * @param string $a_id - * @return ilBadgeType - */ - public function getTypeInstanceByUniqueId($a_id) - { - $parts = explode("/", $a_id); - $comp_id = $parts[0]; - $type_id = $parts[1]; - $provider = $this->getProviderInstance($comp_id); - if($provider) - { - foreach($provider->getBadgeTypes() as $type) - { - if($type->getId() == $type_id) - { - return $type; - } - } - } - } - - public function getInactiveTypes() - { - $types = $this->settings->get("inactive_types", null); - if($types) - { - return unserialize($types); - } - return array(); - } - - public function setInactiveTypes(array $a_types = null) - { - if(is_array($a_types) && - !sizeof($a_types)) - { - $a_types = null; - } - $this->settings->set("inactive_types", $a_types !== null - ? serialize(array_unique($a_types)) - : null); - } - - /** - * Get badges types - * - * @return ilBadgeType[] - */ - public function getAvailableTypes() - { - $res = array(); - - $inactive = $this->getInactiveTypes(); - foreach($this->getComponents() as $component_id) - { - $provider = $this->getProviderInstance($component_id); - if($provider) - { - foreach($provider->getBadgeTypes() as $type) - { - $id = $this->getUniqueTypeId($component_id, $type); - if(!in_array($id, $inactive)) - { - $res[$id] = $type; - } - } - } - } + return $this->settings->get("obi_active", false); + } + + public function setObiActive($a_value) + { + $this->settings->set("obi_active", (bool) $a_value); + } + + public function getObiOrganistation() + { + return $this->settings->get("obi_organisation", null); + } + + public function setObiOrganisation($a_value) + { + $this->settings->set("obi_organisation", trim($a_value)); + } + + public function getObiContact() + { + return $this->settings->get("obi_contact", null); + } + + public function setObiContact($a_value) + { + $this->settings->set("obi_contact", trim($a_value)); + } + + public function getObiSalt() + { + return $this->settings->get("obi_salt", null); + } + + public function setObiSalt($a_value) + { + $this->settings->set("obi_salt", trim($a_value)); + } + + public function getComponents() + { + $components = $this->settings->get("components", null); + if ($components) { + return unserialize($components); + } + return array(); + } + + public function setComponents(array $a_components = null) + { + if (is_array($a_components) && + !sizeof($a_components)) { + $a_components = null; + } + $this->settings->set("components", $a_components !== null + ? serialize(array_unique($a_components)) + : null); + } + + + // + // component handling + // + + protected function getComponent($a_id) + { + $ilDB = $this->db; + + // see ilCtrl + $set = $ilDB->query("SELECT * FROM il_component" . + " WHERE id = " . $ilDB->quote($a_id, "text")); + $rec = $ilDB->fetchAssoc($set); + if ($rec["type"]) { + return $rec; + } + } + + /** + * Get provider instance + * + * @param string $a_component_id + * @return ilBadgeProvider + */ + public function getProviderInstance($a_component_id) + { + $comp = $this->getComponent($a_component_id); + if ($comp) { + $class = "il" . $comp["name"] . "BadgeProvider"; + $file = $comp["type"] . "/" . $comp["name"] . "/classes/class." . $class . ".php"; + if (file_exists($file)) { + include_once $file; + $obj = new $class; + if ($obj instanceof ilBadgeProvider) { + return $obj; + } + } + } + } + + public function getComponentCaption($a_component_id) + { + $comp = $this->getComponent($a_component_id); + if ($comp) { + return $comp["type"] . "/" . $comp["name"]; + } + } + + // + // types + // + + public function getUniqueTypeId($a_component_id, ilBadgeType $a_badge) + { + return $a_component_id . "/" . $a_badge->getId(); + } + + /** + * Get type instance by unique id (component, type) + * @param string $a_id + * @return ilBadgeType + */ + public function getTypeInstanceByUniqueId($a_id) + { + $parts = explode("/", $a_id); + $comp_id = $parts[0]; + $type_id = $parts[1]; + $provider = $this->getProviderInstance($comp_id); + if ($provider) { + foreach ($provider->getBadgeTypes() as $type) { + if ($type->getId() == $type_id) { + return $type; + } + } + } + } + + public function getInactiveTypes() + { + $types = $this->settings->get("inactive_types", null); + if ($types) { + return unserialize($types); + } + return array(); + } + + public function setInactiveTypes(array $a_types = null) + { + if (is_array($a_types) && + !sizeof($a_types)) { + $a_types = null; + } + $this->settings->set("inactive_types", $a_types !== null + ? serialize(array_unique($a_types)) + : null); + } + + /** + * Get badges types + * + * @return ilBadgeType[] + */ + public function getAvailableTypes() + { + $res = array(); + + $inactive = $this->getInactiveTypes(); + foreach ($this->getComponents() as $component_id) { + $provider = $this->getProviderInstance($component_id); + if ($provider) { + foreach ($provider->getBadgeTypes() as $type) { + $id = $this->getUniqueTypeId($component_id, $type); + if (!in_array($id, $inactive)) { + $res[$id] = $type; + } + } + } + } - return $res; - } - - /** - * Get valid badges types for object type - * - * @param string $a_object_type - * @return ilBadgeType[] - */ - public function getAvailableTypesForObjType($a_object_type) - { - $res = array(); - - foreach($this->getAvailableTypes() as $id => $type) - { - if(in_array($a_object_type, $type->getValidObjectTypes())) - { - $res[$id] = $type; - } - } - - return $res; - } - - /** - * Get available manual badges for object id - * - * @param int $a_parent_obj_id - * @param string $a_parent_obj_type - * @return array id,title - */ - public function getAvailableManualBadges($a_parent_obj_id, $a_parent_obj_type = null) - { - $res = array(); - - if(!$a_parent_obj_type) - { - $a_parent_obj_type = ilObject::_lookupType($a_parent_obj_id); - } - - include_once "./Services/Badge/classes/class.ilBadge.php"; - $badges = ilBadge::getInstancesByParentId($a_parent_obj_id); - foreach(ilBadgeHandler::getInstance()->getAvailableTypesForObjType($a_parent_obj_type) as $type_id => $type) - { - if(!$type instanceof ilBadgeAuto) - { - foreach($badges as $badge) - { - if($badge->getTypeId() == $type_id && - $badge->isActive()) - { - $res[$badge->getId()] = $badge->getTitle(); - } - } - } - } - - asort($res); - return $res; - } - - - - // - // service/module definition - // - - /** - * Import component definition - * - * @param string $a_component_id - */ - public static function updateFromXML($a_component_id) - { - $handler = self::getInstance(); - $components = $handler->getComponents(); - $components[] = $a_component_id; - $handler->setComponents($components); - } - - /** - * Remove component definition - * - * @param string $a_component_id - */ - public static function clearFromXML($a_component_id) - { - $handler = self::getInstance(); - $components = $handler->getComponents(); - foreach($components as $idx => $component) - { - if($component == $a_component_id) - { - unset($components[$idx]); - } - } - $handler->setComponents($components); - } - - - // - // helper - // - - public function isObjectActive($a_obj_id, $a_obj_type = null) - { - if(!$this->isActive()) - { - return false; - } - - if(!$a_obj_type) - { - $a_obj_type = ilObject::_lookupType($a_obj_id); - } + return $res; + } + + /** + * Get valid badges types for object type + * + * @param string $a_object_type + * @return ilBadgeType[] + */ + public function getAvailableTypesForObjType($a_object_type) + { + $res = array(); + + foreach ($this->getAvailableTypes() as $id => $type) { + if (in_array($a_object_type, $type->getValidObjectTypes())) { + $res[$id] = $type; + } + } + + return $res; + } + + /** + * Get available manual badges for object id + * + * @param int $a_parent_obj_id + * @param string $a_parent_obj_type + * @return array id,title + */ + public function getAvailableManualBadges($a_parent_obj_id, $a_parent_obj_type = null) + { + $res = array(); + + if (!$a_parent_obj_type) { + $a_parent_obj_type = ilObject::_lookupType($a_parent_obj_id); + } + + include_once "./Services/Badge/classes/class.ilBadge.php"; + $badges = ilBadge::getInstancesByParentId($a_parent_obj_id); + foreach (ilBadgeHandler::getInstance()->getAvailableTypesForObjType($a_parent_obj_type) as $type_id => $type) { + if (!$type instanceof ilBadgeAuto) { + foreach ($badges as $badge) { + if ($badge->getTypeId() == $type_id && + $badge->isActive()) { + $res[$badge->getId()] = $badge->getTitle(); + } + } + } + } + + asort($res); + return $res; + } + + + + // + // service/module definition + // + + /** + * Import component definition + * + * @param string $a_component_id + */ + public static function updateFromXML($a_component_id) + { + $handler = self::getInstance(); + $components = $handler->getComponents(); + $components[] = $a_component_id; + $handler->setComponents($components); + } + + /** + * Remove component definition + * + * @param string $a_component_id + */ + public static function clearFromXML($a_component_id) + { + $handler = self::getInstance(); + $components = $handler->getComponents(); + foreach ($components as $idx => $component) { + if ($component == $a_component_id) { + unset($components[$idx]); + } + } + $handler->setComponents($components); + } + + + // + // helper + // + + public function isObjectActive($a_obj_id, $a_obj_type = null) + { + if (!$this->isActive()) { + return false; + } + + if (!$a_obj_type) { + $a_obj_type = ilObject::_lookupType($a_obj_id); + } - if($a_obj_type != "bdga") - { - include_once 'Services/Container/classes/class.ilContainer.php'; - include_once 'Services/Object/classes/class.ilObjectServiceSettingsGUI.php'; - if(!ilContainer::_lookupContainerSetting( - $a_obj_id, - ilObjectServiceSettingsGUI::BADGES, - false)) - { - return false; - } - } - - return true; - } - - public function triggerEvaluation($a_type_id, $a_user_id, array $a_params = null) - { - if(!$this->isActive() || - in_array($a_type_id, $this->getInactiveTypes())) - { - return; - } - - $type = $this->getTypeInstanceByUniqueId($a_type_id); - if(!$type || - !$type instanceof ilBadgeAuto) - { - return; - } - - include_once "Services/Badge/classes/class.ilBadge.php"; - include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; - $new_badges = array(); - foreach(ilBadge::getInstancesByType($a_type_id) as $badge) - { - if($badge->isActive()) - { - // already assigned? - if(!ilBadgeAssignment::exists($badge->getId(), $a_user_id)) - { - if((bool)$type->evaluate($a_user_id, (array)$a_params, (array)$badge->getConfiguration())) - { - $ass = new ilBadgeAssignment($badge->getId(), $a_user_id); - $ass->store(); - - $new_badges[$a_user_id][] = $badge->getId(); - } - } - } - } - - $this->sendNotification($new_badges); - } - - public function getUserIds($a_parent_ref_id, $a_parent_obj_id = null, $a_parent_type = null) - { - $tree = $this->tree; - - if(!$a_parent_obj_id) - { - $a_parent_obj_id = ilObject::_lookupObjectId($a_parent_ref_id); - } - if(!$a_parent_type) - { - $a_parent_type = ilObject::_lookupType($a_parent_obj_id); - } - - // try to get participants from (parent) course/group - switch($a_parent_type) - { - case "crs": - include_once "Modules/Course/classes/class.ilCourseParticipants.php"; - $member_obj = ilCourseParticipants::_getInstanceByObjId($a_parent_obj_id); - return $member_obj->getMembers(); + if ($a_obj_type != "bdga") { + include_once 'Services/Container/classes/class.ilContainer.php'; + include_once 'Services/Object/classes/class.ilObjectServiceSettingsGUI.php'; + if (!ilContainer::_lookupContainerSetting( + $a_obj_id, + ilObjectServiceSettingsGUI::BADGES, + false + )) { + return false; + } + } + + return true; + } + + public function triggerEvaluation($a_type_id, $a_user_id, array $a_params = null) + { + if (!$this->isActive() || + in_array($a_type_id, $this->getInactiveTypes())) { + return; + } + + $type = $this->getTypeInstanceByUniqueId($a_type_id); + if (!$type || + !$type instanceof ilBadgeAuto) { + return; + } + + include_once "Services/Badge/classes/class.ilBadge.php"; + include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; + $new_badges = array(); + foreach (ilBadge::getInstancesByType($a_type_id) as $badge) { + if ($badge->isActive()) { + // already assigned? + if (!ilBadgeAssignment::exists($badge->getId(), $a_user_id)) { + if ((bool) $type->evaluate($a_user_id, (array) $a_params, (array) $badge->getConfiguration())) { + $ass = new ilBadgeAssignment($badge->getId(), $a_user_id); + $ass->store(); + + $new_badges[$a_user_id][] = $badge->getId(); + } + } + } + } + + $this->sendNotification($new_badges); + } + + public function getUserIds($a_parent_ref_id, $a_parent_obj_id = null, $a_parent_type = null) + { + $tree = $this->tree; + + if (!$a_parent_obj_id) { + $a_parent_obj_id = ilObject::_lookupObjectId($a_parent_ref_id); + } + if (!$a_parent_type) { + $a_parent_type = ilObject::_lookupType($a_parent_obj_id); + } + + // try to get participants from (parent) course/group + switch ($a_parent_type) { + case "crs": + include_once "Modules/Course/classes/class.ilCourseParticipants.php"; + $member_obj = ilCourseParticipants::_getInstanceByObjId($a_parent_obj_id); + return $member_obj->getMembers(); - case "grp": - include_once "Modules/Group/classes/class.ilGroupParticipants.php"; - $member_obj = ilGroupParticipants::_getInstanceByObjId($a_parent_obj_id); - return $member_obj->getMembers(); - - default: - // walk path to find course or group object and use members of that object - $path = $tree->getPathId($a_parent_ref_id); - array_pop($path); - foreach(array_reverse($path) as $path_ref_id) - { - $type = ilObject::_lookupType($path_ref_id, true); - if($type == "crs" || $type == "grp") - { - return $this->getParticipantsForObject($path_ref_id, null, $type); - } - } - break; - } - } - - - // - // PATH HANDLING (PUBLISHING) - // - - protected function getBasePath() - { - return ilUtil::getWebspaceDir()."/pub_badges/"; - } - - public function getInstancePath(ilBadgeAssignment $a_ass) - { - $hash = md5($a_ass->getBadgeId()."_".$a_ass->getUserId()); - - $path = $this->getBasePath()."instances/". - $a_ass->getBadgeId()."/". - floor($a_ass->getUserId()/1000)."/"; - - ilUtil::makeDirParents($path); - - $path .= $hash.".json"; - - return $path; - } + case "grp": + include_once "Modules/Group/classes/class.ilGroupParticipants.php"; + $member_obj = ilGroupParticipants::_getInstanceByObjId($a_parent_obj_id); + return $member_obj->getMembers(); + + default: + // walk path to find course or group object and use members of that object + $path = $tree->getPathId($a_parent_ref_id); + array_pop($path); + foreach (array_reverse($path) as $path_ref_id) { + $type = ilObject::_lookupType($path_ref_id, true); + if ($type == "crs" || $type == "grp") { + return $this->getParticipantsForObject($path_ref_id, null, $type); + } + } + break; + } + } + + + // + // PATH HANDLING (PUBLISHING) + // + + protected function getBasePath() + { + return ilUtil::getWebspaceDir() . "/pub_badges/"; + } + + public function getInstancePath(ilBadgeAssignment $a_ass) + { + $hash = md5($a_ass->getBadgeId() . "_" . $a_ass->getUserId()); + + $path = $this->getBasePath() . "instances/" . + $a_ass->getBadgeId() . "/" . + floor($a_ass->getUserId()/1000) . "/"; + + ilUtil::makeDirParents($path); + + $path .= $hash . ".json"; + + return $path; + } - public function countStaticBadgeInstances(ilBadge $a_badge) - { - $path = $this->getBasePath()."instances/".$a_badge->getId(); - $cnt = 0; - if(is_dir($path)) - { - $this->countStaticBadgeInstancesHelper($cnt, $path); - } - return $cnt; - } - - protected function countStaticBadgeInstancesHelper(&$a_cnt, $a_path) - { - foreach(glob($a_path."/*") as $item) - { - if(is_dir($item)) - { - $this->countStaticBadgeInstancesHelper($a_cnt, $item); - } - else if(substr($item, -5) == ".json") - { - $a_cnt++; - } - } - } - - public function getBadgePath(ilBadge $a_badge) - { - $hash = md5($a_badge->getId()); - - $path = $this->getBasePath()."badges/". - floor($a_badge->getId()/100)."/". - $hash."/"; - - ilUtil::makeDirParents($path); - - return $path; - } - - protected function prepareIssuerJson($a_url) - { - $json = new stdClass(); - $json->{"@context"} = "https://w3id.org/openbadges/v1"; - $json->type = "Issuer"; - $json->id = $a_url; - $json->name = $this->getObiOrganistation(); - $json->url = ILIAS_HTTP_PATH."/"; - $json->email = $this->getObiContact(); - - return $json; - } - - public function getIssuerStaticUrl() - { - $path = $this->getBasePath()."issuer/"; - ilUtil::makeDirParents($path); - $path .= "issuer.json"; - - $url = ILIAS_HTTP_PATH.substr($path, 1); - - if(!file_exists($path)) - { - $json = json_encode($this->prepareIssuerJson($url)); - file_put_contents($path, $json); - } - - return $url; - } - - public function rebuildIssuerStaticUrl() - { - $path = $this->getBasePath()."issuer/issuer.json"; - if(file_exists($path)) - { - unlink($path); - } - $this->getIssuerStaticUrl(); - } - - - // - // notification - // - - public function sendNotification(array $a_user_map, $a_parent_ref_id = null) - { - $badges = array(); - - include_once "Services/Badge/classes/class.ilBadge.php"; - include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; - include_once "Services/Notification/classes/class.ilSystemNotification.php"; - include_once "Services/Link/classes/class.ilLink.php"; - - foreach($a_user_map as $user_id => $badge_ids) - { - $user_badges = array(); - - foreach($badge_ids as $badge_id) - { - // making extra sure - if(!ilBadgeAssignment::exists($badge_id, $user_id)) - { - continue; - } - - if(!array_key_exists($badge_id, $badges)) - { - $badges[$badge_id] = new ilBadge($badge_id); - } - - $badge = $badges[$badge_id]; - - $user_badges[] = $badge->getTitle(); - } - - if(sizeof($user_badges)) - { - // compose and send mail - - $ntf = new ilSystemNotification(false); - $ntf->setLangModules(array("badge")); - - $ntf->setRefId($a_parent_ref_id); - $ntf->setGotoLangId("badge_notification_parent_goto"); - - // user specific language - $lng = $ntf->getUserLanguage($user_id); - - $ntf->setIntroductionLangId("badge_notification_body"); - - $ntf->addAdditionalInfo("badge_notification_badges", implode("\n", $user_badges), true); - - $url = ilLink::_getLink($user_id, "usr", array(), "_bdg"); - $ntf->addAdditionalInfo("badge_notification_badges_goto", $url); - - $ntf->setReasonLangId("badge_notification_reason"); + public function countStaticBadgeInstances(ilBadge $a_badge) + { + $path = $this->getBasePath() . "instances/" . $a_badge->getId(); + $cnt = 0; + if (is_dir($path)) { + $this->countStaticBadgeInstancesHelper($cnt, $path); + } + return $cnt; + } + + protected function countStaticBadgeInstancesHelper(&$a_cnt, $a_path) + { + foreach (glob($a_path . "/*") as $item) { + if (is_dir($item)) { + $this->countStaticBadgeInstancesHelper($a_cnt, $item); + } elseif (substr($item, -5) == ".json") { + $a_cnt++; + } + } + } + + public function getBadgePath(ilBadge $a_badge) + { + $hash = md5($a_badge->getId()); + + $path = $this->getBasePath() . "badges/" . + floor($a_badge->getId()/100) . "/" . + $hash . "/"; + + ilUtil::makeDirParents($path); + + return $path; + } + + protected function prepareIssuerJson($a_url) + { + $json = new stdClass(); + $json->{"@context"} = "https://w3id.org/openbadges/v1"; + $json->type = "Issuer"; + $json->id = $a_url; + $json->name = $this->getObiOrganistation(); + $json->url = ILIAS_HTTP_PATH . "/"; + $json->email = $this->getObiContact(); + + return $json; + } + + public function getIssuerStaticUrl() + { + $path = $this->getBasePath() . "issuer/"; + ilUtil::makeDirParents($path); + $path .= "issuer.json"; + + $url = ILIAS_HTTP_PATH . substr($path, 1); + + if (!file_exists($path)) { + $json = json_encode($this->prepareIssuerJson($url)); + file_put_contents($path, $json); + } + + return $url; + } + + public function rebuildIssuerStaticUrl() + { + $path = $this->getBasePath() . "issuer/issuer.json"; + if (file_exists($path)) { + unlink($path); + } + $this->getIssuerStaticUrl(); + } + + + // + // notification + // + + public function sendNotification(array $a_user_map, $a_parent_ref_id = null) + { + $badges = array(); + + include_once "Services/Badge/classes/class.ilBadge.php"; + include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; + include_once "Services/Notification/classes/class.ilSystemNotification.php"; + include_once "Services/Link/classes/class.ilLink.php"; + + foreach ($a_user_map as $user_id => $badge_ids) { + $user_badges = array(); + + foreach ($badge_ids as $badge_id) { + // making extra sure + if (!ilBadgeAssignment::exists($badge_id, $user_id)) { + continue; + } + + if (!array_key_exists($badge_id, $badges)) { + $badges[$badge_id] = new ilBadge($badge_id); + } + + $badge = $badges[$badge_id]; + + $user_badges[] = $badge->getTitle(); + } + + if (sizeof($user_badges)) { + // compose and send mail + + $ntf = new ilSystemNotification(false); + $ntf->setLangModules(array("badge")); + + $ntf->setRefId($a_parent_ref_id); + $ntf->setGotoLangId("badge_notification_parent_goto"); + + // user specific language + $lng = $ntf->getUserLanguage($user_id); + + $ntf->setIntroductionLangId("badge_notification_body"); + + $ntf->addAdditionalInfo("badge_notification_badges", implode("\n", $user_badges), true); + + $url = ilLink::_getLink($user_id, "usr", array(), "_bdg"); + $ntf->addAdditionalInfo("badge_notification_badges_goto", $url); + + $ntf->setReasonLangId("badge_notification_reason"); - // force email - $mail = new ilMail(ANONYMOUS_USER_ID); - $mail->enableSOAP(false); - $mail->sendMail(ilObjUser::_lookupEmail($user_id), - null, - null, - $lng->txt("badge_notification_subject"), - $ntf->composeAndGetMessage($user_id, null, "read", true), - null, - array("system")); - - - // osd - // bug #24562 - if (ilContext::hasHTML()) - { - $osd_params = array("badge_list" => "
" . implode("
", $user_badges)); + // force email + $mail = new ilMail(ANONYMOUS_USER_ID); + $mail->enableSOAP(false); + $mail->sendMail( + ilObjUser::_lookupEmail($user_id), + null, + null, + $lng->txt("badge_notification_subject"), + $ntf->composeAndGetMessage($user_id, null, "read", true), + null, + array("system") + ); + + + // osd + // bug #24562 + if (ilContext::hasHTML()) { + $osd_params = array("badge_list" => "
" . implode("
", $user_badges)); - require_once "Services/Notifications/classes/class.ilNotificationConfig.php"; - $notification = new ilNotificationConfig("osd_main"); - $notification->setTitleVar("badge_notification_subject", array(), "badge"); - $notification->setShortDescriptionVar("badge_notification_osd", $osd_params, "badge"); - $notification->setLongDescriptionVar("", $osd_params, ""); - $notification->setAutoDisable(false); - $notification->setLink($url); - $notification->setIconPath(ilUtil::getImagePath('icon_bdga.svg')); - $notification->setValidForSeconds(ilNotificationConfig::TTL_SHORT); - $notification->setVisibleForSeconds(ilNotificationConfig::DEFAULT_TTS); - $notification->notifyByUsers(array($user_id)); - } - } - } - } -} \ No newline at end of file + require_once "Services/Notifications/classes/class.ilNotificationConfig.php"; + $notification = new ilNotificationConfig("osd_main"); + $notification->setTitleVar("badge_notification_subject", array(), "badge"); + $notification->setShortDescriptionVar("badge_notification_osd", $osd_params, "badge"); + $notification->setLongDescriptionVar("", $osd_params, ""); + $notification->setAutoDisable(false); + $notification->setLink($url); + $notification->setIconPath(ilUtil::getImagePath('icon_bdga.svg')); + $notification->setValidForSeconds(ilNotificationConfig::TTL_SHORT); + $notification->setVisibleForSeconds(ilNotificationConfig::DEFAULT_TTS); + $notification->notifyByUsers(array($user_id)); + } + } + } + } +} diff --git a/Services/Badge/classes/class.ilBadgeHandlerGUI.php b/Services/Badge/classes/class.ilBadgeHandlerGUI.php index 44df1f2561a22907a4a922eeb998bbf02c2c383f..cf012380306978b9040ea09e514ed34d77e6f57d 100644 --- a/Services/Badge/classes/class.ilBadgeHandlerGUI.php +++ b/Services/Badge/classes/class.ilBadgeHandlerGUI.php @@ -3,50 +3,48 @@ /** * Class ilBadgeHandler - * + * * @author Jörg Lützenkirchen * @version $Id:$ * - * @ilCtrl_Calls ilBadgeHandlerGUI: + * @ilCtrl_Calls ilBadgeHandlerGUI: * @package ServicesBadge */ class ilBadgeHandlerGUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * Constructor - */ - function __construct() - { - global $DIC; + /** + * Constructor + */ + public function __construct() + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - } + $this->ctrl = $DIC->ctrl(); + } - public function executeCommand() - { - $ilCtrl = $this->ctrl; - - if($ilCtrl->isAsynch()) - { - $cmd = $ilCtrl->getCmd(); - echo $this->$cmd(); - exit(); - } - } - - protected function render() - { - include_once "Services/Badge/classes/class.ilBadgeRenderer.php"; - $rnd = ilBadgeRenderer::initFromId(trim($_GET["id"])); - if($rnd) - { - return $rnd->renderModal(); - } - } + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + if ($ilCtrl->isAsynch()) { + $cmd = $ilCtrl->getCmd(); + echo $this->$cmd(); + exit(); + } + } + + protected function render() + { + include_once "Services/Badge/classes/class.ilBadgeRenderer.php"; + $rnd = ilBadgeRenderer::initFromId(trim($_GET["id"])); + if ($rnd) { + return $rnd->renderModal(); + } + } } diff --git a/Services/Badge/classes/class.ilBadgeImageTemplate.php b/Services/Badge/classes/class.ilBadgeImageTemplate.php index 3137554fc9e3b58ef562a144e3a6678f27467d69..d7256388807c62bba83be7fdfdcd61ab4c3098b7 100644 --- a/Services/Badge/classes/class.ilBadgeImageTemplate.php +++ b/Services/Badge/classes/class.ilBadgeImageTemplate.php @@ -10,326 +10,306 @@ */ class ilBadgeImageTemplate { - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; - protected $id; // [int] - protected $title; // [string] - protected $image; // [string] - protected $types; // [array] - - /** - * Constructor - * - * @param int $a_id - * @return self - */ - public function __construct($a_id = null) - { - global $DIC; + protected $id; // [int] + protected $title; // [string] + protected $image; // [string] + protected $types; // [array] + + /** + * Constructor + * + * @param int $a_id + * @return self + */ + public function __construct($a_id = null) + { + global $DIC; - $this->db = $DIC->database(); - if($a_id) - { - $this->read($a_id); - } - } - - public static function getInstances() - { - global $DIC; + $this->db = $DIC->database(); + if ($a_id) { + $this->read($a_id); + } + } + + public static function getInstances() + { + global $DIC; - $ilDB = $DIC->database(); - - $res = array(); - - $types = array(); - $set = $ilDB->query("SELECT * FROM badge_image_templ_type"); - while($row = $ilDB->fetchAssoc($set)) - { - $types[$row["tmpl_id"]][] = $row["type_id"]; - } - - $set = $ilDB->query("SELECT * FROM badge_image_template". - " ORDER BY title"); - while($row = $ilDB->fetchAssoc($set)) - { - $row["types"] = (array)$types[$row["id"]]; - - $obj = new self(); - $obj->importDBRow($row); - $res[] = $obj; - } - - return $res; - } - - public static function getInstancesByType($a_type_unique_id) - { - $res = array(); - - foreach(self::getInstances() as $tmpl) - { - if(!sizeof($tmpl->getTypes()) || - in_array($a_type_unique_id, $tmpl->getTypes())) - { - $res[] = $tmpl; - } - } - - return $res; - } - - - // - // setter/getter - // - - protected function setId($a_id) - { - $this->id = (int)$a_id; - } - - public function getId() - { - return $this->id; - } - - public function setTitle($a_value) - { - $this->title = trim($a_value); - } - - public function getTitle() - { - return $this->title; - } - - protected function setImage($a_value) - { - $this->image = trim($a_value); - } - - public function getTypes() - { - return (array)$this->types; - } - - public function setTypes(array $types = null) - { - $this->types = is_array($types) - ? array_unique($types) - : null; - } - - public function getImage() - { - return $this->image; - } + $ilDB = $DIC->database(); + + $res = array(); + + $types = array(); + $set = $ilDB->query("SELECT * FROM badge_image_templ_type"); + while ($row = $ilDB->fetchAssoc($set)) { + $types[$row["tmpl_id"]][] = $row["type_id"]; + } + + $set = $ilDB->query("SELECT * FROM badge_image_template" . + " ORDER BY title"); + while ($row = $ilDB->fetchAssoc($set)) { + $row["types"] = (array) $types[$row["id"]]; + + $obj = new self(); + $obj->importDBRow($row); + $res[] = $obj; + } + + return $res; + } + + public static function getInstancesByType($a_type_unique_id) + { + $res = array(); + + foreach (self::getInstances() as $tmpl) { + if (!sizeof($tmpl->getTypes()) || + in_array($a_type_unique_id, $tmpl->getTypes())) { + $res[] = $tmpl; + } + } + + return $res; + } + + + // + // setter/getter + // + + protected function setId($a_id) + { + $this->id = (int) $a_id; + } + + public function getId() + { + return $this->id; + } + + public function setTitle($a_value) + { + $this->title = trim($a_value); + } + + public function getTitle() + { + return $this->title; + } + + protected function setImage($a_value) + { + $this->image = trim($a_value); + } + + public function getTypes() + { + return (array) $this->types; + } + + public function setTypes(array $types = null) + { + $this->types = is_array($types) + ? array_unique($types) + : null; + } + + public function getImage() + { + return $this->image; + } - /** - * @param array $a_upload_meta - * @throws ilFileUtilsException - */ - public function uploadImage(array $a_upload_meta) - { - if($this->getId() && - $a_upload_meta["tmp_name"]) - { - $path = $this->getFilePath($this->getId()); + /** + * @param array $a_upload_meta + * @throws ilFileUtilsException + */ + public function uploadImage(array $a_upload_meta) + { + if ($this->getId() && + $a_upload_meta["tmp_name"]) { + $path = $this->getFilePath($this->getId()); - include_once("./Services/Utilities/classes/class.ilFileUtils.php"); - $filename = ilFileUtils::getValidFilename($a_upload_meta["name"]); + include_once("./Services/Utilities/classes/class.ilFileUtils.php"); + $filename = ilFileUtils::getValidFilename($a_upload_meta["name"]); - $suffix = strtolower(array_pop(explode(".", $filename))); - $tgt = $path."img".$this->getId().".".$suffix; + $suffix = strtolower(array_pop(explode(".", $filename))); + $tgt = $path . "img" . $this->getId() . "." . $suffix; - if(ilUtil::moveUploadedFile($a_upload_meta["tmp_name"], "img".$this->getId().".".$suffix, $tgt)) - { - $this->setImage($filename); - $this->update(); - } - } - } - - public function getImagePath() - { - if($this->getId()) - { - if (is_file($this->getFilePath($this->getId())."img".$this->getId())) // formerly (early 5.2 versino), images have been uploaded with no suffix - { - return $this->getFilePath($this->getId()) . "img" . $this->getId(); - } - else - { - $suffix = strtolower(array_pop(explode(".", $this->getImage()))); - return $this->getFilePath($this->getId()) . "img" . $this->getId() . "." . $suffix; - } - } - return ""; - } - - /** - * Init file system storage - * - * @param type $a_id - * @param type $a_subdir - * @return string - */ - protected function getFilePath($a_id, $a_subdir = null) - { - include_once "Services/Badge/classes/class.ilFSStorageBadgeImageTemplate.php"; - $storage = new ilFSStorageBadgeImageTemplate($a_id); - $storage->create(); - - $path = $storage->getAbsolutePath()."/"; - - if($a_subdir) - { - $path .= $a_subdir."/"; - - if(!is_dir($path)) - { - mkdir($path); - } - } - - return $path; - } - - - // - // crud - // - - protected function read($a_id) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT * FROM badge_image_template". - " WHERE id = ".$ilDB->quote($a_id, "integer")); - if($ilDB->numRows($set)) - { - $row = $ilDB->fetchAssoc($set); - $row["types"] = $this->readTypes($a_id); - $this->importDBRow($row); - } - } - - protected function readTypes($a_id) - { - $ilDB = $this->db; - - $res = array(); - - $set = $ilDB->query("SELECT * FROM badge_image_templ_type". - " WHERE tmpl_id = ".$ilDB->quote($a_id, "integer")); - while($row = $ilDB->fetchAssoc($set)) - { - $res[] = $row["type_id"]; - } - - if(!sizeof($res)) - { - $res = null; - } - - return $res; - } - - protected function importDBRow(array $a_row) - { - $this->setId($a_row["id"]); - $this->setTitle($a_row["title"]); - $this->setImage($a_row["image"]); - $this->setTypes($a_row["types"]); - } - - public function create() - { - $ilDB = $this->db; - - if($this->getId()) - { - return $this->update(); - } - - $id = $ilDB->nextId("badge_image_template"); - $this->setId($id); - - $fields = $this->getPropertiesForStorage(); - $fields["id"] = array("integer", $id); - - $ilDB->insert("badge_image_template", $fields); - - $this->saveTypes(); - } - - public function update() - { - $ilDB = $this->db; - - if(!$this->getId()) - { - return $this->create(); - } - - $fields = $this->getPropertiesForStorage(); - - $ilDB->update("badge_image_template", $fields, - array("id"=>array("integer", $this->getId())) - ); - - $this->saveTypes(); - } - - public function delete() - { - $ilDB = $this->db; - - if(!$this->getId()) - { - return; - } - - $path = $this->getFilePath($this->getId()); - ilUtil::delDir($path); - - $ilDB->manipulate("DELETE FROM badge_image_template". - " WHERE id = ".$ilDB->quote($this->getId(), "integer")); - } - - protected function getPropertiesForStorage() - { - return array( - "title" => array("text", $this->getTitle()), - "image" => array("text", $this->getImage()) - ); - } - - protected function saveTypes() - { - $ilDB = $this->db; - - if($this->getId()) - { - $ilDB->manipulate("DELETE FROM badge_image_templ_type". - " WHERE tmpl_id = ".$ilDB->quote($this->getId(), "integer")); - - if($this->getTypes()) - { - foreach($this->getTypes() as $type) - { - $fields = array( - "tmpl_id" => array("integer", $this->getId()), - "type_id" => array("text", $type) - ); - $ilDB->insert("badge_image_templ_type", $fields); - } - } - } - } -} \ No newline at end of file + if (ilUtil::moveUploadedFile($a_upload_meta["tmp_name"], "img" . $this->getId() . "." . $suffix, $tgt)) { + $this->setImage($filename); + $this->update(); + } + } + } + + public function getImagePath() + { + if ($this->getId()) { + if (is_file($this->getFilePath($this->getId()) . "img" . $this->getId())) { // formerly (early 5.2 versino), images have been uploaded with no suffix + return $this->getFilePath($this->getId()) . "img" . $this->getId(); + } else { + $suffix = strtolower(array_pop(explode(".", $this->getImage()))); + return $this->getFilePath($this->getId()) . "img" . $this->getId() . "." . $suffix; + } + } + return ""; + } + + /** + * Init file system storage + * + * @param type $a_id + * @param type $a_subdir + * @return string + */ + protected function getFilePath($a_id, $a_subdir = null) + { + include_once "Services/Badge/classes/class.ilFSStorageBadgeImageTemplate.php"; + $storage = new ilFSStorageBadgeImageTemplate($a_id); + $storage->create(); + + $path = $storage->getAbsolutePath() . "/"; + + if ($a_subdir) { + $path .= $a_subdir . "/"; + + if (!is_dir($path)) { + mkdir($path); + } + } + + return $path; + } + + + // + // crud + // + + protected function read($a_id) + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT * FROM badge_image_template" . + " WHERE id = " . $ilDB->quote($a_id, "integer")); + if ($ilDB->numRows($set)) { + $row = $ilDB->fetchAssoc($set); + $row["types"] = $this->readTypes($a_id); + $this->importDBRow($row); + } + } + + protected function readTypes($a_id) + { + $ilDB = $this->db; + + $res = array(); + + $set = $ilDB->query("SELECT * FROM badge_image_templ_type" . + " WHERE tmpl_id = " . $ilDB->quote($a_id, "integer")); + while ($row = $ilDB->fetchAssoc($set)) { + $res[] = $row["type_id"]; + } + + if (!sizeof($res)) { + $res = null; + } + + return $res; + } + + protected function importDBRow(array $a_row) + { + $this->setId($a_row["id"]); + $this->setTitle($a_row["title"]); + $this->setImage($a_row["image"]); + $this->setTypes($a_row["types"]); + } + + public function create() + { + $ilDB = $this->db; + + if ($this->getId()) { + return $this->update(); + } + + $id = $ilDB->nextId("badge_image_template"); + $this->setId($id); + + $fields = $this->getPropertiesForStorage(); + $fields["id"] = array("integer", $id); + + $ilDB->insert("badge_image_template", $fields); + + $this->saveTypes(); + } + + public function update() + { + $ilDB = $this->db; + + if (!$this->getId()) { + return $this->create(); + } + + $fields = $this->getPropertiesForStorage(); + + $ilDB->update( + "badge_image_template", + $fields, + array("id"=>array("integer", $this->getId())) + ); + + $this->saveTypes(); + } + + public function delete() + { + $ilDB = $this->db; + + if (!$this->getId()) { + return; + } + + $path = $this->getFilePath($this->getId()); + ilUtil::delDir($path); + + $ilDB->manipulate("DELETE FROM badge_image_template" . + " WHERE id = " . $ilDB->quote($this->getId(), "integer")); + } + + protected function getPropertiesForStorage() + { + return array( + "title" => array("text", $this->getTitle()), + "image" => array("text", $this->getImage()) + ); + } + + protected function saveTypes() + { + $ilDB = $this->db; + + if ($this->getId()) { + $ilDB->manipulate("DELETE FROM badge_image_templ_type" . + " WHERE tmpl_id = " . $ilDB->quote($this->getId(), "integer")); + + if ($this->getTypes()) { + foreach ($this->getTypes() as $type) { + $fields = array( + "tmpl_id" => array("integer", $this->getId()), + "type_id" => array("text", $type) + ); + $ilDB->insert("badge_image_templ_type", $fields); + } + } + } + } +} diff --git a/Services/Badge/classes/class.ilBadgeImageTemplateTableGUI.php b/Services/Badge/classes/class.ilBadgeImageTemplateTableGUI.php index fd887068206c0931e771830c26fb147fc0cc5d44..9dc7f165203272a417cd08e981f201f1bd051a64 100644 --- a/Services/Badge/classes/class.ilBadgeImageTemplateTableGUI.php +++ b/Services/Badge/classes/class.ilBadgeImageTemplateTableGUI.php @@ -12,95 +12,90 @@ include_once("Services/Table/classes/class.ilTable2GUI.php"); * @ingroup ServicesBadge */ class ilBadgeImageTemplateTableGUI extends ilTable2GUI -{ - /** - * @var ilCtrl - */ - protected $ctrl; +{ + /** + * @var ilCtrl + */ + protected $ctrl; - protected $has_write; // [bool] - - function __construct($a_parent_obj, $a_parent_cmd = "", $a_has_write = false) - { - global $DIC; + protected $has_write; // [bool] + + public function __construct($a_parent_obj, $a_parent_cmd = "", $a_has_write = false) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->setId("bdgtmpl"); - $this->has_write = (bool)$a_has_write; - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setLimit(9999); - - $this->setTitle($lng->txt("badge_image_templates")); - - if($this->has_write) - { - $this->addColumn("", "", 1); - } - - $this->addColumn($lng->txt("title"), "title"); - $this->addColumn($lng->txt("image"), "image"); - - if($this->has_write) - { - $this->addColumn($lng->txt("action"), ""); - $this->addMultiCommand("confirmDeleteImageTemplates", $lng->txt("delete")); - } - - $this->setSelectAllCheckbox("id"); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.template_row.html", "Services/Badge"); - $this->setDefaultOrderField("title"); - - $this->getItems(); - } - - function getItems() - { - $data = array(); - - include_once "Services/Badge/classes/class.ilBadgeImageTemplate.php"; - foreach(ilBadgeImageTemplate::getInstances() as $template) - { - $data[] = array( - "id" => $template->getId(), - "title" => $template->getTitle(), - "path" => $template->getImagePath(), - "file" => $template->getImage() - ); - } - - $this->setData($data); - } - - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if($this->has_write) - { - $this->tpl->setVariable("VAL_ID", $a_set["id"]); - } - - $this->tpl->setVariable("TXT_TITLE", $a_set["title"]); - $this->tpl->setVariable("VAL_IMG", $a_set["path"]); - $this->tpl->setVariable("TXT_IMG", $a_set["file"]); - - if($this->has_write) - { - $ilCtrl->setParameter($this->getParentObject(), "tid", $a_set["id"]); - $url = $ilCtrl->getLinkTarget($this->getParentObject(), "editImageTemplate"); - $ilCtrl->setParameter($this->getParentObject(), "tid", ""); - - $this->tpl->setVariable("TXT_EDIT", $lng->txt("edit")); - $this->tpl->setVariable("URL_EDIT", $url); - } - } + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->setId("bdgtmpl"); + $this->has_write = (bool) $a_has_write; + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setLimit(9999); + + $this->setTitle($lng->txt("badge_image_templates")); + + if ($this->has_write) { + $this->addColumn("", "", 1); + } + + $this->addColumn($lng->txt("title"), "title"); + $this->addColumn($lng->txt("image"), "image"); + + if ($this->has_write) { + $this->addColumn($lng->txt("action"), ""); + $this->addMultiCommand("confirmDeleteImageTemplates", $lng->txt("delete")); + } + + $this->setSelectAllCheckbox("id"); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.template_row.html", "Services/Badge"); + $this->setDefaultOrderField("title"); + + $this->getItems(); + } + + public function getItems() + { + $data = array(); + + include_once "Services/Badge/classes/class.ilBadgeImageTemplate.php"; + foreach (ilBadgeImageTemplate::getInstances() as $template) { + $data[] = array( + "id" => $template->getId(), + "title" => $template->getTitle(), + "path" => $template->getImagePath(), + "file" => $template->getImage() + ); + } + + $this->setData($data); + } + + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if ($this->has_write) { + $this->tpl->setVariable("VAL_ID", $a_set["id"]); + } + + $this->tpl->setVariable("TXT_TITLE", $a_set["title"]); + $this->tpl->setVariable("VAL_IMG", $a_set["path"]); + $this->tpl->setVariable("TXT_IMG", $a_set["file"]); + + if ($this->has_write) { + $ilCtrl->setParameter($this->getParentObject(), "tid", $a_set["id"]); + $url = $ilCtrl->getLinkTarget($this->getParentObject(), "editImageTemplate"); + $ilCtrl->setParameter($this->getParentObject(), "tid", ""); + + $this->tpl->setVariable("TXT_EDIT", $lng->txt("edit")); + $this->tpl->setVariable("URL_EDIT", $url); + } + } } diff --git a/Services/Badge/classes/class.ilBadgeManagementGUI.php b/Services/Badge/classes/class.ilBadgeManagementGUI.php index ebf2107182352b713217ae5a054a00efc66fbf97..e9afbcfed1b03b06bbbf1e53c9ecc03272a8cb73 100644 --- a/Services/Badge/classes/class.ilBadgeManagementGUI.php +++ b/Services/Badge/classes/class.ilBadgeManagementGUI.php @@ -4,7 +4,7 @@ include_once("./Services/Badge/classes/class.ilBadgeHandler.php"); /** * Class ilBadgeManagementGUI - * + * * @author Jörg Lützenkirchen * @version $Id:$ * @@ -12,941 +12,896 @@ include_once("./Services/Badge/classes/class.ilBadgeHandler.php"); * @package ServicesBadge */ class ilBadgeManagementGUI -{ - /** - * @var ilLanguage - */ - protected $lng; +{ + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilTabsGUI + */ + protected $tabs; - /** - * @var ilTabsGUI - */ - protected $tabs; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilToolbarGUI + */ + protected $toolbar; - /** - * @var ilToolbarGUI - */ - protected $toolbar; + /** + * @var ilTemplate + */ + protected $tpl; - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilObjUser + */ + protected $user; - /** - * @var ilObjUser - */ - protected $user; + protected $parent_ref_id; // [int] + protected $parent_obj_id; // [int] + protected $parent_obj_type; // [string] + + const CLIPBOARD_ID = "bdgclpbrd"; + + /** + * Construct + * + * @param int $a_parent_ref_id + * @param int $a_parent_obj_id + * @param string $a_parent_obj_type + * @return self + */ + public function __construct($a_parent_ref_id, $a_parent_obj_id = null, $a_parent_obj_type = null) + { + global $DIC; - protected $parent_ref_id; // [int] - protected $parent_obj_id; // [int] - protected $parent_obj_type; // [string] - - const CLIPBOARD_ID = "bdgclpbrd"; - - /** - * Construct - * - * @param int $a_parent_ref_id - * @param int $a_parent_obj_id - * @param string $a_parent_obj_type - * @return self - */ - public function __construct($a_parent_ref_id, $a_parent_obj_id = null, $a_parent_obj_type = null) - { - global $DIC; + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->tabs = $DIC->tabs(); + $this->access = $DIC->access(); + $this->toolbar = $DIC->toolbar(); + $this->tpl = $DIC["tpl"]; + $this->user = $DIC->user(); + $lng = $DIC->language(); + + $this->parent_ref_id = $a_parent_ref_id; + $this->parent_obj_id = $a_parent_obj_id + ? $a_parent_obj_id + : ilObject::_lookupObjId($a_parent_ref_id); + $this->parent_obj_type = $a_parent_obj_type + ? $a_parent_obj_type + : ilObject::_lookupType($this->parent_obj_id); - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $this->tabs = $DIC->tabs(); - $this->access = $DIC->access(); - $this->toolbar = $DIC->toolbar(); - $this->tpl = $DIC["tpl"]; - $this->user = $DIC->user(); - $lng = $DIC->language(); - - $this->parent_ref_id = $a_parent_ref_id; - $this->parent_obj_id = $a_parent_obj_id - ? $a_parent_obj_id - : ilObject::_lookupObjId($a_parent_ref_id); - $this->parent_obj_type = $a_parent_obj_type - ? $a_parent_obj_type - : ilObject::_lookupType($this->parent_obj_id); + if (!ilBadgeHandler::getInstance()->isObjectActive($this->parent_obj_id)) { + throw new ilException("inactive object"); + } + + $lng->loadLanguageModule("badge"); + } + + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + $lng = $this->lng; + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd("listBadges"); - if(!ilBadgeHandler::getInstance()->isObjectActive($this->parent_obj_id)) - { - throw new ilException("inactive object"); - } - - $lng->loadLanguageModule("badge"); - } - - public function executeCommand() - { - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - $lng = $this->lng; - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd("listBadges"); + switch ($next_class) { + case "ilpropertyformgui": + // ajax - update + if ((int) $_REQUEST["bid"]) { + include_once "./Services/Badge/classes/class.ilBadge.php"; + $badge = new ilBadge((int) $_REQUEST["bid"]); + $type = $badge->getTypeInstance(); + $form = $this->initBadgeForm("edit", $type, $badge->getTypeId()); + $this->setBadgeFormValues($form, $badge, $type); + } + // ajax- create + else { + $type_id = $_REQUEST["type"]; + $ilCtrl->setParameter($this, "type", $type_id); + $handler = ilBadgeHandler::getInstance(); + $type = $handler->getTypeInstanceByUniqueId($type_id); + $form = $this->initBadgeForm("create", $type, $type_id); + } + $ilCtrl->forwardCommand($form); + break; + + /* + case "illplistofsettingsgui": + $id = $_GET["lpid"]; + if($id) + { + $ilCtrl->saveParameter($this, "bid"); + $ilCtrl->saveParameter($this, "lpid"); - switch($next_class) - { - case "ilpropertyformgui": - // ajax - update - if((int)$_REQUEST["bid"]) - { - include_once "./Services/Badge/classes/class.ilBadge.php"; - $badge = new ilBadge((int)$_REQUEST["bid"]); - $type = $badge->getTypeInstance(); - $form = $this->initBadgeForm("edit", $type, $badge->getTypeId()); - $this->setBadgeFormValues($form, $badge, $type); - } - // ajax- create - else - { - $type_id = $_REQUEST["type"]; - $ilCtrl->setParameter($this, "type", $type_id); - $handler = ilBadgeHandler::getInstance(); - $type = $handler->getTypeInstanceByUniqueId($type_id); - $form = $this->initBadgeForm("create", $type, $type_id); - } - $ilCtrl->forwardCommand($form); - break; - - /* - case "illplistofsettingsgui": - $id = $_GET["lpid"]; - if($id) - { - $ilCtrl->saveParameter($this, "bid"); - $ilCtrl->saveParameter($this, "lpid"); - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget( - $lng->txt("back"), - $ilCtrl->getLinkTarget($this, "editBadge") - ); - include_once './Services/Tracking/classes/class.ilLearningProgressGUI.php'; - include_once "Services/Tracking/classes/repository_statistics/class.ilLPListOfSettingsGUI.php"; - $lpgui = new ilLPListOfSettingsGUI(ilLearningProgressGUI::LP_CONTEXT_REPOSITORY, $id); - $ilCtrl->forwardCommand($lpgui); - break; - } - */ - - default: - $this->$cmd(); - break; - } - - return true; - } - - protected function setTabs($a_active) - { - $ilTabs = $this->tabs; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $ilTabs->addSubTab("badges", - $lng->txt("obj_bdga"), - $ilCtrl->getLinkTarget($this, "listBadges")); - - $ilTabs->addSubTab("users", - $lng->txt("users"), - $ilCtrl->getLinkTarget($this, "listUsers")); - - $ilTabs->activateSubTab($a_active); - } - - protected function hasWrite() - { - $ilAccess = $this->access; - return $ilAccess->checkAccess("write", "", $this->parent_ref_id); - } - - protected function listBadges() - { - $ilToolbar = $this->toolbar; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - - $this->setTabs("badges"); - - if($this->hasWrite()) - { - $handler = ilBadgeHandler::getInstance(); - $valid_types = $handler->getAvailableTypesForObjType($this->parent_obj_type); - if($valid_types) - { - include_once "Services/Badge/classes/class.ilBadge.php"; - $options = array(); - foreach($valid_types as $id => $type) - { - $options[$id] = ($this->parent_obj_type != "bdga") - ? ilBadge::getExtendedTypeCaption($type) - : $type->getCaption(); - } - asort($options); - - include_once "Services/Form/classes/class.ilSelectInputGUI.php"; - $drop = new ilSelectInputGUI($lng->txt("type"), "type"); - $drop->setOptions($options); - $ilToolbar->addInputItem($drop, true); - - $ilToolbar->setFormAction($ilCtrl->getFormAction($this, "addBadge")); - $ilToolbar->addFormButton($lng->txt("create"), "addBadge"); - } - else - { - ilUtil::sendInfo($lng->txt("badge_no_valid_types_for_obj")); - } - - if(is_array($_SESSION[self::CLIPBOARD_ID])) - { - if($valid_types) - { - $ilToolbar->addSeparator(); - } - - $tt = array(); - foreach($this->getValidBadgesFromClipboard() as $badge) - { - $tt[] = $badge->getTitle(); - } - $ttid = "bdgpst"; - include_once "Services/UIComponent/Tooltip/classes/class.ilTooltipGUI.php"; - ilTooltipGUI::addTooltip( - $ttid, - implode("
", $tt), - "", - "bottom center", - "top center", - false - ); - - $lng->loadLanguageModule("content"); - $ilToolbar->addButton($lng->txt("cont_paste_from_clipboard"). - " (".sizeof($tt).")", - $ilCtrl->getLinkTarget($this, "pasteBadges"), - "", "", "", $ttid); - $ilToolbar->addButton($lng->txt("clear_clipboard"), - $ilCtrl->getLinkTarget($this, "clearClipboard")); - } - } - - include_once "Services/Badge/classes/class.ilBadgeTableGUI.php"; - $tbl = new ilBadgeTableGUI($this, "listBadges", $this->parent_obj_id, $this->hasWrite()); - $tpl->setContent($tbl->getHTML()); - } - - protected function applyBadgeFilter() - { - include_once "Services/Badge/classes/class.ilBadgeTableGUI.php"; - $tbl = new ilBadgeTableGUI($this, "listBadges", $this->parent_obj_id, $this->hasWrite()); - $tbl->resetOffset(); - $tbl->writeFilterToSession(); - $this->listBadges(); - } - - protected function resetBadgeFilter() - { - include_once "Services/Badge/classes/class.ilBadgeTableGUI.php"; - $tbl = new ilBadgeTableGUI($this, "listBadges", $this->parent_obj_id, $this->hasWrite()); - $tbl->resetOffset(); - $tbl->resetFilter(); - $this->listBadges(); - } - - - // - // badge (CRUD) - // - - protected function addBadge(ilPropertyFormGUI $a_form = null) - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - - $type_id = $_REQUEST["type"]; - if(!$type_id || - !$this->hasWrite()) - { - $ilCtrl->redirect($this, "listBadges"); - } - - $ilCtrl->setParameter($this, "type", $type_id); - - $handler = ilBadgeHandler::getInstance(); - $type = $handler->getTypeInstanceByUniqueId($type_id); - if(!$type) - { - $ilCtrl->redirect($this, "listBadges"); - } - - if(!$a_form) - { - $a_form = $this->initBadgeForm("create", $type, $type_id); - } - - $tpl->setContent($a_form->getHTML()); - } - - protected function initBadgeForm($a_mode, ilBadgeType $a_type, $a_type_unique_id) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this, "saveBadge")); - $form->setTitle($lng->txt("badge_badge").' "'.$a_type->getCaption().'"'); - - $active = new ilCheckboxInputGUI($lng->txt("active"), "act"); - $form->addItem($active); - - $title = new ilTextInputGUI($lng->txt("title"), "title"); - $title->setRequired(true); - $form->addItem($title); - - $desc = new ilTextAreaInputGUI($lng->txt("description"), "desc"); - $desc->setRequired(true); - $form->addItem($desc); - - $crit = new ilTextAreaInputGUI($lng->txt("badge_criteria"), "crit"); - $crit->setRequired(true); - $form->addItem($crit); - - if($a_mode == "create") - { - // upload - - $img_mode = new ilRadioGroupInputGUI($lng->txt("image"), "img_mode"); - $img_mode->setRequired(true); - $form->addItem($img_mode); - - $img_mode_tmpl = new ilRadioOption($lng->txt("badge_image_from_template"), "tmpl"); - $img_mode->addOption($img_mode_tmpl); + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, "editBadge") + ); + include_once './Services/Tracking/classes/class.ilLearningProgressGUI.php'; + include_once "Services/Tracking/classes/repository_statistics/class.ilLPListOfSettingsGUI.php"; + $lpgui = new ilLPListOfSettingsGUI(ilLearningProgressGUI::LP_CONTEXT_REPOSITORY, $id); + $ilCtrl->forwardCommand($lpgui); + break; + } + */ + + default: + $this->$cmd(); + break; + } + + return true; + } + + protected function setTabs($a_active) + { + $ilTabs = $this->tabs; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $ilTabs->addSubTab( + "badges", + $lng->txt("obj_bdga"), + $ilCtrl->getLinkTarget($this, "listBadges") + ); + + $ilTabs->addSubTab( + "users", + $lng->txt("users"), + $ilCtrl->getLinkTarget($this, "listUsers") + ); + + $ilTabs->activateSubTab($a_active); + } + + protected function hasWrite() + { + $ilAccess = $this->access; + return $ilAccess->checkAccess("write", "", $this->parent_ref_id); + } + + protected function listBadges() + { + $ilToolbar = $this->toolbar; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + + $this->setTabs("badges"); + + if ($this->hasWrite()) { + $handler = ilBadgeHandler::getInstance(); + $valid_types = $handler->getAvailableTypesForObjType($this->parent_obj_type); + if ($valid_types) { + include_once "Services/Badge/classes/class.ilBadge.php"; + $options = array(); + foreach ($valid_types as $id => $type) { + $options[$id] = ($this->parent_obj_type != "bdga") + ? ilBadge::getExtendedTypeCaption($type) + : $type->getCaption(); + } + asort($options); + + include_once "Services/Form/classes/class.ilSelectInputGUI.php"; + $drop = new ilSelectInputGUI($lng->txt("type"), "type"); + $drop->setOptions($options); + $ilToolbar->addInputItem($drop, true); + + $ilToolbar->setFormAction($ilCtrl->getFormAction($this, "addBadge")); + $ilToolbar->addFormButton($lng->txt("create"), "addBadge"); + } else { + ilUtil::sendInfo($lng->txt("badge_no_valid_types_for_obj")); + } + + if (is_array($_SESSION[self::CLIPBOARD_ID])) { + if ($valid_types) { + $ilToolbar->addSeparator(); + } + + $tt = array(); + foreach ($this->getValidBadgesFromClipboard() as $badge) { + $tt[] = $badge->getTitle(); + } + $ttid = "bdgpst"; + include_once "Services/UIComponent/Tooltip/classes/class.ilTooltipGUI.php"; + ilTooltipGUI::addTooltip( + $ttid, + implode("
", $tt), + "", + "bottom center", + "top center", + false + ); + + $lng->loadLanguageModule("content"); + $ilToolbar->addButton( + $lng->txt("cont_paste_from_clipboard") . + " (" . sizeof($tt) . ")", + $ilCtrl->getLinkTarget($this, "pasteBadges"), + "", + "", + "", + $ttid + ); + $ilToolbar->addButton( + $lng->txt("clear_clipboard"), + $ilCtrl->getLinkTarget($this, "clearClipboard") + ); + } + } + + include_once "Services/Badge/classes/class.ilBadgeTableGUI.php"; + $tbl = new ilBadgeTableGUI($this, "listBadges", $this->parent_obj_id, $this->hasWrite()); + $tpl->setContent($tbl->getHTML()); + } + + protected function applyBadgeFilter() + { + include_once "Services/Badge/classes/class.ilBadgeTableGUI.php"; + $tbl = new ilBadgeTableGUI($this, "listBadges", $this->parent_obj_id, $this->hasWrite()); + $tbl->resetOffset(); + $tbl->writeFilterToSession(); + $this->listBadges(); + } + + protected function resetBadgeFilter() + { + include_once "Services/Badge/classes/class.ilBadgeTableGUI.php"; + $tbl = new ilBadgeTableGUI($this, "listBadges", $this->parent_obj_id, $this->hasWrite()); + $tbl->resetOffset(); + $tbl->resetFilter(); + $this->listBadges(); + } + + + // + // badge (CRUD) + // + + protected function addBadge(ilPropertyFormGUI $a_form = null) + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + + $type_id = $_REQUEST["type"]; + if (!$type_id || + !$this->hasWrite()) { + $ilCtrl->redirect($this, "listBadges"); + } + + $ilCtrl->setParameter($this, "type", $type_id); + + $handler = ilBadgeHandler::getInstance(); + $type = $handler->getTypeInstanceByUniqueId($type_id); + if (!$type) { + $ilCtrl->redirect($this, "listBadges"); + } + + if (!$a_form) { + $a_form = $this->initBadgeForm("create", $type, $type_id); + } + + $tpl->setContent($a_form->getHTML()); + } + + protected function initBadgeForm($a_mode, ilBadgeType $a_type, $a_type_unique_id) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this, "saveBadge")); + $form->setTitle($lng->txt("badge_badge") . ' "' . $a_type->getCaption() . '"'); + + $active = new ilCheckboxInputGUI($lng->txt("active"), "act"); + $form->addItem($active); + + $title = new ilTextInputGUI($lng->txt("title"), "title"); + $title->setRequired(true); + $form->addItem($title); + + $desc = new ilTextAreaInputGUI($lng->txt("description"), "desc"); + $desc->setRequired(true); + $form->addItem($desc); + + $crit = new ilTextAreaInputGUI($lng->txt("badge_criteria"), "crit"); + $crit->setRequired(true); + $form->addItem($crit); + + if ($a_mode == "create") { + // upload + + $img_mode = new ilRadioGroupInputGUI($lng->txt("image"), "img_mode"); + $img_mode->setRequired(true); + $form->addItem($img_mode); + + $img_mode_tmpl = new ilRadioOption($lng->txt("badge_image_from_template"), "tmpl"); + $img_mode->addOption($img_mode_tmpl); - $img_mode_up = new ilRadioOption($lng->txt("badge_image_from_upload"), "up"); - $img_mode->addOption($img_mode_up); - - $img_upload = new ilImageFileInputGUI($lng->txt("file"), "img"); - $img_upload->setRequired(true); - $img_upload->setSuffixes(array("png", "svg")); - $img_mode_up->addSubItem($img_upload); + $img_mode_up = new ilRadioOption($lng->txt("badge_image_from_upload"), "up"); + $img_mode->addOption($img_mode_up); + + $img_upload = new ilImageFileInputGUI($lng->txt("file"), "img"); + $img_upload->setRequired(true); + $img_upload->setSuffixes(array("png", "svg")); + $img_mode_up->addSubItem($img_upload); - // templates - - include_once "Services/Badge/classes/class.ilBadgeImageTemplate.php"; - $valid_templates = ilBadgeImageTemplate::getInstancesByType($a_type_unique_id); - if(sizeof($valid_templates)) - { - $options = array(); - $options[""] = $lng->txt("please_select"); - foreach($valid_templates as $tmpl) - { - $options[$tmpl->getId()] = $tmpl->getTitle(); - } + // templates + + include_once "Services/Badge/classes/class.ilBadgeImageTemplate.php"; + $valid_templates = ilBadgeImageTemplate::getInstancesByType($a_type_unique_id); + if (sizeof($valid_templates)) { + $options = array(); + $options[""] = $lng->txt("please_select"); + foreach ($valid_templates as $tmpl) { + $options[$tmpl->getId()] = $tmpl->getTitle(); + } - $tmpl = new ilSelectInputGUI($lng->txt("badge_image_template_form"), "tmpl"); - $tmpl->setRequired(true); - $tmpl->setOptions($options); - $img_mode_tmpl->addSubItem($tmpl); - } - else - { - // no templates, activate upload - $img_mode_tmpl->setDisabled(true); - $img_mode->setValue("up"); - } - } - else - { - $img_upload = new ilImageFileInputGUI($lng->txt("image"), "img"); - $img_upload->setSuffixes(array("png", "svg")); - $img_upload->setALlowDeletion(false); - $form->addItem($img_upload); - } - - $valid = new ilTextInputGUI($lng->txt("badge_valid"), "valid"); - $form->addItem($valid); - - $custom = $a_type->getConfigGUIInstance(); - if($custom && - $custom instanceof ilBadgeTypeGUI) - { - $custom->initConfigForm($form, $this->parent_ref_id); - } - - // :TODO: valid date/period - - if($a_mode == "create") - { - $form->addCommandButton("saveBadge", $lng->txt("save")); - } - else - { - $form->addCommandButton("updateBadge", $lng->txt("save")); - } - $form->addCommandButton("listBadges", $lng->txt("cancel")); - - return $form; - } - - protected function saveBadge() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $type_id = $_REQUEST["type"]; - if(!$type_id || - !$this->hasWrite()) - { - $ilCtrl->redirect($this, "listBadges"); - } - - $ilCtrl->setParameter($this, "type", $type_id); - - $handler = ilBadgeHandler::getInstance(); - $type = $handler->getTypeInstanceByUniqueId($type_id); - if(!$type) - { - $ilCtrl->redirect($this, "listBadges"); - } - - $form = $this->initBadgeForm("create", $type, $type_id); - $custom = $type->getConfigGUIInstance(); + $tmpl = new ilSelectInputGUI($lng->txt("badge_image_template_form"), "tmpl"); + $tmpl->setRequired(true); + $tmpl->setOptions($options); + $img_mode_tmpl->addSubItem($tmpl); + } else { + // no templates, activate upload + $img_mode_tmpl->setDisabled(true); + $img_mode->setValue("up"); + } + } else { + $img_upload = new ilImageFileInputGUI($lng->txt("image"), "img"); + $img_upload->setSuffixes(array("png", "svg")); + $img_upload->setALlowDeletion(false); + $form->addItem($img_upload); + } + + $valid = new ilTextInputGUI($lng->txt("badge_valid"), "valid"); + $form->addItem($valid); + + $custom = $a_type->getConfigGUIInstance(); + if ($custom && + $custom instanceof ilBadgeTypeGUI) { + $custom->initConfigForm($form, $this->parent_ref_id); + } + + // :TODO: valid date/period + + if ($a_mode == "create") { + $form->addCommandButton("saveBadge", $lng->txt("save")); + } else { + $form->addCommandButton("updateBadge", $lng->txt("save")); + } + $form->addCommandButton("listBadges", $lng->txt("cancel")); + + return $form; + } + + protected function saveBadge() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $type_id = $_REQUEST["type"]; + if (!$type_id || + !$this->hasWrite()) { + $ilCtrl->redirect($this, "listBadges"); + } + + $ilCtrl->setParameter($this, "type", $type_id); + + $handler = ilBadgeHandler::getInstance(); + $type = $handler->getTypeInstanceByUniqueId($type_id); + if (!$type) { + $ilCtrl->redirect($this, "listBadges"); + } + + $form = $this->initBadgeForm("create", $type, $type_id); + $custom = $type->getConfigGUIInstance(); - if($form->checkInput() && - (!$custom || $custom->validateForm($form))) - { - include_once "Services/Badge/classes/class.ilBadge.php"; - $badge = new ilBadge(); - $badge->setParentId($this->parent_obj_id); // :TODO: ref_id? - $badge->setTypeId($type_id); - $badge->setActive($form->getInput("act")); - $badge->setTitle($form->getInput("title")); - $badge->setDescription($form->getInput("desc")); - $badge->setCriteria($form->getInput("crit")); - $badge->setValid($form->getInput("valid")); + if ($form->checkInput() && + (!$custom || $custom->validateForm($form))) { + include_once "Services/Badge/classes/class.ilBadge.php"; + $badge = new ilBadge(); + $badge->setParentId($this->parent_obj_id); // :TODO: ref_id? + $badge->setTypeId($type_id); + $badge->setActive($form->getInput("act")); + $badge->setTitle($form->getInput("title")); + $badge->setDescription($form->getInput("desc")); + $badge->setCriteria($form->getInput("crit")); + $badge->setValid($form->getInput("valid")); - if($custom && - $custom instanceof ilBadgeTypeGUI) - { - $badge->setConfiguration($custom->getConfigFromForm($form)); - } - - $badge->create(); - - if($form->getInput("img_mode") == "up") - { - $badge->uploadImage($_FILES["img"]); - } - else - { - $tmpl = new ilBadgeImageTemplate($form->getInput("tmpl")); - $badge->importImage($tmpl->getImage(), $tmpl->getImagePath()); - } - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - $ilCtrl->redirect($this, "listBadges"); - } - - $form->setValuesByPost(); - $this->addBadge($form); - } - - protected function editBadge(ilPropertyFormGUI $a_form = null) - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - $badge_id = $_REQUEST["bid"]; - if(!$badge_id || - !$this->hasWrite()) - { - $ilCtrl->redirect($this, "listBadges"); - } - - $ilCtrl->setParameter($this, "bid", $badge_id); - - include_once "./Services/Badge/classes/class.ilBadge.php"; - $badge = new ilBadge($badge_id); - - $static_cnt = ilBadgeHandler::getInstance()->countStaticBadgeInstances($badge); - if($static_cnt) - { - ilUtil::sendInfo(sprintf($lng->txt("badge_edit_with_published"), $static_cnt)); - } - - if(!$a_form) - { - $type = $badge->getTypeInstance(); - $a_form = $this->initBadgeForm("edit", $type, $badge->getTypeId()); - $this->setBadgeFormValues($a_form, $badge, $type); - } - - $tpl->setContent($a_form->getHTML()); - } - - protected function setBadgeFormValues(ilPropertyFormGUI $a_form, ilBadge $a_badge, ilBadgeType $a_type) - { - $a_form->getItemByPostVar("act")->setChecked($a_badge->isActive()); - $a_form->getItemByPostVar("title")->setValue($a_badge->getTitle()); - $a_form->getItemByPostVar("desc")->setValue($a_badge->getDescription()); - $a_form->getItemByPostVar("crit")->setValue($a_badge->getCriteria()); - $a_form->getItemByPostVar("img")->setValue($a_badge->getImage()); - $a_form->getItemByPostVar("img")->setImage($a_badge->getImagePath()); - $a_form->getItemByPostVar("valid")->setValue($a_badge->getValid()); - - $custom = $a_type->getConfigGUIInstance(); - if($custom && - $custom instanceof ilBadgeTypeGUI) - { - $custom->importConfigToForm($a_form, $a_badge->getConfiguration()); - } - } - - protected function updateBadge() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $badge_id = $_REQUEST["bid"]; - if(!$badge_id || - !$this->hasWrite()) - { - $ilCtrl->redirect($this, "listBadges"); - } - - $ilCtrl->setParameter($this, "bid", $badge_id); - - include_once "./Services/Badge/classes/class.ilBadge.php"; - $badge = new ilBadge($badge_id); - $type = $badge->getTypeInstance(); - $custom = $type->getConfigGUIInstance(); - if($custom && - !($custom instanceof ilBadgeTypeGUI)) - { - $custom = null; - } - $form = $this->initBadgeForm("update", $type, $badge->getTypeId()); - if($form->checkInput() && - (!$custom || $custom->validateForm($form))) - { - $badge->setActive($form->getInput("act")); - $badge->setTitle($form->getInput("title")); - $badge->setDescription($form->getInput("desc")); - $badge->setCriteria($form->getInput("crit")); - $badge->setValid($form->getInput("valid")); - - if($custom) - { - $badge->setConfiguration($custom->getConfigFromForm($form)); - } - - $badge->update(); - - $badge->uploadImage($_FILES["img"]); - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - $ilCtrl->redirect($this, "listBadges"); - } - - ilUtil::sendFailure($lng->txt("form_input_not_valid")); - $form->setValuesByPost(); - $this->editBadge($form); - } - - protected function confirmDeleteBadges() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - $badge_ids = $this->getBadgesFromMultiAction(); - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTarget($this, "listBadges")); - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $confirmation_gui = new ilConfirmationGUI(); - $confirmation_gui->setFormAction($ilCtrl->getFormAction($this)); - $confirmation_gui->setHeaderText($lng->txt("badge_deletion_confirmation")); - $confirmation_gui->setCancel($lng->txt("cancel"), "listBadges"); - $confirmation_gui->setConfirm($lng->txt("delete"), "deleteBadges"); - - include_once "Services/Badge/classes/class.ilBadge.php"; - include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; - foreach($badge_ids as $badge_id) - { - $badge = new ilBadge($badge_id); - $confirmation_gui->addItem("id[]", $badge_id, $badge->getTitle(). - " (".sizeof(ilBadgeAssignment::getInstancesByBadgeId($badge_id)).")"); - } + if ($custom && + $custom instanceof ilBadgeTypeGUI) { + $badge->setConfiguration($custom->getConfigFromForm($form)); + } + + $badge->create(); + + if ($form->getInput("img_mode") == "up") { + $badge->uploadImage($_FILES["img"]); + } else { + $tmpl = new ilBadgeImageTemplate($form->getInput("tmpl")); + $badge->importImage($tmpl->getImage(), $tmpl->getImagePath()); + } + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "listBadges"); + } + + $form->setValuesByPost(); + $this->addBadge($form); + } + + protected function editBadge(ilPropertyFormGUI $a_form = null) + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + $badge_id = $_REQUEST["bid"]; + if (!$badge_id || + !$this->hasWrite()) { + $ilCtrl->redirect($this, "listBadges"); + } + + $ilCtrl->setParameter($this, "bid", $badge_id); + + include_once "./Services/Badge/classes/class.ilBadge.php"; + $badge = new ilBadge($badge_id); + + $static_cnt = ilBadgeHandler::getInstance()->countStaticBadgeInstances($badge); + if ($static_cnt) { + ilUtil::sendInfo(sprintf($lng->txt("badge_edit_with_published"), $static_cnt)); + } + + if (!$a_form) { + $type = $badge->getTypeInstance(); + $a_form = $this->initBadgeForm("edit", $type, $badge->getTypeId()); + $this->setBadgeFormValues($a_form, $badge, $type); + } + + $tpl->setContent($a_form->getHTML()); + } + + protected function setBadgeFormValues(ilPropertyFormGUI $a_form, ilBadge $a_badge, ilBadgeType $a_type) + { + $a_form->getItemByPostVar("act")->setChecked($a_badge->isActive()); + $a_form->getItemByPostVar("title")->setValue($a_badge->getTitle()); + $a_form->getItemByPostVar("desc")->setValue($a_badge->getDescription()); + $a_form->getItemByPostVar("crit")->setValue($a_badge->getCriteria()); + $a_form->getItemByPostVar("img")->setValue($a_badge->getImage()); + $a_form->getItemByPostVar("img")->setImage($a_badge->getImagePath()); + $a_form->getItemByPostVar("valid")->setValue($a_badge->getValid()); + + $custom = $a_type->getConfigGUIInstance(); + if ($custom && + $custom instanceof ilBadgeTypeGUI) { + $custom->importConfigToForm($a_form, $a_badge->getConfiguration()); + } + } + + protected function updateBadge() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $badge_id = $_REQUEST["bid"]; + if (!$badge_id || + !$this->hasWrite()) { + $ilCtrl->redirect($this, "listBadges"); + } + + $ilCtrl->setParameter($this, "bid", $badge_id); + + include_once "./Services/Badge/classes/class.ilBadge.php"; + $badge = new ilBadge($badge_id); + $type = $badge->getTypeInstance(); + $custom = $type->getConfigGUIInstance(); + if ($custom && + !($custom instanceof ilBadgeTypeGUI)) { + $custom = null; + } + $form = $this->initBadgeForm("update", $type, $badge->getTypeId()); + if ($form->checkInput() && + (!$custom || $custom->validateForm($form))) { + $badge->setActive($form->getInput("act")); + $badge->setTitle($form->getInput("title")); + $badge->setDescription($form->getInput("desc")); + $badge->setCriteria($form->getInput("crit")); + $badge->setValid($form->getInput("valid")); + + if ($custom) { + $badge->setConfiguration($custom->getConfigFromForm($form)); + } + + $badge->update(); + + $badge->uploadImage($_FILES["img"]); + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "listBadges"); + } + + ilUtil::sendFailure($lng->txt("form_input_not_valid")); + $form->setValuesByPost(); + $this->editBadge($form); + } + + protected function confirmDeleteBadges() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + $badge_ids = $this->getBadgesFromMultiAction(); + + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, "listBadges") + ); + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $confirmation_gui = new ilConfirmationGUI(); + $confirmation_gui->setFormAction($ilCtrl->getFormAction($this)); + $confirmation_gui->setHeaderText($lng->txt("badge_deletion_confirmation")); + $confirmation_gui->setCancel($lng->txt("cancel"), "listBadges"); + $confirmation_gui->setConfirm($lng->txt("delete"), "deleteBadges"); + + include_once "Services/Badge/classes/class.ilBadge.php"; + include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; + foreach ($badge_ids as $badge_id) { + $badge = new ilBadge($badge_id); + $confirmation_gui->addItem("id[]", $badge_id, $badge->getTitle() . + " (" . sizeof(ilBadgeAssignment::getInstancesByBadgeId($badge_id)) . ")"); + } - $tpl->setContent($confirmation_gui->getHTML()); - } - - protected function deleteBadges() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $badge_ids = $this->getBadgesFromMultiAction(); - - include_once "Services/Badge/classes/class.ilBadge.php"; - foreach($badge_ids as $badge_id) - { - $badge = new ilBadge($badge_id); - $badge->delete(); - } - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - $ilCtrl->redirect($this, "listBadges"); - } + $tpl->setContent($confirmation_gui->getHTML()); + } + + protected function deleteBadges() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $badge_ids = $this->getBadgesFromMultiAction(); + + include_once "Services/Badge/classes/class.ilBadge.php"; + foreach ($badge_ids as $badge_id) { + $badge = new ilBadge($badge_id); + $badge->delete(); + } + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "listBadges"); + } - - // - // badges multi action - // - - protected function getBadgesFromMultiAction() - { - $ilCtrl = $this->ctrl; - - $badge_ids = $_REQUEST["id"]; - if(!$badge_ids || - !$this->hasWrite()) - { - $ilCtrl->redirect($this, "listBadges"); - } - - return $badge_ids; - } - - protected function copyBadges() - { - $ilCtrl = $this->ctrl; - - $badge_ids = $this->getBadgesFromMultiAction(); + + // + // badges multi action + // + + protected function getBadgesFromMultiAction() + { + $ilCtrl = $this->ctrl; + + $badge_ids = $_REQUEST["id"]; + if (!$badge_ids || + !$this->hasWrite()) { + $ilCtrl->redirect($this, "listBadges"); + } + + return $badge_ids; + } + + protected function copyBadges() + { + $ilCtrl = $this->ctrl; + + $badge_ids = $this->getBadgesFromMultiAction(); - $_SESSION[self::CLIPBOARD_ID] = array_unique( - array_merge((array)$_SESSION[self::CLIPBOARD_ID], $badge_ids) - ); - - $ilCtrl->redirect($this, "listBadges"); - } - - protected function clearClipboard() - { - $ilCtrl = $this->ctrl; - - unset($_SESSION[self::CLIPBOARD_ID]); - $ilCtrl->redirect($this, "listBadges"); - } - - protected function getValidBadgesFromClipboard() - { - $res = array(); - - $valid_types = array_keys(ilBadgeHandler::getInstance()->getAvailableTypesForObjType($this->parent_obj_type)); - - include_once "Services/Badge/classes/class.ilBadge.php"; - foreach($_SESSION[self::CLIPBOARD_ID] as $badge_id) - { - $badge = new ilBadge($badge_id); - if(in_array($badge->getTypeId(), $valid_types)) - { - $res[] = $badge; - } - } - - return $res; - } - - protected function pasteBadges() - { - $ilCtrl = $this->ctrl; - - if(!$this->hasWrite() || - !is_array($_SESSION[self::CLIPBOARD_ID])) - { - $ilCtrl->redirect($this, "listBadges"); - } - - foreach($this->getValidBadgesFromClipboard() as $badge) - { - $badge->copy($this->parent_obj_id); - } - - $ilCtrl->redirect($this, "listBadges"); - } - - protected function toggleBadges($a_status) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $badge_ids = $this->getBadgesFromMultiAction(); - - include_once "Services/Badge/classes/class.ilBadge.php"; - foreach($badge_ids as $badge_id) - { - $badge = new ilBadge($badge_id); - $badge->setActive($a_status); - $badge->update(); - } - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - $ilCtrl->redirect($this, "listBadges"); - } - - protected function activateBadges() - { - $this->toggleBadges(true); - } - - protected function deactivateBadges() - { - $this->toggleBadges(false); - } + $_SESSION[self::CLIPBOARD_ID] = array_unique( + array_merge((array) $_SESSION[self::CLIPBOARD_ID], $badge_ids) + ); + + $ilCtrl->redirect($this, "listBadges"); + } + + protected function clearClipboard() + { + $ilCtrl = $this->ctrl; + + unset($_SESSION[self::CLIPBOARD_ID]); + $ilCtrl->redirect($this, "listBadges"); + } + + protected function getValidBadgesFromClipboard() + { + $res = array(); + + $valid_types = array_keys(ilBadgeHandler::getInstance()->getAvailableTypesForObjType($this->parent_obj_type)); + + include_once "Services/Badge/classes/class.ilBadge.php"; + foreach ($_SESSION[self::CLIPBOARD_ID] as $badge_id) { + $badge = new ilBadge($badge_id); + if (in_array($badge->getTypeId(), $valid_types)) { + $res[] = $badge; + } + } + + return $res; + } + + protected function pasteBadges() + { + $ilCtrl = $this->ctrl; + + if (!$this->hasWrite() || + !is_array($_SESSION[self::CLIPBOARD_ID])) { + $ilCtrl->redirect($this, "listBadges"); + } + + foreach ($this->getValidBadgesFromClipboard() as $badge) { + $badge->copy($this->parent_obj_id); + } + + $ilCtrl->redirect($this, "listBadges"); + } + + protected function toggleBadges($a_status) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $badge_ids = $this->getBadgesFromMultiAction(); + + include_once "Services/Badge/classes/class.ilBadge.php"; + foreach ($badge_ids as $badge_id) { + $badge = new ilBadge($badge_id); + $badge->setActive($a_status); + $badge->update(); + } + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "listBadges"); + } + + protected function activateBadges() + { + $this->toggleBadges(true); + } + + protected function deactivateBadges() + { + $this->toggleBadges(false); + } - - // - // users - // - - protected function listUsers() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilToolbar = $this->toolbar; - $tpl = $this->tpl; - - $this->setTabs("users"); - - if($this->hasWrite()) - { - $manual = ilBadgeHandler::getInstance()->getAvailableManualBadges($this->parent_obj_id, $this->parent_obj_type); - if(sizeof($manual)) - { - include_once "Services/Form/classes/class.ilSelectInputGUI.php"; - $drop = new ilSelectInputGUI($lng->txt("badge_badge"), "bid"); - $drop->setOptions($manual); - $ilToolbar->addInputItem($drop, true); + + // + // users + // + + protected function listUsers() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilToolbar = $this->toolbar; + $tpl = $this->tpl; + + $this->setTabs("users"); + + if ($this->hasWrite()) { + $manual = ilBadgeHandler::getInstance()->getAvailableManualBadges($this->parent_obj_id, $this->parent_obj_type); + if (sizeof($manual)) { + include_once "Services/Form/classes/class.ilSelectInputGUI.php"; + $drop = new ilSelectInputGUI($lng->txt("badge_badge"), "bid"); + $drop->setOptions($manual); + $ilToolbar->addInputItem($drop, true); - $ilToolbar->setFormAction($ilCtrl->getFormAction($this, "awardBadgeUserSelection")); - $ilToolbar->addFormButton($lng->txt("badge_award_badge"), "awardBadgeUserSelection"); - } - } - - include_once "Services/Badge/classes/class.ilBadgeUserTableGUI.php"; - $tbl = new ilBadgeUserTableGUI($this, "listUsers", $this->parent_ref_id); - $tpl->setContent($tbl->getHTML()); - } - - protected function applyListUsers() - { - include_once "Services/Badge/classes/class.ilBadgeUserTableGUI.php"; - $tbl = new ilBadgeUserTableGUI($this, "listUsers", $this->parent_ref_id); - $tbl->resetOffset(); - $tbl->writeFilterToSession(); - $this->listUsers(); - } - - protected function resetListUsers() - { - include_once "Services/Badge/classes/class.ilBadgeUserTableGUI.php"; - $tbl = new ilBadgeUserTableGUI($this, "listUsers", $this->parent_ref_id); - $tbl->resetOffset(); - $tbl->resetFilter(); - $this->listUsers(); - } - - protected function awardBadgeUserSelection() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - $lng = $this->lng; - - $bid = (int)$_REQUEST["bid"]; - if(!$bid || - !$this->hasWrite()) - { - $ilCtrl->redirect($this, "listUsers"); - } - - $manual = array_keys(ilBadgeHandler::getInstance()->getAvailableManualBadges($this->parent_obj_id, $this->parent_obj_type)); - if(!in_array($bid, $manual)) - { - $ilCtrl->redirect($this, "listUsers"); - } - - $back_target = "listUsers"; - if($_REQUEST["tgt"] == "bdgl") - { - $ilCtrl->saveParameter($this, "tgt"); - $back_target = "listBadges"; - } - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTarget($this, $back_target)); - - $ilCtrl->setParameter($this, "bid", $bid); - - include_once "./Services/Badge/classes/class.ilBadge.php"; - $badge = new ilBadge($bid); - - include_once "Services/Badge/classes/class.ilBadgeUserTableGUI.php"; - $tbl = new ilBadgeUserTableGUI($this, "awardBadgeUserSelection", $this->parent_ref_id, $badge); - $tpl->setContent($tbl->getHTML()); - } - - protected function applyAwardBadgeUserSelection() - { - include_once "Services/Badge/classes/class.ilBadgeUserTableGUI.php"; - $tbl = new ilBadgeUserTableGUI($this, "awardBadgeUserSelection", $this->parent_ref_id); - $tbl->resetOffset(); - $tbl->writeFilterToSession(); - $this->awardBadgeUserSelection(); - } - - protected function resetAwardBadgeUserSelection() - { - include_once "Services/Badge/classes/class.ilBadgeUserTableGUI.php"; - $tbl = new ilBadgeUserTableGUI($this, "awardBadgeUserSelection", $this->parent_ref_id); - $tbl->resetOffset(); - $tbl->resetFilter(); - $this->awardBadgeUserSelection(); - } - - protected function assignBadge() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - $lng = $this->lng; - - $user_ids = $_POST["id"]; - $badge_id = $_REQUEST["bid"]; - if(!$user_ids || - !$badge_id || - !$this->hasWrite()) - { - $ilCtrl->redirect($this, "listUsers"); - } - - include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; - $new_badges = array(); - foreach($user_ids as $user_id) - { - if(!ilBadgeAssignment::exists($badge_id, $user_id)) - { - $ass = new ilBadgeAssignment($badge_id, $user_id); - $ass->setAwardedBy($ilUser->getId()); - $ass->store(); - - $new_badges[$user_id][] = $badge_id; - } - } - - ilBadgeHandler::getInstance()->sendNotification($new_badges, $this->parent_ref_id); - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - $ilCtrl->redirect($this, "listUsers"); - } - - protected function confirmDeassignBadge() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - $user_ids = $_POST["id"]; - $badge_id = $_REQUEST["bid"]; - if(!$user_ids || - !$badge_id || - !$this->hasWrite()) - { - $ilCtrl->redirect($this, "listUsers"); - } - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTarget($this, "listUsers")); - - include_once "Services/Badge/classes/class.ilBadge.php"; - $badge = new ilBadge($badge_id); - - $ilCtrl->setParameter($this, "bid", $badge->getId()); - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $confirmation_gui = new ilConfirmationGUI(); - $confirmation_gui->setFormAction($ilCtrl->getFormAction($this)); - $confirmation_gui->setHeaderText(sprintf($lng->txt("badge_assignment_deletion_confirmation"), $badge->getTitle())); - $confirmation_gui->setCancel($lng->txt("cancel"), "listUsers"); - $confirmation_gui->setConfirm($lng->txt("delete"), "deassignBadge"); - - include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; - $assigned_users = ilBadgeAssignment::getAssignedUsers($badge->getId()); - - include_once "Services/User/classes/class.ilUserUtil.php"; - foreach($user_ids as $user_id) - { - if(in_array($user_id, $assigned_users)) - { - $confirmation_gui->addItem( - "id[]", - $user_id, - ilUserUtil::getNamePresentation($user_id, false, false, "", true) - ); - } - } + $ilToolbar->setFormAction($ilCtrl->getFormAction($this, "awardBadgeUserSelection")); + $ilToolbar->addFormButton($lng->txt("badge_award_badge"), "awardBadgeUserSelection"); + } + } + + include_once "Services/Badge/classes/class.ilBadgeUserTableGUI.php"; + $tbl = new ilBadgeUserTableGUI($this, "listUsers", $this->parent_ref_id); + $tpl->setContent($tbl->getHTML()); + } + + protected function applyListUsers() + { + include_once "Services/Badge/classes/class.ilBadgeUserTableGUI.php"; + $tbl = new ilBadgeUserTableGUI($this, "listUsers", $this->parent_ref_id); + $tbl->resetOffset(); + $tbl->writeFilterToSession(); + $this->listUsers(); + } + + protected function resetListUsers() + { + include_once "Services/Badge/classes/class.ilBadgeUserTableGUI.php"; + $tbl = new ilBadgeUserTableGUI($this, "listUsers", $this->parent_ref_id); + $tbl->resetOffset(); + $tbl->resetFilter(); + $this->listUsers(); + } + + protected function awardBadgeUserSelection() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + $lng = $this->lng; + + $bid = (int) $_REQUEST["bid"]; + if (!$bid || + !$this->hasWrite()) { + $ilCtrl->redirect($this, "listUsers"); + } + + $manual = array_keys(ilBadgeHandler::getInstance()->getAvailableManualBadges($this->parent_obj_id, $this->parent_obj_type)); + if (!in_array($bid, $manual)) { + $ilCtrl->redirect($this, "listUsers"); + } + + $back_target = "listUsers"; + if ($_REQUEST["tgt"] == "bdgl") { + $ilCtrl->saveParameter($this, "tgt"); + $back_target = "listBadges"; + } + + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, $back_target) + ); + + $ilCtrl->setParameter($this, "bid", $bid); + + include_once "./Services/Badge/classes/class.ilBadge.php"; + $badge = new ilBadge($bid); + + include_once "Services/Badge/classes/class.ilBadgeUserTableGUI.php"; + $tbl = new ilBadgeUserTableGUI($this, "awardBadgeUserSelection", $this->parent_ref_id, $badge); + $tpl->setContent($tbl->getHTML()); + } + + protected function applyAwardBadgeUserSelection() + { + include_once "Services/Badge/classes/class.ilBadgeUserTableGUI.php"; + $tbl = new ilBadgeUserTableGUI($this, "awardBadgeUserSelection", $this->parent_ref_id); + $tbl->resetOffset(); + $tbl->writeFilterToSession(); + $this->awardBadgeUserSelection(); + } + + protected function resetAwardBadgeUserSelection() + { + include_once "Services/Badge/classes/class.ilBadgeUserTableGUI.php"; + $tbl = new ilBadgeUserTableGUI($this, "awardBadgeUserSelection", $this->parent_ref_id); + $tbl->resetOffset(); + $tbl->resetFilter(); + $this->awardBadgeUserSelection(); + } + + protected function assignBadge() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + $lng = $this->lng; + + $user_ids = $_POST["id"]; + $badge_id = $_REQUEST["bid"]; + if (!$user_ids || + !$badge_id || + !$this->hasWrite()) { + $ilCtrl->redirect($this, "listUsers"); + } + + include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; + $new_badges = array(); + foreach ($user_ids as $user_id) { + if (!ilBadgeAssignment::exists($badge_id, $user_id)) { + $ass = new ilBadgeAssignment($badge_id, $user_id); + $ass->setAwardedBy($ilUser->getId()); + $ass->store(); + + $new_badges[$user_id][] = $badge_id; + } + } + + ilBadgeHandler::getInstance()->sendNotification($new_badges, $this->parent_ref_id); + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "listUsers"); + } + + protected function confirmDeassignBadge() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + $user_ids = $_POST["id"]; + $badge_id = $_REQUEST["bid"]; + if (!$user_ids || + !$badge_id || + !$this->hasWrite()) { + $ilCtrl->redirect($this, "listUsers"); + } + + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, "listUsers") + ); + + include_once "Services/Badge/classes/class.ilBadge.php"; + $badge = new ilBadge($badge_id); + + $ilCtrl->setParameter($this, "bid", $badge->getId()); + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $confirmation_gui = new ilConfirmationGUI(); + $confirmation_gui->setFormAction($ilCtrl->getFormAction($this)); + $confirmation_gui->setHeaderText(sprintf($lng->txt("badge_assignment_deletion_confirmation"), $badge->getTitle())); + $confirmation_gui->setCancel($lng->txt("cancel"), "listUsers"); + $confirmation_gui->setConfirm($lng->txt("delete"), "deassignBadge"); + + include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; + $assigned_users = ilBadgeAssignment::getAssignedUsers($badge->getId()); + + include_once "Services/User/classes/class.ilUserUtil.php"; + foreach ($user_ids as $user_id) { + if (in_array($user_id, $assigned_users)) { + $confirmation_gui->addItem( + "id[]", + $user_id, + ilUserUtil::getNamePresentation($user_id, false, false, "", true) + ); + } + } - $tpl->setContent($confirmation_gui->getHTML()); - } - - protected function deassignBadge() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $user_ids = $_POST["id"]; - $badge_id = $_REQUEST["bid"]; - if(!$user_ids || - !$badge_id || - !$this->hasWrite()) - { - $ilCtrl->redirect($this, "listUsers"); - } - - include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; - foreach($user_ids as $user_id) - { - $ass = new ilBadgeAssignment($badge_id, $user_id); - $ass->delete(); - } - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - $ilCtrl->redirect($this, "listUsers"); - } -} \ No newline at end of file + $tpl->setContent($confirmation_gui->getHTML()); + } + + protected function deassignBadge() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $user_ids = $_POST["id"]; + $badge_id = $_REQUEST["bid"]; + if (!$user_ids || + !$badge_id || + !$this->hasWrite()) { + $ilCtrl->redirect($this, "listUsers"); + } + + include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; + foreach ($user_ids as $user_id) { + $ass = new ilBadgeAssignment($badge_id, $user_id); + $ass->delete(); + } + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "listUsers"); + } +} diff --git a/Services/Badge/classes/class.ilBadgePersonalTableGUI.php b/Services/Badge/classes/class.ilBadgePersonalTableGUI.php index a6e9d7816c983f7ea7fe331ef3bc80f633b7634f..b8d54fbb10b77517a1a633662a83146e219e3455 100644 --- a/Services/Badge/classes/class.ilBadgePersonalTableGUI.php +++ b/Services/Badge/classes/class.ilBadgePersonalTableGUI.php @@ -12,220 +12,209 @@ include_once("Services/Table/classes/class.ilTable2GUI.php"); * @ingroup ServicesBadge */ class ilBadgePersonalTableGUI extends ilTable2GUI -{ - /** - * @var ilObjUser - */ - protected $user; +{ + /** + * @var ilObjUser + */ + protected $user; - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilTemplate + */ + protected $tpl; - function __construct($a_parent_obj, $a_parent_cmd, $a_user_id = null) - { - global $DIC; + public function __construct($a_parent_obj, $a_parent_cmd, $a_user_id = null) + { + global $DIC; - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - $this->ctrl = $DIC->ctrl(); - $this->tpl = $DIC["tpl"]; - $lng = $DIC->language(); - $ilUser = $DIC->user(); - $ilCtrl = $DIC->ctrl(); - $tpl = $DIC["tpl"]; - - if(!$a_user_id) - { - $a_user_id = $ilUser->getId(); - } - - $this->setId("bdgprs"); - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setTitle($lng->txt("badge_personal_badges")); - - $this->addColumn("", "", 1); - $this->addColumn($lng->txt("title"), "title"); - $this->addColumn($lng->txt("object"), "parent_title"); - $this->addColumn($lng->txt("badge_issued_on"), "issued_on"); - $this->addColumn($lng->txt("badge_in_profile"), "active"); - $this->addColumn($lng->txt("actions"), ""); + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + $this->ctrl = $DIC->ctrl(); + $this->tpl = $DIC["tpl"]; + $lng = $DIC->language(); + $ilUser = $DIC->user(); + $ilCtrl = $DIC->ctrl(); + $tpl = $DIC["tpl"]; + + if (!$a_user_id) { + $a_user_id = $ilUser->getId(); + } + + $this->setId("bdgprs"); + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setTitle($lng->txt("badge_personal_badges")); + + $this->addColumn("", "", 1); + $this->addColumn($lng->txt("title"), "title"); + $this->addColumn($lng->txt("object"), "parent_title"); + $this->addColumn($lng->txt("badge_issued_on"), "issued_on"); + $this->addColumn($lng->txt("badge_in_profile"), "active"); + $this->addColumn($lng->txt("actions"), ""); - if(ilBadgeHandler::getInstance()->isObiActive()) - { + if (ilBadgeHandler::getInstance()->isObiActive()) { - - // :TODO: use local copy instead? - $tpl->addJavascript("https://backpack.openbadges.org/issuer.js", false); - - $tpl->addJavascript("Services/Badge/js/ilBadge.js"); - $tpl->addOnLoadCode('il.Badge.setUrl("'. - $ilCtrl->getLinkTarget($this->getParentObject(), "addtoBackpack", "", true, false). - '")'); - } - - $this->setDefaultOrderField("title"); - - $this->setFormAction($ilCtrl->getFormAction($this->getParentObject())); - $this->setRowTemplate("tpl.personal_row.html", "Services/Badge"); - - $this->addMultiCommand("activate", $lng->txt("badge_add_to_profile")); - $this->addMultiCommand("deactivate", $lng->txt("badge_remove_from_profile")); - if(ilBadgeHandler::getInstance()->isObiActive()) - { - $this->addMultiCommand("addToBackpackMulti", $lng->txt("badge_add_to_backpack")); - } - $this->setSelectAllCheckbox("badge_id"); - - $this->getItems($a_user_id); - } - - public function initFilters(array $a_parents) - { - $lng = $this->lng; - - $title = $this->addFilterItemByMetaType("title", self::FILTER_TEXT, false, $lng->txt("title")); - $this->filter["title"] = $title->getValue(); - - $lng->loadLanguageModule("search"); - - $options = array( - "" => $lng->txt("search_any"), - "-1" => $lng->txt("none") - ); - asort($a_parents); - - $obj = $this->addFilterItemByMetaType("obj", self::FILTER_SELECT, false, $lng->txt("object")); - $obj->setOptions($options + $a_parents); - $this->filter["obj"] = $obj->getValue(); - } - - function getItems($a_user_id) - { - $lng = $this->lng; - - $data = $filter_parent = array(); - - include_once "Services/Badge/classes/class.ilBadge.php"; - include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; - include_once "Services/Badge/classes/class.ilBadgeRenderer.php"; - foreach(ilBadgeAssignment::getInstancesByUserId($a_user_id) as $ass) - { - $badge = new ilBadge($ass->getBadgeId()); - - $parent = null; - if($badge->getParentId()) - { - $parent = $badge->getParentMeta(); - if($parent["type"] == "bdga") - { - $parent = null; - } - else - { - $filter_parent[$parent["id"]] = - "(".$lng->txt($parent["type"]).") ".$parent["title"]; - } - } - - $data[] = array( - "id" => $badge->getId(), - "title" => $badge->getTitle(), - "image" => $badge->getImagePath(), - "issued_on" => $ass->getTimestamp(), - "parent_title" => $parent ? $parent["title"] : null, - "parent" => $parent, - "active" => (bool)$ass->getPosition(), - "renderer" => new ilBadgeRenderer($ass) - ); - } - - $this->initFilters($filter_parent); - - if($this->filter["title"]) - { - foreach($data as $idx => $row) - { - if(!stristr($row["title"], $this->filter["title"])) - { - unset($data[$idx]); - } - } - } - - if($this->filter["obj"]) - { - foreach($data as $idx => $row) - { - if($this->filter["obj"] > 0) - { - if(!$row["parent"] || $row["parent"]["id"] != $this->filter["obj"]) - { - unset($data[$idx]); - } - } - else - { - if($row["parent"]) - { - unset($data[$idx]); - } - } - } - } - - $this->setData($data); - } - - function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->tpl->setVariable("VAL_ID", $a_set["id"]); - $this->tpl->setVariable("PREVIEW", $a_set["renderer"]->getHTML()); - $this->tpl->setVariable("TXT_TITLE", $a_set["title"]); - $this->tpl->setVariable("TXT_ISSUED_ON", ilDatePresentation::formatDate(new ilDateTime($a_set["issued_on"], IL_CAL_UNIX))); - $this->tpl->setVariable("TXT_ACTIVE", $a_set["active"] - ? $lng->txt("yes") - : $lng->txt("no")); - - if($a_set["parent"]) - { - $this->tpl->setVariable("TXT_PARENT", $a_set["parent_title"]); - $this->tpl->setVariable("SRC_PARENT", - ilObject::_getIcon($a_set["parent"]["id"], "big", $a_set["parent"]["type"])); - } + + // :TODO: use local copy instead? + $tpl->addJavascript("https://backpack.openbadges.org/issuer.js", false); + + $tpl->addJavascript("Services/Badge/js/ilBadge.js"); + $tpl->addOnLoadCode('il.Badge.setUrl("' . + $ilCtrl->getLinkTarget($this->getParentObject(), "addtoBackpack", "", true, false) . + '")'); + } + + $this->setDefaultOrderField("title"); + + $this->setFormAction($ilCtrl->getFormAction($this->getParentObject())); + $this->setRowTemplate("tpl.personal_row.html", "Services/Badge"); + + $this->addMultiCommand("activate", $lng->txt("badge_add_to_profile")); + $this->addMultiCommand("deactivate", $lng->txt("badge_remove_from_profile")); + if (ilBadgeHandler::getInstance()->isObiActive()) { + $this->addMultiCommand("addToBackpackMulti", $lng->txt("badge_add_to_backpack")); + } + $this->setSelectAllCheckbox("badge_id"); + + $this->getItems($a_user_id); + } + + public function initFilters(array $a_parents) + { + $lng = $this->lng; + + $title = $this->addFilterItemByMetaType("title", self::FILTER_TEXT, false, $lng->txt("title")); + $this->filter["title"] = $title->getValue(); + + $lng->loadLanguageModule("search"); + + $options = array( + "" => $lng->txt("search_any"), + "-1" => $lng->txt("none") + ); + asort($a_parents); + + $obj = $this->addFilterItemByMetaType("obj", self::FILTER_SELECT, false, $lng->txt("object")); + $obj->setOptions($options + $a_parents); + $this->filter["obj"] = $obj->getValue(); + } + + public function getItems($a_user_id) + { + $lng = $this->lng; + + $data = $filter_parent = array(); + + include_once "Services/Badge/classes/class.ilBadge.php"; + include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; + include_once "Services/Badge/classes/class.ilBadgeRenderer.php"; + foreach (ilBadgeAssignment::getInstancesByUserId($a_user_id) as $ass) { + $badge = new ilBadge($ass->getBadgeId()); + + $parent = null; + if ($badge->getParentId()) { + $parent = $badge->getParentMeta(); + if ($parent["type"] == "bdga") { + $parent = null; + } else { + $filter_parent[$parent["id"]] = + "(" . $lng->txt($parent["type"]) . ") " . $parent["title"]; + } + } + + $data[] = array( + "id" => $badge->getId(), + "title" => $badge->getTitle(), + "image" => $badge->getImagePath(), + "issued_on" => $ass->getTimestamp(), + "parent_title" => $parent ? $parent["title"] : null, + "parent" => $parent, + "active" => (bool) $ass->getPosition(), + "renderer" => new ilBadgeRenderer($ass) + ); + } + + $this->initFilters($filter_parent); + + if ($this->filter["title"]) { + foreach ($data as $idx => $row) { + if (!stristr($row["title"], $this->filter["title"])) { + unset($data[$idx]); + } + } + } + + if ($this->filter["obj"]) { + foreach ($data as $idx => $row) { + if ($this->filter["obj"] > 0) { + if (!$row["parent"] || $row["parent"]["id"] != $this->filter["obj"]) { + unset($data[$idx]); + } + } else { + if ($row["parent"]) { + unset($data[$idx]); + } + } + } + } + + $this->setData($data); + } + + public function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $this->tpl->setVariable("VAL_ID", $a_set["id"]); + $this->tpl->setVariable("PREVIEW", $a_set["renderer"]->getHTML()); + $this->tpl->setVariable("TXT_TITLE", $a_set["title"]); + $this->tpl->setVariable("TXT_ISSUED_ON", ilDatePresentation::formatDate(new ilDateTime($a_set["issued_on"], IL_CAL_UNIX))); + $this->tpl->setVariable("TXT_ACTIVE", $a_set["active"] + ? $lng->txt("yes") + : $lng->txt("no")); + + if ($a_set["parent"]) { + $this->tpl->setVariable("TXT_PARENT", $a_set["parent_title"]); + $this->tpl->setVariable( + "SRC_PARENT", + ilObject::_getIcon($a_set["parent"]["id"], "big", $a_set["parent"]["type"]) + ); + } - include_once "Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"; - $actions = new ilAdvancedSelectionListGUI(); - $actions->setListTitle(""); + include_once "Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"; + $actions = new ilAdvancedSelectionListGUI(); + $actions->setListTitle(""); - $ilCtrl->setParameter($this->getParentObject(), "badge_id", $a_set["id"]); - $url = $ilCtrl->getLinkTarget($this->getParentObject(), $a_set["active"] - ? "deactivate" - : "activate"); - $ilCtrl->setParameter($this->getParentObject(), "badge_id", ""); - $actions->addItem($lng->txt(!$a_set["active"] - ? "badge_add_to_profile" - : "badge_remove_from_profile") - , "", $url); - - if(ilBadgeHandler::getInstance()->isObiActive()) - { - $actions->addItem($lng->txt("badge_add_to_backpack"), "", "", "", "", "", "", - false, "il.Badge.publish(".$a_set["id"].");"); - } - - $this->tpl->setVariable("ACTIONS", $actions->getHTML()); - } + $ilCtrl->setParameter($this->getParentObject(), "badge_id", $a_set["id"]); + $url = $ilCtrl->getLinkTarget($this->getParentObject(), $a_set["active"] + ? "deactivate" + : "activate"); + $ilCtrl->setParameter($this->getParentObject(), "badge_id", ""); + $actions->addItem($lng->txt(!$a_set["active"] + ? "badge_add_to_profile" + : "badge_remove_from_profile"), "", $url); + + if (ilBadgeHandler::getInstance()->isObiActive()) { + $actions->addItem( + $lng->txt("badge_add_to_backpack"), + "", + "", + "", + "", + "", + "", + false, + "il.Badge.publish(" . $a_set["id"] . ");" + ); + } + + $this->tpl->setVariable("ACTIONS", $actions->getHTML()); + } } - \ No newline at end of file diff --git a/Services/Badge/classes/class.ilBadgeProfileGUI.php b/Services/Badge/classes/class.ilBadgeProfileGUI.php index 6557c2a72a3e26b5b433430e5d85c6866c4507b8..088e11e5e85ea602fdb877b404a697dae37fe86e 100644 --- a/Services/Badge/classes/class.ilBadgeProfileGUI.php +++ b/Services/Badge/classes/class.ilBadgeProfileGUI.php @@ -1,548 +1,524 @@ * @version $Id:$ * * @package ServicesBadge */ class ilBadgeProfileGUI -{ - /** - * @var ilCtrl - */ - protected $ctrl; +{ + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilTemplate + */ + protected $tpl; - /** - * @var ilTabsGUI - */ - protected $tabs; + /** + * @var ilTabsGUI + */ + protected $tabs; - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - /** - * Constructor - */ - function __construct() - { - global $DIC; + /** + * Constructor + */ + public function __construct() + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - $this->tabs = $DIC->tabs(); - $this->user = $DIC->user(); - } + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + $this->tabs = $DIC->tabs(); + $this->user = $DIC->user(); + } - const BACKPACK_EMAIL = "badge_mozilla_bp"; - - function executeCommand() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - - $lng->loadLanguageModule("badge"); - - //$tpl->setTitle($lng->txt("obj_bdga")); - //$tpl->setTitleIcon(ilUtil::getImagePath("icon_bdga.svg")); - - switch($ilCtrl->getNextClass()) - { - default: - $this->setTabs(); - $cmd = $ilCtrl->getCmd("listBadges"); - $this->$cmd(); - break; - } - } - - protected function setTabs() - { - $ilTabs = $this->tabs; - $lng = $this->lng; - $ilCtrl = $this->ctrl; + const BACKPACK_EMAIL = "badge_mozilla_bp"; + + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + + $lng->loadLanguageModule("badge"); + + //$tpl->setTitle($lng->txt("obj_bdga")); + //$tpl->setTitleIcon(ilUtil::getImagePath("icon_bdga.svg")); + + switch ($ilCtrl->getNextClass()) { + default: + $this->setTabs(); + $cmd = $ilCtrl->getCmd("listBadges"); + $this->$cmd(); + break; + } + } + + protected function setTabs() + { + $ilTabs = $this->tabs; + $lng = $this->lng; + $ilCtrl = $this->ctrl; - if(ilBadgeHandler::getInstance()->isObiActive()) - { - $ilTabs->addTab("ilias_badges", - $lng->txt("badge_personal_badges"), - $ilCtrl->getLinkTarget($this, "listBadges")); + if (ilBadgeHandler::getInstance()->isObiActive()) { + $ilTabs->addTab( + "ilias_badges", + $lng->txt("badge_personal_badges"), + $ilCtrl->getLinkTarget($this, "listBadges") + ); - $ilTabs->addTab("backpack_badges", - $lng->txt("badge_backpack_list"), - $ilCtrl->getLinkTarget($this, "listBackpackGroups")); - } - } - - - // - // list - // - - protected function getSubTabs($a_active) - { - $ilTabs = $this->tabs; - $lng = $this->lng; - $ilCtrl = $this->ctrl; + $ilTabs->addTab( + "backpack_badges", + $lng->txt("badge_backpack_list"), + $ilCtrl->getLinkTarget($this, "listBackpackGroups") + ); + } + } + + + // + // list + // + + protected function getSubTabs($a_active) + { + $ilTabs = $this->tabs; + $lng = $this->lng; + $ilCtrl = $this->ctrl; - if(ilBadgeHandler::getInstance()->isObiActive()) - { - $ilTabs->addSubTab("list", - $lng->txt("badge_profile_view"), - $ilCtrl->getLinkTarget($this, "listBadges")); - $ilTabs->addSubTab("manage", - $lng->txt("badge_profile_manage"), - $ilCtrl->getLinkTarget($this, "manageBadges")); - $ilTabs->activateTab("ilias_badges"); - $ilTabs->activateSubTab($a_active); - } - else - { - $ilTabs->addSubTab("list", - $lng->txt("badge_profile_view"), - $ilCtrl->getLinkTarget($this, "listBadges")); - $ilTabs->addSubTab("manage", - $lng->txt("badge_profile_manage"), - $ilCtrl->getLinkTarget($this, "manageBadges")); - $ilTabs->activateSubTab($a_active); - } - - } - - protected function listBadges() - { - $tpl = $this->tpl; - $ilUser = $this->user; - - $this->getSubTabs("list"); - - $data = array(); - - // see ilBadgePersonalTableGUI::getItems() - include_once "Services/Badge/classes/class.ilBadge.php"; - include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; - include_once "Services/Badge/classes/class.ilBadgeRenderer.php"; - foreach(ilBadgeAssignment::getInstancesByUserId($ilUser->getId()) as $ass) - { - $badge = new ilBadge($ass->getBadgeId()); - - $data[] = array( - "id" => $badge->getId(), - "title" => $badge->getTitle(), - "description" => $badge->getDescription(), - "image" => $badge->getImagePath(), - "issued_on" => $ass->getTimestamp(), - "renderer" => new ilBadgeRenderer($ass) - ); - } - - // :TODO: - $data = ilUtil::sortArray($data, "issued_on", "desc", true); - - $tmpl = new ilTemplate("tpl.badge_backpack.html", true, true, "Services/Badge"); + if (ilBadgeHandler::getInstance()->isObiActive()) { + $ilTabs->addSubTab( + "list", + $lng->txt("badge_profile_view"), + $ilCtrl->getLinkTarget($this, "listBadges") + ); + $ilTabs->addSubTab( + "manage", + $lng->txt("badge_profile_manage"), + $ilCtrl->getLinkTarget($this, "manageBadges") + ); + $ilTabs->activateTab("ilias_badges"); + $ilTabs->activateSubTab($a_active); + } else { + $ilTabs->addSubTab( + "list", + $lng->txt("badge_profile_view"), + $ilCtrl->getLinkTarget($this, "listBadges") + ); + $ilTabs->addSubTab( + "manage", + $lng->txt("badge_profile_manage"), + $ilCtrl->getLinkTarget($this, "manageBadges") + ); + $ilTabs->activateSubTab($a_active); + } + } + + protected function listBadges() + { + $tpl = $this->tpl; + $ilUser = $this->user; + + $this->getSubTabs("list"); + + $data = array(); + + // see ilBadgePersonalTableGUI::getItems() + include_once "Services/Badge/classes/class.ilBadge.php"; + include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; + include_once "Services/Badge/classes/class.ilBadgeRenderer.php"; + foreach (ilBadgeAssignment::getInstancesByUserId($ilUser->getId()) as $ass) { + $badge = new ilBadge($ass->getBadgeId()); + + $data[] = array( + "id" => $badge->getId(), + "title" => $badge->getTitle(), + "description" => $badge->getDescription(), + "image" => $badge->getImagePath(), + "issued_on" => $ass->getTimestamp(), + "renderer" => new ilBadgeRenderer($ass) + ); + } + + // :TODO: + $data = ilUtil::sortArray($data, "issued_on", "desc", true); + + $tmpl = new ilTemplate("tpl.badge_backpack.html", true, true, "Services/Badge"); - ilDatePresentation::setUseRelativeDates(false); + ilDatePresentation::setUseRelativeDates(false); - foreach($data as $badge) - { - $tmpl->setCurrentBlock("badge_bl"); - $tmpl->setVariable("BADGE_TITLE", $badge["title"]); - // $tmpl->setVariable("BADGE_DESC", $badge["description"]); :TODO: - $tmpl->setVariable("BADGE_IMAGE", $badge["image"]); - $tmpl->setVariable("BADGE_CRITERIA", $badge["renderer"]->getHref()); - $tmpl->setVariable("BADGE_DATE", ilDatePresentation::formatDate(new ilDateTime($badge["issued_on"], IL_CAL_UNIX))); - $tmpl->parseCurrentBlock(); - } + foreach ($data as $badge) { + $tmpl->setCurrentBlock("badge_bl"); + $tmpl->setVariable("BADGE_TITLE", $badge["title"]); + // $tmpl->setVariable("BADGE_DESC", $badge["description"]); :TODO: + $tmpl->setVariable("BADGE_IMAGE", $badge["image"]); + $tmpl->setVariable("BADGE_CRITERIA", $badge["renderer"]->getHref()); + $tmpl->setVariable("BADGE_DATE", ilDatePresentation::formatDate(new ilDateTime($badge["issued_on"], IL_CAL_UNIX))); + $tmpl->parseCurrentBlock(); + } - $tpl->setContent($tmpl->get()); - } - - protected function manageBadges() - { - $tpl = $this->tpl; - - $this->getSubTabs("manage"); - - include_once "Services/Badge/classes/class.ilBadgePersonalTableGUI.php"; - $tbl = new ilBadgePersonalTableGUI($this, "manageBadges"); - - $tpl->setContent($tbl->getHTML()); - } - - protected function applyFilter() - { - include_once "Services/Badge/classes/class.ilBadgePersonalTableGUI.php"; - $tbl = new ilBadgePersonalTableGUI($this, "manageBadges"); - $tbl->resetOffset(); - $tbl->writeFilterToSession(); - $this->manageBadges(); - } - - protected function resetFilter() - { - include_once "Services/Badge/classes/class.ilBadgePersonalTableGUI.php"; - $tbl = new ilBadgePersonalTableGUI($this, "manageBadges"); - $tbl->resetOffset(); - $tbl->resetFilter(); - $this->manageBadges(); - } - - protected function getMultiSelection() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - $ids = $_POST["badge_id"]; - if(!$ids && is_numeric($_GET["badge_id"])) - { - $ids = array($_GET["badge_id"]); - } - if(is_array($ids)) - { - $res = array(); - include_once "Services/Badge/classes/class.ilBadge.php"; - include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; - foreach($ids as $id) - { - $ass = new ilBadgeAssignment($id, $ilUser->getId()); - if($ass->getTimestamp()) - { - $res[] = $ass; - } - } - - return $res; - } - else - { - ilUtil::sendFailure($lng->txt("select_one"), true); - $ilCtrl->redirect($this, "manageBadges"); - } - } - - protected function activate() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - foreach($this->getMultiSelection() as $ass) - { - // already active? - if(!$ass->getPosition()) - { - $ass->setPosition(999); - $ass->store(); - } - } - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - $ilCtrl->redirect($this, "manageBadges"); - } - - protected function deactivate() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - foreach($this->getMultiSelection() as $ass) - { - // already inactive? - if($ass->getPosition()) - { - $ass->setPosition(null); - $ass->store(); - } - } - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - $ilCtrl->redirect($this, "manageBadges"); - } - - - // - // (mozilla) backpack - // - - protected function addToBackpackMulti() - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $res = array(); - foreach($this->getMultiSelection() as $ass) - { - $url = $this->prepareBadge($ass->getBadgeId()); - if($url !== false) - { - $badge = new ilBadge($ass->getBadgeId()); - $titles[] = $badge->getTitle(); - $res[] = $url; - } - } - - // :TODO: use local copy instead? - $tpl->addJavascript("https://backpack.openbadges.org/issuer.js", false); - - $tpl->addJavascript("Services/Badge/js/ilBadge.js"); - $tpl->addOnloadCode("il.Badge.publishMulti(['".implode("','", $res)."']);"); - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTarget($this, "manageBadges")); - - ilUtil::sendInfo(sprintf($lng->txt("badge_add_to_backpack_multi"), implode(", ", $titles))); - } - - protected function setBackpackSubTabs() - { - $ilTabs = $this->tabs; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $ilTabs->addSubTab("backpack_badges", - $lng->txt("obj_bdga"), - $ilCtrl->getLinkTarget($this, "listBackpackGroups")); - - $ilTabs->addSubTab("backpack_settings", - $lng->txt("settings"), - $ilCtrl->getLinkTarget($this, "editSettings")); - - $ilTabs->activateTab("backpack_badges"); - } - - protected function listBackpackGroups() - { - $lng = $this->lng; - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - if(!ilBadgeHandler::getInstance()->isObiActive()) - { - $ilCtrl->redirect($this, "listBadges"); - } - - $this->setBackpackSubTabs(); - $ilTabs->activateSubTab("backpack_badges"); - - ilUtil::sendInfo($lng->txt("badge_backpack_gallery_info")); - - include_once "Services/Badge/classes/class.ilBadgeBackpack.php"; - $bp = new ilBadgeBackpack($this->getBackpackMail()); - $bp_groups = $bp->getGroups(); + $tpl->setContent($tmpl->get()); + } + + protected function manageBadges() + { + $tpl = $this->tpl; + + $this->getSubTabs("manage"); + + include_once "Services/Badge/classes/class.ilBadgePersonalTableGUI.php"; + $tbl = new ilBadgePersonalTableGUI($this, "manageBadges"); + + $tpl->setContent($tbl->getHTML()); + } + + protected function applyFilter() + { + include_once "Services/Badge/classes/class.ilBadgePersonalTableGUI.php"; + $tbl = new ilBadgePersonalTableGUI($this, "manageBadges"); + $tbl->resetOffset(); + $tbl->writeFilterToSession(); + $this->manageBadges(); + } + + protected function resetFilter() + { + include_once "Services/Badge/classes/class.ilBadgePersonalTableGUI.php"; + $tbl = new ilBadgePersonalTableGUI($this, "manageBadges"); + $tbl->resetOffset(); + $tbl->resetFilter(); + $this->manageBadges(); + } + + protected function getMultiSelection() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + $ids = $_POST["badge_id"]; + if (!$ids && is_numeric($_GET["badge_id"])) { + $ids = array($_GET["badge_id"]); + } + if (is_array($ids)) { + $res = array(); + include_once "Services/Badge/classes/class.ilBadge.php"; + include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; + foreach ($ids as $id) { + $ass = new ilBadgeAssignment($id, $ilUser->getId()); + if ($ass->getTimestamp()) { + $res[] = $ass; + } + } + + return $res; + } else { + ilUtil::sendFailure($lng->txt("select_one"), true); + $ilCtrl->redirect($this, "manageBadges"); + } + } + + protected function activate() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + foreach ($this->getMultiSelection() as $ass) { + // already active? + if (!$ass->getPosition()) { + $ass->setPosition(999); + $ass->store(); + } + } + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "manageBadges"); + } + + protected function deactivate() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + foreach ($this->getMultiSelection() as $ass) { + // already inactive? + if ($ass->getPosition()) { + $ass->setPosition(null); + $ass->store(); + } + } + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "manageBadges"); + } + + + // + // (mozilla) backpack + // + + protected function addToBackpackMulti() + { + $tpl = $this->tpl; + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $res = array(); + foreach ($this->getMultiSelection() as $ass) { + $url = $this->prepareBadge($ass->getBadgeId()); + if ($url !== false) { + $badge = new ilBadge($ass->getBadgeId()); + $titles[] = $badge->getTitle(); + $res[] = $url; + } + } + + // :TODO: use local copy instead? + $tpl->addJavascript("https://backpack.openbadges.org/issuer.js", false); + + $tpl->addJavascript("Services/Badge/js/ilBadge.js"); + $tpl->addOnloadCode("il.Badge.publishMulti(['" . implode("','", $res) . "']);"); + + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, "manageBadges") + ); + + ilUtil::sendInfo(sprintf($lng->txt("badge_add_to_backpack_multi"), implode(", ", $titles))); + } + + protected function setBackpackSubTabs() + { + $ilTabs = $this->tabs; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $ilTabs->addSubTab( + "backpack_badges", + $lng->txt("obj_bdga"), + $ilCtrl->getLinkTarget($this, "listBackpackGroups") + ); + + $ilTabs->addSubTab( + "backpack_settings", + $lng->txt("settings"), + $ilCtrl->getLinkTarget($this, "editSettings") + ); + + $ilTabs->activateTab("backpack_badges"); + } + + protected function listBackpackGroups() + { + $lng = $this->lng; + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + if (!ilBadgeHandler::getInstance()->isObiActive()) { + $ilCtrl->redirect($this, "listBadges"); + } + + $this->setBackpackSubTabs(); + $ilTabs->activateSubTab("backpack_badges"); + + ilUtil::sendInfo($lng->txt("badge_backpack_gallery_info")); + + include_once "Services/Badge/classes/class.ilBadgeBackpack.php"; + $bp = new ilBadgeBackpack($this->getBackpackMail()); + $bp_groups = $bp->getGroups(); - if(!is_array($bp_groups)) - { - ilUtil::sendInfo(sprintf($lng->txt("badge_backpack_connect_failed"), $this->getBackpackMail())); - return; - } - else if(!sizeof($bp_groups)) - { - ilUtil::sendInfo($lng->txt("badge_backpack_no_groups")); - return; - } - - $tmpl = new ilTemplate("tpl.badge_backpack.html", true, true, "Services/Badge"); + if (!is_array($bp_groups)) { + ilUtil::sendInfo(sprintf($lng->txt("badge_backpack_connect_failed"), $this->getBackpackMail())); + return; + } elseif (!sizeof($bp_groups)) { + ilUtil::sendInfo($lng->txt("badge_backpack_no_groups")); + return; + } + + $tmpl = new ilTemplate("tpl.badge_backpack.html", true, true, "Services/Badge"); - $tmpl->setVariable("BACKPACK_TITLE", $lng->txt("badge_backpack_list")); - - ilDatePresentation::setUseRelativeDates(false); + $tmpl->setVariable("BACKPACK_TITLE", $lng->txt("badge_backpack_list")); + + ilDatePresentation::setUseRelativeDates(false); - foreach($bp_groups as $group_id => $group) - { - $bp_badges = $bp->getBadges($group_id); - if(sizeof($bp_badges)) - { - foreach($bp_badges as $idx => $badge) - { - $tmpl->setCurrentBlock("badge_bl"); - $tmpl->setVariable("BADGE_TITLE", $badge["title"]); - $tmpl->setVariable("BADGE_DESC", $badge["description"]); - $tmpl->setVariable("BADGE_IMAGE", $badge["image_url"]); - $tmpl->setVariable("BADGE_CRITERIA", $badge["criteria_url"]); - $tmpl->setVariable("BADGE_ISSUER", $badge["issuer_name"]); - $tmpl->setVariable("BADGE_ISSUER_URL", $badge["issuer_url"]); - $tmpl->setVariable("BADGE_DATE", ilDatePresentation::formatDate($badge["issued_on"])); - $tmpl->parseCurrentBlock(); - } - } + foreach ($bp_groups as $group_id => $group) { + $bp_badges = $bp->getBadges($group_id); + if (sizeof($bp_badges)) { + foreach ($bp_badges as $idx => $badge) { + $tmpl->setCurrentBlock("badge_bl"); + $tmpl->setVariable("BADGE_TITLE", $badge["title"]); + $tmpl->setVariable("BADGE_DESC", $badge["description"]); + $tmpl->setVariable("BADGE_IMAGE", $badge["image_url"]); + $tmpl->setVariable("BADGE_CRITERIA", $badge["criteria_url"]); + $tmpl->setVariable("BADGE_ISSUER", $badge["issuer_name"]); + $tmpl->setVariable("BADGE_ISSUER_URL", $badge["issuer_url"]); + $tmpl->setVariable("BADGE_DATE", ilDatePresentation::formatDate($badge["issued_on"])); + $tmpl->parseCurrentBlock(); + } + } - $tmpl->setCurrentBlock("group_bl"); - $tmpl->setVariable("GROUP_TITLE", $group["title"]); - $tmpl->parseCurrentBlock(); - } + $tmpl->setCurrentBlock("group_bl"); + $tmpl->setVariable("GROUP_TITLE", $group["title"]); + $tmpl->parseCurrentBlock(); + } - $tpl->setContent($tmpl->get()); - } - - protected function prepareBadge($a_badge_id) - { - $ilUser = $this->user; - - // check if current user has given badge - include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; - $ass = new ilBadgeAssignment($a_badge_id, $ilUser->getId()); - if($ass->getTimestamp()) - { - $url = null; - try - { - $url = $ass->getStaticUrl(); - } - catch (Exception $ex) { - - } - if($url) - { - return $url; - } - } - - return false; - } - - protected function addToBackpack() - { - $ilCtrl = $this->ctrl; - - if(!$ilCtrl->isAsynch() || - !ilBadgeHandler::getInstance()->isObiActive()) - { - return false; - } - - $res = new stdClass(); - - $url = false; - $badge_id = (int)$_GET["id"]; - if($badge_id) - { - $url = $this->prepareBadge($badge_id); - } - - if($url !== false) - { - $res->error = false; - $res->url = $url; - } - else - { - $res->error = true; - $res->message = "missing badge id"; - } - - echo json_encode($res); - exit(); - } - - - // - // settings - // - - protected function getBackpackMail() - { - $ilUser = $this->user; - - $mail = $ilUser->getPref(self::BACKPACK_EMAIL); - if(!$mail) - { - $mail = $ilUser->getEmail(); - } - return $mail; - } - - protected function initSettingsForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this, "saveSettings")); - $form->setTitle($lng->txt("settings")); - - $email = new ilEMailInputGUI($lng->txt("badge_backpack_email"), "email"); - // $email->setRequired(true); - $email->setInfo($lng->txt("badge_backpack_email_info")); - $email->setValue($this->getBackpackMail()); - $form->addItem($email); - - $form->addCommandButton("saveSettings", $lng->txt("save")); - - return $form; - } - - protected function editSettings(ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - if(!ilBadgeHandler::getInstance()->isObiActive()) - { - $ilCtrl->redirect($this, "listBadges"); - } - - $this->setBackpackSubTabs(); - $ilTabs->activateSubTab("backpack_settings"); - - if(!$a_form) - { - $a_form = $this->initSettingsForm(); - } - - $tpl->setContent($a_form->getHTML()); - } - - protected function saveSettings() - { - $ilUser = $this->user; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $form = $this->initSettingsForm(); - if($form->checkInput()) - { - $new_email = $form->getInput("email"); - $old_email = $this->getBackpackMail(); - - ilObjUser::_writePref($ilUser->getId(), self::BACKPACK_EMAIL, $new_email); - - // if email was changed: delete badge files - if($new_email != $old_email) - { - include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; - ilBadgeAssignment::clearBadgeCache($ilUser->getId()); - } - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - $ilCtrl->redirect($this, "editSettings"); - } - - $form->setValuesByPost(); - $this->editSettings($form); - } + $tpl->setContent($tmpl->get()); + } + + protected function prepareBadge($a_badge_id) + { + $ilUser = $this->user; + + // check if current user has given badge + include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; + $ass = new ilBadgeAssignment($a_badge_id, $ilUser->getId()); + if ($ass->getTimestamp()) { + $url = null; + try { + $url = $ass->getStaticUrl(); + } catch (Exception $ex) { + } + if ($url) { + return $url; + } + } + + return false; + } + + protected function addToBackpack() + { + $ilCtrl = $this->ctrl; + + if (!$ilCtrl->isAsynch() || + !ilBadgeHandler::getInstance()->isObiActive()) { + return false; + } + + $res = new stdClass(); + + $url = false; + $badge_id = (int) $_GET["id"]; + if ($badge_id) { + $url = $this->prepareBadge($badge_id); + } + + if ($url !== false) { + $res->error = false; + $res->url = $url; + } else { + $res->error = true; + $res->message = "missing badge id"; + } + + echo json_encode($res); + exit(); + } + + + // + // settings + // + + protected function getBackpackMail() + { + $ilUser = $this->user; + + $mail = $ilUser->getPref(self::BACKPACK_EMAIL); + if (!$mail) { + $mail = $ilUser->getEmail(); + } + return $mail; + } + + protected function initSettingsForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this, "saveSettings")); + $form->setTitle($lng->txt("settings")); + + $email = new ilEMailInputGUI($lng->txt("badge_backpack_email"), "email"); + // $email->setRequired(true); + $email->setInfo($lng->txt("badge_backpack_email_info")); + $email->setValue($this->getBackpackMail()); + $form->addItem($email); + + $form->addCommandButton("saveSettings", $lng->txt("save")); + + return $form; + } + + protected function editSettings(ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + if (!ilBadgeHandler::getInstance()->isObiActive()) { + $ilCtrl->redirect($this, "listBadges"); + } + + $this->setBackpackSubTabs(); + $ilTabs->activateSubTab("backpack_settings"); + + if (!$a_form) { + $a_form = $this->initSettingsForm(); + } + + $tpl->setContent($a_form->getHTML()); + } + + protected function saveSettings() + { + $ilUser = $this->user; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $form = $this->initSettingsForm(); + if ($form->checkInput()) { + $new_email = $form->getInput("email"); + $old_email = $this->getBackpackMail(); + + ilObjUser::_writePref($ilUser->getId(), self::BACKPACK_EMAIL, $new_email); + + // if email was changed: delete badge files + if ($new_email != $old_email) { + include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; + ilBadgeAssignment::clearBadgeCache($ilUser->getId()); + } + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "editSettings"); + } + + $form->setValuesByPost(); + $this->editSettings($form); + } } diff --git a/Services/Badge/classes/class.ilBadgeRenderer.php b/Services/Badge/classes/class.ilBadgeRenderer.php index ef3c1e93e9084dece2e486d301a82afa02a8980c..870147e764513e906f2ac2dc627d6efba2e5d8c4 100644 --- a/Services/Badge/classes/class.ilBadgeRenderer.php +++ b/Services/Badge/classes/class.ilBadgeRenderer.php @@ -5,7 +5,7 @@ include_once "Services/Badge/classes/class.ilBadge.php"; /** * Class ilBadgeRenderer - * + * * @author Jörg Lützenkirchen * @version $Id:$ * @@ -13,196 +13,195 @@ include_once "Services/Badge/classes/class.ilBadge.php"; */ class ilBadgeRenderer { - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilTemplate + */ + protected $tpl; - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - protected $assignment; // [ilBadgeAssignment] - protected $badge; // [ilBadge] - - protected static $init; // [bool] - - public function __construct(ilBadgeAssignment $a_assignment = null, ilBadge $a_badge = null) - { - global $DIC; + protected $assignment; // [ilBadgeAssignment] + protected $badge; // [ilBadge] + + protected static $init; // [bool] + + public function __construct(ilBadgeAssignment $a_assignment = null, ilBadge $a_badge = null) + { + global $DIC; - $this->tpl = $DIC["tpl"]; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - if($a_assignment) - { - $this->assignment = $a_assignment; - $this->badge = new ilBadge($this->assignment->getBadgeId()); - } - else - { - $this->badge = $a_badge; - } - } - - public static function initFromId($a_id) - { - $id = explode("_", $_GET["id"]); - if(sizeof($id) == 3) - { - $user_id = $id[0]; - $badge_id = $id[1]; - $hash = $id[2]; - - if($user_id) - { - include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; - $assignment = new ilBadgeAssignment($badge_id, $user_id); - if($assignment->getTimestamp()) - { - $obj = new self($assignment); - } - } - else - { - include_once "Services/Badge/classes/class.ilBadge.php"; - $badge = new ilBadge($badge_id); - $obj = new self(null, $badge); - } - if($hash == $obj->getBadgeHash()) - { - return $obj; - } - } - } - - public function getHTML() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - - if(!self::$init) - { - self::$init = true; - - $url = $ilCtrl->getLinkTargetByClass("ilBadgeHandlerGUI", - "render", "", true, false); - - $tpl->addJavaScript("Services/Badge/js/ilBadgeRenderer.js"); - $tpl->addOnLoadCode('il.BadgeRenderer.init("'.$url.'");'); - } - - $hash = $this->getBadgeHash(); + $this->tpl = $DIC["tpl"]; + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + if ($a_assignment) { + $this->assignment = $a_assignment; + $this->badge = new ilBadge($this->assignment->getBadgeId()); + } else { + $this->badge = $a_badge; + } + } + + public static function initFromId($a_id) + { + $id = explode("_", $_GET["id"]); + if (sizeof($id) == 3) { + $user_id = $id[0]; + $badge_id = $id[1]; + $hash = $id[2]; + + if ($user_id) { + include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; + $assignment = new ilBadgeAssignment($badge_id, $user_id); + if ($assignment->getTimestamp()) { + $obj = new self($assignment); + } + } else { + include_once "Services/Badge/classes/class.ilBadge.php"; + $badge = new ilBadge($badge_id); + $obj = new self(null, $badge); + } + if ($hash == $obj->getBadgeHash()) { + return $obj; + } + } + } + + public function getHTML() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + + if (!self::$init) { + self::$init = true; + + $url = $ilCtrl->getLinkTargetByClass( + "ilBadgeHandlerGUI", + "render", + "", + true, + false + ); + + $tpl->addJavaScript("Services/Badge/js/ilBadgeRenderer.js"); + $tpl->addOnLoadCode('il.BadgeRenderer.init("' . $url . '");'); + } + + $hash = $this->getBadgeHash(); - $btpl = new ilTemplate("tpl.badge_renderer.html", true, true, "Services/Badge"); + $btpl = new ilTemplate("tpl.badge_renderer.html", true, true, "Services/Badge"); $image_path = ilWACSignedPath::signFile($this->badge->getImagePath()); - $btpl->setVariable("BADGE_IMG", $image_path); - $btpl->setVariable("BADGE_TXT", $this->badge->getTitle()); - $btpl->setVariable("BADGE_ID", "badge_". - ($this->assignment - ? $this->assignment->getUserId() - : "")."_". - $this->badge->getId()."_". - $hash); - return $btpl->get(); - } - - public function getHref() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - - if(!self::$init) - { - self::$init = true; - - $url = $ilCtrl->getLinkTargetByClass("ilBadgeHandlerGUI", - "render", "", true, false); - - $tpl->addJavaScript("Services/Badge/js/ilBadgeRenderer.js"); - $tpl->addOnLoadCode('il.BadgeRenderer.init("'.$url.'");'); - } - - $hash = $this->getBadgeHash(); - - return "#\" data-id=\"badge_". - ($this->assignment - ? $this->assignment->getUserId() - : "")."_". - $this->badge->getId()."_". - $hash; - } - - protected function getBadgeHash() - { - return md5("bdg-". - ($this->assignment - ? $this->assignment->getUserId() - : "")."-". - $this->badge->getId()); - } - - public function renderModal() - { - $lng = $this->lng; - - include_once "Services/UIComponent/Modal/classes/class.ilModalGUI.php"; - - // only needed for modal-js-calls - // ilModalGUI::initJS(); - - $modal = ilModalGUI::getInstance(); - $modal->setId("badge_modal_".$this->getBadgeHash()); - $modal->setType(ilModalGUI::TYPE_SMALL); - $modal->setHeading($this->badge->getTitle()); - - $lng->loadLanguageModule("badge"); - - $tpl = new ilTemplate("tpl.badge_modal.html", true, true, "Services/Badge"); - - $tpl->setVariable("IMG_SRC", $this->badge->getImagePath()); - $tpl->setVariable("IMG_TXT", $this->badge->getImage()); - - $tpl->setVariable("TXT_DESC", $lng->txt("description")); - $tpl->setVariable("DESC", nl2br($this->badge->getDescription())); - - $tpl->setVariable("TXT_CRITERIA", $lng->txt("badge_criteria")); - $tpl->setVariable("CRITERIA", nl2br($this->badge->getCriteria())); - - if($this->assignment) - { - $tpl->setVariable("TXT_TSTAMP", $lng->txt("badge_issued_on")); - $tpl->setVariable("TSTAMP", - ilDatePresentation::formatDate(new ilDateTime($this->assignment->getTimestamp(), IL_CAL_UNIX))); - } + $btpl->setVariable("BADGE_IMG", $image_path); + $btpl->setVariable("BADGE_TXT", $this->badge->getTitle()); + $btpl->setVariable("BADGE_ID", "badge_" . + ($this->assignment + ? $this->assignment->getUserId() + : "") . "_" . + $this->badge->getId() . "_" . + $hash); + return $btpl->get(); + } + + public function getHref() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + + if (!self::$init) { + self::$init = true; + + $url = $ilCtrl->getLinkTargetByClass( + "ilBadgeHandlerGUI", + "render", + "", + true, + false + ); + + $tpl->addJavaScript("Services/Badge/js/ilBadgeRenderer.js"); + $tpl->addOnLoadCode('il.BadgeRenderer.init("' . $url . '");'); + } + + $hash = $this->getBadgeHash(); + + return "#\" data-id=\"badge_" . + ($this->assignment + ? $this->assignment->getUserId() + : "") . "_" . + $this->badge->getId() . "_" . + $hash; + } + + protected function getBadgeHash() + { + return md5("bdg-" . + ($this->assignment + ? $this->assignment->getUserId() + : "") . "-" . + $this->badge->getId()); + } + + public function renderModal() + { + $lng = $this->lng; + + include_once "Services/UIComponent/Modal/classes/class.ilModalGUI.php"; + + // only needed for modal-js-calls + // ilModalGUI::initJS(); + + $modal = ilModalGUI::getInstance(); + $modal->setId("badge_modal_" . $this->getBadgeHash()); + $modal->setType(ilModalGUI::TYPE_SMALL); + $modal->setHeading($this->badge->getTitle()); + + $lng->loadLanguageModule("badge"); + + $tpl = new ilTemplate("tpl.badge_modal.html", true, true, "Services/Badge"); + + $tpl->setVariable("IMG_SRC", $this->badge->getImagePath()); + $tpl->setVariable("IMG_TXT", $this->badge->getImage()); + + $tpl->setVariable("TXT_DESC", $lng->txt("description")); + $tpl->setVariable("DESC", nl2br($this->badge->getDescription())); + + $tpl->setVariable("TXT_CRITERIA", $lng->txt("badge_criteria")); + $tpl->setVariable("CRITERIA", nl2br($this->badge->getCriteria())); + + if ($this->assignment) { + $tpl->setVariable("TXT_TSTAMP", $lng->txt("badge_issued_on")); + $tpl->setVariable( + "TSTAMP", + ilDatePresentation::formatDate(new ilDateTime($this->assignment->getTimestamp(), IL_CAL_UNIX)) + ); + } - if($this->badge->getParentId()) - { - $parent = $this->badge->getParentMeta(); - if($parent["type"] != "bdga") - { - $tpl->setVariable("TXT_PARENT", $lng->txt("object")); - $tpl->setVariable("PARENT", $parent["title"]); - $tpl->setVariable("PARENT_TYPE", $lng->txt("obj_".$parent["type"])); - $tpl->setVariable("PARENT_ICON", - ilObject::_getIcon($parent["id"], "big", $parent["type"])); - } - } - - if($this->badge->getValid()) - { - $tpl->setVariable("TXT_VALID", $lng->txt("badge_valid")); - $tpl->setVariable("VALID", $this->badge->getValid()); - } - - $modal->setBody($tpl->get()); - - return $modal->getHTML(); - } -} \ No newline at end of file + if ($this->badge->getParentId()) { + $parent = $this->badge->getParentMeta(); + if ($parent["type"] != "bdga") { + $tpl->setVariable("TXT_PARENT", $lng->txt("object")); + $tpl->setVariable("PARENT", $parent["title"]); + $tpl->setVariable("PARENT_TYPE", $lng->txt("obj_" . $parent["type"])); + $tpl->setVariable( + "PARENT_ICON", + ilObject::_getIcon($parent["id"], "big", $parent["type"]) + ); + } + } + + if ($this->badge->getValid()) { + $tpl->setVariable("TXT_VALID", $lng->txt("badge_valid")); + $tpl->setVariable("VALID", $this->badge->getValid()); + } + + $modal->setBody($tpl->get()); + + return $modal->getHTML(); + } +} diff --git a/Services/Badge/classes/class.ilBadgeTableGUI.php b/Services/Badge/classes/class.ilBadgeTableGUI.php index d0e81f2d532c8347e450c206856e9138b2c8737a..596c7d1265f319fba160855136e15670923911b3 100644 --- a/Services/Badge/classes/class.ilBadgeTableGUI.php +++ b/Services/Badge/classes/class.ilBadgeTableGUI.php @@ -13,157 +13,149 @@ include_once("./Services/Badge/classes/class.ilBadge.php"); * @ingroup ServicesBadge */ class ilBadgeTableGUI extends ilTable2GUI -{ - /** - * @var ilCtrl - */ - protected $ctrl; +{ + /** + * @var ilCtrl + */ + protected $ctrl; - protected $has_write; // [bool] - protected $parent_type; // [string] - - function __construct($a_parent_obj, $a_parent_cmd = "", $a_parent_obj_id, $a_has_write = false) - { - global $DIC; + protected $has_write; // [bool] + protected $parent_type; // [string] + + public function __construct($a_parent_obj, $a_parent_cmd = "", $a_parent_obj_id, $a_has_write = false) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->setId("bdgbdg"); - $this->has_write = (bool)$a_has_write; - $this->parent_type = ilObject::_lookupType($a_parent_obj_id); - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setLimit(9999); - - $this->setTitle($lng->txt("obj_bdga")); - - if($this->has_write) - { - $this->addColumn("", "", 1); - } - - $this->addColumn($lng->txt("title"), "title"); - $this->addColumn($lng->txt("type"), "type"); - $this->addColumn($lng->txt("active"), "active"); - - if($this->has_write) - { - $this->addColumn($lng->txt("action"), ""); - - $lng->loadLanguageModule("content"); - $this->addMultiCommand("copyBadges", $lng->txt("cont_copy_to_clipboard")); - $this->addMultiCommand("activateBadges", $lng->txt("activate")); - $this->addMultiCommand("deactivateBadges", $lng->txt("deactivate")); - $this->addMultiCommand("confirmDeleteBadges", $lng->txt("delete")); - $this->setSelectAllCheckbox("id"); - } - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.badge_row.html", "Services/Badge"); - $this->setDefaultOrderField("title"); - - $this->setFilterCommand("applyBadgeFilter"); - $this->setResetCommand("resetBadgeFilter"); - - $this->initFilter(); - - $this->getItems($a_parent_obj_id); - } - - public function initFilter() - { - $lng = $this->lng; - - $title = $this->addFilterItemByMetaType("title", self::FILTER_TEXT, false, $lng->txt("title")); - $this->filter["title"] = $title->getValue(); - - $handler = ilBadgeHandler::getInstance(); - $valid_types = $handler->getAvailableTypesForObjType($this->parent_type); - if($valid_types && - sizeof($valid_types) > 1) - { - $lng->loadLanguageModule("search"); - - $options = array("" => $lng->txt("search_any")); - foreach($valid_types as $id => $type) - { - $options[$id] = ilBadge::getExtendedTypeCaption($type); - } - asort($options); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->setId("bdgbdg"); + $this->has_write = (bool) $a_has_write; + $this->parent_type = ilObject::_lookupType($a_parent_obj_id); + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setLimit(9999); + + $this->setTitle($lng->txt("obj_bdga")); + + if ($this->has_write) { + $this->addColumn("", "", 1); + } + + $this->addColumn($lng->txt("title"), "title"); + $this->addColumn($lng->txt("type"), "type"); + $this->addColumn($lng->txt("active"), "active"); + + if ($this->has_write) { + $this->addColumn($lng->txt("action"), ""); + + $lng->loadLanguageModule("content"); + $this->addMultiCommand("copyBadges", $lng->txt("cont_copy_to_clipboard")); + $this->addMultiCommand("activateBadges", $lng->txt("activate")); + $this->addMultiCommand("deactivateBadges", $lng->txt("deactivate")); + $this->addMultiCommand("confirmDeleteBadges", $lng->txt("delete")); + $this->setSelectAllCheckbox("id"); + } + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.badge_row.html", "Services/Badge"); + $this->setDefaultOrderField("title"); + + $this->setFilterCommand("applyBadgeFilter"); + $this->setResetCommand("resetBadgeFilter"); + + $this->initFilter(); + + $this->getItems($a_parent_obj_id); + } + + public function initFilter() + { + $lng = $this->lng; + + $title = $this->addFilterItemByMetaType("title", self::FILTER_TEXT, false, $lng->txt("title")); + $this->filter["title"] = $title->getValue(); + + $handler = ilBadgeHandler::getInstance(); + $valid_types = $handler->getAvailableTypesForObjType($this->parent_type); + if ($valid_types && + sizeof($valid_types) > 1) { + $lng->loadLanguageModule("search"); + + $options = array("" => $lng->txt("search_any")); + foreach ($valid_types as $id => $type) { + $options[$id] = ilBadge::getExtendedTypeCaption($type); + } + asort($options); - $type = $this->addFilterItemByMetaType("type", self::FILTER_SELECT, false, $lng->txt("type")); - $type->setOptions($options); - $this->filter["type"] = $type->getValue(); - } - } - - function getItems($a_parent_obj_id) - { - $data = array(); - - include_once "Services/Badge/classes/class.ilBadgeRenderer.php"; - - foreach(ilBadge::getInstancesByParentId($a_parent_obj_id, $this->filter) as $badge) - { - $data[] = array( - "id" => $badge->getId(), - "title" => $badge->getTitle(), - "active" => $badge->isActive(), - "type" => ($this->parent_type != "bdga") - ? ilBadge::getExtendedTypeCaption($badge->getTypeInstance()) - : $badge->getTypeInstance()->getCaption(), - "manual" => (!$badge->getTypeInstance() instanceof ilBadgeAuto), - "renderer" => new ilBadgeRenderer(null, $badge) - ); - } - - $this->setData($data); - } - - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if($this->has_write) - { - $this->tpl->setVariable("VAL_ID", $a_set["id"]); - } - - $this->tpl->setVariable("PREVIEW", $a_set["renderer"]->getHTML()); - $this->tpl->setVariable("TXT_TITLE", $a_set["title"]); - $this->tpl->setVariable("TXT_TYPE", $a_set["type"]); - $this->tpl->setVariable("TXT_ACTIVE", $a_set["active"] - ? $lng->txt("yes") - : $lng->txt("no")); - - if($this->has_write) - { - include_once "Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"; - $actions = new ilAdvancedSelectionListGUI(); - $actions->setListTitle($lng->txt("actions")); - - if($a_set["manual"] && - $a_set["active"]) - { - $ilCtrl->setParameter($this->getParentObject(), "bid", $a_set["id"]); - $ilCtrl->setParameter($this->getParentObject(), "tgt", "bdgl"); - $url = $ilCtrl->getLinkTarget($this->getParentObject(), "awardBadgeUserSelection"); - $ilCtrl->setParameter($this->getParentObject(), "bid", ""); - $ilCtrl->setParameter($this->getParentObject(), "tgt", ""); - $actions->addItem($lng->txt("badge_award_badge"), "", $url); - } - - $ilCtrl->setParameter($this->getParentObject(), "bid", $a_set["id"]); - $url = $ilCtrl->getLinkTarget($this->getParentObject(), "editBadge"); - $ilCtrl->setParameter($this->getParentObject(), "bid", ""); - $actions->addItem($lng->txt("edit"), "", $url); - - $this->tpl->setVariable("ACTIONS", $actions->getHTML()); - } - } + $type = $this->addFilterItemByMetaType("type", self::FILTER_SELECT, false, $lng->txt("type")); + $type->setOptions($options); + $this->filter["type"] = $type->getValue(); + } + } + + public function getItems($a_parent_obj_id) + { + $data = array(); + + include_once "Services/Badge/classes/class.ilBadgeRenderer.php"; + + foreach (ilBadge::getInstancesByParentId($a_parent_obj_id, $this->filter) as $badge) { + $data[] = array( + "id" => $badge->getId(), + "title" => $badge->getTitle(), + "active" => $badge->isActive(), + "type" => ($this->parent_type != "bdga") + ? ilBadge::getExtendedTypeCaption($badge->getTypeInstance()) + : $badge->getTypeInstance()->getCaption(), + "manual" => (!$badge->getTypeInstance() instanceof ilBadgeAuto), + "renderer" => new ilBadgeRenderer(null, $badge) + ); + } + + $this->setData($data); + } + + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if ($this->has_write) { + $this->tpl->setVariable("VAL_ID", $a_set["id"]); + } + + $this->tpl->setVariable("PREVIEW", $a_set["renderer"]->getHTML()); + $this->tpl->setVariable("TXT_TITLE", $a_set["title"]); + $this->tpl->setVariable("TXT_TYPE", $a_set["type"]); + $this->tpl->setVariable("TXT_ACTIVE", $a_set["active"] + ? $lng->txt("yes") + : $lng->txt("no")); + + if ($this->has_write) { + include_once "Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"; + $actions = new ilAdvancedSelectionListGUI(); + $actions->setListTitle($lng->txt("actions")); + + if ($a_set["manual"] && + $a_set["active"]) { + $ilCtrl->setParameter($this->getParentObject(), "bid", $a_set["id"]); + $ilCtrl->setParameter($this->getParentObject(), "tgt", "bdgl"); + $url = $ilCtrl->getLinkTarget($this->getParentObject(), "awardBadgeUserSelection"); + $ilCtrl->setParameter($this->getParentObject(), "bid", ""); + $ilCtrl->setParameter($this->getParentObject(), "tgt", ""); + $actions->addItem($lng->txt("badge_award_badge"), "", $url); + } + + $ilCtrl->setParameter($this->getParentObject(), "bid", $a_set["id"]); + $url = $ilCtrl->getLinkTarget($this->getParentObject(), "editBadge"); + $ilCtrl->setParameter($this->getParentObject(), "bid", ""); + $actions->addItem($lng->txt("edit"), "", $url); + + $this->tpl->setVariable("ACTIONS", $actions->getHTML()); + } + } } diff --git a/Services/Badge/classes/class.ilBadgeTypesTableGUI.php b/Services/Badge/classes/class.ilBadgeTypesTableGUI.php index 0c42643f2aea4346d0d541a57606b02b0a3babbc..39aa5b6727cfc358e0de25554a067c92e4073536 100644 --- a/Services/Badge/classes/class.ilBadgeTypesTableGUI.php +++ b/Services/Badge/classes/class.ilBadgeTypesTableGUI.php @@ -13,99 +13,95 @@ include_once("./Services/Badge/classes/class.ilBadgeHandler.php"); * @ingroup ServicesBadge */ class ilBadgeTypesTableGUI extends ilTable2GUI -{ - /** - * @var ilCtrl - */ - protected $ctrl; +{ + /** + * @var ilCtrl + */ + protected $ctrl; - function __construct($a_parent_obj, $a_parent_cmd = "", $a_has_write) - { - global $DIC; + public function __construct($a_parent_obj, $a_parent_cmd = "", $a_has_write) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->setId("bdgtps"); - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setLimit(9999); - - $this->setTitle($lng->txt("badge_types")); - - $lng->loadLanguageModule("cmps"); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->setId("bdgtps"); + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setLimit(9999); + + $this->setTitle($lng->txt("badge_types")); + + $lng->loadLanguageModule("cmps"); - $this->addColumn("", "", 1); - $this->addColumn($lng->txt("name"), "name"); - $this->addColumn($lng->txt("cmps_component"), "comp"); - $this->addColumn($lng->txt("badge_manual"), "manual"); - $this->addColumn($lng->txt("badge_activity_badges"), "activity"); - $this->addColumn($lng->txt("active"), "inactive"); - - if((bool)$a_has_write) - { - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->addMultiCommand("activateTypes", $lng->txt("activate")); - $this->addMultiCommand("deactivateTypes", $lng->txt("deactivate")); - } - - $this->setRowTemplate("tpl.type_row.html", "Services/Badge"); - $this->setDefaultOrderField("name"); - $this->setSelectAllCheckbox("id"); - - $this->getItems(); - } - - function getItems() - { - $data = array(); - - $handler = ilBadgeHandler::getInstance(); - $inactive = $handler->getInactiveTypes(); - foreach($handler->getComponents() as $component) - { - $provider = $handler->getProviderInstance($component); - if($provider) - { - foreach($provider->getBadgeTypes() as $badge_obj) - { - $id = $handler->getUniqueTypeId($component, $badge_obj); - - $data[] = array( - "id" => $id, - "comp" => $handler->getComponentCaption($component), - "name" => $badge_obj->getCaption(), - "manual" => (!$badge_obj instanceof ilBadgeAuto), - "active" => !in_array($id, $inactive), - "activity" => in_array("bdga", $badge_obj->getValidObjectTypes()) - ); - } - } - } - - $this->setData($data); - - include_once "Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"; - } - - protected function fillRow($a_set) - { - $lng = $this->lng; - - $this->tpl->setVariable("VAL_ID", $a_set["id"]); - $this->tpl->setVariable("TXT_COMP", $a_set["comp"]); - $this->tpl->setVariable("TXT_NAME", $a_set["name"]); - $this->tpl->setVariable("TXT_MANUAL", $a_set["manual"] - ? $lng->txt("yes") - : $lng->txt("no")); - $this->tpl->setVariable("TXT_ACTIVE", $a_set["active"] - ? $lng->txt("yes") - : $lng->txt("no")); - $this->tpl->setVariable("TXT_ACTIVITY", $a_set["activity"] - ? $lng->txt("yes") - : $lng->txt("no")); - } + $this->addColumn("", "", 1); + $this->addColumn($lng->txt("name"), "name"); + $this->addColumn($lng->txt("cmps_component"), "comp"); + $this->addColumn($lng->txt("badge_manual"), "manual"); + $this->addColumn($lng->txt("badge_activity_badges"), "activity"); + $this->addColumn($lng->txt("active"), "inactive"); + + if ((bool) $a_has_write) { + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->addMultiCommand("activateTypes", $lng->txt("activate")); + $this->addMultiCommand("deactivateTypes", $lng->txt("deactivate")); + } + + $this->setRowTemplate("tpl.type_row.html", "Services/Badge"); + $this->setDefaultOrderField("name"); + $this->setSelectAllCheckbox("id"); + + $this->getItems(); + } + + public function getItems() + { + $data = array(); + + $handler = ilBadgeHandler::getInstance(); + $inactive = $handler->getInactiveTypes(); + foreach ($handler->getComponents() as $component) { + $provider = $handler->getProviderInstance($component); + if ($provider) { + foreach ($provider->getBadgeTypes() as $badge_obj) { + $id = $handler->getUniqueTypeId($component, $badge_obj); + + $data[] = array( + "id" => $id, + "comp" => $handler->getComponentCaption($component), + "name" => $badge_obj->getCaption(), + "manual" => (!$badge_obj instanceof ilBadgeAuto), + "active" => !in_array($id, $inactive), + "activity" => in_array("bdga", $badge_obj->getValidObjectTypes()) + ); + } + } + } + + $this->setData($data); + + include_once "Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"; + } + + protected function fillRow($a_set) + { + $lng = $this->lng; + + $this->tpl->setVariable("VAL_ID", $a_set["id"]); + $this->tpl->setVariable("TXT_COMP", $a_set["comp"]); + $this->tpl->setVariable("TXT_NAME", $a_set["name"]); + $this->tpl->setVariable("TXT_MANUAL", $a_set["manual"] + ? $lng->txt("yes") + : $lng->txt("no")); + $this->tpl->setVariable("TXT_ACTIVE", $a_set["active"] + ? $lng->txt("yes") + : $lng->txt("no")); + $this->tpl->setVariable("TXT_ACTIVITY", $a_set["activity"] + ? $lng->txt("yes") + : $lng->txt("no")); + } } diff --git a/Services/Badge/classes/class.ilBadgeUserTableGUI.php b/Services/Badge/classes/class.ilBadgeUserTableGUI.php index e6f3ee1cfe2ff501a39d7338bc913d1f1bd3cb8c..7afa3d27c819fac13f38ce8447a765a505fbf11e 100644 --- a/Services/Badge/classes/class.ilBadgeUserTableGUI.php +++ b/Services/Badge/classes/class.ilBadgeUserTableGUI.php @@ -12,264 +12,238 @@ include_once("Services/Table/classes/class.ilTable2GUI.php"); * @ingroup ServicesBadge */ class ilBadgeUserTableGUI extends ilTable2GUI -{ - /** - * @var ilCtrl - */ - protected $ctrl; +{ + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilTree - */ - protected $tree; + /** + * @var ilTree + */ + protected $tree; - protected $award_badge; // [ilBadge] - protected $do_parent; // [bool] - - function __construct($a_parent_obj, $a_parent_cmd = "", $a_parent_ref_id, ilBadge $a_award_bagde = null, $a_parent_obj_id = null, $a_restrict_badge_id = null) - { - global $DIC; + protected $award_badge; // [ilBadge] + protected $do_parent; // [bool] + + public function __construct($a_parent_obj, $a_parent_cmd = "", $a_parent_ref_id, ilBadge $a_award_bagde = null, $a_parent_obj_id = null, $a_restrict_badge_id = null) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->tree = $DIC->repositoryTree(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->setId("bdgusr"); - $this->award_badge = $a_award_bagde; - $this->do_parent = false; - - $parent_type = ilObject::_lookupType($a_parent_ref_id, true); - if(in_array($parent_type, array("grp", "crs"))) - { - $this->do_parent = (!$a_parent_obj_id && !$this->award_badge); - } + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->tree = $DIC->repositoryTree(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->setId("bdgusr"); + $this->award_badge = $a_award_bagde; + $this->do_parent = false; + + $parent_type = ilObject::_lookupType($a_parent_ref_id, true); + if (in_array($parent_type, array("grp", "crs"))) { + $this->do_parent = (!$a_parent_obj_id && !$this->award_badge); + } - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setLimit(9999); - - if($this->award_badge) - { - $this->setTitle($lng->txt("badge_award_badge").": ".$a_award_bagde->getTitle()); - $this->setDescription($a_award_bagde->getDescription()); - - $this->addColumn("", "", 1); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->addMultiCommand("assignBadge", $lng->txt("badge_award_badge")); - $this->addMultiCommand("confirmDeassignBadge", $lng->txt("badge_remove_badge")); - } - else - { - $parent = ""; - if($a_parent_obj_id) - { - $title = ilObject::_lookupTitle($a_parent_obj_id); - if(!$title) - { - include_once "Services/Object/classes/class.ilObjectDataDeletionLog.php"; - $title = ilObjectDataDeletionLog::get($a_parent_obj_id); - if($title) - { - $title = $title["title"]; - } - } - if($a_restrict_badge_id) - { - include_once("Services/Badge/classes/class.ilBadge.php"); - $badge = new ilBadge($a_restrict_badge_id); - $title .= " - ".$badge->getTitle(); - } - $parent = $title.": "; - } - $this->setTitle($parent.$lng->txt("users")); - } - - $this->addColumn($lng->txt("name"), "name"); - $this->addColumn($lng->txt("login"), "login"); - $this->addColumn($lng->txt("type"), "type"); - $this->addColumn($lng->txt("title"), "title"); - $this->addColumn($lng->txt("badge_issued_on"), "issued"); - - if($this->do_parent) - { - $this->addColumn($lng->txt("object"), "parent_id"); - } - - $this->setDefaultOrderField("name"); - - $this->setRowTemplate("tpl.user_row.html", "Services/Badge"); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setFilterCommand("apply".ucfirst($this->getParentCmd())); - $this->setResetCommand("reset".ucfirst($this->getParentCmd())); + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setLimit(9999); + + if ($this->award_badge) { + $this->setTitle($lng->txt("badge_award_badge") . ": " . $a_award_bagde->getTitle()); + $this->setDescription($a_award_bagde->getDescription()); + + $this->addColumn("", "", 1); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->addMultiCommand("assignBadge", $lng->txt("badge_award_badge")); + $this->addMultiCommand("confirmDeassignBadge", $lng->txt("badge_remove_badge")); + } else { + $parent = ""; + if ($a_parent_obj_id) { + $title = ilObject::_lookupTitle($a_parent_obj_id); + if (!$title) { + include_once "Services/Object/classes/class.ilObjectDataDeletionLog.php"; + $title = ilObjectDataDeletionLog::get($a_parent_obj_id); + if ($title) { + $title = $title["title"]; + } + } + if ($a_restrict_badge_id) { + include_once("Services/Badge/classes/class.ilBadge.php"); + $badge = new ilBadge($a_restrict_badge_id); + $title .= " - " . $badge->getTitle(); + } + $parent = $title . ": "; + } + $this->setTitle($parent . $lng->txt("users")); + } + + $this->addColumn($lng->txt("name"), "name"); + $this->addColumn($lng->txt("login"), "login"); + $this->addColumn($lng->txt("type"), "type"); + $this->addColumn($lng->txt("title"), "title"); + $this->addColumn($lng->txt("badge_issued_on"), "issued"); + + if ($this->do_parent) { + $this->addColumn($lng->txt("object"), "parent_id"); + } + + $this->setDefaultOrderField("name"); + + $this->setRowTemplate("tpl.user_row.html", "Services/Badge"); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setFilterCommand("apply" . ucfirst($this->getParentCmd())); + $this->setResetCommand("reset" . ucfirst($this->getParentCmd())); - $this->initFilter(); - - $this->getItems($a_parent_ref_id, $this->award_badge, $a_parent_obj_id, $a_restrict_badge_id); - } - - public function initFilter() - { - $lng = $this->lng; - - $name = $this->addFilterItemByMetaType("name", self::FILTER_TEXT, false, $lng->txt("name")); - $this->filter["name"] = $name->getValue(); - } - - function getItems($a_parent_ref_id, ilBadge $a_award_bagde = null, $a_parent_obj_id = null, $a_restrict_badge_id = null) - { - $tree = $this->tree; - - $data = array(); - - if(!$a_parent_obj_id) - { - $a_parent_obj_id = ilObject::_lookupObjId($a_parent_ref_id); - } - - // repository context: walk tree for available users - if($a_parent_ref_id) - { - $user_ids = ilBadgeHandler::getInstance()->getUserIds($a_parent_ref_id, $a_parent_obj_id); - } + $this->initFilter(); + + $this->getItems($a_parent_ref_id, $this->award_badge, $a_parent_obj_id, $a_restrict_badge_id); + } + + public function initFilter() + { + $lng = $this->lng; + + $name = $this->addFilterItemByMetaType("name", self::FILTER_TEXT, false, $lng->txt("name")); + $this->filter["name"] = $name->getValue(); + } + + public function getItems($a_parent_ref_id, ilBadge $a_award_bagde = null, $a_parent_obj_id = null, $a_restrict_badge_id = null) + { + $tree = $this->tree; + + $data = array(); + + if (!$a_parent_obj_id) { + $a_parent_obj_id = ilObject::_lookupObjId($a_parent_ref_id); + } + + // repository context: walk tree for available users + if ($a_parent_ref_id) { + $user_ids = ilBadgeHandler::getInstance()->getUserIds($a_parent_ref_id, $a_parent_obj_id); + } - $obj_ids = array($a_parent_obj_id); - - // add sub-items - if($this->do_parent) - { - foreach($tree->getSubTree($tree->getNodeData($a_parent_ref_id)) as $node) - { - $obj_ids[] = $node["obj_id"]; - } - } - - include_once "Services/Badge/classes/class.ilBadge.php"; - include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; - $badges = $assignments = array(); - foreach($obj_ids as $obj_id) - { - foreach(ilBadge::getInstancesByParentId($obj_id) as $badge) - { - $badges[$badge->getId()] = $badge; - } + $obj_ids = array($a_parent_obj_id); + + // add sub-items + if ($this->do_parent) { + foreach ($tree->getSubTree($tree->getNodeData($a_parent_ref_id)) as $node) { + $obj_ids[] = $node["obj_id"]; + } + } + + include_once "Services/Badge/classes/class.ilBadge.php"; + include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; + $badges = $assignments = array(); + foreach ($obj_ids as $obj_id) { + foreach (ilBadge::getInstancesByParentId($obj_id) as $badge) { + $badges[$badge->getId()] = $badge; + } - foreach(ilBadgeAssignment::getInstancesByParentId($obj_id) as $ass) - { - if($a_restrict_badge_id && - $a_restrict_badge_id != $ass->getBadgeId()) - { - continue; - } - - // when awarding we only want to see the current badge - if($this->award_badge && - $ass->getBadgeId() != $this->award_badge->getId()) - { - continue; - } + foreach (ilBadgeAssignment::getInstancesByParentId($obj_id) as $ass) { + if ($a_restrict_badge_id && + $a_restrict_badge_id != $ass->getBadgeId()) { + continue; + } + + // when awarding we only want to see the current badge + if ($this->award_badge && + $ass->getBadgeId() != $this->award_badge->getId()) { + continue; + } - $assignments[$ass->getUserId()][] = $ass; - } - } + $assignments[$ass->getUserId()][] = $ass; + } + } - // administration context: show only existing assignments - if(!$user_ids) - { - $user_ids = array_keys($assignments); - } + // administration context: show only existing assignments + if (!$user_ids) { + $user_ids = array_keys($assignments); + } - include_once "Services/Badge/classes/class.ilBadgeRenderer.php"; - include_once "Services/User/classes/class.ilUserQuery.php"; - $tmp["set"] = array(); - if (count($user_ids) > 0) - { - $uquery = new ilUserQuery(); - $uquery->setLimit(9999); - $uquery->setUserFilter($user_ids); + include_once "Services/Badge/classes/class.ilBadgeRenderer.php"; + include_once "Services/User/classes/class.ilUserQuery.php"; + $tmp["set"] = array(); + if (count($user_ids) > 0) { + $uquery = new ilUserQuery(); + $uquery->setLimit(9999); + $uquery->setUserFilter($user_ids); - if ($this->filter["name"]) - { - $uquery->setTextFilter($this->filter["name"]); - } + if ($this->filter["name"]) { + $uquery->setTextFilter($this->filter["name"]); + } - $tmp = $uquery->query(); - } - foreach($tmp["set"] as $user) - { - // add 1 entry for each badge - if(array_key_exists($user["usr_id"], $assignments)) - { - foreach($assignments[$user["usr_id"]] as $user_ass) - { - $idx = $user_ass->getBadgeId()."-".$user["usr_id"]; - - $badge = $badges[$user_ass->getBadgeId()]; - - if($this->do_parent) - { - $parent = $badge->getParentMeta(); - } - - $data[$idx] = array( - "user_id" => $user["usr_id"], - "name" => $user["lastname"].", ".$user["firstname"], - "login" => $user["login"], - "type" => ilBadge::getExtendedTypeCaption($badge->getTypeInstance()), - "title" => $badge->getTitle(), - "issued" => $user_ass->getTimestamp(), - "parent_id" => $parent["id"], - "parent_meta" => $parent - ); - } - } - // no badge yet, add dummy entry (for manual awarding) - else if($this->award_badge) - { - $idx = "0-".$user["usr_id"]; - - $data[$idx] = array( - "user_id" => $user["usr_id"], - "name" => $user["lastname"].", ".$user["firstname"], - "login" => $user["login"], - "type" => "", - "title" => "", - "issued" => "", - "parent_id" => "" - ); - } - } - - $this->setData($data); - } - - protected function fillRow($a_set) - { - $lng = $this->lng; - - if($this->award_badge) - { - $this->tpl->setVariable("VAL_ID", $a_set["user_id"]); - } - - $this->tpl->setVariable("TXT_NAME", $a_set["name"]); - $this->tpl->setVariable("TXT_LOGIN", $a_set["login"]); - $this->tpl->setVariable("TXT_TYPE", $a_set["type"]); - $this->tpl->setVariable("TXT_TITLE", $a_set["title"]); - $this->tpl->setVariable("TXT_ISSUED", $a_set["issued"] - ? ilDatePresentation::formatDate(new ilDateTime($a_set["issued"], IL_CAL_UNIX)) - : ""); - - if($a_set["parent_id"]) - { - $parent = $a_set["parent_meta"]; - $this->tpl->setVariable("PARENT", $parent["title"]); - $this->tpl->setVariable("PARENT_TYPE", $lng->txt("obj_".$parent["type"])); - $this->tpl->setVariable("PARENT_ICON", - ilObject::_getIcon($parent["id"], "big", $parent["type"])); - } - } + $tmp = $uquery->query(); + } + foreach ($tmp["set"] as $user) { + // add 1 entry for each badge + if (array_key_exists($user["usr_id"], $assignments)) { + foreach ($assignments[$user["usr_id"]] as $user_ass) { + $idx = $user_ass->getBadgeId() . "-" . $user["usr_id"]; + + $badge = $badges[$user_ass->getBadgeId()]; + + if ($this->do_parent) { + $parent = $badge->getParentMeta(); + } + + $data[$idx] = array( + "user_id" => $user["usr_id"], + "name" => $user["lastname"] . ", " . $user["firstname"], + "login" => $user["login"], + "type" => ilBadge::getExtendedTypeCaption($badge->getTypeInstance()), + "title" => $badge->getTitle(), + "issued" => $user_ass->getTimestamp(), + "parent_id" => $parent["id"], + "parent_meta" => $parent + ); + } + } + // no badge yet, add dummy entry (for manual awarding) + elseif ($this->award_badge) { + $idx = "0-" . $user["usr_id"]; + + $data[$idx] = array( + "user_id" => $user["usr_id"], + "name" => $user["lastname"] . ", " . $user["firstname"], + "login" => $user["login"], + "type" => "", + "title" => "", + "issued" => "", + "parent_id" => "" + ); + } + } + + $this->setData($data); + } + + protected function fillRow($a_set) + { + $lng = $this->lng; + + if ($this->award_badge) { + $this->tpl->setVariable("VAL_ID", $a_set["user_id"]); + } + + $this->tpl->setVariable("TXT_NAME", $a_set["name"]); + $this->tpl->setVariable("TXT_LOGIN", $a_set["login"]); + $this->tpl->setVariable("TXT_TYPE", $a_set["type"]); + $this->tpl->setVariable("TXT_TITLE", $a_set["title"]); + $this->tpl->setVariable("TXT_ISSUED", $a_set["issued"] + ? ilDatePresentation::formatDate(new ilDateTime($a_set["issued"], IL_CAL_UNIX)) + : ""); + + if ($a_set["parent_id"]) { + $parent = $a_set["parent_meta"]; + $this->tpl->setVariable("PARENT", $parent["title"]); + $this->tpl->setVariable("PARENT_TYPE", $lng->txt("obj_" . $parent["type"])); + $this->tpl->setVariable( + "PARENT_ICON", + ilObject::_getIcon($parent["id"], "big", $parent["type"]) + ); + } + } } diff --git a/Services/Badge/classes/class.ilBadgeWAC.php b/Services/Badge/classes/class.ilBadgeWAC.php index 8505dbaf824d9b3f65291bae7d91d15ec2f2695b..4866ce8bfc2e0232ecac78d41f91263058b26096 100644 --- a/Services/Badge/classes/class.ilBadgeWAC.php +++ b/Services/Badge/classes/class.ilBadgeWAC.php @@ -5,16 +5,16 @@ require_once('./Services/WebAccessChecker/interfaces/interface.ilWACCheckingClas /** * Class ilBadgeHandler - * + * * @author Jörg Lützenkirchen * @version $Id:$ * * @package ServicesBadge */ class ilBadgeWAC implements ilWACCheckingClass -{ - public function canBeDelivered(ilWACPath $ilWACPath) - { - return true; - } -} \ No newline at end of file +{ + public function canBeDelivered(ilWACPath $ilWACPath) + { + return true; + } +} diff --git a/Services/Badge/classes/class.ilFSStorageBadge.php b/Services/Badge/classes/class.ilFSStorageBadge.php index 9175aa8bf70a8bcf12a29291c68871fb552bca09..339181be0d2cb4331a700f455543a3c7d76c4438 100644 --- a/Services/Badge/classes/class.ilFSStorageBadge.php +++ b/Services/Badge/classes/class.ilFSStorageBadge.php @@ -3,27 +3,27 @@ include_once('Services/FileSystem/classes/class.ilFileSystemStorage.php'); -/** -* +/** +* * @author Jörg Lützenkirchen * @version $Id$ -* +* * @ingroup ServicesBadge */ class ilFSStorageBadge extends ilFileSystemStorage { - public function __construct($a_container_id = 0) - { - parent::__construct(self::STORAGE_SECURED, true, $a_container_id); - } - - protected function getPathPostfix() - { - return 'badge'; - } - - protected function getPathPrefix() - { - return 'ilBadge'; - } + public function __construct($a_container_id = 0) + { + parent::__construct(self::STORAGE_SECURED, true, $a_container_id); + } + + protected function getPathPostfix() + { + return 'badge'; + } + + protected function getPathPrefix() + { + return 'ilBadge'; + } } diff --git a/Services/Badge/classes/class.ilFSStorageBadgeImageTemplate.php b/Services/Badge/classes/class.ilFSStorageBadgeImageTemplate.php index db56caa6eb938529115355e45a05965ccf52864d..b980885334710f99a2847e4ca8164398d5275cd2 100644 --- a/Services/Badge/classes/class.ilFSStorageBadgeImageTemplate.php +++ b/Services/Badge/classes/class.ilFSStorageBadgeImageTemplate.php @@ -3,27 +3,27 @@ include_once('Services/FileSystem/classes/class.ilFileSystemStorage.php'); -/** -* +/** +* * @author Jörg Lützenkirchen * @version $Id$ -* +* * @ingroup ServicesBadge */ class ilFSStorageBadgeImageTemplate extends ilFileSystemStorage { - public function __construct($a_container_id = 0) - { - parent::__construct(self::STORAGE_SECURED, true, $a_container_id); - } - - protected function getPathPostfix() - { - return 'badgetmpl'; - } - - protected function getPathPrefix() - { - return 'ilBadge'; - } + public function __construct($a_container_id = 0) + { + parent::__construct(self::STORAGE_SECURED, true, $a_container_id); + } + + protected function getPathPostfix() + { + return 'badgetmpl'; + } + + protected function getPathPrefix() + { + return 'ilBadge'; + } } diff --git a/Services/Badge/classes/class.ilObjBadgeAdministration.php b/Services/Badge/classes/class.ilObjBadgeAdministration.php index 6793845760f9d44c16ee407108023381ef55ccaf..7436869e7d840470eab0ed8882e0276ad6ca1c99 100644 --- a/Services/Badge/classes/class.ilObjBadgeAdministration.php +++ b/Services/Badge/classes/class.ilObjBadgeAdministration.php @@ -5,27 +5,26 @@ require_once "./Services/Object/classes/class.ilObject.php"; /** * Class ilObjBadgeAdministration - * + * * @author Jörg Lützenkirchen * @version $Id:$ * * @package ServicesBadge */ class ilObjBadgeAdministration extends ilObject -{ - public function __construct($a_id = 0, $a_call_by_reference = true) - { - $this->type = "bdga"; - parent::__construct($a_id,$a_call_by_reference); - } +{ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + $this->type = "bdga"; + parent::__construct($a_id, $a_call_by_reference); + } - public function update() - { - if (!parent::update()) - { - return false; - } + public function update() + { + if (!parent::update()) { + return false; + } - return true; - } -} \ No newline at end of file + return true; + } +} diff --git a/Services/Badge/classes/class.ilObjBadgeAdministrationAccess.php b/Services/Badge/classes/class.ilObjBadgeAdministrationAccess.php index 6b8cbaa37d2b1d64ddf0d6e028ebde890c2be9de..df67de3c4c3467d4c5d415c8cf1578124fedb0a6 100644 --- a/Services/Badge/classes/class.ilObjBadgeAdministrationAccess.php +++ b/Services/Badge/classes/class.ilObjBadgeAdministrationAccess.php @@ -13,6 +13,4 @@ include_once("./Services/Object/classes/class.ilObjectAccess.php"); */ class ilObjBadgeAdministrationAccess extends ilObjectAccess { - - } diff --git a/Services/Badge/classes/class.ilObjBadgeAdministrationGUI.php b/Services/Badge/classes/class.ilObjBadgeAdministrationGUI.php index 690394ac5db6c0dac8ea8c298c92b984ba576063..56ff340d6dd7c30cbf830bdd9cf9e73f39a6ff87 100644 --- a/Services/Badge/classes/class.ilObjBadgeAdministrationGUI.php +++ b/Services/Badge/classes/class.ilObjBadgeAdministrationGUI.php @@ -16,759 +16,755 @@ include_once("./Services/Badge/classes/class.ilBadgeHandler.php"); * @ingroup ServicesBadge */ class ilObjBadgeAdministrationGUI extends ilObjectGUI -{ - /** - * @var ilRbacSystem - */ - protected $rbacsystem; +{ + /** + * @var ilRbacSystem + */ + protected $rbacsystem; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * @var ilToolbarGUI - */ - protected $toolbar; + /** + * @var ilToolbarGUI + */ + protected $toolbar; - /** - * @var ilTabsGUI - */ - protected $tabs; + /** + * @var ilTabsGUI + */ + protected $tabs; - public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) - { - global $DIC; + public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) + { + global $DIC; - $this->rbacsystem = $DIC->rbac()->system(); - $this->ctrl = $DIC->ctrl(); - $this->access = $DIC->access(); - $this->lng = $DIC->language(); - $this->toolbar = $DIC->toolbar(); - $this->tpl = $DIC["tpl"]; - $this->tabs = $DIC->tabs(); - $this->type = "bdga"; - parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); + $this->rbacsystem = $DIC->rbac()->system(); + $this->ctrl = $DIC->ctrl(); + $this->access = $DIC->access(); + $this->lng = $DIC->language(); + $this->toolbar = $DIC->toolbar(); + $this->tpl = $DIC["tpl"]; + $this->tabs = $DIC->tabs(); + $this->type = "bdga"; + parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); - $this->lng->loadLanguageModule("badge"); - } + $this->lng->loadLanguageModule("badge"); + } - public function executeCommand() - { - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); + public function executeCommand() + { + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); - $this->prepareOutput(); + $this->prepareOutput(); - switch($next_class) - { - case 'ilpermissiongui': - $this->tabs_gui->setTabActive('perm_settings'); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $this->ctrl->forwardCommand($perm_gui); - break; - - case 'ilbadgemanagementgui': - $this->assertActive(); - $this->tabs_gui->setTabActive('activity'); - include_once "Services/Badge/classes/class.ilBadgeManagementGUI.php"; - $gui = new ilBadgeManagementGUI($this->ref_id, $this->obj_id, $this->type); - $this->ctrl->forwardCommand($gui); - break; + switch ($next_class) { + case 'ilpermissiongui': + $this->tabs_gui->setTabActive('perm_settings'); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $this->ctrl->forwardCommand($perm_gui); + break; + + case 'ilbadgemanagementgui': + $this->assertActive(); + $this->tabs_gui->setTabActive('activity'); + include_once "Services/Badge/classes/class.ilBadgeManagementGUI.php"; + $gui = new ilBadgeManagementGUI($this->ref_id, $this->obj_id, $this->type); + $this->ctrl->forwardCommand($gui); + break; - default: - if(!$cmd || $cmd == 'view') - { - $cmd = "editSettings"; - } + default: + if (!$cmd || $cmd == 'view') { + $cmd = "editSettings"; + } - $this->$cmd(); - break; - } - return true; - } + $this->$cmd(); + break; + } + return true; + } - public function getAdminTabs() - { - $rbacsystem = $this->rbacsystem; + public function getAdminTabs() + { + $rbacsystem = $this->rbacsystem; - if ($rbacsystem->checkAccess("visible,read",$this->object->getRefId())) - { - $this->tabs_gui->addTab("settings", - $this->lng->txt("settings"), - $this->ctrl->getLinkTarget($this, "editSettings")); - - if(ilBadgeHandler::getInstance()->isActive()) - { - $this->tabs_gui->addTab("types", - $this->lng->txt("badge_types"), - $this->ctrl->getLinkTarget($this, "listTypes")); + if ($rbacsystem->checkAccess("visible,read", $this->object->getRefId())) { + $this->tabs_gui->addTab( + "settings", + $this->lng->txt("settings"), + $this->ctrl->getLinkTarget($this, "editSettings") + ); + + if (ilBadgeHandler::getInstance()->isActive()) { + $this->tabs_gui->addTab( + "types", + $this->lng->txt("badge_types"), + $this->ctrl->getLinkTarget($this, "listTypes") + ); - $this->tabs_gui->addTab("imgtmpl", - $this->lng->txt("badge_image_templates"), - $this->ctrl->getLinkTarget($this, "listImageTemplates")); + $this->tabs_gui->addTab( + "imgtmpl", + $this->lng->txt("badge_image_templates"), + $this->ctrl->getLinkTarget($this, "listImageTemplates") + ); - $this->tabs_gui->addTab("activity", - $this->lng->txt("badge_activity_badges"), - $this->ctrl->getLinkTargetByClass("ilbadgemanagementgui", "")); - - $this->tabs_gui->addTab("obj_badges", - $this->lng->txt("badge_object_badges"), - $this->ctrl->getLinkTarget($this, "listObjectBadges")); - } - } + $this->tabs_gui->addTab( + "activity", + $this->lng->txt("badge_activity_badges"), + $this->ctrl->getLinkTargetByClass("ilbadgemanagementgui", "") + ); + + $this->tabs_gui->addTab( + "obj_badges", + $this->lng->txt("badge_object_badges"), + $this->ctrl->getLinkTarget($this, "listObjectBadges") + ); + } + } - if ($rbacsystem->checkAccess('edit_permission',$this->object->getRefId())) - { - $this->tabs_gui->addTab("perm_settings", - $this->lng->txt("perm_settings"), - $this->ctrl->getLinkTargetByClass('ilpermissiongui',"perm")); - } - } - - protected function assertActive() - { - if(!ilBadgeHandler::getInstance()->isActive()) - { - $this->ctrl->redirect($this, "editSettings"); - } - } - - - // - // settings - // + if ($rbacsystem->checkAccess('edit_permission', $this->object->getRefId())) { + $this->tabs_gui->addTab( + "perm_settings", + $this->lng->txt("perm_settings"), + $this->ctrl->getLinkTargetByClass('ilpermissiongui', "perm") + ); + } + } + + protected function assertActive() + { + if (!ilBadgeHandler::getInstance()->isActive()) { + $this->ctrl->redirect($this, "editSettings"); + } + } + + + // + // settings + // - protected function editSettings($a_form = null) - { - $this->tabs_gui->setTabActive("settings"); - - if(!$a_form) - { - $a_form = $this->initFormSettings(); - } - - $this->tpl->setContent($a_form->getHTML()); - } + protected function editSettings($a_form = null) + { + $this->tabs_gui->setTabActive("settings"); + + if (!$a_form) { + $a_form = $this->initFormSettings(); + } + + $this->tpl->setContent($a_form->getHTML()); + } - protected function saveSettings() - { - $ilCtrl = $this->ctrl; - - $this->checkPermission("write"); - - $form = $this->initFormSettings(); - if($form->checkInput()) - { - $obi = (bool)$form->getInput("act") - ? (bool)$form->getInput("obi") - : null; - - $handler = ilBadgeHandler::getInstance(); - $handler->setActive((bool)$form->getInput("act")); - $handler->setObiActive($obi); - $handler->setObiOrganisation(trim($form->getInput("obi_org"))); - $handler->setObiContact(trim($form->getInput("obi_cont"))); - $handler->setObiSalt(trim($form->getInput("obi_salt"))); - - $handler->rebuildIssuerStaticUrl(); - - ilUtil::sendSuccess($this->lng->txt("settings_saved"),true); - $ilCtrl->redirect($this, "editSettings"); - } - - $form->setValuesByPost(); - $this->editSettings($form); - } + protected function saveSettings() + { + $ilCtrl = $this->ctrl; + + $this->checkPermission("write"); + + $form = $this->initFormSettings(); + if ($form->checkInput()) { + $obi = (bool) $form->getInput("act") + ? (bool) $form->getInput("obi") + : null; + + $handler = ilBadgeHandler::getInstance(); + $handler->setActive((bool) $form->getInput("act")); + $handler->setObiActive($obi); + $handler->setObiOrganisation(trim($form->getInput("obi_org"))); + $handler->setObiContact(trim($form->getInput("obi_cont"))); + $handler->setObiSalt(trim($form->getInput("obi_salt"))); + + $handler->rebuildIssuerStaticUrl(); + + ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "editSettings"); + } + + $form->setValuesByPost(); + $this->editSettings($form); + } - protected function initFormSettings() - { - $ilAccess = $this->access; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - $form->setTitle($this->lng->txt("badge_settings")); - - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - $form->addCommandButton("saveSettings", $this->lng->txt("save")); - $form->addCommandButton("editSettings", $this->lng->txt("cancel")); - } + protected function initFormSettings() + { + $ilAccess = $this->access; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this)); + $form->setTitle($this->lng->txt("badge_settings")); + + if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) { + $form->addCommandButton("saveSettings", $this->lng->txt("save")); + $form->addCommandButton("editSettings", $this->lng->txt("cancel")); + } - $act = new ilCheckboxInputGUI($this->lng->txt("badge_service_activate"), "act"); - $act->setInfo($this->lng->txt("badge_service_activate_info")); - $form->addItem($act); + $act = new ilCheckboxInputGUI($this->lng->txt("badge_service_activate"), "act"); + $act->setInfo($this->lng->txt("badge_service_activate_info")); + $form->addItem($act); - /* see bug #0020124 - $obi = new ilCheckboxInputGUI($this->lng->txt("badge_obi_activate"), "obi"); - $obi->setInfo($this->lng->txt("badge_obi_activate_info")); - $form->addItem($obi); - - $obi_org = new ilTextInputGUI($this->lng->txt("badge_obi_organisation"), "obi_org"); - $obi_org->setRequired(true); - $obi_org->setInfo($this->lng->txt("badge_obi_organisation_info")); - $obi->addSubItem($obi_org); - - $obi_contact = new ilEmailInputGUI($this->lng->txt("badge_obi_contact"), "obi_cont"); - $obi_contact->setRequired(true); - $obi_contact->setInfo($this->lng->txt("badge_obi_contact_info")); - $obi->addSubItem($obi_contact); - - $obi_salt = new ilTextInputGUI($this->lng->txt("badge_obi_salt"), "obi_salt"); - $obi_salt->setRequired(true); - $obi_salt->setInfo($this->lng->txt("badge_obi_salt_info")); - $obi->addSubItem($obi_salt); - */ + /* see bug #0020124 + $obi = new ilCheckboxInputGUI($this->lng->txt("badge_obi_activate"), "obi"); + $obi->setInfo($this->lng->txt("badge_obi_activate_info")); + $form->addItem($obi); - $handler = ilBadgeHandler::getInstance(); - $act->setChecked($handler->isActive()); + $obi_org = new ilTextInputGUI($this->lng->txt("badge_obi_organisation"), "obi_org"); + $obi_org->setRequired(true); + $obi_org->setInfo($this->lng->txt("badge_obi_organisation_info")); + $obi->addSubItem($obi_org); - /* see bug 0020124 - $obi->setChecked($handler->isObiActive()); - $obi_org->setValue($handler->getObiOrganistation()); - $obi_contact->setValue($handler->getObiContact()); - $obi_salt->setValue($handler->getObiSalt()); - */ - - return $form; - } - - - // - // types - // - - protected function listTypes() - { - $ilAccess = $this->access; - - $this->assertActive(); - $this->tabs_gui->setTabActive("types"); - - include_once "Services/Badge/classes/class.ilBadgeTypesTableGUI.php"; - $tbl = new ilBadgeTypesTableGUI($this, "listTypes", - $ilAccess->checkAccess("write", "", $this->object->getRefId())); - $this->tpl->setContent($tbl->getHTML()); - } - - protected function activateTypes() - { - $lng = $this->lng; - - $this->assertActive(); - - $ids = $_POST["id"]; - if ($this->checkPermissionBool("write") && is_array($ids) && count($ids) > 0) { - $handler = ilBadgeHandler::getInstance(); - $inactive = array(); - foreach($handler->getInactiveTypes() as $type) - { - if(!in_array($type, $ids)) - { - $inactive[] = $type; - } - } - $handler->setInactiveTypes($inactive); - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - } - $this->ctrl->redirect($this, "listTypes"); - } - - protected function deactivateTypes() - { - $lng = $this->lng; - - $this->assertActive(); - - $ids = $_POST["id"]; - if ($this->checkPermissionBool("write") && is_array($ids) && count($ids) > 0) { - $handler = ilBadgeHandler::getInstance(); - $inactive = array_merge($handler->getInactiveTypes(), $ids); - $handler->setInactiveTypes($inactive); - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - } - $this->ctrl->redirect($this, "listTypes"); - } - - - // - // images templates - // - - protected function listImageTemplates() - { - $ilAccess = $this->access; - $lng = $this->lng; - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - - $this->assertActive(); - $this->tabs_gui->setTabActive("imgtmpl"); - - if($this->checkPermissionBool("write")) - { - $ilToolbar->addButton($lng->txt("badge_add_template"), - $ilCtrl->getLinkTarget($this, "addImageTemplate")); - } - - include_once "Services/Badge/classes/class.ilBadgeImageTemplateTableGUI.php"; - $tbl = new ilBadgeImageTemplateTableGUI($this, "listImageTemplates", - $ilAccess->checkAccess("write", "", $this->object->getRefId())); - $this->tpl->setContent($tbl->getHTML()); - } - - protected function addImageTemplate(ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - - $this->checkPermission("write"); - - $this->assertActive(); - $this->tabs_gui->setTabActive("imgtmpl"); - - if(!$a_form) - { - $a_form = $this->initImageTemplateForm("create"); - } - - $tpl->setContent($a_form->getHTML()); - } - - protected function initImageTemplateForm($a_mode) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this, "saveBadge")); - $form->setTitle($lng->txt("badge_image_template_form")); - - $title = new ilTextInputGUI($lng->txt("title"), "title"); - $title->setRequired(true); - $form->addItem($title); - - $img = new ilImageFileInputGUI($lng->txt("image"), "img"); - $img->setSuffixes(array("png", "svg")); - if($a_mode == "create") - { - $img->setRequired(true); - } - $img->setALlowDeletion(false); - $form->addItem($img); - - $types_mode = new ilRadioGroupInputGUI($lng->txt("badge_template_types"), "tmode"); - $types_mode->setRequired(true); - $form->addItem($types_mode); - - $type_all = new ilRadioOption($lng->txt("badge_template_types_all"), "all"); - $types_mode->addOption($type_all); - - $type_spec = new ilRadioOption($lng->txt("badge_template_types_specific"), "spec"); - $types_mode->addOption($type_spec); - - $types = new ilCheckboxGroupInputGUI($lng->txt("badge_types"), "type"); - $types->setRequired(true); - $type_spec->addSubItem($types); - - foreach(ilBadgeHandler::getInstance()->getAvailableTypes() as $id => $type) - { - $types->addOption(new ilCheckboxOption($type->getCaption(), $id)); - } - - if($a_mode == "create") - { - $form->addCommandButton("saveImageTemplate", $lng->txt("save")); - } - else - { - $form->addCommandButton("updateImageTemplate", $lng->txt("save")); - } - $form->addCommandButton("listImageTemplates", $lng->txt("cancel")); - - return $form; - } - - protected function saveImageTemplate() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->checkPermission("write"); - - $form = $this->initImageTemplateForm("create"); - if($form->checkInput()) - { - include_once "Services/Badge/classes/class.ilBadgeImageTemplate.php"; - $tmpl = new ilBadgeImageTemplate(); - $tmpl->setTitle($form->getInput("title")); - $tmpl->setTypes($form->getInput("type")); - $tmpl->create(); - - $tmpl->uploadImage($_FILES["img"]); - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - $ilCtrl->redirect($this, "listImageTemplates"); - } - - $form->setValuesByPost(); - $this->addImageTemplate($form); - } - - protected function editImageTemplate(ilPropertyFormGUI $a_form = null) - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - - $this->checkPermission("write"); - - $this->assertActive(); - $this->tabs_gui->setTabActive("imgtmpl"); - - $tmpl_id = $_REQUEST["tid"]; - if(!$tmpl_id) - { - $ilCtrl->redirect($this, "listImageTemplates"); - } - - $ilCtrl->setParameter($this, "tid", $tmpl_id); - - include_once "Services/Badge/classes/class.ilBadgeImageTemplate.php"; - $tmpl = new ilBadgeImageTemplate($tmpl_id); - - if(!$a_form) - { - $a_form = $this->initImageTemplateForm("edit"); - $this->setImageTemplateFormValues($a_form, $tmpl); - } - - $tpl->setContent($a_form->getHTML()); - } - - protected function setImageTemplateFormValues(ilPropertyFormGUI $a_form, ilBadgeImageTemplate $a_tmpl) - { - $a_form->getItemByPostVar("title")->setValue($a_tmpl->getTitle()); - $a_form->getItemByPostVar("img")->setImage($a_tmpl->getImagePath()); - $a_form->getItemByPostVar("img")->setValue($a_tmpl->getImage()); - - if($a_tmpl->getTypes()) - { - $a_form->getItemByPostVar("tmode")->setValue("spec"); - $a_form->getItemByPostVar("type")->setValue($a_tmpl->getTypes()); - } - else - { - $a_form->getItemByPostVar("tmode")->setValue("all"); - } - } - - protected function updateImageTemplate() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->checkPermission("write"); - - $tmpl_id = $_REQUEST["tid"]; - if(!$tmpl_id) - { - $ilCtrl->redirect($this, "listImageTemplates"); - } - - $ilCtrl->setParameter($this, "tid", $tmpl_id); - - include_once "Services/Badge/classes/class.ilBadgeImageTemplate.php"; - $tmpl = new ilBadgeImageTemplate($tmpl_id); - - $form = $this->initImageTemplateForm("update"); - if($form->checkInput()) - { - $tmpl->setTitle($form->getInput("title")); - - if($form->getInput("tmode") != "all") - { - $tmpl->setTypes($form->getInput("type")); - } - else - { - $tmpl->setTypes(null); - } - - $tmpl->update(); - - $tmpl->uploadImage($_FILES["img"]); - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - $ilCtrl->redirect($this, "listImageTemplates"); - } - - $this->setImageTemplateFormValues($form, $tmpl); - $form->setValuesByPost(); - $this->editImageTemplate($form); - } - - protected function confirmDeleteImageTemplates() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - $this->checkPermission("write"); - - $tmpl_ids = $_REQUEST["id"]; - if(!$tmpl_ids) - { - $ilCtrl->redirect($this, "listImageTemplates"); - } - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTarget($this, "listImageTemplates")); - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $confirmation_gui = new ilConfirmationGUI(); - $confirmation_gui->setFormAction($ilCtrl->getFormAction($this)); - $confirmation_gui->setHeaderText($lng->txt("badge_template_deletion_confirmation")); - $confirmation_gui->setCancel($lng->txt("cancel"), "listImageTemplates"); - $confirmation_gui->setConfirm($lng->txt("delete"), "deleteImageTemplates"); - - include_once("./Services/Badge/classes/class.ilBadgeImageTemplate.php"); - foreach($tmpl_ids as $tmpl_id) - { - $tmpl = new ilBadgeImageTemplate($tmpl_id); - $confirmation_gui->addItem("id[]", $tmpl_id, $tmpl->getTitle()); - } + $obi_contact = new ilEmailInputGUI($this->lng->txt("badge_obi_contact"), "obi_cont"); + $obi_contact->setRequired(true); + $obi_contact->setInfo($this->lng->txt("badge_obi_contact_info")); + $obi->addSubItem($obi_contact); - $tpl->setContent($confirmation_gui->getHTML()); - } - - protected function deleteImageTemplates() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->checkPermission("write"); - - $tmpl_ids = $_REQUEST["id"]; - if($tmpl_ids) - { - include_once("./Services/Badge/classes/class.ilBadgeImageTemplate.php"); - foreach($tmpl_ids as $tmpl_id) - { - $tmpl = new ilBadgeImageTemplate($tmpl_id); - $tmpl->delete(); - } - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - } - - $ilCtrl->redirect($this, "listImageTemplates"); - } - - - // - // object badges - // - - protected function listObjectBadges() - { - $ilAccess = $this->access; - $tpl = $this->tpl; - - $this->assertActive(); - $this->tabs_gui->setTabActive("obj_badges"); - - include_once("./Services/Badge/classes/class.ilObjectBadgeTableGUI.php"); - $tbl = new ilObjectBadgeTableGUI($this, "listObjectBadges", - $ilAccess->checkAccess("write", "", $this->object->getRefId())); - $tpl->setContent($tbl->getHTML()); - } - - protected function applyObjectFilter() - { - $ilAccess = $this->access; - - include_once "Services/Badge/classes/class.ilObjectBadgeTableGUI.php"; - $tbl = new ilObjectBadgeTableGUI($this, "listObjectBadges", - $ilAccess->checkAccess("write", "", $this->object->getRefId())); - $tbl->resetOffset(); - $tbl->writeFilterToSession(); - $this->listObjectBadges(); - } - - protected function resetObjectFilter() - { - $ilAccess = $this->access; - - include_once "Services/Badge/classes/class.ilObjectBadgeTableGUI.php"; - $tbl = new ilObjectBadgeTableGUI($this, "listObjectBadges", - $ilAccess->checkAccess("write", "", $this->object->getRefId())); - $tbl->resetOffset(); - $tbl->resetFilter(); - $this->listObjectBadges(); - } - - protected function listObjectBadgeUsers() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - - $parent_obj_id = $_REQUEST["pid"]; - if(!$parent_obj_id) - { - $ilCtrl->redirect($this, "listObjectBadges"); - } - - $this->assertActive(); - - $this->tabs_gui->clearTargets(); - $this->tabs_gui->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTarget($this, "listObjectBadges")); - - $ilCtrl->saveParameter($this, "pid"); - - include_once "Services/Badge/classes/class.ilBadgeUserTableGUI.php"; - $tbl = new ilBadgeUserTableGUI($this, "listUsers", null, null, $parent_obj_id, (int)$_REQUEST["bid"]); - $tpl->setContent($tbl->getHTML()); - } - - protected function applyUserFilter() - { - include_once "Services/Badge/classes/class.ilBadgeUserTableGUI.php"; - $tbl = new ilBadgeUserTableGUI($this, "listUsers", null, null, $parent_obj_id, (int)$_REQUEST["bid"]); - $tbl->resetOffset(); - $tbl->writeFilterToSession(); - $this->listObjectBadgeUsers(); - } - - protected function resetUserFilter() - { - include_once "Services/Badge/classes/class.ilBadgeUserTableGUI.php"; - $tbl = new ilBadgeUserTableGUI($this, "listUsers", null, null, $parent_obj_id, (int)$_REQUEST["bid"]); - $tbl->resetOffset(); - $tbl->resetFilter(); - $this->listObjectBadgeUsers(); - } - - - // - // see ilBadgeManagementGUI - // - - protected function getObjectBadgesFromMultiAction() - { - $ilAccess = $this->access; - $ilCtrl = $this->ctrl; - - $badge_ids = $_REQUEST["id"]; - if(!$badge_ids || - !$ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - $ilCtrl->redirect($this, "listObjectBadges"); - } - - return $badge_ids; - } - - protected function toggleObjectBadges($a_status) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $badge_ids = $this->getObjectBadgesFromMultiAction(); - - include_once "Services/Badge/classes/class.ilBadge.php"; - foreach($badge_ids as $badge_id) - { - $badge = new ilBadge($badge_id); - $badge->setActive($a_status); - $badge->update(); - } - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - $ilCtrl->redirect($this, "listObjectBadges"); - } - - protected function activateObjectBadges() - { - $this->toggleObjectBadges(true); - } - - protected function deactivateObjectBadges() - { - $this->toggleObjectBadges(false); - } - - protected function confirmDeleteObjectBadges() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - $badge_ids = $this->getObjectBadgesFromMultiAction(); - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTarget($this, "listObjectBadges")); - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $confirmation_gui = new ilConfirmationGUI(); - $confirmation_gui->setFormAction($ilCtrl->getFormAction($this)); - $confirmation_gui->setHeaderText($lng->txt("badge_deletion_confirmation")); - $confirmation_gui->setCancel($lng->txt("cancel"), "listObjectBadges"); - $confirmation_gui->setConfirm($lng->txt("delete"), "deleteObjectBadges"); - - include_once "Services/Badge/classes/class.ilBadge.php"; - include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; - foreach($badge_ids as $badge_id) - { - $badge = new ilBadge($badge_id); - $parent = $badge->getParentMeta(); - - // :TODO: container presentation - $container = "(".$parent["type"]."/". - $parent["id"].") ". - $parent["title"]; - if((bool)$parent["deleted"]) - { - $container .= ' '.$lng->txt("deleted").''; - } - - $confirmation_gui->addItem( - "id[]", - $badge_id, - $container." - ". - $badge->getTitle(). - " (".sizeof(ilBadgeAssignment::getInstancesByBadgeId($badge_id)).")" - ); - } + $obi_salt = new ilTextInputGUI($this->lng->txt("badge_obi_salt"), "obi_salt"); + $obi_salt->setRequired(true); + $obi_salt->setInfo($this->lng->txt("badge_obi_salt_info")); + $obi->addSubItem($obi_salt); + */ - $tpl->setContent($confirmation_gui->getHTML()); - } - - protected function deleteObjectBadges() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $badge_ids = $this->getObjectBadgesFromMultiAction(); - - include_once "Services/Badge/classes/class.ilBadge.php"; - foreach($badge_ids as $badge_id) - { - $badge = new ilBadge($badge_id); - $badge->delete(); - } - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - $ilCtrl->redirect($this, "listObjectBadges"); - } -} \ No newline at end of file + $handler = ilBadgeHandler::getInstance(); + $act->setChecked($handler->isActive()); + + /* see bug 0020124 + $obi->setChecked($handler->isObiActive()); + $obi_org->setValue($handler->getObiOrganistation()); + $obi_contact->setValue($handler->getObiContact()); + $obi_salt->setValue($handler->getObiSalt()); + */ + + return $form; + } + + + // + // types + // + + protected function listTypes() + { + $ilAccess = $this->access; + + $this->assertActive(); + $this->tabs_gui->setTabActive("types"); + + include_once "Services/Badge/classes/class.ilBadgeTypesTableGUI.php"; + $tbl = new ilBadgeTypesTableGUI( + $this, + "listTypes", + $ilAccess->checkAccess("write", "", $this->object->getRefId()) + ); + $this->tpl->setContent($tbl->getHTML()); + } + + protected function activateTypes() + { + $lng = $this->lng; + + $this->assertActive(); + + $ids = $_POST["id"]; + if ($this->checkPermissionBool("write") && is_array($ids) && count($ids) > 0) { + $handler = ilBadgeHandler::getInstance(); + $inactive = array(); + foreach ($handler->getInactiveTypes() as $type) { + if (!in_array($type, $ids)) { + $inactive[] = $type; + } + } + $handler->setInactiveTypes($inactive); + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + } + $this->ctrl->redirect($this, "listTypes"); + } + + protected function deactivateTypes() + { + $lng = $this->lng; + + $this->assertActive(); + + $ids = $_POST["id"]; + if ($this->checkPermissionBool("write") && is_array($ids) && count($ids) > 0) { + $handler = ilBadgeHandler::getInstance(); + $inactive = array_merge($handler->getInactiveTypes(), $ids); + $handler->setInactiveTypes($inactive); + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + } + $this->ctrl->redirect($this, "listTypes"); + } + + + // + // images templates + // + + protected function listImageTemplates() + { + $ilAccess = $this->access; + $lng = $this->lng; + $ilToolbar = $this->toolbar; + $ilCtrl = $this->ctrl; + + $this->assertActive(); + $this->tabs_gui->setTabActive("imgtmpl"); + + if ($this->checkPermissionBool("write")) { + $ilToolbar->addButton( + $lng->txt("badge_add_template"), + $ilCtrl->getLinkTarget($this, "addImageTemplate") + ); + } + + include_once "Services/Badge/classes/class.ilBadgeImageTemplateTableGUI.php"; + $tbl = new ilBadgeImageTemplateTableGUI( + $this, + "listImageTemplates", + $ilAccess->checkAccess("write", "", $this->object->getRefId()) + ); + $this->tpl->setContent($tbl->getHTML()); + } + + protected function addImageTemplate(ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + + $this->checkPermission("write"); + + $this->assertActive(); + $this->tabs_gui->setTabActive("imgtmpl"); + + if (!$a_form) { + $a_form = $this->initImageTemplateForm("create"); + } + + $tpl->setContent($a_form->getHTML()); + } + + protected function initImageTemplateForm($a_mode) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this, "saveBadge")); + $form->setTitle($lng->txt("badge_image_template_form")); + + $title = new ilTextInputGUI($lng->txt("title"), "title"); + $title->setRequired(true); + $form->addItem($title); + + $img = new ilImageFileInputGUI($lng->txt("image"), "img"); + $img->setSuffixes(array("png", "svg")); + if ($a_mode == "create") { + $img->setRequired(true); + } + $img->setALlowDeletion(false); + $form->addItem($img); + + $types_mode = new ilRadioGroupInputGUI($lng->txt("badge_template_types"), "tmode"); + $types_mode->setRequired(true); + $form->addItem($types_mode); + + $type_all = new ilRadioOption($lng->txt("badge_template_types_all"), "all"); + $types_mode->addOption($type_all); + + $type_spec = new ilRadioOption($lng->txt("badge_template_types_specific"), "spec"); + $types_mode->addOption($type_spec); + + $types = new ilCheckboxGroupInputGUI($lng->txt("badge_types"), "type"); + $types->setRequired(true); + $type_spec->addSubItem($types); + + foreach (ilBadgeHandler::getInstance()->getAvailableTypes() as $id => $type) { + $types->addOption(new ilCheckboxOption($type->getCaption(), $id)); + } + + if ($a_mode == "create") { + $form->addCommandButton("saveImageTemplate", $lng->txt("save")); + } else { + $form->addCommandButton("updateImageTemplate", $lng->txt("save")); + } + $form->addCommandButton("listImageTemplates", $lng->txt("cancel")); + + return $form; + } + + protected function saveImageTemplate() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->checkPermission("write"); + + $form = $this->initImageTemplateForm("create"); + if ($form->checkInput()) { + include_once "Services/Badge/classes/class.ilBadgeImageTemplate.php"; + $tmpl = new ilBadgeImageTemplate(); + $tmpl->setTitle($form->getInput("title")); + $tmpl->setTypes($form->getInput("type")); + $tmpl->create(); + + $tmpl->uploadImage($_FILES["img"]); + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "listImageTemplates"); + } + + $form->setValuesByPost(); + $this->addImageTemplate($form); + } + + protected function editImageTemplate(ilPropertyFormGUI $a_form = null) + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + + $this->checkPermission("write"); + + $this->assertActive(); + $this->tabs_gui->setTabActive("imgtmpl"); + + $tmpl_id = $_REQUEST["tid"]; + if (!$tmpl_id) { + $ilCtrl->redirect($this, "listImageTemplates"); + } + + $ilCtrl->setParameter($this, "tid", $tmpl_id); + + include_once "Services/Badge/classes/class.ilBadgeImageTemplate.php"; + $tmpl = new ilBadgeImageTemplate($tmpl_id); + + if (!$a_form) { + $a_form = $this->initImageTemplateForm("edit"); + $this->setImageTemplateFormValues($a_form, $tmpl); + } + + $tpl->setContent($a_form->getHTML()); + } + + protected function setImageTemplateFormValues(ilPropertyFormGUI $a_form, ilBadgeImageTemplate $a_tmpl) + { + $a_form->getItemByPostVar("title")->setValue($a_tmpl->getTitle()); + $a_form->getItemByPostVar("img")->setImage($a_tmpl->getImagePath()); + $a_form->getItemByPostVar("img")->setValue($a_tmpl->getImage()); + + if ($a_tmpl->getTypes()) { + $a_form->getItemByPostVar("tmode")->setValue("spec"); + $a_form->getItemByPostVar("type")->setValue($a_tmpl->getTypes()); + } else { + $a_form->getItemByPostVar("tmode")->setValue("all"); + } + } + + protected function updateImageTemplate() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->checkPermission("write"); + + $tmpl_id = $_REQUEST["tid"]; + if (!$tmpl_id) { + $ilCtrl->redirect($this, "listImageTemplates"); + } + + $ilCtrl->setParameter($this, "tid", $tmpl_id); + + include_once "Services/Badge/classes/class.ilBadgeImageTemplate.php"; + $tmpl = new ilBadgeImageTemplate($tmpl_id); + + $form = $this->initImageTemplateForm("update"); + if ($form->checkInput()) { + $tmpl->setTitle($form->getInput("title")); + + if ($form->getInput("tmode") != "all") { + $tmpl->setTypes($form->getInput("type")); + } else { + $tmpl->setTypes(null); + } + + $tmpl->update(); + + $tmpl->uploadImage($_FILES["img"]); + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "listImageTemplates"); + } + + $this->setImageTemplateFormValues($form, $tmpl); + $form->setValuesByPost(); + $this->editImageTemplate($form); + } + + protected function confirmDeleteImageTemplates() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + $this->checkPermission("write"); + + $tmpl_ids = $_REQUEST["id"]; + if (!$tmpl_ids) { + $ilCtrl->redirect($this, "listImageTemplates"); + } + + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, "listImageTemplates") + ); + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $confirmation_gui = new ilConfirmationGUI(); + $confirmation_gui->setFormAction($ilCtrl->getFormAction($this)); + $confirmation_gui->setHeaderText($lng->txt("badge_template_deletion_confirmation")); + $confirmation_gui->setCancel($lng->txt("cancel"), "listImageTemplates"); + $confirmation_gui->setConfirm($lng->txt("delete"), "deleteImageTemplates"); + + include_once("./Services/Badge/classes/class.ilBadgeImageTemplate.php"); + foreach ($tmpl_ids as $tmpl_id) { + $tmpl = new ilBadgeImageTemplate($tmpl_id); + $confirmation_gui->addItem("id[]", $tmpl_id, $tmpl->getTitle()); + } + + $tpl->setContent($confirmation_gui->getHTML()); + } + + protected function deleteImageTemplates() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->checkPermission("write"); + + $tmpl_ids = $_REQUEST["id"]; + if ($tmpl_ids) { + include_once("./Services/Badge/classes/class.ilBadgeImageTemplate.php"); + foreach ($tmpl_ids as $tmpl_id) { + $tmpl = new ilBadgeImageTemplate($tmpl_id); + $tmpl->delete(); + } + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + } + + $ilCtrl->redirect($this, "listImageTemplates"); + } + + + // + // object badges + // + + protected function listObjectBadges() + { + $ilAccess = $this->access; + $tpl = $this->tpl; + + $this->assertActive(); + $this->tabs_gui->setTabActive("obj_badges"); + + include_once("./Services/Badge/classes/class.ilObjectBadgeTableGUI.php"); + $tbl = new ilObjectBadgeTableGUI( + $this, + "listObjectBadges", + $ilAccess->checkAccess("write", "", $this->object->getRefId()) + ); + $tpl->setContent($tbl->getHTML()); + } + + protected function applyObjectFilter() + { + $ilAccess = $this->access; + + include_once "Services/Badge/classes/class.ilObjectBadgeTableGUI.php"; + $tbl = new ilObjectBadgeTableGUI( + $this, + "listObjectBadges", + $ilAccess->checkAccess("write", "", $this->object->getRefId()) + ); + $tbl->resetOffset(); + $tbl->writeFilterToSession(); + $this->listObjectBadges(); + } + + protected function resetObjectFilter() + { + $ilAccess = $this->access; + + include_once "Services/Badge/classes/class.ilObjectBadgeTableGUI.php"; + $tbl = new ilObjectBadgeTableGUI( + $this, + "listObjectBadges", + $ilAccess->checkAccess("write", "", $this->object->getRefId()) + ); + $tbl->resetOffset(); + $tbl->resetFilter(); + $this->listObjectBadges(); + } + + protected function listObjectBadgeUsers() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + + $parent_obj_id = $_REQUEST["pid"]; + if (!$parent_obj_id) { + $ilCtrl->redirect($this, "listObjectBadges"); + } + + $this->assertActive(); + + $this->tabs_gui->clearTargets(); + $this->tabs_gui->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, "listObjectBadges") + ); + + $ilCtrl->saveParameter($this, "pid"); + + include_once "Services/Badge/classes/class.ilBadgeUserTableGUI.php"; + $tbl = new ilBadgeUserTableGUI($this, "listUsers", null, null, $parent_obj_id, (int) $_REQUEST["bid"]); + $tpl->setContent($tbl->getHTML()); + } + + protected function applyUserFilter() + { + include_once "Services/Badge/classes/class.ilBadgeUserTableGUI.php"; + $tbl = new ilBadgeUserTableGUI($this, "listUsers", null, null, $parent_obj_id, (int) $_REQUEST["bid"]); + $tbl->resetOffset(); + $tbl->writeFilterToSession(); + $this->listObjectBadgeUsers(); + } + + protected function resetUserFilter() + { + include_once "Services/Badge/classes/class.ilBadgeUserTableGUI.php"; + $tbl = new ilBadgeUserTableGUI($this, "listUsers", null, null, $parent_obj_id, (int) $_REQUEST["bid"]); + $tbl->resetOffset(); + $tbl->resetFilter(); + $this->listObjectBadgeUsers(); + } + + + // + // see ilBadgeManagementGUI + // + + protected function getObjectBadgesFromMultiAction() + { + $ilAccess = $this->access; + $ilCtrl = $this->ctrl; + + $badge_ids = $_REQUEST["id"]; + if (!$badge_ids || + !$ilAccess->checkAccess("write", "", $this->object->getRefId())) { + $ilCtrl->redirect($this, "listObjectBadges"); + } + + return $badge_ids; + } + + protected function toggleObjectBadges($a_status) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $badge_ids = $this->getObjectBadgesFromMultiAction(); + + include_once "Services/Badge/classes/class.ilBadge.php"; + foreach ($badge_ids as $badge_id) { + $badge = new ilBadge($badge_id); + $badge->setActive($a_status); + $badge->update(); + } + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "listObjectBadges"); + } + + protected function activateObjectBadges() + { + $this->toggleObjectBadges(true); + } + + protected function deactivateObjectBadges() + { + $this->toggleObjectBadges(false); + } + + protected function confirmDeleteObjectBadges() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + $badge_ids = $this->getObjectBadgesFromMultiAction(); + + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, "listObjectBadges") + ); + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $confirmation_gui = new ilConfirmationGUI(); + $confirmation_gui->setFormAction($ilCtrl->getFormAction($this)); + $confirmation_gui->setHeaderText($lng->txt("badge_deletion_confirmation")); + $confirmation_gui->setCancel($lng->txt("cancel"), "listObjectBadges"); + $confirmation_gui->setConfirm($lng->txt("delete"), "deleteObjectBadges"); + + include_once "Services/Badge/classes/class.ilBadge.php"; + include_once "Services/Badge/classes/class.ilBadgeAssignment.php"; + foreach ($badge_ids as $badge_id) { + $badge = new ilBadge($badge_id); + $parent = $badge->getParentMeta(); + + // :TODO: container presentation + $container = "(" . $parent["type"] . "/" . + $parent["id"] . ") " . + $parent["title"]; + if ((bool) $parent["deleted"]) { + $container .= ' ' . $lng->txt("deleted") . ''; + } + + $confirmation_gui->addItem( + "id[]", + $badge_id, + $container . " - " . + $badge->getTitle() . + " (" . sizeof(ilBadgeAssignment::getInstancesByBadgeId($badge_id)) . ")" + ); + } + + $tpl->setContent($confirmation_gui->getHTML()); + } + + protected function deleteObjectBadges() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $badge_ids = $this->getObjectBadgesFromMultiAction(); + + include_once "Services/Badge/classes/class.ilBadge.php"; + foreach ($badge_ids as $badge_id) { + $badge = new ilBadge($badge_id); + $badge->delete(); + } + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "listObjectBadges"); + } +} diff --git a/Services/Badge/classes/class.ilObjectBadgeTableGUI.php b/Services/Badge/classes/class.ilObjectBadgeTableGUI.php index d4c9ab9e9352077bdf415e33b9abfdc66ab8ad46..8db16660c3414cbee05523fdfc97aea83701a51c 100644 --- a/Services/Badge/classes/class.ilObjectBadgeTableGUI.php +++ b/Services/Badge/classes/class.ilObjectBadgeTableGUI.php @@ -13,194 +13,180 @@ include_once("./Services/Badge/classes/class.ilBadge.php"); * @ingroup ServicesBadge */ class ilObjectBadgeTableGUI extends ilTable2GUI -{ - /** - * @var ilCtrl - */ - protected $ctrl; +{ + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - protected $has_write; // [bool] - - function __construct($a_parent_obj, $a_parent_cmd = "", $a_has_write = false) - { - global $DIC; + protected $has_write; // [bool] + + public function __construct($a_parent_obj, $a_parent_cmd = "", $a_has_write = false) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->setId("bdgobdg"); - $this->has_write = (bool)$a_has_write; - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setLimit(9999); - - $this->setTitle($lng->txt("badge_object_badges")); - - if($this->has_write) - { - $this->addColumn("", "", 1); - } - - $this->addColumn($lng->txt("title"), "title"); - $this->addColumn($lng->txt("type"), "type"); - $this->addColumn($lng->txt("object"), "container"); - $this->addColumn($lng->txt("active"), "active"); - $this->addColumn($lng->txt("action"), ""); - - if($this->has_write) - { - $this->addMultiCommand("activateObjectBadges", $lng->txt("activate")); - $this->addMultiCommand("deactivateObjectBadges", $lng->txt("deactivate")); - $this->addMultiCommand("confirmDeleteObjectBadges", $lng->txt("delete")); - $this->setSelectAllCheckbox("id"); - } - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.object_badge_row.html", "Services/Badge"); - $this->setDefaultOrderField("title"); - - $this->setFilterCommand("applyObjectFilter"); - $this->setResetCommand("resetObjectFilter"); - - $this->initFilter(); - - $this->getItems(); - } - - public function initFilter() - { - $lng = $this->lng; - - $title = $this->addFilterItemByMetaType("title", self::FILTER_TEXT, false, $lng->txt("title")); - $this->filter["title"] = $title->getValue(); - - $object = $this->addFilterItemByMetaType("object", self::FILTER_TEXT, false, $lng->txt("object")); - $this->filter["object"] = $object->getValue(); - - $lng->loadLanguageModule("search"); - - $options = array( - "" => $lng->txt("search_any"), - ); - foreach(ilBadgeHandler::getInstance()->getAvailableTypes() as $id => $type) - { - // no activity badges - if(!in_array("bdga", $type->getValidObjectTypes())) - { - $options[$id] = ilBadge::getExtendedTypeCaption($type); - } - } - asort($options); - - $type = $this->addFilterItemByMetaType("type", self::FILTER_SELECT, false, $lng->txt("type")); - $type->setOptions($options); - $this->filter["type"] = $type->getValue(); - } - - function getItems() - { - $lng = $this->lng; - $ilAccess = $this->access; - - $data = $filter_types = array(); - - $types = ilBadgeHandler::getInstance()->getAvailableTypes(); - - include_once "Services/Badge/classes/class.ilBadgeRenderer.php"; - include_once "Services/Link/classes/class.ilLink.php"; - - foreach(ilBadge::getObjectInstances($this->filter) as $badge_item) - { - // :TODO: container presentation - $container_url = null; - $container = ''.$lng->txt( '. - $badge_item["parent_title"]; - - if((bool)$badge_item["deleted"]) - { - $container .= ' '.$lng->txt("deleted").''; - } - else - { - $ref_id = array_shift(ilObject::_getAllReferences($badge_item["parent_id"])); - if($ilAccess->checkAccess("read", "", $ref_id)) - { - $container_url = ilLink::_getLink($ref_id); - } - } - - $type_caption = ilBadge::getExtendedTypeCaption($types[$badge_item["type_id"]]); - - $data[] = array( - "id" => $badge_item["id"], - "active"=> $badge_item["active"], - "type" => $type_caption, - "title" => $badge_item["title"], - "container_meta" => $container, - "container_url" => $container_url, - "container_id" => $badge_item["parent_id"], - "renderer" => new ilBadgeRenderer(null, new ilBadge($badge_item["id"])) - ); - - $filter_types[$badge_item["type_id"]] = $type_caption; - } - - $this->setData($data); - } - - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if($a_set["container_url"]) - { - $this->tpl->setCurrentBlock("container_link_bl"); - $this->tpl->setVariable("TXT_CONTAINER", $a_set["container_meta"]); - $this->tpl->setVariable("URL_CONTAINER", $a_set["container_url"]); - $this->tpl->parseCurrentBlock(); - } - else - { - $this->tpl->setCurrentBlock("container_nolink_bl"); - $this->tpl->setVariable("TXT_CONTAINER_STATIC", $a_set["container_meta"]); - $this->tpl->parseCurrentBlock(); - } - - if($this->has_write) - { - $this->tpl->setVariable("VAL_ID", $a_set["id"]); - } - - $this->tpl->setVariable("PREVIEW", $a_set["renderer"]->getHTML()); - $this->tpl->setVariable("TXT_TITLE", $a_set["title"]); - $this->tpl->setVariable("TXT_TYPE", $a_set["type"]); - $this->tpl->setVariable("TXT_ACTIVE", $a_set["active"] - ? $lng->txt("yes") - : $lng->txt("no")); - - if($this->has_write) - { - $ilCtrl->setParameter($this->getParentObject(), "pid", $a_set["container_id"]); - $ilCtrl->setParameter($this->getParentObject(), "bid", $a_set["id"]); - $url = $ilCtrl->getLinkTarget($this->getParentObject(), "listObjectBadgeUsers"); - $ilCtrl->setParameter($this->getParentObject(), "bid", ""); - $ilCtrl->setParameter($this->getParentObject(), "pid", ""); - - $this->tpl->setVariable("TXT_LIST", $lng->txt("users")); - $this->tpl->setVariable("URL_LIST", $url); - } - } + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->setId("bdgobdg"); + $this->has_write = (bool) $a_has_write; + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setLimit(9999); + + $this->setTitle($lng->txt("badge_object_badges")); + + if ($this->has_write) { + $this->addColumn("", "", 1); + } + + $this->addColumn($lng->txt("title"), "title"); + $this->addColumn($lng->txt("type"), "type"); + $this->addColumn($lng->txt("object"), "container"); + $this->addColumn($lng->txt("active"), "active"); + $this->addColumn($lng->txt("action"), ""); + + if ($this->has_write) { + $this->addMultiCommand("activateObjectBadges", $lng->txt("activate")); + $this->addMultiCommand("deactivateObjectBadges", $lng->txt("deactivate")); + $this->addMultiCommand("confirmDeleteObjectBadges", $lng->txt("delete")); + $this->setSelectAllCheckbox("id"); + } + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.object_badge_row.html", "Services/Badge"); + $this->setDefaultOrderField("title"); + + $this->setFilterCommand("applyObjectFilter"); + $this->setResetCommand("resetObjectFilter"); + + $this->initFilter(); + + $this->getItems(); + } + + public function initFilter() + { + $lng = $this->lng; + + $title = $this->addFilterItemByMetaType("title", self::FILTER_TEXT, false, $lng->txt("title")); + $this->filter["title"] = $title->getValue(); + + $object = $this->addFilterItemByMetaType("object", self::FILTER_TEXT, false, $lng->txt("object")); + $this->filter["object"] = $object->getValue(); + + $lng->loadLanguageModule("search"); + + $options = array( + "" => $lng->txt("search_any"), + ); + foreach (ilBadgeHandler::getInstance()->getAvailableTypes() as $id => $type) { + // no activity badges + if (!in_array("bdga", $type->getValidObjectTypes())) { + $options[$id] = ilBadge::getExtendedTypeCaption($type); + } + } + asort($options); + + $type = $this->addFilterItemByMetaType("type", self::FILTER_SELECT, false, $lng->txt("type")); + $type->setOptions($options); + $this->filter["type"] = $type->getValue(); + } + + public function getItems() + { + $lng = $this->lng; + $ilAccess = $this->access; + + $data = $filter_types = array(); + + $types = ilBadgeHandler::getInstance()->getAvailableTypes(); + + include_once "Services/Badge/classes/class.ilBadgeRenderer.php"; + include_once "Services/Link/classes/class.ilLink.php"; + + foreach (ilBadge::getObjectInstances($this->filter) as $badge_item) { + // :TODO: container presentation + $container_url = null; + $container = '' . $lng->txt( ' . + $badge_item["parent_title"]; + + if ((bool) $badge_item["deleted"]) { + $container .= ' ' . $lng->txt("deleted") . ''; + } else { + $ref_id = array_shift(ilObject::_getAllReferences($badge_item["parent_id"])); + if ($ilAccess->checkAccess("read", "", $ref_id)) { + $container_url = ilLink::_getLink($ref_id); + } + } + + $type_caption = ilBadge::getExtendedTypeCaption($types[$badge_item["type_id"]]); + + $data[] = array( + "id" => $badge_item["id"], + "active"=> $badge_item["active"], + "type" => $type_caption, + "title" => $badge_item["title"], + "container_meta" => $container, + "container_url" => $container_url, + "container_id" => $badge_item["parent_id"], + "renderer" => new ilBadgeRenderer(null, new ilBadge($badge_item["id"])) + ); + + $filter_types[$badge_item["type_id"]] = $type_caption; + } + + $this->setData($data); + } + + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if ($a_set["container_url"]) { + $this->tpl->setCurrentBlock("container_link_bl"); + $this->tpl->setVariable("TXT_CONTAINER", $a_set["container_meta"]); + $this->tpl->setVariable("URL_CONTAINER", $a_set["container_url"]); + $this->tpl->parseCurrentBlock(); + } else { + $this->tpl->setCurrentBlock("container_nolink_bl"); + $this->tpl->setVariable("TXT_CONTAINER_STATIC", $a_set["container_meta"]); + $this->tpl->parseCurrentBlock(); + } + + if ($this->has_write) { + $this->tpl->setVariable("VAL_ID", $a_set["id"]); + } + + $this->tpl->setVariable("PREVIEW", $a_set["renderer"]->getHTML()); + $this->tpl->setVariable("TXT_TITLE", $a_set["title"]); + $this->tpl->setVariable("TXT_TYPE", $a_set["type"]); + $this->tpl->setVariable("TXT_ACTIVE", $a_set["active"] + ? $lng->txt("yes") + : $lng->txt("no")); + + if ($this->has_write) { + $ilCtrl->setParameter($this->getParentObject(), "pid", $a_set["container_id"]); + $ilCtrl->setParameter($this->getParentObject(), "bid", $a_set["id"]); + $url = $ilCtrl->getLinkTarget($this->getParentObject(), "listObjectBadgeUsers"); + $ilCtrl->setParameter($this->getParentObject(), "bid", ""); + $ilCtrl->setParameter($this->getParentObject(), "pid", ""); + + $this->tpl->setVariable("TXT_LIST", $lng->txt("users")); + $this->tpl->setVariable("URL_LIST", $url); + } + } } diff --git a/Services/Badge/interfaces/interface.ilBadgeAuto.php b/Services/Badge/interfaces/interface.ilBadgeAuto.php index b16530f4846c32bc9b9840388058ed3d53ccba95..ae90ee50ebf2bccf331364147e2d94fb0b8c5466 100644 --- a/Services/Badge/interfaces/interface.ilBadgeAuto.php +++ b/Services/Badge/interfaces/interface.ilBadgeAuto.php @@ -11,13 +11,13 @@ */ interface ilBadgeAuto { - /** - * Evaluate if given user has earned badge - * - * @param int $a_user_id - * @param array $a_params - * @param array $a_config - * @return bool - */ - public function evaluate($a_user_id, array $a_params, array $a_config); -} \ No newline at end of file + /** + * Evaluate if given user has earned badge + * + * @param int $a_user_id + * @param array $a_params + * @param array $a_config + * @return bool + */ + public function evaluate($a_user_id, array $a_params, array $a_config); +} diff --git a/Services/Badge/interfaces/interface.ilBadgeProvider.php b/Services/Badge/interfaces/interface.ilBadgeProvider.php index bae45baf7d6c71899ab39fb40a2c7c885bbc362b..469c3770a8d5dbc1a705d09e10d0618f4e5be23d 100644 --- a/Services/Badge/interfaces/interface.ilBadgeProvider.php +++ b/Services/Badge/interfaces/interface.ilBadgeProvider.php @@ -11,10 +11,10 @@ */ interface ilBadgeProvider { - /** - * Get available badge types from component - * - * @return ilBadgeType[] - */ - public function getBadgeTypes(); -} \ No newline at end of file + /** + * Get available badge types from component + * + * @return ilBadgeType[] + */ + public function getBadgeTypes(); +} diff --git a/Services/Badge/interfaces/interface.ilBadgeType.php b/Services/Badge/interfaces/interface.ilBadgeType.php index 033449ad9ff06b3966e58e5d182d8caf73a6eefa..dbbc979c6054dfe08882b4d99611066dadc23e53 100644 --- a/Services/Badge/interfaces/interface.ilBadgeType.php +++ b/Services/Badge/interfaces/interface.ilBadgeType.php @@ -11,38 +11,38 @@ */ interface ilBadgeType { - /** - * Get typ id (unique for component) - * - * @return string - */ - public function getId(); - - /** - * Get caption - * - * @return string - */ - public function getCaption(); - - /** - * Can only be created once? - * - * @return bool - */ - public function isSingleton(); + /** + * Get typ id (unique for component) + * + * @return string + */ + public function getId(); + + /** + * Get caption + * + * @return string + */ + public function getCaption(); + + /** + * Can only be created once? + * + * @return bool + */ + public function isSingleton(); - /** - * Get valid (repository) "parent" object types - * - * @return array - */ - public function getValidObjectTypes(); - - /** - * Get GUI config instance - * - * @return ilBadgeTypeGUI|null - */ - public function getConfigGUIInstance(); -} \ No newline at end of file + /** + * Get valid (repository) "parent" object types + * + * @return array + */ + public function getValidObjectTypes(); + + /** + * Get GUI config instance + * + * @return ilBadgeTypeGUI|null + */ + public function getConfigGUIInstance(); +} diff --git a/Services/Badge/interfaces/interface.ilBadgeTypeGUI.php b/Services/Badge/interfaces/interface.ilBadgeTypeGUI.php index 5228e961e7708f36def15685c9ec6ded05ac909a..7ad57b9290f4365733243e050fc3b47494a9f079 100644 --- a/Services/Badge/interfaces/interface.ilBadgeTypeGUI.php +++ b/Services/Badge/interfaces/interface.ilBadgeTypeGUI.php @@ -11,35 +11,35 @@ */ interface ilBadgeTypeGUI { - /** - * Add custom fields to form - * - * @param ilPropertyFormGUI $a_form - * @param int $a_parent_ref_id - */ - public function initConfigForm(ilPropertyFormGUI $a_form, $a_parent_ref_id); - - /** - * Set form values - * - * @param ilPropertyFormGUI $a_form - * @param array $a_config - */ - public function importConfigToForm(ilPropertyFormGUI $a_form, array $a_config); - - /** - * Export values to DB - * - * @param ilPropertyFormGUI $a_form - * @return array - */ - public function getConfigFromForm(ilPropertyFormGUI $a_form); - - /** - * Custom form validation - * - * @param ilPropertyFormGUI $a_form - * @return bool - */ - public function validateForm(ilPropertyFormGUI $a_form); -} \ No newline at end of file + /** + * Add custom fields to form + * + * @param ilPropertyFormGUI $a_form + * @param int $a_parent_ref_id + */ + public function initConfigForm(ilPropertyFormGUI $a_form, $a_parent_ref_id); + + /** + * Set form values + * + * @param ilPropertyFormGUI $a_form + * @param array $a_config + */ + public function importConfigToForm(ilPropertyFormGUI $a_form, array $a_config); + + /** + * Export values to DB + * + * @param ilPropertyFormGUI $a_form + * @return array + */ + public function getConfigFromForm(ilPropertyFormGUI $a_form); + + /** + * Custom form validation + * + * @param ilPropertyFormGUI $a_form + * @return bool + */ + public function validateForm(ilPropertyFormGUI $a_form); +} diff --git a/Services/Badge/lib/baker.lib.php b/Services/Badge/lib/baker.lib.php index 920f8d32cd6077e1190b11b7aa50c600d94e52fd..38d63f1ded05ad8ffae0344631101ba327f5cf66 100644 --- a/Services/Badge/lib/baker.lib.php +++ b/Services/Badge/lib/baker.lib.php @@ -2,7 +2,7 @@ /** * Php library to Bake the PNG Images - * + * */ class PNGImageBaker { @@ -17,7 +17,8 @@ class PNGImageBaker * * @param string $contents File content as a string */ - public function __construct($contents) { + public function __construct($contents) + { $this->_contents = $contents; $png_signature = pack("C8", 137, 80, 78, 71, 13, 10, 26, 10); // Read 8 bytes of PNG header and verify. @@ -46,7 +47,8 @@ class PNGImageBaker * * @return boolean (true|false) True if file is safe to write this keyword, false otherwise. */ - public function checkChunks($type, $check) { + public function checkChunks($type, $check) + { if (array_key_exists($type, $this->_chunks)) { foreach (array_keys($this->_chunks[$type]) as $typekey) { list($key, $data) = explode("\0", $this->_chunks[$type][$typekey]); @@ -68,8 +70,8 @@ class PNGImageBaker * * @return string $result File content with a new chunk as a string. */ - public function addChunk($chunkType, $key, $value) { - + public function addChunk($chunkType, $key, $value) + { $chunkData = $key . "\0" . $value; $crc = pack("N", crc32($chunkType . $chunkData)); $len = pack("N", strlen($chunkData)); @@ -90,32 +92,38 @@ class PNGImageBaker * * @return string $result New File content. */ - public function removeChunks($chunkType, $key, $png) { + public function removeChunks($chunkType, $key, $png) + { // Read the magic bytes and verify - $retval = substr($png,0,8); + $retval = substr($png, 0, 8); $ipos = 8; - if ($retval != "\x89PNG\x0d\x0a\x1a\x0a") + if ($retval != "\x89PNG\x0d\x0a\x1a\x0a") { throw new Exception('Is not a valid PNG image'); + } // Loop through the chunks. Byte 0-3 is length, Byte 4-7 is type - $chunkHeader = substr($png,$ipos,8); + $chunkHeader = substr($png, $ipos, 8); $ipos = $ipos + 8; while ($chunkHeader) { // Extract length and type from binary data $chunk = @unpack('Nsize/a4type', $chunkHeader); $skip = false; - if ( $chunk['type'] == $chunkType ) { - $data = substr($png,$ipos,$chunk['size']); + if ($chunk['type'] == $chunkType) { + $data = substr($png, $ipos, $chunk['size']); $sections = explode("\0", $data); print_r($sections); - if ( $sections[0] == $key ) $skip = true; + if ($sections[0] == $key) { + $skip = true; + } } // Extract the data and the CRC - $data = substr($png,$ipos,$chunk['size']+4); + $data = substr($png, $ipos, $chunk['size']+4); $ipos = $ipos + $chunk['size'] + 4; // Add in the header, data, and CRC - if ( ! $skip ) $retval = $retval . $chunkHeader . $data; + if (!$skip) { + $retval = $retval . $chunkHeader . $data; + } // Read next chunk header - $chunkHeader = substr($png,$ipos,8); + $chunkHeader = substr($png, $ipos, 8); $ipos = $ipos + 8; } return $retval; @@ -123,43 +131,44 @@ class PNGImageBaker /** * Extracts the baked PNG info by the Key - * + * * @param string $png the png image * @param string $key Keyword that needs to be searched. - * + * * @return mixed - If there is an error - boolean false is returned * If there is PNG information that matches the key an array is returned - * + * */ - public function extractBadgeInfo($png, $key='openbadges') { + public function extractBadgeInfo($png, $key='openbadges') + { // Read the magic bytes and verify - $retval = substr($png,0,8); + $retval = substr($png, 0, 8); $ipos = 8; if ($retval != "\x89PNG\x0d\x0a\x1a\x0a") { return false; } // Loop through the chunks. Byte 0-3 is length, Byte 4-7 is type - $chunkHeader = substr($png,$ipos,8); + $chunkHeader = substr($png, $ipos, 8); $ipos = $ipos + 8; while ($chunkHeader) { // Extract length and type from binary data $chunk = @unpack('Nsize/a4type', $chunkHeader); $skip = false; if ($chunk['type'] == 'tEXt') { - $data = substr($png,$ipos,$chunk['size']); + $data = substr($png, $ipos, $chunk['size']); $sections = explode("\0", $data); if ($sections[0] == $key) { - return $sections; + return $sections; } } // Extract the data and the CRC - $data = substr($png,$ipos,$chunk['size']+4); + $data = substr($png, $ipos, $chunk['size']+4); $ipos = $ipos + $chunk['size'] + 4; // Read next chunk header - $chunkHeader = substr($png,$ipos,8); + $chunkHeader = substr($png, $ipos, 8); $ipos = $ipos + 8; } } -} \ No newline at end of file +} diff --git a/Services/Block/classes/class.ilBlockGUI.php b/Services/Block/classes/class.ilBlockGUI.php index 63031fafcdda55745b7a7feb60e39347519408e2..92737a38ce58cfef438e693c98e9aab5aa00c5bc 100644 --- a/Services/Block/classes/class.ilBlockGUI.php +++ b/Services/Block/classes/class.ilBlockGUI.php @@ -5,1462 +5,1473 @@ /** * This class represents a block method of a block. * -* @author Alex Killing +* @author Alex Killing * @version $Id$ * */ abstract class ilBlockGUI { - /** - * @return string - */ - abstract public function getBlockType(): string; - - /** - * Returns whether block has a corresponding repository object - * - * @return bool - */ - abstract protected function isRepositoryObject(): bool; - - protected $data = array(); - protected $colspan = 1; - protected $enablenuminfo = true; - protected $detail_min = 0; - protected $detail_max = 0; - protected $bigmode = false; - protected $footer_links = array(); - protected $block_id = 0; - protected $header_commands = array(); - protected $allow_moving = true; - protected $move = array("left" => false, "right" => false, "up" => false, "down" => false); - protected $enabledetailrow = true; - protected $header_links = array(); - protected $footerinfo = false; - protected $footerinfo_icon = false; - protected $block_commands = array(); - protected $max_count = false; - protected $close_command = false; - protected $image = false; - protected $property = false; - protected $nav_value = ""; - protected $css_row = ""; - - protected $dropdown; - - /** - * @var ilTemplate|null block template - */ - protected $tpl; - - /** - * @var ilTemplate|null main template - */ - protected $main_tpl; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var - */ - protected $obj_def; - - /** - * Constructor - * - * @param - */ - function __construct() - { - global $DIC; - - $this->user = $DIC->user(); - $this->ctrl = $DIC->ctrl(); - $this->access = $DIC->access(); - $this->lng = $DIC->language(); - $this->main_tpl = $DIC["tpl"]; - $this->obj_def = $DIC["objDefinition"]; - - include_once("./Services/YUI/classes/class.ilYuiUtil.php"); - ilYuiUtil::initConnection(); - $this->main_tpl->addJavaScript("./Services/Block/js/ilblockcallback.js"); - - $this->setLimit($this->user->getPref("hits_per_page")); - } - - public function addHeaderLink($a_href, $a_text, $status = true) - { - $this->header_links[] = - array('href' => $a_href, 'text' => $a_text, 'status' => (bool)$status); - } - - public function getHeaderLinks() - { - return $this->header_links; - } - - /** - * Set Data. - * - * @param array $a_data Data - */ - function setData($a_data) - { - $this->data = $a_data; - } - - /** - * Get Data. - * - * @return array Data - */ - function getData() - { - return $this->data; - } - - /** - * Set Big Mode. - * - * @param boolean $a_bigmode Big Mode - */ - function setBigMode($a_bigmode) - { - $this->bigmode = $a_bigmode; - } - - /** - * Get Big Mode. - * - * @return boolean Big Mode - */ - function getBigMode() - { - return $this->bigmode; - } - - /** - * Set Block Id - * - * @param int $a_block_id Block ID - */ - function setBlockId($a_block_id = 0) - { - $this->block_id = $a_block_id; - } - - /** - * Get Block Id - * - * @return int Block Id - */ - function getBlockId() - { - return $this->block_id; - } - - /** - * Set Available Detail Levels - * - * @param int $a_max Max Level - * @param int $a_min Min Level (Default 0) - */ - function setAvailableDetailLevels($a_max, $a_min = 0) - { - $this->detail_min = $a_min; - $this->detail_max = $a_max; - $this->handleDetailLevel(); - } - - /** - * Set Current Detail Level. - * - * @param int $a_currentdetaillevel Current Detail Level - */ - function setCurrentDetailLevel($a_currentdetaillevel) - { - $this->currentdetaillevel = $a_currentdetaillevel; - } - - /** - * Set GuiObject. - * Only used for repository blocks, that are represented as - * real repository objects (have a ref id and permissions) - * - * @param object $a_gui_object GUI object - */ - public function setGuiObject(&$a_gui_object) - { - $this->gui_object = $a_gui_object; - } - - /** - * Get GuiObject. - * - * @return object GUI object - */ - public function getGuiObject() - { - return $this->gui_object; - } - - /** - * Get Current Detail Level. - * - * @return int Current Detail Level - */ - function getCurrentDetailLevel() - { - return $this->currentdetaillevel; - } - - /** - * Set Title. - * - * @param string $a_title Title - */ - function setTitle($a_title) - { - $this->title = $a_title; - } - - /** - * Get Title. - * - * @return string Title - */ - function getTitle() - { - return $this->title; - } - - /** - * Set Image. - * - * @param string $a_image Image - */ - function setImage($a_image) - { - $this->image = $a_image; - } - - /** - * Get Image. - * - * @return string Image - */ - function getImage() - { - return $this->image; - } - - /** - * Set Offset. - * - * @param int $a_offset Offset - */ - function setOffset($a_offset) - { - $this->offset = $a_offset; - } - - /** - * Get Offset. - * - * @return int Offset - */ - function getOffset() - { - return $this->offset; - } - - function correctOffset() - { - if (!($this->offset < $this->max_count)) - { - $this->setOffset(0); - } - } - - /** - * Set Limit. - * - * @param int $a_limit Limit - */ - function setLimit($a_limit) - { - $this->limit = $a_limit; - } - - /** - * Get Limit. - * - * @return int Limit - */ - function getLimit() - { - return $this->limit; - } - - /** - * Set EnableEdit. - * - * @param boolean $a_enableedit EnableEdit - */ - function setEnableEdit($a_enableedit) - { - $this->enableedit = $a_enableedit; - } - - /** - * Get EnableEdit. - * - * @return boolean EnableEdit - */ - function getEnableEdit() - { - return $this->enableedit; - } - - /** - * Set RepositoryMode. - * - * @param boolean $a_repositorymode RepositoryMode - */ - function setRepositoryMode($a_repositorymode) - { - $this->repositorymode = $a_repositorymode; - } - - /** - * Get RepositoryMode. - * - * @return boolean RepositoryMode - */ - function getRepositoryMode() - { - return $this->repositorymode; - } - - /** - * Set Footer Info. - * - * @param string $a_footerinfo Footer Info - */ - function setFooterInfo($a_footerinfo, $a_hide_and_icon = false) - { - if ($a_hide_and_icon) - { - $this->footerinfo_icon = $a_footerinfo; - } - else - { - $this->footerinfo = $a_footerinfo; - } - } - - /** - * Get Footer Info. - * - * @return string Footer Info - */ - function getFooterInfo($a_hide_and_icon = false) - { - if ($a_hide_and_icon) - { - return $this->footerinfo_icon; - } - else - { - return $this->footerinfo; - } - } - - /** - * Set Subtitle. - * - * @param string $a_subtitle Subtitle - */ - function setSubtitle($a_subtitle) - { - $this->subtitle = $a_subtitle; - } - - /** - * Get Subtitle. - * - * @return string Subtitle - */ - function getSubtitle() - { - return $this->subtitle; - } - - /** - * Set Ref Id (only used if isRepositoryObject() is true). - * - * @param int $a_refid Ref Id - */ - function setRefId($a_refid) - { - $this->refid = $a_refid; - } - - /** - * Get Ref Id (only used if isRepositoryObject() is true). - * - * @return int Ref Id - */ - function getRefId() - { - return $this->refid; - } - - /** - * Set Administration Commmands. - * - * @param boolean $a_admincommands Administration Commmands - */ - function setAdminCommands($a_admincommands) - { - $this->admincommands = $a_admincommands; - } - - /** - * Get Administration Commmands. - * - * @return boolean Administration Commmands - */ - function getAdminCommands() - { - return $this->admincommands; - } - - /** - * Set Columns Span. - * - * @param int $a_colspan Columns Span - */ - function setColSpan($a_colspan) - { - $this->colspan = $a_colspan; - } - - /** - * Get Columns Span. - * - * @return int Columns Span - */ - function getColSpan() - { - return $this->colspan; - } - - /** - * Set EnableDetailRow. - * - * @param boolean $a_enabledetailrow EnableDetailRow - */ - function setEnableDetailRow($a_enabledetailrow) - { - $this->enabledetailrow = $a_enabledetailrow; - } - - /** - * Get EnableDetailRow. - * - * @return boolean EnableDetailRow - */ - function getEnableDetailRow() - { - return $this->enabledetailrow; - } - - - /** - * Set Enable Item Number Info. - * - * @param boolean $a_enablenuminfo Enable Item Number Info - */ - function setEnableNumInfo($a_enablenuminfo) - { - $this->enablenuminfo = $a_enablenuminfo; - } - - /** - * Get Enable Item Number Info. - * - * @return boolean Enable Item Number Info - */ - function getEnableNumInfo() - { - return $this->enablenuminfo; - } - - /** - * This function is supposed to be used for block type specific - * properties, that should be inherited through ilColumnGUI->setBlockProperties - * - * @param string $a_properties properties array (key => value) - */ - function setProperties($a_properties) - { - $this->property = $a_properties; - } - - function getProperty($a_property) - { - return $this->property[$a_property]; - } - - function setProperty($a_property, $a_value) - { - $this->property[$a_property] = $a_value; - } - - /** - * Set Row Template Name. - * - * @param string $a_rowtemplatename Row Template Name - */ - function setRowTemplate($a_rowtemplatename, $a_rowtemplatedir = "") - { - $this->rowtemplatename = $a_rowtemplatename; - $this->rowtemplatedir = $a_rowtemplatedir; - } - - final public function getNavParameter() - { - return $this->getBlockType()."_".$this->getBlockId()."_blnav"; - } - - final public function getDetailParameter() - { - return $this->getBlockType()."_".$this->getBlockId()."_bldet"; - } - - final public function getConfigParameter() - { - return $this->getBlockType()."_".$this->getBlockId()."_blconf"; - } - - final public function getMoveParameter() - { - return $this->getBlockType()."_".$this->getBlockId()."_blmove"; - } - - /** - * Get Row Template Name. - * - * @return string Row Template Name - */ - function getRowTemplateName() - { - return $this->rowtemplatename; - } - - /** - * Get Row Template Directory. - * - * @return string Row Template Directory - */ - function getRowTemplateDir() - { - return $this->rowtemplatedir; - } - - /** - * Add Block Command. - * - * @param string $a_href command link target - * @param string $a_text text - */ - function addBlockCommand($a_href, $a_text, $a_target = "", $a_img = "", $a_right_aligned = false, - $a_checked = false, $a_html = "") - { - return $this->block_commands[] = - array("href" => $a_href, - "text" => $a_text, "target" => $a_target, "img" => $a_img, - "right" => $a_right_aligned, "checked" => $a_checked, "html" => $a_html); - } - - /** - * Get Block commands. - * - * @return array block commands - */ - function getBlockCommands() - { - return $this->block_commands; - } - - /** - * Add Header Block Command. - * - * @param string $a_href command link target - * @param string $a_text text - */ - function addHeaderCommand($a_href, $a_text, $a_as_close = false) - { - if ($a_as_close) - { - $this->close_command = $a_href; - } - else - { - $this->header_commands[] = - array("href" => $a_href, - "text" => $a_text); - } - } - - /** - * Get Header Block commands. - * - * @return array header block commands - */ - function getHeaderCommands() - { - return $this->header_commands; - } - - /** - * Add a footer text/link - */ - function addFooterLink($a_text, $a_href = "", $a_onclick = "", $a_block_id = "", - $a_top = false, $a_omit_separator = false, $a_checked = false) - { - $this->footer_links[] = array( - "text" => $a_text, - "href" => $a_href, - "onclick" => $a_onclick, - "block_id" => $a_block_id, - "top" => $a_top, - "omit_separator" => $a_omit_separator, - "checked" => $a_checked); - } - - /** - * Get footer links. - */ - function getFooterLinks() - { - return $this->footer_links; - } - - /** - * Clear footer links. - */ - function clearFooterLinks() - { - $this->footer_links = array(); - } - - /** - * Get Screen Mode for current command. - */ - static function getScreenMode() - { - return IL_SCREEN_SIDE; - } - - /** - * Handle read/write current detail level. - */ - function handleDetailLevel() - { - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - // set/get detail level - if ($this->detail_max > $this->detail_min) - { - include_once("Services/Block/classes/class.ilBlockSetting.php"); - if (isset($_GET[$this->getDetailParameter()])) - { - ilBlockSetting::_writeDetailLevel($this->getBlockType(), $_GET[$this->getDetailParameter()], - $ilUser->getId(), $this->block_id); - $this->setCurrentDetailLevel($_GET[$this->getDetailParameter()]); - if ((int) $_GET[$this->getDetailParameter()] == 0) - { - $ilCtrl->redirectByClass("ilcolumngui", ""); - } - } - else - { - $this->setCurrentDetailLevel(ilBlockSetting::_lookupDetailLevel($this->getBlockType(), - $ilUser->getId(), $this->block_id)); - } - } - } - - /** - * Handle config status. - */ -/* - function handleConfigStatus() - { - $this->config_mode = false; - - if ($_GET[$this->getConfigParameter()] == "toggle") - { - if ($_SESSION[$this->getConfigParameter()] == "on") - { - $_SESSION[$this->getConfigParameter()] = "off"; - } - else - { - $_SESSION[$this->getConfigParameter()] = "on"; - } - } - if ($_SESSION[$this->getConfigParameter()] == "on") - { - $this->config_mode = true; - } - } -*/ - - /** - * Get HTML. - */ - function getHTML() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilAccess = $this->access; - $ilUser = $this->user; - $objDefinition = $this->obj_def; - - if ($this->isRepositoryObject()) - { - if (!$ilAccess->checkAccess("read", "", $this->getRefId())) - { - return ""; - } - } - - $this->tpl = new ilTemplate("tpl.block.html", true, true, "Services/Block"); - -// $this->handleConfigStatus(); - - $this->fillDataSection(); - - if ($this->getRepositoryMode() && $this->isRepositoryObject()) - { - // #10993 - if ($this->getAdminCommands()) - { - $this->tpl->setCurrentBlock("block_check"); - $this->tpl->setVariable("BL_REF_ID", $this->getRefId()); - $this->tpl->parseCurrentBlock(); - } - - if ($ilAccess->checkAccess("delete", "", $this->getRefId())) - { - $this->addBlockCommand( - "ilias.php?baseClass=ilRepositoryGUI&ref_id=".$_GET["ref_id"]."&cmd=delete". - "&item_ref_id=".$this->getRefId(), - $lng->txt("delete")); - - // see ilObjectListGUI::insertCutCommand(); - $this->addBlockCommand( - "ilias.php?baseClass=ilRepositoryGUI&ref_id=".$_GET["ref_id"]."&cmd=cut". - "&item_ref_id=".$this->getRefId(), - $lng->txt("move")); - } - - // #14595 - see ilObjectListGUI::insertCopyCommand() - if ($ilAccess->checkAccess("copy", "", $this->getRefId())) - { - $parent_type = ilObject::_lookupType($_GET["ref_id"], true); - $parent_gui = "ilObj".$objDefinition->getClassName($parent_type)."GUI"; - - $ilCtrl->setParameterByClass("ilobjectcopygui", "source_id", $this->getRefId()); - $copy_cmd = $ilCtrl->getLinkTargetByClass( - array("ilrepositorygui", $parent_gui, "ilobjectcopygui"), - "initTargetSelection"); - - // see ilObjectListGUI::insertCopyCommand(); - $this->addBlockCommand( - $copy_cmd, - $lng->txt("copy")); - } - } - - // footer info - if ($this->getFooterInfo() != "") - { - $this->tpl->setCurrentBlock("footer_information"); - $this->tpl->setVariable("FOOTER_INFO", $this->getFooterInfo()); - $this->tpl->setVariable("FICOLSPAN", $this->getColSpan()); - $this->tpl->parseCurrentBlock(); - } - - $this->dropdown = array(); - - // commands - if (count($this->getBlockCommands()) > 0) - { - $has_block_command = false; - - foreach($this->getBlockCommands() as $command) - { - if(!$command["img"] && !$command["html"]) - { - $this->dropdown[] = $command; - continue; - } - - $has_block_command = true; - - if ($command["target"] != "") - { - $this->tpl->setCurrentBlock("bc_target"); - $this->tpl->setVariable("CMD_TARGET", $command["target"]); - $this->tpl->parseCurrentBlock(); - } - - if ($command["img"] != "") - { - $this->tpl->setCurrentBlock("bc_image"); - $this->tpl->setVariable("SRC_BC", $command["img"]); - $this->tpl->setVariable("ALT_BC", $command["text"]); - $this->tpl->parseCurrentBlock(); - $this->tpl->setCurrentBlock("block_command"); - } - else if ($command["html"] != "") - { - if($command['href'] !== '') - { - $this->tpl->setCurrentBlock("bc_html"); - $this->tpl->setVariable("HTML", $command["html"]); - $this->tpl->parseCurrentBlock(); - $this->tpl->setCurrentBlock("block_command"); - } - else - { - $this->tpl->setCurrentBlock('bc_html_nohref'); - $this->tpl->setVariable('HTML_NOHREF',$command['html']); - $this->tpl->parseCurrentBlock(); - $this->tpl->setCurrentBlock("block_command"); - } - } - else - { - $this->tpl->setCurrentBlock("block_command"); - $this->tpl->setVariable("CMD_TEXT", $command["text"]); - $this->tpl->setVariable("BC_CLASS", 'class="il_ContainerItemCommand"'); - } - - if($command['href'] !== '') - { - $this->tpl->setVariable("CMD_HREF", $command["href"]); - } - $this->tpl->parseCurrentBlock(); - } - - if($has_block_command) - { - $this->tpl->setCurrentBlock("block_commands"); - $this->tpl->setVariable("CCOLSPAN", $this->getColSpan()); - $this->tpl->parseCurrentBlock(); - } - } - - // fill previous next - $this->fillPreviousNext(); - - // fill footer - $this->fillFooter(); - - // fill row for setting details - $this->fillDetailRow(); - - // header links - if(count($this->getHeaderLinks())) - { - $counter = 0; - foreach($this->getHeaderLinks() as $command) - { - if($counter > 0) - { - $this->tpl->setCurrentBlock('head_delim'); - $this->tpl->touchBlock('head_delim'); - $this->tpl->parseCurrentBlock(); - } - if($command['status'] == true) - { - $this->tpl->setCurrentBlock('head_link'); - $this->tpl->setVariable('HHREF', $command['href']); - $this->tpl->setVariable('HLINK', $command['text']); - $this->tpl->parseCurrentBlock(); - } - else - { - $this->tpl->setCurrentBlock('head_text'); - $this->tpl->setVariable('HTEXT', $command['text']); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setCurrentBlock('head_item'); - $this->tpl->parseCurrentBlock(); - - ++$counter; - } - - $this->tpl->setCurrentBlock('header_links'); - $this->tpl->parseCurrentBlock(); - } - - // for screen readers we first output the title and the commands - // (e.g. close icon afterwards), otherwise we first output the - // header commands, since we want to have the close icon top right - // and not floated after the title - if (is_object($ilUser) && $ilUser->getPref("screen_reader_optimization")) - { - $this->fillHeaderTitleBlock(); - $this->fillHeaderCommands(); - } - else - { - $this->fillHeaderCommands(); - $this->fillHeaderTitleBlock(); - } - - $this->tpl->setVariable("COLSPAN", $this->getColSpan()); - if ($this->getBigMode()) - { - $this->tpl->touchBlock("hclassb"); - } - else - { - $this->tpl->touchBlock("hclass"); - } - - if ($ilCtrl->isAsynch()) - { - // return without div wrapper - echo $this->tpl->getAsynch(); - } - else - { - // return incl. wrapping div with id - return '
getBlockType()."_".$this->block_id.'">'. - $this->tpl->get().'
'; - } - } - - /** - * Fill header commands block - */ - function fillHeaderCommands() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - - // header commands - if (count($this->getHeaderCommands()) > 0 || - ($this->detail_max > $this->detail_min && $this->detail_min == 0) || - $this->close_command != "") - { - - foreach($this->getHeaderCommands() as $command) - { - $this->tpl->setCurrentBlock("header_command"); - $this->tpl->setVariable("HREF_HCOMM", $command["href"]); - $this->tpl->setVariable("TXT_HCOMM", $command["text"]); - $this->tpl->parseCurrentBlock(); - } - - // close button - if (($this->detail_max > $this->detail_min && $this->detail_min == 0 && - !$this->getRepositoryMode()) - || - $this->close_command != "") - { - $alt = $lng->txt("hide"); - if ($this->close_command != "") - { - $url = $this->close_command; - } - else - { - $ilCtrl->setParameterByClass("ilcolumngui", - $this->getDetailParameter(), "0"); - $url = $ilCtrl->getLinkTargetByClass("ilcolumngui", ""); - $ilCtrl->setParameterByClass("ilcolumngui", - $this->getDetailParameter(), ""); - } - - $this->dropdown[] = array("text" => $alt, - "image" => $img, - "href" => $url); - } - - $this->tpl->setCurrentBlock("header_commands"); - $this->tpl->parseCurrentBlock(); - } - - // adv selection gui - include_once "Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"; - $dropdown = new ilAdvancedSelectionListGUI(); - $dropdown->setUseImages(true); - $dropdown->setStyle(ilAdvancedSelectionListGUI::STYLE_LINK_BUTTON); - $dropdown->setHeaderIcon(ilAdvancedSelectionListGUI::ICON_CONFIG); - $dropdown->setId("block_dd_".$this->getBlockType()."_".$this->block_id); - foreach($this->dropdown as $item) - { - if($item["href"] || $item["onclick"]) - { - if ($item["checked"]) - { - $item["image"] = ilUtil::getImagePath("icon_checked.svg"); - } - $dropdown->addItem($item["text"], "", $item["href"], $item["image"], - $item["text"], "", "", false, $item["onclick"]); - } - } - $dropdown = $dropdown->getHTML(); - $this->tpl->setCurrentBlock("header_dropdown"); - $this->tpl->setVariable("ADV_DROPDOWN", $dropdown); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setCurrentBlock("hitem"); - $this->tpl->parseCurrentBlock(); - } - - - /** - * Fill header title block (title and - */ - function fillHeaderTitleBlock() - { - $lng = $this->lng; - - // image - if ($this->getImage() != "") - { - $this->tpl->setCurrentBlock("block_img"); - $this->tpl->setVariable("IMG_BLOCK", $this->getImage()); - $this->tpl->setVariable("IMID", - "block_".$this->getBlockType()."_".$this->block_id); - $this->tpl->setVariable("IMG_ALT", - str_replace(array("'",'"'), "", strip_tags($lng->txt("icon")." ".$this->getTitle()))); - $this->tpl->parseCurrentBlock(); - } - - // header title - $this->tpl->setCurrentBlock("header_title"); - $this->tpl->setVariable("BTID", - "block_".$this->getBlockType()."_".$this->block_id); - $this->tpl->setVariable("BLOCK_TITLE", - $this->getTitle()); - $this->tpl->setVariable("TXT_BLOCK", - $lng->txt("block")); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setCurrentBlock("hitem"); - $this->tpl->parseCurrentBlock(); - } - - - /** - * Call this from overwritten fillDataSection(), if standard row based data is not used. - */ - function setDataSection($a_content) - { - $this->tpl->setCurrentBlock("data_section"); - $this->tpl->setVariable("DATA", $a_content); - $this->tpl->parseCurrentBlock(); - $this->tpl->setVariable("BLOCK_ROW", ""); - } - - /** - * Standard implementation for row based data. - * Overwrite this and call setContent for other data. - */ - function fillDataSection() - { - $this->nav_value = (isset($_POST[$this->getNavParameter()]) && $_POST[$this->getNavParameter()] != "") - ? $_POST[$this->getNavParameter()] - : (isset($_GET[$this->getNavParameter()]) ? $_GET[$this->getNavParameter()] : $this->nav_value); - $this->nav_value = ($this->nav_value == "" && isset($_SESSION[$this->getNavParameter()])) - ? $_SESSION[$this->getNavParameter()] - : $this->nav_value; - - $_SESSION[$this->getNavParameter()] = $this->nav_value; - - $nav = explode(":", $this->nav_value); - if (isset($nav[2])) - { - $this->setOffset($nav[2]); - } - else - { - $this->setOffset(0); - } - - // data - $this->tpl->addBlockFile("BLOCK_ROW", "block_row", $this->getRowTemplateName(), - $this->getRowTemplateDir()); - - $data = $this->getData(); - $this->max_count = count($data); - $this->correctOffset(); - $data = array_slice($data, $this->getOffset(), $this->getLimit()); - - $this->preloadData($data); - - foreach($data as $record) - { - $this->tpl->setCurrentBlock("block_row"); - $this->fillRowColor(); - $this->fillRow($record); - $this->tpl->setCurrentBlock("block_row"); - $this->tpl->parseCurrentBlock(); - } - } - - function fillRow($a_set) - { - foreach ($a_set as $key => $value) - { - $this->tpl->setVariable("VAL_".strtoupper($key), $value); - } - } - - function fillFooter() - { - } - - final protected function fillRowColor($a_placeholder = "CSS_ROW") - { - $this->css_row = ($this->css_row != "ilBlockRow1") - ? "ilBlockRow1" - : "ilBlockRow2"; - $this->tpl->setVariable($a_placeholder, $this->css_row); - } - - /** - * Fill previous/next row - */ - function fillPreviousNext() - { - $lng = $this->lng; - - // table pn numinfo - $numinfo = ""; - if ($this->getEnableNumInfo() && $this->max_count > 0) - { - $start = $this->getOffset() + 1; // compute num info - $end = $this->getOffset() + $this->getLimit(); - - if ($end > $this->max_count or $this->getLimit() == 0) - { - $end = $this->max_count; - } - - $numinfo = "(".$start."-".$end." ".strtolower($lng->txt("of"))." ".$this->max_count.")"; - } - - $this->setPreviousNextLinks(); - $this->fillFooterLinks(true, $numinfo); - - } - - /** - * Get previous/next linkbar. - * - * @author Sascha Hofmann - * - * @return array linkbar or false on error - */ - function setPreviousNextLinks() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - // if more entries then entries per page -> show link bar - if ($this->max_count > $this->getLimit() && ($this->getLimit() != 0)) - { - // previous link - if ($this->getOffset() >= 1) - { - $prevoffset = $this->getOffset() - $this->getLimit(); - - $ilCtrl->setParameterByClass("ilcolumngui", - $this->getNavParameter(), "::".$prevoffset); - - // ajax link - $ilCtrl->setParameterByClass("ilcolumngui", - "block_id", "block_".$this->getBlockType()."_".$this->block_id); - $block_id = "block_".$this->getBlockType()."_".$this->block_id; - $onclick = $ilCtrl->getLinkTargetByClass("ilcolumngui", - "updateBlock", "", true); - $ilCtrl->setParameterByClass("ilcolumngui", - "block_id", ""); - - // normal link - $href = $ilCtrl->getLinkTargetByClass("ilcolumngui", ""); - $text = $lng->txt("previous"); - - $this->addFooterLink($text, $href, $onclick, $block_id, true); - } - - // calculate number of pages - $pages = intval($this->max_count / $this->getLimit()); - - // add a page if a rest remains - if (($this->max_count % $this->getLimit())) - $pages++; - - // show next link (if not last page) - if (! ( ($this->getOffset() / $this->getLimit())==($pages-1) ) && ($pages!=1) ) - { - $newoffset = $this->getOffset() + $this->getLimit(); - - $ilCtrl->setParameterByClass("ilcolumngui", - $this->getNavParameter(), "::".$newoffset); - - // ajax link - $ilCtrl->setParameterByClass("ilcolumngui", - "block_id", "block_".$this->getBlockType()."_".$this->block_id); - //$this->tpl->setCurrentBlock("pnonclick"); - $block_id = "block_".$this->getBlockType()."_".$this->block_id; - $onclick = $ilCtrl->getLinkTargetByClass("ilcolumngui", - "updateBlock", "", true); -//echo "-".$onclick."-"; - //$this->tpl->parseCurrentBlock(); - $ilCtrl->setParameterByClass("ilcolumngui", - "block_id", ""); - - // normal link - $href = $ilCtrl->getLinkTargetByClass("ilcolumngui", ""); - $text = $lng->txt("next"); - - $this->addFooterLink($text, $href, $onclick, $block_id, true); - } - $ilCtrl->setParameterByClass("ilcolumngui", - $this->getNavParameter(), ""); - return true; - } - else - { - return false; - } - } - - /** - * Fill footer links - * - * @return array linkbar or false on error - */ - function fillFooterLinks($a_top = false, $a_numinfo = "") - { - $first = true; - $flinks = $this->getFooterLinks(); - - $prefix = ($a_top) ? "top" : "foot"; - - $has_link = false; - - $omit_separator = false; - foreach($flinks as $flink) - { - if ($flink["top"] != $a_top) - { - continue; - } - - if(!$a_top) - { - if($flink["onclick"]) - { - $flink["onclick"] = "ilBlockJSHandler('".$flink["block_id"]. - "','".$flink["onclick"]."')"; - } - $this->dropdown[] = $flink; - continue; - } - - $has_link = true; - - if (!$first && !$omit_separator) - { - $this->tpl->touchBlock($prefix."_delim"); - $this->tpl->touchBlock($prefix."_item"); - } - - // ajax link - if ($flink["onclick"] != "") - { - $this->tpl->setCurrentBlock($prefix."_onclick"); - $this->tpl->setVariable("OC_BLOCK_ID", - $flink["block_id"]); - $this->tpl->setVariable("OC_HREF", - $flink["onclick"]); - $this->tpl->parseCurrentBlock(); - } - - // normal link - if ($flink["href"] != "") - { - // normal link - $this->tpl->setCurrentBlock($prefix."_link"); - $this->tpl->setVariable("FHREF", - $flink["href"]); - $this->tpl->setVariable("FLINK", $flink["text"]); - $this->tpl->parseCurrentBlock(); - $this->tpl->touchBlock($prefix."_item"); - } - else - { - $this->tpl->setCurrentBlock($prefix."_text"); - $this->tpl->setVariable("FTEXT", $flink["text"]); - $this->tpl->parseCurrentBlock(); - $this->tpl->touchBlock($prefix."_item"); - } - - $first = false; - $omit_separator = $flink["omit_separator"]; - } - - if ($a_numinfo != "" && $has_link) - { - $this->tpl->setVariable("NUMINFO", $a_numinfo); - $first = false; - } - - /* - if (!$first) - { - $this->tpl->setVariable("PCOLSPAN", $this->getColSpan()); - $this->tpl->setCurrentBlock($prefix."_row"); - $this->tpl->parseCurrentBlock(); - } - */ - } - - /** - * Fill Detail Setting Row. - */ - function fillDetailRow() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if ($this->enabledetailrow == false) - { - return; - } - - $start = ($this->detail_min < 1) - ? $start = 1 - : $this->detail_min; - - $end = ($this->detail_max < $this->detail_min) - ? $this->detail_min - : $this->detail_max; - - $settings = array(); - for ($i = $start; $i <= $end; $i++) - { - $settings[] = $i; - } - - if ($end > $start) - { - foreach ($settings as $i) - { - if (($i > $start && $i > 1)) - { - //$this->tpl->touchBlock("det_delim"); - //$this->tpl->touchBlock("det_item"); - } -// if ($i != $this->getCurrentDetailLevel()) -// { - $ilCtrl->setParameterByClass("ilcolumngui", - $this->getDetailParameter(), $i); - - $onclick = $onclick_id = ""; - - // ajax link - if ($i > 0) - { - $ilCtrl->setParameterByClass("ilcolumngui", - "block_id", "block_".$this->getBlockType()."_".$this->block_id); - $onclick = $ilCtrl->getLinkTargetByClass("ilcolumngui", - "updateBlock", "", true); - $onclick_id = "block_".$this->getBlockType()."_".$this->block_id; - $ilCtrl->setParameterByClass("ilcolumngui", - "block_id", ""); - } - - // normal link - //$icon = ilUtil::getImagePath("details".$i.".svg"); - $text = $lng->txt("details")." ".$i; - $url = $ilCtrl->getLinkTargetByClass("ilcolumngui", ""); - - if($onclick) - { - $onclick = "ilBlockJSHandler('".$onclick_id."','".$onclick."')"; - } - - $checked = ($i == $this->getCurrentDetailLevel()); - $this->dropdown[] = array("text" => $text, - "image" => $icon, - "href" => $url, - "onclick" => $onclick, - "checked" => $checked); -// } - } - - // info + icon in detail row - if ($this->getFooterInfo(true) != "") - { - $this->tpl->setCurrentBlock("det_info"); - $this->tpl->setVariable("INFO_TEXT", $this->getFooterInfo(true)); - $this->tpl->setVariable("ALT_DET_INFO", $lng->txt("info_short")); - $this->tpl->setVariable("DI_BLOCK_ID", $this->getBlockType()."_".$this->getBlockId()); - $this->tpl->setVariable("IMG_DET_INFO", ilUtil::getImagePath("icon_info.svg")); - $this->tpl->parseCurrentBlock(); - } - - /* - $this->tpl->setCurrentBlock("detail_setting"); - $this->tpl->setVariable("TXT_DETAILS", $lng->txt("details")); - $this->tpl->setVariable("DCOLSPAN", $this->getColSpan()); - $this->tpl->parseCurrentBlock(); - */ - - $ilCtrl->setParameterByClass("ilcolumngui", - $this->getDetailParameter(), ""); - } - } - - /** - * Can be overwritten in subclasses. Only the visible part of the complete data was passed so a preload of the visible data is possible. - * @param array $data - */ - protected function preloadData(array $data) - { - } + /** + * @return string + */ + abstract public function getBlockType() : string; + + /** + * Returns whether block has a corresponding repository object + * + * @return bool + */ + abstract protected function isRepositoryObject() : bool; + + protected $data = array(); + protected $colspan = 1; + protected $enablenuminfo = true; + protected $detail_min = 0; + protected $detail_max = 0; + protected $bigmode = false; + protected $footer_links = array(); + protected $block_id = 0; + protected $header_commands = array(); + protected $allow_moving = true; + protected $move = array("left" => false, "right" => false, "up" => false, "down" => false); + protected $enabledetailrow = true; + protected $header_links = array(); + protected $footerinfo = false; + protected $footerinfo_icon = false; + protected $block_commands = array(); + protected $max_count = false; + protected $close_command = false; + protected $image = false; + protected $property = false; + protected $nav_value = ""; + protected $css_row = ""; + + protected $dropdown; + + /** + * @var ilTemplate|null block template + */ + protected $tpl; + + /** + * @var ilTemplate|null main template + */ + protected $main_tpl; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var + */ + protected $obj_def; + + /** + * Constructor + * + * @param + */ + public function __construct() + { + global $DIC; + + $this->user = $DIC->user(); + $this->ctrl = $DIC->ctrl(); + $this->access = $DIC->access(); + $this->lng = $DIC->language(); + $this->main_tpl = $DIC["tpl"]; + $this->obj_def = $DIC["objDefinition"]; + + include_once("./Services/YUI/classes/class.ilYuiUtil.php"); + ilYuiUtil::initConnection(); + $this->main_tpl->addJavaScript("./Services/Block/js/ilblockcallback.js"); + + $this->setLimit($this->user->getPref("hits_per_page")); + } + + public function addHeaderLink($a_href, $a_text, $status = true) + { + $this->header_links[] = + array('href' => $a_href, 'text' => $a_text, 'status' => (bool) $status); + } + + public function getHeaderLinks() + { + return $this->header_links; + } + + /** + * Set Data. + * + * @param array $a_data Data + */ + public function setData($a_data) + { + $this->data = $a_data; + } + + /** + * Get Data. + * + * @return array Data + */ + public function getData() + { + return $this->data; + } + + /** + * Set Big Mode. + * + * @param boolean $a_bigmode Big Mode + */ + public function setBigMode($a_bigmode) + { + $this->bigmode = $a_bigmode; + } + + /** + * Get Big Mode. + * + * @return boolean Big Mode + */ + public function getBigMode() + { + return $this->bigmode; + } + + /** + * Set Block Id + * + * @param int $a_block_id Block ID + */ + public function setBlockId($a_block_id = 0) + { + $this->block_id = $a_block_id; + } + + /** + * Get Block Id + * + * @return int Block Id + */ + public function getBlockId() + { + return $this->block_id; + } + + /** + * Set Available Detail Levels + * + * @param int $a_max Max Level + * @param int $a_min Min Level (Default 0) + */ + public function setAvailableDetailLevels($a_max, $a_min = 0) + { + $this->detail_min = $a_min; + $this->detail_max = $a_max; + $this->handleDetailLevel(); + } + + /** + * Set Current Detail Level. + * + * @param int $a_currentdetaillevel Current Detail Level + */ + public function setCurrentDetailLevel($a_currentdetaillevel) + { + $this->currentdetaillevel = $a_currentdetaillevel; + } + + /** + * Set GuiObject. + * Only used for repository blocks, that are represented as + * real repository objects (have a ref id and permissions) + * + * @param object $a_gui_object GUI object + */ + public function setGuiObject(&$a_gui_object) + { + $this->gui_object = $a_gui_object; + } + + /** + * Get GuiObject. + * + * @return object GUI object + */ + public function getGuiObject() + { + return $this->gui_object; + } + + /** + * Get Current Detail Level. + * + * @return int Current Detail Level + */ + public function getCurrentDetailLevel() + { + return $this->currentdetaillevel; + } + + /** + * Set Title. + * + * @param string $a_title Title + */ + public function setTitle($a_title) + { + $this->title = $a_title; + } + + /** + * Get Title. + * + * @return string Title + */ + public function getTitle() + { + return $this->title; + } + + /** + * Set Image. + * + * @param string $a_image Image + */ + public function setImage($a_image) + { + $this->image = $a_image; + } + + /** + * Get Image. + * + * @return string Image + */ + public function getImage() + { + return $this->image; + } + + /** + * Set Offset. + * + * @param int $a_offset Offset + */ + public function setOffset($a_offset) + { + $this->offset = $a_offset; + } + + /** + * Get Offset. + * + * @return int Offset + */ + public function getOffset() + { + return $this->offset; + } + + public function correctOffset() + { + if (!($this->offset < $this->max_count)) { + $this->setOffset(0); + } + } + + /** + * Set Limit. + * + * @param int $a_limit Limit + */ + public function setLimit($a_limit) + { + $this->limit = $a_limit; + } + + /** + * Get Limit. + * + * @return int Limit + */ + public function getLimit() + { + return $this->limit; + } + + /** + * Set EnableEdit. + * + * @param boolean $a_enableedit EnableEdit + */ + public function setEnableEdit($a_enableedit) + { + $this->enableedit = $a_enableedit; + } + + /** + * Get EnableEdit. + * + * @return boolean EnableEdit + */ + public function getEnableEdit() + { + return $this->enableedit; + } + + /** + * Set RepositoryMode. + * + * @param boolean $a_repositorymode RepositoryMode + */ + public function setRepositoryMode($a_repositorymode) + { + $this->repositorymode = $a_repositorymode; + } + + /** + * Get RepositoryMode. + * + * @return boolean RepositoryMode + */ + public function getRepositoryMode() + { + return $this->repositorymode; + } + + /** + * Set Footer Info. + * + * @param string $a_footerinfo Footer Info + */ + public function setFooterInfo($a_footerinfo, $a_hide_and_icon = false) + { + if ($a_hide_and_icon) { + $this->footerinfo_icon = $a_footerinfo; + } else { + $this->footerinfo = $a_footerinfo; + } + } + + /** + * Get Footer Info. + * + * @return string Footer Info + */ + public function getFooterInfo($a_hide_and_icon = false) + { + if ($a_hide_and_icon) { + return $this->footerinfo_icon; + } else { + return $this->footerinfo; + } + } + + /** + * Set Subtitle. + * + * @param string $a_subtitle Subtitle + */ + public function setSubtitle($a_subtitle) + { + $this->subtitle = $a_subtitle; + } + + /** + * Get Subtitle. + * + * @return string Subtitle + */ + public function getSubtitle() + { + return $this->subtitle; + } + + /** + * Set Ref Id (only used if isRepositoryObject() is true). + * + * @param int $a_refid Ref Id + */ + public function setRefId($a_refid) + { + $this->refid = $a_refid; + } + + /** + * Get Ref Id (only used if isRepositoryObject() is true). + * + * @return int Ref Id + */ + public function getRefId() + { + return $this->refid; + } + + /** + * Set Administration Commmands. + * + * @param boolean $a_admincommands Administration Commmands + */ + public function setAdminCommands($a_admincommands) + { + $this->admincommands = $a_admincommands; + } + + /** + * Get Administration Commmands. + * + * @return boolean Administration Commmands + */ + public function getAdminCommands() + { + return $this->admincommands; + } + + /** + * Set Columns Span. + * + * @param int $a_colspan Columns Span + */ + public function setColSpan($a_colspan) + { + $this->colspan = $a_colspan; + } + + /** + * Get Columns Span. + * + * @return int Columns Span + */ + public function getColSpan() + { + return $this->colspan; + } + + /** + * Set EnableDetailRow. + * + * @param boolean $a_enabledetailrow EnableDetailRow + */ + public function setEnableDetailRow($a_enabledetailrow) + { + $this->enabledetailrow = $a_enabledetailrow; + } + + /** + * Get EnableDetailRow. + * + * @return boolean EnableDetailRow + */ + public function getEnableDetailRow() + { + return $this->enabledetailrow; + } + + + /** + * Set Enable Item Number Info. + * + * @param boolean $a_enablenuminfo Enable Item Number Info + */ + public function setEnableNumInfo($a_enablenuminfo) + { + $this->enablenuminfo = $a_enablenuminfo; + } + + /** + * Get Enable Item Number Info. + * + * @return boolean Enable Item Number Info + */ + public function getEnableNumInfo() + { + return $this->enablenuminfo; + } + + /** + * This function is supposed to be used for block type specific + * properties, that should be inherited through ilColumnGUI->setBlockProperties + * + * @param string $a_properties properties array (key => value) + */ + public function setProperties($a_properties) + { + $this->property = $a_properties; + } + + public function getProperty($a_property) + { + return $this->property[$a_property]; + } + + public function setProperty($a_property, $a_value) + { + $this->property[$a_property] = $a_value; + } + + /** + * Set Row Template Name. + * + * @param string $a_rowtemplatename Row Template Name + */ + public function setRowTemplate($a_rowtemplatename, $a_rowtemplatedir = "") + { + $this->rowtemplatename = $a_rowtemplatename; + $this->rowtemplatedir = $a_rowtemplatedir; + } + + final public function getNavParameter() + { + return $this->getBlockType() . "_" . $this->getBlockId() . "_blnav"; + } + + final public function getDetailParameter() + { + return $this->getBlockType() . "_" . $this->getBlockId() . "_bldet"; + } + + final public function getConfigParameter() + { + return $this->getBlockType() . "_" . $this->getBlockId() . "_blconf"; + } + + final public function getMoveParameter() + { + return $this->getBlockType() . "_" . $this->getBlockId() . "_blmove"; + } + + /** + * Get Row Template Name. + * + * @return string Row Template Name + */ + public function getRowTemplateName() + { + return $this->rowtemplatename; + } + + /** + * Get Row Template Directory. + * + * @return string Row Template Directory + */ + public function getRowTemplateDir() + { + return $this->rowtemplatedir; + } + + /** + * Add Block Command. + * + * @param string $a_href command link target + * @param string $a_text text + */ + public function addBlockCommand( + $a_href, + $a_text, + $a_target = "", + $a_img = "", + $a_right_aligned = false, + $a_checked = false, + $a_html = "" + ) { + return $this->block_commands[] = + array("href" => $a_href, + "text" => $a_text, "target" => $a_target, "img" => $a_img, + "right" => $a_right_aligned, "checked" => $a_checked, "html" => $a_html); + } + + /** + * Get Block commands. + * + * @return array block commands + */ + public function getBlockCommands() + { + return $this->block_commands; + } + + /** + * Add Header Block Command. + * + * @param string $a_href command link target + * @param string $a_text text + */ + public function addHeaderCommand($a_href, $a_text, $a_as_close = false) + { + if ($a_as_close) { + $this->close_command = $a_href; + } else { + $this->header_commands[] = + array("href" => $a_href, + "text" => $a_text); + } + } + + /** + * Get Header Block commands. + * + * @return array header block commands + */ + public function getHeaderCommands() + { + return $this->header_commands; + } + + /** + * Add a footer text/link + */ + public function addFooterLink( + $a_text, + $a_href = "", + $a_onclick = "", + $a_block_id = "", + $a_top = false, + $a_omit_separator = false, + $a_checked = false + ) { + $this->footer_links[] = array( + "text" => $a_text, + "href" => $a_href, + "onclick" => $a_onclick, + "block_id" => $a_block_id, + "top" => $a_top, + "omit_separator" => $a_omit_separator, + "checked" => $a_checked); + } + + /** + * Get footer links. + */ + public function getFooterLinks() + { + return $this->footer_links; + } + + /** + * Clear footer links. + */ + public function clearFooterLinks() + { + $this->footer_links = array(); + } + + /** + * Get Screen Mode for current command. + */ + public static function getScreenMode() + { + return IL_SCREEN_SIDE; + } + + /** + * Handle read/write current detail level. + */ + public function handleDetailLevel() + { + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + // set/get detail level + if ($this->detail_max > $this->detail_min) { + include_once("Services/Block/classes/class.ilBlockSetting.php"); + if (isset($_GET[$this->getDetailParameter()])) { + ilBlockSetting::_writeDetailLevel( + $this->getBlockType(), + $_GET[$this->getDetailParameter()], + $ilUser->getId(), + $this->block_id + ); + $this->setCurrentDetailLevel($_GET[$this->getDetailParameter()]); + if ((int) $_GET[$this->getDetailParameter()] == 0) { + $ilCtrl->redirectByClass("ilcolumngui", ""); + } + } else { + $this->setCurrentDetailLevel(ilBlockSetting::_lookupDetailLevel( + $this->getBlockType(), + $ilUser->getId(), + $this->block_id + )); + } + } + } + + /** + * Handle config status. + */ + /* + function handleConfigStatus() + { + $this->config_mode = false; + + if ($_GET[$this->getConfigParameter()] == "toggle") + { + if ($_SESSION[$this->getConfigParameter()] == "on") + { + $_SESSION[$this->getConfigParameter()] = "off"; + } + else + { + $_SESSION[$this->getConfigParameter()] = "on"; + } + } + if ($_SESSION[$this->getConfigParameter()] == "on") + { + $this->config_mode = true; + } + } + */ + + /** + * Get HTML. + */ + public function getHTML() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilAccess = $this->access; + $ilUser = $this->user; + $objDefinition = $this->obj_def; + + if ($this->isRepositoryObject()) { + if (!$ilAccess->checkAccess("read", "", $this->getRefId())) { + return ""; + } + } + + $this->tpl = new ilTemplate("tpl.block.html", true, true, "Services/Block"); + + // $this->handleConfigStatus(); + + $this->fillDataSection(); + + if ($this->getRepositoryMode() && $this->isRepositoryObject()) { + // #10993 + if ($this->getAdminCommands()) { + $this->tpl->setCurrentBlock("block_check"); + $this->tpl->setVariable("BL_REF_ID", $this->getRefId()); + $this->tpl->parseCurrentBlock(); + } + + if ($ilAccess->checkAccess("delete", "", $this->getRefId())) { + $this->addBlockCommand( + "ilias.php?baseClass=ilRepositoryGUI&ref_id=" . $_GET["ref_id"] . "&cmd=delete" . + "&item_ref_id=" . $this->getRefId(), + $lng->txt("delete") + ); + + // see ilObjectListGUI::insertCutCommand(); + $this->addBlockCommand( + "ilias.php?baseClass=ilRepositoryGUI&ref_id=" . $_GET["ref_id"] . "&cmd=cut" . + "&item_ref_id=" . $this->getRefId(), + $lng->txt("move") + ); + } + + // #14595 - see ilObjectListGUI::insertCopyCommand() + if ($ilAccess->checkAccess("copy", "", $this->getRefId())) { + $parent_type = ilObject::_lookupType($_GET["ref_id"], true); + $parent_gui = "ilObj" . $objDefinition->getClassName($parent_type) . "GUI"; + + $ilCtrl->setParameterByClass("ilobjectcopygui", "source_id", $this->getRefId()); + $copy_cmd = $ilCtrl->getLinkTargetByClass( + array("ilrepositorygui", $parent_gui, "ilobjectcopygui"), + "initTargetSelection" + ); + + // see ilObjectListGUI::insertCopyCommand(); + $this->addBlockCommand( + $copy_cmd, + $lng->txt("copy") + ); + } + } + + // footer info + if ($this->getFooterInfo() != "") { + $this->tpl->setCurrentBlock("footer_information"); + $this->tpl->setVariable("FOOTER_INFO", $this->getFooterInfo()); + $this->tpl->setVariable("FICOLSPAN", $this->getColSpan()); + $this->tpl->parseCurrentBlock(); + } + + $this->dropdown = array(); + + // commands + if (count($this->getBlockCommands()) > 0) { + $has_block_command = false; + + foreach ($this->getBlockCommands() as $command) { + if (!$command["img"] && !$command["html"]) { + $this->dropdown[] = $command; + continue; + } + + $has_block_command = true; + + if ($command["target"] != "") { + $this->tpl->setCurrentBlock("bc_target"); + $this->tpl->setVariable("CMD_TARGET", $command["target"]); + $this->tpl->parseCurrentBlock(); + } + + if ($command["img"] != "") { + $this->tpl->setCurrentBlock("bc_image"); + $this->tpl->setVariable("SRC_BC", $command["img"]); + $this->tpl->setVariable("ALT_BC", $command["text"]); + $this->tpl->parseCurrentBlock(); + $this->tpl->setCurrentBlock("block_command"); + } elseif ($command["html"] != "") { + if ($command['href'] !== '') { + $this->tpl->setCurrentBlock("bc_html"); + $this->tpl->setVariable("HTML", $command["html"]); + $this->tpl->parseCurrentBlock(); + $this->tpl->setCurrentBlock("block_command"); + } else { + $this->tpl->setCurrentBlock('bc_html_nohref'); + $this->tpl->setVariable('HTML_NOHREF', $command['html']); + $this->tpl->parseCurrentBlock(); + $this->tpl->setCurrentBlock("block_command"); + } + } else { + $this->tpl->setCurrentBlock("block_command"); + $this->tpl->setVariable("CMD_TEXT", $command["text"]); + $this->tpl->setVariable("BC_CLASS", 'class="il_ContainerItemCommand"'); + } + + if ($command['href'] !== '') { + $this->tpl->setVariable("CMD_HREF", $command["href"]); + } + $this->tpl->parseCurrentBlock(); + } + + if ($has_block_command) { + $this->tpl->setCurrentBlock("block_commands"); + $this->tpl->setVariable("CCOLSPAN", $this->getColSpan()); + $this->tpl->parseCurrentBlock(); + } + } + + // fill previous next + $this->fillPreviousNext(); + + // fill footer + $this->fillFooter(); + + // fill row for setting details + $this->fillDetailRow(); + + // header links + if (count($this->getHeaderLinks())) { + $counter = 0; + foreach ($this->getHeaderLinks() as $command) { + if ($counter > 0) { + $this->tpl->setCurrentBlock('head_delim'); + $this->tpl->touchBlock('head_delim'); + $this->tpl->parseCurrentBlock(); + } + if ($command['status'] == true) { + $this->tpl->setCurrentBlock('head_link'); + $this->tpl->setVariable('HHREF', $command['href']); + $this->tpl->setVariable('HLINK', $command['text']); + $this->tpl->parseCurrentBlock(); + } else { + $this->tpl->setCurrentBlock('head_text'); + $this->tpl->setVariable('HTEXT', $command['text']); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setCurrentBlock('head_item'); + $this->tpl->parseCurrentBlock(); + + ++$counter; + } + + $this->tpl->setCurrentBlock('header_links'); + $this->tpl->parseCurrentBlock(); + } + + // for screen readers we first output the title and the commands + // (e.g. close icon afterwards), otherwise we first output the + // header commands, since we want to have the close icon top right + // and not floated after the title + if (is_object($ilUser) && $ilUser->getPref("screen_reader_optimization")) { + $this->fillHeaderTitleBlock(); + $this->fillHeaderCommands(); + } else { + $this->fillHeaderCommands(); + $this->fillHeaderTitleBlock(); + } + + $this->tpl->setVariable("COLSPAN", $this->getColSpan()); + if ($this->getBigMode()) { + $this->tpl->touchBlock("hclassb"); + } else { + $this->tpl->touchBlock("hclass"); + } + + if ($ilCtrl->isAsynch()) { + // return without div wrapper + echo $this->tpl->getAsynch(); + } else { + // return incl. wrapping div with id + return '
getBlockType() . "_" . $this->block_id . '">' . + $this->tpl->get() . '
'; + } + } + + /** + * Fill header commands block + */ + public function fillHeaderCommands() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + + // header commands + if (count($this->getHeaderCommands()) > 0 || + ($this->detail_max > $this->detail_min && $this->detail_min == 0) || + $this->close_command != "") { + foreach ($this->getHeaderCommands() as $command) { + $this->tpl->setCurrentBlock("header_command"); + $this->tpl->setVariable("HREF_HCOMM", $command["href"]); + $this->tpl->setVariable("TXT_HCOMM", $command["text"]); + $this->tpl->parseCurrentBlock(); + } + + // close button + if (($this->detail_max > $this->detail_min && $this->detail_min == 0 && + !$this->getRepositoryMode()) + || + $this->close_command != "") { + $alt = $lng->txt("hide"); + if ($this->close_command != "") { + $url = $this->close_command; + } else { + $ilCtrl->setParameterByClass( + "ilcolumngui", + $this->getDetailParameter(), + "0" + ); + $url = $ilCtrl->getLinkTargetByClass("ilcolumngui", ""); + $ilCtrl->setParameterByClass( + "ilcolumngui", + $this->getDetailParameter(), + "" + ); + } + + $this->dropdown[] = array("text" => $alt, + "image" => $img, + "href" => $url); + } + + $this->tpl->setCurrentBlock("header_commands"); + $this->tpl->parseCurrentBlock(); + } + + // adv selection gui + include_once "Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"; + $dropdown = new ilAdvancedSelectionListGUI(); + $dropdown->setUseImages(true); + $dropdown->setStyle(ilAdvancedSelectionListGUI::STYLE_LINK_BUTTON); + $dropdown->setHeaderIcon(ilAdvancedSelectionListGUI::ICON_CONFIG); + $dropdown->setId("block_dd_" . $this->getBlockType() . "_" . $this->block_id); + foreach ($this->dropdown as $item) { + if ($item["href"] || $item["onclick"]) { + if ($item["checked"]) { + $item["image"] = ilUtil::getImagePath("icon_checked.svg"); + } + $dropdown->addItem( + $item["text"], + "", + $item["href"], + $item["image"], + $item["text"], + "", + "", + false, + $item["onclick"] + ); + } + } + $dropdown = $dropdown->getHTML(); + $this->tpl->setCurrentBlock("header_dropdown"); + $this->tpl->setVariable("ADV_DROPDOWN", $dropdown); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setCurrentBlock("hitem"); + $this->tpl->parseCurrentBlock(); + } + + + /** + * Fill header title block (title and + */ + public function fillHeaderTitleBlock() + { + $lng = $this->lng; + + // image + if ($this->getImage() != "") { + $this->tpl->setCurrentBlock("block_img"); + $this->tpl->setVariable("IMG_BLOCK", $this->getImage()); + $this->tpl->setVariable( + "IMID", + "block_" . $this->getBlockType() . "_" . $this->block_id + ); + $this->tpl->setVariable( + "IMG_ALT", + str_replace(array("'",'"'), "", strip_tags($lng->txt("icon") . " " . $this->getTitle())) + ); + $this->tpl->parseCurrentBlock(); + } + + // header title + $this->tpl->setCurrentBlock("header_title"); + $this->tpl->setVariable( + "BTID", + "block_" . $this->getBlockType() . "_" . $this->block_id + ); + $this->tpl->setVariable( + "BLOCK_TITLE", + $this->getTitle() + ); + $this->tpl->setVariable( + "TXT_BLOCK", + $lng->txt("block") + ); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setCurrentBlock("hitem"); + $this->tpl->parseCurrentBlock(); + } + + + /** + * Call this from overwritten fillDataSection(), if standard row based data is not used. + */ + public function setDataSection($a_content) + { + $this->tpl->setCurrentBlock("data_section"); + $this->tpl->setVariable("DATA", $a_content); + $this->tpl->parseCurrentBlock(); + $this->tpl->setVariable("BLOCK_ROW", ""); + } + + /** + * Standard implementation for row based data. + * Overwrite this and call setContent for other data. + */ + public function fillDataSection() + { + $this->nav_value = (isset($_POST[$this->getNavParameter()]) && $_POST[$this->getNavParameter()] != "") + ? $_POST[$this->getNavParameter()] + : (isset($_GET[$this->getNavParameter()]) ? $_GET[$this->getNavParameter()] : $this->nav_value); + $this->nav_value = ($this->nav_value == "" && isset($_SESSION[$this->getNavParameter()])) + ? $_SESSION[$this->getNavParameter()] + : $this->nav_value; + + $_SESSION[$this->getNavParameter()] = $this->nav_value; + + $nav = explode(":", $this->nav_value); + if (isset($nav[2])) { + $this->setOffset($nav[2]); + } else { + $this->setOffset(0); + } + + // data + $this->tpl->addBlockFile( + "BLOCK_ROW", + "block_row", + $this->getRowTemplateName(), + $this->getRowTemplateDir() + ); + + $data = $this->getData(); + $this->max_count = count($data); + $this->correctOffset(); + $data = array_slice($data, $this->getOffset(), $this->getLimit()); + + $this->preloadData($data); + + foreach ($data as $record) { + $this->tpl->setCurrentBlock("block_row"); + $this->fillRowColor(); + $this->fillRow($record); + $this->tpl->setCurrentBlock("block_row"); + $this->tpl->parseCurrentBlock(); + } + } + + public function fillRow($a_set) + { + foreach ($a_set as $key => $value) { + $this->tpl->setVariable("VAL_" . strtoupper($key), $value); + } + } + + public function fillFooter() + { + } + + final protected function fillRowColor($a_placeholder = "CSS_ROW") + { + $this->css_row = ($this->css_row != "ilBlockRow1") + ? "ilBlockRow1" + : "ilBlockRow2"; + $this->tpl->setVariable($a_placeholder, $this->css_row); + } + + /** + * Fill previous/next row + */ + public function fillPreviousNext() + { + $lng = $this->lng; + + // table pn numinfo + $numinfo = ""; + if ($this->getEnableNumInfo() && $this->max_count > 0) { + $start = $this->getOffset() + 1; // compute num info + $end = $this->getOffset() + $this->getLimit(); + + if ($end > $this->max_count or $this->getLimit() == 0) { + $end = $this->max_count; + } + + $numinfo = "(" . $start . "-" . $end . " " . strtolower($lng->txt("of")) . " " . $this->max_count . ")"; + } + + $this->setPreviousNextLinks(); + $this->fillFooterLinks(true, $numinfo); + } + + /** + * Get previous/next linkbar. + * + * @author Sascha Hofmann + * + * @return array linkbar or false on error + */ + public function setPreviousNextLinks() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + // if more entries then entries per page -> show link bar + if ($this->max_count > $this->getLimit() && ($this->getLimit() != 0)) { + // previous link + if ($this->getOffset() >= 1) { + $prevoffset = $this->getOffset() - $this->getLimit(); + + $ilCtrl->setParameterByClass( + "ilcolumngui", + $this->getNavParameter(), + "::" . $prevoffset + ); + + // ajax link + $ilCtrl->setParameterByClass( + "ilcolumngui", + "block_id", + "block_" . $this->getBlockType() . "_" . $this->block_id + ); + $block_id = "block_" . $this->getBlockType() . "_" . $this->block_id; + $onclick = $ilCtrl->getLinkTargetByClass( + "ilcolumngui", + "updateBlock", + "", + true + ); + $ilCtrl->setParameterByClass( + "ilcolumngui", + "block_id", + "" + ); + + // normal link + $href = $ilCtrl->getLinkTargetByClass("ilcolumngui", ""); + $text = $lng->txt("previous"); + + $this->addFooterLink($text, $href, $onclick, $block_id, true); + } + + // calculate number of pages + $pages = intval($this->max_count / $this->getLimit()); + + // add a page if a rest remains + if (($this->max_count % $this->getLimit())) { + $pages++; + } + + // show next link (if not last page) + if (!(($this->getOffset() / $this->getLimit())==($pages-1)) && ($pages!=1)) { + $newoffset = $this->getOffset() + $this->getLimit(); + + $ilCtrl->setParameterByClass( + "ilcolumngui", + $this->getNavParameter(), + "::" . $newoffset + ); + + // ajax link + $ilCtrl->setParameterByClass( + "ilcolumngui", + "block_id", + "block_" . $this->getBlockType() . "_" . $this->block_id + ); + //$this->tpl->setCurrentBlock("pnonclick"); + $block_id = "block_" . $this->getBlockType() . "_" . $this->block_id; + $onclick = $ilCtrl->getLinkTargetByClass( + "ilcolumngui", + "updateBlock", + "", + true + ); + //echo "-".$onclick."-"; + //$this->tpl->parseCurrentBlock(); + $ilCtrl->setParameterByClass( + "ilcolumngui", + "block_id", + "" + ); + + // normal link + $href = $ilCtrl->getLinkTargetByClass("ilcolumngui", ""); + $text = $lng->txt("next"); + + $this->addFooterLink($text, $href, $onclick, $block_id, true); + } + $ilCtrl->setParameterByClass( + "ilcolumngui", + $this->getNavParameter(), + "" + ); + return true; + } else { + return false; + } + } + + /** + * Fill footer links + * + * @return array linkbar or false on error + */ + public function fillFooterLinks($a_top = false, $a_numinfo = "") + { + $first = true; + $flinks = $this->getFooterLinks(); + + $prefix = ($a_top) ? "top" : "foot"; + + $has_link = false; + + $omit_separator = false; + foreach ($flinks as $flink) { + if ($flink["top"] != $a_top) { + continue; + } + + if (!$a_top) { + if ($flink["onclick"]) { + $flink["onclick"] = "ilBlockJSHandler('" . $flink["block_id"] . + "','" . $flink["onclick"] . "')"; + } + $this->dropdown[] = $flink; + continue; + } + + $has_link = true; + + if (!$first && !$omit_separator) { + $this->tpl->touchBlock($prefix . "_delim"); + $this->tpl->touchBlock($prefix . "_item"); + } + + // ajax link + if ($flink["onclick"] != "") { + $this->tpl->setCurrentBlock($prefix . "_onclick"); + $this->tpl->setVariable( + "OC_BLOCK_ID", + $flink["block_id"] + ); + $this->tpl->setVariable( + "OC_HREF", + $flink["onclick"] + ); + $this->tpl->parseCurrentBlock(); + } + + // normal link + if ($flink["href"] != "") { + // normal link + $this->tpl->setCurrentBlock($prefix . "_link"); + $this->tpl->setVariable( + "FHREF", + $flink["href"] + ); + $this->tpl->setVariable("FLINK", $flink["text"]); + $this->tpl->parseCurrentBlock(); + $this->tpl->touchBlock($prefix . "_item"); + } else { + $this->tpl->setCurrentBlock($prefix . "_text"); + $this->tpl->setVariable("FTEXT", $flink["text"]); + $this->tpl->parseCurrentBlock(); + $this->tpl->touchBlock($prefix . "_item"); + } + + $first = false; + $omit_separator = $flink["omit_separator"]; + } + + if ($a_numinfo != "" && $has_link) { + $this->tpl->setVariable("NUMINFO", $a_numinfo); + $first = false; + } + + /* + if (!$first) + { + $this->tpl->setVariable("PCOLSPAN", $this->getColSpan()); + $this->tpl->setCurrentBlock($prefix."_row"); + $this->tpl->parseCurrentBlock(); + } + */ + } + + /** + * Fill Detail Setting Row. + */ + public function fillDetailRow() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if ($this->enabledetailrow == false) { + return; + } + + $start = ($this->detail_min < 1) + ? $start = 1 + : $this->detail_min; + + $end = ($this->detail_max < $this->detail_min) + ? $this->detail_min + : $this->detail_max; + + $settings = array(); + for ($i = $start; $i <= $end; $i++) { + $settings[] = $i; + } + + if ($end > $start) { + foreach ($settings as $i) { + if (($i > $start && $i > 1)) { + //$this->tpl->touchBlock("det_delim"); + //$this->tpl->touchBlock("det_item"); + } + // if ($i != $this->getCurrentDetailLevel()) + // { + $ilCtrl->setParameterByClass( + "ilcolumngui", + $this->getDetailParameter(), + $i + ); + + $onclick = $onclick_id = ""; + + // ajax link + if ($i > 0) { + $ilCtrl->setParameterByClass( + "ilcolumngui", + "block_id", + "block_" . $this->getBlockType() . "_" . $this->block_id + ); + $onclick = $ilCtrl->getLinkTargetByClass( + "ilcolumngui", + "updateBlock", + "", + true + ); + $onclick_id = "block_" . $this->getBlockType() . "_" . $this->block_id; + $ilCtrl->setParameterByClass( + "ilcolumngui", + "block_id", + "" + ); + } + + // normal link + //$icon = ilUtil::getImagePath("details".$i.".svg"); + $text = $lng->txt("details") . " " . $i; + $url = $ilCtrl->getLinkTargetByClass("ilcolumngui", ""); + + if ($onclick) { + $onclick = "ilBlockJSHandler('" . $onclick_id . "','" . $onclick . "')"; + } + + $checked = ($i == $this->getCurrentDetailLevel()); + $this->dropdown[] = array("text" => $text, + "image" => $icon, + "href" => $url, + "onclick" => $onclick, + "checked" => $checked); + // } + } + + // info + icon in detail row + if ($this->getFooterInfo(true) != "") { + $this->tpl->setCurrentBlock("det_info"); + $this->tpl->setVariable("INFO_TEXT", $this->getFooterInfo(true)); + $this->tpl->setVariable("ALT_DET_INFO", $lng->txt("info_short")); + $this->tpl->setVariable("DI_BLOCK_ID", $this->getBlockType() . "_" . $this->getBlockId()); + $this->tpl->setVariable("IMG_DET_INFO", ilUtil::getImagePath("icon_info.svg")); + $this->tpl->parseCurrentBlock(); + } + + /* + $this->tpl->setCurrentBlock("detail_setting"); + $this->tpl->setVariable("TXT_DETAILS", $lng->txt("details")); + $this->tpl->setVariable("DCOLSPAN", $this->getColSpan()); + $this->tpl->parseCurrentBlock(); + */ + + $ilCtrl->setParameterByClass( + "ilcolumngui", + $this->getDetailParameter(), + "" + ); + } + } + + /** + * Can be overwritten in subclasses. Only the visible part of the complete data was passed so a preload of the visible data is possible. + * @param array $data + */ + protected function preloadData(array $data) + { + } } diff --git a/Services/Block/classes/class.ilBlockSetting.php b/Services/Block/classes/class.ilBlockSetting.php index f7e973b1977b21a3faf5269deb2b4560a022d602..3f80b6a2ffa0f6b36e9471096c2a06b58946a148 100755 --- a/Services/Block/classes/class.ilBlockSetting.php +++ b/Services/Block/classes/class.ilBlockSetting.php @@ -1,24 +1,24 @@ database(); - $ilSetting = $DIC->settings(); - - $key = $a_type.":".$a_setting.":".$a_user.":".$a_block_id; - if (isset(self::$setting[$key])) - { - return self::$setting[$key]; - } - - $set = $ilDB->query(sprintf("SELECT value FROM il_block_setting WHERE type = %s ". - "AND user_id = %s AND setting = %s AND block_id = %s", - $ilDB->quote($a_type, "text"), - $ilDB->quote($a_user, "integer"), - $ilDB->quote($a_setting, "text"), - $ilDB->quote($a_block_id, "integer"))); - if ($rec = $ilDB->fetchAssoc($set)) - { - self::$setting[$key] = $rec["value"]; - return $rec["value"]; - } - else if ($ilSetting->get('block_default_setting_'.$a_type.'_'.$a_setting, false)) - { - self::$setting[$key] = $ilSetting->get('block_default_setting_'.$a_type.'_'.$a_setting, false); - return $ilSetting->get('block_default_setting_'.$a_type.'_'.$a_setting, false); - } - else - { - self::$setting[$key] = false; - return false; - } - } - - /** - * Sets a default setting for a block. - * - * @global ilSetting $ilSetting - * - * @param string $a_type - * @param string $a_setting - * @param mixed $a_value - */ - public static function _setDefaultSetting($a_type, $a_setting, $a_value) - { - global $DIC; - - $ilSetting = $DIC->settings(); - $ilSetting->set('block_default_setting_'.$a_type.'_'.$a_setting, $a_value); - } - - /** - * Unsets a default setting for a block. - * - * @global ilSetting $ilSetting - * - * @param string $a_type - * @param string $a_setting - */ - public static function _unsetDefaultSetting($a_type, $a_setting) - { - global $DIC; - - $ilSetting = $DIC->settings(); - $ilSetting->delete('block_default_setting_'.$a_type.'_'.$a_setting); - } - - /** - * Preload pd info - * - * @param - * @return - */ - static function preloadPDBlockSettings() - { - global $DIC; - - $ilDB = $DIC->database(); - $ilUser = $DIC->user(); - - if (!self::$pd_preloaded) - { - $blocks = array("pdbookm", "pdcal", "pdfeedb", "pditems", - "pdmail", "pdnews", "pdnotes", "pdsysmess", "pdtag"); - $settings = array("detail", "nr", "side"); - $user_id = $ilUser->getId(); - - foreach ($blocks as $b) - { - foreach ($settings as $s) - { - $key = $b.":".$s.":".$user_id.":0"; - if ($s == "detail") - { - self::$setting[$key] = 2; - } - else - { - self::$setting[$key] = false; - } - } - } - - $set = $ilDB->query($q = "SELECT type, setting, value FROM il_block_setting WHERE ". - " user_id = ".$ilDB->quote($user_id, "integer"). - " AND ".$ilDB->in("type", $blocks, false, "text"). - " AND ".$ilDB->in("setting", $settings, false, "text") - ); - while ($rec = $ilDB->fetchAssoc($set)) - { - $key = $rec["type"].":".$rec["setting"].":".$user_id.":0"; - self::$setting[$key] = $rec["value"]; - } - - self::$pd_preloaded = true; - } - - } - - /** - * Write setting to database. - * - */ - public static function _write($a_type, $a_setting, $a_value, $a_user = 0, $a_block_id = 0) - { - global $DIC; - - $ilDB = $DIC->database(); - - $ilDB->manipulate(sprintf("DELETE FROM il_block_setting WHERE type = %s AND user_id = %s AND block_id = %s AND setting = %s", - $ilDB->quote($a_type, "text"), - $ilDB->quote($a_user, "integer"), - $ilDB->quote((int) $a_block_id, "integer"), - $ilDB->quote($a_setting, "text"))); - $ilDB->manipulate(sprintf("INSERT INTO il_block_setting (type, user_id, setting, block_id, value) VALUES (%s,%s,%s,%s,%s)", - $ilDB->quote($a_type, "text"), - $ilDB->quote($a_user, "integer"), - $ilDB->quote($a_setting, "text"), - $ilDB->quote((int) $a_block_id, "integer"), - $ilDB->quote($a_value, "text"))); - } - - /** - * Lookup detail level. - * - */ - public static function _lookupDetailLevel($a_type, $a_user = 0, $a_block_id = 0) - { - $detail = ilBlockSetting::_lookup($a_type, "detail", $a_user, $a_block_id); - - if ($detail === false) // return a level of 2 (standard value) - { // if record does not exist - return 2; - } - else - { - return $detail; - } - } - - /** - * Write detail level to database. - * - */ - public static function _writeDetailLevel($a_type, $a_value, $a_user = 0, $a_block_id = 0) - { - ilBlockSetting::_write($a_type, "detail", $a_value, $a_user, $a_block_id); - } - - /** - * Lookup number. - * - */ - public static function _lookupNr($a_type, $a_user = 0, $a_block_id = 0) - { - $nr = ilBlockSetting::_lookup($a_type, "nr", $a_user, $a_block_id); - - return $nr; - } - - /** - * Write number to database. - * - */ - public static function _writeNumber($a_type, $a_value, $a_user = 0, $a_block_id = 0) - { - ilBlockSetting::_write($a_type, "nr", $a_value, $a_user, $a_block_id); - } - - /** - * Lookup side. - * - */ - public static function _lookupSide($a_type, $a_user = 0, $a_block_id = 0) - { - $side = ilBlockSetting::_lookup($a_type, "side", $a_user, $a_block_id); - - return $side; - } - - /** - * Write side to database. - * - */ - public static function _writeSide($a_type, $a_value, $a_user = 0, $a_block_id = 0) - { - ilBlockSetting::_write($a_type, "side", $a_value, $a_user, $a_block_id); - } - - /** - * Delete block settings of user - * - */ - public static function _deleteSettingsOfUser($a_user) - { - global $DIC; - - $ilDB = $DIC->database(); - - if ($a_user > 0) - { - $ilDB->manipulate("DELETE FROM il_block_setting WHERE user_id = ". - $ilDB->quote($a_user, "integer")); - } - } - - /** - * Delete block settings of block - * - */ - public static function _deleteSettingsOfBlock($a_block_id, $a_block_type) - { - global $DIC; - - $ilDB = $DIC->database(); - - if ($a_block_id > 0) - { - $ilDB->manipulate("DELETE FROM il_block_setting WHERE block_id = ". - $ilDB->quote($a_block_id, "integer"). - " AND type = ".$ilDB->quote($a_block_type, "text")); - } - } - - /** - * Clone block settings - * - * @param string $block_type - * @param int $block_id - * @param int $new_block_id - */ - static public function cloneSettingsOfBlock(string $block_type, int $block_id, int $new_block_id) - { - global $DIC; - - $db = $DIC->database(); - - $set = $db->queryF("SELECT * FROM il_block_setting ". - " WHERE block_id = %s AND type = %s AND user_id = %s", - array("integer", "text", "integer"), - array($block_id, $block_type, 0) - ); - while ($rec = $db->fetchAssoc($set)) - { - self::_write($block_type, $rec["setting"], $rec["value"], 0, $new_block_id); - } - } - + public static $setting = array(); + public static $pd_preloaded = false; + + /** + * Lookup setting from database. + * + */ + public static function _lookup($a_type, $a_setting, $a_user = 0, $a_block_id = 0) + { + global $DIC; + + $ilDB = $DIC->database(); + $ilSetting = $DIC->settings(); + + $key = $a_type . ":" . $a_setting . ":" . $a_user . ":" . $a_block_id; + if (isset(self::$setting[$key])) { + return self::$setting[$key]; + } + + $set = $ilDB->query(sprintf( + "SELECT value FROM il_block_setting WHERE type = %s " . + "AND user_id = %s AND setting = %s AND block_id = %s", + $ilDB->quote($a_type, "text"), + $ilDB->quote($a_user, "integer"), + $ilDB->quote($a_setting, "text"), + $ilDB->quote($a_block_id, "integer") + )); + if ($rec = $ilDB->fetchAssoc($set)) { + self::$setting[$key] = $rec["value"]; + return $rec["value"]; + } elseif ($ilSetting->get('block_default_setting_' . $a_type . '_' . $a_setting, false)) { + self::$setting[$key] = $ilSetting->get('block_default_setting_' . $a_type . '_' . $a_setting, false); + return $ilSetting->get('block_default_setting_' . $a_type . '_' . $a_setting, false); + } else { + self::$setting[$key] = false; + return false; + } + } + + /** + * Sets a default setting for a block. + * + * @global ilSetting $ilSetting + * + * @param string $a_type + * @param string $a_setting + * @param mixed $a_value + */ + public static function _setDefaultSetting($a_type, $a_setting, $a_value) + { + global $DIC; + + $ilSetting = $DIC->settings(); + $ilSetting->set('block_default_setting_' . $a_type . '_' . $a_setting, $a_value); + } + + /** + * Unsets a default setting for a block. + * + * @global ilSetting $ilSetting + * + * @param string $a_type + * @param string $a_setting + */ + public static function _unsetDefaultSetting($a_type, $a_setting) + { + global $DIC; + + $ilSetting = $DIC->settings(); + $ilSetting->delete('block_default_setting_' . $a_type . '_' . $a_setting); + } + + /** + * Preload pd info + * + * @param + * @return + */ + public static function preloadPDBlockSettings() + { + global $DIC; + + $ilDB = $DIC->database(); + $ilUser = $DIC->user(); + + if (!self::$pd_preloaded) { + $blocks = array("pdbookm", "pdcal", "pdfeedb", "pditems", + "pdmail", "pdnews", "pdnotes", "pdsysmess", "pdtag"); + $settings = array("detail", "nr", "side"); + $user_id = $ilUser->getId(); + + foreach ($blocks as $b) { + foreach ($settings as $s) { + $key = $b . ":" . $s . ":" . $user_id . ":0"; + if ($s == "detail") { + self::$setting[$key] = 2; + } else { + self::$setting[$key] = false; + } + } + } + + $set = $ilDB->query( + $q = "SELECT type, setting, value FROM il_block_setting WHERE " . + " user_id = " . $ilDB->quote($user_id, "integer") . + " AND " . $ilDB->in("type", $blocks, false, "text") . + " AND " . $ilDB->in("setting", $settings, false, "text") + ); + while ($rec = $ilDB->fetchAssoc($set)) { + $key = $rec["type"] . ":" . $rec["setting"] . ":" . $user_id . ":0"; + self::$setting[$key] = $rec["value"]; + } + + self::$pd_preloaded = true; + } + } + + /** + * Write setting to database. + * + */ + public static function _write($a_type, $a_setting, $a_value, $a_user = 0, $a_block_id = 0) + { + global $DIC; + + $ilDB = $DIC->database(); + + $ilDB->manipulate(sprintf( + "DELETE FROM il_block_setting WHERE type = %s AND user_id = %s AND block_id = %s AND setting = %s", + $ilDB->quote($a_type, "text"), + $ilDB->quote($a_user, "integer"), + $ilDB->quote((int) $a_block_id, "integer"), + $ilDB->quote($a_setting, "text") + )); + $ilDB->manipulate(sprintf( + "INSERT INTO il_block_setting (type, user_id, setting, block_id, value) VALUES (%s,%s,%s,%s,%s)", + $ilDB->quote($a_type, "text"), + $ilDB->quote($a_user, "integer"), + $ilDB->quote($a_setting, "text"), + $ilDB->quote((int) $a_block_id, "integer"), + $ilDB->quote($a_value, "text") + )); + } + + /** + * Lookup detail level. + * + */ + public static function _lookupDetailLevel($a_type, $a_user = 0, $a_block_id = 0) + { + $detail = ilBlockSetting::_lookup($a_type, "detail", $a_user, $a_block_id); + + if ($detail === false) { // return a level of 2 (standard value) + // if record does not exist + return 2; + } else { + return $detail; + } + } + + /** + * Write detail level to database. + * + */ + public static function _writeDetailLevel($a_type, $a_value, $a_user = 0, $a_block_id = 0) + { + ilBlockSetting::_write($a_type, "detail", $a_value, $a_user, $a_block_id); + } + + /** + * Lookup number. + * + */ + public static function _lookupNr($a_type, $a_user = 0, $a_block_id = 0) + { + $nr = ilBlockSetting::_lookup($a_type, "nr", $a_user, $a_block_id); + + return $nr; + } + + /** + * Write number to database. + * + */ + public static function _writeNumber($a_type, $a_value, $a_user = 0, $a_block_id = 0) + { + ilBlockSetting::_write($a_type, "nr", $a_value, $a_user, $a_block_id); + } + + /** + * Lookup side. + * + */ + public static function _lookupSide($a_type, $a_user = 0, $a_block_id = 0) + { + $side = ilBlockSetting::_lookup($a_type, "side", $a_user, $a_block_id); + + return $side; + } + + /** + * Write side to database. + * + */ + public static function _writeSide($a_type, $a_value, $a_user = 0, $a_block_id = 0) + { + ilBlockSetting::_write($a_type, "side", $a_value, $a_user, $a_block_id); + } + + /** + * Delete block settings of user + * + */ + public static function _deleteSettingsOfUser($a_user) + { + global $DIC; + + $ilDB = $DIC->database(); + + if ($a_user > 0) { + $ilDB->manipulate("DELETE FROM il_block_setting WHERE user_id = " . + $ilDB->quote($a_user, "integer")); + } + } + + /** + * Delete block settings of block + * + */ + public static function _deleteSettingsOfBlock($a_block_id, $a_block_type) + { + global $DIC; + + $ilDB = $DIC->database(); + + if ($a_block_id > 0) { + $ilDB->manipulate("DELETE FROM il_block_setting WHERE block_id = " . + $ilDB->quote($a_block_id, "integer") . + " AND type = " . $ilDB->quote($a_block_type, "text")); + } + } + + /** + * Clone block settings + * + * @param string $block_type + * @param int $block_id + * @param int $new_block_id + */ + public static function cloneSettingsOfBlock(string $block_type, int $block_id, int $new_block_id) + { + global $DIC; + + $db = $DIC->database(); + + $set = $db->queryF( + "SELECT * FROM il_block_setting " . + " WHERE block_id = %s AND type = %s AND user_id = %s", + array("integer", "text", "integer"), + array($block_id, $block_type, 0) + ); + while ($rec = $db->fetchAssoc($set)) { + self::_write($block_type, $rec["setting"], $rec["value"], 0, $new_block_id); + } + } } -?> diff --git a/Services/Block/classes/class.ilColumnGUI.php b/Services/Block/classes/class.ilColumnGUI.php index 3d45df84679ed00154a022d0ccc6f71dc00fcd0a..9bfa06aa572e9d49a8ba3da39d11b2bcf97632ae 100644 --- a/Services/Block/classes/class.ilColumnGUI.php +++ b/Services/Block/classes/class.ilColumnGUI.php @@ -1,13 +1,13 @@ * @version $Id$ * -* @ilCtrl_IsCalledBy ilColumnGUI: ilCalendarGUI +* @ilCtrl_IsCalledBy ilColumnGUI: ilCalendarGUI * @ilCtrl_Calls ilColumnGUI: */ class ilColumnGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilBrowser - */ - protected $browser; - - /** - * @var ilSetting - */ - protected $settings; - - protected $side = IL_COL_RIGHT; - protected $type; - protected $enableedit = false; - protected $repositorymode = false; - protected $repositoryitems = array(); - - // all blocks that are repository objects - protected $rep_block_types = array("feed","poll"); - protected $block_property = array(); - protected $admincommands = null; - protected $movementmode = null; - protected $enablemovement = false; - - /** - * @var ilAdvancedSelectionListGUI - */ - protected $action_menu; - - // - // This two arrays may be replaced by some - // xml or other magic in the future... - // - - static protected $locations = array( - "ilNewsForContextBlockGUI" => "Services/News/", - "ilCalendarBlockGUI" => "Services/Calendar/", - "ilPDCalendarBlockGUI" => "Services/Calendar/", - "ilPDNotesBlockGUI" => "Services/Notes/", - "ilPDMailBlockGUI" => "Services/Mail/", - "ilPDSysMessageBlockGUI" => "Services/Mail/", - "ilPDSelectedItemsBlockGUI" => "Services/PersonalDesktop/ItemsBlock/", - "ilBookmarkBlockGUI" => "Services/Bookmarks/", - "ilPDNewsBlockGUI" => "Services/News/", - "ilExternalFeedBlockGUI" => "Services/Block/", - "ilPDExternalFeedBlockGUI" => "Services/Feeds/", - 'ilPDTaggingBlockGUI' => 'Services/Tagging/', - 'ilChatroomBlockGUI' => 'Modules/Chatroom/', - 'ilPollBlockGUI' => 'Modules/Poll/', - 'ilClassificationBlockGUI' => 'Services/Classification/', - 'ilPDPortfolioBlockGUI' => 'Modules/Portfolio/', - "ilPDStudyProgrammeSimpleListGUI" => "Modules/StudyProgramme/", - "ilPDStudyProgrammeExpandableListGUI" => "Modules/StudyProgramme/", - "ilForumPostingDraftsBlockGUI" => "Modules/Forum/" - ); - - static protected $block_types = array( - "ilPDMailBlockGUI" => "pdmail", - "ilPDNotesBlockGUI" => "pdnotes", - "ilPDNewsBlockGUI" => "pdnews", - "ilBookmarkBlockGUI" => "pdbookm", - "ilNewsForContextBlockGUI" => "news", - "ilCalendarBlockGUI" => "cal", - "ilPDCalendarBlockGUI" => "pdcal", - "ilExternalFeedBlockGUI" => "feed", - "ilPDExternalFeedBlockGUI" => "pdfeed", - "ilPDSysMessageBlockGUI" => "pdsysmess", - "ilPDSelectedItemsBlockGUI" => "pditems", - 'ilPDTaggingBlockGUI' => 'pdtag', - 'ilChatroomBlockGUI' => 'chatviewer', - 'ilPollBlockGUI' => 'poll', - 'ilClassificationBlockGUI' => 'clsfct', - 'ilPDPortfolioBlockGUI' => 'pdportf', - "ilPDStudyProgrammeSimpleListGUI" => "prgsimplelist", - "ilPDStudyProgrammeExpandableListGUI" => "prgexpandablelist", - "ilForumPostingDraftsBlockGUI" => "pdfrmpostdraft" - ); - - - protected $default_blocks = array( - "cat" => array( - "ilNewsForContextBlockGUI" => IL_COL_RIGHT, - "ilClassificationBlockGUI" => IL_COL_RIGHT - ), - "crs" => array( - "ilNewsForContextBlockGUI" => IL_COL_RIGHT, - "ilCalendarBlockGUI" => IL_COL_RIGHT, - "ilClassificationBlockGUI" => IL_COL_RIGHT - ), - "grp" => array( - "ilNewsForContextBlockGUI" => IL_COL_RIGHT, - "ilCalendarBlockGUI" => IL_COL_RIGHT, - "ilClassificationBlockGUI" => IL_COL_RIGHT - ), - "frm" => array("ilNewsForContextBlockGUI" => IL_COL_RIGHT), - "root" => array(), - "info" => array( - "ilNewsForContextBlockGUI" => IL_COL_RIGHT), - "pd" => array( - "ilPDCalendarBlockGUI" => IL_COL_RIGHT, - "ilPDPortfolioBlockGUI" => IL_COL_RIGHT, - "ilPDSysMessageBlockGUI" => IL_COL_LEFT, - "ilPDNewsBlockGUI" => IL_COL_LEFT, - "ilPDStudyProgrammeSimpleListGUI" => IL_COL_CENTER, - "ilPDStudyProgrammeExpandableListGUI" => IL_COL_CENTER, - "ilPDSelectedItemsBlockGUI" => IL_COL_CENTER, - "ilPDMailBlockGUI" => IL_COL_RIGHT, - "ilPDNotesBlockGUI" => IL_COL_RIGHT, - "ilBookmarkBlockGUI" => IL_COL_RIGHT, - "ilPDTaggingBlockGUI" => IL_COL_RIGHT, - "ilChatroomBlockGUI" => IL_COL_RIGHT, - "ilForumPostingDraftsBlockGUI" => IL_COL_RIGHT - ) - ); - - // these are only for pd blocks - // other blocks are rep objects now - protected $custom_blocks = array( - "cat" => array(), - "crs" => array(), - "grp" => array(), - "frm" => array(), - "root" => array(), - "info" => array(), - "fold" => array(), - "pd" => array("ilPDExternalFeedBlockGUI") - ); - - // check global activation for these block types - // @todo: add calendar - protected $check_global_activation = - array("news" => true, - "cal" => true, - "pdcal" => true, - "pdnews" => true, - "pdfeed" => true, - "pdbookm" => true, - "pdtag" => true, - "pdsysmess" => true, - "pdnotes" => true, - "chatviewer" => true, - "pdfrmpostdraft" => true, - "tagcld" => true, - "pdportf" => true, - "clsfct" => true); - - protected $check_nr_limit = - array("pdfeed" => true); - - /** - * Constructor - * - * @param - */ - public function __construct($a_col_type = "", $a_side = "", $use_std_context = false) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - $this->tpl = $DIC["tpl"]; - $this->browser = $DIC["ilBrowser"]; - $this->settings = $DIC->settings(); - $this->setColType($a_col_type); - $this->setSide($a_side); - } - - /** - * - * Adds location information of the custom block gui - * - * @access public - * @static - * @param string The name of the custom block gui class - * @param string The path of the custom block gui class - * - */ - public static function addCustomBlockLocation($className, $path) - { - self::$locations[$className] = $path; - } - - /** - * - * Adds the block type of the custom block gui - * - * @access public - * @static - * @param string The name of the custom block gui class - * @param string The identifier (block type) of the custom block gui - * - */ - public static function addCustomBlockType($className, $identifier) - { - self::$block_types[$className] = $identifier; - } - - /** - * Get Column Side of Current Command - * - * @return string Column Side - */ - static function getCmdSide() - { - return $_GET["col_side"]; - } - - /** - * Set Column Type. - * - * @param string $a_coltype Column Type - */ - function setColType($a_coltype) - { - $this->coltype = $a_coltype; - } - - /** - * Get Column Type. - * - * @return string Column Type - */ - function getColType() - { - return $this->coltype; - } - - /** - * Set Side IL_COL_LEFT | IL_COL_RIGHT. - * - * @param string $a_side Side IL_COL_LEFT | IL_COL_RIGHT - */ - function setSide($a_side) - { - $this->side = $a_side; - } - - /** - * Get Side IL_COL_LEFT | IL_COL_RIGHT. - * - * @return string Side IL_COL_LEFT | IL_COL_RIGHT - */ - function getSide() - { - return $this->side; - } - - /** - * Set EnableEdit. - * - * @param boolean $a_enableedit EnableEdit - */ - function setEnableEdit($a_enableedit) - { - $this->enableedit = $a_enableedit; - } - - /** - * Get EnableEdit. - * - * @return boolean EnableEdit - */ - function getEnableEdit() - { - return $this->enableedit; - } - - /** - * Set RepositoryMode. - * - * @param boolean $a_repositorymode RepositoryMode - */ - function setRepositoryMode($a_repositorymode) - { - $this->repositorymode = $a_repositorymode; - } - - /** - * Get RepositoryMode. - * - * @return boolean RepositoryMode - */ - function getRepositoryMode() - { - return $this->repositorymode; - } - - /** - * Set Administration Commmands. - * - * @param boolean $a_admincommands Administration Commmands - */ - function setAdminCommands($a_admincommands) - { - $this->admincommands = $a_admincommands; - } - - /** - * Get Administration Commmands. - * - * @return boolean Administration Commmands - */ - function getAdminCommands() - { - return $this->admincommands; - } - - /** - * Set Movement Mode. - * - * @param boolean $a_movementmode Movement Mode - */ - function setMovementMode($a_movementmode) - { - $this->movementmode = $a_movementmode; - } - - /** - * Get Movement Mode. - * - * @return boolean Movement Mode - */ - function getMovementMode() - { - return $this->movementmode; - } - - /** - * Set Enable Movement. - * - * @param boolean $a_enablemovement Enable Movement - */ - function setEnableMovement($a_enablemovement) - { - $this->enablemovement = $a_enablemovement; - } - - /** - * Get Enable Movement. - * - * @return boolean Enable Movement - */ - function getEnableMovement() - { - return $this->enablemovement; - } - - /** - * Get Screen Mode for current command. - */ - static function getScreenMode() - { - global $DIC; - - $ilCtrl = $DIC->ctrl(); - - if ($ilCtrl->getCmdClass() == "ilcolumngui") - { - switch ($ilCtrl->getCmd()) - { - case "addBlock": - return IL_SCREEN_CENTER; - } - } - - $cur_block_type = ""; - if (isset($_GET["block_type"]) && $_GET["block_type"]) - { - $cur_block_type = $_GET["block_type"]; - } - else if (isset($_POST["block_type"])) - { - $cur_block_type = $_POST["block_type"]; - } - - if ($class = array_search($cur_block_type, self::$block_types)) - { - include_once("./".self::$locations[$class]."classes/". - "class.".$class.".php"); - return call_user_func(array($class, 'getScreenMode')); - } - - return IL_SCREEN_SIDE; - } - - /** - * This function is supposed to be used for block type specific - * properties, that should be passed to ilBlockGUI->setProperty - * - * @param string $a_property property name - * @param string $a_value property value - */ - function setBlockProperty($a_block_type, $a_property, $a_value) - { - $this->block_property[$a_block_type][$a_property] = $a_value; - } - - function getBlockProperties($a_block_type) - { - return $this->block_property[$a_block_type]; - } - - function setAllBlockProperties($a_block_properties) - { - $this->block_property = $a_block_properties; - } - - /** - * Set Repository Items. - * - * @param array $a_repositoryitems Repository Items - */ - function setRepositoryItems($a_repositoryitems) - { - $this->repositoryitems = $a_repositoryitems; - } - - /** - * Get Repository Items. - * - * @return array Repository Items - */ - function getRepositoryItems() - { - return $this->repositoryitems; - } - - /** - * execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameter($this, "col_side" ,$this->getSide()); - //$ilCtrl->saveParameter($this, "col_side"); - - $next_class = $ilCtrl->getNextClass(); - $cmd = $ilCtrl->getCmd("getHTML"); - - $cur_block_type = ($_GET["block_type"]) - ? $_GET["block_type"] - : $_POST["block_type"]; - - if ($next_class != "") - { - // forward to block - if ($gui_class = array_search($cur_block_type, self::$block_types)) - { - include_once("./".self::$locations[$gui_class]."classes/". - "class.".$gui_class.".php"); - $ilCtrl->setParameter($this, "block_type", $cur_block_type); - $block_gui = new $gui_class(); - $block_gui->setProperties($this->block_property[$cur_block_type]); - $block_gui->setRepositoryMode($this->getRepositoryMode()); - $block_gui->setEnableEdit($this->getEnableEdit()); - $block_gui->setAdminCommands($this->getAdminCommands()); - - if (in_array($gui_class, $this->custom_blocks[$this->getColType()]) || - in_array($cur_block_type, $this->rep_block_types)) - { - $block_class = substr($gui_class, 0, strlen($gui_class)-3); - include_once("./".self::$locations[$gui_class]."classes/". - "class.".$block_class.".php"); - $app_block = new $block_class($_GET["block_id"]); - $block_gui->setBlock($app_block); - } - $html = $ilCtrl->forwardCommand($block_gui); - $ilCtrl->setParameter($this, "block_type", ""); - - return $html; - } - } - else - { - return $this->$cmd(); - } - } - - /** - * Get HTML for column. - */ - function getHTML() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameter($this, "col_side" ,$this->getSide()); - - $this->tpl = new ilTemplate("tpl.column.html", true, true, "Services/Block"); - - $this->determineBlocks(); - $this->showBlocks(); - - if ($this->getEnableEdit() || !$this->getRepositoryMode()) - { - $this->addHiddenBlockSelector(); - } - - return $this->tpl->get(); - } - - /** - * Show blocks. - */ - function showBlocks() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilUser = $this->user; - - $i = 1; - $sum_moveable = count($this->blocks[$this->getSide()]); - - foreach($this->blocks[$this->getSide()] as $block) - { - if ($ilCtrl->getContextObjType() != "user" || - ilBlockSetting::_lookupDetailLevel($block["type"], - $ilUser->getId(), $block["id"]) > 0) - { - $gui_class = $block["class"]; - $block_class = substr($block["class"], 0, strlen($block["class"])-3); - - // get block gui class - include_once("./".self::$locations[$gui_class]."classes/". - "class.".$gui_class.".php"); - $block_gui = new $gui_class(); - if (isset($this->block_property[$block["type"]])) - { - $block_gui->setProperties($this->block_property[$block["type"]]); - } - $block_gui->setRepositoryMode($this->getRepositoryMode()); - $block_gui->setEnableEdit($this->getEnableEdit()); - $block_gui->setAdminCommands($this->getAdminCommands()); - - // get block for custom blocks - if ($block["custom"]) - { - $path = "./".self::$locations[$gui_class]."classes/". - "class.".$block_class.".php"; - if(file_exists($path)) - { - include_once($path); - $app_block = new $block_class($block["id"]); - } - else - { - // we only need generic block - $app_block = new ilCustomBlock($block["id"]); - } - $block_gui->setBlock($app_block); - if (isset($block["ref_id"])) - { - $block_gui->setRefId($block["ref_id"]); - } - } - - $ilCtrl->setParameter($this, "block_type", $block_gui->getBlockType()); - $this->tpl->setCurrentBlock("col_block"); - - $html = $ilCtrl->getHTML($block_gui); - - // dummy block, if non visible, but movement is ongoing - if ($html == "" && $this->getRepositoryMode() && - $this->getMovementMode()) - { - include_once("./Services/Block/classes/class.ilDummyBlockGUI.php"); - $bl = new ilDummyBlockGUI(); - $bl->setBlockId($block["id"]); - $bl->setBlockType($block["type"]); - $bl->setTitle($lng->txt("invisible_block")); - $bl->setConfigMode($this->getMovementMode()); - $html = $bl->getHTML(); - } - - // don't render a block if it's empty - if ($html != "") - { - $this->tpl->setVariable("BLOCK", $html); - $this->tpl->parseCurrentBlock(); - $ilCtrl->setParameter($this, "block_type", ""); - } - - // count (moveable) blocks - if ($block["type"] != "pdsysmess" && $block["type"] != "pdfeedb" && - $block["type"] != "news") - { - $i++; - } - else - { - $sum_moveable--; - } - } - } - } - - /** - * Add hidden block and create block selectors. - */ - function addHiddenBlockSelector() - { - /** - * @var $lng ilLanguage - * @var $ilUser ilObjUser - * @var $ilCtrl ilCtrl - * $var $tpl ilTemplate - */ - $lng = $this->lng; - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - - // show selector for hidden blocks - include_once("Services/Block/classes/class.ilBlockSetting.php"); - $hidden_blocks = array(); - - foreach($this->blocks[$this->getSide()] as $block) - { - include_once("./".self::$locations[$block["class"]]."classes/". - "class.".$block["class"].".php"); - - if ($block["custom"] == false) - { - if ($ilCtrl->getContextObjType() == "user") // personal desktop - { - if (ilBlockSetting::_lookupDetailLevel($block["type"], $ilUser->getId()) == 0) - { - $hidden_blocks[$block["type"]] = $lng->txt('block_show_'.$block["type"]); - } - } - else if ($ilCtrl->getContextObjType() != "") - { - if (ilBlockSetting::_lookupDetailLevel($block["type"], $ilUser->getId(), - $ilCtrl->getContextObjId()) == 0) - { - $hidden_blocks[$block["type"]."_".$ilCtrl->getContextObjId()] = $lng->txt('block_show_'.$block["type"]); - } - } - } - else - { - if (ilBlockSetting::_lookupDetailLevel($block["type"], $ilUser->getId(), - $block["id"]) == 0) - { - include_once("./Services/Block/classes/class.ilCustomBlock.php"); - $cblock = new ilCustomBlock($block["id"]); - $hidden_blocks[$block["type"]."_".$block["id"]] = sprintf($lng->txt('block_show_x'), $cblock->getTitle()); - } - } - } - if(count($hidden_blocks) > 0) - { - foreach($hidden_blocks as $id => $title) - { - $ilCtrl->setParameter($this, 'block', $id); - $this->action_menu->addItem($title, '', $ilCtrl->getLinkTarget($this, 'activateBlock')); - $ilCtrl->setParameter($this, 'block', ''); - } - } - - // create block selection list - if (!$this->getRepositoryMode() || $this->getEnableEdit()) - { - $add_blocks = array(); - if ($this->getSide() == IL_COL_RIGHT) - { - if (is_array($this->custom_blocks[$this->getColType()])) - { - foreach($this->custom_blocks[$this->getColType()] as $block_class) - { - include_once("./".self::$locations[$block_class]."classes/". - "class.".$block_class.".php"); - $block_gui = new $block_class(); - $block_type = $block_gui->getBlockType(); - - // check if block type is globally (de-)activated - if ($this->isGloballyActivated($block_type)) - { - // check if number of blocks is limited - if (!$this->exceededLimit($block_type)) - { - $add_blocks[$block_type] = $lng->txt('block_create_'.$block_type); - } - } - } - } - } - if(count($add_blocks) > 0) - { - foreach($add_blocks as $id => $title) - { - $ilCtrl->setParameter($this, 'block_type', $id); - $this->action_menu->addItem($title, '', $ilCtrl->getLinkTarget($this, 'addBlock')); - $ilCtrl->setParameter($this, 'block_type', ''); - } - } - } - - $this->addBlockSorting(); - } - - /** - * - */ - protected function addBlockSorting() - { - global $DIC; - - if($this->getSide() == IL_COL_CENTER && $this->getEnableMovement()) - { - $ilBrowser = $this->browser; - $main_tpl = $DIC["tpl"]; - $ilCtrl = $this->ctrl; - - include_once 'Services/jQuery/classes/class.iljQueryUtil.php'; - iljQueryUtil::initjQuery(); - iljQueryUtil::initjQueryUI(); - - if($ilBrowser->isMobile() || $ilBrowser->isIpad()) - { - $main_tpl->addJavaScript('./libs/bower/bower_components/jqueryui-touch-punch/jquery.ui.touch-punch.min.js'); - } - $main_tpl->addJavaScript('./Services/Block/js/block_sorting.js'); - - // set the col_side parameter to pass the ctrl structure flow - $ilCtrl->setParameter($this, 'col_side', IL_COL_CENTER); - - $this->tpl->setVariable('BLOCK_SORTING_STORAGE_URL', $ilCtrl->getLinkTarget($this, 'saveBlockSortingAsynch', '', true, false)); - $this->tpl->setVariable('BLOCK_COLUMNS', json_encode(array('il_left_col', 'il_right_col'))); - $this->tpl->setVariable('BLOCK_COLUMNS_SELECTOR', '#il_left_col,#il_right_col'); - $this->tpl->setVariable('BLOCK_COLUMNS_PARAMETERS', json_encode(array(IL_COL_LEFT, IL_COL_RIGHT))); - - // restore col_side parameter - $ilCtrl->setParameter($this, 'col_side', $this->getSide()); - } - } - - /** - * Update Block (asynchronous) - */ - function updateBlock() - { - $ilCtrl = $this->ctrl; - - $this->determineBlocks(); - $i = 1; - $sum_moveable = count($this->blocks[$this->getSide()]); - - foreach ($this->blocks[$this->getSide()] as $block) - { - - include_once("./".self::$locations[$block["class"]]."classes/". - "class.".$block["class"].".php"); - - // set block id to context obj id, - // if block is not a custom block and context is not personal desktop - if (!$block["custom"] && $ilCtrl->getContextObjType() != "" && $ilCtrl->getContextObjType() != "user") - { - $block["id"] = $ilCtrl->getContextObjId(); - } - - //if (is_int(strpos($_GET["block_id"], "block_".$block["type"]."_".$block["id"]))) - - if ($_GET["block_id"] == "block_".$block["type"]."_".$block["id"]) - { - $gui_class = $block["class"]; - $block_class = substr($block["class"], 0, strlen($block["class"])-3); - - $block_gui = new $gui_class(); - $block_gui->setProperties($this->block_property[$block["type"]]); - $block_gui->setRepositoryMode($this->getRepositoryMode()); - $block_gui->setEnableEdit($this->getEnableEdit()); - $block_gui->setAdminCommands($this->getAdminCommands()); - - // get block for custom blocks - if ($block["custom"]) - { - include_once("./".self::$locations[$gui_class]."classes/". - "class.".$block_class.".php"); - $app_block = new $block_class($block["id"]); - $block_gui->setBlock($app_block); - $block_gui->setRefId($block["ref_id"]); - } - - $ilCtrl->setParameter($this, "block_type", $block["type"]); - echo $ilCtrl->getHTML($block_gui); - exit; - } - - // count (moveable) blocks - if ($block["type"] != "pdsysmess" && $block["type"] != "pdfeedb" - && $block["type"] != "news") - { - $i++; - } - else - { - $sum_moveable--; - } - } - echo "Error: ilColumnGUI::updateBlock: Block '". - $_GET["block_id"]."' unknown."; - exit; - } - - /** - * Activate hidden block - */ - function activateBlock() - { - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - - if ($_GET["block"] != "") - { - $block = explode("_", $_GET["block"]); - include_once("Services/Block/classes/class.ilBlockSetting.php"); - ilBlockSetting::_writeDetailLevel($block[0], 2, $ilUser->getId(), $block[1]); - } - - $ilCtrl->returnToParent($this); - } - - /** - * Add a block - */ - function addBlock() - - { - $ilCtrl = $this->ctrl; - - $class = array_search($_GET["block_type"], self::$block_types); - - $ilCtrl->setCmdClass($class); - $ilCtrl->setCmd("create"); - include_once("./".self::$locations[$class]."classes/class.".$class.".php"); - $block_gui = new $class(); - $block_gui->setProperties($this->block_property[$_GET["block_type"]]); - $block_gui->setRepositoryMode($this->getRepositoryMode()); - $block_gui->setEnableEdit($this->getEnableEdit()); - $block_gui->setAdminCommands($this->getAdminCommands()); - - $ilCtrl->setParameter($this, "block_type", $_GET["block_type"]); - $html = $ilCtrl->forwardCommand($block_gui); - $ilCtrl->setParameter($this, "block_type", ""); - return $html; - } - - /** - * Determine which blocks to show. - */ - function determineBlocks() - { - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - $ilSetting = $this->settings; - - include_once("./Services/Block/classes/class.ilBlockSetting.php"); - $this->blocks[IL_COL_LEFT] = array(); - $this->blocks[IL_COL_RIGHT] = array(); - $this->blocks[IL_COL_CENTER] = array(); - - $user_id = ($this->getColType() == "pd") - ? $ilUser->getId() - : 0; - - $def_nr = 1000; - if (is_array($this->default_blocks[$this->getColType()])) - { - foreach($this->default_blocks[$this->getColType()] as $class => $def_side) - { - $type = self::$block_types[$class]; - - if ($this->isGloballyActivated($type)) - { - $nr = ilBlockSetting::_lookupNr($type, $user_id); - if ($nr === false) - { - $nr = $def_nr++; - } - - - // extra handling for system messages, feedback block and news - if ($type == "news") // always show news first - { - $nr = -15; - } - if ($type == "cal") - { - $nr = -8; - } - if ($type == "pdsysmess") // always show sys mess first - { + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilBrowser + */ + protected $browser; + + /** + * @var ilSetting + */ + protected $settings; + + protected $side = IL_COL_RIGHT; + protected $type; + protected $enableedit = false; + protected $repositorymode = false; + protected $repositoryitems = array(); + + // all blocks that are repository objects + protected $rep_block_types = array("feed","poll"); + protected $block_property = array(); + protected $admincommands = null; + protected $movementmode = null; + protected $enablemovement = false; + + /** + * @var ilAdvancedSelectionListGUI + */ + protected $action_menu; + + // + // This two arrays may be replaced by some + // xml or other magic in the future... + // + + protected static $locations = array( + "ilNewsForContextBlockGUI" => "Services/News/", + "ilCalendarBlockGUI" => "Services/Calendar/", + "ilPDCalendarBlockGUI" => "Services/Calendar/", + "ilPDNotesBlockGUI" => "Services/Notes/", + "ilPDMailBlockGUI" => "Services/Mail/", + "ilPDSysMessageBlockGUI" => "Services/Mail/", + "ilPDSelectedItemsBlockGUI" => "Services/PersonalDesktop/ItemsBlock/", + "ilBookmarkBlockGUI" => "Services/Bookmarks/", + "ilPDNewsBlockGUI" => "Services/News/", + "ilExternalFeedBlockGUI" => "Services/Block/", + "ilPDExternalFeedBlockGUI" => "Services/Feeds/", + 'ilPDTaggingBlockGUI' => 'Services/Tagging/', + 'ilChatroomBlockGUI' => 'Modules/Chatroom/', + 'ilPollBlockGUI' => 'Modules/Poll/', + 'ilClassificationBlockGUI' => 'Services/Classification/', + 'ilPDPortfolioBlockGUI' => 'Modules/Portfolio/', + "ilPDStudyProgrammeSimpleListGUI" => "Modules/StudyProgramme/", + "ilPDStudyProgrammeExpandableListGUI" => "Modules/StudyProgramme/", + "ilForumPostingDraftsBlockGUI" => "Modules/Forum/" + ); + + protected static $block_types = array( + "ilPDMailBlockGUI" => "pdmail", + "ilPDNotesBlockGUI" => "pdnotes", + "ilPDNewsBlockGUI" => "pdnews", + "ilBookmarkBlockGUI" => "pdbookm", + "ilNewsForContextBlockGUI" => "news", + "ilCalendarBlockGUI" => "cal", + "ilPDCalendarBlockGUI" => "pdcal", + "ilExternalFeedBlockGUI" => "feed", + "ilPDExternalFeedBlockGUI" => "pdfeed", + "ilPDSysMessageBlockGUI" => "pdsysmess", + "ilPDSelectedItemsBlockGUI" => "pditems", + 'ilPDTaggingBlockGUI' => 'pdtag', + 'ilChatroomBlockGUI' => 'chatviewer', + 'ilPollBlockGUI' => 'poll', + 'ilClassificationBlockGUI' => 'clsfct', + 'ilPDPortfolioBlockGUI' => 'pdportf', + "ilPDStudyProgrammeSimpleListGUI" => "prgsimplelist", + "ilPDStudyProgrammeExpandableListGUI" => "prgexpandablelist", + "ilForumPostingDraftsBlockGUI" => "pdfrmpostdraft" + ); + + + protected $default_blocks = array( + "cat" => array( + "ilNewsForContextBlockGUI" => IL_COL_RIGHT, + "ilClassificationBlockGUI" => IL_COL_RIGHT + ), + "crs" => array( + "ilNewsForContextBlockGUI" => IL_COL_RIGHT, + "ilCalendarBlockGUI" => IL_COL_RIGHT, + "ilClassificationBlockGUI" => IL_COL_RIGHT + ), + "grp" => array( + "ilNewsForContextBlockGUI" => IL_COL_RIGHT, + "ilCalendarBlockGUI" => IL_COL_RIGHT, + "ilClassificationBlockGUI" => IL_COL_RIGHT + ), + "frm" => array("ilNewsForContextBlockGUI" => IL_COL_RIGHT), + "root" => array(), + "info" => array( + "ilNewsForContextBlockGUI" => IL_COL_RIGHT), + "pd" => array( + "ilPDCalendarBlockGUI" => IL_COL_RIGHT, + "ilPDPortfolioBlockGUI" => IL_COL_RIGHT, + "ilPDSysMessageBlockGUI" => IL_COL_LEFT, + "ilPDNewsBlockGUI" => IL_COL_LEFT, + "ilPDStudyProgrammeSimpleListGUI" => IL_COL_CENTER, + "ilPDStudyProgrammeExpandableListGUI" => IL_COL_CENTER, + "ilPDSelectedItemsBlockGUI" => IL_COL_CENTER, + "ilPDMailBlockGUI" => IL_COL_RIGHT, + "ilPDNotesBlockGUI" => IL_COL_RIGHT, + "ilBookmarkBlockGUI" => IL_COL_RIGHT, + "ilPDTaggingBlockGUI" => IL_COL_RIGHT, + "ilChatroomBlockGUI" => IL_COL_RIGHT, + "ilForumPostingDraftsBlockGUI" => IL_COL_RIGHT + ) + ); + + // these are only for pd blocks + // other blocks are rep objects now + protected $custom_blocks = array( + "cat" => array(), + "crs" => array(), + "grp" => array(), + "frm" => array(), + "root" => array(), + "info" => array(), + "fold" => array(), + "pd" => array("ilPDExternalFeedBlockGUI") + ); + + // check global activation for these block types + // @todo: add calendar + protected $check_global_activation = + array("news" => true, + "cal" => true, + "pdcal" => true, + "pdnews" => true, + "pdfeed" => true, + "pdbookm" => true, + "pdtag" => true, + "pdsysmess" => true, + "pdnotes" => true, + "chatviewer" => true, + "pdfrmpostdraft" => true, + "tagcld" => true, + "pdportf" => true, + "clsfct" => true); + + protected $check_nr_limit = + array("pdfeed" => true); + + /** + * Constructor + * + * @param + */ + public function __construct($a_col_type = "", $a_side = "", $use_std_context = false) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + $this->tpl = $DIC["tpl"]; + $this->browser = $DIC["ilBrowser"]; + $this->settings = $DIC->settings(); + $this->setColType($a_col_type); + $this->setSide($a_side); + } + + /** + * + * Adds location information of the custom block gui + * + * @access public + * @static + * @param string The name of the custom block gui class + * @param string The path of the custom block gui class + * + */ + public static function addCustomBlockLocation($className, $path) + { + self::$locations[$className] = $path; + } + + /** + * + * Adds the block type of the custom block gui + * + * @access public + * @static + * @param string The name of the custom block gui class + * @param string The identifier (block type) of the custom block gui + * + */ + public static function addCustomBlockType($className, $identifier) + { + self::$block_types[$className] = $identifier; + } + + /** + * Get Column Side of Current Command + * + * @return string Column Side + */ + public static function getCmdSide() + { + return $_GET["col_side"]; + } + + /** + * Set Column Type. + * + * @param string $a_coltype Column Type + */ + public function setColType($a_coltype) + { + $this->coltype = $a_coltype; + } + + /** + * Get Column Type. + * + * @return string Column Type + */ + public function getColType() + { + return $this->coltype; + } + + /** + * Set Side IL_COL_LEFT | IL_COL_RIGHT. + * + * @param string $a_side Side IL_COL_LEFT | IL_COL_RIGHT + */ + public function setSide($a_side) + { + $this->side = $a_side; + } + + /** + * Get Side IL_COL_LEFT | IL_COL_RIGHT. + * + * @return string Side IL_COL_LEFT | IL_COL_RIGHT + */ + public function getSide() + { + return $this->side; + } + + /** + * Set EnableEdit. + * + * @param boolean $a_enableedit EnableEdit + */ + public function setEnableEdit($a_enableedit) + { + $this->enableedit = $a_enableedit; + } + + /** + * Get EnableEdit. + * + * @return boolean EnableEdit + */ + public function getEnableEdit() + { + return $this->enableedit; + } + + /** + * Set RepositoryMode. + * + * @param boolean $a_repositorymode RepositoryMode + */ + public function setRepositoryMode($a_repositorymode) + { + $this->repositorymode = $a_repositorymode; + } + + /** + * Get RepositoryMode. + * + * @return boolean RepositoryMode + */ + public function getRepositoryMode() + { + return $this->repositorymode; + } + + /** + * Set Administration Commmands. + * + * @param boolean $a_admincommands Administration Commmands + */ + public function setAdminCommands($a_admincommands) + { + $this->admincommands = $a_admincommands; + } + + /** + * Get Administration Commmands. + * + * @return boolean Administration Commmands + */ + public function getAdminCommands() + { + return $this->admincommands; + } + + /** + * Set Movement Mode. + * + * @param boolean $a_movementmode Movement Mode + */ + public function setMovementMode($a_movementmode) + { + $this->movementmode = $a_movementmode; + } + + /** + * Get Movement Mode. + * + * @return boolean Movement Mode + */ + public function getMovementMode() + { + return $this->movementmode; + } + + /** + * Set Enable Movement. + * + * @param boolean $a_enablemovement Enable Movement + */ + public function setEnableMovement($a_enablemovement) + { + $this->enablemovement = $a_enablemovement; + } + + /** + * Get Enable Movement. + * + * @return boolean Enable Movement + */ + public function getEnableMovement() + { + return $this->enablemovement; + } + + /** + * Get Screen Mode for current command. + */ + public static function getScreenMode() + { + global $DIC; + + $ilCtrl = $DIC->ctrl(); + + if ($ilCtrl->getCmdClass() == "ilcolumngui") { + switch ($ilCtrl->getCmd()) { + case "addBlock": + return IL_SCREEN_CENTER; + } + } + + $cur_block_type = ""; + if (isset($_GET["block_type"]) && $_GET["block_type"]) { + $cur_block_type = $_GET["block_type"]; + } elseif (isset($_POST["block_type"])) { + $cur_block_type = $_POST["block_type"]; + } + + if ($class = array_search($cur_block_type, self::$block_types)) { + include_once("./" . self::$locations[$class] . "classes/" . + "class." . $class . ".php"); + return call_user_func(array($class, 'getScreenMode')); + } + + return IL_SCREEN_SIDE; + } + + /** + * This function is supposed to be used for block type specific + * properties, that should be passed to ilBlockGUI->setProperty + * + * @param string $a_property property name + * @param string $a_value property value + */ + public function setBlockProperty($a_block_type, $a_property, $a_value) + { + $this->block_property[$a_block_type][$a_property] = $a_value; + } + + public function getBlockProperties($a_block_type) + { + return $this->block_property[$a_block_type]; + } + + public function setAllBlockProperties($a_block_properties) + { + $this->block_property = $a_block_properties; + } + + /** + * Set Repository Items. + * + * @param array $a_repositoryitems Repository Items + */ + public function setRepositoryItems($a_repositoryitems) + { + $this->repositoryitems = $a_repositoryitems; + } + + /** + * Get Repository Items. + * + * @return array Repository Items + */ + public function getRepositoryItems() + { + return $this->repositoryitems; + } + + /** + * execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameter($this, "col_side", $this->getSide()); + //$ilCtrl->saveParameter($this, "col_side"); + + $next_class = $ilCtrl->getNextClass(); + $cmd = $ilCtrl->getCmd("getHTML"); + + $cur_block_type = ($_GET["block_type"]) + ? $_GET["block_type"] + : $_POST["block_type"]; + + if ($next_class != "") { + // forward to block + if ($gui_class = array_search($cur_block_type, self::$block_types)) { + include_once("./" . self::$locations[$gui_class] . "classes/" . + "class." . $gui_class . ".php"); + $ilCtrl->setParameter($this, "block_type", $cur_block_type); + $block_gui = new $gui_class(); + $block_gui->setProperties($this->block_property[$cur_block_type]); + $block_gui->setRepositoryMode($this->getRepositoryMode()); + $block_gui->setEnableEdit($this->getEnableEdit()); + $block_gui->setAdminCommands($this->getAdminCommands()); + + if (in_array($gui_class, $this->custom_blocks[$this->getColType()]) || + in_array($cur_block_type, $this->rep_block_types)) { + $block_class = substr($gui_class, 0, strlen($gui_class)-3); + include_once("./" . self::$locations[$gui_class] . "classes/" . + "class." . $block_class . ".php"); + $app_block = new $block_class($_GET["block_id"]); + $block_gui->setBlock($app_block); + } + $html = $ilCtrl->forwardCommand($block_gui); + $ilCtrl->setParameter($this, "block_type", ""); + + return $html; + } + } else { + return $this->$cmd(); + } + } + + /** + * Get HTML for column. + */ + public function getHTML() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameter($this, "col_side", $this->getSide()); + + $this->tpl = new ilTemplate("tpl.column.html", true, true, "Services/Block"); + + $this->determineBlocks(); + $this->showBlocks(); + + if ($this->getEnableEdit() || !$this->getRepositoryMode()) { + $this->addHiddenBlockSelector(); + } + + return $this->tpl->get(); + } + + /** + * Show blocks. + */ + public function showBlocks() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilUser = $this->user; + + $i = 1; + $sum_moveable = count($this->blocks[$this->getSide()]); + + foreach ($this->blocks[$this->getSide()] as $block) { + if ($ilCtrl->getContextObjType() != "user" || + ilBlockSetting::_lookupDetailLevel( + $block["type"], + $ilUser->getId(), + $block["id"] + ) > 0) { + $gui_class = $block["class"]; + $block_class = substr($block["class"], 0, strlen($block["class"])-3); + + // get block gui class + include_once("./" . self::$locations[$gui_class] . "classes/" . + "class." . $gui_class . ".php"); + $block_gui = new $gui_class(); + if (isset($this->block_property[$block["type"]])) { + $block_gui->setProperties($this->block_property[$block["type"]]); + } + $block_gui->setRepositoryMode($this->getRepositoryMode()); + $block_gui->setEnableEdit($this->getEnableEdit()); + $block_gui->setAdminCommands($this->getAdminCommands()); + + // get block for custom blocks + if ($block["custom"]) { + $path = "./" . self::$locations[$gui_class] . "classes/" . + "class." . $block_class . ".php"; + if (file_exists($path)) { + include_once($path); + $app_block = new $block_class($block["id"]); + } else { + // we only need generic block + $app_block = new ilCustomBlock($block["id"]); + } + $block_gui->setBlock($app_block); + if (isset($block["ref_id"])) { + $block_gui->setRefId($block["ref_id"]); + } + } + + $ilCtrl->setParameter($this, "block_type", $block_gui->getBlockType()); + $this->tpl->setCurrentBlock("col_block"); + + $html = $ilCtrl->getHTML($block_gui); + + // dummy block, if non visible, but movement is ongoing + if ($html == "" && $this->getRepositoryMode() && + $this->getMovementMode()) { + include_once("./Services/Block/classes/class.ilDummyBlockGUI.php"); + $bl = new ilDummyBlockGUI(); + $bl->setBlockId($block["id"]); + $bl->setBlockType($block["type"]); + $bl->setTitle($lng->txt("invisible_block")); + $bl->setConfigMode($this->getMovementMode()); + $html = $bl->getHTML(); + } + + // don't render a block if it's empty + if ($html != "") { + $this->tpl->setVariable("BLOCK", $html); + $this->tpl->parseCurrentBlock(); + $ilCtrl->setParameter($this, "block_type", ""); + } + + // count (moveable) blocks + if ($block["type"] != "pdsysmess" && $block["type"] != "pdfeedb" && + $block["type"] != "news") { + $i++; + } else { + $sum_moveable--; + } + } + } + } + + /** + * Add hidden block and create block selectors. + */ + public function addHiddenBlockSelector() + { + /** + * @var $lng ilLanguage + * @var $ilUser ilObjUser + * @var $ilCtrl ilCtrl + * $var $tpl ilTemplate + */ + $lng = $this->lng; + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + + // show selector for hidden blocks + include_once("Services/Block/classes/class.ilBlockSetting.php"); + $hidden_blocks = array(); + + foreach ($this->blocks[$this->getSide()] as $block) { + include_once("./" . self::$locations[$block["class"]] . "classes/" . + "class." . $block["class"] . ".php"); + + if ($block["custom"] == false) { + if ($ilCtrl->getContextObjType() == "user") { // personal desktop + if (ilBlockSetting::_lookupDetailLevel($block["type"], $ilUser->getId()) == 0) { + $hidden_blocks[$block["type"]] = $lng->txt('block_show_' . $block["type"]); + } + } elseif ($ilCtrl->getContextObjType() != "") { + if (ilBlockSetting::_lookupDetailLevel( + $block["type"], + $ilUser->getId(), + $ilCtrl->getContextObjId() + ) == 0) { + $hidden_blocks[$block["type"] . "_" . $ilCtrl->getContextObjId()] = $lng->txt('block_show_' . $block["type"]); + } + } + } else { + if (ilBlockSetting::_lookupDetailLevel( + $block["type"], + $ilUser->getId(), + $block["id"] + ) == 0) { + include_once("./Services/Block/classes/class.ilCustomBlock.php"); + $cblock = new ilCustomBlock($block["id"]); + $hidden_blocks[$block["type"] . "_" . $block["id"]] = sprintf($lng->txt('block_show_x'), $cblock->getTitle()); + } + } + } + if (count($hidden_blocks) > 0) { + foreach ($hidden_blocks as $id => $title) { + $ilCtrl->setParameter($this, 'block', $id); + $this->action_menu->addItem($title, '', $ilCtrl->getLinkTarget($this, 'activateBlock')); + $ilCtrl->setParameter($this, 'block', ''); + } + } + + // create block selection list + if (!$this->getRepositoryMode() || $this->getEnableEdit()) { + $add_blocks = array(); + if ($this->getSide() == IL_COL_RIGHT) { + if (is_array($this->custom_blocks[$this->getColType()])) { + foreach ($this->custom_blocks[$this->getColType()] as $block_class) { + include_once("./" . self::$locations[$block_class] . "classes/" . + "class." . $block_class . ".php"); + $block_gui = new $block_class(); + $block_type = $block_gui->getBlockType(); + + // check if block type is globally (de-)activated + if ($this->isGloballyActivated($block_type)) { + // check if number of blocks is limited + if (!$this->exceededLimit($block_type)) { + $add_blocks[$block_type] = $lng->txt('block_create_' . $block_type); + } + } + } + } + } + if (count($add_blocks) > 0) { + foreach ($add_blocks as $id => $title) { + $ilCtrl->setParameter($this, 'block_type', $id); + $this->action_menu->addItem($title, '', $ilCtrl->getLinkTarget($this, 'addBlock')); + $ilCtrl->setParameter($this, 'block_type', ''); + } + } + } + + $this->addBlockSorting(); + } + + /** + * + */ + protected function addBlockSorting() + { + global $DIC; + + if ($this->getSide() == IL_COL_CENTER && $this->getEnableMovement()) { + $ilBrowser = $this->browser; + $main_tpl = $DIC["tpl"]; + $ilCtrl = $this->ctrl; + + include_once 'Services/jQuery/classes/class.iljQueryUtil.php'; + iljQueryUtil::initjQuery(); + iljQueryUtil::initjQueryUI(); + + if ($ilBrowser->isMobile() || $ilBrowser->isIpad()) { + $main_tpl->addJavaScript('./libs/bower/bower_components/jqueryui-touch-punch/jquery.ui.touch-punch.min.js'); + } + $main_tpl->addJavaScript('./Services/Block/js/block_sorting.js'); + + // set the col_side parameter to pass the ctrl structure flow + $ilCtrl->setParameter($this, 'col_side', IL_COL_CENTER); + + $this->tpl->setVariable('BLOCK_SORTING_STORAGE_URL', $ilCtrl->getLinkTarget($this, 'saveBlockSortingAsynch', '', true, false)); + $this->tpl->setVariable('BLOCK_COLUMNS', json_encode(array('il_left_col', 'il_right_col'))); + $this->tpl->setVariable('BLOCK_COLUMNS_SELECTOR', '#il_left_col,#il_right_col'); + $this->tpl->setVariable('BLOCK_COLUMNS_PARAMETERS', json_encode(array(IL_COL_LEFT, IL_COL_RIGHT))); + + // restore col_side parameter + $ilCtrl->setParameter($this, 'col_side', $this->getSide()); + } + } + + /** + * Update Block (asynchronous) + */ + public function updateBlock() + { + $ilCtrl = $this->ctrl; + + $this->determineBlocks(); + $i = 1; + $sum_moveable = count($this->blocks[$this->getSide()]); + + foreach ($this->blocks[$this->getSide()] as $block) { + include_once("./" . self::$locations[$block["class"]] . "classes/" . + "class." . $block["class"] . ".php"); + + // set block id to context obj id, + // if block is not a custom block and context is not personal desktop + if (!$block["custom"] && $ilCtrl->getContextObjType() != "" && $ilCtrl->getContextObjType() != "user") { + $block["id"] = $ilCtrl->getContextObjId(); + } + + //if (is_int(strpos($_GET["block_id"], "block_".$block["type"]."_".$block["id"]))) + + if ($_GET["block_id"] == "block_" . $block["type"] . "_" . $block["id"]) { + $gui_class = $block["class"]; + $block_class = substr($block["class"], 0, strlen($block["class"])-3); + + $block_gui = new $gui_class(); + $block_gui->setProperties($this->block_property[$block["type"]]); + $block_gui->setRepositoryMode($this->getRepositoryMode()); + $block_gui->setEnableEdit($this->getEnableEdit()); + $block_gui->setAdminCommands($this->getAdminCommands()); + + // get block for custom blocks + if ($block["custom"]) { + include_once("./" . self::$locations[$gui_class] . "classes/" . + "class." . $block_class . ".php"); + $app_block = new $block_class($block["id"]); + $block_gui->setBlock($app_block); + $block_gui->setRefId($block["ref_id"]); + } + + $ilCtrl->setParameter($this, "block_type", $block["type"]); + echo $ilCtrl->getHTML($block_gui); + exit; + } + + // count (moveable) blocks + if ($block["type"] != "pdsysmess" && $block["type"] != "pdfeedb" + && $block["type"] != "news") { + $i++; + } else { + $sum_moveable--; + } + } + echo "Error: ilColumnGUI::updateBlock: Block '" . + $_GET["block_id"] . "' unknown."; + exit; + } + + /** + * Activate hidden block + */ + public function activateBlock() + { + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + + if ($_GET["block"] != "") { + $block = explode("_", $_GET["block"]); + include_once("Services/Block/classes/class.ilBlockSetting.php"); + ilBlockSetting::_writeDetailLevel($block[0], 2, $ilUser->getId(), $block[1]); + } + + $ilCtrl->returnToParent($this); + } + + /** + * Add a block + */ + public function addBlock() + { + $ilCtrl = $this->ctrl; + + $class = array_search($_GET["block_type"], self::$block_types); + + $ilCtrl->setCmdClass($class); + $ilCtrl->setCmd("create"); + include_once("./" . self::$locations[$class] . "classes/class." . $class . ".php"); + $block_gui = new $class(); + $block_gui->setProperties($this->block_property[$_GET["block_type"]]); + $block_gui->setRepositoryMode($this->getRepositoryMode()); + $block_gui->setEnableEdit($this->getEnableEdit()); + $block_gui->setAdminCommands($this->getAdminCommands()); + + $ilCtrl->setParameter($this, "block_type", $_GET["block_type"]); + $html = $ilCtrl->forwardCommand($block_gui); + $ilCtrl->setParameter($this, "block_type", ""); + return $html; + } + + /** + * Determine which blocks to show. + */ + public function determineBlocks() + { + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + $ilSetting = $this->settings; + + include_once("./Services/Block/classes/class.ilBlockSetting.php"); + $this->blocks[IL_COL_LEFT] = array(); + $this->blocks[IL_COL_RIGHT] = array(); + $this->blocks[IL_COL_CENTER] = array(); + + $user_id = ($this->getColType() == "pd") + ? $ilUser->getId() + : 0; + + $def_nr = 1000; + if (is_array($this->default_blocks[$this->getColType()])) { + foreach ($this->default_blocks[$this->getColType()] as $class => $def_side) { + $type = self::$block_types[$class]; + + if ($this->isGloballyActivated($type)) { + $nr = ilBlockSetting::_lookupNr($type, $user_id); + if ($nr === false) { + $nr = $def_nr++; + } + + + // extra handling for system messages, feedback block and news + if ($type == "news") { // always show news first + $nr = -15; + } + if ($type == "cal") { + $nr = -8; + } + if ($type == "pdsysmess") { // always show sys mess first // $nr = -15; - } - if ($type == "pdfeedb") // always show feedback request second - { - $nr = -10; - } - if ($type == "clsfct") // mkunkel wants to have this on top - { - $nr = -16; - } - $side = ilBlockSetting::_lookupSide($type, $user_id); - if ($side === false) - { - $side = $def_side; - } - - $this->blocks[$side][] = array( - "nr" => $nr, - "class" => $class, - "type" => $type, - "id" => 0, - "custom" => false); - } - } - } - - if (!$this->getRepositoryMode()) - { - include_once("./Services/Block/classes/class.ilCustomBlock.php"); - $custom_block = new ilCustomBlock(); - $custom_block->setContextObjId($ilCtrl->getContextObjId()); - $custom_block->setContextObjType($ilCtrl->getContextObjType()); - $c_blocks = $custom_block->queryBlocksForContext(); - - foreach($c_blocks as $c_block) - { - $type = $c_block["type"]; - - if ($this->isGloballyActivated($type)) - { - $class = array_search($type, self::$block_types); - $nr = ilBlockSetting::_lookupNr($type, $user_id, $c_block["id"]); - if ($nr === false) - { - $nr = $def_nr++; - } - $side = ilBlockSetting::_lookupSide($type, $user_id, $c_block["id"]); - if ($side === false) - { - $side = IL_COL_RIGHT; - } - - $this->blocks[$side][] = array( - "nr" => $nr, - "class" => $class, - "type" => $type, - "id" => $c_block["id"], - "custom" => true); - } - } - } - else // get all subitems - { - include_once("./Services/Block/classes/class.ilCustomBlock.php"); - $rep_items = $this->getRepositoryItems(); - - foreach($this->rep_block_types as $block_type) - { - if ($this->isGloballyActivated($block_type)) - { - if (!is_array($rep_items[$block_type])) - { - continue; - } - foreach($rep_items[$block_type] as $item) - { - $costum_block = new ilCustomBlock(); - $costum_block->setContextObjId($item["obj_id"]); - $costum_block->setContextObjType($block_type); - $c_blocks = $costum_block->queryBlocksForContext(); - $c_block = $c_blocks[0]; - - $type = $block_type; - $class = array_search($type, self::$block_types); - $nr = ilBlockSetting::_lookupNr($type, $user_id, $c_block["id"]); - if ($nr === false) - { - $nr = $def_nr++; - } - $side = ilBlockSetting::_lookupSide($type, $user_id, $c_block["id"]); - if ($side === false) - { - $side = IL_COL_RIGHT; - } - - $this->blocks[$side][] = array( - "nr" => $nr, - "class" => $class, - "type" => $type, - "id" => $c_block["id"], - "custom" => true, - "ref_id" => $item["ref_id"]); - } - } - } - - // repository object custom blocks - include_once("./Services/Block/classes/class.ilCustomBlock.php"); - $custom_block = new ilCustomBlock(); - $custom_block->setContextObjId($ilCtrl->getContextObjId()); - $custom_block->setContextObjType($ilCtrl->getContextObjType()); - $c_blocks = $custom_block->queryBlocksForContext(false); // get all sub-object types - - foreach($c_blocks as $c_block) - { - $type = $c_block["type"]; - $class = array_search($type, self::$block_types); - - if($class) - { - $nr = $def_nr++; - $side = IL_COL_RIGHT; - - $this->blocks[$side][] = array( - "nr" => $nr, - "class" => $class, - "type" => $type, - "id" => $c_block["id"], - "custom" => true); - } - } - } - - - $this->blocks[IL_COL_LEFT] = - ilUtil::sortArray($this->blocks[IL_COL_LEFT], "nr", "asc", true); - $this->blocks[IL_COL_RIGHT] = - ilUtil::sortArray($this->blocks[IL_COL_RIGHT], "nr", "asc", true); - $this->blocks[IL_COL_CENTER] = - ilUtil::sortArray($this->blocks[IL_COL_CENTER], "nr", "asc", true); - - } - - /** - * Check whether a block type is globally activated - */ - protected function isGloballyActivated($a_type) - { - $ilSetting = $this->settings; - $ilCtrl = $this->ctrl; - - if (isset($this->check_global_activation[$a_type]) && $this->check_global_activation[$a_type]) - { - if ($a_type == 'pdbookm') - { - if (!$ilSetting->get("disable_bookmarks")) - { - return true; - } - return false; - } - else if ($a_type == 'pdnotes') - { - if (!$ilSetting->get("disable_notes")) - { - return true; - } - return false; - } - else if ($a_type == 'pdportf') - { - if ($ilSetting->get("user_portfolios")) - { - $prfa_set = new ilSetting("prfa"); - if ($prfa_set->get("pd_block", false)) - { - return true; - } - } - return false; - } - elseif($a_type == 'news') - { - include_once 'Services/Container/classes/class.ilContainer.php'; - return - $ilSetting->get('block_activated_news') && - ilContainer::_lookupContainerSetting( - $GLOBALS['ilCtrl']->getContextObjId(), - 'cont_show_news', - true - ); - } - else if($a_type == 'pdsysmess') - { - require_once 'Services/Mail/classes/class.ilObjMail.php'; - return ((int)$ilSetting->get('pd_sys_msg_mode')) == ilObjMail::PD_SYS_MSG_OWN_BLOCK; - } - else if ($ilSetting->get("block_activated_".$a_type)) - { - return true; - } - elseif($a_type == 'cal') - { - include_once('./Services/Calendar/classes/class.ilCalendarSettings.php'); - return ilCalendarSettings::lookupCalendarActivated($GLOBALS['ilCtrl']->getContextObjId()); - - } - elseif($a_type == 'pdcal') - { - include_once('./Services/Calendar/classes/class.ilCalendarSettings.php'); - return ilCalendarSettings::_getInstance()->isEnabled(); - } - elseif($a_type == "tagcld") - { - $tags_active = new ilSetting("tags"); - return (bool)$tags_active->get("enable", false); - } - elseif($a_type == "clsfct") - { - if ($ilCtrl->getContextObjType() == "cat") // taxonomy presentation in classification block - { - return true; - } - $tags_active = new ilSetting("tags"); // tags presentation in classification block - return (bool)$tags_active->get("enable", false); - } - return false; - } - return true; - } - - /** - * Check whether limit is not exceeded - */ - protected function exceededLimit($a_type) - { - $ilSetting = $this->settings; - $ilCtrl = $this->ctrl; - - if ($this->check_nr_limit[$a_type]) - { - if (!$this->getRepositoryMode()) - { - include_once("./Services/Block/classes/class.ilCustomBlock.php"); - $costum_block = new ilCustomBlock(); - $costum_block->setContextObjId($ilCtrl->getContextObjId()); - $costum_block->setContextObjType($ilCtrl->getContextObjType()); - $costum_block->setType($a_type); - $res = $costum_block->queryCntBlockForContext(); - $cnt = (int) $res[0]["cnt"]; - } - else - { - return false; // not implemented for repository yet - } - - - if ($ilSetting->get("block_limit_".$a_type) > $cnt) - { - return false; - } - else - { - return true; - } - } - return false; - } - - /** - * Stores the block sequence asynchronously - */ - public function saveBlockSortingAsynch() - { - /** - * @var $ilUser ilObjUser - */ - $ilUser = $this->user; - - $response = new stdClass(); - $response->success = false; - - if(!isset($_POST[IL_COL_LEFT]['sequence']) && !isset($_POST[IL_COL_RIGHT]['sequence'])) - { - echo json_encode($response); - return; - }; - - if(in_array($this->getColType(), array('pd'))) - { - $response->success = true; - - foreach(array(IL_COL_LEFT => (array)$_POST[IL_COL_LEFT]['sequence'], IL_COL_RIGHT => (array)$_POST[IL_COL_RIGHT]['sequence']) as $side => $blocks) - { - $i = 2; - foreach($blocks as $block) - { - $bid = explode('_', $block); - ilBlockSetting::_writeNumber($bid[1], $i, $ilUser->getId(), $bid[2]); - ilBlockSetting::_writeSide($bid[1], $side, $ilUser->getId(), $bid[2]); - - $i +=2; - } - } - } - - echo json_encode($response); - exit(); - } - - /** - * @param \ilAdvancedSelectionListGUI $action_menu - * @return ilColumnGUI - */ - public function setActionMenu($action_menu) - { - $this->action_menu = $action_menu; - return $this; - } - - /** - * @return \ilAdvancedSelectionListGUI - */ - public function getActionMenu() - { - return $this->action_menu; - } + } + if ($type == "pdfeedb") { // always show feedback request second + $nr = -10; + } + if ($type == "clsfct") { // mkunkel wants to have this on top + $nr = -16; + } + $side = ilBlockSetting::_lookupSide($type, $user_id); + if ($side === false) { + $side = $def_side; + } + + $this->blocks[$side][] = array( + "nr" => $nr, + "class" => $class, + "type" => $type, + "id" => 0, + "custom" => false); + } + } + } + + if (!$this->getRepositoryMode()) { + include_once("./Services/Block/classes/class.ilCustomBlock.php"); + $custom_block = new ilCustomBlock(); + $custom_block->setContextObjId($ilCtrl->getContextObjId()); + $custom_block->setContextObjType($ilCtrl->getContextObjType()); + $c_blocks = $custom_block->queryBlocksForContext(); + + foreach ($c_blocks as $c_block) { + $type = $c_block["type"]; + + if ($this->isGloballyActivated($type)) { + $class = array_search($type, self::$block_types); + $nr = ilBlockSetting::_lookupNr($type, $user_id, $c_block["id"]); + if ($nr === false) { + $nr = $def_nr++; + } + $side = ilBlockSetting::_lookupSide($type, $user_id, $c_block["id"]); + if ($side === false) { + $side = IL_COL_RIGHT; + } + + $this->blocks[$side][] = array( + "nr" => $nr, + "class" => $class, + "type" => $type, + "id" => $c_block["id"], + "custom" => true); + } + } + } else { // get all subitems + include_once("./Services/Block/classes/class.ilCustomBlock.php"); + $rep_items = $this->getRepositoryItems(); + + foreach ($this->rep_block_types as $block_type) { + if ($this->isGloballyActivated($block_type)) { + if (!is_array($rep_items[$block_type])) { + continue; + } + foreach ($rep_items[$block_type] as $item) { + $costum_block = new ilCustomBlock(); + $costum_block->setContextObjId($item["obj_id"]); + $costum_block->setContextObjType($block_type); + $c_blocks = $costum_block->queryBlocksForContext(); + $c_block = $c_blocks[0]; + + $type = $block_type; + $class = array_search($type, self::$block_types); + $nr = ilBlockSetting::_lookupNr($type, $user_id, $c_block["id"]); + if ($nr === false) { + $nr = $def_nr++; + } + $side = ilBlockSetting::_lookupSide($type, $user_id, $c_block["id"]); + if ($side === false) { + $side = IL_COL_RIGHT; + } + + $this->blocks[$side][] = array( + "nr" => $nr, + "class" => $class, + "type" => $type, + "id" => $c_block["id"], + "custom" => true, + "ref_id" => $item["ref_id"]); + } + } + } + + // repository object custom blocks + include_once("./Services/Block/classes/class.ilCustomBlock.php"); + $custom_block = new ilCustomBlock(); + $custom_block->setContextObjId($ilCtrl->getContextObjId()); + $custom_block->setContextObjType($ilCtrl->getContextObjType()); + $c_blocks = $custom_block->queryBlocksForContext(false); // get all sub-object types + + foreach ($c_blocks as $c_block) { + $type = $c_block["type"]; + $class = array_search($type, self::$block_types); + + if ($class) { + $nr = $def_nr++; + $side = IL_COL_RIGHT; + + $this->blocks[$side][] = array( + "nr" => $nr, + "class" => $class, + "type" => $type, + "id" => $c_block["id"], + "custom" => true); + } + } + } + + + $this->blocks[IL_COL_LEFT] = + ilUtil::sortArray($this->blocks[IL_COL_LEFT], "nr", "asc", true); + $this->blocks[IL_COL_RIGHT] = + ilUtil::sortArray($this->blocks[IL_COL_RIGHT], "nr", "asc", true); + $this->blocks[IL_COL_CENTER] = + ilUtil::sortArray($this->blocks[IL_COL_CENTER], "nr", "asc", true); + } + + /** + * Check whether a block type is globally activated + */ + protected function isGloballyActivated($a_type) + { + $ilSetting = $this->settings; + $ilCtrl = $this->ctrl; + + if (isset($this->check_global_activation[$a_type]) && $this->check_global_activation[$a_type]) { + if ($a_type == 'pdbookm') { + if (!$ilSetting->get("disable_bookmarks")) { + return true; + } + return false; + } elseif ($a_type == 'pdnotes') { + if (!$ilSetting->get("disable_notes")) { + return true; + } + return false; + } elseif ($a_type == 'pdportf') { + if ($ilSetting->get("user_portfolios")) { + $prfa_set = new ilSetting("prfa"); + if ($prfa_set->get("pd_block", false)) { + return true; + } + } + return false; + } elseif ($a_type == 'news') { + include_once 'Services/Container/classes/class.ilContainer.php'; + return + $ilSetting->get('block_activated_news') && + ilContainer::_lookupContainerSetting( + $GLOBALS['ilCtrl']->getContextObjId(), + 'cont_show_news', + true + ); + } elseif ($a_type == 'pdsysmess') { + require_once 'Services/Mail/classes/class.ilObjMail.php'; + return ((int) $ilSetting->get('pd_sys_msg_mode')) == ilObjMail::PD_SYS_MSG_OWN_BLOCK; + } elseif ($ilSetting->get("block_activated_" . $a_type)) { + return true; + } elseif ($a_type == 'cal') { + include_once('./Services/Calendar/classes/class.ilCalendarSettings.php'); + return ilCalendarSettings::lookupCalendarActivated($GLOBALS['ilCtrl']->getContextObjId()); + } elseif ($a_type == 'pdcal') { + include_once('./Services/Calendar/classes/class.ilCalendarSettings.php'); + return ilCalendarSettings::_getInstance()->isEnabled(); + } elseif ($a_type == "tagcld") { + $tags_active = new ilSetting("tags"); + return (bool) $tags_active->get("enable", false); + } elseif ($a_type == "clsfct") { + if ($ilCtrl->getContextObjType() == "cat") { // taxonomy presentation in classification block + return true; + } + $tags_active = new ilSetting("tags"); // tags presentation in classification block + return (bool) $tags_active->get("enable", false); + } + return false; + } + return true; + } + + /** + * Check whether limit is not exceeded + */ + protected function exceededLimit($a_type) + { + $ilSetting = $this->settings; + $ilCtrl = $this->ctrl; + + if ($this->check_nr_limit[$a_type]) { + if (!$this->getRepositoryMode()) { + include_once("./Services/Block/classes/class.ilCustomBlock.php"); + $costum_block = new ilCustomBlock(); + $costum_block->setContextObjId($ilCtrl->getContextObjId()); + $costum_block->setContextObjType($ilCtrl->getContextObjType()); + $costum_block->setType($a_type); + $res = $costum_block->queryCntBlockForContext(); + $cnt = (int) $res[0]["cnt"]; + } else { + return false; // not implemented for repository yet + } + + + if ($ilSetting->get("block_limit_" . $a_type) > $cnt) { + return false; + } else { + return true; + } + } + return false; + } + + /** + * Stores the block sequence asynchronously + */ + public function saveBlockSortingAsynch() + { + /** + * @var $ilUser ilObjUser + */ + $ilUser = $this->user; + + $response = new stdClass(); + $response->success = false; + + if (!isset($_POST[IL_COL_LEFT]['sequence']) && !isset($_POST[IL_COL_RIGHT]['sequence'])) { + echo json_encode($response); + return; + }; + + if (in_array($this->getColType(), array('pd'))) { + $response->success = true; + + foreach (array(IL_COL_LEFT => (array) $_POST[IL_COL_LEFT]['sequence'], IL_COL_RIGHT => (array) $_POST[IL_COL_RIGHT]['sequence']) as $side => $blocks) { + $i = 2; + foreach ($blocks as $block) { + $bid = explode('_', $block); + ilBlockSetting::_writeNumber($bid[1], $i, $ilUser->getId(), $bid[2]); + ilBlockSetting::_writeSide($bid[1], $side, $ilUser->getId(), $bid[2]); + + $i +=2; + } + } + } + + echo json_encode($response); + exit(); + } + + /** + * @param \ilAdvancedSelectionListGUI $action_menu + * @return ilColumnGUI + */ + public function setActionMenu($action_menu) + { + $this->action_menu = $action_menu; + return $this; + } + + /** + * @return \ilAdvancedSelectionListGUI + */ + public function getActionMenu() + { + return $this->action_menu; + } } diff --git a/Services/Block/classes/class.ilCustomBlock.php b/Services/Block/classes/class.ilCustomBlock.php index 44744f6d1b53431d5fa36ceddb6ba4e3583d8d38..d52330bcc9eaa10e919e5e2baa84e0bd66398908 100755 --- a/Services/Block/classes/class.ilCustomBlock.php +++ b/Services/Block/classes/class.ilCustomBlock.php @@ -8,398 +8,383 @@ * @author Alex Killing * @version $Id$ */ -class ilCustomBlock +class ilCustomBlock { - /** - * @var ilDB - */ - protected $db; - - - protected $id; - protected $context_obj_id; - protected $context_obj_type; - protected $context_sub_obj_id; - protected $context_sub_obj_type; - protected $type; - protected $title; - - /** - * Constructor. - * - * @param int $a_id - */ - public function __construct($a_id = 0) - { - global $DIC; - - $this->db = $DIC->database(); - if ($a_id > 0) - { - $this->setId($a_id); - $this->read(); - } - - } - - /** - * Set Id. - * - * @param int $a_id - */ - public function setId($a_id) - { - $this->id = $a_id; - } - - /** - * Get Id. - * - * @return int - */ - public function getId() - { - return $this->id; - } - - /** - * Set ContextObjId. - * - * @param int $a_context_obj_id - */ - public function setContextObjId($a_context_obj_id) - { - $this->context_obj_id = $a_context_obj_id; - } - - /** - * Get ContextObjId. - * - * @return int - */ - public function getContextObjId() - { - return (int) $this->context_obj_id; - } - - /** - * Set ContextObjType. - * - * @param int $a_context_obj_type - */ - public function setContextObjType($a_context_obj_type) - { - $this->context_obj_type = $a_context_obj_type; - } - - /** - * Get ContextObjType. - * - * @return int - */ - public function getContextObjType() - { - return $this->context_obj_type; - } - - /** - * Set ContextSubObjId. - * - * @param int $a_context_sub_obj_id - */ - public function setContextSubObjId($a_context_sub_obj_id) - { - $this->context_sub_obj_id = $a_context_sub_obj_id; - } - - /** - * Get ContextSubObjId. - * - * @return int - */ - public function getContextSubObjId() - { - return (int) $this->context_sub_obj_id; - } - - /** - * Set ContextSubObjType. - * - * @param int $a_context_sub_obj_type - */ - public function setContextSubObjType($a_context_sub_obj_type) - { - $this->context_sub_obj_type = $a_context_sub_obj_type; - } - - /** - * Get ContextSubObjType. - * - * @return int - */ - public function getContextSubObjType() - { - return $this->context_sub_obj_type; - } - - /** - * Set Type. - * - * @param string $a_type Type of block. - */ - public function setType($a_type) - { - $this->type = $a_type; - } - - /** - * Get Type. - * - * @return string Type of block. - */ - public function getType() - { - return $this->type; - } - - /** - * Set Title. - * - * @param string $a_title Title of block - */ - public function setTitle($a_title) - { - $this->title = $a_title; - } - - /** - * Get Title. - * - * @return string Title of block - */ - public function getTitle() - { - return $this->title; - } - - /** - * Create new item. - * - */ - public function create() - { - $ilDB = $this->db; - - $this->setId($ilDB->nextId("il_custom_block")); - $query = "INSERT INTO il_custom_block (". - " id". - ", context_obj_id". - ", context_obj_type". - ", context_sub_obj_id". - ", context_sub_obj_type". - ", type". - ", title". - " ) VALUES (". - $ilDB->quote($this->getId(), "integer") - .",".$ilDB->quote($this->getContextObjId(), "integer") - .",".$ilDB->quote($this->getContextObjType(), "text") - .",".$ilDB->quote($this->getContextSubObjId(), "integer") - .",".$ilDB->quote($this->getContextSubObjType(), "text") - .",".$ilDB->quote($this->getType(), "text") - .",".$ilDB->quote($this->getTitle(), "text").")"; - $ilDB->manipulate($query); - } - - /** - * Read item from database. - * - */ - public function read() - { - $ilDB = $this->db; - - $query = "SELECT * FROM il_custom_block WHERE id = ". - $ilDB->quote($this->getId(), "integer"); - $set = $ilDB->query($query); - $rec = $ilDB->fetchAssoc($set); - - $this->setContextObjId($rec["context_obj_id"]); - $this->setContextObjType($rec["context_obj_type"]); - $this->setContextSubObjId($rec["context_sub_obj_id"]); - $this->setContextSubObjType($rec["context_sub_obj_type"]); - $this->setType($rec["type"]); - $this->setTitle($rec["title"]); - - } - - /** - * Update item in database. - * - */ - public function update() - { - $ilDB = $this->db; - - $query = "UPDATE il_custom_block SET ". - " context_obj_id = ".$ilDB->quote($this->getContextObjId(), "integer"). - ", context_obj_type = ".$ilDB->quote($this->getContextObjType(), "text"). - ", context_sub_obj_id = ".$ilDB->quote($this->getContextSubObjId(), "integer"). - ", context_sub_obj_type = ".$ilDB->quote($this->getContextSubObjType(), "text"). - ", type = ".$ilDB->quote($this->getType(), "text"). - ", title = ".$ilDB->quote($this->getTitle(), "text"). - " WHERE id = ".$ilDB->quote($this->getId(), "integer"); - - $ilDB->manipulate($query); - - } - - /** - * Delete item from database. - * - */ - public function delete() - { - $ilDB = $this->db; - - $query = "DELETE FROM il_custom_block". - " WHERE id = ".$ilDB->quote($this->getId(), "integer"); - - $ilDB->manipulate($query); - - } - - /** - * Query getBlocksForContext - * - */ - public function querygetBlocksForContext() - { - $ilDB = $this->db; - - $query = "SELECT id, context_obj_id, context_obj_type, context_sub_obj_id, context_sub_obj_type, type, title ". - "FROM il_custom_block ". - "WHERE ". - "context_obj_id = ".$ilDB->quote($this->getContextObjId(), "integer"). - " AND context_obj_type = ".$ilDB->quote($this->getContextObjType(), "text"). - " AND context_sub_obj_id = ".$ilDB->quote($this->getContextSubObjId(), "integer"). - " AND ".$ilDB->equals("context_sub_obj_type", $this->getContextSubObjType(), "text", true); - //" AND context_sub_obj_type = ".$ilDB->quote($this->getContextSubObjType(), "text").""; - - $set = $ilDB->query($query); - $result = array(); - while($rec = $ilDB->fetchAssoc($set)) - { - $result[] = $rec; - } - - return $result; - - } - - /** - * Query BlocksForContext - * - */ - public function queryBlocksForContext($a_include_sub_obj = true) - { - $ilDB = $this->db; - - $query = "SELECT id, context_obj_id, context_obj_type, context_sub_obj_id, context_sub_obj_type, type, title ". - "FROM il_custom_block ". - "WHERE ". - "context_obj_id = ".$ilDB->quote($this->getContextObjId(), "integer"). - " AND context_obj_type = ".$ilDB->quote($this->getContextObjType(), "text"); - if($a_include_sub_obj_id) - { - $query .= " AND context_sub_obj_id = ".$ilDB->quote($this->getContextSubObjId(), "integer"). - " AND ".$ilDB->equals("context_sub_obj_type", $this->getContextSubObjType(), "text", true); - //" AND context_sub_obj_type = ".$ilDB->quote($this->getContextSubObjType(), "text").""; - } -//echo "$query"; - $set = $ilDB->query($query); - $result = array(); - while($rec = $ilDB->fetchAssoc($set)) - { - $result[] = $rec; - } - - return $result; - - } - - /** - * Query TitleForId - * - */ - public function queryTitleForId() - { - $ilDB = $this->db; -die("ilCustomBlock::queryTitleForId is deprecated"); -/* - $query = "SELECT id ". - "FROM il_custom_block ". - "WHERE ".""; - - $set = $ilDB->query($query); - $result = array(); - while($rec = $set->fetchRow(ilDBConstants::FETCHMODE_ASSOC)) - { - $result[] = $rec; - } - - return $result; -*/ - } - - /** - * Query CntBlockForContext - * - */ - public function queryCntBlockForContext() - { - $ilDB = $this->db; - - $query = "SELECT count(*) as cnt ". - "FROM il_custom_block ". - "WHERE ". - "context_obj_id = ".$ilDB->quote($this->getContextObjId(), "integer"). - " AND context_obj_type = ".$ilDB->quote($this->getContextObjType(), "text"). - " AND context_sub_obj_id = ".$ilDB->quote($this->getContextSubObjId(), "integer"). - " AND ".$ilDB->equals("context_sub_obj_type", $this->getContextSubObjType(), "text", true). - " AND type = ".$ilDB->quote($this->getType(), "text").""; - - $set = $ilDB->query($query); - $result = array(); - while($rec = $ilDB->fetchAssoc($set)) - { - $result[] = $rec; - } - - return $result; - } - - public static function multiBlockQuery($a_context_obj_type, array $a_context_obj_ids) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT id, context_obj_id, context_obj_type, context_sub_obj_id, context_sub_obj_type, type, title ". - "FROM il_custom_block ". - "WHERE ". - $ilDB->in("context_obj_id", $a_context_obj_ids, "", "integer"). - " AND context_obj_type = ".$ilDB->quote($a_context_obj_type, "text"). - " ORDER BY title"; - $set = $ilDB->query($query); - $result = array(); - while($rec = $ilDB->fetchAssoc($set)) - { - $result[] = $rec; - } - - return $result; - } - - + /** + * @var ilDB + */ + protected $db; + + + protected $id; + protected $context_obj_id; + protected $context_obj_type; + protected $context_sub_obj_id; + protected $context_sub_obj_type; + protected $type; + protected $title; + + /** + * Constructor. + * + * @param int $a_id + */ + public function __construct($a_id = 0) + { + global $DIC; + + $this->db = $DIC->database(); + if ($a_id > 0) { + $this->setId($a_id); + $this->read(); + } + } + + /** + * Set Id. + * + * @param int $a_id + */ + public function setId($a_id) + { + $this->id = $a_id; + } + + /** + * Get Id. + * + * @return int + */ + public function getId() + { + return $this->id; + } + + /** + * Set ContextObjId. + * + * @param int $a_context_obj_id + */ + public function setContextObjId($a_context_obj_id) + { + $this->context_obj_id = $a_context_obj_id; + } + + /** + * Get ContextObjId. + * + * @return int + */ + public function getContextObjId() + { + return (int) $this->context_obj_id; + } + + /** + * Set ContextObjType. + * + * @param int $a_context_obj_type + */ + public function setContextObjType($a_context_obj_type) + { + $this->context_obj_type = $a_context_obj_type; + } + + /** + * Get ContextObjType. + * + * @return int + */ + public function getContextObjType() + { + return $this->context_obj_type; + } + + /** + * Set ContextSubObjId. + * + * @param int $a_context_sub_obj_id + */ + public function setContextSubObjId($a_context_sub_obj_id) + { + $this->context_sub_obj_id = $a_context_sub_obj_id; + } + + /** + * Get ContextSubObjId. + * + * @return int + */ + public function getContextSubObjId() + { + return (int) $this->context_sub_obj_id; + } + + /** + * Set ContextSubObjType. + * + * @param int $a_context_sub_obj_type + */ + public function setContextSubObjType($a_context_sub_obj_type) + { + $this->context_sub_obj_type = $a_context_sub_obj_type; + } + + /** + * Get ContextSubObjType. + * + * @return int + */ + public function getContextSubObjType() + { + return $this->context_sub_obj_type; + } + + /** + * Set Type. + * + * @param string $a_type Type of block. + */ + public function setType($a_type) + { + $this->type = $a_type; + } + + /** + * Get Type. + * + * @return string Type of block. + */ + public function getType() + { + return $this->type; + } + + /** + * Set Title. + * + * @param string $a_title Title of block + */ + public function setTitle($a_title) + { + $this->title = $a_title; + } + + /** + * Get Title. + * + * @return string Title of block + */ + public function getTitle() + { + return $this->title; + } + + /** + * Create new item. + * + */ + public function create() + { + $ilDB = $this->db; + + $this->setId($ilDB->nextId("il_custom_block")); + $query = "INSERT INTO il_custom_block (" . + " id" . + ", context_obj_id" . + ", context_obj_type" . + ", context_sub_obj_id" . + ", context_sub_obj_type" . + ", type" . + ", title" . + " ) VALUES (" . + $ilDB->quote($this->getId(), "integer") + . "," . $ilDB->quote($this->getContextObjId(), "integer") + . "," . $ilDB->quote($this->getContextObjType(), "text") + . "," . $ilDB->quote($this->getContextSubObjId(), "integer") + . "," . $ilDB->quote($this->getContextSubObjType(), "text") + . "," . $ilDB->quote($this->getType(), "text") + . "," . $ilDB->quote($this->getTitle(), "text") . ")"; + $ilDB->manipulate($query); + } + + /** + * Read item from database. + * + */ + public function read() + { + $ilDB = $this->db; + + $query = "SELECT * FROM il_custom_block WHERE id = " . + $ilDB->quote($this->getId(), "integer"); + $set = $ilDB->query($query); + $rec = $ilDB->fetchAssoc($set); + + $this->setContextObjId($rec["context_obj_id"]); + $this->setContextObjType($rec["context_obj_type"]); + $this->setContextSubObjId($rec["context_sub_obj_id"]); + $this->setContextSubObjType($rec["context_sub_obj_type"]); + $this->setType($rec["type"]); + $this->setTitle($rec["title"]); + } + + /** + * Update item in database. + * + */ + public function update() + { + $ilDB = $this->db; + + $query = "UPDATE il_custom_block SET " . + " context_obj_id = " . $ilDB->quote($this->getContextObjId(), "integer") . + ", context_obj_type = " . $ilDB->quote($this->getContextObjType(), "text") . + ", context_sub_obj_id = " . $ilDB->quote($this->getContextSubObjId(), "integer") . + ", context_sub_obj_type = " . $ilDB->quote($this->getContextSubObjType(), "text") . + ", type = " . $ilDB->quote($this->getType(), "text") . + ", title = " . $ilDB->quote($this->getTitle(), "text") . + " WHERE id = " . $ilDB->quote($this->getId(), "integer"); + + $ilDB->manipulate($query); + } + + /** + * Delete item from database. + * + */ + public function delete() + { + $ilDB = $this->db; + + $query = "DELETE FROM il_custom_block" . + " WHERE id = " . $ilDB->quote($this->getId(), "integer"); + + $ilDB->manipulate($query); + } + + /** + * Query getBlocksForContext + * + */ + public function querygetBlocksForContext() + { + $ilDB = $this->db; + + $query = "SELECT id, context_obj_id, context_obj_type, context_sub_obj_id, context_sub_obj_type, type, title " . + "FROM il_custom_block " . + "WHERE " . + "context_obj_id = " . $ilDB->quote($this->getContextObjId(), "integer") . + " AND context_obj_type = " . $ilDB->quote($this->getContextObjType(), "text") . + " AND context_sub_obj_id = " . $ilDB->quote($this->getContextSubObjId(), "integer") . + " AND " . $ilDB->equals("context_sub_obj_type", $this->getContextSubObjType(), "text", true); + //" AND context_sub_obj_type = ".$ilDB->quote($this->getContextSubObjType(), "text").""; + + $set = $ilDB->query($query); + $result = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $result[] = $rec; + } + + return $result; + } + + /** + * Query BlocksForContext + * + */ + public function queryBlocksForContext($a_include_sub_obj = true) + { + $ilDB = $this->db; + + $query = "SELECT id, context_obj_id, context_obj_type, context_sub_obj_id, context_sub_obj_type, type, title " . + "FROM il_custom_block " . + "WHERE " . + "context_obj_id = " . $ilDB->quote($this->getContextObjId(), "integer") . + " AND context_obj_type = " . $ilDB->quote($this->getContextObjType(), "text"); + if ($a_include_sub_obj_id) { + $query .= " AND context_sub_obj_id = " . $ilDB->quote($this->getContextSubObjId(), "integer") . + " AND " . $ilDB->equals("context_sub_obj_type", $this->getContextSubObjType(), "text", true); + //" AND context_sub_obj_type = ".$ilDB->quote($this->getContextSubObjType(), "text").""; + } + //echo "$query"; + $set = $ilDB->query($query); + $result = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $result[] = $rec; + } + + return $result; + } + + /** + * Query TitleForId + * + */ + public function queryTitleForId() + { + $ilDB = $this->db; + die("ilCustomBlock::queryTitleForId is deprecated"); + /* + $query = "SELECT id ". + "FROM il_custom_block ". + "WHERE ".""; + + $set = $ilDB->query($query); + $result = array(); + while($rec = $set->fetchRow(ilDBConstants::FETCHMODE_ASSOC)) + { + $result[] = $rec; + } + + return $result; + */ + } + + /** + * Query CntBlockForContext + * + */ + public function queryCntBlockForContext() + { + $ilDB = $this->db; + + $query = "SELECT count(*) as cnt " . + "FROM il_custom_block " . + "WHERE " . + "context_obj_id = " . $ilDB->quote($this->getContextObjId(), "integer") . + " AND context_obj_type = " . $ilDB->quote($this->getContextObjType(), "text") . + " AND context_sub_obj_id = " . $ilDB->quote($this->getContextSubObjId(), "integer") . + " AND " . $ilDB->equals("context_sub_obj_type", $this->getContextSubObjType(), "text", true) . + " AND type = " . $ilDB->quote($this->getType(), "text") . ""; + + $set = $ilDB->query($query); + $result = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $result[] = $rec; + } + + return $result; + } + + public static function multiBlockQuery($a_context_obj_type, array $a_context_obj_ids) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT id, context_obj_id, context_obj_type, context_sub_obj_id, context_sub_obj_type, type, title " . + "FROM il_custom_block " . + "WHERE " . + $ilDB->in("context_obj_id", $a_context_obj_ids, "", "integer") . + " AND context_obj_type = " . $ilDB->quote($a_context_obj_type, "text") . + " ORDER BY title"; + $set = $ilDB->query($query); + $result = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $result[] = $rec; + } + + return $result; + } } -?> diff --git a/Services/Block/classes/class.ilDummyBlockGUI.php b/Services/Block/classes/class.ilDummyBlockGUI.php index 2925cac4cc991a74a8221bfac437dbb600ec3386..2c11d4bc535a3c3a603867cfc97a11147e2316a2 100755 --- a/Services/Block/classes/class.ilDummyBlockGUI.php +++ b/Services/Block/classes/class.ilDummyBlockGUI.php @@ -1,24 +1,24 @@ ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - $this->access = $DIC->access(); - $this->settings = $DIC->settings(); - - parent::__construct(); - - $this->setLimit(5); - $this->allow_moving = true; - } - - /** - * @inheritdoc - */ - public function getBlockType(): string - { - return self::$block_type; - } - - /** - * Set block type - * - * @return string Block type. - */ - static function setBlockType($a_type) - { - self::$block_type = $a_type; - } - - /** - * @inheritdoc - */ - protected function isRepositoryObject(): bool - { - return false; - } - - - /** - * Get Screen Mode for current command. - */ - static function getScreenMode() - { - global $DIC; - - $ilCtrl = $DIC->ctrl(); - - return IL_SCREEN_SIDE; - } - - /** - * Do most of the initialisation. - */ - function setBlock($a_block) - { - } - - /** - * execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - - $next_class = $ilCtrl->getNextClass(); - $cmd = $ilCtrl->getCmd("getHTML"); - - switch ($next_class) - { - default: - return $this->$cmd(); - } - } - - /** - * Fill data section - */ - function fillDataSection() - { - $lng = $this->lng; - - $this->setDataSection($lng->txt("invisible_block_mess")); - } - - /** - * Get block HTML code. - */ - function getHTML() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilUser = $this->user; - $ilAccess = $this->access; - $ilSetting = $this->settings; - - return parent::getHTML(); - } + /** + * @var ilSetting + */ + protected $settings; + + public static $block_type = ""; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + $this->access = $DIC->access(); + $this->settings = $DIC->settings(); + + parent::__construct(); + + $this->setLimit(5); + $this->allow_moving = true; + } + + /** + * @inheritdoc + */ + public function getBlockType() : string + { + return self::$block_type; + } + + /** + * Set block type + * + * @return string Block type. + */ + public static function setBlockType($a_type) + { + self::$block_type = $a_type; + } + + /** + * @inheritdoc + */ + protected function isRepositoryObject() : bool + { + return false; + } + + + /** + * Get Screen Mode for current command. + */ + public static function getScreenMode() + { + global $DIC; + + $ilCtrl = $DIC->ctrl(); + + return IL_SCREEN_SIDE; + } + + /** + * Do most of the initialisation. + */ + public function setBlock($a_block) + { + } + + /** + * execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $next_class = $ilCtrl->getNextClass(); + $cmd = $ilCtrl->getCmd("getHTML"); + + switch ($next_class) { + default: + return $this->$cmd(); + } + } + + /** + * Fill data section + */ + public function fillDataSection() + { + $lng = $this->lng; + + $this->setDataSection($lng->txt("invisible_block_mess")); + } + + /** + * Get block HTML code. + */ + public function getHTML() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilUser = $this->user; + $ilAccess = $this->access; + $ilSetting = $this->settings; + + return parent::getHTML(); + } } - -?> diff --git a/Services/Block/classes/class.ilExternalFeedBlock.php b/Services/Block/classes/class.ilExternalFeedBlock.php index c928d636eb06a57ab083783b718ee255fdb650ce..78eef7d6548334b04504a89b3f9f328eea223675 100755 --- a/Services/Block/classes/class.ilExternalFeedBlock.php +++ b/Services/Block/classes/class.ilExternalFeedBlock.php @@ -11,133 +11,124 @@ include_once("./Services/Block/classes/class.ilCustomBlock.php"); */ class ilExternalFeedBlock extends ilCustomBlock { - /** - * @var ilDB - */ - protected $db; - - /** - * @var Logger - */ - protected $log; - - - protected $feed_url; - - /** - * Constructor. - * - * @param int $a_id - */ - public function __construct($a_id = 0) - { - global $DIC; - - $this->db = $DIC->database(); - $this->log = $DIC["ilLog"]; - if ($a_id > 0) - { - $this->setId($a_id); - $this->read(); - } - - } - - /** - * Set FeedUrl. - * - * @param string $a_feed_url URL of the external news feed. - */ - public function setFeedUrl($a_feed_url) - { - $this->feed_url = $a_feed_url; - } - - /** - * Get FeedUrl. - * - * @return string URL of the external news feed. - */ - public function getFeedUrl() - { - return $this->feed_url; - } - - /** - * Create new item. - * - */ - public function create() - { - $ilDB = $this->db; - $ilLog = $this->log; - - parent::create(); - - $query = "INSERT INTO il_external_feed_block (". - " id". - ", feed_url". - " ) VALUES (". - $ilDB->quote($this->getId(), "integer") - .",".$ilDB->quote($this->getFeedUrl(), "text").")"; - $ilDB->manipulate($query); - - } - - /** - * Read item from database. - * - */ - public function read() - { - $ilDB = $this->db; - - parent::read(); - - $query = "SELECT * FROM il_external_feed_block WHERE id = ". - $ilDB->quote($this->getId(), "integer"); - $set = $ilDB->query($query); - $rec = $ilDB->fetchAssoc($set); - - $this->setFeedUrl($rec["feed_url"]); - - } - - /** - * Update item in database. - * - */ - public function update() - { - $ilDB = $this->db; - - parent::update(); - - $query = "UPDATE il_external_feed_block SET ". - " feed_url = ".$ilDB->quote($this->getFeedUrl(), "text"). - " WHERE id = ".$ilDB->quote($this->getId(), "integer"); - - $ilDB->manipulate($query); - - } - - /** - * Delete item from database. - * - */ - public function delete() - { - $ilDB = $this->db; - - parent::delete(); - - $query = "DELETE FROM il_external_feed_block". - " WHERE id = ".$ilDB->quote($this->getId(), "integer"); - - $ilDB->manipulate($query); - - } - - + /** + * @var ilDB + */ + protected $db; + + /** + * @var Logger + */ + protected $log; + + + protected $feed_url; + + /** + * Constructor. + * + * @param int $a_id + */ + public function __construct($a_id = 0) + { + global $DIC; + + $this->db = $DIC->database(); + $this->log = $DIC["ilLog"]; + if ($a_id > 0) { + $this->setId($a_id); + $this->read(); + } + } + + /** + * Set FeedUrl. + * + * @param string $a_feed_url URL of the external news feed. + */ + public function setFeedUrl($a_feed_url) + { + $this->feed_url = $a_feed_url; + } + + /** + * Get FeedUrl. + * + * @return string URL of the external news feed. + */ + public function getFeedUrl() + { + return $this->feed_url; + } + + /** + * Create new item. + * + */ + public function create() + { + $ilDB = $this->db; + $ilLog = $this->log; + + parent::create(); + + $query = "INSERT INTO il_external_feed_block (" . + " id" . + ", feed_url" . + " ) VALUES (" . + $ilDB->quote($this->getId(), "integer") + . "," . $ilDB->quote($this->getFeedUrl(), "text") . ")"; + $ilDB->manipulate($query); + } + + /** + * Read item from database. + * + */ + public function read() + { + $ilDB = $this->db; + + parent::read(); + + $query = "SELECT * FROM il_external_feed_block WHERE id = " . + $ilDB->quote($this->getId(), "integer"); + $set = $ilDB->query($query); + $rec = $ilDB->fetchAssoc($set); + + $this->setFeedUrl($rec["feed_url"]); + } + + /** + * Update item in database. + * + */ + public function update() + { + $ilDB = $this->db; + + parent::update(); + + $query = "UPDATE il_external_feed_block SET " . + " feed_url = " . $ilDB->quote($this->getFeedUrl(), "text") . + " WHERE id = " . $ilDB->quote($this->getId(), "integer"); + + $ilDB->manipulate($query); + } + + /** + * Delete item from database. + * + */ + public function delete() + { + $ilDB = $this->db; + + parent::delete(); + + $query = "DELETE FROM il_external_feed_block" . + " WHERE id = " . $ilDB->quote($this->getId(), "integer"); + + $ilDB->manipulate($query); + } } -?> diff --git a/Services/Block/classes/class.ilExternalFeedBlockGUI.php b/Services/Block/classes/class.ilExternalFeedBlockGUI.php index ff7b0073836ea7c38143f84236c929b22a72eae0..c55f11f8114887b78dcc17e1f042434bc3f23b57 100755 --- a/Services/Block/classes/class.ilExternalFeedBlockGUI.php +++ b/Services/Block/classes/class.ilExternalFeedBlockGUI.php @@ -19,564 +19,556 @@ include_once("./Services/Feeds/classes/class.ilExternalFeed.php"); */ class ilExternalFeedBlockGUI extends ilExternalFeedBlockGUIGen { - /** - * @var ilSetting - */ - protected $settings; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilObjectDefinition - */ - protected $obj_definition; - - static $block_type = "feed"; - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - $this->access = $DIC->access(); - $this->settings = $DIC->settings(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->obj_definition = $DIC["objDefinition"]; - $lng = $DIC->language(); - - parent::__construct(); - - $lng->loadLanguageModule("feed"); - $this->setLimit(5); - $this->setRowTemplate("tpl.block_external_feed_row.html", "Services/Feeds"); - } - - /** - * @inheritdoc - */ - public function getBlockType(): string - { - return self::$block_type; - } - - /** - * @inheritdoc - */ - protected function isRepositoryObject(): bool - { - return true; - } - - /** - * Get Screen Mode for current command. - */ - static function getScreenMode() - { - global $DIC; - - $ilCtrl = $DIC->ctrl(); - - switch($ilCtrl->getCmd()) - { - case "create": - case "edit": - case "saveFeedBlock": - case "updateFeedBlock": - case "editFeedBlock": - case "showFeedItem": - case "confirmDeleteFeedBlock": - return IL_SCREEN_CENTER; - break; - - default: - return IL_SCREEN_SIDE; - break; - } - } - - /** - * Do most of the initialisation. - */ - function setBlock($a_block) - { - $ilCtrl = $this->ctrl; - - // init block - $this->feed_block = $a_block; - $this->setTitle($this->feed_block->getTitle()); - $this->setBlockId($this->feed_block->getId()); - - // get feed object - include_once("./Services/Feeds/classes/class.ilExternalFeed.php"); - $this->feed = new ilExternalFeed(); - $this->feed->setUrl($this->feed_block->getFeedUrl()); - - // init details - $this->setAvailableDetailLevels(2); - - $ilCtrl->setParameter($this, "block_id", $this->feed_block->getId()); - } - - /** - * execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - - $next_class = $ilCtrl->getNextClass(); - $cmd = $ilCtrl->getCmd("getHTML"); - switch ($next_class) - { - default: - return $this->$cmd(); - } - } - - /** - * Fill data section - */ - function fillDataSection() - { - if ($this->getDynamic()) - { - $this->setDataSection($this->getDynamicReload()); - } - else if ($this->getCurrentDetailLevel() > 1 && count($this->getData()) > 0) - { - parent::fillDataSection(); - } - else - { - $this->setDataSection($this->getOverview()); - } - } - - /** - * Get block HTML code. - */ - function getHTML() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilUser = $this->user; - $ilAccess = $this->access; - $ilSetting = $this->settings; - - if ($this->getCurrentDetailLevel() == 0) - { - return ""; - } - - $feed_set = new ilSetting("feed"); - - if ($feed_set->get("disable_rep_feeds")) - { - return ""; - } - - // if no dynamic reload - if (!$this->getDynamic()) - { - $this->feed->fetch(); - $this->setData($this->feed->getItems()); - } - - //$this->setTitle($this->feed->getChannelTitle()); - $this->setData($this->feed->getItems()); - - if ($ilAccess->checkAccess("write", "", $this->getRefId())) - { - $ilCtrl->setParameterByClass("ilobjexternalfeedgui", - "ref_id", $this->getRefId()); - $ilCtrl->setParameter($this, "external_feed_block_id", $this->getBlockId()); - $this->addBlockCommand( - $ilCtrl->getLinkTargetByClass(array("ilrepositorygui", "ilobjexternalfeedgui", - "ilexternalfeedblockgui"), - "editFeedBlock"), - $lng->txt("settings")); - $ilCtrl->clearParametersByClass("ilobjexternalfeedgui"); - } - - // JS enabler - $add = ""; - if ($_SESSION["il_feed_js"] == "n" || - ($ilUser->getPref("il_feed_js") == "n" && $_SESSION["il_feed_js"] != "y")) - { - $add = $this->getJSEnabler(); - } - - return parent::getHTML().$add; - } - - function getDynamic() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - if ($ilCtrl->getCmdClass() != "ilcolumngui" && $ilCtrl->getCmd() != "enableJS") - { - if ($_SESSION["il_feed_js"] != "n" && - ($ilUser->getPref("il_feed_js") != "n" || $_SESSION["il_feed_js"] == "y")) - { - // do not get feed dynamically, if cache hit is given. - if (!$this->feed->checkCacheHit()) - { - return true; - } - } - } - - return false; - } - - function getDynamicReload() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $ilCtrl->setParameterByClass("ilcolumngui", "block_id", - "block_feed_".$this->getBlockId()); - - $rel_tpl = new ilTemplate("tpl.dynamic_reload.html", true, true, "Services/Feeds"); - $rel_tpl->setVariable("TXT_LOADING", $lng->txt("feed_loading_feed")); - $rel_tpl->setVariable("BLOCK_ID", "block_feed_".$this->getBlockId()); - $rel_tpl->setVariable("TARGET", - $ilCtrl->getLinkTargetByClass("ilcolumngui", "updateBlock", "", true)); - - // no JS - $rel_tpl->setVariable("TXT_FEED_CLICK_HERE", $lng->txt("feed_no_js_click_here")); - $rel_tpl->setVariable("TARGET_NO_JS", - $ilCtrl->getLinkTargetByClass("ilexternalfeedblockgui", "disableJS")); - - return $rel_tpl->get(); - } - - function getJSEnabler() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $ilCtrl->setParameterByClass("ilcolumngui", "block_id", - "block_feed_".$this->getBlockId()); - - $rel_tpl = new ilTemplate("tpl.js_enabler.html", true, true, "Services/Feeds"); - $rel_tpl->setVariable("BLOCK_ID", "block_feed_".$this->getBlockId()); - $rel_tpl->setVariable("TARGET", - $ilCtrl->getLinkTargetByClass("ilexternalfeedblockgui", "enableJS", true, "", false)); - - return $rel_tpl->get(); - } - - - function disableJS() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - $_SESSION["il_feed_js"] = "n"; - $ilUser->writePref("il_feed_js", "n"); - $ilCtrl->returnToParent($this); - } - - function enableJS() - { - $ilUser = $this->user; - - $_SESSION["il_feed_js"] = "y"; - $ilUser->writePref("il_feed_js", "y"); - echo $this->getHTML(); - exit; - } - - /** - * Fill feed item row - */ - function fillRow($item) - { - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - - if ($this->isRepositoryObject() && !$ilAccess->checkAccess("read", "", $this->getRefId())) - { - $this->tpl->setVariable("TXT_TITLE", $item->getTitle()); - } - else - { - $ilCtrl->setParameter($this, "feed_item_id", $item->getId()); - $this->tpl->setCurrentBlock("feed_link"); - $this->tpl->setVariable("VAL_TITLE", $item->getTitle()); - $this->tpl->setVariable("HREF_SHOW", - $ilCtrl->getLinkTarget($this, "showFeedItem")); - $ilCtrl->setParameter($this, "feed_item_id", ""); - $this->tpl->parseCurrentBlock(); - } - } - - /** - * Get overview. - */ - function getOverview() - { - $ilUser = $this->user; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->setEnableNumInfo(false); - return '
'.((int) count($this->getData()))." ".$lng->txt("feed_feed_items")."
"; - } - - /** - * Show Feed Item - */ - function showFeedItem() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("./Services/News/classes/class.ilNewsItem.php"); - - $this->feed->fetch(); - foreach($this->feed->getItems() as $item) - { - if ($item->getId() == $_GET["feed_item_id"]) - { - $c_item = $item; - break; - } - } - - $tpl = new ilTemplate("tpl.show_feed_item.html", true, true, "Services/Feeds"); - - if (is_object($c_item)) - { - if (trim($c_item->getSummary()) != "") // summary - { - $tpl->setCurrentBlock("content"); - $tpl->setVariable("VAL_CONTENT", $c_item->getSummary()); - $tpl->parseCurrentBlock(); - } - if (trim($c_item->getDate()) != "" || trim($c_item->getAuthor()) != "") // date - { - $tpl->setCurrentBlock("date_author"); - if (trim($c_item->getAuthor()) != "") - { - $tpl->setVariable("VAL_AUTHOR", $c_item->getAuthor()." - "); - } - $tpl->setVariable("VAL_DATE", $c_item->getDate()); - $tpl->parseCurrentBlock(); - } - - if (trim($c_item->getLink()) != "") // link - { - $tpl->setCurrentBlock("plink"); - $tpl->setVariable("HREF_LINK", $c_item->getLink()); - $tpl->setVariable("TXT_LINK", $lng->txt("feed_open_source_page")); - $tpl->parseCurrentBlock(); - } - $tpl->setVariable("VAL_TITLE", $c_item->getTitle()); // title - } - - include_once("./Services/PersonalDesktop/classes/class.ilPDContentBlockGUI.php"); - $content_block = new ilPDContentBlockGUI(); - $content_block->setContent($tpl->get()); - $content_block->setTitle($this->getTitle()); - $content_block->setImage(ilUtil::getImagePath("icon_feed.svg")); - $content_block->addHeaderCommand($ilCtrl->getParentReturn($this), - $lng->txt("close"), true); - - return $content_block->getHTML(); - } - - /** - * Create Form for Block. - */ - function create() - { - $html1 = $this->createFeedBlock(); - - $html2 = ""; - if (DEVMODE == 1) - { - $this->initImportForm("feed"); - $html2 = "
".$this->form->getHTML(); - } - - return $html1.$html2; - } - - /** - * Init object import form - * - * @param string new type - */ - public function initImportForm($a_new_type = "") - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $lng->loadLanguageModule("feed"); - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - $this->form->setTarget("_top"); - - // Import file - include_once("./Services/Form/classes/class.ilFileInputGUI.php"); - $fi = new ilFileInputGUI($lng->txt("import_file"), "importfile"); - $fi->setSuffixes(array("zip")); - $fi->setRequired(true); - $this->form->addItem($fi); - - $this->form->addCommandButton("importFile", $lng->txt("import")); - $this->form->addCommandButton("cancelSaveFeedBlock", $lng->txt("cancel")); - $this->form->setTitle($lng->txt($a_new_type."_import")); - - $ilCtrl->setParameter($this, "new_type", $a_new_type); - $this->form->setFormAction($ilCtrl->getFormAction($this)); - } - - /** - * Import - * - * @access public - */ - function importFile() - { - $rbacsystem = $this->rbacsystem; - $tpl = $this->main_tpl; - $lng = $this->lng; - - $new_type = $_POST["new_type"] ? $_POST["new_type"] : $_GET["new_type"]; - - // create permission is already checked in createObject. This check here is done to prevent hacking attempts - if (!$rbacsystem->checkAccess("create", $_GET["ref_id"], $new_type)) - { - $this->ilias->raiseError($this->lng->txt("no_create_permission"), $this->ilias->error_obj->MESSAGE); - } - $this->ctrl->setParameter($this, "new_type", $new_type); - $this->initImportForm($new_type); - if ($this->form->checkInput()) - { - // todo: make some check on manifest file - include_once("./Services/Export/classes/class.ilImport.php"); - $imp = new ilImport((int) $_GET['ref_id']); - $new_id = $imp->importObject($newObj, $_FILES["importfile"]["tmp_name"], - $_FILES["importfile"]["name"], $new_type); - - // put new object id into tree - if ($new_id > 0) - { - $newObj = ilObjectFactory::getInstanceByObjId($new_id); - $newObj->createReference(); - $newObj->putInTree($_GET["ref_id"]); - $newObj->setPermissions($_GET["ref_id"]); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $this->exitSaveFeedBlock(); - } - return; - } - - $this->form->setValuesByPost(); - $tpl->setContent($this->form->getHtml()); - } - - - /** - * FORM FeedBlock: Init form. (We need to overwrite, because Generator - * does not know FeedUrl Inputs yet. - * - * @param int $a_mode Form Edit Mode (IL_FORM_EDIT | IL_FORM_CREATE) - */ - public function initFormFeedBlock($a_mode) - { - $lng = $this->lng; - - $lng->loadLanguageModule("block"); - - require_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - - $this->form_gui = new ilPropertyFormGUI(); - - // Property Title - $text_input = new ilTextInputGUI($lng->txt("block_feed_block_title"), "block_title"); - $text_input->setInfo(""); - $text_input->setRequired(true); - $text_input->setMaxLength(200); - $this->form_gui->addItem($text_input); - - // Property FeedUrl - $text_input = new ilFeedUrlInputGUI($lng->txt("block_feed_block_feed_url"), "block_feed_url"); - $text_input->setInfo($lng->txt("block_feed_block_feed_url_info")); - $text_input->setRequired(true); - $text_input->setMaxLength(250); - $this->form_gui->addItem($text_input); - - - // save and cancel commands - if (in_array($a_mode, array(IL_FORM_CREATE,IL_FORM_RE_CREATE))) - { - $this->form_gui->addCommandButton("saveFeedBlock", $lng->txt("save")); - $this->form_gui->addCommandButton("cancelSaveFeedBlock", $lng->txt("cancel")); - } - else - { - $this->form_gui->addCommandButton("updateFeedBlock", $lng->txt("save")); - $this->form_gui->addCommandButton("cancelUpdateFeedBlock", $lng->txt("cancel")); - } - - $this->form_gui->setTitle($lng->txt("block_feed_block_head")); - $this->form_gui->setFormAction($this->ctrl->getFormAction($this)); - - $this->prepareFormFeedBlock($this->form_gui); - - } - - /** - * FORM FeedBlock: Prepare Saving of FeedBlock. - * - * @param object $a_feed_block FeedBlock object. - */ - public function prepareSaveFeedBlock(&$a_feed_block) - { - $this->getGuiObject()->save($a_feed_block); - $a_feed_block->setType($this->getBlockType()); - } - - /** - * FORM FeedBlock: Exit save. (Can be overwritten in derived classes) - * - */ - public function exitSaveFeedBlock() - { - $this->getGuiObject()->exitSave(); - } - - /** - * FORM FeedBlock: Exit save. (Can be overwritten in derived classes) - * - */ - public function cancelUpdateFeedBlock() - { - $this->getGuiObject()->cancelUpdate(); - } - - /** - * FORM FeedBlock: Exit save. (Can be overwritten in derived classes) - * - */ - public function exitUpdateFeedBlock() - { - $this->getGuiObject()->update($this->external_feed_block); - } + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilObjectDefinition + */ + protected $obj_definition; + + public static $block_type = "feed"; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + $this->access = $DIC->access(); + $this->settings = $DIC->settings(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->obj_definition = $DIC["objDefinition"]; + $lng = $DIC->language(); + + parent::__construct(); + + $lng->loadLanguageModule("feed"); + $this->setLimit(5); + $this->setRowTemplate("tpl.block_external_feed_row.html", "Services/Feeds"); + } + + /** + * @inheritdoc + */ + public function getBlockType() : string + { + return self::$block_type; + } + + /** + * @inheritdoc + */ + protected function isRepositoryObject() : bool + { + return true; + } + + /** + * Get Screen Mode for current command. + */ + public static function getScreenMode() + { + global $DIC; + + $ilCtrl = $DIC->ctrl(); + + switch ($ilCtrl->getCmd()) { + case "create": + case "edit": + case "saveFeedBlock": + case "updateFeedBlock": + case "editFeedBlock": + case "showFeedItem": + case "confirmDeleteFeedBlock": + return IL_SCREEN_CENTER; + break; + + default: + return IL_SCREEN_SIDE; + break; + } + } + + /** + * Do most of the initialisation. + */ + public function setBlock($a_block) + { + $ilCtrl = $this->ctrl; + + // init block + $this->feed_block = $a_block; + $this->setTitle($this->feed_block->getTitle()); + $this->setBlockId($this->feed_block->getId()); + + // get feed object + include_once("./Services/Feeds/classes/class.ilExternalFeed.php"); + $this->feed = new ilExternalFeed(); + $this->feed->setUrl($this->feed_block->getFeedUrl()); + + // init details + $this->setAvailableDetailLevels(2); + + $ilCtrl->setParameter($this, "block_id", $this->feed_block->getId()); + } + + /** + * execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $next_class = $ilCtrl->getNextClass(); + $cmd = $ilCtrl->getCmd("getHTML"); + switch ($next_class) { + default: + return $this->$cmd(); + } + } + + /** + * Fill data section + */ + public function fillDataSection() + { + if ($this->getDynamic()) { + $this->setDataSection($this->getDynamicReload()); + } elseif ($this->getCurrentDetailLevel() > 1 && count($this->getData()) > 0) { + parent::fillDataSection(); + } else { + $this->setDataSection($this->getOverview()); + } + } + + /** + * Get block HTML code. + */ + public function getHTML() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilUser = $this->user; + $ilAccess = $this->access; + $ilSetting = $this->settings; + + if ($this->getCurrentDetailLevel() == 0) { + return ""; + } + + $feed_set = new ilSetting("feed"); + + if ($feed_set->get("disable_rep_feeds")) { + return ""; + } + + // if no dynamic reload + if (!$this->getDynamic()) { + $this->feed->fetch(); + $this->setData($this->feed->getItems()); + } + + //$this->setTitle($this->feed->getChannelTitle()); + $this->setData($this->feed->getItems()); + + if ($ilAccess->checkAccess("write", "", $this->getRefId())) { + $ilCtrl->setParameterByClass( + "ilobjexternalfeedgui", + "ref_id", + $this->getRefId() + ); + $ilCtrl->setParameter($this, "external_feed_block_id", $this->getBlockId()); + $this->addBlockCommand( + $ilCtrl->getLinkTargetByClass( + array("ilrepositorygui", "ilobjexternalfeedgui", + "ilexternalfeedblockgui"), + "editFeedBlock" + ), + $lng->txt("settings") + ); + $ilCtrl->clearParametersByClass("ilobjexternalfeedgui"); + } + + // JS enabler + $add = ""; + if ($_SESSION["il_feed_js"] == "n" || + ($ilUser->getPref("il_feed_js") == "n" && $_SESSION["il_feed_js"] != "y")) { + $add = $this->getJSEnabler(); + } + + return parent::getHTML() . $add; + } + + public function getDynamic() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + if ($ilCtrl->getCmdClass() != "ilcolumngui" && $ilCtrl->getCmd() != "enableJS") { + if ($_SESSION["il_feed_js"] != "n" && + ($ilUser->getPref("il_feed_js") != "n" || $_SESSION["il_feed_js"] == "y")) { + // do not get feed dynamically, if cache hit is given. + if (!$this->feed->checkCacheHit()) { + return true; + } + } + } + + return false; + } + + public function getDynamicReload() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $ilCtrl->setParameterByClass( + "ilcolumngui", + "block_id", + "block_feed_" . $this->getBlockId() + ); + + $rel_tpl = new ilTemplate("tpl.dynamic_reload.html", true, true, "Services/Feeds"); + $rel_tpl->setVariable("TXT_LOADING", $lng->txt("feed_loading_feed")); + $rel_tpl->setVariable("BLOCK_ID", "block_feed_" . $this->getBlockId()); + $rel_tpl->setVariable( + "TARGET", + $ilCtrl->getLinkTargetByClass("ilcolumngui", "updateBlock", "", true) + ); + + // no JS + $rel_tpl->setVariable("TXT_FEED_CLICK_HERE", $lng->txt("feed_no_js_click_here")); + $rel_tpl->setVariable( + "TARGET_NO_JS", + $ilCtrl->getLinkTargetByClass("ilexternalfeedblockgui", "disableJS") + ); + + return $rel_tpl->get(); + } + + public function getJSEnabler() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $ilCtrl->setParameterByClass( + "ilcolumngui", + "block_id", + "block_feed_" . $this->getBlockId() + ); + + $rel_tpl = new ilTemplate("tpl.js_enabler.html", true, true, "Services/Feeds"); + $rel_tpl->setVariable("BLOCK_ID", "block_feed_" . $this->getBlockId()); + $rel_tpl->setVariable( + "TARGET", + $ilCtrl->getLinkTargetByClass("ilexternalfeedblockgui", "enableJS", true, "", false) + ); + + return $rel_tpl->get(); + } + + + public function disableJS() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + $_SESSION["il_feed_js"] = "n"; + $ilUser->writePref("il_feed_js", "n"); + $ilCtrl->returnToParent($this); + } + + public function enableJS() + { + $ilUser = $this->user; + + $_SESSION["il_feed_js"] = "y"; + $ilUser->writePref("il_feed_js", "y"); + echo $this->getHTML(); + exit; + } + + /** + * Fill feed item row + */ + public function fillRow($item) + { + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + + if ($this->isRepositoryObject() && !$ilAccess->checkAccess("read", "", $this->getRefId())) { + $this->tpl->setVariable("TXT_TITLE", $item->getTitle()); + } else { + $ilCtrl->setParameter($this, "feed_item_id", $item->getId()); + $this->tpl->setCurrentBlock("feed_link"); + $this->tpl->setVariable("VAL_TITLE", $item->getTitle()); + $this->tpl->setVariable( + "HREF_SHOW", + $ilCtrl->getLinkTarget($this, "showFeedItem") + ); + $ilCtrl->setParameter($this, "feed_item_id", ""); + $this->tpl->parseCurrentBlock(); + } + } + + /** + * Get overview. + */ + public function getOverview() + { + $ilUser = $this->user; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $this->setEnableNumInfo(false); + return '
' . ((int) count($this->getData())) . " " . $lng->txt("feed_feed_items") . "
"; + } + + /** + * Show Feed Item + */ + public function showFeedItem() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("./Services/News/classes/class.ilNewsItem.php"); + + $this->feed->fetch(); + foreach ($this->feed->getItems() as $item) { + if ($item->getId() == $_GET["feed_item_id"]) { + $c_item = $item; + break; + } + } + + $tpl = new ilTemplate("tpl.show_feed_item.html", true, true, "Services/Feeds"); + + if (is_object($c_item)) { + if (trim($c_item->getSummary()) != "") { // summary + $tpl->setCurrentBlock("content"); + $tpl->setVariable("VAL_CONTENT", $c_item->getSummary()); + $tpl->parseCurrentBlock(); + } + if (trim($c_item->getDate()) != "" || trim($c_item->getAuthor()) != "") { // date + $tpl->setCurrentBlock("date_author"); + if (trim($c_item->getAuthor()) != "") { + $tpl->setVariable("VAL_AUTHOR", $c_item->getAuthor() . " - "); + } + $tpl->setVariable("VAL_DATE", $c_item->getDate()); + $tpl->parseCurrentBlock(); + } + + if (trim($c_item->getLink()) != "") { // link + $tpl->setCurrentBlock("plink"); + $tpl->setVariable("HREF_LINK", $c_item->getLink()); + $tpl->setVariable("TXT_LINK", $lng->txt("feed_open_source_page")); + $tpl->parseCurrentBlock(); + } + $tpl->setVariable("VAL_TITLE", $c_item->getTitle()); // title + } + + include_once("./Services/PersonalDesktop/classes/class.ilPDContentBlockGUI.php"); + $content_block = new ilPDContentBlockGUI(); + $content_block->setContent($tpl->get()); + $content_block->setTitle($this->getTitle()); + $content_block->setImage(ilUtil::getImagePath("icon_feed.svg")); + $content_block->addHeaderCommand( + $ilCtrl->getParentReturn($this), + $lng->txt("close"), + true + ); + + return $content_block->getHTML(); + } + + /** + * Create Form for Block. + */ + public function create() + { + $html1 = $this->createFeedBlock(); + + $html2 = ""; + if (DEVMODE == 1) { + $this->initImportForm("feed"); + $html2 = "
" . $this->form->getHTML(); + } + + return $html1 . $html2; + } + + /** + * Init object import form + * + * @param string new type + */ + public function initImportForm($a_new_type = "") + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $lng->loadLanguageModule("feed"); + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + $this->form->setTarget("_top"); + + // Import file + include_once("./Services/Form/classes/class.ilFileInputGUI.php"); + $fi = new ilFileInputGUI($lng->txt("import_file"), "importfile"); + $fi->setSuffixes(array("zip")); + $fi->setRequired(true); + $this->form->addItem($fi); + + $this->form->addCommandButton("importFile", $lng->txt("import")); + $this->form->addCommandButton("cancelSaveFeedBlock", $lng->txt("cancel")); + $this->form->setTitle($lng->txt($a_new_type . "_import")); + + $ilCtrl->setParameter($this, "new_type", $a_new_type); + $this->form->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * Import + * + * @access public + */ + public function importFile() + { + $rbacsystem = $this->rbacsystem; + $tpl = $this->main_tpl; + $lng = $this->lng; + + $new_type = $_POST["new_type"] ? $_POST["new_type"] : $_GET["new_type"]; + + // create permission is already checked in createObject. This check here is done to prevent hacking attempts + if (!$rbacsystem->checkAccess("create", $_GET["ref_id"], $new_type)) { + $this->ilias->raiseError($this->lng->txt("no_create_permission"), $this->ilias->error_obj->MESSAGE); + } + $this->ctrl->setParameter($this, "new_type", $new_type); + $this->initImportForm($new_type); + if ($this->form->checkInput()) { + // todo: make some check on manifest file + include_once("./Services/Export/classes/class.ilImport.php"); + $imp = new ilImport((int) $_GET['ref_id']); + $new_id = $imp->importObject( + $newObj, + $_FILES["importfile"]["tmp_name"], + $_FILES["importfile"]["name"], + $new_type + ); + + // put new object id into tree + if ($new_id > 0) { + $newObj = ilObjectFactory::getInstanceByObjId($new_id); + $newObj->createReference(); + $newObj->putInTree($_GET["ref_id"]); + $newObj->setPermissions($_GET["ref_id"]); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $this->exitSaveFeedBlock(); + } + return; + } + + $this->form->setValuesByPost(); + $tpl->setContent($this->form->getHtml()); + } + + + /** + * FORM FeedBlock: Init form. (We need to overwrite, because Generator + * does not know FeedUrl Inputs yet. + * + * @param int $a_mode Form Edit Mode (IL_FORM_EDIT | IL_FORM_CREATE) + */ + public function initFormFeedBlock($a_mode) + { + $lng = $this->lng; + + $lng->loadLanguageModule("block"); + + require_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + + $this->form_gui = new ilPropertyFormGUI(); + + // Property Title + $text_input = new ilTextInputGUI($lng->txt("block_feed_block_title"), "block_title"); + $text_input->setInfo(""); + $text_input->setRequired(true); + $text_input->setMaxLength(200); + $this->form_gui->addItem($text_input); + + // Property FeedUrl + $text_input = new ilFeedUrlInputGUI($lng->txt("block_feed_block_feed_url"), "block_feed_url"); + $text_input->setInfo($lng->txt("block_feed_block_feed_url_info")); + $text_input->setRequired(true); + $text_input->setMaxLength(250); + $this->form_gui->addItem($text_input); + + + // save and cancel commands + if (in_array($a_mode, array(IL_FORM_CREATE,IL_FORM_RE_CREATE))) { + $this->form_gui->addCommandButton("saveFeedBlock", $lng->txt("save")); + $this->form_gui->addCommandButton("cancelSaveFeedBlock", $lng->txt("cancel")); + } else { + $this->form_gui->addCommandButton("updateFeedBlock", $lng->txt("save")); + $this->form_gui->addCommandButton("cancelUpdateFeedBlock", $lng->txt("cancel")); + } + + $this->form_gui->setTitle($lng->txt("block_feed_block_head")); + $this->form_gui->setFormAction($this->ctrl->getFormAction($this)); + + $this->prepareFormFeedBlock($this->form_gui); + } + + /** + * FORM FeedBlock: Prepare Saving of FeedBlock. + * + * @param object $a_feed_block FeedBlock object. + */ + public function prepareSaveFeedBlock(&$a_feed_block) + { + $this->getGuiObject()->save($a_feed_block); + $a_feed_block->setType($this->getBlockType()); + } + + /** + * FORM FeedBlock: Exit save. (Can be overwritten in derived classes) + * + */ + public function exitSaveFeedBlock() + { + $this->getGuiObject()->exitSave(); + } + + /** + * FORM FeedBlock: Exit save. (Can be overwritten in derived classes) + * + */ + public function cancelUpdateFeedBlock() + { + $this->getGuiObject()->cancelUpdate(); + } + + /** + * FORM FeedBlock: Exit save. (Can be overwritten in derived classes) + * + */ + public function exitUpdateFeedBlock() + { + $this->getGuiObject()->update($this->external_feed_block); + } } - -?> diff --git a/Services/Block/classes/class.ilExternalFeedBlockGUIGen.php b/Services/Block/classes/class.ilExternalFeedBlockGUIGen.php index 3de4a1f0622f5705aabecd19c41ed4ad1b998067..d0f97c6520b26f09ac4f0fb83f38790e09b7122a 100755 --- a/Services/Block/classes/class.ilExternalFeedBlockGUIGen.php +++ b/Services/Block/classes/class.ilExternalFeedBlockGUIGen.php @@ -1,24 +1,24 @@ lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - - parent::__construct(); - - $this->ctrl = $ilCtrl; - - - include_once("Services/Block/classes/class.ilExternalFeedBlock.php"); - if (isset($_GET["external_feed_block_id"]) && $_GET["external_feed_block_id"] > 0) - { - $this->external_feed_block = new ilExternalFeedBlock($_GET["external_feed_block_id"]); - } - - $this->ctrl->saveParameter($this, array("external_feed_block_id")); - - - } - - /** - * Execute command. - * - */ - public function executeCommand() - { - $ilCtrl = $this->ctrl; - - // get next class and command - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - switch ($next_class) - { - default: - $html = $this->$cmd(); - break; - } - - return $html; - - } - - /** - * Set GuiObject. - * - * @param object $a_gui_object GUI object - */ - public function setGuiObject(&$a_gui_object) - { - $this->gui_object = $a_gui_object; - } - - /** - * Get GuiObject. - * - * @return object GUI object - */ - public function getGuiObject() - { - return $this->gui_object; - } - - /** - * Set FormEditMode. - * - * @param int $a_form_edit_mode Form Edit Mode (IL_FORM_EDIT | IL_FORM_CREATE | IL_FORM_RE_EDIT | IL_FORM_RE_CREATE) - */ - public function setFormEditMode($a_form_edit_mode) - { - $this->form_edit_mode = $a_form_edit_mode; - } - - /** - * Get FormEditMode. - * - * @return int Form Edit Mode (IL_FORM_EDIT | IL_FORM_CREATE | IL_FORM_RE_EDIT | IL_FORM_RE_CREATE) - */ - public function getFormEditMode() - { - return $this->form_edit_mode; - } - - /** - * FORM FeedBlock: Create ExternalFeedBlock. - * - */ - public function createFeedBlock() - { - $this->initFormFeedBlock(IL_FORM_CREATE); - return $this->form_gui->getHtml(); - - } - - /** - * FORM FeedBlock: Edit form. - * - */ - public function editFeedBlock() - { - $this->initFormFeedBlock(IL_FORM_EDIT); - $this->getValuesFeedBlock(); - return $this->form_gui->getHtml(); - - } - - /** - * FORM FeedBlock: Save ExternalFeedBlock. - * - */ - public function saveFeedBlock() - { - $this->initFormFeedBlock(IL_FORM_CREATE); - - if ($this->form_gui->checkInput()) - { - $this->external_feed_block = new ilExternalFeedBlock(); - $this->external_feed_block->setTitle($this->form_gui->getInput("block_title")); - $this->external_feed_block->setFeedUrl($this->form_gui->getInput("block_feed_url")); - $this->prepareSaveFeedBlock($this->external_feed_block); - $this->external_feed_block->create(); - $this->exitSaveFeedBlock(); - } - else - { - $this->form_gui->setValuesByPost(); - return $this->form_gui->getHtml(); - } - - } - - /** - * FORM FeedBlock: Update ExternalFeedBlock. - * - */ - public function updateFeedBlock() - { - $this->initFormFeedBlock(IL_FORM_EDIT); - if ($this->form_gui->checkInput()) - { - - $this->external_feed_block->setTitle($this->form_gui->getInput("block_title")); - $this->external_feed_block->setFeedUrl($this->form_gui->getInput("block_feed_url")); - $this->external_feed_block->update(); - $this->exitUpdateFeedBlock(); - } - else - { - $this->form_gui->setValuesByPost(); - return $this->form_gui->getHtml(); - } - - } - - /** - * FORM FeedBlock: Init form. - * - * @param int $a_mode Form Edit Mode (IL_FORM_EDIT | IL_FORM_CREATE) - */ - public function initFormFeedBlock($a_mode) - { - $lng = $this->lng; - - $lng->loadLanguageModule("block"); - - require_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - - $this->form_gui = new ilPropertyFormGUI(); - - - // Property Title - $text_input = new ilTextInputGUI($lng->txt("block_feed_block_title"), "block_title"); - $text_input->setInfo(""); - $text_input->setRequired(true); - $text_input->setMaxLength(200); - $this->form_gui->addItem($text_input); - - // Property FeedUrl - $text_input = new ilTextInputGUI($lng->txt("block_feed_block_feed_url"), "block_feed_url"); - $text_input->setInfo($lng->txt("block_feed_block_feed_url_info")); - $text_input->setRequired(true); - $text_input->setMaxLength(250); - $this->form_gui->addItem($text_input); - - - // save and cancel commands - if (in_array($a_mode, array(IL_FORM_CREATE,IL_FORM_RE_CREATE))) - { - $this->form_gui->addCommandButton("saveFeedBlock", $lng->txt("save")); - $this->form_gui->addCommandButton("cancelSaveFeedBlock", $lng->txt("cancel")); - } - else - { - $this->form_gui->addCommandButton("updateFeedBlock", $lng->txt("save")); - $this->form_gui->addCommandButton("cancelUpdateFeedBlock", $lng->txt("cancel")); - } - - $this->form_gui->setTitle($lng->txt("block_feed_block_head")); - $this->form_gui->setFormAction($this->ctrl->getFormAction($this)); - - $this->prepareFormFeedBlock($this->form_gui); - - } - - /** - * FORM FeedBlock: Get current values for ExternalFeedBlock form. - * - */ - public function getValuesFeedBlock() - { - $values = array(); - - $values["block_title"] = $this->external_feed_block->getTitle(); - $values["block_feed_url"] = $this->external_feed_block->getFeedUrl(); - - $this->form_gui->setValuesByArray($values); - - } - - /** - * FORM FeedBlock: Cancel save. (Can be overwritten in derived classes) - * - */ - public function cancelSaveFeedBlock() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->returnToParent($this); - } - - /** - * FORM FeedBlock: Cancel update. (Can be overwritten in derived classes) - * - */ - public function cancelUpdateFeedBlock() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->returnToParent($this); - } - - /** - * FORM FeedBlock: Exit save. (Can be overwritten in derived classes) - * - */ - public function exitSaveFeedBlock() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->returnToParent($this); - } - - /** - * FORM FeedBlock: Exit update. (Can be overwritten in derived classes) - * - */ - public function exitUpdateFeedBlock() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->returnToParent($this); - } - - /** - * FORM FeedBlock: Prepare Saving of ExternalFeedBlock. - * - * @param object $a_external_feed_block ExternalFeedBlock object. - */ - public function prepareSaveFeedBlock(&$a_external_feed_block) - { - - } - - /** - * FORM FeedBlock: Prepare form. (Can be overwritten in derived classes) - * - * @param object $a_form_gui ilPropertyFormGUI instance. - */ - public function prepareFormFeedBlock(&$a_form_gui) - { - - } - - + protected $gui_object; + protected $form_edit_mode; + + /** + * Constructor. + * + */ + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + + parent::__construct(); + + $this->ctrl = $ilCtrl; + + + include_once("Services/Block/classes/class.ilExternalFeedBlock.php"); + if (isset($_GET["external_feed_block_id"]) && $_GET["external_feed_block_id"] > 0) { + $this->external_feed_block = new ilExternalFeedBlock($_GET["external_feed_block_id"]); + } + + $this->ctrl->saveParameter($this, array("external_feed_block_id")); + } + + /** + * Execute command. + * + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + // get next class and command + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + switch ($next_class) { + default: + $html = $this->$cmd(); + break; + } + + return $html; + } + + /** + * Set GuiObject. + * + * @param object $a_gui_object GUI object + */ + public function setGuiObject(&$a_gui_object) + { + $this->gui_object = $a_gui_object; + } + + /** + * Get GuiObject. + * + * @return object GUI object + */ + public function getGuiObject() + { + return $this->gui_object; + } + + /** + * Set FormEditMode. + * + * @param int $a_form_edit_mode Form Edit Mode (IL_FORM_EDIT | IL_FORM_CREATE | IL_FORM_RE_EDIT | IL_FORM_RE_CREATE) + */ + public function setFormEditMode($a_form_edit_mode) + { + $this->form_edit_mode = $a_form_edit_mode; + } + + /** + * Get FormEditMode. + * + * @return int Form Edit Mode (IL_FORM_EDIT | IL_FORM_CREATE | IL_FORM_RE_EDIT | IL_FORM_RE_CREATE) + */ + public function getFormEditMode() + { + return $this->form_edit_mode; + } + + /** + * FORM FeedBlock: Create ExternalFeedBlock. + * + */ + public function createFeedBlock() + { + $this->initFormFeedBlock(IL_FORM_CREATE); + return $this->form_gui->getHtml(); + } + + /** + * FORM FeedBlock: Edit form. + * + */ + public function editFeedBlock() + { + $this->initFormFeedBlock(IL_FORM_EDIT); + $this->getValuesFeedBlock(); + return $this->form_gui->getHtml(); + } + + /** + * FORM FeedBlock: Save ExternalFeedBlock. + * + */ + public function saveFeedBlock() + { + $this->initFormFeedBlock(IL_FORM_CREATE); + + if ($this->form_gui->checkInput()) { + $this->external_feed_block = new ilExternalFeedBlock(); + $this->external_feed_block->setTitle($this->form_gui->getInput("block_title")); + $this->external_feed_block->setFeedUrl($this->form_gui->getInput("block_feed_url")); + $this->prepareSaveFeedBlock($this->external_feed_block); + $this->external_feed_block->create(); + $this->exitSaveFeedBlock(); + } else { + $this->form_gui->setValuesByPost(); + return $this->form_gui->getHtml(); + } + } + + /** + * FORM FeedBlock: Update ExternalFeedBlock. + * + */ + public function updateFeedBlock() + { + $this->initFormFeedBlock(IL_FORM_EDIT); + if ($this->form_gui->checkInput()) { + $this->external_feed_block->setTitle($this->form_gui->getInput("block_title")); + $this->external_feed_block->setFeedUrl($this->form_gui->getInput("block_feed_url")); + $this->external_feed_block->update(); + $this->exitUpdateFeedBlock(); + } else { + $this->form_gui->setValuesByPost(); + return $this->form_gui->getHtml(); + } + } + + /** + * FORM FeedBlock: Init form. + * + * @param int $a_mode Form Edit Mode (IL_FORM_EDIT | IL_FORM_CREATE) + */ + public function initFormFeedBlock($a_mode) + { + $lng = $this->lng; + + $lng->loadLanguageModule("block"); + + require_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + + $this->form_gui = new ilPropertyFormGUI(); + + + // Property Title + $text_input = new ilTextInputGUI($lng->txt("block_feed_block_title"), "block_title"); + $text_input->setInfo(""); + $text_input->setRequired(true); + $text_input->setMaxLength(200); + $this->form_gui->addItem($text_input); + + // Property FeedUrl + $text_input = new ilTextInputGUI($lng->txt("block_feed_block_feed_url"), "block_feed_url"); + $text_input->setInfo($lng->txt("block_feed_block_feed_url_info")); + $text_input->setRequired(true); + $text_input->setMaxLength(250); + $this->form_gui->addItem($text_input); + + + // save and cancel commands + if (in_array($a_mode, array(IL_FORM_CREATE,IL_FORM_RE_CREATE))) { + $this->form_gui->addCommandButton("saveFeedBlock", $lng->txt("save")); + $this->form_gui->addCommandButton("cancelSaveFeedBlock", $lng->txt("cancel")); + } else { + $this->form_gui->addCommandButton("updateFeedBlock", $lng->txt("save")); + $this->form_gui->addCommandButton("cancelUpdateFeedBlock", $lng->txt("cancel")); + } + + $this->form_gui->setTitle($lng->txt("block_feed_block_head")); + $this->form_gui->setFormAction($this->ctrl->getFormAction($this)); + + $this->prepareFormFeedBlock($this->form_gui); + } + + /** + * FORM FeedBlock: Get current values for ExternalFeedBlock form. + * + */ + public function getValuesFeedBlock() + { + $values = array(); + + $values["block_title"] = $this->external_feed_block->getTitle(); + $values["block_feed_url"] = $this->external_feed_block->getFeedUrl(); + + $this->form_gui->setValuesByArray($values); + } + + /** + * FORM FeedBlock: Cancel save. (Can be overwritten in derived classes) + * + */ + public function cancelSaveFeedBlock() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->returnToParent($this); + } + + /** + * FORM FeedBlock: Cancel update. (Can be overwritten in derived classes) + * + */ + public function cancelUpdateFeedBlock() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->returnToParent($this); + } + + /** + * FORM FeedBlock: Exit save. (Can be overwritten in derived classes) + * + */ + public function exitSaveFeedBlock() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->returnToParent($this); + } + + /** + * FORM FeedBlock: Exit update. (Can be overwritten in derived classes) + * + */ + public function exitUpdateFeedBlock() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->returnToParent($this); + } + + /** + * FORM FeedBlock: Prepare Saving of ExternalFeedBlock. + * + * @param object $a_external_feed_block ExternalFeedBlock object. + */ + public function prepareSaveFeedBlock(&$a_external_feed_block) + { + } + + /** + * FORM FeedBlock: Prepare form. (Can be overwritten in derived classes) + * + * @param object $a_form_gui ilPropertyFormGUI instance. + */ + public function prepareFormFeedBlock(&$a_form_gui) + { + } } -?> diff --git a/Services/Booking/classes/class.ilBookingEntry.php b/Services/Booking/classes/class.ilBookingEntry.php index 68b840eb50109c6155052160a4936bc6164b08c9..ee235d96befd60684319222cc60505438d9c42ac 100644 --- a/Services/Booking/classes/class.ilBookingEntry.php +++ b/Services/Booking/classes/class.ilBookingEntry.php @@ -12,880 +12,831 @@ */ class ilBookingEntry { - /** - * @var ilDB - */ - protected $db; - - /** - * @var ilObjUser - */ - protected $user; - - private $id = 0; - private $obj_id = 0; - - private $deadline = 0; - private $num_bookings = 1; - private $target_obj_ids = array(); - private $booking_group = 0; - - - /** - * Constructor - */ - public function __construct($a_booking_id = 0) - { - global $DIC; - - $this->db = $DIC->database(); - $this->user = $DIC->user(); - $this->setId($a_booking_id); - if($this->getId()) - { - $this->read(); - } - } - - /** - * Reset booking group (in case of deletion) - * @global type $ilDB - * @param type $a_group_id - * @return boolean - */ - public static function resetGroup($a_group_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = 'UPDATE booking_entry SET booking_group = '.$ilDB->quote(0,'integer').' '. - 'WHERE booking_group = '.$ilDB->quote($a_group_id,'integer'); - $ilDB->manipulate($query); - return true; - } - - /** - * Lookup bookings if user - * @param type $a_app_ids - * @param type $a_usr_id - */ - public static function lookupBookingsOfUser($a_app_ids, $a_usr_id, ilDateTime $start = null) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = 'SELECT entry_id FROM booking_user '. - 'WHERE '.$ilDB->in('entry_id',$a_app_ids,false,'integer').' '. - 'AND user_id = '.$ilDB->quote($a_usr_id,'integer'); - - $res = $ilDB->query($query); - - $booked_entries = array(); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - $booked_entries[] = $row->entry_id; - } - return $booked_entries; - } - - /** - * Set id - * @param int $a_id - * @return - */ - protected function setId($a_id) - { - $this->id = (int)$a_id; - } - - /** - * Get id - * @return - */ - public function getId() - { - return $this->id; - } - - public function setBookingGroup($a_id) - { - $this->booking_group = $a_id; - } - - public function getBookingGroup() - { - return $this->booking_group; - } - - /** - * Set obj id - * @param int $a_id - * @return - */ - public function setObjId($a_id) - { - $this->obj_id = (int)$a_id; - } - - /** - * get obj id - * @return - */ - public function getObjId() - { - return $this->obj_id; - } - - /** - * set deadline hours - * @param int $a_hours - * @return - */ - public function setDeadlineHours($a_hours) - { - $this->deadline = (int)$a_hours; - } - - /** - * get deadline hours - * @return - */ - public function getDeadlineHours() - { - return $this->deadline; - } - - /** - * set number of bookings - * @param int $a_num - * @return - */ - public function setNumberOfBookings($a_num) - { - $this->num_bookings = (int)$a_num; - } - - /** - * get number of bookings - * @return - */ - public function getNumberOfBookings() - { - return $this->num_bookings; - } - - /** - * set target object id - * @param int $a_obj_id - * @return - */ - public function setTargetObjIds($a_obj_id) - { - $this->target_obj_ids = $a_obj_id; - } - - /** - * get target object id - * @return int - */ - public function getTargetObjIds() - { - return $this->target_obj_ids; - } - - /** - * Check if target ref id is visible - * @param type $a_ref_id - */ - public function isTargetObjectVisible($a_ref_id) - { - // no course/group filter - if(!$this->getTargetObjIds()) - { - return true; - } - - $obj_id = ilObject::_lookupObjId($a_ref_id); - return in_array($obj_id, $this->getTargetObjIds()); - } - - /** - * Save a new booking entry - * @return - */ - public function save() - { - $ilDB = $this->db; - - $this->setId($ilDB->nextId('booking_entry')); - $query = 'INSERT INTO booking_entry (booking_id,obj_id,deadline,num_bookings,booking_group) '. - "VALUES ( ". - $ilDB->quote($this->getId(),'integer').', '. - $ilDB->quote($this->getObjId(),'integer').', '. - $ilDB->quote($this->getDeadlineHours(),'integer').', '. - $ilDB->quote($this->getNumberOfBookings(),'integer').','. - $ilDB->quote($this->getBookingGroup(),'integer').' '. - ") "; - $ilDB->manipulate($query); - - foreach((array) $this->target_obj_ids as $obj_id) - { - $query = 'INSERT INTO booking_obj_assignment (booking_id, target_obj_id) '. - 'VALUES( '. - $ilDB->quote($this->getId(),'integer').', '. - $ilDB->quote($obj_id,'integer').' '. - ')'; - $ilDB->manipulate($query); - } - return true; - } - - /** - * Update an existing booking entry - * @return - */ - public function update() - { - $ilDB = $this->db; - - if(!$this->getId()) - { - return false; - } - - $query = "UPDATE booking_entry SET ". - " obj_id = ".$ilDB->quote($this->getObjId(),'integer').", ". - " deadline = ".$ilDB->quote($this->getDeadlineHours(),'integer').", ". - " num_bookings = ".$ilDB->quote($this->getNumberOfBookings(),'integer').', '. - 'booking_group = '.$ilDB->quote($this->getBookingGroup(),'integer').' '. - 'WHERE booking_id = '.$ilDB->quote($this->getId(),'integer'); - $ilDB->manipulate($query); - - // obj assignments - $query = 'DELETE FROM booking_obj_assignment '. - 'WHERE booking_id = '.$ilDB->quote($this->getId(),'integer'); - $ilDB->manipulate($query); - - foreach((array) $this->target_obj_ids as $obj_id) - { - $query = 'INSERT INTO booking_obj_assignment (booking_id, target_obj_id) '. - 'VALUES( '. - $ilDB->quote($this->getId(),'integer').', '. - $ilDB->quote($obj_id,'integer').' '. - ')'; - $ilDB->manipulate($query); - } - return true; - } - - /** - * Delete - * @return - */ - public function delete() - { - $ilDB = $this->db; - - $query = "DELETE FROM booking_entry ". - "WHERE booking_id = ".$ilDB->quote($this->getId(),'integer'); - $ilDB->manipulate($query); - - $query = 'DELETE FROM booking_obj_assignment '. - 'WHERE booking_id = '.$ilDB->quote($this->getId(),'integer'); - $ilDB->manipulate($query); - - return true; - } - - /** - * Read settings from db - * @return - */ - protected function read() - { - $ilDB = $this->db; - - if(!$this->getId()) - { - return false; - } - - $query = "SELECT * FROM booking_entry ". - "WHERE booking_id = ".$ilDB->quote($this->getId(),'integer'); - $res = $ilDB->query($query); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_ASSOC)) - { - $this->setObjId($row['obj_id']); - $this->setDeadlineHours($row['deadline']); - $this->setNumberOfBookings($row['num_bookings']); - $this->setBookingGroup($row['booking_group']); - } - - $query = 'SELECT * FROM booking_obj_assignment '. - 'WHERE booking_id = '.$ilDB->quote($this->getId(),'integer'); - $res = $ilDB->query($query); - - $this->target_obj_ids = array(); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - $this->target_obj_ids[] = $row->target_obj_id; - } - - return true; - } - - /** - * check if current (or given) user is entry owner - * @param int $a_user_id - * @return bool - */ - public function isOwner($a_user_id = NULL) - { - $ilUser = $this->user; - - if(!$a_user_id) - { - $a_user_id = $ilUser->getId(); - } - - if($this->getObjId() == $a_user_id) - { - return true; - } - return false; - } - - /** - * Remove unused booking entries - */ - public static function removeObsoleteEntries() - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query('SELECT DISTINCT(context_id) FROM cal_entries e'. - ' JOIN cal_cat_assignments a ON (e.cal_id = a.cal_id)'. - ' JOIN cal_categories c ON (a.cat_id = c.cat_id) WHERE c.type = '.$ilDB->quote(ilCalendarCategory::TYPE_CH, 'integer')); - - $used = array(); - while($row = $ilDB->fetchAssoc($set)) - { - $used[] = $row['context_id']; - } - - $ilDB->query($q = 'DELETE FROM booking_entry WHERE '.$ilDB->in('booking_id', $used, true, 'integer')); - $ilDB->query($q = 'DELETE FROM booking_obj_assignment WHERE '.$ilDB->in('booking_id',$used,true,'integer')); - } - - /** - * Get instance by calendar entry - * @param int $id - * @return ilBookingEntry - */ - public static function getInstanceByCalendarEntryId($a_id) - { - include_once 'Services/Calendar/classes/class.ilCalendarEntry.php'; - $cal_entry = new ilCalendarEntry($a_id); - $booking_id = $cal_entry->getContextId(); - if($booking_id) - { - return new self($booking_id); - } - } - - /** - * Which objects are bookable? - * - * @param array $a_obj_ids - * @param int $a_target_obj_id - * @return array - */ - public static function isBookable(array $a_obj_ids, $a_target_obj_id = NULL) - { - global $DIC; - - $ilDB = $DIC->database(); - - if($a_target_obj_id) - { - $query = 'SELECT DISTINCT(obj_id) FROM booking_entry be '. - 'JOIN booking_obj_assignment bo ON be.booking_id = bo.booking_id '. - 'WHERE '.$ilDB->in('obj_id', $a_obj_ids, false, 'integer').' '. - 'AND bo.target_obj_id = '.$ilDB->quote($a_target_obj_id,'integer'); - } - else - { - $query = 'SELECT DISTINCT(obj_id) FROM booking_entry be '. - 'WHERE '.$ilDB->in('obj_id', $a_obj_ids, false, 'integer').' '; - } - - $res = $ilDB->query($query); - $all = array(); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - $all[] = $row->obj_id; - } - return $all; - } - - /** - * Consultation hours are offered if - * 1) consultation hour owner is admin or tutor and no object assignment - * 2) object is assigned to consultation hour - * @param type $a_obj_ids - * @param type $a_user_ids - * @return array user ids - */ - public static function lookupBookableUsersForObject($a_obj_id, $a_user_ids) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = 'SELECT be.obj_id bobj FROM booking_entry be '. - 'JOIN booking_obj_assignment bo ON be.booking_id = bo.booking_id '. - 'JOIN cal_entries ce on be.booking_id = ce.context_id '. - 'JOIN cal_cat_assignments cca on ce.cal_id = cca.cal_id '. - 'JOIN cal_categories cc on cca.cat_id = cc.cat_id '. - 'WHERE '.$ilDB->in('be.obj_id', (array) $a_user_ids,false,'integer'). ' '. - 'AND '.$ilDB->in('bo.target_obj_id', (array) $a_obj_id,false,'integer'). ' '. - 'AND cc.obj_id = be.obj_id '. - 'AND cc.type = '. $ilDB->quote(ilCalendarCategory::TYPE_CH,'integer').' '; - - $res = $ilDB->query($query); - - $objs = array(); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - if(!in_array($row->bobj,$objs)) - { - $objs[] = $row->bobj; - } - } - - // non filtered booking entries - $query = 'SELECT be.obj_id bobj FROM booking_entry be '. - 'LEFT JOIN booking_obj_assignment bo ON be.booking_id = bo.booking_id '. - 'JOIN cal_entries ce on be.booking_id = ce.context_id '. - 'JOIN cal_cat_assignments cca on ce.cal_id = cca.cal_id '. - 'JOIN cal_categories cc on cca.cat_id = cc.cat_id '. - 'WHERE bo.booking_id IS NULL '. - 'AND '.$ilDB->in('be.obj_id', (array) $a_user_ids,false,'integer'). ' '. - 'AND cc.obj_id = be.obj_id '. - 'AND cc.type = '. $ilDB->quote(ilCalendarCategory::TYPE_CH,'integer').' '; - - - $res = $ilDB->query($query); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - if(!in_array($row->bobj,$objs)) - { - $objs[] = $row->bobj; - } - } - - return $objs; - } - - /** - * Check if object has assigned consultation hour appointments - * @param type $a_obj_id - * @param type $a_usr_id - */ - public static function hasObjectBookingEntries($a_obj_id, $a_usr_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $user_restriction = ''; - if($a_usr_id) - { - $user_restriction = 'AND obj_id = '.$ilDB->quote($a_usr_id). ' '; - } - - - $query = 'SELECT be.booking_id FROM booking_entry be '. - 'JOIN booking_obj_assignment bo ON be.booking_id = bo.booking_id '. - 'WHERE bo.target_obj_id = '.$ilDB->quote($a_obj_id,'integer').' '. - $user_restriction; - - $res = $ilDB->query($query); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - return true; - } - return false; - } - - public static function lookupBookingMessage($a_entry_id, $a_usr_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = 'SELECT * from booking_user '. - 'WHERE entry_id = '.$ilDB->quote($a_entry_id,'integer').' '. - 'AND user_id = '.$ilDB->quote($a_usr_id,'integer'); - $res = $ilDB->query($query); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - return $row->booking_message; - } - return ''; - } - - /** - * Write booking message - * @param type $a_entry_id - * @param type $a_usr_id - * @param type $a_message - */ - public static function writeBookingMessage($a_entry_id, $a_usr_id, $a_message) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = 'UPDATE booking_user SET '. - 'booking_message = '.$ilDB->quote($a_message,'text').' '. - 'WHERE entry_id = '.$ilDB->quote($a_entry_id,'integer').' '. - 'AND user_id = '.$ilDB->quote($a_usr_id,'integer'); - - $GLOBALS['ilLog']->write(__METHOD__.': '.$query); - - $ilDB->manipulate($query); - return true; - } - - /** - * get current number of bookings - * @param int $a_entry_id - * @return int - */ - public function getCurrentNumberOfBookings($a_entry_id) - { - $ilDB = $this->db; - - $set = $ilDB->query('SELECT COUNT(*) AS counter FROM booking_user'. - ' WHERE entry_id = '.$ilDB->quote($a_entry_id, 'integer')); - $row = $ilDB->fetchAssoc($set); - return (int)$row['counter']; - } - - /** - * get current bookings - * @param int $a_entry_id - * @return array - */ - public function getCurrentBookings($a_entry_id) - { - $ilDB = $this->db; - - $set = $ilDB->query('SELECT user_id FROM booking_user'. - ' WHERE entry_id = '.$ilDB->quote($a_entry_id, 'integer')); - $res = array(); - while($row = $ilDB->fetchAssoc($set)) - { - $res[] = $row['user_id']; - } - return $res; - } - - /** - * Lookup booked users for appointment - * @global type $ilDB - * @param type $a_app_id - * @return type - */ - public static function lookupBookingsForAppointment($a_app_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = 'SELECT user_id FROM booking_user '. - 'WHERE entry_id = '.$ilDB->quote($a_app_id, 'integer'); - $res = $ilDB->query($query); - - $users = array(); - while($row = $ilDB->fetchObject($res)) - { - $users[] = $row->user_id; - } - return $users; - } - - /** - * Lookup booking for an object and user - * @param type $a_obj_id - * @param type $a_usr_id - * @return array - */ - public static function lookupBookingsForObject($a_obj_id, $a_usr_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - - $query = 'SELECT bu.user_id, starta, enda FROM booking_user bu '. - 'JOIN cal_entries ca ON entry_id = ca.cal_id '. - 'JOIN booking_entry be ON context_id = booking_id '. - 'JOIN booking_obj_assignment bo ON be.booking_id = bo.booking_id '. - 'WHERE bo.target_obj_id = '.$ilDB->quote($a_obj_id,'integer').' '. - 'AND be.obj_id = '.$ilDB->quote($a_usr_id).' '. - 'ORDER BY starta'; - $res = $ilDB->query($query); - - $bookings = array(); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - $dt = new ilDateTime($row->starta,IL_CAL_DATETIME, ilTimeZone::UTC); - $dt_end = new ilDateTime($row->enda,IL_CAL_DATETIME, ilTimeZone::UTC); - $bookings[$row->user_id][] = array( - 'dt' => $dt->get(IL_CAL_UNIX), - 'dtend' => $dt_end->get(IL_CAL_UNIX), - 'owner' => $a_usr_id); - - } - return $bookings; - } - - /** - * Lookup bookings for own and managed consultation hours of an object - * @param type $a_obj_id - * @param type $a_usr_id - * @return array - */ - public static function lookupManagedBookingsForObject($a_obj_id,$a_usr_id) - { - $bookings = self::lookupBookingsForObject($a_obj_id, $a_usr_id); - include_once './Services/Calendar/classes/ConsultationHours/class.ilConsultationHourUtils.php'; - foreach(ilConsultationHourUtils::lookupManagedUsers($a_usr_id) as $managed_user_id) - { - foreach(self::lookupBookingsForObject($a_obj_id, $managed_user_id) as $booked_user => $booking) - { - $fullname = ilObjUser::_lookupFullname($managed_user_id); - foreach($booking as $booking_entry) - { - $booking_entry['explanation'] = '('.$fullname.')'; - $bookings[$booked_user][] = $booking_entry; - } - } - } - return $bookings; - } - - - /** - * get current number of bookings - * @param int $a_entry_id - * @param int $a_user_id - * @return bool - */ - public function hasBooked($a_entry_id, $a_user_id = NULL) - { - $ilUser = $this->user; - $ilDB = $this->db; - - if(!$a_user_id) - { - $a_user_id = $ilUser->getId(); - } - - $query = 'SELECT COUNT(*) AS counter FROM booking_user'. - ' WHERE entry_id = '.$ilDB->quote($a_entry_id, 'integer'). - ' AND user_id = '.$ilDB->quote($a_user_id, 'integer'); - $set = $ilDB->query($query); - $row = $ilDB->fetchAssoc($set); - - return (bool) $row['counter']; - } - - /** - * get current number of bookings - * @param int $a_entry_id (calendar entry) - * @param bool $a_check_current_user - * @return bool - */ - public function isBookedOut($a_entry_id, $a_check_current_user = false) - { - $ilUser = $this->user; - - if($this->getNumberOfBookings() == $this->getCurrentNumberOfBookings($a_entry_id)) - { - // check against current user - if($a_check_current_user) - { - if($this->hasBooked($a_entry_id)) - { - return false; - } - if($ilUser->getId() == $this->getObjId()) - { - return false; - } - } - return true; - } - - $deadline = $this->getDeadlineHours(); - if($deadline) - { - include_once 'Services/Calendar/classes/class.ilCalendarEntry.php'; - $entry = new ilCalendarEntry($a_entry_id); - if(time()+($deadline*60*60) > $entry->getStart()->get(IL_CAL_UNIX)) - { - return true; - } - } - return false; - } - - /** - * Check if a calendar appointment is bookable for a specific user - * @param type $a_cal_entry_id - * @param type $a_user_id - * @return bool - */ - public function isAppointmentBookableForUser($a_app_id, $a_user_id) - { - // #12025 - if($a_user_id == ANONYMOUS_USER_ID) - { - return false; - } - - // Check max bookings - if($this->getNumberOfBookings() <= $this->getCurrentNumberOfBookings($a_app_id)) - { - #$GLOBALS['ilLog']->write(__METHOD__.': Number of bookings exceeded'); - return false; - } - - // Check deadline - $dead_limit = new ilDateTime(time(),IL_CAL_UNIX); - $dead_limit->increment(IL_CAL_HOUR,$this->getDeadlineHours()); - - include_once 'Services/Calendar/classes/class.ilCalendarEntry.php'; - $entry = new ilCalendarEntry($a_app_id); - if(ilDateTime::_after($dead_limit, $entry->getStart())) - { - #$GLOBALS['ilLog']->write(__METHOD__.': Deadline reached'); - return false; - } - - // Check group restrictions - if(!$this->getBookingGroup()) - { - #$GLOBALS['ilLog']->write(__METHOD__.': No booking group'); - return true; - } - include_once './Services/Calendar/classes/ConsultationHours/class.ilConsultationHourAppointments.php'; - $group_apps = ilConsultationHourAppointments::getAppointmentIdsByGroup( - $this->getObjId(), - $this->getBookingGroup() - ); - - // Number of bookings in group - $bookings = self::lookupBookingsOfUser($group_apps, $a_user_id); - - include_once './Services/Calendar/classes/ConsultationHours/class.ilConsultationHourGroups.php'; - #$GLOBALS['ilLog']->write(__METHOD__.': '.ilConsultationHourGroups::lookupMaxBookings($this->getBookingGroup())); - - if(count($bookings) >= ilConsultationHourGroups::lookupMaxBookings($this->getBookingGroup())) - { - #$GLOBALS['ilLog']->write(__METHOD__.': Personal booking limit reached'); - return false; - } - #$GLOBALS['ilLog']->write(__METHOD__.': Is bookable!'); - return true; - } - - /** - * book calendar entry for user - * @param int $a_entry_id - * @param int $a_user_id - */ - public function book($a_entry_id, $a_user_id = false) - { - $ilUser = $this->user; - $ilDB = $this->db; - - if(!$a_user_id) - { - $a_user_id = $ilUser->getId(); - } - - if(!$this->hasBooked($a_entry_id, $a_user_id)) - { - $ilDB->manipulate('INSERT INTO booking_user (entry_id, user_id, tstamp)'. - ' VALUES ('.$ilDB->quote($a_entry_id, 'integer').','. - $ilDB->quote($a_user_id, 'integer').','.$ilDB->quote(time(), 'integer').')'); - - include_once 'Services/Calendar/classes/class.ilCalendarMailNotification.php'; - $mail = new ilCalendarMailNotification(); - $mail->setAppointmentId($a_entry_id); - $mail->setRecipients(array($a_user_id)); - $mail->setType(ilCalendarMailNotification::TYPE_BOOKING_CONFIRMATION); - $mail->send(); - } - return true; - } - - /** - * cancel calendar booking for user - * @param int $a_entry_id - * @param int $a_user_id - */ - public function cancelBooking($a_entry_id, $a_user_id = false) - { - $ilUser = $this->user; - $ilDB = $this->db; - - if(!$a_user_id) - { - $a_user_id = $ilUser->getId(); - } - - // @todo do not send mails about past consultation hours - $entry = new ilCalendarEntry($a_entry_id); - - $past = ilDateTime::_before($entry->getStart(), new ilDateTime(time(),IL_CAL_UNIX)); - if($this->hasBooked($a_entry_id, $a_user_id) && !$past) - { - include_once 'Services/Calendar/classes/class.ilCalendarMailNotification.php'; - $mail = new ilCalendarMailNotification(); - $mail->setAppointmentId($a_entry_id); - $mail->setRecipients(array($a_user_id)); - $mail->setType(ilCalendarMailNotification::TYPE_BOOKING_CANCELLATION); - $mail->send(); - } - $this->deleteBooking($a_entry_id,$a_user_id); - return true; - } - - /** - * Delete booking - * @global type $ilDB - * @param type $a_entry_id - * @param type $a_user_id - * @return boolean - */ - public function deleteBooking($a_entry_id, $a_user_id) - { - $ilDB = $this->db; - - $query = 'DELETE FROM booking_user ' . - 'WHERE entry_id = '.$ilDB->quote($a_entry_id, 'integer').' '. - 'AND user_id = '.$ilDB->quote($a_user_id, 'integer'); - $ilDB->manipulate($query); - return true; - } + /** + * @var ilDB + */ + protected $db; + + /** + * @var ilObjUser + */ + protected $user; + + private $id = 0; + private $obj_id = 0; + + private $deadline = 0; + private $num_bookings = 1; + private $target_obj_ids = array(); + private $booking_group = 0; + + + /** + * Constructor + */ + public function __construct($a_booking_id = 0) + { + global $DIC; + + $this->db = $DIC->database(); + $this->user = $DIC->user(); + $this->setId($a_booking_id); + if ($this->getId()) { + $this->read(); + } + } + + /** + * Reset booking group (in case of deletion) + * @global type $ilDB + * @param type $a_group_id + * @return boolean + */ + public static function resetGroup($a_group_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = 'UPDATE booking_entry SET booking_group = ' . $ilDB->quote(0, 'integer') . ' ' . + 'WHERE booking_group = ' . $ilDB->quote($a_group_id, 'integer'); + $ilDB->manipulate($query); + return true; + } + + /** + * Lookup bookings if user + * @param type $a_app_ids + * @param type $a_usr_id + */ + public static function lookupBookingsOfUser($a_app_ids, $a_usr_id, ilDateTime $start = null) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = 'SELECT entry_id FROM booking_user ' . + 'WHERE ' . $ilDB->in('entry_id', $a_app_ids, false, 'integer') . ' ' . + 'AND user_id = ' . $ilDB->quote($a_usr_id, 'integer'); + + $res = $ilDB->query($query); + + $booked_entries = array(); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + $booked_entries[] = $row->entry_id; + } + return $booked_entries; + } + + /** + * Set id + * @param int $a_id + * @return + */ + protected function setId($a_id) + { + $this->id = (int) $a_id; + } + + /** + * Get id + * @return + */ + public function getId() + { + return $this->id; + } + + public function setBookingGroup($a_id) + { + $this->booking_group = $a_id; + } + + public function getBookingGroup() + { + return $this->booking_group; + } + + /** + * Set obj id + * @param int $a_id + * @return + */ + public function setObjId($a_id) + { + $this->obj_id = (int) $a_id; + } + + /** + * get obj id + * @return + */ + public function getObjId() + { + return $this->obj_id; + } + + /** + * set deadline hours + * @param int $a_hours + * @return + */ + public function setDeadlineHours($a_hours) + { + $this->deadline = (int) $a_hours; + } + + /** + * get deadline hours + * @return + */ + public function getDeadlineHours() + { + return $this->deadline; + } + + /** + * set number of bookings + * @param int $a_num + * @return + */ + public function setNumberOfBookings($a_num) + { + $this->num_bookings = (int) $a_num; + } + + /** + * get number of bookings + * @return + */ + public function getNumberOfBookings() + { + return $this->num_bookings; + } + + /** + * set target object id + * @param int $a_obj_id + * @return + */ + public function setTargetObjIds($a_obj_id) + { + $this->target_obj_ids = $a_obj_id; + } + + /** + * get target object id + * @return int + */ + public function getTargetObjIds() + { + return $this->target_obj_ids; + } + + /** + * Check if target ref id is visible + * @param type $a_ref_id + */ + public function isTargetObjectVisible($a_ref_id) + { + // no course/group filter + if (!$this->getTargetObjIds()) { + return true; + } + + $obj_id = ilObject::_lookupObjId($a_ref_id); + return in_array($obj_id, $this->getTargetObjIds()); + } + + /** + * Save a new booking entry + * @return + */ + public function save() + { + $ilDB = $this->db; + + $this->setId($ilDB->nextId('booking_entry')); + $query = 'INSERT INTO booking_entry (booking_id,obj_id,deadline,num_bookings,booking_group) ' . + "VALUES ( " . + $ilDB->quote($this->getId(), 'integer') . ', ' . + $ilDB->quote($this->getObjId(), 'integer') . ', ' . + $ilDB->quote($this->getDeadlineHours(), 'integer') . ', ' . + $ilDB->quote($this->getNumberOfBookings(), 'integer') . ',' . + $ilDB->quote($this->getBookingGroup(), 'integer') . ' ' . + ") "; + $ilDB->manipulate($query); + + foreach ((array) $this->target_obj_ids as $obj_id) { + $query = 'INSERT INTO booking_obj_assignment (booking_id, target_obj_id) ' . + 'VALUES( ' . + $ilDB->quote($this->getId(), 'integer') . ', ' . + $ilDB->quote($obj_id, 'integer') . ' ' . + ')'; + $ilDB->manipulate($query); + } + return true; + } + + /** + * Update an existing booking entry + * @return + */ + public function update() + { + $ilDB = $this->db; + + if (!$this->getId()) { + return false; + } + + $query = "UPDATE booking_entry SET " . + " obj_id = " . $ilDB->quote($this->getObjId(), 'integer') . ", " . + " deadline = " . $ilDB->quote($this->getDeadlineHours(), 'integer') . ", " . + " num_bookings = " . $ilDB->quote($this->getNumberOfBookings(), 'integer') . ', ' . + 'booking_group = ' . $ilDB->quote($this->getBookingGroup(), 'integer') . ' ' . + 'WHERE booking_id = ' . $ilDB->quote($this->getId(), 'integer'); + $ilDB->manipulate($query); + + // obj assignments + $query = 'DELETE FROM booking_obj_assignment ' . + 'WHERE booking_id = ' . $ilDB->quote($this->getId(), 'integer'); + $ilDB->manipulate($query); + + foreach ((array) $this->target_obj_ids as $obj_id) { + $query = 'INSERT INTO booking_obj_assignment (booking_id, target_obj_id) ' . + 'VALUES( ' . + $ilDB->quote($this->getId(), 'integer') . ', ' . + $ilDB->quote($obj_id, 'integer') . ' ' . + ')'; + $ilDB->manipulate($query); + } + return true; + } + + /** + * Delete + * @return + */ + public function delete() + { + $ilDB = $this->db; + + $query = "DELETE FROM booking_entry " . + "WHERE booking_id = " . $ilDB->quote($this->getId(), 'integer'); + $ilDB->manipulate($query); + + $query = 'DELETE FROM booking_obj_assignment ' . + 'WHERE booking_id = ' . $ilDB->quote($this->getId(), 'integer'); + $ilDB->manipulate($query); + + return true; + } + + /** + * Read settings from db + * @return + */ + protected function read() + { + $ilDB = $this->db; + + if (!$this->getId()) { + return false; + } + + $query = "SELECT * FROM booking_entry " . + "WHERE booking_id = " . $ilDB->quote($this->getId(), 'integer'); + $res = $ilDB->query($query); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_ASSOC)) { + $this->setObjId($row['obj_id']); + $this->setDeadlineHours($row['deadline']); + $this->setNumberOfBookings($row['num_bookings']); + $this->setBookingGroup($row['booking_group']); + } + + $query = 'SELECT * FROM booking_obj_assignment ' . + 'WHERE booking_id = ' . $ilDB->quote($this->getId(), 'integer'); + $res = $ilDB->query($query); + + $this->target_obj_ids = array(); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + $this->target_obj_ids[] = $row->target_obj_id; + } + + return true; + } + + /** + * check if current (or given) user is entry owner + * @param int $a_user_id + * @return bool + */ + public function isOwner($a_user_id = null) + { + $ilUser = $this->user; + + if (!$a_user_id) { + $a_user_id = $ilUser->getId(); + } + + if ($this->getObjId() == $a_user_id) { + return true; + } + return false; + } + + /** + * Remove unused booking entries + */ + public static function removeObsoleteEntries() + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query('SELECT DISTINCT(context_id) FROM cal_entries e' . + ' JOIN cal_cat_assignments a ON (e.cal_id = a.cal_id)' . + ' JOIN cal_categories c ON (a.cat_id = c.cat_id) WHERE c.type = ' . $ilDB->quote(ilCalendarCategory::TYPE_CH, 'integer')); + + $used = array(); + while ($row = $ilDB->fetchAssoc($set)) { + $used[] = $row['context_id']; + } + + $ilDB->query($q = 'DELETE FROM booking_entry WHERE ' . $ilDB->in('booking_id', $used, true, 'integer')); + $ilDB->query($q = 'DELETE FROM booking_obj_assignment WHERE ' . $ilDB->in('booking_id', $used, true, 'integer')); + } + + /** + * Get instance by calendar entry + * @param int $id + * @return ilBookingEntry + */ + public static function getInstanceByCalendarEntryId($a_id) + { + include_once 'Services/Calendar/classes/class.ilCalendarEntry.php'; + $cal_entry = new ilCalendarEntry($a_id); + $booking_id = $cal_entry->getContextId(); + if ($booking_id) { + return new self($booking_id); + } + } + + /** + * Which objects are bookable? + * + * @param array $a_obj_ids + * @param int $a_target_obj_id + * @return array + */ + public static function isBookable(array $a_obj_ids, $a_target_obj_id = null) + { + global $DIC; + + $ilDB = $DIC->database(); + + if ($a_target_obj_id) { + $query = 'SELECT DISTINCT(obj_id) FROM booking_entry be ' . + 'JOIN booking_obj_assignment bo ON be.booking_id = bo.booking_id ' . + 'WHERE ' . $ilDB->in('obj_id', $a_obj_ids, false, 'integer') . ' ' . + 'AND bo.target_obj_id = ' . $ilDB->quote($a_target_obj_id, 'integer'); + } else { + $query = 'SELECT DISTINCT(obj_id) FROM booking_entry be ' . + 'WHERE ' . $ilDB->in('obj_id', $a_obj_ids, false, 'integer') . ' '; + } + + $res = $ilDB->query($query); + $all = array(); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + $all[] = $row->obj_id; + } + return $all; + } + + /** + * Consultation hours are offered if + * 1) consultation hour owner is admin or tutor and no object assignment + * 2) object is assigned to consultation hour + * @param type $a_obj_ids + * @param type $a_user_ids + * @return array user ids + */ + public static function lookupBookableUsersForObject($a_obj_id, $a_user_ids) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = 'SELECT be.obj_id bobj FROM booking_entry be ' . + 'JOIN booking_obj_assignment bo ON be.booking_id = bo.booking_id ' . + 'JOIN cal_entries ce on be.booking_id = ce.context_id ' . + 'JOIN cal_cat_assignments cca on ce.cal_id = cca.cal_id ' . + 'JOIN cal_categories cc on cca.cat_id = cc.cat_id ' . + 'WHERE ' . $ilDB->in('be.obj_id', (array) $a_user_ids, false, 'integer') . ' ' . + 'AND ' . $ilDB->in('bo.target_obj_id', (array) $a_obj_id, false, 'integer') . ' ' . + 'AND cc.obj_id = be.obj_id ' . + 'AND cc.type = ' . $ilDB->quote(ilCalendarCategory::TYPE_CH, 'integer') . ' '; + + $res = $ilDB->query($query); + + $objs = array(); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + if (!in_array($row->bobj, $objs)) { + $objs[] = $row->bobj; + } + } + + // non filtered booking entries + $query = 'SELECT be.obj_id bobj FROM booking_entry be ' . + 'LEFT JOIN booking_obj_assignment bo ON be.booking_id = bo.booking_id ' . + 'JOIN cal_entries ce on be.booking_id = ce.context_id ' . + 'JOIN cal_cat_assignments cca on ce.cal_id = cca.cal_id ' . + 'JOIN cal_categories cc on cca.cat_id = cc.cat_id ' . + 'WHERE bo.booking_id IS NULL ' . + 'AND ' . $ilDB->in('be.obj_id', (array) $a_user_ids, false, 'integer') . ' ' . + 'AND cc.obj_id = be.obj_id ' . + 'AND cc.type = ' . $ilDB->quote(ilCalendarCategory::TYPE_CH, 'integer') . ' '; + + + $res = $ilDB->query($query); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + if (!in_array($row->bobj, $objs)) { + $objs[] = $row->bobj; + } + } + + return $objs; + } + + /** + * Check if object has assigned consultation hour appointments + * @param type $a_obj_id + * @param type $a_usr_id + */ + public static function hasObjectBookingEntries($a_obj_id, $a_usr_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $user_restriction = ''; + if ($a_usr_id) { + $user_restriction = 'AND obj_id = ' . $ilDB->quote($a_usr_id) . ' '; + } + + + $query = 'SELECT be.booking_id FROM booking_entry be ' . + 'JOIN booking_obj_assignment bo ON be.booking_id = bo.booking_id ' . + 'WHERE bo.target_obj_id = ' . $ilDB->quote($a_obj_id, 'integer') . ' ' . + $user_restriction; + + $res = $ilDB->query($query); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + return true; + } + return false; + } + + public static function lookupBookingMessage($a_entry_id, $a_usr_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = 'SELECT * from booking_user ' . + 'WHERE entry_id = ' . $ilDB->quote($a_entry_id, 'integer') . ' ' . + 'AND user_id = ' . $ilDB->quote($a_usr_id, 'integer'); + $res = $ilDB->query($query); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + return $row->booking_message; + } + return ''; + } + + /** + * Write booking message + * @param type $a_entry_id + * @param type $a_usr_id + * @param type $a_message + */ + public static function writeBookingMessage($a_entry_id, $a_usr_id, $a_message) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = 'UPDATE booking_user SET ' . + 'booking_message = ' . $ilDB->quote($a_message, 'text') . ' ' . + 'WHERE entry_id = ' . $ilDB->quote($a_entry_id, 'integer') . ' ' . + 'AND user_id = ' . $ilDB->quote($a_usr_id, 'integer'); + + $GLOBALS['ilLog']->write(__METHOD__ . ': ' . $query); + + $ilDB->manipulate($query); + return true; + } + + /** + * get current number of bookings + * @param int $a_entry_id + * @return int + */ + public function getCurrentNumberOfBookings($a_entry_id) + { + $ilDB = $this->db; + + $set = $ilDB->query('SELECT COUNT(*) AS counter FROM booking_user' . + ' WHERE entry_id = ' . $ilDB->quote($a_entry_id, 'integer')); + $row = $ilDB->fetchAssoc($set); + return (int) $row['counter']; + } + + /** + * get current bookings + * @param int $a_entry_id + * @return array + */ + public function getCurrentBookings($a_entry_id) + { + $ilDB = $this->db; + + $set = $ilDB->query('SELECT user_id FROM booking_user' . + ' WHERE entry_id = ' . $ilDB->quote($a_entry_id, 'integer')); + $res = array(); + while ($row = $ilDB->fetchAssoc($set)) { + $res[] = $row['user_id']; + } + return $res; + } + + /** + * Lookup booked users for appointment + * @global type $ilDB + * @param type $a_app_id + * @return type + */ + public static function lookupBookingsForAppointment($a_app_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = 'SELECT user_id FROM booking_user ' . + 'WHERE entry_id = ' . $ilDB->quote($a_app_id, 'integer'); + $res = $ilDB->query($query); + + $users = array(); + while ($row = $ilDB->fetchObject($res)) { + $users[] = $row->user_id; + } + return $users; + } + + /** + * Lookup booking for an object and user + * @param type $a_obj_id + * @param type $a_usr_id + * @return array + */ + public static function lookupBookingsForObject($a_obj_id, $a_usr_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + + $query = 'SELECT bu.user_id, starta, enda FROM booking_user bu ' . + 'JOIN cal_entries ca ON entry_id = ca.cal_id ' . + 'JOIN booking_entry be ON context_id = booking_id ' . + 'JOIN booking_obj_assignment bo ON be.booking_id = bo.booking_id ' . + 'WHERE bo.target_obj_id = ' . $ilDB->quote($a_obj_id, 'integer') . ' ' . + 'AND be.obj_id = ' . $ilDB->quote($a_usr_id) . ' ' . + 'ORDER BY starta'; + $res = $ilDB->query($query); + + $bookings = array(); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + $dt = new ilDateTime($row->starta, IL_CAL_DATETIME, ilTimeZone::UTC); + $dt_end = new ilDateTime($row->enda, IL_CAL_DATETIME, ilTimeZone::UTC); + $bookings[$row->user_id][] = array( + 'dt' => $dt->get(IL_CAL_UNIX), + 'dtend' => $dt_end->get(IL_CAL_UNIX), + 'owner' => $a_usr_id); + } + return $bookings; + } + + /** + * Lookup bookings for own and managed consultation hours of an object + * @param type $a_obj_id + * @param type $a_usr_id + * @return array + */ + public static function lookupManagedBookingsForObject($a_obj_id, $a_usr_id) + { + $bookings = self::lookupBookingsForObject($a_obj_id, $a_usr_id); + include_once './Services/Calendar/classes/ConsultationHours/class.ilConsultationHourUtils.php'; + foreach (ilConsultationHourUtils::lookupManagedUsers($a_usr_id) as $managed_user_id) { + foreach (self::lookupBookingsForObject($a_obj_id, $managed_user_id) as $booked_user => $booking) { + $fullname = ilObjUser::_lookupFullname($managed_user_id); + foreach ($booking as $booking_entry) { + $booking_entry['explanation'] = '(' . $fullname . ')'; + $bookings[$booked_user][] = $booking_entry; + } + } + } + return $bookings; + } + + + /** + * get current number of bookings + * @param int $a_entry_id + * @param int $a_user_id + * @return bool + */ + public function hasBooked($a_entry_id, $a_user_id = null) + { + $ilUser = $this->user; + $ilDB = $this->db; + + if (!$a_user_id) { + $a_user_id = $ilUser->getId(); + } + + $query = 'SELECT COUNT(*) AS counter FROM booking_user' . + ' WHERE entry_id = ' . $ilDB->quote($a_entry_id, 'integer') . + ' AND user_id = ' . $ilDB->quote($a_user_id, 'integer'); + $set = $ilDB->query($query); + $row = $ilDB->fetchAssoc($set); + + return (bool) $row['counter']; + } + + /** + * get current number of bookings + * @param int $a_entry_id (calendar entry) + * @param bool $a_check_current_user + * @return bool + */ + public function isBookedOut($a_entry_id, $a_check_current_user = false) + { + $ilUser = $this->user; + + if ($this->getNumberOfBookings() == $this->getCurrentNumberOfBookings($a_entry_id)) { + // check against current user + if ($a_check_current_user) { + if ($this->hasBooked($a_entry_id)) { + return false; + } + if ($ilUser->getId() == $this->getObjId()) { + return false; + } + } + return true; + } + + $deadline = $this->getDeadlineHours(); + if ($deadline) { + include_once 'Services/Calendar/classes/class.ilCalendarEntry.php'; + $entry = new ilCalendarEntry($a_entry_id); + if (time()+($deadline*60*60) > $entry->getStart()->get(IL_CAL_UNIX)) { + return true; + } + } + return false; + } + + /** + * Check if a calendar appointment is bookable for a specific user + * @param type $a_cal_entry_id + * @param type $a_user_id + * @return bool + */ + public function isAppointmentBookableForUser($a_app_id, $a_user_id) + { + // #12025 + if ($a_user_id == ANONYMOUS_USER_ID) { + return false; + } + + // Check max bookings + if ($this->getNumberOfBookings() <= $this->getCurrentNumberOfBookings($a_app_id)) { + #$GLOBALS['ilLog']->write(__METHOD__.': Number of bookings exceeded'); + return false; + } + + // Check deadline + $dead_limit = new ilDateTime(time(), IL_CAL_UNIX); + $dead_limit->increment(IL_CAL_HOUR, $this->getDeadlineHours()); + + include_once 'Services/Calendar/classes/class.ilCalendarEntry.php'; + $entry = new ilCalendarEntry($a_app_id); + if (ilDateTime::_after($dead_limit, $entry->getStart())) { + #$GLOBALS['ilLog']->write(__METHOD__.': Deadline reached'); + return false; + } + + // Check group restrictions + if (!$this->getBookingGroup()) { + #$GLOBALS['ilLog']->write(__METHOD__.': No booking group'); + return true; + } + include_once './Services/Calendar/classes/ConsultationHours/class.ilConsultationHourAppointments.php'; + $group_apps = ilConsultationHourAppointments::getAppointmentIdsByGroup( + $this->getObjId(), + $this->getBookingGroup() + ); + + // Number of bookings in group + $bookings = self::lookupBookingsOfUser($group_apps, $a_user_id); + + include_once './Services/Calendar/classes/ConsultationHours/class.ilConsultationHourGroups.php'; + #$GLOBALS['ilLog']->write(__METHOD__.': '.ilConsultationHourGroups::lookupMaxBookings($this->getBookingGroup())); + + if (count($bookings) >= ilConsultationHourGroups::lookupMaxBookings($this->getBookingGroup())) { + #$GLOBALS['ilLog']->write(__METHOD__.': Personal booking limit reached'); + return false; + } + #$GLOBALS['ilLog']->write(__METHOD__.': Is bookable!'); + return true; + } + + /** + * book calendar entry for user + * @param int $a_entry_id + * @param int $a_user_id + */ + public function book($a_entry_id, $a_user_id = false) + { + $ilUser = $this->user; + $ilDB = $this->db; + + if (!$a_user_id) { + $a_user_id = $ilUser->getId(); + } + + if (!$this->hasBooked($a_entry_id, $a_user_id)) { + $ilDB->manipulate('INSERT INTO booking_user (entry_id, user_id, tstamp)' . + ' VALUES (' . $ilDB->quote($a_entry_id, 'integer') . ',' . + $ilDB->quote($a_user_id, 'integer') . ',' . $ilDB->quote(time(), 'integer') . ')'); + + include_once 'Services/Calendar/classes/class.ilCalendarMailNotification.php'; + $mail = new ilCalendarMailNotification(); + $mail->setAppointmentId($a_entry_id); + $mail->setRecipients(array($a_user_id)); + $mail->setType(ilCalendarMailNotification::TYPE_BOOKING_CONFIRMATION); + $mail->send(); + } + return true; + } + + /** + * cancel calendar booking for user + * @param int $a_entry_id + * @param int $a_user_id + */ + public function cancelBooking($a_entry_id, $a_user_id = false) + { + $ilUser = $this->user; + $ilDB = $this->db; + + if (!$a_user_id) { + $a_user_id = $ilUser->getId(); + } + + // @todo do not send mails about past consultation hours + $entry = new ilCalendarEntry($a_entry_id); + + $past = ilDateTime::_before($entry->getStart(), new ilDateTime(time(), IL_CAL_UNIX)); + if ($this->hasBooked($a_entry_id, $a_user_id) && !$past) { + include_once 'Services/Calendar/classes/class.ilCalendarMailNotification.php'; + $mail = new ilCalendarMailNotification(); + $mail->setAppointmentId($a_entry_id); + $mail->setRecipients(array($a_user_id)); + $mail->setType(ilCalendarMailNotification::TYPE_BOOKING_CANCELLATION); + $mail->send(); + } + $this->deleteBooking($a_entry_id, $a_user_id); + return true; + } + + /** + * Delete booking + * @global type $ilDB + * @param type $a_entry_id + * @param type $a_user_id + * @return boolean + */ + public function deleteBooking($a_entry_id, $a_user_id) + { + $ilDB = $this->db; + + $query = 'DELETE FROM booking_user ' . + 'WHERE entry_id = ' . $ilDB->quote($a_entry_id, 'integer') . ' ' . + 'AND user_id = ' . $ilDB->quote($a_user_id, 'integer'); + $ilDB->manipulate($query); + return true; + } } - -?> \ No newline at end of file diff --git a/Services/Booking/classes/class.ilBookingPeriod.php b/Services/Booking/classes/class.ilBookingPeriod.php index 97b7c9b9383c15bacefaf658867937df0d745033..5dee8642cc67e9b92c4d4a2643f0a8443d3b9730 100644 --- a/Services/Booking/classes/class.ilBookingPeriod.php +++ b/Services/Booking/classes/class.ilBookingPeriod.php @@ -1,11 +1,11 @@ * @@ -15,37 +15,36 @@ include_once ('./Services/Calendar/interfaces/interface.ilDatePeriod.php'); */ class ilBookingPeriod implements ilDatePeriod { - private $start = null; - private $end = null; + private $start = null; + private $end = null; - /** - * Constructor - */ - public function __construct(ilDateTime $start,ilDateTime $end) - { - $this->start = $start; - $this->end = $end; - } - /** - * @see ilDatePeriod::getEnd() - */ - public function getEnd() - { - return $this->end; - } - /** - * @see ilDatePeriod::getStart() - */ - public function getStart() - { - return $this->start; - } - /** - * @see ilDatePeriod::isFullday() - */ - public function isFullday() - { - return false; - } + /** + * Constructor + */ + public function __construct(ilDateTime $start, ilDateTime $end) + { + $this->start = $start; + $this->end = $end; + } + /** + * @see ilDatePeriod::getEnd() + */ + public function getEnd() + { + return $this->end; + } + /** + * @see ilDatePeriod::getStart() + */ + public function getStart() + { + return $this->start; + } + /** + * @see ilDatePeriod::isFullday() + */ + public function isFullday() + { + return false; + } } -?> \ No newline at end of file diff --git a/Services/COPage/Layout/classes/class.ilPageLayout.php b/Services/COPage/Layout/classes/class.ilPageLayout.php index 7398e7cdffa16bd3ff8e2e678ed99e10d85e999f..428626976c32b6b67f2710a7500ec22cb0701b3c 100644 --- a/Services/COPage/Layout/classes/class.ilPageLayout.php +++ b/Services/COPage/Layout/classes/class.ilPageLayout.php @@ -11,363 +11,359 @@ * * @ingroup ServicesStyle */ -class ilPageLayout +class ilPageLayout { - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; - - const SEQ_TEMPLATE_DIR = './Modules/Scorm2004/templates/editor/page_layouts_temp/thumbnails'; - - const MODULE_SCORM = 1; - const MODULE_PORTFOLIO = 2; - - var $layout_id = null; - var $title = null; - var $description = null; - var $active = null; - var $modules = array(); - - function __construct($a_id=null) - { - global $DIC; + + const SEQ_TEMPLATE_DIR = './Modules/Scorm2004/templates/editor/page_layouts_temp/thumbnails'; + + const MODULE_SCORM = 1; + const MODULE_PORTFOLIO = 2; + + public $layout_id = null; + public $title = null; + public $description = null; + public $active = null; + public $modules = array(); + + public function __construct($a_id=null) + { + global $DIC; - $this->db = $DIC->database(); - $ilDB = $DIC->database(); - //create new instance - if ($a_id == null) { - $this->layout_id = $ilDB->nextId("page_layout"); - $ilDB->insert("page_layout", array( - "layout_id" => array("integer", $this->layout_id), - "active" => array("integer", 0), - "title" => array("text", ""), - "content" => array("clob", ""), - "description" => array("text", "") - )); - //$query = "INSERT INTO page_layout(active) values (0);"; - //$result = $ilDB->query($query); - //$query = "SELECT LAST_INSERT_ID() as id"; - //$res = $ilDB->query($query); - //$row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT); - //$this->layout_id = $row->id; - $this->active = false; - } - else { - $this->layout_id = $a_id; - } - } - - public function getActive() { - return $this->active; - } + $this->db = $DIC->database(); + $ilDB = $DIC->database(); + //create new instance + if ($a_id == null) { + $this->layout_id = $ilDB->nextId("page_layout"); + $ilDB->insert("page_layout", array( + "layout_id" => array("integer", $this->layout_id), + "active" => array("integer", 0), + "title" => array("text", ""), + "content" => array("clob", ""), + "description" => array("text", "") + )); + //$query = "INSERT INTO page_layout(active) values (0);"; + //$result = $ilDB->query($query); + //$query = "SELECT LAST_INSERT_ID() as id"; + //$res = $ilDB->query($query); + //$row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT); + //$this->layout_id = $row->id; + $this->active = false; + } else { + $this->layout_id = $a_id; + } + } + + public function getActive() + { + return $this->active; + } - public function getDescription() { - return $this->description; - } - - public function setDescription($a_description) { - $this->description = $a_description; - } - - public function getTitle() { - return $this->title; - } - - public function setTitle($a_title) { - $this->title = $a_title; - } - - public function getId() { - return $this->layout_id; - } + public function getDescription() + { + return $this->description; + } + + public function setDescription($a_description) + { + $this->description = $a_description; + } + + public function getTitle() + { + return $this->title; + } + + public function setTitle($a_title) + { + $this->title = $a_title; + } + + public function getId() + { + return $this->layout_id; + } - /** - * Set style id - */ - public function setStyleId($a_val) - { - $this->style_id = $a_val; - } + /** + * Set style id + */ + public function setStyleId($a_val) + { + $this->style_id = $a_val; + } - /** - * Get style id - */ - public function getStyleId() - { - return $this->style_id; - } + /** + * Get style id + */ + public function getStyleId() + { + return $this->style_id; + } - /** - * Set special page - */ - public function setSpecialPage($a_val) - { - $this->special_page = $a_val; - } + /** + * Set special page + */ + public function setSpecialPage($a_val) + { + $this->special_page = $a_val; + } - /** - * Get special page - */ - public function getSpecialPage() - { - return $this->special_page; - } - - /** - * Set modules - */ - public function setModules(array $a_values = null) - { - if($a_values) - { - $valid = array_keys($this->getAvailableModules()); - $this->modules = array_intersect($a_values, $valid); - } - else - { - $this->modules = array(); - } - } + /** + * Get special page + */ + public function getSpecialPage() + { + return $this->special_page; + } + + /** + * Set modules + */ + public function setModules(array $a_values = null) + { + if ($a_values) { + $valid = array_keys($this->getAvailableModules()); + $this->modules = array_intersect($a_values, $valid); + } else { + $this->modules = array(); + } + } - /** - * Get modules - */ - public function getModules() - { - return $this->modules; - } + /** + * Get modules + */ + public function getModules() + { + return $this->modules; + } - /** - * (De-)Activate layout - * - * @param boolean $a_setting true/false - */ - public function activate($a_setting=true) - { - $ilDB = $this->db; + /** + * (De-)Activate layout + * + * @param boolean $a_setting true/false + */ + public function activate($a_setting=true) + { + $ilDB = $this->db; - $query = "UPDATE page_layout SET active=".$ilDB->quote($a_setting, "integer"). - " WHERE layout_id =".$ilDB->quote($this->layout_id, "integer"); - $result = $ilDB->manipulate($query); - } + $query = "UPDATE page_layout SET active=" . $ilDB->quote($a_setting, "integer") . + " WHERE layout_id =" . $ilDB->quote($this->layout_id, "integer"); + $result = $ilDB->manipulate($query); + } - /** - * Delete page layout - */ - public function delete() - { - $ilDB = $this->db; + /** + * Delete page layout + */ + public function delete() + { + $ilDB = $this->db; - $query = "DELETE FROM page_layout WHERE layout_id =".$ilDB->quote($this->layout_id, "integer"); - $result = $ilDB->manipulate($query); - } + $query = "DELETE FROM page_layout WHERE layout_id =" . $ilDB->quote($this->layout_id, "integer"); + $result = $ilDB->manipulate($query); + } - /** - * Update page layout - */ - public function update() - { - $ilDB = $this->db; - - $mod_scorm = $mod_portfolio = 0; - if(in_array(self::MODULE_SCORM, $this->modules)) - { - $mod_scorm = 1; - } - if(in_array(self::MODULE_PORTFOLIO, $this->modules)) - { - $mod_portfolio = 1; - } + /** + * Update page layout + */ + public function update() + { + $ilDB = $this->db; + + $mod_scorm = $mod_portfolio = 0; + if (in_array(self::MODULE_SCORM, $this->modules)) { + $mod_scorm = 1; + } + if (in_array(self::MODULE_PORTFOLIO, $this->modules)) { + $mod_portfolio = 1; + } - $query = "UPDATE page_layout SET title=".$ilDB->quote($this->title, "text"). - ",description =".$ilDB->quote($this->description, "text"). - ",active =".$ilDB->quote($this->active, "integer"). - ",style_id =".$ilDB->quote($this->getStyleId(), "integer"). - ",special_page =".$ilDB->quote((int) $this->getSpecialPage(), "integer"). - ",mod_scorm =".$ilDB->quote($mod_scorm, "integer"). - ",mod_portfolio =".$ilDB->quote($mod_portfolio, "integer"). - " WHERE layout_id =".$ilDB->quote($this->layout_id, "integer"); - - $result = $ilDB->manipulate($query); - } + $query = "UPDATE page_layout SET title=" . $ilDB->quote($this->title, "text") . + ",description =" . $ilDB->quote($this->description, "text") . + ",active =" . $ilDB->quote($this->active, "integer") . + ",style_id =" . $ilDB->quote($this->getStyleId(), "integer") . + ",special_page =" . $ilDB->quote((int) $this->getSpecialPage(), "integer") . + ",mod_scorm =" . $ilDB->quote($mod_scorm, "integer") . + ",mod_portfolio =" . $ilDB->quote($mod_portfolio, "integer") . + " WHERE layout_id =" . $ilDB->quote($this->layout_id, "integer"); + + $result = $ilDB->manipulate($query); + } - /** - * Read page layout - */ - public function readObject() - { - $ilDB = $this->db; - $query = "SELECT * FROM page_layout WHERE layout_id =".$ilDB->quote($this->layout_id, "integer"); - $result = $ilDB->query($query); - $row = $ilDB->fetchAssoc($result); - $this->title = $row['title']; - $this->setStyleId($row['style_id']); - $this->setSpecialPage($row['special_page']); - $this->description=$row['description']; - $this->active=$row['active']; - - $mods = array(); - if($row["mod_scorm"]) - { - $mods[] = self::MODULE_SCORM; - } - if($row["mod_portfolio"]) - { - $mods[] = self::MODULE_PORTFOLIO; - } - $this->setModules($mods); - } + /** + * Read page layout + */ + public function readObject() + { + $ilDB = $this->db; + $query = "SELECT * FROM page_layout WHERE layout_id =" . $ilDB->quote($this->layout_id, "integer"); + $result = $ilDB->query($query); + $row = $ilDB->fetchAssoc($result); + $this->title = $row['title']; + $this->setStyleId($row['style_id']); + $this->setSpecialPage($row['special_page']); + $this->description=$row['description']; + $this->active=$row['active']; + + $mods = array(); + if ($row["mod_scorm"]) { + $mods[] = self::MODULE_SCORM; + } + if ($row["mod_portfolio"]) { + $mods[] = self::MODULE_PORTFOLIO; + } + $this->setModules($mods); + } - /** - * Get xml content - * - * @return string content xml - */ - public function getXMLContent() - { - include_once "Services/COPage/Layout/classes/class.ilPageLayoutPage.php"; - $layout_page = new ilPageLayoutPage($this->layout_id); - return $layout_page->getXMLContent(); - } - + /** + * Get xml content + * + * @return string content xml + */ + public function getXMLContent() + { + include_once "Services/COPage/Layout/classes/class.ilPageLayoutPage.php"; + $layout_page = new ilPageLayoutPage($this->layout_id); + return $layout_page->getXMLContent(); + } + - /** - * Get preview - */ - public function getPreview() - { - return $this->generatePreview(); - } - - - private function getXSLPath() { - return "./Services/COPage/Layout/xml/layout2html.xsl"; - } - - private function generatePreview() { - - $xml = $this->getXMLContent(); - - $dom = @domxml_open_mem($xml, DOMXML_LOAD_PARSING, $error); - $xpc = xpath_new_context($dom); - $path = "////PlaceHolder"; - $res = xpath_eval($xpc, $path); - - foreach ($res->nodeset as $item){ - $height = $item->get_attribute("Height"); - - $height = str_ireplace("px","",$height); - $height=$height/10; - $item->set_attribute("Height",$height."px"); - } - $xsl = file_get_contents($this->getXSLPath()); - - $xml = $dom->dump_mem(0, "UTF-8"); - - $args = array( '/_xml' => $xml, '/_xsl' => $xsl ); - - $xh = xslt_create(); - $output = xslt_process($xh, "arg:/_xml", "arg:/_xsl", NULL, $args, NULL); - xslt_error($xh); - xslt_free($xh); - return $output; - } - - /** - * - * Static access functions - */ - - public static function getLayoutsAsArray($a_active=0){ - - global $DIC; + /** + * Get preview + */ + public function getPreview() + { + return $this->generatePreview(); + } + + + private function getXSLPath() + { + return "./Services/COPage/Layout/xml/layout2html.xsl"; + } + + private function generatePreview() + { + $xml = $this->getXMLContent(); + + $dom = @domxml_open_mem($xml, DOMXML_LOAD_PARSING, $error); + $xpc = xpath_new_context($dom); + $path = "////PlaceHolder"; + $res = xpath_eval($xpc, $path); + + foreach ($res->nodeset as $item) { + $height = $item->get_attribute("Height"); + + $height = str_ireplace("px", "", $height); + $height=$height/10; + $item->set_attribute("Height", $height . "px"); + } + $xsl = file_get_contents($this->getXSLPath()); + + $xml = $dom->dump_mem(0, "UTF-8"); + + $args = array( '/_xml' => $xml, '/_xsl' => $xsl ); + + $xh = xslt_create(); + $output = xslt_process($xh, "arg:/_xml", "arg:/_xsl", null, $args, null); + xslt_error($xh); + xslt_free($xh); + return $output; + } + + /** + * + * Static access functions + */ + + public static function getLayoutsAsArray($a_active=0) + { + global $DIC; - $ilDB = $DIC->database(); - $arr_layouts = array(); - if ($active!=0) { - $add ="WHERE (active=1)"; - } - $query = "SELECT * FROM page_layout $add ORDER BY title "; - $result = $ilDB->query($query); - while($row = $result->fetchRow(ilDBConstants::FETCHMODE_ASSOC)) - { - array_push($arr_layouts,$row); - } - return $arr_layouts; - - } - - /** - * Get layouts - */ - public static function getLayouts($a_active = false, $a_special_page = false, $a_module = null) - { - global $DIC; + $ilDB = $DIC->database(); + $arr_layouts = array(); + if ($active!=0) { + $add ="WHERE (active=1)"; + } + $query = "SELECT * FROM page_layout $add ORDER BY title "; + $result = $ilDB->query($query); + while ($row = $result->fetchRow(ilDBConstants::FETCHMODE_ASSOC)) { + array_push($arr_layouts, $row); + } + return $arr_layouts; + } + + /** + * Get layouts + */ + public static function getLayouts($a_active = false, $a_special_page = false, $a_module = null) + { + global $DIC; - $ilDB = $DIC->database(); - $arr_layouts = array(); - $add = "WHERE special_page = ".$ilDB->quote($a_special_page, "integer"); - if ($a_active) - { - $add.= " AND (active = 1)"; - } - switch($a_module) - { - case self::MODULE_SCORM: - $add .= " AND mod_scorm = 1"; - break; - - case self::MODULE_PORTFOLIO: - $add .= " AND mod_portfolio = 1"; - break; - } - $query = "SELECT layout_id FROM page_layout $add ORDER BY title "; - $result = $ilDB->query($query); - while($row = $result->fetchRow(ilDBConstants::FETCHMODE_ASSOC)) - { - array_push($arr_layouts,new ilPageLayout($row['layout_id'])); - } + $ilDB = $DIC->database(); + $arr_layouts = array(); + $add = "WHERE special_page = " . $ilDB->quote($a_special_page, "integer"); + if ($a_active) { + $add.= " AND (active = 1)"; + } + switch ($a_module) { + case self::MODULE_SCORM: + $add .= " AND mod_scorm = 1"; + break; + + case self::MODULE_PORTFOLIO: + $add .= " AND mod_portfolio = 1"; + break; + } + $query = "SELECT layout_id FROM page_layout $add ORDER BY title "; + $result = $ilDB->query($query); + while ($row = $result->fetchRow(ilDBConstants::FETCHMODE_ASSOC)) { + array_push($arr_layouts, new ilPageLayout($row['layout_id'])); + } - return $arr_layouts; - } - - /** - * Get active layouts - */ - public static function activeLayouts($a_special_page = false, $a_module = null) - { - return self::getLayouts(true, $a_special_page, $a_module); - } - - /** - * Import page layout - * - * @param string $a_filename file name - * @param string $a_fiepath complete path (incl. name) to file - * - * @return object new object - */ - static function import($a_filename, $a_filepath) - { - include_once("./Services/Export/classes/class.ilImport.php"); - $imp = new ilImport(); - $imp->importEntity($a_filepath, $a_filename, - "pgtp", "Services/COPage"); - } - - static function getAvailableModules() - { - global $DIC; + return $arr_layouts; + } + + /** + * Get active layouts + */ + public static function activeLayouts($a_special_page = false, $a_module = null) + { + return self::getLayouts(true, $a_special_page, $a_module); + } + + /** + * Import page layout + * + * @param string $a_filename file name + * @param string $a_fiepath complete path (incl. name) to file + * + * @return object new object + */ + public static function import($a_filename, $a_filepath) + { + include_once("./Services/Export/classes/class.ilImport.php"); + $imp = new ilImport(); + $imp->importEntity( + $a_filepath, + $a_filename, + "pgtp", + "Services/COPage" + ); + } + + public static function getAvailableModules() + { + global $DIC; - $lng = $DIC->language(); - - return array( - self::MODULE_SCORM => $lng->txt("style_page_layout_module_scorm"), - self::MODULE_PORTFOLIO => $lng->txt("style_page_layout_module_portfolio") - ); - } + $lng = $DIC->language(); + + return array( + self::MODULE_SCORM => $lng->txt("style_page_layout_module_scorm"), + self::MODULE_PORTFOLIO => $lng->txt("style_page_layout_module_portfolio") + ); + } } - -?> \ No newline at end of file diff --git a/Services/COPage/Layout/classes/class.ilPageLayoutAdministrationGUI.php b/Services/COPage/Layout/classes/class.ilPageLayoutAdministrationGUI.php index 6925ceba02bc8cccd4dc4dae525eec24cb0c4d0a..b068ede872212fe5db5c87452821fccf44edf64e 100644 --- a/Services/COPage/Layout/classes/class.ilPageLayoutAdministrationGUI.php +++ b/Services/COPage/Layout/classes/class.ilPageLayoutAdministrationGUI.php @@ -12,530 +12,505 @@ */ class ilPageLayoutAdministrationGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ILIAS\DI\Container - */ - protected $DIC; - - /** - * @var int - */ - protected $ref_id; - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->dic = $DIC; - $this->ctrl = $DIC->ctrl(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->toolbar = $DIC->toolbar(); - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - $this->ref_id = (int) $_GET["ref_id"]; - $this->tabs = $DIC["ilTabs"]; - - - include_once("./Services/Style/Content/classes/class.ilContentStyleSettings.php"); - $this->settings = new ilContentStyleSettings(); - } - - /** - * Execute command - */ - function executeCommand() - { - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd("listLayouts"); - - if ($cmd == "listLayouts") - { - $this->checkPermission("read"); - } - else - { - $this->checkPermission("sty_write_page_layout"); - } - - switch ($next_class) - { - case 'ilpagelayoutgui': - $this->tabs->clearTargets(); - include_once("./Services/COPage/Layout/classes/class.ilPageLayoutGUI.php"); + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ILIAS\DI\Container + */ + protected $DIC; + + /** + * @var int + */ + protected $ref_id; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->dic = $DIC; + $this->ctrl = $DIC->ctrl(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->toolbar = $DIC->toolbar(); + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + $this->ref_id = (int) $_GET["ref_id"]; + $this->tabs = $DIC["ilTabs"]; + + + include_once("./Services/Style/Content/classes/class.ilContentStyleSettings.php"); + $this->settings = new ilContentStyleSettings(); + } + + /** + * Execute command + */ + public function executeCommand() + { + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd("listLayouts"); + + if ($cmd == "listLayouts") { + $this->checkPermission("read"); + } else { + $this->checkPermission("sty_write_page_layout"); + } + + switch ($next_class) { + case 'ilpagelayoutgui': + $this->tabs->clearTargets(); + include_once("./Services/COPage/Layout/classes/class.ilPageLayoutGUI.php"); // $this->tpl->getStandardTemplate(); - $this->tabs->setBackTarget($this->lng->txt("page_layouts"), - $this->ctrl->getLinkTarget($this, "listLayouts")); - - $this->ctrl->setReturn($this, "listLayouts"); - if ($this->pg_id!=null) { - $layout_gui = new ilPageLayoutGUI("stys", $this->pg_id); - } else { - $layout_gui = new ilPageLayoutGUI("stys", $_GET["obj_id"]); - } - $layout_gui->setTabs(); - $layout_gui->setEditPreview(true); - $this->ctrl->saveParameter($this, "obj_id"); - $ret = $this->ctrl->forwardCommand($layout_gui); - $this->tpl->setContent($ret); - break; - - default: - if (in_array($cmd, array("listLayouts", "editPg", "addPageLayout", "cancelCreate", "createPg", "exportLayout", - "savePageLayoutTypes", "activate", "deactivate", "importPageLayoutForm", "deletePgl", "cancelDeletePg", - "confirmedDeletePg", "importPageLayout"))) - { - $this->$cmd(); - } - else - { - die("Unknown command ".$cmd); - } - } - } - - /** - * Check permission - * - * @param string $a_perm permission(s) - * @return bool - * @throws ilObjectException - */ - function checkPermission($a_perm, $a_throw_exc = true) - { - if (!$this->rbacsystem->checkAccess($a_perm, $this->ref_id)) - { - if ($a_throw_exc) - { - include_once "Services/Object/exceptions/class.ilObjectException.php"; - throw new ilObjectException($this->lng->txt("permission_denied")); - } - return false; - } - return true; - } - - /** - * view list of page layouts - */ - function listLayouts() - { - // show toolbar, if write permission is given - if ($this->checkPermission("sty_write_page_layout", false)) - { - $this->toolbar->addButton($this->lng->txt("sty_add_pgl"), - $this->ctrl->getLinkTarget($this, "addPageLayout")); - $this->toolbar->addButton($this->lng->txt("sty_import_page_layout"), - $this->ctrl->getLinkTarget($this, "importPageLayoutForm")); - } - - $oa_tpl = new ilTemplate("tpl.stys_pglayout.html", true, true, "Services/COPage/Layout"); - - include_once("./Services/COPage/Layout/classes/class.ilPageLayoutTableGUI.php"); - $pglayout_table = new ilPageLayoutTableGUI($this, "listLayouts"); - $oa_tpl->setVariable("PGLAYOUT_TABLE", $pglayout_table->getHTML()); - $this->tpl->setContent($oa_tpl->get()); - - } - - /** - * Activate layout - * - * @param bool $a_activate - */ - function activate($a_activate=true) - { - if (!isset($_POST["pglayout"])) - { - ilUtil::sendInfo($this->lng->txt("no_checkbox"),true); - } - else - { - ilUtil::sendSuccess($this->lng->txt("sty_opt_saved"),true); - foreach ($_POST["pglayout"] as $item) - { - $pg_layout = new ilPageLayout($item); - $pg_layout->activate($a_activate); - } - } - $this->ctrl->redirect($this, "listLayouts"); - } - - /** - * Deactivate layout - */ - function deactivate() - { - $this->activate(false); - } - - /** - * display deletion confirmation screen - */ - function deletePgl() - { - if(!isset($_POST["pglayout"])) - { - ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); - $this->ctrl->redirect($this, "listLayouts"); - } - - unset($this->data); - - // display confirmation message - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($this->ctrl->getFormAction($this)); - $cgui->setHeaderText($this->lng->txt("info_delete_sure")); - $cgui->setCancel($this->lng->txt("cancel"), "cancelDeletePg"); - $cgui->setConfirm($this->lng->txt("confirm"), "confirmedDeletePg"); - - foreach($_POST["pglayout"] as $id) - { - $pg_obj = new ilPageLayout($id); - $pg_obj->readObject(); - - $caption = ilUtil::getImageTagByType("stys", $this->tpl->tplPath). - " ".$pg_obj->getTitle(); - - $cgui->addItem("pglayout[]", $id, $caption); - } - - $this->tpl->setContent($cgui->getHTML()); - } - - /** - * cancel deletion of Page Layout - */ - function cancelDeletePg() - { - ilUtil::sendInfo($this->lng->txt("msg_cancel"),true); - $this->ctrl->redirect($this, "listLayouts"); - } - - /** - * conform deletion of Page Layout - */ - function confirmedDeletePg() - { - foreach ($_POST["pglayout"] as $id) - { - $pg_obj = new ilPageLayout($id); - $pg_obj->delete(); - } - - $this->ctrl->redirect($this, "listLayouts"); - } - - /** - * @param null|ilPropertyFormGUI $a_form - */ - function addPageLayout($a_form = null) - { - if(!$a_form) - { - $a_form = $this->initAddPageLayoutForm(); - } - - $this->tpl->setContent($a_form->getHTML()); - } - - /** - * @return ilPropertyFormGUI - */ - function initAddPageLayoutForm() - { - $this->lng->loadLanguageModule("content"); - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form_gui = new ilPropertyFormGUI(); - $form_gui->setFormAction($this->ctrl->getFormAction($this)); - $form_gui->setTitle($this->lng->txt("sty_create_pgl")); - - $title_input = new ilTextInputGUI($this->lng->txt("title"),"pgl_title"); - $title_input->setSize(50); - $title_input->setMaxLength(128); - $title_input->setValue($this->layout_object->title); - $title_input->setTitle($this->lng->txt("title")); - $title_input->setRequired(true); - - $desc_input = new ilTextAreaInputGUI($this->lng->txt("description"),"pgl_desc"); - $desc_input->setValue($this->layout_object->description); - $desc_input->setRows(3); - $desc_input->setCols(37); - - // special page? - $options = array( - "0" => $this->lng->txt("cont_layout_template"), - "1" => $this->lng->txt("cont_special_page"), - ); - $si = new ilSelectInputGUI($this->lng->txt("type"), "special_page"); - $si->setOptions($options); - - // modules - $mods = new ilCheckboxGroupInputGUI($this->lng->txt("modules"), "module"); - // $mods->setRequired(true); - foreach(ilPageLayout::getAvailableModules() as $mod_id => $mod_caption) - { - $mod = new ilCheckboxOption($mod_caption, $mod_id); - $mods->addOption($mod); - } - - $ttype_input = new ilSelectInputGUI($this->lng->txt("sty_based_on"), "pgl_template"); - - $arr_templates = ilPageLayout::getLayouts(); - $arr_templates1 = ilPageLayout::getLayouts(false, true); - foreach ($arr_templates1 as $v) - { - $arr_templates[] = $v; - } - - $options = array(); - $options['-1'] = $this->lng->txt("none"); - - foreach ($arr_templates as $templ) { - $templ->readObject(); - $key = $templ->getId(); - $value = $templ->getTitle(); - $options[$key] = $value; - } - - $ttype_input->setOptions($options); - $ttype_input->setValue(-1); - $ttype_input->setRequired(true); - - $desc_input->setTitle($this->lng->txt("description")); - $desc_input->setRequired(false); - - $form_gui->addItem($title_input); - $form_gui->addItem($desc_input); - $form_gui->addItem($si); - $form_gui->addItem($mods); - $form_gui->addItem($ttype_input); - - - $form_gui->addCommandButton("createPg", $this->lng->txt("save")); - $form_gui->addCommandButton("cancelCreate", $this->lng->txt("cancel")); - - return $form_gui; - } - - - function createPg() - { - $form_gui = $this->initAddPageLayoutForm(); - if(!$form_gui->checkInput()) - { - $form_gui->setValuesByPost(); - $this->addPageLayout($form_gui); - return; - } - - //create Page-Layout-Object first - $pg_object = new ilPageLayout(); - $pg_object->setTitle($form_gui->getInput('pgl_title')); - $pg_object->setDescription($form_gui->getInput('pgl_desc')); - $pg_object->setSpecialPage($form_gui->getInput('special_page')); - $pg_object->setModules($form_gui->getInput('module')); - $pg_object->update(); - - include_once("./Services/COPage/Layout/classes/class.ilPageLayoutPage.php"); - - //create Page - if(!is_object($pg_content)) - { - $this->pg_content = new ilPageLayoutPage(); - } - - $this->pg_content->setId($pg_object->getId()); - - $tmpl = $form_gui->getInput('pgl_template'); - if ($tmpl != "-1") - { - $layout_obj = new ilPageLayout($tmpl); - $this->pg_content->setXMLContent($layout_obj->getXMLContent()); - $this->pg_content->create(false); - } - else - { - $this->pg_content->create(false); - } - - $this->ctrl->setParameterByClass("ilpagelayoutgui", "obj_id", $pg_object->getId()); - $this->ctrl->redirectByClass("ilpagelayoutgui", "edit"); - } - - /** - * Cancel creation - */ - function cancelCreate() - { - $this->listLayouts(); - } - - /** - * Edit page - */ - function editPg() - { - $this->checkPermission("sty_write_page_layout"); - - $this->ctrl->setCmdClass("ilpagelayoutgui"); - $this->ctrl->setCmd("edit"); - $this->executeCommand(); - } - - /** - * Save page layout types - */ - function savePageLayoutTypes() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("./Services/COPage/Layout/classes/class.ilPageLayout.php"); - - if (is_array($_POST["type"])) - { - foreach($_POST["type"] as $id => $t) - { - if ($id > 0) - { - $l = new ilPageLayout($id); - $l->readObject(); - $l->setSpecialPage($t); - if(is_array($_POST["module"][$id])) - { - $l->setModules(array_keys($_POST["module"][$id])); - } - else - { - $l->setModules(); - } - $l->update(); - } - } - - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified")); - } - - $this->ctrl->redirect($this, "listLayouts"); - } - - - /** - * Export page layout template object - */ - function exportLayout() - { - include_once("./Services/Export/classes/class.ilExport.php"); - $exp = new ilExport(); - - $tmpdir = ilUtil::ilTempnam(); - ilUtil::makeDir($tmpdir); - - $succ = $exp->exportEntity("pgtp", (int) $_GET["layout_id"], "4.2.0", - "Services/COPage", "Title", $tmpdir); - - if ($succ["success"]) - { - ilUtil::deliverFile($succ["directory"]."/".$succ["file"], $succ["file"], - "", false, false, false); - } - if (is_file($succ["directory"]."/".$succ["file"])) - { - unlink($succ["directory"]."/".$succ["file"]); - } - if (is_dir($succ["directory"])) - { - unlink($succ["directory"]); - } - } - - /** - * Import page layout - */ - function importPageLayoutForm() - { - $form = $this->initPageLayoutImportForm(); - $this->tpl->setContent($form->getHTML()); - } - - /** - * Init page layout import form. - */ - public function initPageLayoutImportForm() - { - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - - // template file - $fi = new ilFileInputGUI($this->lng->txt("file"), "file"); - $fi->setSuffixes(array("zip")); - $fi->setRequired(true); - $form->addItem($fi); - - $form->addCommandButton("importPageLayout", $this->lng->txt("import")); - $form->addCommandButton("listLayouts", $this->lng->txt("cancel")); - - $form->setTitle($this->lng->txt("sty_import_page_layout")); - $form->setFormAction($this->ctrl->getFormAction($this)); - - return $form; - } - - /** - * Import page layout - */ - public function importPageLayout() - { - $form = $this->initPageLayoutImportForm(); - if ($form->checkInput()) - { - include_once("./Services/COPage/Layout/classes/class.ilPageLayout.php"); - $pg = ilPageLayout::import($_FILES["file"]["name"], $_FILES["file"]["tmp_name"]); - if ($pg > 0) - { - ilUtil::sendSuccess($this->lng->txt("sty_imported_layout"), true); - } - $this->ctrl->redirect($this, "listLayouts"); - } - else - { - $form->setValuesByPost(); - $this->tpl->setContent($form->getHtml()); - } - } - - + $this->tabs->setBackTarget( + $this->lng->txt("page_layouts"), + $this->ctrl->getLinkTarget($this, "listLayouts") + ); + + $this->ctrl->setReturn($this, "listLayouts"); + if ($this->pg_id!=null) { + $layout_gui = new ilPageLayoutGUI("stys", $this->pg_id); + } else { + $layout_gui = new ilPageLayoutGUI("stys", $_GET["obj_id"]); + } + $layout_gui->setTabs(); + $layout_gui->setEditPreview(true); + $this->ctrl->saveParameter($this, "obj_id"); + $ret = $this->ctrl->forwardCommand($layout_gui); + $this->tpl->setContent($ret); + break; + + default: + if (in_array($cmd, array("listLayouts", "editPg", "addPageLayout", "cancelCreate", "createPg", "exportLayout", + "savePageLayoutTypes", "activate", "deactivate", "importPageLayoutForm", "deletePgl", "cancelDeletePg", + "confirmedDeletePg", "importPageLayout"))) { + $this->$cmd(); + } else { + die("Unknown command " . $cmd); + } + } + } + + /** + * Check permission + * + * @param string $a_perm permission(s) + * @return bool + * @throws ilObjectException + */ + public function checkPermission($a_perm, $a_throw_exc = true) + { + if (!$this->rbacsystem->checkAccess($a_perm, $this->ref_id)) { + if ($a_throw_exc) { + include_once "Services/Object/exceptions/class.ilObjectException.php"; + throw new ilObjectException($this->lng->txt("permission_denied")); + } + return false; + } + return true; + } + + /** + * view list of page layouts + */ + public function listLayouts() + { + // show toolbar, if write permission is given + if ($this->checkPermission("sty_write_page_layout", false)) { + $this->toolbar->addButton( + $this->lng->txt("sty_add_pgl"), + $this->ctrl->getLinkTarget($this, "addPageLayout") + ); + $this->toolbar->addButton( + $this->lng->txt("sty_import_page_layout"), + $this->ctrl->getLinkTarget($this, "importPageLayoutForm") + ); + } + + $oa_tpl = new ilTemplate("tpl.stys_pglayout.html", true, true, "Services/COPage/Layout"); + + include_once("./Services/COPage/Layout/classes/class.ilPageLayoutTableGUI.php"); + $pglayout_table = new ilPageLayoutTableGUI($this, "listLayouts"); + $oa_tpl->setVariable("PGLAYOUT_TABLE", $pglayout_table->getHTML()); + $this->tpl->setContent($oa_tpl->get()); + } + + /** + * Activate layout + * + * @param bool $a_activate + */ + public function activate($a_activate=true) + { + if (!isset($_POST["pglayout"])) { + ilUtil::sendInfo($this->lng->txt("no_checkbox"), true); + } else { + ilUtil::sendSuccess($this->lng->txt("sty_opt_saved"), true); + foreach ($_POST["pglayout"] as $item) { + $pg_layout = new ilPageLayout($item); + $pg_layout->activate($a_activate); + } + } + $this->ctrl->redirect($this, "listLayouts"); + } + + /** + * Deactivate layout + */ + public function deactivate() + { + $this->activate(false); + } + + /** + * display deletion confirmation screen + */ + public function deletePgl() + { + if (!isset($_POST["pglayout"])) { + ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); + $this->ctrl->redirect($this, "listLayouts"); + } + + unset($this->data); + + // display confirmation message + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($this->ctrl->getFormAction($this)); + $cgui->setHeaderText($this->lng->txt("info_delete_sure")); + $cgui->setCancel($this->lng->txt("cancel"), "cancelDeletePg"); + $cgui->setConfirm($this->lng->txt("confirm"), "confirmedDeletePg"); + + foreach ($_POST["pglayout"] as $id) { + $pg_obj = new ilPageLayout($id); + $pg_obj->readObject(); + + $caption = ilUtil::getImageTagByType("stys", $this->tpl->tplPath) . + " " . $pg_obj->getTitle(); + + $cgui->addItem("pglayout[]", $id, $caption); + } + + $this->tpl->setContent($cgui->getHTML()); + } + + /** + * cancel deletion of Page Layout + */ + public function cancelDeletePg() + { + ilUtil::sendInfo($this->lng->txt("msg_cancel"), true); + $this->ctrl->redirect($this, "listLayouts"); + } + + /** + * conform deletion of Page Layout + */ + public function confirmedDeletePg() + { + foreach ($_POST["pglayout"] as $id) { + $pg_obj = new ilPageLayout($id); + $pg_obj->delete(); + } + + $this->ctrl->redirect($this, "listLayouts"); + } + + /** + * @param null|ilPropertyFormGUI $a_form + */ + public function addPageLayout($a_form = null) + { + if (!$a_form) { + $a_form = $this->initAddPageLayoutForm(); + } + + $this->tpl->setContent($a_form->getHTML()); + } + + /** + * @return ilPropertyFormGUI + */ + public function initAddPageLayoutForm() + { + $this->lng->loadLanguageModule("content"); + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form_gui = new ilPropertyFormGUI(); + $form_gui->setFormAction($this->ctrl->getFormAction($this)); + $form_gui->setTitle($this->lng->txt("sty_create_pgl")); + + $title_input = new ilTextInputGUI($this->lng->txt("title"), "pgl_title"); + $title_input->setSize(50); + $title_input->setMaxLength(128); + $title_input->setValue($this->layout_object->title); + $title_input->setTitle($this->lng->txt("title")); + $title_input->setRequired(true); + + $desc_input = new ilTextAreaInputGUI($this->lng->txt("description"), "pgl_desc"); + $desc_input->setValue($this->layout_object->description); + $desc_input->setRows(3); + $desc_input->setCols(37); + + // special page? + $options = array( + "0" => $this->lng->txt("cont_layout_template"), + "1" => $this->lng->txt("cont_special_page"), + ); + $si = new ilSelectInputGUI($this->lng->txt("type"), "special_page"); + $si->setOptions($options); + + // modules + $mods = new ilCheckboxGroupInputGUI($this->lng->txt("modules"), "module"); + // $mods->setRequired(true); + foreach (ilPageLayout::getAvailableModules() as $mod_id => $mod_caption) { + $mod = new ilCheckboxOption($mod_caption, $mod_id); + $mods->addOption($mod); + } + + $ttype_input = new ilSelectInputGUI($this->lng->txt("sty_based_on"), "pgl_template"); + + $arr_templates = ilPageLayout::getLayouts(); + $arr_templates1 = ilPageLayout::getLayouts(false, true); + foreach ($arr_templates1 as $v) { + $arr_templates[] = $v; + } + + $options = array(); + $options['-1'] = $this->lng->txt("none"); + + foreach ($arr_templates as $templ) { + $templ->readObject(); + $key = $templ->getId(); + $value = $templ->getTitle(); + $options[$key] = $value; + } + + $ttype_input->setOptions($options); + $ttype_input->setValue(-1); + $ttype_input->setRequired(true); + + $desc_input->setTitle($this->lng->txt("description")); + $desc_input->setRequired(false); + + $form_gui->addItem($title_input); + $form_gui->addItem($desc_input); + $form_gui->addItem($si); + $form_gui->addItem($mods); + $form_gui->addItem($ttype_input); + + + $form_gui->addCommandButton("createPg", $this->lng->txt("save")); + $form_gui->addCommandButton("cancelCreate", $this->lng->txt("cancel")); + + return $form_gui; + } + + + public function createPg() + { + $form_gui = $this->initAddPageLayoutForm(); + if (!$form_gui->checkInput()) { + $form_gui->setValuesByPost(); + $this->addPageLayout($form_gui); + return; + } + + //create Page-Layout-Object first + $pg_object = new ilPageLayout(); + $pg_object->setTitle($form_gui->getInput('pgl_title')); + $pg_object->setDescription($form_gui->getInput('pgl_desc')); + $pg_object->setSpecialPage($form_gui->getInput('special_page')); + $pg_object->setModules($form_gui->getInput('module')); + $pg_object->update(); + + include_once("./Services/COPage/Layout/classes/class.ilPageLayoutPage.php"); + + //create Page + if (!is_object($pg_content)) { + $this->pg_content = new ilPageLayoutPage(); + } + + $this->pg_content->setId($pg_object->getId()); + + $tmpl = $form_gui->getInput('pgl_template'); + if ($tmpl != "-1") { + $layout_obj = new ilPageLayout($tmpl); + $this->pg_content->setXMLContent($layout_obj->getXMLContent()); + $this->pg_content->create(false); + } else { + $this->pg_content->create(false); + } + + $this->ctrl->setParameterByClass("ilpagelayoutgui", "obj_id", $pg_object->getId()); + $this->ctrl->redirectByClass("ilpagelayoutgui", "edit"); + } + + /** + * Cancel creation + */ + public function cancelCreate() + { + $this->listLayouts(); + } + + /** + * Edit page + */ + public function editPg() + { + $this->checkPermission("sty_write_page_layout"); + + $this->ctrl->setCmdClass("ilpagelayoutgui"); + $this->ctrl->setCmd("edit"); + $this->executeCommand(); + } + + /** + * Save page layout types + */ + public function savePageLayoutTypes() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("./Services/COPage/Layout/classes/class.ilPageLayout.php"); + + if (is_array($_POST["type"])) { + foreach ($_POST["type"] as $id => $t) { + if ($id > 0) { + $l = new ilPageLayout($id); + $l->readObject(); + $l->setSpecialPage($t); + if (is_array($_POST["module"][$id])) { + $l->setModules(array_keys($_POST["module"][$id])); + } else { + $l->setModules(); + } + $l->update(); + } + } + + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified")); + } + + $this->ctrl->redirect($this, "listLayouts"); + } + + + /** + * Export page layout template object + */ + public function exportLayout() + { + include_once("./Services/Export/classes/class.ilExport.php"); + $exp = new ilExport(); + + $tmpdir = ilUtil::ilTempnam(); + ilUtil::makeDir($tmpdir); + + $succ = $exp->exportEntity( + "pgtp", + (int) $_GET["layout_id"], + "4.2.0", + "Services/COPage", + "Title", + $tmpdir + ); + + if ($succ["success"]) { + ilUtil::deliverFile( + $succ["directory"] . "/" . $succ["file"], + $succ["file"], + "", + false, + false, + false + ); + } + if (is_file($succ["directory"] . "/" . $succ["file"])) { + unlink($succ["directory"] . "/" . $succ["file"]); + } + if (is_dir($succ["directory"])) { + unlink($succ["directory"]); + } + } + + /** + * Import page layout + */ + public function importPageLayoutForm() + { + $form = $this->initPageLayoutImportForm(); + $this->tpl->setContent($form->getHTML()); + } + + /** + * Init page layout import form. + */ + public function initPageLayoutImportForm() + { + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + + // template file + $fi = new ilFileInputGUI($this->lng->txt("file"), "file"); + $fi->setSuffixes(array("zip")); + $fi->setRequired(true); + $form->addItem($fi); + + $form->addCommandButton("importPageLayout", $this->lng->txt("import")); + $form->addCommandButton("listLayouts", $this->lng->txt("cancel")); + + $form->setTitle($this->lng->txt("sty_import_page_layout")); + $form->setFormAction($this->ctrl->getFormAction($this)); + + return $form; + } + + /** + * Import page layout + */ + public function importPageLayout() + { + $form = $this->initPageLayoutImportForm(); + if ($form->checkInput()) { + include_once("./Services/COPage/Layout/classes/class.ilPageLayout.php"); + $pg = ilPageLayout::import($_FILES["file"]["name"], $_FILES["file"]["tmp_name"]); + if ($pg > 0) { + ilUtil::sendSuccess($this->lng->txt("sty_imported_layout"), true); + } + $this->ctrl->redirect($this, "listLayouts"); + } else { + $form->setValuesByPost(); + $this->tpl->setContent($form->getHtml()); + } + } } - -?> \ No newline at end of file diff --git a/Services/COPage/Layout/classes/class.ilPageLayoutGUI.php b/Services/COPage/Layout/classes/class.ilPageLayoutGUI.php index 07856e99b281eff12bf81f002325bd6d1909a11f..c54de7bf4ac35a691924b398e46e3c69aa849903 100755 --- a/Services/COPage/Layout/classes/class.ilPageLayoutGUI.php +++ b/Services/COPage/Layout/classes/class.ilPageLayoutGUI.php @@ -6,8 +6,8 @@ include_once("./Modules/Scorm2004/classes/class.ilSCORM2004Page.php"); /** * Class ilPageLayoutGUI GUI class -* -* @author Hendrik Holtmann +* +* @author Hendrik Holtmann * @version $Id$ * * @ilCtrl_Calls ilPageLayoutGUI: ilPageEditorGUI, ilEditClipboardGUI @@ -16,221 +16,222 @@ include_once("./Modules/Scorm2004/classes/class.ilSCORM2004Page.php"); */ class ilPageLayoutGUI extends ilPageObjectGUI { - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilSetting - */ - protected $settings; - - protected $layout_object = null; - - - /** - * Constructor - */ - function __construct($a_parent_type, $a_id = 0, $a_old_nr = 0, $a_prevent_get_id = false, $a_lang = "") - { - global $DIC; - - $this->tpl = $DIC["tpl"]; - $this->ctrl = $DIC->ctrl(); - $this->tabs = $DIC->tabs(); - $this->lng = $DIC->language(); - $this->settings = $DIC->settings(); - $tpl = $DIC["tpl"]; - - parent::__construct($a_parent_type, $a_id, $a_old_nr, $a_prevent_get_id, $a_lang); - - //associated object - include_once("./Services/COPage/Layout/classes/class.ilPageLayout.php"); - - $this->layout_object = new ilPageLayout($a_id); - $this->layout_object->readObject(); - - // content style - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $tpl->setCurrentBlock("ContentStyle"); - $tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->layout_object->getStyleId())); - $tpl->parseCurrentBlock(); - - $tpl->setCurrentBlock("SyntaxStyle"); - $tpl->setVariable("LOCATION_SYNTAX_STYLESHEET", - ilObjStyleSheet::getSyntaxStylePath()); - $tpl->setVariable("LOCATION_ADDITIONAL_STYLESHEET", - ilObjStyleSheet::getPlaceHolderStylePath()); - $tpl->parseCurrentBlock(); - - $this->setStyleId($this->layout_object->getStyleId()); - - } - - /** - * execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - switch($next_class) - { - case 'ilmdeditorgui': - return parent::executeCommand(); - break; - - case "ilpageobjectgui": + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilSetting + */ + protected $settings; + + protected $layout_object = null; + + + /** + * Constructor + */ + public function __construct($a_parent_type, $a_id = 0, $a_old_nr = 0, $a_prevent_get_id = false, $a_lang = "") + { + global $DIC; + + $this->tpl = $DIC["tpl"]; + $this->ctrl = $DIC->ctrl(); + $this->tabs = $DIC->tabs(); + $this->lng = $DIC->language(); + $this->settings = $DIC->settings(); + $tpl = $DIC["tpl"]; + + parent::__construct($a_parent_type, $a_id, $a_old_nr, $a_prevent_get_id, $a_lang); + + //associated object + include_once("./Services/COPage/Layout/classes/class.ilPageLayout.php"); + + $this->layout_object = new ilPageLayout($a_id); + $this->layout_object->readObject(); + + // content style + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $tpl->setCurrentBlock("ContentStyle"); + $tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath($this->layout_object->getStyleId()) + ); + $tpl->parseCurrentBlock(); + + $tpl->setCurrentBlock("SyntaxStyle"); + $tpl->setVariable( + "LOCATION_SYNTAX_STYLESHEET", + ilObjStyleSheet::getSyntaxStylePath() + ); + $tpl->setVariable( + "LOCATION_ADDITIONAL_STYLESHEET", + ilObjStyleSheet::getPlaceHolderStylePath() + ); + $tpl->parseCurrentBlock(); + + $this->setStyleId($this->layout_object->getStyleId()); + } + + /** + * execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + switch ($next_class) { + case 'ilmdeditorgui': + return parent::executeCommand(); + break; + + case "ilpageobjectgui": die("ilPageLayoutGUI forward to ilpageobjectgui error."); - return; - - default: - $html = parent::executeCommand(); - return $html; - } - } - - function create(){ - $this->properties("insert"); - } - - /** - * Edit page layout properties - * - * @param string $a_mode edit mode - */ - function properties($a_mode="save", $a_form = null) - { - $ilTabs = $this->tabs; - - $ilTabs->setTabActive('properties'); - - if(!$a_form) - { - $a_form = $this->initForm($a_mode); - } - - $this->tpl->setContent($a_form->getHTML()); - } - - function initForm($a_mode) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilSetting = $this->settings; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form_gui = new ilPropertyFormGUI(); - $form_gui->setFormAction($ilCtrl->getFormAction($this)); - $form_gui->setTitle($lng->txt("cont_ed_pglprop")); - - // title - $title_input = new ilTextInputGUI($lng->txt("title"),"pgl_title"); - $title_input->setSize(50); - $title_input->setMaxLength(128); - $title_input->setValue($this->layout_object->title); - $title_input->setTitle($lng->txt("title")); - $title_input->setRequired(true); - - // description - $desc_input = new ilTextAreaInputGUI($lng->txt("description"),"pgl_desc"); - $desc_input->setValue($this->layout_object->description); - $desc_input->setRows(3); - $desc_input->setCols(37); - $desc_input->setTitle($lng->txt("description")); - $desc_input->setRequired(false); - - // modules - $mods = new ilCheckboxGroupInputGUI($this->lng->txt("modules"), "module"); - // $mods->setRequired(true); - $mods->setValue($this->layout_object->getModules()); - foreach(ilPageLayout::getAvailableModules() as $mod_id => $mod_caption) - { - $mod = new ilCheckboxOption($mod_caption, $mod_id); - $mods->addOption($mod); - } - - $form_gui->addItem($title_input); - $form_gui->addItem($desc_input); - $form_gui->addItem($mods); - - // style - $fixed_style = $ilSetting->get("fixed_content_style_id"); - $style_id = $this->layout_object->getStyleId(); - - if ($fixed_style > 0) - { - $st = new ilNonEditableValueGUI($lng->txt("cont_current_style")); - $st->setValue(ilObject::_lookupTitle($fixed_style)." (". - $this->lng->txt("global_fixed").")"); - $form_gui->addItem($st); - } - else - { - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $st_styles = ilObjStyleSheet::_getStandardStyles(true, false); - $st_styles[0] = $this->lng->txt("default"); - ksort($st_styles); - $style_sel = new ilSelectInputGUI($lng->txt("obj_sty"), "style_id"); - $style_sel->setOptions($st_styles); - $style_sel->setValue($style_id); - $form_gui->addItem($style_sel); - } - - $form_gui->addCommandButton("updateProperties", $lng->txt($a_mode)); - - return $form_gui; - } - - /** - * Update properties - */ - function updateProperties() - { - $lng = $this->lng; - - $form = $this->initForm("save"); - if(!$form->checkInput()) - { - $form->setValuesByPost(); - return $this->properties("save", $form); - } - - $this->layout_object->setTitle($form->getInput('pgl_title')); - $this->layout_object->setDescription($form->getInput('pgl_desc')); - $this->layout_object->setStyleId($form->getInput('style_id')); - $this->layout_object->setModules($form->getInput('module')); - $this->layout_object->update(); - - ilUtil::sendInfo($lng->txt("saved_successfully")); - $this->properties(); - } - - /** - * output tabs - */ - function setTabs($a_tabs = "") - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - $ilCtrl->setParameterByClass("ilpagelayoutgui", "obj_id", $this->obj->getId()); - $ilTabs->addTarget("properties", - $ilCtrl->getLinkTarget($this, "properties"), array("properties","", ""), "", ""); - $tpl->setTitleIcon(ilUtil::getImagePath("icon_pg.svg")); - $tpl->setTitle($this->layout_object->getTitle()); - $tpl->setDescription(""); - // $tpl->setTitle( - // $lng->txt("sahs_page").": ".$this->node_object->getTitle()); - } - - + return; + + default: + $html = parent::executeCommand(); + return $html; + } + } + + public function create() + { + $this->properties("insert"); + } + + /** + * Edit page layout properties + * + * @param string $a_mode edit mode + */ + public function properties($a_mode="save", $a_form = null) + { + $ilTabs = $this->tabs; + + $ilTabs->setTabActive('properties'); + + if (!$a_form) { + $a_form = $this->initForm($a_mode); + } + + $this->tpl->setContent($a_form->getHTML()); + } + + public function initForm($a_mode) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilSetting = $this->settings; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form_gui = new ilPropertyFormGUI(); + $form_gui->setFormAction($ilCtrl->getFormAction($this)); + $form_gui->setTitle($lng->txt("cont_ed_pglprop")); + + // title + $title_input = new ilTextInputGUI($lng->txt("title"), "pgl_title"); + $title_input->setSize(50); + $title_input->setMaxLength(128); + $title_input->setValue($this->layout_object->title); + $title_input->setTitle($lng->txt("title")); + $title_input->setRequired(true); + + // description + $desc_input = new ilTextAreaInputGUI($lng->txt("description"), "pgl_desc"); + $desc_input->setValue($this->layout_object->description); + $desc_input->setRows(3); + $desc_input->setCols(37); + $desc_input->setTitle($lng->txt("description")); + $desc_input->setRequired(false); + + // modules + $mods = new ilCheckboxGroupInputGUI($this->lng->txt("modules"), "module"); + // $mods->setRequired(true); + $mods->setValue($this->layout_object->getModules()); + foreach (ilPageLayout::getAvailableModules() as $mod_id => $mod_caption) { + $mod = new ilCheckboxOption($mod_caption, $mod_id); + $mods->addOption($mod); + } + + $form_gui->addItem($title_input); + $form_gui->addItem($desc_input); + $form_gui->addItem($mods); + + // style + $fixed_style = $ilSetting->get("fixed_content_style_id"); + $style_id = $this->layout_object->getStyleId(); + + if ($fixed_style > 0) { + $st = new ilNonEditableValueGUI($lng->txt("cont_current_style")); + $st->setValue(ilObject::_lookupTitle($fixed_style) . " (" . + $this->lng->txt("global_fixed") . ")"); + $form_gui->addItem($st); + } else { + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $st_styles = ilObjStyleSheet::_getStandardStyles(true, false); + $st_styles[0] = $this->lng->txt("default"); + ksort($st_styles); + $style_sel = new ilSelectInputGUI($lng->txt("obj_sty"), "style_id"); + $style_sel->setOptions($st_styles); + $style_sel->setValue($style_id); + $form_gui->addItem($style_sel); + } + + $form_gui->addCommandButton("updateProperties", $lng->txt($a_mode)); + + return $form_gui; + } + + /** + * Update properties + */ + public function updateProperties() + { + $lng = $this->lng; + + $form = $this->initForm("save"); + if (!$form->checkInput()) { + $form->setValuesByPost(); + return $this->properties("save", $form); + } + + $this->layout_object->setTitle($form->getInput('pgl_title')); + $this->layout_object->setDescription($form->getInput('pgl_desc')); + $this->layout_object->setStyleId($form->getInput('style_id')); + $this->layout_object->setModules($form->getInput('module')); + $this->layout_object->update(); + + ilUtil::sendInfo($lng->txt("saved_successfully")); + $this->properties(); + } + + /** + * output tabs + */ + public function setTabs($a_tabs = "") + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + $ilCtrl->setParameterByClass("ilpagelayoutgui", "obj_id", $this->obj->getId()); + $ilTabs->addTarget( + "properties", + $ilCtrl->getLinkTarget($this, "properties"), + array("properties","", ""), + "", + "" + ); + $tpl->setTitleIcon(ilUtil::getImagePath("icon_pg.svg")); + $tpl->setTitle($this->layout_object->getTitle()); + $tpl->setDescription(""); + // $tpl->setTitle( + // $lng->txt("sahs_page").": ".$this->node_object->getTitle()); + } } -?> diff --git a/Services/COPage/Layout/classes/class.ilPageLayoutPage.php b/Services/COPage/Layout/classes/class.ilPageLayoutPage.php index 93460d066f8b537ec4bbe68e45e67adf59b87271..e978a9dd502bba689ef811e11b09c6f54d2373f1 100755 --- a/Services/COPage/Layout/classes/class.ilPageLayoutPage.php +++ b/Services/COPage/Layout/classes/class.ilPageLayoutPage.php @@ -5,22 +5,21 @@ include_once("./Services/COPage/classes/class.ilPageObject.php"); /** * Page layout page object - * - * @author Alex Killing + * + * @author Alex Killing * @version $Id$ * * @ingroup ServicesStyle */ class ilPageLayoutPage extends ilPageObject { - /** - * Get parent type - * - * @return string parent type - */ - function getParentType() - { - return "stys"; - } + /** + * Get parent type + * + * @return string parent type + */ + public function getParentType() + { + return "stys"; + } } -?> diff --git a/Services/COPage/Layout/classes/class.ilPageLayoutPageConfig.php b/Services/COPage/Layout/classes/class.ilPageLayoutPageConfig.php index 382e84596ee0462e23c9c91648f202fe93ba89f9..d4db3aa82c077a2dec435eb65b3f5721b15e3ab4 100644 --- a/Services/COPage/Layout/classes/class.ilPageLayoutPageConfig.php +++ b/Services/COPage/Layout/classes/class.ilPageLayoutPageConfig.php @@ -5,7 +5,7 @@ include_once("./Services/COPage/classes/class.ilPageConfig.php"); /** - * Page layout page configuration + * Page layout page configuration * * @author Alex Killing * @version $Id$ @@ -13,28 +13,25 @@ include_once("./Services/COPage/classes/class.ilPageConfig.php"); */ class ilPageLayoutPageConfig extends ilPageConfig { - /** - * @var ilSetting - */ - protected $settings; + /** + * @var ilSetting + */ + protected $settings; - /** - * Init - */ - function init() - { - global $DIC; + /** + * Init + */ + public function init() + { + global $DIC; - $this->settings = $DIC->settings(); + $this->settings = $DIC->settings(); - $this->setPreventHTMLUnmasking(false); - $this->setEnableInternalLinks(false); - $this->setEnablePCType("Question", false); - $this->setEnablePCType("Map", false); - $this->setEnablePCType("FileList", false); - $this->setEnablePCType("PlaceHolder", true); - } - + $this->setPreventHTMLUnmasking(false); + $this->setEnableInternalLinks(false); + $this->setEnablePCType("Question", false); + $this->setEnablePCType("Map", false); + $this->setEnablePCType("FileList", false); + $this->setEnablePCType("PlaceHolder", true); + } } - -?> diff --git a/Services/COPage/Layout/classes/class.ilPageLayoutTableGUI.php b/Services/COPage/Layout/classes/class.ilPageLayoutTableGUI.php index 03ea78bb621092b79da6b2342a87a9a07bfd9c14..445c8acd7457d130578afb8d2d3b189be29089b2 100644 --- a/Services/COPage/Layout/classes/class.ilPageLayoutTableGUI.php +++ b/Services/COPage/Layout/classes/class.ilPageLayoutTableGUI.php @@ -12,152 +12,152 @@ include_once("Services/Table/classes/class.ilTable2GUI.php"); */ class ilPageLayoutTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilRbacSystem - */ - protected $rbacsystem; + /** + * @var ilRbacSystem + */ + protected $rbacsystem; - function __construct($a_parent_obj, $a_parent_cmd) - { - global $DIC; + public function __construct($a_parent_obj, $a_parent_cmd) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->rbacsystem = $DIC->rbac()->system(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $rbacsystem = $DIC->rbac()->system(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->rbacsystem = $DIC->rbac()->system(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $rbacsystem = $DIC->rbac()->system(); - $lng->loadLanguageModule("content"); - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->addColumn("", "", "2%"); - - $this->addColumn($lng->txt("active")); - $this->addColumn($lng->txt("thumbnail")); - $this->addColumn($lng->txt("title")); - $this->addColumn($lng->txt("description")); - $this->addColumn($lng->txt("obj_sty")); - $this->addColumn($lng->txt("type")); - $this->addColumn($lng->txt("modules")); - $this->addColumn($lng->txt("actions")); - - // show command buttons, if write permission is given - if ($a_parent_obj->checkPermission("sty_write_page_layout", false)) - { - $this->addMultiCommand("activate", $lng->txt("activate")); - $this->addMultiCommand("deactivate", $lng->txt("deactivate")); - $this->addMultiCommand("deletePgl", $lng->txt("delete")); - $this->addCommandButton("savePageLayoutTypes", $lng->txt("cont_save_types")); - } - - $this->getPageLayouts(); - - $this->setSelectAllCheckbox("pglayout"); - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.stys_pglayout_table_row.html", - "Services/COPage/Layout"); - $this->setTitle($lng->txt("page_layouts")); - - //build form - /* - $opts = ilUtil::formSelect(12,"new_type",array($lng->txt("page_layout"))); - $this->tpl->setCurrentBlock("add_object"); - $this->tpl->setVariable("SELECT_OBJTYPE", $opts); - $this->tpl->setVariable("BTN_NAME", "createPgGUI"); - $this->tpl->setVariable("TXT_ADD", $this->lng->txt("add")); - $this->tpl->parseCurrentBlock(); - */ - } - - /** - * Get a List of all Page Layouts - */ - function getPageLayouts() { - $this->setData(ilPageLayout::getLayoutsAsArray()); - $this->all_mods = ilPageLayout::getAvailableModules(); - } - - /** - * Standard Version of Fill Row. Most likely to - * be overwritten by derived class. - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - // action - $ilCtrl->setParameter($this->parent_obj, "layout_id", $a_set['layout_id']); + $lng->loadLanguageModule("content"); + + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->addColumn("", "", "2%"); + + $this->addColumn($lng->txt("active")); + $this->addColumn($lng->txt("thumbnail")); + $this->addColumn($lng->txt("title")); + $this->addColumn($lng->txt("description")); + $this->addColumn($lng->txt("obj_sty")); + $this->addColumn($lng->txt("type")); + $this->addColumn($lng->txt("modules")); + $this->addColumn($lng->txt("actions")); + + // show command buttons, if write permission is given + if ($a_parent_obj->checkPermission("sty_write_page_layout", false)) { + $this->addMultiCommand("activate", $lng->txt("activate")); + $this->addMultiCommand("deactivate", $lng->txt("deactivate")); + $this->addMultiCommand("deletePgl", $lng->txt("delete")); + $this->addCommandButton("savePageLayoutTypes", $lng->txt("cont_save_types")); + } + + $this->getPageLayouts(); + + $this->setSelectAllCheckbox("pglayout"); + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate( + "tpl.stys_pglayout_table_row.html", + "Services/COPage/Layout" + ); + $this->setTitle($lng->txt("page_layouts")); + + //build form + /* + $opts = ilUtil::formSelect(12,"new_type",array($lng->txt("page_layout"))); + $this->tpl->setCurrentBlock("add_object"); + $this->tpl->setVariable("SELECT_OBJTYPE", $opts); + $this->tpl->setVariable("BTN_NAME", "createPgGUI"); + $this->tpl->setVariable("TXT_ADD", $this->lng->txt("add")); + $this->tpl->parseCurrentBlock(); + */ + } + + /** + * Get a List of all Page Layouts + */ + public function getPageLayouts() + { + $this->setData(ilPageLayout::getLayoutsAsArray()); + $this->all_mods = ilPageLayout::getAvailableModules(); + } + + /** + * Standard Version of Fill Row. Most likely to + * be overwritten by derived class. + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + // action + $ilCtrl->setParameter($this->parent_obj, "layout_id", $a_set['layout_id']); - if ($this->parent_obj->checkPermission("sty_write_page_layout", false)) - { - $this->tpl->setCurrentBlock("action"); - $this->tpl->setVariable("HREF_ACTION", - $ilCtrl->getLinkTarget($this->parent_obj, "exportLayout")); - $this->tpl->setVariable("TXT_ACTION", $lng->txt("export")); - $this->tpl->parseCurrentBlock(); - } + if ($this->parent_obj->checkPermission("sty_write_page_layout", false)) { + $this->tpl->setCurrentBlock("action"); + $this->tpl->setVariable( + "HREF_ACTION", + $ilCtrl->getLinkTarget($this->parent_obj, "exportLayout") + ); + $this->tpl->setVariable("TXT_ACTION", $lng->txt("export")); + $this->tpl->parseCurrentBlock(); + } - $ilCtrl->setParameter($this->parent_obj, "layout_id", ""); - - // modules - $this->tpl->setCurrentBlock("mod"); - foreach($this->all_mods as $mod_id => $mod_caption) - { - if(($mod_id == ilPageLayout::MODULE_SCORM && $a_set["mod_scorm"]) || - ($mod_id == ilPageLayout::MODULE_PORTFOLIO && $a_set["mod_portfolio"])) - { - $this->tpl->setVariable("MOD_STATUS", " checked=\"checked\""); - } - $this->tpl->setVariable("MODULE_ID", $mod_id); - $this->tpl->setVariable("LAYOUT_ID", $a_set["layout_id"]); - $this->tpl->setVariable("MOD_NAME", $mod_caption); - $this->tpl->parseCurrentBlock(); - } - - if ($a_set['active']) - { - $this->tpl->setVariable("IMG_ACTIVE",ilUtil::getImagePath("icon_ok.svg")); - } - else - { - $this->tpl->setVariable("IMG_ACTIVE",ilUtil::getImagePath("icon_not_ok.svg")); - } - $this->tpl->setVariable("VAL_TITLE", $a_set['title']); - $this->tpl->setVariable("VAL_DESCRIPTION", $a_set['description']); - $this->tpl->setVariable("CHECKBOX_ID", $a_set['layout_id']); - - $ilCtrl->setParameter($this->parent_obj, "obj_id", $a_set['layout_id']); - if ($this->parent_obj->checkPermission("sty_write_page_layout", false)) - { - $this->tpl->setVariable("HREF_EDIT_PGLAYOUT", $ilCtrl->getLinkTarget($this->parent_obj, "editPg")); - } - - $pgl_obj = new ilPageLayout($a_set['layout_id']); - $this->tpl->setVariable("VAL_PREVIEW_HTML",$pgl_obj->getPreview()); + $ilCtrl->setParameter($this->parent_obj, "layout_id", ""); + + // modules + $this->tpl->setCurrentBlock("mod"); + foreach ($this->all_mods as $mod_id => $mod_caption) { + if (($mod_id == ilPageLayout::MODULE_SCORM && $a_set["mod_scorm"]) || + ($mod_id == ilPageLayout::MODULE_PORTFOLIO && $a_set["mod_portfolio"])) { + $this->tpl->setVariable("MOD_STATUS", " checked=\"checked\""); + } + $this->tpl->setVariable("MODULE_ID", $mod_id); + $this->tpl->setVariable("LAYOUT_ID", $a_set["layout_id"]); + $this->tpl->setVariable("MOD_NAME", $mod_caption); + $this->tpl->parseCurrentBlock(); + } + + if ($a_set['active']) { + $this->tpl->setVariable("IMG_ACTIVE", ilUtil::getImagePath("icon_ok.svg")); + } else { + $this->tpl->setVariable("IMG_ACTIVE", ilUtil::getImagePath("icon_not_ok.svg")); + } + $this->tpl->setVariable("VAL_TITLE", $a_set['title']); + $this->tpl->setVariable("VAL_DESCRIPTION", $a_set['description']); + $this->tpl->setVariable("CHECKBOX_ID", $a_set['layout_id']); + + $ilCtrl->setParameter($this->parent_obj, "obj_id", $a_set['layout_id']); + if ($this->parent_obj->checkPermission("sty_write_page_layout", false)) { + $this->tpl->setVariable("HREF_EDIT_PGLAYOUT", $ilCtrl->getLinkTarget($this->parent_obj, "editPg")); + } + + $pgl_obj = new ilPageLayout($a_set['layout_id']); + $this->tpl->setVariable("VAL_PREVIEW_HTML", $pgl_obj->getPreview()); - if ($a_set["style_id"] > 0) - { - $this->tpl->setVariable("STYLE", - ilObject::_lookupTitle($a_set["style_id"])); - } - - $this->tpl->setVariable("TYPE", - ilUtil::formSelect($a_set["special_page"], "type[".$a_set["layout_id"]."]", - array("0" => $lng->txt("cont_layout_template"), - "1" => $lng->txt("cont_special_page")), - false, true) - ); - - } + if ($a_set["style_id"] > 0) { + $this->tpl->setVariable( + "STYLE", + ilObject::_lookupTitle($a_set["style_id"]) + ); + } + $this->tpl->setVariable( + "TYPE", + ilUtil::formSelect( + $a_set["special_page"], + "type[" . $a_set["layout_id"] . "]", + array("0" => $lng->txt("cont_layout_template"), + "1" => $lng->txt("cont_special_page")), + false, + true + ) + ); + } } -?> diff --git a/Services/COPage/classes/class.ilCOPageDataSet.php b/Services/COPage/classes/class.ilCOPageDataSet.php index c8aba8222e3867b3596af0a659150281a8993c21..7323ad40d9e68c45d3b2f7cb424c13884d25a6cc 100644 --- a/Services/COPage/classes/class.ilCOPageDataSet.php +++ b/Services/COPage/classes/class.ilCOPageDataSet.php @@ -5,10 +5,10 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); /** * COPage Data set class - * + * * This class implements the following entities: * - pgtp: page layout template - * + * * Please note that the usual page xml export DOES NOT use the dataset. * The page export uses pre-existing methods to create the xml. * @@ -18,143 +18,144 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); */ class ilCOPageDataSet extends ilDataSet { - protected $master_lang_only = false; + protected $master_lang_only = false; - /** - * Set master language only - * - * @param bool $a_val export only master language - */ - function setMasterLanguageOnly($a_val) - { - $this->master_lang_only = $a_val; - } + /** + * Set master language only + * + * @param bool $a_val export only master language + */ + public function setMasterLanguageOnly($a_val) + { + $this->master_lang_only = $a_val; + } - /** - * Get master language only - * - * @return bool export only master language - */ - function getMasterLanguageOnly() - { - return $this->master_lang_only; - } + /** + * Get master language only + * + * @return bool export only master language + */ + public function getMasterLanguageOnly() + { + return $this->master_lang_only; + } - /** - * Get supported versions - * - * @param - * @return - */ - public function getSupportedVersions() - { - return array("4.2.0"); - } - - /** - * Get xml namespace - * - * @param - * @return - */ - function getXmlNamespace($a_entity, $a_schema_version) - { - return "http://www.ilias.de/xml/Services/COPage/".$a_entity; - } - - /** - * Get field types for entity - * - * @param - * @return - */ - protected function getTypes($a_entity, $a_version) - { - // pgtp: page layout template - if ($a_entity == "pgtp") - { - switch ($a_version) - { - case "4.2.0": - return array( - "Id" => "integer", - "Title" => "text", - "Description" => "text", - "SpecialPage" => "integer", - "StyleId" => "integer"); - } - } - } + /** + * Get supported versions + * + * @param + * @return + */ + public function getSupportedVersions() + { + return array("4.2.0"); + } + + /** + * Get xml namespace + * + * @param + * @return + */ + public function getXmlNamespace($a_entity, $a_schema_version) + { + return "http://www.ilias.de/xml/Services/COPage/" . $a_entity; + } + + /** + * Get field types for entity + * + * @param + * @return + */ + protected function getTypes($a_entity, $a_version) + { + // pgtp: page layout template + if ($a_entity == "pgtp") { + switch ($a_version) { + case "4.2.0": + return array( + "Id" => "integer", + "Title" => "text", + "Description" => "text", + "SpecialPage" => "integer", + "StyleId" => "integer"); + } + } + } - /** - * Read data - * - * @param - * @return - */ - function readData($a_entity, $a_version, $a_ids, $a_field = "") - { - $db = $this->db; + /** + * Read data + * + * @param + * @return + */ + public function readData($a_entity, $a_version, $a_ids, $a_field = "") + { + $db = $this->db; - if (!is_array($a_ids)) - { - $a_ids = array($a_ids); - } - - // mep_data - if ($a_entity == "pgtp") - { - switch ($a_version) - { - case "4.2.0": - $this->getDirectDataFromQuery("SELECT layout_id id, title, description, ". - " style_id, special_page ". - " FROM page_layout ". - "WHERE ". - $db->in("layout_id", $a_ids, false, "integer")); - break; - } - } - } - - /** - * Determine the dependent sets of data - */ - protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) - { - return false; - } - - //// - //// Needs abstraction (interface?) and version handling - //// - - - /** - * Import record - * - * @param - * @return - */ - function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) - { - switch ($a_entity) - { - case "pgtp": - include_once("./Services/COPage/Layout/classes/class.ilPageLayout.php"); - $pt = new ilPageLayout(); - $pt->setTitle($a_rec["Title"]); - $pt->setDescription($a_rec["Description"]); - $pt->setSpecialPage($a_rec["SpecialPage"]); - $pt->update(); - - $this->current_obj = $pt; - $a_mapping->addMapping("Services/COPage", "pgtp", $a_rec["Id"], - $pt->getId()); - $a_mapping->addMapping("Services/COPage", "pg", "stys:".$a_rec["Id"], - "stys:".$pt->getId()); - break; - } - } + if (!is_array($a_ids)) { + $a_ids = array($a_ids); + } + + // mep_data + if ($a_entity == "pgtp") { + switch ($a_version) { + case "4.2.0": + $this->getDirectDataFromQuery("SELECT layout_id id, title, description, " . + " style_id, special_page " . + " FROM page_layout " . + "WHERE " . + $db->in("layout_id", $a_ids, false, "integer")); + break; + } + } + } + + /** + * Determine the dependent sets of data + */ + protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) + { + return false; + } + + //// + //// Needs abstraction (interface?) and version handling + //// + + + /** + * Import record + * + * @param + * @return + */ + public function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) + { + switch ($a_entity) { + case "pgtp": + include_once("./Services/COPage/Layout/classes/class.ilPageLayout.php"); + $pt = new ilPageLayout(); + $pt->setTitle($a_rec["Title"]); + $pt->setDescription($a_rec["Description"]); + $pt->setSpecialPage($a_rec["SpecialPage"]); + $pt->update(); + + $this->current_obj = $pt; + $a_mapping->addMapping( + "Services/COPage", + "pgtp", + $a_rec["Id"], + $pt->getId() + ); + $a_mapping->addMapping( + "Services/COPage", + "pg", + "stys:" . $a_rec["Id"], + "stys:" . $pt->getId() + ); + break; + } + } } -?> \ No newline at end of file diff --git a/Services/COPage/classes/class.ilCOPageExportConfig.php b/Services/COPage/classes/class.ilCOPageExportConfig.php index 933e49034a9296cf2e22a0f5c1133150c37dfad1..89ea46bbb70a3b8aa9f80e85253a42010bf2b847 100644 --- a/Services/COPage/classes/class.ilCOPageExportConfig.php +++ b/Services/COPage/classes/class.ilCOPageExportConfig.php @@ -12,40 +12,37 @@ include_once("./Services/Export/classes/class.ilExportConfig.php"); */ class ilCOPageExportConfig extends ilExportConfig { - protected $master_only = false; - protected $include_media = true; + protected $master_only = false; + protected $include_media = true; - /** - * Set master language only - * - * @param bool $a_val export only master language - */ - function setMasterLanguageOnly($a_val, $a_include_media = true) - { - $this->master_only = $a_val; - $this->include_media = $a_include_media; - } + /** + * Set master language only + * + * @param bool $a_val export only master language + */ + public function setMasterLanguageOnly($a_val, $a_include_media = true) + { + $this->master_only = $a_val; + $this->include_media = $a_include_media; + } - /** - * Get master language only - * - * @return bool export only master language - */ - function getMasterLanguageOnly() - { - return $this->master_only; - } - - /** - * Get include media - * - * @return bool export media? - */ - function getIncludeMedia() - { - return $this->include_media; - } + /** + * Get master language only + * + * @return bool export only master language + */ + public function getMasterLanguageOnly() + { + return $this->master_only; + } + /** + * Get include media + * + * @return bool export media? + */ + public function getIncludeMedia() + { + return $this->include_media; + } } - -?> \ No newline at end of file diff --git a/Services/COPage/classes/class.ilCOPageExporter.php b/Services/COPage/classes/class.ilCOPageExporter.php index c30511f334a9c66be3066f8e99c8433d63e8ec9c..cbb69786f520418109da58bc22d797b86a85e41e 100644 --- a/Services/COPage/classes/class.ilCOPageExporter.php +++ b/Services/COPage/classes/class.ilCOPageExporter.php @@ -12,317 +12,290 @@ include_once("./Services/Export/classes/class.ilXmlExporter.php"); */ class ilCOPageExporter extends ilXmlExporter { - private $ds; - /** - * @var ilCOPageExportConfig - */ - protected $config; + private $ds; + /** + * @var ilCOPageExportConfig + */ + protected $config; - /** - * List of dependencies for page component plugins with an own exporter - * - * The list of ids in the dependency definition has the following format: - * ::: - * - * The implementation assumes the following call sequence of methods - * to avoid a multiple instatiation of page objects - * 1. init() - * 2. getXmlRepresentation() - * 3. getXmlExportTailDependencies() - * - * - * @var array plugin_name => depencency definition array - */ - protected $plugin_dependencies = array(); + /** + * List of dependencies for page component plugins with an own exporter + * + * The list of ids in the dependency definition has the following format: + * ::: + * + * The implementation assumes the following call sequence of methods + * to avoid a multiple instatiation of page objects + * 1. init() + * 2. getXmlRepresentation() + * 3. getXmlExportTailDependencies() + * + * + * @var array plugin_name => depencency definition array + */ + protected $plugin_dependencies = array(); - /** - * Initialisation - */ - function init() - { - global $DIC; - /** @var ilPluginAdmin $ilPluginAdmin */ - $ilPluginAdmin = $DIC['ilPluginAdmin']; + /** + * Initialisation + */ + public function init() + { + global $DIC; + /** @var ilPluginAdmin $ilPluginAdmin */ + $ilPluginAdmin = $DIC['ilPluginAdmin']; - include_once("./Services/COPage/classes/class.ilCOPageDataSet.php"); - $this->ds = new ilCOPageDataSet(); - $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); - $this->ds->setDSPrefix("ds"); - $this->config = $this->getExport()->getConfig("Services/COPage"); - if ($this->config->getMasterLanguageOnly()) - { - $this->ds->setMasterLanguageOnly(true); - } + include_once("./Services/COPage/classes/class.ilCOPageDataSet.php"); + $this->ds = new ilCOPageDataSet(); + $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); + $this->ds->setDSPrefix("ds"); + $this->config = $this->getExport()->getConfig("Services/COPage"); + if ($this->config->getMasterLanguageOnly()) { + $this->ds->setMasterLanguageOnly(true); + } - // collect all page component plugins that have their own exporter - require_once('Services/COPage/classes/class.ilPageComponentPluginExporter.php'); - foreach(ilPluginAdmin::getActivePluginsForSlot(IL_COMP_SERVICE, "COPage", "pgcp") as $plugin_name) - { - if ($ilPluginAdmin->supportsExport(IL_COMP_SERVICE, "COPage", "pgcp", $plugin_name)) - { - require_once('Customizing/global/plugins/Services/COPage/PageComponent/' - .$plugin_name.'/classes/class.il'.$plugin_name.'Exporter.php'); + // collect all page component plugins that have their own exporter + require_once('Services/COPage/classes/class.ilPageComponentPluginExporter.php'); + foreach (ilPluginAdmin::getActivePluginsForSlot(IL_COMP_SERVICE, "COPage", "pgcp") as $plugin_name) { + if ($ilPluginAdmin->supportsExport(IL_COMP_SERVICE, "COPage", "pgcp", $plugin_name)) { + require_once('Customizing/global/plugins/Services/COPage/PageComponent/' + . $plugin_name . '/classes/class.il' . $plugin_name . 'Exporter.php'); - $this->plugin_dependencies[$plugin_name] = array( - "component" => "Plugins/" . $plugin_name, - "entity" => "pgcp", - "ids" => array() - ); - } - } - } + $this->plugin_dependencies[$plugin_name] = array( + "component" => "Plugins/" . $plugin_name, + "entity" => "pgcp", + "ids" => array() + ); + } + } + } - /** - * Get head dependencies - * - * @param string entity - * @param string target release - * @param array ids - * @return array array of array with keys "component", entity", "ids" - */ - function getXmlExportHeadDependencies($a_entity, $a_target_release, $a_ids) - { - if ($a_entity == "pg") - { - // get all media objects and files of the page - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - include_once("./Modules/File/classes/class.ilObjFile.php"); - $mob_ids = array(); - $file_ids = array(); - foreach ($a_ids as $pg_id) - { - $pg_id = explode(":", $pg_id); + /** + * Get head dependencies + * + * @param string entity + * @param string target release + * @param array ids + * @return array array of array with keys "component", entity", "ids" + */ + public function getXmlExportHeadDependencies($a_entity, $a_target_release, $a_ids) + { + if ($a_entity == "pg") { + // get all media objects and files of the page + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + include_once("./Modules/File/classes/class.ilObjFile.php"); + $mob_ids = array(); + $file_ids = array(); + foreach ($a_ids as $pg_id) { + $pg_id = explode(":", $pg_id); - $lang = ($this->config->getMasterLanguageOnly()) - ? "-" - : ""; - - // get media objects - if ($this->config->getIncludeMedia()) - { - $mids = ilObjMediaObject::_getMobsOfObject($pg_id[0] . ":pg", $pg_id[1], 0, $lang); - foreach ($mids as $mid) - { - if (ilObject::_lookupType($mid) == "mob") - { - $mob_ids[] = $mid; - } - } - } - - // get files - $files = ilObjFile::_getFilesOfObject($pg_id[0].":pg", $pg_id[1], 0, $lang); - foreach ($files as $file) - { - if (ilObject::_lookupType($file) == "file") - { - $file_ids[] = $file; - } - } - } - - return array ( - array( - "component" => "Services/MediaObjects", - "entity" => "mob", - "ids" => $mob_ids), - array( - "component" => "Modules/File", - "entity" => "file", - "ids" => $file_ids) - ); - } - - return array(); - } - - /** - * Get tail dependencies - * - * @param string entity - * @param string target release - * @param array ids - * @return array array of array with keys "component", entity", "ids" - */ - function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) - { - if ($a_entity == "pgtp") - { - $pg_ids = array(); - foreach ($a_ids as $id) - { - $pg_ids[] = "stys:".$id; - } - - return array( - array( - "component" => "Services/COPage", - "entity" => "pg", - "ids" => $pg_ids) - ); - } + $lang = ($this->config->getMasterLanguageOnly()) + ? "-" + : ""; + + // get media objects + if ($this->config->getIncludeMedia()) { + $mids = ilObjMediaObject::_getMobsOfObject($pg_id[0] . ":pg", $pg_id[1], 0, $lang); + foreach ($mids as $mid) { + if (ilObject::_lookupType($mid) == "mob") { + $mob_ids[] = $mid; + } + } + } + + // get files + $files = ilObjFile::_getFilesOfObject($pg_id[0] . ":pg", $pg_id[1], 0, $lang); + foreach ($files as $file) { + if (ilObject::_lookupType($file) == "file") { + $file_ids[] = $file; + } + } + } + + return array( + array( + "component" => "Services/MediaObjects", + "entity" => "mob", + "ids" => $mob_ids), + array( + "component" => "Modules/File", + "entity" => "file", + "ids" => $file_ids) + ); + } + + return array(); + } + + /** + * Get tail dependencies + * + * @param string entity + * @param string target release + * @param array ids + * @return array array of array with keys "component", entity", "ids" + */ + public function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) + { + if ($a_entity == "pgtp") { + $pg_ids = array(); + foreach ($a_ids as $id) { + $pg_ids[] = "stys:" . $id; + } + + return array( + array( + "component" => "Services/COPage", + "entity" => "pg", + "ids" => $pg_ids) + ); + } - if (!empty($this->plugin_dependencies)) - { - // use numeric keys instead plugin names - return array_values($this->plugin_dependencies); - } + if (!empty($this->plugin_dependencies)) { + // use numeric keys instead plugin names + return array_values($this->plugin_dependencies); + } - return array(); - } + return array(); + } - /** - * Get xml representation - * - * @param string entity - * @param string schema version - * @param array ids - * @return string xml - */ - public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) - { - if ($a_entity == "pg") - { - include_once("./Services/COPage/classes/class.ilPageObject.php"); - - $id = explode(":", $a_id); + /** + * Get xml representation + * + * @param string entity + * @param string schema version + * @param array ids + * @return string xml + */ + public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) + { + if ($a_entity == "pg") { + include_once("./Services/COPage/classes/class.ilPageObject.php"); + + $id = explode(":", $a_id); - $langs = array("-"); - if (!$this->config->getMasterLanguageOnly()) - { - $trans = ilPageObject::lookupTranslations($id[0], $id[1]); - foreach ($trans as $t) - { - if ($t != "-") - { - $langs[] = $t; - } - } - } + $langs = array("-"); + if (!$this->config->getMasterLanguageOnly()) { + $trans = ilPageObject::lookupTranslations($id[0], $id[1]); + foreach ($trans as $t) { + if ($t != "-") { + $langs[] = $t; + } + } + } - include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); - $xml = ""; - foreach ($langs as $l) - { - $page_object = ilPageObjectFactory::getInstance($id[0], $id[1], 0, $l); - $page_object->buildDom(); - $page_object->insertInstIntoIDs(IL_INST_ID); - $this->extractPluginProperties($page_object); - $pxml = $page_object->getXMLFromDom(false, false, false, "", true); - $pxml = str_replace("&","&", $pxml); - $a_media = ($this->config->getIncludeMedia()) - ? "" - : 'WithoutMedia="1"'; - $xml.= ''; - $xml.= $pxml; - $xml.= ""; - $page_object->freeDom(); - } - - return $xml; - } - if ($a_entity == "pgtp") - { - return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); - } - } + include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); + $xml = ""; + foreach ($langs as $l) { + $page_object = ilPageObjectFactory::getInstance($id[0], $id[1], 0, $l); + $page_object->buildDom(); + $page_object->insertInstIntoIDs(IL_INST_ID); + $this->extractPluginProperties($page_object); + $pxml = $page_object->getXMLFromDom(false, false, false, "", true); + $pxml = str_replace("&", "&", $pxml); + $a_media = ($this->config->getIncludeMedia()) + ? "" + : 'WithoutMedia="1"'; + $xml.= ''; + $xml.= $pxml; + $xml.= ""; + $page_object->freeDom(); + } + + return $xml; + } + if ($a_entity == "pgtp") { + return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); + } + } - /** - * Returns schema versions that the component can export to. - * ILIAS chooses the first one, that has min/max constraints which - * fit to the target release. Please put the newest on top. - * - * @return - */ - function getValidSchemaVersions($a_entity) - { - if ($a_entity == "pg") - { - return array ( - "4.2.0" => array( - "namespace" => "http://www.ilias.de/Services/COPage/pg/4_2", - "xsd_file" => "ilias_pg_4_2.xsd", - "min" => "4.2.0", - "max" => ""), - "4.1.0" => array( - "namespace" => "http://www.ilias.de/Services/COPage/pg/4_1", - "xsd_file" => "ilias_pg_4_1.xsd", - "min" => "4.1.0", - "max" => "4.1.99") - ); - } - if ($a_entity == "pgtp") - { - return array ( - "4.2.0" => array( - "namespace" => "http://www.ilias.de/Services/COPage/pgtp/4_1", - "xsd_file" => "ilias_pgtp_4_1.xsd", - "uses_dataset" => true, - "min" => "4.2.0", - "max" => "") - ); - } - } + /** + * Returns schema versions that the component can export to. + * ILIAS chooses the first one, that has min/max constraints which + * fit to the target release. Please put the newest on top. + * + * @return + */ + public function getValidSchemaVersions($a_entity) + { + if ($a_entity == "pg") { + return array( + "4.2.0" => array( + "namespace" => "http://www.ilias.de/Services/COPage/pg/4_2", + "xsd_file" => "ilias_pg_4_2.xsd", + "min" => "4.2.0", + "max" => ""), + "4.1.0" => array( + "namespace" => "http://www.ilias.de/Services/COPage/pg/4_1", + "xsd_file" => "ilias_pg_4_1.xsd", + "min" => "4.1.0", + "max" => "4.1.99") + ); + } + if ($a_entity == "pgtp") { + return array( + "4.2.0" => array( + "namespace" => "http://www.ilias.de/Services/COPage/pgtp/4_1", + "xsd_file" => "ilias_pgtp_4_1.xsd", + "uses_dataset" => true, + "min" => "4.2.0", + "max" => "") + ); + } + } - /** - * Extract the properties of the plugged page contents - * The page XML is scanned for plugged contents with own exporters - * Their ids are added as dependencies - * - * Called from getXmlRepresentation() for each handled page object - * Extracted data is used by dependent exporters afterwards - * - * @param ilPageObject $a_page - */ - protected function extractPluginProperties($a_page) - { - if (empty($this->plugin_dependencies)) - { - return; - } + /** + * Extract the properties of the plugged page contents + * The page XML is scanned for plugged contents with own exporters + * Their ids are added as dependencies + * + * Called from getXmlRepresentation() for each handled page object + * Extracted data is used by dependent exporters afterwards + * + * @param ilPageObject $a_page + */ + protected function extractPluginProperties($a_page) + { + if (empty($this->plugin_dependencies)) { + return; + } - $a_page->buildDom(); - $domdoc = $a_page->getDomDoc(); - $xpath = new DOMXPath($domdoc); - $nodes = $xpath->query("//PageContent[child::Plugged]"); + $a_page->buildDom(); + $domdoc = $a_page->getDomDoc(); + $xpath = new DOMXPath($domdoc); + $nodes = $xpath->query("//PageContent[child::Plugged]"); - /** @var DOMElement $pcnode */ - foreach($nodes as $pcnode) - { - // page content id (unique in the page) - $pc_id = $pcnode->getAttribute('PCID'); - $plnode = $pcnode->childNodes->item(0); - $plugin_name = $plnode->getAttribute('PluginName'); - $plugin_version = $plnode->getAttribute('PluginVersion'); + /** @var DOMElement $pcnode */ + foreach ($nodes as $pcnode) { + // page content id (unique in the page) + $pc_id = $pcnode->getAttribute('PCID'); + $plnode = $pcnode->childNodes->item(0); + $plugin_name = $plnode->getAttribute('PluginName'); + $plugin_version = $plnode->getAttribute('PluginVersion'); - // dependency should be exported - if (isset($this->plugin_dependencies[$plugin_name])) - { - // construct a unique dependency id of the plugged page content - $id = $a_page->getParentType() - . ':' . $a_page->getId() - . ':' . $a_page->getLanguage() - . ':' . $pc_id; + // dependency should be exported + if (isset($this->plugin_dependencies[$plugin_name])) { + // construct a unique dependency id of the plugged page content + $id = $a_page->getParentType() + . ':' . $a_page->getId() + . ':' . $a_page->getLanguage() + . ':' . $pc_id; - $properties = array(); - /** @var DOMElement $child */ - foreach($plnode->childNodes as $child) - { - $properties[$child->getAttribute('Name')] = $child->nodeValue; - } + $properties = array(); + /** @var DOMElement $child */ + foreach ($plnode->childNodes as $child) { + $properties[$child->getAttribute('Name')] = $child->nodeValue; + } - // statical provision of content to the exporter classes - ilPageComponentPluginExporter::setPCVersion($id, $plugin_version); - ilPageComponentPluginExporter::setPCProperties($id, $properties); + // statical provision of content to the exporter classes + ilPageComponentPluginExporter::setPCVersion($id, $plugin_version); + ilPageComponentPluginExporter::setPCProperties($id, $properties); - // each plugin exporter gets only the ids of its own content - $this->plugin_dependencies[$plugin_name]['ids'][] = $id; - } - } - } + // each plugin exporter gets only the ids of its own content + $this->plugin_dependencies[$plugin_name]['ids'][] = $id; + } + } + } } - -?> \ No newline at end of file diff --git a/Services/COPage/classes/class.ilCOPageHTMLExport.php b/Services/COPage/classes/class.ilCOPageHTMLExport.php index 3c40969b75c27da7e685f797d4b9e9479b965cc4..453e60ba8d6c2a179aac39c12a49484be96f0a37 100644 --- a/Services/COPage/classes/class.ilCOPageHTMLExport.php +++ b/Services/COPage/classes/class.ilCOPageHTMLExport.php @@ -10,629 +10,607 @@ */ class ilCOPageHTMLExport { - /** - * @var array - */ - protected $mobs = array(); - - /** - * @var array - */ - protected $files = array(); - - /** - * @var array - */ - protected $files_direct = array(); - - /** - * @var string - */ - protected $exp_dir = ""; - - /** - * @var int - */ - protected $content_style_id = 0; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilLogger - */ - protected $log; - - /** - * ilCOPageHTMLExport constructor. - * @param $a_exp_dir - */ - function __construct($a_exp_dir) - { - global $DIC; - - $this->log = ilLoggerFactory::getLogger('copg'); - $this->user = $DIC->user(); - - $this->exp_dir = $a_exp_dir; - $this->mobs_dir = $a_exp_dir."/mobs"; - $this->files_dir = $a_exp_dir."/files"; - $this->tex_dir = $a_exp_dir."/teximg"; - $this->content_style_dir = $a_exp_dir."/content_style"; - $this->content_style_img_dir = $a_exp_dir."/content_style/images"; - - include_once("./Services/MediaObjects/classes/class.ilPlayerUtil.php"); - $this->services_dir = $a_exp_dir."/Services"; - $this->media_service_dir = $this->services_dir."/MediaObjects"; - $this->flv_dir = $a_exp_dir."/".ilPlayerUtil::getFlashVideoPlayerDirectory(); - $this->mp3_dir = $this->media_service_dir."/flash_mp3_player"; - - $this->js_dir = $a_exp_dir.'/js'; - $this->js_yahoo_dir = $a_exp_dir.'/js/yahoo'; - $this->css_dir = $a_exp_dir.'/css'; - } - - /** - * Set content style id - * - * @param int $a_val content style id - */ - function setContentStyleId($a_val) - { - $this->content_style_id = $a_val; - } - - /** - * Get content style id - * - * @return int content style id - */ - function getContentStyleId() - { - return $this->content_style_id; - } - - /** - * Create directories - * - * @param - * @return - */ - function createDirectories() - { - ilUtil::makeDir($this->mobs_dir); - ilUtil::makeDir($this->files_dir); - ilUtil::makeDir($this->tex_dir); - ilUtil::makeDir($this->content_style_dir); - ilUtil::makeDir($this->content_style_img_dir); - ilUtil::makeDir($this->services_dir); - ilUtil::makeDir($this->media_service_dir); - ilUtil::makeDir($this->flv_dir); - ilUtil::makeDir($this->mp3_dir); - - ilUtil::makeDir($this->js_dir); - ilUtil::makeDir($this->js_yahoo_dir); - ilUtil::makeDir($this->css_dir); - ilUtil::makeDir($this->css_dir."/yahoo"); - } - - /** - * Export content style - * - * @param - * @return - */ - function exportStyles() - { - - $this->log->debug("export styles"); - - include_once "Services/Style/Content/classes/class.ilObjStyleSheet.php"; - - // export content style sheet - if ($this->getContentStyleId() < 1) - { - $cont_stylesheet = "./Services/COPage/css/content.css"; - - $css = fread(fopen($cont_stylesheet,'r'),filesize($cont_stylesheet)); - preg_match_all("/url\(([^\)]*)\)/",$css,$files); - foreach (array_unique($files[1]) as $fileref) - { - if (is_file(str_replace("..", ".", $fileref))) - { - copy(str_replace("..", ".", $fileref), $this->content_style_img_dir."/".basename($fileref)); - } - $css = str_replace($fileref, "images/".basename($fileref),$css); - } - fwrite(fopen($this->content_style_dir."/content.css",'w'),$css); - } - else - { - $style = new ilObjStyleSheet($this->getContentStyleId()); - $style->writeCSSFile($this->content_style_dir."/content.css", "images"); - $style->copyImagesToDir($this->content_style_img_dir); - } - - // export syntax highlighting style - $syn_stylesheet = ilObjStyleSheet::getSyntaxStylePath(); - copy($syn_stylesheet, $this->exp_dir."/syntaxhighlight.css"); - } - - /** - * Export support scripts - * - * @todo: use ilPageContent js/css functions here (problem: currently they need a page object for init) - * - * @param - * @return - */ - function exportSupportScripts() - { - $this->log->debug("export scripts"); - - // basic js - copy('./Services/JavaScript/js/Basic.js', $this->js_dir.'/Basic.js'); - - copy('./Services/UIComponent/Overlay/js/ilOverlay.js',$this->js_dir.'/ilOverlay.js'); - - // jquery - include_once("./Services/jQuery/classes/class.iljQueryUtil.php"); - copy(iljQueryUtil::getLocaljQueryPath(), $this->js_dir.'/jquery.js'); - copy(iljQueryUtil::getLocaljQueryUIPath(), $this->js_dir.'/jquery-ui-min.js'); - copy(iljQueryUtil::getLocalMaphilightPath(), $this->js_dir.'/maphilight.js'); - - // yui stuff we use - include_once("./Services/YUI/classes/class.ilYuiUtil.php"); - copy(ilYuiUtil::getLocalPath('yahoo/yahoo-min.js'), - $this->js_yahoo_dir.'/yahoo-min.js'); - copy(ilYuiUtil::getLocalPath('yahoo-dom-event/yahoo-dom-event.js'), - $this->js_yahoo_dir.'/yahoo-dom-event.js'); - copy(ilYuiUtil::getLocalPath('animation/animation-min.js'), - $this->js_yahoo_dir.'/animation-min.js'); - copy(ilYuiUtil::getLocalPath('container/container-min.js'), - $this->js_yahoo_dir.'/container-min.js'); - copy(ilYuiUtil::getLocalPath('container/assets/skins/sam/container.css'), - $this->css_dir.'/container.css'); - copy(ilYuiUtil::getLocalPath('container/assets/skins/sam/container.css'), - $this->css_dir.'/yahoo/container.css'); // see #23083 - - // accordion - include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); - foreach (ilAccordionGUI::getLocalJavascriptFiles() as $f) - { - $tfile = $this->exp_dir."/".$f; - ilUtil::makeDirParents(dirname($tfile)); - copy($f, $tfile); - } - foreach (ilAccordionGUI::getLocalCssFiles() as $f) - { - $tfile = $this->exp_dir."/".$f; - ilUtil::makeDirParents(dirname($tfile)); - copy($f, $tfile); - } - - copy('./Services/Accordion/js/accordion.js', - $this->js_dir.'/accordion.js'); - copy('./Services/Accordion/css/accordion.css', - $this->css_dir.'/accordion.css'); - - // page presentation js - copy('./Services/COPage/js/ilCOPagePres.js', - $this->js_dir.'/ilCOPagePres.js'); - - // tooltip - copy('./Services/UIComponent/Tooltip/js/ilTooltip.js', - $this->js_dir.'/ilTooltip.js'); - - // mediaelement.js - include_once("./Services/MediaObjects/classes/class.ilPlayerUtil.php"); - ilPlayerUtil::copyPlayerFilesToTargetDirectory($this->flv_dir); - - // matching / multiple choice - question - copy('./Modules/TestQuestionPool/js/ilMatchingQuestion.js', - $this->js_dir.'/ilMatchingQuestion.js'); - copy('./Modules/TestQuestionPool/js/ilAssMultipleChoice.js', - $this->js_dir.'/ilAssMultipleChoice.js'); - copy('./Modules/TestQuestionPool/templates/default/test_javascript.css', - $this->css_dir.'/test_javascript.css'); - - // auto linking js - include_once("./Services/Link/classes/class.ilLinkifyUtil.php"); - foreach (ilLinkifyUtil::getLocalJsPaths() as $p) - { - if (is_int(strpos($p, "ExtLink"))) - { - copy($p, $this->js_dir.'/ilExtLink.js'); - } - if (is_int(strpos($p, "linkify"))) - { - copy($p, $this->js_dir.'/linkify.js'); - } - } - - -// copy(ilPlayerUtil::getLocalMediaElementCssPath(), + /** + * @var array + */ + protected $mobs = array(); + + /** + * @var array + */ + protected $files = array(); + + /** + * @var array + */ + protected $files_direct = array(); + + /** + * @var string + */ + protected $exp_dir = ""; + + /** + * @var int + */ + protected $content_style_id = 0; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilLogger + */ + protected $log; + + /** + * ilCOPageHTMLExport constructor. + * @param $a_exp_dir + */ + public function __construct($a_exp_dir) + { + global $DIC; + + $this->log = ilLoggerFactory::getLogger('copg'); + $this->user = $DIC->user(); + + $this->exp_dir = $a_exp_dir; + $this->mobs_dir = $a_exp_dir . "/mobs"; + $this->files_dir = $a_exp_dir . "/files"; + $this->tex_dir = $a_exp_dir . "/teximg"; + $this->content_style_dir = $a_exp_dir . "/content_style"; + $this->content_style_img_dir = $a_exp_dir . "/content_style/images"; + + include_once("./Services/MediaObjects/classes/class.ilPlayerUtil.php"); + $this->services_dir = $a_exp_dir . "/Services"; + $this->media_service_dir = $this->services_dir . "/MediaObjects"; + $this->flv_dir = $a_exp_dir . "/" . ilPlayerUtil::getFlashVideoPlayerDirectory(); + $this->mp3_dir = $this->media_service_dir . "/flash_mp3_player"; + + $this->js_dir = $a_exp_dir . '/js'; + $this->js_yahoo_dir = $a_exp_dir . '/js/yahoo'; + $this->css_dir = $a_exp_dir . '/css'; + } + + /** + * Set content style id + * + * @param int $a_val content style id + */ + public function setContentStyleId($a_val) + { + $this->content_style_id = $a_val; + } + + /** + * Get content style id + * + * @return int content style id + */ + public function getContentStyleId() + { + return $this->content_style_id; + } + + /** + * Create directories + * + * @param + * @return + */ + public function createDirectories() + { + ilUtil::makeDir($this->mobs_dir); + ilUtil::makeDir($this->files_dir); + ilUtil::makeDir($this->tex_dir); + ilUtil::makeDir($this->content_style_dir); + ilUtil::makeDir($this->content_style_img_dir); + ilUtil::makeDir($this->services_dir); + ilUtil::makeDir($this->media_service_dir); + ilUtil::makeDir($this->flv_dir); + ilUtil::makeDir($this->mp3_dir); + + ilUtil::makeDir($this->js_dir); + ilUtil::makeDir($this->js_yahoo_dir); + ilUtil::makeDir($this->css_dir); + ilUtil::makeDir($this->css_dir . "/yahoo"); + } + + /** + * Export content style + * + * @param + * @return + */ + public function exportStyles() + { + $this->log->debug("export styles"); + + include_once "Services/Style/Content/classes/class.ilObjStyleSheet.php"; + + // export content style sheet + if ($this->getContentStyleId() < 1) { + $cont_stylesheet = "./Services/COPage/css/content.css"; + + $css = fread(fopen($cont_stylesheet, 'r'), filesize($cont_stylesheet)); + preg_match_all("/url\(([^\)]*)\)/", $css, $files); + foreach (array_unique($files[1]) as $fileref) { + if (is_file(str_replace("..", ".", $fileref))) { + copy(str_replace("..", ".", $fileref), $this->content_style_img_dir . "/" . basename($fileref)); + } + $css = str_replace($fileref, "images/" . basename($fileref), $css); + } + fwrite(fopen($this->content_style_dir . "/content.css", 'w'), $css); + } else { + $style = new ilObjStyleSheet($this->getContentStyleId()); + $style->writeCSSFile($this->content_style_dir . "/content.css", "images"); + $style->copyImagesToDir($this->content_style_img_dir); + } + + // export syntax highlighting style + $syn_stylesheet = ilObjStyleSheet::getSyntaxStylePath(); + copy($syn_stylesheet, $this->exp_dir . "/syntaxhighlight.css"); + } + + /** + * Export support scripts + * + * @todo: use ilPageContent js/css functions here (problem: currently they need a page object for init) + * + * @param + * @return + */ + public function exportSupportScripts() + { + $this->log->debug("export scripts"); + + // basic js + copy('./Services/JavaScript/js/Basic.js', $this->js_dir . '/Basic.js'); + + copy('./Services/UIComponent/Overlay/js/ilOverlay.js', $this->js_dir . '/ilOverlay.js'); + + // jquery + include_once("./Services/jQuery/classes/class.iljQueryUtil.php"); + copy(iljQueryUtil::getLocaljQueryPath(), $this->js_dir . '/jquery.js'); + copy(iljQueryUtil::getLocaljQueryUIPath(), $this->js_dir . '/jquery-ui-min.js'); + copy(iljQueryUtil::getLocalMaphilightPath(), $this->js_dir . '/maphilight.js'); + + // yui stuff we use + include_once("./Services/YUI/classes/class.ilYuiUtil.php"); + copy( + ilYuiUtil::getLocalPath('yahoo/yahoo-min.js'), + $this->js_yahoo_dir . '/yahoo-min.js' + ); + copy( + ilYuiUtil::getLocalPath('yahoo-dom-event/yahoo-dom-event.js'), + $this->js_yahoo_dir . '/yahoo-dom-event.js' + ); + copy( + ilYuiUtil::getLocalPath('animation/animation-min.js'), + $this->js_yahoo_dir . '/animation-min.js' + ); + copy( + ilYuiUtil::getLocalPath('container/container-min.js'), + $this->js_yahoo_dir . '/container-min.js' + ); + copy( + ilYuiUtil::getLocalPath('container/assets/skins/sam/container.css'), + $this->css_dir . '/container.css' + ); + copy( + ilYuiUtil::getLocalPath('container/assets/skins/sam/container.css'), + $this->css_dir . '/yahoo/container.css' + ); // see #23083 + + // accordion + include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); + foreach (ilAccordionGUI::getLocalJavascriptFiles() as $f) { + $tfile = $this->exp_dir . "/" . $f; + ilUtil::makeDirParents(dirname($tfile)); + copy($f, $tfile); + } + foreach (ilAccordionGUI::getLocalCssFiles() as $f) { + $tfile = $this->exp_dir . "/" . $f; + ilUtil::makeDirParents(dirname($tfile)); + copy($f, $tfile); + } + + copy( + './Services/Accordion/js/accordion.js', + $this->js_dir . '/accordion.js' + ); + copy( + './Services/Accordion/css/accordion.css', + $this->css_dir . '/accordion.css' + ); + + // page presentation js + copy( + './Services/COPage/js/ilCOPagePres.js', + $this->js_dir . '/ilCOPagePres.js' + ); + + // tooltip + copy( + './Services/UIComponent/Tooltip/js/ilTooltip.js', + $this->js_dir . '/ilTooltip.js' + ); + + // mediaelement.js + include_once("./Services/MediaObjects/classes/class.ilPlayerUtil.php"); + ilPlayerUtil::copyPlayerFilesToTargetDirectory($this->flv_dir); + + // matching / multiple choice - question + copy( + './Modules/TestQuestionPool/js/ilMatchingQuestion.js', + $this->js_dir . '/ilMatchingQuestion.js' + ); + copy( + './Modules/TestQuestionPool/js/ilAssMultipleChoice.js', + $this->js_dir . '/ilAssMultipleChoice.js' + ); + copy( + './Modules/TestQuestionPool/templates/default/test_javascript.css', + $this->css_dir . '/test_javascript.css' + ); + + // auto linking js + include_once("./Services/Link/classes/class.ilLinkifyUtil.php"); + foreach (ilLinkifyUtil::getLocalJsPaths() as $p) { + if (is_int(strpos($p, "ExtLink"))) { + copy($p, $this->js_dir . '/ilExtLink.js'); + } + if (is_int(strpos($p, "linkify"))) { + copy($p, $this->js_dir . '/linkify.js'); + } + } + + + // copy(ilPlayerUtil::getLocalMediaElementCssPath(), // $this->css_dir.'/mediaelementplayer.css'); // copy(ilPlayerUtil::getLocalMediaElementJsPath(), // $this->js_dir.'/mediaelement-and-player.js'); - } - - /** - * Get prepared main template - * - * @param - * @return - */ - function getPreparedMainTemplate($a_tpl = "") - { - $this->log->debug("get main template"); - - include_once("./Services/MediaObjects/classes/class.ilPlayerUtil.php"); - - if ($a_tpl != "") - { - $tpl = $a_tpl; - } - else - { - // template workaround: reset of template - $tpl = new ilTemplate("tpl.main.html", true, true); - } - - // scripts needed - $scripts = array("./js/yahoo/yahoo-min.js", "./js/yahoo/yahoo-dom-event.js", - "./js/yahoo/animation-min.js", "./js/yahoo/container-min.js", "./js/jquery.js", - "./js/Basic.js", "./js/jquery-ui-min.js", - "./js/ilOverlay.js", "./js/ilCOPagePres.js", - "./js/ilTooltip.js", "./js/maphilight.js", "./js/ilMatchingQuestion.js", "./js/ilAssMultipleChoice.js", - "./js/ilExtLink.js", "./js/linkify.js"); - $scripts = array_merge($scripts, ilPlayerUtil::getJsFilePaths()); - - $mathJaxSetting = new ilSetting("MathJax"); - $use_mathjax = $mathJaxSetting->get("enable"); - if ($use_mathjax) - { - $scripts[] = $mathJaxSetting->get("path_to_mathjax"); - } - - // accordion - include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); - foreach (ilAccordionGUI::getLocalJavascriptFiles() as $f) - { - $scripts[] = $f; - } - - foreach ($scripts as $script) - { - $tpl->setCurrentBlock("js_file"); - $tpl->setVariable("JS_FILE", $script); - $tpl->parseCurrentBlock(); - } - - // css files needed - $style_name = $this->user->prefs["style"].".css"; - $css_files = array("./css/container.css", - "./content_style/content.css", "./style/".$style_name, "./css/test_javascript.css"); - $css_files = array_merge($css_files, ilPlayerUtil::getCssFilePaths()); - - // accordion - include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); - foreach (ilAccordionGUI::getLocalCssFiles() as $f) - { - $css_files[] = $f; - } - - - foreach ($css_files as $css) - { - $tpl->setCurrentBlock("css_file"); - $tpl->setVariable("CSS_FILE", $css); - $tpl->parseCurrentBlock(); - } - - return $tpl; - } - - /** - * Collect page elements (that need to be exported separately) - * - * @param string $a_pg_type page type - * @param int $a_pg_id page id - */ - function collectPageElements($a_type, $a_id) - { - $this->log->debug("collect page elements"); - - // collect media objects - $pg_mobs = ilObjMediaObject::_getMobsOfObject($a_type, $a_id); - foreach($pg_mobs as $pg_mob) - { - $this->mobs[$pg_mob] = $pg_mob; - } - - // collect all files - include_once("./Modules/File/classes/class.ilObjFile.php"); - $files = ilObjFile::_getFilesOfObject($a_type, $a_id); - foreach($files as $f) - { - $this->files[$f] = $f; - } - - - $skill_tree = $ws_tree = null; - - $pcs = ilPageContentUsage::getUsagesOfPage($a_id, $a_type); - foreach ($pcs as $pc) - { - // skils - if ($pc["type"] == "skmg") - { - $skill_id = $pc["id"]; - - // trying to find user id - $user_id = null; - switch($a_type) - { - case "prtf:pg": - include_once "Modules/Portfolio/classes/class.ilPortfolioPage.php"; - $page = new ilPortfolioPage($a_id); - $user_id = $page->create_user; - break; - - default: - // :TODO: - break; - } - - if($user_id) - { - // we only need 1 instance each - if(!$skill_tree) - { - include_once "Services/Skill/classes/class.ilSkillTree.php"; - $skill_tree = new ilSkillTree(); - - include_once "Services/Skill/classes/class.ilPersonalSkill.php"; - - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - $ws_tree = new ilWorkspaceTree($user_id); - } - - // walk skill tree - include_once("./Services/Skill/classes/class.ilVirtualSkillTree.php"); - $vtree = new ilVirtualSkillTree(); - $tref_id = 0; - $skill_id = (int) $skill_id; - include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); - if (ilSkillTreeNode::_lookupType($skill_id) == "sktr") - { - include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); - $tref_id = $skill_id; - $skill_id = ilSkillTemplateReference::_lookupTemplateId($skill_id); - } - $b_skills = $vtree->getSubTreeForCSkillId($skill_id.":".$tref_id, true); - - foreach ($b_skills as $bs) - { - $skill = ilSkillTreeNodeFactory::getInstance($bs["skill_id"]); - $level_data = $skill->getLevelData(); - foreach ($level_data as $k => $v) - { - // get assigned materials from personal skill - $mat = ilPersonalSkill::getAssignedMaterial($user_id, $bs["tref_id"], $v["id"]); - if(sizeof($mat)) - { - foreach($mat as $item) - { - $wsp_id = $item["wsp_id"]; - $obj_id = $ws_tree->lookupObjectId($wsp_id); - - // all possible material types for now - switch(ilObject::_lookupType($obj_id)) - { - case "file": - $this->files[$obj_id] = $obj_id; - break; - - case "tstv": - include_once "Modules/Test/classes/class.ilObjTestVerification.php"; - $obj = new ilObjTestVerification($obj_id, false); - $this->files_direct[$obj_id] = array($obj->getFilePath(), - $obj->getOfflineFilename()); - break; - - case "excv": - include_once "Modules/Exercise/classes/class.ilObjExerciseVerification.php"; - $obj = new ilObjExerciseVerification($obj_id, false); - $this->files_direct[$obj_id] = array($obj->getFilePath(), - $obj->getOfflineFilename()); - break; - - case "crsv": - include_once "Modules/Course/classes/Verification/class.ilObjCourseVerification.php"; - $obj = new ilObjCourseVerification($obj_id, false); - $this->files_direct[$obj_id] = array($obj->getFilePath(), - $obj->getOfflineFilename()); - break; - - case "scov": - include_once "Modules/ScormAicc/classes/Verification/class.ilObjSCORMVerification.php"; - $obj = new ilObjSCORMVerification($obj_id, false); - $this->files_direct[$obj_id] = array($obj->getFilePath(), - $obj->getOfflineFilename()); - break; - } - } - } - } - } - } - } - } - - } - - /** - * Export page elements - * - * @param - * @return - */ - function exportPageElements($a_update_callback = null) - { - $this->log->debug("export page elements"); - - $total = count($this->mobs) + count($this->files) + count($this->files_direct); - $cnt = 0; - - // export all media objects - $linked_mobs = array(); - foreach ($this->mobs as $mob) - { - if (ilObject::_exists($mob) && ilObject::_lookupType($mob) == "mob") - { - $this->exportHTMLMOB($mob, $linked_mobs); - } - if (is_callable($a_update_callback)) - { - $cnt++; - $a_update_callback($total, $cnt); - } - } - $linked_mobs2 = array(); // mobs linked in link areas - foreach ($linked_mobs as $mob) - { - if (ilObject::_exists($mob)) - { - $this->exportHTMLMOB($mob, $linked_mobs2); - } - } - - // export all file objects - foreach ($this->files as $file) - { - $this->exportHTMLFile($file); - if (is_callable($a_update_callback)) - { - $cnt++; - $a_update_callback($total, $cnt); - } - } - - // export all files (which are not objects - foreach ($this->files_direct as $file_id => $attr) - { - $this->exportHTMLFileDirect($file_id, $attr[0], $attr[1]); - if (is_callable($a_update_callback)) - { - $cnt++; - $a_update_callback($total, $cnt); - } - } - } - - /** - * Export media object to html - */ - function exportHTMLMOB($a_mob_id, &$a_linked_mobs) - { - $this->log->debug("export html mobs"); - - $source_dir = ilUtil::getWebspaceDir()."/mobs/mm_".$a_mob_id; - if (is_dir($source_dir)) - { - ilUtil::makeDir($this->mobs_dir."/mm_".$a_mob_id); - ilUtil::rCopy($source_dir, $this->mobs_dir."/mm_".$a_mob_id); - } - - // #12930 - fullscreen - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $mob_obj = new ilObjMediaObject($a_mob_id); - if ($mob_obj->hasFullscreenItem()) - { - // render media object html - $xh = xslt_create(); - $output = xslt_process( - $xh, - "arg:/_xml", - "arg:/_xsl", - NULL, - array( - "/_xml" => - "". - $mob_obj->getXML(IL_MODE_ALIAS). - $mob_obj->getXML(IL_MODE_OUTPUT). - "", - "/_xsl" => file_get_contents("./Services/COPage/xsl/page.xsl") - ), - array("mode"=>"fullscreen")); - xslt_free($xh); - unset($xh); - - // render fullscreen html - $tpl = new ilTemplate("tpl.fullscreen.html", true, true, "Services/COPage"); - $tpl = $this->getPreparedMainTemplate($tpl); // adds js/css - $tpl->setCurrentBlock("ilMedia"); - $tpl->setVariable("MEDIA_CONTENT", $output); - $output = $tpl->get(); - unset($tpl); - - // write file - $file = $this->exp_dir."/fullscreen_".$a_mob_id.".html"; - if(!($fp = @fopen($file,"w+"))) - { - die("Error: Could not open \"".$file."\" for writing". - " in ".__FILE__." on line ".__LINE__."
"); - } - chmod($file, 0770); - fwrite($fp, $output); - fclose($fp); - unset($fp); - unset($output); - } - - $linked_mobs = $mob_obj->getLinkedMediaObjects(); - $a_linked_mobs = array_merge($a_linked_mobs, $linked_mobs); - } - - /** - * Export file object - */ - function exportHTMLFile($a_file_id) - { - $file_dir = $this->files_dir."/file_".$a_file_id; - ilUtil::makeDir($file_dir); - - include_once("./Modules/File/classes/class.ilObjFile.php"); - $file_obj = new ilObjFile($a_file_id, false); - $source_file = $file_obj->getDirectory($file_obj->getVersion())."/".$file_obj->getFileName(); - if (!is_file($source_file)) - { - $source_file = $file_obj->getDirectory()."/".$file_obj->getFileName(); - } - if (is_file($source_file)) - { - copy($source_file, $file_dir."/".$file_obj->getFileName()); - } - } - - /** - * Export file from path - */ - function exportHTMLFileDirect($a_file_id, $a_source_file, $a_file_name) - { - $file_dir = $this->files_dir."/file_".$a_file_id; - ilUtil::makeDir($file_dir); - - if (is_file($a_source_file)) - { - copy($a_source_file, - $file_dir."/".ilUtil::getASCIIFilename($a_file_name)); - } - } - + } + + /** + * Get prepared main template + * + * @param + * @return + */ + public function getPreparedMainTemplate($a_tpl = "") + { + $this->log->debug("get main template"); + + include_once("./Services/MediaObjects/classes/class.ilPlayerUtil.php"); + + if ($a_tpl != "") { + $tpl = $a_tpl; + } else { + // template workaround: reset of template + $tpl = new ilTemplate("tpl.main.html", true, true); + } + + // scripts needed + $scripts = array("./js/yahoo/yahoo-min.js", "./js/yahoo/yahoo-dom-event.js", + "./js/yahoo/animation-min.js", "./js/yahoo/container-min.js", "./js/jquery.js", + "./js/Basic.js", "./js/jquery-ui-min.js", + "./js/ilOverlay.js", "./js/ilCOPagePres.js", + "./js/ilTooltip.js", "./js/maphilight.js", "./js/ilMatchingQuestion.js", "./js/ilAssMultipleChoice.js", + "./js/ilExtLink.js", "./js/linkify.js"); + $scripts = array_merge($scripts, ilPlayerUtil::getJsFilePaths()); + + $mathJaxSetting = new ilSetting("MathJax"); + $use_mathjax = $mathJaxSetting->get("enable"); + if ($use_mathjax) { + $scripts[] = $mathJaxSetting->get("path_to_mathjax"); + } + + // accordion + include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); + foreach (ilAccordionGUI::getLocalJavascriptFiles() as $f) { + $scripts[] = $f; + } + + foreach ($scripts as $script) { + $tpl->setCurrentBlock("js_file"); + $tpl->setVariable("JS_FILE", $script); + $tpl->parseCurrentBlock(); + } + + // css files needed + $style_name = $this->user->prefs["style"] . ".css"; + $css_files = array("./css/container.css", + "./content_style/content.css", "./style/" . $style_name, "./css/test_javascript.css"); + $css_files = array_merge($css_files, ilPlayerUtil::getCssFilePaths()); + + // accordion + include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); + foreach (ilAccordionGUI::getLocalCssFiles() as $f) { + $css_files[] = $f; + } + + + foreach ($css_files as $css) { + $tpl->setCurrentBlock("css_file"); + $tpl->setVariable("CSS_FILE", $css); + $tpl->parseCurrentBlock(); + } + + return $tpl; + } + + /** + * Collect page elements (that need to be exported separately) + * + * @param string $a_pg_type page type + * @param int $a_pg_id page id + */ + public function collectPageElements($a_type, $a_id) + { + $this->log->debug("collect page elements"); + + // collect media objects + $pg_mobs = ilObjMediaObject::_getMobsOfObject($a_type, $a_id); + foreach ($pg_mobs as $pg_mob) { + $this->mobs[$pg_mob] = $pg_mob; + } + + // collect all files + include_once("./Modules/File/classes/class.ilObjFile.php"); + $files = ilObjFile::_getFilesOfObject($a_type, $a_id); + foreach ($files as $f) { + $this->files[$f] = $f; + } + + + $skill_tree = $ws_tree = null; + + $pcs = ilPageContentUsage::getUsagesOfPage($a_id, $a_type); + foreach ($pcs as $pc) { + // skils + if ($pc["type"] == "skmg") { + $skill_id = $pc["id"]; + + // trying to find user id + $user_id = null; + switch ($a_type) { + case "prtf:pg": + include_once "Modules/Portfolio/classes/class.ilPortfolioPage.php"; + $page = new ilPortfolioPage($a_id); + $user_id = $page->create_user; + break; + + default: + // :TODO: + break; + } + + if ($user_id) { + // we only need 1 instance each + if (!$skill_tree) { + include_once "Services/Skill/classes/class.ilSkillTree.php"; + $skill_tree = new ilSkillTree(); + + include_once "Services/Skill/classes/class.ilPersonalSkill.php"; + + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + $ws_tree = new ilWorkspaceTree($user_id); + } + + // walk skill tree + include_once("./Services/Skill/classes/class.ilVirtualSkillTree.php"); + $vtree = new ilVirtualSkillTree(); + $tref_id = 0; + $skill_id = (int) $skill_id; + include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); + if (ilSkillTreeNode::_lookupType($skill_id) == "sktr") { + include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); + $tref_id = $skill_id; + $skill_id = ilSkillTemplateReference::_lookupTemplateId($skill_id); + } + $b_skills = $vtree->getSubTreeForCSkillId($skill_id . ":" . $tref_id, true); + + foreach ($b_skills as $bs) { + $skill = ilSkillTreeNodeFactory::getInstance($bs["skill_id"]); + $level_data = $skill->getLevelData(); + foreach ($level_data as $k => $v) { + // get assigned materials from personal skill + $mat = ilPersonalSkill::getAssignedMaterial($user_id, $bs["tref_id"], $v["id"]); + if (sizeof($mat)) { + foreach ($mat as $item) { + $wsp_id = $item["wsp_id"]; + $obj_id = $ws_tree->lookupObjectId($wsp_id); + + // all possible material types for now + switch (ilObject::_lookupType($obj_id)) { + case "file": + $this->files[$obj_id] = $obj_id; + break; + + case "tstv": + include_once "Modules/Test/classes/class.ilObjTestVerification.php"; + $obj = new ilObjTestVerification($obj_id, false); + $this->files_direct[$obj_id] = array($obj->getFilePath(), + $obj->getOfflineFilename()); + break; + + case "excv": + include_once "Modules/Exercise/classes/class.ilObjExerciseVerification.php"; + $obj = new ilObjExerciseVerification($obj_id, false); + $this->files_direct[$obj_id] = array($obj->getFilePath(), + $obj->getOfflineFilename()); + break; + + case "crsv": + include_once "Modules/Course/classes/Verification/class.ilObjCourseVerification.php"; + $obj = new ilObjCourseVerification($obj_id, false); + $this->files_direct[$obj_id] = array($obj->getFilePath(), + $obj->getOfflineFilename()); + break; + + case "scov": + include_once "Modules/ScormAicc/classes/Verification/class.ilObjSCORMVerification.php"; + $obj = new ilObjSCORMVerification($obj_id, false); + $this->files_direct[$obj_id] = array($obj->getFilePath(), + $obj->getOfflineFilename()); + break; + } + } + } + } + } + } + } + } + } + + /** + * Export page elements + * + * @param + * @return + */ + public function exportPageElements($a_update_callback = null) + { + $this->log->debug("export page elements"); + + $total = count($this->mobs) + count($this->files) + count($this->files_direct); + $cnt = 0; + + // export all media objects + $linked_mobs = array(); + foreach ($this->mobs as $mob) { + if (ilObject::_exists($mob) && ilObject::_lookupType($mob) == "mob") { + $this->exportHTMLMOB($mob, $linked_mobs); + } + if (is_callable($a_update_callback)) { + $cnt++; + $a_update_callback($total, $cnt); + } + } + $linked_mobs2 = array(); // mobs linked in link areas + foreach ($linked_mobs as $mob) { + if (ilObject::_exists($mob)) { + $this->exportHTMLMOB($mob, $linked_mobs2); + } + } + + // export all file objects + foreach ($this->files as $file) { + $this->exportHTMLFile($file); + if (is_callable($a_update_callback)) { + $cnt++; + $a_update_callback($total, $cnt); + } + } + + // export all files (which are not objects + foreach ($this->files_direct as $file_id => $attr) { + $this->exportHTMLFileDirect($file_id, $attr[0], $attr[1]); + if (is_callable($a_update_callback)) { + $cnt++; + $a_update_callback($total, $cnt); + } + } + } + + /** + * Export media object to html + */ + public function exportHTMLMOB($a_mob_id, &$a_linked_mobs) + { + $this->log->debug("export html mobs"); + + $source_dir = ilUtil::getWebspaceDir() . "/mobs/mm_" . $a_mob_id; + if (is_dir($source_dir)) { + ilUtil::makeDir($this->mobs_dir . "/mm_" . $a_mob_id); + ilUtil::rCopy($source_dir, $this->mobs_dir . "/mm_" . $a_mob_id); + } + + // #12930 - fullscreen + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $mob_obj = new ilObjMediaObject($a_mob_id); + if ($mob_obj->hasFullscreenItem()) { + // render media object html + $xh = xslt_create(); + $output = xslt_process( + $xh, + "arg:/_xml", + "arg:/_xsl", + null, + array( + "/_xml" => + "" . + $mob_obj->getXML(IL_MODE_ALIAS) . + $mob_obj->getXML(IL_MODE_OUTPUT) . + "", + "/_xsl" => file_get_contents("./Services/COPage/xsl/page.xsl") + ), + array("mode"=>"fullscreen") + ); + xslt_free($xh); + unset($xh); + + // render fullscreen html + $tpl = new ilTemplate("tpl.fullscreen.html", true, true, "Services/COPage"); + $tpl = $this->getPreparedMainTemplate($tpl); // adds js/css + $tpl->setCurrentBlock("ilMedia"); + $tpl->setVariable("MEDIA_CONTENT", $output); + $output = $tpl->get(); + unset($tpl); + + // write file + $file = $this->exp_dir . "/fullscreen_" . $a_mob_id . ".html"; + if (!($fp = @fopen($file, "w+"))) { + die("Error: Could not open \"" . $file . "\" for writing" . + " in " . __FILE__ . " on line " . __LINE__ . "
"); + } + chmod($file, 0770); + fwrite($fp, $output); + fclose($fp); + unset($fp); + unset($output); + } + + $linked_mobs = $mob_obj->getLinkedMediaObjects(); + $a_linked_mobs = array_merge($a_linked_mobs, $linked_mobs); + } + + /** + * Export file object + */ + public function exportHTMLFile($a_file_id) + { + $file_dir = $this->files_dir . "/file_" . $a_file_id; + ilUtil::makeDir($file_dir); + + include_once("./Modules/File/classes/class.ilObjFile.php"); + $file_obj = new ilObjFile($a_file_id, false); + $source_file = $file_obj->getDirectory($file_obj->getVersion()) . "/" . $file_obj->getFileName(); + if (!is_file($source_file)) { + $source_file = $file_obj->getDirectory() . "/" . $file_obj->getFileName(); + } + if (is_file($source_file)) { + copy($source_file, $file_dir . "/" . $file_obj->getFileName()); + } + } + + /** + * Export file from path + */ + public function exportHTMLFileDirect($a_file_id, $a_source_file, $a_file_name) + { + $file_dir = $this->files_dir . "/file_" . $a_file_id; + ilUtil::makeDir($file_dir); + + if (is_file($a_source_file)) { + copy( + $a_source_file, + $file_dir . "/" . ilUtil::getASCIIFilename($a_file_name) + ); + } + } } - -?> \ No newline at end of file diff --git a/Services/COPage/classes/class.ilCOPageImportConfig.php b/Services/COPage/classes/class.ilCOPageImportConfig.php index ae2628b45b9a8f39cf780849ebaef9a932d455ea..0181ad576f2da1cacf9956498698d21de1d901ed 100644 --- a/Services/COPage/classes/class.ilCOPageImportConfig.php +++ b/Services/COPage/classes/class.ilCOPageImportConfig.php @@ -12,92 +12,90 @@ include_once("./Services/Export/classes/class.ilImportConfig.php"); */ class ilCOPageImportConfig extends ilImportConfig { - protected $update_if_exists = false; - protected $force_lang = ""; - protected $reuse_media = false; - protected $skip_int_link_resolve = false; + protected $update_if_exists = false; + protected $force_lang = ""; + protected $reuse_media = false; + protected $skip_int_link_resolve = false; - /** - * Set update if exists - * - * @param bool $a_val update page if it already exists - */ - function setUpdateIfExists($a_val) - { - $this->update_if_exists = $a_val; - } - - /** - * Get update if exists - * - * @return bool update page if it already exists - */ - function getUpdateIfExists() - { - return $this->update_if_exists; - } - - /** - * Set force language - * - * @param string $a_val language - */ - function setForceLanguage($a_val) - { - $this->force_lang = $a_val; - } - - /** - * Get force language - * - * @return string language - */ - function getForceLanguage() - { - return $this->force_lang; - } + /** + * Set update if exists + * + * @param bool $a_val update page if it already exists + */ + public function setUpdateIfExists($a_val) + { + $this->update_if_exists = $a_val; + } + + /** + * Get update if exists + * + * @return bool update page if it already exists + */ + public function getUpdateIfExists() + { + return $this->update_if_exists; + } + + /** + * Set force language + * + * @param string $a_val language + */ + public function setForceLanguage($a_val) + { + $this->force_lang = $a_val; + } + + /** + * Get force language + * + * @return string language + */ + public function getForceLanguage() + { + return $this->force_lang; + } - //setReuseOriginallyExportedMedia + //setReuseOriginallyExportedMedia - /** - * Set reuse originally exported media - * - * @param bool $a_val reuse originally exported media - */ - function setReuseOriginallyExportedMedia($a_val) - { - $this->reuse_media = $a_val; - } + /** + * Set reuse originally exported media + * + * @param bool $a_val reuse originally exported media + */ + public function setReuseOriginallyExportedMedia($a_val) + { + $this->reuse_media = $a_val; + } - /** - * Get reuse originally exported media - * - * @return bool reuse originally exported media - */ - function getReuseOriginallyExportedMedia() - { - return $this->reuse_media; - } + /** + * Get reuse originally exported media + * + * @return bool reuse originally exported media + */ + public function getReuseOriginallyExportedMedia() + { + return $this->reuse_media; + } - /** - * Set skip internal link resolve - * - * @param bool $a_val do not resolve internal links (as it is done at another place) - */ - function setSkipInternalLinkResolve($a_val) - { - $this->skip_int_link_resolve = $a_val; - } - - /** - * Get skip internal link resolve - * - * @return bool do not resolve internal links (as it is done at another place) - */ - function getSkipInternalLinkResolve() - { - return $this->skip_int_link_resolve; - } + /** + * Set skip internal link resolve + * + * @param bool $a_val do not resolve internal links (as it is done at another place) + */ + public function setSkipInternalLinkResolve($a_val) + { + $this->skip_int_link_resolve = $a_val; + } + + /** + * Get skip internal link resolve + * + * @return bool do not resolve internal links (as it is done at another place) + */ + public function getSkipInternalLinkResolve() + { + return $this->skip_int_link_resolve; + } } - -?> \ No newline at end of file diff --git a/Services/COPage/classes/class.ilCOPageImporter.php b/Services/COPage/classes/class.ilCOPageImporter.php index d4ca50d1dc81cd83fd7b77c022dca56e878015df..76742682cf92220e7003bc6c2fc23c1355a1eebb 100644 --- a/Services/COPage/classes/class.ilCOPageImporter.php +++ b/Services/COPage/classes/class.ilCOPageImporter.php @@ -12,319 +12,292 @@ include_once("./Services/Export/classes/class.ilXmlImporter.php"); */ class ilCOPageImporter extends ilXmlImporter { - /** - * @var ilLogger - */ - protected $log; - - /** - * @var ilCOPageDataSet - */ - protected $ds; - - /** - * Names of active plugins with own importers for additional data - * @var array - */ - protected $importer_plugins = array(); - - /** - * Initialisation - */ - function init() - { - global $DIC; - /** @var ilPluginAdmin $ilPluginAdmin */ - $ilPluginAdmin = $DIC['ilPluginAdmin']; - - include_once("./Services/COPage/classes/class.ilCOPageDataSet.php"); - $this->ds = new ilCOPageDataSet(); - $this->ds->setDSPrefix("ds"); - $this->config = $this->getImport()->getConfig("Services/COPage"); - - $this->log = ilLoggerFactory::getLogger('copg'); - - // collect all page component plugins that have their own exporter - require_once('Services/COPage/classes/class.ilPageComponentPluginImporter.php'); - foreach(ilPluginAdmin::getActivePluginsForSlot(IL_COMP_SERVICE, "COPage", "pgcp") as $plugin_name) - { - if ($ilPluginAdmin->supportsExport(IL_COMP_SERVICE, "COPage", "pgcp", $plugin_name)) - { - require_once('Customizing/global/plugins/Services/COPage/PageComponent/' - .$plugin_name.'/classes/class.il'.$plugin_name.'Importer.php'); - - $this->importer_plugins[] = $plugin_name; - } - } - } - - - /** - * Import XML - * - * @param - * @return - */ - function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) - { - $this->log->debug("entity: ".$a_entity.", id: ".$a_id); - - if ($a_entity == "pgtp") - { - include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); - $parser = new ilDataSetImportParser($a_entity, $this->getSchemaVersion(), - $a_xml, $this->ds, $a_mapping); - } - - if ($a_entity == "pg") - { - $pg_id = $a_mapping->getMapping("Services/COPage", "pg", $a_id); - - $this->log->debug("mapping id: ".$pg_id); - - if ($pg_id != "") - { - $id = explode(":", $pg_id); - if (count($id) == 2) - { - include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); - - while (substr($a_xml, 0, 11) == ""); - - $page_tag = " ".substr($a_xml, 0, $l1+1).""; - $page_data = simplexml_load_string($page_tag); - $lstr = $page_data['Language']; - $p = strpos($a_xml, "") + 13; - $next_xml = "".substr($a_xml, $l1+1, $p - $l1 -1); - - if ($this->config->getForceLanguage() != "") - { - $lstr = $this->config->getForceLanguage(); - } - if ($lstr == "") - { - $lstr = "-"; - } - // see bug #0019049 - $next_xml = str_replace("&", "&", $next_xml); - if ($this->config->getUpdateIfExists() && ilPageObject::_exists($id[0], $id[1], $lstr)) - { - $page = ilPageObjectFactory::getInstance($id[0], $id[1], 0, $lstr); - $page->setImportMode(true); - $page->setXMLContent($next_xml); - $page->updateFromXML(); - $this->extractPluginProperties($page); - } - else - { - $new_page = ilPageObjectFactory::getInstance($id[0]); - $new_page->setImportMode(true); - $new_page->setId($id[1]); - if ($lstr != "" && $lstr != "-") - { - $new_page->setLanguage($lstr); - } - $new_page->setXMLContent($next_xml); - $new_page->setActive(true); - // array_key_exists does NOT work on simplexml! - if (isset($page_data["Active"])) - { - $new_page->setActive($page_data["Active"]); - } - $new_page->setActivationStart($page_data["ActivationStart"]); - $new_page->setActivationEnd($page_data["ActivationEnd"]); - $new_page->setShowActivationInfo($page_data["ShowActivationInfo"]); - $new_page->createFromXML(); - $this->extractPluginProperties($new_page); - } - - $a_xml = substr($a_xml, $p); - if ($lstr == "") - { - $lstr = "-"; - } - $a_mapping->addMapping("Services/COPage", "pgl", $a_id.":".$lstr, $pg_id.":".$lstr); - } - } - } - } - $this->log->debug("done"); - } - - /** - * Final processing - * - * @param array mapping array - */ - function finalProcessing($a_mapping) - { - $this->log->debug("start"); - $pages = $a_mapping->getMappingsOfEntity("Services/COPage", "pgl"); - $media_objects = $a_mapping->getMappingsOfEntity("Services/MediaObjects", "mob"); - $file_objects = $a_mapping->getMappingsOfEntity("Modules/File", "file"); - - $ref_mapping = $a_mapping->getMappingsOfEntity('Services/Container', 'refs'); - - //if (count($media_objects) > 0 || count($file_objects) > 0) - //{ - foreach ($pages as $p) - { - $id = explode(":", $p); - if (count($id) == 3) - { - include_once("./Services/COPage/classes/class.ilPageObject.php"); - if (ilPageObject::_exists($id[0], $id[1], $id[2], true)) - { - include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); - - /** @var ilPageObject $new_page */ - $new_page = ilPageObjectFactory::getInstance($id[0], $id[1], 0, $id[2]); - $new_page->buildDom(); - $med = $new_page->resolveMediaAliases($media_objects, $this->config->getReuseOriginallyExportedMedia()); - $fil = $new_page->resolveFileItems($file_objects); - $new_page->resolveResources($ref_mapping); - $il = false; - if (!$this->config->getSkipInternalLinkResolve()) - { - $il = $new_page->resolveIntLinks(); - $this->log->debug("resolve internal link for page ".$id[0]."-".$id[1]."-".$id[2]); - } - $plug = $this->replacePluginProperties($new_page); - if ($med || $fil || $il || $plug) - { - $new_page->update(false, true); - } - } - } - } - //} - $this->log->debug("end"); - } - - /** - * Extract the properties of the plugged page contents - * The page XML is scanned for plugged contents with own importers - * - * Called from importXmlRepresentation() for each handled page object - * Extracted data is used by plugin importers afterwards - * - * @param ilPageObject $a_page - */ - protected function extractPluginProperties($a_page) - { - if (empty($this->importer_plugins)) - { - return; - } - - $a_page->buildDom(); - $domdoc = $a_page->getDomDoc(); - $xpath = new DOMXPath($domdoc); - $nodes = $xpath->query("//PageContent[child::Plugged]"); - - /** @var DOMElement $pcnode */ - foreach($nodes as $pcnode) - { - // page content id (unique in the page) - $pc_id = $pcnode->getAttribute('PCID'); - $plnode = $pcnode->childNodes->item(0); - $plugin_name = $plnode->getAttribute('PluginName'); - $plugin_version = $plnode->getAttribute('PluginVersion'); - - // additional data will be imported - if (in_array($plugin_name, $this->importer_plugins)) - { - // get the id of the mapped plugged page content - $id = $a_page->getParentType() - . ':' . $a_page->getId() - . ':' . $a_page->getLanguage() - . ':' . $pc_id; - - $properties = array(); - /** @var DOMElement $child */ - foreach($plnode->childNodes as $child) - { - $properties[$child->getAttribute('Name')] = $child->nodeValue; - } - - // statical provision of content to the pluged importer classes - ilPageComponentPluginImporter::setPCVersion($id, $plugin_version); - ilPageComponentPluginImporter::setPCProperties($id, $properties); - } - } - } - - /** - * Replace the properties of the plugged page contents - * The page XML is scanned for plugged contents with own importers - * The pluged content is replace - * - * Called finalProcessing() for each handled page - * Extracted data is used by dependent plugin importers afterwards - * - * @param ilPageObject $a_page - * @return bool page is modified - */ - public function replacePluginProperties($a_page) - { - if (empty($this->importer_plugins)) - { - return false; - } - - $a_page->buildDom(); - $domdoc = $a_page->getDomDoc(); - $xpath = new DOMXPath($domdoc); - $nodes = $xpath->query("//PageContent[child::Plugged]"); - - $modified = false; - - /** @var DOMElement $pcnode */ - foreach($nodes as $pcnode) - { - // page content id (unique in the page) - $pc_id = $pcnode->getAttribute('PCID'); - $plnode = $pcnode->childNodes->item(0); - $plugin_name = $plnode->getAttribute('PluginName'); - - // get the id of the mapped plugged page content - $id = $a_page->getParentType() - . ':' . $a_page->getId() - . ':' . $a_page->getLanguage() - . ':' . $pc_id; - - $plugin_version = ilPageComponentPluginImporter::getPCVersion($id); - $properties = ilPageComponentPluginImporter::getPCProperties($id); - - // update the version if modified by the plugin importer - if (isset($plugin_version)) - { - $plnode->setAttribute('PluginVersion', $plugin_version); - $modified = true; - } - - // update the properties if modified by the plugin importer - if (is_array($properties)) - { - /** @var DOMElement $child */ - foreach($plnode->childNodes as $child) - { - $plnode->removeChild($child); - } - foreach ($properties as $name => $value) - { - $child = new DOMElement('PluggedProperty', $value); - $plnode->appendChild($child); - $child->setAttribute('Name',$name); - } - $modified = true; - } - } - - return $modified; - } + /** + * @var ilLogger + */ + protected $log; + + /** + * @var ilCOPageDataSet + */ + protected $ds; + + /** + * Names of active plugins with own importers for additional data + * @var array + */ + protected $importer_plugins = array(); + + /** + * Initialisation + */ + public function init() + { + global $DIC; + /** @var ilPluginAdmin $ilPluginAdmin */ + $ilPluginAdmin = $DIC['ilPluginAdmin']; + + include_once("./Services/COPage/classes/class.ilCOPageDataSet.php"); + $this->ds = new ilCOPageDataSet(); + $this->ds->setDSPrefix("ds"); + $this->config = $this->getImport()->getConfig("Services/COPage"); + + $this->log = ilLoggerFactory::getLogger('copg'); + + // collect all page component plugins that have their own exporter + require_once('Services/COPage/classes/class.ilPageComponentPluginImporter.php'); + foreach (ilPluginAdmin::getActivePluginsForSlot(IL_COMP_SERVICE, "COPage", "pgcp") as $plugin_name) { + if ($ilPluginAdmin->supportsExport(IL_COMP_SERVICE, "COPage", "pgcp", $plugin_name)) { + require_once('Customizing/global/plugins/Services/COPage/PageComponent/' + . $plugin_name . '/classes/class.il' . $plugin_name . 'Importer.php'); + + $this->importer_plugins[] = $plugin_name; + } + } + } + + + /** + * Import XML + * + * @param + * @return + */ + public function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) + { + $this->log->debug("entity: " . $a_entity . ", id: " . $a_id); + + if ($a_entity == "pgtp") { + include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); + $parser = new ilDataSetImportParser( + $a_entity, + $this->getSchemaVersion(), + $a_xml, + $this->ds, + $a_mapping + ); + } + + if ($a_entity == "pg") { + $pg_id = $a_mapping->getMapping("Services/COPage", "pg", $a_id); + + $this->log->debug("mapping id: " . $pg_id); + + if ($pg_id != "") { + $id = explode(":", $pg_id); + if (count($id) == 2) { + include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); + + while (substr($a_xml, 0, 11) == ""); + + $page_tag = " " . substr($a_xml, 0, $l1+1) . ""; + $page_data = simplexml_load_string($page_tag); + $lstr = $page_data['Language']; + $p = strpos($a_xml, "") + 13; + $next_xml = "" . substr($a_xml, $l1+1, $p - $l1 -1); + + if ($this->config->getForceLanguage() != "") { + $lstr = $this->config->getForceLanguage(); + } + if ($lstr == "") { + $lstr = "-"; + } + // see bug #0019049 + $next_xml = str_replace("&", "&", $next_xml); + if ($this->config->getUpdateIfExists() && ilPageObject::_exists($id[0], $id[1], $lstr)) { + $page = ilPageObjectFactory::getInstance($id[0], $id[1], 0, $lstr); + $page->setImportMode(true); + $page->setXMLContent($next_xml); + $page->updateFromXML(); + $this->extractPluginProperties($page); + } else { + $new_page = ilPageObjectFactory::getInstance($id[0]); + $new_page->setImportMode(true); + $new_page->setId($id[1]); + if ($lstr != "" && $lstr != "-") { + $new_page->setLanguage($lstr); + } + $new_page->setXMLContent($next_xml); + $new_page->setActive(true); + // array_key_exists does NOT work on simplexml! + if (isset($page_data["Active"])) { + $new_page->setActive($page_data["Active"]); + } + $new_page->setActivationStart($page_data["ActivationStart"]); + $new_page->setActivationEnd($page_data["ActivationEnd"]); + $new_page->setShowActivationInfo($page_data["ShowActivationInfo"]); + $new_page->createFromXML(); + $this->extractPluginProperties($new_page); + } + + $a_xml = substr($a_xml, $p); + if ($lstr == "") { + $lstr = "-"; + } + $a_mapping->addMapping("Services/COPage", "pgl", $a_id . ":" . $lstr, $pg_id . ":" . $lstr); + } + } + } + } + $this->log->debug("done"); + } + + /** + * Final processing + * + * @param array mapping array + */ + public function finalProcessing($a_mapping) + { + $this->log->debug("start"); + $pages = $a_mapping->getMappingsOfEntity("Services/COPage", "pgl"); + $media_objects = $a_mapping->getMappingsOfEntity("Services/MediaObjects", "mob"); + $file_objects = $a_mapping->getMappingsOfEntity("Modules/File", "file"); + + $ref_mapping = $a_mapping->getMappingsOfEntity('Services/Container', 'refs'); + + //if (count($media_objects) > 0 || count($file_objects) > 0) + //{ + foreach ($pages as $p) { + $id = explode(":", $p); + if (count($id) == 3) { + include_once("./Services/COPage/classes/class.ilPageObject.php"); + if (ilPageObject::_exists($id[0], $id[1], $id[2], true)) { + include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); + + /** @var ilPageObject $new_page */ + $new_page = ilPageObjectFactory::getInstance($id[0], $id[1], 0, $id[2]); + $new_page->buildDom(); + $med = $new_page->resolveMediaAliases($media_objects, $this->config->getReuseOriginallyExportedMedia()); + $fil = $new_page->resolveFileItems($file_objects); + $new_page->resolveResources($ref_mapping); + $il = false; + if (!$this->config->getSkipInternalLinkResolve()) { + $il = $new_page->resolveIntLinks(); + $this->log->debug("resolve internal link for page " . $id[0] . "-" . $id[1] . "-" . $id[2]); + } + $plug = $this->replacePluginProperties($new_page); + if ($med || $fil || $il || $plug) { + $new_page->update(false, true); + } + } + } + } + //} + $this->log->debug("end"); + } + + /** + * Extract the properties of the plugged page contents + * The page XML is scanned for plugged contents with own importers + * + * Called from importXmlRepresentation() for each handled page object + * Extracted data is used by plugin importers afterwards + * + * @param ilPageObject $a_page + */ + protected function extractPluginProperties($a_page) + { + if (empty($this->importer_plugins)) { + return; + } + + $a_page->buildDom(); + $domdoc = $a_page->getDomDoc(); + $xpath = new DOMXPath($domdoc); + $nodes = $xpath->query("//PageContent[child::Plugged]"); + + /** @var DOMElement $pcnode */ + foreach ($nodes as $pcnode) { + // page content id (unique in the page) + $pc_id = $pcnode->getAttribute('PCID'); + $plnode = $pcnode->childNodes->item(0); + $plugin_name = $plnode->getAttribute('PluginName'); + $plugin_version = $plnode->getAttribute('PluginVersion'); + + // additional data will be imported + if (in_array($plugin_name, $this->importer_plugins)) { + // get the id of the mapped plugged page content + $id = $a_page->getParentType() + . ':' . $a_page->getId() + . ':' . $a_page->getLanguage() + . ':' . $pc_id; + + $properties = array(); + /** @var DOMElement $child */ + foreach ($plnode->childNodes as $child) { + $properties[$child->getAttribute('Name')] = $child->nodeValue; + } + + // statical provision of content to the pluged importer classes + ilPageComponentPluginImporter::setPCVersion($id, $plugin_version); + ilPageComponentPluginImporter::setPCProperties($id, $properties); + } + } + } + + /** + * Replace the properties of the plugged page contents + * The page XML is scanned for plugged contents with own importers + * The pluged content is replace + * + * Called finalProcessing() for each handled page + * Extracted data is used by dependent plugin importers afterwards + * + * @param ilPageObject $a_page + * @return bool page is modified + */ + public function replacePluginProperties($a_page) + { + if (empty($this->importer_plugins)) { + return false; + } + + $a_page->buildDom(); + $domdoc = $a_page->getDomDoc(); + $xpath = new DOMXPath($domdoc); + $nodes = $xpath->query("//PageContent[child::Plugged]"); + + $modified = false; + + /** @var DOMElement $pcnode */ + foreach ($nodes as $pcnode) { + // page content id (unique in the page) + $pc_id = $pcnode->getAttribute('PCID'); + $plnode = $pcnode->childNodes->item(0); + $plugin_name = $plnode->getAttribute('PluginName'); + + // get the id of the mapped plugged page content + $id = $a_page->getParentType() + . ':' . $a_page->getId() + . ':' . $a_page->getLanguage() + . ':' . $pc_id; + + $plugin_version = ilPageComponentPluginImporter::getPCVersion($id); + $properties = ilPageComponentPluginImporter::getPCProperties($id); + + // update the version if modified by the plugin importer + if (isset($plugin_version)) { + $plnode->setAttribute('PluginVersion', $plugin_version); + $modified = true; + } + + // update the properties if modified by the plugin importer + if (is_array($properties)) { + /** @var DOMElement $child */ + foreach ($plnode->childNodes as $child) { + $plnode->removeChild($child); + } + foreach ($properties as $name => $value) { + $child = new DOMElement('PluggedProperty', $value); + $plnode->appendChild($child); + $child->setAttribute('Name', $name); + } + $modified = true; + } + } + + return $modified; + } } - -?> \ No newline at end of file diff --git a/Services/COPage/classes/class.ilCOPageObjDef.php b/Services/COPage/classes/class.ilCOPageObjDef.php index 3570b321b76f70eda308f420021ff74fd83a36f8..b6a90ef539922236adbb6074b7a3803c99625f16 100644 --- a/Services/COPage/classes/class.ilCOPageObjDef.php +++ b/Services/COPage/classes/class.ilCOPageObjDef.php @@ -3,7 +3,7 @@ /* Copyright (c) 1998-2012 ILIAS open source, Extended GPL, see docs/LICENSE */ /** - * COPage page object definition handler + * COPage page object definition handler * * @author Alex Killing * @version $Id$ @@ -11,54 +11,49 @@ */ class ilCOPageObjDef { - static $page_obj_def = null; - - /** - * Init - * - * @param - * @return - */ - static function init() - { - global $DIC; + public static $page_obj_def = null; + + /** + * Init + * + * @param + * @return + */ + public static function init() + { + global $DIC; - $db = $DIC->database(); - - if (self::$page_obj_def == null) - { - $set = $db->query("SELECT * FROM copg_pobj_def "); - while ($rec = $db->fetchAssoc($set)) - { - self::$page_obj_def[$rec["parent_type"]] = $rec; - } - } - } - - /** - * Get definitions - * - * @param - * @return - */ - function getDefinitions() - { - self::init(); - return self::$page_obj_def; - } - - /** - * Get definition by parent type - * - * @param string $a_parent_type parent type - * @return array definition - */ - static function getDefinitionByParentType($a_parent_type) - { - self::init(); - return self::$page_obj_def[$a_parent_type]; - } - + $db = $DIC->database(); + + if (self::$page_obj_def == null) { + $set = $db->query("SELECT * FROM copg_pobj_def "); + while ($rec = $db->fetchAssoc($set)) { + self::$page_obj_def[$rec["parent_type"]] = $rec; + } + } + } + + /** + * Get definitions + * + * @param + * @return + */ + public function getDefinitions() + { + self::init(); + return self::$page_obj_def; + } + + /** + * Get definition by parent type + * + * @param string $a_parent_type parent type + * @return array definition + */ + public static function getDefinitionByParentType($a_parent_type) + { + self::init(); + return self::$page_obj_def[$a_parent_type]; + } } - -?> diff --git a/Services/COPage/classes/class.ilCOPagePCDef.php b/Services/COPage/classes/class.ilCOPagePCDef.php index 5888139a8a6edef640e033e3a25f0d440f8cd0d6..98070f0f9917b2fd74d446c93df8a257b6370fd3 100644 --- a/Services/COPage/classes/class.ilCOPagePCDef.php +++ b/Services/COPage/classes/class.ilCOPagePCDef.php @@ -3,7 +3,7 @@ /* Copyright (c) 1998-2012 ILIAS open source, Extended GPL, see docs/LICENSE */ /** - * COPage PC elements definition handler + * COPage PC elements definition handler * * @author Alex Killing * @version $Id$ @@ -11,137 +11,128 @@ */ class ilCOPagePCDef { - static $pc_def = null; - static $pc_def_by_name = null; - static $pc_gui_classes = array(); - static $pc_gui_classes_lc = array(); - static $pc_def_by_gui_class_cl = array(); - - /** - * Init - * - * @param - * @return - */ - static function init() - { - global $DIC; + public static $pc_def = null; + public static $pc_def_by_name = null; + public static $pc_gui_classes = array(); + public static $pc_gui_classes_lc = array(); + public static $pc_def_by_gui_class_cl = array(); + + /** + * Init + * + * @param + * @return + */ + public static function init() + { + global $DIC; - $db = $DIC->database(); - - if (self::$pc_def == null) - { - $set = $db->query("SELECT * FROM copg_pc_def "); - while ($rec = $db->fetchAssoc($set)) - { - $rec["pc_class"] = "ilPC".$rec["name"]; - $rec["pc_gui_class"] = "ilPC".$rec["name"]."GUI"; - self::$pc_gui_classes[] = $rec["pc_gui_class"]; - self::$pc_gui_classes_lc[] = strtolower($rec["pc_gui_class"]); - self::$pc_def[$rec["pc_type"]] = $rec; - self::$pc_def_by_name[$rec["name"]] = $rec; - self::$pc_def_by_gui_class_cl[strtolower($rec["pc_gui_class"])] = $rec; - } - } - } - - - /** - * Get PC definitions - * - * @param - * @return - */ - static function getPCDefinitions() - { - self::init(); - return self::$pc_def; - } - - /** - * Get PC definition by type - * - * @param string type - * @return array definition - */ - static function getPCDefinitionByType($a_pc_type) - { - self::init(); - return self::$pc_def[$a_pc_type]; - } - - /** - * Get PC definition by name - * - * @param string name - * @return array definition - */ - static function getPCDefinitionByName($a_pc_name) - { - self::init(); - return self::$pc_def_by_name[$a_pc_name]; - } - - /** - * Get PC definition by name - * - * @param string name - * @return array definition - */ - static function getPCDefinitionByGUIClassName($a_gui_class_name) - { - self::init(); - $a_gui_class_name = strtolower($a_gui_class_name); - return self::$pc_def_by_gui_class_cl[$a_gui_class_name]; - } - - /** - * Get instance - * - * @param - * @return - */ - static function requirePCClassByName($a_name) - { - $pc_def = self::getPCDefinitionByName($a_name); - $pc_class = "ilPC".$pc_def["name"]; - $pc_path = "./".$pc_def["component"]."/".$pc_def["directory"]."/class.".$pc_class.".php"; - include_once($pc_path); - } - - /** - * Get instance - * - * @param - * @return - */ - static function requirePCGUIClassByName($a_name) - { - $pc_def = self::getPCDefinitionByName($a_name); - $pc_class = "ilPC".$pc_def["name"]."GUI"; - $pc_path = "./".$pc_def["component"]."/".$pc_def["directory"]."/class.".$pc_class.".php"; - include_once($pc_path); - } - - /** - * Is given class name a pc gui class? - * - * @param - * @return - */ - static function isPCGUIClassName($a_class_name, $a_lower_case = false) - { - if ($a_lower_case) - { - return in_array($a_class_name, self::$pc_gui_classes_lc); - } - else - { - return in_array($a_class_name, self::$pc_gui_classes); - } - } - - + $db = $DIC->database(); + + if (self::$pc_def == null) { + $set = $db->query("SELECT * FROM copg_pc_def "); + while ($rec = $db->fetchAssoc($set)) { + $rec["pc_class"] = "ilPC" . $rec["name"]; + $rec["pc_gui_class"] = "ilPC" . $rec["name"] . "GUI"; + self::$pc_gui_classes[] = $rec["pc_gui_class"]; + self::$pc_gui_classes_lc[] = strtolower($rec["pc_gui_class"]); + self::$pc_def[$rec["pc_type"]] = $rec; + self::$pc_def_by_name[$rec["name"]] = $rec; + self::$pc_def_by_gui_class_cl[strtolower($rec["pc_gui_class"])] = $rec; + } + } + } + + + /** + * Get PC definitions + * + * @param + * @return + */ + public static function getPCDefinitions() + { + self::init(); + return self::$pc_def; + } + + /** + * Get PC definition by type + * + * @param string type + * @return array definition + */ + public static function getPCDefinitionByType($a_pc_type) + { + self::init(); + return self::$pc_def[$a_pc_type]; + } + + /** + * Get PC definition by name + * + * @param string name + * @return array definition + */ + public static function getPCDefinitionByName($a_pc_name) + { + self::init(); + return self::$pc_def_by_name[$a_pc_name]; + } + + /** + * Get PC definition by name + * + * @param string name + * @return array definition + */ + public static function getPCDefinitionByGUIClassName($a_gui_class_name) + { + self::init(); + $a_gui_class_name = strtolower($a_gui_class_name); + return self::$pc_def_by_gui_class_cl[$a_gui_class_name]; + } + + /** + * Get instance + * + * @param + * @return + */ + public static function requirePCClassByName($a_name) + { + $pc_def = self::getPCDefinitionByName($a_name); + $pc_class = "ilPC" . $pc_def["name"]; + $pc_path = "./" . $pc_def["component"] . "/" . $pc_def["directory"] . "/class." . $pc_class . ".php"; + include_once($pc_path); + } + + /** + * Get instance + * + * @param + * @return + */ + public static function requirePCGUIClassByName($a_name) + { + $pc_def = self::getPCDefinitionByName($a_name); + $pc_class = "ilPC" . $pc_def["name"] . "GUI"; + $pc_path = "./" . $pc_def["component"] . "/" . $pc_def["directory"] . "/class." . $pc_class . ".php"; + include_once($pc_path); + } + + /** + * Is given class name a pc gui class? + * + * @param + * @return + */ + public static function isPCGUIClassName($a_class_name, $a_lower_case = false) + { + if ($a_lower_case) { + return in_array($a_class_name, self::$pc_gui_classes_lc); + } else { + return in_array($a_class_name, self::$pc_gui_classes); + } + } } - -?> diff --git a/Services/COPage/classes/class.ilCOPageService.php b/Services/COPage/classes/class.ilCOPageService.php index f5ba2739e3cfcd27fa8569f473d8579141c1c522..0fc11b9d92428dcc1e238f59a73643de7bdb1767 100755 --- a/Services/COPage/classes/class.ilCOPageService.php +++ b/Services/COPage/classes/class.ilCOPageService.php @@ -1,24 +1,24 @@ diff --git a/Services/COPage/classes/class.ilCopySelfAssQuestionTableGUI.php b/Services/COPage/classes/class.ilCopySelfAssQuestionTableGUI.php index 9edfc182704ee0b29800426a5950a270ed47fdbd..47f582a8aaf850bf99fee914d131e8baebfa1082 100644 --- a/Services/COPage/classes/class.ilCopySelfAssQuestionTableGUI.php +++ b/Services/COPage/classes/class.ilCopySelfAssQuestionTableGUI.php @@ -14,133 +14,135 @@ include_once("./Modules/TestQuestionPool/classes/class.assQuestion.php"); */ class ilCopySelfAssQuestionTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var int - */ - protected $pool_ref_id; - - /** - * @var int - */ - protected $pool_obj_id; - - /** - * ilCopySelfAssQuestionTableGUI constructor. - * @param int $a_parent_obj - * @param string $a_parent_cmd - * @param string $a_pool_ref_id - */ - public function __construct($a_parent_obj, $a_parent_cmd, $a_pool_ref_id) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->access = $DIC->access(); - - $this->setId("cont_qpl"); - $this->pool_ref_id = $a_pool_ref_id; - $this->pool_obj_id = ilObject::_lookupObjId($a_pool_ref_id); - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setTitle(ilObject::_lookupTitle($this->pool_obj_id)); - - $this->setFormName('sa_quest_browser'); - - $this->addColumn($this->lng->txt("title"),'title', ''); - $this->addColumn($this->lng->txt("cont_question_type"),'ttype', ''); - $this->addColumn($this->lng->txt("actions"),'', ''); - - - $this->setRowTemplate("tpl.copy_sa_quest_row.html", "Services/COPage"); - - $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); - $this->setDefaultOrderField("title"); - $this->setDefaultOrderDirection("asc"); - - $this->initFilter(); - - $this->getQuestions(); - } - - /** - * Get questions - */ - function getQuestions() - { - global $DIC; - - $access = $this->access; - - include_once("./Modules/TestQuestionPool/classes/class.ilObjQuestionPool.php"); - $all_types = ilObjQuestionPool::_getSelfAssessmentQuestionTypes(); - $all_ids = array(); - foreach ($all_types as $k => $v) - { - $all_ids[] = $v["question_type_id"]; - } - - $questions = array(); - if ($access->checkAccess("read", "", $this->pool_ref_id)) - { - require_once 'Modules/TestQuestionPool/classes/class.ilAssQuestionList.php'; - $questionList = new ilAssQuestionList($DIC->database(), $DIC->language(), - $DIC["ilPluginAdmin"]); - $questionList->setParentObjId($this->pool_obj_id); - $questionList->load(); - - $data = $questionList->getQuestionDataArray(); - - $questions = array(); - foreach ($data as $d) - { - // list only self assessment question types - if (in_array($d["question_type_fi"], $all_ids)) - { - $questions[] = $d; - } - } - - } - $this->setData($questions); - } - - /** - * Fill row - * - * @param array $a_set data array - */ - public function fillRow($a_set) - { - $lng = $this->lng; - $ctrl = $this->ctrl; - - // action: copy - $ctrl->setParameter($this->parent_obj, "q_id", $a_set["question_id"]); - $ctrl->setParameter($this->parent_obj, "subCmd", "copyQuestion"); - $this->tpl->setCurrentBlock("cmd"); - $this->tpl->setVariable("HREF_CMD", - $ctrl->getLinkTarget($this->parent_obj, $this->parent_cmd)); - $this->tpl->setVariable("TXT_CMD", - $lng->txt("cont_copy_question_into_page")); - $this->tpl->parseCurrentBlock(); - $ctrl->setParameter($this->parent_obj, "subCmd", "listPoolQuestions"); - - // properties - $this->tpl->setVariable("TITLE", $a_set["title"]); - $this->tpl->setVariable("TYPE", - assQuestion::_getQuestionTypeName($a_set["type_tag"])); - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var int + */ + protected $pool_ref_id; + + /** + * @var int + */ + protected $pool_obj_id; + + /** + * ilCopySelfAssQuestionTableGUI constructor. + * @param int $a_parent_obj + * @param string $a_parent_cmd + * @param string $a_pool_ref_id + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_pool_ref_id) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->access = $DIC->access(); + + $this->setId("cont_qpl"); + $this->pool_ref_id = $a_pool_ref_id; + $this->pool_obj_id = ilObject::_lookupObjId($a_pool_ref_id); + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setTitle(ilObject::_lookupTitle($this->pool_obj_id)); + + $this->setFormName('sa_quest_browser'); + + $this->addColumn($this->lng->txt("title"), 'title', ''); + $this->addColumn($this->lng->txt("cont_question_type"), 'ttype', ''); + $this->addColumn($this->lng->txt("actions"), '', ''); + + + $this->setRowTemplate("tpl.copy_sa_quest_row.html", "Services/COPage"); + + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd)); + $this->setDefaultOrderField("title"); + $this->setDefaultOrderDirection("asc"); + + $this->initFilter(); + + $this->getQuestions(); + } + + /** + * Get questions + */ + public function getQuestions() + { + global $DIC; + + $access = $this->access; + + include_once("./Modules/TestQuestionPool/classes/class.ilObjQuestionPool.php"); + $all_types = ilObjQuestionPool::_getSelfAssessmentQuestionTypes(); + $all_ids = array(); + foreach ($all_types as $k => $v) { + $all_ids[] = $v["question_type_id"]; + } + + $questions = array(); + if ($access->checkAccess("read", "", $this->pool_ref_id)) { + require_once 'Modules/TestQuestionPool/classes/class.ilAssQuestionList.php'; + $questionList = new ilAssQuestionList( + $DIC->database(), + $DIC->language(), + $DIC["ilPluginAdmin"] + ); + $questionList->setParentObjId($this->pool_obj_id); + $questionList->load(); + + $data = $questionList->getQuestionDataArray(); + + $questions = array(); + foreach ($data as $d) { + // list only self assessment question types + if (in_array($d["question_type_fi"], $all_ids)) { + $questions[] = $d; + } + } + } + $this->setData($questions); + } + + /** + * Fill row + * + * @param array $a_set data array + */ + public function fillRow($a_set) + { + $lng = $this->lng; + $ctrl = $this->ctrl; + + // action: copy + $ctrl->setParameter($this->parent_obj, "q_id", $a_set["question_id"]); + $ctrl->setParameter($this->parent_obj, "subCmd", "copyQuestion"); + $this->tpl->setCurrentBlock("cmd"); + $this->tpl->setVariable( + "HREF_CMD", + $ctrl->getLinkTarget($this->parent_obj, $this->parent_cmd) + ); + $this->tpl->setVariable( + "TXT_CMD", + $lng->txt("cont_copy_question_into_page") + ); + $this->tpl->parseCurrentBlock(); + $ctrl->setParameter($this->parent_obj, "subCmd", "listPoolQuestions"); + + // properties + $this->tpl->setVariable("TITLE", $a_set["title"]); + $this->tpl->setVariable( + "TYPE", + assQuestion::_getQuestionTypeName($a_set["type_tag"]) + ); + } } -?> \ No newline at end of file diff --git a/Services/COPage/classes/class.ilMediaAliasItem.php b/Services/COPage/classes/class.ilMediaAliasItem.php index 729ec4a9286afa825fcc17e1b86cbac37141d26e..4de87826d882b543b35683d71326582987bcc924 100755 --- a/Services/COPage/classes/class.ilMediaAliasItem.php +++ b/Services/COPage/classes/class.ilMediaAliasItem.php @@ -15,841 +15,968 @@ include_once("./Services/Utilities/classes/class.ilDOMUtil.php"); */ class ilMediaAliasItem { - /** - * @var ilLanguage - */ - protected $lng; - - var $dom; - var $hier_id; - var $purpose; - var $item_node; - - function __construct(&$a_dom, $a_hier_id, $a_purpose, $a_pc_id = "", - $a_parent_node_name = "MediaObject") - { - global $DIC; - - $this->lng = $DIC->language(); - $this->dom = $a_dom; - $this->parent_node_name = $a_parent_node_name; - $this->hier_id = $a_hier_id; - $this->purpose = $a_purpose; - $this->setPcId($a_pc_id); - $this->item_node = $this->getMAItemNode($this->hier_id, $this->purpose, - $this->getPcId()); - } - - function getMAItemNode($a_hier_id, $a_purpose, $a_pc_id = "", $a_sub_element = "") - { - if ($a_pc_id != "") - { - $xpc = xpath_new_context($this->dom); - $path = "//PageContent[@PCID = '".$a_pc_id."']/".$this->parent_node_name."/MediaAliasItem[@Purpose='$a_purpose']".$a_sub_element; - $res = xpath_eval($xpc, $path); - if (count($res->nodeset) == 1) - { - return $res->nodeset[0]; - } - } - - $xpc = xpath_new_context($this->dom); - $path = "//PageContent[@HierId = '".$a_hier_id."']/".$this->parent_node_name."/MediaAliasItem[@Purpose='$a_purpose']".$a_sub_element; - $res = xpath_eval($xpc, $path); - if (count($res->nodeset) > 0) - { - return $res->nodeset[0]; - } - } - - function getParameterNodes($a_hier_id, $a_purpose, $a_pc_id = "") - { - if ($a_pc_id != "") - { - $xpc = xpath_new_context($this->dom); - $path = "//PageContent[@PCID = '".$a_pc_id."']/".$this->parent_node_name."/MediaAliasItem[@Purpose='$a_purpose']/Parameter"; - $res = xpath_eval($xpc, $path); - if (count($res->nodeset) > 0) - { - return $res->nodeset; - } - return array(); - } - - $xpc = xpath_new_context($this->dom); - $path = "//PageContent[@HierId = '".$a_hier_id."']/".$this->parent_node_name."/MediaAliasItem[@Purpose='$a_purpose']/Parameter"; - $res = xpath_eval($xpc, $path); - if (count($res->nodeset) > 0) - { - return $res->nodeset; - } - } - - function getMapAreaNodes($a_hier_id, $a_purpose, $a_pc_id = "") - { - if ($a_pc_id != "") - { - $xpc = xpath_new_context($this->dom); - $path = "//PageContent[@PCID = '".$a_pc_id."']/".$this->parent_node_name."/MediaAliasItem[@Purpose='$a_purpose']/MapArea"; - $res = xpath_eval($xpc, $path); - if (count($res->nodeset) > 0) - { - return $res->nodeset; - } - return array(); - } - - $xpc = xpath_new_context($this->dom); - $path = "//PageContent[@HierId = '".$a_hier_id."']/".$this->parent_node_name."/MediaAliasItem[@Purpose='$a_purpose']/MapArea"; - $res = xpath_eval($xpc, $path); - if (count($res->nodeset) > 0) - { - return $res->nodeset; - } - return array(); - } - - /** - * Set PC Id. - * - * @param string $a_pcid PC Id - */ - function setPcId($a_pcid) - { - $this->pcid = $a_pcid; - } - - /** - * Get PC Id. - * - * @return string PC Id - */ - function getPcId() - { - return $this->pcid; - } - - /** - * check if item node exists - * - * @return boolean returns true if item node exists - */ - function exists() - { - if (is_object($this->item_node)) - { - return true; - } - else - { - return false; - } - } - - /** - * inserts new node in dom - */ - function insert() - { - $xpc = xpath_new_context($this->dom); - $path = "//PageContent[@HierId = '".$this->hier_id."']/".$this->parent_node_name; - $res = xpath_eval($xpc, $path); - if (count($res->nodeset) > 0) - { - $obj_node = $res->nodeset[0]; - $item_node = $this->dom->create_element("MediaAliasItem"); - $item_node = $obj_node->append_child($item_node); - $item_node->set_attribute("Purpose", $this->purpose); - $this->item_node = $item_node; - } - } - - /** - * Set width - */ - function setWidth($a_width) - { - ilDOMUtil::setFirstOptionalElement($this->dom, $this->item_node, "Layout", - array("Caption", "TextRepresentation", "Parameter", "MapArea"), - "", array("Width" => $a_width), false); - } - - - /** - * Get width - */ - function getWidth() - { - $layout_node = $this->getMAItemNode($this->hier_id, $this->purpose, - $this->getPcId(), "/Layout"); - if (is_object($layout_node)) - { - return $layout_node->get_attribute("Width"); - } - } - - /** - * check if alias item defines own size or derives size from object - * - * @return boolean returns true if size is not derived from object - */ - function definesSize() - { - $layout_node = $this->getMAItemNode($this->hier_id, $this->purpose, - $this->getPcId(), "/Layout"); - if (is_object($layout_node)) - { - return $layout_node->has_attribute("Width"); - } - return false; - } - - /** - * derive size from object (-> width and height attributes are removed from layout element) - */ - function deriveSize() - { - $layout_node = $this->getMAItemNode($this->hier_id, $this->purpose, - $this->getPcId(), "/Layout"); - if (is_object($layout_node)) - { - if ($layout_node->has_attribute("Width")) - { - $layout_node->remove_attribute("Width"); - } - if ($layout_node->has_attribute("Height")) - { - $layout_node->remove_attribute("Height"); - } - } - } - - /** - * Set Height - */ - function setHeight($a_height) - { - ilDOMUtil::setFirstOptionalElement($this->dom, $this->item_node, "Layout", - array("Caption", "TextRepresentation", "Parameter", "MapArea"), - "", array("Height" => $a_height), false); - } - - - /** - * Get Height - */ - function getHeight() - { - $layout_node = $this->getMAItemNode($this->hier_id, $this->purpose, - $this->getPcId(), "/Layout"); - if (is_object($layout_node)) - { - return $layout_node->get_attribute("Height"); - } - } - - - /** - * Set Caption - */ - function setCaption($a_caption) - { - ilDOMUtil::setFirstOptionalElement($this->dom, $this->item_node, "Caption", - array("TextRepresentation", "Parameter", "MapArea"), - $a_caption, array("Align" => "bottom")); - } - - - /** - * Get Caption - */ - function getCaption() - { - $caption_node = $this->getMAItemNode($this->hier_id, $this->purpose, - $this->getPcId(), "/Caption"); - if (is_object($caption_node)) - { - return $caption_node->get_content(); - } - } - - /** - * check if alias item defines own caption or derives caption from object - * - * @return boolean returns true if caption is not derived from object - */ - function definesCaption() - { - $caption_node = $this->getMAItemNode($this->hier_id, $this->purpose, - $this->getPcId(), "/Caption"); - if (is_object($caption_node)) - { - return true; - } - return false; - } - - /** - * derive caption from object (-> caption element is removed from media alias item) - */ - function deriveCaption() - { - $caption_node = $this->getMAItemNode($this->hier_id, $this->purpose, - $this->getPcId(), "/Caption"); - if (is_object($caption_node)) - { - $caption_node->unlink_node($caption_node); - } - } - - /** - * Set TextRepresentation - */ - function setTextRepresentation($a_text_representation) - { - ilDOMUtil::setFirstOptionalElement($this->dom, $this->item_node, "TextRepresentation", - array("Parameter", "MapArea"), - $a_text_representation, array()); - } - - /** - * Get TextRepresentation - */ - function getTextRepresentation() - { - $text_representation_node = $this->getMAItemNode($this->hier_id, $this->purpose, - $this->getPcId(), "/TextRepresentation"); - if (is_object($text_representation_node)) - { - return $text_representation_node->get_content(); - } - } - - /** - * check if alias item defines own TextRepresentation or derives TextRepresentation from object - * - * @return boolean returns true if TextRepresentation is not derived from object - */ - function definesTextRepresentation() - { - $text_representation_node = $this->getMAItemNode($this->hier_id, $this->purpose, - $this->getPcId(), "/TextRepresentation"); - if (is_object($text_representation_node)) - { - return true; - } - return false; - } - - /** - * derive TextRepresentation from object (-> TextRepresentation element is removed from media alias item) - */ - function deriveTextRepresentation() - { - $text_representation_node = $this->getMAItemNode($this->hier_id, $this->purpose, - $this->getPcId(), "/TextRepresentation"); - if (is_object($text_representation_node)) - { - $text_representation_node->unlink_node($text_representation_node); - } - } - - function setHorizontalAlign($a_halign) - { - ilDOMUtil::setFirstOptionalElement($this->dom, $this->item_node, "Layout", - array("Caption", "TextRepresentation", "Parameter", "MapArea"), - "", array("HorizontalAlign" => $a_halign), false); - } - - - function getHorizontalAlign() - { - $layout_node = $this->getMAItemNode($this->hier_id, $this->purpose, - $this->getPcId(), "/Layout"); - if (is_object($layout_node)) - { - return $layout_node->get_attribute("HorizontalAlign"); - } - } - - /** - * set parameter - */ - function setParameters($a_par_array) - { - $par_nodes = $this->getParameterNodes($this->hier_id, $this->purpose, - $this->getPcId()); - for($i=0; $i < count($par_nodes); $i++) - { - $par_node = $par_nodes[$i]; - $par_node->unlink_node($par_node); - } - - include_once("./Services/MediaObjects/classes/class.ilMediaItem.php"); - if (is_array($a_par_array)) - { - foreach($a_par_array as $par => $val) - { - if (ilMediaItem::checkParameter($par, $val)) - { - $attributes = array("Name" => $par, "Value" => $val); - ilDOMUtil::addElementToList($this->dom, $this->item_node, - "Parameter", array("MapArea"), "", $attributes); - } - } - } - } - - /** - * Get all parameters as string - */ - function getParameterString() - { - $par_nodes = $this->getParameterNodes($this->hier_id, $this->purpose, - $this->getPcId()); - $par_arr = array(); - for($i=0; $i < count($par_nodes); $i++) - { - $par_node = $par_nodes[$i]; - $par_arr[] = $par_node->get_attribute("Name")."=\"".$par_node->get_attribute("Value")."\""; - } - return implode($par_arr, ", "); - } - - /** - * Get all parameters as array - */ - function getParameters() - { - $par_nodes = $this->getParameterNodes($this->hier_id, $this->purpose, - $this->getPcId()); - $par_arr = array(); - for($i=0; $i < count($par_nodes); $i++) - { - $par_node = $par_nodes[$i]; - $par_arr[$par_node->get_attribute("Name")] = - $par_node->get_attribute("Value"); - } - return $par_arr; - } - - /** - * get a single parameter - */ - function getParameter($a_name) - { - } - - /** - * check if alias item defines own parameters or derives parameters from object - * - * @return boolean returns true if parameters are not derived from object - */ - function definesParameters() - { - $par_nodes = $this->getParameterNodes($this->hier_id, $this->purpose, - $this->getPcId()); - if (count($par_nodes) > 0) - { - return true; - } - return false; - } - - /** - * derive parameters from object (-> all parameter elements are removed from media alias item) - */ - function deriveParameters() - { - $par_nodes = $this->getParameterNodes($this->hier_id, $this->purpose, - $this->getPcId()); - if (count($par_nodes) > 0) - { - for($i=0; $i < count($par_nodes); $i++) - { - $par_node = $par_nodes[$i]; - $par_node->unlink_node($par_node); - } - } - } - - - /** - * Get all map areas - */ - function getMapAreas() - { - $ma_nodes = $this->getMapAreaNodes($this->hier_id, $this->purpose, - $this->getPcId()); - $maparea_arr = array(); - for($i=0; $i < count($ma_nodes); $i++) - { - $maparea_node = $ma_nodes[$i]; - $childs = $maparea_node->child_nodes(); - $link = array(); - if ($childs[0]->node_name() == "ExtLink") - { - $link = array("LinkType" => "ExtLink", - "Href" => $childs[0]->get_attribute("Href"), - "Title" => $childs[0]->get_content()); - } - if ($childs[0]->node_name() == "IntLink") - { - $link = array("LinkType" => "IntLink", - "Target" => $childs[0]->get_attribute("Target"), - "Type" => $childs[0]->get_attribute("Type"), - "TargetFrame" => $childs[0]->get_attribute("TargetFame"), - "Title" => $childs[0]->get_content()); - } - $maparea_arr[] = array( - "Nr" => $i + 1, - "Shape" => $maparea_node->get_attribute("Shape"), - "Coords" => $maparea_node->get_attribute("Coords"), - "HighlightMode" => $maparea_node->get_attribute("HighlightMode"), - "HighlightClass" => $maparea_node->get_attribute("HighlightClass"), - "Id" => $maparea_node->get_attribute("Id"), - "Link" => $link); - } - - return $maparea_arr; - } - - /** - * Set title of area - */ - function setAreaTitle($a_nr, $a_title) - { - $ma_nodes = $this->getMapAreaNodes($this->hier_id, $this->purpose, - $this->getPcId()); - if (is_object($ma_nodes[$a_nr - 1])) - { - $childs = $ma_nodes[$a_nr - 1]->child_nodes(); - if (is_object($childs[0]) && - ($childs[0]->node_name() == "IntLink" || $childs[0]->node_name() == "ExtLink")) - { - $childs[0]->set_content($a_title); - } - } - } - - /** - * Set link of area to an internal one - */ - function setAreaIntLink($a_nr, $a_type, $a_target, $a_target_frame) - { - $ma_nodes = $this->getMapAreaNodes($this->hier_id, $this->purpose, - $this->getPcId()); - if (is_object($ma_nodes[$a_nr - 1])) - { - $title = $this->getTitleOfArea($a_nr); - ilDOMUtil::deleteAllChildsByName($ma_nodes[$a_nr - 1], array("IntLink", "ExtLink")); - $attributes = array("Type" => $a_type, "Target" => $a_target, - "TargetFrame" => $a_target_frame); - ilDOMUtil::setFirstOptionalElement($this->dom, $ma_nodes[$a_nr - 1], "IntLink", - array(""), $title, $attributes); - } - } - - /** - * Set link of area to an external one - */ - function setAreaExtLink($a_nr, $a_href) - { - $ma_nodes = $this->getMapAreaNodes($this->hier_id, $this->purpose, - $this->getPcId()); - if (is_object($ma_nodes[$a_nr - 1])) - { - $title = $this->getTitleOfArea($a_nr); - ilDOMUtil::deleteAllChildsByName($ma_nodes[$a_nr - 1], array("IntLink", "ExtLink")); - $attributes = array("Href" => $a_href); - ilDOMUtil::setFirstOptionalElement($this->dom, $ma_nodes[$a_nr - 1], "ExtLink", - array(""), $title, $attributes); - } - } - - /** - * Set shape and coords of single area - */ - function setShape($a_nr, $a_shape_type, $a_coords) - { - $ma_nodes = $this->getMapAreaNodes($this->hier_id, $this->purpose, - $this->getPcId()); - if (is_object($ma_nodes[$a_nr - 1])) - { - $ma_nodes[$a_nr - 1]->set_attribute("Shape", $a_shape_type); - $ma_nodes[$a_nr - 1]->set_attribute("Coords", $a_coords); - } - } - - /** - * Set highlight mode single area - */ - function setAreaHighlightMode($a_nr, $a_mode) - { - $ma_nodes = $this->getMapAreaNodes($this->hier_id, $this->purpose, - $this->getPcId()); - if (is_object($ma_nodes[$a_nr - 1])) - { - $ma_nodes[$a_nr - 1]->set_attribute("HighlightMode", $a_mode); - } - } - - /** - * Set highlight class single area - */ - function setAreaHighlightClass($a_nr, $a_class) - { - $ma_nodes = $this->getMapAreaNodes($this->hier_id, $this->purpose, - $this->getPcId()); - if (is_object($ma_nodes[$a_nr - 1])) - { - $ma_nodes[$a_nr - 1]->set_attribute("HighlightClass", $a_class); - } - } - - /** - * Add a new area to the map - */ - function addMapArea($a_shape_type, $a_coords, $a_title, - $a_link, $a_id = "") - { - $attributes = array("Shape" => $a_shape_type, - "Coords" => $a_coords, "Id" => $a_id); - - $ma_node = ilDOMUtil::addElementToList($this->dom, $this->item_node, - "MapArea", array(), "", $attributes); - - if ($a_link["LinkType"] == "int" || $a_link["LinkType"] == "IntLink") - { - $attributes = array("Type" => $a_link["Type"], - "TargetFrame" => $a_link["TargetFrame"], - "Target" => $a_link["Target"]); - ilDOMUtil::setFirstOptionalElement($this->dom, $ma_node, "IntLink", - array(""), $a_title, $attributes); - } - if ($a_link["LinkType"] == "ext" || $a_link["LinkType"] == "ExtLink") - { - $attributes = array("Href" => $a_link["Href"]); - ilDOMUtil::setFirstOptionalElement($this->dom, $ma_node, "ExtLink", - array(""), $a_title, $attributes); - } - } - - /** - * Delete a sinlge map area - */ - function deleteMapArea($a_nr) - { - $ma_nodes = $this->getMapAreaNodes($this->hier_id, $this->purpose, - $this->getPcId()); - - if (is_object($ma_nodes[$a_nr - 1])) - { - $ma_nodes[$a_nr - 1]->unlink_node($ma_nodes[$a_nr - 1]); - } - } - - /** - * Delete map areas by id - */ - function deleteMapAreaById($a_id) - { - $ma_nodes = $this->getMapAreaNodes($this->hier_id, $this->purpose, - $this->getPcId()); - foreach ($ma_nodes as $node) - { - if ($node->get_attribute("Id") == $a_id) - { - $node->unlink_node($node); - } - } - } - - /** - * Delete all map areas - */ - function deleteAllMapAreas() - { - $xpc = xpath_new_context($this->dom); - $path = "//PageContent[@HierId = '".$this->hier_id."']/".$this->parent_node_name."/MediaAliasItem[@Purpose='".$this->purpose."']/MapArea"; - $res = xpath_eval($xpc, $path); - for ($i = 0; $i < count($res->nodeset); $i++) - { - $res->nodeset[$i]->unlink_node($res->nodeset[$i]); - } - } - - /** - * Get link type - */ - function getLinkTypeOfArea($a_nr) - { - $ma_nodes = $this->getMapAreaNodes($this->hier_id, $this->purpose, - $this->getPcId()); - if (is_object($ma_nodes[$a_nr - 1])) - { - $childs = $ma_nodes[$a_nr - 1]->child_nodes(); - if ($childs[0]->node_name() == "IntLink") - { - return "int"; - } - if ($childs[0]->node_name() == "ExtLink") - { - return "ext"; - } - } - } - - /** - * Get type (only interna link - */ - function getTypeOfArea($a_nr) - { - $ma_nodes = $this->getMapAreaNodes($this->hier_id, $this->purpose, - $this->getPcId()); - if (is_object($ma_nodes[$a_nr - 1])) - { - $childs = $ma_nodes[$a_nr - 1]->child_nodes(); - return $childs[0]->get_attribute("Type"); - } - } - - /** - * Get target (only interna link - */ - function getTargetOfArea($a_nr) - { - $ma_nodes = $this->getMapAreaNodes($this->hier_id, $this->purpose, - $this->getPcId()); - if (is_object($ma_nodes[$a_nr - 1])) - { - $childs = $ma_nodes[$a_nr - 1]->child_nodes(); - return $childs[0]->get_attribute("Target"); - } - } - - /** - * Get target frame (only interna link - */ - function getTargetFrameOfArea($a_nr) - { - $ma_nodes = $this->getMapAreaNodes($this->hier_id, $this->purpose, - $this->getPcId()); - if (is_object($ma_nodes[$a_nr - 1])) - { - $childs = $ma_nodes[$a_nr - 1]->child_nodes(); - return $childs[0]->get_attribute("TargetFrame"); - } - } - - /** - * Get href (only external link) - */ - function getHrefOfArea($a_nr) - { - $ma_nodes = $this->getMapAreaNodes($this->hier_id, $this->purpose, - $this->getPcId()); - if (is_object($ma_nodes[$a_nr - 1])) - { - $childs = $ma_nodes[$a_nr - 1]->child_nodes(); - return $childs[0]->get_attribute("Href"); - } - } - - /** - * Get title - */ - function getTitleOfArea($a_nr) - { - $ma_nodes = $this->getMapAreaNodes($this->hier_id, $this->purpose, - $this->getPcId()); - if (is_object($ma_nodes[$a_nr - 1])) - { - $childs = $ma_nodes[$a_nr - 1]->child_nodes(); - return $childs[0]->get_content(); - } - } - - /** - * delete full item node from dom - */ - function delete() - { - if (is_object($this->item_node)) - { - $this->item_node->unlink_node($this->item_node); - } - } - - /** - * make map work copy of image - * - * @param int $a_area_nr draw area $a_area_nr only - * @param boolean $a_exclude true: draw all areas but area $a_area_nr - */ - function makeMapWorkCopy($a_st_item, $a_area_nr = 0, $a_exclude = false, - $a_output_new_area, $a_area_type, $a_coords) - { - $lng = $this->lng; - - if (!$a_st_item->copyOriginal()) - { - return false; - } - $a_st_item->buildMapWorkImage(); - - // determine ratios (first see whether the instance has w/h defined) - $width = $this->getWidth(); - $height = $this->getHeight(); - - // if instance has no size, use object w/h - if ($width == 0 && $height == 0) - { - $width = $a_st_item->getWidth(); - $height = $a_st_item->getHeight(); - } - $size = @getimagesize($a_st_item->getMapWorkCopyName()); - $x_ratio = 1; - if ($size[0] > 0 && $width > 0) - { - $x_ratio = $width / $size[0]; - } - $y_ratio = 1; - if ($size[1] > 0 && $height > 0) - { - $y_ratio = $height / $size[1]; - } - - // draw map areas - $areas = $this->getMapAreas(); - for ($i=0; $i < count($areas); $i++) - { - if ( ((($i+1) == $a_area_nr) && !$a_exclude) || - ((($i+1) != $a_area_nr) && $a_exclude) || - ($a_area_nr == 0) - ) - { - $area = new ilMapArea(); - $area->setShape($areas[$i]["Shape"]); - $area->setCoords($areas[$i]["Coords"]); - $area->draw($a_st_item->getMapWorkImage(), $a_st_item->color1, $a_st_item->color2, true, - $x_ratio, $y_ratio); - } - } - - if ($a_output_new_area) - { - $area = new ilMapArea(); - $area->setShape($a_area_type); - $area->setCoords($a_coords); - $area->draw($a_st_item->getMapWorkImage(), $a_st_item->color1, $a_st_item->color2, false, - $x_ratio, $y_ratio); - } - - $a_st_item->saveMapWorkImage(); - - return true; - } - + /** + * @var ilLanguage + */ + protected $lng; + + public $dom; + public $hier_id; + public $purpose; + public $item_node; + + public function __construct( + &$a_dom, + $a_hier_id, + $a_purpose, + $a_pc_id = "", + $a_parent_node_name = "MediaObject" + ) { + global $DIC; + + $this->lng = $DIC->language(); + $this->dom = $a_dom; + $this->parent_node_name = $a_parent_node_name; + $this->hier_id = $a_hier_id; + $this->purpose = $a_purpose; + $this->setPcId($a_pc_id); + $this->item_node = $this->getMAItemNode( + $this->hier_id, + $this->purpose, + $this->getPcId() + ); + } + + public function getMAItemNode($a_hier_id, $a_purpose, $a_pc_id = "", $a_sub_element = "") + { + if ($a_pc_id != "") { + $xpc = xpath_new_context($this->dom); + $path = "//PageContent[@PCID = '" . $a_pc_id . "']/" . $this->parent_node_name . "/MediaAliasItem[@Purpose='$a_purpose']" . $a_sub_element; + $res = xpath_eval($xpc, $path); + if (count($res->nodeset) == 1) { + return $res->nodeset[0]; + } + } + + $xpc = xpath_new_context($this->dom); + $path = "//PageContent[@HierId = '" . $a_hier_id . "']/" . $this->parent_node_name . "/MediaAliasItem[@Purpose='$a_purpose']" . $a_sub_element; + $res = xpath_eval($xpc, $path); + if (count($res->nodeset) > 0) { + return $res->nodeset[0]; + } + } + + public function getParameterNodes($a_hier_id, $a_purpose, $a_pc_id = "") + { + if ($a_pc_id != "") { + $xpc = xpath_new_context($this->dom); + $path = "//PageContent[@PCID = '" . $a_pc_id . "']/" . $this->parent_node_name . "/MediaAliasItem[@Purpose='$a_purpose']/Parameter"; + $res = xpath_eval($xpc, $path); + if (count($res->nodeset) > 0) { + return $res->nodeset; + } + return array(); + } + + $xpc = xpath_new_context($this->dom); + $path = "//PageContent[@HierId = '" . $a_hier_id . "']/" . $this->parent_node_name . "/MediaAliasItem[@Purpose='$a_purpose']/Parameter"; + $res = xpath_eval($xpc, $path); + if (count($res->nodeset) > 0) { + return $res->nodeset; + } + } + + public function getMapAreaNodes($a_hier_id, $a_purpose, $a_pc_id = "") + { + if ($a_pc_id != "") { + $xpc = xpath_new_context($this->dom); + $path = "//PageContent[@PCID = '" . $a_pc_id . "']/" . $this->parent_node_name . "/MediaAliasItem[@Purpose='$a_purpose']/MapArea"; + $res = xpath_eval($xpc, $path); + if (count($res->nodeset) > 0) { + return $res->nodeset; + } + return array(); + } + + $xpc = xpath_new_context($this->dom); + $path = "//PageContent[@HierId = '" . $a_hier_id . "']/" . $this->parent_node_name . "/MediaAliasItem[@Purpose='$a_purpose']/MapArea"; + $res = xpath_eval($xpc, $path); + if (count($res->nodeset) > 0) { + return $res->nodeset; + } + return array(); + } + + /** + * Set PC Id. + * + * @param string $a_pcid PC Id + */ + public function setPcId($a_pcid) + { + $this->pcid = $a_pcid; + } + + /** + * Get PC Id. + * + * @return string PC Id + */ + public function getPcId() + { + return $this->pcid; + } + + /** + * check if item node exists + * + * @return boolean returns true if item node exists + */ + public function exists() + { + if (is_object($this->item_node)) { + return true; + } else { + return false; + } + } + + /** + * inserts new node in dom + */ + public function insert() + { + $xpc = xpath_new_context($this->dom); + $path = "//PageContent[@HierId = '" . $this->hier_id . "']/" . $this->parent_node_name; + $res = xpath_eval($xpc, $path); + if (count($res->nodeset) > 0) { + $obj_node = $res->nodeset[0]; + $item_node = $this->dom->create_element("MediaAliasItem"); + $item_node = $obj_node->append_child($item_node); + $item_node->set_attribute("Purpose", $this->purpose); + $this->item_node = $item_node; + } + } + + /** + * Set width + */ + public function setWidth($a_width) + { + ilDOMUtil::setFirstOptionalElement( + $this->dom, + $this->item_node, + "Layout", + array("Caption", "TextRepresentation", "Parameter", "MapArea"), + "", + array("Width" => $a_width), + false + ); + } + + + /** + * Get width + */ + public function getWidth() + { + $layout_node = $this->getMAItemNode( + $this->hier_id, + $this->purpose, + $this->getPcId(), + "/Layout" + ); + if (is_object($layout_node)) { + return $layout_node->get_attribute("Width"); + } + } + + /** + * check if alias item defines own size or derives size from object + * + * @return boolean returns true if size is not derived from object + */ + public function definesSize() + { + $layout_node = $this->getMAItemNode( + $this->hier_id, + $this->purpose, + $this->getPcId(), + "/Layout" + ); + if (is_object($layout_node)) { + return $layout_node->has_attribute("Width"); + } + return false; + } + + /** + * derive size from object (-> width and height attributes are removed from layout element) + */ + public function deriveSize() + { + $layout_node = $this->getMAItemNode( + $this->hier_id, + $this->purpose, + $this->getPcId(), + "/Layout" + ); + if (is_object($layout_node)) { + if ($layout_node->has_attribute("Width")) { + $layout_node->remove_attribute("Width"); + } + if ($layout_node->has_attribute("Height")) { + $layout_node->remove_attribute("Height"); + } + } + } + + /** + * Set Height + */ + public function setHeight($a_height) + { + ilDOMUtil::setFirstOptionalElement( + $this->dom, + $this->item_node, + "Layout", + array("Caption", "TextRepresentation", "Parameter", "MapArea"), + "", + array("Height" => $a_height), + false + ); + } + + + /** + * Get Height + */ + public function getHeight() + { + $layout_node = $this->getMAItemNode( + $this->hier_id, + $this->purpose, + $this->getPcId(), + "/Layout" + ); + if (is_object($layout_node)) { + return $layout_node->get_attribute("Height"); + } + } + + + /** + * Set Caption + */ + public function setCaption($a_caption) + { + ilDOMUtil::setFirstOptionalElement( + $this->dom, + $this->item_node, + "Caption", + array("TextRepresentation", "Parameter", "MapArea"), + $a_caption, + array("Align" => "bottom") + ); + } + + + /** + * Get Caption + */ + public function getCaption() + { + $caption_node = $this->getMAItemNode( + $this->hier_id, + $this->purpose, + $this->getPcId(), + "/Caption" + ); + if (is_object($caption_node)) { + return $caption_node->get_content(); + } + } + + /** + * check if alias item defines own caption or derives caption from object + * + * @return boolean returns true if caption is not derived from object + */ + public function definesCaption() + { + $caption_node = $this->getMAItemNode( + $this->hier_id, + $this->purpose, + $this->getPcId(), + "/Caption" + ); + if (is_object($caption_node)) { + return true; + } + return false; + } + + /** + * derive caption from object (-> caption element is removed from media alias item) + */ + public function deriveCaption() + { + $caption_node = $this->getMAItemNode( + $this->hier_id, + $this->purpose, + $this->getPcId(), + "/Caption" + ); + if (is_object($caption_node)) { + $caption_node->unlink_node($caption_node); + } + } + + /** + * Set TextRepresentation + */ + public function setTextRepresentation($a_text_representation) + { + ilDOMUtil::setFirstOptionalElement( + $this->dom, + $this->item_node, + "TextRepresentation", + array("Parameter", "MapArea"), + $a_text_representation, + array() + ); + } + + /** + * Get TextRepresentation + */ + public function getTextRepresentation() + { + $text_representation_node = $this->getMAItemNode( + $this->hier_id, + $this->purpose, + $this->getPcId(), + "/TextRepresentation" + ); + if (is_object($text_representation_node)) { + return $text_representation_node->get_content(); + } + } + + /** + * check if alias item defines own TextRepresentation or derives TextRepresentation from object + * + * @return boolean returns true if TextRepresentation is not derived from object + */ + public function definesTextRepresentation() + { + $text_representation_node = $this->getMAItemNode( + $this->hier_id, + $this->purpose, + $this->getPcId(), + "/TextRepresentation" + ); + if (is_object($text_representation_node)) { + return true; + } + return false; + } + + /** + * derive TextRepresentation from object (-> TextRepresentation element is removed from media alias item) + */ + public function deriveTextRepresentation() + { + $text_representation_node = $this->getMAItemNode( + $this->hier_id, + $this->purpose, + $this->getPcId(), + "/TextRepresentation" + ); + if (is_object($text_representation_node)) { + $text_representation_node->unlink_node($text_representation_node); + } + } + + public function setHorizontalAlign($a_halign) + { + ilDOMUtil::setFirstOptionalElement( + $this->dom, + $this->item_node, + "Layout", + array("Caption", "TextRepresentation", "Parameter", "MapArea"), + "", + array("HorizontalAlign" => $a_halign), + false + ); + } + + + public function getHorizontalAlign() + { + $layout_node = $this->getMAItemNode( + $this->hier_id, + $this->purpose, + $this->getPcId(), + "/Layout" + ); + if (is_object($layout_node)) { + return $layout_node->get_attribute("HorizontalAlign"); + } + } + + /** + * set parameter + */ + public function setParameters($a_par_array) + { + $par_nodes = $this->getParameterNodes( + $this->hier_id, + $this->purpose, + $this->getPcId() + ); + for ($i=0; $i < count($par_nodes); $i++) { + $par_node = $par_nodes[$i]; + $par_node->unlink_node($par_node); + } + + include_once("./Services/MediaObjects/classes/class.ilMediaItem.php"); + if (is_array($a_par_array)) { + foreach ($a_par_array as $par => $val) { + if (ilMediaItem::checkParameter($par, $val)) { + $attributes = array("Name" => $par, "Value" => $val); + ilDOMUtil::addElementToList( + $this->dom, + $this->item_node, + "Parameter", + array("MapArea"), + "", + $attributes + ); + } + } + } + } + + /** + * Get all parameters as string + */ + public function getParameterString() + { + $par_nodes = $this->getParameterNodes( + $this->hier_id, + $this->purpose, + $this->getPcId() + ); + $par_arr = array(); + for ($i=0; $i < count($par_nodes); $i++) { + $par_node = $par_nodes[$i]; + $par_arr[] = $par_node->get_attribute("Name") . "=\"" . $par_node->get_attribute("Value") . "\""; + } + return implode($par_arr, ", "); + } + + /** + * Get all parameters as array + */ + public function getParameters() + { + $par_nodes = $this->getParameterNodes( + $this->hier_id, + $this->purpose, + $this->getPcId() + ); + $par_arr = array(); + for ($i=0; $i < count($par_nodes); $i++) { + $par_node = $par_nodes[$i]; + $par_arr[$par_node->get_attribute("Name")] = + $par_node->get_attribute("Value"); + } + return $par_arr; + } + + /** + * get a single parameter + */ + public function getParameter($a_name) + { + } + + /** + * check if alias item defines own parameters or derives parameters from object + * + * @return boolean returns true if parameters are not derived from object + */ + public function definesParameters() + { + $par_nodes = $this->getParameterNodes( + $this->hier_id, + $this->purpose, + $this->getPcId() + ); + if (count($par_nodes) > 0) { + return true; + } + return false; + } + + /** + * derive parameters from object (-> all parameter elements are removed from media alias item) + */ + public function deriveParameters() + { + $par_nodes = $this->getParameterNodes( + $this->hier_id, + $this->purpose, + $this->getPcId() + ); + if (count($par_nodes) > 0) { + for ($i=0; $i < count($par_nodes); $i++) { + $par_node = $par_nodes[$i]; + $par_node->unlink_node($par_node); + } + } + } + + + /** + * Get all map areas + */ + public function getMapAreas() + { + $ma_nodes = $this->getMapAreaNodes( + $this->hier_id, + $this->purpose, + $this->getPcId() + ); + $maparea_arr = array(); + for ($i=0; $i < count($ma_nodes); $i++) { + $maparea_node = $ma_nodes[$i]; + $childs = $maparea_node->child_nodes(); + $link = array(); + if ($childs[0]->node_name() == "ExtLink") { + $link = array("LinkType" => "ExtLink", + "Href" => $childs[0]->get_attribute("Href"), + "Title" => $childs[0]->get_content()); + } + if ($childs[0]->node_name() == "IntLink") { + $link = array("LinkType" => "IntLink", + "Target" => $childs[0]->get_attribute("Target"), + "Type" => $childs[0]->get_attribute("Type"), + "TargetFrame" => $childs[0]->get_attribute("TargetFame"), + "Title" => $childs[0]->get_content()); + } + $maparea_arr[] = array( + "Nr" => $i + 1, + "Shape" => $maparea_node->get_attribute("Shape"), + "Coords" => $maparea_node->get_attribute("Coords"), + "HighlightMode" => $maparea_node->get_attribute("HighlightMode"), + "HighlightClass" => $maparea_node->get_attribute("HighlightClass"), + "Id" => $maparea_node->get_attribute("Id"), + "Link" => $link); + } + + return $maparea_arr; + } + + /** + * Set title of area + */ + public function setAreaTitle($a_nr, $a_title) + { + $ma_nodes = $this->getMapAreaNodes( + $this->hier_id, + $this->purpose, + $this->getPcId() + ); + if (is_object($ma_nodes[$a_nr - 1])) { + $childs = $ma_nodes[$a_nr - 1]->child_nodes(); + if (is_object($childs[0]) && + ($childs[0]->node_name() == "IntLink" || $childs[0]->node_name() == "ExtLink")) { + $childs[0]->set_content($a_title); + } + } + } + + /** + * Set link of area to an internal one + */ + public function setAreaIntLink($a_nr, $a_type, $a_target, $a_target_frame) + { + $ma_nodes = $this->getMapAreaNodes( + $this->hier_id, + $this->purpose, + $this->getPcId() + ); + if (is_object($ma_nodes[$a_nr - 1])) { + $title = $this->getTitleOfArea($a_nr); + ilDOMUtil::deleteAllChildsByName($ma_nodes[$a_nr - 1], array("IntLink", "ExtLink")); + $attributes = array("Type" => $a_type, "Target" => $a_target, + "TargetFrame" => $a_target_frame); + ilDOMUtil::setFirstOptionalElement( + $this->dom, + $ma_nodes[$a_nr - 1], + "IntLink", + array(""), + $title, + $attributes + ); + } + } + + /** + * Set link of area to an external one + */ + public function setAreaExtLink($a_nr, $a_href) + { + $ma_nodes = $this->getMapAreaNodes( + $this->hier_id, + $this->purpose, + $this->getPcId() + ); + if (is_object($ma_nodes[$a_nr - 1])) { + $title = $this->getTitleOfArea($a_nr); + ilDOMUtil::deleteAllChildsByName($ma_nodes[$a_nr - 1], array("IntLink", "ExtLink")); + $attributes = array("Href" => $a_href); + ilDOMUtil::setFirstOptionalElement( + $this->dom, + $ma_nodes[$a_nr - 1], + "ExtLink", + array(""), + $title, + $attributes + ); + } + } + + /** + * Set shape and coords of single area + */ + public function setShape($a_nr, $a_shape_type, $a_coords) + { + $ma_nodes = $this->getMapAreaNodes( + $this->hier_id, + $this->purpose, + $this->getPcId() + ); + if (is_object($ma_nodes[$a_nr - 1])) { + $ma_nodes[$a_nr - 1]->set_attribute("Shape", $a_shape_type); + $ma_nodes[$a_nr - 1]->set_attribute("Coords", $a_coords); + } + } + + /** + * Set highlight mode single area + */ + public function setAreaHighlightMode($a_nr, $a_mode) + { + $ma_nodes = $this->getMapAreaNodes( + $this->hier_id, + $this->purpose, + $this->getPcId() + ); + if (is_object($ma_nodes[$a_nr - 1])) { + $ma_nodes[$a_nr - 1]->set_attribute("HighlightMode", $a_mode); + } + } + + /** + * Set highlight class single area + */ + public function setAreaHighlightClass($a_nr, $a_class) + { + $ma_nodes = $this->getMapAreaNodes( + $this->hier_id, + $this->purpose, + $this->getPcId() + ); + if (is_object($ma_nodes[$a_nr - 1])) { + $ma_nodes[$a_nr - 1]->set_attribute("HighlightClass", $a_class); + } + } + + /** + * Add a new area to the map + */ + public function addMapArea( + $a_shape_type, + $a_coords, + $a_title, + $a_link, + $a_id = "" + ) { + $attributes = array("Shape" => $a_shape_type, + "Coords" => $a_coords, "Id" => $a_id); + + $ma_node = ilDOMUtil::addElementToList( + $this->dom, + $this->item_node, + "MapArea", + array(), + "", + $attributes + ); + + if ($a_link["LinkType"] == "int" || $a_link["LinkType"] == "IntLink") { + $attributes = array("Type" => $a_link["Type"], + "TargetFrame" => $a_link["TargetFrame"], + "Target" => $a_link["Target"]); + ilDOMUtil::setFirstOptionalElement( + $this->dom, + $ma_node, + "IntLink", + array(""), + $a_title, + $attributes + ); + } + if ($a_link["LinkType"] == "ext" || $a_link["LinkType"] == "ExtLink") { + $attributes = array("Href" => $a_link["Href"]); + ilDOMUtil::setFirstOptionalElement( + $this->dom, + $ma_node, + "ExtLink", + array(""), + $a_title, + $attributes + ); + } + } + + /** + * Delete a sinlge map area + */ + public function deleteMapArea($a_nr) + { + $ma_nodes = $this->getMapAreaNodes( + $this->hier_id, + $this->purpose, + $this->getPcId() + ); + + if (is_object($ma_nodes[$a_nr - 1])) { + $ma_nodes[$a_nr - 1]->unlink_node($ma_nodes[$a_nr - 1]); + } + } + + /** + * Delete map areas by id + */ + public function deleteMapAreaById($a_id) + { + $ma_nodes = $this->getMapAreaNodes( + $this->hier_id, + $this->purpose, + $this->getPcId() + ); + foreach ($ma_nodes as $node) { + if ($node->get_attribute("Id") == $a_id) { + $node->unlink_node($node); + } + } + } + + /** + * Delete all map areas + */ + public function deleteAllMapAreas() + { + $xpc = xpath_new_context($this->dom); + $path = "//PageContent[@HierId = '" . $this->hier_id . "']/" . $this->parent_node_name . "/MediaAliasItem[@Purpose='" . $this->purpose . "']/MapArea"; + $res = xpath_eval($xpc, $path); + for ($i = 0; $i < count($res->nodeset); $i++) { + $res->nodeset[$i]->unlink_node($res->nodeset[$i]); + } + } + + /** + * Get link type + */ + public function getLinkTypeOfArea($a_nr) + { + $ma_nodes = $this->getMapAreaNodes( + $this->hier_id, + $this->purpose, + $this->getPcId() + ); + if (is_object($ma_nodes[$a_nr - 1])) { + $childs = $ma_nodes[$a_nr - 1]->child_nodes(); + if ($childs[0]->node_name() == "IntLink") { + return "int"; + } + if ($childs[0]->node_name() == "ExtLink") { + return "ext"; + } + } + } + + /** + * Get type (only interna link + */ + public function getTypeOfArea($a_nr) + { + $ma_nodes = $this->getMapAreaNodes( + $this->hier_id, + $this->purpose, + $this->getPcId() + ); + if (is_object($ma_nodes[$a_nr - 1])) { + $childs = $ma_nodes[$a_nr - 1]->child_nodes(); + return $childs[0]->get_attribute("Type"); + } + } + + /** + * Get target (only interna link + */ + public function getTargetOfArea($a_nr) + { + $ma_nodes = $this->getMapAreaNodes( + $this->hier_id, + $this->purpose, + $this->getPcId() + ); + if (is_object($ma_nodes[$a_nr - 1])) { + $childs = $ma_nodes[$a_nr - 1]->child_nodes(); + return $childs[0]->get_attribute("Target"); + } + } + + /** + * Get target frame (only interna link + */ + public function getTargetFrameOfArea($a_nr) + { + $ma_nodes = $this->getMapAreaNodes( + $this->hier_id, + $this->purpose, + $this->getPcId() + ); + if (is_object($ma_nodes[$a_nr - 1])) { + $childs = $ma_nodes[$a_nr - 1]->child_nodes(); + return $childs[0]->get_attribute("TargetFrame"); + } + } + + /** + * Get href (only external link) + */ + public function getHrefOfArea($a_nr) + { + $ma_nodes = $this->getMapAreaNodes( + $this->hier_id, + $this->purpose, + $this->getPcId() + ); + if (is_object($ma_nodes[$a_nr - 1])) { + $childs = $ma_nodes[$a_nr - 1]->child_nodes(); + return $childs[0]->get_attribute("Href"); + } + } + + /** + * Get title + */ + public function getTitleOfArea($a_nr) + { + $ma_nodes = $this->getMapAreaNodes( + $this->hier_id, + $this->purpose, + $this->getPcId() + ); + if (is_object($ma_nodes[$a_nr - 1])) { + $childs = $ma_nodes[$a_nr - 1]->child_nodes(); + return $childs[0]->get_content(); + } + } + + /** + * delete full item node from dom + */ + public function delete() + { + if (is_object($this->item_node)) { + $this->item_node->unlink_node($this->item_node); + } + } + + /** + * make map work copy of image + * + * @param int $a_area_nr draw area $a_area_nr only + * @param boolean $a_exclude true: draw all areas but area $a_area_nr + */ + public function makeMapWorkCopy( + $a_st_item, + $a_area_nr = 0, + $a_exclude = false, + $a_output_new_area, + $a_area_type, + $a_coords + ) { + $lng = $this->lng; + + if (!$a_st_item->copyOriginal()) { + return false; + } + $a_st_item->buildMapWorkImage(); + + // determine ratios (first see whether the instance has w/h defined) + $width = $this->getWidth(); + $height = $this->getHeight(); + + // if instance has no size, use object w/h + if ($width == 0 && $height == 0) { + $width = $a_st_item->getWidth(); + $height = $a_st_item->getHeight(); + } + $size = @getimagesize($a_st_item->getMapWorkCopyName()); + $x_ratio = 1; + if ($size[0] > 0 && $width > 0) { + $x_ratio = $width / $size[0]; + } + $y_ratio = 1; + if ($size[1] > 0 && $height > 0) { + $y_ratio = $height / $size[1]; + } + + // draw map areas + $areas = $this->getMapAreas(); + for ($i=0; $i < count($areas); $i++) { + if (((($i+1) == $a_area_nr) && !$a_exclude) || + ((($i+1) != $a_area_nr) && $a_exclude) || + ($a_area_nr == 0) + ) { + $area = new ilMapArea(); + $area->setShape($areas[$i]["Shape"]); + $area->setCoords($areas[$i]["Coords"]); + $area->draw( + $a_st_item->getMapWorkImage(), + $a_st_item->color1, + $a_st_item->color2, + true, + $x_ratio, + $y_ratio + ); + } + } + + if ($a_output_new_area) { + $area = new ilMapArea(); + $area->setShape($a_area_type); + $area->setCoords($a_coords); + $area->draw( + $a_st_item->getMapWorkImage(), + $a_st_item->color1, + $a_st_item->color2, + false, + $x_ratio, + $y_ratio + ); + } + + $a_st_item->saveMapWorkImage(); + + return true; + } } -?> diff --git a/Services/COPage/classes/class.ilPCBlog.php b/Services/COPage/classes/class.ilPCBlog.php index fb9549e311dd2b9e70312d0ad03f7fc4626b719a..9716f75863b5098e9c5f46ff835fa0f57706794c 100644 --- a/Services/COPage/classes/class.ilPCBlog.php +++ b/Services/COPage/classes/class.ilPCBlog.php @@ -1,146 +1,137 @@ - -* @version $Id: class.ilPCListItem.php 22210 2009-10-26 09:46:06Z akill $ -* -* @ingroup ServicesCOPage -*/ -class ilPCBlog extends ilPageContent -{ - /** - * @var ilObjUser - */ - protected $user; - - /** - * Init page content component. - */ - function init() - { - global $DIC; - - $this->user = $DIC->user(); - $this->setType("blog"); - } - - /** - * Set node - */ - function setNode($a_node) - { - parent::setNode($a_node); // this is the PageContent node - $this->blog_node = $a_node->first_child(); // this is the blog node - } - - /** - * Create blog node in xml. - * - * @param object $a_pg_obj Page Object - * @param string $a_hier_id Hierarchical ID - */ - 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->blog_node = $this->dom->create_element("Blog"); - $this->blog_node = $this->node->append_child($this->blog_node); - } - - /** - * Set blog settings - * - * @param int $a_blog_id - * @param array $a_posting_ids - */ - function setData($a_blog_id, array $a_posting_ids = null) - { - $ilUser = $this->user; - - $this->blog_node->set_attribute("Id", $a_blog_id); - $this->blog_node->set_attribute("User", $ilUser->getId()); - - // remove all children first - $children = $this->blog_node->child_nodes(); - if($children) - { - foreach($children as $child) - { - $this->blog_node->remove_child($child); - } - } - - if(sizeof($a_posting_ids)) - { - foreach($a_posting_ids as $posting_id) - { - $post_node = $this->dom->create_element("BlogPosting"); - $post_node = $this->blog_node->append_child($post_node); - $post_node->set_attribute("Id", $posting_id); - } - } - } - - /** - * Get blog mode - * - * @return string - */ - function getBlogId() - { - if (is_object($this->blog_node)) - { - return $this->blog_node->get_attribute("Id"); - } - } - - /** - * Get blog postings - * - * @return array - */ - function getPostings() - { - $res = array(); - if (is_object($this->blog_node)) - { - $children = $this->blog_node->child_nodes(); - if($children) - { - foreach($children as $child) - { - $res[] = $child->get_attribute("Id"); - } - } - } - return $res; - } -} -?> + +* @version $Id: class.ilPCListItem.php 22210 2009-10-26 09:46:06Z akill $ +* +* @ingroup ServicesCOPage +*/ +class ilPCBlog extends ilPageContent +{ + /** + * @var ilObjUser + */ + protected $user; + + /** + * Init page content component. + */ + public function init() + { + global $DIC; + + $this->user = $DIC->user(); + $this->setType("blog"); + } + + /** + * Set node + */ + public function setNode($a_node) + { + parent::setNode($a_node); // this is the PageContent node + $this->blog_node = $a_node->first_child(); // this is the blog node + } + + /** + * Create blog node in xml. + * + * @param object $a_pg_obj Page Object + * @param string $a_hier_id Hierarchical ID + */ + public 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->blog_node = $this->dom->create_element("Blog"); + $this->blog_node = $this->node->append_child($this->blog_node); + } + + /** + * Set blog settings + * + * @param int $a_blog_id + * @param array $a_posting_ids + */ + public function setData($a_blog_id, array $a_posting_ids = null) + { + $ilUser = $this->user; + + $this->blog_node->set_attribute("Id", $a_blog_id); + $this->blog_node->set_attribute("User", $ilUser->getId()); + + // remove all children first + $children = $this->blog_node->child_nodes(); + if ($children) { + foreach ($children as $child) { + $this->blog_node->remove_child($child); + } + } + + if (sizeof($a_posting_ids)) { + foreach ($a_posting_ids as $posting_id) { + $post_node = $this->dom->create_element("BlogPosting"); + $post_node = $this->blog_node->append_child($post_node); + $post_node->set_attribute("Id", $posting_id); + } + } + } + + /** + * Get blog mode + * + * @return string + */ + public function getBlogId() + { + if (is_object($this->blog_node)) { + return $this->blog_node->get_attribute("Id"); + } + } + + /** + * Get blog postings + * + * @return array + */ + public function getPostings() + { + $res = array(); + if (is_object($this->blog_node)) { + $children = $this->blog_node->child_nodes(); + if ($children) { + foreach ($children as $child) { + $res[] = $child->get_attribute("Id"); + } + } + } + return $res; + } +} diff --git a/Services/COPage/classes/class.ilPCBlogGUI.php b/Services/COPage/classes/class.ilPCBlogGUI.php index f305c9cb50cfcd6f53a302ba3dc78f97434aefdd..d95bb2728cb45ee42c0acdebaa8e2ec34e20c754 100644 --- a/Services/COPage/classes/class.ilPCBlogGUI.php +++ b/Services/COPage/classes/class.ilPCBlogGUI.php @@ -1,335 +1,299 @@ - -* @version $I$ -* -* @ingroup ServicesCOPage -*/ -class ilPCBlogGUI extends ilPageContentGUI -{ - /** - * @var ilObjUser - */ - protected $user; +tpl = $DIC["tpl"]; - $this->ctrl = $DIC->ctrl(); - $this->user = $DIC->user(); - $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 blog form - * - * @param ilPropertyFormGUI $a_form - */ - function insert(ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - - $this->displayValidationError(); - - if(!$a_form) - { - $a_form = $this->initForm(true); - } - $tpl->setContent($a_form->getHTML()); - } - - /** - * Edit blog form - * - * @param ilPropertyFormGUI $a_form - */ - function edit(ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - - $this->displayValidationError(); - - if(!$a_form) - { - $a_form = $this->initForm(); - } - $tpl->setContent($a_form->getHTML()); - } - - /** - * Init blog form - * - * @param bool $a_insert - * @return ilPropertyFormGUI - */ - protected function initForm($a_insert = false) - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - $lng = $this->lng; - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this)); - if ($a_insert) - { - $form->setTitle($this->lng->txt("cont_insert_blog")); - } - else - { - $form->setTitle($this->lng->txt("cont_update_blog")); - } - - $options = array(); - include_once "Modules/Blog/classes/class.ilBlogPosting.php"; - $blogs_ids = ilBlogPosting::searchBlogsByAuthor($ilUser->getId()); - if($blogs_ids) - { - foreach ($blogs_ids as $blog_id) - { - $options[$blog_id] = ilObject::_lookupTitle($blog_id); - } - asort($options); - } - $obj = new ilSelectInputGUI($this->lng->txt("cont_pc_blog"), "blog"); - $obj->setRequired(true); - $obj->setOptions($options); - $form->addItem($obj); - - if ($a_insert) - { - $form->addCommandButton("create_blog", $this->lng->txt("select")); - $form->addCommandButton("cancelCreate", $this->lng->txt("cancel")); - } - else - { - $obj->setValue($this->content_obj->getBlogId()); - $form->addCommandButton("update", $this->lng->txt("select")); - $form->addCommandButton("cancelUpdate", $this->lng->txt("cancel")); - } - - return $form; - } - - /** - * Create new blog - */ - function create() - { - if(!$_POST["blog_id"]) - { - $form = $this->initForm(true); - if($form->checkInput()) - { - return $this->insertPosting($_POST["blog"]); - } - - $form->setValuesByPost(); - return $this->insert($form); - } - else - { - $form = $this->initPostingForm($_POST["blog_id"], true); - if($form->checkInput()) - { - $this->content_obj = new ilPCBlog($this->getPage()); - $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); - $this->content_obj->setData($form->getInput("blog_id"), $form->getInput("posting")); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - } - - $form->setValuesByPost(); - return $this->insertPosting($_POST["blog_id"], $form); - } - } - - /** - * Update blog - */ - function update() - { - if(!$_POST["blog_id"]) - { - $form = $this->initForm(); - if($form->checkInput()) - { - return $this->editPosting($_POST["blog"]); - } - - $this->pg_obj->addHierIDs(); - $form->setValuesByPost(); - return $this->edit($form); - } - else - { - $form = $this->initPostingForm($_POST["blog_id"]); - if($form->checkInput()) - { - $this->content_obj->setData($form->getInput("blog_id"), $form->getInput("posting")); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - } - - $this->pg_obj->addHierIDs(); - $form->setValuesByPost(); - return $this->editPosting($_POST["blog_id"], $form); - } - } - - - /** - * Insert new blog posting form. - * - * @param int $a_blog_id - * @param ilPropertyFormGUI $a_form - */ - function insertPosting($a_blog_id, ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - - $this->displayValidationError(); - - if(!$a_form) - { - $a_form = $this->initPostingForm($a_blog_id, true); - } - $tpl->setContent($a_form->getHTML()); - } - - /** - * Edit blog posting form - * - * @param int $a_blog_id - * @param ilPropertyFormGUI $a_form - */ - function editPosting($a_blog_id, ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - - $this->displayValidationError(); - - if(!$a_form) - { - $a_form = $this->initPostingForm($a_blog_id); - } - $tpl->setContent($a_form->getHTML()); - } - - /** - * Init blog posting form - * - * @param int $a_blog_id - * @param bool $a_insert - * @return ilPropertyFormGUI - */ - protected function initPostingForm($a_blog_id, $a_insert = false) - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this)); - if ($a_insert) - { - $form->setTitle($this->lng->txt("cont_insert_blog")); - } - else - { - $form->setTitle($this->lng->txt("cont_update_blog")); - } - - $options = array(); - include_once "Modules/Blog/classes/class.ilBlogPosting.php"; - $postings = ilBlogPosting::getAllPostings($a_blog_id); - if($postings) - { - foreach($postings as $post) - { - // could be posting from someone else - if($post["author"] == $ilUser->getId()) - { - $date = new ilDateTime($post["date"], IL_CAL_DATETIME); - $title = $post["title"]." - ". - ilDatePresentation::formatDate($date); - - $cbox = new ilCheckboxInputGUI($title, "posting"); - $cbox->setValue($post["id"]); - - $options[] = $cbox; - } - } - } - asort($options); - $obj = new ilCheckboxGroupInputGUI($this->lng->txt("cont_pc_blog_posting"), "posting"); - $obj->setRequired(true); - $obj->setOptions($options); - $form->addItem($obj); - - $blog_id = new ilHiddenInputGUI("blog_id"); - $blog_id->setValue($a_blog_id); - $form->addItem($blog_id); - - if ($a_insert) - { - $form->addCommandButton("create_blog", $this->lng->txt("save")); - $form->addCommandButton("cancelCreate", $this->lng->txt("cancel")); - } - else - { - $obj->setValue($this->content_obj->getPostings()); - $form->addCommandButton("update", $this->lng->txt("save")); - $form->addCommandButton("cancelUpdate", $this->lng->txt("cancel")); - } - - return $form; - } -} - -?> \ No newline at end of file +require_once("./Services/COPage/classes/class.ilPCBlog.php"); +require_once("./Services/COPage/classes/class.ilPageContentGUI.php"); + +/** +* Class ilPCBlogGUI +* +* Handles user commands on blog data +* +* @author Jörg Lützenkirchen +* @version $I$ +* +* @ingroup ServicesCOPage +*/ +class ilPCBlogGUI extends ilPageContentGUI +{ + /** + * @var ilObjUser + */ + protected $user; + + + /** + * Constructor + * @access public + */ + 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->user = $DIC->user(); + $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 blog form + * + * @param ilPropertyFormGUI $a_form + */ + public function insert(ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + + $this->displayValidationError(); + + if (!$a_form) { + $a_form = $this->initForm(true); + } + $tpl->setContent($a_form->getHTML()); + } + + /** + * Edit blog form + * + * @param ilPropertyFormGUI $a_form + */ + public function edit(ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + + $this->displayValidationError(); + + if (!$a_form) { + $a_form = $this->initForm(); + } + $tpl->setContent($a_form->getHTML()); + } + + /** + * Init blog form + * + * @param bool $a_insert + * @return ilPropertyFormGUI + */ + protected function initForm($a_insert = false) + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + $lng = $this->lng; + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this)); + if ($a_insert) { + $form->setTitle($this->lng->txt("cont_insert_blog")); + } else { + $form->setTitle($this->lng->txt("cont_update_blog")); + } + + $options = array(); + include_once "Modules/Blog/classes/class.ilBlogPosting.php"; + $blogs_ids = ilBlogPosting::searchBlogsByAuthor($ilUser->getId()); + if ($blogs_ids) { + foreach ($blogs_ids as $blog_id) { + $options[$blog_id] = ilObject::_lookupTitle($blog_id); + } + asort($options); + } + $obj = new ilSelectInputGUI($this->lng->txt("cont_pc_blog"), "blog"); + $obj->setRequired(true); + $obj->setOptions($options); + $form->addItem($obj); + + if ($a_insert) { + $form->addCommandButton("create_blog", $this->lng->txt("select")); + $form->addCommandButton("cancelCreate", $this->lng->txt("cancel")); + } else { + $obj->setValue($this->content_obj->getBlogId()); + $form->addCommandButton("update", $this->lng->txt("select")); + $form->addCommandButton("cancelUpdate", $this->lng->txt("cancel")); + } + + return $form; + } + + /** + * Create new blog + */ + public function create() + { + if (!$_POST["blog_id"]) { + $form = $this->initForm(true); + if ($form->checkInput()) { + return $this->insertPosting($_POST["blog"]); + } + + $form->setValuesByPost(); + return $this->insert($form); + } else { + $form = $this->initPostingForm($_POST["blog_id"], true); + if ($form->checkInput()) { + $this->content_obj = new ilPCBlog($this->getPage()); + $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); + $this->content_obj->setData($form->getInput("blog_id"), $form->getInput("posting")); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + } + + $form->setValuesByPost(); + return $this->insertPosting($_POST["blog_id"], $form); + } + } + + /** + * Update blog + */ + public function update() + { + if (!$_POST["blog_id"]) { + $form = $this->initForm(); + if ($form->checkInput()) { + return $this->editPosting($_POST["blog"]); + } + + $this->pg_obj->addHierIDs(); + $form->setValuesByPost(); + return $this->edit($form); + } else { + $form = $this->initPostingForm($_POST["blog_id"]); + if ($form->checkInput()) { + $this->content_obj->setData($form->getInput("blog_id"), $form->getInput("posting")); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + } + + $this->pg_obj->addHierIDs(); + $form->setValuesByPost(); + return $this->editPosting($_POST["blog_id"], $form); + } + } + + + /** + * Insert new blog posting form. + * + * @param int $a_blog_id + * @param ilPropertyFormGUI $a_form + */ + public function insertPosting($a_blog_id, ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + + $this->displayValidationError(); + + if (!$a_form) { + $a_form = $this->initPostingForm($a_blog_id, true); + } + $tpl->setContent($a_form->getHTML()); + } + + /** + * Edit blog posting form + * + * @param int $a_blog_id + * @param ilPropertyFormGUI $a_form + */ + public function editPosting($a_blog_id, ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + + $this->displayValidationError(); + + if (!$a_form) { + $a_form = $this->initPostingForm($a_blog_id); + } + $tpl->setContent($a_form->getHTML()); + } + + /** + * Init blog posting form + * + * @param int $a_blog_id + * @param bool $a_insert + * @return ilPropertyFormGUI + */ + protected function initPostingForm($a_blog_id, $a_insert = false) + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this)); + if ($a_insert) { + $form->setTitle($this->lng->txt("cont_insert_blog")); + } else { + $form->setTitle($this->lng->txt("cont_update_blog")); + } + + $options = array(); + include_once "Modules/Blog/classes/class.ilBlogPosting.php"; + $postings = ilBlogPosting::getAllPostings($a_blog_id); + if ($postings) { + foreach ($postings as $post) { + // could be posting from someone else + if ($post["author"] == $ilUser->getId()) { + $date = new ilDateTime($post["date"], IL_CAL_DATETIME); + $title = $post["title"] . " - " . + ilDatePresentation::formatDate($date); + + $cbox = new ilCheckboxInputGUI($title, "posting"); + $cbox->setValue($post["id"]); + + $options[] = $cbox; + } + } + } + asort($options); + $obj = new ilCheckboxGroupInputGUI($this->lng->txt("cont_pc_blog_posting"), "posting"); + $obj->setRequired(true); + $obj->setOptions($options); + $form->addItem($obj); + + $blog_id = new ilHiddenInputGUI("blog_id"); + $blog_id->setValue($a_blog_id); + $form->addItem($blog_id); + + if ($a_insert) { + $form->addCommandButton("create_blog", $this->lng->txt("save")); + $form->addCommandButton("cancelCreate", $this->lng->txt("cancel")); + } else { + $obj->setValue($this->content_obj->getPostings()); + $form->addCommandButton("update", $this->lng->txt("save")); + $form->addCommandButton("cancelUpdate", $this->lng->txt("cancel")); + } + + return $form; + } +} diff --git a/Services/COPage/classes/class.ilPCContentInclude.php b/Services/COPage/classes/class.ilPCContentInclude.php index 9da0596705dc4f4c0a6c0c0d162da008c3426611..758675e09e3fbf83b41eb7db95f348e967d50534 100644 --- a/Services/COPage/classes/class.ilPCContentInclude.php +++ b/Services/COPage/classes/class.ilPCContentInclude.php @@ -16,302 +16,279 @@ require_once("./Services/COPage/classes/class.ilPageContent.php"); */ class ilPCContentInclude extends ilPageContent { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - var $incl_node; + public $incl_node; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * Init page content component. - */ - function init() - { - global $DIC; + /** + * Init page content component. + */ + public function init() + { + global $DIC; - $this->lng = $DIC->language(); - $this->setType("incl"); - $this->access = $DIC->access(); - } + $this->lng = $DIC->language(); + $this->setType("incl"); + $this->access = $DIC->access(); + } - /** - * Set node - */ - function setNode($a_node) - { - parent::setNode($a_node); // this is the PageContent node - $this->incl_node = $a_node->first_child(); // this is the snippet node - } + /** + * Set node + */ + public function setNode($a_node) + { + parent::setNode($a_node); // this is the PageContent node + $this->incl_node = $a_node->first_child(); // this is the snippet node + } - /** - * Create content include node in xml. - * - * @param object $a_pg_obj Page Object - * @param string $a_hier_id Hierarchical ID - */ - 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->incl_node = $this->dom->create_element("ContentInclude"); - $this->incl_node = $this->node->append_child($this->incl_node); - } + /** + * Create content include node in xml. + * + * @param object $a_pg_obj Page Object + * @param string $a_hier_id Hierarchical ID + */ + public 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->incl_node = $this->dom->create_element("ContentInclude"); + $this->incl_node = $this->node->append_child($this->incl_node); + } - /** - * Set content id - */ - function setContentId($a_id) - { - $this->setContentIncludeAttribute("ContentId", $a_id); - } - - /** - * Get content id - */ - function getContentId() - { - return $this->getContentIncludeAttribute("ContentId"); - } + /** + * Set content id + */ + public function setContentId($a_id) + { + $this->setContentIncludeAttribute("ContentId", $a_id); + } + + /** + * Get content id + */ + public function getContentId() + { + return $this->getContentIncludeAttribute("ContentId"); + } - /** - * Set content type - */ - function setContentType($a_type) - { - $this->setContentIncludeAttribute("ContentType", $a_type); - } - - /** - * Get content type - */ - function getContentType() - { - return $this->getContentIncludeAttribute("ContentType"); - } + /** + * Set content type + */ + public function setContentType($a_type) + { + $this->setContentIncludeAttribute("ContentType", $a_type); + } + + /** + * Get content type + */ + public function getContentType() + { + return $this->getContentIncludeAttribute("ContentType"); + } - /** - * Set installation id - */ - function setInstId($a_id) - { - $this->setContentIncludeAttribute("InstId", $a_id); - } + /** + * Set installation id + */ + public function setInstId($a_id) + { + $this->setContentIncludeAttribute("InstId", $a_id); + } - /** - * Get installation id - */ - function getInstId() - { - return $this->getContentIncludeAttribute("InstId"); - } - - /** - * Set attribute of content include tag - * - * @param string attribute name - * @param string attribute value - */ - protected function setContentIncludeAttribute($a_attr, $a_value) - { - if (!empty($a_value)) - { - $this->incl_node->set_attribute($a_attr, $a_value); - } - else - { - if ($this->incl_node->has_attribute($a_attr)) - { - $this->incl_node->remove_attribute($a_attr); - } - } - } + /** + * Get installation id + */ + public function getInstId() + { + return $this->getContentIncludeAttribute("InstId"); + } + + /** + * Set attribute of content include tag + * + * @param string attribute name + * @param string attribute value + */ + protected function setContentIncludeAttribute($a_attr, $a_value) + { + if (!empty($a_value)) { + $this->incl_node->set_attribute($a_attr, $a_value); + } else { + if ($this->incl_node->has_attribute($a_attr)) { + $this->incl_node->remove_attribute($a_attr); + } + } + } - /** - * Get content include tag attribute - * - * @return string attribute name - */ - function getContentIncludeAttribute($a_attr) - { - if (is_object($this->incl_node)) - { - return $this->incl_node->get_attribute($a_attr); - } - } + /** + * Get content include tag attribute + * + * @return string attribute name + */ + public function getContentIncludeAttribute($a_attr) + { + if (is_object($this->incl_node)) { + return $this->incl_node->get_attribute($a_attr); + } + } - /** - * After page has been updated (or created) - * - * @param object $a_page page object - * @param DOMDocument $a_domdoc dom document - * @param string $a_xml xml - * @param bool $a_creation true on creation, otherwise false - */ - static function afterPageUpdate($a_page, DOMDocument $a_domdoc, $a_xml, $a_creation) - { - // pc content include - self::saveContentIncludeUsage($a_page, $a_domdoc); - } - - /** - * Before page is being deleted - * - * @param object $a_page page object - */ - static function beforePageDelete($a_page) - { - include_once("./Services/COPage/classes/class.ilPageContentUsage.php"); - ilPageContentUsage::deleteAllUsages("incl", $a_page->getParentType().":pg", $a_page->getId(), false, $a_page->getLanguage()); - } + /** + * After page has been updated (or created) + * + * @param object $a_page page object + * @param DOMDocument $a_domdoc dom document + * @param string $a_xml xml + * @param bool $a_creation true on creation, otherwise false + */ + public static function afterPageUpdate($a_page, DOMDocument $a_domdoc, $a_xml, $a_creation) + { + // pc content include + self::saveContentIncludeUsage($a_page, $a_domdoc); + } + + /** + * Before page is being deleted + * + * @param object $a_page page object + */ + public static function beforePageDelete($a_page) + { + include_once("./Services/COPage/classes/class.ilPageContentUsage.php"); + ilPageContentUsage::deleteAllUsages("incl", $a_page->getParentType() . ":pg", $a_page->getId(), false, $a_page->getLanguage()); + } - /** - * After page history entry has been created - * - * @param object $a_page page object - * @param DOMDocument $a_old_domdoc old dom document - * @param string $a_old_xml old xml - * @param integer $a_old_nr history number - */ - static function afterPageHistoryEntry($a_page, DOMDocument $a_old_domdoc, $a_old_xml, $a_old_nr) - { - self::saveContentIncludeUsage($a_page, $a_old_domdoc, $a_old_nr); - } + /** + * After page history entry has been created + * + * @param object $a_page page object + * @param DOMDocument $a_old_domdoc old dom document + * @param string $a_old_xml old xml + * @param integer $a_old_nr history number + */ + public static function afterPageHistoryEntry($a_page, DOMDocument $a_old_domdoc, $a_old_xml, $a_old_nr) + { + self::saveContentIncludeUsage($a_page, $a_old_domdoc, $a_old_nr); + } - /** - * save content include usages - */ - static function saveContentIncludeUsage($a_page, $a_domdoc, $a_old_nr = 0) - { - include_once("./Services/COPage/classes/class.ilPageContentUsage.php"); - $ci_ids = self::collectContentIncludes($a_page, $a_domdoc); - ilPageContentUsage::deleteAllUsages("incl", $a_page->getParentType().":pg", $a_page->getId(), $a_old_nr, $a_page->getLanguage()); - foreach($ci_ids as $ci_id) - { - if ((int) $ci_id["inst_id"] <= 0 || $ci_id["inst_id"] == IL_INST_ID) - { - ilPageContentUsage::saveUsage("incl", $ci_id["id"], $a_page->getParentType().":pg", $a_page->getId(), $a_old_nr, - $a_page->getLanguage()); - } - } - } + /** + * save content include usages + */ + public static function saveContentIncludeUsage($a_page, $a_domdoc, $a_old_nr = 0) + { + include_once("./Services/COPage/classes/class.ilPageContentUsage.php"); + $ci_ids = self::collectContentIncludes($a_page, $a_domdoc); + ilPageContentUsage::deleteAllUsages("incl", $a_page->getParentType() . ":pg", $a_page->getId(), $a_old_nr, $a_page->getLanguage()); + foreach ($ci_ids as $ci_id) { + if ((int) $ci_id["inst_id"] <= 0 || $ci_id["inst_id"] == IL_INST_ID) { + ilPageContentUsage::saveUsage( + "incl", + $ci_id["id"], + $a_page->getParentType() . ":pg", + $a_page->getId(), + $a_old_nr, + $a_page->getLanguage() + ); + } + } + } - /** - * get all content includes that are used within the page - */ - static function collectContentIncludes($a_page, $a_domdoc) - { - $xpath = new DOMXPath($a_domdoc); - $nodes = $xpath->query('//ContentInclude'); + /** + * get all content includes that are used within the page + */ + public static function collectContentIncludes($a_page, $a_domdoc) + { + $xpath = new DOMXPath($a_domdoc); + $nodes = $xpath->query('//ContentInclude'); - $ci_ids = array(); - foreach ($nodes as $node) - { - $type = $node->getAttribute("ContentType"); - $id = $node->getAttribute("ContentId"); - $inst_id = $node->getAttribute("InstId"); - $ci_ids[$type.":".$id.":".$inst_id] = array( - "type" => $type, "id" => $id, "inst_id" => $inst_id); - } + $ci_ids = array(); + foreach ($nodes as $node) { + $type = $node->getAttribute("ContentType"); + $id = $node->getAttribute("ContentId"); + $inst_id = $node->getAttribute("InstId"); + $ci_ids[$type . ":" . $id . ":" . $inst_id] = array( + "type" => $type, "id" => $id, "inst_id" => $inst_id); + } - return $ci_ids; - } + return $ci_ids; + } - /** - * @inheritdoc - */ - function modifyPageContentPostXsl($a_html, $a_mode) - { - $lng = $this->lng; + /** + * @inheritdoc + */ + public function modifyPageContentPostXsl($a_html, $a_mode) + { + $lng = $this->lng; - $end = 0; - $start = strpos($a_html, "{{{{{ContentInclude;"); - if (is_int($start)) - { - $end = strpos($a_html, "}}}}}", $start); - } - $i = 1; - while ($end > 0) - { - $param = substr($a_html, $start + 20, $end - $start - 20); - $param = explode(";", $param); + $end = 0; + $start = strpos($a_html, "{{{{{ContentInclude;"); + if (is_int($start)) { + $end = strpos($a_html, "}}}}}", $start); + } + $i = 1; + while ($end > 0) { + $param = substr($a_html, $start + 20, $end - $start - 20); + $param = explode(";", $param); - if ($param[0] == "mep" && is_numeric($param[1])) - { - include_once("./Modules/MediaPool/classes/class.ilMediaPoolPageGUI.php"); - $html = ""; - $snippet_lang = $this->getPage()->getLanguage(); - if (!ilPageObject::_exists("mep", $param[1], $snippet_lang)) - { - $snippet_lang = "-"; - } - if (($param[2] <= 0 || $param[2] == IL_INST_ID) && ilPageObject::_exists("mep", $param[1])) - { - $page_gui = new ilMediaPoolPageGUI($param[1], 0, true, $snippet_lang); - if ($a_mode != "offline") - { - $page_gui->setFileDownloadLink($this->getFileDownloadLink()); - $page_gui->setFullscreenLink($this->getFullscreenLink()); - $page_gui->setSourcecodeDownloadScript($this->getSourcecodeDownloadScript()); - } - else - { - $page_gui->setOutputMode(IL_PAGE_OFFLINE); - } + if ($param[0] == "mep" && is_numeric($param[1])) { + include_once("./Modules/MediaPool/classes/class.ilMediaPoolPageGUI.php"); + $html = ""; + $snippet_lang = $this->getPage()->getLanguage(); + if (!ilPageObject::_exists("mep", $param[1], $snippet_lang)) { + $snippet_lang = "-"; + } + if (($param[2] <= 0 || $param[2] == IL_INST_ID) && ilPageObject::_exists("mep", $param[1])) { + $page_gui = new ilMediaPoolPageGUI($param[1], 0, true, $snippet_lang); + if ($a_mode != "offline") { + $page_gui->setFileDownloadLink($this->getFileDownloadLink()); + $page_gui->setFullscreenLink($this->getFullscreenLink()); + $page_gui->setSourcecodeDownloadScript($this->getSourcecodeDownloadScript()); + } else { + $page_gui->setOutputMode(IL_PAGE_OFFLINE); + } - $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; - } + $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 "
++".$path; -//]--//PageContent[@HierId='3']/Table/TableRow[+1]/TableData[0 style=+1]/PageContent[1]/Paragraph[1] - $res = xpath_eval($xpc, $path); + public 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 + */ + public 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 "
++".$path; + //]--//PageContent[@HierId='3']/Table/TableRow[+1]/TableData[0 style=+1]/PageContent[1]/Paragraph[1] + $res = xpath_eval($xpc, $path); - if (is_object($res->nodeset[0])) - { - return $res->nodeset[0]; - } - else // no node -> delete all childs and create paragraph - { - $xpc2 = xpath_new_context($this->dom); - $path2 = "//PageContent[@HierId='".$this->getHierId()."']". - "/Table/TableRow[".($i+1)."]/TableData[".($j+1)."]"; - //$path2 = "//PageContent"; - - $res2 = xpath_eval($xpc2, $path2); + if (is_object($res->nodeset[0])) { + return $res->nodeset[0]; + } else { // no node -> delete all childs and create paragraph + $xpc2 = xpath_new_context($this->dom); + $path2 = "//PageContent[@HierId='" . $this->getHierId() . "']" . + "/Table/TableRow[" . ($i+1) . "]/TableData[" . ($j+1) . "]"; + //$path2 = "//PageContent"; + + $res2 = xpath_eval($xpc2, $path2); - $td_node = $res2->nodeset[0]; + $td_node = $res2->nodeset[0]; - if (is_object($td_node)) - { - // delete children of paragraph node - $children = $td_node->child_nodes(); - for($i=0; $iremove_child($children[$i]); - } - - // create page content and paragraph node here. - $pc_node = $this->createPageContentNode(false); - $pc_node = $td_node->append_child($pc_node); - $par_node = $this->dom->create_element("Paragraph"); - $par_node = $pc_node->append_child($par_node); - $par_node->set_attribute("Characteristic", "TableContent"); - $par_node->set_attribute("Language", - $this->getLanguage()); + if (is_object($td_node)) { + // delete children of paragraph node + $children = $td_node->child_nodes(); + for ($i=0; $iremove_child($children[$i]); + } + + // create page content and paragraph node here. + $pc_node = $this->createPageContentNode(false); + $pc_node = $td_node->append_child($pc_node); + $par_node = $this->dom->create_element("Paragraph"); + $par_node = $pc_node->append_child($par_node); + $par_node->set_attribute("Characteristic", "TableContent"); + $par_node->set_attribute( + "Language", + $this->getLanguage() + ); - return $par_node; - } - } - - return ""; - } - - /** - * Make cell empty - */ - function makeEmptyCell($td_node) - { - // delete children of paragraph node - $children = $td_node->child_nodes(); - for($i=0; $iremove_child($children[$i]); - } - - // create page content and paragraph node here. - $pc_node = $this->createPageContentNode(false); - $pc_node = $td_node->append_child($pc_node); - $par_node = $this->dom->create_element("Paragraph"); - $par_node = $pc_node->append_child($par_node); - $par_node->set_attribute("Characteristic", "TableContent"); - $par_node->set_attribute("Language", - $this->getLanguage()); - } + return $par_node; + } + } + + return ""; + } + + /** + * Make cell empty + */ + public function makeEmptyCell($td_node) + { + // delete children of paragraph node + $children = $td_node->child_nodes(); + for ($i=0; $iremove_child($children[$i]); + } + + // create page content and paragraph node here. + $pc_node = $this->createPageContentNode(false); + $pc_node = $td_node->append_child($pc_node); + $par_node = $this->dom->create_element("Paragraph"); + $par_node = $pc_node->append_child($par_node); + $par_node->set_attribute("Characteristic", "TableContent"); + $par_node->set_attribute( + "Language", + $this->getLanguage() + ); + } - /** - * Get cell text of row $i and cell $j - */ - function getCellText($i, $j) - { - $cell_par = $this->getCellNode($i, $j); - - if (is_object($cell_par)) - { - $content = ""; - $childs = $cell_par->child_nodes(); - for($i=0; $idom->dump_node($childs[$i]); - } - return $content; - } - else - { - return ""; - } - } + /** + * Get cell text of row $i and cell $j + */ + public function getCellText($i, $j) + { + $cell_par = $this->getCellNode($i, $j); + + if (is_object($cell_par)) { + $content = ""; + $childs = $cell_par->child_nodes(); + for ($i=0; $idom->dump_node($childs[$i]); + } + return $content; + } else { + return ""; + } + } - /** - * Set data of cells - */ - function setData($a_data) - { - $ok = true; -//var_dump($a_data); - if (is_array($a_data)) - { - foreach ($a_data as $i => $row) - { - if (is_array($row)) - { - foreach ($row as $j => $cell) - { -//echo "

=".$cell."="; - $temp_dom = @domxml_open_mem(''.$cell.'', - DOMXML_LOAD_PARSING, $error); + /** + * Set data of cells + */ + public function setData($a_data) + { + $ok = true; + //var_dump($a_data); + if (is_array($a_data)) { + foreach ($a_data as $i => $row) { + if (is_array($row)) { + foreach ($row as $j => $cell) { + //echo "

=".$cell."="; + $temp_dom = @domxml_open_mem( + '' . $cell . '', + DOMXML_LOAD_PARSING, + $error + ); - $par_node = $this->getCellNode($i, $j); -//echo "
=".htmlentities($this->dom->dump_node($par_node))."="; -//echo "
-$i-$j-$cell-"; - // remove all childs - if(empty($error) && is_object($par_node)) - { - // delete children of paragraph node - $children = $par_node->child_nodes(); - for($k=0; $k < count($children); $k++) - { - $par_node->remove_child($children[$k]); - } + $par_node = $this->getCellNode($i, $j); + //echo "
=".htmlentities($this->dom->dump_node($par_node))."="; + //echo "
-$i-$j-$cell-"; + // remove all childs + if (empty($error) && is_object($par_node)) { + // delete children of paragraph node + $children = $par_node->child_nodes(); + for ($k=0; $k < count($children); $k++) { + $par_node->remove_child($children[$k]); + } - // copy new content children in paragraph node - $xpc = xpath_new_context($temp_dom); - $path = "//Paragraph"; - $res = xpath_eval($xpc, $path); + // copy new content children in paragraph node + $xpc = xpath_new_context($temp_dom); + $path = "//Paragraph"; + $res = xpath_eval($xpc, $path); - if (count($res->nodeset) == 1) - { - $new_par_node = $res->nodeset[0]; - $new_childs = $new_par_node->child_nodes(); - for ($l = 0; $l < count($new_childs); $l++) - { - $cloned_child = $new_childs[$l]->clone_node(true); - $par_node->append_child($cloned_child); -//echo "
=".htmlentities($this->dom->dump_node($cloned_child))."="; - } - } - } - else - { - if (!empty($error)) - { - return $error; - } - } - } - } - } - } -//exit; - return true; - } + if (count($res->nodeset) == 1) { + $new_par_node = $res->nodeset[0]; + $new_childs = $new_par_node->child_nodes(); + for ($l = 0; $l < count($new_childs); $l++) { + $cloned_child = $new_childs[$l]->clone_node(true); + $par_node->append_child($cloned_child); + //echo "
=".htmlentities($this->dom->dump_node($cloned_child))."="; + } + } + } else { + if (!empty($error)) { + return $error; + } + } + } + } + } + } + //exit; + return true; + } } - -?> diff --git a/Services/COPage/classes/class.ilPCDataTableGUI.php b/Services/COPage/classes/class.ilPCDataTableGUI.php index 310f73717fbd43e37819b770e3511521b0ec8d8c..101383737d1976c2203fc045b8328584ff53b2b6 100755 --- a/Services/COPage/classes/class.ilPCDataTableGUI.php +++ b/Services/COPage/classes/class.ilPCDataTableGUI.php @@ -17,734 +17,672 @@ require_once("./Services/COPage/classes/class.ilPageContentGUI.php"); */ class ilPCDataTableGUI extends ilPCTableGUI { - /** - * @var ilTabsGUI - */ - protected $tabs; - - - /** - * Constructor - * @access public - */ - function __construct(&$a_pg_obj, &$a_content_obj, $a_hier_id, $a_pc_id = "") - { - global $DIC; - - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $this->tabs = $DIC->tabs(); - parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); - $this->setCharacteristics(array("StandardTable" => $this->lng->txt("cont_StandardTable"))); - } - - /** - * execute command - */ - function executeCommand() - { - $this->getCharacteristicsOfCurrentStyle("table"); // scorm-2004 - - // 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; - } - - - //// - //// Classic editing - //// - - /** - * Edit data of table. (classic version) - */ - function editDataCl() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; -//var_dump($_GET); -//var_dump($_POST); - - $this->setTabs(); - - $this->displayValidationError(); - - include_once("./Services/COPage/classes/class.ilPCParagraph.php"); - - $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.tabledata.html", "Services/COPage"); - $dtpl = $this->tpl; - //$dtpl = new ilTemplate("tpl.tabledata.html", true, true, "Services/COPage"); - $dtpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this, "tableAction")); - $dtpl->setVariable("BB_MENU", $this->getBBMenu("cell_0_0")); - - ilYuiUtil::initDragDrop(); - ilYuiUtil::initConnection(); - ilYuiUtil::initPanel(false); - $this->tpl->addJavascript("./Services/COPage/phpBB/3_0_5/editor.js"); - $this->tpl->addJavascript("./Services/COPage/js/page_editing.js"); - $this->tpl->addJavascript("./Services/COPage/js/paragraph_editing.js"); - - // get all rows - $xpc = xpath_new_context($this->dom); - $path = "//PageContent[@HierId='".$this->getHierId()."']". - "/Table/TableRow"; - $res = xpath_eval($xpc, $path); - - for($i = 0; $i < count($res->nodeset); $i++) - { - - $xpc2 = xpath_new_context($this->dom); - $path2 = "//PageContent[@HierId='".$this->getHierId()."']". - "/Table/TableRow[$i+1]/TableData"; - $res2 = xpath_eval($xpc2, $path2); - - // if this is the first row -> col icons - if ($i == 0) - { - for($j = 0; $j < count($res2->nodeset); $j++) - { - if ($j == 0) - { - $dtpl->touchBlock("empty_td"); - } - - if ($j == 0) - { - if (count($res2->nodeset) == 1) - { - $move_type = "none"; - } - else - { - $move_type = "forward"; - } - } - else if ($j == (count($res2->nodeset) - 1)) - { - $move_type = "backward"; - } - else - { - $move_type = "both"; - } - $dtpl->setCurrentBlock("col_icon"); - $dtpl->setVariable("COL_ICON_ALT", $lng->txt("content_column")); - $dtpl->setVariable("COL_ICON", ilUtil::getImagePath("col.svg")); - $dtpl->setVariable("COL_ONCLICK", "COL_".$move_type); - $dtpl->setVariable("NR", $j); - $dtpl->parseCurrentBlock(); - } - $dtpl->setCurrentBlock("row"); - $dtpl->parseCurrentBlock(); - } - - - for($j = 0; $j < count($res2->nodeset); $j++) - { - // first col: row icons - if ($j == 0) - { - if ($i == 0) - { - if (count($res->nodeset) == 1) - { - $move_type = "none"; - } - else - { - $move_type = "forward"; - } - } - else if ($i == (count($res->nodeset) - 1)) - { - $move_type = "backward"; - } - else - { - $move_type = "both"; - } - $dtpl->setCurrentBlock("row_icon"); - $dtpl->setVariable("ROW_ICON_ALT", $lng->txt("content_row")); - $dtpl->setVariable("ROW_ICON", ilUtil::getImagePath("row.svg")); - $dtpl->setVariable("ROW_ONCLICK", "ROW_".$move_type); - $dtpl->setVariable("NR", $i); - $dtpl->parseCurrentBlock(); - } - - // cell - if ($res2->nodeset[$j]->get_attribute("Hidden") != "Y") - { - $dtpl->setCurrentBlock("cell"); - - if (is_array($_POST["cmd"]) && key($_POST["cmd"]) == "update") - { - $s_text = ilUtil::stripSlashes("cell_".$i."_".$j, false); - } - else - { - $s_text = ilPCParagraph::xml2output($this->content_obj->getCellText($i, $j)); - } - - $dtpl->setVariable("PAR_TA_NAME", "cell[".$i."][".$j."]"); - $dtpl->setVariable("PAR_TA_ID", "cell_".$i."_".$j); - $dtpl->setVariable("PAR_TA_CONTENT", $s_text); - - $cs = $res2->nodeset[$j]->get_attribute("ColSpan"); - $rs = $res2->nodeset[$j]->get_attribute("RowSpan"); -// $dtpl->setVariable("WIDTH", "140"); -// $dtpl->setVariable("HEIGHT", "80"); - if ($cs > 1) - { - $dtpl->setVariable("COLSPAN", 'colspan="'.$cs.'"'); - $dtpl->setVariable("WIDTH", (140 + ($cs - 1) * 146)); - } - if ($rs > 1) - { - $dtpl->setVariable("ROWSPAN", 'rowspan="'.$rs.'"'); - $dtpl->setVariable("HEIGHT", (80 + ($rs - 1) * 86)); - } - $dtpl->parseCurrentBlock(); - } - } - $dtpl->setCurrentBlock("row"); - $dtpl->parseCurrentBlock(); - } - - // init menues - $types = array("row", "col"); - $moves = array("none", "backward", "both", "forward"); - $commands = array( - "row" => array( "newRowAfter" => "cont_ed_new_row_after", - "newRowBefore" => "cont_ed_new_row_before", - "moveRowUp" => "cont_ed_row_up", - "moveRowDown" => "cont_ed_row_down", - "deleteRow" => "cont_ed_delete_row"), - "col" => array( "newColAfter" => "cont_ed_new_col_after", - "newColBefore" => "cont_ed_new_col_before", - "moveColLeft" => "cont_ed_col_left", - "moveColRight" => "cont_ed_col_right", - "deleteCol" => "cont_ed_delete_col") - ); - foreach($types as $type) - { - foreach($moves as $move) - { - foreach($commands[$type] as $command => $lang_var) - { - if ($move == "none" && (substr($command, 0, 4) == "move" || substr($command, 0, 6) == "delete")) - { - continue; - } - if (($move == "backward" && (in_array($command, array("movedown", "moveright")))) || - ($move == "forward" && (in_array($command, array("moveup", "moveleft"))))) - { - continue; - } - $this->tpl->setCurrentBlock("menu_item"); - $this->tpl->setVariable("MENU_ITEM_TITLE", $lng->txt($lang_var)); - $this->tpl->setVariable("CMD", $command); - $this->tpl->setVariable("TYPE", $type); - $this->tpl->parseCurrentBlock(); - } - $this->tpl->setCurrentBlock("menu"); - $this->tpl->setVariable("TYPE", $type); - $this->tpl->setVariable("MOVE", $move); - $this->tpl->parseCurrentBlock(); - } - } - - // update/cancel - $this->tpl->setCurrentBlock("commands"); - $this->tpl->setVariable("BTN_NAME", "update"); - $this->tpl->setVariable("BTN_TEXT", $this->lng->txt("save")); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setVariable("FORMACTION2", - $ilCtrl->getFormAction($this, "tableAction")); - $this->tpl->setVariable("TXT_ACTION", $this->lng->txt("cont_table")); - - } - - /** - * Update table data in dom and update page in db - */ - function update($a_redirect = true) - { - $lng = $this->lng; - - // handle input data - include_once("./Services/COPage/classes/class.ilPCParagraph.php"); - $data = array(); -//var_dump($_POST["cell"]); -//var_dump($_GET); - if (is_array($_POST["cell"])) - { - foreach ($_POST["cell"] as $i => $row) - { - if (is_array($row)) - { - foreach ($row as $j => $cell) - { - $data[$i][$j] = - ilPCParagraph::_input2xml($cell, - $this->content_obj->getLanguage()); - } - } - } - } - - $this->updated = $this->content_obj->setData($data); - - if ($this->updated !== true) - { - $this->editData(); - return; - } - - $this->updated = $this->pg_obj->update(); - - if ($a_redirect) - { - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "editData"); - } - } - - /** - * Update via JavaScript - */ - function updateJS() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if ($_POST["cancel_update"]) - { -// $this->ctrl->redirect($this, "editData"); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - // handle input data - include_once("./Services/COPage/classes/class.ilPCParagraph.php"); - include_once("./Services/COPage/classes/class.ilPCParagraphGUI.php"); - $data = array(); - foreach ($_POST as $k => $content) - { - if (substr($k, 0, 5) != "cell_") - { - continue; - } - - // determine cell content - $div = ilUtil::stripSlashes($content, false); - $p1 = strpos($div, '>'); - $div = substr($div, $p1 + 1); - $div = "
".$div; - $text = ilPCParagraph::handleAjaxContent($div); - if ($text === false) - { - $ilCtrl->returnToParent($this, "jump".$this->hier_id); - } - $text = $text["text"]; - - $text = ilPCParagraph::_input2xml($text, - $this->content_obj->getLanguage(), true, false); - $text = ilPCParagraph::handleAjaxContentPost($text); - - // set content in data array - $id = explode("_", $k); - $data[(int) $id[1]][(int) $id[2]] = $text; - } - - // update data - $this->updated = $this->content_obj->setData($data); - - if ($this->updated !== true) - { - $this->editData(); - return; - } - - $this->updated = $this->pg_obj->update(); - - - // perform table action? (move...?) - //$this->update(false); - $this->pg_obj->addHierIDs(); - $failed = false; - if ($_POST["tab_cmd"] != "") - { - $cell_hier_id = ($_POST["tab_cmd_type"] == "col") - ? $this->hier_id."_1_".($_POST["tab_cmd_id"] + 1) - : $this->hier_id."_".($_POST["tab_cmd_id"] + 1)."_1"; - $cell_obj = $this->pg_obj->getContentObject($cell_hier_id); - if (is_object($cell_obj)) - { - $tab_cmd = $_POST["tab_cmd"]; - $cell_obj->$tab_cmd(); - $ret = $this->pg_obj->update(); - if ($ret !== true) - { - ilUtil::sendFailure($ret[0][1], true); - $failed = true; - } - } - } - - if (!$failed) - { - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - } - if ($_POST["save_return"]) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - else - { - $this->ctrl->redirect($this, "editData"); - } - } - - - /** - * Get new table object - */ - function getNewTableObject() - { - return new ilPCDataTable($this->getPage()); - } - - /** - * After creation processing - */ - function afterCreation() - { - $ilCtrl = $this->ctrl; - - $this->pg_obj->stripHierIDs(); - $this->pg_obj->addHierIDs(); - $ilCtrl->setParameter($this, "hier_id", $this->content_obj->readHierId()); - $ilCtrl->setParameter($this, "pc_id", $this->content_obj->readPCId()); - $this->content_obj->setHierId($this->content_obj->readHierId()); - $this->setHierId($this->content_obj->readHierId()); - $this->content_obj->setPCId($this->content_obj->readPCId()); - $this->editData(); - } - - /** - * Perform operation on table (adding, moving, deleting rows/cols) - */ - function tableAction() - { - $ilCtrl = $this->ctrl; - - $this->update(false); - $this->pg_obj->addHierIDs(); - - $cell_hier_id = ($_POST["type"] == "col") - ? $this->hier_id."_1_".($_POST["id"] + 1) - : $this->hier_id."_".($_POST["id"] + 1)."_1"; - $cell_obj = $this->pg_obj->getContentObject($cell_hier_id); - if (is_object($cell_obj)) - { - $action = (string) ($_POST["action"]); - $cell_obj->$action(); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - } - $ilCtrl->redirect($this, "editData"); - } - - /** - * Set tabs - */ - function setTabs() - { - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - parent::setTabs(); - - $ilTabs->addTarget("cont_ed_edit_data", - $ilCtrl->getLinkTarget($this, "editData"), "editData", - get_class($this)); - - } - - - //// - //// Full JS implementation - //// - - /** - * Edit data of table - */ - function editData() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - - if (!ilPageEditorGUI::_doJSEditing()) - { - return $this->editDataCl(); - } - -//var_dump($_GET); -//var_dump($_POST); - - $this->setTabs(); - - $this->displayValidationError(); - - - include_once("./Services/COPage/classes/class.ilPCParagraph.php"); - - //$this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.tabledata2.html", "Services/COPage"); - //$dtpl = $this->tpl; - $dtpl = new ilTemplate("tpl.tabledata2.html", true, true, "Services/COPage"); - $dtpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this, "tableAction")); - - - $dtpl->setVariable("WYSIWYG_ACTION", - $ilCtrl->getFormAction($this, "updateJS")); - - // get all rows - $xpc = xpath_new_context($this->dom); - $path = "//PageContent[@HierId='".$this->getHierId()."']". - "/Table/TableRow"; - $res = xpath_eval($xpc, $path); - - for($i = 0; $i < count($res->nodeset); $i++) - { - - $xpc2 = xpath_new_context($this->dom); - $path2 = "//PageContent[@HierId='".$this->getHierId()."']". - "/Table/TableRow[$i+1]/TableData"; - $res2 = xpath_eval($xpc2, $path2); - - // if this is the first row -> col icons - if ($i == 0) - { - for($j = 0; $j < count($res2->nodeset); $j++) - { - if ($j == 0) - { - $dtpl->touchBlock("empty_td"); - } - - if ($j == 0) - { - if (count($res2->nodeset) == 1) - { - $move_type = "none"; - } - else - { - $move_type = "forward"; - } - } - else if ($j == (count($res2->nodeset) - 1)) - { - $move_type = "backward"; - } - else - { - $move_type = "both"; - } - $dtpl->setCurrentBlock("col_icon"); - $dtpl->setVariable("COL_ICON_ALT", $lng->txt("content_column")); - $dtpl->setVariable("COL_ICON", ilUtil::getImagePath("col.svg")); - $dtpl->setVariable("COL_ONCLICK", "COL_".$move_type); - $dtpl->setVariable("NR", $j); - $dtpl->parseCurrentBlock(); - } - $dtpl->setCurrentBlock("row"); - $dtpl->parseCurrentBlock(); - } - - - for($j = 0; $j < count($res2->nodeset); $j++) - { - // first col: row icons - if ($j == 0) - { - if ($i == 0) - { - if (count($res->nodeset) == 1) - { - $move_type = "none"; - } - else - { - $move_type = "forward"; - } - } - else if ($i == (count($res->nodeset) - 1)) - { - $move_type = "backward"; - } - else - { - $move_type = "both"; - } - $dtpl->setCurrentBlock("row_icon"); - $dtpl->setVariable("ROW_ICON_ALT", $lng->txt("content_row")); - $dtpl->setVariable("ROW_ICON", ilUtil::getImagePath("row.svg")); - $dtpl->setVariable("ROW_ONCLICK", "ROW_".$move_type); - $dtpl->setVariable("NR", $i); - $dtpl->parseCurrentBlock(); - } - - // cell - if ($res2->nodeset[$j]->get_attribute("Hidden") != "Y") - { - $dtpl->setCurrentBlock("cell"); - - if (is_array($_POST["cmd"]) && key($_POST["cmd"]) == "update") - { - $s_text = ilUtil::stripSlashes("cell_".$i."_".$j, false); - } - else - { - $s_text = ilPCParagraph::xml2output($this->content_obj->getCellText($i, $j), - true, false); - include_once("./Services/COPage/classes/class.ilPCParagraphGUI.php"); - $s_text = ilPCParagraphGUI::xml2outputJS($s_text, "TableContent", - $this->content_obj->readPCId()."_".$i."_".$j); - } - - // #20628 - $s_text = str_replace("{", "{", $s_text); - $s_text = str_replace("}", "}", $s_text); - - $dtpl->setVariable("PAR_TA_NAME", "cell[".$i."][".$j."]"); - $dtpl->setVariable("PAR_TA_ID", "cell_".$i."_".$j); - - $dtpl->setVariable("PAR_TA_CONTENT", $s_text); - - $cs = $res2->nodeset[$j]->get_attribute("ColSpan"); - $rs = $res2->nodeset[$j]->get_attribute("RowSpan"); - $dtpl->setVariable("WIDTH", "140"); - $dtpl->setVariable("HEIGHT", "80"); - if ($cs > 1) - { - $dtpl->setVariable("COLSPAN", 'colspan="'.$cs.'"'); - $dtpl->setVariable("WIDTH", (140 + ($cs - 1) * 146)); - } - if ($rs > 1) - { - $dtpl->setVariable("ROWSPAN", 'rowspan="'.$rs.'"'); - $dtpl->setVariable("HEIGHT", (80 + ($rs - 1) * 86)); - } - $dtpl->parseCurrentBlock(); - } - } - $dtpl->setCurrentBlock("row"); - $dtpl->parseCurrentBlock(); - } - - // init menues - $types = array("row", "col"); - $moves = array("none", "backward", "both", "forward"); - $commands = array( - "row" => array( "newRowAfter" => "cont_ed_new_row_after", - "newRowBefore" => "cont_ed_new_row_before", - "moveRowUp" => "cont_ed_row_up", - "moveRowDown" => "cont_ed_row_down", - "deleteRow" => "cont_ed_delete_row"), - "col" => array( "newColAfter" => "cont_ed_new_col_after", - "newColBefore" => "cont_ed_new_col_before", - "moveColLeft" => "cont_ed_col_left", - "moveColRight" => "cont_ed_col_right", - "deleteCol" => "cont_ed_delete_col") - ); - - foreach($types as $type) - { - foreach($moves as $move) - { - foreach($commands[$type] as $command => $lang_var) - { - if ($move == "none" && (substr($command, 0, 4) == "move" || substr($command, 0, 6) == "delete")) - { - continue; - } - if (($move == "backward" && (in_array($command, array("movedown", "moveright")))) || - ($move == "forward" && (in_array($command, array("moveup", "moveleft"))))) - { - continue; - } - $dtpl->setCurrentBlock("menu_item"); - $dtpl->setVariable("MENU_ITEM_TITLE", $lng->txt($lang_var)); - $dtpl->setVariable("CMD", $command); - $dtpl->setVariable("TYPE", $type); - $dtpl->parseCurrentBlock(); - } - $dtpl->setCurrentBlock("menu"); - $dtpl->setVariable("TYPE", $type); - $dtpl->setVariable("MOVE", $move); - $dtpl->parseCurrentBlock(); - } - } - - - $dtpl->setVariable("FORMACTION2", - $ilCtrl->getFormAction($this, "tableAction")); - $dtpl->setVariable("TXT_ACTION", $this->lng->txt("cont_table")); - - // js editing preparation - include_once("./Services/YUI/classes/class.ilYuiUtil.php"); - ilYuiUtil::initDragDrop(); - ilYuiUtil::initConnection(); - ilYuiUtil::initPanel(false); - //$GLOBALS["tpl"]->addJavascript("Services/COPage/tiny/4_2_4/tinymce.js"); - $GLOBALS["tpl"]->addJavascript("./libs/bower/bower_components/tinymce/tinymce.min.js"); - $GLOBALS["tpl"]->addJavaScript("./Services/COPage/js/ilcopagecallback.js"); - $GLOBALS["tpl"]->addJavascript("Services/COPage/js/page_editing.js"); - - $GLOBALS["tpl"]->addOnloadCode("var preloader = new Image(); + /** + * @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->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->tabs = $DIC->tabs(); + parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); + $this->setCharacteristics(array("StandardTable" => $this->lng->txt("cont_StandardTable"))); + } + + /** + * execute command + */ + public function executeCommand() + { + $this->getCharacteristicsOfCurrentStyle("table"); // scorm-2004 + + // 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; + } + + + //// + //// Classic editing + //// + + /** + * Edit data of table. (classic version) + */ + public function editDataCl() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + //var_dump($_GET); + //var_dump($_POST); + + $this->setTabs(); + + $this->displayValidationError(); + + include_once("./Services/COPage/classes/class.ilPCParagraph.php"); + + $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.tabledata.html", "Services/COPage"); + $dtpl = $this->tpl; + //$dtpl = new ilTemplate("tpl.tabledata.html", true, true, "Services/COPage"); + $dtpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this, "tableAction")); + $dtpl->setVariable("BB_MENU", $this->getBBMenu("cell_0_0")); + + ilYuiUtil::initDragDrop(); + ilYuiUtil::initConnection(); + ilYuiUtil::initPanel(false); + $this->tpl->addJavascript("./Services/COPage/phpBB/3_0_5/editor.js"); + $this->tpl->addJavascript("./Services/COPage/js/page_editing.js"); + $this->tpl->addJavascript("./Services/COPage/js/paragraph_editing.js"); + + // get all rows + $xpc = xpath_new_context($this->dom); + $path = "//PageContent[@HierId='" . $this->getHierId() . "']" . + "/Table/TableRow"; + $res = xpath_eval($xpc, $path); + + for ($i = 0; $i < count($res->nodeset); $i++) { + $xpc2 = xpath_new_context($this->dom); + $path2 = "//PageContent[@HierId='" . $this->getHierId() . "']" . + "/Table/TableRow[$i+1]/TableData"; + $res2 = xpath_eval($xpc2, $path2); + + // if this is the first row -> col icons + if ($i == 0) { + for ($j = 0; $j < count($res2->nodeset); $j++) { + if ($j == 0) { + $dtpl->touchBlock("empty_td"); + } + + if ($j == 0) { + if (count($res2->nodeset) == 1) { + $move_type = "none"; + } else { + $move_type = "forward"; + } + } elseif ($j == (count($res2->nodeset) - 1)) { + $move_type = "backward"; + } else { + $move_type = "both"; + } + $dtpl->setCurrentBlock("col_icon"); + $dtpl->setVariable("COL_ICON_ALT", $lng->txt("content_column")); + $dtpl->setVariable("COL_ICON", ilUtil::getImagePath("col.svg")); + $dtpl->setVariable("COL_ONCLICK", "COL_" . $move_type); + $dtpl->setVariable("NR", $j); + $dtpl->parseCurrentBlock(); + } + $dtpl->setCurrentBlock("row"); + $dtpl->parseCurrentBlock(); + } + + + for ($j = 0; $j < count($res2->nodeset); $j++) { + // first col: row icons + if ($j == 0) { + if ($i == 0) { + if (count($res->nodeset) == 1) { + $move_type = "none"; + } else { + $move_type = "forward"; + } + } elseif ($i == (count($res->nodeset) - 1)) { + $move_type = "backward"; + } else { + $move_type = "both"; + } + $dtpl->setCurrentBlock("row_icon"); + $dtpl->setVariable("ROW_ICON_ALT", $lng->txt("content_row")); + $dtpl->setVariable("ROW_ICON", ilUtil::getImagePath("row.svg")); + $dtpl->setVariable("ROW_ONCLICK", "ROW_" . $move_type); + $dtpl->setVariable("NR", $i); + $dtpl->parseCurrentBlock(); + } + + // cell + if ($res2->nodeset[$j]->get_attribute("Hidden") != "Y") { + $dtpl->setCurrentBlock("cell"); + + if (is_array($_POST["cmd"]) && key($_POST["cmd"]) == "update") { + $s_text = ilUtil::stripSlashes("cell_" . $i . "_" . $j, false); + } else { + $s_text = ilPCParagraph::xml2output($this->content_obj->getCellText($i, $j)); + } + + $dtpl->setVariable("PAR_TA_NAME", "cell[" . $i . "][" . $j . "]"); + $dtpl->setVariable("PAR_TA_ID", "cell_" . $i . "_" . $j); + $dtpl->setVariable("PAR_TA_CONTENT", $s_text); + + $cs = $res2->nodeset[$j]->get_attribute("ColSpan"); + $rs = $res2->nodeset[$j]->get_attribute("RowSpan"); + // $dtpl->setVariable("WIDTH", "140"); + // $dtpl->setVariable("HEIGHT", "80"); + if ($cs > 1) { + $dtpl->setVariable("COLSPAN", 'colspan="' . $cs . '"'); + $dtpl->setVariable("WIDTH", (140 + ($cs - 1) * 146)); + } + if ($rs > 1) { + $dtpl->setVariable("ROWSPAN", 'rowspan="' . $rs . '"'); + $dtpl->setVariable("HEIGHT", (80 + ($rs - 1) * 86)); + } + $dtpl->parseCurrentBlock(); + } + } + $dtpl->setCurrentBlock("row"); + $dtpl->parseCurrentBlock(); + } + + // init menues + $types = array("row", "col"); + $moves = array("none", "backward", "both", "forward"); + $commands = array( + "row" => array( "newRowAfter" => "cont_ed_new_row_after", + "newRowBefore" => "cont_ed_new_row_before", + "moveRowUp" => "cont_ed_row_up", + "moveRowDown" => "cont_ed_row_down", + "deleteRow" => "cont_ed_delete_row"), + "col" => array( "newColAfter" => "cont_ed_new_col_after", + "newColBefore" => "cont_ed_new_col_before", + "moveColLeft" => "cont_ed_col_left", + "moveColRight" => "cont_ed_col_right", + "deleteCol" => "cont_ed_delete_col") + ); + foreach ($types as $type) { + foreach ($moves as $move) { + foreach ($commands[$type] as $command => $lang_var) { + if ($move == "none" && (substr($command, 0, 4) == "move" || substr($command, 0, 6) == "delete")) { + continue; + } + if (($move == "backward" && (in_array($command, array("movedown", "moveright")))) || + ($move == "forward" && (in_array($command, array("moveup", "moveleft"))))) { + continue; + } + $this->tpl->setCurrentBlock("menu_item"); + $this->tpl->setVariable("MENU_ITEM_TITLE", $lng->txt($lang_var)); + $this->tpl->setVariable("CMD", $command); + $this->tpl->setVariable("TYPE", $type); + $this->tpl->parseCurrentBlock(); + } + $this->tpl->setCurrentBlock("menu"); + $this->tpl->setVariable("TYPE", $type); + $this->tpl->setVariable("MOVE", $move); + $this->tpl->parseCurrentBlock(); + } + } + + // update/cancel + $this->tpl->setCurrentBlock("commands"); + $this->tpl->setVariable("BTN_NAME", "update"); + $this->tpl->setVariable("BTN_TEXT", $this->lng->txt("save")); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setVariable( + "FORMACTION2", + $ilCtrl->getFormAction($this, "tableAction") + ); + $this->tpl->setVariable("TXT_ACTION", $this->lng->txt("cont_table")); + } + + /** + * Update table data in dom and update page in db + */ + public function update($a_redirect = true) + { + $lng = $this->lng; + + // handle input data + include_once("./Services/COPage/classes/class.ilPCParagraph.php"); + $data = array(); + //var_dump($_POST["cell"]); + //var_dump($_GET); + if (is_array($_POST["cell"])) { + foreach ($_POST["cell"] as $i => $row) { + if (is_array($row)) { + foreach ($row as $j => $cell) { + $data[$i][$j] = + ilPCParagraph::_input2xml( + $cell, + $this->content_obj->getLanguage() + ); + } + } + } + } + + $this->updated = $this->content_obj->setData($data); + + if ($this->updated !== true) { + $this->editData(); + return; + } + + $this->updated = $this->pg_obj->update(); + + if ($a_redirect) { + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "editData"); + } + } + + /** + * Update via JavaScript + */ + public function updateJS() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if ($_POST["cancel_update"]) { + // $this->ctrl->redirect($this, "editData"); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + // handle input data + include_once("./Services/COPage/classes/class.ilPCParagraph.php"); + include_once("./Services/COPage/classes/class.ilPCParagraphGUI.php"); + $data = array(); + foreach ($_POST as $k => $content) { + if (substr($k, 0, 5) != "cell_") { + continue; + } + + // determine cell content + $div = ilUtil::stripSlashes($content, false); + $p1 = strpos($div, '>'); + $div = substr($div, $p1 + 1); + $div = "
" . $div; + $text = ilPCParagraph::handleAjaxContent($div); + if ($text === false) { + $ilCtrl->returnToParent($this, "jump" . $this->hier_id); + } + $text = $text["text"]; + + $text = ilPCParagraph::_input2xml( + $text, + $this->content_obj->getLanguage(), + true, + false + ); + $text = ilPCParagraph::handleAjaxContentPost($text); + + // set content in data array + $id = explode("_", $k); + $data[(int) $id[1]][(int) $id[2]] = $text; + } + + // update data + $this->updated = $this->content_obj->setData($data); + + if ($this->updated !== true) { + $this->editData(); + return; + } + + $this->updated = $this->pg_obj->update(); + + + // perform table action? (move...?) + //$this->update(false); + $this->pg_obj->addHierIDs(); + $failed = false; + if ($_POST["tab_cmd"] != "") { + $cell_hier_id = ($_POST["tab_cmd_type"] == "col") + ? $this->hier_id . "_1_" . ($_POST["tab_cmd_id"] + 1) + : $this->hier_id . "_" . ($_POST["tab_cmd_id"] + 1) . "_1"; + $cell_obj = $this->pg_obj->getContentObject($cell_hier_id); + if (is_object($cell_obj)) { + $tab_cmd = $_POST["tab_cmd"]; + $cell_obj->$tab_cmd(); + $ret = $this->pg_obj->update(); + if ($ret !== true) { + ilUtil::sendFailure($ret[0][1], true); + $failed = true; + } + } + } + + if (!$failed) { + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + } + if ($_POST["save_return"]) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } else { + $this->ctrl->redirect($this, "editData"); + } + } + + + /** + * Get new table object + */ + public function getNewTableObject() + { + return new ilPCDataTable($this->getPage()); + } + + /** + * After creation processing + */ + public function afterCreation() + { + $ilCtrl = $this->ctrl; + + $this->pg_obj->stripHierIDs(); + $this->pg_obj->addHierIDs(); + $ilCtrl->setParameter($this, "hier_id", $this->content_obj->readHierId()); + $ilCtrl->setParameter($this, "pc_id", $this->content_obj->readPCId()); + $this->content_obj->setHierId($this->content_obj->readHierId()); + $this->setHierId($this->content_obj->readHierId()); + $this->content_obj->setPCId($this->content_obj->readPCId()); + $this->editData(); + } + + /** + * Perform operation on table (adding, moving, deleting rows/cols) + */ + public function tableAction() + { + $ilCtrl = $this->ctrl; + + $this->update(false); + $this->pg_obj->addHierIDs(); + + $cell_hier_id = ($_POST["type"] == "col") + ? $this->hier_id . "_1_" . ($_POST["id"] + 1) + : $this->hier_id . "_" . ($_POST["id"] + 1) . "_1"; + $cell_obj = $this->pg_obj->getContentObject($cell_hier_id); + if (is_object($cell_obj)) { + $action = (string) ($_POST["action"]); + $cell_obj->$action(); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + } + $ilCtrl->redirect($this, "editData"); + } + + /** + * Set tabs + */ + public function setTabs() + { + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + parent::setTabs(); + + $ilTabs->addTarget( + "cont_ed_edit_data", + $ilCtrl->getLinkTarget($this, "editData"), + "editData", + get_class($this) + ); + } + + + //// + //// Full JS implementation + //// + + /** + * Edit data of table + */ + public function editData() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + + if (!ilPageEditorGUI::_doJSEditing()) { + return $this->editDataCl(); + } + + //var_dump($_GET); + //var_dump($_POST); + + $this->setTabs(); + + $this->displayValidationError(); + + + include_once("./Services/COPage/classes/class.ilPCParagraph.php"); + + //$this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.tabledata2.html", "Services/COPage"); + //$dtpl = $this->tpl; + $dtpl = new ilTemplate("tpl.tabledata2.html", true, true, "Services/COPage"); + $dtpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this, "tableAction")); + + + $dtpl->setVariable( + "WYSIWYG_ACTION", + $ilCtrl->getFormAction($this, "updateJS") + ); + + // get all rows + $xpc = xpath_new_context($this->dom); + $path = "//PageContent[@HierId='" . $this->getHierId() . "']" . + "/Table/TableRow"; + $res = xpath_eval($xpc, $path); + + for ($i = 0; $i < count($res->nodeset); $i++) { + $xpc2 = xpath_new_context($this->dom); + $path2 = "//PageContent[@HierId='" . $this->getHierId() . "']" . + "/Table/TableRow[$i+1]/TableData"; + $res2 = xpath_eval($xpc2, $path2); + + // if this is the first row -> col icons + if ($i == 0) { + for ($j = 0; $j < count($res2->nodeset); $j++) { + if ($j == 0) { + $dtpl->touchBlock("empty_td"); + } + + if ($j == 0) { + if (count($res2->nodeset) == 1) { + $move_type = "none"; + } else { + $move_type = "forward"; + } + } elseif ($j == (count($res2->nodeset) - 1)) { + $move_type = "backward"; + } else { + $move_type = "both"; + } + $dtpl->setCurrentBlock("col_icon"); + $dtpl->setVariable("COL_ICON_ALT", $lng->txt("content_column")); + $dtpl->setVariable("COL_ICON", ilUtil::getImagePath("col.svg")); + $dtpl->setVariable("COL_ONCLICK", "COL_" . $move_type); + $dtpl->setVariable("NR", $j); + $dtpl->parseCurrentBlock(); + } + $dtpl->setCurrentBlock("row"); + $dtpl->parseCurrentBlock(); + } + + + for ($j = 0; $j < count($res2->nodeset); $j++) { + // first col: row icons + if ($j == 0) { + if ($i == 0) { + if (count($res->nodeset) == 1) { + $move_type = "none"; + } else { + $move_type = "forward"; + } + } elseif ($i == (count($res->nodeset) - 1)) { + $move_type = "backward"; + } else { + $move_type = "both"; + } + $dtpl->setCurrentBlock("row_icon"); + $dtpl->setVariable("ROW_ICON_ALT", $lng->txt("content_row")); + $dtpl->setVariable("ROW_ICON", ilUtil::getImagePath("row.svg")); + $dtpl->setVariable("ROW_ONCLICK", "ROW_" . $move_type); + $dtpl->setVariable("NR", $i); + $dtpl->parseCurrentBlock(); + } + + // cell + if ($res2->nodeset[$j]->get_attribute("Hidden") != "Y") { + $dtpl->setCurrentBlock("cell"); + + if (is_array($_POST["cmd"]) && key($_POST["cmd"]) == "update") { + $s_text = ilUtil::stripSlashes("cell_" . $i . "_" . $j, false); + } else { + $s_text = ilPCParagraph::xml2output( + $this->content_obj->getCellText($i, $j), + true, + false + ); + include_once("./Services/COPage/classes/class.ilPCParagraphGUI.php"); + $s_text = ilPCParagraphGUI::xml2outputJS( + $s_text, + "TableContent", + $this->content_obj->readPCId() . "_" . $i . "_" . $j + ); + } + + // #20628 + $s_text = str_replace("{", "{", $s_text); + $s_text = str_replace("}", "}", $s_text); + + $dtpl->setVariable("PAR_TA_NAME", "cell[" . $i . "][" . $j . "]"); + $dtpl->setVariable("PAR_TA_ID", "cell_" . $i . "_" . $j); + + $dtpl->setVariable("PAR_TA_CONTENT", $s_text); + + $cs = $res2->nodeset[$j]->get_attribute("ColSpan"); + $rs = $res2->nodeset[$j]->get_attribute("RowSpan"); + $dtpl->setVariable("WIDTH", "140"); + $dtpl->setVariable("HEIGHT", "80"); + if ($cs > 1) { + $dtpl->setVariable("COLSPAN", 'colspan="' . $cs . '"'); + $dtpl->setVariable("WIDTH", (140 + ($cs - 1) * 146)); + } + if ($rs > 1) { + $dtpl->setVariable("ROWSPAN", 'rowspan="' . $rs . '"'); + $dtpl->setVariable("HEIGHT", (80 + ($rs - 1) * 86)); + } + $dtpl->parseCurrentBlock(); + } + } + $dtpl->setCurrentBlock("row"); + $dtpl->parseCurrentBlock(); + } + + // init menues + $types = array("row", "col"); + $moves = array("none", "backward", "both", "forward"); + $commands = array( + "row" => array( "newRowAfter" => "cont_ed_new_row_after", + "newRowBefore" => "cont_ed_new_row_before", + "moveRowUp" => "cont_ed_row_up", + "moveRowDown" => "cont_ed_row_down", + "deleteRow" => "cont_ed_delete_row"), + "col" => array( "newColAfter" => "cont_ed_new_col_after", + "newColBefore" => "cont_ed_new_col_before", + "moveColLeft" => "cont_ed_col_left", + "moveColRight" => "cont_ed_col_right", + "deleteCol" => "cont_ed_delete_col") + ); + + foreach ($types as $type) { + foreach ($moves as $move) { + foreach ($commands[$type] as $command => $lang_var) { + if ($move == "none" && (substr($command, 0, 4) == "move" || substr($command, 0, 6) == "delete")) { + continue; + } + if (($move == "backward" && (in_array($command, array("movedown", "moveright")))) || + ($move == "forward" && (in_array($command, array("moveup", "moveleft"))))) { + continue; + } + $dtpl->setCurrentBlock("menu_item"); + $dtpl->setVariable("MENU_ITEM_TITLE", $lng->txt($lang_var)); + $dtpl->setVariable("CMD", $command); + $dtpl->setVariable("TYPE", $type); + $dtpl->parseCurrentBlock(); + } + $dtpl->setCurrentBlock("menu"); + $dtpl->setVariable("TYPE", $type); + $dtpl->setVariable("MOVE", $move); + $dtpl->parseCurrentBlock(); + } + } + + + $dtpl->setVariable( + "FORMACTION2", + $ilCtrl->getFormAction($this, "tableAction") + ); + $dtpl->setVariable("TXT_ACTION", $this->lng->txt("cont_table")); + + // js editing preparation + include_once("./Services/YUI/classes/class.ilYuiUtil.php"); + ilYuiUtil::initDragDrop(); + ilYuiUtil::initConnection(); + ilYuiUtil::initPanel(false); + //$GLOBALS["tpl"]->addJavascript("Services/COPage/tiny/4_2_4/tinymce.js"); + $GLOBALS["tpl"]->addJavascript("./libs/bower/bower_components/tinymce/tinymce.min.js"); + $GLOBALS["tpl"]->addJavaScript("./Services/COPage/js/ilcopagecallback.js"); + $GLOBALS["tpl"]->addJavascript("Services/COPage/js/page_editing.js"); + + $GLOBALS["tpl"]->addOnloadCode("var preloader = new Image(); preloader.src = './templates/default/images/loader.svg'; - ilCOPage.setContentCss('". - ilObjStyleSheet::getContentStylePath((int) $this->getStyleId()). - ", ".ilUtil::getStyleSheetLocation().", ./Services/COPage/css/tiny_extra.css'); + ilCOPage.setContentCss('" . + ilObjStyleSheet::getContentStylePath((int) $this->getStyleId()) . + ", " . ilUtil::getStyleSheetLocation() . ", ./Services/COPage/css/tiny_extra.css'); ilCOPage.editTD('cell_0_0'); "); - $cfg = $this->getPageConfig(); - - $dtpl->setVariable("IL_TINY_MENU", - ilPageObjectGUI::getTinyMenu( - $this->pg_obj->getParentType(), - $cfg->getEnableInternalLinks(), - $cfg->getEnableWikiLinks(), - $cfg->getEnableKeywords(), - $this->getStyleId(), - false, true, $cfg->getEnableAnchors(), false)); - - // add int link parts - if ($cfg->getEnableInternalLinks() || $cfg->getEnableWikiLinks()) - { - include_once("./Services/Link/classes/class.ilInternalLinkGUI.php"); - $dtpl->setCurrentBlock("int_link_prep"); - $dtpl->setVariable("INT_LINK_PREP", ilInternalLinkGUI::getInitHTML( - $ilCtrl->getLinkTargetByClass(array("ilpageeditorgui", "ilinternallinkgui"), - "", false, true, false))); - } - - $this->tpl->setContent($dtpl->get()); - } - - + $cfg = $this->getPageConfig(); + + $dtpl->setVariable( + "IL_TINY_MENU", + ilPageObjectGUI::getTinyMenu( + $this->pg_obj->getParentType(), + $cfg->getEnableInternalLinks(), + $cfg->getEnableWikiLinks(), + $cfg->getEnableKeywords(), + $this->getStyleId(), + false, + true, + $cfg->getEnableAnchors(), + false + ) + ); + + // add int link parts + if ($cfg->getEnableInternalLinks() || $cfg->getEnableWikiLinks()) { + include_once("./Services/Link/classes/class.ilInternalLinkGUI.php"); + $dtpl->setCurrentBlock("int_link_prep"); + $dtpl->setVariable("INT_LINK_PREP", ilInternalLinkGUI::getInitHTML( + $ilCtrl->getLinkTargetByClass( + array("ilpageeditorgui", "ilinternallinkgui"), + "", + false, + true, + false + ) + )); + } + + $this->tpl->setContent($dtpl->get()); + } } -?> \ No newline at end of file diff --git a/Services/COPage/classes/class.ilPCFileItem.php b/Services/COPage/classes/class.ilPCFileItem.php index 4c0c1b363871eca05bf7e3ef7fb326b89a71bbb7..2890d81cbe73180e88dfd8c415f054b82c6da6ba 100755 --- a/Services/COPage/classes/class.ilPCFileItem.php +++ b/Services/COPage/classes/class.ilPCFileItem.php @@ -17,108 +17,104 @@ require_once("./Services/COPage/classes/class.ilPageContent.php"); */ class ilPCFileItem extends ilPageContent { - /** - * Init page content component. - */ - function init() - { - $this->setType("flit"); - } + /** + * Init page content component. + */ + public function init() + { + $this->setType("flit"); + } - /** - * insert new list item after current one - */ - function newItemAfter($a_id, $a_location, $a_format) - { - $li = $this->getNode(); - $new_item = $this->dom->create_element("FileItem"); - if ($next_li = $li->next_sibling()) - { - $new_item = $next_li->insert_before($new_item, $next_li); - } - else - { - $parent_list = $li->parent_node(); - $new_item = $parent_list->append_child($new_item); - } + /** + * insert new list item after current one + */ + public function newItemAfter($a_id, $a_location, $a_format) + { + $li = $this->getNode(); + $new_item = $this->dom->create_element("FileItem"); + if ($next_li = $li->next_sibling()) { + $new_item = $next_li->insert_before($new_item, $next_li); + } else { + $parent_list = $li->parent_node(); + $new_item = $parent_list->append_child($new_item); + } - // Identifier - $id_node = $this->dom->create_element("Identifier"); - $id_node = $new_item->append_child($id_node); - $id_node->set_attribute("Catalog", "ILIAS"); - $id_node->set_attribute("Entry", "il__file_".$a_id); + // Identifier + $id_node = $this->dom->create_element("Identifier"); + $id_node = $new_item->append_child($id_node); + $id_node->set_attribute("Catalog", "ILIAS"); + $id_node->set_attribute("Entry", "il__file_" . $a_id); - // Location - $loc_node = $this->dom->create_element("Location"); - $loc_node = $new_item->append_child($loc_node); - $loc_node->set_attribute("Type", "LocalFile"); - $loc_node->set_content($a_location); + // Location + $loc_node = $this->dom->create_element("Location"); + $loc_node = $new_item->append_child($loc_node); + $loc_node->set_attribute("Type", "LocalFile"); + $loc_node->set_content($a_location); - // Format - $form_node = $this->dom->create_element("Format"); - $form_node = $new_item->append_child($form_node); - $form_node->set_content($a_format); - } + // Format + $form_node = $this->dom->create_element("Format"); + $form_node = $new_item->append_child($form_node); + $form_node->set_content($a_format); + } - /** - * insert new list item before current one - */ - function newItemBefore($a_id, $a_location, $a_format) - { - $li = $this->getNode(); - $new_item = $this->dom->create_element("FileItem"); - $new_item = $li->insert_before($new_item, $li); + /** + * insert new list item before current one + */ + public function newItemBefore($a_id, $a_location, $a_format) + { + $li = $this->getNode(); + $new_item = $this->dom->create_element("FileItem"); + $new_item = $li->insert_before($new_item, $li); - // Identifier - $id_node = $this->dom->create_element("Identifier"); - $id_node = $new_item->append_child($id_node); - $id_node->set_attribute("Catalog", "ILIAS"); - $id_node->set_attribute("Entry", "il__file_".$a_id); + // Identifier + $id_node = $this->dom->create_element("Identifier"); + $id_node = $new_item->append_child($id_node); + $id_node->set_attribute("Catalog", "ILIAS"); + $id_node->set_attribute("Entry", "il__file_" . $a_id); - // Location - $loc_node = $this->dom->create_element("Location"); - $loc_node = $new_item->append_child($loc_node); - $loc_node->set_attribute("Type", "LocalFile"); - $loc_node->set_content($a_location); + // Location + $loc_node = $this->dom->create_element("Location"); + $loc_node = $new_item->append_child($loc_node); + $loc_node->set_attribute("Type", "LocalFile"); + $loc_node->set_content($a_location); - // Format - $form_node = $this->dom->create_element("Format"); - $form_node = $new_item->append_child($form_node); - $form_node->set_content($a_format); - } + // Format + $form_node = $this->dom->create_element("Format"); + $form_node = $new_item->append_child($form_node); + $form_node->set_content($a_format); + } - /** - * Delete file item - */ - function deleteItem() - { - $li = $this->getNode(); - $li->unlink($li); - } - - /** - * move list item down - */ - function moveItemDown() - { - $li = $this->getNode(); - $next = $li->next_sibling(); - $next_copy = $next->clone_node(true); - $next_copy = $li->insert_before($next_copy, $li); - $next->unlink($next); - } + /** + * Delete file item + */ + public function deleteItem() + { + $li = $this->getNode(); + $li->unlink($li); + } + + /** + * move list item down + */ + public function moveItemDown() + { + $li = $this->getNode(); + $next = $li->next_sibling(); + $next_copy = $next->clone_node(true); + $next_copy = $li->insert_before($next_copy, $li); + $next->unlink($next); + } - /** - * move list item up - */ - function moveItemUp() - { - $li = $this->getNode(); - $prev = $li->previous_sibling(); - $li_copy = $li->clone_node(true); - $li_copy = $prev->insert_before($li_copy, $prev); - $li->unlink($li); - } + /** + * move list item up + */ + public function moveItemUp() + { + $li = $this->getNode(); + $prev = $li->previous_sibling(); + $li_copy = $li->clone_node(true); + $li_copy = $prev->insert_before($li_copy, $prev); + $li->unlink($li); + } } -?> diff --git a/Services/COPage/classes/class.ilPCFileItemFileSelectorGUI.php b/Services/COPage/classes/class.ilPCFileItemFileSelectorGUI.php index 3331f3976bc91a969df2d9f4f11434e93f8f31e0..406bc312cb0b088095688d8fe6bccc6da87d50c2 100644 --- a/Services/COPage/classes/class.ilPCFileItemFileSelectorGUI.php +++ b/Services/COPage/classes/class.ilPCFileItemFileSelectorGUI.php @@ -12,45 +12,46 @@ include_once("./Services/Repository/classes/class.ilRepositorySelectorExplorerGU */ class ilPCFileItemFileSelectorGUI extends ilRepositorySelectorExplorerGUI { - /** - * @inheritdoc - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_selection_gui = null, $a_selection_cmd = "selectObject", - $a_selection_par = "sel_ref_id", $a_id = "rep_exp_sel") - { - parent::__construct($a_parent_obj, $a_parent_cmd, $a_selection_gui, $a_selection_cmd, $a_selection_par, $a_id); - $this->setTypeWhiteList(array("root", "cat", "grp", "crs", "file", "fold")); - $this->setClickableTypes(array("file")); - } - - - /** - * @inheritdoc - */ - function getNodeHref($a_node) - { - $ctrl = $this->ctrl; - - $ctrl->setParameterByClass($this->selection_gui, "subCmd", "selectFile"); - - return parent::getNodeHref($a_node); - } - - /** - * @inheritdoc - */ - function isNodeClickable($a_node) - { - $access = $this->access; - - if (!$access->checkAccess("write", "", $a_node["child"])) - { - return false; - } - - return parent::isNodeClickable($a_node); - } - + /** + * @inheritdoc + */ + public function __construct( + $a_parent_obj, + $a_parent_cmd, + $a_selection_gui = null, + $a_selection_cmd = "selectObject", + $a_selection_par = "sel_ref_id", + $a_id = "rep_exp_sel" + ) { + parent::__construct($a_parent_obj, $a_parent_cmd, $a_selection_gui, $a_selection_cmd, $a_selection_par, $a_id); + $this->setTypeWhiteList(array("root", "cat", "grp", "crs", "file", "fold")); + $this->setClickableTypes(array("file")); + } + + + /** + * @inheritdoc + */ + public function getNodeHref($a_node) + { + $ctrl = $this->ctrl; + + $ctrl->setParameterByClass($this->selection_gui, "subCmd", "selectFile"); + + return parent::getNodeHref($a_node); + } + + /** + * @inheritdoc + */ + public function isNodeClickable($a_node) + { + $access = $this->access; + + if (!$access->checkAccess("write", "", $a_node["child"])) { + return false; + } + + return parent::isNodeClickable($a_node); + } } - -?> \ No newline at end of file diff --git a/Services/COPage/classes/class.ilPCFileItemGUI.php b/Services/COPage/classes/class.ilPCFileItemGUI.php index 7ab151ba0ba3c23bece6c3f9c05a0820387aba4f..96a95cb2256f529fc775ddc775207434ac8d4f8b 100755 --- a/Services/COPage/classes/class.ilPCFileItemGUI.php +++ b/Services/COPage/classes/class.ilPCFileItemGUI.php @@ -1,24 +1,24 @@ lng = $DIC->language(); - $this->tabs = $DIC->tabs(); - $this->ctrl = $DIC->ctrl(); - $this->user = $DIC->user(); - $this->tpl = $DIC["tpl"]; - $this->tree = $DIC->repositoryTree(); - $this->settings = $DIC->settings(); - 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 file item - */ - function newFileItem() - { - $lng = $this->lng; - - if ($_FILES["file"]["name"] == "") - { - $_GET["subCmd"] = "-"; - ilUtil::sendFailure($lng->txt("upload_error_file_not_found")); - return false; - } - - $form = $this->initAddFileForm(); - $form->checkInput(); - - include_once("./Modules/File/classes/class.ilObjFile.php"); - $fileObj = new ilObjFile(); - $fileObj->setType("file"); - $fileObj->setTitle($_FILES["file"]["name"]); - $fileObj->setDescription(""); - $fileObj->setFileName($_FILES["file"]["name"]); - $fileObj->setFileType($_FILES["file"]["type"]); - $fileObj->setFileSize($_FILES["file"]["size"]); - $fileObj->setMode("filelist"); - $fileObj->create(); - $fileObj->raiseUploadError(false); - // upload file to filesystem - $fileObj->createDirectory(); - global $DIC; - $upload = $DIC->upload(); - if ($upload->hasBeenProcessed() !== true) { - $upload->process(); - } - $fileObj->getUploadFile($_FILES["file"]["tmp_name"], - $_FILES["file"]["name"]); - - $this->file_object = $fileObj; - return true; - } - - - /** - * insert new list item after current one - */ - function newItemAfter() - { - $ilTabs = $this->tabs; - - if ($_GET["subCmd"] == "insertNew") - { - $_SESSION["cont_file_insert"] = "insertNew"; - } - if ($_GET["subCmd"] == "insertFromRepository") - { - $_SESSION["cont_file_insert"] = "insertFromRepository"; - } - if ($_GET["subCmd"] == "insertFromWorkspace") - { - $_SESSION["cont_file_insert"] = "insertFromWorkspace"; - } - if (($_GET["subCmd"] == "") && $_SESSION["cont_file_insert"] != "") - { - $_GET["subCmd"] = $_SESSION["cont_file_insert"]; - } - - switch ($_GET["subCmd"]) - { - case "insertFromWorkspace": - $this->insertFromWorkspace("newItemAfter"); - break; - - case "insertFromRepository": - $this->insertFromRepository("newItemAfter"); - break; - - case "selectFile": - $this->insertNewItemAfter($_GET["file_ref_id"]); - break; - - default: - $this->setTabs("newItemAfter"); - $ilTabs->setSubTabActive("cont_new_file"); - - $this->displayValidationError(); - $form = $this->initAddFileForm(false); - $this->tpl->setContent($form->getHTML()); + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilTree + */ + protected $tree; + + /** + * @var ilSetting + */ + protected $settings; + + + /** + * Constructor + * @access public + */ + public function __construct(&$a_pg_obj, &$a_content_obj, $a_hier_id, $a_pc_id = "") + { + global $DIC; + + $this->lng = $DIC->language(); + $this->tabs = $DIC->tabs(); + $this->ctrl = $DIC->ctrl(); + $this->user = $DIC->user(); + $this->tpl = $DIC["tpl"]; + $this->tree = $DIC->repositoryTree(); + $this->settings = $DIC->settings(); + 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 file item + */ + public function newFileItem() + { + $lng = $this->lng; + + if ($_FILES["file"]["name"] == "") { + $_GET["subCmd"] = "-"; + ilUtil::sendFailure($lng->txt("upload_error_file_not_found")); + return false; + } + + $form = $this->initAddFileForm(); + $form->checkInput(); + + include_once("./Modules/File/classes/class.ilObjFile.php"); + $fileObj = new ilObjFile(); + $fileObj->setType("file"); + $fileObj->setTitle($_FILES["file"]["name"]); + $fileObj->setDescription(""); + $fileObj->setFileName($_FILES["file"]["name"]); + $fileObj->setFileType($_FILES["file"]["type"]); + $fileObj->setFileSize($_FILES["file"]["size"]); + $fileObj->setMode("filelist"); + $fileObj->create(); + $fileObj->raiseUploadError(false); + // upload file to filesystem + $fileObj->createDirectory(); + global $DIC; + $upload = $DIC->upload(); + if ($upload->hasBeenProcessed() !== true) { + $upload->process(); + } + $fileObj->getUploadFile( + $_FILES["file"]["tmp_name"], + $_FILES["file"]["name"] + ); + + $this->file_object = $fileObj; + return true; + } + + + /** + * insert new list item after current one + */ + public function newItemAfter() + { + $ilTabs = $this->tabs; + + if ($_GET["subCmd"] == "insertNew") { + $_SESSION["cont_file_insert"] = "insertNew"; + } + if ($_GET["subCmd"] == "insertFromRepository") { + $_SESSION["cont_file_insert"] = "insertFromRepository"; + } + if ($_GET["subCmd"] == "insertFromWorkspace") { + $_SESSION["cont_file_insert"] = "insertFromWorkspace"; + } + if (($_GET["subCmd"] == "") && $_SESSION["cont_file_insert"] != "") { + $_GET["subCmd"] = $_SESSION["cont_file_insert"]; + } + + switch ($_GET["subCmd"]) { + case "insertFromWorkspace": + $this->insertFromWorkspace("newItemAfter"); + break; + + case "insertFromRepository": + $this->insertFromRepository("newItemAfter"); + break; + + case "selectFile": + $this->insertNewItemAfter($_GET["file_ref_id"]); + break; + + default: + $this->setTabs("newItemAfter"); + $ilTabs->setSubTabActive("cont_new_file"); + + $this->displayValidationError(); + $form = $this->initAddFileForm(false); + $this->tpl->setContent($form->getHTML()); break; - // new file list form - $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.file_item_edit.html", "Services/COPage"); - $this->tpl->setVariable("TXT_ACTION", $this->lng->txt("cont_insert_file_item")); - $this->tpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this)); - - $this->displayValidationError(); - - // file - $this->tpl->setVariable("TXT_FILE", $this->lng->txt("file")); - - $this->tpl->parseCurrentBlock(); - - // operations - $this->tpl->setCurrentBlock("commands"); - $this->tpl->setVariable("BTN_NAME", "insertNewItemAfter"); - $this->tpl->setVariable("BTN_TEXT", $this->lng->txt("save")); - $this->tpl->parseCurrentBlock(); - break; - } - } - - /** - * Init add file form - */ - public function initAddFileForm($a_before = true) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - - // file - $fi = new ilFileInputGUI($lng->txt("file"), "file"); - $fi->setRequired(true); - $form->addItem($fi); - - if ($a_before) - { - $form->addCommandButton("insertNewItemBefore", $lng->txt("save")); - } - else - { - $form->addCommandButton("insertNewItemAfter", $lng->txt("save")); - } - $form->addCommandButton("cancelAddFile", $lng->txt("cancel")); - - $form->setTitle($lng->txt("cont_insert_file_item")); - - $form->setFormAction($ilCtrl->getFormAction($this)); - - return $form; - } - - - /** - * Insert file from repository - */ - function insertFromRepository($a_cmd) - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - - $this->setTabs($a_cmd); - $ilTabs->setSubTabActive("cont_file_from_repository"); - $ilCtrl->setParameter($this, "subCmd", "insertFromRepository"); - - include_once("./Services/COPage/classes/class.ilPCFileItemFileSelectorGUI.php"); - $exp = new ilPCFileItemFileSelectorGUI($this, $a_cmd, - $this, $a_cmd, "file_ref_id"); - if (!$exp->handleCommand()) - { - $tpl->setContent($exp->getHTML()); - } - } - - /** - * Insert file from personal workspace - */ - function insertFromWorkspace($a_cmd = "insert") - { - $ilTabs = $this->tabs; - $tree = $this->tree; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $ilUser = $this->user; - - $this->setTabs($a_cmd); - $ilTabs->setSubTabActive("cont_file_from_workspace"); - - include_once("./Services/PersonalWorkspace/classes/class.ilWorkspaceExplorerGUI.php"); - $exp = new ilWorkspaceExplorerGUI($this->user->getId(), $this, $a_cmd, $this, $a_cmd, "fl_wsp_id"); - $ilCtrl->setParameter($this, "subCmd", "selectFile"); - $exp->setCustomLinkTarget($ilCtrl->getLinkTarget($this, $a_cmd)); - $ilCtrl->setParameter($this, "subCmd", "insertFromWorkspace"); - $exp->setTypeWhiteList(array("wsrt", "wfld", "file")); - $exp->setSelectableTypes(array("file")); - if ($exp->handleCommand()) - { - return; - } - $tpl->setContent($exp->getHTML()); - } - - /** - * insert new file item after another item - */ - function insertNewItemAfter($a_file_ref_id = 0) - { - $ilUser = $this->user; - - $res = true; - if(isset($_GET["fl_wsp_id"])) - { - // we need the object id for the instance - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - $tree = new ilWorkspaceTree($ilUser->getId()); - $node = $tree->getNodeData($_GET["fl_wsp_id"]); - - include_once("./Modules/File/classes/class.ilObjFile.php"); - $this->file_object = new ilObjFile($node["obj_id"], false); - } - else if ($a_file_ref_id == 0) - { - $res = $this->newFileItem(); - } - else - { - include_once("./Modules/File/classes/class.ilObjFile.php"); - $this->file_object = new ilObjFile($a_file_ref_id); - } - if ($res) - { - $this->content_obj->newItemAfter($this->file_object->getId(), - $this->file_object->getTitle(), $this->file_object->getFileType()); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - } - - $_GET["subCmd"] = "-"; - $this->newItemAfter(); - } - - /** - * insert new list item before current one - */ - function newItemBefore() - { - $ilTabs = $this->tabs; - - if ($_GET["subCmd"] == "insertNew") - { - $_SESSION["cont_file_insert"] = "insertNew"; - } - if ($_GET["subCmd"] == "insertFromRepository") - { - $_SESSION["cont_file_insert"] = "insertFromRepository"; - } - if ($_GET["subCmd"] == "insertFromWorkspace") - { - $_SESSION["cont_file_insert"] = "insertFromWorkspace"; - } - if (($_GET["subCmd"] == "") && $_SESSION["cont_file_insert"] != "") - { - $_GET["subCmd"] = $_SESSION["cont_file_insert"]; - } - - switch ($_GET["subCmd"]) - { - case "insertFromWorkspace": - $this->insertFromWorkspace("newItemBefore"); - break; - - case "insertFromRepository": - $this->insertFromRepository("newItemBefore"); - break; - - case "selectFile": - $this->insertNewItemBefore($_GET["file_ref_id"]); - break; - - default: - $this->setTabs("newItemBefore"); - $ilTabs->setSubTabActive("cont_new_file"); - - $this->displayValidationError(); - $form = $this->initAddFileForm(true); - $this->tpl->setContent($form->getHTML()); + // new file list form + $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.file_item_edit.html", "Services/COPage"); + $this->tpl->setVariable("TXT_ACTION", $this->lng->txt("cont_insert_file_item")); + $this->tpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this)); + + $this->displayValidationError(); + + // file + $this->tpl->setVariable("TXT_FILE", $this->lng->txt("file")); + + $this->tpl->parseCurrentBlock(); + + // operations + $this->tpl->setCurrentBlock("commands"); + $this->tpl->setVariable("BTN_NAME", "insertNewItemAfter"); + $this->tpl->setVariable("BTN_TEXT", $this->lng->txt("save")); + $this->tpl->parseCurrentBlock(); + break; + } + } + + /** + * Init add file form + */ + public function initAddFileForm($a_before = true) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + + // file + $fi = new ilFileInputGUI($lng->txt("file"), "file"); + $fi->setRequired(true); + $form->addItem($fi); + + if ($a_before) { + $form->addCommandButton("insertNewItemBefore", $lng->txt("save")); + } else { + $form->addCommandButton("insertNewItemAfter", $lng->txt("save")); + } + $form->addCommandButton("cancelAddFile", $lng->txt("cancel")); + + $form->setTitle($lng->txt("cont_insert_file_item")); + + $form->setFormAction($ilCtrl->getFormAction($this)); + + return $form; + } + + + /** + * Insert file from repository + */ + public function insertFromRepository($a_cmd) + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + + $this->setTabs($a_cmd); + $ilTabs->setSubTabActive("cont_file_from_repository"); + $ilCtrl->setParameter($this, "subCmd", "insertFromRepository"); + + include_once("./Services/COPage/classes/class.ilPCFileItemFileSelectorGUI.php"); + $exp = new ilPCFileItemFileSelectorGUI( + $this, + $a_cmd, + $this, + $a_cmd, + "file_ref_id" + ); + if (!$exp->handleCommand()) { + $tpl->setContent($exp->getHTML()); + } + } + + /** + * Insert file from personal workspace + */ + public function insertFromWorkspace($a_cmd = "insert") + { + $ilTabs = $this->tabs; + $tree = $this->tree; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $ilUser = $this->user; + + $this->setTabs($a_cmd); + $ilTabs->setSubTabActive("cont_file_from_workspace"); + + include_once("./Services/PersonalWorkspace/classes/class.ilWorkspaceExplorerGUI.php"); + $exp = new ilWorkspaceExplorerGUI($this->user->getId(), $this, $a_cmd, $this, $a_cmd, "fl_wsp_id"); + $ilCtrl->setParameter($this, "subCmd", "selectFile"); + $exp->setCustomLinkTarget($ilCtrl->getLinkTarget($this, $a_cmd)); + $ilCtrl->setParameter($this, "subCmd", "insertFromWorkspace"); + $exp->setTypeWhiteList(array("wsrt", "wfld", "file")); + $exp->setSelectableTypes(array("file")); + if ($exp->handleCommand()) { + return; + } + $tpl->setContent($exp->getHTML()); + } + + /** + * insert new file item after another item + */ + public function insertNewItemAfter($a_file_ref_id = 0) + { + $ilUser = $this->user; + + $res = true; + if (isset($_GET["fl_wsp_id"])) { + // we need the object id for the instance + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + $tree = new ilWorkspaceTree($ilUser->getId()); + $node = $tree->getNodeData($_GET["fl_wsp_id"]); + + include_once("./Modules/File/classes/class.ilObjFile.php"); + $this->file_object = new ilObjFile($node["obj_id"], false); + } elseif ($a_file_ref_id == 0) { + $res = $this->newFileItem(); + } else { + include_once("./Modules/File/classes/class.ilObjFile.php"); + $this->file_object = new ilObjFile($a_file_ref_id); + } + if ($res) { + $this->content_obj->newItemAfter( + $this->file_object->getId(), + $this->file_object->getTitle(), + $this->file_object->getFileType() + ); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + } + + $_GET["subCmd"] = "-"; + $this->newItemAfter(); + } + + /** + * insert new list item before current one + */ + public function newItemBefore() + { + $ilTabs = $this->tabs; + + if ($_GET["subCmd"] == "insertNew") { + $_SESSION["cont_file_insert"] = "insertNew"; + } + if ($_GET["subCmd"] == "insertFromRepository") { + $_SESSION["cont_file_insert"] = "insertFromRepository"; + } + if ($_GET["subCmd"] == "insertFromWorkspace") { + $_SESSION["cont_file_insert"] = "insertFromWorkspace"; + } + if (($_GET["subCmd"] == "") && $_SESSION["cont_file_insert"] != "") { + $_GET["subCmd"] = $_SESSION["cont_file_insert"]; + } + + switch ($_GET["subCmd"]) { + case "insertFromWorkspace": + $this->insertFromWorkspace("newItemBefore"); + break; + + case "insertFromRepository": + $this->insertFromRepository("newItemBefore"); + break; + + case "selectFile": + $this->insertNewItemBefore($_GET["file_ref_id"]); + break; + + default: + $this->setTabs("newItemBefore"); + $ilTabs->setSubTabActive("cont_new_file"); + + $this->displayValidationError(); + $form = $this->initAddFileForm(true); + $this->tpl->setContent($form->getHTML()); break; - - // new file list form - $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.file_item_edit.html", "Services/COPage"); - $this->tpl->setVariable("TXT_ACTION", $this->lng->txt("cont_insert_file_item")); - $this->tpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this)); - - $this->displayValidationError(); - - // file - $this->tpl->setVariable("TXT_FILE", $this->lng->txt("file")); - - $this->tpl->parseCurrentBlock(); - - // operations - $this->tpl->setCurrentBlock("commands"); - $this->tpl->setVariable("BTN_NAME", "insertNewItemBefore"); - $this->tpl->setVariable("BTN_TEXT", $this->lng->txt("save")); - $this->tpl->parseCurrentBlock(); - break; - } - - } - - /** - * insert new list item before current one - */ - function insertNewItemBefore($a_file_ref_id = 0) - { - $ilUser = $this->user; - - $res = true; - if(isset($_GET["fl_wsp_id"])) - { - // we need the object id for the instance - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - $tree = new ilWorkspaceTree($ilUser->getId()); - $node = $tree->getNodeData($_GET["fl_wsp_id"]); - - include_once("./Modules/File/classes/class.ilObjFile.php"); - $this->file_object = new ilObjFile($node["obj_id"], false); - } - else if ($a_file_ref_id == 0) - { - $res = $this->newFileItem(); - } - else - { - include_once("./Modules/File/classes/class.ilObjFile.php"); - $this->file_object = new ilObjFile($a_file_ref_id); - } - if ($res) - { - $this->content_obj->newItemBefore($this->file_object->getId(), - $this->file_object->getTitle(), $this->file_object->getFileType()); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - } - - $_GET["subCmd"] = "-"; - $this->newItemBefore(); - } - - /** - * delete a list item - */ - function deleteItem() - { - $this->content_obj->deleteItem(); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * output tabs - */ - function setTabs($a_cmd = "") - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $ilSetting = $this->settings; - - $ilTabs->addTarget("cont_back", - $this->ctrl->getParentReturn($this), "", - ""); - - if ($a_cmd != "") - { - $ilCtrl->setParameter($this, "subCmd", "insertNew"); - $ilTabs->addSubTabTarget("cont_new_file", - $ilCtrl->getLinkTarget($this, $a_cmd), $a_cmd); - - $ilCtrl->setParameter($this, "subCmd", "insertFromRepository"); - $ilTabs->addSubTabTarget("cont_file_from_repository", - $ilCtrl->getLinkTarget($this, $a_cmd), $a_cmd); - $ilCtrl->setParameter($this, "subCmd", ""); - - if(!$ilSetting->get("disable_personal_workspace") && - !$ilSetting->get("disable_wsp_files")) - { - $ilCtrl->setParameter($this, "subCmd", "insertFromWorkspace"); - $ilTabs->addSubTabTarget("cont_file_from_workspace", - $ilCtrl->getLinkTarget($this, $a_cmd), $a_cmd); - $ilCtrl->setParameter($this, "subCmd", ""); - } - } - } - - /** - * move list item down - */ - function moveItemDown() - { - $this->content_obj->moveItemDown(); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * move list item up - */ - function moveItemUp() - { - $this->content_obj->moveItemUp(); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * Cancel adding a file - */ - function cancelAddFile() - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } + + // new file list form + $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.file_item_edit.html", "Services/COPage"); + $this->tpl->setVariable("TXT_ACTION", $this->lng->txt("cont_insert_file_item")); + $this->tpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this)); + + $this->displayValidationError(); + + // file + $this->tpl->setVariable("TXT_FILE", $this->lng->txt("file")); + + $this->tpl->parseCurrentBlock(); + + // operations + $this->tpl->setCurrentBlock("commands"); + $this->tpl->setVariable("BTN_NAME", "insertNewItemBefore"); + $this->tpl->setVariable("BTN_TEXT", $this->lng->txt("save")); + $this->tpl->parseCurrentBlock(); + break; + } + } + + /** + * insert new list item before current one + */ + public function insertNewItemBefore($a_file_ref_id = 0) + { + $ilUser = $this->user; + + $res = true; + if (isset($_GET["fl_wsp_id"])) { + // we need the object id for the instance + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + $tree = new ilWorkspaceTree($ilUser->getId()); + $node = $tree->getNodeData($_GET["fl_wsp_id"]); + + include_once("./Modules/File/classes/class.ilObjFile.php"); + $this->file_object = new ilObjFile($node["obj_id"], false); + } elseif ($a_file_ref_id == 0) { + $res = $this->newFileItem(); + } else { + include_once("./Modules/File/classes/class.ilObjFile.php"); + $this->file_object = new ilObjFile($a_file_ref_id); + } + if ($res) { + $this->content_obj->newItemBefore( + $this->file_object->getId(), + $this->file_object->getTitle(), + $this->file_object->getFileType() + ); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + } + + $_GET["subCmd"] = "-"; + $this->newItemBefore(); + } + + /** + * delete a list item + */ + public function deleteItem() + { + $this->content_obj->deleteItem(); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * output tabs + */ + public function setTabs($a_cmd = "") + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $ilSetting = $this->settings; + + $ilTabs->addTarget( + "cont_back", + $this->ctrl->getParentReturn($this), + "", + "" + ); + + if ($a_cmd != "") { + $ilCtrl->setParameter($this, "subCmd", "insertNew"); + $ilTabs->addSubTabTarget( + "cont_new_file", + $ilCtrl->getLinkTarget($this, $a_cmd), + $a_cmd + ); + + $ilCtrl->setParameter($this, "subCmd", "insertFromRepository"); + $ilTabs->addSubTabTarget( + "cont_file_from_repository", + $ilCtrl->getLinkTarget($this, $a_cmd), + $a_cmd + ); + $ilCtrl->setParameter($this, "subCmd", ""); + + if (!$ilSetting->get("disable_personal_workspace") && + !$ilSetting->get("disable_wsp_files")) { + $ilCtrl->setParameter($this, "subCmd", "insertFromWorkspace"); + $ilTabs->addSubTabTarget( + "cont_file_from_workspace", + $ilCtrl->getLinkTarget($this, $a_cmd), + $a_cmd + ); + $ilCtrl->setParameter($this, "subCmd", ""); + } + } + } + + /** + * move list item down + */ + public function moveItemDown() + { + $this->content_obj->moveItemDown(); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * move list item up + */ + public function moveItemUp() + { + $this->content_obj->moveItemUp(); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * Cancel adding a file + */ + public function cancelAddFile() + { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } } -?> diff --git a/Services/COPage/classes/class.ilPCFileList.php b/Services/COPage/classes/class.ilPCFileList.php index 900dbab8c11152ea18876cfa673016d4e5c16a3b..c7fad5c74b908c95b6ea5eb09850221287e9911a 100755 --- a/Services/COPage/classes/class.ilPCFileList.php +++ b/Services/COPage/classes/class.ilPCFileList.php @@ -17,362 +17,348 @@ require_once("./Services/COPage/classes/class.ilPageContent.php"); */ class ilPCFileList extends ilPageContent { - var $list_node; + public $list_node; - /** - * Init page content component. - */ - function init() - { - $this->setType("flst"); - } + /** + * Init page content component. + */ + public function init() + { + $this->setType("flst"); + } - function setNode($a_node) - { - parent::setNode($a_node); // this is the PageContent node - $this->list_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->list_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->list_node = $this->dom->create_element("FileList"); - $this->list_node = $this->node->append_child($this->list_node); - } + public 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->list_node = $this->dom->create_element("FileList"); + $this->list_node = $this->node->append_child($this->list_node); + } - /* - function addItems($a_nr) - { - for ($i=1; $i<=$a_nr; $i++) - { - $new_item = $this->dom->create_element("ListItem"); - $new_item = $this->list_node->append_child($new_item); - } - }*/ + /* + function addItems($a_nr) + { + for ($i=1; $i<=$a_nr; $i++) + { + $new_item = $this->dom->create_element("ListItem"); + $new_item = $this->list_node->append_child($new_item); + } + }*/ - function appendItem($a_id, $a_location, $a_format) - { - // File Item - $new_item = $this->dom->create_element("FileItem"); - $new_item = $this->list_node->append_child($new_item); + public function appendItem($a_id, $a_location, $a_format) + { + // File Item + $new_item = $this->dom->create_element("FileItem"); + $new_item = $this->list_node->append_child($new_item); - // Identifier - $id_node = $this->dom->create_element("Identifier"); - $id_node = $new_item->append_child($id_node); - $id_node->set_attribute("Catalog", "ILIAS"); - $id_node->set_attribute("Entry", "il__file_".$a_id); + // Identifier + $id_node = $this->dom->create_element("Identifier"); + $id_node = $new_item->append_child($id_node); + $id_node->set_attribute("Catalog", "ILIAS"); + $id_node->set_attribute("Entry", "il__file_" . $a_id); - // Location - $loc_node = $this->dom->create_element("Location"); - $loc_node = $new_item->append_child($loc_node); - $loc_node->set_attribute("Type", "LocalFile"); - $loc_node->set_content($a_location); + // Location + $loc_node = $this->dom->create_element("Location"); + $loc_node = $new_item->append_child($loc_node); + $loc_node->set_attribute("Type", "LocalFile"); + $loc_node->set_content($a_location); - // Format - $form_node = $this->dom->create_element("Format"); - $form_node = $new_item->append_child($form_node); - $form_node->set_content($a_format); - } + // Format + $form_node = $this->dom->create_element("Format"); + $form_node = $new_item->append_child($form_node); + $form_node->set_content($a_format); + } - function setListTitle($a_title, $a_language) - { - ilDOMUtil::setFirstOptionalElement($this->dom, - $this->list_node, "Title", array("FileItem"), - $a_title, array("Language" => $a_language)); - } + public function setListTitle($a_title, $a_language) + { + ilDOMUtil::setFirstOptionalElement( + $this->dom, + $this->list_node, + "Title", + array("FileItem"), + $a_title, + array("Language" => $a_language) + ); + } - function getListTitle() - { - $chlds = $this->list_node->child_nodes(); - for($i=0; $inode_name() == "Title") - { - return $chlds[$i]->get_content(); - } - } - return ""; - } + public function getListTitle() + { + $chlds = $this->list_node->child_nodes(); + for ($i=0; $inode_name() == "Title") { + return $chlds[$i]->get_content(); + } + } + return ""; + } - function getLanguage() - { - $chlds = $this->list_node->child_nodes(); - for($i=0; $inode_name() == "Title") - { - return $chlds[$i]->get_attribute("Language"); - } - } - return ""; - } - - /** - * Get list of files - */ - function getFileList() - { - $files = array(); - - // File Item - $childs = $this->list_node->child_nodes(); - for ($i=0; $inode_name() == "FileItem") - { - $id = $entry = ""; - $pc_id = $childs[$i]->get_attribute("PCID"); - $hier_id = $childs[$i]->get_attribute("HierId"); - $class = $childs[$i]->get_attribute("Class"); - - // Identifier - $id_node = $childs[$i]->first_child(); - if ($id_node->node_name() == "Identifier") - { - $entry = $id_node->get_attribute("Entry"); - if (substr($entry, 0, 9) == "il__file_") - { - $id = substr($entry, 9); - } - } - $files[] = array("entry" => $entry, "id" => $id, - "pc_id" => $pc_id, "hier_id" => $hier_id, - "class" => $class); - } - } - - return $files; - } + public function getLanguage() + { + $chlds = $this->list_node->child_nodes(); + for ($i=0; $inode_name() == "Title") { + return $chlds[$i]->get_attribute("Language"); + } + } + return ""; + } + + /** + * Get list of files + */ + public function getFileList() + { + $files = array(); + + // File Item + $childs = $this->list_node->child_nodes(); + for ($i=0; $inode_name() == "FileItem") { + $id = $entry = ""; + $pc_id = $childs[$i]->get_attribute("PCID"); + $hier_id = $childs[$i]->get_attribute("HierId"); + $class = $childs[$i]->get_attribute("Class"); + + // Identifier + $id_node = $childs[$i]->first_child(); + if ($id_node->node_name() == "Identifier") { + $entry = $id_node->get_attribute("Entry"); + if (substr($entry, 0, 9) == "il__file_") { + $id = substr($entry, 9); + } + } + $files[] = array("entry" => $entry, "id" => $id, + "pc_id" => $pc_id, "hier_id" => $hier_id, + "class" => $class); + } + } + + return $files; + } - /** - * Delete file items - */ - function deleteFileItems($a_ids) - { - $files = array(); - - // File Item - $childs = $this->list_node->child_nodes(); + /** + * Delete file items + */ + public function deleteFileItems($a_ids) + { + $files = array(); + + // File Item + $childs = $this->list_node->child_nodes(); - for ($i=0; $inode_name() == "FileItem") - { - $id = $entry = ""; - $pc_id = $childs[$i]->get_attribute("PCID"); - $hier_id = $childs[$i]->get_attribute("HierId"); - - if (in_array($hier_id.":".$pc_id, $a_ids)) - { - $childs[$i]->unlink($childs[$i]); - } - } - } - } + for ($i=0; $inode_name() == "FileItem") { + $id = $entry = ""; + $pc_id = $childs[$i]->get_attribute("PCID"); + $hier_id = $childs[$i]->get_attribute("HierId"); + + if (in_array($hier_id . ":" . $pc_id, $a_ids)) { + $childs[$i]->unlink($childs[$i]); + } + } + } + } - /** - * Save positions of file items - */ - function savePositions($a_pos) - { - asort($a_pos); - - // File Item - $childs = $this->list_node->child_nodes(); - $nodes = array(); - for ($i=0; $inode_name() == "FileItem") - { - $id = $entry = ""; - $pc_id = $childs[$i]->get_attribute("PCID"); - $hier_id = $childs[$i]->get_attribute("HierId"); - $nodes[$hier_id.":".$pc_id] = $childs[$i]; - $childs[$i]->unlink($childs[$i]); - } - } - - foreach($a_pos as $k => $v) - { - if (is_object($nodes[$k])) - { - $nodes[$k] = $this->list_node->append_child($nodes[$k]); - } - } - } + /** + * Save positions of file items + */ + public function savePositions($a_pos) + { + asort($a_pos); + + // File Item + $childs = $this->list_node->child_nodes(); + $nodes = array(); + for ($i=0; $inode_name() == "FileItem") { + $id = $entry = ""; + $pc_id = $childs[$i]->get_attribute("PCID"); + $hier_id = $childs[$i]->get_attribute("HierId"); + $nodes[$hier_id . ":" . $pc_id] = $childs[$i]; + $childs[$i]->unlink($childs[$i]); + } + } + + foreach ($a_pos as $k => $v) { + if (is_object($nodes[$k])) { + $nodes[$k] = $this->list_node->append_child($nodes[$k]); + } + } + } - /** - * Get all style classes - */ - function getAllClasses() - { - $classes = array(); - - // File Item - $childs = $this->list_node->child_nodes(); + /** + * Get all style classes + */ + public function getAllClasses() + { + $classes = array(); + + // File Item + $childs = $this->list_node->child_nodes(); - for ($i=0; $inode_name() == "FileItem") - { - $classes[$childs[$i]->get_attribute("HierId").":". - $childs[$i]->get_attribute("PCID")] = $childs[$i]->get_attribute("Class"); - } - } - - return $classes; - } + for ($i=0; $inode_name() == "FileItem") { + $classes[$childs[$i]->get_attribute("HierId") . ":" . + $childs[$i]->get_attribute("PCID")] = $childs[$i]->get_attribute("Class"); + } + } + + return $classes; + } - /** - * Save style classes of file items - */ - function saveStyleClasses($a_class) - { - // File Item - $childs = $this->list_node->child_nodes(); - for ($i=0; $inode_name() == "FileItem") - { - $childs[$i]->set_attribute("Class", - $a_class[$childs[$i]->get_attribute("HierId").":". - $childs[$i]->get_attribute("PCID")]); - } - } - } + /** + * Save style classes of file items + */ + public function saveStyleClasses($a_class) + { + // File Item + $childs = $this->list_node->child_nodes(); + for ($i=0; $inode_name() == "FileItem") { + $childs[$i]->set_attribute( + "Class", + $a_class[$childs[$i]->get_attribute("HierId") . ":" . + $childs[$i]->get_attribute("PCID")] + ); + } + } + } - /** - * Get lang vars needed for editing - * @return array array of lang var keys - */ - static function getLangVars() - { - return array("ed_edit_files", "ed_insert_filelist", "pc_flist"); - } + /** + * Get lang vars needed for editing + * @return array array of lang var keys + */ + public static function getLangVars() + { + return array("ed_edit_files", "ed_insert_filelist", "pc_flist"); + } - /** - * After page has been updated (or created) - * - * @param object $a_page page object - * @param DOMDocument $a_domdoc dom document - * @param string $a_xml xml - * @param bool $a_creation true on creation, otherwise false - */ - static function afterPageUpdate($a_page, DOMDocument $a_domdoc, $a_xml, $a_creation) - { - if (!$a_page->getImportMode()) - { - // pc filelist - include_once("./Modules/File/classes/class.ilObjFile.php"); - $file_ids = ilObjFile::_getFilesOfObject( - $a_page->getParentType().":pg", $a_page->getId(), 0, $a_page->getLanguage()); - self::saveFileUsage($a_page, $a_domdoc); + /** + * After page has been updated (or created) + * + * @param object $a_page page object + * @param DOMDocument $a_domdoc dom document + * @param string $a_xml xml + * @param bool $a_creation true on creation, otherwise false + */ + public static function afterPageUpdate($a_page, DOMDocument $a_domdoc, $a_xml, $a_creation) + { + if (!$a_page->getImportMode()) { + // pc filelist + include_once("./Modules/File/classes/class.ilObjFile.php"); + $file_ids = ilObjFile::_getFilesOfObject( + $a_page->getParentType() . ":pg", + $a_page->getId(), + 0, + $a_page->getLanguage() + ); + self::saveFileUsage($a_page, $a_domdoc); - foreach($file_ids as $file) // check, whether file object can be deleted - { - if (ilObject::_exists($file) && ilObject::_lookupType($file) == "file") - { - $file_obj = new ilObjFile($file, false); - $usages = $file_obj->getUsages(); - if (count($usages) == 0) // delete, if no usage exists - { - if ($file_obj->getMode() == "filelist") // non-repository object - { - $file_obj->delete(); - } - } - } - } - } + foreach ($file_ids as $file) { // check, whether file object can be deleted + if (ilObject::_exists($file) && ilObject::_lookupType($file) == "file") { + $file_obj = new ilObjFile($file, false); + $usages = $file_obj->getUsages(); + if (count($usages) == 0) { // delete, if no usage exists + if ($file_obj->getMode() == "filelist") { // non-repository object + $file_obj->delete(); + } + } + } + } + } + } + + /** + * Before page is being deleted + * + * @param object $a_page page object + */ + public static function beforePageDelete($a_page) + { + $files = self::collectFileItems($a_page, $a_page->getDomDoc()); + + // delete all file usages + include_once("./Modules/File/classes/class.ilObjFile.php"); + ilObjFile::_deleteAllUsages( + $a_page->getParentType() . ":pg", + $a_page->getId(), + false, + $a_page->getLanguage() + ); - } - - /** - * Before page is being deleted - * - * @param object $a_page page object - */ - static function beforePageDelete($a_page) - { - $files = self::collectFileItems($a_page, $a_page->getDomDoc()); - - // delete all file usages - include_once("./Modules/File/classes/class.ilObjFile.php"); - ilObjFile::_deleteAllUsages($a_page->getParentType().":pg", $a_page->getId(), false, - $a_page->getLanguage()); + include_once("./Modules/File/classes/class.ilObjFile.php"); + foreach ($files as $file_id) { + if (ilObject::_exists($file_id)) { + $file_obj = new ilObjFile($file_id, false); + $file_obj->delete(); + } + } + } - include_once("./Modules/File/classes/class.ilObjFile.php"); - foreach ($files as $file_id) - { - if (ilObject::_exists($file_id)) - { - $file_obj = new ilObjFile($file_id, false); - $file_obj->delete(); - } - } - } + /** + * After page history entry has been created + * + * @param object $a_page page object + * @param DOMDocument $a_old_domdoc old dom document + * @param string $a_old_xml old xml + * @param integer $a_old_nr history number + */ + public static function afterPageHistoryEntry($a_page, DOMDocument $a_old_domdoc, $a_old_xml, $a_old_nr) + { + self::saveFileUsage($a_page, $a_old_domdoc, $a_old_nr); + } - /** - * After page history entry has been created - * - * @param object $a_page page object - * @param DOMDocument $a_old_domdoc old dom document - * @param string $a_old_xml old xml - * @param integer $a_old_nr history number - */ - static function afterPageHistoryEntry($a_page, DOMDocument $a_old_domdoc, $a_old_xml, $a_old_nr) - { - self::saveFileUsage($a_page, $a_old_domdoc, $a_old_nr); - } - - /** - * Save file usages - */ - static function saveFileUsage($a_page, $a_domdoc, $a_old_nr = 0) - { - $file_ids = self::collectFileItems($a_page, $a_domdoc); - include_once("./Modules/File/classes/class.ilObjFile.php"); - ilObjFile::_deleteAllUsages($a_page->getParentType().":pg", $a_page->getId(), $a_old_nr, $a_page->getLanguage()); - foreach($file_ids as $file_id) - { - ilObjFile::_saveUsage($file_id, $a_page->getParentType().":pg", $a_page->getId(), $a_old_nr, - $a_page->getLanguage()); - } - } - - /** - * Get all file items that are used within the page - */ - static function collectFileItems($a_page, $a_domdoc) - { - $xpath = new DOMXPath($a_domdoc); - $nodes = $xpath->query('//FileItem/Identifier'); - $file_ids = array(); - foreach($nodes as $node) - { - $id_arr = explode("_", $node->getAttribute("Entry")); - $file_id = $id_arr[count($id_arr) - 1]; - if ($file_id > 0 && ($id_arr[1] == "" || $id_arr[1] == IL_INST_ID || $id_arr[1] == 0)) - { - $file_ids[$file_id] = $file_id; - } - } - // file items in download links - $xpath = new DOMXPath($a_domdoc); - $nodes = $xpath->query("//IntLink[@Type='File']"); - foreach($nodes as $node) - { - $t = $node->getAttribute("Target"); - if (substr($t, 0, 9) == "il__dfile") - { - $id_arr = explode("_", $t); - $file_id = $id_arr[count($id_arr) - 1]; - $file_ids[$file_id] = $file_id; - } - } - return $file_ids; - } + /** + * Save file usages + */ + public static function saveFileUsage($a_page, $a_domdoc, $a_old_nr = 0) + { + $file_ids = self::collectFileItems($a_page, $a_domdoc); + include_once("./Modules/File/classes/class.ilObjFile.php"); + ilObjFile::_deleteAllUsages($a_page->getParentType() . ":pg", $a_page->getId(), $a_old_nr, $a_page->getLanguage()); + foreach ($file_ids as $file_id) { + ilObjFile::_saveUsage( + $file_id, + $a_page->getParentType() . ":pg", + $a_page->getId(), + $a_old_nr, + $a_page->getLanguage() + ); + } + } + /** + * Get all file items that are used within the page + */ + public static function collectFileItems($a_page, $a_domdoc) + { + $xpath = new DOMXPath($a_domdoc); + $nodes = $xpath->query('//FileItem/Identifier'); + $file_ids = array(); + foreach ($nodes as $node) { + $id_arr = explode("_", $node->getAttribute("Entry")); + $file_id = $id_arr[count($id_arr) - 1]; + if ($file_id > 0 && ($id_arr[1] == "" || $id_arr[1] == IL_INST_ID || $id_arr[1] == 0)) { + $file_ids[$file_id] = $file_id; + } + } + // file items in download links + $xpath = new DOMXPath($a_domdoc); + $nodes = $xpath->query("//IntLink[@Type='File']"); + foreach ($nodes as $node) { + $t = $node->getAttribute("Target"); + if (substr($t, 0, 9) == "il__dfile") { + $id_arr = explode("_", $t); + $file_id = $id_arr[count($id_arr) - 1]; + $file_ids[$file_id] = $file_id; + } + } + return $file_ids; + } } -?> diff --git a/Services/COPage/classes/class.ilPCFileListGUI.php b/Services/COPage/classes/class.ilPCFileListGUI.php index 1b8a47ea4492ea9fc9a93846dc75ccf11a4797c7..7f427e16a25f5554ff09ea862263318c93ee42b4 100755 --- a/Services/COPage/classes/class.ilPCFileListGUI.php +++ b/Services/COPage/classes/class.ilPCFileListGUI.php @@ -16,790 +16,769 @@ require_once("./Services/COPage/classes/class.ilPageContentGUI.php"); */ class ilPCFileListGUI extends ilPageContentGUI { - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilTree - */ - protected $tree; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilSetting - */ - protected $settings; - - - /** - * Constructor - * @access public - */ - function __construct(&$a_pg_obj, &$a_content_obj, $a_hier_id, $a_pc_id = "") - { - global $DIC; - - $this->user = $DIC->user(); - $this->tabs = $DIC->tabs(); - $this->ctrl = $DIC->ctrl(); - $this->tpl = $DIC["tpl"]; - $this->tree = $DIC->repositoryTree(); - $this->lng = $DIC->language(); - $this->toolbar = $DIC->toolbar(); - $this->settings = $DIC->settings(); - parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); - $this->setCharacteristics(array("FileListItem" => $this->lng->txt("cont_FileListItem"))); - } - - /** - * execute command - */ - function executeCommand() - { - // get next class that processes or forwards current command - $next_class = $this->ctrl->getNextClass($this); - - $this->getCharacteristicsOfCurrentStyle("flist_li"); // scorm-2004 - - // get current command - $cmd = $this->ctrl->getCmd(); - - switch($next_class) - { - default: - $ret = $this->$cmd(); - break; - } - - return $ret; - } - - /** - * insert new file list form - */ - function insert($a_form = null) - { - $ilUser = $this->user; - $ilTabs = $this->tabs; - - if ($_GET["subCmd"] == "insertNew") - { - $_SESSION["cont_file_insert"] = "insertNew"; - } - if ($_GET["subCmd"] == "insertFromRepository") - { - $_SESSION["cont_file_insert"] = "insertFromRepository"; - } - if ($_GET["subCmd"] == "insertFromWorkspace") - { - $_SESSION["cont_file_insert"] = "insertFromWorkspace"; - } - if (($_GET["subCmd"] == "") && $_SESSION["cont_file_insert"] != "") - { - $_GET["subCmd"] = $_SESSION["cont_file_insert"]; - } - - switch ($_GET["subCmd"]) - { - case "insertFromWorkspace": - $this->insertFromWorkspace(); - break; - - case "insertFromRepository": - $this->insertFromRepository(); - break; - - case "selectFile": - $this->selectFile(); - break; - - default: - $this->setTabs(); - $ilTabs->setSubTabActive("cont_new_file"); - - $this->displayValidationError(); - - if ($a_form != null) - { - $form = $a_form; - } - else - { - $form = $this->initEditForm("create"); - } - $this->tpl->setContent($form->getHTML()); - break; - } - - } - - /** - * Select file - */ - function selectFile() - { - $ilTabs = $this->tabs; - $ilUser = $this->user; - - $this->setTabs(); - $ilTabs->setSubTabActive("cont_file_from_repository"); - - $this->displayValidationError(); - $form = $this->initEditForm("select_file"); - - $this->tpl->setContent($form->getHTML()); - } - - /** - * Insert file from repository - */ - function insertFromRepository($a_cmd = "insert") - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - - if ($a_cmd == "insert") - { - $this->setTabs(); - } - else - { - $this->setItemTabs($a_cmd); - } - - $ilTabs->setSubTabActive("cont_file_from_repository"); - $ilCtrl->setParameter($this, "subCmd", "insertFromRepository"); - - include_once("./Services/COPage/classes/class.ilPCFileItemFileSelectorGUI.php"); - $exp = new ilPCFileItemFileSelectorGUI($this, $a_cmd, - $this, $a_cmd, "file_ref_id"); - if (!$exp->handleCommand()) - { - $tpl->setContent($exp->getHTML()); - } - } - - /** - * Insert file from personal workspace - */ - function insertFromWorkspace($a_cmd = "insert") - { - $ilTabs = $this->tabs; - $tree = $this->tree; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $ilUser = $this->user; - - if ($a_cmd == "insert") - { - $this->setTabs(); - } - else - { - $this->setItemTabs($a_cmd); - } - - $ilTabs->setSubTabActive("cont_file_from_workspace"); - - include_once("./Services/PersonalWorkspace/classes/class.ilWorkspaceExplorerGUI.php"); - $exp = new ilWorkspaceExplorerGUI($ilUser->getId(), $this, $a_cmd, $this, $a_cmd, "fl_wsp_id"); - $ilCtrl->setParameter($this, "subCmd", "selectFile"); - $exp->setCustomLinkTarget($ilCtrl->getLinkTarget($this, $a_cmd)); - $ilCtrl->setParameter($this, "subCmd", "insertFromWorkspace"); - $exp->setTypeWhiteList(array("wsrt", "wfld", "file")); - $exp->setSelectableTypes(array("file")); - if ($exp->handleCommand()) - { - return; - } - $tpl->setContent($exp->getHTML()); - } - - /** - * create new file list in dom and update page in db - */ - function create() - { - global $DIC; - - include_once("./Modules/File/classes/class.ilObjFile.php"); - - $mode = ($_POST["file_ref_id"] != "") - ? "select_file" - : "create"; - $form = $this->initEditForm($mode); - if (!$form->checkInput()) - { - $form->setValuesByPost(); - $this->insert($form); - return; - } - - // from personal workspace - if(substr($_POST["file_ref_id"], 0, 4) == "wsp_") - { - $fileObj = new ilObjFile(substr($_POST["file_ref_id"], 4), false); - } - // upload - else if ($_POST["file_ref_id"] == 0) - { - $fileObj = new ilObjFile(); - $fileObj->setType("file"); - $fileObj->setTitle($_FILES["file"]["name"]); - $fileObj->setDescription(""); - $fileObj->setFileName($_FILES["file"]["name"]); - $fileObj->setFileType($_FILES["file"]["type"]); - $fileObj->setFileSize($_FILES["file"]["size"]); - $fileObj->setMode("filelist"); - $fileObj->create(); - // upload file to filesystem - $fileObj->createDirectory(); - $fileObj->raiseUploadError(false); - - $upload = $DIC->upload(); - if ($upload->hasBeenProcessed() !== true) { - $upload->process(); - } - - $fileObj->getUploadFile($_FILES["file"]["tmp_name"], - $_FILES["file"]["name"]); - } - // from repository - else - { - $fileObj = new ilObjFile($_POST["file_ref_id"]); - } - $_SESSION["il_text_lang_".$_GET["ref_id"]] = $_POST["flst_language"]; - -//echo "::".is_object($this->dom).":"; - $this->content_obj = new ilPCFileList($this->getPage()); - $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); - $this->content_obj->setListTitle(ilUtil::stripSlashes($_POST["flst_title"]), $_POST["flst_language"]); - $this->content_obj->appendItem($fileObj->getId(), $fileObj->getFileName(), - $fileObj->getFileType()); - - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - else - { - $this->insert(); - } - } - - /** - * edit properties form - */ - function edit() - { - $this->setTabs(false); - - $form = $this->initEditForm(); - $this->tpl->setContent($form->getHTML()); - } - - /** - * Init edit form - * - * @param int $a_mode Edit Mode - */ - public function initEditForm($a_mode = "edit") - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - - if ($a_mode != "add_file") - { - // title - $ti = new ilTextInputGUI($lng->txt("title"), "flst_title"); - $ti->setMaxLength(80); - $ti->setSize(40); - $form->addItem($ti); - - // language - require_once("Services/MetaData/classes/class.ilMDLanguageItem.php"); - $lang = ilMDLanguageItem::_getLanguages(); - $si = new ilSelectInputGUI($lng->txt("language"), "flst_language"); - $si->setOptions($lang); - $form->addItem($si); - } - - if (in_array($a_mode, array("create", "add_file"))) - { - // file - $fi = new ilFileInputGUI($lng->txt("file"), "file"); - $fi->setRequired(true); - $form->addItem($fi); - } - else if (in_array($a_mode, array("select_file"))) - { - // file - $ne = new ilNonEditableValueGUI($lng->txt("file"), ""); - - if(isset($_GET["file_ref_id"])) - { - include_once("./Modules/File/classes/class.ilObjFile.php"); - $file_obj = new ilObjFile((int) $_GET["file_ref_id"]); - if (is_object($file_obj)) - { - // ref id as hidden input - $hi = new ilHiddenInputGUI("file_ref_id"); - $hi->setValue((int) $_GET["file_ref_id"]); - $form->addItem($hi); - - $ne->setValue($file_obj->getTitle()); - } - } - else if(isset($_GET["fl_wsp_id"])) - { - // we need the object id for the instance - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - $tree = new ilWorkspaceTree($ilUser->getId()); - $node = $tree->getNodeData((int) $_GET["fl_wsp_id"]); - - include_once("./Modules/File/classes/class.ilObjFile.php"); - $file_obj = new ilObjFile($node["obj_id"], false); - if (is_object($file_obj)) - { - // ref id as hidden input - $hi = new ilHiddenInputGUI("file_ref_id"); - $hi->setValue("wsp_".(int) $node["obj_id"]); - $form->addItem($hi); - - $ne->setValue($file_obj->getTitle()); - } - $this->tpl->parseCurrentBlock(); - } - - $form->addItem($ne); - } - - - switch ($a_mode) - { - case "edit"; - $ti->setValue($this->content_obj->getListTitle()); - $si->setValue($this->content_obj->getLanguage()); - $form->addCommandButton("saveProperties", $lng->txt("save")); - $form->addCommandButton("cancelUpdate", $lng->txt("cancel")); - $form->setTitle($lng->txt("cont_edit_file_list_properties")); - break; - - case "create": - case "select_file": - if ($_SESSION["il_text_lang_".$_GET["ref_id"]] != "") - { - $s_lang = $_SESSION["il_text_lang_".$_GET["ref_id"]]; - } - else - { - $s_lang = $ilUser->getLanguage(); - } - $si->setValue($s_lang); - $form->addCommandButton("create_flst", $lng->txt("save")); - $form->addCommandButton("cancelCreate", $lng->txt("cancel")); - $form->setTitle($lng->txt("cont_insert_file_list")); - break; - - case "add_file": - $form->addCommandButton("insertNewFileItem", $lng->txt("save")); - $form->addCommandButton("editFiles", $lng->txt("cancel")); - $form->setTitle($lng->txt("cont_insert_file_item")); - break; - } - - $form->setFormAction($ilCtrl->getFormAction($this)); - - return $form; - } - - - /** - * save table properties in db and return to page edit screen - */ - function saveProperties() - { - $this->content_obj->setListTitle(ilUtil::stripSlashes($_POST["flst_title"]), - ilUtil::stripSlashes($_POST["flst_language"])); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - else - { - $this->pg_obj->addHierIDs(); - $this->edit(); - } - } - - /** - * Edit Files - */ - function editFiles() - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->setTabs(false); - - $ilToolbar->addButton($lng->txt("cont_add_file"), - $ilCtrl->getLinkTarget($this, "addFileItem")); - - include_once("./Services/COPage/classes/class.ilPCFileListTableGUI.php"); - $table_gui = new ilPCFileListTableGUI($this, "editFiles", $this->content_obj); - $tpl->setContent($table_gui->getHTML()); - } - - /** - * Set Tabs - */ - function setTabs($a_create = true) - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilSetting = $this->settings; - - if ($a_create) - { - $cmd = "insert"; - - $ilCtrl->setParameter($this, "subCmd", "insertNew"); - $ilTabs->addSubTabTarget("cont_new_file", - $ilCtrl->getLinkTarget($this, $cmd), $cmd); - - $ilCtrl->setParameter($this, "subCmd", "insertFromRepository"); - $ilTabs->addSubTabTarget("cont_file_from_repository", - $ilCtrl->getLinkTarget($this, $cmd), $cmd); - $ilCtrl->setParameter($this, "subCmd", ""); - - if(!$ilSetting->get("disable_personal_workspace") && - !$ilSetting->get("disable_wsp_files")) - { - $ilCtrl->setParameter($this, "subCmd", "insertFromWorkspace"); - $ilTabs->addSubTabTarget("cont_file_from_workspace", - $ilCtrl->getLinkTarget($this, $cmd), $cmd); - $ilCtrl->setParameter($this, "subCmd", ""); - } - } - else - { - $ilTabs->setBackTarget($lng->txt("pg"), - $this->ctrl->getParentReturn($this)); - - $ilTabs->addTarget("cont_ed_edit_files", - $ilCtrl->getLinkTarget($this, "editFiles"), "editFiles", - get_class($this)); - - $ilTabs->addTarget("cont_ed_edit_prop", - $ilCtrl->getLinkTarget($this, "edit"), "edit", - get_class($this)); - - } - } - - /** - * Add file item. This function is called from file list table and calls - * newItemAfter function. - */ - function addFileItem() - { - $ilCtrl = $this->ctrl; - - $files = $this->content_obj->getFileList(); - - if (count($files) >= 1) - { - $ilCtrl->setParameterByClass("ilpcfileitemgui", "hier_id", - $files[count($files) - 1]["hier_id"]); - $ilCtrl->setParameterByClass("ilpcfileitemgui", "pc_id", - $files[count($files) - 1]["pc_id"]); - $ilCtrl->redirectByClass("ilpcfileitemgui", "newItemAfter"); - } - else - { - $ilCtrl->redirect($this, "newFileItem"); - } - } - - /** - * Delete file items from list - */ - function deleteFileItem() - { - $ilCtrl = $this->ctrl; - - if (is_array($_POST["fid"])) - { - $ids = array(); - foreach($_POST["fid"] as $k => $v) - { - $ids[] = $k; - } - $this->content_obj->deleteFileItems($ids); - } - $this->updated = $this->pg_obj->update(); - $ilCtrl->redirect($this, "editFiles"); - } - - /** - * Save positions of file items - */ - function savePositions() - { - $ilCtrl = $this->ctrl; - - if (is_array($_POST["position"])) - { - $this->content_obj->savePositions($_POST["position"]); - } - $this->updated = $this->pg_obj->update(); - $ilCtrl->redirect($this, "editFiles"); - } - - /** - * Save positions of file items and style classes - */ - function savePositionsAndClasses() - { - $ilCtrl = $this->ctrl; - - if (is_array($_POST["position"])) - { - $this->content_obj->savePositions($_POST["position"]); - } - if (is_array($_POST["class"])) - { - $this->content_obj->saveStyleClasses($_POST["class"]); - } - $this->updated = $this->pg_obj->update(); - $ilCtrl->redirect($this, "editFiles"); - } - - /** - * Checks whether style selection shoudl be available or not - */ - function checkStyleSelection() - { - // check whether there is more than one style class - $chars = $this->getCharacteristics(); - - $classes = $this->content_obj->getAllClasses(); - if (count($chars) > 1) - { - return true; - } - foreach ($classes as $class) - { - if ($class != "" && $class != "FileListItem") - { - return true; - } - } - return false; - } - - // - // - // New file item - // - // - - /** - * New file item (called, if there is no file item in an existing) - * - * @param - * @return - */ - function newFileItem() - { - $ilTabs = $this->tabs; - - if ($_GET["subCmd"] == "insertNew") - { - $_SESSION["cont_file_insert"] = "insertNew"; - } - if ($_GET["subCmd"] == "insertFromRepository") - { - $_SESSION["cont_file_insert"] = "insertFromRepository"; - } - if ($_GET["subCmd"] == "insertFromWorkspace") - { - $_SESSION["cont_file_insert"] = "insertFromWorkspace"; - } - if (($_GET["subCmd"] == "") && $_SESSION["cont_file_insert"] != "") - { - $_GET["subCmd"] = $_SESSION["cont_file_insert"]; - } - - switch ($_GET["subCmd"]) - { - case "insertFromWorkspace": - $this->insertFromWorkspace("newFileItem"); - break; - - case "insertFromRepository": - $this->insertFromRepository("newFileItem"); - break; - - case "selectFile": - $this->insertNewFileItem($_GET["file_ref_id"]); - break; - - default: - $this->setItemTabs("newFileItem"); - $ilTabs->setSubTabActive("cont_new_file"); - - $this->displayValidationError(); - - $form = $this->initEditForm("add_file"); - $this->tpl->setContent($form->getHTML()); - break; - } - } - - /** - * insert new file item after another item - */ - function insertNewFileItem($a_file_ref_id = 0) - { - $ilUser = $this->user; - - // from personal workspace - if(isset($_GET["fl_wsp_id"])) - { - // we need the object id for the instance - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - $tree = new ilWorkspaceTree($ilUser->getId()); - $node = $tree->getNodeData($_GET["fl_wsp_id"]); - - include_once("./Modules/File/classes/class.ilObjFile.php"); - $file_obj = new ilObjFile($node["obj_id"], false); - } - // upload - else if ($a_file_ref_id == 0) - { - $file_obj = $this->createFileItem(); - } - // from repository - else - { - include_once("./Modules/File/classes/class.ilObjFile.php"); - $file_obj = new ilObjFile($a_file_ref_id); - } - if (is_object($file_obj)) - { - $this->content_obj->appendItem($file_obj->getId(), - $file_obj->getTitle(), $file_obj->getFileType()); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - //$this->ctrl->returnToParent($this, "jump".$this->hier_id); - $this->ctrl->redirect($this, "editFiles"); - } - } - - $_GET["subCmd"] = "-"; - $this->newFileItem(); - } - - /** - * insert new file item - */ - function createFileItem() - { - global $DIC; - - $lng = $this->lng; - - if ($_FILES["file"]["name"] == "") - { - $_GET["subCmd"] = "-"; - ilUtil::sendFailure($lng->txt("upload_error_file_not_found")); - return false; - } - - $form = $this->initEditForm(); - // see #22541 -// $form->checkInput(); - - include_once("./Modules/File/classes/class.ilObjFile.php"); - $fileObj = new ilObjFile(); - $fileObj->setType("file"); - $fileObj->setTitle($_FILES["file"]["name"]); - $fileObj->setDescription(""); - $fileObj->setVersion(0); - $fileObj->setMaxVersion(0); - $fileObj->setFileName($_FILES["file"]["name"]); - $fileObj->setFileType($_FILES["file"]["type"]); - $fileObj->setFileSize($_FILES["file"]["size"]); - $fileObj->setMode("filelist"); - $fileObj->create(); - $fileObj->createDirectory(); - $fileObj->raiseUploadError(false); - $fileObj->getUploadFile($_FILES["file"]["tmp_name"], $_FILES["file"]["name"]); - // upload file to filesystem - - return $fileObj; - } - - - /** - * output tabs - */ - function setItemTabs($a_cmd = "") - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $ilSetting = $this->settings; - - $ilTabs->addTarget("cont_back", - $this->ctrl->getParentReturn($this), "", - ""); - - if ($a_cmd != "") - { - $ilCtrl->setParameter($this, "subCmd", "insertNew"); - $ilTabs->addSubTabTarget("cont_new_file", - $ilCtrl->getLinkTarget($this, $a_cmd), $a_cmd); - - $ilCtrl->setParameter($this, "subCmd", "insertFromRepository"); - $ilTabs->addSubTabTarget("cont_file_from_repository", - $ilCtrl->getLinkTarget($this, $a_cmd), $a_cmd); - $ilCtrl->setParameter($this, "subCmd", ""); - - if(!$ilSetting->get("disable_personal_workspace") && - !$ilSetting->get("disable_wsp_files")) - { - $ilCtrl->setParameter($this, "subCmd", "insertFromWorkspace"); - $ilTabs->addSubTabTarget("cont_file_from_workspace", - $ilCtrl->getLinkTarget($this, $a_cmd), $a_cmd); - $ilCtrl->setParameter($this, "subCmd", ""); - } - } - } - - + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilTree + */ + protected $tree; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilSetting + */ + protected $settings; + + + /** + * Constructor + * @access public + */ + public function __construct(&$a_pg_obj, &$a_content_obj, $a_hier_id, $a_pc_id = "") + { + global $DIC; + + $this->user = $DIC->user(); + $this->tabs = $DIC->tabs(); + $this->ctrl = $DIC->ctrl(); + $this->tpl = $DIC["tpl"]; + $this->tree = $DIC->repositoryTree(); + $this->lng = $DIC->language(); + $this->toolbar = $DIC->toolbar(); + $this->settings = $DIC->settings(); + parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); + $this->setCharacteristics(array("FileListItem" => $this->lng->txt("cont_FileListItem"))); + } + + /** + * execute command + */ + public function executeCommand() + { + // get next class that processes or forwards current command + $next_class = $this->ctrl->getNextClass($this); + + $this->getCharacteristicsOfCurrentStyle("flist_li"); // scorm-2004 + + // get current command + $cmd = $this->ctrl->getCmd(); + + switch ($next_class) { + default: + $ret = $this->$cmd(); + break; + } + + return $ret; + } + + /** + * insert new file list form + */ + public function insert($a_form = null) + { + $ilUser = $this->user; + $ilTabs = $this->tabs; + + if ($_GET["subCmd"] == "insertNew") { + $_SESSION["cont_file_insert"] = "insertNew"; + } + if ($_GET["subCmd"] == "insertFromRepository") { + $_SESSION["cont_file_insert"] = "insertFromRepository"; + } + if ($_GET["subCmd"] == "insertFromWorkspace") { + $_SESSION["cont_file_insert"] = "insertFromWorkspace"; + } + if (($_GET["subCmd"] == "") && $_SESSION["cont_file_insert"] != "") { + $_GET["subCmd"] = $_SESSION["cont_file_insert"]; + } + + switch ($_GET["subCmd"]) { + case "insertFromWorkspace": + $this->insertFromWorkspace(); + break; + + case "insertFromRepository": + $this->insertFromRepository(); + break; + + case "selectFile": + $this->selectFile(); + break; + + default: + $this->setTabs(); + $ilTabs->setSubTabActive("cont_new_file"); + + $this->displayValidationError(); + + if ($a_form != null) { + $form = $a_form; + } else { + $form = $this->initEditForm("create"); + } + $this->tpl->setContent($form->getHTML()); + break; + } + } + + /** + * Select file + */ + public function selectFile() + { + $ilTabs = $this->tabs; + $ilUser = $this->user; + + $this->setTabs(); + $ilTabs->setSubTabActive("cont_file_from_repository"); + + $this->displayValidationError(); + $form = $this->initEditForm("select_file"); + + $this->tpl->setContent($form->getHTML()); + } + + /** + * Insert file from repository + */ + public function insertFromRepository($a_cmd = "insert") + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + + if ($a_cmd == "insert") { + $this->setTabs(); + } else { + $this->setItemTabs($a_cmd); + } + + $ilTabs->setSubTabActive("cont_file_from_repository"); + $ilCtrl->setParameter($this, "subCmd", "insertFromRepository"); + + include_once("./Services/COPage/classes/class.ilPCFileItemFileSelectorGUI.php"); + $exp = new ilPCFileItemFileSelectorGUI( + $this, + $a_cmd, + $this, + $a_cmd, + "file_ref_id" + ); + if (!$exp->handleCommand()) { + $tpl->setContent($exp->getHTML()); + } + } + + /** + * Insert file from personal workspace + */ + public function insertFromWorkspace($a_cmd = "insert") + { + $ilTabs = $this->tabs; + $tree = $this->tree; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $ilUser = $this->user; + + if ($a_cmd == "insert") { + $this->setTabs(); + } else { + $this->setItemTabs($a_cmd); + } + + $ilTabs->setSubTabActive("cont_file_from_workspace"); + + include_once("./Services/PersonalWorkspace/classes/class.ilWorkspaceExplorerGUI.php"); + $exp = new ilWorkspaceExplorerGUI($ilUser->getId(), $this, $a_cmd, $this, $a_cmd, "fl_wsp_id"); + $ilCtrl->setParameter($this, "subCmd", "selectFile"); + $exp->setCustomLinkTarget($ilCtrl->getLinkTarget($this, $a_cmd)); + $ilCtrl->setParameter($this, "subCmd", "insertFromWorkspace"); + $exp->setTypeWhiteList(array("wsrt", "wfld", "file")); + $exp->setSelectableTypes(array("file")); + if ($exp->handleCommand()) { + return; + } + $tpl->setContent($exp->getHTML()); + } + + /** + * create new file list in dom and update page in db + */ + public function create() + { + global $DIC; + + include_once("./Modules/File/classes/class.ilObjFile.php"); + + $mode = ($_POST["file_ref_id"] != "") + ? "select_file" + : "create"; + $form = $this->initEditForm($mode); + if (!$form->checkInput()) { + $form->setValuesByPost(); + $this->insert($form); + return; + } + + // from personal workspace + if (substr($_POST["file_ref_id"], 0, 4) == "wsp_") { + $fileObj = new ilObjFile(substr($_POST["file_ref_id"], 4), false); + } + // upload + elseif ($_POST["file_ref_id"] == 0) { + $fileObj = new ilObjFile(); + $fileObj->setType("file"); + $fileObj->setTitle($_FILES["file"]["name"]); + $fileObj->setDescription(""); + $fileObj->setFileName($_FILES["file"]["name"]); + $fileObj->setFileType($_FILES["file"]["type"]); + $fileObj->setFileSize($_FILES["file"]["size"]); + $fileObj->setMode("filelist"); + $fileObj->create(); + // upload file to filesystem + $fileObj->createDirectory(); + $fileObj->raiseUploadError(false); + + $upload = $DIC->upload(); + if ($upload->hasBeenProcessed() !== true) { + $upload->process(); + } + + $fileObj->getUploadFile( + $_FILES["file"]["tmp_name"], + $_FILES["file"]["name"] + ); + } + // from repository + else { + $fileObj = new ilObjFile($_POST["file_ref_id"]); + } + $_SESSION["il_text_lang_" . $_GET["ref_id"]] = $_POST["flst_language"]; + + //echo "::".is_object($this->dom).":"; + $this->content_obj = new ilPCFileList($this->getPage()); + $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); + $this->content_obj->setListTitle(ilUtil::stripSlashes($_POST["flst_title"]), $_POST["flst_language"]); + $this->content_obj->appendItem( + $fileObj->getId(), + $fileObj->getFileName(), + $fileObj->getFileType() + ); + + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } else { + $this->insert(); + } + } + + /** + * edit properties form + */ + public function edit() + { + $this->setTabs(false); + + $form = $this->initEditForm(); + $this->tpl->setContent($form->getHTML()); + } + + /** + * Init edit form + * + * @param int $a_mode Edit Mode + */ + public function initEditForm($a_mode = "edit") + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + + if ($a_mode != "add_file") { + // title + $ti = new ilTextInputGUI($lng->txt("title"), "flst_title"); + $ti->setMaxLength(80); + $ti->setSize(40); + $form->addItem($ti); + + // language + require_once("Services/MetaData/classes/class.ilMDLanguageItem.php"); + $lang = ilMDLanguageItem::_getLanguages(); + $si = new ilSelectInputGUI($lng->txt("language"), "flst_language"); + $si->setOptions($lang); + $form->addItem($si); + } + + if (in_array($a_mode, array("create", "add_file"))) { + // file + $fi = new ilFileInputGUI($lng->txt("file"), "file"); + $fi->setRequired(true); + $form->addItem($fi); + } elseif (in_array($a_mode, array("select_file"))) { + // file + $ne = new ilNonEditableValueGUI($lng->txt("file"), ""); + + if (isset($_GET["file_ref_id"])) { + include_once("./Modules/File/classes/class.ilObjFile.php"); + $file_obj = new ilObjFile((int) $_GET["file_ref_id"]); + if (is_object($file_obj)) { + // ref id as hidden input + $hi = new ilHiddenInputGUI("file_ref_id"); + $hi->setValue((int) $_GET["file_ref_id"]); + $form->addItem($hi); + + $ne->setValue($file_obj->getTitle()); + } + } elseif (isset($_GET["fl_wsp_id"])) { + // we need the object id for the instance + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + $tree = new ilWorkspaceTree($ilUser->getId()); + $node = $tree->getNodeData((int) $_GET["fl_wsp_id"]); + + include_once("./Modules/File/classes/class.ilObjFile.php"); + $file_obj = new ilObjFile($node["obj_id"], false); + if (is_object($file_obj)) { + // ref id as hidden input + $hi = new ilHiddenInputGUI("file_ref_id"); + $hi->setValue("wsp_" . (int) $node["obj_id"]); + $form->addItem($hi); + + $ne->setValue($file_obj->getTitle()); + } + $this->tpl->parseCurrentBlock(); + } + + $form->addItem($ne); + } + + + switch ($a_mode) { + case "edit": + $ti->setValue($this->content_obj->getListTitle()); + $si->setValue($this->content_obj->getLanguage()); + $form->addCommandButton("saveProperties", $lng->txt("save")); + $form->addCommandButton("cancelUpdate", $lng->txt("cancel")); + $form->setTitle($lng->txt("cont_edit_file_list_properties")); + break; + + case "create": + case "select_file": + if ($_SESSION["il_text_lang_" . $_GET["ref_id"]] != "") { + $s_lang = $_SESSION["il_text_lang_" . $_GET["ref_id"]]; + } else { + $s_lang = $ilUser->getLanguage(); + } + $si->setValue($s_lang); + $form->addCommandButton("create_flst", $lng->txt("save")); + $form->addCommandButton("cancelCreate", $lng->txt("cancel")); + $form->setTitle($lng->txt("cont_insert_file_list")); + break; + + case "add_file": + $form->addCommandButton("insertNewFileItem", $lng->txt("save")); + $form->addCommandButton("editFiles", $lng->txt("cancel")); + $form->setTitle($lng->txt("cont_insert_file_item")); + break; + } + + $form->setFormAction($ilCtrl->getFormAction($this)); + + return $form; + } + + + /** + * save table properties in db and return to page edit screen + */ + public function saveProperties() + { + $this->content_obj->setListTitle( + ilUtil::stripSlashes($_POST["flst_title"]), + ilUtil::stripSlashes($_POST["flst_language"]) + ); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } else { + $this->pg_obj->addHierIDs(); + $this->edit(); + } + } + + /** + * Edit Files + */ + public function editFiles() + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->setTabs(false); + + $ilToolbar->addButton( + $lng->txt("cont_add_file"), + $ilCtrl->getLinkTarget($this, "addFileItem") + ); + + include_once("./Services/COPage/classes/class.ilPCFileListTableGUI.php"); + $table_gui = new ilPCFileListTableGUI($this, "editFiles", $this->content_obj); + $tpl->setContent($table_gui->getHTML()); + } + + /** + * Set Tabs + */ + public function setTabs($a_create = true) + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilSetting = $this->settings; + + if ($a_create) { + $cmd = "insert"; + + $ilCtrl->setParameter($this, "subCmd", "insertNew"); + $ilTabs->addSubTabTarget( + "cont_new_file", + $ilCtrl->getLinkTarget($this, $cmd), + $cmd + ); + + $ilCtrl->setParameter($this, "subCmd", "insertFromRepository"); + $ilTabs->addSubTabTarget( + "cont_file_from_repository", + $ilCtrl->getLinkTarget($this, $cmd), + $cmd + ); + $ilCtrl->setParameter($this, "subCmd", ""); + + if (!$ilSetting->get("disable_personal_workspace") && + !$ilSetting->get("disable_wsp_files")) { + $ilCtrl->setParameter($this, "subCmd", "insertFromWorkspace"); + $ilTabs->addSubTabTarget( + "cont_file_from_workspace", + $ilCtrl->getLinkTarget($this, $cmd), + $cmd + ); + $ilCtrl->setParameter($this, "subCmd", ""); + } + } else { + $ilTabs->setBackTarget( + $lng->txt("pg"), + $this->ctrl->getParentReturn($this) + ); + + $ilTabs->addTarget( + "cont_ed_edit_files", + $ilCtrl->getLinkTarget($this, "editFiles"), + "editFiles", + get_class($this) + ); + + $ilTabs->addTarget( + "cont_ed_edit_prop", + $ilCtrl->getLinkTarget($this, "edit"), + "edit", + get_class($this) + ); + } + } + + /** + * Add file item. This function is called from file list table and calls + * newItemAfter function. + */ + public function addFileItem() + { + $ilCtrl = $this->ctrl; + + $files = $this->content_obj->getFileList(); + + if (count($files) >= 1) { + $ilCtrl->setParameterByClass( + "ilpcfileitemgui", + "hier_id", + $files[count($files) - 1]["hier_id"] + ); + $ilCtrl->setParameterByClass( + "ilpcfileitemgui", + "pc_id", + $files[count($files) - 1]["pc_id"] + ); + $ilCtrl->redirectByClass("ilpcfileitemgui", "newItemAfter"); + } else { + $ilCtrl->redirect($this, "newFileItem"); + } + } + + /** + * Delete file items from list + */ + public function deleteFileItem() + { + $ilCtrl = $this->ctrl; + + if (is_array($_POST["fid"])) { + $ids = array(); + foreach ($_POST["fid"] as $k => $v) { + $ids[] = $k; + } + $this->content_obj->deleteFileItems($ids); + } + $this->updated = $this->pg_obj->update(); + $ilCtrl->redirect($this, "editFiles"); + } + + /** + * Save positions of file items + */ + public function savePositions() + { + $ilCtrl = $this->ctrl; + + if (is_array($_POST["position"])) { + $this->content_obj->savePositions($_POST["position"]); + } + $this->updated = $this->pg_obj->update(); + $ilCtrl->redirect($this, "editFiles"); + } + + /** + * Save positions of file items and style classes + */ + public function savePositionsAndClasses() + { + $ilCtrl = $this->ctrl; + + if (is_array($_POST["position"])) { + $this->content_obj->savePositions($_POST["position"]); + } + if (is_array($_POST["class"])) { + $this->content_obj->saveStyleClasses($_POST["class"]); + } + $this->updated = $this->pg_obj->update(); + $ilCtrl->redirect($this, "editFiles"); + } + + /** + * Checks whether style selection shoudl be available or not + */ + public function checkStyleSelection() + { + // check whether there is more than one style class + $chars = $this->getCharacteristics(); + + $classes = $this->content_obj->getAllClasses(); + if (count($chars) > 1) { + return true; + } + foreach ($classes as $class) { + if ($class != "" && $class != "FileListItem") { + return true; + } + } + return false; + } + + // + // + // New file item + // + // + + /** + * New file item (called, if there is no file item in an existing) + * + * @param + * @return + */ + public function newFileItem() + { + $ilTabs = $this->tabs; + + if ($_GET["subCmd"] == "insertNew") { + $_SESSION["cont_file_insert"] = "insertNew"; + } + if ($_GET["subCmd"] == "insertFromRepository") { + $_SESSION["cont_file_insert"] = "insertFromRepository"; + } + if ($_GET["subCmd"] == "insertFromWorkspace") { + $_SESSION["cont_file_insert"] = "insertFromWorkspace"; + } + if (($_GET["subCmd"] == "") && $_SESSION["cont_file_insert"] != "") { + $_GET["subCmd"] = $_SESSION["cont_file_insert"]; + } + + switch ($_GET["subCmd"]) { + case "insertFromWorkspace": + $this->insertFromWorkspace("newFileItem"); + break; + + case "insertFromRepository": + $this->insertFromRepository("newFileItem"); + break; + + case "selectFile": + $this->insertNewFileItem($_GET["file_ref_id"]); + break; + + default: + $this->setItemTabs("newFileItem"); + $ilTabs->setSubTabActive("cont_new_file"); + + $this->displayValidationError(); + + $form = $this->initEditForm("add_file"); + $this->tpl->setContent($form->getHTML()); + break; + } + } + + /** + * insert new file item after another item + */ + public function insertNewFileItem($a_file_ref_id = 0) + { + $ilUser = $this->user; + + // from personal workspace + if (isset($_GET["fl_wsp_id"])) { + // we need the object id for the instance + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + $tree = new ilWorkspaceTree($ilUser->getId()); + $node = $tree->getNodeData($_GET["fl_wsp_id"]); + + include_once("./Modules/File/classes/class.ilObjFile.php"); + $file_obj = new ilObjFile($node["obj_id"], false); + } + // upload + elseif ($a_file_ref_id == 0) { + $file_obj = $this->createFileItem(); + } + // from repository + else { + include_once("./Modules/File/classes/class.ilObjFile.php"); + $file_obj = new ilObjFile($a_file_ref_id); + } + if (is_object($file_obj)) { + $this->content_obj->appendItem( + $file_obj->getId(), + $file_obj->getTitle(), + $file_obj->getFileType() + ); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + //$this->ctrl->returnToParent($this, "jump".$this->hier_id); + $this->ctrl->redirect($this, "editFiles"); + } + } + + $_GET["subCmd"] = "-"; + $this->newFileItem(); + } + + /** + * insert new file item + */ + public function createFileItem() + { + global $DIC; + + $lng = $this->lng; + + if ($_FILES["file"]["name"] == "") { + $_GET["subCmd"] = "-"; + ilUtil::sendFailure($lng->txt("upload_error_file_not_found")); + return false; + } + + $form = $this->initEditForm(); + // see #22541 + // $form->checkInput(); + + include_once("./Modules/File/classes/class.ilObjFile.php"); + $fileObj = new ilObjFile(); + $fileObj->setType("file"); + $fileObj->setTitle($_FILES["file"]["name"]); + $fileObj->setDescription(""); + $fileObj->setVersion(0); + $fileObj->setMaxVersion(0); + $fileObj->setFileName($_FILES["file"]["name"]); + $fileObj->setFileType($_FILES["file"]["type"]); + $fileObj->setFileSize($_FILES["file"]["size"]); + $fileObj->setMode("filelist"); + $fileObj->create(); + $fileObj->createDirectory(); + $fileObj->raiseUploadError(false); + $fileObj->getUploadFile($_FILES["file"]["tmp_name"], $_FILES["file"]["name"]); + // upload file to filesystem + + return $fileObj; + } + + + /** + * output tabs + */ + public function setItemTabs($a_cmd = "") + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $ilSetting = $this->settings; + + $ilTabs->addTarget( + "cont_back", + $this->ctrl->getParentReturn($this), + "", + "" + ); + + if ($a_cmd != "") { + $ilCtrl->setParameter($this, "subCmd", "insertNew"); + $ilTabs->addSubTabTarget( + "cont_new_file", + $ilCtrl->getLinkTarget($this, $a_cmd), + $a_cmd + ); + + $ilCtrl->setParameter($this, "subCmd", "insertFromRepository"); + $ilTabs->addSubTabTarget( + "cont_file_from_repository", + $ilCtrl->getLinkTarget($this, $a_cmd), + $a_cmd + ); + $ilCtrl->setParameter($this, "subCmd", ""); + + if (!$ilSetting->get("disable_personal_workspace") && + !$ilSetting->get("disable_wsp_files")) { + $ilCtrl->setParameter($this, "subCmd", "insertFromWorkspace"); + $ilTabs->addSubTabTarget( + "cont_file_from_workspace", + $ilCtrl->getLinkTarget($this, $a_cmd), + $a_cmd + ); + $ilCtrl->setParameter($this, "subCmd", ""); + } + } + } } -?> diff --git a/Services/COPage/classes/class.ilPCFileListTableGUI.php b/Services/COPage/classes/class.ilPCFileListTableGUI.php index 968cdaeda4f78041a50b7772a31819370e052451..722026ef1f641a55f6d674a7cf0b2d63c27b49bd 100755 --- a/Services/COPage/classes/class.ilPCFileListTableGUI.php +++ b/Services/COPage/classes/class.ilPCFileListTableGUI.php @@ -15,85 +15,81 @@ include_once("Services/Table/classes/class.ilTable2GUI.php"); */ class ilPCFileListTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - function __construct($a_parent_obj, $a_parent_cmd, $a_file_list) - { - global $DIC; + public function __construct($a_parent_obj, $a_parent_cmd, $a_file_list) + { + 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->addColumn("", "", "1"); - $this->addColumn($lng->txt("cont_position"), "", "1"); - if ($this->getParentObject()->checkStyleSelection()) - { - $this->addColumn($lng->txt("cont_file"), "", "50%"); - $this->addColumn($lng->txt("cont_characteristic"), "", "50%"); - } - else - { - $this->addColumn($lng->txt("cont_file"), "", "100%"); - } - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.file_list_row.html", - "Services/COPage"); - - $this->file_list = $a_file_list; - $this->setData($this->file_list->getFileList()); - $this->setLimit(0); - - $this->addMultiCommand("deleteFileItem", $lng->txt("delete")); - if (count($this->getData()) > 0) - { - if ($this->getParentObject()->checkStyleSelection()) - { - $this->addCommandButton("savePositionsAndClasses", $lng->txt("cont_save_positions_and_classes")); - } - else - { - $this->addCommandButton("savePositions", $lng->txt("cont_save_positions")); - } - } - - $this->setTitle($lng->txt("cont_files")); - } - - /** - * 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->addColumn("", "", "1"); + $this->addColumn($lng->txt("cont_position"), "", "1"); + if ($this->getParentObject()->checkStyleSelection()) { + $this->addColumn($lng->txt("cont_file"), "", "50%"); + $this->addColumn($lng->txt("cont_characteristic"), "", "50%"); + } else { + $this->addColumn($lng->txt("cont_file"), "", "100%"); + } + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate( + "tpl.file_list_row.html", + "Services/COPage" + ); + + $this->file_list = $a_file_list; + $this->setData($this->file_list->getFileList()); + $this->setLimit(0); + + $this->addMultiCommand("deleteFileItem", $lng->txt("delete")); + if (count($this->getData()) > 0) { + if ($this->getParentObject()->checkStyleSelection()) { + $this->addCommandButton("savePositionsAndClasses", $lng->txt("cont_save_positions_and_classes")); + } else { + $this->addCommandButton("savePositions", $lng->txt("cont_save_positions")); + } + } + + $this->setTitle($lng->txt("cont_files")); + } + + /** + * 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->getParentObject()->checkStyleSelection()) - { - $this->tpl->setCurrentBlock("class_sel"); - $sel = ($a_set["class"] == "") - ? "FileListItem" - : $a_set["class"]; - $this->tpl->setVariable("CLASS_SEL", ilUtil::formSelect($sel, - "class[".$a_set["hier_id"].":".$a_set["pc_id"]."]", - $this->getParentObject()->getCharacteristics(), false, true)); - $this->tpl->parseCurrentBlock(); - } - - $this->pos += 10; - $this->tpl->setVariable("POS", $this->pos); - $this->tpl->setVariable("FID", $a_set["hier_id"].":".$a_set["pc_id"]); - $this->tpl->setVariable("TXT_FILE", ilObject::_lookupTitle($a_set["id"])); - } + if ($this->getParentObject()->checkStyleSelection()) { + $this->tpl->setCurrentBlock("class_sel"); + $sel = ($a_set["class"] == "") + ? "FileListItem" + : $a_set["class"]; + $this->tpl->setVariable("CLASS_SEL", ilUtil::formSelect( + $sel, + "class[" . $a_set["hier_id"] . ":" . $a_set["pc_id"] . "]", + $this->getParentObject()->getCharacteristics(), + false, + true + )); + $this->tpl->parseCurrentBlock(); + } + $this->pos += 10; + $this->tpl->setVariable("POS", $this->pos); + $this->tpl->setVariable("FID", $a_set["hier_id"] . ":" . $a_set["pc_id"]); + $this->tpl->setVariable("TXT_FILE", ilObject::_lookupTitle($a_set["id"])); + } } -?> diff --git a/Services/COPage/classes/class.ilPCGrid.php b/Services/COPage/classes/class.ilPCGrid.php index 4a01ace07113a428767d2050623f925042b98428..8d5e2480ee2d7aa0e6d4fb972ea66a2608d3a648 100755 --- a/Services/COPage/classes/class.ilPCGrid.php +++ b/Services/COPage/classes/class.ilPCGrid.php @@ -1,24 +1,24 @@ setType("grid"); - } + /** + * Init page content component. + */ + public function init() + { + $this->setType("grid"); + } - /** - * Set content node - * @param object $a_node - */ - function setNode($a_node) - { - parent::setNode($a_node); // this is the PageContent node - $this->grid_node = $a_node->first_child(); // this is the Tabs node - } + /** + * Set content node + * @param object $a_node + */ + public function setNode($a_node) + { + parent::setNode($a_node); // this is the PageContent node + $this->grid_node = $a_node->first_child(); // this is the Tabs node + } - /** - * Get sizes - * - * Note that these are mapped to (BS3): - * s > .col-xs, m > .col-sm, l > .col-md, xl > .col-lg - * - * @return array - */ - static function getSizes() - { - return array("s" => "s", "m" => "m", "l" => "l", "xl" => "xl"); - } + /** + * Get sizes + * + * Note that these are mapped to (BS3): + * s > .col-xs, m > .col-sm, l > .col-md, xl > .col-lg + * + * @return array + */ + public static function getSizes() + { + return array("s" => "s", "m" => "m", "l" => "l", "xl" => "xl"); + } - /** - * Get widths - * @return array - */ - static function getWidths() - { - return array( - "1" => "1/12", "2" => "2/12", "3" => "3/12", - "4" => "4/12", "5" => "5/12", "6" => "6/12", - "7" => "7/12", "8" => "8/12", "9" => "9/12", - "10" => "10/12", "11" => "11/12", "12" => "12/12" - ); - } + /** + * Get widths + * @return array + */ + public static function getWidths() + { + return array( + "1" => "1/12", "2" => "2/12", "3" => "3/12", + "4" => "4/12", "5" => "5/12", "6" => "6/12", + "7" => "7/12", "8" => "8/12", "9" => "9/12", + "10" => "10/12", "11" => "11/12", "12" => "12/12" + ); + } - /** - * Create new Grid 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->grid_node = $this->dom->create_element("Grid"); - $this->grid_node = $this->node->append_child($this->grid_node); - } + /** + * Create new Grid node + */ + public 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->grid_node = $this->dom->create_element("Grid"); + $this->grid_node = $this->node->append_child($this->grid_node); + } - /** - * Set attribute of grid tag - * - * @param string $a_attr attribute name - * @param string $a_value attribute value - */ - /* - protected function setTabsAttribute($a_attr, $a_value) - { - if (!empty($a_value)) - { - $this->grid_node->set_attribute($a_attr, $a_value); - } - else - { - if ($this->grid_node->has_attribute($a_attr)) - { - $this->grid_node->remove_attribute($a_attr); - } - } - }*/ + /** + * Set attribute of grid tag + * + * @param string $a_attr attribute name + * @param string $a_value attribute value + */ + /* + protected function setTabsAttribute($a_attr, $a_value) + { + if (!empty($a_value)) + { + $this->grid_node->set_attribute($a_attr, $a_value); + } + else + { + if ($this->grid_node->has_attribute($a_attr)) + { + $this->grid_node->remove_attribute($a_attr); + } + } + }*/ - /** - * Save positions of grid cells - * - * @param array $a_pos - */ - function savePositions($a_pos) - { - asort($a_pos); + /** + * Save positions of grid cells + * + * @param array $a_pos + */ + public function savePositions($a_pos) + { + asort($a_pos); - $childs = $this->grid_node->child_nodes(); - $nodes = array(); - for ($i=0; $inode_name() == "GridCell") - { - $pc_id = $childs[$i]->get_attribute("PCID"); - $hier_id = $childs[$i]->get_attribute("HierId"); - $nodes[$hier_id.":".$pc_id] = $childs[$i]; - $childs[$i]->unlink($childs[$i]); - } - } - - foreach($a_pos as $k => $v) - { - if (is_object($nodes[$k])) - { - $nodes[$k] = $this->grid_node->append_child($nodes[$k]); - } - } - } + $childs = $this->grid_node->child_nodes(); + $nodes = array(); + for ($i=0; $inode_name() == "GridCell") { + $pc_id = $childs[$i]->get_attribute("PCID"); + $hier_id = $childs[$i]->get_attribute("HierId"); + $nodes[$hier_id . ":" . $pc_id] = $childs[$i]; + $childs[$i]->unlink($childs[$i]); + } + } + + foreach ($a_pos as $k => $v) { + if (is_object($nodes[$k])) { + $nodes[$k] = $this->grid_node->append_child($nodes[$k]); + } + } + } - /** - * Save widths of cells - */ - function saveWidths($a_width_s, $a_width_m, $a_width_l, $a_width_xl) - { - $cell_nodes = $this->grid_node->child_nodes(); - for($i = 0; $i < count($cell_nodes); $i++) - { - if ($cell_nodes[$i]->node_name() == "GridCell") - { - $pc_id = $cell_nodes[$i]->get_attribute("PCID"); - $hier_id = $cell_nodes[$i]->get_attribute("HierId"); - $k = $hier_id.":".$pc_id; - $cell_nodes[$i]->set_attribute("WIDTH_XS", ""); - $cell_nodes[$i]->set_attribute("WIDTH_S", $a_width_s[$k]); - $cell_nodes[$i]->set_attribute("WIDTH_M", $a_width_m[$k]); - $cell_nodes[$i]->set_attribute("WIDTH_L", $a_width_l[$k]); - $cell_nodes[$i]->set_attribute("WIDTH_XL", $a_width_xl[$k]); - } - } - } + /** + * Save widths of cells + */ + public function saveWidths($a_width_s, $a_width_m, $a_width_l, $a_width_xl) + { + $cell_nodes = $this->grid_node->child_nodes(); + for ($i = 0; $i < count($cell_nodes); $i++) { + if ($cell_nodes[$i]->node_name() == "GridCell") { + $pc_id = $cell_nodes[$i]->get_attribute("PCID"); + $hier_id = $cell_nodes[$i]->get_attribute("HierId"); + $k = $hier_id . ":" . $pc_id; + $cell_nodes[$i]->set_attribute("WIDTH_XS", ""); + $cell_nodes[$i]->set_attribute("WIDTH_S", $a_width_s[$k]); + $cell_nodes[$i]->set_attribute("WIDTH_M", $a_width_m[$k]); + $cell_nodes[$i]->set_attribute("WIDTH_L", $a_width_l[$k]); + $cell_nodes[$i]->set_attribute("WIDTH_XL", $a_width_xl[$k]); + } + } + } - /** - * Delete grid cell - */ - function deleteGridCell($a_hier_id, $a_pc_id) - { - $childs = $this->grid_node->child_nodes(); - for ($i=0; $inode_name() == "GridCell") - { - if ($a_pc_id == $childs[$i]->get_attribute("PCID") && - $a_hier_id == $childs[$i]->get_attribute("HierId")) - { - $childs[$i]->unlink($childs[$i]); - } - } - } - } + /** + * Delete grid cell + */ + public function deleteGridCell($a_hier_id, $a_pc_id) + { + $childs = $this->grid_node->child_nodes(); + for ($i=0; $inode_name() == "GridCell") { + if ($a_pc_id == $childs[$i]->get_attribute("PCID") && + $a_hier_id == $childs[$i]->get_attribute("HierId")) { + $childs[$i]->unlink($childs[$i]); + } + } + } + } - /** - * Add grid cell - */ - function addGridCell($a_s, $a_m, $a_l, $a_xl) - { - $new_item = $this->dom->create_element("GridCell"); - $new_item = $this->grid_node->append_child($new_item); - //$new_item->set_attribute("xs", $a_xs); - $new_item->set_attribute("WIDTH_XS", ""); - $new_item->set_attribute("WIDTH_S", $a_s); - $new_item->set_attribute("WIDTH_M", $a_m); - $new_item->set_attribute("WIDTH_L", $a_l); - $new_item->set_attribute("WIDTH_XL", $a_xl); - } + /** + * Add grid cell + */ + public function addGridCell($a_s, $a_m, $a_l, $a_xl) + { + $new_item = $this->dom->create_element("GridCell"); + $new_item = $this->grid_node->append_child($new_item); + //$new_item->set_attribute("xs", $a_xs); + $new_item->set_attribute("WIDTH_XS", ""); + $new_item->set_attribute("WIDTH_S", $a_s); + $new_item->set_attribute("WIDTH_M", $a_m); + $new_item->set_attribute("WIDTH_L", $a_l); + $new_item->set_attribute("WIDTH_XL", $a_xl); + } - /** - * Add a cell - */ - function addCell() - { - $new_item = $this->dom->create_element("GridCell"); - $new_item->set_attribute("WIDTH_XS", ""); - $new_item->set_attribute("WIDTH_S", ""); - $new_item->set_attribute("WIDTH_M", ""); - $new_item->set_attribute("WIDTH_L", ""); - $new_item->set_attribute("WIDTH_XL", ""); - $this->grid_node->append_child($new_item); - } + /** + * Add a cell + */ + public function addCell() + { + $new_item = $this->dom->create_element("GridCell"); + $new_item->set_attribute("WIDTH_XS", ""); + $new_item->set_attribute("WIDTH_S", ""); + $new_item->set_attribute("WIDTH_M", ""); + $new_item->set_attribute("WIDTH_L", ""); + $new_item->set_attribute("WIDTH_XL", ""); + $this->grid_node->append_child($new_item); + } - /** - * Get lang vars needed for editing - * @return array array of lang var keys - */ - static function getLangVars() - { - return array("pc_grid", "pc_grid_cell", "ed_delete_cell", "ed_cell_left", "ed_cell_right"); - } + /** + * Get lang vars needed for editing + * @return array array of lang var keys + */ + public static function getLangVars() + { + return array("pc_grid", "pc_grid_cell", "ed_delete_cell", "ed_cell_left", "ed_cell_right"); + } - /** - * Get Javascript files - */ - function getJavascriptFiles($a_mode) - { - return parent::getJavascriptFiles($a_mode); - } + /** + * Get Javascript files + */ + public function getJavascriptFiles($a_mode) + { + return parent::getJavascriptFiles($a_mode); + } - /** - * Get Javascript files - */ - function getCssFiles($a_mode) - { - return parent::getCssFiles($a_mode); - } - - function getCellData() - { - $cells = array(); - $cell_nodes = $this->grid_node->child_nodes(); - $k = 0; - for($i = 0; $i < count($cell_nodes); $i++) - { - if ($cell_nodes[$i]->node_name() == "GridCell") - { - $pc_id = $cell_nodes[$i]->get_attribute("PCID"); - $hier_id = $cell_nodes[$i]->get_attribute("HierId"); - $cells[] = array("pos" => $k, - "xs" => $cell_nodes[$i]->get_attribute("WIDTH_XS"), - "s" => $cell_nodes[$i]->get_attribute("WIDTH_S"), - "m" => $cell_nodes[$i]->get_attribute("WIDTH_M"), - "l" => $cell_nodes[$i]->get_attribute("WIDTH_L"), - "xl" => $cell_nodes[$i]->get_attribute("WIDTH_XL"), - "pc_id" => $pc_id, "hier_id" => $hier_id); - $k++; - } - } - - return $cells; - } + /** + * Get Javascript files + */ + public function getCssFiles($a_mode) + { + return parent::getCssFiles($a_mode); + } + public function getCellData() + { + $cells = array(); + $cell_nodes = $this->grid_node->child_nodes(); + $k = 0; + for ($i = 0; $i < count($cell_nodes); $i++) { + if ($cell_nodes[$i]->node_name() == "GridCell") { + $pc_id = $cell_nodes[$i]->get_attribute("PCID"); + $hier_id = $cell_nodes[$i]->get_attribute("HierId"); + $cells[] = array("pos" => $k, + "xs" => $cell_nodes[$i]->get_attribute("WIDTH_XS"), + "s" => $cell_nodes[$i]->get_attribute("WIDTH_S"), + "m" => $cell_nodes[$i]->get_attribute("WIDTH_M"), + "l" => $cell_nodes[$i]->get_attribute("WIDTH_L"), + "xl" => $cell_nodes[$i]->get_attribute("WIDTH_XL"), + "pc_id" => $pc_id, "hier_id" => $hier_id); + $k++; + } + } + return $cells; + } } -?> diff --git a/Services/COPage/classes/class.ilPCGridCell.php b/Services/COPage/classes/class.ilPCGridCell.php index fa6d3f1b06757ae9f7ac9ff3c024437a640fd559..b76399863bb02febc091ddfc7b7a9656f3815095 100755 --- a/Services/COPage/classes/class.ilPCGridCell.php +++ b/Services/COPage/classes/class.ilPCGridCell.php @@ -13,46 +13,44 @@ require_once("./Services/COPage/classes/class.ilPageContent.php"); */ class ilPCGridCell extends ilPageContent { - /** - * Init page content component. - */ - function init() - { - $this->setType("gcell"); - } + /** + * Init page content component. + */ + public function init() + { + $this->setType("gcell"); + } - /** - * delete tab - */ - function deleteCell() - { - $grid_cell = $this->getNode(); - $grid_cell->unlink($grid_cell); - } + /** + * delete tab + */ + public function deleteCell() + { + $grid_cell = $this->getNode(); + $grid_cell->unlink($grid_cell); + } - /** - * Move cell right - */ - function moveCellRight() - { - $grid_cell = $this->getNode(); - $next = $grid_cell->next_sibling(); - $next_copy = $next->clone_node(true); - $grid_cell->insert_before($next_copy, $grid_cell); - $next->unlink($next); - } - - /** - * Move cell left - */ - function moveCellLeft() - { - $grid_cell = $this->getNode(); - $prev = $grid_cell->previous_sibling(); - $grid_cell_copy = $grid_cell->clone_node(true); - $prev->insert_before($grid_cell_copy, $prev); - $grid_cell->unlink($grid_cell); - } + /** + * Move cell right + */ + public function moveCellRight() + { + $grid_cell = $this->getNode(); + $next = $grid_cell->next_sibling(); + $next_copy = $next->clone_node(true); + $grid_cell->insert_before($next_copy, $grid_cell); + $next->unlink($next); + } + /** + * Move cell left + */ + public function moveCellLeft() + { + $grid_cell = $this->getNode(); + $prev = $grid_cell->previous_sibling(); + $grid_cell_copy = $grid_cell->clone_node(true); + $prev->insert_before($grid_cell_copy, $prev); + $grid_cell->unlink($grid_cell); + } } -?> \ No newline at end of file diff --git a/Services/COPage/classes/class.ilPCGridCellGUI.php b/Services/COPage/classes/class.ilPCGridCellGUI.php index 86af6f7b819fbfa3d34a25351bcd050492b3e503..69c702b2cdf54962104126fd66ffe631d386308a 100755 --- a/Services/COPage/classes/class.ilPCGridCellGUI.php +++ b/Services/COPage/classes/class.ilPCGridCellGUI.php @@ -15,65 +15,62 @@ require_once("./Services/COPage/classes/class.ilPageContentGUI.php"); class ilPCGridCellGUI extends ilPageContentGUI { - /** - * Constructor - */ - function __construct($a_pg_obj, &$a_content_obj, $a_hier_id, $a_pc_id = "") - { - parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); - } + /** + * Constructor + */ + public function __construct($a_pg_obj, &$a_content_obj, $a_hier_id, $a_pc_id = "") + { + 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); + /** + * 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(); + // get current command + $cmd = $this->ctrl->getCmd(); - switch($next_class) - { - default: - $ret = $this->$cmd(); - break; - } + switch ($next_class) { + default: + $ret = $this->$cmd(); + break; + } - return $ret; - } + return $ret; + } - /** - * delete cell - */ - function deleteCell() - { - $this->content_obj->deleteCell(); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } + /** + * delete cell + */ + public function deleteCell() + { + $this->content_obj->deleteCell(); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } - /** - * Move cell right - */ - function moveCellRight() - { - $this->content_obj->moveCellRight(); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * Move cell left - */ - function moveCellLeft() - { - $this->content_obj->moveCellLeft(); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } + /** + * Move cell right + */ + public function moveCellRight() + { + $this->content_obj->moveCellRight(); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + /** + * Move cell left + */ + public function moveCellLeft() + { + $this->content_obj->moveCellLeft(); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } } -?> diff --git a/Services/COPage/classes/class.ilPCGridCellTableGUI.php b/Services/COPage/classes/class.ilPCGridCellTableGUI.php index cfc790769d9babf7da4dbec78c8717da000bb5ae..c4101e20aee8608317d0d9ef3b54417de7e02e2e 100755 --- a/Services/COPage/classes/class.ilPCGridCellTableGUI.php +++ b/Services/COPage/classes/class.ilPCGridCellTableGUI.php @@ -12,63 +12,61 @@ include_once("Services/Table/classes/class.ilTable2GUI.php"); */ class ilPCGridCellTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - function __construct($a_parent_obj, $a_parent_cmd, ilPCGrid $a_grid) - { - 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->addColumn("", "", "1"); - $this->addColumn($lng->txt("cont_position"), "", "1"); - $this->addColumn($lng->txt("cont_grid_width_s")); - $this->addColumn($lng->txt("cont_grid_width_m")); - $this->addColumn($lng->txt("cont_grid_width_l")); - $this->addColumn($lng->txt("cont_grid_width_xl")); - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.grid_cell_row.html", - "Services/COPage"); - - $this->grid = $a_grid; - //$caps = $this->tabs->getCaptions(); - $this->setData($this->grid->getCellData()); - $this->setLimit(0); - - $this->addMultiCommand("confirmCellDeletion", $lng->txt("delete")); - $this->addCommandButton("saveCellData", $lng->txt("save")); - - $this->setTitle($lng->txt("cont_ed_grid_col_widths")); - } - - /** - * Standard Version of Fill Row. Most likely to - * be overwritten by derived class. - */ - protected function fillRow($a_set) - { - $this->pos += 10; - $this->tpl->setVariable("POS", ilUtil::prepareFormOutput($this->pos)); - $tid = $a_set["hier_id"].":".$a_set["pc_id"]; - $this->tpl->setVariable("TID", $tid); - foreach (ilPCGrid::getSizes() as $s) - { - $this->tpl->setCurrentBlock("select_width"); - $this->tpl->setVariable("SELECT_WIDTH", ilUtil::formSelect($a_set[$s], "width_".$s."[$tid]", array("" => "") + ilPCGrid::getWidths(),false, true)); - $this->tpl->parseCurrentBlock(); - } - - } + public function __construct($a_parent_obj, $a_parent_cmd, ilPCGrid $a_grid) + { + 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->addColumn("", "", "1"); + $this->addColumn($lng->txt("cont_position"), "", "1"); + $this->addColumn($lng->txt("cont_grid_width_s")); + $this->addColumn($lng->txt("cont_grid_width_m")); + $this->addColumn($lng->txt("cont_grid_width_l")); + $this->addColumn($lng->txt("cont_grid_width_xl")); + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate( + "tpl.grid_cell_row.html", + "Services/COPage" + ); + + $this->grid = $a_grid; + //$caps = $this->tabs->getCaptions(); + $this->setData($this->grid->getCellData()); + $this->setLimit(0); + + $this->addMultiCommand("confirmCellDeletion", $lng->txt("delete")); + $this->addCommandButton("saveCellData", $lng->txt("save")); + + $this->setTitle($lng->txt("cont_ed_grid_col_widths")); + } + + /** + * Standard Version of Fill Row. Most likely to + * be overwritten by derived class. + */ + protected function fillRow($a_set) + { + $this->pos += 10; + $this->tpl->setVariable("POS", ilUtil::prepareFormOutput($this->pos)); + $tid = $a_set["hier_id"] . ":" . $a_set["pc_id"]; + $this->tpl->setVariable("TID", $tid); + foreach (ilPCGrid::getSizes() as $s) { + $this->tpl->setCurrentBlock("select_width"); + $this->tpl->setVariable("SELECT_WIDTH", ilUtil::formSelect($a_set[$s], "width_" . $s . "[$tid]", array("" => "") + ilPCGrid::getWidths(), false, true)); + $this->tpl->parseCurrentBlock(); + } + } } -?> \ No newline at end of file diff --git a/Services/COPage/classes/class.ilPCGridGUI.php b/Services/COPage/classes/class.ilPCGridGUI.php index dbd93461a484bca68eddba94c8a7c75001609cf3..a5b986d984c888474bde06daa431db02264f9876 100755 --- a/Services/COPage/classes/class.ilPCGridGUI.php +++ b/Services/COPage/classes/class.ilPCGridGUI.php @@ -14,313 +14,297 @@ require_once("./Services/COPage/classes/class.ilPageContentGUI.php"); */ class ilPCGridGUI extends ilPageContentGUI { - protected $toolbar; - protected $tabs; - - /** - * Constructor - * @param $a_pg_obj - * @param $a_content_obj - * @param $a_hier_id - * @param string $a_pc_id - */ - function __construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id = "") - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $ilToolbar = $DIC->toolbar(); - $ilTabs = $DIC->tabs(); - - $this->toolbar = $ilToolbar; - $this->tabs = $ilTabs; - 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 grid - */ - function insert() - { - $this->displayValidationError(); - $form = $this->initCreationForm(); - if ($this->ctrl->getCmd() == "create") - { - $form->setValuesByPost(); - } - $this->tpl->setContent($form->getHTML()); - } - - /** - * Edit grid cells - */ - function editProperties() - { - $this->displayValidationError(); - $this->setTabs(); - - $form = $this->initForm(); - $this->getFormValues($form); - $html = $form->getHTML(); - $this->tpl->setContent($html); - } - - /** - * Init creation form - * @return ilPropertyFormGUI - */ - function initCreationForm() - { - // edit form - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - $form->setTitle($this->lng->txt("cont_ed_insert_grid")); - $form->setDescription($this->lng->txt("cont_ed_insert_grid_info")); - - // number of cells - $ni = new ilNumberInputGUI($this->lng->txt("cont_grid_nr_cells"), "number_of_cells"); - $ni->setMaxLength(2); - $ni->setSize(2); - $form->addItem($ni); - - $sh = new ilFormSectionHeaderGUI(); - $sh->setTitle($this->lng->txt("cont_ed_grid_col_width")); - $sh->setInfo($this->lng->txt("cont_ed_grid_col_width_info")); - $form->addItem($sh); - - $options = array("" => "") + ilPCGrid::getWidths(); - - // widths - foreach (ilPCGrid::getSizes() as $s) - { - $si = new ilSelectInputGUI($this->lng->txt("cont_grid_width_".$s), $s); - $si->setInfo($this->lng->txt("cont_grid_width_".$s."_info")); - $si->setOptions($options); - $form->addItem($si); - } - - // save/cancel buttons - $form->addCommandButton("create_grid", $this->lng->txt("save")); - $form->addCommandButton("cancelCreate", $this->lng->txt("cancel")); - - return $form; - } - - /** - * Create new grid element - */ - function create() - { - $form = $this->initCreationForm(); - if ($form->checkInput()) - { - $this->content_obj = new ilPCGrid($this->getPage()); - $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); - - for ($i = 0; $i < (int) $_POST["number_of_cells"]; $i++) - { - $this->content_obj->addGridCell($_POST["s"], $_POST["m"], $_POST["l"], $_POST["xl"]); - } - - $this->updated = $this->pg_obj->update(); - - if ($this->updated === true) - { - $this->afterCreation(); - //$this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - else - { - $this->insert(); - } - } - else - { - $form->setValuesByPost(); - $this->tpl->setContent($form->getHTML()); - } - } - - /** - * After creation processing - */ - function afterCreation() - { - $this->pg_obj->stripHierIDs(); - $this->pg_obj->addHierIDs(); - $this->ctrl->setParameter($this, "hier_id", $this->content_obj->readHierId()); - $this->ctrl->setParameter($this, "pc_id", $this->content_obj->readPCId()); - $this->content_obj->setHierId($this->content_obj->readHierId()); - $this->setHierId($this->content_obj->readHierId()); - $this->content_obj->setPCId($this->content_obj->readPCId()); - $this->edit(); - } - - - // - // Edit Grid cells - // - - /** - * List all cells - */ - function edit() - { - $this->toolbar->addButton($this->lng->txt("cont_add_cell"), - $this->ctrl->getLinkTarget($this, "addCell")); - - $this->setTabs(); - $this->tabs->activateTab("settings"); - include_once("./Services/COPage/classes/class.ilPCGridCellTableGUI.php"); - $table_gui = new ilPCGridCellTableGUI($this, "edit", $this->content_obj); - $this->tpl->setContent($table_gui->getHTML()); - } - - /** - * Save cell properties - */ - function saveCells() - { - if (is_array($_POST["position"])) - { - $positions = ilUtil::stripSlashesArray($_POST["position"]); - $this->content_obj->savePositions($positions); - } - $this->updated = $this->pg_obj->update(); - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "edit"); - } - - /** - * Add cell - */ - function addCell() - { - $this->content_obj->addCell("", "", "", ""); - $this->updated = $this->pg_obj->update(); - - ilUtil::sendSuccess($this->lng->txt("cont_added_cell"), true); - $this->ctrl->redirect($this, "edit"); - } - - /** - * Confirm cell deletion - */ - function confirmCellDeletion() - { - $this->setTabs(); - - if (!is_array($_POST["tid"]) || count($_POST["tid"]) == 0) - { - ilUtil::sendInfo($this->lng->txt("no_checkbox"), true); - $this->ctrl->redirect($this, "edit"); - } - else - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($this->ctrl->getFormAction($this)); - $cgui->setHeaderText($this->lng->txt("cont_grid_cell_confirm_deletion")); - $cgui->setCancel($this->lng->txt("cancel"), "cancelCellDeletion"); - $cgui->setConfirm($this->lng->txt("delete"), "deleteCells"); - - foreach ($_POST["tid"] as $k => $i) - { - $id = explode(":", $k); - $id = explode("_", $id[0]); - $cgui->addItem("tid[]", $k, $this->lng->txt("cont_grid_cell")." ".$id[count($id) - 1]); - } - - $this->tpl->setContent($cgui->getHTML()); - } - } - - /** - * Cancel cell deletion - */ - function cancelCellDeletion() - { - $this->ctrl->redirect($this, "edit"); - } - - /** - * Delete Cells - */ - function deleteCells() - { - $ilCtrl = $this->ctrl; - - if (is_array($_POST["tid"])) - { - foreach($_POST["tid"] as $tid) - { - $ids = explode(":", $tid); - $this->content_obj->deleteGridCell($ids[0], $ids[1]); - } - } - $this->updated = $this->pg_obj->update(); - - $ilCtrl->redirect($this, "edit"); - } - - - /** - * Set tabs - */ - function setTabs() - { - $this->tabs->setBackTarget($this->lng->txt("pg"), - $this->ctrl->getParentReturn($this)); - - $this->tabs->addTab("settings", - $this->lng->txt("settings"), - $this->ctrl->getLinkTarget($this, "edit") - ); - - } - - /** - * Save tabs properties in db and return to page edit screen - */ - function saveCellData() - { - $width_s = ilUtil::stripSlashesArray($_POST["width_s"]); - $width_m = ilUtil::stripSlashesArray($_POST["width_m"]); - $width_l = ilUtil::stripSlashesArray($_POST["width_l"]); - $width_xl = ilUtil::stripSlashesArray($_POST["width_xl"]); - $this->content_obj->saveWidths($width_s, $width_m, $width_l, $width_xl); - - if (is_array($_POST["position"])) - { - $positions = ilUtil::stripSlashesArray($_POST["position"]); - $this->content_obj->savePositions($positions); - } - $this->updated = $this->pg_obj->update(); - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "edit"); - } - + protected $toolbar; + protected $tabs; + + /** + * Constructor + * @param $a_pg_obj + * @param $a_content_obj + * @param $a_hier_id + * @param string $a_pc_id + */ + public function __construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id = "") + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $ilToolbar = $DIC->toolbar(); + $ilTabs = $DIC->tabs(); + + $this->toolbar = $ilToolbar; + $this->tabs = $ilTabs; + 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 grid + */ + public function insert() + { + $this->displayValidationError(); + $form = $this->initCreationForm(); + if ($this->ctrl->getCmd() == "create") { + $form->setValuesByPost(); + } + $this->tpl->setContent($form->getHTML()); + } + + /** + * Edit grid cells + */ + public function editProperties() + { + $this->displayValidationError(); + $this->setTabs(); + + $form = $this->initForm(); + $this->getFormValues($form); + $html = $form->getHTML(); + $this->tpl->setContent($html); + } + + /** + * Init creation form + * @return ilPropertyFormGUI + */ + public function initCreationForm() + { + // edit form + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this)); + $form->setTitle($this->lng->txt("cont_ed_insert_grid")); + $form->setDescription($this->lng->txt("cont_ed_insert_grid_info")); + + // number of cells + $ni = new ilNumberInputGUI($this->lng->txt("cont_grid_nr_cells"), "number_of_cells"); + $ni->setMaxLength(2); + $ni->setSize(2); + $form->addItem($ni); + + $sh = new ilFormSectionHeaderGUI(); + $sh->setTitle($this->lng->txt("cont_ed_grid_col_width")); + $sh->setInfo($this->lng->txt("cont_ed_grid_col_width_info")); + $form->addItem($sh); + + $options = array("" => "") + ilPCGrid::getWidths(); + + // widths + foreach (ilPCGrid::getSizes() as $s) { + $si = new ilSelectInputGUI($this->lng->txt("cont_grid_width_" . $s), $s); + $si->setInfo($this->lng->txt("cont_grid_width_" . $s . "_info")); + $si->setOptions($options); + $form->addItem($si); + } + + // save/cancel buttons + $form->addCommandButton("create_grid", $this->lng->txt("save")); + $form->addCommandButton("cancelCreate", $this->lng->txt("cancel")); + + return $form; + } + + /** + * Create new grid element + */ + public function create() + { + $form = $this->initCreationForm(); + if ($form->checkInput()) { + $this->content_obj = new ilPCGrid($this->getPage()); + $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); + + for ($i = 0; $i < (int) $_POST["number_of_cells"]; $i++) { + $this->content_obj->addGridCell($_POST["s"], $_POST["m"], $_POST["l"], $_POST["xl"]); + } + + $this->updated = $this->pg_obj->update(); + + if ($this->updated === true) { + $this->afterCreation(); + //$this->ctrl->returnToParent($this, "jump".$this->hier_id); + } else { + $this->insert(); + } + } else { + $form->setValuesByPost(); + $this->tpl->setContent($form->getHTML()); + } + } + + /** + * After creation processing + */ + public function afterCreation() + { + $this->pg_obj->stripHierIDs(); + $this->pg_obj->addHierIDs(); + $this->ctrl->setParameter($this, "hier_id", $this->content_obj->readHierId()); + $this->ctrl->setParameter($this, "pc_id", $this->content_obj->readPCId()); + $this->content_obj->setHierId($this->content_obj->readHierId()); + $this->setHierId($this->content_obj->readHierId()); + $this->content_obj->setPCId($this->content_obj->readPCId()); + $this->edit(); + } + + + // + // Edit Grid cells + // + + /** + * List all cells + */ + public function edit() + { + $this->toolbar->addButton( + $this->lng->txt("cont_add_cell"), + $this->ctrl->getLinkTarget($this, "addCell") + ); + + $this->setTabs(); + $this->tabs->activateTab("settings"); + include_once("./Services/COPage/classes/class.ilPCGridCellTableGUI.php"); + $table_gui = new ilPCGridCellTableGUI($this, "edit", $this->content_obj); + $this->tpl->setContent($table_gui->getHTML()); + } + + /** + * Save cell properties + */ + public function saveCells() + { + if (is_array($_POST["position"])) { + $positions = ilUtil::stripSlashesArray($_POST["position"]); + $this->content_obj->savePositions($positions); + } + $this->updated = $this->pg_obj->update(); + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "edit"); + } + + /** + * Add cell + */ + public function addCell() + { + $this->content_obj->addCell("", "", "", ""); + $this->updated = $this->pg_obj->update(); + + ilUtil::sendSuccess($this->lng->txt("cont_added_cell"), true); + $this->ctrl->redirect($this, "edit"); + } + + /** + * Confirm cell deletion + */ + public function confirmCellDeletion() + { + $this->setTabs(); + + if (!is_array($_POST["tid"]) || count($_POST["tid"]) == 0) { + ilUtil::sendInfo($this->lng->txt("no_checkbox"), true); + $this->ctrl->redirect($this, "edit"); + } else { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($this->ctrl->getFormAction($this)); + $cgui->setHeaderText($this->lng->txt("cont_grid_cell_confirm_deletion")); + $cgui->setCancel($this->lng->txt("cancel"), "cancelCellDeletion"); + $cgui->setConfirm($this->lng->txt("delete"), "deleteCells"); + + foreach ($_POST["tid"] as $k => $i) { + $id = explode(":", $k); + $id = explode("_", $id[0]); + $cgui->addItem("tid[]", $k, $this->lng->txt("cont_grid_cell") . " " . $id[count($id) - 1]); + } + + $this->tpl->setContent($cgui->getHTML()); + } + } + + /** + * Cancel cell deletion + */ + public function cancelCellDeletion() + { + $this->ctrl->redirect($this, "edit"); + } + + /** + * Delete Cells + */ + public function deleteCells() + { + $ilCtrl = $this->ctrl; + + if (is_array($_POST["tid"])) { + foreach ($_POST["tid"] as $tid) { + $ids = explode(":", $tid); + $this->content_obj->deleteGridCell($ids[0], $ids[1]); + } + } + $this->updated = $this->pg_obj->update(); + + $ilCtrl->redirect($this, "edit"); + } + + + /** + * Set tabs + */ + public function setTabs() + { + $this->tabs->setBackTarget( + $this->lng->txt("pg"), + $this->ctrl->getParentReturn($this) + ); + + $this->tabs->addTab( + "settings", + $this->lng->txt("settings"), + $this->ctrl->getLinkTarget($this, "edit") + ); + } + + /** + * Save tabs properties in db and return to page edit screen + */ + public function saveCellData() + { + $width_s = ilUtil::stripSlashesArray($_POST["width_s"]); + $width_m = ilUtil::stripSlashesArray($_POST["width_m"]); + $width_l = ilUtil::stripSlashesArray($_POST["width_l"]); + $width_xl = ilUtil::stripSlashesArray($_POST["width_xl"]); + $this->content_obj->saveWidths($width_s, $width_m, $width_l, $width_xl); + + if (is_array($_POST["position"])) { + $positions = ilUtil::stripSlashesArray($_POST["position"]); + $this->content_obj->savePositions($positions); + } + $this->updated = $this->pg_obj->update(); + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "edit"); + } } -?> \ No newline at end of file diff --git a/Services/COPage/classes/class.ilPCIIMOverlaysTableGUI.php b/Services/COPage/classes/class.ilPCIIMOverlaysTableGUI.php index 212a8f70e1bac06d3ebe191b9b563672940bd212..600c73eb6cf134615547b07e9bfcd66d107d71e5 100644 --- a/Services/COPage/classes/class.ilPCIIMOverlaysTableGUI.php +++ b/Services/COPage/classes/class.ilPCIIMOverlaysTableGUI.php @@ -14,84 +14,83 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilPCIIMOverlaysTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_mob) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_mob) + { + 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(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->mob = $a_mob; - $this->setData($this->getOverlays()); - $this->setTitle($lng->txt("cont_overlay_images")); - - $this->addColumn("", "", "1", true); - $this->addColumn($this->lng->txt("thumbnail"), "", "20px"); - $this->addColumn($this->lng->txt("filename")); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.iim_overlays_row.html", "Services/COPage"); + $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); + $this->mob = $a_mob; + $this->setData($this->getOverlays()); + $this->setTitle($lng->txt("cont_overlay_images")); + + $this->addColumn("", "", "1", true); + $this->addColumn($this->lng->txt("thumbnail"), "", "20px"); + $this->addColumn($this->lng->txt("filename")); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.iim_overlays_row.html", "Services/COPage"); - $this->addMultiCommand("confirmDeleteOverlays", $lng->txt("delete")); - } - - /** - * Get overlays - * - * @return array array of overlays - */ - function getOverlays() - { - $ov = array(); - $files = $this->mob->getFilesOfDirectory("overlays"); - foreach ($files as $f) - { - $ov[] = array("filename" => $f); - } - return $ov; - } - - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - - $this->tpl->setVariable("FILENAME", $a_set["filename"]); - $piname = pathinfo($a_set["filename"]); - $th_path = ilObjMediaObject::getThumbnailPath($this->mob->getId(), - basename($a_set["filename"], ".".$piname['extension']).".png"); - if (!is_file($th_path)) - { - $this->mob->makeThumbnail("overlays/".$a_set["filename"], - basename($a_set["filename"], ".".$piname['extension']).".png"); - } - if (is_file($th_path)) - { - $this->tpl->setVariable("THUMB", ilUtil::img($th_path)); - } - } + $this->addMultiCommand("confirmDeleteOverlays", $lng->txt("delete")); + } + + /** + * Get overlays + * + * @return array array of overlays + */ + public function getOverlays() + { + $ov = array(); + $files = $this->mob->getFilesOfDirectory("overlays"); + foreach ($files as $f) { + $ov[] = array("filename" => $f); + } + return $ov; + } + + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $this->tpl->setVariable("FILENAME", $a_set["filename"]); + $piname = pathinfo($a_set["filename"]); + $th_path = ilObjMediaObject::getThumbnailPath( + $this->mob->getId(), + basename($a_set["filename"], "." . $piname['extension']) . ".png" + ); + if (!is_file($th_path)) { + $this->mob->makeThumbnail( + "overlays/" . $a_set["filename"], + basename($a_set["filename"], "." . $piname['extension']) . ".png" + ); + } + if (is_file($th_path)) { + $this->tpl->setVariable("THUMB", ilUtil::img($th_path)); + } + } } -?> diff --git a/Services/COPage/classes/class.ilPCIIMPopupTableGUI.php b/Services/COPage/classes/class.ilPCIIMPopupTableGUI.php index 389ed241f625b483de6c30b5ef56a8f12ed533f5..c32c976fba2bd44341507231271f0f87a49ebcb5 100755 --- a/Services/COPage/classes/class.ilPCIIMPopupTableGUI.php +++ b/Services/COPage/classes/class.ilPCIIMPopupTableGUI.php @@ -13,53 +13,53 @@ include_once("Services/Table/classes/class.ilTable2GUI.php"); */ class ilPCIIMPopupTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_content_obj) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_content_obj) + { + 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->addColumn("", "", "1"); - $this->addColumn($lng->txt("title"), "", "100%"); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.iim_popup_content_row.html", - "Services/COPage"); - - $this->content_obj = $a_content_obj; - $this->setData($this->content_obj->getPopups()); - $this->setLimit(0); - - $this->addMultiCommand("confirmPopupDeletion", $lng->txt("delete")); - $this->addCommandButton("savePopups", $lng->txt("cont_save_all_titles")); - - $this->setTitle($lng->txt("cont_content_popups")); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->tpl->setVariable("TID", $a_set["hier_id"].":".$a_set["pc_id"]); - $this->tpl->setVariable("TITLE", ilUtil::prepareFormOutput($a_set["title"])); - } + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->addColumn("", "", "1"); + $this->addColumn($lng->txt("title"), "", "100%"); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate( + "tpl.iim_popup_content_row.html", + "Services/COPage" + ); + + $this->content_obj = $a_content_obj; + $this->setData($this->content_obj->getPopups()); + $this->setLimit(0); + + $this->addMultiCommand("confirmPopupDeletion", $lng->txt("delete")); + $this->addCommandButton("savePopups", $lng->txt("cont_save_all_titles")); + + $this->setTitle($lng->txt("cont_content_popups")); + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $this->tpl->setVariable("TID", $a_set["hier_id"] . ":" . $a_set["pc_id"]); + $this->tpl->setVariable("TITLE", ilUtil::prepareFormOutput($a_set["title"])); + } } -?> \ No newline at end of file diff --git a/Services/COPage/classes/class.ilPCIIMTriggerEditorGUI.php b/Services/COPage/classes/class.ilPCIIMTriggerEditorGUI.php index c12437d6054981f2c3d97dc688b11001dbc4cc41..9c1d65993a868ad58b5d75d7efedf29db753cee2 100755 --- a/Services/COPage/classes/class.ilPCIIMTriggerEditorGUI.php +++ b/Services/COPage/classes/class.ilPCIIMTriggerEditorGUI.php @@ -16,335 +16,329 @@ include_once("./Services/COPage/classes/class.ilPCImageMapEditorGUI.php"); */ class ilPCIIMTriggerEditorGUI extends ilPCImageMapEditorGUI { - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilTemplate + */ + protected $tpl; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilToolbarGUI - */ - protected $toolbar; + /** + * @var ilToolbarGUI + */ + protected $toolbar; - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * Constructor - */ - function __construct($a_content_obj, $a_page) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_content_obj, $a_page) + { + global $DIC; - $this->tpl = $DIC["tpl"]; - $this->lng = $DIC->language(); - $this->toolbar = $DIC->toolbar(); - $this->ctrl = $DIC->ctrl(); - $tpl = $DIC["tpl"]; - - include_once("./Services/jQuery/classes/class.iljQueryUtil.php"); - iljQueryUtil::initjQueryUI(); + $this->tpl = $DIC["tpl"]; + $this->lng = $DIC->language(); + $this->toolbar = $DIC->toolbar(); + $this->ctrl = $DIC->ctrl(); + $tpl = $DIC["tpl"]; + + include_once("./Services/jQuery/classes/class.iljQueryUtil.php"); + iljQueryUtil::initjQueryUI(); - $tpl->addJavascript("./Services/COPage/js/ilCOPagePres.js"); - $tpl->addJavascript("./Services/COPage/js/ilCOPagePCInteractiveImage.js"); + $tpl->addJavascript("./Services/COPage/js/ilCOPagePres.js"); + $tpl->addJavascript("./Services/COPage/js/ilCOPagePCInteractiveImage.js"); - include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); - ilAccordionGUI::addJavaScript(); - ilAccordionGUI::addCss(); + include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); + ilAccordionGUI::addJavaScript(); + ilAccordionGUI::addCss(); - parent::__construct($a_content_obj, $a_page); - } - - /** - * Get parent node name - * - * @return string name of parent node - */ - function getParentNodeName() - { - return "InteractiveImage"; - } + parent::__construct($a_content_obj, $a_page); + } + + /** + * Get parent node name + * + * @return string name of parent node + */ + public function getParentNodeName() + { + return "InteractiveImage"; + } - /** - * Get editor title - * - * @return string editor title - */ - function getEditorTitle() - { - $lng = $this->lng; - - return $lng->txt("cont_pc_iim"); - } + /** + * Get editor title + * + * @return string editor title + */ + public function getEditorTitle() + { + $lng = $this->lng; + + return $lng->txt("cont_pc_iim"); + } - /** - * Get trigger table - */ - function getImageMapTableHTML() - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - + /** + * Get trigger table + */ + public function getImageMapTableHTML() + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + - $ilToolbar->addText($lng->txt("cont_drag_element_click_save")); - $ilToolbar->setId("drag_toolbar"); - $ilToolbar->setHidden(true); - $ilToolbar->addButton($lng->txt("save"),"#", "", "", "", "save_pos_button"); - - $ilToolbar->addButton($lng->txt("cancel"), - $ilCtrl->getLinkTarget($this, "editMapAreas")); - - include_once("./Services/COPage/classes/class.ilPCIIMTriggerTableGUI.php"); - $image_map_table = new ilPCIIMTriggerTableGUI($this, "editMapAreas", $this->content_obj, - $this->getParentNodeName()); - return $image_map_table->getHTML(); - } + $ilToolbar->addText($lng->txt("cont_drag_element_click_save")); + $ilToolbar->setId("drag_toolbar"); + $ilToolbar->setHidden(true); + $ilToolbar->addButton($lng->txt("save"), "#", "", "", "", "save_pos_button"); + + $ilToolbar->addButton( + $lng->txt("cancel"), + $ilCtrl->getLinkTarget($this, "editMapAreas") + ); + + include_once("./Services/COPage/classes/class.ilPCIIMTriggerTableGUI.php"); + $image_map_table = new ilPCIIMTriggerTableGUI( + $this, + "editMapAreas", + $this->content_obj, + $this->getParentNodeName() + ); + return $image_map_table->getHTML(); + } - /** - * Get toolbar - * - * @return object toolbar - */ - function getToolbar() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - // toolbar - $tb = new ilToolbarGUI(); - $tb->setFormAction($ilCtrl->getFormAction($this)); - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $options = array( - "Rect" => $lng->txt("cont_Rect"), - "Circle" => $lng->txt("cont_Circle"), - "Poly" => $lng->txt("cont_Poly"), - "Marker" => $lng->txt("cont_marker") - ); - $si = new ilSelectInputGUI($lng->txt("cont_trigger_area"), "shape"); - $si->setOptions($options); - $tb->addInputItem($si, true); - $tb->addFormButton($lng->txt("add"), "addNewArea"); - - return $tb; - } + /** + * Get toolbar + * + * @return object toolbar + */ + public function getToolbar() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + // toolbar + $tb = new ilToolbarGUI(); + $tb->setFormAction($ilCtrl->getFormAction($this)); + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $options = array( + "Rect" => $lng->txt("cont_Rect"), + "Circle" => $lng->txt("cont_Circle"), + "Poly" => $lng->txt("cont_Poly"), + "Marker" => $lng->txt("cont_marker") + ); + $si = new ilSelectInputGUI($lng->txt("cont_trigger_area"), "shape"); + $si->setOptions($options); + $tb->addInputItem($si, true); + $tb->addFormButton($lng->txt("add"), "addNewArea"); + + return $tb; + } - /** - * Add new area - * - * @param - * @return - */ - function addNewArea() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if ($_POST["shape"] == "Marker") - { - $this->content_obj->addTriggerMarker(); - $this->updated = $this->page->update(); - ilUtil::sendSuccess($lng->txt("cont_saved_map_data"), true); - $ilCtrl->redirect($this, "editMapAreas"); - } - else - { - return parent::addNewArea(); - } - } - - /** - * Init area editing form. - * - * @param int $a_mode Edit Mode - */ - public function initAreaEditingForm($a_edit_property) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; + /** + * Add new area + * + * @param + * @return + */ + public function addNewArea() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if ($_POST["shape"] == "Marker") { + $this->content_obj->addTriggerMarker(); + $this->updated = $this->page->update(); + ilUtil::sendSuccess($lng->txt("cont_saved_map_data"), true); + $ilCtrl->redirect($this, "editMapAreas"); + } else { + return parent::addNewArea(); + } + } + + /** + * Init area editing form. + * + * @param int $a_mode Edit Mode + */ + public function initAreaEditingForm($a_edit_property) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setOpenTag(false); - $form->setCloseTag(false); + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setOpenTag(false); + $form->setCloseTag(false); - // name - if ($a_edit_property != "link" && $a_edit_property != "shape") - { - $ti = new ilTextInputGUI($lng->txt("cont_name"), "area_name"); - $ti->setMaxLength(200); - $ti->setSize(20); - //$ti->setRequired(true); - $form->addItem($ti); - } - - // save and cancel commands - if ($a_edit_property == "") - { - $form->setTitle($lng->txt("cont_new_trigger_area")); - $form->addCommandButton("saveArea", $lng->txt("save")); - } - else - { - $form->setTitle($lng->txt("cont_new_area")); - $form->addCommandButton("saveArea", $lng->txt("save")); - } - - return $form; - } + // name + if ($a_edit_property != "link" && $a_edit_property != "shape") { + $ti = new ilTextInputGUI($lng->txt("cont_name"), "area_name"); + $ti->setMaxLength(200); + $ti->setSize(20); + //$ti->setRequired(true); + $form->addItem($ti); + } + + // save and cancel commands + if ($a_edit_property == "") { + $form->setTitle($lng->txt("cont_new_trigger_area")); + $form->addCommandButton("saveArea", $lng->txt("save")); + } else { + $form->setTitle($lng->txt("cont_new_area")); + $form->addCommandButton("saveArea", $lng->txt("save")); + } + + return $form; + } - /** - * Save new or updated map area - */ - function saveArea() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - switch ($_SESSION["il_map_edit_mode"]) - { - // save edited shape - case "edit_shape": - $this->std_alias_item->setShape($_SESSION["il_map_area_nr"], - $_SESSION["il_map_edit_area_type"], $_SESSION["il_map_edit_coords"]); - $this->updated = $this->page->update(); - break; + /** + * Save new or updated map area + */ + public function saveArea() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + switch ($_SESSION["il_map_edit_mode"]) { + // save edited shape + case "edit_shape": + $this->std_alias_item->setShape( + $_SESSION["il_map_area_nr"], + $_SESSION["il_map_edit_area_type"], + $_SESSION["il_map_edit_coords"] + ); + $this->updated = $this->page->update(); + break; - // save new area - default: - $area_type = $_SESSION["il_map_edit_area_type"]; - $coords = $_SESSION["il_map_edit_coords"]; - $this->content_obj->addTriggerArea($this->std_alias_item, - $area_type, $coords, - ilUtil::stripSlashes($_POST["area_name"]), $link); - $this->updated = $this->page->update(); - break; - } + // save new area + default: + $area_type = $_SESSION["il_map_edit_area_type"]; + $coords = $_SESSION["il_map_edit_coords"]; + $this->content_obj->addTriggerArea( + $this->std_alias_item, + $area_type, + $coords, + ilUtil::stripSlashes($_POST["area_name"]), + $link + ); + $this->updated = $this->page->update(); + break; + } - //$this->initMapParameters(); - ilUtil::sendSuccess($lng->txt("cont_saved_map_area"), true); - $ilCtrl->redirect($this, "editMapAreas"); - } - - /** - * Update trigger - */ - function updateTrigger() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->content_obj->setTriggerOverlays($_POST["ov"]); - $this->content_obj->setTriggerPopups($_POST["pop"]); - $this->content_obj->setTriggerOverlayPositions($_POST["ovpos"]); - $this->content_obj->setTriggerMarkerPositions($_POST["markpos"]); - $this->content_obj->setTriggerPopupPositions($_POST["poppos"]); - $this->content_obj->setTriggerPopupSize($_POST["popsize"]); - $this->content_obj->setTriggerTitles($_POST["title"]); - $this->updated = $this->page->update(); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "editMapAreas"); - } - - /** - * Confirm trigger deletion - */ - function confirmDeleteTrigger() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - if (!is_array($_POST["tr"]) || count($_POST["tr"]) == 0) - { - ilUtil::sendFailure($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "editMapAreas"); - } - else - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("cont_really_delete_triggers")); - $cgui->setCancel($lng->txt("cancel"), "editMapAreas"); - $cgui->setConfirm($lng->txt("delete"), "deleteTrigger"); - - foreach ($_POST["tr"] as $i) - { - $cgui->addItem("tr[]", $i, $_POST["title"][$i]); - } - - $tpl->setContent($cgui->getHTML()); - } - } + //$this->initMapParameters(); + ilUtil::sendSuccess($lng->txt("cont_saved_map_area"), true); + $ilCtrl->redirect($this, "editMapAreas"); + } + + /** + * Update trigger + */ + public function updateTrigger() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $this->content_obj->setTriggerOverlays($_POST["ov"]); + $this->content_obj->setTriggerPopups($_POST["pop"]); + $this->content_obj->setTriggerOverlayPositions($_POST["ovpos"]); + $this->content_obj->setTriggerMarkerPositions($_POST["markpos"]); + $this->content_obj->setTriggerPopupPositions($_POST["poppos"]); + $this->content_obj->setTriggerPopupSize($_POST["popsize"]); + $this->content_obj->setTriggerTitles($_POST["title"]); + $this->updated = $this->page->update(); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "editMapAreas"); + } + + /** + * Confirm trigger deletion + */ + public function confirmDeleteTrigger() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + if (!is_array($_POST["tr"]) || count($_POST["tr"]) == 0) { + ilUtil::sendFailure($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "editMapAreas"); + } else { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("cont_really_delete_triggers")); + $cgui->setCancel($lng->txt("cancel"), "editMapAreas"); + $cgui->setConfirm($lng->txt("delete"), "deleteTrigger"); + + foreach ($_POST["tr"] as $i) { + $cgui->addItem("tr[]", $i, $_POST["title"][$i]); + } + + $tpl->setContent($cgui->getHTML()); + } + } - /** - * Delete trigger - */ - function deleteTrigger() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if (is_array($_POST["tr"]) && count($_POST["tr"]) > 0) - { - foreach ($_POST["tr"] as $tr_nr) - { - $this->content_obj->deleteTrigger($this->std_alias_item, $tr_nr); - } - $this->updated = $this->page->update(); - ilUtil::sendSuccess($lng->txt("cont_areas_deleted"), true); - } + /** + * Delete trigger + */ + public function deleteTrigger() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if (is_array($_POST["tr"]) && count($_POST["tr"]) > 0) { + foreach ($_POST["tr"] as $tr_nr) { + $this->content_obj->deleteTrigger($this->std_alias_item, $tr_nr); + } + $this->updated = $this->page->update(); + ilUtil::sendSuccess($lng->txt("cont_areas_deleted"), true); + } - $ilCtrl->redirect($this, "editMapAreas"); - } + $ilCtrl->redirect($this, "editMapAreas"); + } - /** - * Get additional page xml (to be overwritten) - * - * @return string additional page xml - */ - function getAdditionalPageXML() - { - return $this->page->getMultimediaXML(); - } - - /** - * Output post processing - * - * @param - * @return - */ - function outputPostProcessing($a_output) - { - - // for question html get the page gui object - include_once("./Services/COPage/classes/class.ilPageObjectGUI.php"); - $pg_gui = new ilPageObjectGUI($this->page->getParentType(), $this->page->getId()); - $pg_gui->setOutputMode(IL_PAGE_PREVIEW); - $pg_gui->getPageConfig()->setEnableSelfAssessment(true); -// $pg_gui->initSelfAssessmentRendering(true); // todo: solve in other way - $qhtml = $pg_gui->getQuestionHTML(); - if (is_array($qhtml)) - { - foreach ($qhtml as $k => $h) - { - $a_output = str_replace($pg_gui->pl_start."Question;il__qst_$k".$pg_gui->pl_end, " ".$h, $a_output); - } - } -// $a_output = $pg_gui->selfAssessmentRendering($a_output); - - return $a_output; - } + /** + * Get additional page xml (to be overwritten) + * + * @return string additional page xml + */ + public function getAdditionalPageXML() + { + return $this->page->getMultimediaXML(); + } + + /** + * Output post processing + * + * @param + * @return + */ + public function outputPostProcessing($a_output) + { + // for question html get the page gui object + include_once("./Services/COPage/classes/class.ilPageObjectGUI.php"); + $pg_gui = new ilPageObjectGUI($this->page->getParentType(), $this->page->getId()); + $pg_gui->setOutputMode(IL_PAGE_PREVIEW); + $pg_gui->getPageConfig()->setEnableSelfAssessment(true); + // $pg_gui->initSelfAssessmentRendering(true); // todo: solve in other way + $qhtml = $pg_gui->getQuestionHTML(); + if (is_array($qhtml)) { + foreach ($qhtml as $k => $h) { + $a_output = str_replace($pg_gui->pl_start . "Question;il__qst_$k" . $pg_gui->pl_end, " " . $h, $a_output); + } + } + // $a_output = $pg_gui->selfAssessmentRendering($a_output); + return $a_output; + } } -?> \ No newline at end of file diff --git a/Services/COPage/classes/class.ilPCIIMTriggerTableGUI.php b/Services/COPage/classes/class.ilPCIIMTriggerTableGUI.php index c7e5207fce59f299c331d92bee95376f80dcf56e..840f85c2e08ace220b3e953e2a2ff0b6ea120dd0 100755 --- a/Services/COPage/classes/class.ilPCIIMTriggerTableGUI.php +++ b/Services/COPage/classes/class.ilPCIIMTriggerTableGUI.php @@ -15,193 +15,195 @@ include_once("Services/MediaObjects/classes/class.ilImageMapTableGUI.php"); */ class ilPCIIMTriggerTableGUI extends ilImageMapTableGUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_pc_media_object, - $a_parent_node_name) - { - global $DIC; + + /** + * Constructor + */ + public function __construct( + $a_parent_obj, + $a_parent_cmd, + $a_pc_media_object, + $a_parent_node_name + ) { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $lng = $DIC->language(); - - $this->setId("cont_iim_tr"); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $lng = $DIC->language(); + + $this->setId("cont_iim_tr"); - $this->parent_node_name = $a_parent_node_name; - $this->pc_media_object = $a_pc_media_object; - $this->mob = $this->pc_media_object->getMediaObject(); - - $this->areas = array(); - foreach ($this->pc_media_object->getStandardAliasItem()->getMapAreas() as $a) - { - $this->area[$a["Id"]] = $a; - } + $this->parent_node_name = $a_parent_node_name; + $this->pc_media_object = $a_pc_media_object; + $this->mob = $this->pc_media_object->getMediaObject(); + + $this->areas = array(); + foreach ($this->pc_media_object->getStandardAliasItem()->getMapAreas() as $a) { + $this->area[$a["Id"]] = $a; + } - $this->ov_files = $this->mob->getFilesOfDirectory("overlays"); - $this->ov_options = array("" => $lng->txt("please_select")); - foreach ($this->ov_files as $of) - { - $this->ov_options[$of] = $of; - } - $this->popups = $this->pc_media_object->getPopups(); - $this->pop_options = array("" => $lng->txt("please_select")); - foreach ($this->popups as $k => $p) - { - $this->pop_options[$p["nr"]] = $p["title"]; - } - parent::__construct($a_parent_obj, $a_parent_cmd, $a_pc_media_object->getMediaObject()); - $this->setRowTemplate("tpl.iim_trigger_row.html", "Services/COPage"); - } - - /** - * Init columns - */ - function initColumns() - { - $this->addColumn("", "", "1"); // checkbox - $this->addColumn($this->lng->txt("title"), "Title", ""); - $this->addColumn($this->lng->txt("type"), "", ""); - $this->addColumn($this->lng->txt("cont_coords"), "", ""); - $this->addColumn($this->lng->txt("cont_overlay_image"), "", ""); - $this->addColumn($this->lng->txt("cont_content_popup"), "", ""); - $this->addColumn($this->lng->txt("actions"), "", ""); - } + $this->ov_files = $this->mob->getFilesOfDirectory("overlays"); + $this->ov_options = array("" => $lng->txt("please_select")); + foreach ($this->ov_files as $of) { + $this->ov_options[$of] = $of; + } + $this->popups = $this->pc_media_object->getPopups(); + $this->pop_options = array("" => $lng->txt("please_select")); + foreach ($this->popups as $k => $p) { + $this->pop_options[$p["nr"]] = $p["title"]; + } + parent::__construct($a_parent_obj, $a_parent_cmd, $a_pc_media_object->getMediaObject()); + $this->setRowTemplate("tpl.iim_trigger_row.html", "Services/COPage"); + } + + /** + * Init columns + */ + public function initColumns() + { + $this->addColumn("", "", "1"); // checkbox + $this->addColumn($this->lng->txt("title"), "Title", ""); + $this->addColumn($this->lng->txt("type"), "", ""); + $this->addColumn($this->lng->txt("cont_coords"), "", ""); + $this->addColumn($this->lng->txt("cont_overlay_image"), "", ""); + $this->addColumn($this->lng->txt("cont_content_popup"), "", ""); + $this->addColumn($this->lng->txt("actions"), "", ""); + } - /** - * Init actions - */ - function initActions() - { - $lng = $this->lng; - - // action commands - $this->addMultiCommand("confirmDeleteTrigger", $lng->txt("delete")); - - $data = $this->getData(); - if (count($data) > 0) - { - $this->addCommandButton("updateTrigger", $lng->txt("save"), "", "update_tr_button"); - } - } + /** + * Init actions + */ + public function initActions() + { + $lng = $this->lng; + + // action commands + $this->addMultiCommand("confirmDeleteTrigger", $lng->txt("delete")); + + $data = $this->getData(); + if (count($data) > 0) { + $this->addCommandButton("updateTrigger", $lng->txt("save"), "", "update_tr_button"); + } + } - /** - * Get items of current folder - */ - function getItems() - { - $triggers = $this->pc_media_object->getTriggers(); - - $triggers = ilUtil::sortArray($triggers, "Title", "asc", false, true); - $this->setData($triggers); - } - - /** - * Standard Version of Fill Row. Most likely to - * be overwritten by derived class. - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; -//var_dump($a_set); + /** + * Get items of current folder + */ + public function getItems() + { + $triggers = $this->pc_media_object->getTriggers(); + + $triggers = ilUtil::sortArray($triggers, "Title", "asc", false, true); + $this->setData($triggers); + } + + /** + * Standard Version of Fill Row. Most likely to + * be overwritten by derived class. + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + //var_dump($a_set); - $i = $a_set["Nr"]; + $i = $a_set["Nr"]; - // command: edit marker position - if ($a_set["Overlay"] != "") - { - $this->tpl->setCurrentBlock("cmd"); - $this->tpl->setVariable("CMD_ID", "ov_".$i); - $this->tpl->setVariable("HREF_CMD", "#"); - $this->tpl->setVariable("CMD_CLASS", "ov_cmd"); - $this->tpl->setVariable("TXT_CMD", $lng->txt("cont_edit_overlay_position")); - $this->tpl->parseCurrentBlock(); - } - - // command: edit marker position - if ($a_set["PopupNr"] != "") - { - $this->tpl->setCurrentBlock("cmd"); - $this->tpl->setVariable("CMD_ID", "pop_".$i); - $this->tpl->setVariable("HREF_CMD", "#"); - $this->tpl->setVariable("CMD_CLASS", "pop_cmd"); - $this->tpl->setVariable("TXT_CMD", $lng->txt("cont_edit_popup_position")); - $this->tpl->parseCurrentBlock(); - } - - if ($a_set["Type"] == ilPCInteractiveImage::AREA) - { - $this->tpl->setCurrentBlock("coords"); - $this->tpl->setVariable("VAL_COORDS", - implode(explode(",", $this->area[$a_set["Nr"]]["Coords"]), ", ")); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setVariable("TYPE", - $lng->txt("cont_".$this->area[$a_set["Nr"]]["Shape"])); - } - else - { - // command: edit marker position - $this->tpl->setCurrentBlock("cmd"); - $this->tpl->setVariable("CMD_ID", "mark_".$i); - $this->tpl->setVariable("HREF_CMD", "#"); - $this->tpl->setVariable("CMD_CLASS", "mark_cmd"); - $this->tpl->setVariable("TXT_CMD", $lng->txt("cont_edit_marker_position")); - $this->tpl->parseCurrentBlock(); - - // marker position - $this->tpl->setCurrentBlock("marker_pos"); - $this->tpl->setVariable("VAR_MARK_POS", "markpos[".$i."]"); - $this->tpl->setVariable("ID_MARK_POS", "markpos_".$i); - $this->tpl->setVariable("VAL_MARK_POS", $a_set["MarkerX"].",".$a_set["MarkerY"]); - $this->tpl->setVariable("TXT_MLEFT", $lng->txt("cont_left")); - $this->tpl->setVariable("TXT_MTOP", $lng->txt("cont_top")); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setVariable("TYPE", $lng->txt("cont_marker")); - } - - $this->tpl->setVariable("CHECKBOX", - ilUtil::formCheckBox("", "tr[]", $i)); - $this->tpl->setVariable("VAR_NAME", "title[".$i."]"); - $this->tpl->setVariable("VAL_NAME", $a_set["Title"]); - - - $this->tpl->setVariable("VAR_POS", "ovpos[".$i."]"); - $this->tpl->setVariable("ID_OV_POS", "ovpos_".$i); - $this->tpl->setVariable("ID_POP_POS", "poppos_".$i); - $this->tpl->setVariable("VAR_POP_POS", "poppos[".$i."]"); - $this->tpl->setVariable("VAR_POP_SIZE", "popsize[".$i."]"); - $this->tpl->setVariable("VAL_POS", $a_set["OverlayX"].",".$a_set["OverlayY"]); - $this->tpl->setVariable("VAL_POP_POS", $a_set["PopupX"].",".$a_set["PopupY"]); - $this->tpl->setVariable("VAL_POP_SIZE", $a_set["PopupWidth"].",".$a_set["PopupHeight"]); - $this->tpl->setVariable("TXT_IMG", $lng->txt("image")); - $this->tpl->setVariable("TXT_TITLE", $lng->txt("title")); - $this->tpl->setVariable("TXT_LEFT", $lng->txt("cont_left")); - $this->tpl->setVariable("TXT_TOP", $lng->txt("cont_top")); - $this->tpl->setVariable("TXT_WIDTH", $lng->txt("cont_width")); - $this->tpl->setVariable("TXT_HEIGHT", $lng->txt("cont_height")); - $this->tpl->setVariable("OVERLAY_IMAGE", - ilUtil::formSelect($a_set["Overlay"], "ov[".$i."]", $this->ov_options, false, true)); - $this->tpl->setVariable("CONTENT_POPUP", - ilUtil::formSelect($a_set["PopupNr"], "pop[".$i."]", $this->pop_options, false, true)); - } + // command: edit marker position + if ($a_set["Overlay"] != "") { + $this->tpl->setCurrentBlock("cmd"); + $this->tpl->setVariable("CMD_ID", "ov_" . $i); + $this->tpl->setVariable("HREF_CMD", "#"); + $this->tpl->setVariable("CMD_CLASS", "ov_cmd"); + $this->tpl->setVariable("TXT_CMD", $lng->txt("cont_edit_overlay_position")); + $this->tpl->parseCurrentBlock(); + } + + // command: edit marker position + if ($a_set["PopupNr"] != "") { + $this->tpl->setCurrentBlock("cmd"); + $this->tpl->setVariable("CMD_ID", "pop_" . $i); + $this->tpl->setVariable("HREF_CMD", "#"); + $this->tpl->setVariable("CMD_CLASS", "pop_cmd"); + $this->tpl->setVariable("TXT_CMD", $lng->txt("cont_edit_popup_position")); + $this->tpl->parseCurrentBlock(); + } + + if ($a_set["Type"] == ilPCInteractiveImage::AREA) { + $this->tpl->setCurrentBlock("coords"); + $this->tpl->setVariable( + "VAL_COORDS", + implode(explode(",", $this->area[$a_set["Nr"]]["Coords"]), ", ") + ); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setVariable( + "TYPE", + $lng->txt("cont_" . $this->area[$a_set["Nr"]]["Shape"]) + ); + } else { + // command: edit marker position + $this->tpl->setCurrentBlock("cmd"); + $this->tpl->setVariable("CMD_ID", "mark_" . $i); + $this->tpl->setVariable("HREF_CMD", "#"); + $this->tpl->setVariable("CMD_CLASS", "mark_cmd"); + $this->tpl->setVariable("TXT_CMD", $lng->txt("cont_edit_marker_position")); + $this->tpl->parseCurrentBlock(); + + // marker position + $this->tpl->setCurrentBlock("marker_pos"); + $this->tpl->setVariable("VAR_MARK_POS", "markpos[" . $i . "]"); + $this->tpl->setVariable("ID_MARK_POS", "markpos_" . $i); + $this->tpl->setVariable("VAL_MARK_POS", $a_set["MarkerX"] . "," . $a_set["MarkerY"]); + $this->tpl->setVariable("TXT_MLEFT", $lng->txt("cont_left")); + $this->tpl->setVariable("TXT_MTOP", $lng->txt("cont_top")); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setVariable("TYPE", $lng->txt("cont_marker")); + } + $this->tpl->setVariable( + "CHECKBOX", + ilUtil::formCheckBox("", "tr[]", $i) + ); + $this->tpl->setVariable("VAR_NAME", "title[" . $i . "]"); + $this->tpl->setVariable("VAL_NAME", $a_set["Title"]); + + + $this->tpl->setVariable("VAR_POS", "ovpos[" . $i . "]"); + $this->tpl->setVariable("ID_OV_POS", "ovpos_" . $i); + $this->tpl->setVariable("ID_POP_POS", "poppos_" . $i); + $this->tpl->setVariable("VAR_POP_POS", "poppos[" . $i . "]"); + $this->tpl->setVariable("VAR_POP_SIZE", "popsize[" . $i . "]"); + $this->tpl->setVariable("VAL_POS", $a_set["OverlayX"] . "," . $a_set["OverlayY"]); + $this->tpl->setVariable("VAL_POP_POS", $a_set["PopupX"] . "," . $a_set["PopupY"]); + $this->tpl->setVariable("VAL_POP_SIZE", $a_set["PopupWidth"] . "," . $a_set["PopupHeight"]); + $this->tpl->setVariable("TXT_IMG", $lng->txt("image")); + $this->tpl->setVariable("TXT_TITLE", $lng->txt("title")); + $this->tpl->setVariable("TXT_LEFT", $lng->txt("cont_left")); + $this->tpl->setVariable("TXT_TOP", $lng->txt("cont_top")); + $this->tpl->setVariable("TXT_WIDTH", $lng->txt("cont_width")); + $this->tpl->setVariable("TXT_HEIGHT", $lng->txt("cont_height")); + $this->tpl->setVariable( + "OVERLAY_IMAGE", + ilUtil::formSelect($a_set["Overlay"], "ov[" . $i . "]", $this->ov_options, false, true) + ); + $this->tpl->setVariable( + "CONTENT_POPUP", + ilUtil::formSelect($a_set["PopupNr"], "pop[" . $i . "]", $this->pop_options, false, true) + ); + } } -?> diff --git a/Services/COPage/classes/class.ilPCImageMapEditorGUI.php b/Services/COPage/classes/class.ilPCImageMapEditorGUI.php index 2bbcd03d5f0280387df2bbf06ac28062128d7edb..52e7879b03aa0e00c202439932efe3fbf1991ae2 100755 --- a/Services/COPage/classes/class.ilPCImageMapEditorGUI.php +++ b/Services/COPage/classes/class.ilPCImageMapEditorGUI.php @@ -16,284 +16,317 @@ include_once("./Services/MediaObjects/classes/class.ilImageMapEditorGUI.php"); */ class ilPCImageMapEditorGUI extends ilImageMapEditorGUI { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * Constructor - */ - function __construct($a_content_obj, $a_page) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_content_obj, $a_page) + { + global $DIC; - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $this->content_obj = $a_content_obj; - $this->page = $a_page; - parent::__construct($a_content_obj->getMediaObject()); - - $this->std_alias_item = new ilMediaAliasItem($this->content_obj->dom, - $this->content_obj->hier_id, "Standard", $this->content_obj->getPcId(), - $this->getParentNodeName()); - } - - /** - * Get parent node name - * - * @return string name of parent node - */ - function getParentNodeName() - { - return "MediaObject"; - } + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->content_obj = $a_content_obj; + $this->page = $a_page; + parent::__construct($a_content_obj->getMediaObject()); + + $this->std_alias_item = new ilMediaAliasItem( + $this->content_obj->dom, + $this->content_obj->hier_id, + "Standard", + $this->content_obj->getPcId(), + $this->getParentNodeName() + ); + } + + /** + * Get parent node name + * + * @return string name of parent node + */ + public function getParentNodeName() + { + return "MediaObject"; + } - /** - * Get table HTML - */ - function getImageMapTableHTML() - { - include_once("./Services/COPage/classes/class.ilPCImageMapTableGUI.php"); - $image_map_table = new ilPCImageMapTableGUI($this, "editMapAreas", $this->content_obj, - $this->getParentNodeName()); - return $image_map_table->getHTML(); - } + /** + * Get table HTML + */ + public function getImageMapTableHTML() + { + include_once("./Services/COPage/classes/class.ilPCImageMapTableGUI.php"); + $image_map_table = new ilPCImageMapTableGUI( + $this, + "editMapAreas", + $this->content_obj, + $this->getParentNodeName() + ); + return $image_map_table->getHTML(); + } - /** - * Save new or updated map area - */ - function saveArea() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - switch ($_SESSION["il_map_edit_mode"]) - { - // save edited link - case "edit_link": + /** + * Save new or updated map area + */ + public function saveArea() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + switch ($_SESSION["il_map_edit_mode"]) { + // save edited link + case "edit_link": // $std_alias_item = new ilMediaAliasItem($this->content_obj->dom, // $this->content_obj->hier_id, "Standard", $this->content_obj->getPcId()); - if ($_POST["area_link_type"] == IL_INT_LINK) - { - $this->std_alias_item->setAreaIntLink($_SESSION["il_map_area_nr"], - $_SESSION["il_map_il_type"], $_SESSION["il_map_il_target"], - $_SESSION["il_map_il_targetframe"]); - } - else if ($_POST["area_link_type"] == IL_NO_LINK) - { - $this->std_alias_item->setAreaExtLink($_SESSION["il_map_area_nr"], - ""); - } - else - { - $this->std_alias_item->setAreaExtLink($_SESSION["il_map_area_nr"], - ilUtil::stripSlashes($_POST["area_link_ext"])); - } - $this->updated = $this->page->update(); - break; + if ($_POST["area_link_type"] == IL_INT_LINK) { + $this->std_alias_item->setAreaIntLink( + $_SESSION["il_map_area_nr"], + $_SESSION["il_map_il_type"], + $_SESSION["il_map_il_target"], + $_SESSION["il_map_il_targetframe"] + ); + } elseif ($_POST["area_link_type"] == IL_NO_LINK) { + $this->std_alias_item->setAreaExtLink( + $_SESSION["il_map_area_nr"], + "" + ); + } else { + $this->std_alias_item->setAreaExtLink( + $_SESSION["il_map_area_nr"], + ilUtil::stripSlashes($_POST["area_link_ext"]) + ); + } + $this->updated = $this->page->update(); + break; - // save edited shape - case "edit_shape": + // save edited shape + case "edit_shape": // $std_alias_item = new ilMediaAliasItem($this->content_obj->dom, // $this->content_obj->hier_id, "Standard", $this->content_obj->getPcId()); - $this->std_alias_item->setShape($_SESSION["il_map_area_nr"], - $_SESSION["il_map_edit_area_type"], $_SESSION["il_map_edit_coords"]); - $this->updated = $this->page->update(); - break; + $this->std_alias_item->setShape( + $_SESSION["il_map_area_nr"], + $_SESSION["il_map_edit_area_type"], + $_SESSION["il_map_edit_coords"] + ); + $this->updated = $this->page->update(); + break; - // save new area - default: - $area_type = $_SESSION["il_map_edit_area_type"]; - $coords = $_SESSION["il_map_edit_coords"]; + // save new area + default: + $area_type = $_SESSION["il_map_edit_area_type"]; + $coords = $_SESSION["il_map_edit_coords"]; - switch($_POST["area_link_type"]) - { - case IL_EXT_LINK: - $link = array( - "LinkType" => IL_EXT_LINK, - "Href" => ilUtil::stripSlashes($_POST["area_link_ext"])); - break; + switch ($_POST["area_link_type"]) { + case IL_EXT_LINK: + $link = array( + "LinkType" => IL_EXT_LINK, + "Href" => ilUtil::stripSlashes($_POST["area_link_ext"])); + break; - case IL_NO_LINK: - $link = array( - "LinkType" => IL_EXT_LINK, - "Href" => ""); - break; + case IL_NO_LINK: + $link = array( + "LinkType" => IL_EXT_LINK, + "Href" => ""); + break; - case IL_INT_LINK: - $link = array( - "LinkType" => IL_INT_LINK, - "Type" => $_SESSION["il_map_il_type"], - "Target" => $_SESSION["il_map_il_target"], - "TargetFrame" => $_SESSION["il_map_il_targetframe"]); - break; - } + case IL_INT_LINK: + $link = array( + "LinkType" => IL_INT_LINK, + "Type" => $_SESSION["il_map_il_type"], + "Target" => $_SESSION["il_map_il_target"], + "TargetFrame" => $_SESSION["il_map_il_targetframe"]); + break; + } // $std_alias_item = new ilMediaAliasItem($this->content_obj->dom, // $this->content_obj->hier_id, "Standard", $this->content_obj->getPcId()); - $this->std_alias_item->addMapArea($area_type, $coords, - ilUtil::stripSlashes($_POST["area_name"]), $link); - $this->updated = $this->page->update(); + $this->std_alias_item->addMapArea( + $area_type, + $coords, + ilUtil::stripSlashes($_POST["area_name"]), + $link + ); + $this->updated = $this->page->update(); - break; - } + break; + } - //$this->initMapParameters(); - ilUtil::sendSuccess($lng->txt("cont_saved_map_area"), true); - $ilCtrl->redirect($this, "editMapAreas"); - } + //$this->initMapParameters(); + ilUtil::sendSuccess($lng->txt("cont_saved_map_area"), true); + $ilCtrl->redirect($this, "editMapAreas"); + } - /** - * Delete map areas - */ - function deleteAreas() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if (!isset($_POST["area"])) - { - ilUtil::sendFailure($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "editMapAreas"); - } + /** + * Delete map areas + */ + public function deleteAreas() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if (!isset($_POST["area"])) { + ilUtil::sendFailure($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "editMapAreas"); + } -// $std_alias_item = new ilMediaAliasItem($this->content_obj->dom, -// $this->content_obj->hier_id, "Standard", $this->content_obj->getPcId()); + // $std_alias_item = new ilMediaAliasItem($this->content_obj->dom, + // $this->content_obj->hier_id, "Standard", $this->content_obj->getPcId()); - if (count($_POST["area"]) > 0) - { - $i = 0; - arsort($_POST["area"]); - foreach ($_POST["area"] as $area_nr) - { - $this->std_alias_item->deleteMapArea($area_nr); - } - $this->updated = $this->page->update(); - ilUtil::sendSuccess($lng->txt("cont_areas_deleted"), true); - } + if (count($_POST["area"]) > 0) { + $i = 0; + arsort($_POST["area"]); + foreach ($_POST["area"] as $area_nr) { + $this->std_alias_item->deleteMapArea($area_nr); + } + $this->updated = $this->page->update(); + ilUtil::sendSuccess($lng->txt("cont_areas_deleted"), true); + } - $ilCtrl->redirect($this, "editMapAreas"); - } + $ilCtrl->redirect($this, "editMapAreas"); + } - /** - * Get Link Type of Area - */ - function getLinkTypeOfArea($a_nr) - { -// $std_alias_item = new ilMediaAliasItem($this->content_obj->dom, -// $this->content_obj->hier_id, "Standard", $this->content_obj->getPcId()); - return $this->std_alias_item->getLinkTypeOfArea($a_nr); - } + /** + * Get Link Type of Area + */ + public function getLinkTypeOfArea($a_nr) + { + // $std_alias_item = new ilMediaAliasItem($this->content_obj->dom, + // $this->content_obj->hier_id, "Standard", $this->content_obj->getPcId()); + return $this->std_alias_item->getLinkTypeOfArea($a_nr); + } - /** - * Get Type of Area (only internal link) - */ - function getTypeOfArea($a_nr) - { -// $std_alias_item = new ilMediaAliasItem($this->content_obj->dom, -// $this->content_obj->hier_id, "Standard", $this->content_obj->getPcId()); - return $this->std_alias_item->getTypeOfArea($a_nr); - } + /** + * Get Type of Area (only internal link) + */ + public function getTypeOfArea($a_nr) + { + // $std_alias_item = new ilMediaAliasItem($this->content_obj->dom, + // $this->content_obj->hier_id, "Standard", $this->content_obj->getPcId()); + return $this->std_alias_item->getTypeOfArea($a_nr); + } - /** - * Get Target of Area (only internal link) - */ - function getTargetOfArea($a_nr) - { -// $std_alias_item = new ilMediaAliasItem($this->content_obj->dom, -// $this->content_obj->hier_id, "Standard", $this->content_obj->getPcId()); - return $this->std_alias_item->getTargetOfArea($a_nr); - } + /** + * Get Target of Area (only internal link) + */ + public function getTargetOfArea($a_nr) + { + // $std_alias_item = new ilMediaAliasItem($this->content_obj->dom, + // $this->content_obj->hier_id, "Standard", $this->content_obj->getPcId()); + return $this->std_alias_item->getTargetOfArea($a_nr); + } - /** - * Get TargetFrame of Area (only internal link) - */ - function getTargetFrameOfArea($a_nr) - { -// $std_alias_item = new ilMediaAliasItem($this->content_obj->dom, -// $this->content_obj->hier_id, "Standard", $this->content_obj->getPcId()); - return $this->std_alias_item->getTargetFrameOfArea($a_nr); - } + /** + * Get TargetFrame of Area (only internal link) + */ + public function getTargetFrameOfArea($a_nr) + { + // $std_alias_item = new ilMediaAliasItem($this->content_obj->dom, + // $this->content_obj->hier_id, "Standard", $this->content_obj->getPcId()); + return $this->std_alias_item->getTargetFrameOfArea($a_nr); + } - /** - * Get Href of Area (only external link) - */ - function getHrefOfArea($a_nr) - { -// $std_alias_item = new ilMediaAliasItem($this->content_obj->dom, -// $this->content_obj->hier_id, "Standard", $this->content_obj->getPcId()); - return $this->std_alias_item->getHrefOfArea($a_nr); - } + /** + * Get Href of Area (only external link) + */ + public function getHrefOfArea($a_nr) + { + // $std_alias_item = new ilMediaAliasItem($this->content_obj->dom, + // $this->content_obj->hier_id, "Standard", $this->content_obj->getPcId()); + return $this->std_alias_item->getHrefOfArea($a_nr); + } - /** - * Update map areas - */ - function updateAreas() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - -// $std_alias_item = new ilMediaAliasItem($this->content_obj->dom, -// $this->content_obj->hier_id, "Standard", $this->content_obj->getPcId()); - $areas = $this->std_alias_item->getMapAreas(); - foreach($areas as $area) - { + /** + * Update map areas + */ + public function updateAreas() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + // $std_alias_item = new ilMediaAliasItem($this->content_obj->dom, + // $this->content_obj->hier_id, "Standard", $this->content_obj->getPcId()); + $areas = $this->std_alias_item->getMapAreas(); + foreach ($areas as $area) { // fix #26032 empty values lead to "empty text node" errors on page update - $name = ilUtil::stripSlashes($_POST["name_".$area["Nr"]]); + $name = ilUtil::stripSlashes($_POST["name_" . $area["Nr"]]); if ($name == "") { $name = " "; } - $this->std_alias_item->setAreaTitle($area["Nr"], - $name); - $this->std_alias_item->setAreaHighlightMode($area["Nr"], - ilUtil::stripSlashes($_POST["hl_mode_".$area["Nr"]])); - $this->std_alias_item->setAreaHighlightClass($area["Nr"], - ilUtil::stripSlashes($_POST["hl_class_".$area["Nr"]])); - } - $this->page->update(); - - ilUtil::sendSuccess($lng->txt("cont_saved_map_data"), true); - $ilCtrl->redirect($this, "editMapAreas"); - } - - /** - * Make work file for editing - */ - function makeMapWorkCopy($a_edit_property = "", $a_area_nr = 0, - $a_output_new_area = false, $a_area_type = "", $a_coords = "") - { -// old for pc media object -// $media_object = $this->media_object->getMediaItem("Standard"); - $media_object = $this->content_obj->getMediaObject(); - - // create/update imagemap work copy - $st_item = $media_object->getMediaItem("Standard"); - $st_alias_item = new ilMediaAliasItem($this->content_obj->dom, - $this->content_obj->hier_id, "Standard", $this->content_obj->getPcId(), - $this->getParentNodeName()); + $this->std_alias_item->setAreaTitle( + $area["Nr"], + $name + ); + $this->std_alias_item->setAreaHighlightMode( + $area["Nr"], + ilUtil::stripSlashes($_POST["hl_mode_" . $area["Nr"]]) + ); + $this->std_alias_item->setAreaHighlightClass( + $area["Nr"], + ilUtil::stripSlashes($_POST["hl_class_" . $area["Nr"]]) + ); + } + $this->page->update(); + + ilUtil::sendSuccess($lng->txt("cont_saved_map_data"), true); + $ilCtrl->redirect($this, "editMapAreas"); + } + + /** + * Make work file for editing + */ + public function makeMapWorkCopy( + $a_edit_property = "", + $a_area_nr = 0, + $a_output_new_area = false, + $a_area_type = "", + $a_coords = "" + ) { + // old for pc media object + // $media_object = $this->media_object->getMediaItem("Standard"); + $media_object = $this->content_obj->getMediaObject(); + + // create/update imagemap work copy + $st_item = $media_object->getMediaItem("Standard"); + $st_alias_item = new ilMediaAliasItem( + $this->content_obj->dom, + $this->content_obj->hier_id, + "Standard", + $this->content_obj->getPcId(), + $this->getParentNodeName() + ); - if ($a_edit_property == "shape") - { - $st_alias_item->makeMapWorkCopy($st_item, $a_area_nr, true, - $a_output_new_area, $a_area_type, $a_coords); // exclude area currently being edited - } - else - { - $st_alias_item->makeMapWorkCopy($st_item, $a_area_nr, false, - $a_output_new_area, $a_area_type, $a_coords); - } - } + if ($a_edit_property == "shape") { + $st_alias_item->makeMapWorkCopy( + $st_item, + $a_area_nr, + true, + $a_output_new_area, + $a_area_type, + $a_coords + ); // exclude area currently being edited + } else { + $st_alias_item->makeMapWorkCopy( + $st_item, + $a_area_nr, + false, + $a_output_new_area, + $a_area_type, + $a_coords + ); + } + } - function getAliasXML() - { - return $this->content_obj->dumpXML(); - } + public function getAliasXML() + { + return $this->content_obj->dumpXML(); + } } -?> \ No newline at end of file diff --git a/Services/COPage/classes/class.ilPCImageMapTableGUI.php b/Services/COPage/classes/class.ilPCImageMapTableGUI.php index e417c091b88e836d2e55a9366e49e4f4cf582348..9a80e69a8ffe12ef051a0899f440f0f57465ec42 100755 --- a/Services/COPage/classes/class.ilPCImageMapTableGUI.php +++ b/Services/COPage/classes/class.ilPCImageMapTableGUI.php @@ -15,91 +15,115 @@ include_once("Services/MediaObjects/classes/class.ilImageMapTableGUI.php"); */ class ilPCImageMapTableGUI extends ilImageMapTableGUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_pc_media_object, - $a_parent_node_name) - { - global $DIC; + + /** + * Constructor + */ + public function __construct( + $a_parent_obj, + $a_parent_cmd, + $a_pc_media_object, + $a_parent_node_name + ) { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); - $this->parent_node_name = $a_parent_node_name; - $this->pc_media_object = $a_pc_media_object; - parent::__construct($a_parent_obj, $a_parent_cmd, $a_pc_media_object->getMediaObject()); - } + $this->parent_node_name = $a_parent_node_name; + $this->pc_media_object = $a_pc_media_object; + parent::__construct($a_parent_obj, $a_parent_cmd, $a_pc_media_object->getMediaObject()); + } - /** - * Get items of current folder - */ - function getItems() - { - $std_alias_item = new ilMediaAliasItem($this->pc_media_object->dom, - $this->pc_media_object->hier_id, "Standard", $this->pc_media_object->getPcId(), - $this->parent_node_name); - $areas = $std_alias_item->getMapAreas(); + /** + * Get items of current folder + */ + public function getItems() + { + $std_alias_item = new ilMediaAliasItem( + $this->pc_media_object->dom, + $this->pc_media_object->hier_id, + "Standard", + $this->pc_media_object->getPcId(), + $this->parent_node_name + ); + $areas = $std_alias_item->getMapAreas(); - foreach ($areas as $k => $a) - { - $areas[$k]["title"] = $a["Link"]["Title"]; - } - $areas = ilUtil::sortArray($areas, "title", "asc", false, true); - $this->setData($areas); - } - - /** - * Standard Version of Fill Row. Most likely to - * be overwritten by derived class. - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; + foreach ($areas as $k => $a) { + $areas[$k]["title"] = $a["Link"]["Title"]; + } + $areas = ilUtil::sortArray($areas, "title", "asc", false, true); + $this->setData($areas); + } + + /** + * Standard Version of Fill Row. Most likely to + * be overwritten by derived class. + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; - $i = $a_set["Nr"]; - $this->tpl->setVariable("CHECKBOX", - ilUtil::formCheckBox("", "area[]", $i)); - $this->tpl->setVariable("VAR_NAME", "name_".$i); - $this->tpl->setVariable("VAL_NAME", trim($a_set["Link"]["Title"])); - $this->tpl->setVariable("VAL_SHAPE", $a_set["Shape"]); - - $this->tpl->setVariable("VAL_HIGHL_MODE", - ilUtil::formSelect($a_set["HighlightMode"], "hl_mode_".$i, - $this->highl_modes, false, true)); - $this->tpl->setVariable("VAL_HIGHL_CLASS", - ilUtil::formSelect($a_set["HighlightClass"], "hl_class_".$i, - $this->highl_classes, false, true)); - - $this->tpl->setVariable("VAL_COORDS", - implode(explode(",", $a_set["Coords"]), ", ")); - switch ($a_set["Link"]["LinkType"]) - { - case "ExtLink": - $this->tpl->setVariable("VAL_LINK", $a_set["Link"]["Href"]); - break; - - case "IntLink": - $link_str = $this->parent_obj->getMapAreaLinkString($a_set["Link"]["Target"], - $a_set["Link"]["Type"], $a_set["Link"]["TargetFrame"]); - $this->tpl->setVariable("VAL_LINK", $link_str); - break; - } - } + $i = $a_set["Nr"]; + $this->tpl->setVariable( + "CHECKBOX", + ilUtil::formCheckBox("", "area[]", $i) + ); + $this->tpl->setVariable("VAR_NAME", "name_" . $i); + $this->tpl->setVariable("VAL_NAME", trim($a_set["Link"]["Title"])); + $this->tpl->setVariable("VAL_SHAPE", $a_set["Shape"]); + + $this->tpl->setVariable( + "VAL_HIGHL_MODE", + ilUtil::formSelect( + $a_set["HighlightMode"], + "hl_mode_" . $i, + $this->highl_modes, + false, + true + ) + ); + $this->tpl->setVariable( + "VAL_HIGHL_CLASS", + ilUtil::formSelect( + $a_set["HighlightClass"], + "hl_class_" . $i, + $this->highl_classes, + false, + true + ) + ); + + $this->tpl->setVariable( + "VAL_COORDS", + implode(explode(",", $a_set["Coords"]), ", ") + ); + switch ($a_set["Link"]["LinkType"]) { + case "ExtLink": + $this->tpl->setVariable("VAL_LINK", $a_set["Link"]["Href"]); + break; + case "IntLink": + $link_str = $this->parent_obj->getMapAreaLinkString( + $a_set["Link"]["Target"], + $a_set["Link"]["Type"], + $a_set["Link"]["TargetFrame"] + ); + $this->tpl->setVariable("VAL_LINK", $link_str); + break; + } + } } -?> diff --git a/Services/COPage/classes/class.ilPCInteractiveImage.php b/Services/COPage/classes/class.ilPCInteractiveImage.php index 0338fe39286e188dce8d1eb39e10ab40b9c3fd0e..418c5431838e51f510190d34f5a58fc44b3350f8 100755 --- a/Services/COPage/classes/class.ilPCInteractiveImage.php +++ b/Services/COPage/classes/class.ilPCInteractiveImage.php @@ -14,733 +14,710 @@ require_once("./Services/COPage/classes/class.ilPageContent.php"); */ class ilPCInteractiveImage extends ilPageContent { - /** - * @var ilLanguage - */ - protected $lng; - - - var $dom; - var $iim_node; - - const AREA = "Area"; - const MARKER = "Marker"; - - /** - * Init page content component. - */ - function init() - { - global $DIC; - - $this->lng = $DIC->language(); - $this->setType("iim"); - } - - /** - * Read/get Media Object - * - * @param int media object ID - */ - function readMediaObject($a_mob_id = 0) - { - if ($a_mob_id > 0) - { - $mob = new ilObjMediaObject($a_mob_id); - $this->setMediaObject($mob); - } - } - - /** - * Set node (and media object node) - */ - function setNode($a_node) - { - parent::setNode($a_node); // this is the PageContent node - $this->iim_node = $a_node->first_child(); - $this->med_alias_node = $this->iim_node->first_child(); - if (is_object($this->med_alias_node) && $this->med_alias_node->myDOMNode != null) - { - $id = $this->med_alias_node->get_attribute("OriginId"); - $mob_id = ilInternalLink::_extractObjIdOfTarget($id); - if (ilObject::_lookupType($mob_id) == "mob") - { - $this->setMediaObject(new ilObjMediaObject($mob_id)); - } - } - include_once("./Services/COPage/classes/class.ilMediaAliasItem.php"); - $this->std_alias_item = new ilMediaAliasItem($this->dom, - $this->readHierId(), "Standard", $this->readPCId(), - "InteractiveImage"); - } - - /** - * Set dom object - */ - function setDom(&$a_dom) - { - $this->dom = $a_dom; - } - - /** - * Set Media Object. - * - * @param object $a_mediaobject Media Object - */ - function setMediaObject($a_mediaobject) - { - $this->mediaobject = $a_mediaobject; - } - - /** - * Get Media Object. - * - * @return object Media Object - */ - function getMediaObject() - { - return $this->mediaobject; - } - - /** - * Create new media object - */ - function createMediaObject() - { - $this->setMediaObject(new ilObjMediaObject()); - } - - /** - * Create pc media object - */ - function create($a_pg_obj, $a_hier_id) - { - $this->node = $this->createPageContentNode(); - } - - /** - * Get standard media item - * - * @return - */ - function getStandardMediaItem() - { - return $this->getMediaObject()->getMediaItem("Standard"); - } - - /** - * Get standard alias item - */ - function getStandardAliasItem() - { - return $this->std_alias_item; - } - - - /** - * Get base thumbnail target - * - * @return string base thumbnail target - */ - function getBaseThumbnailTarget() - { - return $this->getMediaObject()->getMediaItem("Standard")->getThumbnailTarget(); - } - - - /** - * Create an media alias in page - * - * @param object $a_pg_obj page object - * @param string $a_hier_id hierarchical ID - */ - function createAlias(&$a_pg_obj, $a_hier_id, $a_pc_id = "") - { - $this->node = $this->dom->create_element("PageContent"); - $a_pg_obj->insertContent($this, $a_hier_id, IL_INSERT_AFTER, $a_pc_id); - $this->iim_node = $this->dom->create_element("InteractiveImage"); - $this->iim_node = $this->node->append_child($this->iim_node); - $this->mal_node = $this->dom->create_element("MediaAlias"); - $this->mal_node = $this->iim_node->append_child($this->mal_node); - $this->mal_node->set_attribute("OriginId", "il__mob_".$this->getMediaObject()->getId()); - - // standard view - $item_node = $this->dom->create_element("MediaAliasItem"); - $item_node = $this->iim_node->append_child($item_node); - $item_node->set_attribute("Purpose", "Standard"); - $media_item = $this->getMediaObject()->getMediaItem("Standard"); - - $layout_node = $this->dom->create_element("Layout"); - $layout_node = $item_node->append_child($layout_node); - if ($media_item->getWidth() > 0) - { - //$layout_node->set_attribute("Width", $media_item->getWidth()); - } - if ($media_item->getHeight() > 0) - { - //$layout_node->set_attribute("Height", $media_item->getHeight()); - } - $layout_node->set_attribute("HorizontalAlign", "Left"); - - // caption - if ($media_item->getCaption() != "") - { - $cap_node = $this->dom->create_element("Caption"); - $cap_node = $item_node->append_child($cap_node); - $cap_node->set_attribute("Align", "bottom"); - $cap_node->set_content($media_item->getCaption()); - } - - // text representation - if ($media_item->getTextRepresentation() != "") - { - $tr_node = $this->dom->create_element("TextRepresentation"); - $tr_node = $item_node->append_child($tr_node); - $tr_node->set_content($media_item->getTextRepresentation()); - } - } - - /** - * Dump node xml - */ - function dumpXML() - { - $xml = $this->dom->dump_node($this->node); - return $xml; - } - - /** - * Set style class - * - * @param string $a_class style class - */ - function setStyleClass($a_class) - { -// check this -die("pcinteractiveimage: setstyleclass"); - if (is_object($this->iim_node)) - { - $mal_node = $this->iim_node->first_child(); - if (is_object($mal_node)) - { - if (!empty($a_class)) - { - $mal_node->set_attribute("Class", $a_class); - } - else - { - if ($mal_node->has_attribute("Class")) - { - $mal_node->remove_attribute("Class"); - } - } - } - } - } - - /** - * Get style class - * - * @return string style class - */ - function getStyleClass() - { - if (is_object($this->iim_node)) - { - $mal_node = $this->iim_node->first_child(); - if (is_object($mal_node)) - { - $class = $mal_node->get_attribute("Class"); - return $class; - } - } - } - - - //// - //// Content popups - //// - - - /** - * Add a tab - */ - function addContentPopup() - { - $lng = $this->lng; - - $max = 0; - $popups = $this->getPopups(); - foreach ($popups as $p) - { - $max = max($max, (int) $p["nr"]); - } - - $new_item = $this->dom->create_element("ContentPopup"); - $new_item->set_attribute("Title", $lng->txt("cont_new_popup")); - $new_item->set_attribute("Nr", $max + 1); - $new_item = $this->iim_node->append_child($new_item); - } - - /** - * Get popup captions - */ - function getPopups() - { - $titles = array(); - $childs = $this->iim_node->child_nodes(); - $k = 0; - for($i = 0; $i < count($childs); $i++) - { - if ($childs[$i]->node_name() == "ContentPopup") - { - $pc_id = $childs[$i]->get_attribute("PCID"); - $hier_id = $childs[$i]->get_attribute("HierId"); - $title = $childs[$i]->get_attribute("Title"); - $nr = $childs[$i]->get_attribute("Nr"); - - $titles[] = array("title" => $title, "nr" => $nr, - "pc_id" => $pc_id, "hier_id" => $hier_id); - $k++; - } - } - return $titles; - } - - /** - * Save popups - */ - function savePopups($a_popups) - { - $childs = $this->iim_node->child_nodes(); - for($i = 0; $i < count($childs); $i++) - { - if ($childs[$i]->node_name() == "ContentPopup") - { - $pc_id = $childs[$i]->get_attribute("PCID"); - $hier_id = $childs[$i]->get_attribute("HierId"); - $k = $hier_id.":".$pc_id; - $childs[$i]->set_attribute("Title", $a_popups[$k]); - } - } - } - - /** - * Delete popup - */ - function deletePopup($a_hier_id, $a_pc_id) - { - // File Item - $childs = $this->iim_node->child_nodes(); - $nodes = array(); - for ($i=0; $inode_name() == "ContentPopup") - { - if ($a_pc_id == $childs[$i]->get_attribute("PCID") && - $a_hier_id == $childs[$i]->get_attribute("HierId")) - { - $childs[$i]->unlink($childs[$i]); - } - } - } - } - - /** - * Get caption - */ -/* - function getCaption($a_hier_id, $a_pc_id) - { - $captions = array(); - $tab_nodes = $this->tabs_node->child_nodes(); - $k = 0; - for($i = 0; $i < count($tab_nodes); $i++) - { - if ($tab_nodes[$i]->node_name() == "Tab") - { - if ($a_pc_id == $tab_nodes[$i]->get_attribute("PCID") && - ($a_hier_id == $tab_nodes[$i]->get_attribute("HierId"))) - { - $tab_node_childs = $tab_nodes[$i]->child_nodes(); - for($j = 0; $j < count($tab_node_childs); $j++) - { - if ($tab_node_childs[$j]->node_name() == "TabCaption") - { - return $tab_node_childs[$j]->get_content(); - } - } - } - } - } - - return ""; - } -*/ - - /** - * Save positions of tabs - */ -/* - function savePositions($a_pos) - { - asort($a_pos); - - // File Item - $childs = $this->tabs_node->child_nodes(); - $nodes = array(); - for ($i=0; $inode_name() == "Tab") - { - $pc_id = $childs[$i]->get_attribute("PCID"); - $hier_id = $childs[$i]->get_attribute("HierId"); - $nodes[$hier_id.":".$pc_id] = $childs[$i]; - $childs[$i]->unlink($childs[$i]); - } - } - - foreach($a_pos as $k => $v) - { - if (is_object($nodes[$k])) - { - $nodes[$k] = $this->tabs_node->append_child($nodes[$k]); - } - } - } -*/ - - /** - * Save positions of tabs - */ -/* - function deleteTab($a_hier_id, $a_pc_id) - { - // File Item - $childs = $this->tabs_node->child_nodes(); - $nodes = array(); - for ($i=0; $inode_name() == "Tab") - { - if ($a_pc_id == $childs[$i]->get_attribute("PCID") && - $a_hier_id == $childs[$i]->get_attribute("HierId")) - { - $childs[$i]->unlink($childs[$i]); - } - } - } - } -*/ - - //// - //// Trigger - //// - - /** - * Add a new trigger - */ - function addTriggerArea($a_alias_item, $a_shape_type, $a_coords, $a_title, - $a_link) - { - $max = 0; - $triggers = $this->getTriggers(); - foreach ($triggers as $t) - { - $max = max($max, (int) $t["Nr"]); - } - - $link = array( - "LinkType" => IL_EXT_LINK, - "Href" => ilUtil::stripSlashes("#")); - - $a_alias_item->addMapArea( - $a_shape_type, $a_coords, - ilUtil::stripSlashes($a_title), $link, $max + 1); - - $attributes = array("Type" => self::AREA, - "Title" => ilUtil::stripSlashes($a_title), - "Nr" => $max + 1, - "OverlayX" => "0", "OverlayY" => "0", "Overlay" => "", "PopupNr" => "", - "PopupX" => "0", "PopupY" => "0", "PopupWidth" => "150", "PopupHeight" => "200"); - $ma_node = ilDOMUtil::addElementToList($this->dom, $this->iim_node, - "Trigger", array("ContentPopup"), "", $attributes); - } - - /** - * Add a new trigger marker - */ - function addTriggerMarker() - { - $lng = $this->lng; - - $max = 0; - $triggers = $this->getTriggers(); - foreach ($triggers as $t) - { - $max = max($max, (int) $t["Nr"]); - } - - $attributes = array("Type" => self::MARKER, - "Title" => $lng->txt("cont_new_marker"), - "Nr" => $max + 1, "OverlayX" => "0", "OverlayY" => "0", - "MarkerX" => "0", "MarkerY" => "0", "PopupNr" => "", - "PopupX" => "0", "PopupY" => "0", "PopupWidth" => "150", "PopupHeight" => "200"); - $ma_node = ilDOMUtil::addElementToList($this->dom, $this->iim_node, - "Trigger", array("ContentPopup"), "", $attributes); - } - - /** - * Get trigger nodes - */ - function getTriggerNodes($a_hier_id, $a_pc_id = "") - { - if ($a_pc_id != "") - { - $xpc = xpath_new_context($this->dom); - $path = "//PageContent[@PCID = '".$a_pc_id."']/InteractiveImage/Trigger"; - $res = xpath_eval($xpc, $path); - if (count($res->nodeset) > 0) - { - return $res->nodeset; - } - return array(); - } - - $xpc = xpath_new_context($this->dom); - $path = "//PageContent[@HierId = '".$a_hier_id."']/InteractiveImage/Trigger"; - $res = xpath_eval($xpc, $path); - if (count($res->nodeset) > 0) - { - return $res->nodeset; - } - } - - - /** - * Get triggers - */ - function getTriggers() - { - $tr_nodes = $this->getTriggerNodes($this->hier_id, $this->getPcId()); - $trigger_arr = array(); - for($i=0; $i < count($tr_nodes); $i++) - { - $tr_node = $tr_nodes[$i]; - $childs = $tr_node->child_nodes(); - $trigger_arr[] = array( - "Nr" => $tr_node->get_attribute("Nr"), - "Type" => $tr_node->get_attribute("Type"), - "Title" => $tr_node->get_attribute("Title"), - "OverlayX" => $tr_node->get_attribute("OverlayX"), - "OverlayY" => $tr_node->get_attribute("OverlayY"), - "MarkerX" => $tr_node->get_attribute("MarkerX"), - "MarkerY" => $tr_node->get_attribute("MarkerY"), - "Overlay" => $tr_node->get_attribute("Overlay"), - "PopupNr" => $tr_node->get_attribute("PopupNr"), - "PopupX" => $tr_node->get_attribute("PopupX"), - "PopupY" => $tr_node->get_attribute("PopupY"), - "PopupWidth" => $tr_node->get_attribute("PopupWidth"), - "PopupHeight" => $tr_node->get_attribute("PopupHeight") - ); - } - - return $trigger_arr; - } - - /** - * Delete Trigger - */ - function deleteTrigger($a_alias_item, $a_nr) - { - // File Item - $childs = $this->iim_node->child_nodes(); - $nodes = array(); - for ($i=0; $inode_name() == "Trigger") - { - if ($a_nr == $childs[$i]->get_attribute("Nr")) - { - $childs[$i]->unlink($childs[$i]); - } - } - } - $a_alias_item->deleteMapAreaById($a_nr); - } - - - /** - * Set trigger overlays - * - * @param array array of strings (representing the overlays for the trigger) - */ - function setTriggerOverlays($a_ovs) - { - $tr_nodes = $this->getTriggerNodes($this->hier_id, $this->getPcId()); - for($i=0; $i < count($tr_nodes); $i++) - { - $tr_node = $tr_nodes[$i]; - if (isset($a_ovs["".$tr_node->get_attribute("Nr")])) - { - $tr_node->set_attribute("Overlay", - $a_ovs["".$tr_node->get_attribute("Nr")]); - } - } - } - - /** - * Set trigger overlay position - * - * @param array array of strings (representing the overlays for the trigger) - */ - function setTriggerOverlayPositions($a_pos) - { - $tr_nodes = $this->getTriggerNodes($this->hier_id, $this->getPcId()); - for($i=0; $i < count($tr_nodes); $i++) - { - $tr_node = $tr_nodes[$i]; - if (isset($a_pos["".$tr_node->get_attribute("Nr")])) - { - $pos = explode(",", $a_pos["".$tr_node->get_attribute("Nr")]); - $tr_node->set_attribute("OverlayX", (int) $pos[0]); - $tr_node->set_attribute("OverlayY", (int) $pos[1]); - } - } - } - - /** - * Set trigger marker position - * - * @param array array of strings (representing the marker positions for the trigger) - */ - function setTriggerMarkerPositions($a_pos) - { - $tr_nodes = $this->getTriggerNodes($this->hier_id, $this->getPcId()); - for($i=0; $i < count($tr_nodes); $i++) - { - $tr_node = $tr_nodes[$i]; - if ($tr_node->get_attribute("Type") == self::MARKER) - { - if (isset($a_pos["".$tr_node->get_attribute("Nr")])) - { - $pos = explode(",", $a_pos["".$tr_node->get_attribute("Nr")]); - $tr_node->set_attribute("MarkerX", (int) $pos[0]); - $tr_node->set_attribute("MarkerY", (int) $pos[1]); - } - } - } - } - - /** - * Set trigger popup position - * - * @param array array of strings (representing the popup positions for the trigger) - */ - function setTriggerPopupPositions($a_pos) - { - $tr_nodes = $this->getTriggerNodes($this->hier_id, $this->getPcId()); - for($i=0; $i < count($tr_nodes); $i++) - { - $tr_node = $tr_nodes[$i]; - if (isset($a_pos["".$tr_node->get_attribute("Nr")])) - { - $pos = explode(",", $a_pos["".$tr_node->get_attribute("Nr")]); - $tr_node->set_attribute("PopupX", (int) $pos[0]); - $tr_node->set_attribute("PopupY", (int) $pos[1]); - } - } - } - - /** - * Set trigger popup size - * - * @param array array of strings (representing the popup sizes for the trigger) - */ - function setTriggerPopupSize($a_size) - { - $tr_nodes = $this->getTriggerNodes($this->hier_id, $this->getPcId()); - for($i=0; $i < count($tr_nodes); $i++) - { - $tr_node = $tr_nodes[$i]; - if (isset($a_size["".$tr_node->get_attribute("Nr")])) - { - $size = explode(",", $a_size["".$tr_node->get_attribute("Nr")]); - $tr_node->set_attribute("PopupWidth", (int) $size[0]); - $tr_node->set_attribute("PopupHeight", (int) $size[1]); - } - } - } - - /** - * Set trigger popups - * - * @param array array of strings (representing the popups for the trigger) - */ - function setTriggerPopups($a_pops) - { - $tr_nodes = $this->getTriggerNodes($this->hier_id, $this->getPcId()); - for($i=0; $i < count($tr_nodes); $i++) - { - $tr_node = $tr_nodes[$i]; - if (isset($a_pops["".$tr_node->get_attribute("Nr")])) - { - $pop = $a_pops["".$tr_node->get_attribute("Nr")]; - $tr_node->set_attribute("PopupNr", $pop); - } - } - } - - /** - * Set trigger titles - * - * @param array array of strings (representing the titles for the trigger) - */ - function setTriggerTitles($a_titles) - { - $tr_nodes = $this->getTriggerNodes($this->hier_id, $this->getPcId()); - for($i=0; $i < count($tr_nodes); $i++) - { - $tr_node = $tr_nodes[$i]; - if (isset($a_titles["".$tr_node->get_attribute("Nr")])) - { - $tr_node->set_attribute("Title", - $a_titles["".$tr_node->get_attribute("Nr")]); - $this->setExtLinkTitle($tr_node->get_attribute("Nr"), - $a_titles["".$tr_node->get_attribute("Nr")]); - } - } - } - - /** - * Set ExtLink Title - * - * @param - * @return - */ - function setExtLinkTitle($a_nr, $a_title) - { - if ($this->getPcId() != "") - { - $xpc = xpath_new_context($this->dom); - $path = "//PageContent[@PCID = '".$this->getPcId()."']/InteractiveImage/MediaAliasItem/MapArea[@Id='".$a_nr."']/ExtLink"; - $res = xpath_eval($xpc, $path); - if (count($res->nodeset) > 0) - { - $res->nodeset[0]->set_content($a_title); - } - return; - } - - $xpc = xpath_new_context($this->dom); - $path = "//PageContent[@HierId = '".$this->hier_id."']/InteractiveImage/MediaAliasItem/MapArea[@Id='".$a_nr."']/ExtLink"; - $res = xpath_eval($xpc, $path); - if (count($res->nodeset) > 0) - { - $res->nodeset[0]->set_content($a_title); - } - } - - + /** + * @var ilLanguage + */ + protected $lng; + + + public $dom; + public $iim_node; + + const AREA = "Area"; + const MARKER = "Marker"; + + /** + * Init page content component. + */ + public function init() + { + global $DIC; + + $this->lng = $DIC->language(); + $this->setType("iim"); + } + + /** + * Read/get Media Object + * + * @param int media object ID + */ + public function readMediaObject($a_mob_id = 0) + { + if ($a_mob_id > 0) { + $mob = new ilObjMediaObject($a_mob_id); + $this->setMediaObject($mob); + } + } + + /** + * Set node (and media object node) + */ + public function setNode($a_node) + { + parent::setNode($a_node); // this is the PageContent node + $this->iim_node = $a_node->first_child(); + $this->med_alias_node = $this->iim_node->first_child(); + if (is_object($this->med_alias_node) && $this->med_alias_node->myDOMNode != null) { + $id = $this->med_alias_node->get_attribute("OriginId"); + $mob_id = ilInternalLink::_extractObjIdOfTarget($id); + if (ilObject::_lookupType($mob_id) == "mob") { + $this->setMediaObject(new ilObjMediaObject($mob_id)); + } + } + include_once("./Services/COPage/classes/class.ilMediaAliasItem.php"); + $this->std_alias_item = new ilMediaAliasItem( + $this->dom, + $this->readHierId(), + "Standard", + $this->readPCId(), + "InteractiveImage" + ); + } + + /** + * Set dom object + */ + public function setDom(&$a_dom) + { + $this->dom = $a_dom; + } + + /** + * Set Media Object. + * + * @param object $a_mediaobject Media Object + */ + public function setMediaObject($a_mediaobject) + { + $this->mediaobject = $a_mediaobject; + } + + /** + * Get Media Object. + * + * @return object Media Object + */ + public function getMediaObject() + { + return $this->mediaobject; + } + + /** + * Create new media object + */ + public function createMediaObject() + { + $this->setMediaObject(new ilObjMediaObject()); + } + + /** + * Create pc media object + */ + public function create($a_pg_obj, $a_hier_id) + { + $this->node = $this->createPageContentNode(); + } + + /** + * Get standard media item + * + * @return + */ + public function getStandardMediaItem() + { + return $this->getMediaObject()->getMediaItem("Standard"); + } + + /** + * Get standard alias item + */ + public function getStandardAliasItem() + { + return $this->std_alias_item; + } + + + /** + * Get base thumbnail target + * + * @return string base thumbnail target + */ + public function getBaseThumbnailTarget() + { + return $this->getMediaObject()->getMediaItem("Standard")->getThumbnailTarget(); + } + + + /** + * Create an media alias in page + * + * @param object $a_pg_obj page object + * @param string $a_hier_id hierarchical ID + */ + public function createAlias(&$a_pg_obj, $a_hier_id, $a_pc_id = "") + { + $this->node = $this->dom->create_element("PageContent"); + $a_pg_obj->insertContent($this, $a_hier_id, IL_INSERT_AFTER, $a_pc_id); + $this->iim_node = $this->dom->create_element("InteractiveImage"); + $this->iim_node = $this->node->append_child($this->iim_node); + $this->mal_node = $this->dom->create_element("MediaAlias"); + $this->mal_node = $this->iim_node->append_child($this->mal_node); + $this->mal_node->set_attribute("OriginId", "il__mob_" . $this->getMediaObject()->getId()); + + // standard view + $item_node = $this->dom->create_element("MediaAliasItem"); + $item_node = $this->iim_node->append_child($item_node); + $item_node->set_attribute("Purpose", "Standard"); + $media_item = $this->getMediaObject()->getMediaItem("Standard"); + + $layout_node = $this->dom->create_element("Layout"); + $layout_node = $item_node->append_child($layout_node); + if ($media_item->getWidth() > 0) { + //$layout_node->set_attribute("Width", $media_item->getWidth()); + } + if ($media_item->getHeight() > 0) { + //$layout_node->set_attribute("Height", $media_item->getHeight()); + } + $layout_node->set_attribute("HorizontalAlign", "Left"); + + // caption + if ($media_item->getCaption() != "") { + $cap_node = $this->dom->create_element("Caption"); + $cap_node = $item_node->append_child($cap_node); + $cap_node->set_attribute("Align", "bottom"); + $cap_node->set_content($media_item->getCaption()); + } + + // text representation + if ($media_item->getTextRepresentation() != "") { + $tr_node = $this->dom->create_element("TextRepresentation"); + $tr_node = $item_node->append_child($tr_node); + $tr_node->set_content($media_item->getTextRepresentation()); + } + } + + /** + * Dump node xml + */ + public function dumpXML() + { + $xml = $this->dom->dump_node($this->node); + return $xml; + } + + /** + * Set style class + * + * @param string $a_class style class + */ + public function setStyleClass($a_class) + { + // check this + die("pcinteractiveimage: setstyleclass"); + if (is_object($this->iim_node)) { + $mal_node = $this->iim_node->first_child(); + if (is_object($mal_node)) { + if (!empty($a_class)) { + $mal_node->set_attribute("Class", $a_class); + } else { + if ($mal_node->has_attribute("Class")) { + $mal_node->remove_attribute("Class"); + } + } + } + } + } + + /** + * Get style class + * + * @return string style class + */ + public function getStyleClass() + { + if (is_object($this->iim_node)) { + $mal_node = $this->iim_node->first_child(); + if (is_object($mal_node)) { + $class = $mal_node->get_attribute("Class"); + return $class; + } + } + } + + + //// + //// Content popups + //// + + + /** + * Add a tab + */ + public function addContentPopup() + { + $lng = $this->lng; + + $max = 0; + $popups = $this->getPopups(); + foreach ($popups as $p) { + $max = max($max, (int) $p["nr"]); + } + + $new_item = $this->dom->create_element("ContentPopup"); + $new_item->set_attribute("Title", $lng->txt("cont_new_popup")); + $new_item->set_attribute("Nr", $max + 1); + $new_item = $this->iim_node->append_child($new_item); + } + + /** + * Get popup captions + */ + public function getPopups() + { + $titles = array(); + $childs = $this->iim_node->child_nodes(); + $k = 0; + for ($i = 0; $i < count($childs); $i++) { + if ($childs[$i]->node_name() == "ContentPopup") { + $pc_id = $childs[$i]->get_attribute("PCID"); + $hier_id = $childs[$i]->get_attribute("HierId"); + $title = $childs[$i]->get_attribute("Title"); + $nr = $childs[$i]->get_attribute("Nr"); + + $titles[] = array("title" => $title, "nr" => $nr, + "pc_id" => $pc_id, "hier_id" => $hier_id); + $k++; + } + } + return $titles; + } + + /** + * Save popups + */ + public function savePopups($a_popups) + { + $childs = $this->iim_node->child_nodes(); + for ($i = 0; $i < count($childs); $i++) { + if ($childs[$i]->node_name() == "ContentPopup") { + $pc_id = $childs[$i]->get_attribute("PCID"); + $hier_id = $childs[$i]->get_attribute("HierId"); + $k = $hier_id . ":" . $pc_id; + $childs[$i]->set_attribute("Title", $a_popups[$k]); + } + } + } + + /** + * Delete popup + */ + public function deletePopup($a_hier_id, $a_pc_id) + { + // File Item + $childs = $this->iim_node->child_nodes(); + $nodes = array(); + for ($i=0; $inode_name() == "ContentPopup") { + if ($a_pc_id == $childs[$i]->get_attribute("PCID") && + $a_hier_id == $childs[$i]->get_attribute("HierId")) { + $childs[$i]->unlink($childs[$i]); + } + } + } + } + + /** + * Get caption + */ + /* + function getCaption($a_hier_id, $a_pc_id) + { + $captions = array(); + $tab_nodes = $this->tabs_node->child_nodes(); + $k = 0; + for($i = 0; $i < count($tab_nodes); $i++) + { + if ($tab_nodes[$i]->node_name() == "Tab") + { + if ($a_pc_id == $tab_nodes[$i]->get_attribute("PCID") && + ($a_hier_id == $tab_nodes[$i]->get_attribute("HierId"))) + { + $tab_node_childs = $tab_nodes[$i]->child_nodes(); + for($j = 0; $j < count($tab_node_childs); $j++) + { + if ($tab_node_childs[$j]->node_name() == "TabCaption") + { + return $tab_node_childs[$j]->get_content(); + } + } + } + } + } + + return ""; + } + */ + + /** + * Save positions of tabs + */ + /* + function savePositions($a_pos) + { + asort($a_pos); + + // File Item + $childs = $this->tabs_node->child_nodes(); + $nodes = array(); + for ($i=0; $inode_name() == "Tab") + { + $pc_id = $childs[$i]->get_attribute("PCID"); + $hier_id = $childs[$i]->get_attribute("HierId"); + $nodes[$hier_id.":".$pc_id] = $childs[$i]; + $childs[$i]->unlink($childs[$i]); + } + } + + foreach($a_pos as $k => $v) + { + if (is_object($nodes[$k])) + { + $nodes[$k] = $this->tabs_node->append_child($nodes[$k]); + } + } + } + */ + + /** + * Save positions of tabs + */ + /* + function deleteTab($a_hier_id, $a_pc_id) + { + // File Item + $childs = $this->tabs_node->child_nodes(); + $nodes = array(); + for ($i=0; $inode_name() == "Tab") + { + if ($a_pc_id == $childs[$i]->get_attribute("PCID") && + $a_hier_id == $childs[$i]->get_attribute("HierId")) + { + $childs[$i]->unlink($childs[$i]); + } + } + } + } + */ + + //// + //// Trigger + //// + + /** + * Add a new trigger + */ + public function addTriggerArea( + $a_alias_item, + $a_shape_type, + $a_coords, + $a_title, + $a_link + ) { + $max = 0; + $triggers = $this->getTriggers(); + foreach ($triggers as $t) { + $max = max($max, (int) $t["Nr"]); + } + + $link = array( + "LinkType" => IL_EXT_LINK, + "Href" => ilUtil::stripSlashes("#")); + + $a_alias_item->addMapArea( + $a_shape_type, + $a_coords, + ilUtil::stripSlashes($a_title), + $link, + $max + 1 + ); + + $attributes = array("Type" => self::AREA, + "Title" => ilUtil::stripSlashes($a_title), + "Nr" => $max + 1, + "OverlayX" => "0", "OverlayY" => "0", "Overlay" => "", "PopupNr" => "", + "PopupX" => "0", "PopupY" => "0", "PopupWidth" => "150", "PopupHeight" => "200"); + $ma_node = ilDOMUtil::addElementToList( + $this->dom, + $this->iim_node, + "Trigger", + array("ContentPopup"), + "", + $attributes + ); + } + + /** + * Add a new trigger marker + */ + public function addTriggerMarker() + { + $lng = $this->lng; + + $max = 0; + $triggers = $this->getTriggers(); + foreach ($triggers as $t) { + $max = max($max, (int) $t["Nr"]); + } + + $attributes = array("Type" => self::MARKER, + "Title" => $lng->txt("cont_new_marker"), + "Nr" => $max + 1, "OverlayX" => "0", "OverlayY" => "0", + "MarkerX" => "0", "MarkerY" => "0", "PopupNr" => "", + "PopupX" => "0", "PopupY" => "0", "PopupWidth" => "150", "PopupHeight" => "200"); + $ma_node = ilDOMUtil::addElementToList( + $this->dom, + $this->iim_node, + "Trigger", + array("ContentPopup"), + "", + $attributes + ); + } + + /** + * Get trigger nodes + */ + public function getTriggerNodes($a_hier_id, $a_pc_id = "") + { + if ($a_pc_id != "") { + $xpc = xpath_new_context($this->dom); + $path = "//PageContent[@PCID = '" . $a_pc_id . "']/InteractiveImage/Trigger"; + $res = xpath_eval($xpc, $path); + if (count($res->nodeset) > 0) { + return $res->nodeset; + } + return array(); + } + + $xpc = xpath_new_context($this->dom); + $path = "//PageContent[@HierId = '" . $a_hier_id . "']/InteractiveImage/Trigger"; + $res = xpath_eval($xpc, $path); + if (count($res->nodeset) > 0) { + return $res->nodeset; + } + } + + + /** + * Get triggers + */ + public function getTriggers() + { + $tr_nodes = $this->getTriggerNodes($this->hier_id, $this->getPcId()); + $trigger_arr = array(); + for ($i=0; $i < count($tr_nodes); $i++) { + $tr_node = $tr_nodes[$i]; + $childs = $tr_node->child_nodes(); + $trigger_arr[] = array( + "Nr" => $tr_node->get_attribute("Nr"), + "Type" => $tr_node->get_attribute("Type"), + "Title" => $tr_node->get_attribute("Title"), + "OverlayX" => $tr_node->get_attribute("OverlayX"), + "OverlayY" => $tr_node->get_attribute("OverlayY"), + "MarkerX" => $tr_node->get_attribute("MarkerX"), + "MarkerY" => $tr_node->get_attribute("MarkerY"), + "Overlay" => $tr_node->get_attribute("Overlay"), + "PopupNr" => $tr_node->get_attribute("PopupNr"), + "PopupX" => $tr_node->get_attribute("PopupX"), + "PopupY" => $tr_node->get_attribute("PopupY"), + "PopupWidth" => $tr_node->get_attribute("PopupWidth"), + "PopupHeight" => $tr_node->get_attribute("PopupHeight") + ); + } + + return $trigger_arr; + } + + /** + * Delete Trigger + */ + public function deleteTrigger($a_alias_item, $a_nr) + { + // File Item + $childs = $this->iim_node->child_nodes(); + $nodes = array(); + for ($i=0; $inode_name() == "Trigger") { + if ($a_nr == $childs[$i]->get_attribute("Nr")) { + $childs[$i]->unlink($childs[$i]); + } + } + } + $a_alias_item->deleteMapAreaById($a_nr); + } + + + /** + * Set trigger overlays + * + * @param array array of strings (representing the overlays for the trigger) + */ + public function setTriggerOverlays($a_ovs) + { + $tr_nodes = $this->getTriggerNodes($this->hier_id, $this->getPcId()); + for ($i=0; $i < count($tr_nodes); $i++) { + $tr_node = $tr_nodes[$i]; + if (isset($a_ovs["" . $tr_node->get_attribute("Nr")])) { + $tr_node->set_attribute( + "Overlay", + $a_ovs["" . $tr_node->get_attribute("Nr")] + ); + } + } + } + + /** + * Set trigger overlay position + * + * @param array array of strings (representing the overlays for the trigger) + */ + public function setTriggerOverlayPositions($a_pos) + { + $tr_nodes = $this->getTriggerNodes($this->hier_id, $this->getPcId()); + for ($i=0; $i < count($tr_nodes); $i++) { + $tr_node = $tr_nodes[$i]; + if (isset($a_pos["" . $tr_node->get_attribute("Nr")])) { + $pos = explode(",", $a_pos["" . $tr_node->get_attribute("Nr")]); + $tr_node->set_attribute("OverlayX", (int) $pos[0]); + $tr_node->set_attribute("OverlayY", (int) $pos[1]); + } + } + } + + /** + * Set trigger marker position + * + * @param array array of strings (representing the marker positions for the trigger) + */ + public function setTriggerMarkerPositions($a_pos) + { + $tr_nodes = $this->getTriggerNodes($this->hier_id, $this->getPcId()); + for ($i=0; $i < count($tr_nodes); $i++) { + $tr_node = $tr_nodes[$i]; + if ($tr_node->get_attribute("Type") == self::MARKER) { + if (isset($a_pos["" . $tr_node->get_attribute("Nr")])) { + $pos = explode(",", $a_pos["" . $tr_node->get_attribute("Nr")]); + $tr_node->set_attribute("MarkerX", (int) $pos[0]); + $tr_node->set_attribute("MarkerY", (int) $pos[1]); + } + } + } + } + + /** + * Set trigger popup position + * + * @param array array of strings (representing the popup positions for the trigger) + */ + public function setTriggerPopupPositions($a_pos) + { + $tr_nodes = $this->getTriggerNodes($this->hier_id, $this->getPcId()); + for ($i=0; $i < count($tr_nodes); $i++) { + $tr_node = $tr_nodes[$i]; + if (isset($a_pos["" . $tr_node->get_attribute("Nr")])) { + $pos = explode(",", $a_pos["" . $tr_node->get_attribute("Nr")]); + $tr_node->set_attribute("PopupX", (int) $pos[0]); + $tr_node->set_attribute("PopupY", (int) $pos[1]); + } + } + } + + /** + * Set trigger popup size + * + * @param array array of strings (representing the popup sizes for the trigger) + */ + public function setTriggerPopupSize($a_size) + { + $tr_nodes = $this->getTriggerNodes($this->hier_id, $this->getPcId()); + for ($i=0; $i < count($tr_nodes); $i++) { + $tr_node = $tr_nodes[$i]; + if (isset($a_size["" . $tr_node->get_attribute("Nr")])) { + $size = explode(",", $a_size["" . $tr_node->get_attribute("Nr")]); + $tr_node->set_attribute("PopupWidth", (int) $size[0]); + $tr_node->set_attribute("PopupHeight", (int) $size[1]); + } + } + } + + /** + * Set trigger popups + * + * @param array array of strings (representing the popups for the trigger) + */ + public function setTriggerPopups($a_pops) + { + $tr_nodes = $this->getTriggerNodes($this->hier_id, $this->getPcId()); + for ($i=0; $i < count($tr_nodes); $i++) { + $tr_node = $tr_nodes[$i]; + if (isset($a_pops["" . $tr_node->get_attribute("Nr")])) { + $pop = $a_pops["" . $tr_node->get_attribute("Nr")]; + $tr_node->set_attribute("PopupNr", $pop); + } + } + } + + /** + * Set trigger titles + * + * @param array array of strings (representing the titles for the trigger) + */ + public function setTriggerTitles($a_titles) + { + $tr_nodes = $this->getTriggerNodes($this->hier_id, $this->getPcId()); + for ($i=0; $i < count($tr_nodes); $i++) { + $tr_node = $tr_nodes[$i]; + if (isset($a_titles["" . $tr_node->get_attribute("Nr")])) { + $tr_node->set_attribute( + "Title", + $a_titles["" . $tr_node->get_attribute("Nr")] + ); + $this->setExtLinkTitle( + $tr_node->get_attribute("Nr"), + $a_titles["" . $tr_node->get_attribute("Nr")] + ); + } + } + } + + /** + * Set ExtLink Title + * + * @param + * @return + */ + public function setExtLinkTitle($a_nr, $a_title) + { + if ($this->getPcId() != "") { + $xpc = xpath_new_context($this->dom); + $path = "//PageContent[@PCID = '" . $this->getPcId() . "']/InteractiveImage/MediaAliasItem/MapArea[@Id='" . $a_nr . "']/ExtLink"; + $res = xpath_eval($xpc, $path); + if (count($res->nodeset) > 0) { + $res->nodeset[0]->set_content($a_title); + } + return; + } + + $xpc = xpath_new_context($this->dom); + $path = "//PageContent[@HierId = '" . $this->hier_id . "']/InteractiveImage/MediaAliasItem/MapArea[@Id='" . $a_nr . "']/ExtLink"; + $res = xpath_eval($xpc, $path); + if (count($res->nodeset) > 0) { + $res->nodeset[0]->set_content($a_title); + } + } } -?> diff --git a/Services/COPage/classes/class.ilPCInteractiveImageGUI.php b/Services/COPage/classes/class.ilPCInteractiveImageGUI.php index 839fd5d9a69963be8677cfb21113f572c004c8ea..17ceda57319678d6575d552649d6809f0b93735c 100755 --- a/Services/COPage/classes/class.ilPCInteractiveImageGUI.php +++ b/Services/COPage/classes/class.ilPCInteractiveImageGUI.php @@ -2,8 +2,8 @@ /* Copyright (c) 1998-2011 ILIAS open source, Extended GPL, see docs/LICENSE */ -require_once ("./Services/COPage/classes/class.ilPageContentGUI.php"); -require_once ("./Services/COPage/classes/class.ilPCInteractiveImage.php"); +require_once("./Services/COPage/classes/class.ilPageContentGUI.php"); +require_once("./Services/COPage/classes/class.ilPCInteractiveImage.php"); include_once("./Services/COPage/classes/class.ilMediaAliasItem.php"); /** @@ -18,704 +18,725 @@ include_once("./Services/COPage/classes/class.ilMediaAliasItem.php"); */ class ilPCInteractiveImageGUI extends ilPageContentGUI { - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - function __construct($a_pg_obj, $a_content_obj, $a_hier_id = 0, $a_pc_id = "") - { - global $DIC; - - $this->tpl = $DIC["tpl"]; - $this->lng = $DIC->language(); - $this->tabs = $DIC->tabs(); - $this->ctrl = $DIC->ctrl(); - $this->toolbar = $DIC->toolbar(); - parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); - } - - /** - * execute command - */ - function executeCommand() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilTabs = $this->tabs; - - -// $this->getCharacteristicsOfCurrentStyle("media_cont"); // scorm-2004 - - // get next class that processes or forwards current command - $next_class = $this->ctrl->getNextClass($this); - - // get current command - $cmd = $this->ctrl->getCmd(); - - if (is_object ($this->content_obj)) - { - $tpl->setTitleIcon(ilUtil::getImagePath("icon_mob.svg")); - $this->getTabs($this->tabs_gui); - -/* $mob = $this->content_obj->getMediaObject(); - if (is_object($mob)) - { - $tpl->setVariable("HEADER", $lng->txt("mob").": ". - $this->content_obj->getMediaObject()->getTitle()); - $mob_gui = new ilObjMediaObjectGUI("", $this->content_obj->getMediaObject()->getId(),false, false); - $mob_gui->setBackTitle($this->page_back_title); - $mob_gui->setEnabledMapAreas($this->getEnabledMapAreas()); - $mob_gui->getTabs($this->tabs_gui); - }*/ - } - else - { - } - - switch($next_class) - { - // trigger editor - case "ilpciimtriggereditorgui": - require_once("./Services/COPage/classes/class.ilPCIIMTriggerEditorGUI.php"); - $ilTabs->setTabActive("triggers"); - $image_map_edit = new ilPCIIMTriggerEditorGUI($this->content_obj, - $this->pg_obj); - $ret = $this->ctrl->forwardCommand($image_map_edit); - $tpl->setContent($ret); - break; - - default: - $ret = $this->$cmd(); - break; - } - - return $ret; - } - - /** - * Add tabs to ilTabsGUI object - * - * @param object $tab_gui ilTabsGUI object - * @param boolean $a_create new creation true/false - */ - function getTabs(&$tab_gui, $a_create = false, $a_change_obj_ref = false) - { - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - $lng = $this->lng; - - if (!$a_create) - { - - $ilTabs->setBackTarget($lng->txt("pg"), - $ilCtrl->getParentReturn($this) - ); - - $ilTabs->addTab("triggers", - $lng->txt("cont_active_areas"), - $ilCtrl->getLinkTargetByClass("ilpciimtriggereditorgui", "editMapAreas") - ); - - $ilTabs->addTab("list_overlays", - $lng->txt("cont_overlay_images"), - $ilCtrl->getLinkTarget($this, "listOverlayImages") - ); - - $ilTabs->addTab("content_popups", - $lng->txt("cont_content_popups"), - $ilCtrl->getLinkTarget($this, "listContentPopups") - ); - - $ilTabs->addTab("edit_base_image", - $lng->txt("cont_base_image")." & ".$lng->txt("cont_caption"), - $ilCtrl->getLinkTarget($this, "editBaseImage") - ); - - } - } - - /** - * Insert new media object form. - */ - function insert($a_post_cmd = "edpost", $a_submit_cmd = "create_mob", $a_input_error = false) - { - $ilTabs = $this->tabs; - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - ilUtil::sendInfo($lng->txt("cont_iim_create_info")); - -// $this->getTabs($ilTabs, true); -// $ilTabs->setSubTabActive("cont_new_mob"); - - if ($a_input_error) - { - $form = $this->form; - } - else - { - $form = $this->initForm("create"); - } - $form->setFormAction($ilCtrl->getFormAction($this)); - - $this->displayValidationError(); - - $tpl->setContent($form->getHTML()); - } - - /** - * Edit - */ - function edit() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - - $ilCtrl->redirectByClass(array("ilpcinteractiveimagegui", "ilpciimtriggereditorgui"), "editMapAreas"); - //$tpl->setContent("hh"); - } - - /** - * Edit base image - * - * @param - * @return - */ - function editBaseImage($a_form = null) - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; - $lng = $this->lng; - - $ilTabs->activateTab("edit_base_image"); - - $form = $this->initForm(); - $tpl->setContent($form->getHTML()); - } - - - /** - * Init creation/base image form. - * - * @param int $a_mode Edit Mode - */ - public function initForm($a_mode = "edit") - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - - // image file - $fi = new ilImageFileInputGUI($lng->txt("cont_file"), "image_file"); - $fi->setAllowDeletion(false); - if ($a_mode == "edit") - { - $fi->setImage($this->content_obj->getBaseThumbnailTarget()); - } - $form->addItem($fi); - - if ($a_mode == "edit") - { - // caption - $ti = new ilTextInputGUI($this->lng->txt("cont_caption"), "caption"); - $ti->setMaxLength(200); - $ti->setSize(50); - $form->addItem($ti); - } - - // save and cancel commands - if ($a_mode == "create") - { - $form->setTitle($lng->txt("cont_ed_insert_iim")); - $form->addCommandButton("create_iim", $lng->txt("save")); - $form->addCommandButton("cancelCreate", $lng->txt("cancel")); - } - else - { - // get caption - $std_alias_item = new ilMediaAliasItem($this->dom, $this->getHierId(), "Standard", - $this->content_obj->getPcId(), "InteractiveImage"); - $ti->setValue($std_alias_item->getCaption()); - - $form->setTitle($lng->txt("cont_edit_base_image")); - $form->addCommandButton("update", $lng->txt("save")); - } - - $form->setFormAction($ilCtrl->getFormAction($this)); - - return $form; - } - - /** - * Create new content element - */ - function create() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->content_obj = new ilPCInteractiveImage($this->getPage()); - $this->content_obj->createMediaObject(); - $media_obj = $this->content_obj->getMediaObject(); - $media_obj->setTitle($_FILES['image_file']['name']); - $media_obj->create(); - $mob_dir = ilObjMediaObject::_getDirectory($media_obj->getId()); -// $media_obj->setStandardType("File"); - $media_obj->createDirectory(); - $media_item = new ilMediaItem(); - $media_obj->addMediaItem($media_item); - $media_item->setPurpose("Standard"); - - $file = $mob_dir."/".$_FILES['image_file']['name']; - ilUtil::moveUploadedFile($_FILES['image_file']['tmp_name'], - $_FILES['image_file']['name'], $file); - - // get mime type - $format = ilObjMediaObject::getMimeType($file); - $location = $_FILES['image_file']['name']; - - // set real meta and object data - $media_item->setFormat($format); - $media_item->setLocation($location); - $media_item->setLocationType("LocalFile"); - - ilUtil::renameExecutables($mob_dir); - $media_obj->update(); - - $this->content_obj->createAlias($this->pg_obj, $this->hier_id, $this->pc_id); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->pg_obj->stripHierIDs(); - $this->pg_obj->addHierIDs(); - $ilCtrl->setParameter($this, "hier_id", $this->content_obj->readHierId()); - $ilCtrl->setParameter($this, "pc_id", $this->content_obj->readPCId()); - $this->content_obj->setHierId($this->content_obj->readHierId()); - $this->setHierId($this->content_obj->readHierId()); - $this->content_obj->setPCId($this->content_obj->readPCId()); - ilUtil::sendSuccess($lng->txt("cont_saved_interactive_image"), true); - $this->ctrl->redirectByClass("ilpcinteractiveimagegui", "edit"); - - //$this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - else - { - $this->insert(); - } - } - - /** - * Update (base image) - */ - function update() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $mob = $this->content_obj->getMediaObject(); - $mob_dir = ilObjMediaObject::_getDirectory($mob->getId()); - $std_item = $mob->getMediaItem("Standard"); - $location = $_FILES['image_file']['name']; - - if ($location != "" && is_file($_FILES['image_file']['tmp_name'])) - { - $file = $mob_dir."/".$_FILES['image_file']['name']; - ilUtil::moveUploadedFile($_FILES['image_file']['tmp_name'], - $_FILES['image_file']['name'], $file); - - // get mime type - $format = ilObjMediaObject::getMimeType($file); - $location = $_FILES['image_file']['name']; - $std_item->setFormat($format); - $std_item->setLocation($location); - $std_item->setLocationType("LocalFile"); - $mob->setDescription($format); - $mob->update(); - } - - // set caption - $std_alias_item = new ilMediaAliasItem($this->dom, $this->getHierId(), "Standard", - $this->content_obj->getPcId(), "InteractiveImage"); - $std_alias_item->setCaption(ilUtil::stripSlashes($_POST["caption"])); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - - $ilCtrl->redirectByClass("ilpcinteractiveimagegui", "editBaseImage"); - } - - - /** - * Align media object to center - */ - function centerAlign() - { - $std_alias_item = new ilMediaAliasItem($this->dom, $this->getHierId(), "Standard", - $this->content_obj->getPcId(), "InteractiveImage"); - $std_alias_item->setHorizontalAlign("Center"); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * align media object to left - */ - function leftAlign() - { - $std_alias_item = new ilMediaAliasItem($this->dom, $this->getHierId(), "Standard", - $this->content_obj->getPcId(), "InteractiveImage"); - $std_alias_item->setHorizontalAlign("Left"); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * align media object to right - */ - function rightAlign() - { - $std_alias_item = new ilMediaAliasItem($this->dom, $this->getHierId(), "Standard", - $this->content_obj->getPcId(), "InteractiveImage"); - $std_alias_item->setHorizontalAlign("Right"); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * align media object to left, floating text - */ - function leftFloatAlign() - { - $std_alias_item = new ilMediaAliasItem($this->dom, $this->getHierId(), "Standard", - $this->content_obj->getPcId(), "InteractiveImage"); - $std_alias_item->setHorizontalAlign("LeftFloat"); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * align media object to right, floating text - */ - function rightFloatAlign() - { - $std_alias_item = new ilMediaAliasItem($this->dom, $this->getHierId(), "Standard", - $this->content_obj->getPcId(), "InteractiveImage"); - $std_alias_item->setHorizontalAlign("RightFloat"); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - //// - //// Overlay Images - //// - - /** - * List overlay images - * - * @param - * @return - */ - function listOverlayImages() - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - $lng = $this->lng; - - ilUtil::sendInfo($lng->txt("cont_iim_overlay_info")); - - $ilTabs->setTabActive("list_overlays"); - - $ilToolbar->addButton($lng->txt("cont_add_images"), - $ilCtrl->getLinkTarget($this, "addOverlayImages")); - - include_once("./Services/COPage/classes/class.ilPCIIMOverlaysTableGUI.php"); - $tab = new ilPCIIMOverlaysTableGUI($this, "listOverlayImages", - $this->content_obj->getMediaObject()); - $tpl->setContent($tab->getHTML()); - } - - /** - * Add overlay images - */ - function addOverlayImages($a_form = null) - { - $tpl = $this->tpl; - - if ($a_form) - { - $form = $a_form; - } - else - { - $form = $this->initAddOverlaysForm(); - } - - $tpl->setContent($form->getHTML()); - } - - /** - * Init add overlays form - * - * @param - * @return - */ - function initAddOverlaysForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - $ilTabs->setTabActive("list_overlays"); - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setTitle($lng->txt("cont_add_images")); - $form->setFormAction($ilCtrl->getFormAction($this)); - - // file input - include_once("./Services/Form/classes/class.ilFileWizardInputGUI.php"); - $fi = new ilFileWizardInputGUI($lng->txt("file"), "ovfile"); - $fi->setSuffixes(array("gif", "jpeg", "jpg", "png")); - $fi->setFilenames(array(0 => '')); - $fi->setRequired(true); - $form->addItem($fi); - - $form->addCommandButton("uploadOverlayImages", $lng->txt("upload")); - $form->addCommandButton("listOverlayImages", $lng->txt("cancel")); - - return $form; - } - - - /** - * Upload overlay images - * - * @param - * @return - */ - function uploadOverlayImages() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $form = $this->initAddOverlaysForm(); - if ($form->checkInput()) - { - if (is_array($_FILES["ovfile"]["name"])) - { - foreach ($_FILES["ovfile"]["name"] as $k => $v) - { - $name = $_FILES["ovfile"]["name"][$k]; - $mime = $_FILES["ovfile"]["type"][$k]; - $tmp_name = $_FILES["ovfile"]["tmp_name"][$k]; - $size = $_FILES["ovfile"]["size"][$k]; - - $this->content_obj->getMediaObject()->uploadAdditionalFile($name, - $tmp_name, "overlays"); - $piname = pathinfo($name); - $this->content_obj->getMediaObject()->makeThumbnail("overlays/".$name, - basename($name, ".".$piname['extension']).".png"); - } - } - ilUtil::sendSuccess($lng->txt("msg_obj_modified")); - $ilCtrl->redirect($this, "listOverlayImages"); - } - else - { - $form->setValuesByPost(); - $this->addOverlayImages($form); - } - } - - /** - * Confirm overlay deletion - */ - function confirmDeleteOverlays() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - $ilTabs = $this->tabs; - - $ilTabs->setTabActive("list_overlays"); - - if (!is_array($_POST["file"]) || count($_POST["file"]) == 0) - { - ilUtil::sendFailure($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "listOverlayImages"); - } - else - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("cont_really_delete_overlays")); - $cgui->setCancel($lng->txt("cancel"), "listOverlayImages"); - $cgui->setConfirm($lng->txt("delete"), "deleteOverlays"); - - foreach ($_POST["file"] as $i => $d) - { - $cgui->addItem("file[]", $i, $i); - } - - $tpl->setContent($cgui->getHTML()); - } - } - - /** - * Delete overlays - */ - function deleteOverlays() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if (is_array($_POST["file"]) && count($_POST["file"]) != 0) - { - foreach ($_POST["file"] as $f) - { - $f = str_replace("..", "", ilUtil::stripSlashes($f)); - $this->content_obj->getMediaObject() - ->removeAdditionalFile("overlays/".$f); - } - - ilUtil::sendSuccess($lng->txt("cont_overlays_have_been_deleted"), true); - } - $ilCtrl->redirect($this, "listOverlayImages"); - } - - - //// - //// Content Popups - //// - - /** - * List content popups - */ - function listContentPopups() - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - $lng = $this->lng; - - ilUtil::sendInfo($lng->txt("cont_iim_content_popups_info")); - - $ilTabs->setTabActive("content_popups"); - - $ilToolbar->addButton($lng->txt("cont_add_popup"), - $ilCtrl->getLinkTarget($this, "addPopup")); - - include_once("./Services/COPage/classes/class.ilPCIIMPopupTableGUI.php"); - $tab = new ilPCIIMPopupTableGUI($this, "listContentPopups", - $this->content_obj); - $tpl->setContent($tab->getHTML()); - } - - /** - * Add popup - * - * @param - * @return - */ - function addPopup() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->content_obj->addContentPopup(); - $this->pg_obj->update(); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "listContentPopups"); - } - - /** - * Save popups - */ - function savePopups() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if (is_array($_POST["title"])) - { - $titles = ilUtil::stripSlashesArray($_POST["title"]); - $this->content_obj->savePopUps($titles); - $this->pg_obj->update(); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - } - $ilCtrl->redirect($this, "listContentPopups"); - } - - /** - * Confirm popup deletion - */ - function confirmPopupDeletion() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - $ilTabs = $this->tabs; - - $ilTabs->setTabActive("content_popups"); - - if (!is_array($_POST["tid"]) || count($_POST["tid"]) == 0) - { - ilUtil::sendFailure($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "listContentPopups"); - } - else - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("cont_really_delete_popups")); - $cgui->setCancel($lng->txt("cancel"), "listContentPopups"); - $cgui->setConfirm($lng->txt("delete"), "deletePopups"); - - foreach ($_POST["tid"] as $i => $d) - { - $cgui->addItem("tid[]", $i, $_POST["title"][$i]); - } - - $tpl->setContent($cgui->getHTML()); - } - } - - /** - * Delete popups - * - * @param - * @return - */ - function deletePopups() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if (is_array($_POST["tid"]) && count($_POST["tid"]) != 0) - { - foreach ($_POST["tid"] as $id) - { - $id = explode(":", $id); - $this->content_obj->deletePopup($id[0], $id[1]); - } - $this->pg_obj->update(); - ilUtil::sendSuccess($lng->txt("cont_popups_have_been_deleted"), true); - } - $ilCtrl->redirect($this, "listContentPopups"); - } - + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + public function __construct($a_pg_obj, $a_content_obj, $a_hier_id = 0, $a_pc_id = "") + { + global $DIC; + + $this->tpl = $DIC["tpl"]; + $this->lng = $DIC->language(); + $this->tabs = $DIC->tabs(); + $this->ctrl = $DIC->ctrl(); + $this->toolbar = $DIC->toolbar(); + parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); + } + + /** + * execute command + */ + public function executeCommand() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilTabs = $this->tabs; + + + // $this->getCharacteristicsOfCurrentStyle("media_cont"); // scorm-2004 + + // get next class that processes or forwards current command + $next_class = $this->ctrl->getNextClass($this); + + // get current command + $cmd = $this->ctrl->getCmd(); + + if (is_object($this->content_obj)) { + $tpl->setTitleIcon(ilUtil::getImagePath("icon_mob.svg")); + $this->getTabs($this->tabs_gui); + + /* $mob = $this->content_obj->getMediaObject(); + if (is_object($mob)) + { + $tpl->setVariable("HEADER", $lng->txt("mob").": ". + $this->content_obj->getMediaObject()->getTitle()); + $mob_gui = new ilObjMediaObjectGUI("", $this->content_obj->getMediaObject()->getId(),false, false); + $mob_gui->setBackTitle($this->page_back_title); + $mob_gui->setEnabledMapAreas($this->getEnabledMapAreas()); + $mob_gui->getTabs($this->tabs_gui); + }*/ + } else { + } + + switch ($next_class) { + // trigger editor + case "ilpciimtriggereditorgui": + require_once("./Services/COPage/classes/class.ilPCIIMTriggerEditorGUI.php"); + $ilTabs->setTabActive("triggers"); + $image_map_edit = new ilPCIIMTriggerEditorGUI( + $this->content_obj, + $this->pg_obj + ); + $ret = $this->ctrl->forwardCommand($image_map_edit); + $tpl->setContent($ret); + break; + + default: + $ret = $this->$cmd(); + break; + } + + return $ret; + } + + /** + * Add tabs to ilTabsGUI object + * + * @param object $tab_gui ilTabsGUI object + * @param boolean $a_create new creation true/false + */ + public function getTabs(&$tab_gui, $a_create = false, $a_change_obj_ref = false) + { + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + $lng = $this->lng; + + if (!$a_create) { + $ilTabs->setBackTarget( + $lng->txt("pg"), + $ilCtrl->getParentReturn($this) + ); + + $ilTabs->addTab( + "triggers", + $lng->txt("cont_active_areas"), + $ilCtrl->getLinkTargetByClass("ilpciimtriggereditorgui", "editMapAreas") + ); + + $ilTabs->addTab( + "list_overlays", + $lng->txt("cont_overlay_images"), + $ilCtrl->getLinkTarget($this, "listOverlayImages") + ); + + $ilTabs->addTab( + "content_popups", + $lng->txt("cont_content_popups"), + $ilCtrl->getLinkTarget($this, "listContentPopups") + ); + + $ilTabs->addTab( + "edit_base_image", + $lng->txt("cont_base_image") . " & " . $lng->txt("cont_caption"), + $ilCtrl->getLinkTarget($this, "editBaseImage") + ); + } + } + + /** + * Insert new media object form. + */ + public function insert($a_post_cmd = "edpost", $a_submit_cmd = "create_mob", $a_input_error = false) + { + $ilTabs = $this->tabs; + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + ilUtil::sendInfo($lng->txt("cont_iim_create_info")); + + // $this->getTabs($ilTabs, true); + // $ilTabs->setSubTabActive("cont_new_mob"); + + if ($a_input_error) { + $form = $this->form; + } else { + $form = $this->initForm("create"); + } + $form->setFormAction($ilCtrl->getFormAction($this)); + + $this->displayValidationError(); + + $tpl->setContent($form->getHTML()); + } + + /** + * Edit + */ + public function edit() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + + $ilCtrl->redirectByClass(array("ilpcinteractiveimagegui", "ilpciimtriggereditorgui"), "editMapAreas"); + //$tpl->setContent("hh"); + } + + /** + * Edit base image + * + * @param + * @return + */ + public function editBaseImage($a_form = null) + { + $tpl = $this->tpl; + $ilTabs = $this->tabs; + $lng = $this->lng; + + $ilTabs->activateTab("edit_base_image"); + + $form = $this->initForm(); + $tpl->setContent($form->getHTML()); + } + + + /** + * Init creation/base image form. + * + * @param int $a_mode Edit Mode + */ + public function initForm($a_mode = "edit") + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + + // image file + $fi = new ilImageFileInputGUI($lng->txt("cont_file"), "image_file"); + $fi->setAllowDeletion(false); + if ($a_mode == "edit") { + $fi->setImage($this->content_obj->getBaseThumbnailTarget()); + } + $form->addItem($fi); + + if ($a_mode == "edit") { + // caption + $ti = new ilTextInputGUI($this->lng->txt("cont_caption"), "caption"); + $ti->setMaxLength(200); + $ti->setSize(50); + $form->addItem($ti); + } + + // save and cancel commands + if ($a_mode == "create") { + $form->setTitle($lng->txt("cont_ed_insert_iim")); + $form->addCommandButton("create_iim", $lng->txt("save")); + $form->addCommandButton("cancelCreate", $lng->txt("cancel")); + } else { + // get caption + $std_alias_item = new ilMediaAliasItem( + $this->dom, + $this->getHierId(), + "Standard", + $this->content_obj->getPcId(), + "InteractiveImage" + ); + $ti->setValue($std_alias_item->getCaption()); + + $form->setTitle($lng->txt("cont_edit_base_image")); + $form->addCommandButton("update", $lng->txt("save")); + } + + $form->setFormAction($ilCtrl->getFormAction($this)); + + return $form; + } + + /** + * Create new content element + */ + public function create() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->content_obj = new ilPCInteractiveImage($this->getPage()); + $this->content_obj->createMediaObject(); + $media_obj = $this->content_obj->getMediaObject(); + $media_obj->setTitle($_FILES['image_file']['name']); + $media_obj->create(); + $mob_dir = ilObjMediaObject::_getDirectory($media_obj->getId()); + // $media_obj->setStandardType("File"); + $media_obj->createDirectory(); + $media_item = new ilMediaItem(); + $media_obj->addMediaItem($media_item); + $media_item->setPurpose("Standard"); + + $file = $mob_dir . "/" . $_FILES['image_file']['name']; + ilUtil::moveUploadedFile( + $_FILES['image_file']['tmp_name'], + $_FILES['image_file']['name'], + $file + ); + + // get mime type + $format = ilObjMediaObject::getMimeType($file); + $location = $_FILES['image_file']['name']; + + // set real meta and object data + $media_item->setFormat($format); + $media_item->setLocation($location); + $media_item->setLocationType("LocalFile"); + + ilUtil::renameExecutables($mob_dir); + $media_obj->update(); + + $this->content_obj->createAlias($this->pg_obj, $this->hier_id, $this->pc_id); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->pg_obj->stripHierIDs(); + $this->pg_obj->addHierIDs(); + $ilCtrl->setParameter($this, "hier_id", $this->content_obj->readHierId()); + $ilCtrl->setParameter($this, "pc_id", $this->content_obj->readPCId()); + $this->content_obj->setHierId($this->content_obj->readHierId()); + $this->setHierId($this->content_obj->readHierId()); + $this->content_obj->setPCId($this->content_obj->readPCId()); + ilUtil::sendSuccess($lng->txt("cont_saved_interactive_image"), true); + $this->ctrl->redirectByClass("ilpcinteractiveimagegui", "edit"); + + //$this->ctrl->returnToParent($this, "jump".$this->hier_id); + } else { + $this->insert(); + } + } + + /** + * Update (base image) + */ + public function update() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $mob = $this->content_obj->getMediaObject(); + $mob_dir = ilObjMediaObject::_getDirectory($mob->getId()); + $std_item = $mob->getMediaItem("Standard"); + $location = $_FILES['image_file']['name']; + + if ($location != "" && is_file($_FILES['image_file']['tmp_name'])) { + $file = $mob_dir . "/" . $_FILES['image_file']['name']; + ilUtil::moveUploadedFile( + $_FILES['image_file']['tmp_name'], + $_FILES['image_file']['name'], + $file + ); + + // get mime type + $format = ilObjMediaObject::getMimeType($file); + $location = $_FILES['image_file']['name']; + $std_item->setFormat($format); + $std_item->setLocation($location); + $std_item->setLocationType("LocalFile"); + $mob->setDescription($format); + $mob->update(); + } + + // set caption + $std_alias_item = new ilMediaAliasItem( + $this->dom, + $this->getHierId(), + "Standard", + $this->content_obj->getPcId(), + "InteractiveImage" + ); + $std_alias_item->setCaption(ilUtil::stripSlashes($_POST["caption"])); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + + $ilCtrl->redirectByClass("ilpcinteractiveimagegui", "editBaseImage"); + } + + + /** + * Align media object to center + */ + public function centerAlign() + { + $std_alias_item = new ilMediaAliasItem( + $this->dom, + $this->getHierId(), + "Standard", + $this->content_obj->getPcId(), + "InteractiveImage" + ); + $std_alias_item->setHorizontalAlign("Center"); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * align media object to left + */ + public function leftAlign() + { + $std_alias_item = new ilMediaAliasItem( + $this->dom, + $this->getHierId(), + "Standard", + $this->content_obj->getPcId(), + "InteractiveImage" + ); + $std_alias_item->setHorizontalAlign("Left"); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * align media object to right + */ + public function rightAlign() + { + $std_alias_item = new ilMediaAliasItem( + $this->dom, + $this->getHierId(), + "Standard", + $this->content_obj->getPcId(), + "InteractiveImage" + ); + $std_alias_item->setHorizontalAlign("Right"); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * align media object to left, floating text + */ + public function leftFloatAlign() + { + $std_alias_item = new ilMediaAliasItem( + $this->dom, + $this->getHierId(), + "Standard", + $this->content_obj->getPcId(), + "InteractiveImage" + ); + $std_alias_item->setHorizontalAlign("LeftFloat"); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * align media object to right, floating text + */ + public function rightFloatAlign() + { + $std_alias_item = new ilMediaAliasItem( + $this->dom, + $this->getHierId(), + "Standard", + $this->content_obj->getPcId(), + "InteractiveImage" + ); + $std_alias_item->setHorizontalAlign("RightFloat"); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + //// + //// Overlay Images + //// + + /** + * List overlay images + * + * @param + * @return + */ + public function listOverlayImages() + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + $lng = $this->lng; + + ilUtil::sendInfo($lng->txt("cont_iim_overlay_info")); + + $ilTabs->setTabActive("list_overlays"); + + $ilToolbar->addButton( + $lng->txt("cont_add_images"), + $ilCtrl->getLinkTarget($this, "addOverlayImages") + ); + + include_once("./Services/COPage/classes/class.ilPCIIMOverlaysTableGUI.php"); + $tab = new ilPCIIMOverlaysTableGUI( + $this, + "listOverlayImages", + $this->content_obj->getMediaObject() + ); + $tpl->setContent($tab->getHTML()); + } + + /** + * Add overlay images + */ + public function addOverlayImages($a_form = null) + { + $tpl = $this->tpl; + + if ($a_form) { + $form = $a_form; + } else { + $form = $this->initAddOverlaysForm(); + } + + $tpl->setContent($form->getHTML()); + } + + /** + * Init add overlays form + * + * @param + * @return + */ + public function initAddOverlaysForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + $ilTabs->setTabActive("list_overlays"); + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setTitle($lng->txt("cont_add_images")); + $form->setFormAction($ilCtrl->getFormAction($this)); + + // file input + include_once("./Services/Form/classes/class.ilFileWizardInputGUI.php"); + $fi = new ilFileWizardInputGUI($lng->txt("file"), "ovfile"); + $fi->setSuffixes(array("gif", "jpeg", "jpg", "png")); + $fi->setFilenames(array(0 => '')); + $fi->setRequired(true); + $form->addItem($fi); + + $form->addCommandButton("uploadOverlayImages", $lng->txt("upload")); + $form->addCommandButton("listOverlayImages", $lng->txt("cancel")); + + return $form; + } + + + /** + * Upload overlay images + * + * @param + * @return + */ + public function uploadOverlayImages() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $form = $this->initAddOverlaysForm(); + if ($form->checkInput()) { + if (is_array($_FILES["ovfile"]["name"])) { + foreach ($_FILES["ovfile"]["name"] as $k => $v) { + $name = $_FILES["ovfile"]["name"][$k]; + $mime = $_FILES["ovfile"]["type"][$k]; + $tmp_name = $_FILES["ovfile"]["tmp_name"][$k]; + $size = $_FILES["ovfile"]["size"][$k]; + + $this->content_obj->getMediaObject()->uploadAdditionalFile( + $name, + $tmp_name, + "overlays" + ); + $piname = pathinfo($name); + $this->content_obj->getMediaObject()->makeThumbnail( + "overlays/" . $name, + basename($name, "." . $piname['extension']) . ".png" + ); + } + } + ilUtil::sendSuccess($lng->txt("msg_obj_modified")); + $ilCtrl->redirect($this, "listOverlayImages"); + } else { + $form->setValuesByPost(); + $this->addOverlayImages($form); + } + } + + /** + * Confirm overlay deletion + */ + public function confirmDeleteOverlays() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + $ilTabs = $this->tabs; + + $ilTabs->setTabActive("list_overlays"); + + if (!is_array($_POST["file"]) || count($_POST["file"]) == 0) { + ilUtil::sendFailure($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "listOverlayImages"); + } else { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("cont_really_delete_overlays")); + $cgui->setCancel($lng->txt("cancel"), "listOverlayImages"); + $cgui->setConfirm($lng->txt("delete"), "deleteOverlays"); + + foreach ($_POST["file"] as $i => $d) { + $cgui->addItem("file[]", $i, $i); + } + + $tpl->setContent($cgui->getHTML()); + } + } + + /** + * Delete overlays + */ + public function deleteOverlays() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if (is_array($_POST["file"]) && count($_POST["file"]) != 0) { + foreach ($_POST["file"] as $f) { + $f = str_replace("..", "", ilUtil::stripSlashes($f)); + $this->content_obj->getMediaObject() + ->removeAdditionalFile("overlays/" . $f); + } + + ilUtil::sendSuccess($lng->txt("cont_overlays_have_been_deleted"), true); + } + $ilCtrl->redirect($this, "listOverlayImages"); + } + + + //// + //// Content Popups + //// + + /** + * List content popups + */ + public function listContentPopups() + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + $lng = $this->lng; + + ilUtil::sendInfo($lng->txt("cont_iim_content_popups_info")); + + $ilTabs->setTabActive("content_popups"); + + $ilToolbar->addButton( + $lng->txt("cont_add_popup"), + $ilCtrl->getLinkTarget($this, "addPopup") + ); + + include_once("./Services/COPage/classes/class.ilPCIIMPopupTableGUI.php"); + $tab = new ilPCIIMPopupTableGUI( + $this, + "listContentPopups", + $this->content_obj + ); + $tpl->setContent($tab->getHTML()); + } + + /** + * Add popup + * + * @param + * @return + */ + public function addPopup() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->content_obj->addContentPopup(); + $this->pg_obj->update(); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "listContentPopups"); + } + + /** + * Save popups + */ + public function savePopups() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if (is_array($_POST["title"])) { + $titles = ilUtil::stripSlashesArray($_POST["title"]); + $this->content_obj->savePopUps($titles); + $this->pg_obj->update(); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + } + $ilCtrl->redirect($this, "listContentPopups"); + } + + /** + * Confirm popup deletion + */ + public function confirmPopupDeletion() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + $ilTabs = $this->tabs; + + $ilTabs->setTabActive("content_popups"); + + if (!is_array($_POST["tid"]) || count($_POST["tid"]) == 0) { + ilUtil::sendFailure($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "listContentPopups"); + } else { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("cont_really_delete_popups")); + $cgui->setCancel($lng->txt("cancel"), "listContentPopups"); + $cgui->setConfirm($lng->txt("delete"), "deletePopups"); + + foreach ($_POST["tid"] as $i => $d) { + $cgui->addItem("tid[]", $i, $_POST["title"][$i]); + } + + $tpl->setContent($cgui->getHTML()); + } + } + + /** + * Delete popups + * + * @param + * @return + */ + public function deletePopups() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if (is_array($_POST["tid"]) && count($_POST["tid"]) != 0) { + foreach ($_POST["tid"] as $id) { + $id = explode(":", $id); + $this->content_obj->deletePopup($id[0], $id[1]); + } + $this->pg_obj->update(); + ilUtil::sendSuccess($lng->txt("cont_popups_have_been_deleted"), true); + } + $ilCtrl->redirect($this, "listContentPopups"); + } } -?> diff --git a/Services/COPage/classes/class.ilPCList.php b/Services/COPage/classes/class.ilPCList.php index 8adf2769e6ca394ce19d93c95ad306f305dcae81..1d938677cdc21f1ef4aa61f33d1cc772186f1b53 100755 --- a/Services/COPage/classes/class.ilPCList.php +++ b/Services/COPage/classes/class.ilPCList.php @@ -15,224 +15,206 @@ require_once("./Services/COPage/classes/class.ilPageContent.php"); */ class ilPCList extends ilPageContent { - var $list_node; + public $list_node; - /** - * Init page content component. - */ - function init() - { - $this->setType("list"); - } + /** + * Init page content component. + */ + public function init() + { + $this->setType("list"); + } - /** - * Set pc node - */ - function setNode($a_node) - { - parent::setNode($a_node); // this is the PageContent node - $this->list_node = $a_node->first_child(); // this is the Table node - } + /** + * Set pc node + */ + public function setNode($a_node) + { + parent::setNode($a_node); // this is the PageContent node + $this->list_node = $a_node->first_child(); // this is the Table node + } - /** - * Create new list - */ - 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->list_node = $this->dom->create_element("List"); - $this->list_node = $this->node->append_child($this->list_node); - } + /** + * Create new list + */ + public 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->list_node = $this->dom->create_element("List"); + $this->list_node = $this->node->append_child($this->list_node); + } - /** - * Add a number of items to list - */ - function addItems($a_nr) - { - for ($i=1; $i<=$a_nr; $i++) - { - $new_item = $this->dom->create_element("ListItem"); - $new_item = $this->list_node->append_child($new_item); - } - } + /** + * Add a number of items to list + */ + public function addItems($a_nr) + { + for ($i=1; $i<=$a_nr; $i++) { + $new_item = $this->dom->create_element("ListItem"); + $new_item = $this->list_node->append_child($new_item); + } + } - /** - * Set order type - */ -/* function setOrderType($a_type = "Unordered") - { - switch ($a_type) - { - case "Unordered": - $this->list_node->set_attribute("Type", "Unordered"); - if ($this->list_node->has_attribute("NumberingType")) - { - $this->list_node->remove_attribute("NumberingType"); - } - break; + /** + * Set order type + */ + /* function setOrderType($a_type = "Unordered") + { + switch ($a_type) + { + case "Unordered": + $this->list_node->set_attribute("Type", "Unordered"); + if ($this->list_node->has_attribute("NumberingType")) + { + $this->list_node->remove_attribute("NumberingType"); + } + break; - case "Number": - case "Roman": - case "roman": - case "Alphabetic": - case "alphabetic": - case "Decimal": - $this->list_node->set_attribute("Type", "Ordered"); - $this->list_node->set_attribute("NumberingType", $a_type); - break; - } - }*/ + case "Number": + case "Roman": + case "roman": + case "Alphabetic": + case "alphabetic": + case "Decimal": + $this->list_node->set_attribute("Type", "Ordered"); + $this->list_node->set_attribute("NumberingType", $a_type); + break; + } + }*/ - /** - * Get order type - */ - function getOrderType() - { - if ($this->list_node->get_attribute("Type") == "Unordered") - { - return "Unordered"; - } - - $nt = $this->list_node->get_attribute("NumberingType"); - switch ($nt) - { - case "Number": - case "Roman": - case "roman": - case "Alphabetic": - case "alphabetic": - case "Decimal": - return $nt; - break; - - default: - return "Number"; - } - } + /** + * Get order type + */ + public function getOrderType() + { + if ($this->list_node->get_attribute("Type") == "Unordered") { + return "Unordered"; + } + + $nt = $this->list_node->get_attribute("NumberingType"); + switch ($nt) { + case "Number": + case "Roman": + case "roman": + case "Alphabetic": + case "alphabetic": + case "Decimal": + return $nt; + break; + + default: + return "Number"; + } + } - /** - * Get list type - */ - function getListType() - { - if ($this->list_node->get_attribute("Type") == "Unordered") - { - return "Unordered"; - } - return "Ordered"; - } + /** + * Get list type + */ + public function getListType() + { + if ($this->list_node->get_attribute("Type") == "Unordered") { + return "Unordered"; + } + return "Ordered"; + } - /** - * Set list type - * - * @param string list type - */ - function setListType($a_val) - { - $this->list_node->set_attribute("Type", $a_val); - } + /** + * Set list type + * + * @param string list type + */ + public function setListType($a_val) + { + $this->list_node->set_attribute("Type", $a_val); + } - /** - * Get numbering type - */ - function getNumberingType() - { - $nt = $this->list_node->get_attribute("NumberingType"); - switch ($nt) - { - case "Number": - case "Roman": - case "roman": - case "Alphabetic": - case "alphabetic": - case "Decimal": - return $nt; - break; - - default: - return "Number"; - } - } + /** + * Get numbering type + */ + public function getNumberingType() + { + $nt = $this->list_node->get_attribute("NumberingType"); + switch ($nt) { + case "Number": + case "Roman": + case "roman": + case "Alphabetic": + case "alphabetic": + case "Decimal": + return $nt; + break; + + default: + return "Number"; + } + } - /** - * Set numbering type - * - * @param string numbering type - */ - function setNumberingType($a_val) - { - if ($a_val != "") - { - $this->list_node->set_attribute("NumberingType", $a_val); - } - else - { - if ($this->list_node->has_attribute("NumberingType")) - { - $this->list_node->remove_attribute("NumberingType"); - } - } - } + /** + * Set numbering type + * + * @param string numbering type + */ + public function setNumberingType($a_val) + { + if ($a_val != "") { + $this->list_node->set_attribute("NumberingType", $a_val); + } else { + if ($this->list_node->has_attribute("NumberingType")) { + $this->list_node->remove_attribute("NumberingType"); + } + } + } - /** - * Set start value - * - * @param int start value - */ - function setStartValue($a_val) - { - if ($a_val != "") - { - $this->list_node->set_attribute("StartValue", $a_val); - } - else - { - if ($this->list_node->has_attribute("StartValue")) - { - $this->list_node->remove_attribute("StartValue"); - } - } - } - - /** - * Get start value - * - * @return int start value - */ - function getStartValue() - { - return $this->list_node->get_attribute("StartValue"); - } - - /** - * Set style class - * - * @param string style class - */ - function setStyleClass($a_val) - { - if (!in_array($a_val, array("", "BulletedList", "NumberedList"))) - { - $this->list_node->set_attribute("Class", $a_val); - } - else - { - if ($this->list_node->has_attribute("Class")) - { - $this->list_node->remove_attribute("Class"); - } - } - } - - /** - * Get style class - * - * @return string style class - */ - function getStyleClass() - { - return $this->list_node->get_attribute("Class"); - } + /** + * Set start value + * + * @param int start value + */ + public function setStartValue($a_val) + { + if ($a_val != "") { + $this->list_node->set_attribute("StartValue", $a_val); + } else { + if ($this->list_node->has_attribute("StartValue")) { + $this->list_node->remove_attribute("StartValue"); + } + } + } + + /** + * Get start value + * + * @return int start value + */ + public function getStartValue() + { + return $this->list_node->get_attribute("StartValue"); + } + + /** + * Set style class + * + * @param string style class + */ + public function setStyleClass($a_val) + { + if (!in_array($a_val, array("", "BulletedList", "NumberedList"))) { + $this->list_node->set_attribute("Class", $a_val); + } else { + if ($this->list_node->has_attribute("Class")) { + $this->list_node->remove_attribute("Class"); + } + } + } + + /** + * Get style class + * + * @return string style class + */ + public function getStyleClass() + { + return $this->list_node->get_attribute("Class"); + } } -?> diff --git a/Services/COPage/classes/class.ilPCListGUI.php b/Services/COPage/classes/class.ilPCListGUI.php index 5512e3291cb5bbfa475630c71de7e41fbb16884d..28d7a0a46c6c067e76720d0f475e4cdebbbb3a2c 100755 --- a/Services/COPage/classes/class.ilPCListGUI.php +++ b/Services/COPage/classes/class.ilPCListGUI.php @@ -17,296 +17,271 @@ require_once("./Services/COPage/classes/class.ilPageContentGUI.php"); class ilPCListGUI extends ilPageContentGUI { - /** - * Constructor - * @access public - */ - function __construct(&$a_pg_obj, &$a_content_obj, $a_hier_id, $a_pc_id = "") - { - global $DIC; + /** + * Constructor + * @access public + */ + public function __construct(&$a_pg_obj, &$a_content_obj, $a_hier_id, $a_pc_id = "") + { + global $DIC; - $this->tpl = $DIC["tpl"]; - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); - } + $this->tpl = $DIC["tpl"]; + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + 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); + /** + * 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(); + // get current command + $cmd = $this->ctrl->getCmd(); - switch($next_class) - { - default: - $ret = $this->$cmd(); - break; - } + switch ($next_class) { + default: + $ret = $this->$cmd(); + break; + } - return $ret; - } + return $ret; + } - /** - * insert new list form - */ - function insert() - { - $this->displayValidationError(); - - $this->initListForm("create"); - $this->tpl->setContent($this->form->getHTML()); - } + /** + * insert new list form + */ + public function insert() + { + $this->displayValidationError(); + + $this->initListForm("create"); + $this->tpl->setContent($this->form->getHTML()); + } - /** - * Save list - */ - public function create() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->initListForm("create"); - if ($this->form->checkInput()) - { - $this->content_obj = new ilPCList($this->getPage()); - $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); - $this->content_obj->addItems($_POST["nr_items"]); - $this->content_obj->setStartValue($_POST["start_value"]); - $this->content_obj->setListType($_POST["list_type"]); - if ($_POST["list_type"] == "Unordered") - { - $this->content_obj->setNumberingType(""); - $this->content_obj->setStyleClass($_POST["bullet_style"]); - } - else - { - $this->content_obj->setNumberingType($_POST["numbering_type"]); - $this->content_obj->setStyleClass($_POST["number_style"]); - } - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - } - $this->form->setValuesByPost(); - $tpl->setContent($this->form->getHtml()); - } - - /** - * edit properties form - */ - function edit() - { - $this->displayValidationError(); - - $this->initListForm("edit"); - $this->getValues(); - $this->tpl->setContent($this->form->getHTML()); - } + /** + * Save list + */ + public function create() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $this->initListForm("create"); + if ($this->form->checkInput()) { + $this->content_obj = new ilPCList($this->getPage()); + $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); + $this->content_obj->addItems($_POST["nr_items"]); + $this->content_obj->setStartValue($_POST["start_value"]); + $this->content_obj->setListType($_POST["list_type"]); + if ($_POST["list_type"] == "Unordered") { + $this->content_obj->setNumberingType(""); + $this->content_obj->setStyleClass($_POST["bullet_style"]); + } else { + $this->content_obj->setNumberingType($_POST["numbering_type"]); + $this->content_obj->setStyleClass($_POST["number_style"]); + } + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + } + $this->form->setValuesByPost(); + $tpl->setContent($this->form->getHtml()); + } + + /** + * edit properties form + */ + public function edit() + { + $this->displayValidationError(); + + $this->initListForm("edit"); + $this->getValues(); + $this->tpl->setContent($this->form->getHTML()); + } - /** - * Save properties - */ - function saveProperties() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - - $this->initListForm("edit"); - if ($this->form->checkInput()) - { - $this->content_obj->setStartValue($_POST["start_value"]); - $this->content_obj->setListType($_POST["list_type"]); - if ($_POST["list_type"] == "Unordered") - { - $this->content_obj->setNumberingType(""); - $this->content_obj->setStyleClass($_POST["bullet_style"]); - } - else - { - $this->content_obj->setNumberingType($_POST["numbering_type"]); - $this->content_obj->setStyleClass($_POST["number_style"]); - } - - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - } - $this->form->setValuesByPost(); - $tpl->setContent($this->form->getHtml()); - } - - /** - * Init list form. - * - * @param int $a_mode Edit Mode - */ - public function initListForm($a_mode = "edit") - { - $lng = $this->lng; - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - // type - $radg = new ilRadioGroupInputGUI($lng->txt("type"), "list_type"); - $op1 = new ilRadioOption($lng->txt("cont_bullet_list"), "Unordered"); - - // style of bullet list - require_once("./Services/Form/classes/class.ilAdvSelectInputGUI.php"); - $style = new ilAdvSelectInputGUI($this->lng->txt("cont_style"), - "bullet_style"); - $this->getCharacteristicsOfCurrentStyle("list_u"); - $options = $this->getCharacteristics(); - if ($a_mode == "edit" && $this->content_obj->getListType() == "Unordered" - && $this->content_obj->getStyleClass() != "" - && !in_array($this->content_obj->getStyleClass(), $options)) - { - $options[$this->content_obj->getStyleClass()] = - $this->content_obj->getStyleClass(); - } - if (count($options) > 1) - { - foreach($options as $k => $option) - { - $html = '
  • '. - $option.'
'; - if ($k == "BulletedList") - { - $k = ""; - } - $style->addOption($k, $option, $html); - } - $style->setValue(""); - $op1->addSubItem($style); - } - - $radg->addOption($op1); + /** + * Save properties + */ + public function saveProperties() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + + $this->initListForm("edit"); + if ($this->form->checkInput()) { + $this->content_obj->setStartValue($_POST["start_value"]); + $this->content_obj->setListType($_POST["list_type"]); + if ($_POST["list_type"] == "Unordered") { + $this->content_obj->setNumberingType(""); + $this->content_obj->setStyleClass($_POST["bullet_style"]); + } else { + $this->content_obj->setNumberingType($_POST["numbering_type"]); + $this->content_obj->setStyleClass($_POST["number_style"]); + } + + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + } + $this->form->setValuesByPost(); + $tpl->setContent($this->form->getHtml()); + } + + /** + * Init list form. + * + * @param int $a_mode Edit Mode + */ + public function initListForm($a_mode = "edit") + { + $lng = $this->lng; + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + // type + $radg = new ilRadioGroupInputGUI($lng->txt("type"), "list_type"); + $op1 = new ilRadioOption($lng->txt("cont_bullet_list"), "Unordered"); + + // style of bullet list + require_once("./Services/Form/classes/class.ilAdvSelectInputGUI.php"); + $style = new ilAdvSelectInputGUI( + $this->lng->txt("cont_style"), + "bullet_style" + ); + $this->getCharacteristicsOfCurrentStyle("list_u"); + $options = $this->getCharacteristics(); + if ($a_mode == "edit" && $this->content_obj->getListType() == "Unordered" + && $this->content_obj->getStyleClass() != "" + && !in_array($this->content_obj->getStyleClass(), $options)) { + $options[$this->content_obj->getStyleClass()] = + $this->content_obj->getStyleClass(); + } + if (count($options) > 1) { + foreach ($options as $k => $option) { + $html = '
  • ' . + $option . '
'; + if ($k == "BulletedList") { + $k = ""; + } + $style->addOption($k, $option, $html); + } + $style->setValue(""); + $op1->addSubItem($style); + } + + $radg->addOption($op1); - - $op2 = new ilRadioOption($lng->txt("cont_numbered_list"), "Ordered"); + + $op2 = new ilRadioOption($lng->txt("cont_numbered_list"), "Ordered"); - // style of numbered list - require_once("./Services/Form/classes/class.ilAdvSelectInputGUI.php"); - $style = new ilAdvSelectInputGUI($this->lng->txt("cont_style"), - "number_style"); - $this->getCharacteristicsOfCurrentStyle("list_o"); - $options = $this->getCharacteristics(); - if ($a_mode == "edit" && $this->content_obj->getListType() == "Ordered" - && $this->content_obj->getStyleClass() != "" - && !in_array($this->content_obj->getStyleClass(), $options)) - { - $options[$this->content_obj->getStyleClass()] = - $this->content_obj->getStyleClass(); - } - if (count($options) > 1) - { - foreach($options as $k => $option) - { - $html = '
  1. '. - $option.'
'; - if ($k == "NumberedList") - { - $k = ""; - } - $style->addOption($k, $option, $html); - } - $style->setValue(""); - $op2->addSubItem($style); - } - - // numeric type - $options = array( - "Number" => $this->lng->txt("cont_number_std"), - "Decimal" => $this->lng->txt("cont_decimal"), - "Roman" => $this->lng->txt("cont_roman"), - "roman" => $this->lng->txt("cont_roman_s"), - "Alphabetic" => $this->lng->txt("cont_alphabetic"), - "alphabetic" => $this->lng->txt("cont_alphabetic_s") - ); - $si = new ilSelectInputGUI($this->lng->txt("cont_number_type"), "numbering_type"); - $si->setOptions($options); - $op2->addSubItem($si); - - // starting value - $ni = new ilNumberInputGUI($this->lng->txt("cont_start_value"), "start_value"); - $ni->setMaxLength(3); - $ni->setSize(3); - $ni->setInfo($lng->txt("cont_start_value_info")); - $op2->addSubItem($ni); + // style of numbered list + require_once("./Services/Form/classes/class.ilAdvSelectInputGUI.php"); + $style = new ilAdvSelectInputGUI( + $this->lng->txt("cont_style"), + "number_style" + ); + $this->getCharacteristicsOfCurrentStyle("list_o"); + $options = $this->getCharacteristics(); + if ($a_mode == "edit" && $this->content_obj->getListType() == "Ordered" + && $this->content_obj->getStyleClass() != "" + && !in_array($this->content_obj->getStyleClass(), $options)) { + $options[$this->content_obj->getStyleClass()] = + $this->content_obj->getStyleClass(); + } + if (count($options) > 1) { + foreach ($options as $k => $option) { + $html = '
  1. ' . + $option . '
'; + if ($k == "NumberedList") { + $k = ""; + } + $style->addOption($k, $option, $html); + } + $style->setValue(""); + $op2->addSubItem($style); + } + + // numeric type + $options = array( + "Number" => $this->lng->txt("cont_number_std"), + "Decimal" => $this->lng->txt("cont_decimal"), + "Roman" => $this->lng->txt("cont_roman"), + "roman" => $this->lng->txt("cont_roman_s"), + "Alphabetic" => $this->lng->txt("cont_alphabetic"), + "alphabetic" => $this->lng->txt("cont_alphabetic_s") + ); + $si = new ilSelectInputGUI($this->lng->txt("cont_number_type"), "numbering_type"); + $si->setOptions($options); + $op2->addSubItem($si); + + // starting value + $ni = new ilNumberInputGUI($this->lng->txt("cont_start_value"), "start_value"); + $ni->setMaxLength(3); + $ni->setSize(3); + $ni->setInfo($lng->txt("cont_start_value_info")); + $op2->addSubItem($ni); - $radg->addOption($op2); - $radg->setValue("Unordered"); - $this->form->addItem($radg); - - // nr of items - $options = array(); - if ($a_mode == "create") - { - for ($i=1; $i<=10; $i++) - { - $options[$i] = $i; - } - $si = new ilSelectInputGUI($this->lng->txt("cont_nr_items"), "nr_items"); - $si->setOptions($options); - $si->setValue(2); - $this->form->addItem($si); - } + $radg->addOption($op2); + $radg->setValue("Unordered"); + $this->form->addItem($radg); + + // nr of items + $options = array(); + if ($a_mode == "create") { + for ($i=1; $i<=10; $i++) { + $options[$i] = $i; + } + $si = new ilSelectInputGUI($this->lng->txt("cont_nr_items"), "nr_items"); + $si->setOptions($options); + $si->setValue(2); + $this->form->addItem($si); + } - // save and cancel commands - if ($a_mode == "create") - { - $this->form->addCommandButton("create_list", $lng->txt("save")); - $this->form->addCommandButton("cancelCreate", $lng->txt("cancel")); - $this->form->setTitle($lng->txt("cont_insert_list")); - } - else - { - $this->form->addCommandButton("saveProperties", $lng->txt("save")); - $this->form->addCommandButton("cancelUpdate", $lng->txt("cancel")); - $this->form->setTitle($lng->txt("cont_list_properties")); - } - - $this->form->setFormAction($this->ctrl->getFormAction($this)); - } + // save and cancel commands + if ($a_mode == "create") { + $this->form->addCommandButton("create_list", $lng->txt("save")); + $this->form->addCommandButton("cancelCreate", $lng->txt("cancel")); + $this->form->setTitle($lng->txt("cont_insert_list")); + } else { + $this->form->addCommandButton("saveProperties", $lng->txt("save")); + $this->form->addCommandButton("cancelUpdate", $lng->txt("cancel")); + $this->form->setTitle($lng->txt("cont_list_properties")); + } + + $this->form->setFormAction($this->ctrl->getFormAction($this)); + } - /** - * Get current values for list from - * - */ - public function getValues() - { - $tpl = $this->tpl; - - $values = array(); - - $values["start_value"] = $this->content_obj->getStartValue(); - $values["list_type"] = $this->content_obj->getListType(); - $values["numbering_type"] = $this->content_obj->getNumberingType(); - if ($values["list_type"] == "Ordered") - { - $values["number_style"] = $this->content_obj->getStyleClass(); - $values["bullet_style"] = ""; - } - else - { - $values["bullet_style"] = $this->content_obj->getStyleClass(); - $values["number_style"] = ""; - } - $this->form->setValuesByArray($values); - } - + /** + * Get current values for list from + * + */ + public function getValues() + { + $tpl = $this->tpl; + + $values = array(); + + $values["start_value"] = $this->content_obj->getStartValue(); + $values["list_type"] = $this->content_obj->getListType(); + $values["numbering_type"] = $this->content_obj->getNumberingType(); + if ($values["list_type"] == "Ordered") { + $values["number_style"] = $this->content_obj->getStyleClass(); + $values["bullet_style"] = ""; + } else { + $values["bullet_style"] = $this->content_obj->getStyleClass(); + $values["number_style"] = ""; + } + $this->form->setValuesByArray($values); + } } -?> diff --git a/Services/COPage/classes/class.ilPCListItem.php b/Services/COPage/classes/class.ilPCListItem.php index e8b456400203ef412fceac99f810d3f2933e226f..76735dc247551c7df397749f07edf3bd0c30fef9 100755 --- a/Services/COPage/classes/class.ilPCListItem.php +++ b/Services/COPage/classes/class.ilPCListItem.php @@ -16,89 +16,81 @@ require_once("./Services/COPage/classes/class.ilPageContent.php"); */ class ilPCListItem extends ilPageContent { - var $dom; + public $dom; - /** - * Init page content component. - */ - function init() - { - $this->setType("li"); - } + /** + * Init page content component. + */ + public function init() + { + $this->setType("li"); + } - /** - * insert new list item after current one - */ - function newItemAfter() - { - $li = $this->getNode(); - $new_li = $this->dom->create_element("ListItem"); - if ($next_li = $li->next_sibling()) - { - $new_li = $next_li->insert_before($new_li, $next_li); - } - else - { - $parent_list = $li->parent_node(); - $new_li = $parent_list->append_child($new_li); - } - } + /** + * insert new list item after current one + */ + public function newItemAfter() + { + $li = $this->getNode(); + $new_li = $this->dom->create_element("ListItem"); + if ($next_li = $li->next_sibling()) { + $new_li = $next_li->insert_before($new_li, $next_li); + } else { + $parent_list = $li->parent_node(); + $new_li = $parent_list->append_child($new_li); + } + } - /** - * insert new list item before current one - */ - function newItemBefore() - { - $li = $this->getNode(); - $new_li = $this->dom->create_element("ListItem"); - $new_li = $li->insert_before($new_li, $li); - } + /** + * insert new list item before current one + */ + public function newItemBefore() + { + $li = $this->getNode(); + $new_li = $this->dom->create_element("ListItem"); + $new_li = $li->insert_before($new_li, $li); + } - /** - * delete row of cell - */ - function deleteItem() - { - $parent_node = $this->getNode()->parent_node(); - $cnt = count($parent_node->child_nodes()); - if ($cnt == 1) - { - // if list item is the last one -> delete whole list - $grandma = $parent_node->parent_node(); - $grandma->unlink($grandma); - } - else - { - $li = $this->getNode(); - $li->unlink($li); - } - } + /** + * delete row of cell + */ + public function deleteItem() + { + $parent_node = $this->getNode()->parent_node(); + $cnt = count($parent_node->child_nodes()); + if ($cnt == 1) { + // if list item is the last one -> delete whole list + $grandma = $parent_node->parent_node(); + $grandma->unlink($grandma); + } else { + $li = $this->getNode(); + $li->unlink($li); + } + } - /** - * move list item down - */ - function moveItemDown() - { - $li = $this->getNode(); - $next = $li->next_sibling(); - $next_copy = $next->clone_node(true); - $next_copy = $li->insert_before($next_copy, $li); - $next->unlink($next); - } - - /** - * move list item up - */ - function moveItemUp() - { - $li = $this->getNode(); - $prev = $li->previous_sibling(); - $li_copy = $li->clone_node(true); - $li_copy = $prev->insert_before($li_copy, $prev); - $li->unlink($li); - } + /** + * move list item down + */ + public function moveItemDown() + { + $li = $this->getNode(); + $next = $li->next_sibling(); + $next_copy = $next->clone_node(true); + $next_copy = $li->insert_before($next_copy, $li); + $next->unlink($next); + } + /** + * move list item up + */ + public function moveItemUp() + { + $li = $this->getNode(); + $prev = $li->previous_sibling(); + $li_copy = $li->clone_node(true); + $li_copy = $prev->insert_before($li_copy, $prev); + $li->unlink($li); + } } -?> diff --git a/Services/COPage/classes/class.ilPCListItemGUI.php b/Services/COPage/classes/class.ilPCListItemGUI.php index d1124dd4df1ade5fee9534b8092af477c7131e86..567fe3ee03ef185968ef0af2d7285680d54e4fd5 100755 --- a/Services/COPage/classes/class.ilPCListItemGUI.php +++ b/Services/COPage/classes/class.ilPCListItemGUI.php @@ -1,24 +1,24 @@ ctrl->getNextClass($this); + /** + * 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(); + // get current command + $cmd = $this->ctrl->getCmd(); - switch($next_class) - { - default: - $ret = $this->$cmd(); - break; - } + switch ($next_class) { + default: + $ret = $this->$cmd(); + break; + } - return $ret; - } + return $ret; + } - /** - * insert new list item after current one - */ - function newItemAfter() - { - $this->content_obj->newItemAfter(); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } + /** + * insert new list item after current one + */ + public function newItemAfter() + { + $this->content_obj->newItemAfter(); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } - /** - * insert new list item before current one - */ - function newItemBefore() - { - $this->content_obj->newItemBefore(); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } + /** + * insert new list item before current one + */ + public function newItemBefore() + { + $this->content_obj->newItemBefore(); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } - /** - * delete a list item - */ - function deleteItem() - { - $this->content_obj->deleteItem(); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } + /** + * delete a list item + */ + public function deleteItem() + { + $this->content_obj->deleteItem(); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } - /** - * move list item down - */ - function moveItemDown() - { - $this->content_obj->moveItemDown(); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * move list item up - */ - function moveItemUp() - { - $this->content_obj->moveItemUp(); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } + /** + * move list item down + */ + public function moveItemDown() + { + $this->content_obj->moveItemDown(); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + /** + * move list item up + */ + public function moveItemUp() + { + $this->content_obj->moveItemUp(); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } } -?> diff --git a/Services/COPage/classes/class.ilPCLoginPageElement.php b/Services/COPage/classes/class.ilPCLoginPageElement.php index d70f693f4f89de52bec19fe547c76604cda56f53..b2c0d58a1d76f25940bbd2270d0b7428537d6323 100644 --- a/Services/COPage/classes/class.ilPCLoginPageElement.php +++ b/Services/COPage/classes/class.ilPCLoginPageElement.php @@ -15,112 +15,107 @@ include_once './Services/COPage/classes/class.ilPageContent.php'; */ class ilPCLoginPageElement extends ilPageContent { - public $res_node; - - private static $types = array( - 'login-form' => 'login_form', - 'cas-login-form' => 'cas_login_form', - 'shibboleth-login-form' => 'shib_login_form', - 'openid-connect-login' => 'openid_connect_login', - 'registration-link' => 'registration_link', - 'language-selection' => 'language_selection', - 'user-agreement' => 'user_agreement_link' - ); + public $res_node; + + private static $types = array( + 'login-form' => 'login_form', + 'cas-login-form' => 'cas_login_form', + 'shibboleth-login-form' => 'shib_login_form', + 'openid-connect-login' => 'openid_connect_login', + 'registration-link' => 'registration_link', + 'language-selection' => 'language_selection', + 'user-agreement' => 'user_agreement_link' + ); - /** - * Get all types - * @return array all type - */ - public static function getAllTypes() - { - return self::$types; - } + /** + * Get all types + * @return array all type + */ + public static function getAllTypes() + { + return self::$types; + } - /** - * Init page content component. - */ - public function init() - { - $this->setType('lpe'); - } + /** + * Init page content component. + */ + public function init() + { + $this->setType('lpe'); + } - /** - * Set node - */ - function setNode($a_node) - { - parent::setNode($a_node); // this is the PageContent node - $this->res_node = $a_node->first_child(); // this is the login page element - } + /** + * Set node + */ + public function setNode($a_node) + { + parent::setNode($a_node); // this is the PageContent node + $this->res_node = $a_node->first_child(); // this is the login page element + } - /** - * Create resources node in xml. - * - * @param object $a_pg_obj Page Object - * @param string $a_hier_id Hierarchical ID - */ - 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); - $lpe = $this->dom->create_element('LoginPageElement'); - $this->res_node = $this->node->append_child($lpe); - } + /** + * Create resources node in xml. + * + * @param object $a_pg_obj Page Object + * @param string $a_hier_id Hierarchical ID + */ + public 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); + $lpe = $this->dom->create_element('LoginPageElement'); + $this->res_node = $this->node->append_child($lpe); + } - /** - * Set Type of Login Page Element - * - * @param string $a_type Resource Type Group - */ - function setLoginPageElementType($a_type) - { - if (!empty($a_type)) - { - $this->res_node->set_attribute('Type',$a_type); - } - } + /** + * Set Type of Login Page Element + * + * @param string $a_type Resource Type Group + */ + public function setLoginPageElementType($a_type) + { + if (!empty($a_type)) { + $this->res_node->set_attribute('Type', $a_type); + } + } - /** - * Get log page element type - * - * @return string resource type group - */ - function getLoginPageElementType() - { - if (is_object($this->res_node)) - { - return $this->res_node->get_attribute('Type'); - } - } + /** + * Get log page element type + * + * @return string resource type group + */ + public function getLoginPageElementType() + { + if (is_object($this->res_node)) { + return $this->res_node->get_attribute('Type'); + } + } - /** - * set alignment - */ - public function setAlignment($a_alignment) - { - $this->res_node->set_attribute('HorizontalAlign',$a_alignment); - } - - /** - * Get alignment - * @return string $alignment - */ - public function getAlignment() - { - if(is_object($this->res_node)) - { - return $this->res_node->get_attribute('HorizontalAlign'); - } - } - - /** - * Get lang vars needed for editing - * @return array array of lang var keys - */ - static function getLangVars() - { - return array("ed_insert_login_page_element"); - } + /** + * set alignment + */ + public function setAlignment($a_alignment) + { + $this->res_node->set_attribute('HorizontalAlign', $a_alignment); + } + /** + * Get alignment + * @return string $alignment + */ + public function getAlignment() + { + if (is_object($this->res_node)) { + return $this->res_node->get_attribute('HorizontalAlign'); + } + } + + /** + * Get lang vars needed for editing + * @return array array of lang var keys + */ + public static function getLangVars() + { + return array("ed_insert_login_page_element"); + } } -?> \ No newline at end of file diff --git a/Services/COPage/classes/class.ilPCLoginPageElementGUI.php b/Services/COPage/classes/class.ilPCLoginPageElementGUI.php index f652a5b9f7ddd0d4424420e572a52bb8a3baf875..2ce738c35bfabf6671b0ad8b20336da3cd15b451 100644 --- a/Services/COPage/classes/class.ilPCLoginPageElementGUI.php +++ b/Services/COPage/classes/class.ilPCLoginPageElementGUI.php @@ -17,180 +17,163 @@ include_once './Services/COPage/classes/class.ilPCLoginPageElement.php'; */ class ilPCLoginPageElementGUI extends ilPageContentGUI { - /** - * @var ilObjectDefinition - */ - protected $obj_definition; - - /** - * 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->tpl = $DIC["tpl"]; - $this->lng = $DIC->language(); - $this->obj_definition = $DIC["objDefinition"]; - parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); - - if(!is_object($this->content_obj)) - { - $this->content_obj = new ilPCLoginPageElement($this->getPage()); - } - } - - /** - * Get login page elements - * @return ilPCLoginPageElement $lp_elements - */ - public function getLoginPageElements() - { - return $this->lp_elements; - } - - /** - * 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() - { - $this->edit(true); - } - - /** - * Edit resources form. - */ - public function edit($a_insert = false) - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - $objDefinition = $this->obj_definition; - - $this->displayValidationError(); - - // edit form - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this)); - if ($a_insert) - { - $form->setTitle($this->lng->txt("cont_insert_login_page")); - } - else - { - $form->setTitle($this->lng->txt("cont_update_login_page")); - } - - // type selection - $type_prop = new ilRadioGroupInputGUI($this->lng->txt("cont_type"),"type"); - - foreach(ilPCLoginPageElement::getAllTypes() as $index => $lang_key) - { - $types[$index] = $this->lng->txt('cont_lpe_'.$lang_key); - - $option = new ilRadioOption($this->lng->txt('cont_lpe_'.$lang_key), $index); - $type_prop->addOption($option); - - } - - $selected = $a_insert - ? "" - : $this->content_obj->getLoginPageElementType(); - $type_prop->setValue($selected); - $form->addItem($type_prop); - - // horizonal align - $align_prop = new ilSelectInputGUI($this->lng->txt("cont_align"),"horizontal_align"); - $options = array( - "Left" => $lng->txt("cont_left"), - "Center" => $lng->txt("cont_center"), - "Right" => $lng->txt("cont_right")); -# "LeftFloat" => $lng->txt("cont_left_float"), -# "RightFloat" => $lng->txt("cont_right_float")); - $align_prop->setOptions($options); - $align_prop->setValue($this->content_obj->getAlignment()); - $form->addItem($align_prop); - - - // save/cancel buttons - if ($a_insert) - { - $form->addCommandButton("create_login_page_element", $lng->txt("save")); - $form->addCommandButton("cancelCreate", $lng->txt("cancel")); - } - else - { - $form->addCommandButton("update_login_page_element", $lng->txt("save")); - $form->addCommandButton("cancelUpdate", $lng->txt("cancel")); - } - $html = $form->getHTML(); - $tpl->setContent($html); - return $ret; - } - - - /** - * Create new Login Page Element - */ - public function create() - { - $this->content_obj = new ilPCLoginPageElement($this->getPage()); - $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); - $this->content_obj->setLoginPageElementType($_POST["type"]); - $this->content_obj->setAlignment($_POST['horizontal_align']); - - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - else - { - $this->insert(); - } - } - - /** - * Update Login page element - */ - public function update() - { - $this->content_obj->setLoginPageElementType($_POST["type"]); - $this->content_obj->setAlignment($_POST['horizontal_align']); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - else - { - $this->pg_obj->addHierIDs(); - $this->edit(); - } - } + /** + * @var ilObjectDefinition + */ + protected $obj_definition; + + /** + * 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->tpl = $DIC["tpl"]; + $this->lng = $DIC->language(); + $this->obj_definition = $DIC["objDefinition"]; + parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); + + if (!is_object($this->content_obj)) { + $this->content_obj = new ilPCLoginPageElement($this->getPage()); + } + } + + /** + * Get login page elements + * @return ilPCLoginPageElement $lp_elements + */ + public function getLoginPageElements() + { + return $this->lp_elements; + } + + /** + * 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() + { + $this->edit(true); + } + + /** + * Edit resources form. + */ + public function edit($a_insert = false) + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + $objDefinition = $this->obj_definition; + + $this->displayValidationError(); + + // edit form + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this)); + if ($a_insert) { + $form->setTitle($this->lng->txt("cont_insert_login_page")); + } else { + $form->setTitle($this->lng->txt("cont_update_login_page")); + } + + // type selection + $type_prop = new ilRadioGroupInputGUI($this->lng->txt("cont_type"), "type"); + + foreach (ilPCLoginPageElement::getAllTypes() as $index => $lang_key) { + $types[$index] = $this->lng->txt('cont_lpe_' . $lang_key); + + $option = new ilRadioOption($this->lng->txt('cont_lpe_' . $lang_key), $index); + $type_prop->addOption($option); + } + + $selected = $a_insert + ? "" + : $this->content_obj->getLoginPageElementType(); + $type_prop->setValue($selected); + $form->addItem($type_prop); + + // horizonal align + $align_prop = new ilSelectInputGUI($this->lng->txt("cont_align"), "horizontal_align"); + $options = array( + "Left" => $lng->txt("cont_left"), + "Center" => $lng->txt("cont_center"), + "Right" => $lng->txt("cont_right")); + # "LeftFloat" => $lng->txt("cont_left_float"), + # "RightFloat" => $lng->txt("cont_right_float")); + $align_prop->setOptions($options); + $align_prop->setValue($this->content_obj->getAlignment()); + $form->addItem($align_prop); + + + // save/cancel buttons + if ($a_insert) { + $form->addCommandButton("create_login_page_element", $lng->txt("save")); + $form->addCommandButton("cancelCreate", $lng->txt("cancel")); + } else { + $form->addCommandButton("update_login_page_element", $lng->txt("save")); + $form->addCommandButton("cancelUpdate", $lng->txt("cancel")); + } + $html = $form->getHTML(); + $tpl->setContent($html); + return $ret; + } + + + /** + * Create new Login Page Element + */ + public function create() + { + $this->content_obj = new ilPCLoginPageElement($this->getPage()); + $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); + $this->content_obj->setLoginPageElementType($_POST["type"]); + $this->content_obj->setAlignment($_POST['horizontal_align']); + + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } else { + $this->insert(); + } + } + + /** + * Update Login page element + */ + public function update() + { + $this->content_obj->setLoginPageElementType($_POST["type"]); + $this->content_obj->setAlignment($_POST['horizontal_align']); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } else { + $this->pg_obj->addHierIDs(); + $this->edit(); + } + } } -?> diff --git a/Services/COPage/classes/class.ilPCMap.php b/Services/COPage/classes/class.ilPCMap.php index 91375bf7eee41f2eb7ce1469e81b9c28063802a5..f2e5f274b7464982c15d6ad3ab3c1cdf6b2fd72f 100755 --- a/Services/COPage/classes/class.ilPCMap.php +++ b/Services/COPage/classes/class.ilPCMap.php @@ -16,320 +16,296 @@ require_once("./Services/COPage/classes/class.ilPageContent.php"); */ class ilPCMap extends ilPageContent { - var $map_node; + public $map_node; - /** - * Init page content component. - */ - function init() - { - $this->setType("map"); - } + /** + * Init page content component. + */ + public function init() + { + $this->setType("map"); + } - /** - * Set node - */ - function setNode($a_node) - { - parent::setNode($a_node); // this is the PageContent node - $this->map_node = $a_node->first_child(); // this is the Map node - } + /** + * Set node + */ + public function setNode($a_node) + { + parent::setNode($a_node); // this is the PageContent node + $this->map_node = $a_node->first_child(); // this is the Map node + } - /** - * Create map node in xml. - * - * @param object $a_pg_obj Page Object - * @param string $a_hier_id Hierarchical ID - */ - function create(&$a_pg_obj, $a_hier_id, $a_pc_id = "") - { - $this->node = $this->createPageContentNode(); + /** + * Create map node in xml. + * + * @param object $a_pg_obj Page Object + * @param string $a_hier_id Hierarchical ID + */ + public 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->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"); - } + $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"); + } - /** - * Set latitude of map - * - * @param string $a_lat latitude - */ - function setLatitude($a_lat) - { - if (!empty($a_lat)) - { - $this->map_node->set_attribute("Latitude", $a_lat); - } - else - { - if ($this->map_node->has_attribute("Latitude")) - { - $this->map_node->remove_attribute("Latitude"); - } - } - } + /** + * Set latitude of map + * + * @param string $a_lat latitude + */ + public function setLatitude($a_lat) + { + if (!empty($a_lat)) { + $this->map_node->set_attribute("Latitude", $a_lat); + } else { + if ($this->map_node->has_attribute("Latitude")) { + $this->map_node->remove_attribute("Latitude"); + } + } + } - /** - * Get latitude of map. - * - * @return string latitude - */ - function getLatitude() - { - if (is_object($this->map_node)) - { - return $this->map_node->get_attribute("Latitude"); - } - } + /** + * Get latitude of map. + * + * @return string latitude + */ + public function getLatitude() + { + if (is_object($this->map_node)) { + return $this->map_node->get_attribute("Latitude"); + } + } - /** - * Set longitude of map - * - * @param string $a_long longitude - */ - function setLongitude($a_long) - { - if (!empty($a_long)) - { - $this->map_node->set_attribute("Longitude", $a_long); - } - else - { - if ($this->map_node->has_attribute("Longitude")) - { - $this->map_node->remove_attribute("Longitude"); - } - } - } + /** + * Set longitude of map + * + * @param string $a_long longitude + */ + public function setLongitude($a_long) + { + if (!empty($a_long)) { + $this->map_node->set_attribute("Longitude", $a_long); + } else { + if ($this->map_node->has_attribute("Longitude")) { + $this->map_node->remove_attribute("Longitude"); + } + } + } - /** - * Get longitude of map. - * - * @return string longitude - */ - function getLongitude() - { - if (is_object($this->map_node)) - { - return $this->map_node->get_attribute("Longitude"); - } - } + /** + * Get longitude of map. + * + * @return string longitude + */ + public function getLongitude() + { + if (is_object($this->map_node)) { + return $this->map_node->get_attribute("Longitude"); + } + } - /** - * Set zoom of map - * - * @param string $a_zoom zoom - */ - function setZoom($a_zoom) - { - if (!empty($a_zoom)) - { - $this->map_node->set_attribute("Zoom", $a_zoom); - } - else - { - if ($this->map_node->has_attribute("Zoom")) - { - $this->map_node->remove_attribute("Zoom"); - } - } - } + /** + * Set zoom of map + * + * @param string $a_zoom zoom + */ + public function setZoom($a_zoom) + { + if (!empty($a_zoom)) { + $this->map_node->set_attribute("Zoom", $a_zoom); + } else { + if ($this->map_node->has_attribute("Zoom")) { + $this->map_node->remove_attribute("Zoom"); + } + } + } - /** - * Get zoom of map. - * - * @return string zoom - */ - function getZoom() - { - if (is_object($this->map_node)) - { - return $this->map_node->get_attribute("Zoom"); - } - } - - /** - * Set Layout - * - * @param integer $a_width Width - * @param integer $a_height Height - * @param integer $a_horizonal_align Horizontal Alignment - */ - function setLayout($a_width, $a_height, $a_horizontal_align) - { - if (is_object($this->map_node)) - { - ilDomUtil::setFirstOptionalElement($this->dom, $this->map_node, - "Layout", array("MapCaption"), "", array("Width" => $a_width, - "Height" => $a_height, "HorizontalAlign" => $a_horizontal_align)); - } - } + /** + * Get zoom of map. + * + * @return string zoom + */ + public function getZoom() + { + if (is_object($this->map_node)) { + return $this->map_node->get_attribute("Zoom"); + } + } + + /** + * Set Layout + * + * @param integer $a_width Width + * @param integer $a_height Height + * @param integer $a_horizonal_align Horizontal Alignment + */ + public function setLayout($a_width, $a_height, $a_horizontal_align) + { + if (is_object($this->map_node)) { + ilDomUtil::setFirstOptionalElement( + $this->dom, + $this->map_node, + "Layout", + array("MapCaption"), + "", + array("Width" => $a_width, + "Height" => $a_height, "HorizontalAlign" => $a_horizontal_align) + ); + } + } - /** - * Get Width. - * - * @return integer Width - */ - function getWidth() - { - if (is_object($this->map_node)) - { - $childs = $this->map_node->child_nodes(); - foreach($childs as $child) - { - if ($child->node_name() == "Layout") - { - return $child->get_attribute("Width"); - } - } - } - } + /** + * Get Width. + * + * @return integer Width + */ + public function getWidth() + { + if (is_object($this->map_node)) { + $childs = $this->map_node->child_nodes(); + foreach ($childs as $child) { + if ($child->node_name() == "Layout") { + return $child->get_attribute("Width"); + } + } + } + } - /** - * Get Height. - * - * @return integer Height - */ - function getHeight() - { - if (is_object($this->map_node)) - { - $childs = $this->map_node->child_nodes(); - foreach($childs as $child) - { - if ($child->node_name() == "Layout") - { - return $child->get_attribute("Height"); - } - } - } - } + /** + * Get Height. + * + * @return integer Height + */ + public function getHeight() + { + if (is_object($this->map_node)) { + $childs = $this->map_node->child_nodes(); + foreach ($childs as $child) { + if ($child->node_name() == "Layout") { + return $child->get_attribute("Height"); + } + } + } + } - /** - * Get Horizontal Alignment. - * - * @return string Horizontal Alignment - */ - function getHorizontalAlign() - { - if (is_object($this->map_node)) - { - $childs = $this->map_node->child_nodes(); - foreach($childs as $child) - { - if ($child->node_name() == "Layout") - { - return $child->get_attribute("HorizontalAlign"); - } - } - } - } + /** + * Get Horizontal Alignment. + * + * @return string Horizontal Alignment + */ + public function getHorizontalAlign() + { + if (is_object($this->map_node)) { + $childs = $this->map_node->child_nodes(); + foreach ($childs as $child) { + if ($child->node_name() == "Layout") { + return $child->get_attribute("HorizontalAlign"); + } + } + } + } - /** - * Set Caption. - * - * @param string $a_caption Caption - */ - function setCaption($a_caption) - { - if (is_object($this->map_node)) - { - ilDomUtil::setFirstOptionalElement($this->dom, $this->map_node, - "MapCaption", array(), $a_caption, array()); - } - } + /** + * Set Caption. + * + * @param string $a_caption Caption + */ + public function setCaption($a_caption) + { + if (is_object($this->map_node)) { + ilDomUtil::setFirstOptionalElement( + $this->dom, + $this->map_node, + "MapCaption", + array(), + $a_caption, + array() + ); + } + } - /** - * Get Caption. - * - * @return string Caption - */ - function getCaption() - { - if (is_object($this->map_node)) - { - $childs = $this->map_node->child_nodes(); - foreach($childs as $child) - { - if ($child->node_name() == "MapCaption") - { - return $child->get_content(); - } - } - } - } + /** + * Get Caption. + * + * @return string Caption + */ + public function getCaption() + { + if (is_object($this->map_node)) { + $childs = $this->map_node->child_nodes(); + foreach ($childs as $child) { + if ($child->node_name() == "MapCaption") { + return $child->get_content(); + } + } + } + } - static function handleCaptionInput($a_text) - { - $a_text = str_replace(chr(13).chr(10),"
",$a_text); - $a_text = str_replace(chr(13),"
", $a_text); - $a_text = str_replace(chr(10),"
", $a_text); - - return $a_text; - } - - static function handleCaptionFormOutput($a_text) - { - $a_text = str_replace("
", "\n", $a_text); - $a_text = str_replace("
", "\n", $a_text); - - return $a_text; - } - - /** - * Modify page content after xsl - * - * @param string $a_output - * @return string - */ - function modifyPageContentPostXsl($a_html, $a_mode) - { - $c_pos = 0; - $start = strpos($a_html, "[[[[[Map;"); - if (is_int($start)) - { - $end = strpos($a_html, "]]]]]", $start); - } - $i = 1; - while ($end > 0) - { - $param = substr($a_html, $start + 9, $end - $start - 9); - - $param = explode(";", $param); - if (is_numeric($param[0]) && is_numeric($param[1]) && is_numeric($param[2])) - { - include_once("./Services/Maps/classes/class.ilMapUtil.php"); - $map_gui = ilMapUtil::getMapGUI(); - $map_gui->setMapId("map_".$i) - ->setLatitude($param[0]) - ->setLongitude($param[1]) - ->setZoom($param[2]) - ->setWidth($param[3]."px") - ->setHeight($param[4]."px") - ->setEnableTypeControl(true) - ->setEnableNavigationControl(true) - ->setEnableCentralMarker(true); - $h2 = substr($a_html, 0, $start). - $map_gui->getHtml(). - substr($a_html, $end + 5); - $a_html = $h2; - $i++; - } - $start = strpos($a_html, "[[[[[Map;", $start + 5); - $end = 0; - if (is_int($start)) - { - $end = strpos($a_html, "]]]]]", $start); - } - } - - return $a_html; - } + public static function handleCaptionInput($a_text) + { + $a_text = str_replace(chr(13) . chr(10), "
", $a_text); + $a_text = str_replace(chr(13), "
", $a_text); + $a_text = str_replace(chr(10), "
", $a_text); + + return $a_text; + } + + public static function handleCaptionFormOutput($a_text) + { + $a_text = str_replace("
", "\n", $a_text); + $a_text = str_replace("
", "\n", $a_text); + + return $a_text; + } + /** + * Modify page content after xsl + * + * @param string $a_output + * @return string + */ + public function modifyPageContentPostXsl($a_html, $a_mode) + { + $c_pos = 0; + $start = strpos($a_html, "[[[[[Map;"); + if (is_int($start)) { + $end = strpos($a_html, "]]]]]", $start); + } + $i = 1; + while ($end > 0) { + $param = substr($a_html, $start + 9, $end - $start - 9); + + $param = explode(";", $param); + if (is_numeric($param[0]) && is_numeric($param[1]) && is_numeric($param[2])) { + include_once("./Services/Maps/classes/class.ilMapUtil.php"); + $map_gui = ilMapUtil::getMapGUI(); + $map_gui->setMapId("map_" . $i) + ->setLatitude($param[0]) + ->setLongitude($param[1]) + ->setZoom($param[2]) + ->setWidth($param[3] . "px") + ->setHeight($param[4] . "px") + ->setEnableTypeControl(true) + ->setEnableNavigationControl(true) + ->setEnableCentralMarker(true); + $h2 = substr($a_html, 0, $start) . + $map_gui->getHtml() . + substr($a_html, $end + 5); + $a_html = $h2; + $i++; + } + $start = strpos($a_html, "[[[[[Map;", $start + 5); + $end = 0; + if (is_int($start)) { + $end = strpos($a_html, "]]]]]", $start); + } + } + + return $a_html; + } } - -?> diff --git a/Services/COPage/classes/class.ilPCMapGUI.php b/Services/COPage/classes/class.ilPCMapGUI.php index b916127324f7b72452f47d50be06ec5f8c7334bb..22da0a4ef2ca488bef5d93099c628f19cc52b237 100755 --- a/Services/COPage/classes/class.ilPCMapGUI.php +++ b/Services/COPage/classes/class.ilPCMapGUI.php @@ -1,24 +1,24 @@ 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); - } + $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); + /** + * 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(); + // get current command + $cmd = $this->ctrl->getCmd(); - switch($next_class) - { - default: - $ret = $this->$cmd(); - break; - } + switch ($next_class) { + default: + $ret = $this->$cmd(); + break; + } - return $ret; - } + return $ret; + } - /** - * Insert new map form. - */ - function insert() - { - $tpl = $this->tpl; - - $this->displayValidationError(); - $this->initForm("create"); - $tpl->setContent($this->form->getHTML()); - } + /** + * Insert new map form. + */ + public function insert() + { + $tpl = $this->tpl; + + $this->displayValidationError(); + $this->initForm("create"); + $tpl->setContent($this->form->getHTML()); + } - /** - * Edit map form. - */ - function edit($a_insert = false) - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - $this->displayValidationError(); - $this->initForm("update"); - $this->getValues(); - $tpl->setContent($this->form->getHTML()); + /** + * Edit map form. + */ + public function edit($a_insert = false) + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + $this->displayValidationError(); + $this->initForm("update"); + $this->getValues(); + $tpl->setContent($this->form->getHTML()); - return $ret; - } + return $ret; + } - /** - * Get values from object into form - */ - function getValues() - { - $values = array(); - - $values["location"]["latitude"] = $this->content_obj->getLatitude(); - $values["location"]["longitude"] = $this->content_obj->getLongitude(); - $values["location"]["zoom"] = $this->content_obj->getZoom(); - $values["width"] = $this->content_obj->getWidth(); - $values["height"] = $this->content_obj->getHeight(); - $values["caption"] = $this->content_obj->handleCaptionFormOutput($this->content_obj->getCaption()); - $values["horizontal_align"] = $this->content_obj->getHorizontalAlign(); - - $this->form->setValuesByArray($values); - } - - /** - * Init map creation/update form - */ - function initForm($a_mode) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - // edit form - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - $this->form->setFormAction($ilCtrl->getFormAction($this)); - if ($a_mode == "create") - { - $this->form->setTitle($this->lng->txt("cont_insert_map")); - } - else - { - $this->form->setTitle($this->lng->txt("cont_update_map")); - } - - // location - $loc_prop = new ilLocationInputGUI($this->lng->txt("cont_location"), - "location"); - $loc_prop->setRequired(true); - $this->form->addItem($loc_prop); - - // width - $width_prop = new ilNumberInputGUI($this->lng->txt("cont_width"), - "width"); - $width_prop->setSize(4); - $width_prop->setMaxLength(4); - $width_prop->setRequired(true); - $width_prop->setMinValue(250); - $this->form->addItem($width_prop); - - // height - $height_prop = new ilNumberInputGUI($this->lng->txt("cont_height"), - "height"); - $height_prop->setSize(4); - $height_prop->setMaxLength(4); - $height_prop->setRequired(true); - $height_prop->setMinValue(200); - $this->form->addItem($height_prop); + /** + * Get values from object into form + */ + public function getValues() + { + $values = array(); + + $values["location"]["latitude"] = $this->content_obj->getLatitude(); + $values["location"]["longitude"] = $this->content_obj->getLongitude(); + $values["location"]["zoom"] = $this->content_obj->getZoom(); + $values["width"] = $this->content_obj->getWidth(); + $values["height"] = $this->content_obj->getHeight(); + $values["caption"] = $this->content_obj->handleCaptionFormOutput($this->content_obj->getCaption()); + $values["horizontal_align"] = $this->content_obj->getHorizontalAlign(); + + $this->form->setValuesByArray($values); + } + + /** + * Init map creation/update form + */ + public function initForm($a_mode) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + // edit form + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + $this->form->setFormAction($ilCtrl->getFormAction($this)); + if ($a_mode == "create") { + $this->form->setTitle($this->lng->txt("cont_insert_map")); + } else { + $this->form->setTitle($this->lng->txt("cont_update_map")); + } + + // location + $loc_prop = new ilLocationInputGUI( + $this->lng->txt("cont_location"), + "location" + ); + $loc_prop->setRequired(true); + $this->form->addItem($loc_prop); + + // width + $width_prop = new ilNumberInputGUI( + $this->lng->txt("cont_width"), + "width" + ); + $width_prop->setSize(4); + $width_prop->setMaxLength(4); + $width_prop->setRequired(true); + $width_prop->setMinValue(250); + $this->form->addItem($width_prop); + + // height + $height_prop = new ilNumberInputGUI( + $this->lng->txt("cont_height"), + "height" + ); + $height_prop->setSize(4); + $height_prop->setMaxLength(4); + $height_prop->setRequired(true); + $height_prop->setMinValue(200); + $this->form->addItem($height_prop); - // horizonal align - $align_prop = new ilSelectInputGUI($this->lng->txt("cont_align"), - "horizontal_align"); - $options = array( - "Left" => $lng->txt("cont_left"), - "Center" => $lng->txt("cont_center"), - "Right" => $lng->txt("cont_right"), - "LeftFloat" => $lng->txt("cont_left_float"), - "RightFloat" => $lng->txt("cont_right_float")); - $align_prop->setOptions($options); - $this->form->addItem($align_prop); - - // caption - $caption_prop = new ilTextAreaInputGUI($this->lng->txt("cont_caption"), - "caption"); - $this->form->addItem($caption_prop); + // horizonal align + $align_prop = new ilSelectInputGUI( + $this->lng->txt("cont_align"), + "horizontal_align" + ); + $options = array( + "Left" => $lng->txt("cont_left"), + "Center" => $lng->txt("cont_center"), + "Right" => $lng->txt("cont_right"), + "LeftFloat" => $lng->txt("cont_left_float"), + "RightFloat" => $lng->txt("cont_right_float")); + $align_prop->setOptions($options); + $this->form->addItem($align_prop); + + // caption + $caption_prop = new ilTextAreaInputGUI( + $this->lng->txt("cont_caption"), + "caption" + ); + $this->form->addItem($caption_prop); - // save/cancel buttons - if ($a_mode == "create") - { - $this->form->addCommandButton("create_map", $lng->txt("save")); - $this->form->addCommandButton("cancelCreate", $lng->txt("cancel")); - } - else - { - $this->form->addCommandButton("update_map", $lng->txt("save")); - $this->form->addCommandButton("cancelUpdate", $lng->txt("cancel")); - } - //$html = $form->getHTML(); - } + // save/cancel buttons + if ($a_mode == "create") { + $this->form->addCommandButton("create_map", $lng->txt("save")); + $this->form->addCommandButton("cancelCreate", $lng->txt("cancel")); + } else { + $this->form->addCommandButton("update_map", $lng->txt("save")); + $this->form->addCommandButton("cancelUpdate", $lng->txt("cancel")); + } + //$html = $form->getHTML(); + } - /** - * Create new Map. - */ - function create() - { - $tpl = $this->tpl; - - $this->initForm("create"); - if ($this->form->checkInput()) - { - $this->content_obj = new ilPCMap($this->getPage()); - $location = $this->form->getInput("location"); - $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); - $this->content_obj->setLatitude($location["latitude"]); - $this->content_obj->setLongitude($location["longitude"]); - $this->content_obj->setZoom($location["zoom"]); - $this->content_obj->setLayout($this->form->getInput("width"), - $this->form->getInput("height"), - $this->form->getInput("horizontal_align")); - $this->content_obj->setCaption( - $this->content_obj->handleCaptionInput($this->form->getInput("caption"))); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - return; - } - } - $this->displayValidationError(); - $this->form->setValuesByPost(); - $tpl->setContent($this->form->getHTML()); - } + /** + * Create new Map. + */ + public function create() + { + $tpl = $this->tpl; + + $this->initForm("create"); + if ($this->form->checkInput()) { + $this->content_obj = new ilPCMap($this->getPage()); + $location = $this->form->getInput("location"); + $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); + $this->content_obj->setLatitude($location["latitude"]); + $this->content_obj->setLongitude($location["longitude"]); + $this->content_obj->setZoom($location["zoom"]); + $this->content_obj->setLayout( + $this->form->getInput("width"), + $this->form->getInput("height"), + $this->form->getInput("horizontal_align") + ); + $this->content_obj->setCaption( + $this->content_obj->handleCaptionInput($this->form->getInput("caption")) + ); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + return; + } + } + $this->displayValidationError(); + $this->form->setValuesByPost(); + $tpl->setContent($this->form->getHTML()); + } - /** - * Update Map. - */ - function update() - { - $tpl = $this->tpl; - - $this->initForm("update"); - if ($this->form->checkInput()) - { - $location = $this->form->getInput("location"); - $this->content_obj->setLatitude($location["latitude"]); - $this->content_obj->setLongitude($location["longitude"]); - $this->content_obj->setZoom($location["zoom"]); - $this->content_obj->setLayout($this->form->getInput("width"), - $this->form->getInput("height"), - $this->form->getInput("horizontal_align")); - $this->content_obj->setCaption( - $this->content_obj->handleCaptionInput($this->form->getInput("caption"))); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - return; - } - } - $this->displayValidationError(); - $this->form->setValuesByPost(); - $tpl->setContent($this->form->getHTML()); - } + /** + * Update Map. + */ + public function update() + { + $tpl = $this->tpl; + + $this->initForm("update"); + if ($this->form->checkInput()) { + $location = $this->form->getInput("location"); + $this->content_obj->setLatitude($location["latitude"]); + $this->content_obj->setLongitude($location["longitude"]); + $this->content_obj->setZoom($location["zoom"]); + $this->content_obj->setLayout( + $this->form->getInput("width"), + $this->form->getInput("height"), + $this->form->getInput("horizontal_align") + ); + $this->content_obj->setCaption( + $this->content_obj->handleCaptionInput($this->form->getInput("caption")) + ); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + return; + } + } + $this->displayValidationError(); + $this->form->setValuesByPost(); + $tpl->setContent($this->form->getHTML()); + } } -?> diff --git a/Services/COPage/classes/class.ilPCMediaObject.php b/Services/COPage/classes/class.ilPCMediaObject.php index 3cf78190b299f9a9f3d0b5d798a1a015eacd3e36..25fb89caab41e82c9e241db34d4b3390ac310aca 100755 --- a/Services/COPage/classes/class.ilPCMediaObject.php +++ b/Services/COPage/classes/class.ilPCMediaObject.php @@ -15,456 +15,437 @@ require_once("./Services/COPage/classes/class.ilPageContent.php"); */ class ilPCMediaObject extends ilPageContent { - /** - * @var ilObjUser - */ - protected $user; - - protected $mob_node; - - /** - * Init page content component. - */ - function init() - { - global $DIC; - - $this->user = $DIC->user(); - $this->setType("media"); - } - - /** - * Read/get Media Object - * - * @param int media object ID - */ - function readMediaObject($a_mob_id = 0) - { - if ($a_mob_id > 0) - { - $mob = new ilObjMediaObject($a_mob_id); - $this->setMediaObject($mob); - } - } - - function setNode($a_node) - { - parent::setNode($a_node); // this is the PageContent node - $this->mob_node = $a_node->first_child(); - } - - /** - * set dom object - */ - function setDom(&$a_dom) - { - $this->dom = $a_dom; - } - - /** - * set hierarchical edit id - */ - function setHierId($a_hier_id) - { - $this->hier_id = $a_hier_id; - } - - /** - * Set Media Object. - * - * @param object $a_mediaobject Media Object - */ - function setMediaObject($a_mediaobject) - { - $this->mediaobject = $a_mediaobject; - } - - /** - * Get Media Object. - * - * @return object Media Object - */ - function getMediaObject() - { - return $this->mediaobject; - } - - function createMediaObject() - { - $this->setMediaObject(new ilObjMediaObject()); - } - - /** - * Create pc media object - */ - function create(&$a_pg_obj, $a_hier_id) - { - $this->node = $this->createPageContentNode(); - } - - /** - * Create an media alias in page - * - * @param object $a_pg_obj page object - * @param string $a_hier_id hierarchical ID - w*/ - function createAlias(&$a_pg_obj, $a_hier_id, $a_pc_id = "") - { - $this->node = $this->dom->create_element("PageContent"); - $a_pg_obj->insertContent($this, $a_hier_id, IL_INSERT_AFTER, $a_pc_id); - $this->mob_node = $this->dom->create_element("MediaObject"); - $this->mob_node = $this->node->append_child($this->mob_node); - $this->mal_node = $this->dom->create_element("MediaAlias"); - $this->mal_node = $this->mob_node->append_child($this->mal_node); - $this->mal_node->set_attribute("OriginId", "il__mob_".$this->getMediaObject()->getId()); - - // standard view - $item_node = $this->dom->create_element("MediaAliasItem"); - $item_node = $this->mob_node->append_child($item_node); - $item_node->set_attribute("Purpose", "Standard"); - $media_item = $this->getMediaObject()->getMediaItem("Standard"); - - $layout_node = $this->dom->create_element("Layout"); - $layout_node = $item_node->append_child($layout_node); - if ($media_item->getWidth() > 0) - { - //$layout_node->set_attribute("Width", $media_item->getWidth()); - } - if ($media_item->getHeight() > 0) - { - //$layout_node->set_attribute("Height", $media_item->getHeight()); - } - $layout_node->set_attribute("HorizontalAlign", "Left"); - - // caption - if ($media_item->getCaption() != "") - { - $cap_node = $this->dom->create_element("Caption"); - $cap_node = $item_node->append_child($cap_node); - $cap_node->set_attribute("Align", "bottom"); - $cap_node->set_content($media_item->getCaption()); - } - - // text representation - if ($media_item->getTextRepresentation() != "") - { - $tr_node = $this->dom->create_element("TextRepresentation"); - $tr_node = $item_node->append_child($tr_node); - $tr_node->set_content($media_item->getTextRepresentation()); - } - - $pars = $media_item->getParameters(); - foreach($pars as $par => $val) - { - $par_node = $this->dom->create_element("Parameter"); - $par_node = $item_node->append_child($par_node); - $par_node->set_attribute("Name", $par); - $par_node->set_attribute("Value", $val); - } - - // fullscreen view - $fullscreen_item = $this->getMediaObject()->getMediaItem("Fullscreen"); - if (is_object($fullscreen_item)) - { - $item_node = $this->dom->create_element("MediaAliasItem"); - $item_node = $this->mob_node->append_child($item_node); - $item_node->set_attribute("Purpose", "Fullscreen"); - - // width and height - $layout_node = $this->dom->create_element("Layout"); - $layout_node = $item_node->append_child($layout_node); - if ($fullscreen_item->getWidth() > 0) - { - $layout_node->set_attribute("Width", $fullscreen_item->getWidth()); - } - if ($fullscreen_item->getHeight() > 0) - { - $layout_node->set_attribute("Height", $fullscreen_item->getHeight()); - } - - // caption - if ($fullscreen_item->getCaption() != "") - { - $cap_node = $this->dom->create_element("Caption"); - $cap_node = $item_node->append_child($cap_node); - $cap_node->set_attribute("Align", "bottom"); - $cap_node->set_content($fullscreen_item->getCaption()); - } - - // text representation - if ($fullscreen_item->getTextRepresentation() != "") - { - $tr_node = $this->dom->create_element("TextRepresentation"); - $tr_node = $item_node->append_child($tr_node); - $tr_node->set_content($fullscreen_item->getTextRepresentation()); - } - - $pars = $fullscreen_item->getParameters(); - foreach($pars as $par => $val) - { - $par_node = $this->dom->create_element("Parameter"); - $par_node = $item_node->append_child($par_node); - $par_node->set_attribute("Name", $par); - $par_node->set_attribute("Value", $val); - } - } - } - - /** - * Updates the media object referenced by the media alias. - * This makes only sense, after the media object has changed. - * (-> change object reference function) - */ - function updateObjectReference() - { - if (is_object($this->mob_node)) - { - $this->mal_node = $this->mob_node->first_child(); - if (is_object($this->mal_node) && $this->mal_node->node_name() == "MediaAlias") - { - $this->mal_node->set_attribute("OriginId", "il__mob_".$this->getMediaObject()->getId()); - } - } - } - - /** - * Dump node xml - */ - function dumpXML() - { - $xml = $this->dom->dump_node($this->node); - return $xml; - } - - /** - * Set Style Class of table - * - * @param string $a_class class - */ - function setClass($a_class) - { - if (is_object($this->mob_node)) - { - $mal_node = $this->mob_node->first_child(); - if (is_object($mal_node)) - { - if (!empty($a_class)) - { - $mal_node->set_attribute("Class", $a_class); - } - else - { - if ($mal_node->has_attribute("Class")) - { - $mal_node->remove_attribute("Class"); - } - } - } - } - } - - /** - * Get characteristic of section. - * - * @return string characteristic - */ - function getClass() - { - if (is_object($this->mob_node)) - { - $mal_node = $this->mob_node->first_child(); - if (is_object($mal_node)) - { - $class = $mal_node->get_attribute("Class"); - return $class; - } - } - } - - /** - * Get lang vars needed for editing - * @return array array of lang var keys - */ - static function getLangVars() - { - return array("pc_mob"); - } - - /** - * After page has been updated (or created) - * - * @param object $a_page page object - * @param DOMDocument $a_domdoc dom document - * @param string $a_xml xml - * @param bool $a_creation true on creation, otherwise false - */ - static function afterPageUpdate($a_page, DOMDocument $a_domdoc, $a_xml, $a_creation) - { - if (!$a_page->getImportMode()) - { - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $mob_ids = ilObjMediaObject::_getMobsOfObject( - $a_page->getParentType().":pg", $a_page->getId(), 0, $a_page->getLanguage()); - self::saveMobUsage($a_page, $a_domdoc); - foreach($mob_ids as $mob) // check, whether media object can be deleted - { - if (ilObject::_exists($mob) && ilObject::_lookupType($mob) == "mob") - { - $mob_obj = new ilObjMediaObject($mob); - $usages = $mob_obj->getUsages(false); - if (count($usages) == 0) // delete, if no usage exists - { - $mob_obj->delete(); - } - } - } - } - } - - /** - * Before page is being deleted - * - * @param object $a_page page object - */ - static function beforePageDelete($a_page) - { - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $mob_ids = ilObjMediaObject::_getMobsOfObject( - $a_page->getParentType().":pg", $a_page->getId(), 0, $a_page->getLanguage()); - - ilObjMediaObject::_deleteAllUsages($a_page->getParentType().":pg", $a_page->getId(), false, - $a_page->getLanguage()); - - foreach($mob_ids as $mob) // check, whether media object can be deleted - { - if (ilObject::_exists($mob) && ilObject::_lookupType($mob) == "mob") - { - $mob_obj = new ilObjMediaObject($mob); - $usages = $mob_obj->getUsages(false); - if (count($usages) == 0) // delete, if no usage exists - { - $mob_obj->delete(); - } - } - } - } - - /** - * After page history entry has been created - * - * @param object $a_page page object - * @param DOMDocument $a_old_domdoc old dom document - * @param string $a_old_xml old xml - * @param integer $a_old_nr history number - */ - static function afterPageHistoryEntry($a_page, DOMDocument $a_old_domdoc, $a_old_xml, $a_old_nr) - { - self::saveMobUsage($a_page, $a_old_domdoc, $a_old_nr); - } - - /** - * Save all usages of media objects (media aliases, media objects, internal links) - * - * @param string $a_xml xml data of page - */ - static function saveMobUsage($a_page, $a_domdoc, $a_old_nr = 0) - { - $usages = array(); - - // media aliases - $xpath = new DOMXPath($a_domdoc); - $nodes = $xpath->query('//MediaAlias'); - foreach($nodes as $node) - { - $id_arr = explode("_", $node->getAttribute("OriginId")); - $mob_id = $id_arr[count($id_arr) - 1]; - if ($mob_id > 0 && $id_arr[1] == "") - { - $usages[$mob_id] = true; - } - } - - // media objects - $xpath = new DOMXPath($a_domdoc); - $nodes = $xpath->query('//MediaObject/MetaData/General/Identifier'); - foreach($nodes as $node) - { - $mob_entry = $node->getAttribute("Entry"); - $mob_arr = explode("_", $mob_entry); - $mob_id = $mob_arr[count($mob_arr) - 1]; - if ($mob_id > 0 && $mob_arr[1] == "") - { - $usages[$mob_id] = true; - } - } - - // internal links - $xpath = new DOMXPath($a_domdoc); - $nodes = $xpath->query("//IntLink[@Type='MediaObject']"); - foreach($nodes as $node) - { - $mob_target = $node->getAttribute("Target"); - $mob_arr = explode("_", $mob_target); -//echo "
3
"; -//echo $mob_target."
"; -//var_dump($mob_arr); - $mob_id = $mob_arr[count($mob_arr) - 1]; - if ($mob_id > 0 && $mob_arr[1] == "") - { - $usages[$mob_id] = true; - } - } - - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - ilObjMediaObject::_deleteAllUsages($a_page->getParentType().":pg", $a_page->getId(), $a_old_nr, - $a_page->getLanguage()); - foreach($usages as $mob_id => $val) - { - // save usage, if object exists... - if (ilObject::_lookupType($mob_id) == "mob") - { - ilObjMediaObject::_saveUsage($mob_id, $a_page->getParentType().":pg", $a_page->getId(), $a_old_nr, - $a_page->getLanguage()); - } - } - - return $usages; - } - - /** - * Modify page content after xsl - * - * @param string $a_output - * @return string - */ - function modifyPageContentPostXsl($a_html, $a_mode) - { - $ilUser = $this->user; - - if ($a_mode == "offline") - { - $page = $this->getPage(); - - $mob_ids = ilObjMediaObject::_getMobsOfObject( - $page->getParentType().":pg", $page->getId(), 0, $page->getLanguage()); - foreach ($mob_ids as $mob_id) - { - $mob = new ilObjMediaObject($mob_id); - $srts = $mob->getSrtFiles(); - foreach ($srts as $srt) - { - if ($ilUser->getLanguage() == $srt["language"]) - { - $srt_content = file_get_contents(ilObjMediaObject::_getDirectory($mob->getId())."/".$srt["full_path"]); - $a_html = str_replace("[[[[[mobsubtitle;il__mob_".$mob->getId()."_Standard]]]]]", $srt_content, $a_html); - } - } - } - } - - return $a_html; - } - - + /** + * @var ilObjUser + */ + protected $user; + + protected $mob_node; + + /** + * Init page content component. + */ + public function init() + { + global $DIC; + + $this->user = $DIC->user(); + $this->setType("media"); + } + + /** + * Read/get Media Object + * + * @param int media object ID + */ + public function readMediaObject($a_mob_id = 0) + { + if ($a_mob_id > 0) { + $mob = new ilObjMediaObject($a_mob_id); + $this->setMediaObject($mob); + } + } + + public function setNode($a_node) + { + parent::setNode($a_node); // this is the PageContent node + $this->mob_node = $a_node->first_child(); + } + + /** + * set dom object + */ + public function setDom(&$a_dom) + { + $this->dom = $a_dom; + } + + /** + * set hierarchical edit id + */ + public function setHierId($a_hier_id) + { + $this->hier_id = $a_hier_id; + } + + /** + * Set Media Object. + * + * @param object $a_mediaobject Media Object + */ + public function setMediaObject($a_mediaobject) + { + $this->mediaobject = $a_mediaobject; + } + + /** + * Get Media Object. + * + * @return object Media Object + */ + public function getMediaObject() + { + return $this->mediaobject; + } + + public function createMediaObject() + { + $this->setMediaObject(new ilObjMediaObject()); + } + + /** + * Create pc media object + */ + public function create(&$a_pg_obj, $a_hier_id) + { + $this->node = $this->createPageContentNode(); + } + + /** + * Create an media alias in page + * + * @param object $a_pg_obj page object + * @param string $a_hier_id hierarchical ID + w*/ + public function createAlias(&$a_pg_obj, $a_hier_id, $a_pc_id = "") + { + $this->node = $this->dom->create_element("PageContent"); + $a_pg_obj->insertContent($this, $a_hier_id, IL_INSERT_AFTER, $a_pc_id); + $this->mob_node = $this->dom->create_element("MediaObject"); + $this->mob_node = $this->node->append_child($this->mob_node); + $this->mal_node = $this->dom->create_element("MediaAlias"); + $this->mal_node = $this->mob_node->append_child($this->mal_node); + $this->mal_node->set_attribute("OriginId", "il__mob_" . $this->getMediaObject()->getId()); + + // standard view + $item_node = $this->dom->create_element("MediaAliasItem"); + $item_node = $this->mob_node->append_child($item_node); + $item_node->set_attribute("Purpose", "Standard"); + $media_item = $this->getMediaObject()->getMediaItem("Standard"); + + $layout_node = $this->dom->create_element("Layout"); + $layout_node = $item_node->append_child($layout_node); + if ($media_item->getWidth() > 0) { + //$layout_node->set_attribute("Width", $media_item->getWidth()); + } + if ($media_item->getHeight() > 0) { + //$layout_node->set_attribute("Height", $media_item->getHeight()); + } + $layout_node->set_attribute("HorizontalAlign", "Left"); + + // caption + if ($media_item->getCaption() != "") { + $cap_node = $this->dom->create_element("Caption"); + $cap_node = $item_node->append_child($cap_node); + $cap_node->set_attribute("Align", "bottom"); + $cap_node->set_content($media_item->getCaption()); + } + + // text representation + if ($media_item->getTextRepresentation() != "") { + $tr_node = $this->dom->create_element("TextRepresentation"); + $tr_node = $item_node->append_child($tr_node); + $tr_node->set_content($media_item->getTextRepresentation()); + } + + $pars = $media_item->getParameters(); + foreach ($pars as $par => $val) { + $par_node = $this->dom->create_element("Parameter"); + $par_node = $item_node->append_child($par_node); + $par_node->set_attribute("Name", $par); + $par_node->set_attribute("Value", $val); + } + + // fullscreen view + $fullscreen_item = $this->getMediaObject()->getMediaItem("Fullscreen"); + if (is_object($fullscreen_item)) { + $item_node = $this->dom->create_element("MediaAliasItem"); + $item_node = $this->mob_node->append_child($item_node); + $item_node->set_attribute("Purpose", "Fullscreen"); + + // width and height + $layout_node = $this->dom->create_element("Layout"); + $layout_node = $item_node->append_child($layout_node); + if ($fullscreen_item->getWidth() > 0) { + $layout_node->set_attribute("Width", $fullscreen_item->getWidth()); + } + if ($fullscreen_item->getHeight() > 0) { + $layout_node->set_attribute("Height", $fullscreen_item->getHeight()); + } + + // caption + if ($fullscreen_item->getCaption() != "") { + $cap_node = $this->dom->create_element("Caption"); + $cap_node = $item_node->append_child($cap_node); + $cap_node->set_attribute("Align", "bottom"); + $cap_node->set_content($fullscreen_item->getCaption()); + } + + // text representation + if ($fullscreen_item->getTextRepresentation() != "") { + $tr_node = $this->dom->create_element("TextRepresentation"); + $tr_node = $item_node->append_child($tr_node); + $tr_node->set_content($fullscreen_item->getTextRepresentation()); + } + + $pars = $fullscreen_item->getParameters(); + foreach ($pars as $par => $val) { + $par_node = $this->dom->create_element("Parameter"); + $par_node = $item_node->append_child($par_node); + $par_node->set_attribute("Name", $par); + $par_node->set_attribute("Value", $val); + } + } + } + + /** + * Updates the media object referenced by the media alias. + * This makes only sense, after the media object has changed. + * (-> change object reference function) + */ + public function updateObjectReference() + { + if (is_object($this->mob_node)) { + $this->mal_node = $this->mob_node->first_child(); + if (is_object($this->mal_node) && $this->mal_node->node_name() == "MediaAlias") { + $this->mal_node->set_attribute("OriginId", "il__mob_" . $this->getMediaObject()->getId()); + } + } + } + + /** + * Dump node xml + */ + public function dumpXML() + { + $xml = $this->dom->dump_node($this->node); + return $xml; + } + + /** + * Set Style Class of table + * + * @param string $a_class class + */ + public function setClass($a_class) + { + if (is_object($this->mob_node)) { + $mal_node = $this->mob_node->first_child(); + if (is_object($mal_node)) { + if (!empty($a_class)) { + $mal_node->set_attribute("Class", $a_class); + } else { + if ($mal_node->has_attribute("Class")) { + $mal_node->remove_attribute("Class"); + } + } + } + } + } + + /** + * Get characteristic of section. + * + * @return string characteristic + */ + public function getClass() + { + if (is_object($this->mob_node)) { + $mal_node = $this->mob_node->first_child(); + if (is_object($mal_node)) { + $class = $mal_node->get_attribute("Class"); + return $class; + } + } + } + + /** + * Get lang vars needed for editing + * @return array array of lang var keys + */ + public static function getLangVars() + { + return array("pc_mob"); + } + + /** + * After page has been updated (or created) + * + * @param object $a_page page object + * @param DOMDocument $a_domdoc dom document + * @param string $a_xml xml + * @param bool $a_creation true on creation, otherwise false + */ + public static function afterPageUpdate($a_page, DOMDocument $a_domdoc, $a_xml, $a_creation) + { + if (!$a_page->getImportMode()) { + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $mob_ids = ilObjMediaObject::_getMobsOfObject( + $a_page->getParentType() . ":pg", + $a_page->getId(), + 0, + $a_page->getLanguage() + ); + self::saveMobUsage($a_page, $a_domdoc); + foreach ($mob_ids as $mob) { // check, whether media object can be deleted + if (ilObject::_exists($mob) && ilObject::_lookupType($mob) == "mob") { + $mob_obj = new ilObjMediaObject($mob); + $usages = $mob_obj->getUsages(false); + if (count($usages) == 0) { // delete, if no usage exists + $mob_obj->delete(); + } + } + } + } + } + + /** + * Before page is being deleted + * + * @param object $a_page page object + */ + public static function beforePageDelete($a_page) + { + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $mob_ids = ilObjMediaObject::_getMobsOfObject( + $a_page->getParentType() . ":pg", + $a_page->getId(), + 0, + $a_page->getLanguage() + ); + + ilObjMediaObject::_deleteAllUsages( + $a_page->getParentType() . ":pg", + $a_page->getId(), + false, + $a_page->getLanguage() + ); + + foreach ($mob_ids as $mob) { // check, whether media object can be deleted + if (ilObject::_exists($mob) && ilObject::_lookupType($mob) == "mob") { + $mob_obj = new ilObjMediaObject($mob); + $usages = $mob_obj->getUsages(false); + if (count($usages) == 0) { // delete, if no usage exists + $mob_obj->delete(); + } + } + } + } + + /** + * After page history entry has been created + * + * @param object $a_page page object + * @param DOMDocument $a_old_domdoc old dom document + * @param string $a_old_xml old xml + * @param integer $a_old_nr history number + */ + public static function afterPageHistoryEntry($a_page, DOMDocument $a_old_domdoc, $a_old_xml, $a_old_nr) + { + self::saveMobUsage($a_page, $a_old_domdoc, $a_old_nr); + } + + /** + * Save all usages of media objects (media aliases, media objects, internal links) + * + * @param string $a_xml xml data of page + */ + public static function saveMobUsage($a_page, $a_domdoc, $a_old_nr = 0) + { + $usages = array(); + + // media aliases + $xpath = new DOMXPath($a_domdoc); + $nodes = $xpath->query('//MediaAlias'); + foreach ($nodes as $node) { + $id_arr = explode("_", $node->getAttribute("OriginId")); + $mob_id = $id_arr[count($id_arr) - 1]; + if ($mob_id > 0 && $id_arr[1] == "") { + $usages[$mob_id] = true; + } + } + + // media objects + $xpath = new DOMXPath($a_domdoc); + $nodes = $xpath->query('//MediaObject/MetaData/General/Identifier'); + foreach ($nodes as $node) { + $mob_entry = $node->getAttribute("Entry"); + $mob_arr = explode("_", $mob_entry); + $mob_id = $mob_arr[count($mob_arr) - 1]; + if ($mob_id > 0 && $mob_arr[1] == "") { + $usages[$mob_id] = true; + } + } + + // internal links + $xpath = new DOMXPath($a_domdoc); + $nodes = $xpath->query("//IntLink[@Type='MediaObject']"); + foreach ($nodes as $node) { + $mob_target = $node->getAttribute("Target"); + $mob_arr = explode("_", $mob_target); + //echo "
3
"; + //echo $mob_target."
"; + //var_dump($mob_arr); + $mob_id = $mob_arr[count($mob_arr) - 1]; + if ($mob_id > 0 && $mob_arr[1] == "") { + $usages[$mob_id] = true; + } + } + + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + ilObjMediaObject::_deleteAllUsages( + $a_page->getParentType() . ":pg", + $a_page->getId(), + $a_old_nr, + $a_page->getLanguage() + ); + foreach ($usages as $mob_id => $val) { + // save usage, if object exists... + if (ilObject::_lookupType($mob_id) == "mob") { + ilObjMediaObject::_saveUsage( + $mob_id, + $a_page->getParentType() . ":pg", + $a_page->getId(), + $a_old_nr, + $a_page->getLanguage() + ); + } + } + + return $usages; + } + + /** + * Modify page content after xsl + * + * @param string $a_output + * @return string + */ + public function modifyPageContentPostXsl($a_html, $a_mode) + { + $ilUser = $this->user; + + if ($a_mode == "offline") { + $page = $this->getPage(); + + $mob_ids = ilObjMediaObject::_getMobsOfObject( + $page->getParentType() . ":pg", + $page->getId(), + 0, + $page->getLanguage() + ); + foreach ($mob_ids as $mob_id) { + $mob = new ilObjMediaObject($mob_id); + $srts = $mob->getSrtFiles(); + foreach ($srts as $srt) { + if ($ilUser->getLanguage() == $srt["language"]) { + $srt_content = file_get_contents(ilObjMediaObject::_getDirectory($mob->getId()) . "/" . $srt["full_path"]); + $a_html = str_replace("[[[[[mobsubtitle;il__mob_" . $mob->getId() . "_Standard]]]]]", $srt_content, $a_html); + } + } + } + } + + return $a_html; + } } -?> diff --git a/Services/COPage/classes/class.ilPCMediaObjectGUI.php b/Services/COPage/classes/class.ilPCMediaObjectGUI.php index 314cc8be3a6abfdf246f31fb6964b7bf8d075b0c..20e50be6cdc9f215efedba50e46d8997f447dccf 100755 --- a/Services/COPage/classes/class.ilPCMediaObjectGUI.php +++ b/Services/COPage/classes/class.ilPCMediaObjectGUI.php @@ -1,9 +1,9 @@ tpl = $DIC["tpl"]; - $this->lng = $DIC->language(); - $this->tabs = $DIC->tabs(); - $this->access = $DIC->access(); - $this->toolbar = $DIC->toolbar(); - $this->user = $DIC->user(); - $ilCtrl = $DIC->ctrl(); - $this->ui = $DIC->ui(); - - $this->pool_view = "folder"; - if (in_array($_GET["pool_view"], array("folder", "all"))) - { - $this->pool_view = $_GET["pool_view"]; - } - - $this->ctrl = $ilCtrl; - - $this->ctrl->saveParameter($this, "pool_view"); - -// var_dump($_POST); -//ilUtil::printBacktrace(10); exit; -//echo "constructor target:".$_SESSION["il_map_il_target"].":
"; - parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); - - $this->setCharacteristics(array( - "MediaContainer" => $this->lng->txt("cont_Media"), - "MediaContainerMax50" => "MediaContainerMax50", - "MediaContainerFull100" => "MediaContainerFull100", - "MediaContainerHighlighted" => "MediaContainerHighlighted", - "MediaContainerSeparated" => "MediaContainerSeparated" - )); - - } - - /** - * Set table sub command - * - * @param string $a_val command - */ - function setSubCmd($a_val) - { - $this->sub_cmd = $a_val; - } - - /** - * Get table sub command - * - * @return string command - */ - function getSubCmd() - { - return $this->sub_cmd; - } - - - function setHeader($a_title = "") - { - $this->header = $a_title; - } - - function getHeader() - { - return $this->header; - } - - /** - * Set Enable map areas. - * - * @param boolean $a_enabledmapareas Enable map areas - */ - function setEnabledMapAreas($a_enabledmapareas) - { - $this->enabledmapareas = $a_enabledmapareas; - } - - /** - * Get Enable map areas. - * - * @return boolean Enable map areas - */ - function getEnabledMapAreas() - { - return $this->enabledmapareas; - } - - /** - * execute command - */ - function executeCommand() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilTabs = $this->tabs; - - $this->getCharacteristicsOfCurrentStyle("media_cont"); // scorm-2004 - - // get next class that processes or forwards current command - $next_class = $this->ctrl->getNextClass($this); - - // get current command - $cmd = $this->ctrl->getCmd(); - if (is_object ($this->content_obj)) - { - $this->tpl->clearHeader(); - $tpl->setTitleIcon(ilUtil::getImagePath("icon_mob.svg")); - $this->getTabs($this->tabs_gui); - - $mob = $this->content_obj->getMediaObject(); - if (is_object($mob)) - { - $tpl->setVariable("HEADER", $lng->txt("mob").": ". - $this->content_obj->getMediaObject()->getTitle()); - $mob_gui = new ilObjMediaObjectGUI("", $this->content_obj->getMediaObject()->getId(),false, false); - $mob_gui->setBackTitle($this->page_back_title); - $mob_gui->setEnabledMapAreas($this->getEnabledMapAreas()); - $mob_gui->getTabs($this->tabs_gui); - } - } - else - { - } - - switch($next_class) - { - case "ilobjmediaobjectgui": - include_once ("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); - $this->tpl->clearHeader(); - $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_mob.svg")); - $this->tpl->setTitle($this->lng->txt("mob").": ". - $this->content_obj->getMediaObject()->getTitle()); - $mob_gui = new ilObjMediaObjectGUI("", $this->content_obj->getMediaObject()->getId(),false, false); - $mob_gui->setBackTitle($this->page_back_title); - $mob_gui->setEnabledMapAreas($this->getEnabledMapAreas()); - $ret = $this->ctrl->forwardCommand($mob_gui); - break; - - // instance image map editing - case "ilpcimagemapeditorgui": - require_once("./Services/COPage/classes/class.ilPCImageMapEditorGUI.php"); - $ilTabs->setTabActive("cont_inst_map_areas"); - $image_map_edit = new ilPCImageMapEditorGUI($this->content_obj, - $this->pg_obj); - $ret = $this->ctrl->forwardCommand($image_map_edit); - $tpl->setContent($ret); - $this->checkFixSize(); - break; - - default: - $ret = $this->$cmd(); - break; - } - - return $ret; - } - - /** - * Insert new media object form. - */ - function insert($a_post_cmd = "edpost", $a_submit_cmd = "create_mob", $a_input_error = false) - { - $ilTabs = $this->tabs; - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if ($_GET["subCmd"] == "insertNew") - { - $_SESSION["cont_media_insert"] = "insertNew"; - } - if ($_GET["subCmd"] == "insertFromPool") - { - $_SESSION["cont_media_insert"] = "insertFromPool"; - } - - if (($_GET["subCmd"] == "") && $_SESSION["cont_media_insert"] != "") - { - $_GET["subCmd"] = $_SESSION["cont_media_insert"]; - } - - switch ($_GET["subCmd"]) - { - case "insertFromPool": - $this->insertFromPool(); - break; - - case "poolSelection": - $this->poolSelection(); - break; - - case "selectPool": - $this->selectPool(); - break; - - case "insertNew": - default: - $this->getTabs($ilTabs, true); - $ilTabs->setSubTabActive("cont_new_mob"); - - include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); - if ($a_input_error) - { - $form = $this->form; - } - else - { - $mob_gui = new ilObjMediaObjectGUI(""); - $mob_gui->initForm("create"); - $form = $mob_gui->getForm(); - } - $form->setFormAction($ilCtrl->getFormAction($this, "create_mob")); - $form->clearCommandButtons(); - $form->addCommandButton("create_mob", $lng->txt("save")); - $form->addCommandButton("cancelCreate", $lng->txt("cancel")); - - $this->displayValidationError(); - - $tpl->setContent($form->getHTML()); - - break; - } - } - - /** - * Change object reference - */ - function changeObjectReference() - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if ($_GET["subCmd"] == "insertNew") - { - $_SESSION["cont_media_insert"] = "insertNew"; - } - if ($_GET["subCmd"] == "insertFromPool") - { - $_SESSION["cont_media_insert"] = "insertFromPool"; - } - - if (($_GET["subCmd"] == "") && $_SESSION["cont_media_insert"] != "") - { - $_GET["subCmd"] = $_SESSION["cont_media_insert"]; - } - - switch ($_GET["subCmd"]) - { - case "insertFromPool": - $this->insertFromPool(true); - break; - - case "poolSelection": - $this->poolSelection(true); - break; - - case "selectPool": - $this->selectPool(true); - break; - - case "insertNew": - default: - $ilCtrl->setParameter($this, "subCmd", "changeObjectReference"); - $this->getTabs($ilTabs, true, true); - $ilTabs->setSubTabActive("cont_new_mob"); - - $this->displayValidationError(); - - $mob_gui = new ilObjMediaObjectGUI(""); - $mob_gui->initForm("create"); - $form = $mob_gui->getForm(); - $form->setFormAction($ilCtrl->getFormAction($this)); - $form->clearCommandButtons(); - $form->addCommandButton("createNewObjectReference", $lng->txt("save")); - $form->addCommandButton("cancelCreate", $lng->txt("cancel")); - $this->tpl->setContent($form->getHTML()); - } - } - - - /** - * Check fix size - */ - protected function checkFixSize() - { - $std_alias_item = new ilMediaAliasItem($this->dom, $this->getHierId(), "Standard", - $this->content_obj->getPcId()); - $std_item = $this->content_obj->getMediaObject()->getMediaItem("Standard"); - - $ok = false; - if (($std_alias_item->getWidth() != "" && $std_alias_item->getHeight() != "")) - { - $ok = true; - } - if ($std_alias_item->getWidth() == "" && $std_alias_item->getHeight() == "" - && $std_item->getWidth() != "" && $std_item->getHeight() != "") - { - $ok = true; - } - - if (!$ok) - { - ilUtil::sendFailure($this->lng->txt("mob_no_fixed_size_map_editing")); - } - } - - /** - * Insert media object from pool - */ - function insertFromPool($a_change_obj_ref = false) - { - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - $ilTabs = $this->tabs; - $tpl = $this->tpl; - $lng = $this->lng; - $ui = $this->ui; - - 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(); - - // button: select pool - $ilCtrl->setParameter($this, "subCmd", "poolSelection"); - if ($a_change_obj_ref) - { - $tb->addButton($lng->txt("cont_switch_to_media_pool"), - $ilCtrl->getLinkTarget($this, "changeObjectReference")); - } - else - { - $tb->addButton($lng->txt("cont_switch_to_media_pool"), - $ilCtrl->getLinkTarget($this, "insert")); - - } - $ilCtrl->setParameter($this, "subCmd", ""); - - // view mode: pool view (folders/all media objects) - $f = $ui->factory(); - $tcmd = ($a_change_obj_ref) - ? "changeObjectReference" - : "insert"; - $lng->loadLanguageModule("mep"); - $ilCtrl->setParameter($this, "pool_view", "folder"); - $actions[$lng->txt("folders")] = $ilCtrl->getLinkTarget($this, $tcmd); - $ilCtrl->setParameter($this, "pool_view", "all"); - $actions[$lng->txt("mep_all_mobs")] = $ilCtrl->getLinkTarget($this, $tcmd); - $ilCtrl->setParameter($this, "pool_view", $this->pool_view); - $aria_label = $lng->txt("cont_change_pool_view"); - $view_control = $f->viewControl()->mode($actions, $aria_label)->withActive(($this->pool_view == "folder") - ? $lng->txt("folders") : $lng->txt("mep_all_mobs")); - $tb->addSeparator(); - $tb->addComponent($view_control); - - $html = $tb->getHTML(); - - $this->getTabs($ilTabs, true, $a_change_obj_ref); - $ilTabs->setSubTabActive("cont_mob_from_media_pool"); - - - - - 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"); - $tcmd = ($a_change_obj_ref) - ? "changeObjectReference" - : "insert"; - $tmode = ($a_change_obj_ref) - ? ilMediaPoolTableGUI::IL_MEP_SELECT_SINGLE - : ilMediaPoolTableGUI::IL_MEP_SELECT; - - // handle table sub commands and get the table - if ($this->getSubCmd() == "applyFilter") - { - $mpool_table = new ilMediaPoolTableGUI($this, $tcmd, $pool, "mep_folder", - $tmode, $this->pool_view == "all"); - $mpool_table->resetOffset(); - $mpool_table->writeFilterToSession(); - } - if ($this->getSubCmd() == "resetFilter") - { - $mpool_table = new ilMediaPoolTableGUI($this, $tcmd, $pool, "mep_folder", - $tmode, $this->pool_view == "all"); - $mpool_table->resetOffset(); - $mpool_table->resetFilter(); - } - $mpool_table = new ilMediaPoolTableGUI($this, $tcmd, $pool, "mep_folder", - $tmode, $this->pool_view == "all"); - - $html.= $mpool_table->getHTML(); - - $tpl->setContent($html); - } - else - { - $this->poolSelection($a_change_obj_ref); - } - } - - /** - * Select concrete pool - */ - function selectPool($a_change_obj_ref = false) - { - $ilCtrl = $this->ctrl; - - $_SESSION["cont_media_pool"] = $_GET["pool_ref_id"]; - $ilCtrl->setParameter($this, "subCmd", "insertFromPool"); - if ($a_change_obj_ref) - { - $ilCtrl->redirect($this, "changeObjectReference"); - } - else - { - $ilCtrl->redirect($this, "insert"); - } - } - - /** - * Pool Selection - */ - function poolSelection($a_change_obj_ref = false) - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - - $this->getTabs($ilTabs, true, $a_change_obj_ref); - $ilTabs->setSubTabActive("cont_mob_from_media_pool"); - - include_once "./Services/COPage/classes/class.ilPoolSelectorGUI.php"; - - if ($a_change_obj_ref) - { - $ilCtrl->setParameter($this, "subCmd", "poolSelection"); - $exp = new ilPoolSelectorGUI($this, "changeObjectReference", $this, "changeObjectReference"); - } - else - { - $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 media object and replace currrent media item with it. - * (keep all instance parameters) - */ - function createNewObjectReference() - { - $this->create(false, true); - } - - /** - * Create new media object and replace currrent media item with it. - * (keep all instance parameters) - */ - function selectObjectReference() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - if (is_array($_POST["id"]) && count($_POST["id"]) == 1) - { - include_once("./Services/COPage/classes/class.ilPCMediaObject.php"); - include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); - $fid = ilMediaPoolItem::lookupForeignId($_POST["id"][0]); - $this->content_obj->readMediaObject($fid); - $this->content_obj->updateObjectReference(); - $this->updated = $this->pg_obj->update(); - } - else - { - ilUtil::sendInfo($lng->txt("cont_select_max_one_item"), true); - $ilCtrl->redirect($this, "changeObjectReference"); - - } - $ilCtrl->redirect($this, "editAlias"); - } - - /** - * create new media object in dom and update page in db - */ - function &create($a_create_alias = true, $a_change_obj_ref = false) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if ($_GET["subCmd"] == "insertFromPool") - { - if (is_array($_POST["id"])) - { - for($i = count($_POST["id"]) - 1; $i>=0; $i--) - { - include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); - $fid = ilMediaPoolItem::lookupForeignId($_POST["id"][$i]); - include_once("./Services/COPage/classes/class.ilPCMediaObject.php"); - $this->content_obj = new ilPCMediaObject($this->getPage()); - $this->content_obj->readMediaObject($fid); - $this->content_obj->createAlias($this->pg_obj, $_GET["hier_id"], $this->pc_id); - } - $this->updated = $this->pg_obj->update(); - } - - $ilCtrl->returnToParent($this); - } - - // check form input - $mob_gui = new ilObjMediaObjectGUI(""); - $mob_gui->initForm("create"); - - if (!$mob_gui->checkFormInput()) - { - $this->form = $mob_gui->getForm(); - $this->insert("edpost", "create_mob", true); - return; - } - // create dummy object in db (we need an id) - include_once("./Services/COPage/classes/class.ilPCMediaObject.php"); - if ($a_change_obj_ref != true) - { - $this->content_obj = new ilPCMediaObject($this->getPage()); - } - $this->content_obj->createMediaObject(); - $media_obj = $this->content_obj->getMediaObject(); - - include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); - ilObjMediaObjectGUI::setObjectPerCreationForm($media_obj); - - if ($a_create_alias) - { - // need a pcmediaobject here - //$this->node = $this->createPageContentNode(); - - $this->content_obj->createAlias($this->pg_obj, $this->hier_id, $this->pc_id); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->pg_obj->stripHierIDs(); - $this->pg_obj->addHierIDs(); - $ilCtrl->setParameter($this, "hier_id", $this->content_obj->readHierId()); - $ilCtrl->setParameter($this, "pc_id", $this->content_obj->readPCId()); - $this->content_obj->setHierId($this->content_obj->readHierId()); - $this->setHierId($this->content_obj->readHierId()); - $this->content_obj->setPCId($this->content_obj->readPCId()); - ilUtil::sendSuccess($lng->txt("saved_media_object"), true); - $this->ctrl->redirectByClass("ilobjmediaobjectgui", "edit"); - - //$this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - else - { - $this->insert(); - } - } - else - { - if ($a_change_obj_ref == true) - { - $this->content_obj->updateObjectReference(); - $this->updated = $this->pg_obj->update(); - $this->ctrl->redirect($this, "editAlias"); - } - return $this->content_obj; - } - } - - - /** - * edit properties form - */ - function editAlias() - { - $tpl = $this->tpl; - - $this->initAliasForm(); - $this->getAliasValues(); - $tpl->setContent($this->form_gui->getHTML()); - } - - /** - * Init alias form - */ - function initAliasForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - - $this->form_gui = new ilPropertyFormGUI(); - - // standard view resource - $std_alias_item = new ilMediaAliasItem($this->dom, $this->getHierId(), "Standard", - $this->content_obj->getPcId()); - $std_item = $this->content_obj->getMediaObject()->getMediaItem("Standard"); - - // title, location and format - $title = new ilNonEditableValueGUI($lng->txt("title"), "title"); - $this->form_gui->addItem($title); - $loc = new ilNonEditableValueGUI( - $this->lng->txt("cont_".strtolower($std_item->getLocationType())), "st_location"); - $this->form_gui->addItem($loc); - $format = new ilNonEditableValueGUI( - $this->lng->txt("cont_format"), "st_format"); - $this->form_gui->addItem($format); - - // standard size - $radio_size = new ilRadioGroupInputGUI($lng->txt("size"), "st_derive_size"); - $orig_size = $std_item->getOriginalSize(); - $add_str = ($orig_size["width"] != "" && $orig_size["height"] != "") - ? " (".$orig_size["width"]." x ".$orig_size["height"].")" - : ""; - $op1 = new ilRadioOption($lng->txt("cont_default").$add_str, "y"); - $op2 = new ilRadioOption($lng->txt("cont_custom"), "n"); - $radio_size->addOption($op1); - - // width height - include_once("./Services/MediaObjects/classes/class.ilWidthHeightInputGUI.php"); - $width_height = new ilWidthHeightInputGUI($lng->txt("cont_width"). - " / ".$lng->txt("cont_height"), "st_width_height"); - $width_height->setConstrainProportions(true); - $op2->addSubItem($width_height); - - $radio_size->addOption($op2); - $this->form_gui->addItem($radio_size); - - // standard caption - $rad_caption = new ilRadioGroupInputGUI($lng->txt("cont_caption"), "st_derive_caption"); - $op1 = new ilRadioOption($lng->txt("cont_default"), "y"); - $def_cap = new ilNonEditableValueGUI("", "def_caption"); - $op1->addSubItem($def_cap); - $op2 = new ilRadioOption($lng->txt("cont_custom"), "n"); - $rad_caption->addOption($op1); - - $caption = new ilTextAreaInputGUI("", "st_caption"); - $caption->setCols(30); - $caption->setRows(2); - $op2->addSubItem($caption); - - /*$caption = new ilTextInputGUI("", "st_caption"); - $caption->setSize(40); - $caption->setMaxLength(200); - $op2->addSubItem($caption);*/ - $rad_caption->addOption($op2); - $this->form_gui->addItem($rad_caption); - - // standard text representation - if (substr($std_item->getFormat(), 0, 5) == "image") - { - $rad_tr = new ilRadioGroupInputGUI($lng->txt("text_repr"), "st_derive_text_representation"); - $op1 = new ilRadioOption($lng->txt("cont_default"), "y"); - $def_tr = new ilNonEditableValueGUI("", "def_text_representation"); - $op1->addSubItem($def_tr); - $op2 = new ilRadioOption($lng->txt("cont_custom"), "n"); - $tr = new ilTextAreaInputGUI("", "st_text_representation"); - $tr->setCols(30); - $tr->setRows(2); - $rad_tr->addOption($op1); - $op2->addSubItem($tr); - $rad_tr->addOption($op2); - $this->form_gui->addItem($rad_tr); - $rad_tr->setInfo($lng->txt("text_repr_info")); - } - - // standard parameters - if (!in_array($std_item->getFormat(), ilObjMediaObject::_getSimpleMimeTypes())) - { - if (ilObjMediaObject::_useAutoStartParameterOnly($std_item->getLocation(), - $std_item->getFormat())) // autostart - { - $par = $std_item->getParameters(); - $def_str = ($par["autostart"] == "true") - ? " (".$lng->txt("yes").")" - : " (".$lng->txt("no").")"; - $rad_auto = new ilRadioGroupInputGUI($lng->txt("cont_autostart"), - "st_derive_parameters"); - $op1 = new ilRadioOption($lng->txt("cont_default").$def_str, "y"); - $rad_auto->addOption($op1); - $op2 = new ilRadioOption($lng->txt("cont_custom"), "n"); - $auto = new ilCheckboxInputGUI($lng->txt("enabled"), "st_autostart"); - $op2->addSubItem($auto); - $rad_auto->addOption($op2); - $this->form_gui->addItem($rad_auto); - } - else // parameters - { - $rad_parameters = new ilRadioGroupInputGUI($lng->txt("cont_parameter"), "st_derive_parameters"); - $op1 = new ilRadioOption($lng->txt("cont_default"), "y"); - $def_par = new ilNonEditableValueGUI("", "def_parameters"); - $op1->addSubItem($def_par); - $rad_parameters->addOption($op1); - $op2 = new ilRadioOption($lng->txt("cont_custom"), "n"); - $par = new ilTextAreaInputGUI("", "st_parameters"); - $par->setRows(5); - $par->setCols(50); - $op2->addSubItem($par); - $rad_parameters->addOption($op2); - $this->form_gui->addItem($rad_parameters); - } - } - - // fullscreen view - if($this->content_obj->getMediaObject()->hasFullScreenItem()) - { - $full_alias_item = new ilMediaAliasItem($this->dom, $this->getHierId(), "Fullscreen", - $this->content_obj->getPcId()); - $full_item = $this->content_obj->getMediaObject()->getMediaItem("Fullscreen"); - - $fs_sec = new ilFormSectionHeaderGUI(); - $fs_sec->setTitle($lng->txt("cont_fullscreen")); - $this->form_gui->addItem($fs_sec); - - - // resource - $radio_prop = new ilRadioGroupInputGUI($lng->txt("cont_resource"), "fullscreen"); - $op1 = new ilRadioOption($lng->txt("cont_none"), "n"); - $radio_prop->addOption($op1); - $op2 = new ilRadioOption($this->lng->txt("cont_".strtolower($full_item->getLocationType())).": ". - $full_item->getLocation(), "y"); - $radio_prop->addOption($op2); - $this->form_gui->addItem($radio_prop); - - // format - $format = new ilNonEditableValueGUI( - $this->lng->txt("cont_format"), "full_format"); - $this->form_gui->addItem($format); - - // full size - $radio_size = new ilRadioGroupInputGUI($lng->txt("size"), "full_derive_size"); - $fw_size = $std_item->getOriginalSize(); - $add_str = ($fw_size["width"] != "" && $fw_size["height"] != "") - ? " (".$fw_size["width"]." x ".$fw_size["height"].")" - : ""; - $op1 = new ilRadioOption($lng->txt("cont_default").$add_str, "y"); - $op2 = new ilRadioOption($lng->txt("cont_custom"), "n"); - $radio_size->addOption($op1); - - // width height - include_once("./Services/MediaObjects/classes/class.ilWidthHeightInputGUI.php"); - $width_height = new ilWidthHeightInputGUI($lng->txt("cont_width"). - " / ".$lng->txt("cont_height"), "full_width_height"); - $width_height->setConstrainProportions(true); - $op2->addSubItem($width_height); - - $radio_size->addOption($op2); - $this->form_gui->addItem($radio_size); - - // fullscreen caption - $rad_caption = new ilRadioGroupInputGUI($lng->txt("cont_caption"), "full_derive_caption"); - $op1 = new ilRadioOption($lng->txt("cont_default"), "y"); - $def_cap = new ilNonEditableValueGUI("", "full_def_caption"); - $op1->addSubItem($def_cap); - $op2 = new ilRadioOption($lng->txt("cont_custom"), "n"); - $rad_caption->addOption($op1); - - $caption = new ilTextAreaInputGUI("", "full_caption"); - $caption->setCols(30); - $caption->setRows(2); - $op2->addSubItem($caption); - - /*$caption = new ilTextInputGUI("", "full_caption"); - $caption->setSize(40); - $caption->setMaxLength(200); - $op2->addSubItem($caption);*/ - $rad_caption->addOption($op2); - $this->form_gui->addItem($rad_caption); - - // fullscreen text representation - if (substr($full_item->getFormat(), 0, 5) == "image") - { - $rad_tr = new ilRadioGroupInputGUI($lng->txt("text_repr"), "full_derive_text_representation"); - $op1 = new ilRadioOption($lng->txt("cont_default"), "y"); - $def_tr = new ilNonEditableValueGUI("", "full_def_text_representation"); - $op1->addSubItem($def_tr); - $op2 = new ilRadioOption($lng->txt("cont_custom"), "n"); - $tr = new ilTextAreaInputGUI("", "full_text_representation"); - $tr->setCols(30); - $tr->setRows(2); - $rad_tr->addOption($op1); - $op2->addSubItem($tr); - $rad_tr->addOption($op2); - $this->form_gui->addItem($rad_tr); - $rad_tr->setInfo($lng->txt("text_repr_info")); - } - - // fullscreen parameters - if (!in_array($full_item->getFormat(), ilObjMediaObject::_getSimpleMimeTypes())) - { - if (ilObjMediaObject::_useAutoStartParameterOnly($full_item->getLocation(), - $full_item->getFormat())) // autostart - { - $par = $full_item->getParameters(); - $def_str = ($par["autostart"] == "true") - ? " (".$lng->txt("yes").")" - : " (".$lng->txt("no").")"; - $rad_auto = new ilRadioGroupInputGUI($lng->txt("cont_autostart"), - "full_derive_parameters"); - $op1 = new ilRadioOption($lng->txt("cont_default").$def_str, "y"); - $rad_auto->addOption($op1); - $op2 = new ilRadioOption($lng->txt("cont_custom"), "n"); - $auto = new ilCheckboxInputGUI($lng->txt("enabled"), "full_autostart"); - $op2->addSubItem($auto); - $rad_auto->addOption($op2); - $this->form_gui->addItem($rad_auto); - } - else // parameters - { - $rad_parameters = new ilRadioGroupInputGUI($lng->txt("cont_parameter"), "full_derive_parameters"); - $op1 = new ilRadioOption($lng->txt("cont_default"), "y"); - $def_par = new ilNonEditableValueGUI("", "full_def_parameters"); - $op1->addSubItem($def_par); - $rad_parameters->addOption($op1); - $op2 = new ilRadioOption($lng->txt("cont_custom"), "n"); - $par = new ilTextAreaInputGUI("", "full_parameters"); - $par->setRows(5); - $par->setCols(50); - $op2->addSubItem($par); - $rad_parameters->addOption($op2); - $this->form_gui->addItem($rad_parameters); - } - } - } - - $this->form_gui->setTitle($lng->txt("cont_edit_mob_alias_prop")); - $this->form_gui->addCommandButton("saveAliasProperties", $lng->txt("save")); - $lm_set = new ilSetting("lm"); - if ($lm_set->get("replace_mob_feature")) - { - $this->form_gui->addCommandButton("changeObjectReference", $lng->txt("cont_change_object_reference")); - } - $this->form_gui->setFormAction($ilCtrl->getFormAction($this)); - } - - /** - * Put alias values into form - */ - function getAliasValues() - { - $lng = $this->lng; - - // standard view resource - $std_alias_item = new ilMediaAliasItem($this->dom, $this->getHierId(), "Standard", - $this->content_obj->getPcId()); - $std_item = $this->content_obj->getMediaObject()->getMediaItem("Standard"); - - $values["title"] = $this->content_obj->getMediaObject()->getTitle(); - $values["st_location"] = $std_item->getLocation(); - $values["st_format"] = $std_item->getFormat(); - - // size - $values["st_width_height"]["width"] = $std_alias_item->getWidth(); - $values["st_width_height"]["height"] = $std_alias_item->getHeight(); - $values["st_width_height"]["constr_prop"] = true; - - // caption - $values["st_caption"] = $std_alias_item->getCaption(); - if (trim($std_item->getCaption()) == "") - { - $values["def_caption"] = "".$lng->txt("cont_no_caption").""; - } - else - { - $values["def_caption"] = $std_item->getCaption(); - } - - // text representation - $values["st_text_representation"] = $std_alias_item->getTextRepresentation(); - if (trim($std_item->getTextRepresentation()) == "") - { - $values["def_text_representation"] = "".$lng->txt("cont_no_text").""; - } - else - { - $values["def_text_representation"] = $std_item->getTextRepresentation(); - } - - // parameters / autostart - if (ilObjMediaObject::_useAutoStartParameterOnly($std_item->getLocation(), - $std_item->getFormat())) // autostart - { - $par = $std_alias_item->getParameters(); - if ($par["autostart"] == "true") - { - $values["st_autostart"] = true; - } - } - else // parameters - { - $values["st_parameters"] = $std_alias_item->getParameterString(); - } - - // size - $values["st_derive_size"] = $std_alias_item->definesSize() - ? "n" - : "y"; - if ($values["st_derive_size"] == "y") - { - $values["st_width_height"]["width"] = $std_item->getWidth(); - $values["st_width_height"]["height"] = $std_item->getHeight(); - } - $values["st_derive_caption"] = $std_alias_item->definesCaption() - ? "n" - : "y"; - $values["st_derive_text_representation"] = $std_alias_item->definesTextRepresentation() - ? "n" - : "y"; - $values["st_derive_parameters"] = $std_alias_item->definesParameters() - ? "n" - : "y"; - if (trim($std_item->getParameterString()) == "") - { - $values["def_parameters"] = "".$lng->txt("cont_no_parameters").""; - } - else - { - $values["def_parameters"] = $std_item->getParameterString(); - } - - // fullscreen properties - if($this->content_obj->getMediaObject()->hasFullScreenItem()) - { - $full_alias_item = new ilMediaAliasItem($this->dom, $this->getHierId(), "Fullscreen", - $this->content_obj->getPcId()); - $full_item = $this->content_obj->getMediaObject()->getMediaItem("Fullscreen"); - - $values["fullscreen"] = "n"; - if ($full_alias_item->exists()) - { - $values["fullscreen"] = "y"; - } - - $values["full_location"] = $full_item->getLocation(); - $values["full_format"] = $full_item->getFormat(); - $values["full_width_height"]["width"] = $full_alias_item->getWidth(); - $values["full_width_height"]["height"] = $full_alias_item->getHeight(); - $values["full_width_height"]["constr_prop"] = true; - $values["full_caption"] = $full_alias_item->getCaption(); - if (trim($full_item->getCaption()) == "") - { - $values["full_def_caption"] = "".$lng->txt("cont_no_caption").""; - } - else - { - $values["full_def_caption"] = $full_item->getCaption(); - } - $values["full_text_representation"] = $full_alias_item->getTextRepresentation(); - if (trim($full_item->getTextRepresentation()) == "") - { - $values["full_def_text_representation"] = "".$lng->txt("cont_no_text").""; - } - else - { - $values["full_def_text_representation"] = $full_item->getTextRepresentation(); - } - $values["full_parameters"] = $full_alias_item->getParameterString(); - $values["full_derive_size"] = $full_alias_item->definesSize() - ? "n" - : "y"; - if ($values["full_derive_size"] == "y") - { - $values["full_width_height"]["width"] = $full_item->getWidth(); - $values["full_width_height"]["height"] = $full_item->getHeight(); - } - $values["full_derive_caption"] = $full_alias_item->definesCaption() - ? "n" - : "y"; - $values["full_derive_text_representation"] = $full_alias_item->definesTextRepresentation() - ? "n" - : "y"; - - // parameters - if (ilObjMediaObject::_useAutoStartParameterOnly($full_item->getLocation(), - $full_item->getFormat())) // autostart - { - $par = $full_alias_item->getParameters(); - if ($par["autostart"] == "true") - { - $values["full_autostart"] = true; - } - } - else // parameters - { - $values["full_parameters"] = $full_alias_item->getParameterString(); - } - - $values["full_derive_parameters"] = $full_alias_item->definesParameters() - ? "n" - : "y"; - if (trim($full_item->getParameterString()) == "") - { - $values["full_def_parameters"] = "".$lng->txt("cont_no_parameters").""; - } - else - { - $values["full_def_parameters"] = $full_item->getParameterString(); - } - - } - - $this->form_gui->setValuesByArray($values); - } - - /** - * save table properties in db and return to page edit screen - */ - function saveAliasProperties() - { - $std_alias_item = new ilMediaAliasItem($this->dom, $this->getHierId(), "Standard", - $this->content_obj->getPcId()); - $full_alias_item = new ilMediaAliasItem($this->dom, $this->getHierId(), "Fullscreen", - $this->content_obj->getPcId()); - $std_item = $this->content_obj->getMediaObject()->getMediaItem("Standard"); - $full_item = $this->content_obj->getMediaObject()->getMediaItem("Fullscreen"); - - // standard size - if($_POST["st_derive_size"] == "y") - { - $std_alias_item->deriveSize(); - } - else - { - $std_alias_item->setWidth(ilUtil::stripSlashes($_POST["st_width_height"]["width"])); - $std_alias_item->setHeight(ilUtil::stripSlashes($_POST["st_width_height"]["height"])); - } - - // standard caption - if($_POST["st_derive_caption"] == "y") - { - $std_alias_item->deriveCaption(); - } - else - { - $std_alias_item->setCaption(ilUtil::stripSlashes($_POST["st_caption"])); - } - - // text representation - if($_POST["st_derive_text_representation"] == "y") - { - $std_alias_item->deriveTextRepresentation(); - } - else - { - $std_alias_item->setTextRepresentation(ilUtil::stripSlashes($_POST["st_text_representation"])); - } - - // standard parameters - if($_POST["st_derive_parameters"] == "y") - { - $std_alias_item->deriveParameters(); - } - else - { - if (ilObjMediaObject::_useAutoStartParameterOnly($std_item->getLocation(), - $std_item->getFormat())) // autostart - { - if ($_POST["st_autostart"]) - { - $std_alias_item->setParameters(ilUtil::extractParameterString('autostart="true"')); - } - else - { - $std_alias_item->setParameters(ilUtil::extractParameterString('autostart="false"')); - } - } - else // parameters - { - $std_alias_item->setParameters(ilUtil::extractParameterString(ilUtil::stripSlashes(utf8_decode($_POST["st_parameters"])))); - } - } - - if($this->content_obj->getMediaObject()->hasFullscreenItem()) - { - if ($_POST["fullscreen"] == "y") - { - if (!$full_alias_item->exists()) - { - $full_alias_item->insert(); - } - - // fullscreen size - if($_POST["full_derive_size"] == "y") - { - $full_alias_item->deriveSize(); - } - else - { - $full_alias_item->setWidth(ilUtil::stripSlashes($_POST["full_width_height"]["width"])); - $full_alias_item->setHeight(ilUtil::stripSlashes($_POST["full_width_height"]["height"])); - } - - // fullscreen caption - if($_POST["full_derive_caption"] == "y") - { - $full_alias_item->deriveCaption(); - } - else - { - $full_alias_item->setCaption(ilUtil::stripSlashes($_POST["full_caption"])); - } - - // fullscreen text representation - if($_POST["full_derive_text_representation"] == "y") - { - $full_alias_item->deriveTextRepresentation(); - } - else - { - $full_alias_item->setTextRepresentation(ilUtil::stripSlashes($_POST["full_text_representation"])); - } - - // fullscreen parameters - if($_POST["full_derive_parameters"] == "y") - { - $full_alias_item->deriveParameters(); - } - else - { - if (ilObjMediaObject::_useAutoStartParameterOnly($full_item->getLocation(), - $full_item->getFormat())) // autostart - { - if ($_POST["full_autostart"]) - { - $full_alias_item->setParameters(ilUtil::extractParameterString('autostart="true"')); - } - else - { - $full_alias_item->setParameters(ilUtil::extractParameterString('autostart="false"')); - } - } - else - { - $full_alias_item->setParameters(ilUtil::extractParameterString(ilUtil::stripSlashes(utf8_decode($_POST["full_parameters"])))); - } - } - } - else - { - if ($full_alias_item->exists()) - { - $full_alias_item->delete(); - } - } - } - - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "editAlias"); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - else - { - $this->pg_obj->addHierIDs(); - $this->editAlias(); - } - } - - /** - * copy media object to clipboard - */ - function copyToClipboard() - { - $ilUser = $this->user; - - $ilUser->addObjectToClipboard($this->content_obj->getMediaObject()->getId(), $this->content_obj->getMediaObject()->getType() - , $this->content_obj->getMediaObject()->getTitle()); - ilUtil::sendSuccess($this->lng->txt("copied_to_clipboard"), true); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * align media object to center - */ - function centerAlign() - { - $std_alias_item = new ilMediaAliasItem($this->dom, $this->getHierId(), "Standard", - $this->content_obj->getPcId()); - $std_alias_item->setHorizontalAlign("Center"); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * align media object to left - */ - function leftAlign() - { - $std_alias_item = new ilMediaAliasItem($this->dom, $this->getHierId(), "Standard", - $this->content_obj->getPcId()); - $std_alias_item->setHorizontalAlign("Left"); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * align media object to right - */ - function rightAlign() - { - $std_alias_item = new ilMediaAliasItem($this->dom, $this->getHierId(), "Standard", - $this->content_obj->getPcId()); - $std_alias_item->setHorizontalAlign("Right"); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * align media object to left, floating text - */ - function leftFloatAlign() - { - $std_alias_item = new ilMediaAliasItem($this->dom, $this->getHierId(), "Standard", - $this->content_obj->getPcId()); - $std_alias_item->setHorizontalAlign("LeftFloat"); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * align media object to right, floating text - */ - function rightFloatAlign() - { - $std_alias_item = new ilMediaAliasItem($this->dom, $this->getHierId(), "Standard", - $this->content_obj->getPcId()); - $std_alias_item->setHorizontalAlign("RightFloat"); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * Checks whether style selection shoudl be available or not - */ - function checkStyleSelection() - { - // check whether there is more than one style class - $chars = $this->getCharacteristics(); - - if (count($chars) > 1 || - ($this->content_obj->getClass() != "" && $this->content_obj->getClass() != "Media")) - { - return true; - } - return false; - } - - /** - * Edit Style - */ - function editStyle() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - $this->displayValidationError(); - - // edit form - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this)); - $form->setTitle($this->lng->txt("cont_edit_style")); - - // characteristic selection - require_once("./Services/Form/classes/class.ilAdvSelectInputGUI.php"); - $char_prop = new ilAdvSelectInputGUI($this->lng->txt("cont_characteristic"), - "characteristic"); - - $chars = $this->getCharacteristics(); - if (is_object($this->content_obj)) - { - if ($chars[$a_seleted_value] == "" && ($this->content_obj->getClass() != "")) - { - $chars = array_merge( - array($this->content_obj->getClass() => $this->content_obj->getClass()), - $chars); - } - } - - $selected = $this->content_obj->getClass(); - if ($selected == "") - { - $selected = "MediaContainer"; - } - - foreach ($chars as $k => $char) - { - $html = '
'. - $char.'
'; - $char_prop->addOption($k, $char, $html); - } - - $char_prop->setValue($selected); - $form->addItem($char_prop); - - // save button - $form->addCommandButton("saveStyle", $lng->txt("save")); - - $html = $form->getHTML(); - $tpl->setContent($html); - return $ret; - } - - /** - * Save Style - */ - function saveStyle() - { - $this->content_obj->setClass($_POST["characteristic"]); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - else - { - $this->pg_obj->addHierIDs(); - $this->editStyle(); - } - } - - /** - * add tabs to ilTabsGUI object - * - * @param object $tab_gui ilTabsGUI object - * @param boolean $a_create new creation true/false - */ - function getTabs(&$tab_gui, $a_create = false, $a_change_obj_ref = false) - { - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - if (!$a_create) - { - if ($this->checkStyleSelection()) - { - $ilTabs->addTarget("cont_style", - $ilCtrl->getLinkTarget($this, "editStyle"), "editStyle", - get_class($this)); - } - - $ilTabs->addTarget("cont_mob_inst_prop", - $ilCtrl->getLinkTarget($this, "editAlias"), "editAlias", - get_class($this)); - - if ($this->getEnabledMapAreas()) - { - $st_item = $this->content_obj->getMediaObject()->getMediaItem("Standard"); - if (is_object($st_item)) - { - $format = $st_item->getFormat(); - if (substr($format, 0, 5) == "image" && !is_int(strpos($format, "svg"))) - { - $ilTabs->addTarget("cont_inst_map_areas", - $ilCtrl->getLinkTargetByClass("ilpcimagemapeditorgui", "editMapAreas"), array(), - "ilpcimagemapeditorgui"); - } - } - } - } - else - { - if ($a_change_obj_ref) - { - $cmd = "changeObjectReference"; - } - else - { - $cmd = "insert"; - } - - $ilCtrl->setParameter($this, "subCmd", "insertNew"); - $ilTabs->addSubTabTarget("cont_new_mob", - $ilCtrl->getLinkTarget($this, $cmd), $cmd); - - $ilCtrl->setParameter($this, "subCmd", "insertFromPool"); - $ilTabs->addSubTabTarget("cont_mob_from_media_pool", - $ilCtrl->getLinkTarget($this, $cmd), $cmd); - $ilCtrl->setParameter($this, "subCmd", ""); - } - } - + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var \ILIAS\DI\UIServices + */ + protected $ui; + + /** + * @var string + */ + protected $pool_view; + + public $header; + public $ctrl; + + /** + * @var string table sub command (e.g. applyFilter) + */ + protected $sub_cmd; + + public function __construct($a_pg_obj, $a_content_obj, $a_hier_id = 0, $a_pc_id = "") + { + global $DIC; + + $this->tpl = $DIC["tpl"]; + $this->lng = $DIC->language(); + $this->tabs = $DIC->tabs(); + $this->access = $DIC->access(); + $this->toolbar = $DIC->toolbar(); + $this->user = $DIC->user(); + $ilCtrl = $DIC->ctrl(); + $this->ui = $DIC->ui(); + + $this->pool_view = "folder"; + if (in_array($_GET["pool_view"], array("folder", "all"))) { + $this->pool_view = $_GET["pool_view"]; + } + + $this->ctrl = $ilCtrl; + + $this->ctrl->saveParameter($this, "pool_view"); + + // var_dump($_POST); + //ilUtil::printBacktrace(10); exit; + //echo "constructor target:".$_SESSION["il_map_il_target"].":
"; + parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); + + $this->setCharacteristics(array( + "MediaContainer" => $this->lng->txt("cont_Media"), + "MediaContainerMax50" => "MediaContainerMax50", + "MediaContainerFull100" => "MediaContainerFull100", + "MediaContainerHighlighted" => "MediaContainerHighlighted", + "MediaContainerSeparated" => "MediaContainerSeparated" + )); + } + + /** + * Set table sub command + * + * @param string $a_val command + */ + public function setSubCmd($a_val) + { + $this->sub_cmd = $a_val; + } + + /** + * Get table sub command + * + * @return string command + */ + public function getSubCmd() + { + return $this->sub_cmd; + } + + + public function setHeader($a_title = "") + { + $this->header = $a_title; + } + + public function getHeader() + { + return $this->header; + } + + /** + * Set Enable map areas. + * + * @param boolean $a_enabledmapareas Enable map areas + */ + public function setEnabledMapAreas($a_enabledmapareas) + { + $this->enabledmapareas = $a_enabledmapareas; + } + + /** + * Get Enable map areas. + * + * @return boolean Enable map areas + */ + public function getEnabledMapAreas() + { + return $this->enabledmapareas; + } + + /** + * execute command + */ + public function executeCommand() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilTabs = $this->tabs; + + $this->getCharacteristicsOfCurrentStyle("media_cont"); // scorm-2004 + + // get next class that processes or forwards current command + $next_class = $this->ctrl->getNextClass($this); + + // get current command + $cmd = $this->ctrl->getCmd(); + if (is_object($this->content_obj)) { + $this->tpl->clearHeader(); + $tpl->setTitleIcon(ilUtil::getImagePath("icon_mob.svg")); + $this->getTabs($this->tabs_gui); + + $mob = $this->content_obj->getMediaObject(); + if (is_object($mob)) { + $tpl->setVariable("HEADER", $lng->txt("mob") . ": " . + $this->content_obj->getMediaObject()->getTitle()); + $mob_gui = new ilObjMediaObjectGUI("", $this->content_obj->getMediaObject()->getId(), false, false); + $mob_gui->setBackTitle($this->page_back_title); + $mob_gui->setEnabledMapAreas($this->getEnabledMapAreas()); + $mob_gui->getTabs($this->tabs_gui); + } + } else { + } + + switch ($next_class) { + case "ilobjmediaobjectgui": + include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); + $this->tpl->clearHeader(); + $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_mob.svg")); + $this->tpl->setTitle($this->lng->txt("mob") . ": " . + $this->content_obj->getMediaObject()->getTitle()); + $mob_gui = new ilObjMediaObjectGUI("", $this->content_obj->getMediaObject()->getId(), false, false); + $mob_gui->setBackTitle($this->page_back_title); + $mob_gui->setEnabledMapAreas($this->getEnabledMapAreas()); + $ret = $this->ctrl->forwardCommand($mob_gui); + break; + + // instance image map editing + case "ilpcimagemapeditorgui": + require_once("./Services/COPage/classes/class.ilPCImageMapEditorGUI.php"); + $ilTabs->setTabActive("cont_inst_map_areas"); + $image_map_edit = new ilPCImageMapEditorGUI( + $this->content_obj, + $this->pg_obj + ); + $ret = $this->ctrl->forwardCommand($image_map_edit); + $tpl->setContent($ret); + $this->checkFixSize(); + break; + + default: + $ret = $this->$cmd(); + break; + } + + return $ret; + } + + /** + * Insert new media object form. + */ + public function insert($a_post_cmd = "edpost", $a_submit_cmd = "create_mob", $a_input_error = false) + { + $ilTabs = $this->tabs; + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if ($_GET["subCmd"] == "insertNew") { + $_SESSION["cont_media_insert"] = "insertNew"; + } + if ($_GET["subCmd"] == "insertFromPool") { + $_SESSION["cont_media_insert"] = "insertFromPool"; + } + + if (($_GET["subCmd"] == "") && $_SESSION["cont_media_insert"] != "") { + $_GET["subCmd"] = $_SESSION["cont_media_insert"]; + } + + switch ($_GET["subCmd"]) { + case "insertFromPool": + $this->insertFromPool(); + break; + + case "poolSelection": + $this->poolSelection(); + break; + + case "selectPool": + $this->selectPool(); + break; + + case "insertNew": + default: + $this->getTabs($ilTabs, true); + $ilTabs->setSubTabActive("cont_new_mob"); + + include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); + if ($a_input_error) { + $form = $this->form; + } else { + $mob_gui = new ilObjMediaObjectGUI(""); + $mob_gui->initForm("create"); + $form = $mob_gui->getForm(); + } + $form->setFormAction($ilCtrl->getFormAction($this, "create_mob")); + $form->clearCommandButtons(); + $form->addCommandButton("create_mob", $lng->txt("save")); + $form->addCommandButton("cancelCreate", $lng->txt("cancel")); + + $this->displayValidationError(); + + $tpl->setContent($form->getHTML()); + + break; + } + } + + /** + * Change object reference + */ + public function changeObjectReference() + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if ($_GET["subCmd"] == "insertNew") { + $_SESSION["cont_media_insert"] = "insertNew"; + } + if ($_GET["subCmd"] == "insertFromPool") { + $_SESSION["cont_media_insert"] = "insertFromPool"; + } + + if (($_GET["subCmd"] == "") && $_SESSION["cont_media_insert"] != "") { + $_GET["subCmd"] = $_SESSION["cont_media_insert"]; + } + + switch ($_GET["subCmd"]) { + case "insertFromPool": + $this->insertFromPool(true); + break; + + case "poolSelection": + $this->poolSelection(true); + break; + + case "selectPool": + $this->selectPool(true); + break; + + case "insertNew": + default: + $ilCtrl->setParameter($this, "subCmd", "changeObjectReference"); + $this->getTabs($ilTabs, true, true); + $ilTabs->setSubTabActive("cont_new_mob"); + + $this->displayValidationError(); + + $mob_gui = new ilObjMediaObjectGUI(""); + $mob_gui->initForm("create"); + $form = $mob_gui->getForm(); + $form->setFormAction($ilCtrl->getFormAction($this)); + $form->clearCommandButtons(); + $form->addCommandButton("createNewObjectReference", $lng->txt("save")); + $form->addCommandButton("cancelCreate", $lng->txt("cancel")); + $this->tpl->setContent($form->getHTML()); + } + } + + + /** + * Check fix size + */ + protected function checkFixSize() + { + $std_alias_item = new ilMediaAliasItem( + $this->dom, + $this->getHierId(), + "Standard", + $this->content_obj->getPcId() + ); + $std_item = $this->content_obj->getMediaObject()->getMediaItem("Standard"); + + $ok = false; + if (($std_alias_item->getWidth() != "" && $std_alias_item->getHeight() != "")) { + $ok = true; + } + if ($std_alias_item->getWidth() == "" && $std_alias_item->getHeight() == "" + && $std_item->getWidth() != "" && $std_item->getHeight() != "") { + $ok = true; + } + + if (!$ok) { + ilUtil::sendFailure($this->lng->txt("mob_no_fixed_size_map_editing")); + } + } + + /** + * Insert media object from pool + */ + public function insertFromPool($a_change_obj_ref = false) + { + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + $ilTabs = $this->tabs; + $tpl = $this->tpl; + $lng = $this->lng; + $ui = $this->ui; + + 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(); + + // button: select pool + $ilCtrl->setParameter($this, "subCmd", "poolSelection"); + if ($a_change_obj_ref) { + $tb->addButton( + $lng->txt("cont_switch_to_media_pool"), + $ilCtrl->getLinkTarget($this, "changeObjectReference") + ); + } else { + $tb->addButton( + $lng->txt("cont_switch_to_media_pool"), + $ilCtrl->getLinkTarget($this, "insert") + ); + } + $ilCtrl->setParameter($this, "subCmd", ""); + + // view mode: pool view (folders/all media objects) + $f = $ui->factory(); + $tcmd = ($a_change_obj_ref) + ? "changeObjectReference" + : "insert"; + $lng->loadLanguageModule("mep"); + $ilCtrl->setParameter($this, "pool_view", "folder"); + $actions[$lng->txt("folders")] = $ilCtrl->getLinkTarget($this, $tcmd); + $ilCtrl->setParameter($this, "pool_view", "all"); + $actions[$lng->txt("mep_all_mobs")] = $ilCtrl->getLinkTarget($this, $tcmd); + $ilCtrl->setParameter($this, "pool_view", $this->pool_view); + $aria_label = $lng->txt("cont_change_pool_view"); + $view_control = $f->viewControl()->mode($actions, $aria_label)->withActive(($this->pool_view == "folder") + ? $lng->txt("folders") : $lng->txt("mep_all_mobs")); + $tb->addSeparator(); + $tb->addComponent($view_control); + + $html = $tb->getHTML(); + + $this->getTabs($ilTabs, true, $a_change_obj_ref); + $ilTabs->setSubTabActive("cont_mob_from_media_pool"); + + + + + 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"); + $tcmd = ($a_change_obj_ref) + ? "changeObjectReference" + : "insert"; + $tmode = ($a_change_obj_ref) + ? ilMediaPoolTableGUI::IL_MEP_SELECT_SINGLE + : ilMediaPoolTableGUI::IL_MEP_SELECT; + + // handle table sub commands and get the table + if ($this->getSubCmd() == "applyFilter") { + $mpool_table = new ilMediaPoolTableGUI( + $this, + $tcmd, + $pool, + "mep_folder", + $tmode, + $this->pool_view == "all" + ); + $mpool_table->resetOffset(); + $mpool_table->writeFilterToSession(); + } + if ($this->getSubCmd() == "resetFilter") { + $mpool_table = new ilMediaPoolTableGUI( + $this, + $tcmd, + $pool, + "mep_folder", + $tmode, + $this->pool_view == "all" + ); + $mpool_table->resetOffset(); + $mpool_table->resetFilter(); + } + $mpool_table = new ilMediaPoolTableGUI( + $this, + $tcmd, + $pool, + "mep_folder", + $tmode, + $this->pool_view == "all" + ); + + $html.= $mpool_table->getHTML(); + + $tpl->setContent($html); + } else { + $this->poolSelection($a_change_obj_ref); + } + } + + /** + * Select concrete pool + */ + public function selectPool($a_change_obj_ref = false) + { + $ilCtrl = $this->ctrl; + + $_SESSION["cont_media_pool"] = $_GET["pool_ref_id"]; + $ilCtrl->setParameter($this, "subCmd", "insertFromPool"); + if ($a_change_obj_ref) { + $ilCtrl->redirect($this, "changeObjectReference"); + } else { + $ilCtrl->redirect($this, "insert"); + } + } + + /** + * Pool Selection + */ + public function poolSelection($a_change_obj_ref = false) + { + $tpl = $this->tpl; + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + + $this->getTabs($ilTabs, true, $a_change_obj_ref); + $ilTabs->setSubTabActive("cont_mob_from_media_pool"); + + include_once "./Services/COPage/classes/class.ilPoolSelectorGUI.php"; + + if ($a_change_obj_ref) { + $ilCtrl->setParameter($this, "subCmd", "poolSelection"); + $exp = new ilPoolSelectorGUI($this, "changeObjectReference", $this, "changeObjectReference"); + } else { + $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 media object and replace currrent media item with it. + * (keep all instance parameters) + */ + public function createNewObjectReference() + { + $this->create(false, true); + } + + /** + * Create new media object and replace currrent media item with it. + * (keep all instance parameters) + */ + public function selectObjectReference() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + if (is_array($_POST["id"]) && count($_POST["id"]) == 1) { + include_once("./Services/COPage/classes/class.ilPCMediaObject.php"); + include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); + $fid = ilMediaPoolItem::lookupForeignId($_POST["id"][0]); + $this->content_obj->readMediaObject($fid); + $this->content_obj->updateObjectReference(); + $this->updated = $this->pg_obj->update(); + } else { + ilUtil::sendInfo($lng->txt("cont_select_max_one_item"), true); + $ilCtrl->redirect($this, "changeObjectReference"); + } + $ilCtrl->redirect($this, "editAlias"); + } + + /** + * create new media object in dom and update page in db + */ + public function &create($a_create_alias = true, $a_change_obj_ref = false) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if ($_GET["subCmd"] == "insertFromPool") { + if (is_array($_POST["id"])) { + for ($i = count($_POST["id"]) - 1; $i>=0; $i--) { + include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); + $fid = ilMediaPoolItem::lookupForeignId($_POST["id"][$i]); + include_once("./Services/COPage/classes/class.ilPCMediaObject.php"); + $this->content_obj = new ilPCMediaObject($this->getPage()); + $this->content_obj->readMediaObject($fid); + $this->content_obj->createAlias($this->pg_obj, $_GET["hier_id"], $this->pc_id); + } + $this->updated = $this->pg_obj->update(); + } + + $ilCtrl->returnToParent($this); + } + + // check form input + $mob_gui = new ilObjMediaObjectGUI(""); + $mob_gui->initForm("create"); + + if (!$mob_gui->checkFormInput()) { + $this->form = $mob_gui->getForm(); + $this->insert("edpost", "create_mob", true); + return; + } + // create dummy object in db (we need an id) + include_once("./Services/COPage/classes/class.ilPCMediaObject.php"); + if ($a_change_obj_ref != true) { + $this->content_obj = new ilPCMediaObject($this->getPage()); + } + $this->content_obj->createMediaObject(); + $media_obj = $this->content_obj->getMediaObject(); + + include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); + ilObjMediaObjectGUI::setObjectPerCreationForm($media_obj); + + if ($a_create_alias) { + // need a pcmediaobject here + //$this->node = $this->createPageContentNode(); + + $this->content_obj->createAlias($this->pg_obj, $this->hier_id, $this->pc_id); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->pg_obj->stripHierIDs(); + $this->pg_obj->addHierIDs(); + $ilCtrl->setParameter($this, "hier_id", $this->content_obj->readHierId()); + $ilCtrl->setParameter($this, "pc_id", $this->content_obj->readPCId()); + $this->content_obj->setHierId($this->content_obj->readHierId()); + $this->setHierId($this->content_obj->readHierId()); + $this->content_obj->setPCId($this->content_obj->readPCId()); + ilUtil::sendSuccess($lng->txt("saved_media_object"), true); + $this->ctrl->redirectByClass("ilobjmediaobjectgui", "edit"); + + //$this->ctrl->returnToParent($this, "jump".$this->hier_id); + } else { + $this->insert(); + } + } else { + if ($a_change_obj_ref == true) { + $this->content_obj->updateObjectReference(); + $this->updated = $this->pg_obj->update(); + $this->ctrl->redirect($this, "editAlias"); + } + return $this->content_obj; + } + } + + + /** + * edit properties form + */ + public function editAlias() + { + $tpl = $this->tpl; + + $this->initAliasForm(); + $this->getAliasValues(); + $tpl->setContent($this->form_gui->getHTML()); + } + + /** + * Init alias form + */ + public function initAliasForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + + $this->form_gui = new ilPropertyFormGUI(); + + // standard view resource + $std_alias_item = new ilMediaAliasItem( + $this->dom, + $this->getHierId(), + "Standard", + $this->content_obj->getPcId() + ); + $std_item = $this->content_obj->getMediaObject()->getMediaItem("Standard"); + + // title, location and format + $title = new ilNonEditableValueGUI($lng->txt("title"), "title"); + $this->form_gui->addItem($title); + $loc = new ilNonEditableValueGUI( + $this->lng->txt("cont_" . strtolower($std_item->getLocationType())), + "st_location" + ); + $this->form_gui->addItem($loc); + $format = new ilNonEditableValueGUI( + $this->lng->txt("cont_format"), + "st_format" + ); + $this->form_gui->addItem($format); + + // standard size + $radio_size = new ilRadioGroupInputGUI($lng->txt("size"), "st_derive_size"); + $orig_size = $std_item->getOriginalSize(); + $add_str = ($orig_size["width"] != "" && $orig_size["height"] != "") + ? " (" . $orig_size["width"] . " x " . $orig_size["height"] . ")" + : ""; + $op1 = new ilRadioOption($lng->txt("cont_default") . $add_str, "y"); + $op2 = new ilRadioOption($lng->txt("cont_custom"), "n"); + $radio_size->addOption($op1); + + // width height + include_once("./Services/MediaObjects/classes/class.ilWidthHeightInputGUI.php"); + $width_height = new ilWidthHeightInputGUI($lng->txt("cont_width") . + " / " . $lng->txt("cont_height"), "st_width_height"); + $width_height->setConstrainProportions(true); + $op2->addSubItem($width_height); + + $radio_size->addOption($op2); + $this->form_gui->addItem($radio_size); + + // standard caption + $rad_caption = new ilRadioGroupInputGUI($lng->txt("cont_caption"), "st_derive_caption"); + $op1 = new ilRadioOption($lng->txt("cont_default"), "y"); + $def_cap = new ilNonEditableValueGUI("", "def_caption"); + $op1->addSubItem($def_cap); + $op2 = new ilRadioOption($lng->txt("cont_custom"), "n"); + $rad_caption->addOption($op1); + + $caption = new ilTextAreaInputGUI("", "st_caption"); + $caption->setCols(30); + $caption->setRows(2); + $op2->addSubItem($caption); + + /*$caption = new ilTextInputGUI("", "st_caption"); + $caption->setSize(40); + $caption->setMaxLength(200); + $op2->addSubItem($caption);*/ + $rad_caption->addOption($op2); + $this->form_gui->addItem($rad_caption); + + // standard text representation + if (substr($std_item->getFormat(), 0, 5) == "image") { + $rad_tr = new ilRadioGroupInputGUI($lng->txt("text_repr"), "st_derive_text_representation"); + $op1 = new ilRadioOption($lng->txt("cont_default"), "y"); + $def_tr = new ilNonEditableValueGUI("", "def_text_representation"); + $op1->addSubItem($def_tr); + $op2 = new ilRadioOption($lng->txt("cont_custom"), "n"); + $tr = new ilTextAreaInputGUI("", "st_text_representation"); + $tr->setCols(30); + $tr->setRows(2); + $rad_tr->addOption($op1); + $op2->addSubItem($tr); + $rad_tr->addOption($op2); + $this->form_gui->addItem($rad_tr); + $rad_tr->setInfo($lng->txt("text_repr_info")); + } + + // standard parameters + if (!in_array($std_item->getFormat(), ilObjMediaObject::_getSimpleMimeTypes())) { + if (ilObjMediaObject::_useAutoStartParameterOnly( + $std_item->getLocation(), + $std_item->getFormat() + )) { // autostart + $par = $std_item->getParameters(); + $def_str = ($par["autostart"] == "true") + ? " (" . $lng->txt("yes") . ")" + : " (" . $lng->txt("no") . ")"; + $rad_auto = new ilRadioGroupInputGUI( + $lng->txt("cont_autostart"), + "st_derive_parameters" + ); + $op1 = new ilRadioOption($lng->txt("cont_default") . $def_str, "y"); + $rad_auto->addOption($op1); + $op2 = new ilRadioOption($lng->txt("cont_custom"), "n"); + $auto = new ilCheckboxInputGUI($lng->txt("enabled"), "st_autostart"); + $op2->addSubItem($auto); + $rad_auto->addOption($op2); + $this->form_gui->addItem($rad_auto); + } else { // parameters + $rad_parameters = new ilRadioGroupInputGUI($lng->txt("cont_parameter"), "st_derive_parameters"); + $op1 = new ilRadioOption($lng->txt("cont_default"), "y"); + $def_par = new ilNonEditableValueGUI("", "def_parameters"); + $op1->addSubItem($def_par); + $rad_parameters->addOption($op1); + $op2 = new ilRadioOption($lng->txt("cont_custom"), "n"); + $par = new ilTextAreaInputGUI("", "st_parameters"); + $par->setRows(5); + $par->setCols(50); + $op2->addSubItem($par); + $rad_parameters->addOption($op2); + $this->form_gui->addItem($rad_parameters); + } + } + + // fullscreen view + if ($this->content_obj->getMediaObject()->hasFullScreenItem()) { + $full_alias_item = new ilMediaAliasItem( + $this->dom, + $this->getHierId(), + "Fullscreen", + $this->content_obj->getPcId() + ); + $full_item = $this->content_obj->getMediaObject()->getMediaItem("Fullscreen"); + + $fs_sec = new ilFormSectionHeaderGUI(); + $fs_sec->setTitle($lng->txt("cont_fullscreen")); + $this->form_gui->addItem($fs_sec); + + + // resource + $radio_prop = new ilRadioGroupInputGUI($lng->txt("cont_resource"), "fullscreen"); + $op1 = new ilRadioOption($lng->txt("cont_none"), "n"); + $radio_prop->addOption($op1); + $op2 = new ilRadioOption($this->lng->txt("cont_" . strtolower($full_item->getLocationType())) . ": " . + $full_item->getLocation(), "y"); + $radio_prop->addOption($op2); + $this->form_gui->addItem($radio_prop); + + // format + $format = new ilNonEditableValueGUI( + $this->lng->txt("cont_format"), + "full_format" + ); + $this->form_gui->addItem($format); + + // full size + $radio_size = new ilRadioGroupInputGUI($lng->txt("size"), "full_derive_size"); + $fw_size = $std_item->getOriginalSize(); + $add_str = ($fw_size["width"] != "" && $fw_size["height"] != "") + ? " (" . $fw_size["width"] . " x " . $fw_size["height"] . ")" + : ""; + $op1 = new ilRadioOption($lng->txt("cont_default") . $add_str, "y"); + $op2 = new ilRadioOption($lng->txt("cont_custom"), "n"); + $radio_size->addOption($op1); + + // width height + include_once("./Services/MediaObjects/classes/class.ilWidthHeightInputGUI.php"); + $width_height = new ilWidthHeightInputGUI($lng->txt("cont_width") . + " / " . $lng->txt("cont_height"), "full_width_height"); + $width_height->setConstrainProportions(true); + $op2->addSubItem($width_height); + + $radio_size->addOption($op2); + $this->form_gui->addItem($radio_size); + + // fullscreen caption + $rad_caption = new ilRadioGroupInputGUI($lng->txt("cont_caption"), "full_derive_caption"); + $op1 = new ilRadioOption($lng->txt("cont_default"), "y"); + $def_cap = new ilNonEditableValueGUI("", "full_def_caption"); + $op1->addSubItem($def_cap); + $op2 = new ilRadioOption($lng->txt("cont_custom"), "n"); + $rad_caption->addOption($op1); + + $caption = new ilTextAreaInputGUI("", "full_caption"); + $caption->setCols(30); + $caption->setRows(2); + $op2->addSubItem($caption); + + /*$caption = new ilTextInputGUI("", "full_caption"); + $caption->setSize(40); + $caption->setMaxLength(200); + $op2->addSubItem($caption);*/ + $rad_caption->addOption($op2); + $this->form_gui->addItem($rad_caption); + + // fullscreen text representation + if (substr($full_item->getFormat(), 0, 5) == "image") { + $rad_tr = new ilRadioGroupInputGUI($lng->txt("text_repr"), "full_derive_text_representation"); + $op1 = new ilRadioOption($lng->txt("cont_default"), "y"); + $def_tr = new ilNonEditableValueGUI("", "full_def_text_representation"); + $op1->addSubItem($def_tr); + $op2 = new ilRadioOption($lng->txt("cont_custom"), "n"); + $tr = new ilTextAreaInputGUI("", "full_text_representation"); + $tr->setCols(30); + $tr->setRows(2); + $rad_tr->addOption($op1); + $op2->addSubItem($tr); + $rad_tr->addOption($op2); + $this->form_gui->addItem($rad_tr); + $rad_tr->setInfo($lng->txt("text_repr_info")); + } + + // fullscreen parameters + if (!in_array($full_item->getFormat(), ilObjMediaObject::_getSimpleMimeTypes())) { + if (ilObjMediaObject::_useAutoStartParameterOnly( + $full_item->getLocation(), + $full_item->getFormat() + )) { // autostart + $par = $full_item->getParameters(); + $def_str = ($par["autostart"] == "true") + ? " (" . $lng->txt("yes") . ")" + : " (" . $lng->txt("no") . ")"; + $rad_auto = new ilRadioGroupInputGUI( + $lng->txt("cont_autostart"), + "full_derive_parameters" + ); + $op1 = new ilRadioOption($lng->txt("cont_default") . $def_str, "y"); + $rad_auto->addOption($op1); + $op2 = new ilRadioOption($lng->txt("cont_custom"), "n"); + $auto = new ilCheckboxInputGUI($lng->txt("enabled"), "full_autostart"); + $op2->addSubItem($auto); + $rad_auto->addOption($op2); + $this->form_gui->addItem($rad_auto); + } else { // parameters + $rad_parameters = new ilRadioGroupInputGUI($lng->txt("cont_parameter"), "full_derive_parameters"); + $op1 = new ilRadioOption($lng->txt("cont_default"), "y"); + $def_par = new ilNonEditableValueGUI("", "full_def_parameters"); + $op1->addSubItem($def_par); + $rad_parameters->addOption($op1); + $op2 = new ilRadioOption($lng->txt("cont_custom"), "n"); + $par = new ilTextAreaInputGUI("", "full_parameters"); + $par->setRows(5); + $par->setCols(50); + $op2->addSubItem($par); + $rad_parameters->addOption($op2); + $this->form_gui->addItem($rad_parameters); + } + } + } + + $this->form_gui->setTitle($lng->txt("cont_edit_mob_alias_prop")); + $this->form_gui->addCommandButton("saveAliasProperties", $lng->txt("save")); + $lm_set = new ilSetting("lm"); + if ($lm_set->get("replace_mob_feature")) { + $this->form_gui->addCommandButton("changeObjectReference", $lng->txt("cont_change_object_reference")); + } + $this->form_gui->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * Put alias values into form + */ + public function getAliasValues() + { + $lng = $this->lng; + + // standard view resource + $std_alias_item = new ilMediaAliasItem( + $this->dom, + $this->getHierId(), + "Standard", + $this->content_obj->getPcId() + ); + $std_item = $this->content_obj->getMediaObject()->getMediaItem("Standard"); + + $values["title"] = $this->content_obj->getMediaObject()->getTitle(); + $values["st_location"] = $std_item->getLocation(); + $values["st_format"] = $std_item->getFormat(); + + // size + $values["st_width_height"]["width"] = $std_alias_item->getWidth(); + $values["st_width_height"]["height"] = $std_alias_item->getHeight(); + $values["st_width_height"]["constr_prop"] = true; + + // caption + $values["st_caption"] = $std_alias_item->getCaption(); + if (trim($std_item->getCaption()) == "") { + $values["def_caption"] = "" . $lng->txt("cont_no_caption") . ""; + } else { + $values["def_caption"] = $std_item->getCaption(); + } + + // text representation + $values["st_text_representation"] = $std_alias_item->getTextRepresentation(); + if (trim($std_item->getTextRepresentation()) == "") { + $values["def_text_representation"] = "" . $lng->txt("cont_no_text") . ""; + } else { + $values["def_text_representation"] = $std_item->getTextRepresentation(); + } + + // parameters / autostart + if (ilObjMediaObject::_useAutoStartParameterOnly( + $std_item->getLocation(), + $std_item->getFormat() + )) { // autostart + $par = $std_alias_item->getParameters(); + if ($par["autostart"] == "true") { + $values["st_autostart"] = true; + } + } else { // parameters + $values["st_parameters"] = $std_alias_item->getParameterString(); + } + + // size + $values["st_derive_size"] = $std_alias_item->definesSize() + ? "n" + : "y"; + if ($values["st_derive_size"] == "y") { + $values["st_width_height"]["width"] = $std_item->getWidth(); + $values["st_width_height"]["height"] = $std_item->getHeight(); + } + $values["st_derive_caption"] = $std_alias_item->definesCaption() + ? "n" + : "y"; + $values["st_derive_text_representation"] = $std_alias_item->definesTextRepresentation() + ? "n" + : "y"; + $values["st_derive_parameters"] = $std_alias_item->definesParameters() + ? "n" + : "y"; + if (trim($std_item->getParameterString()) == "") { + $values["def_parameters"] = "" . $lng->txt("cont_no_parameters") . ""; + } else { + $values["def_parameters"] = $std_item->getParameterString(); + } + + // fullscreen properties + if ($this->content_obj->getMediaObject()->hasFullScreenItem()) { + $full_alias_item = new ilMediaAliasItem( + $this->dom, + $this->getHierId(), + "Fullscreen", + $this->content_obj->getPcId() + ); + $full_item = $this->content_obj->getMediaObject()->getMediaItem("Fullscreen"); + + $values["fullscreen"] = "n"; + if ($full_alias_item->exists()) { + $values["fullscreen"] = "y"; + } + + $values["full_location"] = $full_item->getLocation(); + $values["full_format"] = $full_item->getFormat(); + $values["full_width_height"]["width"] = $full_alias_item->getWidth(); + $values["full_width_height"]["height"] = $full_alias_item->getHeight(); + $values["full_width_height"]["constr_prop"] = true; + $values["full_caption"] = $full_alias_item->getCaption(); + if (trim($full_item->getCaption()) == "") { + $values["full_def_caption"] = "" . $lng->txt("cont_no_caption") . ""; + } else { + $values["full_def_caption"] = $full_item->getCaption(); + } + $values["full_text_representation"] = $full_alias_item->getTextRepresentation(); + if (trim($full_item->getTextRepresentation()) == "") { + $values["full_def_text_representation"] = "" . $lng->txt("cont_no_text") . ""; + } else { + $values["full_def_text_representation"] = $full_item->getTextRepresentation(); + } + $values["full_parameters"] = $full_alias_item->getParameterString(); + $values["full_derive_size"] = $full_alias_item->definesSize() + ? "n" + : "y"; + if ($values["full_derive_size"] == "y") { + $values["full_width_height"]["width"] = $full_item->getWidth(); + $values["full_width_height"]["height"] = $full_item->getHeight(); + } + $values["full_derive_caption"] = $full_alias_item->definesCaption() + ? "n" + : "y"; + $values["full_derive_text_representation"] = $full_alias_item->definesTextRepresentation() + ? "n" + : "y"; + + // parameters + if (ilObjMediaObject::_useAutoStartParameterOnly( + $full_item->getLocation(), + $full_item->getFormat() + )) { // autostart + $par = $full_alias_item->getParameters(); + if ($par["autostart"] == "true") { + $values["full_autostart"] = true; + } + } else { // parameters + $values["full_parameters"] = $full_alias_item->getParameterString(); + } + + $values["full_derive_parameters"] = $full_alias_item->definesParameters() + ? "n" + : "y"; + if (trim($full_item->getParameterString()) == "") { + $values["full_def_parameters"] = "" . $lng->txt("cont_no_parameters") . ""; + } else { + $values["full_def_parameters"] = $full_item->getParameterString(); + } + } + + $this->form_gui->setValuesByArray($values); + } + + /** + * save table properties in db and return to page edit screen + */ + public function saveAliasProperties() + { + $std_alias_item = new ilMediaAliasItem( + $this->dom, + $this->getHierId(), + "Standard", + $this->content_obj->getPcId() + ); + $full_alias_item = new ilMediaAliasItem( + $this->dom, + $this->getHierId(), + "Fullscreen", + $this->content_obj->getPcId() + ); + $std_item = $this->content_obj->getMediaObject()->getMediaItem("Standard"); + $full_item = $this->content_obj->getMediaObject()->getMediaItem("Fullscreen"); + + // standard size + if ($_POST["st_derive_size"] == "y") { + $std_alias_item->deriveSize(); + } else { + $std_alias_item->setWidth(ilUtil::stripSlashes($_POST["st_width_height"]["width"])); + $std_alias_item->setHeight(ilUtil::stripSlashes($_POST["st_width_height"]["height"])); + } + + // standard caption + if ($_POST["st_derive_caption"] == "y") { + $std_alias_item->deriveCaption(); + } else { + $std_alias_item->setCaption(ilUtil::stripSlashes($_POST["st_caption"])); + } + + // text representation + if ($_POST["st_derive_text_representation"] == "y") { + $std_alias_item->deriveTextRepresentation(); + } else { + $std_alias_item->setTextRepresentation(ilUtil::stripSlashes($_POST["st_text_representation"])); + } + + // standard parameters + if ($_POST["st_derive_parameters"] == "y") { + $std_alias_item->deriveParameters(); + } else { + if (ilObjMediaObject::_useAutoStartParameterOnly( + $std_item->getLocation(), + $std_item->getFormat() + )) { // autostart + if ($_POST["st_autostart"]) { + $std_alias_item->setParameters(ilUtil::extractParameterString('autostart="true"')); + } else { + $std_alias_item->setParameters(ilUtil::extractParameterString('autostart="false"')); + } + } else { // parameters + $std_alias_item->setParameters(ilUtil::extractParameterString(ilUtil::stripSlashes(utf8_decode($_POST["st_parameters"])))); + } + } + + if ($this->content_obj->getMediaObject()->hasFullscreenItem()) { + if ($_POST["fullscreen"] == "y") { + if (!$full_alias_item->exists()) { + $full_alias_item->insert(); + } + + // fullscreen size + if ($_POST["full_derive_size"] == "y") { + $full_alias_item->deriveSize(); + } else { + $full_alias_item->setWidth(ilUtil::stripSlashes($_POST["full_width_height"]["width"])); + $full_alias_item->setHeight(ilUtil::stripSlashes($_POST["full_width_height"]["height"])); + } + + // fullscreen caption + if ($_POST["full_derive_caption"] == "y") { + $full_alias_item->deriveCaption(); + } else { + $full_alias_item->setCaption(ilUtil::stripSlashes($_POST["full_caption"])); + } + + // fullscreen text representation + if ($_POST["full_derive_text_representation"] == "y") { + $full_alias_item->deriveTextRepresentation(); + } else { + $full_alias_item->setTextRepresentation(ilUtil::stripSlashes($_POST["full_text_representation"])); + } + + // fullscreen parameters + if ($_POST["full_derive_parameters"] == "y") { + $full_alias_item->deriveParameters(); + } else { + if (ilObjMediaObject::_useAutoStartParameterOnly( + $full_item->getLocation(), + $full_item->getFormat() + )) { // autostart + if ($_POST["full_autostart"]) { + $full_alias_item->setParameters(ilUtil::extractParameterString('autostart="true"')); + } else { + $full_alias_item->setParameters(ilUtil::extractParameterString('autostart="false"')); + } + } else { + $full_alias_item->setParameters(ilUtil::extractParameterString(ilUtil::stripSlashes(utf8_decode($_POST["full_parameters"])))); + } + } + } else { + if ($full_alias_item->exists()) { + $full_alias_item->delete(); + } + } + } + + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "editAlias"); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } else { + $this->pg_obj->addHierIDs(); + $this->editAlias(); + } + } + + /** + * copy media object to clipboard + */ + public function copyToClipboard() + { + $ilUser = $this->user; + + $ilUser->addObjectToClipboard($this->content_obj->getMediaObject()->getId(), $this->content_obj->getMediaObject()->getType(), $this->content_obj->getMediaObject()->getTitle()); + ilUtil::sendSuccess($this->lng->txt("copied_to_clipboard"), true); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * align media object to center + */ + public function centerAlign() + { + $std_alias_item = new ilMediaAliasItem( + $this->dom, + $this->getHierId(), + "Standard", + $this->content_obj->getPcId() + ); + $std_alias_item->setHorizontalAlign("Center"); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * align media object to left + */ + public function leftAlign() + { + $std_alias_item = new ilMediaAliasItem( + $this->dom, + $this->getHierId(), + "Standard", + $this->content_obj->getPcId() + ); + $std_alias_item->setHorizontalAlign("Left"); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * align media object to right + */ + public function rightAlign() + { + $std_alias_item = new ilMediaAliasItem( + $this->dom, + $this->getHierId(), + "Standard", + $this->content_obj->getPcId() + ); + $std_alias_item->setHorizontalAlign("Right"); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * align media object to left, floating text + */ + public function leftFloatAlign() + { + $std_alias_item = new ilMediaAliasItem( + $this->dom, + $this->getHierId(), + "Standard", + $this->content_obj->getPcId() + ); + $std_alias_item->setHorizontalAlign("LeftFloat"); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * align media object to right, floating text + */ + public function rightFloatAlign() + { + $std_alias_item = new ilMediaAliasItem( + $this->dom, + $this->getHierId(), + "Standard", + $this->content_obj->getPcId() + ); + $std_alias_item->setHorizontalAlign("RightFloat"); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * Checks whether style selection shoudl be available or not + */ + public function checkStyleSelection() + { + // check whether there is more than one style class + $chars = $this->getCharacteristics(); + + if (count($chars) > 1 || + ($this->content_obj->getClass() != "" && $this->content_obj->getClass() != "Media")) { + return true; + } + return false; + } + + /** + * Edit Style + */ + public function editStyle() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + $this->displayValidationError(); + + // edit form + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this)); + $form->setTitle($this->lng->txt("cont_edit_style")); + + // characteristic selection + require_once("./Services/Form/classes/class.ilAdvSelectInputGUI.php"); + $char_prop = new ilAdvSelectInputGUI( + $this->lng->txt("cont_characteristic"), + "characteristic" + ); + + $chars = $this->getCharacteristics(); + if (is_object($this->content_obj)) { + if ($chars[$a_seleted_value] == "" && ($this->content_obj->getClass() != "")) { + $chars = array_merge( + array($this->content_obj->getClass() => $this->content_obj->getClass()), + $chars + ); + } + } + + $selected = $this->content_obj->getClass(); + if ($selected == "") { + $selected = "MediaContainer"; + } + + foreach ($chars as $k => $char) { + $html = '
' . + $char . '
'; + $char_prop->addOption($k, $char, $html); + } + + $char_prop->setValue($selected); + $form->addItem($char_prop); + + // save button + $form->addCommandButton("saveStyle", $lng->txt("save")); + + $html = $form->getHTML(); + $tpl->setContent($html); + return $ret; + } + + /** + * Save Style + */ + public function saveStyle() + { + $this->content_obj->setClass($_POST["characteristic"]); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } else { + $this->pg_obj->addHierIDs(); + $this->editStyle(); + } + } + + /** + * add tabs to ilTabsGUI object + * + * @param object $tab_gui ilTabsGUI object + * @param boolean $a_create new creation true/false + */ + public function getTabs(&$tab_gui, $a_create = false, $a_change_obj_ref = false) + { + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + if (!$a_create) { + if ($this->checkStyleSelection()) { + $ilTabs->addTarget( + "cont_style", + $ilCtrl->getLinkTarget($this, "editStyle"), + "editStyle", + get_class($this) + ); + } + + $ilTabs->addTarget( + "cont_mob_inst_prop", + $ilCtrl->getLinkTarget($this, "editAlias"), + "editAlias", + get_class($this) + ); + + if ($this->getEnabledMapAreas()) { + $st_item = $this->content_obj->getMediaObject()->getMediaItem("Standard"); + if (is_object($st_item)) { + $format = $st_item->getFormat(); + if (substr($format, 0, 5) == "image" && !is_int(strpos($format, "svg"))) { + $ilTabs->addTarget( + "cont_inst_map_areas", + $ilCtrl->getLinkTargetByClass("ilpcimagemapeditorgui", "editMapAreas"), + array(), + "ilpcimagemapeditorgui" + ); + } + } + } + } else { + if ($a_change_obj_ref) { + $cmd = "changeObjectReference"; + } else { + $cmd = "insert"; + } + + $ilCtrl->setParameter($this, "subCmd", "insertNew"); + $ilTabs->addSubTabTarget( + "cont_new_mob", + $ilCtrl->getLinkTarget($this, $cmd), + $cmd + ); + + $ilCtrl->setParameter($this, "subCmd", "insertFromPool"); + $ilTabs->addSubTabTarget( + "cont_mob_from_media_pool", + $ilCtrl->getLinkTarget($this, $cmd), + $cmd + ); + $ilCtrl->setParameter($this, "subCmd", ""); + } + } } -?> diff --git a/Services/COPage/classes/class.ilPCParagraph.php b/Services/COPage/classes/class.ilPCParagraph.php index 9a179f039e04df156ec32075b043d1342a89d0ca..1b0cab51449c82d1d7e07de8ab751205a3981603 100755 --- a/Services/COPage/classes/class.ilPCParagraph.php +++ b/Services/COPage/classes/class.ilPCParagraph.php @@ -15,2187 +15,2006 @@ require_once("./Services/COPage/classes/class.ilPageContent.php"); */ class ilPCParagraph extends ilPageContent { - /** - * @var ilObjUser - */ - protected $user; - - var $dom; - var $par_node; // node of Paragraph element - - static protected $bb_tags = array( - "com" => "Comment", - "emp" => "Emph", - "str" => "Strong", - "fn" => "Footnote", - "code" => "Code", - "acc" => "Accent", - "imp" => "Important", - "kw" => "Keyw", - "sub" => "Sub", - "sup" => "Sup", - "quot" => "Quotation", - ); - - /** - * Init page content component. - */ - function init() - { - global $DIC; - - $this->user = $DIC->user(); - $this->setType("par"); - } - - /** - * Get bb to xml tag map - * - * @return array map - */ - protected static function getBBMap() - { - return self::$bb_tags; - } - - /** - * Get tag to bb map - * - * @return array map - */ - protected static function getXMLTagMap() - { - return array_flip(self::$bb_tags); - } - - - - /** - * Set Page Content Node - * - * @param object $a_node Page Content DOM Node - */ - function setNode($a_node) - { - parent::setNode($a_node); // this is the PageContent node - - $childs = $a_node->child_nodes(); - for ($i=0; $inode_name() == "Paragraph") - { - $this->par_node = $childs[$i]; //... and this the Paragraph node - } - } - } - - - /** - * Create new page content (incl. paragraph) node at node - * - * @param object $node Parent Node for Page Content - */ - function createAtNode(&$node) - { - $this->node = $this->createPageContentNode(); - $this->par_node = $this->dom->create_element("Paragraph"); - $this->par_node = $this->node->append_child($this->par_node); - $this->par_node->set_attribute("Language", ""); - $node->append_child ($this->node); - } - - /** - * Create new page content (incl. paragraph) node at node - * - * @param object $node Parent Node for Page Content - */ - function createBeforeNode(&$node) - { - $this->node = $this->createPageContentNode(); - $this->par_node = $this->dom->create_element("Paragraph"); - $this->par_node = $this->node->append_child($this->par_node); - $this->par_node->set_attribute("Language", ""); - $node->insert_before($this->node, $node); - } - - /** - * Create paragraph node (incl. page content node) - * after given node. - * - * @param object $node Predecessing node - */ - function createAfter($node) - { - $this->node = $this->createPageContentNode(false); - if($succ_node = $node->next_sibling()) - { - $this->node = $succ_node->insert_before($this->node, $succ_node); - } - else - { - $parent_node = $node->parent_node(); - $this->node = $parent_node->append_child($this->node); - } - $this->par_node = $this->dom->create_element("Paragraph"); - $this->par_node = $this->node->append_child($this->par_node); - $this->par_node->set_attribute("Language", ""); - } - - /** - * Create paragraph node (incl. page content node) - * at given hierarchical ID. - * - * @param object $a_pg_obj Page Object - * @param string $a_hier_id Hierarchical ID - */ - function create(&$a_pg_obj, $a_hier_id, $a_pc_id = "") - { -//echo "-$a_pc_id-"; -//echo "
-".htmlentities($a_pg_obj->getXMLFromDom())."-

"; mk(); - $this->node = $this->dom->create_element("PageContent"); - - // this next line kicks out placeholders, if something is inserted - $a_pg_obj->insertContent($this, $a_hier_id, IL_INSERT_AFTER, $a_pc_id); - - $this->par_node = $this->dom->create_element("Paragraph"); - $this->par_node = $this->node->append_child($this->par_node); - $this->par_node->set_attribute("Language", ""); - } - - /** - * Set (xml) content of text paragraph. - * - * @param string $a_text text content - * @param boolean $a_auto_split auto split paragraph at headlines true/false - */ - function setText($a_text, $a_auto_split = false) - { - if (!is_array($a_text)) - { - $text = array(array("level" => 0, "text" => $a_text)); - } - else - { - $text = $a_text; - } - - if ($a_auto_split) - { - $text = $this->autoSplit($a_text); - } - - // DOMXML_LOAD_PARSING, DOMXML_LOAD_VALIDATING, DOMXML_LOAD_RECOVERING - $check = ""; - foreach ($text as $t) - { - $check.= "".$t["text"].""; - } - /*$temp_dom = domxml_open_mem(''.$text[0]["text"].'', - DOMXML_LOAD_PARSING, $error);*/ - $temp_dom = domxml_open_mem(''.$check.'', - DOMXML_LOAD_PARSING, $error); - //$this->text = $a_text; - - // remove all childs - if(empty($error)) - { - $temp_dom = domxml_open_mem(''.$text[0]["text"].'', - DOMXML_LOAD_PARSING, $error); - - // delete children of paragraph node - $children = $this->par_node->child_nodes(); - for($i=0; $ipar_node->remove_child($children[$i]); - } - - // copy new content children in paragraph node - $xpc = xpath_new_context($temp_dom); - $path = "//Paragraph"; - $res = xpath_eval($xpc, $path); - if (count($res->nodeset) == 1) - { - $new_par_node = $res->nodeset[0]; - $new_childs = $new_par_node->child_nodes(); - - for($i=0; $iclone_node(true); - $this->par_node->append_child($cloned_child); - } - $orig_characteristic = $this->getCharacteristic(); - - // if headlines are entered and current characteristic is a headline - // use no characteristic as standard - if ((count($text) > 1) && (substr($orig_characteristic, 0, 8) == "Headline")) - { - $orig_characteristic = ""; - } - if ($text[0]["level"] > 0) - { - $this->par_node->set_attribute("Characteristic", 'Headline'.$text[0]["level"]); - } - } - - $ok = true; - - $c_node = $this->node; - // add other chunks afterwards - for ($i=1; $igetPage()); - $next_par->createAfter($c_node); - $next_par->setLanguage($this->getLanguage()); - if ($text[$i]["level"] > 0) - { - $next_par->setCharacteristic("Headline".$text[$i]["level"]); - } - else - { - $next_par->setCharacteristic($orig_characteristic); - } - $ok = $next_par->setText($text[$i]["text"], false); - $c_node = $next_par->node; - } - } - - return true; - } - else - { - // We want the correct number of \n here to have the real lines numbers - $text = str_replace("
", "\n", $check); // replace
with \n to get correct line - $text = str_replace("
", "\n", $text); - $text = str_replace("
", "\n", $text); - $text = str_replace("", "\n", $text); - $text = str_replace("", "\n", $text); - $text = str_replace("", "\n", $text); - $text = str_replace("\n", "", $text); - $text = str_replace("", "\n", $text); - include_once("./Services/Dom/classes/class.ilDomDocument.php"); - $doc = new ilDOMDocument(); - $text = ''.$text.''; -//echo htmlentities($text); - $this->success = $doc->loadXML($text); - $error = $doc->errors; - $estr = ""; - foreach ($error as $e) - { - $e = str_replace(" in Entity", "", $e); - $estr.= $e."
"; - } - if (DEVMODE) - { - $estr.= "
".$text; - } - - return $estr; - } - } - - /** - * Get (xml) content of paragraph. - * - * @return string Paragraph Content. - */ - function getText($a_short_mode = false) - { - if (is_object($this->par_node)) - { - $content = ""; - $childs = $this->par_node->child_nodes(); - for($i=0; $idom->dump_node($childs[$i]); - } - return $content; - } - else - { - return ""; - } - } - - /** - * Get paragraph sequenc of current paragraph - */ - function getParagraphSequenceContent($a_pg_obj) - { - $childs = $this->par_node->parent_node()->parent_node()->child_nodes(); - $seq = array(); - $cur_seq = array(); - $found = false; - $pc_id = $this->readPCId(); - $hier_id = $this->readHierId(); - for($i=0; $ichild_nodes(); - if ($pchilds[0]->node_name() == "Paragraph" && - $pchilds[0]->get_attribute("Characteristic") != "Code") - { - $cur_seq[] = $childs[$i]; - - // check whether this is the sequence of the current paragraph - if ($childs[$i]->get_attribute("PCID") == $pc_id && - $childs[$i]->get_attribute("HierId") == $hier_id) - { - $found = true; - } - - // if this is the current sequenc, get it - if ($found) - { - $seq = $cur_seq; - } - } - else - { - // non-paragraph element found -> init the current sequence - $cur_seq = array(); - $found = false; - } - } - - $content = ""; - $ids = "###"; - $id_sep = ""; - foreach ($seq as $p_node) - { - $ids.= $id_sep.$p_node->get_attribute("HierId").":".$p_node->get_attribute("PCID"); - $po = $a_pg_obj->getContentObject($p_node->get_attribute("HierId"), - $p_node->get_attribute("PCID")); - $s_text = $po->getText(); - $s_text = $po->xml2output($s_text, true, false); - $char = $po->getCharacteristic(); - if ($char == "") - { - $char = "Standard"; - } - $s_text = ilPCParagraphGUI::xml2outputJS($s_text, $char, $po->readPCId()); - $content.= $s_text; - $id_sep = ";"; - } - $ids.= "###"; - - return $ids.$content; - } - - /** - * Set Characteristic of paragraph - * - * @param string $a_char Characteristic - */ - function setCharacteristic($a_char) - { - if (!empty($a_char)) - { - $this->par_node->set_attribute("Characteristic", $a_char); - } - else - { - if ($this->par_node->has_attribute("Characteristic")) - { - $this->par_node->remove_attribute("Characteristic"); - } - } - } - - /** - * Get characteristic of paragraph. - * - * @return string characteristic - */ - function getCharacteristic() - { - if (is_object($this->par_node)) - { - return $this->par_node->get_attribute("Characteristic"); - } - } - - - /** - * set attribute subcharacteristic - */ - function setSubCharacteristic($a_char) - { - if (!empty($a_char)) - { - $this->par_node->set_attribute("SubCharacteristic", $a_char); - } - else - { - if ($this->par_node->has_attribute("SubCharacteristic")) - { - $this->par_node->remove_attribute("SubCharacteristic"); - } - } - } - - /** - * Get AutoIndent (Code Paragraphs) - * - * @param string Auto Indent attribute - */ - function getAutoIndent() - { - return $this->par_node->get_attribute("AutoIndent"); - } - - function setAutoIndent($a_char) - { - if (!empty($a_char)) - { - $this->par_node->set_attribute("AutoIndent", $a_char); - } - else - { - if ($this->par_node->has_attribute("AutoIndent")) - { - $this->par_node->remove_attribute("AutoIndent"); - } - } - } - - /** - * get attribute subcharacteristic - */ - function getSubCharacteristic() - { - return $this->par_node->get_attribute("SubCharacteristic"); - } - - /** - * set attribute download title - */ - - function setDownloadTitle($a_char) - { - if (!empty($a_char)) - { - $this->par_node->set_attribute("DownloadTitle", $a_char); - } - else - { - if ($this->par_node->has_attribute("DownloadTitle")) - { - $this->par_node->remove_attribute("DownloadTitle"); - } - } - } - - /** - * get attribute download title - */ - function getDownloadTitle() - { - return $this->par_node->get_attribute("DownloadTitle"); - } - - /** - * set attribute showlinenumbers - */ - - function setShowLineNumbers($a_char) - { - $a_char = empty($a_char)?"n":$a_char; - - $this->par_node->set_attribute("ShowLineNumbers", $a_char); - } - - /** - * get attribute showlinenumbers - * - */ - function getShowLineNumbers() - { - return $this->par_node->get_attribute("ShowLineNumbers"); - } - - /** - * set language - */ - function setLanguage($a_lang) - { - $this->par_node->set_attribute("Language", $a_lang); - } - - /** - * get language - */ - function getLanguage() - { - return $this->par_node->get_attribute("Language"); - } - - function input2xml($a_text, $a_wysiwyg = 0, $a_handle_lists = true) - { - return $this->_input2xml($a_text, $this->getLanguage(), $a_wysiwyg, $a_handle_lists); - } - - /** - * Replace bb code - * - * @param string $a_text text - * @param string $a_bb bb tag - * @param string $a_tag xml tag - * @return string - */ - static protected function replaceBBCode($a_text, $a_bb, $a_tag) - { - $a_text = preg_replace('/\['.$a_bb.'\]/i',"<".$a_tag.">",$a_text); - $a_text = preg_replace('/\[\/'.$a_bb.'\]/i',"",$a_text); - return $a_text; - } - - - /** - * converts user input to xml - */ - static function _input2xml($a_text, $a_lang, $a_wysiwyg = 0, $a_handle_lists = true) - { - if (!$a_wysiwyg) - { - $a_text = ilUtil::stripSlashes($a_text, false); - } - - if ($a_wysiwyg) - { - $a_text = str_replace("
", chr(10), $a_text); - } - - // note: the order of the processing steps is crucial - // and should be the same as in xml2output() in REVERSE order! - $a_text = trim($a_text); - -//echo "
between:".htmlentities($a_text); - - // mask html -if (!$a_wysiwyg) -{ - $a_text = str_replace("&","&",$a_text); -} - $a_text = str_replace("<","<",$a_text); - $a_text = str_replace(">",">",$a_text); - - // Reconvert PageTurn and BibItemIdentifier - $a_text = preg_replace('/<([\s\/]*?PageTurn.*?)>/i',"<$1>",$a_text); - $a_text = preg_replace('/<([\s\/]*?BibItemIdentifier.*?)>/i',"<$1>",$a_text); - -//echo "
second:".htmlentities($a_text); - - // mask curly brackets -/* -echo htmlentities($a_text); - $a_text = str_replace("{", "{", $a_text); - $a_text = str_replace("}", "}", $a_text); -echo htmlentities($a_text);*/ - // linefeed to br - $a_text = str_replace(chr(13).chr(10),"
",$a_text); - $a_text = str_replace(chr(13),"
", $a_text); - $a_text = str_replace(chr(10),"
", $a_text); - - if ($a_handle_lists) - { - $a_text = ilPCParagraph::input2xmlReplaceLists($a_text); - } - - foreach (self::getBBMap() as $bb => $tag) - { - // remove empty tags - $a_text = str_replace("[".$bb."][/".$bb."]", "", $a_text); - - // replace bb code by tag - $a_text = self::replaceBBCode($a_text, $bb, $tag); - } - - $a_text = self::intLinks2xml($a_text); - - // external link - $ws= "[ \t\r\f\v\n]*"; - // remove empty external links - while (preg_match("~\[(xln$ws(url$ws=$ws\"([^\"])*\")$ws(target$ws=$ws(\"(Glossary|FAQ|Media)\"))?$ws)\]\[\/xln\]~i", $a_text, $found)) - { - $a_text = str_replace($found[0], "",$a_text); - } - while (preg_match('~\[(xln$ws(url$ws=$ws(([^]])*)))$ws\]\[\/xln\]~i', $a_text, $found)) - { - $a_text = str_replace($found[0], "",$a_text); - } - // external links - while (preg_match("~\[(xln$ws(url$ws=$ws\"([^\"])*\")$ws(target$ws=$ws(\"(Glossary|FAQ|Media)\"))?$ws)\]~i", $a_text, $found)) - { - $attribs = ilUtil::attribsToArray($found[2]); - if (isset($attribs["url"])) - { - $a2 = ilUtil::attribsToArray($found[4]); - $tstr = ""; - if (in_array($a2["target"], array("FAQ", "Glossary", "Media"))) - { - $tstr = ' TargetFrame="'.$a2["target"].'"'; - } - $a_text = str_replace("[".$found[1]."]", "", $a_text); - } - else - { - $a_text = str_replace("[".$found[1]."]", "[error: xln".$found[1]."]",$a_text); - } - } - - // ie/tinymce fix for links without "", see bug #8391 - while (preg_match('~\[(xln$ws(url$ws=$ws(([^]])*)))$ws\]~i', $a_text, $found)) - { - if ($found[3] != "") - { - $a_text = str_replace("[".$found[1]."]", "", $a_text); - } - else - { - $a_text = str_replace("[".$found[1]."]", "[error: xln".$found[1]."]",$a_text); - } - } - $a_text = preg_replace('~\[\/xln\]~i',"",$a_text); - - // anchor - $ws= "[ \t\r\f\v\n]*"; - while (preg_match("~\[(anc$ws(name$ws=$ws\"([^\"])*\")$ws)\]~i", $a_text, $found)) - { - $attribs = ilUtil::attribsToArray($found[2]); - $a_text = str_replace("[".$found[1]."]", "", $a_text); - } - $a_text = preg_replace("~\[\/anc\]~i", "",$a_text); - - // marked text - while (preg_match("~\[(marked$ws(class$ws=$ws\"([^\"])*\")$ws)\]~i", $a_text, $found)) - { - $attribs = ilUtil::attribsToArray($found[2]); - if (isset($attribs["class"])) - { - $a_text = str_replace("[".$found[1]."]", "", $a_text); - } - else - { - $a_text = str_replace("[".$found[1]."]", "[error:marked".$found[1]."]",$a_text); - } - } - $a_text = preg_replace('~\[\/marked\]~i',"",$a_text); - - -//echo htmlentities($a_text); exit; - return $a_text; - } - - /** - * internal links to xml - * - * @param - * @return - */ - static function intLinks2xml($a_text) - { - global $DIC; - - $objDefinition = $DIC["objDefinition"]; - - $rtypes = $objDefinition->getAllRepositoryTypes(); - - // internal links - //$any = "[^\]]*"; // this doesn't work :-( - $ws= "[ \t\r\f\v\n]*"; - $ltypes = "page|chap|term|media|obj|dfile|sess|wpage|ppage|".implode($rtypes, "|"); - // empty internal links - while (preg_match('~\[(iln'.$ws.'((inst'.$ws.'='.$ws.'([\"0-9])*)?'.$ws. - "((".$ltypes.")$ws=$ws([\"0-9])*)$ws". - "(target$ws=$ws(\"(New|FAQ|Media)\"))?$ws(anchor$ws=$ws(\"([^\"])*\"))?$ws))\]\[\/iln\]~i", $a_text, $found)) - { - $a_text = str_replace($found[0], "",$a_text); - } - while (preg_match('~\[(iln'.$ws.'((inst'.$ws.'='.$ws.'([\"0-9])*)?'.$ws. - "((".$ltypes.")$ws=$ws([\"0-9])*)$ws". - "(target$ws=$ws(\"(New|FAQ|Media)\"))?$ws(anchor$ws=$ws(\"([^\"])*\"))?$ws))\]~i", $a_text, $found)) - { - $attribs = ilUtil::attribsToArray($found[2]); - $inst_str = $attribs["inst"]; - // pages - if (isset($attribs["page"])) - { - $tframestr = ""; - if (!empty($found[10])) - { - $tframestr = " TargetFrame=\"".$found[10]."\" "; - } - $ancstr = ""; - if ($attribs["anchor"] != "") - { - $ancstr = ' Anchor="'.$attribs["anchor"].'" '; - } - // see 26066 for addcslashes - $a_text = preg_replace('/\['.addcslashes($found[1], '/').'\]/i', - "", $a_text); - } - // chapters - else if (isset($attribs["chap"])) - { - if (!empty($found[10])) - { - $tframestr = " TargetFrame=\"".$found[10]."\" "; - } - else - { - $tframestr = ""; - } - $a_text = preg_replace('/\['.$found[1].'\]/i', - "", $a_text); - } - // glossary terms - else if (isset($attribs["term"])) - { - switch ($found[10]) - { - case "New": - $tframestr = " TargetFrame=\"New\" "; - break; - - default: - $tframestr = " TargetFrame=\"Glossary\" "; - break; - } - $a_text = preg_replace('/\['.$found[1].'\]/i', - "", $a_text); - } - // wiki pages - else if (isset($attribs["wpage"])) - { - $tframestr = ""; - $a_text = preg_replace('/\['.$found[1].'\]/i', - "", $a_text); - } - // portfolio pages - else if (isset($attribs["ppage"])) - { - $tframestr = ""; - $a_text = preg_replace('/\['.$found[1].'\]/i', - "", $a_text); - } - // media object - else if (isset($attribs["media"])) - { - if (!empty($found[10])) - { - $tframestr = " TargetFrame=\"".$found[10]."\" "; - $a_text = preg_replace('/\['.$found[1].'\]/i', - "", $a_text); - } - else - { - $a_text = preg_replace('/\['.$found[1].'\]/i', - "", $a_text); - } - } - // direct download file (no repository object) - else if (isset($attribs["dfile"])) - { - $a_text = preg_replace('/\['.$found[1].'\]/i', - "", $a_text); - } - // repository items (id is ref_id (will be used internally but will - // be replaced by object id for export purposes) - else - { - foreach ($objDefinition->getAllRepositoryTypes() as $t) - { - if (isset($attribs[$t])) - { - $obj_id = $attribs[$t]; - } - } - if (isset($attribs["obj"])) - { - $obj_id = $attribs["obj"]; - } - - if ($obj_id > 0) - { - if ($inst_str == "") - { - $a_text = preg_replace('/\['.$found[1].'\]/i', - "", $a_text); - } - else - { - $a_text = preg_replace('/\['.$found[1].'\]/i', - "", $a_text); - } - } - else - { - $a_text = preg_replace('/\['.$found[1].'\]/i', "[error: iln".$found[1]."]",$a_text); - } - } - } - - while (preg_match("~\[(iln$ws((inst$ws=$ws([\"0-9])*)?".$ws."media$ws=$ws([\"0-9])*)$ws)/\]~i", $a_text, $found)) - { - $attribs = ilUtil::attribsToArray($found[2]); - $inst_str = $attribs["inst"]; - $a_text = preg_replace('~\['.$found[1].'/\]~i', - "", $a_text); - } - - // user - while (preg_match("~\[(iln$ws((inst$ws=$ws([\"0-9])*)?".$ws."user$ws=$ws(\"([^\"])*)\")$ws)/\]~i", $a_text, $found)) - { - $attribs = ilUtil::attribsToArray($found[2]); - $inst_str = $attribs["inst"]; - include_once("./Services/User/classes/class.ilObjUser.php"); - $user_id = ilObjUser::_lookupId($attribs['user']); - $a_text = preg_replace('~\['.$found[1].'/\]~i', - "", $a_text); - } - - $a_text = preg_replace('~\[\/iln\]~i',"",$a_text); - return $a_text; - } - - - /** - * Converts xml from DB to output in edit textarea. - * - * @param string $a_text xml from db - * - * @return string string ready for edit textarea - */ - static function input2xmlReplaceLists($a_text) - { - $rows = explode("
", $a_text."
"); -//var_dump($a_text); - - $old_level = 0; - - $text = ""; - - foreach ($rows as $row) - { - $level = 0; - if (str_replace("#", "*", substr($row, 0, 3)) == "***") - { - $level = 3; - } - else if (str_replace("#", "*", substr($row, 0, 2)) == "**") - { - $level = 2; - } - else if (str_replace("#", "*", substr($row, 0, 1)) == "*") - { - $level = 1; - } - - // end previous line - if ($level < $old_level) - { - for ($i = $old_level; $i > $level; $i--) - { - $text.= ""; - } - if ($level > 0) - { - $text.= ""; - } - } - else if ($old_level > 0 && $level > 0 && ($level == $old_level)) - { - $text.= ""; - } - else if (($level == $old_level) && $text != "") - { - $text.= "
"; - } - - // start next line - if ($level > $old_level) - { - for($i = $old_level + 1; $i <= $level; $i++) - { - if (substr($row, $i - 1, 1) == "*") - { - $clist[$i] = "SimpleBulletList"; - } - else - { - $clist[$i] = "SimpleNumberedList"; - } - $text.= "<".$clist[$i].">"; - } - } - else if ($old_level > 0 && $level > 0) - { - $text.= ""; - } - $text.= substr($row, $level); - - $old_level = $level; - } - - // remove "
" at the end - if (substr($text, strlen($text) - 6) == "
") - { - $text = substr($text, 0, strlen($text) - 6); - } - - return $text; - } - - /** - * Replaces tags with * - * - * @param string $a_text xml from db - * - * @return string string containing * for lists - */ - static function xml2outputReplaceLists($a_text) - { - $segments = ilPCParagraph::segmentString($a_text, array("", "", - "
", "", "", "", "")); - - $current_list = array(); - $text = ""; - for ($i=0; $i<= count($segments); $i++) - { - if ($segments[$i] == "") - { - if (count($current_list) == 0) - { - $list_start = true; - } - array_push($current_list, "*"); - $li = false; - } - else if ($segments[$i] == "") - { - if (count($current_list) == 0) - { - $list_start = true; - } - array_push($current_list, "#"); - $li = false; - } - else if ($segments[$i] == "") - { - array_pop($current_list); - $li = false; - } - else if ($segments[$i] == "
") - { - array_pop($current_list); - $li = false; - } - else if ($segments[$i] == "") - { - $li = true; - } - else if ($segments[$i] == "") - { - $li = false; - } - else if ($segments[$i] == "") - { - if ($list_start) - { - $text.= "
"; - $list_start = false; - } - foreach($current_list as $list) - { - $text.= $list; - } - $text.= "
"; - $li = false; - } - else - { - if ($li) - { - if ($list_start) - { - $text.= "
"; - $list_start = false; - } - foreach($current_list as $list) - { - $text.= $list; - } - } - $text.= $segments[$i]; - if ($li) - { - $text.= "
"; - } - $li = false; - } - } - - // remove trailing
, if text ends with list - if ($segments[count($segments) - 1] == "
" || - $segments[count($segments) - 1] == "" && - substr($text, strlen($text) - 6) == "
") - { - $text = substr($text, 0, strlen($text) - 6); - } - - return $text; - } - - /** - * Segments a string into an array at each position of a substring - */ - static function segmentString($a_haystack, $a_needles) - { - $segments = array(); - - $nothing_found = false; - while (!$nothing_found) - { - $nothing_found = true; - $found = -1; - foreach($a_needles as $needle) - { - $pos = stripos($a_haystack, $needle); - if (is_int($pos) && ($pos < $found || $found == -1)) - { - $found = $pos; - $found_needle = $needle; - $nothing_found = false; - } - } - if ($found > 0) - { - $segments[] = substr($a_haystack, 0, $found); - $a_haystack = substr($a_haystack, $found); - } - if ($found > -1) - { - $segments[] = substr($a_haystack, 0, strlen($found_needle)); - $a_haystack = substr($a_haystack, strlen($found_needle)); - } - } - if ($a_haystack != "") - { - $segments[] = $a_haystack; - } - - return $segments; - } - - /** - * Converts xml from DB to output in edit textarea. - * - * @param string $a_text xml from db - * - * @return string string ready for edit textarea - */ - static function xml2output($a_text, $a_wysiwyg = false, $a_replace_lists = true) - { - // note: the order of the processing steps is crucial - // and should be the same as in input2xml() in REVERSE order! - - // xml to bb code - $any = "[^>]*"; - - foreach (self::getBBMap() as $bb => $tag) - { - $a_text = preg_replace('~<'.$tag.'[^>]*>~i',"[".$bb."]", $a_text); - $a_text = preg_replace('~~i',"[/".$bb."]", $a_text); - $a_text = preg_replace('~<'.$tag.'/>~i',"[".$bb."][/".$bb."]", $a_text); - } - - // replace lists - if ($a_replace_lists) - { -//echo "
".htmlentities($a_text); - $a_text = ilPCParagraph::xml2outputReplaceLists($a_text); -//echo "
".htmlentities($a_text); - } - - // internal links - while (preg_match('~~i', $a_text, $found)) - { - $found[0]; - $attribs = ilUtil::attribsToArray($found[1]); - $target = explode("_", $attribs["Target"]); - $target_id = $target[count($target) - 1]; - $inst_str = (!is_int(strpos($attribs["Target"], "__"))) - ? $inst_str = "inst=\"".$target[1]."\" " - : $inst_str = ""; - switch($attribs["Type"]) - { - case "PageObject": - $tframestr = (!empty($attribs["TargetFrame"])) - ? " target=\"".$attribs["TargetFrame"]."\"" - : ""; - $ancstr = (!empty($attribs["Anchor"])) - ? ' anchor="'.$attribs["Anchor"].'"' - : ""; - $a_text = preg_replace('~~i',"[iln ".$inst_str."page=\"".$target_id."\"$tframestr$ancstr]",$a_text); - break; - - case "StructureObject": - $tframestr = (!empty($attribs["TargetFrame"])) - ? " target=\"".$attribs["TargetFrame"]."\"" - : ""; - $a_text = preg_replace('~~i',"[iln ".$inst_str."chap=\"".$target_id."\"$tframestr]",$a_text); - break; - - case "GlossaryItem": - $tframestr = (empty($attribs["TargetFrame"]) || $attribs["TargetFrame"] == "Glossary") - ? "" - : " target=\"".$attribs["TargetFrame"]."\""; - $a_text = preg_replace('~~i',"[iln ".$inst_str."term=\"".$target_id."\"".$tframestr."]",$a_text); - break; - - case "WikiPage": - $tframestr = ""; - $a_text = preg_replace('~~i',"[iln ".$inst_str."wpage=\"".$target_id."\"".$tframestr."]",$a_text); - break; - - case "PortfolioPage": - $tframestr = ""; - $a_text = preg_replace('~~i',"[iln ".$inst_str."ppage=\"".$target_id."\"".$tframestr."]",$a_text); - break; - - case "MediaObject": - if (empty($attribs["TargetFrame"])) - { - $a_text = preg_replace('~~i',"[iln ".$inst_str."media=\"".$target_id."\"/]",$a_text); - } - else - { - $a_text = preg_replace('~~i',"[iln media=\"".$target_id."\"". - " target=\"".$attribs["TargetFrame"]."\"]",$a_text); - } - break; - - // Repository Item (using ref id) - case "RepositoryItem": - if ($inst_str == "") - { - $target_type = ilObject::_lookupType($target_id, true); - } - else - { - $rtype = $target[count($target) - 2]; - $target_type = $rtype; - } - $a_text = preg_replace('~~i',"[iln ".$inst_str."$target_type=\"".$target_id."\"".$tframestr."]",$a_text); - break; - - // Download File (not in repository, Object ID) - case "File": - $a_text = preg_replace('~~i',"[iln ".$inst_str."dfile=\"".$target_id."\"".$tframestr."]",$a_text); - break; - - // User - case "User": - include_once("./Services/User/classes/class.ilObjUser.php"); - $a_text = preg_replace('~~i',"[iln ".$inst_str."user=\"".ilObjUser::_lookupLogin($target_id)."\"/]",$a_text); - break; - - default: - $a_text = preg_replace('~~i',"[iln]",$a_text); - break; - } - } - $a_text = str_replace("","[/iln]",$a_text); - - // external links - while (preg_match('~~i', $a_text, $found)) - { - $found[0]; - $attribs = ilUtil::attribsToArray($found[1]); - //$found[1] = str_replace("?", "\?", $found[1]); - $tstr = ""; - if (in_array($attribs["TargetFrame"], array("FAQ", "Glossary", "Media"))) - { - $tstr = ' target="'.$attribs["TargetFrame"].'"'; - } - $a_text = str_replace("","[xln url=\"".$attribs["Href"]."\"$tstr]",$a_text); - } - $a_text = str_replace("","[/xln]",$a_text); - - // anchor - while (preg_match('~~i', $a_text, $found)) - { - $found[0]; - $attribs = ilUtil::attribsToArray($found[1]); - $a_text = str_replace("","[anc name=\"".$attribs["Name"]."\"][/anc]",$a_text); - } - while (preg_match('~~i', $a_text, $found)) - { - $found[0]; - $attribs = ilUtil::attribsToArray($found[1]); - $a_text = str_replace("","[anc name=\"".$attribs["Name"]."\"]",$a_text); - } - $a_text = str_replace("","[/anc]",$a_text); - - // marked text - while (preg_match('~~i', $a_text, $found)) - { - $found[0]; - $attribs = ilUtil::attribsToArray($found[1]); - $a_text = str_replace("","[marked class=\"".$attribs["Class"]."\"]",$a_text); - } - $a_text = str_replace("","[/marked]",$a_text); - - // br to linefeed - if (!$a_wysiwyg) - { - $a_text = str_replace("
", "\n", $a_text); - $a_text = str_replace("
", "\n", $a_text); - } - -if (!$a_wysiwyg) -{ - // prevent curly brackets from being swallowed up by template engine - $a_text = str_replace("{", "{", $a_text); - $a_text = str_replace("}", "}", $a_text); - - // unmask html - $a_text = str_replace("<", "<", $a_text); - $a_text = str_replace(">", ">",$a_text); - - // this is needed to allow html like ... in paragraphs - $a_text = str_replace(""", "\"", $a_text); - - // make ampersands in (enabled) html attributes work - // e.g. hhh - $a_text = str_replace("&", "&", $a_text); - - // make > and $lt; work to allow (disabled) html descriptions - $a_text = str_replace("<", "&lt;", $a_text); - $a_text = str_replace(">", "&gt;", $a_text); -} - return $a_text; - //return str_replace("
", chr(13).chr(10), $a_text); - } - - /** - * This function splits a paragraph text that has been already - * processed with input2xml at each header position =header1=, - * ==header2== or ===header3=== and returns an array that contains - * the single chunks. - */ - function autoSplit($a_text) - { - $a_text = str_replace ("=", "=
", $a_text); - $a_text = str_replace ("=", "=
", $a_text); - $a_text = str_replace ("
=", "

=", $a_text); - $a_text = str_replace ("=", "
=", $a_text); - $a_text = "
".$a_text."
"; // add preceding and trailing br - - $chunks = array(); - $c_text = $a_text; -//echo "0"; - while ($c_text != "") - { -//var_dump($c_text); flush(); -//echo "1"; - $s1 = strpos($c_text, "
="); - if (is_int($s1)) - { -//echo "2"; - $s2 = strpos($c_text, "
=="); - if (is_int($s2) && $s2 <= $s1) - { -//echo "3"; - $s3 = strpos($c_text, "
==="); - if (is_int($s3) && $s3 <= $s2) // possible level three header - { -//echo "4"; - $n = strpos($c_text, "
", $s3 + 1); - if ($n > ($s3+9) && substr($c_text, $n-3, 9) == "===
") - { -//echo "5"; - // found level three header - if ($s3 > 0 || $head != "") - { -//echo "6"; - $chunks[] = array("level" => 0, - "text" => $this->removeTrailingBr($head.substr($c_text, 0, $s3))); - $head = ""; - } - $chunks[] = array("level" => 3, - "text" => trim(substr($c_text, $s3+9, $n-$s3-12))); - $c_text = $this->handleNextBr(substr($c_text, $n+6)); - } - else - { -//echo "7"; - $head.= substr($c_text, 0, $n); - $c_text = substr($c_text, $n); - } - } - else // possible level two header - { -//echo "8"; - $n = strpos($c_text, "
", $s2 + 1); - if ($n > ($s2+8) && substr($c_text, $n-2, 8) == "==
") - { -//echo "9"; - // found level two header - if ($s2 > 0 || $head != "") - { -//echo "A"; - $chunks[] = array("level" => 0, - "text" => $this->removeTrailingBr($head.substr($c_text, 0, $s2))); - $head = ""; - } - $chunks[] = array("level" => 2, "text" => trim(substr($c_text, $s2+8, $n-$s2-10))); - $c_text = $this->handleNextBr(substr($c_text, $n+6)); - } - else - { -//echo "B"; - $head.= substr($c_text, 0, $n); - $c_text = substr($c_text, $n); - } - } - } - else // possible level one header - { -//echo "C"; - $n = strpos($c_text, "
", $s1 + 1); - if ($n > ($s1+7) && substr($c_text, $n-1, 7) == "=
") - { -//echo "D"; - // found level one header - if ($s1 > 0 || $head != "") - { -//echo "E"; - $chunks[] = array("level" => 0, - "text" => $this->removeTrailingBr($head.substr($c_text, 0, $s1))); - $head = ""; - } - $chunks[] = array("level" => 1, "text" => trim(substr($c_text, $s1+7, $n-$s1-8))); - $c_text = $this->handleNextBr(substr($c_text, $n+6)); -//echo "
ctext:".htmlentities($c_text)."
"; - } - else - { - $head.= substr($c_text, 0, $n); - $c_text = substr($c_text, $n); -//echo "
head:".$head."c_text:".$c_text."
"; - } - } - } - else - { -//echo "G"; - $chunks[] = array("level" => 0, "text" => $head.$c_text); - $head = ""; - $c_text = ""; - } - } - if (count($chunks) == 0) - { - $chunks[] = array("level" => 0, "text" => ""); - } - - - // remove preceding br - if (substr($chunks[0]["text"], 0, 6) == "
") - { - $chunks[0]["text"] = substr($chunks[0]["text"], 6); - } - - // remove trailing br - if (substr($chunks[count($chunks) - 1]["text"], - strlen($chunks[count($chunks) - 1]["text"]) - 6, 6) == "
") - { - $chunks[count($chunks) - 1]["text"] = - substr($chunks[count($chunks) - 1]["text"], 0, strlen($chunks[count($chunks) - 1]["text"]) - 6); - if ($chunks[count($chunks) - 1]["text"] == "") - { - unset($chunks[count($chunks) - 1]); - } - } - return $chunks; - } - - /** - * Remove preceding
- */ - function handleNextBr($a_str) - { - // do not remove, if next line starts with a "=", otherwise two - // headlines in a row will not be recognized - if (substr($a_str, 0, 6) == "
" && substr($a_str, 6, 1) != "=") - { - $a_str = substr($a_str, 6); - } - else - { - // if next line starts with a "=" we need to reinsert the
- // otherwise it will not be recognized - if (substr($a_str, 0, 1) == "=") - { - $a_str = "
".$a_str; - } - } - return $a_str; - } - - /** - * Remove trailing
- */ - function removeTrailingBr($a_str) - { - if (substr($a_str, strlen($a_str) - 6) == "
") - { - $a_str = substr($a_str, 0, strlen($a_str) - 6); - } - return $a_str; - } - - /** - * Need to override getType from ilPageContent to distinguish between Pararagraph and Source - */ - function getType() - { - return ($this->getCharacteristic() == "Code")?"src":parent::getType(); - } - - //// - //// Ajax related procedures - //// - - /** - * Save input coming from ajax - * - * @param - * @return - */ - function saveJS($a_pg_obj, $a_content, $a_char, $a_pc_id, $a_insert_at = "") - { - $ilUser = $this->user; - - $this->log->debug("step 1: ".substr($a_content, 0, 1000)); - $t = self::handleAjaxContent($a_content); - $this->log->debug("step 2: ".substr($t["text"], 0, 1000)); - if ($t === false) - { - return false; - } - - $pc_id = explode(":", $a_pc_id); - $insert_at = explode(":", $a_insert_at); - $t_id = explode(":", $t["id"]); - - // insert new paragraph - if ($a_insert_at != "") - { - $par = new ilPCParagraph($this->getPage()); - $par->create($a_pg_obj, $insert_at[0], $insert_at[1]); - } - else - { - $par = $a_pg_obj->getContentObject($pc_id[0], $pc_id[1]); - } - - if ($a_insert_at != "") - { - $pc_id = $a_pg_obj->generatePCId(); - $par->writePCId($pc_id); - $this->inserted_pc_id = $pc_id; - } - else - { - $this->inserted_pc_id = $pc_id[1]; - } - - $par->setLanguage($ilUser->getLanguage()); - $par->setCharacteristic($t["class"]); - - $t2 = $par->input2xml($t["text"], true, false); - $this->log->debug("step 3: ".substr($t2, 0, 1000)); - - $t2 = ilPCParagraph::handleAjaxContentPost($t2); - $this->log->debug("step 4: ".substr($t2, 0, 1000)); - - $updated = $par->setText($t2, true); - - if ($updated !== true) - { - echo $updated; exit; - return false; - } - $updated = $par->updatePage($a_pg_obj); - //$updated = $a_pg_obj->update(); - return $updated; - } - - /** - * Get last inserted pc ids - * - * @param - * @return - */ - function getLastSavedPCId($a_pg_obj, $a_as_ajax_str = false) - { - if ($a_as_ajax_str) - { - $a_pg_obj->stripHierIDs(); - $a_pg_obj->addHierIds(); - $ids = "###"; -//var_dump($this->inserted_pc_ids); - $combined = $a_pg_obj->getHierIdsForPCIds( - array($this->inserted_pc_id)); - foreach ($combined as $pc_id => $hier_id) - { -//echo "1"; - $ids.= $sep.$hier_id.":".$pc_id; - $sep = ";"; - } - $ids.= "###"; - return $ids; - } - - return $this->inserted_pc_id; - } - - - /** - * Handle ajax content - */ - static function handleAjaxContent($a_content) - { - $a_content = "".$a_content.""; - - $doc = new DOMDocument(); - - $content = ilUtil::stripSlashes($a_content, false); - -// $content = str_replace("<", "<", $content); -// $content = str_replace(">", ">", $content); -//echo "

".htmlentities($content); mk(); - $res = $doc->loadXML($content); - - if (!$res) - { - return false; - } - - // convert tags - $xpath = new DOMXpath($doc); - - $tags = self::getXMLTagMap(); - - $elements = $xpath->query("//span"); - include_once("./Services/Utilities/classes/class.ilDOM2Util.php"); - while (!is_null($elements) && !is_null($element = $elements->item(0))) - { - //$element = $elements->item(0); - $class = $element->getAttribute("class"); - if (substr($class, 0, 16) == "ilc_text_inline_") - { - $class_arr = explode(" ", $class); - $tag = substr($class_arr[0], 16); - if (isset($tags[$tag])) // known tag like strong - { - $cnode = ilDOM2Util::changeName($element, "il" . substr($class_arr[0], 16), false); - } - else // unknown tag -> marked text - { - $cnode = ilDOM2Util::changeName($element, "ilMarked", false); - $cnode->setAttribute("Class", substr($class_arr[0], 16)); - } - for ($i = 1; $i < count($class_arr); $i++) - { - $tag = substr($class_arr[$i], 16); - if (isset($tags[$tag])) // known tag like strong - { - $cnode = ilDOM2Util::addParent($cnode, "il" . substr($class_arr[$i], 16)); - } - else // unknown tag -> marked element - { - $cnode = ilDOM2Util::addParent($cnode, "ilMarked"); - $cnode->setAttribute("Class", substr($class_arr[$i], 16)); - } - } - } - else - { - ilDOM2Util::replaceByChilds($element); - } - - $elements = $xpath->query("//span"); - } - - // convert tags - $xpath = new DOMXpath($doc); - $elements = $xpath->query("/dummy/div"); - - $ret = array(); - if (!is_null($elements)) - { - foreach ($elements as $element) - { - $id = $element->getAttribute("id"); - $class = $element->getAttribute("class"); - $class = substr($class, 15); - if (trim($class) == "") - { - $class = "Standard"; - } - - $text = $doc->saveXML($element); - $text = str_replace("
", "\n", $text); - - // remove wrapping div - $pos = strpos($text, ">"); - $text = substr($text, $pos + 1); - $pos = strrpos($text, "<"); - $text = substr($text, 0, $pos); - - // todo: remove empty spans - - // replace tags by bbcode - foreach (ilPageContentGUI::_getCommonBBButtons() as $bb => $cl) - { - if (!in_array($bb, array("code", "tex", "fn", "xln"))) - { - $text = str_replace("", - "[".$bb."]", $text); - $text = str_replace("", - "[/".$bb."]", $text); - $text = str_replace("", "", $text); - } - } - $text = str_replace(array("", ""), - 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('
    ', "", $text); - $text = str_replace('
      ', "", $text); - - // replace marked text - // external links - $any = "[^>]*"; - while (preg_match('~~i', $text, $found)) - { - $found[0]; - $attribs = ilUtil::attribsToArray($found[1]); - $text = str_replace("","[marked class=\"".$attribs["Class"]."\"]",$text); - } - $text = str_replace("","[/marked]", $text); - - - $ret[] = array("text" => $text, "id" => $id, "class" => $class); - } - } - - // we should only have one here! - return $ret[0]; - } - - /** - * Post input2xml handling of ajax content - */ - static function handleAjaxContentPost($text) - { - $text = str_replace(array("<ul>", "</ul>"), - array("", ""), $text); - $text = str_replace(array("<ul class='ilc_list_u_BulletedList'>", "</ul>"), - array("", ""), $text); - $text = str_replace(array("<ul class=\"ilc_list_u_BulletedList\">", "</ul>"), - array("", ""), $text); - $text = str_replace(array("<ol>", "</ol>"), - array("", ""), $text); - $text = str_replace(array("<ol class='ilc_list_o_NumberedList'>", "</ol>"), - array("", ""), $text); - $text = str_replace(array("<ol class=\"ilc_list_o_NumberedList\">", "</ol>"), - array("", ""), $text); - $text = str_replace(array("<li>", "</li>"), - array("", ""), $text); - $text = str_replace(array("<li class='ilc_list_item_StandardListItem'>", "</li>"), - array("", ""), $text); - $text = str_replace(array("<li class=\"ilc_list_item_StandardListItem\">", "</li>"), - array("", ""), $text); - - $text = str_replace(array("<li class=\"ilc_list_item_StandardListItem\"/>"), - array(""), $text); - - $text = str_replace("
      ", "", $text); - $text = str_replace("
      ", "", $text); - $text = str_replace("
      ", "", $text); - $text = str_replace("
      ", "", $text); - $text = str_replace("

      ", "
      ", $text); - $text = str_replace("

      ", "
      ", $text); - $text = str_replace("
      ", "", $text); - - return $text; - } - - /** - * Update page object - * (it would be better to have this centralized and to change the constructors - * and pass the page object instead the dom object) - * @param - * @return - */ - function updatePage($a_page) - { - $a_page->beforePageContentUpdate($this); - - $ret = $a_page->update(); - return $ret; - } - - /** - * Auto link glossaries - * - * @param - * @return - */ - function autoLinkGlossaries($a_glos) - { - if (is_array($a_glos) && count($a_glos) > 0) - { - include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - - // check which terms occur in the text (we may - // get some false positives due to the strip_tags, but - // we do not want to find strong or list or other stuff - // within the tags - $text = strip_tags($this->getText()); - $found_terms = array(); - foreach ($a_glos as $glo) - { - if (ilObject::_lookupType($glo) == "glo") - { - $terms = ilGlossaryTerm::getTermList($glo); - foreach ($terms as $t) - { - if (is_int(stripos($text, $t["term"]))) - { - $found_terms[$t["id"]] = $t; - } - } - } - } - - // did we find anything? -> modify content - if (count($found_terms) > 0) - { - self::linkTermsInDom($this->dom, $found_terms, $this->par_node); - } - } - } - - /** - * Link terms in a dom page object in bb style - * - * @param - * @return - */ - protected static function linkTermsInDom($a_dom, $a_terms, $a_par_node = null) - { - // sort terms by their length (shortes first) - // to prevent that nested tags are builded - foreach ($a_terms as $k => $t) - { - $a_terms[$k]["termlength"] = strlen($t["term"]); - } - $a_terms = ilUtil::sortArray($a_terms, "termlength", "asc", true); - - - if ($a_dom instanceof php4DOMDocument) - { - $a_dom = $a_dom->myDOMDocument; - } - if ($a_par_node instanceof php4DOMElement) - { - $a_par_node = $a_par_node->myDOMNode; - } - - $xpath = new DOMXPath($a_dom); - - if ($a_par_node == null) - { - $parnodes = $xpath->query("//Paragraph[@Characteristic != 'Code']"); - } - else - { - $parnodes = $xpath->query(".//Paragraph[@Characteristic != 'Code']", $a_par_node->parentNode); - } - - include_once("./Services/Utilities/classes/class.ilStr.php"); - - foreach ($parnodes as $parnode) - { - $textnodes = $xpath->query('.//text()', $parnode); - foreach ($textnodes as $node) - { - $p = $node->getNodePath(); - - // we do not change text nodes inside of links - if (!is_int(strpos($p, "/IntLink")) && - !is_int(strpos($p, "/ExtLink"))) - { - $node_val = $node->nodeValue; - - // all terms - foreach ($a_terms as $t) - { - $pos = ilStr::strIPos($node_val, $t["term"]); - - // if term found - while (is_int($pos)) - { - // check if we are in a tex tag, see #22261 - $tex_bpos = ilStr::strrPos(ilStr::subStr($node_val, 0, $pos), "[tex]"); - $tex_epos = ilStr::strPos($node_val, "[/tex]", $tex_bpos); - if ($tex_bpos > 0 && $tex_epos > 0 && $tex_bpos < $pos && $tex_epos > $pos) - { - $pos+= ilStr::strLen($t["term"]); - } - else - { - - // check if the string is not included in another word - // note that [] - $valid_limiters = array("", " ", " ", ".", ",", ":", ";", "!", "?", "\"", "'", "(", ")"); - $b = ($pos > 0) - ? ilStr::subStr($node_val, $pos - 1, 1) - : ""; - $a = ilStr::subStr($node_val, $pos + ilStr::strLen($t["term"]), 1); - if ((in_array($b, $valid_limiters) || htmlentities($b, null, 'utf-8') == " ") && in_array($a, $valid_limiters)) - { - $mid = '[iln term="' . $t["id"] . '"]' . - ilStr::subStr($node_val, $pos, ilStr::strLen($t["term"])) . - "[/iln]"; - - $node_val = ilStr::subStr($node_val, 0, $pos) . - $mid . - ilStr::subStr($node_val, $pos + ilStr::strLen($t["term"])); - - $pos += ilStr::strLen($mid); - } else - { - $pos += ilStr::strLen($t["term"]); - } - } - $pos = ilStr::strIPos($node_val, $t["term"], $pos); - } - - // insert [iln] tags - } - - $node->nodeValue = $node_val; - } - -// var_dump($p); + /** + * @var ilObjUser + */ + protected $user; + + public $dom; + public $par_node; // node of Paragraph element + + protected static $bb_tags = array( + "com" => "Comment", + "emp" => "Emph", + "str" => "Strong", + "fn" => "Footnote", + "code" => "Code", + "acc" => "Accent", + "imp" => "Important", + "kw" => "Keyw", + "sub" => "Sub", + "sup" => "Sup", + "quot" => "Quotation", + ); + + /** + * Init page content component. + */ + public function init() + { + global $DIC; + + $this->user = $DIC->user(); + $this->setType("par"); + } + + /** + * Get bb to xml tag map + * + * @return array map + */ + protected static function getBBMap() + { + return self::$bb_tags; + } + + /** + * Get tag to bb map + * + * @return array map + */ + protected static function getXMLTagMap() + { + return array_flip(self::$bb_tags); + } + + + + /** + * Set Page Content Node + * + * @param object $a_node Page Content DOM Node + */ + public function setNode($a_node) + { + parent::setNode($a_node); // this is the PageContent node + + $childs = $a_node->child_nodes(); + for ($i=0; $inode_name() == "Paragraph") { + $this->par_node = $childs[$i]; //... and this the Paragraph node + } + } + } + + + /** + * Create new page content (incl. paragraph) node at node + * + * @param object $node Parent Node for Page Content + */ + public function createAtNode(&$node) + { + $this->node = $this->createPageContentNode(); + $this->par_node = $this->dom->create_element("Paragraph"); + $this->par_node = $this->node->append_child($this->par_node); + $this->par_node->set_attribute("Language", ""); + $node->append_child($this->node); + } + + /** + * Create new page content (incl. paragraph) node at node + * + * @param object $node Parent Node for Page Content + */ + public function createBeforeNode(&$node) + { + $this->node = $this->createPageContentNode(); + $this->par_node = $this->dom->create_element("Paragraph"); + $this->par_node = $this->node->append_child($this->par_node); + $this->par_node->set_attribute("Language", ""); + $node->insert_before($this->node, $node); + } + + /** + * Create paragraph node (incl. page content node) + * after given node. + * + * @param object $node Predecessing node + */ + public function createAfter($node) + { + $this->node = $this->createPageContentNode(false); + if ($succ_node = $node->next_sibling()) { + $this->node = $succ_node->insert_before($this->node, $succ_node); + } else { + $parent_node = $node->parent_node(); + $this->node = $parent_node->append_child($this->node); + } + $this->par_node = $this->dom->create_element("Paragraph"); + $this->par_node = $this->node->append_child($this->par_node); + $this->par_node->set_attribute("Language", ""); + } + + /** + * Create paragraph node (incl. page content node) + * at given hierarchical ID. + * + * @param object $a_pg_obj Page Object + * @param string $a_hier_id Hierarchical ID + */ + public function create(&$a_pg_obj, $a_hier_id, $a_pc_id = "") + { + //echo "-$a_pc_id-"; + //echo "
      -".htmlentities($a_pg_obj->getXMLFromDom())."-

      "; mk(); + $this->node = $this->dom->create_element("PageContent"); + + // this next line kicks out placeholders, if something is inserted + $a_pg_obj->insertContent($this, $a_hier_id, IL_INSERT_AFTER, $a_pc_id); + + $this->par_node = $this->dom->create_element("Paragraph"); + $this->par_node = $this->node->append_child($this->par_node); + $this->par_node->set_attribute("Language", ""); + } + + /** + * Set (xml) content of text paragraph. + * + * @param string $a_text text content + * @param boolean $a_auto_split auto split paragraph at headlines true/false + */ + public function setText($a_text, $a_auto_split = false) + { + if (!is_array($a_text)) { + $text = array(array("level" => 0, "text" => $a_text)); + } else { + $text = $a_text; + } + + if ($a_auto_split) { + $text = $this->autoSplit($a_text); + } + + // DOMXML_LOAD_PARSING, DOMXML_LOAD_VALIDATING, DOMXML_LOAD_RECOVERING + $check = ""; + foreach ($text as $t) { + $check.= "" . $t["text"] . ""; + } + /*$temp_dom = domxml_open_mem(''.$text[0]["text"].'', + DOMXML_LOAD_PARSING, $error);*/ + $temp_dom = domxml_open_mem( + '' . $check . '', + DOMXML_LOAD_PARSING, + $error + ); + //$this->text = $a_text; + + // remove all childs + if (empty($error)) { + $temp_dom = domxml_open_mem( + '' . $text[0]["text"] . '', + DOMXML_LOAD_PARSING, + $error + ); + + // delete children of paragraph node + $children = $this->par_node->child_nodes(); + for ($i=0; $ipar_node->remove_child($children[$i]); + } + + // copy new content children in paragraph node + $xpc = xpath_new_context($temp_dom); + $path = "//Paragraph"; + $res = xpath_eval($xpc, $path); + if (count($res->nodeset) == 1) { + $new_par_node = $res->nodeset[0]; + $new_childs = $new_par_node->child_nodes(); + + for ($i=0; $iclone_node(true); + $this->par_node->append_child($cloned_child); + } + $orig_characteristic = $this->getCharacteristic(); + + // if headlines are entered and current characteristic is a headline + // use no characteristic as standard + if ((count($text) > 1) && (substr($orig_characteristic, 0, 8) == "Headline")) { + $orig_characteristic = ""; + } + if ($text[0]["level"] > 0) { + $this->par_node->set_attribute("Characteristic", 'Headline' . $text[0]["level"]); + } + } + + $ok = true; + + $c_node = $this->node; + // add other chunks afterwards + for ($i=1; $igetPage()); + $next_par->createAfter($c_node); + $next_par->setLanguage($this->getLanguage()); + if ($text[$i]["level"] > 0) { + $next_par->setCharacteristic("Headline" . $text[$i]["level"]); + } else { + $next_par->setCharacteristic($orig_characteristic); + } + $ok = $next_par->setText($text[$i]["text"], false); + $c_node = $next_par->node; + } + } + + return true; + } else { + // We want the correct number of \n here to have the real lines numbers + $text = str_replace("
      ", "\n", $check); // replace
      with \n to get correct line + $text = str_replace("
      ", "\n", $text); + $text = str_replace("
      ", "\n", $text); + $text = str_replace("", "\n", $text); + $text = str_replace("", "\n", $text); + $text = str_replace("", "\n", $text); + $text = str_replace("\n", "", $text); + $text = str_replace("", "\n", $text); + include_once("./Services/Dom/classes/class.ilDomDocument.php"); + $doc = new ilDOMDocument(); + $text = '' . $text . ''; + //echo htmlentities($text); + $this->success = $doc->loadXML($text); + $error = $doc->errors; + $estr = ""; + foreach ($error as $e) { + $e = str_replace(" in Entity", "", $e); + $estr.= $e . "
      "; + } + if (DEVMODE) { + $estr.= "
      " . $text; + } + + return $estr; + } + } + + /** + * Get (xml) content of paragraph. + * + * @return string Paragraph Content. + */ + public function getText($a_short_mode = false) + { + if (is_object($this->par_node)) { + $content = ""; + $childs = $this->par_node->child_nodes(); + for ($i=0; $idom->dump_node($childs[$i]); + } + return $content; + } else { + return ""; + } + } + + /** + * Get paragraph sequenc of current paragraph + */ + public function getParagraphSequenceContent($a_pg_obj) + { + $childs = $this->par_node->parent_node()->parent_node()->child_nodes(); + $seq = array(); + $cur_seq = array(); + $found = false; + $pc_id = $this->readPCId(); + $hier_id = $this->readHierId(); + for ($i=0; $ichild_nodes(); + if ($pchilds[0]->node_name() == "Paragraph" && + $pchilds[0]->get_attribute("Characteristic") != "Code") { + $cur_seq[] = $childs[$i]; + + // check whether this is the sequence of the current paragraph + if ($childs[$i]->get_attribute("PCID") == $pc_id && + $childs[$i]->get_attribute("HierId") == $hier_id) { + $found = true; + } + + // if this is the current sequenc, get it + if ($found) { + $seq = $cur_seq; + } + } else { + // non-paragraph element found -> init the current sequence + $cur_seq = array(); + $found = false; + } + } + + $content = ""; + $ids = "###"; + $id_sep = ""; + foreach ($seq as $p_node) { + $ids.= $id_sep . $p_node->get_attribute("HierId") . ":" . $p_node->get_attribute("PCID"); + $po = $a_pg_obj->getContentObject( + $p_node->get_attribute("HierId"), + $p_node->get_attribute("PCID") + ); + $s_text = $po->getText(); + $s_text = $po->xml2output($s_text, true, false); + $char = $po->getCharacteristic(); + if ($char == "") { + $char = "Standard"; + } + $s_text = ilPCParagraphGUI::xml2outputJS($s_text, $char, $po->readPCId()); + $content.= $s_text; + $id_sep = ";"; + } + $ids.= "###"; + + return $ids . $content; + } + + /** + * Set Characteristic of paragraph + * + * @param string $a_char Characteristic + */ + public function setCharacteristic($a_char) + { + if (!empty($a_char)) { + $this->par_node->set_attribute("Characteristic", $a_char); + } else { + if ($this->par_node->has_attribute("Characteristic")) { + $this->par_node->remove_attribute("Characteristic"); + } + } + } + + /** + * Get characteristic of paragraph. + * + * @return string characteristic + */ + public function getCharacteristic() + { + if (is_object($this->par_node)) { + return $this->par_node->get_attribute("Characteristic"); + } + } + + + /** + * set attribute subcharacteristic + */ + public function setSubCharacteristic($a_char) + { + if (!empty($a_char)) { + $this->par_node->set_attribute("SubCharacteristic", $a_char); + } else { + if ($this->par_node->has_attribute("SubCharacteristic")) { + $this->par_node->remove_attribute("SubCharacteristic"); + } + } + } + + /** + * Get AutoIndent (Code Paragraphs) + * + * @param string Auto Indent attribute + */ + public function getAutoIndent() + { + return $this->par_node->get_attribute("AutoIndent"); + } + + public function setAutoIndent($a_char) + { + if (!empty($a_char)) { + $this->par_node->set_attribute("AutoIndent", $a_char); + } else { + if ($this->par_node->has_attribute("AutoIndent")) { + $this->par_node->remove_attribute("AutoIndent"); + } + } + } + + /** + * get attribute subcharacteristic + */ + public function getSubCharacteristic() + { + return $this->par_node->get_attribute("SubCharacteristic"); + } + + /** + * set attribute download title + */ + + public function setDownloadTitle($a_char) + { + if (!empty($a_char)) { + $this->par_node->set_attribute("DownloadTitle", $a_char); + } else { + if ($this->par_node->has_attribute("DownloadTitle")) { + $this->par_node->remove_attribute("DownloadTitle"); + } + } + } + + /** + * get attribute download title + */ + public function getDownloadTitle() + { + return $this->par_node->get_attribute("DownloadTitle"); + } + + /** + * set attribute showlinenumbers + */ + + public function setShowLineNumbers($a_char) + { + $a_char = empty($a_char)?"n":$a_char; + + $this->par_node->set_attribute("ShowLineNumbers", $a_char); + } + + /** + * get attribute showlinenumbers + * + */ + public function getShowLineNumbers() + { + return $this->par_node->get_attribute("ShowLineNumbers"); + } + + /** + * set language + */ + public function setLanguage($a_lang) + { + $this->par_node->set_attribute("Language", $a_lang); + } + + /** + * get language + */ + public function getLanguage() + { + return $this->par_node->get_attribute("Language"); + } + + public function input2xml($a_text, $a_wysiwyg = 0, $a_handle_lists = true) + { + return $this->_input2xml($a_text, $this->getLanguage(), $a_wysiwyg, $a_handle_lists); + } + + /** + * Replace bb code + * + * @param string $a_text text + * @param string $a_bb bb tag + * @param string $a_tag xml tag + * @return string + */ + protected static function replaceBBCode($a_text, $a_bb, $a_tag) + { + $a_text = preg_replace('/\[' . $a_bb . '\]/i', "<" . $a_tag . ">", $a_text); + $a_text = preg_replace('/\[\/' . $a_bb . '\]/i', "", $a_text); + return $a_text; + } + + + /** + * converts user input to xml + */ + public static function _input2xml($a_text, $a_lang, $a_wysiwyg = 0, $a_handle_lists = true) + { + if (!$a_wysiwyg) { + $a_text = ilUtil::stripSlashes($a_text, false); + } + + if ($a_wysiwyg) { + $a_text = str_replace("
      ", chr(10), $a_text); + } + + // note: the order of the processing steps is crucial + // and should be the same as in xml2output() in REVERSE order! + $a_text = trim($a_text); + + //echo "
      between:".htmlentities($a_text); + + // mask html + if (!$a_wysiwyg) { + $a_text = str_replace("&", "&", $a_text); + } + $a_text = str_replace("<", "<", $a_text); + $a_text = str_replace(">", ">", $a_text); + + // Reconvert PageTurn and BibItemIdentifier + $a_text = preg_replace('/<([\s\/]*?PageTurn.*?)>/i', "<$1>", $a_text); + $a_text = preg_replace('/<([\s\/]*?BibItemIdentifier.*?)>/i', "<$1>", $a_text); + + //echo "
      second:".htmlentities($a_text); + + // mask curly brackets + /* + echo htmlentities($a_text); + $a_text = str_replace("{", "{", $a_text); + $a_text = str_replace("}", "}", $a_text); + echo htmlentities($a_text);*/ + // linefeed to br + $a_text = str_replace(chr(13) . chr(10), "
      ", $a_text); + $a_text = str_replace(chr(13), "
      ", $a_text); + $a_text = str_replace(chr(10), "
      ", $a_text); + + if ($a_handle_lists) { + $a_text = ilPCParagraph::input2xmlReplaceLists($a_text); + } + + foreach (self::getBBMap() as $bb => $tag) { + // remove empty tags + $a_text = str_replace("[" . $bb . "][/" . $bb . "]", "", $a_text); + + // replace bb code by tag + $a_text = self::replaceBBCode($a_text, $bb, $tag); + } + + $a_text = self::intLinks2xml($a_text); + + // external link + $ws= "[ \t\r\f\v\n]*"; + // remove empty external links + while (preg_match("~\[(xln$ws(url$ws=$ws\"([^\"])*\")$ws(target$ws=$ws(\"(Glossary|FAQ|Media)\"))?$ws)\]\[\/xln\]~i", $a_text, $found)) { + $a_text = str_replace($found[0], "", $a_text); + } + while (preg_match('~\[(xln$ws(url$ws=$ws(([^]])*)))$ws\]\[\/xln\]~i', $a_text, $found)) { + $a_text = str_replace($found[0], "", $a_text); + } + // external links + while (preg_match("~\[(xln$ws(url$ws=$ws\"([^\"])*\")$ws(target$ws=$ws(\"(Glossary|FAQ|Media)\"))?$ws)\]~i", $a_text, $found)) { + $attribs = ilUtil::attribsToArray($found[2]); + if (isset($attribs["url"])) { + $a2 = ilUtil::attribsToArray($found[4]); + $tstr = ""; + if (in_array($a2["target"], array("FAQ", "Glossary", "Media"))) { + $tstr = ' TargetFrame="' . $a2["target"] . '"'; + } + $a_text = str_replace("[" . $found[1] . "]", "", $a_text); + } else { + $a_text = str_replace("[" . $found[1] . "]", "[error: xln" . $found[1] . "]", $a_text); + } + } + + // ie/tinymce fix for links without "", see bug #8391 + while (preg_match('~\[(xln$ws(url$ws=$ws(([^]])*)))$ws\]~i', $a_text, $found)) { + if ($found[3] != "") { + $a_text = str_replace("[" . $found[1] . "]", "", $a_text); + } else { + $a_text = str_replace("[" . $found[1] . "]", "[error: xln" . $found[1] . "]", $a_text); + } + } + $a_text = preg_replace('~\[\/xln\]~i', "", $a_text); + + // anchor + $ws= "[ \t\r\f\v\n]*"; + while (preg_match("~\[(anc$ws(name$ws=$ws\"([^\"])*\")$ws)\]~i", $a_text, $found)) { + $attribs = ilUtil::attribsToArray($found[2]); + $a_text = str_replace("[" . $found[1] . "]", "", $a_text); + } + $a_text = preg_replace("~\[\/anc\]~i", "", $a_text); + + // marked text + while (preg_match("~\[(marked$ws(class$ws=$ws\"([^\"])*\")$ws)\]~i", $a_text, $found)) { + $attribs = ilUtil::attribsToArray($found[2]); + if (isset($attribs["class"])) { + $a_text = str_replace("[" . $found[1] . "]", "", $a_text); + } else { + $a_text = str_replace("[" . $found[1] . "]", "[error:marked" . $found[1] . "]", $a_text); + } + } + $a_text = preg_replace('~\[\/marked\]~i', "", $a_text); + + + //echo htmlentities($a_text); exit; + return $a_text; + } + + /** + * internal links to xml + * + * @param + * @return + */ + public static function intLinks2xml($a_text) + { + global $DIC; + + $objDefinition = $DIC["objDefinition"]; + + $rtypes = $objDefinition->getAllRepositoryTypes(); + + // internal links + //$any = "[^\]]*"; // this doesn't work :-( + $ws= "[ \t\r\f\v\n]*"; + $ltypes = "page|chap|term|media|obj|dfile|sess|wpage|ppage|" . implode($rtypes, "|"); + // empty internal links + while (preg_match('~\[(iln' . $ws . '((inst' . $ws . '=' . $ws . '([\"0-9])*)?' . $ws . + "((" . $ltypes . ")$ws=$ws([\"0-9])*)$ws" . + "(target$ws=$ws(\"(New|FAQ|Media)\"))?$ws(anchor$ws=$ws(\"([^\"])*\"))?$ws))\]\[\/iln\]~i", $a_text, $found)) { + $a_text = str_replace($found[0], "", $a_text); + } + while (preg_match('~\[(iln' . $ws . '((inst' . $ws . '=' . $ws . '([\"0-9])*)?' . $ws . + "((" . $ltypes . ")$ws=$ws([\"0-9])*)$ws" . + "(target$ws=$ws(\"(New|FAQ|Media)\"))?$ws(anchor$ws=$ws(\"([^\"])*\"))?$ws))\]~i", $a_text, $found)) { + $attribs = ilUtil::attribsToArray($found[2]); + $inst_str = $attribs["inst"]; + // pages + if (isset($attribs["page"])) { + $tframestr = ""; + if (!empty($found[10])) { + $tframestr = " TargetFrame=\"" . $found[10] . "\" "; + } + $ancstr = ""; + if ($attribs["anchor"] != "") { + $ancstr = ' Anchor="' . $attribs["anchor"] . '" '; + } + // see 26066 for addcslashes + $a_text = preg_replace( + '/\[' . addcslashes($found[1], '/') . '\]/i', + "", + $a_text + ); + } + // chapters + elseif (isset($attribs["chap"])) { + if (!empty($found[10])) { + $tframestr = " TargetFrame=\"" . $found[10] . "\" "; + } else { + $tframestr = ""; + } + $a_text = preg_replace( + '/\[' . $found[1] . '\]/i', + "", + $a_text + ); + } + // glossary terms + elseif (isset($attribs["term"])) { + switch ($found[10]) { + case "New": + $tframestr = " TargetFrame=\"New\" "; + break; + + default: + $tframestr = " TargetFrame=\"Glossary\" "; + break; + } + $a_text = preg_replace( + '/\[' . $found[1] . '\]/i', + "", + $a_text + ); + } + // wiki pages + elseif (isset($attribs["wpage"])) { + $tframestr = ""; + $a_text = preg_replace( + '/\[' . $found[1] . '\]/i', + "", + $a_text + ); + } + // portfolio pages + elseif (isset($attribs["ppage"])) { + $tframestr = ""; + $a_text = preg_replace( + '/\[' . $found[1] . '\]/i', + "", + $a_text + ); + } + // media object + elseif (isset($attribs["media"])) { + if (!empty($found[10])) { + $tframestr = " TargetFrame=\"" . $found[10] . "\" "; + $a_text = preg_replace( + '/\[' . $found[1] . '\]/i', + "", + $a_text + ); + } else { + $a_text = preg_replace( + '/\[' . $found[1] . '\]/i', + "", + $a_text + ); + } + } + // direct download file (no repository object) + elseif (isset($attribs["dfile"])) { + $a_text = preg_replace( + '/\[' . $found[1] . '\]/i', + "", + $a_text + ); + } + // repository items (id is ref_id (will be used internally but will + // be replaced by object id for export purposes) + else { + foreach ($objDefinition->getAllRepositoryTypes() as $t) { + if (isset($attribs[$t])) { + $obj_id = $attribs[$t]; + } + } + if (isset($attribs["obj"])) { + $obj_id = $attribs["obj"]; + } + + if ($obj_id > 0) { + if ($inst_str == "") { + $a_text = preg_replace( + '/\[' . $found[1] . '\]/i', + "", + $a_text + ); + } else { + $a_text = preg_replace( + '/\[' . $found[1] . '\]/i', + "", + $a_text + ); + } + } else { + $a_text = preg_replace('/\[' . $found[1] . '\]/i', "[error: iln" . $found[1] . "]", $a_text); + } + } + } + + while (preg_match("~\[(iln$ws((inst$ws=$ws([\"0-9])*)?" . $ws . "media$ws=$ws([\"0-9])*)$ws)/\]~i", $a_text, $found)) { + $attribs = ilUtil::attribsToArray($found[2]); + $inst_str = $attribs["inst"]; + $a_text = preg_replace( + '~\[' . $found[1] . '/\]~i', + "", + $a_text + ); + } + + // user + while (preg_match("~\[(iln$ws((inst$ws=$ws([\"0-9])*)?" . $ws . "user$ws=$ws(\"([^\"])*)\")$ws)/\]~i", $a_text, $found)) { + $attribs = ilUtil::attribsToArray($found[2]); + $inst_str = $attribs["inst"]; + include_once("./Services/User/classes/class.ilObjUser.php"); + $user_id = ilObjUser::_lookupId($attribs['user']); + $a_text = preg_replace( + '~\[' . $found[1] . '/\]~i', + "", + $a_text + ); + } + + $a_text = preg_replace('~\[\/iln\]~i', "", $a_text); + return $a_text; + } + + + /** + * Converts xml from DB to output in edit textarea. + * + * @param string $a_text xml from db + * + * @return string string ready for edit textarea + */ + public static function input2xmlReplaceLists($a_text) + { + $rows = explode("
      ", $a_text . "
      "); + //var_dump($a_text); + + $old_level = 0; + + $text = ""; + + foreach ($rows as $row) { + $level = 0; + if (str_replace("#", "*", substr($row, 0, 3)) == "***") { + $level = 3; + } elseif (str_replace("#", "*", substr($row, 0, 2)) == "**") { + $level = 2; + } elseif (str_replace("#", "*", substr($row, 0, 1)) == "*") { + $level = 1; + } + + // end previous line + if ($level < $old_level) { + for ($i = $old_level; $i > $level; $i--) { + $text.= ""; + } + if ($level > 0) { + $text.= ""; + } + } elseif ($old_level > 0 && $level > 0 && ($level == $old_level)) { + $text.= ""; + } elseif (($level == $old_level) && $text != "") { + $text.= "
      "; + } + + // start next line + if ($level > $old_level) { + for ($i = $old_level + 1; $i <= $level; $i++) { + if (substr($row, $i - 1, 1) == "*") { + $clist[$i] = "SimpleBulletList"; + } else { + $clist[$i] = "SimpleNumberedList"; + } + $text.= "<" . $clist[$i] . ">"; + } + } elseif ($old_level > 0 && $level > 0) { + $text.= ""; + } + $text.= substr($row, $level); + + $old_level = $level; + } + + // remove "
      " at the end + if (substr($text, strlen($text) - 6) == "
      ") { + $text = substr($text, 0, strlen($text) - 6); + } + + return $text; + } + + /** + * Replaces tags with * + * + * @param string $a_text xml from db + * + * @return string string containing * for lists + */ + public static function xml2outputReplaceLists($a_text) + { + $segments = ilPCParagraph::segmentString($a_text, array("", "", + "
      ", "", "", "", "")); + + $current_list = array(); + $text = ""; + for ($i=0; $i<= count($segments); $i++) { + if ($segments[$i] == "") { + if (count($current_list) == 0) { + $list_start = true; + } + array_push($current_list, "*"); + $li = false; + } elseif ($segments[$i] == "") { + if (count($current_list) == 0) { + $list_start = true; + } + array_push($current_list, "#"); + $li = false; + } elseif ($segments[$i] == "") { + array_pop($current_list); + $li = false; + } elseif ($segments[$i] == "
      ") { + array_pop($current_list); + $li = false; + } elseif ($segments[$i] == "") { + $li = true; + } elseif ($segments[$i] == "") { + $li = false; + } elseif ($segments[$i] == "") { + if ($list_start) { + $text.= "
      "; + $list_start = false; + } + foreach ($current_list as $list) { + $text.= $list; + } + $text.= "
      "; + $li = false; + } else { + if ($li) { + if ($list_start) { + $text.= "
      "; + $list_start = false; + } + foreach ($current_list as $list) { + $text.= $list; + } + } + $text.= $segments[$i]; + if ($li) { + $text.= "
      "; + } + $li = false; + } + } + + // remove trailing
      , if text ends with list + if ($segments[count($segments) - 1] == "
      " || + $segments[count($segments) - 1] == "" && + substr($text, strlen($text) - 6) == "
      ") { + $text = substr($text, 0, strlen($text) - 6); + } + + return $text; + } + + /** + * Segments a string into an array at each position of a substring + */ + public static function segmentString($a_haystack, $a_needles) + { + $segments = array(); + + $nothing_found = false; + while (!$nothing_found) { + $nothing_found = true; + $found = -1; + foreach ($a_needles as $needle) { + $pos = stripos($a_haystack, $needle); + if (is_int($pos) && ($pos < $found || $found == -1)) { + $found = $pos; + $found_needle = $needle; + $nothing_found = false; + } + } + if ($found > 0) { + $segments[] = substr($a_haystack, 0, $found); + $a_haystack = substr($a_haystack, $found); + } + if ($found > -1) { + $segments[] = substr($a_haystack, 0, strlen($found_needle)); + $a_haystack = substr($a_haystack, strlen($found_needle)); + } + } + if ($a_haystack != "") { + $segments[] = $a_haystack; + } + + return $segments; + } + + /** + * Converts xml from DB to output in edit textarea. + * + * @param string $a_text xml from db + * + * @return string string ready for edit textarea + */ + public static function xml2output($a_text, $a_wysiwyg = false, $a_replace_lists = true) + { + // note: the order of the processing steps is crucial + // and should be the same as in input2xml() in REVERSE order! + + // xml to bb code + $any = "[^>]*"; + + foreach (self::getBBMap() as $bb => $tag) { + $a_text = preg_replace('~<' . $tag . '[^>]*>~i', "[" . $bb . "]", $a_text); + $a_text = preg_replace('~~i', "[/" . $bb . "]", $a_text); + $a_text = preg_replace('~<' . $tag . '/>~i', "[" . $bb . "][/" . $bb . "]", $a_text); + } + + // replace lists + if ($a_replace_lists) { + //echo "
      ".htmlentities($a_text); + $a_text = ilPCParagraph::xml2outputReplaceLists($a_text); + //echo "
      ".htmlentities($a_text); + } + + // internal links + while (preg_match('~~i', $a_text, $found)) { + $found[0]; + $attribs = ilUtil::attribsToArray($found[1]); + $target = explode("_", $attribs["Target"]); + $target_id = $target[count($target) - 1]; + $inst_str = (!is_int(strpos($attribs["Target"], "__"))) + ? $inst_str = "inst=\"" . $target[1] . "\" " + : $inst_str = ""; + switch ($attribs["Type"]) { + case "PageObject": + $tframestr = (!empty($attribs["TargetFrame"])) + ? " target=\"" . $attribs["TargetFrame"] . "\"" + : ""; + $ancstr = (!empty($attribs["Anchor"])) + ? ' anchor="' . $attribs["Anchor"] . '"' + : ""; + $a_text = preg_replace('~~i', "[iln " . $inst_str . "page=\"" . $target_id . "\"$tframestr$ancstr]", $a_text); + break; + + case "StructureObject": + $tframestr = (!empty($attribs["TargetFrame"])) + ? " target=\"" . $attribs["TargetFrame"] . "\"" + : ""; + $a_text = preg_replace('~~i', "[iln " . $inst_str . "chap=\"" . $target_id . "\"$tframestr]", $a_text); + break; + + case "GlossaryItem": + $tframestr = (empty($attribs["TargetFrame"]) || $attribs["TargetFrame"] == "Glossary") + ? "" + : " target=\"" . $attribs["TargetFrame"] . "\""; + $a_text = preg_replace('~~i', "[iln " . $inst_str . "term=\"" . $target_id . "\"" . $tframestr . "]", $a_text); + break; + + case "WikiPage": + $tframestr = ""; + $a_text = preg_replace('~~i', "[iln " . $inst_str . "wpage=\"" . $target_id . "\"" . $tframestr . "]", $a_text); + break; + + case "PortfolioPage": + $tframestr = ""; + $a_text = preg_replace('~~i', "[iln " . $inst_str . "ppage=\"" . $target_id . "\"" . $tframestr . "]", $a_text); + break; + + case "MediaObject": + if (empty($attribs["TargetFrame"])) { + $a_text = preg_replace('~~i', "[iln " . $inst_str . "media=\"" . $target_id . "\"/]", $a_text); + } else { + $a_text = preg_replace('~~i', "[iln media=\"" . $target_id . "\"" . + " target=\"" . $attribs["TargetFrame"] . "\"]", $a_text); + } + break; + + // Repository Item (using ref id) + case "RepositoryItem": + if ($inst_str == "") { + $target_type = ilObject::_lookupType($target_id, true); + } else { + $rtype = $target[count($target) - 2]; + $target_type = $rtype; + } + $a_text = preg_replace('~~i', "[iln " . $inst_str . "$target_type=\"" . $target_id . "\"" . $tframestr . "]", $a_text); + break; + + // Download File (not in repository, Object ID) + case "File": + $a_text = preg_replace('~~i', "[iln " . $inst_str . "dfile=\"" . $target_id . "\"" . $tframestr . "]", $a_text); + break; + + // User + case "User": + include_once("./Services/User/classes/class.ilObjUser.php"); + $a_text = preg_replace('~~i', "[iln " . $inst_str . "user=\"" . ilObjUser::_lookupLogin($target_id) . "\"/]", $a_text); + break; + + default: + $a_text = preg_replace('~~i', "[iln]", $a_text); + break; + } + } + $a_text = str_replace("", "[/iln]", $a_text); + + // external links + while (preg_match('~~i', $a_text, $found)) { + $found[0]; + $attribs = ilUtil::attribsToArray($found[1]); + //$found[1] = str_replace("?", "\?", $found[1]); + $tstr = ""; + if (in_array($attribs["TargetFrame"], array("FAQ", "Glossary", "Media"))) { + $tstr = ' target="' . $attribs["TargetFrame"] . '"'; + } + $a_text = str_replace("", "[xln url=\"" . $attribs["Href"] . "\"$tstr]", $a_text); + } + $a_text = str_replace("", "[/xln]", $a_text); + + // anchor + while (preg_match('~~i', $a_text, $found)) { + $found[0]; + $attribs = ilUtil::attribsToArray($found[1]); + $a_text = str_replace("", "[anc name=\"" . $attribs["Name"] . "\"][/anc]", $a_text); + } + while (preg_match('~~i', $a_text, $found)) { + $found[0]; + $attribs = ilUtil::attribsToArray($found[1]); + $a_text = str_replace("", "[anc name=\"" . $attribs["Name"] . "\"]", $a_text); + } + $a_text = str_replace("", "[/anc]", $a_text); + + // marked text + while (preg_match('~~i', $a_text, $found)) { + $found[0]; + $attribs = ilUtil::attribsToArray($found[1]); + $a_text = str_replace("", "[marked class=\"" . $attribs["Class"] . "\"]", $a_text); + } + $a_text = str_replace("", "[/marked]", $a_text); + + // br to linefeed + if (!$a_wysiwyg) { + $a_text = str_replace("
      ", "\n", $a_text); + $a_text = str_replace("
      ", "\n", $a_text); + } + + if (!$a_wysiwyg) { + // prevent curly brackets from being swallowed up by template engine + $a_text = str_replace("{", "{", $a_text); + $a_text = str_replace("}", "}", $a_text); + + // unmask html + $a_text = str_replace("<", "<", $a_text); + $a_text = str_replace(">", ">", $a_text); + + // this is needed to allow html like ... in paragraphs + $a_text = str_replace(""", "\"", $a_text); + + // make ampersands in (enabled) html attributes work + // e.g. hhh + $a_text = str_replace("&", "&", $a_text); + + // make > and $lt; work to allow (disabled) html descriptions + $a_text = str_replace("<", "&lt;", $a_text); + $a_text = str_replace(">", "&gt;", $a_text); + } + return $a_text; + //return str_replace("
      ", chr(13).chr(10), $a_text); + } + + /** + * This function splits a paragraph text that has been already + * processed with input2xml at each header position =header1=, + * ==header2== or ===header3=== and returns an array that contains + * the single chunks. + */ + public function autoSplit($a_text) + { + $a_text = str_replace("=", "=
      ", $a_text); + $a_text = str_replace("=", "=
      ", $a_text); + $a_text = str_replace("
      =", "

      =", $a_text); + $a_text = str_replace("=", "
      =", $a_text); + $a_text = "
      " . $a_text . "
      "; // add preceding and trailing br + + $chunks = array(); + $c_text = $a_text; + //echo "0"; + while ($c_text != "") { + //var_dump($c_text); flush(); + //echo "1"; + $s1 = strpos($c_text, "
      ="); + if (is_int($s1)) { + //echo "2"; + $s2 = strpos($c_text, "
      =="); + if (is_int($s2) && $s2 <= $s1) { + //echo "3"; + $s3 = strpos($c_text, "
      ==="); + if (is_int($s3) && $s3 <= $s2) { // possible level three header + //echo "4"; + $n = strpos($c_text, "
      ", $s3 + 1); + if ($n > ($s3+9) && substr($c_text, $n-3, 9) == "===
      ") { + //echo "5"; + // found level three header + if ($s3 > 0 || $head != "") { + //echo "6"; + $chunks[] = array("level" => 0, + "text" => $this->removeTrailingBr($head . substr($c_text, 0, $s3))); + $head = ""; + } + $chunks[] = array("level" => 3, + "text" => trim(substr($c_text, $s3+9, $n-$s3-12))); + $c_text = $this->handleNextBr(substr($c_text, $n+6)); + } else { + //echo "7"; + $head.= substr($c_text, 0, $n); + $c_text = substr($c_text, $n); + } + } else { // possible level two header + //echo "8"; + $n = strpos($c_text, "
      ", $s2 + 1); + if ($n > ($s2+8) && substr($c_text, $n-2, 8) == "==
      ") { + //echo "9"; + // found level two header + if ($s2 > 0 || $head != "") { + //echo "A"; + $chunks[] = array("level" => 0, + "text" => $this->removeTrailingBr($head . substr($c_text, 0, $s2))); + $head = ""; + } + $chunks[] = array("level" => 2, "text" => trim(substr($c_text, $s2+8, $n-$s2-10))); + $c_text = $this->handleNextBr(substr($c_text, $n+6)); + } else { + //echo "B"; + $head.= substr($c_text, 0, $n); + $c_text = substr($c_text, $n); + } + } + } else { // possible level one header + //echo "C"; + $n = strpos($c_text, "
      ", $s1 + 1); + if ($n > ($s1+7) && substr($c_text, $n-1, 7) == "=
      ") { + //echo "D"; + // found level one header + if ($s1 > 0 || $head != "") { + //echo "E"; + $chunks[] = array("level" => 0, + "text" => $this->removeTrailingBr($head . substr($c_text, 0, $s1))); + $head = ""; + } + $chunks[] = array("level" => 1, "text" => trim(substr($c_text, $s1+7, $n-$s1-8))); + $c_text = $this->handleNextBr(substr($c_text, $n+6)); + //echo "
      ctext:".htmlentities($c_text)."
      "; + } else { + $head.= substr($c_text, 0, $n); + $c_text = substr($c_text, $n); + //echo "
      head:".$head."c_text:".$c_text."
      "; + } + } + } else { + //echo "G"; + $chunks[] = array("level" => 0, "text" => $head . $c_text); + $head = ""; + $c_text = ""; + } + } + if (count($chunks) == 0) { + $chunks[] = array("level" => 0, "text" => ""); + } + + + // remove preceding br + if (substr($chunks[0]["text"], 0, 6) == "
      ") { + $chunks[0]["text"] = substr($chunks[0]["text"], 6); + } + + // remove trailing br + if (substr( + $chunks[count($chunks) - 1]["text"], + strlen($chunks[count($chunks) - 1]["text"]) - 6, + 6 + ) == "
      ") { + $chunks[count($chunks) - 1]["text"] = + substr($chunks[count($chunks) - 1]["text"], 0, strlen($chunks[count($chunks) - 1]["text"]) - 6); + if ($chunks[count($chunks) - 1]["text"] == "") { + unset($chunks[count($chunks) - 1]); + } + } + return $chunks; + } + + /** + * Remove preceding
      + */ + public function handleNextBr($a_str) + { + // do not remove, if next line starts with a "=", otherwise two + // headlines in a row will not be recognized + if (substr($a_str, 0, 6) == "
      " && substr($a_str, 6, 1) != "=") { + $a_str = substr($a_str, 6); + } else { + // if next line starts with a "=" we need to reinsert the
      + // otherwise it will not be recognized + if (substr($a_str, 0, 1) == "=") { + $a_str = "
      " . $a_str; + } + } + return $a_str; + } + + /** + * Remove trailing
      + */ + public function removeTrailingBr($a_str) + { + if (substr($a_str, strlen($a_str) - 6) == "
      ") { + $a_str = substr($a_str, 0, strlen($a_str) - 6); + } + return $a_str; + } + + /** + * Need to override getType from ilPageContent to distinguish between Pararagraph and Source + */ + public function getType() + { + return ($this->getCharacteristic() == "Code")?"src":parent::getType(); + } + + //// + //// Ajax related procedures + //// + + /** + * Save input coming from ajax + * + * @param + * @return + */ + public function saveJS($a_pg_obj, $a_content, $a_char, $a_pc_id, $a_insert_at = "") + { + $ilUser = $this->user; + + $this->log->debug("step 1: " . substr($a_content, 0, 1000)); + $t = self::handleAjaxContent($a_content); + $this->log->debug("step 2: " . substr($t["text"], 0, 1000)); + if ($t === false) { + return false; + } + + $pc_id = explode(":", $a_pc_id); + $insert_at = explode(":", $a_insert_at); + $t_id = explode(":", $t["id"]); + + // insert new paragraph + if ($a_insert_at != "") { + $par = new ilPCParagraph($this->getPage()); + $par->create($a_pg_obj, $insert_at[0], $insert_at[1]); + } else { + $par = $a_pg_obj->getContentObject($pc_id[0], $pc_id[1]); + } + + if ($a_insert_at != "") { + $pc_id = $a_pg_obj->generatePCId(); + $par->writePCId($pc_id); + $this->inserted_pc_id = $pc_id; + } else { + $this->inserted_pc_id = $pc_id[1]; + } + + $par->setLanguage($ilUser->getLanguage()); + $par->setCharacteristic($t["class"]); + + $t2 = $par->input2xml($t["text"], true, false); + $this->log->debug("step 3: " . substr($t2, 0, 1000)); + + $t2 = ilPCParagraph::handleAjaxContentPost($t2); + $this->log->debug("step 4: " . substr($t2, 0, 1000)); + + $updated = $par->setText($t2, true); + + if ($updated !== true) { + echo $updated; + exit; + return false; + } + $updated = $par->updatePage($a_pg_obj); + //$updated = $a_pg_obj->update(); + return $updated; + } + + /** + * Get last inserted pc ids + * + * @param + * @return + */ + public function getLastSavedPCId($a_pg_obj, $a_as_ajax_str = false) + { + if ($a_as_ajax_str) { + $a_pg_obj->stripHierIDs(); + $a_pg_obj->addHierIds(); + $ids = "###"; + //var_dump($this->inserted_pc_ids); + $combined = $a_pg_obj->getHierIdsForPCIds( + array($this->inserted_pc_id) + ); + foreach ($combined as $pc_id => $hier_id) { + //echo "1"; + $ids.= $sep . $hier_id . ":" . $pc_id; + $sep = ";"; + } + $ids.= "###"; + return $ids; + } + + return $this->inserted_pc_id; + } + + + /** + * Handle ajax content + */ + public static function handleAjaxContent($a_content) + { + $a_content = "" . $a_content . ""; + + $doc = new DOMDocument(); + + $content = ilUtil::stripSlashes($a_content, false); + + // $content = str_replace("<", "<", $content); + // $content = str_replace(">", ">", $content); + //echo "

      ".htmlentities($content); mk(); + $res = $doc->loadXML($content); + + if (!$res) { + return false; + } + + // convert tags + $xpath = new DOMXpath($doc); + + $tags = self::getXMLTagMap(); + + $elements = $xpath->query("//span"); + include_once("./Services/Utilities/classes/class.ilDOM2Util.php"); + while (!is_null($elements) && !is_null($element = $elements->item(0))) { + //$element = $elements->item(0); + $class = $element->getAttribute("class"); + if (substr($class, 0, 16) == "ilc_text_inline_") { + $class_arr = explode(" ", $class); + $tag = substr($class_arr[0], 16); + if (isset($tags[$tag])) { // known tag like strong + $cnode = ilDOM2Util::changeName($element, "il" . substr($class_arr[0], 16), false); + } else { // unknown tag -> marked text + $cnode = ilDOM2Util::changeName($element, "ilMarked", false); + $cnode->setAttribute("Class", substr($class_arr[0], 16)); + } + for ($i = 1; $i < count($class_arr); $i++) { + $tag = substr($class_arr[$i], 16); + if (isset($tags[$tag])) { // known tag like strong + $cnode = ilDOM2Util::addParent($cnode, "il" . substr($class_arr[$i], 16)); + } else { // unknown tag -> marked element + $cnode = ilDOM2Util::addParent($cnode, "ilMarked"); + $cnode->setAttribute("Class", substr($class_arr[$i], 16)); + } + } + } else { + ilDOM2Util::replaceByChilds($element); + } + + $elements = $xpath->query("//span"); + } + + // convert tags + $xpath = new DOMXpath($doc); + $elements = $xpath->query("/dummy/div"); + + $ret = array(); + if (!is_null($elements)) { + foreach ($elements as $element) { + $id = $element->getAttribute("id"); + $class = $element->getAttribute("class"); + $class = substr($class, 15); + if (trim($class) == "") { + $class = "Standard"; + } + + $text = $doc->saveXML($element); + $text = str_replace("
      ", "\n", $text); + + // remove wrapping div + $pos = strpos($text, ">"); + $text = substr($text, $pos + 1); + $pos = strrpos($text, "<"); + $text = substr($text, 0, $pos); + + // todo: remove empty spans + + // replace tags by bbcode + foreach (ilPageContentGUI::_getCommonBBButtons() as $bb => $cl) { + if (!in_array($bb, array("code", "tex", "fn", "xln"))) { + $text = str_replace( + "", + "[" . $bb . "]", + $text + ); + $text = str_replace( + "", + "[/" . $bb . "]", + $text + ); + $text = str_replace("", "", $text); + } + } + $text = str_replace( + array("", ""), + 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('
        ', "", $text); + $text = str_replace('
          ', "", $text); + + // replace marked text + // external links + $any = "[^>]*"; + while (preg_match('~~i', $text, $found)) { + $found[0]; + $attribs = ilUtil::attribsToArray($found[1]); + $text = str_replace("", "[marked class=\"" . $attribs["Class"] . "\"]", $text); + } + $text = str_replace("", "[/marked]", $text); + + + $ret[] = array("text" => $text, "id" => $id, "class" => $class); + } + } + + // we should only have one here! + return $ret[0]; + } + + /** + * Post input2xml handling of ajax content + */ + public static function handleAjaxContentPost($text) + { + $text = str_replace( + array("<ul>", "</ul>"), + array("", ""), + $text + ); + $text = str_replace( + array("<ul class='ilc_list_u_BulletedList'>", "</ul>"), + array("", ""), + $text + ); + $text = str_replace( + array("<ul class=\"ilc_list_u_BulletedList\">", "</ul>"), + array("", ""), + $text + ); + $text = str_replace( + array("<ol>", "</ol>"), + array("", ""), + $text + ); + $text = str_replace( + array("<ol class='ilc_list_o_NumberedList'>", "</ol>"), + array("", ""), + $text + ); + $text = str_replace( + array("<ol class=\"ilc_list_o_NumberedList\">", "</ol>"), + array("", ""), + $text + ); + $text = str_replace( + array("<li>", "</li>"), + array("", ""), + $text + ); + $text = str_replace( + array("<li class='ilc_list_item_StandardListItem'>", "</li>"), + array("", ""), + $text + ); + $text = str_replace( + array("<li class=\"ilc_list_item_StandardListItem\">", "</li>"), + array("", ""), + $text + ); + + $text = str_replace( + array("<li class=\"ilc_list_item_StandardListItem\"/>"), + array(""), + $text + ); + + $text = str_replace("
          ", "", $text); + $text = str_replace("
          ", "", $text); + $text = str_replace("
          ", "", $text); + $text = str_replace("
          ", "", $text); + $text = str_replace("

          ", "
          ", $text); + $text = str_replace("

          ", "
          ", $text); + $text = str_replace("
          ", "", $text); + + return $text; + } + + /** + * Update page object + * (it would be better to have this centralized and to change the constructors + * and pass the page object instead the dom object) + * @param + * @return + */ + public function updatePage($a_page) + { + $a_page->beforePageContentUpdate($this); + + $ret = $a_page->update(); + return $ret; + } + + /** + * Auto link glossaries + * + * @param + * @return + */ + public function autoLinkGlossaries($a_glos) + { + if (is_array($a_glos) && count($a_glos) > 0) { + include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + + // check which terms occur in the text (we may + // get some false positives due to the strip_tags, but + // we do not want to find strong or list or other stuff + // within the tags + $text = strip_tags($this->getText()); + $found_terms = array(); + foreach ($a_glos as $glo) { + if (ilObject::_lookupType($glo) == "glo") { + $terms = ilGlossaryTerm::getTermList($glo); + foreach ($terms as $t) { + if (is_int(stripos($text, $t["term"]))) { + $found_terms[$t["id"]] = $t; + } + } + } + } + + // did we find anything? -> modify content + if (count($found_terms) > 0) { + self::linkTermsInDom($this->dom, $found_terms, $this->par_node); + } + } + } + + /** + * Link terms in a dom page object in bb style + * + * @param + * @return + */ + protected static function linkTermsInDom($a_dom, $a_terms, $a_par_node = null) + { + // sort terms by their length (shortes first) + // to prevent that nested tags are builded + foreach ($a_terms as $k => $t) { + $a_terms[$k]["termlength"] = strlen($t["term"]); + } + $a_terms = ilUtil::sortArray($a_terms, "termlength", "asc", true); + + + if ($a_dom instanceof php4DOMDocument) { + $a_dom = $a_dom->myDOMDocument; + } + if ($a_par_node instanceof php4DOMElement) { + $a_par_node = $a_par_node->myDOMNode; + } + + $xpath = new DOMXPath($a_dom); + + if ($a_par_node == null) { + $parnodes = $xpath->query("//Paragraph[@Characteristic != 'Code']"); + } else { + $parnodes = $xpath->query(".//Paragraph[@Characteristic != 'Code']", $a_par_node->parentNode); + } + + include_once("./Services/Utilities/classes/class.ilStr.php"); + + foreach ($parnodes as $parnode) { + $textnodes = $xpath->query('.//text()', $parnode); + foreach ($textnodes as $node) { + $p = $node->getNodePath(); + + // we do not change text nodes inside of links + if (!is_int(strpos($p, "/IntLink")) && + !is_int(strpos($p, "/ExtLink"))) { + $node_val = $node->nodeValue; + + // all terms + foreach ($a_terms as $t) { + $pos = ilStr::strIPos($node_val, $t["term"]); + + // if term found + while (is_int($pos)) { + // check if we are in a tex tag, see #22261 + $tex_bpos = ilStr::strrPos(ilStr::subStr($node_val, 0, $pos), "[tex]"); + $tex_epos = ilStr::strPos($node_val, "[/tex]", $tex_bpos); + if ($tex_bpos > 0 && $tex_epos > 0 && $tex_bpos < $pos && $tex_epos > $pos) { + $pos+= ilStr::strLen($t["term"]); + } else { + + // check if the string is not included in another word + // note that [] + $valid_limiters = array("", " ", " ", ".", ",", ":", ";", "!", "?", "\"", "'", "(", ")"); + $b = ($pos > 0) + ? ilStr::subStr($node_val, $pos - 1, 1) + : ""; + $a = ilStr::subStr($node_val, $pos + ilStr::strLen($t["term"]), 1); + if ((in_array($b, $valid_limiters) || htmlentities($b, null, 'utf-8') == " ") && in_array($a, $valid_limiters)) { + $mid = '[iln term="' . $t["id"] . '"]' . + ilStr::subStr($node_val, $pos, ilStr::strLen($t["term"])) . + "[/iln]"; + + $node_val = ilStr::subStr($node_val, 0, $pos) . + $mid . + ilStr::subStr($node_val, $pos + ilStr::strLen($t["term"])); + + $pos += ilStr::strLen($mid); + } else { + $pos += ilStr::strLen($t["term"]); + } + } + $pos = ilStr::strIPos($node_val, $t["term"], $pos); + } + + // insert [iln] tags + } + + $node->nodeValue = $node_val; + } + + // var_dump($p); // var_dump($node->nodeValue); - } - - - // dump paragraph node - $text = $a_dom->saveXML($parnode); - $text = substr($text, 0, strlen($text) - strlen("")); - $text = substr($text, strpos($text, ">") + 1); - - // replace [iln] by tags with xml representation - $text = self::intLinks2xml($text); - - // "set text" - $temp_dom = domxml_open_mem(''.$text.'', - DOMXML_LOAD_PARSING, $error); - $temp_dom = $temp_dom->myDOMDocument; - - if(empty($error)) - { - // delete children of paragraph node - $children = $parnode->childNodes; - while ($parnode->hasChildNodes()) - { - $parnode->removeChild($parnode->firstChild); - } - - // copy new content children in paragraph node - $xpath_temp = new DOMXPath($temp_dom); - $temp_pars = $xpath_temp->query("//Paragraph"); - - foreach ($temp_pars as $new_par_node) - { - $new_childs = $new_par_node->childNodes; - - foreach($new_childs as $new_child) - { - //$cloned_child = $new_child->cloneNode(true); - $cloned_child = $a_dom->importNode($new_child, true); - $parnode->appendChild($cloned_child); - } - } - } - } -// exit; - } - - - /** - * Auto link glossary of whole page - * - * @param - * @return - */ - static function autoLinkGlossariesPage($a_page, $a_terms) - { - $a_page->buildDom(); - $a_dom = $a_page->getDom(); - - self::linkTermsInDom($a_dom, $a_terms); - - $a_page->update(); - } - - /** - * After page has been updated (or created) - * - * @param object $a_page page object - * @param DOMDocument $a_domdoc dom document - * @param string $a_xml xml - * @param bool $a_creation true on creation, otherwise false - */ - static function afterPageUpdate($a_page, DOMDocument $a_domdoc, $a_xml, $a_creation) - { - // pc paragraph - self::saveMetaKeywords($a_page, $a_domdoc); - self::saveAnchors($a_page, $a_domdoc); - } - - /** - * Before page is being deleted - * - * @param object $a_page page object - */ - static function beforePageDelete($a_page) - { - // delete anchors - self::_deleteAnchors($a_page->getParentType(), $a_page->getId(), $a_page->getLanguage()); - } - - /** - * After page history entry has been created - * - * @param object $a_page page object - * @param DOMDocument $a_old_domdoc old dom document - * @param string $a_old_xml old xml - * @param integer $a_old_nr history number - */ - static function afterPageHistoryEntry($a_page, DOMDocument $a_old_domdoc, $a_old_xml, $a_old_nr) - { - } - - /** - * Save anchors - * - * @param string xml page code - */ - static function saveAnchors($a_page, $a_domdoc) - { - self::_deleteAnchors($a_page->getParentType(), $a_page->getId(), $a_page->getLanguage()); - - // get all anchors - $xpath = new DOMXPath($a_domdoc); - $nodes = $xpath->query('//Anchor'); - $saved = array(); - foreach ($nodes as $node) - { - $name = $node->getAttribute("Name"); - if (trim($name) != "" && !in_array($name, $saved)) - { - self::_saveAnchor($a_page->getParentType(), $a_page->getId(), $a_page->getLanguage(), $name); - $saved[] = $name; - } - } - - } - - /** - * Delete anchors of a page - */ - static function _deleteAnchors($a_parent_type, $a_page_id, $a_page_lang) - { - global $DIC; - - $ilDB = $DIC->database(); - - $ilDB->manipulate("DELETE FROM page_anchor WHERE ". - " page_parent_type = ".$ilDB->quote($a_parent_type, "text"). - " AND page_id = ".$ilDB->quote($a_page_id, "integer"). - " AND page_lang = ".$ilDB->quote($a_page_lang, "text") - ); - } - - /** - * Save an anchor - */ - static function _saveAnchor($a_parent_type, $a_page_id, $a_page_lang, $a_anchor_name) - { - global $DIC; - - $ilDB = $DIC->database(); - - $ilDB->manipulate("INSERT INTO page_anchor ". - "(page_parent_type, page_id, page_lang, anchor_name) VALUES (". - $ilDB->quote($a_parent_type, "text").",". - $ilDB->quote($a_page_id, "integer").",". - $ilDB->quote($a_page_lang, "text").",". - $ilDB->quote($a_anchor_name, "text"). - ")"); - } - - /** - * Read anchors of a page - */ - static function _readAnchors($a_parent_type, $a_page_id, $a_page_lang = "-") - { - global $DIC; - - $ilDB = $DIC->database(); - - $and_lang = ($a_page_lang != "") - ? " AND page_lang = ".$ilDB->quote($a_page_lang, "text") - : ""; - - $set = $ilDB->query("SELECT * FROM page_anchor ". - " WHERE page_parent_type = ".$ilDB->quote($a_parent_type, "text"). - " AND page_id = ".$ilDB->quote($a_page_id, "integer"). - $and_lang - ); - $anchors = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $anchors[] = $rec["anchor_name"]; - } - return $anchors; - } - - /** - * save all keywords - * - * @param object $a_page page object - * @param object $a_domdoc dom document - */ - static function saveMetaKeywords($a_page, $a_domdoc) - { - // not nice, should be set by context per method - if ($a_page->getParentType() == "gdf" || - $a_page->getParentType() == "lm") - { - // get existing keywords - $keywords = array(); - - // find all Keyw tags - $xpath = new DOMXPath($a_domdoc); - $nodes = $xpath->query('//Keyw'); - foreach($nodes as $node) - { - $k = trim(strip_tags($node->nodeValue)); - if (!in_array($k, $keywords)) - { - $keywords[] = $k; - } - } - - $meta_type = ($a_page->getParentType() == "gdf") - ? "gdf" - : "pg"; - $meta_rep_id = $a_page->getParentId(); - $meta_id = $a_page->getId(); - - include_once("./Services/MetaData/classes/class.ilMD.php"); - $md_obj = new ilMD($meta_rep_id, $meta_id, $meta_type); - $mkeywords = array(); - $lang = ""; - if(is_object($md_section = $md_obj->getGeneral())) - { - foreach($ids = $md_section->getKeywordIds() as $id) - { - $md_key = $md_section->getKeyword($id); - $mkeywords[] = strtolower($md_key->getKeyword()); - if ($lang == "") - { - $lang = $md_key->getKeywordLanguageCode(); - } - } - if ($lang == "") - { - foreach($ids = $md_section->getLanguageIds() as $id) - { - $md_lang = $md_section->getLanguage($id); - if ($lang == "") - { - $lang = $md_lang->getLanguageCode(); - } - } - } - foreach ($keywords as $k) - { - if (!in_array(strtolower($k), $mkeywords)) - { - if (trim($k) != "" && $lang != "") - { - $md_key = $md_section->addKeyword(); - $md_key->setKeyword(ilUtil::stripSlashes($k)); - $md_key->setKeywordLanguage(new ilMDLanguageItem($lang)); - $md_key->save(); - } - $mkeywords[] = strtolower($k); - } - } - } - } - } - - /** - * Get Javascript files - */ - function getJavascriptFiles($a_mode) - { - $adve_settings = new ilSetting("adve"); - - if ($a_mode != "edit" && $adve_settings->get("auto_url_linking")) - { - include_once("./Services/Link/classes/class.ilLinkifyUtil.php"); - return ilLinkifyUtil::getLocalJsPaths(); - } - - return array(); - } - - /** - * Get onload code - * - * @param - * @return - */ - function getOnloadCode($a_mode) - { - $adve_settings = new ilSetting("adve"); - - if ($a_mode != "edit" && $adve_settings->get("auto_url_linking")) - { - return array("il.ExtLink.autolink('.ilc_Paragraph','ilc_link_ExtLink');"); - } - - return array(); - } - - + } + + + // dump paragraph node + $text = $a_dom->saveXML($parnode); + $text = substr($text, 0, strlen($text) - strlen("")); + $text = substr($text, strpos($text, ">") + 1); + + // replace [iln] by tags with xml representation + $text = self::intLinks2xml($text); + + // "set text" + $temp_dom = domxml_open_mem( + '' . $text . '', + DOMXML_LOAD_PARSING, + $error + ); + $temp_dom = $temp_dom->myDOMDocument; + + if (empty($error)) { + // delete children of paragraph node + $children = $parnode->childNodes; + while ($parnode->hasChildNodes()) { + $parnode->removeChild($parnode->firstChild); + } + + // copy new content children in paragraph node + $xpath_temp = new DOMXPath($temp_dom); + $temp_pars = $xpath_temp->query("//Paragraph"); + + foreach ($temp_pars as $new_par_node) { + $new_childs = $new_par_node->childNodes; + + foreach ($new_childs as $new_child) { + //$cloned_child = $new_child->cloneNode(true); + $cloned_child = $a_dom->importNode($new_child, true); + $parnode->appendChild($cloned_child); + } + } + } + } + // exit; + } + + + /** + * Auto link glossary of whole page + * + * @param + * @return + */ + public static function autoLinkGlossariesPage($a_page, $a_terms) + { + $a_page->buildDom(); + $a_dom = $a_page->getDom(); + + self::linkTermsInDom($a_dom, $a_terms); + + $a_page->update(); + } + + /** + * After page has been updated (or created) + * + * @param object $a_page page object + * @param DOMDocument $a_domdoc dom document + * @param string $a_xml xml + * @param bool $a_creation true on creation, otherwise false + */ + public static function afterPageUpdate($a_page, DOMDocument $a_domdoc, $a_xml, $a_creation) + { + // pc paragraph + self::saveMetaKeywords($a_page, $a_domdoc); + self::saveAnchors($a_page, $a_domdoc); + } + + /** + * Before page is being deleted + * + * @param object $a_page page object + */ + public static function beforePageDelete($a_page) + { + // delete anchors + self::_deleteAnchors($a_page->getParentType(), $a_page->getId(), $a_page->getLanguage()); + } + + /** + * After page history entry has been created + * + * @param object $a_page page object + * @param DOMDocument $a_old_domdoc old dom document + * @param string $a_old_xml old xml + * @param integer $a_old_nr history number + */ + public static function afterPageHistoryEntry($a_page, DOMDocument $a_old_domdoc, $a_old_xml, $a_old_nr) + { + } + + /** + * Save anchors + * + * @param string xml page code + */ + public static function saveAnchors($a_page, $a_domdoc) + { + self::_deleteAnchors($a_page->getParentType(), $a_page->getId(), $a_page->getLanguage()); + + // get all anchors + $xpath = new DOMXPath($a_domdoc); + $nodes = $xpath->query('//Anchor'); + $saved = array(); + foreach ($nodes as $node) { + $name = $node->getAttribute("Name"); + if (trim($name) != "" && !in_array($name, $saved)) { + self::_saveAnchor($a_page->getParentType(), $a_page->getId(), $a_page->getLanguage(), $name); + $saved[] = $name; + } + } + } + + /** + * Delete anchors of a page + */ + public static function _deleteAnchors($a_parent_type, $a_page_id, $a_page_lang) + { + global $DIC; + + $ilDB = $DIC->database(); + + $ilDB->manipulate( + "DELETE FROM page_anchor WHERE " . + " page_parent_type = " . $ilDB->quote($a_parent_type, "text") . + " AND page_id = " . $ilDB->quote($a_page_id, "integer") . + " AND page_lang = " . $ilDB->quote($a_page_lang, "text") + ); + } + + /** + * Save an anchor + */ + public static function _saveAnchor($a_parent_type, $a_page_id, $a_page_lang, $a_anchor_name) + { + global $DIC; + + $ilDB = $DIC->database(); + + $ilDB->manipulate("INSERT INTO page_anchor " . + "(page_parent_type, page_id, page_lang, anchor_name) VALUES (" . + $ilDB->quote($a_parent_type, "text") . "," . + $ilDB->quote($a_page_id, "integer") . "," . + $ilDB->quote($a_page_lang, "text") . "," . + $ilDB->quote($a_anchor_name, "text") . + ")"); + } + + /** + * Read anchors of a page + */ + public static function _readAnchors($a_parent_type, $a_page_id, $a_page_lang = "-") + { + global $DIC; + + $ilDB = $DIC->database(); + + $and_lang = ($a_page_lang != "") + ? " AND page_lang = " . $ilDB->quote($a_page_lang, "text") + : ""; + + $set = $ilDB->query( + "SELECT * FROM page_anchor " . + " WHERE page_parent_type = " . $ilDB->quote($a_parent_type, "text") . + " AND page_id = " . $ilDB->quote($a_page_id, "integer") . + $and_lang + ); + $anchors = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $anchors[] = $rec["anchor_name"]; + } + return $anchors; + } + + /** + * save all keywords + * + * @param object $a_page page object + * @param object $a_domdoc dom document + */ + public static function saveMetaKeywords($a_page, $a_domdoc) + { + // not nice, should be set by context per method + if ($a_page->getParentType() == "gdf" || + $a_page->getParentType() == "lm") { + // get existing keywords + $keywords = array(); + + // find all Keyw tags + $xpath = new DOMXPath($a_domdoc); + $nodes = $xpath->query('//Keyw'); + foreach ($nodes as $node) { + $k = trim(strip_tags($node->nodeValue)); + if (!in_array($k, $keywords)) { + $keywords[] = $k; + } + } + + $meta_type = ($a_page->getParentType() == "gdf") + ? "gdf" + : "pg"; + $meta_rep_id = $a_page->getParentId(); + $meta_id = $a_page->getId(); + + include_once("./Services/MetaData/classes/class.ilMD.php"); + $md_obj = new ilMD($meta_rep_id, $meta_id, $meta_type); + $mkeywords = array(); + $lang = ""; + if (is_object($md_section = $md_obj->getGeneral())) { + foreach ($ids = $md_section->getKeywordIds() as $id) { + $md_key = $md_section->getKeyword($id); + $mkeywords[] = strtolower($md_key->getKeyword()); + if ($lang == "") { + $lang = $md_key->getKeywordLanguageCode(); + } + } + if ($lang == "") { + foreach ($ids = $md_section->getLanguageIds() as $id) { + $md_lang = $md_section->getLanguage($id); + if ($lang == "") { + $lang = $md_lang->getLanguageCode(); + } + } + } + foreach ($keywords as $k) { + if (!in_array(strtolower($k), $mkeywords)) { + if (trim($k) != "" && $lang != "") { + $md_key = $md_section->addKeyword(); + $md_key->setKeyword(ilUtil::stripSlashes($k)); + $md_key->setKeywordLanguage(new ilMDLanguageItem($lang)); + $md_key->save(); + } + $mkeywords[] = strtolower($k); + } + } + } + } + } + + /** + * Get Javascript files + */ + public function getJavascriptFiles($a_mode) + { + $adve_settings = new ilSetting("adve"); + + if ($a_mode != "edit" && $adve_settings->get("auto_url_linking")) { + include_once("./Services/Link/classes/class.ilLinkifyUtil.php"); + return ilLinkifyUtil::getLocalJsPaths(); + } + + return array(); + } + + /** + * Get onload code + * + * @param + * @return + */ + public function getOnloadCode($a_mode) + { + $adve_settings = new ilSetting("adve"); + + if ($a_mode != "edit" && $adve_settings->get("auto_url_linking")) { + return array("il.ExtLink.autolink('.ilc_Paragraph','ilc_link_ExtLink');"); + } + + return array(); + } } -?> diff --git a/Services/COPage/classes/class.ilPCParagraphGUI.php b/Services/COPage/classes/class.ilPCParagraphGUI.php index ca9f4576f3e9387b3fe789b5510a2981270f768d..f7f126295dc25cd767fc6eb34d238c701ee4b57f 100755 --- a/Services/COPage/classes/class.ilPCParagraphGUI.php +++ b/Services/COPage/classes/class.ilPCParagraphGUI.php @@ -16,887 +16,890 @@ require_once("./Services/COPage/classes/class.ilPageContentGUI.php"); */ class ilPCParagraphGUI extends ilPageContentGUI { - /** - * @var ilObjUser - */ - protected $user; - - /** - * Constructor - * @access public - */ - function __construct($a_pg_obj, &$a_content_obj, $a_hier_id, $a_pc_id = "") - { - global $DIC; - - $this->user = $DIC->user(); - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); - - // characteristics (should be flexible in the future) - $this->setCharacteristics(ilPCParagraphGUI::_getStandardCharacteristics()); - } - - /** - * Get standard characteristics - */ - static function _getStandardCharacteristics() - { - global $DIC; - - $lng = $DIC->language(); - - return array("Standard" => $lng->txt("cont_standard"), - "Headline1" => $lng->txt("cont_Headline1"), - "Headline2" => $lng->txt("cont_Headline2"), - "Headline3" => $lng->txt("cont_Headline3"), - "Citation" => $lng->txt("cont_Citation"), - "Mnemonic" => $lng->txt("cont_Mnemonic"), - "Example" => $lng->txt("cont_Example"), - "Additional" => $lng->txt("cont_Additional"), - "Attention" => $lng->txt("cont_Attention"), - "Confirmation" => $lng->txt("cont_Confirmation"), - "Information" => $lng->txt("cont_Information"), - "Link" => $lng->txt("cont_Link"), - "Literature" => $lng->txt("cont_Literature"), - "Separator" => $lng->txt("cont_Separator"), - "StandardCenter" => $lng->txt("cont_StandardCenter"), - "Remark" => $lng->txt("cont_Remark"), - "List" => $lng->txt("cont_List"), - "TableContent" => $lng->txt("cont_TableContent") - ); - } - - /** - * Get standard characteristics - */ - static function _getStandardTextCharacteristics() - { - global $DIC; - - $lng = $DIC->language(); - return ["Mnemonic", "Attention"]; - return array("Mnemonic" => $lng->txt("cont_Mnemonic"), - "Attention" => $lng->txt("cont_Attention") - ); - } - - /** - * Get characteristics - */ - static function _getCharacteristics($a_style_id) - { - $st_chars = ilPCParagraphGUI::_getStandardCharacteristics(); - $chars = ilPCParagraphGUI::_getStandardCharacteristics(); - - if ($a_style_id > 0 && - ilObject::_lookupType($a_style_id) == "sty") - { - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $style = new ilObjStyleSheet($a_style_id); - $types = array("text_block", "heading1", "heading2", "heading3"); - $chars = array(); - foreach ($types as $t) - { - $chars = array_merge($chars, $style->getCharacteristics($t)); - } - $new_chars = array(); - foreach ($chars as $char) - { - if ($st_chars[$char] != "") // keep lang vars for standard chars - { - $new_chars[$char] = $st_chars[$char]; - } - else - { - $new_chars[$char] = $char; - } - asort($new_chars); - } - $chars = $new_chars; - } - - return $chars; - } - - /** - * Get text characteristics - * - * @param int $a_style_id - * @param bool $a_include_core include core styles - * @return string[] - */ - static function _getTextCharacteristics($a_style_id, $a_include_core = false) - { - $chars = array(); - - if ($a_style_id > 0 && - ilObject::_lookupType($a_style_id) == "sty") - { - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $style = new ilObjStyleSheet($a_style_id); - $types = array("text_inline"); - foreach ($types as $t) - { - $chars = array_merge($chars, $style->getCharacteristics($t, false, $a_include_core)); - } - } - else - { - return self::_getStandardTextCharacteristics(); - } - - return $chars; - } - - - /** - * execute command - */ - function executeCommand() - { - // get next class that processes or forwards current command - $next_class = $this->ctrl->getNextClass($this); - - $this->getCharacteristicsOfCurrentStyle( - array("text_block", "heading1", "heading2", "heading3")); // scorm-2004 - - // get current command - $cmd = $this->ctrl->getCmd(); - - $this->log->debug("ilPCParagraphGUI: executeCommand ".$cmd); - - switch($next_class) - { - default: - $ret = $this->$cmd(); - break; - } - - return $ret; - } - - /** - * edit paragraph form - */ - function edit($a_insert = false) - { - $ilUser = $this->user; - - // add paragraph edit template - $tpl = new ilTemplate("tpl.paragraph_edit.html", true, true, "Services/COPage"); - - // help text - $this->insertHelp($tpl); - - // operations - if ($a_insert) - { - $tpl->setCurrentBlock("commands"); - $tpl->setVariable("BTN_NAME", "create_par"); - $tpl->setVariable("BTN_TEXT", $this->lng->txt("save")); - $tpl->setVariable("BTN_CANCEL", "cancelCreate"); - $tpl->setVariable("TXT_CANCEL", $this->lng->txt("cancel")); - $tpl->parseCurrentBlock(); - /*$tpl->setCurrentBlock("commands2"); - $tpl->setVariable("BTN_NAME", "create_par"); - $tpl->setVariable("BTN_TEXT", $this->lng->txt("save")); - $tpl->setVariable("BTN_CANCEL", "cancelCreate"); - $tpl->setVariable("TXT_CANCEL", $this->lng->txt("cancel")); - $tpl->parseCurrentBlock();*/ - $tpl->setVariable("TXT_ACTION", $this->lng->txt("cont_insert_par")); - } - else - { - $tpl->setCurrentBlock("commands"); - $tpl->setVariable("BTN_NAME", "update"); - $tpl->setVariable("BTN_TEXT", $this->lng->txt("save")); - $tpl->setVariable("BTN_CANCEL", "cancelUpdate"); - $tpl->setVariable("TXT_CANCEL", $this->lng->txt("cancel")); - $tpl->parseCurrentBlock(); - /*$tpl->setCurrentBlock("commands2"); - $tpl->setVariable("BTN_NAME", "update"); - $tpl->setVariable("BTN_TEXT", $this->lng->txt("save")); - $tpl->setVariable("BTN_CANCEL", "cancelUpdate"); - $tpl->setVariable("TXT_CANCEL", $this->lng->txt("cancel")); - $tpl->parseCurrentBlock();*/ - $tpl->setVariable("TXT_ACTION", $this->lng->txt("cont_edit_par")); - } - - // language and characteristic selection - $s_char = $this->determineCharacteristic($a_insert); - if (!$a_insert) - { - if (key($_POST["cmd"]) == "update") - { - $s_lang = $_POST["par_language"]; - } - else - { - $s_lang = $this->content_obj->getLanguage(); - } - } - else - { - if (key($_POST["cmd"]) == "create_par") - { - $s_lang = $_POST["par_language"]; - } - else - { - if ($_SESSION["il_text_lang_".$_GET["ref_id"]] != "") - { - $s_lang = $_SESSION["il_text_lang_".$_GET["ref_id"]]; - } - else - { - $s_lang = $ilUser->getLanguage(); - } - } - } - - $this->insertStyleSelectionList($tpl, $s_char); -// $this->insertCharacteristicTable($tpl, $s_char); - - - $tpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this)); - - $tpl->setVariable("PAR_TA_NAME", "par_content"); - $tpl->setVariable("BB_MENU", $this->getBBMenu()); - $this->tpl->addJavascript("./Services/COPage/phpBB/3_0_5/editor.js"); - $this->tpl->addJavascript("./Services/COPage/js/paragraph_editing.js"); - $this->setStyle(); - - $this->displayValidationError(); - - $tpl->setVariable("TXT_LANGUAGE", $this->lng->txt("language")); - $tpl->setVariable("TXT_ANCHOR", $this->lng->txt("cont_anchor")); - - require_once("Services/MetaData/classes/class.ilMDLanguageItem.php"); - $lang = ilMDLanguageItem::_getLanguages(); - $select_lang = ilUtil::formSelect ($s_lang,"par_language",$lang,false,true); - $tpl->setVariable("SELECT_LANGUAGE", $select_lang); - - $tpl->setVariable("TXT_CHARACTERISTIC", $this->lng->txt("cont_characteristic")); -// $select_char = ilUtil::formSelect ($s_char, -// "par_characteristic",$this->chars,false,true); -// $tpl->setVariable("SELECT_CHARACTERISTIC", $select_char); - - if (key($_POST["cmd"]) == "update" || key($_POST["cmd"]) == "create_par") - { - $s_text = ilUtil::stripSlashes($_POST["par_content"], false); - // prevent curly brackets from being swallowed up by template engine - $s_text = str_replace("{", "{", $s_text); - $s_text = str_replace("}", "}", $s_text); - } - else if (!$a_insert) - { - $s_text = $this->content_obj->xml2output($this->content_obj->getText()); - } - - $tpl->setVariable("PAR_TA_CONTENT", $s_text); - - $tpl->parseCurrentBlock(); - - $this->tpl->setContent($tpl->get()); - return $tpl->get(); - } - - /** - * Determine current characteristic - * - * @param - * @return - */ - function determineCharacteristic($a_insert = false) - { - // language and characteristic selection - if (!$a_insert) - { - if (key($_POST["cmd"]) == "update") - { - $s_char = $_POST["par_characteristic"]; - } - else - { - $s_char = $this->content_obj->getCharacteristic(); - if ($s_char == "") - { - $s_char = "Standard"; - } - } - } - else - { - if (key($_POST["cmd"]) == "create_par") - { - $s_char = $_POST["par_characteristic"]; - } - else - { - $s_char = "Standard"; - - // set characteristic of new paragraphs in list items to "List" - $cont_obj = $this->pg_obj->getContentObject($this->getHierId()); - if (is_object($cont_obj)) - { - if ($cont_obj->getType() == "li" || - ($cont_obj->getType() == "par" && $cont_obj->getCharacteristic() == "List")) - { - $s_char = "List"; - } - - if ($cont_obj->getType() == "td" || - ($cont_obj->getType() == "par" && $cont_obj->getCharacteristic() == "TableContent")) - { - $s_char = "TableContent"; - } - - } - } - } - return $s_char; - } - - /** - * Edit paragraph (Ajax mode, sends the content of the paragraph) - */ - function editJS() - { - $s_text = $this->content_obj->getText(); - $this->log->debug("step 1: ".substr($s_text, 0, 1000)); - -//echo "\n

          ".htmlentities($s_text); - $s_text = $this->content_obj->xml2output($s_text, true, false); - $this->log->debug("step 2: ".substr($s_text, 0, 1000)); - -//echo "\n

          ".htmlentities($s_text); - $char = $this->determineCharacteristic(false); - $s_text = ilPCParagraphGUI::xml2outputJS($s_text, $char, $this->content_obj->readPCId()); - $this->log->debug("step 3: ".substr($s_text, 0, 1000)); - -//echo "\n

          ".htmlentities($s_text); - $ids = "###".$this->content_obj->readHierId().":".$this->content_obj->readPCId()."###". - $char."###"; - echo $ids.$s_text; - $this->log->debug("step 4: ".substr($ids.$s_text, 0, 1000)); - exit; - } - - /** - * Edit multiple paragraphs (Ajax mode, sends the content of the paragraphs) - */ - function editMultipleJS() - { - echo $this->content_obj->getParagraphSequenceContent($this->pg_obj); - exit; - } - - /** - * Prepare content for js output - */ - static function xml2outputJS($s_text, $char, $a_pc_id) - { -// $s_text = "
          ".$s_text."
          "; - $s_text = $s_text; - // lists - $s_text = str_replace(array("", ""), - array("
            ", "
          "), - $s_text); - $s_text = str_replace(array("", ""), - array("
            ", "
          "), $s_text); - $s_text = str_replace(array("", ""), - array("
        • ", "
        • "), $s_text); - $s_text = str_replace(array(""), - array("
        • "), $s_text); - //$s_text = str_replace("
          ", "", $s_text); - //$s_text = str_replace("
          ", "", $s_text); - //$s_text = str_replace("

          ", "", $s_text); - - - // spans - include_once("./Services/COPage/classes/class.ilPageContentGUI.php"); - foreach (ilPageContentGUI::_getCommonBBButtons() as $bb => $cl) - { - if (!in_array($bb, array("code", "tex", "fn", "xln", "sub", "sup"))) - { - $s_text = str_replace("[".$bb."]", - '', $s_text); - $s_text = str_replace("[/".$bb."]", - '', $s_text); - } - } - - // marked text spans - $ws= "[ \t\r\f\v\n]*"; - while (preg_match("~\[(marked$ws(class$ws=$ws\"([^\"])*\")$ws)\]~i", $s_text, $found)) - { - $attribs = ilUtil::attribsToArray($found[2]); - if (isset($attribs["class"])) - { - $s_text = str_replace("[".$found[1]."]", "", $s_text); - } - else - { - $s_text = str_replace("[".$found[1]."]", "[error:marked".$found[1]."]",$s_text); - } - } - $s_text = preg_replace('~\[\/marked\]~i',"",$s_text); - - - // code - $s_text = str_replace(array("[code]", "[/code]"), - array("", ""), $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]."
          "; - } - echo $err_str; - $this->log->debug("ilPCParagraphGUI, outputError() and exit: ".substr($err_str, 0, 100)); - exit; - } - - - /** - * Cancel - */ - function cancel() - { - $this->log->debug("ilPCParagraphGUI, cancel(): return to parent: jump".$this->hier_id); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * Insert characteristic table - */ - function insertCharacteristicTable($a_tpl, $a_seleted_value) - { - $i = 0; - - $chars = $this->getCharacteristics(); - - if ($chars[$a_seleted_value] == "" && ($a_seleted_value != "")) - { - $chars = array_merge(array($a_seleted_value => $a_seleted_value), - $chars); - } - - foreach ($chars as $char => $char_lang) - { - $a_tpl->setCurrentBlock("characteristic_cell"); - $a_tpl->setVariable("CHAR_HTML", - '
          '.$char_lang."
          "); - $a_tpl->setVariable("CHAR_VALUE", $char); - if ($char == $a_seleted_value) - { - $a_tpl->setVariable("SELECTED", - ' checked="checked" '); - } - $a_tpl->parseCurrentBlock(); - if ((($i+1) % 3) == 0) // - { - $a_tpl->touchBlock("characteristic_row"); - } - $i++; - } - $a_tpl->touchBlock("characteristic_table"); - } - - /** - * Insert style selection list - * - * @param object $a_tpl - * @param string $a_selected - */ - function insertStyleSelectionList($a_tpl, $a_selected) - { - $a_tpl->setVariable("ADV_SEL_STYLE", self::getStyleSelector($a_selected, - $this->getCharacteristics())); - } - - /** - * Get style selector - */ - static function getStyleSelector($a_selected, $a_chars, $a_use_callback = false) - { - include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"); - $selection = new ilAdvancedSelectionListGUI(); - $selection->setPullRight(false); - $selection->setFormSelectMode("par_characteristic", "", false, - "", "", "", - "", "", "", ""); - $selection->setId("style_selection"); - $selection->setSelectionHeaderClass("ilEditSubmit ilTinyMenuDropDown"); - $selection->setHeaderIcon(ilAdvancedSelectionListGUI::DOWN_ARROW_DARK); - $selection->setSelectedValue($a_selected); - $selection->setUseImages(false); - $selection->setOnClickMode(ilAdvancedSelectionListGUI::ON_ITEM_CLICK_FORM_SELECT); - if ($a_use_callback) - { - $selection->setSelectCallback("ilCOPage.setParagraphClass"); - } - - $chars = $a_chars; - $title_char = ($chars[$a_selected] != "") - ? $chars[$a_selected] - : $a_selected; - $selection->setListTitle($title_char); - - if ($chars[$a_seleted] == "" && ($a_seleted != "")) - { - $chars = array_merge(array($a_seleted => $a_seleted), - $chars); - } - - foreach ($chars as $char => $char_lang) - { - $t = "text_block"; - $tag = "div"; - switch($char) - { - case "Headline1": $t = "heading1"; $tag = "h1"; break; - case "Headline2": $t = "heading2"; $tag = "h2"; break; - case "Headline3": $t = "heading3"; $tag = "h3"; break; - } - $html = '
          <'.$tag.' class="ilc_'.$t.'_'.$char.'" style="'.self::$style_selector_reset.'">'.$char_lang."
          "; - $selection->addItem($char_lang, $char, "", - "", $char, "", $html); - } - return $selection->getHTML(); - } - - /** - * Get character style selector - */ - static function getCharStyleSelector($a_par_type, $a_use_callback = true, $a_style_id = 0) - { - global $DIC; - - $lng = $DIC->language(); - - include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"); - $selection = new ilAdvancedSelectionListGUI(); - $selection->setPullRight(false); - $selection->setFormSelectMode("char_characteristic", "", false, - "", "", "", - "", "", "", ""); - $selection->setId("char_style_selection"); - $selection->setSelectionHeaderClass("ilEditSubmit"); - $selection->setHeaderIcon(ilAdvancedSelectionListGUI::DOWN_ARROW_DARK); - //$selection->setSelectedValue($a_selected); - $selection->setUseImages(false); - $selection->setOnClickMode(ilAdvancedSelectionListGUI::ON_ITEM_CLICK_NOP); - if (is_string($a_use_callback)) { - $selection->setSelectCallback($a_use_callback); - } else if ($a_use_callback === true) { - $selection->setSelectCallback("ilCOPage.setCharacterClass"); - } - - //$chars = $a_chars; - //$title_char = ($chars[$a_selected] != "") - // ? $chars[$a_selected] - // : $a_selected; - $selection->setListTitle(" A"); - - /*if ($chars[$a_seleted] == "" && ($a_seleted != "")) - { - $chars = array_merge(array($a_seleted => $a_seleted), - $chars); - }*/ - - $chars = array( - "Comment" => array("code" => "com", "txt" => $lng->txt("cont_char_style_com")), - "Quotation" => array("code" => "quot", "txt" =>$lng->txt("cont_char_style_quot")), - "Accent" => array("code" => "acc", "txt" => $lng->txt("cont_char_style_acc")), - "Code" => array("code" => "code", "txt" => $lng->txt("cont_char_style_code")) - ); - - foreach (ilPCParagraphGUI::_getTextCharacteristics($a_style_id) as $c) - { - if (!isset($chars[$c])) - { - $chars[$c] = array("code" => "", "txt" => $c); - } - } - - foreach ($chars as $key => $char) - { - if (ilPageEditorSettings::lookupSettingByParentType( - $a_par_type, "active_".$char["code"], true)) - { - $t = "text_inline"; - $tag = "span"; - switch($key) - { - case "Code": $tag = "code"; break; - } - $html = '<'.$tag.' class="ilc_'.$t.'_'.$key.'" style="font-size:90%; margin-top:2px; margin-bottom:2px; position:static;">'.$char["txt"].""; - - // this next line is very important for IE. The real onclick event is on the surrounding of the - // advanced selection list. But it is impossible to prevent the tr-event from removing the focus - // on tiny withouth the following line, that receives the click event before and stops the faulty default - // bevaviour of IE, see bug report #8723 - $html = ''.$html.""; - $selection->addItem($char["txt"], $key, "", - "", $key, "", $html); - } - } - return $selection->getHTML(); - } - - /** - * Set Style - */ - private function setStyle() - { - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - - if ($this->pg_obj->getParentType() == "gdf" || - $this->pg_obj->getParentType() == "lm") - { - if ($this->pg_obj->getParentType() != "gdf") - { - $this->tpl->setContentStylesheet(ilObjStyleSheet::getContentStylePath( - ilObjContentObject::_lookupStyleSheetId($this->pg_obj->getParentId()))); - } - else - { - $this->tpl->setContentStylesheet(ilObjStyleSheet::getContentStylePath(0)); - } - } - else - { - if ($this->pg_obj->getParentType() != "sahs") - { -// $this->tpl->setContentStylesheet(ilObjStyleSheet::getContentStylePath(0)); - } - } - } - - /** - * insert paragraph form - */ - function insert() - { - $this->log->debug("ilPCParagraphGUI, saveJS: got updated value ".$this->updated); - return $this->edit(true); - } + /** + * @var ilObjUser + */ + protected $user; + + /** + * Constructor + * @access public + */ + public function __construct($a_pg_obj, &$a_content_obj, $a_hier_id, $a_pc_id = "") + { + global $DIC; + + $this->user = $DIC->user(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); + + // characteristics (should be flexible in the future) + $this->setCharacteristics(ilPCParagraphGUI::_getStandardCharacteristics()); + } - /** - * update paragraph in dom and update page in db - */ - function update() - { - $this->log->debug("ilPCParagraphGUI, update(): start"); - - // set language and characteristic - $this->content_obj->setLanguage($_POST["par_language"]); - $this->content_obj->setCharacteristic($_POST["par_characteristic"]); - - $this->updated = $this->content_obj->setText( - $this->content_obj->input2xml($_POST["par_content"], - $_POST["usedwsiwygeditor"]), true); - if ($this->updated !== true) - { - $this->edit(); - return; - } - - $this->updated = $this->content_obj->updatePage($this->pg_obj); - - - if ($this->updated === true) - { - $this->log->debug("ilPCParagraphGUI, update(): return to parent: jump".$this->hier_id); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - else - { - $this->log->debug("ilPCParagraphGUI, update(): call edit."); - $this->edit(); - } - } - - - /** - * create new paragraph in dom and update page in db - */ - function create() - { - $this->log->debug("ilPCParagraphGUI, create(): start."); - - if ($_POST["ajaxform_hier_id"] != "") - { - return $this->createJS(); - } - - $this->content_obj = new ilPCParagraph($this->getPage()); -//echo "+".$this->pc_id."+"; - $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); - - $this->content_obj->setLanguage($_POST["par_language"]); - $_SESSION["il_text_lang_".$_GET["ref_id"]] = $_POST["par_language"]; - $this->content_obj->setCharacteristic($_POST["par_characteristic"]); - - $this->updated = $this->content_obj->setText( - $this->content_obj->input2xml($_POST["par_content"], - $_POST["usedwsiwygeditor"]), true); - - if ($this->updated !== true) - { - $this->insert(); - return; - } - $this->updated = $this->content_obj->updatePage($this->pg_obj); - - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - else - { - $this->insert(); - } - } - - /** - * Create paragraph per JS - */ - function createJS() - { - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - - $this->log->debug("ilPCParagraphGUI, createJS(): start"); - - $this->content_obj = new ilPCParagraph($this->getPage()); - $this->updated = $this->content_obj->saveJS($this->pg_obj, - $_POST["ajaxform_content"], - ilUtil::stripSlashes($_POST["ajaxform_char"]), - ilUtil::stripSlashes($_POST["pc_id_str"]), - $_POST["insert_at_id"]); - if ($_POST["quick_save"]) - { - if ($this->updated) - { - $a_pc_id_str = $this->content_obj->getLastSavedPcId($this->pg_obj, true); - echo $a_pc_id_str; - $this->log->debug("ilPCParagraphGUI, createJS(): echo pc id and exit: ".$a_pc_id_str); - exit; - } - } - - if ($this->updated !== true && is_array($this->updated)) - { - $this->outputError($this->updated); - } - - // e.g. e.g. ###3:110dad8bad6df8620071a0a693a2d328### - $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, createJS(): return to edit cmd of ".$ilCtrl->getReturnClass($this)); - - $ilCtrl->redirectByClass($ilCtrl->getReturnClass($this), "edit", "", true); - } - - /** - * Insert Help - */ - function insertHelp($a_tpl) - { - $lng = $this->lng; - - $a_tpl->setCurrentBlock("help_item"); - $a_tpl->setVariable("TXT_HELP", "".$lng->txt("cont_syntax_help").""); - $a_tpl->parseCurrentBlock(); - $a_tpl->setCurrentBlock("help_item"); - $a_tpl->setVariable("TXT_HELP", "* ".$lng->txt("cont_bullet_list")); - $a_tpl->parseCurrentBlock(); - $a_tpl->setCurrentBlock("help_item"); - $a_tpl->setVariable("TXT_HELP", "# ".$lng->txt("cont_numbered_list")); - $a_tpl->parseCurrentBlock(); - $a_tpl->setCurrentBlock("help_item"); - $a_tpl->setVariable("TXT_HELP", "=".$lng->txt("cont_Headline1")."=
          ". - "==".$lng->txt("cont_Headline2")."==
          ". - "===".$lng->txt("cont_Headline3")."==="); - $a_tpl->parseCurrentBlock(); - - if ($this->getPageConfig()->getEnableWikiLinks()) - { - $a_tpl->setCurrentBlock("help_item"); - $a_tpl->setVariable("TXT_HELP", "[[".$lng->txt("cont_wiki_page_link")."]]"); - $a_tpl->parseCurrentBlock(); - } - - $a_tpl->setCurrentBlock("help"); - $a_tpl->parseCurrentBlock(); - } - + /** + * Get standard characteristics + */ + public static function _getStandardCharacteristics() + { + global $DIC; + + $lng = $DIC->language(); + + return array("Standard" => $lng->txt("cont_standard"), + "Headline1" => $lng->txt("cont_Headline1"), + "Headline2" => $lng->txt("cont_Headline2"), + "Headline3" => $lng->txt("cont_Headline3"), + "Citation" => $lng->txt("cont_Citation"), + "Mnemonic" => $lng->txt("cont_Mnemonic"), + "Example" => $lng->txt("cont_Example"), + "Additional" => $lng->txt("cont_Additional"), + "Attention" => $lng->txt("cont_Attention"), + "Confirmation" => $lng->txt("cont_Confirmation"), + "Information" => $lng->txt("cont_Information"), + "Link" => $lng->txt("cont_Link"), + "Literature" => $lng->txt("cont_Literature"), + "Separator" => $lng->txt("cont_Separator"), + "StandardCenter" => $lng->txt("cont_StandardCenter"), + "Remark" => $lng->txt("cont_Remark"), + "List" => $lng->txt("cont_List"), + "TableContent" => $lng->txt("cont_TableContent") + ); + } + + /** + * Get standard characteristics + */ + public static function _getStandardTextCharacteristics() + { + global $DIC; + + $lng = $DIC->language(); + return ["Mnemonic", "Attention"]; + return array("Mnemonic" => $lng->txt("cont_Mnemonic"), + "Attention" => $lng->txt("cont_Attention") + ); + } + + /** + * Get characteristics + */ + public static function _getCharacteristics($a_style_id) + { + $st_chars = ilPCParagraphGUI::_getStandardCharacteristics(); + $chars = ilPCParagraphGUI::_getStandardCharacteristics(); + + if ($a_style_id > 0 && + ilObject::_lookupType($a_style_id) == "sty") { + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $style = new ilObjStyleSheet($a_style_id); + $types = array("text_block", "heading1", "heading2", "heading3"); + $chars = array(); + foreach ($types as $t) { + $chars = array_merge($chars, $style->getCharacteristics($t)); + } + $new_chars = array(); + foreach ($chars as $char) { + if ($st_chars[$char] != "") { // keep lang vars for standard chars + $new_chars[$char] = $st_chars[$char]; + } else { + $new_chars[$char] = $char; + } + asort($new_chars); + } + $chars = $new_chars; + } + + return $chars; + } + + /** + * Get text characteristics + * + * @param int $a_style_id + * @param bool $a_include_core include core styles + * @return string[] + */ + public static function _getTextCharacteristics($a_style_id, $a_include_core = false) + { + $chars = array(); + + if ($a_style_id > 0 && + ilObject::_lookupType($a_style_id) == "sty") { + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $style = new ilObjStyleSheet($a_style_id); + $types = array("text_inline"); + foreach ($types as $t) { + $chars = array_merge($chars, $style->getCharacteristics($t, false, $a_include_core)); + } + } else { + return self::_getStandardTextCharacteristics(); + } + + return $chars; + } + + + /** + * execute command + */ + public function executeCommand() + { + // get next class that processes or forwards current command + $next_class = $this->ctrl->getNextClass($this); + + $this->getCharacteristicsOfCurrentStyle( + array("text_block", "heading1", "heading2", "heading3") + ); // scorm-2004 + + // get current command + $cmd = $this->ctrl->getCmd(); + + $this->log->debug("ilPCParagraphGUI: executeCommand " . $cmd); + + switch ($next_class) { + default: + $ret = $this->$cmd(); + break; + } + + return $ret; + } + + /** + * edit paragraph form + */ + public function edit($a_insert = false) + { + $ilUser = $this->user; + + // add paragraph edit template + $tpl = new ilTemplate("tpl.paragraph_edit.html", true, true, "Services/COPage"); + + // help text + $this->insertHelp($tpl); + + // operations + if ($a_insert) { + $tpl->setCurrentBlock("commands"); + $tpl->setVariable("BTN_NAME", "create_par"); + $tpl->setVariable("BTN_TEXT", $this->lng->txt("save")); + $tpl->setVariable("BTN_CANCEL", "cancelCreate"); + $tpl->setVariable("TXT_CANCEL", $this->lng->txt("cancel")); + $tpl->parseCurrentBlock(); + /*$tpl->setCurrentBlock("commands2"); + $tpl->setVariable("BTN_NAME", "create_par"); + $tpl->setVariable("BTN_TEXT", $this->lng->txt("save")); + $tpl->setVariable("BTN_CANCEL", "cancelCreate"); + $tpl->setVariable("TXT_CANCEL", $this->lng->txt("cancel")); + $tpl->parseCurrentBlock();*/ + $tpl->setVariable("TXT_ACTION", $this->lng->txt("cont_insert_par")); + } else { + $tpl->setCurrentBlock("commands"); + $tpl->setVariable("BTN_NAME", "update"); + $tpl->setVariable("BTN_TEXT", $this->lng->txt("save")); + $tpl->setVariable("BTN_CANCEL", "cancelUpdate"); + $tpl->setVariable("TXT_CANCEL", $this->lng->txt("cancel")); + $tpl->parseCurrentBlock(); + /*$tpl->setCurrentBlock("commands2"); + $tpl->setVariable("BTN_NAME", "update"); + $tpl->setVariable("BTN_TEXT", $this->lng->txt("save")); + $tpl->setVariable("BTN_CANCEL", "cancelUpdate"); + $tpl->setVariable("TXT_CANCEL", $this->lng->txt("cancel")); + $tpl->parseCurrentBlock();*/ + $tpl->setVariable("TXT_ACTION", $this->lng->txt("cont_edit_par")); + } + + // language and characteristic selection + $s_char = $this->determineCharacteristic($a_insert); + if (!$a_insert) { + if (key($_POST["cmd"]) == "update") { + $s_lang = $_POST["par_language"]; + } else { + $s_lang = $this->content_obj->getLanguage(); + } + } else { + if (key($_POST["cmd"]) == "create_par") { + $s_lang = $_POST["par_language"]; + } else { + if ($_SESSION["il_text_lang_" . $_GET["ref_id"]] != "") { + $s_lang = $_SESSION["il_text_lang_" . $_GET["ref_id"]]; + } else { + $s_lang = $ilUser->getLanguage(); + } + } + } + + $this->insertStyleSelectionList($tpl, $s_char); + // $this->insertCharacteristicTable($tpl, $s_char); + + + $tpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this)); + + $tpl->setVariable("PAR_TA_NAME", "par_content"); + $tpl->setVariable("BB_MENU", $this->getBBMenu()); + $this->tpl->addJavascript("./Services/COPage/phpBB/3_0_5/editor.js"); + $this->tpl->addJavascript("./Services/COPage/js/paragraph_editing.js"); + $this->setStyle(); + + $this->displayValidationError(); + + $tpl->setVariable("TXT_LANGUAGE", $this->lng->txt("language")); + $tpl->setVariable("TXT_ANCHOR", $this->lng->txt("cont_anchor")); + + require_once("Services/MetaData/classes/class.ilMDLanguageItem.php"); + $lang = ilMDLanguageItem::_getLanguages(); + $select_lang = ilUtil::formSelect($s_lang, "par_language", $lang, false, true); + $tpl->setVariable("SELECT_LANGUAGE", $select_lang); + + $tpl->setVariable("TXT_CHARACTERISTIC", $this->lng->txt("cont_characteristic")); + // $select_char = ilUtil::formSelect ($s_char, + // "par_characteristic",$this->chars,false,true); + // $tpl->setVariable("SELECT_CHARACTERISTIC", $select_char); + + if (key($_POST["cmd"]) == "update" || key($_POST["cmd"]) == "create_par") { + $s_text = ilUtil::stripSlashes($_POST["par_content"], false); + // prevent curly brackets from being swallowed up by template engine + $s_text = str_replace("{", "{", $s_text); + $s_text = str_replace("}", "}", $s_text); + } elseif (!$a_insert) { + $s_text = $this->content_obj->xml2output($this->content_obj->getText()); + } + + $tpl->setVariable("PAR_TA_CONTENT", $s_text); + + $tpl->parseCurrentBlock(); + + $this->tpl->setContent($tpl->get()); + return $tpl->get(); + } + + /** + * Determine current characteristic + * + * @param + * @return + */ + public function determineCharacteristic($a_insert = false) + { + // language and characteristic selection + if (!$a_insert) { + if (key($_POST["cmd"]) == "update") { + $s_char = $_POST["par_characteristic"]; + } else { + $s_char = $this->content_obj->getCharacteristic(); + if ($s_char == "") { + $s_char = "Standard"; + } + } + } else { + if (key($_POST["cmd"]) == "create_par") { + $s_char = $_POST["par_characteristic"]; + } else { + $s_char = "Standard"; + + // set characteristic of new paragraphs in list items to "List" + $cont_obj = $this->pg_obj->getContentObject($this->getHierId()); + if (is_object($cont_obj)) { + if ($cont_obj->getType() == "li" || + ($cont_obj->getType() == "par" && $cont_obj->getCharacteristic() == "List")) { + $s_char = "List"; + } + + if ($cont_obj->getType() == "td" || + ($cont_obj->getType() == "par" && $cont_obj->getCharacteristic() == "TableContent")) { + $s_char = "TableContent"; + } + } + } + } + return $s_char; + } + + /** + * Edit paragraph (Ajax mode, sends the content of the paragraph) + */ + public function editJS() + { + $s_text = $this->content_obj->getText(); + $this->log->debug("step 1: " . substr($s_text, 0, 1000)); + + //echo "\n

          ".htmlentities($s_text); + $s_text = $this->content_obj->xml2output($s_text, true, false); + $this->log->debug("step 2: " . substr($s_text, 0, 1000)); + + //echo "\n

          ".htmlentities($s_text); + $char = $this->determineCharacteristic(false); + $s_text = ilPCParagraphGUI::xml2outputJS($s_text, $char, $this->content_obj->readPCId()); + $this->log->debug("step 3: " . substr($s_text, 0, 1000)); + + //echo "\n

          ".htmlentities($s_text); + $ids = "###" . $this->content_obj->readHierId() . ":" . $this->content_obj->readPCId() . "###" . + $char . "###"; + echo $ids . $s_text; + $this->log->debug("step 4: " . substr($ids . $s_text, 0, 1000)); + exit; + } + + /** + * Edit multiple paragraphs (Ajax mode, sends the content of the paragraphs) + */ + public function editMultipleJS() + { + echo $this->content_obj->getParagraphSequenceContent($this->pg_obj); + exit; + } + + /** + * Prepare content for js output + */ + public static function xml2outputJS($s_text, $char, $a_pc_id) + { + // $s_text = "
          ".$s_text."
          "; + $s_text = $s_text; + // lists + $s_text = str_replace( + array("", ""), + array("
            ", "
          "), + $s_text + ); + $s_text = str_replace( + array("", ""), + array("
            ", "
          "), + $s_text + ); + $s_text = str_replace( + array("", ""), + array("
        • ", "
        • "), + $s_text + ); + $s_text = str_replace( + array(""), + array("
        • "), + $s_text + ); + //$s_text = str_replace("
          ", "", $s_text); + //$s_text = str_replace("
          ", "", $s_text); + //$s_text = str_replace("

          ", "", $s_text); + + + // spans + include_once("./Services/COPage/classes/class.ilPageContentGUI.php"); + foreach (ilPageContentGUI::_getCommonBBButtons() as $bb => $cl) { + if (!in_array($bb, array("code", "tex", "fn", "xln", "sub", "sup"))) { + $s_text = str_replace( + "[" . $bb . "]", + '', + $s_text + ); + $s_text = str_replace( + "[/" . $bb . "]", + '', + $s_text + ); + } + } + + // marked text spans + $ws= "[ \t\r\f\v\n]*"; + while (preg_match("~\[(marked$ws(class$ws=$ws\"([^\"])*\")$ws)\]~i", $s_text, $found)) { + $attribs = ilUtil::attribsToArray($found[2]); + if (isset($attribs["class"])) { + $s_text = str_replace("[" . $found[1] . "]", "", $s_text); + } else { + $s_text = str_replace("[" . $found[1] . "]", "[error:marked" . $found[1] . "]", $s_text); + } + } + $s_text = preg_replace('~\[\/marked\]~i', "", $s_text); + + + // code + $s_text = str_replace( + array("[code]", "[/code]"), + array("", ""), + $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] . "
          "; + } + echo $err_str; + $this->log->debug("ilPCParagraphGUI, outputError() and exit: " . substr($err_str, 0, 100)); + exit; + } + + + /** + * Cancel + */ + public function cancel() + { + $this->log->debug("ilPCParagraphGUI, cancel(): return to parent: jump" . $this->hier_id); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * Insert characteristic table + */ + public function insertCharacteristicTable($a_tpl, $a_seleted_value) + { + $i = 0; + + $chars = $this->getCharacteristics(); + + if ($chars[$a_seleted_value] == "" && ($a_seleted_value != "")) { + $chars = array_merge( + array($a_seleted_value => $a_seleted_value), + $chars + ); + } + + foreach ($chars as $char => $char_lang) { + $a_tpl->setCurrentBlock("characteristic_cell"); + $a_tpl->setVariable( + "CHAR_HTML", + '
          ' . $char_lang . "
          " + ); + $a_tpl->setVariable("CHAR_VALUE", $char); + if ($char == $a_seleted_value) { + $a_tpl->setVariable( + "SELECTED", + ' checked="checked" ' + ); + } + $a_tpl->parseCurrentBlock(); + if ((($i+1) % 3) == 0) { // + $a_tpl->touchBlock("characteristic_row"); + } + $i++; + } + $a_tpl->touchBlock("characteristic_table"); + } + + /** + * Insert style selection list + * + * @param object $a_tpl + * @param string $a_selected + */ + public function insertStyleSelectionList($a_tpl, $a_selected) + { + $a_tpl->setVariable("ADV_SEL_STYLE", self::getStyleSelector( + $a_selected, + $this->getCharacteristics() + )); + } + + /** + * Get style selector + */ + public static function getStyleSelector($a_selected, $a_chars, $a_use_callback = false) + { + include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"); + $selection = new ilAdvancedSelectionListGUI(); + $selection->setPullRight(false); + $selection->setFormSelectMode( + "par_characteristic", + "", + false, + "", + "", + "", + "", + "", + "", + "" + ); + $selection->setId("style_selection"); + $selection->setSelectionHeaderClass("ilEditSubmit ilTinyMenuDropDown"); + $selection->setHeaderIcon(ilAdvancedSelectionListGUI::DOWN_ARROW_DARK); + $selection->setSelectedValue($a_selected); + $selection->setUseImages(false); + $selection->setOnClickMode(ilAdvancedSelectionListGUI::ON_ITEM_CLICK_FORM_SELECT); + if ($a_use_callback) { + $selection->setSelectCallback("ilCOPage.setParagraphClass"); + } + + $chars = $a_chars; + $title_char = ($chars[$a_selected] != "") + ? $chars[$a_selected] + : $a_selected; + $selection->setListTitle($title_char); + + if ($chars[$a_seleted] == "" && ($a_seleted != "")) { + $chars = array_merge( + array($a_seleted => $a_seleted), + $chars + ); + } + + foreach ($chars as $char => $char_lang) { + $t = "text_block"; + $tag = "div"; + switch ($char) { + case "Headline1": $t = "heading1"; $tag = "h1"; break; + case "Headline2": $t = "heading2"; $tag = "h2"; break; + case "Headline3": $t = "heading3"; $tag = "h3"; break; + } + $html = '
          <' . $tag . ' class="ilc_' . $t . '_' . $char . '" style="' . self::$style_selector_reset . '">' . $char_lang . "
          "; + $selection->addItem( + $char_lang, + $char, + "", + "", + $char, + "", + $html + ); + } + return $selection->getHTML(); + } + + /** + * Get character style selector + */ + public static function getCharStyleSelector($a_par_type, $a_use_callback = true, $a_style_id = 0) + { + global $DIC; + + $lng = $DIC->language(); + + include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"); + $selection = new ilAdvancedSelectionListGUI(); + $selection->setPullRight(false); + $selection->setFormSelectMode( + "char_characteristic", + "", + false, + "", + "", + "", + "", + "", + "", + "" + ); + $selection->setId("char_style_selection"); + $selection->setSelectionHeaderClass("ilEditSubmit"); + $selection->setHeaderIcon(ilAdvancedSelectionListGUI::DOWN_ARROW_DARK); + //$selection->setSelectedValue($a_selected); + $selection->setUseImages(false); + $selection->setOnClickMode(ilAdvancedSelectionListGUI::ON_ITEM_CLICK_NOP); + if (is_string($a_use_callback)) { + $selection->setSelectCallback($a_use_callback); + } elseif ($a_use_callback === true) { + $selection->setSelectCallback("ilCOPage.setCharacterClass"); + } + + //$chars = $a_chars; + //$title_char = ($chars[$a_selected] != "") + // ? $chars[$a_selected] + // : $a_selected; + $selection->setListTitle(" A"); + + /*if ($chars[$a_seleted] == "" && ($a_seleted != "")) + { + $chars = array_merge(array($a_seleted => $a_seleted), + $chars); + }*/ + + $chars = array( + "Comment" => array("code" => "com", "txt" => $lng->txt("cont_char_style_com")), + "Quotation" => array("code" => "quot", "txt" =>$lng->txt("cont_char_style_quot")), + "Accent" => array("code" => "acc", "txt" => $lng->txt("cont_char_style_acc")), + "Code" => array("code" => "code", "txt" => $lng->txt("cont_char_style_code")) + ); + + foreach (ilPCParagraphGUI::_getTextCharacteristics($a_style_id) as $c) { + if (!isset($chars[$c])) { + $chars[$c] = array("code" => "", "txt" => $c); + } + } + + foreach ($chars as $key => $char) { + if (ilPageEditorSettings::lookupSettingByParentType( + $a_par_type, + "active_" . $char["code"], + true + )) { + $t = "text_inline"; + $tag = "span"; + switch ($key) { + case "Code": $tag = "code"; break; + } + $html = '<' . $tag . ' class="ilc_' . $t . '_' . $key . '" style="font-size:90%; margin-top:2px; margin-bottom:2px; position:static;">' . $char["txt"] . ""; + + // this next line is very important for IE. The real onclick event is on the surrounding of the + // advanced selection list. But it is impossible to prevent the tr-event from removing the focus + // on tiny withouth the following line, that receives the click event before and stops the faulty default + // bevaviour of IE, see bug report #8723 + $html = '' . $html . ""; + $selection->addItem( + $char["txt"], + $key, + "", + "", + $key, + "", + $html + ); + } + } + return $selection->getHTML(); + } + + /** + * Set Style + */ + private function setStyle() + { + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + + if ($this->pg_obj->getParentType() == "gdf" || + $this->pg_obj->getParentType() == "lm") { + if ($this->pg_obj->getParentType() != "gdf") { + $this->tpl->setContentStylesheet(ilObjStyleSheet::getContentStylePath( + ilObjContentObject::_lookupStyleSheetId($this->pg_obj->getParentId()) + )); + } else { + $this->tpl->setContentStylesheet(ilObjStyleSheet::getContentStylePath(0)); + } + } else { + if ($this->pg_obj->getParentType() != "sahs") { + // $this->tpl->setContentStylesheet(ilObjStyleSheet::getContentStylePath(0)); + } + } + } + + /** + * insert paragraph form + */ + public function insert() + { + $this->log->debug("ilPCParagraphGUI, saveJS: got updated value " . $this->updated); + return $this->edit(true); + } + + /** + * update paragraph in dom and update page in db + */ + public function update() + { + $this->log->debug("ilPCParagraphGUI, update(): start"); + + // set language and characteristic + $this->content_obj->setLanguage($_POST["par_language"]); + $this->content_obj->setCharacteristic($_POST["par_characteristic"]); + + $this->updated = $this->content_obj->setText( + $this->content_obj->input2xml( + $_POST["par_content"], + $_POST["usedwsiwygeditor"] + ), + true + ); + if ($this->updated !== true) { + $this->edit(); + return; + } + + $this->updated = $this->content_obj->updatePage($this->pg_obj); + + + if ($this->updated === true) { + $this->log->debug("ilPCParagraphGUI, update(): return to parent: jump" . $this->hier_id); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } else { + $this->log->debug("ilPCParagraphGUI, update(): call edit."); + $this->edit(); + } + } + + + /** + * create new paragraph in dom and update page in db + */ + public function create() + { + $this->log->debug("ilPCParagraphGUI, create(): start."); + + if ($_POST["ajaxform_hier_id"] != "") { + return $this->createJS(); + } + + $this->content_obj = new ilPCParagraph($this->getPage()); + //echo "+".$this->pc_id."+"; + $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); + + $this->content_obj->setLanguage($_POST["par_language"]); + $_SESSION["il_text_lang_" . $_GET["ref_id"]] = $_POST["par_language"]; + $this->content_obj->setCharacteristic($_POST["par_characteristic"]); + + $this->updated = $this->content_obj->setText( + $this->content_obj->input2xml( + $_POST["par_content"], + $_POST["usedwsiwygeditor"] + ), + true + ); + + if ($this->updated !== true) { + $this->insert(); + return; + } + $this->updated = $this->content_obj->updatePage($this->pg_obj); + + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } else { + $this->insert(); + } + } + + /** + * Create paragraph per JS + */ + public function createJS() + { + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + + $this->log->debug("ilPCParagraphGUI, createJS(): start"); + + $this->content_obj = new ilPCParagraph($this->getPage()); + $this->updated = $this->content_obj->saveJS( + $this->pg_obj, + $_POST["ajaxform_content"], + ilUtil::stripSlashes($_POST["ajaxform_char"]), + ilUtil::stripSlashes($_POST["pc_id_str"]), + $_POST["insert_at_id"] + ); + if ($_POST["quick_save"]) { + if ($this->updated) { + $a_pc_id_str = $this->content_obj->getLastSavedPcId($this->pg_obj, true); + echo $a_pc_id_str; + $this->log->debug("ilPCParagraphGUI, createJS(): echo pc id and exit: " . $a_pc_id_str); + exit; + } + } + + if ($this->updated !== true && is_array($this->updated)) { + $this->outputError($this->updated); + } + + // e.g. e.g. ###3:110dad8bad6df8620071a0a693a2d328### + $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, createJS(): return to edit cmd of " . $ilCtrl->getReturnClass($this)); + + $ilCtrl->redirectByClass($ilCtrl->getReturnClass($this), "edit", "", true); + } + + /** + * Insert Help + */ + public function insertHelp($a_tpl) + { + $lng = $this->lng; + + $a_tpl->setCurrentBlock("help_item"); + $a_tpl->setVariable("TXT_HELP", "" . $lng->txt("cont_syntax_help") . ""); + $a_tpl->parseCurrentBlock(); + $a_tpl->setCurrentBlock("help_item"); + $a_tpl->setVariable("TXT_HELP", "* " . $lng->txt("cont_bullet_list")); + $a_tpl->parseCurrentBlock(); + $a_tpl->setCurrentBlock("help_item"); + $a_tpl->setVariable("TXT_HELP", "# " . $lng->txt("cont_numbered_list")); + $a_tpl->parseCurrentBlock(); + $a_tpl->setCurrentBlock("help_item"); + $a_tpl->setVariable("TXT_HELP", "=" . $lng->txt("cont_Headline1") . "=
          " . + "==" . $lng->txt("cont_Headline2") . "==
          " . + "===" . $lng->txt("cont_Headline3") . "==="); + $a_tpl->parseCurrentBlock(); + + if ($this->getPageConfig()->getEnableWikiLinks()) { + $a_tpl->setCurrentBlock("help_item"); + $a_tpl->setVariable("TXT_HELP", "[[" . $lng->txt("cont_wiki_page_link") . "]]"); + $a_tpl->parseCurrentBlock(); + } + + $a_tpl->setCurrentBlock("help"); + $a_tpl->parseCurrentBlock(); + } } -?> diff --git a/Services/COPage/classes/class.ilPCPlaceHolder.php b/Services/COPage/classes/class.ilPCPlaceHolder.php index 3858c6ef16e98e3d38abd29b18f65d303f845ead..74ab2368123a67a28dcb90bde6a2d7536271cf0f 100644 --- a/Services/COPage/classes/class.ilPCPlaceHolder.php +++ b/Services/COPage/classes/class.ilPCPlaceHolder.php @@ -14,195 +14,186 @@ require_once("./Services/COPage/classes/class.ilPageContent.php"); * @ingroup ServicesCOPage */ -class ilPCPlaceHolder extends ilPageContent { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - //class of placeholder - - var $q_node; // node of Paragraph element - var $content_class; - var $height; - - /** - * Init page content component. - */ - function init() - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->setType("plach"); - } - - - /** - * Set node - */ - function setNode($a_node) - { - parent::setNode($a_node); // this is the PageContent node - $this->q_node = $a_node->first_child(); //... and this the PlaceHolder - } - - /** - * Create PlaceHolder Element - */ - function create(&$a_pg_obj, $a_hier_id) - { - $this->createPageContentNode(); - $a_pg_obj->insertContent($this, $a_hier_id, IL_INSERT_AFTER); - $this->q_node = $this->dom->create_element("PlaceHolder"); - $this->q_node = $this->node->append_child($this->q_node); - } - - /** - * Set Content Class. - * - * @param string $a_class Content Class - */ - function setContentClass($a_class) - { - if (is_object($this->q_node)) - { - $this->q_node->set_attribute("ContentClass", $a_class); - } - } - - /** - * Get Content Class. - * - * @return string Content Class - */ - function getContentClass() - { - if (is_object($this->q_node)) - { - return $this->q_node->get_attribute("ContentClass", $a_class); - } - return false; - } - - /** - * Set Height - * - * @param string $a_height Height - */ - function setHeight($a_height) - { - if (is_object($this->q_node)) - { - $this->q_node->set_attribute("Height", $a_height); - } - } - - - /** - * Get Height - * - * @return string Content Class - */ - function getHeight() - { - if (is_object($this->q_node)) - { - return $this->q_node->get_attribute("Height", $a_class); - } - return false; - } - - /** - * Get characteristic of PlaceHolder. - * - * @return string characteristic - */ - function getClass() - { - return ""; - } - - /** - * Get lang vars needed for editing - * @return array array of lang var keys - */ - static function getLangVars() - { - return array("question_placeh","media_placeh","text_placeh", - "ed_insert_plach","question_placehl","media_placehl","text_placehl", - "verification_placeh", "verification_placehl"); - } - - - /** - * Modify page content after xsl - * - * @param string $a_html - * @return string - */ - function modifyPageContentPostXsl($a_html, $a_mode) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - // - // Note: this standard output is "overwritten", e.g. by ilPortfolioPageGUI::postOutputProcessing - // - - $c_pos = 0; - $start = strpos($a_html, "{{{{{PlaceHolder#"); - if (is_int($start)) - { - $end = strpos($a_html, "}}}}}", $start); - } - $i = 1; - while ($end > 0) - { - $param = substr($a_html, $start + 17, $end - $start - 17); - $param = explode("#", $param); - - $html = $param[2]; - switch ($param[2]) - { - case "Text": - $html = $lng->txt("cont_text_placeh"); - break; - - case "Media": - $html = $lng->txt("cont_media_placeh"); - break; - - case "Question": - $html = $lng->txt("cont_question_placeh"); - break; - - case "Verification": - $html = $lng->txt("cont_verification_placeh"); - break; - } - - $h2 = substr($a_html, 0, $start). - $html. - substr($a_html, $end + 5); - $a_html = $h2; - $i++; - - $start = strpos($a_html, "{{{{{PlaceHolder#", $start + 5); - $end = 0; - if (is_int($start)) - { - $end = strpos($a_html, "}}}}}", $start); - } - } - return $a_html; - } - - -} \ No newline at end of file +class ilPCPlaceHolder extends ilPageContent +{ + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + //class of placeholder + + public $q_node; // node of Paragraph element + public $content_class; + public $height; + + /** + * Init page content component. + */ + public function init() + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->setType("plach"); + } + + + /** + * Set node + */ + public function setNode($a_node) + { + parent::setNode($a_node); // this is the PageContent node + $this->q_node = $a_node->first_child(); //... and this the PlaceHolder + } + + /** + * Create PlaceHolder Element + */ + public function create(&$a_pg_obj, $a_hier_id) + { + $this->createPageContentNode(); + $a_pg_obj->insertContent($this, $a_hier_id, IL_INSERT_AFTER); + $this->q_node = $this->dom->create_element("PlaceHolder"); + $this->q_node = $this->node->append_child($this->q_node); + } + + /** + * Set Content Class. + * + * @param string $a_class Content Class + */ + public function setContentClass($a_class) + { + if (is_object($this->q_node)) { + $this->q_node->set_attribute("ContentClass", $a_class); + } + } + + /** + * Get Content Class. + * + * @return string Content Class + */ + public function getContentClass() + { + if (is_object($this->q_node)) { + return $this->q_node->get_attribute("ContentClass", $a_class); + } + return false; + } + + /** + * Set Height + * + * @param string $a_height Height + */ + public function setHeight($a_height) + { + if (is_object($this->q_node)) { + $this->q_node->set_attribute("Height", $a_height); + } + } + + + /** + * Get Height + * + * @return string Content Class + */ + public function getHeight() + { + if (is_object($this->q_node)) { + return $this->q_node->get_attribute("Height", $a_class); + } + return false; + } + + /** + * Get characteristic of PlaceHolder. + * + * @return string characteristic + */ + public function getClass() + { + return ""; + } + + /** + * Get lang vars needed for editing + * @return array array of lang var keys + */ + public static function getLangVars() + { + return array("question_placeh","media_placeh","text_placeh", + "ed_insert_plach","question_placehl","media_placehl","text_placehl", + "verification_placeh", "verification_placehl"); + } + + + /** + * Modify page content after xsl + * + * @param string $a_html + * @return string + */ + public function modifyPageContentPostXsl($a_html, $a_mode) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + // + // Note: this standard output is "overwritten", e.g. by ilPortfolioPageGUI::postOutputProcessing + // + + $c_pos = 0; + $start = strpos($a_html, "{{{{{PlaceHolder#"); + if (is_int($start)) { + $end = strpos($a_html, "}}}}}", $start); + } + $i = 1; + while ($end > 0) { + $param = substr($a_html, $start + 17, $end - $start - 17); + $param = explode("#", $param); + + $html = $param[2]; + switch ($param[2]) { + case "Text": + $html = $lng->txt("cont_text_placeh"); + break; + + case "Media": + $html = $lng->txt("cont_media_placeh"); + break; + + case "Question": + $html = $lng->txt("cont_question_placeh"); + break; + + case "Verification": + $html = $lng->txt("cont_verification_placeh"); + break; + } + + $h2 = substr($a_html, 0, $start) . + $html . + substr($a_html, $end + 5); + $a_html = $h2; + $i++; + + $start = strpos($a_html, "{{{{{PlaceHolder#", $start + 5); + $end = 0; + if (is_int($start)) { + $end = strpos($a_html, "}}}}}", $start); + } + } + return $a_html; + } +} diff --git a/Services/COPage/classes/class.ilPCPlaceHolderGUI.php b/Services/COPage/classes/class.ilPCPlaceHolderGUI.php index f60e8a8a918ce6fcebeee29e7409295cf54eacc2..749518bbe066190ecbfdf0507711e5684dc46916 100644 --- a/Services/COPage/classes/class.ilPCPlaceHolderGUI.php +++ b/Services/COPage/classes/class.ilPCPlaceHolderGUI.php @@ -18,387 +18,371 @@ require_once("./Services/COPage/classes/class.ilPageContentGUI.php"); * @ingroup ServicesCOPage */ class ilPCPlaceHolderGUI extends ilPageContentGUI -{ - public $pg_obj; - public $content_obj; - public $hier_id; - public $pc_id; - protected $styleid; - - const TYPE_TEXT = "Text"; - const TYPE_QUESTION = "Question"; - const TYPE_MEDIA = "Media"; - const TYPE_VERIFICATION = "Verification"; - - /** - * Constructor - * @access public - */ - public function __construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id = "") - { - global $DIC; +{ + public $pg_obj; + public $content_obj; + public $hier_id; + public $pc_id; + protected $styleid; + + const TYPE_TEXT = "Text"; + const TYPE_QUESTION = "Question"; + const TYPE_MEDIA = "Media"; + const TYPE_VERIFICATION = "Verification"; + + /** + * Constructor + * @access public + */ + public function __construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id = "") + { + global $DIC; - $this->lng = $DIC->language(); - $this->pg_obj = $a_pg_obj; - $this->content_obj = $a_content_obj; - $this->hier_id = $a_hier_id; - $this->pc_id = $a_pc_id; - - 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(); + $this->lng = $DIC->language(); + $this->pg_obj = $a_pg_obj; + $this->content_obj = $a_content_obj; + $this->hier_id = $a_hier_id; + $this->pc_id = $a_pc_id; + + 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) - { - case 'ilpcmediaobjectgui': //special handling - include_once("./Services/COPage/classes/class.ilPCMediaObjectGUI.php"); - $media_gui = new ilPCMediaObjectGUI($this->pg_obj, $this->content_obj, $this->hier_id, $this->pc_id); - $ret = $this->ctrl->forwardCommand($media_gui); - break; - - default: - $ret = $this->$cmd(); - break; - } - - return $ret; - } - - /** - * Handle Insert - */ - protected function insert() - { - $this->propertyGUI("create", self::TYPE_TEXT, "100px", "insert"); - } - - /** - * create new table in dom and update page in db - */ - protected function create() - { - if ($_POST["plach_height"]=="" || - !preg_match("/[0-9]+/",$_POST["plach_height"])) - { - return $this->insert(); - } - - $this->content_obj = new ilPCPlaceHolder($this->getPage()); - $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); - $this->content_obj->setHeight($_POST["plach_height"]."px"); - $this->content_obj->setContentClass($_POST['plach_type']); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - else - { - $this->insert(); - } - } - - /** - * Handle Editing - */ - public function edit() - { - if($this->getPageConfig()->getEnablePCType("PlaceHolder")) - { - $this->edit_object(); - } - else - { - $this->forward_edit(); - } - } - - /** - * Set Style Id. - * - * @param int $a_styleid Style Id - */ - public function setStyleId($a_styleid) - { - $this->styleid = $a_styleid; - } + switch ($next_class) { + case 'ilpcmediaobjectgui': //special handling + include_once("./Services/COPage/classes/class.ilPCMediaObjectGUI.php"); + $media_gui = new ilPCMediaObjectGUI($this->pg_obj, $this->content_obj, $this->hier_id, $this->pc_id); + $ret = $this->ctrl->forwardCommand($media_gui); + break; + + default: + $ret = $this->$cmd(); + break; + } + + return $ret; + } + + /** + * Handle Insert + */ + protected function insert() + { + $this->propertyGUI("create", self::TYPE_TEXT, "100px", "insert"); + } + + /** + * create new table in dom and update page in db + */ + protected function create() + { + if ($_POST["plach_height"]=="" || + !preg_match("/[0-9]+/", $_POST["plach_height"])) { + return $this->insert(); + } + + $this->content_obj = new ilPCPlaceHolder($this->getPage()); + $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); + $this->content_obj->setHeight($_POST["plach_height"] . "px"); + $this->content_obj->setContentClass($_POST['plach_type']); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } else { + $this->insert(); + } + } + + /** + * Handle Editing + */ + public function edit() + { + if ($this->getPageConfig()->getEnablePCType("PlaceHolder")) { + $this->edit_object(); + } else { + $this->forward_edit(); + } + } + + /** + * Set Style Id. + * + * @param int $a_styleid Style Id + */ + public function setStyleId($a_styleid) + { + $this->styleid = $a_styleid; + } - /** - * Get Style Id. - * - * @return int Style Id - */ - public function getStyleId() - { - return $this->styleid; - } + /** + * Get Style Id. + * + * @return int Style Id + */ + public function getStyleId() + { + return $this->styleid; + } - /** - * Handle Editing Private Methods - */ - protected function edit_object() - { - $this->propertyGUI("saveProperties", - $this->content_obj->getContentClass(), - $this->content_obj->getHeight(), - "save"); - } - - protected function forward_edit() - { - switch ($this->content_obj->getContentClass()) - { - case self::TYPE_MEDIA: - include_once("./Services/COPage/classes/class.ilPCMediaObjectGUI.php"); - $this->ctrl->setCmdClass("ilpcmediaobjectgui"); - $this->ctrl->setCmd("insert"); - $media_gui = new ilPCMediaObjectGUI($this->pg_obj, null); - $this->ctrl->forwardCommand($media_gui); - break; - - case self::TYPE_TEXT: - $this->textCOSelectionGUI(); - break; - - case self::TYPE_QUESTION: - include_once("./Services/COPage/classes/class.ilPCQuestionGUI.php"); - $this->ctrl->setCmdClass("ilpcquestiongui"); - $this->ctrl->setCmd("insert"); - $question_gui = new ilPCQuestionGUI($this->pg_obj, $this->content_obj, $this->hier_id, $this->pc_id); - $question_gui->setSelfAssessmentMode(true); - $this->ctrl->forwardCommand($question_gui); - break; - - case self::TYPE_VERIFICATION: - include_once("./Services/COPage/classes/class.ilPCVerificationGUI.php"); - $this->ctrl->setCmdClass("ilpcverificationgui"); - $this->ctrl->setCmd("insert"); - $cert_gui = new ilPCVerificationGUI($this->pg_obj, $this->content_obj, $this->hier_id, $this->pc_id); - $this->ctrl->forwardCommand($cert_gui); - break; - - default: - break; - } - } - - - /** - * save placeholder properties in db and return to page edit screen - */ - protected function saveProperties() - { - if ($_POST["plach_height"]=="" || - !preg_match("/[0-9]+/",$_POST["plach_height"])) { - return $this->edit_object(); - } - - $this->content_obj->setContentClass($_POST['plach_type']); - $this->content_obj->setHeight($_POST["plach_height"]."px"); - - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - else - { - $this->pg_obj->addHierIDs(); - $this->edit(); - } - } - - /** - * Object Property GUI - */ - protected function propertyGUI($a_action,$a_type,$a_height,$a_mode) - { - $lng = $this->lng; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form_gui = new ilPropertyFormGUI(); - $this->form_gui->setFormAction($this->ctrl->getFormAction($this)); - $this->form_gui->setTitle($lng->txt("cont_ed_plachprop")); + /** + * Handle Editing Private Methods + */ + protected function edit_object() + { + $this->propertyGUI( + "saveProperties", + $this->content_obj->getContentClass(), + $this->content_obj->getHeight(), + "save" + ); + } + + protected function forward_edit() + { + switch ($this->content_obj->getContentClass()) { + case self::TYPE_MEDIA: + include_once("./Services/COPage/classes/class.ilPCMediaObjectGUI.php"); + $this->ctrl->setCmdClass("ilpcmediaobjectgui"); + $this->ctrl->setCmd("insert"); + $media_gui = new ilPCMediaObjectGUI($this->pg_obj, null); + $this->ctrl->forwardCommand($media_gui); + break; + + case self::TYPE_TEXT: + $this->textCOSelectionGUI(); + break; + + case self::TYPE_QUESTION: + include_once("./Services/COPage/classes/class.ilPCQuestionGUI.php"); + $this->ctrl->setCmdClass("ilpcquestiongui"); + $this->ctrl->setCmd("insert"); + $question_gui = new ilPCQuestionGUI($this->pg_obj, $this->content_obj, $this->hier_id, $this->pc_id); + $question_gui->setSelfAssessmentMode(true); + $this->ctrl->forwardCommand($question_gui); + break; + + case self::TYPE_VERIFICATION: + include_once("./Services/COPage/classes/class.ilPCVerificationGUI.php"); + $this->ctrl->setCmdClass("ilpcverificationgui"); + $this->ctrl->setCmd("insert"); + $cert_gui = new ilPCVerificationGUI($this->pg_obj, $this->content_obj, $this->hier_id, $this->pc_id); + $this->ctrl->forwardCommand($cert_gui); + break; + + default: + break; + } + } + + + /** + * save placeholder properties in db and return to page edit screen + */ + protected function saveProperties() + { + if ($_POST["plach_height"]=="" || + !preg_match("/[0-9]+/", $_POST["plach_height"])) { + return $this->edit_object(); + } + + $this->content_obj->setContentClass($_POST['plach_type']); + $this->content_obj->setHeight($_POST["plach_height"] . "px"); + + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } else { + $this->pg_obj->addHierIDs(); + $this->edit(); + } + } + + /** + * Object Property GUI + */ + protected function propertyGUI($a_action, $a_type, $a_height, $a_mode) + { + $lng = $this->lng; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form_gui = new ilPropertyFormGUI(); + $this->form_gui->setFormAction($this->ctrl->getFormAction($this)); + $this->form_gui->setTitle($lng->txt("cont_ed_plachprop")); - $ttype_input = new ilRadioGroupInputGUI($lng->txt("type"), "plach_type"); - $type_captions = $this->getTypeCaptions(); - foreach($this->getAvailableTypes($a_type) as $type) - { - $ttype_input->addOption(new ilRadioOption($type_captions[$type], $type)); - } - $ttype_input->setRequired(true); - $this->form_gui->addItem($ttype_input); - - $theight_input = new ilTextInputGUI($lng->txt("height"),"plach_height"); - $theight_input->setSize(4); - $theight_input->setMaxLength(3); - $theight_input->setTitle($lng->txt("height")." (px)"); - $theight_input->setRequired(true); - $this->form_gui->addItem($theight_input); - - $theight_input->setValue(preg_replace("/px/","",$a_height)); - $ttype_input->setValue($a_type); - - $this->form_gui->addCommandButton($a_action, $lng->txt($a_mode)); - $this->form_gui->addCommandButton("cancelCreate", $lng->txt("cancel")); - $this->tpl->setContent($this->form_gui->getHTML()); - } - - /** - * Text Item Selection - */ - protected function textCOSelectionGUI() - { - $lng = $this->lng; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form_gui = new ilPropertyFormGUI(); - $this->form_gui->setFormAction($this->ctrl->getFormAction($this)); - $this->form_gui->setTitle($lng->txt("cont_ed_select_pctext")); + $ttype_input = new ilRadioGroupInputGUI($lng->txt("type"), "plach_type"); + $type_captions = $this->getTypeCaptions(); + foreach ($this->getAvailableTypes($a_type) as $type) { + $ttype_input->addOption(new ilRadioOption($type_captions[$type], $type)); + } + $ttype_input->setRequired(true); + $this->form_gui->addItem($ttype_input); + + $theight_input = new ilTextInputGUI($lng->txt("height"), "plach_height"); + $theight_input->setSize(4); + $theight_input->setMaxLength(3); + $theight_input->setTitle($lng->txt("height") . " (px)"); + $theight_input->setRequired(true); + $this->form_gui->addItem($theight_input); + + $theight_input->setValue(preg_replace("/px/", "", $a_height)); + $ttype_input->setValue($a_type); + + $this->form_gui->addCommandButton($a_action, $lng->txt($a_mode)); + $this->form_gui->addCommandButton("cancelCreate", $lng->txt("cancel")); + $this->tpl->setContent($this->form_gui->getHTML()); + } + + /** + * Text Item Selection + */ + protected function textCOSelectionGUI() + { + $lng = $this->lng; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form_gui = new ilPropertyFormGUI(); + $this->form_gui->setFormAction($this->ctrl->getFormAction($this)); + $this->form_gui->setTitle($lng->txt("cont_ed_select_pctext")); - // Select Question Type - $ttype_input = new ilRadioGroupInputGUI($lng->txt("cont_ed_textitem"), "pctext_type"); - $ttype_input->addOption(new ilRadioOption($lng->txt("cont_ed_par"), 0)); - $ttype_input->addOption(new ilRadioOption($lng->txt("cont_ed_dtable"), 1)); - $ttype_input->addOption(new ilRadioOption($lng->txt("cont_ed_atable"), 2)); - $ttype_input->addOption(new ilRadioOption($lng->txt("cont_ed_list"), 3)); - $ttype_input->addOption(new ilRadioOption($lng->txt("cont_ed_flist"), 4)); - $ttype_input->addOption(new ilRadioOption($lng->txt("cont_tabs"), 5)); - $this->form_gui->addItem($ttype_input); - - $this->form_gui->addCommandButton("insertPCText", $lng->txt("insert")); - $this->form_gui->addCommandButton("cancelCreate", $lng->txt("cancel")); - $this->tpl->setContent($this->form_gui->getHTML()); - } - - /** - * Forwards Text Item Selection to GUI classes - */ - protected function insertPCText() - { - switch ($_POST['pctext_type']) - { - case 0: //Paragraph / Text - - // js editing? -> redirect to js page editor - // if ($ilSetting->get("enable_js_edit", 1) && ilPageEditorGUI::_doJSEditing()) - if (ilPageEditorGUI::_doJSEditing()) - { - $ret_class = $this->ctrl->getReturnClass($this); - $this->ctrl->setParameterByClass($ret_class, "pl_hier_id", $this->hier_id); - $this->ctrl->setParameterByClass($ret_class, "pl_pc_id", $this->pc_id); - $this->ctrl->redirectByClass($ret_class, - "insertJSAtPlaceholder"); - } + // Select Question Type + $ttype_input = new ilRadioGroupInputGUI($lng->txt("cont_ed_textitem"), "pctext_type"); + $ttype_input->addOption(new ilRadioOption($lng->txt("cont_ed_par"), 0)); + $ttype_input->addOption(new ilRadioOption($lng->txt("cont_ed_dtable"), 1)); + $ttype_input->addOption(new ilRadioOption($lng->txt("cont_ed_atable"), 2)); + $ttype_input->addOption(new ilRadioOption($lng->txt("cont_ed_list"), 3)); + $ttype_input->addOption(new ilRadioOption($lng->txt("cont_ed_flist"), 4)); + $ttype_input->addOption(new ilRadioOption($lng->txt("cont_tabs"), 5)); + $this->form_gui->addItem($ttype_input); + + $this->form_gui->addCommandButton("insertPCText", $lng->txt("insert")); + $this->form_gui->addCommandButton("cancelCreate", $lng->txt("cancel")); + $this->tpl->setContent($this->form_gui->getHTML()); + } + + /** + * Forwards Text Item Selection to GUI classes + */ + protected function insertPCText() + { + switch ($_POST['pctext_type']) { + case 0: //Paragraph / Text + + // js editing? -> redirect to js page editor + // if ($ilSetting->get("enable_js_edit", 1) && ilPageEditorGUI::_doJSEditing()) + if (ilPageEditorGUI::_doJSEditing()) { + $ret_class = $this->ctrl->getReturnClass($this); + $this->ctrl->setParameterByClass($ret_class, "pl_hier_id", $this->hier_id); + $this->ctrl->setParameterByClass($ret_class, "pl_pc_id", $this->pc_id); + $this->ctrl->redirectByClass( + $ret_class, + "insertJSAtPlaceholder" + ); + } - include_once("./Services/COPage/classes/class.ilPCParagraphGUI.php"); - $this->ctrl->setCmdClass("ilpcparagraphgui"); - $this->ctrl->setCmd("insert"); - $paragraph_gui = new ilPCParagraphGUI($this->pg_obj, $this->content_obj, $this->hier_id, $this->pc_id); - $paragraph_gui->setStyleId($this->getStyleId()); - $paragraph_gui->setPageConfig($this->getPageConfig()); - $this->ctrl->forwardCommand($paragraph_gui); - break; - - case 1: //DataTable - include_once("./Services/COPage/classes/class.ilPCDataTableGUI.php"); - $this->ctrl->setCmdClass("ilpcdatatablegui"); - $this->ctrl->setCmd("insert"); - $dtable_gui = new ilPCDataTableGUI($this->pg_obj, $this->content_obj, $this->hier_id, $this->pc_id); - $this->ctrl->forwardCommand($dtable_gui); - break; - - case 2: //Advanced Table - include_once("./Services/COPage/classes/class.ilPCTableGUI.php"); - $this->ctrl->setCmdClass("ilpctablegui"); - $this->ctrl->setCmd("insert"); - $atable_gui = new ilPCTableGUI($this->pg_obj, $this->content_obj, $this->hier_id, $this->pc_id); - $this->ctrl->forwardCommand($atable_gui); - break; - - case 3: //Advanced List - include_once("./Services/COPage/classes/class.ilPCListGUI.php"); - $this->ctrl->setCmdClass("ilpclistgui"); - $this->ctrl->setCmd("insert"); - $list_gui = new ilPCListGUI($this->pg_obj, $this->content_obj, $this->hier_id, $this->pc_id); - $this->ctrl->forwardCommand($list_gui); - break; - - case 4: //File List - include_once ("./Services/COPage/classes/class.ilPCFileListGUI.php"); - $this->ctrl->setCmdClass("ilpcfilelistgui"); - $this->ctrl->setCmd("insert"); - $file_list_gui = new ilPCFileListGUI($this->pg_obj, $this->content_obj, $this->hier_id, $this->pc_id); - $file_list_gui->setStyleId($this->getStyleId()); - $this->ctrl->forwardCommand($file_list_gui); - break; - - case 5: //Tabs - include_once ("./Services/COPage/classes/class.ilPCTabsGUI.php"); - $this->ctrl->setCmdClass("ilpctabsgui"); - $this->ctrl->setCmd("insert"); - $tabs_gui = new ilPCTabsGUI($this->pg_obj, $this->content_obj, $this->hier_id, $this->pc_id); - $tabs_gui->setStyleId($this->getStyleId()); - $this->ctrl->forwardCommand($tabs_gui); - break; - - default: - break; - } - } - - /** - * Cancel - */ - public function cancel() - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - protected function getAvailableTypes($a_selected_type = "") - { - // custom config? - if(method_exists($this->getPageConfig(), "getAvailablePlaceholderTypes")) - { - $types = $this->getPageConfig()->getAvailablePlaceholderTypes(); - } - else - { - $types = array(self::TYPE_TEXT, self::TYPE_MEDIA, self::TYPE_QUESTION); - } + include_once("./Services/COPage/classes/class.ilPCParagraphGUI.php"); + $this->ctrl->setCmdClass("ilpcparagraphgui"); + $this->ctrl->setCmd("insert"); + $paragraph_gui = new ilPCParagraphGUI($this->pg_obj, $this->content_obj, $this->hier_id, $this->pc_id); + $paragraph_gui->setStyleId($this->getStyleId()); + $paragraph_gui->setPageConfig($this->getPageConfig()); + $this->ctrl->forwardCommand($paragraph_gui); + break; + + case 1: //DataTable + include_once("./Services/COPage/classes/class.ilPCDataTableGUI.php"); + $this->ctrl->setCmdClass("ilpcdatatablegui"); + $this->ctrl->setCmd("insert"); + $dtable_gui = new ilPCDataTableGUI($this->pg_obj, $this->content_obj, $this->hier_id, $this->pc_id); + $this->ctrl->forwardCommand($dtable_gui); + break; + + case 2: //Advanced Table + include_once("./Services/COPage/classes/class.ilPCTableGUI.php"); + $this->ctrl->setCmdClass("ilpctablegui"); + $this->ctrl->setCmd("insert"); + $atable_gui = new ilPCTableGUI($this->pg_obj, $this->content_obj, $this->hier_id, $this->pc_id); + $this->ctrl->forwardCommand($atable_gui); + break; + + case 3: //Advanced List + include_once("./Services/COPage/classes/class.ilPCListGUI.php"); + $this->ctrl->setCmdClass("ilpclistgui"); + $this->ctrl->setCmd("insert"); + $list_gui = new ilPCListGUI($this->pg_obj, $this->content_obj, $this->hier_id, $this->pc_id); + $this->ctrl->forwardCommand($list_gui); + break; + + case 4: //File List + include_once("./Services/COPage/classes/class.ilPCFileListGUI.php"); + $this->ctrl->setCmdClass("ilpcfilelistgui"); + $this->ctrl->setCmd("insert"); + $file_list_gui = new ilPCFileListGUI($this->pg_obj, $this->content_obj, $this->hier_id, $this->pc_id); + $file_list_gui->setStyleId($this->getStyleId()); + $this->ctrl->forwardCommand($file_list_gui); + break; + + case 5: //Tabs + include_once("./Services/COPage/classes/class.ilPCTabsGUI.php"); + $this->ctrl->setCmdClass("ilpctabsgui"); + $this->ctrl->setCmd("insert"); + $tabs_gui = new ilPCTabsGUI($this->pg_obj, $this->content_obj, $this->hier_id, $this->pc_id); + $tabs_gui->setStyleId($this->getStyleId()); + $this->ctrl->forwardCommand($tabs_gui); + break; + + default: + break; + } + } + + /** + * Cancel + */ + public function cancel() + { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + protected function getAvailableTypes($a_selected_type = "") + { + // custom config? + if (method_exists($this->getPageConfig(), "getAvailablePlaceholderTypes")) { + $types = $this->getPageConfig()->getAvailablePlaceholderTypes(); + } else { + $types = array(self::TYPE_TEXT, self::TYPE_MEDIA, self::TYPE_QUESTION); + } - include_once("./Services/Certificate/classes/class.ilCertificate.php"); - if (!ilCertificate::isActive()) - { - // we remove type verification if certificates are deactivated and this - // is not the currently selected value - if (($key = array_search(self::TYPE_VERIFICATION, $types)) !== false && - self::TYPE_VERIFICATION != $a_selected_type) - { - unset($types[$key]); - } - } - return $types; - } - - protected function getTypeCaptions() - { - $lng = $this->lng; - - return array( - self::TYPE_TEXT => $lng->txt("cont_ed_plachtext"), - self::TYPE_MEDIA => $lng->txt("cont_ed_plachmedia"), - self::TYPE_QUESTION => $lng->txt("cont_ed_plachquestion"), - self::TYPE_VERIFICATION => $lng->txt("cont_ed_plachverification") - ); - } -} \ No newline at end of file + include_once("./Services/Certificate/classes/class.ilCertificate.php"); + if (!ilCertificate::isActive()) { + // we remove type verification if certificates are deactivated and this + // is not the currently selected value + if (($key = array_search(self::TYPE_VERIFICATION, $types)) !== false && + self::TYPE_VERIFICATION != $a_selected_type) { + unset($types[$key]); + } + } + return $types; + } + + protected function getTypeCaptions() + { + $lng = $this->lng; + + return array( + self::TYPE_TEXT => $lng->txt("cont_ed_plachtext"), + self::TYPE_MEDIA => $lng->txt("cont_ed_plachmedia"), + self::TYPE_QUESTION => $lng->txt("cont_ed_plachquestion"), + self::TYPE_VERIFICATION => $lng->txt("cont_ed_plachverification") + ); + } +} diff --git a/Services/COPage/classes/class.ilPCPlugged.php b/Services/COPage/classes/class.ilPCPlugged.php index 1efa9976347193c180743d0ee590a7ced8e43121..1faa9010f6eefeb2caec844fd1781b41b4fd01df 100755 --- a/Services/COPage/classes/class.ilPCPlugged.php +++ b/Services/COPage/classes/class.ilPCPlugged.php @@ -15,407 +15,385 @@ require_once("./Services/COPage/classes/class.ilPageContent.php"); */ class ilPCPlugged extends ilPageContent { - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilPluginAdmin - */ - protected $plugin_admin; - - var $dom; - var $plug_node; - - /** - * Init page content component. - */ - function init() - { - global $DIC; - - $this->lng = $DIC->language(); - $this->plugin_admin = $DIC["ilPluginAdmin"]; - $this->setType("plug"); - } - - /** - * Set node - */ - function setNode($a_node) - { - parent::setNode($a_node); // this is the PageContent node - $this->plug_node = $a_node->first_child(); // this is the Plugged node - } - - /** - * Create plugged node in xml. - * - * @param object $a_pg_obj Page Object - * @param string $a_hier_id Hierarchical ID - */ - function create($a_pg_obj, $a_hier_id, $a_pc_id, $a_plugin_name, - $a_plugin_version) - { - $this->node = $this->createPageContentNode(); - $a_pg_obj->insertContent($this, $a_hier_id, IL_INSERT_AFTER, $a_pc_id); - $this->plug_node = $this->dom->create_element("Plugged"); - $this->plug_node = $this->node->append_child($this->plug_node); - $this->plug_node->set_attribute("PluginName", $a_plugin_name); - $this->plug_node->set_attribute("PluginVersion", $a_plugin_version); - } - - /** - * Set properties of plugged component. - * - * @param array $a_properties component properties - */ - function setProperties($a_properties) - { - if (!is_object($this->plug_node)) - { - return; - } - - // delete properties - $children = $this->plug_node->child_nodes(); - for($i=0; $iplug_node->remove_child($children[$i]); - } - // set properties - foreach($a_properties as $key => $value) - { - $prop_node = $this->dom->create_element("PluggedProperty"); - $prop_node = $this->plug_node->append_child($prop_node); - $prop_node->set_attribute("Name", $key); - if ($value != "") - { - $prop_node->set_content($value); - } - } - } - - /** - * Get properties of plugged component - * - * @return string characteristic - */ - function getProperties() - { - $properties = array(); - - if (is_object($this->plug_node)) - { - // delete properties - $children = $this->plug_node->child_nodes(); - for($i=0; $inode_name() == "PluggedProperty") - { - $properties[$children[$i]->get_attribute("Name")] = - $children[$i]->get_content(); - } - } - } - - return $properties; - } - - /** - * Set version of plugged component - * - * @param string $a_version version - */ - function setPluginVersion($a_version) - { - if (!empty($a_version)) - { - $this->plug_node->set_attribute("PluginVersion", $a_version); - } - else - { - if ($this->plug_node->has_attribute("PluginVersion")) - { - $this->plug_node->remove_attribute("PluginVersion"); - } - } - } - - /** - * Get version of plugged component - * - * @return string version - */ - function getPluginVersion() - { - if (is_object($this->plug_node)) - { - return $this->plug_node->get_attribute("PluginVersion"); - } - } - - /** - * Set name of plugged component - * - * @param string $a_name name - */ - function setPluginName($a_name) - { - if (!empty($a_name)) - { - $this->plug_node->set_attribute("PluginName", $a_name); - } - else - { - if ($this->plug_node->has_attribute("PluginName")) - { - $this->plug_node->remove_attribute("PluginName"); - } - } - } - - /** - * Get name of plugged component - * - * @return string name - */ - function getPluginName() - { - if (is_object($this->plug_node)) - { - return $this->plug_node->get_attribute("PluginName"); - } - } - - /** - * Handle copied plugged content. This function must, e.g. create copies of - * objects referenced within the content (e.g. question objects) - * - * @param ilPageObject $a_page the current page object - * @param DOMDocument $a_domdoc dom document - */ - static function handleCopiedPluggedContent(ilPageObject $a_page, DOMDocument $a_domdoc) - { - global $DIC; - $ilPluginAdmin = $DIC['ilPluginAdmin']; - - $xpath = new DOMXPath($a_domdoc); - $nodes = $xpath->query("//Plugged"); - - /** @var DOMElement $node */ - foreach($nodes as $node) - { - $plugin_name = $node->getAttribute('PluginName'); - $plugin_version = $node->getAttribute('PluginVersion'); - - if ($ilPluginAdmin->isActive(IL_COMP_SERVICE, "COPage", "pgcp", $plugin_name)) - { - /** @var ilPageComponentPlugin $plugin_obj */ - $plugin_obj = $ilPluginAdmin->getPluginObject(IL_COMP_SERVICE, "COPage", "pgcp", $plugin_name); - $plugin_obj->setPageObj($a_page); - - $properties = array(); - /** @var DOMElement $child */ - foreach($node->childNodes as $child) - { - $properties[$child->getAttribute('Name')] = $child->nodeValue; - } - - // let the plugin copy additional content - // and allow it to modify the saved parameters - $plugin_obj->onClone($properties, $plugin_version); - - foreach($node->childNodes as $child) - { - $node->removeChild($child); - } - foreach ($properties as $name => $value) - { - $child = new DOMElement('PluggedProperty', $value); - $node->appendChild($child); - $child->setAttribute('Name',$name); - } - } - } - } - - /** - * Handle deleted plugged content. This function must, e.g. delete - * objects referenced within the content (e.g. question objects) - * - * @param ilPageObject $a_page the current page object - * @param DOMDocument $a_node dom node - */ - static function handleDeletedPluggedNode(ilPageObject $a_page, DOMNode $a_node) - { - global $DIC; - $ilPluginAdmin = $DIC['ilPluginAdmin']; - - $plugin_name = $a_node->getAttribute('PluginName'); - $plugin_version = $a_node->getAttribute('PluginVersion'); - - if ($ilPluginAdmin->isActive(IL_COMP_SERVICE, "COPage", "pgcp", $plugin_name)) - { - /** @var ilPageComponentPlugin $plugin_obj */ - $plugin_obj = $ilPluginAdmin->getPluginObject(IL_COMP_SERVICE, "COPage", "pgcp", $plugin_name); - $plugin_obj->setPageObj($a_page); - - $properties = array(); - /** @var DOMElement $child */ - foreach($a_node->childNodes as $child) - { - $properties[$child->getAttribute('Name')] = $child->nodeValue; - } - - // let the plugin delete additional content - $plugin_obj->onDelete($properties, $plugin_version); - } - } - - - /** - * Modify page content after xsl - * - * @param string $a_output - * @return string - */ - function modifyPageContentPostXsl($a_html, $a_mode) - { - $lng = $this->lng; - $ilPluginAdmin = $this->plugin_admin; - - $c_pos = 0; - $start = strpos($a_html, "{{{{{Plugged 0) - { - $param = substr($a_html, $start + 5, $end - $start - 5); - $param = str_replace(' xmlns:xhtml="http://www.w3.org/1999/xhtml"', "", $param); - $param = explode("", $param); -//var_dump($param); exit; - $plugin_name = $param[1]; - $plugin_version = $param[2]; - $properties = array(); - - for ($i = 3; $i < count($param); $i+=2) - { - $properties[$param[$i]] = $param[$i+1]; - } - - // get html from plugin - if ($a_mode == "edit") - { - $plugin_html = '
          '.$lng->txt("content_plugin_not_activated")." (".$plugin_name.")
          "; - } - if ($ilPluginAdmin->isActive(IL_COMP_SERVICE, "COPage", "pgcp", $plugin_name)) - { - $plugin_obj = $ilPluginAdmin->getPluginObject(IL_COMP_SERVICE, "COPage", - "pgcp", $plugin_name); - $plugin_obj->setPageObj($this->getPage()); - $gui_obj = $plugin_obj->getUIClassInstance(); - $plugin_html = $gui_obj->getElementHTML($a_mode, $properties, $plugin_version); - } - - $a_html = substr($a_html, 0, $start). - $plugin_html. - substr($a_html, $end + 5); - - if (strlen($a_html) > $start + 5) - { - $start = strpos($a_html, "{{{{{Pluggedplugin_admin; - - $js_files = array(); - - $pl_names = $ilPluginAdmin->getActivePluginsForSlot(IL_COMP_SERVICE, - "COPage", "pgcp"); - foreach ($pl_names as $pl_name) - { - $plugin = $ilPluginAdmin->getPluginObject(IL_COMP_SERVICE, - "COPage", "pgcp", $pl_name); - $plugin->setPageObj($this->getPage()); - $pl_dir = $plugin->getDirectory(); - - $pl_js_files = $plugin->getJavascriptFiles($a_mode); - foreach ($pl_js_files as $pl_js_file) - { - if (!is_int(strpos($pl_js_file, "//"))) - { - $pl_js_file = $pl_dir."/".$pl_js_file; - } - if (!in_array($pl_js_file, $js_files)) - { - $js_files[] = $pl_js_file; - } - } - } -//var_dump($js_files); - return $js_files; - } - - /** - * Get css files - */ - function getCssFiles($a_mode) - { - $ilPluginAdmin = $this->plugin_admin; - - $css_files = array(); - - $pl_names = $ilPluginAdmin->getActivePluginsForSlot(IL_COMP_SERVICE, - "COPage", "pgcp"); - foreach ($pl_names as $pl_name) - { - $plugin = $ilPluginAdmin->getPluginObject(IL_COMP_SERVICE, - "COPage", "pgcp", $pl_name); - $plugin->setPageObj($this->getPage()); - $pl_dir = $plugin->getDirectory(); - - $pl_css_files = $plugin->getCssFiles($a_mode); - foreach ($pl_css_files as $pl_css_file) - { - if (!is_int(strpos($pl_css_file, "//"))) - { - $pl_css_file = $pl_dir."/".$pl_css_file; - } - if (!in_array($pl_css_file, $css_files)) - { - $css_files[] = $pl_css_file; - } - } - } - - return $css_files; - } - + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilPluginAdmin + */ + protected $plugin_admin; + + public $dom; + public $plug_node; + + /** + * Init page content component. + */ + public function init() + { + global $DIC; + + $this->lng = $DIC->language(); + $this->plugin_admin = $DIC["ilPluginAdmin"]; + $this->setType("plug"); + } + + /** + * Set node + */ + public function setNode($a_node) + { + parent::setNode($a_node); // this is the PageContent node + $this->plug_node = $a_node->first_child(); // this is the Plugged node + } + + /** + * Create plugged node in xml. + * + * @param object $a_pg_obj Page Object + * @param string $a_hier_id Hierarchical ID + */ + public function create( + $a_pg_obj, + $a_hier_id, + $a_pc_id, + $a_plugin_name, + $a_plugin_version + ) { + $this->node = $this->createPageContentNode(); + $a_pg_obj->insertContent($this, $a_hier_id, IL_INSERT_AFTER, $a_pc_id); + $this->plug_node = $this->dom->create_element("Plugged"); + $this->plug_node = $this->node->append_child($this->plug_node); + $this->plug_node->set_attribute("PluginName", $a_plugin_name); + $this->plug_node->set_attribute("PluginVersion", $a_plugin_version); + } + + /** + * Set properties of plugged component. + * + * @param array $a_properties component properties + */ + public function setProperties($a_properties) + { + if (!is_object($this->plug_node)) { + return; + } + + // delete properties + $children = $this->plug_node->child_nodes(); + for ($i=0; $iplug_node->remove_child($children[$i]); + } + // set properties + foreach ($a_properties as $key => $value) { + $prop_node = $this->dom->create_element("PluggedProperty"); + $prop_node = $this->plug_node->append_child($prop_node); + $prop_node->set_attribute("Name", $key); + if ($value != "") { + $prop_node->set_content($value); + } + } + } + + /** + * Get properties of plugged component + * + * @return string characteristic + */ + public function getProperties() + { + $properties = array(); + + if (is_object($this->plug_node)) { + // delete properties + $children = $this->plug_node->child_nodes(); + for ($i=0; $inode_name() == "PluggedProperty") { + $properties[$children[$i]->get_attribute("Name")] = + $children[$i]->get_content(); + } + } + } + + return $properties; + } + + /** + * Set version of plugged component + * + * @param string $a_version version + */ + public function setPluginVersion($a_version) + { + if (!empty($a_version)) { + $this->plug_node->set_attribute("PluginVersion", $a_version); + } else { + if ($this->plug_node->has_attribute("PluginVersion")) { + $this->plug_node->remove_attribute("PluginVersion"); + } + } + } + + /** + * Get version of plugged component + * + * @return string version + */ + public function getPluginVersion() + { + if (is_object($this->plug_node)) { + return $this->plug_node->get_attribute("PluginVersion"); + } + } + + /** + * Set name of plugged component + * + * @param string $a_name name + */ + public function setPluginName($a_name) + { + if (!empty($a_name)) { + $this->plug_node->set_attribute("PluginName", $a_name); + } else { + if ($this->plug_node->has_attribute("PluginName")) { + $this->plug_node->remove_attribute("PluginName"); + } + } + } + + /** + * Get name of plugged component + * + * @return string name + */ + public function getPluginName() + { + if (is_object($this->plug_node)) { + return $this->plug_node->get_attribute("PluginName"); + } + } + + /** + * Handle copied plugged content. This function must, e.g. create copies of + * objects referenced within the content (e.g. question objects) + * + * @param ilPageObject $a_page the current page object + * @param DOMDocument $a_domdoc dom document + */ + public static function handleCopiedPluggedContent(ilPageObject $a_page, DOMDocument $a_domdoc) + { + global $DIC; + $ilPluginAdmin = $DIC['ilPluginAdmin']; + + $xpath = new DOMXPath($a_domdoc); + $nodes = $xpath->query("//Plugged"); + + /** @var DOMElement $node */ + foreach ($nodes as $node) { + $plugin_name = $node->getAttribute('PluginName'); + $plugin_version = $node->getAttribute('PluginVersion'); + + if ($ilPluginAdmin->isActive(IL_COMP_SERVICE, "COPage", "pgcp", $plugin_name)) { + /** @var ilPageComponentPlugin $plugin_obj */ + $plugin_obj = $ilPluginAdmin->getPluginObject(IL_COMP_SERVICE, "COPage", "pgcp", $plugin_name); + $plugin_obj->setPageObj($a_page); + + $properties = array(); + /** @var DOMElement $child */ + foreach ($node->childNodes as $child) { + $properties[$child->getAttribute('Name')] = $child->nodeValue; + } + + // let the plugin copy additional content + // and allow it to modify the saved parameters + $plugin_obj->onClone($properties, $plugin_version); + + foreach ($node->childNodes as $child) { + $node->removeChild($child); + } + foreach ($properties as $name => $value) { + $child = new DOMElement('PluggedProperty', $value); + $node->appendChild($child); + $child->setAttribute('Name', $name); + } + } + } + } + + /** + * Handle deleted plugged content. This function must, e.g. delete + * objects referenced within the content (e.g. question objects) + * + * @param ilPageObject $a_page the current page object + * @param DOMDocument $a_node dom node + */ + public static function handleDeletedPluggedNode(ilPageObject $a_page, DOMNode $a_node) + { + global $DIC; + $ilPluginAdmin = $DIC['ilPluginAdmin']; + + $plugin_name = $a_node->getAttribute('PluginName'); + $plugin_version = $a_node->getAttribute('PluginVersion'); + + if ($ilPluginAdmin->isActive(IL_COMP_SERVICE, "COPage", "pgcp", $plugin_name)) { + /** @var ilPageComponentPlugin $plugin_obj */ + $plugin_obj = $ilPluginAdmin->getPluginObject(IL_COMP_SERVICE, "COPage", "pgcp", $plugin_name); + $plugin_obj->setPageObj($a_page); + + $properties = array(); + /** @var DOMElement $child */ + foreach ($a_node->childNodes as $child) { + $properties[$child->getAttribute('Name')] = $child->nodeValue; + } + + // let the plugin delete additional content + $plugin_obj->onDelete($properties, $plugin_version); + } + } + + + /** + * Modify page content after xsl + * + * @param string $a_output + * @return string + */ + public function modifyPageContentPostXsl($a_html, $a_mode) + { + $lng = $this->lng; + $ilPluginAdmin = $this->plugin_admin; + + $c_pos = 0; + $start = strpos($a_html, "{{{{{Plugged 0) { + $param = substr($a_html, $start + 5, $end - $start - 5); + $param = str_replace(' xmlns:xhtml="http://www.w3.org/1999/xhtml"', "", $param); + $param = explode("", $param); + //var_dump($param); exit; + $plugin_name = $param[1]; + $plugin_version = $param[2]; + $properties = array(); + + for ($i = 3; $i < count($param); $i+=2) { + $properties[$param[$i]] = $param[$i+1]; + } + + // get html from plugin + if ($a_mode == "edit") { + $plugin_html = '
          ' . $lng->txt("content_plugin_not_activated") . " (" . $plugin_name . ")
          "; + } + if ($ilPluginAdmin->isActive(IL_COMP_SERVICE, "COPage", "pgcp", $plugin_name)) { + $plugin_obj = $ilPluginAdmin->getPluginObject( + IL_COMP_SERVICE, + "COPage", + "pgcp", + $plugin_name + ); + $plugin_obj->setPageObj($this->getPage()); + $gui_obj = $plugin_obj->getUIClassInstance(); + $plugin_html = $gui_obj->getElementHTML($a_mode, $properties, $plugin_version); + } + + $a_html = substr($a_html, 0, $start) . + $plugin_html . + substr($a_html, $end + 5); + + if (strlen($a_html) > $start + 5) { + $start = strpos($a_html, "{{{{{Pluggedplugin_admin; + + $js_files = array(); + + $pl_names = $ilPluginAdmin->getActivePluginsForSlot( + IL_COMP_SERVICE, + "COPage", + "pgcp" + ); + foreach ($pl_names as $pl_name) { + $plugin = $ilPluginAdmin->getPluginObject( + IL_COMP_SERVICE, + "COPage", + "pgcp", + $pl_name + ); + $plugin->setPageObj($this->getPage()); + $pl_dir = $plugin->getDirectory(); + + $pl_js_files = $plugin->getJavascriptFiles($a_mode); + foreach ($pl_js_files as $pl_js_file) { + if (!is_int(strpos($pl_js_file, "//"))) { + $pl_js_file = $pl_dir . "/" . $pl_js_file; + } + if (!in_array($pl_js_file, $js_files)) { + $js_files[] = $pl_js_file; + } + } + } + //var_dump($js_files); + return $js_files; + } + + /** + * Get css files + */ + public function getCssFiles($a_mode) + { + $ilPluginAdmin = $this->plugin_admin; + + $css_files = array(); + + $pl_names = $ilPluginAdmin->getActivePluginsForSlot( + IL_COMP_SERVICE, + "COPage", + "pgcp" + ); + foreach ($pl_names as $pl_name) { + $plugin = $ilPluginAdmin->getPluginObject( + IL_COMP_SERVICE, + "COPage", + "pgcp", + $pl_name + ); + $plugin->setPageObj($this->getPage()); + $pl_dir = $plugin->getDirectory(); + + $pl_css_files = $plugin->getCssFiles($a_mode); + foreach ($pl_css_files as $pl_css_file) { + if (!is_int(strpos($pl_css_file, "//"))) { + $pl_css_file = $pl_dir . "/" . $pl_css_file; + } + if (!in_array($pl_css_file, $css_files)) { + $css_files[] = $pl_css_file; + } + } + } + + return $css_files; + } } - -?> diff --git a/Services/COPage/classes/class.ilPCPluggedGUI.php b/Services/COPage/classes/class.ilPCPluggedGUI.php index 4a8a5bc3e702938802bd42991e79413a32bbd8e2..cd97528a2224b1307afc130caf94dbe142a3cfb2 100755 --- a/Services/COPage/classes/class.ilPCPluggedGUI.php +++ b/Services/COPage/classes/class.ilPCPluggedGUI.php @@ -18,191 +18,193 @@ require_once("./Services/COPage/classes/class.ilPageContentGUI.php"); */ class ilPCPluggedGUI extends ilPageContentGUI { - /** - * @var ilPluginAdmin - */ - protected $plugin_admin; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - protected $current_plugin = null; - - /** - * Constructor - * @access public - */ - function __construct(&$a_pg_obj, &$a_content_obj, $a_hier_id, $a_plugin_name = "", $a_pc_id = "") - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->plugin_admin = $DIC["ilPluginAdmin"]; - $this->tabs = $DIC->tabs(); - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - - $this->setPluginName($a_plugin_name); - parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); - } - - /** - * Set PluginName. - * - * @param string $a_pluginname PluginName - */ - function setPluginName($a_pluginname) - { - $this->pluginname = $a_pluginname; - } - - /** - * Get PluginName. - * - * @return string PluginName - */ - function getPluginName() - { - return $this->pluginname; - } - - /** - * execute command - */ - function executeCommand() - { - $ilPluginAdmin = $this->plugin_admin; - $ilTabs = $this->tabs; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $ilTabs->setBackTarget($lng->txt("pg"), $ilCtrl->getLinkTarget($this, "returnToParent")); - - // get next class that processes or forwards current command - $next_class = $this->ctrl->getNextClass($this); - - // get all plugins and check, whether next class belongs to one - // of them, then forward - $pl_names = $ilPluginAdmin->getActivePluginsForSlot(IL_COMP_SERVICE, - "COPage", "pgcp"); - foreach ($pl_names as $pl_name) - { - if ($next_class == strtolower("il".$pl_name."plugingui")) - { - $plugin = $ilPluginAdmin->getPluginObject(IL_COMP_SERVICE, - "COPage", "pgcp", $pl_name); - $plugin->setPageObj($this->getPage()); - $this->current_plugin = $plugin; - $this->setPluginName($pl_name); - $gui_obj = $plugin->getUIClassInstance(); - $gui_obj->setPCGUI($this); - $ret = $this->ctrl->forwardCommand($gui_obj); - } - } - - // get current command - $cmd = $this->ctrl->getCmd(); - - if ($next_class == "" || $next_class == "ilpcpluggedgui") - { - $ret = $this->$cmd(); - } - - return $ret; - } - - /** - * Insert new section form. - */ - function insert() - { - $this->edit(true); - } - - /** - * Edit section form. - */ - function edit($a_insert = false) - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - $ilPluginAdmin = $this->plugin_admin; - - $this->displayValidationError(); - - // edit form - if ($a_insert) - { - $plugin_name = $this->getPluginName(); - } - else - { - $plugin_name = $this->content_obj->getPluginName(); - } - if ($ilPluginAdmin->isActive(IL_COMP_SERVICE, "COPage", "pgcp", $plugin_name)) - { - $plugin_obj = $ilPluginAdmin->getPluginObject(IL_COMP_SERVICE, "COPage", - "pgcp", $plugin_name); - $plugin_obj->setPageObj($this->getPage()); - $gui_obj = $plugin_obj->getUIClassInstance(); - $gui_obj->setPCGUI($this); - if ($a_insert) - { - $gui_obj->setMode(ilPageComponentPlugin::CMD_INSERT); - } - else - { - $gui_obj->setMode(ilPageComponentPlugin::CMD_EDIT); - } - $html = $ilCtrl->getHTML($gui_obj); + /** + * @var ilPluginAdmin + */ + protected $plugin_admin; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + protected $current_plugin = null; + + /** + * Constructor + * @access public + */ + public function __construct(&$a_pg_obj, &$a_content_obj, $a_hier_id, $a_plugin_name = "", $a_pc_id = "") + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->plugin_admin = $DIC["ilPluginAdmin"]; + $this->tabs = $DIC->tabs(); + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + + $this->setPluginName($a_plugin_name); + parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); + } + + /** + * Set PluginName. + * + * @param string $a_pluginname PluginName + */ + public function setPluginName($a_pluginname) + { + $this->pluginname = $a_pluginname; + } + + /** + * Get PluginName. + * + * @return string PluginName + */ + public function getPluginName() + { + return $this->pluginname; + } + + /** + * execute command + */ + public function executeCommand() + { + $ilPluginAdmin = $this->plugin_admin; + $ilTabs = $this->tabs; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $ilTabs->setBackTarget($lng->txt("pg"), $ilCtrl->getLinkTarget($this, "returnToParent")); + + // get next class that processes or forwards current command + $next_class = $this->ctrl->getNextClass($this); + + // get all plugins and check, whether next class belongs to one + // of them, then forward + $pl_names = $ilPluginAdmin->getActivePluginsForSlot( + IL_COMP_SERVICE, + "COPage", + "pgcp" + ); + foreach ($pl_names as $pl_name) { + if ($next_class == strtolower("il" . $pl_name . "plugingui")) { + $plugin = $ilPluginAdmin->getPluginObject( + IL_COMP_SERVICE, + "COPage", + "pgcp", + $pl_name + ); + $plugin->setPageObj($this->getPage()); + $this->current_plugin = $plugin; + $this->setPluginName($pl_name); + $gui_obj = $plugin->getUIClassInstance(); + $gui_obj->setPCGUI($this); + $ret = $this->ctrl->forwardCommand($gui_obj); + } } - - $tpl->setContent($html); - } - - - /** - * Create new element - */ - function createElement(array $a_properties) - { - $this->content_obj = new ilPCPlugged($this->getPage()); - $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id, - $this->current_plugin->getPluginName(), $this->current_plugin->getVersion()); - $this->content_obj->setProperties($a_properties); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - return true; - } - return false; - } - - /** - * Update element - */ - function updateElement(array $a_properties) - { - $this->content_obj->setProperties($a_properties); - $this->content_obj->setPluginVersion($this->current_plugin->getVersion()); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - return true; - } - return false; - } - - /** - * Return to parent - */ - function returnToParent() - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - + + // get current command + $cmd = $this->ctrl->getCmd(); + + if ($next_class == "" || $next_class == "ilpcpluggedgui") { + $ret = $this->$cmd(); + } + + return $ret; + } + + /** + * Insert new section form. + */ + public function insert() + { + $this->edit(true); + } + + /** + * Edit section form. + */ + public function edit($a_insert = false) + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + $ilPluginAdmin = $this->plugin_admin; + + $this->displayValidationError(); + + // edit form + if ($a_insert) { + $plugin_name = $this->getPluginName(); + } else { + $plugin_name = $this->content_obj->getPluginName(); + } + if ($ilPluginAdmin->isActive(IL_COMP_SERVICE, "COPage", "pgcp", $plugin_name)) { + $plugin_obj = $ilPluginAdmin->getPluginObject( + IL_COMP_SERVICE, + "COPage", + "pgcp", + $plugin_name + ); + $plugin_obj->setPageObj($this->getPage()); + $gui_obj = $plugin_obj->getUIClassInstance(); + $gui_obj->setPCGUI($this); + if ($a_insert) { + $gui_obj->setMode(ilPageComponentPlugin::CMD_INSERT); + } else { + $gui_obj->setMode(ilPageComponentPlugin::CMD_EDIT); + } + $html = $ilCtrl->getHTML($gui_obj); + } + + $tpl->setContent($html); + } + + + /** + * Create new element + */ + public function createElement(array $a_properties) + { + $this->content_obj = new ilPCPlugged($this->getPage()); + $this->content_obj->create( + $this->pg_obj, + $this->hier_id, + $this->pc_id, + $this->current_plugin->getPluginName(), + $this->current_plugin->getVersion() + ); + $this->content_obj->setProperties($a_properties); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + return true; + } + return false; + } + + /** + * Update element + */ + public function updateElement(array $a_properties) + { + $this->content_obj->setProperties($a_properties); + $this->content_obj->setPluginVersion($this->current_plugin->getVersion()); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + return true; + } + return false; + } + + /** + * Return to parent + */ + public function returnToParent() + { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } } -?> diff --git a/Services/COPage/classes/class.ilPCProfile.php b/Services/COPage/classes/class.ilPCProfile.php index 6fb86ee67ba7a65b99b4339b85ec79689cf19042..1f6b19e57edf91a328e7d5c02ee634633e31ee07 100644 --- a/Services/COPage/classes/class.ilPCProfile.php +++ b/Services/COPage/classes/class.ilPCProfile.php @@ -1,140 +1,130 @@ - -* @version $Id: class.ilPCListItem.php 22210 2009-10-26 09:46:06Z akill $ -* -* @ingroup ServicesCOPage -*/ -class ilPCProfile extends ilPageContent -{ - /** - * @var ilObjUser - */ - protected $user; - - var $dom; - - /** - * Init page content component. - */ - function init() - { - global $DIC; - - $this->user = $DIC->user(); - $this->setType("prof"); - } - - /** - * Set node - */ - function setNode($a_node) - { - parent::setNode($a_node); // this is the PageContent node - $this->prof_node = $a_node->first_child(); // this is the profile node - } - - /** - * Create profile node in xml. - * - * @param object $a_pg_obj Page Object - * @param string $a_hier_id Hierarchical ID - */ - 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->prof_node = $this->dom->create_element("Profile"); - $this->prof_node = $this->node->append_child($this->prof_node); - } - - /** - * Set profile settings - * - * @param string $a_mode - * @param array $a_fields - */ - function setFields($a_mode, array $a_fields = null) - { - $ilUser = $this->user; - - $this->prof_node->set_attribute("Mode", $a_mode); - $this->prof_node->set_attribute("User", $ilUser->getId()); - - // remove all children first - $children = $this->prof_node->child_nodes(); - if($children) - { - foreach($children as $child) - { - $this->prof_node->remove_child($child); - } - } - - if($a_mode == "manual") - { - foreach($a_fields as $field) - { - $field_node = $this->dom->create_element("ProfileField"); - $field_node = $this->prof_node->append_child($field_node); - $field_node->set_attribute("Name", $field); - } - } - } - - /** - * Get profile mode - * - * @return string - */ - function getMode() - { - if (is_object($this->prof_node)) - { - return $this->prof_node->get_attribute("Mode"); - } - } - - /** - * Get profile settings - * - * @return array - */ - function getFields() - { - $res = array(); - if (is_object($this->prof_node)) - { - $children = $this->prof_node->child_nodes(); - if($children) - { - foreach($children as $child) - { - $res[] = $child->get_attribute("Name"); - } - } - } - return $res; - } - - /** - * Get lang vars needed for editing - * @return array array of lang var keys - */ - static function getLangVars() - { - return array("pc_prof", "ed_insert_profile"); - } - -} -?> + +* @version $Id: class.ilPCListItem.php 22210 2009-10-26 09:46:06Z akill $ +* +* @ingroup ServicesCOPage +*/ +class ilPCProfile extends ilPageContent +{ + /** + * @var ilObjUser + */ + protected $user; + + public $dom; + + /** + * Init page content component. + */ + public function init() + { + global $DIC; + + $this->user = $DIC->user(); + $this->setType("prof"); + } + + /** + * Set node + */ + public function setNode($a_node) + { + parent::setNode($a_node); // this is the PageContent node + $this->prof_node = $a_node->first_child(); // this is the profile node + } + + /** + * Create profile node in xml. + * + * @param object $a_pg_obj Page Object + * @param string $a_hier_id Hierarchical ID + */ + public 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->prof_node = $this->dom->create_element("Profile"); + $this->prof_node = $this->node->append_child($this->prof_node); + } + + /** + * Set profile settings + * + * @param string $a_mode + * @param array $a_fields + */ + public function setFields($a_mode, array $a_fields = null) + { + $ilUser = $this->user; + + $this->prof_node->set_attribute("Mode", $a_mode); + $this->prof_node->set_attribute("User", $ilUser->getId()); + + // remove all children first + $children = $this->prof_node->child_nodes(); + if ($children) { + foreach ($children as $child) { + $this->prof_node->remove_child($child); + } + } + + if ($a_mode == "manual") { + foreach ($a_fields as $field) { + $field_node = $this->dom->create_element("ProfileField"); + $field_node = $this->prof_node->append_child($field_node); + $field_node->set_attribute("Name", $field); + } + } + } + + /** + * Get profile mode + * + * @return string + */ + public function getMode() + { + if (is_object($this->prof_node)) { + return $this->prof_node->get_attribute("Mode"); + } + } + + /** + * Get profile settings + * + * @return array + */ + public function getFields() + { + $res = array(); + if (is_object($this->prof_node)) { + $children = $this->prof_node->child_nodes(); + if ($children) { + foreach ($children as $child) { + $res[] = $child->get_attribute("Name"); + } + } + } + return $res; + } + + /** + * Get lang vars needed for editing + * @return array array of lang var keys + */ + public static function getLangVars() + { + return array("pc_prof", "ed_insert_profile"); + } +} diff --git a/Services/COPage/classes/class.ilPCProfileGUI.php b/Services/COPage/classes/class.ilPCProfileGUI.php index 0ed04539f170758ccb73c8d006b5c81889df4fe9..218695ee94babee2eb8815677472393a77f881c4 100644 --- a/Services/COPage/classes/class.ilPCProfileGUI.php +++ b/Services/COPage/classes/class.ilPCProfileGUI.php @@ -1,270 +1,248 @@ - -* @version $I$ -* -* @ingroup ServicesCOPage -*/ -class ilPCProfileGUI extends ilPageContentGUI -{ - /** - * @var ilToolbarGUI - */ - protected $toolbar; +tpl = $DIC["tpl"]; - $this->ctrl = $DIC->ctrl(); - $this->toolbar = $DIC->toolbar(); - 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 personal data form. - * - * @param ilPropertyFormGUI $a_form - */ - function insert(ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - - $this->displayValidationError(); - - if(!$a_form) - { - $a_form = $this->initForm(true); - } - $tpl->setContent($a_form->getHTML()); - } - - /** - * Edit personal data form. - * - * @param ilPropertyFormGUI $a_form - */ - function edit(ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - - $this->displayValidationError(); - - if(!$a_form) - { - $a_form = $this->initForm(); - } - $tpl->setContent($a_form->getHTML()); - } - - /** - * Init profile form - * - * @param bool $a_insert - * @return ilPropertyFormGUI - */ - protected function initForm($a_insert = false) - { - $ilCtrl = $this->ctrl; - $ilToolbar = $this->toolbar; - - $is_template = ($this->getPageConfig()->getEnablePCType("PlaceHolder")); - - if(!$is_template) - { - $ilToolbar->addButton($this->lng->txt("cont_edit_personal_data"), - $ilCtrl->getLinkTargetByClass("ilpersonaldesktopgui", "jumptoprofile"), - "profile"); - - $lng_suffix = ""; - } - else - { - $lng_suffix = "_template"; - } - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this)); - if ($a_insert) - { - $form->setTitle($this->lng->txt("cont_insert_profile")); - } - else - { - $form->setTitle($this->lng->txt("cont_update_profile")); - } - - $mode = new ilRadioGroupInputGUI($this->lng->txt("cont_profile_mode"), "mode"); - $form->addItem($mode); - - $mode_inherit = new ilRadioOption($this->lng->txt("cont_profile_mode_inherit"), "inherit"); - $mode_inherit->setInfo($this->lng->txt("cont_profile_mode".$lng_suffix."_inherit_info")); - $mode->addOption($mode_inherit); - - $mode_manual = new ilRadioOption($this->lng->txt("cont_profile_mode_manual"), "manual"); - $mode_manual->setInfo($this->lng->txt("cont_profile_mode_manual_info")); - $mode->addOption($mode_manual); - - $prefs = array(); - if ($a_insert) - { - $mode->setValue("inherit"); - } - else - { - $mode_value = $this->content_obj->getMode(); - $mode->setValue($mode_value); - - $prefs = array(); - if($mode_value == "manual") - { - foreach($this->content_obj->getFields() as $name) - { - $prefs["public_".$name] = "y"; - } - } - } - - include_once "Services/User/classes/class.ilPersonalProfileGUI.php"; - $profile = new ilPersonalProfileGUI(); - $profile->showPublicProfileFields($form, $prefs, $mode_manual, $is_template); - - if ($a_insert) - { - - $form->addCommandButton("create_profile", $this->lng->txt("save")); - $form->addCommandButton("cancelCreate", $this->lng->txt("cancel")); - } - else - { - - $form->addCommandButton("update", $this->lng->txt("save")); - $form->addCommandButton("cancelUpdate", $this->lng->txt("cancel")); - } - - return $form; - } - - /** - * Gather field values - * - * @return array - */ - protected function getFieldsValues() - { - $fields = array(); - foreach($_POST as $name => $value) - { - if(substr($name, 0, 4) == "chk_") - { - if($value) - { - $fields[] = substr($name, 4); - } - } - } - return $fields; - } - - /** - * Create new personal data. - */ - function create() - { - $form = $this->initForm(true); - if($form->checkInput()) - { - $this->content_obj = new ilPCProfile($this->getPage()); - $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); - $this->content_obj->setFields($form->getInput("mode"), - $this->getFieldsValues()); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - } - - $this->insert($form); - } - - /** - * Update personal data. - */ - function update() - { - $form = $this->initForm(true); - if($form->checkInput()) - { - $this->content_obj->setFields($form->getInput("mode"), - $this->getFieldsValues()); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - } - - $this->pg_obj->addHierIDs(); - $this->edit($form); - } -} - -?> \ No newline at end of file +/** +* Class ilPCProfileGUI +* +* Handles user commands on personal data +* +* @author Jörg Lützenkirchen +* @version $I$ +* +* @ingroup ServicesCOPage +*/ +class ilPCProfileGUI extends ilPageContentGUI +{ + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + + /** + * Constructor + * @access public + */ + 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->toolbar = $DIC->toolbar(); + 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 personal data form. + * + * @param ilPropertyFormGUI $a_form + */ + public function insert(ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + + $this->displayValidationError(); + + if (!$a_form) { + $a_form = $this->initForm(true); + } + $tpl->setContent($a_form->getHTML()); + } + + /** + * Edit personal data form. + * + * @param ilPropertyFormGUI $a_form + */ + public function edit(ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + + $this->displayValidationError(); + + if (!$a_form) { + $a_form = $this->initForm(); + } + $tpl->setContent($a_form->getHTML()); + } + + /** + * Init profile form + * + * @param bool $a_insert + * @return ilPropertyFormGUI + */ + protected function initForm($a_insert = false) + { + $ilCtrl = $this->ctrl; + $ilToolbar = $this->toolbar; + + $is_template = ($this->getPageConfig()->getEnablePCType("PlaceHolder")); + + if (!$is_template) { + $ilToolbar->addButton( + $this->lng->txt("cont_edit_personal_data"), + $ilCtrl->getLinkTargetByClass("ilpersonaldesktopgui", "jumptoprofile"), + "profile" + ); + + $lng_suffix = ""; + } else { + $lng_suffix = "_template"; + } + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this)); + if ($a_insert) { + $form->setTitle($this->lng->txt("cont_insert_profile")); + } else { + $form->setTitle($this->lng->txt("cont_update_profile")); + } + + $mode = new ilRadioGroupInputGUI($this->lng->txt("cont_profile_mode"), "mode"); + $form->addItem($mode); + + $mode_inherit = new ilRadioOption($this->lng->txt("cont_profile_mode_inherit"), "inherit"); + $mode_inherit->setInfo($this->lng->txt("cont_profile_mode" . $lng_suffix . "_inherit_info")); + $mode->addOption($mode_inherit); + + $mode_manual = new ilRadioOption($this->lng->txt("cont_profile_mode_manual"), "manual"); + $mode_manual->setInfo($this->lng->txt("cont_profile_mode_manual_info")); + $mode->addOption($mode_manual); + + $prefs = array(); + if ($a_insert) { + $mode->setValue("inherit"); + } else { + $mode_value = $this->content_obj->getMode(); + $mode->setValue($mode_value); + + $prefs = array(); + if ($mode_value == "manual") { + foreach ($this->content_obj->getFields() as $name) { + $prefs["public_" . $name] = "y"; + } + } + } + + include_once "Services/User/classes/class.ilPersonalProfileGUI.php"; + $profile = new ilPersonalProfileGUI(); + $profile->showPublicProfileFields($form, $prefs, $mode_manual, $is_template); + + if ($a_insert) { + $form->addCommandButton("create_profile", $this->lng->txt("save")); + $form->addCommandButton("cancelCreate", $this->lng->txt("cancel")); + } else { + $form->addCommandButton("update", $this->lng->txt("save")); + $form->addCommandButton("cancelUpdate", $this->lng->txt("cancel")); + } + + return $form; + } + + /** + * Gather field values + * + * @return array + */ + protected function getFieldsValues() + { + $fields = array(); + foreach ($_POST as $name => $value) { + if (substr($name, 0, 4) == "chk_") { + if ($value) { + $fields[] = substr($name, 4); + } + } + } + return $fields; + } + + /** + * Create new personal data. + */ + public function create() + { + $form = $this->initForm(true); + if ($form->checkInput()) { + $this->content_obj = new ilPCProfile($this->getPage()); + $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); + $this->content_obj->setFields( + $form->getInput("mode"), + $this->getFieldsValues() + ); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + } + + $this->insert($form); + } + + /** + * Update personal data. + */ + public function update() + { + $form = $this->initForm(true); + if ($form->checkInput()) { + $this->content_obj->setFields( + $form->getInput("mode"), + $this->getFieldsValues() + ); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + } + + $this->pg_obj->addHierIDs(); + $this->edit($form); + } +} diff --git a/Services/COPage/classes/class.ilPCQuestion.php b/Services/COPage/classes/class.ilPCQuestion.php index 40cf6ad0e9baf627737f9aa5681d668646bf89c1..b7960a6304b450c3717169ac820d6c54aff41f34 100755 --- a/Services/COPage/classes/class.ilPCQuestion.php +++ b/Services/COPage/classes/class.ilPCQuestion.php @@ -17,519 +17,490 @@ require_once("./Services/COPage/classes/class.ilPageContent.php"); */ class ilPCQuestion extends ilPageContent { - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilObjUser - */ - protected $user; - - var $dom; - var $q_node; // node of Paragraph element - - protected static $initial_done; // [bool] - - /** - * Init page content component. - */ - function init() - { - global $DIC; - - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $this->user = $DIC->user(); - $this->setType("pcqst"); - } - - /** - * Set node - */ - function setNode($a_node) - { - parent::setNode($a_node); // this is the PageContent node - $this->q_node = $a_node->first_child(); //... and this the Question - } - - /** - * Set Question Reference. - * - * @param string $a_questionreference Question Reference - */ - function setQuestionReference($a_questionreference) - { - if (is_object($this->q_node)) - { - $this->q_node->set_attribute("QRef", $a_questionreference); - } - } - - /** - * Get Question Reference. - * - * @return string Question Reference - */ - function getQuestionReference() - { - if (is_object($this->q_node)) - { - return $this->q_node->get_attribute("QRef", $a_questionreference); - } - return false; - } - - /** - * Create Question Element - */ - function create(&$a_pg_obj, $a_hier_id) - { - $this->createPageContentNode(); - $a_pg_obj->insertContent($this, $a_hier_id, IL_INSERT_AFTER); - $this->q_node = $this->dom->create_element("Question"); - $this->q_node = $this->node->append_child($this->q_node); - $this->q_node->set_attribute("QRef", ""); - } - - /** - * Copy question from pool into page - * - * @param - * @return - */ - function copyPoolQuestionIntoPage($a_q_id, $a_hier_id) - { - include_once "./Modules/TestQuestionPool/classes/class.assQuestion.php"; - include_once "./Modules/TestQuestionPool/classes/class.assQuestionGUI.php"; - $question = assQuestion::_instanciateQuestion($a_q_id); - $duplicate_id = $question->copyObject(0, $question->getTitle()); - $duplicate = assQuestion::_instanciateQuestion($duplicate_id); - $duplicate->setObjId(0); - - /* PATCH-BEGIN: moved cleanup code to central place ilAssSelfAssessmentQuestionFormatter */ - /* - // we remove everything not supported by the non-tiny self - // assessment question editor - $q = $duplicate->getQuestion(); - - // we try to save all latex tags - $try = true; - $ls = ''; - $le = ''; - while ($try) - { - // search position of start tag - $pos1 = strpos($q, $ls); - if (is_int($pos1)) - { - $pos2 = strpos($q, $le, $pos1); - if (is_int($pos2)) - { - // both found: replace end tag - $q = substr($q, 0, $pos2)."[/tex]".substr($q, $pos2+7); - $q = substr($q, 0, $pos1)."[tex]".substr($q, $pos1+20); - } - else - { - $try = false; - } - } - else - { - $try = false; - } - } - - $tags = assQuestionGUI::getSelfAssessmentTags(); - $tstr = ""; - foreach ($tags as $t) - { - $tstr.="<".$t.">"; - } - $q = ilUtil::secureString($q, true, $tstr); - // self assessment uses nl2br, not p - $duplicate->setQuestion($q); - - $duplicate->saveQuestionDataToDb(); - */ - - require_once 'Modules/TestQuestionPool/classes/questions/class.ilAssSelfAssessmentQuestionFormatter.php'; - ilAssSelfAssessmentQuestionFormatter::prepareQuestionForLearningModule($duplicate); - - /* PATCH-END: moved cleanup code to central place ilAssSelfAssessmentQuestionFormatter */ - - $this->q_node->set_attribute("QRef", "il__qst_".$duplicate_id); - } - - /** - * Get lang vars needed for editing - * @return array array of lang var keys - */ - static function getLangVars() - { - return array("ed_insert_pcqst", "empty_question", "pc_qst"); - } - - /** - * After page has been updated (or created) - * - * @param object page object - * @param DOMDocument $a_domdoc dom document - * @param string xml - * @param bool true on creation, otherwise false - */ - static function afterPageUpdate($a_page, DOMDocument $a_domdoc, $a_xml, $a_creation) - { - global $DIC; - - $ilDB = $DIC->database(); - - include_once("./Services/Link/classes/class.ilInternalLink.php"); - - $ilDB->manipulateF("DELETE FROM page_question WHERE page_parent_type = %s ". - " AND page_id = %s AND page_lang = %s", array("text", "integer", "text"), - array($a_page->getParentType(), $a_page->getId(), $a_page->getLanguage())); - - $xpath = new DOMXPath($a_domdoc); - $nodes = $xpath->query('//Question'); - $q_ids = array(); - foreach ($nodes as $node) - { - $q_ref = $node->getAttribute("QRef"); - - $inst_id = ilInternalLink::_extractInstOfTarget($q_ref); - if (!($inst_id > 0)) - { - $q_id = ilInternalLink::_extractObjIdOfTarget($q_ref); - if ($q_id > 0) - { - $q_ids[$q_id] = $q_id; - } - } - } - foreach($q_ids as $qid) - { - $ilDB->manipulateF("INSERT INTO page_question (page_parent_type, page_id, page_lang, question_id)". - " VALUES (%s,%s,%s,%s)", - array("text", "integer", "text", "integer"), - array($a_page->getParentType(), $a_page->getId(), $a_page->getLanguage(), $qid)); - } - - } - - /** - * Before page is being deleted - * - * @param object page object - */ - static function beforePageDelete($a_page) - { - global $DIC; - - $ilDB = $DIC->database(); - - $ilDB->manipulateF("DELETE FROM page_question WHERE page_parent_type = %s ". - " AND page_id = %s AND page_lang = %s", array("text", "integer", "text"), - array($a_page->getParentType(), $a_page->getId(), $a_page->getLanguage())); - } - - /** - * Get all questions of a page - */ - static function _getQuestionIdsForPage($a_parent_type, $a_page_id, $a_lang = "-") - { - global $DIC; - - $ilDB = $DIC->database(); - - $res = $ilDB->queryF("SELECT * FROM page_question WHERE page_parent_type = %s ". - " AND page_id = %s AND page_lang = %s", - array("text", "integer", "text"), - array($a_parent_type, $a_page_id, $a_lang)); - $q_ids = array(); - while ($rec = $ilDB->fetchAssoc($res)) - { - $q_ids[] = $rec["question_id"]; - } - - return $q_ids; - } - - /** - * Get page for question id - * - * @param - * @return array - */ - static function _getPageForQuestionId($a_q_id, $a_parent_type = "") - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT * FROM page_question ". - " WHERE question_id = ".$ilDB->quote($a_q_id, "integer") - ); - while ($rec = $ilDB->fetchAssoc($set)) - { - if ($a_parent_type == "" || $rec["page_parent_type"] == $a_parent_type) - { - return array("page_id" => $rec["page_id"], "parent_type" => $rec["page_parent_type"]); - } - } - return false; - } - - /** - * Modify page content after xsl - * - * @param string $a_output - * @return string - */ - function modifyPageContentPostXsl($a_output, $a_mode) - { - $lng = $this->lng; - - $qhtml = ""; - - if ($this->getPage()->getPageConfig()->getEnableSelfAssessment()) - { - // #14154 - $q_ids = $this->getPage()->getQuestionIds(); - if(sizeof($q_ids)) - { - include_once "./Modules/TestQuestionPool/classes/class.assQuestionGUI.php"; - foreach($q_ids as $q_id) - { - $q_gui = assQuestionGUI::_getQuestionGUI("", $q_id); - // object check due to #16557 - if(is_object($q_gui->object) && !$q_gui->object->isComplete()) - { - $a_output = str_replace("{{{{{Question;il__qst_".$q_id."}}}}}", - "".$lng->txt("cont_empty_question")."", - $a_output); - } - } - - // this exports the questions which is needed below - $qhtml = $this->getQuestionJsOfPage(($a_mode == "edit") ? true : false, $a_mode); - - require_once './Modules/Scorm2004/classes/class.ilQuestionExporter.php'; - $a_output = "".$a_output; - if(!self::$initial_done) - { - $a_output = "".$a_output; - self::$initial_done = true; - } - } - } - else - { - // set by T&A components - $qhtml = $this->getPage()->getPageConfig()->getQuestionHTML(); - - // address #19788 - if (!is_array($qhtml) || count($qhtml) == 0) - { - // #14154 - $q_ids = $this->getPage()->getQuestionIds(); - if(sizeof($q_ids)) - { - foreach ($q_ids as $k) - { - $a_output = str_replace("{{{{{Question;il__qst_$k"."}}}}}", " ".$lng->txt("copg_questions_not_supported_here"), $a_output); - } - } - } - } - - if (is_array($qhtml)) - { - foreach ($qhtml as $k => $h) - { - $a_output = str_replace("{{{{{Question;il__qst_$k"."}}}}}", " ".$h, $a_output); - } - } - - return $a_output; - } - - /** - * Reset initial state (for exports) - */ - static function resetInitialState() - { - self::$initial_done = false; - } - - /** - * Get Javascript files - */ - function getJavascriptFiles($a_mode) - { - $js_files = array(); - - if ($this->getPage()->getPageConfig()->getEnableSelfAssessment()) - { - $js_files[] = "./Modules/Scorm2004/scripts/questions/pure.js"; - $js_files[] = "./Modules/Scorm2004/scripts/questions/question_handling.js"; - $js_files[] = "Modules/TestQuestionPool/js/ilMatchingQuestion.js"; - $js_files[] = "Modules/TestQuestionPool/js/ilMultipleChoiceQuestion.js"; - - global $DIC; - if( $DIC['ilBrowser']->isMobile() || $DIC['ilBrowser']->isIpad() ) - { - $js_files[] = 'libs/bower/bower_components/jqueryui-touch-punch/jquery.ui.touch-punch.min.js'; - } - - } - - if (!$this->getPage()->getPageConfig()->getEnableSelfAssessmentScorm() && $a_mode != IL_PAGE_PREVIEW - && $a_mode != "offline") - { - $js_files[] = "./Services/COPage/js/ilCOPageQuestionHandler.js"; - } - - return $js_files; - } - - /** - * Get css files - */ - function getCssFiles($a_mode) - { - if ($this->getPage()->getPageConfig()->getEnableSelfAssessment()) - { - return array("./Modules/Scorm2004/templates/default/question_handling.css", - "Modules/TestQuestionPool/templates/default/test_javascript.css"); - } - return array(); - } - - /** - * Get on load code - */ - function getOnloadCode($a_mode) - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - $code = array(); - - if ($this->getPage()->getPageConfig()->getEnableSelfAssessment()) - { - if (!$this->getPage()->getPageConfig()->getEnableSelfAssessmentScorm() && $a_mode != IL_PAGE_PREVIEW - && $a_mode != "offline") - { - $ilCtrl->setParameterByClass(strtolower(get_class($this->getPage()))."gui", "page_id", $this->getPage()->getId()); - $url = $ilCtrl->getLinkTargetByClass(strtolower(get_class($this->getPage()))."gui", "processAnswer", "", true, false); - $code[] = "ilCOPageQuestionHandler.initCallback('".$url."');"; - } - - if ($this->getPage()->getPageConfig()->getDisableDefaultQuestionFeedback()) - { - $code[] = "ilias.questions.default_feedback = false;"; - } - - $code[] = self::getJSTextInitCode($this->getPage()->getPageConfig()->getLocalizationLanguage()).' il.COPagePres.updateQuestionOverviews();'; - } - - $get_stored_tries = $this->getPage()->getPageConfig()->getUseStoredQuestionTries(); - if ($get_stored_tries) - { - $q_ids = $this->getPage()->getQuestionIds(); - if (count($q_ids) > 0) - { - foreach ($q_ids as $q_id) - { - include_once("./Services/COPage/classes/class.ilPageQuestionProcessor.php"); - $as = ilPageQuestionProcessor::getAnswerStatus($q_id, $ilUser->getId()); - $code[] = "ilias.questions.initAnswer(".$q_id.", ".(int) $as["try"].", ".($as["passed"] ? "true" : "null").");"; - } - } - } - return $code; - } - - /** - * Get js txt init code - * - * @param - * @return - */ - static function getJSTextInitCode($a_lang) - { - global $DIC; - - $lng = $DIC->language(); - $ilUser = $DIC->user(); - - if ($a_lang == "") - { - $a_lang = $ilUser->getLanguage(); - } - - return - ' - ilias.questions.txt.wrong_answers = "'.$lng->txtlng("content", "cont_wrong_answers", $a_lang).'"; - ilias.questions.txt.wrong_answers_single = "'.$lng->txtlng("content", "cont_wrong_answers_single", $a_lang).'"; - ilias.questions.txt.tries_remaining = "'.$lng->txtlng("content", "cont_tries_remaining", $a_lang).'"; - ilias.questions.txt.please_try_again = "'.$lng->txtlng("content", "cont_please_try_again", $a_lang).'"; - ilias.questions.txt.all_answers_correct = "'.$lng->txtlng("content", "cont_all_answers_correct", $a_lang).'"; - ilias.questions.txt.enough_answers_correct = "'.$lng->txtlng("content", "cont_enough_answers_correct", $a_lang).'"; - ilias.questions.txt.nr_of_tries_exceeded = "'.$lng->txtlng("content", "cont_nr_of_tries_exceeded", $a_lang).'"; - ilias.questions.txt.correct_answers_shown = "'.$lng->txtlng("content", "cont_correct_answers_shown", $a_lang).'"; - ilias.questions.txt.correct_answers_also = "'.$lng->txtlng("content", "cont_correct_answers_also", $a_lang).'"; - ilias.questions.txt.correct_answer_also = "'.$lng->txtlng("content", "cont_correct_answer_also", $a_lang).'"; - ilias.questions.txt.ov_all_correct = "'.$lng->txtlng("content", "cont_ov_all_correct", $a_lang).'"; - ilias.questions.txt.ov_some_correct = "'.$lng->txtlng("content", "cont_ov_some_correct", $a_lang).'"; - ilias.questions.txt.ov_wrong_answered = "'.$lng->txtlng("content", "cont_ov_wrong_answered", $a_lang).'"; - ilias.questions.txt.please_select = "'.$lng->txtlng("content", "cont_please_select", $a_lang).'"; - ilias.questions.txt.ov_preview = "'.$lng->txtlng("content", "cont_ov_preview", $a_lang).'"; - ilias.questions.txt.submit_answers = "'.$lng->txtlng("content", "cont_submit_answers", $a_lang).'"; + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilObjUser + */ + protected $user; + + public $dom; + public $q_node; // node of Paragraph element + + protected static $initial_done; // [bool] + + /** + * Init page content component. + */ + public function init() + { + global $DIC; + + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->user = $DIC->user(); + $this->setType("pcqst"); + } + + /** + * Set node + */ + public function setNode($a_node) + { + parent::setNode($a_node); // this is the PageContent node + $this->q_node = $a_node->first_child(); //... and this the Question + } + + /** + * Set Question Reference. + * + * @param string $a_questionreference Question Reference + */ + public function setQuestionReference($a_questionreference) + { + if (is_object($this->q_node)) { + $this->q_node->set_attribute("QRef", $a_questionreference); + } + } + + /** + * Get Question Reference. + * + * @return string Question Reference + */ + public function getQuestionReference() + { + if (is_object($this->q_node)) { + return $this->q_node->get_attribute("QRef", $a_questionreference); + } + return false; + } + + /** + * Create Question Element + */ + public function create(&$a_pg_obj, $a_hier_id) + { + $this->createPageContentNode(); + $a_pg_obj->insertContent($this, $a_hier_id, IL_INSERT_AFTER); + $this->q_node = $this->dom->create_element("Question"); + $this->q_node = $this->node->append_child($this->q_node); + $this->q_node->set_attribute("QRef", ""); + } + + /** + * Copy question from pool into page + * + * @param + * @return + */ + public function copyPoolQuestionIntoPage($a_q_id, $a_hier_id) + { + include_once "./Modules/TestQuestionPool/classes/class.assQuestion.php"; + include_once "./Modules/TestQuestionPool/classes/class.assQuestionGUI.php"; + $question = assQuestion::_instanciateQuestion($a_q_id); + $duplicate_id = $question->copyObject(0, $question->getTitle()); + $duplicate = assQuestion::_instanciateQuestion($duplicate_id); + $duplicate->setObjId(0); + + /* PATCH-BEGIN: moved cleanup code to central place ilAssSelfAssessmentQuestionFormatter */ + /* + // we remove everything not supported by the non-tiny self + // assessment question editor + $q = $duplicate->getQuestion(); + + // we try to save all latex tags + $try = true; + $ls = ''; + $le = ''; + while ($try) + { + // search position of start tag + $pos1 = strpos($q, $ls); + if (is_int($pos1)) + { + $pos2 = strpos($q, $le, $pos1); + if (is_int($pos2)) + { + // both found: replace end tag + $q = substr($q, 0, $pos2)."[/tex]".substr($q, $pos2+7); + $q = substr($q, 0, $pos1)."[tex]".substr($q, $pos1+20); + } + else + { + $try = false; + } + } + else + { + $try = false; + } + } + + $tags = assQuestionGUI::getSelfAssessmentTags(); + $tstr = ""; + foreach ($tags as $t) + { + $tstr.="<".$t.">"; + } + $q = ilUtil::secureString($q, true, $tstr); + // self assessment uses nl2br, not p + $duplicate->setQuestion($q); + + $duplicate->saveQuestionDataToDb(); + */ + + require_once 'Modules/TestQuestionPool/classes/questions/class.ilAssSelfAssessmentQuestionFormatter.php'; + ilAssSelfAssessmentQuestionFormatter::prepareQuestionForLearningModule($duplicate); + + /* PATCH-END: moved cleanup code to central place ilAssSelfAssessmentQuestionFormatter */ + + $this->q_node->set_attribute("QRef", "il__qst_" . $duplicate_id); + } + + /** + * Get lang vars needed for editing + * @return array array of lang var keys + */ + public static function getLangVars() + { + return array("ed_insert_pcqst", "empty_question", "pc_qst"); + } + + /** + * After page has been updated (or created) + * + * @param object page object + * @param DOMDocument $a_domdoc dom document + * @param string xml + * @param bool true on creation, otherwise false + */ + public static function afterPageUpdate($a_page, DOMDocument $a_domdoc, $a_xml, $a_creation) + { + global $DIC; + + $ilDB = $DIC->database(); + + include_once("./Services/Link/classes/class.ilInternalLink.php"); + + $ilDB->manipulateF( + "DELETE FROM page_question WHERE page_parent_type = %s " . + " AND page_id = %s AND page_lang = %s", + array("text", "integer", "text"), + array($a_page->getParentType(), $a_page->getId(), $a_page->getLanguage()) + ); + + $xpath = new DOMXPath($a_domdoc); + $nodes = $xpath->query('//Question'); + $q_ids = array(); + foreach ($nodes as $node) { + $q_ref = $node->getAttribute("QRef"); + + $inst_id = ilInternalLink::_extractInstOfTarget($q_ref); + if (!($inst_id > 0)) { + $q_id = ilInternalLink::_extractObjIdOfTarget($q_ref); + if ($q_id > 0) { + $q_ids[$q_id] = $q_id; + } + } + } + foreach ($q_ids as $qid) { + $ilDB->manipulateF( + "INSERT INTO page_question (page_parent_type, page_id, page_lang, question_id)" . + " VALUES (%s,%s,%s,%s)", + array("text", "integer", "text", "integer"), + array($a_page->getParentType(), $a_page->getId(), $a_page->getLanguage(), $qid) + ); + } + } + + /** + * Before page is being deleted + * + * @param object page object + */ + public static function beforePageDelete($a_page) + { + global $DIC; + + $ilDB = $DIC->database(); + + $ilDB->manipulateF( + "DELETE FROM page_question WHERE page_parent_type = %s " . + " AND page_id = %s AND page_lang = %s", + array("text", "integer", "text"), + array($a_page->getParentType(), $a_page->getId(), $a_page->getLanguage()) + ); + } + + /** + * Get all questions of a page + */ + public static function _getQuestionIdsForPage($a_parent_type, $a_page_id, $a_lang = "-") + { + global $DIC; + + $ilDB = $DIC->database(); + + $res = $ilDB->queryF( + "SELECT * FROM page_question WHERE page_parent_type = %s " . + " AND page_id = %s AND page_lang = %s", + array("text", "integer", "text"), + array($a_parent_type, $a_page_id, $a_lang) + ); + $q_ids = array(); + while ($rec = $ilDB->fetchAssoc($res)) { + $q_ids[] = $rec["question_id"]; + } + + return $q_ids; + } + + /** + * Get page for question id + * + * @param + * @return array + */ + public static function _getPageForQuestionId($a_q_id, $a_parent_type = "") + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT * FROM page_question " . + " WHERE question_id = " . $ilDB->quote($a_q_id, "integer") + ); + while ($rec = $ilDB->fetchAssoc($set)) { + if ($a_parent_type == "" || $rec["page_parent_type"] == $a_parent_type) { + return array("page_id" => $rec["page_id"], "parent_type" => $rec["page_parent_type"]); + } + } + return false; + } + + /** + * Modify page content after xsl + * + * @param string $a_output + * @return string + */ + public function modifyPageContentPostXsl($a_output, $a_mode) + { + $lng = $this->lng; + + $qhtml = ""; + + if ($this->getPage()->getPageConfig()->getEnableSelfAssessment()) { + // #14154 + $q_ids = $this->getPage()->getQuestionIds(); + if (sizeof($q_ids)) { + include_once "./Modules/TestQuestionPool/classes/class.assQuestionGUI.php"; + foreach ($q_ids as $q_id) { + $q_gui = assQuestionGUI::_getQuestionGUI("", $q_id); + // object check due to #16557 + if (is_object($q_gui->object) && !$q_gui->object->isComplete()) { + $a_output = str_replace( + "{{{{{Question;il__qst_" . $q_id . "}}}}}", + "" . $lng->txt("cont_empty_question") . "", + $a_output + ); + } + } + + // this exports the questions which is needed below + $qhtml = $this->getQuestionJsOfPage(($a_mode == "edit") ? true : false, $a_mode); + + require_once './Modules/Scorm2004/classes/class.ilQuestionExporter.php'; + $a_output = "" . $a_output; + if (!self::$initial_done) { + $a_output = "" . $a_output; + self::$initial_done = true; + } + } + } else { + // set by T&A components + $qhtml = $this->getPage()->getPageConfig()->getQuestionHTML(); + + // address #19788 + if (!is_array($qhtml) || count($qhtml) == 0) { + // #14154 + $q_ids = $this->getPage()->getQuestionIds(); + if (sizeof($q_ids)) { + foreach ($q_ids as $k) { + $a_output = str_replace("{{{{{Question;il__qst_$k" . "}}}}}", " " . $lng->txt("copg_questions_not_supported_here"), $a_output); + } + } + } + } + + if (is_array($qhtml)) { + foreach ($qhtml as $k => $h) { + $a_output = str_replace("{{{{{Question;il__qst_$k" . "}}}}}", " " . $h, $a_output); + } + } + + return $a_output; + } + + /** + * Reset initial state (for exports) + */ + public static function resetInitialState() + { + self::$initial_done = false; + } + + /** + * Get Javascript files + */ + public function getJavascriptFiles($a_mode) + { + $js_files = array(); + + if ($this->getPage()->getPageConfig()->getEnableSelfAssessment()) { + $js_files[] = "./Modules/Scorm2004/scripts/questions/pure.js"; + $js_files[] = "./Modules/Scorm2004/scripts/questions/question_handling.js"; + $js_files[] = "Modules/TestQuestionPool/js/ilMatchingQuestion.js"; + $js_files[] = "Modules/TestQuestionPool/js/ilMultipleChoiceQuestion.js"; + + global $DIC; + if ($DIC['ilBrowser']->isMobile() || $DIC['ilBrowser']->isIpad()) { + $js_files[] = 'libs/bower/bower_components/jqueryui-touch-punch/jquery.ui.touch-punch.min.js'; + } + } + + if (!$this->getPage()->getPageConfig()->getEnableSelfAssessmentScorm() && $a_mode != IL_PAGE_PREVIEW + && $a_mode != "offline") { + $js_files[] = "./Services/COPage/js/ilCOPageQuestionHandler.js"; + } + + return $js_files; + } + + /** + * Get css files + */ + public function getCssFiles($a_mode) + { + if ($this->getPage()->getPageConfig()->getEnableSelfAssessment()) { + return array("./Modules/Scorm2004/templates/default/question_handling.css", + "Modules/TestQuestionPool/templates/default/test_javascript.css"); + } + return array(); + } + + /** + * Get on load code + */ + public function getOnloadCode($a_mode) + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + $code = array(); + + if ($this->getPage()->getPageConfig()->getEnableSelfAssessment()) { + if (!$this->getPage()->getPageConfig()->getEnableSelfAssessmentScorm() && $a_mode != IL_PAGE_PREVIEW + && $a_mode != "offline") { + $ilCtrl->setParameterByClass(strtolower(get_class($this->getPage())) . "gui", "page_id", $this->getPage()->getId()); + $url = $ilCtrl->getLinkTargetByClass(strtolower(get_class($this->getPage())) . "gui", "processAnswer", "", true, false); + $code[] = "ilCOPageQuestionHandler.initCallback('" . $url . "');"; + } + + if ($this->getPage()->getPageConfig()->getDisableDefaultQuestionFeedback()) { + $code[] = "ilias.questions.default_feedback = false;"; + } + + $code[] = self::getJSTextInitCode($this->getPage()->getPageConfig()->getLocalizationLanguage()) . ' il.COPagePres.updateQuestionOverviews();'; + } + + $get_stored_tries = $this->getPage()->getPageConfig()->getUseStoredQuestionTries(); + if ($get_stored_tries) { + $q_ids = $this->getPage()->getQuestionIds(); + if (count($q_ids) > 0) { + foreach ($q_ids as $q_id) { + include_once("./Services/COPage/classes/class.ilPageQuestionProcessor.php"); + $as = ilPageQuestionProcessor::getAnswerStatus($q_id, $ilUser->getId()); + $code[] = "ilias.questions.initAnswer(" . $q_id . ", " . (int) $as["try"] . ", " . ($as["passed"] ? "true" : "null") . ");"; + } + } + } + return $code; + } + + /** + * Get js txt init code + * + * @param + * @return + */ + public static function getJSTextInitCode($a_lang) + { + global $DIC; + + $lng = $DIC->language(); + $ilUser = $DIC->user(); + + if ($a_lang == "") { + $a_lang = $ilUser->getLanguage(); + } + + return + ' + ilias.questions.txt.wrong_answers = "' . $lng->txtlng("content", "cont_wrong_answers", $a_lang) . '"; + ilias.questions.txt.wrong_answers_single = "' . $lng->txtlng("content", "cont_wrong_answers_single", $a_lang) . '"; + ilias.questions.txt.tries_remaining = "' . $lng->txtlng("content", "cont_tries_remaining", $a_lang) . '"; + ilias.questions.txt.please_try_again = "' . $lng->txtlng("content", "cont_please_try_again", $a_lang) . '"; + ilias.questions.txt.all_answers_correct = "' . $lng->txtlng("content", "cont_all_answers_correct", $a_lang) . '"; + ilias.questions.txt.enough_answers_correct = "' . $lng->txtlng("content", "cont_enough_answers_correct", $a_lang) . '"; + ilias.questions.txt.nr_of_tries_exceeded = "' . $lng->txtlng("content", "cont_nr_of_tries_exceeded", $a_lang) . '"; + ilias.questions.txt.correct_answers_shown = "' . $lng->txtlng("content", "cont_correct_answers_shown", $a_lang) . '"; + ilias.questions.txt.correct_answers_also = "' . $lng->txtlng("content", "cont_correct_answers_also", $a_lang) . '"; + ilias.questions.txt.correct_answer_also = "' . $lng->txtlng("content", "cont_correct_answer_also", $a_lang) . '"; + ilias.questions.txt.ov_all_correct = "' . $lng->txtlng("content", "cont_ov_all_correct", $a_lang) . '"; + ilias.questions.txt.ov_some_correct = "' . $lng->txtlng("content", "cont_ov_some_correct", $a_lang) . '"; + ilias.questions.txt.ov_wrong_answered = "' . $lng->txtlng("content", "cont_ov_wrong_answered", $a_lang) . '"; + ilias.questions.txt.please_select = "' . $lng->txtlng("content", "cont_please_select", $a_lang) . '"; + ilias.questions.txt.ov_preview = "' . $lng->txtlng("content", "cont_ov_preview", $a_lang) . '"; + ilias.questions.txt.submit_answers = "' . $lng->txtlng("content", "cont_submit_answers", $a_lang) . '"; ilias.questions.refresh_lang(); '; - - } - - /** - * Get question js - */ - function getQuestionJsOfPage($a_no_interaction, $a_mode) - { - require_once './Modules/Scorm2004/classes/class.ilQuestionExporter.php'; - $q_ids = $this->getPage()->getQuestionIds(); - $js = array(); - if (count($q_ids) > 0) - { - foreach ($q_ids as $q_id) - { - $q_exporter = new ilQuestionExporter($a_no_interaction); - $image_path = null; - if ($a_mode == "offline") - { - if ($this->getPage()->getParentType() == "sahs") - { - $image_path = "./objects/"; - } - if ($this->getPage()->getParentType() == "lm") - { - $image_path = "./assessment/0/".$q_id."/images/"; - } - } - - $js[$q_id] = $q_exporter->exportQuestion($q_id, $image_path, $a_mode); - } - } - return $js; - } - + } + + /** + * Get question js + */ + public function getQuestionJsOfPage($a_no_interaction, $a_mode) + { + require_once './Modules/Scorm2004/classes/class.ilQuestionExporter.php'; + $q_ids = $this->getPage()->getQuestionIds(); + $js = array(); + if (count($q_ids) > 0) { + foreach ($q_ids as $q_id) { + $q_exporter = new ilQuestionExporter($a_no_interaction); + $image_path = null; + if ($a_mode == "offline") { + if ($this->getPage()->getParentType() == "sahs") { + $image_path = "./objects/"; + } + if ($this->getPage()->getParentType() == "lm") { + $image_path = "./assessment/0/" . $q_id . "/images/"; + } + } + + $js[$q_id] = $q_exporter->exportQuestion($q_id, $image_path, $a_mode); + } + } + return $js; + } } -?> diff --git a/Services/COPage/classes/class.ilPCQuestionGUI.php b/Services/COPage/classes/class.ilPCQuestionGUI.php index 0c8212477135ad289ccca67a856c0ee5e9c3aad7..8622eca2cf95a8b1d71f8fd758c4dfe86f95b1f0 100755 --- a/Services/COPage/classes/class.ilPCQuestionGUI.php +++ b/Services/COPage/classes/class.ilPCQuestionGUI.php @@ -17,624 +17,598 @@ include_once "./Services/COPage/classes/class.ilPCQuestion.php"; */ class ilPCQuestionGUI extends ilPageContentGUI { - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilTree - */ - protected $tree; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * 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->tpl = $DIC["tpl"]; - $this->tabs = $DIC->tabs(); - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - $this->tree = $DIC->repositoryTree(); - $this->toolbar = $DIC->toolbar(); - $ilCtrl = $DIC->ctrl(); - $this->scormlmid = $a_pg_obj->parent_id; - parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); - $ilCtrl->saveParameter($this, array("qpool_ref_id")); - } - - /** - * execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - $lng = $this->lng; - - // get current command - $cmd = $ilCtrl->getCmd(); - $next_class = $ilCtrl->getNextClass($this); - - $q_type = ($_POST["q_type"] != "") - ? $_POST["q_type"] - : $_GET["q_type"]; - - switch($next_class) - { - default: - //set tabs - if ($cmd != "insert") - { - $this->setTabs(); - } - else if ($_GET["subCmd"] != "") - { - $cmd = $_GET["subCmd"]; - } - - $ret = $this->$cmd(); - } - - - - return $ret; - } - - /** - * Set Self Assessment Mode. - * - * @param boolean $a_selfassessmentmode Self Assessment Mode - */ - function setSelfAssessmentMode($a_selfassessmentmode) - { - $this->selfassessmentmode = $a_selfassessmentmode; - } - - /** - * Get Self Assessment Mode. - * - * @return boolean Self Assessment Mode - */ - function getSelfAssessmentMode() - { - return $this->selfassessmentmode; - } - - /** - * Set insert tabs - * - * @param string $a_active active tab id - */ - function setInsertTabs($a_active) - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - // new question - $ilTabs->addSubTab("new_question", - $lng->txt("cont_new_question"), - $ilCtrl->getLinkTarget($this, "insert")); - - // copy from pool - $ilCtrl->setParameter($this, "subCmd", "insertFromPool"); - $ilTabs->addSubTab("copy_question", - $lng->txt("cont_copy_question_from_pool"), - $ilCtrl->getLinkTarget($this, "insert")); - - $ilTabs->activateSubTab($a_active); - - $ilCtrl->setParameter($this, "subCmd", ""); - } - - /** - * Insert new question form - */ - function insert($a_mode = "create") - { - $ilUser = $this->user; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->setInsertTabs("new_question"); - - $this->displayValidationError(); - - // get all question types (@todo: we have to check, whether they are - // suitable for self assessment or not) - include_once("./Modules/TestQuestionPool/classes/class.ilObjQuestionPool.php"); - $all_types = ilObjQuestionPool::_getSelfAssessmentQuestionTypes(); - $options = array(); - $all_types = ilUtil::sortArray($all_types, "order", "asc", true, true); - - foreach ($all_types as $k => $v) - { - $options[$v["type_tag"]] = $k; - } - - // new table form (input of rows and columns) - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form_gui = new ilPropertyFormGUI(); - $this->form_gui->setFormAction($ilCtrl->getFormAction($this)); - $this->form_gui->setTitle($lng->txt("cont_ed_insert_pcqst")); - - // Select Question Type - $qtype_input = new ilSelectInputGUI($lng->txt("cont_question_type"), "q_type"); - $qtype_input->setOptions($options); - $qtype_input->setRequired(true); - $this->form_gui->addItem($qtype_input); - - // additional content editor - // assessment - include_once("./Modules/Test/classes/class.ilObjAssessmentFolder.php"); - if (ilObjAssessmentFolder::isAdditionalQuestionContentEditingModePageObjectEnabled()) - { - $ri = new ilRadioGroupInputGUI($this->lng->txt("tst_add_quest_cont_edit_mode"), "add_quest_cont_edit_mode"); - - $ri->addOption(new ilRadioOption( - $this->lng->txt('tst_add_quest_cont_edit_mode_default'), - assQuestion::ADDITIONAL_CONTENT_EDITING_MODE_DEFAULT - )); - - $ri->addOption(new ilRadioOption( - $this->lng->txt('tst_add_quest_cont_edit_mode_page_object'), - assQuestion::ADDITIONAL_CONTENT_EDITING_MODE_PAGE_OBJECT - )); - - $ri->setValue(assQuestion::ADDITIONAL_CONTENT_EDITING_MODE_DEFAULT); - - $this->form_gui->addItem($ri, true); - } - else - { - $hi = new ilHiddenInputGUI("question_content_editing_type"); - $hi->setValue(assQuestion::ADDITIONAL_CONTENT_EDITING_MODE_DEFAULT); - $this->form_gui->addItem($hi, true); - } - - - // Select Question Pool -/* - include_once("./Modules/TestQuestionPool/classes/class.ilObjQuestionPool.php"); - $qpools = ilObjQuestionPool::_getAvailableQuestionpools(false, false, false, true, false, "write"); - - if (count($qpools) > 0) - { - $pool_options = array(); - foreach ($qpools as $key => $value) - { - $pool_options[$key] = $value["title"]; - } - $pool_input = new ilSelectInputGUI($lng->txt("cont_question_pool"), "qpool_ref_id"); - $pool_input->setOptions($pool_options); - $pool_input->setRequired(true); - $this->form_gui->addItem($pool_input); - } - else - { - $pool_input = new ilTextInputGUI($lng->txt("cont_question_pool"), "qpool_title"); - $pool_input->setRequired(true); - $this->form_gui->addItem($pool_input); - } -*/ - if ($a_mode == "edit_empty") - { - $this->form_gui->addCommandButton("edit", $lng->txt("save")); - } - else - { - $this->form_gui->addCommandButton("create_pcqst", $lng->txt("save")); - $this->form_gui->addCommandButton("cancelCreate", $lng->txt("cancel")); - } - - $this->tpl->setContent($this->form_gui->getHTML()); - } - - - /** - * Create new question - */ - function create() - { - global $lng, $ilCtrl, $ilTabs; - - $ilTabs->setTabActive('question'); - - $this->content_obj = new ilPCQuestion($this->getPage()); - $this->content_obj->create($this->pg_obj, $this->hier_id); - - $this->updated = $this->pg_obj->update(); - - if ($this->updated) - { - // create question pool, if necessary -/* if ($_POST["qpool_ref_id"] <= 0) - { - $pool_ref_id = $this->createQuestionPool($_POST["qpool_title"]); - } - else - { - $pool_ref_id = $_POST["qpool_ref_id"]; - }*/ - - $this->pg_obj->stripHierIDs(); - $this->pg_obj->addHierIDs(); - $hier_id = $this->content_obj->lookupHierId(); - $ilCtrl->setParameter($this, "q_type", $_POST["q_type"]); - $ilCtrl->setParameter($this, "add_quest_cont_edit_mode", $_POST["add_quest_cont_edit_mode"]); -// $ilCtrl->setParameter($this, "qpool_ref_id", $pool_ref_id); - //$ilCtrl->setParameter($this, "hier_id", $hier_id); - $ilCtrl->setParameter($this, "hier_id", $this->content_obj->readHierId()); - $ilCtrl->setParameter($this, "pc_id", $this->content_obj->readPCId()); - - $ilCtrl->redirect($this, "edit"); - } - - $this->insert(); - } - - /** - * Set new question id - */ - function setNewQuestionId($a_par) - { - if ($a_par["new_id"] > 0) - { - $this->content_obj->setQuestionReference("il__qst_".$a_par["new_id"]); - $this->pg_obj->update(); - } - } - - /** - * edit question - */ - function edit() - { - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - $ilTabs->setTabActive('question'); - - - if ($this->getSelfAssessmentMode()) // behaviour in content pages, e.g. scorm - { - $q_ref = $this->content_obj->getQuestionReference(); - - if ($q_ref != "") - { - $inst_id = ilInternalLink::_extractInstOfTarget($q_ref); - if (!($inst_id > 0)) - { - $q_id = ilInternalLink::_extractObjIdOfTarget($q_ref); - } - } - - $q_type = ($_POST["q_type"] != "") - ? $_POST["q_type"] - : $_GET["q_type"]; - $ilCtrl->setParameter($this, "q_type", $q_type); - - if ($q_id == "" && $q_type == "") - { - return $this->insert("edit_empty"); - } - - include_once("./Modules/TestQuestionPool/classes/class.ilQuestionEditGUI.php"); - include_once("./Modules/TestQuestionPool/classes/class.assQuestion.php"); - include_once("./Modules/ScormAicc/classes/class.ilObjSAHSLearningModule.php"); - -/* $ilCtrl->setCmdClass("ilquestioneditgui"); - $ilCtrl->setCmd("editQuestion"); - $edit_gui = new ilQuestionEditGUI();*/ - - // create question first-hand (needed for uploads) - if($q_id < 1 && $q_type) - { - include_once "./Modules/TestQuestionPool/classes/class.assQuestionGUI.php"; - $q_gui = assQuestionGUI::_getQuestionGUI($q_type); - - // feedback editing mode - include_once("./Modules/Test/classes/class.ilObjAssessmentFolder.php"); - if(ilObjAssessmentFolder::isAdditionalQuestionContentEditingModePageObjectEnabled() - && $_REQUEST['add_quest_cont_edit_mode'] != "") - { - $addContEditMode = $_GET['add_quest_cont_edit_mode']; - } - else - { - $addContEditMode = assQuestion::ADDITIONAL_CONTENT_EDITING_MODE_DEFAULT; - } - $q_gui->object->setAdditionalContentEditingMode($addContEditMode); - - //set default tries - $q_gui->object->setDefaultNrOfTries(ilObjSAHSLearningModule::_getTries($this->scormlmid)); - $q_id = $q_gui->object->createNewQuestion(true); - $this->content_obj->setQuestionReference("il__qst_".$q_id); - $this->pg_obj->update(); - unset($q_gui); - } - $ilCtrl->setParameterByClass("ilQuestionEditGUI", "q_id", $q_id); - $ilCtrl->redirectByClass(array(get_class($this->pg_obj)."GUI", "ilQuestionEditGUI"), "editQuestion"); - -/* $edit_gui->setPoolObjId(0); - $edit_gui->setQuestionId($q_id); - $edit_gui->setQuestionType($q_type); - $edit_gui->setSelfAssessmentEditingMode(true); - $edit_gui->setPageConfig($this->getPageConfig()); - $ret = $ilCtrl->forwardCommand($edit_gui); - $this->tpl->setContent($ret);*/ - return $ret; - } - else // behaviour in question pool - { - require_once("./Modules/TestQuestionPool/classes/class.assQuestionGUI.php"); - $q_gui = assQuestionGUI::_getQuestionGUI("", $_GET["q_id"]); - $this->ctrl->redirectByClass(array("ilobjquestionpoolgui", get_class($q_gui)), "editQuestion"); - } - } - - function feedback() - { - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - include_once("./Modules/TestQuestionPool/classes/class.ilQuestionEditGUI.php"); - include_once("./Modules/TestQuestionPool/classes/class.assQuestion.php"); - - $ilTabs->setTabActive('feedback'); - - $q_ref = $this->content_obj->getQuestionReference(); - - if ($q_ref != "") - { - $inst_id = ilInternalLink::_extractInstOfTarget($q_ref); - if (!($inst_id > 0)) - { - $q_id = ilInternalLink::_extractObjIdOfTarget($q_ref); - } - } - - $ilCtrl->setCmdClass("ilquestioneditgui"); - $ilCtrl->setCmd("feedback"); - $edit_gui = new ilQuestionEditGUI(); - if ($q_id > 0) - { - $edit_gui->setQuestionId($q_id); - } -// $edit_gui->setQuestionType("assSingleChoice"); - $edit_gui->setSelfAssessmentEditingMode(true); - $edit_gui->setPageConfig($this->getPageConfig()); - $ret = $ilCtrl->forwardCommand($edit_gui); - $this->tpl->setContent($ret); - return $ret; - - } - /** - * Creates a new questionpool and returns the reference id - * - * Creates a new questionpool and returns the reference id - * - * @return integer Reference id of the newly created questionpool - * @access public - */ - function createQuestionPool($name = "Dummy") - { - $tree = $this->tree; - $parent_ref = $tree->getParentId($_GET["ref_id"]); - include_once "./Modules/TestQuestionPool/classes/class.ilObjQuestionPool.php"; - $qpl = new ilObjQuestionPool(); - $qpl->setType("qpl"); - $qpl->setTitle($name); - $qpl->setDescription(""); - $qpl->create(); - $qpl->createReference(); - $qpl->putInTree($parent_ref); - $qpl->setPermissions($parent_ref); - $qpl->setOnline(1); // must be online to be available - $qpl->saveToDb(); - return $qpl->getRefId(); - } - - /** - * Set tabs - */ - function setTabs() - { - if ($this->getSelfAssessmentMode()) - { - return; - } - - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - include_once("./Modules/TestQuestionPool/classes/class.assQuestion.php"); - - if ($this->content_obj!="") { - $q_ref = $this->content_obj->getQuestionReference(); - } - - if ($q_ref != "") - { - $inst_id = ilInternalLink::_extractInstOfTarget($q_ref); - if (!($inst_id > 0)) - { - $q_id = ilInternalLink::_extractObjIdOfTarget($q_ref); - } - } - - $ilTabs->addTarget("question", - $ilCtrl->getLinkTarget($this, "edit"), array("editQuestion", "save", "cancel", "addSuggestedSolution", - "cancelExplorer", "linkChilds", "removeSuggestedSolution", - "addPair", "addTerm", "delete", "deleteTerms", "editMode", "upload", - "saveEdit","uploadingImage", "uploadingImagemap", "addArea", - "deletearea", "saveShape", "back", "saveEdit", "changeGapType","createGaps","addItem","addYesNo", "addTrueFalse", - "toggleGraphicalAnswers", "setMediaMode"), - ""); - - if ($q_id > 0) - { - if (assQuestion::_getQuestionType($q_id)!= "assTextQuestion") - { - require_once 'Modules/TestQuestionPool/classes/class.assQuestionGUI.php'; - require_once 'Modules/TestQuestionPool/classes/class.ilAssQuestionFeedbackEditingGUI.php'; - $tabCommands = assQuestionGUI::getCommandsFromClassConstants('ilAssQuestionFeedbackEditingGUI'); - $tabLink = ilUtil::appendUrlParameterString( - $ilCtrl->getLinkTargetByClass('ilAssQuestionFeedbackEditingGUI', ilAssQuestionFeedbackEditingGUI::CMD_SHOW), - "q_id=".(int)$q_id - ); - $ilTabs->addTarget('feedback', $tabLink, $tabCommands, $ilCtrl->getCmdClass(), ''); - } - } - } - - //// - //// Get question from pool - //// - - /** - * Insert question from ppol - */ - function insertFromPool() - { - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - $ilTabs = $this->tabs; - $tpl = $this->tpl; - $lng = $this->lng; - $ilToolbar = $this->toolbar; -//var_dump($_SESSION["cont_qst_pool"]); - if ($_SESSION["cont_qst_pool"] != "" && - $ilAccess->checkAccess("write", "", $_SESSION["cont_qst_pool"]) - && ilObject::_lookupType(ilObject::_lookupObjId($_SESSION["cont_qst_pool"])) == "qpl") - { - $this->listPoolQuestions(); - } - else - { - $this->poolSelection(); - } - } - - /** - * Pool selection - * - * @param - * @return - */ - function poolSelection() - { - $ilCtrl = $this->ctrl; - $tree = $this->tree; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - $this->setInsertTabs("copy_question"); - - 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", "qpl")); - $exp->setClickableTypes(array('qpl')); - - if (!$exp->handleCommand()) - { - $tpl->setContent($exp->getHTML()); - } - - } - - /** - * Select concrete question pool - */ - function selectPool() - { - $ilCtrl = $this->ctrl; - - $_SESSION["cont_qst_pool"] = $_GET["pool_ref_id"]; - $ilCtrl->setParameter($this, "subCmd", "insertFromPool"); - $ilCtrl->redirect($this, "insert"); - } - - /** - * List questions of pool - * - * @param - * @return - */ - function listPoolQuestions() - { - $ilToolbar = $this->toolbar; - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - ilUtil::sendInfo($lng->txt("cont_cp_question_diff_formats_info")); - - $ilCtrl->setParameter($this, "subCmd", "poolSelection"); - $ilToolbar->addButton( - $lng->txt("cont_select_other_qpool"), - $ilCtrl->getLinkTarget($this, "insert")); - $ilCtrl->setParameter($this, "subCmd", ""); - - $this->setInsertTabs("copy_question"); - - include_once "./Services/COPage/classes/class.ilCopySelfAssQuestionTableGUI.php"; - - $ilCtrl->setParameter($this, "subCmd", "listPoolQuestions"); - $table_gui = new ilCopySelfAssQuestionTableGUI($this, 'insert', - $_SESSION["cont_qst_pool"]); - - $tpl->setContent($table_gui->getHTML()); - } - - /** - * Copy question into page - * - * @param - * @return - */ - function copyQuestion() - { - $ilCtrl = $this->ctrl; - - $this->content_obj = new ilPCQuestion($this->getPage()); - $this->content_obj->create($this->pg_obj, $_GET["hier_id"]); - - $this->content_obj->copyPoolQuestionIntoPage( - (int) $_GET["q_id"], $_GET["hier_id"]); - - $this->updated = $this->pg_obj->update(); - - $ilCtrl->returnToParent($this); - } - + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilTree + */ + protected $tree; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * 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->tpl = $DIC["tpl"]; + $this->tabs = $DIC->tabs(); + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + $this->tree = $DIC->repositoryTree(); + $this->toolbar = $DIC->toolbar(); + $ilCtrl = $DIC->ctrl(); + $this->scormlmid = $a_pg_obj->parent_id; + parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); + $ilCtrl->saveParameter($this, array("qpool_ref_id")); + } + + /** + * execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + $lng = $this->lng; + + // get current command + $cmd = $ilCtrl->getCmd(); + $next_class = $ilCtrl->getNextClass($this); + + $q_type = ($_POST["q_type"] != "") + ? $_POST["q_type"] + : $_GET["q_type"]; + + switch ($next_class) { + default: + //set tabs + if ($cmd != "insert") { + $this->setTabs(); + } elseif ($_GET["subCmd"] != "") { + $cmd = $_GET["subCmd"]; + } + + $ret = $this->$cmd(); + } + + + + return $ret; + } + + /** + * Set Self Assessment Mode. + * + * @param boolean $a_selfassessmentmode Self Assessment Mode + */ + public function setSelfAssessmentMode($a_selfassessmentmode) + { + $this->selfassessmentmode = $a_selfassessmentmode; + } + + /** + * Get Self Assessment Mode. + * + * @return boolean Self Assessment Mode + */ + public function getSelfAssessmentMode() + { + return $this->selfassessmentmode; + } + + /** + * Set insert tabs + * + * @param string $a_active active tab id + */ + public function setInsertTabs($a_active) + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + // new question + $ilTabs->addSubTab( + "new_question", + $lng->txt("cont_new_question"), + $ilCtrl->getLinkTarget($this, "insert") + ); + + // copy from pool + $ilCtrl->setParameter($this, "subCmd", "insertFromPool"); + $ilTabs->addSubTab( + "copy_question", + $lng->txt("cont_copy_question_from_pool"), + $ilCtrl->getLinkTarget($this, "insert") + ); + + $ilTabs->activateSubTab($a_active); + + $ilCtrl->setParameter($this, "subCmd", ""); + } + + /** + * Insert new question form + */ + public function insert($a_mode = "create") + { + $ilUser = $this->user; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $this->setInsertTabs("new_question"); + + $this->displayValidationError(); + + // get all question types (@todo: we have to check, whether they are + // suitable for self assessment or not) + include_once("./Modules/TestQuestionPool/classes/class.ilObjQuestionPool.php"); + $all_types = ilObjQuestionPool::_getSelfAssessmentQuestionTypes(); + $options = array(); + $all_types = ilUtil::sortArray($all_types, "order", "asc", true, true); + + foreach ($all_types as $k => $v) { + $options[$v["type_tag"]] = $k; + } + + // new table form (input of rows and columns) + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form_gui = new ilPropertyFormGUI(); + $this->form_gui->setFormAction($ilCtrl->getFormAction($this)); + $this->form_gui->setTitle($lng->txt("cont_ed_insert_pcqst")); + + // Select Question Type + $qtype_input = new ilSelectInputGUI($lng->txt("cont_question_type"), "q_type"); + $qtype_input->setOptions($options); + $qtype_input->setRequired(true); + $this->form_gui->addItem($qtype_input); + + // additional content editor + // assessment + include_once("./Modules/Test/classes/class.ilObjAssessmentFolder.php"); + if (ilObjAssessmentFolder::isAdditionalQuestionContentEditingModePageObjectEnabled()) { + $ri = new ilRadioGroupInputGUI($this->lng->txt("tst_add_quest_cont_edit_mode"), "add_quest_cont_edit_mode"); + + $ri->addOption(new ilRadioOption( + $this->lng->txt('tst_add_quest_cont_edit_mode_default'), + assQuestion::ADDITIONAL_CONTENT_EDITING_MODE_DEFAULT + )); + + $ri->addOption(new ilRadioOption( + $this->lng->txt('tst_add_quest_cont_edit_mode_page_object'), + assQuestion::ADDITIONAL_CONTENT_EDITING_MODE_PAGE_OBJECT + )); + + $ri->setValue(assQuestion::ADDITIONAL_CONTENT_EDITING_MODE_DEFAULT); + + $this->form_gui->addItem($ri, true); + } else { + $hi = new ilHiddenInputGUI("question_content_editing_type"); + $hi->setValue(assQuestion::ADDITIONAL_CONTENT_EDITING_MODE_DEFAULT); + $this->form_gui->addItem($hi, true); + } + + + // Select Question Pool + /* + include_once("./Modules/TestQuestionPool/classes/class.ilObjQuestionPool.php"); + $qpools = ilObjQuestionPool::_getAvailableQuestionpools(false, false, false, true, false, "write"); + + if (count($qpools) > 0) + { + $pool_options = array(); + foreach ($qpools as $key => $value) + { + $pool_options[$key] = $value["title"]; + } + $pool_input = new ilSelectInputGUI($lng->txt("cont_question_pool"), "qpool_ref_id"); + $pool_input->setOptions($pool_options); + $pool_input->setRequired(true); + $this->form_gui->addItem($pool_input); + } + else + { + $pool_input = new ilTextInputGUI($lng->txt("cont_question_pool"), "qpool_title"); + $pool_input->setRequired(true); + $this->form_gui->addItem($pool_input); + } + */ + if ($a_mode == "edit_empty") { + $this->form_gui->addCommandButton("edit", $lng->txt("save")); + } else { + $this->form_gui->addCommandButton("create_pcqst", $lng->txt("save")); + $this->form_gui->addCommandButton("cancelCreate", $lng->txt("cancel")); + } + + $this->tpl->setContent($this->form_gui->getHTML()); + } + + + /** + * Create new question + */ + public function create() + { + global $lng, $ilCtrl, $ilTabs; + + $ilTabs->setTabActive('question'); + + $this->content_obj = new ilPCQuestion($this->getPage()); + $this->content_obj->create($this->pg_obj, $this->hier_id); + + $this->updated = $this->pg_obj->update(); + + if ($this->updated) { + // create question pool, if necessary + /* if ($_POST["qpool_ref_id"] <= 0) + { + $pool_ref_id = $this->createQuestionPool($_POST["qpool_title"]); + } + else + { + $pool_ref_id = $_POST["qpool_ref_id"]; + }*/ + + $this->pg_obj->stripHierIDs(); + $this->pg_obj->addHierIDs(); + $hier_id = $this->content_obj->lookupHierId(); + $ilCtrl->setParameter($this, "q_type", $_POST["q_type"]); + $ilCtrl->setParameter($this, "add_quest_cont_edit_mode", $_POST["add_quest_cont_edit_mode"]); + // $ilCtrl->setParameter($this, "qpool_ref_id", $pool_ref_id); + //$ilCtrl->setParameter($this, "hier_id", $hier_id); + $ilCtrl->setParameter($this, "hier_id", $this->content_obj->readHierId()); + $ilCtrl->setParameter($this, "pc_id", $this->content_obj->readPCId()); + + $ilCtrl->redirect($this, "edit"); + } + + $this->insert(); + } + + /** + * Set new question id + */ + public function setNewQuestionId($a_par) + { + if ($a_par["new_id"] > 0) { + $this->content_obj->setQuestionReference("il__qst_" . $a_par["new_id"]); + $this->pg_obj->update(); + } + } + + /** + * edit question + */ + public function edit() + { + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + $ilTabs->setTabActive('question'); + + + if ($this->getSelfAssessmentMode()) { // behaviour in content pages, e.g. scorm + $q_ref = $this->content_obj->getQuestionReference(); + + if ($q_ref != "") { + $inst_id = ilInternalLink::_extractInstOfTarget($q_ref); + if (!($inst_id > 0)) { + $q_id = ilInternalLink::_extractObjIdOfTarget($q_ref); + } + } + + $q_type = ($_POST["q_type"] != "") + ? $_POST["q_type"] + : $_GET["q_type"]; + $ilCtrl->setParameter($this, "q_type", $q_type); + + if ($q_id == "" && $q_type == "") { + return $this->insert("edit_empty"); + } + + include_once("./Modules/TestQuestionPool/classes/class.ilQuestionEditGUI.php"); + include_once("./Modules/TestQuestionPool/classes/class.assQuestion.php"); + include_once("./Modules/ScormAicc/classes/class.ilObjSAHSLearningModule.php"); + + /* $ilCtrl->setCmdClass("ilquestioneditgui"); + $ilCtrl->setCmd("editQuestion"); + $edit_gui = new ilQuestionEditGUI();*/ + + // create question first-hand (needed for uploads) + if ($q_id < 1 && $q_type) { + include_once "./Modules/TestQuestionPool/classes/class.assQuestionGUI.php"; + $q_gui = assQuestionGUI::_getQuestionGUI($q_type); + + // feedback editing mode + include_once("./Modules/Test/classes/class.ilObjAssessmentFolder.php"); + if (ilObjAssessmentFolder::isAdditionalQuestionContentEditingModePageObjectEnabled() + && $_REQUEST['add_quest_cont_edit_mode'] != "") { + $addContEditMode = $_GET['add_quest_cont_edit_mode']; + } else { + $addContEditMode = assQuestion::ADDITIONAL_CONTENT_EDITING_MODE_DEFAULT; + } + $q_gui->object->setAdditionalContentEditingMode($addContEditMode); + + //set default tries + $q_gui->object->setDefaultNrOfTries(ilObjSAHSLearningModule::_getTries($this->scormlmid)); + $q_id = $q_gui->object->createNewQuestion(true); + $this->content_obj->setQuestionReference("il__qst_" . $q_id); + $this->pg_obj->update(); + unset($q_gui); + } + $ilCtrl->setParameterByClass("ilQuestionEditGUI", "q_id", $q_id); + $ilCtrl->redirectByClass(array(get_class($this->pg_obj) . "GUI", "ilQuestionEditGUI"), "editQuestion"); + + /* $edit_gui->setPoolObjId(0); + $edit_gui->setQuestionId($q_id); + $edit_gui->setQuestionType($q_type); + $edit_gui->setSelfAssessmentEditingMode(true); + $edit_gui->setPageConfig($this->getPageConfig()); + $ret = $ilCtrl->forwardCommand($edit_gui); + $this->tpl->setContent($ret);*/ + return $ret; + } else { // behaviour in question pool + require_once("./Modules/TestQuestionPool/classes/class.assQuestionGUI.php"); + $q_gui = assQuestionGUI::_getQuestionGUI("", $_GET["q_id"]); + $this->ctrl->redirectByClass(array("ilobjquestionpoolgui", get_class($q_gui)), "editQuestion"); + } + } + + public function feedback() + { + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + include_once("./Modules/TestQuestionPool/classes/class.ilQuestionEditGUI.php"); + include_once("./Modules/TestQuestionPool/classes/class.assQuestion.php"); + + $ilTabs->setTabActive('feedback'); + + $q_ref = $this->content_obj->getQuestionReference(); + + if ($q_ref != "") { + $inst_id = ilInternalLink::_extractInstOfTarget($q_ref); + if (!($inst_id > 0)) { + $q_id = ilInternalLink::_extractObjIdOfTarget($q_ref); + } + } + + $ilCtrl->setCmdClass("ilquestioneditgui"); + $ilCtrl->setCmd("feedback"); + $edit_gui = new ilQuestionEditGUI(); + if ($q_id > 0) { + $edit_gui->setQuestionId($q_id); + } + // $edit_gui->setQuestionType("assSingleChoice"); + $edit_gui->setSelfAssessmentEditingMode(true); + $edit_gui->setPageConfig($this->getPageConfig()); + $ret = $ilCtrl->forwardCommand($edit_gui); + $this->tpl->setContent($ret); + return $ret; + } + /** + * Creates a new questionpool and returns the reference id + * + * Creates a new questionpool and returns the reference id + * + * @return integer Reference id of the newly created questionpool + * @access public + */ + public function createQuestionPool($name = "Dummy") + { + $tree = $this->tree; + $parent_ref = $tree->getParentId($_GET["ref_id"]); + include_once "./Modules/TestQuestionPool/classes/class.ilObjQuestionPool.php"; + $qpl = new ilObjQuestionPool(); + $qpl->setType("qpl"); + $qpl->setTitle($name); + $qpl->setDescription(""); + $qpl->create(); + $qpl->createReference(); + $qpl->putInTree($parent_ref); + $qpl->setPermissions($parent_ref); + $qpl->setOnline(1); // must be online to be available + $qpl->saveToDb(); + return $qpl->getRefId(); + } + + /** + * Set tabs + */ + public function setTabs() + { + if ($this->getSelfAssessmentMode()) { + return; + } + + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + include_once("./Modules/TestQuestionPool/classes/class.assQuestion.php"); + + if ($this->content_obj!="") { + $q_ref = $this->content_obj->getQuestionReference(); + } + + if ($q_ref != "") { + $inst_id = ilInternalLink::_extractInstOfTarget($q_ref); + if (!($inst_id > 0)) { + $q_id = ilInternalLink::_extractObjIdOfTarget($q_ref); + } + } + + $ilTabs->addTarget( + "question", + $ilCtrl->getLinkTarget($this, "edit"), + array("editQuestion", "save", "cancel", "addSuggestedSolution", + "cancelExplorer", "linkChilds", "removeSuggestedSolution", + "addPair", "addTerm", "delete", "deleteTerms", "editMode", "upload", + "saveEdit","uploadingImage", "uploadingImagemap", "addArea", + "deletearea", "saveShape", "back", "saveEdit", "changeGapType","createGaps","addItem","addYesNo", "addTrueFalse", + "toggleGraphicalAnswers", "setMediaMode"), + "" + ); + + if ($q_id > 0) { + if (assQuestion::_getQuestionType($q_id)!= "assTextQuestion") { + require_once 'Modules/TestQuestionPool/classes/class.assQuestionGUI.php'; + require_once 'Modules/TestQuestionPool/classes/class.ilAssQuestionFeedbackEditingGUI.php'; + $tabCommands = assQuestionGUI::getCommandsFromClassConstants('ilAssQuestionFeedbackEditingGUI'); + $tabLink = ilUtil::appendUrlParameterString( + $ilCtrl->getLinkTargetByClass('ilAssQuestionFeedbackEditingGUI', ilAssQuestionFeedbackEditingGUI::CMD_SHOW), + "q_id=" . (int) $q_id + ); + $ilTabs->addTarget('feedback', $tabLink, $tabCommands, $ilCtrl->getCmdClass(), ''); + } + } + } + + //// + //// Get question from pool + //// + + /** + * Insert question from ppol + */ + public function insertFromPool() + { + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + $ilTabs = $this->tabs; + $tpl = $this->tpl; + $lng = $this->lng; + $ilToolbar = $this->toolbar; + //var_dump($_SESSION["cont_qst_pool"]); + if ($_SESSION["cont_qst_pool"] != "" && + $ilAccess->checkAccess("write", "", $_SESSION["cont_qst_pool"]) + && ilObject::_lookupType(ilObject::_lookupObjId($_SESSION["cont_qst_pool"])) == "qpl") { + $this->listPoolQuestions(); + } else { + $this->poolSelection(); + } + } + + /** + * Pool selection + * + * @param + * @return + */ + public function poolSelection() + { + $ilCtrl = $this->ctrl; + $tree = $this->tree; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + $this->setInsertTabs("copy_question"); + + 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", "qpl")); + $exp->setClickableTypes(array('qpl')); + + if (!$exp->handleCommand()) { + $tpl->setContent($exp->getHTML()); + } + } + + /** + * Select concrete question pool + */ + public function selectPool() + { + $ilCtrl = $this->ctrl; + + $_SESSION["cont_qst_pool"] = $_GET["pool_ref_id"]; + $ilCtrl->setParameter($this, "subCmd", "insertFromPool"); + $ilCtrl->redirect($this, "insert"); + } + + /** + * List questions of pool + * + * @param + * @return + */ + public function listPoolQuestions() + { + $ilToolbar = $this->toolbar; + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + ilUtil::sendInfo($lng->txt("cont_cp_question_diff_formats_info")); + + $ilCtrl->setParameter($this, "subCmd", "poolSelection"); + $ilToolbar->addButton( + $lng->txt("cont_select_other_qpool"), + $ilCtrl->getLinkTarget($this, "insert") + ); + $ilCtrl->setParameter($this, "subCmd", ""); + + $this->setInsertTabs("copy_question"); + + include_once "./Services/COPage/classes/class.ilCopySelfAssQuestionTableGUI.php"; + + $ilCtrl->setParameter($this, "subCmd", "listPoolQuestions"); + $table_gui = new ilCopySelfAssQuestionTableGUI( + $this, + 'insert', + $_SESSION["cont_qst_pool"] + ); + + $tpl->setContent($table_gui->getHTML()); + } + + /** + * Copy question into page + * + * @param + * @return + */ + public function copyQuestion() + { + $ilCtrl = $this->ctrl; + + $this->content_obj = new ilPCQuestion($this->getPage()); + $this->content_obj->create($this->pg_obj, $_GET["hier_id"]); + + $this->content_obj->copyPoolQuestionIntoPage( + (int) $_GET["q_id"], + $_GET["hier_id"] + ); + + $this->updated = $this->pg_obj->update(); + + $ilCtrl->returnToParent($this); + } } -?> diff --git a/Services/COPage/classes/class.ilPCQuestionOverview.php b/Services/COPage/classes/class.ilPCQuestionOverview.php index 58893580f4ae72e5066f2989b2a600959b1d1402..8ea6bacbda68a1f08c05ef8c913b9df4da5705f4 100755 --- a/Services/COPage/classes/class.ilPCQuestionOverview.php +++ b/Services/COPage/classes/class.ilPCQuestionOverview.php @@ -14,115 +14,100 @@ require_once("./Services/COPage/classes/class.ilPageContent.php"); */ class ilPCQuestionOverview extends ilPageContent { - var $dom; - var $qover_node; + public $dom; + public $qover_node; - /** - * Init page content component. - */ - function init() - { - $this->setType("qover"); - } + /** + * Init page content component. + */ + public function init() + { + $this->setType("qover"); + } - /** - * Set node - */ - function setNode($a_node) - { - parent::setNode($a_node); // this is the PageContent node - $this->qover_node = $a_node->first_child(); // this is the question overview node - } + /** + * Set node + */ + public function setNode($a_node) + { + parent::setNode($a_node); // this is the PageContent node + $this->qover_node = $a_node->first_child(); // this is the question overview node + } - /** - * Create question overview node in xml. - * - * @param object $a_pg_obj Page Object - * @param string $a_hier_id Hierarchical ID - */ - 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->qover_node = $this->dom->create_element("QuestionOverview"); - $this->qover_node = $this->node->append_child($this->qover_node); - $this->qover_node->set_attribute("ShortMessage", "y"); - } + /** + * Create question overview node in xml. + * + * @param object $a_pg_obj Page Object + * @param string $a_hier_id Hierarchical ID + */ + public 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->qover_node = $this->dom->create_element("QuestionOverview"); + $this->qover_node = $this->node->append_child($this->qover_node); + $this->qover_node->set_attribute("ShortMessage", "y"); + } - /** - * Set short message - * - * @param boolean $a_val t/f - */ - function setShortMessage($a_val) - { - if ($a_val) - { - $this->qover_node->set_attribute("ShortMessage", "y"); - } - else - { - if ($this->qover_node->has_attribute("ShortMessage")) - { - $this->qover_node->remove_attribute("ShortMessage"); - } - } - } + /** + * Set short message + * + * @param boolean $a_val t/f + */ + public function setShortMessage($a_val) + { + if ($a_val) { + $this->qover_node->set_attribute("ShortMessage", "y"); + } else { + if ($this->qover_node->has_attribute("ShortMessage")) { + $this->qover_node->remove_attribute("ShortMessage"); + } + } + } - /** - * Get short message - * - * @return boolean - */ - function getShortMessage() - { - if (is_object($this->qover_node)) - { - if ($this->qover_node->get_attribute("ShortMessage") == "y") - { - return true; - } - } - return false; - } - - /** - * Set list wrong questions - * - * @param boolean $a_val t/f - */ - function setListWrongQuestions($a_val) - { - if ($a_val) - { - $this->qover_node->set_attribute("ListWrongQuestions", "y"); - } - else - { - if ($this->qover_node->has_attribute("ListWrongQuestions")) - { - $this->qover_node->remove_attribute("ListWrongQuestions"); - } - } - } - - /** - * Get list wrong questions - * - * @return boolean - */ - function getListWrongQuestions() - { - if (is_object($this->qover_node)) - { - if ($this->qover_node->get_attribute("ListWrongQuestions") == "y") - { - return true; - } - } - return false; - } + /** + * Get short message + * + * @return boolean + */ + public function getShortMessage() + { + if (is_object($this->qover_node)) { + if ($this->qover_node->get_attribute("ShortMessage") == "y") { + return true; + } + } + return false; + } + + /** + * Set list wrong questions + * + * @param boolean $a_val t/f + */ + public function setListWrongQuestions($a_val) + { + if ($a_val) { + $this->qover_node->set_attribute("ListWrongQuestions", "y"); + } else { + if ($this->qover_node->has_attribute("ListWrongQuestions")) { + $this->qover_node->remove_attribute("ListWrongQuestions"); + } + } + } + /** + * Get list wrong questions + * + * @return boolean + */ + public function getListWrongQuestions() + { + if (is_object($this->qover_node)) { + if ($this->qover_node->get_attribute("ListWrongQuestions") == "y") { + return true; + } + } + return false; + } } - -?> diff --git a/Services/COPage/classes/class.ilPCQuestionOverviewGUI.php b/Services/COPage/classes/class.ilPCQuestionOverviewGUI.php index c16697b11472c41d3635f3a0e75fd3c10135b819..53e608794fd18484300b11fbed47f7f04ca4ce49 100755 --- a/Services/COPage/classes/class.ilPCQuestionOverviewGUI.php +++ b/Services/COPage/classes/class.ilPCQuestionOverviewGUI.php @@ -17,148 +17,130 @@ require_once("./Services/COPage/classes/class.ilPageContentGUI.php"); class ilPCQuestionOverviewGUI extends ilPageContentGUI { - /** - * Constructor - */ - function __construct(&$a_pg_obj, &$a_content_obj, $a_hier_id, $a_pc_id = "") - { - global $DIC; + /** + * Constructor + */ + public function __construct(&$a_pg_obj, &$a_content_obj, $a_hier_id, $a_pc_id = "") + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->tpl = $DIC["tpl"]; - $this->lng = $DIC->language(); - parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); - } + $this->ctrl = $DIC->ctrl(); + $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); + /** + * 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(); + // get current command + $cmd = $this->ctrl->getCmd(); - switch($next_class) - { - default: - $ret = $this->$cmd(); - break; - } + switch ($next_class) { + default: + $ret = $this->$cmd(); + break; + } - return $ret; - } + return $ret; + } - /** - * Insert new question overview - */ - function insert() - { - $this->edit(true); - } + /** + * Insert new question overview + */ + public function insert() + { + $this->edit(true); + } - /** - * Edit question overview form. - */ - function edit($a_insert = false) - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - $this->displayValidationError(); - - // edit form - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this)); - if ($a_insert) - { - $form->setTitle($this->lng->txt("cont_ed_insert_qover")); - } - else - { - $form->setTitle($this->lng->txt("cont_edit_qover")); - } - - // short message - $cb = new ilCheckboxInputGUI($this->lng->txt("cont_qover_short_message"), "short"); - $cb->setInfo($this->lng->txt("cont_qover_short_message_info")); - if (!$a_insert) - { - $cb->setChecked($this->content_obj->getShortMessage()); - } - else - { - $cb->setChecked(true); - } - $form->addItem($cb); - - // list wrong questions - $cb = new ilCheckboxInputGUI($this->lng->txt("cont_qover_list_wrong_q"), "wrong_questions"); - $cb->setInfo($this->lng->txt("cont_qover_list_wrong_q_info")); - if (!$a_insert) - { - $cb->setChecked($this->content_obj->getListWrongQuestions()); - } - $form->addItem($cb); - - // save/cancel buttons - if ($a_insert) - { - $form->addCommandButton("create_qover", $lng->txt("save")); - $form->addCommandButton("cancelCreate", $lng->txt("cancel")); - } - else - { - $form->addCommandButton("update", $lng->txt("save")); - $form->addCommandButton("cancelUpdate", $lng->txt("cancel")); - } - $html = $form->getHTML(); - $tpl->setContent($html); - return $ret; - } + /** + * Edit question overview form. + */ + public function edit($a_insert = false) + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + $this->displayValidationError(); + + // edit form + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this)); + if ($a_insert) { + $form->setTitle($this->lng->txt("cont_ed_insert_qover")); + } else { + $form->setTitle($this->lng->txt("cont_edit_qover")); + } + + // short message + $cb = new ilCheckboxInputGUI($this->lng->txt("cont_qover_short_message"), "short"); + $cb->setInfo($this->lng->txt("cont_qover_short_message_info")); + if (!$a_insert) { + $cb->setChecked($this->content_obj->getShortMessage()); + } else { + $cb->setChecked(true); + } + $form->addItem($cb); + + // list wrong questions + $cb = new ilCheckboxInputGUI($this->lng->txt("cont_qover_list_wrong_q"), "wrong_questions"); + $cb->setInfo($this->lng->txt("cont_qover_list_wrong_q_info")); + if (!$a_insert) { + $cb->setChecked($this->content_obj->getListWrongQuestions()); + } + $form->addItem($cb); + + // save/cancel buttons + if ($a_insert) { + $form->addCommandButton("create_qover", $lng->txt("save")); + $form->addCommandButton("cancelCreate", $lng->txt("cancel")); + } else { + $form->addCommandButton("update", $lng->txt("save")); + $form->addCommandButton("cancelUpdate", $lng->txt("cancel")); + } + $html = $form->getHTML(); + $tpl->setContent($html); + return $ret; + } - /** - * Create new question overview - */ - function create() - { - $this->content_obj = new ilPCQuestionOverview($this->getPage()); - $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); - $this->content_obj->setShortMessage(ilUtil::stripSlashes($_POST["short"])); - $this->content_obj->setListWrongQuestions(ilUtil::stripSlashes($_POST["wrong_questions"])); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - else - { - $this->insert(); - } - } + /** + * Create new question overview + */ + public function create() + { + $this->content_obj = new ilPCQuestionOverview($this->getPage()); + $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); + $this->content_obj->setShortMessage(ilUtil::stripSlashes($_POST["short"])); + $this->content_obj->setListWrongQuestions(ilUtil::stripSlashes($_POST["wrong_questions"])); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } else { + $this->insert(); + } + } - /** - * Update question overview - */ - function update() - { - $this->content_obj->setShortMessage(ilUtil::stripSlashes($_POST["short"])); - $this->content_obj->setListWrongQuestions(ilUtil::stripSlashes($_POST["wrong_questions"])); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - else - { - $this->pg_obj->addHierIDs(); - $this->edit(); - } - } + /** + * Update question overview + */ + public function update() + { + $this->content_obj->setShortMessage(ilUtil::stripSlashes($_POST["short"])); + $this->content_obj->setListWrongQuestions(ilUtil::stripSlashes($_POST["wrong_questions"])); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } else { + $this->pg_obj->addHierIDs(); + $this->edit(); + } + } } -?> diff --git a/Services/COPage/classes/class.ilPCResources.php b/Services/COPage/classes/class.ilPCResources.php index 4e3fbd92032ba967eb46cc11437d71948eeb1a80..e760271e5021d3ecfcebfedbc0f905c5e32ede62 100755 --- a/Services/COPage/classes/class.ilPCResources.php +++ b/Services/COPage/classes/class.ilPCResources.php @@ -16,182 +16,165 @@ require_once("./Services/COPage/classes/class.ilPageContent.php"); */ class ilPCResources extends ilPageContent { - var $dom; - var $res_node; + public $dom; + public $res_node; - /** - * Init page content component. - */ - function init() - { - $this->setType("repobj"); - } + /** + * Init page content component. + */ + public function init() + { + $this->setType("repobj"); + } - /** - * Set node - */ - function setNode($a_node) - { - parent::setNode($a_node); // this is the PageContent node - $this->res_node = $a_node->first_child(); // this is the Resources node - } + /** + * Set node + */ + public function setNode($a_node) + { + parent::setNode($a_node); // this is the PageContent node + $this->res_node = $a_node->first_child(); // this is the Resources node + } - /** - * Create resources node in xml. - * - * @param object $a_pg_obj Page Object - * @param string $a_hier_id Hierarchical ID - */ - 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->res_node = $this->dom->create_element("Resources"); - $this->res_node = $this->node->append_child($this->res_node); - } + /** + * Create resources node in xml. + * + * @param object $a_pg_obj Page Object + * @param string $a_hier_id Hierarchical ID + */ + public 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->res_node = $this->dom->create_element("Resources"); + $this->res_node = $this->node->append_child($this->res_node); + } - /** - * Set Type of Resource List (currently only one) - * - * @param string $a_type Resource Type Group - */ - function setResourceListType($a_type) - { - if (!empty($a_type)) - { - $children = $this->res_node->child_nodes(); - for ($i=0; $ires_node->remove_child($children[$i]); - } - $list_node = $this->dom->create_element("ResourceList"); - $list_node = $this->res_node->append_child($list_node); - $list_node->set_attribute("Type", $a_type); - } - } + /** + * Set Type of Resource List (currently only one) + * + * @param string $a_type Resource Type Group + */ + public function setResourceListType($a_type) + { + if (!empty($a_type)) { + $children = $this->res_node->child_nodes(); + for ($i=0; $ires_node->remove_child($children[$i]); + } + $list_node = $this->dom->create_element("ResourceList"); + $list_node = $this->res_node->append_child($list_node); + $list_node->set_attribute("Type", $a_type); + } + } - /** - * Set Item Group Ref Id - * - * @param int $a_ref_id item group ref id - */ - function setItemGroupRefId($a_ref_id) - { - if (!empty($a_ref_id)) - { - $children = $this->res_node->child_nodes(); - for ($i=0; $ires_node->remove_child($children[$i]); - } - $list_node = $this->dom->create_element("ItemGroup"); - $list_node = $this->res_node->append_child($list_node); - $list_node->set_attribute("RefId", $a_ref_id); - } - } + /** + * Set Item Group Ref Id + * + * @param int $a_ref_id item group ref id + */ + public function setItemGroupRefId($a_ref_id) + { + if (!empty($a_ref_id)) { + $children = $this->res_node->child_nodes(); + for ($i=0; $ires_node->remove_child($children[$i]); + } + $list_node = $this->dom->create_element("ItemGroup"); + $list_node = $this->res_node->append_child($list_node); + $list_node->set_attribute("RefId", $a_ref_id); + } + } - /** - * Get Resource Lis Type. - * - * @return string resource type group - */ - function getResourceListType() - { - if (is_object($this->res_node)) - { - $children = $this->res_node->child_nodes(); - if (is_object($children[0]) && $children[0]->node_name() == "ResourceList") - { - return $children[0]->get_attribute("Type"); - } - } - return false; - } - - /** - * Get item group ref id - * - * @return int ref id - */ - function getItemGroupRefId() - { - if (is_object($this->res_node)) - { - $children = $this->res_node->child_nodes(); - if (is_object($children[0]) && $children[0]->node_name() == "ItemGroup") - { - return (int) $children[0]->get_attribute("RefId"); - } - } - return false; - } + /** + * Get Resource Lis Type. + * + * @return string resource type group + */ + public function getResourceListType() + { + if (is_object($this->res_node)) { + $children = $this->res_node->child_nodes(); + if (is_object($children[0]) && $children[0]->node_name() == "ResourceList") { + return $children[0]->get_attribute("Type"); + } + } + return false; + } + + /** + * Get item group ref id + * + * @return int ref id + */ + public function getItemGroupRefId() + { + if (is_object($this->res_node)) { + $children = $this->res_node->child_nodes(); + if (is_object($children[0]) && $children[0]->node_name() == "ItemGroup") { + return (int) $children[0]->get_attribute("RefId"); + } + } + return false; + } - /** - * Get main type - * - * @return int ref id - */ - function getMainType() - { - if (is_object($this->res_node)) - { - $children = $this->res_node->child_nodes(); - if (is_object($children[0])) - { - return $children[0]->node_name(); - } - } - return false; - } + /** + * Get main type + * + * @return int ref id + */ + public function getMainType() + { + if (is_object($this->res_node)) { + $children = $this->res_node->child_nodes(); + if (is_object($children[0])) { + return $children[0]->node_name(); + } + } + return false; + } - /** - * Modify ref ids by mapping - * - * @param - * @return - */ - static function modifyItemGroupRefIdsByMapping($a_page, $mappings) - { - $dom = $a_page->getDom(); - - if ($dom instanceof php4DOMDocument) - { - $dom = $dom->myDOMDocument; - } + /** + * Modify ref ids by mapping + * + * @param + * @return + */ + public static function modifyItemGroupRefIdsByMapping($a_page, $mappings) + { + $dom = $a_page->getDom(); + + if ($dom instanceof php4DOMDocument) { + $dom = $dom->myDOMDocument; + } - $xpath_temp = new DOMXPath($dom); - $igs = $xpath_temp->query("//Resources/ItemGroup"); - - foreach ($igs as $ig_node) - { - $ref_id = $ig_node->getAttribute("RefId"); - if ($mappings[$ref_id] > 0) - { - $ig_node->setAttribute("RefId", $mappings[$ref_id]); - } - } - - } - - /** - * Get lang vars needed for editing - * @return array array of lang var keys - */ - static function getLangVars() - { - return array("pc_res"); - } - - /** - * Resolve resources - * - * @param ilPageObject $page - */ - static public function resolveResources(ilPageObject $page, $ref_mappings) - { - self::modifyItemGroupRefIdsByMapping($page, $ref_mappings); - } + $xpath_temp = new DOMXPath($dom); + $igs = $xpath_temp->query("//Resources/ItemGroup"); + + foreach ($igs as $ig_node) { + $ref_id = $ig_node->getAttribute("RefId"); + if ($mappings[$ref_id] > 0) { + $ig_node->setAttribute("RefId", $mappings[$ref_id]); + } + } + } + + /** + * Get lang vars needed for editing + * @return array array of lang var keys + */ + public static function getLangVars() + { + return array("pc_res"); + } + /** + * Resolve resources + * + * @param ilPageObject $page + */ + public static function resolveResources(ilPageObject $page, $ref_mappings) + { + self::modifyItemGroupRefIdsByMapping($page, $ref_mappings); + } } - -?> diff --git a/Services/COPage/classes/class.ilPCResourcesGUI.php b/Services/COPage/classes/class.ilPCResourcesGUI.php index 0cacc7b1964ee753f8b6caa479a03905d0be5d17..0e9ff590edaf19c899dd4fb1b559aff4dab654ce 100755 --- a/Services/COPage/classes/class.ilPCResourcesGUI.php +++ b/Services/COPage/classes/class.ilPCResourcesGUI.php @@ -16,360 +16,312 @@ require_once("./Services/COPage/classes/class.ilPageContentGUI.php"); */ class ilPCResourcesGUI extends ilPageContentGUI { - /** - * @var ilTree - */ - protected $rep_tree; + /** + * @var ilTree + */ + protected $rep_tree; - /** - * @var ilObjectDefinition - */ - protected $obj_definition; + /** + * @var ilObjectDefinition + */ + protected $obj_definition; - /** - * Constructor - * @access public - */ - function __construct(&$a_pg_obj, &$a_content_obj, $a_hier_id, $a_pc_id = "") - { - global $DIC; + /** + * 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->tpl = $DIC["tpl"]; - $this->lng = $DIC->language(); - $this->obj_definition = $DIC["objDefinition"]; - $tree = $DIC->repositoryTree(); - - $this->rep_tree = $tree; - parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); - } + $this->ctrl = $DIC->ctrl(); + $this->tpl = $DIC["tpl"]; + $this->lng = $DIC->language(); + $this->obj_definition = $DIC["objDefinition"]; + $tree = $DIC->repositoryTree(); + + $this->rep_tree = $tree; + 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); + /** + * 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(); + // get current command + $cmd = $this->ctrl->getCmd(); - switch($next_class) - { - default: - $ret = $this->$cmd(); - break; - } + switch ($next_class) { + default: + $ret = $this->$cmd(); + break; + } - return $ret; - } + return $ret; + } - /** - * Insert new resources component form. - */ - function insert() - { - $this->edit(true); - } + /** + * Insert new resources component form. + */ + public function insert() + { + $this->edit(true); + } - /** - * Edit resources form. - */ - function edit($a_insert = false) - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - $objDefinition = $this->obj_definition; - - $this->displayValidationError(); - - // edit form - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this)); - if ($a_insert) - { - $form->setTitle($this->lng->txt("cont_insert_resources")); - } - else - { - $form->setTitle($this->lng->txt("cont_update_resources")); - } - - // count number of existing objects per type and collect item groups - $ref_id = (int) $_GET["ref_id"]; - $childs = $this->rep_tree->getChilds($ref_id); - $type_counts = array(); - $item_groups = array(); - foreach ($childs as $c) - { - // see bug #12471 - //echo "
          -".$c["type"]."-".$objDefinition->getGroupOfObj($c["type"])."-"; - $key = ($objDefinition->getGroupOfObj($c["type"]) != "") - ? $objDefinition->getGroupOfObj($c["type"]) - : $c["type"]; - $type_counts[$key] += 1; - if ($c["type"] == "itgr") - { - $item_groups[$c["ref_id"]] = $c["title"]; - } - } - - if (count($item_groups) > 0) - { - // radio group for type selection - $radg = new ilRadioGroupInputGUI($lng->txt("cont_resources"), "res_type"); - if (!$a_insert && $this->content_obj->getMainType() == "ItemGroup") - { - $radg->setValue("itgr"); - } - else - { - $radg->setValue("by_type"); - } - - $op_type = new ilRadioOption($lng->txt("cont_resources_of_type"), "by_type", ""); - $radg->addOption($op_type); - $op_itemgroup = new ilRadioOption($lng->txt("obj_itgr"), "itgr", ""); - $radg->addOption($op_itemgroup); - $form->addItem($radg); - } - - // type selection - $type_prop = new ilSelectInputGUI($this->lng->txt("cont_type"), - "type"); - $obj_id = ilObject::_lookupObjId($_GET["ref_id"]); - $obj_type = ilObject::_lookupType($obj_id); - $sub_objs = $objDefinition->getGroupedRepositoryObjectTypes($obj_type); - $types = array(); - foreach($sub_objs as $k => $so) - { - if ($k != "itgr") - { - $types[$k] = $this->lng->txt("objs_".$k)." (".(int) $type_counts[$k].")"; - } - } - $type_prop->setOptions($types); - $selected = ($a_insert) - ? "" - : $this->content_obj->getResourceListType(); - $type_prop->setValue($selected); - if (count($item_groups) > 0) - { - $op_type->addSubItem($type_prop); - } - else - { - $form->addItem($type_prop); - } - - if (count($item_groups) > 0) - { - // item groups - $options = $item_groups; - $si = new ilSelectInputGUI($this->lng->txt("obj_itgr"), "itgr"); - $si->setOptions($options); - $selected = ($a_insert) - ? "" - : $this->content_obj->getItemGroupRefId(); - $op_itemgroup->addSubItem($si); - } - - - // save/cancel buttons - if ($a_insert) - { - $form->addCommandButton("create_resources", $lng->txt("save")); - $form->addCommandButton("cancelCreate", $lng->txt("cancel")); - } - else - { - $form->addCommandButton("update_resources", $lng->txt("save")); - $form->addCommandButton("cancelUpdate", $lng->txt("cancel")); - } - $html = $form->getHTML(); - $tpl->setContent($html); - return $ret; + /** + * Edit resources form. + */ + public function edit($a_insert = false) + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + $objDefinition = $this->obj_definition; + + $this->displayValidationError(); + + // edit form + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this)); + if ($a_insert) { + $form->setTitle($this->lng->txt("cont_insert_resources")); + } else { + $form->setTitle($this->lng->txt("cont_update_resources")); + } + + // count number of existing objects per type and collect item groups + $ref_id = (int) $_GET["ref_id"]; + $childs = $this->rep_tree->getChilds($ref_id); + $type_counts = array(); + $item_groups = array(); + foreach ($childs as $c) { + // see bug #12471 + //echo "
          -".$c["type"]."-".$objDefinition->getGroupOfObj($c["type"])."-"; + $key = ($objDefinition->getGroupOfObj($c["type"]) != "") + ? $objDefinition->getGroupOfObj($c["type"]) + : $c["type"]; + $type_counts[$key] += 1; + if ($c["type"] == "itgr") { + $item_groups[$c["ref_id"]] = $c["title"]; + } + } + + if (count($item_groups) > 0) { + // radio group for type selection + $radg = new ilRadioGroupInputGUI($lng->txt("cont_resources"), "res_type"); + if (!$a_insert && $this->content_obj->getMainType() == "ItemGroup") { + $radg->setValue("itgr"); + } else { + $radg->setValue("by_type"); + } + + $op_type = new ilRadioOption($lng->txt("cont_resources_of_type"), "by_type", ""); + $radg->addOption($op_type); + $op_itemgroup = new ilRadioOption($lng->txt("obj_itgr"), "itgr", ""); + $radg->addOption($op_itemgroup); + $form->addItem($radg); + } + + // type selection + $type_prop = new ilSelectInputGUI( + $this->lng->txt("cont_type"), + "type" + ); + $obj_id = ilObject::_lookupObjId($_GET["ref_id"]); + $obj_type = ilObject::_lookupType($obj_id); + $sub_objs = $objDefinition->getGroupedRepositoryObjectTypes($obj_type); + $types = array(); + foreach ($sub_objs as $k => $so) { + if ($k != "itgr") { + $types[$k] = $this->lng->txt("objs_" . $k) . " (" . (int) $type_counts[$k] . ")"; + } + } + $type_prop->setOptions($types); + $selected = ($a_insert) + ? "" + : $this->content_obj->getResourceListType(); + $type_prop->setValue($selected); + if (count($item_groups) > 0) { + $op_type->addSubItem($type_prop); + } else { + $form->addItem($type_prop); + } + + if (count($item_groups) > 0) { + // item groups + $options = $item_groups; + $si = new ilSelectInputGUI($this->lng->txt("obj_itgr"), "itgr"); + $si->setOptions($options); + $selected = ($a_insert) + ? "" + : $this->content_obj->getItemGroupRefId(); + $op_itemgroup->addSubItem($si); + } + + + // save/cancel buttons + if ($a_insert) { + $form->addCommandButton("create_resources", $lng->txt("save")); + $form->addCommandButton("cancelCreate", $lng->txt("cancel")); + } else { + $form->addCommandButton("update_resources", $lng->txt("save")); + $form->addCommandButton("cancelUpdate", $lng->txt("cancel")); + } + $html = $form->getHTML(); + $tpl->setContent($html); + return $ret; + } - } + /** + * Create new Resources Component. + */ + public function create() + { + $this->content_obj = new ilPCResources($this->getPage()); + $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); + + if ($_POST["res_type"] != "itgr") { + $this->content_obj->setResourceListType(ilUtil::stripSlashes($_POST["type"])); + } else { + $this->content_obj->setItemGroupRefId(ilUtil::stripSlashes($_POST["itgr"])); + } + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } else { + $this->insert(); + } + } - /** - * Create new Resources Component. - */ - function create() - { - $this->content_obj = new ilPCResources($this->getPage()); - $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); - - if ($_POST["res_type"] != "itgr") - { - $this->content_obj->setResourceListType(ilUtil::stripSlashes($_POST["type"])); - } - else - { - $this->content_obj->setItemGroupRefId(ilUtil::stripSlashes($_POST["itgr"])); - } - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - else - { - $this->insert(); - } - } + /** + * Update Resources Component. + */ + public function update() + { + if ($_POST["res_type"] != "itgr") { + $this->content_obj->setResourceListType(ilUtil::stripSlashes($_POST["type"])); + } else { + $this->content_obj->setItemGroupRefId(ilUtil::stripSlashes($_POST["itgr"])); + } + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } else { + $this->pg_obj->addHierIDs(); + $this->edit(); + } + } + + /** + * Insert resources + * + * @param + * @return + */ + public static function insertResourcesIntoPageContent($a_content) + { + global $DIC; - /** - * Update Resources Component. - */ - function update() - { - if ($_POST["res_type"] != "itgr") - { - $this->content_obj->setResourceListType(ilUtil::stripSlashes($_POST["type"])); - } - else - { - $this->content_obj->setItemGroupRefId(ilUtil::stripSlashes($_POST["itgr"])); - } - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - else - { - $this->pg_obj->addHierIDs(); - $this->edit(); - } - } - - /** - * Insert resources - * - * @param - * @return - */ - static function insertResourcesIntoPageContent($a_content) - { - global $DIC; + $objDefinition = $DIC["objDefinition"]; + $tree = $DIC->repositoryTree(); + $lng = $DIC->language(); - $objDefinition = $DIC["objDefinition"]; - $tree = $DIC->repositoryTree(); - $lng = $DIC->language(); + $ref_id = (int) $_GET["ref_id"]; + $obj_id = (int) ilObject::_lookupObjId($ref_id); + $obj_type = ilObject::_lookupType($obj_id); + + // determine type -> group + $type_to_grp = array(); + $type_grps = + $objDefinition->getGroupedRepositoryObjectTypes($obj_type); + foreach ($type_grps as $grp => $def) { + foreach ($def["objs"] as $t) { + $type_to_grp[$t] = $grp; + } + } - $ref_id = (int) $_GET["ref_id"]; - $obj_id = (int) ilObject::_lookupObjId($ref_id); - $obj_type = ilObject::_lookupType($obj_id); - - // determine type -> group - $type_to_grp = array(); - $type_grps = - $objDefinition->getGroupedRepositoryObjectTypes($obj_type); - foreach ($type_grps as $grp => $def) - { - foreach ($def["objs"] as $t) - { - $type_to_grp[$t] = $grp; - } - } + $childs = $tree->getChilds($ref_id); + $childs_by_type = array(); + $item_groups = array(); + foreach ($childs as $child) { + $childs_by_type[$type_to_grp[$child["type"]]][] = $child; + if ($child["type"] == "itgr") { + $item_groups[(int) $child["ref_id"]] = $child["title"]; + } + } - $childs = $tree->getChilds($ref_id); - $childs_by_type = array(); - $item_groups = array(); - foreach ($childs as $child) - { - $childs_by_type[$type_to_grp[$child["type"]]][] = $child; - if ($child["type"] == "itgr") - { - $item_groups[(int) $child["ref_id"]] = $child["title"]; - } - } + // handle "by type" lists + foreach ($type_grps as $type => $v) { + if (is_int(strpos($a_content, "[list-" . $type . "]"))) { + // render block + $tpl = new ilTemplate("tpl.resource_block.html", true, true, "Services/COPage"); + $cnt = 0; + + if (is_array($childs_by_type[$type]) && count($childs_by_type[$type]) > 0) { + foreach ($childs_by_type[$type] as $child) { + $tpl->setCurrentBlock("row"); + $tpl->setVariable("IMG", ilUtil::img(ilObject::_getIcon($child["obj_id"], "small"))); + $tpl->setVariable("TITLE", $child["title"]); + $tpl->parseCurrentBlock(); + $cnt++; + } + $tpl->setVariable("HEADER", $lng->txt("objs_" . $type)); + $a_content = str_replace("[list-" . $type . "]", $tpl->get(), $a_content); + } else { + $tpl->setCurrentBlock("row"); + $tpl->setVariable("TITLE", $lng->txt("no_items")); + $tpl->parseCurrentBlock(); + $tpl->setVariable("HEADER", $lng->txt("objs_" . $type)); + $a_content = str_replace("[list-" . $type . "]", $tpl->get(), $a_content); + } + } + } + + // handle item groups + while (preg_match('/\[(item-group-([0-9]*))\]/i', $a_content, $found)) { + $itgr_ref_id = (int) $found[2]; + + // check whether this item group is child -> insert editing html + if (isset($item_groups[$itgr_ref_id])) { + include_once("./Modules/ItemGroup/classes/class.ilItemGroupItems.php"); + $itgr_items = new ilItemGroupItems($itgr_ref_id); + $items = $itgr_items->getValidItems(); + + // render block + $tpl = new ilTemplate("tpl.resource_block.html", true, true, "Services/COPage"); + foreach ($items as $it_ref_id) { + $it_obj_id = ilObject::_lookupObjId($it_ref_id); + $it_title = ilObject::_lookupTitle($it_obj_id); + $it_type = ilObject::_lookupType($it_obj_id); - // handle "by type" lists - foreach ($type_grps as $type => $v) - { - if (is_int(strpos($a_content, "[list-".$type."]"))) - { - // render block - $tpl = new ilTemplate("tpl.resource_block.html", true, true, "Services/COPage"); - $cnt = 0; - - if (is_array($childs_by_type[$type]) && count($childs_by_type[$type]) > 0) - { - foreach ($childs_by_type[$type] as $child) - { - $tpl->setCurrentBlock("row"); - $tpl->setVariable("IMG", ilUtil::img(ilObject::_getIcon($child["obj_id"], "small"))); - $tpl->setVariable("TITLE", $child["title"]); - $tpl->parseCurrentBlock(); - $cnt++; - } - $tpl->setVariable("HEADER", $lng->txt("objs_".$type)); - $a_content = str_replace("[list-".$type."]", $tpl->get(), $a_content); - } - else - { - $tpl->setCurrentBlock("row"); - $tpl->setVariable("TITLE", $lng->txt("no_items")); - $tpl->parseCurrentBlock(); - $tpl->setVariable("HEADER", $lng->txt("objs_".$type)); - $a_content = str_replace("[list-".$type."]", $tpl->get(), $a_content); - } - } - } - - // handle item groups - while (preg_match('/\[(item-group-([0-9]*))\]/i', $a_content, $found)) - { - $itgr_ref_id = (int) $found[2]; - - // check whether this item group is child -> insert editing html - if (isset($item_groups[$itgr_ref_id])) - { - include_once("./Modules/ItemGroup/classes/class.ilItemGroupItems.php"); - $itgr_items = new ilItemGroupItems($itgr_ref_id); - $items = $itgr_items->getValidItems(); - - // render block - $tpl = new ilTemplate("tpl.resource_block.html", true, true, "Services/COPage"); - foreach ($items as $it_ref_id) - { - $it_obj_id = ilObject::_lookupObjId($it_ref_id); - $it_title = ilObject::_lookupTitle($it_obj_id); - $it_type = ilObject::_lookupType($it_obj_id); + // TODO: Handle this switch by module.xml definitions + if (in_array($it_type, array("catr", "crsr", "grpr"))) { + include_once('./Services/ContainerReference/classes/class.ilContainerReference.php'); + $it_title = ilContainerReference::_lookupTitle($it_obj_id); + } - // TODO: Handle this switch by module.xml definitions - if(in_array($it_type, array("catr", "crsr", "grpr"))) - { - include_once('./Services/ContainerReference/classes/class.ilContainerReference.php'); - $it_title = ilContainerReference::_lookupTitle($it_obj_id); - } + $tpl->setCurrentBlock("row"); + $tpl->setVariable("IMG", ilUtil::img(ilObject::_getIcon($it_obj_id, "small"))); + $tpl->setVariable("TITLE", $it_title); + $tpl->parseCurrentBlock(); + } + $tpl->setVariable("HEADER", $item_groups[$itgr_ref_id]); + $html = $tpl->get(); + } else { + $html = "" . $lng->txt("cont_element_refers_removed_itgr") . ""; + } + $a_content = preg_replace('/\[' . $found[1] . '\]/i', $html, $a_content); + } + - $tpl->setCurrentBlock("row"); - $tpl->setVariable("IMG", ilUtil::img(ilObject::_getIcon($it_obj_id, "small"))); - $tpl->setVariable("TITLE", $it_title); - $tpl->parseCurrentBlock(); - } - $tpl->setVariable("HEADER", $item_groups[$itgr_ref_id]); - $html = $tpl->get(); - } - else - { - $html = "".$lng->txt("cont_element_refers_removed_itgr").""; - } - $a_content = preg_replace('/\['.$found[1].'\]/i', $html, $a_content); - } - - - return $a_content; - } - + return $a_content; + } } -?> diff --git a/Services/COPage/classes/class.ilPCSection.php b/Services/COPage/classes/class.ilPCSection.php index 982da4d71282aecf9e4cb010b3a176b86a3b9cb2..f5223d7f4c21c10c64df09be744eeee10061588e 100755 --- a/Services/COPage/classes/class.ilPCSection.php +++ b/Services/COPage/classes/class.ilPCSection.php @@ -16,524 +16,496 @@ require_once("./Services/COPage/classes/class.ilPageContent.php"); */ class ilPCSection extends ilPageContent { - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - var $dom; - var $sec_node; - - /** - * Init page content component. - */ - function init() - { - global $DIC; - - $this->access = $DIC->access(); - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->setType("sec"); - } - - /** - * Set node - */ - function setNode($a_node) - { - parent::setNode($a_node); // this is the PageContent node - $this->sec_node = $a_node->first_child(); // this is the Section node - } - - /** - * Create section node in xml. - * - * @param object $a_pg_obj Page Object - * @param string $a_hier_id Hierarchical ID - */ - 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->sec_node = $this->dom->create_element("Section"); - $this->sec_node = $this->node->append_child($this->sec_node); - $this->sec_node->set_attribute("Characteristic", "Block"); - } - - /** - * Set Characteristic of section - * - * @param string $a_char Characteristic - */ - function setCharacteristic($a_char) - { - if (!empty($a_char)) - { - $this->sec_node->set_attribute("Characteristic", $a_char); - } - else - { - if ($this->sec_node->has_attribute("Characteristic")) - { - $this->sec_node->remove_attribute("Characteristic"); - } - } - } - - /** - * Get characteristic of section. - * - * @return string characteristic - */ - function getCharacteristic() - { - if (is_object($this->sec_node)) - { - $char = $this->sec_node->get_attribute("Characteristic"); - if (substr($char, 0, 4) == "ilc_") - { - $char = substr($char, 4); - } - return $char; - } - } - - /** - * Get lang vars needed for editing - * @return array array of lang var keys - */ - static function getLangVars() - { - return array("ed_insert_section"); - } - - /** - * After page has been updated (or created) - * - * @param object $a_page page object - * @param DOMDocument $a_domdoc dom document - * @param string $a_xml xml - * @param bool $a_creation true on creation, otherwise false - */ - static function afterPageUpdate($a_page, DOMDocument $a_domdoc, $a_xml, $a_creation) - { - include_once("./Services/COPage/classes/class.ilPCSection.php"); - self::saveTimings($a_page); - } - - /** - * Modify page content after xsl - * - * @param string $a_output - * @return string - */ - function modifyPageContentPostXsl($a_output, $a_mode) - { - $a_output = self::insertTimings($a_output); - $a_output = $this->handleAccess($a_output, $a_mode); - - return $a_output; - } - - /** - * Set activation from - * - * @param string $a_unix_ts unix ts activation from - */ - function setActiveFrom($a_unix_ts) - { - if ($a_unix_ts > 0) - { - $this->sec_node->set_attribute("ActiveFrom", $a_unix_ts); - } - else - { - if ($this->sec_node->has_attribute("ActiveFrom")) - { - $this->sec_node->remove_attribute("ActiveFrom"); - } - } - } - - /** - * Get activation from - * - * @return string unix ts activation from - */ - function getActiveFrom() - { - if (is_object($this->sec_node)) - { - return $this->sec_node->get_attribute("ActiveFrom"); - } - - return ""; - } - - /** - * Set activation to - * - * @param string $a_unix_ts unix ts activation to - */ - function setActiveTo($a_unix_ts) - { - if ($a_unix_ts > 0) - { - $this->sec_node->set_attribute("ActiveTo", $a_unix_ts); - } - else - { - if ($this->sec_node->has_attribute("ActiveTo")) - { - $this->sec_node->remove_attribute("ActiveTo"); - } - } - } - - /** - * Get activation to - * - * @return string unix ts activation to - */ - function getActiveTo() - { - if (is_object($this->sec_node)) - { - return $this->sec_node->get_attribute("ActiveTo"); - } - - return ""; - } - - /** - * Set attribute - * - * @param string $a_attr attribute - * @param string $a_val attribute value - */ - protected function setAttribute($a_attr, $a_val) - { - if (!empty($a_val)) - { - $this->sec_node->set_attribute($a_attr, $a_val); - } - else - { - if ($this->sec_node->has_attribute($a_attr)) - { - $this->sec_node->remove_attribute($a_attr); - } - } - } - - /** - * Get attribute - * - * @param string $a_attr attribute - * @return string attribute value - */ - function getAttribute($a_attr) - { - if (is_object($this->sec_node)) - { - return $this->sec_node->get_attribute($a_attr); - } - return ""; - } - - /** - * Set permission - * - * @param string $a_val "read"|"write"|"visible" - */ - function setPermission($a_val) - { - $this->setAttribute("Permission", $a_val); - } - - /** - * Get permission - * - * @return string - */ - function getPermission() - { - return $this->getAttribute("Permission"); - } - - - /** - * Set permission ref id - * - * @param integer $a_ref_id ref id - */ - function setPermissionRefId($a_ref_id) - { - $this->setAttribute("PermissionRefId", "il__ref_".$a_ref_id); - } - - /** - * Get permission ref id - * - * @return int ref id - */ - function getPermissionRefId() - { - $id = explode("_", $this->getAttribute("PermissionRefId")); - if (in_array($id[1], array("", 0, IL_INST_ID))) - { - return $id[3]; - } - return ""; - } - - /** - * Set no link - */ - function setNoLink() - { - ilDOMUtil::deleteAllChildsByName($this->sec_node, array("IntLink", "ExtLink")); - } - - /** - * Set link of area to an external one - * @param string $a_href - */ - function setExtLink($a_href) - { - $this->setNoLink(); - if (trim($a_href) != "") - { - $attributes = array("Href" => trim($a_href)); - ilDOMUtil::setFirstOptionalElement($this->dom, $this->sec_node, "ExtLink", - array(""), "", $attributes); - } - } - - /** - * Set link of area to an internal one - */ - function setIntLink($a_type, $a_target, $a_target_frame) - { - $this->setNoLink(); - $attributes = array("Type" => $a_type, "Target" => $a_target, - "TargetFrame" => $a_target_frame); - ilDOMUtil::setFirstOptionalElement($this->dom, $this->sec_node, "IntLink", - array(""), "", $attributes); - } - - /** - * Get link - * - * @param - * @return - */ - function getLink() - { - $childs = $this->sec_node->child_nodes(); - foreach($childs as $child) - { - if ($child->node_name() == "ExtLink") - { - return array("LinkType" => "ExtLink", - "Href" => $child->get_attribute("Href")); - } - if ($child->node_name() == "IntLink") - { - return array("LinkType" => "IntLink", - "Target" => $child->get_attribute("Target"), - "Type" => $child->get_attribute("Type"), - "TargetFrame" => $child->get_attribute("TargetFrame")); - } - } - return array("LinkType" => "NoLink"); - } - - - /** - * @param $a_html - * @param $a_mode - * @return mixed|string - */ - function handleAccess($a_html, $a_mode) - { - $ilAccess = $this->access; - - while (($start = strpos($a_html, "{{{{{Section;Access;")) > 0) - { - $end = strpos($a_html, "}}}}}", $start); - $access_attr = explode(";", substr($a_html, $start, $end - $start)); - $id = explode("_", $access_attr[3]); - $access = true; - if (in_array($id[1], array("", 0, IL_INST_ID)) && $id[3] > 0) - { - $access = $ilAccess->checkAccess($access_attr[5], "", $id[3]); - } - if ($access) - { - $a_html = substr($a_html, 0, $start).substr($a_html, $end + 5); - } - else - { - $end = strpos($a_html, "{{{{{Section;Access}}}}}", $start); - $a_html = substr($a_html, 0, $start).substr($a_html, $end + 24); - } - } - - $a_html = str_replace("{{{{{Section;Access}}}}}", "", $a_html); - - return $a_html; - } - - /** - * Save timings - * - * @param ilPageObject $a_page page object - */ - static function saveTimings($a_page) - { - global $DIC; - - $ilDB = $DIC->database(); - - $ilDB->manipulate("DELETE FROM copg_section_timings WHERE ". - " page_id = ".$ilDB->quote($a_page->getId(), "integer"). - " AND parent_type = ".$ilDB->quote($a_page->getParentType(), "text") - ); - - $xml = $a_page->getXMLFromDom(); - - $doc = domxml_open_mem($xml); - - // media aliases - $xpc = xpath_new_context($doc); - $path = "//Section"; - $res = xpath_eval($xpc, $path); - for ($i=0; $i < count($res->nodeset); $i++) - { - $from = $res->nodeset[$i]->get_attribute("ActiveFrom"); - if ($from != "") - { - $ilDB->replace("copg_section_timings", - array( - "page_id" => array("integer", $a_page->getId()), - "parent_type" => array("text", $a_page->getParentType()), - "unix_ts" => array("integer", $from) - ), - array() - ); - } - $to = $res->nodeset[$i]->get_attribute("ActiveTo"); - if ($to != "") - { - $ilDB->replace("copg_section_timings", - array( - "page_id" => array("integer", $a_page->getId()), - "parent_type" => array("text", $a_page->getParentType()), - "unix_ts" => array("integer", $to) - ), - array() - ); - } - } - } - - /** - * Get page cache update trigger string - * - * @param ilPageObject $a_page - * @return string trigger string - */ - static function getCacheTriggerString($a_page) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT * FROM copg_section_timings ". - " WHERE page_id = ".$ilDB->quote($a_page->getId(), "integer"). - " AND parent_type = ".$ilDB->quote($a_page->getParentType(), "text") - ); - $str = ""; - $current_ts = new ilDateTime(time(),IL_CAL_UNIX); - $current_ts = $current_ts->get(IL_CAL_UNIX); - while ($rec = $ilDB->fetchAssoc($set)) - { - $unix_ts = $rec["unix_ts"]; - if ($unix_ts < $current_ts) - { - $unix_ts.= "a"; - } - $str.= "-".$unix_ts; - } - - return $str; - } - - /** - * Insert timings (in edit mode) - * - * @param string $a_html html - * @return string htmls - */ - function insertTimings($a_html) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $c_pos = 0; - $start = strpos($a_html, "{{{{{Section;ActiveFrom"); - if (is_int($start)) - { - $end = strpos($a_html, "}}}}}", $start); - } - $i = 1; - while ($end > 0) - { - $param = substr($a_html, $start + 13, $end - $start - 13); - $param = explode(";", $param); - $from = $param[1]; - $to = $param[3]; - $html = ""; - if ($from != "") - { - ilDatePresentation::setUseRelativeDates(false); - $from = new ilDateTime($from, IL_CAL_UNIX); - $html.= $lng->txt("cont_active_from").": ".ilDatePresentation::formatDate($from); - } - if ($to != "") - { - $to = new ilDateTime($to, IL_CAL_UNIX); - $html.= " ".$lng->txt("cont_active_to").": ".ilDatePresentation::formatDate($to); - } - - $h2 = substr($a_html, 0, $start). - $html. - substr($a_html, $end + 5); - $a_html = $h2; - $i++; - - $start = strpos($a_html, "{{{{{Section;ActiveFrom;", $start + 5); - $end = 0; - if (is_int($start)) - { - $end = strpos($a_html, "}}}}}", $start); - } - } - return $a_html; - } - + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + public $dom; + public $sec_node; + + /** + * Init page content component. + */ + public function init() + { + global $DIC; + + $this->access = $DIC->access(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->setType("sec"); + } + + /** + * Set node + */ + public function setNode($a_node) + { + parent::setNode($a_node); // this is the PageContent node + $this->sec_node = $a_node->first_child(); // this is the Section node + } + + /** + * Create section node in xml. + * + * @param object $a_pg_obj Page Object + * @param string $a_hier_id Hierarchical ID + */ + public 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->sec_node = $this->dom->create_element("Section"); + $this->sec_node = $this->node->append_child($this->sec_node); + $this->sec_node->set_attribute("Characteristic", "Block"); + } + + /** + * Set Characteristic of section + * + * @param string $a_char Characteristic + */ + public function setCharacteristic($a_char) + { + if (!empty($a_char)) { + $this->sec_node->set_attribute("Characteristic", $a_char); + } else { + if ($this->sec_node->has_attribute("Characteristic")) { + $this->sec_node->remove_attribute("Characteristic"); + } + } + } + + /** + * Get characteristic of section. + * + * @return string characteristic + */ + public function getCharacteristic() + { + if (is_object($this->sec_node)) { + $char = $this->sec_node->get_attribute("Characteristic"); + if (substr($char, 0, 4) == "ilc_") { + $char = substr($char, 4); + } + return $char; + } + } + + /** + * Get lang vars needed for editing + * @return array array of lang var keys + */ + public static function getLangVars() + { + return array("ed_insert_section"); + } + + /** + * After page has been updated (or created) + * + * @param object $a_page page object + * @param DOMDocument $a_domdoc dom document + * @param string $a_xml xml + * @param bool $a_creation true on creation, otherwise false + */ + public static function afterPageUpdate($a_page, DOMDocument $a_domdoc, $a_xml, $a_creation) + { + include_once("./Services/COPage/classes/class.ilPCSection.php"); + self::saveTimings($a_page); + } + + /** + * Modify page content after xsl + * + * @param string $a_output + * @return string + */ + public function modifyPageContentPostXsl($a_output, $a_mode) + { + $a_output = self::insertTimings($a_output); + $a_output = $this->handleAccess($a_output, $a_mode); + + return $a_output; + } + + /** + * Set activation from + * + * @param string $a_unix_ts unix ts activation from + */ + public function setActiveFrom($a_unix_ts) + { + if ($a_unix_ts > 0) { + $this->sec_node->set_attribute("ActiveFrom", $a_unix_ts); + } else { + if ($this->sec_node->has_attribute("ActiveFrom")) { + $this->sec_node->remove_attribute("ActiveFrom"); + } + } + } + + /** + * Get activation from + * + * @return string unix ts activation from + */ + public function getActiveFrom() + { + if (is_object($this->sec_node)) { + return $this->sec_node->get_attribute("ActiveFrom"); + } + + return ""; + } + + /** + * Set activation to + * + * @param string $a_unix_ts unix ts activation to + */ + public function setActiveTo($a_unix_ts) + { + if ($a_unix_ts > 0) { + $this->sec_node->set_attribute("ActiveTo", $a_unix_ts); + } else { + if ($this->sec_node->has_attribute("ActiveTo")) { + $this->sec_node->remove_attribute("ActiveTo"); + } + } + } + + /** + * Get activation to + * + * @return string unix ts activation to + */ + public function getActiveTo() + { + if (is_object($this->sec_node)) { + return $this->sec_node->get_attribute("ActiveTo"); + } + + return ""; + } + + /** + * Set attribute + * + * @param string $a_attr attribute + * @param string $a_val attribute value + */ + protected function setAttribute($a_attr, $a_val) + { + if (!empty($a_val)) { + $this->sec_node->set_attribute($a_attr, $a_val); + } else { + if ($this->sec_node->has_attribute($a_attr)) { + $this->sec_node->remove_attribute($a_attr); + } + } + } + + /** + * Get attribute + * + * @param string $a_attr attribute + * @return string attribute value + */ + public function getAttribute($a_attr) + { + if (is_object($this->sec_node)) { + return $this->sec_node->get_attribute($a_attr); + } + return ""; + } + + /** + * Set permission + * + * @param string $a_val "read"|"write"|"visible" + */ + public function setPermission($a_val) + { + $this->setAttribute("Permission", $a_val); + } + + /** + * Get permission + * + * @return string + */ + public function getPermission() + { + return $this->getAttribute("Permission"); + } + + + /** + * Set permission ref id + * + * @param integer $a_ref_id ref id + */ + public function setPermissionRefId($a_ref_id) + { + $this->setAttribute("PermissionRefId", "il__ref_" . $a_ref_id); + } + + /** + * Get permission ref id + * + * @return int ref id + */ + public function getPermissionRefId() + { + $id = explode("_", $this->getAttribute("PermissionRefId")); + if (in_array($id[1], array("", 0, IL_INST_ID))) { + return $id[3]; + } + return ""; + } + + /** + * Set no link + */ + public function setNoLink() + { + ilDOMUtil::deleteAllChildsByName($this->sec_node, array("IntLink", "ExtLink")); + } + + /** + * Set link of area to an external one + * @param string $a_href + */ + public function setExtLink($a_href) + { + $this->setNoLink(); + if (trim($a_href) != "") { + $attributes = array("Href" => trim($a_href)); + ilDOMUtil::setFirstOptionalElement( + $this->dom, + $this->sec_node, + "ExtLink", + array(""), + "", + $attributes + ); + } + } + + /** + * Set link of area to an internal one + */ + public function setIntLink($a_type, $a_target, $a_target_frame) + { + $this->setNoLink(); + $attributes = array("Type" => $a_type, "Target" => $a_target, + "TargetFrame" => $a_target_frame); + ilDOMUtil::setFirstOptionalElement( + $this->dom, + $this->sec_node, + "IntLink", + array(""), + "", + $attributes + ); + } + + /** + * Get link + * + * @param + * @return + */ + public function getLink() + { + $childs = $this->sec_node->child_nodes(); + foreach ($childs as $child) { + if ($child->node_name() == "ExtLink") { + return array("LinkType" => "ExtLink", + "Href" => $child->get_attribute("Href")); + } + if ($child->node_name() == "IntLink") { + return array("LinkType" => "IntLink", + "Target" => $child->get_attribute("Target"), + "Type" => $child->get_attribute("Type"), + "TargetFrame" => $child->get_attribute("TargetFrame")); + } + } + return array("LinkType" => "NoLink"); + } + + + /** + * @param $a_html + * @param $a_mode + * @return mixed|string + */ + public function handleAccess($a_html, $a_mode) + { + $ilAccess = $this->access; + + while (($start = strpos($a_html, "{{{{{Section;Access;")) > 0) { + $end = strpos($a_html, "}}}}}", $start); + $access_attr = explode(";", substr($a_html, $start, $end - $start)); + $id = explode("_", $access_attr[3]); + $access = true; + if (in_array($id[1], array("", 0, IL_INST_ID)) && $id[3] > 0) { + $access = $ilAccess->checkAccess($access_attr[5], "", $id[3]); + } + if ($access) { + $a_html = substr($a_html, 0, $start) . substr($a_html, $end + 5); + } else { + $end = strpos($a_html, "{{{{{Section;Access}}}}}", $start); + $a_html = substr($a_html, 0, $start) . substr($a_html, $end + 24); + } + } + + $a_html = str_replace("{{{{{Section;Access}}}}}", "", $a_html); + + return $a_html; + } + + /** + * Save timings + * + * @param ilPageObject $a_page page object + */ + public static function saveTimings($a_page) + { + global $DIC; + + $ilDB = $DIC->database(); + + $ilDB->manipulate( + "DELETE FROM copg_section_timings WHERE " . + " page_id = " . $ilDB->quote($a_page->getId(), "integer") . + " AND parent_type = " . $ilDB->quote($a_page->getParentType(), "text") + ); + + $xml = $a_page->getXMLFromDom(); + + $doc = domxml_open_mem($xml); + + // media aliases + $xpc = xpath_new_context($doc); + $path = "//Section"; + $res = xpath_eval($xpc, $path); + for ($i=0; $i < count($res->nodeset); $i++) { + $from = $res->nodeset[$i]->get_attribute("ActiveFrom"); + if ($from != "") { + $ilDB->replace( + "copg_section_timings", + array( + "page_id" => array("integer", $a_page->getId()), + "parent_type" => array("text", $a_page->getParentType()), + "unix_ts" => array("integer", $from) + ), + array() + ); + } + $to = $res->nodeset[$i]->get_attribute("ActiveTo"); + if ($to != "") { + $ilDB->replace( + "copg_section_timings", + array( + "page_id" => array("integer", $a_page->getId()), + "parent_type" => array("text", $a_page->getParentType()), + "unix_ts" => array("integer", $to) + ), + array() + ); + } + } + } + + /** + * Get page cache update trigger string + * + * @param ilPageObject $a_page + * @return string trigger string + */ + public static function getCacheTriggerString($a_page) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT * FROM copg_section_timings " . + " WHERE page_id = " . $ilDB->quote($a_page->getId(), "integer") . + " AND parent_type = " . $ilDB->quote($a_page->getParentType(), "text") + ); + $str = ""; + $current_ts = new ilDateTime(time(), IL_CAL_UNIX); + $current_ts = $current_ts->get(IL_CAL_UNIX); + while ($rec = $ilDB->fetchAssoc($set)) { + $unix_ts = $rec["unix_ts"]; + if ($unix_ts < $current_ts) { + $unix_ts.= "a"; + } + $str.= "-" . $unix_ts; + } + + return $str; + } + + /** + * Insert timings (in edit mode) + * + * @param string $a_html html + * @return string htmls + */ + public function insertTimings($a_html) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $c_pos = 0; + $start = strpos($a_html, "{{{{{Section;ActiveFrom"); + if (is_int($start)) { + $end = strpos($a_html, "}}}}}", $start); + } + $i = 1; + while ($end > 0) { + $param = substr($a_html, $start + 13, $end - $start - 13); + $param = explode(";", $param); + $from = $param[1]; + $to = $param[3]; + $html = ""; + if ($from != "") { + ilDatePresentation::setUseRelativeDates(false); + $from = new ilDateTime($from, IL_CAL_UNIX); + $html.= $lng->txt("cont_active_from") . ": " . ilDatePresentation::formatDate($from); + } + if ($to != "") { + $to = new ilDateTime($to, IL_CAL_UNIX); + $html.= " " . $lng->txt("cont_active_to") . ": " . ilDatePresentation::formatDate($to); + } + + $h2 = substr($a_html, 0, $start) . + $html . + substr($a_html, $end + 5); + $a_html = $h2; + $i++; + + $start = strpos($a_html, "{{{{{Section;ActiveFrom;", $start + 5); + $end = 0; + if (is_int($start)) { + $end = strpos($a_html, "}}}}}", $start); + } + } + return $a_html; + } } - -?> diff --git a/Services/COPage/classes/class.ilPCSectionGUI.php b/Services/COPage/classes/class.ilPCSectionGUI.php index 9943246b1aacd577c788e41cb2268c406f232186..1fe61fe586b6aeb34f9afd9b1af659d53c811220 100755 --- a/Services/COPage/classes/class.ilPCSectionGUI.php +++ b/Services/COPage/classes/class.ilPCSectionGUI.php @@ -19,380 +19,343 @@ require_once("./Services/COPage/classes/class.ilPageContentGUI.php"); class ilPCSectionGUI extends ilPageContentGUI { - /** - * Constructor - * @access public - */ - function __construct(&$a_pg_obj, &$a_content_obj, $a_hier_id, $a_pc_id = "") - { - global $DIC; - - $this->tpl = $DIC["tpl"]; - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); - - $this->setCharacteristics(ilPCSectionGUI::_getStandardCharacteristics()); - } - - /** - * Get standard characteristics - */ - static function _getStandardCharacteristics() - { - global $DIC; - - $lng = $DIC->language(); - - return array("Block" => $lng->txt("cont_Block"), - "Mnemonic" => $lng->txt("cont_Mnemonic"), - "Remark" => $lng->txt("cont_Remark"), - "Example" => $lng->txt("cont_Example"), - "Additional" => $lng->txt("cont_Additional"), - "Special" => $lng->txt("cont_Special"), - - "Attention" => $lng->txt("cont_Attention"), - "Background" => $lng->txt("cont_Background"), - "Confirmation" => $lng->txt("cont_Confirmation"), - "Information" => $lng->txt("cont_Information"), - "Interaction" => $lng->txt("cont_Interaction"), - "Link" => $lng->txt("cont_Link"), - "Literature" => $lng->txt("cont_Literature"), - "Separator" => $lng->txt("cont_Separator"), - "StandardCenter" => $lng->txt("cont_StandardCenter"), - - "Excursus" => $lng->txt("cont_Excursus"), - "AdvancedKnowledge" => $lng->txt("cont_AdvancedKnowledge")); - } - - /** - * Get characteristics - */ - static function _getCharacteristics($a_style_id) - { - $chars = ilPCSectionGUI::_getStandardCharacteristics(); - - if ($a_style_id > 0 && - ilObject::_lookupType($a_style_id) == "sty") - { - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $style = new ilObjStyleSheet($a_style_id); - $chars = $style->getCharacteristics("section"); - $new_chars = array(); - foreach ($chars as $char) - { - if ($chars[$char] != "") // keep lang vars for standard chars - { - $new_chars[$char] = $chars[$char]; - } - else - { - $new_chars[$char] = $char; - } - asort($new_chars); - } - $chars = $new_chars; - } - return $chars; - } - - /** - * execute command - */ - function executeCommand() - { - $this->getCharacteristicsOfCurrentStyle("section"); // scorm-2004 - - // 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) - { - case "ilpropertyformgui": - include_once './Services/Form/classes/class.ilPropertyFormGUI.php'; - $form = $this->initForm(true); - $this->ctrl->forwardCommand($form); - break; - - default: - $ret = $this->$cmd(); - break; - } - - return $ret; - } - - /** - * Insert new section form. - */ - function insert(ilPropertyFormGUI $a_form = null) - { - $this->edit(true, $a_form); - } - - /** - * Edit section form. - */ - function edit($a_insert = false, ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - - $this->displayValidationError(); - - if(!$a_form) - { - $a_form = $this->initForm($a_insert); - } - - $tpl->setContent($a_form->getHTML()); - } - - /** - * Init editing form - */ - public function initForm($a_insert = false) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - // edit form - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this)); - if ($a_insert) - { - $form->setTitle($this->lng->txt("cont_insert_section")); - } - else - { - $form->setTitle($this->lng->txt("cont_update_section")); - } - - // characteristic selection - require_once("./Services/Form/classes/class.ilAdvSelectInputGUI.php"); - $char_prop = new ilAdvSelectInputGUI($this->lng->txt("cont_characteristic"), - "characteristic"); - - $chars = $this->getCharacteristics(); - if (is_object($this->content_obj)) - { - if ($chars[$a_seleted_value] == "" && ($this->content_obj->getCharacteristic() != "")) - { - $chars = array_merge( - array($this->content_obj->getCharacteristic() => $this->content_obj->getCharacteristic()), - $chars); - } - } - - $selected = ($a_insert) - ? "Block" - : $this->content_obj->getCharacteristic(); - - foreach($chars as $k => $char) - { - $html = '
          '. - $char.'
          '; - $char_prop->addOption($k, $char, $html); - } - - $char_prop->setValue($selected); - $form->addItem($char_prop); - - // link input - include_once 'Services/Form/classes/class.ilLinkInputGUI.php'; - $ac = new ilLinkInputGUI($this->lng->txt('cont_link'), 'link'); - $ac->setAllowedLinkTypes(ilLinkInputGUI::BOTH); - $ac->setRequired(false); - $ac->setInfo($this->lng->txt("copg_sec_link_info")); - $ac->setInternalLinkDefault($this->getPageConfig()->getIntLinkHelpDefaultType(), - $this->getPageConfig()->getIntLinkHelpDefaultId()); - $link_types = array(); - foreach ($this->getPageConfig()->getIntLinkFilters() as $f) - { - $link_types[] = $f; - } - $ac->setInternalLinkFilterTypes($link_types); - $ac->setFilterWhiteList( - $this->getPageConfig()->getIntLinkFilterWhiteList()); - - if (!$a_insert) - { - $l = $this->content_obj->getLink(); - if ($l["LinkType"] == "IntLink") - { - $ac->setValueByIntLinkAttributes($l["Type"], $l["Target"], $l["TargetFrame"]); - } - if ($l["LinkType"] == "ExtLink") - { - $ac->setValue($l["Href"]); - } - } - $form->addItem($ac); - - // activation - - // active from - $dt_prop = new ilDateTimeInputGUI($lng->txt("cont_active_from"), "active_from"); - if (!$a_insert && ($from = $this->content_obj->getActiveFrom()) != "") - { - $dt_prop->setDate(new ilDateTime($from, IL_CAL_UNIX)); - } - $dt_prop->setShowTime(true); - $form->addItem($dt_prop); - - // active to - $dt_prop = new ilDateTimeInputGUI($lng->txt("cont_active_to"), "active_to"); - if (!$a_insert && ($to = $this->content_obj->getActiveTo()) != "") - { - $dt_prop->setDate(new ilDateTime($to, IL_CAL_UNIX)); - } - $dt_prop->setShowTime(true); - $form->addItem($dt_prop); - - // rep selector - if ($this->getPageConfig()->getEnablePermissionChecks()) - { - include_once("./Services/Form/classes/class.ilRepositorySelector2InputGUI.php"); - $rs = new ilRepositorySelector2InputGUI($lng->txt("cont_permission_object"), "permission_ref_id"); - $rs->setParent($this); - $form->addItem($rs); - - // permission - $options = array( - "read" => $lng->txt("read"), - "write" => $lng->txt("write"), - "visible" => $lng->txt("visible"), - ); - $si = new ilSelectInputGUI($lng->txt("permission"), "permission"); - $si->setInfo($lng->txt("cont_permission_object_desc")); - $si->setOptions($options); - $form->addItem($si); - - if (!$a_insert) - { - $si->setValue($this->content_obj->getPermission()); - $rs->setValue($this->content_obj->getPermissionRefId()); - } - } - - // save/cancel buttons - if ($a_insert) - { - $form->addCommandButton("create_section", $lng->txt("save")); - $form->addCommandButton("cancelCreate", $lng->txt("cancel")); - } - else - { - $form->addCommandButton("update", $lng->txt("save")); - $form->addCommandButton("cancelUpdate", $lng->txt("cancel")); - } - return $form; - } - - - /** - * Create new Section. - */ - function create() - { - $form = $this->initForm(true); - if($form->checkInput()) - { - $this->content_obj = new ilPCSection($this->getPage()); - $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); - - $this->setValuesFromForm($form); - - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - } - - $this->insert($form); - } - - /** - * Update Section. - */ - function update() - { - $form = $this->initForm(false); - if($form->checkInput()) - { - $this->setValuesFromForm($form); - - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - } - - $this->pg_obj->addHierIDs(); - $this->edit(false, $form); - } - - /** - * Set values from form - * - * @param object $form form object - */ - function setValuesFromForm($form) - { - $this->content_obj->setCharacteristic($_POST["characteristic"]); - - $from = $form->getItemByPostVar("active_from")->getDate(); - if ($from) - { - $this->content_obj->setActiveFrom($from->get(IL_CAL_UNIX)); - } - else - { - $this->content_obj->setActiveFrom(0); - } - - $to = $form->getItemByPostVar("active_to")->getDate(); - if ($to) - { - $this->content_obj->setActiveTo($to->get(IL_CAL_UNIX)); - } - else - { - $this->content_obj->setActiveTo(0); - } - - if ($this->getPageConfig()->getEnablePermissionChecks()) - { - $this->content_obj->setPermissionRefId($_POST["permission_ref_id"]); - $this->content_obj->setPermission($_POST["permission"]); - } - - if ($_POST["link_mode"] == "ext" && $_POST["link"] != "") - { - $this->content_obj->setExtLink($_POST["link"]); - } - else if ($_POST["link_mode"] == "int" && $_POST["link"] != "") - { - // $_POST["link"] is "crs|96", "chap|2", "term|1", "wpage|1" -// var_dump($_POST); - $la = $form->getItemByPostVar("link")->getIntLinkAttributes(); -// echo "
          "; -// var_dump($la); exit; - if ($la["Type"] != "") - { - $this->content_obj->setIntLink($la["Type"], $la["Target"], $la["TargetFrame"]); - } - } - else - { - $this->content_obj->setNoLink(); - } - } - + /** + * Constructor + * @access public + */ + public function __construct(&$a_pg_obj, &$a_content_obj, $a_hier_id, $a_pc_id = "") + { + global $DIC; + + $this->tpl = $DIC["tpl"]; + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); + + $this->setCharacteristics(ilPCSectionGUI::_getStandardCharacteristics()); + } + + /** + * Get standard characteristics + */ + public static function _getStandardCharacteristics() + { + global $DIC; + + $lng = $DIC->language(); + + return array("Block" => $lng->txt("cont_Block"), + "Mnemonic" => $lng->txt("cont_Mnemonic"), + "Remark" => $lng->txt("cont_Remark"), + "Example" => $lng->txt("cont_Example"), + "Additional" => $lng->txt("cont_Additional"), + "Special" => $lng->txt("cont_Special"), + + "Attention" => $lng->txt("cont_Attention"), + "Background" => $lng->txt("cont_Background"), + "Confirmation" => $lng->txt("cont_Confirmation"), + "Information" => $lng->txt("cont_Information"), + "Interaction" => $lng->txt("cont_Interaction"), + "Link" => $lng->txt("cont_Link"), + "Literature" => $lng->txt("cont_Literature"), + "Separator" => $lng->txt("cont_Separator"), + "StandardCenter" => $lng->txt("cont_StandardCenter"), + + "Excursus" => $lng->txt("cont_Excursus"), + "AdvancedKnowledge" => $lng->txt("cont_AdvancedKnowledge")); + } + + /** + * Get characteristics + */ + public static function _getCharacteristics($a_style_id) + { + $chars = ilPCSectionGUI::_getStandardCharacteristics(); + + if ($a_style_id > 0 && + ilObject::_lookupType($a_style_id) == "sty") { + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $style = new ilObjStyleSheet($a_style_id); + $chars = $style->getCharacteristics("section"); + $new_chars = array(); + foreach ($chars as $char) { + if ($chars[$char] != "") { // keep lang vars for standard chars + $new_chars[$char] = $chars[$char]; + } else { + $new_chars[$char] = $char; + } + asort($new_chars); + } + $chars = $new_chars; + } + return $chars; + } + + /** + * execute command + */ + public function executeCommand() + { + $this->getCharacteristicsOfCurrentStyle("section"); // scorm-2004 + + // 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) { + case "ilpropertyformgui": + include_once './Services/Form/classes/class.ilPropertyFormGUI.php'; + $form = $this->initForm(true); + $this->ctrl->forwardCommand($form); + break; + + default: + $ret = $this->$cmd(); + break; + } + + return $ret; + } + + /** + * Insert new section form. + */ + public function insert(ilPropertyFormGUI $a_form = null) + { + $this->edit(true, $a_form); + } + + /** + * Edit section form. + */ + public function edit($a_insert = false, ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + + $this->displayValidationError(); + + if (!$a_form) { + $a_form = $this->initForm($a_insert); + } + + $tpl->setContent($a_form->getHTML()); + } + + /** + * Init editing form + */ + public function initForm($a_insert = false) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + // edit form + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this)); + if ($a_insert) { + $form->setTitle($this->lng->txt("cont_insert_section")); + } else { + $form->setTitle($this->lng->txt("cont_update_section")); + } + + // characteristic selection + require_once("./Services/Form/classes/class.ilAdvSelectInputGUI.php"); + $char_prop = new ilAdvSelectInputGUI( + $this->lng->txt("cont_characteristic"), + "characteristic" + ); + + $chars = $this->getCharacteristics(); + if (is_object($this->content_obj)) { + if ($chars[$a_seleted_value] == "" && ($this->content_obj->getCharacteristic() != "")) { + $chars = array_merge( + array($this->content_obj->getCharacteristic() => $this->content_obj->getCharacteristic()), + $chars + ); + } + } + + $selected = ($a_insert) + ? "Block" + : $this->content_obj->getCharacteristic(); + + foreach ($chars as $k => $char) { + $html = '
          ' . + $char . '
          '; + $char_prop->addOption($k, $char, $html); + } + + $char_prop->setValue($selected); + $form->addItem($char_prop); + + // link input + include_once 'Services/Form/classes/class.ilLinkInputGUI.php'; + $ac = new ilLinkInputGUI($this->lng->txt('cont_link'), 'link'); + $ac->setAllowedLinkTypes(ilLinkInputGUI::BOTH); + $ac->setRequired(false); + $ac->setInfo($this->lng->txt("copg_sec_link_info")); + $ac->setInternalLinkDefault( + $this->getPageConfig()->getIntLinkHelpDefaultType(), + $this->getPageConfig()->getIntLinkHelpDefaultId() + ); + $link_types = array(); + foreach ($this->getPageConfig()->getIntLinkFilters() as $f) { + $link_types[] = $f; + } + $ac->setInternalLinkFilterTypes($link_types); + $ac->setFilterWhiteList( + $this->getPageConfig()->getIntLinkFilterWhiteList() + ); + + if (!$a_insert) { + $l = $this->content_obj->getLink(); + if ($l["LinkType"] == "IntLink") { + $ac->setValueByIntLinkAttributes($l["Type"], $l["Target"], $l["TargetFrame"]); + } + if ($l["LinkType"] == "ExtLink") { + $ac->setValue($l["Href"]); + } + } + $form->addItem($ac); + + // activation + + // active from + $dt_prop = new ilDateTimeInputGUI($lng->txt("cont_active_from"), "active_from"); + if (!$a_insert && ($from = $this->content_obj->getActiveFrom()) != "") { + $dt_prop->setDate(new ilDateTime($from, IL_CAL_UNIX)); + } + $dt_prop->setShowTime(true); + $form->addItem($dt_prop); + + // active to + $dt_prop = new ilDateTimeInputGUI($lng->txt("cont_active_to"), "active_to"); + if (!$a_insert && ($to = $this->content_obj->getActiveTo()) != "") { + $dt_prop->setDate(new ilDateTime($to, IL_CAL_UNIX)); + } + $dt_prop->setShowTime(true); + $form->addItem($dt_prop); + + // rep selector + if ($this->getPageConfig()->getEnablePermissionChecks()) { + include_once("./Services/Form/classes/class.ilRepositorySelector2InputGUI.php"); + $rs = new ilRepositorySelector2InputGUI($lng->txt("cont_permission_object"), "permission_ref_id"); + $rs->setParent($this); + $form->addItem($rs); + + // permission + $options = array( + "read" => $lng->txt("read"), + "write" => $lng->txt("write"), + "visible" => $lng->txt("visible"), + ); + $si = new ilSelectInputGUI($lng->txt("permission"), "permission"); + $si->setInfo($lng->txt("cont_permission_object_desc")); + $si->setOptions($options); + $form->addItem($si); + + if (!$a_insert) { + $si->setValue($this->content_obj->getPermission()); + $rs->setValue($this->content_obj->getPermissionRefId()); + } + } + + // save/cancel buttons + if ($a_insert) { + $form->addCommandButton("create_section", $lng->txt("save")); + $form->addCommandButton("cancelCreate", $lng->txt("cancel")); + } else { + $form->addCommandButton("update", $lng->txt("save")); + $form->addCommandButton("cancelUpdate", $lng->txt("cancel")); + } + return $form; + } + + + /** + * Create new Section. + */ + public function create() + { + $form = $this->initForm(true); + if ($form->checkInput()) { + $this->content_obj = new ilPCSection($this->getPage()); + $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); + + $this->setValuesFromForm($form); + + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + } + + $this->insert($form); + } + + /** + * Update Section. + */ + public function update() + { + $form = $this->initForm(false); + if ($form->checkInput()) { + $this->setValuesFromForm($form); + + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + } + + $this->pg_obj->addHierIDs(); + $this->edit(false, $form); + } + + /** + * Set values from form + * + * @param object $form form object + */ + public function setValuesFromForm($form) + { + $this->content_obj->setCharacteristic($_POST["characteristic"]); + + $from = $form->getItemByPostVar("active_from")->getDate(); + if ($from) { + $this->content_obj->setActiveFrom($from->get(IL_CAL_UNIX)); + } else { + $this->content_obj->setActiveFrom(0); + } + + $to = $form->getItemByPostVar("active_to")->getDate(); + if ($to) { + $this->content_obj->setActiveTo($to->get(IL_CAL_UNIX)); + } else { + $this->content_obj->setActiveTo(0); + } + + if ($this->getPageConfig()->getEnablePermissionChecks()) { + $this->content_obj->setPermissionRefId($_POST["permission_ref_id"]); + $this->content_obj->setPermission($_POST["permission"]); + } + + if ($_POST["link_mode"] == "ext" && $_POST["link"] != "") { + $this->content_obj->setExtLink($_POST["link"]); + } elseif ($_POST["link_mode"] == "int" && $_POST["link"] != "") { + // $_POST["link"] is "crs|96", "chap|2", "term|1", "wpage|1" + // var_dump($_POST); + $la = $form->getItemByPostVar("link")->getIntLinkAttributes(); + // echo "
          "; + // var_dump($la); exit; + if ($la["Type"] != "") { + $this->content_obj->setIntLink($la["Type"], $la["Target"], $la["TargetFrame"]); + } + } else { + $this->content_obj->setNoLink(); + } + } } -?> diff --git a/Services/COPage/classes/class.ilPCSkills.php b/Services/COPage/classes/class.ilPCSkills.php index 1c8fb01f1137992ecbcd0d5222545619768cb960..afb9defc83e6a7c34afe91f12689e0151dcd83ac 100644 --- a/Services/COPage/classes/class.ilPCSkills.php +++ b/Services/COPage/classes/class.ilPCSkills.php @@ -1,168 +1,177 @@ - -* @version $Id: class.ilPCListItem.php 22210 2009-10-26 09:46:06Z akill $ -* -* @ingroup ServicesCOPage -*/ -class ilPCSkills extends ilPageContent -{ - /** - * @var ilObjUser - */ - protected $user; - - var $dom; - - /** - * Init page content component. - */ - function init() - { - global $DIC; - - $this->user = $DIC->user(); - $this->setType("skills"); - } - - /** - * Set node - */ - function setNode($a_node) - { - parent::setNode($a_node); // this is the PageContent node - $this->skill_node = $a_node->first_child(); // this is the skill node - } - - /** - * Create skill node in xml. - * - * @param object $a_pg_obj Page Object - * @param string $a_hier_id Hierarchical ID - */ - 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->skill_node = $this->dom->create_element("Skills"); - $this->skill_node = $this->node->append_child($this->skill_node); - } - - /** - * Set skill settings - * - * @param int $a_skill_id - */ - function setData($a_skill_id) - { - $ilUser = $this->user; - - $this->skill_node->set_attribute("Id", $a_skill_id); - $this->skill_node->set_attribute("User", $ilUser->getId()); - } - - /** - * Get skill mode - * - * @return string - */ - function getSkillId() - { - if (is_object($this->skill_node)) - { - return $this->skill_node->get_attribute("Id"); - } - } - - /** - * After page has been updated (or created) - * - * @param object $a_page page object - * @param DOMDocument $a_domdoc dom document - * @param string $a_xml xml - * @param bool $a_creation true on creation, otherwise false - */ - static function afterPageUpdate($a_page, DOMDocument $a_domdoc, $a_xml, $a_creation) - { - // pc skill - self::saveSkillUsage($a_page, $a_domdoc); - } - - /** - * Before page is being deleted - * - * @param object $a_page page object - */ - static function beforePageDelete($a_page) - { - require_once('Services/COPage/classes/class.ilPageContentUsage.php'); // Mantis #18636 - ilPageContentUsage::deleteAllUsages("skmg", $a_page->getParentType().":pg", $a_page->getId(), false, - $a_page->getLanguage()); - } - - /** - * After page history entry has been created - * - * @param object $a_page page object - * @param DOMDocument $a_old_domdoc old dom document - * @param string $a_old_xml old xml - * @param integer $a_old_nr history number - */ - static function afterPageHistoryEntry($a_page, DOMDocument $a_old_domdoc, $a_old_xml, $a_old_nr) - { - self::saveSkillUsage($a_page, $a_old_domdoc, $a_old_nr); - } - - /** - * save content include usages - */ - static function saveSkillUsage($a_page, $a_domdoc, $a_old_nr = 0) - { - include_once("./Services/COPage/classes/class.ilPageContentUsage.php"); - $skl_ids = self::collectSkills($a_page, $a_domdoc); - ilPageContentUsage::deleteAllUsages("skmg", $a_page->getParentType().":pg", $a_page->getId(), $a_old_nr, - $a_page->getLanguage()); - foreach($skl_ids as $skl_id) - { - if ((int) $skl_id["inst_id"] <= 0) - { - ilPageContentUsage::saveUsage("skmg", $skl_id["id"], $a_page->getParentType().":pg", $a_page->getId(), $a_old_nr, - $a_page->getLanguage()); - } - } - } - - /** - * get all content includes that are used within the page - */ - static function collectSkills($a_page, $a_domdoc) - { - $xpath = new DOMXPath($a_domdoc); - $nodes = $xpath->query('//Skills'); - - $skl_ids = array(); - foreach($nodes as $node) - { - $user = $node->getAttribute("User"); - $id = $node->getAttribute("Id"); - $inst_id = $node->getAttribute("InstId"); - $skl_ids[$user.":".$id.":".$inst_id] = array( - "user" => $user, "id" => $id, "inst_id" => $inst_id); - } - - return $skl_ids; - } - - -} -?> + +* @version $Id: class.ilPCListItem.php 22210 2009-10-26 09:46:06Z akill $ +* +* @ingroup ServicesCOPage +*/ +class ilPCSkills extends ilPageContent +{ + /** + * @var ilObjUser + */ + protected $user; + + public $dom; + + /** + * Init page content component. + */ + public function init() + { + global $DIC; + + $this->user = $DIC->user(); + $this->setType("skills"); + } + + /** + * Set node + */ + public function setNode($a_node) + { + parent::setNode($a_node); // this is the PageContent node + $this->skill_node = $a_node->first_child(); // this is the skill node + } + + /** + * Create skill node in xml. + * + * @param object $a_pg_obj Page Object + * @param string $a_hier_id Hierarchical ID + */ + public 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->skill_node = $this->dom->create_element("Skills"); + $this->skill_node = $this->node->append_child($this->skill_node); + } + + /** + * Set skill settings + * + * @param int $a_skill_id + */ + public function setData($a_skill_id) + { + $ilUser = $this->user; + + $this->skill_node->set_attribute("Id", $a_skill_id); + $this->skill_node->set_attribute("User", $ilUser->getId()); + } + + /** + * Get skill mode + * + * @return string + */ + public function getSkillId() + { + if (is_object($this->skill_node)) { + return $this->skill_node->get_attribute("Id"); + } + } + + /** + * After page has been updated (or created) + * + * @param object $a_page page object + * @param DOMDocument $a_domdoc dom document + * @param string $a_xml xml + * @param bool $a_creation true on creation, otherwise false + */ + public static function afterPageUpdate($a_page, DOMDocument $a_domdoc, $a_xml, $a_creation) + { + // pc skill + self::saveSkillUsage($a_page, $a_domdoc); + } + + /** + * Before page is being deleted + * + * @param object $a_page page object + */ + public static function beforePageDelete($a_page) + { + require_once('Services/COPage/classes/class.ilPageContentUsage.php'); // Mantis #18636 + ilPageContentUsage::deleteAllUsages( + "skmg", + $a_page->getParentType() . ":pg", + $a_page->getId(), + false, + $a_page->getLanguage() + ); + } + + /** + * After page history entry has been created + * + * @param object $a_page page object + * @param DOMDocument $a_old_domdoc old dom document + * @param string $a_old_xml old xml + * @param integer $a_old_nr history number + */ + public static function afterPageHistoryEntry($a_page, DOMDocument $a_old_domdoc, $a_old_xml, $a_old_nr) + { + self::saveSkillUsage($a_page, $a_old_domdoc, $a_old_nr); + } + + /** + * save content include usages + */ + public static function saveSkillUsage($a_page, $a_domdoc, $a_old_nr = 0) + { + include_once("./Services/COPage/classes/class.ilPageContentUsage.php"); + $skl_ids = self::collectSkills($a_page, $a_domdoc); + ilPageContentUsage::deleteAllUsages( + "skmg", + $a_page->getParentType() . ":pg", + $a_page->getId(), + $a_old_nr, + $a_page->getLanguage() + ); + foreach ($skl_ids as $skl_id) { + if ((int) $skl_id["inst_id"] <= 0) { + ilPageContentUsage::saveUsage( + "skmg", + $skl_id["id"], + $a_page->getParentType() . ":pg", + $a_page->getId(), + $a_old_nr, + $a_page->getLanguage() + ); + } + } + } + + /** + * get all content includes that are used within the page + */ + public static function collectSkills($a_page, $a_domdoc) + { + $xpath = new DOMXPath($a_domdoc); + $nodes = $xpath->query('//Skills'); + + $skl_ids = array(); + foreach ($nodes as $node) { + $user = $node->getAttribute("User"); + $id = $node->getAttribute("Id"); + $inst_id = $node->getAttribute("InstId"); + $skl_ids[$user . ":" . $id . ":" . $inst_id] = array( + "user" => $user, "id" => $id, "inst_id" => $inst_id); + } + + return $skl_ids; + } +} diff --git a/Services/COPage/classes/class.ilPCSkillsGUI.php b/Services/COPage/classes/class.ilPCSkillsGUI.php index 5e7bd4586cda6a846de5105dfa41074d76c0fd34..1d552a60390d815756a942f9449a1119168ebc41 100644 --- a/Services/COPage/classes/class.ilPCSkillsGUI.php +++ b/Services/COPage/classes/class.ilPCSkillsGUI.php @@ -1,283 +1,252 @@ - -* @version $I$ -* -* @ingroup ServicesCOPage -*/ -class ilPCSkillsGUI extends ilPageContentGUI -{ - /** - * @var ilObjUser - */ - protected $user; +tpl = $DIC["tpl"]; - $this->ctrl = $DIC->ctrl(); - $this->user = $DIC->user(); - $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 skills form - * - * @param ilPropertyFormGUI $a_form - */ - function insert(ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - - $this->displayValidationError(); - - // template mode: get skills from global skill tree - if($this->getPageConfig()->getEnablePCType("PlaceHolder")) - { - include_once "Services/Skill/classes/class.ilPersonalSkillExplorerGUI.php"; - $exp = new ilPersonalSkillExplorerGUI($this, "insert", $this, "create", "skill_id"); - if (!$exp->handleCommand()) - { - $tpl->setContent($exp->getHTML()); - } - } - // editor mode: use personal skills - else - { - if(!$a_form) - { - $a_form = $this->initForm(true); - } - $tpl->setContent($a_form->getHTML()); - } - } - - /** - * Edit skills form - * - * @param ilPropertyFormGUI $a_form - */ - function edit(ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - - $this->displayValidationError(); - - // template mode: get skills from global skill tree - if($this->getPageConfig()->getEnablePCType("PlaceHolder")) - { - include_once "Services/Skill/classes/class.ilPersonalSkillExplorerGUI.php"; - $exp = new ilPersonalSkillExplorerGUI($this, "edit", $this, "update", "skill_id"); - if (!$exp->handleCommand()) - { - $tpl->setContent($exp->getHTML()); - } - } - // editor mode: use personal skills - else - { - if(!$a_form) - { - $a_form = $this->initForm(); - } - $tpl->setContent($a_form->getHTML()); - } - } - - /** - * Init skills form - * - * @param bool $a_insert - * @return ilPropertyFormGUI - */ - protected function initForm($a_insert = false) - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - $lng = $this->lng; - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this)); - if ($a_insert) - { - $form->setTitle($this->lng->txt("cont_insert_skills")); - } - else - { - $form->setTitle($this->lng->txt("cont_update_skills")); - } - - $options = array(); - include_once "Services/Skill/classes/class.ilPersonalSkill.php"; - - $skills = ilPersonalSkill::getSelectedUserSkills($ilUser->getId()); - if($skills) - { - foreach($skills as $skill) - { - $options[$skill["skill_node_id"]] = $skill["title"]; - } - asort($options); - } - else - { - ilUtil::sendFailure("cont_no_skills"); - } - $obj = new ilSelectInputGUI($this->lng->txt("cont_pc_skills"), "skill_id"); - $obj->setRequired(true); - $obj->setOptions($options); - $form->addItem($obj); - - if ($a_insert) - { - $form->addCommandButton("create_skill", $this->lng->txt("select")); - $form->addCommandButton("cancelCreate", $this->lng->txt("cancel")); - } - else - { - $obj->setValue($this->content_obj->getSkillId()); - $form->addCommandButton("update", $this->lng->txt("select")); - $form->addCommandButton("cancelUpdate", $this->lng->txt("cancel")); - } - - return $form; - } - - /** - * Create new skill - */ - function create() - { - $valid = false; - - // template mode: get skills from global skill tree - if($this->getPageConfig()->getEnablePCType("PlaceHolder")) - { - $data = (int)$_GET["skill_id"]; - $valid = true; - } - // editor mode: use personal skills - else - { - $form = $this->initForm(true); - if($form->checkInput()) - { - $data = $form->getInput("skill_id"); - $valid = true; - } - } - - if($valid) - { - $this->content_obj = new ilPCSkills($this->getPage()); - $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); - $this->content_obj->setData($data); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - } - - $form->setValuesByPost(); - return $this->insert($form); - } - - /** - * Update blog - */ - function update() - { - // template mode: get skills from global skill tree - if($this->getPageConfig()->getEnablePCType("PlaceHolder")) - { - $data = (int)$_GET["skill_id"]; - $valid = true; - } - // editor mode: use personal skills - else - { - $form = $this->initForm(); - if($form->checkInput()) - { - $data = $form->getInput("skill_id"); - $valid = true; - } - } - - if($valid) - { - $this->content_obj->setData($data); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - } - - $this->pg_obj->addHierIDs(); - $form->setValuesByPost(); - return $this->edit($form); - } -} - -?> \ No newline at end of file +/** +* Class ilPCSkillsGUI +* +* Handles user commands on skills data +* +* @author Jörg Lützenkirchen +* @version $I$ +* +* @ingroup ServicesCOPage +*/ +class ilPCSkillsGUI extends ilPageContentGUI +{ + /** + * @var ilObjUser + */ + protected $user; + + + /** + * Constructor + * @access public + */ + 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->user = $DIC->user(); + $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 skills form + * + * @param ilPropertyFormGUI $a_form + */ + public function insert(ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + + $this->displayValidationError(); + + // template mode: get skills from global skill tree + if ($this->getPageConfig()->getEnablePCType("PlaceHolder")) { + include_once "Services/Skill/classes/class.ilPersonalSkillExplorerGUI.php"; + $exp = new ilPersonalSkillExplorerGUI($this, "insert", $this, "create", "skill_id"); + if (!$exp->handleCommand()) { + $tpl->setContent($exp->getHTML()); + } + } + // editor mode: use personal skills + else { + if (!$a_form) { + $a_form = $this->initForm(true); + } + $tpl->setContent($a_form->getHTML()); + } + } + + /** + * Edit skills form + * + * @param ilPropertyFormGUI $a_form + */ + public function edit(ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + + $this->displayValidationError(); + + // template mode: get skills from global skill tree + if ($this->getPageConfig()->getEnablePCType("PlaceHolder")) { + include_once "Services/Skill/classes/class.ilPersonalSkillExplorerGUI.php"; + $exp = new ilPersonalSkillExplorerGUI($this, "edit", $this, "update", "skill_id"); + if (!$exp->handleCommand()) { + $tpl->setContent($exp->getHTML()); + } + } + // editor mode: use personal skills + else { + if (!$a_form) { + $a_form = $this->initForm(); + } + $tpl->setContent($a_form->getHTML()); + } + } + + /** + * Init skills form + * + * @param bool $a_insert + * @return ilPropertyFormGUI + */ + protected function initForm($a_insert = false) + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + $lng = $this->lng; + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this)); + if ($a_insert) { + $form->setTitle($this->lng->txt("cont_insert_skills")); + } else { + $form->setTitle($this->lng->txt("cont_update_skills")); + } + + $options = array(); + include_once "Services/Skill/classes/class.ilPersonalSkill.php"; + + $skills = ilPersonalSkill::getSelectedUserSkills($ilUser->getId()); + if ($skills) { + foreach ($skills as $skill) { + $options[$skill["skill_node_id"]] = $skill["title"]; + } + asort($options); + } else { + ilUtil::sendFailure("cont_no_skills"); + } + $obj = new ilSelectInputGUI($this->lng->txt("cont_pc_skills"), "skill_id"); + $obj->setRequired(true); + $obj->setOptions($options); + $form->addItem($obj); + + if ($a_insert) { + $form->addCommandButton("create_skill", $this->lng->txt("select")); + $form->addCommandButton("cancelCreate", $this->lng->txt("cancel")); + } else { + $obj->setValue($this->content_obj->getSkillId()); + $form->addCommandButton("update", $this->lng->txt("select")); + $form->addCommandButton("cancelUpdate", $this->lng->txt("cancel")); + } + + return $form; + } + + /** + * Create new skill + */ + public function create() + { + $valid = false; + + // template mode: get skills from global skill tree + if ($this->getPageConfig()->getEnablePCType("PlaceHolder")) { + $data = (int) $_GET["skill_id"]; + $valid = true; + } + // editor mode: use personal skills + else { + $form = $this->initForm(true); + if ($form->checkInput()) { + $data = $form->getInput("skill_id"); + $valid = true; + } + } + + if ($valid) { + $this->content_obj = new ilPCSkills($this->getPage()); + $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); + $this->content_obj->setData($data); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + } + + $form->setValuesByPost(); + return $this->insert($form); + } + + /** + * Update blog + */ + public function update() + { + // template mode: get skills from global skill tree + if ($this->getPageConfig()->getEnablePCType("PlaceHolder")) { + $data = (int) $_GET["skill_id"]; + $valid = true; + } + // editor mode: use personal skills + else { + $form = $this->initForm(); + if ($form->checkInput()) { + $data = $form->getInput("skill_id"); + $valid = true; + } + } + + if ($valid) { + $this->content_obj->setData($data); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + } + + $this->pg_obj->addHierIDs(); + $form->setValuesByPost(); + return $this->edit($form); + } +} diff --git a/Services/COPage/classes/class.ilPCSourceCode.php b/Services/COPage/classes/class.ilPCSourceCode.php index 84477a6daec0000792cf0d0be8260c1755eaf909..e125df6aaf6bbb869c204e05877da2df431b4ce4 100755 --- a/Services/COPage/classes/class.ilPCSourceCode.php +++ b/Services/COPage/classes/class.ilPCSourceCode.php @@ -16,164 +16,155 @@ require_once("./Services/COPage/classes/class.ilPCParagraph.php"); */ class ilPCSourceCode extends ilPCParagraph { - /** - * Init page content component. - */ - function init() - { - $this->setType("src"); - } - - /** - * Get lang vars needed for editing - * @return array array of lang var keys - */ - static function getLangVars() - { - return array("ed_insert_code", "pc_code"); - } - - /** - * Modify page content after xsl - * - * @param string $a_output - * @return string - */ - function modifyPageContentPostXsl($a_output, $outputmode = "presentation") - { - $dom = $this->getPage()->getDom(); - - $xpc = xpath_new_context($dom); - $path = "//Paragraph"; //"[@Characteristic = 'Code']"; - $res = & xpath_eval($xpc, $path); - for($i = 0; $i < count($res->nodeset); $i++) - { - $context_node = $res->nodeset[$i]; - $char = $context_node->get_attribute('Characteristic'); - - if ($char != "Code") - continue; - - $n = $context_node->parent_node(); - $char = $context_node->get_attribute('Characteristic'); - $subchar = $context_node->get_attribute('SubCharacteristic'); - $showlinenumbers = $context_node->get_attribute('ShowLineNumbers'); - $downloadtitle = $context_node->get_attribute('DownloadTitle'); - $autoindent = $context_node->get_attribute('AutoIndent'); - - $content = ""; - - // get XML Content - $childs = $context_node->child_nodes(); - - for($j=0; $jdump_node($childs[$j]); - } - - while ($context_node->has_child_nodes ()) - { - $node_del = $context_node->first_child (); - $context_node->remove_child ($node_del); - } - - $content = str_replace("
          ", "
          ", utf8_decode($content) ); - $content = str_replace("
          ", "\n", $content); - $rownums = count(explode("\n",$content)); - - // see #23028 - //$plain_content = html_entity_decode($content); - $plain_content = $content; - - $plain_content = preg_replace_callback( + /** + * Init page content component. + */ + public function init() + { + $this->setType("src"); + } + + /** + * Get lang vars needed for editing + * @return array array of lang var keys + */ + public static function getLangVars() + { + return array("ed_insert_code", "pc_code"); + } + + /** + * Modify page content after xsl + * + * @param string $a_output + * @return string + */ + public function modifyPageContentPostXsl($a_output, $outputmode = "presentation") + { + $dom = $this->getPage()->getDom(); + + $xpc = xpath_new_context($dom); + $path = "//Paragraph"; //"[@Characteristic = 'Code']"; + $res = &xpath_eval($xpc, $path); + for ($i = 0; $i < count($res->nodeset); $i++) { + $context_node = $res->nodeset[$i]; + $char = $context_node->get_attribute('Characteristic'); + + if ($char != "Code") { + continue; + } + + $n = $context_node->parent_node(); + $char = $context_node->get_attribute('Characteristic'); + $subchar = $context_node->get_attribute('SubCharacteristic'); + $showlinenumbers = $context_node->get_attribute('ShowLineNumbers'); + $downloadtitle = $context_node->get_attribute('DownloadTitle'); + $autoindent = $context_node->get_attribute('AutoIndent'); + + $content = ""; + + // get XML Content + $childs = $context_node->child_nodes(); + + for ($j=0; $jdump_node($childs[$j]); + } + + while ($context_node->has_child_nodes()) { + $node_del = $context_node->first_child(); + $context_node->remove_child($node_del); + } + + $content = str_replace("
          ", "
          ", utf8_decode($content)); + $content = str_replace("
          ", "\n", $content); + $rownums = count(explode("\n", $content)); + + // see #23028 + //$plain_content = html_entity_decode($content); + $plain_content = $content; + + $plain_content = preg_replace_callback( "/\&#x([1-9a-f]{2});?/is", - function($hit) { + function ($hit) { return chr(base_convert($hit[1], 16, 10)); }, $plain_content ); - $plain_content = preg_replace_callback( + $plain_content = preg_replace_callback( "/\&#(\d+);?/is", - function($hit) { + function ($hit) { return chr($hit[1]); }, $plain_content ); - $content = utf8_encode($this->highlightText($plain_content, $subchar, $autoindent)); - - $content = str_replace("&lt;", "<", $content); - $content = str_replace("&gt;", ">", $content); -// $content = str_replace("&", "&", $content); -//var_dump($content); - $rows = ""; - $rownumbers = ""; - $linenumbers= ""; - - //if we have to show line numbers - if (strcmp($showlinenumbers,"y")==0) - { - $linenumbers = ""; - $linenumbers .= "
          ";
          -
          -				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 .= ""; - } - - $rows .= $linenumbers."
          ".$content."
          "; - $rows .= ""; - - // fix for ie explorer which is not able to produce empty line feeds with

          ; - // workaround: add a space after each br. - $newcontent = str_replace("\n", "
          ",$rows); - // fix for IE - $newcontent = str_replace("

          ", "

          ",$newcontent); - // falls drei hintereinander... - $newcontent = str_replace("

          ", "

          ",$newcontent); - - // workaround for preventing template engine - // from hiding paragraph text that is enclosed - // in curly brackets (e.g. "{a}", see ilLMEditorGUI::executeCommand()) - $newcontent = str_replace("{", "{", $newcontent); - $newcontent = str_replace("}", "}", $newcontent); - -//echo htmlentities($newcontent); - $a_output = str_replace("[[[[[Code;".($i + 1)."]]]]]", $newcontent, $a_output); - - if ($outputmode != "presentation" && is_object($this->getPage()->getOfflineHandler()) - && trim($downloadtitle) != "") - { - // call code handler for offline versions - $this->getPage()->getOfflineHandler()->handleCodeParagraph($this->getPage()->getId(), $i + 1, $downloadtitle, $plain_content); - } - } - - return $a_output; - } - - /** - * Highligths Text with given ProgLang - */ - function highlightText($a_text, $proglang, $autoindent = "") - { - - include_once("./Services/UIComponent/SyntaxHighlighter/classes/class.ilSyntaxHighlighter.php"); - $proglang = ilSyntaxHighlighter::getNewLanguageId($proglang); - if (ilSyntaxHighlighter::isSupported($proglang)) - { - $highl = ilSyntaxHighlighter::getInstance($proglang); - $a_text = $highl->highlight($a_text); - } - return $a_text; - } + $content = utf8_encode($this->highlightText($plain_content, $subchar, $autoindent)); + + $content = str_replace("&lt;", "<", $content); + $content = str_replace("&gt;", ">", $content); + // $content = str_replace("&", "&", $content); + //var_dump($content); + $rows = ""; + $rownumbers = ""; + $linenumbers= ""; + + //if we have to show line numbers + if (strcmp($showlinenumbers, "y")==0) { + $linenumbers = ""; + $linenumbers .= "
          ";
          +
          +                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 .= ""; + } + + $rows .= $linenumbers . "
          " . $content . "
          "; + $rows .= ""; + + // fix for ie explorer which is not able to produce empty line feeds with

          ; + // workaround: add a space after each br. + $newcontent = str_replace("\n", "
          ", $rows); + // fix for IE + $newcontent = str_replace("

          ", "

          ", $newcontent); + // falls drei hintereinander... + $newcontent = str_replace("

          ", "

          ", $newcontent); + + // workaround for preventing template engine + // from hiding paragraph text that is enclosed + // in curly brackets (e.g. "{a}", see ilLMEditorGUI::executeCommand()) + $newcontent = str_replace("{", "{", $newcontent); + $newcontent = str_replace("}", "}", $newcontent); + + //echo htmlentities($newcontent); + $a_output = str_replace("[[[[[Code;" . ($i + 1) . "]]]]]", $newcontent, $a_output); + + if ($outputmode != "presentation" && is_object($this->getPage()->getOfflineHandler()) + && trim($downloadtitle) != "") { + // call code handler for offline versions + $this->getPage()->getOfflineHandler()->handleCodeParagraph($this->getPage()->getId(), $i + 1, $downloadtitle, $plain_content); + } + } + + return $a_output; + } + + /** + * Highligths Text with given ProgLang + */ + public function highlightText($a_text, $proglang, $autoindent = "") + { + include_once("./Services/UIComponent/SyntaxHighlighter/classes/class.ilSyntaxHighlighter.php"); + $proglang = ilSyntaxHighlighter::getNewLanguageId($proglang); + if (ilSyntaxHighlighter::isSupported($proglang)) { + $highl = ilSyntaxHighlighter::getInstance($proglang); + $a_text = $highl->highlight($a_text); + } + return $a_text; + } } -?> diff --git a/Services/COPage/classes/class.ilPCSourceCodeGUI.php b/Services/COPage/classes/class.ilPCSourceCodeGUI.php index 192038a912d64431eaca5e08058f24763b4be58f..199b313583b25cdc9f43fa24056198c708d70c12 100755 --- a/Services/COPage/classes/class.ilPCSourceCodeGUI.php +++ b/Services/COPage/classes/class.ilPCSourceCodeGUI.php @@ -17,330 +17,314 @@ require_once("./Services/COPage/classes/class.ilPageContentGUI.php"); */ class ilPCSourceCodeGUI extends ilPageContentGUI { - /** - * @var ilObjUser - */ - protected $user; - - - /** - * Constructor - * @access public - */ - function __construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id = "") - { - global $DIC; - - $this->user = $DIC->user(); - 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; - } - - /** - * edit paragraph form - */ - function edit() - { - $form = $this->initPropertyForm($this->lng->txt("cont_edit_src"), "update", "cancelCreate"); - - if ($this->pg_obj->getParentType() == "lm") - { - $this->tpl->setVariable("LINK_ILINK", - $this->ctrl->getLinkTargetByClass("ilInternalLinkGUI", "showLinkHelp")); - $this->tpl->setVariable("TXT_ILINK", "[".$this->lng->txt("cont_internal_link")."]"); - } - - $this->displayValidationError(); - - if (key($_POST["cmd"]) == "update") - { - $form->setValuesByPost(); - - } - else{ - $form->getItemByPostVar("par_language")->setValue($this->content_obj->getLanguage()); - $form->getItemByPostVar("par_subcharacteristic")->setValue($this->content_obj->getSubCharacteristic()); - $form->getItemByPostVar("par_downloadtitle")->setValue( $this->content_obj->getDownloadTitle()); - $form->getItemByPostVar("par_showlinenumbers")->setChecked( - $this->content_obj->getShowLineNumbers()=="y"?true:false); -// $form->getItemByPostVar("par_autoindent")->setChecked( -// $this->content_obj->getAutoIndent()=="y"?true:false); - - $par_content = $this->content_obj->xml2output($this->content_obj->getText()); - - //TODO: Find a better way to convert back curly brackets - $par_content = str_replace("{","{", $par_content); - $par_content = str_replace("}","}", $par_content); - - $form->getItemByPostVar("par_content")->setValue($par_content); - } - - - $this->tpl->setContent($form->getHTML()); - } - - /** - * insert paragraph form - */ - function insert() - { - $ilUser = $this->user; - - $form = $this->initPropertyForm($this->lng->txt("cont_insert_src"), "create_src", "cancelCreate"); - - if ($this->pg_obj->getParentType() == "lm") - { - $this->tpl->setVariable("LINK_ILINK", - $this->ctrl->getLinkTargetByClass("ilInternalLinkGUI", "showLinkHelp")); - $this->tpl->setVariable("TXT_ILINK", "[".$this->lng->txt("cont_internal_link")."]"); - } - - $this->displayValidationError(); - - if (key($_POST["cmd"]) == "create_src") - { - $form->setValuesByPost(); - - } - else{ - if ($_SESSION["il_text_lang_".$_GET["ref_id"]] != "") - { - $form->getItemByPostVar("par_language")->setValue($_SESSION["il_text_lang_".$_GET["ref_id"]]); - } - else - { - $form->getItemByPostVar("par_language")->setValue($ilUser->getLanguage()); - } - - $form->getItemByPostVar("par_showlinenumbers")->setChecked(true); -// $form->getItemByPostVar("par_autoindent")->setChecked(true); - $form->getItemByPostVar("par_subcharacteristic")->setValue(""); - $form->getItemByPostVar("par_content")->setValue(""); - } - - $this->tpl->setContent($form->getHTML()); - } - - - /** - * update paragraph in dom and update page in db - */ - function update() - { - $this->upload_source(); - - // set language and characteristic - - $this->content_obj->setLanguage($_POST["par_language"]); - $this->content_obj->setCharacteristic($_POST["par_characteristic"]); - - //echo "PARupdate:".htmlentities($this->content_obj->input2xml($_POST["par_content"])).":
          "; exit; - - - // set language and characteristic - $this->content_obj->setLanguage($_POST["par_language"]); - $this->content_obj->setSubCharacteristic($_POST["par_subcharacteristic"]); - $this->content_obj->setDownloadTitle(str_replace('"', '', ilUtil::stripSlashes($_POST["par_downloadtitle"]))); - $this->content_obj->setShowLineNumbers($_POST["par_showlinenumbers"]?"y":"n"); - //$this->content_obj->setAutoIndent($_POST["par_autoindent"]?"y":"n"); - $this->content_obj->setSubCharacteristic($_POST["par_subcharacteristic"]); - $this->content_obj->setCharacteristic("Code"); - - $this->updated = $this->content_obj->setText( - $this->content_obj->input2xml($_POST["par_content"], 0, false)); - - if ($this->updated !== true) - { - //echo "Did not update!"; - $this->edit(); - return; - } - - $this->updated = $this->pg_obj->update(); - - if ($this->updated === true && $this->ctrl->getCmd () != "upload" ) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - else - { - $this->edit(); - } - } - - /** - * cancel update - */ - function cancelUpdate() - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * create new paragraph in dom and update page in db - */ - function create() - { - $this->content_obj = new ilPCSourceCode($this->getPage()); - $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); - $this->content_obj->setLanguage($_POST["par_language"]); - - $_SESSION["il_text_lang_".$_GET["ref_id"]] = $_POST["par_language"]; - - $uploaded = $this->upload_source(); - - $this->content_obj->setCharacteristic ($_POST["par_characteristic"]); - $this->content_obj->setSubCharacteristic($_POST["par_subcharacteristic"]); - $this->content_obj->setDownloadTitle (str_replace('"', '', ilUtil::stripSlashes($_POST["par_downloadtitle"]))); - $this->content_obj->setShowLineNumbers ($_POST["par_showlinenumbers"]?'y':'n'); - $this->content_obj->setCharacteristic ('Code'); - //$this->content_obj->setAutoIndent ($_POST["par_autoindent"]?'y':'n'); - - if ($uploaded) { - $this->insert (); - return; - } - - $this->updated = $this->content_obj->setText( - $this->content_obj->input2xml($_POST["par_content"], 0, false)); - - if ($this->updated !== true) - { - $this->insert(); - return; - } - - $this->updated = $this->pg_obj->update(); - - if ($this->updated === true && !$uploaded) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - else - { - $this->insert (); - } - } - - /** - * cancel creating paragraph - */ - function cancelCreate() - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - function upload_source () { - if (isset($_FILES['userfile']['name'])) - { - $userfile = $_FILES['userfile']['tmp_name']; - - if ($userfile == "" || !is_uploaded_file($userfile)) - { - $error_str = "Error(s):
          Upload error: file name must not be empty!"; - $this->tpl->setVariable("MESSAGE", $error_str); - $this->content_obj->setText($this->content_obj->input2xml(stripslashes($_POST["par_content"]), 0, false)); - return false; - } - - $_POST["par_content"] = file_get_contents($userfile); - $_POST["par_downloadtitle"] = $_FILES['userfile']['name']; - return true; - } - - return false; - } - - - /** - * Get selectable programming languages - * - * @return string[] - */ - function getProgLangOptions() - { - $prog_langs = array( - "" => "other"); - include_once("./Services/UIComponent/SyntaxHighlighter/classes/class.ilSyntaxHighlighter.php"); - foreach (ilSyntaxHighlighter::getSupportedLanguagesV51() as $k => $v) - { - $prog_langs[$k] = $v; - } - return $prog_langs; - } - - /** - * initiates property form GUI class - * - * @param string $a_title - * @param string $a_cmd - * @param string $a_cmd_cancel - * @return ilPropertyFormGUI form class - */ - function initPropertyForm($a_title, $a_cmd, $a_cmd_cancel) - { - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setTitle($a_title); - $form->setFormAction($this->ctrl->getFormAction($this, $a_cmd)); - $form->addCommandButton($a_cmd,$this->lng->txt("save")); - $form->addCommandButton($a_cmd_cancel,$this->lng->txt("cancel")); - - - require_once("Services/MetaData/classes/class.ilMDLanguageItem.php"); - $lang_var = ilMDLanguageItem::_getLanguages(); - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $lang = new ilSelectInputGUI($this->lng->txt("language"),"par_language"); - $lang->setOptions($lang_var); - $form->addItem($lang); - - $prog_langs = $this->getProgLangOptions(); - $code_style = new ilSelectInputGUI( $this->lng->txt("cont_src"), "par_subcharacteristic"); - $code_style->setOptions($prog_langs); - $form->addItem($code_style); - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $line_number = new ilCheckboxInputGUI($this->lng->txt("cont_show_line_numbers"), "par_showlinenumbers"); - $form->addItem($line_number); - //$indent = new ilCheckboxInputGUI($this->lng->txt("cont_autoindent"), "par_autoindent"); - //$form->addItem($indent); - - - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $code = new ilTextAreaInputGUI("", "par_content"); - $code->setRows(12); - $form->addItem($code); - - include_once("./Services/Form/classes/class.ilTextInputGUI.php"); - $downlaod_title = new ilTextInputGUI($this->lng->txt("cont_download_title"), "par_downloadtitle"); - $downlaod_title->setSize(40); - $form->addItem($downlaod_title); - - include_once("./Services/Form/classes/class.ilFileInputGUI.php"); - $file = new ilFileInputGUI($this->lng->txt("import_file"), "userfile"); - $form->addItem($file); - - return $form; - } + /** + * @var ilObjUser + */ + protected $user; + + + /** + * Constructor + * @access public + */ + public function __construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id = "") + { + global $DIC; + + $this->user = $DIC->user(); + 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; + } + + /** + * edit paragraph form + */ + public function edit() + { + $form = $this->initPropertyForm($this->lng->txt("cont_edit_src"), "update", "cancelCreate"); + + if ($this->pg_obj->getParentType() == "lm") { + $this->tpl->setVariable( + "LINK_ILINK", + $this->ctrl->getLinkTargetByClass("ilInternalLinkGUI", "showLinkHelp") + ); + $this->tpl->setVariable("TXT_ILINK", "[" . $this->lng->txt("cont_internal_link") . "]"); + } + + $this->displayValidationError(); + + if (key($_POST["cmd"]) == "update") { + $form->setValuesByPost(); + } else { + $form->getItemByPostVar("par_language")->setValue($this->content_obj->getLanguage()); + $form->getItemByPostVar("par_subcharacteristic")->setValue($this->content_obj->getSubCharacteristic()); + $form->getItemByPostVar("par_downloadtitle")->setValue($this->content_obj->getDownloadTitle()); + $form->getItemByPostVar("par_showlinenumbers")->setChecked( + $this->content_obj->getShowLineNumbers()=="y"?true:false + ); + // $form->getItemByPostVar("par_autoindent")->setChecked( + // $this->content_obj->getAutoIndent()=="y"?true:false); + + $par_content = $this->content_obj->xml2output($this->content_obj->getText()); + + //TODO: Find a better way to convert back curly brackets + $par_content = str_replace("{", "{", $par_content); + $par_content = str_replace("}", "}", $par_content); + + $form->getItemByPostVar("par_content")->setValue($par_content); + } + + + $this->tpl->setContent($form->getHTML()); + } + + /** + * insert paragraph form + */ + public function insert() + { + $ilUser = $this->user; + + $form = $this->initPropertyForm($this->lng->txt("cont_insert_src"), "create_src", "cancelCreate"); + + if ($this->pg_obj->getParentType() == "lm") { + $this->tpl->setVariable( + "LINK_ILINK", + $this->ctrl->getLinkTargetByClass("ilInternalLinkGUI", "showLinkHelp") + ); + $this->tpl->setVariable("TXT_ILINK", "[" . $this->lng->txt("cont_internal_link") . "]"); + } + + $this->displayValidationError(); + + if (key($_POST["cmd"]) == "create_src") { + $form->setValuesByPost(); + } else { + if ($_SESSION["il_text_lang_" . $_GET["ref_id"]] != "") { + $form->getItemByPostVar("par_language")->setValue($_SESSION["il_text_lang_" . $_GET["ref_id"]]); + } else { + $form->getItemByPostVar("par_language")->setValue($ilUser->getLanguage()); + } + + $form->getItemByPostVar("par_showlinenumbers")->setChecked(true); + // $form->getItemByPostVar("par_autoindent")->setChecked(true); + $form->getItemByPostVar("par_subcharacteristic")->setValue(""); + $form->getItemByPostVar("par_content")->setValue(""); + } + + $this->tpl->setContent($form->getHTML()); + } + + + /** + * update paragraph in dom and update page in db + */ + public function update() + { + $this->upload_source(); + + // set language and characteristic + + $this->content_obj->setLanguage($_POST["par_language"]); + $this->content_obj->setCharacteristic($_POST["par_characteristic"]); + + //echo "PARupdate:".htmlentities($this->content_obj->input2xml($_POST["par_content"])).":
          "; exit; + + + // set language and characteristic + $this->content_obj->setLanguage($_POST["par_language"]); + $this->content_obj->setSubCharacteristic($_POST["par_subcharacteristic"]); + $this->content_obj->setDownloadTitle(str_replace('"', '', ilUtil::stripSlashes($_POST["par_downloadtitle"]))); + $this->content_obj->setShowLineNumbers($_POST["par_showlinenumbers"]?"y":"n"); + //$this->content_obj->setAutoIndent($_POST["par_autoindent"]?"y":"n"); + $this->content_obj->setSubCharacteristic($_POST["par_subcharacteristic"]); + $this->content_obj->setCharacteristic("Code"); + + $this->updated = $this->content_obj->setText( + $this->content_obj->input2xml($_POST["par_content"], 0, false) + ); + + if ($this->updated !== true) { + //echo "Did not update!"; + $this->edit(); + return; + } + + $this->updated = $this->pg_obj->update(); + + if ($this->updated === true && $this->ctrl->getCmd() != "upload") { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } else { + $this->edit(); + } + } + + /** + * cancel update + */ + public function cancelUpdate() + { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * create new paragraph in dom and update page in db + */ + public function create() + { + $this->content_obj = new ilPCSourceCode($this->getPage()); + $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); + $this->content_obj->setLanguage($_POST["par_language"]); + + $_SESSION["il_text_lang_" . $_GET["ref_id"]] = $_POST["par_language"]; + + $uploaded = $this->upload_source(); + + $this->content_obj->setCharacteristic($_POST["par_characteristic"]); + $this->content_obj->setSubCharacteristic($_POST["par_subcharacteristic"]); + $this->content_obj->setDownloadTitle(str_replace('"', '', ilUtil::stripSlashes($_POST["par_downloadtitle"]))); + $this->content_obj->setShowLineNumbers($_POST["par_showlinenumbers"]?'y':'n'); + $this->content_obj->setCharacteristic('Code'); + //$this->content_obj->setAutoIndent ($_POST["par_autoindent"]?'y':'n'); + + if ($uploaded) { + $this->insert(); + return; + } + + $this->updated = $this->content_obj->setText( + $this->content_obj->input2xml($_POST["par_content"], 0, false) + ); + + if ($this->updated !== true) { + $this->insert(); + return; + } + + $this->updated = $this->pg_obj->update(); + + if ($this->updated === true && !$uploaded) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } else { + $this->insert(); + } + } + + /** + * cancel creating paragraph + */ + public function cancelCreate() + { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + public function upload_source() + { + if (isset($_FILES['userfile']['name'])) { + $userfile = $_FILES['userfile']['tmp_name']; + + if ($userfile == "" || !is_uploaded_file($userfile)) { + $error_str = "Error(s):
          Upload error: file name must not be empty!"; + $this->tpl->setVariable("MESSAGE", $error_str); + $this->content_obj->setText($this->content_obj->input2xml(stripslashes($_POST["par_content"]), 0, false)); + return false; + } + + $_POST["par_content"] = file_get_contents($userfile); + $_POST["par_downloadtitle"] = $_FILES['userfile']['name']; + return true; + } + + return false; + } + + + /** + * Get selectable programming languages + * + * @return string[] + */ + public function getProgLangOptions() + { + $prog_langs = array( + "" => "other"); + include_once("./Services/UIComponent/SyntaxHighlighter/classes/class.ilSyntaxHighlighter.php"); + foreach (ilSyntaxHighlighter::getSupportedLanguagesV51() as $k => $v) { + $prog_langs[$k] = $v; + } + return $prog_langs; + } + + /** + * initiates property form GUI class + * + * @param string $a_title + * @param string $a_cmd + * @param string $a_cmd_cancel + * @return ilPropertyFormGUI form class + */ + public function initPropertyForm($a_title, $a_cmd, $a_cmd_cancel) + { + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setTitle($a_title); + $form->setFormAction($this->ctrl->getFormAction($this, $a_cmd)); + $form->addCommandButton($a_cmd, $this->lng->txt("save")); + $form->addCommandButton($a_cmd_cancel, $this->lng->txt("cancel")); + + + require_once("Services/MetaData/classes/class.ilMDLanguageItem.php"); + $lang_var = ilMDLanguageItem::_getLanguages(); + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $lang = new ilSelectInputGUI($this->lng->txt("language"), "par_language"); + $lang->setOptions($lang_var); + $form->addItem($lang); + + $prog_langs = $this->getProgLangOptions(); + $code_style = new ilSelectInputGUI($this->lng->txt("cont_src"), "par_subcharacteristic"); + $code_style->setOptions($prog_langs); + $form->addItem($code_style); + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $line_number = new ilCheckboxInputGUI($this->lng->txt("cont_show_line_numbers"), "par_showlinenumbers"); + $form->addItem($line_number); + //$indent = new ilCheckboxInputGUI($this->lng->txt("cont_autoindent"), "par_autoindent"); + //$form->addItem($indent); + + + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $code = new ilTextAreaInputGUI("", "par_content"); + $code->setRows(12); + $form->addItem($code); + + include_once("./Services/Form/classes/class.ilTextInputGUI.php"); + $downlaod_title = new ilTextInputGUI($this->lng->txt("cont_download_title"), "par_downloadtitle"); + $downlaod_title->setSize(40); + $form->addItem($downlaod_title); + + include_once("./Services/Form/classes/class.ilFileInputGUI.php"); + $file = new ilFileInputGUI($this->lng->txt("import_file"), "userfile"); + $form->addItem($file); + + return $form; + } } diff --git a/Services/COPage/classes/class.ilPCTab.php b/Services/COPage/classes/class.ilPCTab.php index 61fdc5de124914865867f5d566299e7834b51d52..ef325c3930f3f80f54c3fd744c6e3fda4ca92596 100755 --- a/Services/COPage/classes/class.ilPCTab.php +++ b/Services/COPage/classes/class.ilPCTab.php @@ -16,78 +16,73 @@ require_once("./Services/COPage/classes/class.ilPageContent.php"); */ class ilPCTab extends ilPageContent { - var $dom; + public $dom; - /** - * Init page content component. - */ - function init() - { - $this->setType("tabstab"); - } + /** + * Init page content component. + */ + public function init() + { + $this->setType("tabstab"); + } - /** - * insert new tab item after current one - */ - function newItemAfter() - { - $tab = $this->getNode(); - $new_tab = $this->dom->create_element("Tab"); - if ($next_tab = $tab->next_sibling()) - { - $new_tab = $next_tab->insert_before($new_tab, $next_tab); - } - else - { - $parent_tabs = $tab->parent_node(); - $new_tab = $parent_tabs->append_child($new_tab); - } - } + /** + * insert new tab item after current one + */ + public function newItemAfter() + { + $tab = $this->getNode(); + $new_tab = $this->dom->create_element("Tab"); + if ($next_tab = $tab->next_sibling()) { + $new_tab = $next_tab->insert_before($new_tab, $next_tab); + } else { + $parent_tabs = $tab->parent_node(); + $new_tab = $parent_tabs->append_child($new_tab); + } + } - /** - * insert new tab item before current one - */ - function newItemBefore() - { - $tab = $this->getNode(); - $new_tab = $this->dom->create_element("Tab"); - $new_tab = $tab->insert_before($new_tab, $tab); - } + /** + * insert new tab item before current one + */ + public function newItemBefore() + { + $tab = $this->getNode(); + $new_tab = $this->dom->create_element("Tab"); + $new_tab = $tab->insert_before($new_tab, $tab); + } - /** - * delete tab - */ - function deleteItem() - { - $tab = $this->getNode(); - $tab->unlink($tab); - } + /** + * delete tab + */ + public function deleteItem() + { + $tab = $this->getNode(); + $tab->unlink($tab); + } - /** - * move tab item down - */ - function moveItemDown() - { - $tab = $this->getNode(); - $next = $tab->next_sibling(); - $next_copy = $next->clone_node(true); - $next_copy = $tab->insert_before($next_copy, $tab); - $next->unlink($next); - } - - /** - * move tab item up - */ - function moveItemUp() - { - $tab = $this->getNode(); - $prev = $tab->previous_sibling(); - $tab_copy = $tab->clone_node(true); - $tab_copy = $prev->insert_before($tab_copy, $prev); - $tab->unlink($tab); - } + /** + * move tab item down + */ + public function moveItemDown() + { + $tab = $this->getNode(); + $next = $tab->next_sibling(); + $next_copy = $next->clone_node(true); + $next_copy = $tab->insert_before($next_copy, $tab); + $next->unlink($next); + } + /** + * move tab item up + */ + public function moveItemUp() + { + $tab = $this->getNode(); + $prev = $tab->previous_sibling(); + $tab_copy = $tab->clone_node(true); + $tab_copy = $prev->insert_before($tab_copy, $prev); + $tab->unlink($tab); + } } -?> diff --git a/Services/COPage/classes/class.ilPCTabGUI.php b/Services/COPage/classes/class.ilPCTabGUI.php index 95d5d16b1ac81799935b3edee2eae9115f2f91f8..1e79e6abed5b28f7be88541fdd25379d2d658a81 100755 --- a/Services/COPage/classes/class.ilPCTabGUI.php +++ b/Services/COPage/classes/class.ilPCTabGUI.php @@ -9,26 +9,23 @@ class ilPCTabGUI extends ilPageContentGUI { - /** - * execute command - */ - function executeCommand() - { - // get next class that processes or forwards current command - $next_class = $this->ctrl->getNextClass($this); + /** + * 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(); + // get current command + $cmd = $this->ctrl->getCmd(); - switch($next_class) - { - default: - $ret = $this->$cmd(); - break; - } - - return $ret; - } + switch ($next_class) { + default: + $ret = $this->$cmd(); + break; + } + return $ret; + } } -?> diff --git a/Services/COPage/classes/class.ilPCTable.php b/Services/COPage/classes/class.ilPCTable.php index 24a90ef73261e0b3d731df9053e465fa04e9d867..450c8f1992f96a6651ba4b8e713bb4a321a832e0 100755 --- a/Services/COPage/classes/class.ilPCTable.php +++ b/Services/COPage/classes/class.ilPCTable.php @@ -16,1038 +16,929 @@ require_once("./Services/COPage/classes/class.ilPageContent.php"); */ class ilPCTable extends ilPageContent { - var $dom; - var $tab_node; - - - /** - * Init page content component. - */ - function init() - { - $this->setType("tab"); - } - - 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", ""); - } - - function &addRow () { - $new_tr = $this->dom->create_element("TableRow"); - $new_tr = &$this->tab_node->append_child($new_tr); - return $new_tr; - } - - function &addCell (&$aRow, $a_data = "", $a_lang = "") - { - $new_td = $this->dom->create_element("TableData"); - $new_td = $aRow->append_child($new_td); - - // insert data if given - if ($a_data != "") - { - $new_pg = $this->createPageContentNode(false); - $new_par = $this->dom->create_element("Paragraph"); - $new_par = $new_pg->append_child($new_par); - $new_par->set_attribute("Language", $a_lang); - $new_par->set_attribute("Characteristic", "TableContent"); - $new_par->set_content($a_data); - $new_td->append_child ($new_pg); - } - - return $new_td; - } - - /** - * add rows to table - */ - function addRows($a_nr_rows, $a_nr_cols) - { - for ($i=1; $i<=$a_nr_rows; $i++) - { - $aRow = $this->addRow(); - for ($j=1; $j<=$a_nr_cols; $j++) - { - $this->addCell($aRow); - } - } - } - - /** - * import from table - */ - function importSpreadsheet($a_lang, $a_data) - { - str_replace($a_data, "\r", "\n"); - str_replace($a_data, "\n\n", "\n"); - $target_rows = array(); - $rows = explode("\n", $a_data); - - // get maximum of cols in a row and - // put data in target_row arrays - foreach($rows as $row) - { - $cells = explode("\t", $row); - $max_cols = ($max_cols > count($cells)) - ? $max_cols - : count($cells); - $target_rows[] = $cells; - } - - // iterate target row arrays and insert data - foreach($target_rows as $row) - { - $aRow = $this->addRow(); - for ($j=0; $j<$max_cols; $j++) - { - // mask html - $data = str_replace("&","&", $row[$j]); - $data = str_replace("<","<", $data); - $data = str_replace(">",">", $data); - - $this->addCell($aRow, $data, $a_lang); - } - } - } - - /** - * get table language - */ - function getLanguage() - { - return $this->getTableAttribute("Language"); - } - - /** - * set table language - * - * @param string $a_lang language code - */ - function setLanguage($a_lang) - { - if($a_lang != "") - { - $this->setTableAttribute("Language", $a_lang); - } - } - - /** - * get table width - */ - function getWidth() - { - return $this->getTableAttribute("Width"); - } - - /** - * set table width - * - * @param string $a_width table width - */ - function setWidth($a_width) - { - $this->setTableAttribute("Width", $a_width); - } - - /** - * get table border width - */ - function getBorder() - { - return $this->getTableAttribute("Border"); - } - - /** - * set table border - * - * @param string $a_border table border - */ - function setBorder($a_border) - { - $this->setTableAttribute("Border", $a_border); - } - - /** - * get table cell spacing - */ - function getCellSpacing() - { - return $this->getTableAttribute("CellSpacing"); - } - - /** - * set table cell spacing - * - * @param string $a_spacing table cell spacing - */ - function setCellSpacing($a_spacing) - { - $this->setTableAttribute("CellSpacing", $a_spacing); - } - - /** - * get table cell padding - */ - function getCellPadding() - { - return $this->getTableAttribute("CellPadding"); - } - - /** - * set table cell padding - * - * @param string $a_padding table cell padding - */ - function setCellPadding($a_padding) - { - $this->setTableAttribute("CellPadding", $a_padding); - } - - /** - * set horizontal align - */ - function setHorizontalAlign($a_halign) - { - $this->tab_node->set_attribute("HorizontalAlign", $a_halign); - } - - /** - * get table cell padding - */ - function getHorizontalAlign() - { - return $this->getTableAttribute("HorizontalAlign"); - } - - /** - * set width of table data cell - */ - function setTDWidth($a_hier_id, $a_width, $a_pc_id = "") - { - $xpc = xpath_new_context($this->dom); - - if ($a_pc_id == "") - { - $path = "//TableData[@HierId = '".$a_hier_id."']"; - } - else - { - $path = "//TableData[@PCID = '".$a_pc_id."']"; - } - $res = xpath_eval($xpc, $path); - - if (count($res->nodeset) == 1) - { - if($a_width != "") - { - $res->nodeset[0]->set_attribute("Width", $a_width); - } - else - { - if ($res->nodeset[0]->has_attribute("Width")) - { - $res->nodeset[0]->remove_attribute("Width"); - } - } - } - } - - /** - * Set TDSpans - */ - function setTDSpans($a_colspans, $a_rowspans) - { - $y = 0; - $rows = $this->tab_node->child_nodes(); - foreach($rows as $row) - { - if ($row->node_name() == "TableRow") - { - $x = 0; - $cells = $row->child_nodes(); - foreach($cells as $cell) - { - if ($cell->node_name() == "TableData") - { - $ckey = $cell->get_attribute("HierId").":".$cell->get_attribute("PCID"); - if((int) $a_colspans[$ckey] > 1) - { - $cell->set_attribute("ColSpan", (int) $a_colspans[$ckey]); - } - else - { - if ($cell->has_attribute("ColSpan")) - { - $cell->remove_attribute("ColSpan"); - } - } - if((int) $a_rowspans[$ckey] > 1) - { - $cell->set_attribute("RowSpan", (int) $a_rowspans[$ckey]); - } - else - { - if ($cell->has_attribute("RowSpan")) - { - $cell->remove_attribute("RowSpan"); - } - } - } - $x++; - } - $y++; - } - } - $this->fixHideAndSpans(); - } - - /** - * Fix Hide and Spans. Reduces col and rowspans that are to high. - * Sets Hide attribute for all cells that are hidden due to other span - * attributes. Sets hidden cells to empty. - */ - function fixHideAndSpans() - { - - // first: get max x and y - $max_x = $max_y = 0; - $y = 0; - $rows = $this->tab_node->child_nodes(); - - foreach($rows as $row) - { - if ($row->node_name() == "TableRow") - { - $x = 0; - $cells = $row->child_nodes(); - foreach($cells as $cell) - { - if ($cell->node_name() == "TableData") - { - $max_x = max ($max_x, $x); - $max_y = max ($max_y, $y); - } - $x++; - } - $y++; - } - } - - // second: fix hidden/colspans for all cells - $y = 0; - $rows = $this->tab_node->child_nodes(); - foreach($rows as $row) - { - if ($row->node_name() == "TableRow") - { - $x = 0; - $cells = $row->child_nodes(); - foreach($cells as $cell) - { - if ($cell->node_name() == "TableData") - { - $cspan = max(1, (int) $cell->get_attribute("ColSpan")); - $rspan = max(1, (int) $cell->get_attribute("RowSpan")); - - // if col or rowspan is to high: reduce it to the max - if ($cspan > $max_x - $x + 1) - { - $cell->set_attribute("ColSpan", $max_x - $x + 1); - $cspan = $max_x - $x + 1; - } - if ($rspan > $max_y - $y + 1) - { - $cell->set_attribute("RowSpan", $max_y - $y + 1); - $rspan = $max_y - $y + 1; - } - - // check hidden status - if ($this->checkCellHidden($colspans, $rowspans, $x, $y)) - { - // hidden: set hidden flag, remove col and rowspan - $cell->set_attribute("Hidden", "Y"); - $cspan = 1; - $rspan = 1; - if ($cell->has_attribute("ColSpan")) - { - $cell->remove_attribute("ColSpan"); - } - if ($cell->has_attribute("RowSpan")) - { - $cell->remove_attribute("RowSpan"); - } - $this->makeEmptyCell($cell); - } - else - { - // not hidden: remove hidden flag if existing - if ($cell->has_attribute("Hidden")) - { - $cell->remove_attribute("Hidden"); - } - } - - $colspans[$x][$y] = $cspan; - $rowspans[$x][$y] = $rspan; - } - $x++; - } - $y++; - } - } - - } - - - /** - * Make cell empty - */ - function makeEmptyCell($td_node) - { - // delete children of paragraph node - $children = $td_node->child_nodes(); - for($i=0; $iremove_child($children[$i]); - } - } - - /** - * Check hidden status - */ - function checkCellHidden($colspans, $rowspans, $x, $y) - { - for ($i = 0; $i<=$x; $i++) - { - for ($j = 0; $j<=$y; $j++) - { - if ($i != $x || $j != $y) - { - if ((($i + $colspans[$i][$j] > $x) && - ($j + $rowspans[$i][$j] > $y))) - { - return true; - } - } - } - } - return false; - } - - /** - * Get all cell classes - * - * @return array array of cell style classes - */ - function getAllCellClasses() - { - $classes = array(); - $rows = $this->tab_node->child_nodes(); - foreach($rows as $row) - { - if ($row->node_name() == "TableRow") - { - $cells = $row->child_nodes(); - foreach($cells as $cell) - { - if ($cell->node_name() == "TableData") - { - $classes[$cell->get_attribute("HierId").":".$cell->get_attribute("PCID")] - = $cell->get_attribute("Class"); - } - } - } - } - - return $classes; - } - - /** - * Get all cell alignments - * - * @return array array of cell alignments - */ - function getAllCellAlignments() - { - $classes = array(); - $rows = $this->tab_node->child_nodes(); - foreach($rows as $row) - { - if ($row->node_name() == "TableRow") - { - $cells = $row->child_nodes(); - foreach($cells as $cell) - { - if ($cell->node_name() == "TableData") - { - $classes[$cell->get_attribute("HierId").":".$cell->get_attribute("PCID")] - = $cell->get_attribute("HorizontalAlign"); - } - } - } - } - - return $classes; - } - - /** - * Get all cell spans - * - * @return array array of cell style classes - */ - function getAllCellSpans() - { - $spans = array(); - $rows = $this->tab_node->child_nodes(); - $y = 0; - $max_x = 0; - $max_y = 0; - foreach($rows as $row) - { - if ($row->node_name() == "TableRow") - { - $x = 0; - $cells = $row->child_nodes(); - foreach($cells as $cell) - { - if ($cell->node_name() == "TableData") - { - $spans[$cell->get_attribute("HierId").":".$cell->get_attribute("PCID")] - = array("x" => $x, "y" => $y, "colspan" => $cell->get_attribute("ColSpan"), - "rowspan" => $cell->get_attribute("RowSpan")); - $max_x = max($max_x, $x); - $max_y = max($max_y, $y); - } - $x++; - } - $y++; - } - } - foreach ($spans as $k => $v) - { - $spans[$k]["max_x"] = $max_x; - $spans[$k]["max_y"] = $max_y; - } - - return $spans; - } - - /** - * Get all cell widhts - * - * @return array array of cell style classes - */ - function getAllCellWidths() - { - $widths = array(); - $rows = $this->tab_node->child_nodes(); - foreach($rows as $row) - { - if ($row->node_name() == "TableRow") - { - $cells = $row->child_nodes(); - foreach($cells as $cell) - { - if ($cell->node_name() == "TableData") - { - $widths[$cell->get_attribute("HierId").":".$cell->get_attribute("PCID")] - = $cell->get_attribute("Width"); - } - } - } - } - - return $widths; - } - - /** - * set class of table data cell - */ - function setTDClass($a_hier_id, $a_class, $a_pc_id = "") - { - $xpc = xpath_new_context($this->dom); - if ($a_pc_id == "") - { - $path = "//TableData[@HierId = '".$a_hier_id."']"; - } - else - { - $path = "//TableData[@PCID = '".$a_pc_id."']"; - } - $res = xpath_eval($xpc, $path); - if (count($res->nodeset) == 1) - { - if($a_class != "") - { - $res->nodeset[0]->set_attribute("Class", $a_class); - } - else - { - if ($res->nodeset[0]->has_attribute("Class")) - { - $res->nodeset[0]->remove_attribute("Class"); - } - } - } - } - - /** - * set alignment of table data cell - */ - function setTDAlignment($a_hier_id, $a_class, $a_pc_id = "") - { - $xpc = xpath_new_context($this->dom); - if ($a_pc_id == "") - { - $path = "//TableData[@HierId = '".$a_hier_id."']"; - } - else - { - $path = "//TableData[@PCID = '".$a_pc_id."']"; - } - $res = xpath_eval($xpc, $path); - if (count($res->nodeset) == 1) - { - if($a_class != "") - { - $res->nodeset[0]->set_attribute("HorizontalAlign", $a_class); - } - else - { - if ($res->nodeset[0]->has_attribute("HorizontalAlign")) - { - $res->nodeset[0]->remove_attribute("HorizontalAlign"); - } - } - } - } - - /** - * get caption - */ - function getCaption() - { - $hier_id = $this->getHierId(); - if(!empty($hier_id)) - { - $xpc = xpath_new_context($this->dom); - $path = "//PageContent[@HierId = '".$hier_id."']/Table/Caption"; - $res = xpath_eval($xpc, $path); - - if (count($res->nodeset) == 1) - { - return $res->nodeset[0]->get_content(); - } - } - } - - /** - * get caption alignment (Top | Bottom) - */ - function getCaptionAlign() - { - $hier_id = $this->getHierId(); - if(!empty($hier_id)) - { - $xpc = xpath_new_context($this->dom); - $path = "//PageContent[@HierId = '".$hier_id."']/Table/Caption"; - $res = xpath_eval($xpc, $path); - if (count($res->nodeset) == 1) - { - return $res->nodeset[0]->get_attribute("Align"); - } - } - } - - /** - * set table caption - */ - function setCaption($a_content, $a_align) - { - if ($a_content != "") - { - ilDOMUtil::setFirstOptionalElement($this->dom, $this->tab_node, "Caption", - array("Summary", "TableRow"), $a_content, - array("Align" => $a_align)); - } - else - { - ilDOMUtil::deleteAllChildsByName($this->tab_node, array("Caption")); - } - } - - - function importTableAttributes (&$node) { - /*echo "importing table attributes"; - var_dump($tableNode);*/ - if ($node->has_attributes ()) - { - foreach($node->attributes() as $n) - { - - switch (strtolower($n->node_name ())) { - case "border": - $this->setBorder ($this->extractText($n)); - break; - case "align": - $this->setHorizontalAlign(ucfirst(strtolower($this->extractText($n)))); - break; - case "cellspacing": - $this->setCellSpacing($this->extractText($n)); - break; - case "cellpadding": - $this->setCellPadding($this->extractText($n)); - break; - case "width": - $this->setWidth($this->extractText($n)); - break; - - } - - } - } - } - - - function importCellAttributes (&$node, &$par) { - /*echo "importing table attributes"; - var_dump($tableNode);*/ - if ($node->has_attributes ()) - { - foreach($node->attributes() as $n) - { - - switch (strtolower($n->node_name ())) { - case "class": - $par->set_attribute("Class", $this->extractText($n)); - break; - case "width": - $par->set_attribute("Width", $this->extractText($n)); - break; - } - - } - } - } - - - function importRow ($lng, &$node) { - /*echo "add Row"; - var_dump($node);*/ - - $aRow = $this->addRow(); - - if ($node->has_child_nodes()) - { - foreach($node->child_nodes() as $n) - { - if ($n->node_type() == XML_ELEMENT_NODE && - strcasecmp($n->node_name (), "td") == 0) - { - $this->importCell ($lng, $n, $aRow); - } - } - } - } - - function importCell ($lng, &$cellNode, &$aRow) { - /*echo "add Cell"; - var_dump($cellNode);*/ - $aCell = $this->addCell($aRow); - $par = new ilPCParagraph($this->getPage()); - $par->createAtNode($aCell); - $par->setText($par->input2xml($this->extractText($cellNode))); - $par->setCharacteristic("TableContent"); - $par->setLanguage($lng); - $this->importCellAttributes($cellNode, $aCell); - } - - function extractText (&$node) { - $owner_document = $node->owner_document (); - $children = $node->child_nodes(); - $total_children = count($children); - for ($i = 0; $i < $total_children; $i++){ - $cur_child_node = $children[$i]; - $output .= $owner_document->dump_node($cur_child_node); - } - return $output; - } - - function importHtml ($lng, $htmlTable) { - $dummy = ilUtil::stripSlashes($htmlTable, false); - //echo htmlentities($dummy); - $dom = @domxml_open_mem($dummy,DOMXML_LOAD_PARSING, $error); - - if ($dom) - { - $xpc = @xpath_new_context($dom); - // extract first table object - $path = "//table[1] | //Table[1]"; - $res = @xpath_eval($xpc, $path); - - if (count($res->nodeset) == 0) - { - $error = "Could not find a table root node"; - } - - if (empty ($error)) - { - for($i = 0; $i < count($res->nodeset); $i++) - { - $node = $res->nodeset[$i]; - - $this->importTableAttributes ($node); - - if ($node->has_child_nodes()) - { - foreach($node->child_nodes() as $n) - { - if ($n->node_type() == XML_ELEMENT_NODE && - strcasecmp($n->node_name (), "tr") == 0) - { - - $this->importRow ($lng, $n); - } - } - } - } - } - $dom->free (); - } - if (is_array($error)) { - $errmsg = ""; - foreach ($error as $errorline) { # Loop through all errors - $errmsg .= "[" . $errorline['line'] . ", " . $errorline['col'] . "]: ".$errorline['errormessage']." at Node '". $errorline['nodename'] . "'
          "; - } - }else - { - $errmsg = $error; - } - - if (empty ($errmsg)) { - return true; - } - - $_SESSION["message"] = $errmsg; - return false; - } - - /** - * Set first row td style - */ - function setFirstRowStyle($a_class) - { - $childs = $this->tab_node->child_nodes(); - foreach($childs as $child) - { - if ($child->node_name() == "TableRow") - { - $gchilds = $child->child_nodes(); - foreach($gchilds as $gchild) - { - if ($gchild->node_name() == "TableData") - { - $gchild->set_attribute("Class", $a_class); - } - } - return; - } - } - } - - /** - * Set Style Class of table - * - * @param string $a_class class - */ - function setClass($a_class) - { - $this->setTableAttribute("Class", $a_class); - } - - /** - * Get characteristic of section. - * - * @return string characteristic - */ - function getClass() - { - return $this->getTableAttribute("Class"); - } - - /** - * Set template - * - * @param string $a_template template - */ - function setTemplate($a_template) - { - $this->setTableAttribute("Template", $a_template); - } - - /** - * Get template - * - * @return string template - */ - function getTemplate() - { - return $this->getTableAttribute("Template"); - } - - /** - * Set header rows - * - * @param string number of header rows - */ - function setHeaderRows($a_nr) - { - $this->setTableAttribute("HeaderRows", $a_nr); - } - - /** - * Get header rows - * - * @return string number of header rows - */ - function getHeaderRows() - { - return $this->getTableAttribute("HeaderRows"); - } - - /** - * Set footer rows - * - * @param string number of footer rows - */ - function setFooterRows($a_nr) - { - $this->setTableAttribute("FooterRows", $a_nr); - } - - /** - * Get footer rows - * - * @return string number of footer rows - */ - function getFooterRows() - { - return $this->getTableAttribute("FooterRows"); - } - - /** - * Set header cols - * - * @param string number of header cols - */ - function setHeaderCols($a_nr) - { - $this->setTableAttribute("HeaderCols", $a_nr); - } - - /** - * Get header cols - * - * @return string number of header cols - */ - function getHeaderCols() - { - return $this->getTableAttribute("HeaderCols"); - } - - /** - * Set footer cols - * - * @param string number of footer cols - */ - function setFooterCols($a_nr) - { - $this->setTableAttribute("FooterCols", $a_nr); - } - - /** - * Get footer cols - * - * @return string number of footer cols - */ - function getFooterCols() - { - return $this->getTableAttribute("FooterCols"); - } - - /** - * Set attribute of table tag - * - * @param string attribute name - * @param string attribute value - */ - protected function setTableAttribute($a_attr, $a_value) - { - if (!empty($a_value)) - { - $this->tab_node->set_attribute($a_attr, $a_value); - } - else - { - if ($this->tab_node->has_attribute($a_attr)) - { - $this->tab_node->remove_attribute($a_attr); - } - } - } - - /** - * Get table tag attribute - * - * @return string attribute name - */ - function getTableAttribute($a_attr) - { - if (is_object($this->tab_node)) - { - return $this->tab_node->get_attribute($a_attr); - } - } - - /** - * Get lang vars needed for editing - * @return array array of lang var keys - */ - static function getLangVars() - { - return array("ed_insert_dtable", "ed_insert_atable","ed_new_row_after", "ed_new_row_before", - "ed_new_col_after", "ed_new_col_before", "ed_delete_col", - "ed_delete_row", "ed_edit_data", "ed_row_up", "ed_row_down", - "ed_col_left", "ed_col_right"); - } - - - /** - * Handle copied content. This function must, e.g. create copies of - * objects referenced within the content (e.g. question objects) - * - * @param DOMDocument $a_domdoc dom document - */ - static function handleCopiedContent(DOMDocument $a_domdoc, $a_self_ass = true, $a_clone_mobs = false) - { - $xpath = new DOMXPath($a_domdoc); - $nodes = $xpath->query("//Table"); - foreach($nodes as $node) - { - $node->removeAttribute("Id"); - } - } + public $dom; + public $tab_node; + + + /** + * Init page content component. + */ + public function init() + { + $this->setType("tab"); + } + + 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 + } + + public 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", ""); + } + + public function &addRow() + { + $new_tr = $this->dom->create_element("TableRow"); + $new_tr = &$this->tab_node->append_child($new_tr); + return $new_tr; + } + + public function &addCell(&$aRow, $a_data = "", $a_lang = "") + { + $new_td = $this->dom->create_element("TableData"); + $new_td = $aRow->append_child($new_td); + + // insert data if given + if ($a_data != "") { + $new_pg = $this->createPageContentNode(false); + $new_par = $this->dom->create_element("Paragraph"); + $new_par = $new_pg->append_child($new_par); + $new_par->set_attribute("Language", $a_lang); + $new_par->set_attribute("Characteristic", "TableContent"); + $new_par->set_content($a_data); + $new_td->append_child($new_pg); + } + + return $new_td; + } + + /** + * add rows to table + */ + public function addRows($a_nr_rows, $a_nr_cols) + { + for ($i=1; $i<=$a_nr_rows; $i++) { + $aRow = $this->addRow(); + for ($j=1; $j<=$a_nr_cols; $j++) { + $this->addCell($aRow); + } + } + } + + /** + * import from table + */ + public function importSpreadsheet($a_lang, $a_data) + { + str_replace($a_data, "\r", "\n"); + str_replace($a_data, "\n\n", "\n"); + $target_rows = array(); + $rows = explode("\n", $a_data); + + // get maximum of cols in a row and + // put data in target_row arrays + foreach ($rows as $row) { + $cells = explode("\t", $row); + $max_cols = ($max_cols > count($cells)) + ? $max_cols + : count($cells); + $target_rows[] = $cells; + } + + // iterate target row arrays and insert data + foreach ($target_rows as $row) { + $aRow = $this->addRow(); + for ($j=0; $j<$max_cols; $j++) { + // mask html + $data = str_replace("&", "&", $row[$j]); + $data = str_replace("<", "<", $data); + $data = str_replace(">", ">", $data); + + $this->addCell($aRow, $data, $a_lang); + } + } + } + + /** + * get table language + */ + public function getLanguage() + { + return $this->getTableAttribute("Language"); + } + + /** + * set table language + * + * @param string $a_lang language code + */ + public function setLanguage($a_lang) + { + if ($a_lang != "") { + $this->setTableAttribute("Language", $a_lang); + } + } + + /** + * get table width + */ + public function getWidth() + { + return $this->getTableAttribute("Width"); + } + + /** + * set table width + * + * @param string $a_width table width + */ + public function setWidth($a_width) + { + $this->setTableAttribute("Width", $a_width); + } + + /** + * get table border width + */ + public function getBorder() + { + return $this->getTableAttribute("Border"); + } + + /** + * set table border + * + * @param string $a_border table border + */ + public function setBorder($a_border) + { + $this->setTableAttribute("Border", $a_border); + } + + /** + * get table cell spacing + */ + public function getCellSpacing() + { + return $this->getTableAttribute("CellSpacing"); + } + + /** + * set table cell spacing + * + * @param string $a_spacing table cell spacing + */ + public function setCellSpacing($a_spacing) + { + $this->setTableAttribute("CellSpacing", $a_spacing); + } + + /** + * get table cell padding + */ + public function getCellPadding() + { + return $this->getTableAttribute("CellPadding"); + } + + /** + * set table cell padding + * + * @param string $a_padding table cell padding + */ + public function setCellPadding($a_padding) + { + $this->setTableAttribute("CellPadding", $a_padding); + } + + /** + * set horizontal align + */ + public function setHorizontalAlign($a_halign) + { + $this->tab_node->set_attribute("HorizontalAlign", $a_halign); + } + + /** + * get table cell padding + */ + public function getHorizontalAlign() + { + return $this->getTableAttribute("HorizontalAlign"); + } + + /** + * set width of table data cell + */ + public function setTDWidth($a_hier_id, $a_width, $a_pc_id = "") + { + $xpc = xpath_new_context($this->dom); + + if ($a_pc_id == "") { + $path = "//TableData[@HierId = '" . $a_hier_id . "']"; + } else { + $path = "//TableData[@PCID = '" . $a_pc_id . "']"; + } + $res = xpath_eval($xpc, $path); + + if (count($res->nodeset) == 1) { + if ($a_width != "") { + $res->nodeset[0]->set_attribute("Width", $a_width); + } else { + if ($res->nodeset[0]->has_attribute("Width")) { + $res->nodeset[0]->remove_attribute("Width"); + } + } + } + } + + /** + * Set TDSpans + */ + public function setTDSpans($a_colspans, $a_rowspans) + { + $y = 0; + $rows = $this->tab_node->child_nodes(); + foreach ($rows as $row) { + if ($row->node_name() == "TableRow") { + $x = 0; + $cells = $row->child_nodes(); + foreach ($cells as $cell) { + if ($cell->node_name() == "TableData") { + $ckey = $cell->get_attribute("HierId") . ":" . $cell->get_attribute("PCID"); + if ((int) $a_colspans[$ckey] > 1) { + $cell->set_attribute("ColSpan", (int) $a_colspans[$ckey]); + } else { + if ($cell->has_attribute("ColSpan")) { + $cell->remove_attribute("ColSpan"); + } + } + if ((int) $a_rowspans[$ckey] > 1) { + $cell->set_attribute("RowSpan", (int) $a_rowspans[$ckey]); + } else { + if ($cell->has_attribute("RowSpan")) { + $cell->remove_attribute("RowSpan"); + } + } + } + $x++; + } + $y++; + } + } + $this->fixHideAndSpans(); + } + + /** + * Fix Hide and Spans. Reduces col and rowspans that are to high. + * Sets Hide attribute for all cells that are hidden due to other span + * attributes. Sets hidden cells to empty. + */ + public function fixHideAndSpans() + { + + // first: get max x and y + $max_x = $max_y = 0; + $y = 0; + $rows = $this->tab_node->child_nodes(); + + foreach ($rows as $row) { + if ($row->node_name() == "TableRow") { + $x = 0; + $cells = $row->child_nodes(); + foreach ($cells as $cell) { + if ($cell->node_name() == "TableData") { + $max_x = max($max_x, $x); + $max_y = max($max_y, $y); + } + $x++; + } + $y++; + } + } + + // second: fix hidden/colspans for all cells + $y = 0; + $rows = $this->tab_node->child_nodes(); + foreach ($rows as $row) { + if ($row->node_name() == "TableRow") { + $x = 0; + $cells = $row->child_nodes(); + foreach ($cells as $cell) { + if ($cell->node_name() == "TableData") { + $cspan = max(1, (int) $cell->get_attribute("ColSpan")); + $rspan = max(1, (int) $cell->get_attribute("RowSpan")); + + // if col or rowspan is to high: reduce it to the max + if ($cspan > $max_x - $x + 1) { + $cell->set_attribute("ColSpan", $max_x - $x + 1); + $cspan = $max_x - $x + 1; + } + if ($rspan > $max_y - $y + 1) { + $cell->set_attribute("RowSpan", $max_y - $y + 1); + $rspan = $max_y - $y + 1; + } + + // check hidden status + if ($this->checkCellHidden($colspans, $rowspans, $x, $y)) { + // hidden: set hidden flag, remove col and rowspan + $cell->set_attribute("Hidden", "Y"); + $cspan = 1; + $rspan = 1; + if ($cell->has_attribute("ColSpan")) { + $cell->remove_attribute("ColSpan"); + } + if ($cell->has_attribute("RowSpan")) { + $cell->remove_attribute("RowSpan"); + } + $this->makeEmptyCell($cell); + } else { + // not hidden: remove hidden flag if existing + if ($cell->has_attribute("Hidden")) { + $cell->remove_attribute("Hidden"); + } + } + + $colspans[$x][$y] = $cspan; + $rowspans[$x][$y] = $rspan; + } + $x++; + } + $y++; + } + } + } + + + /** + * Make cell empty + */ + public function makeEmptyCell($td_node) + { + // delete children of paragraph node + $children = $td_node->child_nodes(); + for ($i=0; $iremove_child($children[$i]); + } + } + + /** + * Check hidden status + */ + public function checkCellHidden($colspans, $rowspans, $x, $y) + { + for ($i = 0; $i<=$x; $i++) { + for ($j = 0; $j<=$y; $j++) { + if ($i != $x || $j != $y) { + if ((($i + $colspans[$i][$j] > $x) && + ($j + $rowspans[$i][$j] > $y))) { + return true; + } + } + } + } + return false; + } + + /** + * Get all cell classes + * + * @return array array of cell style classes + */ + public function getAllCellClasses() + { + $classes = array(); + $rows = $this->tab_node->child_nodes(); + foreach ($rows as $row) { + if ($row->node_name() == "TableRow") { + $cells = $row->child_nodes(); + foreach ($cells as $cell) { + if ($cell->node_name() == "TableData") { + $classes[$cell->get_attribute("HierId") . ":" . $cell->get_attribute("PCID")] + = $cell->get_attribute("Class"); + } + } + } + } + + return $classes; + } + + /** + * Get all cell alignments + * + * @return array array of cell alignments + */ + public function getAllCellAlignments() + { + $classes = array(); + $rows = $this->tab_node->child_nodes(); + foreach ($rows as $row) { + if ($row->node_name() == "TableRow") { + $cells = $row->child_nodes(); + foreach ($cells as $cell) { + if ($cell->node_name() == "TableData") { + $classes[$cell->get_attribute("HierId") . ":" . $cell->get_attribute("PCID")] + = $cell->get_attribute("HorizontalAlign"); + } + } + } + } + + return $classes; + } + + /** + * Get all cell spans + * + * @return array array of cell style classes + */ + public function getAllCellSpans() + { + $spans = array(); + $rows = $this->tab_node->child_nodes(); + $y = 0; + $max_x = 0; + $max_y = 0; + foreach ($rows as $row) { + if ($row->node_name() == "TableRow") { + $x = 0; + $cells = $row->child_nodes(); + foreach ($cells as $cell) { + if ($cell->node_name() == "TableData") { + $spans[$cell->get_attribute("HierId") . ":" . $cell->get_attribute("PCID")] + = array("x" => $x, "y" => $y, "colspan" => $cell->get_attribute("ColSpan"), + "rowspan" => $cell->get_attribute("RowSpan")); + $max_x = max($max_x, $x); + $max_y = max($max_y, $y); + } + $x++; + } + $y++; + } + } + foreach ($spans as $k => $v) { + $spans[$k]["max_x"] = $max_x; + $spans[$k]["max_y"] = $max_y; + } + + return $spans; + } + + /** + * Get all cell widhts + * + * @return array array of cell style classes + */ + public function getAllCellWidths() + { + $widths = array(); + $rows = $this->tab_node->child_nodes(); + foreach ($rows as $row) { + if ($row->node_name() == "TableRow") { + $cells = $row->child_nodes(); + foreach ($cells as $cell) { + if ($cell->node_name() == "TableData") { + $widths[$cell->get_attribute("HierId") . ":" . $cell->get_attribute("PCID")] + = $cell->get_attribute("Width"); + } + } + } + } + + return $widths; + } + + /** + * set class of table data cell + */ + public function setTDClass($a_hier_id, $a_class, $a_pc_id = "") + { + $xpc = xpath_new_context($this->dom); + if ($a_pc_id == "") { + $path = "//TableData[@HierId = '" . $a_hier_id . "']"; + } else { + $path = "//TableData[@PCID = '" . $a_pc_id . "']"; + } + $res = xpath_eval($xpc, $path); + if (count($res->nodeset) == 1) { + if ($a_class != "") { + $res->nodeset[0]->set_attribute("Class", $a_class); + } else { + if ($res->nodeset[0]->has_attribute("Class")) { + $res->nodeset[0]->remove_attribute("Class"); + } + } + } + } + + /** + * set alignment of table data cell + */ + public function setTDAlignment($a_hier_id, $a_class, $a_pc_id = "") + { + $xpc = xpath_new_context($this->dom); + if ($a_pc_id == "") { + $path = "//TableData[@HierId = '" . $a_hier_id . "']"; + } else { + $path = "//TableData[@PCID = '" . $a_pc_id . "']"; + } + $res = xpath_eval($xpc, $path); + if (count($res->nodeset) == 1) { + if ($a_class != "") { + $res->nodeset[0]->set_attribute("HorizontalAlign", $a_class); + } else { + if ($res->nodeset[0]->has_attribute("HorizontalAlign")) { + $res->nodeset[0]->remove_attribute("HorizontalAlign"); + } + } + } + } + + /** + * get caption + */ + public function getCaption() + { + $hier_id = $this->getHierId(); + if (!empty($hier_id)) { + $xpc = xpath_new_context($this->dom); + $path = "//PageContent[@HierId = '" . $hier_id . "']/Table/Caption"; + $res = xpath_eval($xpc, $path); + + if (count($res->nodeset) == 1) { + return $res->nodeset[0]->get_content(); + } + } + } + + /** + * get caption alignment (Top | Bottom) + */ + public function getCaptionAlign() + { + $hier_id = $this->getHierId(); + if (!empty($hier_id)) { + $xpc = xpath_new_context($this->dom); + $path = "//PageContent[@HierId = '" . $hier_id . "']/Table/Caption"; + $res = xpath_eval($xpc, $path); + if (count($res->nodeset) == 1) { + return $res->nodeset[0]->get_attribute("Align"); + } + } + } + + /** + * set table caption + */ + public function setCaption($a_content, $a_align) + { + if ($a_content != "") { + ilDOMUtil::setFirstOptionalElement( + $this->dom, + $this->tab_node, + "Caption", + array("Summary", "TableRow"), + $a_content, + array("Align" => $a_align) + ); + } else { + ilDOMUtil::deleteAllChildsByName($this->tab_node, array("Caption")); + } + } + + + public function importTableAttributes(&$node) + { + /*echo "importing table attributes"; + var_dump($tableNode);*/ + if ($node->has_attributes()) { + foreach ($node->attributes() as $n) { + switch (strtolower($n->node_name())) { + case "border": + $this->setBorder($this->extractText($n)); + break; + case "align": + $this->setHorizontalAlign(ucfirst(strtolower($this->extractText($n)))); + break; + case "cellspacing": + $this->setCellSpacing($this->extractText($n)); + break; + case "cellpadding": + $this->setCellPadding($this->extractText($n)); + break; + case "width": + $this->setWidth($this->extractText($n)); + break; + + } + } + } + } + + + public function importCellAttributes(&$node, &$par) + { + /*echo "importing table attributes"; + var_dump($tableNode);*/ + if ($node->has_attributes()) { + foreach ($node->attributes() as $n) { + switch (strtolower($n->node_name())) { + case "class": + $par->set_attribute("Class", $this->extractText($n)); + break; + case "width": + $par->set_attribute("Width", $this->extractText($n)); + break; + } + } + } + } + + + public function importRow($lng, &$node) + { + /*echo "add Row"; + var_dump($node);*/ + + $aRow = $this->addRow(); + + if ($node->has_child_nodes()) { + foreach ($node->child_nodes() as $n) { + if ($n->node_type() == XML_ELEMENT_NODE && + strcasecmp($n->node_name(), "td") == 0) { + $this->importCell($lng, $n, $aRow); + } + } + } + } + + public function importCell($lng, &$cellNode, &$aRow) + { + /*echo "add Cell"; + var_dump($cellNode);*/ + $aCell = $this->addCell($aRow); + $par = new ilPCParagraph($this->getPage()); + $par->createAtNode($aCell); + $par->setText($par->input2xml($this->extractText($cellNode))); + $par->setCharacteristic("TableContent"); + $par->setLanguage($lng); + $this->importCellAttributes($cellNode, $aCell); + } + + public function extractText(&$node) + { + $owner_document = $node->owner_document(); + $children = $node->child_nodes(); + $total_children = count($children); + for ($i = 0; $i < $total_children; $i++) { + $cur_child_node = $children[$i]; + $output .= $owner_document->dump_node($cur_child_node); + } + return $output; + } + + public function importHtml($lng, $htmlTable) + { + $dummy = ilUtil::stripSlashes($htmlTable, false); + //echo htmlentities($dummy); + $dom = @domxml_open_mem($dummy, DOMXML_LOAD_PARSING, $error); + + if ($dom) { + $xpc = @xpath_new_context($dom); + // extract first table object + $path = "//table[1] | //Table[1]"; + $res = @xpath_eval($xpc, $path); + + if (count($res->nodeset) == 0) { + $error = "Could not find a table root node"; + } + + if (empty($error)) { + for ($i = 0; $i < count($res->nodeset); $i++) { + $node = $res->nodeset[$i]; + + $this->importTableAttributes($node); + + if ($node->has_child_nodes()) { + foreach ($node->child_nodes() as $n) { + if ($n->node_type() == XML_ELEMENT_NODE && + strcasecmp($n->node_name(), "tr") == 0) { + $this->importRow($lng, $n); + } + } + } + } + } + $dom->free(); + } + if (is_array($error)) { + $errmsg = ""; + foreach ($error as $errorline) { # Loop through all errors + $errmsg .= "[" . $errorline['line'] . ", " . $errorline['col'] . "]: " . $errorline['errormessage'] . " at Node '" . $errorline['nodename'] . "'
          "; + } + } else { + $errmsg = $error; + } + + if (empty($errmsg)) { + return true; + } + + $_SESSION["message"] = $errmsg; + return false; + } + + /** + * Set first row td style + */ + public function setFirstRowStyle($a_class) + { + $childs = $this->tab_node->child_nodes(); + foreach ($childs as $child) { + if ($child->node_name() == "TableRow") { + $gchilds = $child->child_nodes(); + foreach ($gchilds as $gchild) { + if ($gchild->node_name() == "TableData") { + $gchild->set_attribute("Class", $a_class); + } + } + return; + } + } + } + + /** + * Set Style Class of table + * + * @param string $a_class class + */ + public function setClass($a_class) + { + $this->setTableAttribute("Class", $a_class); + } + + /** + * Get characteristic of section. + * + * @return string characteristic + */ + public function getClass() + { + return $this->getTableAttribute("Class"); + } + + /** + * Set template + * + * @param string $a_template template + */ + public function setTemplate($a_template) + { + $this->setTableAttribute("Template", $a_template); + } + + /** + * Get template + * + * @return string template + */ + public function getTemplate() + { + return $this->getTableAttribute("Template"); + } + + /** + * Set header rows + * + * @param string number of header rows + */ + public function setHeaderRows($a_nr) + { + $this->setTableAttribute("HeaderRows", $a_nr); + } + + /** + * Get header rows + * + * @return string number of header rows + */ + public function getHeaderRows() + { + return $this->getTableAttribute("HeaderRows"); + } + + /** + * Set footer rows + * + * @param string number of footer rows + */ + public function setFooterRows($a_nr) + { + $this->setTableAttribute("FooterRows", $a_nr); + } + + /** + * Get footer rows + * + * @return string number of footer rows + */ + public function getFooterRows() + { + return $this->getTableAttribute("FooterRows"); + } + + /** + * Set header cols + * + * @param string number of header cols + */ + public function setHeaderCols($a_nr) + { + $this->setTableAttribute("HeaderCols", $a_nr); + } + + /** + * Get header cols + * + * @return string number of header cols + */ + public function getHeaderCols() + { + return $this->getTableAttribute("HeaderCols"); + } + + /** + * Set footer cols + * + * @param string number of footer cols + */ + public function setFooterCols($a_nr) + { + $this->setTableAttribute("FooterCols", $a_nr); + } + + /** + * Get footer cols + * + * @return string number of footer cols + */ + public function getFooterCols() + { + return $this->getTableAttribute("FooterCols"); + } + + /** + * Set attribute of table tag + * + * @param string attribute name + * @param string attribute value + */ + protected function setTableAttribute($a_attr, $a_value) + { + if (!empty($a_value)) { + $this->tab_node->set_attribute($a_attr, $a_value); + } else { + if ($this->tab_node->has_attribute($a_attr)) { + $this->tab_node->remove_attribute($a_attr); + } + } + } + + /** + * Get table tag attribute + * + * @return string attribute name + */ + public function getTableAttribute($a_attr) + { + if (is_object($this->tab_node)) { + return $this->tab_node->get_attribute($a_attr); + } + } + + /** + * Get lang vars needed for editing + * @return array array of lang var keys + */ + public static function getLangVars() + { + return array("ed_insert_dtable", "ed_insert_atable","ed_new_row_after", "ed_new_row_before", + "ed_new_col_after", "ed_new_col_before", "ed_delete_col", + "ed_delete_row", "ed_edit_data", "ed_row_up", "ed_row_down", + "ed_col_left", "ed_col_right"); + } + + + /** + * Handle copied content. This function must, e.g. create copies of + * objects referenced within the content (e.g. question objects) + * + * @param DOMDocument $a_domdoc dom document + */ + public static function handleCopiedContent(DOMDocument $a_domdoc, $a_self_ass = true, $a_clone_mobs = false) + { + $xpath = new DOMXPath($a_domdoc); + $nodes = $xpath->query("//Table"); + foreach ($nodes as $node) { + $node->removeAttribute("Id"); + } + } } - -?> diff --git a/Services/COPage/classes/class.ilPCTableData.php b/Services/COPage/classes/class.ilPCTableData.php index d27cc37c4900e849fe58d34c88744cba22d2c168..c2e93b65cf1228b9e449059b5229d57a58e215ed 100755 --- a/Services/COPage/classes/class.ilPCTableData.php +++ b/Services/COPage/classes/class.ilPCTableData.php @@ -1,24 +1,24 @@ setType("td"); - } - - /** - * insert new row after cell - */ - function newRowAfter() - { - $this->initTablePCNode(); - $td = $this->getNode(); - $parent_tr = $td->parent_node(); - $new_tr = $parent_tr->clone_node(true); - - // remove pc ids - if ($new_tr->has_attribute("PCID")) - { - $new_tr->remove_attribute("PCID"); - } - if ($next_tr = $parent_tr->next_sibling()) - { - $new_tr = $next_tr->insert_before($new_tr, $next_tr); - } - else - { - $parent_table = $parent_tr->parent_node(); - $new_tr = $parent_table->append_child($new_tr); - } - - // remove td content of new row - $this->deleteRowContent($new_tr); - $this->fixHideAndSpans(); - } - - - /** - * insert new row after cell - */ - function newRowBefore() - { - $this->initTablePCNode(); - $td = $this->getNode(); - $parent_tr = $td->parent_node(); - $new_tr = $parent_tr->clone_node(true); - $new_tr = $parent_tr->insert_before($new_tr, $parent_tr); - if ($new_tr->has_attribute("PCID")) - { - $new_tr->remove_attribute("PCID"); - } - - // remove td content of new row - $this->deleteRowContent($new_tr); - $this->fixHideAndSpans(); - } - - - /** - * delete content of cells of a row (not the cells itself) - * - * @access private - */ - function deleteRowContent(&$a_row_node) - { - // remove td content of row - $tds = $a_row_node->child_nodes(); - for($i=0; $ihas_attribute("PCID")) - { - $tds[$i]->remove_attribute("PCID"); - } - $td_childs = $tds[$i]->child_nodes(); - for($j=0; $jremove_child($td_childs[$j]); - } - } - - } - - /** - * delete content of a cell (not the cell itself) - * - * @access private - */ - function deleteTDContent(&$a_td_node) - { - $td_childs = $a_td_node->child_nodes(); - for($j=0; $jremove_child($td_childs[$j]); - } - } - - - /** - * delete row of cell - */ - function deleteRow() - { - $this->initTablePCNode(); - $td = $this->getNode(); - $parent_tr = $td->parent_node(); - $parent_tr->unlink($parent_tr); - $this->fixHideAndSpans(); - } - - - /** - * insert new column after cell - */ - function newColAfter() - { - $this->initTablePCNode(); - $td = $this->getNode(); - - // determine current column nr - $hier_id = $this->getHierId(); - $parts = explode("_", $hier_id); - $col_nr = array_pop($parts); - $col_nr--; - - $parent_tr = $td->parent_node(); - $parent_table = $parent_tr->parent_node(); - - // iterate all table rows - $rows = $parent_table->child_nodes(); - for($i=0; $inode_name() == "TableRow") - { - // clone td at $col_nr - $tds = $rows[$i]->child_nodes(); - $new_td = $tds[$col_nr]->clone_node(true); - - if ($new_td->has_attribute("PCID")) - { - $new_td->remove_attribute("PCID"); - } - - // insert clone after $col_nr - if ($next_td = $tds[$col_nr]->next_sibling()) - { - $new_td = $next_td->insert_before($new_td, $next_td); - } - else - { - $new_td = $rows[$i]->append_child($new_td); - } - $this->deleteTDContent($new_td); - } - } - $this->fixHideAndSpans(); - } - - /** - * insert new column before cell - */ - function newColBefore() - { - $this->initTablePCNode(); - $td = $this->getNode(); - - // determine current column nr - $hier_id = $this->getHierId(); - $parts = explode("_", $hier_id); - $col_nr = array_pop($parts); - $col_nr--; - - $parent_tr = $td->parent_node(); - $parent_table = $parent_tr->parent_node(); - - // iterate all table rows - $rows = $parent_table->child_nodes(); - for($i=0; $inode_name() == "TableRow") - { - // clone td at $col_nr - $tds = $rows[$i]->child_nodes(); - $new_td = $tds[$col_nr]->clone_node(true); - - if ($new_td->has_attribute("PCID")) - { - $new_td->remove_attribute("PCID"); - } - - // insert clone before $col_nr - $new_td = $tds[$col_nr]->insert_before($new_td, $tds[$col_nr]); - $this->deleteTDContent($new_td); - } - } - $this->fixHideAndSpans(); - } - - /** - * delete column of cell - */ - function deleteCol() - { - $this->initTablePCNode(); - $td = $this->getNode(); - - // determine current column nr - $hier_id = $this->getHierId(); - $parts = explode("_", $hier_id); - $col_nr = array_pop($parts); - $col_nr--; - - $parent_tr = $td->parent_node(); - $parent_table = $parent_tr->parent_node(); - - // iterate all table rows - $rows = $parent_table->child_nodes(); - for($i=0; $inode_name() == "TableRow") - { - // unlink td at $col_nr - $tds = $rows[$i]->child_nodes(); - $tds[$col_nr]->unlink($tds[$col_nr]); - } - } - $this->fixHideAndSpans(); - } - - /** - * move row down - */ - function moveRowDown() - { - $this->initTablePCNode(); - $td = $this->getNode(); - $tr = $td->parent_node(); - $next = $tr->next_sibling(); - $next_copy = $next->clone_node(true); - $next_copy = $tr->insert_before($next_copy, $tr); - $next->unlink($next); - $this->fixHideAndSpans(); - } - - /** - * move row up - */ - function moveRowUp() - { - $this->initTablePCNode(); - $td = $this->getNode(); - $tr = $td->parent_node(); - $prev = $tr->previous_sibling(); - $tr_copy = $tr->clone_node(true); - $tr_copy = $prev->insert_before($tr_copy, $prev); - $tr->unlink($tr); - $this->fixHideAndSpans(); - } - - /** - * move column right - */ - function moveColRight() - { - $this->initTablePCNode(); - $td = $this->getNode(); - - // determine current column nr - $hier_id = $this->getHierId(); - $parts = explode("_", $hier_id); - $col_nr = array_pop($parts); - $col_nr--; - - $parent_tr = $td->parent_node(); - $parent_table = $parent_tr->parent_node(); - - // iterate all table rows - $rows = $parent_table->child_nodes(); - for($i=0; $inode_name() == "TableRow") - { - $tds = $rows[$i]->child_nodes(); - $td = $tds[$col_nr]; - //$td = $this->getNode(); - $next = $td->next_sibling(); - $next_copy = $next->clone_node(true); - $next_copy = $td->insert_before($next_copy, $td); - $next->unlink($next); - } - } - $this->fixHideAndSpans(); - } - - /** - * move column left - */ - function moveColLeft() - { - $this->initTablePCNode(); - $td = $this->getNode(); - - // determine current column nr - $hier_id = $this->getHierId(); - $parts = explode("_", $hier_id); - $col_nr = array_pop($parts); - $col_nr--; - - $parent_tr = $td->parent_node(); - $parent_table = $parent_tr->parent_node(); - - // iterate all table rows - $rows = $parent_table->child_nodes(); - for($i=0; $inode_name() == "TableRow") - { - $tds = $rows[$i]->child_nodes(); - $td = $tds[$col_nr]; - $prev = $td->previous_sibling(); - $td_copy = $td->clone_node(true); - $td_copy = $prev->insert_before($td_copy, $prev); - $td->unlink($td); - } - } - $this->fixHideAndSpans(); - } - - /** - * Table PC Node - */ - function initTablePCNode() - { - $td = $this->getNode(); - $tr = $td->parent_node(); - $table = $tr->parent_node(); - $this->table_pc_node = $table->parent_node(); - } - - /** - * Fix hide attribute and spans - */ - function fixHideAndSpans() - { - include_once("./Services/COPage/classes/class.ilPCTable.php"); - $table_obj = new ilPCTable($this->getPage()); - $table_obj->setNode($this->table_pc_node); - $table_obj->readHierId(); - $table_obj->readPCId(); - $table_obj->fixHideAndSpans(); - } + public $dom; + + /** + * Init page content component. + */ + public function init() + { + $this->setType("td"); + } + + /** + * insert new row after cell + */ + public function newRowAfter() + { + $this->initTablePCNode(); + $td = $this->getNode(); + $parent_tr = $td->parent_node(); + $new_tr = $parent_tr->clone_node(true); + + // remove pc ids + if ($new_tr->has_attribute("PCID")) { + $new_tr->remove_attribute("PCID"); + } + if ($next_tr = $parent_tr->next_sibling()) { + $new_tr = $next_tr->insert_before($new_tr, $next_tr); + } else { + $parent_table = $parent_tr->parent_node(); + $new_tr = $parent_table->append_child($new_tr); + } + + // remove td content of new row + $this->deleteRowContent($new_tr); + $this->fixHideAndSpans(); + } + + + /** + * insert new row after cell + */ + public function newRowBefore() + { + $this->initTablePCNode(); + $td = $this->getNode(); + $parent_tr = $td->parent_node(); + $new_tr = $parent_tr->clone_node(true); + $new_tr = $parent_tr->insert_before($new_tr, $parent_tr); + if ($new_tr->has_attribute("PCID")) { + $new_tr->remove_attribute("PCID"); + } + + // remove td content of new row + $this->deleteRowContent($new_tr); + $this->fixHideAndSpans(); + } + + + /** + * delete content of cells of a row (not the cells itself) + * + * @access private + */ + public function deleteRowContent(&$a_row_node) + { + // remove td content of row + $tds = $a_row_node->child_nodes(); + for ($i=0; $ihas_attribute("PCID")) { + $tds[$i]->remove_attribute("PCID"); + } + $td_childs = $tds[$i]->child_nodes(); + for ($j=0; $jremove_child($td_childs[$j]); + } + } + } + + /** + * delete content of a cell (not the cell itself) + * + * @access private + */ + public function deleteTDContent(&$a_td_node) + { + $td_childs = $a_td_node->child_nodes(); + for ($j=0; $jremove_child($td_childs[$j]); + } + } + + + /** + * delete row of cell + */ + public function deleteRow() + { + $this->initTablePCNode(); + $td = $this->getNode(); + $parent_tr = $td->parent_node(); + $parent_tr->unlink($parent_tr); + $this->fixHideAndSpans(); + } + + + /** + * insert new column after cell + */ + public function newColAfter() + { + $this->initTablePCNode(); + $td = $this->getNode(); + + // determine current column nr + $hier_id = $this->getHierId(); + $parts = explode("_", $hier_id); + $col_nr = array_pop($parts); + $col_nr--; + + $parent_tr = $td->parent_node(); + $parent_table = $parent_tr->parent_node(); + + // iterate all table rows + $rows = $parent_table->child_nodes(); + for ($i=0; $inode_name() == "TableRow") { + // clone td at $col_nr + $tds = $rows[$i]->child_nodes(); + $new_td = $tds[$col_nr]->clone_node(true); + + if ($new_td->has_attribute("PCID")) { + $new_td->remove_attribute("PCID"); + } + + // insert clone after $col_nr + if ($next_td = $tds[$col_nr]->next_sibling()) { + $new_td = $next_td->insert_before($new_td, $next_td); + } else { + $new_td = $rows[$i]->append_child($new_td); + } + $this->deleteTDContent($new_td); + } + } + $this->fixHideAndSpans(); + } + + /** + * insert new column before cell + */ + public function newColBefore() + { + $this->initTablePCNode(); + $td = $this->getNode(); + + // determine current column nr + $hier_id = $this->getHierId(); + $parts = explode("_", $hier_id); + $col_nr = array_pop($parts); + $col_nr--; + + $parent_tr = $td->parent_node(); + $parent_table = $parent_tr->parent_node(); + + // iterate all table rows + $rows = $parent_table->child_nodes(); + for ($i=0; $inode_name() == "TableRow") { + // clone td at $col_nr + $tds = $rows[$i]->child_nodes(); + $new_td = $tds[$col_nr]->clone_node(true); + + if ($new_td->has_attribute("PCID")) { + $new_td->remove_attribute("PCID"); + } + + // insert clone before $col_nr + $new_td = $tds[$col_nr]->insert_before($new_td, $tds[$col_nr]); + $this->deleteTDContent($new_td); + } + } + $this->fixHideAndSpans(); + } + + /** + * delete column of cell + */ + public function deleteCol() + { + $this->initTablePCNode(); + $td = $this->getNode(); + + // determine current column nr + $hier_id = $this->getHierId(); + $parts = explode("_", $hier_id); + $col_nr = array_pop($parts); + $col_nr--; + + $parent_tr = $td->parent_node(); + $parent_table = $parent_tr->parent_node(); + + // iterate all table rows + $rows = $parent_table->child_nodes(); + for ($i=0; $inode_name() == "TableRow") { + // unlink td at $col_nr + $tds = $rows[$i]->child_nodes(); + $tds[$col_nr]->unlink($tds[$col_nr]); + } + } + $this->fixHideAndSpans(); + } + + /** + * move row down + */ + public function moveRowDown() + { + $this->initTablePCNode(); + $td = $this->getNode(); + $tr = $td->parent_node(); + $next = $tr->next_sibling(); + $next_copy = $next->clone_node(true); + $next_copy = $tr->insert_before($next_copy, $tr); + $next->unlink($next); + $this->fixHideAndSpans(); + } + + /** + * move row up + */ + public function moveRowUp() + { + $this->initTablePCNode(); + $td = $this->getNode(); + $tr = $td->parent_node(); + $prev = $tr->previous_sibling(); + $tr_copy = $tr->clone_node(true); + $tr_copy = $prev->insert_before($tr_copy, $prev); + $tr->unlink($tr); + $this->fixHideAndSpans(); + } + + /** + * move column right + */ + public function moveColRight() + { + $this->initTablePCNode(); + $td = $this->getNode(); + + // determine current column nr + $hier_id = $this->getHierId(); + $parts = explode("_", $hier_id); + $col_nr = array_pop($parts); + $col_nr--; + + $parent_tr = $td->parent_node(); + $parent_table = $parent_tr->parent_node(); + + // iterate all table rows + $rows = $parent_table->child_nodes(); + for ($i=0; $inode_name() == "TableRow") { + $tds = $rows[$i]->child_nodes(); + $td = $tds[$col_nr]; + //$td = $this->getNode(); + $next = $td->next_sibling(); + $next_copy = $next->clone_node(true); + $next_copy = $td->insert_before($next_copy, $td); + $next->unlink($next); + } + } + $this->fixHideAndSpans(); + } + + /** + * move column left + */ + public function moveColLeft() + { + $this->initTablePCNode(); + $td = $this->getNode(); + + // determine current column nr + $hier_id = $this->getHierId(); + $parts = explode("_", $hier_id); + $col_nr = array_pop($parts); + $col_nr--; + + $parent_tr = $td->parent_node(); + $parent_table = $parent_tr->parent_node(); + + // iterate all table rows + $rows = $parent_table->child_nodes(); + for ($i=0; $inode_name() == "TableRow") { + $tds = $rows[$i]->child_nodes(); + $td = $tds[$col_nr]; + $prev = $td->previous_sibling(); + $td_copy = $td->clone_node(true); + $td_copy = $prev->insert_before($td_copy, $prev); + $td->unlink($td); + } + } + $this->fixHideAndSpans(); + } + + /** + * Table PC Node + */ + public function initTablePCNode() + { + $td = $this->getNode(); + $tr = $td->parent_node(); + $table = $tr->parent_node(); + $this->table_pc_node = $table->parent_node(); + } + + /** + * Fix hide attribute and spans + */ + public function fixHideAndSpans() + { + include_once("./Services/COPage/classes/class.ilPCTable.php"); + $table_obj = new ilPCTable($this->getPage()); + $table_obj->setNode($this->table_pc_node); + $table_obj->readHierId(); + $table_obj->readPCId(); + $table_obj->fixHideAndSpans(); + } } -?> diff --git a/Services/COPage/classes/class.ilPCTableDataGUI.php b/Services/COPage/classes/class.ilPCTableDataGUI.php index 653e81b8e8649fab5d9d61261fd42656e281afd2..5878ce146c42239c7af1d786d3fb085f6f0a412f 100755 --- a/Services/COPage/classes/class.ilPCTableDataGUI.php +++ b/Services/COPage/classes/class.ilPCTableDataGUI.php @@ -18,137 +18,134 @@ require_once("./Services/COPage/classes/class.ilPageContentGUI.php"); class ilPCTableDataGUI extends ilPageContentGUI { - /** - * Constructor - * @access public - */ - function __construct(&$a_pg_obj, &$a_content_obj, $a_hier_id, $a_pc_id = "") - { - 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 row after cell - */ - function newRowAfter() - { - $this->content_obj->newRowAfter(); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * insert new row before cell - */ - function newRowBefore() - { - $this->content_obj->newRowBefore(); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * delete a row - */ - function deleteRow() - { - $this->content_obj->deleteRow(); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - - /** - * insert new col after cell - */ - function newColAfter() - { - $this->content_obj->newColAfter(); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * insert new col before cell - */ - function newColBefore() - { - $this->content_obj->newColBefore(); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * delete column - */ - function deleteCol() - { - $this->content_obj->deleteCol(); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * move row down - */ - function moveRowDown() - { - $this->content_obj->moveRowDown(); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * move list item up - */ - function moveRowUp() - { - $this->content_obj->moveRowUp(); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * move column right - */ - function moveColRight() - { - $this->content_obj->moveColRight(); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * move list item up - */ - function moveColLeft() - { - $this->content_obj->moveColLeft(); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - + /** + * Constructor + * @access public + */ + public function __construct(&$a_pg_obj, &$a_content_obj, $a_hier_id, $a_pc_id = "") + { + 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 row after cell + */ + public function newRowAfter() + { + $this->content_obj->newRowAfter(); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * insert new row before cell + */ + public function newRowBefore() + { + $this->content_obj->newRowBefore(); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * delete a row + */ + public function deleteRow() + { + $this->content_obj->deleteRow(); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + + /** + * insert new col after cell + */ + public function newColAfter() + { + $this->content_obj->newColAfter(); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * insert new col before cell + */ + public function newColBefore() + { + $this->content_obj->newColBefore(); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * delete column + */ + public function deleteCol() + { + $this->content_obj->deleteCol(); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * move row down + */ + public function moveRowDown() + { + $this->content_obj->moveRowDown(); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * move list item up + */ + public function moveRowUp() + { + $this->content_obj->moveRowUp(); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * move column right + */ + public function moveColRight() + { + $this->content_obj->moveColRight(); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * move list item up + */ + public function moveColLeft() + { + $this->content_obj->moveColLeft(); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } } -?> diff --git a/Services/COPage/classes/class.ilPCTableGUI.php b/Services/COPage/classes/class.ilPCTableGUI.php index 7762467115ce2a838a97a27b5cc56e460ae31dc7..0f5aa465682d08c3f041fc438189550cea636e24 100755 --- a/Services/COPage/classes/class.ilPCTableGUI.php +++ b/Services/COPage/classes/class.ilPCTableGUI.php @@ -16,1048 +16,1016 @@ require_once("./Services/COPage/classes/class.ilPageContentGUI.php"); */ class ilPCTableGUI extends ilPageContentGUI { - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilObjUser - */ - protected $user; - - - /** - * Constructor - * @access public - */ - function __construct(&$a_pg_obj, &$a_content_obj, $a_hier_id, $a_pc_id = "") - { - global $DIC; - - $this->tabs = $DIC->tabs(); - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - $this->user = $DIC->user(); - parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); - $this->setCharacteristics(array("StandardTable" => $this->lng->txt("cont_StandardTable"))); - - } - - /** - * Set basic table cell styles - */ - function setBasicTableCellStyles() - { - $this->setCharacteristics(array("Cell1" => "Cell1", "Cell2" => "Cell2", - "Cell3" => "Cell3", "Cell4" => "Cell4")); - } - - /** - * execute command - */ - function executeCommand() - { - $this->getCharacteristicsOfCurrentStyle("table"); // scorm-2004 - - // 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; - } - - - /** - * Set tabs - */ - function setTabs() - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $ilTabs->setBackTarget($lng->txt("pg"), - $this->ctrl->getParentReturn($this)); - - $ilTabs->addTarget("cont_table_properties", - $ilCtrl->getLinkTarget($this, "edit"), "edit", - get_class($this)); - - $ilTabs->addTarget("cont_table_cell_properties", - $ilCtrl->getLinkTarget($this, "editCellStyle"), "editCellStyle", - get_class($this)); - - } - - /** - * Set tabs - */ - function setCellPropertiesSubTabs() - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $ilTabs->addSubTabTarget("cont_style", - $ilCtrl->getLinkTarget($this, "editCellStyle"), "editCellStyle", - get_class($this)); - - $ilTabs->addSubTabTarget("cont_width", - $ilCtrl->getLinkTarget($this, "editCellWidth"), "editCellWidth", - get_class($this)); - - $ilTabs->addSubTabTarget("cont_alignment", - $ilCtrl->getLinkTarget($this, "editCellAlignment"), "editCellAlignment", - get_class($this)); - - $ilTabs->addSubTabTarget("cont_span", - $ilCtrl->getLinkTarget($this, "editCellSpan"), "editCellSpan", - get_class($this)); - - } - - /** - * Get table templates - */ - function getTemplateOptions($a_type = "") - { - return parent::getTemplateOptions("table"); - } - - /** - * edit properties form - */ - function edit() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - - $this->displayValidationError(); - $this->setTabs(); - - $this->initPropertiesForm(); - $this->getPropertiesFormValues(); - $html = $this->form->getHTML(); - $html.= "
          ".$this->renderTable(""); - $tpl->setContent($html); - } - - /** - * Init properties form - */ - function initPropertiesForm($a_mode = "edit") - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - $ilUser = $this->user; - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - $this->form->setFormAction($ilCtrl->getFormAction($this)); - if ($a_mode == "create") - { - $this->form->setTitle($this->lng->txt("cont_insert_table")); - } - else - { - $this->form->setTitle($this->lng->txt("cont_table_properties")); - } - - if ($a_mode == "create") - { - $nr = array(); - for($i=1; $i<=20; $i++) - { - $nr[$i] = $i; - } - - // cols - $cols = new ilSelectInputGUI($this->lng->txt("cont_nr_cols"), "nr_cols"); - $cols->setOptions($nr); - $cols->setValue(2); - $this->form->addItem($cols); - - // rows - $rows = new ilSelectInputGUI($this->lng->txt("cont_nr_rows"), "nr_rows"); - $rows->setOptions($nr); - $rows->setValue(2); - $this->form->addItem($rows); - } - - // width - $width = new ilTextInputGUI($this->lng->txt("cont_table_width"), "width"); - $width->setSize(6); - $width->setMaxLength(6); - $this->form->addItem($width); - - // border - $border = new ilTextInputGUI($this->lng->txt("cont_table_border"), "border"); - $border->setInfo($this->lng->txt("cont_table_border_info")); - $border->setValue("1px"); - $border->setSize(6); - $border->setMaxLength(6); - $this->form->addItem($border); - - // padding - $padding = new ilTextInputGUI($this->lng->txt("cont_table_cellpadding"), "padding"); - $padding->setInfo($this->lng->txt("cont_table_cellpadding_info")); - $padding->setValue("2px"); - $padding->setSize(6); - $padding->setMaxLength(6); - $this->form->addItem($padding); - - // spacing (deprecated, only hidden) - $spacing = new ilHiddenInputGUI("spacing"); - $spacing->setValue("0px"); - $this->form->addItem($spacing); - /*$spacing = new ilTextInputGUI($this->lng->txt("cont_table_cellspacing"), "spacing"); - $spacing->setValue("0px"); - $spacing->setSize(6); - $spacing->setMaxLength(6); - $this->form->addItem($spacing);*/ - - // table templates and table classes - require_once("./Services/Form/classes/class.ilAdvSelectInputGUI.php"); - $char_prop = new ilAdvSelectInputGUI($this->lng->txt("cont_characteristic"), - "characteristic"); - $chars = $this->getCharacteristics(); - $templates = $this->getTemplateOptions(); - $chars = array_merge($templates, $chars); - if (is_object($this->content_obj)) - { - if ($chars[$a_seleted_value] == "" && ($this->content_obj->getClass() != "")) - { - $chars = array_merge( - array($this->content_obj->getClass() => $this->content_obj->getClass()), - $chars); - } - } - foreach($chars as $k => $char) - { - if (strpos($k, ":") > 0) - { - $t = explode(":", $k); - $html = $this->style->lookupTemplatePreview($t[1]).'
          '.$char."
          "; - } - else - { - $html = '
          '. - $char.'
          '; - } - $char_prop->addOption($k, $char, $html); - } - $char_prop->setValue("StandardTable"); - $this->form->addItem($char_prop); - - $nr = array(); - for($i=0; $i<=3; $i++) - { - $nr[$i] = $i; - } - - // row header - $rh = new ilSelectInputGUI($this->lng->txt("cont_nr_row_header"), "row_header"); - $rh->setOptions($nr); - $rh->setValue(1); - $this->form->addItem($rh); - - // row footer - $rf = new ilSelectInputGUI($this->lng->txt("cont_nr_row_footer"), "row_footer"); - $rf->setOptions($nr); - $rf->setValue(0); - $this->form->addItem($rf); - - // col header - $ch = new ilSelectInputGUI($this->lng->txt("cont_nr_col_header"), "col_header"); - $ch->setOptions($nr); - $ch->setValue(0); - $this->form->addItem($ch); - - // col footer - $cf = new ilSelectInputGUI($this->lng->txt("cont_nr_col_footer"), "col_footer"); - $cf->setOptions($nr); - $cf->setValue(0); - $this->form->addItem($cf); - - if ($a_mode == "create") - { - // first row style - require_once("./Services/Form/classes/class.ilAdvSelectInputGUI.php"); - $fr_style = new ilAdvSelectInputGUI($this->lng->txt("cont_first_row_style"), - "first_row_style"); - $this->setBasicTableCellStyles(); - $this->getCharacteristicsOfCurrentStyle("table_cell"); - $chars = $this->getCharacteristics(); - $options = array_merge(array("" => $this->lng->txt("none")), $chars); - foreach($options as $k => $option) - { - $html = '
          '. - $option.'
          '; - $fr_style->addOption($k, $option, $html); - } - - $fr_style->setValue(""); - $this->form->addItem($fr_style); - } - - // alignment - $align_opts = array("Left" => $lng->txt("cont_left"), - "Right" => $lng->txt("cont_right"), "Center" => $lng->txt("cont_center"), - "LeftFloat" => $lng->txt("cont_left_float"), - "RightFloat" => $lng->txt("cont_right_float")); - $align = new ilSelectInputGUI($this->lng->txt("cont_align"), "align"); - $align->setOptions($align_opts); - $align->setValue("Center"); - $this->form->addItem($align); - - // caption - $caption = new ilTextInputGUI($this->lng->txt("cont_caption"), "caption"); - $caption->setSize(60); - $this->form->addItem($caption); - - // caption align - $ca_opts = array("top" => $lng->txt("cont_top"), - "bottom" => $lng->txt("cont_bottom")); - $ca = new ilSelectInputGUI($this->lng->txt("cont_align"), - "cap_align"); - $ca->setOptions($ca_opts); - $caption->addSubItem($ca); - - // import - if ($a_mode == "create") - { - // import table - $import = new ilRadioGroupInputGUI($this->lng->txt("cont_paste_table"), "import_type"); - $op = new ilRadioOption($this->lng->txt("cont_html_table"), "html"); - $import->addOption($op); - $op2 = new ilRadioOption($this->lng->txt("cont_spreadsheet_table"), "spreadsheet"); - - $import_data = new ilTextAreaInputGUI("", "import_table"); - $import_data->setRows(8); - $import_data->setCols(50); - $op2->addSubItem($import_data); - - $import->addOption($op2); - $import->setValue("html"); - $this->form->addItem($import); - } - - // language - if ($_SESSION["il_text_lang_".$_GET["ref_id"]] != "") - { - $s_lang = $_SESSION["il_text_lang_".$_GET["ref_id"]]; - } - else - { - $s_lang = $ilUser->getLanguage(); - } - require_once("Services/MetaData/classes/class.ilMDLanguageItem.php"); - $lang = ilMDLanguageItem::_getLanguages(); - $language = new ilSelectInputGUI($this->lng->txt("language"), "language"); - $language->setOptions($lang); - $language->setValue($s_lang); - $this->form->addItem($language); - - if ($a_mode == "create") - { - $this->form->addCommandButton("create_tab", $lng->txt("save")); - $this->form->addCommandButton("cancelCreate", $lng->txt("cancel")); - } - else - { - $this->form->addCommandButton("saveProperties", $lng->txt("save")); - } - } - - /** - * Get properties form - */ - function getPropertiesFormValues() - { - $values = array(); - $values["width"] = $this->content_obj->getWidth(); - $values["border"] = $this->content_obj->getBorder(); - $values["padding"] = $this->content_obj->getCellPadding(); - $values["spacing"] = $this->content_obj->getCellSpacing(); - $values["row_header"] = $this->content_obj->getHeaderRows(); - $values["row_footer"] = $this->content_obj->getFooterRows(); - $values["col_header"] = $this->content_obj->getHeaderCols(); - $values["col_footer"] = $this->content_obj->getFooterCols(); - if ($this->content_obj->getTemplate() != "") - { - $values["characteristic"] = "t:". - ilObjStyleSheet::_lookupTemplateIdByName($this->getStyleId(), $this->content_obj->getTemplate()).":". - $this->content_obj->getTemplate(); - } - else - { - $values["characteristic"] = $this->content_obj->getClass(); - } - $values["align"] = $this->content_obj->getHorizontalAlign(); - $values["caption"] = $this->content_obj->getCaption(); - $values["cap_align"] = $this->content_obj->getCaptionAlign(); - $values["language"] = $this->content_obj->getLanguage(); - - $this->form->setValuesByArray($values); - - $ca = $this->form->getItemByPostVar("cap_align"); - $ca->setValue($this->content_obj->getCaptionAlign()); - } - - /** - * Render the table - */ - function renderTable($a_mode = "table_edit", $a_submode = "") - { - $tab_node = $this->content_obj->getNode(); - $tab_node->set_attribute("Enabled", "True"); - $content = $this->dom->dump_node($tab_node); - - $trans = $this->pg_obj->getLanguageVariablesXML(); - $mobs = $this->pg_obj->getMultimediaXML(); - if ($this->getStyleId() > 0) - { - if (ilObject::_lookupType($this->getStyleId()) == "sty") - { - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $style = new ilObjStyleSheet($this->getStyleId()); - $template_xml = $style->getTemplateXML(); - } - } - - $content = $content.$mobs.$trans.$template_xml; - - return ilPCTableGUI::_renderTable($content, $a_mode, $a_submode, $this->content_obj); - } - - /** - * Static render table function - */ - static function _renderTable($content, $a_mode = "table_edit", $a_submode = "", $a_table_obj = null) - { - global $DIC; - - $ilUser = $DIC->user(); - - $content = "".$content.""; - - $xsl = file_get_contents("./Services/COPage/xsl/page.xsl"); - $args = array( '/_xml' => $content, '/_xsl' => $xsl ); - $xh = xslt_create(); -//echo "XML:".htmlentities($content).":
          "; -//echo "XSLT:".htmlentities($xsl).":
          "; - $wb_path = ilUtil::getWebspaceDir("output"); - $enlarge_path = ilUtil::getImagePath("enlarge.svg"); - $params = array ('mode' => $a_mode, - 'media_mode' => $ilUser->getPref("ilPageEditor_MediaMode"), - 'media_mode' => 'disable', - 'webspace_path' => $wb_path, 'enlarge_path' => $enlarge_path); - $output = xslt_process($xh,"arg:/_xml","arg:/_xsl",NULL,$args, $params); - echo xslt_error($xh); - xslt_free($xh); - - // unmask user html - $output = str_replace("<","<",$output); - $output = str_replace(">",">",$output); - $output = str_replace("&","&",$output); - - if ($a_mode == "table_edit" && !is_null($a_table_obj)) - { - switch ($a_submode) - { - case "style": - $output = ilPCTableGUI::_addStyleCheckboxes($output, $a_table_obj); - break; - - case "alignment": - $output = ilPCTableGUI::_addAlignmentCheckboxes($output, $a_table_obj); - break; - - case "width": - $output = ilPCTableGUI::_addWidthInputs($output, $a_table_obj); - break; - - case "span": - $output = ilPCTableGUI::_addSpanInputs($output, $a_table_obj); - break; - } - } - - - return '
          '.$output.'
          '; - } - - /** - * Add style checkboxes in edit mode - */ - static function _addStyleCheckboxes($a_output, $a_table) - { - global $DIC; - - $lng = $DIC->language(); - - $classes = $a_table->getAllCellClasses(); - - foreach ($classes as $k => $v) - { - if ($v == "") - { - $v = $lng->txt("none"); - } - if (substr($v, 0, 4) == "ilc_") - { - $v = substr($v, 4); - } - $check = $lng->txt("cont_style").": ". - ''.' '.$v; - - $a_output = str_replace("{{{{{TableEdit;".$k."}}}}}", $check, $a_output); - } - return $a_output; - } - - /** - * Add alignment checkboxes in edit mode - */ - static function _addAlignmentCheckboxes($a_output, $a_table) - { - global $DIC; - - $lng = $DIC->language(); - - $classes = $a_table->getAllCellAlignments(); - - foreach ($classes as $k => $v) - { - if ($v == "") - { - $v = $lng->txt("default"); - } - $check = $lng->txt("cont_alignment").": ". - ''.' '.$v; - - $a_output = str_replace("{{{{{TableEdit;".$k."}}}}}", $check, $a_output); - } - return $a_output; - } - - /** - * Add width inputs - */ - static function _addWidthInputs($a_output, $a_table) - { - global $DIC; - - $lng = $DIC->language(); - - $widths = $a_table->getAllCellWidths(); - - foreach ($widths as $k => $v) - { - $check = $lng->txt("cont_width").": ". - ''.''; - - $a_output = str_replace("{{{{{TableEdit;".$k."}}}}}", $check, $a_output); - } - return $a_output; - } - - /** - * Add span inputs - */ - static function _addSpanInputs($a_output, $a_table) - { - global $DIC; - - $lng = $DIC->language(); - - $spans = $a_table->getAllCellSpans(); - - foreach ($spans as $k => $v) - { - // colspans - $selects = '
          '.$lng->txt("cont_colspan").": ". - '
          "; - - // rowspans - $selects.= '
          '.$lng->txt("cont_rowspan").": ". - '
          "; - - $a_output = str_replace("{{{{{TableEdit;".$k."}}}}}", $selects, $a_output); - } - return $a_output; - } - - /** - * Edit cell styles - */ - function editCellStyle() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - $ilTabs = $this->tabs; - - $this->displayValidationError(); - $this->setTabs(); - $this->setCellPropertiesSubTabs(); - $ilTabs->setSubTabActive("cont_style"); - - // edit form - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this)); - $form->setTitle($this->lng->txt("cont_table_cell_properties")); - - // first row style - require_once("./Services/Form/classes/class.ilAdvSelectInputGUI.php"); - $style = new ilAdvSelectInputGUI($this->lng->txt("cont_style"), - "style"); - $this->setBasicTableCellStyles(); - $this->getCharacteristicsOfCurrentStyle("table_cell"); // scorm-2004 - $chars = $this->getCharacteristics(); // scorm-2004 - $options = array_merge(array("" => $this->lng->txt("none")), $chars); // scorm-2004 - foreach($options as $k => $option) - { - $html = '
          '. - $option.'
          '; - $style->addOption($k, $option, $html); - } - - $style->setValue(""); - $style->setInfo($lng->txt("cont_set_tab_style_info")); - $form->addItem($style); - $form->setKeepOpen(true); - - $form->addCommandButton("setStyles", $lng->txt("cont_set_styles")); - - $html = $form->getHTML(); - $html.= "
          ".$this->renderTable("table_edit", "style").""; - $tpl->setContent($html); - - } - - /** - * Edit cell widths - */ - function editCellWidth() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - $ilTabs = $this->tabs; - - $this->displayValidationError(); - $this->setTabs(); - $this->setCellPropertiesSubTabs(); - $ilTabs->setSubTabActive("cont_width"); - $ilTabs->setTabActive("cont_table_cell_properties"); - - $ctpl = new ilTemplate("tpl.table_cell_properties.html", true, true, "Services/COPage"); - $ctpl->setVariable("BTN_NAME", "setWidths"); - $ctpl->setVariable("BTN_TEXT", $lng->txt("cont_save_widths")); - $ctpl->setVariable("FORMACTION", $ilCtrl->getFormAction($this)); - - $html = $ctpl->get(); - $html.= "
          ".$this->renderTable("table_edit", "width").""; - $tpl->setContent($html); - - } - - /** - * Edit cell spans - */ - function editCellSpan() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - $ilTabs = $this->tabs; - - $this->displayValidationError(); - $this->setTabs(); - $this->setCellPropertiesSubTabs(); - $ilTabs->setSubTabActive("cont_span"); - $ilTabs->setTabActive("cont_table_cell_properties"); - - $ctpl = new ilTemplate("tpl.table_cell_properties.html", true, true, "Services/COPage"); - $ctpl->setVariable("BTN_NAME", "setSpans"); - $ctpl->setVariable("BTN_TEXT", $lng->txt("cont_save_spans")); - $ctpl->setVariable("FORMACTION", $ilCtrl->getFormAction($this)); - - $html = $ctpl->get(); - $html.= "
          ".$this->renderTable("table_edit", "span").""; - $tpl->setContent($html); - - } - - /** - * Set cell styles and - */ - function setStyles() - { - $lng = $this->lng; - - if (is_array($_POST["target"])) - { - foreach ($_POST["target"] as $k => $value) - { - if ($value > 0) - { - $cid = explode(":", $k); - $this->content_obj->setTDClass(ilUtil::stripSlashes($cid[0]), - ilUtil::stripSlashes($_POST["style"]), ilUtil::stripSlashes($cid[1])); - } - } - } - $this->updated = $this->pg_obj->update(); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "editCellStyle"); - } - - /** - * Set cell widths - */ - function setWidths() - { - $lng = $this->lng; - - if (is_array($_POST["width"])) - { - foreach ($_POST["width"] as $k => $width) - { - $cid = explode(":", $k); - $this->content_obj->setTDWidth(ilUtil::stripSlashes($cid[0]), - ilUtil::stripSlashes($width), ilUtil::stripSlashes($cid[1])); - } - } - $this->updated = $this->pg_obj->update(); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "editCellWidth"); - } - - /** - * Set cell spans - */ - function setSpans() - { - $lng = $this->lng; - - if (is_array($_POST["colspan"])) - { - foreach ($_POST["colspan"] as $k => $span) - { - $_POST["colspan"][$k] = ilUtil::stripSlashes($span); - $_POST["rowspan"][$k] = ilUtil::stripSlashes($_POST["rowspan"][$k]); - } - $this->content_obj->setTDSpans($_POST["colspan"], $_POST["rowspan"]); - } - $this->updated = $this->pg_obj->update(); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "editCellSpan"); - } - - /** - * Set properties from input form - */ - function setProperties() - { - // mask html - $caption = ilUtil::stripSlashes($_POST["caption"]); - $caption = str_replace("&","&", $caption); - $caption = str_replace("<","<", $caption); - $caption = str_replace(">",">", $caption); - - $this->content_obj->setLanguage(ilUtil::stripSlashes($_POST["language"])); - $this->content_obj->setWidth(ilUtil::stripSlashes($_POST["width"])); - $this->content_obj->setBorder(ilUtil::stripSlashes($_POST["border"])); - $this->content_obj->setCellSpacing(ilUtil::stripSlashes($_POST["spacing"])); - $this->content_obj->setCellPadding(ilUtil::stripSlashes($_POST["padding"])); - $this->content_obj->setHorizontalAlign(ilUtil::stripSlashes($_POST["align"])); - $this->content_obj->setHeaderRows(ilUtil::stripSlashes($_POST["row_header"])); - $this->content_obj->setHeaderCols(ilUtil::stripSlashes($_POST["col_header"])); - $this->content_obj->setFooterRows(ilUtil::stripSlashes($_POST["row_footer"])); - $this->content_obj->setFooterCols(ilUtil::stripSlashes($_POST["col_footer"])); - if (strpos($_POST["characteristic"], ":") > 0) - { - $t = explode(":", $_POST["characteristic"]); - $this->content_obj->setTemplate(ilUtil::stripSlashes($t[2])); - $this->content_obj->setClass(""); - } - else - { - $this->content_obj->setClass(ilUtil::stripSlashes($_POST["characteristic"])); - $this->content_obj->setTemplate(""); - } - $this->content_obj->setCaption($caption, - ilUtil::stripSlashes($_POST["cap_align"])); - } - - /** - * save table properties in db and return to page edit screen - */ - function saveProperties() - { - $this->setProperties(); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->redirect($this, "edit"); - //$this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - else - { - $this->pg_obj->addHierIDs(); - $this->edit(); - } - } - - /** - * align table to right - */ - function rightAlign() - { - $this->content_obj->setHorizontalAlign("Right"); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * align table to left - */ - function leftAlign() - { - $this->content_obj->setHorizontalAlign("Left"); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * align table to left - */ - function centerAlign() - { - $this->content_obj->setHorizontalAlign("Center"); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * align table to left float - */ - function leftFloatAlign() - { - $this->content_obj->setHorizontalAlign("LeftFloat"); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * align table to left - */ - function rightFloatAlign() - { - $this->content_obj->setHorizontalAlign("RightFloat"); - $_SESSION["il_pg_error"] = $this->pg_obj->update(); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * insert new table form - */ - function insert() - { - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - $this->displayValidationError(); - - $this->initPropertiesForm("create"); - $html = $this->form->getHTML(); - $tpl->setContent($html); - } - - /** - * Get new table object - */ - function getNewTableObject() - { - return new ilPCTable($this->getPage()); - } - - /** - * create new table in dom and update page in db - */ - function create() - { - global $lng; - - $this->content_obj = $this->getNewTableObject(); - $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); - $import_table = trim($_POST["import_table"]); - - // import xhtml or spreadsheet table - if (!empty ($import_table)) - { - switch($_POST["import_type"]) - { - // xhtml import - case "html": - if (!$this->content_obj->importHtml ($_POST["language"], $import_table)) - { - $this->insert(); - return; - } - break; - - // spreadsheet - case "spreadsheet": - $this->content_obj->importSpreadsheet($_POST["language"], $import_table); - break; - } - } - else - { - $this->content_obj->addRows(ilUtil::stripSlashes($_POST["nr_rows"]), - ilUtil::stripSlashes($_POST["nr_cols"])); - } - - $this->setProperties(); - - $frtype = ilUtil::stripSlashes($_POST["first_row_style"]); - if ($frtype != "") - { - $this->content_obj->setFirstRowStyle($frtype); - } - - $this->updated = $this->pg_obj->update(); - - if ($this->updated === true) - { - $this->afterCreation(); - } - else - { - $this->insert(); - } - } - - /** - * After creation processing - */ - function afterCreation() - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - - // - // Edit cell alignments - // - - /** - * Edit cell styles - */ - function editCellAlignment() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - $ilTabs = $this->tabs; - - $this->displayValidationError(); - $this->setTabs(); - $this->setCellPropertiesSubTabs(); - $ilTabs->setSubTabActive("cont_alignment"); - $ilTabs->setTabActive("cont_table_cell_properties"); - - // edit form - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this)); - $form->setTitle($this->lng->txt("cont_table_cell_properties")); - - // alignment - $options = array( - "" => $lng->txt("default"), - "Left" => $lng->txt("cont_left"), - "Center" => $lng->txt("cont_center"), - "Right" => $lng->txt("cont_right") - ); - $si = new ilSelectInputGUI($lng->txt("cont_alignment"), "alignment"); - $si->setOptions($options); - $si->setInfo($lng->txt("")); - $form->addItem($si); - - $form->setKeepOpen(true); - - $form->addCommandButton("setAlignment", $lng->txt("cont_set_alignment")); - - $html = $form->getHTML(); - $html.= "
          ".$this->renderTable("table_edit", "alignment").""; - $tpl->setContent($html); - - } - - /** - * Set cell alignments - */ - function setAlignment() - { - $lng = $this->lng; - - if (is_array($_POST["target"])) - { - foreach ($_POST["target"] as $k => $value) - { - if ($value > 0) - { - $cid = explode(":", $k); - $this->content_obj->setTDAlignment(ilUtil::stripSlashes($cid[0]), - ilUtil::stripSlashes($_POST["alignment"]), ilUtil::stripSlashes($cid[1])); - } - } - } - $this->updated = $this->pg_obj->update(); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - - $this->ctrl->redirect($this, "editCellAlignment"); - } - - + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilObjUser + */ + protected $user; + + + /** + * Constructor + * @access public + */ + public function __construct(&$a_pg_obj, &$a_content_obj, $a_hier_id, $a_pc_id = "") + { + global $DIC; + + $this->tabs = $DIC->tabs(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + $this->user = $DIC->user(); + parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); + $this->setCharacteristics(array("StandardTable" => $this->lng->txt("cont_StandardTable"))); + } + + /** + * Set basic table cell styles + */ + public function setBasicTableCellStyles() + { + $this->setCharacteristics(array("Cell1" => "Cell1", "Cell2" => "Cell2", + "Cell3" => "Cell3", "Cell4" => "Cell4")); + } + + /** + * execute command + */ + public function executeCommand() + { + $this->getCharacteristicsOfCurrentStyle("table"); // scorm-2004 + + // 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; + } + + + /** + * Set tabs + */ + public function setTabs() + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $ilTabs->setBackTarget( + $lng->txt("pg"), + $this->ctrl->getParentReturn($this) + ); + + $ilTabs->addTarget( + "cont_table_properties", + $ilCtrl->getLinkTarget($this, "edit"), + "edit", + get_class($this) + ); + + $ilTabs->addTarget( + "cont_table_cell_properties", + $ilCtrl->getLinkTarget($this, "editCellStyle"), + "editCellStyle", + get_class($this) + ); + } + + /** + * Set tabs + */ + public function setCellPropertiesSubTabs() + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $ilTabs->addSubTabTarget( + "cont_style", + $ilCtrl->getLinkTarget($this, "editCellStyle"), + "editCellStyle", + get_class($this) + ); + + $ilTabs->addSubTabTarget( + "cont_width", + $ilCtrl->getLinkTarget($this, "editCellWidth"), + "editCellWidth", + get_class($this) + ); + + $ilTabs->addSubTabTarget( + "cont_alignment", + $ilCtrl->getLinkTarget($this, "editCellAlignment"), + "editCellAlignment", + get_class($this) + ); + + $ilTabs->addSubTabTarget( + "cont_span", + $ilCtrl->getLinkTarget($this, "editCellSpan"), + "editCellSpan", + get_class($this) + ); + } + + /** + * Get table templates + */ + public function getTemplateOptions($a_type = "") + { + return parent::getTemplateOptions("table"); + } + + /** + * edit properties form + */ + public function edit() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + + $this->displayValidationError(); + $this->setTabs(); + + $this->initPropertiesForm(); + $this->getPropertiesFormValues(); + $html = $this->form->getHTML(); + $html.= "
          " . $this->renderTable(""); + $tpl->setContent($html); + } + + /** + * Init properties form + */ + public function initPropertiesForm($a_mode = "edit") + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + $ilUser = $this->user; + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + $this->form->setFormAction($ilCtrl->getFormAction($this)); + if ($a_mode == "create") { + $this->form->setTitle($this->lng->txt("cont_insert_table")); + } else { + $this->form->setTitle($this->lng->txt("cont_table_properties")); + } + + if ($a_mode == "create") { + $nr = array(); + for ($i=1; $i<=20; $i++) { + $nr[$i] = $i; + } + + // cols + $cols = new ilSelectInputGUI($this->lng->txt("cont_nr_cols"), "nr_cols"); + $cols->setOptions($nr); + $cols->setValue(2); + $this->form->addItem($cols); + + // rows + $rows = new ilSelectInputGUI($this->lng->txt("cont_nr_rows"), "nr_rows"); + $rows->setOptions($nr); + $rows->setValue(2); + $this->form->addItem($rows); + } + + // width + $width = new ilTextInputGUI($this->lng->txt("cont_table_width"), "width"); + $width->setSize(6); + $width->setMaxLength(6); + $this->form->addItem($width); + + // border + $border = new ilTextInputGUI($this->lng->txt("cont_table_border"), "border"); + $border->setInfo($this->lng->txt("cont_table_border_info")); + $border->setValue("1px"); + $border->setSize(6); + $border->setMaxLength(6); + $this->form->addItem($border); + + // padding + $padding = new ilTextInputGUI($this->lng->txt("cont_table_cellpadding"), "padding"); + $padding->setInfo($this->lng->txt("cont_table_cellpadding_info")); + $padding->setValue("2px"); + $padding->setSize(6); + $padding->setMaxLength(6); + $this->form->addItem($padding); + + // spacing (deprecated, only hidden) + $spacing = new ilHiddenInputGUI("spacing"); + $spacing->setValue("0px"); + $this->form->addItem($spacing); + /*$spacing = new ilTextInputGUI($this->lng->txt("cont_table_cellspacing"), "spacing"); + $spacing->setValue("0px"); + $spacing->setSize(6); + $spacing->setMaxLength(6); + $this->form->addItem($spacing);*/ + + // table templates and table classes + require_once("./Services/Form/classes/class.ilAdvSelectInputGUI.php"); + $char_prop = new ilAdvSelectInputGUI( + $this->lng->txt("cont_characteristic"), + "characteristic" + ); + $chars = $this->getCharacteristics(); + $templates = $this->getTemplateOptions(); + $chars = array_merge($templates, $chars); + if (is_object($this->content_obj)) { + if ($chars[$a_seleted_value] == "" && ($this->content_obj->getClass() != "")) { + $chars = array_merge( + array($this->content_obj->getClass() => $this->content_obj->getClass()), + $chars + ); + } + } + foreach ($chars as $k => $char) { + if (strpos($k, ":") > 0) { + $t = explode(":", $k); + $html = $this->style->lookupTemplatePreview($t[1]) . '
          ' . $char . "
          "; + } else { + $html = '
          ' . + $char . '
          '; + } + $char_prop->addOption($k, $char, $html); + } + $char_prop->setValue("StandardTable"); + $this->form->addItem($char_prop); + + $nr = array(); + for ($i=0; $i<=3; $i++) { + $nr[$i] = $i; + } + + // row header + $rh = new ilSelectInputGUI($this->lng->txt("cont_nr_row_header"), "row_header"); + $rh->setOptions($nr); + $rh->setValue(1); + $this->form->addItem($rh); + + // row footer + $rf = new ilSelectInputGUI($this->lng->txt("cont_nr_row_footer"), "row_footer"); + $rf->setOptions($nr); + $rf->setValue(0); + $this->form->addItem($rf); + + // col header + $ch = new ilSelectInputGUI($this->lng->txt("cont_nr_col_header"), "col_header"); + $ch->setOptions($nr); + $ch->setValue(0); + $this->form->addItem($ch); + + // col footer + $cf = new ilSelectInputGUI($this->lng->txt("cont_nr_col_footer"), "col_footer"); + $cf->setOptions($nr); + $cf->setValue(0); + $this->form->addItem($cf); + + if ($a_mode == "create") { + // first row style + require_once("./Services/Form/classes/class.ilAdvSelectInputGUI.php"); + $fr_style = new ilAdvSelectInputGUI( + $this->lng->txt("cont_first_row_style"), + "first_row_style" + ); + $this->setBasicTableCellStyles(); + $this->getCharacteristicsOfCurrentStyle("table_cell"); + $chars = $this->getCharacteristics(); + $options = array_merge(array("" => $this->lng->txt("none")), $chars); + foreach ($options as $k => $option) { + $html = '
          ' . + $option . '
          '; + $fr_style->addOption($k, $option, $html); + } + + $fr_style->setValue(""); + $this->form->addItem($fr_style); + } + + // alignment + $align_opts = array("Left" => $lng->txt("cont_left"), + "Right" => $lng->txt("cont_right"), "Center" => $lng->txt("cont_center"), + "LeftFloat" => $lng->txt("cont_left_float"), + "RightFloat" => $lng->txt("cont_right_float")); + $align = new ilSelectInputGUI($this->lng->txt("cont_align"), "align"); + $align->setOptions($align_opts); + $align->setValue("Center"); + $this->form->addItem($align); + + // caption + $caption = new ilTextInputGUI($this->lng->txt("cont_caption"), "caption"); + $caption->setSize(60); + $this->form->addItem($caption); + + // caption align + $ca_opts = array("top" => $lng->txt("cont_top"), + "bottom" => $lng->txt("cont_bottom")); + $ca = new ilSelectInputGUI( + $this->lng->txt("cont_align"), + "cap_align" + ); + $ca->setOptions($ca_opts); + $caption->addSubItem($ca); + + // import + if ($a_mode == "create") { + // import table + $import = new ilRadioGroupInputGUI($this->lng->txt("cont_paste_table"), "import_type"); + $op = new ilRadioOption($this->lng->txt("cont_html_table"), "html"); + $import->addOption($op); + $op2 = new ilRadioOption($this->lng->txt("cont_spreadsheet_table"), "spreadsheet"); + + $import_data = new ilTextAreaInputGUI("", "import_table"); + $import_data->setRows(8); + $import_data->setCols(50); + $op2->addSubItem($import_data); + + $import->addOption($op2); + $import->setValue("html"); + $this->form->addItem($import); + } + + // language + if ($_SESSION["il_text_lang_" . $_GET["ref_id"]] != "") { + $s_lang = $_SESSION["il_text_lang_" . $_GET["ref_id"]]; + } else { + $s_lang = $ilUser->getLanguage(); + } + require_once("Services/MetaData/classes/class.ilMDLanguageItem.php"); + $lang = ilMDLanguageItem::_getLanguages(); + $language = new ilSelectInputGUI($this->lng->txt("language"), "language"); + $language->setOptions($lang); + $language->setValue($s_lang); + $this->form->addItem($language); + + if ($a_mode == "create") { + $this->form->addCommandButton("create_tab", $lng->txt("save")); + $this->form->addCommandButton("cancelCreate", $lng->txt("cancel")); + } else { + $this->form->addCommandButton("saveProperties", $lng->txt("save")); + } + } + + /** + * Get properties form + */ + public function getPropertiesFormValues() + { + $values = array(); + $values["width"] = $this->content_obj->getWidth(); + $values["border"] = $this->content_obj->getBorder(); + $values["padding"] = $this->content_obj->getCellPadding(); + $values["spacing"] = $this->content_obj->getCellSpacing(); + $values["row_header"] = $this->content_obj->getHeaderRows(); + $values["row_footer"] = $this->content_obj->getFooterRows(); + $values["col_header"] = $this->content_obj->getHeaderCols(); + $values["col_footer"] = $this->content_obj->getFooterCols(); + if ($this->content_obj->getTemplate() != "") { + $values["characteristic"] = "t:" . + ilObjStyleSheet::_lookupTemplateIdByName($this->getStyleId(), $this->content_obj->getTemplate()) . ":" . + $this->content_obj->getTemplate(); + } else { + $values["characteristic"] = $this->content_obj->getClass(); + } + $values["align"] = $this->content_obj->getHorizontalAlign(); + $values["caption"] = $this->content_obj->getCaption(); + $values["cap_align"] = $this->content_obj->getCaptionAlign(); + $values["language"] = $this->content_obj->getLanguage(); + + $this->form->setValuesByArray($values); + + $ca = $this->form->getItemByPostVar("cap_align"); + $ca->setValue($this->content_obj->getCaptionAlign()); + } + + /** + * Render the table + */ + public function renderTable($a_mode = "table_edit", $a_submode = "") + { + $tab_node = $this->content_obj->getNode(); + $tab_node->set_attribute("Enabled", "True"); + $content = $this->dom->dump_node($tab_node); + + $trans = $this->pg_obj->getLanguageVariablesXML(); + $mobs = $this->pg_obj->getMultimediaXML(); + if ($this->getStyleId() > 0) { + if (ilObject::_lookupType($this->getStyleId()) == "sty") { + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $style = new ilObjStyleSheet($this->getStyleId()); + $template_xml = $style->getTemplateXML(); + } + } + + $content = $content . $mobs . $trans . $template_xml; + + return ilPCTableGUI::_renderTable($content, $a_mode, $a_submode, $this->content_obj); + } + + /** + * Static render table function + */ + public static function _renderTable($content, $a_mode = "table_edit", $a_submode = "", $a_table_obj = null) + { + global $DIC; + + $ilUser = $DIC->user(); + + $content = "" . $content . ""; + + $xsl = file_get_contents("./Services/COPage/xsl/page.xsl"); + $args = array( '/_xml' => $content, '/_xsl' => $xsl ); + $xh = xslt_create(); + //echo "XML:".htmlentities($content).":
          "; + //echo "XSLT:".htmlentities($xsl).":
          "; + $wb_path = ilUtil::getWebspaceDir("output"); + $enlarge_path = ilUtil::getImagePath("enlarge.svg"); + $params = array('mode' => $a_mode, + 'media_mode' => $ilUser->getPref("ilPageEditor_MediaMode"), + 'media_mode' => 'disable', + 'webspace_path' => $wb_path, 'enlarge_path' => $enlarge_path); + $output = xslt_process($xh, "arg:/_xml", "arg:/_xsl", null, $args, $params); + echo xslt_error($xh); + xslt_free($xh); + + // unmask user html + $output = str_replace("<", "<", $output); + $output = str_replace(">", ">", $output); + $output = str_replace("&", "&", $output); + + if ($a_mode == "table_edit" && !is_null($a_table_obj)) { + switch ($a_submode) { + case "style": + $output = ilPCTableGUI::_addStyleCheckboxes($output, $a_table_obj); + break; + + case "alignment": + $output = ilPCTableGUI::_addAlignmentCheckboxes($output, $a_table_obj); + break; + + case "width": + $output = ilPCTableGUI::_addWidthInputs($output, $a_table_obj); + break; + + case "span": + $output = ilPCTableGUI::_addSpanInputs($output, $a_table_obj); + break; + } + } + + + return '
          ' . $output . '
          '; + } + + /** + * Add style checkboxes in edit mode + */ + public static function _addStyleCheckboxes($a_output, $a_table) + { + global $DIC; + + $lng = $DIC->language(); + + $classes = $a_table->getAllCellClasses(); + + foreach ($classes as $k => $v) { + if ($v == "") { + $v = $lng->txt("none"); + } + if (substr($v, 0, 4) == "ilc_") { + $v = substr($v, 4); + } + $check = $lng->txt("cont_style") . ": " . + '' . ' ' . $v; + + $a_output = str_replace("{{{{{TableEdit;" . $k . "}}}}}", $check, $a_output); + } + return $a_output; + } + + /** + * Add alignment checkboxes in edit mode + */ + public static function _addAlignmentCheckboxes($a_output, $a_table) + { + global $DIC; + + $lng = $DIC->language(); + + $classes = $a_table->getAllCellAlignments(); + + foreach ($classes as $k => $v) { + if ($v == "") { + $v = $lng->txt("default"); + } + $check = $lng->txt("cont_alignment") . ": " . + '' . ' ' . $v; + + $a_output = str_replace("{{{{{TableEdit;" . $k . "}}}}}", $check, $a_output); + } + return $a_output; + } + + /** + * Add width inputs + */ + public static function _addWidthInputs($a_output, $a_table) + { + global $DIC; + + $lng = $DIC->language(); + + $widths = $a_table->getAllCellWidths(); + + foreach ($widths as $k => $v) { + $check = $lng->txt("cont_width") . ": " . + '' . ''; + + $a_output = str_replace("{{{{{TableEdit;" . $k . "}}}}}", $check, $a_output); + } + return $a_output; + } + + /** + * Add span inputs + */ + public static function _addSpanInputs($a_output, $a_table) + { + global $DIC; + + $lng = $DIC->language(); + + $spans = $a_table->getAllCellSpans(); + + foreach ($spans as $k => $v) { + // colspans + $selects = '
          ' . $lng->txt("cont_colspan") . ": " . + '
          "; + + // rowspans + $selects.= '
          ' . $lng->txt("cont_rowspan") . ": " . + '
          "; + + $a_output = str_replace("{{{{{TableEdit;" . $k . "}}}}}", $selects, $a_output); + } + return $a_output; + } + + /** + * Edit cell styles + */ + public function editCellStyle() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + $ilTabs = $this->tabs; + + $this->displayValidationError(); + $this->setTabs(); + $this->setCellPropertiesSubTabs(); + $ilTabs->setSubTabActive("cont_style"); + + // edit form + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this)); + $form->setTitle($this->lng->txt("cont_table_cell_properties")); + + // first row style + require_once("./Services/Form/classes/class.ilAdvSelectInputGUI.php"); + $style = new ilAdvSelectInputGUI( + $this->lng->txt("cont_style"), + "style" + ); + $this->setBasicTableCellStyles(); + $this->getCharacteristicsOfCurrentStyle("table_cell"); // scorm-2004 + $chars = $this->getCharacteristics(); // scorm-2004 + $options = array_merge(array("" => $this->lng->txt("none")), $chars); // scorm-2004 + foreach ($options as $k => $option) { + $html = '
          ' . + $option . '
          '; + $style->addOption($k, $option, $html); + } + + $style->setValue(""); + $style->setInfo($lng->txt("cont_set_tab_style_info")); + $form->addItem($style); + $form->setKeepOpen(true); + + $form->addCommandButton("setStyles", $lng->txt("cont_set_styles")); + + $html = $form->getHTML(); + $html.= "
          " . $this->renderTable("table_edit", "style") . ""; + $tpl->setContent($html); + } + + /** + * Edit cell widths + */ + public function editCellWidth() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + $ilTabs = $this->tabs; + + $this->displayValidationError(); + $this->setTabs(); + $this->setCellPropertiesSubTabs(); + $ilTabs->setSubTabActive("cont_width"); + $ilTabs->setTabActive("cont_table_cell_properties"); + + $ctpl = new ilTemplate("tpl.table_cell_properties.html", true, true, "Services/COPage"); + $ctpl->setVariable("BTN_NAME", "setWidths"); + $ctpl->setVariable("BTN_TEXT", $lng->txt("cont_save_widths")); + $ctpl->setVariable("FORMACTION", $ilCtrl->getFormAction($this)); + + $html = $ctpl->get(); + $html.= "
          " . $this->renderTable("table_edit", "width") . ""; + $tpl->setContent($html); + } + + /** + * Edit cell spans + */ + public function editCellSpan() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + $ilTabs = $this->tabs; + + $this->displayValidationError(); + $this->setTabs(); + $this->setCellPropertiesSubTabs(); + $ilTabs->setSubTabActive("cont_span"); + $ilTabs->setTabActive("cont_table_cell_properties"); + + $ctpl = new ilTemplate("tpl.table_cell_properties.html", true, true, "Services/COPage"); + $ctpl->setVariable("BTN_NAME", "setSpans"); + $ctpl->setVariable("BTN_TEXT", $lng->txt("cont_save_spans")); + $ctpl->setVariable("FORMACTION", $ilCtrl->getFormAction($this)); + + $html = $ctpl->get(); + $html.= "
          " . $this->renderTable("table_edit", "span") . ""; + $tpl->setContent($html); + } + + /** + * Set cell styles and + */ + public function setStyles() + { + $lng = $this->lng; + + if (is_array($_POST["target"])) { + foreach ($_POST["target"] as $k => $value) { + if ($value > 0) { + $cid = explode(":", $k); + $this->content_obj->setTDClass( + ilUtil::stripSlashes($cid[0]), + ilUtil::stripSlashes($_POST["style"]), + ilUtil::stripSlashes($cid[1]) + ); + } + } + } + $this->updated = $this->pg_obj->update(); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "editCellStyle"); + } + + /** + * Set cell widths + */ + public function setWidths() + { + $lng = $this->lng; + + if (is_array($_POST["width"])) { + foreach ($_POST["width"] as $k => $width) { + $cid = explode(":", $k); + $this->content_obj->setTDWidth( + ilUtil::stripSlashes($cid[0]), + ilUtil::stripSlashes($width), + ilUtil::stripSlashes($cid[1]) + ); + } + } + $this->updated = $this->pg_obj->update(); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "editCellWidth"); + } + + /** + * Set cell spans + */ + public function setSpans() + { + $lng = $this->lng; + + if (is_array($_POST["colspan"])) { + foreach ($_POST["colspan"] as $k => $span) { + $_POST["colspan"][$k] = ilUtil::stripSlashes($span); + $_POST["rowspan"][$k] = ilUtil::stripSlashes($_POST["rowspan"][$k]); + } + $this->content_obj->setTDSpans($_POST["colspan"], $_POST["rowspan"]); + } + $this->updated = $this->pg_obj->update(); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "editCellSpan"); + } + + /** + * Set properties from input form + */ + public function setProperties() + { + // mask html + $caption = ilUtil::stripSlashes($_POST["caption"]); + $caption = str_replace("&", "&", $caption); + $caption = str_replace("<", "<", $caption); + $caption = str_replace(">", ">", $caption); + + $this->content_obj->setLanguage(ilUtil::stripSlashes($_POST["language"])); + $this->content_obj->setWidth(ilUtil::stripSlashes($_POST["width"])); + $this->content_obj->setBorder(ilUtil::stripSlashes($_POST["border"])); + $this->content_obj->setCellSpacing(ilUtil::stripSlashes($_POST["spacing"])); + $this->content_obj->setCellPadding(ilUtil::stripSlashes($_POST["padding"])); + $this->content_obj->setHorizontalAlign(ilUtil::stripSlashes($_POST["align"])); + $this->content_obj->setHeaderRows(ilUtil::stripSlashes($_POST["row_header"])); + $this->content_obj->setHeaderCols(ilUtil::stripSlashes($_POST["col_header"])); + $this->content_obj->setFooterRows(ilUtil::stripSlashes($_POST["row_footer"])); + $this->content_obj->setFooterCols(ilUtil::stripSlashes($_POST["col_footer"])); + if (strpos($_POST["characteristic"], ":") > 0) { + $t = explode(":", $_POST["characteristic"]); + $this->content_obj->setTemplate(ilUtil::stripSlashes($t[2])); + $this->content_obj->setClass(""); + } else { + $this->content_obj->setClass(ilUtil::stripSlashes($_POST["characteristic"])); + $this->content_obj->setTemplate(""); + } + $this->content_obj->setCaption( + $caption, + ilUtil::stripSlashes($_POST["cap_align"]) + ); + } + + /** + * save table properties in db and return to page edit screen + */ + public function saveProperties() + { + $this->setProperties(); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->redirect($this, "edit"); + //$this->ctrl->returnToParent($this, "jump".$this->hier_id); + } else { + $this->pg_obj->addHierIDs(); + $this->edit(); + } + } + + /** + * align table to right + */ + public function rightAlign() + { + $this->content_obj->setHorizontalAlign("Right"); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * align table to left + */ + public function leftAlign() + { + $this->content_obj->setHorizontalAlign("Left"); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * align table to left + */ + public function centerAlign() + { + $this->content_obj->setHorizontalAlign("Center"); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * align table to left float + */ + public function leftFloatAlign() + { + $this->content_obj->setHorizontalAlign("LeftFloat"); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * align table to left + */ + public function rightFloatAlign() + { + $this->content_obj->setHorizontalAlign("RightFloat"); + $_SESSION["il_pg_error"] = $this->pg_obj->update(); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * insert new table form + */ + public function insert() + { + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + $this->displayValidationError(); + + $this->initPropertiesForm("create"); + $html = $this->form->getHTML(); + $tpl->setContent($html); + } + + /** + * Get new table object + */ + public function getNewTableObject() + { + return new ilPCTable($this->getPage()); + } + + /** + * create new table in dom and update page in db + */ + public function create() + { + global $lng; + + $this->content_obj = $this->getNewTableObject(); + $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); + $import_table = trim($_POST["import_table"]); + + // import xhtml or spreadsheet table + if (!empty($import_table)) { + switch ($_POST["import_type"]) { + // xhtml import + case "html": + if (!$this->content_obj->importHtml($_POST["language"], $import_table)) { + $this->insert(); + return; + } + break; + + // spreadsheet + case "spreadsheet": + $this->content_obj->importSpreadsheet($_POST["language"], $import_table); + break; + } + } else { + $this->content_obj->addRows( + ilUtil::stripSlashes($_POST["nr_rows"]), + ilUtil::stripSlashes($_POST["nr_cols"]) + ); + } + + $this->setProperties(); + + $frtype = ilUtil::stripSlashes($_POST["first_row_style"]); + if ($frtype != "") { + $this->content_obj->setFirstRowStyle($frtype); + } + + $this->updated = $this->pg_obj->update(); + + if ($this->updated === true) { + $this->afterCreation(); + } else { + $this->insert(); + } + } + + /** + * After creation processing + */ + public function afterCreation() + { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + + // + // Edit cell alignments + // + + /** + * Edit cell styles + */ + public function editCellAlignment() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + $ilTabs = $this->tabs; + + $this->displayValidationError(); + $this->setTabs(); + $this->setCellPropertiesSubTabs(); + $ilTabs->setSubTabActive("cont_alignment"); + $ilTabs->setTabActive("cont_table_cell_properties"); + + // edit form + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this)); + $form->setTitle($this->lng->txt("cont_table_cell_properties")); + + // alignment + $options = array( + "" => $lng->txt("default"), + "Left" => $lng->txt("cont_left"), + "Center" => $lng->txt("cont_center"), + "Right" => $lng->txt("cont_right") + ); + $si = new ilSelectInputGUI($lng->txt("cont_alignment"), "alignment"); + $si->setOptions($options); + $si->setInfo($lng->txt("")); + $form->addItem($si); + + $form->setKeepOpen(true); + + $form->addCommandButton("setAlignment", $lng->txt("cont_set_alignment")); + + $html = $form->getHTML(); + $html.= "
          " . $this->renderTable("table_edit", "alignment") . ""; + $tpl->setContent($html); + } + + /** + * Set cell alignments + */ + public function setAlignment() + { + $lng = $this->lng; + + if (is_array($_POST["target"])) { + foreach ($_POST["target"] as $k => $value) { + if ($value > 0) { + $cid = explode(":", $k); + $this->content_obj->setTDAlignment( + ilUtil::stripSlashes($cid[0]), + ilUtil::stripSlashes($_POST["alignment"]), + ilUtil::stripSlashes($cid[1]) + ); + } + } + } + $this->updated = $this->pg_obj->update(); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + + $this->ctrl->redirect($this, "editCellAlignment"); + } } -?> diff --git a/Services/COPage/classes/class.ilPCTabs.php b/Services/COPage/classes/class.ilPCTabs.php index 4bbf82bc343dd13592b308966b211c0c92b954cc..0bd2b24d999017823df2f54f033123d260326895 100755 --- a/Services/COPage/classes/class.ilPCTabs.php +++ b/Services/COPage/classes/class.ilPCTabs.php @@ -1,24 +1,24 @@ setType("tabs"); - } + /** + * Init page content component. + */ + public function init() + { + $this->setType("tabs"); + } - /** - * Set content node - */ - function setNode($a_node) - { - parent::setNode($a_node); // this is the PageContent node - $this->tabs_node = $a_node->first_child(); // this is the Tabs node - } + /** + * Set content node + */ + public function setNode($a_node) + { + parent::setNode($a_node); // this is the PageContent node + $this->tabs_node = $a_node->first_child(); // this is the Tabs node + } - /** - * Create new Tabs 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->tabs_node = $this->dom->create_element("Tabs"); - $this->tabs_node = $this->node->append_child($this->tabs_node); - } + /** + * Create new Tabs node + */ + public 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->tabs_node = $this->dom->create_element("Tabs"); + $this->tabs_node = $this->node->append_child($this->tabs_node); + } - /** - * Set attribute of tabs tag - * - * @param string attribute name - * @param string attribute value - */ - protected function setTabsAttribute($a_attr, $a_value) - { - if (!empty($a_value)) - { - $this->tabs_node->set_attribute($a_attr, $a_value); - } - else - { - if ($this->tabs_node->has_attribute($a_attr)) - { - $this->tabs_node->remove_attribute($a_attr); - } - } - } + /** + * Set attribute of tabs tag + * + * @param string attribute name + * @param string attribute value + */ + protected function setTabsAttribute($a_attr, $a_value) + { + if (!empty($a_value)) { + $this->tabs_node->set_attribute($a_attr, $a_value); + } else { + if ($this->tabs_node->has_attribute($a_attr)) { + $this->tabs_node->remove_attribute($a_attr); + } + } + } - /** - * Set type of tabs - * - * @param string $a_type ("HorizontalTabs" | "Accordion") - */ - function setTabType($a_type = "HorizontalTabs") - { - switch ($a_type) - { - case ilPCTabs::ACCORDION_VER: - case ilPCTabs::ACCORDION_HOR: - case ilPCTabs::CAROUSEL: - $this->tabs_node->set_attribute("Type", $a_type); - break; - } - } + /** + * Set type of tabs + * + * @param string $a_type ("HorizontalTabs" | "Accordion") + */ + public function setTabType($a_type = "HorizontalTabs") + { + switch ($a_type) { + case ilPCTabs::ACCORDION_VER: + case ilPCTabs::ACCORDION_HOR: + case ilPCTabs::CAROUSEL: + $this->tabs_node->set_attribute("Type", $a_type); + break; + } + } - /** - * Get type of tabs - */ - function getTabType() - { - return $this->tabs_node->get_attribute("Type"); - } - - /** - * Set content width - * - * @param int content width - */ - function setContentWidth($a_val) - { - $this->setTabsAttribute("ContentWidth", $a_val); - } - - /** - * Get content width - * - * @return int content width - */ - function getContentWidth() - { - return $this->tabs_node->get_attribute("ContentWidth"); - } - - /** - * Set content height - * - * @param int content height - */ - function setContentHeight($a_val) - { - $this->setTabsAttribute("ContentHeight", $a_val); - } - - /** - * Get content height - * - * @return int content height - */ - function getContentHeight() - { - return $this->tabs_node->get_attribute("ContentHeight"); - } + /** + * Get type of tabs + */ + public function getTabType() + { + return $this->tabs_node->get_attribute("Type"); + } + + /** + * Set content width + * + * @param int content width + */ + public function setContentWidth($a_val) + { + $this->setTabsAttribute("ContentWidth", $a_val); + } + + /** + * Get content width + * + * @return int content width + */ + public function getContentWidth() + { + return $this->tabs_node->get_attribute("ContentWidth"); + } + + /** + * Set content height + * + * @param int content height + */ + public function setContentHeight($a_val) + { + $this->setTabsAttribute("ContentHeight", $a_val); + } + + /** + * Get content height + * + * @return int content height + */ + public function getContentHeight() + { + return $this->tabs_node->get_attribute("ContentHeight"); + } - /** - * Set horizontal align - * - * @param string horizontal align - */ - function setHorizontalAlign($a_val) - { - $this->setTabsAttribute("HorizontalAlign", $a_val); - } - - /** - * Get horizontal align - * - * @return string horizontal align - */ - function getHorizontalAlign() - { - return $this->tabs_node->get_attribute("HorizontalAlign"); - } + /** + * Set horizontal align + * + * @param string horizontal align + */ + public function setHorizontalAlign($a_val) + { + $this->setTabsAttribute("HorizontalAlign", $a_val); + } + + /** + * Get horizontal align + * + * @return string horizontal align + */ + public function getHorizontalAlign() + { + return $this->tabs_node->get_attribute("HorizontalAlign"); + } - /** - * Set behavior - * - * @param string behavior - */ - function setBehavior($a_val) - { - $this->setTabsAttribute("Behavior", $a_val); - } - - /** - * Get behavior - * - * @return string behavior - */ - function getBehavior() - { - return $this->tabs_node->get_attribute("Behavior"); - } - - /** - * Get captions - */ - function getCaptions() - { - $captions = array(); - $tab_nodes = $this->tabs_node->child_nodes(); - $k = 0; - for($i = 0; $i < count($tab_nodes); $i++) - { - if ($tab_nodes[$i]->node_name() == "Tab") - { - $pc_id = $tab_nodes[$i]->get_attribute("PCID"); - $hier_id = $tab_nodes[$i]->get_attribute("HierId"); + /** + * Set behavior + * + * @param string behavior + */ + public function setBehavior($a_val) + { + $this->setTabsAttribute("Behavior", $a_val); + } + + /** + * Get behavior + * + * @return string behavior + */ + public function getBehavior() + { + return $this->tabs_node->get_attribute("Behavior"); + } + + /** + * Get captions + */ + public function getCaptions() + { + $captions = array(); + $tab_nodes = $this->tabs_node->child_nodes(); + $k = 0; + for ($i = 0; $i < count($tab_nodes); $i++) { + if ($tab_nodes[$i]->node_name() == "Tab") { + $pc_id = $tab_nodes[$i]->get_attribute("PCID"); + $hier_id = $tab_nodes[$i]->get_attribute("HierId"); - $tab_node_childs = $tab_nodes[$i]->child_nodes(); - $current_caption = ""; - for($j = 0; $j < count($tab_node_childs); $j++) - { - if ($tab_node_childs[$j]->node_name() == "TabCaption") - { - $current_caption = $tab_node_childs[$j]->get_content(); - } - } - $captions[] = array("pos" => $k, - "caption" => $current_caption, "pc_id" => $pc_id, "hier_id" => $hier_id); - $k++; - } - } - - return $captions; - } + $tab_node_childs = $tab_nodes[$i]->child_nodes(); + $current_caption = ""; + for ($j = 0; $j < count($tab_node_childs); $j++) { + if ($tab_node_childs[$j]->node_name() == "TabCaption") { + $current_caption = $tab_node_childs[$j]->get_content(); + } + } + $captions[] = array("pos" => $k, + "caption" => $current_caption, "pc_id" => $pc_id, "hier_id" => $hier_id); + $k++; + } + } + + return $captions; + } - /** - * Get caption - */ - function getCaption($a_hier_id, $a_pc_id) - { - $captions = array(); - $tab_nodes = $this->tabs_node->child_nodes(); - $k = 0; - for($i = 0; $i < count($tab_nodes); $i++) - { - if ($tab_nodes[$i]->node_name() == "Tab") - { - if ($a_pc_id == $tab_nodes[$i]->get_attribute("PCID") && - ($a_hier_id == $tab_nodes[$i]->get_attribute("HierId"))) - { - $tab_node_childs = $tab_nodes[$i]->child_nodes(); - for($j = 0; $j < count($tab_node_childs); $j++) - { - if ($tab_node_childs[$j]->node_name() == "TabCaption") - { - return $tab_node_childs[$j]->get_content(); - } - } - } - } - } - - return ""; - } + /** + * Get caption + */ + public function getCaption($a_hier_id, $a_pc_id) + { + $captions = array(); + $tab_nodes = $this->tabs_node->child_nodes(); + $k = 0; + for ($i = 0; $i < count($tab_nodes); $i++) { + if ($tab_nodes[$i]->node_name() == "Tab") { + if ($a_pc_id == $tab_nodes[$i]->get_attribute("PCID") && + ($a_hier_id == $tab_nodes[$i]->get_attribute("HierId"))) { + $tab_node_childs = $tab_nodes[$i]->child_nodes(); + for ($j = 0; $j < count($tab_node_childs); $j++) { + if ($tab_node_childs[$j]->node_name() == "TabCaption") { + return $tab_node_childs[$j]->get_content(); + } + } + } + } + } + + return ""; + } - /** - * Save positions of tabs - */ - function savePositions($a_pos) - { - asort($a_pos); - - // File Item - $childs = $this->tabs_node->child_nodes(); - $nodes = array(); - for ($i=0; $inode_name() == "Tab") - { - $pc_id = $childs[$i]->get_attribute("PCID"); - $hier_id = $childs[$i]->get_attribute("HierId"); - $nodes[$hier_id.":".$pc_id] = $childs[$i]; - $childs[$i]->unlink($childs[$i]); - } - } - - foreach($a_pos as $k => $v) - { - if (is_object($nodes[$k])) - { - $nodes[$k] = $this->tabs_node->append_child($nodes[$k]); - } - } - } + /** + * Save positions of tabs + */ + public function savePositions($a_pos) + { + asort($a_pos); + + // File Item + $childs = $this->tabs_node->child_nodes(); + $nodes = array(); + for ($i=0; $inode_name() == "Tab") { + $pc_id = $childs[$i]->get_attribute("PCID"); + $hier_id = $childs[$i]->get_attribute("HierId"); + $nodes[$hier_id . ":" . $pc_id] = $childs[$i]; + $childs[$i]->unlink($childs[$i]); + } + } + + foreach ($a_pos as $k => $v) { + if (is_object($nodes[$k])) { + $nodes[$k] = $this->tabs_node->append_child($nodes[$k]); + } + } + } - /** - * Add Tab items - */ - function saveCaptions($a_captions) - { - // iterate all tab nodes - $tab_nodes = $this->tabs_node->child_nodes(); - for($i = 0; $i < count($tab_nodes); $i++) - { - if ($tab_nodes[$i]->node_name() == "Tab") - { - $pc_id = $tab_nodes[$i]->get_attribute("PCID"); - $hier_id = $tab_nodes[$i]->get_attribute("HierId"); - $k = $hier_id.":".$pc_id; - // if caption given, set it, otherwise delete caption subitem - if ($a_captions[$k] != "") - { - ilDOMUtil::setFirstOptionalElement($this->dom, $tab_nodes[$i], "TabCaption", - array(), $a_captions[$k], array()); - } - else - { - ilDOMUtil::deleteAllChildsByName($tab_nodes[$i], array("TabCaption")); - } - } - } - } + /** + * Add Tab items + */ + public function saveCaptions($a_captions) + { + // iterate all tab nodes + $tab_nodes = $this->tabs_node->child_nodes(); + for ($i = 0; $i < count($tab_nodes); $i++) { + if ($tab_nodes[$i]->node_name() == "Tab") { + $pc_id = $tab_nodes[$i]->get_attribute("PCID"); + $hier_id = $tab_nodes[$i]->get_attribute("HierId"); + $k = $hier_id . ":" . $pc_id; + // if caption given, set it, otherwise delete caption subitem + if ($a_captions[$k] != "") { + ilDOMUtil::setFirstOptionalElement( + $this->dom, + $tab_nodes[$i], + "TabCaption", + array(), + $a_captions[$k], + array() + ); + } else { + ilDOMUtil::deleteAllChildsByName($tab_nodes[$i], array("TabCaption")); + } + } + } + } - /** - * Save positions of tabs - */ - function deleteTab($a_hier_id, $a_pc_id) - { - // File Item - $childs = $this->tabs_node->child_nodes(); - $nodes = array(); - for ($i=0; $inode_name() == "Tab") - { - if ($a_pc_id == $childs[$i]->get_attribute("PCID") && - $a_hier_id == $childs[$i]->get_attribute("HierId")) - { - $childs[$i]->unlink($childs[$i]); - } - } - } - } + /** + * Save positions of tabs + */ + public function deleteTab($a_hier_id, $a_pc_id) + { + // File Item + $childs = $this->tabs_node->child_nodes(); + $nodes = array(); + for ($i=0; $inode_name() == "Tab") { + if ($a_pc_id == $childs[$i]->get_attribute("PCID") && + $a_hier_id == $childs[$i]->get_attribute("HierId")) { + $childs[$i]->unlink($childs[$i]); + } + } + } + } - /** - * Add a tab - */ - function addTab($a_caption) - { - $new_item = $this->dom->create_element("Tab"); - $new_item = $this->tabs_node->append_child($new_item); - ilDOMUtil::setFirstOptionalElement($this->dom, $new_item, "TabCaption", - array(), $a_caption, array()); - } - - /** - * Set template - * - * @param string $a_template template - */ - function setTemplate($a_template) - { - $this->setTabsAttribute("Template", $a_template); - } + /** + * Add a tab + */ + public function addTab($a_caption) + { + $new_item = $this->dom->create_element("Tab"); + $new_item = $this->tabs_node->append_child($new_item); + ilDOMUtil::setFirstOptionalElement( + $this->dom, + $new_item, + "TabCaption", + array(), + $a_caption, + array() + ); + } + + /** + * Set template + * + * @param string $a_template template + */ + public function setTemplate($a_template) + { + $this->setTabsAttribute("Template", $a_template); + } - /** - * Get template - * - * @return string template - */ - function getTemplate() - { - return $this->tabs_node->get_attribute("Template"); - } + /** + * Get template + * + * @return string template + */ + public function getTemplate() + { + return $this->tabs_node->get_attribute("Template"); + } - /** - * Get lang vars needed for editing - * @return array array of lang var keys - */ - static function getLangVars() - { - return array("pc_vacc", "pc_hacc", "pc_carousel"); - } + /** + * Get lang vars needed for editing + * @return array array of lang var keys + */ + public static function getLangVars() + { + return array("pc_vacc", "pc_hacc", "pc_carousel"); + } - /** - * Set auto animation waiting time - * - * @param int $a_val auto animation time - */ - function setAutoTime($a_val) - { - $this->setTabsAttribute("AutoAnimWait", $a_val); - } + /** + * Set auto animation waiting time + * + * @param int $a_val auto animation time + */ + public function setAutoTime($a_val) + { + $this->setTabsAttribute("AutoAnimWait", $a_val); + } - /** - * Get auto animation waiting time - * - * @return int auto animation time - */ - function getAutoTime() - { - return $this->tabs_node->get_attribute("AutoAnimWait"); - } + /** + * Get auto animation waiting time + * + * @return int auto animation time + */ + public function getAutoTime() + { + return $this->tabs_node->get_attribute("AutoAnimWait"); + } - /** - * Set random start - * - * @param bool $a_val random start - */ - function setRandomStart($a_val) - { - $this->setTabsAttribute("RandomStart", $a_val); - } + /** + * Set random start + * + * @param bool $a_val random start + */ + public function setRandomStart($a_val) + { + $this->setTabsAttribute("RandomStart", $a_val); + } - /** - * Get random start - * - * @return bool random start - */ - function getRandomStart() - { - return $this->tabs_node->get_attribute("RandomStart"); - } + /** + * Get random start + * + * @return bool random start + */ + public function getRandomStart() + { + return $this->tabs_node->get_attribute("RandomStart"); + } - /** - * Get Javascript files - */ - function getJavascriptFiles($a_mode) - { - include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); - return ilAccordionGUI::getLocalJavascriptFiles(); - } - - /** - * Get Javascript files - */ - function getCssFiles($a_mode) - { - include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); - return ilAccordionGUI::getLocalCssFiles(); - } + /** + * Get Javascript files + */ + public function getJavascriptFiles($a_mode) + { + include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); + return ilAccordionGUI::getLocalJavascriptFiles(); + } + /** + * Get Javascript files + */ + public function getCssFiles($a_mode) + { + include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); + return ilAccordionGUI::getLocalCssFiles(); + } } -?> diff --git a/Services/COPage/classes/class.ilPCTabsGUI.php b/Services/COPage/classes/class.ilPCTabsGUI.php index 33cce8730a11c6157e4a67bc06e9e488a7b0ec4b..cec596f24eb4357f709510035d70768000be8beb 100755 --- a/Services/COPage/classes/class.ilPCTabsGUI.php +++ b/Services/COPage/classes/class.ilPCTabsGUI.php @@ -16,609 +16,581 @@ require_once("./Services/COPage/classes/class.ilPageContentGUI.php"); */ class ilPCTabsGUI extends ilPageContentGUI { - /** - * @var ilDB - */ - protected $db; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * Constructor - * @access 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(); - $this->db = $DIC->database(); - $this->tabs = $DIC->tabs(); - $this->toolbar = $DIC->toolbar(); - 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 tabs - */ - function insert($a_omit_form_init = false) - { - $tpl = $this->tpl; - - $this->displayValidationError(); - - if (!$a_omit_form_init) - { - $this->initForm("create"); - } - $html = $this->form->getHTML(); - $tpl->setContent($html); - } - - /** - * Edit tabs - */ - function editProperties() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - - $this->displayValidationError(); - $this->setTabs(); - - $this->initForm(); - $this->getFormValues(); - $html = $this->form->getHTML(); - $tpl->setContent($html); - } - - /** - * Insert tabs form. - */ - function initForm($a_mode = "edit") - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); - ilAccordionGUI::addCss(); - - // edit form - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - $this->form->setFormAction($ilCtrl->getFormAction($this)); - if ($a_mode != "edit") - { - $this->form->setTitle($lng->txt("cont_ed_insert_tabs")); - } - else - { - $this->form->setTitle($lng->txt("cont_edit_tabs")); - } - - - // type selection - $radg = new ilRadioGroupInputGUI($lng->txt("cont_type"), "type"); - $radg->setValue(ilPCTabs::ACCORDION_VER); - - // type: vertical accordion - $op1 = new ilRadioOption($lng->txt("cont_tabs_acc_ver"), ilPCTabs::ACCORDION_VER); - - $templ = $this->getTemplateOptions("vaccordion"); - require_once("./Services/Form/classes/class.ilAdvSelectInputGUI.php"); - if (count($templ) > 0) - { - $vchar_prop = new ilAdvSelectInputGUI($this->lng->txt("cont_characteristic"), - "vaccord_templ"); - foreach($templ as $k => $te) - { - $t = explode(":", $k); - $html = $this->style->lookupTemplatePreview($t[1]).'
          '.$te."
          "; - $vchar_prop->addOption($k, $te, $html); - if ($t[2] == "VerticalAccordion") - { - $vchar_prop->setValue($k); - } - } - $op1->addSubItem($vchar_prop); - } - else - { - $vchar_prop = new ilHiddenInputGUI("vaccord_templ"); - $this->form->addItem($vchar_prop); - } - $radg->addOption($op1); - - - - // type: horizontal accordion - $op2 = new ilRadioOption($lng->txt("cont_tabs_acc_hor"), ilPCTabs::ACCORDION_HOR); - - $templ = $this->getTemplateOptions("haccordion"); - if (count($templ) > 0) - { - $hchar_prop = new ilAdvSelectInputGUI($this->lng->txt("cont_characteristic"), - "haccord_templ"); - foreach($templ as $k => $te) - { - $t = explode(":", $k); - $html = $this->style->lookupTemplatePreview($t[1]).'
          '.$te."
          "; - $hchar_prop->addOption($k, $te, $html); - if ($t[2] == "HorizontalAccordion") - { - $hchar_prop->setValue($k); - } - } - $op2->addSubItem($hchar_prop); - } - else - { - $hchar_prop = new ilHiddenInputGUI("haccord_templ"); - $this->form->addItem($hchar_prop); - } - - $radg->addOption($op2); - - // type: carousel - $op3 = new ilRadioOption($lng->txt("cont_tabs_carousel"), ilPCTabs::CAROUSEL); - $templ = $this->getTemplateOptions("carousel"); - require_once("./Services/Form/classes/class.ilAdvSelectInputGUI.php"); - if (count($templ) > 0) - { - $cchar_prop = new ilAdvSelectInputGUI($this->lng->txt("cont_characteristic"), - "carousel_templ"); - foreach($templ as $k => $te) - { - $t = explode(":", $k); - $html = $this->style->lookupTemplatePreview($t[1]).'
          '.$te."
          "; - $cchar_prop->addOption($k, $te, $html); - if ($t[2] == "Carousel") - { - $cchar_prop->setValue($k); - } - } - $op3->addSubItem($cchar_prop); - } - else - { - $cchar_prop = new ilHiddenInputGUI("carousel_templ"); - $this->form->addItem($cchar_prop); - } - - $radg->addOption($op3); - $this->form->addItem($radg); - - - // number of initial tabs - if ($a_mode == "create") - { - $nr_prop = new ilSelectInputGUI($lng->txt("cont_number_of_tabs"), - "nr"); - $nrs = array(1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6, - 7 => 7, 8 => 8, 9 => 9, 10 => 10); - $nr_prop->setOptions($nrs); - $this->form->addItem($nr_prop); - } - - $ni = new ilNumberInputGUI($this->lng->txt("cont_tab_cont_width"), "content_width"); - $ni->setMaxLength(4); - $ni->setSize(4); - $this->form->addItem($ni); - - $ni = new ilNumberInputGUI($this->lng->txt("cont_tab_cont_height"), "content_height"); - $ni->setMaxLength(4); - $ni->setSize(4); - $this->form->addItem($ni); - - // behaviour - $options = array( - "AllClosed" => $lng->txt("cont_all_closed"), - "FirstOpen" => $lng->txt("cont_first_open"), - "ForceAllOpen" => $lng->txt("cont_force_all_open"), - ); - $si = new ilSelectInputGUI($this->lng->txt("cont_behavior"), "vbehavior"); - $si->setOptions($options); - $op1->addSubItem($si); - $si = new ilSelectInputGUI($this->lng->txt("cont_behavior"), "hbehavior"); - $si->setOptions($options); - $op2->addSubItem($si); - - - // alignment - $align_opts = array("Left" => $lng->txt("cont_left"), - "Right" => $lng->txt("cont_right"), "Center" => $lng->txt("cont_center"), - "LeftFloat" => $lng->txt("cont_left_float"), - "RightFloat" => $lng->txt("cont_right_float")); - $align = new ilSelectInputGUI($this->lng->txt("cont_align"), "valign"); - $align->setOptions($align_opts); - $align->setValue("Center"); - //$align->setInfo($lng->txt("cont_tabs_hor_align_info")); - $op1->addSubItem($align); - $align = new ilSelectInputGUI($this->lng->txt("cont_align"), "calign"); - $align->setOptions($align_opts); - $align->setValue("Center"); - $op3->addSubItem($align); - - // carousel: time - $ti = new ilNumberInputGUI($this->lng->txt("cont_auto_time"), "auto_time"); - $ti->setMaxLength(6); - $ti->setSize(6); - $ti->setSuffix("ms"); - $ti->setMinValue(100); - $op3->addSubItem($ti); - - // carousel: random start - $cb = new ilCheckboxInputGUI($this->lng->txt("cont_rand_start"), "rand_start"); - //$cb->setOptionTitle($this->lng->txt("")); - //$cb->setInfo($this->lng->txt("")); - $op3->addSubItem($cb); - - - // save/cancel buttons - if ($a_mode == "create") - { - $this->form->addCommandButton("create_section", $lng->txt("save")); - $this->form->addCommandButton("cancelCreate", $lng->txt("cancel")); - } - else - { - $this->form->addCommandButton("update", $lng->txt("save")); - $this->form->addCommandButton("cancelUpdate", $lng->txt("cancel")); - } - } - - /** - * Get form values - */ - function getFormValues() - { - $values["type"] = $this->content_obj->getTabType(); - $values["content_width"] = $this->content_obj->getContentWidth(); - $values["content_height"] = $this->content_obj->getContentHeight(); - $values["valign"] = $this->content_obj->getHorizontalAlign(); - $values["calign"] = $this->content_obj->getHorizontalAlign(); - $values["vbehavior"] = $this->content_obj->getBehavior(); - $values["hbehavior"] = $this->content_obj->getBehavior(); - - $values["auto_time"] = $this->content_obj->getAutoTime(); - $values["rand_start"] = $this->content_obj->getRandomStart(); - - $this->form->setValuesByArray($values); - - if ($values["type"] == ilPCTabs::ACCORDION_VER) - { - $va = $this->form->getItemByPostVar("vaccord_templ"); - $v = "t:". - ilObjStyleSheet::_lookupTemplateIdByName($this->getStyleId(), $this->content_obj->getTemplate()).":". - $this->content_obj->getTemplate(); - $va->setValue($v); - } - if ($values["type"] == ilPCTabs::ACCORDION_HOR) - { - $ha = $this->form->getItemByPostVar("haccord_templ"); - $v = "t:". - ilObjStyleSheet::_lookupTemplateIdByName($this->getStyleId(), $this->content_obj->getTemplate()).":". - $this->content_obj->getTemplate(); - $ha->setValue($v); - } - if ($values["type"] == ilPCTabs::CAROUSEL) - { - $ca = $this->form->getItemByPostVar("carousel_templ"); - $v = "t:". - ilObjStyleSheet::_lookupTemplateIdByName($this->getStyleId(), $this->content_obj->getTemplate()).":". - $this->content_obj->getTemplate(); - $ca->setValue($v); - } - } - - /** - * Create new tabs in dom and update page in db - */ - function create() - { - $ilDB = $this->db; - $lng = $this->lng; - - $this->initForm("create"); - if ($this->form->checkInput()) - { - $this->content_obj = new ilPCTabs($this->getPage()); - $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); - - $this->setPropertiesByForm(); - - for ($i = 0; $i < (int) $_POST["nr"]; $i++) - { - $this->content_obj->addTab($lng->txt("cont_new_tab")); - } - - $this->updated = $this->pg_obj->update(); - - if ($this->updated === true) - { - $this->afterCreation(); - //$this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - else - { - $this->insert(); - } - } - else - { - $this->form->setValuesByPost(); - $this->insert(true); -// return $this->form->getHtml(); - } - } - - /** - * After creation processing - */ - function afterCreation() - { - $ilCtrl = $this->ctrl; - - $this->pg_obj->stripHierIDs(); - $this->pg_obj->addHierIDs(); - $ilCtrl->setParameter($this, "hier_id", $this->content_obj->readHierId()); - $ilCtrl->setParameter($this, "pc_id", $this->content_obj->readPCId()); - $this->content_obj->setHierId($this->content_obj->readHierId()); - $this->setHierId($this->content_obj->readHierId()); - $this->content_obj->setPCId($this->content_obj->readPCId()); - $this->edit(); - } - - /** - * Set properties by post - * - * @param - * @return - */ - function setPropertiesByForm() - { - $c = $this->content_obj; - $f = $this->form; - - $c->setTabType($f->getInput("type")); - - $c->setContentWidth($f->getInput("content_width")); - $c->setContentHeight($f->getInput("content_height")); - $c->setTemplate(""); - switch ($_POST["type"]) - { - case ilPCTabs::ACCORDION_VER: - $t = explode(":", $f->getInput("vaccord_templ")); - $c->setTemplate($t[2]); - $c->setBehavior($f->getInput("vbehavior")); - $c->setHorizontalAlign($f->getInput("valign")); - break; - - case ilPCTabs::ACCORDION_HOR: - $t = explode(":", $f->getInput("haccord_templ")); - $c->setTemplate($t[2]); - $c->setBehavior($f->getInput("hbehavior")); - break; - - case ilPCTabs::CAROUSEL: - $t = explode(":", $f->getInput("carousel_templ")); - $c->setTemplate($t[2]); - $c->setHorizontalAlign($f->getInput("calign")); - $c->setAutoTime($f->getInput("auto_time")); - $c->setRandomStart($f->getInput("rand_start")); - break; - } - } - - - /** - * Save tabs properties in db and return to page edit screen - */ - function update() - { - $this->initForm(); - $this->updated = false; - if ($this->form->checkInput()) - { - $this->setPropertiesByForm(); - $this->updated = $this->pg_obj->update(); - } - if ($this->updated === true) - { - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "editProperties"); - //$this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - else - { - $this->pg_obj->addHierIDs(); - $this->editProperties(); - } - } - - // - // Edit Tabs - // - - - /** - * List all tabs - */ - function edit() - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $ilToolbar = $this->toolbar; - $lng = $this->lng; - - $ilToolbar->addButton($lng->txt("cont_add_tab"), - $ilCtrl->getLinkTarget($this, "addTab")); - - $this->setTabs(); - $ilTabs->activateTab("cont_tabs"); - include_once("./Services/COPage/classes/class.ilPCTabsTableGUI.php"); - $table_gui = new ilPCTabsTableGUI($this, "edit", $this->content_obj); - $tpl->setContent($table_gui->getHTML()); - } - - /** - * Save tabs properties in db and return to page edit screen - */ - function saveTabs() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if (is_array($_POST["caption"])) - { - $captions = ilUtil::stripSlashesArray($_POST["caption"]); - $this->content_obj->saveCaptions($captions); - } - if (is_array($_POST["position"])) - { - $positions = ilUtil::stripSlashesArray($_POST["position"]); - $this->content_obj->savePositions($positions); - } - $this->updated = $this->pg_obj->update(); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "edit"); - } - - /** - * Save tabs properties in db and return to page edit screen - */ - function addTab() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->content_obj->addTab($lng->txt("cont_new_tab")); - $this->updated = $this->pg_obj->update(); - - ilUtil::sendSuccess($lng->txt("cont_added_tab"), true); - $ilCtrl->redirect($this, "edit"); - } - - /** - * Confirm tabs deletion - */ - function confirmTabsDeletion() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - $this->setTabs(); - - if (!is_array($_POST["tid"]) || count($_POST["tid"]) == 0) - { - ilUtil::sendInfo($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "edit"); - } - else - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("cont_tabs_confirm_deletion")); - $cgui->setCancel($lng->txt("cancel"), "cancelTabDeletion"); - $cgui->setConfirm($lng->txt("delete"), "deleteTabs"); - - foreach ($_POST["tid"] as $k => $i) - { - $id = explode(":", $k); - $cgui->addItem("tid[]", $k, - $this->content_obj->getCaption($id[0], $id[1])); - } - - $tpl->setContent($cgui->getHTML()); - } - } - - /** - * Cancel tab deletion - */ - function cancelTabDeletion() - { - $ilCtrl = $this->ctrl; - $ilCtrl->redirect($this, "edit"); - } - - /** - * Delete Tabs - */ - function deleteTabs() - { - $ilCtrl = $this->ctrl; - - if (is_array($_POST["tid"])) - { - foreach($_POST["tid"] as $tid) - { - $ids = explode(":", $tid); - $this->content_obj->deleteTab($ids[0], $ids[1]); - } - } - $this->updated = $this->pg_obj->update(); - - $ilCtrl->redirect($this, "edit"); - } - - - /** - * Set tabs - */ - function setTabs() - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $ilTabs->setBackTarget($lng->txt("pg"), - $this->ctrl->getParentReturn($this)); - - $ilTabs->addTarget("cont_tabs", - $ilCtrl->getLinkTarget($this, "edit"), "edit", - get_class($this)); - - $ilTabs->addTarget("cont_edit_tabs", - $ilCtrl->getLinkTarget($this, "editProperties"), "editProperties", - get_class($this)); - - } + /** + * @var ilDB + */ + protected $db; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * Constructor + * @access public + */ + 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(); + $this->db = $DIC->database(); + $this->tabs = $DIC->tabs(); + $this->toolbar = $DIC->toolbar(); + 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 tabs + */ + public function insert($a_omit_form_init = false) + { + $tpl = $this->tpl; + + $this->displayValidationError(); + + if (!$a_omit_form_init) { + $this->initForm("create"); + } + $html = $this->form->getHTML(); + $tpl->setContent($html); + } + + /** + * Edit tabs + */ + public function editProperties() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + + $this->displayValidationError(); + $this->setTabs(); + + $this->initForm(); + $this->getFormValues(); + $html = $this->form->getHTML(); + $tpl->setContent($html); + } + + /** + * Insert tabs form. + */ + public function initForm($a_mode = "edit") + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); + ilAccordionGUI::addCss(); + + // edit form + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + $this->form->setFormAction($ilCtrl->getFormAction($this)); + if ($a_mode != "edit") { + $this->form->setTitle($lng->txt("cont_ed_insert_tabs")); + } else { + $this->form->setTitle($lng->txt("cont_edit_tabs")); + } + + + // type selection + $radg = new ilRadioGroupInputGUI($lng->txt("cont_type"), "type"); + $radg->setValue(ilPCTabs::ACCORDION_VER); + + // type: vertical accordion + $op1 = new ilRadioOption($lng->txt("cont_tabs_acc_ver"), ilPCTabs::ACCORDION_VER); + + $templ = $this->getTemplateOptions("vaccordion"); + require_once("./Services/Form/classes/class.ilAdvSelectInputGUI.php"); + if (count($templ) > 0) { + $vchar_prop = new ilAdvSelectInputGUI( + $this->lng->txt("cont_characteristic"), + "vaccord_templ" + ); + foreach ($templ as $k => $te) { + $t = explode(":", $k); + $html = $this->style->lookupTemplatePreview($t[1]) . '
          ' . $te . "
          "; + $vchar_prop->addOption($k, $te, $html); + if ($t[2] == "VerticalAccordion") { + $vchar_prop->setValue($k); + } + } + $op1->addSubItem($vchar_prop); + } else { + $vchar_prop = new ilHiddenInputGUI("vaccord_templ"); + $this->form->addItem($vchar_prop); + } + $radg->addOption($op1); + + + + // type: horizontal accordion + $op2 = new ilRadioOption($lng->txt("cont_tabs_acc_hor"), ilPCTabs::ACCORDION_HOR); + + $templ = $this->getTemplateOptions("haccordion"); + if (count($templ) > 0) { + $hchar_prop = new ilAdvSelectInputGUI( + $this->lng->txt("cont_characteristic"), + "haccord_templ" + ); + foreach ($templ as $k => $te) { + $t = explode(":", $k); + $html = $this->style->lookupTemplatePreview($t[1]) . '
          ' . $te . "
          "; + $hchar_prop->addOption($k, $te, $html); + if ($t[2] == "HorizontalAccordion") { + $hchar_prop->setValue($k); + } + } + $op2->addSubItem($hchar_prop); + } else { + $hchar_prop = new ilHiddenInputGUI("haccord_templ"); + $this->form->addItem($hchar_prop); + } + + $radg->addOption($op2); + + // type: carousel + $op3 = new ilRadioOption($lng->txt("cont_tabs_carousel"), ilPCTabs::CAROUSEL); + $templ = $this->getTemplateOptions("carousel"); + require_once("./Services/Form/classes/class.ilAdvSelectInputGUI.php"); + if (count($templ) > 0) { + $cchar_prop = new ilAdvSelectInputGUI( + $this->lng->txt("cont_characteristic"), + "carousel_templ" + ); + foreach ($templ as $k => $te) { + $t = explode(":", $k); + $html = $this->style->lookupTemplatePreview($t[1]) . '
          ' . $te . "
          "; + $cchar_prop->addOption($k, $te, $html); + if ($t[2] == "Carousel") { + $cchar_prop->setValue($k); + } + } + $op3->addSubItem($cchar_prop); + } else { + $cchar_prop = new ilHiddenInputGUI("carousel_templ"); + $this->form->addItem($cchar_prop); + } + + $radg->addOption($op3); + $this->form->addItem($radg); + + + // number of initial tabs + if ($a_mode == "create") { + $nr_prop = new ilSelectInputGUI( + $lng->txt("cont_number_of_tabs"), + "nr" + ); + $nrs = array(1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6, + 7 => 7, 8 => 8, 9 => 9, 10 => 10); + $nr_prop->setOptions($nrs); + $this->form->addItem($nr_prop); + } + + $ni = new ilNumberInputGUI($this->lng->txt("cont_tab_cont_width"), "content_width"); + $ni->setMaxLength(4); + $ni->setSize(4); + $this->form->addItem($ni); + + $ni = new ilNumberInputGUI($this->lng->txt("cont_tab_cont_height"), "content_height"); + $ni->setMaxLength(4); + $ni->setSize(4); + $this->form->addItem($ni); + + // behaviour + $options = array( + "AllClosed" => $lng->txt("cont_all_closed"), + "FirstOpen" => $lng->txt("cont_first_open"), + "ForceAllOpen" => $lng->txt("cont_force_all_open"), + ); + $si = new ilSelectInputGUI($this->lng->txt("cont_behavior"), "vbehavior"); + $si->setOptions($options); + $op1->addSubItem($si); + $si = new ilSelectInputGUI($this->lng->txt("cont_behavior"), "hbehavior"); + $si->setOptions($options); + $op2->addSubItem($si); + + + // alignment + $align_opts = array("Left" => $lng->txt("cont_left"), + "Right" => $lng->txt("cont_right"), "Center" => $lng->txt("cont_center"), + "LeftFloat" => $lng->txt("cont_left_float"), + "RightFloat" => $lng->txt("cont_right_float")); + $align = new ilSelectInputGUI($this->lng->txt("cont_align"), "valign"); + $align->setOptions($align_opts); + $align->setValue("Center"); + //$align->setInfo($lng->txt("cont_tabs_hor_align_info")); + $op1->addSubItem($align); + $align = new ilSelectInputGUI($this->lng->txt("cont_align"), "calign"); + $align->setOptions($align_opts); + $align->setValue("Center"); + $op3->addSubItem($align); + + // carousel: time + $ti = new ilNumberInputGUI($this->lng->txt("cont_auto_time"), "auto_time"); + $ti->setMaxLength(6); + $ti->setSize(6); + $ti->setSuffix("ms"); + $ti->setMinValue(100); + $op3->addSubItem($ti); + + // carousel: random start + $cb = new ilCheckboxInputGUI($this->lng->txt("cont_rand_start"), "rand_start"); + //$cb->setOptionTitle($this->lng->txt("")); + //$cb->setInfo($this->lng->txt("")); + $op3->addSubItem($cb); + + + // save/cancel buttons + if ($a_mode == "create") { + $this->form->addCommandButton("create_section", $lng->txt("save")); + $this->form->addCommandButton("cancelCreate", $lng->txt("cancel")); + } else { + $this->form->addCommandButton("update", $lng->txt("save")); + $this->form->addCommandButton("cancelUpdate", $lng->txt("cancel")); + } + } + + /** + * Get form values + */ + public function getFormValues() + { + $values["type"] = $this->content_obj->getTabType(); + $values["content_width"] = $this->content_obj->getContentWidth(); + $values["content_height"] = $this->content_obj->getContentHeight(); + $values["valign"] = $this->content_obj->getHorizontalAlign(); + $values["calign"] = $this->content_obj->getHorizontalAlign(); + $values["vbehavior"] = $this->content_obj->getBehavior(); + $values["hbehavior"] = $this->content_obj->getBehavior(); + + $values["auto_time"] = $this->content_obj->getAutoTime(); + $values["rand_start"] = $this->content_obj->getRandomStart(); + + $this->form->setValuesByArray($values); + + if ($values["type"] == ilPCTabs::ACCORDION_VER) { + $va = $this->form->getItemByPostVar("vaccord_templ"); + $v = "t:" . + ilObjStyleSheet::_lookupTemplateIdByName($this->getStyleId(), $this->content_obj->getTemplate()) . ":" . + $this->content_obj->getTemplate(); + $va->setValue($v); + } + if ($values["type"] == ilPCTabs::ACCORDION_HOR) { + $ha = $this->form->getItemByPostVar("haccord_templ"); + $v = "t:" . + ilObjStyleSheet::_lookupTemplateIdByName($this->getStyleId(), $this->content_obj->getTemplate()) . ":" . + $this->content_obj->getTemplate(); + $ha->setValue($v); + } + if ($values["type"] == ilPCTabs::CAROUSEL) { + $ca = $this->form->getItemByPostVar("carousel_templ"); + $v = "t:" . + ilObjStyleSheet::_lookupTemplateIdByName($this->getStyleId(), $this->content_obj->getTemplate()) . ":" . + $this->content_obj->getTemplate(); + $ca->setValue($v); + } + } + + /** + * Create new tabs in dom and update page in db + */ + public function create() + { + $ilDB = $this->db; + $lng = $this->lng; + + $this->initForm("create"); + if ($this->form->checkInput()) { + $this->content_obj = new ilPCTabs($this->getPage()); + $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); + + $this->setPropertiesByForm(); + + for ($i = 0; $i < (int) $_POST["nr"]; $i++) { + $this->content_obj->addTab($lng->txt("cont_new_tab")); + } + + $this->updated = $this->pg_obj->update(); + + if ($this->updated === true) { + $this->afterCreation(); + //$this->ctrl->returnToParent($this, "jump".$this->hier_id); + } else { + $this->insert(); + } + } else { + $this->form->setValuesByPost(); + $this->insert(true); + // return $this->form->getHtml(); + } + } + + /** + * After creation processing + */ + public function afterCreation() + { + $ilCtrl = $this->ctrl; + + $this->pg_obj->stripHierIDs(); + $this->pg_obj->addHierIDs(); + $ilCtrl->setParameter($this, "hier_id", $this->content_obj->readHierId()); + $ilCtrl->setParameter($this, "pc_id", $this->content_obj->readPCId()); + $this->content_obj->setHierId($this->content_obj->readHierId()); + $this->setHierId($this->content_obj->readHierId()); + $this->content_obj->setPCId($this->content_obj->readPCId()); + $this->edit(); + } + + /** + * Set properties by post + * + * @param + * @return + */ + public function setPropertiesByForm() + { + $c = $this->content_obj; + $f = $this->form; + + $c->setTabType($f->getInput("type")); + + $c->setContentWidth($f->getInput("content_width")); + $c->setContentHeight($f->getInput("content_height")); + $c->setTemplate(""); + switch ($_POST["type"]) { + case ilPCTabs::ACCORDION_VER: + $t = explode(":", $f->getInput("vaccord_templ")); + $c->setTemplate($t[2]); + $c->setBehavior($f->getInput("vbehavior")); + $c->setHorizontalAlign($f->getInput("valign")); + break; + + case ilPCTabs::ACCORDION_HOR: + $t = explode(":", $f->getInput("haccord_templ")); + $c->setTemplate($t[2]); + $c->setBehavior($f->getInput("hbehavior")); + break; + + case ilPCTabs::CAROUSEL: + $t = explode(":", $f->getInput("carousel_templ")); + $c->setTemplate($t[2]); + $c->setHorizontalAlign($f->getInput("calign")); + $c->setAutoTime($f->getInput("auto_time")); + $c->setRandomStart($f->getInput("rand_start")); + break; + } + } + + + /** + * Save tabs properties in db and return to page edit screen + */ + public function update() + { + $this->initForm(); + $this->updated = false; + if ($this->form->checkInput()) { + $this->setPropertiesByForm(); + $this->updated = $this->pg_obj->update(); + } + if ($this->updated === true) { + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "editProperties"); + //$this->ctrl->returnToParent($this, "jump".$this->hier_id); + } else { + $this->pg_obj->addHierIDs(); + $this->editProperties(); + } + } + + // + // Edit Tabs + // + + + /** + * List all tabs + */ + public function edit() + { + $tpl = $this->tpl; + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $ilToolbar = $this->toolbar; + $lng = $this->lng; + + $ilToolbar->addButton( + $lng->txt("cont_add_tab"), + $ilCtrl->getLinkTarget($this, "addTab") + ); + + $this->setTabs(); + $ilTabs->activateTab("cont_tabs"); + include_once("./Services/COPage/classes/class.ilPCTabsTableGUI.php"); + $table_gui = new ilPCTabsTableGUI($this, "edit", $this->content_obj); + $tpl->setContent($table_gui->getHTML()); + } + + /** + * Save tabs properties in db and return to page edit screen + */ + public function saveTabs() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if (is_array($_POST["caption"])) { + $captions = ilUtil::stripSlashesArray($_POST["caption"]); + $this->content_obj->saveCaptions($captions); + } + if (is_array($_POST["position"])) { + $positions = ilUtil::stripSlashesArray($_POST["position"]); + $this->content_obj->savePositions($positions); + } + $this->updated = $this->pg_obj->update(); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "edit"); + } + + /** + * Save tabs properties in db and return to page edit screen + */ + public function addTab() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $this->content_obj->addTab($lng->txt("cont_new_tab")); + $this->updated = $this->pg_obj->update(); + + ilUtil::sendSuccess($lng->txt("cont_added_tab"), true); + $ilCtrl->redirect($this, "edit"); + } + + /** + * Confirm tabs deletion + */ + public function confirmTabsDeletion() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + $this->setTabs(); + + if (!is_array($_POST["tid"]) || count($_POST["tid"]) == 0) { + ilUtil::sendInfo($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "edit"); + } else { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("cont_tabs_confirm_deletion")); + $cgui->setCancel($lng->txt("cancel"), "cancelTabDeletion"); + $cgui->setConfirm($lng->txt("delete"), "deleteTabs"); + + foreach ($_POST["tid"] as $k => $i) { + $id = explode(":", $k); + $cgui->addItem( + "tid[]", + $k, + $this->content_obj->getCaption($id[0], $id[1]) + ); + } + + $tpl->setContent($cgui->getHTML()); + } + } + + /** + * Cancel tab deletion + */ + public function cancelTabDeletion() + { + $ilCtrl = $this->ctrl; + $ilCtrl->redirect($this, "edit"); + } + + /** + * Delete Tabs + */ + public function deleteTabs() + { + $ilCtrl = $this->ctrl; + + if (is_array($_POST["tid"])) { + foreach ($_POST["tid"] as $tid) { + $ids = explode(":", $tid); + $this->content_obj->deleteTab($ids[0], $ids[1]); + } + } + $this->updated = $this->pg_obj->update(); + + $ilCtrl->redirect($this, "edit"); + } + + + /** + * Set tabs + */ + public function setTabs() + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $ilTabs->setBackTarget( + $lng->txt("pg"), + $this->ctrl->getParentReturn($this) + ); + + $ilTabs->addTarget( + "cont_tabs", + $ilCtrl->getLinkTarget($this, "edit"), + "edit", + get_class($this) + ); + + $ilTabs->addTarget( + "cont_edit_tabs", + $ilCtrl->getLinkTarget($this, "editProperties"), + "editProperties", + get_class($this) + ); + } } -?> diff --git a/Services/COPage/classes/class.ilPCTabsTableGUI.php b/Services/COPage/classes/class.ilPCTabsTableGUI.php index 207afb5d69bea91d52dee82badf208409bc81bff..46ff3db49d7fce9cd00776dc128cf2e92b2c7a07 100755 --- a/Services/COPage/classes/class.ilPCTabsTableGUI.php +++ b/Services/COPage/classes/class.ilPCTabsTableGUI.php @@ -13,57 +13,59 @@ include_once("Services/Table/classes/class.ilTable2GUI.php"); */ class ilPCTabsTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - function __construct($a_parent_obj, $a_parent_cmd, - $a_tabs) - { - global $DIC; + public function __construct( + $a_parent_obj, + $a_parent_cmd, + $a_tabs + ) { + 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->addColumn("", "", "1"); - $this->addColumn($lng->txt("cont_position"), "", "1"); - $this->addColumn($lng->txt("title"), "", "100%"); - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.tabs_row.html", - "Services/COPage"); - - $this->tabs = $a_tabs; - $caps = $this->tabs->getCaptions(); - $this->setData($this->tabs->getCaptions()); - $this->setLimit(0); - - $this->addMultiCommand("confirmTabsDeletion", $lng->txt("delete")); - $this->addCommandButton("saveTabs", $lng->txt("save")); - - $this->setTitle($lng->txt("cont_tabs")); - } - - /** - * 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->pos += 10; - $this->tpl->setVariable("POS", ilUtil::prepareFormOutput($this->pos)); - $this->tpl->setVariable("TID", $a_set["hier_id"].":".$a_set["pc_id"]); - $this->tpl->setVariable("VAL_CAPTION", ilUtil::prepareFormOutput($a_set["caption"])); - } + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->addColumn("", "", "1"); + $this->addColumn($lng->txt("cont_position"), "", "1"); + $this->addColumn($lng->txt("title"), "", "100%"); + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate( + "tpl.tabs_row.html", + "Services/COPage" + ); + + $this->tabs = $a_tabs; + $caps = $this->tabs->getCaptions(); + $this->setData($this->tabs->getCaptions()); + $this->setLimit(0); + + $this->addMultiCommand("confirmTabsDeletion", $lng->txt("delete")); + $this->addCommandButton("saveTabs", $lng->txt("save")); + + $this->setTitle($lng->txt("cont_tabs")); + } + + /** + * 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->pos += 10; + $this->tpl->setVariable("POS", ilUtil::prepareFormOutput($this->pos)); + $this->tpl->setVariable("TID", $a_set["hier_id"] . ":" . $a_set["pc_id"]); + $this->tpl->setVariable("VAL_CAPTION", ilUtil::prepareFormOutput($a_set["caption"])); + } } -?> \ No newline at end of file diff --git a/Services/COPage/classes/class.ilPCVerification.php b/Services/COPage/classes/class.ilPCVerification.php index 842e47e9c1d1352f3bea633a37807f0134ae1e75..cd3f79aaedd0281b52c79899286726510ec6d2dc 100644 --- a/Services/COPage/classes/class.ilPCVerification.php +++ b/Services/COPage/classes/class.ilPCVerification.php @@ -1,124 +1,118 @@ - -* @version $Id: class.ilPCListItem.php 22210 2009-10-26 09:46:06Z akill $ -* -* @ingroup ServicesCOPage -*/ -class ilPCVerification extends ilPageContent -{ - /** - * @var ilObjUser - */ - protected $user; - - var $dom; - - /** - * Init page content component. - */ - function init() - { - global $DIC; - - $this->user = $DIC->user(); - $this->setType("vrfc"); - } - - /** - * Set node - */ - function setNode($a_node) - { - parent::setNode($a_node); // this is the PageContent node - $this->vrfc_node = $a_node->first_child(); // this is the verification node - } - - /** - * Create verification node in xml. - * - * @param object $a_pg_obj Page Object - * @param string $a_hier_id Hierarchical ID - */ - 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->vrfc_node = $this->dom->create_element("Verification"); - $this->vrfc_node = $this->node->append_child($this->vrfc_node); - } - - /** - * Set verification data - * - * @param string $a_type - * @param int $a_id - */ - function setData($a_type, $a_id) - { - $ilUser = $this->user; - - $this->vrfc_node->set_attribute("Type", $a_type); - $this->vrfc_node->set_attribute("Id", $a_id); - $this->vrfc_node->set_attribute("User", $ilUser->getId()); - } - - /** - * Get verification data - * - * @return array - */ - function getData() - { - if (is_object($this->vrfc_node)) - { - return array("id"=>$this->vrfc_node->get_attribute("Id"), - "type"=>$this->vrfc_node->get_attribute("Type"), - "user"=>$this->vrfc_node->get_attribute("User")); - } - } - - /** - * Get lang vars needed for editing - * @return array array of lang var keys - */ - static function getLangVars() - { - return array("pc_vrfc", - "ed_insert_verification"); - } - - public static function isInPortfolioPage(ilPortfolioPage $a_page, $a_type, $a_id) - { - // try to find verification in portfolio page - $a_page->buildDom(); - $dom = $a_page->getDom(); - if($dom instanceof php4DOMDocument) - { - $dom = $dom->myDOMDocument; - } - $xpath_temp = new DOMXPath($dom); - $nodes = $xpath_temp->query("//PageContent/Verification"); - foreach($nodes as $node) - { - if($node->getAttribute("Type") == $a_type && - $node->getAttribute("Id") == $a_id) - { - return true; - } - } - - return false; - } -} - -?> \ No newline at end of file + +* @version $Id: class.ilPCListItem.php 22210 2009-10-26 09:46:06Z akill $ +* +* @ingroup ServicesCOPage +*/ +class ilPCVerification extends ilPageContent +{ + /** + * @var ilObjUser + */ + protected $user; + + public $dom; + + /** + * Init page content component. + */ + public function init() + { + global $DIC; + + $this->user = $DIC->user(); + $this->setType("vrfc"); + } + + /** + * Set node + */ + public function setNode($a_node) + { + parent::setNode($a_node); // this is the PageContent node + $this->vrfc_node = $a_node->first_child(); // this is the verification node + } + + /** + * Create verification node in xml. + * + * @param object $a_pg_obj Page Object + * @param string $a_hier_id Hierarchical ID + */ + public 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->vrfc_node = $this->dom->create_element("Verification"); + $this->vrfc_node = $this->node->append_child($this->vrfc_node); + } + + /** + * Set verification data + * + * @param string $a_type + * @param int $a_id + */ + public function setData($a_type, $a_id) + { + $ilUser = $this->user; + + $this->vrfc_node->set_attribute("Type", $a_type); + $this->vrfc_node->set_attribute("Id", $a_id); + $this->vrfc_node->set_attribute("User", $ilUser->getId()); + } + + /** + * Get verification data + * + * @return array + */ + public function getData() + { + if (is_object($this->vrfc_node)) { + return array("id"=>$this->vrfc_node->get_attribute("Id"), + "type"=>$this->vrfc_node->get_attribute("Type"), + "user"=>$this->vrfc_node->get_attribute("User")); + } + } + + /** + * Get lang vars needed for editing + * @return array array of lang var keys + */ + public static function getLangVars() + { + return array("pc_vrfc", + "ed_insert_verification"); + } + + public static function isInPortfolioPage(ilPortfolioPage $a_page, $a_type, $a_id) + { + // try to find verification in portfolio page + $a_page->buildDom(); + $dom = $a_page->getDom(); + if ($dom instanceof php4DOMDocument) { + $dom = $dom->myDOMDocument; + } + $xpath_temp = new DOMXPath($dom); + $nodes = $xpath_temp->query("//PageContent/Verification"); + foreach ($nodes as $node) { + if ($node->getAttribute("Type") == $a_type && + $node->getAttribute("Id") == $a_id) { + return true; + } + } + + return false; + } +} diff --git a/Services/COPage/classes/class.ilPCVerificationGUI.php b/Services/COPage/classes/class.ilPCVerificationGUI.php index 8e303b33d0a219ec9766af7967481f0d939a37c6..6a3dbbd14f110b892c4ed151b8bedacc9115f977 100644 --- a/Services/COPage/classes/class.ilPCVerificationGUI.php +++ b/Services/COPage/classes/class.ilPCVerificationGUI.php @@ -1,380 +1,367 @@ - -* @version $I$ -* -* @ingroup ServicesCOPage -*/ -class ilPCVerificationGUI extends ilPageContentGUI -{ - /** - * @var ilObjUser - */ - protected $user; - - - /** - * Constructor - * @access 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->user = $DIC->user(); - $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 verification form. - * - * @param ilPropertyFormGUI $a_form - */ - function insert(ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - - $this->displayValidationError(); - - if(!$a_form) - { - $a_form = $this->initForm(true); - } - $tpl->setContent($a_form->getHTML()); - } - - /** - * Edit verification form. - * - * @param ilPropertyFormGUI $a_form - */ - function edit(ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - - $this->displayValidationError(); - - if(!$a_form) - { - $a_form = $this->initForm(); - } - $tpl->setContent($a_form->getHTML()); - } - - /** - * Init verification form - * - * @param bool $a_insert - * @return ilPropertyFormGUI - * @throws ilDateTimeException - */ - protected function initForm($a_insert = false) - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - $lng = $this->lng; - - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this)); - if ($a_insert) - { - $form->setTitle($this->lng->txt("cont_insert_verification")); - } - else - { - $form->setTitle($this->lng->txt("cont_update_verification")); - } - - $lng->loadLanguageModule("wsp"); - $workspaceOptions = array(); - - $certificateSource = new ilRadioGroupInputGUI($this->lng->txt('certificate_selection'), 'certificate_selection'); - - $workspaceRadioButton = new ilRadioOption($this->lng->txt('certificate_workspace_option'), 'certificate_workspace_option'); - $persistentRadioButton = new ilRadioOption($this->lng->txt('certificate_persistent_option'), 'certificate_persistent_option'); - - $tree = new ilWorkspaceTree($ilUser->getId()); - $root = $tree->getRootId(); - if($root) - { - $root = $tree->getNodeData($root); - foreach ($tree->getSubTree($root) as $node) - { - if (in_array($node["type"], array("excv", "tstv", "crsv", "scov"))) - { - $workspaceOptions[$node["obj_id"]] = $node["title"]." (".$lng->txt("wsp_type_".$node["type"]).")"; - } - } - asort($workspaceOptions); - } - - $workspaceCertificates = new ilSelectInputGUI($this->lng->txt("cont_verification_object"), "object"); - $workspaceCertificates->setRequired(true); - $workspaceCertificates->setOptions($workspaceOptions); - - $repository = new ilUserCertificateRepository(); - - $certificates = $repository->fetchActiveCertificates($ilUser->getId()); - - $persistentOptions = array(); - foreach ($certificates as $certificate) { - $userCertificate = $certificate->getUserCertificate(); - $dateTime = ilDatePresentation::formatDate(new ilDateTime($userCertificate->getAcquiredTimestamp(),IL_CAL_UNIX)); - - $type = $lng->txt("wsp_type_" . $userCertificate->getObjType() . 'v'); - $additionalInformation = ' (' . $type . ' / ' . $dateTime .')'; - $persistentOptions[$userCertificate->getObjId()] = $certificate->getObjectTitle() . $additionalInformation; - } - - $persistentObject = new ilSelectInputGUI($this->lng->txt("cont_verification_object"), "persistent_object"); - $persistentObject->setRequired(true); - $persistentObject->setOptions($persistentOptions); - - $persistentRadioButton->addSubItem($persistentObject); - $workspaceRadioButton->addSubItem($workspaceCertificates); - - $certificateSource->addOption($persistentRadioButton); - $certificateSource->addOption($workspaceRadioButton); - - $certificateSource->setValue('certificate_persistent_option'); - - $form->addItem($certificateSource); - - if ($a_insert) { - $form->addCommandButton("create_verification", $this->lng->txt("save")); - $form->addCommandButton("cancelCreate", $this->lng->txt("cancel")); - } else { - $data = $this->content_obj->getData(); - - if ($data['type'] === 'crta') { - $certificateSource->setValue('certificate_persistent_option'); - $persistentObject->setValue($data["id"]); - } else { - $certificateSource->setValue('certificate_workspace_option'); - $workspaceCertificates->setValue($data["id"]); - } - - - $form->addCommandButton("update", $this->lng->txt("save")); - $form->addCommandButton("cancelUpdate", $this->lng->txt("cancel")); - } - - return $form; - } - - /** - * Create new verification - * @throws ilException - */ - function create() - { - $form = $this->initForm(true); - if($form->checkInput()) { - $option = $form->getInput('certificate_selection'); - - if ('certificate_workspace_option' === $option) { - $type = ilObject::_lookupType($form->getInput("object")); - if($type) { - $this->content_obj = new ilPCVerification($this->getPage()); - $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); - $verificationObjectId = $form->getInput("object"); - - $this->content_obj->setData($type, $verificationObjectId); - - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - } - } elseif ('certificate_persistent_option' === $option) { - $objectId = $form->getInput("persistent_object"); - - $userId = $this->user->getId(); - - $certificateFileService = new ilPortfolioCertificateFileService(); - try { - $certificateFileService->createCertificateFile($userId, $objectId); - } catch (\ILIAS\Filesystem\Exception\FileAlreadyExistsException $e) { - ilUtil::sendInfo($this->lng->txt('certificate_file_not_found_error'), true); - $this->log->warning($e->getMessage()); - } catch (\ILIAS\Filesystem\Exception\IOException $e) { - ilUtil::sendInfo($this->lng->txt('certificate_file_input_output_error'), true); - $this->log->error($e->getMessage()); - return $this->ctrl->redirect($this, 'initForm'); - } catch (ilException $e) { - ilUtil::sendFailure($this->lng->txt('error_creating_certificate_pdf'), true); - $this->log->error($e->getMessage()); - return $this->ctrl->redirect($this, 'initForm'); - } - - $this->content_obj = new ilPCVerification($this->getPage()); - $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); - $this->content_obj->setData('crta', $objectId); - - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - $this->log->info('File could not be created'); - } - } - - $this->insert($form); - } - - /** - * Update verification - */ - function update() - { - $form = $this->initForm(true); - if($form->checkInput()) - { - $option = $form->getInput('certificate_selection'); - if ('certificate_workspace_option' === $option) { - $object = $form->getInput("object"); - $type = ilObject::_lookupType($object); - if($type) { - $oldContentData = $this->content_obj->getData(); - - if ('crta' === $oldContentData['type']) { - $userId = $this->user->getId(); - $oldObjectId = $oldContentData['id']; - - $certificateFileService = new ilPortfolioCertificateFileService(); - try { - $certificateFileService->deleteCertificateFile($userId, $oldObjectId); - } catch (\ILIAS\Filesystem\Exception\FileNotFoundException $e) { - ilUtil::sendInfo($this->lng->txt('certificate_file_not_found_error')); - $this->log->warning($e->getMessage()); - } catch (\ILIAS\Filesystem\Exception\IOException $e) { - ilUtil::sendInfo($this->lng->txt('certificate_file_input_output_error')); - $this->log->warning($e->getMessage()); - } - } - - $this->content_obj->setData($type, $object); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - } - } elseif ('certificate_persistent_option' === $option) { - $oldContentData = $this->content_obj->getData(); - - $objectId = $form->getInput("persistent_object"); - - $certificateFileService = new ilPortfolioCertificateFileService(); - - try { - $userId = $this->user->getId(); - - $certificateFileService->createCertificateFile($userId, $objectId); - if ('crta' === $oldContentData['type']) { - $oldObjectId = $oldContentData['id']; - $certificateFileService->deleteCertificateFile($userId, $oldObjectId); - } - } catch (\ILIAS\Filesystem\Exception\FileNotFoundException $e) { - ilUtil::sendInfo($this->lng->txt('certificate_file_not_found_error'), true); - $this->log->warning($e->getMessage()); - } - catch (\ILIAS\Filesystem\Exception\FileAlreadyExistsException $e) { - ilUtil::sendInfo($this->lng->txt('certificate_file_not_found_error'), true); - $this->log->warning($e->getMessage()); - } catch (\ILIAS\Filesystem\Exception\IOException $e) { - ilUtil::sendInfo($this->lng->txt('certificate_file_input_output_error'), true); - $this->log->warning($e->getMessage()); - } catch (ilException $e) { - ilUtil::sendFailure($this->lng->txt('error_creating_certificate_pdf'), true); - $this->log->error($e->getMessage()); - return $this->ctrl->redirect($this, 'initForm'); - } - - $this->content_obj->setData('crta', $objectId); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - $this->log->info('File could not be created'); - } - } - - $this->pg_obj->addHierIDs(); - $this->edit($form); - } - - private function initStorage(int $objectId, string $subDirectory = '') - { - $storage = new ilVerificationStorageFile($objectId); - $storage->create(); - - $path = $storage->getAbsolutePath()."/"; - - if($subDirectory !== '') { - $path .= $subDirectory."/"; - - if(!is_dir($path)) { - mkdir($path); - } - } - - return $path; - } -} - -?> + +* @version $I$ +* +* @ingroup ServicesCOPage +*/ +class ilPCVerificationGUI extends ilPageContentGUI +{ + /** + * @var ilObjUser + */ + protected $user; + + + /** + * Constructor + * @access public + */ + 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->user = $DIC->user(); + $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 verification form. + * + * @param ilPropertyFormGUI $a_form + */ + public function insert(ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + + $this->displayValidationError(); + + if (!$a_form) { + $a_form = $this->initForm(true); + } + $tpl->setContent($a_form->getHTML()); + } + + /** + * Edit verification form. + * + * @param ilPropertyFormGUI $a_form + */ + public function edit(ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + + $this->displayValidationError(); + + if (!$a_form) { + $a_form = $this->initForm(); + } + $tpl->setContent($a_form->getHTML()); + } + + /** + * Init verification form + * + * @param bool $a_insert + * @return ilPropertyFormGUI + * @throws ilDateTimeException + */ + protected function initForm($a_insert = false) + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + $lng = $this->lng; + + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this)); + if ($a_insert) { + $form->setTitle($this->lng->txt("cont_insert_verification")); + } else { + $form->setTitle($this->lng->txt("cont_update_verification")); + } + + $lng->loadLanguageModule("wsp"); + $workspaceOptions = array(); + + $certificateSource = new ilRadioGroupInputGUI($this->lng->txt('certificate_selection'), 'certificate_selection'); + + $workspaceRadioButton = new ilRadioOption($this->lng->txt('certificate_workspace_option'), 'certificate_workspace_option'); + $persistentRadioButton = new ilRadioOption($this->lng->txt('certificate_persistent_option'), 'certificate_persistent_option'); + + $tree = new ilWorkspaceTree($ilUser->getId()); + $root = $tree->getRootId(); + if ($root) { + $root = $tree->getNodeData($root); + foreach ($tree->getSubTree($root) as $node) { + if (in_array($node["type"], array("excv", "tstv", "crsv", "scov"))) { + $workspaceOptions[$node["obj_id"]] = $node["title"] . " (" . $lng->txt("wsp_type_" . $node["type"]) . ")"; + } + } + asort($workspaceOptions); + } + + $workspaceCertificates = new ilSelectInputGUI($this->lng->txt("cont_verification_object"), "object"); + $workspaceCertificates->setRequired(true); + $workspaceCertificates->setOptions($workspaceOptions); + + $repository = new ilUserCertificateRepository(); + + $certificates = $repository->fetchActiveCertificates($ilUser->getId()); + + $persistentOptions = array(); + foreach ($certificates as $certificate) { + $userCertificate = $certificate->getUserCertificate(); + $dateTime = ilDatePresentation::formatDate(new ilDateTime($userCertificate->getAcquiredTimestamp(), IL_CAL_UNIX)); + + $type = $lng->txt("wsp_type_" . $userCertificate->getObjType() . 'v'); + $additionalInformation = ' (' . $type . ' / ' . $dateTime . ')'; + $persistentOptions[$userCertificate->getObjId()] = $certificate->getObjectTitle() . $additionalInformation; + } + + $persistentObject = new ilSelectInputGUI($this->lng->txt("cont_verification_object"), "persistent_object"); + $persistentObject->setRequired(true); + $persistentObject->setOptions($persistentOptions); + + $persistentRadioButton->addSubItem($persistentObject); + $workspaceRadioButton->addSubItem($workspaceCertificates); + + $certificateSource->addOption($persistentRadioButton); + $certificateSource->addOption($workspaceRadioButton); + + $certificateSource->setValue('certificate_persistent_option'); + + $form->addItem($certificateSource); + + if ($a_insert) { + $form->addCommandButton("create_verification", $this->lng->txt("save")); + $form->addCommandButton("cancelCreate", $this->lng->txt("cancel")); + } else { + $data = $this->content_obj->getData(); + + if ($data['type'] === 'crta') { + $certificateSource->setValue('certificate_persistent_option'); + $persistentObject->setValue($data["id"]); + } else { + $certificateSource->setValue('certificate_workspace_option'); + $workspaceCertificates->setValue($data["id"]); + } + + + $form->addCommandButton("update", $this->lng->txt("save")); + $form->addCommandButton("cancelUpdate", $this->lng->txt("cancel")); + } + + return $form; + } + + /** + * Create new verification + * @throws ilException + */ + public function create() + { + $form = $this->initForm(true); + if ($form->checkInput()) { + $option = $form->getInput('certificate_selection'); + + if ('certificate_workspace_option' === $option) { + $type = ilObject::_lookupType($form->getInput("object")); + if ($type) { + $this->content_obj = new ilPCVerification($this->getPage()); + $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); + $verificationObjectId = $form->getInput("object"); + + $this->content_obj->setData($type, $verificationObjectId); + + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + } + } elseif ('certificate_persistent_option' === $option) { + $objectId = $form->getInput("persistent_object"); + + $userId = $this->user->getId(); + + $certificateFileService = new ilPortfolioCertificateFileService(); + try { + $certificateFileService->createCertificateFile($userId, $objectId); + } catch (\ILIAS\Filesystem\Exception\FileAlreadyExistsException $e) { + ilUtil::sendInfo($this->lng->txt('certificate_file_not_found_error'), true); + $this->log->warning($e->getMessage()); + } catch (\ILIAS\Filesystem\Exception\IOException $e) { + ilUtil::sendInfo($this->lng->txt('certificate_file_input_output_error'), true); + $this->log->error($e->getMessage()); + return $this->ctrl->redirect($this, 'initForm'); + } catch (ilException $e) { + ilUtil::sendFailure($this->lng->txt('error_creating_certificate_pdf'), true); + $this->log->error($e->getMessage()); + return $this->ctrl->redirect($this, 'initForm'); + } + + $this->content_obj = new ilPCVerification($this->getPage()); + $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); + $this->content_obj->setData('crta', $objectId); + + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + $this->log->info('File could not be created'); + } + } + + $this->insert($form); + } + + /** + * Update verification + */ + public function update() + { + $form = $this->initForm(true); + if ($form->checkInput()) { + $option = $form->getInput('certificate_selection'); + if ('certificate_workspace_option' === $option) { + $object = $form->getInput("object"); + $type = ilObject::_lookupType($object); + if ($type) { + $oldContentData = $this->content_obj->getData(); + + if ('crta' === $oldContentData['type']) { + $userId = $this->user->getId(); + $oldObjectId = $oldContentData['id']; + + $certificateFileService = new ilPortfolioCertificateFileService(); + try { + $certificateFileService->deleteCertificateFile($userId, $oldObjectId); + } catch (\ILIAS\Filesystem\Exception\FileNotFoundException $e) { + ilUtil::sendInfo($this->lng->txt('certificate_file_not_found_error')); + $this->log->warning($e->getMessage()); + } catch (\ILIAS\Filesystem\Exception\IOException $e) { + ilUtil::sendInfo($this->lng->txt('certificate_file_input_output_error')); + $this->log->warning($e->getMessage()); + } + } + + $this->content_obj->setData($type, $object); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + } + } elseif ('certificate_persistent_option' === $option) { + $oldContentData = $this->content_obj->getData(); + + $objectId = $form->getInput("persistent_object"); + + $certificateFileService = new ilPortfolioCertificateFileService(); + + try { + $userId = $this->user->getId(); + + $certificateFileService->createCertificateFile($userId, $objectId); + if ('crta' === $oldContentData['type']) { + $oldObjectId = $oldContentData['id']; + $certificateFileService->deleteCertificateFile($userId, $oldObjectId); + } + } catch (\ILIAS\Filesystem\Exception\FileNotFoundException $e) { + ilUtil::sendInfo($this->lng->txt('certificate_file_not_found_error'), true); + $this->log->warning($e->getMessage()); + } catch (\ILIAS\Filesystem\Exception\FileAlreadyExistsException $e) { + ilUtil::sendInfo($this->lng->txt('certificate_file_not_found_error'), true); + $this->log->warning($e->getMessage()); + } catch (\ILIAS\Filesystem\Exception\IOException $e) { + ilUtil::sendInfo($this->lng->txt('certificate_file_input_output_error'), true); + $this->log->warning($e->getMessage()); + } catch (ilException $e) { + ilUtil::sendFailure($this->lng->txt('error_creating_certificate_pdf'), true); + $this->log->error($e->getMessage()); + return $this->ctrl->redirect($this, 'initForm'); + } + + $this->content_obj->setData('crta', $objectId); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + $this->log->info('File could not be created'); + } + } + + $this->pg_obj->addHierIDs(); + $this->edit($form); + } + + private function initStorage(int $objectId, string $subDirectory = '') + { + $storage = new ilVerificationStorageFile($objectId); + $storage->create(); + + $path = $storage->getAbsolutePath() . "/"; + + if ($subDirectory !== '') { + $path .= $subDirectory . "/"; + + if (!is_dir($path)) { + mkdir($path); + } + } + + return $path; + } +} diff --git a/Services/COPage/classes/class.ilPageComponentPlugin.php b/Services/COPage/classes/class.ilPageComponentPlugin.php index c0eca24a15e5cbdca6a11d16ce530ddd246ca831..d6cf6cd2c5328300e0e6cddfa43f26115a120889 100644 --- a/Services/COPage/classes/class.ilPageComponentPlugin.php +++ b/Services/COPage/classes/class.ilPageComponentPlugin.php @@ -14,190 +14,184 @@ include_once("./Services/Component/classes/class.ilPlugin.php"); */ abstract class ilPageComponentPlugin extends ilPlugin { - const TXT_CMD_INSERT = "cmd_insert"; - const CMD_INSERT = "insert"; - const CMD_EDIT = "edit"; + const TXT_CMD_INSERT = "cmd_insert"; + const CMD_INSERT = "insert"; + const CMD_EDIT = "edit"; - /** - * - * @var ilPageObject|null - */ - private $page_obj = null; - - /** - * Get Component Type - * - * @return string Component Type - */ - final function getComponentType() - { - return IL_COMP_SERVICE; - } - - /** - * Get Component Name. - * - * @return string Component Name - */ - final function getComponentName() - { - return "COPage"; - } - - /** - * Get Slot Name. - * - * @return string Slot Name - */ - final function getSlot() - { - return "PageComponent"; - } - - /** - * Get Slot ID. - * - * @return string Slot Id - */ - final function getSlotId() - { - return "pgcp"; - } - - /** - * Object initialization done by slot. - */ - protected final function slotInit() - { - // nothing to do here - } - - /** - * Determines the resources that allow to include the - * new content component. - * - * @param string $a_type Parent type (e.g. "cat", "lm", "glo", "wiki", ...) - * - * @return boolean true/false if the resource type allows - */ - abstract function isValidParentType($a_type); - - /** - * Get Javascript files - */ - function getJavascriptFiles($a_mode) - { - return array(); - } - - /** - * Get css files - */ - function getCssFiles($a_mode) - { - return array(); - } - - /** - * Set Mode. - * - * @param string $a_mode Mode - */ - final function setMode($a_mode) - { - $this->mode = $a_mode; - } + /** + * + * @var ilPageObject|null + */ + private $page_obj = null; + + /** + * Get Component Type + * + * @return string Component Type + */ + final public function getComponentType() + { + return IL_COMP_SERVICE; + } + + /** + * Get Component Name. + * + * @return string Component Name + */ + final public function getComponentName() + { + return "COPage"; + } + + /** + * Get Slot Name. + * + * @return string Slot Name + */ + final public function getSlot() + { + return "PageComponent"; + } + + /** + * Get Slot ID. + * + * @return string Slot Id + */ + final public function getSlotId() + { + return "pgcp"; + } + + /** + * Object initialization done by slot. + */ + final protected function slotInit() + { + // nothing to do here + } + + /** + * Determines the resources that allow to include the + * new content component. + * + * @param string $a_type Parent type (e.g. "cat", "lm", "glo", "wiki", ...) + * + * @return boolean true/false if the resource type allows + */ + abstract public function isValidParentType($a_type); + + /** + * Get Javascript files + */ + public function getJavascriptFiles($a_mode) + { + return array(); + } + + /** + * Get css files + */ + public function getCssFiles($a_mode) + { + return array(); + } + + /** + * Set Mode. + * + * @param string $a_mode Mode + */ + final public function setMode($a_mode) + { + $this->mode = $a_mode; + } - /** - * Get Mode. - * - * @return string Mode - */ - final function getMode() - { - return $this->mode; - } + /** + * Get Mode. + * + * @return string Mode + */ + final public function getMode() + { + return $this->mode; + } - /** - * Get UI plugin class - */ - function getUIClassInstance() - { - $class = "il".$this->getPluginName()."PluginGUI"; - $this->includeClass("class.".$class.".php"); - $obj = new $class(); - $obj->setPlugin($this); - return $obj; - } + /** + * Get UI plugin class + */ + public function getUIClassInstance() + { + $class = "il" . $this->getPluginName() . "PluginGUI"; + $this->includeClass("class." . $class . ".php"); + $obj = new $class(); + $obj->setPlugin($this); + return $obj; + } - /** - * Inject the page object - * This must be public to be called by ilPCPlugged - * But the page object should not directly be accessible by plugins - * @param ilPageObject - */ - public function setPageObj($a_page_obj) - { - $this->page_obj = $a_page_obj; - } + /** + * Inject the page object + * This must be public to be called by ilPCPlugged + * But the page object should not directly be accessible by plugins + * @param ilPageObject + */ + public function setPageObj($a_page_obj) + { + $this->page_obj = $a_page_obj; + } - /** - * Get the id of the page - * @return int - */ - public function getPageId() - { - if (isset($this->page_obj)) - { - return $this->page_obj->getId(); - } - return 0; - } + /** + * Get the id of the page + * @return int + */ + public function getPageId() + { + if (isset($this->page_obj)) { + return $this->page_obj->getId(); + } + return 0; + } - /** - * Get the object id of the parent object - * @return int - */ - public function getParentId() - { - if (isset($this->page_obj)) - { - return $this->page_obj->getParentId(); - } - return 0; + /** + * Get the object id of the parent object + * @return int + */ + public function getParentId() + { + if (isset($this->page_obj)) { + return $this->page_obj->getParentId(); + } + return 0; + } - } + /** + * Get the object type og the parent object + * @return string + */ + public function getParentType() + { + if (isset($this->page_obj)) { + return $this->page_obj->getParentType(); + } + return ''; + } - /** - * Get the object type og the parent object - * @return string - */ - public function getParentType() - { - if (isset($this->page_obj)) - { - return $this->page_obj->getParentType(); - } - return ''; - } - - /** - * This function is called when the page content is cloned - * @param array $a_properties (properties saved in the page, should be modified if neccessary) - * @param string $a_plugin_version (plugin version of the properties) - */ - public function onClone(&$a_properties, $a_plugin_version) - { - } - - /** - * This function is called before the page content is deleted - * @param array $a_properties properties saved in the page (will be deleted afterwards) - * @param string $a_plugin_version plugin version of the properties - */ - public function onDelete($a_properties, $a_plugin_version) - { - } + /** + * This function is called when the page content is cloned + * @param array $a_properties (properties saved in the page, should be modified if neccessary) + * @param string $a_plugin_version (plugin version of the properties) + */ + public function onClone(&$a_properties, $a_plugin_version) + { + } + /** + * This function is called before the page content is deleted + * @param array $a_properties properties saved in the page (will be deleted afterwards) + * @param string $a_plugin_version plugin version of the properties + */ + public function onDelete($a_properties, $a_plugin_version) + { + } } -?> diff --git a/Services/COPage/classes/class.ilPageComponentPluginExporter.php b/Services/COPage/classes/class.ilPageComponentPluginExporter.php index bcb2fef91c01bb6f1cd352beb701b747ec6bedf6..0772a1c564c83e1e15db7b605eef31561f9a0615 100644 --- a/Services/COPage/classes/class.ilPageComponentPluginExporter.php +++ b/Services/COPage/classes/class.ilPageComponentPluginExporter.php @@ -14,81 +14,75 @@ include_once("./Services/Export/classes/class.ilXmlExporter.php"); */ abstract class ilPageComponentPluginExporter extends ilXmlExporter { - /** - * Properties of exportable plugged page contents - * The id has the following format: - * ::: - * This format, however, should be irrelevant to child classes - * - * @var array $pc_properties id => [ name => value, ... ] - */ - protected static $pc_properties = array(); + /** + * Properties of exportable plugged page contents + * The id has the following format: + * ::: + * This format, however, should be irrelevant to child classes + * + * @var array $pc_properties id => [ name => value, ... ] + */ + protected static $pc_properties = array(); - /** - * Plugin versions of exportable plugged page contents - * - * @var array $pc_version id => version - */ - protected static $pc_version = array(); + /** + * Plugin versions of exportable plugged page contents + * + * @var array $pc_version id => version + */ + protected static $pc_version = array(); - /** - * Set the properties of a plugged page content - * This method is used by ilCOPageExporter to provide the properties - * - * @param string $a_id - * @param array $a_properties - */ - public static function setPCProperties($a_id, $a_properties) - { - self::$pc_properties[$a_id] = $a_properties; - } + /** + * Set the properties of a plugged page content + * This method is used by ilCOPageExporter to provide the properties + * + * @param string $a_id + * @param array $a_properties + */ + public static function setPCProperties($a_id, $a_properties) + { + self::$pc_properties[$a_id] = $a_properties; + } - /** - * Get the properties of a plugged page content - * - * @param string $a_id - * @return mixed|null - */ - public static function getPCProperties($a_id) - { - if (isset(self::$pc_properties[$a_id])) - { - return self::$pc_properties[$a_id]; - } - else - { - return null; - } - } + /** + * Get the properties of a plugged page content + * + * @param string $a_id + * @return mixed|null + */ + public static function getPCProperties($a_id) + { + if (isset(self::$pc_properties[$a_id])) { + return self::$pc_properties[$a_id]; + } else { + return null; + } + } - /** - * Set the version of a plugged page content - * This method is used by ilCOPageExporter to provide the version - * - * @param string $a_id - * @param string $a_version - */ - public static function setPCVersion($a_id, $a_version) - { - self::$pc_version[$a_id] = $a_version; - } + /** + * Set the version of a plugged page content + * This method is used by ilCOPageExporter to provide the version + * + * @param string $a_id + * @param string $a_version + */ + public static function setPCVersion($a_id, $a_version) + { + self::$pc_version[$a_id] = $a_version; + } - /** - * Get the version of a plugged page content - * - * @param string $a_id - * @return string|null - */ - public static function getPCVersion($a_id) - { - if (isset(self::$pc_version[$a_id])) - { - return self::$pc_version[$a_id]; - } - else - { - return null; - } - } -} \ No newline at end of file + /** + * Get the version of a plugged page content + * + * @param string $a_id + * @return string|null + */ + public static function getPCVersion($a_id) + { + if (isset(self::$pc_version[$a_id])) { + return self::$pc_version[$a_id]; + } else { + return null; + } + } +} diff --git a/Services/COPage/classes/class.ilPageComponentPluginGUI.php b/Services/COPage/classes/class.ilPageComponentPluginGUI.php index ee19d511449aa154e5e8f5a836523c7c330e26bc..76472680ec15de6656d3846554611ec49dfaef33 100644 --- a/Services/COPage/classes/class.ilPageComponentPluginGUI.php +++ b/Services/COPage/classes/class.ilPageComponentPluginGUI.php @@ -12,169 +12,162 @@ */ abstract class ilPageComponentPluginGUI { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * Constructor - */ - function __construct() - { - global $DIC; + /** + * Constructor + */ + public function __construct() + { + global $DIC; - $this->lng = $DIC->language(); - } + $this->lng = $DIC->language(); + } - protected $plugin; - protected $pc_gui; - protected $pc; - - /** - * Set pc gui object - * - * @param object $a_val pc gui object - */ - function setPCGUI($a_val) - { - $this->pc_gui = $a_val; - } - - /** - * Get pc gui object - * - * @return object pc gui object - */ - function getPCGUI() - { - return $this->pc_gui; - } - - /** - * Set plugin object - * - * @param object $a_val plugin object - */ - function setPlugin($a_val) - { - $this->plugin = $a_val; - } - - /** - * Get plugin object - * - * @return object plugin object - */ - function getPlugin() - { - return $this->plugin; - } - - /** - * Set Mode. - * - * @param string $a_mode Mode - */ - final function setMode($a_mode) - { - $this->mode = $a_mode; - } + protected $plugin; + protected $pc_gui; + protected $pc; + + /** + * Set pc gui object + * + * @param object $a_val pc gui object + */ + public function setPCGUI($a_val) + { + $this->pc_gui = $a_val; + } + + /** + * Get pc gui object + * + * @return object pc gui object + */ + public function getPCGUI() + { + return $this->pc_gui; + } + + /** + * Set plugin object + * + * @param object $a_val plugin object + */ + public function setPlugin($a_val) + { + $this->plugin = $a_val; + } + + /** + * Get plugin object + * + * @return object plugin object + */ + public function getPlugin() + { + return $this->plugin; + } + + /** + * Set Mode. + * + * @param string $a_mode Mode + */ + final public function setMode($a_mode) + { + $this->mode = $a_mode; + } - /** - * Get Mode. - * - * @return string Mode - */ - final function getMode() - { - return $this->mode; - } + /** + * Get Mode. + * + * @return string Mode + */ + final public function getMode() + { + return $this->mode; + } - /** - * Get HTML - * - * @param - * @return - */ - function getHTML() - { - if ($this->getMode() == ilPageComponentPlugin::CMD_INSERT) - { - $this->insert(); - } - else if ($this->getMode() == ilPageComponentPlugin::CMD_EDIT) - { - $this->edit(); - } - - } + /** + * Get HTML + * + * @param + * @return + */ + public function getHTML() + { + if ($this->getMode() == ilPageComponentPlugin::CMD_INSERT) { + $this->insert(); + } elseif ($this->getMode() == ilPageComponentPlugin::CMD_EDIT) { + $this->edit(); + } + } - abstract function executeCommand(); - abstract function insert(); - abstract function edit(); - abstract function create(); - abstract function getElementHTML($a_mode, array $a_properties, $plugin_version); - - function createElement(array $a_properties) - { - return $this->getPCGUI()->createElement($a_properties); - } - - function updateElement(array $a_properties) - { - return $this->getPCGUI()->updateElement($a_properties); - } - - /** - * Return to parent - */ - function returnToParent() - { - $this->getPCGUI()->returnToParent(); - } + abstract public function executeCommand(); + abstract public function insert(); + abstract public function edit(); + abstract public function create(); + abstract public function getElementHTML($a_mode, array $a_properties, $plugin_version); + + public function createElement(array $a_properties) + { + return $this->getPCGUI()->createElement($a_properties); + } + + public function updateElement(array $a_properties) + { + return $this->getPCGUI()->updateElement($a_properties); + } + + /** + * Return to parent + */ + public function returnToParent() + { + $this->getPCGUI()->returnToParent(); + } - /** - * Set properties - * - * @param array $a_val properties array - */ - function setProperties(array $a_val) - { - $co = $this->getPCGUI()->getContentObject(); - if (is_object($co)) - { - $co->setProperties($a_val); - } - } - - /** - * Get properties - * - * @return array properties array - */ - function getProperties() - { - $co = $this->getPCGUI()->getContentObject(); - if (is_object($co)) - { - return $co->getProperties($a_val); - } - return array(); - } + /** + * Set properties + * + * @param array $a_val properties array + */ + public function setProperties(array $a_val) + { + $co = $this->getPCGUI()->getContentObject(); + if (is_object($co)) { + $co->setProperties($a_val); + } + } + + /** + * Get properties + * + * @return array properties array + */ + public function getProperties() + { + $co = $this->getPCGUI()->getContentObject(); + if (is_object($co)) { + return $co->getProperties($a_val); + } + return array(); + } - /** - * Add creation button - * - * @param - * @return - */ - final protected function addCreationButton($a_form) - { - $lng = $this->lng; - - $a_form->addCommandButton("create_plug", $lng->txt("save")); - } + /** + * Add creation button + * + * @param + * @return + */ + final protected function addCreationButton($a_form) + { + $lng = $this->lng; + + $a_form->addCommandButton("create_plug", $lng->txt("save")); + } } -?> diff --git a/Services/COPage/classes/class.ilPageComponentPluginImporter.php b/Services/COPage/classes/class.ilPageComponentPluginImporter.php index edaac8fe5bb23111394b238f2b18aa8f4d59bf85..0984e6a4558aad1fc2ebc22b86c9c32ba6c966e0 100644 --- a/Services/COPage/classes/class.ilPageComponentPluginImporter.php +++ b/Services/COPage/classes/class.ilPageComponentPluginImporter.php @@ -14,100 +14,94 @@ include_once("./Services/Export/classes/class.ilXmlImporter.php"); */ abstract class ilPageComponentPluginImporter extends ilXmlImporter { - /** - * Properties of exportable plugged page contents - * The id has the following format: - * ::: - * This format, however, should be irrelevant to child classes - * - * @var array $pc_properties id => [ name => value, ... ] - */ - protected static $pc_properties = array(); + /** + * Properties of exportable plugged page contents + * The id has the following format: + * ::: + * This format, however, should be irrelevant to child classes + * + * @var array $pc_properties id => [ name => value, ... ] + */ + protected static $pc_properties = array(); - /** - * Plugin versions of exportable plugged page contents - * - * @var array $pc_version id => version - */ - protected static $pc_version = array(); + /** + * Plugin versions of exportable plugged page contents + * + * @var array $pc_version id => version + */ + protected static $pc_version = array(); - /** - * Set the properties of a plugged page content - * This method is used by ilCOPageExporter to provide the properties - * - * @param string $a_id - * @param array $a_properties - */ - public static function setPCProperties($a_id, $a_properties) - { - self::$pc_properties[$a_id] = $a_properties; - } + /** + * Set the properties of a plugged page content + * This method is used by ilCOPageExporter to provide the properties + * + * @param string $a_id + * @param array $a_properties + */ + public static function setPCProperties($a_id, $a_properties) + { + self::$pc_properties[$a_id] = $a_properties; + } - /** - * Get the properties of a plugged page content - * - * @param string $a_id - * @return mixed|null - */ - public static function getPCProperties($a_id) - { - if (isset(self::$pc_properties[$a_id])) - { - return self::$pc_properties[$a_id]; - } - else - { - return null; - } - } + /** + * Get the properties of a plugged page content + * + * @param string $a_id + * @return mixed|null + */ + public static function getPCProperties($a_id) + { + if (isset(self::$pc_properties[$a_id])) { + return self::$pc_properties[$a_id]; + } else { + return null; + } + } - /** - * Set the version of a plugged page content - * This method is used by ilCOPageExporter to provide the version - * - * @param string $a_id - * @param string $a_version - */ - public static function setPCVersion($a_id, $a_version) - { - self::$pc_version[$a_id] = $a_version; - } + /** + * Set the version of a plugged page content + * This method is used by ilCOPageExporter to provide the version + * + * @param string $a_id + * @param string $a_version + */ + public static function setPCVersion($a_id, $a_version) + { + self::$pc_version[$a_id] = $a_version; + } - /** - * Get the version of a plugged page content - * - * @param string $a_id - * @return string|null - */ - public static function getPCVersion($a_id) - { - if (isset(self::$pc_version[$a_id])) - { - return self::$pc_version[$a_id]; - } - else - { - return null; - } - } + /** + * Get the version of a plugged page content + * + * @param string $a_id + * @return string|null + */ + public static function getPCVersion($a_id) + { + if (isset(self::$pc_version[$a_id])) { + return self::$pc_version[$a_id]; + } else { + return null; + } + } - /** - * Get the id of the mapped page content - * The id structure should be irrelevant to child classes - * The mapped ID shold be used both for getPCProperties() and setPCProperties() - * when being called in their importXmlRepresentation() - * - * @param string $a_id - * @param ilImportMapping $a_mapping - */ - public static function getPCMapping($a_id, $a_mapping) - { - $parts = explode(':', $a_id); - $old_page_id = $parts[0].':' .$parts[1]; - $new_page_id = $a_mapping->getMapping("Services/COPage", 'pg', $old_page_id); + /** + * Get the id of the mapped page content + * The id structure should be irrelevant to child classes + * The mapped ID shold be used both for getPCProperties() and setPCProperties() + * when being called in their importXmlRepresentation() + * + * @param string $a_id + * @param ilImportMapping $a_mapping + */ + public static function getPCMapping($a_id, $a_mapping) + { + $parts = explode(':', $a_id); + $old_page_id = $parts[0] . ':' . $parts[1]; + $new_page_id = $a_mapping->getMapping("Services/COPage", 'pg', $old_page_id); - return $new_page_id . ':' . $parts[2] . ':' . $parts[3]; - } -} \ No newline at end of file + return $new_page_id . ':' . $parts[2] . ':' . $parts[3]; + } +} diff --git a/Services/COPage/classes/class.ilPageConfig.php b/Services/COPage/classes/class.ilPageConfig.php index 0d7aa4a3a4a2fea8f2092a11153258a169b50086..c8aebc2910ec65c3627585941d73f4edb3844e3c 100644 --- a/Services/COPage/classes/class.ilPageConfig.php +++ b/Services/COPage/classes/class.ilPageConfig.php @@ -11,620 +11,608 @@ */ abstract class ilPageConfig { - /** - * @var ilLanguage - */ - protected $lng; - - protected $int_link_filter = array("File", "PortfolioPage", "PortfolioTemplatePage"); - protected $prevent_rte_usage = false; - protected $use_attached_content = false; - protected $pc_defs = array(); - protected $pc_enabled = array(); - protected $enabledinternallinks = false; - protected $enable_keywords = false; - protected $enable_anchors = false; - protected $enablewikilinks = false; - protected $page_toc = false; - protected $activation = false; - protected $scheduled_activation = false; - protected $preventhtmlunmasking = false; - protected $enabledselfassessment = false; - protected $enabledselfassessment_scorm = false; - protected $int_link_def_type = ""; - protected $int_link_def_id = 0; - protected $multi_lang_support = false; - protected $single_page_mode = false; // currently only used by multi-lang support - // single page means: only one page per parent_id - protected $disable_default_qfeedback = false; - protected $question_html = array(); - protected $use_stored_tries = false; - protected $enable_user_links = false; - - protected $edit_lock_support = true; - - /** - * @var bool - */ - protected $enable_permission_checks = false; - - /** - * Constructor - * - * @param - * @return - */ - final public function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - // load pc_defs - include_once("./Services/COPage/classes/class.ilCOPagePCDef.php"); - $this->pc_defs = ilCOPagePCDef::getPCDefinitions(); - foreach ($this->pc_defs as $def) - { - $this->setEnablePCType($def["name"], (bool) $def["def_enabled"]); - } - - $this->init(); - } - - /** - * Init - * - * @param - * @return - */ - function init() - { - } - - - /** - * Set enable pc type - * - * @param boolean $a_val enable pc type true/false - */ - function setEnablePCType($a_pc_type, $a_val) - { - $this->pc_enabled[$a_pc_type] = $a_val; - } - - /** - * Get enable pc type - * - * @return boolean enable pc type true/false - */ - function getEnablePCType($a_pc_type) - { - return $this->pc_enabled[$a_pc_type]; - } - - /** - * Set enable keywords handling - * - * @param boolean keywords handling - */ - function setEnableKeywords($a_val) - { - $this->enable_keywords = $a_val; - } - - /** - * Get enable keywords handling - * - * @return boolean keywords handling - */ - function getEnableKeywords() - { - return $this->enable_keywords; - } - - /** - * Set enable anchors - * - * @param boolean anchors - */ - function setEnableAnchors($a_val) - { - $this->enable_anchors = $a_val; - } - - /** - * Get enable anchors - * - * @return boolean anchors - */ - function getEnableAnchors() - { - return $this->enable_anchors; - } - - /** - * Set Enable internal links. - * - * @param boolean $a_enabledinternallinks Enable internal links - */ - function setEnableInternalLinks($a_enabledinternallinks) - { - $this->enabledinternallinks = $a_enabledinternallinks; - } - - /** - * Get Enable internal links. - * - * @return boolean Enable internal links - */ - function getEnableInternalLinks() - { - return $this->enabledinternallinks; - } - - /** - * Get enable user links - * - * @return boolean enable user links - */ - function getEnableUserLinks() - { - if (!$this->getEnableInternalLinks()) - { - return false; - } - if ($this->getIntLinkFilterWhiteList() && in_array("User", $this->int_link_filter)) - { - return true; - } - if (!$this->getIntLinkFilterWhiteList() && !in_array("User", $this->int_link_filter)) - { - return true; - } - - return false; - } - - /** - * Set Enable Wiki Links. - * - * @param boolean $a_enablewikilinks Enable Wiki Links - */ - function setEnableWikiLinks($a_enablewikilinks) - { - $this->enablewikilinks = $a_enablewikilinks; - } - - /** - * Get Enable Wiki Links. - * - * @return boolean Enable Wiki Links - */ - function getEnableWikiLinks() - { - return $this->enablewikilinks; - } - - /** - * Add internal links filter - * - * @param string internal links filter - */ - function addIntLinkFilter($a_val) - { - $lng = $this->lng; - - $this->setLocalizationLanguage($lng->getLangKey()); - if (is_array($a_val)) - { - $this->int_link_filter = - array_merge($a_val, $this->int_link_filter); - } - else - { - $this->int_link_filter[] = $a_val; - } - } - - /** - * Remove int link filter - * - * @param string $a_val internal link filter - */ - function removeIntLinkFilter($a_val) - { - foreach ($this->int_link_filter as $k => $v) - { - if ($v == $a_val) - { - unset($this->int_link_filter[$k]); - } - } - } - - - /** - * Get internal links filter - * - * @return string internal links filter - */ - function getIntLinkFilters() - { - return $this->int_link_filter; - } - - /** - * Set internal links filter type list to white list - * - * @param boolean white list - */ - function setIntLinkFilterWhiteList($a_white_list) - { - $this->link_filter_white_list = $a_white_list; - if ($a_white_list) - { - $this->int_link_filter = array(); - } - } - - /** - * Get internal links filter type list to white list - * - * @return boolean white list - */ - function getIntLinkFilterWhiteList() - { - return $this->link_filter_white_list; - } - - /** - * Set prevent rte usage - * - * @param boolean prevent rte usage - */ - function setPreventRteUsage($a_val) - { - $this->prevent_rte_usage = $a_val; - } - - /** - * Get prevent rte usage - * - * @return boolean prevent rte usage - */ - function getPreventRteUsage() - { - return $this->prevent_rte_usage; - } - - /** - * Set localizazion language - * - * @param string $a_val lang key - */ - function setLocalizationLanguage($a_val) - { - $this->localization_lang = $a_val; - } - - /** - * Get localizazion language - * - * @return string lang key - */ - function getLocalizationLanguage() - { - return $this->localization_lang; - } - - /** - * Set use attached content - * - * @param string $a_val use initial attached content - */ - function setUseAttachedContent($a_val) - { - $this->use_attached_content = $a_val; - } - - /** - * Get use attached content - * - * @return string use initial attached content - */ - function getUseAttachedContent() - { - return $this->use_attached_content; - } - - /** - * Set internal link default type - * - * @param string $a_val type - */ - function setIntLinkHelpDefaultType($a_val) - { - $this->int_link_def_type = $a_val; - } - - /** - * Get internal link default type - * - * @return string type - */ - function getIntLinkHelpDefaultType() - { - return $this->int_link_def_type; - } - - /** - * Set internal link default id - * - * @param int $a_val default object if - */ - function setIntLinkHelpDefaultId($a_val, $a_is_ref = true) - { - $this->int_link_def_id = $a_val; - $this->int_link_def_id_is_ref = $a_is_ref; - } - - /** - * Get internal link default id - * - * @return int default object if - */ - function getIntLinkHelpDefaultId() - { - return $this->int_link_def_id; - } - - /** - * Get internal link default id - * - * @return int default object if - */ - function getIntLinkHelpDefaultIdIsRef() - { - return $this->int_link_def_id_is_ref; - } - - /** - * Set enabled actication - * - * @param bool $a_val page activation enabled? - */ - function setEnableActivation($a_val) - { - $this->activation = $a_val; - } - - /** - * Get enabled actication - * - * @return bool page activation enabled? - */ - function getEnableActivation() - { - return $this->activation; - } - - /** - * Set enable scheduled page activation - * - * @param bool $a_val scheduled activated enabled? - */ - function setEnableScheduledActivation($a_val) - { - $this->scheduled_activation = $a_val; - } - - /** - * Get enable scheduled page activation - * - * @return bool scheduled activated enabled? - */ - function getEnableScheduledActivation() - { - return $this->scheduled_activation; - } - - /** - * Set enable page toc - * - * @param bool $a_val enable page toc? - */ - function setEnablePageToc($a_val) - { - $this->page_toc = $a_val; - } - - /** - * Get enable page toc - * - * @return bool enable page toc? - */ - function getEnablePageToc() - { - return $this->page_toc; - } - - /** - * Set Prevent HTML Unmasking (true/false). - * - * @param boolean $a_preventhtmlunmasking Prevent HTML Unmasking (true/false) - */ - function setPreventHTMLUnmasking($a_preventhtmlunmasking) - { - $this->preventhtmlunmasking = $a_preventhtmlunmasking; - } - - /** - * Get Prevent HTML Unmasking (true/false). - * - * @return boolean Prevent HTML Unmasking (true/false) - */ - function getPreventHTMLUnmasking() - { - return $this->preventhtmlunmasking; - } - - /** - * Set Enable Self Assessment Questions. - * - * @param boolean $a_enabledselfassessment Enable Self Assessment Questions - */ - function setEnableSelfAssessment($a_enabledselfassessment, $a_scorm = true) - { - $this->setEnablePCType("Question", (bool) $a_enabledselfassessment); - $this->enabledselfassessment = $a_enabledselfassessment; - $this->enabledselfassessment_scorm = $a_scorm; - } - - - /** - * Get Enable Self Assessment Questions. - * - * @return boolean Enable Self Assessment Questions - */ - function getEnableSelfAssessment() - { - return $this->enabledselfassessment; - } - - /** - * Is self assessment used in SCORM mode? - * - * @return boolean Enable Self Assessment Questions - */ - function getEnableSelfAssessmentScorm() - { - return $this->enabledselfassessment_scorm; - } - - /** - * Set disable default question feedback - * - * @param bool $a_val disable feedback - */ - function setDisableDefaultQuestionFeedback($a_val) - { - $this->disable_default_qfeedback = $a_val; - } - - /** - * Get disable default question feedback - * - * @return bool disable feedback - */ - function getDisableDefaultQuestionFeedback() - { - return $this->disable_default_qfeedback; - } - - /** - * Set multi language support - * - * @param bool $a_val general multi language support? - */ - function setMultiLangSupport($a_val) - { - $this->multi_lang_support = $a_val; - } - - /** - * Get multi language support - * - * @return bool general multi language support? - */ - function getMultiLangSupport() - { - return $this->multi_lang_support; - } - - /** - * Set single page mode - * - * @param bool $a_val single page mode (only one page per parent_id) - */ - function setSinglePageMode($a_val) - { - $this->single_page_mode = $a_val; - } - - /** - * Get single page mode - * - * @return bool single page mode (only one page per parent_id) - */ - function getSinglePageMode() - { - return $this->single_page_mode; - } - - function setQuestionHTML($question_html) - { - $this->question_html = $question_html; - } - - function getQuestionHTML() - { - return $this->question_html; - } - - /** - * Set use stored answers/tries - * - * @param bool $a_val use stored number of tries and given (correct) answers - */ - function setUseStoredQuestionTries($a_val) - { - $this->use_stored_tries = $a_val; - } - - /** - * Get use stored answers/tries - * - * @return bool use stored number of tries and given (correct) answers - */ - function getUseStoredQuestionTries() - { - return $this->use_stored_tries; - } - - /** - * Set enable permission checks - * - * @param bool $a_val enable permission checks - */ - function setEnablePermissionChecks($a_val) - { - $this->enable_permission_checks = $a_val; - } - - /** - * Get enable permission checks - * - * @return bool enable permission checks - */ - function getEnablePermissionChecks() - { - return $this->enable_permission_checks; - } - - /** - * @param $a_val bool set edit lock support for blogs - */ - function setEditLockSupport($a_val) - { - $this->edit_lock_support = $a_val; - } - - /** - * @return bool get edit lock support for blogs - */ - function getEditLockSupport() - { - return $this->edit_lock_support; - } - + /** + * @var ilLanguage + */ + protected $lng; + + protected $int_link_filter = array("File", "PortfolioPage", "PortfolioTemplatePage"); + protected $prevent_rte_usage = false; + protected $use_attached_content = false; + protected $pc_defs = array(); + protected $pc_enabled = array(); + protected $enabledinternallinks = false; + protected $enable_keywords = false; + protected $enable_anchors = false; + protected $enablewikilinks = false; + protected $page_toc = false; + protected $activation = false; + protected $scheduled_activation = false; + protected $preventhtmlunmasking = false; + protected $enabledselfassessment = false; + protected $enabledselfassessment_scorm = false; + protected $int_link_def_type = ""; + protected $int_link_def_id = 0; + protected $multi_lang_support = false; + protected $single_page_mode = false; // currently only used by multi-lang support + // single page means: only one page per parent_id + protected $disable_default_qfeedback = false; + protected $question_html = array(); + protected $use_stored_tries = false; + protected $enable_user_links = false; + + protected $edit_lock_support = true; + + /** + * @var bool + */ + protected $enable_permission_checks = false; + + /** + * Constructor + * + * @param + * @return + */ + final public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + // load pc_defs + include_once("./Services/COPage/classes/class.ilCOPagePCDef.php"); + $this->pc_defs = ilCOPagePCDef::getPCDefinitions(); + foreach ($this->pc_defs as $def) { + $this->setEnablePCType($def["name"], (bool) $def["def_enabled"]); + } + + $this->init(); + } + + /** + * Init + * + * @param + * @return + */ + public function init() + { + } + + + /** + * Set enable pc type + * + * @param boolean $a_val enable pc type true/false + */ + public function setEnablePCType($a_pc_type, $a_val) + { + $this->pc_enabled[$a_pc_type] = $a_val; + } + + /** + * Get enable pc type + * + * @return boolean enable pc type true/false + */ + public function getEnablePCType($a_pc_type) + { + return $this->pc_enabled[$a_pc_type]; + } + + /** + * Set enable keywords handling + * + * @param boolean keywords handling + */ + public function setEnableKeywords($a_val) + { + $this->enable_keywords = $a_val; + } + + /** + * Get enable keywords handling + * + * @return boolean keywords handling + */ + public function getEnableKeywords() + { + return $this->enable_keywords; + } + + /** + * Set enable anchors + * + * @param boolean anchors + */ + public function setEnableAnchors($a_val) + { + $this->enable_anchors = $a_val; + } + + /** + * Get enable anchors + * + * @return boolean anchors + */ + public function getEnableAnchors() + { + return $this->enable_anchors; + } + + /** + * Set Enable internal links. + * + * @param boolean $a_enabledinternallinks Enable internal links + */ + public function setEnableInternalLinks($a_enabledinternallinks) + { + $this->enabledinternallinks = $a_enabledinternallinks; + } + + /** + * Get Enable internal links. + * + * @return boolean Enable internal links + */ + public function getEnableInternalLinks() + { + return $this->enabledinternallinks; + } + + /** + * Get enable user links + * + * @return boolean enable user links + */ + public function getEnableUserLinks() + { + if (!$this->getEnableInternalLinks()) { + return false; + } + if ($this->getIntLinkFilterWhiteList() && in_array("User", $this->int_link_filter)) { + return true; + } + if (!$this->getIntLinkFilterWhiteList() && !in_array("User", $this->int_link_filter)) { + return true; + } + + return false; + } + + /** + * Set Enable Wiki Links. + * + * @param boolean $a_enablewikilinks Enable Wiki Links + */ + public function setEnableWikiLinks($a_enablewikilinks) + { + $this->enablewikilinks = $a_enablewikilinks; + } + + /** + * Get Enable Wiki Links. + * + * @return boolean Enable Wiki Links + */ + public function getEnableWikiLinks() + { + return $this->enablewikilinks; + } + + /** + * Add internal links filter + * + * @param string internal links filter + */ + public function addIntLinkFilter($a_val) + { + $lng = $this->lng; + + $this->setLocalizationLanguage($lng->getLangKey()); + if (is_array($a_val)) { + $this->int_link_filter = + array_merge($a_val, $this->int_link_filter); + } else { + $this->int_link_filter[] = $a_val; + } + } + + /** + * Remove int link filter + * + * @param string $a_val internal link filter + */ + public function removeIntLinkFilter($a_val) + { + foreach ($this->int_link_filter as $k => $v) { + if ($v == $a_val) { + unset($this->int_link_filter[$k]); + } + } + } + + + /** + * Get internal links filter + * + * @return string internal links filter + */ + public function getIntLinkFilters() + { + return $this->int_link_filter; + } + + /** + * Set internal links filter type list to white list + * + * @param boolean white list + */ + public function setIntLinkFilterWhiteList($a_white_list) + { + $this->link_filter_white_list = $a_white_list; + if ($a_white_list) { + $this->int_link_filter = array(); + } + } + + /** + * Get internal links filter type list to white list + * + * @return boolean white list + */ + public function getIntLinkFilterWhiteList() + { + return $this->link_filter_white_list; + } + + /** + * Set prevent rte usage + * + * @param boolean prevent rte usage + */ + public function setPreventRteUsage($a_val) + { + $this->prevent_rte_usage = $a_val; + } + + /** + * Get prevent rte usage + * + * @return boolean prevent rte usage + */ + public function getPreventRteUsage() + { + return $this->prevent_rte_usage; + } + + /** + * Set localizazion language + * + * @param string $a_val lang key + */ + public function setLocalizationLanguage($a_val) + { + $this->localization_lang = $a_val; + } + + /** + * Get localizazion language + * + * @return string lang key + */ + public function getLocalizationLanguage() + { + return $this->localization_lang; + } + + /** + * Set use attached content + * + * @param string $a_val use initial attached content + */ + public function setUseAttachedContent($a_val) + { + $this->use_attached_content = $a_val; + } + + /** + * Get use attached content + * + * @return string use initial attached content + */ + public function getUseAttachedContent() + { + return $this->use_attached_content; + } + + /** + * Set internal link default type + * + * @param string $a_val type + */ + public function setIntLinkHelpDefaultType($a_val) + { + $this->int_link_def_type = $a_val; + } + + /** + * Get internal link default type + * + * @return string type + */ + public function getIntLinkHelpDefaultType() + { + return $this->int_link_def_type; + } + + /** + * Set internal link default id + * + * @param int $a_val default object if + */ + public function setIntLinkHelpDefaultId($a_val, $a_is_ref = true) + { + $this->int_link_def_id = $a_val; + $this->int_link_def_id_is_ref = $a_is_ref; + } + + /** + * Get internal link default id + * + * @return int default object if + */ + public function getIntLinkHelpDefaultId() + { + return $this->int_link_def_id; + } + + /** + * Get internal link default id + * + * @return int default object if + */ + public function getIntLinkHelpDefaultIdIsRef() + { + return $this->int_link_def_id_is_ref; + } + + /** + * Set enabled actication + * + * @param bool $a_val page activation enabled? + */ + public function setEnableActivation($a_val) + { + $this->activation = $a_val; + } + + /** + * Get enabled actication + * + * @return bool page activation enabled? + */ + public function getEnableActivation() + { + return $this->activation; + } + + /** + * Set enable scheduled page activation + * + * @param bool $a_val scheduled activated enabled? + */ + public function setEnableScheduledActivation($a_val) + { + $this->scheduled_activation = $a_val; + } + + /** + * Get enable scheduled page activation + * + * @return bool scheduled activated enabled? + */ + public function getEnableScheduledActivation() + { + return $this->scheduled_activation; + } + + /** + * Set enable page toc + * + * @param bool $a_val enable page toc? + */ + public function setEnablePageToc($a_val) + { + $this->page_toc = $a_val; + } + + /** + * Get enable page toc + * + * @return bool enable page toc? + */ + public function getEnablePageToc() + { + return $this->page_toc; + } + + /** + * Set Prevent HTML Unmasking (true/false). + * + * @param boolean $a_preventhtmlunmasking Prevent HTML Unmasking (true/false) + */ + public function setPreventHTMLUnmasking($a_preventhtmlunmasking) + { + $this->preventhtmlunmasking = $a_preventhtmlunmasking; + } + + /** + * Get Prevent HTML Unmasking (true/false). + * + * @return boolean Prevent HTML Unmasking (true/false) + */ + public function getPreventHTMLUnmasking() + { + return $this->preventhtmlunmasking; + } + + /** + * Set Enable Self Assessment Questions. + * + * @param boolean $a_enabledselfassessment Enable Self Assessment Questions + */ + public function setEnableSelfAssessment($a_enabledselfassessment, $a_scorm = true) + { + $this->setEnablePCType("Question", (bool) $a_enabledselfassessment); + $this->enabledselfassessment = $a_enabledselfassessment; + $this->enabledselfassessment_scorm = $a_scorm; + } + + + /** + * Get Enable Self Assessment Questions. + * + * @return boolean Enable Self Assessment Questions + */ + public function getEnableSelfAssessment() + { + return $this->enabledselfassessment; + } + + /** + * Is self assessment used in SCORM mode? + * + * @return boolean Enable Self Assessment Questions + */ + public function getEnableSelfAssessmentScorm() + { + return $this->enabledselfassessment_scorm; + } + + /** + * Set disable default question feedback + * + * @param bool $a_val disable feedback + */ + public function setDisableDefaultQuestionFeedback($a_val) + { + $this->disable_default_qfeedback = $a_val; + } + + /** + * Get disable default question feedback + * + * @return bool disable feedback + */ + public function getDisableDefaultQuestionFeedback() + { + return $this->disable_default_qfeedback; + } + + /** + * Set multi language support + * + * @param bool $a_val general multi language support? + */ + public function setMultiLangSupport($a_val) + { + $this->multi_lang_support = $a_val; + } + + /** + * Get multi language support + * + * @return bool general multi language support? + */ + public function getMultiLangSupport() + { + return $this->multi_lang_support; + } + + /** + * Set single page mode + * + * @param bool $a_val single page mode (only one page per parent_id) + */ + public function setSinglePageMode($a_val) + { + $this->single_page_mode = $a_val; + } + + /** + * Get single page mode + * + * @return bool single page mode (only one page per parent_id) + */ + public function getSinglePageMode() + { + return $this->single_page_mode; + } + + public function setQuestionHTML($question_html) + { + $this->question_html = $question_html; + } + + public function getQuestionHTML() + { + return $this->question_html; + } + + /** + * Set use stored answers/tries + * + * @param bool $a_val use stored number of tries and given (correct) answers + */ + public function setUseStoredQuestionTries($a_val) + { + $this->use_stored_tries = $a_val; + } + + /** + * Get use stored answers/tries + * + * @return bool use stored number of tries and given (correct) answers + */ + public function getUseStoredQuestionTries() + { + return $this->use_stored_tries; + } + + /** + * Set enable permission checks + * + * @param bool $a_val enable permission checks + */ + public function setEnablePermissionChecks($a_val) + { + $this->enable_permission_checks = $a_val; + } + + /** + * Get enable permission checks + * + * @return bool enable permission checks + */ + public function getEnablePermissionChecks() + { + return $this->enable_permission_checks; + } + + /** + * @param $a_val bool set edit lock support for blogs + */ + public function setEditLockSupport($a_val) + { + $this->edit_lock_support = $a_val; + } + + /** + * @return bool get edit lock support for blogs + */ + public function getEditLockSupport() + { + return $this->edit_lock_support; + } } -?> \ No newline at end of file diff --git a/Services/COPage/classes/class.ilPageContent.php b/Services/COPage/classes/class.ilPageContent.php index 87d31082e84dd18198f2beddeb4c9a045efdba08..1ae4f8c92ebb5cb4c42a096ca326d06e96d27e29 100755 --- a/Services/COPage/classes/class.ilPageContent.php +++ b/Services/COPage/classes/class.ilPageContent.php @@ -16,499 +16,481 @@ */ abstract class ilPageContent { - //var $type; // type - var $hier_id; // hierarchical editing id - var $node; // node in page xml - var $dom; // dom object - var $page_lang; - - /** - * @var string needed for post processing (e.g. content includes) - */ - protected $file_download_link; - - /** - * @var string needed for post processing (e.g. content includes) - */ - protected $fullscreen_link; - - /** - * @var string needed for post processing (e.g. content includes) - */ - protected $sourcecode_download_script; - - /** - * @var ilLogger - */ - protected $log; - - /** - * Constructor. - * - * All initialisation in derived classes should go to the - * init() function - */ - final function __construct($a_pg_obj) - { - $this->log = ilLoggerFactory::getLogger('copg'); - $this->setPage($a_pg_obj); - $this->dom = $a_pg_obj->getDom(); - $this->init(); - if ($this->getType() == "") - { - die ("Error: ilPageContent::init() did not set type"); - } - } - - /** - * Set page - * - * @param object $a_val page object - */ - function setPage($a_val) - { - $this->pg_obj = $a_val; - } - - /** - * Get page - * - * @return object page object - */ - function getPage() - { - return $this->pg_obj; - } - - /** - * Init object. This function must be overwritten and at least set - * the content type. - */ - abstract function init(); - - /** - * Set Type. Must be called in constructor. - * - * @param string $a_type type of page content component - */ - final protected function setType($a_type) - { - $this->type = $a_type; - } - - /** - * Get type of page content - * - * @return string Type as defined by the page content component - */ - function getType() - { - return $this->type; - } - - /** - * Set xml node of page content. - * - * @param object $a_node node object - */ - function setNode($a_node) - { - $this->node = $a_node; - } - - - /** - * Get xml node of page content. - * - * @return object node object - */ - function &getNode() - { - return $this->node; - } - - /** - * Get Javascript files - */ - function getJavascriptFiles($a_mode) - { - return array(); - } - - /** - * Get css files - */ - function getCssFiles($a_mode) - { - return array(); - } - - /** - * Get on load code - */ - function getOnloadCode($a_mode) - { - return array(); - } - - /** - * Set hierarchical ID in xml structure - * - * @param string $a_hier_id Hierarchical ID. - */ - function setHierId($a_hier_id) - { - $this->hier_id = $a_hier_id; - } - - /** - * Get hierarchical id - */ - function getHierId() - { - return $this->hier_id; - } - - - /** - * Get hierarchical id from dom - */ - function lookupHierId() - { - return $this->node->get_attribute("HierId"); - } - - /** - * Read PC Id. - * - * @return string PC Id - */ - function readHierId() - { - if (is_object($this->node)) - { - return $this->node->get_attribute("HierId"); - } - } - - /** - * Set PC Id. - * - * @param string $a_pcid PC Id - */ - function setPcId($a_pcid) - { - $this->pcid = $a_pcid; - } - - /** - * Get PC Id. - * - * @return string PC Id - */ - function getPCId() - { - return $this->pcid; - } - - /** - * Set file download link - * - * @param string $a_download_link download link - */ - function setFileDownloadLink($a_download_link) - { - $this->file_download_link = $a_download_link; - } - - /** - * Get file download link - * - * @return string - */ - function getFileDownloadLink() - { - return $this->file_download_link; - } - - /** - * Set fullscreen link - * - * @param string $a_download_link download link - */ - function setFullscreenLink($a_fullscreen_link) - { - $this->fullscreen_link = $a_fullscreen_link; - } - - /** - * Get fullscreen link - * - * @return string - */ - function getFullscreenLink() - { - return $this->fullscreen_link; - } - - /** - * Set sourcecode download script - * - * @param string $script_name - */ - function setSourcecodeDownloadScript ($script_name) - { - $this->sourcecode_download_script = $script_name; - } - - /** - * Get sourcecode download script - * - * @return string - */ - function getSourcecodeDownloadScript () - { - return $this->sourcecode_download_script; - } - - - /** - * Read PC Id. - * - * @return string PC Id - */ - function readPCId() - { - if (is_object($this->node)) - { - return $this->node->get_attribute("PCID"); - } - } - - /** - * Write pc id - */ - function writePCId($a_pc_id) - { - if (is_object($this->node)) - { - $this->node->set_attribute("PCID", $a_pc_id); - } - } - - /** - * Increases an hierarchical editing id at lowest level (last number) - * - * @param string $ed_id hierarchical ID - * - * @return string hierarchical ID (increased) - */ - final static function incEdId($ed_id) - { - $id = explode("_", $ed_id); - $id[count($id) - 1]++; - - return implode($id, "_"); - } - - /** - * Decreases an hierarchical editing id at lowest level (last number) - * - * @param string $ed_id hierarchical ID - * - * @return string hierarchical ID (decreased) - */ - final static function decEdId($ed_id) - { - $id = explode("_", $ed_id); - $id[count($id) - 1]--; - - return implode($id, "_"); - } - - /** - * Check, if two ids are in same container. - * - * @param string $ed_id1 hierachical ID 1 - * @param string $ed_id2 hierachical ID 2 - * - * @return boolean true/false - */ - final static function haveSameContainer($ed_id1, $ed_id2) - { - $id1 = explode("_", $ed_id1); - $id2 = explode("_", $ed_id1); - if(count($id1) == count($id2)) - { - array_pop($id1); - array_pop($id2); - foreach ($id1 as $key => $id) - { - if($id != $id2[$key]) - { - return false; - } - } - return true; - } - return false; - } - - /** - * Sort an array of Hier IDS in ascending order - */ - static function sortHierIds($a_array) - { - uasort($a_array, array("ilPageContent", "isGreaterHierId")); - - return $a_array; - } - - /** - * Check whether Hier ID $a is greater than Hier ID $b - */ - static function isGreaterHierId($a, $b) - { - $a_arr = explode("_", $a); - $b_arr = explode("_", $b); - for ($i = 0; $i < count($a_arr); $i++) - { - if ((int) $a_arr[$i] > (int) $b_arr[$i]) - { - return true; - } - else if ((int) $a_arr[$i] < (int) $b_arr[$i]) - { - return false; - } - } - return false; - } - - /** - * Set Enabled value for page content component. - * - * @param string $value "True" | "False" - * - */ - function setEnabled($value) - { - if (is_object($this->node)) - { - $this->node->set_attribute("Enabled", $value); - } - } - - /** - * Enable page content. - */ - function enable() - { - $this->setEnabled("True"); - } - - /** - * Disable page content. - */ - function disable() - { - $this->setEnabled("False"); - } - - /** - * Check whether page content is enabled. - * - * @return boolean true/false - */ - final function isEnabled() - { - if (is_object($this->node) && $this->node->has_attribute("Enabled")) - { - $compare = $this->node->get_attribute("Enabled"); - } - else - { - $compare = "True"; - } - - return strcasecmp($compare,"true") == 0; - } - - /** - * Create page content node (always use this method first when adding a new element) - */ - function createPageContentNode($a_set_this_node = true) - { - $node = $this->dom->create_element("PageContent"); - if ($a_set_this_node) - { - $this->node = $node; - } - return $node; - } - - /** - * Get lang vars needed for editing - * @return array array of lang var keys - */ - static function getLangVars() - { - return array(); - } - - /** - * Handle copied content. This function must, e.g. create copies of - * objects referenced within the content (e.g. question objects) - * - * @param DOMDocument $a_domdoc dom document - */ - static function handleCopiedContent(DOMDocument $a_domdoc, $a_self_ass = true, $a_clone_mobs = false) - { - } - - /** - * Modify page content after xsl - * - * @param string $a_output - * @return string - */ - function modifyPageContentPostXsl($a_output, $a_mode) - { - return $a_output; - } - - /** - * After page has been updated (or created) - * - * @param object $a_page page object - * @param DOMDocument $a_domdoc dom document - * @param string $a_xml xml - * @param bool $a_creation true on creation, otherwise false - */ - static function afterPageUpdate($a_page, DOMDocument $a_domdoc, $a_xml, $a_creation) - { - } - - /** - * Before page is being deleted - * - * @param object $a_page page object - */ - static function beforePageDelete($a_page) - { - } - - /** - * After page history entry has been created - * - * @param object $a_page page object - * @param DOMDocument $a_old_domdoc old dom document - * @param string $a_old_xml old xml - * @param integer $a_old_nr history number - */ - static function afterPageHistoryEntry($a_page, DOMDocument $a_old_domdoc, $a_old_xml, $a_old_nr) - { - } - + //var $type; // type + public $hier_id; // hierarchical editing id + public $node; // node in page xml + public $dom; // dom object + public $page_lang; + + /** + * @var string needed for post processing (e.g. content includes) + */ + protected $file_download_link; + + /** + * @var string needed for post processing (e.g. content includes) + */ + protected $fullscreen_link; + + /** + * @var string needed for post processing (e.g. content includes) + */ + protected $sourcecode_download_script; + + /** + * @var ilLogger + */ + protected $log; + + /** + * Constructor. + * + * All initialisation in derived classes should go to the + * init() function + */ + final public function __construct($a_pg_obj) + { + $this->log = ilLoggerFactory::getLogger('copg'); + $this->setPage($a_pg_obj); + $this->dom = $a_pg_obj->getDom(); + $this->init(); + if ($this->getType() == "") { + die("Error: ilPageContent::init() did not set type"); + } + } + + /** + * Set page + * + * @param object $a_val page object + */ + public function setPage($a_val) + { + $this->pg_obj = $a_val; + } + + /** + * Get page + * + * @return object page object + */ + public function getPage() + { + return $this->pg_obj; + } + + /** + * Init object. This function must be overwritten and at least set + * the content type. + */ + abstract public function init(); + + /** + * Set Type. Must be called in constructor. + * + * @param string $a_type type of page content component + */ + final protected function setType($a_type) + { + $this->type = $a_type; + } + + /** + * Get type of page content + * + * @return string Type as defined by the page content component + */ + public function getType() + { + return $this->type; + } + + /** + * Set xml node of page content. + * + * @param object $a_node node object + */ + public function setNode($a_node) + { + $this->node = $a_node; + } + + + /** + * Get xml node of page content. + * + * @return object node object + */ + public function &getNode() + { + return $this->node; + } + + /** + * Get Javascript files + */ + public function getJavascriptFiles($a_mode) + { + return array(); + } + + /** + * Get css files + */ + public function getCssFiles($a_mode) + { + return array(); + } + + /** + * Get on load code + */ + public function getOnloadCode($a_mode) + { + return array(); + } + + /** + * Set hierarchical ID in xml structure + * + * @param string $a_hier_id Hierarchical ID. + */ + public function setHierId($a_hier_id) + { + $this->hier_id = $a_hier_id; + } + + /** + * Get hierarchical id + */ + public function getHierId() + { + return $this->hier_id; + } + + + /** + * Get hierarchical id from dom + */ + public function lookupHierId() + { + return $this->node->get_attribute("HierId"); + } + + /** + * Read PC Id. + * + * @return string PC Id + */ + public function readHierId() + { + if (is_object($this->node)) { + return $this->node->get_attribute("HierId"); + } + } + + /** + * Set PC Id. + * + * @param string $a_pcid PC Id + */ + public function setPcId($a_pcid) + { + $this->pcid = $a_pcid; + } + + /** + * Get PC Id. + * + * @return string PC Id + */ + public function getPCId() + { + return $this->pcid; + } + + /** + * Set file download link + * + * @param string $a_download_link download link + */ + public function setFileDownloadLink($a_download_link) + { + $this->file_download_link = $a_download_link; + } + + /** + * Get file download link + * + * @return string + */ + public function getFileDownloadLink() + { + return $this->file_download_link; + } + + /** + * Set fullscreen link + * + * @param string $a_download_link download link + */ + public function setFullscreenLink($a_fullscreen_link) + { + $this->fullscreen_link = $a_fullscreen_link; + } + + /** + * Get fullscreen link + * + * @return string + */ + public function getFullscreenLink() + { + return $this->fullscreen_link; + } + + /** + * Set sourcecode download script + * + * @param string $script_name + */ + public function setSourcecodeDownloadScript($script_name) + { + $this->sourcecode_download_script = $script_name; + } + + /** + * Get sourcecode download script + * + * @return string + */ + public function getSourcecodeDownloadScript() + { + return $this->sourcecode_download_script; + } + + + /** + * Read PC Id. + * + * @return string PC Id + */ + public function readPCId() + { + if (is_object($this->node)) { + return $this->node->get_attribute("PCID"); + } + } + + /** + * Write pc id + */ + public function writePCId($a_pc_id) + { + if (is_object($this->node)) { + $this->node->set_attribute("PCID", $a_pc_id); + } + } + + /** + * Increases an hierarchical editing id at lowest level (last number) + * + * @param string $ed_id hierarchical ID + * + * @return string hierarchical ID (increased) + */ + final public static function incEdId($ed_id) + { + $id = explode("_", $ed_id); + $id[count($id) - 1]++; + + return implode($id, "_"); + } + + /** + * Decreases an hierarchical editing id at lowest level (last number) + * + * @param string $ed_id hierarchical ID + * + * @return string hierarchical ID (decreased) + */ + final public static function decEdId($ed_id) + { + $id = explode("_", $ed_id); + $id[count($id) - 1]--; + + return implode($id, "_"); + } + + /** + * Check, if two ids are in same container. + * + * @param string $ed_id1 hierachical ID 1 + * @param string $ed_id2 hierachical ID 2 + * + * @return boolean true/false + */ + final public static function haveSameContainer($ed_id1, $ed_id2) + { + $id1 = explode("_", $ed_id1); + $id2 = explode("_", $ed_id1); + if (count($id1) == count($id2)) { + array_pop($id1); + array_pop($id2); + foreach ($id1 as $key => $id) { + if ($id != $id2[$key]) { + return false; + } + } + return true; + } + return false; + } + + /** + * Sort an array of Hier IDS in ascending order + */ + public static function sortHierIds($a_array) + { + uasort($a_array, array("ilPageContent", "isGreaterHierId")); + + return $a_array; + } + + /** + * Check whether Hier ID $a is greater than Hier ID $b + */ + public static function isGreaterHierId($a, $b) + { + $a_arr = explode("_", $a); + $b_arr = explode("_", $b); + for ($i = 0; $i < count($a_arr); $i++) { + if ((int) $a_arr[$i] > (int) $b_arr[$i]) { + return true; + } elseif ((int) $a_arr[$i] < (int) $b_arr[$i]) { + return false; + } + } + return false; + } + + /** + * Set Enabled value for page content component. + * + * @param string $value "True" | "False" + * + */ + public function setEnabled($value) + { + if (is_object($this->node)) { + $this->node->set_attribute("Enabled", $value); + } + } + + /** + * Enable page content. + */ + public function enable() + { + $this->setEnabled("True"); + } + + /** + * Disable page content. + */ + public function disable() + { + $this->setEnabled("False"); + } + + /** + * Check whether page content is enabled. + * + * @return boolean true/false + */ + final public function isEnabled() + { + if (is_object($this->node) && $this->node->has_attribute("Enabled")) { + $compare = $this->node->get_attribute("Enabled"); + } else { + $compare = "True"; + } + + return strcasecmp($compare, "true") == 0; + } + + /** + * Create page content node (always use this method first when adding a new element) + */ + public function createPageContentNode($a_set_this_node = true) + { + $node = $this->dom->create_element("PageContent"); + if ($a_set_this_node) { + $this->node = $node; + } + return $node; + } + + /** + * Get lang vars needed for editing + * @return array array of lang var keys + */ + public static function getLangVars() + { + return array(); + } + + /** + * Handle copied content. This function must, e.g. create copies of + * objects referenced within the content (e.g. question objects) + * + * @param DOMDocument $a_domdoc dom document + */ + public static function handleCopiedContent(DOMDocument $a_domdoc, $a_self_ass = true, $a_clone_mobs = false) + { + } + + /** + * Modify page content after xsl + * + * @param string $a_output + * @return string + */ + public function modifyPageContentPostXsl($a_output, $a_mode) + { + return $a_output; + } + + /** + * After page has been updated (or created) + * + * @param object $a_page page object + * @param DOMDocument $a_domdoc dom document + * @param string $a_xml xml + * @param bool $a_creation true on creation, otherwise false + */ + public static function afterPageUpdate($a_page, DOMDocument $a_domdoc, $a_xml, $a_creation) + { + } + + /** + * Before page is being deleted + * + * @param object $a_page page object + */ + public static function beforePageDelete($a_page) + { + } + + /** + * After page history entry has been created + * + * @param object $a_page page object + * @param DOMDocument $a_old_domdoc old dom document + * @param string $a_old_xml old xml + * @param integer $a_old_nr history number + */ + public static function afterPageHistoryEntry($a_page, DOMDocument $a_old_domdoc, $a_old_xml, $a_old_nr) + { + } } -?> diff --git a/Services/COPage/classes/class.ilPageContentGUI.php b/Services/COPage/classes/class.ilPageContentGUI.php index 987bb3fb19d93d5a81596dda148133aae587e8cc..1fe236e038f985b756bb1f441ef3ee40fbdbf36c 100755 --- a/Services/COPage/classes/class.ilPageContentGUI.php +++ b/Services/COPage/classes/class.ilPageContentGUI.php @@ -13,665 +13,627 @@ require_once("./Services/COPage/classes/class.ilPageContent.php"); */ class ilPageContentGUI { - /** - * @var ilErrorHandling - */ - protected $error; - - var $content_obj; - var $tpl; - var $lng; - - /** - * @var ilCtrl - */ - var $ctrl; - var $pg_obj; - var $hier_id; - var $dom; - var $updated; - var $target_script; - var $return_location; - var $page_config = null; - - /** - * @var ilLogger - */ - protected $log; - - static $style_selector_reset = "margin-top:2px; margin-bottom:2px; text-indent:0px; position:static; float:none; width: auto;"; - - // common bb buttons (special ones are iln and wln) - protected static $common_bb_buttons = array( - "str" => "Strong", "emp" => "Emph", "imp" => "Important", - "sup" => "Sup", "sub" => "Sub", - "com" => "Comment", - "quot" => "Quotation", "acc" => "Accent", "code" => "Code", "tex" => "Tex", - "fn" => "Footnote", "xln" => "ExternalLink" - ); - - /** - * Constructor - * @access public - */ - function __construct($a_pg_obj, $a_content_obj, $a_hier_id = 0, $a_pc_id = "") - { - global $DIC; - - $this->error = $DIC["ilErr"]; - $tpl = $DIC["tpl"]; - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - - $this->log = ilLoggerFactory::getLogger('copg'); - - $this->tpl = $tpl; - $this->lng = $lng; - $this->pg_obj = $a_pg_obj; - $this->ctrl = $ilCtrl; - $this->content_obj = $a_content_obj; - - if($a_hier_id !== 0) - { - $this->hier_id = $a_hier_id; - $this->pc_id = $a_pc_id; -//echo "-".$this->pc_id."-"; - $this->dom = $a_pg_obj->getDom(); - } - } - - /** - * Set content object - * - * @param object $a_val content object - */ - function setContentObject($a_val) - { - $this->content_obj = $a_val; - } - - /** - * Get content object - * - * @return object content object - */ - function getContentObject() - { - return $this->content_obj; - } - - /** - * Set page - * - * @param object $a_val page object - */ - function setPage($a_val) - { - $this->pg_obj = $a_val; - } - - /** - * Get page - * - * @return object page object - */ - function getPage() - { - return $this->pg_obj; - } - - /** - * Set Page Config - * - * @param object Page Config - */ - function setPageConfig($a_val) - { - $this->page_config = $a_val; - } - - /** - * Get Page Config - * - * @return object Page Config - */ - function getPageConfig() - { - return $this->page_config; - } - - /** - * Get common bb buttons - */ - static function _getCommonBBButtons() - { - return self::$common_bb_buttons; - } - - // scorm2004-start - /** - * Set Style Id. - * - * @param int $a_styleid Style Id - */ - function setStyleId($a_styleid) - { - $this->styleid = $a_styleid; - } - - /** - * Get Style Id. - * - * @return int Style Id - */ - function getStyleId() - { - return $this->styleid; - } - - /** - * Get style object - */ - function getStyle() - { - if ((!is_object($this->style) || $this->getStyleId() != $this->style->getId()) && $this->getStyleId() > 0) - { - if (ilObject::_lookupType($this->getStyleId()) == "sty") - { - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $this->style = new ilObjStyleSheet($this->getStyleId()); - } - } - - return $this->style; - } - - /** - * Get characteristics of current style - */ - protected function getCharacteristicsOfCurrentStyle($a_type) - { - if ($this->getStyleId() > 0 && - ilObject::_lookupType($this->getStyleId()) == "sty") - { - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $style = new ilObjStyleSheet($this->getStyleId()); - $chars = array(); - if (!is_array($a_type)) - { - $a_type = array($a_type); - } - foreach ($a_type as $at) - { - $chars = array_merge($chars, $style->getCharacteristics($at, true)); - } - $new_chars = array(); - if (is_array($chars)) - { - foreach ($chars as $char) - { - if ($this->chars[$char] != "") // keep lang vars for standard chars - { - $new_chars[$char] = $this->chars[$char]; - } - else - { - $new_chars[$char] = $char; - } - asort($new_chars); - } - } - $this->setCharacteristics($new_chars); - } - } - - /** - * Set Characteristics - */ - function setCharacteristics($a_chars) - { - $this->chars = $a_chars; - } - - /** - * Get characteristics - */ - function getCharacteristics() - { - return $this->chars ? $this->chars : array(); - } - // scorm2004-end - - - /** - * get hierarchical id in dom object - */ - function getHierId() - { - return $this->hier_id; - } - - /** - * get hierarchical id in dom object - */ - function setHierId($a_hier_id) - { - $this->hier_id = $a_hier_id; - } - - /** - * Get the bb menu incl. script - */ - function getBBMenu($a_ta_name = "par_content") - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("./Services/COPage/classes/class.ilPageEditorSettings.php"); - - $btpl = new ilTemplate("tpl.bb_menu.html", true, true, "Services/COPage"); - - // not nice, should be set by context per method - if ($this->getPageConfig()->getEnableInternalLinks()) - { - $btpl->setCurrentBlock("bb_ilink_button"); - $btpl->setVariable("BB_LINK_ILINK", - $this->ctrl->getLinkTargetByClass("ilInternalLinkGUI", "showLinkHelp")); - $btpl->parseCurrentBlock(); - - // add int link parts - include_once("./Services/Link/classes/class.ilInternalLinkGUI.php"); - $btpl->setCurrentBlock("int_link_prep"); - $btpl->setVariable("INT_LINK_PREP", ilInternalLinkGUI::getInitHTML( - $ilCtrl->getLinkTargetByClass(array("ilpageeditorgui", "ilinternallinkgui"), - "", false, true, false), true)); - $btpl->parseCurrentBlock(); - - } - - if ($this->getPageConfig()->getEnableKeywords()) - { - $btpl->touchBlock("bb_kw_button"); - $btpl->setVariable("TXT_KW", $this->lng->txt("cont_text_keyword")); - } - if ($this->pg_obj->getParentType() == "wpg") - { - $btpl->setCurrentBlock("bb_wikilink_button2"); - $btpl->setVariable("TXT_WIKI_BUTTON2", $lng->txt("obj_wiki")); - $btpl->setVariable("WIKI_BUTTON2_URL", $ilCtrl->getLinkTargetByClass("ilwikipagegui", "")); - $btpl->parseCurrentBlock(); - - $btpl->setCurrentBlock("bb_wikilink_button"); - $btpl->setVariable("TXT_WLN2", $lng->txt("wiki_wiki_page")); - $btpl->parseCurrentBlock(); - } - $mathJaxSetting = new ilSetting("MathJax"); - $style = $this->getStyle(); -//echo URL_TO_LATEX; - foreach (self::$common_bb_buttons as $c => $st) - { - if (ilPageEditorSettings::lookupSettingByParentType($this->pg_obj->getParentType(), "active_".$c, true)) - { - if ($c != "tex" || $mathJaxSetting->get("enable") || defined("URL_TO_LATEX")) - { - if (!in_array($c, array("acc", "com", "quot", "code"))) - { - $btpl->touchBlock("bb_" . $c . "_button"); - $btpl->setVariable("TXT_" . strtoupper($c), $this->lng->txt("cont_text_" . $c)); - $lng->toJS("cont_text_" . $c); - } - } - } - } - - if ($this->getPageConfig()->getEnableAnchors()) - { - $btpl->touchBlock("bb_anc_button"); - $btpl->setVariable("TXT_ANC", $lng->txt("cont_anchor").":"); - $lng->toJS("cont_anchor"); - } - - include_once("./Services/COPage/classes/class.ilPCParagraphGUI.php"); - $btpl->setVariable("CHAR_STYLE_SELECT", ilPCParagraphGUI::getCharStyleSelector($this->pg_obj->getParentType(), "il.COPageBB.setCharacterClass", $this->getStyleId())); - - // footnote -// $btpl->setVariable("TXT_FN", $this->lng->txt("cont_text_fn")); - -// $btpl->setVariable("TXT_CODE", $this->lng->txt("cont_text_code")); - $btpl->setVariable("TXT_ILN", $this->lng->txt("cont_text_iln")); - $lng->toJS("cont_text_iln"); -// $btpl->setVariable("TXT_XLN", $this->lng->txt("cont_text_xln")); -// $btpl->setVariable("TXT_TEX", $this->lng->txt("cont_text_tex")); - $btpl->setVariable("TXT_BB_TIP", $this->lng->txt("cont_bb_tip")); - $btpl->setVariable("TXT_WLN", $lng->txt("wiki_wiki_page")); - $lng->toJS("wiki_wiki_page"); - - $btpl->setVariable("PAR_TA_NAME", $a_ta_name); - - return $btpl->get(); - } - - /** - * delete content element - */ - function delete() - { - $updated = $this->pg_obj->deleteContent($this->hier_id); - if($updated !== true) - { - $_SESSION["il_pg_error"] = $updated; - } - else - { - unset($_SESSION["il_pg_error"]); - } - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * move content element after another element - */ - function moveAfter() - { - $ilErr = $this->error; - - // check if a target is selected - if(!isset($_POST["target"])) - { - $ilErr->raiseError($this->lng->txt("no_checkbox"),$ilErr->MESSAGE); - } - - // check if only one target is selected - if(count($_POST["target"]) > 1) - { - $ilErr->raiseError($this->lng->txt("only_one_target"),$ilErr->MESSAGE); - } - - $a_hid = explode(":", $_POST["target"][0]); -//echo "-".$a_hid[0]."-".$a_hid[1]."-"; - - // check if target is within source - if($this->hier_id == substr($a_hid[0], 0, strlen($this->hier_id))) - { - $ilErr->raiseError($this->lng->txt("cont_target_within_source"),$ilErr->MESSAGE); - } - - // check whether target is allowed - $curr_node = $this->pg_obj->getContentNode($a_hid[0], $a_hid[1]); - if (is_object($curr_node) && $curr_node->node_name() == "FileItem") - { - $ilErr->raiseError($this->lng->txt("cont_operation_not_allowed"),$ilErr->MESSAGE); - } - - // strip "c" "r" of table ids from hierarchical id - $first_hier_character = substr($a_hid[0], 0, 1); - if ($first_hier_character == "c" || - $first_hier_character == "r" || - $first_hier_character == "i") - { - $a_hid[0] = substr($a_hid[0], 1); - } - - // move - $updated = $this->pg_obj->moveContentAfter($this->hier_id, $a_hid[0], - $this->content_obj->getPcId(), $a_hid[1]); - if($updated !== true) - { - $_SESSION["il_pg_error"] = $updated; - } - else - { - unset($_SESSION["il_pg_error"]); - } - $this->log->debug("return to parent jump".$this->hier_id); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * move content element before another element - */ - function moveBefore() - { - $ilErr = $this->error; - - // check if a target is selected - if(!isset($_POST["target"])) - { - $ilErr->raiseError($this->lng->txt("no_checkbox"),$ilErr->MESSAGE); - } - - // check if target is within source - if(count($_POST["target"]) > 1) - { - $ilErr->raiseError($this->lng->txt("only_one_target"),$ilErr->MESSAGE); - } - - $a_hid = explode(":", $_POST["target"][0]); - - // check if target is within source - if($this->hier_id == substr($a_hid[0], 0, strlen($this->hier_id))) - { - $ilErr->raiseError($this->lng->txt("cont_target_within_source"),$ilErr->MESSAGE); - } - - // check whether target is allowed - $curr_node = $this->pg_obj->getContentNode($a_hid[0], $a_hid[1]); - if (is_object($curr_node) && $curr_node->node_name() == "FileItem") - { - $ilErr->raiseError($this->lng->txt("cont_operation_not_allowed"),$ilErr->MESSAGE); - } - - // strip "c" "r" of table ids from hierarchical id - $first_hier_character = substr($a_hid[0], 0, 1); - if ($first_hier_character == "c" || - $first_hier_character == "r" || - $first_hier_character == "i") - { - $a_hid[0] = substr($a_hid[0], 1); - } - - // move - $updated = $this->pg_obj->moveContentBefore($this->hier_id, $a_hid[0], - $this->content_obj->getPcId(), $a_hid[1]); - if($updated !== true) - { - $_SESSION["il_pg_error"] = $updated; - } - else - { - unset($_SESSION["il_pg_error"]); - } - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - - /** - * split page to new page at specified position - */ - function splitPage() - { - $ilErr = $this->error; - - if ($this->pg_obj->getParentType() != "lm") - { - $ilErr->raiseError("Split method called for wrong parent type (". - $this->pg_obj->getParentType().")", $ilErr->FATAL); - } - else - { - $lm_page = ilLMPageObject::_splitPage($this->pg_obj->getId(), - $this->pg_obj->getParentType(), $this->hier_id); - - // jump to new page - $this->ctrl->setParameterByClass("illmpageobjectgui", "obj_id", $lm_page->getId()); - $this->ctrl->redirectByClass("illmpageobjectgui", "edit"); - } - - $this->ctrl->returnToParent($this, "jump".($this->hier_id - 1)); - } - - /** - * split page to next page at specified position - */ - function splitPageNext() - { - $ilErr = $this->error; - - if ($this->pg_obj->getParentType() != "lm") - { - $ilErr->raiseError("Split method called for wrong parent type (". - $this->pg_obj->getParentType().")", $ilErr->FATAL); - } - else - { - $succ_id = ilLMPageObject::_splitPageNext($this->pg_obj->getId(), - $this->pg_obj->getParentType(), $this->hier_id); - - // jump to successor page - if ($succ_id > 0) - { - $this->ctrl->setParameterByClass("illmpageobjectgui", "obj_id", $succ_id); - $this->ctrl->redirectByClass("illmpageobjectgui", "edit"); - } - - } - $this->ctrl->returnToParent($this, "jump".($this->hier_id - 1)); - } - - /** - * display validation errors - */ - function displayValidationError() - { - if(is_array($this->updated)) - { - $error_str = "Error(s):
          "; - foreach ($this->updated as $error) - { - $err_mess = implode($error, " - "); - if (!is_int(strpos($err_mess, ":0:"))) - { - $error_str .= htmlentities($err_mess)."
          "; - } - } - ilUtil::sendFailure($error_str); - } - else if($this->updated != "" && $this->updated !== true) - { - ilUtil::sendFailure("Error(s):
          ". - $this->updated); - } - } - - /** - * cancel creating page content - */ - function cancelCreate() - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * cancel update - */ - function cancelUpdate() - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * Cancel - */ - function cancel() - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * gui function - * set enabled if is not enabled and vice versa - */ - function deactivate() - { - $obj = & $this->content_obj; - - if ($obj->isEnabled ()) - $obj->disable (); - else - $obj->enable (); - - $updated = $this->pg_obj->update($this->hier_id); - if($updated !== true) - { - $_SESSION["il_pg_error"] = $updated; - } - else - { - unset($_SESSION["il_pg_error"]); - } - - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * Cut single element - */ - function cut() - { - $lng = $this->lng; - - $obj = $this->content_obj; - - $updated = $this->pg_obj->cutContents(array($this->hier_id.":".$this->pc_id)); - if($updated !== true) - { - $_SESSION["il_pg_error"] = $updated; - } - else - { - unset($_SESSION["il_pg_error"]); - } - - //ilUtil::sendSuccess($lng->txt("cont_sel_el_cut_use_paste"), true); - $this->log->debug("return to parent jump".$this->hier_id); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - /** - * Copy single element - */ - function copy() - { - $lng = $this->lng; - - $obj = $this->content_obj; - - //ilUtil::sendSuccess($lng->txt("cont_sel_el_copied_use_paste"), true); - $this->pg_obj->copyContents(array($this->hier_id.":".$this->pc_id)); + /** + * @var ilErrorHandling + */ + protected $error; + + public $content_obj; + public $tpl; + public $lng; + + /** + * @var ilCtrl + */ + public $ctrl; + public $pg_obj; + public $hier_id; + public $dom; + public $updated; + public $target_script; + public $return_location; + public $page_config = null; + + /** + * @var ilLogger + */ + protected $log; + + public static $style_selector_reset = "margin-top:2px; margin-bottom:2px; text-indent:0px; position:static; float:none; width: auto;"; + + // common bb buttons (special ones are iln and wln) + protected static $common_bb_buttons = array( + "str" => "Strong", "emp" => "Emph", "imp" => "Important", + "sup" => "Sup", "sub" => "Sub", + "com" => "Comment", + "quot" => "Quotation", "acc" => "Accent", "code" => "Code", "tex" => "Tex", + "fn" => "Footnote", "xln" => "ExternalLink" + ); + + /** + * Constructor + * @access public + */ + public function __construct($a_pg_obj, $a_content_obj, $a_hier_id = 0, $a_pc_id = "") + { + global $DIC; + + $this->error = $DIC["ilErr"]; + $tpl = $DIC["tpl"]; + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + + $this->log = ilLoggerFactory::getLogger('copg'); + + $this->tpl = $tpl; + $this->lng = $lng; + $this->pg_obj = $a_pg_obj; + $this->ctrl = $ilCtrl; + $this->content_obj = $a_content_obj; + + if ($a_hier_id !== 0) { + $this->hier_id = $a_hier_id; + $this->pc_id = $a_pc_id; + //echo "-".$this->pc_id."-"; + $this->dom = $a_pg_obj->getDom(); + } + } + + /** + * Set content object + * + * @param object $a_val content object + */ + public function setContentObject($a_val) + { + $this->content_obj = $a_val; + } + + /** + * Get content object + * + * @return object content object + */ + public function getContentObject() + { + return $this->content_obj; + } + + /** + * Set page + * + * @param object $a_val page object + */ + public function setPage($a_val) + { + $this->pg_obj = $a_val; + } + + /** + * Get page + * + * @return object page object + */ + public function getPage() + { + return $this->pg_obj; + } + + /** + * Set Page Config + * + * @param object Page Config + */ + public function setPageConfig($a_val) + { + $this->page_config = $a_val; + } + + /** + * Get Page Config + * + * @return object Page Config + */ + public function getPageConfig() + { + return $this->page_config; + } + + /** + * Get common bb buttons + */ + public static function _getCommonBBButtons() + { + return self::$common_bb_buttons; + } + + // scorm2004-start + /** + * Set Style Id. + * + * @param int $a_styleid Style Id + */ + public function setStyleId($a_styleid) + { + $this->styleid = $a_styleid; + } + + /** + * Get Style Id. + * + * @return int Style Id + */ + public function getStyleId() + { + return $this->styleid; + } + + /** + * Get style object + */ + public function getStyle() + { + if ((!is_object($this->style) || $this->getStyleId() != $this->style->getId()) && $this->getStyleId() > 0) { + if (ilObject::_lookupType($this->getStyleId()) == "sty") { + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $this->style = new ilObjStyleSheet($this->getStyleId()); + } + } + + return $this->style; + } + + /** + * Get characteristics of current style + */ + protected function getCharacteristicsOfCurrentStyle($a_type) + { + if ($this->getStyleId() > 0 && + ilObject::_lookupType($this->getStyleId()) == "sty") { + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $style = new ilObjStyleSheet($this->getStyleId()); + $chars = array(); + if (!is_array($a_type)) { + $a_type = array($a_type); + } + foreach ($a_type as $at) { + $chars = array_merge($chars, $style->getCharacteristics($at, true)); + } + $new_chars = array(); + if (is_array($chars)) { + foreach ($chars as $char) { + if ($this->chars[$char] != "") { // keep lang vars for standard chars + $new_chars[$char] = $this->chars[$char]; + } else { + $new_chars[$char] = $char; + } + asort($new_chars); + } + } + $this->setCharacteristics($new_chars); + } + } + + /** + * Set Characteristics + */ + public function setCharacteristics($a_chars) + { + $this->chars = $a_chars; + } + + /** + * Get characteristics + */ + public function getCharacteristics() + { + return $this->chars ? $this->chars : array(); + } + // scorm2004-end + + + /** + * get hierarchical id in dom object + */ + public function getHierId() + { + return $this->hier_id; + } + + /** + * get hierarchical id in dom object + */ + public function setHierId($a_hier_id) + { + $this->hier_id = $a_hier_id; + } + + /** + * Get the bb menu incl. script + */ + public function getBBMenu($a_ta_name = "par_content") + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("./Services/COPage/classes/class.ilPageEditorSettings.php"); + + $btpl = new ilTemplate("tpl.bb_menu.html", true, true, "Services/COPage"); + + // not nice, should be set by context per method + if ($this->getPageConfig()->getEnableInternalLinks()) { + $btpl->setCurrentBlock("bb_ilink_button"); + $btpl->setVariable( + "BB_LINK_ILINK", + $this->ctrl->getLinkTargetByClass("ilInternalLinkGUI", "showLinkHelp") + ); + $btpl->parseCurrentBlock(); + + // add int link parts + include_once("./Services/Link/classes/class.ilInternalLinkGUI.php"); + $btpl->setCurrentBlock("int_link_prep"); + $btpl->setVariable("INT_LINK_PREP", ilInternalLinkGUI::getInitHTML( + $ilCtrl->getLinkTargetByClass( + array("ilpageeditorgui", "ilinternallinkgui"), + "", + false, + true, + false + ), + true + )); + $btpl->parseCurrentBlock(); + } + + if ($this->getPageConfig()->getEnableKeywords()) { + $btpl->touchBlock("bb_kw_button"); + $btpl->setVariable("TXT_KW", $this->lng->txt("cont_text_keyword")); + } + if ($this->pg_obj->getParentType() == "wpg") { + $btpl->setCurrentBlock("bb_wikilink_button2"); + $btpl->setVariable("TXT_WIKI_BUTTON2", $lng->txt("obj_wiki")); + $btpl->setVariable("WIKI_BUTTON2_URL", $ilCtrl->getLinkTargetByClass("ilwikipagegui", "")); + $btpl->parseCurrentBlock(); + + $btpl->setCurrentBlock("bb_wikilink_button"); + $btpl->setVariable("TXT_WLN2", $lng->txt("wiki_wiki_page")); + $btpl->parseCurrentBlock(); + } + $mathJaxSetting = new ilSetting("MathJax"); + $style = $this->getStyle(); + //echo URL_TO_LATEX; + foreach (self::$common_bb_buttons as $c => $st) { + if (ilPageEditorSettings::lookupSettingByParentType($this->pg_obj->getParentType(), "active_" . $c, true)) { + if ($c != "tex" || $mathJaxSetting->get("enable") || defined("URL_TO_LATEX")) { + if (!in_array($c, array("acc", "com", "quot", "code"))) { + $btpl->touchBlock("bb_" . $c . "_button"); + $btpl->setVariable("TXT_" . strtoupper($c), $this->lng->txt("cont_text_" . $c)); + $lng->toJS("cont_text_" . $c); + } + } + } + } + + if ($this->getPageConfig()->getEnableAnchors()) { + $btpl->touchBlock("bb_anc_button"); + $btpl->setVariable("TXT_ANC", $lng->txt("cont_anchor") . ":"); + $lng->toJS("cont_anchor"); + } + + include_once("./Services/COPage/classes/class.ilPCParagraphGUI.php"); + $btpl->setVariable("CHAR_STYLE_SELECT", ilPCParagraphGUI::getCharStyleSelector($this->pg_obj->getParentType(), "il.COPageBB.setCharacterClass", $this->getStyleId())); + + // footnote + // $btpl->setVariable("TXT_FN", $this->lng->txt("cont_text_fn")); + + // $btpl->setVariable("TXT_CODE", $this->lng->txt("cont_text_code")); + $btpl->setVariable("TXT_ILN", $this->lng->txt("cont_text_iln")); + $lng->toJS("cont_text_iln"); + // $btpl->setVariable("TXT_XLN", $this->lng->txt("cont_text_xln")); + // $btpl->setVariable("TXT_TEX", $this->lng->txt("cont_text_tex")); + $btpl->setVariable("TXT_BB_TIP", $this->lng->txt("cont_bb_tip")); + $btpl->setVariable("TXT_WLN", $lng->txt("wiki_wiki_page")); + $lng->toJS("wiki_wiki_page"); + + $btpl->setVariable("PAR_TA_NAME", $a_ta_name); + + return $btpl->get(); + } + + /** + * delete content element + */ + public function delete() + { + $updated = $this->pg_obj->deleteContent($this->hier_id); + if ($updated !== true) { + $_SESSION["il_pg_error"] = $updated; + } else { + unset($_SESSION["il_pg_error"]); + } + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * move content element after another element + */ + public function moveAfter() + { + $ilErr = $this->error; + + // check if a target is selected + if (!isset($_POST["target"])) { + $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); + } + + // check if only one target is selected + if (count($_POST["target"]) > 1) { + $ilErr->raiseError($this->lng->txt("only_one_target"), $ilErr->MESSAGE); + } + + $a_hid = explode(":", $_POST["target"][0]); + //echo "-".$a_hid[0]."-".$a_hid[1]."-"; + + // check if target is within source + if ($this->hier_id == substr($a_hid[0], 0, strlen($this->hier_id))) { + $ilErr->raiseError($this->lng->txt("cont_target_within_source"), $ilErr->MESSAGE); + } + + // check whether target is allowed + $curr_node = $this->pg_obj->getContentNode($a_hid[0], $a_hid[1]); + if (is_object($curr_node) && $curr_node->node_name() == "FileItem") { + $ilErr->raiseError($this->lng->txt("cont_operation_not_allowed"), $ilErr->MESSAGE); + } + + // strip "c" "r" of table ids from hierarchical id + $first_hier_character = substr($a_hid[0], 0, 1); + if ($first_hier_character == "c" || + $first_hier_character == "r" || + $first_hier_character == "i") { + $a_hid[0] = substr($a_hid[0], 1); + } + + // move + $updated = $this->pg_obj->moveContentAfter( + $this->hier_id, + $a_hid[0], + $this->content_obj->getPcId(), + $a_hid[1] + ); + if ($updated !== true) { + $_SESSION["il_pg_error"] = $updated; + } else { + unset($_SESSION["il_pg_error"]); + } + $this->log->debug("return to parent jump" . $this->hier_id); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * move content element before another element + */ + public function moveBefore() + { + $ilErr = $this->error; + + // check if a target is selected + if (!isset($_POST["target"])) { + $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); + } + + // check if target is within source + if (count($_POST["target"]) > 1) { + $ilErr->raiseError($this->lng->txt("only_one_target"), $ilErr->MESSAGE); + } + + $a_hid = explode(":", $_POST["target"][0]); + + // check if target is within source + if ($this->hier_id == substr($a_hid[0], 0, strlen($this->hier_id))) { + $ilErr->raiseError($this->lng->txt("cont_target_within_source"), $ilErr->MESSAGE); + } + + // check whether target is allowed + $curr_node = $this->pg_obj->getContentNode($a_hid[0], $a_hid[1]); + if (is_object($curr_node) && $curr_node->node_name() == "FileItem") { + $ilErr->raiseError($this->lng->txt("cont_operation_not_allowed"), $ilErr->MESSAGE); + } + + // strip "c" "r" of table ids from hierarchical id + $first_hier_character = substr($a_hid[0], 0, 1); + if ($first_hier_character == "c" || + $first_hier_character == "r" || + $first_hier_character == "i") { + $a_hid[0] = substr($a_hid[0], 1); + } + + // move + $updated = $this->pg_obj->moveContentBefore( + $this->hier_id, + $a_hid[0], + $this->content_obj->getPcId(), + $a_hid[1] + ); + if ($updated !== true) { + $_SESSION["il_pg_error"] = $updated; + } else { + unset($_SESSION["il_pg_error"]); + } + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + + /** + * split page to new page at specified position + */ + public function splitPage() + { + $ilErr = $this->error; + + if ($this->pg_obj->getParentType() != "lm") { + $ilErr->raiseError("Split method called for wrong parent type (" . + $this->pg_obj->getParentType() . ")", $ilErr->FATAL); + } else { + $lm_page = ilLMPageObject::_splitPage( + $this->pg_obj->getId(), + $this->pg_obj->getParentType(), + $this->hier_id + ); + + // jump to new page + $this->ctrl->setParameterByClass("illmpageobjectgui", "obj_id", $lm_page->getId()); + $this->ctrl->redirectByClass("illmpageobjectgui", "edit"); + } + + $this->ctrl->returnToParent($this, "jump" . ($this->hier_id - 1)); + } + + /** + * split page to next page at specified position + */ + public function splitPageNext() + { + $ilErr = $this->error; + + if ($this->pg_obj->getParentType() != "lm") { + $ilErr->raiseError("Split method called for wrong parent type (" . + $this->pg_obj->getParentType() . ")", $ilErr->FATAL); + } else { + $succ_id = ilLMPageObject::_splitPageNext( + $this->pg_obj->getId(), + $this->pg_obj->getParentType(), + $this->hier_id + ); + + // jump to successor page + if ($succ_id > 0) { + $this->ctrl->setParameterByClass("illmpageobjectgui", "obj_id", $succ_id); + $this->ctrl->redirectByClass("illmpageobjectgui", "edit"); + } + } + $this->ctrl->returnToParent($this, "jump" . ($this->hier_id - 1)); + } + + /** + * display validation errors + */ + public function displayValidationError() + { + if (is_array($this->updated)) { + $error_str = "Error(s):
          "; + foreach ($this->updated as $error) { + $err_mess = implode($error, " - "); + if (!is_int(strpos($err_mess, ":0:"))) { + $error_str .= htmlentities($err_mess) . "
          "; + } + } + ilUtil::sendFailure($error_str); + } elseif ($this->updated != "" && $this->updated !== true) { + ilUtil::sendFailure("Error(s):
          " . + $this->updated); + } + } + + /** + * cancel creating page content + */ + public function cancelCreate() + { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * cancel update + */ + public function cancelUpdate() + { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * Cancel + */ + public function cancel() + { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * gui function + * set enabled if is not enabled and vice versa + */ + public function deactivate() + { + $obj = &$this->content_obj; + + if ($obj->isEnabled()) { + $obj->disable(); + } else { + $obj->enable(); + } + + $updated = $this->pg_obj->update($this->hier_id); + if ($updated !== true) { + $_SESSION["il_pg_error"] = $updated; + } else { + unset($_SESSION["il_pg_error"]); + } + + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * Cut single element + */ + public function cut() + { + $lng = $this->lng; + + $obj = $this->content_obj; + + $updated = $this->pg_obj->cutContents(array($this->hier_id . ":" . $this->pc_id)); + if ($updated !== true) { + $_SESSION["il_pg_error"] = $updated; + } else { + unset($_SESSION["il_pg_error"]); + } + + //ilUtil::sendSuccess($lng->txt("cont_sel_el_cut_use_paste"), true); + $this->log->debug("return to parent jump" . $this->hier_id); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + /** + * Copy single element + */ + public function copy() + { + $lng = $this->lng; + + $obj = $this->content_obj; + + //ilUtil::sendSuccess($lng->txt("cont_sel_el_copied_use_paste"), true); + $this->pg_obj->copyContents(array($this->hier_id . ":" . $this->pc_id)); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - - - /** - * Get table templates - */ - function getTemplateOptions($a_type) - { - $style = $this->getStyle(); - - if (is_object($style)) - { - $ts = $style->getTemplates($a_type); - $options = array(); - foreach ($ts as $t) - { - $options["t:".$t["id"].":".$t["name"]] = $t["name"]; - } - return $options; - } - return array(); - } - + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + + + /** + * Get table templates + */ + public function getTemplateOptions($a_type) + { + $style = $this->getStyle(); + + if (is_object($style)) { + $ts = $style->getTemplates($a_type); + $options = array(); + foreach ($ts as $t) { + $options["t:" . $t["id"] . ":" . $t["name"]] = $t["name"]; + } + return $options; + } + return array(); + } } -?> diff --git a/Services/COPage/classes/class.ilPageContentUsage.php b/Services/COPage/classes/class.ilPageContentUsage.php index 935b3b41ee612332d43a9ae73641c388de8dc2b1..13da77169eb8e20e98fe8b008684bc75d6c532f9 100755 --- a/Services/COPage/classes/class.ilPageContentUsage.php +++ b/Services/COPage/classes/class.ilPageContentUsage.php @@ -7,111 +7,107 @@ * * @author Alex Killing * @version $Id$ -* @ingroup +* @ingroup */ class ilPageContentUsage { - /** - * Save usages - */ - static function saveUsage($a_pc_type, $a_pc_id, $a_usage_type, $a_usage_id, $a_usage_hist_nr = 0, $a_lang = "-") - { - global $DIC; + /** + * Save usages + */ + public static function saveUsage($a_pc_type, $a_pc_id, $a_usage_type, $a_usage_id, $a_usage_hist_nr = 0, $a_lang = "-") + { + global $DIC; - $ilDB = $DIC->database(); - - $ilDB->replace("page_pc_usage", array ( - "pc_type" => array("text", $a_pc_type), - "pc_id" => array("integer", (int) $a_pc_id), - "usage_type" => array("text", $a_usage_type), - "usage_id" => array("integer", (int) $a_usage_id), - "usage_lang" => array("text", $a_lang), - "usage_hist_nr" => array("integer", (int) $a_usage_hist_nr) - ),array()); - } + $ilDB = $DIC->database(); + + $ilDB->replace("page_pc_usage", array( + "pc_type" => array("text", $a_pc_type), + "pc_id" => array("integer", (int) $a_pc_id), + "usage_type" => array("text", $a_usage_type), + "usage_id" => array("integer", (int) $a_usage_id), + "usage_lang" => array("text", $a_lang), + "usage_hist_nr" => array("integer", (int) $a_usage_hist_nr) + ), array()); + } - /** - * Delete all usages - */ - static function deleteAllUsages($a_pc_type, $a_usage_type, $a_usage_id, $a_usage_hist_nr = 0, $a_lang = "-") - { - global $DIC; + /** + * Delete all usages + */ + public static function deleteAllUsages($a_pc_type, $a_usage_type, $a_usage_id, $a_usage_hist_nr = 0, $a_lang = "-") + { + global $DIC; - $ilDB = $DIC->database(); - - $and_hist = ($a_usage_hist_nr !== false) - ? " AND usage_hist_nr = ".$ilDB->quote((int) $a_usage_hist_nr, "integer") - : ""; - - $ilDB->manipulate($q = "DELETE FROM page_pc_usage WHERE usage_type = ". - $ilDB->quote($a_usage_type, "text"). - " AND usage_id = ".$ilDB->quote((int) $a_usage_id, "integer"). - " AND usage_lang = ".$ilDB->quote($a_lang, "text"). - $and_hist. - " AND pc_type = ".$ilDB->quote($a_pc_type, "text")); - } - - /** - * Get usages - */ - static function getUsages($a_pc_type, $a_pc_id, $a_incl_hist = true) - { - global $DIC; + $ilDB = $DIC->database(); + + $and_hist = ($a_usage_hist_nr !== false) + ? " AND usage_hist_nr = " . $ilDB->quote((int) $a_usage_hist_nr, "integer") + : ""; + + $ilDB->manipulate($q = "DELETE FROM page_pc_usage WHERE usage_type = " . + $ilDB->quote($a_usage_type, "text") . + " AND usage_id = " . $ilDB->quote((int) $a_usage_id, "integer") . + " AND usage_lang = " . $ilDB->quote($a_lang, "text") . + $and_hist . + " AND pc_type = " . $ilDB->quote($a_pc_type, "text")); + } + + /** + * Get usages + */ + public static function getUsages($a_pc_type, $a_pc_id, $a_incl_hist = true) + { + global $DIC; - $ilDB = $DIC->database(); - - $q = "SELECT * FROM page_pc_usage ". - " WHERE pc_type = ".$ilDB->quote($a_pc_type, "text"). - " AND pc_id = ".$ilDB->quote($a_pc_id, "integer"); - - if (!$a_incl_hist) - { - $q.= " AND usage_hist_nr = ".$ilDB->quote(0, "integer"); - } - - $set = $ilDB->query($q); - $usages = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $usages[] = $rec; - } - return $usages; - } + $ilDB = $DIC->database(); + + $q = "SELECT * FROM page_pc_usage " . + " WHERE pc_type = " . $ilDB->quote($a_pc_type, "text") . + " AND pc_id = " . $ilDB->quote($a_pc_id, "integer"); + + if (!$a_incl_hist) { + $q.= " AND usage_hist_nr = " . $ilDB->quote(0, "integer"); + } + + $set = $ilDB->query($q); + $usages = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $usages[] = $rec; + } + return $usages; + } - /** - * Get page content usages for page - * - * @param - * @return - */ - static function getUsagesOfPage($a_usage_id, $a_usage_type, $a_hist_nr = 0, $a_all_hist_nrs = false, $a_lang = "-") - { - global $DIC; + /** + * Get page content usages for page + * + * @param + * @return + */ + public static function getUsagesOfPage($a_usage_id, $a_usage_type, $a_hist_nr = 0, $a_all_hist_nrs = false, $a_lang = "-") + { + global $DIC; - $ilDB = $DIC->database(); + $ilDB = $DIC->database(); - if (!$a_all_hist_nrs) - { - $hist_str = " AND usage_hist_nr = ".$ilDB->quote($a_hist_nr, "integer"); - } + if (!$a_all_hist_nrs) { + $hist_str = " AND usage_hist_nr = " . $ilDB->quote($a_hist_nr, "integer"); + } - $set = $ilDB->query("SELECT pc_type, pc_id FROM page_pc_usage WHERE ". - " usage_id = ".$ilDB->quote($a_usage_id, "integer")." AND ". - " usage_lang = ".$ilDB->quote($a_lang, "text")." AND ". - " usage_type = ".$ilDB->quote($a_usage_type, "text"). - $hist_str - ); + $set = $ilDB->query( + "SELECT pc_type, pc_id FROM page_pc_usage WHERE " . + " usage_id = " . $ilDB->quote($a_usage_id, "integer") . " AND " . + " usage_lang = " . $ilDB->quote($a_lang, "text") . " AND " . + " usage_type = " . $ilDB->quote($a_usage_type, "text") . + $hist_str + ); - $usages = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $usages[$rec["pc_type"].":".$rec["pc_id"]] = array( - "type" => $rec["pc_type"], - "id" => $rec["pc_id"] - ); - } - - return $usages; - } + $usages = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $usages[$rec["pc_type"] . ":" . $rec["pc_id"]] = array( + "type" => $rec["pc_type"], + "id" => $rec["pc_id"] + ); + } + return $usages; + } } diff --git a/Services/COPage/classes/class.ilPageEditorGUI.php b/Services/COPage/classes/class.ilPageEditorGUI.php index a4a67cb7d8dccb697fece3ec282326c93d1ca7c6..581f6cb5351191fe34a59a4b75ac14acd6c46dc1 100755 --- a/Services/COPage/classes/class.ilPageEditorGUI.php +++ b/Services/COPage/classes/class.ilPageEditorGUI.php @@ -1,7 +1,7 @@ help = $DIC["ilHelp"]; - $this->user = $DIC->user(); - $this->access = $DIC->access(); - $tpl = $DIC["tpl"]; - $lng = $DIC->language(); - $objDefinition = $DIC["objDefinition"]; - $ilCtrl = $DIC->ctrl(); - $ilTabs = $DIC->tabs(); - - $this->log = ilLoggerFactory::getLogger('copg'); - - // initiate variables - $this->ctrl = $ilCtrl; - $this->tpl = $tpl; - $this->lng = $lng; - $this->objDefinition = $objDefinition; - $this->tabs_gui = $ilTabs; - $this->page = $a_page_object; - $this->page_gui = $a_page_object_gui; - - $this->ctrl->saveParameter($this, array("hier_id", "pc_id")); - } - - - /** - * set header title - * - * @param string $a_header header title - */ - function setHeader($a_header) - { - $this->header = $a_header; - } - - /** - * get header title - * - * @return string header title - */ - function getHeader() - { - return $this->header; - } - - /** - * set locator object - * - * @param object $a_locator locator object - */ - function setLocator(&$a_locator) - { - $this->locator = $a_locator; - } - - /** - * redirect to parent context - */ - function returnToContext() - { - $this->ctrl->returnToParent($this); - } - - function setIntLinkReturn($a_return) - { - $this->int_link_return = $a_return; - } - - - function setPageBackTitle($a_title) - { - $this->page_back_title = $a_title; - } - - /** - * execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - $ilHelp = $this->help; - - $this->log->debug("begin ============"); - - // Step BC (basic command determination) - // determine cmd, cmdClass, hier_id and pc_id - $cmd = $this->ctrl->getCmd("displayPage"); - $cmdClass = strtolower($this->ctrl->getCmdClass()); - - $hier_id = $_GET["hier_id"]; - $pc_id = $_GET["pc_id"]; - if(isset($_POST["new_hier_id"])) - { - $hier_id = $_POST["new_hier_id"]; - } - - $new_type = (isset($_GET["new_type"])) - ? $_GET["new_type"] - : $_POST["new_type"]; - - $this->log->debug("step BC: cmd:$cmd, cmdClass:$cmdClass, hier_id: $hier_id, pc_id: $pc_id"); - - // Step EC (exec_ command handling) - // handle special exec_ commands, modify pc, hier_id - if (substr($cmd, 0, 5) == "exec_") - { - // check whether pc id is given - $pca = explode(":", key($_POST["cmd"])); - $pc_id = $pca[1]; - $cmd = explode("_", $pca[0]); - unset($cmd[0]); - $hier_id = implode($cmd, "_"); - $cmd = $_POST["command".$hier_id]; - } - $this->log->debug("step EC: cmd:$cmd, hier_id: $hier_id, pc_id: $pc_id"); - - // Step CC (handle table container (and similar) commands - // ... strip "c" "r" of table ids from hierarchical id - $first_hier_character = substr($hier_id, 0, 1); - if ($first_hier_character == "c" || - $first_hier_character == "r" || - $first_hier_character == "g" || - $first_hier_character == "i") - { - $hier_id = substr($hier_id, 1); - } - $this->log->debug("step CC: cmd:$cmd, hier_id: $hier_id, pc_id: $pc_id"); - - // Step B (build dom, and ids in XML) - $this->page->buildDom(); - $this->page->addHierIDs(); - - - // Step CS (strip base command) - if ($cmdClass != "ilfilesystemgui") - { - $com = explode("_", $cmd); - $cmd = $com[0]; - } - $this->log->debug("step CS: cmd:$cmd"); - - - // Step NC (determine next class) - $next_class = $this->ctrl->getNextClass($this); - $this->log->debug("step NC: next class: ".$next_class); - - - // Step PH (placeholder handling, placeholders from preview mode come without hier_id) - if ($next_class == "ilpcplaceholdergui" && $hier_id == "" && $_GET["pl_pc_id"] != "") - { - $hid = $this->page->getHierIdsForPCIds(array($_GET["pl_pc_id"])); - $hier_id = $hid[$_GET["pl_pc_id"]]; - } - $this->log->debug("step PH: next class: ".$next_class); - - if ($com[0] == "insert" || $com[0] == "create") - { - // Step CM (creation mode handling) - $cmd = $com[0]; - $ctype = $com[1]; // note ctype holds type if cmdclass is empty, but also subcommands if not (e.g. applyFilter in ilpcmediaobjectgui) - $add_type = $com[2]; - if ($ctype == "mob") $ctype = "media"; - - $this->log->debug("step CM: cmd: ".$cmd.", ctype: ".$ctype.", add_type: ".$add_type); - } - else - { - // Step LM (setting cmd and cmdclass for editing of linked media) - if ($cmd == "editLinkedMedia") - { - $this->ctrl->setCmd("edit"); - $cmd = "edit"; - $_GET["pgEdMediaMode"] = "editLinkedMedia"; - $_GET["mob_id"] = $_POST["mob_id"]; - } - if ($_GET["pgEdMediaMode"] == "editLinkedMedia") - { - $this->ctrl->setParameter($this, "pgEdMediaMode", "editLinkedMedia"); - $this->ctrl->setParameter($this, "mob_id", $_GET["mob_id"]); - if ($cmdClass != "ilinternallinkgui" && $cmdClass != "ilmdeditorgui" - && $cmdClass != "ilimagemapeditorgui" && $cmdClass != "ilfilesystemgui") - { - $this->ctrl->setCmdClass("ilobjmediaobjectgui"); - $cmdClass = "ilobjmediaobjectgui"; - } - } - $this->log->debug("step LM: cmd: ".$cmd.", cmdClass: ".$cmdClass); - - - // Step PR (get content object and return to parent) - $this->log->debug("before PR: cmdClass: $cmdClass, nextClass: $next_class". - ", hier_id: ".$hier_id.", pc_id: ".$pc_id.")"); - // note: ilinternallinkgui for page: no cont_obj is received - // ilinternallinkgui for mob: cont_obj is received - if ($cmd != "insertFromClipboard" && $cmd != "pasteFromClipboard" && - $cmd != "setMediaMode" && $cmd != "copyLinkedMediaToClipboard" && - $cmd != "activatePage" && $cmd != "deactivatePage" && - $cmd != "copyLinkedMediaToMediaPool" && $cmd != "showSnippetInfo" && - $cmd != "deleteSelected" && $cmd != "paste" && - $cmd != "cancelDeleteSelected" && $cmd != "confirmedDeleteSelected" && - $cmd != "copySelected" && $cmd != "cutSelected" && - ($cmd != "displayPage" || $_POST["editImagemapForward_x"] != "" || $_POST["imagemap_x"] != "") && - ($cmd != "displayPage" || $_POST["editImagemapForward_x"] != "") && - $cmd != "activateSelected" && $cmd != "assignCharacteristicForm" && - $cmd != "assignCharacteristic" && - $cmdClass != "ilrepositoryselector2inputgui" && - $cmd != "cancelCreate" && $cmd != "popup" && - $cmdClass != "ileditclipboardgui" && $cmd != "addChangeComment" && - ($cmdClass != "ilinternallinkgui" || ($next_class == "ilpcmediaobjectgui"))) - { - if ($_GET["pgEdMediaMode"] != "editLinkedMedia") - { - $cont_obj = $this->page->getContentObject($hier_id, $pc_id); - if (!is_object($cont_obj)) - { - $this->log->debug("returnToParent"); - $ilCtrl->returnToParent($this); - } - $ctype = $cont_obj->getType(); - } - } - $this->log->debug("step PR: ctype: $ctype"); - } - - - if ($ctype != "media" || !is_object ($cont_obj)) - { - if ($this->getHeader() != "") - { - $this->tpl->setTitle($this->getHeader()); - } - $this->displayLocator(); - } - - $this->cont_obj = $cont_obj; - - - // Step NC (handle empty next class) - $this->ctrl->setParameter($this, "hier_id", $hier_id); - $this->ctrl->setParameter($this, "pc_id", $pc_id); - $this->ctrl->setCmd($cmd); - if ($next_class == "") - { - include_once("./Services/COPage/classes/class.ilCOPagePCDef.php"); - $pc_def = ilCOPagePCDef::getPCDefinitionByType($ctype); - if (is_array($pc_def)) - { - $this->ctrl->setCmdClass($pc_def["pc_gui_class"]); - } - $next_class = $this->ctrl->getNextClass($this); - } - $this->log->debug("step NC: next_class: $next_class"); - - // ... do not do this while imagemap editing is ongoing - // Step IM (handle image map editing) - if ($cmd == "displayPage" && $_POST["editImagemapForward_x"] == "" && $_POST["imagemap_x"] == "") - { - $next_class = ""; - } - $this->log->debug("step IM: next_class: $next_class"); - - - // Step FC (forward command) - $this->log->debug("before FC: next_class:".$next_class.", pc_id:".$pc_id. - ", hier_id:".$hier_id.", ctype:".$ctype.", cmd:".$cmd.", _GET[cmd]: ".$_GET["cmd"]); - switch($next_class) - { - case "ilinternallinkgui": - $link_gui = new ilInternalLinkGUI( - $this->page_gui->getPageConfig()->getIntLinkHelpDefaultType(), - $this->page_gui->getPageConfig()->getIntLinkHelpDefaultId(), - $this->page_gui->getPageConfig()->getIntLinkHelpDefaultIdIsRef()); - $link_gui->setFilterWhiteList( - $this->page_gui->getPageConfig()->getIntLinkFilterWhiteList()); - foreach ($this->page_gui->getPageConfig()->getIntLinkFilters() as $filter) - { - $link_gui->filterLinkType($filter); - } - $link_gui->setReturn($this->int_link_return); - - $ret = $this->ctrl->forwardCommand($link_gui); - break; - - // PC Media Object - case "ilpcmediaobjectgui": - include_once ("./Services/COPage/classes/class.ilPCMediaObjectGUI.php"); - - $this->tabs_gui->clearTargets(); - $this->tabs_gui->setBackTarget($this->page_gui->page_back_title, - $ilCtrl->getLinkTarget($this->page_gui, "edit")); - $pcmob_gui = new ilPCMediaObjectGUI($this->page, $cont_obj, $hier_id, $pc_id); - $pcmob_gui->setStyleId($this->page_gui->getStyleId()); - $pcmob_gui->setSubCmd($ctype); - $pcmob_gui->setEnabledMapAreas($this->page_gui->getPageConfig()->getEnableInternalLinks()); - $ret = $this->ctrl->forwardCommand($pcmob_gui); - $ilHelp->setScreenIdComponent("copg_media"); - break; - - // only for "linked" media - case "ilobjmediaobjectgui": - $this->tabs_gui->clearTargets(); - $this->tabs_gui->setBackTarget($this->lng->txt("back"), - $ilCtrl->getParentReturn($this)); - $mob_gui = new ilObjMediaObjectGUI("", $_GET["mob_id"],false, false); - $mob_gui->getTabs(); - $mob_gui->setEnabledMapAreas($this->page_gui->getPageConfig()->getEnableInternalLinks()); - $this->tpl->setTitle($this->lng->txt("mob").": ". - ilObject::_lookupTitle($_GET["mob_id"])); - $ret = $this->ctrl->forwardCommand($mob_gui); - break; - - // Question - case "ilpcquestiongui": - include_once("./Services/COPage/classes/class.ilPCQuestionGUI.php"); - $pc_question_gui = new ilPCQuestionGUI($this->page, $cont_obj, $hier_id, $pc_id); - $pc_question_gui->setSelfAssessmentMode($this->page_gui->getPageConfig()->getEnableSelfAssessment()); - $pc_question_gui->setPageConfig($this->page_gui->getPageConfig()); - - if ($this->page_gui->getPageConfig()->getEnableSelfAssessment()) - { - $this->tabs_gui->clearTargets(); - $ilHelp->setScreenIdComponent("copg_pcqst"); - $this->tabs_gui->setBackTarget($this->lng->txt("back"), - $ilCtrl->getParentReturn($this)); - $ret = $this->ctrl->forwardCommand($pc_question_gui); - } - else - { - $cmd = $this->ctrl->getCmd(); - $pc_question_gui->$cmd(); - $this->ctrl->redirectByClass(array("ilobjquestionpoolgui", get_class($cont_obj)), "editQuestion"); - } - break; - - // Plugged Component - case "ilpcpluggedgui": - $this->tabs_gui->clearTargets(); - include_once ("./Services/COPage/classes/class.ilPCPluggedGUI.php"); - $plugged_gui = new ilPCPluggedGUI($this->page, $cont_obj, $hier_id, - $add_type, $pc_id); - $ret = $this->ctrl->forwardCommand($plugged_gui); - break; - - default: - - // generic calls to gui classes - include_once("./Services/COPage/classes/class.ilCOPagePCDef.php"); - if (ilCOPagePCDef::isPCGUIClassName($next_class, true)) - { - $this->log->debug("Generic Call"); - $pc_def = ilCOPagePCDef::getPCDefinitionByGUIClassName($next_class); - $this->tabs_gui->clearTargets(); - $this->tabs_gui->setBackTarget($this->page_gui->page_back_title, - $ilCtrl->getLinkTarget($this->page_gui, "edit")); - $ilHelp->setScreenIdComponent("copg_".$pc_def["pc_type"]); - ilCOPagePCDef::requirePCGUIClassByName($pc_def["name"]); - $gui_class_name = $pc_def["pc_gui_class"]; - $pc_gui = new $gui_class_name($this->page, $cont_obj, $hier_id, $pc_id); - if ($pc_def["style_classes"]) - { - $pc_gui->setStyleId($this->page_gui->getStyleId()); - } - $pc_gui->setPageConfig($this->page_gui->getPageConfig()); - $ret = $this->ctrl->forwardCommand($pc_gui); - } - else - { - $this->log->debug("Call ilPageEditorGUI command."); - // cmd belongs to ilPageEditorGUI - - if ($cmd == "pasteFromClipboard") - { - $ret = $this->pasteFromClipboard($hier_id); - } - else if ($cmd == "paste") - { - $ret = $this->paste($hier_id); - } - else - { - $ret = $this->$cmd(); - } - } - break; - - } - - $this->log->debug("end ---"); - - return $ret; - } - - /** - * checks if current user has activated js editing and - * if browser is js capable - */ - static function _doJSEditing() - { - global $DIC; - - $ilUser = $DIC->user(); - - if ($ilUser->getPref("ilPageEditor_JavaScript") != "disable" - && ilPageEditorGUI::_isBrowserJSEditCapable()) - { - return true; - } - return false; - } - - /** - * checks wether browser is javascript editing capable - */ - static function _isBrowserJSEditCapable() - { - return true; - } - - function activatePage() - { - $this->page_gui->activatePage(); - } - - function deactivatePage() - { - $this->page_gui->deactivatePage(); - } - - /** - * set media and editing mode - */ - function setMediaMode() - { - $ilUser = $this->user; - - $ilUser->writePref("ilPageEditor_MediaMode", $_POST["media_mode"]); - $ilUser->writePref("ilPageEditor_HTMLMode", $_POST["html_mode"]); - if ($ilUser->getPref("ilPageEditor_JavaScript") != $_POST["js_mode"]) - { - // not nice, should be solved differently in the future - if ($this->page->getParentType() == "lm") - { - $this->ctrl->setParameterByClass("illmpageobjectgui", "reloadTree", "y"); - } - } - $ilUser->writePref("ilPageEditor_JavaScript", $_POST["js_mode"]); - - // again not so nice... - if ($this->page->getParentType() == "lm") - { - $this->ctrl->redirectByClass("illmpageobjectgui", "edit"); - } - else - { - $this->ctrl->returnToParent($this); - } - } - - /** - * copy linked media object to clipboard - */ - function copyLinkedMediaToClipboard() - { - $ilUser = $this->user; - - ilUtil::sendSuccess($this->lng->txt("copied_to_clipboard"), true); - $ilUser->addObjectToClipboard($_POST["mob_id"], "mob", ilObject::_lookupTitle($_POST["mob_id"])); - $this->ctrl->returnToParent($this); - } - - /** - * copy linked media object to media pool - */ - function copyLinkedMediaToMediaPool() - { - $ilUser = $this->user; - - $this->ctrl->setParameterByClass("ilmediapooltargetselector", "mob_id", $_POST["mob_id"]); - $this->ctrl->redirectByClass("ilmediapooltargetselector", "listPools"); - } - - /** - * add change comment to history - */ - function addChangeComment() - { - include_once("./Services/History/classes/class.ilHistory.php"); - ilHistory::_createEntry($this->page->getId(), "update", - "", $this->page->getParentType().":pg", - ilUtil::stripSlashes($_POST["change_comment"]), true); - ilUtil::sendSuccess($this->lng->txt("cont_added_comment"), true); - $this->ctrl->returnToParent($this); - } - - /** - * Confirm - */ - function deleteSelected() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - $targets = explode(";", $_POST["target"][0]); - - if (count($targets) == 0) - { - ilUtil::sendInfo($lng->txt("no_checkbox"), true); - $this->ctrl->returnToParent($this); - } - else - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("copg_confirm_el_deletion")); - $cgui->setCancel($lng->txt("cancel"), "cancelDeleteSelected"); - $cgui->setConfirm($lng->txt("confirm"), "confirmedDeleteSelected"); - $cgui->addHiddenItem("target", $_POST["target"][0]); - - $tpl->setContent($cgui->getHTML()); - } - } - - /** - * Cancel deletion - * - * @param - * @return - */ - function cancelDeleteSelected() - { - $this->ctrl->returnToParent($this); - } - - - /** - * Delete selected items - */ - function confirmedDeleteSelected() - { - $targets = explode(";", $_POST["target"]); - if (count($targets) > 0) - { - $updated = $this->page->deleteContents($targets, true, - $this->page_gui->getPageConfig()->getEnableSelfAssessment()); - if($updated !== true) - { - $_SESSION["il_pg_error"] = $updated; - } - else - { - unset($_SESSION["il_pg_error"]); - } - } - $this->ctrl->returnToParent($this); - } - - /** - * Copy selected items - */ - function copySelected() - { - $lng = $this->lng; - - if (is_int(strpos($_POST["target"][0], ";"))) - { - $_POST["target"] = explode(";", $_POST["target"][0]); - } - if (is_array($_POST["target"])) - { - $this->page->copyContents($_POST["target"]); - ilUtil::sendSuccess($lng->txt("cont_sel_el_copied_use_paste"), true); - } - $this->ctrl->returnToParent($this); - } - - /** - * Cut selected items - */ - function cutSelected() - { - $lng = $this->lng; - - if (is_int(strpos($_POST["target"][0], ";"))) - { - $_POST["target"] = explode(";", $_POST["target"][0]); - } - if (is_array($_POST["target"])) - { - $updated = $this->page->cutContents($_POST["target"]); - if($updated !== true) - { - $_SESSION["il_pg_error"] = $updated; - } - else - { - unset($_SESSION["il_pg_error"]); - } - ilUtil::sendSuccess($lng->txt("cont_sel_el_cut_use_paste"), true); - } - $this->ctrl->returnToParent($this); - } - - /** - * paste from clipboard (redirects to clipboard) - */ - function paste($a_hier_id) - { - $ilCtrl = $this->ctrl; - $this->page->pasteContents($a_hier_id, $this->page_gui->getPageConfig()->getEnableSelfAssessment()); - include_once("./Modules/LearningModule/classes/class.ilEditClipboard.php"); - //ilEditClipboard::setAction(""); - $this->ctrl->returnToParent($this); - } - - /** - * (de-)activate selected items - */ - function activateSelected() - { - if (is_int(strpos($_POST["target"][0], ";"))) - { - $_POST["target"] = explode(";", $_POST["target"][0]); - } - if (is_array($_POST["target"])) - { - $updated = $this->page->switchEnableMultiple($_POST["target"], true, - $this->page_gui->getPageConfig()->getEnableSelfAssessment()); - if($updated !== true) - { - $_SESSION["il_pg_error"] = $updated; - } - else - { - unset($_SESSION["il_pg_error"]); - } - } - $this->ctrl->returnToParent($this); - } - - /** - * Assign characeristic to text blocks/sections - */ - function assignCharacteristicForm() - { - $tpl = $this->tpl; - $lng = $this->lng; - - if (is_int(strpos($_POST["target"][0], ";"))) - { - $_POST["target"] = explode(";", $_POST["target"][0]); - } - if (is_array($_POST["target"])) - { - $types = array(); - - // check what content element types have been selected - foreach ($_POST["target"] as $t) - { - $tarr = explode(":", $t); - $cont_obj = $this->page->getContentObject($tarr[0], $tarr[1]); - if (is_object($cont_obj) && $cont_obj->getType() == "par") - { - $types["par"] = "par"; - } - if (is_object($cont_obj) && $cont_obj->getType() == "sec") - { - $types["sec"] = "sec"; - } - } - - if (count($types) == 0) - { - ilUtil::sendFailure($lng->txt("cont_select_par_or_section"), true); - $this->ctrl->returnToParent($this); - } - else - { - $this->initCharacteristicForm($_POST["target"], $types); - $tpl->setContent($this->form->getHTML()); - } - } - else - { - $this->ctrl->returnToParent($this); - } - } - - /** - * Init map creation/update form - */ - function initCharacteristicForm($a_target, $a_types) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - - // edit form - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - $this->form->setTitle($this->lng->txt("cont_choose_characteristic")); - - if ($a_types["par"] == "par") - { - $select_prop = new ilSelectInputGUI($this->lng->txt("cont_choose_characteristic_text"), - "char_par"); - include_once("./Services/COPage/classes/class.ilPCParagraphGUI.php"); - $options = ilPCParagraphGUI::_getCharacteristics($this->page_gui->getStyleId()); - $select_prop->setOptions($options); - $this->form->addItem($select_prop); - } - if ($a_types["sec"] == "sec") - { - $select_prop = new ilSelectInputGUI($this->lng->txt("cont_choose_characteristic_section"), - "char_sec"); - include_once("./Services/COPage/classes/class.ilPCSectionGUI.php"); - $options = ilPCSectionGUI::_getCharacteristics($this->page_gui->getStyleId()); - $select_prop->setOptions($options); - $this->form->addItem($select_prop); - } - - foreach ($a_target as $t) - { - $hidden = new ilHiddenInputGUI("target[]"); - $hidden->setValue($t); - $this->form->addItem($hidden); - } - - $this->form->setFormAction($ilCtrl->getFormAction($this)); - $this->form->addCommandButton("assignCharacteristic", $lng->txt("save")); - $this->form->addCommandButton("showPage", $lng->txt("cancel")); - - } - - /** - * Assign characteristic - */ - function assignCharacteristic() - { - $char_par = ilUtil::stripSlashes($_POST["char_par"]); - $char_sec = ilUtil::stripSlashes($_POST["char_sec"]); - if (is_array($_POST["target"])) - { - foreach ($_POST["target"] as $t) - { - $tarr = explode(":", $t); - $cont_obj = $this->page->getContentObject($tarr[0], $tarr[1]); - if (is_object($cont_obj) && $cont_obj->getType() == "par") - { - $cont_obj->setCharacteristic($char_par); - } - if (is_object($cont_obj) && $cont_obj->getType() == "sec") - { - $cont_obj->setCharacteristic($char_sec); - } - } - $updated = $this->page->update(); - if($updated !== true) - { - $_SESSION["il_pg_error"] = $updated; - } - else - { - unset($_SESSION["il_pg_error"]); - } - } - $this->ctrl->returnToParent($this); - } - - /** - * paste from clipboard (redirects to clipboard) - */ - function pasteFromClipboard($a_hier_id) - { - $ilCtrl = $this->ctrl; -//var_dump($a_hier_id); - $ilCtrl->setParameter($this, "hier_id", $a_hier_id); - $ilCtrl->setParameterByClass("ilEditClipboardGUI", "returnCommand", - rawurlencode($ilCtrl->getLinkTarget($this, - "insertFromClipboard", "", false, false))); -//echo ":".$ilCtrl->getLinkTarget($this, "insertFromClipboard").":"; - $ilCtrl->redirectByClass("ilEditClipboardGUI", "getObject"); - } - - /** - * insert object from clipboard - */ - function insertFromClipboard() - { - include_once("./Services/Clipboard/classes/class.ilEditClipboardGUI.php"); - $ids = ilEditClipboardGUI::_getSelectedIDs(); - include_once ("./Services/COPage/classes/class.ilPCMediaObject.php"); - if ($ids != "") - { - foreach ($ids as $id2) - { - $id = explode(":", $id2); - $type = $id[0]; - $id = $id[1]; - if ($type == "mob") - { - $this->content_obj = new ilPCMediaObject($this->page); - $this->content_obj->readMediaObject($id); - $this->content_obj->createAlias($this->page, $_GET["hier_id"]); - $this->updated = $this->page->update(); - } - if ($type == "incl") - { - include_once("./Services/COPage/classes/class.ilPCContentInclude.php"); - $this->content_obj = new ilPCContentInclude($this->page); - $this->content_obj->create($this->page, $_GET["hier_id"]); - $this->content_obj->setContentType("mep"); - $this->content_obj->setContentId($id); - $this->updated = $this->page->update(); - } - } - } - $this->ctrl->returnToParent($this); - } - - /** - * Default for POST reloads and missing - */ - function displayPage() - { - $this->ctrl->returnToParent($this); - } - - /** - * display locator - */ - function displayLocator() - { - /*if(is_object($this->locator)) - { - $this->locator->display(); - }*/ - } - - /** - * Show snippet info - */ - function showSnippetInfo() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilAccess = $this->access; - $ilCtrl = $this->ctrl; - - $stpl = new ilTemplate("tpl.snippet_info.html", true, true, "Services/COPage"); - - include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); - $mep_pools = ilMediaPoolItem::getPoolForItemId($_POST["ci_id"]); - foreach ($mep_pools as $mep_id) - { - $ref_ids = ilObject::_getAllReferences($mep_id); - $edit_link = false; - foreach ($ref_ids as $rid) - { - if (!$edit_link && $ilAccess->checkAccess("write", "", $rid)) - { - $stpl->setCurrentBlock("edit_link"); - $stpl->setVariable("TXT_EDIT", $lng->txt("edit")); - $stpl->setVariable("HREF_EDIT", - "./goto.php?target=mep_".$rid); - $stpl->parseCurrentBlock(); - } - } - $stpl->setCurrentBlock("pool"); - $stpl->setVariable("TXT_MEDIA_POOL", $lng->txt("obj_mep")); - $stpl->setVariable("VAL_MEDIA_POOL", ilObject::_lookupTitle($mep_id)); - $stpl->parseCurrentBlock(); - } - - include_once("./Modules/MediaPool/classes/class.ilMediaPoolPage.php"); - $stpl->setVariable("TXT_TITLE", $lng->txt("title")); - $stpl->setVariable("VAL_TITLE", ilMediaPoolPage::lookupTitle($_POST["ci_id"])); - $stpl->setVariable("TXT_BACK", $lng->txt("back")); - $stpl->setVariable("HREF_BACK", - $ilCtrl->getLinkTarget($this->page_gui, "edit")); - $tpl->setContent($stpl->get()); - } - + /** + * @var ilTabsGUI + */ + protected $tabs_gui; + + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilAccessHandler + */ + protected $access; + + public $tpl; + public $lng; + public $ctrl; + public $objDefinition; + public $page; + public $target_script; + public $return_location; + public $header; + public $tabs; + public $cont_obj; + public $enable_keywords; + public $enable_anchors; + + /** + * @var ilLogger + */ + protected $log; + + /** + * Constructor + * + * @param object $a_page_object page object + * @access public + */ + public function __construct(&$a_page_object, &$a_page_object_gui) + { + global $DIC; + + $this->help = $DIC["ilHelp"]; + $this->user = $DIC->user(); + $this->access = $DIC->access(); + $tpl = $DIC["tpl"]; + $lng = $DIC->language(); + $objDefinition = $DIC["objDefinition"]; + $ilCtrl = $DIC->ctrl(); + $ilTabs = $DIC->tabs(); + + $this->log = ilLoggerFactory::getLogger('copg'); + + // initiate variables + $this->ctrl = $ilCtrl; + $this->tpl = $tpl; + $this->lng = $lng; + $this->objDefinition = $objDefinition; + $this->tabs_gui = $ilTabs; + $this->page = $a_page_object; + $this->page_gui = $a_page_object_gui; + + $this->ctrl->saveParameter($this, array("hier_id", "pc_id")); + } + + + /** + * set header title + * + * @param string $a_header header title + */ + public function setHeader($a_header) + { + $this->header = $a_header; + } + + /** + * get header title + * + * @return string header title + */ + public function getHeader() + { + return $this->header; + } + + /** + * set locator object + * + * @param object $a_locator locator object + */ + public function setLocator(&$a_locator) + { + $this->locator = $a_locator; + } + + /** + * redirect to parent context + */ + public function returnToContext() + { + $this->ctrl->returnToParent($this); + } + + public function setIntLinkReturn($a_return) + { + $this->int_link_return = $a_return; + } + + + public function setPageBackTitle($a_title) + { + $this->page_back_title = $a_title; + } + + /** + * execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $ilHelp = $this->help; + + $this->log->debug("begin ============"); + + // Step BC (basic command determination) + // determine cmd, cmdClass, hier_id and pc_id + $cmd = $this->ctrl->getCmd("displayPage"); + $cmdClass = strtolower($this->ctrl->getCmdClass()); + + $hier_id = $_GET["hier_id"]; + $pc_id = $_GET["pc_id"]; + if (isset($_POST["new_hier_id"])) { + $hier_id = $_POST["new_hier_id"]; + } + + $new_type = (isset($_GET["new_type"])) + ? $_GET["new_type"] + : $_POST["new_type"]; + + $this->log->debug("step BC: cmd:$cmd, cmdClass:$cmdClass, hier_id: $hier_id, pc_id: $pc_id"); + + // Step EC (exec_ command handling) + // handle special exec_ commands, modify pc, hier_id + if (substr($cmd, 0, 5) == "exec_") { + // check whether pc id is given + $pca = explode(":", key($_POST["cmd"])); + $pc_id = $pca[1]; + $cmd = explode("_", $pca[0]); + unset($cmd[0]); + $hier_id = implode($cmd, "_"); + $cmd = $_POST["command" . $hier_id]; + } + $this->log->debug("step EC: cmd:$cmd, hier_id: $hier_id, pc_id: $pc_id"); + + // Step CC (handle table container (and similar) commands + // ... strip "c" "r" of table ids from hierarchical id + $first_hier_character = substr($hier_id, 0, 1); + if ($first_hier_character == "c" || + $first_hier_character == "r" || + $first_hier_character == "g" || + $first_hier_character == "i") { + $hier_id = substr($hier_id, 1); + } + $this->log->debug("step CC: cmd:$cmd, hier_id: $hier_id, pc_id: $pc_id"); + + // Step B (build dom, and ids in XML) + $this->page->buildDom(); + $this->page->addHierIDs(); + + + // Step CS (strip base command) + if ($cmdClass != "ilfilesystemgui") { + $com = explode("_", $cmd); + $cmd = $com[0]; + } + $this->log->debug("step CS: cmd:$cmd"); + + + // Step NC (determine next class) + $next_class = $this->ctrl->getNextClass($this); + $this->log->debug("step NC: next class: " . $next_class); + + + // Step PH (placeholder handling, placeholders from preview mode come without hier_id) + if ($next_class == "ilpcplaceholdergui" && $hier_id == "" && $_GET["pl_pc_id"] != "") { + $hid = $this->page->getHierIdsForPCIds(array($_GET["pl_pc_id"])); + $hier_id = $hid[$_GET["pl_pc_id"]]; + } + $this->log->debug("step PH: next class: " . $next_class); + + if ($com[0] == "insert" || $com[0] == "create") { + // Step CM (creation mode handling) + $cmd = $com[0]; + $ctype = $com[1]; // note ctype holds type if cmdclass is empty, but also subcommands if not (e.g. applyFilter in ilpcmediaobjectgui) + $add_type = $com[2]; + if ($ctype == "mob") { + $ctype = "media"; + } + + $this->log->debug("step CM: cmd: " . $cmd . ", ctype: " . $ctype . ", add_type: " . $add_type); + } else { + // Step LM (setting cmd and cmdclass for editing of linked media) + if ($cmd == "editLinkedMedia") { + $this->ctrl->setCmd("edit"); + $cmd = "edit"; + $_GET["pgEdMediaMode"] = "editLinkedMedia"; + $_GET["mob_id"] = $_POST["mob_id"]; + } + if ($_GET["pgEdMediaMode"] == "editLinkedMedia") { + $this->ctrl->setParameter($this, "pgEdMediaMode", "editLinkedMedia"); + $this->ctrl->setParameter($this, "mob_id", $_GET["mob_id"]); + if ($cmdClass != "ilinternallinkgui" && $cmdClass != "ilmdeditorgui" + && $cmdClass != "ilimagemapeditorgui" && $cmdClass != "ilfilesystemgui") { + $this->ctrl->setCmdClass("ilobjmediaobjectgui"); + $cmdClass = "ilobjmediaobjectgui"; + } + } + $this->log->debug("step LM: cmd: " . $cmd . ", cmdClass: " . $cmdClass); + + + // Step PR (get content object and return to parent) + $this->log->debug("before PR: cmdClass: $cmdClass, nextClass: $next_class" . + ", hier_id: " . $hier_id . ", pc_id: " . $pc_id . ")"); + // note: ilinternallinkgui for page: no cont_obj is received + // ilinternallinkgui for mob: cont_obj is received + if ($cmd != "insertFromClipboard" && $cmd != "pasteFromClipboard" && + $cmd != "setMediaMode" && $cmd != "copyLinkedMediaToClipboard" && + $cmd != "activatePage" && $cmd != "deactivatePage" && + $cmd != "copyLinkedMediaToMediaPool" && $cmd != "showSnippetInfo" && + $cmd != "deleteSelected" && $cmd != "paste" && + $cmd != "cancelDeleteSelected" && $cmd != "confirmedDeleteSelected" && + $cmd != "copySelected" && $cmd != "cutSelected" && + ($cmd != "displayPage" || $_POST["editImagemapForward_x"] != "" || $_POST["imagemap_x"] != "") && + ($cmd != "displayPage" || $_POST["editImagemapForward_x"] != "") && + $cmd != "activateSelected" && $cmd != "assignCharacteristicForm" && + $cmd != "assignCharacteristic" && + $cmdClass != "ilrepositoryselector2inputgui" && + $cmd != "cancelCreate" && $cmd != "popup" && + $cmdClass != "ileditclipboardgui" && $cmd != "addChangeComment" && + ($cmdClass != "ilinternallinkgui" || ($next_class == "ilpcmediaobjectgui"))) { + if ($_GET["pgEdMediaMode"] != "editLinkedMedia") { + $cont_obj = $this->page->getContentObject($hier_id, $pc_id); + if (!is_object($cont_obj)) { + $this->log->debug("returnToParent"); + $ilCtrl->returnToParent($this); + } + $ctype = $cont_obj->getType(); + } + } + $this->log->debug("step PR: ctype: $ctype"); + } + + + if ($ctype != "media" || !is_object($cont_obj)) { + if ($this->getHeader() != "") { + $this->tpl->setTitle($this->getHeader()); + } + $this->displayLocator(); + } + + $this->cont_obj = $cont_obj; + + + // Step NC (handle empty next class) + $this->ctrl->setParameter($this, "hier_id", $hier_id); + $this->ctrl->setParameter($this, "pc_id", $pc_id); + $this->ctrl->setCmd($cmd); + if ($next_class == "") { + include_once("./Services/COPage/classes/class.ilCOPagePCDef.php"); + $pc_def = ilCOPagePCDef::getPCDefinitionByType($ctype); + if (is_array($pc_def)) { + $this->ctrl->setCmdClass($pc_def["pc_gui_class"]); + } + $next_class = $this->ctrl->getNextClass($this); + } + $this->log->debug("step NC: next_class: $next_class"); + + // ... do not do this while imagemap editing is ongoing + // Step IM (handle image map editing) + if ($cmd == "displayPage" && $_POST["editImagemapForward_x"] == "" && $_POST["imagemap_x"] == "") { + $next_class = ""; + } + $this->log->debug("step IM: next_class: $next_class"); + + + // Step FC (forward command) + $this->log->debug("before FC: next_class:" . $next_class . ", pc_id:" . $pc_id . + ", hier_id:" . $hier_id . ", ctype:" . $ctype . ", cmd:" . $cmd . ", _GET[cmd]: " . $_GET["cmd"]); + switch ($next_class) { + case "ilinternallinkgui": + $link_gui = new ilInternalLinkGUI( + $this->page_gui->getPageConfig()->getIntLinkHelpDefaultType(), + $this->page_gui->getPageConfig()->getIntLinkHelpDefaultId(), + $this->page_gui->getPageConfig()->getIntLinkHelpDefaultIdIsRef() + ); + $link_gui->setFilterWhiteList( + $this->page_gui->getPageConfig()->getIntLinkFilterWhiteList() + ); + foreach ($this->page_gui->getPageConfig()->getIntLinkFilters() as $filter) { + $link_gui->filterLinkType($filter); + } + $link_gui->setReturn($this->int_link_return); + + $ret = $this->ctrl->forwardCommand($link_gui); + break; + + // PC Media Object + case "ilpcmediaobjectgui": + include_once("./Services/COPage/classes/class.ilPCMediaObjectGUI.php"); + + $this->tabs_gui->clearTargets(); + $this->tabs_gui->setBackTarget( + $this->page_gui->page_back_title, + $ilCtrl->getLinkTarget($this->page_gui, "edit") + ); + $pcmob_gui = new ilPCMediaObjectGUI($this->page, $cont_obj, $hier_id, $pc_id); + $pcmob_gui->setStyleId($this->page_gui->getStyleId()); + $pcmob_gui->setSubCmd($ctype); + $pcmob_gui->setEnabledMapAreas($this->page_gui->getPageConfig()->getEnableInternalLinks()); + $ret = $this->ctrl->forwardCommand($pcmob_gui); + $ilHelp->setScreenIdComponent("copg_media"); + break; + + // only for "linked" media + case "ilobjmediaobjectgui": + $this->tabs_gui->clearTargets(); + $this->tabs_gui->setBackTarget( + $this->lng->txt("back"), + $ilCtrl->getParentReturn($this) + ); + $mob_gui = new ilObjMediaObjectGUI("", $_GET["mob_id"], false, false); + $mob_gui->getTabs(); + $mob_gui->setEnabledMapAreas($this->page_gui->getPageConfig()->getEnableInternalLinks()); + $this->tpl->setTitle($this->lng->txt("mob") . ": " . + ilObject::_lookupTitle($_GET["mob_id"])); + $ret = $this->ctrl->forwardCommand($mob_gui); + break; + + // Question + case "ilpcquestiongui": + include_once("./Services/COPage/classes/class.ilPCQuestionGUI.php"); + $pc_question_gui = new ilPCQuestionGUI($this->page, $cont_obj, $hier_id, $pc_id); + $pc_question_gui->setSelfAssessmentMode($this->page_gui->getPageConfig()->getEnableSelfAssessment()); + $pc_question_gui->setPageConfig($this->page_gui->getPageConfig()); + + if ($this->page_gui->getPageConfig()->getEnableSelfAssessment()) { + $this->tabs_gui->clearTargets(); + $ilHelp->setScreenIdComponent("copg_pcqst"); + $this->tabs_gui->setBackTarget( + $this->lng->txt("back"), + $ilCtrl->getParentReturn($this) + ); + $ret = $this->ctrl->forwardCommand($pc_question_gui); + } else { + $cmd = $this->ctrl->getCmd(); + $pc_question_gui->$cmd(); + $this->ctrl->redirectByClass(array("ilobjquestionpoolgui", get_class($cont_obj)), "editQuestion"); + } + break; + + // Plugged Component + case "ilpcpluggedgui": + $this->tabs_gui->clearTargets(); + include_once("./Services/COPage/classes/class.ilPCPluggedGUI.php"); + $plugged_gui = new ilPCPluggedGUI( + $this->page, + $cont_obj, + $hier_id, + $add_type, + $pc_id + ); + $ret = $this->ctrl->forwardCommand($plugged_gui); + break; + + default: + + // generic calls to gui classes + include_once("./Services/COPage/classes/class.ilCOPagePCDef.php"); + if (ilCOPagePCDef::isPCGUIClassName($next_class, true)) { + $this->log->debug("Generic Call"); + $pc_def = ilCOPagePCDef::getPCDefinitionByGUIClassName($next_class); + $this->tabs_gui->clearTargets(); + $this->tabs_gui->setBackTarget( + $this->page_gui->page_back_title, + $ilCtrl->getLinkTarget($this->page_gui, "edit") + ); + $ilHelp->setScreenIdComponent("copg_" . $pc_def["pc_type"]); + ilCOPagePCDef::requirePCGUIClassByName($pc_def["name"]); + $gui_class_name = $pc_def["pc_gui_class"]; + $pc_gui = new $gui_class_name($this->page, $cont_obj, $hier_id, $pc_id); + if ($pc_def["style_classes"]) { + $pc_gui->setStyleId($this->page_gui->getStyleId()); + } + $pc_gui->setPageConfig($this->page_gui->getPageConfig()); + $ret = $this->ctrl->forwardCommand($pc_gui); + } else { + $this->log->debug("Call ilPageEditorGUI command."); + // cmd belongs to ilPageEditorGUI + + if ($cmd == "pasteFromClipboard") { + $ret = $this->pasteFromClipboard($hier_id); + } elseif ($cmd == "paste") { + $ret = $this->paste($hier_id); + } else { + $ret = $this->$cmd(); + } + } + break; + + } + + $this->log->debug("end ---"); + + return $ret; + } + + /** + * checks if current user has activated js editing and + * if browser is js capable + */ + public static function _doJSEditing() + { + global $DIC; + + $ilUser = $DIC->user(); + + if ($ilUser->getPref("ilPageEditor_JavaScript") != "disable" + && ilPageEditorGUI::_isBrowserJSEditCapable()) { + return true; + } + return false; + } + + /** + * checks wether browser is javascript editing capable + */ + public static function _isBrowserJSEditCapable() + { + return true; + } + + public function activatePage() + { + $this->page_gui->activatePage(); + } + + public function deactivatePage() + { + $this->page_gui->deactivatePage(); + } + + /** + * set media and editing mode + */ + public function setMediaMode() + { + $ilUser = $this->user; + + $ilUser->writePref("ilPageEditor_MediaMode", $_POST["media_mode"]); + $ilUser->writePref("ilPageEditor_HTMLMode", $_POST["html_mode"]); + if ($ilUser->getPref("ilPageEditor_JavaScript") != $_POST["js_mode"]) { + // not nice, should be solved differently in the future + if ($this->page->getParentType() == "lm") { + $this->ctrl->setParameterByClass("illmpageobjectgui", "reloadTree", "y"); + } + } + $ilUser->writePref("ilPageEditor_JavaScript", $_POST["js_mode"]); + + // again not so nice... + if ($this->page->getParentType() == "lm") { + $this->ctrl->redirectByClass("illmpageobjectgui", "edit"); + } else { + $this->ctrl->returnToParent($this); + } + } + + /** + * copy linked media object to clipboard + */ + public function copyLinkedMediaToClipboard() + { + $ilUser = $this->user; + + ilUtil::sendSuccess($this->lng->txt("copied_to_clipboard"), true); + $ilUser->addObjectToClipboard($_POST["mob_id"], "mob", ilObject::_lookupTitle($_POST["mob_id"])); + $this->ctrl->returnToParent($this); + } + + /** + * copy linked media object to media pool + */ + public function copyLinkedMediaToMediaPool() + { + $ilUser = $this->user; + + $this->ctrl->setParameterByClass("ilmediapooltargetselector", "mob_id", $_POST["mob_id"]); + $this->ctrl->redirectByClass("ilmediapooltargetselector", "listPools"); + } + + /** + * add change comment to history + */ + public function addChangeComment() + { + include_once("./Services/History/classes/class.ilHistory.php"); + ilHistory::_createEntry( + $this->page->getId(), + "update", + "", + $this->page->getParentType() . ":pg", + ilUtil::stripSlashes($_POST["change_comment"]), + true + ); + ilUtil::sendSuccess($this->lng->txt("cont_added_comment"), true); + $this->ctrl->returnToParent($this); + } + + /** + * Confirm + */ + public function deleteSelected() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + $targets = explode(";", $_POST["target"][0]); + + if (count($targets) == 0) { + ilUtil::sendInfo($lng->txt("no_checkbox"), true); + $this->ctrl->returnToParent($this); + } else { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("copg_confirm_el_deletion")); + $cgui->setCancel($lng->txt("cancel"), "cancelDeleteSelected"); + $cgui->setConfirm($lng->txt("confirm"), "confirmedDeleteSelected"); + $cgui->addHiddenItem("target", $_POST["target"][0]); + + $tpl->setContent($cgui->getHTML()); + } + } + + /** + * Cancel deletion + * + * @param + * @return + */ + public function cancelDeleteSelected() + { + $this->ctrl->returnToParent($this); + } + + + /** + * Delete selected items + */ + public function confirmedDeleteSelected() + { + $targets = explode(";", $_POST["target"]); + if (count($targets) > 0) { + $updated = $this->page->deleteContents( + $targets, + true, + $this->page_gui->getPageConfig()->getEnableSelfAssessment() + ); + if ($updated !== true) { + $_SESSION["il_pg_error"] = $updated; + } else { + unset($_SESSION["il_pg_error"]); + } + } + $this->ctrl->returnToParent($this); + } + + /** + * Copy selected items + */ + public function copySelected() + { + $lng = $this->lng; + + if (is_int(strpos($_POST["target"][0], ";"))) { + $_POST["target"] = explode(";", $_POST["target"][0]); + } + if (is_array($_POST["target"])) { + $this->page->copyContents($_POST["target"]); + ilUtil::sendSuccess($lng->txt("cont_sel_el_copied_use_paste"), true); + } + $this->ctrl->returnToParent($this); + } + + /** + * Cut selected items + */ + public function cutSelected() + { + $lng = $this->lng; + + if (is_int(strpos($_POST["target"][0], ";"))) { + $_POST["target"] = explode(";", $_POST["target"][0]); + } + if (is_array($_POST["target"])) { + $updated = $this->page->cutContents($_POST["target"]); + if ($updated !== true) { + $_SESSION["il_pg_error"] = $updated; + } else { + unset($_SESSION["il_pg_error"]); + } + ilUtil::sendSuccess($lng->txt("cont_sel_el_cut_use_paste"), true); + } + $this->ctrl->returnToParent($this); + } + + /** + * paste from clipboard (redirects to clipboard) + */ + public function paste($a_hier_id) + { + $ilCtrl = $this->ctrl; + $this->page->pasteContents($a_hier_id, $this->page_gui->getPageConfig()->getEnableSelfAssessment()); + include_once("./Modules/LearningModule/classes/class.ilEditClipboard.php"); + //ilEditClipboard::setAction(""); + $this->ctrl->returnToParent($this); + } + + /** + * (de-)activate selected items + */ + public function activateSelected() + { + if (is_int(strpos($_POST["target"][0], ";"))) { + $_POST["target"] = explode(";", $_POST["target"][0]); + } + if (is_array($_POST["target"])) { + $updated = $this->page->switchEnableMultiple( + $_POST["target"], + true, + $this->page_gui->getPageConfig()->getEnableSelfAssessment() + ); + if ($updated !== true) { + $_SESSION["il_pg_error"] = $updated; + } else { + unset($_SESSION["il_pg_error"]); + } + } + $this->ctrl->returnToParent($this); + } + + /** + * Assign characeristic to text blocks/sections + */ + public function assignCharacteristicForm() + { + $tpl = $this->tpl; + $lng = $this->lng; + + if (is_int(strpos($_POST["target"][0], ";"))) { + $_POST["target"] = explode(";", $_POST["target"][0]); + } + if (is_array($_POST["target"])) { + $types = array(); + + // check what content element types have been selected + foreach ($_POST["target"] as $t) { + $tarr = explode(":", $t); + $cont_obj = $this->page->getContentObject($tarr[0], $tarr[1]); + if (is_object($cont_obj) && $cont_obj->getType() == "par") { + $types["par"] = "par"; + } + if (is_object($cont_obj) && $cont_obj->getType() == "sec") { + $types["sec"] = "sec"; + } + } + + if (count($types) == 0) { + ilUtil::sendFailure($lng->txt("cont_select_par_or_section"), true); + $this->ctrl->returnToParent($this); + } else { + $this->initCharacteristicForm($_POST["target"], $types); + $tpl->setContent($this->form->getHTML()); + } + } else { + $this->ctrl->returnToParent($this); + } + } + + /** + * Init map creation/update form + */ + public function initCharacteristicForm($a_target, $a_types) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + + // edit form + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + $this->form->setTitle($this->lng->txt("cont_choose_characteristic")); + + if ($a_types["par"] == "par") { + $select_prop = new ilSelectInputGUI( + $this->lng->txt("cont_choose_characteristic_text"), + "char_par" + ); + include_once("./Services/COPage/classes/class.ilPCParagraphGUI.php"); + $options = ilPCParagraphGUI::_getCharacteristics($this->page_gui->getStyleId()); + $select_prop->setOptions($options); + $this->form->addItem($select_prop); + } + if ($a_types["sec"] == "sec") { + $select_prop = new ilSelectInputGUI( + $this->lng->txt("cont_choose_characteristic_section"), + "char_sec" + ); + include_once("./Services/COPage/classes/class.ilPCSectionGUI.php"); + $options = ilPCSectionGUI::_getCharacteristics($this->page_gui->getStyleId()); + $select_prop->setOptions($options); + $this->form->addItem($select_prop); + } + + foreach ($a_target as $t) { + $hidden = new ilHiddenInputGUI("target[]"); + $hidden->setValue($t); + $this->form->addItem($hidden); + } + + $this->form->setFormAction($ilCtrl->getFormAction($this)); + $this->form->addCommandButton("assignCharacteristic", $lng->txt("save")); + $this->form->addCommandButton("showPage", $lng->txt("cancel")); + } + + /** + * Assign characteristic + */ + public function assignCharacteristic() + { + $char_par = ilUtil::stripSlashes($_POST["char_par"]); + $char_sec = ilUtil::stripSlashes($_POST["char_sec"]); + if (is_array($_POST["target"])) { + foreach ($_POST["target"] as $t) { + $tarr = explode(":", $t); + $cont_obj = $this->page->getContentObject($tarr[0], $tarr[1]); + if (is_object($cont_obj) && $cont_obj->getType() == "par") { + $cont_obj->setCharacteristic($char_par); + } + if (is_object($cont_obj) && $cont_obj->getType() == "sec") { + $cont_obj->setCharacteristic($char_sec); + } + } + $updated = $this->page->update(); + if ($updated !== true) { + $_SESSION["il_pg_error"] = $updated; + } else { + unset($_SESSION["il_pg_error"]); + } + } + $this->ctrl->returnToParent($this); + } + + /** + * paste from clipboard (redirects to clipboard) + */ + public function pasteFromClipboard($a_hier_id) + { + $ilCtrl = $this->ctrl; + //var_dump($a_hier_id); + $ilCtrl->setParameter($this, "hier_id", $a_hier_id); + $ilCtrl->setParameterByClass( + "ilEditClipboardGUI", + "returnCommand", + rawurlencode($ilCtrl->getLinkTarget( + $this, + "insertFromClipboard", + "", + false, + false + )) + ); + //echo ":".$ilCtrl->getLinkTarget($this, "insertFromClipboard").":"; + $ilCtrl->redirectByClass("ilEditClipboardGUI", "getObject"); + } + + /** + * insert object from clipboard + */ + public function insertFromClipboard() + { + include_once("./Services/Clipboard/classes/class.ilEditClipboardGUI.php"); + $ids = ilEditClipboardGUI::_getSelectedIDs(); + include_once("./Services/COPage/classes/class.ilPCMediaObject.php"); + if ($ids != "") { + foreach ($ids as $id2) { + $id = explode(":", $id2); + $type = $id[0]; + $id = $id[1]; + if ($type == "mob") { + $this->content_obj = new ilPCMediaObject($this->page); + $this->content_obj->readMediaObject($id); + $this->content_obj->createAlias($this->page, $_GET["hier_id"]); + $this->updated = $this->page->update(); + } + if ($type == "incl") { + include_once("./Services/COPage/classes/class.ilPCContentInclude.php"); + $this->content_obj = new ilPCContentInclude($this->page); + $this->content_obj->create($this->page, $_GET["hier_id"]); + $this->content_obj->setContentType("mep"); + $this->content_obj->setContentId($id); + $this->updated = $this->page->update(); + } + } + } + $this->ctrl->returnToParent($this); + } + + /** + * Default for POST reloads and missing + */ + public function displayPage() + { + $this->ctrl->returnToParent($this); + } + + /** + * display locator + */ + public function displayLocator() + { + /*if(is_object($this->locator)) + { + $this->locator->display(); + }*/ + } + + /** + * Show snippet info + */ + public function showSnippetInfo() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilAccess = $this->access; + $ilCtrl = $this->ctrl; + + $stpl = new ilTemplate("tpl.snippet_info.html", true, true, "Services/COPage"); + + include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); + $mep_pools = ilMediaPoolItem::getPoolForItemId($_POST["ci_id"]); + foreach ($mep_pools as $mep_id) { + $ref_ids = ilObject::_getAllReferences($mep_id); + $edit_link = false; + foreach ($ref_ids as $rid) { + if (!$edit_link && $ilAccess->checkAccess("write", "", $rid)) { + $stpl->setCurrentBlock("edit_link"); + $stpl->setVariable("TXT_EDIT", $lng->txt("edit")); + $stpl->setVariable( + "HREF_EDIT", + "./goto.php?target=mep_" . $rid + ); + $stpl->parseCurrentBlock(); + } + } + $stpl->setCurrentBlock("pool"); + $stpl->setVariable("TXT_MEDIA_POOL", $lng->txt("obj_mep")); + $stpl->setVariable("VAL_MEDIA_POOL", ilObject::_lookupTitle($mep_id)); + $stpl->parseCurrentBlock(); + } + + include_once("./Modules/MediaPool/classes/class.ilMediaPoolPage.php"); + $stpl->setVariable("TXT_TITLE", $lng->txt("title")); + $stpl->setVariable("VAL_TITLE", ilMediaPoolPage::lookupTitle($_POST["ci_id"])); + $stpl->setVariable("TXT_BACK", $lng->txt("back")); + $stpl->setVariable( + "HREF_BACK", + $ilCtrl->getLinkTarget($this->page_gui, "edit") + ); + $tpl->setContent($stpl->get()); + } } -?> diff --git a/Services/COPage/classes/class.ilPageEditorSettings.php b/Services/COPage/classes/class.ilPageEditorSettings.php index e4c8140c71e277f23cc11971e12bb7a16afd75b3..765c35d57a6ffaa0f09e1bab78dd0dc29bce3069 100644 --- a/Services/COPage/classes/class.ilPageEditorSettings.php +++ b/Services/COPage/classes/class.ilPageEditorSettings.php @@ -10,89 +10,85 @@ */ class ilPageEditorSettings { - // settings groups. each group contains one or multiple - // page parent types - protected static $option_groups = array( - "lm" => array("lm"), - "wiki" => array("wpg"), - "scorm" => array("sahs"), - "glo" => array("gdf"), - "test" => array("qpl"), - "rep" => array("root", "cat", "grp", "crs", "fold"), - "copa" => array("copa"), - ); - - /** - * Get all settings groups - */ - static function getGroups() - { - return self::$option_groups; - } - - /** - * Write Setting - */ - static function writeSetting($a_grp, $a_name, $a_value) - { - global $DIC; + // settings groups. each group contains one or multiple + // page parent types + protected static $option_groups = array( + "lm" => array("lm"), + "wiki" => array("wpg"), + "scorm" => array("sahs"), + "glo" => array("gdf"), + "test" => array("qpl"), + "rep" => array("root", "cat", "grp", "crs", "fold"), + "copa" => array("copa"), + ); + + /** + * Get all settings groups + */ + public static function getGroups() + { + return self::$option_groups; + } + + /** + * Write Setting + */ + public static function writeSetting($a_grp, $a_name, $a_value) + { + global $DIC; - $ilDB = $DIC->database(); - - $ilDB->manipulate("DELETE FROM page_editor_settings WHERE ". - "settings_grp = ".$ilDB->quote($a_grp, "text"). - " AND name = ".$ilDB->quote($a_name, "text") - ); - - $ilDB->manipulate("INSERT INTO page_editor_settings ". - "(settings_grp, name, value) VALUES (". - $ilDB->quote($a_grp, "text").",". - $ilDB->quote($a_name, "text").",". - $ilDB->quote($a_value, "text"). - ")"); - } - - /** - * Lookup setting - */ - static function lookupSetting($a_grp, $a_name, $a_default = false) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT value FROM page_editor_settings ". - " WHERE settings_grp = ".$ilDB->quote($a_grp, "text"). - " AND name = ".$ilDB->quote($a_name, "text") - ); - if ($rec = $ilDB->fetchAssoc($set)) - { - return $rec["value"]; - } - - return $a_default; - } - - /** - * Lookup setting by parent type - */ - static function lookupSettingByParentType($a_par_type, $a_name, $a_default = false) - { - foreach(self::$option_groups as $g => $types) - { - if (in_array($a_par_type, $types)) - { - $grp = $g; - } - } - - if ($grp != "") - { - return ilPageEditorSettings::lookupSetting($grp, $a_name, $a_default); - } - - return $a_default; - } + $ilDB = $DIC->database(); + + $ilDB->manipulate( + "DELETE FROM page_editor_settings WHERE " . + "settings_grp = " . $ilDB->quote($a_grp, "text") . + " AND name = " . $ilDB->quote($a_name, "text") + ); + + $ilDB->manipulate("INSERT INTO page_editor_settings " . + "(settings_grp, name, value) VALUES (" . + $ilDB->quote($a_grp, "text") . "," . + $ilDB->quote($a_name, "text") . "," . + $ilDB->quote($a_value, "text") . + ")"); + } + + /** + * Lookup setting + */ + public static function lookupSetting($a_grp, $a_name, $a_default = false) + { + global $DIC; + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT value FROM page_editor_settings " . + " WHERE settings_grp = " . $ilDB->quote($a_grp, "text") . + " AND name = " . $ilDB->quote($a_name, "text") + ); + if ($rec = $ilDB->fetchAssoc($set)) { + return $rec["value"]; + } + + return $a_default; + } + + /** + * Lookup setting by parent type + */ + public static function lookupSettingByParentType($a_par_type, $a_name, $a_default = false) + { + foreach (self::$option_groups as $g => $types) { + if (in_array($a_par_type, $types)) { + $grp = $g; + } + } + + if ($grp != "") { + return ilPageEditorSettings::lookupSetting($grp, $a_name, $a_default); + } + + return $a_default; + } } -?> \ No newline at end of file diff --git a/Services/COPage/classes/class.ilPageHistoryTableGUI.php b/Services/COPage/classes/class.ilPageHistoryTableGUI.php index f0875ebc36a6bba226b5b1198ba1cd2b90ca3ad6..549396f36ef485f748486ca26d5f867a049b0c6c 100755 --- a/Services/COPage/classes/class.ilPageHistoryTableGUI.php +++ b/Services/COPage/classes/class.ilPageHistoryTableGUI.php @@ -13,125 +13,122 @@ include_once("Services/Table/classes/class.ilTable2GUI.php"); */ class ilPageHistoryTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - function __construct($a_parent_obj, $a_parent_cmd = "") - { - global $DIC; + public function __construct($a_parent_obj, $a_parent_cmd = "") + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); - $this->setId("ilCOPgHistoryTable"); - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setTitle($lng->txt("content_page_history")); - - $this->addColumn("", "", "1"); - $this->addColumn("", "", "1"); - $this->addColumn($lng->txt("date"), "", "33%"); - $this->addColumn($lng->txt("user"), "", "33%"); - $this->addColumn($lng->txt("action"), "", "33%"); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.page_history_row.html", "Services/COPage"); - $this->setDefaultOrderField("sortkey"); - $this->setDefaultOrderDirection("desc"); - $this->addMultiCommand("compareVersion", $lng->txt("cont_page_compare")); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - } - - /** - * Should this field be sorted numeric? - * - * @return boolean numeric ordering; default is false - */ - function numericOrdering($a_field) - { - if ($a_field == "sortkey") - { - return true; - } - return false; - } + $this->setId("ilCOPgHistoryTable"); + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setTitle($lng->txt("content_page_history")); + + $this->addColumn("", "", "1"); + $this->addColumn("", "", "1"); + $this->addColumn($lng->txt("date"), "", "33%"); + $this->addColumn($lng->txt("user"), "", "33%"); + $this->addColumn($lng->txt("action"), "", "33%"); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.page_history_row.html", "Services/COPage"); + $this->setDefaultOrderField("sortkey"); + $this->setDefaultOrderDirection("desc"); + $this->addMultiCommand("compareVersion", $lng->txt("cont_page_compare")); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + } + + /** + * Should this field be sorted numeric? + * + * @return boolean numeric ordering; default is false + */ + public function numericOrdering($a_field) + { + if ($a_field == "sortkey") { + 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; - $ilAccess = $this->access; + /** + * Standard Version of Fill Row. Most likely to + * be overwritten by derived class. + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; - // rollback command - if ($a_set["nr"] > 0) - { - $ilCtrl->setParameter($this->getParentObject(), "old_nr", $a_set["nr"]); - $this->tpl->setCurrentBlock("command"); - $this->tpl->setVariable("TXT_COMMAND", $lng->txt("cont_rollback")); - $this->tpl->setVariable("HREF_COMMAND", - $ilCtrl->getLinkTarget($this->getParentObject(), "rollbackConfirmation")); - $this->tpl->parseCurrentBlock(); - $ilCtrl->setParameter($this->getParentObject(), "old_nr", ""); - } - - if (!$this->rselect) - { - $this->tpl->setVariable("RSELECT", 'checked="checked"'); - $this->rselect = true; - } - else if (!$this->lselect) - { - $this->tpl->setVariable("LSELECT", 'checked="checked"'); - $this->lselect = true; - } + // rollback command + if ($a_set["nr"] > 0) { + $ilCtrl->setParameter($this->getParentObject(), "old_nr", $a_set["nr"]); + $this->tpl->setCurrentBlock("command"); + $this->tpl->setVariable("TXT_COMMAND", $lng->txt("cont_rollback")); + $this->tpl->setVariable( + "HREF_COMMAND", + $ilCtrl->getLinkTarget($this->getParentObject(), "rollbackConfirmation") + ); + $this->tpl->parseCurrentBlock(); + $ilCtrl->setParameter($this->getParentObject(), "old_nr", ""); + } + + if (!$this->rselect) { + $this->tpl->setVariable("RSELECT", 'checked="checked"'); + $this->rselect = true; + } elseif (!$this->lselect) { + $this->tpl->setVariable("LSELECT", 'checked="checked"'); + $this->lselect = true; + } - - $this->tpl->setVariable("NR", $a_set["nr"]); - $this->tpl->setVariable("TXT_HDATE", - ilDatePresentation::formatDate(new ilDateTime($a_set["hdate"], IL_CAL_DATETIME))); - - $ilCtrl->setParameter($this->getParentObject(), "old_nr", $a_set["nr"]); - $ilCtrl->setParameter($this->getParentObject(), "history_mode", "1"); - $this->tpl->setVariable("HREF_OLD_PAGE", - $ilCtrl->getLinkTarget($this->getParentObject(), "preview")); - $ilCtrl->setParameter($this->getParentObject(), "history_mode", ""); - - if (ilObject::_exists($a_set["user"])) - { - // user name - $user = ilObjUser::_lookupName($a_set["user"]); - $login = ilObjUser::_lookupLogin($a_set["user"]); - //$this->tpl->setVariable("TXT_LINKED_USER", - // $user["lastname"].", ".$user["firstname"]." [".$login."]"); - - // profile link - include_once("./Services/User/classes/class.ilUserUtil.php"); - $name_pres = ilUserUtil::getNamePresentation($a_set["user"], true, true, $ilCtrl->getLinkTarget($this->getParentObject(), $this->getParentCmd())); - //$ilCtrl->setParameterByClass("ilpublicuserprofilegui", "user", $a_set["user"]); - //$ilCtrl->setParameterByClass("ilpublicuserprofilegui", "back_url", - // rawurlencode($ilCtrl->getLinkTarget($this->getParentObject(), $this->getParentCmd()))); - //$this->tpl->setVariable("USER_LINK", - // $ilCtrl->getLinkTargetByClass("ilpublicuserprofilegui", "getHTML")); - //$img = ilObjUser::_getPersonalPicturePath($a_set["user"], "xxsmall"); - //$this->tpl->setVariable("IMG_USER", $img); - $this->tpl->setVariable("TXT_USER", $name_pres); - - } - - $ilCtrl->setParameter($this->getParentObject(), "old_nr", ""); - } + + $this->tpl->setVariable("NR", $a_set["nr"]); + $this->tpl->setVariable( + "TXT_HDATE", + ilDatePresentation::formatDate(new ilDateTime($a_set["hdate"], IL_CAL_DATETIME)) + ); + $ilCtrl->setParameter($this->getParentObject(), "old_nr", $a_set["nr"]); + $ilCtrl->setParameter($this->getParentObject(), "history_mode", "1"); + $this->tpl->setVariable( + "HREF_OLD_PAGE", + $ilCtrl->getLinkTarget($this->getParentObject(), "preview") + ); + $ilCtrl->setParameter($this->getParentObject(), "history_mode", ""); + + if (ilObject::_exists($a_set["user"])) { + // user name + $user = ilObjUser::_lookupName($a_set["user"]); + $login = ilObjUser::_lookupLogin($a_set["user"]); + //$this->tpl->setVariable("TXT_LINKED_USER", + // $user["lastname"].", ".$user["firstname"]." [".$login."]"); + + // profile link + include_once("./Services/User/classes/class.ilUserUtil.php"); + $name_pres = ilUserUtil::getNamePresentation($a_set["user"], true, true, $ilCtrl->getLinkTarget($this->getParentObject(), $this->getParentCmd())); + //$ilCtrl->setParameterByClass("ilpublicuserprofilegui", "user", $a_set["user"]); + //$ilCtrl->setParameterByClass("ilpublicuserprofilegui", "back_url", + // rawurlencode($ilCtrl->getLinkTarget($this->getParentObject(), $this->getParentCmd()))); + //$this->tpl->setVariable("USER_LINK", + // $ilCtrl->getLinkTargetByClass("ilpublicuserprofilegui", "getHTML")); + //$img = ilObjUser::_getPersonalPicturePath($a_set["user"], "xxsmall"); + //$this->tpl->setVariable("IMG_USER", $img); + $this->tpl->setVariable("TXT_USER", $name_pres); + } + + $ilCtrl->setParameter($this->getParentObject(), "old_nr", ""); + } } -?> diff --git a/Services/COPage/classes/class.ilPageMultiLang.php b/Services/COPage/classes/class.ilPageMultiLang.php index 4e93bdf8991dec07861d447e26ad566b36b7131d..79060ea37128e34bc79dd63097742844e7ce89e0 100644 --- a/Services/COPage/classes/class.ilPageMultiLang.php +++ b/Services/COPage/classes/class.ilPageMultiLang.php @@ -3,7 +3,7 @@ /* Copyright (c) 1998-2014 ILIAS open source, Extended GPL, see docs/LICENSE */ /** - * Multi-language properties + * Multi-language properties * * @author Alex Killing * @version $Id$ @@ -11,273 +11,263 @@ */ class ilPageMultiLang { - protected $db; - protected $parent_type; - protected $parent_id; - protected $master_lang; - protected $languages = array(); - protected $activated = false; - - /** - * Constructor - * - * @param string $a_parent_type parent object type - * @param int $a_parent_id parent object id - * @throws ilCOPageException - */ - function __construct($a_parent_type, $a_parent_id) - { - global $DIC; + protected $db; + protected $parent_type; + protected $parent_id; + protected $master_lang; + protected $languages = array(); + protected $activated = false; + + /** + * Constructor + * + * @param string $a_parent_type parent object type + * @param int $a_parent_id parent object id + * @throws ilCOPageException + */ + public function __construct($a_parent_type, $a_parent_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $this->db = $ilDB; - - $this->setParentType($a_parent_type); - $this->setParentId($a_parent_id); + $ilDB = $DIC->database(); + + $this->db = $ilDB; + + $this->setParentType($a_parent_type); + $this->setParentId($a_parent_id); - if ($this->getParentType() == "") - { - include_once("./Services/COPage/exceptions/class.ilCOPageException.php"); - throw new ilCOPageException("ilPageMultiLang: No parent type passed."); - } - - if ($this->getParentId() <= 0) - { - include_once("./Services/COPage/exceptions/class.ilCOPageException.php"); - throw new ilCOPageException("ilPageMultiLang: No parent ID passed."); - } - - $this->read(); - } - - /** - * Set parent type - * - * @param string $a_val parent type - */ - function setParentType($a_val) - { - $this->parent_type = $a_val; - } - - /** - * Get parent type - * - * @return string parent type - */ - function getParentType() - { - return $this->parent_type; - } - - /** - * Set parent id - * - * @param int $a_val parent id - */ - function setParentId($a_val) - { - $this->parent_id = $a_val; - } - - /** - * Get parent id - * - * @return int parent id - */ - function getParentId() - { - return $this->parent_id; - } - - /** - * Set master language - * - * @param string $a_val master language - */ - function setMasterLanguage($a_val) - { - $this->master_lang = $a_val; - } - - /** - * Get master language - * - * @return string master language - */ - function getMasterLanguage() - { - return $this->master_lang; - } + if ($this->getParentType() == "") { + include_once("./Services/COPage/exceptions/class.ilCOPageException.php"); + throw new ilCOPageException("ilPageMultiLang: No parent type passed."); + } + + if ($this->getParentId() <= 0) { + include_once("./Services/COPage/exceptions/class.ilCOPageException.php"); + throw new ilCOPageException("ilPageMultiLang: No parent ID passed."); + } + + $this->read(); + } + + /** + * Set parent type + * + * @param string $a_val parent type + */ + public function setParentType($a_val) + { + $this->parent_type = $a_val; + } + + /** + * Get parent type + * + * @return string parent type + */ + public function getParentType() + { + return $this->parent_type; + } + + /** + * Set parent id + * + * @param int $a_val parent id + */ + public function setParentId($a_val) + { + $this->parent_id = $a_val; + } + + /** + * Get parent id + * + * @return int parent id + */ + public function getParentId() + { + return $this->parent_id; + } + + /** + * Set master language + * + * @param string $a_val master language + */ + public function setMasterLanguage($a_val) + { + $this->master_lang = $a_val; + } + + /** + * Get master language + * + * @return string master language + */ + public function getMasterLanguage() + { + return $this->master_lang; + } - /** - * Set languages - * - * @param array $a_val array of language codes - */ - function setLanguages(array $a_val) - { - $this->languages = $a_val; - } - - /** - * Get languages - * - * @return array array of language codes - */ - function getLanguages() - { - return $this->languages; - } - - /** - * Add language - * - * @param string $a_lang language - */ - function addLanguage($a_lang) - { - if ($a_lang != "" && !in_array($a_lang, $this->languages)) - { - $this->languages[] = $a_lang; - } - } - - - /** - * Set activated - * - * @param bool $a_val activated? - */ - protected function setActivated($a_val) - { - $this->activated = $a_val; - } - - /** - * Get activated - * - * @return bool activated? - */ - function getActivated() - { - return $this->activated; - } - - /** - * Read - */ - function read() - { - $set = $this->db->query("SELECT * FROM copg_multilang ". - " WHERE parent_type = ".$this->db->quote($this->getParentType(), "text"). - " AND parent_id = ".$this->db->quote($this->getParentId(), "integer") - ); - if ($rec = $this->db->fetchAssoc($set)) - { - $this->setMasterLanguage($rec["master_lang"]); - $this->setActivated(true); - } - else - { - $this->setActivated(false); - } + /** + * Set languages + * + * @param array $a_val array of language codes + */ + public function setLanguages(array $a_val) + { + $this->languages = $a_val; + } + + /** + * Get languages + * + * @return array array of language codes + */ + public function getLanguages() + { + return $this->languages; + } + + /** + * Add language + * + * @param string $a_lang language + */ + public function addLanguage($a_lang) + { + if ($a_lang != "" && !in_array($a_lang, $this->languages)) { + $this->languages[] = $a_lang; + } + } + + + /** + * Set activated + * + * @param bool $a_val activated? + */ + protected function setActivated($a_val) + { + $this->activated = $a_val; + } + + /** + * Get activated + * + * @return bool activated? + */ + public function getActivated() + { + return $this->activated; + } + + /** + * Read + */ + public function read() + { + $set = $this->db->query( + "SELECT * FROM copg_multilang " . + " WHERE parent_type = " . $this->db->quote($this->getParentType(), "text") . + " AND parent_id = " . $this->db->quote($this->getParentId(), "integer") + ); + if ($rec = $this->db->fetchAssoc($set)) { + $this->setMasterLanguage($rec["master_lang"]); + $this->setActivated(true); + } else { + $this->setActivated(false); + } - $this->setLanguages(array()); - $set = $this->db->query("SELECT * FROM copg_multilang_lang ". - " WHERE parent_type = ".$this->db->quote($this->getParentType(), "text"). - " AND parent_id = ".$this->db->quote($this->getParentId(), "integer") - ); - while ($rec = $this->db->fetchAssoc($set)) - { - $this->addLanguage($rec["lang"]); - } - } + $this->setLanguages(array()); + $set = $this->db->query( + "SELECT * FROM copg_multilang_lang " . + " WHERE parent_type = " . $this->db->quote($this->getParentType(), "text") . + " AND parent_id = " . $this->db->quote($this->getParentId(), "integer") + ); + while ($rec = $this->db->fetchAssoc($set)) { + $this->addLanguage($rec["lang"]); + } + } - /** - * Delete - */ - function delete() - { - $this->db->manipulate("DELETE FROM copg_multilang ". - " WHERE parent_type = ".$this->db->quote($this->getParentType(), "text"). - " AND parent_id = ".$this->db->quote($this->getParentId(), "integer") - ); - $this->db->manipulate("DELETE FROM copg_multilang_lang ". - " WHERE parent_type = ".$this->db->quote($this->getParentType(), "text"). - " AND parent_id = ".$this->db->quote($this->getParentId(), "integer") - ); - } + /** + * Delete + */ + public function delete() + { + $this->db->manipulate( + "DELETE FROM copg_multilang " . + " WHERE parent_type = " . $this->db->quote($this->getParentType(), "text") . + " AND parent_id = " . $this->db->quote($this->getParentId(), "integer") + ); + $this->db->manipulate( + "DELETE FROM copg_multilang_lang " . + " WHERE parent_type = " . $this->db->quote($this->getParentType(), "text") . + " AND parent_id = " . $this->db->quote($this->getParentId(), "integer") + ); + } - /** - * Save - */ - function save() - { - $this->delete(); + /** + * Save + */ + public function save() + { + $this->delete(); - $this->db->manipulate("INSERT INTO copg_multilang ". - "(parent_type, parent_id, master_lang) VALUES (". - $this->db->quote($this->getParentType(), "text").",". - $this->db->quote($this->getParentId(), "integer").",". - $this->db->quote($this->getMasterLanguage(), "text"). - ")"); - - foreach ($this->getLanguages() as $lang) - { - $this->db->manipulate("INSERT INTO copg_multilang_lang ". - "(parent_type, parent_id, lang) VALUES (". - $this->db->quote($this->getParentType(), "text").",". - $this->db->quote($this->getParentId(), "integer").",". - $this->db->quote($lang, "text"). - ")"); - } - } + $this->db->manipulate("INSERT INTO copg_multilang " . + "(parent_type, parent_id, master_lang) VALUES (" . + $this->db->quote($this->getParentType(), "text") . "," . + $this->db->quote($this->getParentId(), "integer") . "," . + $this->db->quote($this->getMasterLanguage(), "text") . + ")"); + + foreach ($this->getLanguages() as $lang) { + $this->db->manipulate("INSERT INTO copg_multilang_lang " . + "(parent_type, parent_id, lang) VALUES (" . + $this->db->quote($this->getParentType(), "text") . "," . + $this->db->quote($this->getParentId(), "integer") . "," . + $this->db->quote($lang, "text") . + ")"); + } + } - /** - * Copy multilinguality settings - * - * @param string $a_target_parent_type parent object type - * @param int $a_target_parent_id parent object id - * @return ilPageMultiLang target multilang object - */ - function copy($a_target_parent_type, $a_target_parent_id) - { - if ($this->getActivated()) - { - $target_ml = new ilPageMultiLang($a_target_parent_type, $a_target_parent_id); - $target_ml->setMasterLanguage($this->getMasterLanguage()); - $target_ml->setLanguages($this->getLanguages()); - $target_ml->save(); - return $target_ml; - } + /** + * Copy multilinguality settings + * + * @param string $a_target_parent_type parent object type + * @param int $a_target_parent_id parent object id + * @return ilPageMultiLang target multilang object + */ + public function copy($a_target_parent_type, $a_target_parent_id) + { + if ($this->getActivated()) { + $target_ml = new ilPageMultiLang($a_target_parent_type, $a_target_parent_id); + $target_ml->setMasterLanguage($this->getMasterLanguage()); + $target_ml->setLanguages($this->getLanguages()); + $target_ml->save(); + return $target_ml; + } - return null; - } + return null; + } - /** - * Get effective language for given language. This checks if - * - multilinguality is activated and - * - the given language is part of the available translations - * If not a "-" is returned (master language). - * - * @param string $a_lang language - * @return string effective language ("-" for master) - */ - function getEffectiveLang($a_lang) - { - if ($this->getActivated() && - in_array($a_lang, $this->getLanguages()) && - ilPageObject::_exists($this->getParentType(), $this->getParentId(), $a_lang)) - { - return $a_lang; - } - return "-"; - } - - + /** + * Get effective language for given language. This checks if + * - multilinguality is activated and + * - the given language is part of the available translations + * If not a "-" is returned (master language). + * + * @param string $a_lang language + * @return string effective language ("-" for master) + */ + public function getEffectiveLang($a_lang) + { + if ($this->getActivated() && + in_array($a_lang, $this->getLanguages()) && + ilPageObject::_exists($this->getParentType(), $this->getParentId(), $a_lang)) { + return $a_lang; + } + return "-"; + } } - -?> diff --git a/Services/COPage/classes/class.ilPageMultiLangGUI.php b/Services/COPage/classes/class.ilPageMultiLangGUI.php index 7f076af887d00feb262cf1a0afb6ecdb69c4eef3..5590f264a5d2d2b6ab1e19b7407e0366dff965b5 100644 --- a/Services/COPage/classes/class.ilPageMultiLangGUI.php +++ b/Services/COPage/classes/class.ilPageMultiLangGUI.php @@ -6,7 +6,7 @@ include_once("./Services/COPage/classes/class.ilPageMultiLang.php"); /** * Page multilinguality GUI class. - * This could be generalized as an object service in the future. + * This could be generalized as an object service in the future. * * @author Alex Killing * @version $Id$ @@ -14,88 +14,82 @@ include_once("./Services/COPage/classes/class.ilPageMultiLang.php"); */ class ilPageMultiLangGUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - protected $single_page_mode = false; + protected $single_page_mode = false; - /** - * Constructur - * - * @param string $a_parent_type parent object type - * @param int $a_parent_id parent object id - * @param bool $a_single_page_mode single page mode (page includes ml managing) - */ - function __construct($a_parent_type, $a_parent_id, $a_single_page_mode = false) - { - global $DIC; + /** + * Constructur + * + * @param string $a_parent_type parent object type + * @param int $a_parent_id parent object id + * @param bool $a_single_page_mode single page mode (page includes ml managing) + */ + public function __construct($a_parent_type, $a_parent_id, $a_single_page_mode = false) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - //$this->ml = new ilPageMultiLang($a_parent_type, $a_parent_id); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + //$this->ml = new ilPageMultiLang($a_parent_type, $a_parent_id); - // object translation - include_once("./Services/Object/classes/class.ilObjectTranslation.php"); - $this->ot = ilObjectTranslation::getInstance($a_parent_id); - -// $this->single_page_mode = $a_single_page_mode; - } - - /** - * Execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - - $next_class = $ilCtrl->getNextClass(); - - switch ($next_class) - { - default: - $cmd = $ilCtrl->getCmd("settings"); - if (in_array($cmd, array("settings", "activateMultilinguality", "cancel", - "saveMultilingualitySettings", "confirmDeactivateMultiLanguage", "addLanguage", - "saveLanguages", "deactivateMultiLang", "confirmRemoveLanguages", - "removeLanguages"))) - { - $this->$cmd(); - } - } - } - - /** - * Get multi lang info - */ - function getMultiLangInfo($a_page_lang = "-") - { - $lng = $this->lng; - - if ($a_page_lang == "") - { - $a_page_lang = "-"; - } - - $lng->loadLanguageModule("meta"); - - $tpl = new ilTemplate("tpl.page_multi_lang_info.html", true, true, "Services/COPage"); - $tpl->setVariable("TXT_MASTER_LANG", $lng->txt("obj_master_lang")); - $tpl->setVariable("VAL_ML", $lng->txt("meta_l_".$this->ot->getMasterLanguage())); - $cl = ($a_page_lang == "-") - ? $this->ot->getMasterLanguage() - : $a_page_lang; - $tpl->setVariable("TXT_CURRENT_LANG", $lng->txt("cont_current_lang")); - $tpl->setVariable("VAL_CL", $lng->txt("meta_l_".$cl)); - return $tpl->get(); - } + // object translation + include_once("./Services/Object/classes/class.ilObjectTranslation.php"); + $this->ot = ilObjectTranslation::getInstance($a_parent_id); + + // $this->single_page_mode = $a_single_page_mode; + } + + /** + * Execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $next_class = $ilCtrl->getNextClass(); + + switch ($next_class) { + default: + $cmd = $ilCtrl->getCmd("settings"); + if (in_array($cmd, array("settings", "activateMultilinguality", "cancel", + "saveMultilingualitySettings", "confirmDeactivateMultiLanguage", "addLanguage", + "saveLanguages", "deactivateMultiLang", "confirmRemoveLanguages", + "removeLanguages"))) { + $this->$cmd(); + } + } + } + /** + * Get multi lang info + */ + public function getMultiLangInfo($a_page_lang = "-") + { + $lng = $this->lng; + + if ($a_page_lang == "") { + $a_page_lang = "-"; + } + + $lng->loadLanguageModule("meta"); + + $tpl = new ilTemplate("tpl.page_multi_lang_info.html", true, true, "Services/COPage"); + $tpl->setVariable("TXT_MASTER_LANG", $lng->txt("obj_master_lang")); + $tpl->setVariable("VAL_ML", $lng->txt("meta_l_" . $this->ot->getMasterLanguage())); + $cl = ($a_page_lang == "-") + ? $this->ot->getMasterLanguage() + : $a_page_lang; + $tpl->setVariable("TXT_CURRENT_LANG", $lng->txt("cont_current_lang")); + $tpl->setVariable("VAL_CL", $lng->txt("meta_l_" . $cl)); + return $tpl->get(); + } } - -?> diff --git a/Services/COPage/classes/class.ilPageMultiLangTableGUI.php b/Services/COPage/classes/class.ilPageMultiLangTableGUI.php index 71cf84bff5d30bb335230f6903122e2b56991256..7768bb5fc9a4d86afa2e414b61f3e58176a33fc6 100644 --- a/Services/COPage/classes/class.ilPageMultiLangTableGUI.php +++ b/Services/COPage/classes/class.ilPageMultiLangTableGUI.php @@ -5,7 +5,7 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); /** - * TableGUI class for + * TableGUI class for * * @author Alex Killing * @version $Id$ @@ -14,61 +14,56 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilPageMultiLangTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $lng = $DIC->language(); - $lng->loadLanguageModule("meta"); + $lng->loadLanguageModule("meta"); - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setTitle($lng->txt("cont_languages")); - - $this->addColumn("", "", "1"); - $this->addColumn($this->lng->txt("cont_language")); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.page_ml_row.html", "Services/COPage"); + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setTitle($lng->txt("cont_languages")); + + $this->addColumn("", "", "1"); + $this->addColumn($this->lng->txt("cont_language")); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.page_ml_row.html", "Services/COPage"); - //if (count($this->getData()) > 1) - //{ - $this->addMultiCommand("confirmRemoveLanguages", $lng->txt("remove")); - //} - //$this->addCommandButton("", $lng->txt("")); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - - if (!$a_set["master"]) - { - $this->tpl->setCurrentBlock("cb"); - $this->tpl->setVariable("CB_LANG", $a_set["lang"]); - $this->tpl->parseCurrentBlock(); - } - else - { - $this->tpl->setVariable("ML", "(".$lng->txt("cont_master_lang").")"); - } - $this->tpl->setVariable("LANG", $lng->txt("meta_l_".$a_set["lang"])); - } + //if (count($this->getData()) > 1) + //{ + $this->addMultiCommand("confirmRemoveLanguages", $lng->txt("remove")); + //} + //$this->addCommandButton("", $lng->txt("")); + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + if (!$a_set["master"]) { + $this->tpl->setCurrentBlock("cb"); + $this->tpl->setVariable("CB_LANG", $a_set["lang"]); + $this->tpl->parseCurrentBlock(); + } else { + $this->tpl->setVariable("ML", "(" . $lng->txt("cont_master_lang") . ")"); + } + $this->tpl->setVariable("LANG", $lng->txt("meta_l_" . $a_set["lang"])); + } } -?> \ No newline at end of file diff --git a/Services/COPage/classes/class.ilPageObject.php b/Services/COPage/classes/class.ilPageObject.php index 8c745b181ad46699a0933fd1e40dff799a31e8c9..5c9ecc661c693fda34d727c4383c6f83d4fafa9c 100755 --- a/Services/COPage/classes/class.ilPageObject.php +++ b/Services/COPage/classes/class.ilPageObject.php @@ -5,34 +5,34 @@ define("IL_INSERT_BEFORE", 0); define("IL_INSERT_AFTER", 1); define("IL_INSERT_CHILD", 2); -define ("IL_CHAPTER_TITLE", "st_title"); -define ("IL_PAGE_TITLE", "pg_title"); -define ("IL_NO_HEADER", "none"); +define("IL_CHAPTER_TITLE", "st_title"); +define("IL_PAGE_TITLE", "pg_title"); +define("IL_NO_HEADER", "none"); /** @defgroup ServicesCOPage Services/COPage */ /* - - move dom related code to PageDom class/interface - - move ilDB dependency to ar object - - move internal links related code to extra class - - make factory available through DIC, opt allow decentralized factory parts - - PC types - -- internal links used/implemented? - -- styles used/implemented? - - application classes need - -- page object - --- page object should return php5 domdoc (getDom() vs getDomDoc()?) - esp. plugins should use this - -- remove content element hook, if content is not allowed - - PC types could move to components (e.g. blog, login) - - How to modularize xsl? - -- read from db? - -- xml entries say that xslt code is used -> read file and include in - main xslt file - -*/ + - move dom related code to PageDom class/interface + - move ilDB dependency to ar object + - move internal links related code to extra class + - make factory available through DIC, opt allow decentralized factory parts + - PC types + -- internal links used/implemented? + -- styles used/implemented? + - application classes need + -- page object + --- page object should return php5 domdoc (getDom() vs getDomDoc()?) + esp. plugins should use this + -- remove content element hook, if content is not allowed + - PC types could move to components (e.g. blog, login) + - How to modularize xsl? + -- read from db? + -- xml entries say that xslt code is used -> read file and include in + main xslt file + +*/ /** * Class ilPageObject @@ -47,5507 +47,5085 @@ define ("IL_NO_HEADER", "none"); */ abstract class ilPageObject { - /** - * @var ilObjectDefinition - */ - protected $obj_definition; - - static $exists = array(); - - /** - * @var ilDB - */ - protected $db; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTree - */ - protected $tree; - - /** - * @var int - */ - protected $id; - var $dom; - var $xml; - var $encoding; - var $node; - var $cur_dtd = "ilias_pg_5_4.dtd"; - var $contains_int_link; - var $needs_parsing; - var $parent_type; - var $parent_id; - var $update_listeners; - var $update_listener_cnt; - var $offline_handler; - var $dom_builded; - var $history_saved; - - /** - * @var string - */ - protected $language = "-"; - - /** - * @var array - */ - static protected $activation_data = array(); - - /** - * @var bool - */ - protected $import_mode = false; - - /** - * @var ilLogger - */ - protected $log; - - /** - * @var array - */ - protected $page_record = array(); - - /** - * @var bool - */ - protected $active = false; - - /** - * @var ilPageConfig - */ - protected $page_config; - - /** - * Constructor - * @access public - */ - final public function __construct($a_id = 0, $a_old_nr = 0, $a_lang = "-") - { - global $DIC; - $this->obj_definition = $DIC["objDefinition"]; - $this->db = $DIC->database(); - $this->user = $DIC->user(); - $this->lng = $DIC->language(); - $this->tree = $DIC->repositoryTree(); - $this->log = ilLoggerFactory::getLogger('copg'); - - $this->parent_type = $this->getParentType(); - $this->id = $a_id; - $this->setLanguage($a_lang); - - $this->contains_int_link = false; - $this->needs_parsing = false; - $this->update_listeners = array(); - $this->update_listener_cnt = 0; - $this->dom_builded = false; - $this->page_not_found = false; - $this->old_nr = $a_old_nr; - $this->encoding = "UTF-8"; - $this->id_elements = - array("PageContent", "TableRow", "TableData", "ListItem", "FileItem", - "Section", "Tab", "ContentPopup", "GridCell"); - $this->setActive(true); - $this->show_page_act_info = false; - - if($a_id != 0) - { - $this->read(); - } - - $this->initPageConfig(); - - $this->afterConstructor(); - } - - /** - * After constructor - */ - function afterConstructor() - { - - } - - - /** - * Get parent type - * - * @return string parent type (page type) - */ - abstract function getParentType(); - - - /** - * Init page config - */ - final function initPageConfig() - { - include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); - $cfg = ilPageObjectFactory::getConfigInstance($this->getParentType()); - $this->setPageConfig($cfg); - } - - /** - * Set language - * - * @param string $a_val language code or "-" for unknown / not set - */ - function setLanguage($a_val) - { - $this->language = $a_val; - } - - /** - * Get language - * - * @return string language code - */ - function getLanguage() - { - return $this->language; - } - - /** - * Set page config object - * - * @param object $a_val page config object - */ - function setPageConfig($a_val) - { - $this->page_config = $a_val; - } - - /** - * Get page config object - * - * @return object page config object - */ - function getPageConfig() - { - return $this->page_config; - } - - /** - * Set Render MD5. - * - * @param string $a_rendermd5 Render MD5 - */ - function setRenderMd5($a_rendermd5) - { - $this->rendermd5 = $a_rendermd5; - } - - /** - * Get Render MD5. - * - * @return string Render MD5 - */ - function getRenderMd5() - { - return $this->rendermd5; - } - - /** - * Set Rendered Content. - * - * @param string $a_renderedcontent Rendered Content - */ - function setRenderedContent($a_renderedcontent) - { - $this->renderedcontent = $a_renderedcontent; - } - - /** - * Get Rendered Content. - * - * @return string Rendered Content - */ - function getRenderedContent() - { - return $this->renderedcontent; - } - - /** - * Set Rendered Time. - * - * @param string $a_renderedtime Rendered Time - */ - function setRenderedTime($a_renderedtime) - { - $this->renderedtime = $a_renderedtime; - } - - /** - * Get Rendered Time. - * - * @return string Rendered Time - */ - function getRenderedTime() - { - return $this->renderedtime; - } - - /** - * Set Last Change. - * - * @param string $a_lastchange Last Change - */ - function setLastChange($a_lastchange) - { - $this->lastchange = $a_lastchange; - } - - /** - * Get Last Change. - * - * @return string Last Change - */ - function getLastChange() - { - return $this->lastchange; - } - - /** - * Set last change user - * - * @param integer $a_val last change user - */ - public function setLastChangeUser($a_val) - { - $this->last_change_user = $a_val; - } - - /** - * Get last change user - * - * @return integer last change user - */ - public function getLastChangeUser() - { - return $this->last_change_user; - } - - /** - * Set show page activation info - * - * @param bool $a_val show page actication info - */ - function setShowActivationInfo($a_val) - { - $this->show_page_act_info = $a_val; - } - - /** - * Get show page activation info - * - * @return bool show page actication info - */ - function getShowActivationInfo() - { - return $this->show_page_act_info; - } - - /** - * Read page data - */ - function read() - { - $this->setActive(true); - if ($this->old_nr == 0) - { - $query = "SELECT * FROM page_object". - " WHERE page_id = ".$this->db->quote($this->id, "integer"). - " AND parent_type=".$this->db->quote($this->getParentType(), "text"). - " AND lang = ".$this->db->quote($this->getLanguage(), "text"); - $pg_set = $this->db->query($query); - $this->page_record = $this->db->fetchAssoc($pg_set); - $this->setActive($this->page_record["active"]); - $this->setActivationStart($this->page_record["activation_start"]); - $this->setActivationEnd($this->page_record["activation_end"]); - $this->setShowActivationInfo($this->page_record["show_activation_info"]); - } - else - { - $query = "SELECT * FROM page_history". - " WHERE page_id = ".$this->db->quote($this->id, "integer"). - " AND parent_type=".$this->db->quote($this->getParentType(), "text"). - " AND nr = ".$this->db->quote((int) $this->old_nr, "integer"). - " AND lang = ".$this->db->quote($this->getLanguage(), "text"); - $pg_set = $this->db->query($query); - $this->page_record = $this->db->fetchAssoc($pg_set); - } - if (!$this->page_record) - { - include_once("./Services/COPage/exceptions/class.ilCOPageNotFoundException.php"); - throw new ilCOPageNotFoundException("Error: Page ".$this->id." is not in database". - " (parent type ".$this->getParentType().", lang: ".$this->getLanguage().")."); - } - - $this->xml = $this->page_record["content"]; - $this->setParentId($this->page_record["parent_id"]); - $this->last_change_user = $this->page_record["last_change_user"]; - $this->create_user = $this->page_record["create_user"]; - $this->setRenderedContent($this->page_record["rendered_content"]); - $this->setRenderMd5($this->page_record["render_md5"]); - $this->setRenderedTime($this->page_record["rendered_time"]); - $this->setLastChange($this->page_record["last_change"]); - - } - - /** - * Checks whether page exists - * - * @param string $a_parent_type parent type - * @param int $a_id page id - * @param string $a_lang language code, if empty language independent existence is checked - */ - static function _exists($a_parent_type, $a_id, $a_lang = "", $a_no_cache = false) - { - global $DIC; - - $db = $DIC->database(); - - if (!$a_no_cache && isset(self::$exists[$a_parent_type.":".$a_id.":".$a_lang])) - { - return self::$exists[$a_parent_type.":".$a_id.":".$a_lang]; - } - - $and_lang = ""; - if ($a_lang != "") - { - $and_lang = " AND lang = ".$db->quote($a_lang, "text"); - } - - $query = "SELECT page_id FROM page_object WHERE page_id = ".$db->quote($a_id, "integer")." ". - "AND parent_type = ".$db->quote($a_parent_type, "text").$and_lang; - $set = $db->query($query); - if ($row = $db->fetchAssoc($set)) - { - self::$exists[$a_parent_type.":".$a_id.":".$a_lang] = true; - return true; - } - else - { - self::$exists[$a_parent_type.":".$a_id.":".$a_lang] = false; - return false; - } - } - - /** - * Checks whether page exists and is not empty (may return true on some empty pages) - * - * @param string $a_parent_type parent type - * @param int $a_id page id - * @param string $a_lang language code ("-" for unknown / not set) - */ - static function _existsAndNotEmpty($a_parent_type, $a_id, $a_lang = "-") - { - include_once("./Services/COPage/classes/class.ilPageUtil.php"); - return ilPageUtil::_existsAndNotEmpty($a_parent_type, $a_id, $a_lang); - } - - function buildDom($a_force = false) - { - if ($this->dom_builded && !$a_force) - { - return; - } - -//echo "\n
          buildDomWith:".$this->getId().":xml:".$this->getXMLContent(true).":
          "; - - $options = 0; - //$options = DOMXML_LOAD_VALIDATING; - //$options = LIBXML_DTDLOAD; - //$options = LIBXML_NOXMLDECL; -//echo htmlentities($this->getXMLContent(true))."
          "; - $this->dom = @domxml_open_mem($this->getXMLContent(true), $options, $error); -//var_dump($error); - $xpc = xpath_new_context($this->dom); - $path = "//PageObject"; - $res = xpath_eval($xpc, $path); - if (count($res->nodeset) == 1) - { -// echo "h"; - $this->node = $res->nodeset[0]; - } -//echo htmlentities($this->dom->dump_node($this->node)); exit; - - if (empty($error)) - { - $this->dom_builded = true; - return true; - } - else - { - return $error; - } - } - - function freeDom() - { - //$this->dom->free(); - unset($this->dom); - } - - /** - * Deprecated php4DomDocument - */ - function getDom() - { - return $this->dom; - } - - /** - * Get dom doc (php5 dom document) - * - * @param - * @return - */ - function getDomDoc() - { - if ($this->dom instanceof php4DOMDocument) - { - return $this->dom->myDOMDocument; - } - - return $this->dom; - } - - - /** - * set id - */ - function setId($a_id) - { - $this->id = $a_id; - } - - function getId() - { - return $this->id; - } - - function setParentId($a_id) - { - $this->parent_id = $a_id; - } - - function getParentId() - { - return $this->parent_id; - } - - function addUpdateListener(&$a_object, $a_method, $a_parameters = "") - { - $cnt = $this->update_listener_cnt; - $this->update_listeners[$cnt]["object"] = $a_object; - $this->update_listeners[$cnt]["method"] = $a_method; - $this->update_listeners[$cnt]["parameters"] = $a_parameters; - $this->update_listener_cnt++; - } - - function callUpdateListeners() - { - for($i=0; $i<$this->update_listener_cnt; $i++) - { - $object = $this->update_listeners[$i]["object"]; - $method = $this->update_listeners[$i]["method"]; - $parameters = $this->update_listeners[$i]["parameters"]; - $object->$method($parameters); - } - } - - /** - * set activation - * - * @param boolean $a_active true/false for active or not - */ - function setActive($a_active) - { - $this->active = $a_active; - } - - /** - * get activation - * - * @return boolean true/false for active or not - */ - function getActive($a_check_scheduled_activation = false) - { - if ($a_check_scheduled_activation && !$this->active) - { - include_once("./Services/Calendar/classes/class.ilDateTime.php"); - $start = new ilDateTime($this->getActivationStart(), IL_CAL_DATETIME); - $end = new ilDateTime($this->getActivationEnd(), IL_CAL_DATETIME); - $now = new ilDateTime(time(), IL_CAL_UNIX); - if (!ilDateTime::_before($now, $start) && !ilDateTime::_after($now, $end)) - { - return true; - } - } - return $this->active; - } - - /** - * Preload activation data by Parent Id - * - * @param integer $a_parent_id parent id - */ - static function preloadActivationDataByParentId($a_parent_id) - { - global $DIC; - - $db = $DIC->database(); - $set = $db->query("SELECT page_id, parent_type, lang, active, activation_start, activation_end, show_activation_info FROM page_object ". - " WHERE parent_id = ".$db->quote($a_parent_id, "integer") - ); - while ($rec = $db->fetchAssoc($set)) - { - self::$activation_data[$rec["page_id"].":".$rec["parent_type"].":".$rec["lang"]] = $rec; - } - } - - - /** - * lookup activation status - */ - static function _lookupActive($a_id, $a_parent_type, $a_check_scheduled_activation = false, $a_lang = "-") - { - global $DIC; - - $db = $DIC->database(); - - // language must be set at least to "-" - if ($a_lang == "") - { - $a_lang = "-"; - } - - if (isset(self::$activation_data[$a_id.":".$a_parent_type.":".$a_lang])) - { - $rec = self::$activation_data[$a_id.":".$a_parent_type.":".$a_lang]; - } - else - { - $set = $db->queryF("SELECT active, activation_start, activation_end FROM page_object WHERE page_id = %s". - " AND parent_type = %s AND lang = %s", - array("integer", "text", "text"), - array($a_id, $a_parent_type, $a_lang)); - $rec = $db->fetchAssoc($set); - } - - - $rec["n"] = ilUtil::now(); - - if (!$rec["active"] && $a_check_scheduled_activation) - { - if ($rec["n"] >= $rec["activation_start"] && - $rec["n"] <= $rec["activation_end"]) - { - return true; - } - } - - return $rec["active"]; - } - - /** - * Check whether page is activated by time schedule - */ - static function _isScheduledActivation($a_id, $a_parent_type, $a_lang = "-") - { - global $DIC; - - $db = $DIC->database(); - - // language must be set at least to "-" - if ($a_lang == "") - { - $a_lang = "-"; - } - -//echo "
          "; -//var_dump(self::$activation_data); exit; - if (isset(self::$activation_data[$a_id.":".$a_parent_type.":".$a_lang])) - { - $rec = self::$activation_data[$a_id.":".$a_parent_type.":".$a_lang]; - } - else - { - $set = $db->queryF("SELECT active, activation_start, activation_end FROM page_object WHERE page_id = %s". - " AND parent_type = %s AND lang = %s", array("integer", "text", "text"), - array($a_id, $a_parent_type, $a_lang)); - $rec = $db->fetchAssoc($set); - } - - if (!$rec["active"] && $rec["activation_start"] != "") - { - return true; - } - - return false; - } - - /** - * write activation status - */ - static function _writeActive($a_id, $a_parent_type, $a_active, $a_reset_scheduled_activation = true, $a_lang = "-") - { - global $DIC; - - $db = $DIC->database(); - - // language must be set at least to "-" - if ($a_lang == "") - { - $a_lang = "-"; - } - - if ($a_reset_scheduled_activation) - { - $st = $db->manipulateF("UPDATE page_object SET active = %s, activation_start = %s, ". - " activation_end = %s WHERE page_id = %s". - " AND parent_type = %s AND lang = %s", array("boolean", "timestamp", "timestamp", "integer", "text", "text"), - array($a_active, null, null, $a_id, $a_parent_type, $a_lang)); - } - else - { - $st = $db->prepareManip("UPDATE page_object SET active = %s WHERE page_id = %s". - " AND parent_type = %s AND lang = %s", array("boolean", "integer", "text", "text"), - array($a_active, $a_id, $a_parent_type, $a_lang)); - } - } - - /** - * Lookup activation data - */ - static function _lookupActivationData($a_id, $a_parent_type, $a_lang = "-") - { - global $DIC; - - $db = $DIC->database(); - - // language must be set at least to "-" - if ($a_lang == "") - { - $a_lang = "-"; - } - - if (isset(self::$activation_data[$a_id.":".$a_parent_type.":".$a_lang])) - { - $rec = self::$activation_data[$a_id.":".$a_parent_type.":".$a_lang]; - } - else - { - $set = $db->queryF("SELECT active, activation_start, activation_end, show_activation_info FROM page_object WHERE page_id = %s". - " AND parent_type = %s AND lang = %s", - array("integer", "text", "text"), - array($a_id, $a_parent_type, $a_lang)); - $rec = $db->fetchAssoc($set); - } - - return $rec; - } - - - /** - * Lookup parent id - */ - static function lookupParentId($a_id, $a_type) - { - global $DIC; - - $db = $DIC->database(); - - $res = $db->query("SELECT parent_id FROM page_object WHERE page_id = ".$db->quote($a_id, "integer")." ". - "AND parent_type=".$db->quote($a_type, "text")); - $rec = $db->fetchAssoc($res); - return $rec["parent_id"]; - } - - /** - * Write parent id - */ - static function _writeParentId($a_parent_type, $a_pg_id, $a_par_id) - { - global $DIC; - - $db = $DIC->database(); - $db->manipulateF("UPDATE page_object SET parent_id = %s WHERE page_id = %s". - " AND parent_type = %s", array("integer", "integer", "text"), - array($a_par_id, $a_pg_id, $a_parent_type)); - } - - /** - * Set Activation Start. - * - * @param date $a_activationstart Activation Start - */ - function setActivationStart($a_activationstart) - { - if ($a_activationstart == "") - { - $a_activationstart = null; - } - $this->activationstart = $a_activationstart; - } - - /** - * Get Activation Start. - * - * @return date Activation Start - */ - function getActivationStart() - { - return $this->activationstart; - } - - /** - * Set Activation End. - * - * @param date $a_activationend Activation End - */ - function setActivationEnd($a_activationend) - { - if ($a_activationend == "") - { - $a_activationend = null; - } - $this->activationend = $a_activationend; - } - - /** - * Get Activation End. - * - * @return date Activation End - */ - function getActivationEnd() - { - return $this->activationend; - } - - /** - * Get a content object of the page - * - * @param string hier ID - * @param string PC ID - * - * @return object page content object - */ - function getContentObject($a_hier_id, $a_pc_id = "") - { - $cont_node = $this->getContentNode($a_hier_id, $a_pc_id); - if (!is_object($cont_node)) - { - return false; - } - include_once("./Services/COPage/classes/class.ilCOPagePCDef.php"); - $node_name = $cont_node->node_name(); - if ($node_name == "PageObject") - { - return null; - } - if ($node_name == "PageContent") - { - $child_node = $cont_node->first_child(); - $node_name = $child_node->node_name(); - } - - // table extra handling (@todo: get rid of it) - if ($node_name == "Table") - { - if ($child_node->get_attribute("DataTable") == "y") - { - require_once("./Services/COPage/classes/class.ilPCDataTable.php"); - $tab = new ilPCDataTable($this); - $tab->setNode($cont_node); - $tab->setHierId($a_hier_id); - } - else - { - require_once("./Services/COPage/classes/class.ilPCTable.php"); - $tab = new ilPCTable($this); - $tab->setNode($cont_node); - $tab->setHierId($a_hier_id); - } - $tab->setPcId($a_pc_id); - return $tab; - } - - // media extra handling (@todo: get rid of it) - if ($node_name == "MediaObject") - { - if ($_GET["pgEdMediaMode"] != "") {echo "ilPageObject::error media"; exit;} - - //require_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - require_once("./Services/COPage/classes/class.ilPCMediaObject.php"); - - $mal_node = $child_node->first_child(); -//echo "ilPageObject::getContentObject:nodename:".$mal_node->node_name().":
          "; - $id_arr = explode("_", $mal_node->get_attribute("OriginId")); - $mob_id = $id_arr[count($id_arr) - 1]; - - // allow deletion of non-existing media objects - if (!ilObject::_exists($mob_id) && in_array("delete", $_POST)) - { - $mob_id = 0; - } - - //$mob = new ilObjMediaObject($mob_id); - $mob = new ilPCMediaObject($this); - $mob->readMediaObject($mob_id); - - //$mob->setDom($this->dom); - $mob->setNode($cont_node); - $mob->setHierId($a_hier_id); - $mob->setPcId($a_pc_id); - return $mob; - } - - // - // generic procedure - // - - $pc_def = ilCOPagePCDef::getPCDefinitionByName($node_name); - - // check if pc definition has been found - if (!is_array($pc_def)) - { - include_once("./Services/COPage/exceptions/class.ilCOPageUnknownPCTypeException.php"); - throw new ilCOPageUnknownPCTypeException('Unknown PC Name "'.$node_name.'".'); - } - $pc_class = "ilPC".$pc_def["name"]; - $pc_path = "./".$pc_def["component"]."/".$pc_def["directory"]."/class.".$pc_class.".php"; - require_once($pc_path); - $pc = new $pc_class($this); - $pc->setNode($cont_node); - $pc->setHierId($a_hier_id); - $pc->setPcId($a_pc_id); - return $pc; - } - - /** - * Get content node from dom - * - * @param string $a_hier_id hierarchical ID - * @param string $a_pc_id page content ID - */ - function &getContentNode($a_hier_id, $a_pc_id = "") - { - $xpc = xpath_new_context($this->dom); - if($a_hier_id == "pg") - { - return $this->node; - } - else - { - // get per pc id - if ($a_pc_id != "") - { - $path = "//*[@PCID = '$a_pc_id']"; - $res = xpath_eval($xpc, $path); - if (count($res->nodeset) == 1) - { - $cont_node = $res->nodeset[0]; - return $cont_node; - } - } - - // fall back to hier id - $path = "//*[@HierId = '$a_hier_id']"; - $res = xpath_eval($xpc, $path); - if (count($res->nodeset) == 1) - { - $cont_node = $res->nodeset[0]; - return $cont_node; - } - } - } - - /** - * Get content node from dom - * - * @param string $a_hier_id hierarchical ID - * @param string $a_pc_id page content ID - */ - function checkForTag($a_content_tag, $a_hier_id, $a_pc_id = "") - { - $xpc = xpath_new_context($this->dom); - // get per pc id - if ($a_pc_id != "") - { - $path = "//*[@PCID = '$a_pc_id']//".$a_content_tag; - $res = xpath_eval($xpc, $path); - if (count($res->nodeset) > 0) - { - return true; - } - } - - // fall back to hier id - $path = "//*[@HierId = '$a_hier_id']//".$a_content_tag; - $res = xpath_eval($xpc, $path); - if (count($res->nodeset) > 0) - { - return true; - } - return false; - } - - // only for test purposes - function lookforhier($a_hier_id) - { - $xpc = xpath_new_context($this->dom); - $path = "//*[@HierId = '$a_hier_id']"; - $res = xpath_eval($xpc, $path); - if (count($res->nodeset) == 1) - return "YES"; - else - return "NO"; - } - - - function &getNode() - { - return $this->node; - } - - - /** - * set xml content of page, start with , - * end with , comply with ILIAS DTD, omit MetaData, use utf-8! - * - * @param string $a_xml xml content - * @param string $a_encoding encoding of the content (here is no conversion done! - * it must be already utf-8 encoded at the time) - */ - function setXMLContent($a_xml, $a_encoding = "UTF-8") - { - $this->encoding = $a_encoding; - $this->xml = $a_xml; - } - - /** - * append xml content to page - * setXMLContent must be called before and the same encoding must be used - * - * @param string $a_xml xml content - */ - function appendXMLContent($a_xml) - { - $this->xml.= $a_xml; - } - - - /** - * get xml content of page - */ - function getXMLContent($a_incl_head = false) - { - // build full http path for XML DOCTYPE header. - // Under windows a relative path doesn't work :-( - if($a_incl_head) - { -//echo "+".$this->encoding."+"; - $enc_str = (!empty($this->encoding)) - ? "encoding=\"".$this->encoding."\"" - : ""; - return "". - "cur_dtd."\">". - $this->xml; - } - else - { - return $this->xml; - } - } - - /** - * Copy content of page; replace page components with copies - * where necessary (e.g. questions) - */ - function copyXmlContent($a_clone_mobs = false) - { - $xml = $this->getXmlContent(); - $temp_dom = domxml_open_mem(''.$xml, - DOMXML_LOAD_PARSING, $error); - if(empty($error)) - { - $this->handleCopiedContent($temp_dom, true, $a_clone_mobs); - } - $xml = $temp_dom->dump_mem(0, $this->encoding); - $xml = preg_replace('/<\?xml[^>]*>/i',"",$xml); - $xml = preg_replace('/]*>/i',"",$xml); - - return $xml; - } - -// @todo 1: begin: generalize, remove concrete dependencies - - /** - * Handle copied content - * - * This function copies items, that must be copied, if page - * content is duplicated. - * - * @param - * @return - */ - function handleCopiedContent($a_dom, $a_self_ass = true, $a_clone_mobs = false) - { - include_once("./Services/COPage/classes/class.ilCOPagePCDef.php"); - $defs = ilCOPagePCDef::getPCDefinitions(); - - // handle question elements - if ($a_self_ass) - { - $this->newQuestionCopies($a_dom); - } - else - { - $this->removeQuestions($a_dom); - } - - // handle interactive images - $this->newIIMCopies($a_dom); - - // handle media objects - if ($a_clone_mobs) - { - $this->newMobCopies($a_dom); - } - -// @todo 1: move all functions from above to the new domdoc - if ($a_dom instanceof php4DOMDocument) - { - $a_dom = $a_dom->myDOMDocument; - } - foreach ($defs as $def) - { - ilCOPagePCDef::requirePCClassByName($def["name"]); - $cl = $def["pc_class"]; - if ($cl == 'ilPCPlugged') - { - // the page object is provided for ilPageComponentPlugin - ilPCPlugged::handleCopiedPluggedContent($this, $a_dom); - } - else - { - $cl::handleCopiedContent($a_dom, $a_self_ass, $a_clone_mobs); - } - } - - } - - /** - * Handle content before deletion - * This currently treats only plugged content - * If no node is given, then the whole dom will be scanned - * - * @param php4DOMNode|DOMNode|null $a_node - */ - function handleDeleteContent($a_node = null) - { - if (!isset($a_node)) - { - $xpc = xpath_new_context($this->dom); - $path = "//PageContent"; - $res = xpath_eval($xpc, $path); - $nodes = $res->nodeset; - } - else - { - $nodes = array($a_node); - } - - require_once('Services/COPage/classes/class.ilPCPlugged.php'); - foreach ($nodes as $node) - { - if ($node instanceof php4DOMNode) - { - $node = $node->myDOMNode; - } - - /** @var DOMElement $node */ - if ($node->firstChild->nodeName == 'Plugged') - { - ilPCPlugged::handleDeletedPluggedNode($this, $node->firstChild); - } - } - } - - /** - * Replaces media objects in interactive images - * with copies of the interactive images - */ - function newIIMCopies($temp_dom) - { - // Get question IDs - $path = "//InteractiveImage/MediaAlias"; - $xpc = xpath_new_context($temp_dom); - $res = & xpath_eval($xpc, $path); - - $q_ids = array(); - include_once("./Services/Link/classes/class.ilInternalLink.php"); - for ($i = 0; $i < count ($res->nodeset); $i++) - { - $or_id = $res->nodeset[$i]->get_attribute("OriginId"); - - $inst_id = ilInternalLink::_extractInstOfTarget($or_id); - $mob_id = ilInternalLink::_extractObjIdOfTarget($or_id); - - if (!($inst_id > 0)) - { - if ($mob_id > 0) - { - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $media_object = new ilObjMediaObject($mob_id); - - // now copy this question and change reference to - // new question id - $new_mob = $media_object->duplicate(); - - $res->nodeset[$i]->set_attribute("OriginId", "il__mob_".$new_mob->getId()); - } - } - } - } - - /** - * Replaces media objects with copies - */ - function newMobCopies($temp_dom) - { - // Get question IDs - $path = "//MediaObject/MediaAlias"; - $xpc = xpath_new_context($temp_dom); - $res = & xpath_eval($xpc, $path); - - $q_ids = array(); - include_once("./Services/Link/classes/class.ilInternalLink.php"); - for ($i = 0; $i < count ($res->nodeset); $i++) - { - $or_id = $res->nodeset[$i]->get_attribute("OriginId"); - - $inst_id = ilInternalLink::_extractInstOfTarget($or_id); - $mob_id = ilInternalLink::_extractObjIdOfTarget($or_id); - - if (!($inst_id > 0)) - { - if ($mob_id > 0) - { - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $media_object = new ilObjMediaObject($mob_id); - - // now copy this question and change reference to - // new question id - $new_mob = $media_object->duplicate(); - - $res->nodeset[$i]->set_attribute("OriginId", "il__mob_".$new_mob->getId()); - } - } - } - } - - /** - * Replaces existing question content elements with - * new copies - */ - function newQuestionCopies(&$temp_dom) - { - // Get question IDs - $path = "//Question"; - $xpc = xpath_new_context($temp_dom); - $res = & xpath_eval($xpc, $path); - - $q_ids = array(); - include_once("./Services/Link/classes/class.ilInternalLink.php"); - for ($i = 0; $i < count ($res->nodeset); $i++) - { - $qref = $res->nodeset[$i]->get_attribute("QRef"); - - $inst_id = ilInternalLink::_extractInstOfTarget($qref); - $q_id = ilInternalLink::_extractObjIdOfTarget($qref); - - if (!($inst_id > 0)) - { - if ($q_id > 0) - { - include_once "./Modules/TestQuestionPool/classes/class.assQuestion.php"; - $question = assQuestion::_instantiateQuestion($q_id); - // check due to #16557 - if (is_object($question) && $question->isComplete()) - { - // check if page for question exists - // due to a bug in early 4.2.x version this is possible - if (!ilPageObject::_exists("qpl", $q_id)) - { - $question->createPageObject(); - } - - // now copy this question and change reference to - // new question id - $duplicate_id = $question->duplicate(false); - $res->nodeset[$i]->set_attribute("QRef", "il__qst_".$duplicate_id); - } - } - } - } - } - - /** - * Remove questions from document - * - * @param - * @return - */ - function removeQuestions(&$temp_dom) - { - // Get question IDs - $path = "//Question"; - $xpc = xpath_new_context($temp_dom); - $res = & xpath_eval($xpc, $path); - for ($i = 0; $i < count ($res->nodeset); $i++) - { - $parent_node = $res->nodeset[$i]->parent_node(); - $parent_node->unlink_node($parent_node); - } - } - -// @todo: end - - /** - * Remove questions from document - * - * @param - * @return - */ - function countPageContents() - { - // Get question IDs - $this->buildDom(); - $path = "//PageContent"; - $xpc = xpath_new_context($this->dom); - $res = & xpath_eval($xpc, $path); - return count ($res->nodeset); - } - - /** - * get xml content of page from dom - * (use this, if any changes are made to the document) - */ - function getXMLFromDom($a_incl_head = false, $a_append_mobs = false, $a_append_bib = false, - $a_append_str = "", $a_omit_pageobject_tag = false) - { - if ($a_incl_head) - { -//echo "\n
          #".$this->encoding."#"; - return $this->dom->dump_mem(0, $this->encoding); - } - else - { - // append multimedia object elements - if ($a_append_mobs || $a_append_bib || $a_append_link_info) - { - $mobs = ""; - $bibs = ""; - if ($a_append_mobs) - { - $mobs = $this->getMultimediaXML(); - } - if ($a_append_bib) - { -// deprecated + /** + * @var ilObjectDefinition + */ + protected $obj_definition; + + public static $exists = array(); + + /** + * @var ilDB + */ + protected $db; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTree + */ + protected $tree; + + /** + * @var int + */ + protected $id; + public $dom; + public $xml; + public $encoding; + public $node; + public $cur_dtd = "ilias_pg_5_4.dtd"; + public $contains_int_link; + public $needs_parsing; + public $parent_type; + public $parent_id; + public $update_listeners; + public $update_listener_cnt; + public $offline_handler; + public $dom_builded; + public $history_saved; + + /** + * @var string + */ + protected $language = "-"; + + /** + * @var array + */ + protected static $activation_data = array(); + + /** + * @var bool + */ + protected $import_mode = false; + + /** + * @var ilLogger + */ + protected $log; + + /** + * @var array + */ + protected $page_record = array(); + + /** + * @var bool + */ + protected $active = false; + + /** + * @var ilPageConfig + */ + protected $page_config; + + /** + * Constructor + * @access public + */ + final public function __construct($a_id = 0, $a_old_nr = 0, $a_lang = "-") + { + global $DIC; + $this->obj_definition = $DIC["objDefinition"]; + $this->db = $DIC->database(); + $this->user = $DIC->user(); + $this->lng = $DIC->language(); + $this->tree = $DIC->repositoryTree(); + $this->log = ilLoggerFactory::getLogger('copg'); + + $this->parent_type = $this->getParentType(); + $this->id = $a_id; + $this->setLanguage($a_lang); + + $this->contains_int_link = false; + $this->needs_parsing = false; + $this->update_listeners = array(); + $this->update_listener_cnt = 0; + $this->dom_builded = false; + $this->page_not_found = false; + $this->old_nr = $a_old_nr; + $this->encoding = "UTF-8"; + $this->id_elements = + array("PageContent", "TableRow", "TableData", "ListItem", "FileItem", + "Section", "Tab", "ContentPopup", "GridCell"); + $this->setActive(true); + $this->show_page_act_info = false; + + if ($a_id != 0) { + $this->read(); + } + + $this->initPageConfig(); + + $this->afterConstructor(); + } + + /** + * After constructor + */ + public function afterConstructor() + { + } + + + /** + * Get parent type + * + * @return string parent type (page type) + */ + abstract public function getParentType(); + + + /** + * Init page config + */ + final public function initPageConfig() + { + include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); + $cfg = ilPageObjectFactory::getConfigInstance($this->getParentType()); + $this->setPageConfig($cfg); + } + + /** + * Set language + * + * @param string $a_val language code or "-" for unknown / not set + */ + public function setLanguage($a_val) + { + $this->language = $a_val; + } + + /** + * Get language + * + * @return string language code + */ + public function getLanguage() + { + return $this->language; + } + + /** + * Set page config object + * + * @param object $a_val page config object + */ + public function setPageConfig($a_val) + { + $this->page_config = $a_val; + } + + /** + * Get page config object + * + * @return object page config object + */ + public function getPageConfig() + { + return $this->page_config; + } + + /** + * Set Render MD5. + * + * @param string $a_rendermd5 Render MD5 + */ + public function setRenderMd5($a_rendermd5) + { + $this->rendermd5 = $a_rendermd5; + } + + /** + * Get Render MD5. + * + * @return string Render MD5 + */ + public function getRenderMd5() + { + return $this->rendermd5; + } + + /** + * Set Rendered Content. + * + * @param string $a_renderedcontent Rendered Content + */ + public function setRenderedContent($a_renderedcontent) + { + $this->renderedcontent = $a_renderedcontent; + } + + /** + * Get Rendered Content. + * + * @return string Rendered Content + */ + public function getRenderedContent() + { + return $this->renderedcontent; + } + + /** + * Set Rendered Time. + * + * @param string $a_renderedtime Rendered Time + */ + public function setRenderedTime($a_renderedtime) + { + $this->renderedtime = $a_renderedtime; + } + + /** + * Get Rendered Time. + * + * @return string Rendered Time + */ + public function getRenderedTime() + { + return $this->renderedtime; + } + + /** + * Set Last Change. + * + * @param string $a_lastchange Last Change + */ + public function setLastChange($a_lastchange) + { + $this->lastchange = $a_lastchange; + } + + /** + * Get Last Change. + * + * @return string Last Change + */ + public function getLastChange() + { + return $this->lastchange; + } + + /** + * Set last change user + * + * @param integer $a_val last change user + */ + public function setLastChangeUser($a_val) + { + $this->last_change_user = $a_val; + } + + /** + * Get last change user + * + * @return integer last change user + */ + public function getLastChangeUser() + { + return $this->last_change_user; + } + + /** + * Set show page activation info + * + * @param bool $a_val show page actication info + */ + public function setShowActivationInfo($a_val) + { + $this->show_page_act_info = $a_val; + } + + /** + * Get show page activation info + * + * @return bool show page actication info + */ + public function getShowActivationInfo() + { + return $this->show_page_act_info; + } + + /** + * Read page data + */ + public function read() + { + $this->setActive(true); + if ($this->old_nr == 0) { + $query = "SELECT * FROM page_object" . + " WHERE page_id = " . $this->db->quote($this->id, "integer") . + " AND parent_type=" . $this->db->quote($this->getParentType(), "text") . + " AND lang = " . $this->db->quote($this->getLanguage(), "text"); + $pg_set = $this->db->query($query); + $this->page_record = $this->db->fetchAssoc($pg_set); + $this->setActive($this->page_record["active"]); + $this->setActivationStart($this->page_record["activation_start"]); + $this->setActivationEnd($this->page_record["activation_end"]); + $this->setShowActivationInfo($this->page_record["show_activation_info"]); + } else { + $query = "SELECT * FROM page_history" . + " WHERE page_id = " . $this->db->quote($this->id, "integer") . + " AND parent_type=" . $this->db->quote($this->getParentType(), "text") . + " AND nr = " . $this->db->quote((int) $this->old_nr, "integer") . + " AND lang = " . $this->db->quote($this->getLanguage(), "text"); + $pg_set = $this->db->query($query); + $this->page_record = $this->db->fetchAssoc($pg_set); + } + if (!$this->page_record) { + include_once("./Services/COPage/exceptions/class.ilCOPageNotFoundException.php"); + throw new ilCOPageNotFoundException("Error: Page " . $this->id . " is not in database" . + " (parent type " . $this->getParentType() . ", lang: " . $this->getLanguage() . ")."); + } + + $this->xml = $this->page_record["content"]; + $this->setParentId($this->page_record["parent_id"]); + $this->last_change_user = $this->page_record["last_change_user"]; + $this->create_user = $this->page_record["create_user"]; + $this->setRenderedContent($this->page_record["rendered_content"]); + $this->setRenderMd5($this->page_record["render_md5"]); + $this->setRenderedTime($this->page_record["rendered_time"]); + $this->setLastChange($this->page_record["last_change"]); + } + + /** + * Checks whether page exists + * + * @param string $a_parent_type parent type + * @param int $a_id page id + * @param string $a_lang language code, if empty language independent existence is checked + */ + public static function _exists($a_parent_type, $a_id, $a_lang = "", $a_no_cache = false) + { + global $DIC; + + $db = $DIC->database(); + + if (!$a_no_cache && isset(self::$exists[$a_parent_type . ":" . $a_id . ":" . $a_lang])) { + return self::$exists[$a_parent_type . ":" . $a_id . ":" . $a_lang]; + } + + $and_lang = ""; + if ($a_lang != "") { + $and_lang = " AND lang = " . $db->quote($a_lang, "text"); + } + + $query = "SELECT page_id FROM page_object WHERE page_id = " . $db->quote($a_id, "integer") . " " . + "AND parent_type = " . $db->quote($a_parent_type, "text") . $and_lang; + $set = $db->query($query); + if ($row = $db->fetchAssoc($set)) { + self::$exists[$a_parent_type . ":" . $a_id . ":" . $a_lang] = true; + return true; + } else { + self::$exists[$a_parent_type . ":" . $a_id . ":" . $a_lang] = false; + return false; + } + } + + /** + * Checks whether page exists and is not empty (may return true on some empty pages) + * + * @param string $a_parent_type parent type + * @param int $a_id page id + * @param string $a_lang language code ("-" for unknown / not set) + */ + public static function _existsAndNotEmpty($a_parent_type, $a_id, $a_lang = "-") + { + include_once("./Services/COPage/classes/class.ilPageUtil.php"); + return ilPageUtil::_existsAndNotEmpty($a_parent_type, $a_id, $a_lang); + } + + public function buildDom($a_force = false) + { + if ($this->dom_builded && !$a_force) { + return; + } + + //echo "\n
          buildDomWith:".$this->getId().":xml:".$this->getXMLContent(true).":
          "; + + $options = 0; + //$options = DOMXML_LOAD_VALIDATING; + //$options = LIBXML_DTDLOAD; + //$options = LIBXML_NOXMLDECL; + //echo htmlentities($this->getXMLContent(true))."
          "; + $this->dom = @domxml_open_mem($this->getXMLContent(true), $options, $error); + //var_dump($error); + $xpc = xpath_new_context($this->dom); + $path = "//PageObject"; + $res = xpath_eval($xpc, $path); + if (count($res->nodeset) == 1) { + // echo "h"; + $this->node = $res->nodeset[0]; + } + //echo htmlentities($this->dom->dump_node($this->node)); exit; + + if (empty($error)) { + $this->dom_builded = true; + return true; + } else { + return $error; + } + } + + public function freeDom() + { + //$this->dom->free(); + unset($this->dom); + } + + /** + * Deprecated php4DomDocument + */ + public function getDom() + { + return $this->dom; + } + + /** + * Get dom doc (php5 dom document) + * + * @param + * @return + */ + public function getDomDoc() + { + if ($this->dom instanceof php4DOMDocument) { + return $this->dom->myDOMDocument; + } + + return $this->dom; + } + + + /** + * set id + */ + public function setId($a_id) + { + $this->id = $a_id; + } + + public function getId() + { + return $this->id; + } + + public function setParentId($a_id) + { + $this->parent_id = $a_id; + } + + public function getParentId() + { + return $this->parent_id; + } + + public function addUpdateListener(&$a_object, $a_method, $a_parameters = "") + { + $cnt = $this->update_listener_cnt; + $this->update_listeners[$cnt]["object"] = $a_object; + $this->update_listeners[$cnt]["method"] = $a_method; + $this->update_listeners[$cnt]["parameters"] = $a_parameters; + $this->update_listener_cnt++; + } + + public function callUpdateListeners() + { + for ($i=0; $i<$this->update_listener_cnt; $i++) { + $object = $this->update_listeners[$i]["object"]; + $method = $this->update_listeners[$i]["method"]; + $parameters = $this->update_listeners[$i]["parameters"]; + $object->$method($parameters); + } + } + + /** + * set activation + * + * @param boolean $a_active true/false for active or not + */ + public function setActive($a_active) + { + $this->active = $a_active; + } + + /** + * get activation + * + * @return boolean true/false for active or not + */ + public function getActive($a_check_scheduled_activation = false) + { + if ($a_check_scheduled_activation && !$this->active) { + include_once("./Services/Calendar/classes/class.ilDateTime.php"); + $start = new ilDateTime($this->getActivationStart(), IL_CAL_DATETIME); + $end = new ilDateTime($this->getActivationEnd(), IL_CAL_DATETIME); + $now = new ilDateTime(time(), IL_CAL_UNIX); + if (!ilDateTime::_before($now, $start) && !ilDateTime::_after($now, $end)) { + return true; + } + } + return $this->active; + } + + /** + * Preload activation data by Parent Id + * + * @param integer $a_parent_id parent id + */ + public static function preloadActivationDataByParentId($a_parent_id) + { + global $DIC; + + $db = $DIC->database(); + $set = $db->query( + "SELECT page_id, parent_type, lang, active, activation_start, activation_end, show_activation_info FROM page_object " . + " WHERE parent_id = " . $db->quote($a_parent_id, "integer") + ); + while ($rec = $db->fetchAssoc($set)) { + self::$activation_data[$rec["page_id"] . ":" . $rec["parent_type"] . ":" . $rec["lang"]] = $rec; + } + } + + + /** + * lookup activation status + */ + public static function _lookupActive($a_id, $a_parent_type, $a_check_scheduled_activation = false, $a_lang = "-") + { + global $DIC; + + $db = $DIC->database(); + + // language must be set at least to "-" + if ($a_lang == "") { + $a_lang = "-"; + } + + if (isset(self::$activation_data[$a_id . ":" . $a_parent_type . ":" . $a_lang])) { + $rec = self::$activation_data[$a_id . ":" . $a_parent_type . ":" . $a_lang]; + } else { + $set = $db->queryF( + "SELECT active, activation_start, activation_end FROM page_object WHERE page_id = %s" . + " AND parent_type = %s AND lang = %s", + array("integer", "text", "text"), + array($a_id, $a_parent_type, $a_lang) + ); + $rec = $db->fetchAssoc($set); + } + + + $rec["n"] = ilUtil::now(); + + if (!$rec["active"] && $a_check_scheduled_activation) { + if ($rec["n"] >= $rec["activation_start"] && + $rec["n"] <= $rec["activation_end"]) { + return true; + } + } + + return $rec["active"]; + } + + /** + * Check whether page is activated by time schedule + */ + public static function _isScheduledActivation($a_id, $a_parent_type, $a_lang = "-") + { + global $DIC; + + $db = $DIC->database(); + + // language must be set at least to "-" + if ($a_lang == "") { + $a_lang = "-"; + } + + //echo "
          "; + //var_dump(self::$activation_data); exit; + if (isset(self::$activation_data[$a_id . ":" . $a_parent_type . ":" . $a_lang])) { + $rec = self::$activation_data[$a_id . ":" . $a_parent_type . ":" . $a_lang]; + } else { + $set = $db->queryF( + "SELECT active, activation_start, activation_end FROM page_object WHERE page_id = %s" . + " AND parent_type = %s AND lang = %s", + array("integer", "text", "text"), + array($a_id, $a_parent_type, $a_lang) + ); + $rec = $db->fetchAssoc($set); + } + + if (!$rec["active"] && $rec["activation_start"] != "") { + return true; + } + + return false; + } + + /** + * write activation status + */ + public static function _writeActive($a_id, $a_parent_type, $a_active, $a_reset_scheduled_activation = true, $a_lang = "-") + { + global $DIC; + + $db = $DIC->database(); + + // language must be set at least to "-" + if ($a_lang == "") { + $a_lang = "-"; + } + + if ($a_reset_scheduled_activation) { + $st = $db->manipulateF( + "UPDATE page_object SET active = %s, activation_start = %s, " . + " activation_end = %s WHERE page_id = %s" . + " AND parent_type = %s AND lang = %s", + array("boolean", "timestamp", "timestamp", "integer", "text", "text"), + array($a_active, null, null, $a_id, $a_parent_type, $a_lang) + ); + } else { + $st = $db->prepareManip( + "UPDATE page_object SET active = %s WHERE page_id = %s" . + " AND parent_type = %s AND lang = %s", + array("boolean", "integer", "text", "text"), + array($a_active, $a_id, $a_parent_type, $a_lang) + ); + } + } + + /** + * Lookup activation data + */ + public static function _lookupActivationData($a_id, $a_parent_type, $a_lang = "-") + { + global $DIC; + + $db = $DIC->database(); + + // language must be set at least to "-" + if ($a_lang == "") { + $a_lang = "-"; + } + + if (isset(self::$activation_data[$a_id . ":" . $a_parent_type . ":" . $a_lang])) { + $rec = self::$activation_data[$a_id . ":" . $a_parent_type . ":" . $a_lang]; + } else { + $set = $db->queryF( + "SELECT active, activation_start, activation_end, show_activation_info FROM page_object WHERE page_id = %s" . + " AND parent_type = %s AND lang = %s", + array("integer", "text", "text"), + array($a_id, $a_parent_type, $a_lang) + ); + $rec = $db->fetchAssoc($set); + } + + return $rec; + } + + + /** + * Lookup parent id + */ + public static function lookupParentId($a_id, $a_type) + { + global $DIC; + + $db = $DIC->database(); + + $res = $db->query("SELECT parent_id FROM page_object WHERE page_id = " . $db->quote($a_id, "integer") . " " . + "AND parent_type=" . $db->quote($a_type, "text")); + $rec = $db->fetchAssoc($res); + return $rec["parent_id"]; + } + + /** + * Write parent id + */ + public static function _writeParentId($a_parent_type, $a_pg_id, $a_par_id) + { + global $DIC; + + $db = $DIC->database(); + $db->manipulateF( + "UPDATE page_object SET parent_id = %s WHERE page_id = %s" . + " AND parent_type = %s", + array("integer", "integer", "text"), + array($a_par_id, $a_pg_id, $a_parent_type) + ); + } + + /** + * Set Activation Start. + * + * @param date $a_activationstart Activation Start + */ + public function setActivationStart($a_activationstart) + { + if ($a_activationstart == "") { + $a_activationstart = null; + } + $this->activationstart = $a_activationstart; + } + + /** + * Get Activation Start. + * + * @return date Activation Start + */ + public function getActivationStart() + { + return $this->activationstart; + } + + /** + * Set Activation End. + * + * @param date $a_activationend Activation End + */ + public function setActivationEnd($a_activationend) + { + if ($a_activationend == "") { + $a_activationend = null; + } + $this->activationend = $a_activationend; + } + + /** + * Get Activation End. + * + * @return date Activation End + */ + public function getActivationEnd() + { + return $this->activationend; + } + + /** + * Get a content object of the page + * + * @param string hier ID + * @param string PC ID + * + * @return object page content object + */ + public function getContentObject($a_hier_id, $a_pc_id = "") + { + $cont_node = $this->getContentNode($a_hier_id, $a_pc_id); + if (!is_object($cont_node)) { + return false; + } + include_once("./Services/COPage/classes/class.ilCOPagePCDef.php"); + $node_name = $cont_node->node_name(); + if ($node_name == "PageObject") { + return null; + } + if ($node_name == "PageContent") { + $child_node = $cont_node->first_child(); + $node_name = $child_node->node_name(); + } + + // table extra handling (@todo: get rid of it) + if ($node_name == "Table") { + if ($child_node->get_attribute("DataTable") == "y") { + require_once("./Services/COPage/classes/class.ilPCDataTable.php"); + $tab = new ilPCDataTable($this); + $tab->setNode($cont_node); + $tab->setHierId($a_hier_id); + } else { + require_once("./Services/COPage/classes/class.ilPCTable.php"); + $tab = new ilPCTable($this); + $tab->setNode($cont_node); + $tab->setHierId($a_hier_id); + } + $tab->setPcId($a_pc_id); + return $tab; + } + + // media extra handling (@todo: get rid of it) + if ($node_name == "MediaObject") { + if ($_GET["pgEdMediaMode"] != "") { + echo "ilPageObject::error media"; + exit; + } + + //require_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + require_once("./Services/COPage/classes/class.ilPCMediaObject.php"); + + $mal_node = $child_node->first_child(); + //echo "ilPageObject::getContentObject:nodename:".$mal_node->node_name().":
          "; + $id_arr = explode("_", $mal_node->get_attribute("OriginId")); + $mob_id = $id_arr[count($id_arr) - 1]; + + // allow deletion of non-existing media objects + if (!ilObject::_exists($mob_id) && in_array("delete", $_POST)) { + $mob_id = 0; + } + + //$mob = new ilObjMediaObject($mob_id); + $mob = new ilPCMediaObject($this); + $mob->readMediaObject($mob_id); + + //$mob->setDom($this->dom); + $mob->setNode($cont_node); + $mob->setHierId($a_hier_id); + $mob->setPcId($a_pc_id); + return $mob; + } + + // + // generic procedure + // + + $pc_def = ilCOPagePCDef::getPCDefinitionByName($node_name); + + // check if pc definition has been found + if (!is_array($pc_def)) { + include_once("./Services/COPage/exceptions/class.ilCOPageUnknownPCTypeException.php"); + throw new ilCOPageUnknownPCTypeException('Unknown PC Name "' . $node_name . '".'); + } + $pc_class = "ilPC" . $pc_def["name"]; + $pc_path = "./" . $pc_def["component"] . "/" . $pc_def["directory"] . "/class." . $pc_class . ".php"; + require_once($pc_path); + $pc = new $pc_class($this); + $pc->setNode($cont_node); + $pc->setHierId($a_hier_id); + $pc->setPcId($a_pc_id); + return $pc; + } + + /** + * Get content node from dom + * + * @param string $a_hier_id hierarchical ID + * @param string $a_pc_id page content ID + */ + public function &getContentNode($a_hier_id, $a_pc_id = "") + { + $xpc = xpath_new_context($this->dom); + if ($a_hier_id == "pg") { + return $this->node; + } else { + // get per pc id + if ($a_pc_id != "") { + $path = "//*[@PCID = '$a_pc_id']"; + $res = xpath_eval($xpc, $path); + if (count($res->nodeset) == 1) { + $cont_node = $res->nodeset[0]; + return $cont_node; + } + } + + // fall back to hier id + $path = "//*[@HierId = '$a_hier_id']"; + $res = xpath_eval($xpc, $path); + if (count($res->nodeset) == 1) { + $cont_node = $res->nodeset[0]; + return $cont_node; + } + } + } + + /** + * Get content node from dom + * + * @param string $a_hier_id hierarchical ID + * @param string $a_pc_id page content ID + */ + public function checkForTag($a_content_tag, $a_hier_id, $a_pc_id = "") + { + $xpc = xpath_new_context($this->dom); + // get per pc id + if ($a_pc_id != "") { + $path = "//*[@PCID = '$a_pc_id']//" . $a_content_tag; + $res = xpath_eval($xpc, $path); + if (count($res->nodeset) > 0) { + return true; + } + } + + // fall back to hier id + $path = "//*[@HierId = '$a_hier_id']//" . $a_content_tag; + $res = xpath_eval($xpc, $path); + if (count($res->nodeset) > 0) { + return true; + } + return false; + } + + // only for test purposes + public function lookforhier($a_hier_id) + { + $xpc = xpath_new_context($this->dom); + $path = "//*[@HierId = '$a_hier_id']"; + $res = xpath_eval($xpc, $path); + if (count($res->nodeset) == 1) { + return "YES"; + } else { + return "NO"; + } + } + + + public function &getNode() + { + return $this->node; + } + + + /** + * set xml content of page, start with , + * end with , comply with ILIAS DTD, omit MetaData, use utf-8! + * + * @param string $a_xml xml content + * @param string $a_encoding encoding of the content (here is no conversion done! + * it must be already utf-8 encoded at the time) + */ + public function setXMLContent($a_xml, $a_encoding = "UTF-8") + { + $this->encoding = $a_encoding; + $this->xml = $a_xml; + } + + /** + * append xml content to page + * setXMLContent must be called before and the same encoding must be used + * + * @param string $a_xml xml content + */ + public function appendXMLContent($a_xml) + { + $this->xml.= $a_xml; + } + + + /** + * get xml content of page + */ + public function getXMLContent($a_incl_head = false) + { + // build full http path for XML DOCTYPE header. + // Under windows a relative path doesn't work :-( + if ($a_incl_head) { + //echo "+".$this->encoding."+"; + $enc_str = (!empty($this->encoding)) + ? "encoding=\"" . $this->encoding . "\"" + : ""; + return "" . + "cur_dtd . "\">" . + $this->xml; + } else { + return $this->xml; + } + } + + /** + * Copy content of page; replace page components with copies + * where necessary (e.g. questions) + */ + public function copyXmlContent($a_clone_mobs = false) + { + $xml = $this->getXmlContent(); + $temp_dom = domxml_open_mem( + '' . $xml, + DOMXML_LOAD_PARSING, + $error + ); + if (empty($error)) { + $this->handleCopiedContent($temp_dom, true, $a_clone_mobs); + } + $xml = $temp_dom->dump_mem(0, $this->encoding); + $xml = preg_replace('/<\?xml[^>]*>/i', "", $xml); + $xml = preg_replace('/]*>/i', "", $xml); + + return $xml; + } + + // @todo 1: begin: generalize, remove concrete dependencies + + /** + * Handle copied content + * + * This function copies items, that must be copied, if page + * content is duplicated. + * + * @param + * @return + */ + public function handleCopiedContent($a_dom, $a_self_ass = true, $a_clone_mobs = false) + { + include_once("./Services/COPage/classes/class.ilCOPagePCDef.php"); + $defs = ilCOPagePCDef::getPCDefinitions(); + + // handle question elements + if ($a_self_ass) { + $this->newQuestionCopies($a_dom); + } else { + $this->removeQuestions($a_dom); + } + + // handle interactive images + $this->newIIMCopies($a_dom); + + // handle media objects + if ($a_clone_mobs) { + $this->newMobCopies($a_dom); + } + + // @todo 1: move all functions from above to the new domdoc + if ($a_dom instanceof php4DOMDocument) { + $a_dom = $a_dom->myDOMDocument; + } + foreach ($defs as $def) { + ilCOPagePCDef::requirePCClassByName($def["name"]); + $cl = $def["pc_class"]; + if ($cl == 'ilPCPlugged') { + // the page object is provided for ilPageComponentPlugin + ilPCPlugged::handleCopiedPluggedContent($this, $a_dom); + } else { + $cl::handleCopiedContent($a_dom, $a_self_ass, $a_clone_mobs); + } + } + } + + /** + * Handle content before deletion + * This currently treats only plugged content + * If no node is given, then the whole dom will be scanned + * + * @param php4DOMNode|DOMNode|null $a_node + */ + public function handleDeleteContent($a_node = null) + { + if (!isset($a_node)) { + $xpc = xpath_new_context($this->dom); + $path = "//PageContent"; + $res = xpath_eval($xpc, $path); + $nodes = $res->nodeset; + } else { + $nodes = array($a_node); + } + + require_once('Services/COPage/classes/class.ilPCPlugged.php'); + foreach ($nodes as $node) { + if ($node instanceof php4DOMNode) { + $node = $node->myDOMNode; + } + + /** @var DOMElement $node */ + if ($node->firstChild->nodeName == 'Plugged') { + ilPCPlugged::handleDeletedPluggedNode($this, $node->firstChild); + } + } + } + + /** + * Replaces media objects in interactive images + * with copies of the interactive images + */ + public function newIIMCopies($temp_dom) + { + // Get question IDs + $path = "//InteractiveImage/MediaAlias"; + $xpc = xpath_new_context($temp_dom); + $res = &xpath_eval($xpc, $path); + + $q_ids = array(); + include_once("./Services/Link/classes/class.ilInternalLink.php"); + for ($i = 0; $i < count($res->nodeset); $i++) { + $or_id = $res->nodeset[$i]->get_attribute("OriginId"); + + $inst_id = ilInternalLink::_extractInstOfTarget($or_id); + $mob_id = ilInternalLink::_extractObjIdOfTarget($or_id); + + if (!($inst_id > 0)) { + if ($mob_id > 0) { + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $media_object = new ilObjMediaObject($mob_id); + + // now copy this question and change reference to + // new question id + $new_mob = $media_object->duplicate(); + + $res->nodeset[$i]->set_attribute("OriginId", "il__mob_" . $new_mob->getId()); + } + } + } + } + + /** + * Replaces media objects with copies + */ + public function newMobCopies($temp_dom) + { + // Get question IDs + $path = "//MediaObject/MediaAlias"; + $xpc = xpath_new_context($temp_dom); + $res = &xpath_eval($xpc, $path); + + $q_ids = array(); + include_once("./Services/Link/classes/class.ilInternalLink.php"); + for ($i = 0; $i < count($res->nodeset); $i++) { + $or_id = $res->nodeset[$i]->get_attribute("OriginId"); + + $inst_id = ilInternalLink::_extractInstOfTarget($or_id); + $mob_id = ilInternalLink::_extractObjIdOfTarget($or_id); + + if (!($inst_id > 0)) { + if ($mob_id > 0) { + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $media_object = new ilObjMediaObject($mob_id); + + // now copy this question and change reference to + // new question id + $new_mob = $media_object->duplicate(); + + $res->nodeset[$i]->set_attribute("OriginId", "il__mob_" . $new_mob->getId()); + } + } + } + } + + /** + * Replaces existing question content elements with + * new copies + */ + public function newQuestionCopies(&$temp_dom) + { + // Get question IDs + $path = "//Question"; + $xpc = xpath_new_context($temp_dom); + $res = &xpath_eval($xpc, $path); + + $q_ids = array(); + include_once("./Services/Link/classes/class.ilInternalLink.php"); + for ($i = 0; $i < count($res->nodeset); $i++) { + $qref = $res->nodeset[$i]->get_attribute("QRef"); + + $inst_id = ilInternalLink::_extractInstOfTarget($qref); + $q_id = ilInternalLink::_extractObjIdOfTarget($qref); + + if (!($inst_id > 0)) { + if ($q_id > 0) { + include_once "./Modules/TestQuestionPool/classes/class.assQuestion.php"; + $question = assQuestion::_instantiateQuestion($q_id); + // check due to #16557 + if (is_object($question) && $question->isComplete()) { + // check if page for question exists + // due to a bug in early 4.2.x version this is possible + if (!ilPageObject::_exists("qpl", $q_id)) { + $question->createPageObject(); + } + + // now copy this question and change reference to + // new question id + $duplicate_id = $question->duplicate(false); + $res->nodeset[$i]->set_attribute("QRef", "il__qst_" . $duplicate_id); + } + } + } + } + } + + /** + * Remove questions from document + * + * @param + * @return + */ + public function removeQuestions(&$temp_dom) + { + // Get question IDs + $path = "//Question"; + $xpc = xpath_new_context($temp_dom); + $res = &xpath_eval($xpc, $path); + for ($i = 0; $i < count($res->nodeset); $i++) { + $parent_node = $res->nodeset[$i]->parent_node(); + $parent_node->unlink_node($parent_node); + } + } + + // @todo: end + + /** + * Remove questions from document + * + * @param + * @return + */ + public function countPageContents() + { + // Get question IDs + $this->buildDom(); + $path = "//PageContent"; + $xpc = xpath_new_context($this->dom); + $res = &xpath_eval($xpc, $path); + return count($res->nodeset); + } + + /** + * get xml content of page from dom + * (use this, if any changes are made to the document) + */ + public function getXMLFromDom( + $a_incl_head = false, + $a_append_mobs = false, + $a_append_bib = false, + $a_append_str = "", + $a_omit_pageobject_tag = false + ) { + if ($a_incl_head) { + //echo "\n
          #".$this->encoding."#"; + return $this->dom->dump_mem(0, $this->encoding); + } else { + // append multimedia object elements + if ($a_append_mobs || $a_append_bib || $a_append_link_info) { + $mobs = ""; + $bibs = ""; + if ($a_append_mobs) { + $mobs = $this->getMultimediaXML(); + } + if ($a_append_bib) { + // deprecated // $bibs = $this->getBibliographyXML(); - } - $trans = $this->getLanguageVariablesXML(); - //echo htmlentities($this->dom->dump_node($this->node)); exit; - return "".$this->dom->dump_node($this->node).$mobs.$bibs.$trans.$a_append_str.""; - } - else - { - if (is_object($this->dom)) - { - if ($a_omit_pageobject_tag) - { - $xml = ""; - $childs = $this->node->child_nodes(); - for($i = 0; $i < count($childs); $i++) - { - $xml.= $this->dom->dump_node($childs[$i]); - } - return $xml; - } - else - { - $xml = $this->dom->dump_mem(0, $this->encoding); - $xml = preg_replace('/<\?xml[^>]*>/i',"",$xml); - $xml = preg_replace('/]*>/i',"",$xml); - return $xml; - - // don't use dump_node. This gives always entities. - //return $this->dom->dump_node($this->node); - } - } - else - { - return ""; - } - } - } - } - - /** - * Get language variables as XML - */ - function getLanguageVariablesXML() - { - $xml = ""; - $lang_vars = array( - "ed_paste_clip", "ed_edit", "ed_edit_prop", "ed_delete", "ed_moveafter", - "ed_movebefore", "ed_go", "ed_class", "ed_width", "ed_align_left", - "ed_align_right", "ed_align_center", "ed_align_left_float", - "ed_align_right_float", "ed_delete_item", "ed_new_item_before", - "ed_new_item_after", "ed_copy_clip", "please_select", "ed_split_page", - "ed_item_up", "ed_item_down", "ed_split_page_next","ed_enable", - "de_activate", "ed_paste", "ed_edit_multiple", "ed_cut", "ed_copy", "ed_insert_templ", - "ed_click_to_add_pg", "download"); - - // collect lang vars from pc elements - include_once("./Services/COPage/classes/class.ilCOPagePCDef.php"); - $defs = ilCOPagePCDef::getPCDefinitions(); - foreach ($defs as $def) - { - $lang_vars[] = "pc_".$def["pc_type"]; - $lang_vars[] = "ed_insert_".$def["pc_type"]; - - ilCOPagePCDef::requirePCClassByName($def["name"]); - $cl = $def["pc_class"]; - $lvs = call_user_func($def["pc_class"].'::getLangVars'); - foreach ($lvs as $lv) - { - $lang_vars[] = $lv; - } - } - - foreach ($lang_vars as $lang_var) - { - $this->appendLangVarXML($xml, $lang_var); - } - - $xml.= ""; - - return $xml; - } - - function appendLangVarXML(&$xml, $var) - { - $xml.= "lng->txt("cont_".$var)."\"/>"; - } - -// @todo begin: move this to paragraph class - - function getFirstParagraphText() - { - if($this->dom) - { - require_once("./Services/COPage/classes/class.ilPCParagraph.php"); - $xpc = xpath_new_context($this->dom); - $path = "//Paragraph[1]"; - $res = xpath_eval($xpc, $path); - if (count($res->nodeset) > 0) - { - $cont_node = $res->nodeset[0]->parent_node(); - $par = new ilPCParagraph($this); - $par->setNode($cont_node); - return $par->getText(); - } - } - return ""; - } - - /** - * Set content of paragraph - * - * @param string $a_hier_id Hier ID - * @param string $a_content Content - */ - function setParagraphContent($a_hier_id, $a_content) - { - $node = $this->getContentNode($a_hier_id); - if (is_object($node)) - { - $node->set_content($a_content); - } - } - -// @todo end - - - /** - * lm parser set this flag to true, if the page contains intern links - * (this method should only be called by the import parser) - * - * todo: move to ilLMPageObject !? - * - * @param boolean $a_contains_link true, if page contains intern link tag(s) - */ - // @todo: can we do this better - function setContainsIntLink($a_contains_link) - { - $this->contains_int_link = $a_contains_link; - } - - /** - * returns true, if page was marked as containing an intern link (via setContainsIntLink) - * (this method should only be called by the import parser) - */ - // @todo: can we do this better - function containsIntLink() - { - return $this->contains_int_link; - } - - /** - * Set import mode - * - * @param bool $a_val import mode - */ - function setImportMode($a_val) - { - $this->import_mode = $a_val; - } - - /** - * Get import mode - * - * @return bool import mode - */ - function getImportMode() - { - return $this->import_mode; - } - - function needsImportParsing($a_parse = "") - { - - if ($a_parse === true) - { - $this->needs_parsing = true; - } - if ($a_parse === false) - { - $this->needs_parsing = false; - } - return $this->needs_parsing; - } - - /** - * Set contains question - * - * @param boolean $a_val contains question - */ - // @todo: can we do this better - public function setContainsQuestion($a_val) - { - $this->contains_question = $a_val; - } - - /** - * Get contains question - * - * @return boolean contains question - */ - public function getContainsQuestion() - { - return $this->contains_question; - } - - - /** - * get all media objects, that are referenced and used within - * the page - */ - // @todo: move to media class - function collectMediaObjects($a_inline_only = true) - { -//echo htmlentities($this->getXMLFromDom()); - // determine all media aliases of the page - $xpc = xpath_new_context($this->dom); - $path = "//MediaObject/MediaAlias"; - $res = xpath_eval($xpc, $path); - $mob_ids = array(); - for($i = 0; $i < count($res->nodeset); $i++) - { - $id_arr = explode("_", $res->nodeset[$i]->get_attribute("OriginId")); - $mob_id = $id_arr[count($id_arr) - 1]; - $mob_ids[$mob_id] = $mob_id; - } - - // determine all media aliases of interactive images - $xpc = xpath_new_context($this->dom); - $path = "//InteractiveImage/MediaAlias"; - $res = xpath_eval($xpc, $path); - for($i = 0; $i < count($res->nodeset); $i++) - { - $id_arr = explode("_", $res->nodeset[$i]->get_attribute("OriginId")); - $mob_id = $id_arr[count($id_arr) - 1]; - $mob_ids[$mob_id] = $mob_id; - } - - // determine all inline internal media links - $xpc = xpath_new_context($this->dom); - $path = "//IntLink[@Type = 'MediaObject']"; - $res = xpath_eval($xpc, $path); - - for($i = 0; $i < count($res->nodeset); $i++) - { - if (($res->nodeset[$i]->get_attribute("TargetFrame") == "") || - (!$a_inline_only)) - { - $target = $res->nodeset[$i]->get_attribute("Target"); - $id_arr = explode("_", $target); - if (($id_arr[1] == IL_INST_ID) || - (substr($target, 0, 4) == "il__")) - { - $mob_id = $id_arr[count($id_arr) - 1]; - if (ilObject::_exists($mob_id)) - { - $mob_ids[$mob_id] = $mob_id; - } - } - } - } - - return $mob_ids; - } - - - /** - * get all internal links that are used within the page - */ - // @todo: can we do this better? - function getInternalLinks($a_cnt_multiple = false) - { - // get all internal links of the page - $xpc = xpath_new_context($this->dom); - $path = "//IntLink"; - $res = xpath_eval($xpc, $path); - - $links = array(); - $cnt_multiple = 1; - for($i = 0; $i < count($res->nodeset); $i++) - { - $add = ""; - if ($a_cnt_multiple) - { - $add = ":".$cnt_multiple; - } - $target = $res->nodeset[$i]->get_attribute("Target"); - $type = $res->nodeset[$i]->get_attribute("Type"); - $targetframe = $res->nodeset[$i]->get_attribute("TargetFrame"); - $anchor = $res->nodeset[$i]->get_attribute("Anchor"); - $links[$target.":".$type.":".$targetframe.":".$anchor.$add] = - array("Target" => $target, "Type" => $type, - "TargetFrame" => $targetframe, "Anchor" => $anchor); - - // get links (image map areas) for inline media objects - if ($type == "MediaObject" && $targetframe == "") - { - if (substr($target, 0, 4) =="il__") - { - $id_arr = explode("_", $target); - $id = $id_arr[count($id_arr) - 1]; - - $med_links = ilMediaItem::_getMapAreasIntLinks($id); - foreach($med_links as $key => $med_link) - { - $links[$key] = $med_link; - } - } - - } -//echo "
          -:".$target.":".$type.":".$targetframe.":-"; - $cnt_multiple++; - } - unset($xpc); - - // get all media aliases - $xpc = xpath_new_context($this->dom); - $path = "//MediaAlias"; - $res = xpath_eval($xpc, $path); - - require_once("Services/MediaObjects/classes/class.ilMediaItem.php"); - for($i = 0; $i < count($res->nodeset); $i++) - { - $oid = $res->nodeset[$i]->get_attribute("OriginId"); - if (substr($oid, 0, 4) =="il__") - { - $id_arr = explode("_", $oid); - $id = $id_arr[count($id_arr) - 1]; - - $med_links = ilMediaItem::_getMapAreasIntLinks($id); - foreach($med_links as $key => $med_link) - { - $links[$key] = $med_link; - } - } - } - unset($xpc); - - return $links; - } - - /** - * get a xml string that contains all media object elements, that - * are referenced by any media alias in the page - */ - // @todo: move to media class - function getMultimediaXML() - { - $mob_ids = $this->collectMediaObjects(); - - // get xml of corresponding media objects - $mobs_xml = ""; - require_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - foreach($mob_ids as $mob_id => $dummy) - { - if (ilObject::_lookupType($mob_id) == "mob") - { - $mob_obj = new ilObjMediaObject($mob_id); - $mobs_xml .= $mob_obj->getXML(IL_MODE_OUTPUT, $a_inst = 0, true); - } - } -//var_dump($mobs_xml); - return $mobs_xml; - } - - /** - * get complete media object (alias) element - */ - // @todo: move to media class - function getMediaAliasElement($a_mob_id, $a_nr = 1) - { - $xpc = xpath_new_context($this->dom); - $path = "//MediaObject/MediaAlias[@OriginId='il__mob_$a_mob_id']"; - $res = xpath_eval($xpc, $path); - $mal_node = $res->nodeset[$a_nr - 1]; - $mob_node = $mal_node->parent_node(); - - return $this->dom->dump_node($mob_node); - } - - /** - * Validate the page content agains page DTD - * - * @return array Error array. - */ - function validateDom() - { - $this->stripHierIDs(); - - // possible fix for #14820 - libxml_disable_entity_loader(false); - - @$this->dom->validate($error); - //var_dump($this->dom); exit; - return $error; - } - - /** - * Add hierarchical ID (e.g. for editing) attributes "HierId" to current dom tree. - * This attribute will be added to the following elements: - * PageObject, Paragraph, Table, TableRow, TableData. - * Only elements of these types are counted as "childs" here. - * - * Hierarchical IDs have the format "x_y_z_...", e.g. "1_4_2" means: second - * child of fourth child of first child of page. - * - * The PageObject element gets the special id "pg". The first child of the - * page starts with id 1. The next child gets the 2 and so on. - * - * Another example: The first child of the page is a Paragraph -> id 1. - * The second child is a table -> id 2. The first row gets the id 2_1, the - */ - // @todo: can we do this better? remove dependencies? - function addHierIDs() - { - $this->hier_ids = array(); - $this->first_row_ids = array(); - $this->first_col_ids = array(); - $this->list_item_ids = array(); - $this->file_item_ids = array(); - - // set hierarchical ids for Paragraphs, Tables, TableRows and TableData elements - $xpc = xpath_new_context($this->dom); - //$path = "//Paragraph | //Table | //TableRow | //TableData"; - - $sep = $path = ""; - foreach ($this->id_elements as $el) - { - $path.= $sep."//".$el; - $sep = " | "; - } - - $res = xpath_eval($xpc, $path); - for($i = 0; $i < count($res->nodeset); $i++) - { - $cnode = $res->nodeset[$i]; - $ctag = $cnode->node_name(); - - // get hierarchical id of previous sibling - $sib_hier_id = ""; - while($cnode = $cnode->previous_sibling()) - { - if (($cnode->node_type() == XML_ELEMENT_NODE) - && $cnode->has_attribute("HierId")) - { - $sib_hier_id = $cnode->get_attribute("HierId"); - //$sib_hier_id = $id_attr->value(); - break; - } - } - - if ($sib_hier_id != "") // set id to sibling id "+ 1" - { - require_once("./Services/COPage/classes/class.ilPageContent.php"); - $node_hier_id = ilPageContent::incEdId($sib_hier_id); - $res->nodeset[$i]->set_attribute("HierId", $node_hier_id); - $this->hier_ids[] = $node_hier_id; - if ($ctag == "TableData") - { - if (substr($par_hier_id,strlen($par_hier_id)-2) == "_1") - { - $this->first_row_ids[] = $node_hier_id; - } - } - if ($ctag == "ListItem") - { - $this->list_item_ids[] = $node_hier_id; - } - if ($ctag == "FileItem") - { - $this->file_item_ids[] = $node_hier_id; - } - } - else // no sibling -> node is first child - { - // get hierarchical id of next parent - $cnode = $res->nodeset[$i]; - $par_hier_id = ""; - while($cnode = $cnode->parent_node()) - { - if (($cnode->node_type() == XML_ELEMENT_NODE) - && $cnode->has_attribute("HierId")) - { - $par_hier_id = $cnode->get_attribute("HierId"); - //$par_hier_id = $id_attr->value(); - break; - } - } -//echo "
          par:".$par_hier_id." ($ctag)"; - if (($par_hier_id != "") && ($par_hier_id != "pg")) // set id to parent_id."_1" - { - $node_hier_id = $par_hier_id."_1"; - $res->nodeset[$i]->set_attribute("HierId", $node_hier_id); - $this->hier_ids[] = $node_hier_id; - if ($ctag == "TableData") - { - $this->first_col_ids[] = $node_hier_id; - if (substr($par_hier_id,strlen($par_hier_id)-2) == "_1") - { - $this->first_row_ids[] = $node_hier_id; - } - } - if ($ctag == "ListItem") - { - $this->list_item_ids[] = $node_hier_id; - } - if ($ctag == "FileItem") - { - $this->file_item_ids[] = $node_hier_id; - } - - } - else // no sibling, no parent -> first node - { - $node_hier_id = "1"; - $res->nodeset[$i]->set_attribute("HierId", $node_hier_id); - $this->hier_ids[] = $node_hier_id; - } - } - } - - // set special hierarchical id "pg" for pageobject - $xpc = xpath_new_context($this->dom); - $path = "//PageObject"; - $res = xpath_eval($xpc, $path); - for($i = 0; $i < count($res->nodeset); $i++) // should only be 1 - { - $res->nodeset[$i]->set_attribute("HierId", "pg"); - $this->hier_ids[] = "pg"; - } - unset($xpc); - } - - /** - * get all hierarchical ids - */ - function getHierIds() - { - return $this->hier_ids; - } - - /** - * get ids of all first table rows - */ - // @todo: move to table classes - function getFirstRowIds() - { - return $this->first_row_ids; - } - - /** - * get ids of all first table columns - */ - // @todo: move to table classes - function getFirstColumnIds() - { - return $this->first_col_ids; - } - - /** - * get ids of all list items - */ - // @todo: move to list class - function getListItemIds() - { - return $this->list_item_ids; - } - - /** - * get ids of all file items - */ - // @todo: move to file item class - function getFileItemIds() - { - return $this->file_item_ids; - } - - /** - * strip all hierarchical id attributes out of the dom tree - */ - function stripHierIDs() - { - if(is_object($this->dom)) - { - $xpc = xpath_new_context($this->dom); - $path = "//*[@HierId]"; - $res = xpath_eval($xpc, $path); - for($i = 0; $i < count($res->nodeset); $i++) // should only be 1 - { - if ($res->nodeset[$i]->has_attribute("HierId")) - { - $res->nodeset[$i]->remove_attribute("HierId"); - } - } - unset($xpc); - } - } - - /** - * Get hier ids for a set of pc ids - */ - function getHierIdsForPCIds($a_pc_ids) - { - if (!is_array($a_pc_ids) || count($a_pc_ids) == 0) - { - return array(); - } - $ret = array(); - - if(is_object($this->dom)) - { - $xpc = xpath_new_context($this->dom); - $path = "//*[@PCID]"; - $res = xpath_eval($xpc, $path); - for($i = 0; $i < count($res->nodeset); $i++) // should only be 1 - { - $pc_id = $res->nodeset[$i]->get_attribute("PCID"); - if (in_array($pc_id, $a_pc_ids)) - { - $ret[$pc_id] = $res->nodeset[$i]->get_attribute("HierId"); - } - } - unset($xpc); - } -//var_dump($ret); - return $ret; - } - - /** - * add file sizes - */ - // @todo: move to file item class - function addFileSizes() - { - $xpc = xpath_new_context($this->dom); - $path = "//FileItem"; - $res = xpath_eval($xpc, $path); - for($i = 0; $i < count($res->nodeset); $i++) - { - $cnode = $res->nodeset[$i]; - $size_node = $this->dom->create_element("Size"); - $size_node = $cnode->append_child($size_node); - - $childs = $cnode->child_nodes(); - $size = ""; - for($j = 0; $j < count($childs); $j++) - { - if ($childs[$j]->node_name() == "Identifier") - { - if ($childs[$j]->has_attribute("Entry")) - { - $entry = $childs[$j]->get_attribute("Entry"); - $entry_arr = explode("_", $entry); - $id = $entry_arr[count($entry_arr) - 1]; - require_once("./Modules/File/classes/class.ilObjFile.php"); - $size = ilObjFile::_lookupFileSize($id); - } - } - } - $size_node->set_content($size); - } - - unset($xpc); - } - - /** - * Resolves all internal link targets of the page, if targets are available - * (after import) - */ - // @todo: possible to improve this? - function resolveIntLinks($a_link_map = null) - { - $changed = false; - - $this->log->debug("start"); - - // resolve normal internal links - $xpc = xpath_new_context($this->dom); - $path = "//IntLink"; - $res = xpath_eval($xpc, $path); - for($i = 0; $i < count($res->nodeset); $i++) - { - $target = $res->nodeset[$i]->get_attribute("Target"); - $type = $res->nodeset[$i]->get_attribute("Type"); - - if ($a_link_map == null) - { - $new_target = ilInternalLink::_getIdForImportId($type, $target); - $this->log->debug("no map, type: ".$type.", target: ".$target.", new target: ".$new_target); -// echo "-".$new_target."-".$type."-".$target."-"; exit; - } - else - { - $nt = explode("_", $a_link_map[$target]); - $new_target = false; - if ($nt[1] == IL_INST_ID) - { - $new_target = "il__".$nt[2]."_".$nt[3]; - } - $this->log->debug("map, type: ".$type.", target: ".$target.", new target: ".$new_target); - } - if ($new_target !== false) - { - $res->nodeset[$i]->set_attribute("Target", $new_target); - $changed = true; - } - else // check wether link target is same installation - { - if (ilInternalLink::_extractInstOfTarget($target) == IL_INST_ID && - IL_INST_ID > 0 && $type != "RepositoryItem") - { - $new_target = ilInternalLink::_removeInstFromTarget($target); - if (ilInternalLink::_exists($type, $new_target)) - { - $res->nodeset[$i]->set_attribute("Target", $new_target); - $changed = true; - } - } - } - - } - unset($xpc); - - // resolve internal links in map areas - $xpc = xpath_new_context($this->dom); - $path = "//MediaAlias"; - $res = xpath_eval($xpc, $path); -//echo "
          page::resolve
          "; -//echo "Content:".htmlentities($this->getXMLFromDOM()).":
          "; - for($i = 0; $i < count($res->nodeset); $i++) - { - $orig_id = $res->nodeset[$i]->get_attribute("OriginId"); - $id_arr = explode("_", $orig_id); - $mob_id = $id_arr[count($id_arr) - 1]; - ilMediaItem::_resolveMapAreaLinks($mob_id); - } - return $changed; - } - - /** - * Resolve media aliases - * (after import) - * - * @param array mapping array - */ - // @todo: move to media classes? - function resolveMediaAliases($a_mapping, $a_reuse_existing_by_import = false) - { - // resolve normal internal links - $xpc = xpath_new_context($this->dom); - $path = "//MediaAlias"; - $res = xpath_eval($xpc, $path); - $changed = false; - for($i = 0; $i < count($res->nodeset); $i++) - { - // get the ID of the import file from the xml - $old_id = $res->nodeset[$i]->get_attribute("OriginId"); - $old_id = explode("_", $old_id); - $old_id = $old_id[count($old_id) - 1]; - $new_id = ""; - $import_id = ""; - // get the new id from the current mapping - if ($a_mapping[$old_id] > 0) - { - $new_id = $a_mapping[$old_id]; - if ($a_reuse_existing_by_import) - { - // this should work, if the lm has been imported in a translation installation and re-exported - $import_id = ilObject::_lookupImportId($new_id); - $imp = explode("_", $import_id); - if ($imp[1] == IL_INST_ID && $imp[2] == "mob" && ilObject::_lookupType($imp[3]) == "mob") - { - $new_id = $imp[3]; - } - } - } - // now check, if the translation has been done just by changing text in the exported - // translation file - if ($import_id == "" && $a_reuse_existing_by_import) - { - // if the old_id is also referred by the page content of the default language - // we assume that this media object is unchanged - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $med_of_def_lang = ilObjMediaObject::_getMobsOfObject($this->getParentType().":pg", $this->getId(), 0, "-"); - if (in_array($old_id, $med_of_def_lang)) - { - $new_id = $old_id; - } - } - if ($new_id != "") - { - $res->nodeset[$i]->set_attribute("OriginId", "il__mob_".$new_id); - $changed = true; - } - } - unset($xpc); - return $changed; - } - - /** - * Resolve iim media aliases - * (in ilContObjParse) - * - * @param array mapping array - */ - // @todo: move to iim classes? - function resolveIIMMediaAliases($a_mapping) - { - // resolve normal internal links - $xpc = xpath_new_context($this->dom); - $path = "//InteractiveImage/MediaAlias"; - $res = xpath_eval($xpc, $path); - $changed = false; - for($i = 0; $i < count($res->nodeset); $i++) - { - $old_id = $res->nodeset[$i]->get_attribute("OriginId"); - if ($a_mapping[$old_id] > 0) - { - $res->nodeset[$i]->set_attribute("OriginId", "il__mob_".$a_mapping[$old_id]); - $changed = true; - } - } - unset($xpc); - - return $changed; - } - - /** - * Resolve file items - * (after import) - * - * @param array mapping array - */ - // @todo: move to file classes? - function resolveFileItems($a_mapping) - { - // resolve normal internal links - $xpc = xpath_new_context($this->dom); - $path = "//FileItem/Identifier"; - $res = xpath_eval($xpc, $path); - $changed = false; - for($i = 0; $i < count($res->nodeset); $i++) - { - $old_id = $res->nodeset[$i]->get_attribute("Entry"); - $old_id = explode("_", $old_id); - $old_id = $old_id[count($old_id) - 1]; - if ($a_mapping[$old_id] > 0) - { - $res->nodeset[$i]->set_attribute("Entry", "il__file_".$a_mapping[$old_id]); - $changed = true; - } - } - unset($xpc); - - return $changed; - } - - /** - * Resolve all quesion references - * (after import) - */ - // @todo: move to question classes - function resolveQuestionReferences($a_mapping) - { - // resolve normal internal links - $xpc = xpath_new_context($this->dom); - $path = "//Question"; - $res = xpath_eval($xpc, $path); - $updated = false; - for($i = 0; $i < count($res->nodeset); $i++) - { - $qref = $res->nodeset[$i]->get_attribute("QRef"); - - if (isset($a_mapping[$qref])) - { - $res->nodeset[$i]->set_attribute("QRef", "il__qst_".$a_mapping[$qref]["pool"]); - $updated = true; - } - } - unset($xpc); - - return $updated; - } - - - /** - * Move internal links from one destination to another. This is used - * for pages and structure links. Just use IDs in "from" and "to". - * - * @param array keys are the old targets, values are the new targets - */ - // @todo: generalize, internal links usage info - function moveIntLinks($a_from_to) - { - $this->buildDom(); - - $changed = false; - - // resolve normal internal links - $xpc = xpath_new_context($this->dom); - $path = "//IntLink"; - $res = xpath_eval($xpc, $path); - for($i = 0; $i < count($res->nodeset); $i++) - { - $target = $res->nodeset[$i]->get_attribute("Target"); - $type = $res->nodeset[$i]->get_attribute("Type"); - $obj_id = ilInternalLink::_extractObjIdOfTarget($target); - if ($a_from_to[$obj_id] > 0 && is_int(strpos($target, "__"))) - { - if ($type == "PageObject" && ilLMObject::_lookupType($a_from_to[$obj_id]) == "pg") - { - $res->nodeset[$i]->set_attribute("Target", "il__pg_".$a_from_to[$obj_id]); - $changed = true; - } - if ($type == "StructureObject" && ilLMObject::_lookupType($a_from_to[$obj_id]) == "st") - { - $res->nodeset[$i]->set_attribute("Target", "il__st_".$a_from_to[$obj_id]); - $changed = true; - } - if ($type == "PortfolioPage") - { - $res->nodeset[$i]->set_attribute("Target", "il__ppage_".$a_from_to[$obj_id]); - $changed = true; - } - } - } - unset($xpc); - - // map areas - $this->addHierIDs(); - $xpc = xpath_new_context($this->dom); - $path = "//MediaAlias"; - $res = xpath_eval($xpc, $path); - - require_once("Services/MediaObjects/classes/class.ilMediaItem.php"); - require_once("Services/COPage/classes/class.ilMediaAliasItem.php"); - - for($i = 0; $i < count($res->nodeset); $i++) - { - $media_object_node = $res->nodeset[$i]->parent_node(); - $page_content_node = $media_object_node->parent_node(); - $c_hier_id = $page_content_node->get_attribute("HierId"); - - // first check, wheter we got instance map areas -> take these - $std_alias_item = new ilMediaAliasItem($this->dom, - $c_hier_id, "Standard"); - $areas = $std_alias_item->getMapAreas(); - $correction_needed = false; - if (count($areas) > 0) - { - // check if correction needed - foreach($areas as $area) - { - if ($area["Type"] == "PageObject" || - $area["Type"] == "StructureObject") - { - $t = $area["Target"]; - $tid = _extractObjIdOfTarget($t); - if ($a_from_to[$tid] > 0) - { - $correction_needed = true; - } - } - } - } - else - { - $areas = array(); - - // get object map areas and check whether at least one must - // be corrected - $oid = $res->nodeset[$i]->get_attribute("OriginId"); - if (substr($oid, 0, 4) =="il__") - { - $id_arr = explode("_", $oid); - $id = $id_arr[count($id_arr) - 1]; - - $mob = new ilObjMediaObject($id); - $med_item = $mob->getMediaItem("Standard"); - $med_areas = $med_item->getMapAreas(); - - foreach($med_areas as $area) - { - $link_type = ($area->getLinkType() == "int") - ? "IntLink" - : "ExtLink"; - - $areas[] = array( - "Nr" => $area->getNr(), - "Shape" => $area->getShape(), - "Coords" => $area->getCoords(), - "Link" => array( - "LinkType" => $link_type, - "Href" => $area->getHref(), - "Title" => $area->getTitle(), - "Target" => $area->getTarget(), - "Type" => $area->getType(), - "TargetFrame" => $area->getTargetFrame() - ) - ); - - if ($area->getType() == "PageObject" || - $area->getType() == "StructureObject") - { - $t = $area->getTarget(); - $tid = ilInternalLink::_extractObjIdOfTarget($t); - if ($a_from_to[$tid] > 0) - { - $correction_needed = true; - } -//var_dump($a_from_to); - } - } - } - } - - // correct map area links - if ($correction_needed) - { - $changed = true; - $std_alias_item->deleteAllMapAreas(); - foreach($areas as $area) - { - if ($area["Link"]["LinkType"] == "IntLink") - { - $target = $area["Link"]["Target"]; - $type = $area["Link"]["Type"]; - $obj_id = ilInternalLink::_extractObjIdOfTarget($target); - if ($a_from_to[$obj_id] > 0) - { - if ($type == "PageObject" && ilLMObject::_lookupType($a_from_to[$obj_id]) == "pg") - { - $area["Link"]["Target"] = "il__pg_".$a_from_to[$obj_id]; - } - if ($type == "StructureObject" && ilLMObject::_lookupType($a_from_to[$obj_id]) == "st") - { - $area["Link"]["Target"] = "il__st_".$a_from_to[$obj_id]; - } - } - } - - $std_alias_item->addMapArea($area["Shape"], $area["Coords"], - $area["Link"]["Title"], - array( "Type" => $area["Link"]["Type"], - "TargetFrame" => $area["Link"]["TargetFrame"], - "Target" => $area["Link"]["Target"], - "Href" => $area["Link"]["Href"], - "LinkType" => $area["Link"]["LinkType"], - )); - } - } - } - unset($xpc); - - return $changed; - } - - /** - * Change targest of repository links. Use full targets in "from" and "to"!!! - * - * @param array keys are the old targets, values are the new targets - */ - // @todo: generalize, internal links usage info - static function _handleImportRepositoryLinks($a_rep_import_id, $a_rep_type, $a_rep_ref_id) - { - include_once("./Services/Link/classes/class.ilInternalLink.php"); - -//echo "-".$a_rep_import_id."-".$a_rep_ref_id."-"; - $sources = ilInternalLink::_getSourcesOfTarget("obj", - ilInternalLink::_extractObjIdOfTarget($a_rep_import_id), - ilInternalLink::_extractInstOfTarget($a_rep_import_id)); -//var_dump($sources); - foreach($sources as $source) - { -//echo "A"; - if ($source["type"] == "lm:pg") - { -//echo "B"; - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - if (self::_exists("lm", $source["id"], $source["lang"])) - { - $page_obj = new ilLMPage($source["id"], 0, $source["lang"]); - if (!$page_obj->page_not_found) - { - //echo "C"; - $page_obj->handleImportRepositoryLink($a_rep_import_id, - $a_rep_type, $a_rep_ref_id); - } - $page_obj->update(); - } - } - } - } - - // @todo: generalize, internal links usage info - function handleImportRepositoryLink($a_rep_import_id, $a_rep_type, $a_rep_ref_id) - { - $this->buildDom(); - - // resolve normal internal links - $xpc = xpath_new_context($this->dom); - $path = "//IntLink"; - $res = xpath_eval($xpc, $path); -//echo "1"; - for($i = 0; $i < count($res->nodeset); $i++) - { -//echo "2"; - $target = $res->nodeset[$i]->get_attribute("Target"); - $type = $res->nodeset[$i]->get_attribute("Type"); - if ($target == $a_rep_import_id && $type == "RepositoryItem") - { -//echo "setting:"."il__".$a_rep_type."_".$a_rep_ref_id; - $res->nodeset[$i]->set_attribute("Target", - "il__".$a_rep_type."_".$a_rep_ref_id); - } - } - unset($xpc); - } - - /** - * Handle repository links on copy process - * @param array $a_mapping - * @param int $a_source_ref_id - */ - function handleRepositoryLinksOnCopy($a_mapping, $a_source_ref_id) - { - $tree = $this->tree; - $objDefinition = $this->obj_definition; - - $this->buildDom(); - $this->log->debug("Handle repository links..."); - - // resolve normal internal links - $xpc = xpath_new_context($this->dom); - $path = "//IntLink"; - $res = xpath_eval($xpc, $path); - for($i = 0; $i < count($res->nodeset); $i++) - { - $target = $res->nodeset[$i]->get_attribute("Target"); - $type = $res->nodeset[$i]->get_attribute("Type"); - $this->log->debug("Target: ".$target); - $t = explode("_", $target); - if ($type == "RepositoryItem" && ((int) $t[1] == 0 || (int) $t[1] == IL_INST_ID)) - { - if (isset($a_mapping[$t[3]])) - { - // we have a mapping -> replace the ID - $this->log->debug("... replace " . $t[3] . " with " . $a_mapping[$t[3]] . "."); - $res->nodeset[$i]->set_attribute("Target", - "il__obj_" . $a_mapping[$t[3]]); - } - else if ($this->tree->isGrandChild($a_source_ref_id, $t[3])) - { - // we have no mapping, but the linked object is child of the original node -> remove link - $this->log->debug("... remove links."); - if ($res->nodeset[$i]->parent_node()->node_name() == "MapArea") // simply remove map areas - { - $parent = $res->nodeset[$i]->parent_node(); - $parent->unlink_node($parent); - } - else // replace link by content of the link for other internal links - { - $source_node = $res->nodeset[$i]; - $new_node = $source_node->clone_node(true); - $new_node->unlink_node($new_node); - $childs = $new_node->child_nodes(); - for ($j = 0; $j < count($childs); $j++) - { - $this->log->debug("... move node $j " . $childs[$j]->node_name() . " before " . $source_node->node_name()); - $source_node->insert_before($childs[$j], $source_node); - } - $source_node->unlink_node($source_node); - } - } - } - } - unset($xpc); - - // resolve normal external links - $ilias_url = parse_url(ILIAS_HTTP_PATH); - $xpc = xpath_new_context($this->dom); - $path = "//ExtLink"; - $res = xpath_eval($xpc, $path); - for($i = 0; $i < count($res->nodeset); $i++) - { - $href = $res->nodeset[$i]->get_attribute("Href"); - $this->log->debug("Href: ".$href); - - $url = parse_url($href); - - // only handle links on same host - $this->log->debug("Host: ".$url["host"]); - if ($url["host"] != "" && $url["host"] != $ilias_url["host"]) - { - continue; - } - - // get parameters - $par = array(); - foreach (explode("&", $url["query"]) as $p) - { - $p = explode("=", $p); - $par[$p[0]] = $p[1]; - } - - $target_client_id = $par["client_id"]; - if ($target_client_id != "" && $target_client_id != CLIENT_ID) - { - continue; - } - - // get ref id - $ref_id = 0; - if (is_int(strpos($href, "goto.php"))) - { - $t = explode("_", $par["target"]); - if ($objDefinition->isRBACObject($t[0])) - { - $ref_id = (int) $t[1]; - $type = $t[0]; - } - } - else if (is_int(strpos($href, "ilias.php"))) - { - $ref_id = (int) $par["ref_id"]; - } - - - if ($ref_id > 0) - { - if (isset($a_mapping[$ref_id])) - { - $new_ref_id = $a_mapping[$ref_id]; - $new_href = ""; - // we have a mapping -> replace the ID - if (is_int(strpos($href, "goto.php"))) - { - $nt = str_replace($type."_".$ref_id, $type."_".$new_ref_id, $par["target"]); - $new_href = str_replace("target=".$par["target"], "target=".$nt, $href); - } - else if (is_int(strpos($href, "ilias.php"))) - { - $new_href = str_replace("ref_id=".$par["ref_id"], "ref_id=".$new_ref_id, $href); - } - if ($new_href != "") - { - $this->log->debug("... ext link replace " . $href . " with " . $new_href . "."); - $res->nodeset[$i]->set_attribute("Href", $new_href); - } - } - else if ($tree->isGrandChild($a_source_ref_id, $ref_id)) - { - // we have no mapping, but the linked object is child of the original node -> remove link - $this->log->debug("... remove ext links."); - if ($res->nodeset[$i]->parent_node()->node_name() == "MapArea") // simply remove map areas - { - $parent = $res->nodeset[$i]->parent_node(); - $parent->unlink_node($parent); - } - else // replace link by content of the link for other internal links - { - $source_node = $res->nodeset[$i]; - $new_node = $source_node->clone_node(true); - $new_node->unlink_node($new_node); - $childs = $new_node->child_nodes(); - for ($j = 0; $j < count($childs); $j++) - { - $this->log->debug("... move node $j " . $childs[$j]->node_name() . " before " . $source_node->node_name()); - $source_node->insert_before($childs[$j], $source_node); - } - $source_node->unlink_node($source_node); - } - } - } - } - unset($xpc); - - } - - - /** - * Create new page object with current xml content - */ - function createFromXML() - { - $empty = false; - if($this->getXMLContent() == "") - { - $this->setXMLContent(""); - $empty = true; - } - - $content = $this->getXMLContent(); - $this->buildDom(true); - $dom_doc = $this->getDomDoc(); - - $iel = $this->containsDeactivatedElements($content); - $inl = $this->containsIntLinks($content); - - // create object - $this->db->insert("page_object", array( - "page_id" => array("integer", $this->getId()), - "parent_id" => array("integer", $this->getParentId()), - "lang" => array("text", $this->getLanguage()), - "content" => array("clob", $content), - "parent_type" => array("text", $this->getParentType()), - "create_user" => array("integer", $this->user->getId()), - "last_change_user" => array("integer", $this->user->getId()), - "active" => array("integer", (int) $this->getActive()), - "activation_start" => array("timestamp", $this->getActivationStart()), - "activation_end" => array("timestamp", $this->getActivationEnd()), - "show_activation_info" => array("integer", (int) $this->getShowActivationInfo()), - "inactive_elements" => array("integer", $iel), - "int_links" => array("integer", $inl), - "created" => array("timestamp", ilUtil::now()), - "last_change" => array("timestamp", ilUtil::now()) - )); - - // after update event - $this->__afterUpdate($dom_doc, $content, true, $empty); - - } - - - /** - * Updates page object with current xml content - * - * This function is currently (4.4.0 alpha) called by: - * - ilContObjParser (LM and Glossary import parser) - * - ilSCORM13Package->dbImportSco (SCORM importer) - * - assQuestion->copyPageOfQuestion - */ - function updateFromXML() - { - $this->log->debug("ilPageObject, updateFromXML(): start, id: ".$this->getId()); - - $content = $this->getXMLContent(); - - $this->log->debug("ilPageObject, updateFromXML(): content: ".substr($content, 0, 100)); - - $this->buildDom(true); - $dom_doc = $this->getDomDoc(); - - $iel = $this->containsDeactivatedElements($content); - $inl = $this->containsIntLinks($content); - - $this->db->update("page_object", array( - "content" => array("clob", $content), - "parent_id" => array("integer", $this->getParentId()), - "last_change_user" => array("integer", $this->user->getId()), - "last_change" => array("timestamp", ilUtil::now()), - "active" => array("integer", $this->getActive()), - "activation_start" => array("timestamp", $this->getActivationStart()), - "activation_end" => array("timestamp", $this->getActivationEnd()), - "inactive_elements" => array("integer", $iel), - "int_links" => array("integer", $inl), - ), array( - "page_id" => array("integer", $this->getId()), - "parent_type" => array("text", $this->getParentType()), - "lang" => array("text", $this->getLanguage()) - )); - - // after update event - $this->__afterUpdate($dom_doc, $content); - - $this->log->debug("ilPageObject, updateFromXML(): end"); - - return true; - } - - /** - * After update event handler (internal). The hooks are e.g. for - * storing any dependent relations/references in the database. - * - * @param - */ - protected final function __afterUpdate($a_domdoc, $a_xml, $a_creation = false, $a_empty = false) - { - // we do not need this if we are creating an empty page - if (!$a_creation || !$a_empty) - { - // save internal link information - // the page object is responsible to do this, since it "offers" the - // internal link feature pc and page classes - $this->saveInternalLinks($a_domdoc); - - // save style usage - $this->saveStyleUsage($a_domdoc); - - // pc classes hook - include_once("./Services/COPage/classes/class.ilCOPagePCDef.php"); - $defs = ilCOPagePCDef::getPCDefinitions(); - foreach ($defs as $def) - { - ilCOPagePCDef::requirePCClassByName($def["name"]); - $cl = $def["pc_class"]; - call_user_func($def["pc_class"].'::afterPageUpdate', $this, $a_domdoc, $a_xml, $a_creation); - } - } - - // call page hook - $this->afterUpdate($a_domdoc, $a_xml); - - // call update listeners - $this->callUpdateListeners(); - } - - /** - * After update - * - * @param - * @return - */ - function afterUpdate() - { - } - - - /** - * update complete page content in db (dom xml content is used) - * - */ - function update($a_validate = true, $a_no_history = false) - { - $this->log->debug("ilPageObject, update(): start, id: ".$this->getId()); - - $lm_set = new ilSetting("lm"); - - // add missing pc ids - if (!$this->checkPCIds()) - { - $this->insertPCIds(); - } - - // test validating - if($a_validate) - { - $errors = $this->validateDom(); - } -//var_dump($errors); exit; - if (empty($errors) && !$this->getEditLock()) - { - include_once("./Services/User/classes/class.ilUserUtil.php"); - $lock = $this->getEditLockInfo(); - $errors[0] = array(0 => 0, - 1 => "nocontent#".$this->lng->txt("cont_not_saved_edit_lock_expired")."
          ". - $this->lng->txt("obj_usr").": ". - ilUserUtil::getNamePresentation($lock["edit_lock_user"])."
          ". - $this->lng->txt("content_until").": ". - ilDatePresentation::formatDate(new ilDateTime($lock["edit_lock_until"],IL_CAL_UNIX)) - ); - } - - if (!empty($errors)) - { - $this->log->debug("ilPageObject, update(): errors: ".print_r($errors, true)); - } - -//echo "-".htmlentities($this->getXMLFromDom())."-"; exit; - if(empty($errors)) - { - // @todo 1: is this page type or pc content type - // related -> plugins should be able to hook in!? - $this->performAutomaticModifications(); - - // get xml content - $content = $this->getXMLFromDom(); - $dom_doc = $this->getDomDoc(); - - // this needs to be locked - - // write history entry - $old_set = $this->db->query("SELECT * FROM page_object WHERE ". - "page_id = ".$this->db->quote($this->getId(), "integer")." AND ". - "parent_type = ".$this->db->quote($this->getParentType(), "text")." AND ". - "lang = ".$this->db->quote($this->getLanguage(), "text")); - $last_nr_set = $this->db->query("SELECT max(nr) as mnr FROM page_history WHERE ". - "page_id = ".$this->db->quote($this->getId(), "integer")." AND ". - "parent_type = ".$this->db->quote($this->getParentType(), "text")." AND ". - "lang = ".$this->db->quote($this->getLanguage(), "text")); - $last_nr = $this->db->fetchAssoc($last_nr_set); - if ($old_rec = $this->db->fetchAssoc($old_set)) - { - // only save, if something has changed - // added user id to the check for ilias 5.0, 7.10.2014 - if (($content != $old_rec["content"] || $this->user->getId() != $old_rec["last_change_user"]) && - !$a_no_history && !$this->history_saved && $lm_set->get("page_history", 1)) - { - if ($old_rec["content"] != "") - { - $this->db->manipulateF("DELETE FROM page_history WHERE ". - "page_id = %s AND parent_type = %s AND hdate = %s AND lang = %s", - array("integer", "text", "timestamp", "text"), - array($old_rec["page_id"], $old_rec["parent_type"], $old_rec["last_change"], $old_rec["lang"])); - - // the following lines are a workaround for - // bug 6741 - $last_c = $old_rec["last_change"]; - if ($last_c == "") - { - $last_c = ilUtil::now(); - } - - $this->db->insert("page_history", array( - "page_id" => array("integer", $old_rec["page_id"]), - "parent_type" => array("text", $old_rec["parent_type"]), - "lang" => array("text", $old_rec["lang"]), - "hdate" => array("timestamp", $last_c), - "parent_id" => array("integer", $old_rec["parent_id"]), - "content" => array("clob", $old_rec["content"]), - "user_id" => array("integer", $old_rec["last_change_user"]), - "ilias_version" => array("text", ILIAS_VERSION_NUMERIC), - "nr" => array("integer", (int) $last_nr["mnr"] + 1) - )); - - $old_content = $old_rec["content"]; - $old_domdoc = new DOMDocument(); - $old_nr = $last_nr["mnr"] + 1; - $old_domdoc->loadXML(''.$old_content); - - // after history entry creation event - $this->__afterHistoryEntry($old_domdoc, $old_content, $old_nr); - - $this->history_saved = true; // only save one time - } - else - { - $this->history_saved = true; // do not save on first change - } - } - } -//echo htmlentities($content); - $em = (trim($content) == "") - ? 1 - : 0; - - // @todo: pass dom instead? - $iel = $this->containsDeactivatedElements($content); - $inl = $this->containsIntLinks($content); - - $this->db->update("page_object", array( - "content" => array("clob", $content), - "parent_id" => array("integer", $this->getParentId()), - "last_change_user" => array("integer", $this->user->getId()), - "last_change" => array("timestamp", ilUtil::now()), - "is_empty" => array("integer", $em), - "active" => array("integer", $this->getActive()), - "activation_start" => array("timestamp", $this->getActivationStart()), - "activation_end" => array("timestamp", $this->getActivationEnd()), - "show_activation_info" => array("integer", $this->getShowActivationInfo()), - "inactive_elements" => array("integer", $iel), - "int_links" => array("integer", $inl), - ), array( - "page_id" => array("integer", $this->getId()), - "parent_type" => array("text", $this->getParentType()), - "lang" => array("text", $this->getLanguage()) - )); - - // after update event - $this->__afterUpdate($dom_doc, $content); - - $this->log->debug("ilPageObject, update(): updated and returning true, content: ".substr($this->getXMLContent(), 0, 100)); - -//echo "
          PageObject::update:".htmlentities($this->getXMLContent()).":"; - return true; - } - else - { - return $errors; - } - } - - - - /** - * delete page object - */ - function delete() - { - $copg_logger = ilLoggerFactory::getLogger('copg'); - $copg_logger->debug("ilPageObject: Delete called for ID '".$this->getId()."',". - " parent type: '".$this->getParentType()."', ". - " hist nr: '".$this->old_nr."', ". - " lang: '".$this->getLanguage()."', " - ); - - $mobs = array(); - $files = array(); - - if (!$this->page_not_found) - { - $this->buildDom(); - $mobs = $this->collectMediaObjects(false); - } - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $mobs2 = ilObjMediaObject::_getMobsOfObject($this->getParentType().":pg", $this->getId(), false); - foreach ($mobs2 as $m) - { - if (!in_array($m, $mobs)) - { - $mobs[] = $m; - } - } - - $copg_logger->debug("ilPageObject: ... found ".count($mobs)." media objects."); - - $this->__beforeDelete(); - - // treat plugged content - $this->handleDeleteContent(); - - // delete style usages - $this->deleteStyleUsages(false); - - // delete internal links - $this->deleteInternalLinks(); - - // delete all mob usages - ilObjMediaObject::_deleteAllUsages($this->getParentType().":pg", $this->getId()); - - // delete news - include_once("./Services/News/classes/class.ilNewsItem.php"); - ilNewsItem::deleteNewsOfContext($this->getParentId(), - $this->getParentType(), $this->getId(), "pg"); - - // delete page_object entry - $this->db->manipulate("DELETE FROM page_object ". - "WHERE page_id = ".$this->db->quote($this->getId(), "integer"). - " AND parent_type= ".$this->db->quote($this->getParentType(), "text")); - - // delete media objects - foreach ($mobs as $mob_id) - { - $copg_logger->debug("ilPageObject: ... processing mob ".$mob_id."."); - - if(ilObject::_lookupType($mob_id) != 'mob') - { - $copg_logger->debug("ilPageObject: ... type mismatch. Ignoring mob ".$mob_id."."); - continue; - } - - if (ilObject::_exists($mob_id)) - { - $copg_logger->debug("ilPageObject: ... delete mob ".$mob_id."."); - - $mob_obj = new ilObjMediaObject($mob_id); - $mob_obj->delete(); - } - else - { - $copg_logger->debug("ilPageObject: ... missing mob ".$mob_id."."); - } - } - } - - /** - * Before deletion handler (internal). - * - * @param - */ - protected final function __beforeDelete() - { - // pc classes hook - include_once("./Services/COPage/classes/class.ilCOPagePCDef.php"); - $defs = ilCOPagePCDef::getPCDefinitions(); - foreach ($defs as $def) - { - ilCOPagePCDef::requirePCClassByName($def["name"]); - $cl = $def["pc_class"]; - call_user_func($def["pc_class"].'::beforePageDelete', $this); - } - } - - /** - * Before deletion handler (internal). - * - * @param - */ - protected final function __afterHistoryEntry($a_old_domdoc, $a_old_content, $a_old_nr) - { - // save style usage - $this->saveStyleUsage($a_old_domdoc, $a_old_nr); - - // pc classes hook - include_once("./Services/COPage/classes/class.ilCOPagePCDef.php"); - $defs = ilCOPagePCDef::getPCDefinitions(); - foreach ($defs as $def) - { - ilCOPagePCDef::requirePCClassByName($def["name"]); - $cl = $def["pc_class"]; - call_user_func($def["pc_class"].'::afterPageHistoryEntry', $this, $a_old_domdoc, $a_old_content, $a_old_nr); - } - } - - /** - * Save all style class/template usages - * - * @param string $a_xml xml data of page - */ - function saveStyleUsage($a_domdoc, $a_old_nr = 0) - { - // media aliases - $xpath = new DOMXPath($a_domdoc); - $path = "//Paragraph | //Section | //MediaAlias | //FileItem". - " | //Table | //TableData | //Tabs | //List"; - $nodes = $xpath->query($path); - $usages = array(); - foreach($nodes as $node) - { - switch ($node->localName) - { - case "Paragraph": - $sname = $node->getAttribute("Characteristic"); - $stype = "text_block"; - $template = 0; - break; - - case "Section": - $sname = $node->getAttribute("Characteristic"); - $stype = "section"; - $template = 0; - break; - - case "MediaAlias": - $sname = $node->getAttribute("Class"); - $stype = "media_cont"; - $template = 0; - break; - - case "FileItem": - $sname = $node->getAttribute("Class"); - $stype = "flist_li"; - $template = 0; - break; - - case "Table": - $sname = $node->getAttribute("Template"); - if ($sname == "") - { - $sname = $node->getAttribute("Class"); - $stype = "table"; - $template = 0; - } - else - { - $stype = "table"; - $template = 1; - } - break; - - case "TableData": - $sname = $node->getAttribute("Class"); - $stype = "table_cell"; - $template = 0; - break; - - case "Tabs": - $sname = $node->getAttribute("Template"); - if ($sname != "") - { - if ($node->getAttribute("Type") == "HorizontalAccordion") - { - $stype = "haccordion"; - } - if ($node->getAttribute("Type") == "VerticalAccordion") - { - $stype = "vaccordion"; - } - } - $template = 1; - break; - - case "List": - $sname = $node->getAttribute("Class"); - if ($node->getAttribute("Type") == "Ordered") - { - $stype = "list_o"; - } - else - { - $stype = "list_u"; - } - $template = 0; - break; - } - if ($sname != "" && $stype != "") - { - $usages[$sname.":".$stype.":".$template] = array("sname" => $sname, - "stype" => $stype, "template" => $template); - } - } - - - $this->deleteStyleUsages($a_old_nr); - - foreach ($usages as $u) - { - $id = $this->db->nextId('page_style_usage'); - - $this->db->manipulate("INSERT INTO page_style_usage ". - "(id, page_id, page_type, page_lang, page_nr, template, stype, sname) VALUES (". - $this->db->quote($id, "integer").",". - $this->db->quote($this->getId(), "integer").",". - $this->db->quote($this->getParentType(), "text").",". - $this->db->quote($this->getLanguage(), "text").",". - $this->db->quote($a_old_nr, "integer").",". - $this->db->quote($u["template"], "integer").",". - $this->db->quote($u["stype"], "text").",". - $this->db->quote($u["sname"], "text"). - ")"); - } - } - - /** - * Delete style usages - * - * @param - * @return - */ - function deleteStyleUsages($a_old_nr = 0) - { - if ($a_old_nr !== false) - { - $and_old_nr = " AND page_nr = ".$this->db->quote($a_old_nr, "integer"); - } - - $this->db->manipulate("DELETE FROM page_style_usage WHERE ". - " page_id = ".$this->db->quote($this->getId(), "integer"). - " AND page_type = ".$this->db->quote($this->getParentType(), "text"). - " AND page_lang = ".$this->db->quote($this->getLanguage(), "text"). - $and_old_nr - ); - } - - - /** - * Get last update of included elements (media objects and files). - * This is needed for cache logic, cache must be reloaded if anything has changed. - */ - // @todo: move to content include class - function getLastUpdateOfIncludedElements() - { - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - include_once("./Modules/File/classes/class.ilObjFile.php"); - $mobs = ilObjMediaObject::_getMobsOfObject($this->getParentType().":pg", - $this->getId()); - $files = ilObjFile::_getFilesOfObject($this->getParentType().":pg", - $this->getId()); - $objs = array_merge($mobs, $files); - return ilObject::_getLastUpdateOfObjects($objs); - } - - /** - * Delete internal links - * - * @param - * @return - */ - function deleteInternalLinks() - { - include_once("./Services/Link/classes/class.ilInternalLink.php"); - ilInternalLink::_deleteAllLinksOfSource($this->getParentType().":pg", $this->getId(), - $this->getLanguage()); - } - - - /** - * save internal links of page - * - * @param string xml page code - */ - // @todo: move to specific classes, internal link use info - function saveInternalLinks($a_domdoc) - { - $this->deleteInternalLinks(); - - // query IntLink elements - $xpath = new DOMXPath($a_domdoc); - $nodes = $xpath->query('//IntLink'); - foreach($nodes as $node) - { - $link_type = $node->getAttribute("Type"); - - switch ($link_type) - { - case "StructureObject": - $t_type = "st"; - break; - - case "PageObject": - $t_type = "pg"; - break; - - case "GlossaryItem": - $t_type = "git"; - break; - - case "MediaObject": - $t_type = "mob"; - break; - - case "RepositoryItem": - $t_type = "obj"; - break; - - case "File": - $t_type = "file"; - break; - - case "WikiPage": - $t_type = "wpage"; - break; - - case "PortfolioPage": - $t_type = "ppage"; - break; - - case "User": - $t_type = "user"; - break; - } - - $target = $node->getAttribute("Target"); - $target_arr = explode("_", $target); - $t_id = $target_arr[count($target_arr) - 1]; - - // link to other internal object - if (is_int(strpos($target, "__"))) - { - $t_inst = 0; - } - else // link to unresolved object in other installation - { - $t_inst = $target_arr[1]; - } - - if ($t_id > 0) - { - ilInternalLink::_saveLink($this->getParentType().":pg", $this->getId(), $t_type, - $t_id, $t_inst, $this->getLanguage()); - } - } - } - - /** - * create new page (with current xml data) - */ - function create() - { - $this->createFromXML(); - } - - /** - * delete content object with hierarchical id $a_hid - * - * @param string $a_hid hierarchical id of content object - * @param boolean $a_update update page in db (note: update deletes all - * hierarchical ids in DOM!) - */ - function deleteContent($a_hid, $a_update = true, $a_pcid = "") - { - $curr_node = $this->getContentNode($a_hid, $a_pcid); - $this->handleDeleteContent($curr_node); - $curr_node->unlink_node($curr_node); - if ($a_update) - { - return $this->update(); - } - } - - - /** - * Delete multiple content objects - * - * @param string $a_hids array of hierarchical ids of content objects - * @param boolean $a_update update page in db (note: update deletes all - * hierarchical ids in DOM!) - */ - function deleteContents($a_hids, $a_update = true, $a_self_ass = false) - { - if (!is_array($a_hids)) - { - return; - } - foreach($a_hids as $a_hid) - { - $a_hid = explode(":", $a_hid); -//echo "-".$a_hid[0]."-".$a_hid[1]."-"; - -// @todo 1: hook - // do not delete question nodes in assessment pages - if (!$this->checkForTag("Question", $a_hid[0], $a_hid[1]) || $a_self_ass) - { - $curr_node = $this->getContentNode($a_hid[0], $a_hid[1]); - if (is_object($curr_node)) - { - $parent_node = $curr_node->parent_node(); - if ($parent_node->node_name() != "TableRow") - { - $this->handleDeleteContent($curr_node); - $curr_node->unlink_node($curr_node); - } - } - } - } - if ($a_update) - { - return $this->update(); - } - } - - /** - * Copy contents to clipboard and cut them from the page - * - * @param string $a_hids array of hierarchical ids of content objects - */ - function cutContents($a_hids) - { - $this->copyContents($a_hids); - return $this->deleteContents($a_hids, true, $this->getPageConfig()->getEnableSelfAssessment()); - } - - /** - * Copy contents to clipboard - * - * @param string $a_hids array of hierarchical ids of content objects - */ - function copyContents($a_hids) - { - $user = $this->user; - - if (!is_array($a_hids)) - { - return; - } - - $time = date("Y-m-d H:i:s", time()); - - $hier_ids = array(); - $skip = array(); - foreach($a_hids as $a_hid) - { - if ($a_hid == "") - { - continue; - } - $a_hid = explode(":", $a_hid); - - // check, whether new hid is child of existing one or vice versa - reset($hier_ids); - foreach($hier_ids as $h) - { - if($h."_" == substr($a_hid[0], 0, strlen($h) + 1)) - { - $skip[] = $a_hid[0]; - } - if($a_hid[0]."_" == substr($h, 0, strlen($a_hid[0]) + 1)) - { - $skip[] = $h; - } - } - $pc_id[$a_hid[0]] = $a_hid[1]; - if ($a_hid[0] != "") - { - $hier_ids[$a_hid[0]] = $a_hid[0]; - } - } - foreach ($skip as $s) - { - unset($hier_ids[$s]); - } - include_once("./Services/COPage/classes/class.ilPageContent.php"); - $hier_ids = ilPageContent::sortHierIds($hier_ids); - $nr = 1; - foreach($hier_ids as $hid) - { - $curr_node = $this->getContentNode($hid, $pc_id[$hid]); - if (is_object($curr_node)) - { - if ($curr_node->node_name() == "PageContent") - { - $content = $this->dom->dump_node($curr_node); - // remove pc and hier ids - $content = preg_replace('/PCID=\"[a-z0-9]*\"/i',"",$content); - $content = preg_replace('/HierId=\"[a-z0-9_]*\"/i',"",$content); - - $user->addToPCClipboard($content, $time, $nr); - $nr++; - } - } - } - include_once("./Modules/LearningModule/classes/class.ilEditClipboard.php"); - ilEditClipboard::setAction("copy"); - } - - /** - * Paste contents from pc clipboard - */ - function pasteContents($a_hier_id, $a_self_ass = false) - { - $user = $this->user; - - $a_hid = explode(":", $a_hier_id); - $content = $user->getPCClipboardContent(); - - // we insert from last to first, because we insert all at the - // same hier_id - for ($i = count($content) - 1; $i >= 0; $i--) - { - - $c = $content[$i]; - $temp_dom = domxml_open_mem(''.$c, - DOMXML_LOAD_PARSING, $error); - if(empty($error)) - { - $this->handleCopiedContent($temp_dom, $a_self_ass); - $xpc = xpath_new_context($temp_dom); - $path = "//PageContent"; - $res = xpath_eval($xpc, $path); - if (count($res->nodeset) > 0) - { - $new_pc_node = $res->nodeset[0]; - $cloned_pc_node = $new_pc_node->clone_node (true); - $cloned_pc_node->unlink_node ($cloned_pc_node); - $this->insertContentNode ($cloned_pc_node, $a_hid[0], - IL_INSERT_AFTER, $a_hid[1]); - } - } - else - { -//var_dump($error); - } - } - $e = $this->update(); -//var_dump($e); - } - - /** - * (De-)activate elements - */ - function switchEnableMultiple($a_hids, $a_update = true, $a_self_ass = false) - { - if (!is_array($a_hids)) - { - return; - } - $obj = & $this->content_obj; - - foreach($a_hids as $a_hid) - { - $a_hid = explode(":", $a_hid); - $curr_node = $this->getContentNode($a_hid[0], $a_hid[1]); - if (is_object($curr_node)) - { - if ($curr_node->node_name() == "PageContent") - { - $cont_obj = $this->getContentObject($a_hid[0], $a_hid[1]); - if ($cont_obj->isEnabled ()) - { - // do not deactivate question nodes in assessment pages - if (!$this->checkForTag("Question", $a_hid[0], $a_hid[1]) || $a_self_ass) - { - $cont_obj->disable(); - } - } - else - { - $cont_obj->enable(); - } - } - } - } - - if ($a_update) - { - return $this->update(); - } - } - - - /** - * delete content object with hierarchical id >= $a_hid - * - * @param string $a_hid hierarchical id of content object - * @param boolean $a_update update page in db (note: update deletes all - * hierarchical ids in DOM!) - */ - function deleteContentFromHierId($a_hid, $a_update = true) - { - $hier_ids = $this->getHierIds(); - - // iterate all hierarchical ids - foreach ($hier_ids as $hier_id) - { - // delete top level nodes only - if (!is_int(strpos($hier_id, "_"))) - { - if ($hier_id != "pg" && $hier_id >= $a_hid) - { - $curr_node = $this->getContentNode($hier_id); - $this->handleDeleteContent($curr_node); - $curr_node->unlink_node($curr_node); - } - } - } - if ($a_update) - { - return $this->update(); - } - } - - /** - * delete content object with hierarchical id < $a_hid - * - * @param string $a_hid hierarchical id of content object - * @param boolean $a_update update page in db (note: update deletes all - * hierarchical ids in DOM!) - */ - function deleteContentBeforeHierId($a_hid, $a_update = true) - { - $hier_ids = $this->getHierIds(); - - // iterate all hierarchical ids - foreach ($hier_ids as $hier_id) - { - // delete top level nodes only - if (!is_int(strpos($hier_id, "_"))) - { - if ($hier_id != "pg" && $hier_id < $a_hid) - { - $curr_node = $this->getContentNode($hier_id); - $this->handleDeleteContent($curr_node); - $curr_node->unlink_node($curr_node); - } - } - } - if ($a_update) - { - return $this->update(); - } - } - - - /** - * move content of hierarchical id >= $a_hid to other page - * - * @param string $a_hid hierarchical id of content object - * @param boolean $a_update update page in db (note: update deletes all - * hierarchical ids in DOM!) - */ - static function _moveContentAfterHierId(&$a_source_page, &$a_target_page, $a_hid) - { - $hier_ids = $a_source_page->getHierIds(); - - $copy_ids = array(); - - // iterate all hierarchical ids - 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); - - $parent_node = $a_target_page->getContentNode("pg"); - $target_dom = $a_target_page->getDom(); - $parent_childs = $parent_node->child_nodes(); - $cnt_parent_childs = count($parent_childs); -//echo "-$cnt_parent_childs-"; - $first_child = $parent_childs[0]; - foreach($copy_ids as $copy_id) - { - $source_node = $a_source_page->getContentNode($copy_id); - - $new_node = $source_node->clone_node(true); - $new_node->unlink_node($new_node); - - $source_node->unlink_node($source_node); - - if($cnt_parent_childs == 0) - { - $new_node = $parent_node->append_child($new_node); - } - else - { - //$target_dom->import_node($new_node); - $new_node = $first_child->insert_before($new_node, $first_child); - } - $parent_childs = $parent_node->child_nodes(); - - //$cnt_parent_childs++; - } - - $a_target_page->update(); - $a_source_page->update(); - - } - - /** - * insert a content node before/after a sibling or as first child of a parent - */ - function insertContent(&$a_cont_obj, $a_pos, $a_mode = IL_INSERT_AFTER, $a_pcid = "") - { -//echo "-".$a_pos."-".$a_pcid."-"; - // move mode into container elements is always INSERT_CHILD - $curr_node = $this->getContentNode($a_pos, $a_pcid); - $curr_name = $curr_node->node_name(); - - // @todo: try to generalize this - if (($curr_name == "TableData") || ($curr_name == "PageObject") || - ($curr_name == "ListItem") || ($curr_name == "Section") - || ($curr_name == "Tab") || ($curr_name == "ContentPopup") - || ($curr_name == "GridCell")) - { - $a_mode = IL_INSERT_CHILD; - } - - $hid = $curr_node->get_attribute("HierId"); - if ($hid != "") - { -//echo "-".$a_pos."-".$hid."-"; - $a_pos = $hid; - } - - if($a_mode != IL_INSERT_CHILD) // determine parent hierarchical id - { // of sibling at $a_pos - $pos = explode("_", $a_pos); - $target_pos = array_pop($pos); - $parent_pos = implode($pos, "_"); - } - else // if we should insert a child, $a_pos is alreade the hierarchical id - { // of the parent node - $parent_pos = $a_pos; - } - - // get the parent node - if($parent_pos != "") - { - $parent_node = $this->getContentNode($parent_pos); - } - else - { - $parent_node = $this->getNode(); - } - - // count the parent children - $parent_childs = $parent_node->child_nodes(); - $cnt_parent_childs = count($parent_childs); -//echo "ZZ$a_mode"; - switch ($a_mode) - { - // insert new node after sibling at $a_pos - case IL_INSERT_AFTER: - $new_node = $a_cont_obj->getNode(); - //$a_pos = ilPageContent::incEdId($a_pos); - //$curr_node = $this->getContentNode($a_pos); + } + $trans = $this->getLanguageVariablesXML(); + //echo htmlentities($this->dom->dump_node($this->node)); exit; + return "" . $this->dom->dump_node($this->node) . $mobs . $bibs . $trans . $a_append_str . ""; + } else { + if (is_object($this->dom)) { + if ($a_omit_pageobject_tag) { + $xml = ""; + $childs = $this->node->child_nodes(); + for ($i = 0; $i < count($childs); $i++) { + $xml.= $this->dom->dump_node($childs[$i]); + } + return $xml; + } else { + $xml = $this->dom->dump_mem(0, $this->encoding); + $xml = preg_replace('/<\?xml[^>]*>/i', "", $xml); + $xml = preg_replace('/]*>/i', "", $xml); + return $xml; + + // don't use dump_node. This gives always entities. + //return $this->dom->dump_node($this->node); + } + } else { + return ""; + } + } + } + } + + /** + * Get language variables as XML + */ + public function getLanguageVariablesXML() + { + $xml = ""; + $lang_vars = array( + "ed_paste_clip", "ed_edit", "ed_edit_prop", "ed_delete", "ed_moveafter", + "ed_movebefore", "ed_go", "ed_class", "ed_width", "ed_align_left", + "ed_align_right", "ed_align_center", "ed_align_left_float", + "ed_align_right_float", "ed_delete_item", "ed_new_item_before", + "ed_new_item_after", "ed_copy_clip", "please_select", "ed_split_page", + "ed_item_up", "ed_item_down", "ed_split_page_next","ed_enable", + "de_activate", "ed_paste", "ed_edit_multiple", "ed_cut", "ed_copy", "ed_insert_templ", + "ed_click_to_add_pg", "download"); + + // collect lang vars from pc elements + include_once("./Services/COPage/classes/class.ilCOPagePCDef.php"); + $defs = ilCOPagePCDef::getPCDefinitions(); + foreach ($defs as $def) { + $lang_vars[] = "pc_" . $def["pc_type"]; + $lang_vars[] = "ed_insert_" . $def["pc_type"]; + + ilCOPagePCDef::requirePCClassByName($def["name"]); + $cl = $def["pc_class"]; + $lvs = call_user_func($def["pc_class"] . '::getLangVars'); + foreach ($lvs as $lv) { + $lang_vars[] = $lv; + } + } + + foreach ($lang_vars as $lang_var) { + $this->appendLangVarXML($xml, $lang_var); + } + + $xml.= ""; + + return $xml; + } + + public function appendLangVarXML(&$xml, $var) + { + $xml.= "lng->txt("cont_" . $var) . "\"/>"; + } + + // @todo begin: move this to paragraph class + + public function getFirstParagraphText() + { + if ($this->dom) { + require_once("./Services/COPage/classes/class.ilPCParagraph.php"); + $xpc = xpath_new_context($this->dom); + $path = "//Paragraph[1]"; + $res = xpath_eval($xpc, $path); + if (count($res->nodeset) > 0) { + $cont_node = $res->nodeset[0]->parent_node(); + $par = new ilPCParagraph($this); + $par->setNode($cont_node); + return $par->getText(); + } + } + return ""; + } + + /** + * Set content of paragraph + * + * @param string $a_hier_id Hier ID + * @param string $a_content Content + */ + public function setParagraphContent($a_hier_id, $a_content) + { + $node = $this->getContentNode($a_hier_id); + if (is_object($node)) { + $node->set_content($a_content); + } + } + + // @todo end + + + /** + * lm parser set this flag to true, if the page contains intern links + * (this method should only be called by the import parser) + * + * todo: move to ilLMPageObject !? + * + * @param boolean $a_contains_link true, if page contains intern link tag(s) + */ + // @todo: can we do this better + public function setContainsIntLink($a_contains_link) + { + $this->contains_int_link = $a_contains_link; + } + + /** + * returns true, if page was marked as containing an intern link (via setContainsIntLink) + * (this method should only be called by the import parser) + */ + // @todo: can we do this better + public function containsIntLink() + { + return $this->contains_int_link; + } + + /** + * Set import mode + * + * @param bool $a_val import mode + */ + public function setImportMode($a_val) + { + $this->import_mode = $a_val; + } + + /** + * Get import mode + * + * @return bool import mode + */ + public function getImportMode() + { + return $this->import_mode; + } + + public function needsImportParsing($a_parse = "") + { + if ($a_parse === true) { + $this->needs_parsing = true; + } + if ($a_parse === false) { + $this->needs_parsing = false; + } + return $this->needs_parsing; + } + + /** + * Set contains question + * + * @param boolean $a_val contains question + */ + // @todo: can we do this better + public function setContainsQuestion($a_val) + { + $this->contains_question = $a_val; + } + + /** + * Get contains question + * + * @return boolean contains question + */ + public function getContainsQuestion() + { + return $this->contains_question; + } + + + /** + * get all media objects, that are referenced and used within + * the page + */ + // @todo: move to media class + public function collectMediaObjects($a_inline_only = true) + { + //echo htmlentities($this->getXMLFromDom()); + // determine all media aliases of the page + $xpc = xpath_new_context($this->dom); + $path = "//MediaObject/MediaAlias"; + $res = xpath_eval($xpc, $path); + $mob_ids = array(); + for ($i = 0; $i < count($res->nodeset); $i++) { + $id_arr = explode("_", $res->nodeset[$i]->get_attribute("OriginId")); + $mob_id = $id_arr[count($id_arr) - 1]; + $mob_ids[$mob_id] = $mob_id; + } + + // determine all media aliases of interactive images + $xpc = xpath_new_context($this->dom); + $path = "//InteractiveImage/MediaAlias"; + $res = xpath_eval($xpc, $path); + for ($i = 0; $i < count($res->nodeset); $i++) { + $id_arr = explode("_", $res->nodeset[$i]->get_attribute("OriginId")); + $mob_id = $id_arr[count($id_arr) - 1]; + $mob_ids[$mob_id] = $mob_id; + } + + // determine all inline internal media links + $xpc = xpath_new_context($this->dom); + $path = "//IntLink[@Type = 'MediaObject']"; + $res = xpath_eval($xpc, $path); + + for ($i = 0; $i < count($res->nodeset); $i++) { + if (($res->nodeset[$i]->get_attribute("TargetFrame") == "") || + (!$a_inline_only)) { + $target = $res->nodeset[$i]->get_attribute("Target"); + $id_arr = explode("_", $target); + if (($id_arr[1] == IL_INST_ID) || + (substr($target, 0, 4) == "il__")) { + $mob_id = $id_arr[count($id_arr) - 1]; + if (ilObject::_exists($mob_id)) { + $mob_ids[$mob_id] = $mob_id; + } + } + } + } + + return $mob_ids; + } + + + /** + * get all internal links that are used within the page + */ + // @todo: can we do this better? + public function getInternalLinks($a_cnt_multiple = false) + { + // get all internal links of the page + $xpc = xpath_new_context($this->dom); + $path = "//IntLink"; + $res = xpath_eval($xpc, $path); + + $links = array(); + $cnt_multiple = 1; + for ($i = 0; $i < count($res->nodeset); $i++) { + $add = ""; + if ($a_cnt_multiple) { + $add = ":" . $cnt_multiple; + } + $target = $res->nodeset[$i]->get_attribute("Target"); + $type = $res->nodeset[$i]->get_attribute("Type"); + $targetframe = $res->nodeset[$i]->get_attribute("TargetFrame"); + $anchor = $res->nodeset[$i]->get_attribute("Anchor"); + $links[$target . ":" . $type . ":" . $targetframe . ":" . $anchor . $add] = + array("Target" => $target, "Type" => $type, + "TargetFrame" => $targetframe, "Anchor" => $anchor); + + // get links (image map areas) for inline media objects + if ($type == "MediaObject" && $targetframe == "") { + if (substr($target, 0, 4) =="il__") { + $id_arr = explode("_", $target); + $id = $id_arr[count($id_arr) - 1]; + + $med_links = ilMediaItem::_getMapAreasIntLinks($id); + foreach ($med_links as $key => $med_link) { + $links[$key] = $med_link; + } + } + } + //echo "
          -:".$target.":".$type.":".$targetframe.":-"; + $cnt_multiple++; + } + unset($xpc); + + // get all media aliases + $xpc = xpath_new_context($this->dom); + $path = "//MediaAlias"; + $res = xpath_eval($xpc, $path); + + require_once("Services/MediaObjects/classes/class.ilMediaItem.php"); + for ($i = 0; $i < count($res->nodeset); $i++) { + $oid = $res->nodeset[$i]->get_attribute("OriginId"); + if (substr($oid, 0, 4) =="il__") { + $id_arr = explode("_", $oid); + $id = $id_arr[count($id_arr) - 1]; + + $med_links = ilMediaItem::_getMapAreasIntLinks($id); + foreach ($med_links as $key => $med_link) { + $links[$key] = $med_link; + } + } + } + unset($xpc); + + return $links; + } + + /** + * get a xml string that contains all media object elements, that + * are referenced by any media alias in the page + */ + // @todo: move to media class + public function getMultimediaXML() + { + $mob_ids = $this->collectMediaObjects(); + + // get xml of corresponding media objects + $mobs_xml = ""; + require_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + foreach ($mob_ids as $mob_id => $dummy) { + if (ilObject::_lookupType($mob_id) == "mob") { + $mob_obj = new ilObjMediaObject($mob_id); + $mobs_xml .= $mob_obj->getXML(IL_MODE_OUTPUT, $a_inst = 0, true); + } + } + //var_dump($mobs_xml); + return $mobs_xml; + } + + /** + * get complete media object (alias) element + */ + // @todo: move to media class + public function getMediaAliasElement($a_mob_id, $a_nr = 1) + { + $xpc = xpath_new_context($this->dom); + $path = "//MediaObject/MediaAlias[@OriginId='il__mob_$a_mob_id']"; + $res = xpath_eval($xpc, $path); + $mal_node = $res->nodeset[$a_nr - 1]; + $mob_node = $mal_node->parent_node(); + + return $this->dom->dump_node($mob_node); + } + + /** + * Validate the page content agains page DTD + * + * @return array Error array. + */ + public function validateDom() + { + $this->stripHierIDs(); + + // possible fix for #14820 + libxml_disable_entity_loader(false); + + @$this->dom->validate($error); + //var_dump($this->dom); exit; + return $error; + } + + /** + * Add hierarchical ID (e.g. for editing) attributes "HierId" to current dom tree. + * This attribute will be added to the following elements: + * PageObject, Paragraph, Table, TableRow, TableData. + * Only elements of these types are counted as "childs" here. + * + * Hierarchical IDs have the format "x_y_z_...", e.g. "1_4_2" means: second + * child of fourth child of first child of page. + * + * The PageObject element gets the special id "pg". The first child of the + * page starts with id 1. The next child gets the 2 and so on. + * + * Another example: The first child of the page is a Paragraph -> id 1. + * The second child is a table -> id 2. The first row gets the id 2_1, the + */ + // @todo: can we do this better? remove dependencies? + public function addHierIDs() + { + $this->hier_ids = array(); + $this->first_row_ids = array(); + $this->first_col_ids = array(); + $this->list_item_ids = array(); + $this->file_item_ids = array(); + + // set hierarchical ids for Paragraphs, Tables, TableRows and TableData elements + $xpc = xpath_new_context($this->dom); + //$path = "//Paragraph | //Table | //TableRow | //TableData"; + + $sep = $path = ""; + foreach ($this->id_elements as $el) { + $path.= $sep . "//" . $el; + $sep = " | "; + } + + $res = xpath_eval($xpc, $path); + for ($i = 0; $i < count($res->nodeset); $i++) { + $cnode = $res->nodeset[$i]; + $ctag = $cnode->node_name(); + + // get hierarchical id of previous sibling + $sib_hier_id = ""; + while ($cnode = $cnode->previous_sibling()) { + if (($cnode->node_type() == XML_ELEMENT_NODE) + && $cnode->has_attribute("HierId")) { + $sib_hier_id = $cnode->get_attribute("HierId"); + //$sib_hier_id = $id_attr->value(); + break; + } + } + + if ($sib_hier_id != "") { // set id to sibling id "+ 1" + require_once("./Services/COPage/classes/class.ilPageContent.php"); + $node_hier_id = ilPageContent::incEdId($sib_hier_id); + $res->nodeset[$i]->set_attribute("HierId", $node_hier_id); + $this->hier_ids[] = $node_hier_id; + if ($ctag == "TableData") { + if (substr($par_hier_id, strlen($par_hier_id)-2) == "_1") { + $this->first_row_ids[] = $node_hier_id; + } + } + if ($ctag == "ListItem") { + $this->list_item_ids[] = $node_hier_id; + } + if ($ctag == "FileItem") { + $this->file_item_ids[] = $node_hier_id; + } + } else { // no sibling -> node is first child + // get hierarchical id of next parent + $cnode = $res->nodeset[$i]; + $par_hier_id = ""; + while ($cnode = $cnode->parent_node()) { + if (($cnode->node_type() == XML_ELEMENT_NODE) + && $cnode->has_attribute("HierId")) { + $par_hier_id = $cnode->get_attribute("HierId"); + //$par_hier_id = $id_attr->value(); + break; + } + } + //echo "
          par:".$par_hier_id." ($ctag)"; + if (($par_hier_id != "") && ($par_hier_id != "pg")) { // set id to parent_id."_1" + $node_hier_id = $par_hier_id . "_1"; + $res->nodeset[$i]->set_attribute("HierId", $node_hier_id); + $this->hier_ids[] = $node_hier_id; + if ($ctag == "TableData") { + $this->first_col_ids[] = $node_hier_id; + if (substr($par_hier_id, strlen($par_hier_id)-2) == "_1") { + $this->first_row_ids[] = $node_hier_id; + } + } + if ($ctag == "ListItem") { + $this->list_item_ids[] = $node_hier_id; + } + if ($ctag == "FileItem") { + $this->file_item_ids[] = $node_hier_id; + } + } else { // no sibling, no parent -> first node + $node_hier_id = "1"; + $res->nodeset[$i]->set_attribute("HierId", $node_hier_id); + $this->hier_ids[] = $node_hier_id; + } + } + } + + // set special hierarchical id "pg" for pageobject + $xpc = xpath_new_context($this->dom); + $path = "//PageObject"; + $res = xpath_eval($xpc, $path); + for ($i = 0; $i < count($res->nodeset); $i++) { // should only be 1 + $res->nodeset[$i]->set_attribute("HierId", "pg"); + $this->hier_ids[] = "pg"; + } + unset($xpc); + } + + /** + * get all hierarchical ids + */ + public function getHierIds() + { + return $this->hier_ids; + } + + /** + * get ids of all first table rows + */ + // @todo: move to table classes + public function getFirstRowIds() + { + return $this->first_row_ids; + } + + /** + * get ids of all first table columns + */ + // @todo: move to table classes + public function getFirstColumnIds() + { + return $this->first_col_ids; + } + + /** + * get ids of all list items + */ + // @todo: move to list class + public function getListItemIds() + { + return $this->list_item_ids; + } + + /** + * get ids of all file items + */ + // @todo: move to file item class + public function getFileItemIds() + { + return $this->file_item_ids; + } + + /** + * strip all hierarchical id attributes out of the dom tree + */ + public function stripHierIDs() + { + if (is_object($this->dom)) { + $xpc = xpath_new_context($this->dom); + $path = "//*[@HierId]"; + $res = xpath_eval($xpc, $path); + for ($i = 0; $i < count($res->nodeset); $i++) { // should only be 1 + if ($res->nodeset[$i]->has_attribute("HierId")) { + $res->nodeset[$i]->remove_attribute("HierId"); + } + } + unset($xpc); + } + } + + /** + * Get hier ids for a set of pc ids + */ + public function getHierIdsForPCIds($a_pc_ids) + { + if (!is_array($a_pc_ids) || count($a_pc_ids) == 0) { + return array(); + } + $ret = array(); + + if (is_object($this->dom)) { + $xpc = xpath_new_context($this->dom); + $path = "//*[@PCID]"; + $res = xpath_eval($xpc, $path); + for ($i = 0; $i < count($res->nodeset); $i++) { // should only be 1 + $pc_id = $res->nodeset[$i]->get_attribute("PCID"); + if (in_array($pc_id, $a_pc_ids)) { + $ret[$pc_id] = $res->nodeset[$i]->get_attribute("HierId"); + } + } + unset($xpc); + } + //var_dump($ret); + return $ret; + } + + /** + * add file sizes + */ + // @todo: move to file item class + public function addFileSizes() + { + $xpc = xpath_new_context($this->dom); + $path = "//FileItem"; + $res = xpath_eval($xpc, $path); + for ($i = 0; $i < count($res->nodeset); $i++) { + $cnode = $res->nodeset[$i]; + $size_node = $this->dom->create_element("Size"); + $size_node = $cnode->append_child($size_node); + + $childs = $cnode->child_nodes(); + $size = ""; + for ($j = 0; $j < count($childs); $j++) { + if ($childs[$j]->node_name() == "Identifier") { + if ($childs[$j]->has_attribute("Entry")) { + $entry = $childs[$j]->get_attribute("Entry"); + $entry_arr = explode("_", $entry); + $id = $entry_arr[count($entry_arr) - 1]; + require_once("./Modules/File/classes/class.ilObjFile.php"); + $size = ilObjFile::_lookupFileSize($id); + } + } + } + $size_node->set_content($size); + } + + unset($xpc); + } + + /** + * Resolves all internal link targets of the page, if targets are available + * (after import) + */ + // @todo: possible to improve this? + public function resolveIntLinks($a_link_map = null) + { + $changed = false; + + $this->log->debug("start"); + + // resolve normal internal links + $xpc = xpath_new_context($this->dom); + $path = "//IntLink"; + $res = xpath_eval($xpc, $path); + for ($i = 0; $i < count($res->nodeset); $i++) { + $target = $res->nodeset[$i]->get_attribute("Target"); + $type = $res->nodeset[$i]->get_attribute("Type"); + + if ($a_link_map == null) { + $new_target = ilInternalLink::_getIdForImportId($type, $target); + $this->log->debug("no map, type: " . $type . ", target: " . $target . ", new target: " . $new_target); + // echo "-".$new_target."-".$type."-".$target."-"; exit; + } else { + $nt = explode("_", $a_link_map[$target]); + $new_target = false; + if ($nt[1] == IL_INST_ID) { + $new_target = "il__" . $nt[2] . "_" . $nt[3]; + } + $this->log->debug("map, type: " . $type . ", target: " . $target . ", new target: " . $new_target); + } + if ($new_target !== false) { + $res->nodeset[$i]->set_attribute("Target", $new_target); + $changed = true; + } else { // check wether link target is same installation + if (ilInternalLink::_extractInstOfTarget($target) == IL_INST_ID && + IL_INST_ID > 0 && $type != "RepositoryItem") { + $new_target = ilInternalLink::_removeInstFromTarget($target); + if (ilInternalLink::_exists($type, $new_target)) { + $res->nodeset[$i]->set_attribute("Target", $new_target); + $changed = true; + } + } + } + } + unset($xpc); + + // resolve internal links in map areas + $xpc = xpath_new_context($this->dom); + $path = "//MediaAlias"; + $res = xpath_eval($xpc, $path); + //echo "
          page::resolve
          "; + //echo "Content:".htmlentities($this->getXMLFromDOM()).":
          "; + for ($i = 0; $i < count($res->nodeset); $i++) { + $orig_id = $res->nodeset[$i]->get_attribute("OriginId"); + $id_arr = explode("_", $orig_id); + $mob_id = $id_arr[count($id_arr) - 1]; + ilMediaItem::_resolveMapAreaLinks($mob_id); + } + return $changed; + } + + /** + * Resolve media aliases + * (after import) + * + * @param array mapping array + */ + // @todo: move to media classes? + public function resolveMediaAliases($a_mapping, $a_reuse_existing_by_import = false) + { + // resolve normal internal links + $xpc = xpath_new_context($this->dom); + $path = "//MediaAlias"; + $res = xpath_eval($xpc, $path); + $changed = false; + for ($i = 0; $i < count($res->nodeset); $i++) { + // get the ID of the import file from the xml + $old_id = $res->nodeset[$i]->get_attribute("OriginId"); + $old_id = explode("_", $old_id); + $old_id = $old_id[count($old_id) - 1]; + $new_id = ""; + $import_id = ""; + // get the new id from the current mapping + if ($a_mapping[$old_id] > 0) { + $new_id = $a_mapping[$old_id]; + if ($a_reuse_existing_by_import) { + // this should work, if the lm has been imported in a translation installation and re-exported + $import_id = ilObject::_lookupImportId($new_id); + $imp = explode("_", $import_id); + if ($imp[1] == IL_INST_ID && $imp[2] == "mob" && ilObject::_lookupType($imp[3]) == "mob") { + $new_id = $imp[3]; + } + } + } + // now check, if the translation has been done just by changing text in the exported + // translation file + if ($import_id == "" && $a_reuse_existing_by_import) { + // if the old_id is also referred by the page content of the default language + // we assume that this media object is unchanged + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $med_of_def_lang = ilObjMediaObject::_getMobsOfObject($this->getParentType() . ":pg", $this->getId(), 0, "-"); + if (in_array($old_id, $med_of_def_lang)) { + $new_id = $old_id; + } + } + if ($new_id != "") { + $res->nodeset[$i]->set_attribute("OriginId", "il__mob_" . $new_id); + $changed = true; + } + } + unset($xpc); + return $changed; + } + + /** + * Resolve iim media aliases + * (in ilContObjParse) + * + * @param array mapping array + */ + // @todo: move to iim classes? + public function resolveIIMMediaAliases($a_mapping) + { + // resolve normal internal links + $xpc = xpath_new_context($this->dom); + $path = "//InteractiveImage/MediaAlias"; + $res = xpath_eval($xpc, $path); + $changed = false; + for ($i = 0; $i < count($res->nodeset); $i++) { + $old_id = $res->nodeset[$i]->get_attribute("OriginId"); + if ($a_mapping[$old_id] > 0) { + $res->nodeset[$i]->set_attribute("OriginId", "il__mob_" . $a_mapping[$old_id]); + $changed = true; + } + } + unset($xpc); + + return $changed; + } + + /** + * Resolve file items + * (after import) + * + * @param array mapping array + */ + // @todo: move to file classes? + public function resolveFileItems($a_mapping) + { + // resolve normal internal links + $xpc = xpath_new_context($this->dom); + $path = "//FileItem/Identifier"; + $res = xpath_eval($xpc, $path); + $changed = false; + for ($i = 0; $i < count($res->nodeset); $i++) { + $old_id = $res->nodeset[$i]->get_attribute("Entry"); + $old_id = explode("_", $old_id); + $old_id = $old_id[count($old_id) - 1]; + if ($a_mapping[$old_id] > 0) { + $res->nodeset[$i]->set_attribute("Entry", "il__file_" . $a_mapping[$old_id]); + $changed = true; + } + } + unset($xpc); + + return $changed; + } + + /** + * Resolve all quesion references + * (after import) + */ + // @todo: move to question classes + public function resolveQuestionReferences($a_mapping) + { + // resolve normal internal links + $xpc = xpath_new_context($this->dom); + $path = "//Question"; + $res = xpath_eval($xpc, $path); + $updated = false; + for ($i = 0; $i < count($res->nodeset); $i++) { + $qref = $res->nodeset[$i]->get_attribute("QRef"); + + if (isset($a_mapping[$qref])) { + $res->nodeset[$i]->set_attribute("QRef", "il__qst_" . $a_mapping[$qref]["pool"]); + $updated = true; + } + } + unset($xpc); + + return $updated; + } + + + /** + * Move internal links from one destination to another. This is used + * for pages and structure links. Just use IDs in "from" and "to". + * + * @param array keys are the old targets, values are the new targets + */ + // @todo: generalize, internal links usage info + public function moveIntLinks($a_from_to) + { + $this->buildDom(); + + $changed = false; + + // resolve normal internal links + $xpc = xpath_new_context($this->dom); + $path = "//IntLink"; + $res = xpath_eval($xpc, $path); + for ($i = 0; $i < count($res->nodeset); $i++) { + $target = $res->nodeset[$i]->get_attribute("Target"); + $type = $res->nodeset[$i]->get_attribute("Type"); + $obj_id = ilInternalLink::_extractObjIdOfTarget($target); + if ($a_from_to[$obj_id] > 0 && is_int(strpos($target, "__"))) { + if ($type == "PageObject" && ilLMObject::_lookupType($a_from_to[$obj_id]) == "pg") { + $res->nodeset[$i]->set_attribute("Target", "il__pg_" . $a_from_to[$obj_id]); + $changed = true; + } + if ($type == "StructureObject" && ilLMObject::_lookupType($a_from_to[$obj_id]) == "st") { + $res->nodeset[$i]->set_attribute("Target", "il__st_" . $a_from_to[$obj_id]); + $changed = true; + } + if ($type == "PortfolioPage") { + $res->nodeset[$i]->set_attribute("Target", "il__ppage_" . $a_from_to[$obj_id]); + $changed = true; + } + } + } + unset($xpc); + + // map areas + $this->addHierIDs(); + $xpc = xpath_new_context($this->dom); + $path = "//MediaAlias"; + $res = xpath_eval($xpc, $path); + + require_once("Services/MediaObjects/classes/class.ilMediaItem.php"); + require_once("Services/COPage/classes/class.ilMediaAliasItem.php"); + + for ($i = 0; $i < count($res->nodeset); $i++) { + $media_object_node = $res->nodeset[$i]->parent_node(); + $page_content_node = $media_object_node->parent_node(); + $c_hier_id = $page_content_node->get_attribute("HierId"); + + // first check, wheter we got instance map areas -> take these + $std_alias_item = new ilMediaAliasItem( + $this->dom, + $c_hier_id, + "Standard" + ); + $areas = $std_alias_item->getMapAreas(); + $correction_needed = false; + if (count($areas) > 0) { + // check if correction needed + foreach ($areas as $area) { + if ($area["Type"] == "PageObject" || + $area["Type"] == "StructureObject") { + $t = $area["Target"]; + $tid = _extractObjIdOfTarget($t); + if ($a_from_to[$tid] > 0) { + $correction_needed = true; + } + } + } + } else { + $areas = array(); + + // get object map areas and check whether at least one must + // be corrected + $oid = $res->nodeset[$i]->get_attribute("OriginId"); + if (substr($oid, 0, 4) =="il__") { + $id_arr = explode("_", $oid); + $id = $id_arr[count($id_arr) - 1]; + + $mob = new ilObjMediaObject($id); + $med_item = $mob->getMediaItem("Standard"); + $med_areas = $med_item->getMapAreas(); + + foreach ($med_areas as $area) { + $link_type = ($area->getLinkType() == "int") + ? "IntLink" + : "ExtLink"; + + $areas[] = array( + "Nr" => $area->getNr(), + "Shape" => $area->getShape(), + "Coords" => $area->getCoords(), + "Link" => array( + "LinkType" => $link_type, + "Href" => $area->getHref(), + "Title" => $area->getTitle(), + "Target" => $area->getTarget(), + "Type" => $area->getType(), + "TargetFrame" => $area->getTargetFrame() + ) + ); + + if ($area->getType() == "PageObject" || + $area->getType() == "StructureObject") { + $t = $area->getTarget(); + $tid = ilInternalLink::_extractObjIdOfTarget($t); + if ($a_from_to[$tid] > 0) { + $correction_needed = true; + } + //var_dump($a_from_to); + } + } + } + } + + // correct map area links + if ($correction_needed) { + $changed = true; + $std_alias_item->deleteAllMapAreas(); + foreach ($areas as $area) { + if ($area["Link"]["LinkType"] == "IntLink") { + $target = $area["Link"]["Target"]; + $type = $area["Link"]["Type"]; + $obj_id = ilInternalLink::_extractObjIdOfTarget($target); + if ($a_from_to[$obj_id] > 0) { + if ($type == "PageObject" && ilLMObject::_lookupType($a_from_to[$obj_id]) == "pg") { + $area["Link"]["Target"] = "il__pg_" . $a_from_to[$obj_id]; + } + if ($type == "StructureObject" && ilLMObject::_lookupType($a_from_to[$obj_id]) == "st") { + $area["Link"]["Target"] = "il__st_" . $a_from_to[$obj_id]; + } + } + } + + $std_alias_item->addMapArea( + $area["Shape"], + $area["Coords"], + $area["Link"]["Title"], + array( "Type" => $area["Link"]["Type"], + "TargetFrame" => $area["Link"]["TargetFrame"], + "Target" => $area["Link"]["Target"], + "Href" => $area["Link"]["Href"], + "LinkType" => $area["Link"]["LinkType"], + ) + ); + } + } + } + unset($xpc); + + return $changed; + } + + /** + * Change targest of repository links. Use full targets in "from" and "to"!!! + * + * @param array keys are the old targets, values are the new targets + */ + // @todo: generalize, internal links usage info + public static function _handleImportRepositoryLinks($a_rep_import_id, $a_rep_type, $a_rep_ref_id) + { + include_once("./Services/Link/classes/class.ilInternalLink.php"); + + //echo "-".$a_rep_import_id."-".$a_rep_ref_id."-"; + $sources = ilInternalLink::_getSourcesOfTarget( + "obj", + ilInternalLink::_extractObjIdOfTarget($a_rep_import_id), + ilInternalLink::_extractInstOfTarget($a_rep_import_id) + ); + //var_dump($sources); + foreach ($sources as $source) { + //echo "A"; + if ($source["type"] == "lm:pg") { + //echo "B"; + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + if (self::_exists("lm", $source["id"], $source["lang"])) { + $page_obj = new ilLMPage($source["id"], 0, $source["lang"]); + if (!$page_obj->page_not_found) { + //echo "C"; + $page_obj->handleImportRepositoryLink( + $a_rep_import_id, + $a_rep_type, + $a_rep_ref_id + ); + } + $page_obj->update(); + } + } + } + } + + // @todo: generalize, internal links usage info + public function handleImportRepositoryLink($a_rep_import_id, $a_rep_type, $a_rep_ref_id) + { + $this->buildDom(); + + // resolve normal internal links + $xpc = xpath_new_context($this->dom); + $path = "//IntLink"; + $res = xpath_eval($xpc, $path); + //echo "1"; + for ($i = 0; $i < count($res->nodeset); $i++) { + //echo "2"; + $target = $res->nodeset[$i]->get_attribute("Target"); + $type = $res->nodeset[$i]->get_attribute("Type"); + if ($target == $a_rep_import_id && $type == "RepositoryItem") { + //echo "setting:"."il__".$a_rep_type."_".$a_rep_ref_id; + $res->nodeset[$i]->set_attribute( + "Target", + "il__" . $a_rep_type . "_" . $a_rep_ref_id + ); + } + } + unset($xpc); + } + + /** + * Handle repository links on copy process + * @param array $a_mapping + * @param int $a_source_ref_id + */ + public function handleRepositoryLinksOnCopy($a_mapping, $a_source_ref_id) + { + $tree = $this->tree; + $objDefinition = $this->obj_definition; + + $this->buildDom(); + $this->log->debug("Handle repository links..."); + + // resolve normal internal links + $xpc = xpath_new_context($this->dom); + $path = "//IntLink"; + $res = xpath_eval($xpc, $path); + for ($i = 0; $i < count($res->nodeset); $i++) { + $target = $res->nodeset[$i]->get_attribute("Target"); + $type = $res->nodeset[$i]->get_attribute("Type"); + $this->log->debug("Target: " . $target); + $t = explode("_", $target); + if ($type == "RepositoryItem" && ((int) $t[1] == 0 || (int) $t[1] == IL_INST_ID)) { + if (isset($a_mapping[$t[3]])) { + // we have a mapping -> replace the ID + $this->log->debug("... replace " . $t[3] . " with " . $a_mapping[$t[3]] . "."); + $res->nodeset[$i]->set_attribute( + "Target", + "il__obj_" . $a_mapping[$t[3]] + ); + } elseif ($this->tree->isGrandChild($a_source_ref_id, $t[3])) { + // we have no mapping, but the linked object is child of the original node -> remove link + $this->log->debug("... remove links."); + if ($res->nodeset[$i]->parent_node()->node_name() == "MapArea") { // simply remove map areas + $parent = $res->nodeset[$i]->parent_node(); + $parent->unlink_node($parent); + } else { // replace link by content of the link for other internal links + $source_node = $res->nodeset[$i]; + $new_node = $source_node->clone_node(true); + $new_node->unlink_node($new_node); + $childs = $new_node->child_nodes(); + for ($j = 0; $j < count($childs); $j++) { + $this->log->debug("... move node $j " . $childs[$j]->node_name() . " before " . $source_node->node_name()); + $source_node->insert_before($childs[$j], $source_node); + } + $source_node->unlink_node($source_node); + } + } + } + } + unset($xpc); + + // resolve normal external links + $ilias_url = parse_url(ILIAS_HTTP_PATH); + $xpc = xpath_new_context($this->dom); + $path = "//ExtLink"; + $res = xpath_eval($xpc, $path); + for ($i = 0; $i < count($res->nodeset); $i++) { + $href = $res->nodeset[$i]->get_attribute("Href"); + $this->log->debug("Href: " . $href); + + $url = parse_url($href); + + // only handle links on same host + $this->log->debug("Host: " . $url["host"]); + if ($url["host"] != "" && $url["host"] != $ilias_url["host"]) { + continue; + } + + // get parameters + $par = array(); + foreach (explode("&", $url["query"]) as $p) { + $p = explode("=", $p); + $par[$p[0]] = $p[1]; + } + + $target_client_id = $par["client_id"]; + if ($target_client_id != "" && $target_client_id != CLIENT_ID) { + continue; + } + + // get ref id + $ref_id = 0; + if (is_int(strpos($href, "goto.php"))) { + $t = explode("_", $par["target"]); + if ($objDefinition->isRBACObject($t[0])) { + $ref_id = (int) $t[1]; + $type = $t[0]; + } + } elseif (is_int(strpos($href, "ilias.php"))) { + $ref_id = (int) $par["ref_id"]; + } + + + if ($ref_id > 0) { + if (isset($a_mapping[$ref_id])) { + $new_ref_id = $a_mapping[$ref_id]; + $new_href = ""; + // we have a mapping -> replace the ID + if (is_int(strpos($href, "goto.php"))) { + $nt = str_replace($type . "_" . $ref_id, $type . "_" . $new_ref_id, $par["target"]); + $new_href = str_replace("target=" . $par["target"], "target=" . $nt, $href); + } elseif (is_int(strpos($href, "ilias.php"))) { + $new_href = str_replace("ref_id=" . $par["ref_id"], "ref_id=" . $new_ref_id, $href); + } + if ($new_href != "") { + $this->log->debug("... ext link replace " . $href . " with " . $new_href . "."); + $res->nodeset[$i]->set_attribute("Href", $new_href); + } + } elseif ($tree->isGrandChild($a_source_ref_id, $ref_id)) { + // we have no mapping, but the linked object is child of the original node -> remove link + $this->log->debug("... remove ext links."); + if ($res->nodeset[$i]->parent_node()->node_name() == "MapArea") { // simply remove map areas + $parent = $res->nodeset[$i]->parent_node(); + $parent->unlink_node($parent); + } else { // replace link by content of the link for other internal links + $source_node = $res->nodeset[$i]; + $new_node = $source_node->clone_node(true); + $new_node->unlink_node($new_node); + $childs = $new_node->child_nodes(); + for ($j = 0; $j < count($childs); $j++) { + $this->log->debug("... move node $j " . $childs[$j]->node_name() . " before " . $source_node->node_name()); + $source_node->insert_before($childs[$j], $source_node); + } + $source_node->unlink_node($source_node); + } + } + } + } + unset($xpc); + } + + + /** + * Create new page object with current xml content + */ + public function createFromXML() + { + $empty = false; + if ($this->getXMLContent() == "") { + $this->setXMLContent(""); + $empty = true; + } + + $content = $this->getXMLContent(); + $this->buildDom(true); + $dom_doc = $this->getDomDoc(); + + $iel = $this->containsDeactivatedElements($content); + $inl = $this->containsIntLinks($content); + + // create object + $this->db->insert("page_object", array( + "page_id" => array("integer", $this->getId()), + "parent_id" => array("integer", $this->getParentId()), + "lang" => array("text", $this->getLanguage()), + "content" => array("clob", $content), + "parent_type" => array("text", $this->getParentType()), + "create_user" => array("integer", $this->user->getId()), + "last_change_user" => array("integer", $this->user->getId()), + "active" => array("integer", (int) $this->getActive()), + "activation_start" => array("timestamp", $this->getActivationStart()), + "activation_end" => array("timestamp", $this->getActivationEnd()), + "show_activation_info" => array("integer", (int) $this->getShowActivationInfo()), + "inactive_elements" => array("integer", $iel), + "int_links" => array("integer", $inl), + "created" => array("timestamp", ilUtil::now()), + "last_change" => array("timestamp", ilUtil::now()) + )); + + // after update event + $this->__afterUpdate($dom_doc, $content, true, $empty); + } + + + /** + * Updates page object with current xml content + * + * This function is currently (4.4.0 alpha) called by: + * - ilContObjParser (LM and Glossary import parser) + * - ilSCORM13Package->dbImportSco (SCORM importer) + * - assQuestion->copyPageOfQuestion + */ + public function updateFromXML() + { + $this->log->debug("ilPageObject, updateFromXML(): start, id: " . $this->getId()); + + $content = $this->getXMLContent(); + + $this->log->debug("ilPageObject, updateFromXML(): content: " . substr($content, 0, 100)); + + $this->buildDom(true); + $dom_doc = $this->getDomDoc(); + + $iel = $this->containsDeactivatedElements($content); + $inl = $this->containsIntLinks($content); + + $this->db->update("page_object", array( + "content" => array("clob", $content), + "parent_id" => array("integer", $this->getParentId()), + "last_change_user" => array("integer", $this->user->getId()), + "last_change" => array("timestamp", ilUtil::now()), + "active" => array("integer", $this->getActive()), + "activation_start" => array("timestamp", $this->getActivationStart()), + "activation_end" => array("timestamp", $this->getActivationEnd()), + "inactive_elements" => array("integer", $iel), + "int_links" => array("integer", $inl), + ), array( + "page_id" => array("integer", $this->getId()), + "parent_type" => array("text", $this->getParentType()), + "lang" => array("text", $this->getLanguage()) + )); + + // after update event + $this->__afterUpdate($dom_doc, $content); + + $this->log->debug("ilPageObject, updateFromXML(): end"); + + return true; + } + + /** + * After update event handler (internal). The hooks are e.g. for + * storing any dependent relations/references in the database. + * + * @param + */ + final protected function __afterUpdate($a_domdoc, $a_xml, $a_creation = false, $a_empty = false) + { + // we do not need this if we are creating an empty page + if (!$a_creation || !$a_empty) { + // save internal link information + // the page object is responsible to do this, since it "offers" the + // internal link feature pc and page classes + $this->saveInternalLinks($a_domdoc); + + // save style usage + $this->saveStyleUsage($a_domdoc); + + // pc classes hook + include_once("./Services/COPage/classes/class.ilCOPagePCDef.php"); + $defs = ilCOPagePCDef::getPCDefinitions(); + foreach ($defs as $def) { + ilCOPagePCDef::requirePCClassByName($def["name"]); + $cl = $def["pc_class"]; + call_user_func($def["pc_class"] . '::afterPageUpdate', $this, $a_domdoc, $a_xml, $a_creation); + } + } + + // call page hook + $this->afterUpdate($a_domdoc, $a_xml); + + // call update listeners + $this->callUpdateListeners(); + } + + /** + * After update + * + * @param + * @return + */ + public function afterUpdate() + { + } + + + /** + * update complete page content in db (dom xml content is used) + * + */ + public function update($a_validate = true, $a_no_history = false) + { + $this->log->debug("ilPageObject, update(): start, id: " . $this->getId()); + + $lm_set = new ilSetting("lm"); + + // add missing pc ids + if (!$this->checkPCIds()) { + $this->insertPCIds(); + } + + // test validating + if ($a_validate) { + $errors = $this->validateDom(); + } + //var_dump($errors); exit; + if (empty($errors) && !$this->getEditLock()) { + include_once("./Services/User/classes/class.ilUserUtil.php"); + $lock = $this->getEditLockInfo(); + $errors[0] = array(0 => 0, + 1 => "nocontent#" . $this->lng->txt("cont_not_saved_edit_lock_expired") . "
          " . + $this->lng->txt("obj_usr") . ": " . + ilUserUtil::getNamePresentation($lock["edit_lock_user"]) . "
          " . + $this->lng->txt("content_until") . ": " . + ilDatePresentation::formatDate(new ilDateTime($lock["edit_lock_until"], IL_CAL_UNIX)) + ); + } + + if (!empty($errors)) { + $this->log->debug("ilPageObject, update(): errors: " . print_r($errors, true)); + } + + //echo "-".htmlentities($this->getXMLFromDom())."-"; exit; + if (empty($errors)) { + // @todo 1: is this page type or pc content type + // related -> plugins should be able to hook in!? + $this->performAutomaticModifications(); + + // get xml content + $content = $this->getXMLFromDom(); + $dom_doc = $this->getDomDoc(); + + // this needs to be locked + + // write history entry + $old_set = $this->db->query("SELECT * FROM page_object WHERE " . + "page_id = " . $this->db->quote($this->getId(), "integer") . " AND " . + "parent_type = " . $this->db->quote($this->getParentType(), "text") . " AND " . + "lang = " . $this->db->quote($this->getLanguage(), "text")); + $last_nr_set = $this->db->query("SELECT max(nr) as mnr FROM page_history WHERE " . + "page_id = " . $this->db->quote($this->getId(), "integer") . " AND " . + "parent_type = " . $this->db->quote($this->getParentType(), "text") . " AND " . + "lang = " . $this->db->quote($this->getLanguage(), "text")); + $last_nr = $this->db->fetchAssoc($last_nr_set); + if ($old_rec = $this->db->fetchAssoc($old_set)) { + // only save, if something has changed + // added user id to the check for ilias 5.0, 7.10.2014 + if (($content != $old_rec["content"] || $this->user->getId() != $old_rec["last_change_user"]) && + !$a_no_history && !$this->history_saved && $lm_set->get("page_history", 1)) { + if ($old_rec["content"] != "") { + $this->db->manipulateF( + "DELETE FROM page_history WHERE " . + "page_id = %s AND parent_type = %s AND hdate = %s AND lang = %s", + array("integer", "text", "timestamp", "text"), + array($old_rec["page_id"], $old_rec["parent_type"], $old_rec["last_change"], $old_rec["lang"]) + ); + + // the following lines are a workaround for + // bug 6741 + $last_c = $old_rec["last_change"]; + if ($last_c == "") { + $last_c = ilUtil::now(); + } + + $this->db->insert("page_history", array( + "page_id" => array("integer", $old_rec["page_id"]), + "parent_type" => array("text", $old_rec["parent_type"]), + "lang" => array("text", $old_rec["lang"]), + "hdate" => array("timestamp", $last_c), + "parent_id" => array("integer", $old_rec["parent_id"]), + "content" => array("clob", $old_rec["content"]), + "user_id" => array("integer", $old_rec["last_change_user"]), + "ilias_version" => array("text", ILIAS_VERSION_NUMERIC), + "nr" => array("integer", (int) $last_nr["mnr"] + 1) + )); + + $old_content = $old_rec["content"]; + $old_domdoc = new DOMDocument(); + $old_nr = $last_nr["mnr"] + 1; + $old_domdoc->loadXML('' . $old_content); + + // after history entry creation event + $this->__afterHistoryEntry($old_domdoc, $old_content, $old_nr); + + $this->history_saved = true; // only save one time + } else { + $this->history_saved = true; // do not save on first change + } + } + } + //echo htmlentities($content); + $em = (trim($content) == "") + ? 1 + : 0; + + // @todo: pass dom instead? + $iel = $this->containsDeactivatedElements($content); + $inl = $this->containsIntLinks($content); + + $this->db->update("page_object", array( + "content" => array("clob", $content), + "parent_id" => array("integer", $this->getParentId()), + "last_change_user" => array("integer", $this->user->getId()), + "last_change" => array("timestamp", ilUtil::now()), + "is_empty" => array("integer", $em), + "active" => array("integer", $this->getActive()), + "activation_start" => array("timestamp", $this->getActivationStart()), + "activation_end" => array("timestamp", $this->getActivationEnd()), + "show_activation_info" => array("integer", $this->getShowActivationInfo()), + "inactive_elements" => array("integer", $iel), + "int_links" => array("integer", $inl), + ), array( + "page_id" => array("integer", $this->getId()), + "parent_type" => array("text", $this->getParentType()), + "lang" => array("text", $this->getLanguage()) + )); + + // after update event + $this->__afterUpdate($dom_doc, $content); + + $this->log->debug("ilPageObject, update(): updated and returning true, content: " . substr($this->getXMLContent(), 0, 100)); + + //echo "
          PageObject::update:".htmlentities($this->getXMLContent()).":"; + return true; + } else { + return $errors; + } + } + + + + /** + * delete page object + */ + public function delete() + { + $copg_logger = ilLoggerFactory::getLogger('copg'); + $copg_logger->debug( + "ilPageObject: Delete called for ID '" . $this->getId() . "'," . + " parent type: '" . $this->getParentType() . "', " . + " hist nr: '" . $this->old_nr . "', " . + " lang: '" . $this->getLanguage() . "', " + ); + + $mobs = array(); + $files = array(); + + if (!$this->page_not_found) { + $this->buildDom(); + $mobs = $this->collectMediaObjects(false); + } + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $mobs2 = ilObjMediaObject::_getMobsOfObject($this->getParentType() . ":pg", $this->getId(), false); + foreach ($mobs2 as $m) { + if (!in_array($m, $mobs)) { + $mobs[] = $m; + } + } + + $copg_logger->debug("ilPageObject: ... found " . count($mobs) . " media objects."); + + $this->__beforeDelete(); + + // treat plugged content + $this->handleDeleteContent(); + + // delete style usages + $this->deleteStyleUsages(false); + + // delete internal links + $this->deleteInternalLinks(); + + // delete all mob usages + ilObjMediaObject::_deleteAllUsages($this->getParentType() . ":pg", $this->getId()); + + // delete news + include_once("./Services/News/classes/class.ilNewsItem.php"); + ilNewsItem::deleteNewsOfContext( + $this->getParentId(), + $this->getParentType(), + $this->getId(), + "pg" + ); + + // delete page_object entry + $this->db->manipulate("DELETE FROM page_object " . + "WHERE page_id = " . $this->db->quote($this->getId(), "integer") . + " AND parent_type= " . $this->db->quote($this->getParentType(), "text")); + + // delete media objects + foreach ($mobs as $mob_id) { + $copg_logger->debug("ilPageObject: ... processing mob " . $mob_id . "."); + + if (ilObject::_lookupType($mob_id) != 'mob') { + $copg_logger->debug("ilPageObject: ... type mismatch. Ignoring mob " . $mob_id . "."); + continue; + } + + if (ilObject::_exists($mob_id)) { + $copg_logger->debug("ilPageObject: ... delete mob " . $mob_id . "."); + + $mob_obj = new ilObjMediaObject($mob_id); + $mob_obj->delete(); + } else { + $copg_logger->debug("ilPageObject: ... missing mob " . $mob_id . "."); + } + } + } + + /** + * Before deletion handler (internal). + * + * @param + */ + final protected function __beforeDelete() + { + // pc classes hook + include_once("./Services/COPage/classes/class.ilCOPagePCDef.php"); + $defs = ilCOPagePCDef::getPCDefinitions(); + foreach ($defs as $def) { + ilCOPagePCDef::requirePCClassByName($def["name"]); + $cl = $def["pc_class"]; + call_user_func($def["pc_class"] . '::beforePageDelete', $this); + } + } + + /** + * Before deletion handler (internal). + * + * @param + */ + final protected function __afterHistoryEntry($a_old_domdoc, $a_old_content, $a_old_nr) + { + // save style usage + $this->saveStyleUsage($a_old_domdoc, $a_old_nr); + + // pc classes hook + include_once("./Services/COPage/classes/class.ilCOPagePCDef.php"); + $defs = ilCOPagePCDef::getPCDefinitions(); + foreach ($defs as $def) { + ilCOPagePCDef::requirePCClassByName($def["name"]); + $cl = $def["pc_class"]; + call_user_func($def["pc_class"] . '::afterPageHistoryEntry', $this, $a_old_domdoc, $a_old_content, $a_old_nr); + } + } + + /** + * Save all style class/template usages + * + * @param string $a_xml xml data of page + */ + public function saveStyleUsage($a_domdoc, $a_old_nr = 0) + { + // media aliases + $xpath = new DOMXPath($a_domdoc); + $path = "//Paragraph | //Section | //MediaAlias | //FileItem" . + " | //Table | //TableData | //Tabs | //List"; + $nodes = $xpath->query($path); + $usages = array(); + foreach ($nodes as $node) { + switch ($node->localName) { + case "Paragraph": + $sname = $node->getAttribute("Characteristic"); + $stype = "text_block"; + $template = 0; + break; + + case "Section": + $sname = $node->getAttribute("Characteristic"); + $stype = "section"; + $template = 0; + break; + + case "MediaAlias": + $sname = $node->getAttribute("Class"); + $stype = "media_cont"; + $template = 0; + break; + + case "FileItem": + $sname = $node->getAttribute("Class"); + $stype = "flist_li"; + $template = 0; + break; + + case "Table": + $sname = $node->getAttribute("Template"); + if ($sname == "") { + $sname = $node->getAttribute("Class"); + $stype = "table"; + $template = 0; + } else { + $stype = "table"; + $template = 1; + } + break; + + case "TableData": + $sname = $node->getAttribute("Class"); + $stype = "table_cell"; + $template = 0; + break; + + case "Tabs": + $sname = $node->getAttribute("Template"); + if ($sname != "") { + if ($node->getAttribute("Type") == "HorizontalAccordion") { + $stype = "haccordion"; + } + if ($node->getAttribute("Type") == "VerticalAccordion") { + $stype = "vaccordion"; + } + } + $template = 1; + break; + + case "List": + $sname = $node->getAttribute("Class"); + if ($node->getAttribute("Type") == "Ordered") { + $stype = "list_o"; + } else { + $stype = "list_u"; + } + $template = 0; + break; + } + if ($sname != "" && $stype != "") { + $usages[$sname . ":" . $stype . ":" . $template] = array("sname" => $sname, + "stype" => $stype, "template" => $template); + } + } + + + $this->deleteStyleUsages($a_old_nr); + + foreach ($usages as $u) { + $id = $this->db->nextId('page_style_usage'); + + $this->db->manipulate("INSERT INTO page_style_usage " . + "(id, page_id, page_type, page_lang, page_nr, template, stype, sname) VALUES (" . + $this->db->quote($id, "integer") . "," . + $this->db->quote($this->getId(), "integer") . "," . + $this->db->quote($this->getParentType(), "text") . "," . + $this->db->quote($this->getLanguage(), "text") . "," . + $this->db->quote($a_old_nr, "integer") . "," . + $this->db->quote($u["template"], "integer") . "," . + $this->db->quote($u["stype"], "text") . "," . + $this->db->quote($u["sname"], "text") . + ")"); + } + } + + /** + * Delete style usages + * + * @param + * @return + */ + public function deleteStyleUsages($a_old_nr = 0) + { + if ($a_old_nr !== false) { + $and_old_nr = " AND page_nr = " . $this->db->quote($a_old_nr, "integer"); + } + + $this->db->manipulate( + "DELETE FROM page_style_usage WHERE " . + " page_id = " . $this->db->quote($this->getId(), "integer") . + " AND page_type = " . $this->db->quote($this->getParentType(), "text") . + " AND page_lang = " . $this->db->quote($this->getLanguage(), "text") . + $and_old_nr + ); + } + + + /** + * Get last update of included elements (media objects and files). + * This is needed for cache logic, cache must be reloaded if anything has changed. + */ + // @todo: move to content include class + public function getLastUpdateOfIncludedElements() + { + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + include_once("./Modules/File/classes/class.ilObjFile.php"); + $mobs = ilObjMediaObject::_getMobsOfObject( + $this->getParentType() . ":pg", + $this->getId() + ); + $files = ilObjFile::_getFilesOfObject( + $this->getParentType() . ":pg", + $this->getId() + ); + $objs = array_merge($mobs, $files); + return ilObject::_getLastUpdateOfObjects($objs); + } + + /** + * Delete internal links + * + * @param + * @return + */ + public function deleteInternalLinks() + { + include_once("./Services/Link/classes/class.ilInternalLink.php"); + ilInternalLink::_deleteAllLinksOfSource( + $this->getParentType() . ":pg", + $this->getId(), + $this->getLanguage() + ); + } + + + /** + * save internal links of page + * + * @param string xml page code + */ + // @todo: move to specific classes, internal link use info + public function saveInternalLinks($a_domdoc) + { + $this->deleteInternalLinks(); + + // query IntLink elements + $xpath = new DOMXPath($a_domdoc); + $nodes = $xpath->query('//IntLink'); + foreach ($nodes as $node) { + $link_type = $node->getAttribute("Type"); + + switch ($link_type) { + case "StructureObject": + $t_type = "st"; + break; + + case "PageObject": + $t_type = "pg"; + break; + + case "GlossaryItem": + $t_type = "git"; + break; + + case "MediaObject": + $t_type = "mob"; + break; + + case "RepositoryItem": + $t_type = "obj"; + break; + + case "File": + $t_type = "file"; + break; + + case "WikiPage": + $t_type = "wpage"; + break; + + case "PortfolioPage": + $t_type = "ppage"; + break; + + case "User": + $t_type = "user"; + break; + } + + $target = $node->getAttribute("Target"); + $target_arr = explode("_", $target); + $t_id = $target_arr[count($target_arr) - 1]; + + // link to other internal object + if (is_int(strpos($target, "__"))) { + $t_inst = 0; + } else { // link to unresolved object in other installation + $t_inst = $target_arr[1]; + } + + if ($t_id > 0) { + ilInternalLink::_saveLink( + $this->getParentType() . ":pg", + $this->getId(), + $t_type, + $t_id, + $t_inst, + $this->getLanguage() + ); + } + } + } + + /** + * create new page (with current xml data) + */ + public function create() + { + $this->createFromXML(); + } + + /** + * delete content object with hierarchical id $a_hid + * + * @param string $a_hid hierarchical id of content object + * @param boolean $a_update update page in db (note: update deletes all + * hierarchical ids in DOM!) + */ + public function deleteContent($a_hid, $a_update = true, $a_pcid = "") + { + $curr_node = $this->getContentNode($a_hid, $a_pcid); + $this->handleDeleteContent($curr_node); + $curr_node->unlink_node($curr_node); + if ($a_update) { + return $this->update(); + } + } + + + /** + * Delete multiple content objects + * + * @param string $a_hids array of hierarchical ids of content objects + * @param boolean $a_update update page in db (note: update deletes all + * hierarchical ids in DOM!) + */ + public function deleteContents($a_hids, $a_update = true, $a_self_ass = false) + { + if (!is_array($a_hids)) { + return; + } + foreach ($a_hids as $a_hid) { + $a_hid = explode(":", $a_hid); + //echo "-".$a_hid[0]."-".$a_hid[1]."-"; + + // @todo 1: hook + // do not delete question nodes in assessment pages + if (!$this->checkForTag("Question", $a_hid[0], $a_hid[1]) || $a_self_ass) { + $curr_node = $this->getContentNode($a_hid[0], $a_hid[1]); + if (is_object($curr_node)) { + $parent_node = $curr_node->parent_node(); + if ($parent_node->node_name() != "TableRow") { + $this->handleDeleteContent($curr_node); + $curr_node->unlink_node($curr_node); + } + } + } + } + if ($a_update) { + return $this->update(); + } + } + + /** + * Copy contents to clipboard and cut them from the page + * + * @param string $a_hids array of hierarchical ids of content objects + */ + public function cutContents($a_hids) + { + $this->copyContents($a_hids); + return $this->deleteContents($a_hids, true, $this->getPageConfig()->getEnableSelfAssessment()); + } + + /** + * Copy contents to clipboard + * + * @param string $a_hids array of hierarchical ids of content objects + */ + public function copyContents($a_hids) + { + $user = $this->user; + + if (!is_array($a_hids)) { + return; + } + + $time = date("Y-m-d H:i:s", time()); + + $hier_ids = array(); + $skip = array(); + foreach ($a_hids as $a_hid) { + if ($a_hid == "") { + continue; + } + $a_hid = explode(":", $a_hid); + + // check, whether new hid is child of existing one or vice versa + reset($hier_ids); + foreach ($hier_ids as $h) { + if ($h . "_" == substr($a_hid[0], 0, strlen($h) + 1)) { + $skip[] = $a_hid[0]; + } + if ($a_hid[0] . "_" == substr($h, 0, strlen($a_hid[0]) + 1)) { + $skip[] = $h; + } + } + $pc_id[$a_hid[0]] = $a_hid[1]; + if ($a_hid[0] != "") { + $hier_ids[$a_hid[0]] = $a_hid[0]; + } + } + foreach ($skip as $s) { + unset($hier_ids[$s]); + } + include_once("./Services/COPage/classes/class.ilPageContent.php"); + $hier_ids = ilPageContent::sortHierIds($hier_ids); + $nr = 1; + foreach ($hier_ids as $hid) { + $curr_node = $this->getContentNode($hid, $pc_id[$hid]); + if (is_object($curr_node)) { + if ($curr_node->node_name() == "PageContent") { + $content = $this->dom->dump_node($curr_node); + // remove pc and hier ids + $content = preg_replace('/PCID=\"[a-z0-9]*\"/i', "", $content); + $content = preg_replace('/HierId=\"[a-z0-9_]*\"/i', "", $content); + + $user->addToPCClipboard($content, $time, $nr); + $nr++; + } + } + } + include_once("./Modules/LearningModule/classes/class.ilEditClipboard.php"); + ilEditClipboard::setAction("copy"); + } + + /** + * Paste contents from pc clipboard + */ + public function pasteContents($a_hier_id, $a_self_ass = false) + { + $user = $this->user; + + $a_hid = explode(":", $a_hier_id); + $content = $user->getPCClipboardContent(); + + // we insert from last to first, because we insert all at the + // same hier_id + for ($i = count($content) - 1; $i >= 0; $i--) { + $c = $content[$i]; + $temp_dom = domxml_open_mem( + '' . $c, + DOMXML_LOAD_PARSING, + $error + ); + if (empty($error)) { + $this->handleCopiedContent($temp_dom, $a_self_ass); + $xpc = xpath_new_context($temp_dom); + $path = "//PageContent"; + $res = xpath_eval($xpc, $path); + if (count($res->nodeset) > 0) { + $new_pc_node = $res->nodeset[0]; + $cloned_pc_node = $new_pc_node->clone_node(true); + $cloned_pc_node->unlink_node($cloned_pc_node); + $this->insertContentNode( + $cloned_pc_node, + $a_hid[0], + IL_INSERT_AFTER, + $a_hid[1] + ); + } + } else { + //var_dump($error); + } + } + $e = $this->update(); + //var_dump($e); + } + + /** + * (De-)activate elements + */ + public function switchEnableMultiple($a_hids, $a_update = true, $a_self_ass = false) + { + if (!is_array($a_hids)) { + return; + } + $obj = &$this->content_obj; + + foreach ($a_hids as $a_hid) { + $a_hid = explode(":", $a_hid); + $curr_node = $this->getContentNode($a_hid[0], $a_hid[1]); + if (is_object($curr_node)) { + if ($curr_node->node_name() == "PageContent") { + $cont_obj = $this->getContentObject($a_hid[0], $a_hid[1]); + if ($cont_obj->isEnabled()) { + // do not deactivate question nodes in assessment pages + if (!$this->checkForTag("Question", $a_hid[0], $a_hid[1]) || $a_self_ass) { + $cont_obj->disable(); + } + } else { + $cont_obj->enable(); + } + } + } + } + + if ($a_update) { + return $this->update(); + } + } + + + /** + * delete content object with hierarchical id >= $a_hid + * + * @param string $a_hid hierarchical id of content object + * @param boolean $a_update update page in db (note: update deletes all + * hierarchical ids in DOM!) + */ + public function deleteContentFromHierId($a_hid, $a_update = true) + { + $hier_ids = $this->getHierIds(); + + // iterate all hierarchical ids + foreach ($hier_ids as $hier_id) { + // delete top level nodes only + if (!is_int(strpos($hier_id, "_"))) { + if ($hier_id != "pg" && $hier_id >= $a_hid) { + $curr_node = $this->getContentNode($hier_id); + $this->handleDeleteContent($curr_node); + $curr_node->unlink_node($curr_node); + } + } + } + if ($a_update) { + return $this->update(); + } + } + + /** + * delete content object with hierarchical id < $a_hid + * + * @param string $a_hid hierarchical id of content object + * @param boolean $a_update update page in db (note: update deletes all + * hierarchical ids in DOM!) + */ + public function deleteContentBeforeHierId($a_hid, $a_update = true) + { + $hier_ids = $this->getHierIds(); + + // iterate all hierarchical ids + foreach ($hier_ids as $hier_id) { + // delete top level nodes only + if (!is_int(strpos($hier_id, "_"))) { + if ($hier_id != "pg" && $hier_id < $a_hid) { + $curr_node = $this->getContentNode($hier_id); + $this->handleDeleteContent($curr_node); + $curr_node->unlink_node($curr_node); + } + } + } + if ($a_update) { + return $this->update(); + } + } + + + /** + * move content of hierarchical id >= $a_hid to other page + * + * @param string $a_hid hierarchical id of content object + * @param boolean $a_update update page in db (note: update deletes all + * hierarchical ids in DOM!) + */ + public static function _moveContentAfterHierId(&$a_source_page, &$a_target_page, $a_hid) + { + $hier_ids = $a_source_page->getHierIds(); + + $copy_ids = array(); + + // iterate all hierarchical ids + 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); + + $parent_node = $a_target_page->getContentNode("pg"); + $target_dom = $a_target_page->getDom(); + $parent_childs = $parent_node->child_nodes(); + $cnt_parent_childs = count($parent_childs); + //echo "-$cnt_parent_childs-"; + $first_child = $parent_childs[0]; + foreach ($copy_ids as $copy_id) { + $source_node = $a_source_page->getContentNode($copy_id); + + $new_node = $source_node->clone_node(true); + $new_node->unlink_node($new_node); + + $source_node->unlink_node($source_node); + + if ($cnt_parent_childs == 0) { + $new_node = $parent_node->append_child($new_node); + } else { + //$target_dom->import_node($new_node); + $new_node = $first_child->insert_before($new_node, $first_child); + } + $parent_childs = $parent_node->child_nodes(); + + //$cnt_parent_childs++; + } + + $a_target_page->update(); + $a_source_page->update(); + } + + /** + * insert a content node before/after a sibling or as first child of a parent + */ + public function insertContent(&$a_cont_obj, $a_pos, $a_mode = IL_INSERT_AFTER, $a_pcid = "") + { + //echo "-".$a_pos."-".$a_pcid."-"; + // move mode into container elements is always INSERT_CHILD + $curr_node = $this->getContentNode($a_pos, $a_pcid); + $curr_name = $curr_node->node_name(); + + // @todo: try to generalize this + if (($curr_name == "TableData") || ($curr_name == "PageObject") || + ($curr_name == "ListItem") || ($curr_name == "Section") + || ($curr_name == "Tab") || ($curr_name == "ContentPopup") + || ($curr_name == "GridCell")) { + $a_mode = IL_INSERT_CHILD; + } + + $hid = $curr_node->get_attribute("HierId"); + if ($hid != "") { + //echo "-".$a_pos."-".$hid."-"; + $a_pos = $hid; + } + + if ($a_mode != IL_INSERT_CHILD) { // determine parent hierarchical id + // of sibling at $a_pos + $pos = explode("_", $a_pos); + $target_pos = array_pop($pos); + $parent_pos = implode($pos, "_"); + } else { // if we should insert a child, $a_pos is alreade the hierarchical id + // of the parent node + $parent_pos = $a_pos; + } + + // get the parent node + if ($parent_pos != "") { + $parent_node = $this->getContentNode($parent_pos); + } else { + $parent_node = $this->getNode(); + } + + // count the parent children + $parent_childs = $parent_node->child_nodes(); + $cnt_parent_childs = count($parent_childs); + //echo "ZZ$a_mode"; + switch ($a_mode) { + // insert new node after sibling at $a_pos + case IL_INSERT_AFTER: + $new_node = $a_cont_obj->getNode(); + //$a_pos = ilPageContent::incEdId($a_pos); + //$curr_node = $this->getContentNode($a_pos); //echo "behind $a_pos:"; - if($succ_node = $curr_node->next_sibling()) - { - $new_node = $succ_node->insert_before($new_node, $succ_node); - } - else - { -//echo "movin doin append_child"; - $new_node = $parent_node->append_child($new_node); - } - $a_cont_obj->setNode($new_node); - break; - - case IL_INSERT_BEFORE: + if ($succ_node = $curr_node->next_sibling()) { + $new_node = $succ_node->insert_before($new_node, $succ_node); + } else { + //echo "movin doin append_child"; + $new_node = $parent_node->append_child($new_node); + } + $a_cont_obj->setNode($new_node); + break; + + case IL_INSERT_BEFORE: //echo "INSERT_BEF"; - $new_node = $a_cont_obj->getNode(); - $succ_node = $this->getContentNode($a_pos); - $new_node = $succ_node->insert_before($new_node, $succ_node); - $a_cont_obj->setNode($new_node); - break; - - // insert new node as first child of parent $a_pos (= $a_parent) - case IL_INSERT_CHILD: + $new_node = $a_cont_obj->getNode(); + $succ_node = $this->getContentNode($a_pos); + $new_node = $succ_node->insert_before($new_node, $succ_node); + $a_cont_obj->setNode($new_node); + break; + + // insert new node as first child of parent $a_pos (= $a_parent) + case IL_INSERT_CHILD: //echo "insert as child:parent_childs:$cnt_parent_childs:
          "; - $new_node = $a_cont_obj->getNode(); - if($cnt_parent_childs == 0) - { - $new_node = $parent_node->append_child($new_node); - } - else - { - $new_node = $parent_childs[0]->insert_before($new_node, $parent_childs[0]); - } - $a_cont_obj->setNode($new_node); + $new_node = $a_cont_obj->getNode(); + if ($cnt_parent_childs == 0) { + $new_node = $parent_node->append_child($new_node); + } else { + $new_node = $parent_childs[0]->insert_before($new_node, $parent_childs[0]); + } + $a_cont_obj->setNode($new_node); //echo "PP"; - break; - } - - //check for PlaceHolder to remove in EditMode-keep in Layout Mode - if (!$this->getPageConfig()->getEnablePCType("PlaceHolder")) { - $sub_nodes = $curr_node->child_nodes() ; - foreach ( $sub_nodes as $sub_node ) { - if ($sub_node->node_name() == "PlaceHolder") { - $curr_node->unlink_node(); - } - } - } - } - - /** - * insert a content node before/after a sibling or as first child of a parent - */ - function insertContentNode(&$a_cont_node, $a_pos, $a_mode = IL_INSERT_AFTER, $a_pcid = "") - { - // move mode into container elements is always INSERT_CHILD - $curr_node = $this->getContentNode($a_pos, $a_pcid); - $curr_name = $curr_node->node_name(); - - // @todo: try to generalize - if (($curr_name == "TableData") || ($curr_name == "PageObject") || - ($curr_name == "ListItem") || ($curr_name == "Section") - || ($curr_name == "Tab") || ($curr_name == "ContentPopup") - || ($curr_name == "GridCell")) - { - $a_mode = IL_INSERT_CHILD; - } - - $hid = $curr_node->get_attribute("HierId"); - if ($hid != "") - { - $a_pos = $hid; - } - - if($a_mode != IL_INSERT_CHILD) // determine parent hierarchical id - { // of sibling at $a_pos - $pos = explode("_", $a_pos); - $target_pos = array_pop($pos); - $parent_pos = implode($pos, "_"); - } - else // if we should insert a child, $a_pos is alreade the hierarchical id - { // of the parent node - $parent_pos = $a_pos; - } - - // get the parent node - if($parent_pos != "") - { - $parent_node = $this->getContentNode($parent_pos); - } - else - { - $parent_node = $this->getNode(); - } - - // count the parent children - $parent_childs = $parent_node->child_nodes(); - $cnt_parent_childs = count($parent_childs); - - switch ($a_mode) - { - // insert new node after sibling at $a_pos - case IL_INSERT_AFTER: - //$new_node = $a_cont_obj->getNode(); - if($succ_node = $curr_node->next_sibling()) - { - $a_cont_node = $succ_node->insert_before($a_cont_node, $succ_node); - } - else - { - $a_cont_node = $parent_node->append_child($a_cont_node); - } - //$a_cont_obj->setNode($new_node); - break; - - case IL_INSERT_BEFORE: - //$new_node = $a_cont_obj->getNode(); - $succ_node = $this->getContentNode($a_pos); - $a_cont_node = $succ_node->insert_before($a_cont_node, $succ_node); - //$a_cont_obj->setNode($new_node); - break; - - // insert new node as first child of parent $a_pos (= $a_parent) - case IL_INSERT_CHILD: - //$new_node = $a_cont_obj->getNode(); - if($cnt_parent_childs == 0) - { - $a_cont_node = $parent_node->append_child($a_cont_node); - } - else - { - $a_cont_node = $parent_childs[0]->insert_before($a_cont_node, $parent_childs[0]); - } - //$a_cont_obj->setNode($new_node); - break; - } - } - - /** - * move content object from position $a_source before position $a_target - * (both hierarchical content ids) - */ - function moveContentBefore($a_source, $a_target, $a_spcid = "", $a_tpcid = "") - { - if($a_source == $a_target) - { - return; - } - - // clone the node - $content = $this->getContentObject($a_source, $a_spcid); - $source_node = $content->getNode(); - $clone_node = $source_node->clone_node(true); - - // delete source node - $this->deleteContent($a_source, false, $a_spcid); - - // insert cloned node at target - $content->setNode($clone_node); - $this->insertContent($content, $a_target, IL_INSERT_BEFORE, $a_tpcid); - return $this->update(); - - } - - /** - * move content object from position $a_source before position $a_target - * (both hierarchical content ids) - */ - function moveContentAfter($a_source, $a_target, $a_spcid = "", $a_tpcid = "") - { - if($a_source == $a_target) - { - return; - } - - // clone the node - $content = $this->getContentObject($a_source, $a_spcid); - $source_node = $content->getNode(); - $clone_node = $source_node->clone_node(true); - - // delete source node - $this->deleteContent($a_source, false, $a_spcid); - - // insert cloned node at target - $content->setNode($clone_node); - $this->insertContent($content, $a_target, IL_INSERT_AFTER, $a_tpcid); - return $this->update(); - } - - /** - * transforms bbCode to corresponding xml - */ - // @todo: move to paragraph - function bbCode2XML(&$a_content) - { - $a_content = preg_replace('/\[com\]/i',"",$a_content); - $a_content = preg_replace('/\[\/com\]/i',"",$a_content); - $a_content = preg_replace('/\[emp]/i',"",$a_content); - $a_content = preg_replace('/\[\/emp\]/i',"",$a_content); - $a_content = preg_replace('/\[str]/i',"",$a_content); - $a_content = preg_replace('/\[\/str\]/i',"",$a_content); - } - - /** - * inserts installation id into ids (e.g. il__pg_4 -> il_23_pg_4) - * this is needed for xml export of page - */ - function insertInstIntoIDs($a_inst, $a_res_ref_to_obj_id = true) - { - // insert inst id into internal links - $xpc = xpath_new_context($this->dom); - $path = "//IntLink"; - $res = xpath_eval($xpc, $path); - for($i = 0; $i < count($res->nodeset); $i++) - { - $target = $res->nodeset[$i]->get_attribute("Target"); - $type = $res->nodeset[$i]->get_attribute("Type"); - - if (substr($target, 0, 4) == "il__") - { - $id = substr($target, 4, strlen($target) - 4); - - // convert repository links obj_ to _ - // this leads to bug 6685. - if ($a_res_ref_to_obj_id && $type == "RepositoryItem") - { - $id_arr = explode("_", $id); - - // changed due to bug 6685 - $ref_id = $id_arr[1]; - $obj_id = ilObject::_lookupObjId($id_arr[1]); - - $otype = ilObject::_lookupType($obj_id); - if ($obj_id > 0) - { - // changed due to bug 6685 - // the ref_id should be used, if the content is - // imported on the same installation - // the obj_id should be used, if a different - // installation imports, but has an import_id for - // the object id. - $id = $otype."_".$obj_id."_".$ref_id; - //$id = $otype."_".$ref_id; - } - } - $new_target = "il_".$a_inst."_".$id; - $res->nodeset[$i]->set_attribute("Target", $new_target); - } - } - unset($xpc); - - // @todo: move to media/fileitems/questions, ... - - // insert inst id into media aliases - $xpc = xpath_new_context($this->dom); - $path = "//MediaAlias"; - $res = xpath_eval($xpc, $path); - for($i = 0; $i < count($res->nodeset); $i++) - { - $origin_id = $res->nodeset[$i]->get_attribute("OriginId"); - if (substr($origin_id, 0, 4) == "il__") - { - $new_id = "il_".$a_inst."_".substr($origin_id, 4, strlen($origin_id) - 4); - $res->nodeset[$i]->set_attribute("OriginId", $new_id); - } - } - unset($xpc); - - // insert inst id file item identifier entries - $xpc = xpath_new_context($this->dom); - $path = "//FileItem/Identifier"; - $res = xpath_eval($xpc, $path); - for($i = 0; $i < count($res->nodeset); $i++) - { - $origin_id = $res->nodeset[$i]->get_attribute("Entry"); - if (substr($origin_id, 0, 4) == "il__") - { - $new_id = "il_".$a_inst."_".substr($origin_id, 4, strlen($origin_id) - 4); - $res->nodeset[$i]->set_attribute("Entry", $new_id); - } - } - unset($xpc); - - // insert inst id into question references - $xpc = xpath_new_context($this->dom); - $path = "//Question"; - $res = xpath_eval($xpc, $path); - for($i = 0; $i < count($res->nodeset); $i++) - { - $qref = $res->nodeset[$i]->get_attribute("QRef"); -//echo "
          setted:".$qref; - if (substr($qref, 0, 4) == "il__") - { - $new_id = "il_".$a_inst."_".substr($qref, 4, strlen($qref) - 4); -//echo "
          setting:".$new_id; - $res->nodeset[$i]->set_attribute("QRef", $new_id); - } - } - unset($xpc); - - // insert inst id into content snippets - $xpc = xpath_new_context($this->dom); - $path = "//ContentInclude"; - $res = xpath_eval($xpc, $path); - for($i = 0; $i < count($res->nodeset); $i++) - { - $ci = $res->nodeset[$i]->get_attribute("InstId"); - if ($ci == "") - { - $res->nodeset[$i]->set_attribute("InstId", $a_inst); - } - } - unset($xpc); - - } - - /** - * Check, whether (all) page content hashes are set - */ - function checkPCIds() - { - $this->builddom(); - $mydom = $this->dom; - - $sep = $path = ""; - foreach ($this->id_elements as $el) - { - $path.= $sep."//".$el."[not(@PCID)]"; - $sep = " | "; - $path.= $sep."//".$el."[@PCID='']"; - } - - $xpc = xpath_new_context($mydom); - $res = & xpath_eval($xpc, $path); - - if (count ($res->nodeset) > 0) - { - return false; - } - return true; - } - - /** - * Get all pc ids - * - * @param - * @return - */ - function getAllPCIds() - { - $this->builddom(); - $mydom = $this->dom; - - $pcids = array(); - - $sep = $path = ""; - foreach ($this->id_elements as $el) - { - $path.= $sep."//".$el."[@PCID]"; - $sep = " | "; - } - - // get existing ids - $xpc = xpath_new_context($mydom); - $res = & xpath_eval($xpc, $path); - - for ($i = 0; $i < count ($res->nodeset); $i++) - { - $node = $res->nodeset[$i]; - $pcids[] = $node->get_attribute("PCID"); - } - return $pcids; - } - - /** - * existsPCId - * - * @param - * @return - */ - function existsPCId($a_pc_id) - { - $this->builddom(); - $mydom = $this->dom; - - $pcids = array(); - - $sep = $path = ""; - foreach ($this->id_elements as $el) - { - $path.= $sep."//".$el."[@PCID='".$a_pc_id."']"; - $sep = " | "; - } - - // get existing ids - $xpc = xpath_new_context($mydom); - $res = & xpath_eval($xpc, $path); - return (count($res->nodeset) > 0); - } - - /** - * Generate new pc id - * - * @param array $a_pc_ids existing pc ids - * @return string new pc id - */ - function generatePcId($a_pc_ids = false) - { - if ($a_pc_ids === false) - { - $a_pc_ids = $this->getAllPCIds(); - } - $id = ilUtil::randomHash(10, $a_pc_ids); - return $id; - } - - - /** - * Insert Page Content IDs - */ - function insertPCIds() - { - $this->builddom(); - $mydom = $this->dom; - - $pcids = $this->getAllPCIds(); - - // add missing ones - $sep = $path = ""; - foreach ($this->id_elements as $el) - { - $path.= $sep."//".$el."[not(@PCID)]"; - $sep = " | "; - $path.= $sep."//".$el."[@PCID='']"; - $sep = " | "; - } - $xpc = xpath_new_context($mydom); - $res = & xpath_eval($xpc, $path); - - for ($i = 0; $i < count ($res->nodeset); $i++) - { - $node = $res->nodeset[$i]; - $id = ilUtil::randomHash(10, $pcids); - $pcids[] = $id; -//echo "setting-".$id."-"; - $res->nodeset[$i]->set_attribute("PCID", $id); - } - } - - /** - * Get page contents hashes - */ - function getPageContentsHashes() - { - $this->builddom(); - $this->addHierIds(); - $mydom = $this->dom; - - // get existing ids - $path = "//PageContent"; - $xpc = xpath_new_context($mydom); - $res = & xpath_eval($xpc, $path); - - $hashes = array(); - require_once("./Services/COPage/classes/class.ilPCParagraph.php"); - for ($i = 0; $i < count ($res->nodeset); $i++) - { - $hier_id = $res->nodeset[$i]->get_attribute("HierId"); - $pc_id = $res->nodeset[$i]->get_attribute("PCID"); - $dump = $mydom->dump_node($res->nodeset[$i]); - if (($hpos = strpos($dump, ' HierId="'.$hier_id.'"')) > 0) - { - $dump = substr($dump, 0, $hpos). - substr($dump, $hpos + strlen(' HierId="'.$hier_id.'"')); - } - - $childs = $res->nodeset[$i]->child_nodes(); - $content = ""; - if ($childs[0] && $childs[0]->node_name() == "Paragraph") - { - $content = $mydom->dump_node($childs[0]); - $content = substr($content, strpos($content, ">") + 1, - strrpos($content, "<") - (strpos($content, ">") + 1)); -//var_dump($content); - $content = ilPCParagraph::xml2output($content); -//var_dump($content); - } - //$hashes[$hier_id] = - // array("PCID" => $pc_id, "hash" => md5($dump)); - $hashes[$pc_id] = - array("hier_id" => $hier_id, "hash" => md5($dump), "content" => $content); - } - - return $hashes; - } - - /** - * Get question ids - */ -// @todo: move to questions - function getQuestionIds() - { - $this->builddom(); - $mydom = $this->dom; - - // Get question IDs - $path = "//Question"; - $xpc = xpath_new_context($mydom); - $res = & xpath_eval($xpc, $path); - - $q_ids = array(); - include_once("./Services/Link/classes/class.ilInternalLink.php"); - for ($i = 0; $i < count ($res->nodeset); $i++) - { - $qref = $res->nodeset[$i]->get_attribute("QRef"); - - $inst_id = ilInternalLink::_extractInstOfTarget($qref); - $obj_id = ilInternalLink::_extractObjIdOfTarget($qref); - - if (!($inst_id > 0)) - { - if ($obj_id > 0) - { - $q_ids[] = $obj_id; - } - } - } - return $q_ids; - } - -// @todo: move to paragraph - function send_paragraph ($par_id, $filename) - { - $this->builddom(); - - $mydom = $this->dom; - - $xpc = xpath_new_context($mydom); - - //$path = "//PageContent[position () = $par_id]/Paragraph"; - //$path = "//Paragraph[$par_id]"; - $path = "/descendant::Paragraph[position() = $par_id]"; - - $res = & xpath_eval($xpc, $path); - - if (count ($res->nodeset) != 1) - die ("Should not happen"); - - $context_node = $res->nodeset[0]; - - // get plain text - - $childs = $context_node->child_nodes(); - - for($j=0; $jdump_node($childs[$j]); - } - - $content = str_replace("
          ", "\n", $content); - $content = str_replace("
          ", "\n", $content); - - $plain_content = html_entity_decode($content); - - ilUtil::deliverData($plain_content, $filename); - /* - $file_type = "application/octet-stream"; - header("Content-type: ".$file_type); - header("Content-disposition: attachment; filename=\"$filename\""); - echo $plain_content;*/ - exit(); - } - - /** - * get fo page content - */ -// @todo: deprecated? - function getFO() - { - $xml = $this->getXMLFromDom(false, true, true); - $xsl = file_get_contents("./Services/COPage/xsl/page_fo.xsl"); - $args = array( '/_xml' => $xml, '/_xsl' => $xsl ); - $xh = xslt_create(); - - $params = array (); - - - $fo = xslt_process($xh,"arg:/_xml","arg:/_xsl",NULL,$args, $params); - var_dump($fo); - // do some replacements - $fo = str_replace("\n", "", $fo); - $fo = str_replace("
          ", "
          ", $fo); - $fo = str_replace("
          ", "\n", $fo); - - xslt_free($xh); - - // - $fo = substr($fo, strpos($fo,">") + 1); -//echo "
          fo:
          ".htmlentities($fo); flush(); - return $fo; - } - - function registerOfflineHandler ($handler) { - $this->offline_handler = $handler; - } - - /** - * Get offline handler - * - * @param - * @return - */ - function getOfflineHandler() - { - return $this->offline_handler; - } - - - /** - * lookup whether page contains deactivated elements - */ - static function _lookupContainsDeactivatedElements($a_id, $a_parent_type, $a_lang = "-") - { - global $DIC; - - $db = $DIC->database(); - - if ($a_lang == "") - { - $a_lang = "-"; - } - - $query = "SELECT * FROM page_object WHERE page_id = ". - $db->quote($a_id, "integer")." AND ". - " parent_type = ".$db->quote($a_parent_type, "text")." AND ". - " lang = ".$db->quote($a_lang, "text")." AND ". - " inactive_elements = ".$db->quote(1, "integer"); - $obj_set = $db->query($query); - - if ($obj_rec = $obj_set->fetchRow(ilDBConstants::FETCHMODE_ASSOC)) - { - return true; - } - - return false; - } - - /** - * Check whether content contains deactivated elements - * - * @param - * @return - */ - function containsDeactivatedElements($a_content) - { - if (strpos($a_content, " Enabled=\"False\"")) - { - return true; - } - return false; - } - - /** - * Get History Entries - */ - function getHistoryEntries() - { - $db = $this->db; - - $h_query = "SELECT * FROM page_history ". - " WHERE page_id = ".$db->quote($this->getId(), "integer"). - " AND parent_type = ".$db->quote($this->getParentType(), "text"). - " AND lang = ".$db->quote($this->getLanguage(), "text"). - " ORDER BY hdate DESC"; - - $hset = $db->query($h_query); - $hentries = array(); - - while ($hrec = $db->fetchAssoc($hset)) - { - $hrec["sortkey"] = (int) $hrec["nr"]; - $hrec["user"] = (int) $hrec["user_id"]; - $hentries[] = $hrec; - } -//var_dump($hentries); - return $hentries; - } - - /** - * Get History Entry - */ - function getHistoryEntry($a_old_nr) - { - $db = $this->db; - - $res = $db->queryF("SELECT * FROM page_history ". - " WHERE page_id = %s ". - " AND parent_type = %s ". - " AND nr = %s". - " AND lang = %s", - array("integer", "text", "integer", "text"), - array($this->getId(), $this->getParentType(), $a_old_nr, $this->getLanguage())); - if ($hrec = $db->fetchAssoc($res)) - { - return $hrec; - } - - return false; - } - - - /** - * Get information about a history entry, its predecessor and - * its successor. - * - * @param int $a_nr Nr of history entry - */ - function getHistoryInfo($a_nr) - { - $db = $this->db; - - // determine previous entry - $and_nr = ($a_nr > 0) - ? " AND nr < ".$db->quote((int) $a_nr, "integer") - : ""; - $res = $db->query("SELECT MAX(nr) mnr FROM page_history ". - " WHERE page_id = ".$db->quote($this->getId(), "integer"). - " AND parent_type = ".$db->quote($this->getParentType(), "text"). - " AND lang = ".$db->quote($this->getLanguage(), "text"). - $and_nr); - $row = $db->fetchAssoc($res); - if ($row["mnr"] > 0) - { - $res = $db->query("SELECT * FROM page_history ". - " WHERE page_id = ".$db->quote($this->getId(), "integer"). - " AND parent_type = ".$db->quote($this->getParentType(), "text"). - " AND lang = ".$db->quote($this->getLanguage(), "text"). - " AND nr = ".$db->quote((int) $row["mnr"], "integer")); - $row = $db->fetchAssoc($res); - $ret["previous"] = $row; - } - - // determine next entry - $res = $db->query("SELECT MIN(nr) mnr FROM page_history ". - " WHERE page_id = ".$db->quote($this->getId(), "integer"). - " AND parent_type = ".$db->quote($this->getParentType(), "text"). - " AND lang = ".$db->quote($this->getLanguage(), "text"). - " AND nr > ".$db->quote((int) $a_nr, "integer")); - $row = $db->fetchAssoc($res); - if ($row["mnr"] > 0) - { - $res = $db->query("SELECT * FROM page_history ". - " WHERE page_id = ".$db->quote($this->getId(), "integer"). - " AND parent_type = ".$db->quote($this->getParentType(), "text"). - " AND lang = ".$db->quote($this->getLanguage(), "text"). - " AND nr = ".$db->quote((int) $row["mnr"], "integer")); - $row = $db->fetchAssoc($res); - $ret["next"] = $row; - } - - // current - if ($a_nr > 0) - { - $res = $db->query("SELECT * FROM page_history ". - " WHERE page_id = ".$db->quote($this->getId(), "integer"). - " AND parent_type = ".$db->quote($this->getParentType(), "text"). - " AND lang = ".$db->quote($this->getLanguage(), "text"). - " AND nr = ".$db->quote((int) $a_nr, "integer")); - $row = $db->fetchAssoc($res); - } - else - { - $res = $db->query("SELECT page_id, last_change hdate, parent_type, parent_id, last_change_user user_id, content, lang FROM page_object ". - " WHERE page_id = ".$db->quote($this->getId(), "integer"). - " AND parent_type = ".$db->quote($this->getParentType(), "text"). - " AND lang = ".$db->quote($this->getLanguage(), "text")); - $row = $db->fetchAssoc($res); - } - $ret["current"] = $row; - - return $ret; - } - - function addChangeDivClasses($a_hashes) - { - $xpc = xpath_new_context($this->dom); - $path = "/*[1]"; - $res = xpath_eval($xpc, $path); - $rnode = $res->nodeset[0]; - -//echo "A"; - foreach($a_hashes as $pc_id => $h) - { -//echo "B"; - if ($h["change"] != "") - { - $dc_node = $this->dom->create_element("DivClass"); - $dc_node->set_attribute("HierId", $h["hier_id"]); - $dc_node->set_attribute("Class", "ilEdit".$h["change"]); - $dc_node = $rnode->append_child($dc_node); - } - } -//echo "





          ".htmlentities($this->getXMLFromDom()); - } - - /** - * Compares to revisions of the page - * - * @param int $a_left Nr of first revision - * @param int $a_right Nr of second revision - */ - function compareVersion($a_left, $a_right) - { - // get page objects - include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); - $l_page = ilPageObjectFactory::getInstance($this->getParentType(), $this->getId(), $a_left); - $r_page = ilPageObjectFactory::getInstance($this->getParentType(), $this->getId(), $a_right); - - $l_hashes = $l_page->getPageContentsHashes(); - $r_hashes = $r_page->getPageContentsHashes(); - // determine all deleted and changed page elements - foreach ($l_hashes as $pc_id => $h) - { - if (!isset($r_hashes[$pc_id])) - { - $l_hashes[$pc_id]["change"] = "Deleted"; - } - else - { - if ($l_hashes[$pc_id]["hash"] != $r_hashes[$pc_id]["hash"]) - { - $l_hashes[$pc_id]["change"] = "Modified"; - $r_hashes[$pc_id]["change"] = "Modified"; - - include_once("./Services/COPage/mediawikidiff/class.WordLevelDiff.php"); - // if modified element is a paragraph, highlight changes - if ($l_hashes[$pc_id]["content"] != "" && - $r_hashes[$pc_id]["content"] != "") - { - $new_left = str_replace("\n", "
          ", $l_hashes[$pc_id]["content"]); - $new_right = str_replace("\n", "
          ", $r_hashes[$pc_id]["content"]); - $wldiff = new WordLevelDiff(array($new_left), - array($new_right)); - $new_left = $wldiff->orig(); - $new_right = $wldiff->closing(); - $l_page->setParagraphContent($l_hashes[$pc_id]["hier_id"], $new_left[0]); - $r_page->setParagraphContent($l_hashes[$pc_id]["hier_id"], $new_right[0]); - } - } - } - } - - // determine all new paragraphs - foreach ($r_hashes as $pc_id => $h) - { - if (!isset($l_hashes[$pc_id])) - { - $r_hashes[$pc_id]["change"] = "New"; - } - } - $l_page->addChangeDivClasses($l_hashes); - $r_page->addChangeDivClasses($r_hashes); - - return array("l_page" => $l_page, "r_page" => $r_page, - "l_changes" => $l_hashes, "r_changes" => $r_hashes); - } - - /** - * Increase view cnt - */ - function increaseViewCnt() - { - $db = $this->db; - - $db->manipulate("UPDATE page_object ". - " SET view_cnt = view_cnt + 1 ". - " WHERE page_id = ".$db->quote($this->getId(), "integer"). - " AND parent_type = ".$db->quote($this->getParentType(), "text"). - " AND lang = ".$db->quote($this->getLanguage(), "text")); - } - - /** - * Get recent pages changes for parent object. - * - * @param string $a_parent_type Parent Type - * @param int $a_parent_id Parent ID - * @param int $a_period Time Period - */ - static function getRecentChanges($a_parent_type, $a_parent_id, $a_period = 30, $a_lang = "") - { - global $DIC; - - $db = $DIC->database(); - - $and_lang = ""; - if ($a_lang != "") - { - $and_lang = " AND lang = ".$db->quote($a_lang, "text"); - } - - $page_changes = array(); - $limit_ts = date('Y-m-d H:i:s', time() - ($a_period * 24 * 60 * 60)); - $q = "SELECT * FROM page_object ". - " WHERE parent_id = ".$db->quote($a_parent_id, "integer"). - " AND parent_type = ".$db->quote($a_parent_type, "text"). - " AND last_change >= ".$db->quote($limit_ts, "timestamp").$and_lang; - // " AND (TO_DAYS(now()) - TO_DAYS(last_change)) <= ".((int)$a_period); - $set = $db->query($q); - while($page = $db->fetchAssoc($set)) - { - $page_changes[] = array( - "date" => $page["last_change"], - "id" => $page["page_id"], - "lang" => $page["lang"], - "type" => "page", - "user" => $page["last_change_user"]); - } - - $and_str = ""; - if ($a_period > 0) - { - $limit_ts = date('Y-m-d H:i:s', time() - ($a_period * 24 * 60 * 60)); - $and_str = " AND hdate >= ".$db->quote($limit_ts, "timestamp")." "; - } - - $q = "SELECT * FROM page_history ". - " WHERE parent_id = ".$db->quote($a_parent_id, "integer"). - " AND parent_type = ".$db->quote($a_parent_type, "text"). - $and_str.$and_lang; - $set = $db->query($q); - while ($page = $db->fetchAssoc($set)) - { - $page_changes[] = array( - "date" => $page["hdate"], - "id" => $page["page_id"], - "lang" => $page["lang"], - "type" => "hist", - "nr" => $page["nr"], - "user" => $page["user_id"]); - } - - $page_changes = ilUtil::sortArray($page_changes, "date", "desc"); - - return $page_changes; - } - - /** - * Get all pages for parent object - * - * @param string $a_parent_type - * @param int $a_parent_id - * @param string $a_lang - * @return array - */ - static function getAllPages($a_parent_type, $a_parent_id, $a_lang = "-") - { - global $DIC; - - $db = $DIC->database(); - - $and_lang = ""; - if ($a_lang != "") - { - $and_lang = " AND lang = ".$db->quote($a_lang, "text"); - } - - $q = "SELECT * FROM page_object ". - " WHERE parent_id = ".$db->quote($a_parent_id, "integer"). - " AND parent_type = ".$db->quote($a_parent_type, "text").$and_lang; - $set = $db->query($q); - $pages = array(); - while ($page = $db->fetchAssoc($set)) - { - $key_add = ($a_lang == "") - ? ":".$page["lang"] - : ""; - $pages[$page["page_id"].$key_add] = array( - "date" => $page["last_change"], - "id" => $page["page_id"], - "lang" => $page["lang"], - "user" => $page["last_change_user"]); - } - - return $pages; - } - - /** - * Get new pages. - * - * @param string $a_parent_type Parent Type - * @param int $a_parent_id Parent ID - */ - static function getNewPages($a_parent_type, $a_parent_id, $a_lang = "-") - { - global $DIC; - - $db = $DIC->database(); - - $and_lang = ""; - if ($a_lang != "") - { - $and_lang = " AND lang = ".$db->quote($a_lang, "text"); - } - - $pages = array(); - - $q = "SELECT * FROM page_object ". - " WHERE parent_id = ".$db->quote($a_parent_id, "integer"). - " AND parent_type = ".$db->quote($a_parent_type, "text").$and_lang. - " ORDER BY created DESC"; - $set = $db->query($q); - while($page = $db->fetchAssoc($set)) - { - if ($page["created"] != "") - { - $pages[] = array( - "created" => $page["created"], - "id" => $page["page_id"], - "lang" => $page["lang"], - "user" => $page["create_user"], - ); - } - } - - return $pages; - } - - /** - * Get all contributors for parent object - * - * @param string $a_parent_type Parent Type - * @param int $a_parent_id Parent ID - */ - static function getParentObjectContributors($a_parent_type, $a_parent_id, $a_lang = "-") - { - global $DIC; - - $db = $DIC->database(); - - $and_lang = ""; - if ($a_lang != "") - { - $and_lang = " AND lang = ".$db->quote($a_lang, "text"); - } - - $contributors = array(); - $set = $db->queryF("SELECT last_change_user, lang, page_id FROM page_object ". - " WHERE parent_id = %s AND parent_type = %s ". - " AND last_change_user != %s".$and_lang, - array("integer", "text", "integer"), - array($a_parent_id, $a_parent_type, 0)); - - while ($page = $db->fetchAssoc($set)) - { - if ($a_lang == "") - { - $contributors[$page["last_change_user"]][$page["page_id"]][$page["lang"]] = 1; - } - else - { - $contributors[$page["last_change_user"]][$page["page_id"]] = 1; - } - } - - $set = $db->queryF("SELECT count(*) as cnt, lang, page_id, user_id FROM page_history ". - " WHERE parent_id = %s AND parent_type = %s AND user_id != %s ".$and_lang. - " GROUP BY page_id, user_id, lang ", - array("integer", "text", "integer"), - array($a_parent_id, $a_parent_type, 0)); - while ($hpage = $db->fetchAssoc($set)) - { - if ($a_lang == "") - { - $contributors[$hpage["user_id"]][$hpage["page_id"]][$hpage["lang"]] = - $contributors[$hpage["user_id"]][$hpage["page_id"]][$hpage["lang"]] + $hpage["cnt"]; - } - else - { - $contributors[$hpage["user_id"]][$hpage["page_id"]] = - $contributors[$hpage["user_id"]][$hpage["page_id"]] + $hpage["cnt"]; - } - } - - $c = array(); - foreach ($contributors as $k => $co) - { - if (ilObject::_lookupType($k) == "usr") - { - $name = ilObjUser::_lookupName($k); - $c[] = array("user_id" => $k, "pages" => $co, - "lastname" => $name["lastname"], "firstname" => $name["firstname"]); - } - } - - return $c; - } - - /** - * Get all contributors for parent object - * - * @param string $a_parent_type Parent Type - * @param int $a_parent_id Parent ID - */ - static function getPageContributors($a_parent_type, $a_page_id, $a_lang = "-") - { - global $DIC; - - $db = $DIC->database(); - - $and_lang = ""; - if ($a_lang != "") - { - $and_lang = " AND lang = ".$db->quote($a_lang, "text"); - } - - $contributors = array(); - $set = $db->queryF("SELECT last_change_user, lang FROM page_object ". - " WHERE page_id = %s AND parent_type = %s ". - " AND last_change_user != %s".$and_lang, - array("integer", "text", "integer"), - array($a_page_id, $a_parent_type, 0)); - - while ($page = $db->fetchAssoc($set)) - { - if ($a_lang == "") - { - $contributors[$page["last_change_user"]][$page["lang"]] = 1; - } - else - { - $contributors[$page["last_change_user"]] = 1; - } - } - - $set = $db->queryF("SELECT count(*) as cnt, lang, page_id, user_id FROM page_history ". - " WHERE page_id = %s AND parent_type = %s AND user_id != %s ".$and_lang. - " GROUP BY user_id, page_id, lang ", - array("integer", "text", "integer"), - array($a_page_id, $a_parent_type, 0)); - while ($hpage = $db->fetchAssoc($set)) - { - if ($a_lang == "") - { - $contributors[$hpage["user_id"]][$page["lang"]] = - $contributors[$hpage["user_id"]][$page["lang"]] + $hpage["cnt"]; - } - else - { - $contributors[$hpage["user_id"]] = - $contributors[$hpage["user_id"]] + $hpage["cnt"]; - } - } - - $c = array(); - foreach ($contributors as $k => $co) - { - include_once "Services/User/classes/class.ilObjUser.php"; - $name = ilObjUser::_lookupName($k); - $c[] = array("user_id" => $k, "pages" => $co, - "lastname" => $name["lastname"], "firstname" => $name["firstname"]); - } - - return $c; - } - - /** - * Write rendered content - */ - function writeRenderedContent($a_content, $a_md5) - { - global $DIC; - - $db = $DIC->database(); - - $db->update("page_object", array( - "rendered_content" => array("clob", $a_content), - "render_md5" => array("text", $a_md5), - "rendered_time" => array("timestamp", ilUtil::now()) - ), array( - "page_id" => array("integer", $this->getId()), - "lang" => array("text", $this->getLanguage()), - "parent_type" => array("text", $this->getParentType()) - )); - } - - /** - * Get all pages for parent object that contain internal links - * - * @param string $a_parent_type Parent Type - * @param int $a_parent_id Parent ID - * @param int $a_period Time Period - */ - static function getPagesWithLinks($a_parent_type, $a_parent_id, $a_lang = "-") - { - global $DIC; - - $db = $DIC->database(); - - $and_lang = ""; - if ($a_lang != "") - { - $and_lang = " AND lang = ".$db->quote($a_lang, "text"); - } - - $q = "SELECT * FROM page_object ". - " WHERE parent_id = ".$db->quote($a_parent_id, "integer"). - " AND parent_type = ".$db->quote($a_parent_type, "text"). - " AND int_links = ".$db->quote(1, "integer").$and_lang; - $set = $db->query($q); - $pages = array(); - while ($page = $db->fetchAssoc($set)) - { - $key_add = ($a_lang == "") - ? ":".$page["lang"] - : ""; - $pages[$page["page_id"].$key_add] = array( - "date" => $page["last_change"], - "id" => $page["page_id"], - "lang" => $page["lang"], - "user" => $page["last_change_user"]); - } - - return $pages; - } - - /** - * Check whether content contains internal links - * - * @param - * @return - */ - function containsIntLinks($a_content) - { - if (strpos($a_content, "IntLink")) - { - return true; - } - return false; - } - - /** - * Perform automatic modifications (may be overwritten by sub classes) - */ - function performAutomaticModifications() - { - } - - /** - * Save initial opened content - * - * @param - */ -// @todo begin: generalize - function saveInitialOpenedContent($a_type, $a_id, $a_target) - { - $this->buildDom(); - - $link_type = ""; - - switch($a_type) - { - case "media": - $link_type = "MediaObject"; - $a_id = "il__mob_".$a_id; - break; - - case "page": - $link_type = "PageObject"; - $a_id = "il__pg_".$a_id; - break; - - case "term": - $link_type = "GlossaryItem"; - $a_id = "il__git_".$a_id; - $a_target = "Glossary"; - break; - } - - // if type or id missing -> delete InitOpenedContent, if existing - if ($link_type == "" || $a_id == "") - { - $xpc = xpath_new_context($this->dom); - $path = "//PageObject/InitOpenedContent"; - $res = xpath_eval($xpc, $path); - if (count($res->nodeset) > 0) - { - $res->nodeset[0]->unlink_node($res->nodeset[0]); - } - } - else - { - $xpc = xpath_new_context($this->dom); - $path = "//PageObject/InitOpenedContent"; - $res = xpath_eval($xpc, $path); - if (count($res->nodeset) > 0) - { - $init_node = $res->nodeset[0]; - $childs = $init_node->child_nodes(); - for($i = 0; $i < count($childs); $i++) - { - if ($childs[$i]->node_name() == "IntLink") - { - $il_node = $childs[$i]; - } - } - } - else - { - $path = "//PageObject"; - $res = xpath_eval($xpc, $path); - $page_node = $res->nodeset[0]; - $init_node = $this->dom->create_element("InitOpenedContent"); - $init_node = $page_node->append_child($init_node); - $il_node = $this->dom->create_element("IntLink"); - $il_node = $init_node->append_child($il_node); - } - $il_node->set_attribute("Target", $a_id); - $il_node->set_attribute("Type", $link_type); - $il_node->set_attribute("TargetFrame", $a_target); - } - - $this->update(); - } - - - /** - * Get initial opened content - * - * @param - */ - function getInitialOpenedContent() - { - $this->buildDom(); - - $xpc = xpath_new_context($this->dom); - $path = "//PageObject/InitOpenedContent"; - $res = xpath_eval($xpc, $path); - $il_node = null; - if (count($res->nodeset) > 0) - { - $init_node = $res->nodeset[0]; - $childs = $init_node->child_nodes(); - for($i = 0; $i < count($childs); $i++) - { - if ($childs[$i]->node_name() == "IntLink") - { - $il_node = $childs[$i]; - } - } - } - if (!is_null($il_node)) - { - $id = $il_node->get_attribute("Target"); - $link_type = $il_node->get_attribute("Type"); - $target = $il_node->get_attribute("TargetFrame"); - - switch($link_type) - { - case "MediaObject": - $type = "media"; - break; - - case "PageObject": - $type = "page"; - break; - - case "GlossaryItem": - $type = "term"; - break; - } - include_once("./Services/Link/classes/class.ilInternalLink.php"); - $id = ilInternalLink::_extractObjIdOfTarget($id); - return array("id" => $id, "type" => $type, "target" => $target); - } - - return array(); - } -// @todo end - - /** - * Before page content update - * - * Note: This one is "work in progress", currently only text paragraphs call this hook - * It is called before the page content object invokes the update procedure of - * ilPageObject - * - * @param - * @return - */ - function beforePageContentUpdate($a_page_content) - { - - } - - /** - * Copy page - * - * @param int $a_id target page id - * @param string $a_parent_type target parent type - * @param int $a_parent_id target parent id - */ - function copy($a_id, $a_parent_type = "", $a_parent_id = 0, $a_clone_mobs = false) - { - if ($a_parent_type == "") - { - $a_parent_type = $this->getParentType(); - if ($a_parent_id == 0) - { - $a_parent_id = $this->getParentId(); - } - } - - include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); - foreach (self::lookupTranslations($this->getParentType(), $this->getId()) as $l) - { - $existed = false; - $orig_page = ilPageObjectFactory::getInstance($this->getParentType(), $this->getId(), 0, $l); - if (ilPageObject::_exists($a_parent_type, $a_id, $l)) - { - $new_page_object = ilPageObjectFactory::getInstance($a_parent_type, $a_id, 0, $l); - $existed = true; - } - else - { - $new_page_object = ilPageObjectFactory::getInstance($a_parent_type, 0, 0, $l); - $new_page_object->setParentId($a_parent_id); - $new_page_object->setId($a_id); - } - $new_page_object->setXMLContent($orig_page->copyXMLContent($a_clone_mobs)); - $new_page_object->setActive($orig_page->getActive()); - $new_page_object->setActivationStart($orig_page->getActivationStart()); - $new_page_object->setActivationEnd($orig_page->getActivationEnd()); - if ($existed) - { - $new_page_object->buildDom(); - $new_page_object->update(); - } - else - { - $new_page_object->create(); - } - } - - } - - /** - * Lookup translations - * - * @param string $a_parent_type parent type - * @param int $a_id page id - * @return array language codes - */ - static function lookupTranslations($a_parent_type, $a_id) - { - global $DIC; - - $db = $DIC->database(); - - $set = $db->query("SELECT lang FROM page_object ". - " WHERE page_id = ".$db->quote($a_id, "integer"). - " AND parent_type = ".$db->quote($a_parent_type, "text") - ); - $langs = array(); - while ($rec = $db->fetchAssoc($set)) - { - $langs[] = $rec["lang"]; - } - return $langs; - } - - - /** - * Copy page to translation - * - * @param string $a_target_lang target language - */ - function copyPageToTranslation($a_target_lang) - { - $transl_page = ilPageObjectFactory::getInstance($this->getParentType(), - 0, 0, $a_target_lang); - $transl_page->setId($this->getId()); - $transl_page->setParentId($this->getParentId()); - $transl_page->setXMLContent($this->copyXMLContent()); - $transl_page->setActive($this->getActive()); - $transl_page->setActivationStart($this->getActivationStart()); - $transl_page->setActivationEnd($this->getActivationEnd()); - $transl_page->create(); - } - - //// - //// Page locking - //// - - /** - * Get page lock - */ - function getEditLock() - { - $db = $this->db; - $user = $this->user; - - $min = (int)$this->getEffectiveEditLockTime(); - if($min > 0) - { - // try to set the lock for the user - $ts = time(); - $db->manipulate("UPDATE page_object SET ". - " edit_lock_user = ".$db->quote($user->getId(), "integer").",". - " edit_lock_ts = ".$db->quote($ts, "integer"). - " WHERE (edit_lock_user = ".$db->quote($user->getId(), "integer")." OR ". - " edit_lock_ts < ".$db->quote(time() - ($min * 60), "integer").") ". - " AND page_id = ".$db->quote($this->getId(), "integer"). - " AND parent_type = ".$db->quote($this->getParentType(), "text") - ); - - $set = $db->query("SELECT edit_lock_user FROM page_object ". - " WHERE page_id = ".$db->quote($this->getId(), "integer"). - " AND parent_type = ".$db->quote($this->getParentType(), "text") - ); - $rec = $db->fetchAssoc($set); - if ($rec["edit_lock_user"] != $user->getId()) - { - return false; - } - } - - return true; - } - - /** - * Release page lock - */ - function releasePageLock() - { - $db = $this->db; - $user = $this->user; - $aset = new ilSetting("adve"); - - $min = (int) $aset->get("block_mode_minutes") ; - if ($min > 0) - { - // try to set the lock for the user - $ts = time(); - $db->manipulate("UPDATE page_object SET ". - " edit_lock_user = ".$db->quote($user->getId(), "integer").",". - " edit_lock_ts = 0". - " WHERE edit_lock_user = ".$db->quote($user->getId(), "integer"). - " AND page_id = ".$db->quote($this->getId(), "integer"). - " AND parent_type = ".$db->quote($this->getParentType(), "text") - ); - - $set = $db->query("SELECT edit_lock_user FROM page_object ". - " WHERE page_id = ".$db->quote($this->getId(), "integer"). - " AND parent_type = ".$db->quote($this->getParentType(), "text") - ); - $rec = $db->fetchAssoc($set); - if ($rec["edit_lock_user"] != $user->getId()) - { - return false; - } - } - - return true; - } - - /** - * Get edit lock info - * - * @return array info array - */ - function getEditLockInfo() - { - $db = $this->db; - - $aset = new ilSetting("adve"); - $min = (int) $aset->get("block_mode_minutes"); - - $set = $db->query("SELECT edit_lock_user, edit_lock_ts FROM page_object ". - " WHERE page_id = ".$db->quote($this->getId(), "integer"). - " AND parent_type = ".$db->quote($this->getParentType(), "text") - ); - $rec = $db->fetchAssoc($set); - $rec["edit_lock_until"] = $rec["edit_lock_ts"] + $min * 60; - - return $rec; - } - - /** - * Truncate (html) string - * - * @see http://dodona.wordpress.com/2009/04/05/how-do-i-truncate-an-html-string-without-breaking-the-html-code/ - * - * @param string $a_text - * @param int $a_length - * @param string $a_ending - * @param bool $a_exact - * @param bool $a_consider_html - * @return string - */ - public static function truncateHTML($a_text, $a_length = 100, $a_ending = '...', $a_exact = false, $a_consider_html = true) - { - include_once "Services/Utilities/classes/class.ilStr.php"; - - if ($a_consider_html) - { - // if the plain text is shorter than the maximum length, return the whole text - if(strlen(preg_replace('/<.*?>/', '', $a_text)) <= $a_length) - { - return $a_text; - } - - // splits all html-tags to scanable lines - $total_length = strlen($a_ending); - $open_tags = array(); - $truncate = ''; - preg_match_all('/(<.+?>)?([^<>]*)/s', $a_text, $lines, PREG_SET_ORDER); - foreach($lines as $line_matchings) - { - // if there is any html-tag in this line, handle it and add it (uncounted) to the output - if(!empty($line_matchings[1])) - { - // if it's an "empty element" with or without xhtml-conform closing slash - if(preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) - { - // do nothing - } - // if tag is a closing tag - else if(preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) - { - // delete tag from $open_tags list - $pos = array_search($tag_matchings[1], $open_tags); - if ($pos !== false) - { - unset($open_tags[$pos]); - } - } - // if tag is an opening tag - else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) - { - // add tag to the beginning of $open_tags list - array_unshift($open_tags, strtolower($tag_matchings[1])); - } - // add html-tag to $truncate'd text - $truncate .= $line_matchings[1]; - } - - // calculate the length of the plain text part of the line; handle entities as one character - $content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2])); - if($total_length+$content_length > $a_length) - { - // the number of characters which are left - $left = $a_length - $total_length; - $entities_length = 0; - // search for html entities - if(preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) - { - // calculate the real length of all entities in the legal range - foreach($entities[0] as $entity) - { - if($entity[1]+1-$entities_length <= $left) - { - $left--; - $entities_length += strlen($entity[0]); - } - else - { - // no more characters left - break; - } - } - } - - // $truncate .= substr($line_matchings[2], 0, $left+$entities_length); - $truncate .= ilStr::shortenText($line_matchings[2], 0, $left+$entities_length); - - // maximum lenght is reached, so get off the loop - break; - } - else - { - $truncate .= $line_matchings[2]; - $total_length += $content_length; - } - - // if the maximum length is reached, get off the loop - if($total_length >= $a_length) - { - break; - } - } - } - else - { - if(strlen($a_text) <= $a_length) - { - return $a_text; - } - else - { - // $truncate = substr($a_text, 0, $a_length - strlen($a_ending)); - $truncate = ilStr::shortenText($a_text, 0, $a_length - strlen($a_ending)); - } - } - - // THIS IS BUGGY AS IT MIGHT BREAK AN OPEN TAG AT THE END - if(!sizeof($open_tags)) - { - // if the words shouldn't be cut in the middle... - if (!$a_exact) - { - // ...search the last occurance of a space... - $spacepos = strrpos($truncate, ' '); - if($spacepos !== false) - { - // ...and cut the text in this position - // $truncate = substr($truncate, 0, $spacepos); - $truncate = ilStr::shortenText($truncate, 0, $spacepos); - } - } - } - - // add the defined ending to the text - $truncate .= $a_ending; - - if($a_consider_html) - { - // close all unclosed html-tags - foreach($open_tags as $tag) - { - $truncate .= ''; - } - } - - return $truncate; - } - - /** - * Get content templates - * - * @return array array of arrays with "id" => page id (int), "parent_type" => parent type (string), "title" => title (string) - */ - function getContentTemplates() - { - return array(); - } - - /** - * Get all pages for parent object - * - * @param string $a_parent_type Parent Type - * @param int $a_parent_id Parent ID - * @param string $a_lang language - */ - static function getLastChangeByParent($a_parent_type, $a_parent_id, $a_lang = "") - { - global $DIC; - - $db = $DIC->database(); - - $and_lang = ""; - if ($a_lang != "") - { - $and_lang = " AND lang = ".$db->quote($a_lang, "text"); - } - - $db->setLimit(1); - $q = "SELECT last_change FROM page_object ". - " WHERE parent_id = ".$db->quote($a_parent_id, "integer"). - " AND parent_type = ".$db->quote($a_parent_type, "text").$and_lang. - " ORDER BY last_change DESC"; - - $set = $db->query($q); - $rec = $db->fetchAssoc($set); - - return $rec["last_change"]; - } - - public function getEffectiveEditLockTime() - { - if($this->getPageConfig()->getEditLockSupport() == false) - { - return 0; - } - - $aset = new ilSetting("adve"); - $min = (int)$aset->get("block_mode_minutes") ; - - return $min; - } - - /** - * Get all file object ids - * - * @return array - */ - function getAllFileObjIds() - { - $file_obj_ids = array(); - - // insert inst id file item identifier entries - $xpc = xpath_new_context($this->dom); - $path = "//FileItem/Identifier"; - $res = xpath_eval($xpc, $path); - for($i = 0; $i < count($res->nodeset); $i++) - { - $file_obj_ids[] = $res->nodeset[$i]->get_attribute("Entry"); - } - unset($xpc); - return $file_obj_ids; - } - - /** - * Resolve resources - * @todo: move this into proper "afterImport" routine that calls all PC components - */ - public function resolveResources($ref_mapping) - { - include_once("./Services/COPage/classes/class.ilPCResources.php"); - ilPCResources::resolveResources($this, $ref_mapping); - } - + break; + } + + //check for PlaceHolder to remove in EditMode-keep in Layout Mode + if (!$this->getPageConfig()->getEnablePCType("PlaceHolder")) { + $sub_nodes = $curr_node->child_nodes() ; + foreach ($sub_nodes as $sub_node) { + if ($sub_node->node_name() == "PlaceHolder") { + $curr_node->unlink_node(); + } + } + } + } + + /** + * insert a content node before/after a sibling or as first child of a parent + */ + public function insertContentNode(&$a_cont_node, $a_pos, $a_mode = IL_INSERT_AFTER, $a_pcid = "") + { + // move mode into container elements is always INSERT_CHILD + $curr_node = $this->getContentNode($a_pos, $a_pcid); + $curr_name = $curr_node->node_name(); + + // @todo: try to generalize + if (($curr_name == "TableData") || ($curr_name == "PageObject") || + ($curr_name == "ListItem") || ($curr_name == "Section") + || ($curr_name == "Tab") || ($curr_name == "ContentPopup") + || ($curr_name == "GridCell")) { + $a_mode = IL_INSERT_CHILD; + } + + $hid = $curr_node->get_attribute("HierId"); + if ($hid != "") { + $a_pos = $hid; + } + + if ($a_mode != IL_INSERT_CHILD) { // determine parent hierarchical id + // of sibling at $a_pos + $pos = explode("_", $a_pos); + $target_pos = array_pop($pos); + $parent_pos = implode($pos, "_"); + } else { // if we should insert a child, $a_pos is alreade the hierarchical id + // of the parent node + $parent_pos = $a_pos; + } + + // get the parent node + if ($parent_pos != "") { + $parent_node = $this->getContentNode($parent_pos); + } else { + $parent_node = $this->getNode(); + } + + // count the parent children + $parent_childs = $parent_node->child_nodes(); + $cnt_parent_childs = count($parent_childs); + + switch ($a_mode) { + // insert new node after sibling at $a_pos + case IL_INSERT_AFTER: + //$new_node = $a_cont_obj->getNode(); + if ($succ_node = $curr_node->next_sibling()) { + $a_cont_node = $succ_node->insert_before($a_cont_node, $succ_node); + } else { + $a_cont_node = $parent_node->append_child($a_cont_node); + } + //$a_cont_obj->setNode($new_node); + break; + + case IL_INSERT_BEFORE: + //$new_node = $a_cont_obj->getNode(); + $succ_node = $this->getContentNode($a_pos); + $a_cont_node = $succ_node->insert_before($a_cont_node, $succ_node); + //$a_cont_obj->setNode($new_node); + break; + + // insert new node as first child of parent $a_pos (= $a_parent) + case IL_INSERT_CHILD: + //$new_node = $a_cont_obj->getNode(); + if ($cnt_parent_childs == 0) { + $a_cont_node = $parent_node->append_child($a_cont_node); + } else { + $a_cont_node = $parent_childs[0]->insert_before($a_cont_node, $parent_childs[0]); + } + //$a_cont_obj->setNode($new_node); + break; + } + } + + /** + * move content object from position $a_source before position $a_target + * (both hierarchical content ids) + */ + public function moveContentBefore($a_source, $a_target, $a_spcid = "", $a_tpcid = "") + { + if ($a_source == $a_target) { + return; + } + + // clone the node + $content = $this->getContentObject($a_source, $a_spcid); + $source_node = $content->getNode(); + $clone_node = $source_node->clone_node(true); + + // delete source node + $this->deleteContent($a_source, false, $a_spcid); + + // insert cloned node at target + $content->setNode($clone_node); + $this->insertContent($content, $a_target, IL_INSERT_BEFORE, $a_tpcid); + return $this->update(); + } + + /** + * move content object from position $a_source before position $a_target + * (both hierarchical content ids) + */ + public function moveContentAfter($a_source, $a_target, $a_spcid = "", $a_tpcid = "") + { + if ($a_source == $a_target) { + return; + } + + // clone the node + $content = $this->getContentObject($a_source, $a_spcid); + $source_node = $content->getNode(); + $clone_node = $source_node->clone_node(true); + + // delete source node + $this->deleteContent($a_source, false, $a_spcid); + + // insert cloned node at target + $content->setNode($clone_node); + $this->insertContent($content, $a_target, IL_INSERT_AFTER, $a_tpcid); + return $this->update(); + } + + /** + * transforms bbCode to corresponding xml + */ + // @todo: move to paragraph + public function bbCode2XML(&$a_content) + { + $a_content = preg_replace('/\[com\]/i', "", $a_content); + $a_content = preg_replace('/\[\/com\]/i', "", $a_content); + $a_content = preg_replace('/\[emp]/i', "", $a_content); + $a_content = preg_replace('/\[\/emp\]/i', "", $a_content); + $a_content = preg_replace('/\[str]/i', "", $a_content); + $a_content = preg_replace('/\[\/str\]/i', "", $a_content); + } + + /** + * inserts installation id into ids (e.g. il__pg_4 -> il_23_pg_4) + * this is needed for xml export of page + */ + public function insertInstIntoIDs($a_inst, $a_res_ref_to_obj_id = true) + { + // insert inst id into internal links + $xpc = xpath_new_context($this->dom); + $path = "//IntLink"; + $res = xpath_eval($xpc, $path); + for ($i = 0; $i < count($res->nodeset); $i++) { + $target = $res->nodeset[$i]->get_attribute("Target"); + $type = $res->nodeset[$i]->get_attribute("Type"); + + if (substr($target, 0, 4) == "il__") { + $id = substr($target, 4, strlen($target) - 4); + + // convert repository links obj_ to _ + // this leads to bug 6685. + if ($a_res_ref_to_obj_id && $type == "RepositoryItem") { + $id_arr = explode("_", $id); + + // changed due to bug 6685 + $ref_id = $id_arr[1]; + $obj_id = ilObject::_lookupObjId($id_arr[1]); + + $otype = ilObject::_lookupType($obj_id); + if ($obj_id > 0) { + // changed due to bug 6685 + // the ref_id should be used, if the content is + // imported on the same installation + // the obj_id should be used, if a different + // installation imports, but has an import_id for + // the object id. + $id = $otype . "_" . $obj_id . "_" . $ref_id; + //$id = $otype."_".$ref_id; + } + } + $new_target = "il_" . $a_inst . "_" . $id; + $res->nodeset[$i]->set_attribute("Target", $new_target); + } + } + unset($xpc); + + // @todo: move to media/fileitems/questions, ... + + // insert inst id into media aliases + $xpc = xpath_new_context($this->dom); + $path = "//MediaAlias"; + $res = xpath_eval($xpc, $path); + for ($i = 0; $i < count($res->nodeset); $i++) { + $origin_id = $res->nodeset[$i]->get_attribute("OriginId"); + if (substr($origin_id, 0, 4) == "il__") { + $new_id = "il_" . $a_inst . "_" . substr($origin_id, 4, strlen($origin_id) - 4); + $res->nodeset[$i]->set_attribute("OriginId", $new_id); + } + } + unset($xpc); + + // insert inst id file item identifier entries + $xpc = xpath_new_context($this->dom); + $path = "//FileItem/Identifier"; + $res = xpath_eval($xpc, $path); + for ($i = 0; $i < count($res->nodeset); $i++) { + $origin_id = $res->nodeset[$i]->get_attribute("Entry"); + if (substr($origin_id, 0, 4) == "il__") { + $new_id = "il_" . $a_inst . "_" . substr($origin_id, 4, strlen($origin_id) - 4); + $res->nodeset[$i]->set_attribute("Entry", $new_id); + } + } + unset($xpc); + + // insert inst id into question references + $xpc = xpath_new_context($this->dom); + $path = "//Question"; + $res = xpath_eval($xpc, $path); + for ($i = 0; $i < count($res->nodeset); $i++) { + $qref = $res->nodeset[$i]->get_attribute("QRef"); + //echo "
          setted:".$qref; + if (substr($qref, 0, 4) == "il__") { + $new_id = "il_" . $a_inst . "_" . substr($qref, 4, strlen($qref) - 4); + //echo "
          setting:".$new_id; + $res->nodeset[$i]->set_attribute("QRef", $new_id); + } + } + unset($xpc); + + // insert inst id into content snippets + $xpc = xpath_new_context($this->dom); + $path = "//ContentInclude"; + $res = xpath_eval($xpc, $path); + for ($i = 0; $i < count($res->nodeset); $i++) { + $ci = $res->nodeset[$i]->get_attribute("InstId"); + if ($ci == "") { + $res->nodeset[$i]->set_attribute("InstId", $a_inst); + } + } + unset($xpc); + } + + /** + * Check, whether (all) page content hashes are set + */ + public function checkPCIds() + { + $this->builddom(); + $mydom = $this->dom; + + $sep = $path = ""; + foreach ($this->id_elements as $el) { + $path.= $sep . "//" . $el . "[not(@PCID)]"; + $sep = " | "; + $path.= $sep . "//" . $el . "[@PCID='']"; + } + + $xpc = xpath_new_context($mydom); + $res = &xpath_eval($xpc, $path); + + if (count($res->nodeset) > 0) { + return false; + } + return true; + } + + /** + * Get all pc ids + * + * @param + * @return + */ + public function getAllPCIds() + { + $this->builddom(); + $mydom = $this->dom; + + $pcids = array(); + + $sep = $path = ""; + foreach ($this->id_elements as $el) { + $path.= $sep . "//" . $el . "[@PCID]"; + $sep = " | "; + } + + // get existing ids + $xpc = xpath_new_context($mydom); + $res = &xpath_eval($xpc, $path); + + for ($i = 0; $i < count($res->nodeset); $i++) { + $node = $res->nodeset[$i]; + $pcids[] = $node->get_attribute("PCID"); + } + return $pcids; + } + + /** + * existsPCId + * + * @param + * @return + */ + public function existsPCId($a_pc_id) + { + $this->builddom(); + $mydom = $this->dom; + + $pcids = array(); + + $sep = $path = ""; + foreach ($this->id_elements as $el) { + $path.= $sep . "//" . $el . "[@PCID='" . $a_pc_id . "']"; + $sep = " | "; + } + + // get existing ids + $xpc = xpath_new_context($mydom); + $res = &xpath_eval($xpc, $path); + return (count($res->nodeset) > 0); + } + + /** + * Generate new pc id + * + * @param array $a_pc_ids existing pc ids + * @return string new pc id + */ + public function generatePcId($a_pc_ids = false) + { + if ($a_pc_ids === false) { + $a_pc_ids = $this->getAllPCIds(); + } + $id = ilUtil::randomHash(10, $a_pc_ids); + return $id; + } + + + /** + * Insert Page Content IDs + */ + public function insertPCIds() + { + $this->builddom(); + $mydom = $this->dom; + + $pcids = $this->getAllPCIds(); + + // add missing ones + $sep = $path = ""; + foreach ($this->id_elements as $el) { + $path.= $sep . "//" . $el . "[not(@PCID)]"; + $sep = " | "; + $path.= $sep . "//" . $el . "[@PCID='']"; + $sep = " | "; + } + $xpc = xpath_new_context($mydom); + $res = &xpath_eval($xpc, $path); + + for ($i = 0; $i < count($res->nodeset); $i++) { + $node = $res->nodeset[$i]; + $id = ilUtil::randomHash(10, $pcids); + $pcids[] = $id; + //echo "setting-".$id."-"; + $res->nodeset[$i]->set_attribute("PCID", $id); + } + } + + /** + * Get page contents hashes + */ + public function getPageContentsHashes() + { + $this->builddom(); + $this->addHierIds(); + $mydom = $this->dom; + + // get existing ids + $path = "//PageContent"; + $xpc = xpath_new_context($mydom); + $res = &xpath_eval($xpc, $path); + + $hashes = array(); + require_once("./Services/COPage/classes/class.ilPCParagraph.php"); + for ($i = 0; $i < count($res->nodeset); $i++) { + $hier_id = $res->nodeset[$i]->get_attribute("HierId"); + $pc_id = $res->nodeset[$i]->get_attribute("PCID"); + $dump = $mydom->dump_node($res->nodeset[$i]); + if (($hpos = strpos($dump, ' HierId="' . $hier_id . '"')) > 0) { + $dump = substr($dump, 0, $hpos) . + substr($dump, $hpos + strlen(' HierId="' . $hier_id . '"')); + } + + $childs = $res->nodeset[$i]->child_nodes(); + $content = ""; + if ($childs[0] && $childs[0]->node_name() == "Paragraph") { + $content = $mydom->dump_node($childs[0]); + $content = substr( + $content, + strpos($content, ">") + 1, + strrpos($content, "<") - (strpos($content, ">") + 1) + ); + //var_dump($content); + $content = ilPCParagraph::xml2output($content); + //var_dump($content); + } + //$hashes[$hier_id] = + // array("PCID" => $pc_id, "hash" => md5($dump)); + $hashes[$pc_id] = + array("hier_id" => $hier_id, "hash" => md5($dump), "content" => $content); + } + + return $hashes; + } + + /** + * Get question ids + */ + // @todo: move to questions + public function getQuestionIds() + { + $this->builddom(); + $mydom = $this->dom; + + // Get question IDs + $path = "//Question"; + $xpc = xpath_new_context($mydom); + $res = &xpath_eval($xpc, $path); + + $q_ids = array(); + include_once("./Services/Link/classes/class.ilInternalLink.php"); + for ($i = 0; $i < count($res->nodeset); $i++) { + $qref = $res->nodeset[$i]->get_attribute("QRef"); + + $inst_id = ilInternalLink::_extractInstOfTarget($qref); + $obj_id = ilInternalLink::_extractObjIdOfTarget($qref); + + if (!($inst_id > 0)) { + if ($obj_id > 0) { + $q_ids[] = $obj_id; + } + } + } + return $q_ids; + } + + // @todo: move to paragraph + public function send_paragraph($par_id, $filename) + { + $this->builddom(); + + $mydom = $this->dom; + + $xpc = xpath_new_context($mydom); + + //$path = "//PageContent[position () = $par_id]/Paragraph"; + //$path = "//Paragraph[$par_id]"; + $path = "/descendant::Paragraph[position() = $par_id]"; + + $res = &xpath_eval($xpc, $path); + + if (count($res->nodeset) != 1) { + die("Should not happen"); + } + + $context_node = $res->nodeset[0]; + + // get plain text + + $childs = $context_node->child_nodes(); + + for ($j=0; $jdump_node($childs[$j]); + } + + $content = str_replace("
          ", "\n", $content); + $content = str_replace("
          ", "\n", $content); + + $plain_content = html_entity_decode($content); + + ilUtil::deliverData($plain_content, $filename); + /* + $file_type = "application/octet-stream"; + header("Content-type: ".$file_type); + header("Content-disposition: attachment; filename=\"$filename\""); + echo $plain_content;*/ + exit(); + } + + /** + * get fo page content + */ + // @todo: deprecated? + public function getFO() + { + $xml = $this->getXMLFromDom(false, true, true); + $xsl = file_get_contents("./Services/COPage/xsl/page_fo.xsl"); + $args = array( '/_xml' => $xml, '/_xsl' => $xsl ); + $xh = xslt_create(); + + $params = array(); + + + $fo = xslt_process($xh, "arg:/_xml", "arg:/_xsl", null, $args, $params); + var_dump($fo); + // do some replacements + $fo = str_replace("\n", "", $fo); + $fo = str_replace("
          ", "
          ", $fo); + $fo = str_replace("
          ", "\n", $fo); + + xslt_free($xh); + + // + $fo = substr($fo, strpos($fo, ">") + 1); + //echo "
          fo:
          ".htmlentities($fo); flush(); + return $fo; + } + + public function registerOfflineHandler($handler) + { + $this->offline_handler = $handler; + } + + /** + * Get offline handler + * + * @param + * @return + */ + public function getOfflineHandler() + { + return $this->offline_handler; + } + + + /** + * lookup whether page contains deactivated elements + */ + public static function _lookupContainsDeactivatedElements($a_id, $a_parent_type, $a_lang = "-") + { + global $DIC; + + $db = $DIC->database(); + + if ($a_lang == "") { + $a_lang = "-"; + } + + $query = "SELECT * FROM page_object WHERE page_id = " . + $db->quote($a_id, "integer") . " AND " . + " parent_type = " . $db->quote($a_parent_type, "text") . " AND " . + " lang = " . $db->quote($a_lang, "text") . " AND " . + " inactive_elements = " . $db->quote(1, "integer"); + $obj_set = $db->query($query); + + if ($obj_rec = $obj_set->fetchRow(ilDBConstants::FETCHMODE_ASSOC)) { + return true; + } + + return false; + } + + /** + * Check whether content contains deactivated elements + * + * @param + * @return + */ + public function containsDeactivatedElements($a_content) + { + if (strpos($a_content, " Enabled=\"False\"")) { + return true; + } + return false; + } + + /** + * Get History Entries + */ + public function getHistoryEntries() + { + $db = $this->db; + + $h_query = "SELECT * FROM page_history " . + " WHERE page_id = " . $db->quote($this->getId(), "integer") . + " AND parent_type = " . $db->quote($this->getParentType(), "text") . + " AND lang = " . $db->quote($this->getLanguage(), "text") . + " ORDER BY hdate DESC"; + + $hset = $db->query($h_query); + $hentries = array(); + + while ($hrec = $db->fetchAssoc($hset)) { + $hrec["sortkey"] = (int) $hrec["nr"]; + $hrec["user"] = (int) $hrec["user_id"]; + $hentries[] = $hrec; + } + //var_dump($hentries); + return $hentries; + } + + /** + * Get History Entry + */ + public function getHistoryEntry($a_old_nr) + { + $db = $this->db; + + $res = $db->queryF( + "SELECT * FROM page_history " . + " WHERE page_id = %s " . + " AND parent_type = %s " . + " AND nr = %s" . + " AND lang = %s", + array("integer", "text", "integer", "text"), + array($this->getId(), $this->getParentType(), $a_old_nr, $this->getLanguage()) + ); + if ($hrec = $db->fetchAssoc($res)) { + return $hrec; + } + + return false; + } + + + /** + * Get information about a history entry, its predecessor and + * its successor. + * + * @param int $a_nr Nr of history entry + */ + public function getHistoryInfo($a_nr) + { + $db = $this->db; + + // determine previous entry + $and_nr = ($a_nr > 0) + ? " AND nr < " . $db->quote((int) $a_nr, "integer") + : ""; + $res = $db->query("SELECT MAX(nr) mnr FROM page_history " . + " WHERE page_id = " . $db->quote($this->getId(), "integer") . + " AND parent_type = " . $db->quote($this->getParentType(), "text") . + " AND lang = " . $db->quote($this->getLanguage(), "text") . + $and_nr); + $row = $db->fetchAssoc($res); + if ($row["mnr"] > 0) { + $res = $db->query("SELECT * FROM page_history " . + " WHERE page_id = " . $db->quote($this->getId(), "integer") . + " AND parent_type = " . $db->quote($this->getParentType(), "text") . + " AND lang = " . $db->quote($this->getLanguage(), "text") . + " AND nr = " . $db->quote((int) $row["mnr"], "integer")); + $row = $db->fetchAssoc($res); + $ret["previous"] = $row; + } + + // determine next entry + $res = $db->query("SELECT MIN(nr) mnr FROM page_history " . + " WHERE page_id = " . $db->quote($this->getId(), "integer") . + " AND parent_type = " . $db->quote($this->getParentType(), "text") . + " AND lang = " . $db->quote($this->getLanguage(), "text") . + " AND nr > " . $db->quote((int) $a_nr, "integer")); + $row = $db->fetchAssoc($res); + if ($row["mnr"] > 0) { + $res = $db->query("SELECT * FROM page_history " . + " WHERE page_id = " . $db->quote($this->getId(), "integer") . + " AND parent_type = " . $db->quote($this->getParentType(), "text") . + " AND lang = " . $db->quote($this->getLanguage(), "text") . + " AND nr = " . $db->quote((int) $row["mnr"], "integer")); + $row = $db->fetchAssoc($res); + $ret["next"] = $row; + } + + // current + if ($a_nr > 0) { + $res = $db->query("SELECT * FROM page_history " . + " WHERE page_id = " . $db->quote($this->getId(), "integer") . + " AND parent_type = " . $db->quote($this->getParentType(), "text") . + " AND lang = " . $db->quote($this->getLanguage(), "text") . + " AND nr = " . $db->quote((int) $a_nr, "integer")); + $row = $db->fetchAssoc($res); + } else { + $res = $db->query("SELECT page_id, last_change hdate, parent_type, parent_id, last_change_user user_id, content, lang FROM page_object " . + " WHERE page_id = " . $db->quote($this->getId(), "integer") . + " AND parent_type = " . $db->quote($this->getParentType(), "text") . + " AND lang = " . $db->quote($this->getLanguage(), "text")); + $row = $db->fetchAssoc($res); + } + $ret["current"] = $row; + + return $ret; + } + + public function addChangeDivClasses($a_hashes) + { + $xpc = xpath_new_context($this->dom); + $path = "/*[1]"; + $res = xpath_eval($xpc, $path); + $rnode = $res->nodeset[0]; + + //echo "A"; + foreach ($a_hashes as $pc_id => $h) { + //echo "B"; + if ($h["change"] != "") { + $dc_node = $this->dom->create_element("DivClass"); + $dc_node->set_attribute("HierId", $h["hier_id"]); + $dc_node->set_attribute("Class", "ilEdit" . $h["change"]); + $dc_node = $rnode->append_child($dc_node); + } + } + //echo "





          ".htmlentities($this->getXMLFromDom()); + } + + /** + * Compares to revisions of the page + * + * @param int $a_left Nr of first revision + * @param int $a_right Nr of second revision + */ + public function compareVersion($a_left, $a_right) + { + // get page objects + include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); + $l_page = ilPageObjectFactory::getInstance($this->getParentType(), $this->getId(), $a_left); + $r_page = ilPageObjectFactory::getInstance($this->getParentType(), $this->getId(), $a_right); + + $l_hashes = $l_page->getPageContentsHashes(); + $r_hashes = $r_page->getPageContentsHashes(); + // determine all deleted and changed page elements + foreach ($l_hashes as $pc_id => $h) { + if (!isset($r_hashes[$pc_id])) { + $l_hashes[$pc_id]["change"] = "Deleted"; + } else { + if ($l_hashes[$pc_id]["hash"] != $r_hashes[$pc_id]["hash"]) { + $l_hashes[$pc_id]["change"] = "Modified"; + $r_hashes[$pc_id]["change"] = "Modified"; + + include_once("./Services/COPage/mediawikidiff/class.WordLevelDiff.php"); + // if modified element is a paragraph, highlight changes + if ($l_hashes[$pc_id]["content"] != "" && + $r_hashes[$pc_id]["content"] != "") { + $new_left = str_replace("\n", "
          ", $l_hashes[$pc_id]["content"]); + $new_right = str_replace("\n", "
          ", $r_hashes[$pc_id]["content"]); + $wldiff = new WordLevelDiff( + array($new_left), + array($new_right) + ); + $new_left = $wldiff->orig(); + $new_right = $wldiff->closing(); + $l_page->setParagraphContent($l_hashes[$pc_id]["hier_id"], $new_left[0]); + $r_page->setParagraphContent($l_hashes[$pc_id]["hier_id"], $new_right[0]); + } + } + } + } + + // determine all new paragraphs + foreach ($r_hashes as $pc_id => $h) { + if (!isset($l_hashes[$pc_id])) { + $r_hashes[$pc_id]["change"] = "New"; + } + } + $l_page->addChangeDivClasses($l_hashes); + $r_page->addChangeDivClasses($r_hashes); + + return array("l_page" => $l_page, "r_page" => $r_page, + "l_changes" => $l_hashes, "r_changes" => $r_hashes); + } + + /** + * Increase view cnt + */ + public function increaseViewCnt() + { + $db = $this->db; + + $db->manipulate("UPDATE page_object " . + " SET view_cnt = view_cnt + 1 " . + " WHERE page_id = " . $db->quote($this->getId(), "integer") . + " AND parent_type = " . $db->quote($this->getParentType(), "text") . + " AND lang = " . $db->quote($this->getLanguage(), "text")); + } + + /** + * Get recent pages changes for parent object. + * + * @param string $a_parent_type Parent Type + * @param int $a_parent_id Parent ID + * @param int $a_period Time Period + */ + public static function getRecentChanges($a_parent_type, $a_parent_id, $a_period = 30, $a_lang = "") + { + global $DIC; + + $db = $DIC->database(); + + $and_lang = ""; + if ($a_lang != "") { + $and_lang = " AND lang = " . $db->quote($a_lang, "text"); + } + + $page_changes = array(); + $limit_ts = date('Y-m-d H:i:s', time() - ($a_period * 24 * 60 * 60)); + $q = "SELECT * FROM page_object " . + " WHERE parent_id = " . $db->quote($a_parent_id, "integer") . + " AND parent_type = " . $db->quote($a_parent_type, "text") . + " AND last_change >= " . $db->quote($limit_ts, "timestamp") . $and_lang; + // " AND (TO_DAYS(now()) - TO_DAYS(last_change)) <= ".((int)$a_period); + $set = $db->query($q); + while ($page = $db->fetchAssoc($set)) { + $page_changes[] = array( + "date" => $page["last_change"], + "id" => $page["page_id"], + "lang" => $page["lang"], + "type" => "page", + "user" => $page["last_change_user"]); + } + + $and_str = ""; + if ($a_period > 0) { + $limit_ts = date('Y-m-d H:i:s', time() - ($a_period * 24 * 60 * 60)); + $and_str = " AND hdate >= " . $db->quote($limit_ts, "timestamp") . " "; + } + + $q = "SELECT * FROM page_history " . + " WHERE parent_id = " . $db->quote($a_parent_id, "integer") . + " AND parent_type = " . $db->quote($a_parent_type, "text") . + $and_str . $and_lang; + $set = $db->query($q); + while ($page = $db->fetchAssoc($set)) { + $page_changes[] = array( + "date" => $page["hdate"], + "id" => $page["page_id"], + "lang" => $page["lang"], + "type" => "hist", + "nr" => $page["nr"], + "user" => $page["user_id"]); + } + + $page_changes = ilUtil::sortArray($page_changes, "date", "desc"); + + return $page_changes; + } + + /** + * Get all pages for parent object + * + * @param string $a_parent_type + * @param int $a_parent_id + * @param string $a_lang + * @return array + */ + public static function getAllPages($a_parent_type, $a_parent_id, $a_lang = "-") + { + global $DIC; + + $db = $DIC->database(); + + $and_lang = ""; + if ($a_lang != "") { + $and_lang = " AND lang = " . $db->quote($a_lang, "text"); + } + + $q = "SELECT * FROM page_object " . + " WHERE parent_id = " . $db->quote($a_parent_id, "integer") . + " AND parent_type = " . $db->quote($a_parent_type, "text") . $and_lang; + $set = $db->query($q); + $pages = array(); + while ($page = $db->fetchAssoc($set)) { + $key_add = ($a_lang == "") + ? ":" . $page["lang"] + : ""; + $pages[$page["page_id"] . $key_add] = array( + "date" => $page["last_change"], + "id" => $page["page_id"], + "lang" => $page["lang"], + "user" => $page["last_change_user"]); + } + + return $pages; + } + + /** + * Get new pages. + * + * @param string $a_parent_type Parent Type + * @param int $a_parent_id Parent ID + */ + public static function getNewPages($a_parent_type, $a_parent_id, $a_lang = "-") + { + global $DIC; + + $db = $DIC->database(); + + $and_lang = ""; + if ($a_lang != "") { + $and_lang = " AND lang = " . $db->quote($a_lang, "text"); + } + + $pages = array(); + + $q = "SELECT * FROM page_object " . + " WHERE parent_id = " . $db->quote($a_parent_id, "integer") . + " AND parent_type = " . $db->quote($a_parent_type, "text") . $and_lang . + " ORDER BY created DESC"; + $set = $db->query($q); + while ($page = $db->fetchAssoc($set)) { + if ($page["created"] != "") { + $pages[] = array( + "created" => $page["created"], + "id" => $page["page_id"], + "lang" => $page["lang"], + "user" => $page["create_user"], + ); + } + } + + return $pages; + } + + /** + * Get all contributors for parent object + * + * @param string $a_parent_type Parent Type + * @param int $a_parent_id Parent ID + */ + public static function getParentObjectContributors($a_parent_type, $a_parent_id, $a_lang = "-") + { + global $DIC; + + $db = $DIC->database(); + + $and_lang = ""; + if ($a_lang != "") { + $and_lang = " AND lang = " . $db->quote($a_lang, "text"); + } + + $contributors = array(); + $set = $db->queryF( + "SELECT last_change_user, lang, page_id FROM page_object " . + " WHERE parent_id = %s AND parent_type = %s " . + " AND last_change_user != %s" . $and_lang, + array("integer", "text", "integer"), + array($a_parent_id, $a_parent_type, 0) + ); + + while ($page = $db->fetchAssoc($set)) { + if ($a_lang == "") { + $contributors[$page["last_change_user"]][$page["page_id"]][$page["lang"]] = 1; + } else { + $contributors[$page["last_change_user"]][$page["page_id"]] = 1; + } + } + + $set = $db->queryF( + "SELECT count(*) as cnt, lang, page_id, user_id FROM page_history " . + " WHERE parent_id = %s AND parent_type = %s AND user_id != %s " . $and_lang . + " GROUP BY page_id, user_id, lang ", + array("integer", "text", "integer"), + array($a_parent_id, $a_parent_type, 0) + ); + while ($hpage = $db->fetchAssoc($set)) { + if ($a_lang == "") { + $contributors[$hpage["user_id"]][$hpage["page_id"]][$hpage["lang"]] = + $contributors[$hpage["user_id"]][$hpage["page_id"]][$hpage["lang"]] + $hpage["cnt"]; + } else { + $contributors[$hpage["user_id"]][$hpage["page_id"]] = + $contributors[$hpage["user_id"]][$hpage["page_id"]] + $hpage["cnt"]; + } + } + + $c = array(); + foreach ($contributors as $k => $co) { + if (ilObject::_lookupType($k) == "usr") { + $name = ilObjUser::_lookupName($k); + $c[] = array("user_id" => $k, "pages" => $co, + "lastname" => $name["lastname"], "firstname" => $name["firstname"]); + } + } + + return $c; + } + + /** + * Get all contributors for parent object + * + * @param string $a_parent_type Parent Type + * @param int $a_parent_id Parent ID + */ + public static function getPageContributors($a_parent_type, $a_page_id, $a_lang = "-") + { + global $DIC; + + $db = $DIC->database(); + + $and_lang = ""; + if ($a_lang != "") { + $and_lang = " AND lang = " . $db->quote($a_lang, "text"); + } + + $contributors = array(); + $set = $db->queryF( + "SELECT last_change_user, lang FROM page_object " . + " WHERE page_id = %s AND parent_type = %s " . + " AND last_change_user != %s" . $and_lang, + array("integer", "text", "integer"), + array($a_page_id, $a_parent_type, 0) + ); + + while ($page = $db->fetchAssoc($set)) { + if ($a_lang == "") { + $contributors[$page["last_change_user"]][$page["lang"]] = 1; + } else { + $contributors[$page["last_change_user"]] = 1; + } + } + + $set = $db->queryF( + "SELECT count(*) as cnt, lang, page_id, user_id FROM page_history " . + " WHERE page_id = %s AND parent_type = %s AND user_id != %s " . $and_lang . + " GROUP BY user_id, page_id, lang ", + array("integer", "text", "integer"), + array($a_page_id, $a_parent_type, 0) + ); + while ($hpage = $db->fetchAssoc($set)) { + if ($a_lang == "") { + $contributors[$hpage["user_id"]][$page["lang"]] = + $contributors[$hpage["user_id"]][$page["lang"]] + $hpage["cnt"]; + } else { + $contributors[$hpage["user_id"]] = + $contributors[$hpage["user_id"]] + $hpage["cnt"]; + } + } + + $c = array(); + foreach ($contributors as $k => $co) { + include_once "Services/User/classes/class.ilObjUser.php"; + $name = ilObjUser::_lookupName($k); + $c[] = array("user_id" => $k, "pages" => $co, + "lastname" => $name["lastname"], "firstname" => $name["firstname"]); + } + + return $c; + } + + /** + * Write rendered content + */ + public function writeRenderedContent($a_content, $a_md5) + { + global $DIC; + + $db = $DIC->database(); + + $db->update("page_object", array( + "rendered_content" => array("clob", $a_content), + "render_md5" => array("text", $a_md5), + "rendered_time" => array("timestamp", ilUtil::now()) + ), array( + "page_id" => array("integer", $this->getId()), + "lang" => array("text", $this->getLanguage()), + "parent_type" => array("text", $this->getParentType()) + )); + } + + /** + * Get all pages for parent object that contain internal links + * + * @param string $a_parent_type Parent Type + * @param int $a_parent_id Parent ID + * @param int $a_period Time Period + */ + public static function getPagesWithLinks($a_parent_type, $a_parent_id, $a_lang = "-") + { + global $DIC; + + $db = $DIC->database(); + + $and_lang = ""; + if ($a_lang != "") { + $and_lang = " AND lang = " . $db->quote($a_lang, "text"); + } + + $q = "SELECT * FROM page_object " . + " WHERE parent_id = " . $db->quote($a_parent_id, "integer") . + " AND parent_type = " . $db->quote($a_parent_type, "text") . + " AND int_links = " . $db->quote(1, "integer") . $and_lang; + $set = $db->query($q); + $pages = array(); + while ($page = $db->fetchAssoc($set)) { + $key_add = ($a_lang == "") + ? ":" . $page["lang"] + : ""; + $pages[$page["page_id"] . $key_add] = array( + "date" => $page["last_change"], + "id" => $page["page_id"], + "lang" => $page["lang"], + "user" => $page["last_change_user"]); + } + + return $pages; + } + + /** + * Check whether content contains internal links + * + * @param + * @return + */ + public function containsIntLinks($a_content) + { + if (strpos($a_content, "IntLink")) { + return true; + } + return false; + } + + /** + * Perform automatic modifications (may be overwritten by sub classes) + */ + public function performAutomaticModifications() + { + } + + /** + * Save initial opened content + * + * @param + */ + // @todo begin: generalize + public function saveInitialOpenedContent($a_type, $a_id, $a_target) + { + $this->buildDom(); + + $link_type = ""; + + switch ($a_type) { + case "media": + $link_type = "MediaObject"; + $a_id = "il__mob_" . $a_id; + break; + + case "page": + $link_type = "PageObject"; + $a_id = "il__pg_" . $a_id; + break; + + case "term": + $link_type = "GlossaryItem"; + $a_id = "il__git_" . $a_id; + $a_target = "Glossary"; + break; + } + + // if type or id missing -> delete InitOpenedContent, if existing + if ($link_type == "" || $a_id == "") { + $xpc = xpath_new_context($this->dom); + $path = "//PageObject/InitOpenedContent"; + $res = xpath_eval($xpc, $path); + if (count($res->nodeset) > 0) { + $res->nodeset[0]->unlink_node($res->nodeset[0]); + } + } else { + $xpc = xpath_new_context($this->dom); + $path = "//PageObject/InitOpenedContent"; + $res = xpath_eval($xpc, $path); + if (count($res->nodeset) > 0) { + $init_node = $res->nodeset[0]; + $childs = $init_node->child_nodes(); + for ($i = 0; $i < count($childs); $i++) { + if ($childs[$i]->node_name() == "IntLink") { + $il_node = $childs[$i]; + } + } + } else { + $path = "//PageObject"; + $res = xpath_eval($xpc, $path); + $page_node = $res->nodeset[0]; + $init_node = $this->dom->create_element("InitOpenedContent"); + $init_node = $page_node->append_child($init_node); + $il_node = $this->dom->create_element("IntLink"); + $il_node = $init_node->append_child($il_node); + } + $il_node->set_attribute("Target", $a_id); + $il_node->set_attribute("Type", $link_type); + $il_node->set_attribute("TargetFrame", $a_target); + } + + $this->update(); + } + + + /** + * Get initial opened content + * + * @param + */ + public function getInitialOpenedContent() + { + $this->buildDom(); + + $xpc = xpath_new_context($this->dom); + $path = "//PageObject/InitOpenedContent"; + $res = xpath_eval($xpc, $path); + $il_node = null; + if (count($res->nodeset) > 0) { + $init_node = $res->nodeset[0]; + $childs = $init_node->child_nodes(); + for ($i = 0; $i < count($childs); $i++) { + if ($childs[$i]->node_name() == "IntLink") { + $il_node = $childs[$i]; + } + } + } + if (!is_null($il_node)) { + $id = $il_node->get_attribute("Target"); + $link_type = $il_node->get_attribute("Type"); + $target = $il_node->get_attribute("TargetFrame"); + + switch ($link_type) { + case "MediaObject": + $type = "media"; + break; + + case "PageObject": + $type = "page"; + break; + + case "GlossaryItem": + $type = "term"; + break; + } + include_once("./Services/Link/classes/class.ilInternalLink.php"); + $id = ilInternalLink::_extractObjIdOfTarget($id); + return array("id" => $id, "type" => $type, "target" => $target); + } + + return array(); + } + // @todo end + + /** + * Before page content update + * + * Note: This one is "work in progress", currently only text paragraphs call this hook + * It is called before the page content object invokes the update procedure of + * ilPageObject + * + * @param + * @return + */ + public function beforePageContentUpdate($a_page_content) + { + } + + /** + * Copy page + * + * @param int $a_id target page id + * @param string $a_parent_type target parent type + * @param int $a_parent_id target parent id + */ + public function copy($a_id, $a_parent_type = "", $a_parent_id = 0, $a_clone_mobs = false) + { + if ($a_parent_type == "") { + $a_parent_type = $this->getParentType(); + if ($a_parent_id == 0) { + $a_parent_id = $this->getParentId(); + } + } + + include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); + foreach (self::lookupTranslations($this->getParentType(), $this->getId()) as $l) { + $existed = false; + $orig_page = ilPageObjectFactory::getInstance($this->getParentType(), $this->getId(), 0, $l); + if (ilPageObject::_exists($a_parent_type, $a_id, $l)) { + $new_page_object = ilPageObjectFactory::getInstance($a_parent_type, $a_id, 0, $l); + $existed = true; + } else { + $new_page_object = ilPageObjectFactory::getInstance($a_parent_type, 0, 0, $l); + $new_page_object->setParentId($a_parent_id); + $new_page_object->setId($a_id); + } + $new_page_object->setXMLContent($orig_page->copyXMLContent($a_clone_mobs)); + $new_page_object->setActive($orig_page->getActive()); + $new_page_object->setActivationStart($orig_page->getActivationStart()); + $new_page_object->setActivationEnd($orig_page->getActivationEnd()); + if ($existed) { + $new_page_object->buildDom(); + $new_page_object->update(); + } else { + $new_page_object->create(); + } + } + } + + /** + * Lookup translations + * + * @param string $a_parent_type parent type + * @param int $a_id page id + * @return array language codes + */ + public static function lookupTranslations($a_parent_type, $a_id) + { + global $DIC; + + $db = $DIC->database(); + + $set = $db->query( + "SELECT lang FROM page_object " . + " WHERE page_id = " . $db->quote($a_id, "integer") . + " AND parent_type = " . $db->quote($a_parent_type, "text") + ); + $langs = array(); + while ($rec = $db->fetchAssoc($set)) { + $langs[] = $rec["lang"]; + } + return $langs; + } + + + /** + * Copy page to translation + * + * @param string $a_target_lang target language + */ + public function copyPageToTranslation($a_target_lang) + { + $transl_page = ilPageObjectFactory::getInstance( + $this->getParentType(), + 0, + 0, + $a_target_lang + ); + $transl_page->setId($this->getId()); + $transl_page->setParentId($this->getParentId()); + $transl_page->setXMLContent($this->copyXMLContent()); + $transl_page->setActive($this->getActive()); + $transl_page->setActivationStart($this->getActivationStart()); + $transl_page->setActivationEnd($this->getActivationEnd()); + $transl_page->create(); + } + + //// + //// Page locking + //// + + /** + * Get page lock + */ + public function getEditLock() + { + $db = $this->db; + $user = $this->user; + + $min = (int) $this->getEffectiveEditLockTime(); + if ($min > 0) { + // try to set the lock for the user + $ts = time(); + $db->manipulate( + "UPDATE page_object SET " . + " edit_lock_user = " . $db->quote($user->getId(), "integer") . "," . + " edit_lock_ts = " . $db->quote($ts, "integer") . + " WHERE (edit_lock_user = " . $db->quote($user->getId(), "integer") . " OR " . + " edit_lock_ts < " . $db->quote(time() - ($min * 60), "integer") . ") " . + " AND page_id = " . $db->quote($this->getId(), "integer") . + " AND parent_type = " . $db->quote($this->getParentType(), "text") + ); + + $set = $db->query( + "SELECT edit_lock_user FROM page_object " . + " WHERE page_id = " . $db->quote($this->getId(), "integer") . + " AND parent_type = " . $db->quote($this->getParentType(), "text") + ); + $rec = $db->fetchAssoc($set); + if ($rec["edit_lock_user"] != $user->getId()) { + return false; + } + } + + return true; + } + + /** + * Release page lock + */ + public function releasePageLock() + { + $db = $this->db; + $user = $this->user; + $aset = new ilSetting("adve"); + + $min = (int) $aset->get("block_mode_minutes") ; + if ($min > 0) { + // try to set the lock for the user + $ts = time(); + $db->manipulate( + "UPDATE page_object SET " . + " edit_lock_user = " . $db->quote($user->getId(), "integer") . "," . + " edit_lock_ts = 0" . + " WHERE edit_lock_user = " . $db->quote($user->getId(), "integer") . + " AND page_id = " . $db->quote($this->getId(), "integer") . + " AND parent_type = " . $db->quote($this->getParentType(), "text") + ); + + $set = $db->query( + "SELECT edit_lock_user FROM page_object " . + " WHERE page_id = " . $db->quote($this->getId(), "integer") . + " AND parent_type = " . $db->quote($this->getParentType(), "text") + ); + $rec = $db->fetchAssoc($set); + if ($rec["edit_lock_user"] != $user->getId()) { + return false; + } + } + + return true; + } + + /** + * Get edit lock info + * + * @return array info array + */ + public function getEditLockInfo() + { + $db = $this->db; + + $aset = new ilSetting("adve"); + $min = (int) $aset->get("block_mode_minutes"); + + $set = $db->query( + "SELECT edit_lock_user, edit_lock_ts FROM page_object " . + " WHERE page_id = " . $db->quote($this->getId(), "integer") . + " AND parent_type = " . $db->quote($this->getParentType(), "text") + ); + $rec = $db->fetchAssoc($set); + $rec["edit_lock_until"] = $rec["edit_lock_ts"] + $min * 60; + + return $rec; + } + + /** + * Truncate (html) string + * + * @see http://dodona.wordpress.com/2009/04/05/how-do-i-truncate-an-html-string-without-breaking-the-html-code/ + * + * @param string $a_text + * @param int $a_length + * @param string $a_ending + * @param bool $a_exact + * @param bool $a_consider_html + * @return string + */ + public static function truncateHTML($a_text, $a_length = 100, $a_ending = '...', $a_exact = false, $a_consider_html = true) + { + include_once "Services/Utilities/classes/class.ilStr.php"; + + if ($a_consider_html) { + // if the plain text is shorter than the maximum length, return the whole text + if (strlen(preg_replace('/<.*?>/', '', $a_text)) <= $a_length) { + return $a_text; + } + + // splits all html-tags to scanable lines + $total_length = strlen($a_ending); + $open_tags = array(); + $truncate = ''; + preg_match_all('/(<.+?>)?([^<>]*)/s', $a_text, $lines, PREG_SET_ORDER); + foreach ($lines as $line_matchings) { + // if there is any html-tag in this line, handle it and add it (uncounted) to the output + if (!empty($line_matchings[1])) { + // if it's an "empty element" with or without xhtml-conform closing slash + if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) { + // do nothing + } + // if tag is a closing tag + elseif (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) { + // delete tag from $open_tags list + $pos = array_search($tag_matchings[1], $open_tags); + if ($pos !== false) { + unset($open_tags[$pos]); + } + } + // if tag is an opening tag + elseif (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) { + // add tag to the beginning of $open_tags list + array_unshift($open_tags, strtolower($tag_matchings[1])); + } + // add html-tag to $truncate'd text + $truncate .= $line_matchings[1]; + } + + // calculate the length of the plain text part of the line; handle entities as one character + $content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2])); + if ($total_length+$content_length > $a_length) { + // the number of characters which are left + $left = $a_length - $total_length; + $entities_length = 0; + // search for html entities + if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) { + // calculate the real length of all entities in the legal range + foreach ($entities[0] as $entity) { + if ($entity[1]+1-$entities_length <= $left) { + $left--; + $entities_length += strlen($entity[0]); + } else { + // no more characters left + break; + } + } + } + + // $truncate .= substr($line_matchings[2], 0, $left+$entities_length); + $truncate .= ilStr::shortenText($line_matchings[2], 0, $left+$entities_length); + + // maximum lenght is reached, so get off the loop + break; + } else { + $truncate .= $line_matchings[2]; + $total_length += $content_length; + } + + // if the maximum length is reached, get off the loop + if ($total_length >= $a_length) { + break; + } + } + } else { + if (strlen($a_text) <= $a_length) { + return $a_text; + } else { + // $truncate = substr($a_text, 0, $a_length - strlen($a_ending)); + $truncate = ilStr::shortenText($a_text, 0, $a_length - strlen($a_ending)); + } + } + + // THIS IS BUGGY AS IT MIGHT BREAK AN OPEN TAG AT THE END + if (!sizeof($open_tags)) { + // if the words shouldn't be cut in the middle... + if (!$a_exact) { + // ...search the last occurance of a space... + $spacepos = strrpos($truncate, ' '); + if ($spacepos !== false) { + // ...and cut the text in this position + // $truncate = substr($truncate, 0, $spacepos); + $truncate = ilStr::shortenText($truncate, 0, $spacepos); + } + } + } + + // add the defined ending to the text + $truncate .= $a_ending; + + if ($a_consider_html) { + // close all unclosed html-tags + foreach ($open_tags as $tag) { + $truncate .= ''; + } + } + + return $truncate; + } + + /** + * Get content templates + * + * @return array array of arrays with "id" => page id (int), "parent_type" => parent type (string), "title" => title (string) + */ + public function getContentTemplates() + { + return array(); + } + + /** + * Get all pages for parent object + * + * @param string $a_parent_type Parent Type + * @param int $a_parent_id Parent ID + * @param string $a_lang language + */ + public static function getLastChangeByParent($a_parent_type, $a_parent_id, $a_lang = "") + { + global $DIC; + + $db = $DIC->database(); + + $and_lang = ""; + if ($a_lang != "") { + $and_lang = " AND lang = " . $db->quote($a_lang, "text"); + } + + $db->setLimit(1); + $q = "SELECT last_change FROM page_object " . + " WHERE parent_id = " . $db->quote($a_parent_id, "integer") . + " AND parent_type = " . $db->quote($a_parent_type, "text") . $and_lang . + " ORDER BY last_change DESC"; + + $set = $db->query($q); + $rec = $db->fetchAssoc($set); + + return $rec["last_change"]; + } + + public function getEffectiveEditLockTime() + { + if ($this->getPageConfig()->getEditLockSupport() == false) { + return 0; + } + + $aset = new ilSetting("adve"); + $min = (int) $aset->get("block_mode_minutes") ; + + return $min; + } + + /** + * Get all file object ids + * + * @return array + */ + public function getAllFileObjIds() + { + $file_obj_ids = array(); + + // insert inst id file item identifier entries + $xpc = xpath_new_context($this->dom); + $path = "//FileItem/Identifier"; + $res = xpath_eval($xpc, $path); + for ($i = 0; $i < count($res->nodeset); $i++) { + $file_obj_ids[] = $res->nodeset[$i]->get_attribute("Entry"); + } + unset($xpc); + return $file_obj_ids; + } + + /** + * Resolve resources + * @todo: move this into proper "afterImport" routine that calls all PC components + */ + public function resolveResources($ref_mapping) + { + include_once("./Services/COPage/classes/class.ilPCResources.php"); + ilPCResources::resolveResources($this, $ref_mapping); + } } -?> \ No newline at end of file diff --git a/Services/COPage/classes/class.ilPageObjectFactory.php b/Services/COPage/classes/class.ilPageObjectFactory.php index cb41f00cac04ed4eafc462b178ad7fbd9b804af7..7ccc444ddc7d1ee61e78a586c4adf98638d183eb 100644 --- a/Services/COPage/classes/class.ilPageObjectFactory.php +++ b/Services/COPage/classes/class.ilPageObjectFactory.php @@ -3,7 +3,7 @@ /* Copyright (c) 1998-2012 ILIAS open source, Extended GPL, see docs/LICENSE */ /** - * Page object factory + * Page object factory * * @author Alex Killing * @version $Id$ @@ -11,86 +11,82 @@ */ class ilPageObjectFactory { - /** - * Get page object instance - * - * @param string $a_parent_type parent type - * @param int $a_id page id - * @param int $a_old_nr history number of page - * @param string $a_lang language - * @return object - */ - static function getInstance($a_parent_type, $a_id = 0, $a_old_nr = 0, $a_lang = "-") - { - include_once("./Services/COPage/classes/class.ilCOPageObjDef.php"); - $def = ilCOPageObjDef::getDefinitionByParentType($a_parent_type); - $class = $def["class_name"]; - $path = "./".$def["component"]."/".$def["directory"]."/class.".$class.".php"; - include_once($path); - $obj = new $class($a_id , $a_old_nr, $a_lang); - - return $obj; - } - - /** - * Get page config instance - * - * @param string $a_parent_type parent type - * @return object - */ - static function getConfigInstance($a_parent_type) - { - include_once("./Services/COPage/classes/class.ilCOPageObjDef.php"); - $def = ilCOPageObjDef::getDefinitionByParentType($a_parent_type); - $class = $def["class_name"]."Config"; - $path = "./".$def["component"]."/".$def["directory"]."/class.".$class.".php"; - include_once($path); - $cfg = new $class(); - - return $cfg; - } - - /** - * Get page object GUI instance (currently unfinished, problems e.g. ilBlogPosting constructor) - * - * @param string $a_parent_type parent type - * @param int $a_id page id - * @param int $a_old_nr history number of page - * @param string $a_lang language - * @return object - */ - /* static function getGUIInstance($a_parent_type, $a_id = 0, $a_old_nr = 0, $a_lang = "-") - { - include_once("./Services/COPage/classes/class.ilCOPageObjDef.php"); - $def = ilCOPageObjDef::getDefinitionByParentType($a_parent_type); - $class = $def["class_name"]."GUI"; - $path = "./".$def["component"]."/".$def["directory"]."/class.".$class.".php"; - include_once($path); - if (in_array($a_parent_type, array("cont", "cstr", "lm"))) - { - $obj = new $class($a_id , $a_old_nr, $a_lang); - } - else if (in_array($a_parent_type, array("impr"))) - { - $obj = new $class(); - } - else if (in_array($a_parent_type, array("stys"))) - { - $obj = new $class($a_parent_type, $a_id, $a_old_nr); - } - else if (in_array($a_parent_type, array("blog"))) - { - $obj = new $class($a_parent_type, $a_id, $a_old_nr); - } - else - { - $obj = new $class($a_id , $a_old_nr); - } - - return $obj; - }*/ + /** + * Get page object instance + * + * @param string $a_parent_type parent type + * @param int $a_id page id + * @param int $a_old_nr history number of page + * @param string $a_lang language + * @return object + */ + public static function getInstance($a_parent_type, $a_id = 0, $a_old_nr = 0, $a_lang = "-") + { + include_once("./Services/COPage/classes/class.ilCOPageObjDef.php"); + $def = ilCOPageObjDef::getDefinitionByParentType($a_parent_type); + $class = $def["class_name"]; + $path = "./" . $def["component"] . "/" . $def["directory"] . "/class." . $class . ".php"; + include_once($path); + $obj = new $class($a_id, $a_old_nr, $a_lang); + + return $obj; + } + + /** + * Get page config instance + * + * @param string $a_parent_type parent type + * @return object + */ + public static function getConfigInstance($a_parent_type) + { + include_once("./Services/COPage/classes/class.ilCOPageObjDef.php"); + $def = ilCOPageObjDef::getDefinitionByParentType($a_parent_type); + $class = $def["class_name"] . "Config"; + $path = "./" . $def["component"] . "/" . $def["directory"] . "/class." . $class . ".php"; + include_once($path); + $cfg = new $class(); + + return $cfg; + } + /** + * Get page object GUI instance (currently unfinished, problems e.g. ilBlogPosting constructor) + * + * @param string $a_parent_type parent type + * @param int $a_id page id + * @param int $a_old_nr history number of page + * @param string $a_lang language + * @return object + */ + /* static function getGUIInstance($a_parent_type, $a_id = 0, $a_old_nr = 0, $a_lang = "-") + { + include_once("./Services/COPage/classes/class.ilCOPageObjDef.php"); + $def = ilCOPageObjDef::getDefinitionByParentType($a_parent_type); + $class = $def["class_name"]."GUI"; + $path = "./".$def["component"]."/".$def["directory"]."/class.".$class.".php"; + include_once($path); + if (in_array($a_parent_type, array("cont", "cstr", "lm"))) + { + $obj = new $class($a_id , $a_old_nr, $a_lang); + } + else if (in_array($a_parent_type, array("impr"))) + { + $obj = new $class(); + } + else if (in_array($a_parent_type, array("stys"))) + { + $obj = new $class($a_parent_type, $a_id, $a_old_nr); + } + else if (in_array($a_parent_type, array("blog"))) + { + $obj = new $class($a_parent_type, $a_id, $a_old_nr); + } + else + { + $obj = new $class($a_id , $a_old_nr); + } + return $obj; + }*/ } - -?> diff --git a/Services/COPage/classes/class.ilPageObjectGUI.php b/Services/COPage/classes/class.ilPageObjectGUI.php index 5dc768845e876adb64c4312674dedf67f74e0d78..39044842831896dc8c1f82ca296b21eecf9a22a0 100755 --- a/Services/COPage/classes/class.ilPageObjectGUI.php +++ b/Services/COPage/classes/class.ilPageObjectGUI.php @@ -1,13 +1,13 @@ log = ilLoggerFactory::getLogger('copg'); - $this->tpl = $DIC["tpl"]; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->tabs_gui = $DIC->tabs(); - $this->plugin_admin = $DIC["ilPluginAdmin"]; - $this->access = $DIC->access(); - $this->user = $DIC->user(); - $this->help = $DIC["ilHelp"]; - $this->ui = $DIC->ui(); - - $this->setParentType($a_parent_type); - $this->setId($a_id); - if ($a_old_nr == 0 && !$a_prevent_get_id && $_GET["old_nr"] > 0) - { - $a_old_nr = $_GET["old_nr"]; - } - $this->setOldNr($a_old_nr); - - if ($a_lang == "" && $_GET["transl"] != "") - { - $this->setLanguage($_GET["transl"]); - } - else - { - if ($a_lang == "") - { - $a_lang = "-"; - } - $this->setLanguage($a_lang); - } - - - $this->setOutputMode(IL_PAGE_PRESENTATION); - $this->setEnabledPageFocus(true); - $this->initPageObject(); - $this->setPageConfig($this->getPageObject()->getPageConfig()); - - $this->output2template = true; - $this->question_xml = ""; - $this->question_html = ""; - - $this->template_output_var = "PAGE_CONTENT"; - $this->change_comments = false; - $this->page_back_title = $this->lng->txt("page"); - $this->lng->loadLanguageModule("content"); - $this->lng->loadLanguageModule("copg"); - - $this->setTemplateOutput(false); - - $this->ctrl->saveParameter($this, "transl"); - - $this->afterConstructor(); - } - - /** - * After constructor - */ - function afterConstructor() - { - } - - - /** - * Init page object - */ - protected final function initPageObject() - { - include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); - $page = ilPageObjectFactory::getInstance($this->getParentType(), $this->getId(), $this->getOldNr(), - $this->getLanguage()); - $this->setPageObject($page); - } - - /** - * Set parent type - * - * @param string $a_val parent type - */ - function setParentType($a_val) - { - $this->parent_type = $a_val; - } - - /** - * Get parent type - * - * @return string parent type - */ - function getParentType() - { - return $this->parent_type; - } - - /** - * Set ID - * - * @param integer $a_val id - */ - function setId($a_val) - { - $this->id = $a_val; - } - - /** - * Get ID - * - * @return integer id - */ - function getId() - { - return $this->id; - } - - /** - * Set old nr (historic page) - * - * @param int $a_val old nr - */ - function setOldNr($a_val) - { - $this->old_nr = $a_val; - } - - /** - * Get old nr (historic page) - * - * @return int old nr - */ - function getOldNr() - { - return $this->old_nr; - } - - /** - * Set language - * - * @param string $a_val language - */ - function setLanguage($a_val) - { - $this->language = $a_val; - } - - /** - * Get language - * - * @return string language - */ - function getLanguage() - { - if ($this->language == "") - { - return "-"; - } - - return $this->language; - } - - /** - * Set enable pc type - * - * @param boolean $a_val enable pc type true/false - */ - function setEnablePCType($a_pc_type, $a_val) - { - $this->getPageConfig()->setEnablePCType($a_pc_type, $a_val); - } - - /** - * Get enable pc type - * - * @return boolean enable pc type true/false - */ - function getEnablePCType($a_pc_type) - { - return $this->getPageConfig()->getEnablePCType($a_pc_type); - } - - /** - * Set page config object - * - * @param object config object - */ - function setPageConfig($a_val) - { - $this->page_config = $a_val; - } - - /** - * Get page config object - * - * @return object config object - */ - function getPageConfig() - { - return $this->page_config; - } - - /** - * Set Page Object - * - * @param ilPageObject $a_pg_obj - */ - function setPageObject(ilPageObject $a_pg_obj) - { - $this->obj = $a_pg_obj; - } - - /** - * Get Page Object - * - * @return ilPageObject - */ - function getPageObject() - { - return $this->obj; - } - - /** - * Set Output Mode - * - * @param string Mode IL_PAGE_PRESENTATION | IL_PAGE_EDIT | IL_PAGE_PREVIEW - */ - function setOutputMode($a_mode = IL_PAGE_PRESENTATION) - { - $this->output_mode = $a_mode; - } - - function getOutputMode() - { - return $this->output_mode; - } - - function setTemplateOutput($a_output = true) - { - $this->output2template = $a_output; - } - - function outputToTemplate() - { - return $this->output2template; - } - - function setPresentationTitle($a_title = "") - { - $this->presentation_title = $a_title; - } - - function getPresentationTitle() - { - return $this->presentation_title; - } - - function setHeader($a_title = "") - { - $this->header = $a_title; - } - - function getHeader() - { - return $this->header; - } - - function setLinkParams($l_params = "") - { - $this->link_params = $l_params; - } - - function getLinkParams() - { - return $this->link_params; - } - - function setLinkFrame($l_frame = "") - { - $this->link_frame = $l_frame; - } - - function getLinkFrame() - { - return $this->link_frame; - } - - function setLinkXML($link_xml) - { - $this->link_xml = $link_xml; - $this->link_xml_set = true; - } - - function getLinkXML() - { - return $this->link_xml; - } - - function setQuestionXML($question_xml) - { - $this->question_xml = $question_xml; - } - - function setQuestionHTML($question_html) - { - $this->getPageConfig()->setQuestionHTML($question_html); - } - - function getQuestionXML() - { - return $this->question_xml; - } - - function getQuestionHTML() - { - return $this->getPageConfig()->getQuestionHTML(); - } - - function setTemplateTargetVar($a_variable) - { - $this->target_var = $a_variable; - } - - function getTemplateTargetVar() - { - return $this->target_var; - } - - function setTemplateOutputVar($a_value) - { - $this->template_output_var = $a_value; - } - - function getTemplateOutputVar() - { - return $this->template_output_var; - } - - /** - * Set sourcecode download script - * - * @param string $script_name - */ - function setSourcecodeDownloadScript ($script_name) - { - $this->sourcecode_download_script = $script_name; - } - - /** - * Get sourcecode download script - * - * @return string - */ - function getSourcecodeDownloadScript () - { - return $this->sourcecode_download_script; - } - - function setLocator(&$a_locator) - { - $this->locator = $a_locator; - } - - function setTabs($a_tabs) - { - $this->tabs_gui = $a_tabs; - } - - function setPageBackTitle($a_title) - { - $this->page_back_title = $a_title; - } - - /** - * Set file download link - * - * @param string $a_download_link download link - */ - function setFileDownloadLink($a_download_link) - { - $this->file_download_link = $a_download_link; - } - - /** - * Get file download link - * - * @return string - */ - function getFileDownloadLink() - { - return $this->file_download_link; - } - - /** - * Set fullscreen link - * - * @param string $a_download_link download link - */ - function setFullscreenLink($a_fullscreen_link) - { - $this->fullscreen_link = $a_fullscreen_link; - } - - /** - * Get fullscreen link - * - * @return string - */ - function getFullscreenLink() - { - return $this->fullscreen_link; - } - - function setIntLinkReturn($a_return) - { - $this->int_link_return = $a_return; - } - - function enableChangeComments($a_enabled) - { - $this->change_comments = $a_enabled; - } - - function isEnabledChangeComments() - { - return $this->change_comments; - } - - function enableNotes($a_enabled, $a_parent_id) - { - $this->notes_enabled = $a_enabled; - $this->notes_parent_id = $a_parent_id; - } - - function isEnabledNotes() - { - return $this->notes_enabled; - } - - /** - * set offline directory to offdir - * - * @param offdir contains diretory where to store files - */ - function setOfflineDirectory ($offdir) { - $this->offline_directory = $offdir; - } - - - /** - * get offline directory - * @return directory where to store offline files - */ - function getOfflineDirectory () { - return $this->offline_directory; - } - - - /** - * set link for "view page" button - * - * @param string link target - * @param string target frame - */ - function setViewPageLink($a_link, $a_target = "") - { - $this->view_page_link = $a_link; - $this->view_page_target = $a_target; - } - - /** - * get view page link - */ - function getViewPageLink() - { - return $this->view_page_link; - } - - /** - * get view page target frame - */ - function getViewPageTarget() - { - return $this->view_page_target; - } - - /** - * get view page text - * - * @return string - */ - function getViewPageText() - { - return $this->lng->txt("cont_presentation_view"); - } - - function setActivationListener(&$a_obj, $a_meth) - { - $this->act_obj = $a_obj; - $this->act_meth = $a_meth; - } - - /** - * Set enabled news - * - * @param boolean enabled news - */ - function setEnabledNews($a_enabled, $a_news_obj_id = 0, $a_news_obj_type = 0) - { - $this->enabled_news = $a_enabled; - $this->news_obj_id = $a_news_obj_id; - $this->news_obj_type = $a_news_obj_type; - } - - /** - * Get enabled news - * - * @return boolean enabled news - */ - function getEnabledNews() - { - return $this->enabled_news; - } - - /** - * Set tab hook - */ - function setTabHook($a_object, $a_function) - { - $this->tab_hook = array("obj" => $a_object, "func" => $a_function); - } - - /** - * Set Display first Edit tab, then Preview tab, instead of Page and Edit. - * - * @param boolean $a_editpreview Edit/preview mode - */ - function setEditPreview($a_editpreview) - { - $this->editpreview = $a_editpreview; - } - - /** - * Get Display first Edit tab, then Preview tab, instead of Page and Edit. - * - * @return boolean Edit/Preview mode - */ - function getEditPreview() - { - return $this->editpreview; - } - - /** - * Set Output tabs. - * - * @param boolean $a_enabledtabs Output tabs - */ - function setEnabledTabs($a_enabledtabs) - { - $this->tabs_enabled = $a_enabledtabs; - } - - /** - * Get Output tabs. - * - * @return boolean Output tabs - */ - function getEnabledTabs() - { - return $this->tabs_enabled; - } - - /** - * Set Enable page focus. - * - * @param boolean $a_enabledpagefocus Enable page focus - */ - function setEnabledPageFocus($a_enabledpagefocus) - { - $this->enabledpagefocus = $a_enabledpagefocus; - } - - /** - * Get Enable page focus. - * - * @return boolean Enable page focus - */ - function getEnabledPageFocus() - { - return $this->enabledpagefocus; - } - - /** - * Set Explorer Updater - * - * @param object $a_tree Tree Object - */ - function setExplorerUpdater($a_exp_frame, $a_exp_id, $a_exp_target_script) - { -return; - $this->exp_frame = $a_exp_frame; - $this->exp_id = $a_exp_id; - $this->exp_target_script = $a_exp_target_script; - } - - /** - * Set Prepending HTML. - * - * @param string $a_prependinghtml Prepending HTML - */ - function setPrependingHtml($a_prependinghtml) - { - $this->prependinghtml = $a_prependinghtml; - } - - /** - * Get Prepending HTML. - * - * @return string Prepending HTML - */ - function getPrependingHtml() - { - return $this->prependinghtml; - } - - /** - * Set Enable Editing. - * - * @param boolean $a_enableediting Enable Editing - */ - function setEnableEditing($a_enableediting) - { - $this->enableediting = $a_enableediting; - } - - /** - * Get Enable Editing. - * - * @return boolean Enable Editing - */ - function getEnableEditing() - { - return $this->enableediting; - } - - /** - * Set Get raw page content only. - * - * @param boolean $a_rawpagecontent Get raw page content only - */ - function setRawPageContent($a_rawpagecontent) - { - $this->rawpagecontent = $a_rawpagecontent; - } - - /** - * Get Get raw page content only. - * - * @return boolean Get raw page content only - */ - function getRawPageContent() - { - return $this->rawpagecontent; - } - - /** - * Set Style Id. - * - * @param int $a_styleid Style Id - */ - function setStyleId($a_styleid) - { - $this->styleid = $a_styleid; - } - - /** - * Get Style Id. - * - * @return int Style Id - */ - function getStyleId() - { - return $this->styleid; - } - - /** - * Set compare mode - * - * @param boolean compare_mode - */ - function setCompareMode($a_val) - { - $this->compare_mode = $a_val; - } - - /** - * Get compare mode - * - * @return boolean compare_mode - */ - function getCompareMode() - { - return $this->compare_mode; - } - - /** - * Set abstract only - * - * @param boolean $a_val get only abstract (first text paragraph) - */ - function setAbstractOnly($a_val) - { - $this->abstract_only = $a_val; - } - - /** - * Get abstract only - * - * @return boolean get only abstract (first text paragraph) - */ - function getAbstractOnly() - { - return $this->abstract_only; - } - - /** - * Set render page container - * - * @param bool $a_val render page container - */ - function setRenderPageContainer($a_val) - { - $this->render_page_container = $a_val; - } - - /** - * Get render page container - * - * @return bool render page container - */ - function getRenderPageContainer() - { - return $this->render_page_container; - } - - /** - * Get disabled text - * - * @param - * @return - */ - function getDisabledText() - { - return $this->lng->txt("inactive"); - } - - - /** - * Activate meda data editor - * - * @param int $a_rep_obj_id object id as used in repository - * @param int $a_sub_obj_id sub object id - * @param string $a_type object type - * @param object $a_observer_obj observer object - * @param object $a_observer_func observer function - */ - function activateMetaDataEditor($a_rep_obj, $a_type, $a_sub_obj_id, - $a_observer_obj = NULL, $a_observer_func = "") - { - $this->use_meta_data = true; - $this->meta_data_rep_obj = $a_rep_obj; - $this->meta_data_sub_obj_id = $a_sub_obj_id; - $this->meta_data_type = $a_type; - $this->meta_data_observer_obj = $a_observer_obj; - $this->meta_data_observer_func = $a_observer_func; - } - - /** - * Determine file download link - * - * @return string file download link - */ - function determineFileDownloadLink() - { - $file_download_link = $this->getFileDownloadLink(); - if ($this->getFileDownloadLink() == "" && $this->getOutputMode() != "offline") - { - $file_download_link = $this->ctrl->getLinkTarget($this, "downloadFile"); - } - return $file_download_link; - } - - /** - * Determine fullscreen link - * - * @return string fullscreen link - */ - function determineFullscreenLink() - { - $fullscreen_link = $this->getFullscreenLink(); - if ($this->getFullscreenLink() == "" && $this->getOutputMode() != "offline") - { - $fullscreen_link = $this->ctrl->getLinkTarget($this, "displayMediaFullscreen", "", false, false); - } - return $fullscreen_link; - } - - /** - * Determine source code download script - * - * @return string sourcecode download script - */ - function determineSourcecodeDownloadScript() - { - $l = $this->sourcecode_download_script; - if ($this->sourcecode_download_script == "" && $this->getOutputMode() != "offline") - { - $l = $this->ctrl->getLinkTarget($this, ""); - } - return $l; - } - - /** - * Put information about activated plugins into XML - */ - function getComponentPluginsXML() - { - $xml = ""; - if($this->getOutputMode() == "edit") - { - $pl_names = $this->plugin_admin->getActivePluginsForSlot(IL_COMP_SERVICE, - "COPage", "pgcp"); - foreach ($pl_names as $pl_name) - { - $plugin = $this->plugin_admin->getPluginObject(IL_COMP_SERVICE, - "COPage", "pgcp", $pl_name); - if ($plugin->isValidParentType($this->getPageObject()->getParentType())) - { - $xml.= ''; - } - } - } - if ($xml != "") - { - $xml = "".$xml.""; - } - return $xml; - } - - - /** - * execute command - */ - function executeCommand() - { - $this->getTabs(); - - $this->ctrl->setReturn($this, "edit"); - - $next_class = $this->ctrl->getNextClass($this); - $this->log->debug("next_class: ".$next_class); - switch($next_class) - { - case 'ilobjectmetadatagui': - $this->tabs_gui->activateTab("meta_data"); - include_once 'Services/Object/classes/class.ilObjectMetaDataGUI.php'; - $md_gui = new ilObjectMetaDataGUI($this->meta_data_rep_obj, $this->meta_data_type, $this->meta_data_sub_obj_id); - if (is_object($this->meta_data_observer_obj)) - { - $md_gui->addMDObserver($this->meta_data_observer_obj, - $this->meta_data_observer_func, "General"); - } - $this->ctrl->forwardCommand($md_gui); - break; - - case "ileditclipboardgui": - $clip_gui = new ilEditClipboardGUI(); - $clip_gui->setPageBackTitle($this->page_back_title); - $ret = $this->ctrl->forwardCommand($clip_gui); - break; - - // notes - case "ilnotegui": - switch($_GET["notes_mode"]) - { - default: - $html = $this->edit(); - $this->tabs_gui->setTabActive("edit"); - return $html; - } - break; - - case 'ilpublicuserprofilegui': - require_once './Services/User/classes/class.ilPublicUserProfileGUI.php'; - $profile_gui = new ilPublicUserProfileGUI($_GET["user"]); - $ret = $this->ctrl->forwardCommand($profile_gui); - break; - - case "ilpageeditorgui": - if (!$this->getEnableEditing()) - { - ilUtil::sendFailure($this->lng->txt("permission_denied"), true); - $this->ctrl->redirect($this, "preview"); - } - $page_editor = new ilPageEditorGUI($this->getPageObject(), $this); - $page_editor->setLocator($this->locator); - $page_editor->setHeader($this->getHeader()); - $page_editor->setPageBackTitle($this->page_back_title); - $page_editor->setIntLinkReturn($this->int_link_return); - //$page_editor->executeCommand(); - $ret = $this->ctrl->forwardCommand($page_editor); - break; - - case 'ilnewsitemgui': - include_once("./Services/News/classes/class.ilNewsItemGUI.php"); - $news_item_gui = new ilNewsItemGUI(); - $news_item_gui->setEnableEdit(true); - $news_item_gui->setContextObjId($this->news_obj_id); - $news_item_gui->setContextObjType($this->news_obj_type); - $news_item_gui->setContextSubObjId($this->obj->getId()); - $news_item_gui->setContextSubObjType("pg"); - - $ret = $this->ctrl->forwardCommand($news_item_gui); - break; - - $profile_gui = new ilPublicUserProfileGUI($_GET["user"]); - $ret = $this->ctrl->forwardCommand($profile_gui); - break; - - case "ilpropertyformgui": - include_once './Services/Form/classes/class.ilPropertyFormGUI.php'; - $form = $this->initOpenedContentForm(); - $this->ctrl->forwardCommand($form); - break; - - case "ilinternallinkgui": - $this->lng->loadLanguageModule("content"); - require_once("./Services/Link/classes/class.ilInternalLinkGUI.php"); - $link_gui = new ilInternalLinkGUI("Media_Media", 0); - - $link_gui->filterLinkType("PageObject_FAQ"); - $link_gui->filterLinkType("GlossaryItem"); - $link_gui->filterLinkType("Media_Media"); - $link_gui->filterLinkType("Media_FAQ"); - - $link_gui->setFilterWhiteList(true); - $this->ctrl->forwardCommand($link_gui); - break; - - case "ilquestioneditgui": - $this->setQEditTabs("question"); - include_once("./Modules/TestQuestionPool/classes/class.ilQuestionEditGUI.php"); - $edit_gui = new ilQuestionEditGUI(); - $edit_gui->setPageConfig($this->getPageConfig()); + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTabsGUI + */ + protected $tabs_gui; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilPluginAdmin + */ + protected $plugin_admin; + + /** + * @var ilLogger + */ + protected $log; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilHelp + */ + protected $help; + + /** + * @var ilPageObject + */ + public $obj; + + /** + * @var string + */ + protected $output_mode; + + public $presentation_title; + public $target_script; + public $return_location; + public $target_var; + public $template_output_var; + public $output2template; + public $link_params; + public $sourcecode_download_script; + public $change_comments; + public $question_html; + public $activation = false; + public $activated = true; + public $editpreview = false; + public $use_meta_data = false; + public $link_xml_set = false; + public $enableediting = true; + public $rawpagecontent = false; + public $enabledcontentincludes = false; + public $compare_mode = false; + public $page_config = null; + public $tabs_enabled = true; + public $render_page_container = false; + private $abstract_only = false; + protected $parent_type = ""; + + + //var $pl_start = "{{{{{"; + //var $pl_end = "}}}}}"; + public $pl_start = "{{{{{"; + public $pl_end = "}}}}}"; + + /** + * @var \ILIAS\DI\UIServices + */ + protected $ui; + + /** + * Constructor + * + * @param string $a_parent_type type of parent object + * @param int $a_id page id + * @param int $a_old_nr history number (current version 0) + * @param bool $a_prevent_get_id prevent getting id automatically from $_GET (e.g. set when concentInclude are included) + * @param string $a_lang language ("" reads also $_GET["transl"], "-" forces master lang) + */ + public function __construct( + $a_parent_type, + $a_id, + $a_old_nr = 0, + $a_prevent_get_id = false, + $a_lang = "" + ) { + global $DIC; + + $this->log = ilLoggerFactory::getLogger('copg'); + $this->tpl = $DIC["tpl"]; + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->tabs_gui = $DIC->tabs(); + $this->plugin_admin = $DIC["ilPluginAdmin"]; + $this->access = $DIC->access(); + $this->user = $DIC->user(); + $this->help = $DIC["ilHelp"]; + $this->ui = $DIC->ui(); + + $this->setParentType($a_parent_type); + $this->setId($a_id); + if ($a_old_nr == 0 && !$a_prevent_get_id && $_GET["old_nr"] > 0) { + $a_old_nr = $_GET["old_nr"]; + } + $this->setOldNr($a_old_nr); + + if ($a_lang == "" && $_GET["transl"] != "") { + $this->setLanguage($_GET["transl"]); + } else { + if ($a_lang == "") { + $a_lang = "-"; + } + $this->setLanguage($a_lang); + } + + + $this->setOutputMode(IL_PAGE_PRESENTATION); + $this->setEnabledPageFocus(true); + $this->initPageObject(); + $this->setPageConfig($this->getPageObject()->getPageConfig()); + + $this->output2template = true; + $this->question_xml = ""; + $this->question_html = ""; + + $this->template_output_var = "PAGE_CONTENT"; + $this->change_comments = false; + $this->page_back_title = $this->lng->txt("page"); + $this->lng->loadLanguageModule("content"); + $this->lng->loadLanguageModule("copg"); + + $this->setTemplateOutput(false); + + $this->ctrl->saveParameter($this, "transl"); + + $this->afterConstructor(); + } + + /** + * After constructor + */ + public function afterConstructor() + { + } + + + /** + * Init page object + */ + final protected function initPageObject() + { + include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); + $page = ilPageObjectFactory::getInstance( + $this->getParentType(), + $this->getId(), + $this->getOldNr(), + $this->getLanguage() + ); + $this->setPageObject($page); + } + + /** + * Set parent type + * + * @param string $a_val parent type + */ + public function setParentType($a_val) + { + $this->parent_type = $a_val; + } + + /** + * Get parent type + * + * @return string parent type + */ + public function getParentType() + { + return $this->parent_type; + } + + /** + * Set ID + * + * @param integer $a_val id + */ + public function setId($a_val) + { + $this->id = $a_val; + } + + /** + * Get ID + * + * @return integer id + */ + public function getId() + { + return $this->id; + } + + /** + * Set old nr (historic page) + * + * @param int $a_val old nr + */ + public function setOldNr($a_val) + { + $this->old_nr = $a_val; + } + + /** + * Get old nr (historic page) + * + * @return int old nr + */ + public function getOldNr() + { + return $this->old_nr; + } + + /** + * Set language + * + * @param string $a_val language + */ + public function setLanguage($a_val) + { + $this->language = $a_val; + } + + /** + * Get language + * + * @return string language + */ + public function getLanguage() + { + if ($this->language == "") { + return "-"; + } + + return $this->language; + } + + /** + * Set enable pc type + * + * @param boolean $a_val enable pc type true/false + */ + public function setEnablePCType($a_pc_type, $a_val) + { + $this->getPageConfig()->setEnablePCType($a_pc_type, $a_val); + } + + /** + * Get enable pc type + * + * @return boolean enable pc type true/false + */ + public function getEnablePCType($a_pc_type) + { + return $this->getPageConfig()->getEnablePCType($a_pc_type); + } + + /** + * Set page config object + * + * @param object config object + */ + public function setPageConfig($a_val) + { + $this->page_config = $a_val; + } + + /** + * Get page config object + * + * @return object config object + */ + public function getPageConfig() + { + return $this->page_config; + } + + /** + * Set Page Object + * + * @param ilPageObject $a_pg_obj + */ + public function setPageObject(ilPageObject $a_pg_obj) + { + $this->obj = $a_pg_obj; + } + + /** + * Get Page Object + * + * @return ilPageObject + */ + public function getPageObject() + { + return $this->obj; + } + + /** + * Set Output Mode + * + * @param string Mode IL_PAGE_PRESENTATION | IL_PAGE_EDIT | IL_PAGE_PREVIEW + */ + public function setOutputMode($a_mode = IL_PAGE_PRESENTATION) + { + $this->output_mode = $a_mode; + } + + public function getOutputMode() + { + return $this->output_mode; + } + + public function setTemplateOutput($a_output = true) + { + $this->output2template = $a_output; + } + + public function outputToTemplate() + { + return $this->output2template; + } + + public function setPresentationTitle($a_title = "") + { + $this->presentation_title = $a_title; + } + + public function getPresentationTitle() + { + return $this->presentation_title; + } + + public function setHeader($a_title = "") + { + $this->header = $a_title; + } + + public function getHeader() + { + return $this->header; + } + + public function setLinkParams($l_params = "") + { + $this->link_params = $l_params; + } + + public function getLinkParams() + { + return $this->link_params; + } + + public function setLinkFrame($l_frame = "") + { + $this->link_frame = $l_frame; + } + + public function getLinkFrame() + { + return $this->link_frame; + } + + public function setLinkXML($link_xml) + { + $this->link_xml = $link_xml; + $this->link_xml_set = true; + } + + public function getLinkXML() + { + return $this->link_xml; + } + + public function setQuestionXML($question_xml) + { + $this->question_xml = $question_xml; + } + + public function setQuestionHTML($question_html) + { + $this->getPageConfig()->setQuestionHTML($question_html); + } + + public function getQuestionXML() + { + return $this->question_xml; + } + + public function getQuestionHTML() + { + return $this->getPageConfig()->getQuestionHTML(); + } + + public function setTemplateTargetVar($a_variable) + { + $this->target_var = $a_variable; + } + + public function getTemplateTargetVar() + { + return $this->target_var; + } + + public function setTemplateOutputVar($a_value) + { + $this->template_output_var = $a_value; + } + + public function getTemplateOutputVar() + { + return $this->template_output_var; + } + + /** + * Set sourcecode download script + * + * @param string $script_name + */ + public function setSourcecodeDownloadScript($script_name) + { + $this->sourcecode_download_script = $script_name; + } + + /** + * Get sourcecode download script + * + * @return string + */ + public function getSourcecodeDownloadScript() + { + return $this->sourcecode_download_script; + } + + public function setLocator(&$a_locator) + { + $this->locator = $a_locator; + } + + public function setTabs($a_tabs) + { + $this->tabs_gui = $a_tabs; + } + + public function setPageBackTitle($a_title) + { + $this->page_back_title = $a_title; + } + + /** + * Set file download link + * + * @param string $a_download_link download link + */ + public function setFileDownloadLink($a_download_link) + { + $this->file_download_link = $a_download_link; + } + + /** + * Get file download link + * + * @return string + */ + public function getFileDownloadLink() + { + return $this->file_download_link; + } + + /** + * Set fullscreen link + * + * @param string $a_download_link download link + */ + public function setFullscreenLink($a_fullscreen_link) + { + $this->fullscreen_link = $a_fullscreen_link; + } + + /** + * Get fullscreen link + * + * @return string + */ + public function getFullscreenLink() + { + return $this->fullscreen_link; + } + + public function setIntLinkReturn($a_return) + { + $this->int_link_return = $a_return; + } + + public function enableChangeComments($a_enabled) + { + $this->change_comments = $a_enabled; + } + + public function isEnabledChangeComments() + { + return $this->change_comments; + } + + public function enableNotes($a_enabled, $a_parent_id) + { + $this->notes_enabled = $a_enabled; + $this->notes_parent_id = $a_parent_id; + } + + public function isEnabledNotes() + { + return $this->notes_enabled; + } + + /** + * set offline directory to offdir + * + * @param offdir contains diretory where to store files + */ + public function setOfflineDirectory($offdir) + { + $this->offline_directory = $offdir; + } + + + /** + * get offline directory + * @return directory where to store offline files + */ + public function getOfflineDirectory() + { + return $this->offline_directory; + } + + + /** + * set link for "view page" button + * + * @param string link target + * @param string target frame + */ + public function setViewPageLink($a_link, $a_target = "") + { + $this->view_page_link = $a_link; + $this->view_page_target = $a_target; + } + + /** + * get view page link + */ + public function getViewPageLink() + { + return $this->view_page_link; + } + + /** + * get view page target frame + */ + public function getViewPageTarget() + { + return $this->view_page_target; + } + + /** + * get view page text + * + * @return string + */ + public function getViewPageText() + { + return $this->lng->txt("cont_presentation_view"); + } + + public function setActivationListener(&$a_obj, $a_meth) + { + $this->act_obj = $a_obj; + $this->act_meth = $a_meth; + } + + /** + * Set enabled news + * + * @param boolean enabled news + */ + public function setEnabledNews($a_enabled, $a_news_obj_id = 0, $a_news_obj_type = 0) + { + $this->enabled_news = $a_enabled; + $this->news_obj_id = $a_news_obj_id; + $this->news_obj_type = $a_news_obj_type; + } + + /** + * Get enabled news + * + * @return boolean enabled news + */ + public function getEnabledNews() + { + return $this->enabled_news; + } + + /** + * Set tab hook + */ + public function setTabHook($a_object, $a_function) + { + $this->tab_hook = array("obj" => $a_object, "func" => $a_function); + } + + /** + * Set Display first Edit tab, then Preview tab, instead of Page and Edit. + * + * @param boolean $a_editpreview Edit/preview mode + */ + public function setEditPreview($a_editpreview) + { + $this->editpreview = $a_editpreview; + } + + /** + * Get Display first Edit tab, then Preview tab, instead of Page and Edit. + * + * @return boolean Edit/Preview mode + */ + public function getEditPreview() + { + return $this->editpreview; + } + + /** + * Set Output tabs. + * + * @param boolean $a_enabledtabs Output tabs + */ + public function setEnabledTabs($a_enabledtabs) + { + $this->tabs_enabled = $a_enabledtabs; + } + + /** + * Get Output tabs. + * + * @return boolean Output tabs + */ + public function getEnabledTabs() + { + return $this->tabs_enabled; + } + + /** + * Set Enable page focus. + * + * @param boolean $a_enabledpagefocus Enable page focus + */ + public function setEnabledPageFocus($a_enabledpagefocus) + { + $this->enabledpagefocus = $a_enabledpagefocus; + } + + /** + * Get Enable page focus. + * + * @return boolean Enable page focus + */ + public function getEnabledPageFocus() + { + return $this->enabledpagefocus; + } + + /** + * Set Explorer Updater + * + * @param object $a_tree Tree Object + */ + public function setExplorerUpdater($a_exp_frame, $a_exp_id, $a_exp_target_script) + { + return; + $this->exp_frame = $a_exp_frame; + $this->exp_id = $a_exp_id; + $this->exp_target_script = $a_exp_target_script; + } + + /** + * Set Prepending HTML. + * + * @param string $a_prependinghtml Prepending HTML + */ + public function setPrependingHtml($a_prependinghtml) + { + $this->prependinghtml = $a_prependinghtml; + } + + /** + * Get Prepending HTML. + * + * @return string Prepending HTML + */ + public function getPrependingHtml() + { + return $this->prependinghtml; + } + + /** + * Set Enable Editing. + * + * @param boolean $a_enableediting Enable Editing + */ + public function setEnableEditing($a_enableediting) + { + $this->enableediting = $a_enableediting; + } + + /** + * Get Enable Editing. + * + * @return boolean Enable Editing + */ + public function getEnableEditing() + { + return $this->enableediting; + } + + /** + * Set Get raw page content only. + * + * @param boolean $a_rawpagecontent Get raw page content only + */ + public function setRawPageContent($a_rawpagecontent) + { + $this->rawpagecontent = $a_rawpagecontent; + } + + /** + * Get Get raw page content only. + * + * @return boolean Get raw page content only + */ + public function getRawPageContent() + { + return $this->rawpagecontent; + } + + /** + * Set Style Id. + * + * @param int $a_styleid Style Id + */ + public function setStyleId($a_styleid) + { + $this->styleid = $a_styleid; + } + + /** + * Get Style Id. + * + * @return int Style Id + */ + public function getStyleId() + { + return $this->styleid; + } + + /** + * Set compare mode + * + * @param boolean compare_mode + */ + public function setCompareMode($a_val) + { + $this->compare_mode = $a_val; + } + + /** + * Get compare mode + * + * @return boolean compare_mode + */ + public function getCompareMode() + { + return $this->compare_mode; + } + + /** + * Set abstract only + * + * @param boolean $a_val get only abstract (first text paragraph) + */ + public function setAbstractOnly($a_val) + { + $this->abstract_only = $a_val; + } + + /** + * Get abstract only + * + * @return boolean get only abstract (first text paragraph) + */ + public function getAbstractOnly() + { + return $this->abstract_only; + } + + /** + * Set render page container + * + * @param bool $a_val render page container + */ + public function setRenderPageContainer($a_val) + { + $this->render_page_container = $a_val; + } + + /** + * Get render page container + * + * @return bool render page container + */ + public function getRenderPageContainer() + { + return $this->render_page_container; + } + + /** + * Get disabled text + * + * @param + * @return + */ + public function getDisabledText() + { + return $this->lng->txt("inactive"); + } + + + /** + * Activate meda data editor + * + * @param int $a_rep_obj_id object id as used in repository + * @param int $a_sub_obj_id sub object id + * @param string $a_type object type + * @param object $a_observer_obj observer object + * @param object $a_observer_func observer function + */ + public function activateMetaDataEditor( + $a_rep_obj, + $a_type, + $a_sub_obj_id, + $a_observer_obj = null, + $a_observer_func = "" + ) { + $this->use_meta_data = true; + $this->meta_data_rep_obj = $a_rep_obj; + $this->meta_data_sub_obj_id = $a_sub_obj_id; + $this->meta_data_type = $a_type; + $this->meta_data_observer_obj = $a_observer_obj; + $this->meta_data_observer_func = $a_observer_func; + } + + /** + * Determine file download link + * + * @return string file download link + */ + public function determineFileDownloadLink() + { + $file_download_link = $this->getFileDownloadLink(); + if ($this->getFileDownloadLink() == "" && $this->getOutputMode() != "offline") { + $file_download_link = $this->ctrl->getLinkTarget($this, "downloadFile"); + } + return $file_download_link; + } + + /** + * Determine fullscreen link + * + * @return string fullscreen link + */ + public function determineFullscreenLink() + { + $fullscreen_link = $this->getFullscreenLink(); + if ($this->getFullscreenLink() == "" && $this->getOutputMode() != "offline") { + $fullscreen_link = $this->ctrl->getLinkTarget($this, "displayMediaFullscreen", "", false, false); + } + return $fullscreen_link; + } + + /** + * Determine source code download script + * + * @return string sourcecode download script + */ + public function determineSourcecodeDownloadScript() + { + $l = $this->sourcecode_download_script; + if ($this->sourcecode_download_script == "" && $this->getOutputMode() != "offline") { + $l = $this->ctrl->getLinkTarget($this, ""); + } + return $l; + } + + /** + * Put information about activated plugins into XML + */ + public function getComponentPluginsXML() + { + $xml = ""; + if ($this->getOutputMode() == "edit") { + $pl_names = $this->plugin_admin->getActivePluginsForSlot( + IL_COMP_SERVICE, + "COPage", + "pgcp" + ); + foreach ($pl_names as $pl_name) { + $plugin = $this->plugin_admin->getPluginObject( + IL_COMP_SERVICE, + "COPage", + "pgcp", + $pl_name + ); + if ($plugin->isValidParentType($this->getPageObject()->getParentType())) { + $xml.= ''; + } + } + } + if ($xml != "") { + $xml = "" . $xml . ""; + } + return $xml; + } + + + /** + * execute command + */ + public function executeCommand() + { + $this->getTabs(); + + $this->ctrl->setReturn($this, "edit"); + + $next_class = $this->ctrl->getNextClass($this); + $this->log->debug("next_class: " . $next_class); + switch ($next_class) { + case 'ilobjectmetadatagui': + $this->tabs_gui->activateTab("meta_data"); + include_once 'Services/Object/classes/class.ilObjectMetaDataGUI.php'; + $md_gui = new ilObjectMetaDataGUI($this->meta_data_rep_obj, $this->meta_data_type, $this->meta_data_sub_obj_id); + if (is_object($this->meta_data_observer_obj)) { + $md_gui->addMDObserver( + $this->meta_data_observer_obj, + $this->meta_data_observer_func, + "General" + ); + } + $this->ctrl->forwardCommand($md_gui); + break; + + case "ileditclipboardgui": + $clip_gui = new ilEditClipboardGUI(); + $clip_gui->setPageBackTitle($this->page_back_title); + $ret = $this->ctrl->forwardCommand($clip_gui); + break; + + // notes + case "ilnotegui": + switch ($_GET["notes_mode"]) { + default: + $html = $this->edit(); + $this->tabs_gui->setTabActive("edit"); + return $html; + } + break; + + case 'ilpublicuserprofilegui': + require_once './Services/User/classes/class.ilPublicUserProfileGUI.php'; + $profile_gui = new ilPublicUserProfileGUI($_GET["user"]); + $ret = $this->ctrl->forwardCommand($profile_gui); + break; + + case "ilpageeditorgui": + if (!$this->getEnableEditing()) { + ilUtil::sendFailure($this->lng->txt("permission_denied"), true); + $this->ctrl->redirect($this, "preview"); + } + $page_editor = new ilPageEditorGUI($this->getPageObject(), $this); + $page_editor->setLocator($this->locator); + $page_editor->setHeader($this->getHeader()); + $page_editor->setPageBackTitle($this->page_back_title); + $page_editor->setIntLinkReturn($this->int_link_return); + //$page_editor->executeCommand(); + $ret = $this->ctrl->forwardCommand($page_editor); + break; + + case 'ilnewsitemgui': + include_once("./Services/News/classes/class.ilNewsItemGUI.php"); + $news_item_gui = new ilNewsItemGUI(); + $news_item_gui->setEnableEdit(true); + $news_item_gui->setContextObjId($this->news_obj_id); + $news_item_gui->setContextObjType($this->news_obj_type); + $news_item_gui->setContextSubObjId($this->obj->getId()); + $news_item_gui->setContextSubObjType("pg"); + + $ret = $this->ctrl->forwardCommand($news_item_gui); + break; + + $profile_gui = new ilPublicUserProfileGUI($_GET["user"]); + $ret = $this->ctrl->forwardCommand($profile_gui); + break; + + case "ilpropertyformgui": + include_once './Services/Form/classes/class.ilPropertyFormGUI.php'; + $form = $this->initOpenedContentForm(); + $this->ctrl->forwardCommand($form); + break; + + case "ilinternallinkgui": + $this->lng->loadLanguageModule("content"); + require_once("./Services/Link/classes/class.ilInternalLinkGUI.php"); + $link_gui = new ilInternalLinkGUI("Media_Media", 0); + + $link_gui->filterLinkType("PageObject_FAQ"); + $link_gui->filterLinkType("GlossaryItem"); + $link_gui->filterLinkType("Media_Media"); + $link_gui->filterLinkType("Media_FAQ"); + + $link_gui->setFilterWhiteList(true); + $this->ctrl->forwardCommand($link_gui); + break; + + case "ilquestioneditgui": + $this->setQEditTabs("question"); + include_once("./Modules/TestQuestionPool/classes/class.ilQuestionEditGUI.php"); + $edit_gui = new ilQuestionEditGUI(); + $edit_gui->setPageConfig($this->getPageConfig()); // $edit_gui->addNewIdListener($this, "setNewQuestionId"); - $edit_gui->setSelfAssessmentEditingMode(true); - $ret = $this->ctrl->forwardCommand($edit_gui); - $this->tpl->setContent($ret); - break; - - case 'ilassquestionfeedbackeditinggui': - - $this->onFeedbackEditingForwarding(); - - // set tabs - $this->setQEditTabs("feedback"); - - // load required lang mods - $this->lng->loadLanguageModule("assessment"); - - // set context tabs - require_once 'Modules/TestQuestionPool/classes/class.assQuestionGUI.php'; - require_once 'Modules/TestQuestionPool/classes/class.assQuestion.php'; - $questionGUI = assQuestionGUI::_getQuestionGUI(assQuestion::_getQuestionType((int) $_GET['q_id']), (int) $_GET['q_id']); - $questionGUI->object->setObjId(0); - $questionGUI->object->setSelfAssessmentEditingMode(true); - $questionGUI->object->setPreventRteUsage($this->getPageConfig()->getPreventRteUsage()); - - // forward to ilAssQuestionFeedbackGUI - require_once 'Modules/TestQuestionPool/classes/class.ilAssQuestionFeedbackEditingGUI.php'; - $gui = new ilAssQuestionFeedbackEditingGUI($questionGUI, $this->ctrl, $this->access, $this->tpl, $this->tabs_gui, $this->lng); - $this->ctrl->forwardCommand($gui); - break; + $edit_gui->setSelfAssessmentEditingMode(true); + $ret = $this->ctrl->forwardCommand($edit_gui); + $this->tpl->setContent($ret); + break; + + case 'ilassquestionfeedbackeditinggui': + + $this->onFeedbackEditingForwarding(); + + // set tabs + $this->setQEditTabs("feedback"); + + // load required lang mods + $this->lng->loadLanguageModule("assessment"); + + // set context tabs + require_once 'Modules/TestQuestionPool/classes/class.assQuestionGUI.php'; + require_once 'Modules/TestQuestionPool/classes/class.assQuestion.php'; + $questionGUI = assQuestionGUI::_getQuestionGUI(assQuestion::_getQuestionType((int) $_GET['q_id']), (int) $_GET['q_id']); + $questionGUI->object->setObjId(0); + $questionGUI->object->setSelfAssessmentEditingMode(true); + $questionGUI->object->setPreventRteUsage($this->getPageConfig()->getPreventRteUsage()); + + // forward to ilAssQuestionFeedbackGUI + require_once 'Modules/TestQuestionPool/classes/class.ilAssQuestionFeedbackEditingGUI.php'; + $gui = new ilAssQuestionFeedbackEditingGUI($questionGUI, $this->ctrl, $this->access, $this->tpl, $this->tabs_gui, $this->lng); + $this->ctrl->forwardCommand($gui); + break; /* case "ilpagemultilanggui": - $this->ctrl->setReturn($this, "edit"); - include_once("./Services/COPage/classes/class.ilPageMultiLangGUI.php"); - $ml_gui = new ilPageMultiLangGUI($this->getPageObject()->getParentType(), $this->getPageObject()->getParentId(), - $this->getPageConfig()->getSinglePageMode()); - //$this->setTabs("settings"); - //$this->setSubTabs("cont_multilinguality"); - $ret = $this->ctrl->forwardCommand($ml_gui); - break;*/ - - - case 'ilLearninghistorygui': - $user_id = null; - if ($this->getPageObject()->getParentType() == "prtf") - { - $user_id = ilObject::_lookupOwner($this->getPageObject()->getPortfolioId()); - } - $hist_gui = new ilLearningHistoryGUI(); - $hist_gui->setUserId($user_id); - $this->ctrl->forwardCommand($hist_gui); - break; - - default: - $cmd = $this->ctrl->getCmd("preview"); - $ret = $this->$cmd(); - break; - } -//echo "+$ret+"; - return $ret; - } - - /** - * Set question editing tabs - * - * @param - * @return - */ - function setQEditTabs($a_active) - { - include_once("./Modules/TestQuestionPool/classes/class.assQuestion.php"); - - $this->tabs_gui->clearTargets(); - - $this->tabs_gui->setBackTarget($this->lng->txt("back"), - $this->ctrl->getLinkTarget($this, "edit")); - - $this->ctrl->setParameterByClass("ilquestioneditgui", "q_id", $_GET["q_id"]); - $this->tabs_gui->addTab("question", $this->lng->txt("question"), - $this->ctrl->getLinkTargetByClass("ilquestioneditgui", "editQuestion")); - - require_once 'Modules/TestQuestionPool/classes/class.ilAssQuestionFeedbackEditingGUI.php'; - $this->ctrl->setParameterByClass("ilAssQuestionFeedbackEditingGUI", "q_id", $_GET["q_id"]); - $this->tabs_gui->addTab("feedback", $this->lng->txt("feedback"), - $this->ctrl->getLinkTargetByClass("ilAssQuestionFeedbackEditingGUI", ilAssQuestionFeedbackEditingGUI::CMD_SHOW)); - - $this->tabs_gui->activateTab($a_active); - } - - /** - * On feedback editing forwarding - */ - function onFeedbackEditingForwarding() - { - - } - - - function deactivatePage() - { - $this->getPageObject()->setActivationStart(null); - $this->getPageObject()->setActivationEnd(null); - $this->getPageObject()->setActive(false); - $this->getPageObject()->update(); - $this->ctrl->redirect($this, "edit"); - } - - function activatePage() - { - $this->getPageObject()->setActivationStart(null); - $this->getPageObject()->setActivationEnd(null); - $this->getPageObject()->setActive(true); - $this->getPageObject()->update(); - $this->ctrl->redirect($this, "edit"); - } - - /** - * display content of page - */ - function showPage() - { - // jquery and jquery ui are always provided for components - include_once("./Services/jQuery/classes/class.iljQueryUtil.php"); - iljQueryUtil::initjQuery(); - iljQueryUtil::initjQueryUI(); - -// $this->initSelfAssessmentRendering(); - - include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); - ilObjMediaObjectGUI::includePresentationJS($GLOBALS["tpl"]); - - $GLOBALS["tpl"]->addJavaScript("./Services/COPage/js/ilCOPagePres.js"); - - // needed for overlays in iim - include_once("./Services/UIComponent/Overlay/classes/class.ilOverlayGUI.php"); - ilOverlayGUI::initJavascript(); - - include_once("./Services/MediaObjects/classes/class.ilPlayerUtil.php"); - ilPlayerUtil::initMediaElementJs($GLOBALS["tpl"]); - - // init template - //if($this->outputToTemplate()) - //{ - if($this->getOutputMode() == "edit") - { - $this->log->debug("ilPageObjectGUI, showPage() in edit mode."); - -//echo ":".$this->getTemplateTargetVar().":"; - $tpl = new ilTemplate("tpl.page_edit_wysiwyg.html", true, true, "Services/COPage"); - //$this->tpl->addBlockFile($this->getTemplateTargetVar(), "adm_content", "tpl.page_edit_wysiwyg.html", "Services/COPage"); - - // to do: status dependent class - $tpl->setVariable("CLASS_PAGE_TD", "ilc_Page"); - - // user comment - if ($this->isEnabledChangeComments()) - { - $tpl->setCurrentBlock("change_comment"); - $tpl->setVariable("TXT_ADD_COMMENT", $this->lng->txt("cont_add_change_comment")); - $tpl->parseCurrentBlock(); - } - - $tpl->setVariable("WYSIWYG_ACTION", - $this->ctrl->getFormActionByClass("ilpageeditorgui", "", "", true)); - - // determine media, html and javascript mode - $sel_media_mode = ($this->user->getPref("ilPageEditor_MediaMode") == "disable") - ? "disable" - : "enable"; - $sel_html_mode = ($this->user->getPref("ilPageEditor_HTMLMode") == "disable") - ? "disable" - : "enable"; - $sel_js_mode = "disable"; - //if($ilSetting->get("enable_js_edit", 1)) - //{ - $sel_js_mode = (ilPageEditorGUI::_doJSEditing()) - ? "enable" - : "disable"; - //} - - // show prepending html - $tpl->setVariable("PREPENDING_HTML", $this->getPrependingHtml()); - $tpl->setVariable("TXT_CONFIRM_DELETE", $this->lng->txt("cont_confirm_delete")); - - // presentation view - if ($this->getViewPageLink() != "") - { - $this->tabs_gui->addNonTabbedLink("pres_view", $this->getViewPageText(), - $this->getViewPageLink(), $this->getViewPageTarget()); - } - - // show actions drop down - $this->addActionsMenu($tpl, $sel_media_mode, $sel_html_mode, $sel_js_mode); - - // get js files for JS enabled editing - if ($sel_js_mode == "enable") - { - $this->insertHelp($tpl); - include_once("./Services/YUI/classes/class.ilYuiUtil.php"); - ilYuiUtil::initDragDrop(); - ilYuiUtil::initConnection(); - ilYuiUtil::initPanel(false); - $GLOBALS["tpl"]->addJavaScript("./Services/COPage/js/ilcopagecallback.js"); - $GLOBALS["tpl"]->addJavascript("Services/COPage/js/page_editing.js"); - - include_once("./Services/UIComponent/Modal/classes/class.ilModalGUI.php"); - ilModalGUI::initJS(); - $this->lng->toJS("cont_error"); - $this->lng->toJS("cont_sel_el_cut_use_paste"); - $this->lng->toJS("cont_sel_el_copied_use_paste"); - - include_once './Services/Style/Content/classes/class.ilObjStyleSheet.php'; - $GLOBALS["tpl"]->addOnloadCode("var preloader = new Image(); + $this->ctrl->setReturn($this, "edit"); + include_once("./Services/COPage/classes/class.ilPageMultiLangGUI.php"); + $ml_gui = new ilPageMultiLangGUI($this->getPageObject()->getParentType(), $this->getPageObject()->getParentId(), + $this->getPageConfig()->getSinglePageMode()); + //$this->setTabs("settings"); + //$this->setSubTabs("cont_multilinguality"); + $ret = $this->ctrl->forwardCommand($ml_gui); + break;*/ + + + case 'ilLearninghistorygui': + $user_id = null; + if ($this->getPageObject()->getParentType() == "prtf") { + $user_id = ilObject::_lookupOwner($this->getPageObject()->getPortfolioId()); + } + $hist_gui = new ilLearningHistoryGUI(); + $hist_gui->setUserId($user_id); + $this->ctrl->forwardCommand($hist_gui); + break; + + default: + $cmd = $this->ctrl->getCmd("preview"); + $ret = $this->$cmd(); + break; + } + //echo "+$ret+"; + return $ret; + } + + /** + * Set question editing tabs + * + * @param + * @return + */ + public function setQEditTabs($a_active) + { + include_once("./Modules/TestQuestionPool/classes/class.assQuestion.php"); + + $this->tabs_gui->clearTargets(); + + $this->tabs_gui->setBackTarget( + $this->lng->txt("back"), + $this->ctrl->getLinkTarget($this, "edit") + ); + + $this->ctrl->setParameterByClass("ilquestioneditgui", "q_id", $_GET["q_id"]); + $this->tabs_gui->addTab( + "question", + $this->lng->txt("question"), + $this->ctrl->getLinkTargetByClass("ilquestioneditgui", "editQuestion") + ); + + require_once 'Modules/TestQuestionPool/classes/class.ilAssQuestionFeedbackEditingGUI.php'; + $this->ctrl->setParameterByClass("ilAssQuestionFeedbackEditingGUI", "q_id", $_GET["q_id"]); + $this->tabs_gui->addTab( + "feedback", + $this->lng->txt("feedback"), + $this->ctrl->getLinkTargetByClass("ilAssQuestionFeedbackEditingGUI", ilAssQuestionFeedbackEditingGUI::CMD_SHOW) + ); + + $this->tabs_gui->activateTab($a_active); + } + + /** + * On feedback editing forwarding + */ + public function onFeedbackEditingForwarding() + { + } + + + public function deactivatePage() + { + $this->getPageObject()->setActivationStart(null); + $this->getPageObject()->setActivationEnd(null); + $this->getPageObject()->setActive(false); + $this->getPageObject()->update(); + $this->ctrl->redirect($this, "edit"); + } + + public function activatePage() + { + $this->getPageObject()->setActivationStart(null); + $this->getPageObject()->setActivationEnd(null); + $this->getPageObject()->setActive(true); + $this->getPageObject()->update(); + $this->ctrl->redirect($this, "edit"); + } + + /** + * display content of page + */ + public function showPage() + { + // jquery and jquery ui are always provided for components + include_once("./Services/jQuery/classes/class.iljQueryUtil.php"); + iljQueryUtil::initjQuery(); + iljQueryUtil::initjQueryUI(); + + // $this->initSelfAssessmentRendering(); + + include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); + ilObjMediaObjectGUI::includePresentationJS($GLOBALS["tpl"]); + + $GLOBALS["tpl"]->addJavaScript("./Services/COPage/js/ilCOPagePres.js"); + + // needed for overlays in iim + include_once("./Services/UIComponent/Overlay/classes/class.ilOverlayGUI.php"); + ilOverlayGUI::initJavascript(); + + include_once("./Services/MediaObjects/classes/class.ilPlayerUtil.php"); + ilPlayerUtil::initMediaElementJs($GLOBALS["tpl"]); + + // init template + //if($this->outputToTemplate()) + //{ + if ($this->getOutputMode() == "edit") { + $this->log->debug("ilPageObjectGUI, showPage() in edit mode."); + + //echo ":".$this->getTemplateTargetVar().":"; + $tpl = new ilTemplate("tpl.page_edit_wysiwyg.html", true, true, "Services/COPage"); + //$this->tpl->addBlockFile($this->getTemplateTargetVar(), "adm_content", "tpl.page_edit_wysiwyg.html", "Services/COPage"); + + // to do: status dependent class + $tpl->setVariable("CLASS_PAGE_TD", "ilc_Page"); + + // user comment + if ($this->isEnabledChangeComments()) { + $tpl->setCurrentBlock("change_comment"); + $tpl->setVariable("TXT_ADD_COMMENT", $this->lng->txt("cont_add_change_comment")); + $tpl->parseCurrentBlock(); + } + + $tpl->setVariable( + "WYSIWYG_ACTION", + $this->ctrl->getFormActionByClass("ilpageeditorgui", "", "", true) + ); + + // determine media, html and javascript mode + $sel_media_mode = ($this->user->getPref("ilPageEditor_MediaMode") == "disable") + ? "disable" + : "enable"; + $sel_html_mode = ($this->user->getPref("ilPageEditor_HTMLMode") == "disable") + ? "disable" + : "enable"; + $sel_js_mode = "disable"; + //if($ilSetting->get("enable_js_edit", 1)) + //{ + $sel_js_mode = (ilPageEditorGUI::_doJSEditing()) + ? "enable" + : "disable"; + //} + + // show prepending html + $tpl->setVariable("PREPENDING_HTML", $this->getPrependingHtml()); + $tpl->setVariable("TXT_CONFIRM_DELETE", $this->lng->txt("cont_confirm_delete")); + + // presentation view + if ($this->getViewPageLink() != "") { + $this->tabs_gui->addNonTabbedLink( + "pres_view", + $this->getViewPageText(), + $this->getViewPageLink(), + $this->getViewPageTarget() + ); + } + + // show actions drop down + $this->addActionsMenu($tpl, $sel_media_mode, $sel_html_mode, $sel_js_mode); + + // get js files for JS enabled editing + if ($sel_js_mode == "enable") { + $this->insertHelp($tpl); + include_once("./Services/YUI/classes/class.ilYuiUtil.php"); + ilYuiUtil::initDragDrop(); + ilYuiUtil::initConnection(); + ilYuiUtil::initPanel(false); + $GLOBALS["tpl"]->addJavaScript("./Services/COPage/js/ilcopagecallback.js"); + $GLOBALS["tpl"]->addJavascript("Services/COPage/js/page_editing.js"); + + include_once("./Services/UIComponent/Modal/classes/class.ilModalGUI.php"); + ilModalGUI::initJS(); + $this->lng->toJS("cont_error"); + $this->lng->toJS("cont_sel_el_cut_use_paste"); + $this->lng->toJS("cont_sel_el_copied_use_paste"); + + include_once './Services/Style/Content/classes/class.ilObjStyleSheet.php'; + $GLOBALS["tpl"]->addOnloadCode("var preloader = new Image(); preloader.src = './templates/default/images/loader.svg'; - ilCOPage.setUser('".$this->user->getLogin()."'); - ilCOPage.setContentCss('". - ilObjStyleSheet::getContentStylePath((int) $this->getStyleId()). - ", ".ilUtil::getStyleSheetLocation(). - ", ./Services/COPage/css/tiny_extra.css". - "')"); - include_once("./Services/COPage/classes/class.ilPCParagraphGUI.php"); - foreach (ilPCParagraphGUI::_getTextCharacteristics($this->getStyleId()) as $c) - { - $GLOBALS["tpl"]->addOnloadCode("ilCOPage.addTextFormat('".$c."');"); - } - - $GLOBALS["tpl"]->addJavascript("./libs/bower/bower_components/tinymce/tinymce.min.js"); - $tpl->touchBlock("init_dragging"); - - $cfg = $this->getPageConfig(); - $tpl->setVariable("IL_TINY_MENU", - self::getTinyMenu( - $this->getPageObject()->getParentType(), - $cfg->getEnableInternalLinks(), - $cfg->getEnableWikiLinks(), - $cfg->getEnableKeywords(), - $this->getStyleId(), true, true, - $cfg->getEnableAnchors(), true, - $cfg->getEnableUserLinks() - )); - - // add int link parts - include_once("./Services/Link/classes/class.ilInternalLinkGUI.php"); - $tpl->setCurrentBlock("int_link_prep"); - $tpl->setVariable("INT_LINK_PREP", ilInternalLinkGUI::getInitHTML( - $this->ctrl->getLinkTargetByClass(array("ilpageeditorgui", "ilinternallinkgui"), - "", false, true, false))); - $tpl->parseCurrentBlock(); - - include_once("./Services/YUI/classes/class.ilYuiUtil.php"); - ilYuiUtil::initConnection(); - $GLOBALS["tpl"]->addJavaScript("./Services/UIComponent/Explorer/js/ilExplorer.js"); - - } - - // multiple actions - $cnt_pcs = $this->getPageObject()->countPageContents(); - if ($cnt_pcs > 1 || - ($this->getPageObject()->getParentType() != "qpl" && $cnt_pcs > 0)) - { - $tpl->setCurrentBlock("multi_actions"); - if ($sel_js_mode == "enable") - { - $tpl->setVariable("ONCLICK_DE_ACTIVATE_SELECTED", 'onclick="return ilEditMultiAction(\'activateSelected\');"'); - $tpl->setVariable("ONCLICK_DELETE_SELECTED", 'onclick="return ilEditMultiAction(\'deleteSelected\');"'); - $tpl->setVariable("ONCLICK_ASSIGN_CHARACTERISTIC", 'onclick="return ilEditMultiAction(\'assignCharacteristicForm\');"'); - $tpl->setVariable("ONCLICK_COPY_SELECTED", 'onclick="return ilEditMultiAction(\'copySelected\');"'); - $tpl->setVariable("ONCLICK_CUT_SELECTED", 'onclick="return ilEditMultiAction(\'cutSelected\');"'); - $tpl->setVariable("TXT_SELECT_ALL", $this->lng->txt("select_all")); - $tpl->setVariable("ONCLICK_SELECT_ALL", 'onclick="return ilEditMultiAction(\'selectAll\');"'); - } - $tpl->setVariable("TXT_DE_ACTIVATE_SELECTED", $this->lng->txt("cont_ed_enable")); - $tpl->setVariable("TXT_ASSIGN_CHARACTERISTIC", $this->lng->txt("cont_assign_characteristic")); - $tpl->setVariable("TXT_DELETE_SELECTED", $this->lng->txt("cont_delete_selected")); - $tpl->setVariable("TXT_COPY_SELECTED", $this->lng->txt("copy")); - $tpl->setVariable("TXT_CUT_SELECTED", $this->lng->txt("cut")); - $tpl->setVariable("IMG_ARROW", ilUtil::getImagePath("arrow_downright.svg")); - $tpl->parseCurrentBlock(); - } - } - else - { - // presentation or preview here - - $tpl = new ilTemplate("tpl.page.html", true, true, "Services/COPage"); - if ($this->getEnabledPageFocus()) - { - $tpl->touchBlock("page_focus"); - } - - include_once("./Services/User/classes/class.ilUserUtil.php"); - - // presentation - if( $this->isPageContainerToBeRendered() ) - { - $tpl->touchBlock("page_container_1"); - $tpl->touchBlock("page_container_2"); - $tpl->touchBlock("page_container_3"); - } - - // history - $c_old_nr = $this->getPageObject()->old_nr; - if ($c_old_nr > 0 || $this->getCompareMode() || $_GET["history_mode"] == 1) - { - $hist_info = - $this->getPageObject()->getHistoryInfo($c_old_nr); - - if (!$this->getCompareMode()) - { - $this->ctrl->setParameter($this, "history_mode", "1"); - - // previous revision - if (is_array($hist_info["previous"])) - { - $tpl->setCurrentBlock("previous_rev"); - $tpl->setVariable("TXT_PREV_REV", $this->lng->txt("cont_previous_rev")); - $this->ctrl->setParameter($this, "old_nr", $hist_info["previous"]["nr"]); - $tpl->setVariable("HREF_PREV", - $this->ctrl->getLinkTarget($this, "preview")); - $tpl->parseCurrentBlock(); - } - else - { - $tpl->setCurrentBlock("previous_rev_disabled"); - $tpl->setVariable("TXT_PREV_REV", $this->lng->txt("cont_previous_rev")); - $tpl->parseCurrentBlock(); - } - - // next revision - if ($c_old_nr > 0) - { - $tpl->setCurrentBlock("next_rev"); - $tpl->setVariable("TXT_NEXT_REV", $this->lng->txt("cont_next_rev")); - $this->ctrl->setParameter($this, "old_nr", $hist_info["next"]["nr"]); - $tpl->setVariable("HREF_NEXT", - $this->ctrl->getLinkTarget($this, "preview")); - $tpl->parseCurrentBlock(); - - // latest revision - $tpl->setCurrentBlock("latest_rev"); - $tpl->setVariable("TXT_LATEST_REV", $this->lng->txt("cont_latest_rev")); - $this->ctrl->setParameter($this, "old_nr", ""); - $tpl->setVariable("HREF_LATEST", - $this->ctrl->getLinkTarget($this, "preview")); - $tpl->parseCurrentBlock(); - } - - $this->ctrl->setParameter($this, "history_mode", ""); - - // rollback - if ($c_old_nr > 0 && $this->user->getId() != ANONYMOUS_USER_ID) - { - $tpl->setCurrentBlock("rollback"); - $this->ctrl->setParameter($this, "old_nr", $c_old_nr); - $tpl->setVariable("HREF_ROLLBACK", - $this->ctrl->getLinkTarget($this, "rollbackConfirmation")); - $this->ctrl->setParameter($this, "old_nr", ""); - $tpl->setVariable("TXT_ROLLBACK", - $this->lng->txt("cont_rollback")); - $tpl->parseCurrentBlock(); - } - } - - $tpl->setCurrentBlock("hist_nav"); - $tpl->setVariable("TXT_REVISION", $this->lng->txt("cont_revision")); - $tpl->setVariable("VAL_REVISION_DATE", - ilDatePresentation::formatDate(new ilDateTime($hist_info["current"]["hdate"], IL_CAL_DATETIME))); - $tpl->setVariable("VAL_REV_USER", - ilUserUtil::getNamePresentation($hist_info["current"]["user_id"])); - $tpl->parseCurrentBlock(); - } - } - if ($this->getOutputMode() != IL_PAGE_PRESENTATION && - $this->getOutputMode() != IL_PAGE_OFFLINE && - $this->getOutputMode() != IL_PAGE_PREVIEW && - $this->getOutputMode() != IL_PAGE_PRINT) - { - $tpl->setVariable("FORMACTION", $this->ctrl->getFormActionByClass("ilpageeditorgui")); - } - - // output media object edit list (of media links) - if($this->getOutputMode() == "edit") - { - $links = ilInternalLink::_getTargetsOfSource($this->obj->getParentType().":pg", - $this->obj->getId(), $this->obj->getLanguage()); - $mob_links = array(); - foreach($links as $link) - { - if ($link["type"] == "mob") - { - if (ilObject::_exists($link["id"]) && ilObject::_lookupType($link["id"]) == "mob") - { - $mob_links[$link["id"]] = ilObject::_lookupTitle($link["id"])." [".$link["id"]."]"; - } - } - } - - // linked media objects - if (count($mob_links) > 0) - { - $tpl->setCurrentBlock("med_link"); - $tpl->setVariable("TXT_LINKED_MOBS", $this->lng->txt("cont_linked_mobs")); - $tpl->setVariable("SEL_MED_LINKS", - ilUtil::formSelect(0, "mob_id", $mob_links, false, true)); - $tpl->setVariable("TXT_EDIT_MEDIA", $this->lng->txt("cont_edit_mob")); - $tpl->setVariable("TXT_COPY_TO_CLIPBOARD", $this->lng->txt("cont_copy_to_clipboard")); - //$this->tpl->setVariable("TXT_COPY_TO_POOL", $this->lng->txt("cont_copy_to_mediapool")); - $tpl->parseCurrentBlock(); - } - - // content snippets used - include_once("./Services/COPage/classes/class.ilPCContentInclude.php"); - $snippets = ilPCContentInclude::collectContentIncludes($this->getPageObject(), - $this->getPageObject()->getDomDoc()); - if (count($snippets) > 0) - { - foreach ($snippets as $s) - { - include_once("./Modules/MediaPool/classes/class.ilMediaPoolPage.php"); - $sn_arr[$s["id"]] = ilMediaPoolPage::lookupTitle($s["id"]); - } - $tpl->setCurrentBlock("med_link"); - $tpl->setVariable("TXT_CONTENT_SNIPPETS_USED", $this->lng->txt("cont_snippets_used")); - $tpl->setVariable("SEL_SNIPPETS", - ilUtil::formSelect(0, "ci_id", $sn_arr, false, true)); - $tpl->setVariable("TXT_SHOW_INFO", $this->lng->txt("cont_show_info")); - $tpl->parseCurrentBlock(); - } - - // scheduled activation? - if (!$this->getPageObject()->getActive() && - $this->getPageObject()->getActivationStart() != "" && - $this->getPageConfig()->getEnableScheduledActivation()) - { - $tpl->setCurrentBlock("activation_txt"); - $tpl->setVariable("TXT_SCHEDULED_ACTIVATION", $this->lng->txt("cont_scheduled_activation")); - $tpl->setVariable("SA_FROM", - ilDatePresentation::formatDate( - new ilDateTime($this->getPageObject()->getActivationStart(), - IL_CAL_DATETIME))); - $tpl->setVariable("SA_TO", - ilDatePresentation::formatDate( - new ilDateTime($this->getPageObject()->getActivationEnd(), - IL_CAL_DATETIME))); - $tpl->parseCurrentBlock(); - } - } - - if ($_GET["reloadTree"] == "y") - { - $tpl->setCurrentBlock("reload_tree"); - $tpl->setVariable("LINK_TREE", - $this->ctrl->getLinkTargetByClass("ilobjlearningmodulegui", "explorer", "", false, false)); - $tpl->parseCurrentBlock(); - } -// } - // get content - $builded = $this->obj->buildDom(); - - // manage hierarchical ids - if($this->getOutputMode() == "edit") - { - - // add pc ids, if necessary - if (!$this->obj->checkPCIds()) - { - $this->obj->insertPCIds(); - $this->obj->update(true, true); - } - - $this->obj->addFileSizes(); - $this->obj->addHierIDs(); - - $hids = $this->obj->getHierIds(); - $row1_ids = $this->obj->getFirstRowIds(); - $col1_ids = $this->obj->getFirstColumnIds(); - $litem_ids = $this->obj->getListItemIds(); - $fitem_ids = $this->obj->getFileItemIds(); - - // standard menues - $hids = $this->obj->getHierIds(); - foreach($hids as $hid) - { - $tpl->setCurrentBlock("add_dhtml"); - $tpl->setVariable("CONTEXTMENU", "contextmenu_".$hid); - $tpl->parseCurrentBlock(); - } - - // column menues for tables - foreach($col1_ids as $hid) - { - $tpl->setCurrentBlock("add_dhtml"); - $tpl->setVariable("CONTEXTMENU", "contextmenu_r".$hid); - $tpl->parseCurrentBlock(); - } - - // row menues for tables - foreach($row1_ids as $hid) - { - $tpl->setCurrentBlock("add_dhtml"); - $tpl->setVariable("CONTEXTMENU", "contextmenu_c".$hid); - $tpl->parseCurrentBlock(); - } - - // list item menues - foreach($litem_ids as $hid) - { - $tpl->setCurrentBlock("add_dhtml"); - $tpl->setVariable("CONTEXTMENU", "contextmenu_i".$hid); - $tpl->parseCurrentBlock(); - } - - // file item menues - foreach($fitem_ids as $hid) - { - $tpl->setCurrentBlock("add_dhtml"); - $tpl->setVariable("CONTEXTMENU", "contextmenu_i".$hid); - $tpl->parseCurrentBlock(); - } - } - else - { - $this->obj->addFileSizes(); - } - -//echo "
          -".htmlentities($this->obj->getXMLContent())."-

          "; exit; -//echo "
          -".htmlentities($this->getLinkXML())."-"; exit; - - // set default link xml, if nothing was set yet - if (!$this->link_xml_set) - { - $this->setDefaultLinkXml(); - } - - //$content = $this->obj->getXMLFromDom(false, true, true, - // $this->getLinkXML().$this->getQuestionXML().$this->getComponentPluginsXML()); - $link_xml = $this->getLinkXML(); -//echo "
          -".htmlentities($link_xml)."-"; exit; - // disable/enable auto margins - if ($this->getStyleId() > 0) - { - if (ilObject::_lookupType($this->getStyleId()) == "sty") - { - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $style = new ilObjStyleSheet($this->getStyleId()); - $template_xml = $style->getTemplateXML(); - $disable_auto_margins = "n"; - if ($style->lookupStyleSetting("disable_auto_margins")) - { - $disable_auto_margins = "y"; - } - } - } - - if ($this->getAbstractOnly()) - { - $content = "". - $this->obj->getFirstParagraphText().$link_xml. - ""; - } - else - { - $content = $this->obj->getXMLFromDom(false, true, true, - $link_xml.$this->getQuestionXML().$template_xml.$this->getComponentPluginsXML()); - } - - // check validation errors - if($builded !== true) - { - $this->displayValidationError($builded); - } - else - { - $this->displayValidationError($_SESSION["il_pg_error"]); - } - unset($_SESSION["il_pg_error"]); - - // get title - $pg_title = $this->getPresentationTitle(); - - if($this->getOutputMode() == "edit") - { - $col_path = ilUtil::getImagePath("col.svg"); - $row_path = ilUtil::getImagePath("row.svg"); - $item_path = ilUtil::getImagePath("item.svg"); - $cell_path = ilUtil::getImagePath("cell.svg"); - } - - if ($this->getOutputMode() != "offline") - { - $enlarge_path = ilUtil::getImagePath("enlarge.svg"); - $wb_path = ilUtil::getWebspaceDir("output")."/"; - } - else - { - $enlarge_path = "images/enlarge.svg"; - $wb_path = ""; - } - $pg_title_class = ($this->getOutputMode() == "print") - ? "ilc_PrintPageTitle" - : ""; - - // page splitting only for learning modules and - // digital books - $enable_split_new = ($this->obj->getParentType() == "lm") - ? "y" - : "n"; - - // page splitting to next page only for learning modules and - // digital books if next page exists in tree - if (($this->obj->getParentType() == "lm") && - ilObjContentObject::hasSuccessorPage($this->obj->getParentId(), - $this->obj->getId())) - { - $enable_split_next = "y"; - } - else - { - $enable_split_next = "n"; - } - - $img_path = ilUtil::getImagePath("", false, $this->getOutputMode(), $this->getOutputMode() == "offline"); - - - if ($this->getPageConfig()->getEnablePCType("Tabs")) - { - //include_once("./Services/YUI/classes/class.ilYuiUtil.php"); - //ilYuiUtil::initTabView(); - include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); - ilAccordionGUI::addJavaScript(); - ilAccordionGUI::addCss(); - } - - $file_download_link = $this->determineFileDownloadLink(); - $fullscreen_link = $this->determineFullscreenLink(); - $this->sourcecode_download_script = $this->determineSourcecodeDownloadScript(); - - // default values for various parameters (should be used by - // all instances in the future) - $media_mode = ($this->getOutputMode() == "edit") - ? $this->user->getPref("ilPageEditor_MediaMode") - : "enable"; - - include_once("./Modules/LearningModule/classes/class.ilEditClipboard.php"); - $paste = (ilEditClipboard::getAction() == "copy" && - $this->getOutputMode() == "edit"); - - include_once("./Services/MediaObjects/classes/class.ilPlayerUtil.php"); - - $flv_video_player = ($this->getOutputMode() != "offline") - ? ilPlayerUtil::getFlashVideoPlayerFilename(true) - : ilPlayerUtil::getFlashVideoPlayerFilename(true); - - $cfg = $this->getPageConfig(); - - $current_ts = time(); - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - - // added UTF-8 encoding otherwise umlaute are converted too - include_once("./Services/Maps/classes/class.ilMapUtil.php"); - $params = array ('mode' => $this->getOutputMode(), 'pg_title' => htmlentities($pg_title,ENT_QUOTES,"UTF-8"), - 'enable_placeholder' => $cfg->getEnablePCType("PlaceHolder") ? "y" : "n", - 'pg_id' => $this->obj->getId(), 'pg_title_class' => $pg_title_class, - 'webspace_path' => $wb_path, 'enlarge_path' => $enlarge_path, - 'img_col' => $col_path, - 'img_row' => $row_path, - 'img_cell' => $cell_path, - 'img_item' => $item_path, - 'compare_mode' => $this->getCompareMode() ? "y" : "n", - 'enable_split_new' => $enable_split_new, - 'enable_split_next' => $enable_split_next, - 'link_params' => $this->link_params, - 'file_download_link' => $file_download_link, - 'fullscreen_link' => $fullscreen_link, - 'img_path' => $img_path, - 'parent_id' => $this->obj->getParentId(), - 'download_script' => $this->sourcecode_download_script, - 'encoded_download_script' => urlencode($this->sourcecode_download_script), - 'enable_rep_objects' => $cfg->getEnablePCType("Resources") ? "y" : "n", - 'enable_login_page' => $cfg->getEnablePCType("LoginPageElement") ? "y" : "n", - 'enable_map' => ($cfg->getEnablePCType("Map") && ilMapUtil::isActivated()) ? "y" : "n", - 'enable_tabs' => $cfg->getEnablePCType("Tabs") ? "y" : "n", - 'enable_sa_qst' => $cfg->getEnableSelfAssessment() ? "y" : "n", - 'enable_file_list' => $cfg->getEnablePCType("FileList") ? "y" : "n", - 'enable_content_includes' => $cfg->getEnablePCType("ContentInclude") ? "y" : "n", - 'enable_content_templates' => (count($this->getPageObject()->getContentTemplates()) > 0) ? "y" : "n", - 'paste' => $paste ? "y" : "n", - 'media_mode' => $media_mode, - 'javascript' => $sel_js_mode, - 'paragraph_plugins' => $paragraph_plugin_string, - 'disable_auto_margins' => $disable_auto_margins, - 'page_toc' => $cfg->getEnablePageToc() ? "y" : "n", - 'enable_profile' => $cfg->getEnablePCType("Profile") ? "y" : "n", - 'enable_verification' => $cfg->getEnablePCType("Verification") ? "y" : "n", - 'enable_blog' => $cfg->getEnablePCType("Blog") ? "y" : "n", - 'enable_skills' => $cfg->getEnablePCType("Skills") ? "y" : "n", - 'enable_learning_history' => $cfg->getEnablePCType("LearningHistory") ? "y" : "n", - 'enable_qover' => $cfg->getEnablePCType("QuestionOverview") ? "y" : "n", - 'enable_consultation_hours' => $cfg->getEnablePCType("ConsultationHours") ? "y" : "n", - 'enable_my_courses' => $cfg->getEnablePCType("MyCourses") ? "y" : "n", - 'enable_amd_page_list' => $cfg->getEnablePCType("AMDPageList") ? "y" : "n", - 'current_ts' => $current_ts, - 'enable_html_mob' => ilObjMediaObject::isTypeAllowed("html") ? "y" : "n", - 'flv_video_player' => $flv_video_player, - 'page_perma_link' => $this->getPagePermaLink() - ); - if($this->link_frame != "") // todo other link types - $params["pg_frame"] = $this->link_frame; - - //$content = str_replace(" ", "", $content); - - // this ensures that cache is emptied with every update - $params["version"] = ILIAS_VERSION; - // ensure no cache hit, if included files/media objects have been changed - $params["incl_elements_date"] = $this->obj->getLastUpdateOfIncludedElements(); - - - // should be modularized - include_once("./Services/COPage/classes/class.ilPCSection.php"); - $md5_adds = ilPCSection::getCacheTriggerString($this->getPageObject()); - - // run xslt - $md5 = md5(serialize($params).$link_xml.$template_xml.$md5_adds); - -//$a = microtime(); - - // check cache (same parameters, non-edit mode and rendered time - // > last change - if (($this->getOutputMode() == "preview" || $this->getOutputMode() == "presentation") && - !$this->getCompareMode() && - !$this->getAbstractOnly() && - $md5 == $this->obj->getRenderMd5() && - ($this->obj->getLastChange() < $this->obj->getRenderedTime()) && - $this->obj->getRenderedTime() != "" && - $this->obj->old_nr == 0) - { - // cache hit - $output = $this->obj->getRenderedContent(); - } - else - { - $xsl = file_get_contents("./Services/COPage/xsl/page.xsl"); - - $this->log->debug("Calling XSLT, content: ".substr($content, 0, 100)); - $args = array( '/_xml' => $content, '/_xsl' => $xsl ); - $xh = xslt_create(); - $output = xslt_process($xh, "arg:/_xml","arg:/_xsl", NULL, $args, $params); - - if (($this->getOutputMode() == "presentation" || $this->getOutputMode() == "preview") - && !$this->getAbstractOnly() - && $this->obj->old_nr == 0) - { - $this->obj->writeRenderedContent($output, $md5); - } - xslt_free($xh); - } - - // unmask user html - if (($this->getOutputMode() != "edit" || - $this->user->getPref("ilPageEditor_HTMLMode") != "disable") - && !$this->getPageConfig()->getPreventHTMLUnmasking()) - { - $output = str_replace("<","<",$output); - $output = str_replace(">",">",$output); - } - $output = str_replace("&", "&", $output); - - include_once './Services/MathJax/classes/class.ilMathJax.php'; - $output = ilMathJax::getInstance()->insertLatexImages($output); - - // insert page snippets - //$output = $this->insertContentIncludes($output); - - // insert resource blocks - $output = $this->insertResources($output); - - // insert page toc - if ($this->getPageConfig()->getEnablePageToc()) - { - $output = $this->insertPageToc($output); - } - - // insert advanced output trigger - $output = $this->insertAdvTrigger($output); - - // workaround for preventing template engine - // from hiding paragraph text that is enclosed - // in curly brackets (e.g. "{a}", see ilLMEditorGUI::executeCommand()) - $output = $this->replaceCurlyBrackets($output); - - // remove all newlines (important for code / pre output) - $output = str_replace("\n", "", $output); - -//echo htmlentities($output); - $output = $this->postOutputProcessing($output); -//echo htmlentities($output); - if($this->getOutputMode() == "edit" && - !$this->getPageObject()->getActive($this->getPageConfig()->getEnableScheduledActivation())) - { - $output = '
          '.$this->getDisabledText().'
          '.$output.'
          '; - } - - // for all page components... - include_once("./Services/COPage/classes/class.ilCOPagePCDef.php"); - $defs = ilCOPagePCDef::getPCDefinitions(); - foreach ($defs as $def) - { - ilCOPagePCDef::requirePCClassByName($def["name"]); - $pc_class = $def["pc_class"]; - $pc_obj = new $pc_class($this->getPageObject()); - $pc_obj->setSourcecodeDownloadScript($this->determineSourcecodeDownloadScript()); - $pc_obj->setFileDownloadLink($this->determineFileDownloadLink()); - $pc_obj->setFullscreenLink($this->determineFullscreenLink()); - - // post xsl page content modification by pc elements - $output = $pc_obj->modifyPageContentPostXsl($output, $this->getOutputMode()); - - // javascript files - $js_files = $pc_obj->getJavascriptFiles($this->getOutputMode()); - foreach ($js_files as $js) - { - $GLOBALS["tpl"]->addJavascript($js); - } - - // css files - $css_files = $pc_obj->getCssFiles($this->getOutputMode()); - foreach ($css_files as $css) - { - $GLOBALS["tpl"]->addCss($css); - } - - // onload code - $onload_code = $pc_obj->getOnloadCode($this->getOutputMode()); - foreach ($onload_code as $code) - { - $GLOBALS["tpl"]->addOnloadCode($code); - } - } - -// $output = $this->selfAssessmentRendering($output); - - // output - if ($this->ctrl->isAsynch() && !$this->getRawPageContent() && - $this->getOutputMode() == "edit") - { - // e.g. ###3:110dad8bad6df8620071a0a693a2d328### - if ($_GET["updated_pc_id_str"] != "") - { - echo $_GET["updated_pc_id_str"]; - } - $tpl->setVariable($this->getTemplateOutputVar(), $output); - $tpl->setCurrentBlock("edit_page"); - $tpl->parseCurrentBlock(); - echo $tpl->get("edit_page"); - exit; - } - if ($this->outputToTemplate()) - { - $tpl->setVariable($this->getTemplateOutputVar(), $output); - $this->tpl->setVariable($this->getTemplateTargetVar(), $tpl->get()); + ilCOPage.setUser('" . $this->user->getLogin() . "'); + ilCOPage.setContentCss('" . + ilObjStyleSheet::getContentStylePath((int) $this->getStyleId()) . + ", " . ilUtil::getStyleSheetLocation() . + ", ./Services/COPage/css/tiny_extra.css" . + "')"); + include_once("./Services/COPage/classes/class.ilPCParagraphGUI.php"); + foreach (ilPCParagraphGUI::_getTextCharacteristics($this->getStyleId()) as $c) { + $GLOBALS["tpl"]->addOnloadCode("ilCOPage.addTextFormat('" . $c . "');"); + } + + $GLOBALS["tpl"]->addJavascript("./libs/bower/bower_components/tinymce/tinymce.min.js"); + $tpl->touchBlock("init_dragging"); + + $cfg = $this->getPageConfig(); + $tpl->setVariable( + "IL_TINY_MENU", + self::getTinyMenu( + $this->getPageObject()->getParentType(), + $cfg->getEnableInternalLinks(), + $cfg->getEnableWikiLinks(), + $cfg->getEnableKeywords(), + $this->getStyleId(), + true, + true, + $cfg->getEnableAnchors(), + true, + $cfg->getEnableUserLinks() + ) + ); + + // add int link parts + include_once("./Services/Link/classes/class.ilInternalLinkGUI.php"); + $tpl->setCurrentBlock("int_link_prep"); + $tpl->setVariable("INT_LINK_PREP", ilInternalLinkGUI::getInitHTML( + $this->ctrl->getLinkTargetByClass( + array("ilpageeditorgui", "ilinternallinkgui"), + "", + false, + true, + false + ) + )); + $tpl->parseCurrentBlock(); + + include_once("./Services/YUI/classes/class.ilYuiUtil.php"); + ilYuiUtil::initConnection(); + $GLOBALS["tpl"]->addJavaScript("./Services/UIComponent/Explorer/js/ilExplorer.js"); + } + + // multiple actions + $cnt_pcs = $this->getPageObject()->countPageContents(); + if ($cnt_pcs > 1 || + ($this->getPageObject()->getParentType() != "qpl" && $cnt_pcs > 0)) { + $tpl->setCurrentBlock("multi_actions"); + if ($sel_js_mode == "enable") { + $tpl->setVariable("ONCLICK_DE_ACTIVATE_SELECTED", 'onclick="return ilEditMultiAction(\'activateSelected\');"'); + $tpl->setVariable("ONCLICK_DELETE_SELECTED", 'onclick="return ilEditMultiAction(\'deleteSelected\');"'); + $tpl->setVariable("ONCLICK_ASSIGN_CHARACTERISTIC", 'onclick="return ilEditMultiAction(\'assignCharacteristicForm\');"'); + $tpl->setVariable("ONCLICK_COPY_SELECTED", 'onclick="return ilEditMultiAction(\'copySelected\');"'); + $tpl->setVariable("ONCLICK_CUT_SELECTED", 'onclick="return ilEditMultiAction(\'cutSelected\');"'); + $tpl->setVariable("TXT_SELECT_ALL", $this->lng->txt("select_all")); + $tpl->setVariable("ONCLICK_SELECT_ALL", 'onclick="return ilEditMultiAction(\'selectAll\');"'); + } + $tpl->setVariable("TXT_DE_ACTIVATE_SELECTED", $this->lng->txt("cont_ed_enable")); + $tpl->setVariable("TXT_ASSIGN_CHARACTERISTIC", $this->lng->txt("cont_assign_characteristic")); + $tpl->setVariable("TXT_DELETE_SELECTED", $this->lng->txt("cont_delete_selected")); + $tpl->setVariable("TXT_COPY_SELECTED", $this->lng->txt("copy")); + $tpl->setVariable("TXT_CUT_SELECTED", $this->lng->txt("cut")); + $tpl->setVariable("IMG_ARROW", ilUtil::getImagePath("arrow_downright.svg")); + $tpl->parseCurrentBlock(); + } + } else { + // presentation or preview here + + $tpl = new ilTemplate("tpl.page.html", true, true, "Services/COPage"); + if ($this->getEnabledPageFocus()) { + $tpl->touchBlock("page_focus"); + } + + include_once("./Services/User/classes/class.ilUserUtil.php"); + + // presentation + if ($this->isPageContainerToBeRendered()) { + $tpl->touchBlock("page_container_1"); + $tpl->touchBlock("page_container_2"); + $tpl->touchBlock("page_container_3"); + } + + // history + $c_old_nr = $this->getPageObject()->old_nr; + if ($c_old_nr > 0 || $this->getCompareMode() || $_GET["history_mode"] == 1) { + $hist_info = + $this->getPageObject()->getHistoryInfo($c_old_nr); + + if (!$this->getCompareMode()) { + $this->ctrl->setParameter($this, "history_mode", "1"); + + // previous revision + if (is_array($hist_info["previous"])) { + $tpl->setCurrentBlock("previous_rev"); + $tpl->setVariable("TXT_PREV_REV", $this->lng->txt("cont_previous_rev")); + $this->ctrl->setParameter($this, "old_nr", $hist_info["previous"]["nr"]); + $tpl->setVariable( + "HREF_PREV", + $this->ctrl->getLinkTarget($this, "preview") + ); + $tpl->parseCurrentBlock(); + } else { + $tpl->setCurrentBlock("previous_rev_disabled"); + $tpl->setVariable("TXT_PREV_REV", $this->lng->txt("cont_previous_rev")); + $tpl->parseCurrentBlock(); + } + + // next revision + if ($c_old_nr > 0) { + $tpl->setCurrentBlock("next_rev"); + $tpl->setVariable("TXT_NEXT_REV", $this->lng->txt("cont_next_rev")); + $this->ctrl->setParameter($this, "old_nr", $hist_info["next"]["nr"]); + $tpl->setVariable( + "HREF_NEXT", + $this->ctrl->getLinkTarget($this, "preview") + ); + $tpl->parseCurrentBlock(); + + // latest revision + $tpl->setCurrentBlock("latest_rev"); + $tpl->setVariable("TXT_LATEST_REV", $this->lng->txt("cont_latest_rev")); + $this->ctrl->setParameter($this, "old_nr", ""); + $tpl->setVariable( + "HREF_LATEST", + $this->ctrl->getLinkTarget($this, "preview") + ); + $tpl->parseCurrentBlock(); + } + + $this->ctrl->setParameter($this, "history_mode", ""); + + // rollback + if ($c_old_nr > 0 && $this->user->getId() != ANONYMOUS_USER_ID) { + $tpl->setCurrentBlock("rollback"); + $this->ctrl->setParameter($this, "old_nr", $c_old_nr); + $tpl->setVariable( + "HREF_ROLLBACK", + $this->ctrl->getLinkTarget($this, "rollbackConfirmation") + ); + $this->ctrl->setParameter($this, "old_nr", ""); + $tpl->setVariable( + "TXT_ROLLBACK", + $this->lng->txt("cont_rollback") + ); + $tpl->parseCurrentBlock(); + } + } + + $tpl->setCurrentBlock("hist_nav"); + $tpl->setVariable("TXT_REVISION", $this->lng->txt("cont_revision")); + $tpl->setVariable( + "VAL_REVISION_DATE", + ilDatePresentation::formatDate(new ilDateTime($hist_info["current"]["hdate"], IL_CAL_DATETIME)) + ); + $tpl->setVariable( + "VAL_REV_USER", + ilUserUtil::getNamePresentation($hist_info["current"]["user_id"]) + ); + $tpl->parseCurrentBlock(); + } + } + if ($this->getOutputMode() != IL_PAGE_PRESENTATION && + $this->getOutputMode() != IL_PAGE_OFFLINE && + $this->getOutputMode() != IL_PAGE_PREVIEW && + $this->getOutputMode() != IL_PAGE_PRINT) { + $tpl->setVariable("FORMACTION", $this->ctrl->getFormActionByClass("ilpageeditorgui")); + } + + // output media object edit list (of media links) + if ($this->getOutputMode() == "edit") { + $links = ilInternalLink::_getTargetsOfSource( + $this->obj->getParentType() . ":pg", + $this->obj->getId(), + $this->obj->getLanguage() + ); + $mob_links = array(); + foreach ($links as $link) { + if ($link["type"] == "mob") { + if (ilObject::_exists($link["id"]) && ilObject::_lookupType($link["id"]) == "mob") { + $mob_links[$link["id"]] = ilObject::_lookupTitle($link["id"]) . " [" . $link["id"] . "]"; + } + } + } + + // linked media objects + if (count($mob_links) > 0) { + $tpl->setCurrentBlock("med_link"); + $tpl->setVariable("TXT_LINKED_MOBS", $this->lng->txt("cont_linked_mobs")); + $tpl->setVariable( + "SEL_MED_LINKS", + ilUtil::formSelect(0, "mob_id", $mob_links, false, true) + ); + $tpl->setVariable("TXT_EDIT_MEDIA", $this->lng->txt("cont_edit_mob")); + $tpl->setVariable("TXT_COPY_TO_CLIPBOARD", $this->lng->txt("cont_copy_to_clipboard")); + //$this->tpl->setVariable("TXT_COPY_TO_POOL", $this->lng->txt("cont_copy_to_mediapool")); + $tpl->parseCurrentBlock(); + } + + // content snippets used + include_once("./Services/COPage/classes/class.ilPCContentInclude.php"); + $snippets = ilPCContentInclude::collectContentIncludes( + $this->getPageObject(), + $this->getPageObject()->getDomDoc() + ); + if (count($snippets) > 0) { + foreach ($snippets as $s) { + include_once("./Modules/MediaPool/classes/class.ilMediaPoolPage.php"); + $sn_arr[$s["id"]] = ilMediaPoolPage::lookupTitle($s["id"]); + } + $tpl->setCurrentBlock("med_link"); + $tpl->setVariable("TXT_CONTENT_SNIPPETS_USED", $this->lng->txt("cont_snippets_used")); + $tpl->setVariable( + "SEL_SNIPPETS", + ilUtil::formSelect(0, "ci_id", $sn_arr, false, true) + ); + $tpl->setVariable("TXT_SHOW_INFO", $this->lng->txt("cont_show_info")); + $tpl->parseCurrentBlock(); + } + + // scheduled activation? + if (!$this->getPageObject()->getActive() && + $this->getPageObject()->getActivationStart() != "" && + $this->getPageConfig()->getEnableScheduledActivation()) { + $tpl->setCurrentBlock("activation_txt"); + $tpl->setVariable("TXT_SCHEDULED_ACTIVATION", $this->lng->txt("cont_scheduled_activation")); + $tpl->setVariable( + "SA_FROM", + ilDatePresentation::formatDate( + new ilDateTime( + $this->getPageObject()->getActivationStart(), + IL_CAL_DATETIME + ) + ) + ); + $tpl->setVariable( + "SA_TO", + ilDatePresentation::formatDate( + new ilDateTime( + $this->getPageObject()->getActivationEnd(), + IL_CAL_DATETIME + ) + ) + ); + $tpl->parseCurrentBlock(); + } + } + + if ($_GET["reloadTree"] == "y") { + $tpl->setCurrentBlock("reload_tree"); + $tpl->setVariable( + "LINK_TREE", + $this->ctrl->getLinkTargetByClass("ilobjlearningmodulegui", "explorer", "", false, false) + ); + $tpl->parseCurrentBlock(); + } + // } + // get content + $builded = $this->obj->buildDom(); + + // manage hierarchical ids + if ($this->getOutputMode() == "edit") { + + // add pc ids, if necessary + if (!$this->obj->checkPCIds()) { + $this->obj->insertPCIds(); + $this->obj->update(true, true); + } + + $this->obj->addFileSizes(); + $this->obj->addHierIDs(); + + $hids = $this->obj->getHierIds(); + $row1_ids = $this->obj->getFirstRowIds(); + $col1_ids = $this->obj->getFirstColumnIds(); + $litem_ids = $this->obj->getListItemIds(); + $fitem_ids = $this->obj->getFileItemIds(); + + // standard menues + $hids = $this->obj->getHierIds(); + foreach ($hids as $hid) { + $tpl->setCurrentBlock("add_dhtml"); + $tpl->setVariable("CONTEXTMENU", "contextmenu_" . $hid); + $tpl->parseCurrentBlock(); + } + + // column menues for tables + foreach ($col1_ids as $hid) { + $tpl->setCurrentBlock("add_dhtml"); + $tpl->setVariable("CONTEXTMENU", "contextmenu_r" . $hid); + $tpl->parseCurrentBlock(); + } + + // row menues for tables + foreach ($row1_ids as $hid) { + $tpl->setCurrentBlock("add_dhtml"); + $tpl->setVariable("CONTEXTMENU", "contextmenu_c" . $hid); + $tpl->parseCurrentBlock(); + } + + // list item menues + foreach ($litem_ids as $hid) { + $tpl->setCurrentBlock("add_dhtml"); + $tpl->setVariable("CONTEXTMENU", "contextmenu_i" . $hid); + $tpl->parseCurrentBlock(); + } + + // file item menues + foreach ($fitem_ids as $hid) { + $tpl->setCurrentBlock("add_dhtml"); + $tpl->setVariable("CONTEXTMENU", "contextmenu_i" . $hid); + $tpl->parseCurrentBlock(); + } + } else { + $this->obj->addFileSizes(); + } + + //echo "
          -".htmlentities($this->obj->getXMLContent())."-

          "; exit; + //echo "
          -".htmlentities($this->getLinkXML())."-"; exit; + + // set default link xml, if nothing was set yet + if (!$this->link_xml_set) { + $this->setDefaultLinkXml(); + } + + //$content = $this->obj->getXMLFromDom(false, true, true, + // $this->getLinkXML().$this->getQuestionXML().$this->getComponentPluginsXML()); + $link_xml = $this->getLinkXML(); + //echo "
          -".htmlentities($link_xml)."-"; exit; + // disable/enable auto margins + if ($this->getStyleId() > 0) { + if (ilObject::_lookupType($this->getStyleId()) == "sty") { + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $style = new ilObjStyleSheet($this->getStyleId()); + $template_xml = $style->getTemplateXML(); + $disable_auto_margins = "n"; + if ($style->lookupStyleSetting("disable_auto_margins")) { + $disable_auto_margins = "y"; + } + } + } + + if ($this->getAbstractOnly()) { + $content = "" . + $this->obj->getFirstParagraphText() . $link_xml . + ""; + } else { + $content = $this->obj->getXMLFromDom( + false, + true, + true, + $link_xml . $this->getQuestionXML() . $template_xml . $this->getComponentPluginsXML() + ); + } + + // check validation errors + if ($builded !== true) { + $this->displayValidationError($builded); + } else { + $this->displayValidationError($_SESSION["il_pg_error"]); + } + unset($_SESSION["il_pg_error"]); + + // get title + $pg_title = $this->getPresentationTitle(); + + if ($this->getOutputMode() == "edit") { + $col_path = ilUtil::getImagePath("col.svg"); + $row_path = ilUtil::getImagePath("row.svg"); + $item_path = ilUtil::getImagePath("item.svg"); + $cell_path = ilUtil::getImagePath("cell.svg"); + } + + if ($this->getOutputMode() != "offline") { + $enlarge_path = ilUtil::getImagePath("enlarge.svg"); + $wb_path = ilUtil::getWebspaceDir("output") . "/"; + } else { + $enlarge_path = "images/enlarge.svg"; + $wb_path = ""; + } + $pg_title_class = ($this->getOutputMode() == "print") + ? "ilc_PrintPageTitle" + : ""; + + // page splitting only for learning modules and + // digital books + $enable_split_new = ($this->obj->getParentType() == "lm") + ? "y" + : "n"; + + // page splitting to next page only for learning modules and + // digital books if next page exists in tree + if (($this->obj->getParentType() == "lm") && + ilObjContentObject::hasSuccessorPage( + $this->obj->getParentId(), + $this->obj->getId() + )) { + $enable_split_next = "y"; + } else { + $enable_split_next = "n"; + } + + $img_path = ilUtil::getImagePath("", false, $this->getOutputMode(), $this->getOutputMode() == "offline"); + + + if ($this->getPageConfig()->getEnablePCType("Tabs")) { + //include_once("./Services/YUI/classes/class.ilYuiUtil.php"); + //ilYuiUtil::initTabView(); + include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); + ilAccordionGUI::addJavaScript(); + ilAccordionGUI::addCss(); + } + + $file_download_link = $this->determineFileDownloadLink(); + $fullscreen_link = $this->determineFullscreenLink(); + $this->sourcecode_download_script = $this->determineSourcecodeDownloadScript(); + + // default values for various parameters (should be used by + // all instances in the future) + $media_mode = ($this->getOutputMode() == "edit") + ? $this->user->getPref("ilPageEditor_MediaMode") + : "enable"; + + include_once("./Modules/LearningModule/classes/class.ilEditClipboard.php"); + $paste = (ilEditClipboard::getAction() == "copy" && + $this->getOutputMode() == "edit"); + + include_once("./Services/MediaObjects/classes/class.ilPlayerUtil.php"); + + $flv_video_player = ($this->getOutputMode() != "offline") + ? ilPlayerUtil::getFlashVideoPlayerFilename(true) + : ilPlayerUtil::getFlashVideoPlayerFilename(true); + + $cfg = $this->getPageConfig(); + + $current_ts = time(); + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + + // added UTF-8 encoding otherwise umlaute are converted too + include_once("./Services/Maps/classes/class.ilMapUtil.php"); + $params = array('mode' => $this->getOutputMode(), 'pg_title' => htmlentities($pg_title, ENT_QUOTES, "UTF-8"), + 'enable_placeholder' => $cfg->getEnablePCType("PlaceHolder") ? "y" : "n", + 'pg_id' => $this->obj->getId(), 'pg_title_class' => $pg_title_class, + 'webspace_path' => $wb_path, 'enlarge_path' => $enlarge_path, + 'img_col' => $col_path, + 'img_row' => $row_path, + 'img_cell' => $cell_path, + 'img_item' => $item_path, + 'compare_mode' => $this->getCompareMode() ? "y" : "n", + 'enable_split_new' => $enable_split_new, + 'enable_split_next' => $enable_split_next, + 'link_params' => $this->link_params, + 'file_download_link' => $file_download_link, + 'fullscreen_link' => $fullscreen_link, + 'img_path' => $img_path, + 'parent_id' => $this->obj->getParentId(), + 'download_script' => $this->sourcecode_download_script, + 'encoded_download_script' => urlencode($this->sourcecode_download_script), + 'enable_rep_objects' => $cfg->getEnablePCType("Resources") ? "y" : "n", + 'enable_login_page' => $cfg->getEnablePCType("LoginPageElement") ? "y" : "n", + 'enable_map' => ($cfg->getEnablePCType("Map") && ilMapUtil::isActivated()) ? "y" : "n", + 'enable_tabs' => $cfg->getEnablePCType("Tabs") ? "y" : "n", + 'enable_sa_qst' => $cfg->getEnableSelfAssessment() ? "y" : "n", + 'enable_file_list' => $cfg->getEnablePCType("FileList") ? "y" : "n", + 'enable_content_includes' => $cfg->getEnablePCType("ContentInclude") ? "y" : "n", + 'enable_content_templates' => (count($this->getPageObject()->getContentTemplates()) > 0) ? "y" : "n", + 'paste' => $paste ? "y" : "n", + 'media_mode' => $media_mode, + 'javascript' => $sel_js_mode, + 'paragraph_plugins' => $paragraph_plugin_string, + 'disable_auto_margins' => $disable_auto_margins, + 'page_toc' => $cfg->getEnablePageToc() ? "y" : "n", + 'enable_profile' => $cfg->getEnablePCType("Profile") ? "y" : "n", + 'enable_verification' => $cfg->getEnablePCType("Verification") ? "y" : "n", + 'enable_blog' => $cfg->getEnablePCType("Blog") ? "y" : "n", + 'enable_skills' => $cfg->getEnablePCType("Skills") ? "y" : "n", + 'enable_learning_history' => $cfg->getEnablePCType("LearningHistory") ? "y" : "n", + 'enable_qover' => $cfg->getEnablePCType("QuestionOverview") ? "y" : "n", + 'enable_consultation_hours' => $cfg->getEnablePCType("ConsultationHours") ? "y" : "n", + 'enable_my_courses' => $cfg->getEnablePCType("MyCourses") ? "y" : "n", + 'enable_amd_page_list' => $cfg->getEnablePCType("AMDPageList") ? "y" : "n", + 'current_ts' => $current_ts, + 'enable_html_mob' => ilObjMediaObject::isTypeAllowed("html") ? "y" : "n", + 'flv_video_player' => $flv_video_player, + 'page_perma_link' => $this->getPagePermaLink() + ); + if ($this->link_frame != "") { // todo other link types + $params["pg_frame"] = $this->link_frame; + } + + //$content = str_replace(" ", "", $content); + + // this ensures that cache is emptied with every update + $params["version"] = ILIAS_VERSION; + // ensure no cache hit, if included files/media objects have been changed + $params["incl_elements_date"] = $this->obj->getLastUpdateOfIncludedElements(); + + + // should be modularized + include_once("./Services/COPage/classes/class.ilPCSection.php"); + $md5_adds = ilPCSection::getCacheTriggerString($this->getPageObject()); + + // run xslt + $md5 = md5(serialize($params) . $link_xml . $template_xml . $md5_adds); + + //$a = microtime(); + + // check cache (same parameters, non-edit mode and rendered time + // > last change + if (($this->getOutputMode() == "preview" || $this->getOutputMode() == "presentation") && + !$this->getCompareMode() && + !$this->getAbstractOnly() && + $md5 == $this->obj->getRenderMd5() && + ($this->obj->getLastChange() < $this->obj->getRenderedTime()) && + $this->obj->getRenderedTime() != "" && + $this->obj->old_nr == 0) { + // cache hit + $output = $this->obj->getRenderedContent(); + } else { + $xsl = file_get_contents("./Services/COPage/xsl/page.xsl"); + + $this->log->debug("Calling XSLT, content: " . substr($content, 0, 100)); + $args = array( '/_xml' => $content, '/_xsl' => $xsl ); + $xh = xslt_create(); + $output = xslt_process($xh, "arg:/_xml", "arg:/_xsl", null, $args, $params); + + if (($this->getOutputMode() == "presentation" || $this->getOutputMode() == "preview") + && !$this->getAbstractOnly() + && $this->obj->old_nr == 0) { + $this->obj->writeRenderedContent($output, $md5); + } + xslt_free($xh); + } + + // unmask user html + if (($this->getOutputMode() != "edit" || + $this->user->getPref("ilPageEditor_HTMLMode") != "disable") + && !$this->getPageConfig()->getPreventHTMLUnmasking()) { + $output = str_replace("<", "<", $output); + $output = str_replace(">", ">", $output); + } + $output = str_replace("&", "&", $output); + + include_once './Services/MathJax/classes/class.ilMathJax.php'; + $output = ilMathJax::getInstance()->insertLatexImages($output); + + // insert page snippets + //$output = $this->insertContentIncludes($output); + + // insert resource blocks + $output = $this->insertResources($output); + + // insert page toc + if ($this->getPageConfig()->getEnablePageToc()) { + $output = $this->insertPageToc($output); + } + + // insert advanced output trigger + $output = $this->insertAdvTrigger($output); + + // workaround for preventing template engine + // from hiding paragraph text that is enclosed + // in curly brackets (e.g. "{a}", see ilLMEditorGUI::executeCommand()) + $output = $this->replaceCurlyBrackets($output); + + // remove all newlines (important for code / pre output) + $output = str_replace("\n", "", $output); + + //echo htmlentities($output); + $output = $this->postOutputProcessing($output); + //echo htmlentities($output); + if ($this->getOutputMode() == "edit" && + !$this->getPageObject()->getActive($this->getPageConfig()->getEnableScheduledActivation())) { + $output = '
          ' . $this->getDisabledText() . '
          ' . $output . '
          '; + } + + // for all page components... + include_once("./Services/COPage/classes/class.ilCOPagePCDef.php"); + $defs = ilCOPagePCDef::getPCDefinitions(); + foreach ($defs as $def) { + ilCOPagePCDef::requirePCClassByName($def["name"]); + $pc_class = $def["pc_class"]; + $pc_obj = new $pc_class($this->getPageObject()); + $pc_obj->setSourcecodeDownloadScript($this->determineSourcecodeDownloadScript()); + $pc_obj->setFileDownloadLink($this->determineFileDownloadLink()); + $pc_obj->setFullscreenLink($this->determineFullscreenLink()); + + // post xsl page content modification by pc elements + $output = $pc_obj->modifyPageContentPostXsl($output, $this->getOutputMode()); + + // javascript files + $js_files = $pc_obj->getJavascriptFiles($this->getOutputMode()); + foreach ($js_files as $js) { + $GLOBALS["tpl"]->addJavascript($js); + } + + // css files + $css_files = $pc_obj->getCssFiles($this->getOutputMode()); + foreach ($css_files as $css) { + $GLOBALS["tpl"]->addCss($css); + } + + // onload code + $onload_code = $pc_obj->getOnloadCode($this->getOutputMode()); + foreach ($onload_code as $code) { + $GLOBALS["tpl"]->addOnloadCode($code); + } + } + + // $output = $this->selfAssessmentRendering($output); + + // output + if ($this->ctrl->isAsynch() && !$this->getRawPageContent() && + $this->getOutputMode() == "edit") { + // e.g. ###3:110dad8bad6df8620071a0a693a2d328### + if ($_GET["updated_pc_id_str"] != "") { + echo $_GET["updated_pc_id_str"]; + } + $tpl->setVariable($this->getTemplateOutputVar(), $output); + $tpl->setCurrentBlock("edit_page"); + $tpl->parseCurrentBlock(); + echo $tpl->get("edit_page"); + exit; + } + if ($this->outputToTemplate()) { + $tpl->setVariable($this->getTemplateOutputVar(), $output); + $this->tpl->setVariable($this->getTemplateTargetVar(), $tpl->get()); return $output; - } - else - { - if ($this->getRawPageContent()) // e.g. needed in glossaries - { - return $output; - } - else - { - $tpl->setVariable($this->getTemplateOutputVar(), $output); - return $tpl->get(); - } - } - } - - /** - * Replace curly brackets - * - * @param - * @return - */ - function replaceCurlyBrackets($output) - { -//echo "

          ".htmlentities($output); - - while (is_int($start = strpos($output, "")) && - is_int($end = strpos($output, "", $start))) - { - $output = substr($output, 0, $start). - str_replace(array("{","}"), array("{","}"), - substr($output, $start + 15, $end - ($start + 15))). - substr($output, $end + 13); - } - -// $output = str_replace("{", "{", $output); -// $output = str_replace("}", "}", $output); -//echo "

          ".htmlentities($output); - return $output; - } - - /** - * Get captions for activation action menu entries - */ - protected function getActivationCaptions() - { - return array("deactivatePage" => $this->lng->txt("cont_deactivate_page"), - "activatePage" => $this->lng->txt("cont_activate_page")); - } - - /** - * Add actions menu - */ - function addActionsMenu($a_tpl, $sel_media_mode, $sel_html_mode, $sel_js_mode) - { - global $DIC; - - $ui = $DIC->ui(); - - // actions - include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"); - - // activate/deactivate - $list = new ilAdvancedSelectionListGUI(); - $list->setListTitle($this->lng->txt("actions")); - $list->setId("copage_act"); - $entries = false; - if ($this->getPageConfig()->getEnableActivation()) - { - - $entries = true; - $captions = $this->getActivationCaptions(); - - if ($this->getPageObject()->getActive()) - { - $list->addItem($captions["deactivatePage"], "", - $this->ctrl->getLinkTarget($this, "deactivatePage")); - } - else - { - $list->addItem($captions["activatePage"], "", - $this->ctrl->getLinkTarget($this, "activatePage")); - } - - $a_tpl->setVariable("PAGE_ACTIONS", $list->getHTML()); - } - - // initially opened content - if ($this->getPageConfig()->getUseAttachedContent()) - { - $entries = true; - $list->addItem($this->lng->txt("cont_initial_attached_content"), "", - $this->ctrl->getLinkTarget($this, "initialOpenedContent")); - } - - // multi-lang actions - if ($this->addMultiLangActionsAndInfo($list, $a_tpl)) - { - $entries = true; - } - - if ($entries) - { - $items = $list->getItems(); - if (count($items) > 1) - { - $a_tpl->setVariable("PAGE_ACTIONS", $list->getHTML()); - } - else if (count($items) == 1) - { - $b = $ui->factory()->button()->standard($items[0]["title"], $items[0]["link"]); - $a_tpl->setVariable("PAGE_ACTIONS", $ui->renderer()->render($b)); - } - } - - $this->lng->loadLanguageModule("content"); - $list = new ilAdvancedSelectionListGUI(); - $list->setListTitle($this->lng->txt("cont_edit_mode")); - $list->setId("copage_ed_mode"); - - // media mode - if ($sel_media_mode == "enable") - { - $this->ctrl->setParameter($this, "media_mode", "disable"); - $list->addItem($this->lng->txt("cont_deactivate_media"), "", - $this->ctrl->getLinkTarget($this, "setEditMode")); - } - else - { - $this->ctrl->setParameter($this, "media_mode", "enable"); - $list->addItem($this->lng->txt("cont_activate_media"), "", - $this->ctrl->getLinkTarget($this, "setEditMode")); - } - $this->ctrl->setParameter($this, "media_mode", ""); - - // html mode - if (!$this->getPageConfig()->getPreventHTMLUnmasking()) - { - if ($sel_html_mode == "enable") - { - $this->ctrl->setParameter($this, "html_mode", "disable"); - $list->addItem($this->lng->txt("cont_deactivate_html"), "", - $this->ctrl->getLinkTarget($this, "setEditMode")); - } - else - { - $this->ctrl->setParameter($this, "html_mode", "enable"); - $list->addItem($this->lng->txt("cont_activate_html"), "", - $this->ctrl->getLinkTarget($this, "setEditMode")); - } - } - $this->ctrl->setParameter($this, "html_mode", ""); - - // js mode - if ($sel_js_mode == "enable") - { - $this->ctrl->setParameter($this, "js_mode", "disable"); - $list->addItem($this->lng->txt("cont_deactivate_js"), "", - $this->ctrl->getLinkTarget($this, "setEditMode")); - } - else - { - $this->ctrl->setParameter($this, "js_mode", "enable"); - $list->addItem($this->lng->txt("cont_activate_js"), "", - $this->ctrl->getLinkTarget($this, "setEditMode")); - } - $this->ctrl->setParameter($this, "js_mode", ""); - - $a_tpl->setVariable("EDIT_MODE", $list->getHTML()); - } - - /** - * Add multi-language actions to menu - * - * @param - * @return - */ - function addMultiLangActionsAndInfo($a_list, $a_tpl) - { - $any_items = false; - - $cfg = $this->getPageConfig(); - - // general multi lang support and single page mode? - if ($cfg->getMultiLangSupport()) - { - //include_once("./Services/COPage/classes/class.ilPageMultiLang.php"); - //$ml = new ilPageMultiLang($this->getPageObject()->getParentType(), - // $this->getPageObject()->getParentId()); - - include_once("./Services/Object/classes/class.ilObjectTranslation.php"); - $ot = ilObjectTranslation::getInstance($this->getPageObject()->getParentId()); - - if (!$ot->getContentActivated()) - { -/* if ($cfg->getSinglePageMode()) - { - $a_list->addItem($this->lng->txt("cont_activate_multi_lang"), "", - $this->ctrl->getLinkTargetByClass("ilpagemultilanggui", "activateMultilinguality")); - - $any_items = true; - }*/ - } - else - { - $this->lng->loadLanguageModule("meta"); -//echo $this->getPageObject()->getLanguage(); - if ($this->getPageObject()->getLanguage() != "-") - { - $l = $ot->getMasterLanguage(); - $a_list->addItem($this->lng->txt("cont_edit_language_version").": ". - $this->lng->txt("meta_l_".$l), "", - $this->ctrl->getLinkTarget($this, "editMasterLanguage")); - } - - foreach ($ot->getLanguages() as $al => $lang) - { - if ($this->getPageObject()->getLanguage() != $al && - $al != $ot->getMasterLanguage()) - { - $this->ctrl->setParameter($this, "totransl", $al); - $a_list->addItem($this->lng->txt("cont_edit_language_version").": ". - $this->lng->txt("meta_l_".$al), "", - $this->ctrl->getLinkTarget($this, "switchToLanguage")); - $this->ctrl->setParameter($this, "totransl", $_GET["totransl"]); - } - } - -/* if ($cfg->getSinglePageMode()) - { - $a_list->addItem($this->lng->txt("cont_manage_multilang"), "", - $this->ctrl->getLinkTargetByClass("ilpagemultilanggui", "settings")); - }*/ - - include_once("./Services/COPage/classes/class.ilPageMultiLangGUI.php"); - $ml_gui = new ilPageMultiLangGUI($this->getPageObject()->getParentType(), - $this->getPageObject()->getParentId()); - $a_tpl->setVariable("MULTI_LANG_INFO", $ml_gui->getMultiLangInfo($this->getPageObject()->getLanguage())); - - $any_items = true; - } - } - - return $any_items; - } - - - /** - * Set edit mode - */ - function setEditMode() - { - if ($_GET["media_mode"] != "") - { - if ($_GET["media_mode"] == "disable") - { - $this->user->writePref("ilPageEditor_MediaMode", "disable"); - } - else - { - $this->user->writePref("ilPageEditor_MediaMode", ""); - } - } - if ($_GET["html_mode"] != "") - { - if ($_GET["html_mode"] == "disable") - { - $this->user->writePref("ilPageEditor_HTMLMode", "disable"); - } - else - { - $this->user->writePref("ilPageEditor_HTMLMode", ""); - } - } - if ($_GET["js_mode"] != "") - { - if ($_GET["js_mode"] == "disable") - { - $this->user->writePref("ilPageEditor_JavaScript", "disable"); - } - else - { - $this->user->writePref("ilPageEditor_JavaScript", ""); - } - } - - $this->ctrl->redirect($this, "edit"); - } - - - /** - * Get Tiny Menu - */ - static function getTinyMenu($a_par_type, - $a_int_links = false, $a_wiki_links = false, $a_keywords = false, - $a_style_id = 0, $a_paragraph_styles = true, $a_save_return = true, - $a_anchors = false, $a_save_new = true, $a_user_links = false) - { - global $DIC; - - $lng = $DIC->language(); - $ctrl = $DIC->ctrl(); - - $mathJaxSetting = new ilSetting("MathJax"); - - include_once("./Services/COPage/classes/class.ilPageEditorSettings.php"); - - include_once("./Services/UIComponent/Tooltip/classes/class.ilTooltipGUI.php"); - - $btpl = new ilTemplate("tpl.tiny_menu.html", true, true, "Services/COPage"); - - // debug ghost element - if (DEVMODE == 1) - { - $btpl->touchBlock("debug_ghost"); - } - - // bullet list - $btpl->touchBlock("blist_button"); - ilTooltipGUI::addTooltip("il_edm_blist", - $lng->txt("cont_blist"), - "iltinymenu_bd"); - - // numbered list - $btpl->touchBlock("nlist_button"); - ilTooltipGUI::addTooltip("il_edm_nlist", - $lng->txt("cont_nlist"), - "iltinymenu_bd"); - - // list indent - $btpl->touchBlock("list_indent"); - ilTooltipGUI::addTooltip("ilIndentBut", - $lng->txt("cont_list_indent"), - "iltinymenu_bd"); - - // list outdent - $btpl->touchBlock("list_outdent"); - ilTooltipGUI::addTooltip("ilOutdentBut", - $lng->txt("cont_list_outdent"), - "iltinymenu_bd"); - - if ($a_int_links) - { - $btpl->touchBlock("bb_ilink_button"); - ilTooltipGUI::addTooltip("iosEditInternalLinkTrigger", $lng->txt("cont_link_to_internal"), - "iltinymenu_bd"); - } - ilTooltipGUI::addTooltip("il_edm_xlink", $lng->txt("cont_link_to_external"), - "iltinymenu_bd"); - - if ($a_user_links) - { - $btpl->touchBlock("bb_ulink_button"); - } - - // remove format - $btpl->touchBlock("rformat_button"); - ilTooltipGUI::addTooltip("il_edm_rformat", $lng->txt("cont_remove_format"), - "iltinymenu_bd"); - - if ($a_paragraph_styles) - { - // new paragraph - $btpl->setCurrentBlock("new_par"); - $btpl->setVariable("IMG_NEWPAR", "+"); - $btpl->parseCurrentBlock(); - ilTooltipGUI::addTooltip("il_edm_newpar", $lng->txt("cont_insert_new_paragraph"), - "iltinymenu_bd"); - - $btpl->setCurrentBlock("par_edit"); - $btpl->setVariable("TXT_PAR_FORMAT", $lng->txt("cont_par_format")); - include_once("./Services/COPage/classes/class.ilPCParagraphGUI.php"); - $btpl->setVariable("STYLE_SELECTOR", ilPCParagraphGUI::getStyleSelector($a_selected, - ilPCParagraphGUI::_getCharacteristics($a_style_id), true)); - - ilTooltipGUI::addTooltip("ilAdvSelListAnchorText_style_selection", - $lng->txt("cont_paragraph_styles"), "iltinymenu_bd"); - - $btpl->parseCurrentBlock(); - } - - if ($a_keywords) - { - $btpl->setCurrentBlock("bb_kw_button"); - $btpl->setVariable("CC_KW", "kw"); - $btpl->parseCurrentBlock(); - ilTooltipGUI::addTooltip("il_edm_kw", $lng->txt("cont_text_keyword"), - "iltinymenu_bd"); - - } - - if ($a_wiki_links) - { - $btpl->setCurrentBlock("bb_wikilink_button2"); - $btpl->setVariable("TXT_WIKI_BUTTON2", $lng->txt("obj_wiki")); - $btpl->setVariable("WIKI_BUTTON2_URL", $ctrl->getLinkTargetByClass("ilwikipagegui", "")); - $btpl->parseCurrentBlock(); - ilTooltipGUI::addTooltip("il_edm_wlinkd", $lng->txt("cont_wiki_link_dialog"), - "iltinymenu_bd"); - - $btpl->setCurrentBlock("bb_wikilink_button"); - $btpl->setVariable("TXT_WLN2", $lng->txt("obj_wiki")); - $btpl->parseCurrentBlock(); - ilTooltipGUI::addTooltip("il_edm_wlink", $lng->txt("cont_link_to_wiki"), - "iltinymenu_bd"); - } - - $aset = new ilSetting("adve"); - - include_once("./Services/COPage/classes/class.ilPageContentGUI.php"); - foreach (ilPageContentGUI::_getCommonBBButtons() as $c => $st) - { - // these are handled via drop down now... - if (in_array($c, array("com", "quot", "acc", "code"))) - { - continue; - } - if (ilPageEditorSettings::lookupSettingByParentType( - $a_par_type, "active_".$c, true)) - { - $cc_code = $c; - if ($aset->get("use_physical")) - { - $cc_code = str_replace(array("str", "emp", "imp"), array("B", "I", "U"), $cc_code); - } - - if ($c != "tex" || $mathJaxSetting->get("enable") || defined("URL_TO_LATEX")) - { - $btpl->setCurrentBlock("bb_".$c."_button"); - $btpl->setVariable("CC_".strtoupper($c), $cc_code); - $btpl->parseCurrentBlock(); - ilTooltipGUI::addTooltip("il_edm_cc_".$c, - $lng->txt("cont_cc_".$c), - "iltinymenu_bd"); - -// $btpl->setVariable("TXT_".strtoupper($c), $this->lng->txt("cont_text_".$c)); - } - } - } - - if ($mathJaxSetting->get("enable") || defined("URL_TO_LATEX")) - { - ilTooltipGUI::addTooltip("il_edm_tex", $lng->txt("cont_tex"), - "iltinymenu_bd"); - } - ilTooltipGUI::addTooltip("il_edm_fn", $lng->txt("cont_fn"), - "iltinymenu_bd"); - - include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"); - $sdd = new ilAdvancedSelectionListGUI(); - $sdd->setPullRight(false); - $sdd->setListTitle($lng->txt("save")."..."); - - if ($a_save_return) - { - $btpl->setCurrentBlock("save_return"); - $btpl->setVariable("TXT_SAVE_RETURN", $lng->txt("save_return")); - $btpl->parseCurrentBlock(); - $sdd->addItem($lng->txt("save_return"), "", "#", "", "", "", "", "", "ilCOPage.cmdSaveReturn(false); return false;"); - } - - if ($a_save_new) - { - $btpl->setCurrentBlock("save_new"); - $btpl->setVariable("TXT_SAVE_NEW", $lng->txt("save_new")); - $btpl->parseCurrentBlock(); - $sdd->addItem($lng->txt("save_new"), "", "#", "", "", "", "", "", "ilCOPage.cmdSaveReturn(true); return false;"); - } - - $sdd->addItem($lng->txt("save"), "", "#", "", "", "", "", "", "ilCOPage.cmdSave(null); return false;"); - $sdd->addItem($lng->txt("cancel"), "", "#", "", "", "", "", "", "ilCOPage.cmdCancel(); return false;"); - - if ($a_anchors) - { - $btpl->setCurrentBlock("bb_anc_button"); - $btpl->setVariable("CC_ANC", "anc"); - $btpl->parseCurrentBlock(); - ilTooltipGUI::addTooltip("il_edm_anc", $lng->txt("cont_anchor"), - "iltinymenu_bd"); - } - - $btpl->setVariable("SAVE_DROPDOWN", $sdd->getHTML()); - -/* // footnote - $btpl->setVariable("TXT_ILN", $this->lng->txt("cont_text_iln")); - $btpl->setVariable("TXT_BB_TIP", $this->lng->txt("cont_bb_tip")); - $btpl->setVariable("TXT_WLN", $lng->txt("wiki_wiki_page")); -*/ -// $btpl->setVariable("PAR_TA_NAME", $a_ta_name); - - $btpl->setVariable("TXT_SAVE", $lng->txt("save")); - $btpl->setVariable("TXT_CANCEL", $lng->txt("cancel")); - - $btpl->setVariable("TXT_CHAR_FORMAT", $lng->txt("cont_char_format")); - $btpl->setVariable("TXT_LISTS", $lng->txt("cont_lists")); - $btpl->setVariable("TXT_LINKS", $lng->txt("cont_links")); - $btpl->setVariable("TXT_MORE_FUNCTIONS", $lng->txt("cont_more_functions")); - $btpl->setVariable("TXT_SAVING", $lng->txt("cont_saving")); - - include_once("./Services/COPage/classes/class.ilPCParagraphGUI.php"); - - $btpl->setVariable("CHAR_STYLE_SELECTOR", ilPCParagraphGUI::getCharStyleSelector($a_par_type, true, $a_style_id)); - ilTooltipGUI::addTooltip("ilAdvSelListAnchorElement_char_style_selection", - $lng->txt("cont_more_character_styles"), "iltinymenu_bd"); - - return $btpl->get(); - } - - /** - * Set standard link xml - */ - function setDefaultLinkXml() - { - $int_links = $this->getPageObject()->getInternalLinks(); -//var_dump($int_links); - $link_info = ""; - $targetframe = "None"; - foreach ($int_links as $int_link) - { - $target = $int_link["Target"]; - if (substr($target, 0, 4) == "il__") - { - $target_arr = explode("_", $target); - $target_id = $target_arr[count($target_arr) - 1]; - $type = $int_link["Type"]; - - $targetframe = ($int_link["TargetFrame"] != "") - ? $int_link["TargetFrame"] - : "None"; - - $ltarget="_top"; - if ($targetframe != "None") - { - $ltarget="_blank"; - } - - // anchor - $anc = $anc_add = ""; - if ($int_link["Anchor"] != "") - { - $anc = $int_link["Anchor"]; - $anc_add = "_".rawurlencode($int_link["Anchor"]); - } - - $href = ""; - $lcontent = ""; - switch($type) - { - case "PageObject": - case "StructureObject": - $lm_id = ilLMObject::_lookupContObjID($target_id); - if ($type == "PageObject") - { - $href = "./goto.php?target=pg_".$target_id.$anc_add; - } - else - { - $href = "./goto.php?target=st_".$target_id; - } - if ($lm_id == "") - { - $href = ""; - } - break; - - case "GlossaryItem": - if ($targetframe == "None") - { - $targetframe = "Glossary"; - } - $href = "./goto.php?target=git_".$target_id; - break; - - case "MediaObject": - $this->ctrl->setParameter($this, "mob_id", $target_id); - //$this->ctrl->setParameter($this, "pg_id", $this->obj->getId()); - $href = $this->ctrl->getLinkTarget($this, "displayMedia"); - $this->ctrl->setParameter($this, "mob_id", ""); - break; - - case "WikiPage": - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $href = ilWikiPage::getGotoForWikiPageTarget($target_id); - break; - - case "PortfolioPage": - include_once("./Modules/Portfolio/classes/class.ilPortfolioPage.php"); - $href = ilPortfolioPage::getGotoForPortfolioPageTarget($target_id, ($this->getOutputMode() == "offline")); - break; - - case "RepositoryItem": - $obj_type = ilObject::_lookupType($target_id, true); - $obj_id = ilObject::_lookupObjId($target_id); - $href = "./goto.php?target=".$obj_type."_".$target_id; - break; - - case "User": - $obj_type = ilObject::_lookupType($target_id); - if ($obj_type == "usr") - { - include_once("./Services/User/classes/class.ilUserUtil.php"); - $back = $this->getProfileBackUrl(); - //var_dump($back); exit; - $this->ctrl->setParameterByClass("ilpublicuserprofilegui", "user_id", $target_id); - if (strlen($back)) { - $this->ctrl->setParameterByClass( - "ilpublicuserprofilegui", - "back_url", - rawurlencode($back) - ); - } - $href = ""; - include_once("./Services/User/classes/class.ilUserUtil.php"); - if (ilUserUtil::hasPublicProfile($target_id)) - { - $href = $this->ctrl->getLinkTargetByClass(["ilpersonaldesktopgui", "ilpublicuserprofilegui"], "getHTML"); - } - $this->ctrl->setParameterByClass("ilpublicuserprofilegui", "user_id", ""); - $lcontent = ilUserUtil::getNamePresentation($target_id, false, false); - } - break; - - } - if ($href != "") - { - $anc_par = 'Anchor="' . $anc . '"'; - $link_info .= ""; - } - } - } - $link_info.= ""; - $this->setLinkXML($link_info); - } - - /** - * Get profile back url - */ - function getProfileBackUrl() - { - return $this->ctrl->getLinkTargetByClass(strtolower(get_class($this)), "preview"); - } - - - /** - * Download file of file lists - */ - function downloadFile() - { - $this->obj->buildDom(); - - include_once("./Services/COPage/classes/class.ilPCFileList.php"); - $files = ilPCFileList::collectFileItems($this->obj, $this->obj->getDomDoc()); - - $file = explode("_", $_GET["file_id"]); - require_once("./Modules/File/classes/class.ilObjFile.php"); - $file_id = $file[count($file) - 1]; - - // file must be in page - if (!in_array($file_id, $files)) - { - exit; - } - $fileObj = new ilObjFile($file_id, false); - $fileObj->sendFile(); - exit; - } - - /** - * Show media in fullscreen mode - */ - function displayMediaFullscreen() - { - $this->displayMedia(true); - } - - /** - * Display media - */ - function displayMedia($a_fullscreen = false) - { - $tpl = $this->tpl; - - $tpl = new ilTemplate("tpl.fullscreen.html", true, true, "Modules/LearningModule"); - $tpl->setCurrentBlock("ilMedia"); - - //$int_links = $page_object->getInternalLinks(); - $med_links = ilMediaItem::_getMapAreasIntLinks($_GET["mob_id"]); - - // @todo - //$link_xml = $this->getLinkXML($med_links, $this->getLayoutLinkTargets()); - - require_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $media_obj = new ilObjMediaObject($_GET["mob_id"]); - require_once("./Services/COPage/classes/class.ilPageObject.php"); - $pg_obj = $this->getPageObject(); - $pg_obj->buildDom(); - - if (!empty ($_GET["pg_id"])) - { - $xml = ""; - $xml.= $pg_obj->getMediaAliasElement($_GET["mob_id"]); - $xml.= $media_obj->getXML(IL_MODE_OUTPUT); - $xml.= $link_xml; - $xml.=""; - } - else - { - $xml = ""; - $xml.= $media_obj->getXML(IL_MODE_ALIAS); - $xml.= $media_obj->getXML(IL_MODE_OUTPUT); - $xml.= $link_xml; - $xml.=""; - } - - $xsl = file_get_contents("./Services/COPage/xsl/page.xsl"); - $args = array( '/_xml' => $xml, '/_xsl' => $xsl ); - $xh = xslt_create(); - - $mode = "media"; - if ($a_fullscreen) - { - $mode = "fullscreen"; - } - -//echo "XML:".htmlentities($xml); - // determine target frames for internal links - $wb_path = ilUtil::getWebspaceDir("output")."/"; - $enlarge_path = ilUtil::getImagePath("enlarge.svg"); - $params = array ('mode' => $mode, 'enlarge_path' => $enlarge_path, - 'link_params' => "ref_id=".$_GET["ref_id"],'fullscreen_link' => "", - 'ref_id' => $_GET["ref_id"], 'webspace_path' => $wb_path); - $output = xslt_process($xh,"arg:/_xml","arg:/_xsl",NULL,$args, $params); -//echo "

          ".htmlentities($output); - //echo xslt_error($xh); - xslt_free($xh); - - // unmask user html - require_once('./Services/Style/Content/classes/class.ilObjStyleSheet.php'); - $tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath(0)); - $tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); - $tpl->setVariable("MEDIA_CONTENT", $output); - - // add js - include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); - ilObjMediaObjectGUI::includePresentationJS($tpl); - $tpl->fillJavaScriptFiles(); - $tpl->fillCssFiles(); - - echo $tpl->get(); - exit; - } - - /** - * download source code paragraph - */ - function download_paragraph() - { - $pg_obj = $this->getPageObject(); - $pg_obj->send_paragraph($_GET["par_id"], $_GET["downloadtitle"]); - } - - /** - * Insert page toc - * - * @param string output - * @return string output - */ - function insertPageToc($a_output) - { - include_once("./Services/Utilities/classes/class.ilStr.php"); - - // extract all headings - $offsets = ilStr::strPosAll($a_output, "ilPageTocH"); - $page_heads = array(); - foreach ($offsets as $os) - { - $level = (int) substr($a_output, $os + 10, 1); - if (in_array($level, array(1,2,3))) - { - $anchor = str_replace("TocH", "TocA", - substr($a_output, $os, strpos($a_output, "<", $os) - $os - 3) - ); - - // get heading - $tag_start = stripos($a_output, "", $tag_start); - $head = substr($a_output, $tag_start, $tag_end - $tag_start); - - // get headings text - $text_start = stripos($head, ">") + 1; - $text_end = strripos($head, "", "", $h["text"]); - - // add the list node - $list->addListNode( - "".$h["text"]."", - $i, $par); - - // set the node as current parent of the level - if ($h["level"] == 1) - { - $c_par[1] = $i; - $c_par[2] = 0; - } - if ($h["level"] == 2) - { - $c_par[2] = $i; - } - } - - $tpl = new ilTemplate("tpl.page_toc.html", true, true, - "Services/COPage"); - $tpl->setVariable("PAGE_TOC", $list->getHTML()); - $tpl->setVariable("TXT_PAGE_TOC", $this->lng->txt("cont_page_toc")); - $tpl->setVariable("TXT_HIDE", $this->lng->txt("hide")); - $tpl->setVariable("TXT_SHOW", $this->lng->txt("show")); - - $a_output = str_replace("{{{{{PageTOC}}}}}", - $tpl->get(), $a_output); - $numbers = $list->getNumbers(); - - if (count($numbers) > 0) - { - include_once("./Services/Utilities/classes/class.ilStr.php"); - foreach ($numbers as $n) - { - $a_output = - ilStr::replaceFirsOccurence("", $n." ", $a_output); - } - } - } - else - { - $a_output = str_replace("{{{{{PageTOC}}}}}", - "", $a_output); - } - - return $a_output; - } - - /** - * Insert resources - * - * @param - * @return - */ - function insertResources($a_output) - { - // this is edit mode only - - if ($this->getEnablePCType("Resources") && - ($this->getOutputMode() == "edit" || $this->getOutputMode() == "preview")) - { - include_once("./Services/COPage/classes/class.ilPCResourcesGUI.php"); - $a_output = ilPCResourcesGUI::insertResourcesIntoPageContent($a_output, $this->getOutputMode()); - } - return $a_output; - } - - - - /** - * Insert adv content trigger - * - * @param string $a_output output - * @return string modified output - */ - function insertAdvTrigger($a_output) - { - if (!$this->getAbstractOnly()) - { - $a_output = str_replace("{{{{{LV_show_adv}}}}}", - $this->lng->txt("cont_show_adv"), $a_output); - $a_output = str_replace("{{{{{LV_hide_adv}}}}}", - $this->lng->txt("cont_hide_adv"), $a_output); - } - else - { - $a_output = str_replace("{{{{{LV_show_adv}}}}}", - "", $a_output); - $a_output = str_replace("{{{{{LV_hide_adv}}}}}", - "", $a_output); - } - - return $a_output; - } - - - /** - * Finalizing output processing. Maybe overwritten in derived - * classes, e.g. in wiki module. - */ - function postOutputProcessing($a_output) - { - return $a_output; - } - - /** - * Insert help texts - */ - function insertHelp($a_tpl) - { - $a_tpl->setCurrentBlock("help"); - $a_tpl->setVariable("TXT_ADD_EL", $this->lng->txt("cont_add_elements")); - include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); - $a_tpl->setVariable("PLUS", ilGlyphGUI::get(ilGlyphGUI::ADD)); - $a_tpl->setVariable("DRAG_ARROW", ilGlyphGUI::get(ilGlyphGUI::DRAG)); - $a_tpl->setVariable("TXT_DRAG", $this->lng->txt("cont_drag_and_drop_elements")); - $a_tpl->setVariable("TXT_SEL", $this->lng->txt("cont_double_click_to_delete")); - $a_tpl->parseCurrentBlock(); - } - - /** - * Preview history - */ - function previewHistory() - { - $this->preview(); - } - - /** - * preview - */ - function preview() - { - $this->setOutputMode(IL_PAGE_PREVIEW); - return $this->showPage(); - } - - /** - * edit ("view" before) - */ - function edit() - { - // editing allowed? - if (!$this->getEnableEditing()) - { - ilUtil::sendFailure($this->lng->txt("permission_denied"), true); - $this->ctrl->redirect($this, "preview"); - } - - // not so nive workaround for container pages, bug #0015831 - $ptype = $this->getParentType(); - if ($ptype == "cont" && $_GET["ref_id"] > 0) - { - $ptype = ilObject::_lookupType((int) $_GET["ref_id"], true); - } - $this->help->setScreenId("edit_".$ptype); - - require_once 'Services/Captcha/classes/class.ilCaptchaUtil.php'; - if( - $this->user->isAnonymous() && - !$this->user->isCaptchaVerified() && - ilCaptchaUtil::isActiveForWiki() - ) - { - $form = $this->initCaptchaForm(); - if($_POST['captcha_code'] && $form->checkInput()) - { - $this->user->setCaptchaVerified(true); - } - else - { - return $form->getHTML(); - } - } - - // edit lock - if (!$this->getPageObject()->getEditLock()) - { - include_once("./Services/User/classes/class.ilUserUtil.php"); - $info = $this->lng->txt("content_no_edit_lock"); - $lock = $this->getPageObject()->getEditLockInfo(); - $info .= "
          " . $this->lng->txt("content_until") . ": " . - ilDatePresentation::formatDate(new ilDateTime($lock["edit_lock_until"], IL_CAL_UNIX)); - $info .= "
          " . $this->lng->txt("obj_usr") . ": " . - ilUserUtil::getNamePresentation($lock["edit_lock_user"]); - if (!$this->ctrl->isAsynch()) - { - ilUtil::sendInfo($info); - return ""; - } - else - { - echo $this->tpl->getMessageHTML($info); - exit; - } - } - else - { - if($this->getPageObject()->getEffectiveEditLockTime() > 0) - { - $mess = $this->getBlockingInfoMessage(); - } - } - - $this->setOutputMode(IL_PAGE_EDIT); - - $html = $this->showPage(); - - if ($this->isEnabledNotes()) - { - $html.= "

          ".$this->getNotesHTML(); - } - - return $mess.$html; - } - - /** - * Get block info message - * @return string - */ - protected function getBlockingInfoMessage(): string - { - $ctrl = $this->ctrl; - $lng = $this->lng; - $ui = $this->ui; - - $lock = $this->getPageObject()->getEditLockInfo(); - $info = $this->lng->txt("cont_got_lock_release"); - $info = str_replace("%1", ilDatePresentation::formatDate(new ilDateTime($lock["edit_lock_until"],IL_CAL_UNIX)), $info); - - $mbox = $ui->factory()->messageBox()->info($info) - ->withButtons([$ui->factory()->button()->standard($lng->txt("cont_finish_editing"), $ctrl->getLinkTarget($this, "releasePageLock"))]); - - return $ui->renderer()->render($mbox); - - } - - - /** - * InsertJS at placeholder - * - * @param - * @return - */ - function insertJSAtPlaceholder() - { - $tpl = $this->tpl; - - if ($_GET["pl_hier_id"] == "") - { - $this->obj->buildDom(); - $this->obj->addHierIDs(); - $hid = $this->obj->getHierIdsForPCIds(array($_GET["pl_pc_id"])); - $_GET["pl_hier_id"] = $hid[$_GET["pl_pc_id"]]; - } - -// 'pl_hier_id' => string '2_1_1_1' (length=7) -// 'pl_pc_id' => string '1f77eb1d8a478497d69b99d938fda8f' (length=31) - $html = $this->edit(); - - $tpl->addOnLoadCode("ilCOPage.insertJSAtPlaceholder('". - $_GET["pl_hier_id"].":".$_GET["pl_pc_id"]. - "');", 3); - - return $html; - } - - /** - * Init captcha form. - */ - public function initCaptchaForm() - { - require_once 'Services/Form/classes/class.ilPropertyFormGUI.php'; - $form = new ilPropertyFormGUI(); - - require_once 'Services/Captcha/classes/class.ilCaptchaInputGUI.php'; - $ci = new ilCaptchaInputGUI($this->lng->txt('cont_captcha_code'), 'captcha_code'); - $ci->setRequired(true); - $form->addItem($ci); - - $form->addCommandButton('edit', $this->lng->txt('ok')); - - $form->setTitle($this->lng->txt('cont_captcha_verification')); - $form->setFormAction($this->ctrl->getFormAction($this)); - - return $form; - } - - /* - * presentation - */ - function presentation($a_mode = IL_PAGE_PRESENTATION) - { - $this->setOutputMode($a_mode); - - return $this->showPage(); - } - - function getHTML() - { - $this->getTabs("preview"); - return $this->showPage(); - } - - /** - * show fullscreen view of media object - */ - function showMediaFullscreen($a_style_id = 0) - { - $this->tpl = new ilTemplate("tpl.fullscreen.html", true, true, "Services/COPage"); - $this->tpl->setCurrentBlock("ContentStyle"); - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", 0); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setVariable("PAGETITLE", " - ".ilObject::_lookupTitle($_GET["mob_id"])); - $this->tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); - $this->tpl->setCurrentBlock("ilMedia"); - - require_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $media_obj = new ilObjMediaObject($_GET["mob_id"]); - if (!empty ($_GET["pg_id"])) - { - include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); - $pg_obj = ilPageObjectFactory::getInstance($this->obj->getParentType(), $_GET["pg_id"]); - $pg_obj->buildDom(); - - $xml = ""; - // todo: we get always the first alias now (problem if mob is used multiple - // times in page) - $xml.= $pg_obj->getMediaAliasElement($_GET["mob_id"]); - $xml.= $media_obj->getXML(IL_MODE_OUTPUT); - $xml.=""; - } - else - { - $xml = ""; - $xml.= $media_obj->getXML(IL_MODE_ALIAS); - $xml.= $media_obj->getXML(IL_MODE_OUTPUT); - $xml.=""; - } - -//echo htmlentities($xml); exit; - - $xsl = file_get_contents("./Services/COPage/xsl/page.xsl"); - $args = array( '/_xml' => $xml, '/_xsl' => $xsl ); - $xh = xslt_create(); - -//echo "XML:".htmlentities($xml); - // determine target frames for internal links - //$pg_frame = $_GET["frame"]; - $wb_path = ilUtil::getWebspaceDir("output")."/"; - $mode = "fullscreen"; - $params = array ('mode' => $mode, 'webspace_path' => $wb_path); - $output = xslt_process($xh,"arg:/_xml","arg:/_xsl",NULL,$args, $params); - echo xslt_error($xh); - xslt_free($xh); - - // unmask user html - $this->tpl->setVariable("MEDIA_CONTENT", $output); - } - - /** - * display validation error - * - * @param string $a_error error string - */ - function displayValidationError($a_error) - { - if(is_array($a_error)) - { - $error_str = "Error(s):
          "; - foreach ($a_error as $error) - { - $err_mess = implode($error, " - "); - if (!is_int(strpos($err_mess, ":0:"))) - { - $error_str .= htmlentities($err_mess)."
          "; - } - } - $this->tpl->setVariable("MESSAGE", $error_str); - } - } - - /** - * Get history table as HTML. - */ - function history() - { - if (!$this->getEnableEditing()) - { - return; - } - - $this->tpl->addJavaScript("./Services/COPage/js/page_history.js"); - - include_once("./Services/COPage/classes/class.ilPageHistoryTableGUI.php"); - $table_gui = new ilPageHistoryTableGUI($this, "history"); - $table_gui->setId("hist_table"); - $entries = $this->getPageObject()->getHistoryEntries(); - $entries[] = array('page_id' => $this->getPageObject()->getId(), - 'parent_type' => $this->getPageObject()->getParentType(), - 'hdate' => $this->getPageObject()->getLastChange(), - 'parent_id' => $this->getPageObject()->getParentId(), - 'nr' => 0, - 'sortkey' => 999999, - 'user' => $this->getPageObject()->last_change_user); - $table_gui->setData($entries); - return $table_gui->getHTML(); - } - - /** - * Rollback confirmation - */ - function rollbackConfirmation() - { - if (!$this->getEnableEditing()) - { - return; - } - - include_once("Services/Utilities/classes/class.ilConfirmationGUI.php"); - $c_gui = new ilConfirmationGUI(); - - // set confirm/cancel commands - $this->ctrl->setParameter($this, "rollback_nr", $_GET["old_nr"]); - $c_gui->setFormAction($this->ctrl->getFormAction($this, "rollback")); - $c_gui->setHeaderText($this->lng->txt("cont_rollback_confirmation")); - $c_gui->setCancel($this->lng->txt("cancel"), "history"); - $c_gui->setConfirm($this->lng->txt("confirm"), "rollback"); - - $hentry = $this->obj->getHistoryEntry($_GET["old_nr"]); - - $c_gui->addItem("id[]", $_GET["old_nr"], - ilDatePresentation::formatDate(new ilDateTime($hentry["hdate"], IL_CAL_DATETIME))); - - $this->tpl->setContent($c_gui->getHTML()); - } - - /** - * Rollback to a previous version - */ - function rollback() - { - if (!$this->getEnableEditing()) - { - return; - } - - $hentry = $this->obj->getHistoryEntry($_GET["rollback_nr"]); - - if ($hentry["content"] != "") - { - $this->obj->setXMLContent($hentry["content"]); - $this->obj->buildDom(true); - if ($this->obj->update()) - { - $this->ctrl->redirect($this, "history"); - } - } - $this->ctrl->redirect($this, "history"); - } - - /** - * Set screen id component - * - * @param - * @return - */ - function setScreenIdComponent() - { - $this->help->setScreenIdComponent("copg"); - } - - /** - * adds tabs to tab gui object - * - * @param object $tabs_gui ilTabsGUI object - */ - function getTabs($a_activate = "") - { - $this->setScreenIdComponent(); - - if (!$this->getEnabledTabs()) - { - return; - } - - // back to upper context - if (!$this->getEditPreview()) - { - $this->tabs_gui->addTarget("pg", $this->ctrl->getLinkTarget($this, "preview") - , array("", "preview")); - - if ($this->getEnableEditing()) - { - $this->tabs_gui->addTarget("edit", $this->ctrl->getLinkTarget($this, "edit") - , array("", "edit")); - } - } - else - { - if ($this->getEnableEditing()) - { - $this->tabs_gui->addTarget("edit", $this->ctrl->getLinkTarget($this, "edit") - , array("", "edit")); - } - - $this->tabs_gui->addTarget("cont_preview", $this->ctrl->getLinkTarget($this, "preview") - , array("", "preview")); - } - - //$tabs_gui->addTarget("properties", $this->ctrl->getLinkTarget($this, "properties") - // , "properties", get_class($this)); - - if ($this->use_meta_data) - { - include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php"; - $mdgui = new ilObjectMetaDataGUI($this->meta_data_rep_obj, - $this->meta_data_type, $this->meta_data_sub_obj_id); - $mdtab = $mdgui->getTab(); - if($mdtab) - { - $this->tabs_gui->addTarget("meta_data", - $mdtab, "", "ilobjectmetadatagui"); - } - } - - $lm_set = new ilSetting("lm"); - - if ($this->getEnableEditing() && $lm_set->get("page_history", 1)) - { - $this->tabs_gui->addTarget("history", $this->ctrl->getLinkTarget($this, "history") - , "history", get_class($this)); - if ($_GET["history_mode"] == "1" || $this->ctrl->getCmd() == "compareVersion") - { - $this->tabs_gui->activateTab("history"); - } - } - -/* $tabs = $this->ctrl->getTabs(); - foreach ($tabs as $tab) - { - $tabs_gui->addTarget($tab["lang_var"], $tab["link"] - , $tab["cmd"], $tab["class"]); - } -*/ - if ($this->getEnableEditing() && $this->user->getId() != ANONYMOUS_USER_ID) - { - $this->tabs_gui->addTarget("clipboard", $this->ctrl->getLinkTargetByClass(array(get_class($this), "ilEditClipboardGUI"), "view") - , "view", "ilEditClipboardGUI"); - } - - if ($this->getPageConfig()->getEnableScheduledActivation()) - { - $this->tabs_gui->addTarget("cont_activation", $this->ctrl->getLinkTarget($this, "editActivation"), - "editActivation", get_class($this)); - } - - if ($this->getEnabledNews()) - { - $this->tabs_gui->addTarget("news", - $this->ctrl->getLinkTargetByClass("ilnewsitemgui", "editNews"), - "", "ilnewsitemgui"); - } - - // external hook to add tabs - if (is_array($this->tab_hook)) - { - $func = $this->tab_hook["func"]; - $this->tab_hook["obj"]->$func(); - } - //$this->tabs_gui->setTabActive("pg"); - } - - /** - * Compares two revisions of the page - */ - function compareVersion() - { - if (!$this->getEnableEditing()) - { - return; - } - - $tpl = new ilTemplate("tpl.page_compare.html", true, true, "Services/COPage"); - $compare = $this->obj->compareVersion((int) $_POST["left"], (int) $_POST["right"]); - - // left page - $lpage = $compare["l_page"]; - $cfg = $this->getPageConfig(); - $cfg->setPreventHTMLUnmasking(true); - - $this->setOutputMode(IL_PAGE_PREVIEW); - $this->setPageObject($lpage); - $this->setPresentationTitle($this->getPresentationTitle()); - $this->setCompareMode(true); - - $lhtml = $this->showPage(); - $lhtml = $this->replaceDiffTags($lhtml); - $lhtml = str_replace("<br />", "
          ", $lhtml); - $tpl->setVariable("LEFT", $lhtml); - - // right page - $rpage = $compare["r_page"]; - $this->setPageObject($rpage); - $this->setPresentationTitle($this->getPresentationTitle()); - $this->setCompareMode(true); - $this->setOutputMode(IL_PAGE_PREVIEW); - - $rhtml = $this->showPage(); - $rhtml = $this->replaceDiffTags($rhtml); - $rhtml = str_replace("<br />", "
          ", $rhtml); - $tpl->setVariable("RIGHT", $rhtml); - - $tpl->setVariable("TXT_NEW", $this->lng->txt("cont_pc_new")); - $tpl->setVariable("TXT_MODIFIED", $this->lng->txt("cont_pc_modified")); - $tpl->setVariable("TXT_DELETED", $this->lng->txt("cont_pc_deleted")); - -//var_dump($left); -//var_dump($right); - - return $tpl->get(); - } - - function replaceDiffTags($a_html) - { - $a_html = str_replace("[ilDiffInsStart]", '', $a_html); - $a_html = str_replace("[ilDiffDelStart]", '', $a_html); - $a_html = str_replace("[ilDiffInsEnd]", '', $a_html); - $a_html = str_replace("[ilDiffDelEnd]", '', $a_html); - - return $a_html; - } - - /** - * Edit activation (only, if scheduled page activation is activated in administration) - */ - function editActivation() - { - $atpl = new ilTemplate("tpl.page_activation.php", true, true, "Services/COPage"); - $this->initActivationForm(); - $this->getActivationFormValues(); - $atpl->setVariable("FORM", $this->form->getHTML()); - $atpl->setCurrentBlock("updater"); - $atpl->setVariable("UPDATER_FRAME", $this->exp_frame); - $atpl->setVariable("EXP_ID_UPDATER", $this->exp_id); - $atpl->setVariable("HREF_UPDATER", $this->exp_target_script); - $atpl->parseCurrentBlock(); - $this->tpl->setContent($atpl->get()); - } - - /** - * Init activation form - */ - function initActivationForm() - { - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - $this->form->setFormAction($this->ctrl->getFormAction($this)); - $this->form->setTitle($this->lng->txt("cont_page_activation")); - - // activation type radio - $rad = new ilRadioGroupInputGUI($this->lng->txt("cont_activation"), "activation"); - $rad_op1 = new ilRadioOption($this->lng->txt("cont_activated"), "activated"); - - $rad->addOption($rad_op1); - $rad_op2 = new ilRadioOption($this->lng->txt("cont_deactivated"), "deactivated"); - $rad->addOption($rad_op2); - $rad_op3 = new ilRadioOption($this->lng->txt("cont_scheduled_activation"), "scheduled"); - - $dt_prop = new ilDateTimeInputGUI($this->lng->txt("cont_start"), "start"); - $dt_prop->setRequired(true); - $dt_prop->setShowTime(true); - $rad_op3->addSubItem($dt_prop); - $dt_prop2 = new ilDateTimeInputGUI($this->lng->txt("cont_end"), "end"); - $dt_prop2->setRequired(true); - $dt_prop2->setShowTime(true); - $rad_op3->addSubItem($dt_prop2); - - // show activation information - $cb = new ilCheckboxInputGUI($this->lng->txt("cont_show_activation_info"), "show_activation_info"); - $cb->setInfo($this->lng->txt("cont_show_activation_info_info")); - $rad_op3->addSubItem($cb); - - - $rad->addOption($rad_op3); - - $this->form->addCommandButton("saveActivation", $this->lng->txt("save")); - - $this->form->addItem($rad); - } - - /** - * Get values for activation form - */ - function getActivationFormValues() - { - $activation = "deactivated"; - if ($this->getPageObject()->getActive()) - { - $activation = "activated"; - } - - $dt_prop = $this->form->getItemByPostVar("start"); - if ($this->getPageObject()->getActivationStart() != "") - { - $activation = "scheduled"; - $dt_prop->setDate(new ilDateTime($this->getPageObject()->getActivationStart(), - IL_CAL_DATETIME)); - } - $dt_prop = $this->form->getItemByPostVar("end"); - if ($this->getPageObject()->getActivationEnd() != "") - { - $activation = "scheduled"; - $dt_prop->setDate(new ilDateTime($this->getPageObject()->getActivationEnd(), - IL_CAL_DATETIME)); - } - - $this->form->getItemByPostVar("activation")->setValue($activation); - $this->form->getItemByPostVar("show_activation_info")->setChecked($this->getPageObject()->getShowActivationInfo()); - } - - /** - * Save Activation - */ - function saveActivation() - { - $this->initActivationForm(); - - if ($this->form->checkInput()) - { - $this->getPageObject()->setActive(true); - $this->getPageObject()->setActivationStart(null); - $this->getPageObject()->setActivationEnd(null); - $this->getPageObject()->setShowActivationInfo($_POST["show_activation_info"]); - if ($_POST["activation"] == "deactivated") - { - $this->getPageObject()->setActive(false); - } - if ($_POST["activation"] == "scheduled") - { - $this->getPageObject()->setActive(false); - $this->getPageObject()->setActivationStart( - $this->form->getItemByPostVar("start")->getDate()->get(IL_CAL_DATETIME)); - $this->getPageObject()->setActivationEnd( - $this->form->getItemByPostVar("end")->getDate()->get(IL_CAL_DATETIME)); - } - $this->getPageObject()->update(); - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "editActivation"); - } - $this->form->setValuesByPost(); - $this->tpl->setContent($this->form->getHTML()); - } - - /** - * Get html for public and/or private notes - * - * @param bool $a_content_object - * @param bool $a_enable_private_notes - * @param bool $a_enable_public_notes - * @param bool $a_enable_notes_deletion - * @return string - */ - function getNotesHTML($a_content_object = null, $a_enable_private_notes = true, $a_enable_public_notes = false, $a_enable_notes_deletion = false, $a_callback = null) - { - include_once("Services/Notes/classes/class.ilNoteGUI.php"); - - // scorm 2004 page gui - if(!$a_content_object) - { - $notes_gui = new ilNoteGUI($this->notes_parent_id, - (int)$this->obj->getId(), "pg"); - - $a_enable_private_notes = true; - $a_enable_public_notes = true; - $a_enable_notes_deletion = false; - } - // wiki page gui, blog posting gui - else - { - $notes_gui = new ilNoteGUI($a_content_object->getParentId(), - $a_content_object->getId(), $a_content_object->getParentType()); - } - - if($a_enable_private_notes) - { - $notes_gui->enablePrivateNotes(); - } - if ($a_enable_public_notes) - { - $notes_gui->enablePublicNotes(); - if ((bool)$a_enable_notes_deletion) - { - $notes_gui->enablePublicNotesDeletion(true); - } - } - - if($a_callback) - { - $notes_gui->addObserver($a_callback); - } - - $next_class = $this->ctrl->getNextClass($this); - if ($next_class == "ilnotegui") - { - $html = $this->ctrl->forwardCommand($notes_gui); - } - else - { - $html = $notes_gui->getNotesHTML(); - } - return $html; - } - - /** - * Process answer - */ - function processAnswer() - { - include_once("./Services/COPage/classes/class.ilPageQuestionProcessor.php"); - ilPageQuestionProcessor::saveQuestionAnswer( - ilUtil::stripSlashes($_POST["type"]), - ilUtil::stripSlashes($_POST["id"]), - ilUtil::stripSlashes($_POST["answer"])); - } - - - // - // Initially opened content (e.g. used in learning modules), that - // is presented in another than the main content area (e.g. a picture in - // the bottom left area) - // - - /** - * Initially opened content - * - * @param - * @return - */ - function initialOpenedContent() - { - $this->tabs_gui->activateTab("edit"); - $form = $this->initOpenedContentForm(); - - $this->tpl->setContent($form->getHTML()); - } - - /** - * Init form for initially opened content - * - * @param - * @return - */ - function initOpenedContentForm() - { - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - - // link input - include_once 'Services/Form/classes/class.ilLinkInputGUI.php'; - $ac = new ilLinkInputGUI($this->lng->txt('cont_resource'), 'opened_content'); - $ac->setAllowedLinkTypes(ilLinkInputGUI::INT); - $ac->setInternalLinkDefault("Media_Media", 0); - $ac->setInternalLinkFilterTypes(array("PageObject_FAQ", "GlossaryItem", "Media_Media", "Media_FAQ")); - $val = $this->obj->getInitialOpenedContent(); - if ($val["id"] != "" && $val["type"] != "") - { - $ac->setValue($val["type"]."|".$val["id"]."|".$val["target"]); - } - - $form->addItem($ac); - - $form->addCommandButton("saveInitialOpenedContent", $this->lng->txt("save")); - $form->addCommandButton("edit", $this->lng->txt("cancel")); - $form->setTitle($this->lng->txt("cont_initial_attached_content")); - $form->setFormAction($this->ctrl->getFormAction($this)); - - return $form; - } - - /** - * Save initial opened content - * - * @param - * @return - */ - function saveInitialOpenedContent() - { - $this->obj->saveInitialOpenedContent( - ilUtil::stripSlashes($_POST["opened_content_ajax_type"]), - ilUtil::stripSlashes($_POST["opened_content_ajax_id"]), - ilUtil::stripSlashes($_POST["opened_content_ajax_target"]) - ); - - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified")); - $this->ctrl->redirect($this, "edit"); - } - - //// - //// Multilinguality functions - //// - - - /** - * Switch to language - */ - function switchToLanguage() - { - $l = ilUtil::stripSlashes($_GET["totransl"]); - $p = $this->getPageObject(); - if (!ilPageObject::_exists($p->getParentType(), $p->getId(), $l)) - { - $this->confirmPageTranslationCreation(); - return; - } - $this->ctrl->setParameter($this, "transl", $_GET["totransl"]); - $this->ctrl->redirect($this, "edit"); - } - - /** - * Confirm page translation creation - */ - function confirmPageTranslationCreation() - { - $l = ilUtil::stripSlashes($_GET["totransl"]); - $this->ctrl->setParameter($this, "totransl", $l); - $this->lng->loadLanguageModule("meta"); - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($this->ctrl->getFormAction($this)); - $cgui->setHeaderText($this->lng->txt("cont_page_translation_does_not_exist").": ". - $this->lng->txt("meta_l_".$l)); - $cgui->setCancel($this->lng->txt("cancel"), "editMasterLanguage"); - $cgui->setConfirm($this->lng->txt("confirm"), "createPageTranslation"); - $this->tpl->setContent($cgui->getHTML()); - } - - /** - * Edit master language - */ - function editMasterLanguage() - { - $this->ctrl->setParameter($this, "transl", ""); - $this->ctrl->redirect($this, "edit"); - } - - /** - * Create page translation - */ - function createPageTranslation() - { - $l = ilUtil::stripSlashes($_GET["totransl"]); - - include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); - $p = ilPageObjectFactory::getInstance($this->getPageObject()->getParentType(), - $this->getPageObject()->getId(), 0, "-"); - $p->copyPageToTranslation($l); - $this->ctrl->setParameter($this, "transl", $l); - $this->ctrl->redirect($this, "edit"); - } - - /** - * Release page lock - */ - function releasePageLock() - { - $this->getPageObject()->releasePageLock(); - ilUtil::sendSuccess($this->lng->txt("cont_page_lock_released"), true); - $this->ctrl->redirect($this, "preview"); - } - - protected function isPageContainerToBeRendered() - { - return ( - $this->getRenderPageContainer() || $this->getOutputMode() == IL_PAGE_PREVIEW - ); - } - - /** - * Get page perma link - * - * @param - * @return - */ - function getPagePermaLink() - { - return ""; - } - + } else { + if ($this->getRawPageContent()) { // e.g. needed in glossaries + return $output; + } else { + $tpl->setVariable($this->getTemplateOutputVar(), $output); + return $tpl->get(); + } + } + } + + /** + * Replace curly brackets + * + * @param + * @return + */ + public function replaceCurlyBrackets($output) + { + //echo "

          ".htmlentities($output); + + while (is_int($start = strpos($output, "")) && + is_int($end = strpos($output, "", $start))) { + $output = substr($output, 0, $start) . + str_replace( + array("{","}"), + array("{","}"), + substr($output, $start + 15, $end - ($start + 15)) + ) . + substr($output, $end + 13); + } + + // $output = str_replace("{", "{", $output); + // $output = str_replace("}", "}", $output); + //echo "

          ".htmlentities($output); + return $output; + } + + /** + * Get captions for activation action menu entries + */ + protected function getActivationCaptions() + { + return array("deactivatePage" => $this->lng->txt("cont_deactivate_page"), + "activatePage" => $this->lng->txt("cont_activate_page")); + } + + /** + * Add actions menu + */ + public function addActionsMenu($a_tpl, $sel_media_mode, $sel_html_mode, $sel_js_mode) + { + global $DIC; + + $ui = $DIC->ui(); + + // actions + include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"); + + // activate/deactivate + $list = new ilAdvancedSelectionListGUI(); + $list->setListTitle($this->lng->txt("actions")); + $list->setId("copage_act"); + $entries = false; + if ($this->getPageConfig()->getEnableActivation()) { + $entries = true; + $captions = $this->getActivationCaptions(); + + if ($this->getPageObject()->getActive()) { + $list->addItem( + $captions["deactivatePage"], + "", + $this->ctrl->getLinkTarget($this, "deactivatePage") + ); + } else { + $list->addItem( + $captions["activatePage"], + "", + $this->ctrl->getLinkTarget($this, "activatePage") + ); + } + + $a_tpl->setVariable("PAGE_ACTIONS", $list->getHTML()); + } + + // initially opened content + if ($this->getPageConfig()->getUseAttachedContent()) { + $entries = true; + $list->addItem( + $this->lng->txt("cont_initial_attached_content"), + "", + $this->ctrl->getLinkTarget($this, "initialOpenedContent") + ); + } + + // multi-lang actions + if ($this->addMultiLangActionsAndInfo($list, $a_tpl)) { + $entries = true; + } + + if ($entries) { + $items = $list->getItems(); + if (count($items) > 1) { + $a_tpl->setVariable("PAGE_ACTIONS", $list->getHTML()); + } elseif (count($items) == 1) { + $b = $ui->factory()->button()->standard($items[0]["title"], $items[0]["link"]); + $a_tpl->setVariable("PAGE_ACTIONS", $ui->renderer()->render($b)); + } + } + + $this->lng->loadLanguageModule("content"); + $list = new ilAdvancedSelectionListGUI(); + $list->setListTitle($this->lng->txt("cont_edit_mode")); + $list->setId("copage_ed_mode"); + + // media mode + if ($sel_media_mode == "enable") { + $this->ctrl->setParameter($this, "media_mode", "disable"); + $list->addItem( + $this->lng->txt("cont_deactivate_media"), + "", + $this->ctrl->getLinkTarget($this, "setEditMode") + ); + } else { + $this->ctrl->setParameter($this, "media_mode", "enable"); + $list->addItem( + $this->lng->txt("cont_activate_media"), + "", + $this->ctrl->getLinkTarget($this, "setEditMode") + ); + } + $this->ctrl->setParameter($this, "media_mode", ""); + + // html mode + if (!$this->getPageConfig()->getPreventHTMLUnmasking()) { + if ($sel_html_mode == "enable") { + $this->ctrl->setParameter($this, "html_mode", "disable"); + $list->addItem( + $this->lng->txt("cont_deactivate_html"), + "", + $this->ctrl->getLinkTarget($this, "setEditMode") + ); + } else { + $this->ctrl->setParameter($this, "html_mode", "enable"); + $list->addItem( + $this->lng->txt("cont_activate_html"), + "", + $this->ctrl->getLinkTarget($this, "setEditMode") + ); + } + } + $this->ctrl->setParameter($this, "html_mode", ""); + + // js mode + if ($sel_js_mode == "enable") { + $this->ctrl->setParameter($this, "js_mode", "disable"); + $list->addItem( + $this->lng->txt("cont_deactivate_js"), + "", + $this->ctrl->getLinkTarget($this, "setEditMode") + ); + } else { + $this->ctrl->setParameter($this, "js_mode", "enable"); + $list->addItem( + $this->lng->txt("cont_activate_js"), + "", + $this->ctrl->getLinkTarget($this, "setEditMode") + ); + } + $this->ctrl->setParameter($this, "js_mode", ""); + + $a_tpl->setVariable("EDIT_MODE", $list->getHTML()); + } + + /** + * Add multi-language actions to menu + * + * @param + * @return + */ + public function addMultiLangActionsAndInfo($a_list, $a_tpl) + { + $any_items = false; + + $cfg = $this->getPageConfig(); + + // general multi lang support and single page mode? + if ($cfg->getMultiLangSupport()) { + //include_once("./Services/COPage/classes/class.ilPageMultiLang.php"); + //$ml = new ilPageMultiLang($this->getPageObject()->getParentType(), + // $this->getPageObject()->getParentId()); + + include_once("./Services/Object/classes/class.ilObjectTranslation.php"); + $ot = ilObjectTranslation::getInstance($this->getPageObject()->getParentId()); + + if (!$ot->getContentActivated()) { + /* if ($cfg->getSinglePageMode()) + { + $a_list->addItem($this->lng->txt("cont_activate_multi_lang"), "", + $this->ctrl->getLinkTargetByClass("ilpagemultilanggui", "activateMultilinguality")); + + $any_items = true; + }*/ + } else { + $this->lng->loadLanguageModule("meta"); + //echo $this->getPageObject()->getLanguage(); + if ($this->getPageObject()->getLanguage() != "-") { + $l = $ot->getMasterLanguage(); + $a_list->addItem( + $this->lng->txt("cont_edit_language_version") . ": " . + $this->lng->txt("meta_l_" . $l), + "", + $this->ctrl->getLinkTarget($this, "editMasterLanguage") + ); + } + + foreach ($ot->getLanguages() as $al => $lang) { + if ($this->getPageObject()->getLanguage() != $al && + $al != $ot->getMasterLanguage()) { + $this->ctrl->setParameter($this, "totransl", $al); + $a_list->addItem( + $this->lng->txt("cont_edit_language_version") . ": " . + $this->lng->txt("meta_l_" . $al), + "", + $this->ctrl->getLinkTarget($this, "switchToLanguage") + ); + $this->ctrl->setParameter($this, "totransl", $_GET["totransl"]); + } + } + + /* if ($cfg->getSinglePageMode()) + { + $a_list->addItem($this->lng->txt("cont_manage_multilang"), "", + $this->ctrl->getLinkTargetByClass("ilpagemultilanggui", "settings")); + }*/ + + include_once("./Services/COPage/classes/class.ilPageMultiLangGUI.php"); + $ml_gui = new ilPageMultiLangGUI( + $this->getPageObject()->getParentType(), + $this->getPageObject()->getParentId() + ); + $a_tpl->setVariable("MULTI_LANG_INFO", $ml_gui->getMultiLangInfo($this->getPageObject()->getLanguage())); + + $any_items = true; + } + } + + return $any_items; + } + + + /** + * Set edit mode + */ + public function setEditMode() + { + if ($_GET["media_mode"] != "") { + if ($_GET["media_mode"] == "disable") { + $this->user->writePref("ilPageEditor_MediaMode", "disable"); + } else { + $this->user->writePref("ilPageEditor_MediaMode", ""); + } + } + if ($_GET["html_mode"] != "") { + if ($_GET["html_mode"] == "disable") { + $this->user->writePref("ilPageEditor_HTMLMode", "disable"); + } else { + $this->user->writePref("ilPageEditor_HTMLMode", ""); + } + } + if ($_GET["js_mode"] != "") { + if ($_GET["js_mode"] == "disable") { + $this->user->writePref("ilPageEditor_JavaScript", "disable"); + } else { + $this->user->writePref("ilPageEditor_JavaScript", ""); + } + } + + $this->ctrl->redirect($this, "edit"); + } + + + /** + * Get Tiny Menu + */ + public static function getTinyMenu( + $a_par_type, + $a_int_links = false, + $a_wiki_links = false, + $a_keywords = false, + $a_style_id = 0, + $a_paragraph_styles = true, + $a_save_return = true, + $a_anchors = false, + $a_save_new = true, + $a_user_links = false + ) { + global $DIC; + + $lng = $DIC->language(); + $ctrl = $DIC->ctrl(); + + $mathJaxSetting = new ilSetting("MathJax"); + + include_once("./Services/COPage/classes/class.ilPageEditorSettings.php"); + + include_once("./Services/UIComponent/Tooltip/classes/class.ilTooltipGUI.php"); + + $btpl = new ilTemplate("tpl.tiny_menu.html", true, true, "Services/COPage"); + + // debug ghost element + if (DEVMODE == 1) { + $btpl->touchBlock("debug_ghost"); + } + + // bullet list + $btpl->touchBlock("blist_button"); + ilTooltipGUI::addTooltip( + "il_edm_blist", + $lng->txt("cont_blist"), + "iltinymenu_bd" + ); + + // numbered list + $btpl->touchBlock("nlist_button"); + ilTooltipGUI::addTooltip( + "il_edm_nlist", + $lng->txt("cont_nlist"), + "iltinymenu_bd" + ); + + // list indent + $btpl->touchBlock("list_indent"); + ilTooltipGUI::addTooltip( + "ilIndentBut", + $lng->txt("cont_list_indent"), + "iltinymenu_bd" + ); + + // list outdent + $btpl->touchBlock("list_outdent"); + ilTooltipGUI::addTooltip( + "ilOutdentBut", + $lng->txt("cont_list_outdent"), + "iltinymenu_bd" + ); + + if ($a_int_links) { + $btpl->touchBlock("bb_ilink_button"); + ilTooltipGUI::addTooltip( + "iosEditInternalLinkTrigger", + $lng->txt("cont_link_to_internal"), + "iltinymenu_bd" + ); + } + ilTooltipGUI::addTooltip( + "il_edm_xlink", + $lng->txt("cont_link_to_external"), + "iltinymenu_bd" + ); + + if ($a_user_links) { + $btpl->touchBlock("bb_ulink_button"); + } + + // remove format + $btpl->touchBlock("rformat_button"); + ilTooltipGUI::addTooltip( + "il_edm_rformat", + $lng->txt("cont_remove_format"), + "iltinymenu_bd" + ); + + if ($a_paragraph_styles) { + // new paragraph + $btpl->setCurrentBlock("new_par"); + $btpl->setVariable("IMG_NEWPAR", "+"); + $btpl->parseCurrentBlock(); + ilTooltipGUI::addTooltip( + "il_edm_newpar", + $lng->txt("cont_insert_new_paragraph"), + "iltinymenu_bd" + ); + + $btpl->setCurrentBlock("par_edit"); + $btpl->setVariable("TXT_PAR_FORMAT", $lng->txt("cont_par_format")); + include_once("./Services/COPage/classes/class.ilPCParagraphGUI.php"); + $btpl->setVariable("STYLE_SELECTOR", ilPCParagraphGUI::getStyleSelector( + $a_selected, + ilPCParagraphGUI::_getCharacteristics($a_style_id), + true + )); + + ilTooltipGUI::addTooltip( + "ilAdvSelListAnchorText_style_selection", + $lng->txt("cont_paragraph_styles"), + "iltinymenu_bd" + ); + + $btpl->parseCurrentBlock(); + } + + if ($a_keywords) { + $btpl->setCurrentBlock("bb_kw_button"); + $btpl->setVariable("CC_KW", "kw"); + $btpl->parseCurrentBlock(); + ilTooltipGUI::addTooltip( + "il_edm_kw", + $lng->txt("cont_text_keyword"), + "iltinymenu_bd" + ); + } + + if ($a_wiki_links) { + $btpl->setCurrentBlock("bb_wikilink_button2"); + $btpl->setVariable("TXT_WIKI_BUTTON2", $lng->txt("obj_wiki")); + $btpl->setVariable("WIKI_BUTTON2_URL", $ctrl->getLinkTargetByClass("ilwikipagegui", "")); + $btpl->parseCurrentBlock(); + ilTooltipGUI::addTooltip( + "il_edm_wlinkd", + $lng->txt("cont_wiki_link_dialog"), + "iltinymenu_bd" + ); + + $btpl->setCurrentBlock("bb_wikilink_button"); + $btpl->setVariable("TXT_WLN2", $lng->txt("obj_wiki")); + $btpl->parseCurrentBlock(); + ilTooltipGUI::addTooltip( + "il_edm_wlink", + $lng->txt("cont_link_to_wiki"), + "iltinymenu_bd" + ); + } + + $aset = new ilSetting("adve"); + + include_once("./Services/COPage/classes/class.ilPageContentGUI.php"); + foreach (ilPageContentGUI::_getCommonBBButtons() as $c => $st) { + // these are handled via drop down now... + if (in_array($c, array("com", "quot", "acc", "code"))) { + continue; + } + if (ilPageEditorSettings::lookupSettingByParentType( + $a_par_type, + "active_" . $c, + true + )) { + $cc_code = $c; + if ($aset->get("use_physical")) { + $cc_code = str_replace(array("str", "emp", "imp"), array("B", "I", "U"), $cc_code); + } + + if ($c != "tex" || $mathJaxSetting->get("enable") || defined("URL_TO_LATEX")) { + $btpl->setCurrentBlock("bb_" . $c . "_button"); + $btpl->setVariable("CC_" . strtoupper($c), $cc_code); + $btpl->parseCurrentBlock(); + ilTooltipGUI::addTooltip( + "il_edm_cc_" . $c, + $lng->txt("cont_cc_" . $c), + "iltinymenu_bd" + ); + + // $btpl->setVariable("TXT_".strtoupper($c), $this->lng->txt("cont_text_".$c)); + } + } + } + + if ($mathJaxSetting->get("enable") || defined("URL_TO_LATEX")) { + ilTooltipGUI::addTooltip( + "il_edm_tex", + $lng->txt("cont_tex"), + "iltinymenu_bd" + ); + } + ilTooltipGUI::addTooltip( + "il_edm_fn", + $lng->txt("cont_fn"), + "iltinymenu_bd" + ); + + include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"); + $sdd = new ilAdvancedSelectionListGUI(); + $sdd->setPullRight(false); + $sdd->setListTitle($lng->txt("save") . "..."); + + if ($a_save_return) { + $btpl->setCurrentBlock("save_return"); + $btpl->setVariable("TXT_SAVE_RETURN", $lng->txt("save_return")); + $btpl->parseCurrentBlock(); + $sdd->addItem($lng->txt("save_return"), "", "#", "", "", "", "", "", "ilCOPage.cmdSaveReturn(false); return false;"); + } + + if ($a_save_new) { + $btpl->setCurrentBlock("save_new"); + $btpl->setVariable("TXT_SAVE_NEW", $lng->txt("save_new")); + $btpl->parseCurrentBlock(); + $sdd->addItem($lng->txt("save_new"), "", "#", "", "", "", "", "", "ilCOPage.cmdSaveReturn(true); return false;"); + } + + $sdd->addItem($lng->txt("save"), "", "#", "", "", "", "", "", "ilCOPage.cmdSave(null); return false;"); + $sdd->addItem($lng->txt("cancel"), "", "#", "", "", "", "", "", "ilCOPage.cmdCancel(); return false;"); + + if ($a_anchors) { + $btpl->setCurrentBlock("bb_anc_button"); + $btpl->setVariable("CC_ANC", "anc"); + $btpl->parseCurrentBlock(); + ilTooltipGUI::addTooltip( + "il_edm_anc", + $lng->txt("cont_anchor"), + "iltinymenu_bd" + ); + } + + $btpl->setVariable("SAVE_DROPDOWN", $sdd->getHTML()); + + /* // footnote + $btpl->setVariable("TXT_ILN", $this->lng->txt("cont_text_iln")); + $btpl->setVariable("TXT_BB_TIP", $this->lng->txt("cont_bb_tip")); + $btpl->setVariable("TXT_WLN", $lng->txt("wiki_wiki_page")); + */ + // $btpl->setVariable("PAR_TA_NAME", $a_ta_name); + + $btpl->setVariable("TXT_SAVE", $lng->txt("save")); + $btpl->setVariable("TXT_CANCEL", $lng->txt("cancel")); + + $btpl->setVariable("TXT_CHAR_FORMAT", $lng->txt("cont_char_format")); + $btpl->setVariable("TXT_LISTS", $lng->txt("cont_lists")); + $btpl->setVariable("TXT_LINKS", $lng->txt("cont_links")); + $btpl->setVariable("TXT_MORE_FUNCTIONS", $lng->txt("cont_more_functions")); + $btpl->setVariable("TXT_SAVING", $lng->txt("cont_saving")); + + include_once("./Services/COPage/classes/class.ilPCParagraphGUI.php"); + + $btpl->setVariable("CHAR_STYLE_SELECTOR", ilPCParagraphGUI::getCharStyleSelector($a_par_type, true, $a_style_id)); + ilTooltipGUI::addTooltip( + "ilAdvSelListAnchorElement_char_style_selection", + $lng->txt("cont_more_character_styles"), + "iltinymenu_bd" + ); + + return $btpl->get(); + } + + /** + * Set standard link xml + */ + public function setDefaultLinkXml() + { + $int_links = $this->getPageObject()->getInternalLinks(); + //var_dump($int_links); + $link_info = ""; + $targetframe = "None"; + foreach ($int_links as $int_link) { + $target = $int_link["Target"]; + if (substr($target, 0, 4) == "il__") { + $target_arr = explode("_", $target); + $target_id = $target_arr[count($target_arr) - 1]; + $type = $int_link["Type"]; + + $targetframe = ($int_link["TargetFrame"] != "") + ? $int_link["TargetFrame"] + : "None"; + + $ltarget="_top"; + if ($targetframe != "None") { + $ltarget="_blank"; + } + + // anchor + $anc = $anc_add = ""; + if ($int_link["Anchor"] != "") { + $anc = $int_link["Anchor"]; + $anc_add = "_" . rawurlencode($int_link["Anchor"]); + } + + $href = ""; + $lcontent = ""; + switch ($type) { + case "PageObject": + case "StructureObject": + $lm_id = ilLMObject::_lookupContObjID($target_id); + if ($type == "PageObject") { + $href = "./goto.php?target=pg_" . $target_id . $anc_add; + } else { + $href = "./goto.php?target=st_" . $target_id; + } + if ($lm_id == "") { + $href = ""; + } + break; + + case "GlossaryItem": + if ($targetframe == "None") { + $targetframe = "Glossary"; + } + $href = "./goto.php?target=git_" . $target_id; + break; + + case "MediaObject": + $this->ctrl->setParameter($this, "mob_id", $target_id); + //$this->ctrl->setParameter($this, "pg_id", $this->obj->getId()); + $href = $this->ctrl->getLinkTarget($this, "displayMedia"); + $this->ctrl->setParameter($this, "mob_id", ""); + break; + + case "WikiPage": + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + $href = ilWikiPage::getGotoForWikiPageTarget($target_id); + break; + + case "PortfolioPage": + include_once("./Modules/Portfolio/classes/class.ilPortfolioPage.php"); + $href = ilPortfolioPage::getGotoForPortfolioPageTarget($target_id, ($this->getOutputMode() == "offline")); + break; + + case "RepositoryItem": + $obj_type = ilObject::_lookupType($target_id, true); + $obj_id = ilObject::_lookupObjId($target_id); + $href = "./goto.php?target=" . $obj_type . "_" . $target_id; + break; + + case "User": + $obj_type = ilObject::_lookupType($target_id); + if ($obj_type == "usr") { + include_once("./Services/User/classes/class.ilUserUtil.php"); + $back = $this->getProfileBackUrl(); + //var_dump($back); exit; + $this->ctrl->setParameterByClass("ilpublicuserprofilegui", "user_id", $target_id); + if (strlen($back)) { + $this->ctrl->setParameterByClass( + "ilpublicuserprofilegui", + "back_url", + rawurlencode($back) + ); + } + $href = ""; + include_once("./Services/User/classes/class.ilUserUtil.php"); + if (ilUserUtil::hasPublicProfile($target_id)) { + $href = $this->ctrl->getLinkTargetByClass(["ilpersonaldesktopgui", "ilpublicuserprofilegui"], "getHTML"); + } + $this->ctrl->setParameterByClass("ilpublicuserprofilegui", "user_id", ""); + $lcontent = ilUserUtil::getNamePresentation($target_id, false, false); + } + break; + + } + if ($href != "") { + $anc_par = 'Anchor="' . $anc . '"'; + $link_info .= ""; + } + } + } + $link_info.= ""; + $this->setLinkXML($link_info); + } + + /** + * Get profile back url + */ + public function getProfileBackUrl() + { + return $this->ctrl->getLinkTargetByClass(strtolower(get_class($this)), "preview"); + } + + + /** + * Download file of file lists + */ + public function downloadFile() + { + $this->obj->buildDom(); + + include_once("./Services/COPage/classes/class.ilPCFileList.php"); + $files = ilPCFileList::collectFileItems($this->obj, $this->obj->getDomDoc()); + + $file = explode("_", $_GET["file_id"]); + require_once("./Modules/File/classes/class.ilObjFile.php"); + $file_id = $file[count($file) - 1]; + + // file must be in page + if (!in_array($file_id, $files)) { + exit; + } + $fileObj = new ilObjFile($file_id, false); + $fileObj->sendFile(); + exit; + } + + /** + * Show media in fullscreen mode + */ + public function displayMediaFullscreen() + { + $this->displayMedia(true); + } + + /** + * Display media + */ + public function displayMedia($a_fullscreen = false) + { + $tpl = $this->tpl; + + $tpl = new ilTemplate("tpl.fullscreen.html", true, true, "Modules/LearningModule"); + $tpl->setCurrentBlock("ilMedia"); + + //$int_links = $page_object->getInternalLinks(); + $med_links = ilMediaItem::_getMapAreasIntLinks($_GET["mob_id"]); + + // @todo + //$link_xml = $this->getLinkXML($med_links, $this->getLayoutLinkTargets()); + + require_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $media_obj = new ilObjMediaObject($_GET["mob_id"]); + require_once("./Services/COPage/classes/class.ilPageObject.php"); + $pg_obj = $this->getPageObject(); + $pg_obj->buildDom(); + + if (!empty($_GET["pg_id"])) { + $xml = ""; + $xml.= $pg_obj->getMediaAliasElement($_GET["mob_id"]); + $xml.= $media_obj->getXML(IL_MODE_OUTPUT); + $xml.= $link_xml; + $xml.=""; + } else { + $xml = ""; + $xml.= $media_obj->getXML(IL_MODE_ALIAS); + $xml.= $media_obj->getXML(IL_MODE_OUTPUT); + $xml.= $link_xml; + $xml.=""; + } + + $xsl = file_get_contents("./Services/COPage/xsl/page.xsl"); + $args = array( '/_xml' => $xml, '/_xsl' => $xsl ); + $xh = xslt_create(); + + $mode = "media"; + if ($a_fullscreen) { + $mode = "fullscreen"; + } + + //echo "XML:".htmlentities($xml); + // determine target frames for internal links + $wb_path = ilUtil::getWebspaceDir("output") . "/"; + $enlarge_path = ilUtil::getImagePath("enlarge.svg"); + $params = array('mode' => $mode, 'enlarge_path' => $enlarge_path, + 'link_params' => "ref_id=" . $_GET["ref_id"],'fullscreen_link' => "", + 'ref_id' => $_GET["ref_id"], 'webspace_path' => $wb_path); + $output = xslt_process($xh, "arg:/_xml", "arg:/_xsl", null, $args, $params); + //echo "

          ".htmlentities($output); + //echo xslt_error($xh); + xslt_free($xh); + + // unmask user html + require_once('./Services/Style/Content/classes/class.ilObjStyleSheet.php'); + $tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath(0) + ); + $tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); + $tpl->setVariable("MEDIA_CONTENT", $output); + + // add js + include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); + ilObjMediaObjectGUI::includePresentationJS($tpl); + $tpl->fillJavaScriptFiles(); + $tpl->fillCssFiles(); + + echo $tpl->get(); + exit; + } + + /** + * download source code paragraph + */ + public function download_paragraph() + { + $pg_obj = $this->getPageObject(); + $pg_obj->send_paragraph($_GET["par_id"], $_GET["downloadtitle"]); + } + + /** + * Insert page toc + * + * @param string output + * @return string output + */ + public function insertPageToc($a_output) + { + include_once("./Services/Utilities/classes/class.ilStr.php"); + + // extract all headings + $offsets = ilStr::strPosAll($a_output, "ilPageTocH"); + $page_heads = array(); + foreach ($offsets as $os) { + $level = (int) substr($a_output, $os + 10, 1); + if (in_array($level, array(1,2,3))) { + $anchor = str_replace( + "TocH", + "TocA", + substr($a_output, $os, strpos($a_output, "<", $os) - $os - 3) + ); + + // get heading + $tag_start = stripos($a_output, "", $tag_start); + $head = substr($a_output, $tag_start, $tag_end - $tag_start); + + // get headings text + $text_start = stripos($head, ">") + 1; + $text_end = strripos($head, "", "", $h["text"]); + + // add the list node + $list->addListNode( + "" . $h["text"] . "", + $i, + $par + ); + + // set the node as current parent of the level + if ($h["level"] == 1) { + $c_par[1] = $i; + $c_par[2] = 0; + } + if ($h["level"] == 2) { + $c_par[2] = $i; + } + } + + $tpl = new ilTemplate( + "tpl.page_toc.html", + true, + true, + "Services/COPage" + ); + $tpl->setVariable("PAGE_TOC", $list->getHTML()); + $tpl->setVariable("TXT_PAGE_TOC", $this->lng->txt("cont_page_toc")); + $tpl->setVariable("TXT_HIDE", $this->lng->txt("hide")); + $tpl->setVariable("TXT_SHOW", $this->lng->txt("show")); + + $a_output = str_replace( + "{{{{{PageTOC}}}}}", + $tpl->get(), + $a_output + ); + $numbers = $list->getNumbers(); + + if (count($numbers) > 0) { + include_once("./Services/Utilities/classes/class.ilStr.php"); + foreach ($numbers as $n) { + $a_output = + ilStr::replaceFirsOccurence("", $n . " ", $a_output); + } + } + } else { + $a_output = str_replace( + "{{{{{PageTOC}}}}}", + "", + $a_output + ); + } + + return $a_output; + } + + /** + * Insert resources + * + * @param + * @return + */ + public function insertResources($a_output) + { + // this is edit mode only + + if ($this->getEnablePCType("Resources") && + ($this->getOutputMode() == "edit" || $this->getOutputMode() == "preview")) { + include_once("./Services/COPage/classes/class.ilPCResourcesGUI.php"); + $a_output = ilPCResourcesGUI::insertResourcesIntoPageContent($a_output, $this->getOutputMode()); + } + return $a_output; + } + + + + /** + * Insert adv content trigger + * + * @param string $a_output output + * @return string modified output + */ + public function insertAdvTrigger($a_output) + { + if (!$this->getAbstractOnly()) { + $a_output = str_replace( + "{{{{{LV_show_adv}}}}}", + $this->lng->txt("cont_show_adv"), + $a_output + ); + $a_output = str_replace( + "{{{{{LV_hide_adv}}}}}", + $this->lng->txt("cont_hide_adv"), + $a_output + ); + } else { + $a_output = str_replace( + "{{{{{LV_show_adv}}}}}", + "", + $a_output + ); + $a_output = str_replace( + "{{{{{LV_hide_adv}}}}}", + "", + $a_output + ); + } + + return $a_output; + } + + + /** + * Finalizing output processing. Maybe overwritten in derived + * classes, e.g. in wiki module. + */ + public function postOutputProcessing($a_output) + { + return $a_output; + } + + /** + * Insert help texts + */ + public function insertHelp($a_tpl) + { + $a_tpl->setCurrentBlock("help"); + $a_tpl->setVariable("TXT_ADD_EL", $this->lng->txt("cont_add_elements")); + include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); + $a_tpl->setVariable("PLUS", ilGlyphGUI::get(ilGlyphGUI::ADD)); + $a_tpl->setVariable("DRAG_ARROW", ilGlyphGUI::get(ilGlyphGUI::DRAG)); + $a_tpl->setVariable("TXT_DRAG", $this->lng->txt("cont_drag_and_drop_elements")); + $a_tpl->setVariable("TXT_SEL", $this->lng->txt("cont_double_click_to_delete")); + $a_tpl->parseCurrentBlock(); + } + + /** + * Preview history + */ + public function previewHistory() + { + $this->preview(); + } + + /** + * preview + */ + public function preview() + { + $this->setOutputMode(IL_PAGE_PREVIEW); + return $this->showPage(); + } + + /** + * edit ("view" before) + */ + public function edit() + { + // editing allowed? + if (!$this->getEnableEditing()) { + ilUtil::sendFailure($this->lng->txt("permission_denied"), true); + $this->ctrl->redirect($this, "preview"); + } + + // not so nive workaround for container pages, bug #0015831 + $ptype = $this->getParentType(); + if ($ptype == "cont" && $_GET["ref_id"] > 0) { + $ptype = ilObject::_lookupType((int) $_GET["ref_id"], true); + } + $this->help->setScreenId("edit_" . $ptype); + + require_once 'Services/Captcha/classes/class.ilCaptchaUtil.php'; + if ( + $this->user->isAnonymous() && + !$this->user->isCaptchaVerified() && + ilCaptchaUtil::isActiveForWiki() + ) { + $form = $this->initCaptchaForm(); + if ($_POST['captcha_code'] && $form->checkInput()) { + $this->user->setCaptchaVerified(true); + } else { + return $form->getHTML(); + } + } + + // edit lock + if (!$this->getPageObject()->getEditLock()) { + include_once("./Services/User/classes/class.ilUserUtil.php"); + $info = $this->lng->txt("content_no_edit_lock"); + $lock = $this->getPageObject()->getEditLockInfo(); + $info .= "
          " . $this->lng->txt("content_until") . ": " . + ilDatePresentation::formatDate(new ilDateTime($lock["edit_lock_until"], IL_CAL_UNIX)); + $info .= "
          " . $this->lng->txt("obj_usr") . ": " . + ilUserUtil::getNamePresentation($lock["edit_lock_user"]); + if (!$this->ctrl->isAsynch()) { + ilUtil::sendInfo($info); + return ""; + } else { + echo $this->tpl->getMessageHTML($info); + exit; + } + } else { + if ($this->getPageObject()->getEffectiveEditLockTime() > 0) { + $mess = $this->getBlockingInfoMessage(); + } + } + + $this->setOutputMode(IL_PAGE_EDIT); + + $html = $this->showPage(); + + if ($this->isEnabledNotes()) { + $html.= "

          " . $this->getNotesHTML(); + } + + return $mess . $html; + } + + /** + * Get block info message + * @return string + */ + protected function getBlockingInfoMessage() : string + { + $ctrl = $this->ctrl; + $lng = $this->lng; + $ui = $this->ui; + + $lock = $this->getPageObject()->getEditLockInfo(); + $info = $this->lng->txt("cont_got_lock_release"); + $info = str_replace("%1", ilDatePresentation::formatDate(new ilDateTime($lock["edit_lock_until"], IL_CAL_UNIX)), $info); + + $mbox = $ui->factory()->messageBox()->info($info) + ->withButtons([$ui->factory()->button()->standard($lng->txt("cont_finish_editing"), $ctrl->getLinkTarget($this, "releasePageLock"))]); + + return $ui->renderer()->render($mbox); + } + + + /** + * InsertJS at placeholder + * + * @param + * @return + */ + public function insertJSAtPlaceholder() + { + $tpl = $this->tpl; + + if ($_GET["pl_hier_id"] == "") { + $this->obj->buildDom(); + $this->obj->addHierIDs(); + $hid = $this->obj->getHierIdsForPCIds(array($_GET["pl_pc_id"])); + $_GET["pl_hier_id"] = $hid[$_GET["pl_pc_id"]]; + } + + // 'pl_hier_id' => string '2_1_1_1' (length=7) + // 'pl_pc_id' => string '1f77eb1d8a478497d69b99d938fda8f' (length=31) + $html = $this->edit(); + + $tpl->addOnLoadCode("ilCOPage.insertJSAtPlaceholder('" . + $_GET["pl_hier_id"] . ":" . $_GET["pl_pc_id"] . + "');", 3); + + return $html; + } + + /** + * Init captcha form. + */ + public function initCaptchaForm() + { + require_once 'Services/Form/classes/class.ilPropertyFormGUI.php'; + $form = new ilPropertyFormGUI(); + + require_once 'Services/Captcha/classes/class.ilCaptchaInputGUI.php'; + $ci = new ilCaptchaInputGUI($this->lng->txt('cont_captcha_code'), 'captcha_code'); + $ci->setRequired(true); + $form->addItem($ci); + + $form->addCommandButton('edit', $this->lng->txt('ok')); + + $form->setTitle($this->lng->txt('cont_captcha_verification')); + $form->setFormAction($this->ctrl->getFormAction($this)); + + return $form; + } + + /* + * presentation + */ + public function presentation($a_mode = IL_PAGE_PRESENTATION) + { + $this->setOutputMode($a_mode); + + return $this->showPage(); + } + + public function getHTML() + { + $this->getTabs("preview"); + return $this->showPage(); + } + + /** + * show fullscreen view of media object + */ + public function showMediaFullscreen($a_style_id = 0) + { + $this->tpl = new ilTemplate("tpl.fullscreen.html", true, true, "Services/COPage"); + $this->tpl->setCurrentBlock("ContentStyle"); + $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", 0); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setVariable("PAGETITLE", " - " . ilObject::_lookupTitle($_GET["mob_id"])); + $this->tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); + $this->tpl->setCurrentBlock("ilMedia"); + + require_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $media_obj = new ilObjMediaObject($_GET["mob_id"]); + if (!empty($_GET["pg_id"])) { + include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); + $pg_obj = ilPageObjectFactory::getInstance($this->obj->getParentType(), $_GET["pg_id"]); + $pg_obj->buildDom(); + + $xml = ""; + // todo: we get always the first alias now (problem if mob is used multiple + // times in page) + $xml.= $pg_obj->getMediaAliasElement($_GET["mob_id"]); + $xml.= $media_obj->getXML(IL_MODE_OUTPUT); + $xml.=""; + } else { + $xml = ""; + $xml.= $media_obj->getXML(IL_MODE_ALIAS); + $xml.= $media_obj->getXML(IL_MODE_OUTPUT); + $xml.=""; + } + + //echo htmlentities($xml); exit; + + $xsl = file_get_contents("./Services/COPage/xsl/page.xsl"); + $args = array( '/_xml' => $xml, '/_xsl' => $xsl ); + $xh = xslt_create(); + + //echo "XML:".htmlentities($xml); + // determine target frames for internal links + //$pg_frame = $_GET["frame"]; + $wb_path = ilUtil::getWebspaceDir("output") . "/"; + $mode = "fullscreen"; + $params = array('mode' => $mode, 'webspace_path' => $wb_path); + $output = xslt_process($xh, "arg:/_xml", "arg:/_xsl", null, $args, $params); + echo xslt_error($xh); + xslt_free($xh); + + // unmask user html + $this->tpl->setVariable("MEDIA_CONTENT", $output); + } + + /** + * display validation error + * + * @param string $a_error error string + */ + public function displayValidationError($a_error) + { + if (is_array($a_error)) { + $error_str = "Error(s):
          "; + foreach ($a_error as $error) { + $err_mess = implode($error, " - "); + if (!is_int(strpos($err_mess, ":0:"))) { + $error_str .= htmlentities($err_mess) . "
          "; + } + } + $this->tpl->setVariable("MESSAGE", $error_str); + } + } + + /** + * Get history table as HTML. + */ + public function history() + { + if (!$this->getEnableEditing()) { + return; + } + + $this->tpl->addJavaScript("./Services/COPage/js/page_history.js"); + + include_once("./Services/COPage/classes/class.ilPageHistoryTableGUI.php"); + $table_gui = new ilPageHistoryTableGUI($this, "history"); + $table_gui->setId("hist_table"); + $entries = $this->getPageObject()->getHistoryEntries(); + $entries[] = array('page_id' => $this->getPageObject()->getId(), + 'parent_type' => $this->getPageObject()->getParentType(), + 'hdate' => $this->getPageObject()->getLastChange(), + 'parent_id' => $this->getPageObject()->getParentId(), + 'nr' => 0, + 'sortkey' => 999999, + 'user' => $this->getPageObject()->last_change_user); + $table_gui->setData($entries); + return $table_gui->getHTML(); + } + + /** + * Rollback confirmation + */ + public function rollbackConfirmation() + { + if (!$this->getEnableEditing()) { + return; + } + + include_once("Services/Utilities/classes/class.ilConfirmationGUI.php"); + $c_gui = new ilConfirmationGUI(); + + // set confirm/cancel commands + $this->ctrl->setParameter($this, "rollback_nr", $_GET["old_nr"]); + $c_gui->setFormAction($this->ctrl->getFormAction($this, "rollback")); + $c_gui->setHeaderText($this->lng->txt("cont_rollback_confirmation")); + $c_gui->setCancel($this->lng->txt("cancel"), "history"); + $c_gui->setConfirm($this->lng->txt("confirm"), "rollback"); + + $hentry = $this->obj->getHistoryEntry($_GET["old_nr"]); + + $c_gui->addItem( + "id[]", + $_GET["old_nr"], + ilDatePresentation::formatDate(new ilDateTime($hentry["hdate"], IL_CAL_DATETIME)) + ); + + $this->tpl->setContent($c_gui->getHTML()); + } + + /** + * Rollback to a previous version + */ + public function rollback() + { + if (!$this->getEnableEditing()) { + return; + } + + $hentry = $this->obj->getHistoryEntry($_GET["rollback_nr"]); + + if ($hentry["content"] != "") { + $this->obj->setXMLContent($hentry["content"]); + $this->obj->buildDom(true); + if ($this->obj->update()) { + $this->ctrl->redirect($this, "history"); + } + } + $this->ctrl->redirect($this, "history"); + } + + /** + * Set screen id component + * + * @param + * @return + */ + public function setScreenIdComponent() + { + $this->help->setScreenIdComponent("copg"); + } + + /** + * adds tabs to tab gui object + * + * @param object $tabs_gui ilTabsGUI object + */ + public function getTabs($a_activate = "") + { + $this->setScreenIdComponent(); + + if (!$this->getEnabledTabs()) { + return; + } + + // back to upper context + if (!$this->getEditPreview()) { + $this->tabs_gui->addTarget("pg", $this->ctrl->getLinkTarget($this, "preview"), array("", "preview")); + + if ($this->getEnableEditing()) { + $this->tabs_gui->addTarget("edit", $this->ctrl->getLinkTarget($this, "edit"), array("", "edit")); + } + } else { + if ($this->getEnableEditing()) { + $this->tabs_gui->addTarget("edit", $this->ctrl->getLinkTarget($this, "edit"), array("", "edit")); + } + + $this->tabs_gui->addTarget("cont_preview", $this->ctrl->getLinkTarget($this, "preview"), array("", "preview")); + } + + //$tabs_gui->addTarget("properties", $this->ctrl->getLinkTarget($this, "properties") + // , "properties", get_class($this)); + + if ($this->use_meta_data) { + include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php"; + $mdgui = new ilObjectMetaDataGUI( + $this->meta_data_rep_obj, + $this->meta_data_type, + $this->meta_data_sub_obj_id + ); + $mdtab = $mdgui->getTab(); + if ($mdtab) { + $this->tabs_gui->addTarget( + "meta_data", + $mdtab, + "", + "ilobjectmetadatagui" + ); + } + } + + $lm_set = new ilSetting("lm"); + + if ($this->getEnableEditing() && $lm_set->get("page_history", 1)) { + $this->tabs_gui->addTarget("history", $this->ctrl->getLinkTarget($this, "history"), "history", get_class($this)); + if ($_GET["history_mode"] == "1" || $this->ctrl->getCmd() == "compareVersion") { + $this->tabs_gui->activateTab("history"); + } + } + + /* $tabs = $this->ctrl->getTabs(); + foreach ($tabs as $tab) + { + $tabs_gui->addTarget($tab["lang_var"], $tab["link"] + , $tab["cmd"], $tab["class"]); + } + */ + if ($this->getEnableEditing() && $this->user->getId() != ANONYMOUS_USER_ID) { + $this->tabs_gui->addTarget("clipboard", $this->ctrl->getLinkTargetByClass(array(get_class($this), "ilEditClipboardGUI"), "view"), "view", "ilEditClipboardGUI"); + } + + if ($this->getPageConfig()->getEnableScheduledActivation()) { + $this->tabs_gui->addTarget( + "cont_activation", + $this->ctrl->getLinkTarget($this, "editActivation"), + "editActivation", + get_class($this) + ); + } + + if ($this->getEnabledNews()) { + $this->tabs_gui->addTarget( + "news", + $this->ctrl->getLinkTargetByClass("ilnewsitemgui", "editNews"), + "", + "ilnewsitemgui" + ); + } + + // external hook to add tabs + if (is_array($this->tab_hook)) { + $func = $this->tab_hook["func"]; + $this->tab_hook["obj"]->$func(); + } + //$this->tabs_gui->setTabActive("pg"); + } + + /** + * Compares two revisions of the page + */ + public function compareVersion() + { + if (!$this->getEnableEditing()) { + return; + } + + $tpl = new ilTemplate("tpl.page_compare.html", true, true, "Services/COPage"); + $compare = $this->obj->compareVersion((int) $_POST["left"], (int) $_POST["right"]); + + // left page + $lpage = $compare["l_page"]; + $cfg = $this->getPageConfig(); + $cfg->setPreventHTMLUnmasking(true); + + $this->setOutputMode(IL_PAGE_PREVIEW); + $this->setPageObject($lpage); + $this->setPresentationTitle($this->getPresentationTitle()); + $this->setCompareMode(true); + + $lhtml = $this->showPage(); + $lhtml = $this->replaceDiffTags($lhtml); + $lhtml = str_replace("<br />", "
          ", $lhtml); + $tpl->setVariable("LEFT", $lhtml); + + // right page + $rpage = $compare["r_page"]; + $this->setPageObject($rpage); + $this->setPresentationTitle($this->getPresentationTitle()); + $this->setCompareMode(true); + $this->setOutputMode(IL_PAGE_PREVIEW); + + $rhtml = $this->showPage(); + $rhtml = $this->replaceDiffTags($rhtml); + $rhtml = str_replace("<br />", "
          ", $rhtml); + $tpl->setVariable("RIGHT", $rhtml); + + $tpl->setVariable("TXT_NEW", $this->lng->txt("cont_pc_new")); + $tpl->setVariable("TXT_MODIFIED", $this->lng->txt("cont_pc_modified")); + $tpl->setVariable("TXT_DELETED", $this->lng->txt("cont_pc_deleted")); + + //var_dump($left); + //var_dump($right); + + return $tpl->get(); + } + + public function replaceDiffTags($a_html) + { + $a_html = str_replace("[ilDiffInsStart]", '', $a_html); + $a_html = str_replace("[ilDiffDelStart]", '', $a_html); + $a_html = str_replace("[ilDiffInsEnd]", '', $a_html); + $a_html = str_replace("[ilDiffDelEnd]", '', $a_html); + + return $a_html; + } + + /** + * Edit activation (only, if scheduled page activation is activated in administration) + */ + public function editActivation() + { + $atpl = new ilTemplate("tpl.page_activation.php", true, true, "Services/COPage"); + $this->initActivationForm(); + $this->getActivationFormValues(); + $atpl->setVariable("FORM", $this->form->getHTML()); + $atpl->setCurrentBlock("updater"); + $atpl->setVariable("UPDATER_FRAME", $this->exp_frame); + $atpl->setVariable("EXP_ID_UPDATER", $this->exp_id); + $atpl->setVariable("HREF_UPDATER", $this->exp_target_script); + $atpl->parseCurrentBlock(); + $this->tpl->setContent($atpl->get()); + } + + /** + * Init activation form + */ + public function initActivationForm() + { + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + $this->form->setFormAction($this->ctrl->getFormAction($this)); + $this->form->setTitle($this->lng->txt("cont_page_activation")); + + // activation type radio + $rad = new ilRadioGroupInputGUI($this->lng->txt("cont_activation"), "activation"); + $rad_op1 = new ilRadioOption($this->lng->txt("cont_activated"), "activated"); + + $rad->addOption($rad_op1); + $rad_op2 = new ilRadioOption($this->lng->txt("cont_deactivated"), "deactivated"); + $rad->addOption($rad_op2); + $rad_op3 = new ilRadioOption($this->lng->txt("cont_scheduled_activation"), "scheduled"); + + $dt_prop = new ilDateTimeInputGUI($this->lng->txt("cont_start"), "start"); + $dt_prop->setRequired(true); + $dt_prop->setShowTime(true); + $rad_op3->addSubItem($dt_prop); + $dt_prop2 = new ilDateTimeInputGUI($this->lng->txt("cont_end"), "end"); + $dt_prop2->setRequired(true); + $dt_prop2->setShowTime(true); + $rad_op3->addSubItem($dt_prop2); + + // show activation information + $cb = new ilCheckboxInputGUI($this->lng->txt("cont_show_activation_info"), "show_activation_info"); + $cb->setInfo($this->lng->txt("cont_show_activation_info_info")); + $rad_op3->addSubItem($cb); + + + $rad->addOption($rad_op3); + + $this->form->addCommandButton("saveActivation", $this->lng->txt("save")); + + $this->form->addItem($rad); + } + + /** + * Get values for activation form + */ + public function getActivationFormValues() + { + $activation = "deactivated"; + if ($this->getPageObject()->getActive()) { + $activation = "activated"; + } + + $dt_prop = $this->form->getItemByPostVar("start"); + if ($this->getPageObject()->getActivationStart() != "") { + $activation = "scheduled"; + $dt_prop->setDate(new ilDateTime( + $this->getPageObject()->getActivationStart(), + IL_CAL_DATETIME + )); + } + $dt_prop = $this->form->getItemByPostVar("end"); + if ($this->getPageObject()->getActivationEnd() != "") { + $activation = "scheduled"; + $dt_prop->setDate(new ilDateTime( + $this->getPageObject()->getActivationEnd(), + IL_CAL_DATETIME + )); + } + + $this->form->getItemByPostVar("activation")->setValue($activation); + $this->form->getItemByPostVar("show_activation_info")->setChecked($this->getPageObject()->getShowActivationInfo()); + } + + /** + * Save Activation + */ + public function saveActivation() + { + $this->initActivationForm(); + + if ($this->form->checkInput()) { + $this->getPageObject()->setActive(true); + $this->getPageObject()->setActivationStart(null); + $this->getPageObject()->setActivationEnd(null); + $this->getPageObject()->setShowActivationInfo($_POST["show_activation_info"]); + if ($_POST["activation"] == "deactivated") { + $this->getPageObject()->setActive(false); + } + if ($_POST["activation"] == "scheduled") { + $this->getPageObject()->setActive(false); + $this->getPageObject()->setActivationStart( + $this->form->getItemByPostVar("start")->getDate()->get(IL_CAL_DATETIME) + ); + $this->getPageObject()->setActivationEnd( + $this->form->getItemByPostVar("end")->getDate()->get(IL_CAL_DATETIME) + ); + } + $this->getPageObject()->update(); + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "editActivation"); + } + $this->form->setValuesByPost(); + $this->tpl->setContent($this->form->getHTML()); + } + + /** + * Get html for public and/or private notes + * + * @param bool $a_content_object + * @param bool $a_enable_private_notes + * @param bool $a_enable_public_notes + * @param bool $a_enable_notes_deletion + * @return string + */ + public function getNotesHTML($a_content_object = null, $a_enable_private_notes = true, $a_enable_public_notes = false, $a_enable_notes_deletion = false, $a_callback = null) + { + include_once("Services/Notes/classes/class.ilNoteGUI.php"); + + // scorm 2004 page gui + if (!$a_content_object) { + $notes_gui = new ilNoteGUI( + $this->notes_parent_id, + (int) $this->obj->getId(), + "pg" + ); + + $a_enable_private_notes = true; + $a_enable_public_notes = true; + $a_enable_notes_deletion = false; + } + // wiki page gui, blog posting gui + else { + $notes_gui = new ilNoteGUI( + $a_content_object->getParentId(), + $a_content_object->getId(), + $a_content_object->getParentType() + ); + } + + if ($a_enable_private_notes) { + $notes_gui->enablePrivateNotes(); + } + if ($a_enable_public_notes) { + $notes_gui->enablePublicNotes(); + if ((bool) $a_enable_notes_deletion) { + $notes_gui->enablePublicNotesDeletion(true); + } + } + + if ($a_callback) { + $notes_gui->addObserver($a_callback); + } + + $next_class = $this->ctrl->getNextClass($this); + if ($next_class == "ilnotegui") { + $html = $this->ctrl->forwardCommand($notes_gui); + } else { + $html = $notes_gui->getNotesHTML(); + } + return $html; + } + + /** + * Process answer + */ + public function processAnswer() + { + include_once("./Services/COPage/classes/class.ilPageQuestionProcessor.php"); + ilPageQuestionProcessor::saveQuestionAnswer( + ilUtil::stripSlashes($_POST["type"]), + ilUtil::stripSlashes($_POST["id"]), + ilUtil::stripSlashes($_POST["answer"]) + ); + } + + + // + // Initially opened content (e.g. used in learning modules), that + // is presented in another than the main content area (e.g. a picture in + // the bottom left area) + // + + /** + * Initially opened content + * + * @param + * @return + */ + public function initialOpenedContent() + { + $this->tabs_gui->activateTab("edit"); + $form = $this->initOpenedContentForm(); + + $this->tpl->setContent($form->getHTML()); + } + + /** + * Init form for initially opened content + * + * @param + * @return + */ + public function initOpenedContentForm() + { + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + + // link input + include_once 'Services/Form/classes/class.ilLinkInputGUI.php'; + $ac = new ilLinkInputGUI($this->lng->txt('cont_resource'), 'opened_content'); + $ac->setAllowedLinkTypes(ilLinkInputGUI::INT); + $ac->setInternalLinkDefault("Media_Media", 0); + $ac->setInternalLinkFilterTypes(array("PageObject_FAQ", "GlossaryItem", "Media_Media", "Media_FAQ")); + $val = $this->obj->getInitialOpenedContent(); + if ($val["id"] != "" && $val["type"] != "") { + $ac->setValue($val["type"] . "|" . $val["id"] . "|" . $val["target"]); + } + + $form->addItem($ac); + + $form->addCommandButton("saveInitialOpenedContent", $this->lng->txt("save")); + $form->addCommandButton("edit", $this->lng->txt("cancel")); + $form->setTitle($this->lng->txt("cont_initial_attached_content")); + $form->setFormAction($this->ctrl->getFormAction($this)); + + return $form; + } + + /** + * Save initial opened content + * + * @param + * @return + */ + public function saveInitialOpenedContent() + { + $this->obj->saveInitialOpenedContent( + ilUtil::stripSlashes($_POST["opened_content_ajax_type"]), + ilUtil::stripSlashes($_POST["opened_content_ajax_id"]), + ilUtil::stripSlashes($_POST["opened_content_ajax_target"]) + ); + + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified")); + $this->ctrl->redirect($this, "edit"); + } + + //// + //// Multilinguality functions + //// + + + /** + * Switch to language + */ + public function switchToLanguage() + { + $l = ilUtil::stripSlashes($_GET["totransl"]); + $p = $this->getPageObject(); + if (!ilPageObject::_exists($p->getParentType(), $p->getId(), $l)) { + $this->confirmPageTranslationCreation(); + return; + } + $this->ctrl->setParameter($this, "transl", $_GET["totransl"]); + $this->ctrl->redirect($this, "edit"); + } + + /** + * Confirm page translation creation + */ + public function confirmPageTranslationCreation() + { + $l = ilUtil::stripSlashes($_GET["totransl"]); + $this->ctrl->setParameter($this, "totransl", $l); + $this->lng->loadLanguageModule("meta"); + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($this->ctrl->getFormAction($this)); + $cgui->setHeaderText($this->lng->txt("cont_page_translation_does_not_exist") . ": " . + $this->lng->txt("meta_l_" . $l)); + $cgui->setCancel($this->lng->txt("cancel"), "editMasterLanguage"); + $cgui->setConfirm($this->lng->txt("confirm"), "createPageTranslation"); + $this->tpl->setContent($cgui->getHTML()); + } + + /** + * Edit master language + */ + public function editMasterLanguage() + { + $this->ctrl->setParameter($this, "transl", ""); + $this->ctrl->redirect($this, "edit"); + } + + /** + * Create page translation + */ + public function createPageTranslation() + { + $l = ilUtil::stripSlashes($_GET["totransl"]); + + include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); + $p = ilPageObjectFactory::getInstance( + $this->getPageObject()->getParentType(), + $this->getPageObject()->getId(), + 0, + "-" + ); + $p->copyPageToTranslation($l); + $this->ctrl->setParameter($this, "transl", $l); + $this->ctrl->redirect($this, "edit"); + } + + /** + * Release page lock + */ + public function releasePageLock() + { + $this->getPageObject()->releasePageLock(); + ilUtil::sendSuccess($this->lng->txt("cont_page_lock_released"), true); + $this->ctrl->redirect($this, "preview"); + } + + protected function isPageContainerToBeRendered() + { + return ( + $this->getRenderPageContainer() || $this->getOutputMode() == IL_PAGE_PREVIEW + ); + } + + /** + * Get page perma link + * + * @param + * @return + */ + public function getPagePermaLink() + { + return ""; + } } -?> diff --git a/Services/COPage/classes/class.ilPageQuestionProcessor.php b/Services/COPage/classes/class.ilPageQuestionProcessor.php index ce0eac9a6e8bb419a76cfd9815a6fe270e5bd5d8..bce368f091a748d7eb4c91af558e1b9f32f8bd16 100644 --- a/Services/COPage/classes/class.ilPageQuestionProcessor.php +++ b/Services/COPage/classes/class.ilPageQuestionProcessor.php @@ -10,404 +10,392 @@ */ class ilPageQuestionProcessor { - /** - * constructor - * - * @param - * @return - */ - function __construct() - { - - } - - - /** - * Save question answer - * - * @param - * @return - */ - static function saveQuestionAnswer($a_type, $a_id, $a_answer) - { - global $DIC; - - $ilUser = $DIC->user(); - $ilLog = $DIC["ilLog"]; - $ilDB = $DIC->database(); -//$a_type = "assOrderingQuestion"; -//$a_id = 74; -//$a_answer = '{"tries":1,"wrong":2,"passed":false,"answer":[true,true,false,true,false],"interactionId":null,"choice":["1","2","5","4","3"]}'; - $ilLog->write($a_type); - $ilLog->write($a_id); - $ilLog->write($a_answer); - include_once("./Services/JSON/classes/class.ilJsonUtil.php"); - $answer = ilJsonUtil::decode($a_answer); - $tries = $answer->tries; - $passed = $answer->passed; - $choice = $answer->choice; - $points = self::calculatePoints($a_type, $a_id, $choice); - $ilLog->write("Points: ".$points); - - $set = $ilDB->query("SELECT * FROM page_qst_answer WHERE ". - " qst_id = ".$ilDB->quote($a_id, "integer")." AND ". - " user_id = ".$ilDB->quote($ilUser->getId(), "integer") - ); - - /* - if ($rec = $ilDB->fetchAssoc($set)) - { - $ilDB->manipulate("UPDATE page_qst_answer SET ". - " try = try + 1,". - " passed = ".$ilDB->quote($passed, "integer").",". - " points = ".$ilDB->quote($points, "float"). - " WHERE qst_id = ".$ilDB->quote($a_id, "integer"). - " AND user_id = ".$ilDB->quote($ilUser->getId(), "integer") - ); - } - else - { - $ilDB->manipulate("INSERT INTO page_qst_answer ". - "(qst_id, user_id, try, passed, points) VALUES (". - $ilDB->quote($a_id, "integer").",". - $ilDB->quote($ilUser->getId(), "integer").",". - $ilDB->quote(1, "integer").",". - $ilDB->quote($passed, "integer").",". - $ilDB->quote($points, "float"). - ")"); - } - */ - - // #15146 - if (!$ilDB->fetchAssoc($set)) - { - $ilDB->replace("page_qst_answer", - array( - "qst_id" => array("integer", $a_id), - "user_id" => array("integer", $ilUser->getId()) - ), - array( - "try" => array("integer", 1), - "passed" => array("integer", $passed), - "points" => array("float", $points) - ) - ); - } - else - { - $ilDB->manipulate("UPDATE page_qst_answer SET ". - " try = try + 1,". - " passed = ".$ilDB->quote($passed, "integer").",". - " points = ".$ilDB->quote($points, "float"). - " WHERE qst_id = ".$ilDB->quote($a_id, "integer"). - " AND user_id = ".$ilDB->quote($ilUser->getId(), "integer") - ); - } - } - - /** - * Get statistics for question - * - * @param int question id - * @return array - */ - static function getQuestionStatistics($a_q_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT count(user_id) usr_cnt FROM page_qst_answer WHERE ". - " qst_id = ".$ilDB->quote($a_q_id, "integer") - ); - $rec = $ilDB->fetchAssoc($set); - $all = $rec["usr_cnt"]; - - $first = false; - $second = false; - $third_or_more = false; - - if ($all > 0) - { - $set = $ilDB->query("SELECT count(user_id) usr_cnt FROM page_qst_answer WHERE ". - " qst_id = ".$ilDB->quote($a_q_id, "integer")." AND ". - " passed = ".$ilDB->quote(1, "integer")." AND ". - " try = ".$ilDB->quote(1, "integer") - ); - $rec = $ilDB->fetchAssoc($set); - $first = $rec["usr_cnt"]; - - $set = $ilDB->query("SELECT count(user_id) usr_cnt FROM page_qst_answer WHERE ". - " qst_id = ".$ilDB->quote($a_q_id, "integer")." AND ". - " passed = ".$ilDB->quote(1, "integer")." AND ". - " try = ".$ilDB->quote(2, "integer") - ); - $rec = $ilDB->fetchAssoc($set); - $second = $rec["usr_cnt"]; - - $set = $ilDB->query($q = "SELECT count(user_id) usr_cnt FROM page_qst_answer WHERE ". - " qst_id = ".$ilDB->quote($a_q_id, "integer")." AND ". - " passed = ".$ilDB->quote(1, "integer")." AND ". - " try >= ".$ilDB->quote(3, "integer") - ); - $rec = $ilDB->fetchAssoc($set); - $third_or_more = $rec["usr_cnt"]; - } - - return array("all" => $all, "first" => $first, "second" => $second, "third_or_more" => $third_or_more); - } - - /** - * Calculate points - * - * This function calculates the points for a given answer. - * Better would be to re-use from T&A here in the future. - * When this code has been written this has not been possible yet. - * - * @param - * @return - */ - static function calculatePoints($a_type, $a_id, $a_choice) - { - global $DIC; - - $ilLog = $DIC["ilLog"]; - - switch ($a_type) - { - case "assSingleChoice": - include_once("./Modules/TestQuestionPool/classes/class.assSingleChoice.php"); - $q = new assSingleChoice(); - $q->loadFromDb($a_id); - $points = 0; - foreach ($q->getAnswers() as $key => $answer) - { - if (isset($a_choice[0]) && $key == $a_choice[0]) - { - $points += $answer->getPoints(); - } - } - break; - - case "assMultipleChoice": - include_once("./Modules/TestQuestionPool/classes/class.assMultipleChoice.php"); - $q = new assMultipleChoice(); - $q->loadFromDb($a_id); - $points = 0; - foreach ($q->getAnswers() as $key => $answer) - { - if (is_array($a_choice) && in_array($key, $a_choice)) - { - $points += $answer->getPoints(); - } - else - { - $points += $answer->getPointsUnchecked(); - } - } - break; - - case "assClozeTest": - include_once("./Modules/TestQuestionPool/classes/class.assClozeTest.php"); - $q = new assClozeTest(); - $q->loadFromDb($a_id); - $points = 0; - foreach ($q->getGaps() as $id => $gap) - { - $choice = $a_choice[$id]; - switch ($gap->getType()) - { - case CLOZE_TEXT: - $gappoints = 0; - for ($order = 0; $order < $gap->getItemCount(); $order++) - { - $answer = $gap->getItem($order); - $gotpoints = $q->getTextgapPoints($answer->getAnswertext(), - $choice, $answer->getPoints()); - if ($gotpoints > $gappoints) $gappoints = $gotpoints; - } - $points += $gappoints; + /** + * constructor + * + * @param + * @return + */ + public function __construct() + { + } + + + /** + * Save question answer + * + * @param + * @return + */ + public static function saveQuestionAnswer($a_type, $a_id, $a_answer) + { + global $DIC; + + $ilUser = $DIC->user(); + $ilLog = $DIC["ilLog"]; + $ilDB = $DIC->database(); + //$a_type = "assOrderingQuestion"; + //$a_id = 74; + //$a_answer = '{"tries":1,"wrong":2,"passed":false,"answer":[true,true,false,true,false],"interactionId":null,"choice":["1","2","5","4","3"]}'; + $ilLog->write($a_type); + $ilLog->write($a_id); + $ilLog->write($a_answer); + include_once("./Services/JSON/classes/class.ilJsonUtil.php"); + $answer = ilJsonUtil::decode($a_answer); + $tries = $answer->tries; + $passed = $answer->passed; + $choice = $answer->choice; + $points = self::calculatePoints($a_type, $a_id, $choice); + $ilLog->write("Points: " . $points); + + $set = $ilDB->query( + "SELECT * FROM page_qst_answer WHERE " . + " qst_id = " . $ilDB->quote($a_id, "integer") . " AND " . + " user_id = " . $ilDB->quote($ilUser->getId(), "integer") + ); + + /* + if ($rec = $ilDB->fetchAssoc($set)) + { + $ilDB->manipulate("UPDATE page_qst_answer SET ". + " try = try + 1,". + " passed = ".$ilDB->quote($passed, "integer").",". + " points = ".$ilDB->quote($points, "float"). + " WHERE qst_id = ".$ilDB->quote($a_id, "integer"). + " AND user_id = ".$ilDB->quote($ilUser->getId(), "integer") + ); + } + else + { + $ilDB->manipulate("INSERT INTO page_qst_answer ". + "(qst_id, user_id, try, passed, points) VALUES (". + $ilDB->quote($a_id, "integer").",". + $ilDB->quote($ilUser->getId(), "integer").",". + $ilDB->quote(1, "integer").",". + $ilDB->quote($passed, "integer").",". + $ilDB->quote($points, "float"). + ")"); + } + */ + + // #15146 + if (!$ilDB->fetchAssoc($set)) { + $ilDB->replace( + "page_qst_answer", + array( + "qst_id" => array("integer", $a_id), + "user_id" => array("integer", $ilUser->getId()) + ), + array( + "try" => array("integer", 1), + "passed" => array("integer", $passed), + "points" => array("float", $points) + ) + ); + } else { + $ilDB->manipulate( + "UPDATE page_qst_answer SET " . + " try = try + 1," . + " passed = " . $ilDB->quote($passed, "integer") . "," . + " points = " . $ilDB->quote($points, "float") . + " WHERE qst_id = " . $ilDB->quote($a_id, "integer") . + " AND user_id = " . $ilDB->quote($ilUser->getId(), "integer") + ); + } + } + + /** + * Get statistics for question + * + * @param int question id + * @return array + */ + public static function getQuestionStatistics($a_q_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT count(user_id) usr_cnt FROM page_qst_answer WHERE " . + " qst_id = " . $ilDB->quote($a_q_id, "integer") + ); + $rec = $ilDB->fetchAssoc($set); + $all = $rec["usr_cnt"]; + + $first = false; + $second = false; + $third_or_more = false; + + if ($all > 0) { + $set = $ilDB->query( + "SELECT count(user_id) usr_cnt FROM page_qst_answer WHERE " . + " qst_id = " . $ilDB->quote($a_q_id, "integer") . " AND " . + " passed = " . $ilDB->quote(1, "integer") . " AND " . + " try = " . $ilDB->quote(1, "integer") + ); + $rec = $ilDB->fetchAssoc($set); + $first = $rec["usr_cnt"]; + + $set = $ilDB->query( + "SELECT count(user_id) usr_cnt FROM page_qst_answer WHERE " . + " qst_id = " . $ilDB->quote($a_q_id, "integer") . " AND " . + " passed = " . $ilDB->quote(1, "integer") . " AND " . + " try = " . $ilDB->quote(2, "integer") + ); + $rec = $ilDB->fetchAssoc($set); + $second = $rec["usr_cnt"]; + + $set = $ilDB->query( + $q = "SELECT count(user_id) usr_cnt FROM page_qst_answer WHERE " . + " qst_id = " . $ilDB->quote($a_q_id, "integer") . " AND " . + " passed = " . $ilDB->quote(1, "integer") . " AND " . + " try >= " . $ilDB->quote(3, "integer") + ); + $rec = $ilDB->fetchAssoc($set); + $third_or_more = $rec["usr_cnt"]; + } + + return array("all" => $all, "first" => $first, "second" => $second, "third_or_more" => $third_or_more); + } + + /** + * Calculate points + * + * This function calculates the points for a given answer. + * Better would be to re-use from T&A here in the future. + * When this code has been written this has not been possible yet. + * + * @param + * @return + */ + public static function calculatePoints($a_type, $a_id, $a_choice) + { + global $DIC; + + $ilLog = $DIC["ilLog"]; + + switch ($a_type) { + case "assSingleChoice": + include_once("./Modules/TestQuestionPool/classes/class.assSingleChoice.php"); + $q = new assSingleChoice(); + $q->loadFromDb($a_id); + $points = 0; + foreach ($q->getAnswers() as $key => $answer) { + if (isset($a_choice[0]) && $key == $a_choice[0]) { + $points += $answer->getPoints(); + } + } + break; + + case "assMultipleChoice": + include_once("./Modules/TestQuestionPool/classes/class.assMultipleChoice.php"); + $q = new assMultipleChoice(); + $q->loadFromDb($a_id); + $points = 0; + foreach ($q->getAnswers() as $key => $answer) { + if (is_array($a_choice) && in_array($key, $a_choice)) { + $points += $answer->getPoints(); + } else { + $points += $answer->getPointsUnchecked(); + } + } + break; + + case "assClozeTest": + include_once("./Modules/TestQuestionPool/classes/class.assClozeTest.php"); + $q = new assClozeTest(); + $q->loadFromDb($a_id); + $points = 0; + foreach ($q->getGaps() as $id => $gap) { + $choice = $a_choice[$id]; + switch ($gap->getType()) { + case CLOZE_TEXT: + $gappoints = 0; + for ($order = 0; $order < $gap->getItemCount(); $order++) { + $answer = $gap->getItem($order); + $gotpoints = $q->getTextgapPoints( + $answer->getAnswertext(), + $choice, + $answer->getPoints() + ); + if ($gotpoints > $gappoints) { + $gappoints = $gotpoints; + } + } + $points += $gappoints; //$ilLog->write("ct: ".$gappoints); - break; - - case CLOZE_NUMERIC: - $gappoints = 0; - for ($order = 0; $order < $gap->getItemCount(); $order++) - { - $answer = $gap->getItem($order); - $gotpoints = $q->getNumericgapPoints($answer->getAnswertext(), - $choice, $answer->getPoints(), - $answer->getLowerBound(), $answer->getUpperBound()); - if ($gotpoints > $gappoints) $gappoints = $gotpoints; - } - $points += $gappoints; + break; + + case CLOZE_NUMERIC: + $gappoints = 0; + for ($order = 0; $order < $gap->getItemCount(); $order++) { + $answer = $gap->getItem($order); + $gotpoints = $q->getNumericgapPoints( + $answer->getAnswertext(), + $choice, + $answer->getPoints(), + $answer->getLowerBound(), + $answer->getUpperBound() + ); + if ($gotpoints > $gappoints) { + $gappoints = $gotpoints; + } + } + $points += $gappoints; //$ilLog->write("cn: ".$gappoints); - break; - - case CLOZE_SELECT: - for ($order = 0; $order < $gap->getItemCount(); $order++) - { - $answer = $gap->getItem($order); - if ($choice == $answer->getOrder()) - { - $answerpoints = $answer->getPoints(); - $points += $answerpoints; -//$ilLog->write("cs: ".$answerpoints); - } - } - break; - } - } - break; - - case "assMatchingQuestion": - include_once("./Modules/TestQuestionPool/classes/class.assMatchingQuestion.php"); - $q = new assMatchingQuestion(); - $q->loadFromDb($a_id); - $points = 0; - for ($i = 0; $i < $q->getMatchingPairCount(); $i++) - { - $pair = $q->getMatchingPair($i); - if (is_array($a_choice) && in_array($pair->definition->identifier."-".$pair->term->identifier, $a_choice)) - { - $points += $pair->points; - } - } - break; - - case "assOrderingQuestion": - - // TODO-LSD: change calculation strategy according to lsd cleanup changes - - include_once("./Modules/TestQuestionPool/classes/class.assOrderingQuestion.php"); - $q = new assOrderingQuestion(); - $q->loadFromDb($a_id); - $points = 0; - $cnt = 1; - $right = true; - foreach ( $q->getOrderElements() as $answer) - { - if ($a_choice[$cnt - 1] != $cnt) - { - $right = false; - } - $cnt++; - } - if ($right) - { - $points = $q->getPoints(); - } - break; - - case "assImagemapQuestion": - include_once("./Modules/TestQuestionPool/classes/class.assImagemapQuestion.php"); - $q = new assImagemapQuestion(); - $q->loadFromDb($a_id); - $points = 0; - - foreach ($q->getAnswers() as $key => $answer) - { - if (is_array($a_choice) && in_array($key, $a_choice)) - { - $points += $answer->getPoints(); - } - } - break; - - } - - if ($points < 0) - { - $points = 0; - } - - return (int) $points; - } - - /** - * Get statistics for question - * - * @param int question id - * @return array - */ - static function getAnswerStatus($a_q_id, $a_user_id = 0) - { - global $DIC; - - $ilDB = $DIC->database(); - - $qst = (is_array($a_q_id)) - ? $ilDB->in("qst_id", $a_q_id, false, "integer") - : " qst_id = ".$ilDB->quote($a_q_id, "integer"); - - $and = ($a_user_id > 0) - ? " AND user_id = ".$ilDB->quote($a_user_id, "integer") - : ""; - - $set = $ilDB->query("SELECT * FROM page_qst_answer WHERE ". - $qst. - $and - ); - - if (is_array($a_q_id) || $a_user_id == 0) - { - $recs = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $key = ($a_user_id == 0) - ? $rec["qst_id"].":".$rec["user_id"] - : $rec["qst_id"]; - $recs[$key] = $rec; - } - return $recs; - } - else - { - return $ilDB->fetchAssoc($set); - } - } - - /** - * Reset tries - * - * @param int $a_q_id question id - * @param int $a_user_id user id - */ - static function resetTries($a_q_id, $a_user_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $ilDB->manipulate($q = "UPDATE page_qst_answer SET ". - " try = ".$ilDB->quote(0, "integer").",". - " passed = ".$ilDB->quote(0, "integer").",". - " points = ".$ilDB->quote(0, "integer").",". - " unlocked = ".$ilDB->quote(0, "integer"). - " WHERE qst_id = ".$ilDB->quote($a_q_id, "integer"). - " AND user_id = ".$ilDB->quote($a_user_id, "integer") - ); - } - - /** - * Reset tries - * - * @param int $a_q_id question id - * @param int $a_user_id user id - */ - static function unlock($a_q_id, $a_user_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $ilDB->manipulate($q = "UPDATE page_qst_answer SET ". - " unlocked = ".$ilDB->quote(1, "integer"). - " WHERE qst_id = ".$ilDB->quote($a_q_id, "integer"). - " AND user_id = ".$ilDB->quote($a_user_id, "integer") - ); - } - - + break; + + case CLOZE_SELECT: + for ($order = 0; $order < $gap->getItemCount(); $order++) { + $answer = $gap->getItem($order); + if ($choice == $answer->getOrder()) { + $answerpoints = $answer->getPoints(); + $points += $answerpoints; + //$ilLog->write("cs: ".$answerpoints); + } + } + break; + } + } + break; + + case "assMatchingQuestion": + include_once("./Modules/TestQuestionPool/classes/class.assMatchingQuestion.php"); + $q = new assMatchingQuestion(); + $q->loadFromDb($a_id); + $points = 0; + for ($i = 0; $i < $q->getMatchingPairCount(); $i++) { + $pair = $q->getMatchingPair($i); + if (is_array($a_choice) && in_array($pair->definition->identifier . "-" . $pair->term->identifier, $a_choice)) { + $points += $pair->points; + } + } + break; + + case "assOrderingQuestion": + + // TODO-LSD: change calculation strategy according to lsd cleanup changes + + include_once("./Modules/TestQuestionPool/classes/class.assOrderingQuestion.php"); + $q = new assOrderingQuestion(); + $q->loadFromDb($a_id); + $points = 0; + $cnt = 1; + $right = true; + foreach ($q->getOrderElements() as $answer) { + if ($a_choice[$cnt - 1] != $cnt) { + $right = false; + } + $cnt++; + } + if ($right) { + $points = $q->getPoints(); + } + break; + + case "assImagemapQuestion": + include_once("./Modules/TestQuestionPool/classes/class.assImagemapQuestion.php"); + $q = new assImagemapQuestion(); + $q->loadFromDb($a_id); + $points = 0; + + foreach ($q->getAnswers() as $key => $answer) { + if (is_array($a_choice) && in_array($key, $a_choice)) { + $points += $answer->getPoints(); + } + } + break; + + } + + if ($points < 0) { + $points = 0; + } + + return (int) $points; + } + + /** + * Get statistics for question + * + * @param int question id + * @return array + */ + public static function getAnswerStatus($a_q_id, $a_user_id = 0) + { + global $DIC; + + $ilDB = $DIC->database(); + + $qst = (is_array($a_q_id)) + ? $ilDB->in("qst_id", $a_q_id, false, "integer") + : " qst_id = " . $ilDB->quote($a_q_id, "integer"); + + $and = ($a_user_id > 0) + ? " AND user_id = " . $ilDB->quote($a_user_id, "integer") + : ""; + + $set = $ilDB->query( + "SELECT * FROM page_qst_answer WHERE " . + $qst . + $and + ); + + if (is_array($a_q_id) || $a_user_id == 0) { + $recs = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $key = ($a_user_id == 0) + ? $rec["qst_id"] . ":" . $rec["user_id"] + : $rec["qst_id"]; + $recs[$key] = $rec; + } + return $recs; + } else { + return $ilDB->fetchAssoc($set); + } + } + + /** + * Reset tries + * + * @param int $a_q_id question id + * @param int $a_user_id user id + */ + public static function resetTries($a_q_id, $a_user_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $ilDB->manipulate( + $q = "UPDATE page_qst_answer SET " . + " try = " . $ilDB->quote(0, "integer") . "," . + " passed = " . $ilDB->quote(0, "integer") . "," . + " points = " . $ilDB->quote(0, "integer") . "," . + " unlocked = " . $ilDB->quote(0, "integer") . + " WHERE qst_id = " . $ilDB->quote($a_q_id, "integer") . + " AND user_id = " . $ilDB->quote($a_user_id, "integer") + ); + } + + /** + * Reset tries + * + * @param int $a_q_id question id + * @param int $a_user_id user id + */ + public static function unlock($a_q_id, $a_user_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $ilDB->manipulate( + $q = "UPDATE page_qst_answer SET " . + " unlocked = " . $ilDB->quote(1, "integer") . + " WHERE qst_id = " . $ilDB->quote($a_q_id, "integer") . + " AND user_id = " . $ilDB->quote($a_user_id, "integer") + ); + } } -?> diff --git a/Services/COPage/classes/class.ilPageUtil.php b/Services/COPage/classes/class.ilPageUtil.php index 988c04c8b4a764810384e34dfe449b5ca3ced03c..0c12c04813a588dbde92b72bfa35ae10750781df 100644 --- a/Services/COPage/classes/class.ilPageUtil.php +++ b/Services/COPage/classes/class.ilPageUtil.php @@ -6,37 +6,33 @@ */ class ilPageUtil { - /** - * checks whether page exists and is not empty (may return true on some empty pages) - * - * @param string $a_parent_type parent type - * @param int $a_id page id - */ - static function _existsAndNotEmpty($a_parent_type, $a_id, $a_lang = "-") - { - global $DIC; + /** + * checks whether page exists and is not empty (may return true on some empty pages) + * + * @param string $a_parent_type parent type + * @param int $a_id page id + */ + public static function _existsAndNotEmpty($a_parent_type, $a_id, $a_lang = "-") + { + global $DIC; - $ilDB = $DIC->database(); - - // language must be set at least to "-" - if ($a_lang == "") - { - $a_lang = "-"; - } - $and_lang = " AND lang = ".$ilDB->quote($a_lang, "text"); - - $query = "SELECT page_id, is_empty FROM page_object WHERE page_id = ".$ilDB->quote($a_id, "integer")." ". - "AND parent_type= ".$ilDB->quote($a_parent_type, "text").$and_lang; + $ilDB = $DIC->database(); + + // language must be set at least to "-" + if ($a_lang == "") { + $a_lang = "-"; + } + $and_lang = " AND lang = " . $ilDB->quote($a_lang, "text"); + + $query = "SELECT page_id, is_empty FROM page_object WHERE page_id = " . $ilDB->quote($a_id, "integer") . " " . + "AND parent_type= " . $ilDB->quote($a_parent_type, "text") . $and_lang; - $set = $ilDB->query($query); - if ($row = $ilDB->fetchAssoc($set)) - { - if ($row["is_empty"] != 1) - { - return true; - } - } - return false; - } + $set = $ilDB->query($query); + if ($row = $ilDB->fetchAssoc($set)) { + if ($row["is_empty"] != 1) { + return true; + } + } + return false; + } } -?> \ No newline at end of file diff --git a/Services/COPage/classes/class.ilPoolSelectorGUI.php b/Services/COPage/classes/class.ilPoolSelectorGUI.php index b5013cb0560a026be2210377e3968f2271bc2fdd..82df44f2ef24ecd02cec5f06b939f87dd1b4cdfc 100755 --- a/Services/COPage/classes/class.ilPoolSelectorGUI.php +++ b/Services/COPage/classes/class.ilPoolSelectorGUI.php @@ -14,77 +14,83 @@ include_once "./Services/Repository/classes/class.ilRepositorySelectorExplorerGU class ilPoolSelectorGUI extends ilRepositorySelectorExplorerGUI { - protected $clickable_types = array(); - protected $selection_subcmd = ""; + protected $clickable_types = array(); + protected $selection_subcmd = ""; - /** - * Constructor - * - * @param object $a_parent_obj - * @param string $a_parent_cmd - * @param object $a_selection_gui - * @param string $a_selection_cmd - * @param string $a_selection_par - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_selection_gui = null, $a_selection_cmd = "insert", - $a_selection_subcmd = "selectPool", $a_selection_par = "pool_ref_id") - { - global $DIC; + /** + * Constructor + * + * @param object $a_parent_obj + * @param string $a_parent_cmd + * @param object $a_selection_gui + * @param string $a_selection_cmd + * @param string $a_selection_par + */ + public function __construct( + $a_parent_obj, + $a_parent_cmd, + $a_selection_gui = null, + $a_selection_cmd = "insert", + $a_selection_subcmd = "selectPool", + $a_selection_par = "pool_ref_id" + ) { + global $DIC; - $this->ctrl = $DIC->ctrl(); - if($a_selection_gui == null) - { - $a_selection_gui = $a_parent_obj; - } + $this->ctrl = $DIC->ctrl(); + if ($a_selection_gui == null) { + $a_selection_gui = $a_parent_obj; + } - $this->selection_subcmd = $a_selection_subcmd; - parent::__construct($a_parent_obj, $a_parent_cmd, $a_selection_gui, $a_selection_cmd, - $a_selection_par); + $this->selection_subcmd = $a_selection_subcmd; + parent::__construct( + $a_parent_obj, + $a_parent_cmd, + $a_selection_gui, + $a_selection_cmd, + $a_selection_par + ); - $this->setAjax(true); - } + $this->setAjax(true); + } - /** - * Get href for node - * - * @param mixed $a_node node object/array - * @return string href attribute - */ - function getNodeHref($a_node) - { - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameterByClass($this->selection_gui, "subCmd", $this->selection_subcmd); - $link = parent::getNodeHref($a_node); - $ilCtrl->setParameterByClass($this->selection_gui, "subCmd", ""); - return $link; - } + /** + * Get href for node + * + * @param mixed $a_node node object/array + * @return string href attribute + */ + public function getNodeHref($a_node) + { + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameterByClass($this->selection_gui, "subCmd", $this->selection_subcmd); + $link = parent::getNodeHref($a_node); + $ilCtrl->setParameterByClass($this->selection_gui, "subCmd", ""); + return $link; + } - /** - * Is node visible - * - * @param array $a_node node data - * @return bool visible true/false - */ - function isNodeVisible($a_node) - { - if(parent::isNodeVisible($a_node)) - { - //hide empty container - if(count($this->getChildsOfNode($a_node["child"]))>0 || $this->isNodeClickable($a_node)) - { - // #16523 - if($a_node["type"] == "qpl") - { - include_once "Modules/TestQuestionPool/classes/class.ilObjQuestionPool.php"; - return ilObjQuestionPool::_lookupOnline($a_node["obj_id"]); - } + /** + * Is node visible + * + * @param array $a_node node data + * @return bool visible true/false + */ + public function isNodeVisible($a_node) + { + if (parent::isNodeVisible($a_node)) { + //hide empty container + if (count($this->getChildsOfNode($a_node["child"]))>0 || $this->isNodeClickable($a_node)) { + // #16523 + if ($a_node["type"] == "qpl") { + include_once "Modules/TestQuestionPool/classes/class.ilObjQuestionPool.php"; + return ilObjQuestionPool::_lookupOnline($a_node["obj_id"]); + } - return true; - } - } - - return false; - } -} \ No newline at end of file + return true; + } + } + + return false; + } +} diff --git a/Services/COPage/exceptions/class.ilCOPageAlreadyExists.php b/Services/COPage/exceptions/class.ilCOPageAlreadyExists.php index 9e1c2912a745b5e88740af0cd837c2051b566843..f0333c0f78bc2dc95975675caa397aef60fdddb0 100644 --- a/Services/COPage/exceptions/class.ilCOPageAlreadyExists.php +++ b/Services/COPage/exceptions/class.ilCOPageAlreadyExists.php @@ -1,27 +1,26 @@ - * @version $Id$ - * + * @version $Id$ + * */ class ilCOPageAlreadyExists extends ilException { - /** - * Constructor - * - * A message is not optional as in build in class Exception - * - * @param string $a_message message - */ - public function __construct($a_message) - { - parent::__construct($a_message); - } + /** + * Constructor + * + * A message is not optional as in build in class Exception + * + * @param string $a_message message + */ + public function __construct($a_message) + { + parent::__construct($a_message); + } } -?> diff --git a/Services/COPage/exceptions/class.ilCOPageException.php b/Services/COPage/exceptions/class.ilCOPageException.php index dea1c2d03f43f16b7b97ac2e60f8906d805df8e0..124b6d1621c43c36b1ef8b491dff7b710b72b2df 100644 --- a/Services/COPage/exceptions/class.ilCOPageException.php +++ b/Services/COPage/exceptions/class.ilCOPageException.php @@ -1,27 +1,26 @@ - * @version $Id$ - * + * @version $Id$ + * */ class ilCOPageException extends ilException { - /** - * Constructor - * - * A message is not optional as in build in class Exception - * - * @param string $a_message message - */ - public function __construct($a_message) - { - parent::__construct($a_message); - } + /** + * Constructor + * + * A message is not optional as in build in class Exception + * + * @param string $a_message message + */ + public function __construct($a_message) + { + parent::__construct($a_message); + } } -?> diff --git a/Services/COPage/exceptions/class.ilCOPageNotFoundException.php b/Services/COPage/exceptions/class.ilCOPageNotFoundException.php index cce729a127b0495c4ede54d46e60f91a37a29c37..02a337d7020dbde94ab98650dd3a790c6d588605 100644 --- a/Services/COPage/exceptions/class.ilCOPageNotFoundException.php +++ b/Services/COPage/exceptions/class.ilCOPageNotFoundException.php @@ -1,27 +1,26 @@ - * @version $Id$ - * + * @version $Id$ + * */ class ilCOPageNotFoundException extends ilException { - /** - * Constructor - * - * A message is not optional as in build in class Exception - * - * @param string $a_message message - */ - public function __construct($a_message) - { - parent::__construct($a_message); - } + /** + * Constructor + * + * A message is not optional as in build in class Exception + * + * @param string $a_message message + */ + public function __construct($a_message) + { + parent::__construct($a_message); + } } -?> diff --git a/Services/COPage/exceptions/class.ilCOPageUnknownPCTypeException.php b/Services/COPage/exceptions/class.ilCOPageUnknownPCTypeException.php index 54387a64f3d4b6822747f26bf9b96932aefd9824..afdc589b02bc30a85dd9fa65200f1995eb7d80b5 100644 --- a/Services/COPage/exceptions/class.ilCOPageUnknownPCTypeException.php +++ b/Services/COPage/exceptions/class.ilCOPageUnknownPCTypeException.php @@ -1,27 +1,26 @@ - * @version $Id$ - * + * @version $Id$ + * */ class ilCOPageUnknownPCTypeException extends ilException { - /** - * Constructor - * - * A message is not optional as in build in class Exception - * - * @param string $a_message message - */ - public function __construct($a_message) - { - parent::__construct($a_message); - } + /** + * Constructor + * + * A message is not optional as in build in class Exception + * + * @param string $a_message message + */ + public function __construct($a_message) + { + parent::__construct($a_message); + } } -?> diff --git a/Services/COPage/interfaces/interface.ilCOPageCollectorInterface.php b/Services/COPage/interfaces/interface.ilCOPageCollectorInterface.php index c39e3f2626f925842cf24619075b8157579ced41..ca1f93a4a91dd7b397afefdfc9b32f29c62b73e4 100644 --- a/Services/COPage/interfaces/interface.ilCOPageCollectorInterface.php +++ b/Services/COPage/interfaces/interface.ilCOPageCollectorInterface.php @@ -10,11 +10,11 @@ */ interface ilCOPageCollectorInterface { - /** - * Get all page IDs of an repository object - * - * @param int $obj_id object id of repository object - * @return array[] inner array keys: "parent_type", "id", "lang" - */ - public function getAllPageIds($obj_id); -} \ No newline at end of file + /** + * Get all page IDs of an repository object + * + * @param int $obj_id object id of repository object + * @return array[] inner array keys: "parent_type", "id", "lang" + */ + public function getAllPageIds($obj_id); +} diff --git a/Services/COPage/mediawikidiff/class.WordLevelDiff.php b/Services/COPage/mediawikidiff/class.WordLevelDiff.php index 53b5e444a15e560fad0dbb0e47654b9372ba4c47..516c976fdd2b4f8311f248814d5f199710aafb2a 100644 --- a/Services/COPage/mediawikidiff/class.WordLevelDiff.php +++ b/Services/COPage/mediawikidiff/class.WordLevelDiff.php @@ -14,74 +14,82 @@ * @public * @addtogroup DifferenceEngine */ -class DifferenceEngine { - /**#@+ - * @private - */ - var $mOldid, $mNewid, $mTitle; - var $mOldtitle, $mNewtitle, $mPagetitle; - var $mOldtext, $mNewtext; - var $mOldPage, $mNewPage; - var $mRcidMarkPatrolled; - var $mOldRev, $mNewRev; - var $mRevisionsLoaded = false; // Have the revisions been loaded - var $mTextLoaded = 0; // How many text blobs have been loaded, 0, 1 or 2? - /**#@-*/ - - /** - * Constructor - * @param $titleObj Title object that the diff is associated with - * @param $old Integer: old ID we want to show and diff with. - * @param $new String: either 'prev' or 'next'. - * @param $rcid Integer: ??? FIXME (default 0) - */ - function __construct( $titleObj = null, $old = 0, $new = 0, $rcid = 0 ) { - $this->mTitle = $titleObj; - wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n"); - - if ( 'prev' === $new ) { - # Show diff between revision $old and the previous one. - # Get previous one from DB. - # - $this->mNewid = intval($old); - - $this->mOldid = $this->mTitle->getPreviousRevisionID( $this->mNewid ); - - } elseif ( 'next' === $new ) { - # Show diff between revision $old and the previous one. - # Get previous one from DB. - # - $this->mOldid = intval($old); - $this->mNewid = $this->mTitle->getNextRevisionID( $this->mOldid ); - if ( false === $this->mNewid ) { - # if no result, NewId points to the newest old revision. The only newer - # revision is cur, which is "0". - $this->mNewid = 0; - } - - } else { - $this->mOldid = intval($old); - $this->mNewid = intval($new); - } - $this->mRcidMarkPatrolled = intval($rcid); # force it to be an integer - } - - function showDiffPage( $diffOnly = false ) { - global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol; - $fname = 'DifferenceEngine::showDiffPage'; - //wfProfileIn( $fname ); - - # If external diffs are enabled both globally and for the user, - # we'll use the application/x-external-editor interface to call - # an external diff tool like kompare, kdiff3, etc. - if($wgUseExternalEditor && $wgUser->getOption('externaldiff')) { - global $wgInputEncoding,$wgServer,$wgScript,$wgLang; - $wgOut->disable(); - header ( "Content-type: application/x-external-editor; charset=".$wgInputEncoding ); - $url1=$this->mTitle->getFullURL("action=raw&oldid=".$this->mOldid); - $url2=$this->mTitle->getFullURL("action=raw&oldid=".$this->mNewid); - $special=$wgLang->getNsText(NS_SPECIAL); - $control=<<mTitle = $titleObj; + wfDebug("DifferenceEngine old '$old' new '$new' rcid '$rcid'\n"); + + if ('prev' === $new) { + # Show diff between revision $old and the previous one. + # Get previous one from DB. + # + $this->mNewid = intval($old); + + $this->mOldid = $this->mTitle->getPreviousRevisionID($this->mNewid); + } elseif ('next' === $new) { + # Show diff between revision $old and the previous one. + # Get previous one from DB. + # + $this->mOldid = intval($old); + $this->mNewid = $this->mTitle->getNextRevisionID($this->mOldid); + if (false === $this->mNewid) { + # if no result, NewId points to the newest old revision. The only newer + # revision is cur, which is "0". + $this->mNewid = 0; + } + } else { + $this->mOldid = intval($old); + $this->mNewid = intval($new); + } + $this->mRcidMarkPatrolled = intval($rcid); # force it to be an integer + } + + public function showDiffPage($diffOnly = false) + { + global $wgUser, $wgOut, $wgUseExternalEditor, $wgUseRCPatrol; + $fname = 'DifferenceEngine::showDiffPage'; + //wfProfileIn( $fname ); + + # If external diffs are enabled both globally and for the user, + # we'll use the application/x-external-editor interface to call + # an external diff tool like kompare, kdiff3, etc. + if ($wgUseExternalEditor && $wgUser->getOption('externaldiff')) { + global $wgInputEncoding,$wgServer,$wgScript,$wgLang; + $wgOut->disable(); + header("Content-type: application/x-external-editor; charset=" . $wgInputEncoding); + $url1=$this->mTitle->getFullURL("action=raw&oldid=" . $this->mOldid); + $url2=$this->mTitle->getFullURL("action=raw&oldid=" . $this->mNewid); + $special=$wgLang->getNsText(NS_SPECIAL); + $control=<<setArticleFlag( false ); - if ( ! $this->loadRevisionData() ) { - $t = $this->mTitle->getPrefixedText() . " (Diff: {$this->mOldid}, {$this->mNewid})"; - $mtext = wfMsg( 'missingarticle', "$t" ); - $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) ); - $wgOut->addWikitext( $mtext ); - //wfProfileOut( $fname ); - return; - } - - wfRunHooks( 'DiffViewHeader', array( $this, $this->mOldRev, $this->mNewRev ) ); - - if ( $this->mNewRev->isCurrent() ) { - $wgOut->setArticleFlag( true ); - } - - # mOldid is false if the difference engine is called with a "vague" query for - # a diff between a version V and its previous version V' AND the version V - # is the first version of that article. In that case, V' does not exist. - if ( $this->mOldid === false ) { - $this->showFirstRevision(); - $this->renderNewRevision(); // should we respect $diffOnly here or not? - //wfProfileOut( $fname ); - return; - } - - $wgOut->suppressQuickbar(); - - $oldTitle = $this->mOldPage->getPrefixedText(); - $newTitle = $this->mNewPage->getPrefixedText(); - if( $oldTitle == $newTitle ) { - $wgOut->setPageTitle( $newTitle ); - } else { - $wgOut->setPageTitle( $oldTitle . ', ' . $newTitle ); - } - $wgOut->setSubtitle( wfMsg( 'difference' ) ); - $wgOut->setRobotpolicy( 'noindex,nofollow' ); - - if ( !( $this->mOldPage->userCanRead() && $this->mNewPage->userCanRead() ) ) { - $wgOut->loginToUse(); - $wgOut->output(); - //wfProfileOut( $fname ); - exit; - } - - $sk = $wgUser->getSkin(); - - if ( $this->mNewRev->isCurrent() && $wgUser->isAllowed('rollback') ) { - $rollback = '   ' . $sk->generateRollback( $this->mNewRev ); - } else { - $rollback = ''; - } - if( $wgUseRCPatrol && $this->mRcidMarkPatrolled != 0 && $wgUser->isAllowed( 'patrol' ) ) { - $patrol = ' [' . $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'markaspatrolleddiff' ), "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}" ) . ']'; - } else { - $patrol = ''; - } - - $prevlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'previousdiff' ), - 'diff=prev&oldid='.$this->mOldid, '', '', 'id="differences-prevlink"' ); - if ( $this->mNewRev->isCurrent() ) { - $nextlink = ' '; - } else { - $nextlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'nextdiff' ), - 'diff=next&oldid='.$this->mNewid, '', '', 'id="differences-nextlink"' ); - } - - $oldminor = ''; - $newminor = ''; - - if ($this->mOldRev->mMinorEdit == 1) { - $oldminor = wfElement( 'span', array( 'class' => 'minor' ), - wfMsg( 'minoreditletter') ) . ' '; - } - - if ($this->mNewRev->mMinorEdit == 1) { - $newminor = wfElement( 'span', array( 'class' => 'minor' ), - wfMsg( 'minoreditletter') ) . ' '; - } - - $oldHeader = "{$this->mOldtitle}
          " . - $sk->revUserTools( $this->mOldRev ) . "
          " . - $oldminor . $sk->revComment( $this->mOldRev, !$diffOnly ) . "
          " . - $prevlink; - $newHeader = "{$this->mNewtitle}
          " . - $sk->revUserTools( $this->mNewRev ) . " $rollback
          " . - $newminor . $sk->revComment( $this->mNewRev, !$diffOnly ) . "
          " . - $nextlink . $patrol; - - $this->showDiff( $oldHeader, $newHeader ); - - if ( !$diffOnly ) - $this->renderNewRevision(); - - //wfProfileOut( $fname ); - } - - /** - * Show the new revision of the page. - */ - function renderNewRevision() { - global $wgOut; - $fname = 'DifferenceEngine::renderNewRevision'; - //wfProfileIn( $fname ); - - $wgOut->addHTML( "

          {$this->mPagetitle}

          \n" ); - #add deleted rev tag if needed - if ( !$this->mNewRev->userCan(Revision::DELETED_TEXT) ) { - $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) ); - } - - if( !$this->mNewRev->isCurrent() ) { - $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false ); - } - - $this->loadNewText(); - if( is_object( $this->mNewRev ) ) { - $wgOut->setRevisionId( $this->mNewRev->getId() ); - } - - $wgOut->addWikiTextTidy( $this->mNewtext ); - - if( !$this->mNewRev->isCurrent() ) { - $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting ); - } - - //wfProfileOut( $fname ); - } - - /** - * Show the first revision of an article. Uses normal diff headers in - * contrast to normal "old revision" display style. - */ - function showFirstRevision() { - global $wgOut, $wgUser; - - $fname = 'DifferenceEngine::showFirstRevision'; - //wfProfileIn( $fname ); - - # Get article text from the DB - # - if ( ! $this->loadNewText() ) { - $t = $this->mTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " . - "{$this->mNewid})"; - $mtext = wfMsg( 'missingarticle', "$t" ); - $wgOut->setPagetitle( wfMsg( 'errorpagetitle' ) ); - $wgOut->addWikitext( $mtext ); - //wfProfileOut( $fname ); - return; - } - if ( $this->mNewRev->isCurrent() ) { - $wgOut->setArticleFlag( true ); - } - - # Check if user is allowed to look at this page. If not, bail out. - # - if ( !( $this->mTitle->userCanRead() ) ) { - $wgOut->loginToUse(); - $wgOut->output(); - //wfProfileOut( $fname ); - exit; - } - - # Prepare the header box - # - $sk = $wgUser->getSkin(); - - $nextlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'nextdiff' ), 'diff=next&oldid='.$this->mNewid, '', '', 'id="differences-nextlink"' ); - $header = "
          {$this->mOldtitle}
          " . - $sk->revUserTools( $this->mNewRev ) . "
          " . - $sk->revComment( $this->mNewRev ) . "
          " . - $nextlink . "
          \n"; - - $wgOut->addHTML( $header ); - - $wgOut->setSubtitle( wfMsg( 'difference' ) ); - $wgOut->setRobotpolicy( 'noindex,nofollow' ); - - //wfProfileOut( $fname ); - } - - /** - * Get the diff text, send it to $wgOut - * Returns false if the diff could not be generated, otherwise returns true - */ - function showDiff( $otitle, $ntitle ) { - global $wgOut; - $diff = $this->getDiff( $otitle, $ntitle ); - if ( $diff === false ) { - $wgOut->addWikitext( wfMsg( 'missingarticle', "(fixme, bug)" ) ); - return false; - } else { - $wgOut->addHTML( $diff ); - return true; - } - } - - /** - * Get diff table, including header - * Note that the interface has changed, it's no longer static. - * Returns false on error - */ - function getDiff( $otitle, $ntitle ) { - $body = $this->getDiffBody(); - if ( $body === false ) { - return false; - } else { - $multi = $this->getMultiNotice(); - return $this->addHeader( $body, $otitle, $ntitle, $multi ); - } - } - - /** - * Get the diff table body, without header - * Results are cached - * Returns false on error - */ - function getDiffBody() { - global $wgMemc; - $fname = 'DifferenceEngine::getDiffBody'; - //wfProfileIn( $fname ); - - // Cacheable? - $key = false; - if ( $this->mOldid && $this->mNewid ) { - // Try cache - $key = wfMemcKey( 'diff', 'oldid', $this->mOldid, 'newid', $this->mNewid ); - $difftext = $wgMemc->get( $key ); - if ( $difftext ) { - wfIncrStats( 'diff_cache_hit' ); - $difftext = $this->localiseLineNumbers( $difftext ); - $difftext .= "\n\n"; - //wfProfileOut( $fname ); - return $difftext; - } - } - - #loadtext is permission safe, this just clears out the diff - if ( !$this->loadText() ) { - //wfProfileOut( $fname ); - return false; - } else if ( $this->mOldRev && !$this->mOldRev->userCan(Revision::DELETED_TEXT) ) { - return ''; - } else if ( $this->mNewRev && !$this->mNewRev->userCan(Revision::DELETED_TEXT) ) { - return ''; - } - - $difftext = $this->generateDiffBody( $this->mOldtext, $this->mNewtext ); - - // Save to cache for 7 days - if ( $key !== false && $difftext !== false ) { - wfIncrStats( 'diff_cache_miss' ); - $wgMemc->set( $key, $difftext, 7*86400 ); - } else { - wfIncrStats( 'diff_uncacheable' ); - } - // Replace line numbers with the text in the user's language - if ( $difftext !== false ) { - $difftext = $this->localiseLineNumbers( $difftext ); - } - //wfProfileOut( $fname ); - return $difftext; - } - - /** - * Generate a diff, no caching - * $otext and $ntext must be already segmented - */ - function generateDiffBody( $otext, $ntext ) { - global $wgExternalDiffEngine, $wgContLang; - $fname = 'DifferenceEngine::generateDiffBody'; - - $otext = str_replace( "\r\n", "\n", $otext ); - $ntext = str_replace( "\r\n", "\n", $ntext ); - - if ( $wgExternalDiffEngine == 'wikidiff' ) { - # For historical reasons, external diff engine expects - # input text to be HTML-escaped already - $otext = htmlspecialchars ( $wgContLang->segmentForDiff( $otext ) ); - $ntext = htmlspecialchars ( $wgContLang->segmentForDiff( $ntext ) ); - if( !function_exists( 'wikidiff_do_diff' ) ) { - dl('php_wikidiff.so'); - } - return $wgContLang->unsegementForDiff( wikidiff_do_diff( $otext, $ntext, 2 ) ); - } - - if ( $wgExternalDiffEngine == 'wikidiff2' ) { - # Better external diff engine, the 2 may some day be dropped - # This one does the escaping and segmenting itself - if ( !function_exists( 'wikidiff2_do_diff' ) ) { - //wfProfileIn( "$fname-dl" ); - @dl('php_wikidiff2.so'); - //wfProfileOut( "$fname-dl" ); - } - if ( function_exists( 'wikidiff2_do_diff' ) ) { - //wfProfileIn( 'wikidiff2_do_diff' ); - $text = wikidiff2_do_diff( $otext, $ntext, 2 ); - //wfProfileOut( 'wikidiff2_do_diff' ); - return $text; - } - } - if ( $wgExternalDiffEngine !== false ) { - # Diff via the shell - global $wgTmpDirectory; - $tempName1 = tempnam( $wgTmpDirectory, 'diff_' ); - $tempName2 = tempnam( $wgTmpDirectory, 'diff_' ); - - $tempFile1 = fopen( $tempName1, "w" ); - if ( !$tempFile1 ) { - //wfProfileOut( $fname ); - return false; - } - $tempFile2 = fopen( $tempName2, "w" ); - if ( !$tempFile2 ) { - //wfProfileOut( $fname ); - return false; - } - fwrite( $tempFile1, $otext ); - fwrite( $tempFile2, $ntext ); - fclose( $tempFile1 ); - fclose( $tempFile2 ); - $cmd = wfEscapeShellArg( $wgExternalDiffEngine, $tempName1, $tempName2 ); - //wfProfileIn( "$fname-shellexec" ); - $difftext = wfShellExec( $cmd ); - //wfProfileOut( "$fname-shellexec" ); - unlink( $tempName1 ); - unlink( $tempName2 ); - return $difftext; - } - - # Native PHP diff - $ota = explode( "\n", $wgContLang->segmentForDiff( $otext ) ); - $nta = explode( "\n", $wgContLang->segmentForDiff( $ntext ) ); - $diffs = new Diff( $ota, $nta ); - $formatter = new TableDiffFormatter(); - return $wgContLang->unsegmentForDiff( $formatter->format( $diffs ) ); - } - - - /** - * Replace line numbers with the text in the user's language - */ - function localiseLineNumbers( $text ) { - return preg_replace_callback( '//', - array( &$this, 'localiseLineNumbersCb' ), $text ); - } - - function localiseLineNumbersCb( $matches ) { - global $wgLang; - return wfMsgExt( 'lineno', array('parseinline'), $wgLang->formatNum( $matches[1] ) ); - } - - - /** - * If there are revisions between the ones being compared, return a note saying so. - */ - function getMultiNotice() { - if ( !is_object($this->mOldRev) || !is_object($this->mNewRev) ) - return ''; - - if( !$this->mOldPage->equals( $this->mNewPage ) ) { - // Comparing two different pages? Count would be meaningless. - return ''; - } - - $oldid = $this->mOldRev->getId(); - $newid = $this->mNewRev->getId(); - if ( $oldid > $newid ) { - $tmp = $oldid; $oldid = $newid; $newid = $tmp; - } - - $n = $this->mTitle->countRevisionsBetween( $oldid, $newid ); - if ( !$n ) - return ''; - - return wfMsgExt( 'diff-multi', array( 'parseinline' ), $n ); - } - - - /** - * Add the header to a diff body - */ - function addHeader( $diff, $otitle, $ntitle, $multi = '' ) { - global $wgOut; - - if ( $this->mOldRev && $this->mOldRev->isDeleted(Revision::DELETED_TEXT) ) { - $otitle = ''.$otitle.''; - } - if ( $this->mNewRev && $this->mNewRev->isDeleted(Revision::DELETED_TEXT) ) { - $ntitle = ''.$ntitle.''; - } - $header = " + echo($control); + return; + } + + $wgOut->setArticleFlag(false); + if (!$this->loadRevisionData()) { + $t = $this->mTitle->getPrefixedText() . " (Diff: {$this->mOldid}, {$this->mNewid})"; + $mtext = wfMsg('missingarticle', "$t"); + $wgOut->setPagetitle(wfMsg('errorpagetitle')); + $wgOut->addWikitext($mtext); + //wfProfileOut( $fname ); + return; + } + + wfRunHooks('DiffViewHeader', array( $this, $this->mOldRev, $this->mNewRev )); + + if ($this->mNewRev->isCurrent()) { + $wgOut->setArticleFlag(true); + } + + # mOldid is false if the difference engine is called with a "vague" query for + # a diff between a version V and its previous version V' AND the version V + # is the first version of that article. In that case, V' does not exist. + if ($this->mOldid === false) { + $this->showFirstRevision(); + $this->renderNewRevision(); // should we respect $diffOnly here or not? + //wfProfileOut( $fname ); + return; + } + + $wgOut->suppressQuickbar(); + + $oldTitle = $this->mOldPage->getPrefixedText(); + $newTitle = $this->mNewPage->getPrefixedText(); + if ($oldTitle == $newTitle) { + $wgOut->setPageTitle($newTitle); + } else { + $wgOut->setPageTitle($oldTitle . ', ' . $newTitle); + } + $wgOut->setSubtitle(wfMsg('difference')); + $wgOut->setRobotpolicy('noindex,nofollow'); + + if (!($this->mOldPage->userCanRead() && $this->mNewPage->userCanRead())) { + $wgOut->loginToUse(); + $wgOut->output(); + //wfProfileOut( $fname ); + exit; + } + + $sk = $wgUser->getSkin(); + + if ($this->mNewRev->isCurrent() && $wgUser->isAllowed('rollback')) { + $rollback = '   ' . $sk->generateRollback($this->mNewRev); + } else { + $rollback = ''; + } + if ($wgUseRCPatrol && $this->mRcidMarkPatrolled != 0 && $wgUser->isAllowed('patrol')) { + $patrol = ' [' . $sk->makeKnownLinkObj($this->mTitle, wfMsg('markaspatrolleddiff'), "action=markpatrolled&rcid={$this->mRcidMarkPatrolled}") . ']'; + } else { + $patrol = ''; + } + + $prevlink = $sk->makeKnownLinkObj( + $this->mTitle, + wfMsgHtml('previousdiff'), + 'diff=prev&oldid=' . $this->mOldid, + '', + '', + 'id="differences-prevlink"' + ); + if ($this->mNewRev->isCurrent()) { + $nextlink = ' '; + } else { + $nextlink = $sk->makeKnownLinkObj( + $this->mTitle, + wfMsgHtml('nextdiff'), + 'diff=next&oldid=' . $this->mNewid, + '', + '', + 'id="differences-nextlink"' + ); + } + + $oldminor = ''; + $newminor = ''; + + if ($this->mOldRev->mMinorEdit == 1) { + $oldminor = wfElement( + 'span', + array( 'class' => 'minor' ), + wfMsg('minoreditletter') + ) . ' '; + } + + if ($this->mNewRev->mMinorEdit == 1) { + $newminor = wfElement( + 'span', + array( 'class' => 'minor' ), + wfMsg('minoreditletter') + ) . ' '; + } + + $oldHeader = "{$this->mOldtitle}
          " . + $sk->revUserTools($this->mOldRev) . "
          " . + $oldminor . $sk->revComment($this->mOldRev, !$diffOnly) . "
          " . + $prevlink; + $newHeader = "{$this->mNewtitle}
          " . + $sk->revUserTools($this->mNewRev) . " $rollback
          " . + $newminor . $sk->revComment($this->mNewRev, !$diffOnly) . "
          " . + $nextlink . $patrol; + + $this->showDiff($oldHeader, $newHeader); + + if (!$diffOnly) { + $this->renderNewRevision(); + } + + //wfProfileOut( $fname ); + } + + /** + * Show the new revision of the page. + */ + public function renderNewRevision() + { + global $wgOut; + $fname = 'DifferenceEngine::renderNewRevision'; + //wfProfileIn( $fname ); + + $wgOut->addHTML("

          {$this->mPagetitle}

          \n"); + #add deleted rev tag if needed + if (!$this->mNewRev->userCan(Revision::DELETED_TEXT)) { + $wgOut->addWikiText(wfMsg('rev-deleted-text-permission')); + } + + if (!$this->mNewRev->isCurrent()) { + $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection(false); + } + + $this->loadNewText(); + if (is_object($this->mNewRev)) { + $wgOut->setRevisionId($this->mNewRev->getId()); + } + + $wgOut->addWikiTextTidy($this->mNewtext); + + if (!$this->mNewRev->isCurrent()) { + $wgOut->parserOptions()->setEditSection($oldEditSectionSetting); + } + + //wfProfileOut( $fname ); + } + + /** + * Show the first revision of an article. Uses normal diff headers in + * contrast to normal "old revision" display style. + */ + public function showFirstRevision() + { + global $wgOut, $wgUser; + + $fname = 'DifferenceEngine::showFirstRevision'; + //wfProfileIn( $fname ); + + # Get article text from the DB + # + if (!$this->loadNewText()) { + $t = $this->mTitle->getPrefixedText() . " (Diff: {$this->mOldid}, " . + "{$this->mNewid})"; + $mtext = wfMsg('missingarticle', "$t"); + $wgOut->setPagetitle(wfMsg('errorpagetitle')); + $wgOut->addWikitext($mtext); + //wfProfileOut( $fname ); + return; + } + if ($this->mNewRev->isCurrent()) { + $wgOut->setArticleFlag(true); + } + + # Check if user is allowed to look at this page. If not, bail out. + # + if (!($this->mTitle->userCanRead())) { + $wgOut->loginToUse(); + $wgOut->output(); + //wfProfileOut( $fname ); + exit; + } + + # Prepare the header box + # + $sk = $wgUser->getSkin(); + + $nextlink = $sk->makeKnownLinkObj($this->mTitle, wfMsgHtml('nextdiff'), 'diff=next&oldid=' . $this->mNewid, '', '', 'id="differences-nextlink"'); + $header = "
          {$this->mOldtitle}
          " . + $sk->revUserTools($this->mNewRev) . "
          " . + $sk->revComment($this->mNewRev) . "
          " . + $nextlink . "
          \n"; + + $wgOut->addHTML($header); + + $wgOut->setSubtitle(wfMsg('difference')); + $wgOut->setRobotpolicy('noindex,nofollow'); + + //wfProfileOut( $fname ); + } + + /** + * Get the diff text, send it to $wgOut + * Returns false if the diff could not be generated, otherwise returns true + */ + public function showDiff($otitle, $ntitle) + { + global $wgOut; + $diff = $this->getDiff($otitle, $ntitle); + if ($diff === false) { + $wgOut->addWikitext(wfMsg('missingarticle', "(fixme, bug)")); + return false; + } else { + $wgOut->addHTML($diff); + return true; + } + } + + /** + * Get diff table, including header + * Note that the interface has changed, it's no longer static. + * Returns false on error + */ + public function getDiff($otitle, $ntitle) + { + $body = $this->getDiffBody(); + if ($body === false) { + return false; + } else { + $multi = $this->getMultiNotice(); + return $this->addHeader($body, $otitle, $ntitle, $multi); + } + } + + /** + * Get the diff table body, without header + * Results are cached + * Returns false on error + */ + public function getDiffBody() + { + global $wgMemc; + $fname = 'DifferenceEngine::getDiffBody'; + //wfProfileIn( $fname ); + + // Cacheable? + $key = false; + if ($this->mOldid && $this->mNewid) { + // Try cache + $key = wfMemcKey('diff', 'oldid', $this->mOldid, 'newid', $this->mNewid); + $difftext = $wgMemc->get($key); + if ($difftext) { + wfIncrStats('diff_cache_hit'); + $difftext = $this->localiseLineNumbers($difftext); + $difftext .= "\n\n"; + //wfProfileOut( $fname ); + return $difftext; + } + } + + #loadtext is permission safe, this just clears out the diff + if (!$this->loadText()) { + //wfProfileOut( $fname ); + return false; + } elseif ($this->mOldRev && !$this->mOldRev->userCan(Revision::DELETED_TEXT)) { + return ''; + } elseif ($this->mNewRev && !$this->mNewRev->userCan(Revision::DELETED_TEXT)) { + return ''; + } + + $difftext = $this->generateDiffBody($this->mOldtext, $this->mNewtext); + + // Save to cache for 7 days + if ($key !== false && $difftext !== false) { + wfIncrStats('diff_cache_miss'); + $wgMemc->set($key, $difftext, 7*86400); + } else { + wfIncrStats('diff_uncacheable'); + } + // Replace line numbers with the text in the user's language + if ($difftext !== false) { + $difftext = $this->localiseLineNumbers($difftext); + } + //wfProfileOut( $fname ); + return $difftext; + } + + /** + * Generate a diff, no caching + * $otext and $ntext must be already segmented + */ + public function generateDiffBody($otext, $ntext) + { + global $wgExternalDiffEngine, $wgContLang; + $fname = 'DifferenceEngine::generateDiffBody'; + + $otext = str_replace("\r\n", "\n", $otext); + $ntext = str_replace("\r\n", "\n", $ntext); + + if ($wgExternalDiffEngine == 'wikidiff') { + # For historical reasons, external diff engine expects + # input text to be HTML-escaped already + $otext = htmlspecialchars($wgContLang->segmentForDiff($otext)); + $ntext = htmlspecialchars($wgContLang->segmentForDiff($ntext)); + if (!function_exists('wikidiff_do_diff')) { + dl('php_wikidiff.so'); + } + return $wgContLang->unsegementForDiff(wikidiff_do_diff($otext, $ntext, 2)); + } + + if ($wgExternalDiffEngine == 'wikidiff2') { + # Better external diff engine, the 2 may some day be dropped + # This one does the escaping and segmenting itself + if (!function_exists('wikidiff2_do_diff')) { + //wfProfileIn( "$fname-dl" ); + @dl('php_wikidiff2.so'); + //wfProfileOut( "$fname-dl" ); + } + if (function_exists('wikidiff2_do_diff')) { + //wfProfileIn( 'wikidiff2_do_diff' ); + $text = wikidiff2_do_diff($otext, $ntext, 2); + //wfProfileOut( 'wikidiff2_do_diff' ); + return $text; + } + } + if ($wgExternalDiffEngine !== false) { + # Diff via the shell + global $wgTmpDirectory; + $tempName1 = tempnam($wgTmpDirectory, 'diff_'); + $tempName2 = tempnam($wgTmpDirectory, 'diff_'); + + $tempFile1 = fopen($tempName1, "w"); + if (!$tempFile1) { + //wfProfileOut( $fname ); + return false; + } + $tempFile2 = fopen($tempName2, "w"); + if (!$tempFile2) { + //wfProfileOut( $fname ); + return false; + } + fwrite($tempFile1, $otext); + fwrite($tempFile2, $ntext); + fclose($tempFile1); + fclose($tempFile2); + $cmd = wfEscapeShellArg($wgExternalDiffEngine, $tempName1, $tempName2); + //wfProfileIn( "$fname-shellexec" ); + $difftext = wfShellExec($cmd); + //wfProfileOut( "$fname-shellexec" ); + unlink($tempName1); + unlink($tempName2); + return $difftext; + } + + # Native PHP diff + $ota = explode("\n", $wgContLang->segmentForDiff($otext)); + $nta = explode("\n", $wgContLang->segmentForDiff($ntext)); + $diffs = new Diff($ota, $nta); + $formatter = new TableDiffFormatter(); + return $wgContLang->unsegmentForDiff($formatter->format($diffs)); + } + + + /** + * Replace line numbers with the text in the user's language + */ + public function localiseLineNumbers($text) + { + return preg_replace_callback( + '//', + array( &$this, 'localiseLineNumbersCb' ), + $text + ); + } + + public function localiseLineNumbersCb($matches) + { + global $wgLang; + return wfMsgExt('lineno', array('parseinline'), $wgLang->formatNum($matches[1])); + } + + + /** + * If there are revisions between the ones being compared, return a note saying so. + */ + public function getMultiNotice() + { + if (!is_object($this->mOldRev) || !is_object($this->mNewRev)) { + return ''; + } + + if (!$this->mOldPage->equals($this->mNewPage)) { + // Comparing two different pages? Count would be meaningless. + return ''; + } + + $oldid = $this->mOldRev->getId(); + $newid = $this->mNewRev->getId(); + if ($oldid > $newid) { + $tmp = $oldid; + $oldid = $newid; + $newid = $tmp; + } + + $n = $this->mTitle->countRevisionsBetween($oldid, $newid); + if (!$n) { + return ''; + } + + return wfMsgExt('diff-multi', array( 'parseinline' ), $n); + } + + + /** + * Add the header to a diff body + */ + public function addHeader($diff, $otitle, $ntitle, $multi = '') + { + global $wgOut; + + if ($this->mOldRev && $this->mOldRev->isDeleted(Revision::DELETED_TEXT)) { + $otitle = '' . $otitle . ''; + } + if ($this->mNewRev && $this->mNewRev->isDeleted(Revision::DELETED_TEXT)) { + $ntitle = '' . $ntitle . ''; + } + $header = " @@ -499,154 +543,156 @@ CONTROL; "; - if ( $multi != '' ) - $header .= ""; - - return $header . $diff . "
          {$otitle}
          {$multi}
          "; - } - - /** - * Use specified text instead of loading from the database - */ - function setText( $oldText, $newText ) { - $this->mOldtext = $oldText; - $this->mNewtext = $newText; - $this->mTextLoaded = 2; - } - - /** - * Load revision metadata for the specified articles. If newid is 0, then compare - * the old article in oldid to the current article; if oldid is 0, then - * compare the current article to the immediately previous one (ignoring the - * value of newid). - * - * If oldid is false, leave the corresponding revision object set - * to false. This is impossible via ordinary user input, and is provided for - * API convenience. - */ - function loadRevisionData() { - global $wgLang; - if ( $this->mRevisionsLoaded ) { - return true; - } else { - // Whether it succeeds or fails, we don't want to try again - $this->mRevisionsLoaded = true; - } - - // Load the new revision object - if( $this->mNewid ) { - $this->mNewRev = Revision::newFromId( $this->mNewid ); - } else { - $this->mNewRev = Revision::newFromTitle( $this->mTitle ); - } - - if( is_null( $this->mNewRev ) ) { - return false; - } - - // Set assorted variables - $timestamp = $wgLang->timeanddate( $this->mNewRev->getTimestamp(), true ); - $this->mNewPage = $this->mNewRev->getTitle(); - if( $this->mNewRev->isCurrent() ) { - $newLink = $this->mNewPage->escapeLocalUrl(); - $this->mPagetitle = htmlspecialchars( wfMsg( 'currentrev' ) ); - $newEdit = $this->mNewPage->escapeLocalUrl( 'action=edit' ); - - $this->mNewtitle = "{$this->mPagetitle} ($timestamp)" - . " (" . htmlspecialchars( wfMsg( 'editold' ) ) . ")"; - - } else { - $newLink = $this->mNewPage->escapeLocalUrl( 'oldid=' . $this->mNewid ); - $newEdit = $this->mNewPage->escapeLocalUrl( 'action=edit&oldid=' . $this->mNewid ); - $this->mPagetitle = htmlspecialchars( wfMsg( 'revisionasof', $timestamp ) ); - - $this->mNewtitle = "{$this->mPagetitle}" - . " (" . htmlspecialchars( wfMsg( 'editold' ) ) . ")"; - } - - // Load the old revision object - $this->mOldRev = false; - if( $this->mOldid ) { - $this->mOldRev = Revision::newFromId( $this->mOldid ); - } elseif ( $this->mOldid === 0 ) { - $rev = $this->mNewRev->getPrevious(); - if( $rev ) { - $this->mOldid = $rev->getId(); - $this->mOldRev = $rev; - } else { - // No previous revision; mark to show as first-version only. - $this->mOldid = false; - $this->mOldRev = false; - } - }/* elseif ( $this->mOldid === false ) leave mOldRev false; */ - - if( is_null( $this->mOldRev ) ) { - return false; - } - - if ( $this->mOldRev ) { - $this->mOldPage = $this->mOldRev->getTitle(); - - $t = $wgLang->timeanddate( $this->mOldRev->getTimestamp(), true ); - $oldLink = $this->mOldPage->escapeLocalUrl( 'oldid=' . $this->mOldid ); - $oldEdit = $this->mOldPage->escapeLocalUrl( 'action=edit&oldid=' . $this->mOldid ); - $this->mOldtitle = "" . htmlspecialchars( wfMsg( 'revisionasof', $t ) ) - . " (" . htmlspecialchars( wfMsg( 'editold' ) ) . ")"; - //now that we considered old rev, we can make undo link (bug 8133, multi-edit undo) - $newUndo = $this->mNewPage->escapeLocalUrl( 'action=edit&undoafter=' . $this->mOldid . '&undo=' . $this->mNewid); - $this->mNewtitle .= " (" . htmlspecialchars( wfMsg( 'editundo' ) ) . ")"; - } - - return true; - } - - /** - * Load the text of the revisions, as well as revision data. - */ - function loadText() { - if ( $this->mTextLoaded == 2 ) { - return true; - } else { - // Whether it succeeds or fails, we don't want to try again - $this->mTextLoaded = 2; - } - - if ( !$this->loadRevisionData() ) { - return false; - } - if ( $this->mOldRev ) { - // FIXME: permission tests - $this->mOldtext = $this->mOldRev->revText(); - if ( $this->mOldtext === false ) { - return false; - } - } - if ( $this->mNewRev ) { - $this->mNewtext = $this->mNewRev->revText(); - if ( $this->mNewtext === false ) { - return false; - } - } - return true; - } - - /** - * Load the text of the new revision, not the old one - */ - function loadNewText() { - if ( $this->mTextLoaded >= 1 ) { - return true; - } else { - $this->mTextLoaded = 1; - } - if ( !$this->loadRevisionData() ) { - return false; - } - $this->mNewtext = $this->mNewRev->getText(); - return true; - } - - + if ($multi != '') { + $header .= "{$multi}"; + } + + return $header . $diff . ""; + } + + /** + * Use specified text instead of loading from the database + */ + public function setText($oldText, $newText) + { + $this->mOldtext = $oldText; + $this->mNewtext = $newText; + $this->mTextLoaded = 2; + } + + /** + * Load revision metadata for the specified articles. If newid is 0, then compare + * the old article in oldid to the current article; if oldid is 0, then + * compare the current article to the immediately previous one (ignoring the + * value of newid). + * + * If oldid is false, leave the corresponding revision object set + * to false. This is impossible via ordinary user input, and is provided for + * API convenience. + */ + public function loadRevisionData() + { + global $wgLang; + if ($this->mRevisionsLoaded) { + return true; + } else { + // Whether it succeeds or fails, we don't want to try again + $this->mRevisionsLoaded = true; + } + + // Load the new revision object + if ($this->mNewid) { + $this->mNewRev = Revision::newFromId($this->mNewid); + } else { + $this->mNewRev = Revision::newFromTitle($this->mTitle); + } + + if (is_null($this->mNewRev)) { + return false; + } + + // Set assorted variables + $timestamp = $wgLang->timeanddate($this->mNewRev->getTimestamp(), true); + $this->mNewPage = $this->mNewRev->getTitle(); + if ($this->mNewRev->isCurrent()) { + $newLink = $this->mNewPage->escapeLocalUrl(); + $this->mPagetitle = htmlspecialchars(wfMsg('currentrev')); + $newEdit = $this->mNewPage->escapeLocalUrl('action=edit'); + + $this->mNewtitle = "{$this->mPagetitle} ($timestamp)" + . " (" . htmlspecialchars(wfMsg('editold')) . ")"; + } else { + $newLink = $this->mNewPage->escapeLocalUrl('oldid=' . $this->mNewid); + $newEdit = $this->mNewPage->escapeLocalUrl('action=edit&oldid=' . $this->mNewid); + $this->mPagetitle = htmlspecialchars(wfMsg('revisionasof', $timestamp)); + + $this->mNewtitle = "{$this->mPagetitle}" + . " (" . htmlspecialchars(wfMsg('editold')) . ")"; + } + + // Load the old revision object + $this->mOldRev = false; + if ($this->mOldid) { + $this->mOldRev = Revision::newFromId($this->mOldid); + } elseif ($this->mOldid === 0) { + $rev = $this->mNewRev->getPrevious(); + if ($rev) { + $this->mOldid = $rev->getId(); + $this->mOldRev = $rev; + } else { + // No previous revision; mark to show as first-version only. + $this->mOldid = false; + $this->mOldRev = false; + } + }/* elseif ( $this->mOldid === false ) leave mOldRev false; */ + + if (is_null($this->mOldRev)) { + return false; + } + + if ($this->mOldRev) { + $this->mOldPage = $this->mOldRev->getTitle(); + + $t = $wgLang->timeanddate($this->mOldRev->getTimestamp(), true); + $oldLink = $this->mOldPage->escapeLocalUrl('oldid=' . $this->mOldid); + $oldEdit = $this->mOldPage->escapeLocalUrl('action=edit&oldid=' . $this->mOldid); + $this->mOldtitle = "" . htmlspecialchars(wfMsg('revisionasof', $t)) + . " (" . htmlspecialchars(wfMsg('editold')) . ")"; + //now that we considered old rev, we can make undo link (bug 8133, multi-edit undo) + $newUndo = $this->mNewPage->escapeLocalUrl('action=edit&undoafter=' . $this->mOldid . '&undo=' . $this->mNewid); + $this->mNewtitle .= " (" . htmlspecialchars(wfMsg('editundo')) . ")"; + } + + return true; + } + + /** + * Load the text of the revisions, as well as revision data. + */ + public function loadText() + { + if ($this->mTextLoaded == 2) { + return true; + } else { + // Whether it succeeds or fails, we don't want to try again + $this->mTextLoaded = 2; + } + + if (!$this->loadRevisionData()) { + return false; + } + if ($this->mOldRev) { + // FIXME: permission tests + $this->mOldtext = $this->mOldRev->revText(); + if ($this->mOldtext === false) { + return false; + } + } + if ($this->mNewRev) { + $this->mNewtext = $this->mNewRev->revText(); + if ($this->mNewtext === false) { + return false; + } + } + return true; + } + + /** + * Load the text of the new revision, not the old one + */ + public function loadNewText() + { + if ($this->mTextLoaded >= 1) { + return true; + } else { + $this->mTextLoaded = 1; + } + if (!$this->loadRevisionData()) { + return false; + } + $this->mNewtext = $this->mNewRev->getText(); + return true; + } } // A PHP diff engine for phpwiki. (Taken from phpwiki-1.3.3) @@ -662,22 +708,26 @@ define('USE_ASSERTS', function_exists('assert')); * @private * @addtogroup DifferenceEngine */ -class _DiffOp { - var $type; - var $orig; - var $closing; - - function reverse() { - trigger_error('pure virtual', E_USER_ERROR); - } - - function norig() { - return $this->orig ? sizeof($this->orig) : 0; - } - - function nclosing() { - return $this->closing ? sizeof($this->closing) : 0; - } +class _DiffOp +{ + public $type; + public $orig; + public $closing; + + public function reverse() + { + trigger_error('pure virtual', E_USER_ERROR); + } + + public function norig() + { + return $this->orig ? sizeof($this->orig) : 0; + } + + public function nclosing() + { + return $this->closing ? sizeof($this->closing) : 0; + } } /** @@ -685,19 +735,23 @@ class _DiffOp { * @private * @addtogroup DifferenceEngine */ -class _DiffOp_Copy extends _DiffOp { - var $type = 'copy'; - - function __construct ($orig, $closing = false) { - if (!is_array($closing)) - $closing = $orig; - $this->orig = $orig; - $this->closing = $closing; - } - - function reverse() { - return new _DiffOp_Copy($this->closing, $this->orig); - } +class _DiffOp_Copy extends _DiffOp +{ + public $type = 'copy'; + + public function __construct($orig, $closing = false) + { + if (!is_array($closing)) { + $closing = $orig; + } + $this->orig = $orig; + $this->closing = $closing; + } + + public function reverse() + { + return new _DiffOp_Copy($this->closing, $this->orig); + } } /** @@ -705,17 +759,20 @@ class _DiffOp_Copy extends _DiffOp { * @private * @addtogroup DifferenceEngine */ -class _DiffOp_Delete extends _DiffOp { - var $type = 'delete'; - - function __construct ($lines) { - $this->orig = $lines; - $this->closing = false; - } - - function reverse() { - return new _DiffOp_Add($this->orig); - } +class _DiffOp_Delete extends _DiffOp +{ + public $type = 'delete'; + + public function __construct($lines) + { + $this->orig = $lines; + $this->closing = false; + } + + public function reverse() + { + return new _DiffOp_Add($this->orig); + } } /** @@ -723,17 +780,20 @@ class _DiffOp_Delete extends _DiffOp { * @private * @addtogroup DifferenceEngine */ -class _DiffOp_Add extends _DiffOp { - var $type = 'add'; - - function __construct ($lines) { - $this->closing = $lines; - $this->orig = false; - } - - function reverse() { - return new _DiffOp_Delete($this->closing); - } +class _DiffOp_Add extends _DiffOp +{ + public $type = 'add'; + + public function __construct($lines) + { + $this->closing = $lines; + $this->orig = false; + } + + public function reverse() + { + return new _DiffOp_Delete($this->closing); + } } /** @@ -741,17 +801,20 @@ class _DiffOp_Add extends _DiffOp { * @private * @addtogroup DifferenceEngine */ -class _DiffOp_Change extends _DiffOp { - var $type = 'change'; - - function __construct ($orig, $closing) { - $this->orig = $orig; - $this->closing = $closing; - } - - function reverse() { - return new _DiffOp_Change($this->closing, $this->orig); - } +class _DiffOp_Change extends _DiffOp +{ + public $type = 'change'; + + public function __construct($orig, $closing) + { + $this->orig = $orig; + $this->closing = $closing; + } + + public function reverse() + { + return new _DiffOp_Change($this->closing, $this->orig); + } } @@ -780,417 +843,452 @@ class _DiffOp_Change extends _DiffOp { */ class _DiffEngine { - const MAX_XREF_LENGTH = 10000; - - function diff ($from_lines, $to_lines) { - $fname = '_DiffEngine::diff'; - //wfProfileIn( $fname ); - - $n_from = sizeof($from_lines); - $n_to = sizeof($to_lines); - - $this->xchanged = $this->ychanged = array(); - $this->xv = $this->yv = array(); - $this->xind = $this->yind = array(); - unset($this->seq); - unset($this->in_seq); - unset($this->lcs); - - // Skip leading common lines. - for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) { - if ($from_lines[$skip] !== $to_lines[$skip]) - break; - $this->xchanged[$skip] = $this->ychanged[$skip] = false; - } - // Skip trailing common lines. - $xi = $n_from; $yi = $n_to; - for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) { - if ($from_lines[$xi] !== $to_lines[$yi]) - break; - $this->xchanged[$xi] = $this->ychanged[$yi] = false; - } - - // Ignore lines which do not exist in both files. - for ($xi = $skip; $xi < $n_from - $endskip; $xi++) { - $xhash[$this->_line_hash($from_lines[$xi])] = 1; - } - - for ($yi = $skip; $yi < $n_to - $endskip; $yi++) { - $line = $to_lines[$yi]; - if ( ($this->ychanged[$yi] = empty($xhash[$this->_line_hash($line)])) ) - continue; - $yhash[$this->_line_hash($line)] = 1; - $this->yv[] = $line; - $this->yind[] = $yi; - } - for ($xi = $skip; $xi < $n_from - $endskip; $xi++) { - $line = $from_lines[$xi]; - if ( ($this->xchanged[$xi] = empty($yhash[$this->_line_hash($line)])) ) - continue; - $this->xv[] = $line; - $this->xind[] = $xi; - } - - // Find the LCS. - $this->_compareseq(0, sizeof($this->xv), 0, sizeof($this->yv)); - - // Merge edits when possible - $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged); - $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged); - - // Compute the edit operations. - $edits = array(); - $xi = $yi = 0; - while ($xi < $n_from || $yi < $n_to) { - USE_ASSERTS && assert($yi < $n_to || $this->xchanged[$xi]); - USE_ASSERTS && assert($xi < $n_from || $this->ychanged[$yi]); - - // Skip matching "snake". - $copy = array(); - while ( $xi < $n_from && $yi < $n_to - && !$this->xchanged[$xi] && !$this->ychanged[$yi]) { - $copy[] = $from_lines[$xi++]; - ++$yi; - } - if ($copy) - $edits[] = new _DiffOp_Copy($copy); - - // Find deletes & adds. - $delete = array(); - while ($xi < $n_from && $this->xchanged[$xi]) - $delete[] = $from_lines[$xi++]; - - $add = array(); - while ($yi < $n_to && $this->ychanged[$yi]) - $add[] = $to_lines[$yi++]; - - if ($delete && $add) - $edits[] = new _DiffOp_Change($delete, $add); - elseif ($delete) - $edits[] = new _DiffOp_Delete($delete); - elseif ($add) - $edits[] = new _DiffOp_Add($add); - } - //wfProfileOut( $fname ); - return $edits; - } - - /** - * Returns the whole line if it's small enough, or the MD5 hash otherwise - */ - function _line_hash( $line ) { - if ( strlen( $line ) > self::MAX_XREF_LENGTH ) { - return md5( $line ); - } else { - return $line; - } - } - - - /* Divide the Largest Common Subsequence (LCS) of the sequences - * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally - * sized segments. - * - * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an - * array of NCHUNKS+1 (X, Y) indexes giving the diving points between - * sub sequences. The first sub-sequence is contained in [X0, X1), - * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note - * that (X0, Y0) == (XOFF, YOFF) and - * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM). - * - * This function assumes that the first lines of the specified portions - * of the two files do not match, and likewise that the last lines do not - * match. The caller must trim matching lines from the beginning and end - * of the portions it is going to specify. - */ - function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) { - $fname = '_DiffEngine::_diag'; - //wfProfileIn( $fname ); - $flip = false; - - if ($xlim - $xoff > $ylim - $yoff) { - // Things seems faster (I'm not sure I understand why) - // when the shortest sequence in X. - $flip = true; - list ($xoff, $xlim, $yoff, $ylim) - = array( $yoff, $ylim, $xoff, $xlim); - } - - if ($flip) - for ($i = $ylim - 1; $i >= $yoff; $i--) - $ymatches[$this->xv[$i]][] = $i; - else - for ($i = $ylim - 1; $i >= $yoff; $i--) - $ymatches[$this->yv[$i]][] = $i; - - $this->lcs = 0; - $this->seq[0]= $yoff - 1; - $this->in_seq = array(); - $ymids[0] = array(); - - $numer = $xlim - $xoff + $nchunks - 1; - $x = $xoff; - for ($chunk = 0; $chunk < $nchunks; $chunk++) { - //wfProfileIn( "$fname-chunk" ); - if ($chunk > 0) - for ($i = 0; $i <= $this->lcs; $i++) - $ymids[$i][$chunk-1] = $this->seq[$i]; - - $x1 = $xoff + (int)(($numer + ($xlim-$xoff)*$chunk) / $nchunks); - for ( ; $x < $x1; $x++) { - $line = $flip ? $this->yv[$x] : $this->xv[$x]; - if (empty($ymatches[$line])) - continue; - $matches = $ymatches[$line]; - reset($matches); - while (list ($junk, $y) = each($matches)) - if (empty($this->in_seq[$y])) { - $k = $this->_lcs_pos($y); - USE_ASSERTS && assert($k > 0); - $ymids[$k] = $ymids[$k-1]; - break; - } - while (list ( /* $junk */, $y) = each($matches)) { - if ($y > $this->seq[$k-1]) { - USE_ASSERTS && assert($y < $this->seq[$k]); - // Optimization: this is a common case: - // next match is just replacing previous match. - $this->in_seq[$this->seq[$k]] = false; - $this->seq[$k] = $y; - $this->in_seq[$y] = 1; - } else if (empty($this->in_seq[$y])) { - $k = $this->_lcs_pos($y); - USE_ASSERTS && assert($k > 0); - $ymids[$k] = $ymids[$k-1]; - } - } - } - //wfProfileOut( "$fname-chunk" ); - } - - $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff); - $ymid = $ymids[$this->lcs]; - for ($n = 0; $n < $nchunks - 1; $n++) { - $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks); - $y1 = $ymid[$n] + 1; - $seps[] = $flip ? array($y1, $x1) : array($x1, $y1); - } - $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim); - - //wfProfileOut( $fname ); - return array($this->lcs, $seps); - } - - function _lcs_pos ($ypos) { - $fname = '_DiffEngine::_lcs_pos'; - //wfProfileIn( $fname ); - - $end = $this->lcs; - if ($end == 0 || $ypos > $this->seq[$end]) { - $this->seq[++$this->lcs] = $ypos; - $this->in_seq[$ypos] = 1; - //wfProfileOut( $fname ); - return $this->lcs; - } - - $beg = 1; - while ($beg < $end) { - $mid = (int)(($beg + $end) / 2); - if ( $ypos > $this->seq[$mid] ) - $beg = $mid + 1; - else - $end = $mid; - } - - USE_ASSERTS && assert($ypos != $this->seq[$end]); - - $this->in_seq[$this->seq[$end]] = false; - $this->seq[$end] = $ypos; - $this->in_seq[$ypos] = 1; - //wfProfileOut( $fname ); - return $end; - } - - /* Find LCS of two sequences. - * - * The results are recorded in the vectors $this->{x,y}changed[], by - * storing a 1 in the element for each line that is an insertion - * or deletion (ie. is not in the LCS). - * - * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1. - * - * Note that XLIM, YLIM are exclusive bounds. - * All line numbers are origin-0 and discarded lines are not counted. - */ - function _compareseq ($xoff, $xlim, $yoff, $ylim) { - $fname = '_DiffEngine::_compareseq'; - //wfProfileIn( $fname ); - - // Slide down the bottom initial diagonal. - while ($xoff < $xlim && $yoff < $ylim - && $this->xv[$xoff] == $this->yv[$yoff]) { - ++$xoff; - ++$yoff; - } - - // Slide up the top initial diagonal. - while ($xlim > $xoff && $ylim > $yoff - && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) { - --$xlim; - --$ylim; - } - - if ($xoff == $xlim || $yoff == $ylim) - $lcs = 0; - else { - // This is ad hoc but seems to work well. - //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5); - //$nchunks = max(2,min(8,(int)$nchunks)); - $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1; - list ($lcs, $seps) - = $this->_diag($xoff,$xlim,$yoff, $ylim,$nchunks); - } - - if ($lcs == 0) { - // X and Y sequences have no common subsequence: - // mark all changed. - while ($yoff < $ylim) - $this->ychanged[$this->yind[$yoff++]] = 1; - while ($xoff < $xlim) - $this->xchanged[$this->xind[$xoff++]] = 1; - } else { - // Use the partitions to split this problem into subproblems. - reset($seps); - $pt1 = $seps[0]; - while ($pt2 = next($seps)) { - $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]); - $pt1 = $pt2; - } - } - //wfProfileOut( $fname ); - } - - /* Adjust inserts/deletes of identical lines to join changes - * as much as possible. - * - * We do something when a run of changed lines include a - * line at one end and has an excluded, identical line at the other. - * We are free to choose which identical line is included. - * `compareseq' usually chooses the one at the beginning, - * but usually it is cleaner to consider the following identical line - * to be the "change". - * - * This is extracted verbatim from analyze.c (GNU diffutils-2.7). - */ - function _shift_boundaries ($lines, &$changed, $other_changed) { - $fname = '_DiffEngine::_shift_boundaries'; - //wfProfileIn( $fname ); - $i = 0; - $j = 0; - - USE_ASSERTS && assert(sizeof($lines) == sizeof($changed)); - $len = sizeof($lines); - $other_len = sizeof($other_changed); - - while (1) { - /* - * Scan forwards to find beginning of another run of changes. - * Also keep track of the corresponding point in the other file. - * - * Throughout this code, $i and $j are adjusted together so that - * the first $i elements of $changed and the first $j elements - * of $other_changed both contain the same number of zeros - * (unchanged lines). - * Furthermore, $j is always kept so that $j == $other_len or - * $other_changed[$j] == false. - */ - while ($j < $other_len && $other_changed[$j]) - $j++; - - while ($i < $len && ! $changed[$i]) { - USE_ASSERTS && assert($j < $other_len && ! $other_changed[$j]); - $i++; $j++; - while ($j < $other_len && $other_changed[$j]) - $j++; - } - - if ($i == $len) - break; - - $start = $i; - - // Find the end of this run of changes. - while (++$i < $len && $changed[$i]) - continue; - - do { - /* - * Record the length of this run of changes, so that - * we can later determine whether the run has grown. - */ - $runlength = $i - $start; - - /* - * Move the changed region back, so long as the - * previous unchanged line matches the last changed one. - * This merges with previous changed regions. - */ - while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) { - $changed[--$start] = 1; - $changed[--$i] = false; - while ($start > 0 && $changed[$start - 1]) - $start--; - USE_ASSERTS && assert($j > 0); - while ($other_changed[--$j]) - continue; - USE_ASSERTS && assert($j >= 0 && !$other_changed[$j]); - } - - /* - * Set CORRESPONDING to the end of the changed run, at the last - * point where it corresponds to a changed run in the other file. - * CORRESPONDING == LEN means no such point has been found. - */ - $corresponding = $j < $other_len ? $i : $len; - - /* - * Move the changed region forward, so long as the - * first changed line matches the following unchanged one. - * This merges with following changed regions. - * Do this second, so that if there are no merges, - * the changed region is moved forward as far as possible. - */ - while ($i < $len && $lines[$start] == $lines[$i]) { - $changed[$start++] = false; - $changed[$i++] = 1; - while ($i < $len && $changed[$i]) - $i++; - - USE_ASSERTS && assert($j < $other_len && ! $other_changed[$j]); - $j++; - if ($j < $other_len && $other_changed[$j]) { - $corresponding = $i; - while ($j < $other_len && $other_changed[$j]) - $j++; - } - } - } while ($runlength != $i - $start); - - /* - * If possible, move the fully-merged run of changes - * back to a corresponding run in the other file. - */ - while ($corresponding < $i) { - $changed[--$start] = 1; - $changed[--$i] = 0; - USE_ASSERTS && assert($j > 0); - while ($other_changed[--$j]) - continue; - USE_ASSERTS && assert($j >= 0 && !$other_changed[$j]); - } - } - //wfProfileOut( $fname ); - } + const MAX_XREF_LENGTH = 10000; + + public function diff($from_lines, $to_lines) + { + $fname = '_DiffEngine::diff'; + //wfProfileIn( $fname ); + + $n_from = sizeof($from_lines); + $n_to = sizeof($to_lines); + + $this->xchanged = $this->ychanged = array(); + $this->xv = $this->yv = array(); + $this->xind = $this->yind = array(); + unset($this->seq); + unset($this->in_seq); + unset($this->lcs); + + // Skip leading common lines. + for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) { + if ($from_lines[$skip] !== $to_lines[$skip]) { + break; + } + $this->xchanged[$skip] = $this->ychanged[$skip] = false; + } + // Skip trailing common lines. + $xi = $n_from; + $yi = $n_to; + for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) { + if ($from_lines[$xi] !== $to_lines[$yi]) { + break; + } + $this->xchanged[$xi] = $this->ychanged[$yi] = false; + } + + // Ignore lines which do not exist in both files. + for ($xi = $skip; $xi < $n_from - $endskip; $xi++) { + $xhash[$this->_line_hash($from_lines[$xi])] = 1; + } + + for ($yi = $skip; $yi < $n_to - $endskip; $yi++) { + $line = $to_lines[$yi]; + if (($this->ychanged[$yi] = empty($xhash[$this->_line_hash($line)]))) { + continue; + } + $yhash[$this->_line_hash($line)] = 1; + $this->yv[] = $line; + $this->yind[] = $yi; + } + for ($xi = $skip; $xi < $n_from - $endskip; $xi++) { + $line = $from_lines[$xi]; + if (($this->xchanged[$xi] = empty($yhash[$this->_line_hash($line)]))) { + continue; + } + $this->xv[] = $line; + $this->xind[] = $xi; + } + + // Find the LCS. + $this->_compareseq(0, sizeof($this->xv), 0, sizeof($this->yv)); + + // Merge edits when possible + $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged); + $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged); + + // Compute the edit operations. + $edits = array(); + $xi = $yi = 0; + while ($xi < $n_from || $yi < $n_to) { + USE_ASSERTS && assert($yi < $n_to || $this->xchanged[$xi]); + USE_ASSERTS && assert($xi < $n_from || $this->ychanged[$yi]); + + // Skip matching "snake". + $copy = array(); + while ($xi < $n_from && $yi < $n_to + && !$this->xchanged[$xi] && !$this->ychanged[$yi]) { + $copy[] = $from_lines[$xi++]; + ++$yi; + } + if ($copy) { + $edits[] = new _DiffOp_Copy($copy); + } + + // Find deletes & adds. + $delete = array(); + while ($xi < $n_from && $this->xchanged[$xi]) { + $delete[] = $from_lines[$xi++]; + } + + $add = array(); + while ($yi < $n_to && $this->ychanged[$yi]) { + $add[] = $to_lines[$yi++]; + } + + if ($delete && $add) { + $edits[] = new _DiffOp_Change($delete, $add); + } elseif ($delete) { + $edits[] = new _DiffOp_Delete($delete); + } elseif ($add) { + $edits[] = new _DiffOp_Add($add); + } + } + //wfProfileOut( $fname ); + return $edits; + } + + /** + * Returns the whole line if it's small enough, or the MD5 hash otherwise + */ + public function _line_hash($line) + { + if (strlen($line) > self::MAX_XREF_LENGTH) { + return md5($line); + } else { + return $line; + } + } + + + /* Divide the Largest Common Subsequence (LCS) of the sequences + * [XOFF, XLIM) and [YOFF, YLIM) into NCHUNKS approximately equally + * sized segments. + * + * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an + * array of NCHUNKS+1 (X, Y) indexes giving the diving points between + * sub sequences. The first sub-sequence is contained in [X0, X1), + * [Y0, Y1), the second in [X1, X2), [Y1, Y2) and so on. Note + * that (X0, Y0) == (XOFF, YOFF) and + * (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM). + * + * This function assumes that the first lines of the specified portions + * of the two files do not match, and likewise that the last lines do not + * match. The caller must trim matching lines from the beginning and end + * of the portions it is going to specify. + */ + public function _diag($xoff, $xlim, $yoff, $ylim, $nchunks) + { + $fname = '_DiffEngine::_diag'; + //wfProfileIn( $fname ); + $flip = false; + + if ($xlim - $xoff > $ylim - $yoff) { + // Things seems faster (I'm not sure I understand why) + // when the shortest sequence in X. + $flip = true; + list($xoff, $xlim, $yoff, $ylim) + = array( $yoff, $ylim, $xoff, $xlim); + } + + if ($flip) { + for ($i = $ylim - 1; $i >= $yoff; $i--) { + $ymatches[$this->xv[$i]][] = $i; + } + } else { + for ($i = $ylim - 1; $i >= $yoff; $i--) { + $ymatches[$this->yv[$i]][] = $i; + } + } + + $this->lcs = 0; + $this->seq[0]= $yoff - 1; + $this->in_seq = array(); + $ymids[0] = array(); + + $numer = $xlim - $xoff + $nchunks - 1; + $x = $xoff; + for ($chunk = 0; $chunk < $nchunks; $chunk++) { + //wfProfileIn( "$fname-chunk" ); + if ($chunk > 0) { + for ($i = 0; $i <= $this->lcs; $i++) { + $ymids[$i][$chunk-1] = $this->seq[$i]; + } + } + + $x1 = $xoff + (int) (($numer + ($xlim-$xoff)*$chunk) / $nchunks); + for (; $x < $x1; $x++) { + $line = $flip ? $this->yv[$x] : $this->xv[$x]; + if (empty($ymatches[$line])) { + continue; + } + $matches = $ymatches[$line]; + reset($matches); + while (list($junk, $y) = each($matches)) { + if (empty($this->in_seq[$y])) { + $k = $this->_lcs_pos($y); + USE_ASSERTS && assert($k > 0); + $ymids[$k] = $ymids[$k-1]; + break; + } + } + while (list( /* $junk */, $y) = each($matches)) { + if ($y > $this->seq[$k-1]) { + USE_ASSERTS && assert($y < $this->seq[$k]); + // Optimization: this is a common case: + // next match is just replacing previous match. + $this->in_seq[$this->seq[$k]] = false; + $this->seq[$k] = $y; + $this->in_seq[$y] = 1; + } elseif (empty($this->in_seq[$y])) { + $k = $this->_lcs_pos($y); + USE_ASSERTS && assert($k > 0); + $ymids[$k] = $ymids[$k-1]; + } + } + } + //wfProfileOut( "$fname-chunk" ); + } + + $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff); + $ymid = $ymids[$this->lcs]; + for ($n = 0; $n < $nchunks - 1; $n++) { + $x1 = $xoff + (int) (($numer + ($xlim - $xoff) * $n) / $nchunks); + $y1 = $ymid[$n] + 1; + $seps[] = $flip ? array($y1, $x1) : array($x1, $y1); + } + $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim); + + //wfProfileOut( $fname ); + return array($this->lcs, $seps); + } + + public function _lcs_pos($ypos) + { + $fname = '_DiffEngine::_lcs_pos'; + //wfProfileIn( $fname ); + + $end = $this->lcs; + if ($end == 0 || $ypos > $this->seq[$end]) { + $this->seq[++$this->lcs] = $ypos; + $this->in_seq[$ypos] = 1; + //wfProfileOut( $fname ); + return $this->lcs; + } + + $beg = 1; + while ($beg < $end) { + $mid = (int) (($beg + $end) / 2); + if ($ypos > $this->seq[$mid]) { + $beg = $mid + 1; + } else { + $end = $mid; + } + } + + USE_ASSERTS && assert($ypos != $this->seq[$end]); + + $this->in_seq[$this->seq[$end]] = false; + $this->seq[$end] = $ypos; + $this->in_seq[$ypos] = 1; + //wfProfileOut( $fname ); + return $end; + } + + /* Find LCS of two sequences. + * + * The results are recorded in the vectors $this->{x,y}changed[], by + * storing a 1 in the element for each line that is an insertion + * or deletion (ie. is not in the LCS). + * + * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1. + * + * Note that XLIM, YLIM are exclusive bounds. + * All line numbers are origin-0 and discarded lines are not counted. + */ + public function _compareseq($xoff, $xlim, $yoff, $ylim) + { + $fname = '_DiffEngine::_compareseq'; + //wfProfileIn( $fname ); + + // Slide down the bottom initial diagonal. + while ($xoff < $xlim && $yoff < $ylim + && $this->xv[$xoff] == $this->yv[$yoff]) { + ++$xoff; + ++$yoff; + } + + // Slide up the top initial diagonal. + while ($xlim > $xoff && $ylim > $yoff + && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) { + --$xlim; + --$ylim; + } + + if ($xoff == $xlim || $yoff == $ylim) { + $lcs = 0; + } else { + // This is ad hoc but seems to work well. + //$nchunks = sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5); + //$nchunks = max(2,min(8,(int)$nchunks)); + $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1; + list($lcs, $seps) + = $this->_diag($xoff, $xlim, $yoff, $ylim, $nchunks); + } + + if ($lcs == 0) { + // X and Y sequences have no common subsequence: + // mark all changed. + while ($yoff < $ylim) { + $this->ychanged[$this->yind[$yoff++]] = 1; + } + while ($xoff < $xlim) { + $this->xchanged[$this->xind[$xoff++]] = 1; + } + } else { + // Use the partitions to split this problem into subproblems. + reset($seps); + $pt1 = $seps[0]; + while ($pt2 = next($seps)) { + $this->_compareseq($pt1[0], $pt2[0], $pt1[1], $pt2[1]); + $pt1 = $pt2; + } + } + //wfProfileOut( $fname ); + } + + /* Adjust inserts/deletes of identical lines to join changes + * as much as possible. + * + * We do something when a run of changed lines include a + * line at one end and has an excluded, identical line at the other. + * We are free to choose which identical line is included. + * `compareseq' usually chooses the one at the beginning, + * but usually it is cleaner to consider the following identical line + * to be the "change". + * + * This is extracted verbatim from analyze.c (GNU diffutils-2.7). + */ + public function _shift_boundaries($lines, &$changed, $other_changed) + { + $fname = '_DiffEngine::_shift_boundaries'; + //wfProfileIn( $fname ); + $i = 0; + $j = 0; + + USE_ASSERTS && assert(sizeof($lines) == sizeof($changed)); + $len = sizeof($lines); + $other_len = sizeof($other_changed); + + while (1) { + /* + * Scan forwards to find beginning of another run of changes. + * Also keep track of the corresponding point in the other file. + * + * Throughout this code, $i and $j are adjusted together so that + * the first $i elements of $changed and the first $j elements + * of $other_changed both contain the same number of zeros + * (unchanged lines). + * Furthermore, $j is always kept so that $j == $other_len or + * $other_changed[$j] == false. + */ + while ($j < $other_len && $other_changed[$j]) { + $j++; + } + + while ($i < $len && !$changed[$i]) { + USE_ASSERTS && assert($j < $other_len && !$other_changed[$j]); + $i++; + $j++; + while ($j < $other_len && $other_changed[$j]) { + $j++; + } + } + + if ($i == $len) { + break; + } + + $start = $i; + + // Find the end of this run of changes. + while (++$i < $len && $changed[$i]) { + continue; + } + + do { + /* + * Record the length of this run of changes, so that + * we can later determine whether the run has grown. + */ + $runlength = $i - $start; + + /* + * Move the changed region back, so long as the + * previous unchanged line matches the last changed one. + * This merges with previous changed regions. + */ + while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) { + $changed[--$start] = 1; + $changed[--$i] = false; + while ($start > 0 && $changed[$start - 1]) { + $start--; + } + USE_ASSERTS && assert($j > 0); + while ($other_changed[--$j]) { + continue; + } + USE_ASSERTS && assert($j >= 0 && !$other_changed[$j]); + } + + /* + * Set CORRESPONDING to the end of the changed run, at the last + * point where it corresponds to a changed run in the other file. + * CORRESPONDING == LEN means no such point has been found. + */ + $corresponding = $j < $other_len ? $i : $len; + + /* + * Move the changed region forward, so long as the + * first changed line matches the following unchanged one. + * This merges with following changed regions. + * Do this second, so that if there are no merges, + * the changed region is moved forward as far as possible. + */ + while ($i < $len && $lines[$start] == $lines[$i]) { + $changed[$start++] = false; + $changed[$i++] = 1; + while ($i < $len && $changed[$i]) { + $i++; + } + + USE_ASSERTS && assert($j < $other_len && !$other_changed[$j]); + $j++; + if ($j < $other_len && $other_changed[$j]) { + $corresponding = $i; + while ($j < $other_len && $other_changed[$j]) { + $j++; + } + } + } + } while ($runlength != $i - $start); + + /* + * If possible, move the fully-merged run of changes + * back to a corresponding run in the other file. + */ + while ($corresponding < $i) { + $changed[--$start] = 1; + $changed[--$i] = 0; + USE_ASSERTS && assert($j > 0); + while ($other_changed[--$j]) { + continue; + } + USE_ASSERTS && assert($j >= 0 && !$other_changed[$j]); + } + } + //wfProfileOut( $fname ); + } } /** @@ -1201,137 +1299,153 @@ class _DiffEngine */ class Diff { - var $edits; - - /** - * Constructor. - * Computes diff between sequences of strings. - * - * @param $from_lines array An array of strings. - * (Typically these are lines from a file.) - * @param $to_lines array An array of strings. - */ - function __construct($from_lines, $to_lines) { - $eng = new _DiffEngine; - $this->edits = $eng->diff($from_lines, $to_lines); - //$this->_check($from_lines, $to_lines); - } - - /** - * Compute reversed Diff. - * - * SYNOPSIS: - * - * $diff = new Diff($lines1, $lines2); - * $rev = $diff->reverse(); - * @return object A Diff object representing the inverse of the - * original diff. - */ - function reverse () { - $rev = $this; - $rev->edits = array(); - foreach ($this->edits as $edit) { - $rev->edits[] = $edit->reverse(); - } - return $rev; - } - - /** - * Check for empty diff. - * - * @return bool True iff two sequences were identical. - */ - function isEmpty () { - foreach ($this->edits as $edit) { - if ($edit->type != 'copy') - return false; - } - return true; - } - - /** - * Compute the length of the Longest Common Subsequence (LCS). - * - * This is mostly for diagnostic purposed. - * - * @return int The length of the LCS. - */ - function lcs () { - $lcs = 0; - foreach ($this->edits as $edit) { - if ($edit->type == 'copy') - $lcs += sizeof($edit->orig); - } - return $lcs; - } - - /** - * Get the original set of lines. - * - * This reconstructs the $from_lines parameter passed to the - * constructor. - * - * @return array The original sequence of strings. - */ - function orig() { - $lines = array(); - - foreach ($this->edits as $edit) { - if ($edit->orig) - array_splice($lines, sizeof($lines), 0, $edit->orig); - } - return $lines; - } - - /** - * Get the closing set of lines. - * - * This reconstructs the $to_lines parameter passed to the - * constructor. - * - * @return array The sequence of strings. - */ - function closing() { - $lines = array(); - - foreach ($this->edits as $edit) { - if ($edit->closing) - array_splice($lines, sizeof($lines), 0, $edit->closing); - } - return $lines; - } - - /** - * Check a Diff for validity. - * - * This is here only for debugging purposes. - */ - function _check ($from_lines, $to_lines) { - $fname = 'Diff::_check'; - //wfProfileIn( $fname ); - if (serialize($from_lines) != serialize($this->orig())) - trigger_error("Reconstructed original doesn't match", E_USER_ERROR); - if (serialize($to_lines) != serialize($this->closing())) - trigger_error("Reconstructed closing doesn't match", E_USER_ERROR); - - $rev = $this->reverse(); - if (serialize($to_lines) != serialize($rev->orig())) - trigger_error("Reversed original doesn't match", E_USER_ERROR); - if (serialize($from_lines) != serialize($rev->closing())) - trigger_error("Reversed closing doesn't match", E_USER_ERROR); - - - $prevtype = 'none'; - foreach ($this->edits as $edit) { - if ( $prevtype == $edit->type ) - trigger_error("Edit sequence is non-optimal", E_USER_ERROR); - $prevtype = $edit->type; - } - - $lcs = $this->lcs(); - trigger_error('Diff okay: LCS = '.$lcs, E_USER_NOTICE); - //wfProfileOut( $fname ); - } + public $edits; + + /** + * Constructor. + * Computes diff between sequences of strings. + * + * @param $from_lines array An array of strings. + * (Typically these are lines from a file.) + * @param $to_lines array An array of strings. + */ + public function __construct($from_lines, $to_lines) + { + $eng = new _DiffEngine; + $this->edits = $eng->diff($from_lines, $to_lines); + //$this->_check($from_lines, $to_lines); + } + + /** + * Compute reversed Diff. + * + * SYNOPSIS: + * + * $diff = new Diff($lines1, $lines2); + * $rev = $diff->reverse(); + * @return object A Diff object representing the inverse of the + * original diff. + */ + public function reverse() + { + $rev = $this; + $rev->edits = array(); + foreach ($this->edits as $edit) { + $rev->edits[] = $edit->reverse(); + } + return $rev; + } + + /** + * Check for empty diff. + * + * @return bool True iff two sequences were identical. + */ + public function isEmpty() + { + foreach ($this->edits as $edit) { + if ($edit->type != 'copy') { + return false; + } + } + return true; + } + + /** + * Compute the length of the Longest Common Subsequence (LCS). + * + * This is mostly for diagnostic purposed. + * + * @return int The length of the LCS. + */ + public function lcs() + { + $lcs = 0; + foreach ($this->edits as $edit) { + if ($edit->type == 'copy') { + $lcs += sizeof($edit->orig); + } + } + return $lcs; + } + + /** + * Get the original set of lines. + * + * This reconstructs the $from_lines parameter passed to the + * constructor. + * + * @return array The original sequence of strings. + */ + public function orig() + { + $lines = array(); + + foreach ($this->edits as $edit) { + if ($edit->orig) { + array_splice($lines, sizeof($lines), 0, $edit->orig); + } + } + return $lines; + } + + /** + * Get the closing set of lines. + * + * This reconstructs the $to_lines parameter passed to the + * constructor. + * + * @return array The sequence of strings. + */ + public function closing() + { + $lines = array(); + + foreach ($this->edits as $edit) { + if ($edit->closing) { + array_splice($lines, sizeof($lines), 0, $edit->closing); + } + } + return $lines; + } + + /** + * Check a Diff for validity. + * + * This is here only for debugging purposes. + */ + public function _check($from_lines, $to_lines) + { + $fname = 'Diff::_check'; + //wfProfileIn( $fname ); + if (serialize($from_lines) != serialize($this->orig())) { + trigger_error("Reconstructed original doesn't match", E_USER_ERROR); + } + if (serialize($to_lines) != serialize($this->closing())) { + trigger_error("Reconstructed closing doesn't match", E_USER_ERROR); + } + + $rev = $this->reverse(); + if (serialize($to_lines) != serialize($rev->orig())) { + trigger_error("Reversed original doesn't match", E_USER_ERROR); + } + if (serialize($from_lines) != serialize($rev->closing())) { + trigger_error("Reversed closing doesn't match", E_USER_ERROR); + } + + + $prevtype = 'none'; + foreach ($this->edits as $edit) { + if ($prevtype == $edit->type) { + trigger_error("Edit sequence is non-optimal", E_USER_ERROR); + } + $prevtype = $edit->type; + } + + $lcs = $this->lcs(); + trigger_error('Diff okay: LCS = ' . $lcs, E_USER_NOTICE); + //wfProfileOut( $fname ); + } } /** @@ -1341,55 +1455,59 @@ class Diff */ class MappedDiff extends Diff { - /** - * Constructor. - * - * Computes diff between sequences of strings. - * - * This can be used to compute things like - * case-insensitve diffs, or diffs which ignore - * changes in white-space. - * - * @param $from_lines array An array of strings. - * (Typically these are lines from a file.) - * - * @param $to_lines array An array of strings. - * - * @param $mapped_from_lines array This array should - * have the same size number of elements as $from_lines. - * The elements in $mapped_from_lines and - * $mapped_to_lines are what is actually compared - * when computing the diff. - * - * @param $mapped_to_lines array This array should - * have the same number of elements as $to_lines. - */ - function __construct($from_lines, $to_lines, - $mapped_from_lines, $mapped_to_lines) { - $fname = 'MappedDiff::MappedDiff'; - //wfProfileIn( $fname ); - - assert(sizeof($from_lines) == sizeof($mapped_from_lines)); - assert(sizeof($to_lines) == sizeof($mapped_to_lines)); - - parent::__construct($mapped_from_lines, $mapped_to_lines); - - $xi = $yi = 0; - for ($i = 0; $i < sizeof($this->edits); $i++) { - $orig = &$this->edits[$i]->orig; - if (is_array($orig)) { - $orig = array_slice($from_lines, $xi, sizeof($orig)); - $xi += sizeof($orig); - } - - $closing = &$this->edits[$i]->closing; - if (is_array($closing)) { - $closing = array_slice($to_lines, $yi, sizeof($closing)); - $yi += sizeof($closing); - } - } - //wfProfileOut( $fname ); - } + /** + * Constructor. + * + * Computes diff between sequences of strings. + * + * This can be used to compute things like + * case-insensitve diffs, or diffs which ignore + * changes in white-space. + * + * @param $from_lines array An array of strings. + * (Typically these are lines from a file.) + * + * @param $to_lines array An array of strings. + * + * @param $mapped_from_lines array This array should + * have the same size number of elements as $from_lines. + * The elements in $mapped_from_lines and + * $mapped_to_lines are what is actually compared + * when computing the diff. + * + * @param $mapped_to_lines array This array should + * have the same number of elements as $to_lines. + */ + public function __construct( + $from_lines, + $to_lines, + $mapped_from_lines, + $mapped_to_lines + ) { + $fname = 'MappedDiff::MappedDiff'; + //wfProfileIn( $fname ); + + assert(sizeof($from_lines) == sizeof($mapped_from_lines)); + assert(sizeof($to_lines) == sizeof($mapped_to_lines)); + + parent::__construct($mapped_from_lines, $mapped_to_lines); + + $xi = $yi = 0; + for ($i = 0; $i < sizeof($this->edits); $i++) { + $orig = &$this->edits[$i]->orig; + if (is_array($orig)) { + $orig = array_slice($from_lines, $xi, sizeof($orig)); + $xi += sizeof($orig); + } + + $closing = &$this->edits[$i]->closing; + if (is_array($closing)) { + $closing = array_slice($to_lines, $yi, sizeof($closing)); + $yi += sizeof($closing); + } + } + //wfProfileOut( $fname ); + } } /** @@ -1404,155 +1522,181 @@ class MappedDiff extends Diff */ class DiffFormatter { - /** - * Number of leading context "lines" to preserve. - * - * This should be left at zero for this class, but subclasses - * may want to set this to other values. - */ - var $leading_context_lines = 0; - - /** - * Number of trailing context "lines" to preserve. - * - * This should be left at zero for this class, but subclasses - * may want to set this to other values. - */ - var $trailing_context_lines = 0; - - /** - * Format a diff. - * - * @param $diff object A Diff object. - * @return string The formatted output. - */ - function format($diff) { - $fname = 'DiffFormatter::format'; - //wfProfileIn( $fname ); - - $xi = $yi = 1; - $block = false; - $context = array(); - - $nlead = $this->leading_context_lines; - $ntrail = $this->trailing_context_lines; - - $this->_start_diff(); - - foreach ($diff->edits as $edit) { - if ($edit->type == 'copy') { - if (is_array($block)) { - if (sizeof($edit->orig) <= $nlead + $ntrail) { - $block[] = $edit; - } - else{ - if ($ntrail) { - $context = array_slice($edit->orig, 0, $ntrail); - $block[] = new _DiffOp_Copy($context); - } - $this->_block($x0, $ntrail + $xi - $x0, - $y0, $ntrail + $yi - $y0, - $block); - $block = false; - } - } - $context = $edit->orig; - } - else { - if (! is_array($block)) { - $context = array_slice($context, sizeof($context) - $nlead); - $x0 = $xi - sizeof($context); - $y0 = $yi - sizeof($context); - $block = array(); - if ($context) - $block[] = new _DiffOp_Copy($context); - } - $block[] = $edit; - } - - if ($edit->orig) - $xi += sizeof($edit->orig); - if ($edit->closing) - $yi += sizeof($edit->closing); - } - - if (is_array($block)) - $this->_block($x0, $xi - $x0, - $y0, $yi - $y0, - $block); - - $end = $this->_end_diff(); - //wfProfileOut( $fname ); - return $end; - } - - function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) { - $fname = 'DiffFormatter::_block'; - //wfProfileIn( $fname ); - $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen)); - foreach ($edits as $edit) { - if ($edit->type == 'copy') - $this->_context($edit->orig); - elseif ($edit->type == 'add') - $this->_added($edit->closing); - elseif ($edit->type == 'delete') - $this->_deleted($edit->orig); - elseif ($edit->type == 'change') - $this->_changed($edit->orig, $edit->closing); - else - trigger_error('Unknown edit type', E_USER_ERROR); - } - $this->_end_block(); - //wfProfileOut( $fname ); - } - - function _start_diff() { - ob_start(); - } - - function _end_diff() { - $val = ob_get_contents(); - ob_end_clean(); - return $val; - } - - function _block_header($xbeg, $xlen, $ybeg, $ylen) { - if ($xlen > 1) - $xbeg .= "," . ($xbeg + $xlen - 1); - if ($ylen > 1) - $ybeg .= "," . ($ybeg + $ylen - 1); - - return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg; - } - - function _start_block($header) { - echo $header; - } - - function _end_block() { - } - - function _lines($lines, $prefix = ' ') { - foreach ($lines as $line) - echo "$prefix $line\n"; - } - - function _context($lines) { - $this->_lines($lines); - } - - function _added($lines) { - $this->_lines($lines, '>'); - } - function _deleted($lines) { - $this->_lines($lines, '<'); - } - - function _changed($orig, $closing) { - $this->_deleted($orig); - echo "---\n"; - $this->_added($closing); - } + /** + * Number of leading context "lines" to preserve. + * + * This should be left at zero for this class, but subclasses + * may want to set this to other values. + */ + public $leading_context_lines = 0; + + /** + * Number of trailing context "lines" to preserve. + * + * This should be left at zero for this class, but subclasses + * may want to set this to other values. + */ + public $trailing_context_lines = 0; + + /** + * Format a diff. + * + * @param $diff object A Diff object. + * @return string The formatted output. + */ + public function format($diff) + { + $fname = 'DiffFormatter::format'; + //wfProfileIn( $fname ); + + $xi = $yi = 1; + $block = false; + $context = array(); + + $nlead = $this->leading_context_lines; + $ntrail = $this->trailing_context_lines; + + $this->_start_diff(); + + foreach ($diff->edits as $edit) { + if ($edit->type == 'copy') { + if (is_array($block)) { + if (sizeof($edit->orig) <= $nlead + $ntrail) { + $block[] = $edit; + } else { + if ($ntrail) { + $context = array_slice($edit->orig, 0, $ntrail); + $block[] = new _DiffOp_Copy($context); + } + $this->_block( + $x0, + $ntrail + $xi - $x0, + $y0, + $ntrail + $yi - $y0, + $block + ); + $block = false; + } + } + $context = $edit->orig; + } else { + if (!is_array($block)) { + $context = array_slice($context, sizeof($context) - $nlead); + $x0 = $xi - sizeof($context); + $y0 = $yi - sizeof($context); + $block = array(); + if ($context) { + $block[] = new _DiffOp_Copy($context); + } + } + $block[] = $edit; + } + + if ($edit->orig) { + $xi += sizeof($edit->orig); + } + if ($edit->closing) { + $yi += sizeof($edit->closing); + } + } + + if (is_array($block)) { + $this->_block( + $x0, + $xi - $x0, + $y0, + $yi - $y0, + $block + ); + } + + $end = $this->_end_diff(); + //wfProfileOut( $fname ); + return $end; + } + + public function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) + { + $fname = 'DiffFormatter::_block'; + //wfProfileIn( $fname ); + $this->_start_block($this->_block_header($xbeg, $xlen, $ybeg, $ylen)); + foreach ($edits as $edit) { + if ($edit->type == 'copy') { + $this->_context($edit->orig); + } elseif ($edit->type == 'add') { + $this->_added($edit->closing); + } elseif ($edit->type == 'delete') { + $this->_deleted($edit->orig); + } elseif ($edit->type == 'change') { + $this->_changed($edit->orig, $edit->closing); + } else { + trigger_error('Unknown edit type', E_USER_ERROR); + } + } + $this->_end_block(); + //wfProfileOut( $fname ); + } + + public function _start_diff() + { + ob_start(); + } + + public function _end_diff() + { + $val = ob_get_contents(); + ob_end_clean(); + return $val; + } + + public function _block_header($xbeg, $xlen, $ybeg, $ylen) + { + if ($xlen > 1) { + $xbeg .= "," . ($xbeg + $xlen - 1); + } + if ($ylen > 1) { + $ybeg .= "," . ($ybeg + $ylen - 1); + } + + return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg; + } + + public function _start_block($header) + { + echo $header; + } + + public function _end_block() + { + } + + public function _lines($lines, $prefix = ' ') + { + foreach ($lines as $line) { + echo "$prefix $line\n"; + } + } + + public function _context($lines) + { + $this->_lines($lines); + } + + public function _added($lines) + { + $this->_lines($lines, '>'); + } + public function _deleted($lines) + { + $this->_lines($lines, '<'); + } + + public function _changed($orig, $closing) + { + $this->_deleted($orig); + echo "---\n"; + $this->_added($closing); + } } @@ -1568,60 +1712,70 @@ define('NBSP', ' '); // iso-8859-x non-breaking space. * @private * @addtogroup DifferenceEngine */ -class _HWLDF_WordAccumulator { - function __construct () { - $this->_lines = array(); - $this->_line = ''; - $this->_group = ''; - $this->_tag = ''; - } - - function _flushGroup ($new_tag) { - if ($this->_group !== '') { - if ($this->_tag == 'ins') - $this->_line .= '[ilDiffInsStart]' . - htmlspecialchars ( $this->_group ) . '[ilDiffInsEnd]'; - elseif ($this->_tag == 'del') - $this->_line .= '[ilDiffDelStart]' . - htmlspecialchars ( $this->_group ) . '[ilDiffDelEnd]'; - else - $this->_line .= htmlspecialchars ( $this->_group ); - } - $this->_group = ''; - $this->_tag = $new_tag; - } - - function _flushLine ($new_tag) { - $this->_flushGroup($new_tag); - if ($this->_line != '') - array_push ( $this->_lines, $this->_line ); - else - # make empty lines visible by inserting an NBSP - array_push ( $this->_lines, NBSP ); - $this->_line = ''; - } - - function addWords ($words, $tag = '') { - if ($tag != $this->_tag) - $this->_flushGroup($tag); - - foreach ($words as $word) { - // new-line should only come as first char of word. - if ($word == '') - continue; - if ($word[0] == "\n") { - $this->_flushLine($tag); - $word = substr($word, 1); - } - assert(!strstr($word, "\n")); - $this->_group .= $word; - } - } - - function getLines() { - $this->_flushLine('~done'); - return $this->_lines; - } +class _HWLDF_WordAccumulator +{ + public function __construct() + { + $this->_lines = array(); + $this->_line = ''; + $this->_group = ''; + $this->_tag = ''; + } + + public function _flushGroup($new_tag) + { + if ($this->_group !== '') { + if ($this->_tag == 'ins') { + $this->_line .= '[ilDiffInsStart]' . + htmlspecialchars($this->_group) . '[ilDiffInsEnd]'; + } elseif ($this->_tag == 'del') { + $this->_line .= '[ilDiffDelStart]' . + htmlspecialchars($this->_group) . '[ilDiffDelEnd]'; + } else { + $this->_line .= htmlspecialchars($this->_group); + } + } + $this->_group = ''; + $this->_tag = $new_tag; + } + + public function _flushLine($new_tag) + { + $this->_flushGroup($new_tag); + if ($this->_line != '') { + array_push($this->_lines, $this->_line); + } else { + # make empty lines visible by inserting an NBSP + array_push($this->_lines, NBSP); + } + $this->_line = ''; + } + + public function addWords($words, $tag = '') + { + if ($tag != $this->_tag) { + $this->_flushGroup($tag); + } + + foreach ($words as $word) { + // new-line should only come as first char of word. + if ($word == '') { + continue; + } + if ($word[0] == "\n") { + $this->_flushLine($tag); + $word = substr($word, 1); + } + assert(!strstr($word, "\n")); + $this->_group .= $word; + } + } + + public function getLines() + { + $this->_flushLine('~done'); + return $this->_lines; + } } /** @@ -1631,84 +1785,96 @@ class _HWLDF_WordAccumulator { */ class WordLevelDiff extends MappedDiff { - const MAX_LINE_LENGTH = 10000; - - function __construct ($orig_lines, $closing_lines) { - $fname = 'WordLevelDiff::WordLevelDiff'; - //wfProfileIn( $fname ); - - list ($orig_words, $orig_stripped) = $this->_split($orig_lines); - list ($closing_words, $closing_stripped) = $this->_split($closing_lines); - - parent::__construct($orig_words, $closing_words, - $orig_stripped, $closing_stripped); - //wfProfileOut( $fname ); - } - - function _split($lines) { - $fname = 'WordLevelDiff::_split'; - //wfProfileIn( $fname ); - - $words = array(); - $stripped = array(); - $first = true; - foreach ( $lines as $line ) { - # If the line is too long, just pretend the entire line is one big word - # This prevents resource exhaustion problems - if ( $first ) { - $first = false; - } else { - $words[] = "\n"; - $stripped[] = "\n"; - } - if ( strlen( $line ) > self::MAX_LINE_LENGTH ) { - $words[] = $line; - $stripped[] = $line; - } else { - $m = array(); - if (preg_match_all('/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs', - $line, $m)) - { - $words = array_merge( $words, $m[0] ); - $stripped = array_merge( $stripped, $m[1] ); - } - } - } - //wfProfileOut( $fname ); - return array($words, $stripped); - } - - function orig () { - $fname = 'WordLevelDiff::orig'; - //wfProfileIn( $fname ); - $orig = new _HWLDF_WordAccumulator; - - foreach ($this->edits as $edit) { - if ($edit->type == 'copy') - $orig->addWords($edit->orig); - elseif ($edit->orig) - $orig->addWords($edit->orig, 'del'); - } - $lines = $orig->getLines(); - //wfProfileOut( $fname ); - return $lines; - } - - function closing () { - $fname = 'WordLevelDiff::closing'; - //wfProfileIn( $fname ); - $closing = new _HWLDF_WordAccumulator; - - foreach ($this->edits as $edit) { - if ($edit->type == 'copy') - $closing->addWords($edit->closing); - elseif ($edit->closing) - $closing->addWords($edit->closing, 'ins'); - } - $lines = $closing->getLines(); - //wfProfileOut( $fname ); - return $lines; - } + const MAX_LINE_LENGTH = 10000; + + public function __construct($orig_lines, $closing_lines) + { + $fname = 'WordLevelDiff::WordLevelDiff'; + //wfProfileIn( $fname ); + + list($orig_words, $orig_stripped) = $this->_split($orig_lines); + list($closing_words, $closing_stripped) = $this->_split($closing_lines); + + parent::__construct( + $orig_words, + $closing_words, + $orig_stripped, + $closing_stripped + ); + //wfProfileOut( $fname ); + } + + public function _split($lines) + { + $fname = 'WordLevelDiff::_split'; + //wfProfileIn( $fname ); + + $words = array(); + $stripped = array(); + $first = true; + foreach ($lines as $line) { + # If the line is too long, just pretend the entire line is one big word + # This prevents resource exhaustion problems + if ($first) { + $first = false; + } else { + $words[] = "\n"; + $stripped[] = "\n"; + } + if (strlen($line) > self::MAX_LINE_LENGTH) { + $words[] = $line; + $stripped[] = $line; + } else { + $m = array(); + if (preg_match_all( + '/ ( [^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | . ) (?: (?!< \n) [^\S\n])? /xs', + $line, + $m + )) { + $words = array_merge($words, $m[0]); + $stripped = array_merge($stripped, $m[1]); + } + } + } + //wfProfileOut( $fname ); + return array($words, $stripped); + } + + public function orig() + { + $fname = 'WordLevelDiff::orig'; + //wfProfileIn( $fname ); + $orig = new _HWLDF_WordAccumulator; + + foreach ($this->edits as $edit) { + if ($edit->type == 'copy') { + $orig->addWords($edit->orig); + } elseif ($edit->orig) { + $orig->addWords($edit->orig, 'del'); + } + } + $lines = $orig->getLines(); + //wfProfileOut( $fname ); + return $lines; + } + + public function closing() + { + $fname = 'WordLevelDiff::closing'; + //wfProfileIn( $fname ); + $closing = new _HWLDF_WordAccumulator; + + foreach ($this->edits as $edit) { + if ($edit->type == 'copy') { + $closing->addWords($edit->closing); + } elseif ($edit->closing) { + $closing->addWords($edit->closing, 'ins'); + } + } + $lines = $closing->getLines(); + //wfProfileOut( $fname ); + return $lines; + } } /** @@ -1719,90 +1885,101 @@ class WordLevelDiff extends MappedDiff */ class TableDiffFormatter extends DiffFormatter { - function __construct() { - $this->leading_context_lines = 2; - $this->trailing_context_lines = 2; - } - - function _block_header( $xbeg, $xlen, $ybeg, $ylen ) { - $r = '\n" . - '\n"; - return $r; - } - - function _start_block( $header ) { - echo $header; - } - - function _end_block() { - } - - function _lines( $lines, $prefix=' ', $color='white' ) { - } - - # HTML-escape parameter before calling this - function addedLine( $line ) { - return "+{$line}"; - } - - # HTML-escape parameter before calling this - function deletedLine( $line ) { - return "-{$line}"; - } - - # HTML-escape parameter before calling this - function contextLine( $line ) { - return " {$line}"; - } - - function emptyLine() { - return ' '; - } - - function _added( $lines ) { - foreach ($lines as $line) { - echo '' . $this->emptyLine() . - $this->addedLine( htmlspecialchars ( $line ) ) . "\n"; - } - } - - function _deleted($lines) { - foreach ($lines as $line) { - echo '' . $this->deletedLine( htmlspecialchars ( $line ) ) . - $this->emptyLine() . "\n"; - } - } - - function _context( $lines ) { - foreach ($lines as $line) { - echo '' . - $this->contextLine( htmlspecialchars ( $line ) ) . - $this->contextLine( htmlspecialchars ( $line ) ) . "\n"; - } - } - - function _changed( $orig, $closing ) { - $fname = 'TableDiffFormatter::_changed'; - //wfProfileIn( $fname ); - - $diff = new WordLevelDiff( $orig, $closing ); - $del = $diff->orig(); - $add = $diff->closing(); - - # Notice that WordLevelDiff returns HTML-escaped output. - # Hence, we will be calling addedLine/deletedLine without HTML-escaping. - - while ( $line = array_shift( $del ) ) { - $aline = array_shift( $add ); - echo '' . $this->deletedLine( $line ) . - $this->addedLine( $aline ) . "\n"; - } - foreach ($add as $line) { # If any leftovers - echo '' . $this->emptyLine() . - $this->addedLine( $line ) . "\n"; - } - //wfProfileOut( $fname ); - } + public function __construct() + { + $this->leading_context_lines = 2; + $this->trailing_context_lines = 2; + } + + public function _block_header($xbeg, $xlen, $ybeg, $ylen) + { + $r = '\n" . + '\n"; + return $r; + } + + public function _start_block($header) + { + echo $header; + } + + public function _end_block() + { + } + + public function _lines($lines, $prefix=' ', $color='white') + { + } + + # HTML-escape parameter before calling this + public function addedLine($line) + { + return "+{$line}"; + } + + # HTML-escape parameter before calling this + public function deletedLine($line) + { + return "-{$line}"; + } + + # HTML-escape parameter before calling this + public function contextLine($line) + { + return " {$line}"; + } + + public function emptyLine() + { + return ' '; + } + + public function _added($lines) + { + foreach ($lines as $line) { + echo '' . $this->emptyLine() . + $this->addedLine(htmlspecialchars($line)) . "\n"; + } + } + + public function _deleted($lines) + { + foreach ($lines as $line) { + echo '' . $this->deletedLine(htmlspecialchars($line)) . + $this->emptyLine() . "\n"; + } + } + + public function _context($lines) + { + foreach ($lines as $line) { + echo '' . + $this->contextLine(htmlspecialchars($line)) . + $this->contextLine(htmlspecialchars($line)) . "\n"; + } + } + + public function _changed($orig, $closing) + { + $fname = 'TableDiffFormatter::_changed'; + //wfProfileIn( $fname ); + + $diff = new WordLevelDiff($orig, $closing); + $del = $diff->orig(); + $add = $diff->closing(); + + # Notice that WordLevelDiff returns HTML-escaped output. + # Hence, we will be calling addedLine/deletedLine without HTML-escaping. + + while ($line = array_shift($del)) { + $aline = array_shift($add); + echo '' . $this->deletedLine($line) . + $this->addedLine($aline) . "\n"; + } + foreach ($add as $line) { # If any leftovers + echo '' . $this->emptyLine() . + $this->addedLine($line) . "\n"; + } + //wfProfileOut( $fname ); + } } - -?> diff --git a/Services/Chart/classes/class.ilChart.php b/Services/Chart/classes/class.ilChart.php index f4849921384089f5422ff44eb283e8b73bfd1b34..a80c5b3beb1d9319194f75f5ad007e81cd234b60 100644 --- a/Services/Chart/classes/class.ilChart.php +++ b/Services/Chart/classes/class.ilChart.php @@ -12,414 +12,379 @@ include_once "Services/Chart/classes/class.ilChartLegend.php"; */ abstract class ilChart { - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilTemplate + */ + protected $tpl; - protected $id; // [string] - protected $width; // [string] - protected $height; // [string] - protected $data; // [array] - protected $legend; // [ilChartLegend] - protected $shadow; // [int] - protected $colors; // [array] - protected $auto_resize; // [bool] - protected $stacked; // [bool] + protected $id; // [string] + protected $width; // [string] + protected $height; // [string] + protected $data; // [array] + protected $legend; // [ilChartLegend] + protected $shadow; // [int] + protected $colors; // [array] + protected $auto_resize; // [bool] + protected $stacked; // [bool] - const TYPE_GRID = 1; - const TYPE_PIE = 2; - const TYPE_SPIDER = 3; + const TYPE_GRID = 1; + const TYPE_PIE = 2; + const TYPE_SPIDER = 3; - /** - * Constructor - * - * @param string $a_id - */ - protected function __construct($a_id) - { - global $DIC; + /** + * Constructor + * + * @param string $a_id + */ + protected function __construct($a_id) + { + global $DIC; - $this->tpl = $DIC["tpl"]; - $this->id = $a_id; - $this->data = array(); - - $this->setShadow(2); - } + $this->tpl = $DIC["tpl"]; + $this->id = $a_id; + $this->data = array(); + + $this->setShadow(2); + } - /** - * Get type instance - * - * @param int $a_type - * @param string $a_id - * @return ilChart - */ - public static function getInstanceByType($a_type, $a_id) - { - switch($a_type) - { - case self::TYPE_GRID: - include_once "Services/Chart/classes/class.ilChartGrid.php"; - return new ilChartGrid($a_id); - - case self::TYPE_PIE: - include_once "Services/Chart/classes/class.ilChartPie.php"; - return new ilChartPie($a_id); - - case self::TYPE_SPIDER: - include_once "Services/Chart/classes/class.ilChartSpider.php"; - return new ilChartSpider($a_id); - } - } - - /** - * Get data series instance - * - * @return ilChartData - */ - abstract public function getDataInstance($a_type = null); - - /** - * Validate data series - * - * @return bool - */ - abstract protected function isValidDataType(ilChartData $a_series); - - /** - * Basic validation - * - * @return bool - */ - protected function isValid() - { - if(sizeof($this->data)) - { - return true; - } - return false; - } + /** + * Get type instance + * + * @param int $a_type + * @param string $a_id + * @return ilChart + */ + public static function getInstanceByType($a_type, $a_id) + { + switch ($a_type) { + case self::TYPE_GRID: + include_once "Services/Chart/classes/class.ilChartGrid.php"; + return new ilChartGrid($a_id); + + case self::TYPE_PIE: + include_once "Services/Chart/classes/class.ilChartPie.php"; + return new ilChartPie($a_id); + + case self::TYPE_SPIDER: + include_once "Services/Chart/classes/class.ilChartSpider.php"; + return new ilChartSpider($a_id); + } + } + + /** + * Get data series instance + * + * @return ilChartData + */ + abstract public function getDataInstance($a_type = null); + + /** + * Validate data series + * + * @return bool + */ + abstract protected function isValidDataType(ilChartData $a_series); + + /** + * Basic validation + * + * @return bool + */ + protected function isValid() + { + if (sizeof($this->data)) { + return true; + } + return false; + } - /** - * Set chart size - * - * @param int $a_x - * @param int $a_y - */ - public function setSize($a_x, $a_y) - { - $this->width = $a_x; - $this->height = $a_y; - } + /** + * Set chart size + * + * @param int $a_x + * @param int $a_y + */ + public function setSize($a_x, $a_y) + { + $this->width = $a_x; + $this->height = $a_y; + } - /** - * Add data series - * - * @param ilChartData $a_series - * @param mixed $a_id - * @return mixed index - */ - public function addData(ilChartData $a_series, $a_idx = null) - { - if($this->isValidDataType($a_series)) - { - if($a_idx === null) - { - $a_idx = sizeof($this->data); - } - $this->data[$a_idx] = $a_series; - return $a_idx; - } - } + /** + * Add data series + * + * @param ilChartData $a_series + * @param mixed $a_id + * @return mixed index + */ + public function addData(ilChartData $a_series, $a_idx = null) + { + if ($this->isValidDataType($a_series)) { + if ($a_idx === null) { + $a_idx = sizeof($this->data); + } + $this->data[$a_idx] = $a_series; + return $a_idx; + } + } - /** - * Set chart legend - * - * @param ilChartLegend $a_legend - */ - public function setLegend(ilChartLegend $a_legend) - { - $this->legend = $a_legend; - } - - /** - * Set colors - * - * @param array $a_values - */ - public function setColors($a_values) - { - foreach($a_values as $color) - { - if(self::isValidColor($color)) - { - $this->colors[] = $color; - } - } - } + /** + * Set chart legend + * + * @param ilChartLegend $a_legend + */ + public function setLegend(ilChartLegend $a_legend) + { + $this->legend = $a_legend; + } + + /** + * Set colors + * + * @param array $a_values + */ + public function setColors($a_values) + { + foreach ($a_values as $color) { + if (self::isValidColor($color)) { + $this->colors[] = $color; + } + } + } - /** - * Get colors - * - * @return array - */ - public function getColors() - { - return $this->colors; - } + /** + * Get colors + * + * @return array + */ + public function getColors() + { + return $this->colors; + } - /** - * Validate html color code - * - * @param string $a_value - * @return bool - */ - public static function isValidColor($a_value) - { - if(preg_match("/^#[0-9a-f]{3}$/i", $a_value, $match)) - { - return true; - } - else if(preg_match("/^#[0-9a-f]{6}$/i", $a_value, $match)) - { - return true; - } - } + /** + * Validate html color code + * + * @param string $a_value + * @return bool + */ + public static function isValidColor($a_value) + { + if (preg_match("/^#[0-9a-f]{3}$/i", $a_value, $match)) { + return true; + } elseif (preg_match("/^#[0-9a-f]{6}$/i", $a_value, $match)) { + return true; + } + } - /** - * Render html color code - * - * @param string $a_value - * @param float $a_opacity - * @return string - */ - public static function renderColor($a_value, $a_opacity = 1) - { - if(self::isValidColor($a_value)) - { - if(strlen($a_value) == 4) - { - return "rgba(".hexdec($a_value[1].$a_value[1]).", ". - hexdec($a_value[2].$a_value[2]).", ". - hexdec($a_value[3].$a_value[3]).", ".$a_opacity.")"; - } - else - { - return "rgba(".hexdec($a_value[1].$a_value[2]).", ". - hexdec($a_value[3].$a_value[4]).", ". - hexdec($a_value[5].$a_value[6]).", ".$a_opacity.")"; - } - } - } + /** + * Render html color code + * + * @param string $a_value + * @param float $a_opacity + * @return string + */ + public static function renderColor($a_value, $a_opacity = 1) + { + if (self::isValidColor($a_value)) { + if (strlen($a_value) == 4) { + return "rgba(" . hexdec($a_value[1] . $a_value[1]) . ", " . + hexdec($a_value[2] . $a_value[2]) . ", " . + hexdec($a_value[3] . $a_value[3]) . ", " . $a_opacity . ")"; + } else { + return "rgba(" . hexdec($a_value[1] . $a_value[2]) . ", " . + hexdec($a_value[3] . $a_value[4]) . ", " . + hexdec($a_value[5] . $a_value[6]) . ", " . $a_opacity . ")"; + } + } + } - /** - * Set shadow - * - * @param int $a_value - */ - public function setShadow($a_value) - { - $this->shadow = (int)$a_value; - } + /** + * Set shadow + * + * @param int $a_value + */ + public function setShadow($a_value) + { + $this->shadow = (int) $a_value; + } - /** - * Get shadow - * - * @return int - */ - public function getShadow() - { - return $this->shadow; - } - - /** - * Toggle auto-resizing on window resize/redraw - * - * @param bool $a_value - */ - public function setAutoResize($a_value) - { - $this->auto_resize = (bool)$a_value; - } - - /** - * Toggle stacking - * - * @param bool $a_value - */ - public function setStacked($a_value) - { - $this->stacked = (bool)$a_value; - } - - /** - * Init JS script files - */ - protected function initJS() - { - $tpl = $this->tpl; - - include_once "Services/jQuery/classes/class.iljQueryUtil.php"; - iljQueryUtil::initjQuery(); - - $tpl->addJavascript("Services/Chart/js/flot/excanvas.min.js"); - $tpl->addJavascript("Services/Chart/js/flot/jquery.flot.min.js"); - - if((bool)$this->auto_resize) - { - // #13108 - $tpl->addJavascript("Services/Chart/js/flot/jquery.flot.resize.min.js"); - } - - if((bool)$this->stacked) - { - $tpl->addJavascript("Services/Chart/js/flot/jquery.flot.stack.min.js"); - } - - $this->addCustomJS(); - } - - /** - * Add type-specific JS script - */ - protected function addCustomJS() - { - - } - - /** - * Convert (global) properties to flot config - * - * @param object $a_options - */ - public function parseGlobalOptions(stdClass $a_options) - { - - } - - /** - * Render - */ - public function getHTML() - { - if(!$this->isValid()) - { - return; - } - - $this->initJS(); - - $chart = new ilTemplate("tpl.grid.html", true, true, "Services/Chart"); - $chart->setVariable("ID", $this->id); - - if($this->width) - { - if(is_numeric($this->width)) - { - $chart->setVariable("WIDTH", "width:".$this->width."px;"); - } - else - { - $chart->setVariable("WIDTH", "width:".$this->width.";"); - } - } - if($this->height) - { - if(is_numeric($this->height)) - { - $chart->setVariable("HEIGHT", "height:".$this->height."px;"); - } - else - { - $chart->setVariable("HEIGHT", "height:".$this->height.";"); - } - } - - - // (series) data - - $json_series = array(); - foreach($this->data as $series) - { - $series->parseData($json_series); - } - $chart->setVariable("SERIES", json_encode($json_series)); - - - // global options - - $json_options = new stdClass(); - $json_options->series = new stdClass(); - $json_options->series->shadowSize = (int)$this->getShadow(); - $json_options->series->lines = new stdClass(); - $json_options->series->lines->show = false; - $json_options->series->stack = (bool)$this->stacked; - - foreach($this->data as $series) - { - $series->parseGlobalOptions($json_options, $this); - } - - $this->parseGlobalOptions($json_options); - - $colors = $this->getColors(); - if($colors) - { - $json_options->colors = array(); - foreach($colors as $color) - { - $json_options->colors[] = self::renderColor($color); - } - } + /** + * Get shadow + * + * @return int + */ + public function getShadow() + { + return $this->shadow; + } + + /** + * Toggle auto-resizing on window resize/redraw + * + * @param bool $a_value + */ + public function setAutoResize($a_value) + { + $this->auto_resize = (bool) $a_value; + } + + /** + * Toggle stacking + * + * @param bool $a_value + */ + public function setStacked($a_value) + { + $this->stacked = (bool) $a_value; + } + + /** + * Init JS script files + */ + protected function initJS() + { + $tpl = $this->tpl; + + include_once "Services/jQuery/classes/class.iljQueryUtil.php"; + iljQueryUtil::initjQuery(); + + $tpl->addJavascript("Services/Chart/js/flot/excanvas.min.js"); + $tpl->addJavascript("Services/Chart/js/flot/jquery.flot.min.js"); + + if ((bool) $this->auto_resize) { + // #13108 + $tpl->addJavascript("Services/Chart/js/flot/jquery.flot.resize.min.js"); + } + + if ((bool) $this->stacked) { + $tpl->addJavascript("Services/Chart/js/flot/jquery.flot.stack.min.js"); + } + + $this->addCustomJS(); + } + + /** + * Add type-specific JS script + */ + protected function addCustomJS() + { + } + + /** + * Convert (global) properties to flot config + * + * @param object $a_options + */ + public function parseGlobalOptions(stdClass $a_options) + { + } + + /** + * Render + */ + public function getHTML() + { + if (!$this->isValid()) { + return; + } + + $this->initJS(); + + $chart = new ilTemplate("tpl.grid.html", true, true, "Services/Chart"); + $chart->setVariable("ID", $this->id); + + if ($this->width) { + if (is_numeric($this->width)) { + $chart->setVariable("WIDTH", "width:" . $this->width . "px;"); + } else { + $chart->setVariable("WIDTH", "width:" . $this->width . ";"); + } + } + if ($this->height) { + if (is_numeric($this->height)) { + $chart->setVariable("HEIGHT", "height:" . $this->height . "px;"); + } else { + $chart->setVariable("HEIGHT", "height:" . $this->height . ";"); + } + } + + + // (series) data + + $json_series = array(); + foreach ($this->data as $series) { + $series->parseData($json_series); + } + $chart->setVariable("SERIES", json_encode($json_series)); + + + // global options + + $json_options = new stdClass(); + $json_options->series = new stdClass(); + $json_options->series->shadowSize = (int) $this->getShadow(); + $json_options->series->lines = new stdClass(); + $json_options->series->lines->show = false; + $json_options->series->stack = (bool) $this->stacked; + + foreach ($this->data as $series) { + $series->parseGlobalOptions($json_options, $this); + } + + $this->parseGlobalOptions($json_options); + + $colors = $this->getColors(); + if ($colors) { + $json_options->colors = array(); + foreach ($colors as $color) { + $json_options->colors[] = self::renderColor($color); + } + } - // legend - $json_options->legend = new stdClass(); - if(!$this->legend) - { - $json_options->legend->show = false; - } - else - { - $this->legend->parseOptions($json_options->legend); - } - - $chart->setVariable("OPTIONS", json_encode($json_options)); - - $ret = $chart->get(); - return $ret; - } - - /* - ilChart - ->setColors - ->setHover() [tooltip?] - [->setClick] - ->setZooming - ->setPanning - ->setTooltip - ->addData[Series] - - labels - - type - - pie: nur 1x - - bar, lines, points, steps, stacked? - - highlight?! - => min/max, transmission type (google api) + // legend + $json_options->legend = new stdClass(); + if (!$this->legend) { + $json_options->legend->show = false; + } else { + $this->legend->parseOptions($json_options->legend); + } + + $chart->setVariable("OPTIONS", json_encode($json_options)); + + $ret = $chart->get(); + return $ret; + } + + /* + ilChart + ->setColors + ->setHover() [tooltip?] + [->setClick] + ->setZooming + ->setPanning + ->setTooltip + ->addData[Series] + - labels + - type + - pie: nur 1x + - bar, lines, points, steps, stacked? + - highlight?! + => min/max, transmission type (google api) - grid-based - ->setGrid - ->setTicks(color, size, decimals, length) - ->addAxisX (multiple, Zero) [id, mode, position, color, label] - ->addAxisY (multiple?) [id, mode, position, color, label] - ->setBackgroundFill(opacity, color/gradient) - ->setThreshold(int/float) - ->setToggles(bool) + grid-based + ->setGrid + ->setTicks(color, size, decimals, length) + ->addAxisX (multiple, Zero) [id, mode, position, color, label] + ->addAxisY (multiple?) [id, mode, position, color, label] + ->setBackgroundFill(opacity, color/gradient) + ->setThreshold(int/float) + ->setToggles(bool) - pie - ->setCollapse(int/float, color, label) - ->setRotation(int angle?) - ->setRadius(inner, outer) - */ + pie + ->setCollapse(int/float, color, label) + ->setRotation(int angle?) + ->setRadius(inner, outer) + */ } - -?> \ No newline at end of file diff --git a/Services/Chart/classes/class.ilChartData.php b/Services/Chart/classes/class.ilChartData.php index 0f4c2cb55b9a17fca07dd939af367d00e73a7919..703a556951e5fdc7e23f00c71b745ef9729214fe 100644 --- a/Services/Chart/classes/class.ilChartData.php +++ b/Services/Chart/classes/class.ilChartData.php @@ -10,170 +10,159 @@ */ abstract class ilChartData { - protected $type; // [string] - protected $label; // [string] - protected $data; // [array] - protected $fill; // [float] - protected $fill_color; // [color/gradient] - protected $hidden; // [bool] + protected $type; // [string] + protected $label; // [string] + protected $data; // [array] + protected $fill; // [float] + protected $fill_color; // [color/gradient] + protected $hidden; // [bool] - /** - * Get series type - * - * @return string - */ - abstract protected function getTypeString(); - - /** - * Set hidden - * - * @param bool $a_value - */ - public function setHidden($a_value) - { - $this->hidden = (bool)$a_value; - } + /** + * Get series type + * + * @return string + */ + abstract protected function getTypeString(); + + /** + * Set hidden + * + * @param bool $a_value + */ + public function setHidden($a_value) + { + $this->hidden = (bool) $a_value; + } - /** - * Is hidden? - * - * @return bool - */ - public function isHidden() - { - return $this->hidden; - } + /** + * Is hidden? + * + * @return bool + */ + public function isHidden() + { + return $this->hidden; + } - /** - * Set label - * - * @param string $a_value - */ - public function setLabel($a_value) - { - $this->label = (string)$a_value; - } + /** + * Set label + * + * @param string $a_value + */ + public function setLabel($a_value) + { + $this->label = (string) $a_value; + } - /** - * Get label - * - * @return string - */ - public function getLabel() - { - return $this->label; - } + /** + * Get label + * + * @return string + */ + public function getLabel() + { + return $this->label; + } - /** - * Set data - * - * @param float $a_x - * @param float $a_y - */ - public function addPoint($a_x, $a_y = null) - { - if($a_y !== null) - { - $this->data[] = array($a_x, $a_y); - } - else - { - $this->data[] = $a_x; - } - } + /** + * Set data + * + * @param float $a_x + * @param float $a_y + */ + public function addPoint($a_x, $a_y = null) + { + if ($a_y !== null) { + $this->data[] = array($a_x, $a_y); + } else { + $this->data[] = $a_x; + } + } - /** - * Get data - * - * @return array - */ - public function getData() - { - return $this->data; - } + /** + * Get data + * + * @return array + */ + public function getData() + { + return $this->data; + } - /** - * Set fill - * - * @param float $a_value - * @param string $a_color - */ - public function setFill($a_value, $a_color = null) - { - $this->fill = $a_value; - if(ilChart::isValidColor($a_color)) - { - $this->fill_color = $a_color; - } - } + /** + * Set fill + * + * @param float $a_value + * @param string $a_color + */ + public function setFill($a_value, $a_color = null) + { + $this->fill = $a_value; + if (ilChart::isValidColor($a_color)) { + $this->fill_color = $a_color; + } + } - /** - * Get fill - * - * @return array (fill, color) - */ - public function getFill() - { - return array("fill"=>$this->fill, "color"=>$this->fill_color); - } - - /** - * Convert data options to flot config - * - * @param array $a_options - * @param ilChart $a_chart - */ - protected function parseDataOptions(array &$a_options) - { - - } - - /** - * Convert data to flot config - * - * @param array $a_data - * @return object - */ - public function parseData(array &$a_data) - { - $series = new stdClass(); - $series->label = str_replace("\"", "\\\"", $this->getLabel()); - - $series->data = array(); - foreach($this->getData() as $point) - { - $series->data[] = array($point[0], $point[1]); - } - - $options = array("show"=>($this->isHidden() ? false : true)); - - $fill = $this->getFill(); - if($fill["fill"]) - { - $options["fill"] = $fill["fill"]; - if($fill["color"]) - { - $options["fillColor"] = ilChart::renderColor($fill["color"], $fill["fill"]); - } - } - - $this->parseDataOptions($options); - - $series->{$this->getTypeString()} = $options; - - $a_data[] = $series; - } - - /** - * Convert (global) properties to flot config - * - * @param object $a_options - * @param ilChart $a_chart - */ - public function parseGlobalOptions(stdClass $a_options, ilChart $a_chart) - { - - } + /** + * Get fill + * + * @return array (fill, color) + */ + public function getFill() + { + return array("fill"=>$this->fill, "color"=>$this->fill_color); + } + + /** + * Convert data options to flot config + * + * @param array $a_options + * @param ilChart $a_chart + */ + protected function parseDataOptions(array &$a_options) + { + } + + /** + * Convert data to flot config + * + * @param array $a_data + * @return object + */ + public function parseData(array &$a_data) + { + $series = new stdClass(); + $series->label = str_replace("\"", "\\\"", $this->getLabel()); + + $series->data = array(); + foreach ($this->getData() as $point) { + $series->data[] = array($point[0], $point[1]); + } + + $options = array("show"=>($this->isHidden() ? false : true)); + + $fill = $this->getFill(); + if ($fill["fill"]) { + $options["fill"] = $fill["fill"]; + if ($fill["color"]) { + $options["fillColor"] = ilChart::renderColor($fill["color"], $fill["fill"]); + } + } + + $this->parseDataOptions($options); + + $series->{$this->getTypeString()} = $options; + + $a_data[] = $series; + } + + /** + * Convert (global) properties to flot config + * + * @param object $a_options + * @param ilChart $a_chart + */ + public function parseGlobalOptions(stdClass $a_options, ilChart $a_chart) + { + } } - -?> \ No newline at end of file diff --git a/Services/Chart/classes/class.ilChartDataBars.php b/Services/Chart/classes/class.ilChartDataBars.php index e9e5346308520ef4d125f63bf8487b5fbbe4c7ca..a6acaea486bb1ce9f45ecd8bf6cff21996fdaf8c 100644 --- a/Services/Chart/classes/class.ilChartDataBars.php +++ b/Services/Chart/classes/class.ilChartDataBars.php @@ -1,82 +1,76 @@ - - * @version $Id$ - * @ingroup ServicesChart - */ -class ilChartDataBars extends ilChartData -{ - protected $line_width; // [int] - protected $bar_width; // [float] bar - protected $bar_align; // [string] bar - protected $bar_horizontal; // [bool] bar - - protected function getTypeString() - { - return "bars"; - } - - /** - * Set line width - * - * @param int $a_value - */ - public function setLineWidth($a_value) - { - $this->line_width = (int)$a_value; - } - - /** - * Get line width - * - * @return int - */ - public function getLineWidth() - { - return $this->line_width; - } - - /** - * Set bar options - * - * @param float $a_width - * @param string $a_align - * @param bool $a_horizontal - */ - public function setBarOptions($a_width, $a_align = "center", $a_horizontal = false) - { - $this->bar_width = (float)str_replace(",", ".", $a_width); - if(in_array((string)$a_align, array("center", "left"))) - { - $this->bar_align = (string)$a_align; - } - $this->bar_horizontal = (bool)$a_horizontal; - } - - protected function parseDataOptions(array &$a_options) - { - $width = $this->getLineWidth(); - if($width !== null) - { - $a_options["lineWidth"] = $width; - } - - if($this->bar_width) - { - $a_options["barWidth"] = $this->bar_width; - $a_options["align"] = $this->bar_align; - if($this->bar_horizontal) - { - $a_options["horizontal"] = true; - } - } - } -} - -?> \ No newline at end of file + + * @version $Id$ + * @ingroup ServicesChart + */ +class ilChartDataBars extends ilChartData +{ + protected $line_width; // [int] + protected $bar_width; // [float] bar + protected $bar_align; // [string] bar + protected $bar_horizontal; // [bool] bar + + protected function getTypeString() + { + return "bars"; + } + + /** + * Set line width + * + * @param int $a_value + */ + public function setLineWidth($a_value) + { + $this->line_width = (int) $a_value; + } + + /** + * Get line width + * + * @return int + */ + public function getLineWidth() + { + return $this->line_width; + } + + /** + * Set bar options + * + * @param float $a_width + * @param string $a_align + * @param bool $a_horizontal + */ + public function setBarOptions($a_width, $a_align = "center", $a_horizontal = false) + { + $this->bar_width = (float) str_replace(",", ".", $a_width); + if (in_array((string) $a_align, array("center", "left"))) { + $this->bar_align = (string) $a_align; + } + $this->bar_horizontal = (bool) $a_horizontal; + } + + protected function parseDataOptions(array &$a_options) + { + $width = $this->getLineWidth(); + if ($width !== null) { + $a_options["lineWidth"] = $width; + } + + if ($this->bar_width) { + $a_options["barWidth"] = $this->bar_width; + $a_options["align"] = $this->bar_align; + if ($this->bar_horizontal) { + $a_options["horizontal"] = true; + } + } + } +} diff --git a/Services/Chart/classes/class.ilChartDataLines.php b/Services/Chart/classes/class.ilChartDataLines.php index 6045e65303bffcdb4cbb2860d8b9503145372452..f14b56adcbe100768c4a99182689058dfbd724cb 100644 --- a/Services/Chart/classes/class.ilChartDataLines.php +++ b/Services/Chart/classes/class.ilChartDataLines.php @@ -1,78 +1,74 @@ - - * @version $Id$ - * @ingroup ServicesChart - */ -class ilChartDataLines extends ilChartData -{ - protected $line_width; // [int] - protected $steps; // [bool] lines - - protected function getTypeString() - { - return "lines"; - } - - /** - * Set line width - * - * @param int $a_value - */ - public function setLineWidth($a_value) - { - $this->line_width = (int)$a_value; - } - - /** - * Get line width - * - * @return int - */ - public function getLineWidth() - { - return $this->line_width; - } - - /** - * Set line steps - * - * @param bool $a_value - */ - public function setLineSteps($a_value) - { - $this->steps = (bool)$a_value; - } - - /** - * Get line steps - * - * @return bool - */ - public function getLineSteps() - { - return $this->steps; - } - - protected function parseDataOptions(array &$a_options) - { - $width = $this->getLineWidth(); - if($width !== null) - { - $a_options["lineWidth"] = $width; - } - - if($this->getLineSteps()) - { - $a_options["steps"] = true; - } - } -} - -?> \ No newline at end of file + + * @version $Id$ + * @ingroup ServicesChart + */ +class ilChartDataLines extends ilChartData +{ + protected $line_width; // [int] + protected $steps; // [bool] lines + + protected function getTypeString() + { + return "lines"; + } + + /** + * Set line width + * + * @param int $a_value + */ + public function setLineWidth($a_value) + { + $this->line_width = (int) $a_value; + } + + /** + * Get line width + * + * @return int + */ + public function getLineWidth() + { + return $this->line_width; + } + + /** + * Set line steps + * + * @param bool $a_value + */ + public function setLineSteps($a_value) + { + $this->steps = (bool) $a_value; + } + + /** + * Get line steps + * + * @return bool + */ + public function getLineSteps() + { + return $this->steps; + } + + protected function parseDataOptions(array &$a_options) + { + $width = $this->getLineWidth(); + if ($width !== null) { + $a_options["lineWidth"] = $width; + } + + if ($this->getLineSteps()) { + $a_options["steps"] = true; + } + } +} diff --git a/Services/Chart/classes/class.ilChartDataPie.php b/Services/Chart/classes/class.ilChartDataPie.php index 6bf471b2878f494967da8af9bbe36fc1514f9f3d..fba3af6d1ecf35599bce0641d4c18913c8e24cae 100644 --- a/Services/Chart/classes/class.ilChartDataPie.php +++ b/Services/Chart/classes/class.ilChartDataPie.php @@ -1,128 +1,120 @@ - - * @version $Id$ - * @ingroup ServicesChart - */ -class ilChartDataPie extends ilChartData -{ - protected $line_width; // [int] - protected $label_radius; //mixed - - protected function getTypeString() - { - return "pie"; - } - - /** - * Set line width - * - * @param int $a_value - */ - public function setLineWidth($a_value) - { - $this->line_width = (int)$a_value; - } - - /** - * Get line width - * - * @return int - */ - public function getLineWidth() - { - return $this->line_width; - } - - /** - * - * Sets the radius at which to place the labels. If value is between 0 and 1 (inclusive) then - * it will use that as a percentage of the available space (size of the container), otherwise - * it will use the value as a direct pixel length. - * - * @param mixed $a_value - */ - public function setLabelRadius($a_value) - { - $this->label_radius = $a_value; - } - - /** - * @return mixed - */ - public function getLabelRadius() - { - return $this->label_radius; - } - - public function addPoint($a_value, $a_caption = null) - { - $this->data[] = array($a_value, $a_caption); - } - - public function parseData(array &$a_data) - { - foreach($this->data as $slice) - { - $series = new stdClass(); - $series->label = str_replace("\"", "\\\"", $slice[1]); - - // add percentage to legend - if(!$this->getLabelRadius()) - { - $series->label .= " (".$slice[0]."%)"; - } - - $series->data = $slice[0]; - - $options = array("show"=>($this->isHidden() ? false : true)); - - $series->{$this->getTypeString()} = $options; - - $a_data[] = $series; - } - } - - public function parseGlobalOptions(stdClass $a_options, ilChart $a_chart) - { - $a_options->series->pie = new stdClass(); - $a_options->series->pie->show = true; - - // fill vs. stroke - trying to normalize data attributes - - $fill = $this->getFill(); - $width = $this->getLineWidth(); - if($fill["fill"] || $width) - { - $a_options->series->pie->stroke = new stdClass; - if($width) - { - $a_options->series->pie->stroke->width = $width; - } - if($fill["color"]) - { - $a_options->series->pie->stroke->color = ilChart::renderColor($fill["color"], $fill["fill"]); - } - } - - $radius = $this->getLabelRadius(); - if ($radius) - { - $a_options->series->pie->label = new stdClass; - $a_options->series->pie->label->background = new stdClass; - $a_options->series->pie->radius = 1; - $a_options->series->pie->label->radius = $radius; - $a_options->series->pie->label->show = true; - $a_options->series->pie->label->background->color = "#444"; - $a_options->series->pie->label->background->opacity = 0.8; - } - } -} - -?> \ No newline at end of file + + * @version $Id$ + * @ingroup ServicesChart + */ +class ilChartDataPie extends ilChartData +{ + protected $line_width; // [int] + protected $label_radius; //mixed + + protected function getTypeString() + { + return "pie"; + } + + /** + * Set line width + * + * @param int $a_value + */ + public function setLineWidth($a_value) + { + $this->line_width = (int) $a_value; + } + + /** + * Get line width + * + * @return int + */ + public function getLineWidth() + { + return $this->line_width; + } + + /** + * + * Sets the radius at which to place the labels. If value is between 0 and 1 (inclusive) then + * it will use that as a percentage of the available space (size of the container), otherwise + * it will use the value as a direct pixel length. + * + * @param mixed $a_value + */ + public function setLabelRadius($a_value) + { + $this->label_radius = $a_value; + } + + /** + * @return mixed + */ + public function getLabelRadius() + { + return $this->label_radius; + } + + public function addPoint($a_value, $a_caption = null) + { + $this->data[] = array($a_value, $a_caption); + } + + public function parseData(array &$a_data) + { + foreach ($this->data as $slice) { + $series = new stdClass(); + $series->label = str_replace("\"", "\\\"", $slice[1]); + + // add percentage to legend + if (!$this->getLabelRadius()) { + $series->label .= " (" . $slice[0] . "%)"; + } + + $series->data = $slice[0]; + + $options = array("show"=>($this->isHidden() ? false : true)); + + $series->{$this->getTypeString()} = $options; + + $a_data[] = $series; + } + } + + public function parseGlobalOptions(stdClass $a_options, ilChart $a_chart) + { + $a_options->series->pie = new stdClass(); + $a_options->series->pie->show = true; + + // fill vs. stroke - trying to normalize data attributes + + $fill = $this->getFill(); + $width = $this->getLineWidth(); + if ($fill["fill"] || $width) { + $a_options->series->pie->stroke = new stdClass; + if ($width) { + $a_options->series->pie->stroke->width = $width; + } + if ($fill["color"]) { + $a_options->series->pie->stroke->color = ilChart::renderColor($fill["color"], $fill["fill"]); + } + } + + $radius = $this->getLabelRadius(); + if ($radius) { + $a_options->series->pie->label = new stdClass; + $a_options->series->pie->label->background = new stdClass; + $a_options->series->pie->radius = 1; + $a_options->series->pie->label->radius = $radius; + $a_options->series->pie->label->show = true; + $a_options->series->pie->label->background->color = "#444"; + $a_options->series->pie->label->background->opacity = 0.8; + } + } +} diff --git a/Services/Chart/classes/class.ilChartDataPoints.php b/Services/Chart/classes/class.ilChartDataPoints.php index 4851c8355b5fa91ad4891440b26c9df8603479c1..a336733d349b4ebcd3253728b1dfb7b9145f9405 100644 --- a/Services/Chart/classes/class.ilChartDataPoints.php +++ b/Services/Chart/classes/class.ilChartDataPoints.php @@ -1,79 +1,75 @@ - - * @version $Id$ - * @ingroup ServicesChart - */ -class ilChartDataPoints extends ilChartData -{ - protected $line_width; // [int] - protected $radius; // [int] points - - protected function getTypeString() - { - return "points"; - } - - /** - * Set line width - * - * @param int $a_value - */ - public function setLineWidth($a_value) - { - $this->line_width = (int)$a_value; - } - - /** - * Get line width - * - * @return int - */ - public function getLineWidth() - { - return $this->line_width; - } - - /** - * Set radius - * - * @param int $a_value - */ - public function setPointRadius($a_value) - { - $this->radius = (int)$a_value; - } - - /** - * Get radius - * - * @return int - */ - public function getPointRadius() - { - return $this->radius; - } - - protected function parseDataOptions(array &$a_options) - { - $width = $this->getLineWidth(); - if($width !== null) - { - $a_options["lineWidth"] = $width; - } - - $radius = $this->getPointRadius(); - if($radius !== null) - { - $a_options["radius"] = $radius; - } - } -} - -?> \ No newline at end of file + + * @version $Id$ + * @ingroup ServicesChart + */ +class ilChartDataPoints extends ilChartData +{ + protected $line_width; // [int] + protected $radius; // [int] points + + protected function getTypeString() + { + return "points"; + } + + /** + * Set line width + * + * @param int $a_value + */ + public function setLineWidth($a_value) + { + $this->line_width = (int) $a_value; + } + + /** + * Get line width + * + * @return int + */ + public function getLineWidth() + { + return $this->line_width; + } + + /** + * Set radius + * + * @param int $a_value + */ + public function setPointRadius($a_value) + { + $this->radius = (int) $a_value; + } + + /** + * Get radius + * + * @return int + */ + public function getPointRadius() + { + return $this->radius; + } + + protected function parseDataOptions(array &$a_options) + { + $width = $this->getLineWidth(); + if ($width !== null) { + $a_options["lineWidth"] = $width; + } + + $radius = $this->getPointRadius(); + if ($radius !== null) { + $a_options["radius"] = $radius; + } + } +} diff --git a/Services/Chart/classes/class.ilChartDataSpider.php b/Services/Chart/classes/class.ilChartDataSpider.php index 6692f8677c6d12de905275afcd047e37ee916219..6b4986643af80849409f2b2649854c4393aa5b99 100644 --- a/Services/Chart/classes/class.ilChartDataSpider.php +++ b/Services/Chart/classes/class.ilChartDataSpider.php @@ -1,97 +1,87 @@ - - * @version $Id$ - * @ingroup ServicesChart - */ -class ilChartDataSpider extends ilChartData -{ - protected function getTypeString() - { - return "spider"; - } - - public function parseData(array &$a_data) - { - parent::parseData($a_data); - - $fill = $this->getFill(); - if ($fill["color"] != "") - { - $a_data[count($a_data)-1]->color = ilChart::renderColor($fill["color"] , "0.5"); - } - } - - public function parseGlobalOptions(stdClass $a_options, ilChart $a_chart) - { - $spider = new stdClass(); - $spider->active = true; - - $spider->highlight = new stdClass(); - $spider->highlight->mode = "line"; - - - $spider->legs = new stdClass(); - $spider->legs->fillStyle = ilChart::renderColor("#000", "0.7"); - switch (count($a_chart->getLegLabels())) - { - case 4: - case 6: - $spider->legs->legStartAngle = 10; - break; - - default: - $spider->legs->legStartAngle = 0; - break; - } - - $spider->legs->data = array(); - - $max_str_len = 0; - foreach ($a_chart->getLegLabels() as $l) - { - $l = ilUtil::shortenText ($l, 80, true); - - $label = new stdClass(); - $label->label = $l; - $spider->legs->data[] = $label; - - $max_str_len = max($max_str_len, strlen($l)); - } - - // depending on caption length - if ($max_str_len > 60) - { - $font_size = 10; - } - else if ($max_str_len > 30) - { - $font_size = 12; - } - else - { - $font_size = 15; - } - $spider->legs->font = $font_size."px Arial"; - - $spider->spiderSize = 0.7; - $spider->lineWidth = 1; - $spider->pointSize = 0; - - $spider->connection = new StdClass(); - $spider->connection->width = 2; - - $spider->legMin = 0.0000001; - $spider->legMax = $a_chart->getYAxisMax(); - - $a_options->series->spider = $spider; - } -} - -?> \ No newline at end of file + + * @version $Id$ + * @ingroup ServicesChart + */ +class ilChartDataSpider extends ilChartData +{ + protected function getTypeString() + { + return "spider"; + } + + public function parseData(array &$a_data) + { + parent::parseData($a_data); + + $fill = $this->getFill(); + if ($fill["color"] != "") { + $a_data[count($a_data)-1]->color = ilChart::renderColor($fill["color"], "0.5"); + } + } + + public function parseGlobalOptions(stdClass $a_options, ilChart $a_chart) + { + $spider = new stdClass(); + $spider->active = true; + + $spider->highlight = new stdClass(); + $spider->highlight->mode = "line"; + + + $spider->legs = new stdClass(); + $spider->legs->fillStyle = ilChart::renderColor("#000", "0.7"); + switch (count($a_chart->getLegLabels())) { + case 4: + case 6: + $spider->legs->legStartAngle = 10; + break; + + default: + $spider->legs->legStartAngle = 0; + break; + } + + $spider->legs->data = array(); + + $max_str_len = 0; + foreach ($a_chart->getLegLabels() as $l) { + $l = ilUtil::shortenText($l, 80, true); + + $label = new stdClass(); + $label->label = $l; + $spider->legs->data[] = $label; + + $max_str_len = max($max_str_len, strlen($l)); + } + + // depending on caption length + if ($max_str_len > 60) { + $font_size = 10; + } elseif ($max_str_len > 30) { + $font_size = 12; + } else { + $font_size = 15; + } + $spider->legs->font = $font_size . "px Arial"; + + $spider->spiderSize = 0.7; + $spider->lineWidth = 1; + $spider->pointSize = 0; + + $spider->connection = new StdClass(); + $spider->connection->width = 2; + + $spider->legMin = 0.0000001; + $spider->legMax = $a_chart->getYAxisMax(); + + $a_options->series->spider = $spider; + } +} diff --git a/Services/Chart/classes/class.ilChartGrid.php b/Services/Chart/classes/class.ilChartGrid.php index 8331913fc4c905223be746e9b8a3e4cac4299ccb..bd541c5b482949a1293b2947e1f11ff7f0ca1ca7 100644 --- a/Services/Chart/classes/class.ilChartGrid.php +++ b/Services/Chart/classes/class.ilChartGrid.php @@ -1,153 +1,137 @@ - - * @version $Id$ - * @ingroup ServicesChart - */ -class ilChartGrid extends ilChart -{ - protected $ticks; // [array] - protected $integer_axis; // [array] - - const DATA_LINES = 1; - const DATA_BARS = 2; - const DATA_POINTS = 3; - - protected function __construct($a_id) - { - parent::__construct($a_id); - - $this->setXAxisToInteger(false); - $this->setYAxisToInteger(false); - } - - public function getDataInstance($a_type = null) - { - switch($a_type) - { - case self::DATA_BARS: - include_once "Services/Chart/classes/class.ilChartDataBars.php"; - return new ilChartDataBars(); - - case self::DATA_POINTS: - include_once "Services/Chart/classes/class.ilChartDataPoints.php"; - return new ilChartDataPoints(); - - default: - case self::DATA_LINES: - include_once "Services/Chart/classes/class.ilChartDataLines.php"; - return new ilChartDataLines(); - } - } - - protected function isValidDataType(ilChartData $a_series) - { - if($a_series instanceof ilChartDataLines - || $a_series instanceof ilChartDataBars - || $a_series instanceof ilChartDataPoints) - { - return true; - } - return false; - } - - /** - * Set ticks - * - * @param int|array $a_x - * @param int|array $a_y - * @param bool $a_labeled - */ - public function setTicks($a_x, $a_y, $a_labeled = false) - { - $this->ticks = array("x" => $a_x, "y" => $a_y, "labeled" => (bool)$a_labeled); - } - - /** - * Get ticks - * - * @return array (x, y) - */ - public function getTicks() - { - return $this->ticks; - } - - /** - * Restrict y-axis to integer values - * - * @param bool $a_status - */ - public function setYAxisToInteger($a_status) - { - $this->integer_axis["y"] = (bool)$a_status; - } - - /** - * Restrict x-axis to integer values - * - * @param bool $a_status - */ - public function setXAxisToInteger($a_status) - { - $this->integer_axis["x"] = (bool)$a_status; - } - - public function parseGlobalOptions(stdClass $a_options) - { - // axis/ticks - $tmp = array(); - $ticks = $this->getTicks(); - if($ticks) - { - $labeled = (bool)$ticks["labeled"]; - unset($ticks["labeled"]); - foreach($ticks as $axis => $def) - { - if(is_numeric($def) || is_array($def)) - { - $a_options->{$axis."axis"} = new stdClass(); - } - if(is_numeric($def)) - { - $a_options->{$axis."axis"}->ticks = $def; - } - else if(is_array($def)) - { - $a_options->{$axis."axis"}->ticks = array(); - foreach($def as $idx => $value) - { - if($labeled) - { - $a_options->{$axis."axis"}->ticks[] = array($idx, $value); - } - else - { - $a_options->{$axis."axis"}->ticks[] = $value; - } - } - } - } - } - - // optional: remove decimals - if($this->integer_axis["x"] && !isset($a_options->xaxis)) - { - $a_options->{"xaxis"} = new stdClass(); - $a_options->{"xaxis"}->tickDecimals = 0; - } - if($this->integer_axis["y"] && !isset($a_options->yaxis)) - { - $a_options->{"yaxis"} = new stdClass(); - $a_options->{"yaxis"}->tickDecimals = 0; - } - } -} - -?> \ No newline at end of file + + * @version $Id$ + * @ingroup ServicesChart + */ +class ilChartGrid extends ilChart +{ + protected $ticks; // [array] + protected $integer_axis; // [array] + + const DATA_LINES = 1; + const DATA_BARS = 2; + const DATA_POINTS = 3; + + protected function __construct($a_id) + { + parent::__construct($a_id); + + $this->setXAxisToInteger(false); + $this->setYAxisToInteger(false); + } + + public function getDataInstance($a_type = null) + { + switch ($a_type) { + case self::DATA_BARS: + include_once "Services/Chart/classes/class.ilChartDataBars.php"; + return new ilChartDataBars(); + + case self::DATA_POINTS: + include_once "Services/Chart/classes/class.ilChartDataPoints.php"; + return new ilChartDataPoints(); + + default: + case self::DATA_LINES: + include_once "Services/Chart/classes/class.ilChartDataLines.php"; + return new ilChartDataLines(); + } + } + + protected function isValidDataType(ilChartData $a_series) + { + if ($a_series instanceof ilChartDataLines + || $a_series instanceof ilChartDataBars + || $a_series instanceof ilChartDataPoints) { + return true; + } + return false; + } + + /** + * Set ticks + * + * @param int|array $a_x + * @param int|array $a_y + * @param bool $a_labeled + */ + public function setTicks($a_x, $a_y, $a_labeled = false) + { + $this->ticks = array("x" => $a_x, "y" => $a_y, "labeled" => (bool) $a_labeled); + } + + /** + * Get ticks + * + * @return array (x, y) + */ + public function getTicks() + { + return $this->ticks; + } + + /** + * Restrict y-axis to integer values + * + * @param bool $a_status + */ + public function setYAxisToInteger($a_status) + { + $this->integer_axis["y"] = (bool) $a_status; + } + + /** + * Restrict x-axis to integer values + * + * @param bool $a_status + */ + public function setXAxisToInteger($a_status) + { + $this->integer_axis["x"] = (bool) $a_status; + } + + public function parseGlobalOptions(stdClass $a_options) + { + // axis/ticks + $tmp = array(); + $ticks = $this->getTicks(); + if ($ticks) { + $labeled = (bool) $ticks["labeled"]; + unset($ticks["labeled"]); + foreach ($ticks as $axis => $def) { + if (is_numeric($def) || is_array($def)) { + $a_options->{$axis . "axis"} = new stdClass(); + } + if (is_numeric($def)) { + $a_options->{$axis . "axis"}->ticks = $def; + } elseif (is_array($def)) { + $a_options->{$axis . "axis"}->ticks = array(); + foreach ($def as $idx => $value) { + if ($labeled) { + $a_options->{$axis . "axis"}->ticks[] = array($idx, $value); + } else { + $a_options->{$axis . "axis"}->ticks[] = $value; + } + } + } + } + } + + // optional: remove decimals + if ($this->integer_axis["x"] && !isset($a_options->xaxis)) { + $a_options->{"xaxis"} = new stdClass(); + $a_options->{"xaxis"}->tickDecimals = 0; + } + if ($this->integer_axis["y"] && !isset($a_options->yaxis)) { + $a_options->{"yaxis"} = new stdClass(); + $a_options->{"yaxis"}->tickDecimals = 0; + } + } +} diff --git a/Services/Chart/classes/class.ilChartLegend.php b/Services/Chart/classes/class.ilChartLegend.php index 01512fa86b59737924e1188fe793ebe506ab550a..66b00077a8891371cb66e20589514f80eedbd69f 100644 --- a/Services/Chart/classes/class.ilChartLegend.php +++ b/Services/Chart/classes/class.ilChartLegend.php @@ -10,209 +10,202 @@ */ class ilChartLegend { - protected $position; // [string] - protected $columns; // [int] - protected $margin_x; // [int] - protected $margin_y; // [int] - protected $background; // [color] - protected $opacity; // [float] 0-1 - protected $border; // [color] - protected $container; // [string] + protected $position; // [string] + protected $columns; // [int] + protected $margin_x; // [int] + protected $margin_y; // [int] + protected $background; // [color] + protected $opacity; // [float] 0-1 + protected $border; // [color] + protected $container; // [string] - /** - * Constructor - */ - public function __construct() - { - $this->setPosition("ne"); - $this->setColumns(1); - $this->setMargin(5, 5); - $this->setBackground("#888"); - $this->setOpacity(0.1); - $this->setLabelBorder("#bbb"); - } + /** + * Constructor + */ + public function __construct() + { + $this->setPosition("ne"); + $this->setColumns(1); + $this->setMargin(5, 5); + $this->setBackground("#888"); + $this->setOpacity(0.1); + $this->setLabelBorder("#bbb"); + } - /** - * Set Position - * - * @param string $position - */ - public function setPosition($a_position) - { - $all = array("ne", "nw", "se", "sw"); - if(in_array((string)$a_position, $all)) - { - $this->position = (string)$a_position; - } - } + /** + * Set Position + * + * @param string $position + */ + public function setPosition($a_position) + { + $all = array("ne", "nw", "se", "sw"); + if (in_array((string) $a_position, $all)) { + $this->position = (string) $a_position; + } + } - /** - * Get Position - * - * @return string - */ - public function getPosition() - { - return $this->position; - } + /** + * Get Position + * + * @return string + */ + public function getPosition() + { + return $this->position; + } - /** - * Set number of columns - * - * @param int $a_value - */ - public function setColumns($a_value) - { - $this->columns = (int)$a_value; - } + /** + * Set number of columns + * + * @param int $a_value + */ + public function setColumns($a_value) + { + $this->columns = (int) $a_value; + } - /** - * Get number of columns - * - * @return int - */ - public function getColumns() - { - return $this->columns; - } + /** + * Get number of columns + * + * @return int + */ + public function getColumns() + { + return $this->columns; + } - /** - * Set margins - * - * @param int $a_x - * @param int $a_y - */ - public function setMargin($a_x, $a_y) - { - $this->margin_x = (int)$a_x; - $this->margin_y = (int)$a_y; - } + /** + * Set margins + * + * @param int $a_x + * @param int $a_y + */ + public function setMargin($a_x, $a_y) + { + $this->margin_x = (int) $a_x; + $this->margin_y = (int) $a_y; + } - /** - * Get margins - * - * @return array (x, y) - */ - public function getMargin() - { - return array("x"=>$this->margin_x, "y"=>$this->margin_y); - } + /** + * Get margins + * + * @return array (x, y) + */ + public function getMargin() + { + return array("x"=>$this->margin_x, "y"=>$this->margin_y); + } - /** - * Set background color - * - * @param string $a_color - */ - public function setBackground($a_color) - { - if(ilChart::isValidColor($a_color)) - { - $this->background = $a_color; - } - } + /** + * Set background color + * + * @param string $a_color + */ + public function setBackground($a_color) + { + if (ilChart::isValidColor($a_color)) { + $this->background = $a_color; + } + } - /** - * Get background color - * - * @return string - */ - public function getBackground() - { - return $this->background; - } + /** + * Get background color + * + * @return string + */ + public function getBackground() + { + return $this->background; + } - /** - * Set Opacity - * - * @param float $a_value - */ - public function setOpacity($a_value) - { - $a_value = (float)$a_value; - if($a_value >= 0 && $a_value <= 1) - { - $this->opacity = $a_value; - } - } + /** + * Set Opacity + * + * @param float $a_value + */ + public function setOpacity($a_value) + { + $a_value = (float) $a_value; + if ($a_value >= 0 && $a_value <= 1) { + $this->opacity = $a_value; + } + } - /** - * Get opacity - * - * @return float - */ - public function getOpacity() - { - return $this->opacity; - } + /** + * Get opacity + * + * @return float + */ + public function getOpacity() + { + return $this->opacity; + } - /** - * Set label border - * - * @param string $a_color - */ - public function setLabelBorder($a_color) - { - if(ilChart::isValidColor($a_color)) - { - $this->border = $a_color; - } - } + /** + * Set label border + * + * @param string $a_color + */ + public function setLabelBorder($a_color) + { + if (ilChart::isValidColor($a_color)) { + $this->border = $a_color; + } + } - /** - * Get label border - * - * @return string - */ - public function getLabelBorder() - { - return $this->border; - } - - /** - * Set container id - * - * @param string - */ - public function setContainer($a_value) - { - $this->container = trim($a_value); - } - - /** - * Get container id - * - * @return string - */ - public function getContainer() - { - return $this->container; - } - - /** - * Convert (global) properties to flot config - * - * @param object $a_options - */ - public function parseOptions(stdClass $a_options) - { - $a_options->show = true; - - $a_options->noColumns = $this->getColumns(); - $a_options->position = $this->getPosition(); - - $margin = $this->getMargin(); - $a_options->margin = array($margin["x"], $margin["y"]); - - $a_options->backgroundColor = ilChart::renderColor($this->getBackground()); - $a_options->backgroundOpacity = str_replace(",",".",$this->getOpacity()); - $a_options->labelBoxBorderColor = ilChart::renderColor($this->getLabelBorder()); - - $container = $this->getContainer(); - if($container) - { - $a_options->container = '#'.$container; - } - } + /** + * Get label border + * + * @return string + */ + public function getLabelBorder() + { + return $this->border; + } + + /** + * Set container id + * + * @param string + */ + public function setContainer($a_value) + { + $this->container = trim($a_value); + } + + /** + * Get container id + * + * @return string + */ + public function getContainer() + { + return $this->container; + } + + /** + * Convert (global) properties to flot config + * + * @param object $a_options + */ + public function parseOptions(stdClass $a_options) + { + $a_options->show = true; + + $a_options->noColumns = $this->getColumns(); + $a_options->position = $this->getPosition(); + + $margin = $this->getMargin(); + $a_options->margin = array($margin["x"], $margin["y"]); + + $a_options->backgroundColor = ilChart::renderColor($this->getBackground()); + $a_options->backgroundOpacity = str_replace(",", ".", $this->getOpacity()); + $a_options->labelBoxBorderColor = ilChart::renderColor($this->getLabelBorder()); + + $container = $this->getContainer(); + if ($container) { + $a_options->container = '#' . $container; + } + } } - -?> \ No newline at end of file diff --git a/Services/Chart/classes/class.ilChartPie.php b/Services/Chart/classes/class.ilChartPie.php index f5580a2701be1326600d48de0578568b11f053ce..afb3db8757e8a54fb1900d0ef786555914c651cc 100644 --- a/Services/Chart/classes/class.ilChartPie.php +++ b/Services/Chart/classes/class.ilChartPie.php @@ -1,45 +1,43 @@ - - * @version $Id$ - * @ingroup ServicesChart - */ -class ilChartPie extends ilChart -{ - public function getDataInstance($a_type = null) - { - include_once "Services/Chart/classes/class.ilChartDataPie.php"; - return new ilChartDataPie(); - } - - protected function isValidDataType(ilChartData $a_series) - { - return ($a_series instanceof ilChartDataPie); - } - - protected function addCustomJS() - { - $tpl = $this->tpl; - - $tpl->addJavascript("Services/Chart/js/flot/jquery.flot.pie.js"); - } - - public function parseGlobalOptions(stdClass $a_options) - { - // if no inner labels set, use legend - if(!isset($a_options->series->pie->label) && - !$this->legend) - { - $legend = new ilChartLegend(); - $legend->setPosition("nw"); - $this->setLegend($legend); - } - } -} - + + * @version $Id$ + * @ingroup ServicesChart + */ +class ilChartPie extends ilChart +{ + public function getDataInstance($a_type = null) + { + include_once "Services/Chart/classes/class.ilChartDataPie.php"; + return new ilChartDataPie(); + } + + protected function isValidDataType(ilChartData $a_series) + { + return ($a_series instanceof ilChartDataPie); + } + + protected function addCustomJS() + { + $tpl = $this->tpl; + + $tpl->addJavascript("Services/Chart/js/flot/jquery.flot.pie.js"); + } + + public function parseGlobalOptions(stdClass $a_options) + { + // if no inner labels set, use legend + if (!isset($a_options->series->pie->label) && + !$this->legend) { + $legend = new ilChartLegend(); + $legend->setPosition("nw"); + $this->setLegend($legend); + } + } +} diff --git a/Services/Chart/classes/class.ilChartSpider.php b/Services/Chart/classes/class.ilChartSpider.php index 921f80e16967c1ecb41159180fdd9da2c35b419d..00836c3bf83778aba8146fa4be1859e2ac99c300 100644 --- a/Services/Chart/classes/class.ilChartSpider.php +++ b/Services/Chart/classes/class.ilChartSpider.php @@ -1,89 +1,87 @@ - - * @version $Id$ - * @ingroup ServicesChart - */ -class ilChartSpider extends ilChart -{ - protected $leg_labels = array(); // [array] - protected $y_max = 0; // [float] - - public function getDataInstance($a_type = null) - { - include_once "Services/Chart/classes/class.ilChartDataSpider.php"; - return new ilChartDataSpider(); - } - - protected function isValidDataType(ilChartData $a_series) - { - return ($a_series instanceof ilChartDataSpider); - } - - /** - * Set leg labels - * - * @param array $a_val leg labels (array of strings) - */ - public function setLegLabels($a_val) - { - $this->leg_labels = $a_val; - } - - /** - * Get leg labels - * - * @return array leg labels (array of strings) - */ - public function getLegLabels() - { - return $this->leg_labels; - } - - - /** - * Set y axis max value - * - * @param float $a_val y axis max value - */ - public function setYAxisMax($a_val) - { - $this->y_max = $a_val; - } - - /** - * Get y axis max value - * - * @return float y axis max value - */ - public function getYAxisMax() - { - return $this->y_max; - } - - protected function addCustomJS() - { - $tpl = $this->tpl; - - $tpl->addJavascript("Services/Chart/js/flot/jquery.flot.highlighter.js"); - $tpl->addJavascript("Services/Chart/js/flot/jquery.flot.spider.js"); - } - - public function parseGlobalOptions(stdClass $a_options) - { - $a_options->grid = new stdClass(); - $a_options->grid->hoverable = false; - $a_options->grid->clickable = false; - $a_options->grid->ticks = $this->getYAxisMax(); - $a_options->grid->tickColor = ilChart::renderColor("#000", "0.1"); - $a_options->grid->mode = "spider"; - } -} - -?> \ No newline at end of file + + * @version $Id$ + * @ingroup ServicesChart + */ +class ilChartSpider extends ilChart +{ + protected $leg_labels = array(); // [array] + protected $y_max = 0; // [float] + + public function getDataInstance($a_type = null) + { + include_once "Services/Chart/classes/class.ilChartDataSpider.php"; + return new ilChartDataSpider(); + } + + protected function isValidDataType(ilChartData $a_series) + { + return ($a_series instanceof ilChartDataSpider); + } + + /** + * Set leg labels + * + * @param array $a_val leg labels (array of strings) + */ + public function setLegLabels($a_val) + { + $this->leg_labels = $a_val; + } + + /** + * Get leg labels + * + * @return array leg labels (array of strings) + */ + public function getLegLabels() + { + return $this->leg_labels; + } + + + /** + * Set y axis max value + * + * @param float $a_val y axis max value + */ + public function setYAxisMax($a_val) + { + $this->y_max = $a_val; + } + + /** + * Get y axis max value + * + * @return float y axis max value + */ + public function getYAxisMax() + { + return $this->y_max; + } + + protected function addCustomJS() + { + $tpl = $this->tpl; + + $tpl->addJavascript("Services/Chart/js/flot/jquery.flot.highlighter.js"); + $tpl->addJavascript("Services/Chart/js/flot/jquery.flot.spider.js"); + } + + public function parseGlobalOptions(stdClass $a_options) + { + $a_options->grid = new stdClass(); + $a_options->grid->hoverable = false; + $a_options->grid->clickable = false; + $a_options->grid->ticks = $this->getYAxisMax(); + $a_options->grid->tickColor = ilChart::renderColor("#000", "0.1"); + $a_options->grid->mode = "spider"; + } +} diff --git a/Services/Classification/classes/class.ilClassificationBlockGUI.php b/Services/Classification/classes/class.ilClassificationBlockGUI.php index a58b8bfce5929f9accab118ea8953b6c0160ba4f..ac6cbcc5103668deac8f52dd02d88edf94e8fde8 100644 --- a/Services/Classification/classes/class.ilClassificationBlockGUI.php +++ b/Services/Classification/classes/class.ilClassificationBlockGUI.php @@ -1,412 +1,371 @@ - - * @version $Id$ - * - * @ilCtrl_IsCalledBy ilClassificationBlockGUI: ilColumnGUI - * - * @ingroup ServicesClassification - */ -class ilClassificationBlockGUI extends ilBlockGUI -{ - /** - * @var ilObjectDefinition - */ - protected $obj_definition; - - /** - * @var ilTree - */ - protected $tree; - - protected $parent_obj_type; // [string] - protected $parent_obj_id; // [int] - protected $parent_ref_id; // [int] - protected $providers; // [array] - protected $item_list_gui; // [array] - - protected static $providers_cache; // [array] - - public function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $this->obj_definition = $DIC["objDefinition"]; - $this->tree = $DIC->repositoryTree(); - $this->access = $DIC->access(); - $lng = $DIC->language(); - - parent::__construct(); - - $this->parent_ref_id = (int)$_GET["ref_id"]; - $this->parent_obj_id = ilObject::_lookupObjId($this->parent_ref_id); - $this->parent_obj_type = ilObject::_lookupType($this->parent_obj_id); - - $lng->loadLanguageModule("classification"); - $this->setTitle($lng->txt("clsfct_block_title")); - $this->setFooterInfo($lng->txt("clsfct_block_info")); - } - - /** - * @inheritdoc - */ - public function getBlockType() :string - { - return 'clsfct'; - } - - /** - * @inheritdoc - */ - protected function isRepositoryObject(): bool - { - return false; - } - - public function executeCommand() - { - $ilCtrl = $this->ctrl; - - $cmd = $ilCtrl->getCmd(); - $next_class = $ilCtrl->getNextClass($this); - - switch ($next_class) - { - default: - // explorer call - if($ilCtrl->isAsynch() && $cmd != "getAjax" && $cmd != "filterContainer") - { - $this->getHTML(); - } - else - { - $this->$cmd(); - } - break; - } - } - - static function getScreenMode() - { - global $DIC; - - $ilCtrl = $DIC->ctrl(); - - if($ilCtrl->isAsynch()) - { - return; - } - - switch($ilCtrl->getCmd()) - { - case "filterContainer": - return IL_SCREEN_CENTER; - } - } - - public function getHTML() - { - $tpl = $this->main_tpl; - $ilCtrl = $this->ctrl; - - if(!$ilCtrl->isAsynch()) - { - unset($_SESSION[self::getBlockType()]); - } - - $this->initProviders(); - - if(!$this->validate()) - { - return ""; - } - - $tpl->addJavaScript("Services/Classification/js/ilClassification.js"); - - return parent::getHTML(); - } - - public function getAjax() - { - $tpl = $this->main_tpl; - - $this->initProviders(true); - - echo $this->getHTML(); - echo $tpl->getOnLoadCodeForAsynch(); - - exit(); - } - - public function fillDataSection() - { - $tpl = $this->main_tpl; - - $ilCtrl = $this->ctrl; - - $html = array(); - foreach($this->providers as $provider) - { - $provider->render($html, $this); - } - - $this->tpl->setVariable("BLOCK_ROW", ""); - - $ajax_block_id = "block_".$this->getBlockType()."_0"; - $ajax_block_url = $ilCtrl->getLinkTarget($this, "getAjax", "", true, false); - $ajax_content_id = "il_center_col"; - $ajax_content_url = $ilCtrl->getLinkTarget($this, "filterContainer", "", true, false); - - $tabs = new ilTabsGUI(); - $tabs->setBackTarget($this->lng->txt("clsfct_back_to_cat"), $ilCtrl->getParentReturn($this)); - $tabs->addTab("sel_objects", $this->lng->txt("clsfct_selected_objects"), "#"); - $tabs_html = $tabs->getHTML(); - - - // #15008 - always load regardless of content (because of redraw) - $tpl->addOnLoadCode('il.Classification.setAjax("'.$ajax_block_id.'", "'. - $ajax_block_url.'", "'.$ajax_content_id.'", "'.$ajax_content_url.'", '.json_encode($tabs_html).');'); - - if(sizeof($html)) - { - $btpl = new ilTemplate("tpl.classification_block.html", true, true, "Services/Classification"); - - foreach($html as $item) - { - $btpl->setCurrentBlock("provider_chunk_bl"); - $btpl->setVariable("TITLE", $item["title"]); - $btpl->setVariable("CHUNK", $item["html"]); - $btpl->parseCurrentBlock(); - } - - $this->tpl->setVariable("DATA", $btpl->get()); - } - } - - protected function validate() - { - return sizeof($this->providers); - } - - protected function filterContainer() - { - $objDefinition = $this->obj_definition; - $lng = $this->lng; - $tree = $this->tree; - $ilAccess = $this->access; - $tpl = $this->main_tpl; - - $this->initProviders(); - - // empty selection is invalid - if(!$_SESSION[self::getBlockType()]) - { - exit(); - } - - $all_matching_provider_object_ids = null; - - foreach($this->providers as $provider) - { - $id = get_class($provider); - $current = $_SESSION[self::getBlockType()][$id]; - if($current) - { - // combine providers AND - $provider_object_ids = $provider->getFilteredObjects(); - if(is_array($all_matching_provider_object_ids)) - { - $all_matching_provider_object_ids = array_intersect($matching_provider_object_ids, $provider_object_ids); - } - else - { - $all_matching_provider_object_ids = $provider_object_ids; - } - } - } - - $has_content = false; - - $ltpl = new ilTemplate("tpl.classification_object_list.html", true, true, "Services/Classification"); - - if(sizeof($all_matching_provider_object_ids)) - { - $fields = array( - "object_reference.ref_id" - ,"object_data.obj_id" - ,"object_data.type" - ,"object_data.title" - ,"object_data.description" - ); - $matching = $tree->getSubTreeFilteredByObjIds($this->parent_ref_id, $all_matching_provider_object_ids, $fields); - if(sizeof($matching)) - { - $valid_objects = array(); - - // :TODO: not sure if this makes sense... - include_once "Services/Object/classes/class.ilObjectListGUIPreloader.php"; - $preloader = new ilObjectListGUIPreloader(ilObjectListGUI::CONTEXT_REPOSITORY); - - foreach($matching as $item) - { - if($item["ref_id"] != $this->parent_ref_id && - !$tree->isDeleted($item["ref_id"]) && - $ilAccess->checkAccess("visible", "", $item["ref_id"])) - { - // group all valid items in blocks - // by their parent group/course or category - $block_ref_id = 0; - $block_title = ""; - foreach ($tree->getPathFull($item["ref_id"]) as $p) - { - if (in_array($p["type"], array("root", "cat", "crs", "grp"))) - { - $block_ref_id = $p["ref_id"]; - $block_title = $p["title"]; - } - } - if ($block_ref_id > 0) - { - if (!is_array($valid_objects[$block_ref_id])) - { - $valid_objects[$block_ref_id] = array( - "title" => $block_title, - "items" => array() - ); - } - $valid_objects[$block_ref_id]["items"][] = $item; - } - - $preloader->addItem($item["obj_id"], $item["type"], $item["ref_id"]); - } - } - $valid_objects = ilUtil::sortArray($valid_objects, "title", "asc", false, true); - if(sizeof($valid_objects)) - { - $has_content = true; - - $preloader->preload(); - - // see ilPDTaggingBlockGUI::showResourcesForTag() - - $this->item_list_gui = array(); - foreach($valid_objects as $block) - { - $items = ilUtil::sortArray($block["items"], "title", "asc", false, true); - foreach ($items as $obj) - { - $type = $obj["type"]; - - // get list gui class for each object type - if (empty($this->item_list_gui[$type])) - { - $class = $objDefinition->getClassName($type); - $location = $objDefinition->getLocation($type); - - $full_class = "ilObj" . $class . "ListGUI"; - - include_once($location . "/class." . $full_class . ".php"); - $this->item_list_gui[$type] = new $full_class(); - $this->item_list_gui[$type]->enableDelete(false); - $this->item_list_gui[$type]->enablePath( - true, - $this->parent_ref_id, - new \ilSessionClassificationPathGUI() - ); - $this->item_list_gui[$type]->enableLinkedPath(true); - $this->item_list_gui[$type]->enableCut(false); - $this->item_list_gui[$type]->enableCopy(false); - $this->item_list_gui[$type]->enableSubscribe(false); - $this->item_list_gui[$type]->enableLink(false); - $this->item_list_gui[$type]->enableIcon(true); - - // :TOOD: for each item or just for each list? - foreach ($this->providers as $provider) - { - $provider->initListGUI($this->item_list_gui[$type]); - } - } - - $html = $this->item_list_gui[$type]->getListItemHTML( - $obj["ref_id"], - $obj["obj_id"], - $obj["title"], - $obj["description"]); - - if ($html != "") - { - $ltpl->setCurrentBlock("res_row"); - $ltpl->setVariable("RESOURCE_HTML", $html); - $ltpl->parseCurrentBlock(); - } - } - $ltpl->setCurrentBlock("block"); - $ltpl->setVariable("BLOCK_TITLE", $block["title"]); - $ltpl->parseCurrentBlock(); - } - } - } - } - - if($has_content) - { - echo $ltpl->get(); - } - else - { - //$content_block->setContent($lng->txt("clsfct_content_no_match")); - echo $tpl->getMessageHTML($lng->txt("clsfct_content_no_match"), "info"); - } - - exit(); - } - - protected function initProviders($a_check_post = false) - { - if(!isset(self::$providers_cache[$this->parent_ref_id])) - { - include_once "Services/Classification/classes/class.ilClassificationProvider.php"; - self::$providers_cache[$this->parent_ref_id] = ilClassificationProvider::getValidProviders( - $this->parent_ref_id, - $this->parent_obj_id, - $this->parent_obj_typ - ); - } - $this->providers = self::$providers_cache[$this->parent_ref_id]; - - if($a_check_post && (bool)!$_REQUEST["rdrw"]) - { - foreach($this->providers as $provider) - { - $id = get_class($provider); - $current = $provider->importPostData($_SESSION[self::getBlockType()][$id]); - if($current) - { - $_SESSION[self::getBlockType()][$id] = $current; - } - else - { - unset($_SESSION[self::getBlockType()][$id]); - } - } - } - - foreach($this->providers as $provider) - { - $id = get_class($provider); - $current = $_SESSION[self::getBlockType()][$id]; - if($current) - { - $provider->setSelection($current); - } - } - } -} \ No newline at end of file + + * @version $Id$ + * + * @ilCtrl_IsCalledBy ilClassificationBlockGUI: ilColumnGUI + * + * @ingroup ServicesClassification + */ +class ilClassificationBlockGUI extends ilBlockGUI +{ + /** + * @var ilObjectDefinition + */ + protected $obj_definition; + + /** + * @var ilTree + */ + protected $tree; + + protected $parent_obj_type; // [string] + protected $parent_obj_id; // [int] + protected $parent_ref_id; // [int] + protected $providers; // [array] + protected $item_list_gui; // [array] + + protected static $providers_cache; // [array] + + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->obj_definition = $DIC["objDefinition"]; + $this->tree = $DIC->repositoryTree(); + $this->access = $DIC->access(); + $lng = $DIC->language(); + + parent::__construct(); + + $this->parent_ref_id = (int) $_GET["ref_id"]; + $this->parent_obj_id = ilObject::_lookupObjId($this->parent_ref_id); + $this->parent_obj_type = ilObject::_lookupType($this->parent_obj_id); + + $lng->loadLanguageModule("classification"); + $this->setTitle($lng->txt("clsfct_block_title")); + $this->setFooterInfo($lng->txt("clsfct_block_info")); + } + + /** + * @inheritdoc + */ + public function getBlockType() : string + { + return 'clsfct'; + } + + /** + * @inheritdoc + */ + protected function isRepositoryObject() : bool + { + return false; + } + + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $cmd = $ilCtrl->getCmd(); + $next_class = $ilCtrl->getNextClass($this); + + switch ($next_class) { + default: + // explorer call + if ($ilCtrl->isAsynch() && $cmd != "getAjax" && $cmd != "filterContainer") { + $this->getHTML(); + } else { + $this->$cmd(); + } + break; + } + } + + public static function getScreenMode() + { + global $DIC; + + $ilCtrl = $DIC->ctrl(); + + if ($ilCtrl->isAsynch()) { + return; + } + + switch ($ilCtrl->getCmd()) { + case "filterContainer": + return IL_SCREEN_CENTER; + } + } + + public function getHTML() + { + $tpl = $this->main_tpl; + $ilCtrl = $this->ctrl; + + if (!$ilCtrl->isAsynch()) { + unset($_SESSION[self::getBlockType()]); + } + + $this->initProviders(); + + if (!$this->validate()) { + return ""; + } + + $tpl->addJavaScript("Services/Classification/js/ilClassification.js"); + + return parent::getHTML(); + } + + public function getAjax() + { + $tpl = $this->main_tpl; + + $this->initProviders(true); + + echo $this->getHTML(); + echo $tpl->getOnLoadCodeForAsynch(); + + exit(); + } + + public function fillDataSection() + { + $tpl = $this->main_tpl; + + $ilCtrl = $this->ctrl; + + $html = array(); + foreach ($this->providers as $provider) { + $provider->render($html, $this); + } + + $this->tpl->setVariable("BLOCK_ROW", ""); + + $ajax_block_id = "block_" . $this->getBlockType() . "_0"; + $ajax_block_url = $ilCtrl->getLinkTarget($this, "getAjax", "", true, false); + $ajax_content_id = "il_center_col"; + $ajax_content_url = $ilCtrl->getLinkTarget($this, "filterContainer", "", true, false); + + $tabs = new ilTabsGUI(); + $tabs->setBackTarget($this->lng->txt("clsfct_back_to_cat"), $ilCtrl->getParentReturn($this)); + $tabs->addTab("sel_objects", $this->lng->txt("clsfct_selected_objects"), "#"); + $tabs_html = $tabs->getHTML(); + + + // #15008 - always load regardless of content (because of redraw) + $tpl->addOnLoadCode('il.Classification.setAjax("' . $ajax_block_id . '", "' . + $ajax_block_url . '", "' . $ajax_content_id . '", "' . $ajax_content_url . '", ' . json_encode($tabs_html) . ');'); + + if (sizeof($html)) { + $btpl = new ilTemplate("tpl.classification_block.html", true, true, "Services/Classification"); + + foreach ($html as $item) { + $btpl->setCurrentBlock("provider_chunk_bl"); + $btpl->setVariable("TITLE", $item["title"]); + $btpl->setVariable("CHUNK", $item["html"]); + $btpl->parseCurrentBlock(); + } + + $this->tpl->setVariable("DATA", $btpl->get()); + } + } + + protected function validate() + { + return sizeof($this->providers); + } + + protected function filterContainer() + { + $objDefinition = $this->obj_definition; + $lng = $this->lng; + $tree = $this->tree; + $ilAccess = $this->access; + $tpl = $this->main_tpl; + + $this->initProviders(); + + // empty selection is invalid + if (!$_SESSION[self::getBlockType()]) { + exit(); + } + + $all_matching_provider_object_ids = null; + + foreach ($this->providers as $provider) { + $id = get_class($provider); + $current = $_SESSION[self::getBlockType()][$id]; + if ($current) { + // combine providers AND + $provider_object_ids = $provider->getFilteredObjects(); + if (is_array($all_matching_provider_object_ids)) { + $all_matching_provider_object_ids = array_intersect($matching_provider_object_ids, $provider_object_ids); + } else { + $all_matching_provider_object_ids = $provider_object_ids; + } + } + } + + $has_content = false; + + $ltpl = new ilTemplate("tpl.classification_object_list.html", true, true, "Services/Classification"); + + if (sizeof($all_matching_provider_object_ids)) { + $fields = array( + "object_reference.ref_id" + ,"object_data.obj_id" + ,"object_data.type" + ,"object_data.title" + ,"object_data.description" + ); + $matching = $tree->getSubTreeFilteredByObjIds($this->parent_ref_id, $all_matching_provider_object_ids, $fields); + if (sizeof($matching)) { + $valid_objects = array(); + + // :TODO: not sure if this makes sense... + include_once "Services/Object/classes/class.ilObjectListGUIPreloader.php"; + $preloader = new ilObjectListGUIPreloader(ilObjectListGUI::CONTEXT_REPOSITORY); + + foreach ($matching as $item) { + if ($item["ref_id"] != $this->parent_ref_id && + !$tree->isDeleted($item["ref_id"]) && + $ilAccess->checkAccess("visible", "", $item["ref_id"])) { + // group all valid items in blocks + // by their parent group/course or category + $block_ref_id = 0; + $block_title = ""; + foreach ($tree->getPathFull($item["ref_id"]) as $p) { + if (in_array($p["type"], array("root", "cat", "crs", "grp"))) { + $block_ref_id = $p["ref_id"]; + $block_title = $p["title"]; + } + } + if ($block_ref_id > 0) { + if (!is_array($valid_objects[$block_ref_id])) { + $valid_objects[$block_ref_id] = array( + "title" => $block_title, + "items" => array() + ); + } + $valid_objects[$block_ref_id]["items"][] = $item; + } + + $preloader->addItem($item["obj_id"], $item["type"], $item["ref_id"]); + } + } + $valid_objects = ilUtil::sortArray($valid_objects, "title", "asc", false, true); + if (sizeof($valid_objects)) { + $has_content = true; + + $preloader->preload(); + + // see ilPDTaggingBlockGUI::showResourcesForTag() + + $this->item_list_gui = array(); + foreach ($valid_objects as $block) { + $items = ilUtil::sortArray($block["items"], "title", "asc", false, true); + foreach ($items as $obj) { + $type = $obj["type"]; + + // get list gui class for each object type + if (empty($this->item_list_gui[$type])) { + $class = $objDefinition->getClassName($type); + $location = $objDefinition->getLocation($type); + + $full_class = "ilObj" . $class . "ListGUI"; + + include_once($location . "/class." . $full_class . ".php"); + $this->item_list_gui[$type] = new $full_class(); + $this->item_list_gui[$type]->enableDelete(false); + $this->item_list_gui[$type]->enablePath( + true, + $this->parent_ref_id, + new \ilSessionClassificationPathGUI() + ); + $this->item_list_gui[$type]->enableLinkedPath(true); + $this->item_list_gui[$type]->enableCut(false); + $this->item_list_gui[$type]->enableCopy(false); + $this->item_list_gui[$type]->enableSubscribe(false); + $this->item_list_gui[$type]->enableLink(false); + $this->item_list_gui[$type]->enableIcon(true); + + // :TOOD: for each item or just for each list? + foreach ($this->providers as $provider) { + $provider->initListGUI($this->item_list_gui[$type]); + } + } + + $html = $this->item_list_gui[$type]->getListItemHTML( + $obj["ref_id"], + $obj["obj_id"], + $obj["title"], + $obj["description"] + ); + + if ($html != "") { + $ltpl->setCurrentBlock("res_row"); + $ltpl->setVariable("RESOURCE_HTML", $html); + $ltpl->parseCurrentBlock(); + } + } + $ltpl->setCurrentBlock("block"); + $ltpl->setVariable("BLOCK_TITLE", $block["title"]); + $ltpl->parseCurrentBlock(); + } + } + } + } + + if ($has_content) { + echo $ltpl->get(); + } else { + //$content_block->setContent($lng->txt("clsfct_content_no_match")); + echo $tpl->getMessageHTML($lng->txt("clsfct_content_no_match"), "info"); + } + + exit(); + } + + protected function initProviders($a_check_post = false) + { + if (!isset(self::$providers_cache[$this->parent_ref_id])) { + include_once "Services/Classification/classes/class.ilClassificationProvider.php"; + self::$providers_cache[$this->parent_ref_id] = ilClassificationProvider::getValidProviders( + $this->parent_ref_id, + $this->parent_obj_id, + $this->parent_obj_typ + ); + } + $this->providers = self::$providers_cache[$this->parent_ref_id]; + + if ($a_check_post && (bool) !$_REQUEST["rdrw"]) { + foreach ($this->providers as $provider) { + $id = get_class($provider); + $current = $provider->importPostData($_SESSION[self::getBlockType()][$id]); + if ($current) { + $_SESSION[self::getBlockType()][$id] = $current; + } else { + unset($_SESSION[self::getBlockType()][$id]); + } + } + } + + foreach ($this->providers as $provider) { + $id = get_class($provider); + $current = $_SESSION[self::getBlockType()][$id]; + if ($current) { + $provider->setSelection($current); + } + } + } +} diff --git a/Services/Classification/classes/class.ilClassificationProvider.php b/Services/Classification/classes/class.ilClassificationProvider.php index f2cd15d49dc306683fc171cf43b3cd2ad5fffd4a..28b611a1d23a25e97feb6e1944b7adf2a1d0c1f9 100644 --- a/Services/Classification/classes/class.ilClassificationProvider.php +++ b/Services/Classification/classes/class.ilClassificationProvider.php @@ -1,120 +1,116 @@ - - * @version $Id$ - * - * @ingroup ServicesClassification - */ -abstract class ilClassificationProvider -{ - protected $parent_ref_id; // [int] - protected $parent_obj_id; // [int] - protected $parent_type; // [string] - - /** - * Constructor - * - * @param int $a_parent_ref_id - * @param int $a_parent_obj_id - * @param string $a_parent_obj_type - * @return self - */ - public function __construct($a_parent_ref_id, $a_parent_obj_id, $a_parent_obj_type) - { - $this->parent_ref_id = (int)$a_parent_ref_id; - $this->parent_obj_id = (int)$a_parent_obj_id; - $this->parent_type = (string)$a_parent_obj_type; - - $this->init(); - } - - /** - * Instance initialisation - */ - protected function init() - { - - } - - /** - * Get all valid providers (for parent container) - * - * @param int $a_parent_ref_id - * @param int $a_parent_obj_id - * @param string $a_parent_obj_type - * @return array - */ - public static function getValidProviders($a_parent_ref_id, $a_parent_obj_id, $a_parent_obj_type) - { - $res = array(); - - include_once "Services/Taxonomy/classes/class.ilTaxonomyClassificationProvider.php"; - if(ilTaxonomyClassificationProvider::isActive($a_parent_ref_id, $a_parent_obj_id, $a_parent_obj_type)) - { - $res[] = new ilTaxonomyClassificationProvider($a_parent_ref_id, $a_parent_obj_id, $a_parent_obj_type); - } - - include_once "Services/Tagging/classes/class.ilTaggingClassificationProvider.php"; - if(ilTaggingClassificationProvider::isActive($a_parent_ref_id, $a_parent_obj_id, $a_parent_obj_type)) - { - $res[] = new ilTaggingClassificationProvider($a_parent_ref_id, $a_parent_obj_id, $a_parent_obj_type); - } - - return $res; - } - - /** - * Is provider currently active? - * - * @param int $a_parent_ref_id - * @param int $a_parent_obj_id - * @param string $a_parent_obj_type - * @return bool - */ - abstract public static function isActive($a_parent_ref_id, $a_parent_obj_id, $a_parent_obj_type); - - /** - * Render HTML chunks - * - * @param array $a_html - * @param object $a_parent_gui - */ - abstract public function render(array &$a_html, $a_parent_gui); - - /** - * Import post data - * - * @param mixed $a_saved - * @return mixed - */ - abstract public function importPostData($a_saved = null); - - /** - * Set selection - * - * @param mixed $a_value - */ - abstract public function setSelection($a_value); - - /** - * Get filtered object ref ids - * - * @return array - */ - abstract public function getFilteredObjects(); - - - /** - * Init list gui properties - * - * @param ilObjectListGUI $a_list_gui - */ - public function initListGUI(ilObjectListGUI $a_list_gui) - { - - } -} \ No newline at end of file + + * @version $Id$ + * + * @ingroup ServicesClassification + */ +abstract class ilClassificationProvider +{ + protected $parent_ref_id; // [int] + protected $parent_obj_id; // [int] + protected $parent_type; // [string] + + /** + * Constructor + * + * @param int $a_parent_ref_id + * @param int $a_parent_obj_id + * @param string $a_parent_obj_type + * @return self + */ + public function __construct($a_parent_ref_id, $a_parent_obj_id, $a_parent_obj_type) + { + $this->parent_ref_id = (int) $a_parent_ref_id; + $this->parent_obj_id = (int) $a_parent_obj_id; + $this->parent_type = (string) $a_parent_obj_type; + + $this->init(); + } + + /** + * Instance initialisation + */ + protected function init() + { + } + + /** + * Get all valid providers (for parent container) + * + * @param int $a_parent_ref_id + * @param int $a_parent_obj_id + * @param string $a_parent_obj_type + * @return array + */ + public static function getValidProviders($a_parent_ref_id, $a_parent_obj_id, $a_parent_obj_type) + { + $res = array(); + + include_once "Services/Taxonomy/classes/class.ilTaxonomyClassificationProvider.php"; + if (ilTaxonomyClassificationProvider::isActive($a_parent_ref_id, $a_parent_obj_id, $a_parent_obj_type)) { + $res[] = new ilTaxonomyClassificationProvider($a_parent_ref_id, $a_parent_obj_id, $a_parent_obj_type); + } + + include_once "Services/Tagging/classes/class.ilTaggingClassificationProvider.php"; + if (ilTaggingClassificationProvider::isActive($a_parent_ref_id, $a_parent_obj_id, $a_parent_obj_type)) { + $res[] = new ilTaggingClassificationProvider($a_parent_ref_id, $a_parent_obj_id, $a_parent_obj_type); + } + + return $res; + } + + /** + * Is provider currently active? + * + * @param int $a_parent_ref_id + * @param int $a_parent_obj_id + * @param string $a_parent_obj_type + * @return bool + */ + abstract public static function isActive($a_parent_ref_id, $a_parent_obj_id, $a_parent_obj_type); + + /** + * Render HTML chunks + * + * @param array $a_html + * @param object $a_parent_gui + */ + abstract public function render(array &$a_html, $a_parent_gui); + + /** + * Import post data + * + * @param mixed $a_saved + * @return mixed + */ + abstract public function importPostData($a_saved = null); + + /** + * Set selection + * + * @param mixed $a_value + */ + abstract public function setSelection($a_value); + + /** + * Get filtered object ref ids + * + * @return array + */ + abstract public function getFilteredObjects(); + + + /** + * Init list gui properties + * + * @param ilObjectListGUI $a_list_gui + */ + public function initListGUI(ilObjectListGUI $a_list_gui) + { + } +} diff --git a/Services/Clipboard/classes/class.ilClipboardTableGUI.php b/Services/Clipboard/classes/class.ilClipboardTableGUI.php index eeae2273042eb48e26fca91d0f1aad240f5a3a97..a8cf0867f3f1f863b41bb6662cc76d2bd9cb62d0 100755 --- a/Services/Clipboard/classes/class.ilClipboardTableGUI.php +++ b/Services/Clipboard/classes/class.ilClipboardTableGUI.php @@ -14,140 +14,140 @@ include_once("Services/Table/classes/class.ilTable2GUI.php"); */ class ilClipboardTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $this->user = $DIC->user(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilAccess = $DIC->access(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - $lng->loadLanguageModule("mep"); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->user = $DIC->user(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilAccess = $DIC->access(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + $lng->loadLanguageModule("mep"); - $this->addColumn("", "", "1"); // checkbox - $this->addColumn($lng->txt("mep_thumbnail"), "", "1"); - $this->addColumn($lng->txt("mep_title_and_description"), "", "100%"); - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.clipboard_tbl_row.html", - "Services/Clipboard"); - $this->getItems(); - - // title - $this->setTitle($lng->txt("clipboard")); + $this->addColumn("", "", "1"); // checkbox + $this->addColumn($lng->txt("mep_thumbnail"), "", "1"); + $this->addColumn($lng->txt("mep_title_and_description"), "", "100%"); + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate( + "tpl.clipboard_tbl_row.html", + "Services/Clipboard" + ); + $this->getItems(); + + // title + $this->setTitle($lng->txt("clipboard")); - $this->setDefaultOrderField("title"); - - // action commands - if ($this->parent_obj->mode == "getObject") - { - $this->addMultiCommand("insert", $this->parent_obj->getInsertButtonTitle()); - } - $this->addMultiCommand("remove", $lng->txt("remove")); - - $this->setSelectAllCheckbox("id"); - } + $this->setDefaultOrderField("title"); + + // action commands + if ($this->parent_obj->mode == "getObject") { + $this->addMultiCommand("insert", $this->parent_obj->getInsertButtonTitle()); + } + $this->addMultiCommand("remove", $lng->txt("remove")); + + $this->setSelectAllCheckbox("id"); + } - /** - * Get items from user clipboard - */ - function getItems() - { - $ilUser = $this->user; - - $objs = $ilUser->getClipboardObjects("mob"); - $objs2 = $ilUser->getClipboardObjects("incl"); - $objs = array_merge($objs, $objs2); - $objs = ilUtil::sortArray($objs, $_GET["sort_by"], $_GET["sort_order"]); + /** + * Get items from user clipboard + */ + public function getItems() + { + $ilUser = $this->user; + + $objs = $ilUser->getClipboardObjects("mob"); + $objs2 = $ilUser->getClipboardObjects("incl"); + $objs = array_merge($objs, $objs2); + $objs = ilUtil::sortArray($objs, $_GET["sort_by"], $_GET["sort_order"]); - $this->setData($objs); - } - - /** - * Standard Version of Fill Row. Most likely to - * be overwritten by derived class. - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; + $this->setData($objs); + } + + /** + * Standard Version of Fill Row. Most likely to + * be overwritten by derived class. + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; - if ($a_set["type"] == "mob") - { - // output thumbnail - $mob = new ilObjMediaObject($a_set["id"]); - $med = $mob->getMediaItem("Standard"); - $target = $med->getThumbnailTarget(); - if ($target != "") - { - $this->tpl->setCurrentBlock("thumbnail"); - $this->tpl->setVariable("IMG_THUMB", $target); - $this->tpl->parseCurrentBlock(); - } - } - else if ($a_set["type"] == "incl") - { - $this->tpl->setCurrentBlock("thumbnail"); - $this->tpl->setVariable("IMG_THUMB", - ilUtil::getImagePath("icon_pg.svg")); - $this->tpl->parseCurrentBlock(); - } - - // allow editing of media objects - if ($this->parent_obj->mode != "getObject" && $a_set["type"] == "mob") - { - // output edit link - $this->tpl->setCurrentBlock("edit"); - $ilCtrl->setParameter($this->parent_obj, "clip_item_id", $a_set["id"]); - $ilCtrl->setParameterByClass("ilObjMediaObjectGUI", "clip_item_id", $a_set["id"]); - $this->tpl->setVariable("EDIT_LINK", - $ilCtrl->getLinkTargetByClass("ilObjMediaObjectGUI", "edit", - array("ilEditClipboardGUI"))); - $this->tpl->setVariable("TEXT_OBJECT", $a_set["title"]. - " [".$a_set["id"]."]"); - $this->tpl->parseCurrentBlock(); - } - else // just list elements for selection - { - $this->tpl->setCurrentBlock("show"); - $this->tpl->setVariable("TEXT_OBJECT2", $a_set["title"]. - " [".$a_set["id"]."]"); - $this->tpl->parseCurrentBlock(); - } - - include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); - if ($a_set["type"] == "mob") - { - $this->tpl->setVariable("MEDIA_INFO", - ilObjMediaObjectGUI::_getMediaInfoHTML($mob)); - } - $this->tpl->setVariable("CHECKBOX_ID", $a_set["type"].":".$a_set["id"]); - } + if ($a_set["type"] == "mob") { + // output thumbnail + $mob = new ilObjMediaObject($a_set["id"]); + $med = $mob->getMediaItem("Standard"); + $target = $med->getThumbnailTarget(); + if ($target != "") { + $this->tpl->setCurrentBlock("thumbnail"); + $this->tpl->setVariable("IMG_THUMB", $target); + $this->tpl->parseCurrentBlock(); + } + } elseif ($a_set["type"] == "incl") { + $this->tpl->setCurrentBlock("thumbnail"); + $this->tpl->setVariable( + "IMG_THUMB", + ilUtil::getImagePath("icon_pg.svg") + ); + $this->tpl->parseCurrentBlock(); + } + // allow editing of media objects + if ($this->parent_obj->mode != "getObject" && $a_set["type"] == "mob") { + // output edit link + $this->tpl->setCurrentBlock("edit"); + $ilCtrl->setParameter($this->parent_obj, "clip_item_id", $a_set["id"]); + $ilCtrl->setParameterByClass("ilObjMediaObjectGUI", "clip_item_id", $a_set["id"]); + $this->tpl->setVariable( + "EDIT_LINK", + $ilCtrl->getLinkTargetByClass( + "ilObjMediaObjectGUI", + "edit", + array("ilEditClipboardGUI") + ) + ); + $this->tpl->setVariable("TEXT_OBJECT", $a_set["title"] . + " [" . $a_set["id"] . "]"); + $this->tpl->parseCurrentBlock(); + } else { // just list elements for selection + $this->tpl->setCurrentBlock("show"); + $this->tpl->setVariable("TEXT_OBJECT2", $a_set["title"] . + " [" . $a_set["id"] . "]"); + $this->tpl->parseCurrentBlock(); + } + + include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); + if ($a_set["type"] == "mob") { + $this->tpl->setVariable( + "MEDIA_INFO", + ilObjMediaObjectGUI::_getMediaInfoHTML($mob) + ); + } + $this->tpl->setVariable("CHECKBOX_ID", $a_set["type"] . ":" . $a_set["id"]); + } } -?> diff --git a/Services/Clipboard/classes/class.ilEditClipboardGUI.php b/Services/Clipboard/classes/class.ilEditClipboardGUI.php index c7d70599fab174ae2f00e8e07be45a9d298bce84..7d8905781b43a0451bee248a86fbbbfc3489f76c 100755 --- a/Services/Clipboard/classes/class.ilEditClipboardGUI.php +++ b/Services/Clipboard/classes/class.ilEditClipboardGUI.php @@ -17,298 +17,290 @@ require_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); */ class ilEditClipboardGUI { - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilTree - */ - protected $tree; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * Constructor - * @access public - */ - function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $this->user = $DIC->user(); - $this->tabs = $DIC->tabs(); - $this->tree = $DIC->repositoryTree(); - $this->tpl = $DIC["tpl"]; - $this->toolbar = $DIC->toolbar(); - $this->error = $DIC["ilErr"]; - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - - $this->multiple = false; - $this->page_back_title = $lng->txt("cont_back"); - if ($_GET["returnCommand"] != "") - { - $this->mode = "getObject"; - } - else - { - $this->mode = ""; - } - - $ilCtrl->setParameter($this, "returnCommand", - rawurlencode($_GET["returnCommand"])); - - $ilCtrl->saveParameter($this, array("clip_item_id")); - } - - /** - * execute command - */ - function executeCommand() - { - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - $lng = $this->lng; - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd(); - - switch($next_class) - { - case "ilobjmediaobjectgui": - $ilCtrl->setReturn($this, "view"); - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTarget($this, "view")); - $mob_gui = new ilObjMediaObjectGUI("", $_GET["clip_item_id"],false, false); - $mob_gui->setTabs(); - $ret = $ilCtrl->forwardCommand($mob_gui); - switch($cmd) - { - case "save": - $ilUser->addObjectToClipboard($ret->getId(), "mob", $ret->getTitle()); - $ilCtrl->redirect($this, "view"); - break; - } - break; - - default: - $ret = $this->$cmd(); - break; - } - - return $ret; - } - - /** - * set, if multiple selections are enabled - */ - function setMultipleSelections($a_multiple = true) - { - $this->multiple = $a_multiple; - } - - /** - * check wether multiple selections are enabled - */ - function getMultipleSelections() - { - return $this->multiple; - } - - /** - * Set Insert Button Title. - * - * @param string $a_insertbuttontitle Insert Button Title - */ - function setInsertButtonTitle($a_insertbuttontitle) - { - $this->insertbuttontitle = $a_insertbuttontitle; - } - - /** - * Get Insert Button Title. - * - * @return string Insert Button Title - */ - function getInsertButtonTitle() - { - $lng = $this->lng; - - if ($this->insertbuttontitle == "") - { - return $lng->txt("insert"); - } - - return $this->insertbuttontitle; - } - - /* - * display clipboard content - */ - function view() - { - $tree = $this->tree; - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - - include_once("./Services/UIComponent/Button/classes/class.ilLinkButton.php"); - $but = ilLinkButton::getInstance(); - $but->setUrl($ilCtrl->getLinkTargetByClass("ilobjmediaobjectgui", "create")); - $but->setCaption("cont_create_mob"); - $ilToolbar->addButtonInstance($but); - - include_once("./Services/Clipboard/classes/class.ilClipboardTableGUI.php"); - $table_gui = new ilClipboardTableGUI($this, "view"); - $tpl->setContent($table_gui->getHTML()); - } - - - /** - * get Object - */ - function getObject() - { - $this->mode = "getObject"; - $this->view(); - } - - - /** - * remove item from clipboard - */ - function remove() - { - $ilErr = $this->error; - $ilUser = $this->user; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - // check number of objects - if (!isset($_POST["id"])) - { - $ilErr->raiseError($lng->txt("no_checkbox"), $ilErr->MESSAGE); - } - - foreach($_POST["id"] AS $obj_id) - { - $id = explode(":", $obj_id); - if ($id[0] == "mob") - { - $ilUser->removeObjectFromClipboard($id[1], "mob"); - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $mob = new ilObjMediaObject($id[1]); - $mob->delete(); // this method don't delete, if mob is used elsewhere - } - if ($id[0] == "incl") - { - $ilUser->removeObjectFromClipboard($id[1], "incl"); - } - } - $ilCtrl->redirect($this, "view"); - } - - /** - * insert - */ - function insert() - { - $lng = $this->lng; - $ilErr = $this->error; - - // check number of objects - if (!isset($_POST["id"])) - { - $ilErr->raiseError($lng->txt("no_checkbox"), $ilErr->MESSAGE); - } - - if (!$this->getMultipleSelections()) - { - if(count($_POST["id"]) > 1) - { - $ilErr->raiseError($lng->txt("cont_select_max_one_item"), $ilErr->MESSAGE); - } - } - - $_SESSION["ilEditClipboard_mob_id"] = $_POST["id"]; - ilUtil::redirect($_GET["returnCommand"]); - } - - static function _getSelectedIDs() - { - return $_SESSION["ilEditClipboard_mob_id"]; - } - - /** - * output tabs - */ - function setTabs() - { - $ilTabs = $this->tabs; - $lng = $this->lng; - $tpl = $this->tpl; - - $tpl->setTitle($lng->txt("clipboard")); - $this->getTabs($ilTabs); - } - - /** - * Set title for back link - */ - function setPageBackTitle($a_title) - { - $this->page_back_title = $a_title; - } - - /** - * adds tabs to tab gui object - * - * @param object $tabs_gui ilTabsGUI object - */ - function getTabs(&$tabs_gui) - { - $ilCtrl = $this->ctrl; - - // back to upper context - $tabs_gui->setBackTarget($this->page_back_title, - $ilCtrl->getParentReturn($this)); - } - + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilTree + */ + protected $tree; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * Constructor + * @access public + */ + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->user = $DIC->user(); + $this->tabs = $DIC->tabs(); + $this->tree = $DIC->repositoryTree(); + $this->tpl = $DIC["tpl"]; + $this->toolbar = $DIC->toolbar(); + $this->error = $DIC["ilErr"]; + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + + $this->multiple = false; + $this->page_back_title = $lng->txt("cont_back"); + if ($_GET["returnCommand"] != "") { + $this->mode = "getObject"; + } else { + $this->mode = ""; + } + + $ilCtrl->setParameter( + $this, + "returnCommand", + rawurlencode($_GET["returnCommand"]) + ); + + $ilCtrl->saveParameter($this, array("clip_item_id")); + } + + /** + * execute command + */ + public function executeCommand() + { + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + $lng = $this->lng; + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd(); + + switch ($next_class) { + case "ilobjmediaobjectgui": + $ilCtrl->setReturn($this, "view"); + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, "view") + ); + $mob_gui = new ilObjMediaObjectGUI("", $_GET["clip_item_id"], false, false); + $mob_gui->setTabs(); + $ret = $ilCtrl->forwardCommand($mob_gui); + switch ($cmd) { + case "save": + $ilUser->addObjectToClipboard($ret->getId(), "mob", $ret->getTitle()); + $ilCtrl->redirect($this, "view"); + break; + } + break; + + default: + $ret = $this->$cmd(); + break; + } + + return $ret; + } + + /** + * set, if multiple selections are enabled + */ + public function setMultipleSelections($a_multiple = true) + { + $this->multiple = $a_multiple; + } + + /** + * check wether multiple selections are enabled + */ + public function getMultipleSelections() + { + return $this->multiple; + } + + /** + * Set Insert Button Title. + * + * @param string $a_insertbuttontitle Insert Button Title + */ + public function setInsertButtonTitle($a_insertbuttontitle) + { + $this->insertbuttontitle = $a_insertbuttontitle; + } + + /** + * Get Insert Button Title. + * + * @return string Insert Button Title + */ + public function getInsertButtonTitle() + { + $lng = $this->lng; + + if ($this->insertbuttontitle == "") { + return $lng->txt("insert"); + } + + return $this->insertbuttontitle; + } + + /* + * display clipboard content + */ + public function view() + { + $tree = $this->tree; + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + + include_once("./Services/UIComponent/Button/classes/class.ilLinkButton.php"); + $but = ilLinkButton::getInstance(); + $but->setUrl($ilCtrl->getLinkTargetByClass("ilobjmediaobjectgui", "create")); + $but->setCaption("cont_create_mob"); + $ilToolbar->addButtonInstance($but); + + include_once("./Services/Clipboard/classes/class.ilClipboardTableGUI.php"); + $table_gui = new ilClipboardTableGUI($this, "view"); + $tpl->setContent($table_gui->getHTML()); + } + + + /** + * get Object + */ + public function getObject() + { + $this->mode = "getObject"; + $this->view(); + } + + + /** + * remove item from clipboard + */ + public function remove() + { + $ilErr = $this->error; + $ilUser = $this->user; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + // check number of objects + if (!isset($_POST["id"])) { + $ilErr->raiseError($lng->txt("no_checkbox"), $ilErr->MESSAGE); + } + + foreach ($_POST["id"] as $obj_id) { + $id = explode(":", $obj_id); + if ($id[0] == "mob") { + $ilUser->removeObjectFromClipboard($id[1], "mob"); + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $mob = new ilObjMediaObject($id[1]); + $mob->delete(); // this method don't delete, if mob is used elsewhere + } + if ($id[0] == "incl") { + $ilUser->removeObjectFromClipboard($id[1], "incl"); + } + } + $ilCtrl->redirect($this, "view"); + } + + /** + * insert + */ + public function insert() + { + $lng = $this->lng; + $ilErr = $this->error; + + // check number of objects + if (!isset($_POST["id"])) { + $ilErr->raiseError($lng->txt("no_checkbox"), $ilErr->MESSAGE); + } + + if (!$this->getMultipleSelections()) { + if (count($_POST["id"]) > 1) { + $ilErr->raiseError($lng->txt("cont_select_max_one_item"), $ilErr->MESSAGE); + } + } + + $_SESSION["ilEditClipboard_mob_id"] = $_POST["id"]; + ilUtil::redirect($_GET["returnCommand"]); + } + + public static function _getSelectedIDs() + { + return $_SESSION["ilEditClipboard_mob_id"]; + } + + /** + * output tabs + */ + public function setTabs() + { + $ilTabs = $this->tabs; + $lng = $this->lng; + $tpl = $this->tpl; + + $tpl->setTitle($lng->txt("clipboard")); + $this->getTabs($ilTabs); + } + + /** + * Set title for back link + */ + public function setPageBackTitle($a_title) + { + $this->page_back_title = $a_title; + } + + /** + * adds tabs to tab gui object + * + * @param object $tabs_gui ilTabsGUI object + */ + public function getTabs(&$tabs_gui) + { + $ilCtrl = $this->ctrl; + + // back to upper context + $tabs_gui->setBackTarget( + $this->page_back_title, + $ilCtrl->getParentReturn($this) + ); + } } -?> diff --git a/Services/Container/Skills/classes/class.ilContSkillAdminGUI.php b/Services/Container/Skills/classes/class.ilContSkillAdminGUI.php index 77b27223d7c39811744ca5b81fa48d6f04a0bdf7..4096224ccfa3ec3138e5ec31e21be879a9024198 100644 --- a/Services/Container/Skills/classes/class.ilContSkillAdminGUI.php +++ b/Services/Container/Skills/classes/class.ilContSkillAdminGUI.php @@ -10,534 +10,501 @@ */ class ilContSkillAdminGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilContainerGUI - */ - protected $container_gui; - - /** - * @var ilContainer - */ - protected $container; - - /** - * @var ilContainerSkills - */ - protected $container_skills; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * Constructor - * - * @param - */ - function __construct($a_container_gui) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->tabs = $DIC->tabs(); - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - $this->toolbar = $DIC->toolbar(); - $this->access = $DIC->access(); - - $this->container_gui = $a_container_gui; - $this->container = $a_container_gui->object; - $this->ref_id = $this->container->getRefId(); - - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $this->skill_tree = new ilSkillTree(); - - include_once("./Services/Container/Skills/classes/class.ilContainerSkills.php"); - $this->container_skills = new ilContainerSkills($this->container->getId()); - - $this->user_id = (int) $_GET["usr_id"]; - } - - /** - * Execute command - */ - function executeCommand() - { - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd("listMembers"); - - switch ($next_class) - { - default: - if ( - ($this->access->checkAccess("write", "", $this->ref_id) && - in_array($cmd, array("listCompetences", "settings", "saveSettings", "selectSkill", - "saveSelectedSkill", "confirmRemoveSelectedSkill", "removeSelectedSkill"))) - || - ($this->access->checkAccess("grade", "", $this->ref_id) && - in_array($cmd, array("listMembers", "assignCompetences", - "saveCompetenceAssignment", "publishAssignments", "deassignCompetencesConfirm", "deassignCompetences"))) - ) - { - $this->$cmd(); - } - } - } - - //// MANAGE MEMBERS - - /** - * List members - */ - function listMembers() - { - $tpl = $this->tpl; - $tabs = $this->tabs; - - $tabs->activateSubTab("members"); - - // table - include_once("./Services/Container/Skills/classes/class.ilContSkillMemberTableGUI.php"); - $tab = new ilContSkillMemberTableGUI($this, "listMembers", $this->container_skills); - - $tpl->setContent($tab->getHTML()); - - } - - /** - * Assign competences to a member - */ - function assignCompetences() - { - $tpl = $this->tpl; - $tabs = $this->tabs; - $ctrl = $this->ctrl; - - $ctrl->saveParameter($this, "usr_id"); - $tabs->activateSubTab("members"); - - $form = $this->initCompetenceAssignmentForm(); - $tpl->setContent($form->getHTML()); - - } - - /** - * Init competence assignment form - */ - public function initCompetenceAssignmentForm() - { - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - - include_once("./Services/Container/Skills/classes/class.ilContainerMemberSkills.php"); - $mem_skills = new ilContainerMemberSkills($this->container_skills->getId(), $this->user_id); - $mem_levels = $mem_skills->getSkillLevels(); - - // user name - $name = ilObjUser::_lookupName($this->user_id); - $ne = new ilNonEditableValueGUI($this->lng->txt("obj_user"), ""); - $ne->setValue($name["lastname"].", ".$name["firstname"]." [".$name["login"]."]"); - $form->addItem($ne); - - foreach ($this->container_skills->getOrderedSkills() as $sk) - { - $skill = new ilBasicSkill($sk["skill_id"]); - - // skill level options - $options = array( - "-1" => $this->lng->txt("cont_skill_do_not_set"), - ); - foreach ($skill->getLevelData() as $l) - { - $options[$l["id"]] = $l["title"]; - } - $si = new ilSelectInputGUI(ilBasicSkill::_lookupTitle($sk["skill_id"], $sk["tref_id"]), "skill_".$sk["skill_id"]."_".$sk["tref_id"]); - $si->setOptions($options); - $si->setInfo($this->getPathString($sk["skill_id"], $sk["tref_id"])); - if (isset($mem_levels[$sk["skill_id"].":".$sk["tref_id"]])) - { - $si->setValue($mem_levels[$sk["skill_id"].":".$sk["tref_id"]]); - } - $form->addItem($si); - } - - // save and cancel commands - $form->addCommandButton("saveCompetenceAssignment", $this->lng->txt("save")); - $form->addCommandButton("listMembers", $this->lng->txt("cancel")); - - $form->setTitle($this->lng->txt("cont_assign_skills")); - $form->setFormAction($this->ctrl->getFormAction($this)); - - return $form; - } - - /** - * Get path string - * - * @return string path string - */ - function getPathString($a_skill_id, $a_tref_id = 0) - { - $skill_tree = $this->skill_tree; - - $path = $skill_tree->getSkillTreePath($a_skill_id, $a_tref_id); - $titles = array(); - foreach ($path as $v) - { - if ($v["type"] != "skrt" && !($v["skill_id"] == $a_skill_id && $v["tref_id"] == $a_tref_id)) - { - $titles[] = $v["title"]; - } - } - - return implode(" > ", $titles); - } - - /** - * Save competence assignment - * - * @param - */ - function saveCompetenceAssignment() - { - $ctrl = $this->ctrl; - $lng = $this->lng; - - $form = $this->initCompetenceAssignmentForm(); - $form->checkInput(); - - $levels = array(); - foreach ($this->container_skills->getSkills() as $sk) - { - $l = $form->getInput("skill_".$sk["skill_id"]."_".$sk["tref_id"]); - if ($l != -1) - { - $levels[$sk["skill_id"].":".$sk["tref_id"]] = $l; - } - } - - include_once("./Services/Container/Skills/classes/class.ilContainerMemberSkills.php"); - $mem_skills = new ilContainerMemberSkills($this->container_skills->getId(), $this->user_id); - $mem_skills->saveLevelForSkills($levels); - - if (!ilContainer::_lookupContainerSetting($this->container->getId(), "cont_skill_publish", 0)) - { - $mem_skills->publish($this->container->getRefId()); - } - - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ctrl->redirect($this, "listMembers"); - } - - /** - * Publish assignments - */ - function publishAssignments() - { - $ctrl = $this->ctrl; - $lng = $this->lng; - - $user_ids = $_POST["usr_id"]; - if (!is_array($_POST["usr_id"]) && $_GET["usr_id"] > 0) - { - $user_ids[] = $_GET["usr_id"]; - } - - include_once("./Services/Container/Skills/classes/class.ilContainerMemberSkills.php"); - $not_changed = array(); - foreach ($user_ids as $user_id) - { - $mem_skills = new ilContainerMemberSkills($this->container_skills->getId(), $user_id); - if (!$mem_skills->publish($this->container->getRefId())) - { - $not_changed[] = $user_id; - } - } - - if (count($not_changed) == 0) - { - ilUtil::sendSuccess($lng->txt("cont_skll_published"), true); - } - else - { - $names = array_map(function ($id) { - return ilUserUtil::getNamePresentation($id, false, false, "", true); - }, $not_changed); - ilUtil::sendInfo($lng->txt("cont_skll_published_some_not")." (".implode("; ", $names).")", true); - } - - - $ctrl->redirect($this, "listMembers"); - } - - /** - * Deassign competences confirmation - */ - function deassignCompetencesConfirm() - { - $ctrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - $tabs = $this->tabs; - - $tabs->activateSubTab("members"); - - $user_ids = $_POST["usr_id"]; - if (!is_array($_POST["usr_id"]) && $_GET["usr_id"] > 0) - { - $user_ids[] = $_GET["usr_id"]; - } - - if (!is_array($user_ids) || count($user_ids) == 0) - { - ilUtil::sendInfo($lng->txt("no_checkbox"), true); - $ctrl->redirect($this, "listMembers"); - } - else - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ctrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("cont_really_deassign_skills")); - $cgui->setCancel($lng->txt("cancel"), "listMembers"); - $cgui->setConfirm($lng->txt("cont_deassign_competence"), "deassignCompetences"); - - foreach ($user_ids as $i) - { - $name = ilUserUtil::getNamePresentation($i, false, false, "", true); - $cgui->addItem("usr_id[]", $i, $name); - } - - $tpl->setContent($cgui->getHTML()); - } - - } - - /** - * Deassign competences - */ - function deassignCompetences() - { - $ctrl = $this->ctrl; - $lng = $this->lng; - - foreach ($_POST["usr_id"] as $user_id) - { - include_once("./Services/Container/Skills/classes/class.ilContainerMemberSkills.php"); - $mem_skills = new ilContainerMemberSkills($this->container_skills->getId(), $user_id); - $mem_skills->removeAllSkillLevels($this->container->getRefId()); - } - - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ctrl->redirect($this, "listMembers"); - } - - - //// MANAGE COMPETENCES - - /** - * Select competences - */ - function listCompetences() - { - $tpl = $this->tpl; - $tabs = $this->tabs; - $toolbar = $this->toolbar; - $ctrl = $this->ctrl; - $lng = $this->lng; - - $tabs->activateSubTab("competences"); - - $toolbar->addButton($lng->txt("cont_add_skill"), - $ctrl->getLinkTarget($this, "selectSkill")); - - // table - include_once("./Services/Container/Skills/classes/class.ilContSkillTableGUI.php"); - $tab = new ilContSkillTableGUI($this, "listCompetences", $this->container_skills); - - $tpl->setContent($tab->getHTML()); - } - - /** - * Select skill for container - */ - function selectSkill() - { - $tpl = $this->tpl; - $tabs = $this->tabs; - - $tabs->activateSubTab("competences"); - - include_once("./Services/Skill/classes/class.ilSkillSelectorGUI.php"); - $sel = new ilSkillSelectorGUI($this, "selectSkill", $this, "saveSelectedSkill"); - if (!$sel->handleCommand()) - { - $tpl->setContent($sel->getHTML()); - } - } - - /** - * Save selected skill - */ - function saveSelectedSkill() - { - $lng = $this->lng; - $ctrl = $this->ctrl; - - $s = explode(":",($_GET["selected_skill"])); - - $this->container_skills->addSkill((int) $s[0], (int) $s[1]); - $this->container_skills->save(); - - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - - $ctrl->redirect($this, "listCompetences"); - } - - /** - * Confirm - */ - function confirmRemoveSelectedSkill() - { - $lng = $this->lng; - $ctrl = $this->ctrl; - $tpl = $this->tpl; - - if (!is_array($_POST["id"]) || count($_POST["id"]) == 0) - { - ilUtil::sendInfo($lng->txt("no_checkbox"), true); - $ctrl->redirect($this, "listCompetences"); - } - else - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ctrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("cont_really_remove_skill_from_course")); - $cgui->setCancel($lng->txt("cancel"), "listCompetences"); - $cgui->setConfirm($lng->txt("remove"), "removeSelectedSkill"); - - foreach ($_POST["id"] as $i) - { - $s = explode(":", $i); - $cgui->addItem("id[]", $i, ilBasicSkill::_lookupTitle((int) $s[0], (int) $s[1])); - } - - $tpl->setContent($cgui->getHTML()); - } - } - - /** - * Remove skill from course selection - */ - function removeSelectedSkill() - { - $lng = $this->lng; - $ctrl = $this->ctrl; - - if (is_array($_POST["id"]) && count($_POST["id"]) > 0) - { - foreach ($_POST["id"] as $id) - { - $s = explode(":", $id); - $this->container_skills->removeSkill($s[0], $s[1]); - } - $this->container_skills->save(); - } - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - - $ctrl->redirect($this, "listCompetences"); - } - - - //// SETTINGS - - /** - * Settings - */ - function settings() - { - $tpl = $this->tpl; - $tabs = $this->tabs; - - $tabs->activateSubTab("settings"); - - $form = $this->initSettingsForm(); - - $tpl->setContent($form->getHTML()); - } - - /** - * Init settings form. - */ - public function initSettingsForm() - { - $lng = $this->lng; - $ctrl = $this->ctrl; - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - - // publish - $radg = new ilRadioGroupInputGUI($lng->txt("cont_skill_publish"), "cont_skill_publish"); - $op1 = new ilRadioOption($lng->txt("cont_skill_publish_auto"), 0, $lng->txt("cont_skill_publish_auto_info")); - $radg->addOption($op1); - $op2 = new ilRadioOption($lng->txt("cont_skill_publish_manual"), 1, $lng->txt("cont_skill_publish_manual_info")); - $radg->addOption($op2); - $form->addItem($radg); - $radg->setValue(ilContainer::_lookupContainerSetting($this->container->getId(), "cont_skill_publish", 0)); - - $form->addCommandButton("saveSettings", $lng->txt("save")); - - $form->setTitle($lng->txt("settings")); - $form->setFormAction($ctrl->getFormAction($this)); - - return $form; - } - - /** - * Save settings - */ - function saveSettings() - { - $lng = $this->lng; - $ctrl = $this->ctrl; - - $form = $this->initSettingsForm(); - $form->checkInput(); - ilContainer::_writeContainerSetting($this->container->getId(), "cont_skill_publish", $form->getInput("cont_skill_publish")); - - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - - $ctrl->redirect($this, "settings"); - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilContainerGUI + */ + protected $container_gui; + + /** + * @var ilContainer + */ + protected $container; + + /** + * @var ilContainerSkills + */ + protected $container_skills; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * Constructor + * + * @param + */ + public function __construct($a_container_gui) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->tabs = $DIC->tabs(); + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + $this->toolbar = $DIC->toolbar(); + $this->access = $DIC->access(); + + $this->container_gui = $a_container_gui; + $this->container = $a_container_gui->object; + $this->ref_id = $this->container->getRefId(); + + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $this->skill_tree = new ilSkillTree(); + + include_once("./Services/Container/Skills/classes/class.ilContainerSkills.php"); + $this->container_skills = new ilContainerSkills($this->container->getId()); + + $this->user_id = (int) $_GET["usr_id"]; + } + + /** + * Execute command + */ + public function executeCommand() + { + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd("listMembers"); + + switch ($next_class) { + default: + if ( + ($this->access->checkAccess("write", "", $this->ref_id) && + in_array($cmd, array("listCompetences", "settings", "saveSettings", "selectSkill", + "saveSelectedSkill", "confirmRemoveSelectedSkill", "removeSelectedSkill"))) + || + ($this->access->checkAccess("grade", "", $this->ref_id) && + in_array($cmd, array("listMembers", "assignCompetences", + "saveCompetenceAssignment", "publishAssignments", "deassignCompetencesConfirm", "deassignCompetences"))) + ) { + $this->$cmd(); + } + } + } + + //// MANAGE MEMBERS + + /** + * List members + */ + public function listMembers() + { + $tpl = $this->tpl; + $tabs = $this->tabs; + + $tabs->activateSubTab("members"); + + // table + include_once("./Services/Container/Skills/classes/class.ilContSkillMemberTableGUI.php"); + $tab = new ilContSkillMemberTableGUI($this, "listMembers", $this->container_skills); + + $tpl->setContent($tab->getHTML()); + } + + /** + * Assign competences to a member + */ + public function assignCompetences() + { + $tpl = $this->tpl; + $tabs = $this->tabs; + $ctrl = $this->ctrl; + + $ctrl->saveParameter($this, "usr_id"); + $tabs->activateSubTab("members"); + + $form = $this->initCompetenceAssignmentForm(); + $tpl->setContent($form->getHTML()); + } + + /** + * Init competence assignment form + */ + public function initCompetenceAssignmentForm() + { + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + + include_once("./Services/Container/Skills/classes/class.ilContainerMemberSkills.php"); + $mem_skills = new ilContainerMemberSkills($this->container_skills->getId(), $this->user_id); + $mem_levels = $mem_skills->getSkillLevels(); + + // user name + $name = ilObjUser::_lookupName($this->user_id); + $ne = new ilNonEditableValueGUI($this->lng->txt("obj_user"), ""); + $ne->setValue($name["lastname"] . ", " . $name["firstname"] . " [" . $name["login"] . "]"); + $form->addItem($ne); + + foreach ($this->container_skills->getOrderedSkills() as $sk) { + $skill = new ilBasicSkill($sk["skill_id"]); + + // skill level options + $options = array( + "-1" => $this->lng->txt("cont_skill_do_not_set"), + ); + foreach ($skill->getLevelData() as $l) { + $options[$l["id"]] = $l["title"]; + } + $si = new ilSelectInputGUI(ilBasicSkill::_lookupTitle($sk["skill_id"], $sk["tref_id"]), "skill_" . $sk["skill_id"] . "_" . $sk["tref_id"]); + $si->setOptions($options); + $si->setInfo($this->getPathString($sk["skill_id"], $sk["tref_id"])); + if (isset($mem_levels[$sk["skill_id"] . ":" . $sk["tref_id"]])) { + $si->setValue($mem_levels[$sk["skill_id"] . ":" . $sk["tref_id"]]); + } + $form->addItem($si); + } + + // save and cancel commands + $form->addCommandButton("saveCompetenceAssignment", $this->lng->txt("save")); + $form->addCommandButton("listMembers", $this->lng->txt("cancel")); + + $form->setTitle($this->lng->txt("cont_assign_skills")); + $form->setFormAction($this->ctrl->getFormAction($this)); + + return $form; + } + + /** + * Get path string + * + * @return string path string + */ + public function getPathString($a_skill_id, $a_tref_id = 0) + { + $skill_tree = $this->skill_tree; + + $path = $skill_tree->getSkillTreePath($a_skill_id, $a_tref_id); + $titles = array(); + foreach ($path as $v) { + if ($v["type"] != "skrt" && !($v["skill_id"] == $a_skill_id && $v["tref_id"] == $a_tref_id)) { + $titles[] = $v["title"]; + } + } + + return implode(" > ", $titles); + } + + /** + * Save competence assignment + * + * @param + */ + public function saveCompetenceAssignment() + { + $ctrl = $this->ctrl; + $lng = $this->lng; + + $form = $this->initCompetenceAssignmentForm(); + $form->checkInput(); + + $levels = array(); + foreach ($this->container_skills->getSkills() as $sk) { + $l = $form->getInput("skill_" . $sk["skill_id"] . "_" . $sk["tref_id"]); + if ($l != -1) { + $levels[$sk["skill_id"] . ":" . $sk["tref_id"]] = $l; + } + } + + include_once("./Services/Container/Skills/classes/class.ilContainerMemberSkills.php"); + $mem_skills = new ilContainerMemberSkills($this->container_skills->getId(), $this->user_id); + $mem_skills->saveLevelForSkills($levels); + + if (!ilContainer::_lookupContainerSetting($this->container->getId(), "cont_skill_publish", 0)) { + $mem_skills->publish($this->container->getRefId()); + } + + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ctrl->redirect($this, "listMembers"); + } + + /** + * Publish assignments + */ + public function publishAssignments() + { + $ctrl = $this->ctrl; + $lng = $this->lng; + + $user_ids = $_POST["usr_id"]; + if (!is_array($_POST["usr_id"]) && $_GET["usr_id"] > 0) { + $user_ids[] = $_GET["usr_id"]; + } + + include_once("./Services/Container/Skills/classes/class.ilContainerMemberSkills.php"); + $not_changed = array(); + foreach ($user_ids as $user_id) { + $mem_skills = new ilContainerMemberSkills($this->container_skills->getId(), $user_id); + if (!$mem_skills->publish($this->container->getRefId())) { + $not_changed[] = $user_id; + } + } + + if (count($not_changed) == 0) { + ilUtil::sendSuccess($lng->txt("cont_skll_published"), true); + } else { + $names = array_map(function ($id) { + return ilUserUtil::getNamePresentation($id, false, false, "", true); + }, $not_changed); + ilUtil::sendInfo($lng->txt("cont_skll_published_some_not") . " (" . implode("; ", $names) . ")", true); + } + + + $ctrl->redirect($this, "listMembers"); + } + + /** + * Deassign competences confirmation + */ + public function deassignCompetencesConfirm() + { + $ctrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + $tabs = $this->tabs; + + $tabs->activateSubTab("members"); + + $user_ids = $_POST["usr_id"]; + if (!is_array($_POST["usr_id"]) && $_GET["usr_id"] > 0) { + $user_ids[] = $_GET["usr_id"]; + } + + if (!is_array($user_ids) || count($user_ids) == 0) { + ilUtil::sendInfo($lng->txt("no_checkbox"), true); + $ctrl->redirect($this, "listMembers"); + } else { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ctrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("cont_really_deassign_skills")); + $cgui->setCancel($lng->txt("cancel"), "listMembers"); + $cgui->setConfirm($lng->txt("cont_deassign_competence"), "deassignCompetences"); + + foreach ($user_ids as $i) { + $name = ilUserUtil::getNamePresentation($i, false, false, "", true); + $cgui->addItem("usr_id[]", $i, $name); + } + + $tpl->setContent($cgui->getHTML()); + } + } + + /** + * Deassign competences + */ + public function deassignCompetences() + { + $ctrl = $this->ctrl; + $lng = $this->lng; + + foreach ($_POST["usr_id"] as $user_id) { + include_once("./Services/Container/Skills/classes/class.ilContainerMemberSkills.php"); + $mem_skills = new ilContainerMemberSkills($this->container_skills->getId(), $user_id); + $mem_skills->removeAllSkillLevels($this->container->getRefId()); + } + + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ctrl->redirect($this, "listMembers"); + } + + + //// MANAGE COMPETENCES + + /** + * Select competences + */ + public function listCompetences() + { + $tpl = $this->tpl; + $tabs = $this->tabs; + $toolbar = $this->toolbar; + $ctrl = $this->ctrl; + $lng = $this->lng; + + $tabs->activateSubTab("competences"); + + $toolbar->addButton( + $lng->txt("cont_add_skill"), + $ctrl->getLinkTarget($this, "selectSkill") + ); + + // table + include_once("./Services/Container/Skills/classes/class.ilContSkillTableGUI.php"); + $tab = new ilContSkillTableGUI($this, "listCompetences", $this->container_skills); + + $tpl->setContent($tab->getHTML()); + } + + /** + * Select skill for container + */ + public function selectSkill() + { + $tpl = $this->tpl; + $tabs = $this->tabs; + + $tabs->activateSubTab("competences"); + + include_once("./Services/Skill/classes/class.ilSkillSelectorGUI.php"); + $sel = new ilSkillSelectorGUI($this, "selectSkill", $this, "saveSelectedSkill"); + if (!$sel->handleCommand()) { + $tpl->setContent($sel->getHTML()); + } + } + + /** + * Save selected skill + */ + public function saveSelectedSkill() + { + $lng = $this->lng; + $ctrl = $this->ctrl; + + $s = explode(":", ($_GET["selected_skill"])); + + $this->container_skills->addSkill((int) $s[0], (int) $s[1]); + $this->container_skills->save(); + + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + + $ctrl->redirect($this, "listCompetences"); + } + + /** + * Confirm + */ + public function confirmRemoveSelectedSkill() + { + $lng = $this->lng; + $ctrl = $this->ctrl; + $tpl = $this->tpl; + + if (!is_array($_POST["id"]) || count($_POST["id"]) == 0) { + ilUtil::sendInfo($lng->txt("no_checkbox"), true); + $ctrl->redirect($this, "listCompetences"); + } else { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ctrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("cont_really_remove_skill_from_course")); + $cgui->setCancel($lng->txt("cancel"), "listCompetences"); + $cgui->setConfirm($lng->txt("remove"), "removeSelectedSkill"); + + foreach ($_POST["id"] as $i) { + $s = explode(":", $i); + $cgui->addItem("id[]", $i, ilBasicSkill::_lookupTitle((int) $s[0], (int) $s[1])); + } + + $tpl->setContent($cgui->getHTML()); + } + } + + /** + * Remove skill from course selection + */ + public function removeSelectedSkill() + { + $lng = $this->lng; + $ctrl = $this->ctrl; + + if (is_array($_POST["id"]) && count($_POST["id"]) > 0) { + foreach ($_POST["id"] as $id) { + $s = explode(":", $id); + $this->container_skills->removeSkill($s[0], $s[1]); + } + $this->container_skills->save(); + } + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + + $ctrl->redirect($this, "listCompetences"); + } + + + //// SETTINGS + + /** + * Settings + */ + public function settings() + { + $tpl = $this->tpl; + $tabs = $this->tabs; + + $tabs->activateSubTab("settings"); + + $form = $this->initSettingsForm(); + + $tpl->setContent($form->getHTML()); + } + + /** + * Init settings form. + */ + public function initSettingsForm() + { + $lng = $this->lng; + $ctrl = $this->ctrl; + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + + // publish + $radg = new ilRadioGroupInputGUI($lng->txt("cont_skill_publish"), "cont_skill_publish"); + $op1 = new ilRadioOption($lng->txt("cont_skill_publish_auto"), 0, $lng->txt("cont_skill_publish_auto_info")); + $radg->addOption($op1); + $op2 = new ilRadioOption($lng->txt("cont_skill_publish_manual"), 1, $lng->txt("cont_skill_publish_manual_info")); + $radg->addOption($op2); + $form->addItem($radg); + $radg->setValue(ilContainer::_lookupContainerSetting($this->container->getId(), "cont_skill_publish", 0)); + + $form->addCommandButton("saveSettings", $lng->txt("save")); + + $form->setTitle($lng->txt("settings")); + $form->setFormAction($ctrl->getFormAction($this)); + + return $form; + } + + /** + * Save settings + */ + public function saveSettings() + { + $lng = $this->lng; + $ctrl = $this->ctrl; + + $form = $this->initSettingsForm(); + $form->checkInput(); + ilContainer::_writeContainerSetting($this->container->getId(), "cont_skill_publish", $form->getInput("cont_skill_publish")); + + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + + $ctrl->redirect($this, "settings"); + } } - -?> \ No newline at end of file diff --git a/Services/Container/Skills/classes/class.ilContSkillMemberTableGUI.php b/Services/Container/Skills/classes/class.ilContSkillMemberTableGUI.php index 47e8fe8f49093acbf8211a376c8351f8c9b1581f..074822cebe62db81fbe6d3f5927b4275d105e90b 100644 --- a/Services/Container/Skills/classes/class.ilContSkillMemberTableGUI.php +++ b/Services/Container/Skills/classes/class.ilContSkillMemberTableGUI.php @@ -13,156 +13,145 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilContSkillMemberTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilContainerSkills - */ - protected $container_skills; - - /** - * @var \ILIAS\DI\UIServices - */ - protected $ui; - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, ilContainerSkills $a_cont_skills) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - $this->ui = $DIC->ui(); - - $this->setId("cont_skll_mem_".$a_cont_skills->getId()); - - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $this->skill_tree = new ilSkillTree(); - - $this->container_skills = $a_cont_skills; - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setData($this->getMembers()); - $this->setTitle($this->lng->txt("cont_cont_skills")); - - $this->addColumn("", "", "1", true); - $this->addColumn($this->lng->txt("name"), "name"); - $this->addColumn($this->lng->txt("login"), "login"); - $this->addColumn($this->lng->txt("cont_mem_skills"), ""); - $this->addColumn($this->lng->txt("cont_published"), ""); - $this->addColumn($this->lng->txt("actions")); - - $this->setDefaultOrderField("name"); - $this->setDefaultOrderDirection("asc"); - $this->setSelectAllCheckbox("usr_id"); - - $this->setFormAction($this->ctrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.cont_member_skill_row.html", "Services/Container/Skills"); - - if (ilContainer::_lookupContainerSetting($this->container_skills->getId(), "cont_skill_publish", 0)) - { - $this->addMultiCommand("publishAssignments", $this->lng->txt("cont_publish_assignment")); - } - $this->addMultiCommand("deassignCompetencesConfirm", $this->lng->txt("cont_deassign_competence")); - } - - /** - * Get members - * - * @param - * @return - */ - function getMembers() - { - include_once("./Modules/Course/classes/class.ilCourseParticipants.php"); - $p = ilCourseParticipants::getInstanceByObjId($this->container_skills->getId()); - - $members = array(); - foreach ($p->getMembers() as $m) - { - $name = ilObjUser::_lookupName($m); - $members[] = array( - "id" => $m, - "name" => $name["lastname"].", ".$name["firstname"], - "login" => $name["login"], - "skills" => array() - ); - } - return $members; - } - - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $tpl = $this->tpl; - $ctrl = $this->ctrl; - $lng = $this->lng; - $ui = $this->ui; - - // levels - include_once("./Services/Container/Skills/classes/class.ilContainerMemberSkills.php"); - $mskills = new ilContainerMemberSkills($this->container_skills->getId(), $a_set["id"]); - foreach ($mskills->getOrderedSkillLevels() as $sk) - { - $tpl->setCurrentBlock("level"); - $tpl->setVariable("TXT_SKILL", ilBasicSkill::_lookupTitle($sk["skill_id"], $sk["tref_id"])); - $tpl->setVariable("TXT_LEVEL", ilBasicSkill::lookupLevelTitle($sk["level_id"])); - $tpl->setVariable("PATH", $this->getParentObject()->getPathString($sk["skill_id"], $sk["tref_id"])); - $tpl->parseCurrentBlock(); - } - - // published - if ($mskills->getPublished()) - { - $tpl->setVariable("PUBLISHED", $lng->txt("yes")); - } - else - { - $tpl->setVariable("PUBLISHED", $lng->txt("no")); - } - - - $tpl->setVariable("NAME", $a_set["name"]); - $tpl->setVariable("ID", $a_set["id"]); - $tpl->setVariable("LOGIN", $a_set["login"]); - - $ctrl->setParameter($this->parent_obj, "usr_id", $a_set["id"]); - - $items = array(); - $b = $ui->factory()->button(); - if (!$mskills->getPublished() || (!ilContainer::_lookupContainerSetting($this->container_skills->getId(), "cont_skill_publish", 0))) - { - $items[] = $b->shy($lng->txt("cont_assign_competence"), $ctrl->getLinkTarget($this->parent_obj, "assignCompetences")); - } - if (!$mskills->getPublished()) - { - $items[] = $b->shy($lng->txt("cont_publish_assignment"), $ctrl->getLinkTarget($this->parent_obj, "publishAssignments")); - } - $items[] = $b->shy($lng->txt("cont_deassign_competence"), $ctrl->getLinkTarget($this->parent_obj, "deassignCompetencesConfirm")); - $dd = $ui->factory()->dropdown()->standard($items); - - $tpl->setVariable("ACTIONS", $ui->renderer()->render($dd)); - - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilContainerSkills + */ + protected $container_skills; + + /** + * @var \ILIAS\DI\UIServices + */ + protected $ui; + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, ilContainerSkills $a_cont_skills) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + $this->ui = $DIC->ui(); + + $this->setId("cont_skll_mem_" . $a_cont_skills->getId()); + + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $this->skill_tree = new ilSkillTree(); + + $this->container_skills = $a_cont_skills; + + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setData($this->getMembers()); + $this->setTitle($this->lng->txt("cont_cont_skills")); + + $this->addColumn("", "", "1", true); + $this->addColumn($this->lng->txt("name"), "name"); + $this->addColumn($this->lng->txt("login"), "login"); + $this->addColumn($this->lng->txt("cont_mem_skills"), ""); + $this->addColumn($this->lng->txt("cont_published"), ""); + $this->addColumn($this->lng->txt("actions")); + + $this->setDefaultOrderField("name"); + $this->setDefaultOrderDirection("asc"); + $this->setSelectAllCheckbox("usr_id"); + + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.cont_member_skill_row.html", "Services/Container/Skills"); + + if (ilContainer::_lookupContainerSetting($this->container_skills->getId(), "cont_skill_publish", 0)) { + $this->addMultiCommand("publishAssignments", $this->lng->txt("cont_publish_assignment")); + } + $this->addMultiCommand("deassignCompetencesConfirm", $this->lng->txt("cont_deassign_competence")); + } + + /** + * Get members + * + * @param + * @return + */ + public function getMembers() + { + include_once("./Modules/Course/classes/class.ilCourseParticipants.php"); + $p = ilCourseParticipants::getInstanceByObjId($this->container_skills->getId()); + + $members = array(); + foreach ($p->getMembers() as $m) { + $name = ilObjUser::_lookupName($m); + $members[] = array( + "id" => $m, + "name" => $name["lastname"] . ", " . $name["firstname"], + "login" => $name["login"], + "skills" => array() + ); + } + return $members; + } + + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $tpl = $this->tpl; + $ctrl = $this->ctrl; + $lng = $this->lng; + $ui = $this->ui; + + // levels + include_once("./Services/Container/Skills/classes/class.ilContainerMemberSkills.php"); + $mskills = new ilContainerMemberSkills($this->container_skills->getId(), $a_set["id"]); + foreach ($mskills->getOrderedSkillLevels() as $sk) { + $tpl->setCurrentBlock("level"); + $tpl->setVariable("TXT_SKILL", ilBasicSkill::_lookupTitle($sk["skill_id"], $sk["tref_id"])); + $tpl->setVariable("TXT_LEVEL", ilBasicSkill::lookupLevelTitle($sk["level_id"])); + $tpl->setVariable("PATH", $this->getParentObject()->getPathString($sk["skill_id"], $sk["tref_id"])); + $tpl->parseCurrentBlock(); + } + + // published + if ($mskills->getPublished()) { + $tpl->setVariable("PUBLISHED", $lng->txt("yes")); + } else { + $tpl->setVariable("PUBLISHED", $lng->txt("no")); + } + + + $tpl->setVariable("NAME", $a_set["name"]); + $tpl->setVariable("ID", $a_set["id"]); + $tpl->setVariable("LOGIN", $a_set["login"]); + + $ctrl->setParameter($this->parent_obj, "usr_id", $a_set["id"]); + + $items = array(); + $b = $ui->factory()->button(); + if (!$mskills->getPublished() || (!ilContainer::_lookupContainerSetting($this->container_skills->getId(), "cont_skill_publish", 0))) { + $items[] = $b->shy($lng->txt("cont_assign_competence"), $ctrl->getLinkTarget($this->parent_obj, "assignCompetences")); + } + if (!$mskills->getPublished()) { + $items[] = $b->shy($lng->txt("cont_publish_assignment"), $ctrl->getLinkTarget($this->parent_obj, "publishAssignments")); + } + $items[] = $b->shy($lng->txt("cont_deassign_competence"), $ctrl->getLinkTarget($this->parent_obj, "deassignCompetencesConfirm")); + $dd = $ui->factory()->dropdown()->standard($items); + + $tpl->setVariable("ACTIONS", $ui->renderer()->render($dd)); + } } -?> \ No newline at end of file diff --git a/Services/Container/Skills/classes/class.ilContSkillPresentationGUI.php b/Services/Container/Skills/classes/class.ilContSkillPresentationGUI.php index 998b089bd3466c1cacf5eb257eef80eb4fe027ad..fead73763cf7c791f493792c7b90196b3db40acf 100644 --- a/Services/Container/Skills/classes/class.ilContSkillPresentationGUI.php +++ b/Services/Container/Skills/classes/class.ilContSkillPresentationGUI.php @@ -11,145 +11,138 @@ */ class ilContSkillPresentationGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilContainerGUI - */ - protected $container_gui; - - /** - * @var ilContainer - */ - protected $container; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * Constructor - * - * @param - */ - function __construct($a_container_gui) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->tabs = $DIC->tabs(); - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - $this->user = $DIC->user(); - - $this->container_gui = $a_container_gui; - $this->container = $a_container_gui->object; - - include_once("./Services/Container/Skills/classes/class.ilContainerSkills.php"); - $this->container_skills = new ilContainerSkills($this->container->getId()); - - } - - /** - * Execute command - */ - function executeCommand() - { - $ctrl = $this->ctrl; - $tabs = $this->tabs; - - $tabs->activateSubTab("list"); - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd("show"); - - switch ($next_class) - { - case "ilpersonalskillsgui": - $ctrl->forwardCommand($this->getPersonalSkillsGUI()); - break; - - default: - if (in_array($cmd, array("show"))) - { - $this->$cmd(); - } - } - } - - /** - * Get personal skills gui - * - * @return ilPersonalSkillsGUI - */ - protected function getPersonalSkillsGUI() - { - $lng = $this->lng; - - include_once("./Services/Skill/classes/class.ilPersonalSkillsGUI.php"); - $gui = new ilPersonalSkillsGUI(); - $gui->setGapAnalysisActualStatusModePerObject($this->container->getId()); - $gui->setTriggerObjectsFilter($this->getSubtreeObjectIds()); - $gui->setHistoryView(true); // NOT IMPLEMENTED YET - $skills = array_map(function ($v) { - return array( - "base_skill_id" => $v["skill_id"], - "tref_id" => $v["tref_id"] - ); - }, $this->container_skills->getSkills()); - $gui->setObjectSkills($this->container_skills->getId(), $skills); - return $gui; - } - - - - /** - * Show - */ - function show() - { - $gui = $this->getPersonalSkillsGUI(); - $gui->listProfilesForGap(); - } - - protected function getSubtreeObjectIds() - { - global $DIC; /* @var ILIAS\DI\Container $DIC */ - - $nodes = $DIC->repositoryTree()->getSubTree( - $DIC->repositoryTree()->getNodeData( $this->container->getRefId() ) - ); - - $objects = array(); - - foreach($nodes as $node) - { - $objects[] = $node['obj_id']; - } - - - return $objects; - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilContainerGUI + */ + protected $container_gui; + + /** + * @var ilContainer + */ + protected $container; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * Constructor + * + * @param + */ + public function __construct($a_container_gui) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->tabs = $DIC->tabs(); + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + $this->user = $DIC->user(); + + $this->container_gui = $a_container_gui; + $this->container = $a_container_gui->object; + + include_once("./Services/Container/Skills/classes/class.ilContainerSkills.php"); + $this->container_skills = new ilContainerSkills($this->container->getId()); + } + + /** + * Execute command + */ + public function executeCommand() + { + $ctrl = $this->ctrl; + $tabs = $this->tabs; + + $tabs->activateSubTab("list"); + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd("show"); + + switch ($next_class) { + case "ilpersonalskillsgui": + $ctrl->forwardCommand($this->getPersonalSkillsGUI()); + break; + + default: + if (in_array($cmd, array("show"))) { + $this->$cmd(); + } + } + } + + /** + * Get personal skills gui + * + * @return ilPersonalSkillsGUI + */ + protected function getPersonalSkillsGUI() + { + $lng = $this->lng; + + include_once("./Services/Skill/classes/class.ilPersonalSkillsGUI.php"); + $gui = new ilPersonalSkillsGUI(); + $gui->setGapAnalysisActualStatusModePerObject($this->container->getId()); + $gui->setTriggerObjectsFilter($this->getSubtreeObjectIds()); + $gui->setHistoryView(true); // NOT IMPLEMENTED YET + $skills = array_map(function ($v) { + return array( + "base_skill_id" => $v["skill_id"], + "tref_id" => $v["tref_id"] + ); + }, $this->container_skills->getSkills()); + $gui->setObjectSkills($this->container_skills->getId(), $skills); + return $gui; + } + + + + /** + * Show + */ + public function show() + { + $gui = $this->getPersonalSkillsGUI(); + $gui->listProfilesForGap(); + } + + protected function getSubtreeObjectIds() + { + global $DIC; /* @var ILIAS\DI\Container $DIC */ + + $nodes = $DIC->repositoryTree()->getSubTree( + $DIC->repositoryTree()->getNodeData($this->container->getRefId()) + ); + + $objects = array(); + + foreach ($nodes as $node) { + $objects[] = $node['obj_id']; + } + + + return $objects; + } } - -?> \ No newline at end of file diff --git a/Services/Container/Skills/classes/class.ilContSkillTableGUI.php b/Services/Container/Skills/classes/class.ilContSkillTableGUI.php index cc71fff5f07401eecf9c1aec33079e172dcd33f2..bae5968d34c80f1f7bb68c3798f4fba2bff53db9 100644 --- a/Services/Container/Skills/classes/class.ilContSkillTableGUI.php +++ b/Services/Container/Skills/classes/class.ilContSkillTableGUI.php @@ -13,101 +13,97 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilContSkillTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilContainerSkills - */ - protected $container_skills; - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, ilContainerSkills $a_cont_skills) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $this->skill_tree = new ilSkillTree(); - - $this->container_skills = $a_cont_skills; - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setData($this->getSkills()); - $this->setTitle($this->lng->txt("cont_cont_skills")); - - $this->addColumn("", "", "1", true); - $this->addColumn($this->lng->txt("cont_skill"), "", "1"); - $this->addColumn($this->lng->txt("cont_path"), "", "1"); - - $this->setFormAction($this->ctrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.cont_skill_row.html", "Services/Container/Skills"); - $this->setSelectAllCheckbox("id"); - - $this->addMultiCommand("confirmRemoveSelectedSkill", $this->lng->txt("remove")); - //$this->addCommandButton("", $lng->txt("")); - } - - /** - * Get skills - * - * @param - * @return - */ - function getSkills() - { - $skills = array(); - foreach ($this->container_skills->getSkills() as $sk) - { - $skills[] = array( - "skill_id" => $sk["skill_id"], - "tref_id" => $sk["tref_id"], - "title" => ilBasicSkill::_lookupTitle($sk["skill_id"], $sk["tref_id"]) - ); - } - - // order skills per virtual skill tree - include_once("./Services/Skill/classes/class.ilVirtualSkillTree.php"); - $vtree = new ilVirtualSkillTree(); - $skills = $vtree->getOrderedNodeset($skills, "skill_id", "tref_id"); - - return $skills; - } - - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $tpl = $this->tpl; - $skill_tree = $this->skill_tree; - - $tpl->setVariable("TITLE", $a_set["title"]); - $tpl->setVariable("ID", $a_set["skill_id"].":".$a_set["tref_id"]); - - $path = $this->getParentObject()->getPathString($a_set["skill_id"], $a_set["tref_id"]); - - $tpl->setVariable("PATH", $path); - - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilContainerSkills + */ + protected $container_skills; + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, ilContainerSkills $a_cont_skills) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $this->skill_tree = new ilSkillTree(); + + $this->container_skills = $a_cont_skills; + + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setData($this->getSkills()); + $this->setTitle($this->lng->txt("cont_cont_skills")); + + $this->addColumn("", "", "1", true); + $this->addColumn($this->lng->txt("cont_skill"), "", "1"); + $this->addColumn($this->lng->txt("cont_path"), "", "1"); + + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.cont_skill_row.html", "Services/Container/Skills"); + $this->setSelectAllCheckbox("id"); + + $this->addMultiCommand("confirmRemoveSelectedSkill", $this->lng->txt("remove")); + //$this->addCommandButton("", $lng->txt("")); + } + + /** + * Get skills + * + * @param + * @return + */ + public function getSkills() + { + $skills = array(); + foreach ($this->container_skills->getSkills() as $sk) { + $skills[] = array( + "skill_id" => $sk["skill_id"], + "tref_id" => $sk["tref_id"], + "title" => ilBasicSkill::_lookupTitle($sk["skill_id"], $sk["tref_id"]) + ); + } + + // order skills per virtual skill tree + include_once("./Services/Skill/classes/class.ilVirtualSkillTree.php"); + $vtree = new ilVirtualSkillTree(); + $skills = $vtree->getOrderedNodeset($skills, "skill_id", "tref_id"); + + return $skills; + } + + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $tpl = $this->tpl; + $skill_tree = $this->skill_tree; + + $tpl->setVariable("TITLE", $a_set["title"]); + $tpl->setVariable("ID", $a_set["skill_id"] . ":" . $a_set["tref_id"]); + + $path = $this->getParentObject()->getPathString($a_set["skill_id"], $a_set["tref_id"]); + + $tpl->setVariable("PATH", $path); + } } -?> \ No newline at end of file diff --git a/Services/Container/Skills/classes/class.ilContainerMemberSkills.php b/Services/Container/Skills/classes/class.ilContainerMemberSkills.php index f6742828d7ac385770dc207c4b0b839a47680e06..89668d2cb3a835798f073ae205f7e43ce5ecd4ff 100644 --- a/Services/Container/Skills/classes/class.ilContainerMemberSkills.php +++ b/Services/Container/Skills/classes/class.ilContainerMemberSkills.php @@ -10,231 +10,241 @@ class ilContainerMemberSkills { - /** - * @var ilDB - */ - protected $db; - - /** - * @var array - */ - protected $skills = array(); - - /** - * @var int object id - */ - protected $obj_id; - - /** - * @var int - */ - protected $user_id; - - /** - * @var array - */ - protected $skill_levels = array(); - - /** - * @var bool - */ - protected $published = false; - - /** - * Constrictor - * - * @param int $a_obj_id - */ - function __construct($a_obj_id, $a_user_id) - { - global $DIC; - - $this->db = $DIC->database(); - - $this->setObjId($a_obj_id); - $this->setUserId($a_user_id); - if ($a_obj_id > 0 && $a_user_id > 0) - { - $this->read(); - } - } - - /** - * Set object id - * - * @param int $a_val object id - */ - function setObjId($a_val) - { - $this->obj_id = $a_val; - } - - /** - * Get object id - * - * @return int - */ - function getObjId() - { - return $this->obj_id; - } - - /** - * Set user id - * - * @param int $a_val user id - */ - function setUserId($a_val) - { - $this->user_id = $a_val; - } - - /** - * Get user id - * - * @return int - */ - function getUserId() - { - return $this->user_id; - } - - /** - * Read - */ - function read() - { - $db = $this->db; - - $set = $db->query("SELECT * FROM cont_member_skills ". - " WHERE obj_id = ".$db->quote($this->getObjId(), "integer"). - " AND user_id = ".$db->quote($this->getUserId(), "integer") - ); - $this->skill_levels = array(); - while ($rec = $this->db->fetchAssoc($set)) - { - $this->skill_levels[$rec["skill_id"].":".$rec["tref_id"]] = $rec["level_id"]; - $this->published = $rec["published"]; // this is a little weak, but the value should be the same for all save skills - } - } - - /** - * Get Skill levels - * - * @return array (key is skill_id:tref_id, value is level id) - */ - function getSkillLevels() - { - return $this->skill_levels; - } - - /** - * Get ordered skill levels - * - * @return array[] each item comes with keys "level_id", "skill_id", "tref_id" - */ - function getOrderedSkillLevels() - { - $skill_levels = array_map(function ($a, $k) { - $s = explode(":", $k); - return array("level_id" => $a, "skill_id" => $s[0], "tref_id" => $s[1]); - }, $this->getSkillLevels(), array_keys($this->getSkillLevels())); - - include_once("./Services/Skill/classes/class.ilVirtualSkillTree.php"); - $vtree = new ilVirtualSkillTree(); - return $vtree->getOrderedNodeset($skill_levels, "skill_id", "tref_id"); - } - - - /** - * Get published - * - * @return bool - */ - function getPublished() - { - return $this->published; - } - - /** - * Save levels for skills - * - * @param array $a_level_data (key is skill_id:tref_id, value is level id) - */ - function saveLevelForSkills($a_level_data) - { - $db = $this->db; - - $this->delete(); - foreach ($a_level_data as $k => $v) - { - $sk = explode(":", $k); - $db->manipulate("INSERT INTO cont_member_skills ". - "(obj_id, user_id, skill_id, tref_id, level_id, published) VALUES (". - $db->quote($this->getObjId(), "integer").",". - $db->quote($this->getUserId(), "integer").",". - $db->quote($sk[0], "integer").",". - $db->quote($sk[1], "integer").",". - $db->quote($v, "integer").",". - $db->quote(0, "integer"). - ")"); - } - - $this->skill_levels = $a_level_data; - } - - /** - * Delete all level data for current user - * - * @param - */ - function delete() - { - $db = $this->db; - - $db->manipulate("DELETE FROM cont_member_skills WHERE ". - " obj_id = ".$db->quote($this->getObjId(), "integer"). - " AND user_id = ".$db->quote($this->getUserId(), "integer")); - } - - /** - * Publish - */ - function publish($a_ref_id) - { - $db = $this->db; - - $changed = ilBasicSkill::removeAllUserSkillLevelStatusOfObject($this->getUserId(), $this->getObjId(), false, - $this->getObjId()); - - foreach ($this->skill_levels as $sk => $l) - { - $changed = true; - $sk = explode(":", $sk); - ilBasicSkill::writeUserSkillLevelStatus($l, $this->user_id, $a_ref_id, $sk[1], ilBasicSkill::ACHIEVED, - false, false, $this->obj_id); - } - - $db->manipulate("UPDATE cont_member_skills SET ". - " published = ".$db->quote(1, "integer"). - " WHERE obj_id = ".$db->quote($this->getObjId(), "integer"). - " AND user_id = ".$db->quote($this->getUserId(), "integer")); - - return $changed; - } - - - /** - * Remove all skill levels - */ - function removeAllSkillLevels() - { - ilBasicSkill::removeAllUserSkillLevelStatusOfObject($this->getUserId(), $this->getObjId(), false, - $this->getObjId()); - - $this->delete(); - } - + /** + * @var ilDB + */ + protected $db; + + /** + * @var array + */ + protected $skills = array(); + + /** + * @var int object id + */ + protected $obj_id; + + /** + * @var int + */ + protected $user_id; + + /** + * @var array + */ + protected $skill_levels = array(); + + /** + * @var bool + */ + protected $published = false; + + /** + * Constrictor + * + * @param int $a_obj_id + */ + public function __construct($a_obj_id, $a_user_id) + { + global $DIC; + + $this->db = $DIC->database(); + + $this->setObjId($a_obj_id); + $this->setUserId($a_user_id); + if ($a_obj_id > 0 && $a_user_id > 0) { + $this->read(); + } + } + + /** + * Set object id + * + * @param int $a_val object id + */ + public function setObjId($a_val) + { + $this->obj_id = $a_val; + } + + /** + * Get object id + * + * @return int + */ + public function getObjId() + { + return $this->obj_id; + } + + /** + * Set user id + * + * @param int $a_val user id + */ + public function setUserId($a_val) + { + $this->user_id = $a_val; + } + + /** + * Get user id + * + * @return int + */ + public function getUserId() + { + return $this->user_id; + } + + /** + * Read + */ + public function read() + { + $db = $this->db; + + $set = $db->query( + "SELECT * FROM cont_member_skills " . + " WHERE obj_id = " . $db->quote($this->getObjId(), "integer") . + " AND user_id = " . $db->quote($this->getUserId(), "integer") + ); + $this->skill_levels = array(); + while ($rec = $this->db->fetchAssoc($set)) { + $this->skill_levels[$rec["skill_id"] . ":" . $rec["tref_id"]] = $rec["level_id"]; + $this->published = $rec["published"]; // this is a little weak, but the value should be the same for all save skills + } + } + + /** + * Get Skill levels + * + * @return array (key is skill_id:tref_id, value is level id) + */ + public function getSkillLevels() + { + return $this->skill_levels; + } + + /** + * Get ordered skill levels + * + * @return array[] each item comes with keys "level_id", "skill_id", "tref_id" + */ + public function getOrderedSkillLevels() + { + $skill_levels = array_map(function ($a, $k) { + $s = explode(":", $k); + return array("level_id" => $a, "skill_id" => $s[0], "tref_id" => $s[1]); + }, $this->getSkillLevels(), array_keys($this->getSkillLevels())); + + include_once("./Services/Skill/classes/class.ilVirtualSkillTree.php"); + $vtree = new ilVirtualSkillTree(); + return $vtree->getOrderedNodeset($skill_levels, "skill_id", "tref_id"); + } + + + /** + * Get published + * + * @return bool + */ + public function getPublished() + { + return $this->published; + } + + /** + * Save levels for skills + * + * @param array $a_level_data (key is skill_id:tref_id, value is level id) + */ + public function saveLevelForSkills($a_level_data) + { + $db = $this->db; + + $this->delete(); + foreach ($a_level_data as $k => $v) { + $sk = explode(":", $k); + $db->manipulate("INSERT INTO cont_member_skills " . + "(obj_id, user_id, skill_id, tref_id, level_id, published) VALUES (" . + $db->quote($this->getObjId(), "integer") . "," . + $db->quote($this->getUserId(), "integer") . "," . + $db->quote($sk[0], "integer") . "," . + $db->quote($sk[1], "integer") . "," . + $db->quote($v, "integer") . "," . + $db->quote(0, "integer") . + ")"); + } + + $this->skill_levels = $a_level_data; + } + + /** + * Delete all level data for current user + * + * @param + */ + public function delete() + { + $db = $this->db; + + $db->manipulate("DELETE FROM cont_member_skills WHERE " . + " obj_id = " . $db->quote($this->getObjId(), "integer") . + " AND user_id = " . $db->quote($this->getUserId(), "integer")); + } + + /** + * Publish + */ + public function publish($a_ref_id) + { + $db = $this->db; + + $changed = ilBasicSkill::removeAllUserSkillLevelStatusOfObject( + $this->getUserId(), + $this->getObjId(), + false, + $this->getObjId() + ); + + foreach ($this->skill_levels as $sk => $l) { + $changed = true; + $sk = explode(":", $sk); + ilBasicSkill::writeUserSkillLevelStatus( + $l, + $this->user_id, + $a_ref_id, + $sk[1], + ilBasicSkill::ACHIEVED, + false, + false, + $this->obj_id + ); + } + + $db->manipulate("UPDATE cont_member_skills SET " . + " published = " . $db->quote(1, "integer") . + " WHERE obj_id = " . $db->quote($this->getObjId(), "integer") . + " AND user_id = " . $db->quote($this->getUserId(), "integer")); + + return $changed; + } + + + /** + * Remove all skill levels + */ + public function removeAllSkillLevels() + { + ilBasicSkill::removeAllUserSkillLevelStatusOfObject( + $this->getUserId(), + $this->getObjId(), + false, + $this->getObjId() + ); + + $this->delete(); + } } - -?> \ No newline at end of file diff --git a/Services/Container/Skills/classes/class.ilContainerSkillGUI.php b/Services/Container/Skills/classes/class.ilContainerSkillGUI.php index 78bce0f1e1b51206df854b03147f2326e6d43334..76a18d6e24e5be3f489d06dacc2e42314c010a45 100644 --- a/Services/Container/Skills/classes/class.ilContainerSkillGUI.php +++ b/Services/Container/Skills/classes/class.ilContainerSkillGUI.php @@ -11,133 +11,132 @@ */ class ilContainerSkillGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilContainerGUI - */ - protected $container_gui; - - - /** - * @var ilContainer - */ - protected $container; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * Constructor - * - * @param - */ - function __construct($a_container_gui) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->tabs = $DIC->tabs(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - - $this->container_gui = $a_container_gui; - $this->container = $a_container_gui->object; - $this->ref_id = $this->container->getRefId(); - } - - /** - * Execute command - */ - function executeCommand() - { - $ctrl = $this->ctrl; - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd("show"); - - $this->addTabs(); - - switch ($next_class) - { - case "ilcontskillpresentationgui": - if ($this->access->checkAccess("read", "", $this->ref_id)) - { - include_once("./Services/Container/Skills/classes/class.ilContSkillPresentationGUI.php"); - $gui = new ilContSkillPresentationGUI($this->container_gui); - $ctrl->forwardCommand($gui); - } - break; - - case "ilcontskilladmingui": - if ($this->access->checkAccess("write", "", $this->ref_id) || $this->access->checkAccess("grade", "", $this->ref_id)) - { - include_once("./Services/Container/Skills/classes/class.ilContSkillAdminGUI.php"); - $gui = new ilContSkillAdminGUI($this->container_gui); - $ctrl->forwardCommand($gui); - } - break; - - default: - /*if (in_array($cmd, array("show"))) - { - $this->$cmd(); - }*/ - } - } - - /** - * Add tabs - * - * @param - */ - function addTabs() - { - $tabs = $this->tabs; - $lng = $this->lng; - $ctrl = $this->ctrl; - - if ($this->access->checkAccess("read", "", $this->ref_id)) - { - $tabs->addSubTab("list", - $lng->txt("cont_skill_show"), - $ctrl->getLinkTargetByClass("ilContSkillPresentationGUI", "")); - } - - if ($this->access->checkAccess("grade", "", $this->ref_id)) - { - $tabs->addSubTab("members", - $lng->txt("cont_skill_members"), - $ctrl->getLinkTargetByClass("ilContSkillAdminGUI", "listMembers")); - } - - if ($this->access->checkAccess("write", "", $this->ref_id)) - { - $tabs->addSubTab("competences", - $lng->txt("cont_skill_assigned_comp"), - $ctrl->getLinkTargetByClass("ilContSkillAdminGUI", "listCompetences")); - - $tabs->addSubTab("settings", - $lng->txt("settings"), - $ctrl->getLinkTargetByClass("ilContSkillAdminGUI", "settings")); - } - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilContainerGUI + */ + protected $container_gui; + + + /** + * @var ilContainer + */ + protected $container; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * Constructor + * + * @param + */ + public function __construct($a_container_gui) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->tabs = $DIC->tabs(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + + $this->container_gui = $a_container_gui; + $this->container = $a_container_gui->object; + $this->ref_id = $this->container->getRefId(); + } + + /** + * Execute command + */ + public function executeCommand() + { + $ctrl = $this->ctrl; + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd("show"); + + $this->addTabs(); + + switch ($next_class) { + case "ilcontskillpresentationgui": + if ($this->access->checkAccess("read", "", $this->ref_id)) { + include_once("./Services/Container/Skills/classes/class.ilContSkillPresentationGUI.php"); + $gui = new ilContSkillPresentationGUI($this->container_gui); + $ctrl->forwardCommand($gui); + } + break; + + case "ilcontskilladmingui": + if ($this->access->checkAccess("write", "", $this->ref_id) || $this->access->checkAccess("grade", "", $this->ref_id)) { + include_once("./Services/Container/Skills/classes/class.ilContSkillAdminGUI.php"); + $gui = new ilContSkillAdminGUI($this->container_gui); + $ctrl->forwardCommand($gui); + } + break; + + default: + /*if (in_array($cmd, array("show"))) + { + $this->$cmd(); + }*/ + } + } + + /** + * Add tabs + * + * @param + */ + public function addTabs() + { + $tabs = $this->tabs; + $lng = $this->lng; + $ctrl = $this->ctrl; + + if ($this->access->checkAccess("read", "", $this->ref_id)) { + $tabs->addSubTab( + "list", + $lng->txt("cont_skill_show"), + $ctrl->getLinkTargetByClass("ilContSkillPresentationGUI", "") + ); + } + + if ($this->access->checkAccess("grade", "", $this->ref_id)) { + $tabs->addSubTab( + "members", + $lng->txt("cont_skill_members"), + $ctrl->getLinkTargetByClass("ilContSkillAdminGUI", "listMembers") + ); + } + + if ($this->access->checkAccess("write", "", $this->ref_id)) { + $tabs->addSubTab( + "competences", + $lng->txt("cont_skill_assigned_comp"), + $ctrl->getLinkTargetByClass("ilContSkillAdminGUI", "listCompetences") + ); + + $tabs->addSubTab( + "settings", + $lng->txt("settings"), + $ctrl->getLinkTargetByClass("ilContSkillAdminGUI", "settings") + ); + } + } } - -?> \ No newline at end of file diff --git a/Services/Container/Skills/classes/class.ilContainerSkills.php b/Services/Container/Skills/classes/class.ilContainerSkills.php index a9b7c8583aff95870fe0a537a894684db5b93d0a..820d596bf9e455e3ce4120281473cb42b5b4510a 100644 --- a/Services/Container/Skills/classes/class.ilContainerSkills.php +++ b/Services/Container/Skills/classes/class.ilContainerSkills.php @@ -10,163 +10,156 @@ class ilContainerSkills { - /** - * @var ilDB - */ - protected $db; - - /** - * @var array - */ - protected $skills = array(); - - /** - * @var int object id - */ - protected $id; - - /** - * Constrictor - * - * @param int $a_obj_id - */ - function __construct($a_obj_id) - { - global $DIC; - - $this->db = $DIC->database(); - - $this->setId($a_obj_id); - if ($a_obj_id > 0) - { - $this->read(); - } - } - - /** - * Set id - * - * @param int $a_val object id - */ - function setId($a_val) - { - $this->id = $a_val; - } - - /** - * Get id - * - * @return int object id - */ - function getId() - { - return $this->id; - } - - /** - * Reset skills - */ - function resetSkills() - { - $this->skills = array(); - } - - /** - * Add skill - * - * @param int $a_skill_id skill id - * @param int $a_val tref id - */ - function addSkill($a_skill_id, $a_tref_id) - { - $this->skills[$a_skill_id."-".$a_tref_id] = array( - "skill_id" => $a_skill_id, - "tref_id" => $a_tref_id - ); - } - - /** - * Remove skill - * - * @param int $a_skill_id skill id - * @param int $a_val tref id - */ - function removeSkill($a_skill_id, $a_tref_id) - { - unset($this->skills[$a_skill_id."-".$a_tref_id]); - } - - - /** - * Get skills - * - * @return - */ - function getSkills() - { - return $this->skills; - } - - /** - * Get odered skills - * - * @param - * @return - */ - function getOrderedSkills() - { - include_once("./Services/Skill/classes/class.ilVirtualSkillTree.php"); - $vtree = new ilVirtualSkillTree(); - return $vtree->getOrderedNodeset($this->getSkills(), "skill_id", "tref_id"); - } - - - /** - * Read - */ - function read() - { - $db = $this->db; - - $this->skills = array(); - $set = $db->query("SELECT * FROM cont_skills ". - " WHERE id = ".$db->quote($this->getId(), "integer")); - while ($rec = $db->fetchAssoc($set)) - { - $this->skills[$rec["skill_id"]."-".$rec["tref_id"]] = $rec; - } - } - - /** - * Delete - */ - function delete() - { - $db = $this->db; - - $db->manipulate("DELETE FROM cont_skills WHERE ". - " id = ".$db->quote($this->getId(), "integer")); - - } - - /** - * Save - */ - function save() - { - $db = $this->db; - - $this->delete(); - foreach ($this->skills as $s) - { - $db->manipulate("INSERT INTO cont_skills ". - "(id, skill_id, tref_id) VALUES (". - $db->quote($this->getId(), "integer").",". - $db->quote($s["skill_id"], "integer").",". - $db->quote($s["tref_id"], "integer").")"); - } - } - + /** + * @var ilDB + */ + protected $db; + + /** + * @var array + */ + protected $skills = array(); + + /** + * @var int object id + */ + protected $id; + + /** + * Constrictor + * + * @param int $a_obj_id + */ + public function __construct($a_obj_id) + { + global $DIC; + + $this->db = $DIC->database(); + + $this->setId($a_obj_id); + if ($a_obj_id > 0) { + $this->read(); + } + } + + /** + * Set id + * + * @param int $a_val object id + */ + public function setId($a_val) + { + $this->id = $a_val; + } + + /** + * Get id + * + * @return int object id + */ + public function getId() + { + return $this->id; + } + + /** + * Reset skills + */ + public function resetSkills() + { + $this->skills = array(); + } + + /** + * Add skill + * + * @param int $a_skill_id skill id + * @param int $a_val tref id + */ + public function addSkill($a_skill_id, $a_tref_id) + { + $this->skills[$a_skill_id . "-" . $a_tref_id] = array( + "skill_id" => $a_skill_id, + "tref_id" => $a_tref_id + ); + } + + /** + * Remove skill + * + * @param int $a_skill_id skill id + * @param int $a_val tref id + */ + public function removeSkill($a_skill_id, $a_tref_id) + { + unset($this->skills[$a_skill_id . "-" . $a_tref_id]); + } + + + /** + * Get skills + * + * @return + */ + public function getSkills() + { + return $this->skills; + } + + /** + * Get odered skills + * + * @param + * @return + */ + public function getOrderedSkills() + { + include_once("./Services/Skill/classes/class.ilVirtualSkillTree.php"); + $vtree = new ilVirtualSkillTree(); + return $vtree->getOrderedNodeset($this->getSkills(), "skill_id", "tref_id"); + } + + + /** + * Read + */ + public function read() + { + $db = $this->db; + + $this->skills = array(); + $set = $db->query("SELECT * FROM cont_skills " . + " WHERE id = " . $db->quote($this->getId(), "integer")); + while ($rec = $db->fetchAssoc($set)) { + $this->skills[$rec["skill_id"] . "-" . $rec["tref_id"]] = $rec; + } + } + + /** + * Delete + */ + public function delete() + { + $db = $this->db; + + $db->manipulate("DELETE FROM cont_skills WHERE " . + " id = " . $db->quote($this->getId(), "integer")); + } + + /** + * Save + */ + public function save() + { + $db = $this->db; + + $this->delete(); + foreach ($this->skills as $s) { + $db->manipulate("INSERT INTO cont_skills " . + "(id, skill_id, tref_id) VALUES (" . + $db->quote($this->getId(), "integer") . "," . + $db->quote($s["skill_id"], "integer") . "," . + $db->quote($s["tref_id"], "integer") . ")"); + } + } } - -?> \ No newline at end of file diff --git a/Services/Container/classes/class.ilContainer.php b/Services/Container/classes/class.ilContainer.php index 4be0ed72b0739d7fcaca57ab671b1efa05fafef8..6013eec3f6c0ae80f74e72ee52561f4bab3581f2 100755 --- a/Services/Container/classes/class.ilContainer.php +++ b/Services/Container/classes/class.ilContainer.php @@ -1,24 +1,24 @@ +* +* @author Alex Killing * @version $Id$ * * @extends ilObject */ class ilContainer extends ilObject { - /** - * @var ilDB - */ - protected $db; - - /** - * @var Logger - */ - protected $log; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilTree - */ - protected $tree; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilObjectDefinition - */ - protected $obj_definition; - - protected $order_type = 0; - protected $hiddenfilesfound = false; - protected $news_timeline = false; - protected $news_timeline_auto_entries = false; - - // container view constants - const VIEW_SESSIONS = 0; - const VIEW_OBJECTIVE = 1; - const VIEW_TIMING = 2; - const VIEW_ARCHIVE = 3; - const VIEW_SIMPLE = 4; - const VIEW_BY_TYPE = 5; - const VIEW_INHERIT = 6; - - const VIEW_DEFAULT = self::VIEW_BY_TYPE; - - - const SORT_TITLE = 0; - const SORT_MANUAL = 1; - const SORT_ACTIVATION = 2; - const SORT_INHERIT = 3; - const SORT_CREATION = 4; - - const SORT_DIRECTION_ASC = 0; - const SORT_DIRECTION_DESC = 1; - - const SORT_NEW_ITEMS_POSITION_TOP = 0; - const SORT_NEW_ITEMS_POSITION_BOTTOM = 1; - - const SORT_NEW_ITEMS_ORDER_TITLE = 0; - const SORT_NEW_ITEMS_ORDER_CREATION = 1; - const SORT_NEW_ITEMS_ORDER_ACTIVATION = 2; - - static $data_preloaded = false; - - /** - * @var ilSetting - */ - protected $setting; - - /** - * @var ilObjectTranslation - */ - protected $obj_trans = null; - - function __construct($a_id = 0, $a_reference = true) - { - global $DIC; - - $this->db = $DIC->database(); - $this->log = $DIC["ilLog"]; - $this->access = $DIC->access(); - $this->error = $DIC["ilErr"]; - $this->rbacsystem = $DIC->rbac()->system(); - $this->tree = $DIC->repositoryTree(); - $this->user = $DIC->user(); - $this->obj_definition = $DIC["objDefinition"]; - - - $this->setting = $DIC["ilSetting"]; - parent::__construct($a_id, $a_reference); - include_once("./Services/Object/classes/class.ilObjectTranslation.php"); - - if ($this->getId() > 0) - { - $this->obj_trans = ilObjectTranslation::getInstance($this->getId()); - } - } - - /** - * Get object translation - * @return ilObjectTranslation - */ - public function getObjectTranslation() - { - return $this->obj_trans; - } - - /** - * Get object translation - * @param ilObjectTranslation $obj_trans - */ - public function setObjectTranslation(ilObjectTranslation $obj_trans) - { - $this->obj_trans = $obj_trans; - } - - /** - * Create directory for the container. - * It is /container_data. - */ - function createContainerDirectory() - { - $webspace_dir = ilUtil::getWebspaceDir(); - $cont_dir = $webspace_dir."/container_data"; - if (!is_dir($cont_dir)) - { - ilUtil::makeDir($cont_dir); - } - $obj_dir = $cont_dir."/obj_".$this->getId(); - if (!is_dir($obj_dir)) - { - ilUtil::makeDir($obj_dir); - } - } - - /** - * Get the container directory. - * - * @return string container directory - */ - function getContainerDirectory() - { - return $this->_getContainerDirectory($this->getId()); - } - - /** - * Get the container directory. - * - * @return string container directory - */ - static function _getContainerDirectory($a_id) - { - return ilUtil::getWebspaceDir()."/container_data/obj_".$a_id; - } - - /** - * Set Found hidden files (set by getSubItems). - * - * @param boolean $a_hiddenfilesfound Found hidden files (set by getSubItems) - */ - function setHiddenFilesFound($a_hiddenfilesfound) - { - $this->hiddenfilesfound = $a_hiddenfilesfound; - } - - /** - * Get Found hidden files (set by getSubItems). - * - * @return boolean Found hidden files (set by getSubItems) - */ - function getHiddenFilesFound() - { - return $this->hiddenfilesfound; - } - - /** - * get ID of assigned style sheet object - */ - function getStyleSheetId() - { - return $this->style_id; - } - - /** - * set ID of assigned style sheet object - */ - function setStyleSheetId($a_style_id) - { - $this->style_id = $a_style_id; - } - - /** - * Set news timeline - * - * @param bool $a_val activate news timeline - */ - function setNewsTimeline($a_val) - { - $this->news_timeline = $a_val; - } - - /** - * Get news timeline - * - * @return bool activate news timeline - */ - function getNewsTimeline() - { - return $this->news_timeline; - } - - /** - * Set news timeline auto entries - * - * @param bool $a_val include automatically created entries - */ - function setNewsTimelineAutoEntries($a_val) - { - $this->news_timeline_auto_entries = $a_val; - } - - /** - * Get news timeline auto entries - * - * @return bool include automatically created entries - */ - function getNewsTimelineAutoEntries() - { - return $this->news_timeline_auto_entries; - } - - /** - * Set news timline is landing page - * - * @param bool $a_val is news timline landing page? - */ - function setNewsTimelineLandingPage($a_val) - { - $this->news_timeline_landing_page = $a_val; - } - - /** - * Get news timline is landing page - * - * @return bool is news timline landing page? - */ - function getNewsTimelineLandingPage() - { - return $this->news_timeline_landing_page; - } - - /** - * Is news timeline effective? - * - * @return bool - */ - public function isNewsTimelineEffective() - { - if ($this->getUseNews()) - { - if ($this->getNewsTimeline()) - { - return true; - } - } - return false; - } - - /** - * Is news timeline landing page effective? - * - * @return bool - */ - public function isNewsTimelineLandingPageEffective() - { - if ($this->getUseNews()) - { - if ($this->getNewsTimeline()) - { - if ($this->getNewsTimelineLandingPage()) - { - return true; - } - } - } - return false; - } - - - /** - * Set news block activated - * - * @param bool $a_val news block activated - */ - function setNewsBlockActivated($a_val) - { - $this->news_block_activated = $a_val; - } - - /** - * Get news block activated - * - * @return bool news block activated - */ - function getNewsBlockActivated() - { - return $this->news_block_activated; - } - - /** - * Set use news - * - * @param bool $a_val use news system? - */ - function setUseNews($a_val) - { - $this->use_news = $a_val; - } - - /** - * Get use news - * - * @return bool use news system? - */ - function getUseNews() - { - return $this->use_news; - } - - /** - * Lookup a container setting. - * - * @param int container id - * @param string setting keyword - * - * @return string setting value - */ - static function _lookupContainerSetting($a_id, $a_keyword, $a_default_value = NULL) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "SELECT * FROM container_settings WHERE ". - " id = ".$ilDB->quote($a_id ,'integer')." AND ". - " keyword = ".$ilDB->quote($a_keyword ,'text'); - $set = $ilDB->query($q); - $rec = $set->fetchRow(ilDBConstants::FETCHMODE_ASSOC); - - if(isset($rec['value'])) - { - return $rec["value"]; - } - if($a_default_value === NULL) - { - return ''; - } - return $a_default_value; - } - - /** - * @param $a_id - * @param $a_keyword - * @param $a_value - */ - public static function _writeContainerSetting($a_id, $a_keyword, $a_value) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "DELETE FROM container_settings WHERE ". - "id = ".$ilDB->quote($a_id,'integer')." ". - "AND keyword = ".$ilDB->quote($a_keyword,'text'); - $res = $ilDB->manipulate($query); - - $log = ilLoggerFactory::getLogger("cont"); - $log->debug("Write container setting, id: ".$a_id.", keyword: ".$a_keyword.", value: ".$a_value); - - $query = "INSERT INTO container_settings (id, keyword, value) VALUES (". - $ilDB->quote($a_id ,'integer').", ". - $ilDB->quote($a_keyword ,'text').", ". - $ilDB->quote($a_value ,'text'). - ")"; - - $res = $ilDB->manipulate($query); - } - - public static function _getContainerSettings($a_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $res = array(); - - $sql = "SELECT * FROM container_settings WHERE ". - " id = ".$ilDB->quote($a_id ,'integer'); - $set = $ilDB->query($sql); - while($row = $ilDB->fetchAssoc($set)) - { - $res[$row["keyword"]] = $row["value"]; - } - - return $res; - } - - public static function _deleteContainerSettings($a_id, $a_keyword = null, $a_keyword_like = false) - { - global $DIC; - - $ilDB = $DIC->database(); - - if(!$a_id) - { - return; - } - - $sql = "DELETE FROM container_settings WHERE ". - " id = ".$ilDB->quote($a_id ,'integer'); - if($a_keyword) - { - if(!$a_keyword_like) - { - $sql .= " AND keyword = ".$ilDB->quote($a_keyword, "text"); - } - else - { - $sql .= " AND ".$ilDB->like("keyword", "text", $a_keyword); - } - } - $ilDB->manipulate($sql); - } - - public static function _exportContainerSettings(ilXmlWriter $a_xml, $a_obj_id) - { - // container settings - $settings = self::_getContainerSettings($a_obj_id); - if(sizeof($settings)) - { - $a_xml->xmlStartTag("ContainerSettings"); - - foreach($settings as $keyword => $value) - { - // :TODO: proper custom icon export/import - if(stristr($keyword, "icon")) - { - continue; - } - - $a_xml->xmlStartTag( - 'ContainerSetting', - array( - 'id' => $keyword, - ) - ); - - $a_xml->xmlData($value); - $a_xml->xmlEndTag("ContainerSetting"); - } - - $a_xml->xmlEndTag("ContainerSettings"); - } - } - - /** - * Clone container settings - * - * @access public - * @param int target ref_id - * @param int copy id - * @return object new object - */ - public function cloneObject($a_target_id,$a_copy_id = 0, $a_omit_tree = false) - { - /** @var ilObjCourse $new_obj */ - $new_obj = parent::cloneObject($a_target_id,$a_copy_id, $a_omit_tree); - - // translations - include_once("./Services/Object/classes/class.ilObjectTranslation.php"); - $ot = ilObjectTranslation::getInstance($this->getId()); - $ot->copy($new_obj->getId()); - - include_once('./Services/Container/classes/class.ilContainerSortingSettings.php'); - #18624 - copy all sorting settings - ilContainerSortingSettings::_cloneSettings($this->getId(), $new_obj->getId()); - - // copy content page - include_once("./Services/Container/classes/class.ilContainerPage.php"); - if (ilContainerPage::_exists("cont", - $this->getId())) - { - $orig_page = new ilContainerPage($this->getId()); - $orig_page->copy($new_obj->getId(), "cont", $new_obj->getId()); - } - - // #20614 - copy style - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $style_id = $this->getStyleSheetId(); - if ($style_id > 0) - { - if (!!ilObjStyleSheet::_lookupStandard($style_id)) - { - $style_obj = ilObjectFactory::getInstanceByObjId($style_id); - $new_id = $style_obj->ilClone(); - $new_obj->setStyleSheetId($new_id); - $new_obj->update(); - } - else - { - $new_obj->setStyleSheetId($this->getStyleSheetId()); - } - } - - // #10271 - copy start objects page - include_once("./Services/Container/classes/class.ilContainerStartObjectsPage.php"); - if (ilContainerStartObjectsPage::_exists("cstr", - $this->getId())) - { - $orig_page = new ilContainerStartObjectsPage($this->getId()); - $orig_page->copy($new_obj->getId(), "cstr", $new_obj->getId()); - } - - // #10271 - foreach(self::_getContainerSettings($this->getId()) as $keyword => $value) - { - self::_writeContainerSetting($new_obj->getId(), $keyword, $value); - } + /** + * @var ilDB + */ + protected $db; + + /** + * @var Logger + */ + protected $log; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilTree + */ + protected $tree; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilObjectDefinition + */ + protected $obj_definition; + + protected $order_type = 0; + protected $hiddenfilesfound = false; + protected $news_timeline = false; + protected $news_timeline_auto_entries = false; + + // container view constants + const VIEW_SESSIONS = 0; + const VIEW_OBJECTIVE = 1; + const VIEW_TIMING = 2; + const VIEW_ARCHIVE = 3; + const VIEW_SIMPLE = 4; + const VIEW_BY_TYPE = 5; + const VIEW_INHERIT = 6; + + const VIEW_DEFAULT = self::VIEW_BY_TYPE; + + + const SORT_TITLE = 0; + const SORT_MANUAL = 1; + const SORT_ACTIVATION = 2; + const SORT_INHERIT = 3; + const SORT_CREATION = 4; + + const SORT_DIRECTION_ASC = 0; + const SORT_DIRECTION_DESC = 1; + + const SORT_NEW_ITEMS_POSITION_TOP = 0; + const SORT_NEW_ITEMS_POSITION_BOTTOM = 1; + + const SORT_NEW_ITEMS_ORDER_TITLE = 0; + const SORT_NEW_ITEMS_ORDER_CREATION = 1; + const SORT_NEW_ITEMS_ORDER_ACTIVATION = 2; + + public static $data_preloaded = false; + + /** + * @var ilSetting + */ + protected $setting; + + /** + * @var ilObjectTranslation + */ + protected $obj_trans = null; + + public function __construct($a_id = 0, $a_reference = true) + { + global $DIC; + + $this->db = $DIC->database(); + $this->log = $DIC["ilLog"]; + $this->access = $DIC->access(); + $this->error = $DIC["ilErr"]; + $this->rbacsystem = $DIC->rbac()->system(); + $this->tree = $DIC->repositoryTree(); + $this->user = $DIC->user(); + $this->obj_definition = $DIC["objDefinition"]; + + + $this->setting = $DIC["ilSetting"]; + parent::__construct($a_id, $a_reference); + include_once("./Services/Object/classes/class.ilObjectTranslation.php"); + + if ($this->getId() > 0) { + $this->obj_trans = ilObjectTranslation::getInstance($this->getId()); + } + } + + /** + * Get object translation + * @return ilObjectTranslation + */ + public function getObjectTranslation() + { + return $this->obj_trans; + } + + /** + * Get object translation + * @param ilObjectTranslation $obj_trans + */ + public function setObjectTranslation(ilObjectTranslation $obj_trans) + { + $this->obj_trans = $obj_trans; + } + + /** + * Create directory for the container. + * It is /container_data. + */ + public function createContainerDirectory() + { + $webspace_dir = ilUtil::getWebspaceDir(); + $cont_dir = $webspace_dir . "/container_data"; + if (!is_dir($cont_dir)) { + ilUtil::makeDir($cont_dir); + } + $obj_dir = $cont_dir . "/obj_" . $this->getId(); + if (!is_dir($obj_dir)) { + ilUtil::makeDir($obj_dir); + } + } + + /** + * Get the container directory. + * + * @return string container directory + */ + public function getContainerDirectory() + { + return $this->_getContainerDirectory($this->getId()); + } + + /** + * Get the container directory. + * + * @return string container directory + */ + public static function _getContainerDirectory($a_id) + { + return ilUtil::getWebspaceDir() . "/container_data/obj_" . $a_id; + } + + /** + * Set Found hidden files (set by getSubItems). + * + * @param boolean $a_hiddenfilesfound Found hidden files (set by getSubItems) + */ + public function setHiddenFilesFound($a_hiddenfilesfound) + { + $this->hiddenfilesfound = $a_hiddenfilesfound; + } + + /** + * Get Found hidden files (set by getSubItems). + * + * @return boolean Found hidden files (set by getSubItems) + */ + public function getHiddenFilesFound() + { + return $this->hiddenfilesfound; + } + + /** + * get ID of assigned style sheet object + */ + public function getStyleSheetId() + { + return $this->style_id; + } + + /** + * set ID of assigned style sheet object + */ + public function setStyleSheetId($a_style_id) + { + $this->style_id = $a_style_id; + } + + /** + * Set news timeline + * + * @param bool $a_val activate news timeline + */ + public function setNewsTimeline($a_val) + { + $this->news_timeline = $a_val; + } + + /** + * Get news timeline + * + * @return bool activate news timeline + */ + public function getNewsTimeline() + { + return $this->news_timeline; + } + + /** + * Set news timeline auto entries + * + * @param bool $a_val include automatically created entries + */ + public function setNewsTimelineAutoEntries($a_val) + { + $this->news_timeline_auto_entries = $a_val; + } + + /** + * Get news timeline auto entries + * + * @return bool include automatically created entries + */ + public function getNewsTimelineAutoEntries() + { + return $this->news_timeline_auto_entries; + } + + /** + * Set news timline is landing page + * + * @param bool $a_val is news timline landing page? + */ + public function setNewsTimelineLandingPage($a_val) + { + $this->news_timeline_landing_page = $a_val; + } + + /** + * Get news timline is landing page + * + * @return bool is news timline landing page? + */ + public function getNewsTimelineLandingPage() + { + return $this->news_timeline_landing_page; + } + + /** + * Is news timeline effective? + * + * @return bool + */ + public function isNewsTimelineEffective() + { + if ($this->getUseNews()) { + if ($this->getNewsTimeline()) { + return true; + } + } + return false; + } + + /** + * Is news timeline landing page effective? + * + * @return bool + */ + public function isNewsTimelineLandingPageEffective() + { + if ($this->getUseNews()) { + if ($this->getNewsTimeline()) { + if ($this->getNewsTimelineLandingPage()) { + return true; + } + } + } + return false; + } + + + /** + * Set news block activated + * + * @param bool $a_val news block activated + */ + public function setNewsBlockActivated($a_val) + { + $this->news_block_activated = $a_val; + } + + /** + * Get news block activated + * + * @return bool news block activated + */ + public function getNewsBlockActivated() + { + return $this->news_block_activated; + } + + /** + * Set use news + * + * @param bool $a_val use news system? + */ + public function setUseNews($a_val) + { + $this->use_news = $a_val; + } + + /** + * Get use news + * + * @return bool use news system? + */ + public function getUseNews() + { + return $this->use_news; + } + + /** + * Lookup a container setting. + * + * @param int container id + * @param string setting keyword + * + * @return string setting value + */ + public static function _lookupContainerSetting($a_id, $a_keyword, $a_default_value = null) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "SELECT * FROM container_settings WHERE " . + " id = " . $ilDB->quote($a_id, 'integer') . " AND " . + " keyword = " . $ilDB->quote($a_keyword, 'text'); + $set = $ilDB->query($q); + $rec = $set->fetchRow(ilDBConstants::FETCHMODE_ASSOC); + + if (isset($rec['value'])) { + return $rec["value"]; + } + if ($a_default_value === null) { + return ''; + } + return $a_default_value; + } + + /** + * @param $a_id + * @param $a_keyword + * @param $a_value + */ + public static function _writeContainerSetting($a_id, $a_keyword, $a_value) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "DELETE FROM container_settings WHERE " . + "id = " . $ilDB->quote($a_id, 'integer') . " " . + "AND keyword = " . $ilDB->quote($a_keyword, 'text'); + $res = $ilDB->manipulate($query); + + $log = ilLoggerFactory::getLogger("cont"); + $log->debug("Write container setting, id: " . $a_id . ", keyword: " . $a_keyword . ", value: " . $a_value); + + $query = "INSERT INTO container_settings (id, keyword, value) VALUES (" . + $ilDB->quote($a_id, 'integer') . ", " . + $ilDB->quote($a_keyword, 'text') . ", " . + $ilDB->quote($a_value, 'text') . + ")"; + + $res = $ilDB->manipulate($query); + } + + public static function _getContainerSettings($a_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $res = array(); + + $sql = "SELECT * FROM container_settings WHERE " . + " id = " . $ilDB->quote($a_id, 'integer'); + $set = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($set)) { + $res[$row["keyword"]] = $row["value"]; + } + + return $res; + } + + public static function _deleteContainerSettings($a_id, $a_keyword = null, $a_keyword_like = false) + { + global $DIC; + + $ilDB = $DIC->database(); + + if (!$a_id) { + return; + } + + $sql = "DELETE FROM container_settings WHERE " . + " id = " . $ilDB->quote($a_id, 'integer'); + if ($a_keyword) { + if (!$a_keyword_like) { + $sql .= " AND keyword = " . $ilDB->quote($a_keyword, "text"); + } else { + $sql .= " AND " . $ilDB->like("keyword", "text", $a_keyword); + } + } + $ilDB->manipulate($sql); + } + + public static function _exportContainerSettings(ilXmlWriter $a_xml, $a_obj_id) + { + // container settings + $settings = self::_getContainerSettings($a_obj_id); + if (sizeof($settings)) { + $a_xml->xmlStartTag("ContainerSettings"); + + foreach ($settings as $keyword => $value) { + // :TODO: proper custom icon export/import + if (stristr($keyword, "icon")) { + continue; + } + + $a_xml->xmlStartTag( + 'ContainerSetting', + array( + 'id' => $keyword, + ) + ); + + $a_xml->xmlData($value); + $a_xml->xmlEndTag("ContainerSetting"); + } + + $a_xml->xmlEndTag("ContainerSettings"); + } + } + + /** + * Clone container settings + * + * @access public + * @param int target ref_id + * @param int copy id + * @return object new object + */ + public function cloneObject($a_target_id, $a_copy_id = 0, $a_omit_tree = false) + { + /** @var ilObjCourse $new_obj */ + $new_obj = parent::cloneObject($a_target_id, $a_copy_id, $a_omit_tree); + + // translations + include_once("./Services/Object/classes/class.ilObjectTranslation.php"); + $ot = ilObjectTranslation::getInstance($this->getId()); + $ot->copy($new_obj->getId()); + + include_once('./Services/Container/classes/class.ilContainerSortingSettings.php'); + #18624 - copy all sorting settings + ilContainerSortingSettings::_cloneSettings($this->getId(), $new_obj->getId()); + + // copy content page + include_once("./Services/Container/classes/class.ilContainerPage.php"); + if (ilContainerPage::_exists( + "cont", + $this->getId() + )) { + $orig_page = new ilContainerPage($this->getId()); + $orig_page->copy($new_obj->getId(), "cont", $new_obj->getId()); + } + + // #20614 - copy style + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $style_id = $this->getStyleSheetId(); + if ($style_id > 0) { + if (!!ilObjStyleSheet::_lookupStandard($style_id)) { + $style_obj = ilObjectFactory::getInstanceByObjId($style_id); + $new_id = $style_obj->ilClone(); + $new_obj->setStyleSheetId($new_id); + $new_obj->update(); + } else { + $new_obj->setStyleSheetId($this->getStyleSheetId()); + } + } + + // #10271 - copy start objects page + include_once("./Services/Container/classes/class.ilContainerStartObjectsPage.php"); + if (ilContainerStartObjectsPage::_exists( + "cstr", + $this->getId() + )) { + $orig_page = new ilContainerStartObjectsPage($this->getId()); + $orig_page->copy($new_obj->getId(), "cstr", $new_obj->getId()); + } + + // #10271 + foreach (self::_getContainerSettings($this->getId()) as $keyword => $value) { + self::_writeContainerSetting($new_obj->getId(), $keyword, $value); + } $new_obj->setNewsTimeline($this->getNewsTimeline()); $new_obj->setNewsBlockActivated($this->getNewsBlockActivated()); @@ -588,625 +566,587 @@ class ilContainer extends ilObject $mom_noti->cloneSettings($new_obj->getRefId()); return $new_obj; - } - - /** - * Clone object dependencies (container sorting) - * - * @access public - * @param int target ref id of new course - * @param int copy id - * return bool - */ - public function cloneDependencies($a_target_id,$a_copy_id) - { - $ilLog = $this->log; - - parent::cloneDependencies($a_target_id, $a_copy_id); - - include_once('./Services/Container/classes/class.ilContainerSorting.php'); - ilContainerSorting::_getInstance($this->getId())->cloneSorting($a_target_id,$a_copy_id); - - // fix internal links to other objects - ilContainer::fixInternalLinksAfterCopy($a_target_id,$a_copy_id, $this->getRefId()); - - // fix item group references in page content - include_once("./Modules/ItemGroup/classes/class.ilObjItemGroup.php"); - ilObjItemGroup::fixContainerItemGroupRefsAfterCloning($this, $a_copy_id); - - include_once('Services/Object/classes/class.ilObjectLP.php'); - $olp = ilObjectLP::getInstance($this->getId()); - $collection = $olp->getCollectionInstance(); - if($collection) - { - $collection->cloneCollection($a_target_id, $a_copy_id); - } - - return true; - } - - /** - * clone all objects according to this container - * - * @param string $session_id - * @param string $client_id - * @param string $new_type - * @param int $ref_id - * @param int $clone_source - * @param array $options - * @param bool force soap - * @param int submode 1 => copy all, 2 => copy content - * @return new refid if clone has finished or parameter ref id if cloning is still in progress - * @return array(copy_id => xyz, ref_id => new ref_id) - */ - public function cloneAllObject($session_id, $client_id, $new_type, $ref_id, $clone_source, $options, $soap_call = false, $a_submode = 1) - { - $ilLog = $this->log; - - include_once('./Services/Link/classes/class.ilLink.php'); - include_once('Services/CopyWizard/classes/class.ilCopyWizardOptions.php'); - - $ilAccess = $this->access; - $ilErr = $this->error; - $rbacsystem = $this->rbacsystem; - $tree = $this->tree; - $ilUser = $this->user; - - // Save wizard options - $copy_id = ilCopyWizardOptions::_allocateCopyId(); - $wizard_options = ilCopyWizardOptions::_getInstance($copy_id); - $wizard_options->saveOwner($ilUser->getId()); - $wizard_options->saveRoot($clone_source); - - // add entry for source container - $wizard_options->initContainer($clone_source, $ref_id); - - foreach($options as $source_id => $option) - { - $wizard_options->addEntry($source_id,$option); - } - $wizard_options->read(); - $wizard_options->storeTree($clone_source); - - include_once './Services/Object/classes/class.ilObjectCopyGUI.php'; - if($a_submode == ilObjectCopyGUI::SUBMODE_CONTENT_ONLY) - { - ilLoggerFactory::getLogger('obj')->info('Copy content only...'); - ilLoggerFactory::getLogger('obj')->debug('Added mapping, source ID: '.$clone_source.', target ID: '.$ref_id); - $wizard_options->read(); - $wizard_options->dropFirstNode(); - $wizard_options->appendMapping($clone_source,$ref_id); - } - - - #print_r($options); - // Duplicate session to avoid logout problems with backgrounded SOAP calls - $new_session_id = ilSession::_duplicate($session_id); - // Start cloning process using soap call - include_once 'Services/WebServices/SOAP/classes/class.ilSoapClient.php'; - - $soap_client = new ilSoapClient(); - $soap_client->setResponseTimeout(5); - $soap_client->enableWSDL(true); - - $ilLog->write(__METHOD__.': Trying to call Soap client...'); - if($soap_client->init()) - { - ilLoggerFactory::getLogger('obj')->info('Calling soap clone method'); - $res = $soap_client->call('ilClone',array($new_session_id.'::'.$client_id, $copy_id)); - } - else - { - ilLoggerFactory::getLogger('obj')->warning('SOAP clone call failed. Calling clone method manually'); - $wizard_options->disableSOAP(); - $wizard_options->read(); - include_once('./webservice/soap/include/inc.soap_functions.php'); - $res = ilSoapFunctions::ilClone($new_session_id.'::'.$client_id, $copy_id); - } - return array( - 'copy_id' => $copy_id, - 'ref_id' => (int) $res - ); - } - - /** - * delete category and all related data - * - * @return boolean true if all object data were removed; false if only a references were removed - */ - function delete() - { - // always call parent delete function first!! - if (!parent::delete()) - { - return false; - } - // delete translations - $this->obj_trans->delete(); - - return true; - } - - /** - * Get container view mode - */ - function getViewMode() - { - return ilContainer::VIEW_BY_TYPE; - } - - /** - * Get order type default implementation - */ - function getOrderType() - { - return $this->order_type ? $this->order_type : ilContainer::SORT_TITLE; - } - - function setOrderType($a_value) - { - $this->order_type = $a_value; - } - - /** - * Get subitems of container - * - * @param bool administration panel enabled - * @param bool side blocks enabled - * - * @return array - */ - public function getSubItems($a_admin_panel_enabled = false, $a_include_side_block = false, $a_get_single = 0) - { - $objDefinition = $this->obj_definition; - $tree = $this->tree; - - // Caching - if (is_array($this->items[(int) $a_admin_panel_enabled][(int) $a_include_side_block]) && - !$a_get_single) - { - return $this->items[(int) $a_admin_panel_enabled][(int) $a_include_side_block]; - } - - $type_grps = $this->getGroupedObjTypes(); - $objects = $tree->getChilds($this->getRefId(), "title"); - - $objects = self::getCompleteDescriptions($objects); - - $found = false; - $all_ref_ids = array(); - - if(!self::$data_preloaded) - { - include_once("./Services/Object/classes/class.ilObjectListGUIPreloader.php"); - $preloader = new ilObjectListGUIPreloader(ilObjectListGUI::CONTEXT_REPOSITORY); - } - - include_once('Services/Container/classes/class.ilContainerSorting.php'); - $sort = ilContainerSorting::_getInstance($this->getId()); - - // TODO: check this - // get items attached to a session - include_once './Modules/Session/classes/class.ilEventItems.php'; - $event_items = ilEventItems::_getItemsOfContainer($this->getRefId()); - - foreach ($objects as $key => $object) - { - if ($a_get_single > 0 && $object["child"] != $a_get_single) - { - continue; - } - - // hide object types in devmode - if ($objDefinition->getDevMode($object["type"]) || $object["type"] == "adm" - || $object["type"] == "rolf") - { - continue; - } - - // remove inactive plugins - if ($objDefinition->isInactivePlugin($object["type"])) - { - continue; - } - - // BEGIN WebDAV: Don't display hidden Files, Folders and Categories - if (in_array($object['type'], array('file','fold','cat'))) - { - include_once 'Modules/File/classes/class.ilObjFileAccess.php'; - if (ilObjFileAccess::_isFileHidden($object['title'])) - { - $this->setHiddenFilesFound(true); - if (!$a_admin_panel_enabled) - { - continue; - } - } - } - // END WebDAV: Don't display hidden Files, Folders and Categories - - // including event items! - if (!self::$data_preloaded) - { - $preloader->addItem($object["obj_id"], $object["type"], $object["child"]); - } - - // filter out items that are attached to an event - if (in_array($object['ref_id'],$event_items)) - { - continue; - } - - // filter side block items - if(!$a_include_side_block && $objDefinition->isSideBlock($object['type'])) - { - continue; - } - - $all_ref_ids[] = $object["child"]; - } - - // data preloader - if (!self::$data_preloaded) - { - $preloader->preload(); - unset($preloader); - - self::$data_preloaded = true; - } - - foreach($objects as $key => $object) - { - // see above, objects were filtered - if(!in_array($object["child"], $all_ref_ids)) - { - continue; - } - - // group object type groups together (e.g. learning resources) - $type = $objDefinition->getGroupOfObj($object["type"]); - if ($type == "") - { - $type = $object["type"]; - } - - // this will add activation properties - $this->addAdditionalSubItemInformation($object); - - $this->items[$type][$key] = $object; - - $this->items["_all"][$key] = $object; - if ($object["type"] != "sess") - { - $this->items["_non_sess"][$key] = $object; - } - } - - $this->items[(int) $a_admin_panel_enabled][(int) $a_include_side_block] - = $sort->sortItems($this->items); - - return $this->items[(int) $a_admin_panel_enabled][(int) $a_include_side_block]; - } - - /** - * Check whether we got any items - */ - function gotItems() - { - if (is_array($this->items["_all"]) && count($this->items["_all"]) > 0) - { - return true; - } - return false; - } - - /** - * Add additional information to sub item, e.g. used in - * courses for timings information etc. - */ - function addAdditionalSubItemInformation(&$object) - { - } - - /** - * Get grouped repository object types. - * - * @return array array of object types - */ - function getGroupedObjTypes() - { - $objDefinition = $this->obj_definition; - - if (empty($this->type_grps)) - { - $this->type_grps = $objDefinition->getGroupedRepositoryObjectTypes($this->getType()); - } - return $this->type_grps; - } - - /** - * Check whether page editing is allowed for container - */ - function enablePageEditing() - { - $ilSetting = $this->setting; - - // @todo: this will need a more general approach - if ($ilSetting->get("enable_cat_page_edit")) - { - return true; - } - } - - /** - * Create - */ - function create() - { - global $DIC; - - $lng = $DIC->language(); - - $ret = parent::create(); - - // set translation object, since we have an object id now - $this->obj_trans = ilObjectTranslation::getInstance($this->getId()); - - // add default translation - $this->addTranslation($this->getTitle(), - $this->getDescription(), $lng->getDefaultLanguage(), true); - - if (((int) $this->getStyleSheetId()) > 0) - { - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - ilObjStyleSheet::writeStyleUsage($this->getId(), $this->getStyleSheetId()); - } - - $log = ilLoggerFactory::getLogger("cont"); - $log->debug("Create Container, id: ".$this->getId()); - - self::_writeContainerSetting($this->getId(), "news_timeline", (int) $this->getNewsTimeline()); - self::_writeContainerSetting($this->getId(), "news_timeline_incl_auto", (int) $this->getNewsTimelineAutoEntries()); - self::_writeContainerSetting($this->getId(), "news_timeline_landing_page", (int) $this->getNewsTimelineLandingPage()); - include_once("./Services/Object/classes/class.ilObjectServiceSettingsGUI.php"); - self::_writeContainerSetting($this->getId() ,ilObjectServiceSettingsGUI::NEWS_VISIBILITY,(int) $this->getNewsBlockActivated()); - self::_writeContainerSetting($this->getId() ,ilObjectServiceSettingsGUI::USE_NEWS,(int) $this->getUseNews()); - - return $ret; - } - - /** - * @inheritdoc - */ - function putInTree($a_parent_ref) - { - parent::putInTree($a_parent_ref); - - // copy title, icon actions visibilities - if (self::_lookupContainerSetting(ilObject::_lookupObjId($a_parent_ref), "hide_header_icon_and_title")) - { - self::_writeContainerSetting($this->getId(), "hide_header_icon_and_title", true); - } - if (self::_lookupContainerSetting(ilObject::_lookupObjId($a_parent_ref), "hide_top_actions")) - { - self::_writeContainerSetting($this->getId(), "hide_top_actions", true); - } - } - - /** - * Update - */ - function update() - { - $ret = parent::update(); - - $trans = $this->getObjectTranslation(); - $trans->setDefaultTitle($this->getTitle()); - $trans->setDefaultDescription($this->getDescription()); - $trans->save(); - - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - ilObjStyleSheet::writeStyleUsage($this->getId(), $this->getStyleSheetId()); - - $log = ilLoggerFactory::getLogger("cont"); - $log->debug("Update Container, id: ".$this->getId()); - - self::_writeContainerSetting($this->getId(), "news_timeline", (int) $this->getNewsTimeline()); - self::_writeContainerSetting($this->getId(), "news_timeline_incl_auto", (int) $this->getNewsTimelineAutoEntries()); - self::_writeContainerSetting($this->getId(), "news_timeline_landing_page", (int) $this->getNewsTimelineLandingPage()); - include_once("./Services/Object/classes/class.ilObjectServiceSettingsGUI.php"); - self::_writeContainerSetting($this->getId() ,ilObjectServiceSettingsGUI::NEWS_VISIBILITY,(int) $this->getNewsBlockActivated()); - self::_writeContainerSetting($this->getId() ,ilObjectServiceSettingsGUI::USE_NEWS,(int) $this->getUseNews()); - - return $ret; - } - - - /** - * read - * - * @access public - * @param - * @return - */ - public function read() - { - parent::read(); - - include_once("./Services/Container/classes/class.ilContainerSortingSettings.php"); - $this->setOrderType(ilContainerSortingSettings::_lookupSortMode($this->getId())); - - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $this->setStyleSheetId((int) ilObjStyleSheet::lookupObjectStyle($this->getId())); - - $this->readContainerSettings(); - $this->obj_trans = ilObjectTranslation::getInstance($this->getId()); - } - - /** - * Read container settings - * - * @param - * @return - */ - function readContainerSettings() - { - $this->setNewsTimeline(self::_lookupContainerSetting($this->getId(), "news_timeline")); - $this->setNewsTimelineAutoEntries(self::_lookupContainerSetting($this->getId(), "news_timeline_incl_auto")); - $this->setNewsTimelineLandingPage(self::_lookupContainerSetting($this->getId(), "news_timeline_landing_page")); - include_once("./Services/Object/classes/class.ilObjectServiceSettingsGUI.php"); - $this->setNewsBlockActivated(self::_lookupContainerSetting($this->getId(), ilObjectServiceSettingsGUI::NEWS_VISIBILITY, - $this->setting->get('block_activated_news',true))); - $this->setUseNews(self::_lookupContainerSetting($this->getId(), ilObjectServiceSettingsGUI::USE_NEWS, true)); - } - - - /** - * overwrites description fields to long or short description in an assoc array - * keys needed (obj_id and description) - * - * @param array $objects - * @return array - */ - public static function getCompleteDescriptions(array $objects) - { - global $DIC; - - $ilSetting = $DIC->settings(); - $ilObjDataCache = $DIC["ilObjDataCache"]; - // using long descriptions? - $short_desc = $ilSetting->get("rep_shorten_description"); - $short_desc_max_length = $ilSetting->get("rep_shorten_description_length"); - if(!$short_desc || $short_desc_max_length != ilObject::DESC_LENGTH) - { - // using (part of) shortened description - if($short_desc && $short_desc_max_length && $short_desc_max_length < ilObject::DESC_LENGTH) - { - foreach($objects as $key => $object) - { - $objects[$key]["description"] = ilUtil::shortenText($object["description"], $short_desc_max_length, true); - } - } - // using (part of) long description - else - { - $obj_ids = array(); - foreach($objects as $key => $object) - { - $obj_ids[] = $object["obj_id"]; - } - if(sizeof($obj_ids)) - { - $long_desc = ilObject::getLongDescriptions($obj_ids); - foreach($objects as $key => $object) - { - // #12166 - keep translation, ignore long description - if($ilObjDataCache->isTranslatedDescription($object["obj_id"])) - { - $long_desc[$object["obj_id"]] = $object["description"]; - } - if($short_desc && $short_desc_max_length) - { - $long_desc[$object["obj_id"]] = ilUtil::shortenText($long_desc[$object["obj_id"]], $short_desc_max_length, true); - } - $objects[$key]["description"] = $long_desc[$object["obj_id"]]; - } - } - } - } - return $objects; - } - - /** - * Fix internal links after copy process - * - * @param int $a_target_id ref if of new container - * @param int $a_copy_id copy process id - */ - protected static function fixInternalLinksAfterCopy($a_target_id, $a_copy_id, $a_source_ref_id) - { - global $DIC; - - /** @var ilObjectDefinition $obj_definition */ - $obj_definition = $DIC["objDefinition"]; - - $obj_id = ilObject::_lookupObjId($a_target_id); - include_once("./Services/Container/classes/class.ilContainerPage.php"); - if (ilContainerPage::_exists("cont", $obj_id)) - { - include_once("./Services/CopyWizard/classes/class.ilCopyWizardOptions.php"); - $cwo = ilCopyWizardOptions::_getInstance($a_copy_id); - $mapping = $cwo->getMappings(); - $pg = new ilContainerPage($obj_id); - $pg->handleRepositoryLinksOnCopy($mapping, $a_source_ref_id); - $pg->update(true, true); - foreach ($mapping as $old_ref_id => $new_ref_id) - { + } + + /** + * Clone object dependencies (container sorting) + * + * @access public + * @param int target ref id of new course + * @param int copy id + * return bool + */ + public function cloneDependencies($a_target_id, $a_copy_id) + { + $ilLog = $this->log; + + parent::cloneDependencies($a_target_id, $a_copy_id); + + include_once('./Services/Container/classes/class.ilContainerSorting.php'); + ilContainerSorting::_getInstance($this->getId())->cloneSorting($a_target_id, $a_copy_id); + + // fix internal links to other objects + ilContainer::fixInternalLinksAfterCopy($a_target_id, $a_copy_id, $this->getRefId()); + + // fix item group references in page content + include_once("./Modules/ItemGroup/classes/class.ilObjItemGroup.php"); + ilObjItemGroup::fixContainerItemGroupRefsAfterCloning($this, $a_copy_id); + + include_once('Services/Object/classes/class.ilObjectLP.php'); + $olp = ilObjectLP::getInstance($this->getId()); + $collection = $olp->getCollectionInstance(); + if ($collection) { + $collection->cloneCollection($a_target_id, $a_copy_id); + } + + return true; + } + + /** + * clone all objects according to this container + * + * @param string $session_id + * @param string $client_id + * @param string $new_type + * @param int $ref_id + * @param int $clone_source + * @param array $options + * @param bool force soap + * @param int submode 1 => copy all, 2 => copy content + * @return new refid if clone has finished or parameter ref id if cloning is still in progress + * @return array(copy_id => xyz, ref_id => new ref_id) + */ + public function cloneAllObject($session_id, $client_id, $new_type, $ref_id, $clone_source, $options, $soap_call = false, $a_submode = 1) + { + $ilLog = $this->log; + + include_once('./Services/Link/classes/class.ilLink.php'); + include_once('Services/CopyWizard/classes/class.ilCopyWizardOptions.php'); + + $ilAccess = $this->access; + $ilErr = $this->error; + $rbacsystem = $this->rbacsystem; + $tree = $this->tree; + $ilUser = $this->user; + + // Save wizard options + $copy_id = ilCopyWizardOptions::_allocateCopyId(); + $wizard_options = ilCopyWizardOptions::_getInstance($copy_id); + $wizard_options->saveOwner($ilUser->getId()); + $wizard_options->saveRoot($clone_source); + + // add entry for source container + $wizard_options->initContainer($clone_source, $ref_id); + + foreach ($options as $source_id => $option) { + $wizard_options->addEntry($source_id, $option); + } + $wizard_options->read(); + $wizard_options->storeTree($clone_source); + + include_once './Services/Object/classes/class.ilObjectCopyGUI.php'; + if ($a_submode == ilObjectCopyGUI::SUBMODE_CONTENT_ONLY) { + ilLoggerFactory::getLogger('obj')->info('Copy content only...'); + ilLoggerFactory::getLogger('obj')->debug('Added mapping, source ID: ' . $clone_source . ', target ID: ' . $ref_id); + $wizard_options->read(); + $wizard_options->dropFirstNode(); + $wizard_options->appendMapping($clone_source, $ref_id); + } + + + #print_r($options); + // Duplicate session to avoid logout problems with backgrounded SOAP calls + $new_session_id = ilSession::_duplicate($session_id); + // Start cloning process using soap call + include_once 'Services/WebServices/SOAP/classes/class.ilSoapClient.php'; + + $soap_client = new ilSoapClient(); + $soap_client->setResponseTimeout(5); + $soap_client->enableWSDL(true); + + $ilLog->write(__METHOD__ . ': Trying to call Soap client...'); + if ($soap_client->init()) { + ilLoggerFactory::getLogger('obj')->info('Calling soap clone method'); + $res = $soap_client->call('ilClone', array($new_session_id . '::' . $client_id, $copy_id)); + } else { + ilLoggerFactory::getLogger('obj')->warning('SOAP clone call failed. Calling clone method manually'); + $wizard_options->disableSOAP(); + $wizard_options->read(); + include_once('./webservice/soap/include/inc.soap_functions.php'); + $res = ilSoapFunctions::ilClone($new_session_id . '::' . $client_id, $copy_id); + } + return array( + 'copy_id' => $copy_id, + 'ref_id' => (int) $res + ); + } + + /** + * delete category and all related data + * + * @return boolean true if all object data were removed; false if only a references were removed + */ + public function delete() + { + // always call parent delete function first!! + if (!parent::delete()) { + return false; + } + // delete translations + $this->obj_trans->delete(); + + return true; + } + + /** + * Get container view mode + */ + public function getViewMode() + { + return ilContainer::VIEW_BY_TYPE; + } + + /** + * Get order type default implementation + */ + public function getOrderType() + { + return $this->order_type ? $this->order_type : ilContainer::SORT_TITLE; + } + + public function setOrderType($a_value) + { + $this->order_type = $a_value; + } + + /** + * Get subitems of container + * + * @param bool administration panel enabled + * @param bool side blocks enabled + * + * @return array + */ + public function getSubItems($a_admin_panel_enabled = false, $a_include_side_block = false, $a_get_single = 0) + { + $objDefinition = $this->obj_definition; + $tree = $this->tree; + + // Caching + if (is_array($this->items[(int) $a_admin_panel_enabled][(int) $a_include_side_block]) && + !$a_get_single) { + return $this->items[(int) $a_admin_panel_enabled][(int) $a_include_side_block]; + } + + $type_grps = $this->getGroupedObjTypes(); + $objects = $tree->getChilds($this->getRefId(), "title"); + + $objects = self::getCompleteDescriptions($objects); + + $found = false; + $all_ref_ids = array(); + + if (!self::$data_preloaded) { + include_once("./Services/Object/classes/class.ilObjectListGUIPreloader.php"); + $preloader = new ilObjectListGUIPreloader(ilObjectListGUI::CONTEXT_REPOSITORY); + } + + include_once('Services/Container/classes/class.ilContainerSorting.php'); + $sort = ilContainerSorting::_getInstance($this->getId()); + + // TODO: check this + // get items attached to a session + include_once './Modules/Session/classes/class.ilEventItems.php'; + $event_items = ilEventItems::_getItemsOfContainer($this->getRefId()); + + foreach ($objects as $key => $object) { + if ($a_get_single > 0 && $object["child"] != $a_get_single) { + continue; + } + + // hide object types in devmode + if ($objDefinition->getDevMode($object["type"]) || $object["type"] == "adm" + || $object["type"] == "rolf") { + continue; + } + + // remove inactive plugins + if ($objDefinition->isInactivePlugin($object["type"])) { + continue; + } + + // BEGIN WebDAV: Don't display hidden Files, Folders and Categories + if (in_array($object['type'], array('file','fold','cat'))) { + include_once 'Modules/File/classes/class.ilObjFileAccess.php'; + if (ilObjFileAccess::_isFileHidden($object['title'])) { + $this->setHiddenFilesFound(true); + if (!$a_admin_panel_enabled) { + continue; + } + } + } + // END WebDAV: Don't display hidden Files, Folders and Categories + + // including event items! + if (!self::$data_preloaded) { + $preloader->addItem($object["obj_id"], $object["type"], $object["child"]); + } + + // filter out items that are attached to an event + if (in_array($object['ref_id'], $event_items)) { + continue; + } + + // filter side block items + if (!$a_include_side_block && $objDefinition->isSideBlock($object['type'])) { + continue; + } + + $all_ref_ids[] = $object["child"]; + } + + // data preloader + if (!self::$data_preloaded) { + $preloader->preload(); + unset($preloader); + + self::$data_preloaded = true; + } + + foreach ($objects as $key => $object) { + // see above, objects were filtered + if (!in_array($object["child"], $all_ref_ids)) { + continue; + } + + // group object type groups together (e.g. learning resources) + $type = $objDefinition->getGroupOfObj($object["type"]); + if ($type == "") { + $type = $object["type"]; + } + + // this will add activation properties + $this->addAdditionalSubItemInformation($object); + + $this->items[$type][$key] = $object; + + $this->items["_all"][$key] = $object; + if ($object["type"] != "sess") { + $this->items["_non_sess"][$key] = $object; + } + } + + $this->items[(int) $a_admin_panel_enabled][(int) $a_include_side_block] + = $sort->sortItems($this->items); + + return $this->items[(int) $a_admin_panel_enabled][(int) $a_include_side_block]; + } + + /** + * Check whether we got any items + */ + public function gotItems() + { + if (is_array($this->items["_all"]) && count($this->items["_all"]) > 0) { + return true; + } + return false; + } + + /** + * Add additional information to sub item, e.g. used in + * courses for timings information etc. + */ + public function addAdditionalSubItemInformation(&$object) + { + } + + /** + * Get grouped repository object types. + * + * @return array array of object types + */ + public function getGroupedObjTypes() + { + $objDefinition = $this->obj_definition; + + if (empty($this->type_grps)) { + $this->type_grps = $objDefinition->getGroupedRepositoryObjectTypes($this->getType()); + } + return $this->type_grps; + } + + /** + * Check whether page editing is allowed for container + */ + public function enablePageEditing() + { + $ilSetting = $this->setting; + + // @todo: this will need a more general approach + if ($ilSetting->get("enable_cat_page_edit")) { + return true; + } + } + + /** + * Create + */ + public function create() + { + global $DIC; + + $lng = $DIC->language(); + + $ret = parent::create(); + + // set translation object, since we have an object id now + $this->obj_trans = ilObjectTranslation::getInstance($this->getId()); + + // add default translation + $this->addTranslation( + $this->getTitle(), + $this->getDescription(), + $lng->getDefaultLanguage(), + true + ); + + if (((int) $this->getStyleSheetId()) > 0) { + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + ilObjStyleSheet::writeStyleUsage($this->getId(), $this->getStyleSheetId()); + } + + $log = ilLoggerFactory::getLogger("cont"); + $log->debug("Create Container, id: " . $this->getId()); + + self::_writeContainerSetting($this->getId(), "news_timeline", (int) $this->getNewsTimeline()); + self::_writeContainerSetting($this->getId(), "news_timeline_incl_auto", (int) $this->getNewsTimelineAutoEntries()); + self::_writeContainerSetting($this->getId(), "news_timeline_landing_page", (int) $this->getNewsTimelineLandingPage()); + include_once("./Services/Object/classes/class.ilObjectServiceSettingsGUI.php"); + self::_writeContainerSetting($this->getId(), ilObjectServiceSettingsGUI::NEWS_VISIBILITY, (int) $this->getNewsBlockActivated()); + self::_writeContainerSetting($this->getId(), ilObjectServiceSettingsGUI::USE_NEWS, (int) $this->getUseNews()); + + return $ret; + } + + /** + * @inheritdoc + */ + public function putInTree($a_parent_ref) + { + parent::putInTree($a_parent_ref); + + // copy title, icon actions visibilities + if (self::_lookupContainerSetting(ilObject::_lookupObjId($a_parent_ref), "hide_header_icon_and_title")) { + self::_writeContainerSetting($this->getId(), "hide_header_icon_and_title", true); + } + if (self::_lookupContainerSetting(ilObject::_lookupObjId($a_parent_ref), "hide_top_actions")) { + self::_writeContainerSetting($this->getId(), "hide_top_actions", true); + } + } + + /** + * Update + */ + public function update() + { + $ret = parent::update(); + + $trans = $this->getObjectTranslation(); + $trans->setDefaultTitle($this->getTitle()); + $trans->setDefaultDescription($this->getDescription()); + $trans->save(); + + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + ilObjStyleSheet::writeStyleUsage($this->getId(), $this->getStyleSheetId()); + + $log = ilLoggerFactory::getLogger("cont"); + $log->debug("Update Container, id: " . $this->getId()); + + self::_writeContainerSetting($this->getId(), "news_timeline", (int) $this->getNewsTimeline()); + self::_writeContainerSetting($this->getId(), "news_timeline_incl_auto", (int) $this->getNewsTimelineAutoEntries()); + self::_writeContainerSetting($this->getId(), "news_timeline_landing_page", (int) $this->getNewsTimelineLandingPage()); + include_once("./Services/Object/classes/class.ilObjectServiceSettingsGUI.php"); + self::_writeContainerSetting($this->getId(), ilObjectServiceSettingsGUI::NEWS_VISIBILITY, (int) $this->getNewsBlockActivated()); + self::_writeContainerSetting($this->getId(), ilObjectServiceSettingsGUI::USE_NEWS, (int) $this->getUseNews()); + + return $ret; + } + + + /** + * read + * + * @access public + * @param + * @return + */ + public function read() + { + parent::read(); + + include_once("./Services/Container/classes/class.ilContainerSortingSettings.php"); + $this->setOrderType(ilContainerSortingSettings::_lookupSortMode($this->getId())); + + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $this->setStyleSheetId((int) ilObjStyleSheet::lookupObjectStyle($this->getId())); + + $this->readContainerSettings(); + $this->obj_trans = ilObjectTranslation::getInstance($this->getId()); + } + + /** + * Read container settings + * + * @param + * @return + */ + public function readContainerSettings() + { + $this->setNewsTimeline(self::_lookupContainerSetting($this->getId(), "news_timeline")); + $this->setNewsTimelineAutoEntries(self::_lookupContainerSetting($this->getId(), "news_timeline_incl_auto")); + $this->setNewsTimelineLandingPage(self::_lookupContainerSetting($this->getId(), "news_timeline_landing_page")); + include_once("./Services/Object/classes/class.ilObjectServiceSettingsGUI.php"); + $this->setNewsBlockActivated(self::_lookupContainerSetting( + $this->getId(), + ilObjectServiceSettingsGUI::NEWS_VISIBILITY, + $this->setting->get('block_activated_news', true) + )); + $this->setUseNews(self::_lookupContainerSetting($this->getId(), ilObjectServiceSettingsGUI::USE_NEWS, true)); + } + + + /** + * overwrites description fields to long or short description in an assoc array + * keys needed (obj_id and description) + * + * @param array $objects + * @return array + */ + public static function getCompleteDescriptions(array $objects) + { + global $DIC; + + $ilSetting = $DIC->settings(); + $ilObjDataCache = $DIC["ilObjDataCache"]; + // using long descriptions? + $short_desc = $ilSetting->get("rep_shorten_description"); + $short_desc_max_length = $ilSetting->get("rep_shorten_description_length"); + if (!$short_desc || $short_desc_max_length != ilObject::DESC_LENGTH) { + // using (part of) shortened description + if ($short_desc && $short_desc_max_length && $short_desc_max_length < ilObject::DESC_LENGTH) { + foreach ($objects as $key => $object) { + $objects[$key]["description"] = ilUtil::shortenText($object["description"], $short_desc_max_length, true); + } + } + // using (part of) long description + else { + $obj_ids = array(); + foreach ($objects as $key => $object) { + $obj_ids[] = $object["obj_id"]; + } + if (sizeof($obj_ids)) { + $long_desc = ilObject::getLongDescriptions($obj_ids); + foreach ($objects as $key => $object) { + // #12166 - keep translation, ignore long description + if ($ilObjDataCache->isTranslatedDescription($object["obj_id"])) { + $long_desc[$object["obj_id"]] = $object["description"]; + } + if ($short_desc && $short_desc_max_length) { + $long_desc[$object["obj_id"]] = ilUtil::shortenText($long_desc[$object["obj_id"]], $short_desc_max_length, true); + } + $objects[$key]["description"] = $long_desc[$object["obj_id"]]; + } + } + } + } + return $objects; + } + + /** + * Fix internal links after copy process + * + * @param int $a_target_id ref if of new container + * @param int $a_copy_id copy process id + */ + protected static function fixInternalLinksAfterCopy($a_target_id, $a_copy_id, $a_source_ref_id) + { + global $DIC; + + /** @var ilObjectDefinition $obj_definition */ + $obj_definition = $DIC["objDefinition"]; + + $obj_id = ilObject::_lookupObjId($a_target_id); + include_once("./Services/Container/classes/class.ilContainerPage.php"); + if (ilContainerPage::_exists("cont", $obj_id)) { + include_once("./Services/CopyWizard/classes/class.ilCopyWizardOptions.php"); + $cwo = ilCopyWizardOptions::_getInstance($a_copy_id); + $mapping = $cwo->getMappings(); + $pg = new ilContainerPage($obj_id); + $pg->handleRepositoryLinksOnCopy($mapping, $a_source_ref_id); + $pg->update(true, true); + foreach ($mapping as $old_ref_id => $new_ref_id) { if (!is_int($old_ref_id) || !is_int($new_ref_id)) { continue; } - $type = ilObject::_lookupType($new_ref_id, true); - $class = "il".$obj_definition->getClassName($type)."PageCollector"; - $loc = $obj_definition->getLocation($type); - $file = $loc."/class.".$class.".php"; - if (is_file($file)) - { - include_once($file); - /** @var ilCOPageCollectorInterface $coll */ - $coll = new $class(); - foreach ($coll->getAllPageIds(ilObject::_lookupObjId($new_ref_id)) as $page_id) - { - if (ilPageObject::_exists($page_id["parent_type"], $page_id["id"], $page_id["lang"])) - { - /** @var ilPageObject $page */ - $page = ilPageObjectFactory::getInstance($page_id["parent_type"], $page_id["id"], 0, $page_id["lang"]); - $page->handleRepositoryLinksOnCopy($mapping, $a_source_ref_id); - $page->update(true, true); - } - } - } - } - } - } - - /** - * Remove all translations of container - */ - function removeTranslations() - { - $this->obj_trans->delete(); - } - - /** - * Delete translation - * - * @param $a_lang - */ - function deleteTranslation($a_lang) - { - $this->obj_trans->removeLanguage($a_lang); - $this->obj_trans->save(); - } - - /** - * Add translation - * - * @param $a_title - * @param $a_desc - * @param $a_lang - * @param $a_lang_default - * @return bool - */ - function addTranslation($a_title,$a_desc,$a_lang,$a_lang_default) - { - if (empty($a_title)) - { - $a_title = "NO TITLE"; - } - - $this->obj_trans->addLanguage($a_lang, $a_title, $a_desc, $a_lang_default, true); - $this->obj_trans->save(); - - return true; - } -} \ No newline at end of file + $type = ilObject::_lookupType($new_ref_id, true); + $class = "il" . $obj_definition->getClassName($type) . "PageCollector"; + $loc = $obj_definition->getLocation($type); + $file = $loc . "/class." . $class . ".php"; + if (is_file($file)) { + include_once($file); + /** @var ilCOPageCollectorInterface $coll */ + $coll = new $class(); + foreach ($coll->getAllPageIds(ilObject::_lookupObjId($new_ref_id)) as $page_id) { + if (ilPageObject::_exists($page_id["parent_type"], $page_id["id"], $page_id["lang"])) { + /** @var ilPageObject $page */ + $page = ilPageObjectFactory::getInstance($page_id["parent_type"], $page_id["id"], 0, $page_id["lang"]); + $page->handleRepositoryLinksOnCopy($mapping, $a_source_ref_id); + $page->update(true, true); + } + } + } + } + } + } + + /** + * Remove all translations of container + */ + public function removeTranslations() + { + $this->obj_trans->delete(); + } + + /** + * Delete translation + * + * @param $a_lang + */ + public function deleteTranslation($a_lang) + { + $this->obj_trans->removeLanguage($a_lang); + $this->obj_trans->save(); + } + + /** + * Add translation + * + * @param $a_title + * @param $a_desc + * @param $a_lang + * @param $a_lang_default + * @return bool + */ + public function addTranslation($a_title, $a_desc, $a_lang, $a_lang_default) + { + if (empty($a_title)) { + $a_title = "NO TITLE"; + } + + $this->obj_trans->addLanguage($a_lang, $a_title, $a_desc, $a_lang_default, true); + $this->obj_trans->save(); + + return true; + } +} diff --git a/Services/Container/classes/class.ilContainerAccess.php b/Services/Container/classes/class.ilContainerAccess.php index 7777af31d237941e951cab202ab25a286335ac28..41a07cc431a1bf3eed6a6cb1c81a6e5b1218ad00 100644 --- a/Services/Container/classes/class.ilContainerAccess.php +++ b/Services/Container/classes/class.ilContainerAccess.php @@ -13,25 +13,24 @@ */ class ilContainerAccess implements \ilWACCheckingClass { - /** - * @param ilWACPath $ilWACPath - * - * @return bool - */ - public function canBeDelivered(ilWACPath $ilWACPath) { - global $DIC; + /** + * @param ilWACPath $ilWACPath + * + * @return bool + */ + public function canBeDelivered(ilWACPath $ilWACPath) + { + global $DIC; - $access = $DIC->access(); + $access = $DIC->access(); - preg_match("/\\/obj_([\\d]*)\\//uism", $ilWACPath->getPath(), $results); - foreach (ilObject2::_getAllReferences($results[1]) as $ref_id) { - if ($access->checkAccess('visible', '', $ref_id) || $access->checkAccess('read', '', $ref_id)) { - return true; - } - } + preg_match("/\\/obj_([\\d]*)\\//uism", $ilWACPath->getPath(), $results); + foreach (ilObject2::_getAllReferences($results[1]) as $ref_id) { + if ($access->checkAccess('visible', '', $ref_id) || $access->checkAccess('read', '', $ref_id)) { + return true; + } + } - return false; - } + return false; + } } - -?> \ No newline at end of file diff --git a/Services/Container/classes/class.ilContainerBlockPropertiesStorage.php b/Services/Container/classes/class.ilContainerBlockPropertiesStorage.php index b7401b8cb49024f5418deca6c095c2f608db10f9..26bfd30c6792b356bb0b1ffc05324e3c85520ecb 100644 --- a/Services/Container/classes/class.ilContainerBlockPropertiesStorage.php +++ b/Services/Container/classes/class.ilContainerBlockPropertiesStorage.php @@ -10,97 +10,91 @@ */ class ilContainerBlockPropertiesStorage { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - /** - * Constructor - */ - function __construct() - { - global $DIC; + /** + * Constructor + */ + public function __construct() + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->user = $DIC->user(); - } + $this->ctrl = $DIC->ctrl(); + $this->user = $DIC->user(); + } - /** - * execute command - */ - function &executeCommand() - { - $ilCtrl = $this->ctrl; + /** + * execute command + */ + public function &executeCommand() + { + $ilCtrl = $this->ctrl; - $cmd = $ilCtrl->getCmd(); - if (in_array($cmd, array("store"))) - { - $this->$cmd(); - } - } - - /** - * Store property - */ - function store() - { - $ilUser = $this->user; + $cmd = $ilCtrl->getCmd(); + if (in_array($cmd, array("store"))) { + $this->$cmd(); + } + } + + /** + * Store property + */ + public function store() + { + $ilUser = $this->user; - switch ($_GET["act"]) - { + switch ($_GET["act"]) { - case "expand": - self::storeProperty($_GET["cont_block_id"], (int) $ilUser->getId(), "opened", "1"); - break; - - case "collapse": - self::storeProperty($_GET["cont_block_id"], (int) $ilUser->getId(), "opened", "0"); - break; - } - } - - /** - * Store property in session or db - * - * @param string $a_block_id - * @param int $a_user_id - * @param string $a_property - * @param string $a_value - */ - static function storeProperty($a_block_id, $a_user_id, $a_property, $a_value) - { - $_SESSION["cont_block"][$a_block_id][$a_user_id][$a_property] = $a_value; - ilLoggerFactory::getLogger("cont") - ->debug("block id: ".$a_block_id.", user id: ".$a_user_id.", property: ".$a_property.", val: ".print_r($a_value, true)); - } - - /** - * Get property in session or db - * - * @param string $a_block_id - * @param int $a_user_id - * @param string $a_property - * @return bool|string - */ - static function getProperty($a_block_id, $a_user_id, $a_property) - { - $val = false; - if (isset($_SESSION["cont_block"][$a_block_id][$a_user_id][$a_property])) - { - $val = $_SESSION["cont_block"][$a_block_id][$a_user_id][$a_property]; - } - ilLoggerFactory::getLogger("cont") - ->debug("block id: ".$a_block_id.", user id: ".$a_user_id.", property: ".$a_property.", val: ".print_r($val, true)); - return $val; - } - + case "expand": + self::storeProperty($_GET["cont_block_id"], (int) $ilUser->getId(), "opened", "1"); + break; + case "collapse": + self::storeProperty($_GET["cont_block_id"], (int) $ilUser->getId(), "opened", "0"); + break; + } + } + + /** + * Store property in session or db + * + * @param string $a_block_id + * @param int $a_user_id + * @param string $a_property + * @param string $a_value + */ + public static function storeProperty($a_block_id, $a_user_id, $a_property, $a_value) + { + $_SESSION["cont_block"][$a_block_id][$a_user_id][$a_property] = $a_value; + ilLoggerFactory::getLogger("cont") + ->debug("block id: " . $a_block_id . ", user id: " . $a_user_id . ", property: " . $a_property . ", val: " . print_r($a_value, true)); + } + + /** + * Get property in session or db + * + * @param string $a_block_id + * @param int $a_user_id + * @param string $a_property + * @return bool|string + */ + public static function getProperty($a_block_id, $a_user_id, $a_property) + { + $val = false; + if (isset($_SESSION["cont_block"][$a_block_id][$a_user_id][$a_property])) { + $val = $_SESSION["cont_block"][$a_block_id][$a_user_id][$a_property]; + } + ilLoggerFactory::getLogger("cont") + ->debug("block id: " . $a_block_id . ", user id: " . $a_user_id . ", property: " . $a_property . ", val: " . print_r($val, true)); + return $val; + } } -?> diff --git a/Services/Container/classes/class.ilContainerByTypeContentGUI.php b/Services/Container/classes/class.ilContainerByTypeContentGUI.php index ba4e20f3796274753e24a8858f8784146b3d7619..f91a751ca3733bce399c58d0d9024daf6e0dea34 100644 --- a/Services/Container/classes/class.ilContainerByTypeContentGUI.php +++ b/Services/Container/classes/class.ilContainerByTypeContentGUI.php @@ -1,24 +1,24 @@ access = $DIC->access(); - $this->user = $DIC->user(); - parent::__construct($container_gui_obj); - $this->initDetails(); - $this->block_limit = (int) ilContainer::_lookupContainerSetting($container_gui_obj->object->getId(), "block_limit"); - } - - /** - * get details level - * - * @access public - * @param int $a_session_id - * @return int DEATAILS_LEVEL - */ - public function getDetailsLevel($a_session_id) - { - if($this->getContainerGUI()->isActiveAdministrationPanel()) - { - return self::DETAILS_DEACTIVATED; - } - if(isset($_SESSION['sess']['expanded'][$a_session_id])) - { - return $_SESSION['sess']['expanded'][$a_session_id]; - } - if($a_session_id == $this->force_details) - { - return self::DETAILS_ALL; - } - else - { - return self::DETAILS_TITLE; - } - } - + $this->access = $DIC->access(); + $this->user = $DIC->user(); + parent::__construct($container_gui_obj); + $this->initDetails(); + $this->block_limit = (int) ilContainer::_lookupContainerSetting($container_gui_obj->object->getId(), "block_limit"); + } + + /** + * get details level + * + * @access public + * @param int $a_session_id + * @return int DEATAILS_LEVEL + */ + public function getDetailsLevel($a_session_id) + { + if ($this->getContainerGUI()->isActiveAdministrationPanel()) { + return self::DETAILS_DEACTIVATED; + } + if (isset($_SESSION['sess']['expanded'][$a_session_id])) { + return $_SESSION['sess']['expanded'][$a_session_id]; + } + if ($a_session_id == $this->force_details) { + return self::DETAILS_ALL; + } else { + return self::DETAILS_TITLE; + } + } + - /** - * Get content HTML for main column. - */ - function getMainContent() - { - $ilAccess = $this->access; + /** + * Get content HTML for main column. + */ + public function getMainContent() + { + $ilAccess = $this->access; - $tpl = new ilTemplate("tpl.container_page.html", true, true, - "Services/Container"); - - // get all sub items - $this->items = $this->getContainerObject()->getSubItems( - $this->getContainerGUI()->isActiveAdministrationPanel()); + $tpl = new ilTemplate( + "tpl.container_page.html", + true, + true, + "Services/Container" + ); + + // get all sub items + $this->items = $this->getContainerObject()->getSubItems( + $this->getContainerGUI()->isActiveAdministrationPanel() + ); - // Show introduction, if repository is empty - // @todo: maybe we move this - if ((!is_array($this->items) || count($this->items) == 0) && - $this->getContainerObject()->getRefId() == ROOT_FOLDER_ID && - $ilAccess->checkAccess("write", "", $this->getContainerObject()->getRefId())) - { - $html = $this->getIntroduction(); - $tpl->setVariable("CONTAINER_PAGE_CONTENT", $html); - } - else // show item list otherwise - { - $html = $this->renderItemList(); - $tpl->setVariable("CONTAINER_PAGE_CONTENT", $html); - } + // Show introduction, if repository is empty + // @todo: maybe we move this + if ((!is_array($this->items) || count($this->items) == 0) && + $this->getContainerObject()->getRefId() == ROOT_FOLDER_ID && + $ilAccess->checkAccess("write", "", $this->getContainerObject()->getRefId())) { + $html = $this->getIntroduction(); + $tpl->setVariable("CONTAINER_PAGE_CONTENT", $html); + } else { // show item list otherwise + $html = $this->renderItemList(); + $tpl->setVariable("CONTAINER_PAGE_CONTENT", $html); + } - return $tpl->get(); - } - - /** - * Render Items - */ - function renderItemList() - { - include_once("Services/Object/classes/class.ilObjectListGUIFactory.php"); - - $this->clearAdminCommandsDetermination(); - - $this->initRenderer(); - - // text/media page content - $output_html = $this->getContainerGUI()->getContainerPageHTML(); - - // get embedded blocks - if ($output_html != "") - { - $output_html = $this->insertPageEmbeddedBlocks($output_html); - } + return $tpl->get(); + } + + /** + * Render Items + */ + public function renderItemList() + { + include_once("Services/Object/classes/class.ilObjectListGUIFactory.php"); + + $this->clearAdminCommandsDetermination(); + + $this->initRenderer(); + + // text/media page content + $output_html = $this->getContainerGUI()->getContainerPageHTML(); + + // get embedded blocks + if ($output_html != "") { + $output_html = $this->insertPageEmbeddedBlocks($output_html); + } - // item groups - $pos = $this->getItemGroupsHTML(); - - // iterate all types - foreach ($this->getGroupedObjTypes() as $type => $v) - { - if(is_array($this->items[$type]) && - $this->renderer->addTypeBlock($type)) - { - $this->renderer->setBlockPosition($type, ++$pos); - - $position = 1; - - foreach($this->items[$type] as $item_data) - { - $item_ref_id = $item_data["child"]; + // item groups + $pos = $this->getItemGroupsHTML(); + + // iterate all types + foreach ($this->getGroupedObjTypes() as $type => $v) { + if (is_array($this->items[$type]) && + $this->renderer->addTypeBlock($type)) { + $this->renderer->setBlockPosition($type, ++$pos); + + $position = 1; + + foreach ($this->items[$type] as $item_data) { + $item_ref_id = $item_data["child"]; - if ($this->block_limit > 0 && !$this->getContainerGUI()->isActiveItemOrdering() && $position == $this->block_limit + 1) - { - if ($position == $this->block_limit + 1) - { - // render more button - $this->renderer->addShowMoreButton($type); - } - continue; - } - - if(!$this->renderer->hasItem($item_ref_id)) - { - $html = $this->renderItem($item_data, $position++); - if ($html != "") - { - $this->renderer->addItemToBlock($type, $item_data["type"], $item_ref_id, $html); - } - } - } - } - } - - $output_html .= $this->renderer->getHTML(); - - return $output_html; - } - - /** - * init details - * - * @access protected - * @param - * @return - */ - protected function initDetails() - { - $ilUser = $this->user; - - if($_GET['expand']) - { - if($_GET['expand'] > 0) - { - $_SESSION['sess']['expanded'][abs((int) $_GET['expand'])] = self::DETAILS_ALL; - } - else - { - $_SESSION['sess']['expanded'][abs((int) $_GET['expand'])] = self::DETAILS_TITLE; - } - } - - - if($this->getContainerObject()->getType() == 'crs') - { - include_once('./Modules/Session/classes/class.ilSessionAppointment.php'); - if($session = ilSessionAppointment::lookupNextSessionByCourse($this->getContainerObject()->getRefId())) - { - $this->force_details = $session; - } - elseif($session = ilSessionAppointment::lookupLastSessionByCourse($this->getContainerObject()->getRefId())) - { - $this->force_details = $session; - } - } - } - + if ($this->block_limit > 0 && !$this->getContainerGUI()->isActiveItemOrdering() && $position == $this->block_limit + 1) { + if ($position == $this->block_limit + 1) { + // render more button + $this->renderer->addShowMoreButton($type); + } + continue; + } + if (!$this->renderer->hasItem($item_ref_id)) { + $html = $this->renderItem($item_data, $position++); + if ($html != "") { + $this->renderer->addItemToBlock($type, $item_data["type"], $item_ref_id, $html); + } + } + } + } + } + + $output_html .= $this->renderer->getHTML(); + + return $output_html; + } + + /** + * init details + * + * @access protected + * @param + * @return + */ + protected function initDetails() + { + $ilUser = $this->user; + + if ($_GET['expand']) { + if ($_GET['expand'] > 0) { + $_SESSION['sess']['expanded'][abs((int) $_GET['expand'])] = self::DETAILS_ALL; + } else { + $_SESSION['sess']['expanded'][abs((int) $_GET['expand'])] = self::DETAILS_TITLE; + } + } + + + if ($this->getContainerObject()->getType() == 'crs') { + include_once('./Modules/Session/classes/class.ilSessionAppointment.php'); + if ($session = ilSessionAppointment::lookupNextSessionByCourse($this->getContainerObject()->getRefId())) { + $this->force_details = $session; + } elseif ($session = ilSessionAppointment::lookupLastSessionByCourse($this->getContainerObject()->getRefId())) { + $this->force_details = $session; + } + } + } } // END class.ilContainerSimpleContentGUI -?> diff --git a/Services/Container/classes/class.ilContainerContentGUI.php b/Services/Container/classes/class.ilContainerContentGUI.php index 64724d77b67f109dc74553064e910221aff4fd06..dead2d56bd2c89b846394af612de9854c9d6fb1d 100644 --- a/Services/Container/classes/class.ilContainerContentGUI.php +++ b/Services/Container/classes/class.ilContainerContentGUI.php @@ -15,1134 +15,1079 @@ */ abstract class ilContainerContentGUI { - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilPluginAdmin - */ - protected $plugin_admin; - - /** - * @var ilDB - */ - protected $db; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilSetting - */ - protected $settings; - - /** - * @var ilObjectDefinition - */ - protected $obj_definition; - - const DETAILS_DEACTIVATED = 0; - const DETAILS_TITLE = 1; - const DETAILS_ALL = 2; - - const VIEW_MODE_LIST = 0; - const VIEW_MODE_TILE = 1; - - protected $details_level = self::DETAILS_DEACTIVATED; - - /** - * @var ilContainerRenderer - */ - protected $renderer; - - var $container_gui; - var $container_obj; - - /** - * @var ilLogger - */ - protected $log; - - /** - * @var int - */ - protected $view_mode; - - /** - * Constructor - * - */ - function __construct(&$container_gui_obj) - { - global $DIC; - - $this->tpl = $DIC["tpl"]; - $this->ctrl = $DIC->ctrl(); - $this->user = $DIC->user(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $this->plugin_admin = $DIC["ilPluginAdmin"]; - $this->db = $DIC->database(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->settings = $DIC->settings(); - $this->obj_definition = $DIC["objDefinition"]; - $tpl = $DIC["tpl"]; - - $this->container_gui = $container_gui_obj; - $this->container_obj = $this->container_gui->object; - - $tpl->addJavaScript("./Services/Container/js/Container.js"); - - $this->log = ilLoggerFactory::getLogger('cont'); - - $this->view_mode = (ilContainer::_lookupContainerSetting($this->container_obj->getId(), "list_presentation") == "tile" && - !$this->container_gui->isActiveAdministrationPanel() && - !$this->container_gui->isActiveOrdering()) - ? self::VIEW_MODE_TILE - : self::VIEW_MODE_LIST; - - } - - /** - * Get view mode - */ - protected function getViewMode() - { - return $this->view_mode; - } - - - /** - * get details level - * - * @access protected - * @param - * @return - */ - protected function getDetailsLevel($a_item_id) - { - return $this->details_level; - } - - /** - * Get container object. - * - * @return object container object instance - */ - public function getContainerObject() - { - return $this->container_obj; - } - - /** - * Get container GUI object - * - * @return object container GUI instance - */ - public function getContainerGUI() - { - return $this->container_gui; - } - - /** - * Sets view output into column layout - * - * This method sets the output of the right and main column - * in the global standard template. - */ - public function setOutput() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - - // note: we do not want to get the center html in case of - // asynchronous calls to blocks in the right column (e.g. news) - // see #13012 - if ($ilCtrl->getNextClass() == "ilcolumngui" && - $ilCtrl->isAsynch()) - { - $tpl->setRightContent($this->getRightColumnHTML()); - } - - // BEGIN ChangeEvent: record read event. - require_once('Services/Tracking/classes/class.ilChangeEvent.php'); - $ilUser = $this->user; - - $obj_id = ilObject::_lookupObjId($this->getContainerObject()->getRefId()); - ilChangeEvent::_recordReadEvent( - $this->getContainerObject()->getType(), - $this->getContainerObject()->getRefId(), - $obj_id, $ilUser->getId()); - // END ChangeEvent: record read event. - - - $tpl->setContent($this->getCenterColumnHTML()); - - // see above, all other cases (this was the old position of setRightContent, - // maybe the position above is ok and all ifs can be removed) - if ($ilCtrl->getNextClass() != "ilcolumngui" || - !$ilCtrl->isAsynch()) - { - $tpl->setRightContent($this->getRightColumnHTML()); - } - - } - - /** - * Get HTML for right column - */ - protected function getRightColumnHTML() - { - $ilUser = $this->user; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - $ilPluginAdmin = $this->plugin_admin; - - $ilCtrl->saveParameterByClass("ilcolumngui", "col_return"); - - $obj_id = ilObject::_lookupObjId($this->getContainerObject()->getRefId()); - $obj_type = ilObject::_lookupType($obj_id); - - include_once("Services/Block/classes/class.ilColumnGUI.php"); - $column_gui = new ilColumnGUI($obj_type, IL_COL_RIGHT); - - if ($column_gui->getScreenMode() == IL_SCREEN_FULL) - { - return ""; - } - - $this->getContainerGUI()->setColumnSettings($column_gui); - - if ($ilCtrl->getNextClass() == "ilcolumngui" && - $column_gui->getCmdSide() == IL_COL_RIGHT && - $column_gui->getScreenMode() == IL_SCREEN_SIDE) - { - - $html = $ilCtrl->forwardCommand($column_gui); - } - else - { - if (!$ilCtrl->isAsynch()) - { - $html = ""; - - // user interface plugin slot + default rendering - include_once("./Services/UIComponent/classes/class.ilUIHookProcessor.php"); - $uip = new ilUIHookProcessor("Services/Container", "right_column", - array("container_content_gui" => $this)); - if (!$uip->replaced()) - { - $html = $ilCtrl->getHTML($column_gui); - } - $html = $uip->getHTML($html); - } - } - - return $html; - } - - /** - * Get HTML for center column - */ - protected function getCenterColumnHTML() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $ilDB = $this->db; - - $ilCtrl->saveParameterByClass("ilcolumngui", "col_return"); - - $tpl->addOnLoadCode("il.Object.setRedrawListItemUrl('". - $ilCtrl->getLinkTarget($this->container_gui, "redrawListItem", "", true)."');"); - - $tpl->addOnLoadCode("il.Object.setRatingUrl('". - $ilCtrl->getLinkTargetByClass(array(get_class($this->container_gui), "ilcommonactiondispatchergui", "ilratinggui"), - "saveRating", "", true, false)."');"); - - switch ($ilCtrl->getNextClass()) - { - case "ilcolumngui": - $this->container_gui->setSideColumnReturn(); - $html = $this->__forwardToColumnGUI(); - break; - - default: - $ilDB->useSlave(true); - $html = $this->getMainContent(); - $ilDB->useSlave(false); - break; - } - - return $html; - } - - /** - * Get content HTML for main column, this one must be - * overwritten in derived classes. - */ - abstract function getMainContent(); - - /** - * Init container renderer - */ - protected function initRenderer() - { - include_once('./Services/Container/classes/class.ilContainerSorting.php'); - $sorting = ilContainerSorting::_getInstance($this->getContainerObject()->getId()); - - include_once "Services/Container/classes/class.ilContainerRenderer.php"; - $this->renderer = new ilContainerRenderer( - ($this->getContainerGUI()->isActiveAdministrationPanel() && !$_SESSION["clipboard"]) - ,$this->getContainerGUI()->isMultiDownloadEnabled() - ,$this->getContainerGUI()->isActiveOrdering() && (get_class($this) != "ilContainerObjectiveGUI") // no block sorting in objective view - ,$sorting->getBlockPositions() - ,$this->container_gui - ,$this->getViewMode() - ); - } - - /** - * Get columngui output - */ - final private function __forwardToColumnGUI() - { - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - - include_once("Services/Block/classes/class.ilColumnGUI.php"); - - // this gets us the subitems we need in setColumnSettings() - // todo: this should be done in ilCourseGUI->getSubItems - - $obj_id = ilObject::_lookupObjId($this->getContainerObject()->getRefId()); - $obj_type = ilObject::_lookupType($obj_id); - - if (!$ilCtrl->isAsynch()) - { - //if ($column_gui->getScreenMode() != IL_SCREEN_SIDE) - if (ilColumnGUI::getScreenMode() != IL_SCREEN_SIDE) - { - // right column wants center - if (ilColumnGUI::getCmdSide() == IL_COL_RIGHT) - { - $column_gui = new ilColumnGUI($obj_type, IL_COL_RIGHT); - $this->getContainerGUI()->setColumnSettings($column_gui); - $html = $ilCtrl->forwardCommand($column_gui); - } - // left column wants center - if (ilColumnGUI::getCmdSide() == IL_COL_LEFT) - { - $column_gui = new ilColumnGUI($obj_type, IL_COL_LEFT); - $this->getContainerGUI()->setColumnSettings($column_gui); - $html = $ilCtrl->forwardCommand($column_gui); - } - } - else - { - $html = $this->getMainContent(); - } - } - - return $html; - } - - /** - * cleaer administration commands determination - */ - protected function clearAdminCommandsDetermination() - { - $this->adminCommands = false; - } - - /** - * determin admin commands - */ - protected function determineAdminCommands($a_ref_id, $a_admin_com_included_in_list = false) - { - $rbacsystem = $this->rbacsystem; - -//echo "-".$a_admin_com_included_in_list."-"; - - if (!$this->adminCommands) - { - if (!$this->getContainerGUI()->isActiveAdministrationPanel()) - { - if ($rbacsystem->checkAccess("delete", $a_ref_id)) - { - $this->adminCommands = true; - } - } - else - { - $this->adminCommands = $a_admin_com_included_in_list; - } - } - } - - /** - * Get ListGUI object for item - */ - protected function getItemGUI($item_data,$a_show_path = false) - { - include_once 'Services/Object/classes/class.ilObjectListGUIFactory.php'; - - // get item list gui object - if (!is_object ($this->list_gui[$item_data["type"]])) - { - $item_list_gui =& ilObjectListGUIFactory::_getListGUIByType($item_data["type"]); - $item_list_gui->setContainerObject($this->getContainerGUI()); - $this->list_gui[$item_data["type"]] =& $item_list_gui; - } - else - { - $item_list_gui =& $this->list_gui[$item_data["type"]]; - - } - - // unique js-ids - $item_list_gui->setParentRefId($item_data["parent"]); - - $item_list_gui->setDefaultCommandParameters(array()); - $item_list_gui->disableTitleLink(false); - $item_list_gui->resetConditionTarget(); - - // show administration command buttons (or not) - if (!$this->getContainerGUI()->isActiveAdministrationPanel()) - { -// $item_list_gui->enableDelete(false); + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilPluginAdmin + */ + protected $plugin_admin; + + /** + * @var ilDB + */ + protected $db; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var ilObjectDefinition + */ + protected $obj_definition; + + const DETAILS_DEACTIVATED = 0; + const DETAILS_TITLE = 1; + const DETAILS_ALL = 2; + + const VIEW_MODE_LIST = 0; + const VIEW_MODE_TILE = 1; + + protected $details_level = self::DETAILS_DEACTIVATED; + + /** + * @var ilContainerRenderer + */ + protected $renderer; + + public $container_gui; + public $container_obj; + + /** + * @var ilLogger + */ + protected $log; + + /** + * @var int + */ + protected $view_mode; + + /** + * Constructor + * + */ + public function __construct(&$container_gui_obj) + { + global $DIC; + + $this->tpl = $DIC["tpl"]; + $this->ctrl = $DIC->ctrl(); + $this->user = $DIC->user(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->plugin_admin = $DIC["ilPluginAdmin"]; + $this->db = $DIC->database(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->settings = $DIC->settings(); + $this->obj_definition = $DIC["objDefinition"]; + $tpl = $DIC["tpl"]; + + $this->container_gui = $container_gui_obj; + $this->container_obj = $this->container_gui->object; + + $tpl->addJavaScript("./Services/Container/js/Container.js"); + + $this->log = ilLoggerFactory::getLogger('cont'); + + $this->view_mode = (ilContainer::_lookupContainerSetting($this->container_obj->getId(), "list_presentation") == "tile" && + !$this->container_gui->isActiveAdministrationPanel() && + !$this->container_gui->isActiveOrdering()) + ? self::VIEW_MODE_TILE + : self::VIEW_MODE_LIST; + } + + /** + * Get view mode + */ + protected function getViewMode() + { + return $this->view_mode; + } + + + /** + * get details level + * + * @access protected + * @param + * @return + */ + protected function getDetailsLevel($a_item_id) + { + return $this->details_level; + } + + /** + * Get container object. + * + * @return object container object instance + */ + public function getContainerObject() + { + return $this->container_obj; + } + + /** + * Get container GUI object + * + * @return object container GUI instance + */ + public function getContainerGUI() + { + return $this->container_gui; + } + + /** + * Sets view output into column layout + * + * This method sets the output of the right and main column + * in the global standard template. + */ + public function setOutput() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + + // note: we do not want to get the center html in case of + // asynchronous calls to blocks in the right column (e.g. news) + // see #13012 + if ($ilCtrl->getNextClass() == "ilcolumngui" && + $ilCtrl->isAsynch()) { + $tpl->setRightContent($this->getRightColumnHTML()); + } + + // BEGIN ChangeEvent: record read event. + require_once('Services/Tracking/classes/class.ilChangeEvent.php'); + $ilUser = $this->user; + + $obj_id = ilObject::_lookupObjId($this->getContainerObject()->getRefId()); + ilChangeEvent::_recordReadEvent( + $this->getContainerObject()->getType(), + $this->getContainerObject()->getRefId(), + $obj_id, + $ilUser->getId() + ); + // END ChangeEvent: record read event. + + + $tpl->setContent($this->getCenterColumnHTML()); + + // see above, all other cases (this was the old position of setRightContent, + // maybe the position above is ok and all ifs can be removed) + if ($ilCtrl->getNextClass() != "ilcolumngui" || + !$ilCtrl->isAsynch()) { + $tpl->setRightContent($this->getRightColumnHTML()); + } + } + + /** + * Get HTML for right column + */ + protected function getRightColumnHTML() + { + $ilUser = $this->user; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + $ilPluginAdmin = $this->plugin_admin; + + $ilCtrl->saveParameterByClass("ilcolumngui", "col_return"); + + $obj_id = ilObject::_lookupObjId($this->getContainerObject()->getRefId()); + $obj_type = ilObject::_lookupType($obj_id); + + include_once("Services/Block/classes/class.ilColumnGUI.php"); + $column_gui = new ilColumnGUI($obj_type, IL_COL_RIGHT); + + if ($column_gui->getScreenMode() == IL_SCREEN_FULL) { + return ""; + } + + $this->getContainerGUI()->setColumnSettings($column_gui); + + if ($ilCtrl->getNextClass() == "ilcolumngui" && + $column_gui->getCmdSide() == IL_COL_RIGHT && + $column_gui->getScreenMode() == IL_SCREEN_SIDE) { + $html = $ilCtrl->forwardCommand($column_gui); + } else { + if (!$ilCtrl->isAsynch()) { + $html = ""; + + // user interface plugin slot + default rendering + include_once("./Services/UIComponent/classes/class.ilUIHookProcessor.php"); + $uip = new ilUIHookProcessor( + "Services/Container", + "right_column", + array("container_content_gui" => $this) + ); + if (!$uip->replaced()) { + $html = $ilCtrl->getHTML($column_gui); + } + $html = $uip->getHTML($html); + } + } + + return $html; + } + + /** + * Get HTML for center column + */ + protected function getCenterColumnHTML() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $ilDB = $this->db; + + $ilCtrl->saveParameterByClass("ilcolumngui", "col_return"); + + $tpl->addOnLoadCode("il.Object.setRedrawListItemUrl('" . + $ilCtrl->getLinkTarget($this->container_gui, "redrawListItem", "", true) . "');"); + + $tpl->addOnLoadCode("il.Object.setRatingUrl('" . + $ilCtrl->getLinkTargetByClass( + array(get_class($this->container_gui), "ilcommonactiondispatchergui", "ilratinggui"), + "saveRating", + "", + true, + false + ) . "');"); + + switch ($ilCtrl->getNextClass()) { + case "ilcolumngui": + $this->container_gui->setSideColumnReturn(); + $html = $this->__forwardToColumnGUI(); + break; + + default: + $ilDB->useSlave(true); + $html = $this->getMainContent(); + $ilDB->useSlave(false); + break; + } + + return $html; + } + + /** + * Get content HTML for main column, this one must be + * overwritten in derived classes. + */ + abstract public function getMainContent(); + + /** + * Init container renderer + */ + protected function initRenderer() + { + include_once('./Services/Container/classes/class.ilContainerSorting.php'); + $sorting = ilContainerSorting::_getInstance($this->getContainerObject()->getId()); + + include_once "Services/Container/classes/class.ilContainerRenderer.php"; + $this->renderer = new ilContainerRenderer( + ($this->getContainerGUI()->isActiveAdministrationPanel() && !$_SESSION["clipboard"]), + $this->getContainerGUI()->isMultiDownloadEnabled(), + $this->getContainerGUI()->isActiveOrdering() && (get_class($this) != "ilContainerObjectiveGUI") // no block sorting in objective view + , + $sorting->getBlockPositions(), + $this->container_gui, + $this->getViewMode() + ); + } + + /** + * Get columngui output + */ + final private function __forwardToColumnGUI() + { + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + + include_once("Services/Block/classes/class.ilColumnGUI.php"); + + // this gets us the subitems we need in setColumnSettings() + // todo: this should be done in ilCourseGUI->getSubItems + + $obj_id = ilObject::_lookupObjId($this->getContainerObject()->getRefId()); + $obj_type = ilObject::_lookupType($obj_id); + + if (!$ilCtrl->isAsynch()) { + //if ($column_gui->getScreenMode() != IL_SCREEN_SIDE) + if (ilColumnGUI::getScreenMode() != IL_SCREEN_SIDE) { + // right column wants center + if (ilColumnGUI::getCmdSide() == IL_COL_RIGHT) { + $column_gui = new ilColumnGUI($obj_type, IL_COL_RIGHT); + $this->getContainerGUI()->setColumnSettings($column_gui); + $html = $ilCtrl->forwardCommand($column_gui); + } + // left column wants center + if (ilColumnGUI::getCmdSide() == IL_COL_LEFT) { + $column_gui = new ilColumnGUI($obj_type, IL_COL_LEFT); + $this->getContainerGUI()->setColumnSettings($column_gui); + $html = $ilCtrl->forwardCommand($column_gui); + } + } else { + $html = $this->getMainContent(); + } + } + + return $html; + } + + /** + * cleaer administration commands determination + */ + protected function clearAdminCommandsDetermination() + { + $this->adminCommands = false; + } + + /** + * determin admin commands + */ + protected function determineAdminCommands($a_ref_id, $a_admin_com_included_in_list = false) + { + $rbacsystem = $this->rbacsystem; + + //echo "-".$a_admin_com_included_in_list."-"; + + if (!$this->adminCommands) { + if (!$this->getContainerGUI()->isActiveAdministrationPanel()) { + if ($rbacsystem->checkAccess("delete", $a_ref_id)) { + $this->adminCommands = true; + } + } else { + $this->adminCommands = $a_admin_com_included_in_list; + } + } + } + + /** + * Get ListGUI object for item + */ + protected function getItemGUI($item_data, $a_show_path = false) + { + include_once 'Services/Object/classes/class.ilObjectListGUIFactory.php'; + + // get item list gui object + if (!is_object($this->list_gui[$item_data["type"]])) { + $item_list_gui =&ilObjectListGUIFactory::_getListGUIByType($item_data["type"]); + $item_list_gui->setContainerObject($this->getContainerGUI()); + $this->list_gui[$item_data["type"]] =&$item_list_gui; + } else { + $item_list_gui =&$this->list_gui[$item_data["type"]]; + } + + // unique js-ids + $item_list_gui->setParentRefId($item_data["parent"]); + + $item_list_gui->setDefaultCommandParameters(array()); + $item_list_gui->disableTitleLink(false); + $item_list_gui->resetConditionTarget(); + + // show administration command buttons (or not) + if (!$this->getContainerGUI()->isActiveAdministrationPanel()) { + // $item_list_gui->enableDelete(false); // $item_list_gui->enableLink(false); // $item_list_gui->enableCut(false); - } - - // activate common social commands - $item_list_gui->enableComments(true); - $item_list_gui->enableNotes(true); - $item_list_gui->enableTags(true); - $item_list_gui->enableRating(true); - - // reset - $item_list_gui->forceVisibleOnly(false); - - // container specific modifications - $this->getContainerGUI()->modifyItemGUI($item_list_gui, $item_data, $a_show_path); - - return $item_list_gui; - } - - /** - * Determine all blocks that are embedded in the container page - */ - function determinePageEmbeddedBlocks($a_container_page_html) - { - $type_grps = $this->getGroupedObjTypes(); - - // iterate all types - foreach ($type_grps as $type => $v) - { - // set template (overall or type specific) - if (is_int(strpos($a_container_page_html, "[list-".$type."]"))) - { - $this->addEmbeddedBlock("type", $type); - } - } - - // determine item groups - while (preg_match('~\[(item-group-([0-9]*))\]~i', $a_container_page_html, $found)) - { - $this->addEmbeddedBlock("itgr", (int) $found[2]); - - $a_container_page_html = preg_replace('~\['.$found[1].'\]~i', $html, $a_container_page_html); - } - } - - /** - * Add embedded block - * - * @param - */ - function addEmbeddedBlock($block_type, $block_parameter) - { - $this->embedded_block[$block_type][] = $block_parameter; - } - - /** - * Get page embedded blocks - */ - function getEmbeddedBlocks() - { - return $this->embedded_block; - } - - /** - * Render Page Embedded Blocks - */ - function renderPageEmbeddedBlocks() - { - $lng = $this->lng; - - // item groups - if (is_array($this->embedded_block["itgr"])) - { - $item_groups = array(); - if (is_array($this->items["itgr"])) - { - foreach ($this->items["itgr"] as $ig) - { - $item_groups[$ig["ref_id"]] = $ig; - } - } - - foreach ($this->embedded_block["itgr"] as $ref_id) - { - if(isset($item_groups[$ref_id])) - { - $this->renderItemGroup($item_groups[$ref_id]); - } - } - } - - // type specific blocks - if (is_array($this->embedded_block["type"])) - { - foreach ($this->embedded_block["type"] as $k => $type) - { - if (is_array($this->items[$type]) && - $this->renderer->addTypeBlock($type)) - { - // :TODO: obsolete? - if($type == 'sess') - { - $this->items['sess'] = ilUtil::sortArray($this->items['sess'],'start','ASC',true,true); - } - - $position = 1; - - foreach($this->items[$type] as $k => $item_data) - { - if(!$this->renderer->hasItem($item_data["child"])) - { - $html = $this->renderItem($item_data, $position++); - if ($html != "") - { - $this->renderer->addItemToBlock($type, $item_data["type"], $item_data["child"], $html); - } - } - } - } - } - } - } - - /** - * Render an item - * @param $a_item_data - * @param int $a_position - * @param bool $a_force_icon - * @param string $a_pos_prefix - * @return string - */ - function renderItem($a_item_data,$a_position = 0,$a_force_icon = false, $a_pos_prefix = "") - { - $ilSetting = $this->settings; - $ilAccess = $this->access; - $ilCtrl = $this->ctrl; - - // Pass type, obj_id and tree to checkAccess method to improve performance - if(!$ilAccess->checkAccess('visible','',$a_item_data['ref_id'],$a_item_data['type'],$a_item_data['obj_id'],$a_item_data['tree'])) - { - return ''; - } - - if ($this->getViewMode() == self::VIEW_MODE_TILE) - { - return $this->renderCard($a_item_data, $a_position, $a_force_icon, $a_pos_prefix); - } - - $item_list_gui = $this->getItemGUI($a_item_data); - if ($ilSetting->get("icon_position_in_lists") == "item_rows" || - $a_item_data["type"] == "sess" || $a_force_icon) - { - $item_list_gui->enableIcon(true); - } - - if ($this->getContainerGUI()->isActiveAdministrationPanel() && !$_SESSION["clipboard"]) - { - $item_list_gui->enableCheckbox(true); - } - else if ($this->getContainerGUI()->isMultiDownloadEnabled()) - { - // display multi download checkboxes - $item_list_gui->enableDownloadCheckbox($a_item_data["ref_id"], true); - } - - if ($this->getContainerGUI()->isActiveItemOrdering() && ($a_item_data['type'] != 'sess' || get_class($this) != 'ilContainerSessionsContentGUI')) - { - $item_list_gui->setPositionInputField($a_pos_prefix."[".$a_item_data["ref_id"]."]", - sprintf('%d', (int)$a_position*10)); - } - - if($a_item_data['type'] == 'sess' and get_class($this) != 'ilContainerObjectiveGUI') - { - switch($this->getDetailsLevel($a_item_data['obj_id'])) - { - case self::DETAILS_TITLE: - $item_list_gui->setDetailsLevel(ilObjectListGUI::DETAILS_MINIMAL); - $item_list_gui->enableExpand(true); - $item_list_gui->setExpanded(false); - $item_list_gui->enableDescription(false); - $item_list_gui->enableProperties(true); - break; - - case self::DETAILS_ALL: - $item_list_gui->setDetailsLevel(ilObjectListGUI::DETAILS_ALL); - $item_list_gui->enableExpand(true); - $item_list_gui->setExpanded(true); - $item_list_gui->enableDescription(true); - $item_list_gui->enableProperties(true); - break; - - default: - $item_list_gui->setDetailsLevel(ilObjectListGUI::DETAILS_ALL); - $item_list_gui->enableExpand(true); - $item_list_gui->enableDescription(true); - $item_list_gui->enableProperties(true); - break; - } - } - - if(method_exists($this, "addItemDetails")) - { - $this->addItemDetails($item_list_gui, $a_item_data); - } - - // show subitems - if($a_item_data['type'] == 'sess' and ( - $this->getDetailsLevel($a_item_data['obj_id']) != self::DETAILS_TITLE or - $this->getContainerGUI()->isActiveAdministrationPanel() or - $this->getContainerGUI()->isActiveItemOrdering() - ) - ) - { - $pos = 1; - - include_once('./Services/Container/classes/class.ilContainerSorting.php'); - include_once('./Services/Object/classes/class.ilObjectActivation.php'); - $items = ilObjectActivation::getItemsByEvent($a_item_data['obj_id']); - $items = ilContainerSorting::_getInstance($this->getContainerObject()->getId())->sortSubItems('sess',$a_item_data['obj_id'],$items); - $items = ilContainer::getCompleteDescriptions($items); - - $item_readable = $ilAccess->checkAccess('read','',$a_item_data['ref_id']); - - foreach($items as $item) - { - // TODO: this should be removed and be handled by if(strlen($sub_item_html)) - // see mantis: 0003944 - if(!$ilAccess->checkAccess('visible','',$item['ref_id'])) - { - continue; - } - - $item_list_gui2 = $this->getItemGUI($item); - $item_list_gui2->enableIcon(true); - $item_list_gui2->enableItemDetailLinks(false); - - // unique js-ids - $item_list_gui2->setParentRefId($a_item_data['ref_id']); - - // @see mantis 10488 - if(!$item_readable and !$ilAccess->checkAccess('write','',$item['ref_id'])) - { - $item_list_gui2->forceVisibleOnly(true); - } - - if ($this->getContainerGUI()->isActiveAdministrationPanel() && !$_SESSION["clipboard"]) - { - $item_list_gui2->enableCheckbox(true); - } - else if ($this->getContainerGUI()->isMultiDownloadEnabled()) - { - // display multi download checkbox - $item_list_gui2->enableDownloadCheckbox($item['ref_id'], true); - } - - if ($this->getContainerGUI()->isActiveItemOrdering()) - { - $item_list_gui2->setPositionInputField("[sess][".$a_item_data['obj_id']."][".$item["ref_id"]."]", - sprintf('%d', (int)$pos*10)); - $pos++; - } - - // #10611 - ilObjectActivation::addListGUIActivationProperty($item_list_gui2, $item); - - $sub_item_html = $item_list_gui2->getListItemHTML($item['ref_id'], - $item['obj_id'], $item['title'], $item['description']); - - $this->determineAdminCommands($item["ref_id"],$item_list_gui2->adminCommandsIncluded()); - if(strlen($sub_item_html)) - { - $item_list_gui->addSubItemHTML($sub_item_html); - } - } - } - - - if ($ilSetting->get("item_cmd_asynch")) - { - $asynch = true; - $ilCtrl->setParameter($this->container_gui, "cmdrefid", $a_item_data['ref_id']); - $asynch_url = $ilCtrl->getLinkTarget($this->container_gui, - "getAsynchItemList", "", true, false); - $ilCtrl->setParameter($this->container_gui, "cmdrefid", ""); - - //#0020343 - $fold_set = new ilSetting('fold'); - if ($a_item_data['type'] == 'fold' && $fold_set->get("bgtask_download") && $fold_set->get("enable_download_folder")) { - include_once "Services/BackgroundTask/classes/class.ilFolderDownloadBackgroundTaskHandler.php"; - ilFolderDownloadBackgroundTaskHandler::initObjectListAction(); - } - } - - include_once "Services/Object/classes/class.ilObjectActivation.php"; - ilObjectActivation::addListGUIActivationProperty($item_list_gui, $a_item_data); - - $html = $item_list_gui->getListItemHTML($a_item_data['ref_id'], - $a_item_data['obj_id'], $a_item_data['title'], $a_item_data['description'], - $asynch, false, $asynch_url); - $this->determineAdminCommands($a_item_data["ref_id"], - $item_list_gui->adminCommandsIncluded()); - - - return $html; - } - - /** - * Render card - * @param $a_item_data - * @param int $a_position - * @param bool $a_force_icon - * @param string $a_pos_prefix - * @return string - */ - function renderCard($a_item_data, $a_position = 0,$a_force_icon = false, $a_pos_prefix = "") - { - global $DIC; - $f = $DIC->ui()->factory(); - $r = $DIC->ui()->renderer(); - $user = $DIC->user(); - - $item_list_gui = $this->getItemGUI($a_item_data); - $item_list_gui->setAjaxHash(ilCommonActionDispatcherGUI::buildAjaxHash( - ilCommonActionDispatcherGUI::TYPE_REPOSITORY, - $a_item_data['ref_id'], - $a_item_data['type'], - $a_item_data['obj_id'])); - $item_list_gui->initItem($a_item_data['ref_id'], $a_item_data['obj_id'], - $a_item_data['title'], $a_item_data['description']); - - // actions - $item_list_gui->insertCommands(); - $actions = []; - foreach ($item_list_gui->current_selection_list->getItems() as $item) - { - if (!isset($item["onclick"]) || $item["onclick"] == "") - { - $button = - $f->button()->shy($item["title"], $item["link"]); - } - else - { - $button = - $f->button()->shy($item["title"], "")->withAdditionalOnLoadCode(function($id) use ($item){ - return - "$('#$id').click(function(e) { ".$item["onclick"]."});"; - }); - } - $actions[] = $button; - - } - - - $def_command = $item_list_gui->getDefaultCommand(); - $dropdown = $f->dropdown()->standard($actions); - - $img = $DIC->object()->commonSettings()->tileImage()->getByObjId($a_item_data['obj_id']); - - if ($img->exists()) - { - $path = $img->getFullPath(); - } - else - { - $path = ilUtil::getImagePath("cont_tile/cont_tile_default_".$a_item_data['type'].".svg"); - if (!is_file($path)) - { - $path = ilUtil::getImagePath("cont_tile/cont_tile_default.svg"); - } - } - - $sections = []; - $title = $a_item_data["title"]; - - // workaround for scorm - $modified_link = - $item_list_gui->modifySAHSlaunch($def_command["link"], $def_command["frame"]); - - - $image = $f->image()->responsive($path, ""); - if ($def_command["link"] != "") // #24256 - { - if ($def_command["frame"] != "" && ($modified_link == $def_command["link"])) { - $image = $image->withAdditionalOnLoadCode(function($id) use ($def_command) { - return - "$('#$id').click(function(e) { window.open('".str_replace("&", "&", $def_command["link"])."', '".$def_command["frame"]."');});"; - }); - - $button = - $f->button()->shy($title, "")->withAdditionalOnLoadCode(function($id) use ($def_command) { - return - "$('#$id').click(function(e) { window.open('".str_replace("&", "&", $def_command["link"])."', '".$def_command["frame"]."');});"; - }); - $title = $r->render($button); - } - else { - $image = $image->withAction($modified_link); - } - } - - // description, @todo: move to new ks element - if ($a_item_data["description"] != "") { - $sections[] = $f->legacy("
          ".$a_item_data["description"]."
          "); - } - - if ($a_item_data["type"] == "sess") - { - $app_info = ilSessionAppointment::_lookupAppointment($a_item_data['obj_id']); - if ($title != "") { - $title = ": ".$title; - } - $title = ilSessionAppointment::_appointmentToString($app_info['start'], $app_info['end'], $app_info['fullday']). - $title; - } - - $icon = $f->icon()->standard($a_item_data["type"], $this->lng->txt("obj_".$a_item_data["type"])) - ->withIsOutlined(true); - $card = $f->card()->repositoryObject( - $title."", - $image - )->withObjectIcon( - $icon - )->withActions($dropdown - ); - - if ($def_command["link"] != "" && ($def_command["frame"] == "" || $modified_link != $def_command["link"])) // #24256 - { - $card = $card->withTitleAction($modified_link); - } - - // properties - $l = []; - foreach ($item_list_gui->determineProperties() as $p) - { - if ($p["property"] != $this->lng->txt("learning_progress")) - { - $l[(string) $p["property"]] = (string) $p["value"]; - } - } - - if (count($l) > 0) - { - $prop_list = $f->listing()->descriptive($l); - $sections[] = $prop_list; - } - if (count($sections) > 0) { - $card = $card->withSections($sections); - } - // learning progress - include_once "Services/Tracking/classes/class.ilLPStatus.php"; - $lp = ilLPStatus::getListGUIStatus($a_item_data["obj_id"], false); - if ($lp) - { - $percentage = (int) ilLPStatus::_lookupPercentage($a_item_data["obj_id"], $user->getId()); - if ($lp["status"] == ilLPStatus::LP_STATUS_COMPLETED_NUM) - { - $percentage = 100; - } - //var_dump(ilLPStatus::_lookupPercentage($a_item_data["obj_id"], $user->getId())); exit; - $progressmeter = $f->chart()->progressMeter()->mini(100, $percentage); - $card = $card->withProgress($progressmeter); - } - - return $card; - } - - /** - * Insert blocks into container page - */ - function insertPageEmbeddedBlocks($a_output_html) - { - $this->determinePageEmbeddedBlocks($a_output_html); - $this->renderPageEmbeddedBlocks($this->items); - - // iterate all types - foreach ($this->getGroupedObjTypes() as $type => $v) - { - // set template (overall or type specific) - if (is_int(strpos($a_output_html, "[list-".$type."]"))) - { - $a_output_html = preg_replace('~\[list-'.$type.'\]~i', - $this->renderer->renderSingleTypeBlock($type), $a_output_html); - } - } - - // insert all item groups - while (preg_match('~\[(item-group-([0-9]*))\]~i', $a_output_html, $found)) - { - $itgr_ref_id = (int) $found[2]; - - $a_output_html = preg_replace('~\['.$found[1].'\]~i', - $this->renderer->renderSingleCustomBlock($itgr_ref_id), $a_output_html); - } - - return $a_output_html; - } - - /** - * Render single block - * - * @param string block id - * @return string - */ - public function getSingleTypeBlockAsynch($type) - { - $this->initRenderer(); - // get all sub items - $this->items = $this->getContainerObject()->getSubItems( - $this->getContainerGUI()->isActiveAdministrationPanel()); - - - $ref_ids = array_map(function($i) { - $parts = explode("_", $i); - return $parts[2]; - }, $_POST["ids"]); - - // iterate all types - if(is_array($this->items[$type]) && - $this->renderer->addTypeBlock($type)) - { - //$this->renderer->setBlockPosition($type, ++$pos); - - $position = 1; - foreach($this->items[$type] as $item_data) - { - $item_ref_id = $item_data["child"]; - - if (in_array($item_ref_id, $ref_ids)) - { - continue; - } - - if ($this->block_limit > 0 && $position == $this->block_limit + 1) - { - if ($position == $this->block_limit + 1) - { - // render more button - $this->renderer->addShowMoreButton($type); - } - continue; - } - - if(!$this->renderer->hasItem($item_ref_id)) - { - $html = $this->renderItem($item_data, $position++); - if ($html != "") - { - $this->renderer->addItemToBlock($type, $item_data["type"], $item_ref_id, $html); - } - } - } - } - - return $this->renderer->renderSingleTypeBlock($type); - } - - /** - * Get grouped repository object types. - * - * @return array array of object types - */ - function getGroupedObjTypes() - { - $objDefinition = $this->obj_definition; - - if (empty($this->type_grps)) - { - $this->type_grps = - $objDefinition->getGroupedRepositoryObjectTypes($this->getContainerObject()->getType()); - } - return $this->type_grps; - } - - /** - * Get introduction. - */ - function getIntroduction() - { - $ilUser = $this->user; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $lng->loadLanguageModule("rep"); - - $tpl = new ilTemplate("tpl.rep_intro.html", true, true, "Services/Repository"); - $tpl->setVariable("IMG_REP_LARGE", ilObject::_getIcon("", "big", "root")); - $tpl->setVariable("TXT_WELCOME", $lng->txt("rep_intro")); - $tpl->setVariable("TXT_INTRO_1", $lng->txt("rep_intro1")); - $tpl->setVariable("TXT_INTRO_2", $lng->txt("rep_intro2")); - $tpl->setVariable("TXT_INTRO_3", sprintf($lng->txt("rep_intro3"), $lng->txt("add"))); - $tpl->setVariable("TXT_INTRO_4", sprintf($lng->txt("rep_intro4"), $lng->txt("cat_add"))); - $tpl->setVariable("TXT_INTRO_5", $lng->txt("rep_intro5")); - $tpl->setVariable("TXT_INTRO_6", $lng->txt("rep_intro6")); - - return $tpl->get(); - } - - /** - * Get item groups HTML - * - * @param - * @return - */ - function getItemGroupsHTML($a_pos = 0) - { - if (is_array($this->items["itgr"])) - { - foreach ($this->items["itgr"] as $itgr) - { - if (!$this->renderer->hasCustomBlock($itgr["child"])) - { - $this->renderItemGroup($itgr); - - $this->renderer->setBlockPosition($itgr["ref_id"], ++$a_pos); - } - } - } - return $a_pos; - } - - /** - * Render item group - * - * @param - * @return - */ - function renderItemGroup($a_itgr) - { - $ilAccess = $this->access; - $ilUser = $this->user; - - // #16493 - $perm_ok = ($ilAccess->checkAccess("visible", "", $a_itgr['ref_id']) && - $ilAccess->checkAccess("read", "", $a_itgr['ref_id'])); - - include_once('./Services/Container/classes/class.ilContainerSorting.php'); - include_once('./Services/Object/classes/class.ilObjectActivation.php'); - $items = ilObjectActivation::getItemsByItemGroup($a_itgr['ref_id']); - - // if no permission is given, set the items to "rendered" but - // do not display the whole block - if (!$perm_ok) - { - foreach($items as $item) - { - $this->renderer->hideItem($item["child"]); - } - return; - } - - $item_list_gui = $this->getItemGUI($a_itgr); - $item_list_gui->enableNotes(false); - $item_list_gui->enableTags(false); - $item_list_gui->enableComments(false); - $item_list_gui->enableTimings(false); - $item_list_gui->getListItemHTML($a_itgr["ref_id"], $a_itgr["obj_id"], - $a_itgr["title"], $a_itgr["description"]); - $commands_html = $item_list_gui->getCommandsHTML(); - - // determine behaviour - include_once("./Modules/ItemGroup/classes/class.ilObjItemGroup.php"); - include_once("./Modules/ItemGroup/classes/class.ilItemGroupBehaviour.php"); - $beh = ilObjItemGroup::lookupBehaviour($a_itgr["obj_id"]); - include_once("./Services/Container/classes/class.ilContainerBlockPropertiesStorage.php"); - $stored_val = ilContainerBlockPropertiesStorage::getProperty("itgr_".$a_itgr["ref_id"], $ilUser->getId(), "opened"); - if ($stored_val !== false) - { - $beh = ($stored_val == "1") - ? ilItemGroupBehaviour::EXPANDABLE_OPEN - : ilItemGroupBehaviour::EXPANDABLE_CLOSED; - } - - $data = array( - "behaviour" => $beh, - "store-url" => "./ilias.php?baseClass=ilcontainerblockpropertiesstorage&cmd=store". - "&cont_block_id=itgr_".$a_itgr['ref_id'] - ); - if (ilObjItemGroup::lookupHideTitle($a_itgr["obj_id"]) && - !$this->getContainerGUI()->isActiveAdministrationPanel()) - { - $this->renderer->addCustomBlock($a_itgr["ref_id"], "", $commands_html, $data); - } - else - { - $this->renderer->addCustomBlock($a_itgr["ref_id"], $a_itgr["title"], $commands_html, $data); - } - - - // render item group sub items - - $items = ilContainerSorting::_getInstance( - $this->getContainerObject()->getId())->sortSubItems('itgr', $a_itgr['obj_id'], $items); - - // #18285 - $items = ilContainer::getCompleteDescriptions($items); - - $position = 1; - foreach($items as $item) - { - // we are NOT using hasItem() here, because item might be in multiple item groups - $html2 = $this->renderItem($item, $position++, false, "[itgr][".$a_itgr['obj_id']."]"); - if ($html2 != "") - { - // :TODO: show it multiple times? - $this->renderer->addItemToBlock($a_itgr["ref_id"], $item["type"], $item["child"], $html2, true); - } - } - } + } + + // activate common social commands + $item_list_gui->enableComments(true); + $item_list_gui->enableNotes(true); + $item_list_gui->enableTags(true); + $item_list_gui->enableRating(true); + + // reset + $item_list_gui->forceVisibleOnly(false); + + // container specific modifications + $this->getContainerGUI()->modifyItemGUI($item_list_gui, $item_data, $a_show_path); + + return $item_list_gui; + } + + /** + * Determine all blocks that are embedded in the container page + */ + public function determinePageEmbeddedBlocks($a_container_page_html) + { + $type_grps = $this->getGroupedObjTypes(); + + // iterate all types + foreach ($type_grps as $type => $v) { + // set template (overall or type specific) + if (is_int(strpos($a_container_page_html, "[list-" . $type . "]"))) { + $this->addEmbeddedBlock("type", $type); + } + } + + // determine item groups + while (preg_match('~\[(item-group-([0-9]*))\]~i', $a_container_page_html, $found)) { + $this->addEmbeddedBlock("itgr", (int) $found[2]); + + $a_container_page_html = preg_replace('~\[' . $found[1] . '\]~i', $html, $a_container_page_html); + } + } + + /** + * Add embedded block + * + * @param + */ + public function addEmbeddedBlock($block_type, $block_parameter) + { + $this->embedded_block[$block_type][] = $block_parameter; + } + + /** + * Get page embedded blocks + */ + public function getEmbeddedBlocks() + { + return $this->embedded_block; + } + + /** + * Render Page Embedded Blocks + */ + public function renderPageEmbeddedBlocks() + { + $lng = $this->lng; + + // item groups + if (is_array($this->embedded_block["itgr"])) { + $item_groups = array(); + if (is_array($this->items["itgr"])) { + foreach ($this->items["itgr"] as $ig) { + $item_groups[$ig["ref_id"]] = $ig; + } + } + + foreach ($this->embedded_block["itgr"] as $ref_id) { + if (isset($item_groups[$ref_id])) { + $this->renderItemGroup($item_groups[$ref_id]); + } + } + } + + // type specific blocks + if (is_array($this->embedded_block["type"])) { + foreach ($this->embedded_block["type"] as $k => $type) { + if (is_array($this->items[$type]) && + $this->renderer->addTypeBlock($type)) { + // :TODO: obsolete? + if ($type == 'sess') { + $this->items['sess'] = ilUtil::sortArray($this->items['sess'], 'start', 'ASC', true, true); + } + + $position = 1; + + foreach ($this->items[$type] as $k => $item_data) { + if (!$this->renderer->hasItem($item_data["child"])) { + $html = $this->renderItem($item_data, $position++); + if ($html != "") { + $this->renderer->addItemToBlock($type, $item_data["type"], $item_data["child"], $html); + } + } + } + } + } + } + } + + /** + * Render an item + * @param $a_item_data + * @param int $a_position + * @param bool $a_force_icon + * @param string $a_pos_prefix + * @return string + */ + public function renderItem($a_item_data, $a_position = 0, $a_force_icon = false, $a_pos_prefix = "") + { + $ilSetting = $this->settings; + $ilAccess = $this->access; + $ilCtrl = $this->ctrl; + + // Pass type, obj_id and tree to checkAccess method to improve performance + if (!$ilAccess->checkAccess('visible', '', $a_item_data['ref_id'], $a_item_data['type'], $a_item_data['obj_id'], $a_item_data['tree'])) { + return ''; + } + + if ($this->getViewMode() == self::VIEW_MODE_TILE) { + return $this->renderCard($a_item_data, $a_position, $a_force_icon, $a_pos_prefix); + } + + $item_list_gui = $this->getItemGUI($a_item_data); + if ($ilSetting->get("icon_position_in_lists") == "item_rows" || + $a_item_data["type"] == "sess" || $a_force_icon) { + $item_list_gui->enableIcon(true); + } + + if ($this->getContainerGUI()->isActiveAdministrationPanel() && !$_SESSION["clipboard"]) { + $item_list_gui->enableCheckbox(true); + } elseif ($this->getContainerGUI()->isMultiDownloadEnabled()) { + // display multi download checkboxes + $item_list_gui->enableDownloadCheckbox($a_item_data["ref_id"], true); + } + + if ($this->getContainerGUI()->isActiveItemOrdering() && ($a_item_data['type'] != 'sess' || get_class($this) != 'ilContainerSessionsContentGUI')) { + $item_list_gui->setPositionInputField( + $a_pos_prefix . "[" . $a_item_data["ref_id"] . "]", + sprintf('%d', (int) $a_position*10) + ); + } + + if ($a_item_data['type'] == 'sess' and get_class($this) != 'ilContainerObjectiveGUI') { + switch ($this->getDetailsLevel($a_item_data['obj_id'])) { + case self::DETAILS_TITLE: + $item_list_gui->setDetailsLevel(ilObjectListGUI::DETAILS_MINIMAL); + $item_list_gui->enableExpand(true); + $item_list_gui->setExpanded(false); + $item_list_gui->enableDescription(false); + $item_list_gui->enableProperties(true); + break; + + case self::DETAILS_ALL: + $item_list_gui->setDetailsLevel(ilObjectListGUI::DETAILS_ALL); + $item_list_gui->enableExpand(true); + $item_list_gui->setExpanded(true); + $item_list_gui->enableDescription(true); + $item_list_gui->enableProperties(true); + break; + + default: + $item_list_gui->setDetailsLevel(ilObjectListGUI::DETAILS_ALL); + $item_list_gui->enableExpand(true); + $item_list_gui->enableDescription(true); + $item_list_gui->enableProperties(true); + break; + } + } + + if (method_exists($this, "addItemDetails")) { + $this->addItemDetails($item_list_gui, $a_item_data); + } + + // show subitems + if ($a_item_data['type'] == 'sess' and ( + $this->getDetailsLevel($a_item_data['obj_id']) != self::DETAILS_TITLE or + $this->getContainerGUI()->isActiveAdministrationPanel() or + $this->getContainerGUI()->isActiveItemOrdering() + ) + ) { + $pos = 1; + + include_once('./Services/Container/classes/class.ilContainerSorting.php'); + include_once('./Services/Object/classes/class.ilObjectActivation.php'); + $items = ilObjectActivation::getItemsByEvent($a_item_data['obj_id']); + $items = ilContainerSorting::_getInstance($this->getContainerObject()->getId())->sortSubItems('sess', $a_item_data['obj_id'], $items); + $items = ilContainer::getCompleteDescriptions($items); + + $item_readable = $ilAccess->checkAccess('read', '', $a_item_data['ref_id']); + + foreach ($items as $item) { + // TODO: this should be removed and be handled by if(strlen($sub_item_html)) + // see mantis: 0003944 + if (!$ilAccess->checkAccess('visible', '', $item['ref_id'])) { + continue; + } + + $item_list_gui2 = $this->getItemGUI($item); + $item_list_gui2->enableIcon(true); + $item_list_gui2->enableItemDetailLinks(false); + + // unique js-ids + $item_list_gui2->setParentRefId($a_item_data['ref_id']); + + // @see mantis 10488 + if (!$item_readable and !$ilAccess->checkAccess('write', '', $item['ref_id'])) { + $item_list_gui2->forceVisibleOnly(true); + } + + if ($this->getContainerGUI()->isActiveAdministrationPanel() && !$_SESSION["clipboard"]) { + $item_list_gui2->enableCheckbox(true); + } elseif ($this->getContainerGUI()->isMultiDownloadEnabled()) { + // display multi download checkbox + $item_list_gui2->enableDownloadCheckbox($item['ref_id'], true); + } + + if ($this->getContainerGUI()->isActiveItemOrdering()) { + $item_list_gui2->setPositionInputField( + "[sess][" . $a_item_data['obj_id'] . "][" . $item["ref_id"] . "]", + sprintf('%d', (int) $pos*10) + ); + $pos++; + } + + // #10611 + ilObjectActivation::addListGUIActivationProperty($item_list_gui2, $item); + + $sub_item_html = $item_list_gui2->getListItemHTML( + $item['ref_id'], + $item['obj_id'], + $item['title'], + $item['description'] + ); + + $this->determineAdminCommands($item["ref_id"], $item_list_gui2->adminCommandsIncluded()); + if (strlen($sub_item_html)) { + $item_list_gui->addSubItemHTML($sub_item_html); + } + } + } + + + if ($ilSetting->get("item_cmd_asynch")) { + $asynch = true; + $ilCtrl->setParameter($this->container_gui, "cmdrefid", $a_item_data['ref_id']); + $asynch_url = $ilCtrl->getLinkTarget( + $this->container_gui, + "getAsynchItemList", + "", + true, + false + ); + $ilCtrl->setParameter($this->container_gui, "cmdrefid", ""); + + //#0020343 + $fold_set = new ilSetting('fold'); + if ($a_item_data['type'] == 'fold' && $fold_set->get("bgtask_download") && $fold_set->get("enable_download_folder")) { + include_once "Services/BackgroundTask/classes/class.ilFolderDownloadBackgroundTaskHandler.php"; + ilFolderDownloadBackgroundTaskHandler::initObjectListAction(); + } + } + + include_once "Services/Object/classes/class.ilObjectActivation.php"; + ilObjectActivation::addListGUIActivationProperty($item_list_gui, $a_item_data); + + $html = $item_list_gui->getListItemHTML( + $a_item_data['ref_id'], + $a_item_data['obj_id'], + $a_item_data['title'], + $a_item_data['description'], + $asynch, + false, + $asynch_url + ); + $this->determineAdminCommands( + $a_item_data["ref_id"], + $item_list_gui->adminCommandsIncluded() + ); + + + return $html; + } + + /** + * Render card + * @param $a_item_data + * @param int $a_position + * @param bool $a_force_icon + * @param string $a_pos_prefix + * @return string + */ + public function renderCard($a_item_data, $a_position = 0, $a_force_icon = false, $a_pos_prefix = "") + { + global $DIC; + $f = $DIC->ui()->factory(); + $r = $DIC->ui()->renderer(); + $user = $DIC->user(); + + $item_list_gui = $this->getItemGUI($a_item_data); + $item_list_gui->setAjaxHash(ilCommonActionDispatcherGUI::buildAjaxHash( + ilCommonActionDispatcherGUI::TYPE_REPOSITORY, + $a_item_data['ref_id'], + $a_item_data['type'], + $a_item_data['obj_id'] + )); + $item_list_gui->initItem( + $a_item_data['ref_id'], + $a_item_data['obj_id'], + $a_item_data['title'], + $a_item_data['description'] + ); + + // actions + $item_list_gui->insertCommands(); + $actions = []; + foreach ($item_list_gui->current_selection_list->getItems() as $item) { + if (!isset($item["onclick"]) || $item["onclick"] == "") { + $button = + $f->button()->shy($item["title"], $item["link"]); + } else { + $button = + $f->button()->shy($item["title"], "")->withAdditionalOnLoadCode(function ($id) use ($item) { + return + "$('#$id').click(function(e) { " . $item["onclick"] . "});"; + }); + } + $actions[] = $button; + } + + + $def_command = $item_list_gui->getDefaultCommand(); + $dropdown = $f->dropdown()->standard($actions); + + $img = $DIC->object()->commonSettings()->tileImage()->getByObjId($a_item_data['obj_id']); + + if ($img->exists()) { + $path = $img->getFullPath(); + } else { + $path = ilUtil::getImagePath("cont_tile/cont_tile_default_" . $a_item_data['type'] . ".svg"); + if (!is_file($path)) { + $path = ilUtil::getImagePath("cont_tile/cont_tile_default.svg"); + } + } + + $sections = []; + $title = $a_item_data["title"]; + + // workaround for scorm + $modified_link = + $item_list_gui->modifySAHSlaunch($def_command["link"], $def_command["frame"]); + + + $image = $f->image()->responsive($path, ""); + if ($def_command["link"] != "") { // #24256 + if ($def_command["frame"] != "" && ($modified_link == $def_command["link"])) { + $image = $image->withAdditionalOnLoadCode(function ($id) use ($def_command) { + return + "$('#$id').click(function(e) { window.open('" . str_replace("&", "&", $def_command["link"]) . "', '" . $def_command["frame"] . "');});"; + }); + + $button = + $f->button()->shy($title, "")->withAdditionalOnLoadCode(function ($id) use ($def_command) { + return + "$('#$id').click(function(e) { window.open('" . str_replace("&", "&", $def_command["link"]) . "', '" . $def_command["frame"] . "');});"; + }); + $title = $r->render($button); + } else { + $image = $image->withAction($modified_link); + } + } + + // description, @todo: move to new ks element + if ($a_item_data["description"] != "") { + $sections[] = $f->legacy("
          " . $a_item_data["description"] . "
          "); + } + + if ($a_item_data["type"] == "sess") { + $app_info = ilSessionAppointment::_lookupAppointment($a_item_data['obj_id']); + if ($title != "") { + $title = ": " . $title; + } + $title = ilSessionAppointment::_appointmentToString($app_info['start'], $app_info['end'], $app_info['fullday']) . + $title; + } + + $icon = $f->icon()->standard($a_item_data["type"], $this->lng->txt("obj_" . $a_item_data["type"])) + ->withIsOutlined(true); + $card = $f->card()->repositoryObject( + $title . "", + $image + )->withObjectIcon( + $icon + )->withActions( + $dropdown + ); + + if ($def_command["link"] != "" && ($def_command["frame"] == "" || $modified_link != $def_command["link"])) { // #24256 + $card = $card->withTitleAction($modified_link); + } + + // properties + $l = []; + foreach ($item_list_gui->determineProperties() as $p) { + if ($p["property"] != $this->lng->txt("learning_progress")) { + $l[(string) $p["property"]] = (string) $p["value"]; + } + } + + if (count($l) > 0) { + $prop_list = $f->listing()->descriptive($l); + $sections[] = $prop_list; + } + if (count($sections) > 0) { + $card = $card->withSections($sections); + } + // learning progress + include_once "Services/Tracking/classes/class.ilLPStatus.php"; + $lp = ilLPStatus::getListGUIStatus($a_item_data["obj_id"], false); + if ($lp) { + $percentage = (int) ilLPStatus::_lookupPercentage($a_item_data["obj_id"], $user->getId()); + if ($lp["status"] == ilLPStatus::LP_STATUS_COMPLETED_NUM) { + $percentage = 100; + } + //var_dump(ilLPStatus::_lookupPercentage($a_item_data["obj_id"], $user->getId())); exit; + $progressmeter = $f->chart()->progressMeter()->mini(100, $percentage); + $card = $card->withProgress($progressmeter); + } + + return $card; + } + + /** + * Insert blocks into container page + */ + public function insertPageEmbeddedBlocks($a_output_html) + { + $this->determinePageEmbeddedBlocks($a_output_html); + $this->renderPageEmbeddedBlocks($this->items); + + // iterate all types + foreach ($this->getGroupedObjTypes() as $type => $v) { + // set template (overall or type specific) + if (is_int(strpos($a_output_html, "[list-" . $type . "]"))) { + $a_output_html = preg_replace( + '~\[list-' . $type . '\]~i', + $this->renderer->renderSingleTypeBlock($type), + $a_output_html + ); + } + } + + // insert all item groups + while (preg_match('~\[(item-group-([0-9]*))\]~i', $a_output_html, $found)) { + $itgr_ref_id = (int) $found[2]; + + $a_output_html = preg_replace( + '~\[' . $found[1] . '\]~i', + $this->renderer->renderSingleCustomBlock($itgr_ref_id), + $a_output_html + ); + } + + return $a_output_html; + } + + /** + * Render single block + * + * @param string block id + * @return string + */ + public function getSingleTypeBlockAsynch($type) + { + $this->initRenderer(); + // get all sub items + $this->items = $this->getContainerObject()->getSubItems( + $this->getContainerGUI()->isActiveAdministrationPanel() + ); + + + $ref_ids = array_map(function ($i) { + $parts = explode("_", $i); + return $parts[2]; + }, $_POST["ids"]); + + // iterate all types + if (is_array($this->items[$type]) && + $this->renderer->addTypeBlock($type)) { + //$this->renderer->setBlockPosition($type, ++$pos); + + $position = 1; + foreach ($this->items[$type] as $item_data) { + $item_ref_id = $item_data["child"]; + + if (in_array($item_ref_id, $ref_ids)) { + continue; + } + + if ($this->block_limit > 0 && $position == $this->block_limit + 1) { + if ($position == $this->block_limit + 1) { + // render more button + $this->renderer->addShowMoreButton($type); + } + continue; + } + + if (!$this->renderer->hasItem($item_ref_id)) { + $html = $this->renderItem($item_data, $position++); + if ($html != "") { + $this->renderer->addItemToBlock($type, $item_data["type"], $item_ref_id, $html); + } + } + } + } + + return $this->renderer->renderSingleTypeBlock($type); + } + + /** + * Get grouped repository object types. + * + * @return array array of object types + */ + public function getGroupedObjTypes() + { + $objDefinition = $this->obj_definition; + + if (empty($this->type_grps)) { + $this->type_grps = + $objDefinition->getGroupedRepositoryObjectTypes($this->getContainerObject()->getType()); + } + return $this->type_grps; + } + + /** + * Get introduction. + */ + public function getIntroduction() + { + $ilUser = $this->user; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $lng->loadLanguageModule("rep"); + + $tpl = new ilTemplate("tpl.rep_intro.html", true, true, "Services/Repository"); + $tpl->setVariable("IMG_REP_LARGE", ilObject::_getIcon("", "big", "root")); + $tpl->setVariable("TXT_WELCOME", $lng->txt("rep_intro")); + $tpl->setVariable("TXT_INTRO_1", $lng->txt("rep_intro1")); + $tpl->setVariable("TXT_INTRO_2", $lng->txt("rep_intro2")); + $tpl->setVariable("TXT_INTRO_3", sprintf($lng->txt("rep_intro3"), $lng->txt("add"))); + $tpl->setVariable("TXT_INTRO_4", sprintf($lng->txt("rep_intro4"), $lng->txt("cat_add"))); + $tpl->setVariable("TXT_INTRO_5", $lng->txt("rep_intro5")); + $tpl->setVariable("TXT_INTRO_6", $lng->txt("rep_intro6")); + + return $tpl->get(); + } + + /** + * Get item groups HTML + * + * @param + * @return + */ + public function getItemGroupsHTML($a_pos = 0) + { + if (is_array($this->items["itgr"])) { + foreach ($this->items["itgr"] as $itgr) { + if (!$this->renderer->hasCustomBlock($itgr["child"])) { + $this->renderItemGroup($itgr); + + $this->renderer->setBlockPosition($itgr["ref_id"], ++$a_pos); + } + } + } + return $a_pos; + } + + /** + * Render item group + * + * @param + * @return + */ + public function renderItemGroup($a_itgr) + { + $ilAccess = $this->access; + $ilUser = $this->user; + + // #16493 + $perm_ok = ($ilAccess->checkAccess("visible", "", $a_itgr['ref_id']) && + $ilAccess->checkAccess("read", "", $a_itgr['ref_id'])); + + include_once('./Services/Container/classes/class.ilContainerSorting.php'); + include_once('./Services/Object/classes/class.ilObjectActivation.php'); + $items = ilObjectActivation::getItemsByItemGroup($a_itgr['ref_id']); + + // if no permission is given, set the items to "rendered" but + // do not display the whole block + if (!$perm_ok) { + foreach ($items as $item) { + $this->renderer->hideItem($item["child"]); + } + return; + } + + $item_list_gui = $this->getItemGUI($a_itgr); + $item_list_gui->enableNotes(false); + $item_list_gui->enableTags(false); + $item_list_gui->enableComments(false); + $item_list_gui->enableTimings(false); + $item_list_gui->getListItemHTML( + $a_itgr["ref_id"], + $a_itgr["obj_id"], + $a_itgr["title"], + $a_itgr["description"] + ); + $commands_html = $item_list_gui->getCommandsHTML(); + + // determine behaviour + include_once("./Modules/ItemGroup/classes/class.ilObjItemGroup.php"); + include_once("./Modules/ItemGroup/classes/class.ilItemGroupBehaviour.php"); + $beh = ilObjItemGroup::lookupBehaviour($a_itgr["obj_id"]); + include_once("./Services/Container/classes/class.ilContainerBlockPropertiesStorage.php"); + $stored_val = ilContainerBlockPropertiesStorage::getProperty("itgr_" . $a_itgr["ref_id"], $ilUser->getId(), "opened"); + if ($stored_val !== false) { + $beh = ($stored_val == "1") + ? ilItemGroupBehaviour::EXPANDABLE_OPEN + : ilItemGroupBehaviour::EXPANDABLE_CLOSED; + } + + $data = array( + "behaviour" => $beh, + "store-url" => "./ilias.php?baseClass=ilcontainerblockpropertiesstorage&cmd=store" . + "&cont_block_id=itgr_" . $a_itgr['ref_id'] + ); + if (ilObjItemGroup::lookupHideTitle($a_itgr["obj_id"]) && + !$this->getContainerGUI()->isActiveAdministrationPanel()) { + $this->renderer->addCustomBlock($a_itgr["ref_id"], "", $commands_html, $data); + } else { + $this->renderer->addCustomBlock($a_itgr["ref_id"], $a_itgr["title"], $commands_html, $data); + } + + + // render item group sub items + + $items = ilContainerSorting::_getInstance( + $this->getContainerObject()->getId() + )->sortSubItems('itgr', $a_itgr['obj_id'], $items); + + // #18285 + $items = ilContainer::getCompleteDescriptions($items); + + $position = 1; + foreach ($items as $item) { + // we are NOT using hasItem() here, because item might be in multiple item groups + $html2 = $this->renderItem($item, $position++, false, "[itgr][" . $a_itgr['obj_id'] . "]"); + if ($html2 != "") { + // :TODO: show it multiple times? + $this->renderer->addItemToBlock($a_itgr["ref_id"], $item["type"], $item["child"], $html2, true); + } + } + } } - -?> \ No newline at end of file diff --git a/Services/Container/classes/class.ilContainerExporter.php b/Services/Container/classes/class.ilContainerExporter.php index dc87b8013e58499dcea5cedeb7b25b133878c8e1..576d9f325db40fb9704e95a1fdf6f511f8f707ad 100644 --- a/Services/Container/classes/class.ilContainerExporter.php +++ b/Services/Container/classes/class.ilContainerExporter.php @@ -16,88 +16,78 @@ include_once './Services/Export/classes/class.ilXmlExporter.php'; */ class ilContainerExporter extends ilXmlExporter { - private $writer = null; + private $writer = null; - /** - * Constructor - */ - public function __construct() - { - - } - - /** - * Init export - * @return - */ - public function init() - { - } - - public function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) - { - if($a_entity != 'struct') - { - return; - } - - - $res = array(); - - // pages - - $pg_ids = array(); - - // container pages - include_once("./Services/Container/classes/class.ilContainerPage.php"); - foreach($a_ids as $id) - { - if(ilContainerPage::_exists("cont", $id)) - { - $pg_ids[] = "cont:".$id; - } - } - - // container start objects pages - include_once("./Services/Container/classes/class.ilContainerStartObjectsPage.php"); - foreach($a_ids as $id) - { - if(ilContainerStartObjectsPage::_exists("cstr", $id)) - { - $pg_ids[] = "cstr:".$id; - } - } - - 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); - // see #24888 - $style_id = ilObjStyleSheet::getEffectiveContentStyleId($style_id); - if($style_id > 0) - { - $style_ids[] = $style_id; - } - } - if(sizeof($style_ids)) - { - $res[] = array( - "component" => "Services/Style", - "entity" => "sty", - "ids" => $style_ids - ); - } + /** + * Constructor + */ + public function __construct() + { + } + + /** + * Init export + * @return + */ + public function init() + { + } + + public function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) + { + if ($a_entity != 'struct') { + return; + } + + + $res = array(); + + // pages + + $pg_ids = array(); + + // container pages + include_once("./Services/Container/classes/class.ilContainerPage.php"); + foreach ($a_ids as $id) { + if (ilContainerPage::_exists("cont", $id)) { + $pg_ids[] = "cont:" . $id; + } + } + + // container start objects pages + include_once("./Services/Container/classes/class.ilContainerStartObjectsPage.php"); + foreach ($a_ids as $id) { + if (ilContainerStartObjectsPage::_exists("cstr", $id)) { + $pg_ids[] = "cstr:" . $id; + } + } + + 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); + // see #24888 + $style_id = ilObjStyleSheet::getEffectiveContentStyleId($style_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( @@ -106,46 +96,44 @@ class ilContainerExporter extends ilXmlExporter "ids" => $a_ids); return $res; - } - - /** - * Get xml - * @param object $a_entity - * @param object $a_schema_version - * @param object $a_id - * @return - */ - public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) - { - global $DIC; + } + + /** + * Get xml + * @param object $a_entity + * @param object $a_schema_version + * @param object $a_id + * @return + */ + public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) + { + global $DIC; - $log = $DIC->logger()->root(); - if($a_entity == 'struct') - { - $log->debug(__METHOD__.': Received id = '.$a_id); - $writer = new ilContainerXmlWriter(end(ilObject::_getAllReferences($a_id))); - $writer->write(); - return $writer->xmlDumpMem(false); - } - } - - /** - * Returns schema versions that the component can export to. - * ILIAS chooses the first one, that has min/max constraints which - * fit to the target release. Please put the newest on top. - * - * @return - */ - public function getValidSchemaVersions($a_entity) - { - return array ( - "4.1.0" => array( - "namespace" => "http://www.ilias.de/Modules/Folder/fold/4_1", - "xsd_file" => "ilias_fold_4_1.xsd", - "uses_dataset" => false, - "min" => "4.1.0", - "max" => "") - ); - } + $log = $DIC->logger()->root(); + if ($a_entity == 'struct') { + $log->debug(__METHOD__ . ': Received id = ' . $a_id); + $writer = new ilContainerXmlWriter(end(ilObject::_getAllReferences($a_id))); + $writer->write(); + return $writer->xmlDumpMem(false); + } + } + + /** + * Returns schema versions that the component can export to. + * ILIAS chooses the first one, that has min/max constraints which + * fit to the target release. Please put the newest on top. + * + * @return + */ + public function getValidSchemaVersions($a_entity) + { + return array( + "4.1.0" => array( + "namespace" => "http://www.ilias.de/Modules/Folder/fold/4_1", + "xsd_file" => "ilias_fold_4_1.xsd", + "uses_dataset" => false, + "min" => "4.1.0", + "max" => "") + ); + } } -?> \ No newline at end of file diff --git a/Services/Container/classes/class.ilContainerGUI.php b/Services/Container/classes/class.ilContainerGUI.php index 727a3831382adefbbf6c3848604ebfd186fd2ec0..ef59f909b430fd5ae583fc9665fdbbf5ebb81d79 100644 --- a/Services/Container/classes/class.ilContainerGUI.php +++ b/Services/Container/classes/class.ilContainerGUI.php @@ -21,1450 +21,1445 @@ include_once './Services/PersonalDesktop/interfaces/interface.ilDesktopItemHandl */ class ilContainerGUI extends ilObjectGUI implements ilDesktopItemHandling { - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilSetting - */ - protected $settings; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilDB - */ - protected $db; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * @var ilObjectDefinition - */ - protected $obj_definition; - - /** - * @var ilRbacAdmin - */ - protected $rbacadmin; - - /** - * @var ilRbacReview - */ - protected $rbacreview; - - /** - * @var Logger - */ - protected $log; - - /** - * @var ilObjectDataCache - */ - protected $obj_data_cache; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilPluginAdmin - */ - protected $plugin_admin; - - /** - * @var ilAppEventHandler - */ - protected $app_event_handler; - - var $bl_cnt = 1; // block counter - var $multi_download_enabled = false; - - /** - * @var \ILIAS\DI\UIServices - */ - protected $ui; - - /** - * Constructor - * @access public - */ - function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) - { - global $DIC; - - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - $this->ctrl = $DIC->ctrl(); - $this->tabs = $DIC->tabs(); - $this->settings = $DIC->settings(); - $this->user = $DIC->user(); - $this->db = $DIC->database(); - $this->access = $DIC->access(); - $this->tree = $DIC->repositoryTree(); - $this->error = $DIC["ilErr"]; - $this->obj_definition = $DIC["objDefinition"]; - $this->rbacadmin = $DIC->rbac()->admin(); - $this->rbacreview = $DIC->rbac()->review(); - $this->log = $DIC["ilLog"]; - $this->obj_data_cache = $DIC["ilObjDataCache"]; - $this->toolbar = $DIC->toolbar(); - $this->plugin_admin = $DIC["ilPluginAdmin"]; - $this->app_event_handler = $DIC["ilAppEventHandler"]; - $this->ui = $DIC->ui(); - $rbacsystem = $DIC->rbac()->system(); - $lng = $DIC->language(); - - $this->rbacsystem = $rbacsystem; - - $lng->loadLanguageModule("cntr"); - $lng->loadLanguageModule('cont'); - - // prepare output things should generally be made in executeCommand - // method (maybe dependent on current class/command - parent::__construct($a_data, $a_id, $a_call_by_reference, false); - } - - /** - * execute command - * note: this method is overwritten in all container objects - */ - function executeCommand() - { - $tpl = $this->tpl; - - $next_class = $this->ctrl->getNextClass(); - $cmd = $this->ctrl->getCmd("render"); - - - switch($next_class) - { - // page editing - case "ilcontainerpagegui": - if ($_GET["redirectSource"] != "ilinternallinkgui") - { - $ret = $this->forwardToPageObject(); - $tpl->setContent($ret); - } - else - { - return ""; - } - break; - - case "ilobjstylesheetgui": - $this->forwardToStyleSheet(); - break; - - default: - $this->prepareOutput(); - $cmd .= "Object"; - $this->$cmd(); - break; - } - return true; - } - - /** - * Get values for edit form - * - * @return array - */ - protected function getEditFormValues() - { - $values = parent::getEditFormValues(); - - include_once './Services/DidacticTemplate/classes/class.ilDidacticTemplateObjSettings.php'; - $values['didactic_type'] = - 'dtpl_'.ilDidacticTemplateObjSettings::lookupTemplateId($this->object->getRefId()); - - return $values; - } - - /** - * - */ - protected function afterUpdate() - { - // check if template is changed - include_once './Services/DidacticTemplate/classes/class.ilDidacticTemplateObjSettings.php'; - $current_tpl_id = (int) ilDidacticTemplateObjSettings::lookupTemplateId( - $this->object->getRefId() - ); - $new_tpl_id = (int) $this->getDidacticTemplateVar('dtpl'); - - if($new_tpl_id != $current_tpl_id) - { - $_REQUEST['tplid'] = $new_tpl_id; - - // redirect to didactic template confirmation - include_once './Services/DidacticTemplate/classes/class.ilDidacticTemplateGUI.php'; - $this->ctrl->setReturn($this,'edit'); - $this->ctrl->setCmdClass('ildidactictemplategui'); - $this->ctrl->setCmd('confirmTemplateSwitch'); - $dtpl_gui = new ilDidacticTemplateGUI($this); - return $this->ctrl->forwardCommand($dtpl_gui); - } - parent::afterUpdate(); - } - - - /** - * Forward to style object - */ - function forwardToStyleSheet() - { - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - $ilTabs->clearTargets(); - - $cmd = $ilCtrl->getCmd(); - 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" || $_GET["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"); - } - } - - - /** - * forward command to page object - */ - function &forwardToPageObject() - { - $lng = $this->lng; - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - - $cmd = $ilCtrl->getCmd(); - - if (in_array($cmd, array("displayMediaFullscreen", "downloadFile", "displayMedia"))) - { - $this->checkPermission("read"); - } - else - { - $this->checkPermission("write"); - } - - $ilTabs->clearTargets(); - - if ($_GET["redirectSource"] == "ilinternallinkgui") - { - exit; - } - - $xpage_id = ilContainer::_lookupContainerSetting($this->object->getId(), - "xhtml_page"); - if ($xpage_id > 0) - { - $ilTabs->setBackTarget($lng->txt("cntr_back_to_old_editor"), - $ilCtrl->getLinkTarget($this, "switchToOldEditor"), "_top"); - } - else - { - $ilTabs->setBackTarget($lng->txt("back"), "./goto.php?target=".$this->object->getType()."_". - $this->object->getRefId(), "_top"); - } - - // page object - include_once("./Services/Container/classes/class.ilContainerPage.php"); - include_once("./Services/Container/classes/class.ilContainerPageGUI.php"); - - $lng->loadLanguageModule("content"); - - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->object->getStyleSheetId())); - $this->tpl->setCurrentBlock("SyntaxStyle"); - $this->tpl->setVariable("LOCATION_SYNTAX_STYLESHEET", - ilObjStyleSheet::getSyntaxStylePath()); - $this->tpl->parseCurrentBlock(); - - if (!ilContainerPage::_exists("cont", - $this->object->getId())) - { - // doesn't exist -> create new one - $new_page_object = new ilContainerPage(); - $new_page_object->setParentId($this->object->getId()); - $new_page_object->setId($this->object->getId()); - $new_page_object->createFromXML(); - } - - // get page object - $this->ctrl->setReturnByClass("ilcontainerpagegui", "edit"); - $page_gui = new ilContainerPageGUI($this->object->getId()); - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $page_gui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId( - $this->object->getStyleSheetId(), $this->object->getType())); - - $page_gui->setTemplateTargetVar("ADM_CONTENT"); - $page_gui->setFileDownloadLink(""); - $page_gui->setFullscreenLink($this->ctrl->getLinkTarget($this, "showMediaFullscreen")); - //$page_gui->setLinkParams($this->ctrl->getUrlParameterString()); // todo - $page_gui->setPresentationTitle(""); - $page_gui->setTemplateOutput(false); - - // old editor information text - $xpage_id = ilContainer::_lookupContainerSetting($this->object->getId(), - "xhtml_page"); - if ($xpage_id > 0) - { - $wtpl = new ilTemplate("tpl.cntr_old_editor_message.html", true, - true, "Services/Container"); - $wtpl->setVariable("ALT_WARNING", $lng->txt("warning")); - $wtpl->setVariable("IMG_WARNING", - ilUtil::getImagePath("icon_alert.svg")); - $wtpl->setVariable("TXT_MIGRATION_INFO", $lng->txt("cntr_switch_to_new_editor_message")); - $wtpl->setVariable("TXT_MIGRATION_INFO", $lng->txt("cntr_switch_to_new_editor_message")); - $wtpl->setVariable("HREF_SWITCH_TO_NEW_EDITOR", - $ilCtrl->getLinkTarget($this, "useNewEditor")); - $wtpl->setVariable("TXT_MIGRATION_SWITCH", - $lng->txt("cntr_switch_to_new_editor_cmd")); - $page_gui->setPrependingHtml($wtpl->get()); - } - - // style tab - $page_gui->setTabHook($this, "addPageTabs"); - - $ret = $this->ctrl->forwardCommand($page_gui); - - //$ret =& $page_gui->executeCommand(); - return $ret; - } - - /** - * Add page tabs - */ - function addPageTabs() - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - - $ilTabs->addTarget("obj_sty", - $ilCtrl->getLinkTarget($this, 'editStyleProperties'), "editStyleProperties"); - } - - /** - * Get container page HTML - */ - function getContainerPageHTML() - { - $ilSetting = $this->settings; - $ilUser = $this->user; - - if (!$ilSetting->get("enable_cat_page_edit")) - { - return; - } - - // old page editor content - $xpage_id = ilContainer::_lookupContainerSetting($this->object->getId(), - "xhtml_page"); - if ($xpage_id > 0) - { - include_once("Services/XHTMLPage/classes/class.ilXHTMLPage.php"); - $xpage = new ilXHTMLPage($xpage_id); - return $xpage->getContent(); - } - - - // page object - - - // if page does not exist, return nothing - include_once("./Services/COPage/classes/class.ilPageUtil.php"); - if (!ilPageUtil::_existsAndNotEmpty("cont", - $this->object->getId())) - { - return ""; - } - include_once("./Services/Container/classes/class.ilContainerPage.php"); - include_once("./Services/Container/classes/class.ilContainerPageGUI.php"); - - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->object->getStyleSheetId())); - $this->tpl->setCurrentBlock("SyntaxStyle"); - $this->tpl->setVariable("LOCATION_SYNTAX_STYLESHEET", - ilObjStyleSheet::getSyntaxStylePath()); - $this->tpl->parseCurrentBlock(); - - // get page object - include_once("./Services/Object/classes/class.ilObjectTranslation.php"); - $ot = ilObjectTranslation::getInstance($this->object->getId()); - $lang = $ot->getEffectiveContentLang($ilUser->getCurrentLanguage(), "cont"); - $page_gui = new ilContainerPageGUI($this->object->getId(), 0, $lang); - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $page_gui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId( - $this->object->getStyleSheetId(), $this->object->getType())); - - $page_gui->setPresentationTitle(""); - $page_gui->setTemplateOutput(false); - $page_gui->setHeader(""); - $ret = $page_gui->showPage(); - - //$ret = "
          ".$ret."
          "; - - //$ret =& $page_gui->executeCommand(); - return $ret; - } - - /** - * prepare output - */ - public function prepareOutput($a_show_subobjects = true) - { - if (parent::prepareOutput($a_show_subobjects)) // return false in admin mode - { - if ($this->getCreationMode() != true && $a_show_subobjects) - { - // This method is called directly from ilContainerGUI::renderObject - #$this->showPossibleSubObjects(); - $this->showTreeFlatIcon(); - - // Member view - include_once './Services/Container/classes/class.ilMemberViewGUI.php'; - ilMemberViewGUI::showMemberViewSwitch($this->object->getRefId()); - } - } - } - - function showTreeFlatIcon() - { - $tpl = $this->tpl; - - // dont show icon, if role (permission gui->rolegui) is edited - if ($_GET["obj_id"] != "") - { - return; - } - // hide for member view - include_once './Services/Container/classes/class.ilMemberViewSettings.php'; - if(ilMemberViewSettings::getInstance()->isActive()) - { - return; - } - - $mode = ($_SESSION["il_rep_mode"] == "flat") - ? "tree" - : "flat"; - $link = "ilias.php?baseClass=ilRepositoryGUI&cmd=frameset&set_mode=".$mode."&ref_id=".$this->object->getRefId(); - $tpl->setTreeFlatIcon($link, $mode); - } - - /** - * called by prepare output - */ - function setTitleAndDescription() - { - if (!ilContainer::_lookupContainerSetting($this->object->getId(), "hide_header_icon_and_title")) - { - $this->tpl->setTitle($this->object->getTitle()); - $this->tpl->setDescription($this->object->getLongDescription()); - - // set tile icon - $icon = ilObject::_getIcon($this->object->getId(), "big", $this->object->getType()); - $this->tpl->setTitleIcon($icon, $this->lng->txt("obj_".$this->object->getType())); - - include_once './Services/Object/classes/class.ilObjectListGUIFactory.php'; - $lgui = ilObjectListGUIFactory::_getListGUIByType($this->object->getType()); - $lgui->initItem($this->object->getRefId(), $this->object->getId()); - $this->tpl->setAlertProperties($lgui->getAlertProperties()); - } - } - - /** - * show possible sub objects selection list - */ - function showPossibleSubObjects() - { - include_once "Services/Object/classes/class.ilObjectAddNewItemGUI.php"; - $gui = new ilObjectAddNewItemGUI($this->object->getRefId()); - $gui->render(); - } - - /** - * Get content gui object - * - * @param - * @return - */ - function getContentGUI() - { - switch ($this->object->getViewMode()) - { - // all items in one block - case ilContainer::VIEW_SIMPLE: - include_once("./Services/Container/classes/class.ilContainerSimpleContentGUI.php"); - $container_view = new ilContainerSimpleContentGUI($this); - break; - - case ilContainer::VIEW_OBJECTIVE: - include_once('./Services/Container/classes/class.ilContainerObjectiveGUI.php'); - $container_view = new ilContainerObjectiveGUI($this); - break; - - // all items in one block - case ilContainer::VIEW_SESSIONS: - case ilCourseConstants::IL_CRS_VIEW_TIMING: // not nice this workaround - include_once("./Services/Container/classes/class.ilContainerSessionsContentGUI.php"); - $container_view = new ilContainerSessionsContentGUI($this); - break; - - // all items in one block - case ilContainer::VIEW_BY_TYPE: - default: - include_once("./Services/Container/classes/class.ilContainerByTypeContentGUI.php"); - $container_view = new ilContainerByTypeContentGUI($this); - break; - } - - return $container_view; - } - - - - /** - * render the object - */ - function renderObject() - { - $ilDB = $this->db; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $ilSetting = $this->settings; - - $container_view = $this->getContentGUI(); - - $this->setContentSubTabs(); - if ($this->isActiveAdministrationPanel()) - { - $ilTabs->activateSubTab("manage"); - } - else - { - $ilTabs->activateSubTab("view_content"); - } - - $container_view->setOutput(); - - $this->adminCommands = $container_view->adminCommands; - - // it is important not to show the subobjects/admin panel here, since - // we will create nested forms in case, e.g. a news/calendar item is added - if ($ilCtrl->getNextClass() != "ilcolumngui") - { - $this->showAdministrationPanel(); - $this->showPossibleSubObjects(); - } - - $this->showPermanentLink(); - - // add tree updater javascript - if ((int) $_GET["ref_id"] > 1 && $ilSetting->get("rep_tree_synchronize")) - { - $ilCtrl->setParameter($this, "active_node", (int) $_GET["ref_id"]); - } - } - - /** - * render the object - */ - function renderBlockAsynchObject() - { - $container_view = $this->getContentGUI(); - echo $container_view->getSingleTypeBlockAsynch($_GET["type"]); - exit; - } - - - /** - * Set content sub tabs - */ - function setContentSubTabs() - { - $this->addStandardContainerSubTabs(); - } - - /** - * show administration panel - */ - function showAdministrationPanel() - { - global $DIC; - - $ilAccess = $this->access; - $lng = $this->lng; - - $main_tpl = $DIC->ui()->mainTemplate(); - - $lng->loadLanguageModule('cntr'); - - if ($_SESSION["clipboard"]) - { - // #11545 - $main_tpl->setPageFormAction($this->ctrl->getFormAction($this)); - - include_once './Services/UIComponent/Toolbar/classes/class.ilToolbarGUI.php'; - $toolbar = new ilToolbarGUI(); - $this->ctrl->setParameter($this, "type", ""); - $this->ctrl->setParameter($this, "item_ref_id", ""); - - $toolbar->addFormButton( - $this->lng->txt('paste_clipboard_items'), - 'paste' - ); - - $toolbar->addFormButton( - $this->lng->txt('clear_clipboard'), - 'clear' - ); - - $main_tpl->addAdminPanelToolbar($toolbar, true, false); - } - else if ($this->isActiveAdministrationPanel()) - { - // #11545 - $main_tpl->setPageFormAction($this->ctrl->getFormAction($this)); - - include_once './Services/UIComponent/Toolbar/classes/class.ilToolbarGUI.php'; - $toolbar = new ilToolbarGUI(); - $this->ctrl->setParameter($this, "type", ""); - $this->ctrl->setParameter($this, "item_ref_id", ""); - -// if (!$_SESSION["clipboard"]) -// { - if ($this->object->gotItems()) - { - $toolbar->setLeadingImage( - ilUtil::getImagePath("arrow_upright.svg"), - $lng->txt("actions") - ); - $toolbar->addFormButton( - $this->lng->txt('delete_selected_items'), - 'delete' - ); - $toolbar->addFormButton( - $this->lng->txt('move_selected_items'), - 'cut' - ); - $toolbar->addFormButton( - $this->lng->txt('copy_selected_items'), - 'copy' - ); - $toolbar->addFormButton( - $this->lng->txt('link_selected_items'), - 'link' - ); - // add download button if multi download enabled - $folder_set = new ilSetting("fold"); - if ($folder_set->get("enable_multi_download") == true) - { - $toolbar->addSeparator(); - - if(!$folder_set->get("bgtask_download", 0)) - { - $toolbar->addFormButton( - $this->lng->txt('download_selected_items'), - 'download' - ); - } - else - { - - $url = $this->ctrl->getLinkTargetByClass(array("ilrepositorygui", "ilobjfoldergui", "ilbackgroundtaskhub"), "", "", true, false); - $main_tpl->addJavaScript("Services/BackgroundTask/js/BgTask.js"); - $main_tpl->addOnLoadCode("il.BgTask.initMultiForm('ilFolderDownloadBackgroundTaskHandler');"); - $main_tpl->addOnLoadCode('il.BgTask.setAjax("'.$url.'");'); - - include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; - $button = ilSubmitButton::getInstance(); - $button->setCaption("download_selected_items"); - $button->addCSSClass("ilbgtasksubmit"); - $button->setCommand("download"); - $toolbar->addButtonInstance($button); - } - } - } - if($this->object->getType() == 'crs' or $this->object->getType() == 'grp') - { - if($this->object->gotItems()) - { - $toolbar->addSeparator(); - } - - $toolbar->addButton( - $this->lng->txt('cntr_adopt_content'), - $this->ctrl->getLinkTargetByClass( - 'ilObjectCopyGUI', - 'adoptContent') - ); - } -// } - /*else - { - - if ($this->isMultiDownloadEnabled()) - { - $toolbar->addSeparator(); - $toolbar->addFormButton( - $this->lng->txt('download_selected_items'), - 'download' - ); - } - }*/ - - $main_tpl->addAdminPanelToolbar( - $toolbar, - ($this->object->gotItems() && !$_SESSION["clipboard"]) ? true : false, - ($this->object->gotItems() && !$_SESSION["clipboard"]) ? true : false - ); - - // form action needed, see http://www.ilias.de/mantis/view.php?id=9630 - if ($this->object->gotItems()) - { - $main_tpl->setPageFormAction($this->ctrl->getFormAction($this)); - } - } - else - { - if ($this->edit_order) - { - if($this->object->gotItems() and $ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - include_once('./Services/Container/classes/class.ilContainer.php'); - - if ($this->isActiveOrdering()) - { - // #11843 - $main_tpl->setPageFormAction($this->ctrl->getFormAction($this)); - - include_once './Services/UIComponent/Toolbar/classes/class.ilToolbarGUI.php'; - $toolbar = new ilToolbarGUI(); - $this->ctrl->setParameter($this, "type", ""); - $this->ctrl->setParameter($this, "item_ref_id", ""); - - $toolbar->addFormButton( - $this->lng->txt('sorting_save'), - 'saveSorting' - ); - - $main_tpl->addAdminPanelToolbar($toolbar, true, false); - - } - } - } - // bugfix mantis 24559 - // undoing an erroneous change inside mantis 23516 by adding "Download Multiple Objects"-functionality for non-admins - // as they don't have the possibility to use the multi-download-capability of the manage-tab - else if ($this->isMultiDownloadEnabled()) - { - // bugfix mantis 0021272 - $ref_id = $_GET['ref_id']; - $num_files = $this->tree->getChildsByType($ref_id, "file"); - $num_folders = $this->tree->getChildsByType($ref_id, "fold"); - if(count($num_files) > 0 OR count($num_folders) > 0) - { - // #11843 - $GLOBALS['tpl']->setPageFormAction($this->ctrl->getFormAction($this)); - - include_once './Services/UIComponent/Toolbar/classes/class.ilToolbarGUI.php'; - $toolbar = new ilToolbarGUI(); - $this->ctrl->setParameter($this, "type", ""); - $this->ctrl->setParameter($this, "item_ref_id", ""); - - $toolbar->addFormButton( - $this->lng->txt('download_selected_items'), - 'download' - ); - - $GLOBALS['tpl']->addAdminPanelToolbar( - $toolbar, - $this->object->gotItems() ? true : false, - $this->object->gotItems() ? true : false - ); - } - else - { - ilUtil::sendInfo($this->lng->txt('msg_no_downloadable_objects'), true); - } - } - } - } - - function __showTimingsButton(&$tpl) - { - $tree = $this->tree; - - if(!$tree->checkForParentType($this->object->getRefId(),'crs')) - { - return false; - } - $tpl->setCurrentBlock("custom_button"); - $tpl->setVariable("ADMIN_MODE_LINK",$this->ctrl->getLinkTargetByClass('ilcoursecontentgui','editTimings')); - $tpl->setVariable("TXT_ADMIN_MODE",$this->lng->txt('timings_edit')); - $tpl->parseCurrentBlock(); - return true; - } - /** - * show permanent link - */ - function showPermanentLink() - { - global $DIC; - - $tpl = $DIC->ui()->mainTemplate(); - - $tpl->setPermanentLink($this->object->getType(), - $this->object->getRefId(), "", "_top"); - } - - /** - * Switch to standard page editor - */ - function switchToStdEditorObject() - { - $ilCtrl = $this->ctrl; - - $_SESSION["il_cntr_editor"] = "std"; - $ilCtrl->redirect($this, "editPageFrame"); - } - - /** - * Switch to old page editor - */ - function switchToOldEditorObject() - { - $ilCtrl = $this->ctrl; - - $_SESSION["il_cntr_editor"] = "old"; - $ilCtrl->redirect($this, "editPageFrame"); - } - - /** - * Use new editor (-> delete xhtml content page) - */ - function useNewEditorObject() - { - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - include_once("./Services/XHTMLPage/classes/class.ilXHTMLPage.php"); - - /* keep old page content for now... - $xpage_id = ilContainer::_lookupContainerSetting($this->object->getId(), - "xhtml_page"); - if ($xpage_id) - { - $xpage = new ilXHTMLPage($xpage_id); - } - */ - - ilContainer::_writeContainerSetting($this->object->getId(), - "xhtml_page", 0); - - ilUtil::sendSuccess($lng->txt("cntr_switched_editor"), true); - } - - $ilCtrl->redirect($this, "editPageFrame"); - } - - /** - * show page editor frameset - */ - function editPageFrameObject() - { - // old tiny stuff - $xpage_id = ilContainer::_lookupContainerSetting($this->object->getId(), - "xhtml_page"); - if ($xpage_id > 0 && $_SESSION["il_cntr_editor"] != "std") - { - $this->ctrl->redirect($this, "editPageContent"); - } - else - { - $this->ctrl->redirectByClass(array("ilcontainerpagegui"), "edit"); - } - } - - /** - * edit page content (for repository root node and categories) - * - * @access public - */ - function editPageContentObject() - { - $rbacsystem = $this->rbacsystem; - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilErr = $this->error; - - if (!$rbacsystem->checkAccess("write", $this->ref_id)) - { - $ilErr->raiseError($this->lng->txt("msg_no_perm_write"), $ilErr->MESSAGE); - } - - $xpage_id = ilContainer::_lookupContainerSetting($this->object->getId(), - "xhtml_page"); - if ($xpage_id > 0) - { - include_once("Services/XHTMLPage/classes/class.ilXHTMLPage.php"); - $xpage = new ilXHTMLPage($xpage_id); - $content = $xpage->getContent(); - } - - // get template - $tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.container_edit_page_content.html", - "Services/Container"); - $tpl->setVariable("VAL_CONTENT", ilUtil::prepareFormOutput($content)); - $tpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this)); - $tpl->setVariable("TXT_EDIT_PAGE_CONTENT", - $this->lng->txt("edit_page_content")); - $tpl->setVariable("TXT_SAVE", $this->lng->txt("save")); - $tpl->setVariable("TXT_CANCEL", $this->lng->txt("cancel")); - $tpl->setVariable("TXT_MIGRATION_INFO", $lng->txt("cntr_old_editor_warning")); - $tpl->setVariable("TXT_MIGRATION_OPEN_STD_EDITOR", $lng->txt("cntr_old_editor_open_standard_editor")); - $tpl->setVariable("IMG_WARNING", ilUtil::getImagePath("icon_alert.svg")); - $tpl->setVariable("HREF_OPEN_STD_EDITOR", $ilCtrl->getLinkTarget($this, "switchToStdEditor")); - $tpl->setVariable("ALT_WARNING", $lng->txt("warning")); - - include_once("./Services/Form/classes/class.ilFormPropertyGUI.php"); - include_once("./Services/Form/classes/class.ilTextAreaInputGUI.php"); - //$ta = new ilTextAreaInputGUI(); - //$tags = $ta->getRteTagSet("extended_table_img"); - - // add rte support - include_once "./Services/RTE/classes/class.ilRTE.php"; - $rtestring = ilRTE::_getRTEClassname(); - include_once "./Services/RTE/classes/class.$rtestring.php"; - $rte = new $rtestring(); - //$rte->addPlugin("latex"); - include_once "./Services/Object/classes/class.ilObject.php"; - $obj_id = ilObject::_lookupObjectId($_GET["ref_id"]); - $obj_type = ilObject::_lookupType($_GET["ref_id"], TRUE); - $rte->addRTESupport($obj_id, $obj_type); - //$rte->setStyleSelect(true); - //$rte->addCustomRTESupport($obj_id, $obj_type, $tags); - } - - function savePageContentObject() - { - include_once("Services/XHTMLPage/classes/class.ilXHTMLPage.php"); - include_once "./Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php"; - $xpage_id = ilContainer::_lookupContainerSetting($this->object->getId(), - "xhtml_page"); - - /*include_once("./Services/Form/classes/class.ilFormPropertyGUI.php"); - include_once("./Services/Form/classes/class.ilTextAreaInputGUI.php"); - $ta = new ilTextAreaInputGUI(); - $ta->setRteTagSet("extended_table_img"); - $tags = $ta->getRteTagString();*/ - - //$text = ilUtil::stripSlashes($_POST["page_content"], - // true, - // $tags); - - $text = ilUtil::stripSlashes($_POST["page_content"], - true, - ilObjAdvancedEditing::_getUsedHTMLTagsAsString()); - if ($xpage_id > 0) - { - $xpage = new ilXHTMLPage($xpage_id); - $xpage->setContent($text); - $xpage->save(); - } - else - { - $xpage = new ilXHTMLPage(); - $xpage->setContent($text); - $xpage->save(); - ilContainer::_writeContainerSetting($this->object->getId(), - "xhtml_page", $xpage->getId()); - } - - include_once("Services/RTE/classes/class.ilRTE.php"); - ilRTE::_cleanupMediaObjectUsage($text, $this->object->getType().":html", - $this->object->getId()); - - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, ""); - } - - function cancelPageContentObject() - { - $this->ctrl->redirect($this, ""); - } - - function showLinkListObject() - { - $lng = $this->lng; - $tree = $this->tree; - - $tpl = new ilTemplate("tpl.container_link_help.html", true, true, - "Services/Container"); - - $type_ordering = array( - "cat", "fold", "crs", "grp", "chat", "frm", "lres", - "glo", "webr", "file", "exc", - "tst", "svy", "mep", "qpl", "spl"); - - $childs = $tree->getChilds($_GET["ref_id"]); - foreach($childs as $child) - { - if (in_array($child["type"], array("lm", "sahs", "htlm"))) - { - $cnt["lres"]++; - } - else - { - $cnt[$child["type"]]++; - } - } - - $tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); - $tpl->setVariable("TXT_HELP_HEADER", $lng->txt("help")); - foreach($type_ordering as $type) - { - $tpl->setCurrentBlock("row"); - $tpl->setVariable("ROWCOL", "tblrow".((($i++)%2)+1)); - if ($type != "lres") - { - $tpl->setVariable("TYPE", $lng->txt("objs_".$type). - " (".((int)$cnt[$type]).")"); - } - else - { - $tpl->setVariable("TYPE", $lng->txt("obj_lrss"). - " (".((int)$cnt["lres"]).")"); - } - $tpl->setVariable("TXT_LINK", "[list-".$type."]"); - $tpl->parseCurrentBlock(); - } - $tpl->show(); - exit; - - } - - /** - * cleaer administration commands determination - */ - function clearAdminCommandsDetermination() - { - $this->adminCommands = false; - } - - /** - * determin admin commands - */ -/* function determineAdminCommands($a_ref_id, $a_admin_com_included_in_list = false) - { - if (!$this->adminCommands) - { - if (!$this->isActiveAdministrationPanel()) - { - if ($this->rbacsystem->checkAccess("delete", $a_ref_id)) - { - $this->adminCommands = true; - } - } - else - { - $this->adminCommands = $a_admin_com_included_in_list; - } - } - }*/ - - /** - * returns a new list block template - * - * @access private - * @return object block template - */ - function &newBlockTemplate() - { - $tpl = new ilTemplate("tpl.container_list_block.html", true, true, - "Services/Container"); - $this->cur_row_type = "row_type_1"; - return $tpl; - } - - /** - * adds a header row to a block template - * - * @param object $a_tpl block template - * @param string $a_type object type - * @access private - */ - function addHeaderRow(&$a_tpl, $a_type, $a_show_image = true) - { - $icon = ilUtil::getImagePath("icon_".$a_type.".svg"); - $title = $this->lng->txt("objs_".$a_type); - - if ($a_show_image) - { - $a_tpl->setCurrentBlock("container_header_row_image"); - $a_tpl->setVariable("HEADER_IMG", $icon); - $a_tpl->setVariable("HEADER_ALT", $title); - } - else - { - $a_tpl->setCurrentBlock("container_header_row"); - } - - $a_tpl->setVariable("BLOCK_HEADER_CONTENT", $title); - $a_tpl->parseCurrentBlock(); - //$a_tpl->touchBlock("container_row"); - } - - /** - * adds a standard row to a block template - * - * @param object $a_tpl block template - * @param string $a_html html code - * @access private - */ - function addStandardRow(&$a_tpl, $a_html, $a_item_ref_id = "", $a_item_obj_id = "", - $a_image_type = "") - { - $ilSetting = $this->settings; - - $this->cur_row_type = ($this->cur_row_type == "row_type_1") - ? "row_type_2" - : "row_type_1"; - - $a_tpl->touchBlock($this->cur_row_type); - - $nbsp = true; - if ($ilSetting->get("icon_position_in_lists") == "item_rows") - { - $icon = ilUtil::getImagePath("icon_".$a_image_type.".svg"); - $alt = $this->lng->txt("obj_".$a_image_type); - - if ($ilSetting->get('custom_icons')) { - global $DIC; - /** @var \ilObjectCustomIconFactory $customIconFactory */ - $customIconFactory = $DIC['object.customicons.factory']; - $customIcon = $customIconFactory->getPresenterByObjId($a_item_obj_id, $a_image_type); - - if ($customIcon->exists()) { - $icon = $customIcon->getFullPath(); - } - } - - $a_tpl->setCurrentBlock("block_row_image"); - $a_tpl->setVariable("ROW_IMG", $icon); - $a_tpl->setVariable("ROW_ALT", $alt); - $a_tpl->parseCurrentBlock(); - $nbsp = false; - } - - if ($this->isActiveAdministrationPanel()) - { - $a_tpl->setCurrentBlock("block_row_check"); - $a_tpl->setVariable("ITEM_ID", $a_item_ref_id); - $a_tpl->parseCurrentBlock(); - $nbsp = false; - } - include_once('Services/Container/classes/class.ilContainerSortingSettings.php'); - if($this->isActiveAdministrationPanel() && - ilContainerSortingSettings::_lookupSortMode($this->object->getId()) == ilContainer::SORT_MANUAL) - { - $a_tpl->setCurrentBlock('block_position'); - $a_tpl->setVariable('POS_TYPE',$a_image_type); - $a_tpl->setVariable('POS_ID',$a_item_ref_id); - $a_tpl->setVariable('POSITION',sprintf('%.1f',$this->current_position++)); - $a_tpl->parseCurrentBlock(); - } - if ($nbsp) - { - $a_tpl->setVariable("ROW_NBSP", " "); - } - $a_tpl->setCurrentBlock("container_standard_row"); - $a_tpl->setVariable("BLOCK_ROW_CONTENT", $a_html); - $a_tpl->parseCurrentBlock(); - $a_tpl->touchBlock("container_row"); - } - - /** - * add message row - */ - function addMessageRow(&$a_tpl, $a_message, $a_type) - { - $this->cur_row_type = ($this->cur_row_type == "row_type_1") - ? "row_type_2" - : "row_type_1"; - - $a_tpl->touchBlock($this->cur_row_type); - - $type = $this->lng->txt("obj_".$a_type); - $a_message = str_replace("[type]", $type, $a_message); - - $a_tpl->setVariable("ROW_NBSP", " "); - - $a_tpl->setCurrentBlock("container_standard_row"); - $a_tpl->setVariable("BLOCK_ROW_CONTENT", - $a_message); - $a_tpl->parseCurrentBlock(); - $a_tpl->touchBlock("container_row"); - } - - function resetRowType() - { - $this->cur_row_type = ""; - } - - - /** - * Add page editor tabs - */ - function setPageEditorTabs() - { - $lng = $this->lng; - - if (!$this->isActiveAdministrationPanel() - || strtolower($this->ctrl->getCmdClass()) != "ilcontainerpagegui") - { - return; - } - - $lng->loadLanguageModule("content"); - //$tabs_gui = new ilTabsGUI(); - //$tabs_gui->setSubTabs(); - - // back to upper context - $this->tabs_gui->setBackTarget($this->lng->txt("obj_cat"), - $this->ctrl->getLinkTarget($this, "frameset"), - ilFrameTargetInfo::_getFrame("MainContent")); - - $this->tabs_gui->addTarget("edit", $this->ctrl->getLinkTargetByClass("ilcontainerpagegui", "view") - , array("", "view"), "ilcontainerpagegui"); - - //$this->tpl->setTabs($tabs_gui->getHTML()); - } - - /** - * Add standar container subtabs for view, manage, oderdering and text/media editor link - */ - function addStandardContainerSubTabs($a_include_view = true) - { - $ilTabs = $this->tabs; - $ilAccess = $this->access; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - $ilSetting = $this->settings; - - if (!is_object($this->object)) - { - return; - } - - if ($a_include_view && $ilAccess->checkAccess("read", "", $this->object->getRefId())) - { - if (!$this->isActiveAdministrationPanel()) - { - $ilTabs->addSubTab("view_content", $lng->txt("view"), $ilCtrl->getLinkTarget($this, "view")); - } - else - { - $ilTabs->addSubTab("view_content", $lng->txt("view"), $ilCtrl->getLinkTarget($this, "disableAdministrationPanel")); - } - } - - if ( $ilUser->getId() != ANONYMOUS_USER_ID && - ($this->adminCommands || - (is_object($this->object) && - ($ilAccess->checkAccess("write", "", $this->object->getRefId()))) - || - (is_object($this->object) && - ($this->object->getHiddenFilesFound())) || - $_SESSION["clipboard"] - ) - ) - { - if ($this->isActiveAdministrationPanel()) - { - $ilTabs->addSubTab("manage", $lng->txt("cntr_manage"), $ilCtrl->getLinkTarget($this, "")); - } - else - { - $ilTabs->addSubTab("manage", $lng->txt("cntr_manage"), $ilCtrl->getLinkTarget($this, "enableAdministrationPanel")); - } - } - if ($ilUser->getId() != ANONYMOUS_USER_ID && - is_object($this->object) && - $ilAccess->checkAccess("write", "", $this->object->getRefId()) /* && - $this->object->getOrderType() == ilContainer::SORT_MANUAL */ // always on because of custom block order - ) - { - $ilTabs->addSubTab("ordering", $lng->txt("cntr_ordering"), $ilCtrl->getLinkTarget($this, "editOrder")); - } - if ($ilUser->getId() != ANONYMOUS_USER_ID && - is_object($this->object) && - $ilAccess->checkAccess("write", "", $this->object->getRefId()) - ) - { - if ($ilSetting->get("enable_cat_page_edit")) - { - $ilTabs->addSubTab("page_editor", $lng->txt("cntr_text_media_editor"), $ilCtrl->getLinkTarget($this, "editPageFrame"), - ilFrameTargetInfo::_getFrame("MainContent")); - } - } - } - - - /** - * common tabs for all container objects (should be called - * at the end of child getTabs() method - */ - function getTabs() - { - $rbacsystem = $this->rbacsystem; - $ilCtrl = $this->ctrl; - - // edit permissions - if ($rbacsystem->checkAccess('edit_permission',$this->ref_id)) - { - $this->tabs_gui->addTarget("perm_settings", - $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm"), - array("perm","info","owner"), 'ilpermissiongui'); - if ($ilCtrl->getNextClass() == "ilpermissiongui") - { - $this->tabs_gui->activateTab("perm_settings"); - } - } - - // show clipboard - if (strtolower($_GET["baseClass"]) == "ilrepositorygui" && !empty($_SESSION["clipboard"])) - { - $this->tabs_gui->addTarget("clipboard", - $this->ctrl->getLinkTarget($this, "clipboard"), "clipboard", get_class($this)); - } - - } - - //***************** - // COMMON METHODS (may be overwritten in derived classes - // if special handling is necessary) - //***************** - - /** - * enable administration panel - */ - function enableAdministrationPanelObject() - { - $_SESSION["il_cont_admin_panel"] = true; - $this->ctrl->redirect($this, "render"); - } - - /** - * enable administration panel - */ - function disableAdministrationPanelObject() - { - $_SESSION["il_cont_admin_panel"] = false; - $this->ctrl->redirect($this, "render"); - } - - /** - * Edit order - */ - function editOrderObject() - { - $ilTabs = $this->tabs; - - $this->edit_order = true; - $_SESSION["il_cont_admin_panel"] = false; - $this->renderObject(); - - $ilTabs->activateSubTab("ordering"); - } - - /** - * Check if ordering is enabled - * @return bool - */ - public function isActiveOrdering() - { - return $this->edit_order ? true : false; - } - - /** - * Check if item ordering is enabled - * @return bool - */ - public function isActiveItemOrdering() - { - if($this->isActiveOrdering()) - { - return (ilContainerSortingSettings::_lookupSortMode($this->object->getId()) == ilContainer::SORT_MANUAL); - } - return false; - } - + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilDB + */ + protected $db; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilObjectDefinition + */ + protected $obj_definition; + + /** + * @var ilRbacAdmin + */ + protected $rbacadmin; + + /** + * @var ilRbacReview + */ + protected $rbacreview; + + /** + * @var Logger + */ + protected $log; + + /** + * @var ilObjectDataCache + */ + protected $obj_data_cache; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilPluginAdmin + */ + protected $plugin_admin; + + /** + * @var ilAppEventHandler + */ + protected $app_event_handler; + + public $bl_cnt = 1; // block counter + public $multi_download_enabled = false; + + /** + * @var \ILIAS\DI\UIServices + */ + protected $ui; + + /** + * Constructor + * @access public + */ + public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) + { + global $DIC; + + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + $this->ctrl = $DIC->ctrl(); + $this->tabs = $DIC->tabs(); + $this->settings = $DIC->settings(); + $this->user = $DIC->user(); + $this->db = $DIC->database(); + $this->access = $DIC->access(); + $this->tree = $DIC->repositoryTree(); + $this->error = $DIC["ilErr"]; + $this->obj_definition = $DIC["objDefinition"]; + $this->rbacadmin = $DIC->rbac()->admin(); + $this->rbacreview = $DIC->rbac()->review(); + $this->log = $DIC["ilLog"]; + $this->obj_data_cache = $DIC["ilObjDataCache"]; + $this->toolbar = $DIC->toolbar(); + $this->plugin_admin = $DIC["ilPluginAdmin"]; + $this->app_event_handler = $DIC["ilAppEventHandler"]; + $this->ui = $DIC->ui(); + $rbacsystem = $DIC->rbac()->system(); + $lng = $DIC->language(); + + $this->rbacsystem = $rbacsystem; + + $lng->loadLanguageModule("cntr"); + $lng->loadLanguageModule('cont'); + + // prepare output things should generally be made in executeCommand + // method (maybe dependent on current class/command + parent::__construct($a_data, $a_id, $a_call_by_reference, false); + } + + /** + * execute command + * note: this method is overwritten in all container objects + */ + public function executeCommand() + { + $tpl = $this->tpl; + + $next_class = $this->ctrl->getNextClass(); + $cmd = $this->ctrl->getCmd("render"); + + + switch ($next_class) { + // page editing + case "ilcontainerpagegui": + if ($_GET["redirectSource"] != "ilinternallinkgui") { + $ret = $this->forwardToPageObject(); + $tpl->setContent($ret); + } else { + return ""; + } + break; + + case "ilobjstylesheetgui": + $this->forwardToStyleSheet(); + break; + + default: + $this->prepareOutput(); + $cmd .= "Object"; + $this->$cmd(); + break; + } + return true; + } + + /** + * Get values for edit form + * + * @return array + */ + protected function getEditFormValues() + { + $values = parent::getEditFormValues(); + + include_once './Services/DidacticTemplate/classes/class.ilDidacticTemplateObjSettings.php'; + $values['didactic_type'] = + 'dtpl_' . ilDidacticTemplateObjSettings::lookupTemplateId($this->object->getRefId()); + + return $values; + } + + /** + * + */ + protected function afterUpdate() + { + // check if template is changed + include_once './Services/DidacticTemplate/classes/class.ilDidacticTemplateObjSettings.php'; + $current_tpl_id = (int) ilDidacticTemplateObjSettings::lookupTemplateId( + $this->object->getRefId() + ); + $new_tpl_id = (int) $this->getDidacticTemplateVar('dtpl'); + + if ($new_tpl_id != $current_tpl_id) { + $_REQUEST['tplid'] = $new_tpl_id; + + // redirect to didactic template confirmation + include_once './Services/DidacticTemplate/classes/class.ilDidacticTemplateGUI.php'; + $this->ctrl->setReturn($this, 'edit'); + $this->ctrl->setCmdClass('ildidactictemplategui'); + $this->ctrl->setCmd('confirmTemplateSwitch'); + $dtpl_gui = new ilDidacticTemplateGUI($this); + return $this->ctrl->forwardCommand($dtpl_gui); + } + parent::afterUpdate(); + } + + + /** + * Forward to style object + */ + public function forwardToStyleSheet() + { + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + $ilTabs->clearTargets(); + + $cmd = $ilCtrl->getCmd(); + 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" || $_GET["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"); + } + } + + + /** + * forward command to page object + */ + public function &forwardToPageObject() + { + $lng = $this->lng; + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + + $cmd = $ilCtrl->getCmd(); + + if (in_array($cmd, array("displayMediaFullscreen", "downloadFile", "displayMedia"))) { + $this->checkPermission("read"); + } else { + $this->checkPermission("write"); + } + + $ilTabs->clearTargets(); + + if ($_GET["redirectSource"] == "ilinternallinkgui") { + exit; + } + + $xpage_id = ilContainer::_lookupContainerSetting( + $this->object->getId(), + "xhtml_page" + ); + if ($xpage_id > 0) { + $ilTabs->setBackTarget( + $lng->txt("cntr_back_to_old_editor"), + $ilCtrl->getLinkTarget($this, "switchToOldEditor"), + "_top" + ); + } else { + $ilTabs->setBackTarget($lng->txt("back"), "./goto.php?target=" . $this->object->getType() . "_" . + $this->object->getRefId(), "_top"); + } + + // page object + include_once("./Services/Container/classes/class.ilContainerPage.php"); + include_once("./Services/Container/classes/class.ilContainerPageGUI.php"); + + $lng->loadLanguageModule("content"); + + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $this->tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath($this->object->getStyleSheetId()) + ); + $this->tpl->setCurrentBlock("SyntaxStyle"); + $this->tpl->setVariable( + "LOCATION_SYNTAX_STYLESHEET", + ilObjStyleSheet::getSyntaxStylePath() + ); + $this->tpl->parseCurrentBlock(); + + if (!ilContainerPage::_exists( + "cont", + $this->object->getId() + )) { + // doesn't exist -> create new one + $new_page_object = new ilContainerPage(); + $new_page_object->setParentId($this->object->getId()); + $new_page_object->setId($this->object->getId()); + $new_page_object->createFromXML(); + } + + // get page object + $this->ctrl->setReturnByClass("ilcontainerpagegui", "edit"); + $page_gui = new ilContainerPageGUI($this->object->getId()); + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $page_gui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId( + $this->object->getStyleSheetId(), + $this->object->getType() + )); + + $page_gui->setTemplateTargetVar("ADM_CONTENT"); + $page_gui->setFileDownloadLink(""); + $page_gui->setFullscreenLink($this->ctrl->getLinkTarget($this, "showMediaFullscreen")); + //$page_gui->setLinkParams($this->ctrl->getUrlParameterString()); // todo + $page_gui->setPresentationTitle(""); + $page_gui->setTemplateOutput(false); + + // old editor information text + $xpage_id = ilContainer::_lookupContainerSetting( + $this->object->getId(), + "xhtml_page" + ); + if ($xpage_id > 0) { + $wtpl = new ilTemplate( + "tpl.cntr_old_editor_message.html", + true, + true, + "Services/Container" + ); + $wtpl->setVariable("ALT_WARNING", $lng->txt("warning")); + $wtpl->setVariable( + "IMG_WARNING", + ilUtil::getImagePath("icon_alert.svg") + ); + $wtpl->setVariable("TXT_MIGRATION_INFO", $lng->txt("cntr_switch_to_new_editor_message")); + $wtpl->setVariable("TXT_MIGRATION_INFO", $lng->txt("cntr_switch_to_new_editor_message")); + $wtpl->setVariable( + "HREF_SWITCH_TO_NEW_EDITOR", + $ilCtrl->getLinkTarget($this, "useNewEditor") + ); + $wtpl->setVariable( + "TXT_MIGRATION_SWITCH", + $lng->txt("cntr_switch_to_new_editor_cmd") + ); + $page_gui->setPrependingHtml($wtpl->get()); + } + + // style tab + $page_gui->setTabHook($this, "addPageTabs"); + + $ret = $this->ctrl->forwardCommand($page_gui); + + //$ret =& $page_gui->executeCommand(); + return $ret; + } + + /** + * Add page tabs + */ + public function addPageTabs() + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + + $ilTabs->addTarget( + "obj_sty", + $ilCtrl->getLinkTarget($this, 'editStyleProperties'), + "editStyleProperties" + ); + } + + /** + * Get container page HTML + */ + public function getContainerPageHTML() + { + $ilSetting = $this->settings; + $ilUser = $this->user; + + if (!$ilSetting->get("enable_cat_page_edit")) { + return; + } + + // old page editor content + $xpage_id = ilContainer::_lookupContainerSetting( + $this->object->getId(), + "xhtml_page" + ); + if ($xpage_id > 0) { + include_once("Services/XHTMLPage/classes/class.ilXHTMLPage.php"); + $xpage = new ilXHTMLPage($xpage_id); + return $xpage->getContent(); + } + + + // page object + + + // if page does not exist, return nothing + include_once("./Services/COPage/classes/class.ilPageUtil.php"); + if (!ilPageUtil::_existsAndNotEmpty( + "cont", + $this->object->getId() + )) { + return ""; + } + include_once("./Services/Container/classes/class.ilContainerPage.php"); + include_once("./Services/Container/classes/class.ilContainerPageGUI.php"); + + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $this->tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath($this->object->getStyleSheetId()) + ); + $this->tpl->setCurrentBlock("SyntaxStyle"); + $this->tpl->setVariable( + "LOCATION_SYNTAX_STYLESHEET", + ilObjStyleSheet::getSyntaxStylePath() + ); + $this->tpl->parseCurrentBlock(); + + // get page object + include_once("./Services/Object/classes/class.ilObjectTranslation.php"); + $ot = ilObjectTranslation::getInstance($this->object->getId()); + $lang = $ot->getEffectiveContentLang($ilUser->getCurrentLanguage(), "cont"); + $page_gui = new ilContainerPageGUI($this->object->getId(), 0, $lang); + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $page_gui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId( + $this->object->getStyleSheetId(), + $this->object->getType() + )); + + $page_gui->setPresentationTitle(""); + $page_gui->setTemplateOutput(false); + $page_gui->setHeader(""); + $ret = $page_gui->showPage(); + + //$ret = "
          ".$ret."
          "; + + //$ret =& $page_gui->executeCommand(); + return $ret; + } + + /** + * prepare output + */ + public function prepareOutput($a_show_subobjects = true) + { + if (parent::prepareOutput($a_show_subobjects)) { // return false in admin mode + if ($this->getCreationMode() != true && $a_show_subobjects) { + // This method is called directly from ilContainerGUI::renderObject + #$this->showPossibleSubObjects(); + $this->showTreeFlatIcon(); + + // Member view + include_once './Services/Container/classes/class.ilMemberViewGUI.php'; + ilMemberViewGUI::showMemberViewSwitch($this->object->getRefId()); + } + } + } + + public function showTreeFlatIcon() + { + $tpl = $this->tpl; + + // dont show icon, if role (permission gui->rolegui) is edited + if ($_GET["obj_id"] != "") { + return; + } + // hide for member view + include_once './Services/Container/classes/class.ilMemberViewSettings.php'; + if (ilMemberViewSettings::getInstance()->isActive()) { + return; + } + + $mode = ($_SESSION["il_rep_mode"] == "flat") + ? "tree" + : "flat"; + $link = "ilias.php?baseClass=ilRepositoryGUI&cmd=frameset&set_mode=" . $mode . "&ref_id=" . $this->object->getRefId(); + $tpl->setTreeFlatIcon($link, $mode); + } + + /** + * called by prepare output + */ + public function setTitleAndDescription() + { + if (!ilContainer::_lookupContainerSetting($this->object->getId(), "hide_header_icon_and_title")) { + $this->tpl->setTitle($this->object->getTitle()); + $this->tpl->setDescription($this->object->getLongDescription()); + + // set tile icon + $icon = ilObject::_getIcon($this->object->getId(), "big", $this->object->getType()); + $this->tpl->setTitleIcon($icon, $this->lng->txt("obj_" . $this->object->getType())); + + include_once './Services/Object/classes/class.ilObjectListGUIFactory.php'; + $lgui = ilObjectListGUIFactory::_getListGUIByType($this->object->getType()); + $lgui->initItem($this->object->getRefId(), $this->object->getId()); + $this->tpl->setAlertProperties($lgui->getAlertProperties()); + } + } + + /** + * show possible sub objects selection list + */ + public function showPossibleSubObjects() + { + include_once "Services/Object/classes/class.ilObjectAddNewItemGUI.php"; + $gui = new ilObjectAddNewItemGUI($this->object->getRefId()); + $gui->render(); + } + + /** + * Get content gui object + * + * @param + * @return + */ + public function getContentGUI() + { + switch ($this->object->getViewMode()) { + // all items in one block + case ilContainer::VIEW_SIMPLE: + include_once("./Services/Container/classes/class.ilContainerSimpleContentGUI.php"); + $container_view = new ilContainerSimpleContentGUI($this); + break; + + case ilContainer::VIEW_OBJECTIVE: + include_once('./Services/Container/classes/class.ilContainerObjectiveGUI.php'); + $container_view = new ilContainerObjectiveGUI($this); + break; + + // all items in one block + case ilContainer::VIEW_SESSIONS: + case ilCourseConstants::IL_CRS_VIEW_TIMING: // not nice this workaround + include_once("./Services/Container/classes/class.ilContainerSessionsContentGUI.php"); + $container_view = new ilContainerSessionsContentGUI($this); + break; + + // all items in one block + case ilContainer::VIEW_BY_TYPE: + default: + include_once("./Services/Container/classes/class.ilContainerByTypeContentGUI.php"); + $container_view = new ilContainerByTypeContentGUI($this); + break; + } + + return $container_view; + } + + + + /** + * render the object + */ + public function renderObject() + { + $ilDB = $this->db; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $ilSetting = $this->settings; + + $container_view = $this->getContentGUI(); + + $this->setContentSubTabs(); + if ($this->isActiveAdministrationPanel()) { + $ilTabs->activateSubTab("manage"); + } else { + $ilTabs->activateSubTab("view_content"); + } + + $container_view->setOutput(); + + $this->adminCommands = $container_view->adminCommands; + + // it is important not to show the subobjects/admin panel here, since + // we will create nested forms in case, e.g. a news/calendar item is added + if ($ilCtrl->getNextClass() != "ilcolumngui") { + $this->showAdministrationPanel(); + $this->showPossibleSubObjects(); + } + + $this->showPermanentLink(); + + // add tree updater javascript + if ((int) $_GET["ref_id"] > 1 && $ilSetting->get("rep_tree_synchronize")) { + $ilCtrl->setParameter($this, "active_node", (int) $_GET["ref_id"]); + } + } + + /** + * render the object + */ + public function renderBlockAsynchObject() + { + $container_view = $this->getContentGUI(); + echo $container_view->getSingleTypeBlockAsynch($_GET["type"]); + exit; + } + + + /** + * Set content sub tabs + */ + public function setContentSubTabs() + { + $this->addStandardContainerSubTabs(); + } + + /** + * show administration panel + */ + public function showAdministrationPanel() + { + global $DIC; + + $ilAccess = $this->access; + $lng = $this->lng; + + $main_tpl = $DIC->ui()->mainTemplate(); + + $lng->loadLanguageModule('cntr'); + + if ($_SESSION["clipboard"]) { + // #11545 + $main_tpl->setPageFormAction($this->ctrl->getFormAction($this)); + + include_once './Services/UIComponent/Toolbar/classes/class.ilToolbarGUI.php'; + $toolbar = new ilToolbarGUI(); + $this->ctrl->setParameter($this, "type", ""); + $this->ctrl->setParameter($this, "item_ref_id", ""); + + $toolbar->addFormButton( + $this->lng->txt('paste_clipboard_items'), + 'paste' + ); + + $toolbar->addFormButton( + $this->lng->txt('clear_clipboard'), + 'clear' + ); + + $main_tpl->addAdminPanelToolbar($toolbar, true, false); + } elseif ($this->isActiveAdministrationPanel()) { + // #11545 + $main_tpl->setPageFormAction($this->ctrl->getFormAction($this)); + + include_once './Services/UIComponent/Toolbar/classes/class.ilToolbarGUI.php'; + $toolbar = new ilToolbarGUI(); + $this->ctrl->setParameter($this, "type", ""); + $this->ctrl->setParameter($this, "item_ref_id", ""); + + // if (!$_SESSION["clipboard"]) + // { + if ($this->object->gotItems()) { + $toolbar->setLeadingImage( + ilUtil::getImagePath("arrow_upright.svg"), + $lng->txt("actions") + ); + $toolbar->addFormButton( + $this->lng->txt('delete_selected_items'), + 'delete' + ); + $toolbar->addFormButton( + $this->lng->txt('move_selected_items'), + 'cut' + ); + $toolbar->addFormButton( + $this->lng->txt('copy_selected_items'), + 'copy' + ); + $toolbar->addFormButton( + $this->lng->txt('link_selected_items'), + 'link' + ); + // add download button if multi download enabled + $folder_set = new ilSetting("fold"); + if ($folder_set->get("enable_multi_download") == true) { + $toolbar->addSeparator(); + + if (!$folder_set->get("bgtask_download", 0)) { + $toolbar->addFormButton( + $this->lng->txt('download_selected_items'), + 'download' + ); + } else { + $url = $this->ctrl->getLinkTargetByClass(array("ilrepositorygui", "ilobjfoldergui", "ilbackgroundtaskhub"), "", "", true, false); + $main_tpl->addJavaScript("Services/BackgroundTask/js/BgTask.js"); + $main_tpl->addOnLoadCode("il.BgTask.initMultiForm('ilFolderDownloadBackgroundTaskHandler');"); + $main_tpl->addOnLoadCode('il.BgTask.setAjax("' . $url . '");'); + + include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; + $button = ilSubmitButton::getInstance(); + $button->setCaption("download_selected_items"); + $button->addCSSClass("ilbgtasksubmit"); + $button->setCommand("download"); + $toolbar->addButtonInstance($button); + } + } + } + if ($this->object->getType() == 'crs' or $this->object->getType() == 'grp') { + if ($this->object->gotItems()) { + $toolbar->addSeparator(); + } + + $toolbar->addButton( + $this->lng->txt('cntr_adopt_content'), + $this->ctrl->getLinkTargetByClass( + 'ilObjectCopyGUI', + 'adoptContent' + ) + ); + } + // } + /*else + { + + if ($this->isMultiDownloadEnabled()) + { + $toolbar->addSeparator(); + $toolbar->addFormButton( + $this->lng->txt('download_selected_items'), + 'download' + ); + } + }*/ + + $main_tpl->addAdminPanelToolbar( + $toolbar, + ($this->object->gotItems() && !$_SESSION["clipboard"]) ? true : false, + ($this->object->gotItems() && !$_SESSION["clipboard"]) ? true : false + ); + + // form action needed, see http://www.ilias.de/mantis/view.php?id=9630 + if ($this->object->gotItems()) { + $main_tpl->setPageFormAction($this->ctrl->getFormAction($this)); + } + } else { + if ($this->edit_order) { + if ($this->object->gotItems() and $ilAccess->checkAccess("write", "", $this->object->getRefId())) { + include_once('./Services/Container/classes/class.ilContainer.php'); + + if ($this->isActiveOrdering()) { + // #11843 + $main_tpl->setPageFormAction($this->ctrl->getFormAction($this)); + + include_once './Services/UIComponent/Toolbar/classes/class.ilToolbarGUI.php'; + $toolbar = new ilToolbarGUI(); + $this->ctrl->setParameter($this, "type", ""); + $this->ctrl->setParameter($this, "item_ref_id", ""); + + $toolbar->addFormButton( + $this->lng->txt('sorting_save'), + 'saveSorting' + ); + + $main_tpl->addAdminPanelToolbar($toolbar, true, false); + } + } + } + // bugfix mantis 24559 + // undoing an erroneous change inside mantis 23516 by adding "Download Multiple Objects"-functionality for non-admins + // as they don't have the possibility to use the multi-download-capability of the manage-tab + elseif ($this->isMultiDownloadEnabled()) { + // bugfix mantis 0021272 + $ref_id = $_GET['ref_id']; + $num_files = $this->tree->getChildsByType($ref_id, "file"); + $num_folders = $this->tree->getChildsByType($ref_id, "fold"); + if (count($num_files) > 0 or count($num_folders) > 0) { + // #11843 + $GLOBALS['tpl']->setPageFormAction($this->ctrl->getFormAction($this)); + + include_once './Services/UIComponent/Toolbar/classes/class.ilToolbarGUI.php'; + $toolbar = new ilToolbarGUI(); + $this->ctrl->setParameter($this, "type", ""); + $this->ctrl->setParameter($this, "item_ref_id", ""); + + $toolbar->addFormButton( + $this->lng->txt('download_selected_items'), + 'download' + ); + + $GLOBALS['tpl']->addAdminPanelToolbar( + $toolbar, + $this->object->gotItems() ? true : false, + $this->object->gotItems() ? true : false + ); + } else { + ilUtil::sendInfo($this->lng->txt('msg_no_downloadable_objects'), true); + } + } + } + } + + public function __showTimingsButton(&$tpl) + { + $tree = $this->tree; + + if (!$tree->checkForParentType($this->object->getRefId(), 'crs')) { + return false; + } + $tpl->setCurrentBlock("custom_button"); + $tpl->setVariable("ADMIN_MODE_LINK", $this->ctrl->getLinkTargetByClass('ilcoursecontentgui', 'editTimings')); + $tpl->setVariable("TXT_ADMIN_MODE", $this->lng->txt('timings_edit')); + $tpl->parseCurrentBlock(); + return true; + } + /** + * show permanent link + */ + public function showPermanentLink() + { + global $DIC; + + $tpl = $DIC->ui()->mainTemplate(); + + $tpl->setPermanentLink( + $this->object->getType(), + $this->object->getRefId(), + "", + "_top" + ); + } + + /** + * Switch to standard page editor + */ + public function switchToStdEditorObject() + { + $ilCtrl = $this->ctrl; + + $_SESSION["il_cntr_editor"] = "std"; + $ilCtrl->redirect($this, "editPageFrame"); + } + + /** + * Switch to old page editor + */ + public function switchToOldEditorObject() + { + $ilCtrl = $this->ctrl; + + $_SESSION["il_cntr_editor"] = "old"; + $ilCtrl->redirect($this, "editPageFrame"); + } + + /** + * Use new editor (-> delete xhtml content page) + */ + public function useNewEditorObject() + { + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) { + include_once("./Services/XHTMLPage/classes/class.ilXHTMLPage.php"); + + /* keep old page content for now... + $xpage_id = ilContainer::_lookupContainerSetting($this->object->getId(), + "xhtml_page"); + if ($xpage_id) + { + $xpage = new ilXHTMLPage($xpage_id); + } + */ + + ilContainer::_writeContainerSetting( + $this->object->getId(), + "xhtml_page", + 0 + ); + + ilUtil::sendSuccess($lng->txt("cntr_switched_editor"), true); + } + + $ilCtrl->redirect($this, "editPageFrame"); + } + + /** + * show page editor frameset + */ + public function editPageFrameObject() + { + // old tiny stuff + $xpage_id = ilContainer::_lookupContainerSetting( + $this->object->getId(), + "xhtml_page" + ); + if ($xpage_id > 0 && $_SESSION["il_cntr_editor"] != "std") { + $this->ctrl->redirect($this, "editPageContent"); + } else { + $this->ctrl->redirectByClass(array("ilcontainerpagegui"), "edit"); + } + } + + /** + * edit page content (for repository root node and categories) + * + * @access public + */ + public function editPageContentObject() + { + $rbacsystem = $this->rbacsystem; + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilErr = $this->error; + + if (!$rbacsystem->checkAccess("write", $this->ref_id)) { + $ilErr->raiseError($this->lng->txt("msg_no_perm_write"), $ilErr->MESSAGE); + } + + $xpage_id = ilContainer::_lookupContainerSetting( + $this->object->getId(), + "xhtml_page" + ); + if ($xpage_id > 0) { + include_once("Services/XHTMLPage/classes/class.ilXHTMLPage.php"); + $xpage = new ilXHTMLPage($xpage_id); + $content = $xpage->getContent(); + } + + // get template + $tpl->addBlockFile( + "ADM_CONTENT", + "adm_content", + "tpl.container_edit_page_content.html", + "Services/Container" + ); + $tpl->setVariable("VAL_CONTENT", ilUtil::prepareFormOutput($content)); + $tpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this)); + $tpl->setVariable( + "TXT_EDIT_PAGE_CONTENT", + $this->lng->txt("edit_page_content") + ); + $tpl->setVariable("TXT_SAVE", $this->lng->txt("save")); + $tpl->setVariable("TXT_CANCEL", $this->lng->txt("cancel")); + $tpl->setVariable("TXT_MIGRATION_INFO", $lng->txt("cntr_old_editor_warning")); + $tpl->setVariable("TXT_MIGRATION_OPEN_STD_EDITOR", $lng->txt("cntr_old_editor_open_standard_editor")); + $tpl->setVariable("IMG_WARNING", ilUtil::getImagePath("icon_alert.svg")); + $tpl->setVariable("HREF_OPEN_STD_EDITOR", $ilCtrl->getLinkTarget($this, "switchToStdEditor")); + $tpl->setVariable("ALT_WARNING", $lng->txt("warning")); + + include_once("./Services/Form/classes/class.ilFormPropertyGUI.php"); + include_once("./Services/Form/classes/class.ilTextAreaInputGUI.php"); + //$ta = new ilTextAreaInputGUI(); + //$tags = $ta->getRteTagSet("extended_table_img"); + + // add rte support + include_once "./Services/RTE/classes/class.ilRTE.php"; + $rtestring = ilRTE::_getRTEClassname(); + include_once "./Services/RTE/classes/class.$rtestring.php"; + $rte = new $rtestring(); + //$rte->addPlugin("latex"); + include_once "./Services/Object/classes/class.ilObject.php"; + $obj_id = ilObject::_lookupObjectId($_GET["ref_id"]); + $obj_type = ilObject::_lookupType($_GET["ref_id"], true); + $rte->addRTESupport($obj_id, $obj_type); + //$rte->setStyleSelect(true); + //$rte->addCustomRTESupport($obj_id, $obj_type, $tags); + } + + public function savePageContentObject() + { + include_once("Services/XHTMLPage/classes/class.ilXHTMLPage.php"); + include_once "./Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php"; + $xpage_id = ilContainer::_lookupContainerSetting( + $this->object->getId(), + "xhtml_page" + ); + + /*include_once("./Services/Form/classes/class.ilFormPropertyGUI.php"); + include_once("./Services/Form/classes/class.ilTextAreaInputGUI.php"); + $ta = new ilTextAreaInputGUI(); + $ta->setRteTagSet("extended_table_img"); + $tags = $ta->getRteTagString();*/ + + //$text = ilUtil::stripSlashes($_POST["page_content"], + // true, + // $tags); + + $text = ilUtil::stripSlashes( + $_POST["page_content"], + true, + ilObjAdvancedEditing::_getUsedHTMLTagsAsString() + ); + if ($xpage_id > 0) { + $xpage = new ilXHTMLPage($xpage_id); + $xpage->setContent($text); + $xpage->save(); + } else { + $xpage = new ilXHTMLPage(); + $xpage->setContent($text); + $xpage->save(); + ilContainer::_writeContainerSetting( + $this->object->getId(), + "xhtml_page", + $xpage->getId() + ); + } + + include_once("Services/RTE/classes/class.ilRTE.php"); + ilRTE::_cleanupMediaObjectUsage( + $text, + $this->object->getType() . ":html", + $this->object->getId() + ); + + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, ""); + } + + public function cancelPageContentObject() + { + $this->ctrl->redirect($this, ""); + } + + public function showLinkListObject() + { + $lng = $this->lng; + $tree = $this->tree; + + $tpl = new ilTemplate( + "tpl.container_link_help.html", + true, + true, + "Services/Container" + ); + + $type_ordering = array( + "cat", "fold", "crs", "grp", "chat", "frm", "lres", + "glo", "webr", "file", "exc", + "tst", "svy", "mep", "qpl", "spl"); + + $childs = $tree->getChilds($_GET["ref_id"]); + foreach ($childs as $child) { + if (in_array($child["type"], array("lm", "sahs", "htlm"))) { + $cnt["lres"]++; + } else { + $cnt[$child["type"]]++; + } + } + + $tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); + $tpl->setVariable("TXT_HELP_HEADER", $lng->txt("help")); + foreach ($type_ordering as $type) { + $tpl->setCurrentBlock("row"); + $tpl->setVariable("ROWCOL", "tblrow" . ((($i++)%2)+1)); + if ($type != "lres") { + $tpl->setVariable("TYPE", $lng->txt("objs_" . $type) . + " (" . ((int) $cnt[$type]) . ")"); + } else { + $tpl->setVariable("TYPE", $lng->txt("obj_lrss") . + " (" . ((int) $cnt["lres"]) . ")"); + } + $tpl->setVariable("TXT_LINK", "[list-" . $type . "]"); + $tpl->parseCurrentBlock(); + } + $tpl->show(); + exit; + } + + /** + * cleaer administration commands determination + */ + public function clearAdminCommandsDetermination() + { + $this->adminCommands = false; + } + + /** + * determin admin commands + */ + /* function determineAdminCommands($a_ref_id, $a_admin_com_included_in_list = false) + { + if (!$this->adminCommands) + { + if (!$this->isActiveAdministrationPanel()) + { + if ($this->rbacsystem->checkAccess("delete", $a_ref_id)) + { + $this->adminCommands = true; + } + } + else + { + $this->adminCommands = $a_admin_com_included_in_list; + } + } + }*/ + + /** + * returns a new list block template + * + * @access private + * @return object block template + */ + public function &newBlockTemplate() + { + $tpl = new ilTemplate( + "tpl.container_list_block.html", + true, + true, + "Services/Container" + ); + $this->cur_row_type = "row_type_1"; + return $tpl; + } + + /** + * adds a header row to a block template + * + * @param object $a_tpl block template + * @param string $a_type object type + * @access private + */ + public function addHeaderRow(&$a_tpl, $a_type, $a_show_image = true) + { + $icon = ilUtil::getImagePath("icon_" . $a_type . ".svg"); + $title = $this->lng->txt("objs_" . $a_type); + + if ($a_show_image) { + $a_tpl->setCurrentBlock("container_header_row_image"); + $a_tpl->setVariable("HEADER_IMG", $icon); + $a_tpl->setVariable("HEADER_ALT", $title); + } else { + $a_tpl->setCurrentBlock("container_header_row"); + } + + $a_tpl->setVariable("BLOCK_HEADER_CONTENT", $title); + $a_tpl->parseCurrentBlock(); + //$a_tpl->touchBlock("container_row"); + } + + /** + * adds a standard row to a block template + * + * @param object $a_tpl block template + * @param string $a_html html code + * @access private + */ + public function addStandardRow( + &$a_tpl, + $a_html, + $a_item_ref_id = "", + $a_item_obj_id = "", + $a_image_type = "" + ) { + $ilSetting = $this->settings; + + $this->cur_row_type = ($this->cur_row_type == "row_type_1") + ? "row_type_2" + : "row_type_1"; + + $a_tpl->touchBlock($this->cur_row_type); + + $nbsp = true; + if ($ilSetting->get("icon_position_in_lists") == "item_rows") { + $icon = ilUtil::getImagePath("icon_" . $a_image_type . ".svg"); + $alt = $this->lng->txt("obj_" . $a_image_type); + + if ($ilSetting->get('custom_icons')) { + global $DIC; + /** @var \ilObjectCustomIconFactory $customIconFactory */ + $customIconFactory = $DIC['object.customicons.factory']; + $customIcon = $customIconFactory->getPresenterByObjId($a_item_obj_id, $a_image_type); + + if ($customIcon->exists()) { + $icon = $customIcon->getFullPath(); + } + } + + $a_tpl->setCurrentBlock("block_row_image"); + $a_tpl->setVariable("ROW_IMG", $icon); + $a_tpl->setVariable("ROW_ALT", $alt); + $a_tpl->parseCurrentBlock(); + $nbsp = false; + } + + if ($this->isActiveAdministrationPanel()) { + $a_tpl->setCurrentBlock("block_row_check"); + $a_tpl->setVariable("ITEM_ID", $a_item_ref_id); + $a_tpl->parseCurrentBlock(); + $nbsp = false; + } + include_once('Services/Container/classes/class.ilContainerSortingSettings.php'); + if ($this->isActiveAdministrationPanel() && + ilContainerSortingSettings::_lookupSortMode($this->object->getId()) == ilContainer::SORT_MANUAL) { + $a_tpl->setCurrentBlock('block_position'); + $a_tpl->setVariable('POS_TYPE', $a_image_type); + $a_tpl->setVariable('POS_ID', $a_item_ref_id); + $a_tpl->setVariable('POSITION', sprintf('%.1f', $this->current_position++)); + $a_tpl->parseCurrentBlock(); + } + if ($nbsp) { + $a_tpl->setVariable("ROW_NBSP", " "); + } + $a_tpl->setCurrentBlock("container_standard_row"); + $a_tpl->setVariable("BLOCK_ROW_CONTENT", $a_html); + $a_tpl->parseCurrentBlock(); + $a_tpl->touchBlock("container_row"); + } + + /** + * add message row + */ + public function addMessageRow(&$a_tpl, $a_message, $a_type) + { + $this->cur_row_type = ($this->cur_row_type == "row_type_1") + ? "row_type_2" + : "row_type_1"; + + $a_tpl->touchBlock($this->cur_row_type); + + $type = $this->lng->txt("obj_" . $a_type); + $a_message = str_replace("[type]", $type, $a_message); + + $a_tpl->setVariable("ROW_NBSP", " "); + + $a_tpl->setCurrentBlock("container_standard_row"); + $a_tpl->setVariable( + "BLOCK_ROW_CONTENT", + $a_message + ); + $a_tpl->parseCurrentBlock(); + $a_tpl->touchBlock("container_row"); + } + + public function resetRowType() + { + $this->cur_row_type = ""; + } + + + /** + * Add page editor tabs + */ + public function setPageEditorTabs() + { + $lng = $this->lng; + + if (!$this->isActiveAdministrationPanel() + || strtolower($this->ctrl->getCmdClass()) != "ilcontainerpagegui") { + return; + } + + $lng->loadLanguageModule("content"); + //$tabs_gui = new ilTabsGUI(); + //$tabs_gui->setSubTabs(); + + // back to upper context + $this->tabs_gui->setBackTarget( + $this->lng->txt("obj_cat"), + $this->ctrl->getLinkTarget($this, "frameset"), + ilFrameTargetInfo::_getFrame("MainContent") + ); + + $this->tabs_gui->addTarget("edit", $this->ctrl->getLinkTargetByClass("ilcontainerpagegui", "view"), array("", "view"), "ilcontainerpagegui"); + + //$this->tpl->setTabs($tabs_gui->getHTML()); + } + + /** + * Add standar container subtabs for view, manage, oderdering and text/media editor link + */ + public function addStandardContainerSubTabs($a_include_view = true) + { + $ilTabs = $this->tabs; + $ilAccess = $this->access; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + $ilSetting = $this->settings; + + if (!is_object($this->object)) { + return; + } + + if ($a_include_view && $ilAccess->checkAccess("read", "", $this->object->getRefId())) { + if (!$this->isActiveAdministrationPanel()) { + $ilTabs->addSubTab("view_content", $lng->txt("view"), $ilCtrl->getLinkTarget($this, "view")); + } else { + $ilTabs->addSubTab("view_content", $lng->txt("view"), $ilCtrl->getLinkTarget($this, "disableAdministrationPanel")); + } + } + + if ($ilUser->getId() != ANONYMOUS_USER_ID && + ( + $this->adminCommands || + (is_object($this->object) && + ($ilAccess->checkAccess("write", "", $this->object->getRefId()))) + || + (is_object($this->object) && + ($this->object->getHiddenFilesFound())) || + $_SESSION["clipboard"] + ) + ) { + if ($this->isActiveAdministrationPanel()) { + $ilTabs->addSubTab("manage", $lng->txt("cntr_manage"), $ilCtrl->getLinkTarget($this, "")); + } else { + $ilTabs->addSubTab("manage", $lng->txt("cntr_manage"), $ilCtrl->getLinkTarget($this, "enableAdministrationPanel")); + } + } + if ($ilUser->getId() != ANONYMOUS_USER_ID && + is_object($this->object) && + $ilAccess->checkAccess("write", "", $this->object->getRefId()) /* && + $this->object->getOrderType() == ilContainer::SORT_MANUAL */ // always on because of custom block order + ) { + $ilTabs->addSubTab("ordering", $lng->txt("cntr_ordering"), $ilCtrl->getLinkTarget($this, "editOrder")); + } + if ($ilUser->getId() != ANONYMOUS_USER_ID && + is_object($this->object) && + $ilAccess->checkAccess("write", "", $this->object->getRefId()) + ) { + if ($ilSetting->get("enable_cat_page_edit")) { + $ilTabs->addSubTab( + "page_editor", + $lng->txt("cntr_text_media_editor"), + $ilCtrl->getLinkTarget($this, "editPageFrame"), + ilFrameTargetInfo::_getFrame("MainContent") + ); + } + } + } + + + /** + * common tabs for all container objects (should be called + * at the end of child getTabs() method + */ + public function getTabs() + { + $rbacsystem = $this->rbacsystem; + $ilCtrl = $this->ctrl; + + // edit permissions + if ($rbacsystem->checkAccess('edit_permission', $this->ref_id)) { + $this->tabs_gui->addTarget( + "perm_settings", + $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm"), + array("perm","info","owner"), + 'ilpermissiongui' + ); + if ($ilCtrl->getNextClass() == "ilpermissiongui") { + $this->tabs_gui->activateTab("perm_settings"); + } + } + + // show clipboard + if (strtolower($_GET["baseClass"]) == "ilrepositorygui" && !empty($_SESSION["clipboard"])) { + $this->tabs_gui->addTarget( + "clipboard", + $this->ctrl->getLinkTarget($this, "clipboard"), + "clipboard", + get_class($this) + ); + } + } + + //***************** + // COMMON METHODS (may be overwritten in derived classes + // if special handling is necessary) + //***************** + + /** + * enable administration panel + */ + public function enableAdministrationPanelObject() + { + $_SESSION["il_cont_admin_panel"] = true; + $this->ctrl->redirect($this, "render"); + } + + /** + * enable administration panel + */ + public function disableAdministrationPanelObject() + { + $_SESSION["il_cont_admin_panel"] = false; + $this->ctrl->redirect($this, "render"); + } + + /** + * Edit order + */ + public function editOrderObject() + { + $ilTabs = $this->tabs; + + $this->edit_order = true; + $_SESSION["il_cont_admin_panel"] = false; + $this->renderObject(); + + $ilTabs->activateSubTab("ordering"); + } + + /** + * Check if ordering is enabled + * @return bool + */ + public function isActiveOrdering() + { + return $this->edit_order ? true : false; + } + + /** + * Check if item ordering is enabled + * @return bool + */ + public function isActiveItemOrdering() + { + if ($this->isActiveOrdering()) { + return (ilContainerSortingSettings::_lookupSortMode($this->object->getId()) == ilContainer::SORT_MANUAL); + } + return false; + } + /** * @see ilDesktopItemHandling::addToDesk() */ public function addToDeskObject() { - $ilSetting = $this->settings; - $lng = $this->lng; - - if((int)$ilSetting->get('disable_my_offers')) - { - return $this->renderObject(); - } - - include_once './Services/PersonalDesktop/classes/class.ilDesktopItemGUI.php'; - ilDesktopItemGUI::addToDesktop(); - ilUtil::sendSuccess($lng->txt("added_to_desktop")); - $this->renderObject(); + $ilSetting = $this->settings; + $lng = $this->lng; + + if ((int) $ilSetting->get('disable_my_offers')) { + return $this->renderObject(); + } + + include_once './Services/PersonalDesktop/classes/class.ilDesktopItemGUI.php'; + ilDesktopItemGUI::addToDesktop(); + ilUtil::sendSuccess($lng->txt("added_to_desktop")); + $this->renderObject(); } /** @@ -1472,2503 +1467,2383 @@ class ilContainerGUI extends ilObjectGUI implements ilDesktopItemHandling */ public function removeFromDeskObject() { - $ilSetting = $this->settings; - $lng = $this->lng; - - if((int)$ilSetting->get('disable_my_offers')) - { - return $this->renderObject(); - } - - include_once './Services/PersonalDesktop/classes/class.ilDesktopItemGUI.php'; - ilDesktopItemGUI::removeFromDesktop(); - ilUtil::sendSuccess($lng->txt("removed_from_desktop")); - $this->renderObject(); - } - - // bugfix mantis 24559 - // undoing an erroneous change inside mantis 23516 by adding "Download Multiple Objects"-functionality for non-admins - // as they don't have the possibility to use the multi-download-capability of the manage-tab - function enableMultiDownloadObject() - { - $this->multi_download_enabled = true; - $this->renderObject(); - } - - function isMultiDownloadEnabled() - { - return $this->multi_download_enabled; - } - - /** - * cut object(s) out from a container and write the information to clipboard - * - * - * @access public - */ - function cutObject() - { - $rbacsystem = $this->rbacsystem; - $ilCtrl = $this->ctrl; - $ilErr = $this->error; - - if ($_GET["item_ref_id"] != "") - { - $_POST["id"] = array($_GET["item_ref_id"]); - } - - $no_cut = []; - - if (!isset($_POST["id"])) - { - $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); - } - - // FOR ALL OBJECTS THAT SHOULD BE COPIED - foreach ($_POST["id"] as $ref_id) - { - // GET COMPLETE NODE_DATA OF ALL SUBTREE NODES - $node_data = $this->tree->getNodeData($ref_id); - $subtree_nodes = $this->tree->getSubTree($node_data); - - $all_node_data[] = $node_data; - $all_subtree_nodes[] = $subtree_nodes; - - // CHECK DELETE PERMISSION OF ALL OBJECTS IN ACTUAL SUBTREE - foreach ($subtree_nodes as $node) - { - if($node['type'] == 'rolf') - { - continue; - } - - if (!$rbacsystem->checkAccess('delete',$node["ref_id"])) - { - $no_cut[] = $node["ref_id"]; - } - } - } - // IF THERE IS ANY OBJECT WITH NO PERMISSION TO 'delete' - if (count($no_cut)) - { - $titles = array(); - foreach((array) $no_cut as $cut_id) - { - $titles[] = ilObject::_lookupTitle(ilObject::_lookupObjId($cut_id)); - } - $ilErr->raiseError( - $this->lng->txt("msg_no_perm_cut")." ".implode(',',(array) $titles), - $ilErr->MESSAGE - ); - } - $_SESSION["clipboard"]["parent"] = $_GET["ref_id"]; - $_SESSION["clipboard"]["cmd"] = $ilCtrl->getCmd(); - $_SESSION["clipboard"]["ref_ids"] = $_POST["id"]; - - ilUtil::sendInfo($this->lng->txt("msg_cut_clipboard"),true); - - return $this->initAndDisplayMoveIntoObjectObject(); - } // END CUT - - /** - * Copy object(s) out from a container and write the information to clipboard - * It is not possible to copy multiple objects at once. - * - * - * @access public - */ - function copyObject() - { - $rbacsystem = $this->rbacsystem; - $ilCtrl = $this->ctrl; - $objDefinition = $this->obj_definition; - $ilErr = $this->error; - - $no_copy = []; - - if ($_GET["item_ref_id"] != "") - { - $_POST["id"] = array($_GET["item_ref_id"]); - } - - if (!isset($_POST["id"])) - { - $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); - } - - // FOR ALL OBJECTS THAT SHOULD BE COPIED - $containers = 0; - foreach ($_POST["id"] as $ref_id) - { - // GET COMPLETE NODE_DATA OF ALL SUBTREE NODES - $node_data = $this->tree->getNodeData($ref_id); - - // count containers - if ($objDefinition->isContainer($node_data["type"])) - { - $containers++; - } - - $subtree_nodes = $this->tree->getSubTree($node_data); - - $all_node_data[] = $node_data; - $all_subtree_nodes[] = $subtree_nodes; - - // CHECK COPY PERMISSION OF ALL OBJECTS IN ACTUAL SUBTREE - foreach ($subtree_nodes as $node) - { - if($node['type'] == 'rolf') - { - continue; - } - - if (!$rbacsystem->checkAccess('visible,read,copy',$node["ref_id"])) - { - $no_copy[] = $node["ref_id"]; - } - } - } - - if ($containers > 0 && count($_POST["id"]) > 1) - { - $ilErr->raiseError($this->lng->txt("cntr_container_only_on_their_own"), $ilErr->MESSAGE); - } - - // IF THERE IS ANY OBJECT WITH NO PERMISSION TO 'delete' - if (is_array($no_copy) && count($no_copy)) - { - $titles = array(); - foreach((array) $no_copy as $copy_id) - { - $titles[] = ilObject::_lookupTitle(ilObject::_lookupObjId($copy_id)); - } - $ilErr->raiseError( - $this->lng->txt("msg_no_perm_copy") . " " . implode(',',$titles), - $ilErr->MESSAGE); - } - - // if we have a single container, set it as source id and redirect to ilObjectCopyGUI - if (count($_POST["id"]) == 1) - { - $ilCtrl->setParameterByClass("ilobjectcopygui", "source_id", $_POST["id"][0]); - $ilCtrl->redirectByClass("ilobjectcopygui", "initTargetSelection"); - } - else - { - $ilCtrl->setParameterByClass("ilobjectcopygui", "source_ids", implode($_POST["id"],"_")); - $ilCtrl->redirectByClass("ilobjectcopygui", "initTargetSelection"); - } - - $_SESSION["clipboard"]["parent"] = $_GET["ref_id"]; - $_SESSION["clipboard"]["cmd"] = $ilCtrl->getCmd(); - $_SESSION["clipboard"]["ref_ids"] = $_POST["id"]; - - ilUtil::sendInfo($this->lng->txt("msg_copy_clipboard"), true); - - return $this->initAndDisplayCopyIntoMultipleObjectsObject(); - } // END COPY - - function downloadObject() - { - $rbacsystem = $this->rbacsystem; - $ilErr = $this->error; - - $no_download = []; - $no_perm = []; - - if ($_GET["item_ref_id"] != "") - { - $_POST["id"] = array($_GET["item_ref_id"]); - } - - if (!isset($_POST["id"])) - { - $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); - } - - // FOR ALL OBJECTS THAT SHOULD BE DOWNLOADED - foreach ($_POST["id"] as $ref_id) - { - $object = ilObjectFactory::getInstanceByRefId($ref_id); - $obj_type = $object->getType(); - if (!in_array($obj_type, array("fold", "file"))) - { - $no_download[] = $object->getType(); - } - else if (!$rbacsystem->checkAccess('read', $ref_id)) - { - $no_perm[] = $ref_id; - } - } - - // IF THERE IS ANY OBJECT THAT CANNOT BE DOWNLOADED - if (count($no_download)) - { - $no_download = array_unique($no_download); - foreach ($no_download as $type) - { - $txt_objs[] = $this->lng->txt("objs_".$type); - } - $ilErr->raiseError(implode(', ',$txt_objs)." ".$this->lng->txt("msg_obj_no_download"), $ilErr->MESSAGE); - } - - // NO ACCESS - if (count($no_perm)) - { - $ilErr->raiseError( - $this->lng->txt("msg_obj_perm_download")." ".implode(',',$no_perm), - $ilErr->MESSAGE); - } - - // download the objects - $this->downloadMultipleObjects($_POST["id"]); - } - - private function downloadMultipleObjects($a_ref_ids) - { - $lng = $this->lng; - $rbacsystem = $this->rbacsystem; - $ilAccess = $this->access; - - include_once 'Modules/Folder/classes/class.ilObjFolder.php'; - include_once 'Modules/File/classes/class.ilObjFile.php'; - include_once 'Modules/File/classes/class.ilFileException.php'; - - // create temporary file to download - $zip = PATH_TO_ZIP; - $tmpdir = ilUtil::ilTempnam(); - ilUtil::makeDir($tmpdir); - - try - { - // copy each selected object - foreach ($a_ref_ids as $ref_id) - { - if (!$ilAccess->checkAccess("read", "", $ref_id)) - continue; - - if (ilObject::_isInTrash($ref_id)) - continue; - - // get object - $object = ilObjectFactory::getInstanceByRefId($ref_id); - $obj_type = $object->getType(); - if ($obj_type == "fold") - { - // copy folder to temp directory - self::recurseFolder($ref_id, $object->getTitle(), $tmpdir); - } - else if ($obj_type == "file") - { - // copy file to temp directory - self::copyFile($object->getId(), $object->getTitle(), $tmpdir); - } - } - - // compress the folder - $deliverFilename = ilUtil::getAsciiFilename($this->object->getTitle()) . ".zip"; - $tmpzipfile = ilUtil::ilTempnam() . ".zip"; - ilUtil::zip($tmpdir, $tmpzipfile, true); - ilUtil::delDir($tmpdir); - ilUtil::deliverFile($tmpzipfile, $deliverFilename, '', false, true, true); - } - catch (ilFileException $e) - { - ilUtil::sendInfo($e->getMessage(), true); - } - } - - /** - * private functions which iterates through all folders and files - * and create an according file structure in a temporary directory. This function works recursive. - * - * @param integer $refid reference it - * @param tmpdictory $tmpdir - * @return returns first created directory - */ - private static function recurseFolder($refid, $title, $tmpdir) - { - global $DIC; - - $rbacsystem = $DIC->rbac()->system(); - $tree = $DIC->repositoryTree(); - $ilAccess = $DIC->access(); - - $tmpdir = $tmpdir . DIRECTORY_SEPARATOR . ilUtil::getASCIIFilename($title); - ilUtil::makeDir($tmpdir); - - $subtree = $tree->getChildsByTypeFilter($refid, array("fold","file")); - - foreach ($subtree as $child) - { - if (!$ilAccess->checkAccess("read", "", $child["ref_id"])) - continue; - - if (ilObject::_isInTrash($child["ref_id"])) - continue; - - if ($child["type"] == "fold") - self::recurseFolder($child["ref_id"], $child["title"], $tmpdir); - else - self::copyFile($child["obj_id"], $child["title"], $tmpdir); - } - } - - private static function copyFile($obj_id, $title, $tmpdir) - { - $newFilename = $tmpdir . DIRECTORY_SEPARATOR . ilUtil::getASCIIFilename($title); - - // copy to temporary directory - $oldFilename = ilObjFile::_lookupAbsolutePath($obj_id); - - if (!copy($oldFilename, $newFilename)) - throw new ilFileException("Could not copy ".$oldFilename." to ".$newFilename); - - touch($newFilename, filectime($oldFilename)); - } - - /** - * create an new reference of an object in tree - * it's like a hard link of unix - * - * @access public - */ - function linkObject() - { - $rbacsystem = $this->rbacsystem; - $ilCtrl = $this->ctrl; - $ilErr = $this->error; - - $no_cut = []; - $no_link = []; - - if ($_GET["item_ref_id"] != "") - { - $_POST["id"] = array($_GET["item_ref_id"]); - } - - if (!isset($_POST["id"])) - { - $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); - } - - // CHECK ACCESS - foreach ($_POST["id"] as $ref_id) - { - if (!$rbacsystem->checkAccess('delete',$ref_id)) - { - $no_cut[] = $ref_id; - } - - $object = ilObjectFactory::getInstanceByRefId($ref_id); - - if (!$this->objDefinition->allowLink($object->getType())) - { - $no_link[] = $object->getType(); - } - } - - // NO ACCESS - if (count($no_cut)) - { - $ilErr->raiseError($this->lng->txt("msg_no_perm_link")." ". - implode(',',$no_cut), $ilErr->MESSAGE); - } - - if (count($no_link)) - { - //#12203 - $ilErr->raiseError($this->lng->txt("msg_obj_no_link"), $ilErr->MESSAGE); - } - - // WRITE TO CLIPBOARD - $clipboard["parent"] = $_GET["ref_id"]; - $clipboard["cmd"] = $ilCtrl->getCmd(); - - foreach ($_POST["id"] as $ref_id) - { - $clipboard["ref_ids"][] = $ref_id; - } - - $_SESSION["clipboard"] = $clipboard; - - $suffix = 'p'; - if(count($clipboard["ref_ids"]) == 1) - { - $suffix = 's'; - } - ilUtil::sendInfo($this->lng->txt("msg_link_clipboard_" . $suffix),true); - - return $this->initAndDisplayLinkIntoMultipleObjectsObject(); - - } // END LINK - - - /** - * clear clipboard and go back to last object - * - * @access public - */ - function clearObject() - { - unset($_SESSION["clipboard"]); - unset($_SESSION["il_rep_clipboard"]); - - //var_dump($this->getReturnLocation("clear",$this->ctrl->getLinkTarget($this)),get_class($this)); - - // only redirect if clipboard was cleared - if (isset($_POST["cmd"]["clear"])) - { - ilUtil::sendSuccess($this->lng->txt("msg_clear_clipboard"),true); - // fixed mantis 0018474: Clear Clipboard redirects to Subtab View, instead of Subtab "Edit Multiple" - $this->ctrl->redirect($this, 'render'); - } - } - - public function performPasteIntoMultipleObjectsObject() - { - $rbacsystem = $this->rbacsystem; - $rbacadmin = $this->rbacadmin; - $rbacreview = $this->rbacreview; - $ilLog = $this->log; - $tree = $this->tree; - $ilObjDataCache = $this->obj_data_cache; - $ilUser = $this->user; - $ilErr = $this->error; - $lng = $this->lng; - $ctrl = $this->ctrl; - $ui = $this->ui; - - $exists = []; - $is_child = []; - $not_allowed_subobject = []; - $no_paste = []; - - $command = $_SESSION['clipboard']['cmd']; - if(!in_array($command, array('cut', 'link', 'copy'))) - { - $message = __METHOD__.": cmd was neither 'cut', 'link' nor 'copy'; may be a hack attempt!"; - $ilErr->raiseError($message, $ilErr->WARNING); - } - - if($command == 'cut') - { - if(isset($_POST['node']) && (int)$_POST['node']) - $_POST['nodes'] = array($_POST['node']); - } - - if(!is_array($_POST['nodes']) || !count($_POST['nodes'])) - { - ilUtil::sendFailure($this->lng->txt('select_at_least_one_object')); - switch ($command) - { - case 'cut': - $this->showPasteTreeObject(); - break; - case 'copy': - $this->showPasteTreeObject(); - break; - case 'link': - $this->showPasteTreeObject(); - break; - } - return; - } - - // this loop does all checks - $folder_objects_cache = array(); - foreach($_SESSION['clipboard']['ref_ids'] as $ref_id) - { - $obj_data = ilObjectFactory::getInstanceByRefId($ref_id); - $current_parent_id = $tree->getParentId($obj_data->getRefId()); - - foreach($_POST['nodes'] as $folder_ref_id) - { - if(!array_key_exists($folder_ref_id, $folder_objects_cache)) - { - $folder_objects_cache[$folder_ref_id] = ilObjectFactory::getInstanceByRefId($folder_ref_id); - } - - // CHECK ACCESS - if(!$rbacsystem->checkAccess('create', $folder_ref_id, $obj_data->getType())) - { - $no_paste[] = sprintf($this->lng->txt('msg_no_perm_paste_object_in_folder'), $obj_data->getTitle().' ['.$obj_data->getRefId().']', $folder_objects_cache[$folder_ref_id]->getTitle().' ['.$folder_objects_cache[$folder_ref_id]->getRefId().']'); - } - - // CHECK IF REFERENCE ALREADY EXISTS - if($folder_ref_id == $current_parent_id) - { - $exists[] = sprintf($this->lng->txt('msg_obj_exists_in_folder'), $obj_data->getTitle().' ['.$obj_data->getRefId().']', $folder_objects_cache[$folder_ref_id]->getTitle().' ['.$folder_objects_cache[$folder_ref_id]->getRefId().']'); - } - - // CHECK IF PASTE OBJECT SHALL BE CHILD OF ITSELF - if ($tree->isGrandChild($ref_id, $folder_ref_id) || - $ref_id == $folder_ref_id) - { - $is_child[] = sprintf($this->lng->txt('msg_paste_object_not_in_itself'), $obj_data->getTitle().' ['.$obj_data->getRefId().']'); - } - - // CHECK IF OBJECT IS ALLOWED TO CONTAIN PASTED OBJECT AS SUBOBJECT - if(!in_array($obj_data->getType(), array_keys($folder_objects_cache[$folder_ref_id]->getPossibleSubObjects()))) - { - $not_allowed_subobject[] = sprintf($this->lng->txt('msg_obj_may_not_contain_objects_of_type'), $folder_objects_cache[$folder_ref_id]->getTitle().' ['.$folder_objects_cache[$folder_ref_id]->getRefId().']', - $lng->txt('obj_'.$obj_data->getType())); - } - } - } - - //////////////////////////// - // process checking results - if(count($exists) && $command != "copy") - { - $error .= implode('
          ', $exists); - } - - if(count($is_child)) - { - $error .= $error != '' ? '
          ' : ''; - $error .= implode('
          ', $is_child); - } - - if(count($not_allowed_subobject)) - { - $error .= $error != '' ? '
          ' : ''; - $error .= implode('
          ', $not_allowed_subobject); - } - - if(count($no_paste)) - { - $error .= $error != '' ? '
          ' : ''; - $error .= implode('
          ', $no_paste); - } - - if($error != '') - { - ilUtil::sendFailure($error); - switch ($command) - { - case 'cut': - $this->showPasteTreeObject(); - break; - case 'copy': - $this->showPasteTreeObject(); - break; - case 'link': - $this->showPasteTreeObject(); - break; - } - return; - } - - // log pasteObject call - $ilLog->write(__METHOD__.", cmd: ".$command); - - //////////////////////////////////////////////////////// - // everything ok: now paste the objects to new location - - // to prevent multiple actions via back/reload button - $ref_ids = $_SESSION['clipboard']['ref_ids']; - unset($_SESSION['clipboard']['ref_ids']); - - // BEGIN ChangeEvent: Record paste event. - require_once('Services/Tracking/classes/class.ilChangeEvent.php'); - // END ChangeEvent: Record paste event. - - // process COPY command - if($command == 'copy') - { - foreach($_POST['nodes'] as $folder_ref_id) - { - foreach($ref_ids as $ref_id) - { - $revIdMapping = array(); - - $oldNode_data = $tree->getNodeData($ref_id); - if ($oldNode_data['parent'] == $folder_ref_id) - { - require_once 'Modules/File/classes/class.ilObjFileAccess.php'; - $newTitle = ilObjFileAccess::_appendNumberOfCopyToFilename($oldNode_data['title'],null); - $newRef = $this->cloneNodes($ref_id, $folder_ref_id, $refIdMapping, $newTitle); - } - else - { - $newRef = $this->cloneNodes($ref_id, $folder_ref_id, $refIdMapping, null); - } - - // BEGIN ChangeEvent: Record copy event. - $old_parent_data = $tree->getParentNodeData($ref_id); - $newNode_data = $tree->getNodeData($newRef); - ilChangeEvent::_recordReadEvent($oldNode_data['type'], $ref_id, - $oldNode_data['obj_id'], $ilUser->getId()); - ilChangeEvent::_recordWriteEvent($newNode_data['obj_id'], $ilUser->getId(), 'add', - $ilObjDataCache->lookupObjId($folder_ref_id)); - ilChangeEvent::_catchupWriteEvents($newNode_data['obj_id'], $ilUser->getId()); - // END PATCH ChangeEvent: Record cut event. - } - } - - ilUtil::sendSuccess($this->lng->txt('msg_cloned'), true); - } // END COPY - - // process CUT command - if($command == 'cut') - { - foreach($_POST['nodes'] as $folder_ref_id) - { - foreach($ref_ids as $ref_id) - { - // Store old parent - $old_parent = $tree->getParentId($ref_id); - $tree->moveTree($ref_id, $folder_ref_id); - $rbacadmin->adjustMovedObjectPermissions($ref_id, $old_parent); - - include_once('./Services/Conditions/classes/class.ilConditionHandler.php'); - ilConditionHandler::_adjustMovedObjectConditions($ref_id); - - // BEGIN ChangeEvent: Record cut event. - $node_data = $tree->getNodeData($ref_id); - $old_parent_data = $tree->getNodeData($old_parent); - ilChangeEvent::_recordWriteEvent($node_data['obj_id'], $ilUser->getId(), 'remove', - $old_parent_data['obj_id']); - ilChangeEvent::_recordWriteEvent($node_data['obj_id'], $ilUser->getId(), 'add', - $ilObjDataCache->lookupObjId($folder_ref_id)); - ilChangeEvent::_catchupWriteEvents($node_data['obj_id'], $ilUser->getId()); - // END PATCH ChangeEvent: Record cut event. - } - - // prevent multiple iterations for cut cmommand - break; - } - - ilUtil::sendSuccess($this->lng->txt('msg_cut_copied'), true); - } // END CUT - - // process LINK command - if($command == 'link') - { - $linked_to_folders = array(); - - include_once "Services/AccessControl/classes/class.ilRbacLog.php"; - $rbac_log_active = ilRbacLog::isActive(); - - foreach($_POST['nodes'] as $folder_ref_id) - { - $linked_to_folders[$folder_ref_id] = $ilObjDataCache->lookupTitle($ilObjDataCache->lookupObjId($folder_ref_id)); - - foreach($ref_ids as $ref_id) - { - // get node data - $top_node = $tree->getNodeData($ref_id); - - // get subnodes of top nodes - $subnodes[$ref_id] = $tree->getSubtree($top_node); - } - - // now move all subtrees to new location - foreach($subnodes as $key => $subnode) - { - // first paste top_node.... - $obj_data = ilObjectFactory::getInstanceByRefId($key); - $new_ref_id = $obj_data->createReference(); - $obj_data->putInTree($folder_ref_id); - $obj_data->setPermissions($folder_ref_id); - - // rbac log - if($rbac_log_active) - { - $rbac_log_roles = $rbacreview->getParentRoleIds($new_ref_id, false); - $rbac_log = ilRbacLog::gatherFaPa($new_ref_id, array_keys($rbac_log_roles), true); - ilRbacLog::add(ilRbacLog::LINK_OBJECT, $new_ref_id, $rbac_log, $key); - } - - // BEGIN ChangeEvent: Record link event. - $node_data = $tree->getNodeData($new_ref_id); - ilChangeEvent::_recordWriteEvent($node_data['obj_id'], $ilUser->getId(), 'add', - $ilObjDataCache->lookupObjId($folder_ref_id)); - ilChangeEvent::_catchupWriteEvents($node_data['obj_id'], $ilUser->getId()); - // END PATCH ChangeEvent: Record link event. - } - - $ilLog->write(__METHOD__.', link finished'); - } - - $linked_targets = array(); - $links = []; - if(count($linked_to_folders)) - { - require_once 'Services/Link/classes/class.ilLink.php'; - foreach($linked_to_folders as $ref_id => $title) - { - $linked_targets[] = '' . $title . ''; - $links[] = $ui->factory()->link()->standard($title, ilLink::_getLink($ref_id)); - } - } - - $suffix = 'p'; - if(count($ref_ids) == 1) - { - $suffix = 's'; - } - - $mbox = $ui->factory()->messageBox()->success($this->lng->txt('mgs_objects_linked_to_the_following_folders_' . $suffix)) - ->withLinks($links); - - ilUtil::sendSuccess($ui->renderer()->render($mbox), true); - } // END LINK - - // clear clipboard - $this->clearObject(); - - $this->ctrl->returnToParent($this); - } - - public function initAndDisplayLinkIntoMultipleObjectsObject() - { - $tree = $this->tree; - - // empty session on init - $_SESSION['paste_linked_repexpand'] = array(); - - // copy opend nodes from repository explorer - $_SESSION['paste_linked_repexpand'] = is_array($_SESSION['repexpand']) ? $_SESSION['repexpand'] : array(); - - // open current position - $path = $tree->getPathId((int)$_GET['ref_id']); - foreach((array)$path as $node_id) - { - if(!in_array($node_id, $_SESSION['paste_linked_repexpand'])) - $_SESSION['paste_linked_repexpand'][] = $node_id; - } - - return $this->showPasteTreeObject(); - } - - /** - * Show paste tree - */ - public function showPasteTreeObject() - { - $ilTabs = $this->tabs; - $ilToolbar = $this->toolbar; - $ilErr = $this->error; - - $ilTabs->setTabActive('view_content'); - - if(!in_array($_SESSION['clipboard']['cmd'], array('link', 'copy', 'cut'))) - { - $message = __METHOD__.": Unknown action."; - $ilErr->raiseError($message, $ilErr->WARNING); - } - $cmd = $_SESSION['clipboard']['cmd']; - - // - $exp = $this->getTreeSelectorGUI($cmd); - if ($exp->handleCommand()) - { - return; - } - $output = $exp->getHTML(); - - $txt_var = ($cmd == "copy") - ? "copy" - : "paste"; - - // toolbars - $t = new ilToolbarGUI(); - $t->setFormAction($this->ctrl->getFormAction($this, "performPasteIntoMultipleObjects")); - - include_once("./Services/UIComponent/Button/classes/class.ilSubmitButton.php"); - $b = ilSubmitButton::getInstance(); - $b->setCaption($txt_var); - $b->setCommand("performPasteIntoMultipleObjects"); - - //$t->addFormButton($this->lng->txt($txt_var), "performPasteIntoMultipleObjects"); - $t->addStickyItem($b); - - $t->addSeparator(); - $this->lng->loadLanguageModule('obj'); - $t->addFormButton($this->lng->txt("obj_insert_into_clipboard"), "keepObjectsInClipboard"); - - $t->addFormButton($this->lng->txt("cancel"), "cancelMoveLink"); - $t->setCloseFormTag(false); - $t->setLeadingImage(ilUtil::getImagePath("arrow_upright.svg"), " "); - $output = $t->getHTML().$output; - $t->setLeadingImage(ilUtil::getImagePath("arrow_downright.svg"), " "); - $t->setCloseFormTag(true); - $t->setOpenFormTag(false); - $output.= "
          ".$t->getHTML(); - - $this->tpl->setContent($output); - } - - - /** - * Cancel move|link - * empty clipboard and return to parent - */ - public function cancelMoveLinkObject() - { - $ilCtrl = $this->ctrl; - - unset($_SESSION['clipboard']); - $ilCtrl->returnToParent($this); - } - - /** - * Keep objects in the clipboard - */ - function keepObjectsInClipboardObject() - { - $ilCtrl = $this->ctrl; - - ilUtil::sendSuccess($this->lng->txt("obj_inserted_clipboard"), true); - $ilCtrl->returnToParent($this); - } - - - public function initAndDisplayCopyIntoMultipleObjectsObject() - { - $tree = $this->tree; - - // empty session on init - $_SESSION['paste_copy_repexpand'] = array(); - - // copy opend nodes from repository explorer - $_SESSION['paste_copy_repexpand'] = is_array($_SESSION['repexpand']) ? $_SESSION['repexpand'] : array(); - - // open current position - $path = $tree->getPathId((int)$_GET['ref_id']); - foreach((array)$path as $node_id) - { - if(!in_array($node_id, $_SESSION['paste_copy_repexpand'])) - $_SESSION['paste_copy_repexpand'][] = $node_id; - } - - return $this->showPasteTreeObject(); - } - - - public function initAndDisplayMoveIntoObjectObject() - { - $tree = $this->tree; - - // empty session on init - $_SESSION['paste_cut_repexpand'] = array(); - - // copy opend nodes from repository explorer - $_SESSION['paste_cut_repexpand'] = is_array($_SESSION['repexpand']) ? $_SESSION['repexpand'] : array(); - - // open current position - $path = $tree->getPathId((int)$_GET['ref_id']); - foreach((array)$path as $node_id) - { - if(!in_array($node_id, $_SESSION['paste_cut_repexpand'])) - $_SESSION['paste_cut_repexpand'][] = $node_id; - } - - return $this->showPasteTreeObject(); - } - - - /** - * paste object from clipboard to current place - * Depending on the chosen command the object(s) are linked, copied or moved - * - * @access public - */ - function pasteObject() - { - $rbacsystem = $this->rbacsystem; - $rbacadmin = $this->rbacadmin; - $ilLog = $this->log; - $tree = $this->tree; - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - $ilErr = $this->error; + $ilSetting = $this->settings; + $lng = $this->lng; + + if ((int) $ilSetting->get('disable_my_offers')) { + return $this->renderObject(); + } + + include_once './Services/PersonalDesktop/classes/class.ilDesktopItemGUI.php'; + ilDesktopItemGUI::removeFromDesktop(); + ilUtil::sendSuccess($lng->txt("removed_from_desktop")); + $this->renderObject(); + } - $exists = []; - $no_paste = []; - $is_child = []; - $not_allowed_subobject = []; + // bugfix mantis 24559 + // undoing an erroneous change inside mantis 23516 by adding "Download Multiple Objects"-functionality for non-admins + // as they don't have the possibility to use the multi-download-capability of the manage-tab + public function enableMultiDownloadObject() + { + $this->multi_download_enabled = true; + $this->renderObject(); + } + + public function isMultiDownloadEnabled() + { + return $this->multi_download_enabled; + } + + /** + * cut object(s) out from a container and write the information to clipboard + * + * + * @access public + */ + public function cutObject() + { + $rbacsystem = $this->rbacsystem; + $ilCtrl = $this->ctrl; + $ilErr = $this->error; + + if ($_GET["item_ref_id"] != "") { + $_POST["id"] = array($_GET["item_ref_id"]); + } + + $no_cut = []; + + if (!isset($_POST["id"])) { + $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); + } + + // FOR ALL OBJECTS THAT SHOULD BE COPIED + foreach ($_POST["id"] as $ref_id) { + // GET COMPLETE NODE_DATA OF ALL SUBTREE NODES + $node_data = $this->tree->getNodeData($ref_id); + $subtree_nodes = $this->tree->getSubTree($node_data); + + $all_node_data[] = $node_data; + $all_subtree_nodes[] = $subtree_nodes; + + // CHECK DELETE PERMISSION OF ALL OBJECTS IN ACTUAL SUBTREE + foreach ($subtree_nodes as $node) { + if ($node['type'] == 'rolf') { + continue; + } + + if (!$rbacsystem->checkAccess('delete', $node["ref_id"])) { + $no_cut[] = $node["ref_id"]; + } + } + } + // IF THERE IS ANY OBJECT WITH NO PERMISSION TO 'delete' + if (count($no_cut)) { + $titles = array(); + foreach ((array) $no_cut as $cut_id) { + $titles[] = ilObject::_lookupTitle(ilObject::_lookupObjId($cut_id)); + } + $ilErr->raiseError( + $this->lng->txt("msg_no_perm_cut") . " " . implode(',', (array) $titles), + $ilErr->MESSAGE + ); + } + $_SESSION["clipboard"]["parent"] = $_GET["ref_id"]; + $_SESSION["clipboard"]["cmd"] = $ilCtrl->getCmd(); + $_SESSION["clipboard"]["ref_ids"] = $_POST["id"]; + + ilUtil::sendInfo($this->lng->txt("msg_cut_clipboard"), true); + + return $this->initAndDisplayMoveIntoObjectObject(); + } // END CUT - // BEGIN ChangeEvent: Record paste event. - require_once('Services/Tracking/classes/class.ilChangeEvent.php'); - // END ChangeEvent: Record paste event. - -//var_dump($_SESSION["clipboard"]);exit; - if (!in_array($_SESSION["clipboard"]["cmd"],array("cut","link","copy"))) - { - $message = get_class($this)."::pasteObject(): cmd was neither 'cut','link' or 'copy'; may be a hack attempt!"; - $ilErr->raiseError($message, $ilErr->WARNING); - } - - // this loop does all checks - foreach ($_SESSION["clipboard"]["ref_ids"] as $ref_id) - { - $obj_data = ilObjectFactory::getInstanceByRefId($ref_id); - - // CHECK ACCESS - if (!$rbacsystem->checkAccess('create',$this->object->getRefId(), $obj_data->getType())) - { - $no_paste[] = $ref_id; - $no_paste_titles[] = $obj_data->getTitle(); - } - - // CHECK IF REFERENCE ALREADY EXISTS - if ($this->object->getRefId() == $this->tree->getParentId($obj_data->getRefId())) - { - $exists[] = $ref_id; - break; - } - - // CHECK IF PASTE OBJECT SHALL BE CHILD OF ITSELF - if ($this->tree->isGrandChild($ref_id,$this->object->getRefId())) - { - $is_child[] = ilObject::_lookupTitle(ilObject::_lookupObjId($ref_id)); - } - - if ($ref_id == $this->object->getRefId()) - { - $is_child[] = ilObject::_lookupTitle(ilObject::_lookupObjId($ref_id)); - } - - // CHECK IF OBJECT IS ALLOWED TO CONTAIN PASTED OBJECT AS SUBOBJECT - $obj_type = $obj_data->getType(); - - if (!in_array($obj_type, array_keys($this->object->getPossibleSubObjects()))) - { - $not_allowed_subobject[] = $obj_data->getType(); - } - } - - //////////////////////////// - // process checking results - // BEGIN WebDAV: Copying an object into the same container is allowed - if (count($exists) > 0 && $_SESSION["clipboard"]["cmd"] != "copy") - // END WebDAV: Copying an object into the same container is allowed - { - $ilErr->raiseError($this->lng->txt("msg_obj_exists"), $ilErr->MESSAGE); - } - - if (count($is_child) > 0) - { - $ilErr->raiseError($this->lng->txt("msg_not_in_itself")." ".implode(',',$is_child), - $ilErr->MESSAGE); - } - - if (count($not_allowed_subobject) > 0) - { - $ilErr->raiseError($this->lng->txt("msg_may_not_contain")." ".implode(',',$not_allowed_subobject), - $ilErr->MESSAGE); - } - - if (count($no_paste) > 0) - { - $ilErr->raiseError($this->lng->txt("msg_no_perm_paste")." ". - implode(',',$no_paste), $ilErr->MESSAGE); - } - - // log pasteObject call - $ilLog->write("ilObjectGUI::pasteObject(), cmd: ".$_SESSION["clipboard"]["cmd"]); - - //////////////////////////////////////////////////////// - // everything ok: now paste the objects to new location - - // to prevent multiple actions via back/reload button - $ref_ids = $_SESSION["clipboard"]["ref_ids"]; - unset($_SESSION["clipboard"]["ref_ids"]); - - // BEGIN WebDAV: Support a copy command in the repository - // process COPY command - if ($_SESSION["clipboard"]["cmd"] == "copy") - { - unset($_SESSION["clipboard"]["cmd"]); - - // new implementation, redirects to ilObjectCopyGUI - if (count($ref_ids) == 1) - { - $ilCtrl->setParameterByClass("ilobjectcopygui", "target", $this->object->getRefId()); - $ilCtrl->setParameterByClass("ilobjectcopygui", "source_id", $ref_ids[0]); - $ilCtrl->redirectByClass("ilobjectcopygui", "saveTarget"); - } - else - { - $ilCtrl->setParameterByClass("ilobjectcopygui", "target", $this->object->getRefId()); - $ilCtrl->setParameterByClass("ilobjectcopygui", "source_ids", implode($ref_ids, "_")); - $ilCtrl->redirectByClass("ilobjectcopygui", "saveTarget"); - } - - - - /* old implementation - - foreach($ref_ids as $ref_id) - { - $revIdMapping = array(); - - $oldNode_data = $tree->getNodeData($ref_id); - if ($oldNode_data['parent'] == $this->object->getRefId()) - { - require_once 'Modules/File/classes/class.ilObjFileAccess.php'; - $newTitle = ilObjFileAccess::_appendNumberOfCopyToFilename($oldNode_data['title'],null); - $newRef = $this->cloneNodes($ref_id, $this->object->getRefId(), $refIdMapping, $newTitle); - } - else - { - $newRef = $this->cloneNodes($ref_id, $this->object->getRefId(), $refIdMapping, null); - } - - // BEGIN ChangeEvent: Record copy event. - $old_parent_data = $tree->getParentNodeData($ref_id); - $newNode_data = $tree->getNodeData($newRef); - ilChangeEvent::_recordReadEvent($oldNode_data['type'], $ref_id, - $oldNode_data['obj_id'], $ilUser->getId()); - ilChangeEvent::_recordWriteEvent($newNode_data['obj_id'], $ilUser->getId(), 'add', - $this->object->getId()); - ilChangeEvent::_catchupWriteEvents($newNode_data['obj_id'], $ilUser->getId()); - // END ChangeEvent: Record copy event. - }*/ - - $ilLog->write("ilObjectGUI::pasteObject(), copy finished"); - } - // END WebDAV: Support a Copy command in the repository - - // process CUT command - if ($_SESSION["clipboard"]["cmd"] == "cut") - { - - foreach($ref_ids as $ref_id) - { - // Store old parent - $old_parent = $tree->getParentId($ref_id); - $this->tree->moveTree($ref_id,$this->object->getRefId()); - $rbacadmin->adjustMovedObjectPermissions($ref_id,$old_parent); - - include_once('./Services/Conditions/classes/class.ilConditionHandler.php'); - ilConditionHandler::_adjustMovedObjectConditions($ref_id); - - // BEGIN ChangeEvent: Record cut event. - $node_data = $tree->getNodeData($ref_id); - $old_parent_data = $tree->getNodeData($old_parent); - ilChangeEvent::_recordWriteEvent($node_data['obj_id'], $ilUser->getId(), 'remove', - $old_parent_data['obj_id']); - ilChangeEvent::_recordWriteEvent($node_data['obj_id'], $ilUser->getId(), 'add', - $this->object->getId()); - ilChangeEvent::_catchupWriteEvents($node_data['obj_id'], $ilUser->getId()); - // END PATCH ChangeEvent: Record cut event. - } - } // END CUT - - // process LINK command - if ($_SESSION["clipboard"]["cmd"] == "link") - { - foreach ($ref_ids as $ref_id) - { - // get node data - $top_node = $this->tree->getNodeData($ref_id); - - // get subnodes of top nodes - $subnodes[$ref_id] = $this->tree->getSubtree($top_node); - } - - // now move all subtrees to new location - foreach ($subnodes as $key => $subnode) - { - // first paste top_node.... - $obj_data = ilObjectFactory::getInstanceByRefId($ref_id); - $new_ref_id = $obj_data->createReference(); - $obj_data->putInTree($_GET["ref_id"]); - $obj_data->setPermissions($_GET["ref_id"]); - - // BEGIN ChangeEvent: Record link event. - $node_data = $tree->getNodeData($new_ref_id); - ilChangeEvent::_recordWriteEvent($node_data['obj_id'], $ilUser->getId(), 'add', - $this->object->getId()); - ilChangeEvent::_catchupWriteEvents($node_data['obj_id'], $ilUser->getId()); - // END PATCH ChangeEvent: Record link event. - } - - $ilLog->write("ilObjectGUI::pasteObject(), link finished"); - - } // END LINK - - // save cmd for correct message output after clearing the clipboard - $last_cmd = $_SESSION["clipboard"]["cmd"]; - - - // clear clipboard - $this->clearObject(); - - if ($last_cmd == "cut") - { - ilUtil::sendSuccess($this->lng->txt("msg_cut_copied"),true); - } - // BEGIN WebDAV: Support a copy command in repository - else if ($last_cmd == "copy") - { - ilUtil::sendSuccess($this->lng->txt("msg_cloned"),true); - } - else if ($last_cmd == 'link') - // END WebDAV: Support copy command in repository - { - ilUtil::sendSuccess($this->lng->txt("msg_linked"),true); - } - - $this->ctrl->returnToParent($this); - - } // END PASTE - - - /** - * show clipboard - */ - function clipboardObject() - { - $ilErr = $this->error; - $ilLog = $this->log; - $ilTabs = $this->tabs; - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $ilTabs->activateTab("clipboard"); - - // function should not be called if clipboard is empty - if (empty($_SESSION['clipboard']) or !is_array($_SESSION['clipboard'])) - { - $message = sprintf('%s::clipboardObject(): Illegal access. Clipboard variable is empty!', get_class($this)); - $ilLog->write($message,$ilLog->FATAL); - $ilErr->raiseError($this->lng->txt("permission_denied"),$ilErr->WARNING); - } - - $data = array(); - foreach($_SESSION["clipboard"]["ref_ids"] as $ref_id) - { - if(!$tmp_obj = ilObjectFactory::getInstanceByRefId($ref_id,false)) - { - continue; - } - - $data[] = array( - "type" => $tmp_obj->getType(), - "type_txt" => $this->lng->txt("obj_".$tmp_obj->getType()), - "title" => $tmp_obj->getTitle(), - "cmd" => ($_SESSION["clipboard"]["cmd"] == "cut") ? $this->lng->txt("move") :$this->lng->txt($_SESSION["clipboard"]["cmd"]), - "ref_id" => $ref_id, - "obj_id" => $tmp_obj->getId() - ); - - unset($tmp_obj); - } - - include_once("./Services/Object/classes/class.ilObjClipboardTableGUI.php"); - $tab = new ilObjClipboardTableGUI($this, "clipboard"); - $tab->setData($data); - $tpl->setContent($tab->getHTML()); - - if (count($data) > 0) - { - $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); - $ilToolbar->addFormButton($lng->txt("insert_object_here"), - "paste"); - $ilToolbar->addFormButton($lng->txt("clear_clipboard"), - "clear"); - } - - return true; - } - - function isActiveAdministrationPanel() - { - $ilAccess = $this->access; - - // #10081 - if($_SESSION["il_cont_admin_panel"] && - $this->object->getRefId() && - !$ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - return false; - } - - return $_SESSION["il_cont_admin_panel"]; - } - - /** - * May be overwritten in subclasses. - */ - function setColumnSettings(ilColumnGUI $column_gui) - { - $ilAccess = $this->access; - parent::setColumnSettings($column_gui); - - if ($ilAccess->checkAccess("write", "", $this->object->getRefId()) && - $this->isActiveAdministrationPanel() && - $this->allowBlocksMoving()) - { - $column_gui->setEnableMovement(true); - } - - $column_gui->setRepositoryItems( - $this->object->getSubItems($this->isActiveAdministrationPanel(), true)); - - //if ($ilAccess->checkAccess("write", "", $this->object->getRefId()) - // && $this->allowBlocksConfigure()) - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - $column_gui->setBlockProperty("news", "settings", true); - //$column_gui->setBlockProperty("news", "public_notifications_option", true); - $column_gui->setBlockProperty("news", "default_visibility_option", true); - $column_gui->setBlockProperty("news", "hide_news_block_option", true); - } - - if ($this->isActiveAdministrationPanel()) - { - $column_gui->setAdminCommands(true); - } - } - - /** - * Standard is to allow blocks moving - */ - function allowBlocksMoving() - { - return true; - } - - /** - * Standard is to allow blocks configuration - */ - function allowBlocksConfigure() - { - return true; - } - - /** - * - * - * @access public - * @param - * - */ - public function cloneWizardPageTreeObject() - { - $this->cloneWizardPageObject(true); - } - - /** - * - * - * @access public - * @param - * - */ - public function cloneWizardPageListObject() - { - $this->cloneWizardPageObject(false); - } - - /** - * Show clone wizard page for container objects - * - * @access public - * - */ - public function cloneWizardPageObject($a_tree_view = true) - { - include_once('Services/CopyWizard/classes/class.ilCopyWizardPageFactory.php'); - - $ilObjDataCache = $this->obj_data_cache; - $tree = $this->tree; - - if(!$_REQUEST['clone_source']) - { - ilUtil::sendFailure($this->lng->txt('select_one')); - if(isset($_SESSION['wizard_search_title'])) - { - $this->searchCloneSourceObject(); - } - else - { - $this->createObject(); - } - return false; - } - $source_id = $_REQUEST['clone_source']; - $new_type = $_REQUEST['new_type']; - $this->ctrl->setParameter($this,'clone_source',(int) $_REQUEST['clone_source']); - $this->ctrl->setParameter($this,'new_type',$new_type); - - - // Generell JavaScript - $this->tpl->addJavaScript('./Services/CopyWizard/js/ilContainer.js'); - $this->tpl->setVariable('BODY_ATTRIBUTES','onload="ilDisableChilds(\'cmd\');"'); - - - $this->tpl->addBlockFile('ADM_CONTENT','adm_content','tpl.container_wizard_page.html', - "Services/Container"); - $this->tpl->setVariable('FORMACTION',$this->ctrl->getFormAction($this)); - $this->tpl->setVariable('TYPE_IMG',ilUtil::getImagePath('icon_'.$new_type.'.svg')); - $this->tpl->setVariable('ALT_IMG',$this->lng->txt('obj_'.$new_type)); - $this->tpl->setVariable('TXT_DUPLICATE',$this->lng->txt($new_type.'_wizard_page')); - $this->tpl->setVariable('INFO_DUPLICATE',$this->lng->txt($new_type.'_copy_threads_info')); - $this->tpl->setVariable('BTN_COPY',$this->lng->txt('obj_'.$new_type.'_duplicate')); - $this->tpl->setVariable('BTN_BACK',$this->lng->txt('btn_back')); - if(isset($_SESSION['wizard_search_title'])) - { - $this->tpl->setVariable('CMD_BACK','searchCloneSource'); - } - else - { - $this->tpl->setVariable('CMD_BACK','create'); - } - - $this->tpl->setVariable('BTN_TREE',$this->lng->txt('treeview')); - $this->tpl->setVariable('BTN_LIST',$this->lng->txt('flatview')); - - // Fill item rows - // tree view - if($a_tree_view) - { - $first = true; - $has_items = false; - foreach($subnodes = $tree->getSubtree($source_node = $tree->getNodeData($source_id),true) as $node) - { - if($first == true) - { - $first = false; - continue; - } - - if($node['type'] == 'rolf') - { - continue; - } - - $has_items = true; - - for($i = $source_node['depth'];$i < $node['depth']; $i++) - { - $this->tpl->touchBlock('padding'); - $this->tpl->touchBlock('end_padding'); - } - // fill options - $copy_wizard_page = ilCopyWizardPageFactory::_getInstanceByType($source_id,$node['type']); - $copy_wizard_page->fillTreeSelection($node['ref_id'],$node['type'],$node['depth']); - - $this->tpl->setCurrentBlock('tree_row'); - $this->tpl->setVariable('TREE_IMG',ilUtil::getImagePath('icon_'.$node['type'].'.svg')); - $this->tpl->setVariable('TREE_ALT_IMG',$this->lng->txt('obj_'.$node['type'])); - $this->tpl->setVariable('TREE_TITLE',$node['title']); - $this->tpl->parseCurrentBlock(); - } - if(!$has_items) - { - $this->tpl->setCurrentBlock('no_content'); - $this->tpl->setVariable('TXT_NO_CONTENT',$this->lng->txt('container_no_items')); - $this->tpl->parseCurrentBlock(); - } - else - { - $this->tpl->setCurrentBlock('tree_footer'); - $this->tpl->setVariable('TXT_COPY_ALL',$this->lng->txt('copy_all')); - $this->tpl->setVariable('TXT_LINK_ALL',$this->lng->txt('link_all')); - $this->tpl->setVariable('TXT_OMIT_ALL',$this->lng->txt('omit_all')); - $this->tpl->parseCurrentBlock(); - - } - } - else - { - foreach($tree->getSubTreeTypes($source_id,array('rolf','crs')) as $type) - { - $copy_wizard_page = ilCopyWizardPageFactory::_getInstanceByType($source_id,$type); - if(strlen($html = $copy_wizard_page->getWizardPageBlockHTML())) - { - $this->tpl->setCurrentBlock('obj_row'); - $this->tpl->setVariable('ITEM_BLOCK',$html); - $this->tpl->parseCurrentBlock(); - } - } - } - } - - /** - * Clone all object - * Overwritten method for copying container objects - * - * @access public - * - */ - public function cloneAllObject() - { - $ilLog = $this->log; - $ilCtrl = $this->ctrl; - - include_once('./Services/Link/classes/class.ilLink.php'); - include_once('Services/CopyWizard/classes/class.ilCopyWizardOptions.php'); - - $ilAccess = $this->access; - $ilErr = $this->error; - $rbacsystem = $this->rbacsystem; - $tree = $this->tree; - $ilUser = $this->user; - - $new_type = $_REQUEST['new_type']; - $ref_id = (int) $_GET['ref_id']; - $clone_source = (int) $_REQUEST['clone_source']; - - if(!$rbacsystem->checkAccess('create', $ref_id,$new_type)) - { - $ilErr->raiseError($this->lng->txt('permission_denied')); - } - if(!$clone_source) - { - ilUtil::sendFailure($this->lng->txt('select_one')); - $this->createObject(); - return false; - } - if(!$ilAccess->checkAccess('write','', $clone_source,$new_type)) - { - $ilErr->raiseError($this->lng->txt('permission_denied')); - } - - $options = $_POST['cp_options'] ? $_POST['cp_options'] : array(); - $orig = ilObjectFactory::getInstanceByRefId($clone_source); - $result = $orig->cloneAllObject($_COOKIE[session_name()], $_COOKIE['ilClientId'], $new_type, $ref_id, $clone_source, $options); - - include_once './Services/CopyWizard/classes/class.ilCopyWizardOptions.php'; - if(ilCopyWizardOptions::_isFinished($result['copy_id'])) - { - ilUtil::sendSuccess($this->lng->txt("object_duplicated"),true); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $result['ref_id']); - $ilCtrl->redirectByClass("ilrepositorygui", ""); - } - else - { - ilUtil::sendInfo($this->lng->txt("object_copy_in_progress"),true); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $ref_id); - $ilCtrl->redirectByClass("ilrepositorygui", ""); - } - } - - - /** - * Save Sorting - * - * @access public - * @param - * - */ - public function saveSortingObject() - { - include_once('Services/Container/classes/class.ilContainerSorting.php'); - $sorting = ilContainerSorting::_getInstance($this->object->getId()); - - // Allow comma - $positions = str_replace(',','.',$_POST['position']); - - $sorting->savePost($positions); - ilUtil::sendSuccess($this->lng->txt('cntr_saved_sorting'), true); - $this->ctrl->redirect($this, "editOrder"); - } - - // BEGIN WebDAV: Support a copy command in the repository - /** - * Recursively clones all nodes of the RBAC tree. - * - * @access private - * @param integer ref_id of source object - * @param integer ref_id of destination object - * @param array mapping new_ref_id => old_ref_id - * @param string the new name of the copy (optional). - * @return The ref_id pointing to the cloned object. - */ - function cloneNodes($srcRef,$dstRef,&$mapping, $newName=null) - { - $tree = $this->tree; - - // clone the source node - $srcObj = ilObjectFactory::getInstanceByRefId($srcRef); - error_log(__METHOD__.' cloning srcRef='.$srcRef.' dstRef='.$dstRef.'...'); - $newRef = $srcObj->cloneObject($dstRef)->getRefId(); - error_log(__METHOD__.' ...cloning... newRef='.$newRef.'...'); - - // We must immediately apply a new name to the object, to - // prevent confusion of WebDAV clients about having two objects with identical - // name in the repository. - if (! is_null($newName)) - { - $newObj = ilObjectFactory::getInstanceByRefId($newRef); - $newObj->setTitle($newName); - $newObj->update(); - unset($newObj); - } - unset($srcObj); - $mapping[$newRef] = $srcRef; - - // clone all children of the source node - $children = $tree->getChilds($srcRef); - foreach ($tree->getChilds($srcRef) as $child) - { - // Don't clone role folders, because it does not make sense to clone local roles - // FIXME - Maybe it does make sense (?) - if ($child["type"] != 'rolf') - { - $this->cloneNodes($child["ref_id"],$newRef,$mapping); - } - else - { - if (count($rolf = $tree->getChildsByType($newRef,"rolf"))) - { - $mapping[$rolf[0]["ref_id"]] = $child["ref_id"]; - } - } - } - error_log(__METHOD__.' ...cloned srcRef='.$srcRef.' dstRef='.$dstRef.' newRef='.$newRef); - return $newRef; - } - // END PATCH WebDAV: Support a copy command in the repository - - /** - * Modify list gui for presentation in container - * @param type $a_item_list_gui - * @param type $a_item_data - * @param type $a_show_path - */ - public function modifyItemGUI($a_item_list_gui, $a_item_data, $a_show_path) - { - $lng = $this->lng; - - if($a_show_path) - { - $a_item_list_gui->addCustomProperty($lng->txt('path'), - ilContainer::buildPath($a_item_data['ref_id'], $this->object->getRefId()), - false, true); - } - } - - /** - * build path - */ - static function _buildPath($a_ref_id, $a_course_ref_id) - { - global $DIC; - - $tree = $DIC->repositoryTree(); - - $path_arr = $tree->getPathFull($a_ref_id, $a_course_ref_id); - $counter = 0; - foreach($path_arr as $data) - { - if($counter++) - { - $path .= " > "; - } - $path .= $data['title']; - } - - return $path; - } - - // - // Style editing - // - - /** - * Edit style properties - */ - function editStylePropertiesObject() - { - $ilTabs = $this->tabs; - $tpl = $this->tpl; - - $this->checkPermission("write"); - - $this->initStylePropertiesForm(); - $tpl->setContent($this->form->getHTML()); - - $ilTabs->activateTab("obj_sty"); - } - - /** - * Init style properties form - */ - function initStylePropertiesForm() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilTabs = $this->tabs; - $ilSetting = $this->settings; - $tpl = $this->tpl; - - $tpl->setTreeFlatIcon("", ""); - $ilTabs->clearTargets(); - $xpage_id = ilContainer::_lookupContainerSetting($this->object->getId(), - "xhtml_page"); - if ($xpage_id > 0) - { - $ilTabs->setBackTarget($lng->txt("cntr_back_to_old_editor"), - $ilCtrl->getLinkTarget($this, "switchToOldEditor"), "_top"); - } - else - { - $ilTabs->setBackTarget($lng->txt("back"), "./goto.php?target=".$this->object->getType()."_". - $this->object->getRefId(), "_top"); - } - - include_once("./Services/Container/classes/class.ilContainerPageGUI.php"); - $page_gui = new ilContainerPageGUI($this->object->getId()); - $style_id = $this->object->getStyleSheetId(); - if (ilObject::_lookupType($style_id) == "sty") - { - $page_gui->setStyleId($style_id); - } - else - { - $style_id = 0; - } - $page_gui->setTabHook($this, "addPageTabs"); - $ilCtrl->getHTML($page_gui); - $ilTabs->setTabActive("obj_sty"); - - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $lng->loadLanguageModule("style"); - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - $fixed_style = $ilSetting->get("fixed_content_style_id"); -// $style_id = $this->object->getStyleSheetId(); - - if ($fixed_style > 0) - { - $st = new ilNonEditableValueGUI($lng->txt("wiki_current_style")); - $st->setValue(ilObject::_lookupTitle($fixed_style)." (". - $this->lng->txt("global_fixed").")"); - $this->form->addItem($st); - } - else - { - $st_styles = ilObjStyleSheet::_getStandardStyles(true, false, - $_GET["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($lng->txt("style_current_style")); - $st->setValue(ilObject::_lookupTitle($style_id)); - $this->form->addItem($st); - -//$this->ctrl->getLinkTargetByClass("ilObjStyleSheetGUI", "edit")); - - // delete command - $this->form->addCommandButton("editStyle", - $lng->txt("style_edit_style")); - $this->form->addCommandButton("deleteStyle", - $lng->txt("style_delete_style")); -//$this->ctrl->getLinkTargetByClass("ilObjStyleSheetGUI", "delete")); - } - } - - if ($style_id <= 0 || ilObjStyleSheet::_lookupStandard($style_id)) - { - $style_sel = ilUtil::formSelect ($style_id, "style_id", - $st_styles, false, true); - $style_sel = new ilSelectInputGUI($lng->txt("style_current_style"), "style_id"); - $style_sel->setOptions($st_styles); - $style_sel->setValue($style_id); - $this->form->addItem($style_sel); -//$this->ctrl->getLinkTargetByClass("ilObjStyleSheetGUI", "create")); - $this->form->addCommandButton("saveStyleSettings", - $lng->txt("save")); - $this->form->addCommandButton("createStyle", - $lng->txt("sty_create_ind_style")); - } - } - $this->form->setTitle($lng->txt("obj_sty")); - $this->form->setFormAction($ilCtrl->getFormAction($this)); - } - - /** - * Create Style - */ - function createStyleObject() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirectByClass("ilobjstylesheetgui", "create"); - } - - /** - * Edit Style - */ - function editStyleObject() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirectByClass("ilobjstylesheetgui", "edit"); - } - - /** - * Delete Style - */ - function deleteStyleObject() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirectByClass("ilobjstylesheetgui", "delete"); - } - - /** - * Save style settings - */ - function saveStyleSettingsObject() - { - $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(ilUtil::stripSlashes($_POST["style_id"])); - $this->object->update(); - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - } - $this->ctrl->redirect($this, "editStyleProperties"); - } - - /** - * Get item list command drop down asynchronously - */ - function getAsynchItemListObject() - { - $ilCtrl = $this->ctrl; - - $ref_id = $_GET["cmdrefid"]; - $obj_id = ilObject::_lookupObjId($ref_id); - $type = ilObject::_lookupType($obj_id); - - // this should be done via container-object->getSubItem in the future - $data = array("child" => $ref_id, "ref_id" => $ref_id, "obj_id" => $obj_id, - "type" => $type); - include_once 'Services/Object/classes/class.ilObjectListGUIFactory.php'; - $item_list_gui = ilObjectListGUIFactory::_getListGUIByType($type); - $item_list_gui->setContainerObject($this); - - $item_list_gui->enableComments(true); - $item_list_gui->enableNotes(true); - $item_list_gui->enableTags(true); - - $this->modifyItemGUI($item_list_gui, $data, false); - $html = $item_list_gui->getListItemHTML($ref_id, - $obj_id, "", "", true, true); - - // include plugin slot for async item list - $ilPluginAdmin = $this->plugin_admin; - $pl_names = $ilPluginAdmin->getActivePluginsForSlot(IL_COMP_SERVICE, "UIComponent", "uihk"); - foreach ($pl_names as $pl) - { - $ui_plugin = ilPluginAdmin::getPluginObject(IL_COMP_SERVICE, "UIComponent", "uihk", $pl); - $gui_class = $ui_plugin->getUIClassInstance(); - $resp = $gui_class->getHTML("Services/Container", "async_item_list", array("html" => $html)); - if ($resp["mode"] != ilUIHookPluginGUI::KEEP) - { - $html = $gui_class->modifyHTML($html, $resp); - } - } - - echo $html; - exit; - } - - /** - * Show webdav password instruction - * @return - */ - protected function showPasswordInstructionObject($a_init = true) - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - - if($a_init) - { - ilUtil::sendInfo($this->lng->txt('webdav_pwd_instruction')); - $this->initFormPasswordInstruction(); - } - - include_once ('Services/WebDAV/classes/class.ilWebDAVUtil.php'); - $dav_util = ilWebDAVUtil::getInstance(); - $ilToolbar->addButton( - $this->lng->txt('mount_webfolder'), - $dav_util->getMountURI($this->object->getRefId()), - '_blank', - '', - $dav_util->getFolderURI($this->object->getRefId()) - ); - - - $tpl->setContent($this->form->getHTML()); - } - - /** - * Init password form - * @return - */ - protected function initFormPasswordInstruction() - { - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - $this->form->setFormAction($this->ctrl->getFormAction($this)); - - // new password - $ipass = new ilPasswordInputGUI($this->lng->txt("desired_password"), "new_password"); - $ipass->setRequired(true); - - $this->form->addItem($ipass); - $this->form->addCommandButton("savePassword", $this->lng->txt("save")); - $this->form->addCommandButton('cancel', $this->lng->txt('cancel')); - - $this->form->setTitle($this->lng->txt("chg_ilias_and_webfolder_password")); - $this->form->setFormAction($this->ctrl->getFormAction($this)); - - return $this->form; - } - - /** - * Save password - * @return - */ - protected function savePasswordObject() - { - $ilUser = $this->user; - - $form = $this->initFormPasswordInstruction(); - if($form->checkInput()) - { - $ilUser->resetPassword($this->form->getInput('new_password'),$this->form->getInput('new_password')); - ilUtil::sendSuccess($this->lng->txt('webdav_pwd_instruction_success'),true); - $this->showPasswordInstructionObject(false); - return true; - } - $form->setValuesByPost(); - $this->showPasswordInstructionObject(); - } - - /** - * Redraw a list item (ajax) - * - * @param - * @return - */ - function redrawListItemObject() - { - $tpl = $this->tpl; - - $html = null; - - $item_data = $this->object->getSubItems(false, false, (int) $_GET["child_ref_id"]); - $container_view = $this->getContentGUI(); - - // list item is session material (not part of "_all"-items - see below) - include_once './Modules/Session/classes/class.ilEventItems.php'; - $event_items = ilEventItems::_getItemsOfContainer($this->object->getRefId()); - if(in_array((int)$_GET["child_ref_id"], $event_items)) - { - include_once('./Services/Object/classes/class.ilObjectActivation.php'); - foreach ($this->object->items["sess"] as $id) - { - $items = ilObjectActivation::getItemsByEvent($id['obj_id']); - foreach($items as $event_item) - { - if ($event_item["child"] == (int)$_GET["child_ref_id"]) - { - // sessions - if((int)$_GET["parent_ref_id"]) - { - $event_item["parent"] = (int)$_GET["parent_ref_id"]; - } - $html = $container_view->renderItem($event_item); - } - } - } - } - - // "normal" list item - if(!$html) - { - foreach ($this->object->items["_all"] as $id) - { - if ($id["child"] == (int) $_GET["child_ref_id"]) - { - $html = $container_view->renderItem($id); - } - } - } - - if($html) - { - echo $html; - - // we need to add onload code manually (rating, comments, etc.) - echo $tpl->getOnLoadCodeForAsynch(); - } - - exit; - } - - // begin-patch fm - /** - * Add file manager link - * @param $a_sub_type - * @param $a_sub_id - * - */ - protected function initHeaderAction($a_sub_type = null, $a_sub_id = null) - { - $lg = parent::initHeaderAction($a_sub_type, $a_sub_id); - - // begin-patch fm - include_once './Services/WebServices/FileManager/classes/class.ilFMSettings.php'; - if(ilFMSettings::getInstance()->isEnabled()) - { - if($lg instanceof ilObjectListGUI) - { - $lg->addCustomCommand($this->ctrl->getLinkTarget($this,'fileManagerLaunch'), 'fm_start','_blank'); - } - } - // end-patch fm - return $lg; - } - - /** - * Launch jnlp - */ - protected function fileManagerLaunchObject() - { - $ilUser = $this->user; - - $tpl = new ilTemplate('tpl.fm_launch_ws.html',false,false,'Services/WebServices/FileManager'); - $tpl->setVariable('JNLP_URL',ILIAS_HTTP_PATH.'/Services/WebServices/FileManager/lib/dist/FileManager.jnlp'); - $tpl->setVariable('SESSION_ID', $_COOKIE[session_name()].'::'.CLIENT_ID); - $tpl->setVariable('UID',$ilUser->getId()); - $tpl->setVariable('REF_ID', $this->object->getRefId()); - $tpl->setVariable('WSDL_URI', ILIAS_HTTP_PATH.'/webservice/soap/server.php?wsdl'); - $tpl->setVariable('LOCAL_FRAME', ilFMSettings::getInstance()->isLocalFSEnabled() ? 1 : 0); - $tpl->setVariable('REST_URI',ILIAS_HTTP_PATH.'/Services/WebServices/Rest/server.php'); - $tpl->setVariable('FILE_LOCKS',0); - $tpl->setVariable('UPLOAD_FILESIZE', ilFMSettings::getInstance()->getMaxFileSize()); - - include_once("./Modules/SystemFolder/classes/class.ilObjSystemFolder.php"); - $header_top_title = ilObjSystemFolder::_getHeaderTitle(); - $tpl->setVariable('HEADER_TITLE',$header_top_title ? $header_top_title : ''); - echo $tpl->get(); - exit; - } - // begin-patch fm - - /** - * Show tree - */ - function showRepTree() - { - $tpl = $this->tpl; - $ilUser = $this->user; - $ilSetting = $this->settings; - $ilCtrl = $this->ctrl; - - // set current repository view mode - if (!empty($_GET["set_mode"])) - { - $_SESSION["il_rep_mode"] = $_GET["set_mode"]; - if ($ilUser->getId() != ANONYMOUS_USER_ID) - { - $ilUser->writePref("il_rep_mode", $_GET["set_mode"]); - } - } - - // get user setting - if ($_SESSION["il_rep_mode"] == "") - { - if ($ilUser->getId() != ANONYMOUS_USER_ID) - { - $_SESSION["il_rep_mode"] = $ilUser->getPref("il_rep_mode"); - } - } - - // if nothing set, get default view - if ($_SESSION["il_rep_mode"] == "") - { - $_SESSION["il_rep_mode"] = $ilSetting->get("default_repository_view"); - } - - $mode = ($_SESSION["il_rep_mode"] != "") - ? $_SESSION["il_rep_mode"] - : "flat"; - - // check for administration context, see #0016312 - if ($mode == "tree" && (strtolower($_GET["baseClass"]) != "iladministrationgui")) - { - include_once("./Services/Repository/classes/class.ilRepositoryExplorerGUI.php"); - $exp = new ilRepositoryExplorerGUI($this, "showRepTree"); - if(method_exists($this, 'getAdditionalWhitelistTypes')) { - $whitelist = array_merge ( - $exp->getTypeWhiteList(), - $this->getAdditionalWhitelistTypes() - ); - $exp->setTypeWhiteList($whitelist); - } - - if (!$exp->handleCommand()) - { - $tpl->setLeftNavContent($exp->getHTML()); - } - } - } - - /** - * Init object edit form - * - * @return ilPropertyFormGUI - */ - protected function initEditForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $lng->loadLanguageModule($this->object->getType()); - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this, "update")); - $form->setTitle($this->lng->txt($this->object->getType()."_edit")); - - $this->initFormTitleDescription($form); - - $this->initEditCustomForm($form); - - $form->addCommandButton("update", $this->lng->txt("save")); - //$this->form->addCommandButton("cancelUpdate", $lng->txt("cancel")); - - return $form; - } - - /** - * Init title/description for edit form - * @param ilPropertyFormGUI $form - */ - public function initFormTitleDescription(ilPropertyFormGUI $form) - { - /** @var ilObjectTranslation $trans */ - if (is_object($this->object)) // note: this form can also be used for new groups (create group via awareness tool) - { - $trans = $this->object->getObjectTranslation(); - } - - $title = new ilTextInputGUI($this->lng->txt("title"), "title"); - $title->setRequired(true); - $title->setSize(min(40, ilObject::TITLE_LENGTH)); - $title->setMaxLength(ilObject::TITLE_LENGTH); - if(is_object($trans)) - { - $title->setValue($trans->getDefaultTitle()); - } - $form->addItem($title); - - if(is_object($trans) && sizeof($trans->getLanguages()) > 1) - { - include_once('Services/MetaData/classes/class.ilMDLanguageItem.php'); - $languages = ilMDLanguageItem::_getLanguages(); - $title->setInfo($this->lng->txt("language").": ".$languages[$trans->getDefaultLanguage()]. - ' » '.$this->lng->txt("obj_more_translations").''); - - unset($languages); - } - - $desc = new ilTextAreaInputGUI($this->lng->txt("description"), "desc"); - $desc->setRows(2); - $desc->setCols(40); - if(is_object($trans)) - { - $desc->setValue($trans->getDefaultDescription()); - } - $form->addItem($desc); - } - - - /** - * Append sorting settings to property form - * @param ilPropertyFormGUI $form - * @param type $a_sorting_settings - */ - protected function initSortingForm(ilPropertyFormGUI $form, array $a_sorting_settings) - { - include_once('Services/Container/classes/class.ilContainerSortingSettings.php'); - include_once './Services/Container/classes/class.ilContainer.php'; - - $settings = new ilContainerSortingSettings($this->object->getId()); - $sort = new ilRadioGroupInputGUI($this->lng->txt('sorting_header'), "sorting"); - - if(in_array(ilContainer::SORT_INHERIT, $a_sorting_settings)) - { - $sort_inherit = new ilRadioOption(); - $sort_inherit->setTitle( - $this->lng->txt('sort_inherit_prefix'). - ' ('.ilContainerSortingSettings::sortModeToString( - ilContainerSortingSettings::lookupSortModeFromParentContainer( - $this->object->getId())).') ' - ); - $sort_inherit->setValue(ilContainer::SORT_INHERIT); - $sort_inherit->setInfo($this->lng->txt('sorting_info_inherit')); - $sort->addOption($sort_inherit); - } - if(in_array(ilContainer::SORT_TITLE,$a_sorting_settings)) - { - $sort_title = new ilRadioOption( - $this->lng->txt('sorting_title_header'), - ilContainer::SORT_TITLE - ); - $sort_title->setInfo($this->lng->txt('sorting_info_title')); - - $this->initSortingDirectionForm($settings,$sort_title,'title'); - $sort->addOption($sort_title); - } - if(in_array(ilContainer::SORT_CREATION, $a_sorting_settings)) - { - $sort_activation = new ilRadioOption($this->lng->txt('sorting_creation_header'),ilContainer::SORT_CREATION); - $sort_activation->setInfo($this->lng->txt('sorting_creation_info')); - $this->initSortingDirectionForm($settings,$sort_activation,'creation'); - $sort->addOption($sort_activation); - } - if(in_array(ilContainer::SORT_ACTIVATION, $a_sorting_settings)) - { - $sort_activation = new ilRadioOption($this->lng->txt('crs_sort_activation'),ilContainer::SORT_ACTIVATION); - $sort_activation->setInfo($this->lng->txt('crs_sort_timing_info')); - $this->initSortingDirectionForm($settings,$sort_activation,'activation'); - $sort->addOption($sort_activation); - } - if(in_array(ilContainer::SORT_MANUAL, $a_sorting_settings)) - { - $sort_manual = new ilRadioOption( - $this->lng->txt('sorting_manual_header'), - ilContainer::SORT_MANUAL - ); - $sort_manual->setInfo($this->lng->txt('sorting_info_manual')); - $this->initManualSortingOptionForm($settings, $sort_manual, "manual", $a_sorting_settings); - $sort->addOption($sort_manual); - } - - // Handle moved containers and there possibly invalid values - if(in_array($settings->getSortMode(), $a_sorting_settings)) - { - $sort->setValue($settings->getSortMode()); - } - else - { - $sort->setValue(ilContainer::SORT_TITLE); - } - $form->addItem($sort); - - return $form; - } - - /** - * Add list presentation settings to form - * @param ilPropertyFormGUI $form - * @return ilPropertyFormGUI - */ - protected function initListPresentationForm(ilPropertyFormGUI $form) - { - $lpres = new ilRadioGroupInputGUI($this->lng->txt('cont_list_presentation'), "list_presentation"); - - $item_list = new ilRadioOption($this->lng->txt('cont_item_list'), ""); - //$item_list->setInfo($this->lng->txt('cont_item_list_info')); - $lpres->addOption($item_list); - - $tile_view = new ilRadioOption($this->lng->txt('cont_tile_view'), "tile"); - //$tile_view->setInfo($this->lng->txt('cont_tile_view_info')); - $lpres->addOption($tile_view); - - $lpres->setValue( - ilContainer::_lookupContainerSetting($this->object->getId(), "list_presentation")); - - $form->addItem($lpres); - - return $form; - } - - /** - * Save list presentation setting - * @param ilPropertyFormGUI $form - */ - protected function saveListPresentation(ilPropertyFormGUI $form) - { - $val = ($form->getInput('list_presentation') == "tile") - ? "tile" - : ""; - ilContainer::_writeContainerSetting($this->object->getId(), "list_presentation", $val); - } - - - /** - * Add sorting direction - * @param ilFormPropertyGUI $element - */ - protected function initSortingDirectionForm(ilContainerSortingSettings $sorting_settings, $element, $a_prefix) - { - if($a_prefix == 'manual') - { - $txt = $this->lng->txt('sorting_new_items_direction'); - } - else - { - $txt = $this->lng->txt('sorting_direction'); - } - - $direction = new ilRadioGroupInputGUI($txt,$a_prefix.'_sorting_direction'); - $direction->setValue($sorting_settings->getSortDirection()); - $direction->setRequired(TRUE); - - // asc - $asc = new ilRadioOption( - $this->lng->txt('sorting_asc'), - ilContainer::SORT_DIRECTION_ASC - ); - $direction->addOption($asc); - - // desc - $desc = new ilRadioOption( - $this->lng->txt('sorting_desc'), - ilContainer::SORT_DIRECTION_DESC - ); - $direction->addOption($desc); - - $element->addSubItem($direction); - - return $element; - } - - /** - * Add manual sorting options - * - */ - protected function initManualSortingOptionForm(ilContainerSortingSettings $settings, $element, $a_prefix, - $a_sorting_settings) - { - $position = new ilRadioGroupInputGUI($this->lng->txt('sorting_new_items_position'),$a_prefix.'_new_items_position'); - $position->setValue($settings->getSortNewItemsPosition()); - $position->setRequired(TRUE); - - //new items insert on top - $new_top = new ilRadioOption( - $this->lng->txt('sorting_new_items_at_top'), - ilContainer::SORT_NEW_ITEMS_POSITION_TOP - ); - - $position->addOption($new_top); - - //new items insert at bottom - $new_bottom = new ilRadioOption( - $this->lng->txt('sorting_new_items_at_bottom'), - ilContainer::SORT_NEW_ITEMS_POSITION_BOTTOM - ); - - $position->addOption($new_bottom); - - $element->addSubItem($position); - - $order = new ilRadioGroupInputGUI($this->lng->txt('sorting_new_items_order'),$a_prefix.'_new_items_order'); - $order->setValue($settings->getSortNewItemsOrder()); - $order->setRequired(TRUE); - - if(in_array(ilContainer::SORT_TITLE, $a_sorting_settings)) - { - //new items sort in alphabetical order - $new_title = new ilRadioOption( - $this->lng->txt('sorting_title_header'), - ilContainer::SORT_NEW_ITEMS_ORDER_TITLE - ); - - $order->addOption($new_title); - } - - if(in_array(ilContainer::SORT_CREATION, $a_sorting_settings)) - { - //new items sort by creation date - $new_creation = new ilRadioOption( - $this->lng->txt('sorting_creation_header'), - ilContainer::SORT_NEW_ITEMS_ORDER_CREATION - ); - - $order->addOption($new_creation); - } - - - if(in_array(ilContainer::SORT_ACTIVATION, $a_sorting_settings)) - { - //new items by activation - $new_activation = new ilRadioOption( - $this->lng->txt('crs_sort_activation'), - ilContainer::SORT_NEW_ITEMS_ORDER_ACTIVATION - ); - - $order->addOption($new_activation); - } - - $element->addSubItem($order); - - $this->initSortingDirectionForm($settings,$element,'manual'); - - return $element; - } - - /** - * Save sorting settings - * @param ilPropertyFormGUI $form - */ - protected function saveSortingSettings(ilPropertyFormGUI $form) - { - include_once('Services/Container/classes/class.ilContainerSortingSettings.php'); - $settings = new ilContainerSortingSettings($this->object->getId()); - $settings->setSortMode($form->getInput("sorting")); - - switch($form->getInput('sorting')) - { - case ilContainer::SORT_TITLE: - $settings->setSortDirection($form->getInput('title_sorting_direction')); - break; - case ilContainer::SORT_ACTIVATION: - $settings->setSortDirection($form->getInput('activation_sorting_direction')); - break; - case ilContainer::SORT_CREATION: - $settings->setSortDirection($form->getInput('creation_sorting_direction')); - break; - case ilContainer::SORT_MANUAL: - $settings->setSortNewItemsPosition($form->getInput('manual_new_items_position')); - $settings->setSortNewItemsOrder($form->getInput('manual_new_items_order')); - $settings->setSortDirection($form->getInput('manual_sorting_direction')); - break; - } - - $settings->update(); - } - - /** - * Show trash content of object - * - * @access public - */ - public function trashObject() - { - $tpl = $this->tpl; - - include_once("./Services/Repository/classes/class.ilRepUtilGUI.php"); - $ru = new ilRepUtilGUI($this); - $ru->showTrashTable($_GET["ref_id"]); - } - - /** - * remove objects from trash bin and all entries therefore every object needs a specific deleteObject() method - * - * @access public - */ - public function removeFromSystemObject() - { - $ilLog = $this->log; - $ilAppEventHandler = $this->app_event_handler; - $lng = $this->lng; - - include_once("./Services/Repository/classes/class.ilRepUtilGUI.php"); - $ru = new ilRepUtilGUI($this); - $ru->removeObjectsFromSystem($_POST["trash_id"]); - $this->ctrl->redirect($this, "trash"); - } - - /** - * Get objects back from trash - */ - public function undeleteObject() - { - include_once("./Services/Repository/classes/class.ilRepUtilGUI.php"); - $ru = new ilRepUtilGUI($this); - $ru->restoreObjects($_GET["ref_id"], $_POST["trash_id"]); - $this->ctrl->redirect($this, "trash"); - } - - /** - * confirmation screen remove from system - */ - public function confirmRemoveFromSystemObject() - { - $lng = $this->lng; - include_once("./Services/Repository/classes/class.ilRepUtilGUI.php"); - - if(!isset($_POST["trash_id"])) - { - ilUtil::sendFailure($lng->txt("no_checkbox"), true); - $this->ctrl->redirect($this, "trash"); - } - - $ru = new ilRepUtilGUI($this); - $ru->confirmRemoveFromSystemObject($_POST["trash_id"]); - } - - /** - * @param $cmd string - * @return ilTreeExplorerGUI - */ - protected function getTreeSelectorGUI($cmd) - { - include_once("./Services/Repository/classes/class.ilRepositorySelectorExplorerGUI.php"); - $exp = new ilRepositorySelectorExplorerGUI($this, "showPasteTree"); - // TODO: The study programme 'prg' is not included here, as the - // ilRepositorySelectorExplorerGUI only handles static rules for - // parent-child-relations and not the dynamic relationsships - // required for the SP (see #16909). - $exp->setTypeWhiteList(array("root", "cat", "grp", "crs", "fold")); - - // Not all types are allowed in the LearningSequence - // Extend whitelist, if all selected types are possible subojects of LSO - if(in_array($_SESSION["clipboard"]["cmd"], ["link", "cut"])) { - $lso_types = array_keys($this->obj_definition->getSubObjects('lso')); - $refs = $_SESSION["clipboard"]["ref_ids"]; - $allow_lso = true; - foreach ($refs as $item_ref_id) { - $type = ilObject::_lookupType($item_ref_id, true); - if (! in_array($type, $lso_types)) { - $allow_lso = false; - } - } - if ($allow_lso) { - $whitelist = $exp->getTypeWhiteList(); - $whitelist[] = 'lso'; - $exp->setTypeWhiteList($whitelist); - } - } - - if ($cmd == "link") { - $exp->setSelectMode("nodes", true); - return $exp; - } else { - $exp->setSelectMode("nodes[]", false); - return $exp; - } - } - - /** - * Set return point for side column actions - */ - function setSideColumnReturn() - { - $this->ctrl->setReturn($this, ""); - } + /** + * Copy object(s) out from a container and write the information to clipboard + * It is not possible to copy multiple objects at once. + * + * + * @access public + */ + public function copyObject() + { + $rbacsystem = $this->rbacsystem; + $ilCtrl = $this->ctrl; + $objDefinition = $this->obj_definition; + $ilErr = $this->error; + + $no_copy = []; + + if ($_GET["item_ref_id"] != "") { + $_POST["id"] = array($_GET["item_ref_id"]); + } + + if (!isset($_POST["id"])) { + $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); + } + + // FOR ALL OBJECTS THAT SHOULD BE COPIED + $containers = 0; + foreach ($_POST["id"] as $ref_id) { + // GET COMPLETE NODE_DATA OF ALL SUBTREE NODES + $node_data = $this->tree->getNodeData($ref_id); + + // count containers + if ($objDefinition->isContainer($node_data["type"])) { + $containers++; + } + + $subtree_nodes = $this->tree->getSubTree($node_data); + + $all_node_data[] = $node_data; + $all_subtree_nodes[] = $subtree_nodes; + + // CHECK COPY PERMISSION OF ALL OBJECTS IN ACTUAL SUBTREE + foreach ($subtree_nodes as $node) { + if ($node['type'] == 'rolf') { + continue; + } + + if (!$rbacsystem->checkAccess('visible,read,copy', $node["ref_id"])) { + $no_copy[] = $node["ref_id"]; + } + } + } + + if ($containers > 0 && count($_POST["id"]) > 1) { + $ilErr->raiseError($this->lng->txt("cntr_container_only_on_their_own"), $ilErr->MESSAGE); + } + + // IF THERE IS ANY OBJECT WITH NO PERMISSION TO 'delete' + if (is_array($no_copy) && count($no_copy)) { + $titles = array(); + foreach ((array) $no_copy as $copy_id) { + $titles[] = ilObject::_lookupTitle(ilObject::_lookupObjId($copy_id)); + } + $ilErr->raiseError( + $this->lng->txt("msg_no_perm_copy") . " " . implode(',', $titles), + $ilErr->MESSAGE + ); + } + + // if we have a single container, set it as source id and redirect to ilObjectCopyGUI + if (count($_POST["id"]) == 1) { + $ilCtrl->setParameterByClass("ilobjectcopygui", "source_id", $_POST["id"][0]); + $ilCtrl->redirectByClass("ilobjectcopygui", "initTargetSelection"); + } else { + $ilCtrl->setParameterByClass("ilobjectcopygui", "source_ids", implode($_POST["id"], "_")); + $ilCtrl->redirectByClass("ilobjectcopygui", "initTargetSelection"); + } + + $_SESSION["clipboard"]["parent"] = $_GET["ref_id"]; + $_SESSION["clipboard"]["cmd"] = $ilCtrl->getCmd(); + $_SESSION["clipboard"]["ref_ids"] = $_POST["id"]; + + ilUtil::sendInfo($this->lng->txt("msg_copy_clipboard"), true); + + return $this->initAndDisplayCopyIntoMultipleObjectsObject(); + } // END COPY + + public function downloadObject() + { + $rbacsystem = $this->rbacsystem; + $ilErr = $this->error; + + $no_download = []; + $no_perm = []; + + if ($_GET["item_ref_id"] != "") { + $_POST["id"] = array($_GET["item_ref_id"]); + } + + if (!isset($_POST["id"])) { + $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); + } + + // FOR ALL OBJECTS THAT SHOULD BE DOWNLOADED + foreach ($_POST["id"] as $ref_id) { + $object = ilObjectFactory::getInstanceByRefId($ref_id); + $obj_type = $object->getType(); + if (!in_array($obj_type, array("fold", "file"))) { + $no_download[] = $object->getType(); + } elseif (!$rbacsystem->checkAccess('read', $ref_id)) { + $no_perm[] = $ref_id; + } + } + + // IF THERE IS ANY OBJECT THAT CANNOT BE DOWNLOADED + if (count($no_download)) { + $no_download = array_unique($no_download); + foreach ($no_download as $type) { + $txt_objs[] = $this->lng->txt("objs_" . $type); + } + $ilErr->raiseError(implode(', ', $txt_objs) . " " . $this->lng->txt("msg_obj_no_download"), $ilErr->MESSAGE); + } + + // NO ACCESS + if (count($no_perm)) { + $ilErr->raiseError( + $this->lng->txt("msg_obj_perm_download") . " " . implode(',', $no_perm), + $ilErr->MESSAGE + ); + } + + // download the objects + $this->downloadMultipleObjects($_POST["id"]); + } + + private function downloadMultipleObjects($a_ref_ids) + { + $lng = $this->lng; + $rbacsystem = $this->rbacsystem; + $ilAccess = $this->access; + + include_once 'Modules/Folder/classes/class.ilObjFolder.php'; + include_once 'Modules/File/classes/class.ilObjFile.php'; + include_once 'Modules/File/classes/class.ilFileException.php'; + + // create temporary file to download + $zip = PATH_TO_ZIP; + $tmpdir = ilUtil::ilTempnam(); + ilUtil::makeDir($tmpdir); + + try { + // copy each selected object + foreach ($a_ref_ids as $ref_id) { + if (!$ilAccess->checkAccess("read", "", $ref_id)) { + continue; + } + + if (ilObject::_isInTrash($ref_id)) { + continue; + } + + // get object + $object = ilObjectFactory::getInstanceByRefId($ref_id); + $obj_type = $object->getType(); + if ($obj_type == "fold") { + // copy folder to temp directory + self::recurseFolder($ref_id, $object->getTitle(), $tmpdir); + } elseif ($obj_type == "file") { + // copy file to temp directory + self::copyFile($object->getId(), $object->getTitle(), $tmpdir); + } + } + + // compress the folder + $deliverFilename = ilUtil::getAsciiFilename($this->object->getTitle()) . ".zip"; + $tmpzipfile = ilUtil::ilTempnam() . ".zip"; + ilUtil::zip($tmpdir, $tmpzipfile, true); + ilUtil::delDir($tmpdir); + ilUtil::deliverFile($tmpzipfile, $deliverFilename, '', false, true, true); + } catch (ilFileException $e) { + ilUtil::sendInfo($e->getMessage(), true); + } + } + + /** + * private functions which iterates through all folders and files + * and create an according file structure in a temporary directory. This function works recursive. + * + * @param integer $refid reference it + * @param tmpdictory $tmpdir + * @return returns first created directory + */ + private static function recurseFolder($refid, $title, $tmpdir) + { + global $DIC; + + $rbacsystem = $DIC->rbac()->system(); + $tree = $DIC->repositoryTree(); + $ilAccess = $DIC->access(); + + $tmpdir = $tmpdir . DIRECTORY_SEPARATOR . ilUtil::getASCIIFilename($title); + ilUtil::makeDir($tmpdir); + + $subtree = $tree->getChildsByTypeFilter($refid, array("fold","file")); + + foreach ($subtree as $child) { + if (!$ilAccess->checkAccess("read", "", $child["ref_id"])) { + continue; + } + + if (ilObject::_isInTrash($child["ref_id"])) { + continue; + } + + if ($child["type"] == "fold") { + self::recurseFolder($child["ref_id"], $child["title"], $tmpdir); + } else { + self::copyFile($child["obj_id"], $child["title"], $tmpdir); + } + } + } + + private static function copyFile($obj_id, $title, $tmpdir) + { + $newFilename = $tmpdir . DIRECTORY_SEPARATOR . ilUtil::getASCIIFilename($title); + + // copy to temporary directory + $oldFilename = ilObjFile::_lookupAbsolutePath($obj_id); + + if (!copy($oldFilename, $newFilename)) { + throw new ilFileException("Could not copy " . $oldFilename . " to " . $newFilename); + } + + touch($newFilename, filectime($oldFilename)); + } + /** + * create an new reference of an object in tree + * it's like a hard link of unix + * + * @access public + */ + public function linkObject() + { + $rbacsystem = $this->rbacsystem; + $ilCtrl = $this->ctrl; + $ilErr = $this->error; + + $no_cut = []; + $no_link = []; + + if ($_GET["item_ref_id"] != "") { + $_POST["id"] = array($_GET["item_ref_id"]); + } + + if (!isset($_POST["id"])) { + $ilErr->raiseError($this->lng->txt("no_checkbox"), $ilErr->MESSAGE); + } + + // CHECK ACCESS + foreach ($_POST["id"] as $ref_id) { + if (!$rbacsystem->checkAccess('delete', $ref_id)) { + $no_cut[] = $ref_id; + } + + $object = ilObjectFactory::getInstanceByRefId($ref_id); + + if (!$this->objDefinition->allowLink($object->getType())) { + $no_link[] = $object->getType(); + } + } + + // NO ACCESS + if (count($no_cut)) { + $ilErr->raiseError($this->lng->txt("msg_no_perm_link") . " " . + implode(',', $no_cut), $ilErr->MESSAGE); + } + + if (count($no_link)) { + //#12203 + $ilErr->raiseError($this->lng->txt("msg_obj_no_link"), $ilErr->MESSAGE); + } + + // WRITE TO CLIPBOARD + $clipboard["parent"] = $_GET["ref_id"]; + $clipboard["cmd"] = $ilCtrl->getCmd(); + + foreach ($_POST["id"] as $ref_id) { + $clipboard["ref_ids"][] = $ref_id; + } + + $_SESSION["clipboard"] = $clipboard; + + $suffix = 'p'; + if (count($clipboard["ref_ids"]) == 1) { + $suffix = 's'; + } + ilUtil::sendInfo($this->lng->txt("msg_link_clipboard_" . $suffix), true); + + return $this->initAndDisplayLinkIntoMultipleObjectsObject(); + } // END LINK + + + /** + * clear clipboard and go back to last object + * + * @access public + */ + public function clearObject() + { + unset($_SESSION["clipboard"]); + unset($_SESSION["il_rep_clipboard"]); + + //var_dump($this->getReturnLocation("clear",$this->ctrl->getLinkTarget($this)),get_class($this)); + + // only redirect if clipboard was cleared + if (isset($_POST["cmd"]["clear"])) { + ilUtil::sendSuccess($this->lng->txt("msg_clear_clipboard"), true); + // fixed mantis 0018474: Clear Clipboard redirects to Subtab View, instead of Subtab "Edit Multiple" + $this->ctrl->redirect($this, 'render'); + } + } + + public function performPasteIntoMultipleObjectsObject() + { + $rbacsystem = $this->rbacsystem; + $rbacadmin = $this->rbacadmin; + $rbacreview = $this->rbacreview; + $ilLog = $this->log; + $tree = $this->tree; + $ilObjDataCache = $this->obj_data_cache; + $ilUser = $this->user; + $ilErr = $this->error; + $lng = $this->lng; + $ctrl = $this->ctrl; + $ui = $this->ui; + + $exists = []; + $is_child = []; + $not_allowed_subobject = []; + $no_paste = []; + + $command = $_SESSION['clipboard']['cmd']; + if (!in_array($command, array('cut', 'link', 'copy'))) { + $message = __METHOD__ . ": cmd was neither 'cut', 'link' nor 'copy'; may be a hack attempt!"; + $ilErr->raiseError($message, $ilErr->WARNING); + } + + if ($command == 'cut') { + if (isset($_POST['node']) && (int) $_POST['node']) { + $_POST['nodes'] = array($_POST['node']); + } + } + + if (!is_array($_POST['nodes']) || !count($_POST['nodes'])) { + ilUtil::sendFailure($this->lng->txt('select_at_least_one_object')); + switch ($command) { + case 'cut': + $this->showPasteTreeObject(); + break; + case 'copy': + $this->showPasteTreeObject(); + break; + case 'link': + $this->showPasteTreeObject(); + break; + } + return; + } + + // this loop does all checks + $folder_objects_cache = array(); + foreach ($_SESSION['clipboard']['ref_ids'] as $ref_id) { + $obj_data = ilObjectFactory::getInstanceByRefId($ref_id); + $current_parent_id = $tree->getParentId($obj_data->getRefId()); + + foreach ($_POST['nodes'] as $folder_ref_id) { + if (!array_key_exists($folder_ref_id, $folder_objects_cache)) { + $folder_objects_cache[$folder_ref_id] = ilObjectFactory::getInstanceByRefId($folder_ref_id); + } + + // CHECK ACCESS + if (!$rbacsystem->checkAccess('create', $folder_ref_id, $obj_data->getType())) { + $no_paste[] = sprintf($this->lng->txt('msg_no_perm_paste_object_in_folder'), $obj_data->getTitle() . ' [' . $obj_data->getRefId() . ']', $folder_objects_cache[$folder_ref_id]->getTitle() . ' [' . $folder_objects_cache[$folder_ref_id]->getRefId() . ']'); + } + + // CHECK IF REFERENCE ALREADY EXISTS + if ($folder_ref_id == $current_parent_id) { + $exists[] = sprintf($this->lng->txt('msg_obj_exists_in_folder'), $obj_data->getTitle() . ' [' . $obj_data->getRefId() . ']', $folder_objects_cache[$folder_ref_id]->getTitle() . ' [' . $folder_objects_cache[$folder_ref_id]->getRefId() . ']'); + } + + // CHECK IF PASTE OBJECT SHALL BE CHILD OF ITSELF + if ($tree->isGrandChild($ref_id, $folder_ref_id) || + $ref_id == $folder_ref_id) { + $is_child[] = sprintf($this->lng->txt('msg_paste_object_not_in_itself'), $obj_data->getTitle() . ' [' . $obj_data->getRefId() . ']'); + } + + // CHECK IF OBJECT IS ALLOWED TO CONTAIN PASTED OBJECT AS SUBOBJECT + if (!in_array($obj_data->getType(), array_keys($folder_objects_cache[$folder_ref_id]->getPossibleSubObjects()))) { + $not_allowed_subobject[] = sprintf( + $this->lng->txt('msg_obj_may_not_contain_objects_of_type'), + $folder_objects_cache[$folder_ref_id]->getTitle() . ' [' . $folder_objects_cache[$folder_ref_id]->getRefId() . ']', + $lng->txt('obj_' . $obj_data->getType()) + ); + } + } + } + + //////////////////////////// + // process checking results + if (count($exists) && $command != "copy") { + $error .= implode('
          ', $exists); + } + + if (count($is_child)) { + $error .= $error != '' ? '
          ' : ''; + $error .= implode('
          ', $is_child); + } + + if (count($not_allowed_subobject)) { + $error .= $error != '' ? '
          ' : ''; + $error .= implode('
          ', $not_allowed_subobject); + } + + if (count($no_paste)) { + $error .= $error != '' ? '
          ' : ''; + $error .= implode('
          ', $no_paste); + } + + if ($error != '') { + ilUtil::sendFailure($error); + switch ($command) { + case 'cut': + $this->showPasteTreeObject(); + break; + case 'copy': + $this->showPasteTreeObject(); + break; + case 'link': + $this->showPasteTreeObject(); + break; + } + return; + } + + // log pasteObject call + $ilLog->write(__METHOD__ . ", cmd: " . $command); + + //////////////////////////////////////////////////////// + // everything ok: now paste the objects to new location + + // to prevent multiple actions via back/reload button + $ref_ids = $_SESSION['clipboard']['ref_ids']; + unset($_SESSION['clipboard']['ref_ids']); + + // BEGIN ChangeEvent: Record paste event. + require_once('Services/Tracking/classes/class.ilChangeEvent.php'); + // END ChangeEvent: Record paste event. + + // process COPY command + if ($command == 'copy') { + foreach ($_POST['nodes'] as $folder_ref_id) { + foreach ($ref_ids as $ref_id) { + $revIdMapping = array(); + + $oldNode_data = $tree->getNodeData($ref_id); + if ($oldNode_data['parent'] == $folder_ref_id) { + require_once 'Modules/File/classes/class.ilObjFileAccess.php'; + $newTitle = ilObjFileAccess::_appendNumberOfCopyToFilename($oldNode_data['title'], null); + $newRef = $this->cloneNodes($ref_id, $folder_ref_id, $refIdMapping, $newTitle); + } else { + $newRef = $this->cloneNodes($ref_id, $folder_ref_id, $refIdMapping, null); + } + + // BEGIN ChangeEvent: Record copy event. + $old_parent_data = $tree->getParentNodeData($ref_id); + $newNode_data = $tree->getNodeData($newRef); + ilChangeEvent::_recordReadEvent( + $oldNode_data['type'], + $ref_id, + $oldNode_data['obj_id'], + $ilUser->getId() + ); + ilChangeEvent::_recordWriteEvent( + $newNode_data['obj_id'], + $ilUser->getId(), + 'add', + $ilObjDataCache->lookupObjId($folder_ref_id) + ); + ilChangeEvent::_catchupWriteEvents($newNode_data['obj_id'], $ilUser->getId()); + // END PATCH ChangeEvent: Record cut event. + } + } + + ilUtil::sendSuccess($this->lng->txt('msg_cloned'), true); + } // END COPY + + // process CUT command + if ($command == 'cut') { + foreach ($_POST['nodes'] as $folder_ref_id) { + foreach ($ref_ids as $ref_id) { + // Store old parent + $old_parent = $tree->getParentId($ref_id); + $tree->moveTree($ref_id, $folder_ref_id); + $rbacadmin->adjustMovedObjectPermissions($ref_id, $old_parent); + + include_once('./Services/Conditions/classes/class.ilConditionHandler.php'); + ilConditionHandler::_adjustMovedObjectConditions($ref_id); + + // BEGIN ChangeEvent: Record cut event. + $node_data = $tree->getNodeData($ref_id); + $old_parent_data = $tree->getNodeData($old_parent); + ilChangeEvent::_recordWriteEvent( + $node_data['obj_id'], + $ilUser->getId(), + 'remove', + $old_parent_data['obj_id'] + ); + ilChangeEvent::_recordWriteEvent( + $node_data['obj_id'], + $ilUser->getId(), + 'add', + $ilObjDataCache->lookupObjId($folder_ref_id) + ); + ilChangeEvent::_catchupWriteEvents($node_data['obj_id'], $ilUser->getId()); + // END PATCH ChangeEvent: Record cut event. + } + + // prevent multiple iterations for cut cmommand + break; + } + + ilUtil::sendSuccess($this->lng->txt('msg_cut_copied'), true); + } // END CUT + + // process LINK command + if ($command == 'link') { + $linked_to_folders = array(); + + include_once "Services/AccessControl/classes/class.ilRbacLog.php"; + $rbac_log_active = ilRbacLog::isActive(); + + foreach ($_POST['nodes'] as $folder_ref_id) { + $linked_to_folders[$folder_ref_id] = $ilObjDataCache->lookupTitle($ilObjDataCache->lookupObjId($folder_ref_id)); + + foreach ($ref_ids as $ref_id) { + // get node data + $top_node = $tree->getNodeData($ref_id); + + // get subnodes of top nodes + $subnodes[$ref_id] = $tree->getSubtree($top_node); + } + + // now move all subtrees to new location + foreach ($subnodes as $key => $subnode) { + // first paste top_node.... + $obj_data = ilObjectFactory::getInstanceByRefId($key); + $new_ref_id = $obj_data->createReference(); + $obj_data->putInTree($folder_ref_id); + $obj_data->setPermissions($folder_ref_id); + + // rbac log + if ($rbac_log_active) { + $rbac_log_roles = $rbacreview->getParentRoleIds($new_ref_id, false); + $rbac_log = ilRbacLog::gatherFaPa($new_ref_id, array_keys($rbac_log_roles), true); + ilRbacLog::add(ilRbacLog::LINK_OBJECT, $new_ref_id, $rbac_log, $key); + } + + // BEGIN ChangeEvent: Record link event. + $node_data = $tree->getNodeData($new_ref_id); + ilChangeEvent::_recordWriteEvent( + $node_data['obj_id'], + $ilUser->getId(), + 'add', + $ilObjDataCache->lookupObjId($folder_ref_id) + ); + ilChangeEvent::_catchupWriteEvents($node_data['obj_id'], $ilUser->getId()); + // END PATCH ChangeEvent: Record link event. + } + + $ilLog->write(__METHOD__ . ', link finished'); + } + + $linked_targets = array(); + $links = []; + if (count($linked_to_folders)) { + require_once 'Services/Link/classes/class.ilLink.php'; + foreach ($linked_to_folders as $ref_id => $title) { + $linked_targets[] = '' . $title . ''; + $links[] = $ui->factory()->link()->standard($title, ilLink::_getLink($ref_id)); + } + } + + $suffix = 'p'; + if (count($ref_ids) == 1) { + $suffix = 's'; + } + + $mbox = $ui->factory()->messageBox()->success($this->lng->txt('mgs_objects_linked_to_the_following_folders_' . $suffix)) + ->withLinks($links); + + ilUtil::sendSuccess($ui->renderer()->render($mbox), true); + } // END LINK + + // clear clipboard + $this->clearObject(); + + $this->ctrl->returnToParent($this); + } + + public function initAndDisplayLinkIntoMultipleObjectsObject() + { + $tree = $this->tree; + + // empty session on init + $_SESSION['paste_linked_repexpand'] = array(); + + // copy opend nodes from repository explorer + $_SESSION['paste_linked_repexpand'] = is_array($_SESSION['repexpand']) ? $_SESSION['repexpand'] : array(); + + // open current position + $path = $tree->getPathId((int) $_GET['ref_id']); + foreach ((array) $path as $node_id) { + if (!in_array($node_id, $_SESSION['paste_linked_repexpand'])) { + $_SESSION['paste_linked_repexpand'][] = $node_id; + } + } + + return $this->showPasteTreeObject(); + } + + /** + * Show paste tree + */ + public function showPasteTreeObject() + { + $ilTabs = $this->tabs; + $ilToolbar = $this->toolbar; + $ilErr = $this->error; + + $ilTabs->setTabActive('view_content'); + + if (!in_array($_SESSION['clipboard']['cmd'], array('link', 'copy', 'cut'))) { + $message = __METHOD__ . ": Unknown action."; + $ilErr->raiseError($message, $ilErr->WARNING); + } + $cmd = $_SESSION['clipboard']['cmd']; + + // + $exp = $this->getTreeSelectorGUI($cmd); + if ($exp->handleCommand()) { + return; + } + $output = $exp->getHTML(); + + $txt_var = ($cmd == "copy") + ? "copy" + : "paste"; + + // toolbars + $t = new ilToolbarGUI(); + $t->setFormAction($this->ctrl->getFormAction($this, "performPasteIntoMultipleObjects")); + + include_once("./Services/UIComponent/Button/classes/class.ilSubmitButton.php"); + $b = ilSubmitButton::getInstance(); + $b->setCaption($txt_var); + $b->setCommand("performPasteIntoMultipleObjects"); + + //$t->addFormButton($this->lng->txt($txt_var), "performPasteIntoMultipleObjects"); + $t->addStickyItem($b); + + $t->addSeparator(); + $this->lng->loadLanguageModule('obj'); + $t->addFormButton($this->lng->txt("obj_insert_into_clipboard"), "keepObjectsInClipboard"); + + $t->addFormButton($this->lng->txt("cancel"), "cancelMoveLink"); + $t->setCloseFormTag(false); + $t->setLeadingImage(ilUtil::getImagePath("arrow_upright.svg"), " "); + $output = $t->getHTML() . $output; + $t->setLeadingImage(ilUtil::getImagePath("arrow_downright.svg"), " "); + $t->setCloseFormTag(true); + $t->setOpenFormTag(false); + $output.= "
          " . $t->getHTML(); + + $this->tpl->setContent($output); + } + + + /** + * Cancel move|link + * empty clipboard and return to parent + */ + public function cancelMoveLinkObject() + { + $ilCtrl = $this->ctrl; + + unset($_SESSION['clipboard']); + $ilCtrl->returnToParent($this); + } + + /** + * Keep objects in the clipboard + */ + public function keepObjectsInClipboardObject() + { + $ilCtrl = $this->ctrl; + + ilUtil::sendSuccess($this->lng->txt("obj_inserted_clipboard"), true); + $ilCtrl->returnToParent($this); + } + + + public function initAndDisplayCopyIntoMultipleObjectsObject() + { + $tree = $this->tree; + + // empty session on init + $_SESSION['paste_copy_repexpand'] = array(); + + // copy opend nodes from repository explorer + $_SESSION['paste_copy_repexpand'] = is_array($_SESSION['repexpand']) ? $_SESSION['repexpand'] : array(); + + // open current position + $path = $tree->getPathId((int) $_GET['ref_id']); + foreach ((array) $path as $node_id) { + if (!in_array($node_id, $_SESSION['paste_copy_repexpand'])) { + $_SESSION['paste_copy_repexpand'][] = $node_id; + } + } + + return $this->showPasteTreeObject(); + } + + + public function initAndDisplayMoveIntoObjectObject() + { + $tree = $this->tree; + + // empty session on init + $_SESSION['paste_cut_repexpand'] = array(); + + // copy opend nodes from repository explorer + $_SESSION['paste_cut_repexpand'] = is_array($_SESSION['repexpand']) ? $_SESSION['repexpand'] : array(); + + // open current position + $path = $tree->getPathId((int) $_GET['ref_id']); + foreach ((array) $path as $node_id) { + if (!in_array($node_id, $_SESSION['paste_cut_repexpand'])) { + $_SESSION['paste_cut_repexpand'][] = $node_id; + } + } + + return $this->showPasteTreeObject(); + } + + + /** + * paste object from clipboard to current place + * Depending on the chosen command the object(s) are linked, copied or moved + * + * @access public + */ + public function pasteObject() + { + $rbacsystem = $this->rbacsystem; + $rbacadmin = $this->rbacadmin; + $ilLog = $this->log; + $tree = $this->tree; + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + $ilErr = $this->error; + + $exists = []; + $no_paste = []; + $is_child = []; + $not_allowed_subobject = []; + + // BEGIN ChangeEvent: Record paste event. + require_once('Services/Tracking/classes/class.ilChangeEvent.php'); + // END ChangeEvent: Record paste event. + + //var_dump($_SESSION["clipboard"]);exit; + if (!in_array($_SESSION["clipboard"]["cmd"], array("cut","link","copy"))) { + $message = get_class($this) . "::pasteObject(): cmd was neither 'cut','link' or 'copy'; may be a hack attempt!"; + $ilErr->raiseError($message, $ilErr->WARNING); + } + + // this loop does all checks + foreach ($_SESSION["clipboard"]["ref_ids"] as $ref_id) { + $obj_data = ilObjectFactory::getInstanceByRefId($ref_id); + + // CHECK ACCESS + if (!$rbacsystem->checkAccess('create', $this->object->getRefId(), $obj_data->getType())) { + $no_paste[] = $ref_id; + $no_paste_titles[] = $obj_data->getTitle(); + } + + // CHECK IF REFERENCE ALREADY EXISTS + if ($this->object->getRefId() == $this->tree->getParentId($obj_data->getRefId())) { + $exists[] = $ref_id; + break; + } + + // CHECK IF PASTE OBJECT SHALL BE CHILD OF ITSELF + if ($this->tree->isGrandChild($ref_id, $this->object->getRefId())) { + $is_child[] = ilObject::_lookupTitle(ilObject::_lookupObjId($ref_id)); + } + + if ($ref_id == $this->object->getRefId()) { + $is_child[] = ilObject::_lookupTitle(ilObject::_lookupObjId($ref_id)); + } + + // CHECK IF OBJECT IS ALLOWED TO CONTAIN PASTED OBJECT AS SUBOBJECT + $obj_type = $obj_data->getType(); + + if (!in_array($obj_type, array_keys($this->object->getPossibleSubObjects()))) { + $not_allowed_subobject[] = $obj_data->getType(); + } + } + + //////////////////////////// + // process checking results + // BEGIN WebDAV: Copying an object into the same container is allowed + if (count($exists) > 0 && $_SESSION["clipboard"]["cmd"] != "copy") { + // END WebDAV: Copying an object into the same container is allowed + $ilErr->raiseError($this->lng->txt("msg_obj_exists"), $ilErr->MESSAGE); + } + + if (count($is_child) > 0) { + $ilErr->raiseError( + $this->lng->txt("msg_not_in_itself") . " " . implode(',', $is_child), + $ilErr->MESSAGE + ); + } + + if (count($not_allowed_subobject) > 0) { + $ilErr->raiseError( + $this->lng->txt("msg_may_not_contain") . " " . implode(',', $not_allowed_subobject), + $ilErr->MESSAGE + ); + } + + if (count($no_paste) > 0) { + $ilErr->raiseError($this->lng->txt("msg_no_perm_paste") . " " . + implode(',', $no_paste), $ilErr->MESSAGE); + } + + // log pasteObject call + $ilLog->write("ilObjectGUI::pasteObject(), cmd: " . $_SESSION["clipboard"]["cmd"]); + + //////////////////////////////////////////////////////// + // everything ok: now paste the objects to new location + + // to prevent multiple actions via back/reload button + $ref_ids = $_SESSION["clipboard"]["ref_ids"]; + unset($_SESSION["clipboard"]["ref_ids"]); + + // BEGIN WebDAV: Support a copy command in the repository + // process COPY command + if ($_SESSION["clipboard"]["cmd"] == "copy") { + unset($_SESSION["clipboard"]["cmd"]); + + // new implementation, redirects to ilObjectCopyGUI + if (count($ref_ids) == 1) { + $ilCtrl->setParameterByClass("ilobjectcopygui", "target", $this->object->getRefId()); + $ilCtrl->setParameterByClass("ilobjectcopygui", "source_id", $ref_ids[0]); + $ilCtrl->redirectByClass("ilobjectcopygui", "saveTarget"); + } else { + $ilCtrl->setParameterByClass("ilobjectcopygui", "target", $this->object->getRefId()); + $ilCtrl->setParameterByClass("ilobjectcopygui", "source_ids", implode($ref_ids, "_")); + $ilCtrl->redirectByClass("ilobjectcopygui", "saveTarget"); + } + + + + /* old implementation + + foreach($ref_ids as $ref_id) + { + $revIdMapping = array(); + + $oldNode_data = $tree->getNodeData($ref_id); + if ($oldNode_data['parent'] == $this->object->getRefId()) + { + require_once 'Modules/File/classes/class.ilObjFileAccess.php'; + $newTitle = ilObjFileAccess::_appendNumberOfCopyToFilename($oldNode_data['title'],null); + $newRef = $this->cloneNodes($ref_id, $this->object->getRefId(), $refIdMapping, $newTitle); + } + else + { + $newRef = $this->cloneNodes($ref_id, $this->object->getRefId(), $refIdMapping, null); + } + + // BEGIN ChangeEvent: Record copy event. + $old_parent_data = $tree->getParentNodeData($ref_id); + $newNode_data = $tree->getNodeData($newRef); + ilChangeEvent::_recordReadEvent($oldNode_data['type'], $ref_id, + $oldNode_data['obj_id'], $ilUser->getId()); + ilChangeEvent::_recordWriteEvent($newNode_data['obj_id'], $ilUser->getId(), 'add', + $this->object->getId()); + ilChangeEvent::_catchupWriteEvents($newNode_data['obj_id'], $ilUser->getId()); + // END ChangeEvent: Record copy event. + }*/ + + $ilLog->write("ilObjectGUI::pasteObject(), copy finished"); + } + // END WebDAV: Support a Copy command in the repository + + // process CUT command + if ($_SESSION["clipboard"]["cmd"] == "cut") { + foreach ($ref_ids as $ref_id) { + // Store old parent + $old_parent = $tree->getParentId($ref_id); + $this->tree->moveTree($ref_id, $this->object->getRefId()); + $rbacadmin->adjustMovedObjectPermissions($ref_id, $old_parent); + + include_once('./Services/Conditions/classes/class.ilConditionHandler.php'); + ilConditionHandler::_adjustMovedObjectConditions($ref_id); + + // BEGIN ChangeEvent: Record cut event. + $node_data = $tree->getNodeData($ref_id); + $old_parent_data = $tree->getNodeData($old_parent); + ilChangeEvent::_recordWriteEvent( + $node_data['obj_id'], + $ilUser->getId(), + 'remove', + $old_parent_data['obj_id'] + ); + ilChangeEvent::_recordWriteEvent( + $node_data['obj_id'], + $ilUser->getId(), + 'add', + $this->object->getId() + ); + ilChangeEvent::_catchupWriteEvents($node_data['obj_id'], $ilUser->getId()); + // END PATCH ChangeEvent: Record cut event. + } + } // END CUT + + // process LINK command + if ($_SESSION["clipboard"]["cmd"] == "link") { + foreach ($ref_ids as $ref_id) { + // get node data + $top_node = $this->tree->getNodeData($ref_id); + + // get subnodes of top nodes + $subnodes[$ref_id] = $this->tree->getSubtree($top_node); + } + + // now move all subtrees to new location + foreach ($subnodes as $key => $subnode) { + // first paste top_node.... + $obj_data = ilObjectFactory::getInstanceByRefId($ref_id); + $new_ref_id = $obj_data->createReference(); + $obj_data->putInTree($_GET["ref_id"]); + $obj_data->setPermissions($_GET["ref_id"]); + + // BEGIN ChangeEvent: Record link event. + $node_data = $tree->getNodeData($new_ref_id); + ilChangeEvent::_recordWriteEvent( + $node_data['obj_id'], + $ilUser->getId(), + 'add', + $this->object->getId() + ); + ilChangeEvent::_catchupWriteEvents($node_data['obj_id'], $ilUser->getId()); + // END PATCH ChangeEvent: Record link event. + } + + $ilLog->write("ilObjectGUI::pasteObject(), link finished"); + } // END LINK + + // save cmd for correct message output after clearing the clipboard + $last_cmd = $_SESSION["clipboard"]["cmd"]; + + + // clear clipboard + $this->clearObject(); + + if ($last_cmd == "cut") { + ilUtil::sendSuccess($this->lng->txt("msg_cut_copied"), true); + } + // BEGIN WebDAV: Support a copy command in repository + elseif ($last_cmd == "copy") { + ilUtil::sendSuccess($this->lng->txt("msg_cloned"), true); + } elseif ($last_cmd == 'link') { + // END WebDAV: Support copy command in repository + ilUtil::sendSuccess($this->lng->txt("msg_linked"), true); + } + + $this->ctrl->returnToParent($this); + } // END PASTE + + + /** + * show clipboard + */ + public function clipboardObject() + { + $ilErr = $this->error; + $ilLog = $this->log; + $ilTabs = $this->tabs; + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $ilTabs->activateTab("clipboard"); + + // function should not be called if clipboard is empty + if (empty($_SESSION['clipboard']) or !is_array($_SESSION['clipboard'])) { + $message = sprintf('%s::clipboardObject(): Illegal access. Clipboard variable is empty!', get_class($this)); + $ilLog->write($message, $ilLog->FATAL); + $ilErr->raiseError($this->lng->txt("permission_denied"), $ilErr->WARNING); + } + + $data = array(); + foreach ($_SESSION["clipboard"]["ref_ids"] as $ref_id) { + if (!$tmp_obj = ilObjectFactory::getInstanceByRefId($ref_id, false)) { + continue; + } + + $data[] = array( + "type" => $tmp_obj->getType(), + "type_txt" => $this->lng->txt("obj_" . $tmp_obj->getType()), + "title" => $tmp_obj->getTitle(), + "cmd" => ($_SESSION["clipboard"]["cmd"] == "cut") ? $this->lng->txt("move") :$this->lng->txt($_SESSION["clipboard"]["cmd"]), + "ref_id" => $ref_id, + "obj_id" => $tmp_obj->getId() + ); + + unset($tmp_obj); + } + + include_once("./Services/Object/classes/class.ilObjClipboardTableGUI.php"); + $tab = new ilObjClipboardTableGUI($this, "clipboard"); + $tab->setData($data); + $tpl->setContent($tab->getHTML()); + + if (count($data) > 0) { + $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); + $ilToolbar->addFormButton( + $lng->txt("insert_object_here"), + "paste" + ); + $ilToolbar->addFormButton( + $lng->txt("clear_clipboard"), + "clear" + ); + } + + return true; + } + + public function isActiveAdministrationPanel() + { + $ilAccess = $this->access; + + // #10081 + if ($_SESSION["il_cont_admin_panel"] && + $this->object->getRefId() && + !$ilAccess->checkAccess("write", "", $this->object->getRefId())) { + return false; + } + + return $_SESSION["il_cont_admin_panel"]; + } + + /** + * May be overwritten in subclasses. + */ + public function setColumnSettings(ilColumnGUI $column_gui) + { + $ilAccess = $this->access; + parent::setColumnSettings($column_gui); + + if ($ilAccess->checkAccess("write", "", $this->object->getRefId()) && + $this->isActiveAdministrationPanel() && + $this->allowBlocksMoving()) { + $column_gui->setEnableMovement(true); + } + + $column_gui->setRepositoryItems( + $this->object->getSubItems($this->isActiveAdministrationPanel(), true) + ); + + //if ($ilAccess->checkAccess("write", "", $this->object->getRefId()) + // && $this->allowBlocksConfigure()) + if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) { + $column_gui->setBlockProperty("news", "settings", true); + //$column_gui->setBlockProperty("news", "public_notifications_option", true); + $column_gui->setBlockProperty("news", "default_visibility_option", true); + $column_gui->setBlockProperty("news", "hide_news_block_option", true); + } + + if ($this->isActiveAdministrationPanel()) { + $column_gui->setAdminCommands(true); + } + } + + /** + * Standard is to allow blocks moving + */ + public function allowBlocksMoving() + { + return true; + } + + /** + * Standard is to allow blocks configuration + */ + public function allowBlocksConfigure() + { + return true; + } + + /** + * + * + * @access public + * @param + * + */ + public function cloneWizardPageTreeObject() + { + $this->cloneWizardPageObject(true); + } + + /** + * + * + * @access public + * @param + * + */ + public function cloneWizardPageListObject() + { + $this->cloneWizardPageObject(false); + } + + /** + * Show clone wizard page for container objects + * + * @access public + * + */ + public function cloneWizardPageObject($a_tree_view = true) + { + include_once('Services/CopyWizard/classes/class.ilCopyWizardPageFactory.php'); + + $ilObjDataCache = $this->obj_data_cache; + $tree = $this->tree; + + if (!$_REQUEST['clone_source']) { + ilUtil::sendFailure($this->lng->txt('select_one')); + if (isset($_SESSION['wizard_search_title'])) { + $this->searchCloneSourceObject(); + } else { + $this->createObject(); + } + return false; + } + $source_id = $_REQUEST['clone_source']; + $new_type = $_REQUEST['new_type']; + $this->ctrl->setParameter($this, 'clone_source', (int) $_REQUEST['clone_source']); + $this->ctrl->setParameter($this, 'new_type', $new_type); + + + // Generell JavaScript + $this->tpl->addJavaScript('./Services/CopyWizard/js/ilContainer.js'); + $this->tpl->setVariable('BODY_ATTRIBUTES', 'onload="ilDisableChilds(\'cmd\');"'); + + + $this->tpl->addBlockFile( + 'ADM_CONTENT', + 'adm_content', + 'tpl.container_wizard_page.html', + "Services/Container" + ); + $this->tpl->setVariable('FORMACTION', $this->ctrl->getFormAction($this)); + $this->tpl->setVariable('TYPE_IMG', ilUtil::getImagePath('icon_' . $new_type . '.svg')); + $this->tpl->setVariable('ALT_IMG', $this->lng->txt('obj_' . $new_type)); + $this->tpl->setVariable('TXT_DUPLICATE', $this->lng->txt($new_type . '_wizard_page')); + $this->tpl->setVariable('INFO_DUPLICATE', $this->lng->txt($new_type . '_copy_threads_info')); + $this->tpl->setVariable('BTN_COPY', $this->lng->txt('obj_' . $new_type . '_duplicate')); + $this->tpl->setVariable('BTN_BACK', $this->lng->txt('btn_back')); + if (isset($_SESSION['wizard_search_title'])) { + $this->tpl->setVariable('CMD_BACK', 'searchCloneSource'); + } else { + $this->tpl->setVariable('CMD_BACK', 'create'); + } + + $this->tpl->setVariable('BTN_TREE', $this->lng->txt('treeview')); + $this->tpl->setVariable('BTN_LIST', $this->lng->txt('flatview')); + + // Fill item rows + // tree view + if ($a_tree_view) { + $first = true; + $has_items = false; + foreach ($subnodes = $tree->getSubtree($source_node = $tree->getNodeData($source_id), true) as $node) { + if ($first == true) { + $first = false; + continue; + } + + if ($node['type'] == 'rolf') { + continue; + } + + $has_items = true; + + for ($i = $source_node['depth'];$i < $node['depth']; $i++) { + $this->tpl->touchBlock('padding'); + $this->tpl->touchBlock('end_padding'); + } + // fill options + $copy_wizard_page = ilCopyWizardPageFactory::_getInstanceByType($source_id, $node['type']); + $copy_wizard_page->fillTreeSelection($node['ref_id'], $node['type'], $node['depth']); + + $this->tpl->setCurrentBlock('tree_row'); + $this->tpl->setVariable('TREE_IMG', ilUtil::getImagePath('icon_' . $node['type'] . '.svg')); + $this->tpl->setVariable('TREE_ALT_IMG', $this->lng->txt('obj_' . $node['type'])); + $this->tpl->setVariable('TREE_TITLE', $node['title']); + $this->tpl->parseCurrentBlock(); + } + if (!$has_items) { + $this->tpl->setCurrentBlock('no_content'); + $this->tpl->setVariable('TXT_NO_CONTENT', $this->lng->txt('container_no_items')); + $this->tpl->parseCurrentBlock(); + } else { + $this->tpl->setCurrentBlock('tree_footer'); + $this->tpl->setVariable('TXT_COPY_ALL', $this->lng->txt('copy_all')); + $this->tpl->setVariable('TXT_LINK_ALL', $this->lng->txt('link_all')); + $this->tpl->setVariable('TXT_OMIT_ALL', $this->lng->txt('omit_all')); + $this->tpl->parseCurrentBlock(); + } + } else { + foreach ($tree->getSubTreeTypes($source_id, array('rolf','crs')) as $type) { + $copy_wizard_page = ilCopyWizardPageFactory::_getInstanceByType($source_id, $type); + if (strlen($html = $copy_wizard_page->getWizardPageBlockHTML())) { + $this->tpl->setCurrentBlock('obj_row'); + $this->tpl->setVariable('ITEM_BLOCK', $html); + $this->tpl->parseCurrentBlock(); + } + } + } + } + + /** + * Clone all object + * Overwritten method for copying container objects + * + * @access public + * + */ + public function cloneAllObject() + { + $ilLog = $this->log; + $ilCtrl = $this->ctrl; + + include_once('./Services/Link/classes/class.ilLink.php'); + include_once('Services/CopyWizard/classes/class.ilCopyWizardOptions.php'); + + $ilAccess = $this->access; + $ilErr = $this->error; + $rbacsystem = $this->rbacsystem; + $tree = $this->tree; + $ilUser = $this->user; + + $new_type = $_REQUEST['new_type']; + $ref_id = (int) $_GET['ref_id']; + $clone_source = (int) $_REQUEST['clone_source']; + + if (!$rbacsystem->checkAccess('create', $ref_id, $new_type)) { + $ilErr->raiseError($this->lng->txt('permission_denied')); + } + if (!$clone_source) { + ilUtil::sendFailure($this->lng->txt('select_one')); + $this->createObject(); + return false; + } + if (!$ilAccess->checkAccess('write', '', $clone_source, $new_type)) { + $ilErr->raiseError($this->lng->txt('permission_denied')); + } + + $options = $_POST['cp_options'] ? $_POST['cp_options'] : array(); + $orig = ilObjectFactory::getInstanceByRefId($clone_source); + $result = $orig->cloneAllObject($_COOKIE[session_name()], $_COOKIE['ilClientId'], $new_type, $ref_id, $clone_source, $options); + + include_once './Services/CopyWizard/classes/class.ilCopyWizardOptions.php'; + if (ilCopyWizardOptions::_isFinished($result['copy_id'])) { + ilUtil::sendSuccess($this->lng->txt("object_duplicated"), true); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $result['ref_id']); + $ilCtrl->redirectByClass("ilrepositorygui", ""); + } else { + ilUtil::sendInfo($this->lng->txt("object_copy_in_progress"), true); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $ref_id); + $ilCtrl->redirectByClass("ilrepositorygui", ""); + } + } + + + /** + * Save Sorting + * + * @access public + * @param + * + */ + public function saveSortingObject() + { + include_once('Services/Container/classes/class.ilContainerSorting.php'); + $sorting = ilContainerSorting::_getInstance($this->object->getId()); + + // Allow comma + $positions = str_replace(',', '.', $_POST['position']); + + $sorting->savePost($positions); + ilUtil::sendSuccess($this->lng->txt('cntr_saved_sorting'), true); + $this->ctrl->redirect($this, "editOrder"); + } + + // BEGIN WebDAV: Support a copy command in the repository + /** + * Recursively clones all nodes of the RBAC tree. + * + * @access private + * @param integer ref_id of source object + * @param integer ref_id of destination object + * @param array mapping new_ref_id => old_ref_id + * @param string the new name of the copy (optional). + * @return The ref_id pointing to the cloned object. + */ + public function cloneNodes($srcRef, $dstRef, &$mapping, $newName=null) + { + $tree = $this->tree; + + // clone the source node + $srcObj = ilObjectFactory::getInstanceByRefId($srcRef); + error_log(__METHOD__ . ' cloning srcRef=' . $srcRef . ' dstRef=' . $dstRef . '...'); + $newRef = $srcObj->cloneObject($dstRef)->getRefId(); + error_log(__METHOD__ . ' ...cloning... newRef=' . $newRef . '...'); + + // We must immediately apply a new name to the object, to + // prevent confusion of WebDAV clients about having two objects with identical + // name in the repository. + if (!is_null($newName)) { + $newObj = ilObjectFactory::getInstanceByRefId($newRef); + $newObj->setTitle($newName); + $newObj->update(); + unset($newObj); + } + unset($srcObj); + $mapping[$newRef] = $srcRef; + + // clone all children of the source node + $children = $tree->getChilds($srcRef); + foreach ($tree->getChilds($srcRef) as $child) { + // Don't clone role folders, because it does not make sense to clone local roles + // FIXME - Maybe it does make sense (?) + if ($child["type"] != 'rolf') { + $this->cloneNodes($child["ref_id"], $newRef, $mapping); + } else { + if (count($rolf = $tree->getChildsByType($newRef, "rolf"))) { + $mapping[$rolf[0]["ref_id"]] = $child["ref_id"]; + } + } + } + error_log(__METHOD__ . ' ...cloned srcRef=' . $srcRef . ' dstRef=' . $dstRef . ' newRef=' . $newRef); + return $newRef; + } + // END PATCH WebDAV: Support a copy command in the repository + + /** + * Modify list gui for presentation in container + * @param type $a_item_list_gui + * @param type $a_item_data + * @param type $a_show_path + */ + public function modifyItemGUI($a_item_list_gui, $a_item_data, $a_show_path) + { + $lng = $this->lng; + + if ($a_show_path) { + $a_item_list_gui->addCustomProperty( + $lng->txt('path'), + ilContainer::buildPath($a_item_data['ref_id'], $this->object->getRefId()), + false, + true + ); + } + } + + /** + * build path + */ + public static function _buildPath($a_ref_id, $a_course_ref_id) + { + global $DIC; + + $tree = $DIC->repositoryTree(); + + $path_arr = $tree->getPathFull($a_ref_id, $a_course_ref_id); + $counter = 0; + foreach ($path_arr as $data) { + if ($counter++) { + $path .= " > "; + } + $path .= $data['title']; + } + + return $path; + } + + // + // Style editing + // + + /** + * Edit style properties + */ + public function editStylePropertiesObject() + { + $ilTabs = $this->tabs; + $tpl = $this->tpl; + + $this->checkPermission("write"); + + $this->initStylePropertiesForm(); + $tpl->setContent($this->form->getHTML()); + + $ilTabs->activateTab("obj_sty"); + } + + /** + * Init style properties form + */ + public function initStylePropertiesForm() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilTabs = $this->tabs; + $ilSetting = $this->settings; + $tpl = $this->tpl; + + $tpl->setTreeFlatIcon("", ""); + $ilTabs->clearTargets(); + $xpage_id = ilContainer::_lookupContainerSetting( + $this->object->getId(), + "xhtml_page" + ); + if ($xpage_id > 0) { + $ilTabs->setBackTarget( + $lng->txt("cntr_back_to_old_editor"), + $ilCtrl->getLinkTarget($this, "switchToOldEditor"), + "_top" + ); + } else { + $ilTabs->setBackTarget($lng->txt("back"), "./goto.php?target=" . $this->object->getType() . "_" . + $this->object->getRefId(), "_top"); + } + + include_once("./Services/Container/classes/class.ilContainerPageGUI.php"); + $page_gui = new ilContainerPageGUI($this->object->getId()); + $style_id = $this->object->getStyleSheetId(); + if (ilObject::_lookupType($style_id) == "sty") { + $page_gui->setStyleId($style_id); + } else { + $style_id = 0; + } + $page_gui->setTabHook($this, "addPageTabs"); + $ilCtrl->getHTML($page_gui); + $ilTabs->setTabActive("obj_sty"); + + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $lng->loadLanguageModule("style"); + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + $fixed_style = $ilSetting->get("fixed_content_style_id"); + // $style_id = $this->object->getStyleSheetId(); + + if ($fixed_style > 0) { + $st = new ilNonEditableValueGUI($lng->txt("wiki_current_style")); + $st->setValue(ilObject::_lookupTitle($fixed_style) . " (" . + $this->lng->txt("global_fixed") . ")"); + $this->form->addItem($st); + } else { + $st_styles = ilObjStyleSheet::_getStandardStyles( + true, + false, + $_GET["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($lng->txt("style_current_style")); + $st->setValue(ilObject::_lookupTitle($style_id)); + $this->form->addItem($st); + + //$this->ctrl->getLinkTargetByClass("ilObjStyleSheetGUI", "edit")); + + // delete command + $this->form->addCommandButton( + "editStyle", + $lng->txt("style_edit_style") + ); + $this->form->addCommandButton( + "deleteStyle", + $lng->txt("style_delete_style") + ); + //$this->ctrl->getLinkTargetByClass("ilObjStyleSheetGUI", "delete")); + } + } + + if ($style_id <= 0 || ilObjStyleSheet::_lookupStandard($style_id)) { + $style_sel = ilUtil::formSelect( + $style_id, + "style_id", + $st_styles, + false, + true + ); + $style_sel = new ilSelectInputGUI($lng->txt("style_current_style"), "style_id"); + $style_sel->setOptions($st_styles); + $style_sel->setValue($style_id); + $this->form->addItem($style_sel); + //$this->ctrl->getLinkTargetByClass("ilObjStyleSheetGUI", "create")); + $this->form->addCommandButton( + "saveStyleSettings", + $lng->txt("save") + ); + $this->form->addCommandButton( + "createStyle", + $lng->txt("sty_create_ind_style") + ); + } + } + $this->form->setTitle($lng->txt("obj_sty")); + $this->form->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * Create Style + */ + public function createStyleObject() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirectByClass("ilobjstylesheetgui", "create"); + } + + /** + * Edit Style + */ + public function editStyleObject() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirectByClass("ilobjstylesheetgui", "edit"); + } + + /** + * Delete Style + */ + public function deleteStyleObject() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirectByClass("ilobjstylesheetgui", "delete"); + } + + /** + * Save style settings + */ + public function saveStyleSettingsObject() + { + $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(ilUtil::stripSlashes($_POST["style_id"])); + $this->object->update(); + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + } + $this->ctrl->redirect($this, "editStyleProperties"); + } + + /** + * Get item list command drop down asynchronously + */ + public function getAsynchItemListObject() + { + $ilCtrl = $this->ctrl; + + $ref_id = $_GET["cmdrefid"]; + $obj_id = ilObject::_lookupObjId($ref_id); + $type = ilObject::_lookupType($obj_id); + + // this should be done via container-object->getSubItem in the future + $data = array("child" => $ref_id, "ref_id" => $ref_id, "obj_id" => $obj_id, + "type" => $type); + include_once 'Services/Object/classes/class.ilObjectListGUIFactory.php'; + $item_list_gui = ilObjectListGUIFactory::_getListGUIByType($type); + $item_list_gui->setContainerObject($this); + + $item_list_gui->enableComments(true); + $item_list_gui->enableNotes(true); + $item_list_gui->enableTags(true); + + $this->modifyItemGUI($item_list_gui, $data, false); + $html = $item_list_gui->getListItemHTML( + $ref_id, + $obj_id, + "", + "", + true, + true + ); + + // include plugin slot for async item list + $ilPluginAdmin = $this->plugin_admin; + $pl_names = $ilPluginAdmin->getActivePluginsForSlot(IL_COMP_SERVICE, "UIComponent", "uihk"); + foreach ($pl_names as $pl) { + $ui_plugin = ilPluginAdmin::getPluginObject(IL_COMP_SERVICE, "UIComponent", "uihk", $pl); + $gui_class = $ui_plugin->getUIClassInstance(); + $resp = $gui_class->getHTML("Services/Container", "async_item_list", array("html" => $html)); + if ($resp["mode"] != ilUIHookPluginGUI::KEEP) { + $html = $gui_class->modifyHTML($html, $resp); + } + } + + echo $html; + exit; + } + + /** + * Show webdav password instruction + * @return + */ + protected function showPasswordInstructionObject($a_init = true) + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + + if ($a_init) { + ilUtil::sendInfo($this->lng->txt('webdav_pwd_instruction')); + $this->initFormPasswordInstruction(); + } + + include_once('Services/WebDAV/classes/class.ilWebDAVUtil.php'); + $dav_util = ilWebDAVUtil::getInstance(); + $ilToolbar->addButton( + $this->lng->txt('mount_webfolder'), + $dav_util->getMountURI($this->object->getRefId()), + '_blank', + '', + $dav_util->getFolderURI($this->object->getRefId()) + ); + + + $tpl->setContent($this->form->getHTML()); + } + + /** + * Init password form + * @return + */ + protected function initFormPasswordInstruction() + { + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + $this->form->setFormAction($this->ctrl->getFormAction($this)); + + // new password + $ipass = new ilPasswordInputGUI($this->lng->txt("desired_password"), "new_password"); + $ipass->setRequired(true); + + $this->form->addItem($ipass); + $this->form->addCommandButton("savePassword", $this->lng->txt("save")); + $this->form->addCommandButton('cancel', $this->lng->txt('cancel')); + + $this->form->setTitle($this->lng->txt("chg_ilias_and_webfolder_password")); + $this->form->setFormAction($this->ctrl->getFormAction($this)); + + return $this->form; + } + + /** + * Save password + * @return + */ + protected function savePasswordObject() + { + $ilUser = $this->user; + + $form = $this->initFormPasswordInstruction(); + if ($form->checkInput()) { + $ilUser->resetPassword($this->form->getInput('new_password'), $this->form->getInput('new_password')); + ilUtil::sendSuccess($this->lng->txt('webdav_pwd_instruction_success'), true); + $this->showPasswordInstructionObject(false); + return true; + } + $form->setValuesByPost(); + $this->showPasswordInstructionObject(); + } + + /** + * Redraw a list item (ajax) + * + * @param + * @return + */ + public function redrawListItemObject() + { + $tpl = $this->tpl; + + $html = null; + + $item_data = $this->object->getSubItems(false, false, (int) $_GET["child_ref_id"]); + $container_view = $this->getContentGUI(); + + // list item is session material (not part of "_all"-items - see below) + include_once './Modules/Session/classes/class.ilEventItems.php'; + $event_items = ilEventItems::_getItemsOfContainer($this->object->getRefId()); + if (in_array((int) $_GET["child_ref_id"], $event_items)) { + include_once('./Services/Object/classes/class.ilObjectActivation.php'); + foreach ($this->object->items["sess"] as $id) { + $items = ilObjectActivation::getItemsByEvent($id['obj_id']); + foreach ($items as $event_item) { + if ($event_item["child"] == (int) $_GET["child_ref_id"]) { + // sessions + if ((int) $_GET["parent_ref_id"]) { + $event_item["parent"] = (int) $_GET["parent_ref_id"]; + } + $html = $container_view->renderItem($event_item); + } + } + } + } + + // "normal" list item + if (!$html) { + foreach ($this->object->items["_all"] as $id) { + if ($id["child"] == (int) $_GET["child_ref_id"]) { + $html = $container_view->renderItem($id); + } + } + } + + if ($html) { + echo $html; + + // we need to add onload code manually (rating, comments, etc.) + echo $tpl->getOnLoadCodeForAsynch(); + } + + exit; + } + + // begin-patch fm + /** + * Add file manager link + * @param $a_sub_type + * @param $a_sub_id + * + */ + protected function initHeaderAction($a_sub_type = null, $a_sub_id = null) + { + $lg = parent::initHeaderAction($a_sub_type, $a_sub_id); + + // begin-patch fm + include_once './Services/WebServices/FileManager/classes/class.ilFMSettings.php'; + if (ilFMSettings::getInstance()->isEnabled()) { + if ($lg instanceof ilObjectListGUI) { + $lg->addCustomCommand($this->ctrl->getLinkTarget($this, 'fileManagerLaunch'), 'fm_start', '_blank'); + } + } + // end-patch fm + return $lg; + } + + /** + * Launch jnlp + */ + protected function fileManagerLaunchObject() + { + $ilUser = $this->user; + + $tpl = new ilTemplate('tpl.fm_launch_ws.html', false, false, 'Services/WebServices/FileManager'); + $tpl->setVariable('JNLP_URL', ILIAS_HTTP_PATH . '/Services/WebServices/FileManager/lib/dist/FileManager.jnlp'); + $tpl->setVariable('SESSION_ID', $_COOKIE[session_name()] . '::' . CLIENT_ID); + $tpl->setVariable('UID', $ilUser->getId()); + $tpl->setVariable('REF_ID', $this->object->getRefId()); + $tpl->setVariable('WSDL_URI', ILIAS_HTTP_PATH . '/webservice/soap/server.php?wsdl'); + $tpl->setVariable('LOCAL_FRAME', ilFMSettings::getInstance()->isLocalFSEnabled() ? 1 : 0); + $tpl->setVariable('REST_URI', ILIAS_HTTP_PATH . '/Services/WebServices/Rest/server.php'); + $tpl->setVariable('FILE_LOCKS', 0); + $tpl->setVariable('UPLOAD_FILESIZE', ilFMSettings::getInstance()->getMaxFileSize()); + + include_once("./Modules/SystemFolder/classes/class.ilObjSystemFolder.php"); + $header_top_title = ilObjSystemFolder::_getHeaderTitle(); + $tpl->setVariable('HEADER_TITLE', $header_top_title ? $header_top_title : ''); + echo $tpl->get(); + exit; + } + // begin-patch fm + + /** + * Show tree + */ + public function showRepTree() + { + $tpl = $this->tpl; + $ilUser = $this->user; + $ilSetting = $this->settings; + $ilCtrl = $this->ctrl; + + // set current repository view mode + if (!empty($_GET["set_mode"])) { + $_SESSION["il_rep_mode"] = $_GET["set_mode"]; + if ($ilUser->getId() != ANONYMOUS_USER_ID) { + $ilUser->writePref("il_rep_mode", $_GET["set_mode"]); + } + } + + // get user setting + if ($_SESSION["il_rep_mode"] == "") { + if ($ilUser->getId() != ANONYMOUS_USER_ID) { + $_SESSION["il_rep_mode"] = $ilUser->getPref("il_rep_mode"); + } + } + + // if nothing set, get default view + if ($_SESSION["il_rep_mode"] == "") { + $_SESSION["il_rep_mode"] = $ilSetting->get("default_repository_view"); + } + + $mode = ($_SESSION["il_rep_mode"] != "") + ? $_SESSION["il_rep_mode"] + : "flat"; + + // check for administration context, see #0016312 + if ($mode == "tree" && (strtolower($_GET["baseClass"]) != "iladministrationgui")) { + include_once("./Services/Repository/classes/class.ilRepositoryExplorerGUI.php"); + $exp = new ilRepositoryExplorerGUI($this, "showRepTree"); + if (method_exists($this, 'getAdditionalWhitelistTypes')) { + $whitelist = array_merge( + $exp->getTypeWhiteList(), + $this->getAdditionalWhitelistTypes() + ); + $exp->setTypeWhiteList($whitelist); + } + + if (!$exp->handleCommand()) { + $tpl->setLeftNavContent($exp->getHTML()); + } + } + } + + /** + * Init object edit form + * + * @return ilPropertyFormGUI + */ + protected function initEditForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $lng->loadLanguageModule($this->object->getType()); + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this, "update")); + $form->setTitle($this->lng->txt($this->object->getType() . "_edit")); + + $this->initFormTitleDescription($form); + + $this->initEditCustomForm($form); + + $form->addCommandButton("update", $this->lng->txt("save")); + //$this->form->addCommandButton("cancelUpdate", $lng->txt("cancel")); + + return $form; + } + + /** + * Init title/description for edit form + * @param ilPropertyFormGUI $form + */ + public function initFormTitleDescription(ilPropertyFormGUI $form) + { + /** @var ilObjectTranslation $trans */ + if (is_object($this->object)) { // note: this form can also be used for new groups (create group via awareness tool) + $trans = $this->object->getObjectTranslation(); + } + + $title = new ilTextInputGUI($this->lng->txt("title"), "title"); + $title->setRequired(true); + $title->setSize(min(40, ilObject::TITLE_LENGTH)); + $title->setMaxLength(ilObject::TITLE_LENGTH); + if (is_object($trans)) { + $title->setValue($trans->getDefaultTitle()); + } + $form->addItem($title); + + if (is_object($trans) && sizeof($trans->getLanguages()) > 1) { + include_once('Services/MetaData/classes/class.ilMDLanguageItem.php'); + $languages = ilMDLanguageItem::_getLanguages(); + $title->setInfo($this->lng->txt("language") . ": " . $languages[$trans->getDefaultLanguage()] . + ' » ' . $this->lng->txt("obj_more_translations") . ''); + + unset($languages); + } + + $desc = new ilTextAreaInputGUI($this->lng->txt("description"), "desc"); + $desc->setRows(2); + $desc->setCols(40); + if (is_object($trans)) { + $desc->setValue($trans->getDefaultDescription()); + } + $form->addItem($desc); + } + + + /** + * Append sorting settings to property form + * @param ilPropertyFormGUI $form + * @param type $a_sorting_settings + */ + protected function initSortingForm(ilPropertyFormGUI $form, array $a_sorting_settings) + { + include_once('Services/Container/classes/class.ilContainerSortingSettings.php'); + include_once './Services/Container/classes/class.ilContainer.php'; + + $settings = new ilContainerSortingSettings($this->object->getId()); + $sort = new ilRadioGroupInputGUI($this->lng->txt('sorting_header'), "sorting"); + + if (in_array(ilContainer::SORT_INHERIT, $a_sorting_settings)) { + $sort_inherit = new ilRadioOption(); + $sort_inherit->setTitle( + $this->lng->txt('sort_inherit_prefix') . + ' (' . ilContainerSortingSettings::sortModeToString( + ilContainerSortingSettings::lookupSortModeFromParentContainer( + $this->object->getId() + ) + ) . ') ' + ); + $sort_inherit->setValue(ilContainer::SORT_INHERIT); + $sort_inherit->setInfo($this->lng->txt('sorting_info_inherit')); + $sort->addOption($sort_inherit); + } + if (in_array(ilContainer::SORT_TITLE, $a_sorting_settings)) { + $sort_title = new ilRadioOption( + $this->lng->txt('sorting_title_header'), + ilContainer::SORT_TITLE + ); + $sort_title->setInfo($this->lng->txt('sorting_info_title')); + + $this->initSortingDirectionForm($settings, $sort_title, 'title'); + $sort->addOption($sort_title); + } + if (in_array(ilContainer::SORT_CREATION, $a_sorting_settings)) { + $sort_activation = new ilRadioOption($this->lng->txt('sorting_creation_header'), ilContainer::SORT_CREATION); + $sort_activation->setInfo($this->lng->txt('sorting_creation_info')); + $this->initSortingDirectionForm($settings, $sort_activation, 'creation'); + $sort->addOption($sort_activation); + } + if (in_array(ilContainer::SORT_ACTIVATION, $a_sorting_settings)) { + $sort_activation = new ilRadioOption($this->lng->txt('crs_sort_activation'), ilContainer::SORT_ACTIVATION); + $sort_activation->setInfo($this->lng->txt('crs_sort_timing_info')); + $this->initSortingDirectionForm($settings, $sort_activation, 'activation'); + $sort->addOption($sort_activation); + } + if (in_array(ilContainer::SORT_MANUAL, $a_sorting_settings)) { + $sort_manual = new ilRadioOption( + $this->lng->txt('sorting_manual_header'), + ilContainer::SORT_MANUAL + ); + $sort_manual->setInfo($this->lng->txt('sorting_info_manual')); + $this->initManualSortingOptionForm($settings, $sort_manual, "manual", $a_sorting_settings); + $sort->addOption($sort_manual); + } + + // Handle moved containers and there possibly invalid values + if (in_array($settings->getSortMode(), $a_sorting_settings)) { + $sort->setValue($settings->getSortMode()); + } else { + $sort->setValue(ilContainer::SORT_TITLE); + } + $form->addItem($sort); + + return $form; + } + + /** + * Add list presentation settings to form + * @param ilPropertyFormGUI $form + * @return ilPropertyFormGUI + */ + protected function initListPresentationForm(ilPropertyFormGUI $form) + { + $lpres = new ilRadioGroupInputGUI($this->lng->txt('cont_list_presentation'), "list_presentation"); + + $item_list = new ilRadioOption($this->lng->txt('cont_item_list'), ""); + //$item_list->setInfo($this->lng->txt('cont_item_list_info')); + $lpres->addOption($item_list); + + $tile_view = new ilRadioOption($this->lng->txt('cont_tile_view'), "tile"); + //$tile_view->setInfo($this->lng->txt('cont_tile_view_info')); + $lpres->addOption($tile_view); + + $lpres->setValue( + ilContainer::_lookupContainerSetting($this->object->getId(), "list_presentation") + ); + + $form->addItem($lpres); + + return $form; + } + + /** + * Save list presentation setting + * @param ilPropertyFormGUI $form + */ + protected function saveListPresentation(ilPropertyFormGUI $form) + { + $val = ($form->getInput('list_presentation') == "tile") + ? "tile" + : ""; + ilContainer::_writeContainerSetting($this->object->getId(), "list_presentation", $val); + } + + + /** + * Add sorting direction + * @param ilFormPropertyGUI $element + */ + protected function initSortingDirectionForm(ilContainerSortingSettings $sorting_settings, $element, $a_prefix) + { + if ($a_prefix == 'manual') { + $txt = $this->lng->txt('sorting_new_items_direction'); + } else { + $txt = $this->lng->txt('sorting_direction'); + } + + $direction = new ilRadioGroupInputGUI($txt, $a_prefix . '_sorting_direction'); + $direction->setValue($sorting_settings->getSortDirection()); + $direction->setRequired(true); + + // asc + $asc = new ilRadioOption( + $this->lng->txt('sorting_asc'), + ilContainer::SORT_DIRECTION_ASC + ); + $direction->addOption($asc); + + // desc + $desc = new ilRadioOption( + $this->lng->txt('sorting_desc'), + ilContainer::SORT_DIRECTION_DESC + ); + $direction->addOption($desc); + + $element->addSubItem($direction); + + return $element; + } + + /** + * Add manual sorting options + * + */ + protected function initManualSortingOptionForm( + ilContainerSortingSettings $settings, + $element, + $a_prefix, + $a_sorting_settings + ) { + $position = new ilRadioGroupInputGUI($this->lng->txt('sorting_new_items_position'), $a_prefix . '_new_items_position'); + $position->setValue($settings->getSortNewItemsPosition()); + $position->setRequired(true); + + //new items insert on top + $new_top = new ilRadioOption( + $this->lng->txt('sorting_new_items_at_top'), + ilContainer::SORT_NEW_ITEMS_POSITION_TOP + ); + + $position->addOption($new_top); + + //new items insert at bottom + $new_bottom = new ilRadioOption( + $this->lng->txt('sorting_new_items_at_bottom'), + ilContainer::SORT_NEW_ITEMS_POSITION_BOTTOM + ); + + $position->addOption($new_bottom); + + $element->addSubItem($position); + + $order = new ilRadioGroupInputGUI($this->lng->txt('sorting_new_items_order'), $a_prefix . '_new_items_order'); + $order->setValue($settings->getSortNewItemsOrder()); + $order->setRequired(true); + + if (in_array(ilContainer::SORT_TITLE, $a_sorting_settings)) { + //new items sort in alphabetical order + $new_title = new ilRadioOption( + $this->lng->txt('sorting_title_header'), + ilContainer::SORT_NEW_ITEMS_ORDER_TITLE + ); + + $order->addOption($new_title); + } + + if (in_array(ilContainer::SORT_CREATION, $a_sorting_settings)) { + //new items sort by creation date + $new_creation = new ilRadioOption( + $this->lng->txt('sorting_creation_header'), + ilContainer::SORT_NEW_ITEMS_ORDER_CREATION + ); + + $order->addOption($new_creation); + } + + + if (in_array(ilContainer::SORT_ACTIVATION, $a_sorting_settings)) { + //new items by activation + $new_activation = new ilRadioOption( + $this->lng->txt('crs_sort_activation'), + ilContainer::SORT_NEW_ITEMS_ORDER_ACTIVATION + ); + + $order->addOption($new_activation); + } + + $element->addSubItem($order); + + $this->initSortingDirectionForm($settings, $element, 'manual'); + + return $element; + } + + /** + * Save sorting settings + * @param ilPropertyFormGUI $form + */ + protected function saveSortingSettings(ilPropertyFormGUI $form) + { + include_once('Services/Container/classes/class.ilContainerSortingSettings.php'); + $settings = new ilContainerSortingSettings($this->object->getId()); + $settings->setSortMode($form->getInput("sorting")); + + switch ($form->getInput('sorting')) { + case ilContainer::SORT_TITLE: + $settings->setSortDirection($form->getInput('title_sorting_direction')); + break; + case ilContainer::SORT_ACTIVATION: + $settings->setSortDirection($form->getInput('activation_sorting_direction')); + break; + case ilContainer::SORT_CREATION: + $settings->setSortDirection($form->getInput('creation_sorting_direction')); + break; + case ilContainer::SORT_MANUAL: + $settings->setSortNewItemsPosition($form->getInput('manual_new_items_position')); + $settings->setSortNewItemsOrder($form->getInput('manual_new_items_order')); + $settings->setSortDirection($form->getInput('manual_sorting_direction')); + break; + } + + $settings->update(); + } + + /** + * Show trash content of object + * + * @access public + */ + public function trashObject() + { + $tpl = $this->tpl; + + include_once("./Services/Repository/classes/class.ilRepUtilGUI.php"); + $ru = new ilRepUtilGUI($this); + $ru->showTrashTable($_GET["ref_id"]); + } + + /** + * remove objects from trash bin and all entries therefore every object needs a specific deleteObject() method + * + * @access public + */ + public function removeFromSystemObject() + { + $ilLog = $this->log; + $ilAppEventHandler = $this->app_event_handler; + $lng = $this->lng; + + include_once("./Services/Repository/classes/class.ilRepUtilGUI.php"); + $ru = new ilRepUtilGUI($this); + $ru->removeObjectsFromSystem($_POST["trash_id"]); + $this->ctrl->redirect($this, "trash"); + } + + /** + * Get objects back from trash + */ + public function undeleteObject() + { + include_once("./Services/Repository/classes/class.ilRepUtilGUI.php"); + $ru = new ilRepUtilGUI($this); + $ru->restoreObjects($_GET["ref_id"], $_POST["trash_id"]); + $this->ctrl->redirect($this, "trash"); + } + + /** + * confirmation screen remove from system + */ + public function confirmRemoveFromSystemObject() + { + $lng = $this->lng; + include_once("./Services/Repository/classes/class.ilRepUtilGUI.php"); + + if (!isset($_POST["trash_id"])) { + ilUtil::sendFailure($lng->txt("no_checkbox"), true); + $this->ctrl->redirect($this, "trash"); + } + + $ru = new ilRepUtilGUI($this); + $ru->confirmRemoveFromSystemObject($_POST["trash_id"]); + } + + /** + * @param $cmd string + * @return ilTreeExplorerGUI + */ + protected function getTreeSelectorGUI($cmd) + { + include_once("./Services/Repository/classes/class.ilRepositorySelectorExplorerGUI.php"); + $exp = new ilRepositorySelectorExplorerGUI($this, "showPasteTree"); + // TODO: The study programme 'prg' is not included here, as the + // ilRepositorySelectorExplorerGUI only handles static rules for + // parent-child-relations and not the dynamic relationsships + // required for the SP (see #16909). + $exp->setTypeWhiteList(array("root", "cat", "grp", "crs", "fold")); + + // Not all types are allowed in the LearningSequence + // Extend whitelist, if all selected types are possible subojects of LSO + if (in_array($_SESSION["clipboard"]["cmd"], ["link", "cut"])) { + $lso_types = array_keys($this->obj_definition->getSubObjects('lso')); + $refs = $_SESSION["clipboard"]["ref_ids"]; + $allow_lso = true; + foreach ($refs as $item_ref_id) { + $type = ilObject::_lookupType($item_ref_id, true); + if (!in_array($type, $lso_types)) { + $allow_lso = false; + } + } + if ($allow_lso) { + $whitelist = $exp->getTypeWhiteList(); + $whitelist[] = 'lso'; + $exp->setTypeWhiteList($whitelist); + } + } + + if ($cmd == "link") { + $exp->setSelectMode("nodes", true); + return $exp; + } else { + $exp->setSelectMode("nodes[]", false); + return $exp; + } + } + + /** + * Set return point for side column actions + */ + public function setSideColumnReturn() + { + $this->ctrl->setReturn($this, ""); + } } -?> \ No newline at end of file diff --git a/Services/Container/classes/class.ilContainerImporter.php b/Services/Container/classes/class.ilContainerImporter.php index 4f7f8ac0e663d7a214bdef9bc0c3f384f3c6d168..15343a9936cc5c62c902fa9060b43bfa033c5d05 100644 --- a/Services/Container/classes/class.ilContainerImporter.php +++ b/Services/Container/classes/class.ilContainerImporter.php @@ -15,71 +15,64 @@ include_once("./Services/Export/classes/class.ilXmlImporter.php"); class ilContainerImporter extends ilXmlImporter { - /** - * @var ilLogger - */ - protected $cont_log; + /** + * @var ilLogger + */ + protected $cont_log; - public function init() - { - $this->cont_log = ilLoggerFactory::getLogger('cont'); - } - - /** - * Import XML - * - * @inheritdoc - */ - function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) - { - include_once './Services/Container/classes/class.ilContainerXmlParser.php'; + public function init() + { + $this->cont_log = ilLoggerFactory::getLogger('cont'); + } + + /** + * Import XML + * + * @inheritdoc + */ + public function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) + { + include_once './Services/Container/classes/class.ilContainerXmlParser.php'; - $this->cont_log->debug('Import xml: '. $a_xml); - $this->cont_log->debug('Using id: ' . $a_id); - - $parser = new ilContainerXmlParser($a_mapping,trim($a_xml)); - $parser->parse($a_id); - } + $this->cont_log->debug('Import xml: ' . $a_xml); + $this->cont_log->debug('Using id: ' . $a_id); + + $parser = new ilContainerXmlParser($a_mapping, trim($a_xml)); + $parser->parse($a_id); + } - /** - * @inheritdoc - */ - function finalProcessing($a_mapping) - { - // pages - include_once('./Services/COPage/classes/class.ilPageObject.php'); - $page_map = $a_mapping->getMappingsOfEntity('Services/COPage', 'pg'); - foreach ($page_map as $old_pg_id => $new_pg_id) - { - $parts = explode(':', $old_pg_id); - $pg_type = $parts[0]; - $old_obj_id = $parts[1]; - $new_pg_id = array_pop(explode(':', $new_pg_id)); - $new_obj_id = $a_mapping->getMapping('Services/Container', 'objs', $old_obj_id); - // see bug #22718, this missed a check for the pg type - if (in_array($pg_type, array("crs", "grp", "fold", "cont"))) - { - if ($new_obj_id > 0) - { - ilPageObject::_writeParentId($pg_type, $new_pg_id, $new_obj_id); - $this->cont_log->debug('write parent id, type: '.$pg_type.", page id: ".$new_pg_id.", parent id: ".$new_obj_id); - } - } - } - - // style - 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(ilContainerXmlParser::$style_map[$old_sty_id])) - { - foreach(ilContainerXmlParser::$style_map[$old_sty_id] as $obj_id) - { - ilObjStyleSheet::writeStyleUsage($obj_id, $new_sty_id); - } - } - } - } + /** + * @inheritdoc + */ + public function finalProcessing($a_mapping) + { + // pages + include_once('./Services/COPage/classes/class.ilPageObject.php'); + $page_map = $a_mapping->getMappingsOfEntity('Services/COPage', 'pg'); + foreach ($page_map as $old_pg_id => $new_pg_id) { + $parts = explode(':', $old_pg_id); + $pg_type = $parts[0]; + $old_obj_id = $parts[1]; + $new_pg_id = array_pop(explode(':', $new_pg_id)); + $new_obj_id = $a_mapping->getMapping('Services/Container', 'objs', $old_obj_id); + // see bug #22718, this missed a check for the pg type + if (in_array($pg_type, array("crs", "grp", "fold", "cont"))) { + if ($new_obj_id > 0) { + ilPageObject::_writeParentId($pg_type, $new_pg_id, $new_obj_id); + $this->cont_log->debug('write parent id, type: ' . $pg_type . ", page id: " . $new_pg_id . ", parent id: " . $new_obj_id); + } + } + } + + // style + 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(ilContainerXmlParser::$style_map[$old_sty_id])) { + foreach (ilContainerXmlParser::$style_map[$old_sty_id] as $obj_id) { + ilObjStyleSheet::writeStyleUsage($obj_id, $new_sty_id); + } + } + } + } } -?> \ No newline at end of file diff --git a/Services/Container/classes/class.ilContainerLinkListGUI.php b/Services/Container/classes/class.ilContainerLinkListGUI.php index 076648dfdbf79eda913250b2b23df85f23d15771..d911e5c78fde1a0046770a1efa1a7f966dab7bf5 100755 --- a/Services/Container/classes/class.ilContainerLinkListGUI.php +++ b/Services/Container/classes/class.ilContainerLinkListGUI.php @@ -1,24 +1,24 @@ ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->tree = $DIC->repositoryTree(); - $ilCtrl = $DIC->ctrl(); - - $this->ctrl =& $ilCtrl; - } + public $ctrl; - function executeCommand() - { - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - //$this->prepareOutput(); + /** + * Constructor + * @access public + */ + public function __construct() + { + global $DIC; - switch($next_class) - { - default: - $this->$cmd(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->tree = $DIC->repositoryTree(); + $ilCtrl = $DIC->ctrl(); + + $this->ctrl =&$ilCtrl; + } - break; - } - return true; - } - - function show() - { - $lng = $this->lng; - $tree = $this->tree; - - $tpl = new ilTemplate("tpl.container_link_help.html", true, true, - "Services/Container"); - - $type_ordering = array( - "cat", "fold", "crs", "grp", "chat", "frm", "lres", - "glo", "webr", "file", "exc", - "tst", "svy", "mep", "qpl", "spl"); - - $childs = $tree->getChilds($_GET["ref_id"]); - foreach($childs as $child) - { - if (in_array($child["type"], array("lm", "sahs", "htlm"))) - { - $cnt["lres"]++; - } - else - { - $cnt[$child["type"]]++; - } - } - - $tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); - $tpl->setVariable("TXT_HELP_HEADER", $lng->txt("help")); - foreach($type_ordering as $type) - { - $tpl->setCurrentBlock("row"); - $tpl->setVariable("ROWCOL", "tblrow".((($i++)%2)+1)); - if ($type != "lres") - { - $tpl->setVariable("TYPE", $lng->txt("objs_".$type). - " (".((int)$cnt[$type]).")"); - } - else - { - $tpl->setVariable("TYPE", $lng->txt("obj_lrss"). - " (".((int)$cnt["lres"]).")"); - } - $tpl->setVariable("TXT_LINK", "[list-".$type."]"); - $tpl->parseCurrentBlock(); - } - $tpl->show(); - exit; + public function executeCommand() + { + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + //$this->prepareOutput(); - } + switch ($next_class) { + default: + $this->$cmd(); + break; + } + return true; + } + + public function show() + { + $lng = $this->lng; + $tree = $this->tree; + + $tpl = new ilTemplate( + "tpl.container_link_help.html", + true, + true, + "Services/Container" + ); + + $type_ordering = array( + "cat", "fold", "crs", "grp", "chat", "frm", "lres", + "glo", "webr", "file", "exc", + "tst", "svy", "mep", "qpl", "spl"); + + $childs = $tree->getChilds($_GET["ref_id"]); + foreach ($childs as $child) { + if (in_array($child["type"], array("lm", "sahs", "htlm"))) { + $cnt["lres"]++; + } else { + $cnt[$child["type"]]++; + } + } + + $tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); + $tpl->setVariable("TXT_HELP_HEADER", $lng->txt("help")); + foreach ($type_ordering as $type) { + $tpl->setCurrentBlock("row"); + $tpl->setVariable("ROWCOL", "tblrow" . ((($i++)%2)+1)); + if ($type != "lres") { + $tpl->setVariable("TYPE", $lng->txt("objs_" . $type) . + " (" . ((int) $cnt[$type]) . ")"); + } else { + $tpl->setVariable("TYPE", $lng->txt("obj_lrss") . + " (" . ((int) $cnt["lres"]) . ")"); + } + $tpl->setVariable("TXT_LINK", "[list-" . $type . "]"); + $tpl->parseCurrentBlock(); + } + $tpl->show(); + exit; + } } // END class.ilContainerLinkListGUI -?> diff --git a/Services/Container/classes/class.ilContainerNewsSettingsGUI.php b/Services/Container/classes/class.ilContainerNewsSettingsGUI.php index 157ff8f3e0115573064afcfa14982ea0e443d4b9..e39fd140ce90cc89b9ab1a4cfa0257f4153bae9d 100644 --- a/Services/Container/classes/class.ilContainerNewsSettingsGUI.php +++ b/Services/Container/classes/class.ilContainerNewsSettingsGUI.php @@ -11,377 +11,371 @@ */ class ilContainerNewsSettingsGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilSetting - */ - protected $setting; - - /** - * @var ilObjectGUI - */ - protected $parent_gui; - - /** - * @var ilObject - */ - protected $object; - - /** - * @var bool - */ - protected $has_timeline; - - /** - * @var bool - */ - protected $has_cron_notifications; - - /** - * @var bool - */ - protected $has_hide_by_date; - - /** - * @var bool - */ - protected $has_public_notification; - - /** - * @var bool - */ - protected $has_block_forced; - - /** - * Constructor - */ - function __construct(ilObjectGUI $a_parent_gui) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->lng->loadLanguageModule("news"); - $this->tpl = $DIC["tpl"]; - $this->setting = $DIC["ilSetting"]; - $this->parent_gui = $a_parent_gui; - $this->object = $this->parent_gui->object; - - $this->initDefaultOptions(); - } - - /** - * Execute command - */ - function executeCommand() - { - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd("show"); - - switch ($next_class) - { - default: - if (in_array($cmd, array("show", "save"))) - { - $this->$cmd(); - } - } - } - - /** - * Show - * - * @param - * @return - */ - function show() - { - $form = $this->initForm(); - $this->tpl->setContent($form->getHTML()); - } - - /** - * Init settings form. - */ - public function initForm() - { - $form = new ilPropertyFormGUI(); - - //from crs/grp/cat settings - additional feature - news - - if($this->setting->get('block_activated_news')) - { - $news = new ilCheckboxInputGUI($this->lng->txt('news_news_block'), ilObjectServiceSettingsGUI::NEWS_VISIBILITY); - $news->setValue(1); - if($this->has_block_forced){ - $news->setChecked(true); - $news->setDisabled(true); - } else { - $news->setChecked($this->object->getNewsBlockActivated()); - } - $news->setInfo($this->lng->txt('obj_tool_setting_news_info')); - ilNewsForContextBlockGUI::addToSettingsForm($news); - $form->addItem($news); - } - - // Timeline (courses and groups) - if($this->has_timeline) - { - // timeline - $cb = new ilCheckboxInputGUI($this->lng->txt("cont_news_timeline"), "news_timeline"); - $cb->setInfo($this->lng->txt("cont_news_timeline_info")); - $cb->setChecked($this->object->getNewsTimeline()); - $form->addItem($cb); - - // ...timeline: auto entries - $cb2 = new ilCheckboxInputGUI($this->lng->txt("cont_news_timeline_auto_entries"), "news_timeline_auto_entries"); - $cb2->setInfo($this->lng->txt("cont_news_timeline_auto_entries_info")); - $cb2->setChecked($this->object->getNewsTimelineAutoEntries()); - $cb->addSubItem($cb2); - - // ...timeline: landing page - $cb2 = new ilCheckboxInputGUI($this->lng->txt("cont_news_timeline_landing_page"), "news_timeline_landing_page"); - $cb2->setInfo($this->lng->txt("cont_news_timeline_landing_page_info")); - $cb2->setChecked($this->object->getNewsTimelineLandingPage()); - $cb->addSubItem($cb2); - } - - // Cron Notifications (courses and groups) - if($this->has_cron_notifications) - { - if (in_array(ilObject::_lookupType($this->object->getId()), array('crs', 'grp'))) - { - $ref_id = array_pop(ilObject::_getAllReferences($this->object->getId())); - include_once 'Services/Membership/classes/class.ilMembershipNotifications.php'; - ilMembershipNotifications::addToSettingsForm($ref_id, $form, null); - } - } - - $block_id = $this->ctrl->getContextObjId(); - - // Visibility by date - $hide_news_per_date = ilBlockSetting::_lookup(ilNewsForContextBlockGUI::$block_type, "hide_news_per_date", - 0, $block_id); - $hide_news_date = ilBlockSetting::_lookup(ilNewsForContextBlockGUI::$block_type, "hide_news_date", - 0, $block_id); - - if ($hide_news_date != "") - { - $hide_news_date = explode(" ", $hide_news_date); - } - - // Hide news before a date (courses, groups and categories) - if($this->has_hide_by_date) - { - //Hide news per date - $hnpd = new ilCheckboxInputGUI($this->lng->txt("news_hide_news_per_date"), - "hide_news_per_date"); - $hnpd->setInfo($this->lng->txt("news_hide_news_per_date_info")); - $hnpd->setChecked($hide_news_per_date); - - $dt_prop = new ilDateTimeInputGUI($this->lng->txt("news_hide_news_date"), "hide_news_date"); - $dt_prop->setRequired(true); - - if ($hide_news_date != "") - { - $dt_prop->setDate(new ilDateTime($hide_news_date[0].' '.$hide_news_date[1],IL_CAL_DATETIME)); - } - - $dt_prop->setShowTime(true); - - $hnpd->addSubItem($dt_prop); - - $form->addItem($hnpd); - } - - // public notifications (forums) - if($this->has_public_notification) - { - $public = ilBlockSetting::_lookup("news", "public_notifications", 0, $block_id); - - $ch = new ilCheckboxInputGUI($this->lng->txt("news_notifications_public"), - "public_notifications"); - $ch->setInfo($this->lng->txt("news_notifications_public_info")); - $ch->setChecked($public); - $form->addItem($ch); - } - - $form->setTitle($this->lng->txt("cont_news_settings")); - $form->setFormAction($this->ctrl->getFormAction($this)); - $form->addCommandButton("save", $this->lng->txt("save")); - - return $form; - } - - /** - * Save settings form - */ - public function save() - { - $form = $this->initForm(); - if ($form->checkInput()) - { - include_once("./Services/Object/classes/class.ilObjectServiceSettingsGUI.php"); - //non container objects force this news block (forums etc.) - if(!$this->has_block_forced){ - $this->object->setNewsBlockActivated($form->getInput(ilObjectServiceSettingsGUI::NEWS_VISIBILITY)); - } - if($this->has_timeline) { - $this->object->setNewsTimeline($form->getInput("news_timeline")); - $this->object->setNewsTimelineAutoEntries($form->getInput("news_timeline_auto_entries")); - $this->object->setNewsTimelineLandingPage($form->getInput("news_timeline_landing_page")); - } - - if($this->setting->get('block_activated_news')) - { - //save contextblock settings - $context_block_settings = array( - "public_feed" => $_POST["notifications_public_feed"], - "default_visibility" => $_POST["default_visibility"], - "hide_news_per_date" => $_POST["hide_news_per_date"], - "hide_news_date" => $_POST["hide_news_date"] - ); - if($this->has_public_notification) { - $context_block_settings["public_notifications"] = $_POST['public_notifications']; - } - - ilNewsForContextBlockGUI::writeSettings($context_block_settings); - - if (in_array(ilObject::_lookupType($this->object->getId()), array('crs', 'grp'))) - { - $ref_id = array_pop(ilObject::_getAllReferences($this->object->getId())); - - include_once "Services/Membership/classes/class.ilMembershipNotifications.php"; - ilMembershipNotifications::importFromForm($ref_id, $form); - } - } - - $this->object->update(); - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, ""); - } - else - { - $form->setValuesByPost(); - $this->tpl->setContent($form->getHtml()); - } - } - - /** - * Set all possible news options as false; - */ - public function initDefaultOptions() - { - $this->has_timeline = false; - $this->has_cron_notifications = false; - $this->has_hide_by_date = false; - $this->has_block_forced = false; - } - - /** - * Set if the container has timeline or not - * @param bool $a_value - */ - public function setTimeline(bool $a_value) - { - $this->has_timeline = $a_value; - } - - /** - * Get if the container has timeline or not - * @return bool - */ - public function getTimeline(): bool - { - return $this->has_timeline; - } - - /** - * Set if the container has a configurable cron job to send notifications. - * @param bool $a_value - */ - public function setCronNotifications(bool $a_value) - { - $this->has_cron_notifications = $a_value; - } - - /** - * Get if the container has a configurable cron job to send notifications. - * @return mixed - */ - public function getCronNotifications(): bool - { - return $this->getCronNotifications(); - } - - /** - * Set if the container can hide news created before a date - * @param bool $a_value - */ - public function setHideByDate(bool $a_value) - { - $this->has_hide_by_date = $a_value; - } - - /** - * Get if the container can hide news created before a date. - * @return bool - */ - public function getHideByDate() : bool - { - return $this->has_hide_by_date; - } - - /** - * Set if this repository object has public notifications - * @param bool $a_value - */ - public function setPublicNotification(bool $a_value) - { - $this->has_public_notification = $a_value; - } - - /** - * Get if this repository object has public notifications available. - * @return bool - */ - public function getPublicNotification() - { - return $this->has_public_notification; - } - - /** - * Set if the News block is forced - * @param bool $a_value - */ - public function setNewsBlockForced(bool $a_value) - { - $this->has_block_forced = $a_value; - } - - /** - * Get if the repository object has the news block forced - * @return bool - */ - public function getNewsBlockForced():bool - { - return $this->has_block_forced; - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilSetting + */ + protected $setting; + + /** + * @var ilObjectGUI + */ + protected $parent_gui; + + /** + * @var ilObject + */ + protected $object; + + /** + * @var bool + */ + protected $has_timeline; + + /** + * @var bool + */ + protected $has_cron_notifications; + + /** + * @var bool + */ + protected $has_hide_by_date; + + /** + * @var bool + */ + protected $has_public_notification; + + /** + * @var bool + */ + protected $has_block_forced; + + /** + * Constructor + */ + public function __construct(ilObjectGUI $a_parent_gui) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->lng->loadLanguageModule("news"); + $this->tpl = $DIC["tpl"]; + $this->setting = $DIC["ilSetting"]; + $this->parent_gui = $a_parent_gui; + $this->object = $this->parent_gui->object; + + $this->initDefaultOptions(); + } + + /** + * Execute command + */ + public function executeCommand() + { + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd("show"); + + switch ($next_class) { + default: + if (in_array($cmd, array("show", "save"))) { + $this->$cmd(); + } + } + } + + /** + * Show + * + * @param + * @return + */ + public function show() + { + $form = $this->initForm(); + $this->tpl->setContent($form->getHTML()); + } + + /** + * Init settings form. + */ + public function initForm() + { + $form = new ilPropertyFormGUI(); + + //from crs/grp/cat settings - additional feature - news + + if ($this->setting->get('block_activated_news')) { + $news = new ilCheckboxInputGUI($this->lng->txt('news_news_block'), ilObjectServiceSettingsGUI::NEWS_VISIBILITY); + $news->setValue(1); + if ($this->has_block_forced) { + $news->setChecked(true); + $news->setDisabled(true); + } else { + $news->setChecked($this->object->getNewsBlockActivated()); + } + $news->setInfo($this->lng->txt('obj_tool_setting_news_info')); + ilNewsForContextBlockGUI::addToSettingsForm($news); + $form->addItem($news); + } + + // Timeline (courses and groups) + if ($this->has_timeline) { + // timeline + $cb = new ilCheckboxInputGUI($this->lng->txt("cont_news_timeline"), "news_timeline"); + $cb->setInfo($this->lng->txt("cont_news_timeline_info")); + $cb->setChecked($this->object->getNewsTimeline()); + $form->addItem($cb); + + // ...timeline: auto entries + $cb2 = new ilCheckboxInputGUI($this->lng->txt("cont_news_timeline_auto_entries"), "news_timeline_auto_entries"); + $cb2->setInfo($this->lng->txt("cont_news_timeline_auto_entries_info")); + $cb2->setChecked($this->object->getNewsTimelineAutoEntries()); + $cb->addSubItem($cb2); + + // ...timeline: landing page + $cb2 = new ilCheckboxInputGUI($this->lng->txt("cont_news_timeline_landing_page"), "news_timeline_landing_page"); + $cb2->setInfo($this->lng->txt("cont_news_timeline_landing_page_info")); + $cb2->setChecked($this->object->getNewsTimelineLandingPage()); + $cb->addSubItem($cb2); + } + + // Cron Notifications (courses and groups) + if ($this->has_cron_notifications) { + if (in_array(ilObject::_lookupType($this->object->getId()), array('crs', 'grp'))) { + $ref_id = array_pop(ilObject::_getAllReferences($this->object->getId())); + include_once 'Services/Membership/classes/class.ilMembershipNotifications.php'; + ilMembershipNotifications::addToSettingsForm($ref_id, $form, null); + } + } + + $block_id = $this->ctrl->getContextObjId(); + + // Visibility by date + $hide_news_per_date = ilBlockSetting::_lookup( + ilNewsForContextBlockGUI::$block_type, + "hide_news_per_date", + 0, + $block_id + ); + $hide_news_date = ilBlockSetting::_lookup( + ilNewsForContextBlockGUI::$block_type, + "hide_news_date", + 0, + $block_id + ); + + if ($hide_news_date != "") { + $hide_news_date = explode(" ", $hide_news_date); + } + + // Hide news before a date (courses, groups and categories) + if ($this->has_hide_by_date) { + //Hide news per date + $hnpd = new ilCheckboxInputGUI( + $this->lng->txt("news_hide_news_per_date"), + "hide_news_per_date" + ); + $hnpd->setInfo($this->lng->txt("news_hide_news_per_date_info")); + $hnpd->setChecked($hide_news_per_date); + + $dt_prop = new ilDateTimeInputGUI($this->lng->txt("news_hide_news_date"), "hide_news_date"); + $dt_prop->setRequired(true); + + if ($hide_news_date != "") { + $dt_prop->setDate(new ilDateTime($hide_news_date[0] . ' ' . $hide_news_date[1], IL_CAL_DATETIME)); + } + + $dt_prop->setShowTime(true); + + $hnpd->addSubItem($dt_prop); + + $form->addItem($hnpd); + } + + // public notifications (forums) + if ($this->has_public_notification) { + $public = ilBlockSetting::_lookup("news", "public_notifications", 0, $block_id); + + $ch = new ilCheckboxInputGUI( + $this->lng->txt("news_notifications_public"), + "public_notifications" + ); + $ch->setInfo($this->lng->txt("news_notifications_public_info")); + $ch->setChecked($public); + $form->addItem($ch); + } + + $form->setTitle($this->lng->txt("cont_news_settings")); + $form->setFormAction($this->ctrl->getFormAction($this)); + $form->addCommandButton("save", $this->lng->txt("save")); + + return $form; + } + + /** + * Save settings form + */ + public function save() + { + $form = $this->initForm(); + if ($form->checkInput()) { + include_once("./Services/Object/classes/class.ilObjectServiceSettingsGUI.php"); + //non container objects force this news block (forums etc.) + if (!$this->has_block_forced) { + $this->object->setNewsBlockActivated($form->getInput(ilObjectServiceSettingsGUI::NEWS_VISIBILITY)); + } + if ($this->has_timeline) { + $this->object->setNewsTimeline($form->getInput("news_timeline")); + $this->object->setNewsTimelineAutoEntries($form->getInput("news_timeline_auto_entries")); + $this->object->setNewsTimelineLandingPage($form->getInput("news_timeline_landing_page")); + } + + if ($this->setting->get('block_activated_news')) { + //save contextblock settings + $context_block_settings = array( + "public_feed" => $_POST["notifications_public_feed"], + "default_visibility" => $_POST["default_visibility"], + "hide_news_per_date" => $_POST["hide_news_per_date"], + "hide_news_date" => $_POST["hide_news_date"] + ); + if ($this->has_public_notification) { + $context_block_settings["public_notifications"] = $_POST['public_notifications']; + } + + ilNewsForContextBlockGUI::writeSettings($context_block_settings); + + if (in_array(ilObject::_lookupType($this->object->getId()), array('crs', 'grp'))) { + $ref_id = array_pop(ilObject::_getAllReferences($this->object->getId())); + + include_once "Services/Membership/classes/class.ilMembershipNotifications.php"; + ilMembershipNotifications::importFromForm($ref_id, $form); + } + } + + $this->object->update(); + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, ""); + } else { + $form->setValuesByPost(); + $this->tpl->setContent($form->getHtml()); + } + } + + /** + * Set all possible news options as false; + */ + public function initDefaultOptions() + { + $this->has_timeline = false; + $this->has_cron_notifications = false; + $this->has_hide_by_date = false; + $this->has_block_forced = false; + } + + /** + * Set if the container has timeline or not + * @param bool $a_value + */ + public function setTimeline(bool $a_value) + { + $this->has_timeline = $a_value; + } + + /** + * Get if the container has timeline or not + * @return bool + */ + public function getTimeline() : bool + { + return $this->has_timeline; + } + + /** + * Set if the container has a configurable cron job to send notifications. + * @param bool $a_value + */ + public function setCronNotifications(bool $a_value) + { + $this->has_cron_notifications = $a_value; + } + + /** + * Get if the container has a configurable cron job to send notifications. + * @return mixed + */ + public function getCronNotifications() : bool + { + return $this->getCronNotifications(); + } + + /** + * Set if the container can hide news created before a date + * @param bool $a_value + */ + public function setHideByDate(bool $a_value) + { + $this->has_hide_by_date = $a_value; + } + + /** + * Get if the container can hide news created before a date. + * @return bool + */ + public function getHideByDate() : bool + { + return $this->has_hide_by_date; + } + + /** + * Set if this repository object has public notifications + * @param bool $a_value + */ + public function setPublicNotification(bool $a_value) + { + $this->has_public_notification = $a_value; + } + + /** + * Get if this repository object has public notifications available. + * @return bool + */ + public function getPublicNotification() + { + return $this->has_public_notification; + } + + /** + * Set if the News block is forced + * @param bool $a_value + */ + public function setNewsBlockForced(bool $a_value) + { + $this->has_block_forced = $a_value; + } + + /** + * Get if the repository object has the news block forced + * @return bool + */ + public function getNewsBlockForced() : bool + { + return $this->has_block_forced; + } } - -?> \ No newline at end of file diff --git a/Services/Container/classes/class.ilContainerObjectiveGUI.php b/Services/Container/classes/class.ilContainerObjectiveGUI.php index 4c26d0cdfe0dedaa5173277a50ea77ebe9f35757..53d7eeb7f0ec408cf2439ecc752f9ccd75f36a2f 100644 --- a/Services/Container/classes/class.ilContainerObjectiveGUI.php +++ b/Services/Container/classes/class.ilContainerObjectiveGUI.php @@ -13,1672 +13,1548 @@ */ class ilContainerObjectiveGUI extends ilContainerContentGUI { - /** - * @var \ilLogger |null - */ - private $logger = null; - - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - protected $force_details = 0; - - /** - * @var \ilLOSettings - */ - protected $loc_settings; - - const MATERIALS_TESTS = 1; - const MATERIALS_OTHER = 2; - - private $output_html = ''; - - private $test_assignments = null; - - /** - * Constructor - * - * @access public - * @param object container gui object - * @return - */ - public function __construct($a_container_gui) - { - global $DIC; - - $this->tabs = $DIC->tabs(); - $this->access = $DIC->access(); - $this->user = $DIC->user(); - $this->settings = $DIC->settings(); - $this->ctrl = $DIC->ctrl(); - $this->toolbar = $DIC->toolbar(); - $lng = $DIC->language(); - - $this->logger = $DIC->logger()->crs(); - - $this->lng = $lng; - parent::__construct($a_container_gui); - - $this->initDetails(); - $this->initTestAssignments(); - } - - /** - * Get test assignments object - * @return ilLOTestAssignments - */ - public function getTestAssignments() - { - return $this->test_assignments; - } - - /** - * @return \ilLOSettings - */ - public function getSettings() - { - return $this->loc_settings; - } - - - - /** - * get details level - * - * @access public - * @param - * @return - */ - public function getDetailsLevel($a_objective_id) - { - // no details anymore - return self::DETAILS_ALL; - } - - /** - * Impementation of abstract method getMainContent - * - * @access public - * @return - */ - public function getMainContent() - { - $lng = $this->lng; - $ilTabs = $this->tabs; - $ilAccess = $this->access; - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - - // see bug #7452 -// $ilTabs->setSubTabActive($this->getContainerObject()->getType().'_content'); - - - include_once 'Services/Object/classes/class.ilObjectListGUIFactory.php'; - - $tpl = new ilTemplate("tpl.container_page.html", true, true,"Services/Container"); - - if($ilAccess->checkAccess('write','',$this->getContainerObject()->getRefId())) - { - // check for results - include_once './Modules/Course/classes/Objectives/class.ilLOUserResults.php'; - if(ilLOUserResults::hasResults($this->getContainerObject()->getId(), $ilUser->getId())) - { - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $ilToolbar = new ilToolbarGUI(); - $ilToolbar->addButton( - $lng->txt('crs_reset_results'), - $ilCtrl->getLinkTargetByClass(get_class($this->getContainerGUI()),'reset') - ); - } - - } - - // Feedback - // @todo -// $this->__showFeedBack(); - - $this->items = $this->getContainerObject()->getSubItems($this->getContainerGUI()->isActiveAdministrationPanel()); - - $is_manage = $this->getContainerGUI()->isActiveAdministrationPanel(); - $is_order = $this->getContainerGUI()->isActiveOrdering(); - - include_once './Modules/Course/classes/Objectives/class.ilLOSettings.php'; - $this->loc_settings = ilLOSettings::getInstanceByObjId($this->getContainerObject()->getId()); - - $this->initRenderer(); - - if(!$is_manage && !$is_order) - { - // currently inactive - // $this->showStatus($tpl); - } - if(!$is_manage) - { - $this->showObjectives($tpl, $is_order); - - // $this->showMaterials($tpl,self::MATERIALS_TESTS, false, !$is_order); - - // check for results - include_once './Modules/Course/classes/Objectives/class.ilLOUserResults.php'; - $has_results = ilLOUserResults::hasResults($this->getContainerObject()->getId(), $ilUser->getId()); - - include_once './Modules/Test/classes/class.ilObjTestAccess.php'; - $tst_obj_id = ilObject::_lookupObjId($this->loc_settings->getInitialTest()); - - if( - $this->loc_settings->getInitialTest() && - $this->loc_settings->isGeneralInitialTestVisible() && - !$this->loc_settings->isInitialTestStart() && - !ilObjTestAccess::checkCondition($tst_obj_id, ilConditionHandler::OPERATOR_FINISHED, '', $ilUser->getId()) - ) - { - $this->output_html .= $this->renderTest($this->loc_settings->getInitialTest(), null, true, true); - } - else if( - $this->loc_settings->getQualifiedTest() && - $this->loc_settings->isGeneralQualifiedTestVisible() - ) - { - $this->output_html .= $this->renderTest($this->loc_settings->getQualifiedTest(), null, false, true); - } - - $this->showMaterials($tpl,self::MATERIALS_OTHER, false, !$is_order); - } - else - { - $this->showMaterials($tpl, null, $is_manage); - } - - // reset results by setting or for admins - include_once './Modules/Course/classes/Objectives/class.ilLOSettings.php'; - if( - ilLOSettings::getInstanceByObjId($this->getContainerObject()->getId())->isResetResultsEnabled() or - $ilAccess->checkAccess('write','',$this->getContainerObject()->getRefId()) - ) - { - if($has_results) - { - if (!$is_manage && !$is_order) - { - $this->showButton('askReset',$lng->txt('crs_reset_results')); - } - } - } - - $tpl->setVariable('CONTAINER_PAGE_CONTENT',$this->output_html); - - return $tpl->get(); - } - - /** - * show status - * - * @access public - * @param - * @return - */ - public function showStatus($tpl) - { - $ilUser = $this->user; - $lng = $this->lng; - - include_once('./Modules/Course/classes/class.ilCourseObjectiveResultCache.php'); - - $status = ilCourseObjectiveResultCache::getStatus($ilUser->getId(),$this->getContainerObject()->getId()); - if($status == IL_OBJECTIVE_STATUS_EMPTY) { - return; - } - $info_tpl = new ilTemplate('tpl.crs_objectives_view_info_table.html',true,true,'Modules/Course'); - $info_tpl->setVariable("INFO_STRING",$lng->txt('crs_objectives_info_'.$status)); - - $this->output_html .= $info_tpl->get(); - } - - /** - * show objectives - * - * @access public - * @param object $tpl template object - * @return - */ - public function showObjectives($a_tpl, $a_is_order = false) - { - $lng = $this->lng; - $ilSetting = $this->settings; - $tpl = $this->tpl; - - $this->clearAdminCommandsDetermination(); - - // get embedded blocks - $has_container_page = false; - if(!$a_is_order) - { - $output_html = $this->getContainerGUI()->getContainerPageHTML(); - if ($output_html != "") - { - $has_container_page = true; - $this->output_html .= $this->insertPageEmbeddedBlocks($output_html); - } - unset($output_html); - } - - // All objectives - include_once './Modules/Course/classes/class.ilCourseObjective.php'; - if(!count($objective_ids = ilCourseObjective::_getObjectiveIds($this->getContainerObject()->getId(),true))) - { - return false; - } - - include_once('./Modules/Course/classes/class.ilCourseObjectiveListGUI.php'); - $this->objective_list_gui = new ilCourseObjectiveListGUI(); - $this->objective_list_gui->setContainerObject($this->getContainerGUI()); - if ($ilSetting->get("icon_position_in_lists") == "item_rows") - { - $this->objective_list_gui->enableIcon(true); - } - - $acc = null; - if(!$a_is_order) - { - include_once "Services/Accordion/classes/class.ilAccordionGUI.php"; - $acc = new ilAccordionGUI(); - $acc->setUseSessionStorage(true); - $acc->setAllowMultiOpened(true); - $acc->setBehaviour(ilAccordionGUI::FIRST_OPEN); - $acc->setId("crsobjtv_".$this->container_obj->getId()); - } - else - { - $this->renderer->addCustomBlock('lobj',$lng->txt('crs_objectives')); - } - - $lur_data = $this->parseLOUserResults(); - - $has_initial = ilLOSettings::getInstanceByObjId($this->container_obj->getId())->worksWithInitialTest(); - - $has_lo_page = false; - $obj_cnt = 0; - foreach($objective_ids as $objective_id) - { - include_once './Modules/Course/classes/Objectives/class.ilLOUtils.php'; - if( - $has_initial && - ( - !isset($lur_data[$objective_id]) or - ilLOUtils::hasActiveRun( - $this->container_obj->getId(), - ilLOSettings::getInstanceByObjId($this->container_obj->getId())->getInitialTest(), - $objective_id) - ) - ) - { - $lur_data[$objective_id] = array("type"=>ilLOSettings::TYPE_TEST_INITIAL); - } - - if($html = $this->renderObjective($objective_id, $has_lo_page, $acc, $lur_data[$objective_id])) - { - $this->renderer->addItemToBlock('lobj', 'lobj', $objective_id, $html); - } - $obj_cnt++; - } - - // buttons for showing/hiding all objectives - if (!$a_is_order && $obj_cnt > 1) - { - $this->showButton("", $lng->txt("crs_show_all_obj"), "", "crs_show_all_obj_btn"); - $this->showButton("", $lng->txt("crs_hide_all_obj"), "", "crs_hide_all_obj_btn"); - $acc->setShowAllElement("crs_show_all_obj_btn"); - $acc->setHideAllElement("crs_hide_all_obj_btn"); - } - - if(!$has_container_page && $has_lo_page) - { - // add core co page css - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath(0)); - $tpl->setCurrentBlock("SyntaxStyle"); - $tpl->setVariable("LOCATION_SYNTAX_STYLESHEET", - ilObjStyleSheet::getSyntaxStylePath()); - $tpl->parseCurrentBlock(); - } - - // order/block - if($a_is_order) - { - $this->addFooterRow(); - - $this->output_html .= $output_html.$this->renderer->getHTML(); - - $this->renderer->resetDetails(); - } - // view/accordion - else - { - $this->output_html .= "
          ".$acc->getHTML()."
          "; - } - } - - /** - * add footer row - * - * @access public - * @param - * @return - */ - public function addFooterRow() - { - // no details - return; - - /* - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $this->getContainerObject()->getRefId()); - $ilCtrl->setParameterByClass("ilrepositorygui", "details_level", "1"); - $url = $ilCtrl->getLinkTargetByClass("ilrepositorygui", ""); - $this->renderer->addDetailsLevel(2, $url, ($this->details_level == self::DETAILS_TITLE)); - - $ilCtrl->setParameterByClass("ilrepositorygui", "details_level", "2"); - $url = $ilCtrl->getLinkTargetByClass("ilrepositorygui", ""); - $this->renderer->addDetailsLevel(3, $url, ($this->details_level == self::DETAILS_ALL)); - - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - */ - } - - protected function renderTest($a_test_ref_id, $a_objective_id, $a_is_initial = false, $a_add_border = false, $a_lo_result = array()) - { - global $DIC; - - $tree = $DIC->repositoryTree(); - - $node_data = []; - if($a_test_ref_id) - { - $node_data = $tree->getNodeData($a_test_ref_id); - } - if(!$node_data['child']) - { - return ''; - } - - // update ti - if($a_objective_id) - { - if($a_is_initial) - { - $title = sprintf($this->lng->txt('crs_loc_itst_for_objective'), ilCourseObjective::lookupObjectiveTitle($a_objective_id)); - } - else - { - $title = sprintf($this->lng->txt('crs_loc_qtst_for_objective'), ilCourseObjective::lookupObjectiveTitle($a_objective_id)); - } - $node_data['objective_id'] = $a_objective_id; - $node_data['objective_status'] = - ( - $a_lo_result['status'] == ilLOUserResults::STATUS_COMPLETED ? - false : - false - ); - } - else - { - $obj_id = ilObject::_lookupObjId($a_test_ref_id); - $title = ilObject::_lookupTitle($obj_id); - - $title .= ( - ' ('. - ( - $a_is_initial - ? $this->lng->txt('crs_loc_itest_info') - : $this->lng->txt('crs_loc_qtest_info') - ). - ')' - ); - $node_data['objective_id'] = 0; - } - - $node_data['title'] = $title; - - return "
          ".$this->renderItem($node_data)."
          "; - } - - /** - * Show all other (no assigned tests, no assigned materials) materials - * - * @access public - * @param object $tpl template object - * @return void - */ - public function showMaterials($a_tpl,$a_mode = null,$a_is_manage = false,$a_as_accordion = false) - { - $ilAccess = $this->access; - $lng = $this->lng; - - $this->clearAdminCommandsDetermination(); - - if (is_array($this->items["_all"])) - { - $this->objective_map = $this->buildObjectiveMap(); - - // all rows - $item_r = array(); - - $position = 1; - foreach($this->items["_all"] as $k => $item_data) - { - if($a_mode == self::MATERIALS_TESTS and $item_data['type'] != 'tst') - { - continue; - } - if ($item_data['type'] == 'itgr') - { - continue; - } - if(!$a_is_manage) - { - // if test object is qualified or initial do not show here - include_once './Modules/Course/classes/Objectives/class.ilLOTestAssignments.php'; - include_once './Modules/Course/classes/Objectives/class.ilLOSettings.php'; - $assignments = ilLOTestAssignments::getInstance($this->getContainerObject()->getId()); - if($assignments->getTypeByTest($item_data['child']) != ilLOSettings::TYPE_TEST_UNDEFINED) - { - continue; - } - } - - if($this->rendered_items[$item_data["child"]] !== true && - !$this->renderer->hasItem($item_data["child"])) - { - $this->rendered_items[$item_data['child']] = true; - - // TODO: Position (DONE ?) - $html = $this->renderItem($item_data,$position++,$a_mode == self::MATERIALS_TESTS ? false : true); - if ($html != "") - { - $item_r[] = array("html" => $html, "id" => $item_data["child"], "type" => $item_data["type"]); - } - } - } - - // if we have at least one item, output the block - if (count($item_r) > 0) - { - if(!$a_as_accordion) - { - $pos = 0; - - switch($a_mode) - { - case self::MATERIALS_TESTS: - $block_id = "tst"; - $this->renderer->addTypeBlock($block_id); - break; - - case self::MATERIALS_OTHER: - $block_id = "oth"; - $this->renderer->addCustomBlock($block_id, $lng->txt('crs_other_resources')); - break; - - // manage - default: - $block_id = "all"; - $this->renderer->addCustomBlock($block_id, $lng->txt('content')); - break; - } - - // :TODO: - if ($a_mode != self::MATERIALS_TESTS) - { - $pos = $this->getItemGroupsHTML(); - } - - foreach($item_r as $h) - { - if(!$this->renderer->hasItem($h["id"])) - { - $this->renderer->addItemToBlock($block_id, $h["type"], $h["id"], $h["html"]); - } - } - - $this->output_html .= $this->renderer->getHTML(); - } - else - { - switch($a_mode) - { - case self::MATERIALS_TESTS: - $txt = $lng->txt('objs_tst'); - break; - - case self::MATERIALS_OTHER: - $txt = $lng->txt('crs_other_resources'); - break; - } - - include_once "Services/Accordion/classes/class.ilAccordionGUI.php"; - $acc = new ilAccordionGUI(); - $acc->setId("crsobjtvmat".$a_mode."_".$this->container_obj->getId()); - - $acc_content = array(); - foreach($item_r as $h) - { - $acc_content[] = $h["html"]; - } - $acc->addItem($txt, $this->buildAccordionContent($acc_content)); - - $this->output_html .= $acc->getHTML(); - } - } - } - } - - protected function buildObjectiveMap() - { - $objective_map = array(); - include_once './Modules/Course/classes/class.ilCourseObjective.php'; - // begin-patch lok - if(count($objective_ids = ilCourseObjective::_getObjectiveIds($this->getContainerObject()->getId(),true))) - // end-patch lok - { - include_once('./Modules/Course/classes/class.ilCourseObjectiveMaterials.php'); - foreach($objective_ids as $objective_id) - { - foreach(ilCourseObjectiveMaterials::_getAssignedMaterials($objective_id) as $mat_ref_id) - { - $objective_map["material"][$mat_ref_id][] = $objective_id; - - if(!isset($objective_map["names"][$objective_id])) - { - $objective = new ilCourseObjective($this->getContainerObject(), $objective_id); - $objective_map["names"][$objective_id] = $objective->getTitle(); - } - } - } - - // initial/qualifying test - $tst = $this->loc_settings->getInitialTest(); - if($tst) - { - $objective_map["test_i"] = $tst; - } - $tst = $this->loc_settings->getQualifiedTest(); - if($tst) - { - $objective_map["test_q"] = $tst; - } - - // objective test assignments - include_once 'Modules/Course/classes/Objectives/class.ilLOSettings.php'; - include_once 'Modules/Course/classes/Objectives/class.ilLOTestAssignments.php'; - $ass_test = new ilLOTestAssignments($this->getContainerObject()->getId()); - foreach($ass_test->getAssignmentsByType(ilLOSettings::TYPE_TEST_INITIAL) as $ass) - { - $title = ilCourseObjective::lookupObjectiveTitle($ass->getObjectiveId()); - $objective_map["test_ass"][$ass->getTestRefId()][$ass->getAssignmentType()][] = $title; - } - foreach($ass_test->getAssignmentsByType(ilLOSettings::TYPE_TEST_QUALIFIED) as $ass) - { - $title = ilCourseObjective::lookupObjectiveTitle($ass->getObjectiveId()); - $objective_map["test_ass"][$ass->getTestRefId()][$ass->getAssignmentType()][] = $title; - } - } - - return $objective_map; - } - - protected function addItemDetails(ilObjectListGUI $a_item_list_gui, array $a_item) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - $item_ref_id = $a_item["ref_id"]; - - if(is_array($this->objective_map)) - { - $details = array(); - if(isset($this->objective_map["material"][$item_ref_id])) - { - // #12965 - foreach($this->objective_map["material"][$item_ref_id] as $objective_id) - { - $ilCtrl->setParameterByClass('ilcourseobjectivesgui', 'objective_id', $objective_id); - $url = $ilCtrl->getLinkTargetByClass(array('illoeditorgui', 'ilcourseobjectivesgui'), 'edit'); - $ilCtrl->setParameterByClass('ilcourseobjectivesgui', 'objective_id', ''); - - $details[] = array( - 'desc' => $lng->txt('crs_loc_tab_materials').': ', - 'target' => '_top', - 'link' => $url, - 'name' => $this->objective_map["names"][$objective_id] - ); - } - } - if($this->objective_map["test_i"] == $item_ref_id) - { - $ilCtrl->setParameterByClass('illoeditorgui', 'tt', 1); - $details[] = array( - 'desc' => '', - 'target' => '_top', - 'link' => $ilCtrl->getLinkTargetByClass('illoeditorgui', 'testOverview'), - 'name' => $lng->txt('crs_loc_tab_itest') - ); - $ilCtrl->setParameterByClass('illoeditorgui', 'tt', 0); - } - if($this->objective_map["test_q"] == $item_ref_id) - { - $ilCtrl->setParameterByClass('illoeditorgui', 'tt', 2); - $details[] = array( - 'desc' => '', - 'target' => '_top', - 'link' => $ilCtrl->getLinkTargetByClass('illoeditorgui', 'testOverview'), - 'name' => $lng->txt('crs_loc_tab_qtest') - ); - $ilCtrl->setParameterByClass('illoeditorgui', 'tt', 0); - } - - // #15367 - if(is_array($this->objective_map["test_ass"][$item_ref_id])) - { - foreach($this->objective_map["test_ass"][$item_ref_id] as $type => $items) - { - if($type == ilLOSettings::TYPE_TEST_INITIAL) - { - $caption = $lng->txt('crs_loc_tab_itest'); - $ilCtrl->setParameterByClass('illoeditorgui', 'tt', 1); - } - else - { - $caption = $lng->txt('crs_loc_tab_qtest'); - $ilCtrl->setParameterByClass('illoeditorgui', 'tt', 2); - } - foreach($items as $objtv_title) - { - $details[] = array( - 'desc' => '', - 'target' => '_top', - 'link' => $ilCtrl->getLinkTargetByClass('illoeditorgui', 'testsOverview'), - 'name' => $caption." (".$this->lng->txt("crs_loc_learning_objective").": ".$objtv_title.")" - ); - } - $ilCtrl->setParameterByClass('illoeditorgui', 'tt', 0); - } - } - - if(sizeof($details)) - { - $a_item_list_gui->enableItemDetailLinks(true); - $a_item_list_gui->setItemDetailLinks($details, $lng->txt('crs_loc_settings_tbl').': '); - } - else - { - $a_item_list_gui->enableItemDetailLinks(false); - } - } - - // order - if($this->getContainerGUI()->isActiveOrdering()) - { - $a_item_list_gui->enableCommands(true, true); - $a_item_list_gui->enableProperties(false); - } - // view - else if(!$this->getContainerGUI()->isActiveAdministrationPanel()) - { - $a_item_list_gui->enableCommands(true, true); - $a_item_list_gui->enableProperties(false); - } - - if($a_item['objective_id']) - { - $a_item_list_gui->setDefaultCommandParameters(array('objective_id' => $a_item['objective_id'])); - - - if($this->loc_settings->getQualifiedTest() == $a_item['ref_id']) - { - $a_item_list_gui->setConditionTarget($this->getContainerObject()->getRefId(), $a_item['objective_id'], 'lobj'); - // check conditions of target - include_once './Services/Conditions/classes/class.ilConditionHandler.php'; - $fullfilled = ilConditionHandler::_checkAllConditionsOfTarget($this->getContainerObject()->getRefId(),$a_item['objective_id'],'lobj'); - if(!$fullfilled || $a_item['objective_status']) - { - $a_item_list_gui->disableTitleLink(true); - } - } - include_once './Modules/Course/classes/Objectives/class.ilLOUserResults.php'; - $res = ilLOUserResults::lookupResult( - $this->getContainerObject()->getId(), - $ilUser->getId(), - $a_item['objective_id'], - ilLOUserResults::TYPE_QUALIFIED); - - $res = $this->updateResult($res,$a_item['ref_id'],$a_item['objective_id'], $ilUser->getId()); - - if($res['is_final']) - { - $a_item_list_gui->disableTitleLink(true); - $a_item_list_gui->enableProperties(true); - $a_item_list_gui->addCustomProperty( - $this->lng->txt('crs_loc_passes_reached'), - '', - true - ); - } - elseif($this->loc_settings->getQualifiedTest() == $a_item['ref_id']) - { - include_once './Modules/Course/classes/class.ilCourseObjective.php'; - $poss_pass = ilCourseObjective::lookupMaxPasses($a_item['objective_id']); - - if($poss_pass) - { - $a_item_list_gui->enableProperties(true); - $a_item_list_gui->addCustomProperty( - $this->lng->txt('crs_loc_passes_left'), - (($poss_pass - $res['tries']) > 0) ? ($poss_pass - $res['tries']) : 1, - false - ); - } - } - } - } - - protected function updateResult($a_res,$a_item_ref_id,$a_objective_id,$a_user_id) - { - - if($this->loc_settings->getQualifiedTest() == $a_item_ref_id) - { - // Check for existing test run, and decrease tries, reset final if run exists - include_once './Modules/Test/classes/class.ilObjTest.php'; - include_once './Modules/Course/classes/Objectives/class.ilLOSettings.php'; - $active = ilObjTest::isParticipantsLastPassActive( - $a_item_ref_id, - $a_user_id); - - if($active) - { - include_once './Modules/Course/classes/Objectives/class.ilLOTestRun.php'; - if(ilLOTestRun::lookupRunExistsForObjective( - ilObject::_lookupObjId($a_item_ref_id), - $a_objective_id, - $a_user_id)) - { - ($a_res['tries'] > 0) ? --$a_res['tries'] : 0; - $a_res['is_final'] = 0; - } - } - } - return $a_res; - - } - - /** - * render objective - * - * @access protected - * @param int objective id - * @param bool co page status - * @param ilAccordionGUI $a_accordion - * @param array $a_lo_result - * @return string html - */ - protected function renderObjective($a_objective_id, &$a_has_lo_page, ilAccordionGUI $a_accordion = null, array $a_lo_result = null) - { - $ilUser = $this->user; - $lng = $this->lng; - - include_once('./Modules/Course/classes/class.ilCourseObjective.php'); - $objective = new ilCourseObjective($this->getContainerObject(),$a_objective_id); - - include_once('./Services/Container/classes/class.ilContainerSorting.php'); - include_once('./Services/Object/classes/class.ilObjectActivation.php'); - $items = ilObjectActivation::getItemsByObjective($a_objective_id); - - // sorting is handled by ilCourseObjectiveMaterials - // $items = ilContainerSorting::_getInstance($this->getContainerObject()->getId())->sortSubItems('lobj',$a_objective_id,$items); - - include_once('./Modules/Course/classes/class.ilCourseObjectiveMaterials.php'); - $objectives_lm_obj = new ilCourseObjectiveMaterials($a_objective_id); - - // #13381 - map material assignment to position - $sort_map = array(); - foreach($objectives_lm_obj->getMaterials() as $item) - { - $sort_map[$item["lm_ass_id"]] = $item["position"]; - } - - $is_manage = $this->getContainerGUI()->isActiveAdministrationPanel(); - $is_order = $this->getContainerGUI()->isActiveOrdering(); - - $sort_content = array(); - - foreach($items as $item) - { - if($this->getDetailsLevel($a_objective_id) < self::DETAILS_ALL) - { - continue; - } - - $item_list_gui2 = $this->getItemGUI($item); - $item_list_gui2->enableIcon(true); - - if($is_order || $a_accordion) - { - $item_list_gui2->enableCommands(true, true); - $item_list_gui2->enableProperties(false); - } - - $chapters = $objectives_lm_obj->getChapters(); - if(count($chapters)) - { - $has_sections = false; - foreach($chapters as $chapter) - { - if($chapter['ref_id'] != $item['child']) - { - continue; - } - $has_sections = true; - - include_once './Modules/LearningModule/classes/class.ilLMObject.php'; - $title = $item['title']. - " › ".ilLMObject::_lookupTitle($chapter['obj_id']). - " (".$lng->txt('obj_'.$chapter['type']).")"; - - $item_list_gui2->setDefaultCommandParameters(array( - "obj_id" => $chapter['obj_id'], - "focus_id" => $chapter['obj_id'], - "focus_return" => $this->container_obj->getRefId())); - - if($is_order) - { - $item_list_gui2->setPositionInputField("[lobj][".$a_objective_id."][".$chapter['lm_ass_id']."]", - sprintf('%d', $chapter['position']*10)); - } - - $sub_item_html = $item_list_gui2->getListItemHTML($item['ref_id'], - $item['obj_id'], $title, $item['description']); - - // #13381 - use materials order - $sort_key = str_pad($chapter['position'], 5, 0, STR_PAD_LEFT)."_".strtolower($title)."_".$chapter['lm_ass_id']; - $sort_content[$sort_key] = $sub_item_html; - } - } - - $this->rendered_items[$item['child']] = true; - - if($lm_ass_id = $objectives_lm_obj->isAssigned($item['ref_id'], true)) - { - if($is_order) - { - $item_list_gui2->setPositionInputField("[lobj][".$a_objective_id."][".$lm_ass_id."]", - sprintf('%d', $sort_map[$lm_ass_id]*10)); - } - - $sub_item_html = $item_list_gui2->getListItemHTML($item['ref_id'], - $item['obj_id'], $item['title'], $item['description']); - - // #13381 - use materials order - $sort_key = str_pad($sort_map[$lm_ass_id], 5, 0, STR_PAD_LEFT)."_".strtolower($item['title'])."_".$lm_ass_id; - $sort_content[$sort_key] = $sub_item_html; - } - } - - if($this->getDetailsLevel($a_objective_id) == self::DETAILS_ALL) - { - $this->objective_list_gui->enableCommands(false); - } - else - { - $this->objective_list_gui->enableCommands(true); - } - - if($is_order) - { - $this->objective_list_gui->setPositionInputField("[lobj][".$a_objective_id."][0]", - $objective->__getPosition()*10); - } - - ksort($sort_content); - - if(!$a_accordion) - { - foreach($sort_content as $sub_item_html) - { - $this->objective_list_gui->addSubItemHTML($sub_item_html); - } - - return $this->objective_list_gui->getObjectiveListItemHTML( - 0, - $a_objective_id, - $objective->getTitle(), - $objective->getDescription(), - ($is_manage || $is_order)); - } - else - { - $acc_content = $sort_content; - - $initial_shown = false; - $initial_test_ref_id = $this->getTestAssignments()->getTestByObjective($a_objective_id, ilLOSettings::TYPE_TEST_INITIAL); - $initial_test_obj_id = ilObject::_lookupObjId($initial_test_ref_id); - include_once './Modules/Test/classes/class.ilObjTestAccess.php'; - - if( - $initial_test_obj_id && - $this->getSettings()->hasSeparateInitialTests() && - !ilObjTestAccess::checkCondition($initial_test_obj_id, ilConditionHandler::OPERATOR_FINISHED, '', $ilUser->getId()) - ) - { - $acc_content[] = $this->renderTest( - $this->getTestAssignments()->getTestByObjective($a_objective_id, ilLOSettings::TYPE_TEST_INITIAL), - $a_objective_id, - true, - false, - $a_lo_result); - $initial_shown = TRUE; - } - elseif($this->getSettings()->hasSeparateQualifiedTests()) - { - $acc_content[] = $this->renderTest( - $this->getTestAssignments()->getTestByObjective($a_objective_id, ilLOSettings::TYPE_TEST_QUALIFIED), - $a_objective_id, - false, - false, - $a_lo_result); - } - - - /* - if($this->loc_settings->getInitialTest() && - $this->loc_settings->getType() == ilLOSettings::LOC_INITIAL_SEL && - !$a_lo_risult["initial_status"]) - { - $acc_content[] = $this->renderTest($this->loc_settings->getInitialTest(), $a_objective_id, true, false, $a_lo_result); - $initial_shown = true; - } - if(!$initial_shown && - $this->loc_settings->getQualifiedTest() && - $this->loc_settings->isQualifiedTestPerObjectiveVisible()) - { - $acc_content[] = $this->renderTest($this->loc_settings->getQualifiedTest(), $a_objective_id, false, false, $a_lo_result); - } - */ - - $co_page = null; - include_once("./Services/COPage/classes/class.ilPageUtil.php"); - if(ilPageUtil::_existsAndNotEmpty("lobj", $objective->getObjectiveId())) - { - $a_has_lo_page = true; - - include_once 'Modules/Course/classes/Objectives/class.ilLOPageGUI.php'; - $page_gui = new ilLOPageGUI($objective->getObjectiveId()); - - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $page_gui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId(0)); - $page_gui->setPresentationTitle(""); - $page_gui->setTemplateOutput(false); - $page_gui->setHeader(""); - - $co_page = "
          ".$page_gui->showPage()."
          "; - } - - $a_accordion->addItem( - $this->buildAccordionTitle($objective, $a_lo_result), - $co_page. - $this->buildAccordionContent($acc_content), - (isset($_GET["oobj"]) && (int)$_GET["oobj"] == $objective->getObjectiveId()) - ); - } - } - - /** - * init details - * - * @access protected - * @param - * @return - */ - protected function initDetails() - { - $ilUser = $this->user; - - // no details - return; - - } - - protected function initTestAssignments() - { - include_once './Modules/Course/classes/Objectives/class.ilLOTestAssignments.php'; - $this->test_assignments = ilLOTestAssignments::getInstance($this->getContainerObject()->getId()); - } - - /** - * Parse learning objective results. - * @return type - */ - protected function parseLOUserResults() - { - $ilUser = $this->user; - - $res = array(); - - include_once "Modules/Course/classes/Objectives/class.ilLOTestAssignments.php"; - $lo_ass = ilLOTestAssignments::getInstance($this->getContainerObject()->getId()); - - include_once "Modules/Course/classes/Objectives/class.ilLOUserResults.php"; - $lur = new ilLOUserResults($this->getContainerObject()->getId(), $ilUser->getId()); - foreach($lur->getCourseResultsForUserPresentation() as $objective_id => $types) - { - // show either initial or qualified for objective - if(isset($types[ilLOUserResults::TYPE_INITIAL])) - { - $initial_status = $types[ilLOUserResults::TYPE_INITIAL]["status"]; - } - - // qualified test has priority - if(isset($types[ilLOUserResults::TYPE_QUALIFIED])) - { - $result = $types[ilLOUserResults::TYPE_QUALIFIED]; - $result["type"] = ilLOUserResults::TYPE_QUALIFIED; - $result["initial"] = $types[ilLOUserResults::TYPE_INITIAL]; - } - else - { - $result = $types[ilLOUserResults::TYPE_INITIAL]; - $result["type"] = ilLOUserResults::TYPE_INITIAL; - } - - $result["initial_status"] = $initial_status; - - $result["itest"] = $lo_ass->getTestByObjective($objective_id, ilLOSettings::TYPE_TEST_INITIAL); - $result["qtest"] = $lo_ass->getTestByObjective($objective_id, ilLOSettings::TYPE_TEST_QUALIFIED); - - $res[$objective_id] = $result; - } - - return $res; - } - - /** - * Render progress bar(s) - * - * @param int $a_perc_result - * @param int $a_perc_limit - * @param string $a_css - * @param string $a_caption - * @param string $a_url - * @param string $a_tt_id - * @param string $a_tt_txt - * @param string $a_next_step - * @param string $a_sub (html) - * @param int $a_sub_style - * @return type - */ - public static function renderProgressBar($a_perc_result = null, - $a_perc_limit = null, - $a_css = null, - $a_caption = null, - $a_url = null, - $a_tt_id = null, - $a_tt_txt = null, - $a_next_step = null, - $a_sub = false, - $a_sub_style = 30) - { - global $DIC; - - $tpl = new ilTemplate("tpl.objective_progressbar.html", true, true, "Services/Container"); - - if($a_perc_result !== null) - { - $tpl->setCurrentBlock("statusbar_bl"); - $tpl->setVariable("PERC_STATUS", $a_perc_result); - $tpl->setVariable("PERC_WIDTH", $a_perc_result); - $tpl->setVariable("PERC_COLOR", $a_css); - if($a_perc_limit) - { - // :TODO: magic? - $limit_pos = (99-(int)$a_perc_limit)*-1; - $tpl->setVariable("LIMIT_POS", $limit_pos); - } - if($a_tt_txt && - $a_tt_id) - { - $tpl->setVariable("TT_ID", $a_tt_id); - } - $tpl->parseCurrentBlock(); - } - - if($a_caption) - { - if($a_url) - { - include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; - $button = ilLinkButton::getInstance(); - $button->setCaption($a_caption, false); - $button->setUrl($a_url); - - $tpl->setCurrentBlock("statustxt_bl"); - $tpl->setVariable("TXT_PROGRESS_STATUS", $button->render()); - $tpl->parseCurrentBlock(); - } - else - { - $tpl->setCurrentBlock("statustxt_no_link_bl"); - $tpl->setVariable("TXT_PROGRESS_STATUS_NO_LINK", $a_caption); - $tpl->parseCurrentBlock(); - } - } - - - if($a_next_step) - { - $tpl->setCurrentBlock("nstep_bl"); - $tpl->setVariable("TXT_NEXT_STEP", $a_next_step); - $tpl->parseCurrentBlock(); - } - - if($a_tt_id && - $a_tt_txt) - { - include_once("./Services/UIComponent/Tooltip/classes/class.ilTooltipGUI.php"); - ilTooltipGUI::addTooltip($a_tt_id, $a_tt_txt); - } - - if($a_sub) - { - $tpl->setVariable("SUB_STYLE", ' style="padding-left: '.$a_sub_style.'px;"'); - $tpl->setVariable("SUB_INIT", $a_sub); - } - - return $tpl->get(); - } - - /** - * Render progress bar(s) - * - * @param int $a_perc_result - * @param int $a_perc_limit - * @param int $a_compare_value - * @param string $a_caption - * @param string $a_url - * @param string $a_tt_id - * @param string $a_tt_txt - * @param string $a_next_step - * @param string $a_sub (html) - * @param int $a_sub_style - * @param string $a_main_text - * @param string $a_required_text - * @return type - */ - public static function renderProgressMeter($a_perc_result = null, - $a_perc_limit = null, - $a_compare_value = null, - $a_caption = null, - $a_url = null, - $a_tt_id = null, - $a_tt_txt = null, - $a_next_step = null, - $a_sub = false, - $a_sub_style = 30, - $a_main_text = '', - $a_required_text = '') - - { - global $DIC; - - $tpl = new ilTemplate("tpl.objective_progressmeter.html", true, true, "Services/Container"); - - $lng = $DIC->language(); - $lng->loadLanguageModule('crs'); - - - - if(is_numeric($a_perc_result)) - { - $uiFactory = $DIC->ui()->factory(); - $uiRenderer = $DIC->ui()->renderer(); - - /* - $pMeter = $uiFactory->chart()->progressMeter()->standard( - 100, - (int) $a_perc_result, - (int) $a_perc_limit - ); - */ - - $pMeter = $uiFactory->chart()->progressMeter()->standard( - 100, - (int) $a_perc_result, - (int) $a_perc_limit, - (int) $a_compare_value - ); - - if(strlen($a_main_text)) - { - #$pMeter = $pMeter->withMainText($a_main_text); - } - if(strlen($a_required_text)) - { - #$pMeter = $pMeter->withRequiredText($a_required_text); - } - $tpl->setVariable('PROGRESS_METER', $uiRenderer->render($pMeter)); - } - - /* - if($a_caption) - { - if($a_url) - { - include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; - $button = ilLinkButton::getInstance(); - $button->setCaption($a_caption, false); - $button->setUrl($a_url); - - $tpl->setCurrentBlock("statustxt_bl"); - $tpl->setVariable("TXT_PROGRESS_STATUS", $button->render()); - $tpl->parseCurrentBlock(); - } - else - { - $tpl->setCurrentBlock("statustxt_no_link_bl"); - $tpl->setVariable("TXT_PROGRESS_STATUS_NO_LINK", $a_caption); - $tpl->parseCurrentBlock(); - } - } - */ - - if($a_tt_id && - $a_tt_txt) - { - include_once("./Services/UIComponent/Tooltip/classes/class.ilTooltipGUI.php"); - ilTooltipGUI::addTooltip($a_tt_id, $a_tt_txt); - } - - if($a_sub) - { - $tpl->setVariable("SUB_STYLE", ' style="padding-left: '.$a_sub_style.'px;"'); - $tpl->setVariable("SUB_INIT", $a_sub); - } - - return $tpl->get(); - } - - /** - * Get objective result summary - * - * @param bool - * @param int - * @param array - * @todo refactor to presentation class - */ - public static function getObjectiveResultSummary($a_has_initial_test, $a_objective_id, $a_lo_result) - { - global $DIC; - - $lng = $DIC->language(); - $lng->loadLanguageModule('crs'); - - $is_qualified = - ($a_lo_result["type"] == ilLOUserResults::TYPE_QUALIFIED); - $is_qualified_initial = - ( - $a_lo_result['type'] == ilLOUserResults::TYPE_INITIAL && - ilLOSettings::getInstanceByObjId($a_lo_result['course_id'])->isInitialTestQualifying() - ); - $has_completed = - ($a_lo_result["status"] == ilLOUserResults::STATUS_COMPLETED); - - $next_step = $progress_txt = $bar_color = $test_url = $initial_sub = null; - - if( - $is_qualified || - $is_qualified_initial) - { - if($has_completed) - { - $next_step = $lng->txt("crs_loc_progress_objective_complete"); - } - else - { - $next_step = $lng->txt("crs_loc_progress_do_qualifying_again"); - } - } - // initial test - else - { - if($a_lo_result["status"]) - { - $next_step = - $has_completed ? - $lng->txt("crs_loc_progress_do_qualifying") : - $lng->txt("crs_loc_suggested"); - } - else - { - $next_step = (bool) $a_has_initial_test ? - $lng->txt("crs_loc_progress_no_result_do_initial") : - $lng->txt("crs_loc_progress_no_result_no_initial"); - } - } - return $next_step; - } - - /** - * Render progressbar(s) for given objective and result data - * - * @param bool $a_has_initial_test - * @param int $a_objective_id - * @param bool $a_lo_result - * @param bool $a_list_mode - * @param bool $a_sub - * @param mixed $a_tt_suffix - * @return string - */ - public static function buildObjectiveProgressBar($a_has_initial_test, $a_objective_id, array $a_lo_result, $a_list_mode = false, $a_sub = false, $a_tt_suffix = null) - { - global $DIC; - - $lng = $DIC->language(); - $lng->loadLanguageModule('crs'); - - // tooltip (has to be unique!) - - $tooltip_id = "crsobjtvusr_".$a_objective_id."_".$a_lo_result["type"]."_".((int)$a_sub); - if($a_tt_suffix !== null) - { - $tooltip_id .= "_".$a_tt_suffix; - } - - $tt_txt = sprintf( - $lng->txt("crs_loc_tt_info"), - $a_lo_result["result_perc"], - $a_lo_result["limit_perc"] - ); - - - include_once './Modules/Course/classes/Objectives/class.ilLOUtils.php'; - include_once './Modules/Course/classes/Objectives/class.ilLOSettings.php'; - - $is_qualified = ($a_lo_result["type"] == ilLOUserResults::TYPE_QUALIFIED); - $is_qualified_initial = ($a_lo_result['type'] == ilLOUserResults::TYPE_INITIAL && - ilLOSettings::getInstanceByObjId($a_lo_result['course_id'])->isInitialTestQualifying()); - $has_completed = ($a_lo_result["status"] == ilLOUserResults::STATUS_COMPLETED); - - $next_step = $progress_txt = $bar_color = $test_url = $initial_sub = null; - - $compare_value = null; - - if($is_qualified || - $is_qualified_initial) - { - $progress_txt = $lng->txt("crs_loc_progress_result_qtest"); - $tt_txt = $lng->txt("crs_loc_tab_qtest").": ".$tt_txt; - - if($has_completed) - { - $next_step = $lng->txt("crs_loc_progress_objective_complete"); - $bar_color = "ilCourseObjectiveProgressBarCompleted"; - - // render 2nd progressbar if there is also an initial test - if($is_qualified && - $a_has_initial_test && - is_array($a_lo_result["initial"])) - { - $a_lo_result["initial"]["itest"] = $a_lo_result["itest"]; - - // force list mode to get rid of next step - #$initial_sub = self::buildObjectiveProgressBar(true, $a_objective_id, $a_lo_result["initial"], true, true, $a_tt_suffix); - $compare_value = $a_lo_result['initial']['result_perc']; - } - } - else - { - $next_step = $lng->txt("crs_loc_progress_do_qualifying_again"); - $bar_color = "ilCourseObjectiveProgressBarFailed"; - } - } - // initial test - else - { - if($a_lo_result["status"]) - { - $progress_txt = $lng->txt("crs_loc_progress_result_itest"); - $tt_txt = $lng->txt("crs_loc_tab_itest").": ".$tt_txt; - - $bar_color = "ilCourseObjectiveProgressBarNeutral"; - $next_step = $has_completed - ? $lng->txt("crs_loc_progress_do_qualifying") - : $lng->txt("crs_loc_suggested"); - } - // not attempted: no progress bar - else - { - $next_step = (bool)$a_has_initial_test - ? $lng->txt("crs_loc_progress_no_result_do_initial") - : $lng->txt("crs_loc_progress_no_result_no_initial"); - } - } - - // link to test results - // - first try to fetch a link for qualifying test results - if($a_lo_result["qtest"]) - { - $test_url = ilLOUtils::getTestResultLinkForUser($a_lo_result["qtest"], $a_lo_result["user_id"]); - } - // - when no qualifiying test results link was fetched, try for initial test - if(!$test_url && $a_lo_result["itest"]) - { - $test_url = ilLOUtils::getTestResultLinkForUser($a_lo_result["itest"], $a_lo_result["user_id"]); - } - - $main_text = $lng->txt('crs_loc_itest_info'); - if($a_lo_result['type'] == ilLOSettings::TYPE_TEST_QUALIFIED) - { - $main_text = $lng->txt('crs_loc_qtest_info'); - } - - - - return self::renderProgressMeter( - $a_lo_result["result_perc"], - $a_lo_result["limit_perc"], - $compare_value, - $progress_txt, - $test_url, - $tooltip_id, - $tt_txt, - $a_list_mode - ? null - : $next_step, - $initial_sub, - $a_list_mode - ? 30 - : 10, - $main_text, - $lng->txt('crs_lobj_pm_min_goal') - ); - } - - /** - * @param \ilCourseObjective $a_objective - * @param array|null $a_lo_result - * @return string - * @throws \ilTemplateException - */ - protected function buildAccordionTitle(ilCourseObjective $a_objective, array $a_lo_result = null) - { - global $DIC; - - $renderer = $DIC->ui()->renderer(); - $ui_factory = $DIC->ui()->factory(); - - $tpl = new ilTemplate("tpl.objective_accordion_title.html", true, true, "Services/Container"); - - if($a_lo_result) - { - $tpl->setVariable("PROGRESS_BAR", self::buildObjectiveProgressBar( - (bool) $this->loc_settings->worksWithInitialTest(), - $a_objective->getObjectiveId(), - $a_lo_result) - ); - } - - $tpl->setVariable("TITLE", $this->lng->txt("crs_loc_learning_objective").": ".trim($a_objective->getTitle())); - $tpl->setVariable("DESCRIPTION", nl2br(trim($a_objective->getDescription()))); - - $this->logger->dump($a_lo_result); - - $initial_res = null; - $initial_lim = null; - if($this->loc_settings->worksWithInitialTest()) { - if(array_key_exists('initial', $a_lo_result)) { - $initial_res = (int) $a_lo_result['initial']['result_perc']; - $initial_lim = (int) $a_lo_result['initial']['limit_perc']; - } - if( - $a_lo_result['type'] == ilLOUserResults::TYPE_INITIAL && - isset($a_lo_result['result_perc']) - ) { - $initial_res = (int) $a_lo_result['result_perc']; - $initial_lim = (int) $a_lo_result['limit_perc']; - } - } - - if($initial_res !== null) { - - $link = \ilLOUtils::getTestResultLinkForUser( - $a_lo_result["itest"], - $a_lo_result["user_id"] - ); - - if(strlen($link)) { - $tpl->setCurrentBlock('i_with_link'); - $tpl->setVariable( - 'IBTN', - $renderer->render( - $ui_factory->button()->shy( - $this->lng->txt('crs_objective_result_details'), - $link - ) - ) - ); - $tpl->parseCurrentBlock(); - } - - - $tpl->setCurrentBlock('res_initial'); - $tpl->setVariable( - 'IRESULT', - sprintf( - $this->lng->txt('crs_objective_result_summary_initial'), - (int) $initial_res.'%', - (int) $initial_lim.'%' - ) - ); - $tpl->parseCurrentBlock(); - } - - $qual_res = null; - $qual_lim = null; - - if($a_lo_result['type'] == ilLOUserResults::TYPE_QUALIFIED) { - - $qual_res = (int) $a_lo_result['result_perc']; - $qual_lim = (int) $a_lo_result['limit_perc']; - } - - if($qual_res !== null) { - - $link = \ilLOUtils::getTestResultLinkForUser( - $a_lo_result["qtest"], - $a_lo_result["user_id"] - ); - - if(strlen($link)) { - $tpl->setCurrentBlock('q_with_link'); - $tpl->setVariable( - 'QBTN', - $renderer->render( - $ui_factory->button()->shy( - $this->lng->txt('crs_objective_result_details'), - $link - ) - ) - ); - $tpl->parseCurrentBlock(); - } - $tpl->setCurrentBlock('res_qualifying'); - $tpl->setVariable( - 'QRESULT', - sprintf( - $this->lng->txt('crs_objective_result_summary_qualifying'), - (int) $qual_res.'%', - (int) $qual_lim.'%' - ) - ); - $tpl->parseCurrentBlock(); - } - - $this->logger->dump($a_lo_result); - - - $summary = self::getObjectiveResultSummary( - (bool) $this->loc_settings->worksWithInitialTest(), - $a_objective->getObjectiveId(), - $a_lo_result - ); - if(strlen($summary)) { - $tpl->setCurrentBlock('objective_summary'); - $tpl->setVariable('SUMMARY_TXT', $summary); - $tpl->parseCurrentBlock(); - } - - // #15510 - $tpl->setVariable("ANCHOR_ID", "objtv_acc_".$a_objective->getObjectiveId()); - - return $tpl->get(); - } - - protected function buildAccordionContent(array $a_items) - { - $tpl = new ilTemplate("tpl.objective_accordion_content.html", true, true, "Services/Container"); - foreach($a_items as $item) - { - $tpl->setCurrentBlock("items_bl"); - $tpl->setVariable("ITEM", $item); - $tpl->parseCurrentBlock(); - } - return $tpl->get(); - } - - /** - * show action button - * - * @access protected - * @param - * @return - */ - protected function showButton($a_cmd,$a_text,$a_target = '', $a_id = "") - { - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - - // #11842 - $ilToolbar->addButton($a_text, - $ilCtrl->getLinkTarget($this->getContainerGUI(),$a_cmd), - $a_target, "", '', $a_id); - } + /** + * @var \ilLogger |null + */ + private $logger = null; + + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + protected $force_details = 0; + + /** + * @var \ilLOSettings + */ + protected $loc_settings; + + const MATERIALS_TESTS = 1; + const MATERIALS_OTHER = 2; + + private $output_html = ''; + + private $test_assignments = null; + + /** + * Constructor + * + * @access public + * @param object container gui object + * @return + */ + public function __construct($a_container_gui) + { + global $DIC; + + $this->tabs = $DIC->tabs(); + $this->access = $DIC->access(); + $this->user = $DIC->user(); + $this->settings = $DIC->settings(); + $this->ctrl = $DIC->ctrl(); + $this->toolbar = $DIC->toolbar(); + $lng = $DIC->language(); + + $this->logger = $DIC->logger()->crs(); + + $this->lng = $lng; + parent::__construct($a_container_gui); + + $this->initDetails(); + $this->initTestAssignments(); + } + + /** + * Get test assignments object + * @return ilLOTestAssignments + */ + public function getTestAssignments() + { + return $this->test_assignments; + } + + /** + * @return \ilLOSettings + */ + public function getSettings() + { + return $this->loc_settings; + } + + + + /** + * get details level + * + * @access public + * @param + * @return + */ + public function getDetailsLevel($a_objective_id) + { + // no details anymore + return self::DETAILS_ALL; + } + + /** + * Impementation of abstract method getMainContent + * + * @access public + * @return + */ + public function getMainContent() + { + $lng = $this->lng; + $ilTabs = $this->tabs; + $ilAccess = $this->access; + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + + // see bug #7452 + // $ilTabs->setSubTabActive($this->getContainerObject()->getType().'_content'); + + + include_once 'Services/Object/classes/class.ilObjectListGUIFactory.php'; + + $tpl = new ilTemplate("tpl.container_page.html", true, true, "Services/Container"); + + if ($ilAccess->checkAccess('write', '', $this->getContainerObject()->getRefId())) { + // check for results + include_once './Modules/Course/classes/Objectives/class.ilLOUserResults.php'; + if (ilLOUserResults::hasResults($this->getContainerObject()->getId(), $ilUser->getId())) { + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $ilToolbar = new ilToolbarGUI(); + $ilToolbar->addButton( + $lng->txt('crs_reset_results'), + $ilCtrl->getLinkTargetByClass(get_class($this->getContainerGUI()), 'reset') + ); + } + } + + // Feedback + // @todo + // $this->__showFeedBack(); + + $this->items = $this->getContainerObject()->getSubItems($this->getContainerGUI()->isActiveAdministrationPanel()); + + $is_manage = $this->getContainerGUI()->isActiveAdministrationPanel(); + $is_order = $this->getContainerGUI()->isActiveOrdering(); + + include_once './Modules/Course/classes/Objectives/class.ilLOSettings.php'; + $this->loc_settings = ilLOSettings::getInstanceByObjId($this->getContainerObject()->getId()); + + $this->initRenderer(); + + if (!$is_manage && !$is_order) { + // currently inactive + // $this->showStatus($tpl); + } + if (!$is_manage) { + $this->showObjectives($tpl, $is_order); + + // $this->showMaterials($tpl,self::MATERIALS_TESTS, false, !$is_order); + + // check for results + include_once './Modules/Course/classes/Objectives/class.ilLOUserResults.php'; + $has_results = ilLOUserResults::hasResults($this->getContainerObject()->getId(), $ilUser->getId()); + + include_once './Modules/Test/classes/class.ilObjTestAccess.php'; + $tst_obj_id = ilObject::_lookupObjId($this->loc_settings->getInitialTest()); + + if ( + $this->loc_settings->getInitialTest() && + $this->loc_settings->isGeneralInitialTestVisible() && + !$this->loc_settings->isInitialTestStart() && + !ilObjTestAccess::checkCondition($tst_obj_id, ilConditionHandler::OPERATOR_FINISHED, '', $ilUser->getId()) + ) { + $this->output_html .= $this->renderTest($this->loc_settings->getInitialTest(), null, true, true); + } elseif ( + $this->loc_settings->getQualifiedTest() && + $this->loc_settings->isGeneralQualifiedTestVisible() + ) { + $this->output_html .= $this->renderTest($this->loc_settings->getQualifiedTest(), null, false, true); + } + + $this->showMaterials($tpl, self::MATERIALS_OTHER, false, !$is_order); + } else { + $this->showMaterials($tpl, null, $is_manage); + } + + // reset results by setting or for admins + include_once './Modules/Course/classes/Objectives/class.ilLOSettings.php'; + if ( + ilLOSettings::getInstanceByObjId($this->getContainerObject()->getId())->isResetResultsEnabled() or + $ilAccess->checkAccess('write', '', $this->getContainerObject()->getRefId()) + ) { + if ($has_results) { + if (!$is_manage && !$is_order) { + $this->showButton('askReset', $lng->txt('crs_reset_results')); + } + } + } + + $tpl->setVariable('CONTAINER_PAGE_CONTENT', $this->output_html); + + return $tpl->get(); + } + + /** + * show status + * + * @access public + * @param + * @return + */ + public function showStatus($tpl) + { + $ilUser = $this->user; + $lng = $this->lng; + + include_once('./Modules/Course/classes/class.ilCourseObjectiveResultCache.php'); + + $status = ilCourseObjectiveResultCache::getStatus($ilUser->getId(), $this->getContainerObject()->getId()); + if ($status == IL_OBJECTIVE_STATUS_EMPTY) { + return; + } + $info_tpl = new ilTemplate('tpl.crs_objectives_view_info_table.html', true, true, 'Modules/Course'); + $info_tpl->setVariable("INFO_STRING", $lng->txt('crs_objectives_info_' . $status)); + + $this->output_html .= $info_tpl->get(); + } + + /** + * show objectives + * + * @access public + * @param object $tpl template object + * @return + */ + public function showObjectives($a_tpl, $a_is_order = false) + { + $lng = $this->lng; + $ilSetting = $this->settings; + $tpl = $this->tpl; + + $this->clearAdminCommandsDetermination(); + + // get embedded blocks + $has_container_page = false; + if (!$a_is_order) { + $output_html = $this->getContainerGUI()->getContainerPageHTML(); + if ($output_html != "") { + $has_container_page = true; + $this->output_html .= $this->insertPageEmbeddedBlocks($output_html); + } + unset($output_html); + } + + // All objectives + include_once './Modules/Course/classes/class.ilCourseObjective.php'; + if (!count($objective_ids = ilCourseObjective::_getObjectiveIds($this->getContainerObject()->getId(), true))) { + return false; + } + + include_once('./Modules/Course/classes/class.ilCourseObjectiveListGUI.php'); + $this->objective_list_gui = new ilCourseObjectiveListGUI(); + $this->objective_list_gui->setContainerObject($this->getContainerGUI()); + if ($ilSetting->get("icon_position_in_lists") == "item_rows") { + $this->objective_list_gui->enableIcon(true); + } + + $acc = null; + if (!$a_is_order) { + include_once "Services/Accordion/classes/class.ilAccordionGUI.php"; + $acc = new ilAccordionGUI(); + $acc->setUseSessionStorage(true); + $acc->setAllowMultiOpened(true); + $acc->setBehaviour(ilAccordionGUI::FIRST_OPEN); + $acc->setId("crsobjtv_" . $this->container_obj->getId()); + } else { + $this->renderer->addCustomBlock('lobj', $lng->txt('crs_objectives')); + } + + $lur_data = $this->parseLOUserResults(); + + $has_initial = ilLOSettings::getInstanceByObjId($this->container_obj->getId())->worksWithInitialTest(); + + $has_lo_page = false; + $obj_cnt = 0; + foreach ($objective_ids as $objective_id) { + include_once './Modules/Course/classes/Objectives/class.ilLOUtils.php'; + if ( + $has_initial && + ( + !isset($lur_data[$objective_id]) or + ilLOUtils::hasActiveRun( + $this->container_obj->getId(), + ilLOSettings::getInstanceByObjId($this->container_obj->getId())->getInitialTest(), + $objective_id + ) + ) + ) { + $lur_data[$objective_id] = array("type"=>ilLOSettings::TYPE_TEST_INITIAL); + } + + if ($html = $this->renderObjective($objective_id, $has_lo_page, $acc, $lur_data[$objective_id])) { + $this->renderer->addItemToBlock('lobj', 'lobj', $objective_id, $html); + } + $obj_cnt++; + } + + // buttons for showing/hiding all objectives + if (!$a_is_order && $obj_cnt > 1) { + $this->showButton("", $lng->txt("crs_show_all_obj"), "", "crs_show_all_obj_btn"); + $this->showButton("", $lng->txt("crs_hide_all_obj"), "", "crs_hide_all_obj_btn"); + $acc->setShowAllElement("crs_show_all_obj_btn"); + $acc->setHideAllElement("crs_hide_all_obj_btn"); + } + + if (!$has_container_page && $has_lo_page) { + // add core co page css + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath(0) + ); + $tpl->setCurrentBlock("SyntaxStyle"); + $tpl->setVariable( + "LOCATION_SYNTAX_STYLESHEET", + ilObjStyleSheet::getSyntaxStylePath() + ); + $tpl->parseCurrentBlock(); + } + + // order/block + if ($a_is_order) { + $this->addFooterRow(); + + $this->output_html .= $output_html . $this->renderer->getHTML(); + + $this->renderer->resetDetails(); + } + // view/accordion + else { + $this->output_html .= "
          " . $acc->getHTML() . "
          "; + } + } + + /** + * add footer row + * + * @access public + * @param + * @return + */ + public function addFooterRow() + { + // no details + return; + + /* + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $this->getContainerObject()->getRefId()); + $ilCtrl->setParameterByClass("ilrepositorygui", "details_level", "1"); + $url = $ilCtrl->getLinkTargetByClass("ilrepositorygui", ""); + $this->renderer->addDetailsLevel(2, $url, ($this->details_level == self::DETAILS_TITLE)); + + $ilCtrl->setParameterByClass("ilrepositorygui", "details_level", "2"); + $url = $ilCtrl->getLinkTargetByClass("ilrepositorygui", ""); + $this->renderer->addDetailsLevel(3, $url, ($this->details_level == self::DETAILS_ALL)); + + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + */ + } + + protected function renderTest($a_test_ref_id, $a_objective_id, $a_is_initial = false, $a_add_border = false, $a_lo_result = array()) + { + global $DIC; + + $tree = $DIC->repositoryTree(); + + $node_data = []; + if ($a_test_ref_id) { + $node_data = $tree->getNodeData($a_test_ref_id); + } + if (!$node_data['child']) { + return ''; + } + + // update ti + if ($a_objective_id) { + if ($a_is_initial) { + $title = sprintf($this->lng->txt('crs_loc_itst_for_objective'), ilCourseObjective::lookupObjectiveTitle($a_objective_id)); + } else { + $title = sprintf($this->lng->txt('crs_loc_qtst_for_objective'), ilCourseObjective::lookupObjectiveTitle($a_objective_id)); + } + $node_data['objective_id'] = $a_objective_id; + $node_data['objective_status'] = + ( + $a_lo_result['status'] == ilLOUserResults::STATUS_COMPLETED ? + false : + false + ); + } else { + $obj_id = ilObject::_lookupObjId($a_test_ref_id); + $title = ilObject::_lookupTitle($obj_id); + + $title .= ( + ' (' . + ( + $a_is_initial + ? $this->lng->txt('crs_loc_itest_info') + : $this->lng->txt('crs_loc_qtest_info') + ) . + ')' + ); + $node_data['objective_id'] = 0; + } + + $node_data['title'] = $title; + + return "
          " . $this->renderItem($node_data) . "
          "; + } + + /** + * Show all other (no assigned tests, no assigned materials) materials + * + * @access public + * @param object $tpl template object + * @return void + */ + public function showMaterials($a_tpl, $a_mode = null, $a_is_manage = false, $a_as_accordion = false) + { + $ilAccess = $this->access; + $lng = $this->lng; + + $this->clearAdminCommandsDetermination(); + + if (is_array($this->items["_all"])) { + $this->objective_map = $this->buildObjectiveMap(); + + // all rows + $item_r = array(); + + $position = 1; + foreach ($this->items["_all"] as $k => $item_data) { + if ($a_mode == self::MATERIALS_TESTS and $item_data['type'] != 'tst') { + continue; + } + if ($item_data['type'] == 'itgr') { + continue; + } + if (!$a_is_manage) { + // if test object is qualified or initial do not show here + include_once './Modules/Course/classes/Objectives/class.ilLOTestAssignments.php'; + include_once './Modules/Course/classes/Objectives/class.ilLOSettings.php'; + $assignments = ilLOTestAssignments::getInstance($this->getContainerObject()->getId()); + if ($assignments->getTypeByTest($item_data['child']) != ilLOSettings::TYPE_TEST_UNDEFINED) { + continue; + } + } + + if ($this->rendered_items[$item_data["child"]] !== true && + !$this->renderer->hasItem($item_data["child"])) { + $this->rendered_items[$item_data['child']] = true; + + // TODO: Position (DONE ?) + $html = $this->renderItem($item_data, $position++, $a_mode == self::MATERIALS_TESTS ? false : true); + if ($html != "") { + $item_r[] = array("html" => $html, "id" => $item_data["child"], "type" => $item_data["type"]); + } + } + } + + // if we have at least one item, output the block + if (count($item_r) > 0) { + if (!$a_as_accordion) { + $pos = 0; + + switch ($a_mode) { + case self::MATERIALS_TESTS: + $block_id = "tst"; + $this->renderer->addTypeBlock($block_id); + break; + + case self::MATERIALS_OTHER: + $block_id = "oth"; + $this->renderer->addCustomBlock($block_id, $lng->txt('crs_other_resources')); + break; + + // manage + default: + $block_id = "all"; + $this->renderer->addCustomBlock($block_id, $lng->txt('content')); + break; + } + + // :TODO: + if ($a_mode != self::MATERIALS_TESTS) { + $pos = $this->getItemGroupsHTML(); + } + + foreach ($item_r as $h) { + if (!$this->renderer->hasItem($h["id"])) { + $this->renderer->addItemToBlock($block_id, $h["type"], $h["id"], $h["html"]); + } + } + + $this->output_html .= $this->renderer->getHTML(); + } else { + switch ($a_mode) { + case self::MATERIALS_TESTS: + $txt = $lng->txt('objs_tst'); + break; + + case self::MATERIALS_OTHER: + $txt = $lng->txt('crs_other_resources'); + break; + } + + include_once "Services/Accordion/classes/class.ilAccordionGUI.php"; + $acc = new ilAccordionGUI(); + $acc->setId("crsobjtvmat" . $a_mode . "_" . $this->container_obj->getId()); + + $acc_content = array(); + foreach ($item_r as $h) { + $acc_content[] = $h["html"]; + } + $acc->addItem($txt, $this->buildAccordionContent($acc_content)); + + $this->output_html .= $acc->getHTML(); + } + } + } + } + + protected function buildObjectiveMap() + { + $objective_map = array(); + include_once './Modules/Course/classes/class.ilCourseObjective.php'; + // begin-patch lok + if (count($objective_ids = ilCourseObjective::_getObjectiveIds($this->getContainerObject()->getId(), true))) { + // end-patch lok + include_once('./Modules/Course/classes/class.ilCourseObjectiveMaterials.php'); + foreach ($objective_ids as $objective_id) { + foreach (ilCourseObjectiveMaterials::_getAssignedMaterials($objective_id) as $mat_ref_id) { + $objective_map["material"][$mat_ref_id][] = $objective_id; + + if (!isset($objective_map["names"][$objective_id])) { + $objective = new ilCourseObjective($this->getContainerObject(), $objective_id); + $objective_map["names"][$objective_id] = $objective->getTitle(); + } + } + } + + // initial/qualifying test + $tst = $this->loc_settings->getInitialTest(); + if ($tst) { + $objective_map["test_i"] = $tst; + } + $tst = $this->loc_settings->getQualifiedTest(); + if ($tst) { + $objective_map["test_q"] = $tst; + } + + // objective test assignments + include_once 'Modules/Course/classes/Objectives/class.ilLOSettings.php'; + include_once 'Modules/Course/classes/Objectives/class.ilLOTestAssignments.php'; + $ass_test = new ilLOTestAssignments($this->getContainerObject()->getId()); + foreach ($ass_test->getAssignmentsByType(ilLOSettings::TYPE_TEST_INITIAL) as $ass) { + $title = ilCourseObjective::lookupObjectiveTitle($ass->getObjectiveId()); + $objective_map["test_ass"][$ass->getTestRefId()][$ass->getAssignmentType()][] = $title; + } + foreach ($ass_test->getAssignmentsByType(ilLOSettings::TYPE_TEST_QUALIFIED) as $ass) { + $title = ilCourseObjective::lookupObjectiveTitle($ass->getObjectiveId()); + $objective_map["test_ass"][$ass->getTestRefId()][$ass->getAssignmentType()][] = $title; + } + } + + return $objective_map; + } + + protected function addItemDetails(ilObjectListGUI $a_item_list_gui, array $a_item) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + $item_ref_id = $a_item["ref_id"]; + + if (is_array($this->objective_map)) { + $details = array(); + if (isset($this->objective_map["material"][$item_ref_id])) { + // #12965 + foreach ($this->objective_map["material"][$item_ref_id] as $objective_id) { + $ilCtrl->setParameterByClass('ilcourseobjectivesgui', 'objective_id', $objective_id); + $url = $ilCtrl->getLinkTargetByClass(array('illoeditorgui', 'ilcourseobjectivesgui'), 'edit'); + $ilCtrl->setParameterByClass('ilcourseobjectivesgui', 'objective_id', ''); + + $details[] = array( + 'desc' => $lng->txt('crs_loc_tab_materials') . ': ', + 'target' => '_top', + 'link' => $url, + 'name' => $this->objective_map["names"][$objective_id] + ); + } + } + if ($this->objective_map["test_i"] == $item_ref_id) { + $ilCtrl->setParameterByClass('illoeditorgui', 'tt', 1); + $details[] = array( + 'desc' => '', + 'target' => '_top', + 'link' => $ilCtrl->getLinkTargetByClass('illoeditorgui', 'testOverview'), + 'name' => $lng->txt('crs_loc_tab_itest') + ); + $ilCtrl->setParameterByClass('illoeditorgui', 'tt', 0); + } + if ($this->objective_map["test_q"] == $item_ref_id) { + $ilCtrl->setParameterByClass('illoeditorgui', 'tt', 2); + $details[] = array( + 'desc' => '', + 'target' => '_top', + 'link' => $ilCtrl->getLinkTargetByClass('illoeditorgui', 'testOverview'), + 'name' => $lng->txt('crs_loc_tab_qtest') + ); + $ilCtrl->setParameterByClass('illoeditorgui', 'tt', 0); + } + + // #15367 + if (is_array($this->objective_map["test_ass"][$item_ref_id])) { + foreach ($this->objective_map["test_ass"][$item_ref_id] as $type => $items) { + if ($type == ilLOSettings::TYPE_TEST_INITIAL) { + $caption = $lng->txt('crs_loc_tab_itest'); + $ilCtrl->setParameterByClass('illoeditorgui', 'tt', 1); + } else { + $caption = $lng->txt('crs_loc_tab_qtest'); + $ilCtrl->setParameterByClass('illoeditorgui', 'tt', 2); + } + foreach ($items as $objtv_title) { + $details[] = array( + 'desc' => '', + 'target' => '_top', + 'link' => $ilCtrl->getLinkTargetByClass('illoeditorgui', 'testsOverview'), + 'name' => $caption . " (" . $this->lng->txt("crs_loc_learning_objective") . ": " . $objtv_title . ")" + ); + } + $ilCtrl->setParameterByClass('illoeditorgui', 'tt', 0); + } + } + + if (sizeof($details)) { + $a_item_list_gui->enableItemDetailLinks(true); + $a_item_list_gui->setItemDetailLinks($details, $lng->txt('crs_loc_settings_tbl') . ': '); + } else { + $a_item_list_gui->enableItemDetailLinks(false); + } + } + + // order + if ($this->getContainerGUI()->isActiveOrdering()) { + $a_item_list_gui->enableCommands(true, true); + $a_item_list_gui->enableProperties(false); + } + // view + elseif (!$this->getContainerGUI()->isActiveAdministrationPanel()) { + $a_item_list_gui->enableCommands(true, true); + $a_item_list_gui->enableProperties(false); + } + + if ($a_item['objective_id']) { + $a_item_list_gui->setDefaultCommandParameters(array('objective_id' => $a_item['objective_id'])); + + + if ($this->loc_settings->getQualifiedTest() == $a_item['ref_id']) { + $a_item_list_gui->setConditionTarget($this->getContainerObject()->getRefId(), $a_item['objective_id'], 'lobj'); + // check conditions of target + include_once './Services/Conditions/classes/class.ilConditionHandler.php'; + $fullfilled = ilConditionHandler::_checkAllConditionsOfTarget($this->getContainerObject()->getRefId(), $a_item['objective_id'], 'lobj'); + if (!$fullfilled || $a_item['objective_status']) { + $a_item_list_gui->disableTitleLink(true); + } + } + include_once './Modules/Course/classes/Objectives/class.ilLOUserResults.php'; + $res = ilLOUserResults::lookupResult( + $this->getContainerObject()->getId(), + $ilUser->getId(), + $a_item['objective_id'], + ilLOUserResults::TYPE_QUALIFIED + ); + + $res = $this->updateResult($res, $a_item['ref_id'], $a_item['objective_id'], $ilUser->getId()); + + if ($res['is_final']) { + $a_item_list_gui->disableTitleLink(true); + $a_item_list_gui->enableProperties(true); + $a_item_list_gui->addCustomProperty( + $this->lng->txt('crs_loc_passes_reached'), + '', + true + ); + } elseif ($this->loc_settings->getQualifiedTest() == $a_item['ref_id']) { + include_once './Modules/Course/classes/class.ilCourseObjective.php'; + $poss_pass = ilCourseObjective::lookupMaxPasses($a_item['objective_id']); + + if ($poss_pass) { + $a_item_list_gui->enableProperties(true); + $a_item_list_gui->addCustomProperty( + $this->lng->txt('crs_loc_passes_left'), + (($poss_pass - $res['tries']) > 0) ? ($poss_pass - $res['tries']) : 1, + false + ); + } + } + } + } + + protected function updateResult($a_res, $a_item_ref_id, $a_objective_id, $a_user_id) + { + if ($this->loc_settings->getQualifiedTest() == $a_item_ref_id) { + // Check for existing test run, and decrease tries, reset final if run exists + include_once './Modules/Test/classes/class.ilObjTest.php'; + include_once './Modules/Course/classes/Objectives/class.ilLOSettings.php'; + $active = ilObjTest::isParticipantsLastPassActive( + $a_item_ref_id, + $a_user_id + ); + + if ($active) { + include_once './Modules/Course/classes/Objectives/class.ilLOTestRun.php'; + if (ilLOTestRun::lookupRunExistsForObjective( + ilObject::_lookupObjId($a_item_ref_id), + $a_objective_id, + $a_user_id + )) { + ($a_res['tries'] > 0) ? --$a_res['tries'] : 0; + $a_res['is_final'] = 0; + } + } + } + return $a_res; + } + + /** + * render objective + * + * @access protected + * @param int objective id + * @param bool co page status + * @param ilAccordionGUI $a_accordion + * @param array $a_lo_result + * @return string html + */ + protected function renderObjective($a_objective_id, &$a_has_lo_page, ilAccordionGUI $a_accordion = null, array $a_lo_result = null) + { + $ilUser = $this->user; + $lng = $this->lng; + + include_once('./Modules/Course/classes/class.ilCourseObjective.php'); + $objective = new ilCourseObjective($this->getContainerObject(), $a_objective_id); + + include_once('./Services/Container/classes/class.ilContainerSorting.php'); + include_once('./Services/Object/classes/class.ilObjectActivation.php'); + $items = ilObjectActivation::getItemsByObjective($a_objective_id); + + // sorting is handled by ilCourseObjectiveMaterials + // $items = ilContainerSorting::_getInstance($this->getContainerObject()->getId())->sortSubItems('lobj',$a_objective_id,$items); + + include_once('./Modules/Course/classes/class.ilCourseObjectiveMaterials.php'); + $objectives_lm_obj = new ilCourseObjectiveMaterials($a_objective_id); + + // #13381 - map material assignment to position + $sort_map = array(); + foreach ($objectives_lm_obj->getMaterials() as $item) { + $sort_map[$item["lm_ass_id"]] = $item["position"]; + } + + $is_manage = $this->getContainerGUI()->isActiveAdministrationPanel(); + $is_order = $this->getContainerGUI()->isActiveOrdering(); + + $sort_content = array(); + + foreach ($items as $item) { + if ($this->getDetailsLevel($a_objective_id) < self::DETAILS_ALL) { + continue; + } + + $item_list_gui2 = $this->getItemGUI($item); + $item_list_gui2->enableIcon(true); + + if ($is_order || $a_accordion) { + $item_list_gui2->enableCommands(true, true); + $item_list_gui2->enableProperties(false); + } + + $chapters = $objectives_lm_obj->getChapters(); + if (count($chapters)) { + $has_sections = false; + foreach ($chapters as $chapter) { + if ($chapter['ref_id'] != $item['child']) { + continue; + } + $has_sections = true; + + include_once './Modules/LearningModule/classes/class.ilLMObject.php'; + $title = $item['title'] . + " › " . ilLMObject::_lookupTitle($chapter['obj_id']) . + " (" . $lng->txt('obj_' . $chapter['type']) . ")"; + + $item_list_gui2->setDefaultCommandParameters(array( + "obj_id" => $chapter['obj_id'], + "focus_id" => $chapter['obj_id'], + "focus_return" => $this->container_obj->getRefId())); + + if ($is_order) { + $item_list_gui2->setPositionInputField( + "[lobj][" . $a_objective_id . "][" . $chapter['lm_ass_id'] . "]", + sprintf('%d', $chapter['position']*10) + ); + } + + $sub_item_html = $item_list_gui2->getListItemHTML( + $item['ref_id'], + $item['obj_id'], + $title, + $item['description'] + ); + + // #13381 - use materials order + $sort_key = str_pad($chapter['position'], 5, 0, STR_PAD_LEFT) . "_" . strtolower($title) . "_" . $chapter['lm_ass_id']; + $sort_content[$sort_key] = $sub_item_html; + } + } + + $this->rendered_items[$item['child']] = true; + + if ($lm_ass_id = $objectives_lm_obj->isAssigned($item['ref_id'], true)) { + if ($is_order) { + $item_list_gui2->setPositionInputField( + "[lobj][" . $a_objective_id . "][" . $lm_ass_id . "]", + sprintf('%d', $sort_map[$lm_ass_id]*10) + ); + } + + $sub_item_html = $item_list_gui2->getListItemHTML( + $item['ref_id'], + $item['obj_id'], + $item['title'], + $item['description'] + ); + + // #13381 - use materials order + $sort_key = str_pad($sort_map[$lm_ass_id], 5, 0, STR_PAD_LEFT) . "_" . strtolower($item['title']) . "_" . $lm_ass_id; + $sort_content[$sort_key] = $sub_item_html; + } + } + + if ($this->getDetailsLevel($a_objective_id) == self::DETAILS_ALL) { + $this->objective_list_gui->enableCommands(false); + } else { + $this->objective_list_gui->enableCommands(true); + } + + if ($is_order) { + $this->objective_list_gui->setPositionInputField( + "[lobj][" . $a_objective_id . "][0]", + $objective->__getPosition()*10 + ); + } + + ksort($sort_content); + + if (!$a_accordion) { + foreach ($sort_content as $sub_item_html) { + $this->objective_list_gui->addSubItemHTML($sub_item_html); + } + + return $this->objective_list_gui->getObjectiveListItemHTML( + 0, + $a_objective_id, + $objective->getTitle(), + $objective->getDescription(), + ($is_manage || $is_order) + ); + } else { + $acc_content = $sort_content; + + $initial_shown = false; + $initial_test_ref_id = $this->getTestAssignments()->getTestByObjective($a_objective_id, ilLOSettings::TYPE_TEST_INITIAL); + $initial_test_obj_id = ilObject::_lookupObjId($initial_test_ref_id); + include_once './Modules/Test/classes/class.ilObjTestAccess.php'; + + if ( + $initial_test_obj_id && + $this->getSettings()->hasSeparateInitialTests() && + !ilObjTestAccess::checkCondition($initial_test_obj_id, ilConditionHandler::OPERATOR_FINISHED, '', $ilUser->getId()) + ) { + $acc_content[] = $this->renderTest( + $this->getTestAssignments()->getTestByObjective($a_objective_id, ilLOSettings::TYPE_TEST_INITIAL), + $a_objective_id, + true, + false, + $a_lo_result + ); + $initial_shown = true; + } elseif ($this->getSettings()->hasSeparateQualifiedTests()) { + $acc_content[] = $this->renderTest( + $this->getTestAssignments()->getTestByObjective($a_objective_id, ilLOSettings::TYPE_TEST_QUALIFIED), + $a_objective_id, + false, + false, + $a_lo_result + ); + } + + + /* + if($this->loc_settings->getInitialTest() && + $this->loc_settings->getType() == ilLOSettings::LOC_INITIAL_SEL && + !$a_lo_risult["initial_status"]) + { + $acc_content[] = $this->renderTest($this->loc_settings->getInitialTest(), $a_objective_id, true, false, $a_lo_result); + $initial_shown = true; + } + if(!$initial_shown && + $this->loc_settings->getQualifiedTest() && + $this->loc_settings->isQualifiedTestPerObjectiveVisible()) + { + $acc_content[] = $this->renderTest($this->loc_settings->getQualifiedTest(), $a_objective_id, false, false, $a_lo_result); + } + */ + + $co_page = null; + include_once("./Services/COPage/classes/class.ilPageUtil.php"); + if (ilPageUtil::_existsAndNotEmpty("lobj", $objective->getObjectiveId())) { + $a_has_lo_page = true; + + include_once 'Modules/Course/classes/Objectives/class.ilLOPageGUI.php'; + $page_gui = new ilLOPageGUI($objective->getObjectiveId()); + + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $page_gui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId(0)); + $page_gui->setPresentationTitle(""); + $page_gui->setTemplateOutput(false); + $page_gui->setHeader(""); + + $co_page = "
          " . $page_gui->showPage() . "
          "; + } + + $a_accordion->addItem( + $this->buildAccordionTitle($objective, $a_lo_result), + $co_page . + $this->buildAccordionContent($acc_content), + (isset($_GET["oobj"]) && (int) $_GET["oobj"] == $objective->getObjectiveId()) + ); + } + } + + /** + * init details + * + * @access protected + * @param + * @return + */ + protected function initDetails() + { + $ilUser = $this->user; + + // no details + return; + } + + protected function initTestAssignments() + { + include_once './Modules/Course/classes/Objectives/class.ilLOTestAssignments.php'; + $this->test_assignments = ilLOTestAssignments::getInstance($this->getContainerObject()->getId()); + } + + /** + * Parse learning objective results. + * @return type + */ + protected function parseLOUserResults() + { + $ilUser = $this->user; + + $res = array(); + + include_once "Modules/Course/classes/Objectives/class.ilLOTestAssignments.php"; + $lo_ass = ilLOTestAssignments::getInstance($this->getContainerObject()->getId()); + + include_once "Modules/Course/classes/Objectives/class.ilLOUserResults.php"; + $lur = new ilLOUserResults($this->getContainerObject()->getId(), $ilUser->getId()); + foreach ($lur->getCourseResultsForUserPresentation() as $objective_id => $types) { + // show either initial or qualified for objective + if (isset($types[ilLOUserResults::TYPE_INITIAL])) { + $initial_status = $types[ilLOUserResults::TYPE_INITIAL]["status"]; + } + + // qualified test has priority + if (isset($types[ilLOUserResults::TYPE_QUALIFIED])) { + $result = $types[ilLOUserResults::TYPE_QUALIFIED]; + $result["type"] = ilLOUserResults::TYPE_QUALIFIED; + $result["initial"] = $types[ilLOUserResults::TYPE_INITIAL]; + } else { + $result = $types[ilLOUserResults::TYPE_INITIAL]; + $result["type"] = ilLOUserResults::TYPE_INITIAL; + } + + $result["initial_status"] = $initial_status; + + $result["itest"] = $lo_ass->getTestByObjective($objective_id, ilLOSettings::TYPE_TEST_INITIAL); + $result["qtest"] = $lo_ass->getTestByObjective($objective_id, ilLOSettings::TYPE_TEST_QUALIFIED); + + $res[$objective_id] = $result; + } + + return $res; + } + + /** + * Render progress bar(s) + * + * @param int $a_perc_result + * @param int $a_perc_limit + * @param string $a_css + * @param string $a_caption + * @param string $a_url + * @param string $a_tt_id + * @param string $a_tt_txt + * @param string $a_next_step + * @param string $a_sub (html) + * @param int $a_sub_style + * @return type + */ + public static function renderProgressBar( + $a_perc_result = null, + $a_perc_limit = null, + $a_css = null, + $a_caption = null, + $a_url = null, + $a_tt_id = null, + $a_tt_txt = null, + $a_next_step = null, + $a_sub = false, + $a_sub_style = 30 + ) { + global $DIC; + + $tpl = new ilTemplate("tpl.objective_progressbar.html", true, true, "Services/Container"); + + if ($a_perc_result !== null) { + $tpl->setCurrentBlock("statusbar_bl"); + $tpl->setVariable("PERC_STATUS", $a_perc_result); + $tpl->setVariable("PERC_WIDTH", $a_perc_result); + $tpl->setVariable("PERC_COLOR", $a_css); + if ($a_perc_limit) { + // :TODO: magic? + $limit_pos = (99-(int) $a_perc_limit)*-1; + $tpl->setVariable("LIMIT_POS", $limit_pos); + } + if ($a_tt_txt && + $a_tt_id) { + $tpl->setVariable("TT_ID", $a_tt_id); + } + $tpl->parseCurrentBlock(); + } + + if ($a_caption) { + if ($a_url) { + include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; + $button = ilLinkButton::getInstance(); + $button->setCaption($a_caption, false); + $button->setUrl($a_url); + + $tpl->setCurrentBlock("statustxt_bl"); + $tpl->setVariable("TXT_PROGRESS_STATUS", $button->render()); + $tpl->parseCurrentBlock(); + } else { + $tpl->setCurrentBlock("statustxt_no_link_bl"); + $tpl->setVariable("TXT_PROGRESS_STATUS_NO_LINK", $a_caption); + $tpl->parseCurrentBlock(); + } + } + + + if ($a_next_step) { + $tpl->setCurrentBlock("nstep_bl"); + $tpl->setVariable("TXT_NEXT_STEP", $a_next_step); + $tpl->parseCurrentBlock(); + } + + if ($a_tt_id && + $a_tt_txt) { + include_once("./Services/UIComponent/Tooltip/classes/class.ilTooltipGUI.php"); + ilTooltipGUI::addTooltip($a_tt_id, $a_tt_txt); + } + + if ($a_sub) { + $tpl->setVariable("SUB_STYLE", ' style="padding-left: ' . $a_sub_style . 'px;"'); + $tpl->setVariable("SUB_INIT", $a_sub); + } + + return $tpl->get(); + } + + /** + * Render progress bar(s) + * + * @param int $a_perc_result + * @param int $a_perc_limit + * @param int $a_compare_value + * @param string $a_caption + * @param string $a_url + * @param string $a_tt_id + * @param string $a_tt_txt + * @param string $a_next_step + * @param string $a_sub (html) + * @param int $a_sub_style + * @param string $a_main_text + * @param string $a_required_text + * @return type + */ + public static function renderProgressMeter( + $a_perc_result = null, + $a_perc_limit = null, + $a_compare_value = null, + $a_caption = null, + $a_url = null, + $a_tt_id = null, + $a_tt_txt = null, + $a_next_step = null, + $a_sub = false, + $a_sub_style = 30, + $a_main_text = '', + $a_required_text = '' + ) { + global $DIC; + + $tpl = new ilTemplate("tpl.objective_progressmeter.html", true, true, "Services/Container"); + + $lng = $DIC->language(); + $lng->loadLanguageModule('crs'); + + + + if (is_numeric($a_perc_result)) { + $uiFactory = $DIC->ui()->factory(); + $uiRenderer = $DIC->ui()->renderer(); + + /* + $pMeter = $uiFactory->chart()->progressMeter()->standard( + 100, + (int) $a_perc_result, + (int) $a_perc_limit + ); + */ + + $pMeter = $uiFactory->chart()->progressMeter()->standard( + 100, + (int) $a_perc_result, + (int) $a_perc_limit, + (int) $a_compare_value + ); + + if (strlen($a_main_text)) { + #$pMeter = $pMeter->withMainText($a_main_text); + } + if (strlen($a_required_text)) { + #$pMeter = $pMeter->withRequiredText($a_required_text); + } + $tpl->setVariable('PROGRESS_METER', $uiRenderer->render($pMeter)); + } + + /* + if($a_caption) + { + if($a_url) + { + include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; + $button = ilLinkButton::getInstance(); + $button->setCaption($a_caption, false); + $button->setUrl($a_url); + + $tpl->setCurrentBlock("statustxt_bl"); + $tpl->setVariable("TXT_PROGRESS_STATUS", $button->render()); + $tpl->parseCurrentBlock(); + } + else + { + $tpl->setCurrentBlock("statustxt_no_link_bl"); + $tpl->setVariable("TXT_PROGRESS_STATUS_NO_LINK", $a_caption); + $tpl->parseCurrentBlock(); + } + } + */ + + if ($a_tt_id && + $a_tt_txt) { + include_once("./Services/UIComponent/Tooltip/classes/class.ilTooltipGUI.php"); + ilTooltipGUI::addTooltip($a_tt_id, $a_tt_txt); + } + + if ($a_sub) { + $tpl->setVariable("SUB_STYLE", ' style="padding-left: ' . $a_sub_style . 'px;"'); + $tpl->setVariable("SUB_INIT", $a_sub); + } + + return $tpl->get(); + } + + /** + * Get objective result summary + * + * @param bool + * @param int + * @param array + * @todo refactor to presentation class + */ + public static function getObjectiveResultSummary($a_has_initial_test, $a_objective_id, $a_lo_result) + { + global $DIC; + + $lng = $DIC->language(); + $lng->loadLanguageModule('crs'); + + $is_qualified = + ($a_lo_result["type"] == ilLOUserResults::TYPE_QUALIFIED); + $is_qualified_initial = + ( + $a_lo_result['type'] == ilLOUserResults::TYPE_INITIAL && + ilLOSettings::getInstanceByObjId($a_lo_result['course_id'])->isInitialTestQualifying() + ); + $has_completed = + ($a_lo_result["status"] == ilLOUserResults::STATUS_COMPLETED); + + $next_step = $progress_txt = $bar_color = $test_url = $initial_sub = null; + + if ( + $is_qualified || + $is_qualified_initial) { + if ($has_completed) { + $next_step = $lng->txt("crs_loc_progress_objective_complete"); + } else { + $next_step = $lng->txt("crs_loc_progress_do_qualifying_again"); + } + } + // initial test + else { + if ($a_lo_result["status"]) { + $next_step = + $has_completed ? + $lng->txt("crs_loc_progress_do_qualifying") : + $lng->txt("crs_loc_suggested"); + } else { + $next_step = (bool) $a_has_initial_test ? + $lng->txt("crs_loc_progress_no_result_do_initial") : + $lng->txt("crs_loc_progress_no_result_no_initial"); + } + } + return $next_step; + } + + /** + * Render progressbar(s) for given objective and result data + * + * @param bool $a_has_initial_test + * @param int $a_objective_id + * @param bool $a_lo_result + * @param bool $a_list_mode + * @param bool $a_sub + * @param mixed $a_tt_suffix + * @return string + */ + public static function buildObjectiveProgressBar($a_has_initial_test, $a_objective_id, array $a_lo_result, $a_list_mode = false, $a_sub = false, $a_tt_suffix = null) + { + global $DIC; + + $lng = $DIC->language(); + $lng->loadLanguageModule('crs'); + + // tooltip (has to be unique!) + + $tooltip_id = "crsobjtvusr_" . $a_objective_id . "_" . $a_lo_result["type"] . "_" . ((int) $a_sub); + if ($a_tt_suffix !== null) { + $tooltip_id .= "_" . $a_tt_suffix; + } + + $tt_txt = sprintf( + $lng->txt("crs_loc_tt_info"), + $a_lo_result["result_perc"], + $a_lo_result["limit_perc"] + ); + + + include_once './Modules/Course/classes/Objectives/class.ilLOUtils.php'; + include_once './Modules/Course/classes/Objectives/class.ilLOSettings.php'; + + $is_qualified = ($a_lo_result["type"] == ilLOUserResults::TYPE_QUALIFIED); + $is_qualified_initial = ($a_lo_result['type'] == ilLOUserResults::TYPE_INITIAL && + ilLOSettings::getInstanceByObjId($a_lo_result['course_id'])->isInitialTestQualifying()); + $has_completed = ($a_lo_result["status"] == ilLOUserResults::STATUS_COMPLETED); + + $next_step = $progress_txt = $bar_color = $test_url = $initial_sub = null; + + $compare_value = null; + + if ($is_qualified || + $is_qualified_initial) { + $progress_txt = $lng->txt("crs_loc_progress_result_qtest"); + $tt_txt = $lng->txt("crs_loc_tab_qtest") . ": " . $tt_txt; + + if ($has_completed) { + $next_step = $lng->txt("crs_loc_progress_objective_complete"); + $bar_color = "ilCourseObjectiveProgressBarCompleted"; + + // render 2nd progressbar if there is also an initial test + if ($is_qualified && + $a_has_initial_test && + is_array($a_lo_result["initial"])) { + $a_lo_result["initial"]["itest"] = $a_lo_result["itest"]; + + // force list mode to get rid of next step + #$initial_sub = self::buildObjectiveProgressBar(true, $a_objective_id, $a_lo_result["initial"], true, true, $a_tt_suffix); + $compare_value = $a_lo_result['initial']['result_perc']; + } + } else { + $next_step = $lng->txt("crs_loc_progress_do_qualifying_again"); + $bar_color = "ilCourseObjectiveProgressBarFailed"; + } + } + // initial test + else { + if ($a_lo_result["status"]) { + $progress_txt = $lng->txt("crs_loc_progress_result_itest"); + $tt_txt = $lng->txt("crs_loc_tab_itest") . ": " . $tt_txt; + + $bar_color = "ilCourseObjectiveProgressBarNeutral"; + $next_step = $has_completed + ? $lng->txt("crs_loc_progress_do_qualifying") + : $lng->txt("crs_loc_suggested"); + } + // not attempted: no progress bar + else { + $next_step = (bool) $a_has_initial_test + ? $lng->txt("crs_loc_progress_no_result_do_initial") + : $lng->txt("crs_loc_progress_no_result_no_initial"); + } + } + + // link to test results + // - first try to fetch a link for qualifying test results + if ($a_lo_result["qtest"]) { + $test_url = ilLOUtils::getTestResultLinkForUser($a_lo_result["qtest"], $a_lo_result["user_id"]); + } + // - when no qualifiying test results link was fetched, try for initial test + if (!$test_url && $a_lo_result["itest"]) { + $test_url = ilLOUtils::getTestResultLinkForUser($a_lo_result["itest"], $a_lo_result["user_id"]); + } + + $main_text = $lng->txt('crs_loc_itest_info'); + if ($a_lo_result['type'] == ilLOSettings::TYPE_TEST_QUALIFIED) { + $main_text = $lng->txt('crs_loc_qtest_info'); + } + + + + return self::renderProgressMeter( + $a_lo_result["result_perc"], + $a_lo_result["limit_perc"], + $compare_value, + $progress_txt, + $test_url, + $tooltip_id, + $tt_txt, + $a_list_mode + ? null + : $next_step, + $initial_sub, + $a_list_mode + ? 30 + : 10, + $main_text, + $lng->txt('crs_lobj_pm_min_goal') + ); + } + + /** + * @param \ilCourseObjective $a_objective + * @param array|null $a_lo_result + * @return string + * @throws \ilTemplateException + */ + protected function buildAccordionTitle(ilCourseObjective $a_objective, array $a_lo_result = null) + { + global $DIC; + + $renderer = $DIC->ui()->renderer(); + $ui_factory = $DIC->ui()->factory(); + + $tpl = new ilTemplate("tpl.objective_accordion_title.html", true, true, "Services/Container"); + + if ($a_lo_result) { + $tpl->setVariable( + "PROGRESS_BAR", + self::buildObjectiveProgressBar( + (bool) $this->loc_settings->worksWithInitialTest(), + $a_objective->getObjectiveId(), + $a_lo_result + ) + ); + } + + $tpl->setVariable("TITLE", $this->lng->txt("crs_loc_learning_objective") . ": " . trim($a_objective->getTitle())); + $tpl->setVariable("DESCRIPTION", nl2br(trim($a_objective->getDescription()))); + + $this->logger->dump($a_lo_result); + + $initial_res = null; + $initial_lim = null; + if ($this->loc_settings->worksWithInitialTest()) { + if (array_key_exists('initial', $a_lo_result)) { + $initial_res = (int) $a_lo_result['initial']['result_perc']; + $initial_lim = (int) $a_lo_result['initial']['limit_perc']; + } + if ( + $a_lo_result['type'] == ilLOUserResults::TYPE_INITIAL && + isset($a_lo_result['result_perc']) + ) { + $initial_res = (int) $a_lo_result['result_perc']; + $initial_lim = (int) $a_lo_result['limit_perc']; + } + } + + if ($initial_res !== null) { + $link = \ilLOUtils::getTestResultLinkForUser( + $a_lo_result["itest"], + $a_lo_result["user_id"] + ); + + if (strlen($link)) { + $tpl->setCurrentBlock('i_with_link'); + $tpl->setVariable( + 'IBTN', + $renderer->render( + $ui_factory->button()->shy( + $this->lng->txt('crs_objective_result_details'), + $link + ) + ) + ); + $tpl->parseCurrentBlock(); + } + + + $tpl->setCurrentBlock('res_initial'); + $tpl->setVariable( + 'IRESULT', + sprintf( + $this->lng->txt('crs_objective_result_summary_initial'), + (int) $initial_res . '%', + (int) $initial_lim . '%' + ) + ); + $tpl->parseCurrentBlock(); + } + + $qual_res = null; + $qual_lim = null; + + if ($a_lo_result['type'] == ilLOUserResults::TYPE_QUALIFIED) { + $qual_res = (int) $a_lo_result['result_perc']; + $qual_lim = (int) $a_lo_result['limit_perc']; + } + + if ($qual_res !== null) { + $link = \ilLOUtils::getTestResultLinkForUser( + $a_lo_result["qtest"], + $a_lo_result["user_id"] + ); + + if (strlen($link)) { + $tpl->setCurrentBlock('q_with_link'); + $tpl->setVariable( + 'QBTN', + $renderer->render( + $ui_factory->button()->shy( + $this->lng->txt('crs_objective_result_details'), + $link + ) + ) + ); + $tpl->parseCurrentBlock(); + } + $tpl->setCurrentBlock('res_qualifying'); + $tpl->setVariable( + 'QRESULT', + sprintf( + $this->lng->txt('crs_objective_result_summary_qualifying'), + (int) $qual_res . '%', + (int) $qual_lim . '%' + ) + ); + $tpl->parseCurrentBlock(); + } + + $this->logger->dump($a_lo_result); + + + $summary = self::getObjectiveResultSummary( + (bool) $this->loc_settings->worksWithInitialTest(), + $a_objective->getObjectiveId(), + $a_lo_result + ); + if (strlen($summary)) { + $tpl->setCurrentBlock('objective_summary'); + $tpl->setVariable('SUMMARY_TXT', $summary); + $tpl->parseCurrentBlock(); + } + + // #15510 + $tpl->setVariable("ANCHOR_ID", "objtv_acc_" . $a_objective->getObjectiveId()); + + return $tpl->get(); + } + + protected function buildAccordionContent(array $a_items) + { + $tpl = new ilTemplate("tpl.objective_accordion_content.html", true, true, "Services/Container"); + foreach ($a_items as $item) { + $tpl->setCurrentBlock("items_bl"); + $tpl->setVariable("ITEM", $item); + $tpl->parseCurrentBlock(); + } + return $tpl->get(); + } + + /** + * show action button + * + * @access protected + * @param + * @return + */ + protected function showButton($a_cmd, $a_text, $a_target = '', $a_id = "") + { + $ilToolbar = $this->toolbar; + $ilCtrl = $this->ctrl; + + // #11842 + $ilToolbar->addButton( + $a_text, + $ilCtrl->getLinkTarget($this->getContainerGUI(), $a_cmd), + $a_target, + "", + '', + $a_id + ); + } } -?> diff --git a/Services/Container/classes/class.ilContainerPage.php b/Services/Container/classes/class.ilContainerPage.php index e6be3f02f904beb49bdf942a1bc24477bab51597..04165a68c50334ac2cffd98f7d60a0ba15169058 100755 --- a/Services/Container/classes/class.ilContainerPage.php +++ b/Services/Container/classes/class.ilContainerPage.php @@ -5,23 +5,21 @@ include_once("./Services/COPage/classes/class.ilPageObject.php"); /** * Container page object - * - * @author Alex Killing + * + * @author Alex Killing * @version $Id$ * * @ingroup ServicesContainer */ class ilContainerPage extends ilPageObject { - /** - * Get parent type - * - * @return string parent type - */ - function getParentType() - { - return "cont"; - } - + /** + * Get parent type + * + * @return string parent type + */ + public function getParentType() + { + return "cont"; + } } -?> diff --git a/Services/Container/classes/class.ilContainerPageConfig.php b/Services/Container/classes/class.ilContainerPageConfig.php index 2ee8a3415bd357673e225f9bc5cf309a7e0595e1..c2997d25bf47925e2edd22e4f80d5ca2fa92c7f8 100644 --- a/Services/Container/classes/class.ilContainerPageConfig.php +++ b/Services/Container/classes/class.ilContainerPageConfig.php @@ -5,7 +5,7 @@ include_once("./Services/COPage/classes/class.ilPageConfig.php"); /** - * Container page configuration + * Container page configuration * * @author Alex Killing * @version $Id$ @@ -13,36 +13,32 @@ include_once("./Services/COPage/classes/class.ilPageConfig.php"); */ class ilContainerPageConfig extends ilPageConfig { - /** - * @var ilSetting - */ - protected $settings; - - /** - * Init - */ - function init() - { - global $DIC; - - $this->settings = $DIC->settings(); - - $this->setEnableInternalLinks(true); - $this->setIntLinkHelpDefaultType("RepositoryItem"); - $this->setEnablePCType("FileList", false); - $this->setEnablePCType("Map", true); - $this->setEnablePCType("Resources", true); - $this->setMultiLangSupport(true); - $this->setSinglePageMode(true); - $this->setEnablePermissionChecks(true); - - $mset = new ilSetting("mobs"); - if ($mset->get("mep_activate_pages")) - { - $this->setEnablePCType("ContentInclude", true); - } - } - + /** + * @var ilSetting + */ + protected $settings; + + /** + * Init + */ + public function init() + { + global $DIC; + + $this->settings = $DIC->settings(); + + $this->setEnableInternalLinks(true); + $this->setIntLinkHelpDefaultType("RepositoryItem"); + $this->setEnablePCType("FileList", false); + $this->setEnablePCType("Map", true); + $this->setEnablePCType("Resources", true); + $this->setMultiLangSupport(true); + $this->setSinglePageMode(true); + $this->setEnablePermissionChecks(true); + + $mset = new ilSetting("mobs"); + if ($mset->get("mep_activate_pages")) { + $this->setEnablePCType("ContentInclude", true); + } + } } - -?> diff --git a/Services/Container/classes/class.ilContainerPageGUI.php b/Services/Container/classes/class.ilContainerPageGUI.php index bfd5cdb9605eeb68045e16af7c36c6261b9f826b..5d6f0457c003dd45555c0b9f9c591d4cdc591ed2 100755 --- a/Services/Container/classes/class.ilContainerPageGUI.php +++ b/Services/Container/classes/class.ilContainerPageGUI.php @@ -7,8 +7,8 @@ include_once("./Services/Container/classes/class.ilContainerPage.php"); /** * Container page GUI class - * - * @author Alex Killing + * + * @author Alex Killing * * @ilCtrl_Calls ilContainerPageGUI: ilPageEditorGUI, ilEditClipboardGUI, ilMDEditorGUI * @ilCtrl_Calls ilContainerPageGUI: ilPublicUserProfileGUI, ilNoteGUI @@ -18,31 +18,29 @@ include_once("./Services/Container/classes/class.ilContainerPage.php"); */ class ilContainerPageGUI extends ilPageObjectGUI { - /** - * Constructor - */ - function __construct($a_id = 0, $a_old_nr = 0, $a_lang = "") - { - global $DIC; - - $this->tpl = $DIC["tpl"]; - $tpl = $DIC["tpl"]; + /** + * Constructor + */ + public function __construct($a_id = 0, $a_old_nr = 0, $a_lang = "") + { + global $DIC; - parent::__construct("cont", $a_id, $a_old_nr, false, $a_lang); - } + $this->tpl = $DIC["tpl"]; + $tpl = $DIC["tpl"]; - /** - * Get profile back url - */ - function getProfileBackUrl() - { - include_once("./Services/Link/classes/class.ilLink.php"); - $link = ilLink::_getLink((int) $_GET["ref_id"]); - // make it relative, since profile only accepts relative links as back links - $link = substr($link, strpos($link, "//") + 2); - $link = substr($link, strpos($link, "/")); - return $link; - } + parent::__construct("cont", $a_id, $a_old_nr, false, $a_lang); + } -} -?> + /** + * Get profile back url + */ + public function getProfileBackUrl() + { + include_once("./Services/Link/classes/class.ilLink.php"); + $link = ilLink::_getLink((int) $_GET["ref_id"]); + // make it relative, since profile only accepts relative links as back links + $link = substr($link, strpos($link, "//") + 2); + $link = substr($link, strpos($link, "/")); + return $link; + } +} diff --git a/Services/Container/classes/class.ilContainerRenderer.php b/Services/Container/classes/class.ilContainerRenderer.php index 362ee970ad438536f7463f57ad60029a27deacef..8be500368b53f21219072001ba3a7ff6860460b9 100644 --- a/Services/Container/classes/class.ilContainerRenderer.php +++ b/Services/Container/classes/class.ilContainerRenderer.php @@ -1,861 +1,784 @@ - -* @version $Id: class.ilContainerGUI.php 52026 2014-08-05 10:22:06Z smeyer $ -*/ -class ilContainerRenderer -{ - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilSetting - */ - protected $settings; - - /** - * @var ilObjectDefinition - */ - protected $obj_definition; - - // switches - protected $enable_manage_select_all; // [bool] - protected $enable_multi_download; // [bool] - protected $active_block_ordering; // [bool] - - // properties - protected $type_blocks = array(); // [array] - protected $custom_blocks = array(); // [array] - protected $items = array(); // [array] - protected $hidden_items = array(); // [array] - protected $block_items = array(); // [array] - protected $details = array(); // [array] - protected $item_ids = array(); // [array] - - // block (unique) ids - protected $rendered_blocks = array(); // [array] - protected $bl_cnt = 0; // [int] - protected $cur_row_type; // [string] - - // ordering - protected $block_pos = array(); // [array] - protected $block_custom_pos = array(); // [array] - protected $order_cnt = 0; // [int] - - /** - * @var array - */ - protected $show_more = []; - - const UNIQUE_SEPARATOR = "-"; - - /** - * @var int - */ - protected $view_mode; - - /** - * @var \ILIAS\DI\UIServices - */ - protected $ui; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * Constructor - * - * @param bool $a_enable_manage_select_all - * @param bool $a_enable_multi_download - * @param bool $a_active_block_ordering - * @param array $a_block_custom_positions - */ - public function __construct($a_enable_manage_select_all = false, $a_enable_multi_download = false, $a_active_block_ordering = false, $a_block_custom_positions, $container_gui_obj, $a_view_mode = - ilContainerContentGUI::VIEW_MODE_LIST) - { - global $DIC; - - $this->lng = $DIC->language(); - $this->settings = $DIC->settings(); - $this->ui = $DIC->ui(); - $this->obj_definition = $DIC["objDefinition"]; - $this->enable_manage_select_all = (bool)$a_enable_manage_select_all; - $this->enable_multi_download = (bool)$a_enable_multi_download; - $this->active_block_ordering = (bool)$a_active_block_ordering; - $this->block_custom_pos = $a_block_custom_positions; - $this->view_mode = $a_view_mode; - $this->container_gui = $container_gui_obj; - $this->ctrl = $DIC->ctrl(); - } - - /** - * Get view mode - */ - protected function getViewMode() - { - return $this->view_mode; - } - - // - // blocks - // - - /** - * Add type block - * - * @param string $a_type repository object type - * @param string $a_prefix html snippet - * @param string $a_postfix html snippet - * @return boolean - */ - public function addTypeBlock($a_type, $a_prefix = null, $a_postfix = null) - { - if($a_type != "itgr" && - !$this->hasTypeBlock($a_type)) - { - $this->type_blocks[$a_type] = array( - "prefix" => $a_prefix - ,"postfix" => $a_postfix - ); - return true; - } - return false; - } - - /** - * Type block already exists? - * - * @param string $a_type repository object type - * @return bool - */ - public function hasTypeBlock($a_type) - { - return array_key_exists($a_type, $this->type_blocks); - } - - /** - * Add custom block - * - * @param mixed $a_id - * @param string $a_caption - * @param string $a_actions html snippet - * @return boolean - */ - public function addCustomBlock($a_id, $a_caption, $a_actions = null, $a_data = array()) - { - if(!$this->hasCustomBlock($a_id)) - { - $this->custom_blocks[$a_id] = array( - "caption" => $a_caption - ,"actions" => $a_actions - ,"data" => $a_data - ); - return true; - } - return false; - } - - /** - * Custom block already exists? - * - * @param mixed $a_id - * @return bool - */ - public function hasCustomBlock($a_id) - { - return array_key_exists($a_id, $this->custom_blocks); - } - - /** - * Any block with id exists? - * - * @param mixed $a_id - * @return bool - */ - public function isValidBlock($a_id) - { - return ($this->hasTypeBlock($a_id) || - $this->hasCustomBlock($a_id)); - } - - - // - // items - // - - /** - * Mark item id as used, but do not render - * - * @param mixed $a_id - */ - public function hideItem($a_id) - { - // see hasItem(); - $this->hidden_items[$a_id] = true; - - // #16629 - do not remove hidden items from other blocks - // $this->removeItem($a_id); - } - - /** - * Remove item (from any block) - * - * @param mixed $a_id - */ - public function removeItem($a_id) - { - if(!$this->hasItem($a_id)) - { - return; - } - - unset($this->item_ids[$a_id]); - unset($this->hidden_items[$a_id]); - - foreach(array_keys($this->items) as $item_id) - { - if(array_pop(explode(self::UNIQUE_SEPARATOR, $item_id)) == $a_id) - { - unset($this->items[$item_id]); - } - } - - foreach($this->block_items as $block_id => $items) - { - foreach($items as $idx => $item_id) - { - if(array_pop(explode(self::UNIQUE_SEPARATOR, $item_id)) == $a_id) - { - unset($this->block_items[$block_id][$idx]); - if(!sizeof($this->block_items[$block_id])) - { - unset($this->block_items[$block_id]); - } - break; - } - } - } - } - - /** - * Item with id exists? - * - * @param mixed $a_id - * @return bool - */ - public function hasItem($a_id) - { - return (array_key_exists($a_id, $this->item_ids) || - array_key_exists($a_id, $this->hidden_items)); - } - - /** - * Add item to existing block - * - * @param mixed $a_block_id - * @param string $a_item_type repository object type - * @param mixed $a_item_id - * @param string $a_item_html html snippet - * @param bool $a_force enable multiple rendering - * @return boolean - */ - public function addItemToBlock($a_block_id, $a_item_type, $a_item_id, $a_item_html, $a_force = false) - { - if($this->isValidBlock($a_block_id) && - $a_item_type != "itgr" && - (!$this->hasItem($a_item_id) || $a_force)) - { - if (is_string($a_item_html) && trim($a_item_html) == "") - { - return false; - } - if (!$a_item_html) - { - return false; - } - - - // #16563 - item_id (== ref_id) is NOT unique, adding parent block id - $uniq_id = $a_block_id.self::UNIQUE_SEPARATOR.$a_item_id; - - $this->items[$uniq_id] = array( - "type" => $a_item_type - ,"html" => $a_item_html - ); - - // #18326 - $this->item_ids[$a_item_id] = true; - - $this->block_items[$a_block_id][] = $uniq_id; - return true; - } - return false; - } - - /** - * Add show more button to a block - */ - public function addShowMoreButton($a_block_id) - { - $this->show_more[] = $a_block_id; - } - - /** - * Add details level - * - * @param int $a_level - * @param string $a_url - * @param bool $a_active - */ - public function addDetailsLevel($a_level, $a_url, $a_active = false) - { - $this->details[$a_level] = array( - "url" => $a_url - ,"active" => (bool)$a_active - ); - } - - /** - * Reset/remove all detail levels - */ - public function resetDetails() - { - $this->details = array(); - } - - - // - // render - // - - /** - * Set block position - * - * @param mixed $a_block_id - * @param int $a_pos - */ - public function setBlockPosition($a_block_id, $a_pos) - { - if($this->isValidBlock($a_block_id)) - { - $this->block_pos[$a_block_id] = $a_pos; - } - } - - /** - * Get rendered html (of all blocks) - * - * @return string - */ - public function getHTML() - { - $valid = false; - - $block_tpl = $this->initBlockTemplate(); - - foreach($this->processBlockPositions() as $block_id) - { - if(array_key_exists($block_id, $this->custom_blocks)) - { - if($this->renderHelperCustomBlock($block_tpl, $block_id)) - { - $this->addSeparatorRow($block_tpl); - $valid = true; - } - } - if(array_key_exists($block_id, $this->type_blocks)) - { - if($this->renderHelperTypeBlock($block_tpl, $block_id)) - { - $this->addSeparatorRow($block_tpl); - $valid = true; - } - } - } - - if($valid) - { - $this->renderDetails($block_tpl); - - return $block_tpl->get(); - } - } - - /** - * Get rendered html of single type block - * - * @param string $a_type repository object type - * @return html - */ - public function renderSingleTypeBlock($a_type) - { - $block_tpl = $this->initBlockTemplate(); - - if($this->renderHelperTypeBlock($block_tpl, $a_type, true)) - { - return $block_tpl->get(); - } - } - - /** - * Get rendered html of single custom block - * - * @param mixed $a_id - * @return html - */ - public function renderSingleCustomBlock($a_id) - { - $block_tpl = $this->initBlockTemplate(); - - if($this->renderHelperCustomBlock($block_tpl, $a_id, true)) - { - return $block_tpl->get(); - } - } - - - // - // render (helper) - // - - /** - * Process block positions - * - * @return array block ids - */ - protected function processBlockPositions() - { - // manual order - if(is_array($this->block_custom_pos) && sizeof($this->block_custom_pos)) - { - $tmp = $this->block_pos; - $this->block_pos = array(); - foreach($this->block_custom_pos as $idx => $block_id) - { - if($this->isValidBlock($block_id)) - { - $this->block_pos[$block_id] = $idx; - } - } - - // at least some manual are valid - if(sizeof($this->block_pos)) - { - // append missing blocks from default order - $last = max($this->block_pos); - foreach(array_keys($tmp) as $block_id) - { - if(!array_key_exists($block_id, $this->block_pos)) - { - $this->block_pos[$block_id] = ++$last; - } - } - } - // all manual invalid, use default - else - { - $this->block_pos = $tmp; - } - } - - // add missing blocks to order - $last = sizeof($this->block_pos) - ? max($this->block_pos) - : 0; - foreach(array_keys($this->custom_blocks) as $block_id) - { - if(!array_key_exists($block_id, $this->block_pos)) - { - $this->block_pos[$block_id] = ++$last; - } - } - foreach(array_keys($this->type_blocks) as $block_id) - { - if(!array_key_exists($block_id, $this->block_pos)) - { - $this->block_pos[$block_id] = ++$last; - } - } - - asort($this->block_pos); - - return array_keys($this->block_pos); - } - - /** - * Render custom block - * - * @param ilTemplate $a_block_tpl - * @param mixed $a_block_id - * @param bool $a_is_single - * @return boolean - */ - protected function renderHelperCustomBlock(ilTemplate $a_block_tpl, $a_block_id, $a_is_single = false) - { - if($this->hasCustomBlock($a_block_id)) - { - return $this->renderHelperGeneric($a_block_tpl, $a_block_id, $this->custom_blocks[$a_block_id], $a_is_single); - } - return false; - } - - /** - * Render type block - * - * @param ilTemplate $a_block_tpl - * @param string $a_type repository object type - * @param bool $a_is_single - * @return boolean - */ - protected function renderHelperTypeBlock(ilTemplate $a_block_tpl, $a_type, $a_is_single = false) - { - if($this->hasTypeBlock($a_type)) - { - $block = $this->type_blocks[$a_type]; - $block["type"] = $a_type; - return $this->renderHelperGeneric($a_block_tpl, $a_type, $block, $a_is_single); - } - return false; - } - - /** - * Render block - * - * @param ilTemplate $a_block_tpl - * @param mixed $a_block_id - * @param array $a_block block properties - * @param bool $a_is_single - * @return boolean - */ - protected function renderHelperGeneric(ilTemplate $a_block_tpl, $a_block_id, array $a_block, $a_is_single = false) - { - $ctrl = $this->ctrl; - if(!in_array($a_block_id, $this->rendered_blocks)) - { - $this->rendered_blocks[] = $a_block_id; - - $block_types = array(); - if(is_array($this->block_items[$a_block_id])) - { - foreach($this->block_items[$a_block_id] as $item_id) - { - if(isset($this->items[$item_id]["type"])) - { - $block_types[] = $this->items[$item_id]["type"]; - } - } - } - - // #14610 - manage empty item groups - if(is_array($this->block_items[$a_block_id]) || - is_numeric($a_block_id)) - { - $cards = []; - - $order_id = (!$a_is_single && $this->active_block_ordering) - ? $a_block_id - : null; - $this->addHeaderRow($a_block_tpl, $a_block["type"], $a_block["caption"], array_unique($block_types), $a_block["actions"], $order_id, $a_block["data"]); - - if ($this->getViewMode() == ilContainerContentGUI::VIEW_MODE_LIST) - { - if ($a_block["prefix"]) - { - $this->addStandardRow($a_block_tpl, $a_block["prefix"]); - } - } - - if(is_array($this->block_items[$a_block_id])) - { - foreach($this->block_items[$a_block_id] as $item_id) - { - if ($this->getViewMode() == ilContainerContentGUI::VIEW_MODE_LIST) - { - $this->addStandardRow($a_block_tpl, $this->items[$item_id]["html"], $item_id); - } - else - { - $cards[] = $this->items[$item_id]["html"]; - } - } - } - - if ($this->getViewMode() == ilContainerContentGUI::VIEW_MODE_LIST) - { - if ($a_block["postfix"]) - { - $this->addStandardRow($a_block_tpl, $a_block["postfix"]); - } - } - - if ($this->getViewMode() == ilContainerContentGUI::VIEW_MODE_TILE) - { - $f = $this->ui->factory(); - $renderer = $this->ui->renderer(); - - //Create a deck with large cards - $deck = $f->deck($cards)->withNormalCardsSize(); - //$deck = $f->deck($cards)->withSmallCardsSize(); - - - $html = $renderer->render($deck); - $a_block_tpl->setCurrentBlock("tile_rows"); - $a_block_tpl->setVariable("TILE_ROWS", $html); - $a_block_tpl->parseCurrentBlock(); - - } - - // show more - if (in_array($a_block_id, $this->show_more)) - { - $a_block_tpl->setCurrentBlock("show_more"); - - $ctrl->setParameter($this->container_gui, "type", $a_block_id); - $url = $ctrl->getLinkTarget($this->container_gui, "renderBlockAsynch", "", true); - $ctrl->setParameter($this->container_gui, "type", ""); - - $f = $this->ui->factory(); - $renderer = $this->ui->renderer(); - $button = $f->button()->standard($this->lng->txt("cont_show_more"), "") - ->withLoadingAnimationOnClick(true) - ->withOnLoadCode(function ($id) use ($a_block_id, $url) { - return "il.Container.initShowMore('$id', '$a_block_id', '".$url."');"; - }); - if ($ctrl->isAsynch()) - { - $a_block_tpl->setVariable("SHOW_MORE_BUTTON", $renderer->renderAsync($button)); - } - else - { - $a_block_tpl->setVariable("SHOW_MORE_BUTTON", $renderer->render($button)); - } - $a_block_tpl->parseCurrentBlock(); - $a_block_tpl->setCurrentBlock("show_more"); - $a_block_tpl->parseCurrentBlock(); - } - - return true; - } - } - - return false; - } - - /** - * Init template - * - * @return ilTemplate - */ - protected function initBlockTemplate() - { - // :TODO: obsolete? - $this->cur_row_type = "row_type_1"; - - return new ilTemplate("tpl.container_list_block.html", true, true, "Services/Container"); - } - - /** - * Render block header - * - * @param ilTemplate $a_tpl - * @param string $a_type - * @param string $a_text - * @param array $a_types_in_block - * @param string $a_commands_html - * @param int $a_order_id - */ - protected function addHeaderRow(ilTemplate $a_tpl, $a_type = "", $a_text = "", array $a_types_in_block = null, $a_commands_html = null, $a_order_id = null, $a_data = array()) - { - $lng = $this->lng; - $ilSetting = $this->settings; - $objDefinition = $this->obj_definition; - - $a_tpl->setVariable("CB_ID", ' id="bl_cntr_'.(++$this->bl_cnt).'"'); - - if ($this->enable_manage_select_all) - { - $this->renderSelectAllBlock($a_tpl); - } - else if ($this->enable_multi_download) - { - if ($a_type) - { - $a_types_in_block = array($a_type); - } - foreach($a_types_in_block as $type) - { - if (in_array($type, $this->getDownloadableTypes())) - { - $this->renderSelectAllBlock($a_tpl); - break; - } - } - } - - if ($a_text == "" && $a_type != "") - { - if (!$objDefinition->isPlugin($a_type)) - { - $title = $lng->txt("objs_".$a_type); - } - else - { - include_once("./Services/Component/classes/class.ilPlugin.php"); - $pl = ilObjectPlugin::getPluginObjectByType($a_type); - $title= $pl->txt("objs_".$a_type); - } - } - else - { - $title = $a_text; - } - - include_once("./Modules/ItemGroup/classes/class.ilItemGroupBehaviour.php"); - if (is_array($a_data)) - { - foreach ($a_data as $k => $v) - { - $a_tpl->setCurrentBlock("cb_data"); - $a_tpl->setVariable("DATA_KEY", $k); - $a_tpl->setVariable("DATA_VALUE", $v); - $a_tpl->parseCurrentBlock(); - - if ($k == "behaviour" && $v == ilItemGroupBehaviour::EXPANDABLE_CLOSED) - { - $a_tpl->touchBlock("container_items_hide"); - } - } - } - - if ($ilSetting->get("icon_position_in_lists") != "item_rows" && - $a_type != "") - { - $icon = ilUtil::getImagePath("icon_".$a_type.".svg"); - - $a_tpl->setCurrentBlock("container_header_row_image"); - $a_tpl->setVariable("HEADER_IMG", $icon); - $a_tpl->setVariable("HEADER_ALT", $title); - } - else - { - $a_tpl->setCurrentBlock("container_header_row"); - } - - if($a_order_id) - { - $a_tpl->setVariable("BLOCK_HEADER_ORDER_NAME", "position[blocks][".$a_order_id."]"); - $a_tpl->setVariable("BLOCK_HEADER_ORDER_NUM", (++$this->order_cnt)*10); - } - - $a_tpl->setVariable("BLOCK_HEADER_CONTENT", $title); - $a_tpl->setVariable("CHR_COMMANDS", $a_commands_html); - $a_tpl->parseCurrentBlock(); - - //$a_tpl->touchBlock("container_row"); - - $this->resetRowType(); - } - - /** - * Render item row - * - * @param ilTemplate $a_tpl - * @param string $a_html - * @param int $a_ref_id - */ - protected function addStandardRow(ilTemplate $a_tpl, $a_html, $a_ref_id = 0) - { - // :TODO: obsolete? - $this->cur_row_type = ($this->cur_row_type == "row_type_1") - ? "row_type_2" - : "row_type_1"; - - if ($a_ref_id > 0) - { - $a_tpl->setCurrentBlock($this->cur_row_type); - $a_tpl->setVariable("ROW_ID", 'id="item_row_'.$a_ref_id.'"'); - $a_tpl->parseCurrentBlock(); - } - else - { - $a_tpl->touchBlock($this->cur_row_type); - } - - $a_tpl->setCurrentBlock("container_standard_row"); - $a_tpl->setVariable("BLOCK_ROW_CONTENT", $a_html); - $a_tpl->parseCurrentBlock(); - - $a_tpl->touchBlock("container_row"); - } - - /** - * Render "select all" - */ - protected function renderSelectAllBlock(ilTemplate $a_tpl) - { - $lng = $this->lng; - - $a_tpl->setCurrentBlock("select_all_row"); - $a_tpl->setVariable("CHECKBOXNAME", "bl_cb_".$this->bl_cnt); - $a_tpl->setVariable("SEL_ALL_PARENT", "bl_cntr_".$this->bl_cnt); - $a_tpl->setVariable("SEL_ALL_PARENT", "bl_cntr_".$this->bl_cnt); - $a_tpl->setVariable("TXT_SELECT_ALL", $lng->txt("select_all")); - $a_tpl->parseCurrentBlock(); - } - - /** - * Render separator row - * - * @param ilTemplate $a_tpl - */ - protected function addSeparatorRow(ilTemplate $a_tpl) - { - $a_tpl->setCurrentBlock("container_block"); - $a_tpl->parseCurrentBlock(); - } - - /** - * Reset internal row type - */ - protected function resetRowType() - { - // :TODO: obsolete? - $this->cur_row_type = ""; - } - - /** - * Get downloadable repository object types - * - * @return array - */ - protected function getDownloadableTypes() - { - return array("fold", "file"); - } - - /** - * Render detail level - * - * @param ilTemplate $a_tpl - */ - public function renderDetails(ilTemplate $a_tpl) - { - $lng = $this->lng; - - if(sizeof($this->details)) - { - $a_tpl->setCurrentBlock('container_details_row'); - $a_tpl->setVariable('TXT_DETAILS', $lng->txt('details')); - $a_tpl->parseCurrentBlock(); - } - } -} + +* @version $Id: class.ilContainerGUI.php 52026 2014-08-05 10:22:06Z smeyer $ +*/ +class ilContainerRenderer +{ + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var ilObjectDefinition + */ + protected $obj_definition; + + // switches + protected $enable_manage_select_all; // [bool] + protected $enable_multi_download; // [bool] + protected $active_block_ordering; // [bool] + + // properties + protected $type_blocks = array(); // [array] + protected $custom_blocks = array(); // [array] + protected $items = array(); // [array] + protected $hidden_items = array(); // [array] + protected $block_items = array(); // [array] + protected $details = array(); // [array] + protected $item_ids = array(); // [array] + + // block (unique) ids + protected $rendered_blocks = array(); // [array] + protected $bl_cnt = 0; // [int] + protected $cur_row_type; // [string] + + // ordering + protected $block_pos = array(); // [array] + protected $block_custom_pos = array(); // [array] + protected $order_cnt = 0; // [int] + + /** + * @var array + */ + protected $show_more = []; + + const UNIQUE_SEPARATOR = "-"; + + /** + * @var int + */ + protected $view_mode; + + /** + * @var \ILIAS\DI\UIServices + */ + protected $ui; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * Constructor + * + * @param bool $a_enable_manage_select_all + * @param bool $a_enable_multi_download + * @param bool $a_active_block_ordering + * @param array $a_block_custom_positions + */ + public function __construct($a_enable_manage_select_all = false, $a_enable_multi_download = false, $a_active_block_ordering = false, $a_block_custom_positions, $container_gui_obj, $a_view_mode = + ilContainerContentGUI::VIEW_MODE_LIST) + { + global $DIC; + + $this->lng = $DIC->language(); + $this->settings = $DIC->settings(); + $this->ui = $DIC->ui(); + $this->obj_definition = $DIC["objDefinition"]; + $this->enable_manage_select_all = (bool) $a_enable_manage_select_all; + $this->enable_multi_download = (bool) $a_enable_multi_download; + $this->active_block_ordering = (bool) $a_active_block_ordering; + $this->block_custom_pos = $a_block_custom_positions; + $this->view_mode = $a_view_mode; + $this->container_gui = $container_gui_obj; + $this->ctrl = $DIC->ctrl(); + } + + /** + * Get view mode + */ + protected function getViewMode() + { + return $this->view_mode; + } + + // + // blocks + // + + /** + * Add type block + * + * @param string $a_type repository object type + * @param string $a_prefix html snippet + * @param string $a_postfix html snippet + * @return boolean + */ + public function addTypeBlock($a_type, $a_prefix = null, $a_postfix = null) + { + if ($a_type != "itgr" && + !$this->hasTypeBlock($a_type)) { + $this->type_blocks[$a_type] = array( + "prefix" => $a_prefix + ,"postfix" => $a_postfix + ); + return true; + } + return false; + } + + /** + * Type block already exists? + * + * @param string $a_type repository object type + * @return bool + */ + public function hasTypeBlock($a_type) + { + return array_key_exists($a_type, $this->type_blocks); + } + + /** + * Add custom block + * + * @param mixed $a_id + * @param string $a_caption + * @param string $a_actions html snippet + * @return boolean + */ + public function addCustomBlock($a_id, $a_caption, $a_actions = null, $a_data = array()) + { + if (!$this->hasCustomBlock($a_id)) { + $this->custom_blocks[$a_id] = array( + "caption" => $a_caption + ,"actions" => $a_actions + ,"data" => $a_data + ); + return true; + } + return false; + } + + /** + * Custom block already exists? + * + * @param mixed $a_id + * @return bool + */ + public function hasCustomBlock($a_id) + { + return array_key_exists($a_id, $this->custom_blocks); + } + + /** + * Any block with id exists? + * + * @param mixed $a_id + * @return bool + */ + public function isValidBlock($a_id) + { + return ($this->hasTypeBlock($a_id) || + $this->hasCustomBlock($a_id)); + } + + + // + // items + // + + /** + * Mark item id as used, but do not render + * + * @param mixed $a_id + */ + public function hideItem($a_id) + { + // see hasItem(); + $this->hidden_items[$a_id] = true; + + // #16629 - do not remove hidden items from other blocks + // $this->removeItem($a_id); + } + + /** + * Remove item (from any block) + * + * @param mixed $a_id + */ + public function removeItem($a_id) + { + if (!$this->hasItem($a_id)) { + return; + } + + unset($this->item_ids[$a_id]); + unset($this->hidden_items[$a_id]); + + foreach (array_keys($this->items) as $item_id) { + if (array_pop(explode(self::UNIQUE_SEPARATOR, $item_id)) == $a_id) { + unset($this->items[$item_id]); + } + } + + foreach ($this->block_items as $block_id => $items) { + foreach ($items as $idx => $item_id) { + if (array_pop(explode(self::UNIQUE_SEPARATOR, $item_id)) == $a_id) { + unset($this->block_items[$block_id][$idx]); + if (!sizeof($this->block_items[$block_id])) { + unset($this->block_items[$block_id]); + } + break; + } + } + } + } + + /** + * Item with id exists? + * + * @param mixed $a_id + * @return bool + */ + public function hasItem($a_id) + { + return (array_key_exists($a_id, $this->item_ids) || + array_key_exists($a_id, $this->hidden_items)); + } + + /** + * Add item to existing block + * + * @param mixed $a_block_id + * @param string $a_item_type repository object type + * @param mixed $a_item_id + * @param string $a_item_html html snippet + * @param bool $a_force enable multiple rendering + * @return boolean + */ + public function addItemToBlock($a_block_id, $a_item_type, $a_item_id, $a_item_html, $a_force = false) + { + if ($this->isValidBlock($a_block_id) && + $a_item_type != "itgr" && + (!$this->hasItem($a_item_id) || $a_force)) { + if (is_string($a_item_html) && trim($a_item_html) == "") { + return false; + } + if (!$a_item_html) { + return false; + } + + + // #16563 - item_id (== ref_id) is NOT unique, adding parent block id + $uniq_id = $a_block_id . self::UNIQUE_SEPARATOR . $a_item_id; + + $this->items[$uniq_id] = array( + "type" => $a_item_type + ,"html" => $a_item_html + ); + + // #18326 + $this->item_ids[$a_item_id] = true; + + $this->block_items[$a_block_id][] = $uniq_id; + return true; + } + return false; + } + + /** + * Add show more button to a block + */ + public function addShowMoreButton($a_block_id) + { + $this->show_more[] = $a_block_id; + } + + /** + * Add details level + * + * @param int $a_level + * @param string $a_url + * @param bool $a_active + */ + public function addDetailsLevel($a_level, $a_url, $a_active = false) + { + $this->details[$a_level] = array( + "url" => $a_url + ,"active" => (bool) $a_active + ); + } + + /** + * Reset/remove all detail levels + */ + public function resetDetails() + { + $this->details = array(); + } + + + // + // render + // + + /** + * Set block position + * + * @param mixed $a_block_id + * @param int $a_pos + */ + public function setBlockPosition($a_block_id, $a_pos) + { + if ($this->isValidBlock($a_block_id)) { + $this->block_pos[$a_block_id] = $a_pos; + } + } + + /** + * Get rendered html (of all blocks) + * + * @return string + */ + public function getHTML() + { + $valid = false; + + $block_tpl = $this->initBlockTemplate(); + + foreach ($this->processBlockPositions() as $block_id) { + if (array_key_exists($block_id, $this->custom_blocks)) { + if ($this->renderHelperCustomBlock($block_tpl, $block_id)) { + $this->addSeparatorRow($block_tpl); + $valid = true; + } + } + if (array_key_exists($block_id, $this->type_blocks)) { + if ($this->renderHelperTypeBlock($block_tpl, $block_id)) { + $this->addSeparatorRow($block_tpl); + $valid = true; + } + } + } + + if ($valid) { + $this->renderDetails($block_tpl); + + return $block_tpl->get(); + } + } + + /** + * Get rendered html of single type block + * + * @param string $a_type repository object type + * @return html + */ + public function renderSingleTypeBlock($a_type) + { + $block_tpl = $this->initBlockTemplate(); + + if ($this->renderHelperTypeBlock($block_tpl, $a_type, true)) { + return $block_tpl->get(); + } + } + + /** + * Get rendered html of single custom block + * + * @param mixed $a_id + * @return html + */ + public function renderSingleCustomBlock($a_id) + { + $block_tpl = $this->initBlockTemplate(); + + if ($this->renderHelperCustomBlock($block_tpl, $a_id, true)) { + return $block_tpl->get(); + } + } + + + // + // render (helper) + // + + /** + * Process block positions + * + * @return array block ids + */ + protected function processBlockPositions() + { + // manual order + if (is_array($this->block_custom_pos) && sizeof($this->block_custom_pos)) { + $tmp = $this->block_pos; + $this->block_pos = array(); + foreach ($this->block_custom_pos as $idx => $block_id) { + if ($this->isValidBlock($block_id)) { + $this->block_pos[$block_id] = $idx; + } + } + + // at least some manual are valid + if (sizeof($this->block_pos)) { + // append missing blocks from default order + $last = max($this->block_pos); + foreach (array_keys($tmp) as $block_id) { + if (!array_key_exists($block_id, $this->block_pos)) { + $this->block_pos[$block_id] = ++$last; + } + } + } + // all manual invalid, use default + else { + $this->block_pos = $tmp; + } + } + + // add missing blocks to order + $last = sizeof($this->block_pos) + ? max($this->block_pos) + : 0; + foreach (array_keys($this->custom_blocks) as $block_id) { + if (!array_key_exists($block_id, $this->block_pos)) { + $this->block_pos[$block_id] = ++$last; + } + } + foreach (array_keys($this->type_blocks) as $block_id) { + if (!array_key_exists($block_id, $this->block_pos)) { + $this->block_pos[$block_id] = ++$last; + } + } + + asort($this->block_pos); + + return array_keys($this->block_pos); + } + + /** + * Render custom block + * + * @param ilTemplate $a_block_tpl + * @param mixed $a_block_id + * @param bool $a_is_single + * @return boolean + */ + protected function renderHelperCustomBlock(ilTemplate $a_block_tpl, $a_block_id, $a_is_single = false) + { + if ($this->hasCustomBlock($a_block_id)) { + return $this->renderHelperGeneric($a_block_tpl, $a_block_id, $this->custom_blocks[$a_block_id], $a_is_single); + } + return false; + } + + /** + * Render type block + * + * @param ilTemplate $a_block_tpl + * @param string $a_type repository object type + * @param bool $a_is_single + * @return boolean + */ + protected function renderHelperTypeBlock(ilTemplate $a_block_tpl, $a_type, $a_is_single = false) + { + if ($this->hasTypeBlock($a_type)) { + $block = $this->type_blocks[$a_type]; + $block["type"] = $a_type; + return $this->renderHelperGeneric($a_block_tpl, $a_type, $block, $a_is_single); + } + return false; + } + + /** + * Render block + * + * @param ilTemplate $a_block_tpl + * @param mixed $a_block_id + * @param array $a_block block properties + * @param bool $a_is_single + * @return boolean + */ + protected function renderHelperGeneric(ilTemplate $a_block_tpl, $a_block_id, array $a_block, $a_is_single = false) + { + $ctrl = $this->ctrl; + if (!in_array($a_block_id, $this->rendered_blocks)) { + $this->rendered_blocks[] = $a_block_id; + + $block_types = array(); + if (is_array($this->block_items[$a_block_id])) { + foreach ($this->block_items[$a_block_id] as $item_id) { + if (isset($this->items[$item_id]["type"])) { + $block_types[] = $this->items[$item_id]["type"]; + } + } + } + + // #14610 - manage empty item groups + if (is_array($this->block_items[$a_block_id]) || + is_numeric($a_block_id)) { + $cards = []; + + $order_id = (!$a_is_single && $this->active_block_ordering) + ? $a_block_id + : null; + $this->addHeaderRow($a_block_tpl, $a_block["type"], $a_block["caption"], array_unique($block_types), $a_block["actions"], $order_id, $a_block["data"]); + + if ($this->getViewMode() == ilContainerContentGUI::VIEW_MODE_LIST) { + if ($a_block["prefix"]) { + $this->addStandardRow($a_block_tpl, $a_block["prefix"]); + } + } + + if (is_array($this->block_items[$a_block_id])) { + foreach ($this->block_items[$a_block_id] as $item_id) { + if ($this->getViewMode() == ilContainerContentGUI::VIEW_MODE_LIST) { + $this->addStandardRow($a_block_tpl, $this->items[$item_id]["html"], $item_id); + } else { + $cards[] = $this->items[$item_id]["html"]; + } + } + } + + if ($this->getViewMode() == ilContainerContentGUI::VIEW_MODE_LIST) { + if ($a_block["postfix"]) { + $this->addStandardRow($a_block_tpl, $a_block["postfix"]); + } + } + + if ($this->getViewMode() == ilContainerContentGUI::VIEW_MODE_TILE) { + $f = $this->ui->factory(); + $renderer = $this->ui->renderer(); + + //Create a deck with large cards + $deck = $f->deck($cards)->withNormalCardsSize(); + //$deck = $f->deck($cards)->withSmallCardsSize(); + + + $html = $renderer->render($deck); + $a_block_tpl->setCurrentBlock("tile_rows"); + $a_block_tpl->setVariable("TILE_ROWS", $html); + $a_block_tpl->parseCurrentBlock(); + } + + // show more + if (in_array($a_block_id, $this->show_more)) { + $a_block_tpl->setCurrentBlock("show_more"); + + $ctrl->setParameter($this->container_gui, "type", $a_block_id); + $url = $ctrl->getLinkTarget($this->container_gui, "renderBlockAsynch", "", true); + $ctrl->setParameter($this->container_gui, "type", ""); + + $f = $this->ui->factory(); + $renderer = $this->ui->renderer(); + $button = $f->button()->standard($this->lng->txt("cont_show_more"), "") + ->withLoadingAnimationOnClick(true) + ->withOnLoadCode(function ($id) use ($a_block_id, $url) { + return "il.Container.initShowMore('$id', '$a_block_id', '" . $url . "');"; + }); + if ($ctrl->isAsynch()) { + $a_block_tpl->setVariable("SHOW_MORE_BUTTON", $renderer->renderAsync($button)); + } else { + $a_block_tpl->setVariable("SHOW_MORE_BUTTON", $renderer->render($button)); + } + $a_block_tpl->parseCurrentBlock(); + $a_block_tpl->setCurrentBlock("show_more"); + $a_block_tpl->parseCurrentBlock(); + } + + return true; + } + } + + return false; + } + + /** + * Init template + * + * @return ilTemplate + */ + protected function initBlockTemplate() + { + // :TODO: obsolete? + $this->cur_row_type = "row_type_1"; + + return new ilTemplate("tpl.container_list_block.html", true, true, "Services/Container"); + } + + /** + * Render block header + * + * @param ilTemplate $a_tpl + * @param string $a_type + * @param string $a_text + * @param array $a_types_in_block + * @param string $a_commands_html + * @param int $a_order_id + */ + protected function addHeaderRow(ilTemplate $a_tpl, $a_type = "", $a_text = "", array $a_types_in_block = null, $a_commands_html = null, $a_order_id = null, $a_data = array()) + { + $lng = $this->lng; + $ilSetting = $this->settings; + $objDefinition = $this->obj_definition; + + $a_tpl->setVariable("CB_ID", ' id="bl_cntr_' . (++$this->bl_cnt) . '"'); + + if ($this->enable_manage_select_all) { + $this->renderSelectAllBlock($a_tpl); + } elseif ($this->enable_multi_download) { + if ($a_type) { + $a_types_in_block = array($a_type); + } + foreach ($a_types_in_block as $type) { + if (in_array($type, $this->getDownloadableTypes())) { + $this->renderSelectAllBlock($a_tpl); + break; + } + } + } + + if ($a_text == "" && $a_type != "") { + if (!$objDefinition->isPlugin($a_type)) { + $title = $lng->txt("objs_" . $a_type); + } else { + include_once("./Services/Component/classes/class.ilPlugin.php"); + $pl = ilObjectPlugin::getPluginObjectByType($a_type); + $title= $pl->txt("objs_" . $a_type); + } + } else { + $title = $a_text; + } + + include_once("./Modules/ItemGroup/classes/class.ilItemGroupBehaviour.php"); + if (is_array($a_data)) { + foreach ($a_data as $k => $v) { + $a_tpl->setCurrentBlock("cb_data"); + $a_tpl->setVariable("DATA_KEY", $k); + $a_tpl->setVariable("DATA_VALUE", $v); + $a_tpl->parseCurrentBlock(); + + if ($k == "behaviour" && $v == ilItemGroupBehaviour::EXPANDABLE_CLOSED) { + $a_tpl->touchBlock("container_items_hide"); + } + } + } + + if ($ilSetting->get("icon_position_in_lists") != "item_rows" && + $a_type != "") { + $icon = ilUtil::getImagePath("icon_" . $a_type . ".svg"); + + $a_tpl->setCurrentBlock("container_header_row_image"); + $a_tpl->setVariable("HEADER_IMG", $icon); + $a_tpl->setVariable("HEADER_ALT", $title); + } else { + $a_tpl->setCurrentBlock("container_header_row"); + } + + if ($a_order_id) { + $a_tpl->setVariable("BLOCK_HEADER_ORDER_NAME", "position[blocks][" . $a_order_id . "]"); + $a_tpl->setVariable("BLOCK_HEADER_ORDER_NUM", (++$this->order_cnt)*10); + } + + $a_tpl->setVariable("BLOCK_HEADER_CONTENT", $title); + $a_tpl->setVariable("CHR_COMMANDS", $a_commands_html); + $a_tpl->parseCurrentBlock(); + + //$a_tpl->touchBlock("container_row"); + + $this->resetRowType(); + } + + /** + * Render item row + * + * @param ilTemplate $a_tpl + * @param string $a_html + * @param int $a_ref_id + */ + protected function addStandardRow(ilTemplate $a_tpl, $a_html, $a_ref_id = 0) + { + // :TODO: obsolete? + $this->cur_row_type = ($this->cur_row_type == "row_type_1") + ? "row_type_2" + : "row_type_1"; + + if ($a_ref_id > 0) { + $a_tpl->setCurrentBlock($this->cur_row_type); + $a_tpl->setVariable("ROW_ID", 'id="item_row_' . $a_ref_id . '"'); + $a_tpl->parseCurrentBlock(); + } else { + $a_tpl->touchBlock($this->cur_row_type); + } + + $a_tpl->setCurrentBlock("container_standard_row"); + $a_tpl->setVariable("BLOCK_ROW_CONTENT", $a_html); + $a_tpl->parseCurrentBlock(); + + $a_tpl->touchBlock("container_row"); + } + + /** + * Render "select all" + */ + protected function renderSelectAllBlock(ilTemplate $a_tpl) + { + $lng = $this->lng; + + $a_tpl->setCurrentBlock("select_all_row"); + $a_tpl->setVariable("CHECKBOXNAME", "bl_cb_" . $this->bl_cnt); + $a_tpl->setVariable("SEL_ALL_PARENT", "bl_cntr_" . $this->bl_cnt); + $a_tpl->setVariable("SEL_ALL_PARENT", "bl_cntr_" . $this->bl_cnt); + $a_tpl->setVariable("TXT_SELECT_ALL", $lng->txt("select_all")); + $a_tpl->parseCurrentBlock(); + } + + /** + * Render separator row + * + * @param ilTemplate $a_tpl + */ + protected function addSeparatorRow(ilTemplate $a_tpl) + { + $a_tpl->setCurrentBlock("container_block"); + $a_tpl->parseCurrentBlock(); + } + + /** + * Reset internal row type + */ + protected function resetRowType() + { + // :TODO: obsolete? + $this->cur_row_type = ""; + } + + /** + * Get downloadable repository object types + * + * @return array + */ + protected function getDownloadableTypes() + { + return array("fold", "file"); + } + + /** + * Render detail level + * + * @param ilTemplate $a_tpl + */ + public function renderDetails(ilTemplate $a_tpl) + { + $lng = $this->lng; + + if (sizeof($this->details)) { + $a_tpl->setCurrentBlock('container_details_row'); + $a_tpl->setVariable('TXT_DETAILS', $lng->txt('details')); + $a_tpl->parseCurrentBlock(); + } + } +} diff --git a/Services/Container/classes/class.ilContainerSessionsContentGUI.php b/Services/Container/classes/class.ilContainerSessionsContentGUI.php index e46d5b7d45b8db3c9abff7727fb744af0e46d615..f43b495859865ac17c337334164e68d0281e7489 100644 --- a/Services/Container/classes/class.ilContainerSessionsContentGUI.php +++ b/Services/Container/classes/class.ilContainerSessionsContentGUI.php @@ -1,24 +1,24 @@ tabs = $DIC->tabs(); - $this->user = $DIC->user(); - $this->ctrl = $DIC->ctrl(); - $lng = $DIC->language(); - - parent::__construct($container_gui_obj); - $this->lng = $lng; - $this->initDetails(); - } - + $this->tabs = $DIC->tabs(); + $this->user = $DIC->user(); + $this->ctrl = $DIC->ctrl(); + $lng = $DIC->language(); + + parent::__construct($container_gui_obj); + $this->lng = $lng; + $this->initDetails(); + } + - /** - * get details level - * - * @access public - * @param int $a_session_id - * @return int DEATAILS_LEVEL - */ - public function getDetailsLevel($a_session_id) - { - if($this->getContainerGUI()->isActiveAdministrationPanel()) - { - return self::DETAILS_DEACTIVATED; - } - if(isset($_SESSION['sess']['expanded'][$a_session_id])) - { - return $_SESSION['sess']['expanded'][$a_session_id]; - } - if(in_array($a_session_id,$this->force_details)) - { - return self::DETAILS_ALL; - } - else - { - return self::DETAILS_TITLE; - } - } + /** + * get details level + * + * @access public + * @param int $a_session_id + * @return int DEATAILS_LEVEL + */ + public function getDetailsLevel($a_session_id) + { + if ($this->getContainerGUI()->isActiveAdministrationPanel()) { + return self::DETAILS_DEACTIVATED; + } + if (isset($_SESSION['sess']['expanded'][$a_session_id])) { + return $_SESSION['sess']['expanded'][$a_session_id]; + } + if (in_array($a_session_id, $this->force_details)) { + return self::DETAILS_ALL; + } else { + return self::DETAILS_TITLE; + } + } - /** - * Get content HTML for main column. - */ - function getMainContent() - { - $lng = $this->lng; - $ilTabs = $this->tabs; + /** + * Get content HTML for main column. + */ + public function getMainContent() + { + $lng = $this->lng; + $ilTabs = $this->tabs; - // see bug #7452 -// $ilTabs->setSubTabActive($this->getContainerObject()->getType().'_content'); + // see bug #7452 + // $ilTabs->setSubTabActive($this->getContainerObject()->getType().'_content'); - include_once 'Services/Object/classes/class.ilObjectListGUIFactory.php'; + include_once 'Services/Object/classes/class.ilObjectListGUIFactory.php'; - $tpl = new ilTemplate("tpl.container_page.html", true, true, - "Services/Container"); + $tpl = new ilTemplate( + "tpl.container_page.html", + true, + true, + "Services/Container" + ); - $this->__showMaterials($tpl); - - return $tpl->get(); - } + $this->__showMaterials($tpl); + + return $tpl->get(); + } - /** - * Show Materials - */ - function __showMaterials($a_tpl) - { - $lng = $this->lng; + /** + * Show Materials + */ + public function __showMaterials($a_tpl) + { + $lng = $this->lng; - $this->items = $this->getContainerObject()->getSubItems($this->getContainerGUI()->isActiveAdministrationPanel()); - $this->clearAdminCommandsDetermination(); - - $this->initRenderer(); - - $output_html = $this->getContainerGUI()->getContainerPageHTML(); - - // get embedded blocks - if ($output_html != "") - { - $output_html = $this->insertPageEmbeddedBlocks($output_html); - } - - if (is_array($this->items["sess"]) || - $this->items['sess_link']['prev']['value'] || - $this->items['sess_link']['next']['value']) - { - $this->items['sess'] = ilUtil::sortArray($this->items['sess'],'start','asc',true,false); - - if($this->items['sess_link']['prev']['value']) - { - $prefix = $this->renderSessionLimitLink(true); - } - if($this->items['sess_link']['next']['value']) - { - $postfix = $this->renderSessionLimitLink(false); - } - - $this->renderer->addTypeBlock("sess", $prefix, $postfix); - $this->renderer->setBlockPosition("sess", 1); - - $position = 1; - - foreach($this->items["sess"] as $item_data) - { - if (!$this->renderer->hasItem($item_data["child"])) - { - $html = $this->renderItem($item_data, $position++, true); - if ($html != "") - { - $this->renderer->addItemToBlock("sess", $item_data["type"], $item_data["child"], $html); - } - } - } - } + $this->items = $this->getContainerObject()->getSubItems($this->getContainerGUI()->isActiveAdministrationPanel()); + $this->clearAdminCommandsDetermination(); + + $this->initRenderer(); + + $output_html = $this->getContainerGUI()->getContainerPageHTML(); + + // get embedded blocks + if ($output_html != "") { + $output_html = $this->insertPageEmbeddedBlocks($output_html); + } + + if (is_array($this->items["sess"]) || + $this->items['sess_link']['prev']['value'] || + $this->items['sess_link']['next']['value']) { + $this->items['sess'] = ilUtil::sortArray($this->items['sess'], 'start', 'asc', true, false); + + if ($this->items['sess_link']['prev']['value']) { + $prefix = $this->renderSessionLimitLink(true); + } + if ($this->items['sess_link']['next']['value']) { + $postfix = $this->renderSessionLimitLink(false); + } + + $this->renderer->addTypeBlock("sess", $prefix, $postfix); + $this->renderer->setBlockPosition("sess", 1); + + $position = 1; + + foreach ($this->items["sess"] as $item_data) { + if (!$this->renderer->hasItem($item_data["child"])) { + $html = $this->renderItem($item_data, $position++, true); + if ($html != "") { + $this->renderer->addItemToBlock("sess", $item_data["type"], $item_data["child"], $html); + } + } + } + } - $pos = $this->getItemGroupsHTML(1); - - if (is_array($this->items["_all"])) - { - $this->renderer->addCustomBlock("_all", $lng->txt("content")); - $this->renderer->setBlockPosition("_all", ++$pos); - - $position = 1; - - foreach($this->items["_all"] as $item_data) - { - // #14599 - if ($item_data["type"] == "sess" || $item_data["type"] == "itgr") - { - continue; - } - - if (!$this->renderer->hasItem($item_data["child"])) - { - $html = $this->renderItem($item_data, $position++, true); - if ($html != "") - { - $this->renderer->addItemToBlock("_all", $item_data["type"], $item_data["child"], $html); - } - } - } - } + $pos = $this->getItemGroupsHTML(1); + + if (is_array($this->items["_all"])) { + $this->renderer->addCustomBlock("_all", $lng->txt("content")); + $this->renderer->setBlockPosition("_all", ++$pos); + + $position = 1; + + foreach ($this->items["_all"] as $item_data) { + // #14599 + if ($item_data["type"] == "sess" || $item_data["type"] == "itgr") { + continue; + } + + if (!$this->renderer->hasItem($item_data["child"])) { + $html = $this->renderItem($item_data, $position++, true); + if ($html != "") { + $this->renderer->addItemToBlock("_all", $item_data["type"], $item_data["child"], $html); + } + } + } + } - $output_html .= $this->renderer->getHTML(); - - $a_tpl->setVariable("CONTAINER_PAGE_CONTENT", $output_html); - } + $output_html .= $this->renderer->getHTML(); + + $a_tpl->setVariable("CONTAINER_PAGE_CONTENT", $output_html); + } - /** - * Show link to show/hide all previous/next sessions - * @return string - */ - protected function renderSessionLimitLink($a_previous = true) - { - $lng = $this->lng; - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - - $lng->loadLanguageModule('crs'); + /** + * Show link to show/hide all previous/next sessions + * @return string + */ + protected function renderSessionLimitLink($a_previous = true) + { + $lng = $this->lng; + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + + $lng->loadLanguageModule('crs'); - $tpl = new ilTemplate('tpl.container_list_item.html',true,true, - "Services/Container"); - $tpl->setVariable('DIV_CLASS','ilContainerListItemOuter'); - $tpl->setCurrentBlock('item_title_linked'); + $tpl = new ilTemplate( + 'tpl.container_list_item.html', + true, + true, + "Services/Container" + ); + $tpl->setVariable('DIV_CLASS', 'ilContainerListItemOuter'); + $tpl->setCurrentBlock('item_title_linked'); - if($a_previous) - { - $prefp = $ilUser->getPref('crs_sess_show_prev_'.$this->getContainerObject()->getId()); - - if($prefp) - { - $tpl->setVariable('TXT_TITLE_LINKED',$lng->txt('crs_link_hide_prev_sessions')); - $ilCtrl->setParameterByClass(get_class($this->getContainerGUI()),'crs_prev_sess',(int) !$prefp); - $tpl->setVariable('HREF_TITLE_LINKED',$ilCtrl->getLinkTargetByClass(get_class($this->getContainerGUI()))); - $ilCtrl->clearParametersByClass(get_class($this->getContainerGUI())); - } - else - { - $tpl->setVariable('TXT_TITLE_LINKED',$lng->txt('crs_link_show_all_prev_sessions')); - $ilCtrl->setParameterByClass(get_class($this->getContainerGUI()),'crs_prev_sess',(int) !$prefp); - $tpl->setVariable('HREF_TITLE_LINKED',$ilCtrl->getLinkTargetByClass(get_class($this->getContainerGUI()))); - $ilCtrl->clearParametersByClass(get_class($this->getContainerGUI())); - } - } - else - { - $prefn = $ilUser->getPref('crs_sess_show_next_'.$this->getContainerObject()->getId()); + if ($a_previous) { + $prefp = $ilUser->getPref('crs_sess_show_prev_' . $this->getContainerObject()->getId()); + + if ($prefp) { + $tpl->setVariable('TXT_TITLE_LINKED', $lng->txt('crs_link_hide_prev_sessions')); + $ilCtrl->setParameterByClass(get_class($this->getContainerGUI()), 'crs_prev_sess', (int) !$prefp); + $tpl->setVariable('HREF_TITLE_LINKED', $ilCtrl->getLinkTargetByClass(get_class($this->getContainerGUI()))); + $ilCtrl->clearParametersByClass(get_class($this->getContainerGUI())); + } else { + $tpl->setVariable('TXT_TITLE_LINKED', $lng->txt('crs_link_show_all_prev_sessions')); + $ilCtrl->setParameterByClass(get_class($this->getContainerGUI()), 'crs_prev_sess', (int) !$prefp); + $tpl->setVariable('HREF_TITLE_LINKED', $ilCtrl->getLinkTargetByClass(get_class($this->getContainerGUI()))); + $ilCtrl->clearParametersByClass(get_class($this->getContainerGUI())); + } + } else { + $prefn = $ilUser->getPref('crs_sess_show_next_' . $this->getContainerObject()->getId()); - if($prefn) - { - $tpl->setVariable('TXT_TITLE_LINKED',$lng->txt('crs_link_hide_next_sessions')); - $ilCtrl->setParameterByClass(get_class($this->getContainerGUI()),'crs_next_sess',(int) !$prefn); - $tpl->setVariable('HREF_TITLE_LINKED',$ilCtrl->getLinkTargetByClass(get_class($this->getContainerGUI()))); - $ilCtrl->clearParametersByClass(get_class($this->getContainerGUI())); - } - else - { - $tpl->setVariable('TXT_TITLE_LINKED',$lng->txt('crs_link_show_all_next_sessions')); - $ilCtrl->setParameterByClass(get_class($this->getContainerGUI()),'crs_next_sess',(int) !$prefn); - $tpl->setVariable('HREF_TITLE_LINKED',$ilCtrl->getLinkTargetByClass(get_class($this->getContainerGUI()))); - $ilCtrl->clearParametersByClass(get_class($this->getContainerGUI())); - } - } - $tpl->parseCurrentBlock(); + if ($prefn) { + $tpl->setVariable('TXT_TITLE_LINKED', $lng->txt('crs_link_hide_next_sessions')); + $ilCtrl->setParameterByClass(get_class($this->getContainerGUI()), 'crs_next_sess', (int) !$prefn); + $tpl->setVariable('HREF_TITLE_LINKED', $ilCtrl->getLinkTargetByClass(get_class($this->getContainerGUI()))); + $ilCtrl->clearParametersByClass(get_class($this->getContainerGUI())); + } else { + $tpl->setVariable('TXT_TITLE_LINKED', $lng->txt('crs_link_show_all_next_sessions')); + $ilCtrl->setParameterByClass(get_class($this->getContainerGUI()), 'crs_next_sess', (int) !$prefn); + $tpl->setVariable('HREF_TITLE_LINKED', $ilCtrl->getLinkTargetByClass(get_class($this->getContainerGUI()))); + $ilCtrl->clearParametersByClass(get_class($this->getContainerGUI())); + } + } + $tpl->parseCurrentBlock(); - return $tpl->get(); - } - - - /** - * add footer row - * - * @access public - * @param - * @return - */ - public function addFooterRow($tpl) - { - $ilCtrl = $this->ctrl; + return $tpl->get(); + } + + + /** + * add footer row + * + * @access public + * @param + * @return + */ + public function addFooterRow($tpl) + { + $ilCtrl = $this->ctrl; - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - - $tpl->setCurrentBlock('container_details_row'); - $tpl->setVariable('TXT_DETAILS',$this->lng->txt('details')); - $tpl->parseCurrentBlock(); - } - - /** - * init details - * - * @access protected - * @param - * @return - */ - protected function initDetails() - { - $ilUser = $this->user; - - if($_GET['expand']) - { - if($_GET['expand'] > 0) - { - $_SESSION['sess']['expanded'][abs((int) $_GET['expand'])] = self::DETAILS_ALL; - } - else - { - $_SESSION['sess']['expanded'][abs((int) $_GET['expand'])] = self::DETAILS_TITLE; - } - } - - include_once('./Modules/Session/classes/class.ilSessionAppointment.php'); - if($session = ilSessionAppointment::lookupNextSessionByCourse($this->getContainerObject()->getRefId())) - { - $this->force_details = $session; - } - elseif($session = ilSessionAppointment::lookupLastSessionByCourse($this->getContainerObject()->getRefId())) - { - $this->force_details = array($session); - } - } - - + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + + $tpl->setCurrentBlock('container_details_row'); + $tpl->setVariable('TXT_DETAILS', $this->lng->txt('details')); + $tpl->parseCurrentBlock(); + } + + /** + * init details + * + * @access protected + * @param + * @return + */ + protected function initDetails() + { + $ilUser = $this->user; + + if ($_GET['expand']) { + if ($_GET['expand'] > 0) { + $_SESSION['sess']['expanded'][abs((int) $_GET['expand'])] = self::DETAILS_ALL; + } else { + $_SESSION['sess']['expanded'][abs((int) $_GET['expand'])] = self::DETAILS_TITLE; + } + } + include_once('./Modules/Session/classes/class.ilSessionAppointment.php'); + if ($session = ilSessionAppointment::lookupNextSessionByCourse($this->getContainerObject()->getRefId())) { + $this->force_details = $session; + } elseif ($session = ilSessionAppointment::lookupLastSessionByCourse($this->getContainerObject()->getRefId())) { + $this->force_details = array($session); + } + } } // END class.ilContainerSessionsContentGUI -?> diff --git a/Services/Container/classes/class.ilContainerSimpleContentGUI.php b/Services/Container/classes/class.ilContainerSimpleContentGUI.php index 30c665b72cbaa7b567214e7ff2e6a142526e10cc..2db03993b0b0b37a1397d3da7afe32d368c88a86 100644 --- a/Services/Container/classes/class.ilContainerSimpleContentGUI.php +++ b/Services/Container/classes/class.ilContainerSimpleContentGUI.php @@ -1,24 +1,24 @@ lng = $DIC->language(); - $this->tabs = $DIC->tabs(); - $this->access = $DIC->access(); - $this->user = $DIC->user(); - parent::__construct($container_gui_obj); - $this->initDetails(); - } - - - /** - * Get content HTML for main column. - */ - function getMainContent() - { - $lng = $this->lng; - $ilTabs = $this->tabs; - - // see bug #7452 -// $ilTabs->setSubTabActive($this->getContainerObject()->getType().'_content'); - - include_once 'Services/Object/classes/class.ilObjectListGUIFactory.php'; - - $tpl = new ilTemplate("tpl.container_page.html", true, true, - "Services/Container"); - - // Feedback - // @todo -// $this->__showFeedBack(); - - $this->__showMaterials($tpl); - - return $tpl->get(); - } - - /** - * Show Materials - */ - function __showMaterials($a_tpl) - { - $ilAccess = $this->access; - $lng = $this->lng; - - $this->items = $this->getContainerObject()->getSubItems($this->getContainerGUI()->isActiveAdministrationPanel()); - $this->clearAdminCommandsDetermination(); - - $this->initRenderer(); - - $output_html = $this->getContainerGUI()->getContainerPageHTML(); - - // get embedded blocks - if ($output_html != "") - { - $output_html = $this->insertPageEmbeddedBlocks($output_html); - } - - // item groups - $this->getItemGroupsHTML(); - - if (is_array($this->items["_all"])) - { - $this->renderer->addCustomBlock("_all", $lng->txt("content")); - - $position = 1; - foreach($this->items["_all"] as $k => $item_data) - { - if (!$this->renderer->hasItem($item_data["child"])) - { - $html = $this->renderItem($item_data, $position++, true); - if ($html != "") - { - $this->renderer->addItemToBlock("_all", $item_data["type"], $item_data["child"], $html); - } - } - } - } - - $output_html .= $this->renderer->getHTML(); - - $a_tpl->setVariable("CONTAINER_PAGE_CONTENT", $output_html); - } - - /** - * init details - * - * @access protected - * @param - * @return - */ - protected function initDetails() - { - $ilUser = $this->user; - - if($_GET['expand']) - { - if($_GET['expand'] > 0) - { - $_SESSION['sess']['expanded'][abs((int) $_GET['expand'])] = self::DETAILS_ALL; - } - else - { - $_SESSION['sess']['expanded'][abs((int) $_GET['expand'])] = self::DETAILS_TITLE; - } - } - - - if($this->getContainerObject()->getType() == 'crs') - { - include_once('./Modules/Session/classes/class.ilSessionAppointment.php'); - if($session = ilSessionAppointment::lookupNextSessionByCourse($this->getContainerObject()->getRefId())) - { - $this->force_details = $session; - } - elseif($session = ilSessionAppointment::lookupLastSessionByCourse($this->getContainerObject()->getRefId())) - { - $this->force_details = $session; - } - } - } - - /** - * get details level - * - * @access public - * @param int $a_session_id - * @return int DEATAILS_LEVEL - */ - public function getDetailsLevel($a_session_id) - { - if($this->getContainerGUI()->isActiveAdministrationPanel()) - { - return self::DETAILS_DEACTIVATED; - } - if(isset($_SESSION['sess']['expanded'][$a_session_id])) - { - return $_SESSION['sess']['expanded'][$a_session_id]; - } - if($a_session_id == $this->force_details) - { - return self::DETAILS_ALL; - } - else - { - return self::DETAILS_TITLE; - } - } - - - + /** + * @var ilTabsGUI + */ + protected $tabs; + + protected $force_details; + + /** + * Constructor + * + */ + public function __construct($container_gui_obj) + { + global $DIC; + + $this->lng = $DIC->language(); + $this->tabs = $DIC->tabs(); + $this->access = $DIC->access(); + $this->user = $DIC->user(); + parent::__construct($container_gui_obj); + $this->initDetails(); + } + + + /** + * Get content HTML for main column. + */ + public function getMainContent() + { + $lng = $this->lng; + $ilTabs = $this->tabs; + + // see bug #7452 + // $ilTabs->setSubTabActive($this->getContainerObject()->getType().'_content'); + + include_once 'Services/Object/classes/class.ilObjectListGUIFactory.php'; + + $tpl = new ilTemplate( + "tpl.container_page.html", + true, + true, + "Services/Container" + ); + + // Feedback + // @todo + // $this->__showFeedBack(); + + $this->__showMaterials($tpl); + + return $tpl->get(); + } + + /** + * Show Materials + */ + public function __showMaterials($a_tpl) + { + $ilAccess = $this->access; + $lng = $this->lng; + + $this->items = $this->getContainerObject()->getSubItems($this->getContainerGUI()->isActiveAdministrationPanel()); + $this->clearAdminCommandsDetermination(); + + $this->initRenderer(); + + $output_html = $this->getContainerGUI()->getContainerPageHTML(); + + // get embedded blocks + if ($output_html != "") { + $output_html = $this->insertPageEmbeddedBlocks($output_html); + } + + // item groups + $this->getItemGroupsHTML(); + + if (is_array($this->items["_all"])) { + $this->renderer->addCustomBlock("_all", $lng->txt("content")); + + $position = 1; + foreach ($this->items["_all"] as $k => $item_data) { + if (!$this->renderer->hasItem($item_data["child"])) { + $html = $this->renderItem($item_data, $position++, true); + if ($html != "") { + $this->renderer->addItemToBlock("_all", $item_data["type"], $item_data["child"], $html); + } + } + } + } + + $output_html .= $this->renderer->getHTML(); + + $a_tpl->setVariable("CONTAINER_PAGE_CONTENT", $output_html); + } + + /** + * init details + * + * @access protected + * @param + * @return + */ + protected function initDetails() + { + $ilUser = $this->user; + + if ($_GET['expand']) { + if ($_GET['expand'] > 0) { + $_SESSION['sess']['expanded'][abs((int) $_GET['expand'])] = self::DETAILS_ALL; + } else { + $_SESSION['sess']['expanded'][abs((int) $_GET['expand'])] = self::DETAILS_TITLE; + } + } + + + if ($this->getContainerObject()->getType() == 'crs') { + include_once('./Modules/Session/classes/class.ilSessionAppointment.php'); + if ($session = ilSessionAppointment::lookupNextSessionByCourse($this->getContainerObject()->getRefId())) { + $this->force_details = $session; + } elseif ($session = ilSessionAppointment::lookupLastSessionByCourse($this->getContainerObject()->getRefId())) { + $this->force_details = $session; + } + } + } + + /** + * get details level + * + * @access public + * @param int $a_session_id + * @return int DEATAILS_LEVEL + */ + public function getDetailsLevel($a_session_id) + { + if ($this->getContainerGUI()->isActiveAdministrationPanel()) { + return self::DETAILS_DEACTIVATED; + } + if (isset($_SESSION['sess']['expanded'][$a_session_id])) { + return $_SESSION['sess']['expanded'][$a_session_id]; + } + if ($a_session_id == $this->force_details) { + return self::DETAILS_ALL; + } else { + return self::DETAILS_TITLE; + } + } } // END class.ilContainerSimpleContentGUI -?> diff --git a/Services/Container/classes/class.ilContainerSorting.php b/Services/Container/classes/class.ilContainerSorting.php index 76fd2c0733d7bc6e96aa6aa8bb24b64513b004ab..69812e3c3c5b6272b02ed1cdebab6ae629828628 100644 --- a/Services/Container/classes/class.ilContainerSorting.php +++ b/Services/Container/classes/class.ilContainerSorting.php @@ -1,668 +1,615 @@ * @version $Id$ -* -* -* @ingroup ServicesContainer +* +* +* @ingroup ServicesContainer */ class ilContainerSorting { - /** - * @var Logger - */ - protected $log; - - /** - * @var ilTree - */ - protected $tree; - - protected static $instances = array(); - - protected $obj_id; - protected $db; - - protected $sorting_settings = null; - const ORDER_DEFAULT = 999999; - - /** - * Constructor - * - * @access private - * @param int obj_id - * - */ - private function __construct($a_obj_id) - { - global $DIC; - - $this->log = $DIC["ilLog"]; - $this->tree = $DIC->repositoryTree(); - $ilDB = $DIC->database(); - - $this->db = $ilDB; - $this->obj_id = $a_obj_id; - - $this->read(); - } - - /** - * Get sorting settings - * @return ilContainerSortingSettings - */ - public function getSortingSettings() - { - return $this->sorting_settings; - } - - /** - * get instance by obj_id - * - * @access public - * @param int obj_id - * @return object ilContainerSorting - * @static - */ - public static function _getInstance($a_obj_id) - { - if(isset(self::$instances[$a_obj_id])) - { - return self::$instances[$a_obj_id]; - } - return self::$instances[$a_obj_id] = new ilContainerSorting($a_obj_id); - } - - /** - * Get positions of subitems - * @param int $a_obj_id - * @return - */ - public static function lookupPositions($a_obj_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT * FROM container_sorting WHERE ". - "obj_id = ".$ilDB->quote($a_obj_id,'integer'); - $res = $ilDB->query($query); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - $sorted[$row->child_id] = $row->position; - } - return $sorted ? $sorted : array(); - } - - /** - * clone sorting - * - * @return - * @static - */ - public function cloneSorting($a_target_id,$a_copy_id) - { - $ilDB = $this->db; - - $ilLog = ilLoggerFactory::getLogger("cont"); - $ilLog->debug("Cloning container sorting."); - - $target_obj_id = ilObject::_lookupObjId($a_target_id); - - include_once('./Services/CopyWizard/classes/class.ilCopyWizardOptions.php'); - $mappings = ilCopyWizardOptions::_getInstance($a_copy_id)->getMappings(); - - - // copy blocks sorting - $set = $ilDB->queryF("SELECT * FROM container_sorting_bl ". - " WHERE obj_id = %s ", - array("integer"), - array($this->obj_id) - ); - if ($rec = $ilDB->fetchAssoc($set)) - { - if ($rec["block_ids"] != "") - { - $ilLog->debug("Got block sorting for obj_id = ".$this->obj_id.": ".$rec["block_ids"]); - $new_ids = implode(";", array_map(function ($block_id) use ($mappings) { - if (is_numeric($block_id)) - { - $block_id = $mappings[$block_id]; - } - return $block_id; - }, explode(";", $rec["block_ids"]))); - - $ilDB->insert("container_sorting_bl", array( - "obj_id" => array("integer", $target_obj_id), - "block_ids" => array("text", $new_ids) - )); - - $ilLog->debug("Write block sorting for obj_id = ".$target_obj_id.": ".$new_ids); - } - } - - - $ilLog->debug("Read container_sorting for obj_id = ".$this->obj_id); - - $query = "SELECT * FROM container_sorting ". - "WHERE obj_id = ".$ilDB->quote($this->obj_id, 'integer'); - - $res = $ilDB->query($query); - - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - if(!isset($mappings[$row->child_id]) or !$mappings[$row->child_id]) - { - $ilLog->debug("No mapping found for child id:".$row->child_id); - continue; - } - - - $new_parent_id = 0; - if($row->parent_id) - { - // see bug #20347 - // at least in the case of sessions and item groups parent_ids in container sorting are object IDs but $mappings store references - if (in_array($row->parent_type, array("sess", "itgr"))) - { - $par_refs = ilObject::_getAllReferences($row->parent_id); - $par_ref_id = current($par_refs); // should be only one - $ilLog->debug("Got ref id: ".$par_ref_id." for obj_id ".$row->parent_id." map ref id: ".$mappings[$par_ref_id]."."); - if (isset($mappings[$par_ref_id])) - { - $new_parent_ref_id = $mappings[$par_ref_id]; - $new_parent_id = ilObject::_lookupObjectId($new_parent_ref_id); - } - } - else // not sure if this is still used for other cases that expect ref ids - { - $new_parent_id = $mappings[$row->parent_id]; - } - if ((int) $new_parent_id == 0) - { - $ilLog->debug("No mapping found for parent id:" . $row->parent_id . ", child_id: " . $row->child_id); - continue; - } - } - - $query = "DELETE FROM container_sorting ". - "WHERE obj_id = ".$ilDB->quote($target_obj_id,'integer')." ". - "AND child_id = ".$ilDB->quote($mappings[$row->child_id],'integer')." ". - "AND parent_type = ".$ilDB->quote($row->parent_type,'text').' '. - "AND parent_id = ".$ilDB->quote((int) $new_parent_id,'integer'); - $ilLog->debug($query); - $ilDB->manipulate($query); - - // Add new value - $query = "INSERT INTO container_sorting (obj_id,child_id,position,parent_type,parent_id) ". - "VALUES( ". - $ilDB->quote($target_obj_id ,'integer').", ". - $ilDB->quote($mappings[$row->child_id] ,'integer').", ". - $ilDB->quote($row->position,'integer').", ". - $ilDB->quote($row->parent_type,'text').", ". - $ilDB->quote((int) $new_parent_id,'integer'). - ")"; - $ilLog->debug($query); - $ilDB->manipulate($query); - } - return true; - } - - - - /** - * sort subitems - * - * @access public - * @param array item data - * @return array sorted item data - */ - public function sortItems($a_items) - { - $sorted = array(); - if($this->getSortingSettings()->getSortMode() != ilContainer::SORT_MANUAL) - { - switch($this->getSortingSettings()->getSortMode()) - { - case ilContainer::SORT_TITLE: - foreach((array) $a_items as $type => $data) - { - // #16311 - sorting will remove keys (prev/next) - if($type == 'sess_link') - { - $sorted[$type] = $data; - continue; - } - - // this line used until #4389 has been fixed (3.10.6) - // reanimated with 4.4.0 - $sorted[$type] = ilUtil::sortArray( - (array) $data, - 'title', - ($this->getSortingSettings()->getSortDirection() == ilContainer::SORT_DIRECTION_ASC) ? 'asc' : 'desc', - FALSE - ); - - // the next line tried to use db sorting and has replaced sortArray due to bug #4389 - // but leads to bug #12165. PHP should be able to do a proper sorting, if the locale - // is set correctly, so we witch back to sortArray (with 4.4.0) and see what - // feedback we get - // (next line has been used from 3.10.6 to 4.3.x) + /** + * @var Logger + */ + protected $log; + + /** + * @var ilTree + */ + protected $tree; + + protected static $instances = array(); + + protected $obj_id; + protected $db; + + protected $sorting_settings = null; + const ORDER_DEFAULT = 999999; + + /** + * Constructor + * + * @access private + * @param int obj_id + * + */ + private function __construct($a_obj_id) + { + global $DIC; + + $this->log = $DIC["ilLog"]; + $this->tree = $DIC->repositoryTree(); + $ilDB = $DIC->database(); + + $this->db = $ilDB; + $this->obj_id = $a_obj_id; + + $this->read(); + } + + /** + * Get sorting settings + * @return ilContainerSortingSettings + */ + public function getSortingSettings() + { + return $this->sorting_settings; + } + + /** + * get instance by obj_id + * + * @access public + * @param int obj_id + * @return object ilContainerSorting + * @static + */ + public static function _getInstance($a_obj_id) + { + if (isset(self::$instances[$a_obj_id])) { + return self::$instances[$a_obj_id]; + } + return self::$instances[$a_obj_id] = new ilContainerSorting($a_obj_id); + } + + /** + * Get positions of subitems + * @param int $a_obj_id + * @return + */ + public static function lookupPositions($a_obj_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT * FROM container_sorting WHERE " . + "obj_id = " . $ilDB->quote($a_obj_id, 'integer'); + $res = $ilDB->query($query); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + $sorted[$row->child_id] = $row->position; + } + return $sorted ? $sorted : array(); + } + + /** + * clone sorting + * + * @return + * @static + */ + public function cloneSorting($a_target_id, $a_copy_id) + { + $ilDB = $this->db; + + $ilLog = ilLoggerFactory::getLogger("cont"); + $ilLog->debug("Cloning container sorting."); + + $target_obj_id = ilObject::_lookupObjId($a_target_id); + + include_once('./Services/CopyWizard/classes/class.ilCopyWizardOptions.php'); + $mappings = ilCopyWizardOptions::_getInstance($a_copy_id)->getMappings(); + + + // copy blocks sorting + $set = $ilDB->queryF( + "SELECT * FROM container_sorting_bl " . + " WHERE obj_id = %s ", + array("integer"), + array($this->obj_id) + ); + if ($rec = $ilDB->fetchAssoc($set)) { + if ($rec["block_ids"] != "") { + $ilLog->debug("Got block sorting for obj_id = " . $this->obj_id . ": " . $rec["block_ids"]); + $new_ids = implode(";", array_map(function ($block_id) use ($mappings) { + if (is_numeric($block_id)) { + $block_id = $mappings[$block_id]; + } + return $block_id; + }, explode(";", $rec["block_ids"]))); + + $ilDB->insert("container_sorting_bl", array( + "obj_id" => array("integer", $target_obj_id), + "block_ids" => array("text", $new_ids) + )); + + $ilLog->debug("Write block sorting for obj_id = " . $target_obj_id . ": " . $new_ids); + } + } + + + $ilLog->debug("Read container_sorting for obj_id = " . $this->obj_id); + + $query = "SELECT * FROM container_sorting " . + "WHERE obj_id = " . $ilDB->quote($this->obj_id, 'integer'); + + $res = $ilDB->query($query); + + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + if (!isset($mappings[$row->child_id]) or !$mappings[$row->child_id]) { + $ilLog->debug("No mapping found for child id:" . $row->child_id); + continue; + } + + + $new_parent_id = 0; + if ($row->parent_id) { + // see bug #20347 + // at least in the case of sessions and item groups parent_ids in container sorting are object IDs but $mappings store references + if (in_array($row->parent_type, array("sess", "itgr"))) { + $par_refs = ilObject::_getAllReferences($row->parent_id); + $par_ref_id = current($par_refs); // should be only one + $ilLog->debug("Got ref id: " . $par_ref_id . " for obj_id " . $row->parent_id . " map ref id: " . $mappings[$par_ref_id] . "."); + if (isset($mappings[$par_ref_id])) { + $new_parent_ref_id = $mappings[$par_ref_id]; + $new_parent_id = ilObject::_lookupObjectId($new_parent_ref_id); + } + } else { // not sure if this is still used for other cases that expect ref ids + $new_parent_id = $mappings[$row->parent_id]; + } + if ((int) $new_parent_id == 0) { + $ilLog->debug("No mapping found for parent id:" . $row->parent_id . ", child_id: " . $row->child_id); + continue; + } + } + + $query = "DELETE FROM container_sorting " . + "WHERE obj_id = " . $ilDB->quote($target_obj_id, 'integer') . " " . + "AND child_id = " . $ilDB->quote($mappings[$row->child_id], 'integer') . " " . + "AND parent_type = " . $ilDB->quote($row->parent_type, 'text') . ' ' . + "AND parent_id = " . $ilDB->quote((int) $new_parent_id, 'integer'); + $ilLog->debug($query); + $ilDB->manipulate($query); + + // Add new value + $query = "INSERT INTO container_sorting (obj_id,child_id,position,parent_type,parent_id) " . + "VALUES( " . + $ilDB->quote($target_obj_id, 'integer') . ", " . + $ilDB->quote($mappings[$row->child_id], 'integer') . ", " . + $ilDB->quote($row->position, 'integer') . ", " . + $ilDB->quote($row->parent_type, 'text') . ", " . + $ilDB->quote((int) $new_parent_id, 'integer') . + ")"; + $ilLog->debug($query); + $ilDB->manipulate($query); + } + return true; + } + + + + /** + * sort subitems + * + * @access public + * @param array item data + * @return array sorted item data + */ + public function sortItems($a_items) + { + $sorted = array(); + if ($this->getSortingSettings()->getSortMode() != ilContainer::SORT_MANUAL) { + switch ($this->getSortingSettings()->getSortMode()) { + case ilContainer::SORT_TITLE: + foreach ((array) $a_items as $type => $data) { + // #16311 - sorting will remove keys (prev/next) + if ($type == 'sess_link') { + $sorted[$type] = $data; + continue; + } + + // this line used until #4389 has been fixed (3.10.6) + // reanimated with 4.4.0 + $sorted[$type] = ilUtil::sortArray( + (array) $data, + 'title', + ($this->getSortingSettings()->getSortDirection() == ilContainer::SORT_DIRECTION_ASC) ? 'asc' : 'desc', + false + ); + + // the next line tried to use db sorting and has replaced sortArray due to bug #4389 + // but leads to bug #12165. PHP should be able to do a proper sorting, if the locale + // is set correctly, so we witch back to sortArray (with 4.4.0) and see what + // feedback we get + // (next line has been used from 3.10.6 to 4.3.x) // $sorted[$type] = $data; - } - return $sorted ? $sorted : array(); - - case ilContainer::SORT_ACTIVATION: - foreach((array) $a_items as $type => $data) - { - // #16311 - sorting will remove keys (prev/next) - if($type == 'sess_link') - { - $sorted[$type] = $data; - continue; - } - - $sorted[$type] = ilUtil::sortArray( - (array) $data, - 'start', - ($this->getSortingSettings()->getSortDirection() == ilContainer::SORT_DIRECTION_ASC) ? 'asc' : 'desc', - TRUE - ); - - } - return $sorted ? $sorted : array(); - - - case ilContainer::SORT_CREATION: - foreach((array) $a_items as $type => $data) - { - // #16311 - sorting will remove keys (prev/next) - if($type == 'sess_link') - { - $sorted[$type] = $data; - continue; - } - - $sorted[$type] = ilUtil::sortArray( - (array) $data, - 'create_date', - ($this->getSortingSettings()->getSortDirection() == ilContainer::SORT_DIRECTION_ASC) ? 'asc' : 'desc', - TRUE - ); - } - return $sorted ? $sorted : array(); - } - return $a_items; - } - if(!is_array($a_items) || !count($a_items)) - { - return $a_items; - } - $sorted = array(); - foreach((array) $a_items as $type => $data) - { - if($type == 'sess_link') - { - $sorted[$type] = $data; - continue; - } - - // Add position - $items = array(); - foreach((array) $data as $key => $item) - { - $items[$key] = $item; - if(is_array($this->sorting['all']) and isset($this->sorting['all'][$item['child']])) - { - $items[$key]['position'] = $this->sorting['all'][$item['child']]; - } - else - { - $items[$key]['position'] = self::ORDER_DEFAULT; - } - } - - $items = $this->sortOrderDefault($items); - - switch($type) - { - case '_all': - $sorted[$type] = ilUtil::sortArray((array) $items,'position','asc',true); - break; - - case '_non_sess': - $sorted[$type] = ilUtil::sortArray((array) $items,'position','asc',true); - break; - - default: - $sorted[$type] = ilUtil::sortArray((array) $items,'position','asc',true); - break; - } - } - return $sorted ? $sorted : array(); - } - - /** - * sort subitems (items of sessions or learning objectives) - * - * @access public - * @param - * @return - */ - public function sortSubItems($a_parent_type,$a_parent_id,$a_items) - { - switch($this->getSortingSettings()->getSortMode()) - { - case ilContainer::SORT_MANUAL: - $items = array(); - foreach($a_items as $key => $item) - { - $items[$key] = $item; - $items[$key]['position'] = isset($this->sorting[$a_parent_type][$a_parent_id][$item['child']]) ? - $this->sorting[$a_parent_type][$a_parent_id][$item['child']] : self::ORDER_DEFAULT; - } - - $items = $this->sortOrderDefault($items); - return ilUtil::sortArray((array) $items,'position','asc',TRUE); - - - case ilContainer::SORT_ACTIVATION: - return ilUtil::sortArray( - (array) $a_items, - 'start', - ($this->getSortingSettings()->getSortDirection() == ilContainer::SORT_DIRECTION_ASC) ? 'asc' : 'desc', - TRUE - ); - - case ilContainer::SORT_CREATION: - return ilUtil::sortArray( - (array) $a_items, - 'create_date', - ($this->getSortingSettings()->getSortDirection() == ilContainer::SORT_DIRECTION_ASC) ? 'asc' : 'desc', - TRUE - ); - - default: - case ilContainer::SORT_TITLE: - return ilUtil::sortArray( - (array) $a_items, - 'title', - ($this->getSortingSettings()->getSortDirection() == ilContainer::SORT_DIRECTION_ASC) ? 'asc' : 'desc', - FALSE - ); - } - - } - - /** - * Save post - * - * @access public - * @param array of positions e.g array(crs => array(1,2,3),'lres' => array(3,5,6)) - * - */ - public function savePost($a_type_positions) - { - if(!is_array($a_type_positions)) - { - return false; - } - $items = []; - foreach($a_type_positions as $key => $position) - { - if($key == "blocks") - { - $this->saveBlockPositions($position); - } - else if(!is_array($position)) - { - $items[$key] = $position * 100; - } - else - { - foreach($position as $parent_id => $sub_items) - { - $this->saveSubItems($key,$parent_id,$sub_items ? $sub_items : array()); - } - } - } - - if(!count($items)) { - return $this->saveItems(array()); - } - - asort($items); - $new_indexed = []; - $position = 0; - foreach($items as $key => $null) - { - $new_indexed[$key] = ++$position; - } - - $this->saveItems($new_indexed); - } - - - /** - * save items - * - * @access protected - * @param string parent_type only used for sessions and objectives in the moment. Otherwise empty - * @param int parent id - * @param array array of items - * @return - */ - protected function saveItems($a_items) - { - $ilDB = $this->db; - - foreach($a_items as $child_id => $position) - { - $ilDB->replace( - 'container_sorting', - array( - 'obj_id' => array('integer',$this->obj_id), - 'child_id' => array('integer',$child_id), - 'parent_id' => array('integer',0) - ), - array( - 'parent_type' => array('text',''), - 'position' => array('integer',$position) - ) - ); - } - return true; - } - - /** - * Save subitem ordering (sessions, learning objectives) - * @param string $a_parent_type - * @param integer $a_parent_id - * @param array $a_items - * @return - */ - protected function saveSubItems($a_parent_type,$a_parent_id,$a_items) - { - $ilDB = $this->db; - - foreach($a_items as $child_id => $position) - { - $ilDB->replace( - 'container_sorting', - array( - 'obj_id' => array('integer',$this->obj_id), - 'child_id' => array('integer',$child_id), - 'parent_id' => array('integer',$a_parent_id) - ), - array( - 'parent_type' => array('text',$a_parent_type), - 'position' => array('integer',$position) - ) - ); - } - return true; - - } - - /** - * Save block custom positions (for current object id) - * - * @param array $a_values - */ - protected function saveBlockPositions(array $a_values) - { - $ilDB = $this->db; - - asort($a_values); - $ilDB->replace( - 'container_sorting_bl', - array( - 'obj_id' => array('integer',$this->obj_id) - ), - array( - 'block_ids' => array('text', implode(";", array_keys($a_values))) - ) - ); - } - - /** - * Read block custom positions (for current object id) - * - * @return array - */ - public function getBlockPositions() - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT block_ids". - " FROM container_sorting_bl". - " WHERE obj_id = ".$ilDB->quote($this->obj_id, "integer")); - $row = $ilDB->fetchAssoc($set); - if($row["block_ids"]) - { - return explode(";", $row["block_ids"]); - } - } - - - /** - * Read - * - * @access private - * - */ - private function read() - { - $tree = $this->tree; - - if(!$this->obj_id) - { - $this->sorting_settings = new ilContainerSortingSettings(); - return true; - } - - $sorting_settings = ilContainerSortingSettings::getInstanceByObjId($this->obj_id); - $this->sorting_settings = $sorting_settings->loadEffectiveSettings(); - $query = "SELECT * FROM container_sorting ". - "WHERE obj_id = ".$this->db->quote($this->obj_id ,'integer')." ORDER BY position"; - $res = $this->db->query($query); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - if($row->parent_id) - { - $this->sorting[$row->parent_type][$row->parent_id][$row->child_id] = $row->position; - } - else - { - $this->sorting['all'][$row->child_id] = $row->position; - } - } - return true; - } - - /** - * Position and order sort order for new object without position in manual sorting type - * - * @param $items - * @return array - */ - private function sortOrderDefault($items) - { - $no_position = array(); - - foreach($items as $key => $item) - { - if($item["position"] == self::ORDER_DEFAULT) - { - $no_position[]= array("key" => $key, "title" => $item["title"], "create_date" => $item["create_date"], - "start" => $item["start"]); - } - - } - - if(!count($no_position)) - { - return $items; - } - - switch($this->getSortingSettings()->getSortNewItemsOrder()) - { - case ilContainer::SORT_NEW_ITEMS_ORDER_TITLE: - $no_position = ilUtil::sortArray( (array) $no_position, - 'title', - ($this->getSortingSettings()->getSortDirection() == ilContainer::SORT_DIRECTION_ASC) ? 'asc' : 'desc', - TRUE); - break; - case ilContainer::SORT_NEW_ITEMS_ORDER_CREATION: - $no_position = ilUtil::sortArray((array) $no_position, - 'create_date', - ($this->getSortingSettings()->getSortDirection() == ilContainer::SORT_DIRECTION_ASC) ? 'asc' : 'desc', - TRUE); - break; - case ilContainer::SORT_NEW_ITEMS_ORDER_ACTIVATION: - $no_position = ilUtil::sortArray((array) $no_position, - 'start', - ($this->getSortingSettings()->getSortDirection() == ilContainer::SORT_DIRECTION_ASC) ? 'asc' : 'desc', - TRUE); - - } - $count = $this->getSortingSettings()->getSortNewItemsPosition() - == ilContainer::SORT_NEW_ITEMS_POSITION_TOP ? -900000 : 900000; - - foreach($no_position as $values) - { - $items[$values["key"]]["position"] = $count; - $count++; - } - return $items; - } + } + return $sorted ? $sorted : array(); + + case ilContainer::SORT_ACTIVATION: + foreach ((array) $a_items as $type => $data) { + // #16311 - sorting will remove keys (prev/next) + if ($type == 'sess_link') { + $sorted[$type] = $data; + continue; + } + + $sorted[$type] = ilUtil::sortArray( + (array) $data, + 'start', + ($this->getSortingSettings()->getSortDirection() == ilContainer::SORT_DIRECTION_ASC) ? 'asc' : 'desc', + true + ); + } + return $sorted ? $sorted : array(); + + + case ilContainer::SORT_CREATION: + foreach ((array) $a_items as $type => $data) { + // #16311 - sorting will remove keys (prev/next) + if ($type == 'sess_link') { + $sorted[$type] = $data; + continue; + } + + $sorted[$type] = ilUtil::sortArray( + (array) $data, + 'create_date', + ($this->getSortingSettings()->getSortDirection() == ilContainer::SORT_DIRECTION_ASC) ? 'asc' : 'desc', + true + ); + } + return $sorted ? $sorted : array(); + } + return $a_items; + } + if (!is_array($a_items) || !count($a_items)) { + return $a_items; + } + $sorted = array(); + foreach ((array) $a_items as $type => $data) { + if ($type == 'sess_link') { + $sorted[$type] = $data; + continue; + } + + // Add position + $items = array(); + foreach ((array) $data as $key => $item) { + $items[$key] = $item; + if (is_array($this->sorting['all']) and isset($this->sorting['all'][$item['child']])) { + $items[$key]['position'] = $this->sorting['all'][$item['child']]; + } else { + $items[$key]['position'] = self::ORDER_DEFAULT; + } + } + + $items = $this->sortOrderDefault($items); + + switch ($type) { + case '_all': + $sorted[$type] = ilUtil::sortArray((array) $items, 'position', 'asc', true); + break; + + case '_non_sess': + $sorted[$type] = ilUtil::sortArray((array) $items, 'position', 'asc', true); + break; + + default: + $sorted[$type] = ilUtil::sortArray((array) $items, 'position', 'asc', true); + break; + } + } + return $sorted ? $sorted : array(); + } + + /** + * sort subitems (items of sessions or learning objectives) + * + * @access public + * @param + * @return + */ + public function sortSubItems($a_parent_type, $a_parent_id, $a_items) + { + switch ($this->getSortingSettings()->getSortMode()) { + case ilContainer::SORT_MANUAL: + $items = array(); + foreach ($a_items as $key => $item) { + $items[$key] = $item; + $items[$key]['position'] = isset($this->sorting[$a_parent_type][$a_parent_id][$item['child']]) ? + $this->sorting[$a_parent_type][$a_parent_id][$item['child']] : self::ORDER_DEFAULT; + } + + $items = $this->sortOrderDefault($items); + return ilUtil::sortArray((array) $items, 'position', 'asc', true); + + + case ilContainer::SORT_ACTIVATION: + return ilUtil::sortArray( + (array) $a_items, + 'start', + ($this->getSortingSettings()->getSortDirection() == ilContainer::SORT_DIRECTION_ASC) ? 'asc' : 'desc', + true + ); + + case ilContainer::SORT_CREATION: + return ilUtil::sortArray( + (array) $a_items, + 'create_date', + ($this->getSortingSettings()->getSortDirection() == ilContainer::SORT_DIRECTION_ASC) ? 'asc' : 'desc', + true + ); + + default: + case ilContainer::SORT_TITLE: + return ilUtil::sortArray( + (array) $a_items, + 'title', + ($this->getSortingSettings()->getSortDirection() == ilContainer::SORT_DIRECTION_ASC) ? 'asc' : 'desc', + false + ); + } + } + + /** + * Save post + * + * @access public + * @param array of positions e.g array(crs => array(1,2,3),'lres' => array(3,5,6)) + * + */ + public function savePost($a_type_positions) + { + if (!is_array($a_type_positions)) { + return false; + } + $items = []; + foreach ($a_type_positions as $key => $position) { + if ($key == "blocks") { + $this->saveBlockPositions($position); + } elseif (!is_array($position)) { + $items[$key] = $position * 100; + } else { + foreach ($position as $parent_id => $sub_items) { + $this->saveSubItems($key, $parent_id, $sub_items ? $sub_items : array()); + } + } + } + + if (!count($items)) { + return $this->saveItems(array()); + } + + asort($items); + $new_indexed = []; + $position = 0; + foreach ($items as $key => $null) { + $new_indexed[$key] = ++$position; + } + + $this->saveItems($new_indexed); + } + + + /** + * save items + * + * @access protected + * @param string parent_type only used for sessions and objectives in the moment. Otherwise empty + * @param int parent id + * @param array array of items + * @return + */ + protected function saveItems($a_items) + { + $ilDB = $this->db; + + foreach ($a_items as $child_id => $position) { + $ilDB->replace( + 'container_sorting', + array( + 'obj_id' => array('integer',$this->obj_id), + 'child_id' => array('integer',$child_id), + 'parent_id' => array('integer',0) + ), + array( + 'parent_type' => array('text',''), + 'position' => array('integer',$position) + ) + ); + } + return true; + } + + /** + * Save subitem ordering (sessions, learning objectives) + * @param string $a_parent_type + * @param integer $a_parent_id + * @param array $a_items + * @return + */ + protected function saveSubItems($a_parent_type, $a_parent_id, $a_items) + { + $ilDB = $this->db; + + foreach ($a_items as $child_id => $position) { + $ilDB->replace( + 'container_sorting', + array( + 'obj_id' => array('integer',$this->obj_id), + 'child_id' => array('integer',$child_id), + 'parent_id' => array('integer',$a_parent_id) + ), + array( + 'parent_type' => array('text',$a_parent_type), + 'position' => array('integer',$position) + ) + ); + } + return true; + } + + /** + * Save block custom positions (for current object id) + * + * @param array $a_values + */ + protected function saveBlockPositions(array $a_values) + { + $ilDB = $this->db; + + asort($a_values); + $ilDB->replace( + 'container_sorting_bl', + array( + 'obj_id' => array('integer',$this->obj_id) + ), + array( + 'block_ids' => array('text', implode(";", array_keys($a_values))) + ) + ); + } + + /** + * Read block custom positions (for current object id) + * + * @return array + */ + public function getBlockPositions() + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT block_ids" . + " FROM container_sorting_bl" . + " WHERE obj_id = " . $ilDB->quote($this->obj_id, "integer")); + $row = $ilDB->fetchAssoc($set); + if ($row["block_ids"]) { + return explode(";", $row["block_ids"]); + } + } + + + /** + * Read + * + * @access private + * + */ + private function read() + { + $tree = $this->tree; + + if (!$this->obj_id) { + $this->sorting_settings = new ilContainerSortingSettings(); + return true; + } + + $sorting_settings = ilContainerSortingSettings::getInstanceByObjId($this->obj_id); + $this->sorting_settings = $sorting_settings->loadEffectiveSettings(); + $query = "SELECT * FROM container_sorting " . + "WHERE obj_id = " . $this->db->quote($this->obj_id, 'integer') . " ORDER BY position"; + $res = $this->db->query($query); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + if ($row->parent_id) { + $this->sorting[$row->parent_type][$row->parent_id][$row->child_id] = $row->position; + } else { + $this->sorting['all'][$row->child_id] = $row->position; + } + } + return true; + } + + /** + * Position and order sort order for new object without position in manual sorting type + * + * @param $items + * @return array + */ + private function sortOrderDefault($items) + { + $no_position = array(); + + foreach ($items as $key => $item) { + if ($item["position"] == self::ORDER_DEFAULT) { + $no_position[]= array("key" => $key, "title" => $item["title"], "create_date" => $item["create_date"], + "start" => $item["start"]); + } + } + + if (!count($no_position)) { + return $items; + } + + switch ($this->getSortingSettings()->getSortNewItemsOrder()) { + case ilContainer::SORT_NEW_ITEMS_ORDER_TITLE: + $no_position = ilUtil::sortArray( + (array) $no_position, + 'title', + ($this->getSortingSettings()->getSortDirection() == ilContainer::SORT_DIRECTION_ASC) ? 'asc' : 'desc', + true + ); + break; + case ilContainer::SORT_NEW_ITEMS_ORDER_CREATION: + $no_position = ilUtil::sortArray( + (array) $no_position, + 'create_date', + ($this->getSortingSettings()->getSortDirection() == ilContainer::SORT_DIRECTION_ASC) ? 'asc' : 'desc', + true + ); + break; + case ilContainer::SORT_NEW_ITEMS_ORDER_ACTIVATION: + $no_position = ilUtil::sortArray( + (array) $no_position, + 'start', + ($this->getSortingSettings()->getSortDirection() == ilContainer::SORT_DIRECTION_ASC) ? 'asc' : 'desc', + true + ); + + } + $count = $this->getSortingSettings()->getSortNewItemsPosition() + == ilContainer::SORT_NEW_ITEMS_POSITION_TOP ? -900000 : 900000; + + foreach ($no_position as $values) { + $items[$values["key"]]["position"] = $count; + $count++; + } + return $items; + } } - - -?> \ No newline at end of file diff --git a/Services/Container/classes/class.ilContainerSortingSettings.php b/Services/Container/classes/class.ilContainerSortingSettings.php index 5bf334a2d4b2e38060e8b0e76234e53708e88c8c..7f4cbd0d6db74bde08a60f2b1486569db1109648 100644 --- a/Services/Container/classes/class.ilContainerSortingSettings.php +++ b/Services/Container/classes/class.ilContainerSortingSettings.php @@ -1,562 +1,539 @@ * @version $Id$ -* -* -* @ingroup ServicesContainer +* +* +* @ingroup ServicesContainer */ class ilContainerSortingSettings { - /** - * @var ilTree - */ - protected $tree; - - private static $instances = array(); - - protected $obj_id; - protected $sort_mode = ilContainer::SORT_TITLE; - protected $sort_direction = ilContainer::SORT_DIRECTION_ASC; - protected $new_items_position = ilContainer::SORT_NEW_ITEMS_POSITION_BOTTOM; - protected $new_items_order = ilContainer::SORT_NEW_ITEMS_ORDER_TITLE; - - protected $db; - - /** - * Constructor - * - * @access public - * @param - * - */ - public function __construct($a_obj_id = 0) - { - global $DIC; - - $this->tree = $DIC->repositoryTree(); - $ilDB = $DIC->database(); - - $this->obj_id = $a_obj_id; - $this->db = $ilDB; - - $this->read(); - } - - /** - * Get singleton instance - * @param type $a_obj_id - * @return ilContainerSortingSettings - */ - public static function getInstanceByObjId($a_obj_id) - { - if(self::$instances[$a_obj_id]) - { - return self::$instances[$a_obj_id]; - } - return self::$instances[$a_obj_id] = new self($a_obj_id); - } - - /** - * Load inherited settings - * @return ilContainerSortingSettings - */ - public function loadEffectiveSettings() - { - if($this->getSortMode() != ilContainer::SORT_INHERIT) - { - return $this; - } - - $effective_settings = $this->getInheritedSettings($this->obj_id); - $inherited = clone $this; - - if($effective_settings->getSortMode() == ilContainer::SORT_INHERIT) - { - $inherited->setSortMode(ilContainer::SORT_TITLE); - } - else - { - $inherited->setSortMode($effective_settings->getSortMode()); - $inherited->setSortNewItemsOrder($effective_settings->getSortNewItemsOrder()); - $inherited->setSortNewItemsPosition($effective_settings->getSortNewItemsPosition()); - } - return $inherited; - } - - - /** - * Read inherited settings of course/group - * @param int $a_container_obj_id - */ - public function getInheritedSettings($a_container_obj_id) - { - $tree = $this->tree; - - if(!$a_container_obj_id) - { - $a_container_obj_id = $this->obj_id; - } - - $ref_ids = ilObject::_getAllReferences($a_container_obj_id); - $ref_id = current($ref_ids); - - if($cont_ref_id = $tree->checkForParentType($ref_id,'grp',true)) - { - $parent_obj_id = ilObject::_lookupObjId($cont_ref_id); - $parent_settings = self::getInstanceByObjId($parent_obj_id); - - if($parent_settings->getSortMode() == ilContainer::SORT_INHERIT) - { - return $this->getInheritedSettings($parent_obj_id); - } - return $parent_settings; - } - - if($cont_ref_id = $tree->checkForParentType($ref_id,'crs',true)) - { - $parent_obj_id = ilObject::_lookupObjId($cont_ref_id); - $parent_settings = self::getInstanceByObjId($parent_obj_id); - return $parent_settings; - } - // no parent settings found => return current settings - return $this; - } - - - public static function _readSortMode($a_obj_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT * FROM container_sorting_set ". - "WHERE obj_id = ".$ilDB->quote($a_obj_id ,'integer')." "; - $res = $ilDB->query($query); - - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - return $row->sort_mode; - } - return ilContainer::SORT_INHERIT; - } - - - /** - * lookup sort mode - * - * @access public - * @static - * - * @param int obj_id - */ - public static function _lookupSortMode($a_obj_id) - { - global $DIC; - - $tree = $DIC->repositoryTree(); - $ilDB = $DIC->database(); - $objDefinition = $DIC["objDefinition"]; - - // Try to read from table - $query = "SELECT * FROM container_sorting_set ". - "WHERE obj_id = ".$ilDB->quote($a_obj_id ,'integer')." "; - $res = $ilDB->query($query); - - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - if($row->sort_mode != ilContainer::SORT_INHERIT) - { - return $row->sort_mode; - } - } - return self::lookupSortModeFromParentContainer($a_obj_id); - } - - /** - * Lookup sort mode from parent container - * @param object $a_obj_id - * @return - */ - public static function lookupSortModeFromParentContainer($a_obj_id) - { - $settings = self::getInstanceByObjId($a_obj_id); - $inherited_settings = $settings->getInheritedSettings($a_obj_id); - return $inherited_settings->getSortMode(); - } - - /** - * Clone settings - * - * @access public - * @static - * - * @param int orig obj_id - * @þaram int new obj_id - */ - public static function _cloneSettings($a_old_id,$a_new_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT sort_mode,sort_direction,new_items_position,new_items_order ". - "FROM container_sorting_set ". - "WHERE obj_id = ".$ilDB->quote($a_old_id ,'integer')." "; - $res = $ilDB->query($query); - while($row = $ilDB->fetchAssoc($res)) - { - $query = "DELETE FROM container_sorting_set ". - "WHERE obj_id = ".$ilDB->quote($a_new_id)." "; - $ilDB->manipulate($query); - - $query = "INSERT INTO container_sorting_set ". - "(obj_id,sort_mode, sort_direction, new_items_position, new_items_order) ". - "VALUES( ". - $ilDB->quote($a_new_id ,'integer').", ". - $ilDB->quote($row["sort_mode"],'integer').", ". - $ilDB->quote($row["sort_direction"],'integer').', '. - $ilDB->quote($row["new_items_position"],'integer').', '. - $ilDB->quote($row["new_items_order"],'integer').' '. - ")"; - $ilDB->manipulate($query); - } - return true; - } - - /** - * get sort mode - * - * @access public - * - */ - public function getSortMode() - { - return $this->sort_mode ? $this->sort_mode : 0; - } - - /** - * Get sort direction - * @return type - */ - public function getSortDirection() - { - return $this->sort_direction ? $this->sort_direction : ilContainer::SORT_DIRECTION_ASC; - } - - /** - * GET new item position - * @return int position - */ - public function getSortNewItemsPosition() - { - return $this->new_items_position; - } - - /** - * GET new item order - * @return int position - */ - public function getSortNewItemsOrder() - { - return $this->new_items_order; - } - - /** - * set sort mode - * - * @access public - * @param int MODE_TITLE | MODE_MANUAL | MODE_ACTIVATION - * - */ - public function setSortMode($a_mode) - { - $this->sort_mode = (int) $a_mode; - } - - /** - * Set sort direction - * @param type $a_direction - */ - public function setSortDirection($a_direction) - { - $this->sort_direction = (int) $a_direction; - } - - /** - * SET new item position - * @param int $a_position - */ - public function setSortNewItemsPosition($a_position) - { - $this->new_items_position = (int)$a_position; - } - - /** - * SET new item order - * @param int $a_order - */ - public function setSortNewItemsOrder($a_order) - { - $this->new_items_order = (int)$a_order; - } - - /** - * Update - * - * @access public - * - */ - public function update() - { - $ilDB = $this->db; - - $query = "DELETE FROM container_sorting_set ". - "WHERE obj_id = ".$ilDB->quote($this->obj_id,'integer'); - $res = $ilDB->manipulate($query); - - $this->save(); - } - - /** - * save settings - * - * @access public - * - */ - public function save() - { - $ilDB = $this->db; - - $query = "INSERT INTO container_sorting_set ". - "(obj_id,sort_mode, sort_direction, new_items_position, new_items_order) ". - "VALUES ( ". - $this->db->quote($this->obj_id ,'integer').", ". - $this->db->quote($this->sort_mode ,'integer').", ". - $this->db->quote($this->sort_direction,'integer').', '. - $this->db->quote($this->new_items_position,'integer').', '. - $this->db->quote($this->new_items_order,'integer').' '. - ")"; - $res = $ilDB->manipulate($query); - } - - /** - * Delete setting - * @return - */ - public function delete() - { - $ilDB = $this->db; - - $query = 'DELETE FROM container_sorting_set WHERE obj_id = '.$ilDB->quote($this->obj_id,'integer'); - $ilDB->query($query); - } - - /** - * read settings - * - * @access private - * @param - * - */ - protected function read() - { - if(!$this->obj_id) - { - return TRUE; - } - - $query = "SELECT * FROM container_sorting_set ". - "WHERE obj_id = ".$this->db->quote($this->obj_id ,'integer')." "; - - $res = $this->db->query($query); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - $this->sort_mode = $row->sort_mode; - $this->sort_direction = $row->sort_direction; - $this->new_items_position = $row->new_items_position; - $this->new_items_order = $row->new_items_order; - return TRUE; - } - } - - /** - * get String representation of sort mode - * @param int $a_sort_mode - * @return - */ - public static function sortModeToString($a_sort_mode) - { - global $DIC; - - $lng = $DIC->language(); - - $lng->loadLanguageModule('crs'); - switch($a_sort_mode) - { - case ilContainer::SORT_ACTIVATION: - return $lng->txt('crs_sort_activation'); - - case ilContainer::SORT_MANUAL: - return $lng->txt('crs_sort_manual'); - - case ilContainer::SORT_TITLE: - return $lng->txt('crs_sort_title'); - - case ilContainer::SORT_CREATION: - return $lng->txt('sorting_creation_header'); - } - return ''; - } - - /** - * sorting XML-export for all container objects - * - * @param ilXmlWriter $xml - * @param $obj_id - */ - public static function _exportContainerSortingSettings(ilXmlWriter $xml, $obj_id) - { - $settings = self::getInstanceByObjId($obj_id); - - $attr = array(); - switch($settings->getSortMode()) - { - case ilContainer::SORT_MANUAL: - switch($settings->getSortNewItemsOrder()) - { - case ilContainer::SORT_NEW_ITEMS_ORDER_ACTIVATION: - $order = 'Activation'; - break; - case ilContainer::SORT_NEW_ITEMS_ORDER_CREATION: - $order = 'Creation'; - break; - case ilContainer::SORT_NEW_ITEMS_ORDER_TITLE: - $order = 'Title'; - break; - } - - $attr = array( - 'direction' => $settings->getSortDirection() == ilContainer::SORT_DIRECTION_ASC ? "ASC" : "DESC", - 'position' => $settings->getSortNewItemsPosition() == ilContainer::SORT_NEW_ITEMS_POSITION_BOTTOM ? "Bottom" : "Top", - 'order' => $order, - 'type' => 'Manual' - ); - - break; - - case ilContainer::SORT_CREATION: - $attr = array( - 'direction' => $settings->getSortDirection() == ilContainer::SORT_DIRECTION_ASC ? "ASC" : "DESC", - 'type' => 'Creation' - ); - break; - - case ilContainer::SORT_TITLE: - $attr = array( - 'direction' => $settings->getSortDirection() == ilContainer::SORT_DIRECTION_ASC ? "ASC" : "DESC", - 'type' => 'Title' - ); - break; - case ilContainer::SORT_ACTIVATION: - $attr = array( - 'direction' => $settings->getSortDirection() == ilContainer::SORT_DIRECTION_ASC ? "ASC" : "DESC", - 'type' => 'Activation' - ); - break; - case ilContainer::SORT_INHERIT: - $attr = array( - 'type' => 'Inherit' - ); - } - $xml->xmlElement('Sort', $attr); - } - - /** - * sorting import for all container objects - * - * @param $attibs array (type, direction, position, order) - * @param $obj_id - */ - public static function _importContainerSortingSettings($attibs, $obj_id) - { - $settings = self::getInstanceByObjId($obj_id); - - switch($attibs['type']) - { - case 'Manual': - $settings->setSortMode(ilContainer::SORT_MANUAL); - break; - case 'Creation': - $settings->setSortMode(ilContainer::SORT_CREATION); - break; - case 'Title': - $settings->setSortMode(ilContainer::SORT_TITLE); - break; - case 'Activation': - $settings->setSortMode(ilContainer::SORT_ACTIVATION); - break; - } - - switch($attibs['direction']) - { - case 'ASC': - $settings->setSortDirection(ilContainer::SORT_DIRECTION_ASC); - break; - case 'DESC': - $settings->setSortDirection(ilContainer::SORT_DIRECTION_DESC); - break; - } - - switch($attibs['position']) - { - case "Top": - $settings->setSortNewItemsPosition(ilContainer::SORT_NEW_ITEMS_POSITION_TOP); - break; - case "Bottom": - $settings->setSortNewItemsPosition(ilContainer::SORT_NEW_ITEMS_POSITION_BOTTOM); - break; - } - - switch($attibs['order']) - { - case 'Creation': - $settings->setSortNewItemsOrder(ilContainer::SORT_NEW_ITEMS_ORDER_CREATION); - break; - case 'Title': - $settings->setSortNewItemsOrder(ilContainer::SORT_NEW_ITEMS_ORDER_TITLE); - break; - case 'Activation': - $settings->setSortNewItemsOrder(ilContainer::SORT_NEW_ITEMS_ORDER_ACTIVATION); - } - - $settings->update(); - } + /** + * @var ilTree + */ + protected $tree; + + private static $instances = array(); + + protected $obj_id; + protected $sort_mode = ilContainer::SORT_TITLE; + protected $sort_direction = ilContainer::SORT_DIRECTION_ASC; + protected $new_items_position = ilContainer::SORT_NEW_ITEMS_POSITION_BOTTOM; + protected $new_items_order = ilContainer::SORT_NEW_ITEMS_ORDER_TITLE; + + protected $db; + + /** + * Constructor + * + * @access public + * @param + * + */ + public function __construct($a_obj_id = 0) + { + global $DIC; + + $this->tree = $DIC->repositoryTree(); + $ilDB = $DIC->database(); + + $this->obj_id = $a_obj_id; + $this->db = $ilDB; + + $this->read(); + } + + /** + * Get singleton instance + * @param type $a_obj_id + * @return ilContainerSortingSettings + */ + public static function getInstanceByObjId($a_obj_id) + { + if (self::$instances[$a_obj_id]) { + return self::$instances[$a_obj_id]; + } + return self::$instances[$a_obj_id] = new self($a_obj_id); + } + + /** + * Load inherited settings + * @return ilContainerSortingSettings + */ + public function loadEffectiveSettings() + { + if ($this->getSortMode() != ilContainer::SORT_INHERIT) { + return $this; + } + + $effective_settings = $this->getInheritedSettings($this->obj_id); + $inherited = clone $this; + + if ($effective_settings->getSortMode() == ilContainer::SORT_INHERIT) { + $inherited->setSortMode(ilContainer::SORT_TITLE); + } else { + $inherited->setSortMode($effective_settings->getSortMode()); + $inherited->setSortNewItemsOrder($effective_settings->getSortNewItemsOrder()); + $inherited->setSortNewItemsPosition($effective_settings->getSortNewItemsPosition()); + } + return $inherited; + } + + + /** + * Read inherited settings of course/group + * @param int $a_container_obj_id + */ + public function getInheritedSettings($a_container_obj_id) + { + $tree = $this->tree; + + if (!$a_container_obj_id) { + $a_container_obj_id = $this->obj_id; + } + + $ref_ids = ilObject::_getAllReferences($a_container_obj_id); + $ref_id = current($ref_ids); + + if ($cont_ref_id = $tree->checkForParentType($ref_id, 'grp', true)) { + $parent_obj_id = ilObject::_lookupObjId($cont_ref_id); + $parent_settings = self::getInstanceByObjId($parent_obj_id); + + if ($parent_settings->getSortMode() == ilContainer::SORT_INHERIT) { + return $this->getInheritedSettings($parent_obj_id); + } + return $parent_settings; + } + + if ($cont_ref_id = $tree->checkForParentType($ref_id, 'crs', true)) { + $parent_obj_id = ilObject::_lookupObjId($cont_ref_id); + $parent_settings = self::getInstanceByObjId($parent_obj_id); + return $parent_settings; + } + // no parent settings found => return current settings + return $this; + } + + + public static function _readSortMode($a_obj_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT * FROM container_sorting_set " . + "WHERE obj_id = " . $ilDB->quote($a_obj_id, 'integer') . " "; + $res = $ilDB->query($query); + + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + return $row->sort_mode; + } + return ilContainer::SORT_INHERIT; + } + + + /** + * lookup sort mode + * + * @access public + * @static + * + * @param int obj_id + */ + public static function _lookupSortMode($a_obj_id) + { + global $DIC; + + $tree = $DIC->repositoryTree(); + $ilDB = $DIC->database(); + $objDefinition = $DIC["objDefinition"]; + + // Try to read from table + $query = "SELECT * FROM container_sorting_set " . + "WHERE obj_id = " . $ilDB->quote($a_obj_id, 'integer') . " "; + $res = $ilDB->query($query); + + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + if ($row->sort_mode != ilContainer::SORT_INHERIT) { + return $row->sort_mode; + } + } + return self::lookupSortModeFromParentContainer($a_obj_id); + } + + /** + * Lookup sort mode from parent container + * @param object $a_obj_id + * @return + */ + public static function lookupSortModeFromParentContainer($a_obj_id) + { + $settings = self::getInstanceByObjId($a_obj_id); + $inherited_settings = $settings->getInheritedSettings($a_obj_id); + return $inherited_settings->getSortMode(); + } + + /** + * Clone settings + * + * @access public + * @static + * + * @param int orig obj_id + * @þaram int new obj_id + */ + public static function _cloneSettings($a_old_id, $a_new_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT sort_mode,sort_direction,new_items_position,new_items_order " . + "FROM container_sorting_set " . + "WHERE obj_id = " . $ilDB->quote($a_old_id, 'integer') . " "; + $res = $ilDB->query($query); + while ($row = $ilDB->fetchAssoc($res)) { + $query = "DELETE FROM container_sorting_set " . + "WHERE obj_id = " . $ilDB->quote($a_new_id) . " "; + $ilDB->manipulate($query); + + $query = "INSERT INTO container_sorting_set " . + "(obj_id,sort_mode, sort_direction, new_items_position, new_items_order) " . + "VALUES( " . + $ilDB->quote($a_new_id, 'integer') . ", " . + $ilDB->quote($row["sort_mode"], 'integer') . ", " . + $ilDB->quote($row["sort_direction"], 'integer') . ', ' . + $ilDB->quote($row["new_items_position"], 'integer') . ', ' . + $ilDB->quote($row["new_items_order"], 'integer') . ' ' . + ")"; + $ilDB->manipulate($query); + } + return true; + } + + /** + * get sort mode + * + * @access public + * + */ + public function getSortMode() + { + return $this->sort_mode ? $this->sort_mode : 0; + } + + /** + * Get sort direction + * @return type + */ + public function getSortDirection() + { + return $this->sort_direction ? $this->sort_direction : ilContainer::SORT_DIRECTION_ASC; + } + + /** + * GET new item position + * @return int position + */ + public function getSortNewItemsPosition() + { + return $this->new_items_position; + } + + /** + * GET new item order + * @return int position + */ + public function getSortNewItemsOrder() + { + return $this->new_items_order; + } + + /** + * set sort mode + * + * @access public + * @param int MODE_TITLE | MODE_MANUAL | MODE_ACTIVATION + * + */ + public function setSortMode($a_mode) + { + $this->sort_mode = (int) $a_mode; + } + + /** + * Set sort direction + * @param type $a_direction + */ + public function setSortDirection($a_direction) + { + $this->sort_direction = (int) $a_direction; + } + + /** + * SET new item position + * @param int $a_position + */ + public function setSortNewItemsPosition($a_position) + { + $this->new_items_position = (int) $a_position; + } + + /** + * SET new item order + * @param int $a_order + */ + public function setSortNewItemsOrder($a_order) + { + $this->new_items_order = (int) $a_order; + } + + /** + * Update + * + * @access public + * + */ + public function update() + { + $ilDB = $this->db; + + $query = "DELETE FROM container_sorting_set " . + "WHERE obj_id = " . $ilDB->quote($this->obj_id, 'integer'); + $res = $ilDB->manipulate($query); + + $this->save(); + } + + /** + * save settings + * + * @access public + * + */ + public function save() + { + $ilDB = $this->db; + + $query = "INSERT INTO container_sorting_set " . + "(obj_id,sort_mode, sort_direction, new_items_position, new_items_order) " . + "VALUES ( " . + $this->db->quote($this->obj_id, 'integer') . ", " . + $this->db->quote($this->sort_mode, 'integer') . ", " . + $this->db->quote($this->sort_direction, 'integer') . ', ' . + $this->db->quote($this->new_items_position, 'integer') . ', ' . + $this->db->quote($this->new_items_order, 'integer') . ' ' . + ")"; + $res = $ilDB->manipulate($query); + } + + /** + * Delete setting + * @return + */ + public function delete() + { + $ilDB = $this->db; + + $query = 'DELETE FROM container_sorting_set WHERE obj_id = ' . $ilDB->quote($this->obj_id, 'integer'); + $ilDB->query($query); + } + + /** + * read settings + * + * @access private + * @param + * + */ + protected function read() + { + if (!$this->obj_id) { + return true; + } + + $query = "SELECT * FROM container_sorting_set " . + "WHERE obj_id = " . $this->db->quote($this->obj_id, 'integer') . " "; + + $res = $this->db->query($query); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + $this->sort_mode = $row->sort_mode; + $this->sort_direction = $row->sort_direction; + $this->new_items_position = $row->new_items_position; + $this->new_items_order = $row->new_items_order; + return true; + } + } + + /** + * get String representation of sort mode + * @param int $a_sort_mode + * @return + */ + public static function sortModeToString($a_sort_mode) + { + global $DIC; + + $lng = $DIC->language(); + + $lng->loadLanguageModule('crs'); + switch ($a_sort_mode) { + case ilContainer::SORT_ACTIVATION: + return $lng->txt('crs_sort_activation'); + + case ilContainer::SORT_MANUAL: + return $lng->txt('crs_sort_manual'); + + case ilContainer::SORT_TITLE: + return $lng->txt('crs_sort_title'); + + case ilContainer::SORT_CREATION: + return $lng->txt('sorting_creation_header'); + } + return ''; + } + + /** + * sorting XML-export for all container objects + * + * @param ilXmlWriter $xml + * @param $obj_id + */ + public static function _exportContainerSortingSettings(ilXmlWriter $xml, $obj_id) + { + $settings = self::getInstanceByObjId($obj_id); + + $attr = array(); + switch ($settings->getSortMode()) { + case ilContainer::SORT_MANUAL: + switch ($settings->getSortNewItemsOrder()) { + case ilContainer::SORT_NEW_ITEMS_ORDER_ACTIVATION: + $order = 'Activation'; + break; + case ilContainer::SORT_NEW_ITEMS_ORDER_CREATION: + $order = 'Creation'; + break; + case ilContainer::SORT_NEW_ITEMS_ORDER_TITLE: + $order = 'Title'; + break; + } + + $attr = array( + 'direction' => $settings->getSortDirection() == ilContainer::SORT_DIRECTION_ASC ? "ASC" : "DESC", + 'position' => $settings->getSortNewItemsPosition() == ilContainer::SORT_NEW_ITEMS_POSITION_BOTTOM ? "Bottom" : "Top", + 'order' => $order, + 'type' => 'Manual' + ); + + break; + + case ilContainer::SORT_CREATION: + $attr = array( + 'direction' => $settings->getSortDirection() == ilContainer::SORT_DIRECTION_ASC ? "ASC" : "DESC", + 'type' => 'Creation' + ); + break; + + case ilContainer::SORT_TITLE: + $attr = array( + 'direction' => $settings->getSortDirection() == ilContainer::SORT_DIRECTION_ASC ? "ASC" : "DESC", + 'type' => 'Title' + ); + break; + case ilContainer::SORT_ACTIVATION: + $attr = array( + 'direction' => $settings->getSortDirection() == ilContainer::SORT_DIRECTION_ASC ? "ASC" : "DESC", + 'type' => 'Activation' + ); + break; + case ilContainer::SORT_INHERIT: + $attr = array( + 'type' => 'Inherit' + ); + } + $xml->xmlElement('Sort', $attr); + } + + /** + * sorting import for all container objects + * + * @param $attibs array (type, direction, position, order) + * @param $obj_id + */ + public static function _importContainerSortingSettings($attibs, $obj_id) + { + $settings = self::getInstanceByObjId($obj_id); + + switch ($attibs['type']) { + case 'Manual': + $settings->setSortMode(ilContainer::SORT_MANUAL); + break; + case 'Creation': + $settings->setSortMode(ilContainer::SORT_CREATION); + break; + case 'Title': + $settings->setSortMode(ilContainer::SORT_TITLE); + break; + case 'Activation': + $settings->setSortMode(ilContainer::SORT_ACTIVATION); + break; + } + + switch ($attibs['direction']) { + case 'ASC': + $settings->setSortDirection(ilContainer::SORT_DIRECTION_ASC); + break; + case 'DESC': + $settings->setSortDirection(ilContainer::SORT_DIRECTION_DESC); + break; + } + + switch ($attibs['position']) { + case "Top": + $settings->setSortNewItemsPosition(ilContainer::SORT_NEW_ITEMS_POSITION_TOP); + break; + case "Bottom": + $settings->setSortNewItemsPosition(ilContainer::SORT_NEW_ITEMS_POSITION_BOTTOM); + break; + } + + switch ($attibs['order']) { + case 'Creation': + $settings->setSortNewItemsOrder(ilContainer::SORT_NEW_ITEMS_ORDER_CREATION); + break; + case 'Title': + $settings->setSortNewItemsOrder(ilContainer::SORT_NEW_ITEMS_ORDER_TITLE); + break; + case 'Activation': + $settings->setSortNewItemsOrder(ilContainer::SORT_NEW_ITEMS_ORDER_ACTIVATION); + } + + $settings->update(); + } } -?> \ No newline at end of file diff --git a/Services/Container/classes/class.ilContainerStartObjects.php b/Services/Container/classes/class.ilContainerStartObjects.php index b8f1688d6d54b283cf9fc6e25000e9410b34a54d..44d555b73fb39dfb52e79f2108717aeb97e3b52e 100644 --- a/Services/Container/classes/class.ilContainerStartObjects.php +++ b/Services/Container/classes/class.ilContainerStartObjects.php @@ -1,336 +1,313 @@ - - * @version $Id: class.ilCourseStart.php 44362 2013-08-22 08:36:03Z jluetzen $ - * - * @ingroup ServicesContainer - */ -class ilContainerStartObjects -{ - /** - * @var ilTree - */ - protected $tree; - - /** - * @var ilDB - */ - protected $db; - - /** - * @var ilObjectDataCache - */ - protected $obj_data_cache; - - /** - * @var Logger - */ - protected $log; - - protected $ref_id; - protected $obj_id; - protected $start_objs = array(); - - public function __construct($a_object_ref_id, $a_object_id) - { - global $DIC; - - $this->tree = $DIC->repositoryTree(); - $this->db = $DIC->database(); - $this->obj_data_cache = $DIC["ilObjDataCache"]; - $this->log = $DIC["ilLog"]; - $this->setRefId($a_object_ref_id); - $this->setObjId($a_object_id); - - $this->__read(); - } - - protected function setObjId($a_id) - { - $this->obj_id = $a_id; - } - - public function getObjId() - { - return $this->obj_id; - } - - protected function setRefId($a_ref_id) - { - $this->ref_id = $a_ref_id; - } - - public function getRefId() - { - return $this->ref_id; - } - - public function getStartObjects() - { - return $this->start_objs ? $this->start_objs : array(); - } - - protected function __read() - { - $tree = $this->tree; - $ilDB = $this->db; - - $this->start_objs = array(); - - $query = "SELECT * FROM crs_start". - " WHERE crs_id = ".$ilDB->quote($this->getObjId(), 'integer'). - " ORDER BY pos, crs_start_id"; - $res = $ilDB->query($query); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - if($tree->isInTree($row->item_ref_id)) - { - $this->start_objs[$row->crs_start_id]['item_ref_id'] = $row->item_ref_id; - } - else - { - $this->delete($row->item_ref_id); - } - } - return true; - } - - /** - * Delete item by sequence id - * @param type $a_crs_start_id - * @return boolean - */ - public function delete($a_crs_start_id) - { - $ilDB = $this->db; - - $query = "DELETE FROM crs_start". - " WHERE crs_start_id = ".$ilDB->quote($a_crs_start_id, 'integer'). - " AND crs_id = ".$ilDB->quote($this->getObjId(), 'integer'); - $ilDB->manipulate($query); - return true; - } - - /** - * Delete item by ref_id - * @param type $a_item_ref_id - */ - public function deleteItem($a_item_ref_id) - { - $ilDB = $this->db; - - $query = "DELETE FROM crs_start". - " WHERE crs_id = ".$ilDB->quote($this->getObjId(), 'integer'). - " AND item_ref_id = ".$ilDB->quote($a_item_ref_id, 'integer'); - $ilDB->manipulate($query); - return true; - } - - public function exists($a_item_ref_id) - { - $ilDB = $this->db; - - $query = "SELECT * FROM crs_start". - " WHERE crs_id = ".$ilDB->quote($this->getObjId(), 'integer'). - " AND item_ref_id = ".$ilDB->quote($a_item_ref_id, 'integer'); - $res = $ilDB->query($query); - - return $res->numRows() ? true : false; - } - - public function add($a_item_ref_id) - { - $ilDB = $this->db; - - if($a_item_ref_id) - { - $max_pos = $ilDB->query("SELECT max(pos) pos FROM crs_start". - " WHERE crs_id = ".$ilDB->quote($this->getObjId(), "integer")); - $max_pos = $ilDB->fetchAssoc($max_pos); - $max_pos = ((int)$max_pos["pos"])+10; - - $next_id = $ilDB->nextId('crs_start'); - $query = "INSERT INTO crs_start". - " (crs_start_id,crs_id,item_ref_id,pos)". - " VALUES". - " (".$ilDB->quote($next_id, 'integer'). - ", ".$ilDB->quote($this->getObjId(), 'integer'). - ", ".$ilDB->quote($a_item_ref_id, 'integer'). - ", ".$ilDB->quote($max_pos, 'integer'). - ")"; - $ilDB->manipulate($query); - return true; - } - return false; - } - - public function __deleteAll() - { - $ilDB = $this->db; - - $query = "DELETE FROM crs_start". - " WHERE crs_id = ".$ilDB->quote($this->getObjId(), 'integer'); - $ilDB->manipulate($query); - return true; - } - - public function setObjectPos($a_start_id, $a_pos) - { - $ilDB = $this->db; - - if(!(int)$a_start_id || !(int)$a_pos) - { - return; - } - - $ilDB->manipulate("UPDATE crs_start". - " SET pos = ".$ilDB->quote($a_pos, "integer"). - " WHERE crs_id = ".$ilDB->quote($this->getObjId(), 'integer'). - " AND crs_start_id = ".$ilDB->quote($a_start_id, 'integer')); - } - - public function getPossibleStarters() - { - include_once "Services/Object/classes/class.ilObjectActivation.php"; - foreach(ilObjectActivation::getItems($this->getRefId(), false) as $node) - { - switch($node['type']) - { - case 'lm': - case 'sahs': - case 'copa': - case 'svy': - case 'tst': - $poss_items[] = $node['ref_id']; - break; - } - } - return $poss_items ? $poss_items : array(); - } - - public function allFullfilled($a_user_id) - { - foreach($this->getStartObjects() as $item) - { - if(!$this->isFullfilled($a_user_id, $item['item_ref_id'])) - { - return false; - } - } - return true; - } - - public function isFullfilled($a_user_id, $a_item_id) - { - $ilObjDataCache = $this->obj_data_cache; - - $obj_id = $ilObjDataCache->lookupObjId($a_item_id); - $type = $ilObjDataCache->lookupType($obj_id); - - switch($type) - { - case 'tst': - include_once './Modules/Test/classes/class.ilObjTestAccess.php'; - if(!ilObjTestAccess::checkCondition($obj_id,'finished','',$a_user_id)) // #14000 - { - return false; - } - break; - - case 'svy': - - include_once './Modules/Survey/classes/class.ilObjSurveyAccess.php'; - if(!ilObjSurveyAccess::_lookupFinished($obj_id, $a_user_id)) - { - return false; - } - break; - - case 'sahs': - include_once 'Services/Tracking/classes/class.ilLPStatus.php'; - if(!ilLPStatus::_hasUserCompleted($obj_id, $a_user_id)) - { - return false; - } - break; - - case 'copa': - if (!ilLPStatus::_hasUserCompleted($obj_id, $a_user_id)) { - return false; - } - break; - - default: - include_once './Modules/Course/classes/class.ilCourseLMHistory.php'; - $lm_continue = new ilCourseLMHistory($this->getRefId(), $a_user_id); - $continue_data = $lm_continue->getLMHistory(); - if(!isset($continue_data[$a_item_id])) - { - return false; - } - break; - } - - return true; - } - - public function cloneDependencies($a_target_id, $a_copy_id) - { - $ilObjDataCache = $this->obj_data_cache; - $ilLog = $this->log; - - $ilLog->write(__METHOD__.': Begin course start objects...'); - - $new_obj_id = $ilObjDataCache->lookupObjId($a_target_id); - $start = new self($a_target_id, $new_obj_id); - - include_once('Services/CopyWizard/classes/class.ilCopyWizardOptions.php'); - $cwo = ilCopyWizardOptions::_getInstance($a_copy_id); - $mappings = $cwo->getMappings(); - foreach($this->getStartObjects() as $data) - { - $item_ref_id = $data['item_ref_id']; - if(isset($mappings[$item_ref_id]) and $mappings[$item_ref_id]) - { - $ilLog->write(__METHOD__.': Clone start object nr. '.$item_ref_id); - $start->add($mappings[$item_ref_id]); - } - else - { - $ilLog->write(__METHOD__.': No mapping found for start object nr. '.$item_ref_id); - } - } - $ilLog->write(__METHOD__.': ... end course start objects'); - return true; - } - - /** - * Check if object is start object - * @param type $a_container_id - * @param type $a_item_ref_id - * @return boolean - */ - public static function isStartObject($a_container_id, $a_item_ref_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = 'SELECT crs_start_id FROM crs_start '. - 'WHERE crs_id = '.$ilDB->quote($a_container_id,'integer').' '. - 'AND item_ref_id = '.$ilDB->quote($a_item_ref_id,'integer'); - $res = $ilDB->query($query); - if($res->numRows() >= 1) - { - return true; - } - return false; - } - -} - -?> \ No newline at end of file + + * @version $Id: class.ilCourseStart.php 44362 2013-08-22 08:36:03Z jluetzen $ + * + * @ingroup ServicesContainer + */ +class ilContainerStartObjects +{ + /** + * @var ilTree + */ + protected $tree; + + /** + * @var ilDB + */ + protected $db; + + /** + * @var ilObjectDataCache + */ + protected $obj_data_cache; + + /** + * @var Logger + */ + protected $log; + + protected $ref_id; + protected $obj_id; + protected $start_objs = array(); + + public function __construct($a_object_ref_id, $a_object_id) + { + global $DIC; + + $this->tree = $DIC->repositoryTree(); + $this->db = $DIC->database(); + $this->obj_data_cache = $DIC["ilObjDataCache"]; + $this->log = $DIC["ilLog"]; + $this->setRefId($a_object_ref_id); + $this->setObjId($a_object_id); + + $this->__read(); + } + + protected function setObjId($a_id) + { + $this->obj_id = $a_id; + } + + public function getObjId() + { + return $this->obj_id; + } + + protected function setRefId($a_ref_id) + { + $this->ref_id = $a_ref_id; + } + + public function getRefId() + { + return $this->ref_id; + } + + public function getStartObjects() + { + return $this->start_objs ? $this->start_objs : array(); + } + + protected function __read() + { + $tree = $this->tree; + $ilDB = $this->db; + + $this->start_objs = array(); + + $query = "SELECT * FROM crs_start" . + " WHERE crs_id = " . $ilDB->quote($this->getObjId(), 'integer') . + " ORDER BY pos, crs_start_id"; + $res = $ilDB->query($query); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + if ($tree->isInTree($row->item_ref_id)) { + $this->start_objs[$row->crs_start_id]['item_ref_id'] = $row->item_ref_id; + } else { + $this->delete($row->item_ref_id); + } + } + return true; + } + + /** + * Delete item by sequence id + * @param type $a_crs_start_id + * @return boolean + */ + public function delete($a_crs_start_id) + { + $ilDB = $this->db; + + $query = "DELETE FROM crs_start" . + " WHERE crs_start_id = " . $ilDB->quote($a_crs_start_id, 'integer') . + " AND crs_id = " . $ilDB->quote($this->getObjId(), 'integer'); + $ilDB->manipulate($query); + return true; + } + + /** + * Delete item by ref_id + * @param type $a_item_ref_id + */ + public function deleteItem($a_item_ref_id) + { + $ilDB = $this->db; + + $query = "DELETE FROM crs_start" . + " WHERE crs_id = " . $ilDB->quote($this->getObjId(), 'integer') . + " AND item_ref_id = " . $ilDB->quote($a_item_ref_id, 'integer'); + $ilDB->manipulate($query); + return true; + } + + public function exists($a_item_ref_id) + { + $ilDB = $this->db; + + $query = "SELECT * FROM crs_start" . + " WHERE crs_id = " . $ilDB->quote($this->getObjId(), 'integer') . + " AND item_ref_id = " . $ilDB->quote($a_item_ref_id, 'integer'); + $res = $ilDB->query($query); + + return $res->numRows() ? true : false; + } + + public function add($a_item_ref_id) + { + $ilDB = $this->db; + + if ($a_item_ref_id) { + $max_pos = $ilDB->query("SELECT max(pos) pos FROM crs_start" . + " WHERE crs_id = " . $ilDB->quote($this->getObjId(), "integer")); + $max_pos = $ilDB->fetchAssoc($max_pos); + $max_pos = ((int) $max_pos["pos"])+10; + + $next_id = $ilDB->nextId('crs_start'); + $query = "INSERT INTO crs_start" . + " (crs_start_id,crs_id,item_ref_id,pos)" . + " VALUES" . + " (" . $ilDB->quote($next_id, 'integer') . + ", " . $ilDB->quote($this->getObjId(), 'integer') . + ", " . $ilDB->quote($a_item_ref_id, 'integer') . + ", " . $ilDB->quote($max_pos, 'integer') . + ")"; + $ilDB->manipulate($query); + return true; + } + return false; + } + + public function __deleteAll() + { + $ilDB = $this->db; + + $query = "DELETE FROM crs_start" . + " WHERE crs_id = " . $ilDB->quote($this->getObjId(), 'integer'); + $ilDB->manipulate($query); + return true; + } + + public function setObjectPos($a_start_id, $a_pos) + { + $ilDB = $this->db; + + if (!(int) $a_start_id || !(int) $a_pos) { + return; + } + + $ilDB->manipulate("UPDATE crs_start" . + " SET pos = " . $ilDB->quote($a_pos, "integer") . + " WHERE crs_id = " . $ilDB->quote($this->getObjId(), 'integer') . + " AND crs_start_id = " . $ilDB->quote($a_start_id, 'integer')); + } + + public function getPossibleStarters() + { + include_once "Services/Object/classes/class.ilObjectActivation.php"; + foreach (ilObjectActivation::getItems($this->getRefId(), false) as $node) { + switch ($node['type']) { + case 'lm': + case 'sahs': + case 'copa': + case 'svy': + case 'tst': + $poss_items[] = $node['ref_id']; + break; + } + } + return $poss_items ? $poss_items : array(); + } + + public function allFullfilled($a_user_id) + { + foreach ($this->getStartObjects() as $item) { + if (!$this->isFullfilled($a_user_id, $item['item_ref_id'])) { + return false; + } + } + return true; + } + + public function isFullfilled($a_user_id, $a_item_id) + { + $ilObjDataCache = $this->obj_data_cache; + + $obj_id = $ilObjDataCache->lookupObjId($a_item_id); + $type = $ilObjDataCache->lookupType($obj_id); + + switch ($type) { + case 'tst': + include_once './Modules/Test/classes/class.ilObjTestAccess.php'; + if (!ilObjTestAccess::checkCondition($obj_id, 'finished', '', $a_user_id)) { // #14000 + return false; + } + break; + + case 'svy': + + include_once './Modules/Survey/classes/class.ilObjSurveyAccess.php'; + if (!ilObjSurveyAccess::_lookupFinished($obj_id, $a_user_id)) { + return false; + } + break; + + case 'sahs': + include_once 'Services/Tracking/classes/class.ilLPStatus.php'; + if (!ilLPStatus::_hasUserCompleted($obj_id, $a_user_id)) { + return false; + } + break; + + case 'copa': + if (!ilLPStatus::_hasUserCompleted($obj_id, $a_user_id)) { + return false; + } + break; + + default: + include_once './Modules/Course/classes/class.ilCourseLMHistory.php'; + $lm_continue = new ilCourseLMHistory($this->getRefId(), $a_user_id); + $continue_data = $lm_continue->getLMHistory(); + if (!isset($continue_data[$a_item_id])) { + return false; + } + break; + } + + return true; + } + + public function cloneDependencies($a_target_id, $a_copy_id) + { + $ilObjDataCache = $this->obj_data_cache; + $ilLog = $this->log; + + $ilLog->write(__METHOD__ . ': Begin course start objects...'); + + $new_obj_id = $ilObjDataCache->lookupObjId($a_target_id); + $start = new self($a_target_id, $new_obj_id); + + include_once('Services/CopyWizard/classes/class.ilCopyWizardOptions.php'); + $cwo = ilCopyWizardOptions::_getInstance($a_copy_id); + $mappings = $cwo->getMappings(); + foreach ($this->getStartObjects() as $data) { + $item_ref_id = $data['item_ref_id']; + if (isset($mappings[$item_ref_id]) and $mappings[$item_ref_id]) { + $ilLog->write(__METHOD__ . ': Clone start object nr. ' . $item_ref_id); + $start->add($mappings[$item_ref_id]); + } else { + $ilLog->write(__METHOD__ . ': No mapping found for start object nr. ' . $item_ref_id); + } + } + $ilLog->write(__METHOD__ . ': ... end course start objects'); + return true; + } + + /** + * Check if object is start object + * @param type $a_container_id + * @param type $a_item_ref_id + * @return boolean + */ + public static function isStartObject($a_container_id, $a_item_ref_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = 'SELECT crs_start_id FROM crs_start ' . + 'WHERE crs_id = ' . $ilDB->quote($a_container_id, 'integer') . ' ' . + 'AND item_ref_id = ' . $ilDB->quote($a_item_ref_id, 'integer'); + $res = $ilDB->query($query); + if ($res->numRows() >= 1) { + return true; + } + return false; + } +} diff --git a/Services/Container/classes/class.ilContainerStartObjectsContentGUI.php b/Services/Container/classes/class.ilContainerStartObjectsContentGUI.php index 57d92da20c4457c1ca379ca78af2be3288a5489b..96df9e21ec701df20d567961dbe322188eb0e70a 100644 --- a/Services/Container/classes/class.ilContainerStartObjectsContentGUI.php +++ b/Services/Container/classes/class.ilContainerStartObjectsContentGUI.php @@ -1,149 +1,154 @@ - - * $Id: class.ilObjCourseGUI.php 47058 2014-01-08 08:07:12Z mjansen $ - * - * @ingroup ServicesContainer - */ -class ilContainerStartObjectsContentGUI -{ - /** - * @var ilTemplate - */ - protected $tpl; + + * $Id: class.ilObjCourseGUI.php 47058 2014-01-08 08:07:12Z mjansen $ + * + * @ingroup ServicesContainer + */ +class ilContainerStartObjectsContentGUI +{ + /** + * @var ilTemplate + */ + protected $tpl; - /** - * @var ilSetting - */ - protected $settings; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilSetting + */ + protected $settings; - protected $start_object; // [ilContainerStartObjects] - protected $enable_desktop; // [bool] - protected $parent_gui; // [ilContainerGUI] - protected $parent_obj; - - /** - * Constructor - * - * @param ilContainer $a_parent_obj - */ - public function __construct($a_gui, ilContainer $a_parent_obj) - { - global $DIC; + /** + * @var ilObjUser + */ + protected $user; - $this->tpl = $DIC["tpl"]; - $this->lng = $DIC->language(); - $this->settings = $DIC->settings(); - $this->user = $DIC->user(); - include_once "Services/Container/classes/class.ilContainerStartObjects.php"; - $this->parent_gui = $a_gui; - $this->parent_obj = $a_parent_obj; - $this->start_object = new ilContainerStartObjects($a_parent_obj->getRefId(), - $a_parent_obj->getId()); - } - - /** - * Toggle add-to/remove-from-desktop - * - * @param bool $a_value - * @param ilContainerGUI $a_parent_gui - */ - public function enableDesktop($a_value, ilContainerGUI $a_parent_gui) - { - $this->enable_desktop = (bool)$a_value; - - if($this->enable_desktop) - { - $this->parent_gui = $a_parent_gui; - } - } - - /** - * Get container start objects list (presentation) - * - * @return string - */ - public function getHTML() - { - $tpl = $this->tpl; - $lng = $this->lng; - - $lng->loadLanguageModule("crs"); - - include_once "Services/Container/classes/class.ilContainerStartObjectsContentTableGUI.php"; - $tbl = new ilContainerStartObjectsContentTableGUI( - $this->parent_gui, - "", - $this->start_object, - $this->enable_desktop - ); - $tpl->setContent( - $this->getPageHTML(). - $tbl->getHTML() - ); - } - - /** - * Render COPage - * - * @see ilContainerGUI - * @return string - */ - protected function getPageHTML() - { - $tpl = $this->tpl; - $ilSetting = $this->settings; - $ilUser = $this->user; - - if (!$ilSetting->get("enable_cat_page_edit")) - { - return; - } - - $page_id = $this->start_object->getObjId(); - - // if page does not exist, return nothing - include_once("./Services/COPage/classes/class.ilPageUtil.php"); - if (!ilPageUtil::_existsAndNotEmpty("cstr", $page_id)) - { - return; - } - - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath(ilObjStyleSheet::getEffectiveContentStyleId( - $this->parent_obj->getStyleSheetId(), $this->parent_obj->getType()))); - $tpl->setCurrentBlock("SyntaxStyle"); - $tpl->setVariable("LOCATION_SYNTAX_STYLESHEET", - ilObjStyleSheet::getSyntaxStylePath()); - $tpl->parseCurrentBlock(); - - include_once("./Services/Container/classes/class.ilContainerStartObjectsPageGUI.php"); - $page_gui = new ilContainerStartObjectsPageGUI($page_id); - - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $page_gui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId( - $this->parent_obj->getStyleSheetId(), $this->parent_obj->getType())); - - $page_gui->setPresentationTitle(""); - $page_gui->setTemplateOutput(false); - $page_gui->setHeader(""); - return $page_gui->showPage(); - } -} - -?> \ No newline at end of file + protected $start_object; // [ilContainerStartObjects] + protected $enable_desktop; // [bool] + protected $parent_gui; // [ilContainerGUI] + protected $parent_obj; + + /** + * Constructor + * + * @param ilContainer $a_parent_obj + */ + public function __construct($a_gui, ilContainer $a_parent_obj) + { + global $DIC; + + $this->tpl = $DIC["tpl"]; + $this->lng = $DIC->language(); + $this->settings = $DIC->settings(); + $this->user = $DIC->user(); + include_once "Services/Container/classes/class.ilContainerStartObjects.php"; + $this->parent_gui = $a_gui; + $this->parent_obj = $a_parent_obj; + $this->start_object = new ilContainerStartObjects( + $a_parent_obj->getRefId(), + $a_parent_obj->getId() + ); + } + + /** + * Toggle add-to/remove-from-desktop + * + * @param bool $a_value + * @param ilContainerGUI $a_parent_gui + */ + public function enableDesktop($a_value, ilContainerGUI $a_parent_gui) + { + $this->enable_desktop = (bool) $a_value; + + if ($this->enable_desktop) { + $this->parent_gui = $a_parent_gui; + } + } + + /** + * Get container start objects list (presentation) + * + * @return string + */ + public function getHTML() + { + $tpl = $this->tpl; + $lng = $this->lng; + + $lng->loadLanguageModule("crs"); + + include_once "Services/Container/classes/class.ilContainerStartObjectsContentTableGUI.php"; + $tbl = new ilContainerStartObjectsContentTableGUI( + $this->parent_gui, + "", + $this->start_object, + $this->enable_desktop + ); + $tpl->setContent( + $this->getPageHTML() . + $tbl->getHTML() + ); + } + + /** + * Render COPage + * + * @see ilContainerGUI + * @return string + */ + protected function getPageHTML() + { + $tpl = $this->tpl; + $ilSetting = $this->settings; + $ilUser = $this->user; + + if (!$ilSetting->get("enable_cat_page_edit")) { + return; + } + + $page_id = $this->start_object->getObjId(); + + // if page does not exist, return nothing + include_once("./Services/COPage/classes/class.ilPageUtil.php"); + if (!ilPageUtil::_existsAndNotEmpty("cstr", $page_id)) { + return; + } + + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath(ilObjStyleSheet::getEffectiveContentStyleId( + $this->parent_obj->getStyleSheetId(), + $this->parent_obj->getType() + )) + ); + $tpl->setCurrentBlock("SyntaxStyle"); + $tpl->setVariable( + "LOCATION_SYNTAX_STYLESHEET", + ilObjStyleSheet::getSyntaxStylePath() + ); + $tpl->parseCurrentBlock(); + + include_once("./Services/Container/classes/class.ilContainerStartObjectsPageGUI.php"); + $page_gui = new ilContainerStartObjectsPageGUI($page_id); + + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $page_gui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId( + $this->parent_obj->getStyleSheetId(), + $this->parent_obj->getType() + )); + + $page_gui->setPresentationTitle(""); + $page_gui->setTemplateOutput(false); + $page_gui->setHeader(""); + return $page_gui->showPage(); + } +} diff --git a/Services/Container/classes/class.ilContainerStartObjectsContentTableGUI.php b/Services/Container/classes/class.ilContainerStartObjectsContentTableGUI.php index 36119f0933705c3b1cc33d1e3886b675941bf5c3..159d10ce160dd9d09521e1cf857cf6d7e218d5a3 100644 --- a/Services/Container/classes/class.ilContainerStartObjectsContentTableGUI.php +++ b/Services/Container/classes/class.ilContainerStartObjectsContentTableGUI.php @@ -1,323 +1,299 @@ - - * @version $Id$ - * - * @ingroup ServicesContainer - */ -class ilContainerStartObjectsContentTableGUI extends ilTable2GUI -{ - /** - * @var ilCtrl - */ - protected $ctrl; + + * @version $Id$ + * + * @ingroup ServicesContainer + */ +class ilContainerStartObjectsContentTableGUI extends ilTable2GUI +{ + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilObjUser + */ + protected $user; - /** - * @var ilObjectDefinition - */ - protected $obj_definition; + /** + * @var ilObjectDataCache + */ + protected $obj_data_cache; - protected $start_object; // [ilContainerStartObjects] - protected $item_list_guis; // [array] - protected $enable_desktop; // [bool] - - public function __construct($a_parent_obj, $a_parent_cmd, ilContainerStartObjects $a_start_objects, $a_enable_desktop = true) - { - global $DIC; + /** + * @var ilAccessHandler + */ + protected $access; - $this->user = $DIC->user(); - $this->obj_data_cache = $DIC["ilObjDataCache"]; - $this->access = $DIC->access(); - $this->obj_definition = $DIC["objDefinition"]; - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - - $this->lng = $lng; - $this->ctrl = $ilCtrl; - - $this->start_object = $a_start_objects; - $this->enable_desktop = (bool)$a_enable_desktop; - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->addColumn($this->lng->txt('crs_nr'),'nr'); - $this->addColumn($this->lng->txt('title'),'title'); - $this->addColumn($this->lng->txt('crs_objective_accomplished'), 'status'); - $this->addColumn($this->lng->txt('actions'), ''); - - $this->setTitle($this->lng->txt('crs_table_start_objects')); - $this->setDescription($this->lng->txt('crs_info_start')); - - $this->setRowTemplate("tpl.start_objects_content_row.html", "Services/Container"); - $this->setFormAction($this->ctrl->getFormAction($a_parent_obj)); - - $this->setDefaultOrderField('nr'); - $this->setDefaultOrderDirection('asc'); - - $this->getItems(); - } - - protected function getItems() - { - $ilUser = $this->user; - $ilObjDataCache = $this->obj_data_cache; - $ilAccess = $this->access; - - include_once './Modules/Course/classes/class.ilCourseLMHistory.php'; - include_once './Services/Link/classes/class.ilLink.php'; - - $lm_continue = new ilCourseLMHistory($this->start_object->getRefId(),$ilUser->getId()); - $continue_data = $lm_continue->getLMHistory(); - - $items = array(); - $counter = 0; - foreach($this->start_object->getStartObjects() as $start) - { - $obj_id = $ilObjDataCache->lookupObjId($start['item_ref_id']); - $ref_id = $start['item_ref_id']; - $type = $ilObjDataCache->lookupType($obj_id); - - if(!$ilAccess->checkAccess("visible", "", $ref_id)) - { - continue; - } - - // start object status - if($this->start_object->isFullfilled($ilUser->getId(), $ref_id)) - { - $accomplished = 'accomplished'; - } - else - { - $accomplished = 'not_accomplished'; - } - - // add/remove desktop - $actions = array(); - if((bool)$this->enable_desktop) - { - // add to desktop link - if(!$ilUser->isDesktopItem($ref_id,$type)) - { - if ($ilAccess->checkAccess('read','',$ref_id)) - { - $this->ctrl->setParameter($this->getParentObject(),'item_ref_id',$ref_id); - $this->ctrl->setParameter($this->getParentObject(),'item_id',$ref_id); - $this->ctrl->setParameter($this->getParentObject(),'type',$type); - $url = $this->ctrl->getLinkTarget($this->getParentObject(),'addToDesk'); - $actions[$url] = $this->lng->txt("to_desktop"); - } - } - else - { - $this->ctrl->setParameter($this->getParentObject(),'item_ref_id',$ref_id); - $this->ctrl->setParameter($this->getParentObject(),'item_id',$ref_id); - $this->ctrl->setParameter($this->getParentObject(),'type',$type); - $url = $this->ctrl->getLinkTarget($this->getParentObject(),'removeFromDesk'); - $actions[$url] = $this->lng->txt("unsubscribe"); - } - } - - $default_params = null; - if($type == "tst") - { - $default_params["crs_show_result"] = $ref_id; - } - /* continue is currently inactive - if(isset($continue_data[$ref_id])) - { - // :TODO: should "continue" be default or 2nd link/action? - // $this->lng->txt('continue_work') - $default_params["obj_id"] = $continue_data[$ref_id]['lm_page_id']; - } - */ - - if ($accomplished == 'accomplished') - { - $icon = ilUtil::getImagePath("icon_ok.svg"); - } - else - { - $icon = ilUtil::getImagePath("icon_not_ok.svg"); - } - - $items[] = array("nr" => ++$counter, - "obj_id" => $obj_id, - "ref_id" => $ref_id, - "type" => $type, - "append_default" => $default_params, - "title" => $ilObjDataCache->lookupTitle($obj_id), - "description" => $ilObjDataCache->lookupDescription($obj_id), - "status" => $this->lng->txt('crs_objective_'.$accomplished), - "status_img" => $icon, - "actions" => $actions); - } - - include_once("./Services/Object/classes/class.ilObjectListGUIPreloader.php"); - $preloader = new ilObjectListGUIPreloader(ilObjectListGUI::CONTEXT_REPOSITORY); - foreach($items as $item) - { - $preloader->addItem($item["obj_id"], $item["type"], $item["ref_id"]); - } - $preloader->preload(); - unset($preloader); - - reset($items); - $this->setData($items); - } - - /** - * Get list gui for object type - * - * @see ilPDSelectedItemsBlockGUI - * - * @param string $a_type - * @return ilObjectListGUI - */ - protected function getItemListGUI($a_type) - { - $objDefinition = $this->obj_definition; - - if (!isset($this->item_list_guis[$a_type])) - { - $class = $objDefinition->getClassName($a_type); - // Fixed problem with deactivated plugins and existing repo. object plugin objects on the user's desktop - if(!$class) - { - return NULL; - } - // Fixed problem with deactivated plugins and existing repo. object plugin objects on the user's desktop - $location = $objDefinition->getLocation($a_type); - if(!$location) - { - return NULL; - } - $full_class = "ilObj".$class."ListGUI"; - include_once($location."/class.".$full_class.".php"); - $item_list_gui = new $full_class(); - $this->item_list_guis[$a_type] = $item_list_gui; - } - else - { - $item_list_gui = $this->item_list_guis[$a_type]; - } - - $item_list_gui->setDefaultCommandParameters(array()); - - return $item_list_gui; - } - - /** - * Get list gui for object instance - * - * @param array $a_item - * @return string - */ - protected function getListItem($a_item) - { - $item_list_gui = $this->getItemListGUI($a_item["type"]); - if(!$item_list_gui) - { - return; - } - - $item_list_gui->setContainerObject($this); - $item_list_gui->enableCommands(true, true); - - // ilObjectActivation::addListGUIActivationProperty($item_list_gui, $a_item); - - // notes, comment currently do not work properly - $item_list_gui->enableNotes(false); - $item_list_gui->enableComments(false); - $item_list_gui->enableTags(false); - - $item_list_gui->enableIcon(true); - $item_list_gui->enableDelete(false); - $item_list_gui->enableCut(false); - $item_list_gui->enableCopy(false); - $item_list_gui->enableLink(false); - $item_list_gui->enableInfoScreen(true); - $item_list_gui->enableSubscribe(false); - - $level = 3; - - if ($level < 3) - { - $item_list_gui->enableDescription(false); - $item_list_gui->enableProperties(false); - $item_list_gui->enablePreconditions(false); - } - - if($a_item["append_default"]) - { - $item_list_gui->setDefaultCommandParameters($a_item["append_default"]); - } - if (is_object($item_list_gui)) - { - return $item_list_gui->getListItemHTML($a_item["ref_id"], - $a_item["obj_id"], $a_item["title"], $a_item["description"]); - } - } - - public function fillRow($a_set) - { - $this->tpl->setVariable("VAL_NR", $a_set["nr"]); - - // begin-patch lok - $this->tpl->setVariable("TXT_TITLE", $this->getListItem($a_set)); - /* - include_once './Modules/Course/classes/Objectives/class.ilLOSettings.php'; - if(ilLOSettings::getInstanceByObjId($this->getParentObject()->object->getId())->isObjectiveTest($a_set['ref_id'])) - { - $this->ctrl->setParameter($this->getParentObject(),'tid',$a_set['ref_id']); - $this->tpl->setVariable('TYPE_IMG',ilUtil::getTypeIconPath($a_set['type'], $a_set['obj_id'], 'small')); - $this->tpl->setVariable('TITLE_MANUAL_LINK',$this->ctrl->getLinkTargetByClass(get_class($this->getParentObject()),'redirectLocToTest')); - $this->tpl->setVariable('VAL_TITLE_MANUAL',$a_set['title']); - } - else - { - $this->tpl->setVariable('TYPE_IMG',ilUtil::getTypeIconPath($a_set['type'], $a_set['obj_id'], 'small')); - include_once './Services/Link/classes/class.ilLink.php'; - $this->tpl->setVariable('TITLE_MANUAL_LINK',ilLink::_getLink($a_set['ref_id'])); - $this->tpl->setVariable('VAL_TITLE_MANUAL',$a_set['title']); - } - // end-patch lok - */ - - $this->tpl->setVariable("TXT_STATUS", $a_set["status"]); - $this->tpl->setVariable("IMG_STATUS", $a_set["status_img"]); - - if($a_set["actions"]) - { - $this->tpl->setCurrentBlock("link"); - foreach($a_set["actions"] as $url => $caption) - { - $this->tpl->setVariable("LINK_HREF", $url); - $this->tpl->setVariable("LINK_NAME", $caption); - } - $this->tpl->parseCurrentBlock(); - } - } -} - -?> \ No newline at end of file + /** + * @var ilObjectDefinition + */ + protected $obj_definition; + + protected $start_object; // [ilContainerStartObjects] + protected $item_list_guis; // [array] + protected $enable_desktop; // [bool] + + public function __construct($a_parent_obj, $a_parent_cmd, ilContainerStartObjects $a_start_objects, $a_enable_desktop = true) + { + global $DIC; + + $this->user = $DIC->user(); + $this->obj_data_cache = $DIC["ilObjDataCache"]; + $this->access = $DIC->access(); + $this->obj_definition = $DIC["objDefinition"]; + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + + $this->lng = $lng; + $this->ctrl = $ilCtrl; + + $this->start_object = $a_start_objects; + $this->enable_desktop = (bool) $a_enable_desktop; + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->addColumn($this->lng->txt('crs_nr'), 'nr'); + $this->addColumn($this->lng->txt('title'), 'title'); + $this->addColumn($this->lng->txt('crs_objective_accomplished'), 'status'); + $this->addColumn($this->lng->txt('actions'), ''); + + $this->setTitle($this->lng->txt('crs_table_start_objects')); + $this->setDescription($this->lng->txt('crs_info_start')); + + $this->setRowTemplate("tpl.start_objects_content_row.html", "Services/Container"); + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj)); + + $this->setDefaultOrderField('nr'); + $this->setDefaultOrderDirection('asc'); + + $this->getItems(); + } + + protected function getItems() + { + $ilUser = $this->user; + $ilObjDataCache = $this->obj_data_cache; + $ilAccess = $this->access; + + include_once './Modules/Course/classes/class.ilCourseLMHistory.php'; + include_once './Services/Link/classes/class.ilLink.php'; + + $lm_continue = new ilCourseLMHistory($this->start_object->getRefId(), $ilUser->getId()); + $continue_data = $lm_continue->getLMHistory(); + + $items = array(); + $counter = 0; + foreach ($this->start_object->getStartObjects() as $start) { + $obj_id = $ilObjDataCache->lookupObjId($start['item_ref_id']); + $ref_id = $start['item_ref_id']; + $type = $ilObjDataCache->lookupType($obj_id); + + if (!$ilAccess->checkAccess("visible", "", $ref_id)) { + continue; + } + + // start object status + if ($this->start_object->isFullfilled($ilUser->getId(), $ref_id)) { + $accomplished = 'accomplished'; + } else { + $accomplished = 'not_accomplished'; + } + + // add/remove desktop + $actions = array(); + if ((bool) $this->enable_desktop) { + // add to desktop link + if (!$ilUser->isDesktopItem($ref_id, $type)) { + if ($ilAccess->checkAccess('read', '', $ref_id)) { + $this->ctrl->setParameter($this->getParentObject(), 'item_ref_id', $ref_id); + $this->ctrl->setParameter($this->getParentObject(), 'item_id', $ref_id); + $this->ctrl->setParameter($this->getParentObject(), 'type', $type); + $url = $this->ctrl->getLinkTarget($this->getParentObject(), 'addToDesk'); + $actions[$url] = $this->lng->txt("to_desktop"); + } + } else { + $this->ctrl->setParameter($this->getParentObject(), 'item_ref_id', $ref_id); + $this->ctrl->setParameter($this->getParentObject(), 'item_id', $ref_id); + $this->ctrl->setParameter($this->getParentObject(), 'type', $type); + $url = $this->ctrl->getLinkTarget($this->getParentObject(), 'removeFromDesk'); + $actions[$url] = $this->lng->txt("unsubscribe"); + } + } + + $default_params = null; + if ($type == "tst") { + $default_params["crs_show_result"] = $ref_id; + } + /* continue is currently inactive + if(isset($continue_data[$ref_id])) + { + // :TODO: should "continue" be default or 2nd link/action? + // $this->lng->txt('continue_work') + $default_params["obj_id"] = $continue_data[$ref_id]['lm_page_id']; + } + */ + + if ($accomplished == 'accomplished') { + $icon = ilUtil::getImagePath("icon_ok.svg"); + } else { + $icon = ilUtil::getImagePath("icon_not_ok.svg"); + } + + $items[] = array("nr" => ++$counter, + "obj_id" => $obj_id, + "ref_id" => $ref_id, + "type" => $type, + "append_default" => $default_params, + "title" => $ilObjDataCache->lookupTitle($obj_id), + "description" => $ilObjDataCache->lookupDescription($obj_id), + "status" => $this->lng->txt('crs_objective_' . $accomplished), + "status_img" => $icon, + "actions" => $actions); + } + + include_once("./Services/Object/classes/class.ilObjectListGUIPreloader.php"); + $preloader = new ilObjectListGUIPreloader(ilObjectListGUI::CONTEXT_REPOSITORY); + foreach ($items as $item) { + $preloader->addItem($item["obj_id"], $item["type"], $item["ref_id"]); + } + $preloader->preload(); + unset($preloader); + + reset($items); + $this->setData($items); + } + + /** + * Get list gui for object type + * + * @see ilPDSelectedItemsBlockGUI + * + * @param string $a_type + * @return ilObjectListGUI + */ + protected function getItemListGUI($a_type) + { + $objDefinition = $this->obj_definition; + + if (!isset($this->item_list_guis[$a_type])) { + $class = $objDefinition->getClassName($a_type); + // Fixed problem with deactivated plugins and existing repo. object plugin objects on the user's desktop + if (!$class) { + return null; + } + // Fixed problem with deactivated plugins and existing repo. object plugin objects on the user's desktop + $location = $objDefinition->getLocation($a_type); + if (!$location) { + return null; + } + $full_class = "ilObj" . $class . "ListGUI"; + include_once($location . "/class." . $full_class . ".php"); + $item_list_gui = new $full_class(); + $this->item_list_guis[$a_type] = $item_list_gui; + } else { + $item_list_gui = $this->item_list_guis[$a_type]; + } + + $item_list_gui->setDefaultCommandParameters(array()); + + return $item_list_gui; + } + + /** + * Get list gui for object instance + * + * @param array $a_item + * @return string + */ + protected function getListItem($a_item) + { + $item_list_gui = $this->getItemListGUI($a_item["type"]); + if (!$item_list_gui) { + return; + } + + $item_list_gui->setContainerObject($this); + $item_list_gui->enableCommands(true, true); + + // ilObjectActivation::addListGUIActivationProperty($item_list_gui, $a_item); + + // notes, comment currently do not work properly + $item_list_gui->enableNotes(false); + $item_list_gui->enableComments(false); + $item_list_gui->enableTags(false); + + $item_list_gui->enableIcon(true); + $item_list_gui->enableDelete(false); + $item_list_gui->enableCut(false); + $item_list_gui->enableCopy(false); + $item_list_gui->enableLink(false); + $item_list_gui->enableInfoScreen(true); + $item_list_gui->enableSubscribe(false); + + $level = 3; + + if ($level < 3) { + $item_list_gui->enableDescription(false); + $item_list_gui->enableProperties(false); + $item_list_gui->enablePreconditions(false); + } + + if ($a_item["append_default"]) { + $item_list_gui->setDefaultCommandParameters($a_item["append_default"]); + } + if (is_object($item_list_gui)) { + return $item_list_gui->getListItemHTML( + $a_item["ref_id"], + $a_item["obj_id"], + $a_item["title"], + $a_item["description"] + ); + } + } + + public function fillRow($a_set) + { + $this->tpl->setVariable("VAL_NR", $a_set["nr"]); + + // begin-patch lok + $this->tpl->setVariable("TXT_TITLE", $this->getListItem($a_set)); + /* + include_once './Modules/Course/classes/Objectives/class.ilLOSettings.php'; + if(ilLOSettings::getInstanceByObjId($this->getParentObject()->object->getId())->isObjectiveTest($a_set['ref_id'])) + { + $this->ctrl->setParameter($this->getParentObject(),'tid',$a_set['ref_id']); + $this->tpl->setVariable('TYPE_IMG',ilUtil::getTypeIconPath($a_set['type'], $a_set['obj_id'], 'small')); + $this->tpl->setVariable('TITLE_MANUAL_LINK',$this->ctrl->getLinkTargetByClass(get_class($this->getParentObject()),'redirectLocToTest')); + $this->tpl->setVariable('VAL_TITLE_MANUAL',$a_set['title']); + } + else + { + $this->tpl->setVariable('TYPE_IMG',ilUtil::getTypeIconPath($a_set['type'], $a_set['obj_id'], 'small')); + include_once './Services/Link/classes/class.ilLink.php'; + $this->tpl->setVariable('TITLE_MANUAL_LINK',ilLink::_getLink($a_set['ref_id'])); + $this->tpl->setVariable('VAL_TITLE_MANUAL',$a_set['title']); + } + // end-patch lok + */ + + $this->tpl->setVariable("TXT_STATUS", $a_set["status"]); + $this->tpl->setVariable("IMG_STATUS", $a_set["status_img"]); + + if ($a_set["actions"]) { + $this->tpl->setCurrentBlock("link"); + foreach ($a_set["actions"] as $url => $caption) { + $this->tpl->setVariable("LINK_HREF", $url); + $this->tpl->setVariable("LINK_NAME", $caption); + } + $this->tpl->parseCurrentBlock(); + } + } +} diff --git a/Services/Container/classes/class.ilContainerStartObjectsGUI.php b/Services/Container/classes/class.ilContainerStartObjectsGUI.php index 4667b8b778334c447a605826782a0d1e40db22ec..45901a05f3395e21aa83f6f2899ae54bb72825f9 100644 --- a/Services/Container/classes/class.ilContainerStartObjectsGUI.php +++ b/Services/Container/classes/class.ilContainerStartObjectsGUI.php @@ -1,288 +1,283 @@ - - * $Id: class.ilObjCourseGUI.php 47058 2014-01-08 08:07:12Z mjansen $ - * - * @ilCtrl_Calls ilContainerStartObjectsGUI: ilContainerStartObjectsPageGUI - * @ingroup ServicesContainer - */ -class ilContainerStartObjectsGUI -{ - /** - * @var ilCtrl - */ - protected $ctrl; + + * $Id: class.ilObjCourseGUI.php 47058 2014-01-08 08:07:12Z mjansen $ + * + * @ilCtrl_Calls ilContainerStartObjectsGUI: ilContainerStartObjectsPageGUI + * @ingroup ServicesContainer + */ +class ilContainerStartObjectsGUI +{ + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilTabsGUI + */ + protected $tabs_gui; - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilTemplate + */ + protected $tpl; - /** - * @var ilSetting - */ - protected $settings; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * @var ilToolbarGUI - */ - protected $toolbar; + /** + * @var ilSetting + */ + protected $settings; - protected $object; // [ilObject] - protected $start_object; // [ilContainerStartObjects] - - public function __construct(ilObject $a_parent_obj) - { - global $DIC; + /** + * @var ilToolbarGUI + */ + protected $toolbar; - $this->access = $DIC->access(); - $this->settings = $DIC->settings(); - $this->toolbar = $DIC->toolbar(); - $ilCtrl = $DIC->ctrl(); - $ilTabs = $DIC->tabs(); - $lng = $DIC->language(); - $tpl = $DIC["tpl"]; - - $this->ctrl = $ilCtrl; - $this->tabs_gui = $ilTabs; - $this->lng = $lng; - $this->tpl = $tpl; - $this->object = $a_parent_obj; - - include_once "Services/Container/classes/class.ilContainerStartObjects.php"; - $this->start_object = new ilContainerStartObjects($this->object->getRefId(), - $this->object->getId()); - - $this->lng->loadLanguageModule("crs"); - } - - public function executeCommand() - { - // $this->prepareOutput(); - - switch($this->ctrl->getNextClass($this)) - { - case "ilcontainerstartobjectspagegui": - $this->checkPermission("write"); - $this->tabs_gui->clearTargets(); - $this->tabs_gui->setBackTarget($this->lng->txt("back"), - $this->ctrl->getLinkTarget($this, "listStructure")); - - include_once "Services/Container/classes/class.ilContainerStartObjectsPage.php"; - if(!ilContainerStartObjectsPage::_exists("cstr", $this->object->getId())) - { - // doesn't exist -> create new one - $new_page_object = new ilContainerStartObjectsPage(); - $new_page_object->setParentId($this->object->getId()); - $new_page_object->setId($this->object->getId()); - $new_page_object->createFromXML(); - unset($new_page_object); - } - - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath(ilObjStyleSheet::getEffectiveContentStyleId( - $this->object->getStyleSheetId(), $this->object->getType()))); - - $this->ctrl->setReturnByClass("ilcontainerstartobjectspagegui", "edit"); - include_once "Services/Container/classes/class.ilContainerStartObjectsPageGUI.php"; - $pgui = new ilContainerStartObjectsPageGUI($this->object->getId()); - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $pgui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId( - $this->object->getStyleSheetId(), $this->object->getType())); - - $ret = $this->ctrl->forwardCommand($pgui); - if($ret) - { - $this->tpl->setContent($ret); - } - break; - - default: - $cmd = $this->ctrl->getCmd("listStructure"); - $cmd .= "Object"; - $this->$cmd(); - break; - } - } - - protected function checkPermission($a_cmd) - { - $ilAccess = $this->access; - - $ref_id = $this->object->getRefId(); - if(!$ilAccess->checkAccess($a_cmd, "", $ref_id)) - { - ilUtil::sendFailure($this->lng->txt("permission_denied"), true); - ilUtil::redirect("goto.php?target=".$this->object->getType()."_".$ref_id); - } - } - - public function setTabs($a_active = "manage") - { - $ilSetting = $this->settings; - - $this->tabs_gui->addSubTab("manage", - $this->lng->txt("cntr_manage"), - $this->ctrl->getLinkTarget($this, "listStructure")); - - // :TODO: depending on this setting? - if ($ilSetting->get("enable_cat_page_edit")) - { - $this->tabs_gui->addSubTab("page_editor", - $this->lng->txt("cntr_text_media_editor"), - $this->ctrl->getLinkTargetByClass("ilContainerStartObjectsPageGUI", "edit")); - } - - $this->tabs_gui->activateSubTab($a_active); - } - - protected function listStructureObject() - { - $ilToolbar = $this->toolbar; - - $this->checkPermission('write'); - $this->setTabs(); - - $ilToolbar->addButton($this->lng->txt('crs_add_starter'), - $this->ctrl->getLinkTarget($this, 'selectStarter')); - - include_once './Services/Container/classes/class.ilContainerStartObjectsTableGUI.php'; - $table = new ilContainerStartObjectsTableGUI($this, 'listStructure', $this->start_object); - $this->tpl->setContent($table->getHTML()); - } - - protected function saveSortingObject() - { - $pos = $_POST["pos"]; - if(is_array($pos)) - { - asort($pos); - $counter = 0; - foreach(array_keys($pos) as $start_id) - { - $counter += 10; - $this->start_object->setObjectPos($start_id, $counter); - } - - ilUtil::sendSuccess($this->lng->txt('cntr_saved_sorting'), true); - } - - $this->ctrl->redirect($this, "listStructure"); - } - - protected function askDeleteStarterObject() - { - if(!count($_POST['starter'])) - { - ilUtil::sendFailure($this->lng->txt('select_one'), true); - $this->ctrl->redirect($this, "listStructure"); - } - - $this->checkPermission('write'); - $this->setTabs(); - - // display confirmation message - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($this->ctrl->getFormAction($this, "listStructure")); - $cgui->setHeaderText($this->lng->txt("crs_starter_delete_sure")); - $cgui->setCancel($this->lng->txt("cancel"), "listStructure"); - $cgui->setConfirm($this->lng->txt("remove"), "deleteStarter"); - - // list objects that should be deleted - $all = $this->start_object->getStartObjects(); - foreach($_POST['starter'] as $starter_id) - { - $obj_id = ilObject::_lookupObjId($all[$starter_id]["item_ref_id"]); - $title = ilObject::_lookupTitle($obj_id); - $icon = ilObject::_getIcon($obj_id, "tiny"); - $alt = $this->lng->txt('obj_'.ilObject::_lookupType($obj_id)); - $cgui->addItem("starter[]", $starter_id, $title, $icon, $alt); - } - - $this->tpl->setContent($cgui->getHTML()); - } - - protected function deleteStarterObject() - { - $this->checkPermission('write'); - - if(!count($_POST['starter'])) - { - ilUtil::sendFailure($this->lng->txt('select_one'), true); - } - else - { - foreach($_POST['starter'] as $starter_id) - { - $this->start_object->delete((int)$starter_id); - } - - ilUtil::sendSuccess($this->lng->txt('crs_starter_deleted'), true); - } - - $this->ctrl->redirect($this, "listStructure"); - } - - protected function selectStarterObject() - { - $this->checkPermission('write'); - $this->setTabs(); - - include_once './Services/Container/classes/class.ilContainerStartObjectsTableGUI.php'; - $table = new ilContainerStartObjectsTableGUI($this, 'selectStarter', $this->start_object); - $this->tpl->setContent($table->getHTML()); - } - - protected function addStarterObject() - { - $this->checkPermission('write'); - - if(!count($_POST['starter'])) - { - ilUtil::sendFailure($this->lng->txt('select_one'), true); - $this->ctrl->redirect($this, "selectStarter"); - } - - $added = 0; - foreach($_POST['starter'] as $item_ref_id) - { - if(!$this->start_object->exists($item_ref_id)) - { - ++$added; - $this->start_object->add($item_ref_id); - } - } - if($added) - { - ilUtil::sendSuccess($this->lng->txt('crs_added_starters'), true); - $this->ctrl->redirect($this, "listStructure"); - } - else - { - ilUtil::sendFailure($this->lng->txt('crs_starters_already_assigned'), true); - $this->ctrl->redirect($this, "selectStarter"); - } - } -} - -?> \ No newline at end of file + protected $object; // [ilObject] + protected $start_object; // [ilContainerStartObjects] + + public function __construct(ilObject $a_parent_obj) + { + global $DIC; + + $this->access = $DIC->access(); + $this->settings = $DIC->settings(); + $this->toolbar = $DIC->toolbar(); + $ilCtrl = $DIC->ctrl(); + $ilTabs = $DIC->tabs(); + $lng = $DIC->language(); + $tpl = $DIC["tpl"]; + + $this->ctrl = $ilCtrl; + $this->tabs_gui = $ilTabs; + $this->lng = $lng; + $this->tpl = $tpl; + $this->object = $a_parent_obj; + + include_once "Services/Container/classes/class.ilContainerStartObjects.php"; + $this->start_object = new ilContainerStartObjects( + $this->object->getRefId(), + $this->object->getId() + ); + + $this->lng->loadLanguageModule("crs"); + } + + public function executeCommand() + { + // $this->prepareOutput(); + + switch ($this->ctrl->getNextClass($this)) { + case "ilcontainerstartobjectspagegui": + $this->checkPermission("write"); + $this->tabs_gui->clearTargets(); + $this->tabs_gui->setBackTarget( + $this->lng->txt("back"), + $this->ctrl->getLinkTarget($this, "listStructure") + ); + + include_once "Services/Container/classes/class.ilContainerStartObjectsPage.php"; + if (!ilContainerStartObjectsPage::_exists("cstr", $this->object->getId())) { + // doesn't exist -> create new one + $new_page_object = new ilContainerStartObjectsPage(); + $new_page_object->setParentId($this->object->getId()); + $new_page_object->setId($this->object->getId()); + $new_page_object->createFromXML(); + unset($new_page_object); + } + + $this->tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath(ilObjStyleSheet::getEffectiveContentStyleId( + $this->object->getStyleSheetId(), + $this->object->getType() + )) + ); + + $this->ctrl->setReturnByClass("ilcontainerstartobjectspagegui", "edit"); + include_once "Services/Container/classes/class.ilContainerStartObjectsPageGUI.php"; + $pgui = new ilContainerStartObjectsPageGUI($this->object->getId()); + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $pgui->setStyleId(ilObjStyleSheet::getEffectiveContentStyleId( + $this->object->getStyleSheetId(), + $this->object->getType() + )); + + $ret = $this->ctrl->forwardCommand($pgui); + if ($ret) { + $this->tpl->setContent($ret); + } + break; + + default: + $cmd = $this->ctrl->getCmd("listStructure"); + $cmd .= "Object"; + $this->$cmd(); + break; + } + } + + protected function checkPermission($a_cmd) + { + $ilAccess = $this->access; + + $ref_id = $this->object->getRefId(); + if (!$ilAccess->checkAccess($a_cmd, "", $ref_id)) { + ilUtil::sendFailure($this->lng->txt("permission_denied"), true); + ilUtil::redirect("goto.php?target=" . $this->object->getType() . "_" . $ref_id); + } + } + + public function setTabs($a_active = "manage") + { + $ilSetting = $this->settings; + + $this->tabs_gui->addSubTab( + "manage", + $this->lng->txt("cntr_manage"), + $this->ctrl->getLinkTarget($this, "listStructure") + ); + + // :TODO: depending on this setting? + if ($ilSetting->get("enable_cat_page_edit")) { + $this->tabs_gui->addSubTab( + "page_editor", + $this->lng->txt("cntr_text_media_editor"), + $this->ctrl->getLinkTargetByClass("ilContainerStartObjectsPageGUI", "edit") + ); + } + + $this->tabs_gui->activateSubTab($a_active); + } + + protected function listStructureObject() + { + $ilToolbar = $this->toolbar; + + $this->checkPermission('write'); + $this->setTabs(); + + $ilToolbar->addButton( + $this->lng->txt('crs_add_starter'), + $this->ctrl->getLinkTarget($this, 'selectStarter') + ); + + include_once './Services/Container/classes/class.ilContainerStartObjectsTableGUI.php'; + $table = new ilContainerStartObjectsTableGUI($this, 'listStructure', $this->start_object); + $this->tpl->setContent($table->getHTML()); + } + + protected function saveSortingObject() + { + $pos = $_POST["pos"]; + if (is_array($pos)) { + asort($pos); + $counter = 0; + foreach (array_keys($pos) as $start_id) { + $counter += 10; + $this->start_object->setObjectPos($start_id, $counter); + } + + ilUtil::sendSuccess($this->lng->txt('cntr_saved_sorting'), true); + } + + $this->ctrl->redirect($this, "listStructure"); + } + + protected function askDeleteStarterObject() + { + if (!count($_POST['starter'])) { + ilUtil::sendFailure($this->lng->txt('select_one'), true); + $this->ctrl->redirect($this, "listStructure"); + } + + $this->checkPermission('write'); + $this->setTabs(); + + // display confirmation message + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($this->ctrl->getFormAction($this, "listStructure")); + $cgui->setHeaderText($this->lng->txt("crs_starter_delete_sure")); + $cgui->setCancel($this->lng->txt("cancel"), "listStructure"); + $cgui->setConfirm($this->lng->txt("remove"), "deleteStarter"); + + // list objects that should be deleted + $all = $this->start_object->getStartObjects(); + foreach ($_POST['starter'] as $starter_id) { + $obj_id = ilObject::_lookupObjId($all[$starter_id]["item_ref_id"]); + $title = ilObject::_lookupTitle($obj_id); + $icon = ilObject::_getIcon($obj_id, "tiny"); + $alt = $this->lng->txt('obj_' . ilObject::_lookupType($obj_id)); + $cgui->addItem("starter[]", $starter_id, $title, $icon, $alt); + } + + $this->tpl->setContent($cgui->getHTML()); + } + + protected function deleteStarterObject() + { + $this->checkPermission('write'); + + if (!count($_POST['starter'])) { + ilUtil::sendFailure($this->lng->txt('select_one'), true); + } else { + foreach ($_POST['starter'] as $starter_id) { + $this->start_object->delete((int) $starter_id); + } + + ilUtil::sendSuccess($this->lng->txt('crs_starter_deleted'), true); + } + + $this->ctrl->redirect($this, "listStructure"); + } + + protected function selectStarterObject() + { + $this->checkPermission('write'); + $this->setTabs(); + + include_once './Services/Container/classes/class.ilContainerStartObjectsTableGUI.php'; + $table = new ilContainerStartObjectsTableGUI($this, 'selectStarter', $this->start_object); + $this->tpl->setContent($table->getHTML()); + } + + protected function addStarterObject() + { + $this->checkPermission('write'); + + if (!count($_POST['starter'])) { + ilUtil::sendFailure($this->lng->txt('select_one'), true); + $this->ctrl->redirect($this, "selectStarter"); + } + + $added = 0; + foreach ($_POST['starter'] as $item_ref_id) { + if (!$this->start_object->exists($item_ref_id)) { + ++$added; + $this->start_object->add($item_ref_id); + } + } + if ($added) { + ilUtil::sendSuccess($this->lng->txt('crs_added_starters'), true); + $this->ctrl->redirect($this, "listStructure"); + } else { + ilUtil::sendFailure($this->lng->txt('crs_starters_already_assigned'), true); + $this->ctrl->redirect($this, "selectStarter"); + } + } +} diff --git a/Services/Container/classes/class.ilContainerStartObjectsPage.php b/Services/Container/classes/class.ilContainerStartObjectsPage.php index 2cda034cb17786e03581e96c5a7e46475d93f5f9..5d3933cd23750f30398b6f1fb546975d470f5542 100644 --- a/Services/Container/classes/class.ilContainerStartObjectsPage.php +++ b/Services/Container/classes/class.ilContainerStartObjectsPage.php @@ -1,27 +1,24 @@ - - * @version $Id$ - * @ingroup ServicesContainer - */ -class ilContainerStartObjectsPage extends ilPageObject -{ - /** - * Get parent type - * - * @return string parent type - */ - function getParentType() - { - return "cstr"; - } - -} - -?> \ No newline at end of file + + * @version $Id$ + * @ingroup ServicesContainer + */ +class ilContainerStartObjectsPage extends ilPageObject +{ + /** + * Get parent type + * + * @return string parent type + */ + public function getParentType() + { + return "cstr"; + } +} diff --git a/Services/Container/classes/class.ilContainerStartObjectsPageConfig.php b/Services/Container/classes/class.ilContainerStartObjectsPageConfig.php index a3c6caf956df024afb9092d8b5819dcade1d2cc7..e14781121be5d4d81a5fba1a74d8736b913936b9 100644 --- a/Services/Container/classes/class.ilContainerStartObjectsPageConfig.php +++ b/Services/Container/classes/class.ilContainerStartObjectsPageConfig.php @@ -1,32 +1,29 @@ - - * @version $Id$ - * @ingroup ServicesContainer - */ -class ilContainerStartObjectsPageConfig extends ilPageConfig -{ - /** - * Init - */ - function init() - { - $this->setEnableInternalLinks(true); - $this->setIntLinkHelpDefaultType("RepositoryItem"); - $this->setEnablePCType("FileList", false); - $this->setEnablePCType("Map", true); - $this->setEnablePCType("Resources", false); - $this->setMultiLangSupport(false); - $this->setSinglePageMode(true); - } - -} - -?> + + * @version $Id$ + * @ingroup ServicesContainer + */ +class ilContainerStartObjectsPageConfig extends ilPageConfig +{ + /** + * Init + */ + public function init() + { + $this->setEnableInternalLinks(true); + $this->setIntLinkHelpDefaultType("RepositoryItem"); + $this->setEnablePCType("FileList", false); + $this->setEnablePCType("Map", true); + $this->setEnablePCType("Resources", false); + $this->setMultiLangSupport(false); + $this->setSinglePageMode(true); + } +} diff --git a/Services/Container/classes/class.ilContainerStartObjectsPageGUI.php b/Services/Container/classes/class.ilContainerStartObjectsPageGUI.php index e98c94ce2a5018ba273002621926f88f79b9a980..6ae824a89a458a713725e94dcbfb02f6832ec883 100644 --- a/Services/Container/classes/class.ilContainerStartObjectsPageGUI.php +++ b/Services/Container/classes/class.ilContainerStartObjectsPageGUI.php @@ -1,30 +1,28 @@ - - * - * @ilCtrl_Calls ilContainerStartObjectsPageGUI: ilPageEditorGUI, ilEditClipboardGUI, ilMDEditorGUI - * @ilCtrl_Calls ilContainerStartObjectsPageGUI: ilPublicUserProfileGUI, ilNoteGUI - * @ilCtrl_Calls ilContainerStartObjectsPageGUI: ilPropertyFormGUI, ilInternalLinkGUI, ilPageMultiLangGUI - * - * @ingroup ServicesContainer - */ -class ilContainerStartObjectsPageGUI extends ilPageObjectGUI -{ - /** - * Constructor - */ - function __construct($a_id = 0, $a_old_nr = 0, $a_lang = "") - { - parent::__construct("cstr", $a_id, $a_old_nr, false, $a_lang); - } - -} -?> + + * + * @ilCtrl_Calls ilContainerStartObjectsPageGUI: ilPageEditorGUI, ilEditClipboardGUI, ilMDEditorGUI + * @ilCtrl_Calls ilContainerStartObjectsPageGUI: ilPublicUserProfileGUI, ilNoteGUI + * @ilCtrl_Calls ilContainerStartObjectsPageGUI: ilPropertyFormGUI, ilInternalLinkGUI, ilPageMultiLangGUI + * + * @ingroup ServicesContainer + */ +class ilContainerStartObjectsPageGUI extends ilPageObjectGUI +{ + /** + * Constructor + */ + public function __construct($a_id = 0, $a_old_nr = 0, $a_lang = "") + { + parent::__construct("cstr", $a_id, $a_old_nr, false, $a_lang); + } +} diff --git a/Services/Container/classes/class.ilContainerStartObjectsTableGUI.php b/Services/Container/classes/class.ilContainerStartObjectsTableGUI.php index a40cecfc8299a0f682b4b7de9077d2536151836a..8b3572f17c1ff683301711bd06932fc2fec010f3 100644 --- a/Services/Container/classes/class.ilContainerStartObjectsTableGUI.php +++ b/Services/Container/classes/class.ilContainerStartObjectsTableGUI.php @@ -1,153 +1,141 @@ - - * @version $Id$ - * - * @ingroup ServicesContainer - */ -class ilContainerStartObjectsTableGUI extends ilTable2GUI -{ - /** - * @var ilCtrl - */ - protected $ctrl; +language(); - $ilCtrl = $DIC->ctrl(); - - $this->lng = $lng; - $this->ctrl = $ilCtrl; - $this->lng->loadLanguageModule('crs'); - - $this->start_obj = $a_start_objects; - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->addColumn('','', 1); - - if($a_parent_cmd == 'listStructure') - { - $this->addColumn($this->lng->txt('cntr_ordering'),'pos', '5%'); - } - - $this->addColumn($this->lng->txt('type'),'type', 1); - $this->addColumn($this->lng->txt('title'),'title'); - $this->addColumn($this->lng->txt('description'),'description'); - - // add - if($a_parent_cmd != 'listStructure') - { - $this->setTitle($this->lng->txt('crs_select_starter')); - $this->addMultiCommand('addStarter', $this->lng->txt('crs_add_starter')); - $this->addCommandButton('listStructure', $this->lng->txt('cancel')); - - $this->setDefaultOrderField('title'); - $this->setDefaultOrderDirection('asc'); - } - // list - else - { - $this->setTitle($this->lng->txt('crs_start_objects')); - $this->addMultiCommand('askDeleteStarter', $this->lng->txt('remove')); - $this->addCommandButton('saveSorting', $this->lng->txt('sorting_save')); - - $this->setDefaultOrderField('pos'); - $this->setDefaultOrderDirection('asc'); - } - - $this->setRowTemplate("tpl.start_objects_row.html", "Services/Container"); - $this->setFormAction($this->ctrl->getFormAction($a_parent_obj)); - $this->setSelectAllCheckbox('starter'); - - $data = array(); - - // add - if($a_parent_cmd != 'listStructure') - { - $data = $this->getPossibleObjects(); - } - // list - else - { - $data = $this->getStartObjects(); - } - - $this->setData($data); - } - - protected function getPossibleObjects() - { - $data = array(); - foreach($this->start_obj->getPossibleStarters() as $item_ref_id) - { - $tmp_obj = ilObjectFactory::getInstanceByRefId($item_ref_id); - - $data[$item_ref_id]['id'] = $item_ref_id; - $data[$item_ref_id]['title'] = $tmp_obj->getTitle(); - $data[$item_ref_id]['type'] = $this->lng->txt('obj_'.$tmp_obj->getType()); - $data[$item_ref_id]['icon'] = ilObject::_getIcon($tmp_obj->getId(), 'tiny'); - - if(strlen($tmp_obj->getDescription())) - { - $data[$item_ref_id]['description'] = $tmp_obj->getDescription(); - } - } - - return $data; - } - - protected function getStartObjects() - { - $data = array(); - $counter = 0; - foreach($this->start_obj->getStartObjects() as $start_id => $item) - { - $tmp_obj = ilObjectFactory::getInstanceByRefId($item['item_ref_id']); - - $data[$item['item_ref_id']]['id'] = $start_id; - $data[$item['item_ref_id']]['title'] = $tmp_obj->getTitle(); - $data[$item['item_ref_id']]['type'] = $this->lng->txt('obj_'.$tmp_obj->getType()); - $data[$item['item_ref_id']]['icon'] = ilObject::_getIcon($tmp_obj->getId(), 'tiny'); - - $counter += 10; - $data[$item['item_ref_id']]['pos'] = $counter; - - if(strlen($tmp_obj->getDescription())) - { - $data[$item['item_ref_id']]['description'] = $tmp_obj->getDescription(); - } - } - - return $data; - } - - public function fillRow($a_set) - { - if($this->getParentCmd() == 'listStructure') - { - $this->tpl->setCurrentBlock('pos_bl'); - $this->tpl->setVariable("POS_ID", $a_set["id"]); - $this->tpl->setVariable("POS", $a_set["pos"]); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setVariable("ID", $a_set["id"]); - $this->tpl->setVariable("TXT_TITLE", $a_set["title"]); - $this->tpl->setVariable("TXT_DESCRIPTION", $a_set["description"]); - $this->tpl->setVariable("ICON_SRC", $a_set["icon"]); - $this->tpl->setVariable("ICON_ALT", $a_set["type"]); - } -} - -?> \ No newline at end of file +/** + * ilContainerStartObjectsTableGUI + * @author Jörg Lützenkirchen + * @version $Id$ + * + * @ingroup ServicesContainer + */ +class ilContainerStartObjectsTableGUI extends ilTable2GUI +{ + /** + * @var ilCtrl + */ + protected $ctrl; + + protected $start_obj; // [ilContainerStartObjects] + + public function __construct($a_parent_obj, $a_parent_cmd, ilContainerStartObjects $a_start_objects) + { + global $DIC; + + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + + $this->lng = $lng; + $this->ctrl = $ilCtrl; + $this->lng->loadLanguageModule('crs'); + + $this->start_obj = $a_start_objects; + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->addColumn('', '', 1); + + if ($a_parent_cmd == 'listStructure') { + $this->addColumn($this->lng->txt('cntr_ordering'), 'pos', '5%'); + } + + $this->addColumn($this->lng->txt('type'), 'type', 1); + $this->addColumn($this->lng->txt('title'), 'title'); + $this->addColumn($this->lng->txt('description'), 'description'); + + // add + if ($a_parent_cmd != 'listStructure') { + $this->setTitle($this->lng->txt('crs_select_starter')); + $this->addMultiCommand('addStarter', $this->lng->txt('crs_add_starter')); + $this->addCommandButton('listStructure', $this->lng->txt('cancel')); + + $this->setDefaultOrderField('title'); + $this->setDefaultOrderDirection('asc'); + } + // list + else { + $this->setTitle($this->lng->txt('crs_start_objects')); + $this->addMultiCommand('askDeleteStarter', $this->lng->txt('remove')); + $this->addCommandButton('saveSorting', $this->lng->txt('sorting_save')); + + $this->setDefaultOrderField('pos'); + $this->setDefaultOrderDirection('asc'); + } + + $this->setRowTemplate("tpl.start_objects_row.html", "Services/Container"); + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj)); + $this->setSelectAllCheckbox('starter'); + + $data = array(); + + // add + if ($a_parent_cmd != 'listStructure') { + $data = $this->getPossibleObjects(); + } + // list + else { + $data = $this->getStartObjects(); + } + + $this->setData($data); + } + + protected function getPossibleObjects() + { + $data = array(); + foreach ($this->start_obj->getPossibleStarters() as $item_ref_id) { + $tmp_obj = ilObjectFactory::getInstanceByRefId($item_ref_id); + + $data[$item_ref_id]['id'] = $item_ref_id; + $data[$item_ref_id]['title'] = $tmp_obj->getTitle(); + $data[$item_ref_id]['type'] = $this->lng->txt('obj_' . $tmp_obj->getType()); + $data[$item_ref_id]['icon'] = ilObject::_getIcon($tmp_obj->getId(), 'tiny'); + + if (strlen($tmp_obj->getDescription())) { + $data[$item_ref_id]['description'] = $tmp_obj->getDescription(); + } + } + + return $data; + } + + protected function getStartObjects() + { + $data = array(); + $counter = 0; + foreach ($this->start_obj->getStartObjects() as $start_id => $item) { + $tmp_obj = ilObjectFactory::getInstanceByRefId($item['item_ref_id']); + + $data[$item['item_ref_id']]['id'] = $start_id; + $data[$item['item_ref_id']]['title'] = $tmp_obj->getTitle(); + $data[$item['item_ref_id']]['type'] = $this->lng->txt('obj_' . $tmp_obj->getType()); + $data[$item['item_ref_id']]['icon'] = ilObject::_getIcon($tmp_obj->getId(), 'tiny'); + + $counter += 10; + $data[$item['item_ref_id']]['pos'] = $counter; + + if (strlen($tmp_obj->getDescription())) { + $data[$item['item_ref_id']]['description'] = $tmp_obj->getDescription(); + } + } + + return $data; + } + + public function fillRow($a_set) + { + if ($this->getParentCmd() == 'listStructure') { + $this->tpl->setCurrentBlock('pos_bl'); + $this->tpl->setVariable("POS_ID", $a_set["id"]); + $this->tpl->setVariable("POS", $a_set["pos"]); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setVariable("ID", $a_set["id"]); + $this->tpl->setVariable("TXT_TITLE", $a_set["title"]); + $this->tpl->setVariable("TXT_DESCRIPTION", $a_set["description"]); + $this->tpl->setVariable("ICON_SRC", $a_set["icon"]); + $this->tpl->setVariable("ICON_ALT", $a_set["type"]); + } +} diff --git a/Services/Container/classes/class.ilContainerXmlParser.php b/Services/Container/classes/class.ilContainerXmlParser.php index ac9715e616ed91e8827427146646c576db2e429f..020d25a82aa43e68f5682da6b60766f1f6565714 100644 --- a/Services/Container/classes/class.ilContainerXmlParser.php +++ b/Services/Container/classes/class.ilContainerXmlParser.php @@ -13,240 +13,225 @@ include_once './Services/Export/classes/class.ilExportOptions.php'; */ class ilContainerXmlParser { - /** - * @var ilSetting - */ - protected $settings; - - /** - * @var ilObjectDefinition - */ - protected $obj_definition; - - /** - * @var ilLogger - */ - protected $cont_log; - - private $source = 0; - private $mapping = null; - private $xml = ''; - - private $sxml = null; - private $root_id = 0; - - static public $style_map = array(); - - /** - * Constructor - */ - public function __construct(ilImportMapping $mapping,$xml = '') - { - global $DIC; - - $this->settings = $DIC->settings(); - $this->obj_definition = $DIC["objDefinition"]; - $this->mapping = $mapping; - $this->xml = $xml; - $this->cont_log = ilLoggerFactory::getLogger('cont'); - } - - /** - * Get ilImportMapping object - * - * @return ilImportMapping $map - */ - public function getMapping() - { - return $this->mapping; - } - - public function parse($a_root_id) - { - $this->sxml = simplexml_load_string($this->xml); - $this->root_id = $a_root_id; - - foreach($this->sxml->Item as $item) - { - $this->initItem($item,$this->mapping->getTargetId()); - } - } - - /** - * Init Item - * @param object $item - * @param object $a_parent_node - * @return - */ - protected function initItem($item, $a_parent_node) - { - $ilSetting = $this->settings; - - $title = (string) $item['Title']; - $ref_id = (string) $item['RefId']; - $obj_id = (string) $item['Id']; - $type = (string) $item['Type']; - - - $new_ref = $this->getMapping()->getMapping('Services/Container', 'refs', $ref_id); - - if( - !$new_ref && - ($obj_id == $this->root_id) - ) - { - // if container without subitems a dummy container has already been created - // see ilImportContainer::createDummy() - $new_ref = $this->mapping->getMapping('Services/Container', 'refs', 0); - - // see below and ilContainerImporter::finalProcessing() - $this->mapping->addMapping('Services/Container','objs', $obj_id, ilObject::_lookupObjId($new_ref)); - } - - if(!$new_ref) - { - $new_ref = $this->createObject($ref_id,$obj_id,$type,$title,$a_parent_node); - } - - // Course item information - foreach($item->Timing as $timing) - { - $this->parseTiming($new_ref,$a_parent_node,$timing); - } - - foreach($item->Item as $subitem) - { - $this->initItem($subitem, $new_ref); - } - - $new_obj_id = $this->mapping->getMapping('Services/Container', 'objs', $obj_id); - - // style - if((int)$item['Style']) - { - self::$style_map[(int)$item['Style']][] = $new_obj_id; - } - - // pages - if($ilSetting->get('enable_cat_page_edit', false)) - { - if($item['Page'] == "1") - { - $this->mapping->addMapping('Services/COPage', 'pg', 'cont:'.$obj_id, 'cont:'.$new_obj_id); - $this->cont_log->debug("add pg cont mapping, old: ".$obj_id.", new: ".$new_obj_id.", Page: -".$item['Page']."-"); - } - - if($item['StartPage'] == "1") - { - $this->mapping->addMapping('Services/COPage', 'pg', 'cstr:'.$obj_id, 'cstr:'.$new_obj_id); - } - } - } - - /** - * Parse timing info - * @param object $a_ref_id - * @param object $a_parent_id - * @param object $timing - * @return - */ - protected function parseTiming($a_ref_id,$a_parent_id,$timing) - { - $type = (string) $timing['Type']; - $visible = (string) $timing['Visible']; - $changeable = (string) $timing['Changeable']; - - include_once './Services/Object/classes/class.ilObjectActivation.php'; - $crs_item = new ilObjectActivation(); - $crs_item->setTimingType($type); - $crs_item->toggleVisible((bool) $visible); - $crs_item->toggleChangeable((bool) $changeable); - - foreach($timing->children() as $sub) - { - switch((string) $sub->getName()) - { - case 'Start': - $dt = new ilDateTime((string) $sub,IL_CAL_DATETIME,ilTimeZone::UTC); - $crs_item->setTimingStart($dt->get(IL_CAL_UNIX)); - break; - - case 'End': - $dt = new ilDateTime((string) $sub,IL_CAL_DATETIME,ilTimeZone::UTC); - $crs_item->setTimingEnd($dt->get(IL_CAL_UNIX)); - break; - - case 'SuggestionStart': - $dt = new ilDateTime((string) $sub,IL_CAL_DATETIME,ilTimeZone::UTC); - $crs_item->setSuggestionStart($dt->get(IL_CAL_UNIX)); - break; - - case 'SuggestionEnd': - $dt = new ilDateTime((string) $sub,IL_CAL_DATETIME,ilTimeZone::UTC); - $crs_item->setSuggestionEnd($dt->get(IL_CAL_UNIX)); - break; - - case 'EarliestStart': - $dt = new ilDateTime((string) $sub,IL_CAL_DATETIME,ilTimeZone::UTC); - $crs_item->setEarliestStart($dt->get(IL_CAL_UNIX)); - break; - - case 'LatestEnd': - break; - } - } - - - if($crs_item->getTimingStart()) - { - $crs_item->update($a_ref_id, $a_parent_id); - } - } - - /** - * Create the objects - * @param object $ref_id - * @param object $obj_id - * @param object $type - * @param object $title - * @param object $parent_node - * @return - */ - protected function createObject($ref_id,$obj_id,$type,$title,$parent_node) - { - $objDefinition = $this->obj_definition; - - // A mapping for this object already exists => create reference - $new_obj_id = $this->getMapping()->getMapping('Services/Container', 'objs', $obj_id); - if($new_obj_id) - { - include_once './Services/Object/classes/class.ilObjectFactory.php'; - $obj = ilObjectFactory::getInstanceByObjId($new_obj_id,false); - if($obj instanceof ilObject) - { - $obj->createReference(); - $obj->putInTree($parent_node); - $obj->setPermissions($parent_node); - $this->mapping->addMapping('Services/Container','refs',$ref_id,$obj->getRefId()); - return $obj->getRefId(); - } - } - - $class_name = "ilObj".$objDefinition->getClassName($type); - $location = $objDefinition->getLocation($type); - - include_once($location."/class.".$class_name.".php"); - $new = new $class_name(); - $new->setTitle($title); - $new->create(true); - $new->createReference(); - $new->putInTree($parent_node); - $new->setPermissions($parent_node); - - $this->mapping->addMapping('Services/Container','objs', $obj_id, $new->getId()); - $this->mapping->addMapping('Services/Container','refs',$ref_id,$new->getRefId()); - - return $new->getRefId(); - } + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var ilObjectDefinition + */ + protected $obj_definition; + + /** + * @var ilLogger + */ + protected $cont_log; + + private $source = 0; + private $mapping = null; + private $xml = ''; + + private $sxml = null; + private $root_id = 0; + + public static $style_map = array(); + + /** + * Constructor + */ + public function __construct(ilImportMapping $mapping, $xml = '') + { + global $DIC; + + $this->settings = $DIC->settings(); + $this->obj_definition = $DIC["objDefinition"]; + $this->mapping = $mapping; + $this->xml = $xml; + $this->cont_log = ilLoggerFactory::getLogger('cont'); + } + + /** + * Get ilImportMapping object + * + * @return ilImportMapping $map + */ + public function getMapping() + { + return $this->mapping; + } + + public function parse($a_root_id) + { + $this->sxml = simplexml_load_string($this->xml); + $this->root_id = $a_root_id; + + foreach ($this->sxml->Item as $item) { + $this->initItem($item, $this->mapping->getTargetId()); + } + } + + /** + * Init Item + * @param object $item + * @param object $a_parent_node + * @return + */ + protected function initItem($item, $a_parent_node) + { + $ilSetting = $this->settings; + + $title = (string) $item['Title']; + $ref_id = (string) $item['RefId']; + $obj_id = (string) $item['Id']; + $type = (string) $item['Type']; + + + $new_ref = $this->getMapping()->getMapping('Services/Container', 'refs', $ref_id); + + if ( + !$new_ref && + ($obj_id == $this->root_id) + ) { + // if container without subitems a dummy container has already been created + // see ilImportContainer::createDummy() + $new_ref = $this->mapping->getMapping('Services/Container', 'refs', 0); + + // see below and ilContainerImporter::finalProcessing() + $this->mapping->addMapping('Services/Container', 'objs', $obj_id, ilObject::_lookupObjId($new_ref)); + } + + if (!$new_ref) { + $new_ref = $this->createObject($ref_id, $obj_id, $type, $title, $a_parent_node); + } + + // Course item information + foreach ($item->Timing as $timing) { + $this->parseTiming($new_ref, $a_parent_node, $timing); + } + + foreach ($item->Item as $subitem) { + $this->initItem($subitem, $new_ref); + } + + $new_obj_id = $this->mapping->getMapping('Services/Container', 'objs', $obj_id); + + // style + if ((int) $item['Style']) { + self::$style_map[(int) $item['Style']][] = $new_obj_id; + } + + // pages + if ($ilSetting->get('enable_cat_page_edit', false)) { + if ($item['Page'] == "1") { + $this->mapping->addMapping('Services/COPage', 'pg', 'cont:' . $obj_id, 'cont:' . $new_obj_id); + $this->cont_log->debug("add pg cont mapping, old: " . $obj_id . ", new: " . $new_obj_id . ", Page: -" . $item['Page'] . "-"); + } + + if ($item['StartPage'] == "1") { + $this->mapping->addMapping('Services/COPage', 'pg', 'cstr:' . $obj_id, 'cstr:' . $new_obj_id); + } + } + } + + /** + * Parse timing info + * @param object $a_ref_id + * @param object $a_parent_id + * @param object $timing + * @return + */ + protected function parseTiming($a_ref_id, $a_parent_id, $timing) + { + $type = (string) $timing['Type']; + $visible = (string) $timing['Visible']; + $changeable = (string) $timing['Changeable']; + + include_once './Services/Object/classes/class.ilObjectActivation.php'; + $crs_item = new ilObjectActivation(); + $crs_item->setTimingType($type); + $crs_item->toggleVisible((bool) $visible); + $crs_item->toggleChangeable((bool) $changeable); + + foreach ($timing->children() as $sub) { + switch ((string) $sub->getName()) { + case 'Start': + $dt = new ilDateTime((string) $sub, IL_CAL_DATETIME, ilTimeZone::UTC); + $crs_item->setTimingStart($dt->get(IL_CAL_UNIX)); + break; + + case 'End': + $dt = new ilDateTime((string) $sub, IL_CAL_DATETIME, ilTimeZone::UTC); + $crs_item->setTimingEnd($dt->get(IL_CAL_UNIX)); + break; + + case 'SuggestionStart': + $dt = new ilDateTime((string) $sub, IL_CAL_DATETIME, ilTimeZone::UTC); + $crs_item->setSuggestionStart($dt->get(IL_CAL_UNIX)); + break; + + case 'SuggestionEnd': + $dt = new ilDateTime((string) $sub, IL_CAL_DATETIME, ilTimeZone::UTC); + $crs_item->setSuggestionEnd($dt->get(IL_CAL_UNIX)); + break; + + case 'EarliestStart': + $dt = new ilDateTime((string) $sub, IL_CAL_DATETIME, ilTimeZone::UTC); + $crs_item->setEarliestStart($dt->get(IL_CAL_UNIX)); + break; + + case 'LatestEnd': + break; + } + } + + + if ($crs_item->getTimingStart()) { + $crs_item->update($a_ref_id, $a_parent_id); + } + } + + /** + * Create the objects + * @param object $ref_id + * @param object $obj_id + * @param object $type + * @param object $title + * @param object $parent_node + * @return + */ + protected function createObject($ref_id, $obj_id, $type, $title, $parent_node) + { + $objDefinition = $this->obj_definition; + + // A mapping for this object already exists => create reference + $new_obj_id = $this->getMapping()->getMapping('Services/Container', 'objs', $obj_id); + if ($new_obj_id) { + include_once './Services/Object/classes/class.ilObjectFactory.php'; + $obj = ilObjectFactory::getInstanceByObjId($new_obj_id, false); + if ($obj instanceof ilObject) { + $obj->createReference(); + $obj->putInTree($parent_node); + $obj->setPermissions($parent_node); + $this->mapping->addMapping('Services/Container', 'refs', $ref_id, $obj->getRefId()); + return $obj->getRefId(); + } + } + + $class_name = "ilObj" . $objDefinition->getClassName($type); + $location = $objDefinition->getLocation($type); + + include_once($location . "/class." . $class_name . ".php"); + $new = new $class_name(); + $new->setTitle($title); + $new->create(true); + $new->createReference(); + $new->putInTree($parent_node); + $new->setPermissions($parent_node); + + $this->mapping->addMapping('Services/Container', 'objs', $obj_id, $new->getId()); + $this->mapping->addMapping('Services/Container', 'refs', $ref_id, $new->getRefId()); + + return $new->getRefId(); + } } -?> \ No newline at end of file diff --git a/Services/Container/classes/class.ilContainerXmlWriter.php b/Services/Container/classes/class.ilContainerXmlWriter.php index b66f35e784c020d52ace0dbd7a2f8732102b270b..a18392a3a6d46ea422a125794f475b166561c4f4 100644 --- a/Services/Container/classes/class.ilContainerXmlWriter.php +++ b/Services/Container/classes/class.ilContainerXmlWriter.php @@ -14,153 +14,140 @@ include_once './Services/Export/classes/class.ilExportOptions.php'; */ class ilContainerXmlWriter extends ilXmlWriter { - /** - * @var ilTree - */ - protected $tree; + /** + * @var ilTree + */ + protected $tree; - protected $exp_options = null; - private $source = 0; + protected $exp_options = null; + private $source = 0; - /** - * Constructor - */ - public function __construct($a_ref_id) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_ref_id) + { + global $DIC; - $this->tree = $DIC->repositoryTree(); - parent::__construct(); - $this->source = $a_ref_id; - $this->exp_options = ilExportOptions::getInstance(); - - } - - /** - * Write XML - * @return - * @throws UnexpectedValueException Thrown if obj_id is not of type webr or no obj_id is given - */ - public function write() - { - $this->xmlStartTag('Items'); - $this->writeSubitems($this->source); - $this->xmlEndTag('Items'); - } - - /** - * Write tree childs - * Recursive method - * @param object $a_ref_id - * @return - */ - protected function writeSubitems($a_ref_id) - { - $tree = $this->tree; - - // because of the co-page-stuff (incl. styles) we also need to process the container itself - if($a_ref_id != $this->source) - { - $mode = $this->exp_options->getOptionByRefId($a_ref_id, ilExportOptions::KEY_ITEM_MODE); - if($mode == NULL or $mode == ilExportOptions::EXPORT_OMIT) - { - return false; - } - } + $this->tree = $DIC->repositoryTree(); + parent::__construct(); + $this->source = $a_ref_id; + $this->exp_options = ilExportOptions::getInstance(); + } + + /** + * Write XML + * @return + * @throws UnexpectedValueException Thrown if obj_id is not of type webr or no obj_id is given + */ + public function write() + { + $this->xmlStartTag('Items'); + $this->writeSubitems($this->source); + $this->xmlEndTag('Items'); + } + + /** + * Write tree childs + * Recursive method + * @param object $a_ref_id + * @return + */ + protected function writeSubitems($a_ref_id) + { + $tree = $this->tree; + + // because of the co-page-stuff (incl. styles) we also need to process the container itself + if ($a_ref_id != $this->source) { + $mode = $this->exp_options->getOptionByRefId($a_ref_id, ilExportOptions::KEY_ITEM_MODE); + if ($mode == null or $mode == ilExportOptions::EXPORT_OMIT) { + return false; + } + } - $obj_id = ilObject::_lookupObjId($a_ref_id); - - include_once('./Services/Container/classes/class.ilContainerPage.php'); - include_once('./Services/Container/classes/class.ilContainerStartObjectsPage.php'); - include_once('./Services/Style/Content/classes/class.ilObjStyleSheet.php'); - - $this->xmlStartTag( - 'Item', - array( - 'RefId' => $a_ref_id, - 'Id' => $obj_id, - 'Title' => ilObject::_lookupTitle($obj_id), - 'Type' => ilObject::_lookupType($obj_id), - 'Page' => ilContainerPage::_exists('cont', $obj_id), - 'StartPage' => ilContainerStartObjectsPage::_exists('cstr', $obj_id), - 'Style' => ilObjStyleSheet::lookupObjectStyle($obj_id) - ) - ); - - $this->writeCourseItemInformation($a_ref_id); - - foreach($tree->getChilds($a_ref_id) as $node) - { - $this->writeSubitems($node['child']); - } - - $this->xmlEndTag('Item'); - return true; - } - - - /** - * Write course item information - * Starting time, ending time... - * @param int $a_ref_id - * @return - */ - protected function writeCourseItemInformation($a_ref_id) - { - include_once './Services/Object/classes/class.ilObjectActivation.php'; - $item = ilObjectActivation::getItem($a_ref_id); - - $this->xmlStartTag( - 'Timing', - array( - 'Type' => $item['timing_type'], - 'Visible' => $item['visible'], - 'Changeable'=> $item['changeable'], - ) - ); - if($item['timing_start']) - { - $tmp_date = new ilDateTime($item['timing_start'],IL_CAL_UNIX); - $this->xmlElement('Start',array(),$tmp_date->get(IL_CAL_DATETIME,'',ilTimeZone::UTC)); - } - if($item['timing_end']) - { - $tmp_date = new ilDateTime($item['timing_end'],IL_CAL_UNIX); - $this->xmlElement('End',array(),$tmp_date->get(IL_CAL_DATETIME,'',ilTimeZone::UTC)); - } - if($item['suggestion_start']) - { - $tmp_date = new ilDateTime($item['suggestion_start'],IL_CAL_UNIX); - $this->xmlElement('SuggestionStart',array(),$tmp_date->get(IL_CAL_DATETIME,'',ilTimeZone::UTC)); - } - if($item['suggestion_end']) - { - $tmp_date = new ilDateTime($item['suggestion_end'],IL_CAL_UNIX); - $this->xmlElement('SuggestionEnd',array(),$tmp_date->get(IL_CAL_DATETIME,'',ilTimeZone::UTC)); - } - if($item['earliest_start']) - { - $tmp_date = new ilDateTime($item['earliest_start'],IL_CAL_UNIX); - $this->xmlElement('EarliestStart',array(),$tmp_date->get(IL_CAL_DATETIME,'',ilTimeZone::UTC)); - } + $obj_id = ilObject::_lookupObjId($a_ref_id); + + include_once('./Services/Container/classes/class.ilContainerPage.php'); + include_once('./Services/Container/classes/class.ilContainerStartObjectsPage.php'); + include_once('./Services/Style/Content/classes/class.ilObjStyleSheet.php'); + + $this->xmlStartTag( + 'Item', + array( + 'RefId' => $a_ref_id, + 'Id' => $obj_id, + 'Title' => ilObject::_lookupTitle($obj_id), + 'Type' => ilObject::_lookupType($obj_id), + 'Page' => ilContainerPage::_exists('cont', $obj_id), + 'StartPage' => ilContainerStartObjectsPage::_exists('cstr', $obj_id), + 'Style' => ilObjStyleSheet::lookupObjectStyle($obj_id) + ) + ); + + $this->writeCourseItemInformation($a_ref_id); + + foreach ($tree->getChilds($a_ref_id) as $node) { + $this->writeSubitems($node['child']); + } + + $this->xmlEndTag('Item'); + return true; + } + + + /** + * Write course item information + * Starting time, ending time... + * @param int $a_ref_id + * @return + */ + protected function writeCourseItemInformation($a_ref_id) + { + include_once './Services/Object/classes/class.ilObjectActivation.php'; + $item = ilObjectActivation::getItem($a_ref_id); + + $this->xmlStartTag( + 'Timing', + array( + 'Type' => $item['timing_type'], + 'Visible' => $item['visible'], + 'Changeable'=> $item['changeable'], + ) + ); + if ($item['timing_start']) { + $tmp_date = new ilDateTime($item['timing_start'], IL_CAL_UNIX); + $this->xmlElement('Start', array(), $tmp_date->get(IL_CAL_DATETIME, '', ilTimeZone::UTC)); + } + if ($item['timing_end']) { + $tmp_date = new ilDateTime($item['timing_end'], IL_CAL_UNIX); + $this->xmlElement('End', array(), $tmp_date->get(IL_CAL_DATETIME, '', ilTimeZone::UTC)); + } + if ($item['suggestion_start']) { + $tmp_date = new ilDateTime($item['suggestion_start'], IL_CAL_UNIX); + $this->xmlElement('SuggestionStart', array(), $tmp_date->get(IL_CAL_DATETIME, '', ilTimeZone::UTC)); + } + if ($item['suggestion_end']) { + $tmp_date = new ilDateTime($item['suggestion_end'], IL_CAL_UNIX); + $this->xmlElement('SuggestionEnd', array(), $tmp_date->get(IL_CAL_DATETIME, '', ilTimeZone::UTC)); + } + if ($item['earliest_start']) { + $tmp_date = new ilDateTime($item['earliest_start'], IL_CAL_UNIX); + $this->xmlElement('EarliestStart', array(), $tmp_date->get(IL_CAL_DATETIME, '', ilTimeZone::UTC)); + } - $this->xmlEndTag('Timing'); - - } - - /** - * Build XML header - * @return - */ - protected function buildHeader() - { - $this->xmlSetDtdDef(""); - $this->xmlSetGenCmt("Container object"); - $this->xmlHeader(); + $this->xmlEndTag('Timing'); + } + + /** + * Build XML header + * @return + */ + protected function buildHeader() + { + $this->xmlSetDtdDef(""); + $this->xmlSetGenCmt("Container object"); + $this->xmlHeader(); - return true; - } - - + return true; + } } -?> \ No newline at end of file diff --git a/Services/Container/classes/class.ilMemberViewGUI.php b/Services/Container/classes/class.ilMemberViewGUI.php index ea67c6fb3763638c805b75587aad4638c0c5d376..43de7e7ef419aacb4459a3b57674d9cc5b0ee3cc 100644 --- a/Services/Container/classes/class.ilMemberViewGUI.php +++ b/Services/Container/classes/class.ilMemberViewGUI.php @@ -1,24 +1,24 @@ access(); - $ilCtrl = $DIC->ctrl(); - - $settings = ilMemberViewSettings::getInstance(); - if(!$settings->isEnabled()) - { - return false; - } - global $DIC; + $ilAccess = $DIC->access(); + $ilCtrl = $DIC->ctrl(); + + $settings = ilMemberViewSettings::getInstance(); + if (!$settings->isEnabled()) { + return false; + } + global $DIC; - $tpl = $DIC["tpl"]; - $tree = $DIC->repositoryTree(); - $lng = $DIC->language(); - $ilTabs = $DIC->tabs(); - - // No course or group in path => aborting - if(!$tree->checkForParentType($a_ref_id, 'crs') and - !$tree->checkForParentType($a_ref_id, 'grp')) - { - return false; - } - - // TODO: check edit_permission - - $active = $settings->isActive(); - - $type = ilObject::_lookupType(ilObject::_lookupObjId($a_ref_id)); - if(($type == 'crs' or $type == 'grp') and $ilAccess->checkAccess('write','',$a_ref_id)) - { - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $a_ref_id); - $ilCtrl->setParameterByClass("ilrepositorygui", "mv", "1"); - $ilCtrl->setParameterByClass("ilrepositorygui", "set_mode", "flat"); - $ilTabs->addNonTabbedLink("members_view", - $lng->txt('mem_view_activate'), - $ilCtrl->getLinkTargetByClass("ilrepositorygui", "frameset") - ); - $ilCtrl->clearParametersByClass("ilrepositorygui"); - return true; - } - return true; - } + $tpl = $DIC["tpl"]; + $tree = $DIC->repositoryTree(); + $lng = $DIC->language(); + $ilTabs = $DIC->tabs(); + + // No course or group in path => aborting + if (!$tree->checkForParentType($a_ref_id, 'crs') and + !$tree->checkForParentType($a_ref_id, 'grp')) { + return false; + } + + // TODO: check edit_permission + + $active = $settings->isActive(); + + $type = ilObject::_lookupType(ilObject::_lookupObjId($a_ref_id)); + if (($type == 'crs' or $type == 'grp') and $ilAccess->checkAccess('write', '', $a_ref_id)) { + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $a_ref_id); + $ilCtrl->setParameterByClass("ilrepositorygui", "mv", "1"); + $ilCtrl->setParameterByClass("ilrepositorygui", "set_mode", "flat"); + $ilTabs->addNonTabbedLink( + "members_view", + $lng->txt('mem_view_activate'), + $ilCtrl->getLinkTargetByClass("ilrepositorygui", "frameset") + ); + $ilCtrl->clearParametersByClass("ilrepositorygui"); + return true; + } + return true; + } } diff --git a/Services/Container/classes/class.ilMemberViewSettings.php b/Services/Container/classes/class.ilMemberViewSettings.php index fdf9515f88cd942b3df843963c32aea2c812d5e2..bf9ed549d307756e26dd144c9b3a2993ea0fc809 100644 --- a/Services/Container/classes/class.ilMemberViewSettings.php +++ b/Services/Container/classes/class.ilMemberViewSettings.php @@ -1,78 +1,77 @@ - * + * */ class ilMemberViewSettings { - /** - * @var ilTree - */ - protected $tree; + /** + * @var ilTree + */ + protected $tree; - /** - * @var ilSetting - */ - protected $settings; + /** + * @var ilSetting + */ + protected $settings; - private static $instance = null; - - private $active = false; - private $enabled = false; - private $container = null; - private $container_items = array(); - - private $current_ref_id = 0; - - /** - * Constructor (singleton) - * @return - */ - private function __construct() - { - global $DIC; + private static $instance = null; + + private $active = false; + private $enabled = false; + private $container = null; + private $container_items = array(); + + private $current_ref_id = 0; + + /** + * Constructor (singleton) + * @return + */ + private function __construct() + { + global $DIC; - $this->tree = $DIC->repositoryTree(); - $this->settings = $DIC->settings(); - $this->read(); - } - - /** - * Get instance - * @return object ilMemberViewSettings - */ - public static function getInstance() - { - if(self::$instance != null) - { - return self::$instance; - } - return self::$instance = new ilMemberViewSettings(); - } - + $this->tree = $DIC->repositoryTree(); + $this->settings = $DIC->settings(); + $this->read(); + } + + /** + * Get instance + * @return object ilMemberViewSettings + */ + public static function getInstance() + { + if (self::$instance != null) { + return self::$instance; + } + return self::$instance = new ilMemberViewSettings(); + } + /** * Returns $container. * @see ilMemberView::$container @@ -81,15 +80,15 @@ class ilMemberViewSettings { return $this->container; } - - /** - * Get current ref_id of request - * @return type - */ - public function getCurrentRefId() - { - return $this->current_ref_id; - } + + /** + * Get current ref_id of request + * @return type + */ + public function getCurrentRefId() + { + return $this->current_ref_id; + } /** * Sets $container. @@ -99,152 +98,140 @@ class ilMemberViewSettings public function setContainer($container) { $this->container = $container; - $_SESSION['member_view_container'] = $this->container; - $_SESSION['il_cont_admin_panel'] = false; + $_SESSION['member_view_container'] = $this->container; + $_SESSION['il_cont_admin_panel'] = false; } - /** - * Check if member view currently enabled - * @return bool - */ - public function isActive() - { - $tree = $this->tree; - - if(!$this->active) - { - // Not active - return false; - } - + /** + * Check if member view currently enabled + * @return bool + */ + public function isActive() + { + $tree = $this->tree; + + if (!$this->active) { + // Not active + return false; + } + - if(!$this->getCurrentRefId()) - { - // No ref id given => mail, search, personal desktop menu in other tab - return false; - } - - if(!in_array($this->getCurrentRefId(),$this->container_items) and - $this->getContainer() != $this->getCurrentRefId()) - { - // outside of course - return false; - } - return true; - } - - /** - * Check if member view is currently enabled for given ref id - * @param int $a_ref_id - * @return bool - */ - public function isActiveForRefId($a_ref_id) - { - if(!$this->active || !(int)$a_ref_id) - { - // Not active - return false; - } - - if(!in_array($a_ref_id,$this->container_items) and - $this->getContainer() != $a_ref_id) - { - // outside of course - return false; - } - return true; - } - - /** - * Enable member view for this session and container. - * @return - * @param int $a_ref_id Reference Id of course or group - * @exception IllegalArgumentException Thrown if reference id is not a course or group - */ - public function activate($a_ref_id) - { - $this->active = true; - $this->setContainer($a_ref_id); - } - - /** - * Deactivate member view - * @return - */ - public function deactivate() - { - $this->active = false; - $this->container = null; - unset($_SESSION['member_view_container']); - } - - /** - * Toggle activation status - * @return - * @param int $a_ref_id - * @param bool $a_activation - */ - public function toggleActivation($a_ref_id,$a_activation) - { - if($a_activation) - { - return $this->activate($a_ref_id); - } - else - { - return $this->deactivate($a_ref_id); - } - } - - /** - * Check if members view is enabled in the administration - * @return bool active - */ - public function isEnabled() - { - return (bool) $this->enabled; - } - - /** - * Read settings - * @return void - */ - protected function read() - { - $ilSetting = $this->settings; - $tree = $this->tree; - - $this->findEffectiveRefId(); - - // member view is always enabled - // (2013-06-18, http://www.ilias.de/docu/goto_docu_wiki_1357_Reorganising_Administration.html) - - // $this->enabled = $ilSetting->get('preview_learner'); - $this->enabled = true; - - if(isset($_SESSION['member_view_container'])) - { - $this->active = true; - $this->container = (int) $_SESSION['member_view_container']; - $this->container_items = $tree->getSubTreeIds($this->getContainer()); - } - } - - /** - * Find effective ref_id for request - */ - protected function findEffectiveRefId() - { - if((int) $_GET['ref_id']) - { - return $this->current_ref_id = (int) $_GET['ref_id']; - } - - $target_arr = explode('_',(string) $_GET['target']); - if(isset($target_arr[1]) and (int) $target_arr[1]) - { - $this->current_ref_id = (int) $target_arr[1]; - } - } + if (!$this->getCurrentRefId()) { + // No ref id given => mail, search, personal desktop menu in other tab + return false; + } + + if (!in_array($this->getCurrentRefId(), $this->container_items) and + $this->getContainer() != $this->getCurrentRefId()) { + // outside of course + return false; + } + return true; + } + + /** + * Check if member view is currently enabled for given ref id + * @param int $a_ref_id + * @return bool + */ + public function isActiveForRefId($a_ref_id) + { + if (!$this->active || !(int) $a_ref_id) { + // Not active + return false; + } + + if (!in_array($a_ref_id, $this->container_items) and + $this->getContainer() != $a_ref_id) { + // outside of course + return false; + } + return true; + } + + /** + * Enable member view for this session and container. + * @return + * @param int $a_ref_id Reference Id of course or group + * @exception IllegalArgumentException Thrown if reference id is not a course or group + */ + public function activate($a_ref_id) + { + $this->active = true; + $this->setContainer($a_ref_id); + } + + /** + * Deactivate member view + * @return + */ + public function deactivate() + { + $this->active = false; + $this->container = null; + unset($_SESSION['member_view_container']); + } + + /** + * Toggle activation status + * @return + * @param int $a_ref_id + * @param bool $a_activation + */ + public function toggleActivation($a_ref_id, $a_activation) + { + if ($a_activation) { + return $this->activate($a_ref_id); + } else { + return $this->deactivate($a_ref_id); + } + } + + /** + * Check if members view is enabled in the administration + * @return bool active + */ + public function isEnabled() + { + return (bool) $this->enabled; + } + + /** + * Read settings + * @return void + */ + protected function read() + { + $ilSetting = $this->settings; + $tree = $this->tree; + + $this->findEffectiveRefId(); + + // member view is always enabled + // (2013-06-18, http://www.ilias.de/docu/goto_docu_wiki_1357_Reorganising_Administration.html) + + // $this->enabled = $ilSetting->get('preview_learner'); + $this->enabled = true; + + if (isset($_SESSION['member_view_container'])) { + $this->active = true; + $this->container = (int) $_SESSION['member_view_container']; + $this->container_items = $tree->getSubTreeIds($this->getContainer()); + } + } + + /** + * Find effective ref_id for request + */ + protected function findEffectiveRefId() + { + if ((int) $_GET['ref_id']) { + return $this->current_ref_id = (int) $_GET['ref_id']; + } + + $target_arr = explode('_', (string) $_GET['target']); + if (isset($target_arr[1]) and (int) $target_arr[1]) { + $this->current_ref_id = (int) $target_arr[1]; + } + } } -?> \ No newline at end of file diff --git a/Services/ContainerReference/classes/class.ilContainerReference.php b/Services/ContainerReference/classes/class.ilContainerReference.php index aa60ccd5577d0a59ae4326ffea26525e18907099..4dfd453c96d9f1c76107150f66911ddba548b073 100644 --- a/Services/ContainerReference/classes/class.ilContainerReference.php +++ b/Services/ContainerReference/classes/class.ilContainerReference.php @@ -1,398 +1,382 @@ * @version $Id$ -* * -* @ingroup ServicesContainerReference +* +* @ingroup ServicesContainerReference */ class ilContainerReference extends ilObject { - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - const TITLE_TYPE_REUSE = 1; - const TITLE_TYPE_CUSTOM = 2; - - protected $db = null; - protected $target_id = null; - protected $target_ref_id = null; - protected $title_type = self::TITLE_TYPE_REUSE; - - /** - * Constructor - * @param int $a_id reference id - * @param bool $a_call_by_reference - * @return void - */ - public function __construct($a_id = 0,$a_call_by_reference = true) - { - global $DIC; + const TITLE_TYPE_REUSE = 1; + const TITLE_TYPE_CUSTOM = 2; + + protected $db = null; + protected $target_id = null; + protected $target_ref_id = null; + protected $title_type = self::TITLE_TYPE_REUSE; + + /** + * Constructor + * @param int $a_id reference id + * @param bool $a_call_by_reference + * @return void + */ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + global $DIC; - $this->db = $DIC->database(); - $this->user = $DIC->user(); - $ilDB = $DIC->database(); + $this->db = $DIC->database(); + $this->user = $DIC->user(); + $ilDB = $DIC->database(); - parent::__construct($a_id,$a_call_by_reference); - } - - /** - * lookup target id - * - * @access public - * @param int $a_ref_id Course reference obj_id - * @return - * @static - */ - public static function _lookupTargetId($a_obj_id) - { - global $DIC; + parent::__construct($a_id, $a_call_by_reference); + } + + /** + * lookup target id + * + * @access public + * @param int $a_ref_id Course reference obj_id + * @return + * @static + */ + public static function _lookupTargetId($a_obj_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $query = "SELECT * FROM container_reference ". - "WHERE obj_id = ".$ilDB->quote($a_obj_id,'integer')." "; - $res = $ilDB->query($query); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - return $row->target_obj_id; - } - return $a_obj_id; - } - - /** - * Lookup target ref_id - * @param int $a_obj_id obj_id - * @return - * @static - */ - public static function _lookupTargetRefId($a_obj_id) - { - global $DIC; + $ilDB = $DIC->database(); + + $query = "SELECT * FROM container_reference " . + "WHERE obj_id = " . $ilDB->quote($a_obj_id, 'integer') . " "; + $res = $ilDB->query($query); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + return $row->target_obj_id; + } + return $a_obj_id; + } + + /** + * Lookup target ref_id + * @param int $a_obj_id obj_id + * @return + * @static + */ + public static function _lookupTargetRefId($a_obj_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $query = "SELECT ref_id FROM object_reference obr ". - "JOIN container_reference cr ON obr.obj_id = cr.target_obj_id ". - "WHERE cr.obj_id = ".$ilDB->quote($a_obj_id,'integer'); - $res = $ilDB->query($query); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - return $row->ref_id; - } - return false; - } - - /** - * Overwitten from base class - * @param int $a_obj_id - * @return - */ - public static function _lookupTitle($a_obj_id) - { - global $DIC; + $ilDB = $DIC->database(); + + $query = "SELECT ref_id FROM object_reference obr " . + "JOIN container_reference cr ON obr.obj_id = cr.target_obj_id " . + "WHERE cr.obj_id = " . $ilDB->quote($a_obj_id, 'integer'); + $res = $ilDB->query($query); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + return $row->ref_id; + } + return false; + } + + /** + * Overwitten from base class + * @param int $a_obj_id + * @return + */ + public static function _lookupTitle($a_obj_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $query = 'SELECT title,title_type FROM container_reference cr '. - 'JOIN object_data od ON cr.obj_id = od.obj_id '. - 'WHERE cr.obj_id = '.$ilDB->quote($a_obj_id,'integer'); - $res = $ilDB->query($query); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - if($row->title_type == ilContainerReference::TITLE_TYPE_CUSTOM) - { - return $row->title; - } - } - return ilContainerReference::_lookupTargetTitle($a_obj_id); - } - - /** - * Lookup target title - * - * @return string title - * @static - */ - public static function _lookupTargetTitle($a_obj_id) - { - global $DIC; + $ilDB = $DIC->database(); + + $query = 'SELECT title,title_type FROM container_reference cr ' . + 'JOIN object_data od ON cr.obj_id = od.obj_id ' . + 'WHERE cr.obj_id = ' . $ilDB->quote($a_obj_id, 'integer'); + $res = $ilDB->query($query); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + if ($row->title_type == ilContainerReference::TITLE_TYPE_CUSTOM) { + return $row->title; + } + } + return ilContainerReference::_lookupTargetTitle($a_obj_id); + } + + /** + * Lookup target title + * + * @return string title + * @static + */ + public static function _lookupTargetTitle($a_obj_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $query = "SELECT title FROM object_data od ". - "JOIN container_reference cr ON target_obj_id = od.obj_id ". - "WHERE cr.obj_id = ".$ilDB->quote($a_obj_id ,'integer'); - $res = $ilDB->query($query); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - return $row->title; - } - return ''; - } - - /** - * lookup source id - * - * @param int $a_target_id obj_id of course or category - * @return int obj_id of references - * @static - */ - public static function _lookupSourceId($a_target_id) - { - global $DIC; + $ilDB = $DIC->database(); + + $query = "SELECT title FROM object_data od " . + "JOIN container_reference cr ON target_obj_id = od.obj_id " . + "WHERE cr.obj_id = " . $ilDB->quote($a_obj_id, 'integer'); + $res = $ilDB->query($query); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + return $row->title; + } + return ''; + } + + /** + * lookup source id + * + * @param int $a_target_id obj_id of course or category + * @return int obj_id of references + * @static + */ + public static function _lookupSourceId($a_target_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $query = "SELECT * FROM container_reference ". - "WHERE target_obj_id = ".$ilDB->quote($a_target_id,'integer')." "; - $res = $ilDB->query($query); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - return $row->obj_id; - } - return false; - } - - /** - * Get ids of all container references that target the object with the - * given id. - * - * @param int $a_target_id obj_id of course or category - * @return int[] obj_ids of references - * @static - */ - public static function _lookupSourceIds($a_target_id) - { - global $DIC; + $ilDB = $DIC->database(); + + $query = "SELECT * FROM container_reference " . + "WHERE target_obj_id = " . $ilDB->quote($a_target_id, 'integer') . " "; + $res = $ilDB->query($query); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + return $row->obj_id; + } + return false; + } + + /** + * Get ids of all container references that target the object with the + * given id. + * + * @param int $a_target_id obj_id of course or category + * @return int[] obj_ids of references + * @static + */ + public static function _lookupSourceIds($a_target_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $query = "SELECT * FROM container_reference ". - "WHERE target_obj_id = ".$ilDB->quote($a_target_id,'integer')." "; - $res = $ilDB->query($query); - $ret = array(); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - $ret[] = $row->obj_id; - } - return $ret; - } - - /** - * get target id - * - * @access public - * @return - */ - public function getTargetId() - { - return $this->target_id; - } - - - /** - * set target id - * - * @access public - * @param int $a_target_id target id - * @return - */ - public function setTargetId($a_target_id) - { - $this->target_id = $a_target_id; - } - - /** - * set target ref_id - * - * @access public - * @param - * @return - */ - public function setTargetRefId($a_id) - { - $this->target_ref_id = $a_id; - } - - /** - * get Target ref_id - * - * @access public - * @param - * @return - */ - public function getTargetRefId() - { - return $this->target_ref_id; - } - - /** - * get title type - * @return type - */ - public function getTitleType() - { - return $this->title_type; - } - - /** - * Set title type - * @param type $type - */ - public function setTitleType($type) - { - $this->title_type = $type; - } - - /** - * read - * - * @access public - * @return - */ - public function read() - { - $ilDB = $this->db; - - parent::read(); - - $query = "SELECT * FROM container_reference ". - "WHERE obj_id = ".$ilDB->quote($this->getId(),'integer')." "; - $res = $ilDB->query($query); - - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - $this->setTargetId($row->target_obj_id); - $this->setTitleType($row->title_type); - } - $ref_ids = ilObject::_getAllReferences($this->getTargetId()); - $this->setTargetRefId(current($ref_ids)); - - if($this->getTitleType() == ilContainerReference::TITLE_TYPE_REUSE) - { - #$this->title = $this->lng->txt('reference_of').' '.ilObject::_lookupTitle($this->getTargetId()); - $this->title = ilObject::_lookupTitle($this->getTargetId()); - } - } + $ilDB = $DIC->database(); + + $query = "SELECT * FROM container_reference " . + "WHERE target_obj_id = " . $ilDB->quote($a_target_id, 'integer') . " "; + $res = $ilDB->query($query); + $ret = array(); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + $ret[] = $row->obj_id; + } + return $ret; + } + + /** + * get target id + * + * @access public + * @return + */ + public function getTargetId() + { + return $this->target_id; + } + + + /** + * set target id + * + * @access public + * @param int $a_target_id target id + * @return + */ + public function setTargetId($a_target_id) + { + $this->target_id = $a_target_id; + } + + /** + * set target ref_id + * + * @access public + * @param + * @return + */ + public function setTargetRefId($a_id) + { + $this->target_ref_id = $a_id; + } + + /** + * get Target ref_id + * + * @access public + * @param + * @return + */ + public function getTargetRefId() + { + return $this->target_ref_id; + } + + /** + * get title type + * @return type + */ + public function getTitleType() + { + return $this->title_type; + } + + /** + * Set title type + * @param type $type + */ + public function setTitleType($type) + { + $this->title_type = $type; + } + + /** + * read + * + * @access public + * @return + */ + public function read() + { + $ilDB = $this->db; + + parent::read(); + + $query = "SELECT * FROM container_reference " . + "WHERE obj_id = " . $ilDB->quote($this->getId(), 'integer') . " "; + $res = $ilDB->query($query); + + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + $this->setTargetId($row->target_obj_id); + $this->setTitleType($row->title_type); + } + $ref_ids = ilObject::_getAllReferences($this->getTargetId()); + $this->setTargetRefId(current($ref_ids)); + + if ($this->getTitleType() == ilContainerReference::TITLE_TYPE_REUSE) { + #$this->title = $this->lng->txt('reference_of').' '.ilObject::_lookupTitle($this->getTargetId()); + $this->title = ilObject::_lookupTitle($this->getTargetId()); + } + } - /** - * Get presentation title - * @return string presentation title - */ - public function getPresentationTitle() - { - if($this->getTitleType() == self::TITLE_TYPE_CUSTOM) - { - return $this->getTitle(); - } - else - { - return $this->lng->txt('reference_of').' '.$this->getTitle(); - } - } - - /** - * update object - * - * @access public - * @param - * @return - */ - public function update() - { - $ilDB = $this->db; - - parent::update(); - - $query = "DELETE FROM container_reference ". - "WHERE obj_id = ".$ilDB->quote($this->getId(),'integer')." "; - $ilDB->manipulate($query); - - $query = "INSERT INTO container_reference (obj_id, target_obj_id, title_type) ". - "VALUES( ". - $ilDB->quote($this->getId(),'integer').", ". - $ilDB->quote($this->getTargetId(),'integer').", ". - $ilDB->quote($this->getTitleType(),'integer').' '. - ")"; - $ilDB->manipulate($query); - } - - /** - * delete - * - * @access public - * @param - * @return - */ - public function delete() - { - $ilDB = $this->db; + /** + * Get presentation title + * @return string presentation title + */ + public function getPresentationTitle() + { + if ($this->getTitleType() == self::TITLE_TYPE_CUSTOM) { + return $this->getTitle(); + } else { + return $this->lng->txt('reference_of') . ' ' . $this->getTitle(); + } + } + + /** + * update object + * + * @access public + * @param + * @return + */ + public function update() + { + $ilDB = $this->db; + + parent::update(); + + $query = "DELETE FROM container_reference " . + "WHERE obj_id = " . $ilDB->quote($this->getId(), 'integer') . " "; + $ilDB->manipulate($query); + + $query = "INSERT INTO container_reference (obj_id, target_obj_id, title_type) " . + "VALUES( " . + $ilDB->quote($this->getId(), 'integer') . ", " . + $ilDB->quote($this->getTargetId(), 'integer') . ", " . + $ilDB->quote($this->getTitleType(), 'integer') . ' ' . + ")"; + $ilDB->manipulate($query); + } + + /** + * delete + * + * @access public + * @param + * @return + */ + public function delete() + { + $ilDB = $this->db; - if(!parent::delete()) - { - return false; - } + if (!parent::delete()) { + return false; + } - $query = "DELETE FROM container_reference ". - "WHERE obj_id = ".$ilDB->quote($this->getId(),'integer')." "; - $ilDB->manipulate($query); - - return true; - } - - /** - * Clone course reference - * - * @access public - * @param int target ref_id - * @param int copy id - * - */ - public function cloneObject($a_target_id,$a_copy_id = 0, $a_omit_tree = false) - { - $ilDB = $this->db; - $ilUser = $this->user; - - $new_obj = parent::cloneObject($a_target_id,$a_copy_id, $a_omit_tree); - - $query = "INSERT INTO container_reference (obj_id, target_obj_id, title_type) ". - "VALUES( ". - $ilDB->quote($new_obj->getId(),'integer').", ". - $ilDB->quote($this->getTargetId(),'integer').", ". - $ilDB->quote($this->getTitleType(),'integer').' '. - ")"; - $ilDB->manipulate($query); - return $new_obj; - } - + $query = "DELETE FROM container_reference " . + "WHERE obj_id = " . $ilDB->quote($this->getId(), 'integer') . " "; + $ilDB->manipulate($query); + + return true; + } + + /** + * Clone course reference + * + * @access public + * @param int target ref_id + * @param int copy id + * + */ + public function cloneObject($a_target_id, $a_copy_id = 0, $a_omit_tree = false) + { + $ilDB = $this->db; + $ilUser = $this->user; + + $new_obj = parent::cloneObject($a_target_id, $a_copy_id, $a_omit_tree); + + $query = "INSERT INTO container_reference (obj_id, target_obj_id, title_type) " . + "VALUES( " . + $ilDB->quote($new_obj->getId(), 'integer') . ", " . + $ilDB->quote($this->getTargetId(), 'integer') . ", " . + $ilDB->quote($this->getTitleType(), 'integer') . ' ' . + ")"; + $ilDB->manipulate($query); + return $new_obj; + } } - -?> \ No newline at end of file diff --git a/Services/ContainerReference/classes/class.ilContainerReferenceAccess.php b/Services/ContainerReference/classes/class.ilContainerReferenceAccess.php index 3c9742fab8fbde5aa3af1c682b1cd8accf685320..37bf2a8b13348f6f23702cc5cc16abfa1bebc938 100644 --- a/Services/ContainerReference/classes/class.ilContainerReferenceAccess.php +++ b/Services/ContainerReference/classes/class.ilContainerReferenceAccess.php @@ -1,84 +1,82 @@ * @version $Id$ -* -* +* +* * @ingroup ModulesCourseReference */ class ilContainerReferenceAccess extends ilObjectAccess { - /** - * checks wether a user may invoke a command or not - * (this method is called by ilAccessHandler::checkAccess) - * - * @param string $a_cmd command (not permission!) - * @param string $a_permission permission - * @param int $a_ref_id reference id - * @param int $a_obj_id object id - * @param int $a_user_id user id (if not provided, current user is taken) - * - * @return boolean true, if everything is ok - */ - public function _checkAccess($a_cmd, $a_permission, $a_ref_id, $a_obj_id, $a_user_id = "") - { - return true; - } - - /** - * Check if target is accessible and not deleted - * @param int $a_ref_id ref_id - * @return bool - * @static - */ - public static function _isAccessible($a_ref_id) - { - global $DIC; + /** + * checks wether a user may invoke a command or not + * (this method is called by ilAccessHandler::checkAccess) + * + * @param string $a_cmd command (not permission!) + * @param string $a_permission permission + * @param int $a_ref_id reference id + * @param int $a_obj_id object id + * @param int $a_user_id user id (if not provided, current user is taken) + * + * @return boolean true, if everything is ok + */ + public function _checkAccess($a_cmd, $a_permission, $a_ref_id, $a_obj_id, $a_user_id = "") + { + return true; + } + + /** + * Check if target is accessible and not deleted + * @param int $a_ref_id ref_id + * @return bool + * @static + */ + public static function _isAccessible($a_ref_id) + { + global $DIC; - $ilDB = $DIC->database(); - $tree = $DIC->repositoryTree(); - $access = $DIC->access(); - - $obj_id = ilObject::_lookupObjId($a_ref_id); - $query = "SELECT target_obj_id FROM container_reference ". - "WHERE obj_id = ".$ilDB->quote($obj_id,'integer')." "; - $res = $ilDB->query($query); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - $target_id = $row->target_obj_id; - } - $target_ref_ids = ilObject::_getAllReferences($target_id); - $target_ref_id = current($target_ref_ids); - return - !$tree->isDeleted($target_ref_id) && - $access->checkAccess('read','',$target_ref_id); - } -} -?> \ No newline at end of file + $ilDB = $DIC->database(); + $tree = $DIC->repositoryTree(); + $access = $DIC->access(); + + $obj_id = ilObject::_lookupObjId($a_ref_id); + $query = "SELECT target_obj_id FROM container_reference " . + "WHERE obj_id = " . $ilDB->quote($obj_id, 'integer') . " "; + $res = $ilDB->query($query); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + $target_id = $row->target_obj_id; + } + $target_ref_ids = ilObject::_getAllReferences($target_id); + $target_ref_id = current($target_ref_ids); + return + !$tree->isDeleted($target_ref_id) && + $access->checkAccess('read', '', $target_ref_id); + } +} diff --git a/Services/ContainerReference/classes/class.ilContainerReferenceAppEventListener.php b/Services/ContainerReference/classes/class.ilContainerReferenceAppEventListener.php index 1ad851b9cc83b695692fb68618941e17fd6561e3..fe9d9b0a2f4d4c29652ed365ffbe591ef606d220 100644 --- a/Services/ContainerReference/classes/class.ilContainerReferenceAppEventListener.php +++ b/Services/ContainerReference/classes/class.ilContainerReferenceAppEventListener.php @@ -1,121 +1,113 @@ * @version $Id$ -* * -* @ingroup +* +* @ingroup */ -class ilContainerReferenceAppEventListener implements ilAppEventListener +class ilContainerReferenceAppEventListener implements ilAppEventListener { - /** - * Handle events like create, update, delete - * - * @access public - * @param string $a_component component, e.g. "Modules/Forum" or "Services/User" - * @param string $a_event event e.g. "createUser", "updateUser", "deleteUser", ... - * @param array $a_parameter parameter array (assoc), array("name" => ..., "phone_office" => ...) * - * @static - */ - public static function handleEvent($a_component, $a_event, $a_parameter) - { - global $DIC; + /** + * Handle events like create, update, delete + * + * @access public + * @param string $a_component component, e.g. "Modules/Forum" or "Services/User" + * @param string $a_event event e.g. "createUser", "updateUser", "deleteUser", ... + * @param array $a_parameter parameter array (assoc), array("name" => ..., "phone_office" => ...) * + * @static + */ + public static function handleEvent($a_component, $a_event, $a_parameter) + { + global $DIC; - $ilLog = $DIC["ilLog"]; - - switch($a_component) - { - case 'Modules/Course': - case 'Modules/Category': - - switch($a_event) - { - case 'delete': - $ilLog->write(__METHOD__.': Handling delete event.'); - self::deleteReferences($a_parameter['obj_id']); - break; - } - break; - } - } - - /** - * Delete references - * - * @static - */ - public static function deleteReferences($a_target_id) - { - global $DIC; + $ilLog = $DIC["ilLog"]; + + switch ($a_component) { + case 'Modules/Course': + case 'Modules/Category': + + switch ($a_event) { + case 'delete': + $ilLog->write(__METHOD__ . ': Handling delete event.'); + self::deleteReferences($a_parameter['obj_id']); + break; + } + break; + } + } + + /** + * Delete references + * + * @static + */ + public static function deleteReferences($a_target_id) + { + global $DIC; - $ilLog = $DIC["ilLog"]; - $ilAppEventHandler = $DIC["ilAppEventHandler"]; - $tree = $DIC["tree"]; - - include_once('./Services/ContainerReference/classes/class.ilContainerReference.php'); - if(!$source_id = ilContainerReference::_lookupSourceId($a_target_id)) - { - return true; - } - foreach(ilObject::_getAllReferences($source_id) as $ref_id) - { - if(!$instance = ilObjectFactory::getInstanceByRefId($ref_id,false)) - { - continue; - } - $type = $instance->getType(); - switch($type) - { - case 'grpr': - case 'crsr': - case 'catr': - $parent_id = $tree->getParentId($ref_id); - $instance->delete(); - $ilLog->write(__METHOD__.': Deleted reference object of type '.$instance->getType().' with Id '.$instance->getId()); - $ilAppEventHandler->raise( - 'Services/ContainerReference', - 'deleteReference', - [ - 'ref_id' => $ref_id, - 'old_parent_ref_id' => $parent_id, - 'type' => $type - ] - ); - break; - - default: - $ilLog->write(__METHOD__.': Unexpected object type '.$instance->getType().' with Id '.$instance->getId()); - break; - } - - } - return true; - } + $ilLog = $DIC["ilLog"]; + $ilAppEventHandler = $DIC["ilAppEventHandler"]; + $tree = $DIC["tree"]; + + include_once('./Services/ContainerReference/classes/class.ilContainerReference.php'); + if (!$source_id = ilContainerReference::_lookupSourceId($a_target_id)) { + return true; + } + foreach (ilObject::_getAllReferences($source_id) as $ref_id) { + if (!$instance = ilObjectFactory::getInstanceByRefId($ref_id, false)) { + continue; + } + $type = $instance->getType(); + switch ($type) { + case 'grpr': + case 'crsr': + case 'catr': + $parent_id = $tree->getParentId($ref_id); + $instance->delete(); + $ilLog->write(__METHOD__ . ': Deleted reference object of type ' . $instance->getType() . ' with Id ' . $instance->getId()); + $ilAppEventHandler->raise( + 'Services/ContainerReference', + 'deleteReference', + [ + 'ref_id' => $ref_id, + 'old_parent_ref_id' => $parent_id, + 'type' => $type + ] + ); + break; + + default: + $ilLog->write(__METHOD__ . ': Unexpected object type ' . $instance->getType() . ' with Id ' . $instance->getId()); + break; + } + } + return true; + } } -?> diff --git a/Services/ContainerReference/classes/class.ilContainerReferenceExporter.php b/Services/ContainerReference/classes/class.ilContainerReferenceExporter.php index acc20e1841994d061061b43dc4c708823f4ebb30..3b7ac72042bc91f19c59e42bfee14faf113a6a99 100644 --- a/Services/ContainerReference/classes/class.ilContainerReferenceExporter.php +++ b/Services/ContainerReference/classes/class.ilContainerReferenceExporter.php @@ -5,104 +5,99 @@ include_once './Services/Export/classes/class.ilXmlExporter.php'; /** * Class for category export - * + * * @author Stefan Meyer * $Id$ */ abstract class ilContainerReferenceExporter extends ilXmlExporter { - /** - * Get head dependencies - * - * @param string entity - * @param string target release - * @param array ids - * @return array array of array with keys "component", entity", "ids" - */ - public function getXmlExportHeadDependencies($a_entity, $a_target_release, $a_ids) - { - global $DIC; + /** + * Get head dependencies + * + * @param string entity + * @param string target release + * @param array ids + * @return array array of array with keys "component", entity", "ids" + */ + public function getXmlExportHeadDependencies($a_entity, $a_target_release, $a_ids) + { + global $DIC; - $log = $DIC->logger()->root(); + $log = $DIC->logger()->root(); - include_once './Services/Export/classes/class.ilExportOptions.php'; - $eo = ilExportOptions::getInstance(); + include_once './Services/Export/classes/class.ilExportOptions.php'; + $eo = ilExportOptions::getInstance(); - $obj_id = end($a_ids); + $obj_id = end($a_ids); - $log->debug(__METHOD__.': '.$obj_id); - if($eo->getOption(ilExportOptions::KEY_ROOT) != $obj_id) - { - return array(); - } - if(count(ilExportOptions::getInstance()->getSubitemsForExport()) > 1) - { - return array( - array( - 'component' => 'Services/Container', - 'entity' => 'struct', - 'ids' => $a_ids - ) - ); - } - return array(); - } - - abstract protected function initWriter(ilContainerReference $ref); + $log->debug(__METHOD__ . ': ' . $obj_id); + if ($eo->getOption(ilExportOptions::KEY_ROOT) != $obj_id) { + return array(); + } + if (count(ilExportOptions::getInstance()->getSubitemsForExport()) > 1) { + return array( + array( + 'component' => 'Services/Container', + 'entity' => 'struct', + 'ids' => $a_ids + ) + ); + } + return array(); + } + + abstract protected function initWriter(ilContainerReference $ref); - /** - * Get xml - * @param object $a_entity - * @param object $a_schema_version - * @param object $a_id - * @return - */ - public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) - { - global $DIC; + /** + * Get xml + * @param object $a_entity + * @param object $a_schema_version + * @param object $a_id + * @return + */ + public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) + { + global $DIC; - $log = $DIC->logger()->root(); + $log = $DIC->logger()->root(); - $ref_ref_id = end(ilObject::_getAllReferences($a_id)); - $ref = ilObjectFactory::getInstanceByRefId($ref_ref_id,false); + $ref_ref_id = end(ilObject::_getAllReferences($a_id)); + $ref = ilObjectFactory::getInstanceByRefId($ref_ref_id, false); - if(!$ref instanceof ilContainerReference) - { - $log->debug(__METHOD__. $a_id . ' is not instance of type category!'); - return ''; - } - $writer = $this->initWriter($ref); - $writer->setMode(ilContainerReferenceXmlWriter::MODE_EXPORT); - $writer->export(false); - return $writer->getXml(); - } + if (!$ref instanceof ilContainerReference) { + $log->debug(__METHOD__ . $a_id . ' is not instance of type category!'); + return ''; + } + $writer = $this->initWriter($ref); + $writer->setMode(ilContainerReferenceXmlWriter::MODE_EXPORT); + $writer->export(false); + return $writer->getXml(); + } - /** - * Returns schema versions that the component can export to. - * ILIAS chooses the first one, that has min/max constraints which - * fit to the target release. Please put the newest on top. - * - * @return - */ - public function getValidSchemaVersions($a_entity) - { - return array ( - "4.3.0" => array( - "namespace" => "http://www.ilias.de/Modules/CategoryReference/catr/4_3", - "xsd_file" => "ilias_catr_4_3.xsd", - "uses_dataset" => false, - "min" => "4.3.0", - "max" => "") - ); - } - - /** - * Init method - */ - public function init() { - - } + /** + * Returns schema versions that the component can export to. + * ILIAS chooses the first one, that has min/max constraints which + * fit to the target release. Please put the newest on top. + * + * @return + */ + public function getValidSchemaVersions($a_entity) + { + return array( + "4.3.0" => array( + "namespace" => "http://www.ilias.de/Modules/CategoryReference/catr/4_3", + "xsd_file" => "ilias_catr_4_3.xsd", + "uses_dataset" => false, + "min" => "4.3.0", + "max" => "") + ); + } + /** + * Init method + */ + public function init() + { + } } -?> diff --git a/Services/ContainerReference/classes/class.ilContainerReferenceGUI.php b/Services/ContainerReference/classes/class.ilContainerReferenceGUI.php index 3275a9e06b1d493816b0ab0f6b53f9f7f3c53549..ab761d23865d7dfb359089859b277fd0ce518915 100644 --- a/Services/ContainerReference/classes/class.ilContainerReferenceGUI.php +++ b/Services/ContainerReference/classes/class.ilContainerReferenceGUI.php @@ -1,445 +1,423 @@ * @version $Id$ -* * -* @ingroup ServicesContainerReference +* +* @ingroup ServicesContainerReference */ class ilContainerReferenceGUI extends ilObjectGUI { - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilLocatorGUI - */ - protected $locator; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * @var ilSetting - */ - protected $settings; - - const MAX_SELECTION_ENTRIES = 50; - - const MODE_CREATE = 1; - const MODE_EDIT = 2; - - protected $existing_objects = array(); - - /** @var string */ - protected $target_type; - /** @var string */ - protected $reference_type; - /** @var ilPropertyFormGUI */ - protected $form; - - /** - * Constructor - * @param - */ - public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) - { - global $DIC; - - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $this->tabs = $DIC->tabs(); - $this->locator = $DIC["ilLocator"]; - $this->user = $DIC->user(); - $this->access = $DIC->access(); - $this->error = $DIC["ilErr"]; - $this->settings = $DIC->settings(); - $lng = $DIC->language(); - parent::__construct($a_data, $a_id,$a_call_by_reference,$a_prepare_output); - - $lng->loadLanguageModule('objref'); - } - - /** - * Execute command - * - * @access public - * - * @return bool|mixed - * @throws ilCtrlException - */ - public function executeCommand() - { - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - - if(isset($_GET['creation_mode']) && $_GET['creation_mode'] == self::MODE_CREATE) - { - $this->setCreationMode(true); - } - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd(); - - $this->prepareOutput(); - - switch($next_class) - { - case "ilpropertyformgui": - $form = $this->initForm($this->creation_mode ? self::MODE_CREATE : self::MODE_EDIT); - $this->ctrl->forwardCommand($form); - break; - - case 'ilpermissiongui': - $ilTabs->setTabActive('perm_settings'); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $ilCtrl->forwardCommand(new ilPermissionGUI($this)); - break; - - default: - if(!$cmd || $cmd == 'view') - { - $cmd = "edit"; - } - $cmd .= "Object"; - $this->$cmd(); - break; - } - return true; - } - - /** - * Add locator item - */ - protected function addLocatorItems() - { - $ilLocator = $this->locator; - - if($this->object instanceof ilObject) - { - $ilLocator->addItem($this->object->getPresentationTitle(),$this->ctrl->getLinkTarget($this)); - } - } - - /** - * redirect to target - * @param - */ - public function redirectObject() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $this->object->getTargetRefId()); - $ilCtrl->redirectByClass("ilrepositorygui", ""); - } - - /** - * Create object - * - * @return void - */ - public function createObject() - { - $ilUser = $this->user; - $ilAccess = $this->access; - $ilErr = $this->error; - $ilSetting = $this->settings; - - $new_type = $_REQUEST["new_type"]; - if(!$ilAccess->checkAccess("create_".$this->getReferenceType(),'',$_GET["ref_id"], $new_type)) - { - $ilErr->raiseError($this->lng->txt("permission_denied"),$ilErr->MESSAGE); - } - $form = $this->initForm(self::MODE_CREATE); - $this->tpl->setContent($form->getHTML()); - } - - - /** - * save object - * - * @access public - * @param - * @return - */ - public function saveObject() - { - $ilAccess = $this->access; - - if(!(int) $_REQUEST['target_id']) - { - ilUtil::sendFailure($this->lng->txt('select_one')); - $this->createObject(); - return false; - } - if(!$ilAccess->checkAccess('visible','',(int) $_REQUEST['target_id'])) - { - ilUtil::sendFailure($this->lng->txt('permission_denied')); - $this->createObject(); - return false; - } - - parent::saveObject(); - } - - protected function initCreateForm($a_new_type) - { - return $this->initForm(self::MODE_CREATE); - } - - /** - * @param ilObject $a_new_object - */ - protected function afterSave(ilObject $a_new_object) - { - $target_obj_id = ilObject::_lookupObjId((int) $this->form->getInput('target_id')); - $a_new_object->setTargetId($target_obj_id); - - $a_new_object->setTitleType($this->form->getInput('title_type')); - if($this->form->getInput('title_type') == ilContainerReference::TITLE_TYPE_CUSTOM) - { - $a_new_object->setTitle($this->form->getInput('title')); - } - - $a_new_object->update(); - - ilUtil::sendSuccess($this->lng->txt("object_added"), true); - $this->ctrl->setParameter($this,'ref_id',$a_new_object->getRefId()); - $this->ctrl->setParameter($this,'creation_mode',0); - $this->ctrl->redirect($this,'firstEdit'); - } - - /** - * show edit screen without info message - */ - protected function firstEditObject() - { - $this->editObject(); - } - - public function editReferenceObject() - { - $this->editObject(); - } - - /** - * edit title - * - * @param ilPropertyFormGUI $form - */ - public function editObject(ilPropertyFormGUI $form = null) - { - global $DIC; - - $main_tpl = $DIC->ui()->mainTemplate(); - - $ilTabs = $this->tabs; - - $ilTabs->setTabActive('settings'); - - if(!$form instanceof ilPropertyFormGUI) - { - $form = $this->initForm(); - } - $main_tpl->setContent($form->getHTML()); - } - - /** - * Init title form - * @param int $a_mode - * @return ilPropertyFormGUI - */ - protected function initForm($a_mode = self::MODE_EDIT) - { - include_once './Services/Form/classes/class.ilPropertyFormGUI.php'; - include_once './Services/ContainerReference/classes/class.ilContainerReference.php'; - $form = new ilPropertyFormGUI(); - - if ($a_mode == self::MODE_CREATE) { - $form->setTitle($this->lng->txt($this->getReferenceType(). '_new' )); - - $this->ctrl->setParameter($this, 'creation_mode', $a_mode); - $this->ctrl->setParameter($this, 'new_type', $_REQUEST['new_type']); - } - else - { - $form->setTitle($this->lng->txt('edit')); - } - - $form->setFormAction($this->ctrl->getFormAction($this)); - if ($a_mode == self::MODE_CREATE) - { - $form->addCommandButton('save', $this->lng->txt('create')); - $form->addCommandButton('cancel', $this->lng->txt('cancel')); - } - else - { - $form->addCommandButton('update', $this->lng->txt('save')); - } - - // title type - $ttype = new ilRadioGroupInputGUI($this->lng->txt('title'), 'title_type'); - if ($a_mode == self::MODE_EDIT) - { - $ttype->setValue($this->object->getTitleType()); - } - else - { - $ttype->setValue(ilContainerReference::TITLE_TYPE_REUSE); - } - - $reuse = new ilRadioOption($this->lng->txt('objref_reuse_title')); - $reuse->setValue(ilContainerReference::TITLE_TYPE_REUSE); - $ttype->addOption($reuse); - - $custom = new ilRadioOption($this->lng->txt('objref_custom_title')); - $custom->setValue(ilContainerReference::TITLE_TYPE_CUSTOM); - - // title - $title = new ilTextInputGUI($this->lng->txt('title'),'title'); - $title->setSize(min(40, ilObject::TITLE_LENGTH)); - $title->setMaxLength(ilObject::TITLE_LENGTH); - $title->setRequired(true); - - if($a_mode == self::MODE_EDIT) - { - $title->setValue($this->object->getTitle()); - } - - $custom->addSubItem($title); - $ttype->addOption($custom); - $form->addItem($ttype); - - include_once("./Services/Form/classes/class.ilRepositorySelector2InputGUI.php"); - $repo = new ilRepositorySelector2InputGUI($this->lng->txt("objref_edit_ref"), "target_id"); - //$repo->setParent($this); - $repo->setRequired(true); - $repo->getExplorerGUI()->setSelectableTypes(array($this->getTargetType())); - $repo->getExplorerGUI()->setTypeWhiteList(array_merge( - array($this->getTargetType()), - array("root", "cat", "grp", "fold", "crs")) - ); - $repo->setInfo($this->lng->txt($this->getReferenceType().'_edit_info')); - - if($a_mode == self::MODE_EDIT) - { - $repo->getExplorerGUI()->setPathOpen($this->object->getTargetRefId()); - $repo->setValue($this->object->getTargetRefId()); - } - - $form->addItem($repo); - $this->form = $form; - return $form; - } - - /** - * update title - */ - public function updateObject() - { - $ilAccess = $this->access; - $form = $this->initForm(); - if($form->checkInput()) - { - $this->object->setTitleType($form->getInput('title_type')); - if($form->getInput('title_type') == ilContainerReference::TITLE_TYPE_CUSTOM) - { - $this->object->setTitle($form->getInput('title')); - } - - if(!$ilAccess->checkAccess('visible','',(int) $form->getInput('target_id')) || - ilObject::_lookupType($form->getInput('target_id'), true) != $this->target_type) - { - ilUtil::sendFailure($this->lng->txt('permission_denied')); - $this->editObject(); - return false; - } - $this->checkPermission('write'); - - $target_obj_id = ilObject::_lookupObjId((int) $form->getInput('target_id')); - $this->object->setTargetId($target_obj_id); - - - $this->object->update(); - ilUtil::sendSuccess($this->lng->txt('settings_saved'), true); - $this->ctrl->redirect($this,'edit'); - } - $form->setValuesByPost(); - ilUtil::sendFailure($this->lng->txt('err_check_input')); - $this->editObject($form); - return true; - } - - /** - * get target type - * - * @access public - * @return string - */ - public function getTargetType() - { - return $this->target_type; - } - - /** - * get reference type - * - * @access public - * @return string - */ - public function getReferenceType() - { - return $this->reference_type; - } - - /** - * @return int - */ - public function getId() - { - return $this->obj_id; - } - + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilLocatorGUI + */ + protected $locator; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilSetting + */ + protected $settings; + + const MAX_SELECTION_ENTRIES = 50; + + const MODE_CREATE = 1; + const MODE_EDIT = 2; + + protected $existing_objects = array(); + + /** @var string */ + protected $target_type; + /** @var string */ + protected $reference_type; + /** @var ilPropertyFormGUI */ + protected $form; + + /** + * Constructor + * @param + */ + public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) + { + global $DIC; + + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->tabs = $DIC->tabs(); + $this->locator = $DIC["ilLocator"]; + $this->user = $DIC->user(); + $this->access = $DIC->access(); + $this->error = $DIC["ilErr"]; + $this->settings = $DIC->settings(); + $lng = $DIC->language(); + parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); + + $lng->loadLanguageModule('objref'); + } + + /** + * Execute command + * + * @access public + * + * @return bool|mixed + * @throws ilCtrlException + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + + if (isset($_GET['creation_mode']) && $_GET['creation_mode'] == self::MODE_CREATE) { + $this->setCreationMode(true); + } + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd(); + + $this->prepareOutput(); + + switch ($next_class) { + case "ilpropertyformgui": + $form = $this->initForm($this->creation_mode ? self::MODE_CREATE : self::MODE_EDIT); + $this->ctrl->forwardCommand($form); + break; + + case 'ilpermissiongui': + $ilTabs->setTabActive('perm_settings'); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $ilCtrl->forwardCommand(new ilPermissionGUI($this)); + break; + + default: + if (!$cmd || $cmd == 'view') { + $cmd = "edit"; + } + $cmd .= "Object"; + $this->$cmd(); + break; + } + return true; + } + + /** + * Add locator item + */ + protected function addLocatorItems() + { + $ilLocator = $this->locator; + + if ($this->object instanceof ilObject) { + $ilLocator->addItem($this->object->getPresentationTitle(), $this->ctrl->getLinkTarget($this)); + } + } + + /** + * redirect to target + * @param + */ + public function redirectObject() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $this->object->getTargetRefId()); + $ilCtrl->redirectByClass("ilrepositorygui", ""); + } + + /** + * Create object + * + * @return void + */ + public function createObject() + { + $ilUser = $this->user; + $ilAccess = $this->access; + $ilErr = $this->error; + $ilSetting = $this->settings; + + $new_type = $_REQUEST["new_type"]; + if (!$ilAccess->checkAccess("create_" . $this->getReferenceType(), '', $_GET["ref_id"], $new_type)) { + $ilErr->raiseError($this->lng->txt("permission_denied"), $ilErr->MESSAGE); + } + $form = $this->initForm(self::MODE_CREATE); + $this->tpl->setContent($form->getHTML()); + } + + + /** + * save object + * + * @access public + * @param + * @return + */ + public function saveObject() + { + $ilAccess = $this->access; + + if (!(int) $_REQUEST['target_id']) { + ilUtil::sendFailure($this->lng->txt('select_one')); + $this->createObject(); + return false; + } + if (!$ilAccess->checkAccess('visible', '', (int) $_REQUEST['target_id'])) { + ilUtil::sendFailure($this->lng->txt('permission_denied')); + $this->createObject(); + return false; + } + + parent::saveObject(); + } + + protected function initCreateForm($a_new_type) + { + return $this->initForm(self::MODE_CREATE); + } + + /** + * @param ilObject $a_new_object + */ + protected function afterSave(ilObject $a_new_object) + { + $target_obj_id = ilObject::_lookupObjId((int) $this->form->getInput('target_id')); + $a_new_object->setTargetId($target_obj_id); + + $a_new_object->setTitleType($this->form->getInput('title_type')); + if ($this->form->getInput('title_type') == ilContainerReference::TITLE_TYPE_CUSTOM) { + $a_new_object->setTitle($this->form->getInput('title')); + } + + $a_new_object->update(); + + ilUtil::sendSuccess($this->lng->txt("object_added"), true); + $this->ctrl->setParameter($this, 'ref_id', $a_new_object->getRefId()); + $this->ctrl->setParameter($this, 'creation_mode', 0); + $this->ctrl->redirect($this, 'firstEdit'); + } + + /** + * show edit screen without info message + */ + protected function firstEditObject() + { + $this->editObject(); + } + + public function editReferenceObject() + { + $this->editObject(); + } + + /** + * edit title + * + * @param ilPropertyFormGUI $form + */ + public function editObject(ilPropertyFormGUI $form = null) + { + global $DIC; + + $main_tpl = $DIC->ui()->mainTemplate(); + + $ilTabs = $this->tabs; + + $ilTabs->setTabActive('settings'); + + if (!$form instanceof ilPropertyFormGUI) { + $form = $this->initForm(); + } + $main_tpl->setContent($form->getHTML()); + } + + /** + * Init title form + * @param int $a_mode + * @return ilPropertyFormGUI + */ + protected function initForm($a_mode = self::MODE_EDIT) + { + include_once './Services/Form/classes/class.ilPropertyFormGUI.php'; + include_once './Services/ContainerReference/classes/class.ilContainerReference.php'; + $form = new ilPropertyFormGUI(); + + if ($a_mode == self::MODE_CREATE) { + $form->setTitle($this->lng->txt($this->getReferenceType() . '_new')); + + $this->ctrl->setParameter($this, 'creation_mode', $a_mode); + $this->ctrl->setParameter($this, 'new_type', $_REQUEST['new_type']); + } else { + $form->setTitle($this->lng->txt('edit')); + } + + $form->setFormAction($this->ctrl->getFormAction($this)); + if ($a_mode == self::MODE_CREATE) { + $form->addCommandButton('save', $this->lng->txt('create')); + $form->addCommandButton('cancel', $this->lng->txt('cancel')); + } else { + $form->addCommandButton('update', $this->lng->txt('save')); + } + + // title type + $ttype = new ilRadioGroupInputGUI($this->lng->txt('title'), 'title_type'); + if ($a_mode == self::MODE_EDIT) { + $ttype->setValue($this->object->getTitleType()); + } else { + $ttype->setValue(ilContainerReference::TITLE_TYPE_REUSE); + } + + $reuse = new ilRadioOption($this->lng->txt('objref_reuse_title')); + $reuse->setValue(ilContainerReference::TITLE_TYPE_REUSE); + $ttype->addOption($reuse); + + $custom = new ilRadioOption($this->lng->txt('objref_custom_title')); + $custom->setValue(ilContainerReference::TITLE_TYPE_CUSTOM); + + // title + $title = new ilTextInputGUI($this->lng->txt('title'), 'title'); + $title->setSize(min(40, ilObject::TITLE_LENGTH)); + $title->setMaxLength(ilObject::TITLE_LENGTH); + $title->setRequired(true); + + if ($a_mode == self::MODE_EDIT) { + $title->setValue($this->object->getTitle()); + } + + $custom->addSubItem($title); + $ttype->addOption($custom); + $form->addItem($ttype); + + include_once("./Services/Form/classes/class.ilRepositorySelector2InputGUI.php"); + $repo = new ilRepositorySelector2InputGUI($this->lng->txt("objref_edit_ref"), "target_id"); + //$repo->setParent($this); + $repo->setRequired(true); + $repo->getExplorerGUI()->setSelectableTypes(array($this->getTargetType())); + $repo->getExplorerGUI()->setTypeWhiteList( + array_merge( + array($this->getTargetType()), + array("root", "cat", "grp", "fold", "crs") + ) + ); + $repo->setInfo($this->lng->txt($this->getReferenceType() . '_edit_info')); + + if ($a_mode == self::MODE_EDIT) { + $repo->getExplorerGUI()->setPathOpen($this->object->getTargetRefId()); + $repo->setValue($this->object->getTargetRefId()); + } + + $form->addItem($repo); + $this->form = $form; + return $form; + } + + /** + * update title + */ + public function updateObject() + { + $ilAccess = $this->access; + $form = $this->initForm(); + if ($form->checkInput()) { + $this->object->setTitleType($form->getInput('title_type')); + if ($form->getInput('title_type') == ilContainerReference::TITLE_TYPE_CUSTOM) { + $this->object->setTitle($form->getInput('title')); + } + + if (!$ilAccess->checkAccess('visible', '', (int) $form->getInput('target_id')) || + ilObject::_lookupType($form->getInput('target_id'), true) != $this->target_type) { + ilUtil::sendFailure($this->lng->txt('permission_denied')); + $this->editObject(); + return false; + } + $this->checkPermission('write'); + + $target_obj_id = ilObject::_lookupObjId((int) $form->getInput('target_id')); + $this->object->setTargetId($target_obj_id); + + + $this->object->update(); + ilUtil::sendSuccess($this->lng->txt('settings_saved'), true); + $this->ctrl->redirect($this, 'edit'); + } + $form->setValuesByPost(); + ilUtil::sendFailure($this->lng->txt('err_check_input')); + $this->editObject($form); + return true; + } + + /** + * get target type + * + * @access public + * @return string + */ + public function getTargetType() + { + return $this->target_type; + } + + /** + * get reference type + * + * @access public + * @return string + */ + public function getReferenceType() + { + return $this->reference_type; + } + + /** + * @return int + */ + public function getId() + { + return $this->obj_id; + } } -?> diff --git a/Services/ContainerReference/classes/class.ilContainerReferenceImporter.php b/Services/ContainerReference/classes/class.ilContainerReferenceImporter.php index 782891715b7cf1860b73e0ab13bff23693fec034..c5b11fe54b9892fb15f59d4e680082c324a885fb 100644 --- a/Services/ContainerReference/classes/class.ilContainerReferenceImporter.php +++ b/Services/ContainerReference/classes/class.ilContainerReferenceImporter.php @@ -14,93 +14,83 @@ include_once("./Services/Export/classes/class.ilXmlImporter.php"); */ abstract class ilContainerReferenceImporter extends ilXmlImporter { - protected $ref = null; - + protected $ref = null; + - public function init() - { - } - - /** - * Init reference - * @return ilContainerReference - */ - protected function initReference($a_ref_id = 0) - { - $this->ref = ilObjectFactory::getInstanceByRefId($a_ref_id,true); - } - - /** - * Get reference type - */ - abstract protected function getType(); - - /** - * Init xml parser - */ - abstract protected function initParser($a_xml); - - /** - * get reference - * @return ilContainerReference - */ - protected function getReference() - { - return $this->ref; - } - - /** - * Import XML - * - * @param - * @return - */ - function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) - { - global $DIC; + public function init() + { + } + + /** + * Init reference + * @return ilContainerReference + */ + protected function initReference($a_ref_id = 0) + { + $this->ref = ilObjectFactory::getInstanceByRefId($a_ref_id, true); + } + + /** + * Get reference type + */ + abstract protected function getType(); + + /** + * Init xml parser + */ + abstract protected function initParser($a_xml); + + /** + * get reference + * @return ilContainerReference + */ + protected function getReference() + { + return $this->ref; + } + + /** + * Import XML + * + * @param + * @return + */ + public function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) + { + global $DIC; - $objDefinition = $DIC["objDefinition"]; - $log = $DIC->logger()->root(); + $objDefinition = $DIC["objDefinition"]; + $log = $DIC->logger()->root(); - include_once './Modules/Category/classes/class.ilObjCategory.php'; - if($new_id = $a_mapping->getMapping('Services/Container','objs',$a_id)) - { - $refs = ilObject::_getAllReferences($new_id); - $this->initReference(end($refs)); - } - // Mapping for containers without subitems - elseif($new_id = $a_mapping->getMapping('Services/Container','refs',0)) - { - $this->initReference($new_id); - } - elseif(!$this->getReference() instanceof ilContainerReference) - { - $this->initReference(); - $this->getReference()->create(true); - } + include_once './Modules/Category/classes/class.ilObjCategory.php'; + if ($new_id = $a_mapping->getMapping('Services/Container', 'objs', $a_id)) { + $refs = ilObject::_getAllReferences($new_id); + $this->initReference(end($refs)); + } + // Mapping for containers without subitems + elseif ($new_id = $a_mapping->getMapping('Services/Container', 'refs', 0)) { + $this->initReference($new_id); + } elseif (!$this->getReference() instanceof ilContainerReference) { + $this->initReference(); + $this->getReference()->create(true); + } - try - { - $parser = $this->initParser($a_xml); - $parser->setReference($this->getReference()); - $parser->setMode(ilContainerReferenceXmlParser::MODE_UPDATE); - $parser->startParsing(); - - $a_mapping->addMapping( - $objDefinition->getComponentForType($this->getType()), - $this->getType(), - $a_id, - $this->getReference()->getId() - ); - } - catch(ilSaxParserException $e) - { - $log->error(__METHOD__.': Parsing failed with message, "'.$e->getMessage().'".'); - } - catch(Exception $e) - { - $log->error(__METHOD__.': Parsing failed with message, "'.$e->getMessage().'".'); - } - } + try { + $parser = $this->initParser($a_xml); + $parser->setReference($this->getReference()); + $parser->setMode(ilContainerReferenceXmlParser::MODE_UPDATE); + $parser->startParsing(); + + $a_mapping->addMapping( + $objDefinition->getComponentForType($this->getType()), + $this->getType(), + $a_id, + $this->getReference()->getId() + ); + } catch (ilSaxParserException $e) { + $log->error(__METHOD__ . ': Parsing failed with message, "' . $e->getMessage() . '".'); + } catch (Exception $e) { + $log->error(__METHOD__ . ': Parsing failed with message, "' . $e->getMessage() . '".'); + } + } } -?> diff --git a/Services/ContainerReference/classes/class.ilContainerReferenceXmlParser.php b/Services/ContainerReference/classes/class.ilContainerReferenceXmlParser.php index 4462d5896c2a95f0e817931b4d98ce6923331516..55c6e5ded63827479fc1f37ba22648ed9d2860c0 100644 --- a/Services/ContainerReference/classes/class.ilContainerReferenceXmlParser.php +++ b/Services/ContainerReference/classes/class.ilContainerReferenceXmlParser.php @@ -1,24 +1,24 @@ error = $DIC["ilErr"]; - parent::__construct(null); - - $this->mode = ilContainerReferenceXmlParser::MODE_CREATE; - $this->setXMLContent($a_xml); - } - - /** - * Get parent id - * @return type - */ - public function getParentId() - { - return $this->parent_id; - } - - /** - * 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->ref instanceof ilContainerReference) - { - return $this->ref; - } - return 0; - } - - - /** - * handler for begin of element - */ - public function handlerBeginTag($a_xml_parser, $a_name, $a_attribs) - { - $ilErr = $this->error; - - switch($a_name) - { - case "ContainerReference": - break; - - case 'Title': - switch($a_attribs['type']) - { - case ilContainerReference::TITLE_TYPE_REUSE: - $this->getReference()->setTitleType(ilContainerReference::TITLE_TYPE_REUSE); - break; - - default: - $this->getReference()->setTitleType(ilContainerReference::TITLE_TYPE_REUSE); - break; - } - break; - - case 'Target': - $this->getReference()->setTargetId($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 "ContainerReference": - $this->save(); - break; - - case 'Title': - if($this->getReference()->getTitleType() == ilContainerReference::TITLE_TYPE_CUSTOM) - { - $this->getReference()->setTitle(trim($this->cdata)); - } - 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 - */ - include_once './Modules/Category/classes/class.ilCategoryXmlParser.php'; - if ($this->mode == ilCategoryXmlParser::MODE_CREATE) - { - $this->create(); - $this->getReference()->create(); - $this->getReference()->createReference(); - $this->getReference()->putInTree($this->getParentId()); - $this->getReference()->setPermissions($this->getParentId()); - } - $this->getReference()->update(); - return true; - } - - - - - /** - * Set import mode - * @param type $mode - */ - public function setMode($mode) - { - $this->mode = $mode; - } - - - /** - * Set container reference - * @param ilContainerReference $ref - */ - public function setReference(ilContainerReference $ref) - { - $this->ref = $ref; - } - - /** - * Get container reference - * @return ilContainerReference - */ - public function getReference() - { - return $this->ref; - } + /** + * @var ilErrorHandling + */ + protected $error; + + const MODE_CREATE = 1; + const MODE_UPDATE = 2; + + private $ref = null; + private $parent_id = 0; + + /** + * Constructor + * + * @param string $a_xml_file xml file + * + * @access public + */ + + public function __construct($a_xml, $a_parent_id = 0) + { + global $DIC; + + $this->error = $DIC["ilErr"]; + parent::__construct(null); + + $this->mode = ilContainerReferenceXmlParser::MODE_CREATE; + $this->setXMLContent($a_xml); + } + + /** + * Get parent id + * @return type + */ + public function getParentId() + { + return $this->parent_id; + } + + /** + * 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->ref instanceof ilContainerReference) { + return $this->ref; + } + return 0; + } + + + /** + * handler for begin of element + */ + public function handlerBeginTag($a_xml_parser, $a_name, $a_attribs) + { + $ilErr = $this->error; + + switch ($a_name) { + case "ContainerReference": + break; + + case 'Title': + switch ($a_attribs['type']) { + case ilContainerReference::TITLE_TYPE_REUSE: + $this->getReference()->setTitleType(ilContainerReference::TITLE_TYPE_REUSE); + break; + + default: + $this->getReference()->setTitleType(ilContainerReference::TITLE_TYPE_REUSE); + break; + } + break; + + case 'Target': + $this->getReference()->setTargetId($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 "ContainerReference": + $this->save(); + break; + + case 'Title': + if ($this->getReference()->getTitleType() == ilContainerReference::TITLE_TYPE_CUSTOM) { + $this->getReference()->setTitle(trim($this->cdata)); + } + 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 + */ + include_once './Modules/Category/classes/class.ilCategoryXmlParser.php'; + if ($this->mode == ilCategoryXmlParser::MODE_CREATE) { + $this->create(); + $this->getReference()->create(); + $this->getReference()->createReference(); + $this->getReference()->putInTree($this->getParentId()); + $this->getReference()->setPermissions($this->getParentId()); + } + $this->getReference()->update(); + return true; + } + + + + + /** + * Set import mode + * @param type $mode + */ + public function setMode($mode) + { + $this->mode = $mode; + } + + + /** + * Set container reference + * @param ilContainerReference $ref + */ + public function setReference(ilContainerReference $ref) + { + $this->ref = $ref; + } + + /** + * Get container reference + * @return ilContainerReference + */ + public function getReference() + { + return $this->ref; + } } -?> \ No newline at end of file diff --git a/Services/ContainerReference/classes/class.ilContainerReferenceXmlWriter.php b/Services/ContainerReference/classes/class.ilContainerReferenceXmlWriter.php index 2ffb47a8637972c9107891c6061837d90f31d7ef..ca785ea6d6596635841bb77e28eb5075f0ec0b88 100644 --- a/Services/ContainerReference/classes/class.ilContainerReferenceXmlWriter.php +++ b/Services/ContainerReference/classes/class.ilContainerReferenceXmlWriter.php @@ -11,146 +11,142 @@ include_once "./Services/Xml/classes/class.ilXmlWriter.php"; */ class ilContainerReferenceXmlWriter extends ilXmlWriter { - /** - * @var ilSetting - */ - protected $settings; + /** + * @var ilSetting + */ + protected $settings; - const MODE_SOAP = 1; - const MODE_EXPORT = 2; - - private $mode = self::MODE_SOAP; - private $xml; - private $ref; + const MODE_SOAP = 1; + const MODE_EXPORT = 2; + + private $mode = self::MODE_SOAP; + private $xml; + private $ref; - /** - * constructor - * @param string xml version - * @param string output encoding - * @param string input encoding - * @access public - */ - public function __construct(ilContainerReference $ref = null) - { - global $DIC; + /** + * constructor + * @param string xml version + * @param string output encoding + * @param string input encoding + * @access public + */ + public function __construct(ilContainerReference $ref = null) + { + global $DIC; - $this->settings = $DIC->settings(); - parent::__construct(); - $this->ref = $ref; - } + $this->settings = $DIC->settings(); + parent::__construct(); + $this->ref = $ref; + } - /** - * Set export mode - * @param int $a_mode - */ - public function setMode($a_mode) - { - $this->mode = $a_mode; - } + /** + * 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 export mode + * @return int + */ + public function getMode() + { + return $this->mode; + } - /** - * Get category object - * @return ilContainerReference - */ - public function getReference() - { - return $this->ref; - } + /** + * Get category object + * @return ilContainerReference + */ + public function getReference() + { + return $this->ref; + } - /** - * Start wrting xml - */ - public function export($a_with_header = true) - { - if($this->getMode() == self::MODE_EXPORT) - { - if($a_with_header) - { - $this->buildHeader(); - } - $this->buildReference(); - $this->buildTarget(); - $this->buildTitle(); - $this->buildFooter(); - } - } + /** + * Start wrting xml + */ + public function export($a_with_header = true) + { + if ($this->getMode() == self::MODE_EXPORT) { + if ($a_with_header) { + $this->buildHeader(); + } + $this->buildReference(); + $this->buildTarget(); + $this->buildTitle(); + $this->buildFooter(); + } + } - /** - * get XML - * @return string - */ - public function getXml() - { - return $this->xmlDumpMem(false); - } + /** + * get XML + * @return string + */ + public function getXml() + { + return $this->xmlDumpMem(false); + } - /** - * Build xml header - * @return bool - */ - protected function buildHeader() - { - $ilSetting = $this->settings; + /** + * Build xml header + * @return bool + */ + protected function buildHeader() + { + $ilSetting = $this->settings; - $this->xmlSetDtdDef(""); - $this->xmlSetGenCmt("Export of ILIAS container reference ". $this->getReference()->getId()." of installation ".$ilSetting->get('inst_id')."."); - $this->xmlHeader(); + $this->xmlSetDtdDef(""); + $this->xmlSetGenCmt("Export of ILIAS container reference " . $this->getReference()->getId() . " of installation " . $ilSetting->get('inst_id') . "."); + $this->xmlHeader(); - return true; - } - - /** - * Build target element - */ - protected function buildTarget() - { - $this->xmlElement('Target', array('id' => $this->getReference()->getTargetId())); - } - - /** - * Build title element - */ - protected function buildTitle() - { - $title = ''; - if($this->getReference()->getTitleType() == ilContainerReference::TITLE_TYPE_CUSTOM) - { - $title = $this->getReference()->getTitle(); - } - - $this->xmlElement( - 'Title', - array( - 'type' => $this->getReference()->getTitleType() - ), - $title - ); - } + return true; + } + + /** + * Build target element + */ + protected function buildTarget() + { + $this->xmlElement('Target', array('id' => $this->getReference()->getTargetId())); + } + + /** + * Build title element + */ + protected function buildTitle() + { + $title = ''; + if ($this->getReference()->getTitleType() == ilContainerReference::TITLE_TYPE_CUSTOM) { + $title = $this->getReference()->getTitle(); + } + + $this->xmlElement( + 'Title', + array( + 'type' => $this->getReference()->getTitleType() + ), + $title + ); + } - /** - * Build category xml - */ - protected function buildReference() - { - $this->xmlStartTag('ContainerReference'); - } - - /** - * Add footer elements - */ - protected function buildFooter() - { - $this->xmlEndTag('ContainerReference'); - } + /** + * Build category xml + */ + protected function buildReference() + { + $this->xmlStartTag('ContainerReference'); + } + + /** + * Add footer elements + */ + protected function buildFooter() + { + $this->xmlEndTag('ContainerReference'); + } } -?> \ No newline at end of file diff --git a/Services/ContainerReference/classes/class.ilContainerSelectionExplorer.php b/Services/ContainerReference/classes/class.ilContainerSelectionExplorer.php index 546ce1566629103d4e66afeb56187cd9f6744def..cbbcc3112a6e395b6026fe54761b7e5ede5d82fe 100644 --- a/Services/ContainerReference/classes/class.ilContainerSelectionExplorer.php +++ b/Services/ContainerReference/classes/class.ilContainerSelectionExplorer.php @@ -1,155 +1,150 @@ * @version $Id$ -* * -* @ingroup +* +* @ingroup */ class ilContainerSelectionExplorer extends ilExplorer { - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - protected $target_type; - - /** - * Constructor - */ - public function __construct($a_target) - { - global $DIC; + protected $target_type; + + /** + * Constructor + */ + public function __construct($a_target) + { + global $DIC; - $this->access = $DIC->access(); - $this->lng = $DIC->language(); - $tree = $DIC->repositoryTree(); - - parent::__construct($a_target); - - $this->tree = $tree; - $this->root_id = $this->tree->readRootId(); - $this->order_column = "title"; + $this->access = $DIC->access(); + $this->lng = $DIC->language(); + $tree = $DIC->repositoryTree(); + + parent::__construct($a_target); + + $this->tree = $tree; + $this->root_id = $this->tree->readRootId(); + $this->order_column = "title"; - $this->setSessionExpandVariable("ref_repexpand"); - - - $this->addFilter("root"); - $this->addFilter("cat"); - $this->addFilter("grp"); - #$this->addFilter("fold"); - $this->addFilter("crs"); + $this->setSessionExpandVariable("ref_repexpand"); + + + $this->addFilter("root"); + $this->addFilter("cat"); + $this->addFilter("grp"); + #$this->addFilter("fold"); + $this->addFilter("crs"); - $this->setFilterMode(IL_FM_POSITIVE); - $this->setFiltered(true); - $this->setTitleLength(ilObject::TITLE_LENGTH); - - $this->checkPermissions(true); - - } - - /** - * set target type - * @param - * @return - */ - public function setTargetType($a_type) - { - $this->target_type = $a_type; - } - - /** - * get target type - * @param - * @return - */ - public function getTargetType() - { - return $this->target_type; - } - - /** - * check if item is clickable - * @param - * @return - */ - public function isClickable($a_type,$a_id = 0) - { - $ilAccess = $this->access; - - if($this->getTargetType() == $a_type) - { - if($ilAccess->checkAccess('visible','',$a_id)) - { - return true; - } - } - return FALSE; - } + $this->setFilterMode(IL_FM_POSITIVE); + $this->setFiltered(true); + $this->setTitleLength(ilObject::TITLE_LENGTH); + + $this->checkPermissions(true); + } + + /** + * set target type + * @param + * @return + */ + public function setTargetType($a_type) + { + $this->target_type = $a_type; + } + + /** + * get target type + * @param + * @return + */ + public function getTargetType() + { + return $this->target_type; + } + + /** + * check if item is clickable + * @param + * @return + */ + public function isClickable($a_type, $a_id = 0) + { + $ilAccess = $this->access; + + if ($this->getTargetType() == $a_type) { + if ($ilAccess->checkAccess('visible', '', $a_id)) { + return true; + } + } + return false; + } - /** - * Visible permission is sufficient - * @param type $a_ref_id - * @param type $a_type - * @return type - */ - public function isVisible($a_ref_id, $a_type) - { - $ilAccess = $this->access; - - return $ilAccess->checkAccess('visible','',$a_ref_id); - } - - /** - * overwritten method from base class - * @access public - * @param integer obj_id - * @param integer array options - */ - function formatHeader($a_tpl, $a_obj_id,$a_option) - { - $lng = $this->lng; + /** + * Visible permission is sufficient + * @param type $a_ref_id + * @param type $a_type + * @return type + */ + public function isVisible($a_ref_id, $a_type) + { + $ilAccess = $this->access; + + return $ilAccess->checkAccess('visible', '', $a_ref_id); + } + + /** + * overwritten method from base class + * @access public + * @param integer obj_id + * @param integer array options + */ + public function formatHeader($a_tpl, $a_obj_id, $a_option) + { + $lng = $this->lng; - $tpl = new ilTemplate("tpl.tree.html", true, true, "Services/UIComponent/Explorer"); + $tpl = new ilTemplate("tpl.tree.html", true, true, "Services/UIComponent/Explorer"); - $tpl->setCurrentBlock("text"); - $tpl->setVariable("OBJ_TITLE", $lng->txt("repository")); - $tpl->parseCurrentBlock(); + $tpl->setCurrentBlock("text"); + $tpl->setVariable("OBJ_TITLE", $lng->txt("repository")); + $tpl->parseCurrentBlock(); - $this->output[] = $tpl->get(); - } - + $this->output[] = $tpl->get(); + } } -?> diff --git a/Services/Context/classes/class.ilContext.php b/Services/Context/classes/class.ilContext.php index e244e3c806143a77504bb27cc603b17aedcf2264..c15e17c3fd5d98c8e16a4e2b8abf93c4fc9ff7ce 100644 --- a/Services/Context/classes/class.ilContext.php +++ b/Services/Context/classes/class.ilContext.php @@ -1,215 +1,208 @@ - - * @author Stefan Hecken - * @version $Id$ - * - * @ingroup ServicesContext - */ -class ilContext -{ - protected static $class_name; // [string] - protected static $type; // [string] - - const CONTEXT_WEB = "ilContextWeb"; - const CONTEXT_CRON = "ilContextCron"; - const CONTEXT_RSS = "ilContextRss"; - const CONTEXT_ICAL = "ilContextIcal"; - const CONTEXT_SOAP = "ilContextSoap"; - const CONTEXT_SOAP_NO_AUTH = 'ilContextSoapNoAuth'; - const CONTEXT_WEBDAV = "ilContextWebdav"; - const CONTEXT_RSS_AUTH = "ilContextRssAuth"; - const CONTEXT_SESSION_REMINDER = "ilContextSessionReminder"; - const CONTEXT_SOAP_WITHOUT_CLIENT = "ilContextSoapWithoutClient"; - const CONTEXT_UNITTEST = "ilContextUnitTest"; - const CONTEXT_REST = "ilContextRest"; - const CONTEXT_SCORM = "ilContextScorm"; - const CONTEXT_WAC = "ilContextWAC"; - const CONTEXT_APACHE_SSO = 'ilContextApacheSSO'; - const CONTEXT_SHIBBOLETH = 'ilContextShibboleth'; - const CONTEXT_LTI_PROVIDER = 'ilContextLTIProvider'; - const CONTEXT_SAML = 'ilContextSaml'; - - - /** - * Init context by type - * - * @param string $a_type - * @return bool - */ - public static function init($a_type) - { - include_once "Services/Context/classes/class.".$a_type.".php"; - self::$class_name = $a_type; - self::$type = $a_type; - - return true; - } - - /** - * Call context method directly without internal handling - * - * @param int $a_type - * @return mixed - */ - public static function directCall($a_type, $a_method) - { - $class_name = $a_type; - if($class_name) - { - include_once "Services/Context/classes/class.".$class_name.".php"; - if(method_exists($class_name, $a_method)) - { - return call_user_func(array($class_name, $a_method)); - } - } - } - - /** - * Call current content - * - * @param string $a_method - * @return bool - */ - protected static function callContext($a_method) - { - if(!self::$class_name) - { - self::init(self::CONTEXT_WEB); - } - return call_user_func(array(self::$class_name, $a_method)); - } - - /** - * Are redirects supported? - * - * @return bool - */ - public static function supportsRedirects() - { - global $DIC; - - $ilCtrl = null; - if (isset($DIC["ilCtrl"])) - { - $ilCtrl = $DIC->ctrl(); - } - - // asynchronous calls must never be redirected - if($ilCtrl && $ilCtrl->isAsynch()) - { - return false; - } - - return (bool)self::callContext("supportsRedirects"); - } - - /** - * Based on user authentication? - * - * @return bool - */ - public static function hasUser() - { - return (bool)self::callContext("hasUser"); - } - - /** - * Uses HTTP aka browser - * - * @return bool - */ - public static function usesHTTP() - { - return (bool)self::callContext("usesHTTP"); - } - - /** - * Has HTML output - * - * @return bool - */ - public static function hasHTML() - { - return (bool)self::callContext("hasHTML"); - } - - /** - * Uses template engine - * - * @return bool - */ - public static function usesTemplate() - { - return (bool)self::callContext("usesTemplate"); - } - - /** - * Init client - * - * @return bool - */ - public static function initClient() - { - return (bool)self::callContext("initClient"); - } - - /** - * Try authentication - * - * @return bool - */ - public static function doAuthentication() - { - return (bool)self::callContext("doAuthentication"); - } - - /** - * Supports push messages - * - * @return bool - */ - public static function supportsPushMessages() - { - return (bool)self::callContext("supportsPushMessages"); - } - - /** - * Get context type - * - * @return string - */ - public static function getType() - { - return self::$type; - } - - /** - * Check if context supports persistent - * session handling. - * false for cli context - * - * @return bool - */ - public static function supportsPersistentSessions() - { - return (bool) self::callContext('supportsPersistentSessions'); - } - - /** - * Context that are not only temporary in a session (e.g. WAC is, Cron is not) - * - * @return bool - */ - public static function isSessionMainContext() - { - return (bool) self::callContext('isSessionMainContext'); - } -} - -?> + + * @author Stefan Hecken + * @version $Id$ + * + * @ingroup ServicesContext + */ +class ilContext +{ + protected static $class_name; // [string] + protected static $type; // [string] + + const CONTEXT_WEB = "ilContextWeb"; + const CONTEXT_CRON = "ilContextCron"; + const CONTEXT_RSS = "ilContextRss"; + const CONTEXT_ICAL = "ilContextIcal"; + const CONTEXT_SOAP = "ilContextSoap"; + const CONTEXT_SOAP_NO_AUTH = 'ilContextSoapNoAuth'; + const CONTEXT_WEBDAV = "ilContextWebdav"; + const CONTEXT_RSS_AUTH = "ilContextRssAuth"; + const CONTEXT_SESSION_REMINDER = "ilContextSessionReminder"; + const CONTEXT_SOAP_WITHOUT_CLIENT = "ilContextSoapWithoutClient"; + const CONTEXT_UNITTEST = "ilContextUnitTest"; + const CONTEXT_REST = "ilContextRest"; + const CONTEXT_SCORM = "ilContextScorm"; + const CONTEXT_WAC = "ilContextWAC"; + const CONTEXT_APACHE_SSO = 'ilContextApacheSSO'; + const CONTEXT_SHIBBOLETH = 'ilContextShibboleth'; + const CONTEXT_LTI_PROVIDER = 'ilContextLTIProvider'; + const CONTEXT_SAML = 'ilContextSaml'; + + + /** + * Init context by type + * + * @param string $a_type + * @return bool + */ + public static function init($a_type) + { + include_once "Services/Context/classes/class." . $a_type . ".php"; + self::$class_name = $a_type; + self::$type = $a_type; + + return true; + } + + /** + * Call context method directly without internal handling + * + * @param int $a_type + * @return mixed + */ + public static function directCall($a_type, $a_method) + { + $class_name = $a_type; + if ($class_name) { + include_once "Services/Context/classes/class." . $class_name . ".php"; + if (method_exists($class_name, $a_method)) { + return call_user_func(array($class_name, $a_method)); + } + } + } + + /** + * Call current content + * + * @param string $a_method + * @return bool + */ + protected static function callContext($a_method) + { + if (!self::$class_name) { + self::init(self::CONTEXT_WEB); + } + return call_user_func(array(self::$class_name, $a_method)); + } + + /** + * Are redirects supported? + * + * @return bool + */ + public static function supportsRedirects() + { + global $DIC; + + $ilCtrl = null; + if (isset($DIC["ilCtrl"])) { + $ilCtrl = $DIC->ctrl(); + } + + // asynchronous calls must never be redirected + if ($ilCtrl && $ilCtrl->isAsynch()) { + return false; + } + + return (bool) self::callContext("supportsRedirects"); + } + + /** + * Based on user authentication? + * + * @return bool + */ + public static function hasUser() + { + return (bool) self::callContext("hasUser"); + } + + /** + * Uses HTTP aka browser + * + * @return bool + */ + public static function usesHTTP() + { + return (bool) self::callContext("usesHTTP"); + } + + /** + * Has HTML output + * + * @return bool + */ + public static function hasHTML() + { + return (bool) self::callContext("hasHTML"); + } + + /** + * Uses template engine + * + * @return bool + */ + public static function usesTemplate() + { + return (bool) self::callContext("usesTemplate"); + } + + /** + * Init client + * + * @return bool + */ + public static function initClient() + { + return (bool) self::callContext("initClient"); + } + + /** + * Try authentication + * + * @return bool + */ + public static function doAuthentication() + { + return (bool) self::callContext("doAuthentication"); + } + + /** + * Supports push messages + * + * @return bool + */ + public static function supportsPushMessages() + { + return (bool) self::callContext("supportsPushMessages"); + } + + /** + * Get context type + * + * @return string + */ + public static function getType() + { + return self::$type; + } + + /** + * Check if context supports persistent + * session handling. + * false for cli context + * + * @return bool + */ + public static function supportsPersistentSessions() + { + return (bool) self::callContext('supportsPersistentSessions'); + } + + /** + * Context that are not only temporary in a session (e.g. WAC is, Cron is not) + * + * @return bool + */ + public static function isSessionMainContext() + { + return (bool) self::callContext('isSessionMainContext'); + } +} diff --git a/Services/Context/classes/class.ilContextApacheSSO.php b/Services/Context/classes/class.ilContextApacheSSO.php index a495779b701222aadeb5be88f80bf7763a2eedb1..44f935e4b445199fe32b95d9d9b199ca741e0fb5 100644 --- a/Services/Context/classes/class.ilContextApacheSSO.php +++ b/Services/Context/classes/class.ilContextApacheSSO.php @@ -4,113 +4,110 @@ include_once "Services/Context/interfaces/interface.ilContextTemplate.php"; -/** +/** * Service context for cron - * + * * @author Jörg Lützenkirchen * @version $Id$ - * + * * @ingroup ServicesContext */ class ilContextApacheSSO implements ilContextTemplate -{ - /** - * Are redirects supported? - * - * @return bool - */ - public static function supportsRedirects() - { - return true; - } - - /** - * Based on user authentication? - * - * @return bool - */ - public static function hasUser() - { - return true; - } - - /** - * Uses HTTP aka browser - * - * @return bool - */ - public static function usesHTTP() - { - return true; - } - - /** - * Has HTML output - * - * @return bool - */ - public static function hasHTML() - { - return true; - } - - /** - * Uses template engine - * - * @return bool - */ - public static function usesTemplate() - { - return true; - } - - /** - * Init client - * - * @return bool - */ - public static function initClient() - { - return true; - } - - /** - * Try authentication - * - * @return bool - */ - public static function doAuthentication() - { - return true; - } - - /** - * Check if persistent session handling is supported - * @return boolean - */ - public static function supportsPersistentSessions() - { - return true; - } +{ + /** + * Are redirects supported? + * + * @return bool + */ + public static function supportsRedirects() + { + return true; + } + + /** + * Based on user authentication? + * + * @return bool + */ + public static function hasUser() + { + return true; + } + + /** + * Uses HTTP aka browser + * + * @return bool + */ + public static function usesHTTP() + { + return true; + } + + /** + * Has HTML output + * + * @return bool + */ + public static function hasHTML() + { + return true; + } + + /** + * Uses template engine + * + * @return bool + */ + public static function usesTemplate() + { + return true; + } + + /** + * Init client + * + * @return bool + */ + public static function initClient() + { + return true; + } + + /** + * Try authentication + * + * @return bool + */ + public static function doAuthentication() + { + return true; + } + + /** + * Check if persistent session handling is supported + * @return boolean + */ + public static function supportsPersistentSessions() + { + return true; + } - /** - * Supports push messages - * - * @return bool - */ - public static function supportsPushMessages() - { - return false; - } - - /** - * @inheritdoc - */ - public static function isSessionMainContext() - { - return false; - } + /** + * Supports push messages + * + * @return bool + */ + public static function supportsPushMessages() + { + return false; + } + /** + * @inheritdoc + */ + public static function isSessionMainContext() + { + return false; + } } - -?> \ No newline at end of file diff --git a/Services/Context/classes/class.ilContextCron.php b/Services/Context/classes/class.ilContextCron.php index b16aa72c8b0ff119293b0f970a34a8eff2e561ba..a3a9a4f74123916dae69bc22ae8ec97357c0fe32 100644 --- a/Services/Context/classes/class.ilContextCron.php +++ b/Services/Context/classes/class.ilContextCron.php @@ -1,116 +1,113 @@ - - * @version $Id$ - * - * @ingroup ServicesContext - */ -class ilContextCron implements ilContextTemplate -{ - /** - * Are redirects supported? - * - * @return bool - */ - public static function supportsRedirects() - { - return false; - } - - /** - * Based on user authentication? - * - * @return bool - */ - public static function hasUser() - { - return true; - } - - /** - * Uses HTTP aka browser - * - * @return bool - */ - public static function usesHTTP() - { - return false; - } - - /** - * Has HTML output - * - * @return bool - */ - public static function hasHTML() - { - return false; - } - - /** - * Uses template engine - * - * @return bool - */ - public static function usesTemplate() - { - return false; - } - - /** - * Init client - * - * @return bool - */ - public static function initClient() - { - return true; - } - - /** - * Try authentication - * - * @return bool - */ - public static function doAuthentication() - { - return true; - } - - /** - * Check if persistent session handling is supported - * @return boolean - */ - public static function supportsPersistentSessions() - { - return false; - } - - /** - * Supports push messages - * - * @return bool - */ - public static function supportsPushMessages() - { - return false; - } - - /** - * @inheritdoc - */ - public static function isSessionMainContext() - { - return true; - } - -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @ingroup ServicesContext + */ +class ilContextCron implements ilContextTemplate +{ + /** + * Are redirects supported? + * + * @return bool + */ + public static function supportsRedirects() + { + return false; + } + + /** + * Based on user authentication? + * + * @return bool + */ + public static function hasUser() + { + return true; + } + + /** + * Uses HTTP aka browser + * + * @return bool + */ + public static function usesHTTP() + { + return false; + } + + /** + * Has HTML output + * + * @return bool + */ + public static function hasHTML() + { + return false; + } + + /** + * Uses template engine + * + * @return bool + */ + public static function usesTemplate() + { + return false; + } + + /** + * Init client + * + * @return bool + */ + public static function initClient() + { + return true; + } + + /** + * Try authentication + * + * @return bool + */ + public static function doAuthentication() + { + return true; + } + + /** + * Check if persistent session handling is supported + * @return boolean + */ + public static function supportsPersistentSessions() + { + return false; + } + + /** + * Supports push messages + * + * @return bool + */ + public static function supportsPushMessages() + { + return false; + } + + /** + * @inheritdoc + */ + public static function isSessionMainContext() + { + return true; + } +} diff --git a/Services/Context/classes/class.ilContextIcal.php b/Services/Context/classes/class.ilContextIcal.php index 391a9e99a69c09859b18975c62de842ccd2fedb1..41054cb6c26c466bc6ff192e0cd586ec9b05a70b 100644 --- a/Services/Context/classes/class.ilContextIcal.php +++ b/Services/Context/classes/class.ilContextIcal.php @@ -1,116 +1,113 @@ - - * @version $Id$ - * - * @ingroup ServicesContext - */ -class ilContextIcal implements ilContextTemplate -{ - /** - * Are redirects supported? - * - * @return bool - */ - public static function supportsRedirects() - { - return false; - } - - /** - * Based on user authentication? - * - * @return bool - */ - public static function hasUser() - { - return true; - } - - /** - * Uses HTTP aka browser - * - * @return bool - */ - public static function usesHTTP() - { - return true; - } - - /** - * Has HTML output - * - * @return bool - */ - public static function hasHTML() - { - return false; - } - - /** - * Uses template engine - * - * @return bool - */ - public static function usesTemplate() - { - return false; - } - - /** - * Init client - * - * @return bool - */ - public static function initClient() - { - return true; - } - - /** - * Try authentication - * - * @return bool - */ - public static function doAuthentication() - { - return false; - } - - /** - * Check if persistent session handling is supported - * @return boolean - */ - public static function supportsPersistentSessions() - { - return false; - } - - /** - * Supports push messages - * - * @return bool - */ - public static function supportsPushMessages() - { - return false; - } - - /** - * @inheritdoc - */ - public static function isSessionMainContext() - { - return true; - } - -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @ingroup ServicesContext + */ +class ilContextIcal implements ilContextTemplate +{ + /** + * Are redirects supported? + * + * @return bool + */ + public static function supportsRedirects() + { + return false; + } + + /** + * Based on user authentication? + * + * @return bool + */ + public static function hasUser() + { + return true; + } + + /** + * Uses HTTP aka browser + * + * @return bool + */ + public static function usesHTTP() + { + return true; + } + + /** + * Has HTML output + * + * @return bool + */ + public static function hasHTML() + { + return false; + } + + /** + * Uses template engine + * + * @return bool + */ + public static function usesTemplate() + { + return false; + } + + /** + * Init client + * + * @return bool + */ + public static function initClient() + { + return true; + } + + /** + * Try authentication + * + * @return bool + */ + public static function doAuthentication() + { + return false; + } + + /** + * Check if persistent session handling is supported + * @return boolean + */ + public static function supportsPersistentSessions() + { + return false; + } + + /** + * Supports push messages + * + * @return bool + */ + public static function supportsPushMessages() + { + return false; + } + + /** + * @inheritdoc + */ + public static function isSessionMainContext() + { + return true; + } +} diff --git a/Services/Context/classes/class.ilContextLTIProvider.php b/Services/Context/classes/class.ilContextLTIProvider.php index b6315edfb619c23a30df88f3e72e7fb30da10b87..643de454627823f644352c4f84b72cf67a1facd1 100644 --- a/Services/Context/classes/class.ilContextLTIProvider.php +++ b/Services/Context/classes/class.ilContextLTIProvider.php @@ -5,97 +5,95 @@ include_once "Services/Context/interfaces/interface.ilContextTemplate.php"; -/** +/** * Service context for LTI provider - * + * * @author Stefan Meyer - * + * * @ingroup ServicesContext */ class ilContextLTIProvider implements ilContextTemplate { - - /** - * Do authentication - */ - public static function doAuthentication() - { - return true; - } + + /** + * Do authentication + */ + public static function doAuthentication() + { + return true; + } - /** - * Has html - */ - public static function hasHTML() - { - return true; - } + /** + * Has html + */ + public static function hasHTML() + { + return true; + } - /** - * Has user (maybe?) - */ - public static function hasUser() - { - return true; - } + /** + * Has user (maybe?) + */ + public static function hasUser() + { + return true; + } - /** - * init client - */ - public static function initClient() - { - return true; - } + /** + * init client + */ + public static function initClient() + { + return true; + } - /** - * supports persistent session - */ - public static function supportsPersistentSessions() - { - return true; - } + /** + * supports persistent session + */ + public static function supportsPersistentSessions() + { + return true; + } - /** - * supports redirects - */ - public static function supportsRedirects() - { - return true; - } + /** + * supports redirects + */ + public static function supportsRedirects() + { + return true; + } - /** - * uses http - */ - public static function usesHTTP() - { - return true; - } + /** + * uses http + */ + public static function usesHTTP() + { + return true; + } - /** - * uses template - */ - public static function usesTemplate() - { - return true; - } + /** + * uses template + */ + public static function usesTemplate() + { + return true; + } - /** - * Supports push messages - * - * @return bool - */ - public static function supportsPushMessages() - { - return false; - } - - /** - * @inheritdoc - */ - public static function isSessionMainContext() - { - return false; - } + /** + * Supports push messages + * + * @return bool + */ + public static function supportsPushMessages() + { + return false; + } + /** + * @inheritdoc + */ + public static function isSessionMainContext() + { + return false; + } } -?> \ No newline at end of file diff --git a/Services/Context/classes/class.ilContextRest.php b/Services/Context/classes/class.ilContextRest.php index bf146d3d809f3430b3412a91b23d24c63bdb2f00..b163c37507069a8bbaad63c4c2e007ee388704d2 100644 --- a/Services/Context/classes/class.ilContextRest.php +++ b/Services/Context/classes/class.ilContextRest.php @@ -1,117 +1,114 @@ - - * @version $Id$ - * - * @ingroup ServicesContext - */ -class ilContextRest implements ilContextTemplate -{ - /** - * Are redirects supported? - * - * @return bool - */ - public static function supportsRedirects() - { - return false; - } - - /** - * Based on user authentication? - * - * @return bool - */ - public static function hasUser() - { - return false; - } - - /** - * Uses HTTP aka browser - * - * @return bool - */ - public static function usesHTTP() - { - return true; - } - - /** - * Has HTML output - * - * @return bool - */ - public static function hasHTML() - { - return false; - } - - /** - * Uses template engine - * - * @return bool - */ - public static function usesTemplate() - { - return false; - } - - /** - * Init client - * - * @return bool - */ - public static function initClient() - { - return true; - } - - /** - * Try authentication - * - * @return bool - */ - public static function doAuthentication() - { - return false; - } - - /** - * Check if persistent session handling is supported - * @return boolean - */ - public static function supportsPersistentSessions() - { - return false; - } - - - /** - * Supports push messages - * - * @return bool - */ - public static function supportsPushMessages() - { - return false; - } - - /** - * @inheritdoc - */ - public static function isSessionMainContext() - { - return true; - } - -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @ingroup ServicesContext + */ +class ilContextRest implements ilContextTemplate +{ + /** + * Are redirects supported? + * + * @return bool + */ + public static function supportsRedirects() + { + return false; + } + + /** + * Based on user authentication? + * + * @return bool + */ + public static function hasUser() + { + return false; + } + + /** + * Uses HTTP aka browser + * + * @return bool + */ + public static function usesHTTP() + { + return true; + } + + /** + * Has HTML output + * + * @return bool + */ + public static function hasHTML() + { + return false; + } + + /** + * Uses template engine + * + * @return bool + */ + public static function usesTemplate() + { + return false; + } + + /** + * Init client + * + * @return bool + */ + public static function initClient() + { + return true; + } + + /** + * Try authentication + * + * @return bool + */ + public static function doAuthentication() + { + return false; + } + + /** + * Check if persistent session handling is supported + * @return boolean + */ + public static function supportsPersistentSessions() + { + return false; + } + + + /** + * Supports push messages + * + * @return bool + */ + public static function supportsPushMessages() + { + return false; + } + + /** + * @inheritdoc + */ + public static function isSessionMainContext() + { + return true; + } +} diff --git a/Services/Context/classes/class.ilContextRss.php b/Services/Context/classes/class.ilContextRss.php index d19b5f8c3494463a6ddb8a88ce01e4a7e97934fe..d74c9fddde3b5a0d51e98cd5ccc6e2378e74570c 100644 --- a/Services/Context/classes/class.ilContextRss.php +++ b/Services/Context/classes/class.ilContextRss.php @@ -1,117 +1,114 @@ - - * @version $Id$ - * - * @ingroup ServicesContext - */ -class ilContextRss implements ilContextTemplate -{ - /** - * Are redirects supported? - * - * @return bool - */ - public static function supportsRedirects() - { - return false; - } - - /** - * Based on user authentication? - * - * @return bool - */ - public static function hasUser() - { - return true; - } - - /** - * Uses HTTP aka browser - * - * @return bool - */ - public static function usesHTTP() - { - return true; - } - - /** - * Has HTML output - * - * @return bool - */ - public static function hasHTML() - { - return true; - } - - /** - * Uses template engine - * - * @return bool - */ - public static function usesTemplate() - { - return true; - } - - /** - * Init client - * - * @return bool - */ - public static function initClient() - { - return true; - } - - /** - * Try authentication - * - * @return bool - */ - public static function doAuthentication() - { - return false; - } - - /** - * Check if persistent session handling is supported - * @return boolean - */ - public static function supportsPersistentSessions() - { - return false; - } - - - /** - * Supports push messages - * - * @return bool - */ - public static function supportsPushMessages() - { - return false; - } - - /** - * @inheritdoc - */ - public static function isSessionMainContext() - { - return true; - } - -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @ingroup ServicesContext + */ +class ilContextRss implements ilContextTemplate +{ + /** + * Are redirects supported? + * + * @return bool + */ + public static function supportsRedirects() + { + return false; + } + + /** + * Based on user authentication? + * + * @return bool + */ + public static function hasUser() + { + return true; + } + + /** + * Uses HTTP aka browser + * + * @return bool + */ + public static function usesHTTP() + { + return true; + } + + /** + * Has HTML output + * + * @return bool + */ + public static function hasHTML() + { + return true; + } + + /** + * Uses template engine + * + * @return bool + */ + public static function usesTemplate() + { + return true; + } + + /** + * Init client + * + * @return bool + */ + public static function initClient() + { + return true; + } + + /** + * Try authentication + * + * @return bool + */ + public static function doAuthentication() + { + return false; + } + + /** + * Check if persistent session handling is supported + * @return boolean + */ + public static function supportsPersistentSessions() + { + return false; + } + + + /** + * Supports push messages + * + * @return bool + */ + public static function supportsPushMessages() + { + return false; + } + + /** + * @inheritdoc + */ + public static function isSessionMainContext() + { + return true; + } +} diff --git a/Services/Context/classes/class.ilContextRssAuth.php b/Services/Context/classes/class.ilContextRssAuth.php index c2e000976eaa0a3819fe392ed0b3551b2459b187..34bee2d001dc3188231cda480e2112d09025d915 100644 --- a/Services/Context/classes/class.ilContextRssAuth.php +++ b/Services/Context/classes/class.ilContextRssAuth.php @@ -1,117 +1,114 @@ - - * @version $Id$ - * - * @ingroup ServicesContext - */ -class ilContextRssAuth implements ilContextTemplate -{ - /** - * Are redirects supported? - * - * @return bool - */ - public static function supportsRedirects() - { - return false; - } - - /** - * Based on user authentication? - * - * @return bool - */ - public static function hasUser() - { - return true; - } - - /** - * Uses HTTP aka browser - * - * @return bool - */ - public static function usesHTTP() - { - return true; - } - - /** - * Has HTML output - * - * @return bool - */ - public static function hasHTML() - { - return true; - } - - /** - * Uses template engine - * - * @return bool - */ - public static function usesTemplate() - { - return true; - } - - /** - * Init client - * - * @return bool - */ - public static function initClient() - { - return true; - } - - /** - * Try authentication - * - * @return bool - */ - public static function doAuthentication() - { - return false; - } - - /** - * Check if persistent session handling is supported - * @return boolean - */ - public static function supportsPersistentSessions() - { - return false; - } - - - /** - * Supports push messages - * - * @return bool - */ - public static function supportsPushMessages() - { - return false; - } - - /** - * @inheritdoc - */ - public static function isSessionMainContext() - { - return true; - } - -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @ingroup ServicesContext + */ +class ilContextRssAuth implements ilContextTemplate +{ + /** + * Are redirects supported? + * + * @return bool + */ + public static function supportsRedirects() + { + return false; + } + + /** + * Based on user authentication? + * + * @return bool + */ + public static function hasUser() + { + return true; + } + + /** + * Uses HTTP aka browser + * + * @return bool + */ + public static function usesHTTP() + { + return true; + } + + /** + * Has HTML output + * + * @return bool + */ + public static function hasHTML() + { + return true; + } + + /** + * Uses template engine + * + * @return bool + */ + public static function usesTemplate() + { + return true; + } + + /** + * Init client + * + * @return bool + */ + public static function initClient() + { + return true; + } + + /** + * Try authentication + * + * @return bool + */ + public static function doAuthentication() + { + return false; + } + + /** + * Check if persistent session handling is supported + * @return boolean + */ + public static function supportsPersistentSessions() + { + return false; + } + + + /** + * Supports push messages + * + * @return bool + */ + public static function supportsPushMessages() + { + return false; + } + + /** + * @inheritdoc + */ + public static function isSessionMainContext() + { + return true; + } +} diff --git a/Services/Context/classes/class.ilContextSaml.php b/Services/Context/classes/class.ilContextSaml.php index d4d1f26326c07adbb3aa737ceb5d40485f355a1d..23ccf97eebb744b40995705a6a465ab3a0afe3e6 100644 --- a/Services/Context/classes/class.ilContextSaml.php +++ b/Services/Context/classes/class.ilContextSaml.php @@ -8,86 +8,85 @@ require_once 'Services/Context/interfaces/interface.ilContextTemplate.php'; */ class ilContextSaml implements ilContextTemplate { - /** - * @inheritdoc - */ - public static function supportsRedirects() - { - return true; - } + /** + * @inheritdoc + */ + public static function supportsRedirects() + { + return true; + } - /** - * @inheritdoc - */ - public static function hasUser() - { - return true; - } + /** + * @inheritdoc + */ + public static function hasUser() + { + return true; + } - /** - * @inheritdoc - */ - public static function usesHTTP() - { - return true; - } + /** + * @inheritdoc + */ + public static function usesHTTP() + { + return true; + } - /** - * @inheritdoc - */ - public static function hasHTML() - { - return true; - } + /** + * @inheritdoc + */ + public static function hasHTML() + { + return true; + } - /** - * @inheritdoc - */ - public static function usesTemplate() - { - return true; - } + /** + * @inheritdoc + */ + public static function usesTemplate() + { + return true; + } - /** - * @inheritdoc - */ - public static function initClient() - { - return true; - } + /** + * @inheritdoc + */ + public static function initClient() + { + return true; + } - /** - * @inheritdoc - */ - public static function doAuthentication() - { - return true; - } + /** + * @inheritdoc + */ + public static function doAuthentication() + { + return true; + } - /** - * @inheritdoc - */ - public static function supportsPersistentSessions() - { - return true; - } + /** + * @inheritdoc + */ + public static function supportsPersistentSessions() + { + return true; + } - /** - * Supports push messages - * - * @return bool - */ - public static function supportsPushMessages() - { - return false; - } + /** + * Supports push messages + * + * @return bool + */ + public static function supportsPushMessages() + { + return false; + } - /** - * @inheritdoc - */ - public static function isSessionMainContext() - { - return false; - } - -} \ No newline at end of file + /** + * @inheritdoc + */ + public static function isSessionMainContext() + { + return false; + } +} diff --git a/Services/Context/classes/class.ilContextScorm.php b/Services/Context/classes/class.ilContextScorm.php index 485b3324b53ea472baabb0a8b99ceca7d09eb292..25a5c199bdd815ae7d3e53a12b2761fc60121dec 100644 --- a/Services/Context/classes/class.ilContextScorm.php +++ b/Services/Context/classes/class.ilContextScorm.php @@ -1,116 +1,113 @@ - - * @version $Id$ - * - * @ingroup ServicesContext - */ -class ilContextScorm implements ilContextTemplate -{ - /** - * Are redirects supported? - * - * @return bool - */ - public static function supportsRedirects() - { - return false; - } - - /** - * Based on user authentication? - * - * @return bool - */ - public static function hasUser() - { - return true; - } - - /** - * Uses HTTP aka browser - * - * @return bool - */ - public static function usesHTTP() - { - return false; - } - - /** - * Has HTML output - * - * @return bool - */ - public static function hasHTML() - { - return false; - } - - /** - * Uses template engine - * - * @return bool - */ - public static function usesTemplate() - { - return false; - } - - /** - * Init client - * - * @return bool - */ - public static function initClient() - { - return true; - } - - /** - * Try authentication - * - * @return bool - */ - public static function doAuthentication() - { - return false; - } - - /** - * Check if persistent session handling is supported - * @return boolean - */ - public static function supportsPersistentSessions() - { - return false; - } - - /** - * Supports push messages - * - * @return bool - */ - public static function supportsPushMessages() - { - return false; - } - - /** - * @inheritdoc - */ - public static function isSessionMainContext() - { - return false; - } - -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @ingroup ServicesContext + */ +class ilContextScorm implements ilContextTemplate +{ + /** + * Are redirects supported? + * + * @return bool + */ + public static function supportsRedirects() + { + return false; + } + + /** + * Based on user authentication? + * + * @return bool + */ + public static function hasUser() + { + return true; + } + + /** + * Uses HTTP aka browser + * + * @return bool + */ + public static function usesHTTP() + { + return false; + } + + /** + * Has HTML output + * + * @return bool + */ + public static function hasHTML() + { + return false; + } + + /** + * Uses template engine + * + * @return bool + */ + public static function usesTemplate() + { + return false; + } + + /** + * Init client + * + * @return bool + */ + public static function initClient() + { + return true; + } + + /** + * Try authentication + * + * @return bool + */ + public static function doAuthentication() + { + return false; + } + + /** + * Check if persistent session handling is supported + * @return boolean + */ + public static function supportsPersistentSessions() + { + return false; + } + + /** + * Supports push messages + * + * @return bool + */ + public static function supportsPushMessages() + { + return false; + } + + /** + * @inheritdoc + */ + public static function isSessionMainContext() + { + return false; + } +} diff --git a/Services/Context/classes/class.ilContextSessionReminder.php b/Services/Context/classes/class.ilContextSessionReminder.php index becf3fc1d427fa932982c80980e6a6e50e091abe..bba3b88933acb1ec23fa1754286eeb74f0e539eb 100644 --- a/Services/Context/classes/class.ilContextSessionReminder.php +++ b/Services/Context/classes/class.ilContextSessionReminder.php @@ -1,116 +1,113 @@ - - * @version $Id$ - * - * @ingroup ServicesContext - */ -class ilContextSessionReminder implements ilContextTemplate -{ - /** - * Are redirects supported? - * - * @return bool - */ - public static function supportsRedirects() - { - return false; - } - - /** - * Based on user authentication? - * - * @return bool - */ - public static function hasUser() - { - return false; - } - - /** - * Uses HTTP aka browser - * - * @return bool - */ - public static function usesHTTP() - { - return true; - } - - /** - * Has HTML output - * - * @return bool - */ - public static function hasHTML() - { - return false; - } - - /** - * Uses template engine - * - * @return bool - */ - public static function usesTemplate() - { - return false; - } - - /** - * Init client - * - * @return bool - */ - public static function initClient() - { - return true; - } - - /** - * Try authentication - * - * @return bool - */ - public static function doAuthentication() - { - return false; - } - - /** - * Check if persistent session handling is supported - * @return boolean - */ - public static function supportsPersistentSessions() - { - return false; - } - - /** - * Supports push messages - * - * @return bool - */ - public static function supportsPushMessages() - { - return false; - } - - /** - * @inheritdoc - */ - public static function isSessionMainContext() - { - return false; - } - -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @ingroup ServicesContext + */ +class ilContextSessionReminder implements ilContextTemplate +{ + /** + * Are redirects supported? + * + * @return bool + */ + public static function supportsRedirects() + { + return false; + } + + /** + * Based on user authentication? + * + * @return bool + */ + public static function hasUser() + { + return false; + } + + /** + * Uses HTTP aka browser + * + * @return bool + */ + public static function usesHTTP() + { + return true; + } + + /** + * Has HTML output + * + * @return bool + */ + public static function hasHTML() + { + return false; + } + + /** + * Uses template engine + * + * @return bool + */ + public static function usesTemplate() + { + return false; + } + + /** + * Init client + * + * @return bool + */ + public static function initClient() + { + return true; + } + + /** + * Try authentication + * + * @return bool + */ + public static function doAuthentication() + { + return false; + } + + /** + * Check if persistent session handling is supported + * @return boolean + */ + public static function supportsPersistentSessions() + { + return false; + } + + /** + * Supports push messages + * + * @return bool + */ + public static function supportsPushMessages() + { + return false; + } + + /** + * @inheritdoc + */ + public static function isSessionMainContext() + { + return false; + } +} diff --git a/Services/Context/classes/class.ilContextShibboleth.php b/Services/Context/classes/class.ilContextShibboleth.php index e8c4252877fce8a5d7a6bff6df047d0c6bbfd900..e424d6d94fdfd633a1f0dbd300a3f51718af0075 100644 --- a/Services/Context/classes/class.ilContextShibboleth.php +++ b/Services/Context/classes/class.ilContextShibboleth.php @@ -4,114 +4,110 @@ include_once "Services/Context/interfaces/interface.ilContextTemplate.php"; -/** +/** * Service context for cron - * + * * @author Jörg Lützenkirchen * @version $Id$ - * + * * @ingroup ServicesContext */ class ilContextShibboleth implements ilContextTemplate -{ - /** - * Are redirects supported? - * - * @return bool - */ - public static function supportsRedirects() - { - return true; - } - - /** - * Based on user authentication? - * - * @return bool - */ - public static function hasUser() - { - return true; - } - - /** - * Uses HTTP aka browser - * - * @return bool - */ - public static function usesHTTP() - { - return true; - } - - /** - * Has HTML output - * - * @return bool - */ - public static function hasHTML() - { - return true; - } - - /** - * Uses template engine - * - * @return bool - */ - public static function usesTemplate() - { - return true; - } - - /** - * Init client - * - * @return bool - */ - public static function initClient() - { - return true; - } - - /** - * Try authentication - * - * @return bool - */ - public static function doAuthentication() - { - return true; - } - - /** - * Check if persistent session handling is supported - * @return boolean - */ - public static function supportsPersistentSessions() - { - return true; - } - - /** - * Supports push messages - * - * @return bool - */ - public static function supportsPushMessages() - { - return false; - } - - /** - * @inheritdoc - */ - public static function isSessionMainContext() - { - return false; - } +{ + /** + * Are redirects supported? + * + * @return bool + */ + public static function supportsRedirects() + { + return true; + } + + /** + * Based on user authentication? + * + * @return bool + */ + public static function hasUser() + { + return true; + } + + /** + * Uses HTTP aka browser + * + * @return bool + */ + public static function usesHTTP() + { + return true; + } + + /** + * Has HTML output + * + * @return bool + */ + public static function hasHTML() + { + return true; + } + + /** + * Uses template engine + * + * @return bool + */ + public static function usesTemplate() + { + return true; + } + + /** + * Init client + * + * @return bool + */ + public static function initClient() + { + return true; + } + + /** + * Try authentication + * + * @return bool + */ + public static function doAuthentication() + { + return true; + } + + /** + * Check if persistent session handling is supported + * @return boolean + */ + public static function supportsPersistentSessions() + { + return true; + } + /** + * Supports push messages + * + * @return bool + */ + public static function supportsPushMessages() + { + return false; + } + /** + * @inheritdoc + */ + public static function isSessionMainContext() + { + return false; + } } - -?> \ No newline at end of file diff --git a/Services/Context/classes/class.ilContextSoap.php b/Services/Context/classes/class.ilContextSoap.php index ae5a76287b5c978e22b7a19635bddcf65d6d76d1..b681fb043b630557b405301b9ba5d0eca55ef9cc 100644 --- a/Services/Context/classes/class.ilContextSoap.php +++ b/Services/Context/classes/class.ilContextSoap.php @@ -1,116 +1,113 @@ - - * @version $Id$ - * - * @ingroup ServicesContext - */ -class ilContextSoap implements ilContextTemplate -{ - /** - * Are redirects supported? - * - * @return bool - */ - public static function supportsRedirects() - { - return false; - } - - /** - * Based on user authentication? - * - * @return bool - */ - public static function hasUser() - { - return true; - } - - /** - * Uses HTTP aka browser - * - * @return bool - */ - public static function usesHTTP() - { - return true; - } - - /** - * Has HTML output - * - * @return bool - */ - public static function hasHTML() - { - return true; - } - - /** - * Uses template engine - * - * @return bool - */ - public static function usesTemplate() - { - return true; - } - - /** - * Init client - * - * @return bool - */ - public static function initClient() - { - return true; - } - - /** - * Try authentication - * - * @return bool - */ - public static function doAuthentication() - { - return false; - } - - /** - * Check if persistent session handling is supported - * @return boolean - */ - public static function supportsPersistentSessions() - { - return true; - } - - /** - * Supports push messages - * - * @return bool - */ - public static function supportsPushMessages() - { - return false; - } - - /** - * @inheritdoc - */ - public static function isSessionMainContext() - { - return true; - } - -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @ingroup ServicesContext + */ +class ilContextSoap implements ilContextTemplate +{ + /** + * Are redirects supported? + * + * @return bool + */ + public static function supportsRedirects() + { + return false; + } + + /** + * Based on user authentication? + * + * @return bool + */ + public static function hasUser() + { + return true; + } + + /** + * Uses HTTP aka browser + * + * @return bool + */ + public static function usesHTTP() + { + return true; + } + + /** + * Has HTML output + * + * @return bool + */ + public static function hasHTML() + { + return true; + } + + /** + * Uses template engine + * + * @return bool + */ + public static function usesTemplate() + { + return true; + } + + /** + * Init client + * + * @return bool + */ + public static function initClient() + { + return true; + } + + /** + * Try authentication + * + * @return bool + */ + public static function doAuthentication() + { + return false; + } + + /** + * Check if persistent session handling is supported + * @return boolean + */ + public static function supportsPersistentSessions() + { + return true; + } + + /** + * Supports push messages + * + * @return bool + */ + public static function supportsPushMessages() + { + return false; + } + + /** + * @inheritdoc + */ + public static function isSessionMainContext() + { + return true; + } +} diff --git a/Services/Context/classes/class.ilContextSoapNoAuth.php b/Services/Context/classes/class.ilContextSoapNoAuth.php index 03db0ed861df5cf1c43954fa833ae12262efcbbf..6f877d79573b7bf7863aa6fb12ec81be5137239c 100644 --- a/Services/Context/classes/class.ilContextSoapNoAuth.php +++ b/Services/Context/classes/class.ilContextSoapNoAuth.php @@ -1,84 +1,92 @@ - - * @version $Id$ - * - * @ingroup ServicesContext - */ -class ilContextSoapWithoutClient implements ilContextTemplate -{ - /** - * Are redirects supported? - * - * @return bool - */ - public static function supportsRedirects() - { - return false; - } - - /** - * Based on user authentication? - * - * @return bool - */ - public static function hasUser() - { - return true; - } - - /** - * Uses HTTP aka browser - * - * @return bool - */ - public static function usesHTTP() - { - return true; - } - - /** - * Has HTML output - * - * @return bool - */ - public static function hasHTML() - { - return false; - } - - /** - * Uses template engine - * - * @return bool - */ - public static function usesTemplate() - { - return false; - } - - /** - * Init client - * - * @return bool - */ - public static function initClient() - { - return false; - } - - /** - * Try authentication - * - * @return bool - */ - public static function doAuthentication() - { - return false; - } - - /** - * Check if persistent session handling is supported - * @return boolean - */ - public static function supportsPersistentSessions() - { - return false; - } - - /** - * Supports push messages - * - * @return bool - */ - public static function supportsPushMessages() - { - return false; - } - - /** - * @inheritdoc - */ - public static function isSessionMainContext() - { - return true; - } - -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @ingroup ServicesContext + */ +class ilContextSoapWithoutClient implements ilContextTemplate +{ + /** + * Are redirects supported? + * + * @return bool + */ + public static function supportsRedirects() + { + return false; + } + + /** + * Based on user authentication? + * + * @return bool + */ + public static function hasUser() + { + return true; + } + + /** + * Uses HTTP aka browser + * + * @return bool + */ + public static function usesHTTP() + { + return true; + } + + /** + * Has HTML output + * + * @return bool + */ + public static function hasHTML() + { + return false; + } + + /** + * Uses template engine + * + * @return bool + */ + public static function usesTemplate() + { + return false; + } + + /** + * Init client + * + * @return bool + */ + public static function initClient() + { + return false; + } + + /** + * Try authentication + * + * @return bool + */ + public static function doAuthentication() + { + return false; + } + + /** + * Check if persistent session handling is supported + * @return boolean + */ + public static function supportsPersistentSessions() + { + return false; + } + + /** + * Supports push messages + * + * @return bool + */ + public static function supportsPushMessages() + { + return false; + } + + /** + * @inheritdoc + */ + public static function isSessionMainContext() + { + return true; + } +} diff --git a/Services/Context/classes/class.ilContextUnitTest.php b/Services/Context/classes/class.ilContextUnitTest.php index ee49f6e3f21d6d6a9cc045c85615c676ffe465dc..f2169b3643b4a58174ae652d359536cca9a14375 100644 --- a/Services/Context/classes/class.ilContextUnitTest.php +++ b/Services/Context/classes/class.ilContextUnitTest.php @@ -1,116 +1,113 @@ - - * @version $Id$ - * - * @ingroup ServicesContext - */ -class ilContextUnitTest implements ilContextTemplate -{ - /** - * Are redirects supported? - * - * @return bool - */ - public static function supportsRedirects() - { - return false; - } - - /** - * Based on user authentication? - * - * @return bool - */ - public static function hasUser() - { - return true; - } - - /** - * Uses HTTP aka browser - * - * @return bool - */ - public static function usesHTTP() - { - return false; - } - - /** - * Has HTML output - * - * @return bool - */ - public static function hasHTML() - { - return false; - } - - /** - * Uses template engine - * - * @return bool - */ - public static function usesTemplate() - { - return false; - } - - /** - * Init client - * - * @return bool - */ - public static function initClient() - { - return true; - } - - /** - * Try authentication - * - * @return bool - */ - public static function doAuthentication() - { - return false; - } - - /** - * Check if persistent session handling is supported - * @return boolean - */ - public static function supportsPersistentSessions() - { - return false; - } - - /** - * Supports push messages - * - * @return bool - */ - public static function supportsPushMessages() - { - return false; - } - - /** - * @inheritdoc - */ - public static function isSessionMainContext() - { - return true; - } - -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @ingroup ServicesContext + */ +class ilContextUnitTest implements ilContextTemplate +{ + /** + * Are redirects supported? + * + * @return bool + */ + public static function supportsRedirects() + { + return false; + } + + /** + * Based on user authentication? + * + * @return bool + */ + public static function hasUser() + { + return true; + } + + /** + * Uses HTTP aka browser + * + * @return bool + */ + public static function usesHTTP() + { + return false; + } + + /** + * Has HTML output + * + * @return bool + */ + public static function hasHTML() + { + return false; + } + + /** + * Uses template engine + * + * @return bool + */ + public static function usesTemplate() + { + return false; + } + + /** + * Init client + * + * @return bool + */ + public static function initClient() + { + return true; + } + + /** + * Try authentication + * + * @return bool + */ + public static function doAuthentication() + { + return false; + } + + /** + * Check if persistent session handling is supported + * @return boolean + */ + public static function supportsPersistentSessions() + { + return false; + } + + /** + * Supports push messages + * + * @return bool + */ + public static function supportsPushMessages() + { + return false; + } + + /** + * @inheritdoc + */ + public static function isSessionMainContext() + { + return true; + } +} diff --git a/Services/Context/classes/class.ilContextWAC.php b/Services/Context/classes/class.ilContextWAC.php index 862ccc49036ceefbb52e452d2836ef49ba7265e6..6a0c4c8a4346c17307412fe2fed967d13a75baea 100644 --- a/Services/Context/classes/class.ilContextWAC.php +++ b/Services/Context/classes/class.ilContextWAC.php @@ -1,98 +1,103 @@ - - */ -class ilContextWAC implements ilContextTemplate { - - /** - * @return bool - */ - public static function supportsRedirects() { - return false; - } - - - /** - * @return bool - */ - public static function hasUser() { - return true; - } - - - /** - * @return bool - */ - public static function usesHTTP() { - return true; - } - - - /** - * @return bool - */ - public static function hasHTML() { - return true; - } - - - /** - * @return bool - */ - public static function usesTemplate() { - return true; - } - - - /** - * @return bool - */ - public static function initClient() { - return true; - } - - - /** - * @return bool - */ - public static function doAuthentication() { - return true; - } - - /** - * Check if persistent session handling is supported - * @return boolean - */ - public static function supportsPersistentSessions() - { - return true; - } - - /** - * Supports push messages - * - * @return bool - */ - public static function supportsPushMessages() - { - return false; - } - - /** - * @inheritdoc - */ - public static function isSessionMainContext() - { - return false; - } - -} - -?> \ No newline at end of file + + */ +class ilContextWAC implements ilContextTemplate +{ + + /** + * @return bool + */ + public static function supportsRedirects() + { + return false; + } + + + /** + * @return bool + */ + public static function hasUser() + { + return true; + } + + + /** + * @return bool + */ + public static function usesHTTP() + { + return true; + } + + + /** + * @return bool + */ + public static function hasHTML() + { + return true; + } + + + /** + * @return bool + */ + public static function usesTemplate() + { + return true; + } + + + /** + * @return bool + */ + public static function initClient() + { + return true; + } + + + /** + * @return bool + */ + public static function doAuthentication() + { + return true; + } + + /** + * Check if persistent session handling is supported + * @return boolean + */ + public static function supportsPersistentSessions() + { + return true; + } + + /** + * Supports push messages + * + * @return bool + */ + public static function supportsPushMessages() + { + return false; + } + + /** + * @inheritdoc + */ + public static function isSessionMainContext() + { + return false; + } +} diff --git a/Services/Context/classes/class.ilContextWeb.php b/Services/Context/classes/class.ilContextWeb.php index 7fc99e97ad7566265bb802ef085a263492906f31..2143ee19e855cf60c4e1aa354b5f9a285636359f 100644 --- a/Services/Context/classes/class.ilContextWeb.php +++ b/Services/Context/classes/class.ilContextWeb.php @@ -1,116 +1,113 @@ - - * @version $Id$ - * - * @ingroup ServicesContext - */ -class ilContextWeb implements ilContextTemplate -{ - /** - * Are redirects supported? - * - * @return bool - */ - public static function supportsRedirects() - { - return true; - } - - /** - * Based on user authentication? - * - * @return bool - */ - public static function hasUser() - { - return true; - } - - /** - * Uses HTTP aka browser - * - * @return bool - */ - public static function usesHTTP() - { - return true; - } - - /** - * Has HTML output - * - * @return bool - */ - public static function hasHTML() - { - return true; - } - - /** - * Uses template engine - * - * @return bool - */ - public static function usesTemplate() - { - return true; - } - - /** - * Init client - * - * @return bool - */ - public static function initClient() - { - return true; - } - - /** - * Try authentication - * - * @return bool - */ - public static function doAuthentication() - { - return false; - } - - /** - * Check if persistent session handling is supported - * @return boolean - */ - public static function supportsPersistentSessions() - { - return true; - } - - /** - * Supports push messages - * - * @return bool - */ - public static function supportsPushMessages() - { - return true; - } - - /** - * @inheritdoc - */ - public static function isSessionMainContext() - { - return true; - } - -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @ingroup ServicesContext + */ +class ilContextWeb implements ilContextTemplate +{ + /** + * Are redirects supported? + * + * @return bool + */ + public static function supportsRedirects() + { + return true; + } + + /** + * Based on user authentication? + * + * @return bool + */ + public static function hasUser() + { + return true; + } + + /** + * Uses HTTP aka browser + * + * @return bool + */ + public static function usesHTTP() + { + return true; + } + + /** + * Has HTML output + * + * @return bool + */ + public static function hasHTML() + { + return true; + } + + /** + * Uses template engine + * + * @return bool + */ + public static function usesTemplate() + { + return true; + } + + /** + * Init client + * + * @return bool + */ + public static function initClient() + { + return true; + } + + /** + * Try authentication + * + * @return bool + */ + public static function doAuthentication() + { + return false; + } + + /** + * Check if persistent session handling is supported + * @return boolean + */ + public static function supportsPersistentSessions() + { + return true; + } + + /** + * Supports push messages + * + * @return bool + */ + public static function supportsPushMessages() + { + return true; + } + + /** + * @inheritdoc + */ + public static function isSessionMainContext() + { + return true; + } +} diff --git a/Services/Context/classes/class.ilContextWebdav.php b/Services/Context/classes/class.ilContextWebdav.php index 0f07792fb1128d5325e296fda69ad22d11ac35b6..88bf84d9b6795519b2cfe4da82c66602fdae6db8 100644 --- a/Services/Context/classes/class.ilContextWebdav.php +++ b/Services/Context/classes/class.ilContextWebdav.php @@ -1,116 +1,113 @@ - - * @version $Id$ - * - * @ingroup ServicesContext - */ -class ilContextWebdav implements ilContextTemplate -{ - /** - * Are redirects supported? - * - * @return bool - */ - public static function supportsRedirects() - { - return false; - } - - /** - * Based on user authentication? - * - * @return bool - */ - public static function hasUser() - { - return true; - } - - /** - * Uses HTTP aka browser - * - * @return bool - */ - public static function usesHTTP() - { - return true; - } - - /** - * Has HTML output - * - * @return bool - */ - public static function hasHTML() - { - return true; - } - - /** - * Uses template engine - * - * @return bool - */ - public static function usesTemplate() - { - return true; - } - - /** - * Init client - * - * @return bool - */ - public static function initClient() - { - return true; - } - - /** - * Try authentication - * - * @return bool - */ - public static function doAuthentication() - { - return false; - } - - /** - * Check if persistent session handling is supported - * @return boolean - */ - public static function supportsPersistentSessions() - { - return true; - } - - /** - * Supports push messages - * - * @return bool - */ - public static function supportsPushMessages() - { - return false; - } - - /** - * @inheritdoc - */ - public static function isSessionMainContext() - { - return true; - } - -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @ingroup ServicesContext + */ +class ilContextWebdav implements ilContextTemplate +{ + /** + * Are redirects supported? + * + * @return bool + */ + public static function supportsRedirects() + { + return false; + } + + /** + * Based on user authentication? + * + * @return bool + */ + public static function hasUser() + { + return true; + } + + /** + * Uses HTTP aka browser + * + * @return bool + */ + public static function usesHTTP() + { + return true; + } + + /** + * Has HTML output + * + * @return bool + */ + public static function hasHTML() + { + return true; + } + + /** + * Uses template engine + * + * @return bool + */ + public static function usesTemplate() + { + return true; + } + + /** + * Init client + * + * @return bool + */ + public static function initClient() + { + return true; + } + + /** + * Try authentication + * + * @return bool + */ + public static function doAuthentication() + { + return false; + } + + /** + * Check if persistent session handling is supported + * @return boolean + */ + public static function supportsPersistentSessions() + { + return true; + } + + /** + * Supports push messages + * + * @return bool + */ + public static function supportsPushMessages() + { + return false; + } + + /** + * @inheritdoc + */ + public static function isSessionMainContext() + { + return true; + } +} diff --git a/Services/Context/interfaces/interface.ilContextTemplate.php b/Services/Context/interfaces/interface.ilContextTemplate.php index 6ccaabf154280c2170191d91d77174365c87860b..60e9fb0b3e8d71a6080b81f661c4ffd2fd7c62a2 100644 --- a/Services/Context/interfaces/interface.ilContextTemplate.php +++ b/Services/Context/interfaces/interface.ilContextTemplate.php @@ -8,74 +8,72 @@ */ interface ilContextTemplate { - /** - * Are redirects supported? - * - * @return bool - */ - public static function supportsRedirects(); + /** + * Are redirects supported? + * + * @return bool + */ + public static function supportsRedirects(); - /** - * Based on user authentication? - * - * @return bool - */ - public static function hasUser(); + /** + * Based on user authentication? + * + * @return bool + */ + public static function hasUser(); - /** - * Uses HTTP aka browser - * - * @return bool - */ - public static function usesHTTP(); + /** + * Uses HTTP aka browser + * + * @return bool + */ + public static function usesHTTP(); - /** - * Has HTML output - * - * @return bool - */ - public static function hasHTML(); + /** + * Has HTML output + * + * @return bool + */ + public static function hasHTML(); - /** - * Uses template engine - * - * @return bool - */ - public static function usesTemplate(); + /** + * Uses template engine + * + * @return bool + */ + public static function usesTemplate(); - /** - * Init client - * - * @return bool - */ - public static function initClient(); + /** + * Init client + * + * @return bool + */ + public static function initClient(); - /** - * Try authentication - * - * @return bool - */ - public static function doAuthentication(); - - - /** - * Check if persistent sessions are supported - * false for context cli - */ - public static function supportsPersistentSessions(); + /** + * Try authentication + * + * @return bool + */ + public static function doAuthentication(); + + + /** + * Check if persistent sessions are supported + * false for context cli + */ + public static function supportsPersistentSessions(); - /** - * Check if push messages are supported, see #0018206 - * @return bool - */ - public static function supportsPushMessages(); + /** + * Check if push messages are supported, see #0018206 + * @return bool + */ + public static function supportsPushMessages(); - /** - * Context that are not only temporary in a session (e.g. WAC is, Cron is not) - * - * @return bool - */ - public static function isSessionMainContext(); - - -} \ No newline at end of file + /** + * Context that are not only temporary in a session (e.g. WAC is, Cron is not) + * + * @return bool + */ + public static function isSessionMainContext(); +} diff --git a/Services/Context/test/class.ilContextExtended.php b/Services/Context/test/class.ilContextExtended.php index 11ff3547ffc024ff290464d9a874d628b63b055b..3789913e1cae84c6a12f81f728aeb5c90b2d15a1 100644 --- a/Services/Context/test/class.ilContextExtended.php +++ b/Services/Context/test/class.ilContextExtended.php @@ -2,29 +2,27 @@ /* Copyright (c) 1998-2010 ILIAS open source, Extended GPL, see docs/LICENSE */ -/** +/** * Extended Service context (factory) class * * ONLY FOR TESTS!!!! - * + * * @author Stefan Hecken * @version $Id$ - * + * * @ingroup ServicesContext */ require_once("Services/Context/classes/class.ilContext.php"); class ilContextExtended extends ilContext -{ - /** - * Get context className - * - * @return int - */ - public static function getClassName() - { - return self::$class_name; - } +{ + /** + * Get context className + * + * @return int + */ + public static function getClassName() + { + return self::$class_name; + } } - -?> \ No newline at end of file diff --git a/Services/Context/test/ilContextTest.php b/Services/Context/test/ilContextTest.php index 76aa8ee6064964b114cff4234a68c006b940498d..2f6e413a4405a4f5f17b8cef0c9810f399f3830b 100644 --- a/Services/Context/test/ilContextTest.php +++ b/Services/Context/test/ilContextTest.php @@ -5,41 +5,45 @@ * @author Stefan Hecken * @version 1.0.0 */ -class ilContextTest extends PHPUnit_Framework_TestCase { - protected $backupGlobals = FALSE; +class ilContextTest extends PHPUnit_Framework_TestCase +{ + protected $backupGlobals = false; - protected function setUp() { - PHPUnit_Framework_Error_Deprecated::$enabled = FALSE; - require_once("Services/Context/test/class.ilContextExtended.php"); - } - - /** - * test init ilContext - * - * @dataProvider contextProvider - */ - public function testInit($context, $className) { - $context_obj = ilContextExtended::init($context); - $this->assertTrue($context_obj); - $this->assertEquals(ilContextExtended::getType(), $context); - $this->assertEquals(ilContextExtended::getClassName(), $className); - } + protected function setUp() + { + PHPUnit_Framework_Error_Deprecated::$enabled = false; + require_once("Services/Context/test/class.ilContextExtended.php"); + } + + /** + * test init ilContext + * + * @dataProvider contextProvider + */ + public function testInit($context, $className) + { + $context_obj = ilContextExtended::init($context); + $this->assertTrue($context_obj); + $this->assertEquals(ilContextExtended::getType(), $context); + $this->assertEquals(ilContextExtended::getClassName(), $className); + } - public function contextProvider() { - require_once("Services/Context/test/class.ilContextExtended.php"); + public function contextProvider() + { + require_once("Services/Context/test/class.ilContextExtended.php"); - return array(array(ilContextExtended::CONTEXT_WEB,"ilContextWeb"), - array(ilContextExtended::CONTEXT_CRON,"ilContextCron"), - array(ilContextExtended::CONTEXT_RSS,"ilContextRss"), - array(ilContextExtended::CONTEXT_ICAL,"ilContextIcal"), - array(ilContextExtended::CONTEXT_SOAP,"ilContextSoap"), - array(ilContextExtended::CONTEXT_WEBDAV,"ilContextWebdav"), - array(ilContextExtended::CONTEXT_RSS_AUTH,"ilContextRssAuth"), - array(ilContextExtended::CONTEXT_SESSION_REMINDER,"ilContextSessionReminder"), - array(ilContextExtended::CONTEXT_SOAP_WITHOUT_CLIENT,"ilContextSoapWithoutClient"), - array(ilContextExtended::CONTEXT_UNITTEST,"ilContextUnitTest"), - array(ilContextExtended::CONTEXT_REST,"ilContextRest"), - array(ilContextExtended::CONTEXT_SCORM,"ilContextScorm"), - array(ilContextExtended::CONTEXT_WAC,"ilContextWAC")); - } -} \ No newline at end of file + return array(array(ilContextExtended::CONTEXT_WEB,"ilContextWeb"), + array(ilContextExtended::CONTEXT_CRON,"ilContextCron"), + array(ilContextExtended::CONTEXT_RSS,"ilContextRss"), + array(ilContextExtended::CONTEXT_ICAL,"ilContextIcal"), + array(ilContextExtended::CONTEXT_SOAP,"ilContextSoap"), + array(ilContextExtended::CONTEXT_WEBDAV,"ilContextWebdav"), + array(ilContextExtended::CONTEXT_RSS_AUTH,"ilContextRssAuth"), + array(ilContextExtended::CONTEXT_SESSION_REMINDER,"ilContextSessionReminder"), + array(ilContextExtended::CONTEXT_SOAP_WITHOUT_CLIENT,"ilContextSoapWithoutClient"), + array(ilContextExtended::CONTEXT_UNITTEST,"ilContextUnitTest"), + array(ilContextExtended::CONTEXT_REST,"ilContextRest"), + array(ilContextExtended::CONTEXT_SCORM,"ilContextScorm"), + array(ilContextExtended::CONTEXT_WAC,"ilContextWAC")); + } +} diff --git a/Services/Context/test/ilServicesContextSuite.php b/Services/Context/test/ilServicesContextSuite.php index f5bab5bded8c35d8188a891d814840c861f34da7..cbb098e28e26fbf69dab7ec3b108f5978b397710 100644 --- a/Services/Context/test/ilServicesContextSuite.php +++ b/Services/Context/test/ilServicesContextSuite.php @@ -4,7 +4,8 @@ * @author Stefan Hecken * @version 1.0.0 */ -class ilServicesContextSuite extends PHPUnit_Framework_TestSuite { +class ilServicesContextSuite extends PHPUnit_Framework_TestSuite +{ public static function suite() { $suite = new ilServicesContextSuite(); diff --git a/Services/DataSet/classes/class.ilDataSet.php b/Services/DataSet/classes/class.ilDataSet.php index ccb329eeb302ae492f89143f05480480fd1c5d04..accacf23812c942429a1db3ebc43075649a4231e 100644 --- a/Services/DataSet/classes/class.ilDataSet.php +++ b/Services/DataSet/classes/class.ilDataSet.php @@ -19,650 +19,618 @@ * * @author Alex Killing * @version $Id$ -* @ingroup +* @ingroup */ abstract class ilDataSet { - var $dircnt; - protected $current_installation_id = ""; - - const EXPORT_NO_INST_ID = 1; - const EXPORT_ID_ILIAS_LOCAL = 2; - const EXPORT_ID_ILIAS_LOCAL_INVALID = 3; - const EXPORT_ID_ILIAS_REMOTE = 4; - const EXPORT_ID_ILIAS_REMOTE_INVALID = 5; - const EXPORT_ID = 6; - const EXPORT_ID_INVALID = 7; + public $dircnt; + protected $current_installation_id = ""; + + const EXPORT_NO_INST_ID = 1; + const EXPORT_ID_ILIAS_LOCAL = 2; + const EXPORT_ID_ILIAS_LOCAL_INVALID = 3; + const EXPORT_ID_ILIAS_REMOTE = 4; + const EXPORT_ID_ILIAS_REMOTE_INVALID = 5; + const EXPORT_ID = 6; + const EXPORT_ID_INVALID = 7; - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; - /** - * @var ilLogger - */ - protected $ds_log; - - /** - * Constructor - */ - function __construct() - { - global $DIC; + /** + * @var ilLogger + */ + protected $ds_log; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; - $this->db = $DIC->database(); - $this->ds_log = ilLoggerFactory::getLogger('ds'); - } - - /** - * Init - * - * @param string (abstract) entity name - * @param string version string, always the ILIAS release - * versions that defined the a structure - * or made changes to it, never use another - * version. Example: structure is defined - * in 4.1.0 and changed in 4.3.0 -> use these - * values only, not 4.2.0 (ask for the 4.1.0 - * version in ILIAS 4.2.0) - */ - final public function init($a_entity, $a_schema_version) - { - $this->entity = $a_entity; - $this->schema_version = $a_schema_version; - $this->data = array(); - } - - /** - * Get supported version - * - * @return array array of supported version - */ - abstract public function getSupportedVersions(); - - /** - * Get (abstract) types for (abstract) field names. - * Please note that the abstract fields/types only depend on - * the version! Not on a choosen representation! - * - * @return array types array, e.g. - * array("field_1" => "text", "field_2" => "integer", ...) - */ - abstract protected function getTypes($a_entity, $a_version); - - /** - * Get xml namespace - * - */ - abstract protected function getXmlNamespace($a_entity, $a_schema_version); - - /** - * Read data from DB. This should result in the - * abstract field structure of the version set in the constructor. - * - * @param array one or multiple ids - */ - abstract function readData($a_entity, $a_version, $a_ids); - - /** - * Set export directories - * - * @param - * @return - */ - function setExportDirectories($a_relative, $a_absolute) - { - $this->relative_export_dir = $a_relative; - $this->absolute_export_dir = $a_absolute; - } + $this->db = $DIC->database(); + $this->ds_log = ilLoggerFactory::getLogger('ds'); + } + + /** + * Init + * + * @param string (abstract) entity name + * @param string version string, always the ILIAS release + * versions that defined the a structure + * or made changes to it, never use another + * version. Example: structure is defined + * in 4.1.0 and changed in 4.3.0 -> use these + * values only, not 4.2.0 (ask for the 4.1.0 + * version in ILIAS 4.2.0) + */ + final public function init($a_entity, $a_schema_version) + { + $this->entity = $a_entity; + $this->schema_version = $a_schema_version; + $this->data = array(); + } + + /** + * Get supported version + * + * @return array array of supported version + */ + abstract public function getSupportedVersions(); + + /** + * Get (abstract) types for (abstract) field names. + * Please note that the abstract fields/types only depend on + * the version! Not on a choosen representation! + * + * @return array types array, e.g. + * array("field_1" => "text", "field_2" => "integer", ...) + */ + abstract protected function getTypes($a_entity, $a_version); + + /** + * Get xml namespace + * + */ + abstract protected function getXmlNamespace($a_entity, $a_schema_version); + + /** + * Read data from DB. This should result in the + * abstract field structure of the version set in the constructor. + * + * @param array one or multiple ids + */ + abstract public function readData($a_entity, $a_version, $a_ids); + + /** + * Set export directories + * + * @param + * @return + */ + public function setExportDirectories($a_relative, $a_absolute) + { + $this->relative_export_dir = $a_relative; + $this->absolute_export_dir = $a_absolute; + } - /** - * Set import directory - * - * @param string import directory - */ - function setImportDirectory($a_val) - { - $this->import_directory = $a_val; - } + /** + * Set import directory + * + * @param string import directory + */ + public function setImportDirectory($a_val) + { + $this->import_directory = $a_val; + } - /** - * Get import directory - * - * @return string import directory - */ - function getImportDirectory() - { - return $this->import_directory; - } + /** + * Get import directory + * + * @return string import directory + */ + public function getImportDirectory() + { + return $this->import_directory; + } - /** - * Set XML dataset namespace prefix - * - * @param string XML dataset namespace prefix - */ - function setDSPrefix($a_val) - { - $this->var = $a_val; - } + /** + * Set XML dataset namespace prefix + * + * @param string XML dataset namespace prefix + */ + public function setDSPrefix($a_val) + { + $this->var = $a_val; + } - /** - * Get XML dataset namespace prefix - * - * @return string XML dataset namespace prefix - */ - function getDSPrefix() - { - return $this->var; - } + /** + * Get XML dataset namespace prefix + * + * @return string XML dataset namespace prefix + */ + public function getDSPrefix() + { + return $this->var; + } - function getDSPrefixString() - { - if ($this->getDSPrefix() != "") - { - return $this->getDSPrefix().":"; - } - } + public function getDSPrefixString() + { + if ($this->getDSPrefix() != "") { + return $this->getDSPrefix() . ":"; + } + } - /** - * Get data from query.This is a standard procedure, - * all db field names are directly mapped to abstract fields. - * @param string $a_query - * @param bool $a_convert_to_leading_upper - * @param bool $a_set should internal data array already be set? - * @return array - */ - function getDirectDataFromQuery($a_query, $a_convert_to_leading_upper = true, $a_set = true) - { - $ilDB = $this->db; - - $set = $ilDB->query($a_query); - $this->data = array(); - $ret = []; - while ($rec = $ilDB->fetchAssoc($set)) - { - if ($a_convert_to_leading_upper) - { - $tmp = array(); - foreach ($rec as $k => $v) - { - $tmp[$this->convertToLeadingUpper($k)] - = $v; - } - $rec = $tmp; - } + /** + * Get data from query.This is a standard procedure, + * all db field names are directly mapped to abstract fields. + * @param string $a_query + * @param bool $a_convert_to_leading_upper + * @param bool $a_set should internal data array already be set? + * @return array + */ + public function getDirectDataFromQuery($a_query, $a_convert_to_leading_upper = true, $a_set = true) + { + $ilDB = $this->db; + + $set = $ilDB->query($a_query); + $this->data = array(); + $ret = []; + while ($rec = $ilDB->fetchAssoc($set)) { + if ($a_convert_to_leading_upper) { + $tmp = array(); + foreach ($rec as $k => $v) { + $tmp[$this->convertToLeadingUpper($k)] + = $v; + } + $rec = $tmp; + } - if ($a_set) - { - $this->data[] = $rec; - } - $ret[] = $rec; - } - return $ret; - } + if ($a_set) { + $this->data[] = $rec; + } + $ret[] = $rec; + } + return $ret; + } - /** - * Make xyz_abc a XyzAbc string - * - * @param - * @return - */ - function convertToLeadingUpper($a_str) - { - $a_str = strtoupper(substr($a_str, 0, 1)).substr($a_str, 1); - while (is_int($pos = strpos($a_str, "_"))) - { - $a_str = substr($a_str, 0, $pos). - strtoupper(substr($a_str, $pos+1, 1)). - substr($a_str, $pos+2); - } - return $a_str; - } + /** + * Make xyz_abc a XyzAbc string + * + * @param + * @return + */ + public function convertToLeadingUpper($a_str) + { + $a_str = strtoupper(substr($a_str, 0, 1)) . substr($a_str, 1); + while (is_int($pos = strpos($a_str, "_"))) { + $a_str = substr($a_str, 0, $pos) . + strtoupper(substr($a_str, $pos+1, 1)) . + substr($a_str, $pos+2); + } + return $a_str; + } - - /** - * Get json representation - */ - final function getJsonRepresentation() - { - if ($this->version === false) - { - return false; - } - - $arr["entity"] = $this->getJsonEntityName(); - $arr["version"] = $this->version; - $arr["install_id"] = IL_INST_ID; - $arr["install_url"] = ILIAS_HTTP_PATH; - $arr["types"] = $this->getJsonTypes(); - $arr["set"] = array(); - foreach ($this->data as $d) - { - $arr["set"][] = $this->getJsonRecord($d); - } - - include_once("./Services/JSON/classes/class.ilJsonUtil.php"); + + /** + * Get json representation + */ + final public function getJsonRepresentation() + { + if ($this->version === false) { + return false; + } + + $arr["entity"] = $this->getJsonEntityName(); + $arr["version"] = $this->version; + $arr["install_id"] = IL_INST_ID; + $arr["install_url"] = ILIAS_HTTP_PATH; + $arr["types"] = $this->getJsonTypes(); + $arr["set"] = array(); + foreach ($this->data as $d) { + $arr["set"][] = $this->getJsonRecord($d); + } + + include_once("./Services/JSON/classes/class.ilJsonUtil.php"); - return ilJsonUtil::encode($arr); - } + return ilJsonUtil::encode($arr); + } - /** - * Get xml representation - * - * - * - * - * - * - * - * ... - * - * - * - * content - * my_date - * my_number - * - * ... - * - * - */ - final function getXmlRepresentation($a_entity, $a_schema_version, - $a_ids, $a_field = "", $a_omit_header = false, $a_omit_types = false) - { - $this->dircnt = 1; - - // step 1: check target release and supported versions - - - - // step 2: init writer - include_once "./Services/Xml/classes/class.ilXmlWriter.php"; - $writer = new ilXmlWriter(); - if (!$a_omit_header) - { - $writer->xmlHeader(); - } - - // collect namespaces - $namespaces = $prefixes = array(); - $this->getNamespaces($namespaces, $a_entity, $a_schema_version); - $atts = array("InstallationId" => IL_INST_ID, - "InstallationUrl" => ILIAS_HTTP_PATH, "TopEntity" => $a_entity); - $cnt = 1; - foreach ($namespaces as $entity => $ns) - { - $prefix = "ns".$cnt; - $prefixes[$entity] = $prefix; -// $atts["xmlns:".$prefix] = $ns; - $cnt++; - } + /** + * Get xml representation + * + * + * + * + * + * + * + * ... + * + * + * + * content + * my_date + * my_number + * + * ... + * + * + */ + final public function getXmlRepresentation( + $a_entity, + $a_schema_version, + $a_ids, + $a_field = "", + $a_omit_header = false, + $a_omit_types = false + ) { + $this->dircnt = 1; + + // step 1: check target release and supported versions + + + + // step 2: init writer + include_once "./Services/Xml/classes/class.ilXmlWriter.php"; + $writer = new ilXmlWriter(); + if (!$a_omit_header) { + $writer->xmlHeader(); + } + + // collect namespaces + $namespaces = $prefixes = array(); + $this->getNamespaces($namespaces, $a_entity, $a_schema_version); + $atts = array("InstallationId" => IL_INST_ID, + "InstallationUrl" => ILIAS_HTTP_PATH, "TopEntity" => $a_entity); + $cnt = 1; + foreach ($namespaces as $entity => $ns) { + $prefix = "ns" . $cnt; + $prefixes[$entity] = $prefix; + // $atts["xmlns:".$prefix] = $ns; + $cnt++; + } - $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 - */ - 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 "
          copy-".$c."-".$this->absolute_export_dir."/dsDir_".$this->dircnt."-"; - $c = $this->relative_export_dir."/dsDir_".$this->dircnt; - $this->dircnt++; - } - break; - } - // this changes schema/dtd - //$a_writer->xmlElement($a_prefixes[$a_entity].":".$f, - // array(), $c); - $a_writer->xmlElement($f, array(), $c); - } - - $a_writer->xmlEndTag($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 "
          copy-".$c."-".$this->absolute_export_dir."/dsDir_".$this->dircnt."-"; + $c = $this->relative_export_dir . "/dsDir_" . $this->dircnt; + $this->dircnt++; + } + break; + } + // this changes schema/dtd + //$a_writer->xmlElement($a_prefixes[$a_entity].":".$f, + // array(), $c); + $a_writer->xmlElement($f, array(), $c); + } + + $a_writer->xmlEndTag($this->getXmlEntityTag($a_entity, $a_schema_version)); - $a_writer->xmlEndTag($this->getDSPrefixString()."Rec"); - - $this->afterXmlRecordWriting($a_entity, $a_schema_version, $d); + $a_writer->xmlEndTag($this->getDSPrefixString() . "Rec"); + + $this->afterXmlRecordWriting($a_entity, $a_schema_version, $d); - // foreach record records of dependent entities - $this->ds_log->debug("...get dependencies"); - $deps = $this->getDependencies($a_entity, $a_schema_version, $rec, $a_ids); - $this->ds_log->debug("...dependencies: ".print_r($deps, true)); - if (is_array($deps)) - { - foreach ($deps as $dp => $par) - { - $this->addRecordsXml($a_writer, $a_prefixes, $dp, $a_schema_version, $par["ids"], $par["field"]); - } - } - } - } - else if ($this->data === false) - { - // false -> add records of dependent entities (no record) - $this->ds_log->debug("...get dependencies (no record)"); - $deps = $this->getDependencies($a_entity, $a_schema_version, null, $a_ids); - if (is_array($deps)) - { - foreach ($deps as $dp => $par) - { - $this->addRecordsXml($a_writer, $a_prefixes, $dp, $a_schema_version, $par["ids"], $par["field"]); - } - } - } - } - - /** - * After xml record writing hook record - * - * @param - * @return - */ - function afterXmlRecordWriting($a_entity, $a_version, $a_set) - { - } + // foreach record records of dependent entities + $this->ds_log->debug("...get dependencies"); + $deps = $this->getDependencies($a_entity, $a_schema_version, $rec, $a_ids); + $this->ds_log->debug("...dependencies: " . print_r($deps, true)); + if (is_array($deps)) { + foreach ($deps as $dp => $par) { + $this->addRecordsXml($a_writer, $a_prefixes, $dp, $a_schema_version, $par["ids"], $par["field"]); + } + } + } + } elseif ($this->data === false) { + // false -> add records of dependent entities (no record) + $this->ds_log->debug("...get dependencies (no record)"); + $deps = $this->getDependencies($a_entity, $a_schema_version, null, $a_ids); + if (is_array($deps)) { + foreach ($deps as $dp => $par) { + $this->addRecordsXml($a_writer, $a_prefixes, $dp, $a_schema_version, $par["ids"], $par["field"]); + } + } + } + } + + /** + * After xml record writing hook record + * + * @param + * @return + */ + public function afterXmlRecordWriting($a_entity, $a_version, $a_set) + { + } - /** - * Add types to xml writer - * - * @param - */ - private function addTypesXml($a_writer, $a_entity, $a_schema_version) - { - $types = $this->getXmlTypes($a_entity, $a_schema_version); - - // add types of current entity - if (is_array($types)) - { - $a_writer->xmlStartTag($this->getDSPrefixString()."Types", - array("Entity" => $this->getXmlEntityName($a_entity, $a_schema_version), - "SchemaVersion" => $a_schema_version)); - foreach ($this->getXmlTypes($a_entity, $a_schema_version) as $f => $t) - { - $a_writer->xmlElement($this->getDSPrefixString().'FieldType', - array("Name" => $f, "Type" => $t)); - } - $a_writer->xmlEndTag($this->getDSPrefixString()."Types"); - } - - // add types of dependent entities - $deps = $this->getDependencies($a_entity, $a_schema_version, null, null); - if (is_array($deps)) - { - foreach ($deps as $dp => $w) - { - $this->addTypesXml($a_writer, $dp, $a_schema_version); - } - } - - } - - /** - * Get xml namespaces - * - * @param array namespaces per entity - * @param string entity - * @param string target release - */ - function getNamespaces(&$namespaces, $a_entity, $a_schema_version) - { - $ns = $this->getXmlNamespace($a_entity, $a_schema_version); - if ($ns != "") - { - $namespaces[$a_entity] = $ns; - } - // add types of dependent entities - $deps = $this->getDependencies($a_entity, $a_schema_version, null, null); - if (is_array($deps)) - { - foreach ($deps as $dp => $w) - { - $this->getNamespaces($namespaces, $dp, $a_schema_version); - } - } - } - - /** - * Get xml record for version - * - * @param array abstract data record - * @return array xml record - */ - function getXmlRecord($a_entity, $a_version, $a_set) - { - return $a_set; - } - - /** - * Get json record for version - * - * @param array abstract data record - * @return array json record - */ - function getJsonRecord($a_set) - { - return $a_set; - } - - /** - * Get xml types - * - * @return array types array for xml/version set in constructor - */ - function getXmlTypes($a_entity, $a_version) - { - return $this->getTypes($a_entity, $a_version); - } - - /** - * Get json types - * - * @return array types array for json/version set in constructor - */ - function getJsonTypes($a_entity, $a_version) - { - return $this->getTypes($a_entity, $a_version); - } - - /** - * Get entity name for xml - * (may be overwritten) - * - * @return string - */ - function getXMLEntityName($a_entity, $a_version) - { - return $a_entity; - } + /** + * Add types to xml writer + * + * @param + */ + private function addTypesXml($a_writer, $a_entity, $a_schema_version) + { + $types = $this->getXmlTypes($a_entity, $a_schema_version); + + // add types of current entity + if (is_array($types)) { + $a_writer->xmlStartTag( + $this->getDSPrefixString() . "Types", + array("Entity" => $this->getXmlEntityName($a_entity, $a_schema_version), + "SchemaVersion" => $a_schema_version) + ); + foreach ($this->getXmlTypes($a_entity, $a_schema_version) as $f => $t) { + $a_writer->xmlElement( + $this->getDSPrefixString() . 'FieldType', + array("Name" => $f, "Type" => $t) + ); + } + $a_writer->xmlEndTag($this->getDSPrefixString() . "Types"); + } + + // add types of dependent entities + $deps = $this->getDependencies($a_entity, $a_schema_version, null, null); + if (is_array($deps)) { + foreach ($deps as $dp => $w) { + $this->addTypesXml($a_writer, $dp, $a_schema_version); + } + } + } + + /** + * Get xml namespaces + * + * @param array namespaces per entity + * @param string entity + * @param string target release + */ + public function getNamespaces(&$namespaces, $a_entity, $a_schema_version) + { + $ns = $this->getXmlNamespace($a_entity, $a_schema_version); + if ($ns != "") { + $namespaces[$a_entity] = $ns; + } + // add types of dependent entities + $deps = $this->getDependencies($a_entity, $a_schema_version, null, null); + if (is_array($deps)) { + foreach ($deps as $dp => $w) { + $this->getNamespaces($namespaces, $dp, $a_schema_version); + } + } + } + + /** + * Get xml record for version + * + * @param array abstract data record + * @return array xml record + */ + public function getXmlRecord($a_entity, $a_version, $a_set) + { + return $a_set; + } + + /** + * Get json record for version + * + * @param array abstract data record + * @return array json record + */ + public function getJsonRecord($a_set) + { + return $a_set; + } + + /** + * Get xml types + * + * @return array types array for xml/version set in constructor + */ + public function getXmlTypes($a_entity, $a_version) + { + return $this->getTypes($a_entity, $a_version); + } + + /** + * Get json types + * + * @return array types array for json/version set in constructor + */ + public function getJsonTypes($a_entity, $a_version) + { + return $this->getTypes($a_entity, $a_version); + } + + /** + * Get entity name for xml + * (may be overwritten) + * + * @return string + */ + public function getXMLEntityName($a_entity, $a_version) + { + return $a_entity; + } - /** - * Get entity tag - * - * @param - * @return - */ - function getXMLEntityTag($a_entity, $a_schema_version) - { - return $this->convertToLeadingUpper($a_entity); - } - - /** - * Get entity name for json - * (may be overwritten) - */ - function getJsonEntityName($a_entity, $a_version) - { - return $a_entity; - } - - /** - * Set import object - * - * @param object import object - */ - function setImport($a_val) - { - $this->import = $a_val; - } - - /** - * Get import object - * - * @return object import object - */ - function getImport() - { - return $this->import; - } + /** + * Get entity tag + * + * @param + * @return + */ + public function getXMLEntityTag($a_entity, $a_schema_version) + { + return $this->convertToLeadingUpper($a_entity); + } + + /** + * Get entity name for json + * (may be overwritten) + */ + public function getJsonEntityName($a_entity, $a_version) + { + return $a_entity; + } + + /** + * Set import object + * + * @param object import object + */ + public function setImport($a_val) + { + $this->import = $a_val; + } + + /** + * Get import object + * + * @return object import object + */ + public function getImport() + { + return $this->import; + } - /** - * Set current installation id - * - * @param string $a_val current installation id - */ - function setCurrentInstallationId($a_val) - { - $this->current_installation_id = $a_val; - } + /** + * Set current installation id + * + * @param string $a_val current installation id + */ + public function setCurrentInstallationId($a_val) + { + $this->current_installation_id = $a_val; + } - /** - * Get current installation id - * - * @return string current installation id - */ - function getCurrentInstallationId() - { - return $this->current_installation_id; - } - - /** - * Build ilias export id - * - * @param string $a_type - * @param int $a_id - * @return string - */ - protected function createObjectExportId($a_type, $a_id) - { - return "il_".IL_INST_ID."_".$a_type."_".$a_id; - } - - /** - * Parse export id - * - * @param string $a_id - * @param int $a_fallback_id - * @return array type, id - */ - protected function parseObjectExportId($a_id, $a_fallback_id = NULL) - { - // ilias export id? - if(substr($a_id, 0, 3) == "il_") - { - $parts = explode("_", $a_id); - $inst_id = $parts[1]; - $type = $parts[2]; - $id = $parts[3]; - - // missing installation ids? - if(($inst_id == 0 || IL_INST_ID == 0) && !DEVMODE) - { - return array("type"=>self::EXPORT_NO_INST_ID, "id"=>$a_fallback_id); - } - - // same installation? - if($inst_id == IL_INST_ID) - { - // still existing? - if(ilObject::_lookupType($id) == $type) - { - return array("type"=>self::EXPORT_ID_ILIAS_LOCAL, "id"=>$id); - } - // not found - else - { - return array("type"=>self::EXPORT_ID_ILIAS_LOCAL_INVALID, "id"=>$a_fallback_id); - } - } - // different installation - else - { - $id = ilObject::_getIdForImportId($a_id); - // matching type? - if($id && ilObject::_lookupType($id) == $type) - { - return array("type"=>self::EXPORT_ID_ILIAS_REMOTE, "id"=>$id); - } - // not found - else - { - return array("type"=>self::EXPORT_ID_ILIAS_REMOTE_INVALID, "id"=>$a_fallback_id); - } - } - } - - // external id - $id = ilObject::_getIdForImportId($a_id); - if($id) - { - return array("type"=>self::EXPORT_ID, "id"=>$id); - } - else - { - return array("type"=>self::EXPORT_ID_INVALID, "id"=>$a_fallback_id); - } - } + /** + * Get current installation id + * + * @return string current installation id + */ + public function getCurrentInstallationId() + { + return $this->current_installation_id; + } + + /** + * Build ilias export id + * + * @param string $a_type + * @param int $a_id + * @return string + */ + protected function createObjectExportId($a_type, $a_id) + { + return "il_" . IL_INST_ID . "_" . $a_type . "_" . $a_id; + } + + /** + * Parse export id + * + * @param string $a_id + * @param int $a_fallback_id + * @return array type, id + */ + protected function parseObjectExportId($a_id, $a_fallback_id = null) + { + // ilias export id? + if (substr($a_id, 0, 3) == "il_") { + $parts = explode("_", $a_id); + $inst_id = $parts[1]; + $type = $parts[2]; + $id = $parts[3]; + + // missing installation ids? + if (($inst_id == 0 || IL_INST_ID == 0) && !DEVMODE) { + return array("type"=>self::EXPORT_NO_INST_ID, "id"=>$a_fallback_id); + } + + // same installation? + if ($inst_id == IL_INST_ID) { + // still existing? + if (ilObject::_lookupType($id) == $type) { + return array("type"=>self::EXPORT_ID_ILIAS_LOCAL, "id"=>$id); + } + // not found + else { + return array("type"=>self::EXPORT_ID_ILIAS_LOCAL_INVALID, "id"=>$a_fallback_id); + } + } + // different installation + else { + $id = ilObject::_getIdForImportId($a_id); + // matching type? + if ($id && ilObject::_lookupType($id) == $type) { + return array("type"=>self::EXPORT_ID_ILIAS_REMOTE, "id"=>$id); + } + // not found + else { + return array("type"=>self::EXPORT_ID_ILIAS_REMOTE_INVALID, "id"=>$a_fallback_id); + } + } + } + + // external id + $id = ilObject::_getIdForImportId($a_id); + if ($id) { + return array("type"=>self::EXPORT_ID, "id"=>$id); + } else { + return array("type"=>self::EXPORT_ID_INVALID, "id"=>$a_fallback_id); + } + } } - -?> \ No newline at end of file diff --git a/Services/DataSet/classes/class.ilDataSetImportParser.php b/Services/DataSet/classes/class.ilDataSetImportParser.php index 7c5c367e5b4f38556b88de4cc7fb75a9ec5315a7..dd634ce40e6261bb200dd49778f6f60480d64a72 100644 --- a/Services/DataSet/classes/class.ilDataSetImportParser.php +++ b/Services/DataSet/classes/class.ilDataSetImportParser.php @@ -12,169 +12,163 @@ include_once("./Services/Xml/classes/class.ilSaxParser.php"); */ class ilDataSetImportParser extends ilSaxParser { - protected $import = null; // import object - protected $entities = array(); // types array - protected $current_entity = ""; // current entity - protected $current_version = ""; // current version - protected $current_ftypes = array(); // current field types - protected $entities_sent = false; // sent entities to import class? - protected $in_record = false; // are we currently in a rec tag? - protected $current_field = ""; // current field - protected $current_field_values = array(); // current field values - protected $current_installation_id = ""; - - - /** - * Constructor - * - * @param - * @return - */ - function __construct($a_top_entity, $a_schema_version, $a_xml, $a_ds, $a_mapping) - { - $this->ds = $a_ds; - $this->mapping = $a_mapping; - $this->top_entity = $a_top_entity; - $this->schema_version = $a_schema_version; - $this->dspref = ($this->ds->getDSPrefix() != "") - ? $this->ds->getDSPrefix().":" - : ""; - - parent::__construct(); - $this->setXMLContent($a_xml); - $this->startParsing(); + protected $import = null; // import object + protected $entities = array(); // types array + protected $current_entity = ""; // current entity + protected $current_version = ""; // current version + protected $current_ftypes = array(); // current field types + protected $entities_sent = false; // sent entities to import class? + protected $in_record = false; // are we currently in a rec tag? + protected $current_field = ""; // current field + protected $current_field_values = array(); // current field values + protected $current_installation_id = ""; + + + /** + * Constructor + * + * @param + * @return + */ + public function __construct($a_top_entity, $a_schema_version, $a_xml, $a_ds, $a_mapping) + { + $this->ds = $a_ds; + $this->mapping = $a_mapping; + $this->top_entity = $a_top_entity; + $this->schema_version = $a_schema_version; + $this->dspref = ($this->ds->getDSPrefix() != "") + ? $this->ds->getDSPrefix() . ":" + : ""; + + parent::__construct(); + $this->setXMLContent($a_xml); + $this->startParsing(); + } + /** + * Get current installation id + * + * @param + * @return + */ + public function getCurrentInstallationId() + { + return $this->current_installation_id; + } - } + + /** + * Set event handlers + * + * @param resource reference to the xml parser + * @access private + */ + public function setHandlers($a_xml_parser) + { + xml_set_object($a_xml_parser, $this); + xml_set_element_handler($a_xml_parser, 'handleBeginTag', 'handleEndTag'); + xml_set_character_data_handler($a_xml_parser, 'handleCharacterData'); + } - /** - * Get current installation id - * - * @param - * @return - */ - function getCurrentInstallationId() - { - return $this->current_installation_id; - } - - - /** - * Set event handlers - * - * @param resource reference to the xml parser - * @access private - */ - function setHandlers($a_xml_parser) - { - xml_set_object($a_xml_parser,$this); - xml_set_element_handler($a_xml_parser, 'handleBeginTag', 'handleEndTag'); - xml_set_character_data_handler($a_xml_parser, 'handleCharacterData'); - } - - - /** - * Start parser - */ - function startParsing() - { - parent::startParsing(); - } - - /** - * Begin Tag - */ - function handleBeginTag($a_xml_parser, $a_name, $a_attribs) - { - switch ($a_name) - { - case $this->dspref."DataSet": + + /** + * Start parser + */ + public function startParsing() + { + parent::startParsing(); + } + + /** + * Begin Tag + */ + public function handleBeginTag($a_xml_parser, $a_name, $a_attribs) + { + switch ($a_name) { + case $this->dspref . "DataSet": // $this->import->initDataset($this->ds_component, $a_attribs["top_entity"]); - $this->current_installation_id = $a_attribs["InstallationId"]; - $this->ds->setCurrentInstallationId($a_attribs["InstallationId"]); - break; - - case $this->dspref."Types": - $this->current_entity = $a_attribs["Entity"]; - $this->current_version = $a_attribs["Version"]; - break; - - case $this->dspref."FieldType": - $this->current_ftypes[$a_attribs["Name"]] = - $a_attribs["Type"]; - break; - - case $this->dspref."Rec": - $this->current_entity = $a_attribs["Entity"]; - $this->in_record = true; - $this->current_field_values = array(); - break; - - default: - if ($this->in_record) - { - $field = explode(":", $a_name); // remove namespace - $field = $field[count($field) - 1]; - $this->current_field = $field; - } - } - } - - /** - * End Tag - */ - function handleEndTag($a_xml_parser, $a_name) - { - switch ($a_name) - { - case $this->dspref."Types": - $this->entities[$this->current_entity] = - array( - "version" => $this->current_version, - "types" => $this->current_ftypes - ); - $this->current_ftypes = array(); - $this->current_entity = ""; - $this->current_version = ""; - break; - - case $this->dspref."Rec": - $this->ds->importRecord($this->current_entity, - $this->entities[$this->current_entity]["types"], - $this->current_field_values, - $this->mapping, - $this->schema_version); - $this->in_record = false; - $this->current_entity = ""; - $this->current_field_values = array(); - break; - - default: - if ($this->in_record && $this->current_field != "") - { - $this->current_field_values[$this->current_field] = - $this->chr_data; - } - $this->current_field = ""; - break; - } - - $this->chr_data = ""; - } - - /** - * End Tag - */ - function handleCharacterData($a_xml_parser,$a_data) - { - //$a_data = str_replace("<","<",$a_data); - //$a_data = str_replace(">",">",$a_data); - // DELETE WHITESPACES AND NEWLINES OF CHARACTER DATA - //$a_data = preg_replace("/\n/","",$a_data); - //$a_data = preg_replace("/\t+/","",$a_data); + $this->current_installation_id = $a_attribs["InstallationId"]; + $this->ds->setCurrentInstallationId($a_attribs["InstallationId"]); + break; + + case $this->dspref . "Types": + $this->current_entity = $a_attribs["Entity"]; + $this->current_version = $a_attribs["Version"]; + break; + + case $this->dspref . "FieldType": + $this->current_ftypes[$a_attribs["Name"]] = + $a_attribs["Type"]; + break; + + case $this->dspref . "Rec": + $this->current_entity = $a_attribs["Entity"]; + $this->in_record = true; + $this->current_field_values = array(); + break; + + default: + if ($this->in_record) { + $field = explode(":", $a_name); // remove namespace + $field = $field[count($field) - 1]; + $this->current_field = $field; + } + } + } + + /** + * End Tag + */ + public function handleEndTag($a_xml_parser, $a_name) + { + switch ($a_name) { + case $this->dspref . "Types": + $this->entities[$this->current_entity] = + array( + "version" => $this->current_version, + "types" => $this->current_ftypes + ); + $this->current_ftypes = array(); + $this->current_entity = ""; + $this->current_version = ""; + break; + + case $this->dspref . "Rec": + $this->ds->importRecord( + $this->current_entity, + $this->entities[$this->current_entity]["types"], + $this->current_field_values, + $this->mapping, + $this->schema_version + ); + $this->in_record = false; + $this->current_entity = ""; + $this->current_field_values = array(); + break; + + default: + if ($this->in_record && $this->current_field != "") { + $this->current_field_values[$this->current_field] = + $this->chr_data; + } + $this->current_field = ""; + break; + } + + $this->chr_data = ""; + } + + /** + * End Tag + */ + public function handleCharacterData($a_xml_parser, $a_data) + { + //$a_data = str_replace("<","<",$a_data); + //$a_data = str_replace(">",">",$a_data); + // DELETE WHITESPACES AND NEWLINES OF CHARACTER DATA + //$a_data = preg_replace("/\n/","",$a_data); + //$a_data = preg_replace("/\t+/","",$a_data); - $this->chr_data .= $a_data; - } - + $this->chr_data .= $a_data; + } } -?> \ No newline at end of file diff --git a/Services/Dom/classes/class.ilDomDocument.php b/Services/Dom/classes/class.ilDomDocument.php index dbc2e120a31085a4abaf801e8090b039d5e731db..848257ccd7479d7c616fff1405d4acb403ad338f 100644 --- a/Services/Dom/classes/class.ilDomDocument.php +++ b/Services/Dom/classes/class.ilDomDocument.php @@ -2,7 +2,7 @@ /* Copyright (c) 1998-2009 ILIAS open source, Extended GPL, see docs/LICENSE */ /** - * Dom document wrapper. + * Dom document wrapper. * * @author author * @version $Id$ @@ -10,68 +10,60 @@ */ class ilDomDocument { - private $doc; - private $errors = array(); + private $doc; + private $errors = array(); - /** - * Constructor - * @param DOMDocument PHP dom document - */ - function __construct() - { - $this->doc = new DOMDocument(); - } + /** + * Constructor + * @param DOMDocument PHP dom document + */ + public function __construct() + { + $this->doc = new DOMDocument(); + } - /** - * Call - */ - public function __call($a_method, $a_args) - { - if (in_array($a_method, array("validate", "loadXML"))) - { - set_error_handler(array($this, "handleError")); - $rv = call_user_func_array(array($this->doc, $a_method), $a_args); - restore_error_handler(); - return $rv; - } - else - { - return call_user_func_array(array($this->doc, $a_method), $a_args); - } - } - - /** - * Get - */ - public function __get($a_mem) - { - if ($a_mem == "errors") - { - return $this->errors; - } - else - { - return $this->doc->$a_mem; - } - } + /** + * Call + */ + public function __call($a_method, $a_args) + { + if (in_array($a_method, array("validate", "loadXML"))) { + set_error_handler(array($this, "handleError")); + $rv = call_user_func_array(array($this->doc, $a_method), $a_args); + restore_error_handler(); + return $rv; + } else { + return call_user_func_array(array($this->doc, $a_method), $a_args); + } + } + + /** + * Get + */ + public function __get($a_mem) + { + if ($a_mem == "errors") { + return $this->errors; + } else { + return $this->doc->$a_mem; + } + } - /** - * Set - */ - public function __set($a_mem, $a_val) - { - $this->_delegate->$a_mem = $a_val; - } - - /** - * Handle error - */ - public function handleError($a_no, $a_string, $a_file = null, $a_line = null, $a_context = null) - { - $pos = strpos($a_string, "]:"); - $err = trim(substr($a_string, $pos + 2)); - $this->errors[] = $err; - } -} + /** + * Set + */ + public function __set($a_mem, $a_val) + { + $this->_delegate->$a_mem = $a_val; + } -?> \ No newline at end of file + /** + * Handle error + */ + public function handleError($a_no, $a_string, $a_file = null, $a_line = null, $a_context = null) + { + $pos = strpos($a_string, "]:"); + $err = trim(substr($a_string, $pos + 2)); + $this->errors[] = $err; + } +} diff --git a/Services/EventHandling/classes/class.ilAppEventHandler.php b/Services/EventHandling/classes/class.ilAppEventHandler.php index fe9e62e685dcb828c485a1807e5a7e58bcf246ff..78e0f2dab611e8aabdd1e7ba9a8e05eb55f3e86c 100755 --- a/Services/EventHandling/classes/class.ilAppEventHandler.php +++ b/Services/EventHandling/classes/class.ilAppEventHandler.php @@ -1,24 +1,24 @@ listener["Services/User"] = array("Services/News"); * This information will go to xml files in the future. -* +* * A component has to implement a listener class that implements * Services/EventHandling/interfaces/interface.ilAppEventListener.php * @@ -57,164 +57,159 @@ require_once './Services/WorkflowEngine/classes/class.ilWorkflowEngine.php'; */ class ilAppEventHandler { - /** - * @var ilDB - */ - protected $db; - - protected $listener; // [array] - - /** - * @var ilLogger - */ - protected $logger; - - /** - * Constructor - */ - public function __construct() - { - global $DIC; - - $this->db = $DIC->database(); - $this->initListeners(); - - $this->logger = \ilLoggerFactory::getLogger('evnt'); - } - - protected function initListeners() - { - require_once('./Services/GlobalCache/classes/class.ilGlobalCache.php'); - $ilGlobalCache = ilGlobalCache::getInstance(ilGlobalCache::COMP_EVENTS); - $cached_listeners = $ilGlobalCache->get('listeners'); - if (is_array($cached_listeners)) { - $this->listener = $cached_listeners; - - return; - } - - $ilDB = $this->db; - - $this->listener = array(); - - $sql = "SELECT * FROM il_event_handling". - " WHERE type = ".$ilDB->quote("listen", "text"); - $res = $ilDB->query($sql); - while($row = $ilDB->fetchAssoc($res)) - { - $this->listener[$row["id"]][] = $row["component"]; - } - - $ilGlobalCache->set('listeners', $this->listener); - } - - - - /** - * Raise an event. The event is passed to all interested listeners. - * - * @param string $a_component component, e.g. "Modules/Forum" or "Services/User" - * @param string $a_event event e.g. "createUser", "updateUser", "deleteUser", ... - * @param array $a_parameter parameter array (assoc), array("name" => ..., "phone_office" => ...) - */ - public function raise($a_component, $a_event, $a_parameter = "") - { - $this->logger->debug(sprintf( - "Received event '%s' from component '%s'.", - $a_event, $a_component - )); - - // lazy transforming event data to string - $this->logger->debug(new class($a_parameter) { - /** - * @var mixed - */ - protected $parameter; - - /** - * @param mixed $parameter - */ - public function __construct($parameter) - { - $this->parameter = $parameter; - } - - /** - * @return string - */ - public function __toString() - { - if(is_object($this->parameter)) { - return 'Event data class: ' . get_class($this->parameter); - } - - return 'Event data size: ' . sizeof($this->parameter); - //return 'Event data: ' . print_r($this->parameter, 1); - } - }); - - $this->logger->debug("Started event propagation for event listeners ..."); - - if (is_array($this->listener[$a_component])) - { - foreach ($this->listener[$a_component] as $listener) - { - // Allow listeners like Services/WebServices/ECS - $last_slash = strripos($listener,'/'); - $comp = substr($listener,0,$last_slash); - - // any kind of plugins with events in their plugin.xml - if ($comp == 'Plugins') - { - $name = substr($listener,$last_slash + 1); - - foreach (ilPluginAdmin::getActivePlugins() as $pdata) - { - if ($pdata['name'] == $name) - { - $plugin = ilPluginAdmin::getPluginObject( - $pdata['component_type'], - $pdata['component_name'], - $pdata['slot_id'], - $pdata['name']); - - $plugin->handleEvent($a_component, $a_event, $a_parameter); - } - } - } - else - { - $class = 'il'.substr($listener,$last_slash + 1).'AppEventListener'; - $file = "./".$listener."/classes/class.".$class.".php"; - - // if file exists, call listener - if (is_file($file)) - { - include_once($file); - call_user_func(array($class, 'handleEvent'), $a_component, $a_event, $a_parameter); - } - } - } - } - - $this->logger->debug("Finished event listener handling, started event propagation for event hook plugins ..."); - - // get all event hook plugins and forward the event to them - include_once("./Services/Component/classes/class.ilPluginAdmin.php"); - $plugins = ilPluginAdmin::getActivePluginsForSlot("Services", "EventHandling", "evhk"); - foreach ($plugins as $pl) - { - $plugin = ilPluginAdmin::getPluginObject("Services", "EventHandling", - "evhk", $pl); - $plugin->handleEvent($a_component, $a_event, $a_parameter); - } - - $this->logger->debug("Finished event hook plugin handling, started event propagation for workflow engine ..."); - - $workflow_engine = new ilWorkflowEngine(false); - $workflow_engine->handleEvent($a_component, $a_event, $a_parameter); - - $this->logger->debug("Finished workflow engine handling."); - } + /** + * @var ilDB + */ + protected $db; + + protected $listener; // [array] + + /** + * @var ilLogger + */ + protected $logger; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->db = $DIC->database(); + $this->initListeners(); + + $this->logger = \ilLoggerFactory::getLogger('evnt'); + } + + protected function initListeners() + { + require_once('./Services/GlobalCache/classes/class.ilGlobalCache.php'); + $ilGlobalCache = ilGlobalCache::getInstance(ilGlobalCache::COMP_EVENTS); + $cached_listeners = $ilGlobalCache->get('listeners'); + if (is_array($cached_listeners)) { + $this->listener = $cached_listeners; + + return; + } + + $ilDB = $this->db; + + $this->listener = array(); + + $sql = "SELECT * FROM il_event_handling" . + " WHERE type = " . $ilDB->quote("listen", "text"); + $res = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($res)) { + $this->listener[$row["id"]][] = $row["component"]; + } + + $ilGlobalCache->set('listeners', $this->listener); + } + + + + /** + * Raise an event. The event is passed to all interested listeners. + * + * @param string $a_component component, e.g. "Modules/Forum" or "Services/User" + * @param string $a_event event e.g. "createUser", "updateUser", "deleteUser", ... + * @param array $a_parameter parameter array (assoc), array("name" => ..., "phone_office" => ...) + */ + public function raise($a_component, $a_event, $a_parameter = "") + { + $this->logger->debug(sprintf( + "Received event '%s' from component '%s'.", + $a_event, + $a_component + )); + + // lazy transforming event data to string + $this->logger->debug(new class($a_parameter) { + /** + * @var mixed + */ + protected $parameter; + + /** + * @param mixed $parameter + */ + public function __construct($parameter) + { + $this->parameter = $parameter; + } + + /** + * @return string + */ + public function __toString() + { + if (is_object($this->parameter)) { + return 'Event data class: ' . get_class($this->parameter); + } + + return 'Event data size: ' . sizeof($this->parameter); + //return 'Event data: ' . print_r($this->parameter, 1); + } + }); + + $this->logger->debug("Started event propagation for event listeners ..."); + + if (is_array($this->listener[$a_component])) { + foreach ($this->listener[$a_component] as $listener) { + // Allow listeners like Services/WebServices/ECS + $last_slash = strripos($listener, '/'); + $comp = substr($listener, 0, $last_slash); + + // any kind of plugins with events in their plugin.xml + if ($comp == 'Plugins') { + $name = substr($listener, $last_slash + 1); + + foreach (ilPluginAdmin::getActivePlugins() as $pdata) { + if ($pdata['name'] == $name) { + $plugin = ilPluginAdmin::getPluginObject( + $pdata['component_type'], + $pdata['component_name'], + $pdata['slot_id'], + $pdata['name'] + ); + + $plugin->handleEvent($a_component, $a_event, $a_parameter); + } + } + } else { + $class = 'il' . substr($listener, $last_slash + 1) . 'AppEventListener'; + $file = "./" . $listener . "/classes/class." . $class . ".php"; + + // if file exists, call listener + if (is_file($file)) { + include_once($file); + call_user_func(array($class, 'handleEvent'), $a_component, $a_event, $a_parameter); + } + } + } + } + + $this->logger->debug("Finished event listener handling, started event propagation for event hook plugins ..."); + + // get all event hook plugins and forward the event to them + include_once("./Services/Component/classes/class.ilPluginAdmin.php"); + $plugins = ilPluginAdmin::getActivePluginsForSlot("Services", "EventHandling", "evhk"); + foreach ($plugins as $pl) { + $plugin = ilPluginAdmin::getPluginObject( + "Services", + "EventHandling", + "evhk", + $pl + ); + $plugin->handleEvent($a_component, $a_event, $a_parameter); + } + + $this->logger->debug("Finished event hook plugin handling, started event propagation for workflow engine ..."); + + $workflow_engine = new ilWorkflowEngine(false); + $workflow_engine->handleEvent($a_component, $a_event, $a_parameter); + + $this->logger->debug("Finished workflow engine handling."); + } } -?> diff --git a/Services/EventHandling/classes/class.ilEventHandlingService.php b/Services/EventHandling/classes/class.ilEventHandlingService.php index 39bbd76cf49000a1d9f7ae5d41b8257a51390530..adb92b76cc690056679fb4c17a4e6ed2ab8412ee 100755 --- a/Services/EventHandling/classes/class.ilEventHandlingService.php +++ b/Services/EventHandling/classes/class.ilEventHandlingService.php @@ -1,24 +1,24 @@ diff --git a/Services/EventHandling/classes/class.ilEventHookPlugin.php b/Services/EventHandling/classes/class.ilEventHookPlugin.php index 1290fcfafd34105dc97bae1a12ae039abd02a8ac..941135745b263f1b5f92cb09382deee062dfe9da 100755 --- a/Services/EventHandling/classes/class.ilEventHookPlugin.php +++ b/Services/EventHandling/classes/class.ilEventHookPlugin.php @@ -1,24 +1,24 @@ diff --git a/Services/EventHandling/interfaces/interface.ilAppEventListener.php b/Services/EventHandling/interfaces/interface.ilAppEventListener.php index ca596955a150b68b3a7021dbfab07f83dc837b84..840c9ac288af6bd0b89811b794f37370f068c841 100644 --- a/Services/EventHandling/interfaces/interface.ilAppEventListener.php +++ b/Services/EventHandling/interfaces/interface.ilAppEventListener.php @@ -1,24 +1,24 @@ ..., "phone_office" => ...) - */ - static function handleEvent($a_component, $a_event, $a_parameter); + /** + * Handle an event in a listener. + * + * @param string $a_component component, e.g. "Modules/Forum" or "Services/User" + * @param string $a_event event e.g. "createUser", "updateUser", "deleteUser", ... + * @param array $a_parameter parameter array (assoc), array("name" => ..., "phone_office" => ...) + */ + public static function handleEvent($a_component, $a_event, $a_parameter); } -?> diff --git a/Services/Excel/classes/class.ilExcel.php b/Services/Excel/classes/class.ilExcel.php index db2c14a570caa40ecd8e86906966c2b634645eef..d71eeeb21aa319a137d98510b4d3fcd7e0c225ec 100644 --- a/Services/Excel/classes/class.ilExcel.php +++ b/Services/Excel/classes/class.ilExcel.php @@ -21,606 +21,571 @@ use PhpOffice\PhpSpreadsheet\Cell\DataType; */ class ilExcel { - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var PhpOffice\PhpSpreadsheet\ - */ - protected $workbook; // [PhpSpreadsheet] - - /** - * @var string - */ - protected $type; // [string] - - const FORMAT_XML = "Xlsx"; - const FORMAT_BIFF = "Xls"; - - /** - * Constructor - * - * @return self - */ - public function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - $this->setFormat(self::FORMAT_XML); - $this->workbook = new Spreadsheet(); - $this->workbook->removeSheetByIndex(0); - } - - // - // loading files - // - - /** - * Loads a spreadsheet from file - * @param $filename - */ - public function loadFromFile($filename) { - $this->workbook = IOFactory::load($filename); - } - - // - // type/format - // - - /** - * Get valid file formats - * - * @return array - */ - public function getValidFormats() - { - return array(self::FORMAT_XML, self::FORMAT_BIFF); - } - - /** - * Set file format - * - * @param string $a_format - */ - public function setFormat($a_format) - { - if(in_array($a_format, $this->getValidFormats())) - { - $this->format = $a_format; - } - } - - - // - // sheets - // - - /** - * Add sheet - * - * @param string $a_name - * @param bool $a_activate - * @return int index - */ - public function addSheet($a_name, $a_activate = true) - { - #20749 - // see Worksheet::$_invalidCharacters; - $invalid = array('*', ':', '/', '\\', '?', '[', ']', '\'-','\''); - - $a_name = str_replace($invalid, "", $a_name); - - // #19056 - phpExcel only allows 31 chars - // see https://github.com/PHPOffice/PHPExcel/issues/79 - $a_name = ilUtil::shortenText($a_name, 31); - - $sheet = new Worksheet($this->workbook, $a_name); - $this->workbook->addSheet($sheet); - $new_index = $this->workbook->getSheetCount()-1; - - if((bool)$a_activate) - { - $this->setActiveSheet($new_index); - } - - return $new_index; - } - - /** - * Set active sheet - * - * @param int $a_index - */ - public function setActiveSheet($a_index) - { - $this->workbook->setActiveSheetIndex($a_index); - } - - - /** - * Returns number of sheets - * - * @return int - */ - public function getSheetCount() { - return $this->workbook->getSheetCount(); - } - - - /** - * Return the current sheet title - * - * @return string - */ - public function getSheetTitle() { - return $this->workbook->getActiveSheet()->getTitle(); - } - - - // - // cells - // - - /** - * Prepare value for cell - * - * @param mixed $a_value - * @return mixed - */ - protected function prepareValue($a_value) - { - $lng = $this->lng; - - // :TODO: does this make sense? - if(is_bool($a_value)) - { - $a_value = $this->prepareBooleanValue($a_value); - } - else if($a_value instanceof ilDateTime) - { - $a_value = $this->prepareDateValue($a_value); - } - else if(is_string($a_value)) - { - $a_value = $this->prepareString($a_value); - } - - return $a_value; - } - - /** - * @param ilDateTime $a_value - * @return string - */ - protected function prepareDateValue(ilDateTime $a_value) - { - switch(true) - { - case $a_value instanceof ilDate: - $a_value = Date::stringToExcel($a_value->get(IL_CAL_DATE)); - break; - - default: - $a_value = Date::stringToExcel($a_value->get(IL_CAL_DATETIME)); - break; - } - - return $a_value; - } - - /** - * @param bool $a_value - * @return string - */ - protected function prepareBooleanValue($a_value) - { - $lng = $this->lng; - - return $a_value ? $lng->txt('yes') : $lng->txt('no'); - } - - /** - * @param string $a_value - * @return string - */ - protected function prepareString($a_value) - { - return strip_tags($a_value); // #14542 - } - - /** - * Set date format - * - * @param Cell $a_cell - * @param mixed $a_value - */ - protected function setDateFormat(Cell $a_cell, $a_value) - { - if($a_value instanceof ilDate) - { - // :TODO: i18n? - $a_cell->getStyle()->getNumberFormat()->setFormatCode("dd.mm.yyyy"); - } - else if($a_value instanceof ilDateTime) - { - // :TODO: i18n? - $a_cell->getStyle()->getNumberFormat()->setFormatCode("dd.mm.yyyy hh:mm:ss"); - } - } - - /** - * Set cell value by coordinates - * - * @param string $a_coords - * @param mixed $a_value - */ - public function setCellByCoordinates($a_coords, $a_value) - { - if($a_value instanceof ilDateTime) - { - $wb = $this->workbook->getActiveSheet()->setCellValue( - $a_coords, - $this->prepareValue($a_value) - ); - $cell = $wb->getCell($a_coords); - $this->setDateFormat($cell, $a_value); - } - elseif(is_numeric($a_value)) - { - $this->workbook->getActiveSheet()->setCellValueExplicit( - $a_coords, - $this->prepareValue($a_value), - DataType::TYPE_NUMERIC - ); - - } - else - { - $this->workbook->getActiveSheet()->setCellValueExplicit( - $a_coords, - $this->prepareValue($a_value), - DataType::TYPE_STRING - ); - - } - - } - - /** - * Set cell value - * - * @param int $a_row - * @param int $a_col - * @param mixed $a_value - */ - public function setCell($a_row, $a_col, $a_value) - { - $col = $this->columnIndexAdjustment($a_col); - - if($a_value instanceof ilDateTime) - { - $wb = $this->workbook->getActiveSheet()->setCellValueByColumnAndRow( - $col, - $a_row, - $this->prepareValue($a_value) - ); - $this->setDateFormat($wb->getCellByColumnAndRow($col, $a_row), $a_value); - } - elseif(is_numeric($a_value)) - { - $wb = $this->workbook->getActiveSheet()->setCellValueExplicitByColumnAndRow( - $col, - $a_row, - $this->prepareValue($a_value), - DataType::TYPE_NUMERIC - ); - } - else - { - $wb = $this->workbook->getActiveSheet()->setCellValueExplicitByColumnAndRow( - $col, - $a_row, - $this->prepareValue($a_value), - DataType::TYPE_STRING - ); - } - - } - - /** - * Set cell values from array - * - * @param array $a_values - * @param string $a_top_left - * @param mixed $a_null_value - */ - public function setCellArray(array $a_values, $a_top_left = "A1", $a_null_value = NULL) - { - foreach($a_values as $row_idx => $cols) - { - if(is_array($cols)) - { - foreach($cols as $col_idx => $col_value) - { - $a_values[$row_idx][$col_idx] = $this->prepareValue($col_value); - } - } - else - { - $a_values[$row_idx] = $this->prepareValue($cols); - } - } - - $this->workbook->getActiveSheet()->fromArray($a_values, $a_null_value, $a_top_left); - } - - - /** - * Returns the value of a cell - * - * @param int $a_row - * @param int $a_col - * - * @return mixed - */ - public function getCell($a_row, $a_col) - { - $col = $this->columnIndexAdjustment($a_col); - - return $this->workbook->getActiveSheet()->getCellByColumnAndRow($col, $a_row)->getValue(); - } - - - /** - * Returns the active sheet as an array - * - * @return array - */ - public function getSheetAsArray() { - return $this->workbook->getActiveSheet()->toArray(); - } - - - /** - * Returns the number of columns the sheet contains - * - * @return int - */ - public function getColumnCount() { - return Coordinate::columnIndexFromString($this->workbook->getActiveSheet()->getHighestDataColumn()); - } - - /** - * Get column "name" from number - * - * @param int $a_col - * @return string - */ - public function getColumnCoord($a_col) - { - $col = $this->columnIndexAdjustment($a_col); - - return Coordinate::stringFromColumnIndex($col); - } - - /** - * Set all existing columns on all sheets to autosize - */ - protected function setGlobalAutoSize() - { - // this may change the active sheet - foreach($this->workbook->getWorksheetIterator() as $worksheet) - { - $this->workbook->setActiveSheetIndex($this->workbook->getIndex($worksheet)); - $sheet = $this->workbook->getActiveSheet(); - $cellIterator = $sheet->getRowIterator()->current()->getCellIterator(); - $cellIterator->setIterateOnlyExistingCells(true); - foreach($cellIterator as $cell) - { - $sheet->getColumnDimension($cell->getColumn())->setAutoSize(true); - } - } - } - - // - // deliver/save - // - - /** - * Prepare workbook for storage/delivery - */ - protected function prepareStorage($a_file_name) - { - $this->setGlobalAutoSize(); - $this->workbook->setActiveSheetIndex(0); - - switch($this->format) - { - case self::FORMAT_BIFF: - if(!stristr($a_file_name, ".xls")) - { - $a_file_name .= ".xls"; - } - break; - - case self::FORMAT_XML: - if(!stristr($a_file_name, ".xlsx")) - { - $a_file_name .= ".xlsx"; - } - break; - } - - return $a_file_name; - } - - /** - * Send workbook to client - * - * @param string $a_file_name - */ - public function sendToClient($a_file_name) - { - require_once('./Services/FileDelivery/classes/class.ilPHPOutputDelivery.php'); - - $a_file_name = $this->prepareStorage($a_file_name); - switch ($this->format) { - case self::FORMAT_BIFF: - $a_mime_type = ilMimeTypeUtil::APPLICATION__VND_MS_EXCEL; - break; - - case self::FORMAT_XML: - $a_mime_type = ilMimeTypeUtil::APPLICATION__VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET; - break; - default: - $a_mime_type = ilMimeTypeUtil::APPLICATION__OCTET_STREAM; - break; - } - $tmp_name = ilUtil::ilTempnam(); - - $writer = IOFactory::createWriter($this->workbook, $this->format); - $writer->save($tmp_name); - - ilFileDelivery::deliverFileAttached($tmp_name, $a_file_name, $a_mime_type, true); - } - - /** - * Save workbook to file - * - * @param string $a_file full path - */ - public function writeToFile($a_file) - { - $a_file = $this->prepareStorage($a_file); - - $writer = IOFactory::createWriter($this->workbook, $this->format); - $writer->save($a_file); - } - - - /** - * @return string - * @throws \PHPExcel_Reader_Exception - */ - public function writeToTmpFile() { - $writer = IOFactory::createWriter($this->workbook, $this->format); - $filename = ilUtil::ilTempnam(); - $writer->save($filename); - - return $filename; - } - - // - // style (:TODO: more options?) - // - - /** - * Set cell(s) to bold - * - * @param string $a_coords - */ - public function setBold($a_coords) - { - $this->workbook->getActiveSheet()->getStyle($a_coords)->getFont()->setBold(true); - } - - /** - * Set cell(s) colors - * - * @param string $a_coords - * @param string $a_background - * @param string $a_font - */ - public function setColors($a_coords, $a_background, $a_font = null) - { - $opts = array( - 'fill' => array( - 'type' => Fill::FILL_SOLID, - 'color' => array('rgb' => $a_background) - ) - ); - - if($a_font) - { - $opts['font'] = array( - 'color' => array('rgb' => $a_font) - ); - } - - $this->workbook->getActiveSheet()->getStyle($a_coords)->applyFromArray($opts); - } - - /** - * Toggle cell(s) borders - * - * @param string $a_coords - * @param bool $a_top - * @param bool $a_right - * @param bool $a_bottom - * @param bool $a_left - */ - public function setBorders($a_coords, $a_top, $a_right = false, $a_bottom = false, $a_left = false) - { - $style = $this->workbook->getActiveSheet()->getStyle($a_coords); - - // :TODO: border styles? - if($a_top) - { - $style->getBorders()->getTop()->setBorderStyle(Border::BORDER_THIN); - } - if($a_right) - { - $style->getBorders()->getRight()->setBorderStyle(Border::BORDER_THIN); - } - if($a_bottom) - { - $style->getBorders()->getBottom()->setBorderStyle(Border::BORDER_THIN); - } - if($a_left) - { - $style->getBorders()->getLeft()->setBorderStyle(Border::BORDER_THIN); - } - } - - /** - * Get cell coordinate (e.g. "B2") for column and row number - * - * @param int $pColumn - * @param int $pRow - * @return string - */ - function getCoordByColumnAndRow($pColumn = 1, $pRow = 1) - { - $col = $this->columnIndexAdjustment($pColumn); - $columnLetter = Coordinate::stringFromColumnIndex($col); - - return $columnLetter . $pRow; - } - - /** - * @param $a_row int - * @param $a_column int - * @param $a_path - */ - function addLink($a_row, $a_column, $a_path) - { - $column = $this->columnIndexAdjustment($a_column); - - $this->workbook->getActiveSheet()->getCellByColumnAndRow($column,$a_row)->getHyperlink()->setUrl($a_path); - } - - /** - * Adjustment needed because of migration PHPExcel to PhpSpreadsheet. - * PhpExcel column was 0 index based and PhpSpreadshet set this index to 1 - * @param $column - * @return int - */ - function columnIndexAdjustment(int $column) : int - { - return ++$column; - } - -} \ No newline at end of file + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var PhpOffice\PhpSpreadsheet\ + */ + protected $workbook; // [PhpSpreadsheet] + + /** + * @var string + */ + protected $type; // [string] + + const FORMAT_XML = "Xlsx"; + const FORMAT_BIFF = "Xls"; + + /** + * Constructor + * + * @return self + */ + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + $this->setFormat(self::FORMAT_XML); + $this->workbook = new Spreadsheet(); + $this->workbook->removeSheetByIndex(0); + } + + // + // loading files + // + + /** + * Loads a spreadsheet from file + * @param $filename + */ + public function loadFromFile($filename) + { + $this->workbook = IOFactory::load($filename); + } + + // + // type/format + // + + /** + * Get valid file formats + * + * @return array + */ + public function getValidFormats() + { + return array(self::FORMAT_XML, self::FORMAT_BIFF); + } + + /** + * Set file format + * + * @param string $a_format + */ + public function setFormat($a_format) + { + if (in_array($a_format, $this->getValidFormats())) { + $this->format = $a_format; + } + } + + + // + // sheets + // + + /** + * Add sheet + * + * @param string $a_name + * @param bool $a_activate + * @return int index + */ + public function addSheet($a_name, $a_activate = true) + { + #20749 + // see Worksheet::$_invalidCharacters; + $invalid = array('*', ':', '/', '\\', '?', '[', ']', '\'-','\''); + + $a_name = str_replace($invalid, "", $a_name); + + // #19056 - phpExcel only allows 31 chars + // see https://github.com/PHPOffice/PHPExcel/issues/79 + $a_name = ilUtil::shortenText($a_name, 31); + + $sheet = new Worksheet($this->workbook, $a_name); + $this->workbook->addSheet($sheet); + $new_index = $this->workbook->getSheetCount()-1; + + if ((bool) $a_activate) { + $this->setActiveSheet($new_index); + } + + return $new_index; + } + + /** + * Set active sheet + * + * @param int $a_index + */ + public function setActiveSheet($a_index) + { + $this->workbook->setActiveSheetIndex($a_index); + } + + + /** + * Returns number of sheets + * + * @return int + */ + public function getSheetCount() + { + return $this->workbook->getSheetCount(); + } + + + /** + * Return the current sheet title + * + * @return string + */ + public function getSheetTitle() + { + return $this->workbook->getActiveSheet()->getTitle(); + } + + + // + // cells + // + + /** + * Prepare value for cell + * + * @param mixed $a_value + * @return mixed + */ + protected function prepareValue($a_value) + { + $lng = $this->lng; + + // :TODO: does this make sense? + if (is_bool($a_value)) { + $a_value = $this->prepareBooleanValue($a_value); + } elseif ($a_value instanceof ilDateTime) { + $a_value = $this->prepareDateValue($a_value); + } elseif (is_string($a_value)) { + $a_value = $this->prepareString($a_value); + } + + return $a_value; + } + + /** + * @param ilDateTime $a_value + * @return string + */ + protected function prepareDateValue(ilDateTime $a_value) + { + switch (true) { + case $a_value instanceof ilDate: + $a_value = Date::stringToExcel($a_value->get(IL_CAL_DATE)); + break; + + default: + $a_value = Date::stringToExcel($a_value->get(IL_CAL_DATETIME)); + break; + } + + return $a_value; + } + + /** + * @param bool $a_value + * @return string + */ + protected function prepareBooleanValue($a_value) + { + $lng = $this->lng; + + return $a_value ? $lng->txt('yes') : $lng->txt('no'); + } + + /** + * @param string $a_value + * @return string + */ + protected function prepareString($a_value) + { + return strip_tags($a_value); // #14542 + } + + /** + * Set date format + * + * @param Cell $a_cell + * @param mixed $a_value + */ + protected function setDateFormat(Cell $a_cell, $a_value) + { + if ($a_value instanceof ilDate) { + // :TODO: i18n? + $a_cell->getStyle()->getNumberFormat()->setFormatCode("dd.mm.yyyy"); + } elseif ($a_value instanceof ilDateTime) { + // :TODO: i18n? + $a_cell->getStyle()->getNumberFormat()->setFormatCode("dd.mm.yyyy hh:mm:ss"); + } + } + + /** + * Set cell value by coordinates + * + * @param string $a_coords + * @param mixed $a_value + */ + public function setCellByCoordinates($a_coords, $a_value) + { + if ($a_value instanceof ilDateTime) { + $wb = $this->workbook->getActiveSheet()->setCellValue( + $a_coords, + $this->prepareValue($a_value) + ); + $cell = $wb->getCell($a_coords); + $this->setDateFormat($cell, $a_value); + } elseif (is_numeric($a_value)) { + $this->workbook->getActiveSheet()->setCellValueExplicit( + $a_coords, + $this->prepareValue($a_value), + DataType::TYPE_NUMERIC + ); + } else { + $this->workbook->getActiveSheet()->setCellValueExplicit( + $a_coords, + $this->prepareValue($a_value), + DataType::TYPE_STRING + ); + } + } + + /** + * Set cell value + * + * @param int $a_row + * @param int $a_col + * @param mixed $a_value + */ + public function setCell($a_row, $a_col, $a_value) + { + $col = $this->columnIndexAdjustment($a_col); + + if ($a_value instanceof ilDateTime) { + $wb = $this->workbook->getActiveSheet()->setCellValueByColumnAndRow( + $col, + $a_row, + $this->prepareValue($a_value) + ); + $this->setDateFormat($wb->getCellByColumnAndRow($col, $a_row), $a_value); + } elseif (is_numeric($a_value)) { + $wb = $this->workbook->getActiveSheet()->setCellValueExplicitByColumnAndRow( + $col, + $a_row, + $this->prepareValue($a_value), + DataType::TYPE_NUMERIC + ); + } else { + $wb = $this->workbook->getActiveSheet()->setCellValueExplicitByColumnAndRow( + $col, + $a_row, + $this->prepareValue($a_value), + DataType::TYPE_STRING + ); + } + } + + /** + * Set cell values from array + * + * @param array $a_values + * @param string $a_top_left + * @param mixed $a_null_value + */ + public function setCellArray(array $a_values, $a_top_left = "A1", $a_null_value = null) + { + foreach ($a_values as $row_idx => $cols) { + if (is_array($cols)) { + foreach ($cols as $col_idx => $col_value) { + $a_values[$row_idx][$col_idx] = $this->prepareValue($col_value); + } + } else { + $a_values[$row_idx] = $this->prepareValue($cols); + } + } + + $this->workbook->getActiveSheet()->fromArray($a_values, $a_null_value, $a_top_left); + } + + + /** + * Returns the value of a cell + * + * @param int $a_row + * @param int $a_col + * + * @return mixed + */ + public function getCell($a_row, $a_col) + { + $col = $this->columnIndexAdjustment($a_col); + + return $this->workbook->getActiveSheet()->getCellByColumnAndRow($col, $a_row)->getValue(); + } + + + /** + * Returns the active sheet as an array + * + * @return array + */ + public function getSheetAsArray() + { + return $this->workbook->getActiveSheet()->toArray(); + } + + + /** + * Returns the number of columns the sheet contains + * + * @return int + */ + public function getColumnCount() + { + return Coordinate::columnIndexFromString($this->workbook->getActiveSheet()->getHighestDataColumn()); + } + + /** + * Get column "name" from number + * + * @param int $a_col + * @return string + */ + public function getColumnCoord($a_col) + { + $col = $this->columnIndexAdjustment($a_col); + + return Coordinate::stringFromColumnIndex($col); + } + + /** + * Set all existing columns on all sheets to autosize + */ + protected function setGlobalAutoSize() + { + // this may change the active sheet + foreach ($this->workbook->getWorksheetIterator() as $worksheet) { + $this->workbook->setActiveSheetIndex($this->workbook->getIndex($worksheet)); + $sheet = $this->workbook->getActiveSheet(); + $cellIterator = $sheet->getRowIterator()->current()->getCellIterator(); + $cellIterator->setIterateOnlyExistingCells(true); + foreach ($cellIterator as $cell) { + $sheet->getColumnDimension($cell->getColumn())->setAutoSize(true); + } + } + } + + // + // deliver/save + // + + /** + * Prepare workbook for storage/delivery + */ + protected function prepareStorage($a_file_name) + { + $this->setGlobalAutoSize(); + $this->workbook->setActiveSheetIndex(0); + + switch ($this->format) { + case self::FORMAT_BIFF: + if (!stristr($a_file_name, ".xls")) { + $a_file_name .= ".xls"; + } + break; + + case self::FORMAT_XML: + if (!stristr($a_file_name, ".xlsx")) { + $a_file_name .= ".xlsx"; + } + break; + } + + return $a_file_name; + } + + /** + * Send workbook to client + * + * @param string $a_file_name + */ + public function sendToClient($a_file_name) + { + require_once('./Services/FileDelivery/classes/class.ilPHPOutputDelivery.php'); + + $a_file_name = $this->prepareStorage($a_file_name); + switch ($this->format) { + case self::FORMAT_BIFF: + $a_mime_type = ilMimeTypeUtil::APPLICATION__VND_MS_EXCEL; + break; + + case self::FORMAT_XML: + $a_mime_type = ilMimeTypeUtil::APPLICATION__VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET; + break; + default: + $a_mime_type = ilMimeTypeUtil::APPLICATION__OCTET_STREAM; + break; + } + $tmp_name = ilUtil::ilTempnam(); + + $writer = IOFactory::createWriter($this->workbook, $this->format); + $writer->save($tmp_name); + + ilFileDelivery::deliverFileAttached($tmp_name, $a_file_name, $a_mime_type, true); + } + + /** + * Save workbook to file + * + * @param string $a_file full path + */ + public function writeToFile($a_file) + { + $a_file = $this->prepareStorage($a_file); + + $writer = IOFactory::createWriter($this->workbook, $this->format); + $writer->save($a_file); + } + + + /** + * @return string + * @throws \PHPExcel_Reader_Exception + */ + public function writeToTmpFile() + { + $writer = IOFactory::createWriter($this->workbook, $this->format); + $filename = ilUtil::ilTempnam(); + $writer->save($filename); + + return $filename; + } + + // + // style (:TODO: more options?) + // + + /** + * Set cell(s) to bold + * + * @param string $a_coords + */ + public function setBold($a_coords) + { + $this->workbook->getActiveSheet()->getStyle($a_coords)->getFont()->setBold(true); + } + + /** + * Set cell(s) colors + * + * @param string $a_coords + * @param string $a_background + * @param string $a_font + */ + public function setColors($a_coords, $a_background, $a_font = null) + { + $opts = array( + 'fill' => array( + 'type' => Fill::FILL_SOLID, + 'color' => array('rgb' => $a_background) + ) + ); + + if ($a_font) { + $opts['font'] = array( + 'color' => array('rgb' => $a_font) + ); + } + + $this->workbook->getActiveSheet()->getStyle($a_coords)->applyFromArray($opts); + } + + /** + * Toggle cell(s) borders + * + * @param string $a_coords + * @param bool $a_top + * @param bool $a_right + * @param bool $a_bottom + * @param bool $a_left + */ + public function setBorders($a_coords, $a_top, $a_right = false, $a_bottom = false, $a_left = false) + { + $style = $this->workbook->getActiveSheet()->getStyle($a_coords); + + // :TODO: border styles? + if ($a_top) { + $style->getBorders()->getTop()->setBorderStyle(Border::BORDER_THIN); + } + if ($a_right) { + $style->getBorders()->getRight()->setBorderStyle(Border::BORDER_THIN); + } + if ($a_bottom) { + $style->getBorders()->getBottom()->setBorderStyle(Border::BORDER_THIN); + } + if ($a_left) { + $style->getBorders()->getLeft()->setBorderStyle(Border::BORDER_THIN); + } + } + + /** + * Get cell coordinate (e.g. "B2") for column and row number + * + * @param int $pColumn + * @param int $pRow + * @return string + */ + public function getCoordByColumnAndRow($pColumn = 1, $pRow = 1) + { + $col = $this->columnIndexAdjustment($pColumn); + $columnLetter = Coordinate::stringFromColumnIndex($col); + + return $columnLetter . $pRow; + } + + /** + * @param $a_row int + * @param $a_column int + * @param $a_path + */ + public function addLink($a_row, $a_column, $a_path) + { + $column = $this->columnIndexAdjustment($a_column); + + $this->workbook->getActiveSheet()->getCellByColumnAndRow($column, $a_row)->getHyperlink()->setUrl($a_path); + } + + /** + * Adjustment needed because of migration PHPExcel to PhpSpreadsheet. + * PhpExcel column was 0 index based and PhpSpreadshet set this index to 1 + * @param $column + * @return int + */ + public function columnIndexAdjustment(int $column) : int + { + return ++$column; + } +} diff --git a/Services/Export/classes/class.ilExport.php b/Services/Export/classes/class.ilExport.php index 2616d32320c891c6dd866ec2a38e2ae61cab8a54..2e9346382ea24fdc9ede45018c508ad33f28f3a6 100644 --- a/Services/Export/classes/class.ilExport.php +++ b/Services/Export/classes/class.ilExport.php @@ -12,611 +12,596 @@ */ class ilExport { - /** - * @var ilLogger - */ - protected $log; - - public static $new_file_structure = array('cat','exc','crs','sess','file','grp','frm', 'usr', 'catr', 'crsr', 'grpr'); - - // this should be part of module.xml and be parsed in the future - static $export_implementer = array("tst", "lm", "glo", "sahs"); - - protected $configs = array(); - - /** - * Default constructor - * @return - */ - public function __construct() - { - $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 ilExportConfig $a_comp configuration object or null - * @throws ilExportException - */ - 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]."ExportConfig"; - $export_config_file = "./".$a_comp."/classes/class.".$a_class.".php"; - if (!is_file($export_config_file)) - { - include_once("./Services/Export/exceptions/class.ilExportException.php"); - throw new ilExportException('Component "'.$a_comp.'" does not provide ExportConfig class.'); - } - include_once($export_config_file); - $exp_config = new $a_class(); - $this->configs[$a_comp] = $exp_config; - - return $exp_config; - } - - - /** - * Get a list of subitems of a repository resource, that implement - * the export. Includes also information on last export file. - */ - static function _getValidExportSubItems($a_ref_id) - { - global $DIC; - - $tree = $DIC['tree']; - - $valid_items = array(); - $sub_items = $tree->getSubTree($tree->getNodeData($a_ref_id)); - foreach ($sub_items as $sub_item) - { - if (in_array($sub_item["type"], self::$export_implementer)) - { - $valid_items[] = array("type" => $sub_item["type"], - "title" => $sub_item["title"], "ref_id" => $sub_item["child"], - "obj_id" => $sub_item["obj_id"], - "timestamp" => - ilExport::_getLastExportFileDate($sub_item["obj_id"], "xml", $sub_item["type"])); - } - } - return $valid_items; - } - - /** - * Get date of last export file - * - * @param int $a_obj_id object id - * @param string $a_type export type ("xml", "html", ...), default "xml" - * @param string $a_obj_type object type (optional, if not given, type is looked up) - */ - static function _getLastExportFileDate($a_obj_id, $a_type = "", $a_obj_type = "") - { - $files = ilExport::_getExportFiles($a_obj_id, $a_type, $a_obj_type); - if (is_array($files)) - { - $files = ilUtil::sortArray($files, "timestamp", "desc"); - return $files[0]["timestamp"]; - } - return false; - } - - /** - * Get last export file information - * - * @param int $a_obj_id object id - * @param string $a_type export type ("xml", "html", ...), default "xml" - * @param string $a_obj_type object type (optional, if not given, type is looked up) - */ - static function _getLastExportFileInformation($a_obj_id, $a_type = "", $a_obj_type = "") - { - $files = ilExport::_getExportFiles($a_obj_id, $a_type, $a_obj_type); - if (is_array($files)) - { - $files = ilUtil::sortArray($files, "timestamp", "desc"); - return $files[0]; - } - return false; - } - - /** - * Get export directory for an repository object - * - * @param int $a_obj_id object id - * @param string $a_type export type ("xml", "html", ...), default "xml" - * @param string $a_obj_type object type (optional, if not given, type is looked up) - * - * @return string export directory - */ - public static function _getExportDirectory($a_obj_id, $a_type = "xml", $a_obj_type = "", $a_entity = "") - { - global $DIC; - - $logger = $DIC->logger()->exp(); - - - $objDefinition = $DIC['objDefinition']; - - $ent = ($a_entity == "") - ? "" - : "_".$a_entity; - - - if ($a_obj_type == "") - { - $a_obj_type = ilObject::_lookupType($a_obj_id); - } - - if(in_array($a_obj_type, self::$new_file_structure)) - { - include_once './Services/FileSystem/classes/class.ilFileSystemStorage.php'; - $dir = ilUtil::getDataDir().DIRECTORY_SEPARATOR; - $dir .= 'il'.$objDefinition->getClassName($a_obj_type).$ent.DIRECTORY_SEPARATOR; - $dir .= ilFileSystemStorage::_createPathFromId($a_obj_id, $a_obj_type).DIRECTORY_SEPARATOR; - $dir .= ($a_type == 'xml' ? 'export' : 'export_'.$a_type); - return $dir; - } - - include_once './Services/Export/classes/class.ilImportExportFactory.php'; - $exporter_class = ilImportExportFactory::getExporterClass($a_obj_type); - $export_dir = call_user_func(array($exporter_class,'lookupExportDirectory'),$a_obj_type,$a_obj_id,$a_type,$a_entity); - - $logger->debug('Export dir is '.$export_dir); - return $export_dir; - } - - /** - * Get Export Files for a repository object - */ - static function _getExportFiles($a_obj_id, $a_export_types = "", $a_obj_type = "") - { - if ($a_obj_type == "") - { - $a_obj_type = ilObject::_lookupType($a_obj_id); - } - - if ($a_export_types == "") - { - $a_export_types = array("xml"); - } - if (!is_array($a_export_types)) - { - $a_export_types = array($a_export_types); - } - - // initialize array - $file = array(); - - $types = $a_export_types; - - foreach($types as $type) - { - $dir = ilExport::_getExportDirectory($a_obj_id, $type, $a_obj_type); - - // quit if import dir not available - if (!@is_dir($dir) or - !is_writeable($dir)) - { - continue; - } - - // open directory - $h_dir = dir($dir); - - // get files and save the in the array - while ($entry = $h_dir->read()) - { - if ($entry != "." and - $entry != ".." and - substr($entry, -4) == ".zip" and - preg_match("/^[0-9]{10}_{2}[0-9]+_{2}(".$a_obj_type."_)*[0-9]+\.zip\$/", $entry)) - { - $ts = substr($entry, 0, strpos($entry, "__")); - $file[$entry.$type] = array("type" => $type, "file" => $entry, - "size" => filesize($dir."/".$entry), - "timestamp" => $ts); - } - } - - // close import directory - $h_dir->close(); - } - - // sort files - ksort ($file); - reset ($file); - return $file; - } - - - /** - * @param $a_obj_id - * @param string $a_export_type - * @param string $a_obj_type - * @return bool - */ - public static function _createExportDirectory($a_obj_id, $a_export_type = "xml", $a_obj_type = "") - { - global $DIC; - - $ilErr = $DIC['ilErr']; - - if ($a_obj_type == "") - { - $a_obj_type = ilObject::_lookupType($a_obj_id); - } - - $edir = ilExport::_getExportDirectory($a_obj_id,$a_export_type,$a_obj_type); - ilUtil::makeDirParents($edir); - return true; - } - - /** - * Generates an index.html file including links to all xml files included - * (for container exports) - */ - static function _generateIndexFile($a_filename, $a_obj_id, $a_files, $a_type = "") - { - global $DIC; - - $lng = $DIC['lng']; - - $lng->loadLanguageModule("export"); - - if ($a_type == "") - { - $a_type = ilObject::_lookupType($a_obj_id); - } - $a_tpl = new ilTemplate("tpl.main.html", true, true); - $location_stylesheet = ilUtil::getStyleSheetLocation(); - $a_tpl->setVariable("LOCATION_STYLESHEET",$location_stylesheet); - $a_tpl->getStandardTemplate(); - $a_tpl->setTitle(ilObject::_lookupTitle($a_obj_id)); - $a_tpl->setDescription($lng->txt("export_export_date").": ". - date('Y-m-d H:i:s', time())." (".date_default_timezone_get().")"); - $f_tpl = new ilTemplate("tpl.export_list.html", true, true, "Services/Export"); - foreach ($a_files as $file) - { - $f_tpl->setCurrentBlock("file_row"); - $f_tpl->setVariable("TITLE", $file["title"]); - $f_tpl->setVariable("TYPE", $lng->txt("obj_".$file["type"])); - $f_tpl->setVariable("FILE", $file["file"]); - $f_tpl->parseCurrentBlock(); - } - $a_tpl->setContent($f_tpl->get()); - $index_content = $a_tpl->get("DEFAULT", false, false, false, true, false, false); - - $f = fopen ($a_filename, "w"); - fwrite($f, $index_content); - fclose($f); - } - - //// - //// New functions coming with 4.1 export revision - //// - - /*** - * - * - Walk through sequence - * - Each step in sequence creates one xml file, - * e.g. Services/Mediapool/set_1.xml - * - manifest.xml lists all files - * - * - * - * ... - * log->debug("export type: $a_type, id: $a_id, target_release: ".$a_target_release); - - // if no target release specified, use latest major release number - if ($a_target_release == "") - { - $v = explode(".", ILIAS_VERSION_NUMERIC); - $a_target_release = $v[0].".".$v[1].".0"; - $this->log->debug("target_release set to: ".$a_target_release); - } - - // manifest writer - include_once "./Services/Xml/classes/class.ilXmlWriter.php"; - $this->manifest_writer = new ilXmlWriter(); - $this->manifest_writer->xmlHeader(); - $this->manifest_writer->xmlStartTag( - 'Manifest', - array( - "MainEntity" => $a_type, - "Title" => ilObject::_lookupTitle($a_id), - "TargetRelease" => $a_target_release, - "InstallationId" => IL_INST_ID, - "InstallationUrl" => ILIAS_HTTP_PATH)); - - // get export class - ilExport::_createExportDirectory($a_id, "xml", $a_type); - $export_dir = ilExport::_getExportDirectory($a_id, "xml", $a_type); - $ts = time(); - - // Workaround for test assessment - $sub_dir = $ts.'__'.IL_INST_ID.'__'.$a_type.'_'.$a_id; - $new_file = $sub_dir.'.zip'; - - $this->export_run_dir = $export_dir."/".$sub_dir; - ilUtil::makeDirParents($this->export_run_dir); - $this->log->debug("export dir: ".$this->export_run_dir); - - $this->cnt = array(); - - include_once './Services/Export/classes/class.ilImportExportFactory.php'; - $class = ilImportExportFactory::getExporterClass($a_type); - $comp = ilImportExportFactory::getComponentForExport($a_type); - - $success = $this->processExporter($comp, $class, $a_type, $a_target_release, $a_id); - - $this->manifest_writer->xmlEndTag('Manifest'); - - $this->manifest_writer->xmlDumpFile($this->export_run_dir."/manifest.xml", false); - - // zip the file - $this->log->debug("zip: ".$export_dir."/".$new_file); - ilUtil::zip($this->export_run_dir, $export_dir."/".$new_file); - ilUtil::delDir($this->export_run_dir); - - // Store info about export - if($success) - { - include_once './Services/Export/classes/class.ilExportFileInfo.php'; - $exp = new ilExportFileInfo($a_id); - $exp->setVersion($a_target_release); - $exp->setCreationDate(new ilDateTime($ts,IL_CAL_UNIX)); - $exp->setExportType('xml'); - $exp->setFilename($new_file); - $exp->create(); - } - - return array( - "success" => $success, - "file" => $new_file, - "directory" => $export_dir - ); - } - - /** - * Export an ILIAS entity - * - * @param string $a_entity entity type, e.g. "sty" - * @param mixed $a_id entity id - * @param string $a_target_release target release - * @param string $a_component component that exports (e.g. "Services/Style") - * - * @return array success and info array - */ - function exportEntity($a_entity, $a_id, $a_target_release, - $a_component, $a_title, $a_export_dir, $a_type_for_file = "") - { - global $DIC; - - $objDefinition = $DIC['objDefinition']; - $tpl = $DIC['tpl']; - - // if no target release specified, use latest major release number - if ($a_target_release == "") - { - $v = explode(".", ILIAS_VERSION_NUMERIC); - $a_target_release = $v[0].".".$v[1].".0"; - } - - if ($a_type_for_file == "") - { - $a_type_for_file = $a_entity; - } - - $comp = $a_component; - $c = explode("/", $comp); - $class = "il".$c[1]."Exporter"; - - // manifest writer - include_once "./Services/Xml/classes/class.ilXmlWriter.php"; - $this->manifest_writer = new ilXmlWriter(); - $this->manifest_writer->xmlHeader(); - $this->manifest_writer->xmlStartTag( - 'Manifest', - array( - "MainEntity" => $a_entity, - "Title" => $a_title, - "TargetRelease" => $a_target_release, - "InstallationId" => IL_INST_ID, - "InstallationUrl" => ILIAS_HTTP_PATH)); - - $export_dir = $a_export_dir; - $ts = time(); - - // determine file name and subdirectory - $sub_dir = $ts.'__'.IL_INST_ID.'__'.$a_type_for_file.'_'.$a_id; - $new_file = $sub_dir.'.zip'; - - $this->export_run_dir = $export_dir."/".$sub_dir; - ilUtil::makeDirParents($this->export_run_dir); - - $this->cnt = array(); - - $success = $this->processExporter($comp, $class, $a_entity, $a_target_release, $a_id); - - $this->manifest_writer->xmlEndTag('Manifest'); - - $this->manifest_writer->xmlDumpFile($this->export_run_dir."/manifest.xml", false); - - // zip the file - ilUtil::zip($this->export_run_dir, $export_dir."/".$new_file); - ilUtil::delDir($this->export_run_dir); - - return array( - "success" => $success, - "file" => $new_file, - "directory" => $export_dir - ); - } - - /** - * Process exporter - * - * @param string $a_comp e.g. "Modules/Forum" - * @param string $a_class - * @param string $a_entity e.g. "frm" - * @param string $a_target_release e.g. "5.1.0" - * @param string $a_id id of entity (e.g. object id) - * @return bool success true/false - * @throws ilExportException - */ - function processExporter($a_comp, $a_class, $a_entity, $a_target_release, $a_id) - { - $success = true; - - $this->log->debug("process exporter, comp: ".$a_comp.", class: ".$a_class.", entity: ".$a_entity. - ", target release ".$a_target_release.", id: ".$a_id); - - if (!is_array($a_id)) - { - if ($a_id == "") - { - return; - } - $a_id = array($a_id); - } - - // get exporter object - if(!class_exists($a_class)) - { - $export_class_file = "./".$a_comp."/classes/class.".$a_class.".php"; - if (!is_file($export_class_file)) - { - include_once("./Services/Export/exceptions/class.ilExportException.php"); - throw new ilExportException('Export class file "'.$export_class_file.'" not found.'); - } - include_once($export_class_file); - } - - $exp = new $a_class(); - $exp->setExport($this); - if (!isset($this->cnt[$a_comp])) - { - $this->cnt[$a_comp] = 1; - } - else - { - $this->cnt[$a_comp]++; - } - $set_dir_relative = $a_comp."/set_".$this->cnt[$a_comp]; - $set_dir_absolute = $this->export_run_dir."/".$set_dir_relative; - ilUtil::makeDirParents($set_dir_absolute); - $this->log->debug("dir: ".$set_dir_absolute); - - $this->log->debug("init exporter"); - $exp->init(); - - // process head dependencies - $this->log->debug("process head dependencies for ".$a_entity); - $sequence = $exp->getXmlExportHeadDependencies($a_entity, $a_target_release, $a_id); - foreach ($sequence as $s) - { - $comp = explode("/", $s["component"]); - $exp_class = "il".$comp[1]."Exporter"; - $s = $this->processExporter($s["component"], $exp_class, - $s["entity"], $a_target_release, $s["ids"]); - if (!$s) - { - $success = false; - } - } - - // write export.xml file - $export_writer = new ilXmlWriter(); - $export_writer->xmlHeader(); - - $sv = $exp->determineSchemaVersion($a_entity, $a_target_release); - $this->log->debug("schema version for entity: $a_entity, target release: $a_target_release"); - $this->log->debug("...is: ".$sv["schema_version"].", namespace: ".$sv["namespace"]. - ", xsd file: ".$sv["xsd_file"].", uses_dataset: ".((int)$sv["uses_dataset"])); - - $attribs = array("InstallationId" => IL_INST_ID, - "InstallationUrl" => ILIAS_HTTP_PATH, - "Entity" => $a_entity, "SchemaVersion" => $sv["schema_version"], "TargetRelease" => $a_target_release, - "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance", - "xmlns:exp" => "http://www.ilias.de/Services/Export/exp/4_1", - "xsi:schemaLocation" => "http://www.ilias.de/Services/Export/exp/4_1 ".ILIAS_HTTP_PATH."/xml/ilias_export_4_1.xsd" - ); - if ($sv["namespace"] != "" && $sv["xsd_file"] != "") - { - $attribs["xsi:schemaLocation"].= " ".$sv["namespace"]." ". - ILIAS_HTTP_PATH."/xml/".$sv["xsd_file"]; - $attribs["xmlns"] = $sv["namespace"]; - } - if ($sv["uses_dataset"]) - { - $attribs["xsi:schemaLocation"].= " ". - "http://www.ilias.de/Services/DataSet/ds/4_3 ".ILIAS_HTTP_PATH."/xml/ilias_ds_4_3.xsd"; - $attribs["xmlns:ds"] = "http://www.ilias.de/Services/DataSet/ds/4_3"; - } - - - $export_writer->xmlStartTag('exp:Export', $attribs); - - $dir_cnt = 1; - foreach ($a_id as $id) - { - $exp->setExportDirectories($set_dir_relative."/expDir_".$dir_cnt, - $set_dir_absolute."/expDir_".$dir_cnt); - $export_writer->xmlStartTag('exp:ExportItem', array("Id" => $id)); - //$xml = $exp->getXmlRepresentation($a_entity, $a_target_release, $id); - $xml = $exp->getXmlRepresentation($a_entity, $sv["schema_version"], $id); - $export_writer->appendXml($xml); - $export_writer->xmlEndTag('exp:ExportItem'); - $dir_cnt++; - } - - $export_writer->xmlEndTag('exp:Export'); - $export_writer->xmlDumpFile($set_dir_absolute."/export.xml", false); - - $this->manifest_writer->xmlElement("ExportFile", - array("Component" => $a_comp, "Path" => $set_dir_relative."/export.xml")); - - // process tail dependencies - $this->log->debug("process tail dependencies of ".$a_entity); - $sequence = $exp->getXmlExportTailDependencies($a_entity, $a_target_release, $a_id); - foreach ($sequence as $s) - { - $comp = explode("/", $s["component"]); - $exp_class = "il".$comp[1]."Exporter"; - $s = $this->processExporter($s["component"], $exp_class, - $s["entity"], $a_target_release, $s["ids"]); - if (!$s) - { - $success = false; - } - } - - $this->log->debug("returning ".((int) $success)." for ".$a_entity); - return $success; - } + /** + * @var ilLogger + */ + protected $log; + + public static $new_file_structure = array('cat','exc','crs','sess','file','grp','frm', 'usr', 'catr', 'crsr', 'grpr'); + + // this should be part of module.xml and be parsed in the future + public static $export_implementer = array("tst", "lm", "glo", "sahs"); + + protected $configs = array(); + + /** + * Default constructor + * @return + */ + public function __construct() + { + $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 ilExportConfig $a_comp configuration object or null + * @throws ilExportException + */ + 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] . "ExportConfig"; + $export_config_file = "./" . $a_comp . "/classes/class." . $a_class . ".php"; + if (!is_file($export_config_file)) { + include_once("./Services/Export/exceptions/class.ilExportException.php"); + throw new ilExportException('Component "' . $a_comp . '" does not provide ExportConfig class.'); + } + include_once($export_config_file); + $exp_config = new $a_class(); + $this->configs[$a_comp] = $exp_config; + + return $exp_config; + } + + + /** + * Get a list of subitems of a repository resource, that implement + * the export. Includes also information on last export file. + */ + public static function _getValidExportSubItems($a_ref_id) + { + global $DIC; + + $tree = $DIC['tree']; + + $valid_items = array(); + $sub_items = $tree->getSubTree($tree->getNodeData($a_ref_id)); + foreach ($sub_items as $sub_item) { + if (in_array($sub_item["type"], self::$export_implementer)) { + $valid_items[] = array("type" => $sub_item["type"], + "title" => $sub_item["title"], "ref_id" => $sub_item["child"], + "obj_id" => $sub_item["obj_id"], + "timestamp" => + ilExport::_getLastExportFileDate($sub_item["obj_id"], "xml", $sub_item["type"])); + } + } + return $valid_items; + } + + /** + * Get date of last export file + * + * @param int $a_obj_id object id + * @param string $a_type export type ("xml", "html", ...), default "xml" + * @param string $a_obj_type object type (optional, if not given, type is looked up) + */ + public static function _getLastExportFileDate($a_obj_id, $a_type = "", $a_obj_type = "") + { + $files = ilExport::_getExportFiles($a_obj_id, $a_type, $a_obj_type); + if (is_array($files)) { + $files = ilUtil::sortArray($files, "timestamp", "desc"); + return $files[0]["timestamp"]; + } + return false; + } + + /** + * Get last export file information + * + * @param int $a_obj_id object id + * @param string $a_type export type ("xml", "html", ...), default "xml" + * @param string $a_obj_type object type (optional, if not given, type is looked up) + */ + public static function _getLastExportFileInformation($a_obj_id, $a_type = "", $a_obj_type = "") + { + $files = ilExport::_getExportFiles($a_obj_id, $a_type, $a_obj_type); + if (is_array($files)) { + $files = ilUtil::sortArray($files, "timestamp", "desc"); + return $files[0]; + } + return false; + } + + /** + * Get export directory for an repository object + * + * @param int $a_obj_id object id + * @param string $a_type export type ("xml", "html", ...), default "xml" + * @param string $a_obj_type object type (optional, if not given, type is looked up) + * + * @return string export directory + */ + public static function _getExportDirectory($a_obj_id, $a_type = "xml", $a_obj_type = "", $a_entity = "") + { + global $DIC; + + $logger = $DIC->logger()->exp(); + + + $objDefinition = $DIC['objDefinition']; + + $ent = ($a_entity == "") + ? "" + : "_" . $a_entity; + + + if ($a_obj_type == "") { + $a_obj_type = ilObject::_lookupType($a_obj_id); + } + + if (in_array($a_obj_type, self::$new_file_structure)) { + include_once './Services/FileSystem/classes/class.ilFileSystemStorage.php'; + $dir = ilUtil::getDataDir() . DIRECTORY_SEPARATOR; + $dir .= 'il' . $objDefinition->getClassName($a_obj_type) . $ent . DIRECTORY_SEPARATOR; + $dir .= ilFileSystemStorage::_createPathFromId($a_obj_id, $a_obj_type) . DIRECTORY_SEPARATOR; + $dir .= ($a_type == 'xml' ? 'export' : 'export_' . $a_type); + return $dir; + } + + include_once './Services/Export/classes/class.ilImportExportFactory.php'; + $exporter_class = ilImportExportFactory::getExporterClass($a_obj_type); + $export_dir = call_user_func(array($exporter_class,'lookupExportDirectory'), $a_obj_type, $a_obj_id, $a_type, $a_entity); + + $logger->debug('Export dir is ' . $export_dir); + return $export_dir; + } + + /** + * Get Export Files for a repository object + */ + public static function _getExportFiles($a_obj_id, $a_export_types = "", $a_obj_type = "") + { + if ($a_obj_type == "") { + $a_obj_type = ilObject::_lookupType($a_obj_id); + } + + if ($a_export_types == "") { + $a_export_types = array("xml"); + } + if (!is_array($a_export_types)) { + $a_export_types = array($a_export_types); + } + + // initialize array + $file = array(); + + $types = $a_export_types; + + foreach ($types as $type) { + $dir = ilExport::_getExportDirectory($a_obj_id, $type, $a_obj_type); + + // quit if import dir not available + if (!@is_dir($dir) or + !is_writeable($dir)) { + continue; + } + + // open directory + $h_dir = dir($dir); + + // get files and save the in the array + while ($entry = $h_dir->read()) { + if ($entry != "." and + $entry != ".." and + substr($entry, -4) == ".zip" and + preg_match("/^[0-9]{10}_{2}[0-9]+_{2}(" . $a_obj_type . "_)*[0-9]+\.zip\$/", $entry)) { + $ts = substr($entry, 0, strpos($entry, "__")); + $file[$entry . $type] = array("type" => $type, "file" => $entry, + "size" => filesize($dir . "/" . $entry), + "timestamp" => $ts); + } + } + + // close import directory + $h_dir->close(); + } + + // sort files + ksort($file); + reset($file); + return $file; + } + + + /** + * @param $a_obj_id + * @param string $a_export_type + * @param string $a_obj_type + * @return bool + */ + public static function _createExportDirectory($a_obj_id, $a_export_type = "xml", $a_obj_type = "") + { + global $DIC; + + $ilErr = $DIC['ilErr']; + + if ($a_obj_type == "") { + $a_obj_type = ilObject::_lookupType($a_obj_id); + } + + $edir = ilExport::_getExportDirectory($a_obj_id, $a_export_type, $a_obj_type); + ilUtil::makeDirParents($edir); + return true; + } + + /** + * Generates an index.html file including links to all xml files included + * (for container exports) + */ + public static function _generateIndexFile($a_filename, $a_obj_id, $a_files, $a_type = "") + { + global $DIC; + + $lng = $DIC['lng']; + + $lng->loadLanguageModule("export"); + + if ($a_type == "") { + $a_type = ilObject::_lookupType($a_obj_id); + } + $a_tpl = new ilTemplate("tpl.main.html", true, true); + $location_stylesheet = ilUtil::getStyleSheetLocation(); + $a_tpl->setVariable("LOCATION_STYLESHEET", $location_stylesheet); + $a_tpl->getStandardTemplate(); + $a_tpl->setTitle(ilObject::_lookupTitle($a_obj_id)); + $a_tpl->setDescription($lng->txt("export_export_date") . ": " . + date('Y-m-d H:i:s', time()) . " (" . date_default_timezone_get() . ")"); + $f_tpl = new ilTemplate("tpl.export_list.html", true, true, "Services/Export"); + foreach ($a_files as $file) { + $f_tpl->setCurrentBlock("file_row"); + $f_tpl->setVariable("TITLE", $file["title"]); + $f_tpl->setVariable("TYPE", $lng->txt("obj_" . $file["type"])); + $f_tpl->setVariable("FILE", $file["file"]); + $f_tpl->parseCurrentBlock(); + } + $a_tpl->setContent($f_tpl->get()); + $index_content = $a_tpl->get("DEFAULT", false, false, false, true, false, false); + + $f = fopen($a_filename, "w"); + fwrite($f, $index_content); + fclose($f); + } + + //// + //// New functions coming with 4.1 export revision + //// + + /*** + * + * - Walk through sequence + * - Each step in sequence creates one xml file, + * e.g. Services/Mediapool/set_1.xml + * - manifest.xml lists all files + * + * + * + * ... + * log->debug("export type: $a_type, id: $a_id, target_release: " . $a_target_release); + + // if no target release specified, use latest major release number + if ($a_target_release == "") { + $v = explode(".", ILIAS_VERSION_NUMERIC); + $a_target_release = $v[0] . "." . $v[1] . ".0"; + $this->log->debug("target_release set to: " . $a_target_release); + } + + // manifest writer + include_once "./Services/Xml/classes/class.ilXmlWriter.php"; + $this->manifest_writer = new ilXmlWriter(); + $this->manifest_writer->xmlHeader(); + $this->manifest_writer->xmlStartTag( + 'Manifest', + array( + "MainEntity" => $a_type, + "Title" => ilObject::_lookupTitle($a_id), + "TargetRelease" => $a_target_release, + "InstallationId" => IL_INST_ID, + "InstallationUrl" => ILIAS_HTTP_PATH) + ); + + // get export class + ilExport::_createExportDirectory($a_id, "xml", $a_type); + $export_dir = ilExport::_getExportDirectory($a_id, "xml", $a_type); + $ts = time(); + + // Workaround for test assessment + $sub_dir = $ts . '__' . IL_INST_ID . '__' . $a_type . '_' . $a_id; + $new_file = $sub_dir . '.zip'; + + $this->export_run_dir = $export_dir . "/" . $sub_dir; + ilUtil::makeDirParents($this->export_run_dir); + $this->log->debug("export dir: " . $this->export_run_dir); + + $this->cnt = array(); + + include_once './Services/Export/classes/class.ilImportExportFactory.php'; + $class = ilImportExportFactory::getExporterClass($a_type); + $comp = ilImportExportFactory::getComponentForExport($a_type); + + $success = $this->processExporter($comp, $class, $a_type, $a_target_release, $a_id); + + $this->manifest_writer->xmlEndTag('Manifest'); + + $this->manifest_writer->xmlDumpFile($this->export_run_dir . "/manifest.xml", false); + + // zip the file + $this->log->debug("zip: " . $export_dir . "/" . $new_file); + ilUtil::zip($this->export_run_dir, $export_dir . "/" . $new_file); + ilUtil::delDir($this->export_run_dir); + + // Store info about export + if ($success) { + include_once './Services/Export/classes/class.ilExportFileInfo.php'; + $exp = new ilExportFileInfo($a_id); + $exp->setVersion($a_target_release); + $exp->setCreationDate(new ilDateTime($ts, IL_CAL_UNIX)); + $exp->setExportType('xml'); + $exp->setFilename($new_file); + $exp->create(); + } + + return array( + "success" => $success, + "file" => $new_file, + "directory" => $export_dir + ); + } + + /** + * Export an ILIAS entity + * + * @param string $a_entity entity type, e.g. "sty" + * @param mixed $a_id entity id + * @param string $a_target_release target release + * @param string $a_component component that exports (e.g. "Services/Style") + * + * @return array success and info array + */ + public function exportEntity( + $a_entity, + $a_id, + $a_target_release, + $a_component, + $a_title, + $a_export_dir, + $a_type_for_file = "" + ) { + global $DIC; + + $objDefinition = $DIC['objDefinition']; + $tpl = $DIC['tpl']; + + // if no target release specified, use latest major release number + if ($a_target_release == "") { + $v = explode(".", ILIAS_VERSION_NUMERIC); + $a_target_release = $v[0] . "." . $v[1] . ".0"; + } + + if ($a_type_for_file == "") { + $a_type_for_file = $a_entity; + } + + $comp = $a_component; + $c = explode("/", $comp); + $class = "il" . $c[1] . "Exporter"; + + // manifest writer + include_once "./Services/Xml/classes/class.ilXmlWriter.php"; + $this->manifest_writer = new ilXmlWriter(); + $this->manifest_writer->xmlHeader(); + $this->manifest_writer->xmlStartTag( + 'Manifest', + array( + "MainEntity" => $a_entity, + "Title" => $a_title, + "TargetRelease" => $a_target_release, + "InstallationId" => IL_INST_ID, + "InstallationUrl" => ILIAS_HTTP_PATH) + ); + + $export_dir = $a_export_dir; + $ts = time(); + + // determine file name and subdirectory + $sub_dir = $ts . '__' . IL_INST_ID . '__' . $a_type_for_file . '_' . $a_id; + $new_file = $sub_dir . '.zip'; + + $this->export_run_dir = $export_dir . "/" . $sub_dir; + ilUtil::makeDirParents($this->export_run_dir); + + $this->cnt = array(); + + $success = $this->processExporter($comp, $class, $a_entity, $a_target_release, $a_id); + + $this->manifest_writer->xmlEndTag('Manifest'); + + $this->manifest_writer->xmlDumpFile($this->export_run_dir . "/manifest.xml", false); + + // zip the file + ilUtil::zip($this->export_run_dir, $export_dir . "/" . $new_file); + ilUtil::delDir($this->export_run_dir); + + return array( + "success" => $success, + "file" => $new_file, + "directory" => $export_dir + ); + } + + /** + * Process exporter + * + * @param string $a_comp e.g. "Modules/Forum" + * @param string $a_class + * @param string $a_entity e.g. "frm" + * @param string $a_target_release e.g. "5.1.0" + * @param string $a_id id of entity (e.g. object id) + * @return bool success true/false + * @throws ilExportException + */ + public function processExporter($a_comp, $a_class, $a_entity, $a_target_release, $a_id) + { + $success = true; + + $this->log->debug("process exporter, comp: " . $a_comp . ", class: " . $a_class . ", entity: " . $a_entity . + ", target release " . $a_target_release . ", id: " . $a_id); + + if (!is_array($a_id)) { + if ($a_id == "") { + return; + } + $a_id = array($a_id); + } + + // get exporter object + if (!class_exists($a_class)) { + $export_class_file = "./" . $a_comp . "/classes/class." . $a_class . ".php"; + if (!is_file($export_class_file)) { + include_once("./Services/Export/exceptions/class.ilExportException.php"); + throw new ilExportException('Export class file "' . $export_class_file . '" not found.'); + } + include_once($export_class_file); + } + + $exp = new $a_class(); + $exp->setExport($this); + if (!isset($this->cnt[$a_comp])) { + $this->cnt[$a_comp] = 1; + } else { + $this->cnt[$a_comp]++; + } + $set_dir_relative = $a_comp . "/set_" . $this->cnt[$a_comp]; + $set_dir_absolute = $this->export_run_dir . "/" . $set_dir_relative; + ilUtil::makeDirParents($set_dir_absolute); + $this->log->debug("dir: " . $set_dir_absolute); + + $this->log->debug("init exporter"); + $exp->init(); + + // process head dependencies + $this->log->debug("process head dependencies for " . $a_entity); + $sequence = $exp->getXmlExportHeadDependencies($a_entity, $a_target_release, $a_id); + foreach ($sequence as $s) { + $comp = explode("/", $s["component"]); + $exp_class = "il" . $comp[1] . "Exporter"; + $s = $this->processExporter( + $s["component"], + $exp_class, + $s["entity"], + $a_target_release, + $s["ids"] + ); + if (!$s) { + $success = false; + } + } + + // write export.xml file + $export_writer = new ilXmlWriter(); + $export_writer->xmlHeader(); + + $sv = $exp->determineSchemaVersion($a_entity, $a_target_release); + $this->log->debug("schema version for entity: $a_entity, target release: $a_target_release"); + $this->log->debug("...is: " . $sv["schema_version"] . ", namespace: " . $sv["namespace"] . + ", xsd file: " . $sv["xsd_file"] . ", uses_dataset: " . ((int) $sv["uses_dataset"])); + + $attribs = array("InstallationId" => IL_INST_ID, + "InstallationUrl" => ILIAS_HTTP_PATH, + "Entity" => $a_entity, "SchemaVersion" => $sv["schema_version"], "TargetRelease" => $a_target_release, + "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance", + "xmlns:exp" => "http://www.ilias.de/Services/Export/exp/4_1", + "xsi:schemaLocation" => "http://www.ilias.de/Services/Export/exp/4_1 " . ILIAS_HTTP_PATH . "/xml/ilias_export_4_1.xsd" + ); + if ($sv["namespace"] != "" && $sv["xsd_file"] != "") { + $attribs["xsi:schemaLocation"].= " " . $sv["namespace"] . " " . + ILIAS_HTTP_PATH . "/xml/" . $sv["xsd_file"]; + $attribs["xmlns"] = $sv["namespace"]; + } + if ($sv["uses_dataset"]) { + $attribs["xsi:schemaLocation"].= " " . + "http://www.ilias.de/Services/DataSet/ds/4_3 " . ILIAS_HTTP_PATH . "/xml/ilias_ds_4_3.xsd"; + $attribs["xmlns:ds"] = "http://www.ilias.de/Services/DataSet/ds/4_3"; + } + + + $export_writer->xmlStartTag('exp:Export', $attribs); + + $dir_cnt = 1; + foreach ($a_id as $id) { + $exp->setExportDirectories( + $set_dir_relative . "/expDir_" . $dir_cnt, + $set_dir_absolute . "/expDir_" . $dir_cnt + ); + $export_writer->xmlStartTag('exp:ExportItem', array("Id" => $id)); + //$xml = $exp->getXmlRepresentation($a_entity, $a_target_release, $id); + $xml = $exp->getXmlRepresentation($a_entity, $sv["schema_version"], $id); + $export_writer->appendXml($xml); + $export_writer->xmlEndTag('exp:ExportItem'); + $dir_cnt++; + } + + $export_writer->xmlEndTag('exp:Export'); + $export_writer->xmlDumpFile($set_dir_absolute . "/export.xml", false); + + $this->manifest_writer->xmlElement( + "ExportFile", + array("Component" => $a_comp, "Path" => $set_dir_relative . "/export.xml") + ); + + // process tail dependencies + $this->log->debug("process tail dependencies of " . $a_entity); + $sequence = $exp->getXmlExportTailDependencies($a_entity, $a_target_release, $a_id); + foreach ($sequence as $s) { + $comp = explode("/", $s["component"]); + $exp_class = "il" . $comp[1] . "Exporter"; + $s = $this->processExporter( + $s["component"], + $exp_class, + $s["entity"], + $a_target_release, + $s["ids"] + ); + if (!$s) { + $success = false; + } + } + + $this->log->debug("returning " . ((int) $success) . " for " . $a_entity); + return $success; + } } -?> diff --git a/Services/Export/classes/class.ilExportConfig.php b/Services/Export/classes/class.ilExportConfig.php index 9694edf9def13984a264644b8a3026b54ced68eb..5b00879419a4c7484a72566c062dcb09a3585718 100644 --- a/Services/Export/classes/class.ilExportConfig.php +++ b/Services/Export/classes/class.ilExportConfig.php @@ -11,8 +11,4 @@ */ abstract class ilExportConfig { - - } - -?> \ No newline at end of file diff --git a/Services/Export/classes/class.ilExportContainer.php b/Services/Export/classes/class.ilExportContainer.php index a9b7c11a3a4ddc5f0f303915916437380988fc70..dfcdd39b11fd3d329fb3e3cb8d466def2a698801 100644 --- a/Services/Export/classes/class.ilExportContainer.php +++ b/Services/Export/classes/class.ilExportContainer.php @@ -14,178 +14,171 @@ include_once './Services/Export/classes/class.ilExport.php'; */ class ilExportContainer extends ilExport { - private $cont_export_dir = ''; - private $cont_manifest_writer = null; - private $eo = null; - - - /** - * Constructor - * @param ilExportOptions $eo - * @return - */ - public function __construct(ilExportOptions $eo) - { - $this->eo = $eo; - parent::__construct(); - } - - /** - * Export a container - * - * @param object $a_type - * @param object $a_obj_id - * @param object $a_target_release - * @return - */ - public function exportObject($a_type, $a_id, $a_target_release = "") - { - $log = $GLOBALS['DIC']->logger()->exp(); + private $cont_export_dir = ''; + private $cont_manifest_writer = null; + private $eo = null; + + + /** + * Constructor + * @param ilExportOptions $eo + * @return + */ + public function __construct(ilExportOptions $eo) + { + $this->eo = $eo; + parent::__construct(); + } + + /** + * Export a container + * + * @param object $a_type + * @param object $a_obj_id + * @param object $a_target_release + * @return + */ + public function exportObject($a_type, $a_id, $a_target_release = "") + { + $log = $GLOBALS['DIC']->logger()->exp(); - // if no target release specified, use latest major release number - if ($a_target_release == "") - { - $v = explode(".", ILIAS_VERSION_NUMERIC); - $a_target_release = $v[0].".".$v[1].".0"; - } - - // Create base export directory - ilExport::_createExportDirectory($a_id, "xml", $a_type); - $export_dir = ilExport::_getExportDirectory($a_id, "xml", $a_type); - $ts = time(); - $sub_dir = $ts."__".IL_INST_ID."__".$a_type."_".$a_id; - - $this->cont_export_dir = $export_dir.DIRECTORY_SEPARATOR.$sub_dir; - ilUtil::makeDirParents($this->cont_export_dir); - - $log->debug('Using base directory: '.$this->export_run_dir); - - $this->manifestWriterBegin($a_type, $a_id, $a_target_release); - $this->addContainer(); - $this->addSubitems($a_id,$a_type,$a_target_release); - $this->manifestWriterEnd($a_type, $a_id, $a_target_release); + // if no target release specified, use latest major release number + if ($a_target_release == "") { + $v = explode(".", ILIAS_VERSION_NUMERIC); + $a_target_release = $v[0] . "." . $v[1] . ".0"; + } + + // Create base export directory + ilExport::_createExportDirectory($a_id, "xml", $a_type); + $export_dir = ilExport::_getExportDirectory($a_id, "xml", $a_type); + $ts = time(); + $sub_dir = $ts . "__" . IL_INST_ID . "__" . $a_type . "_" . $a_id; + + $this->cont_export_dir = $export_dir . DIRECTORY_SEPARATOR . $sub_dir; + ilUtil::makeDirParents($this->cont_export_dir); + + $log->debug('Using base directory: ' . $this->export_run_dir); + + $this->manifestWriterBegin($a_type, $a_id, $a_target_release); + $this->addContainer(); + $this->addSubitems($a_id, $a_type, $a_target_release); + $this->manifestWriterEnd($a_type, $a_id, $a_target_release); - ilUtil::zip($this->cont_export_dir, $this->cont_export_dir.'.zip'); - ilUtil::delDir($this->cont_export_dir); - } - - /** - * Write container manifest - * @return - */ - protected function manifestWriterBegin($a_type, $a_id, $a_target_release) - { - include_once "./Services/Xml/classes/class.ilXmlWriter.php"; - $this->cont_manifest_writer = new ilXmlWriter(); - $this->cont_manifest_writer->xmlHeader(); - $this->cont_manifest_writer->xmlStartTag( - 'Manifest', - array( - "MainEntity" => $a_type, - "Title" => ilObject::_lookupTitle($a_id), - "TargetRelease" => $a_target_release, - "InstallationId" => IL_INST_ID, - "InstallationUrl" => ILIAS_HTTP_PATH) - ); - } - - /** - * Add container description - * @return - */ - protected function addContainer() - { - - } - - - /** - * Add subitems - * @param object $a_id - * @param object $a_type - * @return - */ - protected function addSubitems($a_id,$a_type,$a_target_release) - { - global $DIC; + ilUtil::zip($this->cont_export_dir, $this->cont_export_dir . '.zip'); + ilUtil::delDir($this->cont_export_dir); + } + + /** + * Write container manifest + * @return + */ + protected function manifestWriterBegin($a_type, $a_id, $a_target_release) + { + include_once "./Services/Xml/classes/class.ilXmlWriter.php"; + $this->cont_manifest_writer = new ilXmlWriter(); + $this->cont_manifest_writer->xmlHeader(); + $this->cont_manifest_writer->xmlStartTag( + 'Manifest', + array( + "MainEntity" => $a_type, + "Title" => ilObject::_lookupTitle($a_id), + "TargetRelease" => $a_target_release, + "InstallationId" => IL_INST_ID, + "InstallationUrl" => ILIAS_HTTP_PATH) + ); + } + + /** + * Add container description + * @return + */ + protected function addContainer() + { + } + + + /** + * Add subitems + * @param object $a_id + * @param object $a_type + * @return + */ + protected function addSubitems($a_id, $a_type, $a_target_release) + { + global $DIC; - $logger = + $logger = - $set_number = 1; - foreach($this->eo->getSubitemsForExport() as $ref_id) - { - // get last export file - $obj_id = ilObject::_lookupObjId($ref_id); - - $expi = ilExportFileInfo::lookupLastExport($obj_id, 'xml',$a_target_release); - - if(!$expi instanceof ilExportFileInfo) - { - $this->log->warning('Cannot find export file for refId '.$ref_id.', type '.ilObject::_lookupType($a_id)); - continue; - } - - $exp_dir = ilExport::_getExportDirectory($obj_id,'xml',ilObject::_lookupType($obj_id)); - $exp_full = $exp_dir.DIRECTORY_SEPARATOR.$expi->getFilename(); - - $this->log->debug('Zip path '.$exp_full); - - // Unzip - ilUtil::unzip($exp_full,true,false); - - // create set directory - ilUtil::makeDirParents($this->cont_export_dir.DIRECTORY_SEPARATOR.'set_'.$set_number); - - // cut .zip - $new_path_rel = 'set_'.$set_number.DIRECTORY_SEPARATOR.$expi->getBasename(); - $new_path_abs = $this->cont_export_dir.DIRECTORY_SEPARATOR.$new_path_rel; - - $this->log->debug($new_path_rel.' '.$new_path_abs); + $set_number = 1; + foreach ($this->eo->getSubitemsForExport() as $ref_id) { + // get last export file + $obj_id = ilObject::_lookupObjId($ref_id); + + $expi = ilExportFileInfo::lookupLastExport($obj_id, 'xml', $a_target_release); + + if (!$expi instanceof ilExportFileInfo) { + $this->log->warning('Cannot find export file for refId ' . $ref_id . ', type ' . ilObject::_lookupType($a_id)); + continue; + } + + $exp_dir = ilExport::_getExportDirectory($obj_id, 'xml', ilObject::_lookupType($obj_id)); + $exp_full = $exp_dir . DIRECTORY_SEPARATOR . $expi->getFilename(); + + $this->log->debug('Zip path ' . $exp_full); + + // Unzip + ilUtil::unzip($exp_full, true, false); + + // create set directory + ilUtil::makeDirParents($this->cont_export_dir . DIRECTORY_SEPARATOR . 'set_' . $set_number); + + // cut .zip + $new_path_rel = 'set_' . $set_number . DIRECTORY_SEPARATOR . $expi->getBasename(); + $new_path_abs = $this->cont_export_dir . DIRECTORY_SEPARATOR . $new_path_rel; + + $this->log->debug($new_path_rel . ' ' . $new_path_abs); - // Move export - rename( - $exp_dir.DIRECTORY_SEPARATOR.$expi->getBasename(), - $new_path_abs - ); - - $this->log->debug($exp_dir.DIRECTORY_SEPARATOR.$expi->getBasename().' -> '.$new_path_abs); - - // Delete latest container xml of source - if($a_id == $obj_id) - { - $expi->delete(); - if(file_exists($exp_full)) - { - $this->log->info('Deleting'. $exp_full); - unlink($exp_full); - } - } - - $this->cont_manifest_writer->xmlElement( - 'ExportSet', - array( - 'Path' => $new_path_rel, - 'Type' => ilObject::_lookupType($obj_id) - ) - ); - - - ++$set_number; - } - } - - /** - * Write manifest footer - * @param object $a_type - * @param object $a_id - * @param object $a_target_release - * @return - */ - protected function manifestWriterEnd($a_type, $a_id, $a_target_release) - { - $this->cont_manifest_writer->xmlEndTag('Manifest'); - $this->log->debug($this->cont_export_dir.DIRECTORY_SEPARATOR.'manifest.xml'); - $this->cont_manifest_writer->xmlDumpFile($this->cont_export_dir.DIRECTORY_SEPARATOR.'manifest.xml',true); - } + // Move export + rename( + $exp_dir . DIRECTORY_SEPARATOR . $expi->getBasename(), + $new_path_abs + ); + + $this->log->debug($exp_dir . DIRECTORY_SEPARATOR . $expi->getBasename() . ' -> ' . $new_path_abs); + + // Delete latest container xml of source + if ($a_id == $obj_id) { + $expi->delete(); + if (file_exists($exp_full)) { + $this->log->info('Deleting' . $exp_full); + unlink($exp_full); + } + } + + $this->cont_manifest_writer->xmlElement( + 'ExportSet', + array( + 'Path' => $new_path_rel, + 'Type' => ilObject::_lookupType($obj_id) + ) + ); + + + ++$set_number; + } + } + + /** + * Write manifest footer + * @param object $a_type + * @param object $a_id + * @param object $a_target_release + * @return + */ + protected function manifestWriterEnd($a_type, $a_id, $a_target_release) + { + $this->cont_manifest_writer->xmlEndTag('Manifest'); + $this->log->debug($this->cont_export_dir . DIRECTORY_SEPARATOR . 'manifest.xml'); + $this->cont_manifest_writer->xmlDumpFile($this->cont_export_dir . DIRECTORY_SEPARATOR . 'manifest.xml', true); + } } -?> \ No newline at end of file diff --git a/Services/Export/classes/class.ilExportFileInfo.php b/Services/Export/classes/class.ilExportFileInfo.php index ca3a5eadc69336e02fb8517774243dde6082ada5..df3ad5820735e451277caa470b15c2f55939a3a7 100644 --- a/Services/Export/classes/class.ilExportFileInfo.php +++ b/Services/Export/classes/class.ilExportFileInfo.php @@ -12,244 +12,240 @@ */ class ilExportFileInfo { - const CURRENT_VERSION = "4.1.0"; - - - private $obj_id = 0; - private $version = self::CURRENT_VERSION; - private $export_type = ''; - private $file_name = ''; - private $create_date = null; + const CURRENT_VERSION = "4.1.0"; + + + private $obj_id = 0; + private $version = self::CURRENT_VERSION; + private $export_type = ''; + private $file_name = ''; + private $create_date = null; - /** - * ilExportFileInfo constructor. - * @param int $a_obj_id - * @param string $a_export_type - * @param string $a_filename - */ - public function __construct($a_obj_id, $a_export_type = '',$a_filename = '') - { - $this->obj_id = $a_obj_id; - $this->export_type = $a_export_type; - $this->file_name = $a_filename; - if($this->getObjId() and $this->getExportType() and $this->getFilename()) - { - $this->read(); - } - } + /** + * ilExportFileInfo constructor. + * @param int $a_obj_id + * @param string $a_export_type + * @param string $a_filename + */ + public function __construct($a_obj_id, $a_export_type = '', $a_filename = '') + { + $this->obj_id = $a_obj_id; + $this->export_type = $a_export_type; + $this->file_name = $a_filename; + if ($this->getObjId() and $this->getExportType() and $this->getFilename()) { + $this->read(); + } + } - /** - * Lookup last export - * @param object $a_obj_id - * @param string type xml | html | scorm2004... - * @param string version - * @return object ilExportFileInfo - */ - public static function lookupLastExport($a_obj_id,$a_type,$a_version = '') - { - global $DIC; + /** + * Lookup last export + * @param object $a_obj_id + * @param string type xml | html | scorm2004... + * @param string version + * @return object ilExportFileInfo + */ + public static function lookupLastExport($a_obj_id, $a_type, $a_version = '') + { + global $DIC; - $ilDB = $DIC['ilDB']; - - $query = "SELECT * FROM export_file_info ". - "WHERE obj_id = ".$ilDB->quote($a_obj_id,'integer').' '. - "AND export_type = ".$ilDB->quote($a_type,'text').' '. - "ORDER BY create_date DESC"; - $res = $ilDB->query($query); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - if(!$a_version or $row->version == $a_version) - { - return new ilExportFileInfo($row->obj_id,$row->export_type,$row->filename); - } - } - return null; - } + $ilDB = $DIC['ilDB']; + + $query = "SELECT * FROM export_file_info " . + "WHERE obj_id = " . $ilDB->quote($a_obj_id, 'integer') . ' ' . + "AND export_type = " . $ilDB->quote($a_type, 'text') . ' ' . + "ORDER BY create_date DESC"; + $res = $ilDB->query($query); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + if (!$a_version or $row->version == $a_version) { + return new ilExportFileInfo($row->obj_id, $row->export_type, $row->filename); + } + } + return null; + } - - /** - * Delete all export entries by obj_id - * @param object $a_obj_id - * @return - */ - public static function deleteByObjId($a_obj_id) - { - global $DIC; + + /** + * Delete all export entries by obj_id + * @param object $a_obj_id + * @return + */ + public static function deleteByObjId($a_obj_id) + { + global $DIC; - $ilDB = $DIC['ilDB']; - - $ilDB->manipulate("DELETE FROM export_file_info WHERE obj_id = ".$ilDB->quote($a_obj_id)); - return true; - } - - - - /** - * set export type - * @param string $a_type xml | html ... - * @return - */ - public function setExportType($a_type) - { - $this->export_type = $a_type; - } - - /** - * get export type - * @return string export type - */ - public function getExportType() - { - return $this->export_type; - } - - /** - * set filename - * @param string $a_name - * @return - */ - public function setFilename($a_name) - { - $this->file_name = $a_name; - } - - /** - * get filename - * @return - */ - public function getFilename() - { - return $this->file_name; - } - - public function getBasename($a_ext = '.zip') - { - return basename($this->getFilename(),$a_ext); - } - - /** - * Set obj id - * @param object $a_id - * @return - */ - public function setObjId($a_id) - { - $this->obj_id = $a_id; - } - - /** - * Get obj id - * @return - */ - public function getObjId() - { - return $this->obj_id; - } + $ilDB = $DIC['ilDB']; + + $ilDB->manipulate("DELETE FROM export_file_info WHERE obj_id = " . $ilDB->quote($a_obj_id)); + return true; + } + + + + /** + * set export type + * @param string $a_type xml | html ... + * @return + */ + public function setExportType($a_type) + { + $this->export_type = $a_type; + } + + /** + * get export type + * @return string export type + */ + public function getExportType() + { + return $this->export_type; + } + + /** + * set filename + * @param string $a_name + * @return + */ + public function setFilename($a_name) + { + $this->file_name = $a_name; + } + + /** + * get filename + * @return + */ + public function getFilename() + { + return $this->file_name; + } + + public function getBasename($a_ext = '.zip') + { + return basename($this->getFilename(), $a_ext); + } + + /** + * Set obj id + * @param object $a_id + * @return + */ + public function setObjId($a_id) + { + $this->obj_id = $a_id; + } + + /** + * Get obj id + * @return + */ + public function getObjId() + { + return $this->obj_id; + } - /** - * set version - * @return - */ - public function setVersion($a_version) - { - $this->version = $a_version; - } - - /** - * get version - * @return - */ - public function getVersion() - { - return $this->version; - } - - /** - * get creation date - * @return ilDateTime $date - */ - public function getCreationDate() - { - return $this->create_date instanceof ilDateTime ? $this->create_date : new ilDateTime(time(),IL_CAL_UNIX); - } - - /** - * set creation date - * @param ilDateTime $dt [optional] - * @return - */ - public function setCreationDate(ilDateTime $dt = null) - { - $this->create_date = $dt; - } - - /** - * Create new export entry - */ - public function create() - { - global $DIC; + /** + * set version + * @return + */ + public function setVersion($a_version) + { + $this->version = $a_version; + } + + /** + * get version + * @return + */ + public function getVersion() + { + return $this->version; + } + + /** + * get creation date + * @return ilDateTime $date + */ + public function getCreationDate() + { + return $this->create_date instanceof ilDateTime ? $this->create_date : new ilDateTime(time(), IL_CAL_UNIX); + } + + /** + * set creation date + * @param ilDateTime $dt [optional] + * @return + */ + public function setCreationDate(ilDateTime $dt = null) + { + $this->create_date = $dt; + } + + /** + * Create new export entry + */ + public function create() + { + global $DIC; - $db = $DIC->database(); + $db = $DIC->database(); - $exists_query = 'select * from export_file_info ' . - 'where obj_id = ' . $db->quote($this->obj_id,'integer'). ' '. - 'and export_type = ' . $db->quote($this->getExportType(),'text').' '. - 'and filename = ' . $db->quote($this->getFilename(),'text'); - $exists_res = $db->query($exists_query); + $exists_query = 'select * from export_file_info ' . + 'where obj_id = ' . $db->quote($this->obj_id, 'integer') . ' ' . + 'and export_type = ' . $db->quote($this->getExportType(), 'text') . ' ' . + 'and filename = ' . $db->quote($this->getFilename(), 'text'); + $exists_res = $db->query($exists_query); - if(!$exists_res->numRows()) { - $query = "INSERT INTO export_file_info (obj_id, export_type, filename, version, create_date) ". - "VALUES ( ". - $db->quote($this->getObjId(),'integer').', '. - $db->quote($this->getExportType(),'text').', '. - $db->quote($this->getFilename(),'text').', '. - $db->quote($this->getVersion(),'text').', '. - $db->quote($this->getCreationDate()->get(IL_CAL_DATETIME,'',ilTimeZone::UTC),'timestamp').' '. - ")"; - $db->manipulate($query); - } - } + if (!$exists_res->numRows()) { + $query = "INSERT INTO export_file_info (obj_id, export_type, filename, version, create_date) " . + "VALUES ( " . + $db->quote($this->getObjId(), 'integer') . ', ' . + $db->quote($this->getExportType(), 'text') . ', ' . + $db->quote($this->getFilename(), 'text') . ', ' . + $db->quote($this->getVersion(), 'text') . ', ' . + $db->quote($this->getCreationDate()->get(IL_CAL_DATETIME, '', ilTimeZone::UTC), 'timestamp') . ' ' . + ")"; + $db->manipulate($query); + } + } - /** - * Delete one export entry - * @return - */ - public function delete() - { - global $DIC; + /** + * Delete one export entry + * @return + */ + public function delete() + { + global $DIC; - $ilDB = $DIC['ilDB']; - - $ilDB->manipulate('DELETE FROM export_file_info '. - 'WHERE obj_id = '.$ilDB->quote($this->getObjId(),'integer').' '. - 'AND filename = '.$ilDB->quote($this->getFilename(),'text') - ); - return true; - } - - /** - * Read - * @return - */ - protected function read() - { - global $DIC; + $ilDB = $DIC['ilDB']; + + $ilDB->manipulate( + 'DELETE FROM export_file_info ' . + 'WHERE obj_id = ' . $ilDB->quote($this->getObjId(), 'integer') . ' ' . + 'AND filename = ' . $ilDB->quote($this->getFilename(), 'text') + ); + return true; + } + + /** + * Read + * @return + */ + protected function read() + { + global $DIC; - $ilDB = $DIC['ilDB']; - - $query = "SELECT * FROM export_file_info ". - "WHERE obj_id = ".$ilDB->quote($this->getObjId(),'integer').' '. - "AND export_type = ".$ilDB->quote($this->getExportType(),'text').' '. - "AND filename = ".$ilDB->quote($this->getFilename(),'text'); - - $res = $ilDB->query($query); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - $this->setVersion($row->version); - $this->setCreationDate(new ilDateTime($row->create_date,IL_CAL_DATETIME,ilTimeZone::UTC)); - } - return true; - } + $ilDB = $DIC['ilDB']; + + $query = "SELECT * FROM export_file_info " . + "WHERE obj_id = " . $ilDB->quote($this->getObjId(), 'integer') . ' ' . + "AND export_type = " . $ilDB->quote($this->getExportType(), 'text') . ' ' . + "AND filename = " . $ilDB->quote($this->getFilename(), 'text'); + + $res = $ilDB->query($query); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + $this->setVersion($row->version); + $this->setCreationDate(new ilDateTime($row->create_date, IL_CAL_DATETIME, ilTimeZone::UTC)); + } + return true; + } } -?> \ No newline at end of file diff --git a/Services/Export/classes/class.ilExportFileParser.php b/Services/Export/classes/class.ilExportFileParser.php index 95cca30bc4969ed0602653db233fd90ea3397aa5..d83ad619d75f2cab32e659feee7f0d91570b2aee 100644 --- a/Services/Export/classes/class.ilExportFileParser.php +++ b/Services/Export/classes/class.ilExportFileParser.php @@ -13,120 +13,118 @@ include_once "./Services/Xml/classes/class.ilXmlWriter.php"; */ class ilExportFileParser extends ilSaxParser { - protected $item_xml = ""; - - /** - * Constructor - * - * @param - * @return - */ - function __construct($a_file, $a_callback_obj, $a_callback_func) - { - $this->callback_obj = $a_callback_obj; - $this->callback_func = $a_callback_func; + protected $item_xml = ""; + + /** + * Constructor + * + * @param + * @return + */ + public function __construct($a_file, $a_callback_obj, $a_callback_func) + { + $this->callback_obj = $a_callback_obj; + $this->callback_func = $a_callback_func; - parent::__construct($a_file, true); - $this->startParsing(); - } - - /** - * Set event handlers - * - * @param resource reference to the xml parser - * @access private - */ - function setHandlers($a_xml_parser) - { - xml_set_object($a_xml_parser,$this); - xml_set_element_handler($a_xml_parser, 'handleBeginTag', 'handleEndTag'); - xml_set_character_data_handler($a_xml_parser, 'handleCharacterData'); - } - - /** - * Start parser - */ - function startParsing() - { - parent::startParsing(); - } - - /** - * Begin Tag - */ - function handleBeginTag($a_xml_parser, $a_name, $a_attribs) - { - if ($this->in_export_item) - { - $this->export_item_writer->xmlStartTag($a_name, $a_attribs); - } + parent::__construct($a_file, true); + $this->startParsing(); + } + + /** + * Set event handlers + * + * @param resource reference to the xml parser + * @access private + */ + public function setHandlers($a_xml_parser) + { + xml_set_object($a_xml_parser, $this); + xml_set_element_handler($a_xml_parser, 'handleBeginTag', 'handleEndTag'); + xml_set_character_data_handler($a_xml_parser, 'handleCharacterData'); + } + + /** + * Start parser + */ + public function startParsing() + { + parent::startParsing(); + } + + /** + * Begin Tag + */ + public function handleBeginTag($a_xml_parser, $a_name, $a_attribs) + { + if ($this->in_export_item) { + $this->export_item_writer->xmlStartTag($a_name, $a_attribs); + } - switch ($a_name) - { - case "exp:Export": - $this->entity = $a_attribs["Entity"]; - $this->install_id = $a_attribs["InstallationId"]; - $this->install_url = $a_attribs["InstallationUrl"]; - $this->schema_version = $a_attribs["SchemaVersion"]; - break; + switch ($a_name) { + case "exp:Export": + $this->entity = $a_attribs["Entity"]; + $this->install_id = $a_attribs["InstallationId"]; + $this->install_url = $a_attribs["InstallationUrl"]; + $this->schema_version = $a_attribs["SchemaVersion"]; + break; - case "exp:ExportItem": - $this->in_export_item = true; - $this->current_id = $a_attribs["Id"]; + case "exp:ExportItem": + $this->in_export_item = true; + $this->current_id = $a_attribs["Id"]; - $this->export_item_writer = new ilXmlWriter(); + $this->export_item_writer = new ilXmlWriter(); - $this->item_xml = ""; - $this->expfiles[] = array("component" => $a_attribs["Component"], - "path" => $a_attribs["Path"]); - break; - } - } - - /** - * End Tag - */ - function handleEndTag($a_xml_parser, $a_name) - { - switch ($a_name) - { - case "exp:ExportItem": - $this->in_export_item = false; - $cf = $this->callback_func; - $this->callback_obj->$cf($this->entity, $this->schema_version, $this->current_id, - $this->export_item_writer->xmlDumpMem(false), $this->install_id, - $this->install_url); - break; + $this->item_xml = ""; + $this->expfiles[] = array("component" => $a_attribs["Component"], + "path" => $a_attribs["Path"]); + break; + } + } + + /** + * End Tag + */ + public function handleEndTag($a_xml_parser, $a_name) + { + switch ($a_name) { + case "exp:ExportItem": + $this->in_export_item = false; + $cf = $this->callback_func; + $this->callback_obj->$cf( + $this->entity, + $this->schema_version, + $this->current_id, + $this->export_item_writer->xmlDumpMem(false), + $this->install_id, + $this->install_url + ); + break; - } + } - if ($this->in_export_item) - { - $this->export_item_writer->xmlEndTag($a_name); - } + if ($this->in_export_item) { + $this->export_item_writer->xmlEndTag($a_name); + } - $this->chr_data = ""; - } - - /** - * End Tag - */ - function handleCharacterData($a_xml_parser,$a_data) - { - //$a_data = str_replace("<","<",$a_data); - //$a_data = str_replace(">",">",$a_data); - // DELETE WHITESPACES AND NEWLINES OF CHARACTER DATA - //$a_data = preg_replace("/\n/","",$a_data); - //$a_data = preg_replace("/\t+/","",$a_data); + $this->chr_data = ""; + } + + /** + * End Tag + */ + public function handleCharacterData($a_xml_parser, $a_data) + { + //$a_data = str_replace("<","<",$a_data); + //$a_data = str_replace(">",">",$a_data); + // DELETE WHITESPACES AND NEWLINES OF CHARACTER DATA + //$a_data = preg_replace("/\n/","",$a_data); + //$a_data = preg_replace("/\t+/","",$a_data); - $this->chr_data .= $a_data; + $this->chr_data .= $a_data; - if ($this->in_export_item) - { - $this->export_item_writer->xmlData($a_data); - } - } - + if ($this->in_export_item) { + $this->export_item_writer->xmlData($a_data); + } + } } -?> \ No newline at end of file diff --git a/Services/Export/classes/class.ilExportGUI.php b/Services/Export/classes/class.ilExportGUI.php index 5520ed4864eedf6d4598d98a8fd7abb8c30ddf18..da14832b46942ddfa096ff6672b2bf3782fd94ca 100644 --- a/Services/Export/classes/class.ilExportGUI.php +++ b/Services/Export/classes/class.ilExportGUI.php @@ -13,527 +13,483 @@ */ class ilExportGUI { - protected $formats = array(); - protected $custom_columns = array(); - protected $custom_multi_commands = array(); - - private $parent_gui = null; - - /** - * Constuctor - * - * @param - * @return - */ - function __construct($a_parent_gui, $a_main_obj = null) - { - global $DIC; + protected $formats = array(); + protected $custom_columns = array(); + protected $custom_multi_commands = array(); + + private $parent_gui = null; + + /** + * Constuctor + * + * @param + * @return + */ + public function __construct($a_parent_gui, $a_main_obj = null) + { + global $DIC; - $lng = $DIC['lng']; - $tpl = $DIC['tpl']; - - $this->parent_gui = $a_parent_gui; - if ($a_main_obj == null) - { - $this->obj = $a_parent_gui->object; - } - else - { - $this->obj = $a_main_obj; - } - $lng->loadLanguageModule("exp"); - $this->tpl = $tpl; - } + $lng = $DIC['lng']; + $tpl = $DIC['tpl']; + + $this->parent_gui = $a_parent_gui; + if ($a_main_obj == null) { + $this->obj = $a_parent_gui->object; + } else { + $this->obj = $a_main_obj; + } + $lng->loadLanguageModule("exp"); + $this->tpl = $tpl; + } - /** - * @return ilExportTableGUI - */ - protected function buildExportTableGUI() - { - include_once("./Services/Export/classes/class.ilExportTableGUI.php"); - $table = new ilExportTableGUI($this, "listExportFiles", $this->obj); - return $table; - } + /** + * @return ilExportTableGUI + */ + protected function buildExportTableGUI() + { + include_once("./Services/Export/classes/class.ilExportTableGUI.php"); + $table = new ilExportTableGUI($this, "listExportFiles", $this->obj); + return $table; + } - /** - * get parent gui - * @return - */ - protected function getParentGUI() - { - return $this->parent_gui; - } - - /** - * Add formats - * - * @param array formats - */ - function addFormat($a_key, $a_txt = "", $a_call_obj = null, $a_call_func = "") - { - global $DIC; + /** + * get parent gui + * @return + */ + protected function getParentGUI() + { + return $this->parent_gui; + } + + /** + * Add formats + * + * @param array formats + */ + public function addFormat($a_key, $a_txt = "", $a_call_obj = null, $a_call_func = "") + { + global $DIC; - $lng = $DIC['lng']; - - if ($a_txt == "") - { - $a_txt = $lng->txt("exp_".$a_key); - } - $this->formats[] = array("key" => $a_key, "txt" => $a_txt, - "call_obj" => $a_call_obj, "call_func" => $a_call_func); - } - - /** - * Get formats - * - * @return array formats - */ - function getFormats() - { - return $this->formats; - } - - /** - * Add custom column - * - * @param - * @return - */ - function addCustomColumn($a_txt, $a_obj, $a_func) - { - $this->custom_columns[] = array("txt" => $a_txt, - "obj" => $a_obj, - "func" => $a_func); - } - - /** - * Add custom multi command - * - * @param - * @return - */ - function addCustomMultiCommand($a_txt, $a_obj, $a_func) - { - $this->custom_multi_commands[] = array("txt" => $a_txt, - "obj" => $a_obj, - "func" => $a_func); - } - - /** - * Get custom multi commands - */ - function getCustomMultiCommands() - { - return $this->custom_multi_commands; - } + $lng = $DIC['lng']; + + if ($a_txt == "") { + $a_txt = $lng->txt("exp_" . $a_key); + } + $this->formats[] = array("key" => $a_key, "txt" => $a_txt, + "call_obj" => $a_call_obj, "call_func" => $a_call_func); + } + + /** + * Get formats + * + * @return array formats + */ + public function getFormats() + { + return $this->formats; + } + + /** + * Add custom column + * + * @param + * @return + */ + public function addCustomColumn($a_txt, $a_obj, $a_func) + { + $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_obj, $a_func) + { + $this->custom_multi_commands[] = array("txt" => $a_txt, + "obj" => $a_obj, + "func" => $a_func); + } + + /** + * Get custom multi commands + */ + public function getCustomMultiCommands() + { + return $this->custom_multi_commands; + } - /** - * Get custom columns - * - * @param - * @return - */ - function getCustomColumns() - { - return $this->custom_columns; - } + /** + * Get custom columns + * + * @param + * @return + */ + public function getCustomColumns() + { + return $this->custom_columns; + } - /** - * Execute command - * - * @param - * @return - */ - function executeCommand() - { - global $DIC; + /** + * Execute command + * + * @param + * @return + */ + public function executeCommand() + { + global $DIC; - $ilCtrl = $DIC['ilCtrl']; - $ilAccess = $DIC['ilAccess']; - $ilErr = $DIC['ilErr']; - $lng = $DIC['lng']; - - // this should work (at least) for repository objects - if(method_exists($this->obj, 'getRefId') and $this->obj->getRefId()) - { - if(!$ilAccess->checkAccess('write','',$this->obj->getRefId())) - { - $ilErr->raiseError($lng->txt('permission_denied'),$ilErr->WARNING); - } - } - - $cmd = $ilCtrl->getCmd("listExportFiles"); - - switch ($cmd) - { - case "listExportFiles": - $this->$cmd(); - break; - - default: - if (substr($cmd, 0, 7) == "create_") - { - $this->createExportFile(); - } - else if (substr($cmd, 0, 6) == "multi_") // custom multi command - { - $this->handleCustomMultiCommand(); - } - else - { - $this->$cmd(); - } - break; - } - } - - /** - * List export files - * - * @param - * @return - */ - function listExportFiles() - { - global $DIC; + $ilCtrl = $DIC['ilCtrl']; + $ilAccess = $DIC['ilAccess']; + $ilErr = $DIC['ilErr']; + $lng = $DIC['lng']; + + // this should work (at least) for repository objects + if (method_exists($this->obj, 'getRefId') and $this->obj->getRefId()) { + if (!$ilAccess->checkAccess('write', '', $this->obj->getRefId())) { + $ilErr->raiseError($lng->txt('permission_denied'), $ilErr->WARNING); + } + } + + $cmd = $ilCtrl->getCmd("listExportFiles"); + + switch ($cmd) { + case "listExportFiles": + $this->$cmd(); + break; + + default: + if (substr($cmd, 0, 7) == "create_") { + $this->createExportFile(); + } elseif (substr($cmd, 0, 6) == "multi_") { // custom multi command + $this->handleCustomMultiCommand(); + } else { + $this->$cmd(); + } + break; + } + } + + /** + * List export files + * + * @param + * @return + */ + public function listExportFiles() + { + global $DIC; - $tpl = $DIC['tpl']; - $ilToolbar = $DIC['ilToolbar']; - $ilCtrl = $DIC['ilCtrl']; - $lng = $DIC['lng']; + $tpl = $DIC['tpl']; + $ilToolbar = $DIC['ilToolbar']; + $ilCtrl = $DIC['ilCtrl']; + $lng = $DIC['lng']; - include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; - $button = ilSubmitButton::getInstance(); - - // creation buttons - $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); - if (count($this->getFormats()) > 1) - { - // type selection - foreach ($this->getFormats() as $f) - { - $options[$f["key"]] = $f["txt"]; - } - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $si = new ilSelectInputGUI($lng->txt("type"), "format"); - $si->setOptions($options); - $ilToolbar->addInputItem($si, true); - - $button->setCaption("exp_create_file"); - $button->setCommand("createExportFile"); - } - else - { - $format = $this->getFormats(); - $format = $format[0]; - - $button->setCaption($lng->txt("exp_create_file")." (".$format["txt"].")", false); - $button->setCommand("create_".$format["key"]); - } - - $ilToolbar->addButtonInstance($button); + include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; + $button = ilSubmitButton::getInstance(); + + // creation buttons + $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); + if (count($this->getFormats()) > 1) { + // type selection + foreach ($this->getFormats() as $f) { + $options[$f["key"]] = $f["txt"]; + } + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $si = new ilSelectInputGUI($lng->txt("type"), "format"); + $si->setOptions($options); + $ilToolbar->addInputItem($si, true); + + $button->setCaption("exp_create_file"); + $button->setCommand("createExportFile"); + } else { + $format = $this->getFormats(); + $format = $format[0]; + + $button->setCaption($lng->txt("exp_create_file") . " (" . $format["txt"] . ")", false); + $button->setCommand("create_" . $format["key"]); + } + + $ilToolbar->addButtonInstance($button); - $table = $this->buildExportTableGUI(); - $table->setSelectAllCheckbox("file"); - foreach ($this->getCustomColumns() as $c) - { - $table->addCustomColumn($c["txt"], $c["obj"], $c["func"]); - } - foreach ($this->getCustomMultiCommands() as $c) - { - $table->addCustomMultiCommand($c["txt"], "multi_".$c["func"]); - } - $tpl->setContent($table->getHTML()); - } - - /** - * Create export file - * - * @param - * @return - */ - function createExportFile() - { - global $DIC; + $table = $this->buildExportTableGUI(); + $table->setSelectAllCheckbox("file"); + foreach ($this->getCustomColumns() as $c) { + $table->addCustomColumn($c["txt"], $c["obj"], $c["func"]); + } + foreach ($this->getCustomMultiCommands() as $c) { + $table->addCustomMultiCommand($c["txt"], "multi_" . $c["func"]); + } + $tpl->setContent($table->getHTML()); + } + + /** + * Create export file + * + * @param + * @return + */ + public function createExportFile() + { + global $DIC; - $ilCtrl = $DIC['ilCtrl']; - $lng = $DIC['lng']; - - if ($ilCtrl->getCmd() == "createExportFile") - { - $format = ilUtil::stripSlashes($_POST["format"]); - } - else - { - $format = substr($ilCtrl->getCmd(), 7); - } - foreach ($this->getFormats() as $f) - { - if ($f["key"] == $format) - { - if (is_object($f["call_obj"])) - { - $f["call_obj"]->{$f["call_func"]}(); - } - elseif($this->getParentGUI() instanceof ilContainerGUI) - { - return $this->showItemSelection(); - } - else if ($format == "xml") // standard procedure - { - include_once("./Services/Export/classes/class.ilExport.php"); - $exp = new ilExport(); - $exp->exportObject($this->obj->getType(),$this->obj->getId()); - } - } - } - - ilUtil::sendSuccess($lng->txt("exp_file_created"), true); - $ilCtrl->redirect($this, "listExportFiles"); - } - - /** - * Confirm file deletion - */ - function confirmDeletion() - { - global $DIC; + $ilCtrl = $DIC['ilCtrl']; + $lng = $DIC['lng']; + + if ($ilCtrl->getCmd() == "createExportFile") { + $format = ilUtil::stripSlashes($_POST["format"]); + } else { + $format = substr($ilCtrl->getCmd(), 7); + } + foreach ($this->getFormats() as $f) { + if ($f["key"] == $format) { + if (is_object($f["call_obj"])) { + $f["call_obj"]->{$f["call_func"]}(); + } elseif ($this->getParentGUI() instanceof ilContainerGUI) { + return $this->showItemSelection(); + } elseif ($format == "xml") { // standard procedure + include_once("./Services/Export/classes/class.ilExport.php"); + $exp = new ilExport(); + $exp->exportObject($this->obj->getType(), $this->obj->getId()); + } + } + } + + ilUtil::sendSuccess($lng->txt("exp_file_created"), true); + $ilCtrl->redirect($this, "listExportFiles"); + } + + /** + * Confirm file deletion + */ + public function confirmDeletion() + { + global $DIC; - $ilCtrl = $DIC['ilCtrl']; - $tpl = $DIC['tpl']; - $lng = $DIC['lng']; - - if (!is_array($_POST["file"]) || count($_POST["file"]) == 0) - { - ilUtil::sendInfo($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "listExportFiles"); - } - else - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("exp_really_delete")); - $cgui->setCancel($lng->txt("cancel"), "listExportFiles"); - $cgui->setConfirm($lng->txt("delete"), "delete"); - - foreach ($_POST["file"] as $i) - { - if(strpos($i, ':') !== false) - { - $iarr = explode(":", $i); - $filename = $iarr[1]; - } - else - { - $filename = $i; - } - $cgui->addItem("file[]", $i, $filename); - } - - $tpl->setContent($cgui->getHTML()); - } - } - - /** - * Delete files - */ - function delete() - { - global $DIC; + $ilCtrl = $DIC['ilCtrl']; + $tpl = $DIC['tpl']; + $lng = $DIC['lng']; + + if (!is_array($_POST["file"]) || count($_POST["file"]) == 0) { + ilUtil::sendInfo($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "listExportFiles"); + } else { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("exp_really_delete")); + $cgui->setCancel($lng->txt("cancel"), "listExportFiles"); + $cgui->setConfirm($lng->txt("delete"), "delete"); + + foreach ($_POST["file"] as $i) { + if (strpos($i, ':') !== false) { + $iarr = explode(":", $i); + $filename = $iarr[1]; + } else { + $filename = $i; + } + $cgui->addItem("file[]", $i, $filename); + } + + $tpl->setContent($cgui->getHTML()); + } + } + + /** + * Delete files + */ + public function delete() + { + global $DIC; - $ilCtrl = $DIC['ilCtrl']; - - foreach($_POST["file"] as $file) - { - $file = explode(":", $file); - - $file[1] = basename($file[1]); - - include_once("./Services/Export/classes/class.ilExport.php"); - $export_dir = ilExport::_getExportDirectory($this->obj->getId(), - str_replace("..", "", $file[0]), $this->obj->getType()); + $ilCtrl = $DIC['ilCtrl']; + + foreach ($_POST["file"] as $file) { + $file = explode(":", $file); + + $file[1] = basename($file[1]); + + include_once("./Services/Export/classes/class.ilExport.php"); + $export_dir = ilExport::_getExportDirectory( + $this->obj->getId(), + str_replace("..", "", $file[0]), + $this->obj->getType() + ); - $exp_file = $export_dir."/".str_replace("..", "", $file[1]); - $exp_dir = $export_dir."/".substr($file[1], 0, strlen($file[1]) - 4); - if (@is_file($exp_file)) - { - unlink($exp_file); - } - if (@is_dir($exp_dir)) - { - ilUtil::delDir($exp_dir); - } - - // delete entry in database - include_once './Services/Export/classes/class.ilExportFileInfo.php'; - $info = new ilExportFileInfo($this->obj->getId(),$file[0],$file[1]); - $info->delete(); - } - $ilCtrl->redirect($this, "listExportFiles"); - } - - /** - * Download file - */ - public function download() - { - global $DIC; + $exp_file = $export_dir . "/" . str_replace("..", "", $file[1]); + $exp_dir = $export_dir . "/" . substr($file[1], 0, strlen($file[1]) - 4); + if (@is_file($exp_file)) { + unlink($exp_file); + } + if (@is_dir($exp_dir)) { + ilUtil::delDir($exp_dir); + } + + // delete entry in database + include_once './Services/Export/classes/class.ilExportFileInfo.php'; + $info = new ilExportFileInfo($this->obj->getId(), $file[0], $file[1]); + $info->delete(); + } + $ilCtrl->redirect($this, "listExportFiles"); + } + + /** + * Download file + */ + public function download() + { + global $DIC; - $ilCtrl = $DIC['ilCtrl']; - $lng = $DIC['lng']; - - if(!isset($_GET["file"]) || - is_array($_GET["file"])) - { - $ilCtrl->redirect($this, "listExportFiles"); - } + $ilCtrl = $DIC['ilCtrl']; + $lng = $DIC['lng']; + + if (!isset($_GET["file"]) || + is_array($_GET["file"])) { + $ilCtrl->redirect($this, "listExportFiles"); + } - $file = explode(":", trim($_GET["file"])); - include_once("./Services/Export/classes/class.ilExport.php"); - $export_dir = ilExport::_getExportDirectory($this->obj->getId(), - str_replace("..", "", $file[0]), $this->obj->getType()); - - $file[1] = basename($file[1]); - - ilUtil::deliverFile($export_dir."/".$file[1], - $file[1]); - } - - /** - * Handle custom multi command - * - * @param - * @return - */ - function handleCustomMultiCommand() - { - global $DIC; + $file = explode(":", trim($_GET["file"])); + include_once("./Services/Export/classes/class.ilExport.php"); + $export_dir = ilExport::_getExportDirectory( + $this->obj->getId(), + str_replace("..", "", $file[0]), + $this->obj->getType() + ); + + $file[1] = basename($file[1]); + + ilUtil::deliverFile( + $export_dir . "/" . $file[1], + $file[1] + ); + } + + /** + * Handle custom multi command + * + * @param + * @return + */ + public function handleCustomMultiCommand() + { + global $DIC; - $ilCtrl = $DIC['ilCtrl']; + $ilCtrl = $DIC['ilCtrl']; - $cmd = substr($ilCtrl->getCmd(), 6); - foreach ($this->getCustomMultiCommands() as $c) - { - if ($c["func"] == $cmd) - { - $c["obj"]->{$c["func"]}($_POST["file"]); - } - } - } - - /** - * Show container item selection table - * @return - */ - protected function showItemSelection() - { - global $DIC; + $cmd = substr($ilCtrl->getCmd(), 6); + foreach ($this->getCustomMultiCommands() as $c) { + if ($c["func"] == $cmd) { + $c["obj"]->{$c["func"]}($_POST["file"]); + } + } + } + + /** + * Show container item selection table + * @return + */ + protected function showItemSelection() + { + global $DIC; - $tpl = $DIC['tpl']; - - $tpl->addJavaScript('./Services/CopyWizard/js/ilContainer.js'); - $tpl->setVariable('BODY_ATTRIBUTES','onload="ilDisableChilds(\'cmd\');"'); + $tpl = $DIC['tpl']; + + $tpl->addJavaScript('./Services/CopyWizard/js/ilContainer.js'); + $tpl->setVariable('BODY_ATTRIBUTES', 'onload="ilDisableChilds(\'cmd\');"'); - include_once './Services/Export/classes/class.ilExportSelectionTableGUI.php'; - $table = new ilExportSelectionTableGUI($this,'listExportFiles'); - $table->parseContainer($this->getParentGUI()->object->getRefId()); - $this->tpl->setContent($table->getHTML()); - } + include_once './Services/Export/classes/class.ilExportSelectionTableGUI.php'; + $table = new ilExportSelectionTableGUI($this, 'listExportFiles'); + $table->parseContainer($this->getParentGUI()->object->getRefId()); + $this->tpl->setContent($table->getHTML()); + } - /** - * Save selection of subitems - * @return - */ - protected function saveItemSelection() - { - global $DIC; + /** + * Save selection of subitems + * @return + */ + protected function saveItemSelection() + { + global $DIC; - $tree = $DIC['tree']; - $objDefinition = $DIC['objDefinition']; - $ilAccess = $DIC['ilAccess']; - $ilCtrl = $DIC['ilCtrl']; - $lng = $DIC['lng']; + $tree = $DIC['tree']; + $objDefinition = $DIC['objDefinition']; + $ilAccess = $DIC['ilAccess']; + $ilCtrl = $DIC['ilCtrl']; + $lng = $DIC['lng']; - include_once './Services/Export/classes/class.ilExportOptions.php'; - $eo = ilExportOptions::newInstance(ilExportOptions::allocateExportId()); - $eo->addOption(ilExportOptions::KEY_ROOT,0,0,$this->obj->getId()); - - $items_selected = false; - foreach($tree->getSubTree($root = $tree->getNodeData($this->getParentGUI()->object->getRefId())) as $node) - { - if($node['type'] == 'rolf') - { - continue; - } - if($node['ref_id'] == $this->getParentGUI()->object->getRefId()) - { - $eo->addOption( - ilExportOptions::KEY_ITEM_MODE, - $node['ref_id'], - $node['obj_id'], - ilExportOptions::EXPORT_BUILD - ); - continue; - } - // no export available or no access - if(!$objDefinition->allowExport($node['type']) or !$ilAccess->checkAccess('write','',$node['ref_id'])) - { - - $eo->addOption( - ilExportOptions::KEY_ITEM_MODE, - $node['ref_id'], - $node['obj_id'], - ilExportOptions::EXPORT_OMIT - ); - continue; - } - - $mode = isset($_POST['cp_options'][$node['ref_id']]['type']) ? - $_POST['cp_options'][$node['ref_id']]['type'] : - ilExportOptions::EXPORT_OMIT; - $eo->addOption( - ilExportOptions::KEY_ITEM_MODE, - $node['ref_id'], - $node['obj_id'], - $mode - ); - if($mode != ilExportOptions::EXPORT_OMIT) - { - $items_selected = true; - } - } - - include_once("./Services/Export/classes/class.ilExport.php"); - if($items_selected) - { - // TODO: move this to background soap - $eo->read(); - $exp = new ilExport(); - foreach($eo->getSubitemsForCreation($this->obj->getRefId()) as $ref_id) - { - $obj_id = ilObject::_lookupObjId($ref_id); - $type = ilObject::_lookupType($obj_id); - $exp->exportObject($type,$obj_id); - } - // Fixme: there is a naming conflict between the container settings xml and the container subitem xml. - sleep(1); - // Export container - include_once './Services/Export/classes/class.ilExportContainer.php'; - $cexp = new ilExportContainer($eo); - $cexp->exportObject($this->obj->getType(),$this->obj->getId()); - } - else - { - $exp = new ilExport(); - $exp->exportObject($this->obj->getType(),$this->obj->getId()); - } + include_once './Services/Export/classes/class.ilExportOptions.php'; + $eo = ilExportOptions::newInstance(ilExportOptions::allocateExportId()); + $eo->addOption(ilExportOptions::KEY_ROOT, 0, 0, $this->obj->getId()); + + $items_selected = false; + foreach ($tree->getSubTree($root = $tree->getNodeData($this->getParentGUI()->object->getRefId())) as $node) { + if ($node['type'] == 'rolf') { + continue; + } + if ($node['ref_id'] == $this->getParentGUI()->object->getRefId()) { + $eo->addOption( + ilExportOptions::KEY_ITEM_MODE, + $node['ref_id'], + $node['obj_id'], + ilExportOptions::EXPORT_BUILD + ); + continue; + } + // no export available or no access + if (!$objDefinition->allowExport($node['type']) or !$ilAccess->checkAccess('write', '', $node['ref_id'])) { + $eo->addOption( + ilExportOptions::KEY_ITEM_MODE, + $node['ref_id'], + $node['obj_id'], + ilExportOptions::EXPORT_OMIT + ); + continue; + } + + $mode = isset($_POST['cp_options'][$node['ref_id']]['type']) ? + $_POST['cp_options'][$node['ref_id']]['type'] : + ilExportOptions::EXPORT_OMIT; + $eo->addOption( + ilExportOptions::KEY_ITEM_MODE, + $node['ref_id'], + $node['obj_id'], + $mode + ); + if ($mode != ilExportOptions::EXPORT_OMIT) { + $items_selected = true; + } + } + + include_once("./Services/Export/classes/class.ilExport.php"); + if ($items_selected) { + // TODO: move this to background soap + $eo->read(); + $exp = new ilExport(); + foreach ($eo->getSubitemsForCreation($this->obj->getRefId()) as $ref_id) { + $obj_id = ilObject::_lookupObjId($ref_id); + $type = ilObject::_lookupType($obj_id); + $exp->exportObject($type, $obj_id); + } + // Fixme: there is a naming conflict between the container settings xml and the container subitem xml. + sleep(1); + // Export container + include_once './Services/Export/classes/class.ilExportContainer.php'; + $cexp = new ilExportContainer($eo); + $cexp->exportObject($this->obj->getType(), $this->obj->getId()); + } else { + $exp = new ilExport(); + $exp->exportObject($this->obj->getType(), $this->obj->getId()); + } - // Delete export options - $eo->delete(); + // Delete export options + $eo->delete(); - ilUtil::sendSuccess($lng->txt('export_created'),true); - $ilCtrl->redirect($this, "listExportFiles"); - } + ilUtil::sendSuccess($lng->txt('export_created'), true); + $ilCtrl->redirect($this, "listExportFiles"); + } } -?> \ No newline at end of file diff --git a/Services/Export/classes/class.ilExportOptions.php b/Services/Export/classes/class.ilExportOptions.php index 58feeb9bb9f3721675ba2dc8f5a43cdc51087f13..8604393d3698b67c06823c0314f0ed4e5c2dd921 100644 --- a/Services/Export/classes/class.ilExportOptions.php +++ b/Services/Export/classes/class.ilExportOptions.php @@ -12,241 +12,228 @@ */ class ilExportOptions { - private static $instance = null; - - const EXPORT_EXISTING = 1; - const EXPORT_BUILD = 2; - const EXPORT_OMIT = 3; - - const KEY_INIT = 1; - const KEY_ITEM_MODE = 2; - const KEY_ROOT = 3; - - private $export_id = 0; - private $ref_options = array(); - private $obj_options = array(); - private $options = array(); - - /** - * Singleton constructor - * @return - */ - private function __construct($a_export_id) - { - $this->export_id = $a_export_id; - $this->read(); - } - - /** - * Get singelton instance - * @return object ilExportOptions - */ - public static function getInstance() - { - if(self::$instance) - { - return self::$instance; - } - } - - /** - * Create new instance - * @param object $a_export_id - * @return object ilExportOptions - */ - public static function newInstance($a_export_id) - { - return self::$instance = new ilExportOptions($a_export_id); - } - - /** - * Allocate a new export id - * @return - */ - public static function allocateExportId() - { - global $DIC; + private static $instance = null; + + const EXPORT_EXISTING = 1; + const EXPORT_BUILD = 2; + const EXPORT_OMIT = 3; + + const KEY_INIT = 1; + const KEY_ITEM_MODE = 2; + const KEY_ROOT = 3; + + private $export_id = 0; + private $ref_options = array(); + private $obj_options = array(); + private $options = array(); + + /** + * Singleton constructor + * @return + */ + private function __construct($a_export_id) + { + $this->export_id = $a_export_id; + $this->read(); + } + + /** + * Get singelton instance + * @return object ilExportOptions + */ + public static function getInstance() + { + if (self::$instance) { + return self::$instance; + } + } + + /** + * Create new instance + * @param object $a_export_id + * @return object ilExportOptions + */ + public static function newInstance($a_export_id) + { + return self::$instance = new ilExportOptions($a_export_id); + } + + /** + * Allocate a new export id + * @return + */ + public static function allocateExportId() + { + global $DIC; - $ilDB = $DIC['ilDB']; - - // get last export id - $query = 'SELECT MAX(export_id) exp FROM export_options '. - 'GROUP BY export_id '; - $res = $ilDB->query($query); - $exp_id = 1; - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - $exp_id = $row->exp + 1; - } - $query = 'INSERT INTO export_options (export_id,keyword,ref_id,obj_id,value) '. - 'VALUES( '. - $ilDB->quote($exp_id,'integer').', '. - $ilDB->quote(self::KEY_INIT,'integer').', '. - $ilDB->quote(0,'integer').', '. - $ilDB->quote(0,'integer').', '. - $ilDB->quote(0,'integer').' '. - ')'; - $ilDB->manipulate($query); + $ilDB = $DIC['ilDB']; + + // get last export id + $query = 'SELECT MAX(export_id) exp FROM export_options ' . + 'GROUP BY export_id '; + $res = $ilDB->query($query); + $exp_id = 1; + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + $exp_id = $row->exp + 1; + } + $query = 'INSERT INTO export_options (export_id,keyword,ref_id,obj_id,value) ' . + 'VALUES( ' . + $ilDB->quote($exp_id, 'integer') . ', ' . + $ilDB->quote(self::KEY_INIT, 'integer') . ', ' . + $ilDB->quote(0, 'integer') . ', ' . + $ilDB->quote(0, 'integer') . ', ' . + $ilDB->quote(0, 'integer') . ' ' . + ')'; + $ilDB->manipulate($query); - 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(); + 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 * $Id$ */ class ilImportExportFactory { - const PLUGINS_DIR = "Plugins"; + const PLUGINS_DIR = "Plugins"; - public static function getExporterClass($a_type) - { - /** - * @var $objDefinition ilObjectDefinition - */ - global $DIC; + public static function getExporterClass($a_type) + { + /** + * @var $objDefinition ilObjectDefinition + */ + global $DIC; - $objDefinition = $DIC['objDefinition']; + $objDefinition = $DIC['objDefinition']; - if($objDefinition->isPlugin($a_type)) - { - $classname = 'il'.$objDefinition->getClassName($a_type).'Exporter'; - $location = $objDefinition->getLocation($a_type); - if(include_once $location.'/class.'.$classname.'.php') - { - return $classname; - } - } - else - { - - $comp = $objDefinition->getComponentForType($a_type); - $class = array_pop(explode("/", $comp)); - $class = "il".$class."Exporter"; + if ($objDefinition->isPlugin($a_type)) { + $classname = 'il' . $objDefinition->getClassName($a_type) . 'Exporter'; + $location = $objDefinition->getLocation($a_type); + if (include_once $location . '/class.' . $classname . '.php') { + return $classname; + } + } else { + $comp = $objDefinition->getComponentForType($a_type); + $class = array_pop(explode("/", $comp)); + $class = "il" . $class . "Exporter"; - // page component plugin exporter classes are already included - // the component is not registered by ilObjDefinition - if (class_exists($class)) - { - return $class; - } - - // the next line had a "@" in front of the include_once - // I removed this because it tages ages to track down errors - // if the include class contains parse errors. - // Alex, 20 Jul 2012 - if(include_once "./".$comp."/classes/class.".$class.".php") - { - return $class; - } - } - - throw new InvalidArgumentException('Invalid exporter type given'); - } - - public static function getComponentForExport($a_type) - { - /** - * @var $objDefinition ilObjectDefinition - */ - global $DIC; + // page component plugin exporter classes are already included + // the component is not registered by ilObjDefinition + if (class_exists($class)) { + return $class; + } + + // the next line had a "@" in front of the include_once + // I removed this because it tages ages to track down errors + // if the include class contains parse errors. + // Alex, 20 Jul 2012 + if (include_once "./" . $comp . "/classes/class." . $class . ".php") { + return $class; + } + } + + throw new InvalidArgumentException('Invalid exporter type given'); + } + + public static function getComponentForExport($a_type) + { + /** + * @var $objDefinition ilObjectDefinition + */ + global $DIC; - $objDefinition = $DIC['objDefinition']; + $objDefinition = $DIC['objDefinition']; - if($objDefinition->isPlugin($a_type)) - { - return self::PLUGINS_DIR."/".$a_type; - } - else - { - return $objDefinition->getComponentForType($a_type); - } - } + if ($objDefinition->isPlugin($a_type)) { + return self::PLUGINS_DIR . "/" . $a_type; + } else { + return $objDefinition->getComponentForType($a_type); + } + } - /** - * Get the importer class of a component - * - * @param string $a_component component - * @return string class name of the importer class (or empty if the importer should be ignored) - * @throws InvalidArgumentException the importer class is not found but should not be ignored - */ - public static function getImporterClass($a_component) - { - /** - * @var $objDefinition ilObjectDefinition - */ - global $DIC; + /** + * Get the importer class of a component + * + * @param string $a_component component + * @return string class name of the importer class (or empty if the importer should be ignored) + * @throws InvalidArgumentException the importer class is not found but should not be ignored + */ + public static function getImporterClass($a_component) + { + /** + * @var $objDefinition ilObjectDefinition + */ + global $DIC; - $objDefinition = $DIC['objDefinition']; - - $parts = explode('/', $a_component); - $component_type = $parts[0]; - $component = $parts[1]; - - if($component_type == self::PLUGINS_DIR && - $objDefinition->isPlugin($component)) - { - $classname = 'il'.$objDefinition->getClassName($component).'Importer'; - $location = $objDefinition->getLocation($component); - if(include_once $location.'/class.'.$classname.'.php') - { - return $classname; - } - } - else - { - $class = "il".$component."Importer"; + $objDefinition = $DIC['objDefinition']; + + $parts = explode('/', $a_component); + $component_type = $parts[0]; + $component = $parts[1]; + + if ($component_type == self::PLUGINS_DIR && + $objDefinition->isPlugin($component)) { + $classname = 'il' . $objDefinition->getClassName($component) . 'Importer'; + $location = $objDefinition->getLocation($component); + if (include_once $location . '/class.' . $classname . '.php') { + return $classname; + } + } else { + $class = "il" . $component . "Importer"; - // treat special case of page component plugins - // they are imported with component type PLUGINS_DIR - // but are not yet recognized by ilObjDefinition::isPlugin() - // - // if they are active, then their importer class is already included by ilCOPageImporter::init() - if (class_exists($class)) - { - return $class; - } - // the page component plugin is not installed or not active - // return an empty class name instead of throwing an exception - // in this case the import should be continued without treating the page component - elseif ($component_type == self::PLUGINS_DIR) - { - return ""; - } + // treat special case of page component plugins + // they are imported with component type PLUGINS_DIR + // but are not yet recognized by ilObjDefinition::isPlugin() + // + // if they are active, then their importer class is already included by ilCOPageImporter::init() + if (class_exists($class)) { + return $class; + } + // the page component plugin is not installed or not active + // return an empty class name instead of throwing an exception + // in this case the import should be continued without treating the page component + elseif ($component_type == self::PLUGINS_DIR) { + return ""; + } - if (is_file ("./".$a_component."/classes/class.".$class.".php")) - { - if (include_once "./" . $a_component . "/classes/class." . $class . ".php") - { - return $class; - } - } - } - - throw new InvalidArgumentException('Invalid importer type given: '."./" . $a_component . "/classes/class." . $class . ".php"); - } + if (is_file("./" . $a_component . "/classes/class." . $class . ".php")) { + if (include_once "./" . $a_component . "/classes/class." . $class . ".php") { + return $class; + } + } + } + + throw new InvalidArgumentException('Invalid importer type given: ' . "./" . $a_component . "/classes/class." . $class . ".php"); + } } -?> diff --git a/Services/Export/classes/class.ilImportMapping.php b/Services/Export/classes/class.ilImportMapping.php index d8355855914fadc18fa50fed8c45e75f2460d86f..11af1b63ac11a29d04e663131021c730f005ad75 100644 --- a/Services/Export/classes/class.ilImportMapping.php +++ b/Services/Export/classes/class.ilImportMapping.php @@ -10,150 +10,145 @@ */ class ilImportMapping { - var $mappings; - var $install_id; - var $install_url; - var $log; - - protected $target_id = 0; + public $mappings; + public $install_id; + public $install_url; + public $log; + + protected $target_id = 0; - /** - * Constructor - * - * @param - * @return - */ - function __construct() - { - $this->mappings = array(); - $this->log = ilLoggerFactory::getLogger("exp"); - $this->log->debug("ilImportMapping Construct this->mappings = array()"); - } + /** + * Constructor + * + * @param + * @return + */ + public function __construct() + { + $this->mappings = array(); + $this->log = ilLoggerFactory::getLogger("exp"); + $this->log->debug("ilImportMapping Construct this->mappings = array()"); + } - /** - * Set Installation ID - * - * @param string Installation ID - */ - final function setInstallId($a_val) - { - $this->install_id = $a_val; - } + /** + * Set Installation ID + * + * @param string Installation ID + */ + final public function setInstallId($a_val) + { + $this->install_id = $a_val; + } - /** - * Get Installation ID - * - * @return string Installation ID - */ - final function getInstallId() - { - return $this->install_id; - } + /** + * Get Installation ID + * + * @return string Installation ID + */ + final public function getInstallId() + { + return $this->install_id; + } - /** - * Set Installation Url - * - * @param string Installation Url - */ - final function setInstallUrl($a_val) - { - $this->install_url = $a_val; - } + /** + * Set Installation Url + * + * @param string Installation Url + */ + final public function setInstallUrl($a_val) + { + $this->install_url = $a_val; + } - /** - * Get Installation Url - * - * @return string Installation Url - */ - final function getInstallUrl() - { - return $this->install_url; - } - - /** - * set target id - * @param object $a_target_id - * @return - */ - public final function setTargetId($a_target_id) - { - $this->target_id = $a_target_id; - $this->log->debug("a_target_id=".$a_target_id); - } - - /** - * get target id - * @return - */ - public final function getTargetId() - { - return $this->target_id; - } + /** + * Get Installation Url + * + * @return string Installation Url + */ + final public function getInstallUrl() + { + return $this->install_url; + } + + /** + * set target id + * @param object $a_target_id + * @return + */ + final public function setTargetId($a_target_id) + { + $this->target_id = $a_target_id; + $this->log->debug("a_target_id=" . $a_target_id); + } + + /** + * get target id + * @return + */ + final public function getTargetId() + { + return $this->target_id; + } - /** - * Add mapping - * - * @param string component - * @param string entity - * @param string old id - * @param string new id - */ - function addMapping($a_comp, $a_entity, $a_old_id, $a_new_id) - { - $this->mappings[$a_comp][$a_entity][$a_old_id] = $a_new_id; - $this->log->debug("ADD MAPPING this->mappings = ", $this->mappings); - } + /** + * Add mapping + * + * @param string component + * @param string entity + * @param string old id + * @param string new id + */ + public function addMapping($a_comp, $a_entity, $a_old_id, $a_new_id) + { + $this->mappings[$a_comp][$a_entity][$a_old_id] = $a_new_id; + $this->log->debug("ADD MAPPING this->mappings = ", $this->mappings); + } - /** - * Get a mapping - * - * @param string component - * @param string entity - * @param string old id - * - * @return string new id, or false if no mapping given - */ - function getMapping($a_comp, $a_entity, $a_old_id) - { - $this->log->debug("a_comp = $a_comp, a_entity = $a_entity , a_old_id = $a_old_id"); + /** + * Get a mapping + * + * @param string component + * @param string entity + * @param string old id + * + * @return string new id, or false if no mapping given + */ + public function getMapping($a_comp, $a_entity, $a_old_id) + { + $this->log->debug("a_comp = $a_comp, a_entity = $a_entity , a_old_id = $a_old_id"); - if(!isset ($this->mappings[$a_comp]) or !isset ($this->mappings[$a_comp][$a_entity])) - { - return false; - } - if (isset($this->mappings[$a_comp][$a_entity][$a_old_id])) - { - return $this->mappings[$a_comp][$a_entity][$a_old_id]; - } + if (!isset($this->mappings[$a_comp]) or !isset($this->mappings[$a_comp][$a_entity])) { + return false; + } + if (isset($this->mappings[$a_comp][$a_entity][$a_old_id])) { + return $this->mappings[$a_comp][$a_entity][$a_old_id]; + } - return false; - } + return false; + } - /** - * Get mapping - * - * @return array mapping - */ - function getAllMappings() - { - return $this->mappings; - } - - /** - * Get mappings for entity - * - * @param string component - * @param string entity - * @return - */ - function getMappingsOfEntity($a_comp, $a_entity) - { - if (isset($this->mappings[$a_comp][$a_entity])) - { - return $this->mappings[$a_comp][$a_entity]; - } - return array(); - } + /** + * Get mapping + * + * @return array mapping + */ + public function getAllMappings() + { + return $this->mappings; + } + /** + * Get mappings for entity + * + * @param string component + * @param string entity + * @return + */ + public function getMappingsOfEntity($a_comp, $a_entity) + { + if (isset($this->mappings[$a_comp][$a_entity])) { + return $this->mappings[$a_comp][$a_entity]; + } + return array(); + } } -?> \ No newline at end of file diff --git a/Services/Export/classes/class.ilManifestParser.php b/Services/Export/classes/class.ilManifestParser.php index 34b796e099283610a6e82f6aa911a51efbe12e51..f790911be054f8e7987bf5bd1ef342580c9c9e39 100644 --- a/Services/Export/classes/class.ilManifestParser.php +++ b/Services/Export/classes/class.ilManifestParser.php @@ -12,209 +12,205 @@ include_once("./Services/Xml/classes/class.ilSaxParser.php"); */ class ilManifestParser extends ilSaxParser { - protected $expfiles = array(); - protected $expsets = array(); - - /** - * Constructor - * - * @param - * @return - */ - function __construct($a_file) - { - parent::__construct($a_file, true); - $this->startParsing(); - } - - /** - * Set Installation ID - * - * @param string Installation ID - */ - final function setInstallId($a_val) - { - $this->install_id = $a_val; - } - - /** - * Get Installation ID - * - * @return string Installation ID - */ - final function getInstallId() - { - return $this->install_id; - } - - /** - * Set Installation Url - * - * @param string Installation Url - */ - final function setInstallUrl($a_val) - { - $this->install_url = $a_val; - } - - /** - * Get Installation Url - * - * @return string Installation Url - */ - final function getInstallUrl() - { - return $this->install_url; - } - - /** - * Set main entity - * - * @param string main entity - */ - function setMainEntity($a_val) - { - $this->main_entity = $a_val; - } - - /** - * Get main entity - * - * @return string main entity - */ - function getMainEntity() - { - return $this->main_entity; - } - - /** - * Set title - * - * @param string title - */ - function setTitle($a_val) - { - $this->title = $a_val; - } - - /** - * Get title - * - * @return string title - */ - function getTitle() - { - return $this->title; - } - - /** - * Set target release - * - * @param string target release - */ - function setTargetRelease($a_val) - { - $this->target_release = $a_val; - } - - /** - * Get target release - * - * @return string target release - */ - function getTargetRelease() - { - return $this->target_release; - } - - /** - * Get xml files - * - * @return array of strings xml file pathes - */ - function getExportFiles() - { - return $this->expfiles; - } - - public function getExportSets() - { - return $this->expsets; - } - - /** - * Set event handlers - * - * @param resource reference to the xml parser - * @access private - */ - function setHandlers($a_xml_parser) - { - xml_set_object($a_xml_parser,$this); - xml_set_element_handler($a_xml_parser, 'handleBeginTag', 'handleEndTag'); - xml_set_character_data_handler($a_xml_parser, 'handleCharacterData'); - } - - - /** - * Start parser - */ - function startParsing() - { - parent::startParsing(); - } - - /** - * Begin Tag - */ - function handleBeginTag($a_xml_parser, $a_name, $a_attribs) - { - switch ($a_name) - { - case "Manifest": - $this->setInstallId($a_attribs["InstallationId"]); - $this->setInstallUrl($a_attribs["InstallationUrl"]); - $this->setTitle($a_attribs["Title"]); - $this->setTargetRelease($a_attribs["TargetRelease"]); - $this->setMainEntity($a_attribs["MainEntity"]); - break; - - case "ExportFile": - $this->expfiles[] = array("component" => $a_attribs["Component"], - "path" => $a_attribs["Path"]); - break; - - case "ExportSet": - $this->expsets[] = array( - 'path' => $a_attribs['Path'], - 'type' => $a_attribs['Type'] - ); - break; - } - } - - /** - * End Tag - */ - function handleEndTag($a_xml_parser, $a_name) - { - - $this->chr_data = ""; - } - - /** - * End Tag - */ - function handleCharacterData($a_xml_parser,$a_data) - { - //$a_data = str_replace("<","<",$a_data); - //$a_data = str_replace(">",">",$a_data); - // DELETE WHITESPACES AND NEWLINES OF CHARACTER DATA - //$a_data = preg_replace("/\n/","",$a_data); - //$a_data = preg_replace("/\t+/","",$a_data); - - $this->chr_data .= $a_data; - } - + protected $expfiles = array(); + protected $expsets = array(); + + /** + * Constructor + * + * @param + * @return + */ + public function __construct($a_file) + { + parent::__construct($a_file, true); + $this->startParsing(); + } + + /** + * Set Installation ID + * + * @param string Installation ID + */ + final public function setInstallId($a_val) + { + $this->install_id = $a_val; + } + + /** + * Get Installation ID + * + * @return string Installation ID + */ + final public function getInstallId() + { + return $this->install_id; + } + + /** + * Set Installation Url + * + * @param string Installation Url + */ + final public function setInstallUrl($a_val) + { + $this->install_url = $a_val; + } + + /** + * Get Installation Url + * + * @return string Installation Url + */ + final public function getInstallUrl() + { + return $this->install_url; + } + + /** + * Set main entity + * + * @param string main entity + */ + public function setMainEntity($a_val) + { + $this->main_entity = $a_val; + } + + /** + * Get main entity + * + * @return string main entity + */ + public function getMainEntity() + { + return $this->main_entity; + } + + /** + * Set title + * + * @param string title + */ + public function setTitle($a_val) + { + $this->title = $a_val; + } + + /** + * Get title + * + * @return string title + */ + public function getTitle() + { + return $this->title; + } + + /** + * Set target release + * + * @param string target release + */ + public function setTargetRelease($a_val) + { + $this->target_release = $a_val; + } + + /** + * Get target release + * + * @return string target release + */ + public function getTargetRelease() + { + return $this->target_release; + } + + /** + * Get xml files + * + * @return array of strings xml file pathes + */ + public function getExportFiles() + { + return $this->expfiles; + } + + public function getExportSets() + { + return $this->expsets; + } + + /** + * Set event handlers + * + * @param resource reference to the xml parser + * @access private + */ + public function setHandlers($a_xml_parser) + { + xml_set_object($a_xml_parser, $this); + xml_set_element_handler($a_xml_parser, 'handleBeginTag', 'handleEndTag'); + xml_set_character_data_handler($a_xml_parser, 'handleCharacterData'); + } + + + /** + * Start parser + */ + public function startParsing() + { + parent::startParsing(); + } + + /** + * Begin Tag + */ + public function handleBeginTag($a_xml_parser, $a_name, $a_attribs) + { + switch ($a_name) { + case "Manifest": + $this->setInstallId($a_attribs["InstallationId"]); + $this->setInstallUrl($a_attribs["InstallationUrl"]); + $this->setTitle($a_attribs["Title"]); + $this->setTargetRelease($a_attribs["TargetRelease"]); + $this->setMainEntity($a_attribs["MainEntity"]); + break; + + case "ExportFile": + $this->expfiles[] = array("component" => $a_attribs["Component"], + "path" => $a_attribs["Path"]); + break; + + case "ExportSet": + $this->expsets[] = array( + 'path' => $a_attribs['Path'], + 'type' => $a_attribs['Type'] + ); + break; + } + } + + /** + * End Tag + */ + public function handleEndTag($a_xml_parser, $a_name) + { + $this->chr_data = ""; + } + + /** + * End Tag + */ + public function handleCharacterData($a_xml_parser, $a_data) + { + //$a_data = str_replace("<","<",$a_data); + //$a_data = str_replace(">",">",$a_data); + // DELETE WHITESPACES AND NEWLINES OF CHARACTER DATA + //$a_data = preg_replace("/\n/","",$a_data); + //$a_data = preg_replace("/\t+/","",$a_data); + + $this->chr_data .= $a_data; + } } -?> \ No newline at end of file diff --git a/Services/Export/classes/class.ilSubItemSelectionTableGUI.php b/Services/Export/classes/class.ilSubItemSelectionTableGUI.php index 6c0cd4bc27f4fbe8a9c5ecb77bc0d7f47285f730..dee85302121337b3220a4754296b64965612bd37 100755 --- a/Services/Export/classes/class.ilSubItemSelectionTableGUI.php +++ b/Services/Export/classes/class.ilSubItemSelectionTableGUI.php @@ -13,72 +13,77 @@ include_once("Services/Table/classes/class.ilTable2GUI.php"); */ class ilSubItemSelectionTableGUI extends ilTable2GUI { + public function __construct( + $a_parent_obj, + $a_parent_cmd, + $a_ref_id, + $a_cmd = "createExportFile", + $a_cmd_txt = "" + ) { + global $DIC; - public function __construct($a_parent_obj, $a_parent_cmd, - $a_ref_id, $a_cmd = "createExportFile", $a_cmd_txt = "") - { - global $DIC; + $ilCtrl = $DIC['ilCtrl']; + $lng = $DIC['lng']; + + parent::__construct($a_parent_obj, $a_parent_cmd); + $lng->loadLanguageModule("export"); - $ilCtrl = $DIC['ilCtrl']; - $lng = $DIC['lng']; - - parent::__construct($a_parent_obj, $a_parent_cmd); - $lng->loadLanguageModule("export"); + if ($a_cmd_txt == "") { + $a_cmd_txt = $lng->txt("export_create_export_file"); + } - if ($a_cmd_txt == "") - { - $a_cmd_txt = $lng->txt("export_create_export_file"); - } - - $this->addColumn($lng->txt("export_resource")); - $this->addColumn($lng->txt("export_last_export")); - $this->addColumn($lng->txt("export_last_export_file"), "", "20%"); - $this->addColumn($lng->txt("export_create_new_file"), "", "20%"); - $this->addColumn($lng->txt("export_omit_resource"), "", "20%"); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->addCommandButton($a_cmd, $a_cmd_txt); - $this->setRowTemplate("tpl.sub_item_selection_row.html", - "Services/Export"); - $this->setTitle($lng->txt("export_select_resources")); - include_once("./Services/Export/classes/class.ilExport.php"); - $this->setData(ilExport::_getValidExportSubItems($a_ref_id)); - $this->setLimit(99999); - } - - /** - * Standard Version of Fill Row. Most likely to - * be overwritten by derived class. - */ - protected function fillRow($a_set) - { - global $DIC; - - $lng = $DIC['lng']; - $ilCtrl = $DIC['ilCtrl']; - - $now = new ilDateTime(time(),IL_CAL_UNIX); - - $this->tpl->setVariable("IMG_ALT", $lng->txt("obj_".$a_set["type"])); - $this->tpl->setVariable("IMG_SRC", ilObject::_getIcon($a_set["obj_id"], - "small", $a_set["type"])); - $this->tpl->setVariable("VAL_TITLE", $a_set["title"]); - $this->tpl->setVariable("ID", $a_set["ref_id"]); - $this->tpl->setVariable("TXT_LAST_EXPORT_FILE", $lng->txt("export_last_file")); - $this->tpl->setVariable("TXT_OMIT", $lng->txt("export_omit")); - $this->tpl->setVariable("TXT_CREATE_NEW_EXPORT_FILE", $lng->txt("export_create")); - $preset = "CREATE"; - if ($a_set["timestamp"] > 0) - { - $last_export = new ilDateTime($a_set["timestamp"], IL_CAL_UNIX); - $this->tpl->setVariable("VAL_LAST_EXPORT", - ilDatePresentation::formatDate($last_export)); - if (ilDateTime::_equals($last_export, $now, IL_CAL_DAY)) - { - $preset = "LAST_FILE"; - } - } - $this->tpl->setVariable("SEL_".$preset, ' checked="checked" '); - } + $this->addColumn($lng->txt("export_resource")); + $this->addColumn($lng->txt("export_last_export")); + $this->addColumn($lng->txt("export_last_export_file"), "", "20%"); + $this->addColumn($lng->txt("export_create_new_file"), "", "20%"); + $this->addColumn($lng->txt("export_omit_resource"), "", "20%"); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->addCommandButton($a_cmd, $a_cmd_txt); + $this->setRowTemplate( + "tpl.sub_item_selection_row.html", + "Services/Export" + ); + $this->setTitle($lng->txt("export_select_resources")); + include_once("./Services/Export/classes/class.ilExport.php"); + $this->setData(ilExport::_getValidExportSubItems($a_ref_id)); + $this->setLimit(99999); + } + + /** + * Standard Version of Fill Row. Most likely to + * be overwritten by derived class. + */ + protected function fillRow($a_set) + { + global $DIC; + $lng = $DIC['lng']; + $ilCtrl = $DIC['ilCtrl']; + + $now = new ilDateTime(time(), IL_CAL_UNIX); + + $this->tpl->setVariable("IMG_ALT", $lng->txt("obj_" . $a_set["type"])); + $this->tpl->setVariable("IMG_SRC", ilObject::_getIcon( + $a_set["obj_id"], + "small", + $a_set["type"] + )); + $this->tpl->setVariable("VAL_TITLE", $a_set["title"]); + $this->tpl->setVariable("ID", $a_set["ref_id"]); + $this->tpl->setVariable("TXT_LAST_EXPORT_FILE", $lng->txt("export_last_file")); + $this->tpl->setVariable("TXT_OMIT", $lng->txt("export_omit")); + $this->tpl->setVariable("TXT_CREATE_NEW_EXPORT_FILE", $lng->txt("export_create")); + $preset = "CREATE"; + if ($a_set["timestamp"] > 0) { + $last_export = new ilDateTime($a_set["timestamp"], IL_CAL_UNIX); + $this->tpl->setVariable( + "VAL_LAST_EXPORT", + ilDatePresentation::formatDate($last_export) + ); + if (ilDateTime::_equals($last_export, $now, IL_CAL_DAY)) { + $preset = "LAST_FILE"; + } + } + $this->tpl->setVariable("SEL_" . $preset, ' checked="checked" '); + } } -?> diff --git a/Services/Export/classes/class.ilXmlExporter.php b/Services/Export/classes/class.ilXmlExporter.php index 6e27f960f174f29ad828a2cd77e76fba36dae6b0..b2f51fc567de5eb82ccac7159575cace633f31f4 100644 --- a/Services/Export/classes/class.ilXmlExporter.php +++ b/Services/Export/classes/class.ilXmlExporter.php @@ -10,172 +10,166 @@ */ abstract class ilXmlExporter { - protected $dir_relative; - protected $dir_absolute; - protected $exp; - - /** - * Constructor - * - * @param - * @return - */ - public function __construct() - { - - } - - /** - * Set export object - * - * @param ilExport $a_exp export object - */ - function setExport(ilExport $a_exp) - { - $this->exp = $a_exp; - } - - /** - * Get export - * - * @return ilExport export object - */ - function getExport() - { - return $this->exp; - } - - /** - * export directory lookup - * @return string export directory - */ - public static function lookupExportDirectory($a_obj_type, $a_obj_id, $a_export_type = 'xml', $a_entity = "") - { - $ent = ($a_entity == "") - ? "" - : "_".$a_entity; - - if($a_export_type == 'xml') - { - return ilUtil::getDataDir()."/".$a_obj_type.$ent."_data"."/".$a_obj_type."_".$a_obj_id."/export"; - } - return ilUtil::getDataDir()."/".$a_obj_type.$ent."_data"."/".$a_obj_type."_".$a_obj_id."/export_".$a_export_type; - } - - /** - * Get xml representation - * - * @param string entity - * @param string schema version - * @param string id - * @return string xml string - */ - abstract public function getXmlRepresentation($a_entity, $a_schema_version, $a_id); - - abstract public function init(); - - - /** - * Export directories - * - * @param string relative directory - * @param string absolute directory - */ - public function setExportDirectories($a_dir_relative, $a_dir_absolute) - { - $this->dir_relative = $a_dir_relative; - $this->dir_absolute = $a_dir_absolute; - } - - /** - * Get relative export directory - * - * @return string relative directory - */ - public function getRelativeExportDirectory() - { - return $this->dir_relative; - } - - /** - * Get absolute export directory - * - * @return string absolute directory - */ - public function getAbsoluteExportDirectory() - { - return $this->dir_absolute; - } - - /** - * Get head dependencies - * - * @param string entity - * @param string target release - * @param array ids - * @return array array of array with keys "component", entity", "ids" - */ - public function getXmlExportHeadDependencies($a_entity, $a_target_release, $a_ids) - { - return array(); - } - - /** - * Get tail dependencies - * - * @param string entity - * @param string target release - * @param array ids - * @return array array of array with keys "component", entity", "ids" - */ - public function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) - { - return array(); - } - - /** - * Returns schema versions that the component can export to. - * ILIAS chooses the first one, that has min/max constraints which - * fit to the target release. Please put the newest on top. Example: - * - * return array ( - * "4.1.0" => array( - * "namespace" => "http://www.ilias.de/Services/MetaData/md/4_1", - * "xsd_file" => "ilias_md_4_1.xsd", - * "min" => "4.1.0", - * "max" => "") - * ); - * - * - * @return array - */ - abstract public function getValidSchemaVersions($a_entity); - - /** - * Determine schema version - * - * @param - * @return - */ - public final function determineSchemaVersion($a_entity, $a_target_release) - { - $svs = $this->getValidSchemaVersions($a_entity); - $found = false; - foreach ($svs as $k => $sv) - { - if (!$found) - { - if (version_compare($sv["min"], ILIAS_VERSION_NUMERIC, "<=") - && ($sv["max"] == "" || version_compare($sv["max"], ILIAS_VERSION_NUMERIC, ">="))) - { - $rsv = $sv; - $rsv["schema_version"] = $k; - $found = true; - } - } - } - - return $rsv; - } + protected $dir_relative; + protected $dir_absolute; + protected $exp; + + /** + * Constructor + * + * @param + * @return + */ + public function __construct() + { + } + + /** + * Set export object + * + * @param ilExport $a_exp export object + */ + public function setExport(ilExport $a_exp) + { + $this->exp = $a_exp; + } + + /** + * Get export + * + * @return ilExport export object + */ + public function getExport() + { + return $this->exp; + } + + /** + * export directory lookup + * @return string export directory + */ + public static function lookupExportDirectory($a_obj_type, $a_obj_id, $a_export_type = 'xml', $a_entity = "") + { + $ent = ($a_entity == "") + ? "" + : "_" . $a_entity; + + if ($a_export_type == 'xml') { + return ilUtil::getDataDir() . "/" . $a_obj_type . $ent . "_data" . "/" . $a_obj_type . "_" . $a_obj_id . "/export"; + } + return ilUtil::getDataDir() . "/" . $a_obj_type . $ent . "_data" . "/" . $a_obj_type . "_" . $a_obj_id . "/export_" . $a_export_type; + } + + /** + * Get xml representation + * + * @param string entity + * @param string schema version + * @param string id + * @return string xml string + */ + abstract public function getXmlRepresentation($a_entity, $a_schema_version, $a_id); + + abstract public function init(); + + + /** + * Export directories + * + * @param string relative directory + * @param string absolute directory + */ + public function setExportDirectories($a_dir_relative, $a_dir_absolute) + { + $this->dir_relative = $a_dir_relative; + $this->dir_absolute = $a_dir_absolute; + } + + /** + * Get relative export directory + * + * @return string relative directory + */ + public function getRelativeExportDirectory() + { + return $this->dir_relative; + } + + /** + * Get absolute export directory + * + * @return string absolute directory + */ + public function getAbsoluteExportDirectory() + { + return $this->dir_absolute; + } + + /** + * Get head dependencies + * + * @param string entity + * @param string target release + * @param array ids + * @return array array of array with keys "component", entity", "ids" + */ + public function getXmlExportHeadDependencies($a_entity, $a_target_release, $a_ids) + { + return array(); + } + + /** + * Get tail dependencies + * + * @param string entity + * @param string target release + * @param array ids + * @return array array of array with keys "component", entity", "ids" + */ + public function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) + { + return array(); + } + + /** + * Returns schema versions that the component can export to. + * ILIAS chooses the first one, that has min/max constraints which + * fit to the target release. Please put the newest on top. Example: + * + * return array ( + * "4.1.0" => array( + * "namespace" => "http://www.ilias.de/Services/MetaData/md/4_1", + * "xsd_file" => "ilias_md_4_1.xsd", + * "min" => "4.1.0", + * "max" => "") + * ); + * + * + * @return array + */ + abstract public function getValidSchemaVersions($a_entity); + + /** + * Determine schema version + * + * @param + * @return + */ + final public function determineSchemaVersion($a_entity, $a_target_release) + { + $svs = $this->getValidSchemaVersions($a_entity); + $found = false; + foreach ($svs as $k => $sv) { + if (!$found) { + if (version_compare($sv["min"], ILIAS_VERSION_NUMERIC, "<=") + && ($sv["max"] == "" || version_compare($sv["max"], ILIAS_VERSION_NUMERIC, ">="))) { + $rsv = $sv; + $rsv["schema_version"] = $k; + $found = true; + } + } + } + + return $rsv; + } } -?> diff --git a/Services/Export/classes/class.ilXmlImporter.php b/Services/Export/classes/class.ilXmlImporter.php index a20c6eb02d7e6c84f7b0d7b3c656868bb77e3a50..d0c32d921a9a523f2da9a4cfa507d8f8fe70880d 100644 --- a/Services/Export/classes/class.ilXmlImporter.php +++ b/Services/Export/classes/class.ilXmlImporter.php @@ -10,191 +10,186 @@ */ abstract class ilXmlImporter { - protected $skip_entities = array(); - protected $imp; // import object - - /** - * Constructor - * - * @param - * @return - */ - function __construct() - { - - } - - /** - * Set import - * - * @param ilImport $a_val import object - */ - function setImport($a_val) - { - $this->imp = $a_val; - } - - /** - * Get import - * - * @return ilImport import object - */ - function getImport() - { - return $this->imp; - } - /** - * Init - */ - function init() - { - } - - /** - * Set installation id - * - * @param string installation id - */ - function setInstallId($a_val) - { - $this->install_id = $a_val; - } - - /** - * Get installation id - * - * @return string installation id - */ - function getInstallId() - { - return $this->install_id; - } - - /** - * Set installation url - * - * @param string installation url - */ - function setInstallUrl($a_val) - { - $this->install_url = $a_val; - } - - /** - * Get installation url - * - * @return string installation url - */ - function getInstallUrl() - { - return $this->install_url; - } - - /** - * Set schema version - * - * @param string schema version - */ - function setSchemaVersion($a_val) - { - $this->schema_version = $a_val; - } - - /** - * Get schema version - * - * @return string schema version - */ - function getSchemaVersion() - { - return $this->schema_version; - } - - /** - * Set import directory - * - * @param string import directory - */ - function setImportDirectory($a_val) - { - $this->import_directory = $a_val; - } - - /** - * Get import directory - * - * @return string import directory - */ - function getImportDirectory() - { - return $this->import_directory; - } - - /** - * Set skip entities - * - * @param array $a_val entities to skip - */ - function setSkipEntities($a_val) - { - $this->skip_entities = $a_val; - } - - /** - * Get skip entities - * - * @return array entities to skip - */ - function getSkipEntities() - { - return $this->skip_entities; - } - - /** - * Is exporting and importing installation identical? - * - * @param - * @return - */ - function exportedFromSameInstallation() - { - if ($this->getInstallId() > 0 && ($this->getInstallId() == IL_INST_ID)) - { - return true; - } - return false; - } - - - /** - * Import xml representation - * - * @param string entity - * @param string target release - * @param string id - * @return string xml string - */ - abstract public function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping); - - /** - * Final processing - * - * @param array mapping array - */ - function finalProcessing($a_mapping) - { - - } - - // begin-patch optes_lok_export - /** - * Called after all container objects have been implemented. - * @param ilImportMapping $mapping - */ - public function afterContainerImportProcessing(ilImportMapping $mapping) - { - - } - // end-patch optes_lok_export + protected $skip_entities = array(); + protected $imp; // import object + + /** + * Constructor + * + * @param + * @return + */ + public function __construct() + { + } + + /** + * Set import + * + * @param ilImport $a_val import object + */ + public function setImport($a_val) + { + $this->imp = $a_val; + } + + /** + * Get import + * + * @return ilImport import object + */ + public function getImport() + { + return $this->imp; + } + /** + * Init + */ + public function init() + { + } + + /** + * Set installation id + * + * @param string installation id + */ + public function setInstallId($a_val) + { + $this->install_id = $a_val; + } + + /** + * Get installation id + * + * @return string installation id + */ + public function getInstallId() + { + return $this->install_id; + } + + /** + * Set installation url + * + * @param string installation url + */ + public function setInstallUrl($a_val) + { + $this->install_url = $a_val; + } + + /** + * Get installation url + * + * @return string installation url + */ + public function getInstallUrl() + { + return $this->install_url; + } + + /** + * Set schema version + * + * @param string schema version + */ + public function setSchemaVersion($a_val) + { + $this->schema_version = $a_val; + } + + /** + * Get schema version + * + * @return string schema version + */ + public function getSchemaVersion() + { + return $this->schema_version; + } + + /** + * Set import directory + * + * @param string import directory + */ + public function setImportDirectory($a_val) + { + $this->import_directory = $a_val; + } + + /** + * Get import directory + * + * @return string import directory + */ + public function getImportDirectory() + { + return $this->import_directory; + } + + /** + * Set skip entities + * + * @param array $a_val entities to skip + */ + public function setSkipEntities($a_val) + { + $this->skip_entities = $a_val; + } + + /** + * Get skip entities + * + * @return array entities to skip + */ + public function getSkipEntities() + { + return $this->skip_entities; + } + + /** + * Is exporting and importing installation identical? + * + * @param + * @return + */ + public function exportedFromSameInstallation() + { + if ($this->getInstallId() > 0 && ($this->getInstallId() == IL_INST_ID)) { + return true; + } + return false; + } + + + /** + * Import xml representation + * + * @param string entity + * @param string target release + * @param string id + * @return string xml string + */ + abstract public function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping); + + /** + * Final processing + * + * @param array mapping array + */ + public function finalProcessing($a_mapping) + { + } + + // begin-patch optes_lok_export + /** + * Called after all container objects have been implemented. + * @param ilImportMapping $mapping + */ + public function afterContainerImportProcessing(ilImportMapping $mapping) + { + } + // end-patch optes_lok_export } -?> diff --git a/Services/Export/exceptions/class.ilExportException.php b/Services/Export/exceptions/class.ilExportException.php index 5b85a43923191a4cad8052ae4dfcb825a22ee939..a933d073bd17dded3a603aa4ff51633530c4bc69 100644 --- a/Services/Export/exceptions/class.ilExportException.php +++ b/Services/Export/exceptions/class.ilExportException.php @@ -2,27 +2,26 @@ /* Copyright (c) 1998-2015 ILIAS open source, Extended GPL, see docs/LICENSE */ -require_once 'Services/Exceptions/classes/class.ilException.php'; +require_once 'Services/Exceptions/classes/class.ilException.php'; -/** +/** * General export exception - * + * * @author Alex Killing - * @version $Id$ - * + * @version $Id$ + * */ class ilExportException extends ilException { - /** - * Constructor - * - * A message is not optional as in build in class Exception - * - * @param string $a_message message - */ - public function __construct($a_message) - { - parent::__construct($a_message); - } + /** + * Constructor + * + * A message is not optional as in build in class Exception + * + * @param string $a_message message + */ + public function __construct($a_message) + { + parent::__construct($a_message); + } } -?> diff --git a/Services/Export/exceptions/class.ilImportException.php b/Services/Export/exceptions/class.ilImportException.php index 0edee77111e7893a427abd367acd706d784b6458..aee0244e399be861bf3f6682b34d2468f636eafd 100644 --- a/Services/Export/exceptions/class.ilImportException.php +++ b/Services/Export/exceptions/class.ilImportException.php @@ -2,27 +2,26 @@ /* Copyright (c) 1998-2012 ILIAS open source, Extended GPL, see docs/LICENSE */ -require_once 'Services/Exceptions/classes/class.ilException.php'; +require_once 'Services/Exceptions/classes/class.ilException.php'; -/** - * General import exception - * +/** + * General import exception + * * @author Alex Killing - * @version $Id$ - * + * @version $Id$ + * */ class ilImportException extends ilException { - /** - * Constructor - * - * A message is not optional as in build in class Exception - * - * @param string $a_message message - */ - public function __construct($a_message) - { - parent::__construct($a_message); - } + /** + * Constructor + * + * A message is not optional as in build in class Exception + * + * @param string $a_message message + */ + public function __construct($a_message) + { + parent::__construct($a_message); + } } -?> diff --git a/Services/Export/exceptions/class.ilImportObjectTypeMismatchException.php b/Services/Export/exceptions/class.ilImportObjectTypeMismatchException.php index e207e0e9d07319485c6e7f0811a6507b029dc8cd..69c4164db730ca2e981ac9d6bbcace3c4aa82972 100644 --- a/Services/Export/exceptions/class.ilImportObjectTypeMismatchException.php +++ b/Services/Export/exceptions/class.ilImportObjectTypeMismatchException.php @@ -2,16 +2,15 @@ /* Copyright (c) 1998-2012 ILIAS open source, Extended GPL, see docs/LICENSE */ -include_once("./Services/Export/exceptions/class.ilImportException.php"); +include_once("./Services/Export/exceptions/class.ilImportException.php"); -/** +/** * Import object type does not match - * + * * @author Alex Killing - * @version $Id$ - * + * @version $Id$ + * */ class ilImportObjectTypeMismatchException extends ilImportException { } -?> diff --git a/Services/Export/exceptions/class.ilManifestFileNotFoundImportException.php b/Services/Export/exceptions/class.ilManifestFileNotFoundImportException.php index 91a94bc3c2ddcbdc8cd56058bbc48523a8ba38fa..0b52a03f926079858deb0bde932044a67953c2e2 100644 --- a/Services/Export/exceptions/class.ilManifestFileNotFoundImportException.php +++ b/Services/Export/exceptions/class.ilManifestFileNotFoundImportException.php @@ -2,58 +2,57 @@ /* Copyright (c) 1998-2012 ILIAS open source, Extended GPL, see docs/LICENSE */ -include_once("./Services/Export/exceptions/class.ilImportException.php"); +include_once("./Services/Export/exceptions/class.ilImportException.php"); -/** +/** * manifest.xml file not found-exception for import - * + * * @author Alex Killing - * @version $Id$ - * + * @version $Id$ + * */ class ilManifestFileNotFoundImportException extends ilImportException { - private $manifest_dir = ""; - private $tmp_dir = ""; - - /** - * Set manifest directory - * - * @param string $a_val manifest directory - */ - function setManifestDir($a_val) - { - $this->manifest_dir = $a_val; - } - - /** - * Get manifest directory - * - * @return string manifest directory - */ - function getManifestDir() - { - return $this->manifest_dir; - } - - /** - * Set temporary directory - * - * @param string $a_val temporary directory - */ - function setTmpDir($a_val) - { - $this->tmp_dir = $a_val; - } - - /** - * Get temporary directory - * - * @return string temporary directory - */ - function getTmpDir() - { - return $this->tmp_dir; - } + private $manifest_dir = ""; + private $tmp_dir = ""; + + /** + * Set manifest directory + * + * @param string $a_val manifest directory + */ + public function setManifestDir($a_val) + { + $this->manifest_dir = $a_val; + } + + /** + * Get manifest directory + * + * @return string manifest directory + */ + public function getManifestDir() + { + return $this->manifest_dir; + } + + /** + * Set temporary directory + * + * @param string $a_val temporary directory + */ + public function setTmpDir($a_val) + { + $this->tmp_dir = $a_val; + } + + /** + * Get temporary directory + * + * @return string temporary directory + */ + public function getTmpDir() + { + return $this->tmp_dir; + } } -?> diff --git a/Services/Feeds/classes/class.ilExternalFeed.php b/Services/Feeds/classes/class.ilExternalFeed.php index cc8bcd36d7335c790b62f0a6f70ddf3899a9cd4a..f63118c49d13770f08319ea91e794ec169e58fe9 100755 --- a/Services/Feeds/classes/class.ilExternalFeed.php +++ b/Services/Feeds/classes/class.ilExternalFeed.php @@ -5,10 +5,10 @@ require_once './Services/Http/classes/class.ilProxySettings.php'; define("MAGPIE_DIR", "./Services/Feeds/magpierss/"); define("MAGPIE_CACHE_ON", true); -define("MAGPIE_CACHE_DIR", "./".ILIAS_WEB_DIR."/".CLIENT_ID."/magpie_cache"); +define("MAGPIE_CACHE_DIR", "./" . ILIAS_WEB_DIR . "/" . CLIENT_ID . "/magpie_cache"); define('MAGPIE_OUTPUT_ENCODING', "UTF-8"); define('MAGPIE_CACHE_AGE', 900); // 900 seconds = 15 minutes -include_once(MAGPIE_DIR."/rss_fetch.inc"); +include_once(MAGPIE_DIR . "/rss_fetch.inc"); include_once("./Services/Feeds/classes/class.ilExternalFeedItem.php"); @@ -21,310 +21,283 @@ include_once("./Services/Feeds/classes/class.ilExternalFeedItem.php"); */ class ilExternalFeed { - protected $items = array(); - - /** - * Constructor - */ - function __construct() - { - // IF YOU ADD THINGS HERE, THEY MAY ALSO BE ADDED TO - // SOME OF THE STATIC METHODS - $this->_createCacheDirectory(); + protected $items = array(); + + /** + * Constructor + */ + public function __construct() + { + // IF YOU ADD THINGS HERE, THEY MAY ALSO BE ADDED TO + // SOME OF THE STATIC METHODS + $this->_createCacheDirectory(); - if(ilProxySettings::_getInstance()->isActive()) - { - define('IL_FEED_PROXY_HOST', ilProxySettings::_getInstance()->getHost()); - define('IL_FEED_PROXY_PORT', ilProxySettings::_getInstance()->getPort()); - } - else - { - define('IL_FEED_PROXY_HOST', ""); - define('IL_FEED_PROXY_PORT', ""); - } - } + if (ilProxySettings::_getInstance()->isActive()) { + define('IL_FEED_PROXY_HOST', ilProxySettings::_getInstance()->getHost()); + define('IL_FEED_PROXY_PORT', ilProxySettings::_getInstance()->getPort()); + } else { + define('IL_FEED_PROXY_HOST', ""); + define('IL_FEED_PROXY_PORT', ""); + } + } - /** - * Set Url. - * - * @param string $a_url Url - */ - function setUrl($a_url) - { - $this->url = $a_url; - } + /** + * Set Url. + * + * @param string $a_url Url + */ + public function setUrl($a_url) + { + $this->url = $a_url; + } - /** - * Get Url. - * - * @return string Url - */ - function getUrl() - { - return $this->url; - } + /** + * Get Url. + * + * @return string Url + */ + public function getUrl() + { + return $this->url; + } - /** - * Set Error. - * - * @param string $a_error Error - */ - function setError($a_error) - { - $this->error = $a_error; - } + /** + * Set Error. + * + * @param string $a_error Error + */ + public function setError($a_error) + { + $this->error = $a_error; + } - /** - * Get Error. - * - * @return string Error - */ - function getError() - { - return $this->error; - } + /** + * Get Error. + * + * @return string Error + */ + public function getError() + { + return $this->error; + } - /** - * Create magpie cache directorry (if not existing) - */ - static function _createCacheDirectory() - { - if (!is_dir(ilUtil::getWebspaceDir()."/magpie_cache")) - { - ilUtil::makeDir(ilUtil::getWebspaceDir()."/magpie_cache"); - } - } - - /** - * Check Url - * - * @param string URL - * @return mixed true, if everything is fine, error string otherwise - */ - static function _checkUrl($a_url) - { - if (!defined('IL_FEED_PROXY_HOST')) - { - ilExternalFeed::_createCacheDirectory(); + /** + * Create magpie cache directorry (if not existing) + */ + public static function _createCacheDirectory() + { + if (!is_dir(ilUtil::getWebspaceDir() . "/magpie_cache")) { + ilUtil::makeDir(ilUtil::getWebspaceDir() . "/magpie_cache"); + } + } + + /** + * Check Url + * + * @param string URL + * @return mixed true, if everything is fine, error string otherwise + */ + public static function _checkUrl($a_url) + { + if (!defined('IL_FEED_PROXY_HOST')) { + ilExternalFeed::_createCacheDirectory(); - if(ilProxySettings::_getInstance()->isActive()) - { - define('IL_FEED_PROXY_HOST', ilProxySettings::_getInstance()->getHost()); - define('IL_FEED_PROXY_PORT', ilProxySettings::_getInstance()->getPort()); - } - else - { - define('IL_FEED_PROXY_HOST', ""); - define('IL_FEED_PROXY_PORT', ""); - } - } - - $feed = @fetch_rss($a_url); - if (!$feed) - { - $error = magpie_error(); - - if ($error != "") - { - return $error; - } - else - { - return "Unknown Error."; - } - } - - return true; - } - - /** - * Fetch the feed - */ - function fetch() - { - if ($this->getUrl() != "") - { - $this->feed = @fetch_rss($this->getUrl()); - } - - if(!$this->feed) - { - $error = magpie_error(); - if ($error == "") - { - $this->setError("Unknown Error."); - } - else - { - $this->setError(magpie_error()); - } - return false; - } - - if (is_array($this->feed->items)) - { - foreach($this->feed->items as $item) - { - $item_obj = new ilExternalFeedItem(); - $item_obj->setMagpieItem($item); - $this->items[] = $item_obj; - } - } - } - - /** - * Check cache hit - */ - function checkCacheHit() - { - ilExternalFeed::_createCacheDirectory(); - - $cache = new RSSCache( MAGPIE_CACHE_DIR, MAGPIE_CACHE_AGE ); + if (ilProxySettings::_getInstance()->isActive()) { + define('IL_FEED_PROXY_HOST', ilProxySettings::_getInstance()->getHost()); + define('IL_FEED_PROXY_PORT', ilProxySettings::_getInstance()->getPort()); + } else { + define('IL_FEED_PROXY_HOST', ""); + define('IL_FEED_PROXY_PORT', ""); + } + } + + $feed = @fetch_rss($a_url); + if (!$feed) { + $error = magpie_error(); + + if ($error != "") { + return $error; + } else { + return "Unknown Error."; + } + } + + return true; + } + + /** + * Fetch the feed + */ + public function fetch() + { + if ($this->getUrl() != "") { + $this->feed = @fetch_rss($this->getUrl()); + } + + if (!$this->feed) { + $error = magpie_error(); + if ($error == "") { + $this->setError("Unknown Error."); + } else { + $this->setError(magpie_error()); + } + return false; + } + + if (is_array($this->feed->items)) { + foreach ($this->feed->items as $item) { + $item_obj = new ilExternalFeedItem(); + $item_obj->setMagpieItem($item); + $this->items[] = $item_obj; + } + } + } + + /** + * Check cache hit + */ + public function checkCacheHit() + { + ilExternalFeed::_createCacheDirectory(); + + $cache = new RSSCache(MAGPIE_CACHE_DIR, MAGPIE_CACHE_AGE); $cache_status = 0; // response of check_cache $request_headers = array(); // HTTP headers to send with fetch $rss = 0; // parsed RSS object $errormsg = 0; // errors, if any - $cache_key = $this->getUrl().MAGPIE_OUTPUT_ENCODING; + $cache_key = $this->getUrl() . MAGPIE_OUTPUT_ENCODING; if (!$cache->ERROR) { // return cache HIT, MISS, or STALE - $cache_status = $cache->check_cache( $cache_key); + $cache_status = $cache->check_cache($cache_key); } // if object cached, and cache is fresh, return cached obj - if ($cache_status == 'HIT') - { - return true; - } - - return false; - } - - /** - * Get Channel - */ - function getChannelTitle() - { - return $this->feed->channel["title"]; - } + if ($cache_status == 'HIT') { + return true; + } + + return false; + } + + /** + * Get Channel + */ + public function getChannelTitle() + { + return $this->feed->channel["title"]; + } - /** - * Get Description - */ - function getChannelDescription() - { - return $this->feed->channel["description"]; - } + /** + * Get Description + */ + public function getChannelDescription() + { + return $this->feed->channel["description"]; + } - /** - * Get Items - */ - function getItems() - { - return $this->items; - } - - /** - * Determine Feed Url - * - * @param $a_url URL that - */ - static function _determineFeedUrl($a_url) - { - if (!defined('IL_FEED_PROXY_HOST')) - { - if(ilProxySettings::_getInstance()->isActive()) - { - define('IL_FEED_PROXY_HOST', ilProxySettings::_getInstance()->getHost()); - define('IL_FEED_PROXY_PORT', ilProxySettings::_getInstance()->getPort()); - } - else - { - define('IL_FEED_PROXY_HOST', ""); - define('IL_FEED_PROXY_PORT', ""); - } - } + /** + * Get Items + */ + public function getItems() + { + return $this->items; + } + + /** + * Determine Feed Url + * + * @param $a_url URL that + */ + public static function _determineFeedUrl($a_url) + { + if (!defined('IL_FEED_PROXY_HOST')) { + if (ilProxySettings::_getInstance()->isActive()) { + define('IL_FEED_PROXY_HOST', ilProxySettings::_getInstance()->getHost()); + define('IL_FEED_PROXY_PORT', ilProxySettings::_getInstance()->getPort()); + } else { + define('IL_FEED_PROXY_HOST', ""); + define('IL_FEED_PROXY_PORT', ""); + } + } - $res = @fopen($a_url, "r"); - - if (!$res) - { - return ""; - } - - $contents = ''; - while (!feof($res)) - { - $contents.= fread($res, 8192); - } - fclose($res); - - return ilExternalFeed::_getRSSLocation($contents, $a_url); - } - - /** - * This one is by Keith Devens - *, see http://keithdevens.com/weblog/archive/2002/Jun/03/RSSAuto-DiscoveryPHP - */ - static function _getRSSLocation($html, $location) - { - if(!$html or !$location){ - return false; - }else{ - #search through the HTML, save all tags - # and store each link's attributes in an associative array - preg_match_all('//si', $html, $matches); - $links = $matches[1]; - $final_links = array(); - $link_count = count($links); - for($n=0; $n<$link_count; $n++){ - $attributes = preg_split('/\s+/s', $links[$n]); - foreach($attributes as $attribute){ - $att = preg_split('/\s*=\s*/s', $attribute, 2); - if(isset($att[1])){ - $att[1] = preg_replace('/([\'"]?)(.*)\1/', '$2', $att[1]); - $final_link[strtolower($att[0])] = $att[1]; - } - } - $final_links[$n] = $final_link; - } - #now figure out which one points to the RSS file - for($n=0; $n<$link_count; $n++){ - if(strtolower($final_links[$n]['rel']) == 'alternate'){ - if(strtolower($final_links[$n]['type']) == 'application/rss+xml'){ - $href = $final_links[$n]['href']; - } - if(!$href and strtolower($final_links[$n]['type']) == 'text/xml'){ - #kludge to make the first version of this still work - $href = $final_links[$n]['href']; - } - if($href){ - if(strstr($href, "http://") !== false){ #if it's absolute - $full_url = $href; - }else{ #otherwise, 'absolutize' it - $url_parts = parse_url($location); - #only made it work for http:// links. Any problem with this? - $full_url = "http://$url_parts[host]"; - if(isset($url_parts['port'])){ - $full_url .= ":$url_parts[port]"; - } - if($href{0} != '/'){ #it's a relative link on the domain - $full_url .= dirname($url_parts['path']); - if(substr($full_url, -1) != '/'){ - #if the last character isn't a '/', add it - $full_url .= '/'; - } - } - $full_url .= $href; - } - return $full_url; - } - } - } - return false; - } - } + $res = @fopen($a_url, "r"); + + if (!$res) { + return ""; + } + + $contents = ''; + while (!feof($res)) { + $contents.= fread($res, 8192); + } + fclose($res); + + return ilExternalFeed::_getRSSLocation($contents, $a_url); + } + + /** + * This one is by Keith Devens + *, see http://keithdevens.com/weblog/archive/2002/Jun/03/RSSAuto-DiscoveryPHP + */ + public static function _getRSSLocation($html, $location) + { + if (!$html or !$location) { + return false; + } else { + #search through the HTML, save all tags + # and store each link's attributes in an associative array + preg_match_all('//si', $html, $matches); + $links = $matches[1]; + $final_links = array(); + $link_count = count($links); + for ($n=0; $n<$link_count; $n++) { + $attributes = preg_split('/\s+/s', $links[$n]); + foreach ($attributes as $attribute) { + $att = preg_split('/\s*=\s*/s', $attribute, 2); + if (isset($att[1])) { + $att[1] = preg_replace('/([\'"]?)(.*)\1/', '$2', $att[1]); + $final_link[strtolower($att[0])] = $att[1]; + } + } + $final_links[$n] = $final_link; + } + #now figure out which one points to the RSS file + for ($n=0; $n<$link_count; $n++) { + if (strtolower($final_links[$n]['rel']) == 'alternate') { + if (strtolower($final_links[$n]['type']) == 'application/rss+xml') { + $href = $final_links[$n]['href']; + } + if (!$href and strtolower($final_links[$n]['type']) == 'text/xml') { + #kludge to make the first version of this still work + $href = $final_links[$n]['href']; + } + if ($href) { + if (strstr($href, "http://") !== false) { #if it's absolute + $full_url = $href; + } else { #otherwise, 'absolutize' it + $url_parts = parse_url($location); + #only made it work for http:// links. Any problem with this? + $full_url = "http://$url_parts[host]"; + if (isset($url_parts['port'])) { + $full_url .= ":$url_parts[port]"; + } + if ($href{0} != '/') { #it's a relative link on the domain + $full_url .= dirname($url_parts['path']); + if (substr($full_url, -1) != '/') { + #if the last character isn't a '/', add it + $full_url .= '/'; + } + } + $full_url .= $href; + } + return $full_url; + } + } + } + return false; + } + } } -?> diff --git a/Services/Feeds/classes/class.ilExternalFeedItem.php b/Services/Feeds/classes/class.ilExternalFeedItem.php index fd9977983341452334ae170184c1314c00261575..108df3579f4acb1347dccd7095013651a5d2f781 100644 --- a/Services/Feeds/classes/class.ilExternalFeedItem.php +++ b/Services/Feeds/classes/class.ilExternalFeedItem.php @@ -11,224 +11,219 @@ */ class ilExternalFeedItem { - function __construct() - { - } - - /** - * Set Magpie Item and read it into internal variables - */ - function setMagpieItem($a_item) - { - $this->magpie_item = $a_item; - - //var_dump($a_item); - - // title - $this->setTitle( - $this->secureString($a_item["title"])); - - // link - if (isset($a_item["link_"])) - { - $this->setLink( - ilUtil::secureUrl(ilUtil::secureLink($this->secureString($a_item["link_"])))); - } - else - { - if (isset($a_item["link"])) - { - $this->setLink( - ilUtil::secureUrl(ilUtil::secureLink($this->secureString($a_item["link"])))); - } - } - // summary - if (isset($a_item["atom_content"])) - { - $this->setSummary( - $this->secureString($a_item["atom_content"])); - } - else if (isset($a_item["summary"])) - { - $this->setSummary( - $this->secureString($a_item["summary"])); - } - else if (isset($a_item["description"])) - { - $this->setSummary( - $this->secureString($a_item["description"])); - } - - // date - if (isset($a_item["pubdate"])) - { - $this->setDate( - $this->secureString($a_item["pubdate"])); - } - else if (isset($a_item["updated"])) - { - $this->setDate( - $this->secureString($a_item["updated"])); - } - - // Author - if (isset($a_item["dc"]["creator"])) - { - $this->setAuthor( - $this->secureString($a_item["dc"]["creator"])); - } - - // id - $this->setId(md5($this->getTitle().$this->getSummary())); - - } - - function secureString($a_str) - { - $a_str = ilUtil::secureString($a_str, true, "
            • "); - - // set target to blank for all links - $a_str = preg_replace_callback( - '/]*?href=["\']([^"\']*)["\'][^>]*?>/i', - function($matches) { - return sprintf( - '', - \ilUtil::secureUrl($matches[1]) - ); - }, - $a_str - ); - - return $a_str; - } - - /** - * Get Magpie Item - * - * @return object Magpie Item - */ - function getMagpieItem() - { - return $this->magpie_item; - } - - /** - * Set Title. - * - * @param string $a_title Title - */ - function setTitle($a_title) - { - $this->title = $a_title; - } - - /** - * Get Title. - * - * @return string Title - */ - function getTitle() - { - return $this->title; - } - - /** - * Set Link. - * - * @param string $a_link Link - */ - function setLink($a_link) - { - $this->link = $a_link; - } - - /** - * Get Link. - * - * @return string Link - */ - function getLink() - { - return $this->link; - } - - /** - * Set Summary. - * - * @param string $a_summary Summary - */ - function setSummary($a_summary) - { - $this->summary = $a_summary; - } - - /** - * Get Summary. - * - * @return string Summary - */ - function getSummary() - { - return $this->summary; - } - - /** - * Set Date. - * - * @param string $a_date Date - */ - function setDate($a_date) - { - $this->date = $a_date; - } - - /** - * Get Date. - * - * @return string Date - */ - function getDate() - { - return $this->date; - } - - /** - * Set Id. - * - * @param string $a_id Id - */ - function setId($a_id) - { - $this->id = $a_id; - } - - /** - * Get Id. - * - * @return string Id - */ - function getId() - { - return $this->id; - } - - /** - * Set Author. - * - * @param string $a_author Author - */ - function setAuthor($a_author) - { - $this->author = $a_author; - } - - /** - * Get Author. - * - * @return string Author - */ - function getAuthor() - { - return $this->author; - } + public function __construct() + { + } + + /** + * Set Magpie Item and read it into internal variables + */ + public function setMagpieItem($a_item) + { + $this->magpie_item = $a_item; + + //var_dump($a_item); + + // title + $this->setTitle( + $this->secureString($a_item["title"]) + ); + + // link + if (isset($a_item["link_"])) { + $this->setLink( + ilUtil::secureUrl(ilUtil::secureLink($this->secureString($a_item["link_"]))) + ); + } else { + if (isset($a_item["link"])) { + $this->setLink( + ilUtil::secureUrl(ilUtil::secureLink($this->secureString($a_item["link"]))) + ); + } + } + // summary + if (isset($a_item["atom_content"])) { + $this->setSummary( + $this->secureString($a_item["atom_content"]) + ); + } elseif (isset($a_item["summary"])) { + $this->setSummary( + $this->secureString($a_item["summary"]) + ); + } elseif (isset($a_item["description"])) { + $this->setSummary( + $this->secureString($a_item["description"]) + ); + } + + // date + if (isset($a_item["pubdate"])) { + $this->setDate( + $this->secureString($a_item["pubdate"]) + ); + } elseif (isset($a_item["updated"])) { + $this->setDate( + $this->secureString($a_item["updated"]) + ); + } + + // Author + if (isset($a_item["dc"]["creator"])) { + $this->setAuthor( + $this->secureString($a_item["dc"]["creator"]) + ); + } + + // id + $this->setId(md5($this->getTitle() . $this->getSummary())); + } + + public function secureString($a_str) + { + $a_str = ilUtil::secureString($a_str, true, "
                • "); + + // set target to blank for all links + $a_str = preg_replace_callback( + '/]*?href=["\']([^"\']*)["\'][^>]*?>/i', + function ($matches) { + return sprintf( + '', + \ilUtil::secureUrl($matches[1]) + ); + }, + $a_str + ); + + return $a_str; + } + + /** + * Get Magpie Item + * + * @return object Magpie Item + */ + public function getMagpieItem() + { + return $this->magpie_item; + } + + /** + * Set Title. + * + * @param string $a_title Title + */ + public function setTitle($a_title) + { + $this->title = $a_title; + } + + /** + * Get Title. + * + * @return string Title + */ + public function getTitle() + { + return $this->title; + } + + /** + * Set Link. + * + * @param string $a_link Link + */ + public function setLink($a_link) + { + $this->link = $a_link; + } + + /** + * Get Link. + * + * @return string Link + */ + public function getLink() + { + return $this->link; + } + + /** + * Set Summary. + * + * @param string $a_summary Summary + */ + public function setSummary($a_summary) + { + $this->summary = $a_summary; + } + + /** + * Get Summary. + * + * @return string Summary + */ + public function getSummary() + { + return $this->summary; + } + + /** + * Set Date. + * + * @param string $a_date Date + */ + public function setDate($a_date) + { + $this->date = $a_date; + } + + /** + * Get Date. + * + * @return string Date + */ + public function getDate() + { + return $this->date; + } + + /** + * Set Id. + * + * @param string $a_id Id + */ + public function setId($a_id) + { + $this->id = $a_id; + } + + /** + * Get Id. + * + * @return string Id + */ + public function getId() + { + return $this->id; + } + + /** + * Set Author. + * + * @param string $a_author Author + */ + public function setAuthor($a_author) + { + $this->author = $a_author; + } + + /** + * Get Author. + * + * @return string Author + */ + public function getAuthor() + { + return $this->author; + } } diff --git a/Services/Feeds/classes/class.ilFeedItem.php b/Services/Feeds/classes/class.ilFeedItem.php index 157d05b50a4c2060db483d25ef2cc7dc1ae9f10c..9e28bbe1107ae81f383280099892e02550f4766f 100755 --- a/Services/Feeds/classes/class.ilFeedItem.php +++ b/Services/Feeds/classes/class.ilFeedItem.php @@ -1,24 +1,24 @@ * @version $Id$ */ -class ilFeedItem +class ilFeedItem { - - private $about; - private $title; - private $link; - private $description; - - /** - * Set About. - * - * @param string $a_About - */ - public function setAbout($a_About) - { - $this->about = $a_About; - } - - /** - * Get About. - * - * @return string - */ - public function getAbout() - { - return $this->about; - } - - /** - * Set Title. - * - * @param string $a_Title - */ - public function setTitle($a_Title) - { - $this->title = $a_Title; - } - - /** - * Get Title. - * - * @return string - */ - public function getTitle() - { - return $this->title; - } - - /** - * Set Link. - * - * @param string $a_Link - */ - public function setLink($a_Link) - { - $this->link = $a_Link; - } - - /** - * Get Link. - * - * @return string - */ - public function getLink() - { - return $this->link; - } - - /** - * Set Description. - * - * @param string $a_Description - */ - public function setDescription($a_Description) - { - $this->description = $a_Description; - } - - /** - * Get Description. - * - * @return string - */ - public function getDescription() - { - return $this->description; - } - - /** - * Set Enclosure URL. - * - * @param string $a_enclosureurl Enclosure URL - */ - function setEnclosureUrl($a_enclosureurl) - { - $this->enclosureurl = $a_enclosureurl; - } - - /** - * Get Enclosure URL. - * - * @return string Enclosure URL - */ - function getEnclosureUrl() - { - return $this->enclosureurl; - } - - /** - * Set Enclosure Type. - * - * @param string $a_enclosuretype Enclosure Type - */ - function setEnclosureType($a_enclosuretype) - { - $this->enclosuretype = $a_enclosuretype; - } - - /** - * Get Enclosure Type. - * - * @return string Enclosure Type - */ - function getEnclosureType() - { - return $this->enclosuretype; - } - - /** - * Set Enclosure Length. - * - * @param int $a_enclosurelength Enclosure Length - */ - function setEnclosureLength($a_enclosurelength) - { - $this->enclosurelength = $a_enclosurelength; - } - - /** - * Get Enclosure Length. - * - * @return int Enclosure Length - */ - function getEnclosureLength() - { - return $this->enclosurelength; - } - - /** - * Set Date. - * - * @param string $a_date Date (yyyy-mm-dd hh:mm:ss) - */ - function setDate($a_date) - { - $this->date = $a_date; - } - - /** - * Get Date. - * - * @return string Date - */ - function getDate() - { - return $this->date; - } - + private $about; + private $title; + private $link; + private $description; + + /** + * Set About. + * + * @param string $a_About + */ + public function setAbout($a_About) + { + $this->about = $a_About; + } + + /** + * Get About. + * + * @return string + */ + public function getAbout() + { + return $this->about; + } + + /** + * Set Title. + * + * @param string $a_Title + */ + public function setTitle($a_Title) + { + $this->title = $a_Title; + } + + /** + * Get Title. + * + * @return string + */ + public function getTitle() + { + return $this->title; + } + + /** + * Set Link. + * + * @param string $a_Link + */ + public function setLink($a_Link) + { + $this->link = $a_Link; + } + + /** + * Get Link. + * + * @return string + */ + public function getLink() + { + return $this->link; + } + + /** + * Set Description. + * + * @param string $a_Description + */ + public function setDescription($a_Description) + { + $this->description = $a_Description; + } + + /** + * Get Description. + * + * @return string + */ + public function getDescription() + { + return $this->description; + } + + /** + * Set Enclosure URL. + * + * @param string $a_enclosureurl Enclosure URL + */ + public function setEnclosureUrl($a_enclosureurl) + { + $this->enclosureurl = $a_enclosureurl; + } + + /** + * Get Enclosure URL. + * + * @return string Enclosure URL + */ + public function getEnclosureUrl() + { + return $this->enclosureurl; + } + + /** + * Set Enclosure Type. + * + * @param string $a_enclosuretype Enclosure Type + */ + public function setEnclosureType($a_enclosuretype) + { + $this->enclosuretype = $a_enclosuretype; + } + + /** + * Get Enclosure Type. + * + * @return string Enclosure Type + */ + public function getEnclosureType() + { + return $this->enclosuretype; + } + + /** + * Set Enclosure Length. + * + * @param int $a_enclosurelength Enclosure Length + */ + public function setEnclosureLength($a_enclosurelength) + { + $this->enclosurelength = $a_enclosurelength; + } + + /** + * Get Enclosure Length. + * + * @return int Enclosure Length + */ + public function getEnclosureLength() + { + return $this->enclosurelength; + } + + /** + * Set Date. + * + * @param string $a_date Date (yyyy-mm-dd hh:mm:ss) + */ + public function setDate($a_date) + { + $this->date = $a_date; + } + + /** + * Get Date. + * + * @return string Date + */ + public function getDate() + { + return $this->date; + } } diff --git a/Services/Feeds/classes/class.ilFeedWriter.php b/Services/Feeds/classes/class.ilFeedWriter.php index a72000521b460a4e4154cea5bf2934765c044153..919eceba9663df67269384be7be11e18dfec0650 100644 --- a/Services/Feeds/classes/class.ilFeedWriter.php +++ b/Services/Feeds/classes/class.ilFeedWriter.php @@ -24,245 +24,230 @@ include_once("Services/Feeds/classes/class.ilFeedItem.php"); */ class ilFeedWriter { - /** - * @var ilTree - */ - protected $tree; - - /** - * @var ilLanguage - */ - protected $lng; - - var $encoding = "UTF-8"; - var $ch_about = ""; - var $ch_title = ""; - var $ch_link = ""; - var $ch_description = ""; - var $items = array(); - - /** - * ilFeedWriter constructor. - */ - function __construct() - { - global $DIC; - - $this->tree = $DIC->repositoryTree(); - $this->lng = $DIC->language(); - - } - - /** - * Set feed encoding. Default is UTF-8. - */ - function setEncoding($a_enc) - { - $this->encoding = $a_enc; - } - - function getEncoding() - { - return $this->encoding; - } - - /** - * Unique URI that defines the channel - */ - function setChannelAbout($a_ab) - { - $this->ch_about = $a_ab; - } - - function getChannelAbout() - { - return $this->ch_about; - } - - /** - * Channel Title - */ - function setChannelTitle($a_title) - { - $this->ch_title = $a_title; - } - - function getChannelTitle() - { - return $this->ch_title; - } - - /** - * Channel Link - * URL to which an HTML rendering of the channel title will link - */ - function setChannelLink($a_link) - { - $this->ch_link = $a_link; - } - - function getChannelLink() - { - return $this->ch_link; - } - - /** - * Channel Description - */ - function setChannelDescription($a_desc) - { - $this->ch_desc = $a_desc; - } - - function getChannelDescription() - { - return $this->ch_desc; - } - - /** - * Add Item - * Item is an object of type ilFeedItem - */ - function addItem($a_item) - { - $this->items[] = $a_item; - } - - function getItems() - { - return $this->items; - } - - function prepareStr($a_str) - { - $a_str = str_replace("&", "&", $a_str); - $a_str = str_replace("<", "<", $a_str); - $a_str = str_replace(">", ">", $a_str); - return $a_str; - } - - /** - * get feed xml - */ - function getFeed() - { - include_once("./Services/UICore/classes/class.ilTemplate.php"); - $this->tpl = new ilTemplate("tpl.rss_2_0.xml", true, true, "Services/Feeds"); - - $this->tpl->setVariable("XML", "xml"); - $this->tpl->setVariable("CONTENT_ENCODING", $this->getEncoding()); - $this->tpl->setVariable("CHANNEL_ABOUT", $this->getChannelAbout()); - $this->tpl->setVariable("CHANNEL_TITLE", $this->getChannelTitle()); - $this->tpl->setVariable("CHANNEL_LINK", $this->getChannelLink()); - $this->tpl->setVariable("CHANNEL_DESCRIPTION", $this->getChannelDescription()); - - foreach($this->items as $item) - { - $this->tpl->setCurrentBlock("rdf_seq"); - $this->tpl->setVariable("RESOURCE", $item->getAbout()); - $this->tpl->parseCurrentBlock(); - - // Date - if ($item->getDate() != "") - { - $this->tpl->setCurrentBlock("date"); - $d = $item->getDate(); - $yyyy = substr($d, 0, 4); - $mm = substr($d, 5, 2); - $dd = substr($d, 8, 2); - $h = substr($d, 11, 2); - $m = substr($d, 14, 2); - $s = substr($d, 17, 2); - $this->tpl->setVariable("ITEM_DATE", - date("r", mktime($h, $m, $s, $mm, $dd, $yyyy))); - $this->tpl->parseCurrentBlock(); - } - - // Enclosure - if ($item->getEnclosureUrl() != "") - { - $this->tpl->setCurrentBlock("enclosure"); - $this->tpl->setVariable("ENC_URL", $item->getEnclosureUrl()); - $this->tpl->setVariable("ENC_LENGTH", $item->getEnclosureLength()); - $this->tpl->setVariable("ENC_TYPE", $item->getEnclosureType()); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setCurrentBlock("item"); - $this->tpl->setVariable("ITEM_ABOUT", $item->getAbout()); - $this->tpl->setVariable("ITEM_TITLE", $item->getTitle()); - $this->tpl->setVariable("ITEM_DESCRIPTION", $item->getDescription()); - $this->tpl->setVariable("ITEM_LINK", $item->getLink()); - $this->tpl->parseCurrentBlock(); - - } - - $this->tpl->parseCurrentBlock(); - return $this->tpl->get(); - } - - function showFeed() - { - header("Content-Type: text/xml; charset=UTF-8;"); - echo $this->getFeed(); - } - - function getContextPath($a_ref_id) - { - $tree = $this->tree; - $lng = $this->lng; - - $items = array(); - - if ($a_ref_id > 0) - { - $path = $tree->getPathFull($a_ref_id); - - // we want to show the full path, from the major container to the item - // (folders are not! treated as containers here), at least one parent item - $r_path = array_reverse($path); - $first = ""; - $omit = array(); - $do_omit = false; - foreach ($r_path as $key => $row) - { - if ($first == "") - { - if (in_array($row["type"], array("root", "cat", "grp", "crs")) ) - { - $first = $row["child"]; - } - } - $omit[$row["child"]] = $do_omit; - } - - $add_it = false; - foreach ($path as $key => $row) - { - if ($first == $row["child"]) - { - $add_it = true; - } - - if ($add_it && !$omit[$row["child"]] && - (($row["child"] != $a_ref_id))) - { - if ($row["title"] == "ILIAS" && $row["type"] == "root") - { - $row["title"] = $lng->txt("repository"); - } - $items[] = $row["title"]; - } - } - } - - if (count($items) > 0) - { - return "[".implode(" > ", $items)."]"; - } - return ""; - } - - + /** + * @var ilTree + */ + protected $tree; + + /** + * @var ilLanguage + */ + protected $lng; + + public $encoding = "UTF-8"; + public $ch_about = ""; + public $ch_title = ""; + public $ch_link = ""; + public $ch_description = ""; + public $items = array(); + + /** + * ilFeedWriter constructor. + */ + public function __construct() + { + global $DIC; + + $this->tree = $DIC->repositoryTree(); + $this->lng = $DIC->language(); + } + + /** + * Set feed encoding. Default is UTF-8. + */ + public function setEncoding($a_enc) + { + $this->encoding = $a_enc; + } + + public function getEncoding() + { + return $this->encoding; + } + + /** + * Unique URI that defines the channel + */ + public function setChannelAbout($a_ab) + { + $this->ch_about = $a_ab; + } + + public function getChannelAbout() + { + return $this->ch_about; + } + + /** + * Channel Title + */ + public function setChannelTitle($a_title) + { + $this->ch_title = $a_title; + } + + public function getChannelTitle() + { + return $this->ch_title; + } + + /** + * Channel Link + * URL to which an HTML rendering of the channel title will link + */ + public function setChannelLink($a_link) + { + $this->ch_link = $a_link; + } + + public function getChannelLink() + { + return $this->ch_link; + } + + /** + * Channel Description + */ + public function setChannelDescription($a_desc) + { + $this->ch_desc = $a_desc; + } + + public function getChannelDescription() + { + return $this->ch_desc; + } + + /** + * Add Item + * Item is an object of type ilFeedItem + */ + public function addItem($a_item) + { + $this->items[] = $a_item; + } + + public function getItems() + { + return $this->items; + } + + public function prepareStr($a_str) + { + $a_str = str_replace("&", "&", $a_str); + $a_str = str_replace("<", "<", $a_str); + $a_str = str_replace(">", ">", $a_str); + return $a_str; + } + + /** + * get feed xml + */ + public function getFeed() + { + include_once("./Services/UICore/classes/class.ilTemplate.php"); + $this->tpl = new ilTemplate("tpl.rss_2_0.xml", true, true, "Services/Feeds"); + + $this->tpl->setVariable("XML", "xml"); + $this->tpl->setVariable("CONTENT_ENCODING", $this->getEncoding()); + $this->tpl->setVariable("CHANNEL_ABOUT", $this->getChannelAbout()); + $this->tpl->setVariable("CHANNEL_TITLE", $this->getChannelTitle()); + $this->tpl->setVariable("CHANNEL_LINK", $this->getChannelLink()); + $this->tpl->setVariable("CHANNEL_DESCRIPTION", $this->getChannelDescription()); + + foreach ($this->items as $item) { + $this->tpl->setCurrentBlock("rdf_seq"); + $this->tpl->setVariable("RESOURCE", $item->getAbout()); + $this->tpl->parseCurrentBlock(); + + // Date + if ($item->getDate() != "") { + $this->tpl->setCurrentBlock("date"); + $d = $item->getDate(); + $yyyy = substr($d, 0, 4); + $mm = substr($d, 5, 2); + $dd = substr($d, 8, 2); + $h = substr($d, 11, 2); + $m = substr($d, 14, 2); + $s = substr($d, 17, 2); + $this->tpl->setVariable( + "ITEM_DATE", + date("r", mktime($h, $m, $s, $mm, $dd, $yyyy)) + ); + $this->tpl->parseCurrentBlock(); + } + + // Enclosure + if ($item->getEnclosureUrl() != "") { + $this->tpl->setCurrentBlock("enclosure"); + $this->tpl->setVariable("ENC_URL", $item->getEnclosureUrl()); + $this->tpl->setVariable("ENC_LENGTH", $item->getEnclosureLength()); + $this->tpl->setVariable("ENC_TYPE", $item->getEnclosureType()); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setCurrentBlock("item"); + $this->tpl->setVariable("ITEM_ABOUT", $item->getAbout()); + $this->tpl->setVariable("ITEM_TITLE", $item->getTitle()); + $this->tpl->setVariable("ITEM_DESCRIPTION", $item->getDescription()); + $this->tpl->setVariable("ITEM_LINK", $item->getLink()); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->parseCurrentBlock(); + return $this->tpl->get(); + } + + public function showFeed() + { + header("Content-Type: text/xml; charset=UTF-8;"); + echo $this->getFeed(); + } + + public function getContextPath($a_ref_id) + { + $tree = $this->tree; + $lng = $this->lng; + + $items = array(); + + if ($a_ref_id > 0) { + $path = $tree->getPathFull($a_ref_id); + + // we want to show the full path, from the major container to the item + // (folders are not! treated as containers here), at least one parent item + $r_path = array_reverse($path); + $first = ""; + $omit = array(); + $do_omit = false; + foreach ($r_path as $key => $row) { + if ($first == "") { + if (in_array($row["type"], array("root", "cat", "grp", "crs"))) { + $first = $row["child"]; + } + } + $omit[$row["child"]] = $do_omit; + } + + $add_it = false; + foreach ($path as $key => $row) { + if ($first == $row["child"]) { + $add_it = true; + } + + if ($add_it && !$omit[$row["child"]] && + (($row["child"] != $a_ref_id))) { + if ($row["title"] == "ILIAS" && $row["type"] == "root") { + $row["title"] = $lng->txt("repository"); + } + $items[] = $row["title"]; + } + } + } + + if (count($items) > 0) { + return "[" . implode(" > ", $items) . "]"; + } + return ""; + } } -?> diff --git a/Services/Feeds/classes/class.ilObjectFeedWriter.php b/Services/Feeds/classes/class.ilObjectFeedWriter.php index e9f2153327efe0c4f31ac0ead52903f3e4cacd3b..d3f8323889e5d19fd9c57a8bfb64dd81861cb2da 100755 --- a/Services/Feeds/classes/class.ilObjectFeedWriter.php +++ b/Services/Feeds/classes/class.ilObjectFeedWriter.php @@ -18,211 +18,185 @@ include_once("./Services/Feeds/classes/class.ilFeedWriter.php"); */ class ilObjectFeedWriter extends ilFeedWriter { - /** - * @var ilSetting - */ - protected $settings; - - /** - * @var ilLanguage - */ - protected $lng; - - function __construct($a_ref_id, $a_userid = false, $a_purpose = false) - { - global $DIC; - - $this->settings = $DIC->settings(); - $this->lng = $DIC->language(); - $ilSetting = $DIC->settings(); - $lng = $DIC->language(); - - parent::__construct(); - - if ($a_ref_id <= 0) - { - return; - } - - include_once("./Services/Block/classes/class.ilBlockSetting.php"); - $news_set = new ilSetting("news"); - if (!$news_set->get("enable_rss_for_internal")) - { - return; - } - $obj_id = ilObject::_lookupObjId($a_ref_id); - $obj_type = ilObject::_lookupType($obj_id); - $obj_title = ilObject::_lookupTitle($obj_id); - - if (!ilBlockSetting::_lookup("news", "public_feed", 0, $obj_id)) - { - return; - } - - // path - $loc = $this->getContextPath($a_ref_id); - - if ($ilSetting->get('short_inst_name') != "") - { - $this->setChannelTitle($ilSetting->get('short_inst_name')." - ". - $this->prepareStr($loc." ".$obj_title)); - } - else - { - $this->setChannelTitle("ILIAS"." - ". - $this->prepareStr($loc." ".$obj_title.($a_purpose ? " - ".$a_purpose : ""))); - } - $this->setChannelAbout(ILIAS_HTTP_PATH); - $this->setChannelLink(ILIAS_HTTP_PATH); - // not nice, to do: general solution - if ($obj_type == "mcst") - { - include_once("./Modules/MediaCast/classes/class.ilObjMediaCastAccess.php"); - - if (!ilObjMediaCastAccess::_lookupOnline($obj_id)) - { - $lng->loadLanguageModule("mcst"); - - $feed_item = new ilFeedItem(); - $feed_item->setTitle($lng->txt("mcst_media_cast_not_online")); - $feed_item->setDescription($lng->txt("mcst_media_cast_not_online_text")); - $feed_item->setLink(ILIAS_HTTP_PATH."/goto.php?client_id=".CLIENT_ID. - "&target=".$item["context_obj_type"]); - $this->addItem($feed_item); - return; - } - } - - - $rss_period = ilNewsItem::_lookupRSSPeriod(); - - ilNewsItem::setPrivateFeedId($a_userid); - $news_item = new ilNewsItem(); - $news_item->setContextObjId($obj_id); - $news_item->setContextObjType($obj_type); - $items = $news_item->getNewsForRefId($a_ref_id, true, false, $rss_period, true); - - if ($a_purpose) { - include_once("./Services/MediaObjects/classes/class.ilMediaItem.php"); - } - - $i = 0; - foreach($items as $item) - { - $i++; - - if ($a_purpose != false && $obj_type == "mcst") - { - $mob = ilMediaItem::_getMediaItemsOfMObId($item["mob_id"], $a_purpose); - - if ($mob == false) - { - continue; - } - - } - - $obj_title = ilObject::_lookupTitle($item["context_obj_id"]); - - $feed_item = new ilFeedItem(); - - $title = ilNewsItem::determineNewsTitle - ($item["context_obj_type"], $item["title"], $item["content_is_lang_var"], - $item["agg_ref_id"], $item["aggregation"]); - - $loc = ""; - - if ($news_set->get("rss_title_format") == "news_obj") - { - $sep = (trim($this->prepareStr($loc)) == "") - ? "" - : " "; - $feed_item->setTitle($this->prepareStr($title)." (".$this->prepareStr($loc).$sep.$this->prepareStr($obj_title). - ")"); - } - else - { - $feed_item->setTitle($this->prepareStr($loc)." ".$this->prepareStr($obj_title). - ": ".$this->prepareStr($title)); - } - $feed_item->setDescription($this->prepareStr(nl2br( - ilNewsItem::determineNewsContent($item["context_obj_type"], $item["content"], $item["content_text_is_lang_var"])))); - - // lm hack, not nice - if (in_array($item["context_obj_type"], array("lm")) && $item["context_sub_obj_type"] == "pg" - && $item["context_sub_obj_id"] > 0) - { - $feed_item->setLink(ILIAS_HTTP_PATH."/goto.php?client_id=".CLIENT_ID. - "&target=pg_".$item["context_sub_obj_id"]."_".$item["ref_id"]); - } - else if ($item["context_obj_type"] == "wiki" && $item["context_sub_obj_type"] == "wpg" - && $item["context_sub_obj_id"] > 0) - { - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - include_once("./Modules/Wiki/classes/class.ilWikiUtil.php"); - $wptitle = ilWikiUtil::makeUrlTitle(ilWikiPage::lookupTitle($item["context_sub_obj_id"])); - $feed_item->setLink(ILIAS_HTTP_PATH."/goto.php?client_id=".CLIENT_ID. - "&target=".$item["context_obj_type"]."_".$item["ref_id"]."_".$wptitle); - } - else if (in_array($item["context_obj_type"], array("frm")) && $item["context_sub_obj_type"] == "pos" - && $item["context_sub_obj_id"] > 0) - { - // frm hack, not nice - include_once("./Modules/Forum/classes/class.ilObjForumAccess.php"); - $thread_id = ilObjForumAccess::_getThreadForPosting($item["context_sub_obj_id"]); - if ($thread_id > 0) - { - $feed_item->setLink(ILIAS_HTTP_PATH."/goto.php?client_id=".CLIENT_ID. - "&target=".$item["context_obj_type"]."_".$item["ref_id"]."_".$thread_id."_".$item["context_sub_obj_id"]); - } - else - { - $feed_item->setLink(ILIAS_HTTP_PATH."/goto.php?client_id=".CLIENT_ID. - "&target=".$item["context_obj_type"]."_".$item["ref_id"]); - } - } - else - { - $feed_item->setLink(ILIAS_HTTP_PATH."/goto.php?client_id=".CLIENT_ID. - "&target=".$item["context_obj_type"]."_".$item["ref_id"]); -//echo "
                  ".ILIAS_HTTP_PATH."/goto.php?client_id=".CLIENT_ID. + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var ilLanguage + */ + protected $lng; + + public function __construct($a_ref_id, $a_userid = false, $a_purpose = false) + { + global $DIC; + + $this->settings = $DIC->settings(); + $this->lng = $DIC->language(); + $ilSetting = $DIC->settings(); + $lng = $DIC->language(); + + parent::__construct(); + + if ($a_ref_id <= 0) { + return; + } + + include_once("./Services/Block/classes/class.ilBlockSetting.php"); + $news_set = new ilSetting("news"); + if (!$news_set->get("enable_rss_for_internal")) { + return; + } + $obj_id = ilObject::_lookupObjId($a_ref_id); + $obj_type = ilObject::_lookupType($obj_id); + $obj_title = ilObject::_lookupTitle($obj_id); + + if (!ilBlockSetting::_lookup("news", "public_feed", 0, $obj_id)) { + return; + } + + // path + $loc = $this->getContextPath($a_ref_id); + + if ($ilSetting->get('short_inst_name') != "") { + $this->setChannelTitle($ilSetting->get('short_inst_name') . " - " . + $this->prepareStr($loc . " " . $obj_title)); + } else { + $this->setChannelTitle("ILIAS" . " - " . + $this->prepareStr($loc . " " . $obj_title . ($a_purpose ? " - " . $a_purpose : ""))); + } + $this->setChannelAbout(ILIAS_HTTP_PATH); + $this->setChannelLink(ILIAS_HTTP_PATH); + // not nice, to do: general solution + if ($obj_type == "mcst") { + include_once("./Modules/MediaCast/classes/class.ilObjMediaCastAccess.php"); + + if (!ilObjMediaCastAccess::_lookupOnline($obj_id)) { + $lng->loadLanguageModule("mcst"); + + $feed_item = new ilFeedItem(); + $feed_item->setTitle($lng->txt("mcst_media_cast_not_online")); + $feed_item->setDescription($lng->txt("mcst_media_cast_not_online_text")); + $feed_item->setLink(ILIAS_HTTP_PATH . "/goto.php?client_id=" . CLIENT_ID . + "&target=" . $item["context_obj_type"]); + $this->addItem($feed_item); + return; + } + } + + + $rss_period = ilNewsItem::_lookupRSSPeriod(); + + ilNewsItem::setPrivateFeedId($a_userid); + $news_item = new ilNewsItem(); + $news_item->setContextObjId($obj_id); + $news_item->setContextObjType($obj_type); + $items = $news_item->getNewsForRefId($a_ref_id, true, false, $rss_period, true); + + if ($a_purpose) { + include_once("./Services/MediaObjects/classes/class.ilMediaItem.php"); + } + + $i = 0; + foreach ($items as $item) { + $i++; + + if ($a_purpose != false && $obj_type == "mcst") { + $mob = ilMediaItem::_getMediaItemsOfMObId($item["mob_id"], $a_purpose); + + if ($mob == false) { + continue; + } + } + + $obj_title = ilObject::_lookupTitle($item["context_obj_id"]); + + $feed_item = new ilFeedItem(); + + $title = ilNewsItem::determineNewsTitle( + $item["context_obj_type"], + $item["title"], + $item["content_is_lang_var"], + $item["agg_ref_id"], + $item["aggregation"] + ); + + $loc = ""; + + if ($news_set->get("rss_title_format") == "news_obj") { + $sep = (trim($this->prepareStr($loc)) == "") + ? "" + : " "; + $feed_item->setTitle($this->prepareStr($title) . " (" . $this->prepareStr($loc) . $sep . $this->prepareStr($obj_title) . + ")"); + } else { + $feed_item->setTitle($this->prepareStr($loc) . " " . $this->prepareStr($obj_title) . + ": " . $this->prepareStr($title)); + } + $feed_item->setDescription($this->prepareStr(nl2br( + ilNewsItem::determineNewsContent($item["context_obj_type"], $item["content"], $item["content_text_is_lang_var"]) + ))); + + // lm hack, not nice + if (in_array($item["context_obj_type"], array("lm")) && $item["context_sub_obj_type"] == "pg" + && $item["context_sub_obj_id"] > 0) { + $feed_item->setLink(ILIAS_HTTP_PATH . "/goto.php?client_id=" . CLIENT_ID . + "&target=pg_" . $item["context_sub_obj_id"] . "_" . $item["ref_id"]); + } elseif ($item["context_obj_type"] == "wiki" && $item["context_sub_obj_type"] == "wpg" + && $item["context_sub_obj_id"] > 0) { + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + include_once("./Modules/Wiki/classes/class.ilWikiUtil.php"); + $wptitle = ilWikiUtil::makeUrlTitle(ilWikiPage::lookupTitle($item["context_sub_obj_id"])); + $feed_item->setLink(ILIAS_HTTP_PATH . "/goto.php?client_id=" . CLIENT_ID . + "&target=" . $item["context_obj_type"] . "_" . $item["ref_id"] . "_" . $wptitle); + } elseif (in_array($item["context_obj_type"], array("frm")) && $item["context_sub_obj_type"] == "pos" + && $item["context_sub_obj_id"] > 0) { + // frm hack, not nice + include_once("./Modules/Forum/classes/class.ilObjForumAccess.php"); + $thread_id = ilObjForumAccess::_getThreadForPosting($item["context_sub_obj_id"]); + if ($thread_id > 0) { + $feed_item->setLink(ILIAS_HTTP_PATH . "/goto.php?client_id=" . CLIENT_ID . + "&target=" . $item["context_obj_type"] . "_" . $item["ref_id"] . "_" . $thread_id . "_" . $item["context_sub_obj_id"]); + } else { + $feed_item->setLink(ILIAS_HTTP_PATH . "/goto.php?client_id=" . CLIENT_ID . + "&target=" . $item["context_obj_type"] . "_" . $item["ref_id"]); + } + } else { + $feed_item->setLink(ILIAS_HTTP_PATH . "/goto.php?client_id=" . CLIENT_ID . + "&target=" . $item["context_obj_type"] . "_" . $item["ref_id"]); + //echo "
                  ".ILIAS_HTTP_PATH."/goto.php?client_id=".CLIENT_ID. // "&target=".$item["context_obj_type"]."_".$item["ref_id"]; - } - - $feed_item->setAbout($feed_item->getLink()."&il_about_feed=".$item["id"]); - $feed_item->setDate($item["creation_date"]); - - // Enclosure - if ($item["content_type"] == NEWS_AUDIO && - $item["mob_id"] > 0 && ilObject::_exists($item["mob_id"])) - { - $go_on = true; - if ($obj_type == "mcst") - { - include_once("./Modules/MediaCast/classes/class.ilObjMediaCastAccess.php"); - - if (!ilObjMediaCastAccess::_lookupPublicFiles($obj_id)) - { - $go_on = false; - } - } - - if ($go_on) - { - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $url = ilObjMediaObject::_lookupItemPath($item["mob_id"], true, true, $mob["purpose"]); - $file = ilObjMediaObject::_lookupItemPath($item["mob_id"], false, false, $mob["purpose"]); - if (is_file($file)) - { - $size = filesize($file); - } - $feed_item->setEnclosureUrl($url); - $feed_item->setEnclosureType((isset($mob["format"]))?$mob["format"]:"audio/mpeg"); - $feed_item->setEnclosureLength($size); - } - } - $this->addItem($feed_item); - } - } + } + + $feed_item->setAbout($feed_item->getLink() . "&il_about_feed=" . $item["id"]); + $feed_item->setDate($item["creation_date"]); + + // Enclosure + if ($item["content_type"] == NEWS_AUDIO && + $item["mob_id"] > 0 && ilObject::_exists($item["mob_id"])) { + $go_on = true; + if ($obj_type == "mcst") { + include_once("./Modules/MediaCast/classes/class.ilObjMediaCastAccess.php"); + + if (!ilObjMediaCastAccess::_lookupPublicFiles($obj_id)) { + $go_on = false; + } + } + + if ($go_on) { + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $url = ilObjMediaObject::_lookupItemPath($item["mob_id"], true, true, $mob["purpose"]); + $file = ilObjMediaObject::_lookupItemPath($item["mob_id"], false, false, $mob["purpose"]); + if (is_file($file)) { + $size = filesize($file); + } + $feed_item->setEnclosureUrl($url); + $feed_item->setEnclosureType((isset($mob["format"]))?$mob["format"]:"audio/mpeg"); + $feed_item->setEnclosureLength($size); + } + } + $this->addItem($feed_item); + } + } } -?> diff --git a/Services/Feeds/classes/class.ilPDExternalFeedBlock.php b/Services/Feeds/classes/class.ilPDExternalFeedBlock.php index 7a19944c275c06a3e7fb055e9d70d440a5faf918..6882e3504542b4501f28f75eed70c0f59f1fa026 100755 --- a/Services/Feeds/classes/class.ilPDExternalFeedBlock.php +++ b/Services/Feeds/classes/class.ilPDExternalFeedBlock.php @@ -1,24 +1,24 @@ diff --git a/Services/Feeds/classes/class.ilPDExternalFeedBlockGUI.php b/Services/Feeds/classes/class.ilPDExternalFeedBlockGUI.php index be4784393ad2137455b45afaacec634eb5c95b94..37cedf8474f92238b6e77771370c033b5dd776a9 100755 --- a/Services/Feeds/classes/class.ilPDExternalFeedBlockGUI.php +++ b/Services/Feeds/classes/class.ilPDExternalFeedBlockGUI.php @@ -1,24 +1,24 @@ ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - $this->access = $DIC->access(); - $this->settings = $DIC->settings(); - $lng = $DIC->language(); - - parent::__construct(); - - $lng->loadLanguageModule("feed"); - - $this->setLimit(5); - $this->setRowTemplate("tpl.block_external_feed_row.html", "Services/Feeds"); - } - - /** - * @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() - { - global $DIC; - - $ilCtrl = $DIC->ctrl(); - - switch($ilCtrl->getCmd()) - { - case "create": - case "edit": - case "saveFeedBlock": - case "updateFeedBlock": - case "editFeedBlock": - case "showFeedItem": - case "confirmDeleteFeedBlock": - return IL_SCREEN_CENTER; - break; - - default: - return IL_SCREEN_SIDE; - break; - } - } - - /** - * Do most of the initialisation. - */ - function setBlock($a_block) - { - $ilCtrl = $this->ctrl; - - // init block - $this->feed_block = $a_block; - $this->setTitle($this->feed_block->getTitle()); - $this->setBlockId($this->feed_block->getId()); - - // get feed object - include_once("./Services/Feeds/classes/class.ilExternalFeed.php"); - $this->feed = new ilExternalFeed(); - $this->feed->setUrl($this->feed_block->getFeedUrl()); - - // init details - $this->setAvailableDetailLevels(2); - - $ilCtrl->setParameter($this, "block_id", $this->feed_block->getId()); - } - - /** - * execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - - $next_class = $ilCtrl->getNextClass(); - $cmd = $ilCtrl->getCmd("getHTML"); - - switch ($next_class) - { - default: - return $this->$cmd(); - } - } - - /** - * Fill data section - */ - function fillDataSection() - { - if ($this->getDynamic()) - { - $this->setDataSection($this->getDynamicReload()); - } - else if ($this->getCurrentDetailLevel() > 1 && count($this->getData()) > 0) - { - parent::fillDataSection(); - } - else - { - $this->setDataSection($this->getOverview()); - } - } - - /** - * Get block HTML code. - */ - function getHTML() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilUser = $this->user; - $ilSetting = $this->settings; - - - if ($ilSetting->get("block_limit_pdfeed") == 0) - { - return ""; - } - - if ($this->getCurrentDetailLevel() == 0) - { - return ""; - } - - - // if no dynamic reload - if (!$this->getDynamic()) - { - $this->feed->fetch(); - $this->setData($this->feed->getItems()); - } - - $ilCtrl->setParameter($this, "external_feed_block_id", - $this->getBlockId()); - $this->addBlockCommand( - $ilCtrl->getLinkTarget($this, - "editFeedBlock"), - $lng->txt("edit")); - $this->addBlockCommand( - $ilCtrl->getLinkTarget($this, - "confirmDeleteFeedBlock"), - $lng->txt("delete")); - $ilCtrl->setParameter($this, "external_feed_block_id", ""); - - // JS enabler - $add = ""; - if ($_SESSION["il_feed_js"] == "n" || - ($ilUser->getPref("il_feed_js") == "n" && $_SESSION["il_feed_js"] != "y")) - { - $add = $this->getJSEnabler(); - } - - return parent::getHTML().$add; - } - - function getDynamic() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - if ($ilCtrl->getCmdClass() != "ilcolumngui" && $ilCtrl->getCmd() != "enableJS") - { - $sess_feed_js = ""; - if (isset($_SESSION["il_feed_js"])) - { - $sess_feed_js = $_SESSION["il_feed_js"]; - } - if ($sess_feed_js != "n" && - ($ilUser->getPref("il_feed_js") != "n" || $sess_feed_js == "y")) - { - // do not get feed dynamically, if cache hit is given. - if (!$this->feed->checkCacheHit()) - { - return true; - } - } - } - - return false; - } - - function getDynamicReload() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $ilCtrl->setParameterByClass("ilcolumngui", "block_id", - "block_pdfeed_".$this->getBlockId()); - - $rel_tpl = new ilTemplate("tpl.dynamic_reload.html", true, true, "Services/Feeds"); - $rel_tpl->setVariable("TXT_LOADING", $lng->txt("feed_loading_feed")); - $rel_tpl->setVariable("BLOCK_ID", "block_pdfeed_".$this->getBlockId()); - $rel_tpl->setVariable("TARGET", - $ilCtrl->getLinkTargetByClass("ilcolumngui", "updateBlock", "", true)); - - // no JS - $rel_tpl->setVariable("TXT_FEED_CLICK_HERE", $lng->txt("feed_no_js_click_here")); - $rel_tpl->setVariable("TARGET_NO_JS", - $ilCtrl->getLinkTargetByClass("ilpdexternalfeedblockgui", "disableJS")); - - return $rel_tpl->get(); - } - - function getJSEnabler() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameterByClass("ilcolumngui", "block_id", - "block_pdfeed_".$this->getBlockId()); - - $rel_tpl = new ilTemplate("tpl.js_enabler.html", true, true, "Services/Feeds"); - $rel_tpl->setVariable("BLOCK_ID", "block_pdfeed_".$this->getBlockId()); - $rel_tpl->setVariable("TARGET", - $ilCtrl->getLinkTargetByClass("ilpdexternalfeedblockgui", "enableJS", true)); - - return $rel_tpl->get(); - } - - - function disableJS() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - $_SESSION["il_feed_js"] = "n"; - $ilUser->writePref("il_feed_js", "n"); - $ilCtrl->redirectByClass("ilpersonaldesktopgui", "show"); - } - - function enableJS() - { - $ilUser = $this->user; - - $_SESSION["il_feed_js"] = "y"; - $ilUser->writePref("il_feed_js", "y"); - echo $this->getHTML(); - exit; - } - - /** - * Fill feed item row - */ - function fillRow($item) - { - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameter($this, "feed_item_id", $item->getId()); - $this->tpl->setVariable("VAL_TITLE", $item->getTitle()); - $this->tpl->setVariable("HREF_SHOW", - $ilCtrl->getLinkTarget($this, "showFeedItem")); - $ilCtrl->setParameter($this, "feed_item_id", ""); - } - - /** - * Get overview. - */ - function getOverview() - { - $lng = $this->lng; - - $this->setEnableNumInfo(false); - return '
                  '.((int) count($this->getData()))." ".$lng->txt("feed_feed_items")."
                  "; - } - - /** - * Show Feed Item - */ - function showFeedItem() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("./Services/News/classes/class.ilNewsItem.php"); - - $this->feed->fetch(); - foreach($this->feed->getItems() as $item) - { - if ($item->getId() == $_GET["feed_item_id"]) - { - $c_item = $item; - break; - } - } - - $tpl = new ilTemplate("tpl.show_feed_item.html", true, true, "Services/Feeds"); - - if (is_object($c_item)) - { - if (trim($c_item->getSummary()) != "") // summary - { - $tpl->setCurrentBlock("content"); - $tpl->setVariable("VAL_CONTENT", $c_item->getSummary()); - $tpl->parseCurrentBlock(); - } - if (trim($c_item->getDate()) != "" || trim($c_item->getAuthor()) != "") // date - { - $tpl->setCurrentBlock("date_author"); - if (trim($c_item->getAuthor()) != "") - { - $tpl->setVariable("VAL_AUTHOR", $c_item->getAuthor()." - "); - } - $tpl->setVariable("VAL_DATE", $c_item->getDate()); - $tpl->parseCurrentBlock(); - } - - if (trim($c_item->getLink()) != "") // link - { - $tpl->setCurrentBlock("plink"); - $tpl->setVariable("HREF_LINK", $c_item->getLink()); - $tpl->setVariable("TXT_LINK", $lng->txt("feed_open_source_page")); - $tpl->parseCurrentBlock(); - } - $tpl->setVariable("VAL_TITLE", $c_item->getTitle()); // title - } - - include_once("./Services/PersonalDesktop/classes/class.ilPDContentBlockGUI.php"); - $content_block = new ilPDContentBlockGUI(); - $content_block->setContent($tpl->get()); - $content_block->setTitle($this->getTitle()); - $content_block->setImage(ilUtil::getImagePath("icon_feed.svg")); - $content_block->addHeaderCommand($ilCtrl->getParentReturn($this), - $lng->txt("selected_items_back")); - - return $content_block->getHTML(); - } - - /** - * Create Form for Block. - */ - function create() - { - return $this->createFeedBlock(); - } - - /** - * FORM FeedBlock: Init form. (We need to overwrite, because Generator - * does not know FeedUrl Inputs yet. - * - * @param int $a_mode Form Edit Mode (IL_FORM_EDIT | IL_FORM_CREATE) - */ - public function initFormFeedBlock($a_mode) - { - $lng = $this->lng; - - $lng->loadLanguageModule("block"); - - require_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - - $this->form_gui = new ilPropertyFormGUI(); - - // Property Title - $text_input = new ilTextInputGUI($lng->txt("block_feed_block_title"), "block_title"); - $text_input->setInfo(""); - $text_input->setRequired(true); - $text_input->setMaxLength(200); - $this->form_gui->addItem($text_input); - - // Property FeedUrl - $text_input = new ilFeedUrlInputGUI($lng->txt("block_feed_block_feed_url"), "block_feed_url"); - $text_input->setInfo($lng->txt("block_feed_block_feed_url_info")); - $text_input->setRequired(true); - $text_input->setMaxLength(250); - $this->form_gui->addItem($text_input); - - - // save and cancel commands - if (in_array($a_mode, array(IL_FORM_CREATE,IL_FORM_RE_CREATE))) - { - $this->form_gui->addCommandButton("saveFeedBlock", $lng->txt("save")); - $this->form_gui->addCommandButton("cancelSaveFeedBlock", $lng->txt("cancel")); - } - else - { - $this->form_gui->addCommandButton("updateFeedBlock", $lng->txt("save")); - $this->form_gui->addCommandButton("cancelUpdateFeedBlock", $lng->txt("cancel")); - } - - $this->form_gui->setTitle($lng->txt("block_feed_block_head")); - $this->form_gui->setFormAction($this->ctrl->getFormAction($this)); - - $this->prepareFormFeedBlock($this->form_gui); - - } - - /** - * FORM FeedBlock: Prepare Saving of FeedBlock. - * - * @param object $a_feed_block FeedBlock object. - */ - public function prepareSaveFeedBlock(&$a_feed_block) - { - $ilCtrl = $this->ctrl; - - $a_feed_block->setContextObjId($ilCtrl->getContextObjId()); - $a_feed_block->setContextObjType($ilCtrl->getContextObjType()); - $a_feed_block->setType("pdfeed"); - } - - /** - * Confirmation of feed block deletion - */ - function confirmDeleteFeedBlock() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - include_once("Services/Utilities/classes/class.ilConfirmationGUI.php"); - $c_gui = new ilConfirmationGUI(); - - // set confirm/cancel commands - $c_gui->setFormAction($ilCtrl->getFormAction($this, "deleteFeedBlock")); - $c_gui->setHeaderText($lng->txt("info_delete_sure")); - $c_gui->setCancel($lng->txt("cancel"), "exitDeleteFeedBlock"); - $c_gui->setConfirm($lng->txt("confirm"), "deleteFeedBlock"); - - // add items to delete - $c_gui->addItem("external_feed_block_id", - $this->feed_block->getId(), $this->feed_block->getTitle(), - ilUtil::getImagePath("icon_feed.svg")); - - return $c_gui->getHTML(); - } - - /** - * Cancel deletion of feed block - */ - function exitDeleteFeedBlock() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->returnToParent($this); - } - - /** - * Delete feed block - */ - function deleteFeedBlock() - { - $ilCtrl = $this->ctrl; - - $this->feed_block->delete(); - $ilCtrl->returnToParent($this); - } + /** + * @var ilSetting + */ + protected $settings; + + public static $block_type = "pdfeed"; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + $this->access = $DIC->access(); + $this->settings = $DIC->settings(); + $lng = $DIC->language(); + + parent::__construct(); + + $lng->loadLanguageModule("feed"); + + $this->setLimit(5); + $this->setRowTemplate("tpl.block_external_feed_row.html", "Services/Feeds"); + } + + /** + * @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() + { + global $DIC; + + $ilCtrl = $DIC->ctrl(); + + switch ($ilCtrl->getCmd()) { + case "create": + case "edit": + case "saveFeedBlock": + case "updateFeedBlock": + case "editFeedBlock": + case "showFeedItem": + case "confirmDeleteFeedBlock": + return IL_SCREEN_CENTER; + break; + + default: + return IL_SCREEN_SIDE; + break; + } + } + + /** + * Do most of the initialisation. + */ + public function setBlock($a_block) + { + $ilCtrl = $this->ctrl; + + // init block + $this->feed_block = $a_block; + $this->setTitle($this->feed_block->getTitle()); + $this->setBlockId($this->feed_block->getId()); + + // get feed object + include_once("./Services/Feeds/classes/class.ilExternalFeed.php"); + $this->feed = new ilExternalFeed(); + $this->feed->setUrl($this->feed_block->getFeedUrl()); + + // init details + $this->setAvailableDetailLevels(2); + + $ilCtrl->setParameter($this, "block_id", $this->feed_block->getId()); + } + + /** + * execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $next_class = $ilCtrl->getNextClass(); + $cmd = $ilCtrl->getCmd("getHTML"); + + switch ($next_class) { + default: + return $this->$cmd(); + } + } + + /** + * Fill data section + */ + public function fillDataSection() + { + if ($this->getDynamic()) { + $this->setDataSection($this->getDynamicReload()); + } elseif ($this->getCurrentDetailLevel() > 1 && count($this->getData()) > 0) { + parent::fillDataSection(); + } else { + $this->setDataSection($this->getOverview()); + } + } + + /** + * Get block HTML code. + */ + public function getHTML() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilUser = $this->user; + $ilSetting = $this->settings; + + + if ($ilSetting->get("block_limit_pdfeed") == 0) { + return ""; + } + + if ($this->getCurrentDetailLevel() == 0) { + return ""; + } + + + // if no dynamic reload + if (!$this->getDynamic()) { + $this->feed->fetch(); + $this->setData($this->feed->getItems()); + } + + $ilCtrl->setParameter( + $this, + "external_feed_block_id", + $this->getBlockId() + ); + $this->addBlockCommand( + $ilCtrl->getLinkTarget( + $this, + "editFeedBlock" + ), + $lng->txt("edit") + ); + $this->addBlockCommand( + $ilCtrl->getLinkTarget( + $this, + "confirmDeleteFeedBlock" + ), + $lng->txt("delete") + ); + $ilCtrl->setParameter($this, "external_feed_block_id", ""); + + // JS enabler + $add = ""; + if ($_SESSION["il_feed_js"] == "n" || + ($ilUser->getPref("il_feed_js") == "n" && $_SESSION["il_feed_js"] != "y")) { + $add = $this->getJSEnabler(); + } + + return parent::getHTML() . $add; + } + + public function getDynamic() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + if ($ilCtrl->getCmdClass() != "ilcolumngui" && $ilCtrl->getCmd() != "enableJS") { + $sess_feed_js = ""; + if (isset($_SESSION["il_feed_js"])) { + $sess_feed_js = $_SESSION["il_feed_js"]; + } + if ($sess_feed_js != "n" && + ($ilUser->getPref("il_feed_js") != "n" || $sess_feed_js == "y")) { + // do not get feed dynamically, if cache hit is given. + if (!$this->feed->checkCacheHit()) { + return true; + } + } + } + + return false; + } + + public function getDynamicReload() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $ilCtrl->setParameterByClass( + "ilcolumngui", + "block_id", + "block_pdfeed_" . $this->getBlockId() + ); + + $rel_tpl = new ilTemplate("tpl.dynamic_reload.html", true, true, "Services/Feeds"); + $rel_tpl->setVariable("TXT_LOADING", $lng->txt("feed_loading_feed")); + $rel_tpl->setVariable("BLOCK_ID", "block_pdfeed_" . $this->getBlockId()); + $rel_tpl->setVariable( + "TARGET", + $ilCtrl->getLinkTargetByClass("ilcolumngui", "updateBlock", "", true) + ); + + // no JS + $rel_tpl->setVariable("TXT_FEED_CLICK_HERE", $lng->txt("feed_no_js_click_here")); + $rel_tpl->setVariable( + "TARGET_NO_JS", + $ilCtrl->getLinkTargetByClass("ilpdexternalfeedblockgui", "disableJS") + ); + + return $rel_tpl->get(); + } + + public function getJSEnabler() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameterByClass( + "ilcolumngui", + "block_id", + "block_pdfeed_" . $this->getBlockId() + ); + + $rel_tpl = new ilTemplate("tpl.js_enabler.html", true, true, "Services/Feeds"); + $rel_tpl->setVariable("BLOCK_ID", "block_pdfeed_" . $this->getBlockId()); + $rel_tpl->setVariable( + "TARGET", + $ilCtrl->getLinkTargetByClass("ilpdexternalfeedblockgui", "enableJS", true) + ); + + return $rel_tpl->get(); + } + + + public function disableJS() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + $_SESSION["il_feed_js"] = "n"; + $ilUser->writePref("il_feed_js", "n"); + $ilCtrl->redirectByClass("ilpersonaldesktopgui", "show"); + } + + public function enableJS() + { + $ilUser = $this->user; + + $_SESSION["il_feed_js"] = "y"; + $ilUser->writePref("il_feed_js", "y"); + echo $this->getHTML(); + exit; + } + + /** + * Fill feed item row + */ + public function fillRow($item) + { + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameter($this, "feed_item_id", $item->getId()); + $this->tpl->setVariable("VAL_TITLE", $item->getTitle()); + $this->tpl->setVariable( + "HREF_SHOW", + $ilCtrl->getLinkTarget($this, "showFeedItem") + ); + $ilCtrl->setParameter($this, "feed_item_id", ""); + } + + /** + * Get overview. + */ + public function getOverview() + { + $lng = $this->lng; + + $this->setEnableNumInfo(false); + return '
                  ' . ((int) count($this->getData())) . " " . $lng->txt("feed_feed_items") . "
                  "; + } + + /** + * Show Feed Item + */ + public function showFeedItem() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("./Services/News/classes/class.ilNewsItem.php"); + + $this->feed->fetch(); + foreach ($this->feed->getItems() as $item) { + if ($item->getId() == $_GET["feed_item_id"]) { + $c_item = $item; + break; + } + } + + $tpl = new ilTemplate("tpl.show_feed_item.html", true, true, "Services/Feeds"); + + if (is_object($c_item)) { + if (trim($c_item->getSummary()) != "") { // summary + $tpl->setCurrentBlock("content"); + $tpl->setVariable("VAL_CONTENT", $c_item->getSummary()); + $tpl->parseCurrentBlock(); + } + if (trim($c_item->getDate()) != "" || trim($c_item->getAuthor()) != "") { // date + $tpl->setCurrentBlock("date_author"); + if (trim($c_item->getAuthor()) != "") { + $tpl->setVariable("VAL_AUTHOR", $c_item->getAuthor() . " - "); + } + $tpl->setVariable("VAL_DATE", $c_item->getDate()); + $tpl->parseCurrentBlock(); + } + + if (trim($c_item->getLink()) != "") { // link + $tpl->setCurrentBlock("plink"); + $tpl->setVariable("HREF_LINK", $c_item->getLink()); + $tpl->setVariable("TXT_LINK", $lng->txt("feed_open_source_page")); + $tpl->parseCurrentBlock(); + } + $tpl->setVariable("VAL_TITLE", $c_item->getTitle()); // title + } + + include_once("./Services/PersonalDesktop/classes/class.ilPDContentBlockGUI.php"); + $content_block = new ilPDContentBlockGUI(); + $content_block->setContent($tpl->get()); + $content_block->setTitle($this->getTitle()); + $content_block->setImage(ilUtil::getImagePath("icon_feed.svg")); + $content_block->addHeaderCommand( + $ilCtrl->getParentReturn($this), + $lng->txt("selected_items_back") + ); + + return $content_block->getHTML(); + } + + /** + * Create Form for Block. + */ + public function create() + { + return $this->createFeedBlock(); + } + + /** + * FORM FeedBlock: Init form. (We need to overwrite, because Generator + * does not know FeedUrl Inputs yet. + * + * @param int $a_mode Form Edit Mode (IL_FORM_EDIT | IL_FORM_CREATE) + */ + public function initFormFeedBlock($a_mode) + { + $lng = $this->lng; + + $lng->loadLanguageModule("block"); + + require_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + + $this->form_gui = new ilPropertyFormGUI(); + + // Property Title + $text_input = new ilTextInputGUI($lng->txt("block_feed_block_title"), "block_title"); + $text_input->setInfo(""); + $text_input->setRequired(true); + $text_input->setMaxLength(200); + $this->form_gui->addItem($text_input); + + // Property FeedUrl + $text_input = new ilFeedUrlInputGUI($lng->txt("block_feed_block_feed_url"), "block_feed_url"); + $text_input->setInfo($lng->txt("block_feed_block_feed_url_info")); + $text_input->setRequired(true); + $text_input->setMaxLength(250); + $this->form_gui->addItem($text_input); + + + // save and cancel commands + if (in_array($a_mode, array(IL_FORM_CREATE,IL_FORM_RE_CREATE))) { + $this->form_gui->addCommandButton("saveFeedBlock", $lng->txt("save")); + $this->form_gui->addCommandButton("cancelSaveFeedBlock", $lng->txt("cancel")); + } else { + $this->form_gui->addCommandButton("updateFeedBlock", $lng->txt("save")); + $this->form_gui->addCommandButton("cancelUpdateFeedBlock", $lng->txt("cancel")); + } + + $this->form_gui->setTitle($lng->txt("block_feed_block_head")); + $this->form_gui->setFormAction($this->ctrl->getFormAction($this)); + + $this->prepareFormFeedBlock($this->form_gui); + } + + /** + * FORM FeedBlock: Prepare Saving of FeedBlock. + * + * @param object $a_feed_block FeedBlock object. + */ + public function prepareSaveFeedBlock(&$a_feed_block) + { + $ilCtrl = $this->ctrl; + + $a_feed_block->setContextObjId($ilCtrl->getContextObjId()); + $a_feed_block->setContextObjType($ilCtrl->getContextObjType()); + $a_feed_block->setType("pdfeed"); + } + + /** + * Confirmation of feed block deletion + */ + public function confirmDeleteFeedBlock() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + include_once("Services/Utilities/classes/class.ilConfirmationGUI.php"); + $c_gui = new ilConfirmationGUI(); + + // set confirm/cancel commands + $c_gui->setFormAction($ilCtrl->getFormAction($this, "deleteFeedBlock")); + $c_gui->setHeaderText($lng->txt("info_delete_sure")); + $c_gui->setCancel($lng->txt("cancel"), "exitDeleteFeedBlock"); + $c_gui->setConfirm($lng->txt("confirm"), "deleteFeedBlock"); + + // add items to delete + $c_gui->addItem( + "external_feed_block_id", + $this->feed_block->getId(), + $this->feed_block->getTitle(), + ilUtil::getImagePath("icon_feed.svg") + ); + + return $c_gui->getHTML(); + } + + /** + * Cancel deletion of feed block + */ + public function exitDeleteFeedBlock() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->returnToParent($this); + } + + /** + * Delete feed block + */ + public function deleteFeedBlock() + { + $ilCtrl = $this->ctrl; + + $this->feed_block->delete(); + $ilCtrl->returnToParent($this); + } } - -?> \ No newline at end of file diff --git a/Services/Feeds/classes/class.ilUserFeedWriter.php b/Services/Feeds/classes/class.ilUserFeedWriter.php index aa914d89b66a01ed7023a8ddc85bd562eaa618bb..1b4f99595e6070887f02240f63a09cdeada8b37b 100644 --- a/Services/Feeds/classes/class.ilUserFeedWriter.php +++ b/Services/Feeds/classes/class.ilUserFeedWriter.php @@ -18,157 +18,136 @@ include_once("./Services/Feeds/classes/class.ilFeedWriter.php"); */ class ilUserFeedWriter extends ilFeedWriter { - /** - * @var ilSetting - */ - protected $settings; + /** + * @var ilSetting + */ + protected $settings; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - - function __construct($a_user_id, $a_hash, $privFeed = false) - { - global $DIC; + + public function __construct($a_user_id, $a_hash, $privFeed = false) + { + global $DIC; - $this->settings = $DIC->settings(); - $this->lng = $DIC->language(); - $ilSetting = $DIC->settings(); - $lng = $DIC->language(); + $this->settings = $DIC->settings(); + $this->lng = $DIC->language(); + $ilSetting = $DIC->settings(); + $lng = $DIC->language(); - parent::__construct(); - - //$lng->loadLanguageModule("news"); - - if ($a_user_id == "" || $a_hash == "") - { - return; - } - - $news_set = new ilSetting("news"); - if (!$news_set->get("enable_rss_for_internal")) - { - return; - } + parent::__construct(); + + //$lng->loadLanguageModule("news"); + + if ($a_user_id == "" || $a_hash == "") { + return; + } + + $news_set = new ilSetting("news"); + if (!$news_set->get("enable_rss_for_internal")) { + return; + } - include_once "Services/User/classes/class.ilObjUser.php"; - $hash = ilObjUser::_lookupFeedHash($a_user_id); - - include_once("./Services/News/classes/class.ilNewsItem.php"); - $rss_period = ilNewsItem::_lookupRSSPeriod(); + include_once "Services/User/classes/class.ilObjUser.php"; + $hash = ilObjUser::_lookupFeedHash($a_user_id); + + include_once("./Services/News/classes/class.ilNewsItem.php"); + $rss_period = ilNewsItem::_lookupRSSPeriod(); - if ($a_hash == $hash) - { - if ($privFeed) - { - //ilNewsItem::setPrivateFeedId($a_user_id); - $items = ilNewsItem::_getNewsItemsOfUser($a_user_id, false, true, $rss_period); - } - else - { - $items = ilNewsItem::_getNewsItemsOfUser($a_user_id, true, true, $rss_period); - } - - if ($ilSetting->get('short_inst_name') != "") - { - $this->setChannelTitle($ilSetting->get('short_inst_name')); - } - else - { - $this->setChannelTitle("ILIAS"); - } + if ($a_hash == $hash) { + if ($privFeed) { + //ilNewsItem::setPrivateFeedId($a_user_id); + $items = ilNewsItem::_getNewsItemsOfUser($a_user_id, false, true, $rss_period); + } else { + $items = ilNewsItem::_getNewsItemsOfUser($a_user_id, true, true, $rss_period); + } + + if ($ilSetting->get('short_inst_name') != "") { + $this->setChannelTitle($ilSetting->get('short_inst_name')); + } else { + $this->setChannelTitle("ILIAS"); + } - $this->setChannelAbout(ILIAS_HTTP_PATH); - $this->setChannelLink(ILIAS_HTTP_PATH); - //$this->setChannelDescription("ILIAS Channel Description"); - $i = 0; - foreach($items as $item) - { - $obj_id = ilObject::_lookupObjId($item["ref_id"]); - $obj_type = ilObject::_lookupType($obj_id); - $obj_title = ilObject::_lookupTitle($obj_id); + $this->setChannelAbout(ILIAS_HTTP_PATH); + $this->setChannelLink(ILIAS_HTTP_PATH); + //$this->setChannelDescription("ILIAS Channel Description"); + $i = 0; + foreach ($items as $item) { + $obj_id = ilObject::_lookupObjId($item["ref_id"]); + $obj_type = ilObject::_lookupType($obj_id); + $obj_title = ilObject::_lookupTitle($obj_id); - // not nice, to do: general solution - if ($obj_type == "mcst") - { - include_once("./Modules/MediaCast/classes/class.ilObjMediaCastAccess.php"); - if (!ilObjMediaCastAccess::_lookupOnline($obj_id)) - { - continue; - } - } + // not nice, to do: general solution + if ($obj_type == "mcst") { + include_once("./Modules/MediaCast/classes/class.ilObjMediaCastAccess.php"); + if (!ilObjMediaCastAccess::_lookupOnline($obj_id)) { + continue; + } + } - $i++; - $feed_item = new ilFeedItem(); - $title = ilNewsItem::determineNewsTitle - ($item["context_obj_type"], $item["title"], $item["content_is_lang_var"], - $item["agg_ref_id"], $item["aggregation"]); + $i++; + $feed_item = new ilFeedItem(); + $title = ilNewsItem::determineNewsTitle( + $item["context_obj_type"], + $item["title"], + $item["content_is_lang_var"], + $item["agg_ref_id"], + $item["aggregation"] + ); - // path - $loc = $this->getContextPath($item["ref_id"]); - - // title - if ($news_set->get("rss_title_format") == "news_obj") - { - $feed_item->setTitle($this->prepareStr(str_replace("
                  ", " ", $title)). - " (".$this->prepareStr($loc)." ".$this->prepareStr($obj_title). - ")"); - } - else - { - $feed_item->setTitle($this->prepareStr($loc)." ".$this->prepareStr($obj_title). - ": ".$this->prepareStr(str_replace("
                  ", " ", $title))); - } - - // description - $content = $this->prepareStr(nl2br( - ilNewsItem::determineNewsContent($item["context_obj_type"], $item["content"], $item["content_text_is_lang_var"]))); - $feed_item->setDescription($content); + // path + $loc = $this->getContextPath($item["ref_id"]); + + // title + if ($news_set->get("rss_title_format") == "news_obj") { + $feed_item->setTitle($this->prepareStr(str_replace("
                  ", " ", $title)) . + " (" . $this->prepareStr($loc) . " " . $this->prepareStr($obj_title) . + ")"); + } else { + $feed_item->setTitle($this->prepareStr($loc) . " " . $this->prepareStr($obj_title) . + ": " . $this->prepareStr(str_replace("
                  ", " ", $title))); + } + + // description + $content = $this->prepareStr(nl2br( + ilNewsItem::determineNewsContent($item["context_obj_type"], $item["content"], $item["content_text_is_lang_var"]) + )); + $feed_item->setDescription($content); - // lm page hack, not nice - if (in_array($item["context_obj_type"], array("lm")) && $item["context_sub_obj_type"] == "pg" - && $item["context_sub_obj_id"] > 0) - { - $feed_item->setLink(ILIAS_HTTP_PATH."/goto.php?client_id=".CLIENT_ID. - "&target=pg_".$item["context_sub_obj_id"]."_".$item["ref_id"]); - } - else if ($item["context_obj_type"] == "wiki" && $item["context_sub_obj_type"] == "wpg" - && $item["context_sub_obj_id"] > 0) - { - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $wptitle = ilWikiPage::lookupTitle($item["context_sub_obj_id"]); - $feed_item->setLink(ILIAS_HTTP_PATH."/goto.php?client_id=".CLIENT_ID. - "&target=".$item["context_obj_type"]."_".$item["ref_id"]."_".urlencode($wptitle)); // #14629 - } - else if (in_array($item["context_obj_type"], array("frm")) && $item["context_sub_obj_type"] == "pos" - && $item["context_sub_obj_id"] > 0) - { - // frm hack, not nice - include_once("./Modules/Forum/classes/class.ilObjForumAccess.php"); - $thread_id = ilObjForumAccess::_getThreadForPosting($item["context_sub_obj_id"]); - if ($thread_id > 0) - { - $feed_item->setLink(ILIAS_HTTP_PATH."/goto.php?client_id=".CLIENT_ID. - "&target=".$item["context_obj_type"]."_".$item["ref_id"]."_".$thread_id."_".$item["context_sub_obj_id"]); - } - else - { - $feed_item->setLink(ILIAS_HTTP_PATH."/goto.php?client_id=".CLIENT_ID. - "&target=".$item["context_obj_type"]."_".$item["ref_id"]); - } - } - else - { - $feed_item->setLink(ILIAS_HTTP_PATH."/goto.php?client_id=".CLIENT_ID. - "&target=".$item["context_obj_type"]."_".$item["ref_id"]); - } - $feed_item->setAbout($feed_item->getLink()."&il_about_feed=".$item["id"]); - $feed_item->setDate($item["creation_date"]); - $this->addItem($feed_item); - } - } - } + // lm page hack, not nice + if (in_array($item["context_obj_type"], array("lm")) && $item["context_sub_obj_type"] == "pg" + && $item["context_sub_obj_id"] > 0) { + $feed_item->setLink(ILIAS_HTTP_PATH . "/goto.php?client_id=" . CLIENT_ID . + "&target=pg_" . $item["context_sub_obj_id"] . "_" . $item["ref_id"]); + } elseif ($item["context_obj_type"] == "wiki" && $item["context_sub_obj_type"] == "wpg" + && $item["context_sub_obj_id"] > 0) { + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + $wptitle = ilWikiPage::lookupTitle($item["context_sub_obj_id"]); + $feed_item->setLink(ILIAS_HTTP_PATH . "/goto.php?client_id=" . CLIENT_ID . + "&target=" . $item["context_obj_type"] . "_" . $item["ref_id"] . "_" . urlencode($wptitle)); // #14629 + } elseif (in_array($item["context_obj_type"], array("frm")) && $item["context_sub_obj_type"] == "pos" + && $item["context_sub_obj_id"] > 0) { + // frm hack, not nice + include_once("./Modules/Forum/classes/class.ilObjForumAccess.php"); + $thread_id = ilObjForumAccess::_getThreadForPosting($item["context_sub_obj_id"]); + if ($thread_id > 0) { + $feed_item->setLink(ILIAS_HTTP_PATH . "/goto.php?client_id=" . CLIENT_ID . + "&target=" . $item["context_obj_type"] . "_" . $item["ref_id"] . "_" . $thread_id . "_" . $item["context_sub_obj_id"]); + } else { + $feed_item->setLink(ILIAS_HTTP_PATH . "/goto.php?client_id=" . CLIENT_ID . + "&target=" . $item["context_obj_type"] . "_" . $item["ref_id"]); + } + } else { + $feed_item->setLink(ILIAS_HTTP_PATH . "/goto.php?client_id=" . CLIENT_ID . + "&target=" . $item["context_obj_type"] . "_" . $item["ref_id"]); + } + $feed_item->setAbout($feed_item->getLink() . "&il_about_feed=" . $item["id"]); + $feed_item->setDate($item["creation_date"]); + $this->addItem($feed_item); + } + } + } } -?> diff --git a/Services/Form/classes/class.ilAdvSelectInputGUI.php b/Services/Form/classes/class.ilAdvSelectInputGUI.php index 9aa39bc3f550853f75088ac4957ff158368d8029..c688d03bd0b3bb485dd8c1caebc2b27413f5eba0 100755 --- a/Services/Form/classes/class.ilAdvSelectInputGUI.php +++ b/Services/Form/classes/class.ilAdvSelectInputGUI.php @@ -7,137 +7,149 @@ * It can hold graphical selection items, uses javascript and falls back * to a normal selection list, when javascript is disabled. * -* @author Alex Killing +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilAdvSelectInputGUI extends ilFormPropertyGUI { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - protected $options = array(); - protected $value; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + protected $options = array(); + protected $value; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - parent::__construct($a_title, $a_postvar); - $this->setType("advselect"); - } + $this->lng = $DIC->language(); + parent::__construct($a_title, $a_postvar); + $this->setType("advselect"); + } - /** - * Add an Options. - * - * @param array $a_options Options. Array ("value" => "option_html") - */ - function addOption($a_value, $a_text, $a_html = "") - { - $this->options[$a_value] = array("value" => $a_value, - "txt" => $a_text, "html" => $a_html); - } + /** + * Add an Options. + * + * @param array $a_options Options. Array ("value" => "option_html") + */ + public function addOption($a_value, $a_text, $a_html = "") + { + $this->options[$a_value] = array("value" => $a_value, + "txt" => $a_text, "html" => $a_html); + } - /** - * Get Options. - * - * @return array Options. Array ("value" => "option_html") - */ - function getOptions() - { - return $this->options; - } + /** + * Get Options. + * + * @return array Options. Array ("value" => "option_html") + */ + public function getOptions() + { + return $this->options; + } - /** - * Set Value. - * - * @param string $a_value Value - */ - function setValue($a_value) - { - $this->value = $a_value; - } + /** + * Set Value. + * + * @param string $a_value Value + */ + public function setValue($a_value) + { + $this->value = $a_value; + } - /** - * Get Value. - * - * @return string Value - */ - function getValue() - { - return $this->value; - } - - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $this->setValue($a_values[$this->getPostVar()]); - } + /** + * Get Value. + * + * @return string Value + */ + public function getValue() + { + return $this->value; + } + + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $this->setValue($a_values[$this->getPostVar()]); + } - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - $_POST[$this->getPostVar()] = - ilUtil::stripSlashes($_POST[$this->getPostVar()]); - if ($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") - { - $this->setAlert($lng->txt("msg_input_is_required")); + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + $_POST[$this->getPostVar()] = + ilUtil::stripSlashes($_POST[$this->getPostVar()]); + if ($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") { + $this->setAlert($lng->txt("msg_input_is_required")); - return false; - } - return true; - } + return false; + } + return true; + } - /** - * Insert property html - * - * @return int Size - */ - function insert($a_tpl) - { - include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"); - $selection = new ilAdvancedSelectionListGUI(); - $selection->setFormSelectMode($this->getPostVar(), "", false, - "", "", "", - "", "", "", ""); - $selection->setId($this->getPostVar()); - $selection->setHeaderIcon(ilAdvancedSelectionListGUI::DOWN_ARROW_DARK); - $selection->setSelectedValue($this->getValue()); - $selection->setUseImages(false); - $selection->setOnClickMode(ilAdvancedSelectionListGUI::ON_ITEM_CLICK_FORM_SELECT); - - foreach($this->getOptions() as $option) - { - $selection->addItem($option["txt"], $option["value"], "", - "", $option["value"], "", $option["html"]); - if ($this->getValue() == $option["value"]) - { - $selection->setListTitle($option["txt"]); - } - } - - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $selection->getHTML()); - $a_tpl->parseCurrentBlock(); - } + /** + * Insert property html + * + * @return int Size + */ + public function insert($a_tpl) + { + include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"); + $selection = new ilAdvancedSelectionListGUI(); + $selection->setFormSelectMode( + $this->getPostVar(), + "", + false, + "", + "", + "", + "", + "", + "", + "" + ); + $selection->setId($this->getPostVar()); + $selection->setHeaderIcon(ilAdvancedSelectionListGUI::DOWN_ARROW_DARK); + $selection->setSelectedValue($this->getValue()); + $selection->setUseImages(false); + $selection->setOnClickMode(ilAdvancedSelectionListGUI::ON_ITEM_CLICK_FORM_SELECT); + foreach ($this->getOptions() as $option) { + $selection->addItem( + $option["txt"], + $option["value"], + "", + "", + $option["value"], + "", + $option["html"] + ); + if ($this->getValue() == $option["value"]) { + $selection->setListTitle($option["txt"]); + } + } + + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $selection->getHTML()); + $a_tpl->parseCurrentBlock(); + } } diff --git a/Services/Form/classes/class.ilAlphabetInputGUI.php b/Services/Form/classes/class.ilAlphabetInputGUI.php index a8f587c4913fe7028c86a540d054b3c69284a43a..9fb74face05518963edbec81eeb593e53aa3bf43 100644 --- a/Services/Form/classes/class.ilAlphabetInputGUI.php +++ b/Services/Form/classes/class.ilAlphabetInputGUI.php @@ -8,233 +8,226 @@ include_once 'Services/UIComponent/Toolbar/interfaces/interface.ilToolbarItem.ph /** * This class represents a text property in a property form. * -* @author Alex Killing +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilAlphabetInputGUI extends ilFormPropertyGUI implements ilToolbarItem { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - protected $letters; - protected $parent_object; - protected $parent_cmd; - protected $highlight; - protected $highlight_letter; + protected $letters; + protected $parent_object; + protected $parent_cmd; + protected $highlight; + protected $highlight_letter; - /** - * @var bool - */ - protected $fix_db_umlauts = false; + /** + * @var bool + */ + protected $fix_db_umlauts = false; - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - parent::__construct($a_title, $a_postvar); - } + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + parent::__construct($a_title, $a_postvar); + } - /** - * Set Value. - * - * @param string $a_value Value - */ - function setValue($a_value) - { - $this->value = $a_value; - } + /** + * Set Value. + * + * @param string $a_value Value + */ + public function setValue($a_value) + { + $this->value = $a_value; + } - /** - * Get Value. - * - * @return string Value - */ - function getValue() - { - return $this->value; - } + /** + * Get Value. + * + * @return string Value + */ + public function getValue() + { + return $this->value; + } - - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $this->setValue($a_values[$this->getPostVar()]); - } + + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $this->setValue($a_values[$this->getPostVar()]); + } - /** - * Set letters available - * - * @param array letters - */ - function setLetters($a_val) - { - $this->letters = $a_val; - } - - /** - * Get letters available - * - * @return array letters - */ - function getLetters() - { - return $this->letters; - } + /** + * Set letters available + * + * @param array letters + */ + public function setLetters($a_val) + { + $this->letters = $a_val; + } + + /** + * Get letters available + * + * @return array letters + */ + public function getLetters() + { + return $this->letters; + } - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - $_POST[$this->getPostVar()] = ilUtil::stripSlashes($_POST[$this->getPostVar()]); - if ($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") - { - $this->setAlert($lng->txt("msg_input_is_required")); + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + $_POST[$this->getPostVar()] = ilUtil::stripSlashes($_POST[$this->getPostVar()]); + if ($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") { + $this->setAlert($lng->txt("msg_input_is_required")); - return false; - } - - return true; - } - - /** - * Set fix db umlauts - * - * @param bool $a_val fix db umlauts - */ - function setFixDBUmlauts($a_val) - { - $this->fix_db_umlauts = $a_val; - } - - /** - * Get fix db umlauts - * - * @return bool fix db umlauts - */ - function getFixDBUmlauts() - { - return $this->fix_db_umlauts; - } - - /** - * Fix db umlauts - * - * @param - * @return - */ - function fixDBUmlauts($l) - { - if ($this->fix_db_umlauts && !ilUtil::dbSupportsDisctinctUmlauts()) - { - $l = str_replace (array("Ä", "Ö", "Ü", "ä", "ö", "ü"), array("A", "O", "U", "a", "o", "u"), $l); - } - return $l; - } - - - /** - * Render item - */ - protected function render($a_mode = "") - { - die("only implemented for toolbar usage"); - } - - /** - * Insert property html - * - * @return int Size - */ -// function insert($a_tpl) -// { -// $a_tpl->setCurrentBlock("prop_generic"); -// $a_tpl->setVariable("PROP_GENERIC", "zz"); -// $a_tpl->parseCurrentBlock(); -// } - - /** - * Set parent cmd - * - * @param object parent object - * @param string parent command - */ - function setParentCommand($a_obj, $a_cmd) - { - $this->parent_object = $a_obj; - $this->parent_cmd = $a_cmd; - } - - /** - * Set highlighted - * - * @param - * @return - */ - function setHighlighted($a_high_letter) - { - $this->highlight = true; - $this->highlight_letter = $a_high_letter; - } - - /** - * Get HTML for toolbar - */ - function getToolbarHTML() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $lng->loadLanguageModule("form"); + return false; + } + + return true; + } + + /** + * Set fix db umlauts + * + * @param bool $a_val fix db umlauts + */ + public function setFixDBUmlauts($a_val) + { + $this->fix_db_umlauts = $a_val; + } + + /** + * Get fix db umlauts + * + * @return bool fix db umlauts + */ + public function getFixDBUmlauts() + { + return $this->fix_db_umlauts; + } + + /** + * Fix db umlauts + * + * @param + * @return + */ + public function fixDBUmlauts($l) + { + if ($this->fix_db_umlauts && !ilUtil::dbSupportsDisctinctUmlauts()) { + $l = str_replace(array("Ä", "Ö", "Ü", "ä", "ö", "ü"), array("A", "O", "U", "a", "o", "u"), $l); + } + return $l; + } + + + /** + * Render item + */ + protected function render($a_mode = "") + { + die("only implemented for toolbar usage"); + } + + /** + * Insert property html + * + * @return int Size + */ + // function insert($a_tpl) + // { + // $a_tpl->setCurrentBlock("prop_generic"); + // $a_tpl->setVariable("PROP_GENERIC", "zz"); + // $a_tpl->parseCurrentBlock(); + // } + + /** + * Set parent cmd + * + * @param object parent object + * @param string parent command + */ + public function setParentCommand($a_obj, $a_cmd) + { + $this->parent_object = $a_obj; + $this->parent_cmd = $a_cmd; + } + + /** + * Set highlighted + * + * @param + * @return + */ + public function setHighlighted($a_high_letter) + { + $this->highlight = true; + $this->highlight_letter = $a_high_letter; + } + + /** + * Get HTML for toolbar + */ + public function getToolbarHTML() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $lng->loadLanguageModule("form"); - $tpl = new ilTemplate("tpl.prop_alphabet.html", true, true, "Services/Form"); - foreach ((array)$this->getLetters() as $l) - { - $l = $this->fixDBUmlauts($l); - $tpl->setCurrentBlock("letter"); - $tpl->setVariable("TXT_LET", $l); - $ilCtrl->setParameter($this->parent_object, "letter", rawurlencode($l)); - $tpl->setVariable("TXT_LET", $l); - $tpl->setVariable("HREF_LET", $ilCtrl->getLinkTarget($this->parent_object, $this->parent_cmd)); - if ($this->highlight && $this->highlight_letter !== null && $this->highlight_letter == $l) - { - $tpl->setVariable("CLASS", ' class="ilHighlighted" '); - } - $tpl->parseCurrentBlock(); - } - $ilCtrl->setParameter($this->parent_object, "letter", ""); - $tpl->setVariable("TXT_ALL", $lng->txt("form_alphabet_all")); - $tpl->setVariable("HREF_ALL", $ilCtrl->getLinkTarget($this->parent_object, $this->parent_cmd)); - if ($this->highlight && $this->highlight_letter === null) - { - $tpl->setVariable("CLASSA", ' class="ilHighlighted" '); - } - return $tpl->get(); - } - + $tpl = new ilTemplate("tpl.prop_alphabet.html", true, true, "Services/Form"); + foreach ((array) $this->getLetters() as $l) { + $l = $this->fixDBUmlauts($l); + $tpl->setCurrentBlock("letter"); + $tpl->setVariable("TXT_LET", $l); + $ilCtrl->setParameter($this->parent_object, "letter", rawurlencode($l)); + $tpl->setVariable("TXT_LET", $l); + $tpl->setVariable("HREF_LET", $ilCtrl->getLinkTarget($this->parent_object, $this->parent_cmd)); + if ($this->highlight && $this->highlight_letter !== null && $this->highlight_letter == $l) { + $tpl->setVariable("CLASS", ' class="ilHighlighted" '); + } + $tpl->parseCurrentBlock(); + } + $ilCtrl->setParameter($this->parent_object, "letter", ""); + $tpl->setVariable("TXT_ALL", $lng->txt("form_alphabet_all")); + $tpl->setVariable("HREF_ALL", $ilCtrl->getLinkTarget($this->parent_object, $this->parent_cmd)); + if ($this->highlight && $this->highlight_letter === null) { + $tpl->setVariable("CLASSA", ' class="ilHighlighted" '); + } + return $tpl->get(); + } } -?> \ No newline at end of file diff --git a/Services/Form/classes/class.ilBirthdayInputGUI.php b/Services/Form/classes/class.ilBirthdayInputGUI.php index 99c9c8a239cc7d7aa446213014d738367ff1fa38..7896d2e7a87efed234949a2b5c8737fbfb875e78 100755 --- a/Services/Form/classes/class.ilBirthdayInputGUI.php +++ b/Services/Form/classes/class.ilBirthdayInputGUI.php @@ -6,27 +6,25 @@ include_once("./Services/Form/classes/class.ilDateTimeInputGUI.php"); /** * This class represents a text property in a property form. * -* @author Alex Killing +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilBirthdayInputGUI extends ilDateTimeInputGUI -{ - public function getStartYear() - { - return date("Y")-100; - } - - protected function parseDatePickerConfig() - { - $config = parent::parseDatePickerConfig(); - - $config["viewMode"] = "years"; - $config["calendarWeeks"] = false; - $config["showTodayButton"] = false; - - return $config; - } +{ + public function getStartYear() + { + return date("Y")-100; + } + + protected function parseDatePickerConfig() + { + $config = parent::parseDatePickerConfig(); + + $config["viewMode"] = "years"; + $config["calendarWeeks"] = false; + $config["showTodayButton"] = false; + + return $config; + } } - -?> \ No newline at end of file diff --git a/Services/Form/classes/class.ilCSSRectInputGUI.php b/Services/Form/classes/class.ilCSSRectInputGUI.php index 43ce16d53a20d71ebdfbf8a1729eccb333b65985..bde8cf721d4c8617e98bdccda14d99a1d49ce470 100644 --- a/Services/Form/classes/class.ilCSSRectInputGUI.php +++ b/Services/Form/classes/class.ilCSSRectInputGUI.php @@ -1,295 +1,292 @@ +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilCSSRectInputGUI extends ilSubEnabledFormPropertyGUI { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - protected $top; - protected $left; - protected $right; - protected $bottom; - protected $size; - protected $useUnits; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + protected $top; + protected $left; + protected $right; + protected $bottom; + protected $size; + protected $useUnits; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - parent::__construct($a_title, $a_postvar); - $this->size = 6; - $this->useUnits = TRUE; - } + $this->lng = $DIC->language(); + parent::__construct($a_title, $a_postvar); + $this->size = 6; + $this->useUnits = true; + } - public function setValue($valueArray) - { - $this->top = $valueArray['top']; - $this->left = $valueArray['left']; - $this->right = $valueArray['right']; - $this->bottom = $valueArray['bottom']; - } + public function setValue($valueArray) + { + $this->top = $valueArray['top']; + $this->left = $valueArray['left']; + $this->right = $valueArray['right']; + $this->bottom = $valueArray['bottom']; + } - /** - * Set use units. - * - * @param boolean $a_value Use units - */ - function setUseUnits($a_value) - { - $this->useUnits = $a_value; - } + /** + * Set use units. + * + * @param boolean $a_value Use units + */ + public function setUseUnits($a_value) + { + $this->useUnits = $a_value; + } - /** - * Get use units - * - * @return boolean use units - */ - function useUnits() - { - return $this->useUnits; - } + /** + * Get use units + * + * @return boolean use units + */ + public function useUnits() + { + return $this->useUnits; + } - /** - * Set Top. - * - * @param string $a_value Top - */ - function setTop($a_value) - { - $this->top = $a_value; - } + /** + * Set Top. + * + * @param string $a_value Top + */ + public function setTop($a_value) + { + $this->top = $a_value; + } - /** - * Get Top. - * - * @return string Top - */ - function getTop() - { - return $this->top; - } + /** + * Get Top. + * + * @return string Top + */ + public function getTop() + { + return $this->top; + } - /** - * Set Bottom. - * - * @param string $a_value Bottom - */ - function setBottom($a_value) - { - $this->bottom = $a_value; - } + /** + * Set Bottom. + * + * @param string $a_value Bottom + */ + public function setBottom($a_value) + { + $this->bottom = $a_value; + } - /** - * Get Bottom. - * - * @return string Bottom - */ - function getBottom() - { - return $this->bottom; - } + /** + * Get Bottom. + * + * @return string Bottom + */ + public function getBottom() + { + return $this->bottom; + } - /** - * Set Left. - * - * @param string $a_value Left - */ - function setLeft($a_value) - { - $this->left = $a_value; - } + /** + * Set Left. + * + * @param string $a_value Left + */ + public function setLeft($a_value) + { + $this->left = $a_value; + } - /** - * Get Left. - * - * @return string Left - */ - function getLeft() - { - return $this->left; - } + /** + * Get Left. + * + * @return string Left + */ + public function getLeft() + { + return $this->left; + } - /** - * Set Right. - * - * @param string $a_value Right - */ - function setRight($a_value) - { - $this->right = $a_value; - } + /** + * Set Right. + * + * @param string $a_value Right + */ + public function setRight($a_value) + { + $this->right = $a_value; + } - /** - * Get Right. - * - * @return string Right - */ - function getRight() - { - return $this->right; - } + /** + * Get Right. + * + * @return string Right + */ + public function getRight() + { + return $this->right; + } - /** - * Set Size. - * - * @param int $a_size Size - */ - function setSize($a_size) - { - $this->size = $a_size; - } + /** + * Set Size. + * + * @param int $a_size Size + */ + public function setSize($a_size) + { + $this->size = $a_size; + } - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $postVar = $this->getPostVar(); + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $postVar = $this->getPostVar(); - $values = array( - 'top' => $a_values[$postVar . '_top'], - 'bottom' => $a_values[$postVar . '_bottom'], - 'right' => $a_values[$postVar . '_right'], - 'left' => $a_values[$postVar . '_left'], - ); + $values = array( + 'top' => $a_values[$postVar . '_top'], + 'bottom' => $a_values[$postVar . '_bottom'], + 'right' => $a_values[$postVar . '_right'], + 'left' => $a_values[$postVar . '_left'], + ); - $this->setValue($values); - } + $this->setValue($values); + } - /** - * Get Size. - * - * @return int Size - */ - function getSize() - { - return $this->size; - } - - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - $_POST[$this->getPostVar() . '_top'] = ilUtil::stripSlashes($_POST[$this->getPostVar()]['top']); - $_POST[$this->getPostVar() . '_right'] = ilUtil::stripSlashes($_POST[$this->getPostVar()]['right']); - $_POST[$this->getPostVar() . '_bottom'] = ilUtil::stripSlashes($_POST[$this->getPostVar()]['bottom']); - $_POST[$this->getPostVar() . '_left'] = ilUtil::stripSlashes($_POST[$this->getPostVar()]['left']); + /** + * Get Size. + * + * @return int Size + */ + public function getSize() + { + return $this->size; + } + + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + $_POST[$this->getPostVar() . '_top'] = ilUtil::stripSlashes($_POST[$this->getPostVar()]['top']); + $_POST[$this->getPostVar() . '_right'] = ilUtil::stripSlashes($_POST[$this->getPostVar()]['right']); + $_POST[$this->getPostVar() . '_bottom'] = ilUtil::stripSlashes($_POST[$this->getPostVar()]['bottom']); + $_POST[$this->getPostVar() . '_left'] = ilUtil::stripSlashes($_POST[$this->getPostVar()]['left']); - if ( - $this->getRequired() && - ((trim($_POST[$this->getPostVar() . '_top'] == "")) - || (trim($_POST[$this->getPostVar() . '_bottom']) == "") - || (trim($_POST[$this->getPostVar() . '_left']) == "") - || (trim($_POST[$this->getPostVar() . '_right']) == "") - ) - ) { - $this->setAlert($lng->txt("msg_input_is_required")); - return false; - } + if ( + $this->getRequired() && + ( + (trim($_POST[$this->getPostVar() . '_top'] == "")) + || (trim($_POST[$this->getPostVar() . '_bottom']) == "") + || (trim($_POST[$this->getPostVar() . '_left']) == "") + || (trim($_POST[$this->getPostVar() . '_right']) == "") + ) + ) { + $this->setAlert($lng->txt("msg_input_is_required")); + return false; + } - if ($this->useUnits()) { - if ((!preg_match('/^(([1-9]+|([1-9]+[0]*[\.,]{0,1}[\d]+))|(0[\.,](0*[1-9]+[\d]*))|0)(cm|mm|in|pt|pc|px|em)$/is', $_POST[$this->getPostVar() . '_top'])) || - (!preg_match('/^(([1-9]+|([1-9]+[0]*[\.,]{0,1}[\d]+))|(0[\.,](0*[1-9]+[\d]*))|0)(cm|mm|in|pt|pc|px|em)$/is', $_POST[$this->getPostVar() . '_right'])) || - (!preg_match('/^(([1-9]+|([1-9]+[0]*[\.,]{0,1}[\d]+))|(0[\.,](0*[1-9]+[\d]*))|0)(cm|mm|in|pt|pc|px|em)$/is', $_POST[$this->getPostVar() . '_bottom'])) || - (!preg_match('/^(([1-9]+|([1-9]+[0]*[\.,]{0,1}[\d]+))|(0[\.,](0*[1-9]+[\d]*))|0)(cm|mm|in|pt|pc|px|em)$/is', $_POST[$this->getPostVar() . '_left']))) - { - $this->setAlert($lng->txt("msg_unit_is_required")); - return false; - } - } - return $this->checkSubItemsInput(); - } + if ($this->useUnits()) { + if ((!preg_match('/^(([1-9]+|([1-9]+[0]*[\.,]{0,1}[\d]+))|(0[\.,](0*[1-9]+[\d]*))|0)(cm|mm|in|pt|pc|px|em)$/is', $_POST[$this->getPostVar() . '_top'])) || + (!preg_match('/^(([1-9]+|([1-9]+[0]*[\.,]{0,1}[\d]+))|(0[\.,](0*[1-9]+[\d]*))|0)(cm|mm|in|pt|pc|px|em)$/is', $_POST[$this->getPostVar() . '_right'])) || + (!preg_match('/^(([1-9]+|([1-9]+[0]*[\.,]{0,1}[\d]+))|(0[\.,](0*[1-9]+[\d]*))|0)(cm|mm|in|pt|pc|px|em)$/is', $_POST[$this->getPostVar() . '_bottom'])) || + (!preg_match('/^(([1-9]+|([1-9]+[0]*[\.,]{0,1}[\d]+))|(0[\.,](0*[1-9]+[\d]*))|0)(cm|mm|in|pt|pc|px|em)$/is', $_POST[$this->getPostVar() . '_left']))) { + $this->setAlert($lng->txt("msg_unit_is_required")); + return false; + } + } + return $this->checkSubItemsInput(); + } - /** - * Insert property html - * - * @return int Size - */ - function insert($a_tpl) - { - $lng = $this->lng; - - if (strlen($this->getTop())) - { - $a_tpl->setCurrentBlock("cssrect_value_top"); - $a_tpl->setVariable("CSSRECT_VALUE", ilUtil::prepareFormOutput($this->getTop())); - $a_tpl->parseCurrentBlock(); - } - if (strlen($this->getBottom())) - { - $a_tpl->setCurrentBlock("cssrect_value_bottom"); - $a_tpl->setVariable("CSSRECT_VALUE", ilUtil::prepareFormOutput($this->getBottom())); - $a_tpl->parseCurrentBlock(); - } - if (strlen($this->getLeft())) - { - $a_tpl->setCurrentBlock("cssrect_value_left"); - $a_tpl->setVariable("CSSRECT_VALUE", ilUtil::prepareFormOutput($this->getLeft())); - $a_tpl->parseCurrentBlock(); - } - if (strlen($this->getRight())) - { - $a_tpl->setCurrentBlock("cssrect_value_right"); - $a_tpl->setVariable("CSSRECT_VALUE", ilUtil::prepareFormOutput($this->getRight())); - $a_tpl->parseCurrentBlock(); - } - $a_tpl->setCurrentBlock("cssrect"); - $a_tpl->setVariable("ID", $this->getFieldId()); - $a_tpl->setVariable("SIZE", $this->getSize()); - $a_tpl->setVariable("POST_VAR", $this->getPostVar()); - $a_tpl->setVariable("TEXT_TOP", $lng->txt("pos_top")); - $a_tpl->setVariable("TEXT_RIGHT", $lng->txt("pos_right")); - $a_tpl->setVariable("TEXT_BOTTOM", $lng->txt("pos_bottom")); - $a_tpl->setVariable("TEXT_LEFT", $lng->txt("pos_left")); - if ($this->getDisabled()) - { - $a_tpl->setVariable("DISABLED", - " disabled=\"disabled\""); - } - $a_tpl->parseCurrentBlock(); - } + /** + * Insert property html + * + * @return int Size + */ + public function insert($a_tpl) + { + $lng = $this->lng; + + if (strlen($this->getTop())) { + $a_tpl->setCurrentBlock("cssrect_value_top"); + $a_tpl->setVariable("CSSRECT_VALUE", ilUtil::prepareFormOutput($this->getTop())); + $a_tpl->parseCurrentBlock(); + } + if (strlen($this->getBottom())) { + $a_tpl->setCurrentBlock("cssrect_value_bottom"); + $a_tpl->setVariable("CSSRECT_VALUE", ilUtil::prepareFormOutput($this->getBottom())); + $a_tpl->parseCurrentBlock(); + } + if (strlen($this->getLeft())) { + $a_tpl->setCurrentBlock("cssrect_value_left"); + $a_tpl->setVariable("CSSRECT_VALUE", ilUtil::prepareFormOutput($this->getLeft())); + $a_tpl->parseCurrentBlock(); + } + if (strlen($this->getRight())) { + $a_tpl->setCurrentBlock("cssrect_value_right"); + $a_tpl->setVariable("CSSRECT_VALUE", ilUtil::prepareFormOutput($this->getRight())); + $a_tpl->parseCurrentBlock(); + } + $a_tpl->setCurrentBlock("cssrect"); + $a_tpl->setVariable("ID", $this->getFieldId()); + $a_tpl->setVariable("SIZE", $this->getSize()); + $a_tpl->setVariable("POST_VAR", $this->getPostVar()); + $a_tpl->setVariable("TEXT_TOP", $lng->txt("pos_top")); + $a_tpl->setVariable("TEXT_RIGHT", $lng->txt("pos_right")); + $a_tpl->setVariable("TEXT_BOTTOM", $lng->txt("pos_bottom")); + $a_tpl->setVariable("TEXT_LEFT", $lng->txt("pos_left")); + if ($this->getDisabled()) { + $a_tpl->setVariable( + "DISABLED", + " disabled=\"disabled\"" + ); + } + $a_tpl->parseCurrentBlock(); + } } diff --git a/Services/Form/classes/class.ilCheckboxGroupInputGUI.php b/Services/Form/classes/class.ilCheckboxGroupInputGUI.php index 9225cf8ecc8ed7bba1aea4ee16070d9a58de4f09..090e78837dbfa2c55f89a26a28cbf84dd55194e3 100755 --- a/Services/Form/classes/class.ilCheckboxGroupInputGUI.php +++ b/Services/Form/classes/class.ilCheckboxGroupInputGUI.php @@ -1,24 +1,24 @@ lng = $DIC->language(); - parent::__construct($a_title, $a_postvar); - $this->setType("checkboxgroup"); - } + $this->lng = $DIC->language(); + parent::__construct($a_title, $a_postvar); + $this->setType("checkboxgroup"); + } - /** - * Set use values as keys - * - * @param bool $a_val use values as keys - */ - function setUseValuesAsKeys($a_val) - { - $this->use_values_as_keys = $a_val; - } - - /** - * Get use values as keys - * - * @return bool use values as keys - */ - function getUseValuesAsKeys() - { - return $this->use_values_as_keys; - } - - /** - * Add Option. - * - * @param object $a_option CheckboxOption object - */ - function addOption($a_option) - { - $this->options[] = $a_option; - } + /** + * Set use values as keys + * + * @param bool $a_val use values as keys + */ + public function setUseValuesAsKeys($a_val) + { + $this->use_values_as_keys = $a_val; + } + + /** + * Get use values as keys + * + * @return bool use values as keys + */ + public function getUseValuesAsKeys() + { + return $this->use_values_as_keys; + } + + /** + * Add Option. + * + * @param object $a_option CheckboxOption object + */ + public function addOption($a_option) + { + $this->options[] = $a_option; + } - /** - * Set Options. - * - * @param array $a_options Options. Array ("value" => "option_text") - */ - function setOptions($a_options) - { - foreach($a_options as $key => $label) { - if (is_string($label)) { - $chb = new ilCheckboxInputGUI($label, $key); - $this->options[] = $chb; - } - else if ($label instanceof ilCheckboxInputGUI) { - $this->options[] = $label; - } + /** + * Set Options. + * + * @param array $a_options Options. Array ("value" => "option_text") + */ + public function setOptions($a_options) + { + foreach ($a_options as $key => $label) { + if (is_string($label)) { + $chb = new ilCheckboxInputGUI($label, $key); + $this->options[] = $chb; + } elseif ($label instanceof ilCheckboxInputGUI) { + $this->options[] = $label; } - } + } + } - /** - * Get Options. - * - * @return array Array of CheckboxOption objects - */ - function getOptions() - { - return $this->options; - } + /** + * Get Options. + * + * @return array Array of CheckboxOption objects + */ + public function getOptions() + { + return $this->options; + } - /** - * Set Value. - * - * @param array $a_value Value - */ - function setValue($a_value) - { - $this->value = $a_value; - } + /** + * Set Value. + * + * @param array $a_value Value + */ + public function setValue($a_value) + { + $this->value = $a_value; + } - /** - * Get Value. - * - * @return array Value - */ - function getValue() - { - return $this->value; - } + /** + * Get Value. + * + * @return array Value + */ + public function getValue() + { + return $this->value; + } - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $this->setValue($a_values[$this->getPostVar()]); - foreach($this->getOptions() as $option) - { - foreach($option->getSubItems() as $item) - { - $item->setValueByArray($a_values); - } - } - } - - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $this->setValue($a_values[$this->getPostVar()]); + foreach ($this->getOptions() as $option) { + foreach ($option->getSubItems() as $item) { + $item->setValueByArray($a_values); + } + } + } - if ($this->getRequired() && (!is_array($_POST[$this->getPostVar()]) || count($_POST[$this->getPostVar()]) === 0)) { - $this->setAlert($lng->txt('msg_input_is_required')); - return false; - } + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; - $ok = true; - foreach($this->getOptions() as $option) - { - foreach($option->getSubItems() as $item) - { - $item_ok = $item->checkInput(); - if (!$item_ok && in_array($option->getValue(), $_POST[$this->getPostVar()])) - { - $ok = false; - } - } - } - return $ok; + if ($this->getRequired() && (!is_array($_POST[$this->getPostVar()]) || count($_POST[$this->getPostVar()]) === 0)) { + $this->setAlert($lng->txt('msg_input_is_required')); + return false; + } - } + $ok = true; + foreach ($this->getOptions() as $option) { + foreach ($option->getSubItems() as $item) { + $item_ok = $item->checkInput(); + if (!$item_ok && in_array($option->getValue(), $_POST[$this->getPostVar()])) { + $ok = false; + } + } + } + return $ok; + } - /** - * Insert property html - * - * @return int Size - */ - function insert($a_tpl) - { - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $this->render()); - $a_tpl->parseCurrentBlock(); - } + /** + * Insert property html + * + * @return int Size + */ + public function insert($a_tpl) + { + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $this->render()); + $a_tpl->parseCurrentBlock(); + } - /** - * Get item by post var - * - * @return mixed false or item object - */ - function getItemByPostVar($a_post_var) - { - if ($this->getPostVar() == $a_post_var) - { - return $this; - } + /** + * Get item by post var + * + * @return mixed false or item object + */ + public function getItemByPostVar($a_post_var) + { + if ($this->getPostVar() == $a_post_var) { + return $this; + } - foreach($this->getOptions() as $option) - { - foreach($option->getSubItems() as $item) - { - if ($item->getType() != "section_header") - { - $ret = $item->getItemByPostVar($a_post_var); - if (is_object($ret)) - { - return $ret; - } - } - } - } + foreach ($this->getOptions() as $option) { + foreach ($option->getSubItems() as $item) { + if ($item->getType() != "section_header") { + $ret = $item->getItemByPostVar($a_post_var); + if (is_object($ret)) { + return $ret; + } + } + } + } - return false; - } - - public function getTableFilterHTML() - { - return $this->render(); - } - - public function getToolbarHTML() - { - return $this->render('toolbar'); - } - - protected function render($a_mode = '') - { - $tpl = new ilTemplate("tpl.prop_checkbox_group.html", true, true, "Services/Form"); + return false; + } + + public function getTableFilterHTML() + { + return $this->render(); + } + + public function getToolbarHTML() + { + return $this->render('toolbar'); + } + + protected function render($a_mode = '') + { + $tpl = new ilTemplate("tpl.prop_checkbox_group.html", true, true, "Services/Form"); - foreach($this->getOptions() as $option) - { - // information text for option - if ($option->getInfo() != "") - { - $tpl->setCurrentBlock("checkbox_option_desc"); - $tpl->setVariable("CHECKBOX_OPTION_DESC", $option->getInfo()); - $tpl->parseCurrentBlock(); - } + foreach ($this->getOptions() as $option) { + // information text for option + if ($option->getInfo() != "") { + $tpl->setCurrentBlock("checkbox_option_desc"); + $tpl->setVariable("CHECKBOX_OPTION_DESC", $option->getInfo()); + $tpl->parseCurrentBlock(); + } - if (count($option->getSubItems()) > 0) - { - $tpl->setCurrentBlock("checkbox_option_subform"); - $pf = new ilPropertyFormGUI(); - $pf->setMode("subform"); - $pf->setItems($option->getSubItems()); - $tpl->setVariable("SUB_FORM", $pf->getContent()); - $tpl->setVariable("SOP_ID", $this->getFieldId()."_".$option->getValue()); - if ($pf->getMultipart()) - { - $this->getParentForm()->setMultipart(true); - } - $tpl->parseCurrentBlock(); - if ($pf->getMultipart()) - { - $this->getParentForm()->setMultipart(true); - } - } + if (count($option->getSubItems()) > 0) { + $tpl->setCurrentBlock("checkbox_option_subform"); + $pf = new ilPropertyFormGUI(); + $pf->setMode("subform"); + $pf->setItems($option->getSubItems()); + $tpl->setVariable("SUB_FORM", $pf->getContent()); + $tpl->setVariable("SOP_ID", $this->getFieldId() . "_" . $option->getValue()); + if ($pf->getMultipart()) { + $this->getParentForm()->setMultipart(true); + } + $tpl->parseCurrentBlock(); + if ($pf->getMultipart()) { + $this->getParentForm()->setMultipart(true); + } + } - $tpl->setCurrentBlock("prop_checkbox_option"); - - if (!$this->getUseValuesAsKeys()) - { - $tpl->setVariable("POST_VAR", $this->getPostVar() . '[]'); - $tpl->setVariable("VAL_CHECKBOX_OPTION", $option->getValue()); - } - else - { - $tpl->setVariable("POST_VAR", $this->getPostVar().'['.$option->getValue().']'); - $tpl->setVariable("VAL_CHECKBOX_OPTION", "1"); - } - - $tpl->setVariable("OP_ID", $this->getFieldId()."_".$option->getValue()); - $tpl->setVariable("FID", $this->getFieldId()); - - if($this->getDisabled() or $option->getDisabled()) - { - $tpl->setVariable('DISABLED','disabled="disabled" '); - } + $tpl->setCurrentBlock("prop_checkbox_option"); + + if (!$this->getUseValuesAsKeys()) { + $tpl->setVariable("POST_VAR", $this->getPostVar() . '[]'); + $tpl->setVariable("VAL_CHECKBOX_OPTION", $option->getValue()); + } else { + $tpl->setVariable("POST_VAR", $this->getPostVar() . '[' . $option->getValue() . ']'); + $tpl->setVariable("VAL_CHECKBOX_OPTION", "1"); + } + + $tpl->setVariable("OP_ID", $this->getFieldId() . "_" . $option->getValue()); + $tpl->setVariable("FID", $this->getFieldId()); + + if ($this->getDisabled() or $option->getDisabled()) { + $tpl->setVariable('DISABLED', 'disabled="disabled" '); + } - if (is_array($this->getValue())) - { - if (!$this->getUseValuesAsKeys()) - { - if (in_array($option->getValue(), $this->getValue())) - { - $tpl->setVariable("CHK_CHECKBOX_OPTION", - 'checked="checked"'); - } - } - else - { - $cval = $this->getValue(); - if ($cval[$option->getValue()] == 1) - { - $tpl->setVariable("CHK_CHECKBOX_OPTION", - 'checked="checked"'); - } - } - } - $tpl->setVariable("TXT_CHECKBOX_OPTION", $option->getTitle()); + if (is_array($this->getValue())) { + if (!$this->getUseValuesAsKeys()) { + if (in_array($option->getValue(), $this->getValue())) { + $tpl->setVariable( + "CHK_CHECKBOX_OPTION", + 'checked="checked"' + ); + } + } else { + $cval = $this->getValue(); + if ($cval[$option->getValue()] == 1) { + $tpl->setVariable( + "CHK_CHECKBOX_OPTION", + 'checked="checked"' + ); + } + } + } + $tpl->setVariable("TXT_CHECKBOX_OPTION", $option->getTitle()); - $tpl->parseCurrentBlock(); - } - $tpl->setVariable("ID", $this->getFieldId()); + $tpl->parseCurrentBlock(); + } + $tpl->setVariable("ID", $this->getFieldId()); - return $tpl->get(); - } + return $tpl->get(); + } - /** - * returns a flat array of possibly existing subitems recursively - * - * @return array - */ - public function getSubInputItemsRecursive() - { - $subInputItems = parent::getSubInputItemsRecursive(); - foreach($this->getOptions() as $option) - { - /** - * @var $option ilRadioOption - */ - $subInputItems = array_merge( $subInputItems, $option->getSubInputItemsRecursive() ); - } + /** + * returns a flat array of possibly existing subitems recursively + * + * @return array + */ + public function getSubInputItemsRecursive() + { + $subInputItems = parent::getSubInputItemsRecursive(); + foreach ($this->getOptions() as $option) { + /** + * @var $option ilRadioOption + */ + $subInputItems = array_merge($subInputItems, $option->getSubInputItemsRecursive()); + } - return $subInputItems; - } + return $subInputItems; + } } diff --git a/Services/Form/classes/class.ilCheckboxInputGUI.php b/Services/Form/classes/class.ilCheckboxInputGUI.php index f57d8cb2d91b7d9468052cc6c0c198a82d81dcde..d79dd1204b2eb18edd824a1bfd8fe215ed1d68a7 100755 --- a/Services/Form/classes/class.ilCheckboxInputGUI.php +++ b/Services/Form/classes/class.ilCheckboxInputGUI.php @@ -1,24 +1,24 @@ +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilCheckboxInputGUI extends ilSubEnabledFormPropertyGUI implements ilToolbarItem { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - protected $value = "1"; - protected $checked; - protected $optiontitle = ""; - protected $additional_attributes = ''; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + protected $value = "1"; + protected $checked; + protected $optiontitle = ""; + protected $additional_attributes = ''; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - parent::__construct($a_title, $a_postvar); - $this->setType("checkbox"); - } + $this->lng = $DIC->language(); + parent::__construct($a_title, $a_postvar); + $this->setType("checkbox"); + } - /** - * Set Value. - * - * @param string $a_value Value - */ - function setValue($a_value) - { - $this->value = $a_value; - } + /** + * Set Value. + * + * @param string $a_value Value + */ + public function setValue($a_value) + { + $this->value = $a_value; + } - /** - * Get Value. - * - * @return string Value - */ - function getValue() - { - return $this->value; - } + /** + * Get Value. + * + * @return string Value + */ + public function getValue() + { + return $this->value; + } - /** - * Set Checked. - * - * @param boolean $a_checked Checked - */ - function setChecked($a_checked) - { - $this->checked = $a_checked; - } + /** + * Set Checked. + * + * @param boolean $a_checked Checked + */ + public function setChecked($a_checked) + { + $this->checked = $a_checked; + } - /** - * Get Checked. - * - * @return boolean Checked - */ - function getChecked() - { - return $this->checked; - } + /** + * Get Checked. + * + * @return boolean Checked + */ + public function getChecked() + { + return $this->checked; + } - /** - * Set Option Title (optional). - * - * @param string $a_optiontitle Option Title (optional) - */ - function setOptionTitle($a_optiontitle) - { - $this->optiontitle = $a_optiontitle; - } + /** + * Set Option Title (optional). + * + * @param string $a_optiontitle Option Title (optional) + */ + public function setOptionTitle($a_optiontitle) + { + $this->optiontitle = $a_optiontitle; + } - /** - * Get Option Title (optional). - * - * @return string Option Title (optional) - */ - function getOptionTitle() - { - return $this->optiontitle; - } + /** + * Get Option Title (optional). + * + * @return string Option Title (optional) + */ + public function getOptionTitle() + { + return $this->optiontitle; + } - /** - * Set value by array - * - * @param object $a_item Item - */ - function setValueByArray($a_values) - { - $this->setChecked($a_values[$this->getPostVar()]); - foreach($this->getSubItems() as $item) - { - $item->setValueByArray($a_values); - } - } - - /** - * Set addiotional attributes - * - * @param string $a_attrs addition attribute string - */ - function setAdditionalAttributes($a_attrs) - { - $this->additional_attributes = $a_attrs; - } - - /** - * get addtional attributes - * - */ - function getAdditionalAttributes() - { - return $this->additional_attributes; - } + /** + * Set value by array + * + * @param object $a_item Item + */ + public function setValueByArray($a_values) + { + $this->setChecked($a_values[$this->getPostVar()]); + foreach ($this->getSubItems() as $item) { + $item->setValueByArray($a_values); + } + } + + /** + * Set addiotional attributes + * + * @param string $a_attrs addition attribute string + */ + public function setAdditionalAttributes($a_attrs) + { + $this->additional_attributes = $a_attrs; + } + + /** + * get addtional attributes + * + */ + public function getAdditionalAttributes() + { + return $this->additional_attributes; + } - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - $_POST[$this->getPostVar()] = - ilUtil::stripSlashes($_POST[$this->getPostVar()]); - - // getRequired() is NOT processed here! + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + $_POST[$this->getPostVar()] = + ilUtil::stripSlashes($_POST[$this->getPostVar()]); + + // getRequired() is NOT processed here! - $ok = $this->checkSubItemsInput(); + $ok = $this->checkSubItemsInput(); - // only not ok, if checkbox not checked - if (!$ok && $_POST[$this->getPostVar()] == "") - { - $ok = true; - } + // only not ok, if checkbox not checked + if (!$ok && $_POST[$this->getPostVar()] == "") { + $ok = true; + } - return $ok; - } - - /** - * Sub form hidden on init? - * - */ - public function hideSubForm() - { - return !$this->getChecked(); - } + return $ok; + } + + /** + * Sub form hidden on init? + * + */ + public function hideSubForm() + { + return !$this->getChecked(); + } - /** - * Render item - */ - function render($a_mode = '') - { - $tpl = new ilTemplate("tpl.prop_checkbox.html", true, true, "Services/Form"); - - $tpl->setVariable("POST_VAR", $this->getPostVar()); - $tpl->setVariable("ID", $this->getFieldId()); - $tpl->setVariable("PROPERTY_VALUE", $this->getValue()); - $tpl->setVariable("OPTION_TITLE", $this->getOptionTitle()); - if(strlen($this->getAdditionalAttributes())) - { - $tpl->setVariable('PROP_CHECK_ATTRS',$this->getAdditionalAttributes()); - } - if ($this->getChecked()) - { - $tpl->setVariable("PROPERTY_CHECKED", - 'checked="checked"'); - } - if ($this->getDisabled()) - { - $tpl->setVariable("DISABLED", - 'disabled="disabled"'); - } - - if ($a_mode == "toolbar") - { - // block-inline hack, see: http://blog.mozilla.com/webdev/2009/02/20/cross-browser-inline-block/ - // -moz-inline-stack for FF2 - // zoom 1; *display:inline for IE6 & 7 - $tpl->setVariable("STYLE_PAR", 'display: -moz-inline-stack; display:inline-block; zoom: 1; *display:inline;'); - } + /** + * Render item + */ + public function render($a_mode = '') + { + $tpl = new ilTemplate("tpl.prop_checkbox.html", true, true, "Services/Form"); + + $tpl->setVariable("POST_VAR", $this->getPostVar()); + $tpl->setVariable("ID", $this->getFieldId()); + $tpl->setVariable("PROPERTY_VALUE", $this->getValue()); + $tpl->setVariable("OPTION_TITLE", $this->getOptionTitle()); + if (strlen($this->getAdditionalAttributes())) { + $tpl->setVariable('PROP_CHECK_ATTRS', $this->getAdditionalAttributes()); + } + if ($this->getChecked()) { + $tpl->setVariable( + "PROPERTY_CHECKED", + 'checked="checked"' + ); + } + if ($this->getDisabled()) { + $tpl->setVariable( + "DISABLED", + 'disabled="disabled"' + ); + } + + if ($a_mode == "toolbar") { + // block-inline hack, see: http://blog.mozilla.com/webdev/2009/02/20/cross-browser-inline-block/ + // -moz-inline-stack for FF2 + // zoom 1; *display:inline for IE6 & 7 + $tpl->setVariable("STYLE_PAR", 'display: -moz-inline-stack; display:inline-block; zoom: 1; *display:inline;'); + } - $tpl->setVariable("ARIA_LABEL", ilUtil::prepareFormOutput($this->getTitle())); + $tpl->setVariable("ARIA_LABEL", ilUtil::prepareFormOutput($this->getTitle())); - return $tpl->get(); - } + return $tpl->get(); + } - /** - * Insert property html - * - * @return int Size - */ - function insert($a_tpl) - { - $html = $this->render(); + /** + * Insert property html + * + * @return int Size + */ + public function insert($a_tpl) + { + $html = $this->render(); - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $html); - $a_tpl->parseCurrentBlock(); - } + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $html); + $a_tpl->parseCurrentBlock(); + } - /** - * Get HTML for table filter - */ - function getTableFilterHTML() - { - $html = $this->render(); - return $html; - } + /** + * Get HTML for table filter + */ + public function getTableFilterHTML() + { + $html = $this->render(); + return $html; + } - /** - * serialize data - */ - function serializeData() - { - return serialize($this->getChecked()); - } - - /** - * unserialize data - */ - function unserializeData($a_data) - { - $data = unserialize($a_data); + /** + * serialize data + */ + public function serializeData() + { + return serialize($this->getChecked()); + } + + /** + * unserialize data + */ + public function unserializeData($a_data) + { + $data = unserialize($a_data); - if ($data) - { - $this->setValue($data); - $this->setChecked(true); - } - } - - /** - * Get HTML for toolbar - */ - function getToolbarHTML() - { - $html = $this->render('toolbar'); - return $html; - } + if ($data) { + $this->setValue($data); + $this->setChecked(true); + } + } + + /** + * Get HTML for toolbar + */ + public function getToolbarHTML() + { + $html = $this->render('toolbar'); + return $html; + } } diff --git a/Services/Form/classes/class.ilCheckboxOption.php b/Services/Form/classes/class.ilCheckboxOption.php index 1e9c840f1e638863070be88873712e3fc73e3166..7228b5417e3c1ff2d1922b7f55636f3c879bf72a 100755 --- a/Services/Form/classes/class.ilCheckboxOption.php +++ b/Services/Form/classes/class.ilCheckboxOption.php @@ -1,30 +1,30 @@ +* @author Helmut Schottmüller * @version $Id$ * @ingroup ServicesForm */ diff --git a/Services/Form/classes/class.ilColorPickerInputGUI.php b/Services/Form/classes/class.ilColorPickerInputGUI.php index 44ea97d3d28e27cfc9d36875aca1b0295a615131..af568179b41f929e622ca31c541a7791f4829693 100644 --- a/Services/Form/classes/class.ilColorPickerInputGUI.php +++ b/Services/Form/classes/class.ilColorPickerInputGUI.php @@ -12,252 +12,230 @@ class ilColorPickerInputGUI extends ilTextInputGUI { - protected $hex; + protected $hex; - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - public function __construct($a_title = "", $a_postvar = "") - { - parent::__construct($a_title, $a_postvar); - $this->setType("color"); - $this->setDefaultColor("04427e"); - } - - /** - * check input - * - * @access public - * @return - */ - public function checkInput() - { - if( - $this->getRequired() && - !strlen($_POST[$this->getPostVar()]) - ) - { - $this->setAlert($this->lng->txt("msg_input_is_required")); - return false; - } - - if ($this->getAcceptNamedColors() && substr($_POST[$this->getPostVar()], 0, 1) == "!") - { - $_POST[$this->getPostVar()] = - ilUtil::stripslashes(trim($_POST[$this->getPostVar()])); - } - else - { - $_POST[$this->getPostVar()] = - $this->determineHexcode(ilUtil::stripslashes(trim($_POST[$this->getPostVar()]))); - } - return true; - } - - /** - * Set values by array - * @param type $a_values - */ - public function setValueByArray($a_values) - { - $this->setValue($a_values[$this->getPostVar()]); - } - - /** - * set value - * - * @access public - * @param string $a_value color hexcode - * @return - */ - public function setValue($a_value) - { - $a_value = trim($a_value); - if ($this->getAcceptNamedColors() && substr($a_value, 0, 1) == "!") - { - parent::setValue($a_value); - } - else - { - $this->hex = ilColorPickerInputGUI::determineHexcode($a_value); - parent::setValue($this->getHexcode()); - } - } - - /** - * Set Default Color. - * - * @param mixed $a_defaultcolor Default Color - */ - function setDefaultColor($a_defaultcolor) - { - $this->defaultcolor = $a_defaultcolor; - } + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + parent::__construct($a_title, $a_postvar); + $this->setType("color"); + $this->setDefaultColor("04427e"); + } + + /** + * check input + * + * @access public + * @return + */ + public function checkInput() + { + if ( + $this->getRequired() && + !strlen($_POST[$this->getPostVar()]) + ) { + $this->setAlert($this->lng->txt("msg_input_is_required")); + return false; + } + + if ($this->getAcceptNamedColors() && substr($_POST[$this->getPostVar()], 0, 1) == "!") { + $_POST[$this->getPostVar()] = + ilUtil::stripslashes(trim($_POST[$this->getPostVar()])); + } else { + $_POST[$this->getPostVar()] = + $this->determineHexcode(ilUtil::stripslashes(trim($_POST[$this->getPostVar()]))); + } + return true; + } + + /** + * Set values by array + * @param type $a_values + */ + public function setValueByArray($a_values) + { + $this->setValue($a_values[$this->getPostVar()]); + } + + /** + * set value + * + * @access public + * @param string $a_value color hexcode + * @return + */ + public function setValue($a_value) + { + $a_value = trim($a_value); + if ($this->getAcceptNamedColors() && substr($a_value, 0, 1) == "!") { + parent::setValue($a_value); + } else { + $this->hex = ilColorPickerInputGUI::determineHexcode($a_value); + parent::setValue($this->getHexcode()); + } + } + + /** + * Set Default Color. + * + * @param mixed $a_defaultcolor Default Color + */ + public function setDefaultColor($a_defaultcolor) + { + $this->defaultcolor = $a_defaultcolor; + } - /** - * Get Default Color. - * - * @return mixed Default Color - */ - function getDefaultColor() - { - return $this->defaultcolor; - } + /** + * Get Default Color. + * + * @return mixed Default Color + */ + public function getDefaultColor() + { + return $this->defaultcolor; + } - /** - * Set Accept Named Colors (Leading '!'). - * - * @param boolean $a_acceptnamedcolors Accept Named Colors (Leading '!') - */ - function setAcceptNamedColors($a_acceptnamedcolors) - { - $this->acceptnamedcolors = $a_acceptnamedcolors; - } + /** + * Set Accept Named Colors (Leading '!'). + * + * @param boolean $a_acceptnamedcolors Accept Named Colors (Leading '!') + */ + public function setAcceptNamedColors($a_acceptnamedcolors) + { + $this->acceptnamedcolors = $a_acceptnamedcolors; + } - /** - * Get Accept Named Colors (Leading '!'). - * - * @return boolean Accept Named Colors (Leading '!') - */ - function getAcceptNamedColors() - { - return $this->acceptnamedcolors; - } + /** + * Get Accept Named Colors (Leading '!'). + * + * @return boolean Accept Named Colors (Leading '!') + */ + public function getAcceptNamedColors() + { + return $this->acceptnamedcolors; + } - /** - * get hexcode - * - * @access public - * @return - */ - public function getHexcode() - { - if(strpos($this->hex,'#') === 0) - { - return substr($this->hex,1); - } - return $this->hex ? $this->hex : $this->getDefaultColor(); - } - - /** - * Determine hex code for a given value - */ - static function determineHexcode($a_value) - { - $a_value = trim(strtolower($a_value)); + /** + * get hexcode + * + * @access public + * @return + */ + public function getHexcode() + { + if (strpos($this->hex, '#') === 0) { + return substr($this->hex, 1); + } + return $this->hex ? $this->hex : $this->getDefaultColor(); + } + + /** + * Determine hex code for a given value + */ + public static function determineHexcode($a_value) + { + $a_value = trim(strtolower($a_value)); - // remove leading # - if(strpos($a_value,'#') === 0) - { - $a_value = substr($a_value,1); - } - - // handle standard color names (no leading (!)) - switch ($a_value) - { - // html4 colors - case "black": $a_value = "000000"; break; - case "maroon": $a_value = "800000"; break; - case "green": $a_value = "008000"; break; - case "olive": $a_value = "808000"; break; - case "navy": $a_value = "000080"; break; - case "purple": $a_value = "800080"; break; - case "teal": $a_value = "008080"; break; - case "silver": $a_value = "C0C0C0"; break; - case "gray": $a_value = "808080"; break; - case "red": $a_value = "ff0000"; break; - case "lime": $a_value = "00ff00"; break; - case "yellow": $a_value = "ffff00"; break; - case "blue": $a_value = "0000ff"; break; - case "fuchsia": $a_value = "ff00ff"; break; - case "aqua": $a_value = "00ffff"; break; - case "white": $a_value = "ffffff"; break; - - // other colors used by ILIAS, supported by modern browsers - case "brown": $a_value = "a52a2a"; break; - } - - // handle rgb values - if (substr($a_value, 0, 3) == "rgb") - { - $pos1 = strpos($a_value, "("); - $pos2 = strpos($a_value, ")"); - $rgb = explode(",", substr($a_value, $pos1 + 1, $pos2 - $pos1 - 1)); - $r = str_pad(dechex($rgb[0]), 2, "0", STR_PAD_LEFT); - $g = str_pad(dechex($rgb[1]), 2, "0", STR_PAD_LEFT); - $b = str_pad(dechex($rgb[2]), 2, "0", STR_PAD_LEFT); - $a_value = $r.$g.$b; - } - - $a_value = trim(strtolower($a_value)); - - // expand three digit hex numbers - if (preg_match("/^[0-9a-f]3/", $a_value) && strlen($a_value == 3)) - { - $a_value = "".$a_value; - $a_value = "0".$a_value[0]."0".$a_value[1]."0".$a_value[2]; - } - - if (!preg_match("/^[a-f0-9]{6}/", $a_value)) - { - $a_value = ""; - } + // remove leading # + if (strpos($a_value, '#') === 0) { + $a_value = substr($a_value, 1); + } + + // handle standard color names (no leading (!)) + switch ($a_value) { + // html4 colors + case "black": $a_value = "000000"; break; + case "maroon": $a_value = "800000"; break; + case "green": $a_value = "008000"; break; + case "olive": $a_value = "808000"; break; + case "navy": $a_value = "000080"; break; + case "purple": $a_value = "800080"; break; + case "teal": $a_value = "008080"; break; + case "silver": $a_value = "C0C0C0"; break; + case "gray": $a_value = "808080"; break; + case "red": $a_value = "ff0000"; break; + case "lime": $a_value = "00ff00"; break; + case "yellow": $a_value = "ffff00"; break; + case "blue": $a_value = "0000ff"; break; + case "fuchsia": $a_value = "ff00ff"; break; + case "aqua": $a_value = "00ffff"; break; + case "white": $a_value = "ffffff"; break; + + // other colors used by ILIAS, supported by modern browsers + case "brown": $a_value = "a52a2a"; break; + } + + // handle rgb values + if (substr($a_value, 0, 3) == "rgb") { + $pos1 = strpos($a_value, "("); + $pos2 = strpos($a_value, ")"); + $rgb = explode(",", substr($a_value, $pos1 + 1, $pos2 - $pos1 - 1)); + $r = str_pad(dechex($rgb[0]), 2, "0", STR_PAD_LEFT); + $g = str_pad(dechex($rgb[1]), 2, "0", STR_PAD_LEFT); + $b = str_pad(dechex($rgb[2]), 2, "0", STR_PAD_LEFT); + $a_value = $r . $g . $b; + } + + $a_value = trim(strtolower($a_value)); + + // expand three digit hex numbers + if (preg_match("/^[0-9a-f]3/", $a_value) && strlen($a_value == 3)) { + $a_value = "" . $a_value; + $a_value = "0" . $a_value[0] . "0" . $a_value[1] . "0" . $a_value[2]; + } + + if (!preg_match("/^[a-f0-9]{6}/", $a_value)) { + $a_value = ""; + } - return strtoupper($a_value); - } - - /** - * Insert property html - * - * @return int Size - */ - function insert($a_tpl) - { - include_once('./Services/YUI/classes/class.ilYuiUtil.php'); - - ilYuiUtil::initColorPicker(); - - - $a_tpl->setCurrentBlock("prop_color"); + return strtoupper($a_value); + } + + /** + * Insert property html + * + * @return int Size + */ + public function insert($a_tpl) + { + include_once('./Services/YUI/classes/class.ilYuiUtil.php'); + + ilYuiUtil::initColorPicker(); + + + $a_tpl->setCurrentBlock("prop_color"); - $js_tpl = new ilTemplate('tpl.color_picker.js',true,true,'Services/Form'); - $js_tpl->setVariable('THUMB_PATH',ilUtil::getImagePath('color_picker_thumb.png','Services/Form')); - $js_tpl->setVariable('HUE_THUMB_PATH',ilUtil::getImagePath('color_picker_hue_thumb.png','Services/Form')); - $js_tpl->setVariable('COLOR_ID',$this->getFieldId()); - $ic = ilColorPickerInputGUI::determineHexcode($this->getHexcode()); - if ($ic == "") - { - $ic = "FFFFFF"; - } - $js_tpl->setVariable('INIT_COLOR_SHORT',$ic); - $js_tpl->setVariable('INIT_COLOR','#'.$this->getHexcode()); - $js_tpl->setVariable('POST_VAR', $this->getPostVar()); - - - if($this->getDisabled()) - { - $a_tpl->setVariable('COLOR_DISABLED','disabled="disabled"'); - } - else - { - $a_tpl->setVariable('PROP_COLOR_JS',$js_tpl->get()); - } - $a_tpl->setVariable("POST_VAR", $this->getPostVar()); - $a_tpl->setVariable("PROP_COLOR_ID", $this->getFieldId()); + $js_tpl = new ilTemplate('tpl.color_picker.js', true, true, 'Services/Form'); + $js_tpl->setVariable('THUMB_PATH', ilUtil::getImagePath('color_picker_thumb.png', 'Services/Form')); + $js_tpl->setVariable('HUE_THUMB_PATH', ilUtil::getImagePath('color_picker_hue_thumb.png', 'Services/Form')); + $js_tpl->setVariable('COLOR_ID', $this->getFieldId()); + $ic = ilColorPickerInputGUI::determineHexcode($this->getHexcode()); + if ($ic == "") { + $ic = "FFFFFF"; + } + $js_tpl->setVariable('INIT_COLOR_SHORT', $ic); + $js_tpl->setVariable('INIT_COLOR', '#' . $this->getHexcode()); + $js_tpl->setVariable('POST_VAR', $this->getPostVar()); + + + if ($this->getDisabled()) { + $a_tpl->setVariable('COLOR_DISABLED', 'disabled="disabled"'); + } else { + $a_tpl->setVariable('PROP_COLOR_JS', $js_tpl->get()); + } + $a_tpl->setVariable("POST_VAR", $this->getPostVar()); + $a_tpl->setVariable("PROP_COLOR_ID", $this->getFieldId()); - if (substr(trim($this->getValue()), 0, 1) == "!" && $this->getAcceptNamedColors()) - { - $a_tpl->setVariable("PROPERTY_VALUE_COLOR",ilUtil::prepareFormOutput(trim($this->getValue()))); - } - else - { - $a_tpl->setVariable("PROPERTY_VALUE_COLOR",ilUtil::prepareFormOutput($this->getHexcode())); - } - $a_tpl->parseCurrentBlock(); - } - + if (substr(trim($this->getValue()), 0, 1) == "!" && $this->getAcceptNamedColors()) { + $a_tpl->setVariable("PROPERTY_VALUE_COLOR", ilUtil::prepareFormOutput(trim($this->getValue()))); + } else { + $a_tpl->setVariable("PROPERTY_VALUE_COLOR", ilUtil::prepareFormOutput($this->getHexcode())); + } + $a_tpl->parseCurrentBlock(); + } } -?> \ No newline at end of file diff --git a/Services/Form/classes/class.ilCombinationInputGUI.php b/Services/Form/classes/class.ilCombinationInputGUI.php index 0affa63cddd1d36b1f9ff9a9f494322201fa80d0..9072a0dc98baeea8b0e94052011e0164349f2a19 100644 --- a/Services/Form/classes/class.ilCombinationInputGUI.php +++ b/Services/Form/classes/class.ilCombinationInputGUI.php @@ -1,370 +1,325 @@ +* @author Jörg Lützenkirchen * @version $Id$ * @ingroup ServicesForm */ class ilCombinationInputGUI extends ilSubEnabledFormPropertyGUI implements ilTableFilterItem { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * Constructor - */ - function __construct($a_title = "", $a_postvar = "") - { - parent::__construct($a_title, $a_postvar); - global $DIC; + /** + * Constructor + */ + public function __construct($a_title = "", $a_postvar = "") + { + parent::__construct($a_title, $a_postvar); + global $DIC; - $this->lng = $DIC->language(); - } + $this->lng = $DIC->language(); + } - protected $items = array(); - protected $labels; - protected $comparison; + protected $items = array(); + protected $labels; + protected $comparison; - const COMPARISON_ASCENDING = 1; - const COMPARISON_DESCENDING = 2; + const COMPARISON_ASCENDING = 1; + const COMPARISON_DESCENDING = 2; - /** - * Add property item - * - * @param string $id - * @param object $item - * @param string $label - */ - function addCombinationItem($id, $item, $label = "") - { - $this->items[$id] = $item; - if($label) - { - $this->labels[$id] = $label; - } - } + /** + * Add property item + * + * @param string $id + * @param object $item + * @param string $label + */ + public function addCombinationItem($id, $item, $label = "") + { + $this->items[$id] = $item; + if ($label) { + $this->labels[$id] = $label; + } + } - /** - * Get property item - * - * @param string $id - * @return object - */ - function getCombinationItem($id) - { - if(isset($this->items[$id])) - { - return $this->items[$id]; - } - } + /** + * Get property item + * + * @param string $id + * @return object + */ + public function getCombinationItem($id) + { + if (isset($this->items[$id])) { + return $this->items[$id]; + } + } - /** - * Remove property item - * - * @param string $id - */ - function removeCombinationItem($id) - { - if(isset($this->items[$id])) - { - unset($this->items[$id]); - } - } + /** + * Remove property item + * + * @param string $id + */ + public function removeCombinationItem($id) + { + if (isset($this->items[$id])) { + unset($this->items[$id]); + } + } - /** - * Call item methods - * - * @param string $method - * @param array $param - */ - function __call($method, $param) - { - $result = array(); - foreach($this->items as $id => $obj) - { - if(method_exists($obj, $method)) - { - $result[$id] = call_user_func_array(array($obj, $method), $param); - } - } - return $result; - } + /** + * Call item methods + * + * @param string $method + * @param array $param + */ + public function __call($method, $param) + { + $result = array(); + foreach ($this->items as $id => $obj) { + if (method_exists($obj, $method)) { + $result[$id] = call_user_func_array(array($obj, $method), $param); + } + } + return $result; + } - /** - * serialize data - */ - function serializeData() - { - $result = array(); - foreach($this->items as $id => $obj) - { - $result[$id] = $obj->serializeData(); - } - return serialize($result); - } + /** + * serialize data + */ + public function serializeData() + { + $result = array(); + foreach ($this->items as $id => $obj) { + $result[$id] = $obj->serializeData(); + } + return serialize($result); + } - /** - * unserialize data - */ - function unserializeData($a_data) - { - $data = unserialize($a_data); + /** + * unserialize data + */ + public function unserializeData($a_data) + { + $data = unserialize($a_data); - if ($data) - { - foreach($this->items as $id => $obj) - { - $obj->unserializeData($data[$id]); - } - } - else - { - foreach($this->items as $id => $obj) - { - if(method_exists($obj, "setValue")) - { - $this->setValue(false); - } - } - } - } + if ($data) { + foreach ($this->items as $id => $obj) { + $obj->unserializeData($data[$id]); + } + } else { + foreach ($this->items as $id => $obj) { + if (method_exists($obj, "setValue")) { + $this->setValue(false); + } + } + } + } - /** - * Set mode for comparison (extended validation) - * - * @param int $mode - * @return bool - */ - function setComparisonMode($mode) - { - if(in_array($mode, array(self::COMPARISON_ASCENDING, self::COMPARISON_DESCENDING))) - { - foreach($this->items as $obj) - { - if(!method_exists($obj, "getPostValueForComparison")) - { - return false; - } - } - $this->comparison_mode = $mode; - return true; - } - } + /** + * Set mode for comparison (extended validation) + * + * @param int $mode + * @return bool + */ + public function setComparisonMode($mode) + { + if (in_array($mode, array(self::COMPARISON_ASCENDING, self::COMPARISON_DESCENDING))) { + foreach ($this->items as $obj) { + if (!method_exists($obj, "getPostValueForComparison")) { + return false; + } + } + $this->comparison_mode = $mode; + return true; + } + } - /** - * Set Value. - * - * @param string $a_value Value - */ - function setValue($a_value) - { - if(is_array($a_value)) - { - foreach($a_value as $id => $value) - { - if(isset($this->items[$id])) - { - if(method_exists($this->items[$id], "setValue")) - { - $this->items[$id]->setValue($value); - } - // datetime - else if(method_exists($this->items[$id], "setDate")) - { - $this->items[$id]->setDate($value); - } - } - } - } - else if($a_value === NULL) - { - foreach($this->items as $item) - { - if(method_exists($item, "setValue")) - { - $item->setValue(NULL); - } - // datetime - else if(method_exists($item, "setDate")) - { - $item->setDate(); - } - // duration - else if(method_exists($item, "setMonths")) - { - $item->setMonths(0); - $item->setDays(0); - $item->setHours(0); - $item->setMinutes(0); - $item->setSeconds(0); - } - } - } - } + /** + * Set Value. + * + * @param string $a_value Value + */ + public function setValue($a_value) + { + if (is_array($a_value)) { + foreach ($a_value as $id => $value) { + if (isset($this->items[$id])) { + if (method_exists($this->items[$id], "setValue")) { + $this->items[$id]->setValue($value); + } + // datetime + elseif (method_exists($this->items[$id], "setDate")) { + $this->items[$id]->setDate($value); + } + } + } + } elseif ($a_value === null) { + foreach ($this->items as $item) { + if (method_exists($item, "setValue")) { + $item->setValue(null); + } + // datetime + elseif (method_exists($item, "setDate")) { + $item->setDate(); + } + // duration + elseif (method_exists($item, "setMonths")) { + $item->setMonths(0); + $item->setDays(0); + $item->setHours(0); + $item->setMinutes(0); + $item->setSeconds(0); + } + } + } + } - /** - * Get Value. - * - * @return string Value - */ - function getValue() - { - $result = array(); - foreach($this->items as $id => $obj) - { - if(method_exists($obj, "getValue")) - { - $result[$id] = $obj->getValue(); - } - // datetime - else if(method_exists($obj, "setDate")) - { - $result[$id] = $obj->getDate(); - } - } - return $result; - } + /** + * Get Value. + * + * @return string Value + */ + public function getValue() + { + $result = array(); + foreach ($this->items as $id => $obj) { + if (method_exists($obj, "getValue")) { + $result[$id] = $obj->getValue(); + } + // datetime + elseif (method_exists($obj, "setDate")) { + $result[$id] = $obj->getDate(); + } + } + return $result; + } - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - foreach($this->items as $id => $obj) - { - $obj->setValueByArray($a_values); - } - } + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + foreach ($this->items as $id => $obj) { + $obj->setValueByArray($a_values); + } + } - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - if(sizeof($this->items)) - { - foreach($this->items as $id => $obj) - { - if(!$obj->checkInput()) - { - return false; - } - } + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + if (sizeof($this->items)) { + foreach ($this->items as $id => $obj) { + if (!$obj->checkInput()) { + return false; + } + } - if($this->comparison_mode) - { - $prev = NULL; - foreach($this->items as $id => $obj) - { - $value = $obj->getPostValueForComparison(); - if($value != "") - { - if($prev !== NULL) - { - if($this->comparison_mode == self::COMPARISON_ASCENDING) - { - if($value < $prev) - { - return false; - } - } - else - { - if($value > $prev) - { - return false; - } - } - } - $prev = $value; - } - } - } - } + if ($this->comparison_mode) { + $prev = null; + foreach ($this->items as $id => $obj) { + $value = $obj->getPostValueForComparison(); + if ($value != "") { + if ($prev !== null) { + if ($this->comparison_mode == self::COMPARISON_ASCENDING) { + if ($value < $prev) { + return false; + } + } else { + if ($value > $prev) { + return false; + } + } + } + $prev = $value; + } + } + } + } - return $this->checkSubItemsInput(); - } + return $this->checkSubItemsInput(); + } - /** - * Insert property html - * - * @return int Size - */ - function insert($a_tpl) - { - $html = $this->render(); + /** + * Insert property html + * + * @return int Size + */ + public function insert($a_tpl) + { + $html = $this->render(); - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $html); - $a_tpl->parseCurrentBlock(); - } + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $html); + $a_tpl->parseCurrentBlock(); + } - /** - * Render item - */ - function render() - { - $lng = $this->lng; + /** + * Render item + */ + public function render() + { + $lng = $this->lng; - $tpl = new ilTemplate("tpl.prop_combination.html", true, true, "Services/Form"); + $tpl = new ilTemplate("tpl.prop_combination.html", true, true, "Services/Form"); - if(sizeof($this->items)) - { - foreach($this->items as $id => $obj) - { - // label - if(isset($this->labels[$id])) - { - $tpl->setCurrentBlock("prop_combination_label"); - $tpl->setVariable("LABEL", $this->labels[$id]); - $tpl->parseCurrentBlock(); - } + if (sizeof($this->items)) { + foreach ($this->items as $id => $obj) { + // label + if (isset($this->labels[$id])) { + $tpl->setCurrentBlock("prop_combination_label"); + $tpl->setVariable("LABEL", $this->labels[$id]); + $tpl->parseCurrentBlock(); + } - $tpl->setCurrentBlock("prop_combination"); - $tpl->setVariable("FIELD", $obj->render()); - $tpl->parseCurrentBlock(); - } - } + $tpl->setCurrentBlock("prop_combination"); + $tpl->setVariable("FIELD", $obj->render()); + $tpl->parseCurrentBlock(); + } + } - return $tpl->get(); - } + return $tpl->get(); + } /** - * Get HTML for table filter - */ - function getTableFilterHTML() - { - $html = $this->render(); - return $html; - } + * Get HTML for table filter + */ + public function getTableFilterHTML() + { + $html = $this->render(); + return $html; + } } diff --git a/Services/Form/classes/class.ilCountrySelectInputGUI.php b/Services/Form/classes/class.ilCountrySelectInputGUI.php index 4481d1e65e52c23b9f00465c3bbe86c14ad0f196..325616533b3bc3c26926816540a69244b70ca9f1 100644 --- a/Services/Form/classes/class.ilCountrySelectInputGUI.php +++ b/Services/Form/classes/class.ilCountrySelectInputGUI.php @@ -14,50 +14,49 @@ include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); */ class ilCountrySelectInputGUI extends ilSelectInputGUI { - /** - * @var ilLanguage - */ - protected $lng; - - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; - - $this->lng = $DIC->language(); - parent::__construct($a_title, $a_postvar); - $this->setType("cselect"); - } - - /** - * Get Options. - * - * @return array Options. Array ("value" => "option_text") - */ - public function getOptions() - { - $lng = $this->lng; - - $lng->loadLanguageModule("meta"); - $lng->loadLanguageModule("form"); - - include_once("./Services/Utilities/classes/class.ilCountry.php"); - - foreach (ilCountry::getCountryCodes() as $c) - { - $options[$c] = $lng->txt("meta_c_".$c); - } - asort($options); - - $options = array("" => "- ".$lng->txt("form_please_select")." -") - + $options; - - return $options; - } + /** + * @var ilLanguage + */ + protected $lng; + + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; + + $this->lng = $DIC->language(); + parent::__construct($a_title, $a_postvar); + $this->setType("cselect"); + } + + /** + * Get Options. + * + * @return array Options. Array ("value" => "option_text") + */ + public function getOptions() + { + $lng = $this->lng; + + $lng->loadLanguageModule("meta"); + $lng->loadLanguageModule("form"); + + include_once("./Services/Utilities/classes/class.ilCountry.php"); + + foreach (ilCountry::getCountryCodes() as $c) { + $options[$c] = $lng->txt("meta_c_" . $c); + } + asort($options); + + $options = array("" => "- " . $lng->txt("form_please_select") . " -") + + $options; + + return $options; + } } diff --git a/Services/Form/classes/class.ilCustomInputGUI.php b/Services/Form/classes/class.ilCustomInputGUI.php index f8fbfa8805bc51a934a293e816f1c8caf4f58179..e6798308fdf27f0cb3ee6da4d5702230de82d178 100755 --- a/Services/Form/classes/class.ilCustomInputGUI.php +++ b/Services/Form/classes/class.ilCustomInputGUI.php @@ -1,24 +1,24 @@ lng = $DIC->language(); - parent::__construct($a_title, $a_postvar); - $this->setType("custom"); - } - - /** - * Set Html. - * - * @param string $a_html Html - */ - function setHtml($a_html) - { - $this->html = $a_html; - } + $this->lng = $DIC->language(); + parent::__construct($a_title, $a_postvar); + $this->setType("custom"); + } + + /** + * Set Html. + * + * @param string $a_html Html + */ + public function setHtml($a_html) + { + $this->html = $a_html; + } - /** - * Get Html. - * - * @return string Html - */ - function getHtml() - { - return $this->html; - } + /** + * Get Html. + * + * @return string Html + */ + public function getHtml() + { + return $this->html; + } - /** - * Set value by array - * - * @param object $a_item Item - */ - function setValueByArray($a_values) - { - foreach($this->getSubItems() as $item) - { - $item->setValueByArray($a_values); - } - } + /** + * Set value by array + * + * @param object $a_item Item + */ + public function setValueByArray($a_values) + { + foreach ($this->getSubItems() as $item) { + $item->setValueByArray($a_values); + } + } - /** - * Insert property html - * - */ - function insert($a_tpl) - { - $a_tpl->setCurrentBlock("prop_custom"); - $a_tpl->setVariable("CUSTOM_CONTENT", $this->getHtml()); - $a_tpl->parseCurrentBlock(); - } - - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - if($this->getPostVar()) - { - $_POST[$this->getPostVar()] = ilUtil::stripSlashes($_POST[$this->getPostVar()]); - if ($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") - { - $this->setAlert($lng->txt("msg_input_is_required")); - return false; - } - } - return $this->checkSubItemsInput(); - } + /** + * Insert property html + * + */ + public function insert($a_tpl) + { + $a_tpl->setCurrentBlock("prop_custom"); + $a_tpl->setVariable("CUSTOM_CONTENT", $this->getHtml()); + $a_tpl->parseCurrentBlock(); + } + + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + if ($this->getPostVar()) { + $_POST[$this->getPostVar()] = ilUtil::stripSlashes($_POST[$this->getPostVar()]); + if ($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") { + $this->setAlert($lng->txt("msg_input_is_required")); + return false; + } + } + return $this->checkSubItemsInput(); + } } diff --git a/Services/Form/classes/class.ilDateDurationInputGUI.php b/Services/Form/classes/class.ilDateDurationInputGUI.php index 9739cc9599c307d4a1f9f45dc1e3088332888d9e..a90cc0f1550f45762d9a0915fecd1838e02975bf 100644 --- a/Services/Form/classes/class.ilDateDurationInputGUI.php +++ b/Services/Form/classes/class.ilDateDurationInputGUI.php @@ -13,604 +13,581 @@ include_once 'Services/Table/interfaces/interface.ilTableFilterItem.php'; */ class ilDateDurationInputGUI extends ilSubEnabledFormPropertyGUI implements ilTableFilterItem { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - protected $start = null; - protected $startyear = null; - protected $start_text = null; - protected $end_text = null; - protected $minute_step_size = 5; - protected $end = null; - protected $showtime = false; - protected $toggle_fulltime = false; - protected $toggle_fulltime_txt = ''; - protected $toggle_fulltime_checked = false; - protected $allowOpenIntervals = false; + protected $start = null; + protected $startyear = null; + protected $start_text = null; + protected $end_text = null; + protected $minute_step_size = 5; + protected $end = null; + protected $showtime = false; + protected $toggle_fulltime = false; + protected $toggle_fulltime_txt = ''; + protected $toggle_fulltime_checked = false; + protected $allowOpenIntervals = false; - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - public function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - parent::__construct($a_title, $a_postvar); - $this->setType("dateduration"); - } - - /** - * Enable toggling between date and time - * @param object $a_title - * @param object $a_checked - * @return - */ - public function enableToggleFullTime($a_title,$a_checked) - { - $this->toggle_fulltime_txt = $a_title; - $this->toggle_fulltime_checked = $a_checked; - $this->toggle_fulltime = true; - } - - /** - * Check if toggling between date and time enabled - * @return - */ - public function enabledToggleFullTime() - { - return $this->toggle_fulltime; - } - - /** - * Set start date - * E.g $dt_form->setDate(new ilDateTime(time(),IL_CAL_UTC)); - * or $dt_form->setDate(new ilDateTime('2008-06-12 08:00:00',IL_CAL_DATETIME)); - * - * For fullday (no timezone conversion) events use: - * - * $dt_form->setDate(new ilDate('2008-08-01',IL_CAL_DATE)); - * - * @param object $a_date ilDate or ilDateTime object - */ - public function setStart(ilDateTime $a_date = null) - { - $this->start = $a_date; - } - - /** - * Set text, which will be shown before the start date - * @param object $a_txt - * @return - */ - public function setStartText($a_txt) - { - $this->start_text = $a_txt; - } - - /** - * get start text - * @return - */ - public function getStartText() - { - return $this->start_text; - } + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + parent::__construct($a_title, $a_postvar); + $this->setType("dateduration"); + } + + /** + * Enable toggling between date and time + * @param object $a_title + * @param object $a_checked + * @return + */ + public function enableToggleFullTime($a_title, $a_checked) + { + $this->toggle_fulltime_txt = $a_title; + $this->toggle_fulltime_checked = $a_checked; + $this->toggle_fulltime = true; + } + + /** + * Check if toggling between date and time enabled + * @return + */ + public function enabledToggleFullTime() + { + return $this->toggle_fulltime; + } + + /** + * Set start date + * E.g $dt_form->setDate(new ilDateTime(time(),IL_CAL_UTC)); + * or $dt_form->setDate(new ilDateTime('2008-06-12 08:00:00',IL_CAL_DATETIME)); + * + * For fullday (no timezone conversion) events use: + * + * $dt_form->setDate(new ilDate('2008-08-01',IL_CAL_DATE)); + * + * @param object $a_date ilDate or ilDateTime object + */ + public function setStart(ilDateTime $a_date = null) + { + $this->start = $a_date; + } + + /** + * Set text, which will be shown before the start date + * @param object $a_txt + * @return + */ + public function setStartText($a_txt) + { + $this->start_text = $a_txt; + } + + /** + * get start text + * @return + */ + public function getStartText() + { + return $this->start_text; + } - /** - * Set text, which will be shown before the end date - * @param object $a_txt - * @return - */ - public function setEndText($a_txt) - { - $this->end_text = $a_txt; - } - - /** - * Get end text - * @return - */ - public function getEndText() - { - return $this->end_text; - } + /** + * Set text, which will be shown before the end date + * @param object $a_txt + * @return + */ + public function setEndText($a_txt) + { + $this->end_text = $a_txt; + } + + /** + * Get end text + * @return + */ + public function getEndText() + { + return $this->end_text; + } - /** - * Get Date, yyyy-mm-dd. - * - * @return object Date, yyyy-mm-dd - */ - public function getStart() - { - return $this->start; - } - - /** - * Set end date - * E.g $dt_form->setDate(new ilDateTime(time(),IL_CAL_UTC)); - * or $dt_form->setDate(new ilDateTime('2008-06-12 08:00:00',IL_CAL_DATETIME)); - * - * For fullday (no timezone conversion) events use: - * - * $dt_form->setDate(new ilDate('2008-08-01',IL_CAL_DATE)); - * - * @param object $a_date ilDate or ilDateTime object - */ - public function setEnd(ilDateTime $a_date = null) - { - $this->end = $a_date; - } + /** + * Get Date, yyyy-mm-dd. + * + * @return object Date, yyyy-mm-dd + */ + public function getStart() + { + return $this->start; + } + + /** + * Set end date + * E.g $dt_form->setDate(new ilDateTime(time(),IL_CAL_UTC)); + * or $dt_form->setDate(new ilDateTime('2008-06-12 08:00:00',IL_CAL_DATETIME)); + * + * For fullday (no timezone conversion) events use: + * + * $dt_form->setDate(new ilDate('2008-08-01',IL_CAL_DATE)); + * + * @param object $a_date ilDate or ilDateTime object + */ + public function setEnd(ilDateTime $a_date = null) + { + $this->end = $a_date; + } - /** - * Get Date, yyyy-mm-dd. - * - * @return object Date, yyyy-mm-dd - */ - public function getEnd() - { - return $this->end; - } - - /** - * Set Show Time Information. - * - * @param boolean $a_showtime Show Time Information - */ - public function setShowTime($a_showtime) - { - $this->showtime = $a_showtime; - } + /** + * Get Date, yyyy-mm-dd. + * + * @return object Date, yyyy-mm-dd + */ + public function getEnd() + { + return $this->end; + } + + /** + * Set Show Time Information. + * + * @param boolean $a_showtime Show Time Information + */ + public function setShowTime($a_showtime) + { + $this->showtime = $a_showtime; + } - /** - * Get Show Time Information. - * - * @return boolean Show Time Information - */ - public function getShowTime() - { - return $this->showtime; - } - - /** - * Show seconds not implemented yet - * @return - */ - public function getShowSeconds() - { - return false; - } - - /** - * Set start year - * - * @param integer Start year - */ - public function setStartYear($a_year) - { - $this->startyear = $a_year; - } - - /** - * Get start year - * - * @return integer Start year - */ - public function getStartYear() - { - return $this->startyear; - } - - /** - * Set minute step size - * E.g 5 => The selection will only show 00,05,10... minutes - * - * @access public - * @param int minute step_size 1,5,10,15,20... - * - */ - public function setMinuteStepSize($a_step_size) - { - $this->minute_step_size = $a_step_size; - } - - /** - * Get minute step size - * - * @access public - * - */ - public function getMinuteStepSize() - { - return $this->minute_step_size; - } - - /** - * Set value by array - * - * @param array $a_values value array - */ - public function setValueByArray($a_values) - { - $incoming = $a_values[$this->getPostVar()]; - if (is_array($incoming)) { - $format = $incoming['tgl'] ? 0 : $this->getDatePickerTimeFormat(); - $this->toggle_fulltime_checked = (bool)$incoming['tgl']; + /** + * Get Show Time Information. + * + * @return boolean Show Time Information + */ + public function getShowTime() + { + return $this->showtime; + } + + /** + * Show seconds not implemented yet + * @return + */ + public function getShowSeconds() + { + return false; + } + + /** + * Set start year + * + * @param integer Start year + */ + public function setStartYear($a_year) + { + $this->startyear = $a_year; + } + + /** + * Get start year + * + * @return integer Start year + */ + public function getStartYear() + { + return $this->startyear; + } + + /** + * Set minute step size + * E.g 5 => The selection will only show 00,05,10... minutes + * + * @access public + * @param int minute step_size 1,5,10,15,20... + * + */ + public function setMinuteStepSize($a_step_size) + { + $this->minute_step_size = $a_step_size; + } + + /** + * Get minute step size + * + * @access public + * + */ + public function getMinuteStepSize() + { + return $this->minute_step_size; + } + + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $incoming = $a_values[$this->getPostVar()]; + if (is_array($incoming)) { + $format = $incoming['tgl'] ? 0 : $this->getDatePickerTimeFormat(); + $this->toggle_fulltime_checked = (bool) $incoming['tgl']; - if ($this->openIntervalsAllowed()) { - if (is_string($incoming['start']) && trim($incoming['start']) !== '') { - $this->setStart(ilCalendarUtil::parseIncomingDate($incoming["start"], $format)); - } else { - $this->setStart(new ilDate(null, IL_CAL_UNIX)); - } + if ($this->openIntervalsAllowed()) { + if (is_string($incoming['start']) && trim($incoming['start']) !== '') { + $this->setStart(ilCalendarUtil::parseIncomingDate($incoming["start"], $format)); + } else { + $this->setStart(new ilDate(null, IL_CAL_UNIX)); + } - if (is_string($incoming['end']) && trim($incoming['end']) !== '') { - $this->setEnd(ilCalendarUtil::parseIncomingDate($incoming["end"], $format)); - } else { - $this->setEnd(new ilDate(null, IL_CAL_UNIX)); - } - } else { - $this->setStart(ilCalendarUtil::parseIncomingDate($incoming["start"], $format)); - $this->setEnd(ilCalendarUtil::parseIncomingDate($incoming["end"], $format)); - } - } + if (is_string($incoming['end']) && trim($incoming['end']) !== '') { + $this->setEnd(ilCalendarUtil::parseIncomingDate($incoming["end"], $format)); + } else { + $this->setEnd(new ilDate(null, IL_CAL_UNIX)); + } + } else { + $this->setStart(ilCalendarUtil::parseIncomingDate($incoming["start"], $format)); + $this->setEnd(ilCalendarUtil::parseIncomingDate($incoming["end"], $format)); + } + } - foreach($this->getSubItems() as $item) - { - $item->setValueByArray($a_values); - } - } - - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - public function checkInput() - { - $lng = $this->lng; - - if($this->getDisabled()) - { - return true; - } - - $post = $_POST[$this->getPostVar()]; - if(!is_array($post)) - { - return false; - } - - $start = $post["start"]; - $end = $post["end"]; - - // if full day is active, ignore time format - $format = $post['tgl'] - ? 0 - : $this->getDatePickerTimeFormat(); - - // always done to make sure there are no obsolete values left - $this->setStart(null); - $this->setEnd(null); + foreach ($this->getSubItems() as $item) { + $item->setValueByArray($a_values); + } + } + + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + if ($this->getDisabled()) { + return true; + } + + $post = $_POST[$this->getPostVar()]; + if (!is_array($post)) { + return false; + } + + $start = $post["start"]; + $end = $post["end"]; + + // if full day is active, ignore time format + $format = $post['tgl'] + ? 0 + : $this->getDatePickerTimeFormat(); + + // always done to make sure there are no obsolete values left + $this->setStart(null); + $this->setEnd(null); - $valid_start = false; - if (trim($start)) { - $parsed = ilCalendarUtil::parseIncomingDate($start, $format); - if ($parsed) { - $this->setStart($parsed); - $valid_start = true; - } - } else { - if (!$this->getRequired() && !trim($end)) { - $valid_start = true; - } else { - if ($this->openIntervalsAllowed() && !strlen(trim($start))) { - $valid_start = true; - } - } - } + $valid_start = false; + if (trim($start)) { + $parsed = ilCalendarUtil::parseIncomingDate($start, $format); + if ($parsed) { + $this->setStart($parsed); + $valid_start = true; + } + } else { + if (!$this->getRequired() && !trim($end)) { + $valid_start = true; + } else { + if ($this->openIntervalsAllowed() && !strlen(trim($start))) { + $valid_start = true; + } + } + } - $valid_end = false; - if (trim($end)) { - $parsed = ilCalendarUtil::parseIncomingDate($end, $format); - if ($parsed) { - $this->setEnd($parsed); - $valid_end = true; - } - } else { - if (!$this->getRequired() && !trim($start)) { - $valid_end = true; - } else { - if ($this->openIntervalsAllowed() && !strlen(trim($end))) { - $valid_end = true; - } - } - } + $valid_end = false; + if (trim($end)) { + $parsed = ilCalendarUtil::parseIncomingDate($end, $format); + if ($parsed) { + $this->setEnd($parsed); + $valid_end = true; + } + } else { + if (!$this->getRequired() && !trim($start)) { + $valid_end = true; + } else { + if ($this->openIntervalsAllowed() && !strlen(trim($end))) { + $valid_end = true; + } + } + } - if($this->getStartYear()) - { - if($valid_start && - $this->getStart()->get(IL_CAL_FKT_DATE, "Y") < $this->getStartYear()) - { - $valid_start = false; - } - if($valid_end && - $this->getEnd()->get(IL_CAL_FKT_DATE, "Y") < $this->getStartYear()) - { - $valid_end = false; - } - } - $valid = ($valid_start && $valid_end); + if ($this->getStartYear()) { + if ($valid_start && + $this->getStart()->get(IL_CAL_FKT_DATE, "Y") < $this->getStartYear()) { + $valid_start = false; + } + if ($valid_end && + $this->getEnd()->get(IL_CAL_FKT_DATE, "Y") < $this->getStartYear()) { + $valid_end = false; + } + } + $valid = ($valid_start && $valid_end); - if($valid && - $this->getStart() && - $this->getEnd() && - ilDateTime::_after($this->getStart(), $this->getEnd())) - { - $valid = false; - } + if ($valid && + $this->getStart() && + $this->getEnd() && + ilDateTime::_after($this->getStart(), $this->getEnd())) { + $valid = false; + } - if ($this->openIntervalsAllowed()) { - if (!$this->getStart()) { - $_POST[$this->getPostVar()]["start"] = null; - } + if ($this->openIntervalsAllowed()) { + if (!$this->getStart()) { + $_POST[$this->getPostVar()]["start"] = null; + } - if (!$this->getEnd()) { - $_POST[$this->getPostVar()]["end"] = null; - } - $valid = true; - } elseif (!$valid) { - $this->invalid_input_start = $start; - $this->invalid_input_end = $end; + if (!$this->getEnd()) { + $_POST[$this->getPostVar()]["end"] = null; + } + $valid = true; + } elseif (!$valid) { + $this->invalid_input_start = $start; + $this->invalid_input_end = $end; - $_POST[$this->getPostVar()]["start"] = null; - $_POST[$this->getPostVar()]["end"] = null; + $_POST[$this->getPostVar()]["start"] = null; + $_POST[$this->getPostVar()]["end"] = null; - $this->setAlert($lng->txt("form_msg_wrong_date")); - } else { - if ( - !$this->getStart() || - !$this->getEnd() - ) { - $_POST[$this->getPostVar()]["start"] = null; - $_POST[$this->getPostVar()]["end"] = null; - } - } + $this->setAlert($lng->txt("form_msg_wrong_date")); + } else { + if ( + !$this->getStart() || + !$this->getEnd() + ) { + $_POST[$this->getPostVar()]["start"] = null; + $_POST[$this->getPostVar()]["end"] = null; + } + } - if($valid) - { - $valid = $this->checkSubItemsInput(); - } - - return $valid; - } - - protected function getDatePickerTimeFormat() - { - return (int)$this->getShowTime() + (int)$this->getShowSeconds(); - } - - /** - * parse properties to datepicker config - * - * @return array - */ - protected function parseDatePickerConfig() - { - $config = null; - if($this->getMinuteStepSize()) - { - $config['stepping'] = (int)$this->getMinuteStepSize(); - } - if($this->getStartYear()) - { - $config['minDate'] = $this->getStartYear().'-01-01'; - } - return $config; - } - - /** - * Insert property html - * - */ - public function render() - { - $ilUser = $this->user; - $lng = $this->lng; - - $tpl = new ilTemplate("tpl.prop_datetime_duration.html", true, true, "Services/Form"); - - if($this->enabledToggleFullTime()) - { - $this->setShowTime(true); - - $toggle_id = md5($this->getPostVar().'_fulltime'); // :TODO: unique? - - $tpl->setCurrentBlock('toggle_fullday'); - $tpl->setVariable('DATE_TOGGLE_ID', $this->getPostVar().'[tgl]'); - $tpl->setVariable('FULLDAY_TOGGLE_ID', $toggle_id); - $tpl->setVariable('FULLDAY_TOGGLE_CHECKED', $this->toggle_fulltime_checked ? 'checked="checked"' : ''); - $tpl->setVariable('FULLDAY_TOGGLE_DISABLED', $this->getDisabled() ? 'disabled="disabled"' : ''); - $tpl->setVariable('TXT_TOGGLE_FULLDAY', $this->toggle_fulltime_txt); - $tpl->parseCurrentBlock(); - } - - // config picker - if(!$this->getDisabled()) - { - // :TODO: unique? - $picker_start_id = md5($this->getPostVar().'_start'); - $picker_end_id = md5($this->getPostVar().'_end'); - - $tpl->setVariable('DATEPICKER_START_ID', $picker_start_id); - $tpl->setVariable('DATEPICKER_END_ID', $picker_end_id); - - ilCalendarUtil::addDateTimePicker( - $picker_start_id, - $this->getDatePickerTimeFormat(), - $this->parseDatePickerConfig(), - $picker_end_id, - $this->parseDatePickerConfig(), - $toggle_id, - "subform_".$this->getPostVar() - ); - } - else - { - $tpl->setVariable('DATEPICKER_START_DISABLED', 'disabled="disabled" '); - $tpl->setVariable('DATEPICKER_END_DISABLED', 'disabled="disabled" '); - } - - $start_txt = $this->getStartText(); - if($start_txt === null) - { - $start_txt = $lng->txt("form_date_duration_start"); - } - if(trim($start_txt)) - { - $tpl->setVariable('START_LABEL', $start_txt); - $tpl->setVariable('START_ARIA_LABEL', ilUtil::prepareFormOutput($start_txt)); - $tpl->touchBlock('start_width_bl'); - } - - $end_txt = $this->getEndText(); - if($end_txt === null) - { - $end_txt = $lng->txt("form_date_duration_end"); - } - if(trim($end_txt)) - { - $tpl->setVariable('END_LABEL', $end_txt); - $tpl->setVariable('END_ARIA_LABEL', ilUtil::prepareFormOutput($end_txt)); - $tpl->touchBlock('end_width_bl'); - } - - - $tpl->setVariable('DATE_START_ID', $this->getPostVar().'[start]'); - $tpl->setVariable('DATE_END_ID', $this->getPostVar().'[end]'); - - // placeholder - // :TODO: i18n? - $pl_format = ilCalendarUtil::getUserDateFormat($this->getDatePickerTimeFormat()); - $tpl->setVariable('START_PLACEHOLDER', $pl_format); - $tpl->setVariable('END_PLACEHOLDER', $pl_format); - - - // values + if ($valid) { + $valid = $this->checkSubItemsInput(); + } + + return $valid; + } + + protected function getDatePickerTimeFormat() + { + return (int) $this->getShowTime() + (int) $this->getShowSeconds(); + } + + /** + * parse properties to datepicker config + * + * @return array + */ + protected function parseDatePickerConfig() + { + $config = null; + if ($this->getMinuteStepSize()) { + $config['stepping'] = (int) $this->getMinuteStepSize(); + } + if ($this->getStartYear()) { + $config['minDate'] = $this->getStartYear() . '-01-01'; + } + return $config; + } + + /** + * Insert property html + * + */ + public function render() + { + $ilUser = $this->user; + $lng = $this->lng; + + $tpl = new ilTemplate("tpl.prop_datetime_duration.html", true, true, "Services/Form"); + + if ($this->enabledToggleFullTime()) { + $this->setShowTime(true); + + $toggle_id = md5($this->getPostVar() . '_fulltime'); // :TODO: unique? + + $tpl->setCurrentBlock('toggle_fullday'); + $tpl->setVariable('DATE_TOGGLE_ID', $this->getPostVar() . '[tgl]'); + $tpl->setVariable('FULLDAY_TOGGLE_ID', $toggle_id); + $tpl->setVariable('FULLDAY_TOGGLE_CHECKED', $this->toggle_fulltime_checked ? 'checked="checked"' : ''); + $tpl->setVariable('FULLDAY_TOGGLE_DISABLED', $this->getDisabled() ? 'disabled="disabled"' : ''); + $tpl->setVariable('TXT_TOGGLE_FULLDAY', $this->toggle_fulltime_txt); + $tpl->parseCurrentBlock(); + } + + // config picker + if (!$this->getDisabled()) { + // :TODO: unique? + $picker_start_id = md5($this->getPostVar() . '_start'); + $picker_end_id = md5($this->getPostVar() . '_end'); + + $tpl->setVariable('DATEPICKER_START_ID', $picker_start_id); + $tpl->setVariable('DATEPICKER_END_ID', $picker_end_id); + + ilCalendarUtil::addDateTimePicker( + $picker_start_id, + $this->getDatePickerTimeFormat(), + $this->parseDatePickerConfig(), + $picker_end_id, + $this->parseDatePickerConfig(), + $toggle_id, + "subform_" . $this->getPostVar() + ); + } else { + $tpl->setVariable('DATEPICKER_START_DISABLED', 'disabled="disabled" '); + $tpl->setVariable('DATEPICKER_END_DISABLED', 'disabled="disabled" '); + } + + $start_txt = $this->getStartText(); + if ($start_txt === null) { + $start_txt = $lng->txt("form_date_duration_start"); + } + if (trim($start_txt)) { + $tpl->setVariable('START_LABEL', $start_txt); + $tpl->setVariable('START_ARIA_LABEL', ilUtil::prepareFormOutput($start_txt)); + $tpl->touchBlock('start_width_bl'); + } + + $end_txt = $this->getEndText(); + if ($end_txt === null) { + $end_txt = $lng->txt("form_date_duration_end"); + } + if (trim($end_txt)) { + $tpl->setVariable('END_LABEL', $end_txt); + $tpl->setVariable('END_ARIA_LABEL', ilUtil::prepareFormOutput($end_txt)); + $tpl->touchBlock('end_width_bl'); + } + + + $tpl->setVariable('DATE_START_ID', $this->getPostVar() . '[start]'); + $tpl->setVariable('DATE_END_ID', $this->getPostVar() . '[end]'); + + // placeholder + // :TODO: i18n? + $pl_format = ilCalendarUtil::getUserDateFormat($this->getDatePickerTimeFormat()); + $tpl->setVariable('START_PLACEHOLDER', $pl_format); + $tpl->setVariable('END_PLACEHOLDER', $pl_format); + + + // values - $date_value = htmlspecialchars($this->invalid_input_start); - if(!$date_value && - $this->getStart()) - { - $out_format = ilCalendarUtil::getUserDateFormat($this->getDatePickerTimeFormat(), true); - $date_value = $this->getStart()->get(IL_CAL_FKT_DATE, $out_format, $ilUser->getTimeZone()); - } - $tpl->setVariable('DATEPICKER_START_VALUE', $date_value); - - $date_value = htmlspecialchars($this->invalid_input_end); - if(!$date_value && - $this->getEnd()) - { - $out_format = ilCalendarUtil::getUserDateFormat($this->getDatePickerTimeFormat(), true); - $date_value = $this->getEnd()->get(IL_CAL_FKT_DATE, $out_format, $ilUser->getTimeZone()); - } - $tpl->setVariable('DATEPICKER_END_VALUE', $date_value); - - if($this->getRequired()) - { - $tpl->setVariable("START_REQUIRED", "required=\"required\""); - $tpl->setVariable("END_REQUIRED", "required=\"required\""); - } - - return $tpl->get(); - } - - /** - * Insert property html - * - * @return int Size - */ - public function insert($a_tpl) - { - $html = $this->render(); + $date_value = htmlspecialchars($this->invalid_input_start); + if (!$date_value && + $this->getStart()) { + $out_format = ilCalendarUtil::getUserDateFormat($this->getDatePickerTimeFormat(), true); + $date_value = $this->getStart()->get(IL_CAL_FKT_DATE, $out_format, $ilUser->getTimeZone()); + } + $tpl->setVariable('DATEPICKER_START_VALUE', $date_value); + + $date_value = htmlspecialchars($this->invalid_input_end); + if (!$date_value && + $this->getEnd()) { + $out_format = ilCalendarUtil::getUserDateFormat($this->getDatePickerTimeFormat(), true); + $date_value = $this->getEnd()->get(IL_CAL_FKT_DATE, $out_format, $ilUser->getTimeZone()); + } + $tpl->setVariable('DATEPICKER_END_VALUE', $date_value); + + if ($this->getRequired()) { + $tpl->setVariable("START_REQUIRED", "required=\"required\""); + $tpl->setVariable("END_REQUIRED", "required=\"required\""); + } + + return $tpl->get(); + } + + /** + * Insert property html + * + * @return int Size + */ + public function insert($a_tpl) + { + $html = $this->render(); - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $html); - $a_tpl->parseCurrentBlock(); - } + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $html); + $a_tpl->parseCurrentBlock(); + } - /** - * Used for table filter presentation - * @return string - */ - public function getTableFilterHTML() - { - return $this->render(); - } + /** + * Used for table filter presentation + * @return string + */ + public function getTableFilterHTML() + { + return $this->render(); + } - /** - * Used for storing the date duration data in session for table gui filters - * @return array - */ - public function getValue() - { - return array( - 'start' => $this->getStart()->get(IL_CAL_UNIX), - 'end' => $this->getEnd()->get(IL_CAL_UNIX) - ); - } + /** + * Used for storing the date duration data in session for table gui filters + * @return array + */ + public function getValue() + { + return array( + 'start' => $this->getStart()->get(IL_CAL_UNIX), + 'end' => $this->getEnd()->get(IL_CAL_UNIX) + ); + } - /** - * Called from table gui with the stored session value - * Attention: If the user resets the table filter, a boolean false is passed by the table gui - * @see getValue() - * @param array|bool $value - */ - public function setValue($value) - { - if(is_array($value)) - { - $this->setStart(new ilDateTime($value['start'], IL_CAL_UNIX)); - $this->setEnd(new ilDateTime($value['end'], IL_CAL_UNIX)); - } - } + /** + * Called from table gui with the stored session value + * Attention: If the user resets the table filter, a boolean false is passed by the table gui + * @see getValue() + * @param array|bool $value + */ + public function setValue($value) + { + if (is_array($value)) { + $this->setStart(new ilDateTime($value['start'], IL_CAL_UNIX)); + $this->setEnd(new ilDateTime($value['end'], IL_CAL_UNIX)); + } + } - public function hideSubForm() - { - if($this->invalid_input_start || - $this->invalid_input_end) - { - return false; - } + public function hideSubForm() + { + if ($this->invalid_input_start || + $this->invalid_input_end) { + return false; + } - return ((!$this->getStart() || $this->getStart()->isNull()) && - (!$this->getEnd() || $this->getEnd()->isNull())); - } + return ((!$this->getStart() || $this->getStart()->isNull()) && + (!$this->getEnd() || $this->getEnd()->isNull())); + } - /** - * @return bool - */ - public function openIntervalsAllowed(): bool - { - return $this->allowOpenIntervals; - } + /** + * @return bool + */ + public function openIntervalsAllowed() : bool + { + return $this->allowOpenIntervals; + } - /** - * @param bool $allowOpenInterval - */ - public function setAllowOpenIntervals(bool $allowOpenInterval) - { - $this->allowOpenIntervals = $allowOpenInterval; - } + /** + * @param bool $allowOpenInterval + */ + public function setAllowOpenIntervals(bool $allowOpenInterval) + { + $this->allowOpenIntervals = $allowOpenInterval; + } } diff --git a/Services/Form/classes/class.ilDateTimeInputGUI.php b/Services/Form/classes/class.ilDateTimeInputGUI.php index e6855efd9a7ae228c1aa99517cf78aae3d224fce..66d693af445030a5c03d725b3bfc77b273e70079 100755 --- a/Services/Form/classes/class.ilDateTimeInputGUI.php +++ b/Services/Form/classes/class.ilDateTimeInputGUI.php @@ -4,414 +4,384 @@ /** * This class represents a date/time property in a property form. * -* @author Alex Killing +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilDateTimeInputGUI extends ilSubEnabledFormPropertyGUI implements ilTableFilterItem, ilToolbarItem { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - protected $date; - protected $time = "00:00:00"; - protected $showtime = false; - protected $showseconds = false; - protected $minute_step_size = 5; - protected $startyear = ''; - protected $invalid_input = ''; + protected $date; + protected $time = "00:00:00"; + protected $showtime = false; + protected $showseconds = false; + protected $minute_step_size = 5; + protected $startyear = ''; + protected $invalid_input = ''; - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - parent::__construct($a_title, $a_postvar); - $this->setType("datetime"); - } + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + parent::__construct($a_title, $a_postvar); + $this->setType("datetime"); + } - /** - * set date - * E.g $dt_form->setDate(new ilDateTime(time(),IL_CAL_UTC)); - * or $dt_form->setDate(new ilDateTime('2008-06-12 08:00:00',IL_CAL_DATETIME)); - * - * For fullday (no timezone conversion) events use: - * - * $dt_form->setDate(new ilDate('2008-08-01',IL_CAL_DATE)); - * - * @param object $a_date ilDate or ilDateTime object - */ - function setDate(ilDateTime $a_date = NULL) - { - $this->date = $a_date; - } + /** + * set date + * E.g $dt_form->setDate(new ilDateTime(time(),IL_CAL_UTC)); + * or $dt_form->setDate(new ilDateTime('2008-06-12 08:00:00',IL_CAL_DATETIME)); + * + * For fullday (no timezone conversion) events use: + * + * $dt_form->setDate(new ilDate('2008-08-01',IL_CAL_DATE)); + * + * @param object $a_date ilDate or ilDateTime object + */ + public function setDate(ilDateTime $a_date = null) + { + $this->date = $a_date; + } - /** - * Get Date, yyyy-mm-dd. - * - * @return object Date, yyyy-mm-dd - */ - function getDate() - { - return $this->date; - } + /** + * Get Date, yyyy-mm-dd. + * + * @return object Date, yyyy-mm-dd + */ + public function getDate() + { + return $this->date; + } - /** - * Set Show Time Information. - * - * @param boolean $a_showtime Show Time Information - */ - function setShowTime($a_showtime) - { - $this->showtime = $a_showtime; - } + /** + * Set Show Time Information. + * + * @param boolean $a_showtime Show Time Information + */ + public function setShowTime($a_showtime) + { + $this->showtime = $a_showtime; + } - /** - * Get Show Time Information. - * - * @return boolean Show Time Information - */ - function getShowTime() - { - return $this->showtime; - } - - /** - * Set start year - * - * @param integer Start year - */ - function setStartYear($a_year) - { - $this->startyear = $a_year; - } - - /** - * Get start year - * - * @return integer Start year - */ - function getStartYear() - { - return $this->startyear; - } - - /** - * Set minute step size - * E.g 5 => The selection will only show 00,05,10... minutes - * - * @access public - * @param int minute step_size 1,5,10,15,20... - * - */ - public function setMinuteStepSize($a_step_size) - { - $this->minute_step_size = $a_step_size; - } - - /** - * Get minute step size - * - * @access public - * - */ - public function getMinuteStepSize() - { - return $this->minute_step_size; - } + /** + * Get Show Time Information. + * + * @return boolean Show Time Information + */ + public function getShowTime() + { + return $this->showtime; + } + + /** + * Set start year + * + * @param integer Start year + */ + public function setStartYear($a_year) + { + $this->startyear = $a_year; + } + + /** + * Get start year + * + * @return integer Start year + */ + public function getStartYear() + { + return $this->startyear; + } + + /** + * Set minute step size + * E.g 5 => The selection will only show 00,05,10... minutes + * + * @access public + * @param int minute step_size 1,5,10,15,20... + * + */ + public function setMinuteStepSize($a_step_size) + { + $this->minute_step_size = $a_step_size; + } + + /** + * Get minute step size + * + * @access public + * + */ + public function getMinuteStepSize() + { + return $this->minute_step_size; + } - /** - * Set Show Seconds. - * - * @param boolean $a_showseconds Show Seconds - */ - function setShowSeconds($a_showseconds) - { - $this->showseconds = $a_showseconds; - } + /** + * Set Show Seconds. + * + * @param boolean $a_showseconds Show Seconds + */ + public function setShowSeconds($a_showseconds) + { + $this->showseconds = $a_showseconds; + } - /** - * Get Show Seconds. - * - * @return boolean Show Seconds - */ - function getShowSeconds() - { - return $this->showseconds; - } + /** + * Get Show Seconds. + * + * @return boolean Show Seconds + */ + public function getShowSeconds() + { + return $this->showseconds; + } - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $incoming = $a_values[$this->getPostVar()]; - $this->setDate(ilCalendarUtil::parseIncomingDate($incoming, $this->getDatePickerTimeFormat())); - - foreach($this->getSubItems() as $item) - { - $item->setValueByArray($a_values); - } - } - - protected function getDatePickerTimeFormat() - { - return (int)$this->getShowTime() + (int)$this->getShowSeconds(); - } - - public function hasInvalidInput() - { - return (bool)$this->invalid_input; - } + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $incoming = $a_values[$this->getPostVar()]; + $this->setDate(ilCalendarUtil::parseIncomingDate($incoming, $this->getDatePickerTimeFormat())); + + foreach ($this->getSubItems() as $item) { + $item->setValueByArray($a_values); + } + } + + protected function getDatePickerTimeFormat() + { + return (int) $this->getShowTime() + (int) $this->getShowSeconds(); + } + + public function hasInvalidInput() + { + return (bool) $this->invalid_input; + } - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - if ($this->getDisabled()) - { - return true; - } + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + if ($this->getDisabled()) { + return true; + } - $post = $_POST[$this->getPostVar()]; - - // always done to make sure there are no obsolete values left - $this->setDate(null); - - $valid = false; - if(trim($post)) - { - $parsed = ilCalendarUtil::parseIncomingDate($post, $this->getDatePickerTimeFormat()); - if($parsed) - { - $this->setDate($parsed); - $valid = true; - } - } - else if(!$this->getRequired()) - { - $valid = true; - } - - if($valid && - $this->getDate() && - $this->getStartYear() && - $this->getDate()->get(IL_CAL_FKT_DATE, "Y") < $this->getStartYear()) - { - $valid = false; - } - - if(!$valid) - { - $this->invalid_input = $post; - $_POST[$this->getPostVar()] = null; - - $this->setAlert($lng->txt("form_msg_wrong_date")); - } - else - { - if($this->getDate() !== null) - { - // getInput() should return a generic format - $post_format = $this->getShowTime() - ? IL_CAL_DATETIME - : IL_CAL_DATE; - $_POST[$this->getPostVar()] = $this->getDate()->get($post_format); - } - else - { - $_POST[$this->getPostVar()] = null; - } - } - - if($valid) - { - $valid = $this->checkSubItemsInput(); - } - - return $valid; - } - - /** - * parse properties to datepicker config - * - * @return array - */ - protected function parseDatePickerConfig() - { - $config = null; - if($this->getMinuteStepSize()) - { - $config['stepping'] = (int)$this->getMinuteStepSize(); - } - if($this->getStartYear()) - { - $config['minDate'] = $this->getStartYear().'-01-01'; - } - return $config; - } + $post = $_POST[$this->getPostVar()]; + + // always done to make sure there are no obsolete values left + $this->setDate(null); + + $valid = false; + if (trim($post)) { + $parsed = ilCalendarUtil::parseIncomingDate($post, $this->getDatePickerTimeFormat()); + if ($parsed) { + $this->setDate($parsed); + $valid = true; + } + } elseif (!$this->getRequired()) { + $valid = true; + } + + if ($valid && + $this->getDate() && + $this->getStartYear() && + $this->getDate()->get(IL_CAL_FKT_DATE, "Y") < $this->getStartYear()) { + $valid = false; + } + + if (!$valid) { + $this->invalid_input = $post; + $_POST[$this->getPostVar()] = null; + + $this->setAlert($lng->txt("form_msg_wrong_date")); + } else { + if ($this->getDate() !== null) { + // getInput() should return a generic format + $post_format = $this->getShowTime() + ? IL_CAL_DATETIME + : IL_CAL_DATE; + $_POST[$this->getPostVar()] = $this->getDate()->get($post_format); + } else { + $_POST[$this->getPostVar()] = null; + } + } + + if ($valid) { + $valid = $this->checkSubItemsInput(); + } + + return $valid; + } + + /** + * parse properties to datepicker config + * + * @return array + */ + protected function parseDatePickerConfig() + { + $config = null; + if ($this->getMinuteStepSize()) { + $config['stepping'] = (int) $this->getMinuteStepSize(); + } + if ($this->getStartYear()) { + $config['minDate'] = $this->getStartYear() . '-01-01'; + } + return $config; + } - /** - * Insert property html - * - */ - function render() - { - $ilUser = $this->user; - - $tpl = new ilTemplate("tpl.prop_datetime.html", true, true, "Services/Form"); + /** + * Insert property html + * + */ + public function render() + { + $ilUser = $this->user; + + $tpl = new ilTemplate("tpl.prop_datetime.html", true, true, "Services/Form"); - // config picker - if(!$this->getDisabled()) - { - $picker_id = md5($this->getPostVar()); // :TODO: unique? - $tpl->setVariable('DATEPICKER_ID', $picker_id); - - ilCalendarUtil::addDateTimePicker( - $picker_id, - $this->getDatePickerTimeFormat(), - $this->parseDatePickerConfig(), - null, - null, - null, - "subform_".$this->getPostVar() - ); - } - else - { - $tpl->setVariable('DATEPICKER_DISABLED', 'disabled="disabled" '); - } - - // :TODO: i18n? - $pl_format = ilCalendarUtil::getUserDateFormat($this->getDatePickerTimeFormat()); - $tpl->setVariable('PLACEHOLDER', $pl_format); - - // current value - $date_value = htmlspecialchars($this->invalid_input); - if(!$date_value && - $this->getDate()) - { - $out_format = ilCalendarUtil::getUserDateFormat($this->getDatePickerTimeFormat(), true); - $date_value = $this->getDate()->get(IL_CAL_FKT_DATE, $out_format, $ilUser->getTimeZone()); - } + // config picker + if (!$this->getDisabled()) { + $picker_id = md5($this->getPostVar()); // :TODO: unique? + $tpl->setVariable('DATEPICKER_ID', $picker_id); + + ilCalendarUtil::addDateTimePicker( + $picker_id, + $this->getDatePickerTimeFormat(), + $this->parseDatePickerConfig(), + null, + null, + null, + "subform_" . $this->getPostVar() + ); + } else { + $tpl->setVariable('DATEPICKER_DISABLED', 'disabled="disabled" '); + } + + // :TODO: i18n? + $pl_format = ilCalendarUtil::getUserDateFormat($this->getDatePickerTimeFormat()); + $tpl->setVariable('PLACEHOLDER', $pl_format); + + // current value + $date_value = htmlspecialchars($this->invalid_input); + if (!$date_value && + $this->getDate()) { + $out_format = ilCalendarUtil::getUserDateFormat($this->getDatePickerTimeFormat(), true); + $date_value = $this->getDate()->get(IL_CAL_FKT_DATE, $out_format, $ilUser->getTimeZone()); + } - $tpl->setVariable('DATEPICKER_VALUE', $date_value); - $tpl->setVariable('DATE_ID', $this->getPostVar()); - - if($this->getRequired()) - { - $tpl->setVariable("REQUIRED", "required=\"required\""); - } - - return $tpl->get(); - } + $tpl->setVariable('DATEPICKER_VALUE', $date_value); + $tpl->setVariable('DATE_ID', $this->getPostVar()); + + if ($this->getRequired()) { + $tpl->setVariable("REQUIRED", "required=\"required\""); + } + + return $tpl->get(); + } - /** - * Insert property html - * - * @return int Size - */ - function insert($a_tpl) - { - $html = $this->render(); + /** + * Insert property html + * + * @return int Size + */ + public function insert($a_tpl) + { + $html = $this->render(); - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $html); - $a_tpl->parseCurrentBlock(); - } + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $html); + $a_tpl->parseCurrentBlock(); + } - /** - * Get HTML for table filter - */ - function getTableFilterHTML() - { - $html = $this->render(); - return $html; - } + /** + * Get HTML for table filter + */ + public function getTableFilterHTML() + { + $html = $this->render(); + return $html; + } - /** - * serialize data - */ - function serializeData() - { - if($this->getDate()) - { - return serialize($this->getDate()->get(IL_CAL_UNIX)); - } - } - - /** - * unserialize data - */ - function unserializeData($a_data) - { - $tmp = unserialize($a_data); - if($tmp) - { - // we used to serialize the complete instance - if(is_object($tmp)) - { - $date = $tmp; - } - else - { - $date = $this->getShowTime() - ? new ilDateTime($tmp, IL_CAL_UNIX) - : new ilDate($tmp, IL_CAL_UNIX); - } - $this->setDate($date); - } - else - { - $this->setDate(null); - } - } + /** + * serialize data + */ + public function serializeData() + { + if ($this->getDate()) { + return serialize($this->getDate()->get(IL_CAL_UNIX)); + } + } + + /** + * unserialize data + */ + public function unserializeData($a_data) + { + $tmp = unserialize($a_data); + if ($tmp) { + // we used to serialize the complete instance + if (is_object($tmp)) { + $date = $tmp; + } else { + $date = $this->getShowTime() + ? new ilDateTime($tmp, IL_CAL_UNIX) + : new ilDate($tmp, IL_CAL_UNIX); + } + $this->setDate($date); + } else { + $this->setDate(null); + } + } - /** - * parse post value to make it comparable - * - * used by combination input gui - */ - function getPostValueForComparison() - { - // :TODO: - return trim($_POST[$this->getPostVar()]); - } - - /** - * Get HTML for toolbar - */ - function getToolbarHTML() - { - $html = $this->render("toolbar"); - return $html; - } - - public function hideSubForm() - { - return (!$this->getDate() || $this->getDate()->isNull()); - } + /** + * parse post value to make it comparable + * + * used by combination input gui + */ + public function getPostValueForComparison() + { + // :TODO: + return trim($_POST[$this->getPostVar()]); + } + + /** + * Get HTML for toolbar + */ + public function getToolbarHTML() + { + $html = $this->render("toolbar"); + return $html; + } + + public function hideSubForm() + { + return (!$this->getDate() || $this->getDate()->isNull()); + } } - -?> \ No newline at end of file diff --git a/Services/Form/classes/class.ilDragDropFileInputGUI.php b/Services/Form/classes/class.ilDragDropFileInputGUI.php index 0c5dcece167f7e43f6d105ec505b2c67e1efd010..f12d82ac2fd3e57faf28994b975e639e7d573bfe 100644 --- a/Services/Form/classes/class.ilDragDropFileInputGUI.php +++ b/Services/Form/classes/class.ilDragDropFileInputGUI.php @@ -6,244 +6,231 @@ include_once("./Services/Form/classes/class.ilFileInputGUI.php"); /** * This class represents a file input property where multiple files can be dopped in a property form. * -* @author Stefan Born +* @author Stefan Born * @version $Id$ * @ingroup ServicesForm */ class ilDragDropFileInputGUI extends ilFileInputGUI { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - private $uniqueId = 0; - private $archive_suffixes = array(); - private $submit_button_name = null; - private $cancel_button_name = null; - - private static $uniqueInc = 1; - - static private function getNextUniqueId() - { - return self::$uniqueInc++; - } - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + private $uniqueId = 0; + private $archive_suffixes = array(); + private $submit_button_name = null; + private $cancel_button_name = null; + + private static $uniqueInc = 1; + + private static function getNextUniqueId() + { + return self::$uniqueInc++; + } + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - parent::__construct($a_title, $a_postvar); - $this->uniqueId = self::getNextUniqueId(); - } - - /** - * Set accepted archive suffixes. - * - * @param array $a_suffixes Accepted archive suffixes. - */ - function setArchiveSuffixes($a_suffixes) - { - $this->archive_suffixes = $a_suffixes; - } + $this->lng = $DIC->language(); + parent::__construct($a_title, $a_postvar); + $this->uniqueId = self::getNextUniqueId(); + } + + /** + * Set accepted archive suffixes. + * + * @param array $a_suffixes Accepted archive suffixes. + */ + public function setArchiveSuffixes($a_suffixes) + { + $this->archive_suffixes = $a_suffixes; + } - /** - * Get accepted archive suffixes. - * - * @return array Accepted archive suffixes. - */ - function getArchiveSuffixes() - { - return $this->archive_suffixes; - } - - function setCommandButtonNames($a_submit_name, $a_cancel_name) - { - $this->submit_button_name = $a_submit_name; - $this->cancel_button_name = $a_cancel_name; - } - - /** - * Render html - */ - function render($a_mode = "") - { - $lng = $this->lng; + /** + * Get accepted archive suffixes. + * + * @return array Accepted archive suffixes. + */ + public function getArchiveSuffixes() + { + return $this->archive_suffixes; + } + + public function setCommandButtonNames($a_submit_name, $a_cancel_name) + { + $this->submit_button_name = $a_submit_name; + $this->cancel_button_name = $a_cancel_name; + } + + /** + * Render html + */ + public function render($a_mode = "") + { + $lng = $this->lng; - $quota_exceeded = $quota_legend = false; - if(self::$check_wsp_quota) - { - include_once "Services/DiskQuota/classes/class.ilDiskQuotaHandler.php"; - if(!ilDiskQuotaHandler::isUploadPossible()) - { - $lng->loadLanguageModule("file"); - return $lng->txt("personal_workspace_quota_exceeded_warning"); - } - else - { - $quota_legend = ilDiskQuotaHandler::getStatusLegend(); - } - } + $quota_exceeded = $quota_legend = false; + if (self::$check_wsp_quota) { + include_once "Services/DiskQuota/classes/class.ilDiskQuotaHandler.php"; + if (!ilDiskQuotaHandler::isUploadPossible()) { + $lng->loadLanguageModule("file"); + return $lng->txt("personal_workspace_quota_exceeded_warning"); + } else { + $quota_legend = ilDiskQuotaHandler::getStatusLegend(); + } + } - // make sure jQuery is loaded - iljQueryUtil::initjQuery(); - - // add file upload scripts - include_once("./Services/FileUpload/classes/class.ilFileUploadGUI.php"); - ilFileUploadGUI::initFileUpload(); - - // load template - $this->tpl = new ilTemplate("tpl.prop_dndfiles.html", true, true, "Services/Form"); - - // general variables - $this->tpl->setVariable("UPLOAD_ID", $this->uniqueId); - - // input - $this->tpl->setVariable("FILE_SELECT_ICON", ilObject::_getIcon("", "", "fold")); - $this->tpl->setVariable("TXT_SHOW_ALL_DETAILS", $lng->txt('show_all_details')); - $this->tpl->setVariable("TXT_HIDE_ALL_DETAILS", $lng->txt('hide_all_details')); - $this->tpl->setVariable("TXT_SELECTED_FILES", $lng->txt('selected_files')); - $this->tpl->setVariable("TXT_DRAG_FILES_HERE", $lng->txt('drag_files_here')); - $this->tpl->setVariable("TXT_NUM_OF_SELECTED_FILES", $lng->txt('num_of_selected_files')); - $this->tpl->setVariable("TXT_SELECT_FILES_FROM_COMPUTER", $lng->txt('select_files_from_computer')); - $this->tpl->setVariable("TXT_OR", $lng->txt('logic_or')); - $this->tpl->setVariable("INPUT_ACCEPT_SUFFIXES", $this->getInputAcceptSuffixes($this->getSuffixes())); + // make sure jQuery is loaded + iljQueryUtil::initjQuery(); + + // add file upload scripts + include_once("./Services/FileUpload/classes/class.ilFileUploadGUI.php"); + ilFileUploadGUI::initFileUpload(); + + // load template + $this->tpl = new ilTemplate("tpl.prop_dndfiles.html", true, true, "Services/Form"); + + // general variables + $this->tpl->setVariable("UPLOAD_ID", $this->uniqueId); + + // input + $this->tpl->setVariable("FILE_SELECT_ICON", ilObject::_getIcon("", "", "fold")); + $this->tpl->setVariable("TXT_SHOW_ALL_DETAILS", $lng->txt('show_all_details')); + $this->tpl->setVariable("TXT_HIDE_ALL_DETAILS", $lng->txt('hide_all_details')); + $this->tpl->setVariable("TXT_SELECTED_FILES", $lng->txt('selected_files')); + $this->tpl->setVariable("TXT_DRAG_FILES_HERE", $lng->txt('drag_files_here')); + $this->tpl->setVariable("TXT_NUM_OF_SELECTED_FILES", $lng->txt('num_of_selected_files')); + $this->tpl->setVariable("TXT_SELECT_FILES_FROM_COMPUTER", $lng->txt('select_files_from_computer')); + $this->tpl->setVariable("TXT_OR", $lng->txt('logic_or')); + $this->tpl->setVariable("INPUT_ACCEPT_SUFFIXES", $this->getInputAcceptSuffixes($this->getSuffixes())); - // info - $this->tpl->setCurrentBlock("max_size"); - $this->tpl->setVariable("TXT_MAX_SIZE", $lng->txt("file_notice")." ".$this->getMaxFileSizeString()); - $this->tpl->parseCurrentBlock(); - - if($quota_legend) - { - $this->tpl->setVariable("TXT_MAX_SIZE", $quota_legend); - $this->tpl->parseCurrentBlock(); - } - - $this->outputSuffixes($this->tpl); - - // create file upload object - $upload = new ilFileUploadGUI("ilFileUploadDropZone_" . $this->uniqueId, $this->uniqueId, false); - $upload->enableFormSubmit("ilFileUploadInput_" . $this->uniqueId, $this->submit_button_name, $this->cancel_button_name); - $upload->setDropAreaId("ilFileUploadDropArea_" . $this->uniqueId); - $upload->setFileListId("ilFileUploadList_" . $this->uniqueId); - $upload->setFileSelectButtonId("ilFileUploadFileSelect_" . $this->uniqueId); - - $this->tpl->setVariable("FILE_UPLOAD", $upload->getHTML()); - - return $this->tpl->get(); - } - - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - // if no information is received, something went wrong - // this is e.g. the case, if the post_max_size has been exceeded - if (!is_array($_FILES[$this->getPostVar()])) - { - $this->setAlert($lng->txt("form_msg_file_size_exceeds")); - return false; - } - - // empty file, could be a folder - if ($_FILES[$this->getPostVar()]["size"] < 1) - { - $this->setAlert($lng->txt("error_upload_was_zero_bytes")); - return false; - } + // info + $this->tpl->setCurrentBlock("max_size"); + $this->tpl->setVariable("TXT_MAX_SIZE", $lng->txt("file_notice") . " " . $this->getMaxFileSizeString()); + $this->tpl->parseCurrentBlock(); + + if ($quota_legend) { + $this->tpl->setVariable("TXT_MAX_SIZE", $quota_legend); + $this->tpl->parseCurrentBlock(); + } + + $this->outputSuffixes($this->tpl); + + // create file upload object + $upload = new ilFileUploadGUI("ilFileUploadDropZone_" . $this->uniqueId, $this->uniqueId, false); + $upload->enableFormSubmit("ilFileUploadInput_" . $this->uniqueId, $this->submit_button_name, $this->cancel_button_name); + $upload->setDropAreaId("ilFileUploadDropArea_" . $this->uniqueId); + $upload->setFileListId("ilFileUploadList_" . $this->uniqueId); + $upload->setFileSelectButtonId("ilFileUploadFileSelect_" . $this->uniqueId); + + $this->tpl->setVariable("FILE_UPLOAD", $upload->getHTML()); + + return $this->tpl->get(); + } + + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + // if no information is received, something went wrong + // this is e.g. the case, if the post_max_size has been exceeded + if (!is_array($_FILES[$this->getPostVar()])) { + $this->setAlert($lng->txt("form_msg_file_size_exceeds")); + return false; + } + + // empty file, could be a folder + if ($_FILES[$this->getPostVar()]["size"] < 1) { + $this->setAlert($lng->txt("error_upload_was_zero_bytes")); + return false; + } - // call base - $inputValid = parent::checkInput(); - - // set additionally sent input on post array - if ($inputValid) - { - $_POST[$this->getPostVar()]["extract"] = isset($_POST["extract"]) ? (bool)$_POST["extract"] : false; - $_POST[$this->getPostVar()]["title"] = isset($_POST["title"]) ? $_POST["title"] : ""; - $_POST[$this->getPostVar()]["description"] = isset($_POST["description"]) ? $_POST["description"] : ""; - $_POST[$this->getPostVar()]["keep_structure"] = isset($_POST["keep_structure"]) ? (bool)$_POST["keep_structure"] : true; + // call base + $inputValid = parent::checkInput(); + + // set additionally sent input on post array + if ($inputValid) { + $_POST[$this->getPostVar()]["extract"] = isset($_POST["extract"]) ? (bool) $_POST["extract"] : false; + $_POST[$this->getPostVar()]["title"] = isset($_POST["title"]) ? $_POST["title"] : ""; + $_POST[$this->getPostVar()]["description"] = isset($_POST["description"]) ? $_POST["description"] : ""; + $_POST[$this->getPostVar()]["keep_structure"] = isset($_POST["keep_structure"]) ? (bool) $_POST["keep_structure"] : true; - include_once("./Services/Utilities/classes/class.ilStr.php"); - $_POST[$this->getPostVar()]["name"] = ilStr::normalizeUtf8String($_POST[$this->getPostVar()]["name"]); - $_POST[$this->getPostVar()]["title"] = ilStr::normalizeUtf8String($_POST[$this->getPostVar()]["title"]); - - } - - return $inputValid; - } - - protected function getInputAcceptSuffixes($suffixes) - { - $list = $delim = ""; - - if (is_array($suffixes) && count($suffixes) > 0) - { - foreach($suffixes as $suffix) - { - $list .= $delim . "." . $suffix; - $delim = ","; - } - } - - return $list; - } - - protected function buildSuffixList($suffixes) - { - $list = $delim = ""; - - if (is_array($suffixes) && count($suffixes) > 0) - { - foreach($suffixes as $suffix) - { - $list .= $delim . "\"" . $suffix . "\""; - $delim = ", "; - } - } - - return $list; - } - - protected function getMaxFileSize() - { - // get the value for the maximal uploadable filesize from the php.ini (if available) - $umf = ini_get("upload_max_filesize"); - // get the value for the maximal post data from the php.ini (if available) - $pms = ini_get("post_max_size"); - - //convert from short-string representation to "real" bytes - $multiplier_a=array("K"=>1024, "M"=>1024*1024, "G"=>1024*1024*1024); - - $umf_parts=preg_split("/(\d+)([K|G|M])/", $umf, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY); - $pms_parts=preg_split("/(\d+)([K|G|M])/", $pms, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY); - - if (count($umf_parts) == 2) { - $umf = $umf_parts[0]*$multiplier_a[$umf_parts[1]]; - } - if (count($pms_parts) == 2) { - $pms = $pms_parts[0]*$multiplier_a[$pms_parts[1]]; - } - - // use the smaller one as limit - $max_filesize = min($umf, $pms); - - if (!$max_filesize) - $max_filesize=max($umf, $pms); - - return $max_filesize; - } + include_once("./Services/Utilities/classes/class.ilStr.php"); + $_POST[$this->getPostVar()]["name"] = ilStr::normalizeUtf8String($_POST[$this->getPostVar()]["name"]); + $_POST[$this->getPostVar()]["title"] = ilStr::normalizeUtf8String($_POST[$this->getPostVar()]["title"]); + } + + return $inputValid; + } + + protected function getInputAcceptSuffixes($suffixes) + { + $list = $delim = ""; + + if (is_array($suffixes) && count($suffixes) > 0) { + foreach ($suffixes as $suffix) { + $list .= $delim . "." . $suffix; + $delim = ","; + } + } + + return $list; + } + + protected function buildSuffixList($suffixes) + { + $list = $delim = ""; + + if (is_array($suffixes) && count($suffixes) > 0) { + foreach ($suffixes as $suffix) { + $list .= $delim . "\"" . $suffix . "\""; + $delim = ", "; + } + } + + return $list; + } + + protected function getMaxFileSize() + { + // get the value for the maximal uploadable filesize from the php.ini (if available) + $umf = ini_get("upload_max_filesize"); + // get the value for the maximal post data from the php.ini (if available) + $pms = ini_get("post_max_size"); + + //convert from short-string representation to "real" bytes + $multiplier_a=array("K"=>1024, "M"=>1024*1024, "G"=>1024*1024*1024); + + $umf_parts=preg_split("/(\d+)([K|G|M])/", $umf, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY); + $pms_parts=preg_split("/(\d+)([K|G|M])/", $pms, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY); + + if (count($umf_parts) == 2) { + $umf = $umf_parts[0]*$multiplier_a[$umf_parts[1]]; + } + if (count($pms_parts) == 2) { + $pms = $pms_parts[0]*$multiplier_a[$pms_parts[1]]; + } + + // use the smaller one as limit + $max_filesize = min($umf, $pms); + + if (!$max_filesize) { + $max_filesize=max($umf, $pms); + } + + return $max_filesize; + } } -?> \ No newline at end of file diff --git a/Services/Form/classes/class.ilDurationInputGUI.php b/Services/Form/classes/class.ilDurationInputGUI.php index 3ee56c6a25f33ad3471c53dd443fbcf7be9c72a7..6e160d182184bc53f6684bb11d865ae56a7c065e 100755 --- a/Services/Form/classes/class.ilDurationInputGUI.php +++ b/Services/Form/classes/class.ilDurationInputGUI.php @@ -1,471 +1,510 @@ +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilDurationInputGUI extends ilFormPropertyGUI { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - protected $months = 0; - protected $days = 0; - protected $hours = 0; - protected $minutes = 0; - protected $seconds = 0; - protected $showmonths = false; - protected $showdays = false; - protected $showhours = true; - protected $showminutes = true; - protected $showseconds = false; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + protected $months = 0; + protected $days = 0; + protected $hours = 0; + protected $minutes = 0; + protected $seconds = 0; + protected $showmonths = false; + protected $showdays = false; + protected $showhours = true; + protected $showminutes = true; + protected $showseconds = false; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - parent::__construct($a_title, $a_postvar); - $this->setType("duration"); - } + $this->lng = $DIC->language(); + parent::__construct($a_title, $a_postvar); + $this->setType("duration"); + } - /** - * Set Days. - * - * @param int $a_days Days - */ - function setDays($a_days) - { - $this->days = $a_days; - } + /** + * Set Days. + * + * @param int $a_days Days + */ + public function setDays($a_days) + { + $this->days = $a_days; + } - /** - * Get Days. - * - * @return int Days - */ - function getDays() - { - return (int) $this->days; - } + /** + * Get Days. + * + * @return int Days + */ + public function getDays() + { + return (int) $this->days; + } - /** - * Set Hours. - * - * @param int $a_hours Hours - */ - function setHours($a_hours) - { - $this->hours = $a_hours; - } + /** + * Set Hours. + * + * @param int $a_hours Hours + */ + public function setHours($a_hours) + { + $this->hours = $a_hours; + } - /** - * Get Hours. - * - * @return int Hours - */ - function getHours() - { - return (int) $this->hours; - } + /** + * Get Hours. + * + * @return int Hours + */ + public function getHours() + { + return (int) $this->hours; + } - /** - * Set Minutes. - * - * @param int $a_minutes Minutes - */ - function setMinutes($a_minutes) - { - $this->minutes = $a_minutes; - } + /** + * Set Minutes. + * + * @param int $a_minutes Minutes + */ + public function setMinutes($a_minutes) + { + $this->minutes = $a_minutes; + } - /** - * Get Minutes. - * - * @return int Minutes - */ - function getMinutes() - { - return (int) $this->minutes; - } + /** + * Get Minutes. + * + * @return int Minutes + */ + public function getMinutes() + { + return (int) $this->minutes; + } - /** - * Set Seconds. - * - * @param int $a_seconds Seconds - */ - function setSeconds($a_seconds) - { - $this->seconds = $a_seconds; - } - - /** - * set months - * - * @access public - * @param int months - * - */ - public function setMonths($a_months) - { - $this->months = $a_months; - } - - /** - * get months - * - * @access public - * - */ - public function getMonths() - { - return (int) $this->months; - } + /** + * Set Seconds. + * + * @param int $a_seconds Seconds + */ + public function setSeconds($a_seconds) + { + $this->seconds = $a_seconds; + } + + /** + * set months + * + * @access public + * @param int months + * + */ + public function setMonths($a_months) + { + $this->months = $a_months; + } + + /** + * get months + * + * @access public + * + */ + public function getMonths() + { + return (int) $this->months; + } - /** - * Get Seconds. - * - * @return int Seconds - */ - function getSeconds() - { - return (int) $this->seconds; - } - - /** - * Set show months - * - * @access public - * @param boolean $a_show_month - */ - public function setShowMonths($a_show_months) - { - $this->showmonths = $a_show_months; - } - - /** - * Get show months - * - * @access public - */ - public function getShowMonths() - { - return $this->showmonths; - } + /** + * Get Seconds. + * + * @return int Seconds + */ + public function getSeconds() + { + return (int) $this->seconds; + } + + /** + * Set show months + * + * @access public + * @param boolean $a_show_month + */ + public function setShowMonths($a_show_months) + { + $this->showmonths = $a_show_months; + } + + /** + * Get show months + * + * @access public + */ + public function getShowMonths() + { + return $this->showmonths; + } - /** - * Set Show Days. - * - * @param boolean $a_showdays Show Days - */ - function setShowDays($a_showdays) - { - $this->showdays = $a_showdays; - } + /** + * Set Show Days. + * + * @param boolean $a_showdays Show Days + */ + public function setShowDays($a_showdays) + { + $this->showdays = $a_showdays; + } - /** - * Get Show Days. - * - * @return boolean Show Days - */ - function getShowDays() - { - return $this->showdays; - } + /** + * Get Show Days. + * + * @return boolean Show Days + */ + public function getShowDays() + { + return $this->showdays; + } - /** - * Set Show Hours. - * - * @param boolean $a_showhours Show Hours - */ - function setShowHours($a_showhours) - { - $this->showhours = $a_showhours; - } + /** + * Set Show Hours. + * + * @param boolean $a_showhours Show Hours + */ + public function setShowHours($a_showhours) + { + $this->showhours = $a_showhours; + } - /** - * Get Show Hours. - * - * @return boolean Show Hours - */ - function getShowHours() - { - return $this->showhours; - } + /** + * Get Show Hours. + * + * @return boolean Show Hours + */ + public function getShowHours() + { + return $this->showhours; + } - /** - * Set Show Minutes. - * - * @param boolean $a_showminutes Show Minutes - */ - function setShowMinutes($a_showminutes) - { - $this->showminutes = $a_showminutes; - } + /** + * Set Show Minutes. + * + * @param boolean $a_showminutes Show Minutes + */ + public function setShowMinutes($a_showminutes) + { + $this->showminutes = $a_showminutes; + } - /** - * Get Show Minutes. - * - * @return boolean Show Minutes - */ - function getShowMinutes() - { - return $this->showminutes; - } + /** + * Get Show Minutes. + * + * @return boolean Show Minutes + */ + public function getShowMinutes() + { + return $this->showminutes; + } - /** - * Set Show Seconds. - * - * @param boolean $a_showseconds Show Seconds - */ - function setShowSeconds($a_showseconds) - { - $this->showseconds = $a_showseconds; - } + /** + * Set Show Seconds. + * + * @param boolean $a_showseconds Show Seconds + */ + public function setShowSeconds($a_showseconds) + { + $this->showseconds = $a_showseconds; + } - /** - * Get Show Seconds. - * - * @return boolean Show Seconds - */ - function getShowSeconds() - { - return $this->showseconds; - } + /** + * Get Show Seconds. + * + * @return boolean Show Seconds + */ + public function getShowSeconds() + { + return $this->showseconds; + } - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $this->setMonths($a_values[$this->getPostVar()]["MM"]); - $this->setDays($a_values[$this->getPostVar()]["dd"]); - $this->setHours($a_values[$this->getPostVar()]["hh"]); - $this->setMinutes($a_values[$this->getPostVar()]["mm"]); - $this->setSeconds($a_values[$this->getPostVar()]["ss"]); - } + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $this->setMonths($a_values[$this->getPostVar()]["MM"]); + $this->setDays($a_values[$this->getPostVar()]["dd"]); + $this->setHours($a_values[$this->getPostVar()]["hh"]); + $this->setMinutes($a_values[$this->getPostVar()]["mm"]); + $this->setSeconds($a_values[$this->getPostVar()]["ss"]); + } - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - $_POST[$this->getPostVar()]["MM"] = - ilUtil::stripSlashes($_POST[$this->getPostVar()]["MM"]); - $_POST[$this->getPostVar()]["dd"] = - ilUtil::stripSlashes($_POST[$this->getPostVar()]["dd"]); - $_POST[$this->getPostVar()]["hh"] = - ilUtil::stripSlashes($_POST[$this->getPostVar()]["hh"]); - $_POST[$this->getPostVar()]["mm"] = - ilUtil::stripSlashes($_POST[$this->getPostVar()]["mm"]); - $_POST[$this->getPostVar()]["ss"] = - ilUtil::stripSlashes($_POST[$this->getPostVar()]["ss"]); + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + $_POST[$this->getPostVar()]["MM"] = + ilUtil::stripSlashes($_POST[$this->getPostVar()]["MM"]); + $_POST[$this->getPostVar()]["dd"] = + ilUtil::stripSlashes($_POST[$this->getPostVar()]["dd"]); + $_POST[$this->getPostVar()]["hh"] = + ilUtil::stripSlashes($_POST[$this->getPostVar()]["hh"]); + $_POST[$this->getPostVar()]["mm"] = + ilUtil::stripSlashes($_POST[$this->getPostVar()]["mm"]); + $_POST[$this->getPostVar()]["ss"] = + ilUtil::stripSlashes($_POST[$this->getPostVar()]["ss"]); - return true; - } + return true; + } - /** - * Insert property html - * - * @return int Size - */ - function insert($a_tpl) - { - $html = $this->render(); + /** + * Insert property html + * + * @return int Size + */ + public function insert($a_tpl) + { + $html = $this->render(); - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $html); - $a_tpl->parseCurrentBlock(); - } + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $html); + $a_tpl->parseCurrentBlock(); + } - /** - * Insert property html - * - */ - function render() - { - $lng = $this->lng; + /** + * Insert property html + * + */ + public function render() + { + $lng = $this->lng; - $tpl = new ilTemplate("tpl.prop_duration.html", true, true, "Services/Form"); - - if($this->getShowMonths()) - { - $tpl->setCurrentBlock("dur_months"); - $tpl->setVariable("TXT_MONTHS", $lng->txt("form_months")); - $val = array(); - for ($i=0; $i<=36; $i++) - { - $val[$i] = $i; - } - $tpl->setVariable("SELECT_MONTHS", - ilUtil::formSelect($this->getMonths(), $this->getPostVar()."[MM]", - $val, false, true, 0, '', '', $this->getDisabled())); - $tpl->parseCurrentBlock(); - } - if ($this->getShowDays()) - { - $tpl->setCurrentBlock("dur_days"); - $tpl->setVariable("TXT_DAYS", $lng->txt("form_days")); - $val = array(); - for ($i=0; $i<=366; $i++) - { - $val[$i] = $i; - } - $tpl->setVariable("SELECT_DAYS", - ilUtil::formSelect($this->getDays(), $this->getPostVar()."[dd]", - $val, false, true, 0, '', '', $this->getDisabled())); - $tpl->parseCurrentBlock(); - } - if ($this->getShowHours()) - { - $tpl->setCurrentBlock("dur_hours"); - $tpl->setVariable("TXT_HOURS", $lng->txt("form_hours")); - $val = array(); - for ($i=0; $i<=23; $i++) - { - $val[$i] = $i; - } - $tpl->setVariable("SELECT_HOURS", - ilUtil::formSelect($this->getHours(), $this->getPostVar()."[hh]", - $val, false, true, 0, '', '', $this->getDisabled())); - $tpl->parseCurrentBlock(); - } - if ($this->getShowMinutes()) - { - $tpl->setCurrentBlock("dur_minutes"); - $tpl->setVariable("TXT_MINUTES", $lng->txt("form_minutes")); - $val = array(); - for ($i=0; $i<=59; $i++) - { - $val[$i] = $i; - } - $tpl->setVariable("SELECT_MINUTES", - ilUtil::formSelect($this->getMinutes(), $this->getPostVar()."[mm]", - $val, false, true, 0, '', '', $this->getDisabled())); - $tpl->parseCurrentBlock(); - } - if ($this->getShowSeconds()) - { - $tpl->setCurrentBlock("dur_seconds"); - $tpl->setVariable("TXT_SECONDS", $lng->txt("form_seconds")); - $val = array(); - for ($i=0; $i<=59; $i++) - { - $val[$i] = $i; - } - $tpl->setVariable("SELECT_SECONDS", - ilUtil::formSelect($this->getSeconds(), $this->getPostVar()."[ss]", - $val, false, true, 0, '', '', $this->getDisabled())); - $tpl->parseCurrentBlock(); - } - - return $tpl->get(); - } + $tpl = new ilTemplate("tpl.prop_duration.html", true, true, "Services/Form"); + + if ($this->getShowMonths()) { + $tpl->setCurrentBlock("dur_months"); + $tpl->setVariable("TXT_MONTHS", $lng->txt("form_months")); + $val = array(); + for ($i=0; $i<=36; $i++) { + $val[$i] = $i; + } + $tpl->setVariable( + "SELECT_MONTHS", + ilUtil::formSelect( + $this->getMonths(), + $this->getPostVar() . "[MM]", + $val, + false, + true, + 0, + '', + '', + $this->getDisabled() + ) + ); + $tpl->parseCurrentBlock(); + } + if ($this->getShowDays()) { + $tpl->setCurrentBlock("dur_days"); + $tpl->setVariable("TXT_DAYS", $lng->txt("form_days")); + $val = array(); + for ($i=0; $i<=366; $i++) { + $val[$i] = $i; + } + $tpl->setVariable( + "SELECT_DAYS", + ilUtil::formSelect( + $this->getDays(), + $this->getPostVar() . "[dd]", + $val, + false, + true, + 0, + '', + '', + $this->getDisabled() + ) + ); + $tpl->parseCurrentBlock(); + } + if ($this->getShowHours()) { + $tpl->setCurrentBlock("dur_hours"); + $tpl->setVariable("TXT_HOURS", $lng->txt("form_hours")); + $val = array(); + for ($i=0; $i<=23; $i++) { + $val[$i] = $i; + } + $tpl->setVariable( + "SELECT_HOURS", + ilUtil::formSelect( + $this->getHours(), + $this->getPostVar() . "[hh]", + $val, + false, + true, + 0, + '', + '', + $this->getDisabled() + ) + ); + $tpl->parseCurrentBlock(); + } + if ($this->getShowMinutes()) { + $tpl->setCurrentBlock("dur_minutes"); + $tpl->setVariable("TXT_MINUTES", $lng->txt("form_minutes")); + $val = array(); + for ($i=0; $i<=59; $i++) { + $val[$i] = $i; + } + $tpl->setVariable( + "SELECT_MINUTES", + ilUtil::formSelect( + $this->getMinutes(), + $this->getPostVar() . "[mm]", + $val, + false, + true, + 0, + '', + '', + $this->getDisabled() + ) + ); + $tpl->parseCurrentBlock(); + } + if ($this->getShowSeconds()) { + $tpl->setCurrentBlock("dur_seconds"); + $tpl->setVariable("TXT_SECONDS", $lng->txt("form_seconds")); + $val = array(); + for ($i=0; $i<=59; $i++) { + $val[$i] = $i; + } + $tpl->setVariable( + "SELECT_SECONDS", + ilUtil::formSelect( + $this->getSeconds(), + $this->getPostVar() . "[ss]", + $val, + false, + true, + 0, + '', + '', + $this->getDisabled() + ) + ); + $tpl->parseCurrentBlock(); + } + + return $tpl->get(); + } - /** - * Get HTML for table filter - */ - function getTableFilterHTML() - { - $html = $this->render(); - return $html; - } + /** + * Get HTML for table filter + */ + public function getTableFilterHTML() + { + $html = $this->render(); + return $html; + } - /** - * serialize data - */ - function serializeData() - { - $data = array("months" => $this->getMonths(), - "days" => $this->getDays(), - "hours" => $this->getHours(), - "minutes" => $this->getMinutes(), - "seconds" => $this->getSeconds()); + /** + * serialize data + */ + public function serializeData() + { + $data = array("months" => $this->getMonths(), + "days" => $this->getDays(), + "hours" => $this->getHours(), + "minutes" => $this->getMinutes(), + "seconds" => $this->getSeconds()); - return serialize($data); - } + return serialize($data); + } - /** - * unserialize data - */ - function unserializeData($a_data) - { - $data = unserialize($a_data); - - $this->setMonths($data["months"]); - $this->setDays($data["days"]); - $this->setHours($data["hours"]); - $this->setMinutes($data["minutes"]); - $this->setSeconds($data["seconds"]); - } + /** + * unserialize data + */ + public function unserializeData($a_data) + { + $data = unserialize($a_data); + + $this->setMonths($data["months"]); + $this->setDays($data["days"]); + $this->setHours($data["hours"]); + $this->setMinutes($data["minutes"]); + $this->setSeconds($data["seconds"]); + } - /** - * Get combined value in seconds - * - * @return int - */ - public function getValueInSeconds() - { - $value = 0; - if($this->getShowMonths()) - { - $value += $this->getMonths()*30*24*60*60; - } - if($this->getShowDays()) - { - $value += $this->getDays()*24*60*60; - } - if($this->getShowHours()) - { - $value += $this->getHours()*60*60; - } - if($this->getShowMinutes()) - { - $value += $this->getMinutes()*60; - } - if($this->getShowSeconds()) - { - $value += $this->getSeconds(); - } - return $value; - } + /** + * Get combined value in seconds + * + * @return int + */ + public function getValueInSeconds() + { + $value = 0; + if ($this->getShowMonths()) { + $value += $this->getMonths()*30*24*60*60; + } + if ($this->getShowDays()) { + $value += $this->getDays()*24*60*60; + } + if ($this->getShowHours()) { + $value += $this->getHours()*60*60; + } + if ($this->getShowMinutes()) { + $value += $this->getMinutes()*60; + } + if ($this->getShowSeconds()) { + $value += $this->getSeconds(); + } + return $value; + } } -?> \ No newline at end of file diff --git a/Services/Form/classes/class.ilEMailInputGUI.php b/Services/Form/classes/class.ilEMailInputGUI.php index 20ca665a57150b9590174d3ae8572eb3c4d885c6..495bbdf69763a4b7efa91746721d682a5dd6f19b 100755 --- a/Services/Form/classes/class.ilEMailInputGUI.php +++ b/Services/Form/classes/class.ilEMailInputGUI.php @@ -1,24 +1,24 @@ lng = $DIC->language(); - parent::__construct($a_title, $a_postvar); - $this->setRetype(false); - } - - /** - * Set Value. - * @param string $a_value Value - */ - function setValue($a_value) - { - $this->value = $a_value; - } - - /** - * Get Value. - * @return string Value - */ - function getValue() - { - return $this->value; - } - - /** - * Set value by array - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $this->setValue($a_values[$this->getPostVar()]); - $this->setRetypeValue($a_values[$this->getPostVar() . '_retype']); - } - - /** - * Allow extended email address format - * - * "example@example.com" vs "example " - * - * @param bool $a_value - */ - function allowRFC822($a_value) - { - $this->allowRFC822 = (bool)$a_value; - } - - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - $_POST[$this->getPostVar()] = ilUtil::stripSlashes($_POST[$this->getPostVar()], !(bool)$this->allowRFC822); - $_POST[$this->getPostVar() . '_retype'] = ilUtil::stripSlashes($_POST[$this->getPostVar() . '_retype'], !(bool)$this->allowRFC822); - if($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") - { - $this->setAlert($lng->txt("msg_input_is_required")); - - return false; - } - if($this->getRetype() && ($_POST[$this->getPostVar()] != $_POST[$this->getPostVar() . '_retype'])) - { - $this->setAlert($lng->txt('email_not_match')); - - return false; - } - if(!ilUtil::is_email($_POST[$this->getPostVar()]) && - trim($_POST[$this->getPostVar()]) != "" - ) - { - $this->setAlert($lng->txt("email_not_valid")); - - return false; - } - - - return true; - } - - /** - * @param ilTemplate $a_tpl - */ - function insert(ilTemplate $a_tpl) - { - $lng = $this->lng; - - $ptpl = new ilTemplate('tpl.prop_email.html', true, true, 'Services/Form'); - - if($this->getRetype()) - { - $ptpl->setCurrentBlock('retype_email'); - $ptpl->setVariable('RSIZE', $this->getSize()); - $ptpl->setVariable('RID', $this->getFieldId()); - $ptpl->setVariable('RMAXLENGTH', $this->getMaxLength()); - $ptpl->setVariable('RPOST_VAR', $this->getPostVar()); - - $retype_value = $this->getRetypeValue(); - $ptpl->setVariable('PROPERTY_RETYPE_VALUE', ilUtil::prepareFormOutput($retype_value)); - if($this->getDisabled()) - { - $ptpl->setVariable('RDISABLED', ' disabled="disabled"'); - } - $ptpl->setVariable('TXT_RETYPE', $lng->txt('form_retype_email')); - $ptpl->parseCurrentBlock(); - } - - $ptpl->setVariable('POST_VAR', $this->getPostVar()); - $ptpl->setVariable('ID', $this->getFieldId()); - $ptpl->setVariable('PROPERTY_VALUE', ilUtil::prepareFormOutput($this->getValue())); - $ptpl->setVariable('SIZE', $this->getSize()); - $ptpl->setVariable('MAXLENGTH', $this->getMaxLength()); - if($this->getDisabled()) - { - $ptpl->setVariable('DISABLED', ' disabled="disabled"'); - $ptpl->setVariable('HIDDEN_INPUT', $this->getHiddenTag($this->getPostVar(), $this->getValue())); - } - - if($this->getRequired()) - { - $ptpl->setVariable("REQUIRED", "required=\"required\""); - } - - $a_tpl->setCurrentBlock('prop_generic'); - $a_tpl->setVariable('PROP_GENERIC', $ptpl->get()); - $a_tpl->parseCurrentBlock(); - } - - /** - * @param boolean $a_val - */ - public function setRetype($a_val) - { - $this->retype = $a_val; - } - - /** - * @return boolean - */ - public function getRetype() - { - return $this->retype; - } - - /** - * @param string $a_retypevalue - */ - public function setRetypeValue($a_retypevalue) - { - $this->retypevalue = $a_retypevalue; - } - - /** - * @return string - */ - public function getRetypeValue() - { - return $this->retypevalue; - } - - /** - * @param int $size - */ - public function setSize($size) - { - $this->size = $size; - } - - /** - * @return int - */ - public function getSize() - { - return $this->size; - } - - /** - * @param int $max_length - */ - public function setMaxLength($max_length) - { - $this->max_length = $max_length; - } - - /** - * @return int - */ - public function getMaxLength() - { - return $this->max_length; - } + /** + * @var ilLanguage + */ + protected $lng; + + protected $value; + protected $size = 30; + protected $max_length = 80; + protected $allowRFC822 = false; // [bool] + + /** + * @var bool + */ + protected $retype = false; + + /** + * @var string + */ + protected $retypevalue = ''; + + /** + * Constructor + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; + + $this->lng = $DIC->language(); + parent::__construct($a_title, $a_postvar); + $this->setRetype(false); + } + + /** + * Set Value. + * @param string $a_value Value + */ + public function setValue($a_value) + { + $this->value = $a_value; + } + + /** + * Get Value. + * @return string Value + */ + public function getValue() + { + return $this->value; + } + + /** + * Set value by array + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $this->setValue($a_values[$this->getPostVar()]); + $this->setRetypeValue($a_values[$this->getPostVar() . '_retype']); + } + + /** + * Allow extended email address format + * + * "example@example.com" vs "example " + * + * @param bool $a_value + */ + public function allowRFC822($a_value) + { + $this->allowRFC822 = (bool) $a_value; + } + + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + $_POST[$this->getPostVar()] = ilUtil::stripSlashes($_POST[$this->getPostVar()], !(bool) $this->allowRFC822); + $_POST[$this->getPostVar() . '_retype'] = ilUtil::stripSlashes($_POST[$this->getPostVar() . '_retype'], !(bool) $this->allowRFC822); + if ($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") { + $this->setAlert($lng->txt("msg_input_is_required")); + + return false; + } + if ($this->getRetype() && ($_POST[$this->getPostVar()] != $_POST[$this->getPostVar() . '_retype'])) { + $this->setAlert($lng->txt('email_not_match')); + + return false; + } + if (!ilUtil::is_email($_POST[$this->getPostVar()]) && + trim($_POST[$this->getPostVar()]) != "" + ) { + $this->setAlert($lng->txt("email_not_valid")); + + return false; + } + + + return true; + } + + /** + * @param ilTemplate $a_tpl + */ + public function insert(ilTemplate $a_tpl) + { + $lng = $this->lng; + + $ptpl = new ilTemplate('tpl.prop_email.html', true, true, 'Services/Form'); + + if ($this->getRetype()) { + $ptpl->setCurrentBlock('retype_email'); + $ptpl->setVariable('RSIZE', $this->getSize()); + $ptpl->setVariable('RID', $this->getFieldId()); + $ptpl->setVariable('RMAXLENGTH', $this->getMaxLength()); + $ptpl->setVariable('RPOST_VAR', $this->getPostVar()); + + $retype_value = $this->getRetypeValue(); + $ptpl->setVariable('PROPERTY_RETYPE_VALUE', ilUtil::prepareFormOutput($retype_value)); + if ($this->getDisabled()) { + $ptpl->setVariable('RDISABLED', ' disabled="disabled"'); + } + $ptpl->setVariable('TXT_RETYPE', $lng->txt('form_retype_email')); + $ptpl->parseCurrentBlock(); + } + + $ptpl->setVariable('POST_VAR', $this->getPostVar()); + $ptpl->setVariable('ID', $this->getFieldId()); + $ptpl->setVariable('PROPERTY_VALUE', ilUtil::prepareFormOutput($this->getValue())); + $ptpl->setVariable('SIZE', $this->getSize()); + $ptpl->setVariable('MAXLENGTH', $this->getMaxLength()); + if ($this->getDisabled()) { + $ptpl->setVariable('DISABLED', ' disabled="disabled"'); + $ptpl->setVariable('HIDDEN_INPUT', $this->getHiddenTag($this->getPostVar(), $this->getValue())); + } + + if ($this->getRequired()) { + $ptpl->setVariable("REQUIRED", "required=\"required\""); + } + + $a_tpl->setCurrentBlock('prop_generic'); + $a_tpl->setVariable('PROP_GENERIC', $ptpl->get()); + $a_tpl->parseCurrentBlock(); + } + + /** + * @param boolean $a_val + */ + public function setRetype($a_val) + { + $this->retype = $a_val; + } + + /** + * @return boolean + */ + public function getRetype() + { + return $this->retype; + } + + /** + * @param string $a_retypevalue + */ + public function setRetypeValue($a_retypevalue) + { + $this->retypevalue = $a_retypevalue; + } + + /** + * @return string + */ + public function getRetypeValue() + { + return $this->retypevalue; + } + + /** + * @param int $size + */ + public function setSize($size) + { + $this->size = $size; + } + + /** + * @return int + */ + public function getSize() + { + return $this->size; + } + + /** + * @param int $max_length + */ + public function setMaxLength($max_length) + { + $this->max_length = $max_length; + } + + /** + * @return int + */ + public function getMaxLength() + { + return $this->max_length; + } } diff --git a/Services/Form/classes/class.ilFeedUrlInputGUI.php b/Services/Form/classes/class.ilFeedUrlInputGUI.php index a3a513d4a66af8deb0276c5115344b1e02bebc00..4b54770de6a400f9aebc7a290579a0efcda5309e 100755 --- a/Services/Form/classes/class.ilFeedUrlInputGUI.php +++ b/Services/Form/classes/class.ilFeedUrlInputGUI.php @@ -1,121 +1,114 @@ +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilFeedUrlInputGUI extends ilTextInputGUI { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - protected $value; - protected $maxlength = 200; - protected $size = 40; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + protected $value; + protected $maxlength = 200; + protected $size = 40; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - parent::__construct($a_title, $a_postvar); - $this->setType("feedurl"); - } + $this->lng = $DIC->language(); + parent::__construct($a_title, $a_postvar); + $this->setType("feedurl"); + } - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - $lng->loadLanguageModule("feed"); - - $_POST[$this->getPostVar()] = - ilUtil::stripSlashes($_POST[$this->getPostVar()]); - - // remove safari pseudo protocol - if (substr($_POST[$this->getPostVar()], 0, 5) == "feed:") - { - $_POST[$this->getPostVar()] = "http:". - substr($_POST[$this->getPostVar()], 5); - } - - // add missing http:// - if (!is_int(strpos($_POST[$this->getPostVar()], "://"))) - { - $_POST[$this->getPostVar()] = "http://".$_POST[$this->getPostVar()]; - } - - // check required - if ($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") - { - $this->setAlert($lng->txt("msg_input_is_required")); + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + $lng->loadLanguageModule("feed"); + + $_POST[$this->getPostVar()] = + ilUtil::stripSlashes($_POST[$this->getPostVar()]); + + // remove safari pseudo protocol + if (substr($_POST[$this->getPostVar()], 0, 5) == "feed:") { + $_POST[$this->getPostVar()] = "http:" . + substr($_POST[$this->getPostVar()], 5); + } + + // add missing http:// + if (!is_int(strpos($_POST[$this->getPostVar()], "://"))) { + $_POST[$this->getPostVar()] = "http://" . $_POST[$this->getPostVar()]; + } + + // check required + if ($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") { + $this->setAlert($lng->txt("msg_input_is_required")); - return false; - } - - // check feed url - $url = $_POST[$this->getPostVar()]; - include_once("./Services/Feeds/classes/class.ilExternalFeed.php"); - $check = ilExternalFeed::_checkUrl($url); + return false; + } + + // check feed url + $url = $_POST[$this->getPostVar()]; + include_once("./Services/Feeds/classes/class.ilExternalFeed.php"); + $check = ilExternalFeed::_checkUrl($url); - // try to determine a feed url, if we failed here - if ($check !== true) - { - $url2 = ilExternalFeed::_determineFeedUrl($url); - $check2 = ilExternalFeed::_checkUrl($url2); - - if ($check2 === true) - { - $_POST[$this->getPostVar()] = $url2; - $check = true; - } - } - - // if check failed, output error message - if ($check !== true) - { - $check = str_replace("MagpieRSS:", "", $check); - $this->setAlert($lng->txt("feed_no_valid_url")."
                  ".$check); - return false; - } - - return true; - } + // try to determine a feed url, if we failed here + if ($check !== true) { + $url2 = ilExternalFeed::_determineFeedUrl($url); + $check2 = ilExternalFeed::_checkUrl($url2); + + if ($check2 === true) { + $_POST[$this->getPostVar()] = $url2; + $check = true; + } + } + // if check failed, output error message + if ($check !== true) { + $check = str_replace("MagpieRSS:", "", $check); + $this->setAlert($lng->txt("feed_no_valid_url") . "
                  " . $check); + return false; + } + + return true; + } } diff --git a/Services/Form/classes/class.ilFileInputGUI.php b/Services/Form/classes/class.ilFileInputGUI.php index ce7df02047cc9f86145a8c24ae394143cc17603a..a1407233d633f7a5be75bedd71f41cad896e7f47 100755 --- a/Services/Form/classes/class.ilFileInputGUI.php +++ b/Services/Form/classes/class.ilFileInputGUI.php @@ -7,563 +7,539 @@ include_once("./Services/Form/classes/class.ilSubEnabledFormPropertyGUI.php"); /** * This class represents a file property in a property form. * -* @author Alex Killing +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilFileInputGUI extends ilSubEnabledFormPropertyGUI implements ilToolbarItem { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - private $filename; - private $filename_post; - protected $size = 40; - protected $pending; - protected $allow_deletion; - - static protected $check_wsp_quota; + private $filename; + private $filename_post; + protected $size = 40; + protected $pending; + protected $allow_deletion; + + protected static $check_wsp_quota; - /** - * @var array - */ - protected $forbidden_suffixes = array(); - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + /** + * @var array + */ + protected $forbidden_suffixes = array(); + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - $lng = $DIC->language(); - - parent::__construct($a_title, $a_postvar); - $this->setType("file"); - $this->setHiddenTitle("(".$lng->txt("form_file_input").")"); - } - - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - if (!is_array($a_values[$this->getPostVar()])) - { - $this->setValue($a_values[$this->getPostVar()]); - } - $this->setFilename($a_values[$this->getFileNamePostVar()]); - } + $this->lng = $DIC->language(); + $lng = $DIC->language(); + + parent::__construct($a_title, $a_postvar); + $this->setType("file"); + $this->setHiddenTitle("(" . $lng->txt("form_file_input") . ")"); + } + + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + if (!is_array($a_values[$this->getPostVar()])) { + $this->setValue($a_values[$this->getPostVar()]); + } + $this->setFilename($a_values[$this->getFileNamePostVar()]); + } - /** - * Set Value. (used for displaying file title of existing file below input field) - * - * @param string $a_value Value - */ - function setValue($a_value) - { - $this->value = $a_value; - } + /** + * Set Value. (used for displaying file title of existing file below input field) + * + * @param string $a_value Value + */ + public function setValue($a_value) + { + $this->value = $a_value; + } - /** - * Get Value. - * - * @return string Value - */ - function getValue() - { - return $this->value; - } - - /** - * Set Size. - * - * @param int $a_size Size - */ - function setSize($a_size) - { - $this->size = $a_size; - } + /** + * Get Value. + * + * @return string Value + */ + public function getValue() + { + return $this->value; + } + + /** + * Set Size. + * + * @param int $a_size Size + */ + public function setSize($a_size) + { + $this->size = $a_size; + } - /** - * Get Size. - * - * @return int Size - */ - function getSize() - { - return $this->size; - } + /** + * Get Size. + * + * @return int Size + */ + public function getSize() + { + return $this->size; + } - /** - * Set filename value (if filename selection is enabled) - * - * @param string $a_val - */ - public function setFilename($a_val) - { - $this->filename = $a_val; - } - - /** - * Get Value. - * - * @return string Value - */ - function getFilename() - { - return $this->filename; - } - - + /** + * Set filename value (if filename selection is enabled) + * + * @param string $a_val + */ + public function setFilename($a_val) + { + $this->filename = $a_val; + } + + /** + * Get Value. + * + * @return string Value + */ + public function getFilename() + { + return $this->filename; + } + + - /** - * Set Accepted Suffixes. - * - * @param array $a_suffixes Accepted Suffixes - */ - function setSuffixes($a_suffixes) - { - $this->suffixes = $a_suffixes; - } + /** + * Set Accepted Suffixes. + * + * @param array $a_suffixes Accepted Suffixes + */ + public function setSuffixes($a_suffixes) + { + $this->suffixes = $a_suffixes; + } - /** - * Get Accepted Suffixes. - * - * @return array Accepted Suffixes - */ - function getSuffixes() - { - return $this->suffixes; - } + /** + * Get Accepted Suffixes. + * + * @return array Accepted Suffixes + */ + public function getSuffixes() + { + return $this->suffixes; + } - /** - * Set forbidden Suffixes. - * - * @param array $a_suffixes forbidden Suffixes - */ - function setForbiddenSuffixes($a_suffixes) - { - $this->forbidden_suffixes = $a_suffixes; - } + /** + * Set forbidden Suffixes. + * + * @param array $a_suffixes forbidden Suffixes + */ + public function setForbiddenSuffixes($a_suffixes) + { + $this->forbidden_suffixes = $a_suffixes; + } - /** - * Get Accepted Suffixes. - * - * @return array forbidden Suffixes - */ - function getForbiddenSuffixes() - { - return $this->forbidden_suffixes; - } + /** + * Get Accepted Suffixes. + * + * @return array forbidden Suffixes + */ + public function getForbiddenSuffixes() + { + return $this->forbidden_suffixes; + } - /** - * Set pending filename value - * - * @param string $a_val - */ - public function setPending($a_val) - { - $this->pending = $a_val; - } - - /** - * Get pending filename - * - * @return string Value - */ - function getPending() - { - return $this->pending; - } - - /** - * If enabled, users get the possibility to enter a filename for the uploaded file - * - * @access public - * @param string post variable - * - */ - public function enableFileNameSelection($a_post_var) - { - $this->filename_selection = true; - $this->filename_post = $a_post_var; - } - - /** - * Check if filename selection is enabled - * - * @access public - * @return bool enabled/disabled - */ - public function isFileNameSelectionEnabled() - { - return $this->filename_selection ? true : false; - } - - /** - * Get file name post var - * - * @access public - * @param string file name post var - * - */ - public function getFileNamePostVar() - { - return $this->filename_post; - } - - /** - * Set allow deletion - * - * @param boolean $a_val allow deletion - */ - function setALlowDeletion($a_val) - { - $this->allow_deletion = $a_val; - } - - /** - * Get allow deletion - * - * @return boolean allow deletion - */ - function getALlowDeletion() - { - return $this->allow_deletion; - } + /** + * Set pending filename value + * + * @param string $a_val + */ + public function setPending($a_val) + { + $this->pending = $a_val; + } + + /** + * Get pending filename + * + * @return string Value + */ + public function getPending() + { + return $this->pending; + } + + /** + * If enabled, users get the possibility to enter a filename for the uploaded file + * + * @access public + * @param string post variable + * + */ + public function enableFileNameSelection($a_post_var) + { + $this->filename_selection = true; + $this->filename_post = $a_post_var; + } + + /** + * Check if filename selection is enabled + * + * @access public + * @return bool enabled/disabled + */ + public function isFileNameSelectionEnabled() + { + return $this->filename_selection ? true : false; + } + + /** + * Get file name post var + * + * @access public + * @param string file name post var + * + */ + public function getFileNamePostVar() + { + return $this->filename_post; + } + + /** + * Set allow deletion + * + * @param boolean $a_val allow deletion + */ + public function setALlowDeletion($a_val) + { + $this->allow_deletion = $a_val; + } + + /** + * Get allow deletion + * + * @return boolean allow deletion + */ + public function getALlowDeletion() + { + return $this->allow_deletion; + } - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - // #18756 - if($this->getDisabled()) - { - return true; - } + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + // #18756 + if ($this->getDisabled()) { + return true; + } - // if no information is received, something went wrong - // this is e.g. the case, if the post_max_size has been exceeded - if (!is_array($_FILES[$this->getPostVar()])) - { - $this->setAlert($lng->txt("form_msg_file_size_exceeds")); - return false; - } + // if no information is received, something went wrong + // this is e.g. the case, if the post_max_size has been exceeded + if (!is_array($_FILES[$this->getPostVar()])) { + $this->setAlert($lng->txt("form_msg_file_size_exceeds")); + return false; + } - $_FILES[$this->getPostVar()]["name"] = ilUtil::stripSlashes($_FILES[$this->getPostVar()]["name"]); + $_FILES[$this->getPostVar()]["name"] = ilUtil::stripSlashes($_FILES[$this->getPostVar()]["name"]); - include_once("./Services/Utilities/classes/class.ilStr.php"); - $_FILES[$this->getPostVar()]["name"] = ilStr::normalizeUtf8String($_FILES[$this->getPostVar()]["name"]); + include_once("./Services/Utilities/classes/class.ilStr.php"); + $_FILES[$this->getPostVar()]["name"] = ilStr::normalizeUtf8String($_FILES[$this->getPostVar()]["name"]); - // remove trailing '/' - $_FILES[$this->getPostVar()]["name"] = rtrim($_FILES[$this->getPostVar()]["name"], '/'); + // remove trailing '/' + $_FILES[$this->getPostVar()]["name"] = rtrim($_FILES[$this->getPostVar()]["name"], '/'); - $filename = $_FILES[$this->getPostVar()]["name"]; - $filename_arr = pathinfo($_FILES[$this->getPostVar()]["name"]); - $suffix = $filename_arr["extension"]; - $mimetype = $_FILES[$this->getPostVar()]["type"]; - $size_bytes = $_FILES[$this->getPostVar()]["size"]; - $temp_name = $_FILES[$this->getPostVar()]["tmp_name"]; - $error = $_FILES[$this->getPostVar()]["error"]; - $_POST[$this->getPostVar()] = $_FILES[$this->getPostVar()]; - - // error handling - if ($error > 0) - { - switch ($error) - { - case UPLOAD_ERR_INI_SIZE: - $this->setAlert($lng->txt("form_msg_file_size_exceeds")); - return false; - break; - - case UPLOAD_ERR_FORM_SIZE: - $this->setAlert($lng->txt("form_msg_file_size_exceeds")); - return false; - break; - - case UPLOAD_ERR_PARTIAL: - $this->setAlert($lng->txt("form_msg_file_partially_uploaded")); - return false; - break; - - case UPLOAD_ERR_NO_FILE: - if ($this->getRequired()) - { - if (!strlen($this->getValue())) - { - $this->setAlert($lng->txt("form_msg_file_no_upload")); - return false; - } - } - break; - - case UPLOAD_ERR_NO_TMP_DIR: - $this->setAlert($lng->txt("form_msg_file_missing_tmp_dir")); - return false; - break; - - case UPLOAD_ERR_CANT_WRITE: - $this->setAlert($lng->txt("form_msg_file_cannot_write_to_disk")); - return false; - break; - - case UPLOAD_ERR_EXTENSION: - $this->setAlert($lng->txt("form_msg_file_upload_stopped_ext")); - return false; - break; - } - } - - // check suffixes - if ($_FILES[$this->getPostVar()]["tmp_name"] != "") - { - if (is_array($this->forbidden_suffixes) && in_array(strtolower($suffix), $this->forbidden_suffixes)) - { - $this->setAlert($lng->txt("form_msg_file_type_is_not_allowed")." (".$suffix.")"); - return false; - } - if (is_array($this->getSuffixes()) && count($this->getSuffixes()) > 0) - { - if (!in_array(strtolower($suffix), $this->getSuffixes())) - { - $this->setAlert($lng->txt("form_msg_file_wrong_file_type")); - return false; - } - } - } - - // virus handling - if ($_FILES[$this->getPostVar()]["tmp_name"] != "") - { - $vir = ilUtil::virusHandling($temp_name, $filename); - if ($vir[0] == false) - { - $this->setAlert($lng->txt("form_msg_file_virus_found")."
                  ".$vir[1]); - return false; - } - } - - return true; - } + $filename = $_FILES[$this->getPostVar()]["name"]; + $filename_arr = pathinfo($_FILES[$this->getPostVar()]["name"]); + $suffix = $filename_arr["extension"]; + $mimetype = $_FILES[$this->getPostVar()]["type"]; + $size_bytes = $_FILES[$this->getPostVar()]["size"]; + $temp_name = $_FILES[$this->getPostVar()]["tmp_name"]; + $error = $_FILES[$this->getPostVar()]["error"]; + $_POST[$this->getPostVar()] = $_FILES[$this->getPostVar()]; + + // error handling + if ($error > 0) { + switch ($error) { + case UPLOAD_ERR_INI_SIZE: + $this->setAlert($lng->txt("form_msg_file_size_exceeds")); + return false; + break; + + case UPLOAD_ERR_FORM_SIZE: + $this->setAlert($lng->txt("form_msg_file_size_exceeds")); + return false; + break; + + case UPLOAD_ERR_PARTIAL: + $this->setAlert($lng->txt("form_msg_file_partially_uploaded")); + return false; + break; + + case UPLOAD_ERR_NO_FILE: + if ($this->getRequired()) { + if (!strlen($this->getValue())) { + $this->setAlert($lng->txt("form_msg_file_no_upload")); + return false; + } + } + break; + + case UPLOAD_ERR_NO_TMP_DIR: + $this->setAlert($lng->txt("form_msg_file_missing_tmp_dir")); + return false; + break; + + case UPLOAD_ERR_CANT_WRITE: + $this->setAlert($lng->txt("form_msg_file_cannot_write_to_disk")); + return false; + break; + + case UPLOAD_ERR_EXTENSION: + $this->setAlert($lng->txt("form_msg_file_upload_stopped_ext")); + return false; + break; + } + } + + // check suffixes + if ($_FILES[$this->getPostVar()]["tmp_name"] != "") { + if (is_array($this->forbidden_suffixes) && in_array(strtolower($suffix), $this->forbidden_suffixes)) { + $this->setAlert($lng->txt("form_msg_file_type_is_not_allowed") . " (" . $suffix . ")"); + return false; + } + if (is_array($this->getSuffixes()) && count($this->getSuffixes()) > 0) { + if (!in_array(strtolower($suffix), $this->getSuffixes())) { + $this->setAlert($lng->txt("form_msg_file_wrong_file_type")); + return false; + } + } + } + + // virus handling + if ($_FILES[$this->getPostVar()]["tmp_name"] != "") { + $vir = ilUtil::virusHandling($temp_name, $filename); + if ($vir[0] == false) { + $this->setAlert($lng->txt("form_msg_file_virus_found") . "
                  " . $vir[1]); + return false; + } + } + + return true; + } - /** - * Render html - */ - function render($a_mode = "") - { - $lng = $this->lng; - - $quota_exceeded = $quota_legend = false; - if(self::$check_wsp_quota) - { - include_once "Services/DiskQuota/classes/class.ilDiskQuotaHandler.php"; - if(!ilDiskQuotaHandler::isUploadPossible()) - { - $lng->loadLanguageModule("file"); - $quota_exceeded = $lng->txt("personal_workspace_quota_exceeded_warning"); - } - else - { - $quota_legend = ilDiskQuotaHandler::getStatusLegend(); - } - } - - $f_tpl = new ilTemplate("tpl.prop_file.html", true, true, "Services/Form"); - - - // show filename selection if enabled - if($this->isFileNameSelectionEnabled()) - { - $f_tpl->setCurrentBlock('filename'); - $f_tpl->setVariable('POST_FILENAME',$this->getFileNamePostVar()); - $f_tpl->setVariable('VAL_FILENAME',$this->getFilename()); - $f_tpl->setVariable('FILENAME_ID',$this->getFieldId()); - $f_tpl->setVAriable('TXT_FILENAME_HINT',$lng->txt('if_no_title_then_filename')); - $f_tpl->parseCurrentBlock(); - } - else - { - if (trim($this->getValue() != "")) - { - if (!$this->getDisabled() && $this->getALlowDeletion()) - { - $f_tpl->setCurrentBlock("delete_bl"); - $f_tpl->setVariable("POST_VAR_D", $this->getPostVar()); - $f_tpl->setVariable("TXT_DELETE_EXISTING", - $lng->txt("delete_existing_file")); - $f_tpl->parseCurrentBlock(); - } - - $f_tpl->setCurrentBlock('prop_file_propval'); - $f_tpl->setVariable('FILE_VAL', $this->getValue()); - $f_tpl->parseCurrentBlock(); - } - } + /** + * Render html + */ + public function render($a_mode = "") + { + $lng = $this->lng; + + $quota_exceeded = $quota_legend = false; + if (self::$check_wsp_quota) { + include_once "Services/DiskQuota/classes/class.ilDiskQuotaHandler.php"; + if (!ilDiskQuotaHandler::isUploadPossible()) { + $lng->loadLanguageModule("file"); + $quota_exceeded = $lng->txt("personal_workspace_quota_exceeded_warning"); + } else { + $quota_legend = ilDiskQuotaHandler::getStatusLegend(); + } + } + + $f_tpl = new ilTemplate("tpl.prop_file.html", true, true, "Services/Form"); + + + // show filename selection if enabled + if ($this->isFileNameSelectionEnabled()) { + $f_tpl->setCurrentBlock('filename'); + $f_tpl->setVariable('POST_FILENAME', $this->getFileNamePostVar()); + $f_tpl->setVariable('VAL_FILENAME', $this->getFilename()); + $f_tpl->setVariable('FILENAME_ID', $this->getFieldId()); + $f_tpl->setVAriable('TXT_FILENAME_HINT', $lng->txt('if_no_title_then_filename')); + $f_tpl->parseCurrentBlock(); + } else { + if (trim($this->getValue() != "")) { + if (!$this->getDisabled() && $this->getALlowDeletion()) { + $f_tpl->setCurrentBlock("delete_bl"); + $f_tpl->setVariable("POST_VAR_D", $this->getPostVar()); + $f_tpl->setVariable( + "TXT_DELETE_EXISTING", + $lng->txt("delete_existing_file") + ); + $f_tpl->parseCurrentBlock(); + } + + $f_tpl->setCurrentBlock('prop_file_propval'); + $f_tpl->setVariable('FILE_VAL', $this->getValue()); + $f_tpl->parseCurrentBlock(); + } + } - if ($a_mode != "toolbar") - { - if(!$quota_exceeded) - { - $this->outputSuffixes($f_tpl); + if ($a_mode != "toolbar") { + if (!$quota_exceeded) { + $this->outputSuffixes($f_tpl); - $f_tpl->setCurrentBlock("max_size"); - $f_tpl->setVariable("TXT_MAX_SIZE", $lng->txt("file_notice")." ". - $this->getMaxFileSizeString()); - $f_tpl->parseCurrentBlock(); - - if($quota_legend) - { - $f_tpl->setVariable("TXT_MAX_SIZE", $quota_legend); - $f_tpl->parseCurrentBlock(); - } - } - else - { - $f_tpl->setCurrentBlock("max_size"); - $f_tpl->setVariable("TXT_MAX_SIZE", $quota_exceeded); - $f_tpl->parseCurrentBlock(); - } - } - else if($quota_exceeded) - { - return $quota_exceeded; - } + $f_tpl->setCurrentBlock("max_size"); + $f_tpl->setVariable("TXT_MAX_SIZE", $lng->txt("file_notice") . " " . + $this->getMaxFileSizeString()); + $f_tpl->parseCurrentBlock(); + + if ($quota_legend) { + $f_tpl->setVariable("TXT_MAX_SIZE", $quota_legend); + $f_tpl->parseCurrentBlock(); + } + } else { + $f_tpl->setCurrentBlock("max_size"); + $f_tpl->setVariable("TXT_MAX_SIZE", $quota_exceeded); + $f_tpl->parseCurrentBlock(); + } + } elseif ($quota_exceeded) { + return $quota_exceeded; + } - $pending = $this->getPending(); - if($pending) - { - $f_tpl->setCurrentBlock("pending"); - $f_tpl->setVariable("TXT_PENDING", $lng->txt("file_upload_pending"). - ": ".$pending); - $f_tpl->parseCurrentBlock(); - } - - if ($this->getDisabled() || $quota_exceeded) - { - $f_tpl->setVariable("DISABLED", - " disabled=\"disabled\""); - } - - $f_tpl->setVariable("POST_VAR", $this->getPostVar()); - $f_tpl->setVariable("ID", $this->getFieldId()); - $f_tpl->setVariable("SIZE", $this->getSize()); - - - /* experimental: bootstrap'ed file upload */ - $f_tpl->setVariable("TXT_BROWSE", $lng->txt("select_file")); - - - return $f_tpl->get(); - } - - /** - * Insert property html - * - * @return int Size - */ - function insert($a_tpl) - { - $html = $this->render(); + $pending = $this->getPending(); + if ($pending) { + $f_tpl->setCurrentBlock("pending"); + $f_tpl->setVariable("TXT_PENDING", $lng->txt("file_upload_pending") . + ": " . $pending); + $f_tpl->parseCurrentBlock(); + } + + if ($this->getDisabled() || $quota_exceeded) { + $f_tpl->setVariable( + "DISABLED", + " disabled=\"disabled\"" + ); + } + + $f_tpl->setVariable("POST_VAR", $this->getPostVar()); + $f_tpl->setVariable("ID", $this->getFieldId()); + $f_tpl->setVariable("SIZE", $this->getSize()); + + + /* experimental: bootstrap'ed file upload */ + $f_tpl->setVariable("TXT_BROWSE", $lng->txt("select_file")); + + + return $f_tpl->get(); + } + + /** + * Insert property html + * + * @return int Size + */ + public function insert($a_tpl) + { + $html = $this->render(); - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $html); - $a_tpl->parseCurrentBlock(); - } + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $html); + $a_tpl->parseCurrentBlock(); + } - protected function outputSuffixes($a_tpl, $a_block = "allowed_suffixes") - { - $lng = $this->lng; - - if (is_array($this->getSuffixes()) && count($this->getSuffixes()) > 0) - { - $suff_str = $delim = ""; - foreach($this->getSuffixes() as $suffix) - { - $suff_str.= $delim.".".$suffix; - $delim = ", "; - } - $a_tpl->setCurrentBlock($a_block); - $a_tpl->setVariable("TXT_ALLOWED_SUFFIXES", - $lng->txt("file_allowed_suffixes")." ".$suff_str); - $a_tpl->parseCurrentBlock(); - } - } - - protected function getMaxFileSizeString() - { - // get the value for the maximal uploadable filesize from the php.ini (if available) - $umf = ini_get("upload_max_filesize"); - // get the value for the maximal post data from the php.ini (if available) - $pms = ini_get("post_max_size"); - - //convert from short-string representation to "real" bytes - $multiplier_a=array("K"=>1024, "M"=>1024*1024, "G"=>1024*1024*1024); - - $umf_parts=preg_split("/(\d+)([K|G|M])/", $umf, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY); + protected function outputSuffixes($a_tpl, $a_block = "allowed_suffixes") + { + $lng = $this->lng; + + if (is_array($this->getSuffixes()) && count($this->getSuffixes()) > 0) { + $suff_str = $delim = ""; + foreach ($this->getSuffixes() as $suffix) { + $suff_str.= $delim . "." . $suffix; + $delim = ", "; + } + $a_tpl->setCurrentBlock($a_block); + $a_tpl->setVariable( + "TXT_ALLOWED_SUFFIXES", + $lng->txt("file_allowed_suffixes") . " " . $suff_str + ); + $a_tpl->parseCurrentBlock(); + } + } + + protected function getMaxFileSizeString() + { + // get the value for the maximal uploadable filesize from the php.ini (if available) + $umf = ini_get("upload_max_filesize"); + // get the value for the maximal post data from the php.ini (if available) + $pms = ini_get("post_max_size"); + + //convert from short-string representation to "real" bytes + $multiplier_a=array("K"=>1024, "M"=>1024*1024, "G"=>1024*1024*1024); + + $umf_parts=preg_split("/(\d+)([K|G|M])/", $umf, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY); $pms_parts=preg_split("/(\d+)([K|G|M])/", $pms, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY); - if (count($umf_parts) == 2) { $umf = $umf_parts[0]*$multiplier_a[$umf_parts[1]]; } - if (count($pms_parts) == 2) { $pms = $pms_parts[0]*$multiplier_a[$pms_parts[1]]; } + if (count($umf_parts) == 2) { + $umf = $umf_parts[0]*$multiplier_a[$umf_parts[1]]; + } + if (count($pms_parts) == 2) { + $pms = $pms_parts[0]*$multiplier_a[$pms_parts[1]]; + } // use the smaller one as limit - $max_filesize = min($umf, $pms); + $max_filesize = min($umf, $pms); - if (!$max_filesize) $max_filesize=max($umf, $pms); - - //format for display in mega-bytes - $max_filesize = sprintf("%.1f MB",$max_filesize/1024/1024); - - return $max_filesize; - } - - /** - * Get deletion flag - */ - function getDeletionFlag() - { - if ($_POST[$this->getPostVar()."_delete"]) - { - return true; - } - return false; - } - - /** - * Get HTML for toolbar - */ - function getToolbarHTML() - { - $html = $this->render("toolbar"); - return $html; - } - - static function setPersonalWorkspaceQuotaCheck($a_value) - { - if((bool)$a_value) - { - include_once "Services/WebDAV/classes/class.ilDiskQuotaActivationChecker.php"; - if(ilDiskQuotaActivationChecker::_isPersonalWorkspaceActive()) - { - self::$check_wsp_quota = true; - return; - } - } - self::$check_wsp_quota = false; - } + if (!$max_filesize) { + $max_filesize=max($umf, $pms); + } + + //format for display in mega-bytes + $max_filesize = sprintf("%.1f MB", $max_filesize/1024/1024); + + return $max_filesize; + } + + /** + * Get deletion flag + */ + public function getDeletionFlag() + { + if ($_POST[$this->getPostVar() . "_delete"]) { + return true; + } + return false; + } + + /** + * Get HTML for toolbar + */ + public function getToolbarHTML() + { + $html = $this->render("toolbar"); + return $html; + } + + public static function setPersonalWorkspaceQuotaCheck($a_value) + { + if ((bool) $a_value) { + include_once "Services/WebDAV/classes/class.ilDiskQuotaActivationChecker.php"; + if (ilDiskQuotaActivationChecker::_isPersonalWorkspaceActive()) { + self::$check_wsp_quota = true; + return; + } + } + self::$check_wsp_quota = false; + } } diff --git a/Services/Form/classes/class.ilFileStandardDropzoneInputGUI.php b/Services/Form/classes/class.ilFileStandardDropzoneInputGUI.php index e57a39eafcddda8dc3aa3a4c39cff1f11c671593..9a34c35e61ec0a252a15bdd7c373d155cd3b503b 100755 --- a/Services/Form/classes/class.ilFileStandardDropzoneInputGUI.php +++ b/Services/Form/classes/class.ilFileStandardDropzoneInputGUI.php @@ -30,215 +30,229 @@ * * @author Fabian Schmid */ -class ilFileStandardDropzoneInputGUI extends ilFileInputGUI implements ilToolbarItem { - - use \ILIAS\Modules\OrgUnit\ARHelper\DIC; - - const ASYNC_FILEUPLOAD = "async_fileupload"; - /** - * @var int if there are more than one ilFileStandardDropzoneInputGUI in the same Form, this - * value will be incremented during rendering to make sure all Inputs will be handled - * correctly - */ - protected static $count = 0; - /** - * @var string Set it to the URL (using ilCtrl->getFormAction() ) to override the Endpoint the - * Form will be sent to. If not set, the ilFileStandardDropzoneInputGUI will get the - * Form-Action of it's nearest form - */ - protected $upload_url = ''; - /** - * @var int The amount of files which can be uploaded. Standard is 1 since the old - * ilFileInputGUI in most cases allows one. - */ - protected $max_files = 1; - /** - * @var \ILIAS\Data\DataSize only files beneath this size will be accepted to upload. Currently - * this uses the defined valued of the php.ini - */ - protected $max_file_size; - /** - * @var string The message which will be rendered within the dropzone. - */ - protected $dropzone_message = ''; - - - /** - * @return string the URL where the form will be sent to. - */ - public function getUploadUrl() { - return $this->upload_url; - } - - - /** - * Set the URL (using ilCtrl->getFormAction() ) to override the Endpoint the - * Form will be sent to. If not set, the ilFileStandardDropzoneInputGUI will get the - * Form-Action of it's nearest form - * - * @param string $upload_url - * - * @return $this - */ - public function setUploadUrl($upload_url) { - $this->upload_url = $upload_url; - - return $this; - } - - - /** - * @return int Amount of allowed files in this input - */ - public function getMaxFiles() { - return $this->max_files; - } - - - /** - * @param int $max_files The amount of files which can be uploaded. Standard is 1 since the old - * ilFileInputGUI in most cases allows one. - */ - public function setMaxFiles($max_files) { - $this->max_files = $max_files; - } - - - /** - * @return \ILIAS\Data\DataSize allowed size of files which can be uploaded - */ - public function getMaxFilesize() { - return $this->max_file_size; - } - - - /** - * @param \ILIAS\Data\DataSize $max_file_size only files beneath this size will be accepted to - * upload. Currently this uses the defined valued of - * the php.ini - */ - public function setMaxFilesize(\ILIAS\Data\DataSize $max_file_size) { - $this->max_file_size = $max_file_size; - } - - - /** - * @return string The message which will be rendered within the dropzone. - */ - public function getDropzoneMessage() { - return $this->dropzone_message; - } - - - /** - * @param string $dropzone_message The message which will be rendered within the dropzone. - */ - public function setDropzoneMessage($dropzone_message) { - $this->dropzone_message = $dropzone_message; - } - - - /** - * @inheritdoc - */ - public function render($a_mode = "") { - $this->handleUploadURL(); - $this->handleSuffixes(); - - $f = $this->ui()->factory(); - $r = $this->ui()->renderer(); - - $this->initDropzoneMessage(); - - $dropzone = $f->dropzone() - ->file() - ->standard($this->getUploadUrl()) - ->withParameterName($this->getPostVar()) - ->withMaxFiles($this->getMaxFiles()) - ->withMessage($this->getDropzoneMessage()) - ->withAllowedFileTypes($this->getSuffixes()); - $dropzone = $this->handleMaxFileSize($dropzone); - if ($this->isFileNameSelectionEnabled()) { - $dropzone = $dropzone->withUserDefinedFileNamesEnabled(true); - } - - $render = $r->render($dropzone); - - $n = ++ self::$count; - $out = "
                  " . $render . '
                  '; - // We need some javascript magic - - $this->ui()->mainTemplate()->addJavaScript('./Services/Form/js/ilFileStandardDropzoneInputGUI.js'); - $this->ui()->mainTemplate()->addOnLoadCode("ilFileStandardDropzoneInputGUI.init('ilFileStandardDropzoneInputGUIWrapper{$n}');"); - - return $out; - } - - - /** - * @inheritdoc - */ - public function checkInput() { - $hasUploads = $this->dic()->upload()->hasUploads(); - if ($this->getRequired() && !$hasUploads) { - return false; // No file uploaded but is was required - } - - if ($hasUploads) { - try { - $_POST[$this->getPostVar()] = $_FILES[$this->getPostVar()]; - } catch (Exception $e) { - return false; - } - - return true; - } - - return true; - } - - - protected function handleUploadURL() { - if (!$this->getUploadUrl()) { - $parentWrapper = $this; - while (!$parentWrapper instanceof ilPropertyFormGUI && $parentWrapper !== null) { - $parentWrapper = $parentWrapper->getParent(); - } - - $str_replace = str_replace("&", "&", $parentWrapper->getFormAction()); - $this->setUploadUrl($str_replace . "&" . self::ASYNC_FILEUPLOAD . "=true"); - } - } - - - protected function handleSuffixes() { - if (!is_array($this->getSuffixes())) { - $this->setSuffixes(array()); - } - } - - - /** - * @param ILIAS\UI\Component\Dropzone\File\Standard $dropzone - * - * @return ILIAS\UI\Component\Dropzone\File\Standard - */ - protected function handleMaxFileSize($dropzone) { - if ($this->getMaxFilesize()) { - $dropzone = $dropzone->withFileSizeLimit($this->getMaxFilesize()); - } - - return $dropzone; - } - - - protected function initDropzoneMessage() { - if (!$this->getDropzoneMessage()) { - if ($this->getMaxFiles() === 1) { - $this->setDropzoneMessage($this->lng()->txt('drag_file_here')); - } else { - $this->setDropzoneMessage($this->lng()->txt('drag_files_here')); - } - } - } +class ilFileStandardDropzoneInputGUI extends ilFileInputGUI implements ilToolbarItem +{ + use \ILIAS\Modules\OrgUnit\ARHelper\DIC; + + const ASYNC_FILEUPLOAD = "async_fileupload"; + /** + * @var int if there are more than one ilFileStandardDropzoneInputGUI in the same Form, this + * value will be incremented during rendering to make sure all Inputs will be handled + * correctly + */ + protected static $count = 0; + /** + * @var string Set it to the URL (using ilCtrl->getFormAction() ) to override the Endpoint the + * Form will be sent to. If not set, the ilFileStandardDropzoneInputGUI will get the + * Form-Action of it's nearest form + */ + protected $upload_url = ''; + /** + * @var int The amount of files which can be uploaded. Standard is 1 since the old + * ilFileInputGUI in most cases allows one. + */ + protected $max_files = 1; + /** + * @var \ILIAS\Data\DataSize only files beneath this size will be accepted to upload. Currently + * this uses the defined valued of the php.ini + */ + protected $max_file_size; + /** + * @var string The message which will be rendered within the dropzone. + */ + protected $dropzone_message = ''; + + + /** + * @return string the URL where the form will be sent to. + */ + public function getUploadUrl() + { + return $this->upload_url; + } + + + /** + * Set the URL (using ilCtrl->getFormAction() ) to override the Endpoint the + * Form will be sent to. If not set, the ilFileStandardDropzoneInputGUI will get the + * Form-Action of it's nearest form + * + * @param string $upload_url + * + * @return $this + */ + public function setUploadUrl($upload_url) + { + $this->upload_url = $upload_url; + + return $this; + } + + + /** + * @return int Amount of allowed files in this input + */ + public function getMaxFiles() + { + return $this->max_files; + } + + + /** + * @param int $max_files The amount of files which can be uploaded. Standard is 1 since the old + * ilFileInputGUI in most cases allows one. + */ + public function setMaxFiles($max_files) + { + $this->max_files = $max_files; + } + + + /** + * @return \ILIAS\Data\DataSize allowed size of files which can be uploaded + */ + public function getMaxFilesize() + { + return $this->max_file_size; + } + + + /** + * @param \ILIAS\Data\DataSize $max_file_size only files beneath this size will be accepted to + * upload. Currently this uses the defined valued of + * the php.ini + */ + public function setMaxFilesize(\ILIAS\Data\DataSize $max_file_size) + { + $this->max_file_size = $max_file_size; + } + + + /** + * @return string The message which will be rendered within the dropzone. + */ + public function getDropzoneMessage() + { + return $this->dropzone_message; + } + + + /** + * @param string $dropzone_message The message which will be rendered within the dropzone. + */ + public function setDropzoneMessage($dropzone_message) + { + $this->dropzone_message = $dropzone_message; + } + + + /** + * @inheritdoc + */ + public function render($a_mode = "") + { + $this->handleUploadURL(); + $this->handleSuffixes(); + + $f = $this->ui()->factory(); + $r = $this->ui()->renderer(); + + $this->initDropzoneMessage(); + + $dropzone = $f->dropzone() + ->file() + ->standard($this->getUploadUrl()) + ->withParameterName($this->getPostVar()) + ->withMaxFiles($this->getMaxFiles()) + ->withMessage($this->getDropzoneMessage()) + ->withAllowedFileTypes($this->getSuffixes()); + $dropzone = $this->handleMaxFileSize($dropzone); + if ($this->isFileNameSelectionEnabled()) { + $dropzone = $dropzone->withUserDefinedFileNamesEnabled(true); + } + + $render = $r->render($dropzone); + + $n = ++self::$count; + $out = "
                  " . $render . '
                  '; + // We need some javascript magic + + $this->ui()->mainTemplate()->addJavaScript('./Services/Form/js/ilFileStandardDropzoneInputGUI.js'); + $this->ui()->mainTemplate()->addOnLoadCode("ilFileStandardDropzoneInputGUI.init('ilFileStandardDropzoneInputGUIWrapper{$n}');"); + + return $out; + } + + + /** + * @inheritdoc + */ + public function checkInput() + { + $hasUploads = $this->dic()->upload()->hasUploads(); + if ($this->getRequired() && !$hasUploads) { + return false; // No file uploaded but is was required + } + + if ($hasUploads) { + try { + $_POST[$this->getPostVar()] = $_FILES[$this->getPostVar()]; + } catch (Exception $e) { + return false; + } + + return true; + } + + return true; + } + + + protected function handleUploadURL() + { + if (!$this->getUploadUrl()) { + $parentWrapper = $this; + while (!$parentWrapper instanceof ilPropertyFormGUI && $parentWrapper !== null) { + $parentWrapper = $parentWrapper->getParent(); + } + + $str_replace = str_replace("&", "&", $parentWrapper->getFormAction()); + $this->setUploadUrl($str_replace . "&" . self::ASYNC_FILEUPLOAD . "=true"); + } + } + + + protected function handleSuffixes() + { + if (!is_array($this->getSuffixes())) { + $this->setSuffixes(array()); + } + } + + + /** + * @param ILIAS\UI\Component\Dropzone\File\Standard $dropzone + * + * @return ILIAS\UI\Component\Dropzone\File\Standard + */ + protected function handleMaxFileSize($dropzone) + { + if ($this->getMaxFilesize()) { + $dropzone = $dropzone->withFileSizeLimit($this->getMaxFilesize()); + } + + return $dropzone; + } + + + protected function initDropzoneMessage() + { + if (!$this->getDropzoneMessage()) { + if ($this->getMaxFiles() === 1) { + $this->setDropzoneMessage($this->lng()->txt('drag_file_here')); + } else { + $this->setDropzoneMessage($this->lng()->txt('drag_files_here')); + } + } + } } diff --git a/Services/Form/classes/class.ilFileWizardInputGUI.php b/Services/Form/classes/class.ilFileWizardInputGUI.php index 7cfb42dee30b0c587dfd1a65cfec12c5f427f4f3..745a91f1fe086b244a15b803e7ab5de6e0a1e29b 100644 --- a/Services/Form/classes/class.ilFileWizardInputGUI.php +++ b/Services/Form/classes/class.ilFileWizardInputGUI.php @@ -1,309 +1,294 @@ +* @author Helmut Schottmüller * @version $Id: class.ilFileWizardInputGUI.php 18834 2009-02-03 10:10:29Z hschottm $ * @ingroup ServicesForm */ class ilFileWizardInputGUI extends ilFileInputGUI { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilTemplate + */ + protected $tpl; - protected $filenames = array(); - protected $allowMove = false; - protected $imagepath_web = ""; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + protected $filenames = array(); + protected $allowMove = false; + protected $imagepath_web = ""; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - parent::__construct($a_title, $a_postvar); - } + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + parent::__construct($a_title, $a_postvar); + } - /** - * Set the web image path - * - * @param string $a_path Path - */ - public function setImagePathWeb($a_path) - { - $this->imagepath_web = $a_path; - } - - /** - * Get the web image path - * - * @return string Path - */ - public function getImagePathWeb() - { - return $this->imagepath_web; - } + /** + * Set the web image path + * + * @param string $a_path Path + */ + public function setImagePathWeb($a_path) + { + $this->imagepath_web = $a_path; + } + + /** + * Get the web image path + * + * @return string Path + */ + public function getImagePathWeb() + { + return $this->imagepath_web; + } - /** - * Set filenames - * - * @param array $a_value Value - */ - function setFilenames($a_filenames) - { - $this->filenames = $a_filenames; - } + /** + * Set filenames + * + * @param array $a_value Value + */ + public function setFilenames($a_filenames) + { + $this->filenames = $a_filenames; + } - /** - * Get filenames - * - * @return array filenames - */ - function getFilenames() - { - return $this->filenames; - } + /** + * Get filenames + * + * @return array filenames + */ + public function getFilenames() + { + return $this->filenames; + } - /** - * Set allow move - * - * @param boolean $a_allow_move Allow move - */ - function setAllowMove($a_allow_move) - { - $this->allowMove = $a_allow_move; - } + /** + * Set allow move + * + * @param boolean $a_allow_move Allow move + */ + public function setAllowMove($a_allow_move) + { + $this->allowMove = $a_allow_move; + } - /** - * Get allow move - * - * @return boolean Allow move - */ - function getAllowMove() - { - return $this->allowMove; - } + /** + * Get allow move + * + * @return boolean Allow move + */ + public function getAllowMove() + { + return $this->allowMove; + } - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - // see ilFileInputGUI - // if no information is received, something went wrong - // this is e.g. the case, if the post_max_size has been exceeded - if (!is_array($_FILES[$this->getPostVar()])) - { - $this->setAlert($lng->txt("form_msg_file_size_exceeds")); - return false; - } - - $pictures = $_FILES[$this->getPostVar()]; - $uploadcheck = true; - if (is_array($pictures)) - { - foreach ($pictures['name'] as $index => $name) - { - // remove trailing '/' - $name = rtrim($name, '/'); + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + // see ilFileInputGUI + // if no information is received, something went wrong + // this is e.g. the case, if the post_max_size has been exceeded + if (!is_array($_FILES[$this->getPostVar()])) { + $this->setAlert($lng->txt("form_msg_file_size_exceeds")); + return false; + } + + $pictures = $_FILES[$this->getPostVar()]; + $uploadcheck = true; + if (is_array($pictures)) { + foreach ($pictures['name'] as $index => $name) { + // remove trailing '/' + $name = rtrim($name, '/'); - $filename = $name; - $filename_arr = pathinfo($name); - $suffix = $filename_arr["extension"]; - $mimetype = $pictures["type"][$index]; - $size_bytes = $pictures["size"][$index]; - $temp_name = $pictures["tmp_name"][$index]; - $error = $pictures["error"][$index]; + $filename = $name; + $filename_arr = pathinfo($name); + $suffix = $filename_arr["extension"]; + $mimetype = $pictures["type"][$index]; + $size_bytes = $pictures["size"][$index]; + $temp_name = $pictures["tmp_name"][$index]; + $error = $pictures["error"][$index]; - include_once("./Services/Utilities/classes/class.ilStr.php"); - $_FILES[$this->getPostVar()]["name"][$index] = ilStr::normalizeUtf8String($_FILES[$this->getPostVar()]["name"][$index]); + include_once("./Services/Utilities/classes/class.ilStr.php"); + $_FILES[$this->getPostVar()]["name"][$index] = ilStr::normalizeUtf8String($_FILES[$this->getPostVar()]["name"][$index]); - // error handling - if ($error > 0) - { - switch ($error) - { - case UPLOAD_ERR_INI_SIZE: - $this->setAlert($lng->txt("form_msg_file_size_exceeds")); - $uploadcheck = false; - break; + // error handling + if ($error > 0) { + switch ($error) { + case UPLOAD_ERR_INI_SIZE: + $this->setAlert($lng->txt("form_msg_file_size_exceeds")); + $uploadcheck = false; + break; - case UPLOAD_ERR_FORM_SIZE: - $this->setAlert($lng->txt("form_msg_file_size_exceeds")); - $uploadcheck = false; - break; + case UPLOAD_ERR_FORM_SIZE: + $this->setAlert($lng->txt("form_msg_file_size_exceeds")); + $uploadcheck = false; + break; - case UPLOAD_ERR_PARTIAL: - $this->setAlert($lng->txt("form_msg_file_partially_uploaded")); - $uploadcheck = false; - break; + case UPLOAD_ERR_PARTIAL: + $this->setAlert($lng->txt("form_msg_file_partially_uploaded")); + $uploadcheck = false; + break; - case UPLOAD_ERR_NO_FILE: - if ($this->getRequired()) - { - $filename = $this->filenames[$index]; - if (!strlen($filename)) - { - $this->setAlert($lng->txt("form_msg_file_no_upload")); - $uploadcheck = false; - } - } - break; + case UPLOAD_ERR_NO_FILE: + if ($this->getRequired()) { + $filename = $this->filenames[$index]; + if (!strlen($filename)) { + $this->setAlert($lng->txt("form_msg_file_no_upload")); + $uploadcheck = false; + } + } + break; - case UPLOAD_ERR_NO_TMP_DIR: - $this->setAlert($lng->txt("form_msg_file_missing_tmp_dir")); - $uploadcheck = false; - break; + case UPLOAD_ERR_NO_TMP_DIR: + $this->setAlert($lng->txt("form_msg_file_missing_tmp_dir")); + $uploadcheck = false; + break; - case UPLOAD_ERR_CANT_WRITE: - $this->setAlert($lng->txt("form_msg_file_cannot_write_to_disk")); - $uploadcheck = false; - break; + case UPLOAD_ERR_CANT_WRITE: + $this->setAlert($lng->txt("form_msg_file_cannot_write_to_disk")); + $uploadcheck = false; + break; - case UPLOAD_ERR_EXTENSION: - $this->setAlert($lng->txt("form_msg_file_upload_stopped_ext")); - $uploadcheck = false; - break; - } - } + case UPLOAD_ERR_EXTENSION: + $this->setAlert($lng->txt("form_msg_file_upload_stopped_ext")); + $uploadcheck = false; + break; + } + } - // check suffixes - if ($pictures["tmp_name"][$index] != "" && is_array($this->getSuffixes())) - { - if (!in_array(strtolower($suffix), $this->getSuffixes())) - { - $this->setAlert($lng->txt("form_msg_file_wrong_file_type")); - $uploadcheck = false; - } - } + // check suffixes + if ($pictures["tmp_name"][$index] != "" && is_array($this->getSuffixes())) { + if (!in_array(strtolower($suffix), $this->getSuffixes())) { + $this->setAlert($lng->txt("form_msg_file_wrong_file_type")); + $uploadcheck = false; + } + } - // virus handling - if ($pictures["tmp_name"][$index] != "") - { - $vir = ilUtil::virusHandling($temp_name, $filename); - if ($vir[0] == false) - { - $this->setAlert($lng->txt("form_msg_file_virus_found")."
                  ".$vir[1]); - $uploadcheck = false; - } - } - } + // virus handling + if ($pictures["tmp_name"][$index] != "") { + $vir = ilUtil::virusHandling($temp_name, $filename); + if ($vir[0] == false) { + $this->setAlert($lng->txt("form_msg_file_virus_found") . "
                  " . $vir[1]); + $uploadcheck = false; + } + } + } + } - } + if (!$uploadcheck) { + return false; + } + + return $this->checkSubItemsInput(); + } - if (!$uploadcheck) - { - return FALSE; - } - - return $this->checkSubItemsInput(); - } + /** + * Insert property html + * + * @return int Size + */ + public function insert($a_tpl) + { + $lng = $this->lng; + + $tpl = new ilTemplate("tpl.prop_filewizardinput.html", true, true, "Services/Form"); - /** - * Insert property html - * - * @return int Size - */ - function insert($a_tpl) - { - $lng = $this->lng; - - $tpl = new ilTemplate("tpl.prop_filewizardinput.html", true, true, "Services/Form"); + $i = 0; + foreach ($this->filenames as $value) { + if (strlen($value)) { + $tpl->setCurrentBlock("image"); + $tpl->setVariable("SRC_IMAGE", $this->getImagePathWeb() . ilUtil::prepareFormOutput($value)); + $tpl->setVariable("PICTURE_FILE", ilUtil::prepareFormOutput($value)); + $tpl->setVariable("ID", $this->getFieldId() . "[$i]"); + $tpl->setVariable("ALT_IMAGE", ilUtil::prepareFormOutput($value)); + $tpl->parseCurrentBlock(); + } + if ($this->getAllowMove()) { + $tpl->setCurrentBlock("move"); + $tpl->setVariable("CMD_UP", "cmd[up" . $this->getFieldId() . "][$i]"); + $tpl->setVariable("CMD_DOWN", "cmd[down" . $this->getFieldId() . "][$i]"); + $tpl->setVariable("ID", $this->getFieldId() . "[$i]"); + include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); + $tpl->setVariable("UP_BUTTON", ilGlyphGUI::get(ilGlyphGUI::UP)); + $tpl->setVariable("DOWN_BUTTON", ilGlyphGUI::get(ilGlyphGUI::DOWN)); + $tpl->parseCurrentBlock(); + } - $i = 0; - foreach ($this->filenames as $value) - { - if (strlen($value)) - { - $tpl->setCurrentBlock("image"); - $tpl->setVariable("SRC_IMAGE", $this->getImagePathWeb() . ilUtil::prepareFormOutput($value)); - $tpl->setVariable("PICTURE_FILE", ilUtil::prepareFormOutput($value)); - $tpl->setVariable("ID", $this->getFieldId() . "[$i]"); - $tpl->setVariable("ALT_IMAGE", ilUtil::prepareFormOutput($value)); - $tpl->parseCurrentBlock(); - } - if ($this->getAllowMove()) - { - $tpl->setCurrentBlock("move"); - $tpl->setVariable("CMD_UP", "cmd[up" . $this->getFieldId() . "][$i]"); - $tpl->setVariable("CMD_DOWN", "cmd[down" . $this->getFieldId() . "][$i]"); - $tpl->setVariable("ID", $this->getFieldId() . "[$i]"); - include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); - $tpl->setVariable("UP_BUTTON", ilGlyphGUI::get(ilGlyphGUI::UP)); - $tpl->setVariable("DOWN_BUTTON", ilGlyphGUI::get(ilGlyphGUI::DOWN)); - $tpl->parseCurrentBlock(); - } + $this->outputSuffixes($tpl, "allowed_image_suffixes"); + + $tpl->setCurrentBlock("row"); + $tpl->setVariable("POST_VAR", $this->getPostVar() . "[$i]"); + $tpl->setVariable("ID", $this->getFieldId() . "[$i]"); + $tpl->setVariable("CMD_ADD", "cmd[add" . $this->getFieldId() . "][$i]"); + $tpl->setVariable("CMD_REMOVE", "cmd[remove" . $this->getFieldId() . "][$i]"); + $tpl->setVariable("ALT_ADD", $lng->txt("add")); + $tpl->setVariable("ALT_REMOVE", $lng->txt("remove")); + if ($this->getDisabled()) { + $tpl->setVariable( + "DISABLED", + " disabled=\"disabled\"" + ); + } + + include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); + $tpl->setVariable("ADD_BUTTON", ilGlyphGUI::get(ilGlyphGUI::ADD)); + $tpl->setVariable("REMOVE_BUTTON", ilGlyphGUI::get(ilGlyphGUI::REMOVE)); + $tpl->setVariable("TXT_MAX_SIZE", $lng->txt("file_notice") . " " . $this->getMaxFileSizeString()); + $tpl->parseCurrentBlock(); + $i++; + } + $tpl->setVariable("ELEMENT_ID", $this->getFieldId()); - $this->outputSuffixes($tpl, "allowed_image_suffixes"); - - $tpl->setCurrentBlock("row"); - $tpl->setVariable("POST_VAR", $this->getPostVar() . "[$i]"); - $tpl->setVariable("ID", $this->getFieldId() . "[$i]"); - $tpl->setVariable("CMD_ADD", "cmd[add" . $this->getFieldId() . "][$i]"); - $tpl->setVariable("CMD_REMOVE", "cmd[remove" . $this->getFieldId() . "][$i]"); - $tpl->setVariable("ALT_ADD", $lng->txt("add")); - $tpl->setVariable("ALT_REMOVE", $lng->txt("remove")); - if ($this->getDisabled()) - { - $tpl->setVariable("DISABLED", - " disabled=\"disabled\""); - } - - include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); - $tpl->setVariable("ADD_BUTTON", ilGlyphGUI::get(ilGlyphGUI::ADD)); - $tpl->setVariable("REMOVE_BUTTON", ilGlyphGUI::get(ilGlyphGUI::REMOVE)); - $tpl->setVariable("TXT_MAX_SIZE", $lng->txt("file_notice") . " " . $this->getMaxFileSizeString()); - $tpl->parseCurrentBlock(); - $i++; - } - $tpl->setVariable("ELEMENT_ID", $this->getFieldId()); - - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $tpl->get()); - $a_tpl->parseCurrentBlock(); - - $main_tpl = $this->tpl; - $main_tpl->addJavascript("./Services/Form/js/ServiceFormWizardInput.js"); - $main_tpl->addJavascript("./Services/Form/templates/default/filewizard.js"); - } + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $tpl->get()); + $a_tpl->parseCurrentBlock(); + + $main_tpl = $this->tpl; + $main_tpl->addJavascript("./Services/Form/js/ServiceFormWizardInput.js"); + $main_tpl->addJavascript("./Services/Form/templates/default/filewizard.js"); + } } diff --git a/Services/Form/classes/class.ilFlashFileInputGUI.php b/Services/Form/classes/class.ilFlashFileInputGUI.php index 49e0c7b968e9f8aa02c5b1e877b38491b3702168..537e548a21dbe4d1f64b2ff444f50a9dda4c04ae 100755 --- a/Services/Form/classes/class.ilFlashFileInputGUI.php +++ b/Services/Form/classes/class.ilFlashFileInputGUI.php @@ -4,403 +4,393 @@ /** * This class represents an image file property in a property form. * -* @author Helmut Schottmüller +* @author Helmut Schottmüller * @version $Id$ * @ingroup ServicesForm */ class ilFlashFileInputGUI extends ilFileInputGUI { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - protected $applet; - protected $applet_path_web; - protected $width; - protected $height; - protected $parameters; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + protected $applet; + protected $applet_path_web; + protected $width; + protected $height; + protected $parameters; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - parent::__construct($a_title, $a_postvar); - $this->setType("flash_file"); - $this->setSuffixes(array("swf")); - $this->width = 550; - $this->height = 400; - $this->parameters = array(); - } + $this->lng = $DIC->language(); + parent::__construct($a_title, $a_postvar); + $this->setType("flash_file"); + $this->setSuffixes(array("swf")); + $this->width = 550; + $this->height = 400; + $this->parameters = array(); + } - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $this->setValue($a_values[$this->getPostVar()]); - } + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $this->setValue($a_values[$this->getPostVar()]); + } - function getValue() - { - return $this->getApplet(); - } + public function getValue() + { + return $this->getApplet(); + } - function setValue($a_value) - { - if (is_array($a_value)) - { - if (array_key_exists('width', $a_value)) $this->setWidth($a_value['width']); - if (array_key_exists('height', $a_value)) $this->setHeight($a_value['height']); - if (array_key_exists('filename', $a_value)) $this->setApplet($a_value['filename']); - if (is_array($a_value['flash_param_name'])) - { - $this->parameters = array(); - foreach ($a_value['flash_param_name'] as $idx => $val) - { - $this->parameters[$val] = $a_value['flash_param_value'][$idx]; - } - } - } - } + public function setValue($a_value) + { + if (is_array($a_value)) { + if (array_key_exists('width', $a_value)) { + $this->setWidth($a_value['width']); + } + if (array_key_exists('height', $a_value)) { + $this->setHeight($a_value['height']); + } + if (array_key_exists('filename', $a_value)) { + $this->setApplet($a_value['filename']); + } + if (is_array($a_value['flash_param_name'])) { + $this->parameters = array(); + foreach ($a_value['flash_param_name'] as $idx => $val) { + $this->parameters[$val] = $a_value['flash_param_value'][$idx]; + } + } + } + } - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; - // remove trailing '/' - $_FILES[$this->getPostVar()]["name"] = rtrim($_FILES[$this->getPostVar()]["name"], '/'); + // remove trailing '/' + $_FILES[$this->getPostVar()]["name"] = rtrim($_FILES[$this->getPostVar()]["name"], '/'); - $filename = $_FILES[$this->getPostVar()]["name"]; - $filename_arr = pathinfo($_FILES[$this->getPostVar()]["name"]); - $suffix = $filename_arr["extension"]; - $mimetype = $_FILES[$this->getPostVar()]["type"]; - $size_bytes = $_FILES[$this->getPostVar()]["size"]; - $temp_name = $_FILES[$this->getPostVar()]["tmp_name"]; - $error = $_FILES[$this->getPostVar()]["error"]; + $filename = $_FILES[$this->getPostVar()]["name"]; + $filename_arr = pathinfo($_FILES[$this->getPostVar()]["name"]); + $suffix = $filename_arr["extension"]; + $mimetype = $_FILES[$this->getPostVar()]["type"]; + $size_bytes = $_FILES[$this->getPostVar()]["size"]; + $temp_name = $_FILES[$this->getPostVar()]["tmp_name"]; + $error = $_FILES[$this->getPostVar()]["error"]; - // error handling - if ($error > 0) - { - switch ($error) - { - case UPLOAD_ERR_INI_SIZE: - $this->setAlert($lng->txt("form_msg_file_size_exceeds")); - return false; - break; - - case UPLOAD_ERR_FORM_SIZE: - $this->setAlert($lng->txt("form_msg_file_size_exceeds")); - return false; - break; - - case UPLOAD_ERR_PARTIAL: - $this->setAlert($lng->txt("form_msg_file_partially_uploaded")); - return false; - break; - - case UPLOAD_ERR_NO_FILE: - if ($this->getRequired()) - { - if (!strlen($this->getValue())) - { - $this->setAlert($lng->txt("form_msg_file_no_upload")); - return false; - } - } - break; - - case UPLOAD_ERR_NO_TMP_DIR: - $this->setAlert($lng->txt("form_msg_file_missing_tmp_dir")); - return false; - break; - - case UPLOAD_ERR_CANT_WRITE: - $this->setAlert($lng->txt("form_msg_file_cannot_write_to_disk")); - return false; - break; - - case UPLOAD_ERR_EXTENSION: - $this->setAlert($lng->txt("form_msg_file_upload_stopped_ext")); - return false; - break; - } - } - - // check suffixes - if ($_FILES[$this->getPostVar()]["tmp_name"] != "" && - is_array($this->getSuffixes())) - { - if (!in_array(strtolower($suffix), $this->getSuffixes())) - { - $this->setAlert($lng->txt("form_msg_file_wrong_file_type")); - return false; - } - } - - // virus handling - if ($_FILES[$this->getPostVar()]["tmp_name"] != "") - { - $vir = ilUtil::virusHandling($temp_name, $filename); - if ($vir[0] == false) - { - $this->setAlert($lng->txt("form_msg_file_virus_found")."
                  ".$vir[1]); - return false; - } - } + // error handling + if ($error > 0) { + switch ($error) { + case UPLOAD_ERR_INI_SIZE: + $this->setAlert($lng->txt("form_msg_file_size_exceeds")); + return false; + break; + + case UPLOAD_ERR_FORM_SIZE: + $this->setAlert($lng->txt("form_msg_file_size_exceeds")); + return false; + break; + + case UPLOAD_ERR_PARTIAL: + $this->setAlert($lng->txt("form_msg_file_partially_uploaded")); + return false; + break; + + case UPLOAD_ERR_NO_FILE: + if ($this->getRequired()) { + if (!strlen($this->getValue())) { + $this->setAlert($lng->txt("form_msg_file_no_upload")); + return false; + } + } + break; + + case UPLOAD_ERR_NO_TMP_DIR: + $this->setAlert($lng->txt("form_msg_file_missing_tmp_dir")); + return false; + break; + + case UPLOAD_ERR_CANT_WRITE: + $this->setAlert($lng->txt("form_msg_file_cannot_write_to_disk")); + return false; + break; + + case UPLOAD_ERR_EXTENSION: + $this->setAlert($lng->txt("form_msg_file_upload_stopped_ext")); + return false; + break; + } + } + + // check suffixes + if ($_FILES[$this->getPostVar()]["tmp_name"] != "" && + is_array($this->getSuffixes())) { + if (!in_array(strtolower($suffix), $this->getSuffixes())) { + $this->setAlert($lng->txt("form_msg_file_wrong_file_type")); + return false; + } + } + + // virus handling + if ($_FILES[$this->getPostVar()]["tmp_name"] != "") { + $vir = ilUtil::virusHandling($temp_name, $filename); + if ($vir[0] == false) { + $this->setAlert($lng->txt("form_msg_file_virus_found") . "
                  " . $vir[1]); + return false; + } + } - if (is_array($_POST[$this->getPostVar()])) - { - if (($this->getRequired() && strlen($_POST[$this->getPostVar()]['width']) == 0) || - ($this->getRequired() && strlen($_POST[$this->getPostVar()]['height']) == 0)) - { - $this->setAlert($lng->txt("msg_input_is_required")); - return false; - } - if (is_array($_POST[$this->getPostVar()]['flash_param_name'])) - { - foreach ($_POST[$this->getPostVar()]['flash_param_name'] as $idx => $val) - { - if (strlen($val) == 0 || strlen($_POST[$this->getPostVar()]['flash_param_value'][$idx]) == 0) - { - $this->setAlert($lng->txt("msg_input_is_required")); - return false; - } - } - } - } - - return true; - } + if (is_array($_POST[$this->getPostVar()])) { + if (($this->getRequired() && strlen($_POST[$this->getPostVar()]['width']) == 0) || + ($this->getRequired() && strlen($_POST[$this->getPostVar()]['height']) == 0)) { + $this->setAlert($lng->txt("msg_input_is_required")); + return false; + } + if (is_array($_POST[$this->getPostVar()]['flash_param_name'])) { + foreach ($_POST[$this->getPostVar()]['flash_param_name'] as $idx => $val) { + if (strlen($val) == 0 || strlen($_POST[$this->getPostVar()]['flash_param_value'][$idx]) == 0) { + $this->setAlert($lng->txt("msg_input_is_required")); + return false; + } + } + } + } + + return true; + } - /** - * Set applet. - * - * @param string $a_applet Applet - */ - function setApplet($a_applet) - { - $this->applet = $a_applet; - } + /** + * Set applet. + * + * @param string $a_applet Applet + */ + public function setApplet($a_applet) + { + $this->applet = $a_applet; + } - /** - * Get applet. - * - * @return string Applet - */ - function getApplet() - { - return $this->applet; - } + /** + * Get applet. + * + * @return string Applet + */ + public function getApplet() + { + return $this->applet; + } - /** - * Set applet.path web - * - * @param string $a_path Applet path web - */ - function setAppletPathWeb($a_path) - { - $this->applet_path_web = $a_path; - } + /** + * Set applet.path web + * + * @param string $a_path Applet path web + */ + public function setAppletPathWeb($a_path) + { + $this->applet_path_web = $a_path; + } - /** - * Get applet.path web - * - * @return string Applet path web - */ - function getAppletPathWeb() - { - return $this->applet_path_web; - } + /** + * Get applet.path web + * + * @return string Applet path web + */ + public function getAppletPathWeb() + { + return $this->applet_path_web; + } - /** - * Get width. - * - * @return integer width - */ - function getWidth() - { - return $this->width; - } + /** + * Get width. + * + * @return integer width + */ + public function getWidth() + { + return $this->width; + } - /** - * Set width. - * - * @param integer $a_width width - */ - function setWidth($a_width) - { - $this->width = $a_width; - } + /** + * Set width. + * + * @param integer $a_width width + */ + public function setWidth($a_width) + { + $this->width = $a_width; + } - /** - * Get height. - * - * @return integer height - */ - function getHeight() - { - return $this->height; - } + /** + * Get height. + * + * @return integer height + */ + public function getHeight() + { + return $this->height; + } - /** - * Set height. - * - * @param integer $a_height height - */ - function setHeight($a_height) - { - $this->height = $a_height; - } - - /** - * Get parameters. - * - * @return array Parameters - */ - function getParameters() - { - return $this->parameters; - } - - /** - * Set parameters. - * - * @param array $a_parameters Parameters - */ - function setParameters($a_parameters) - { - $this->parameters = $a_parameters; - } + /** + * Set height. + * + * @param integer $a_height height + */ + public function setHeight($a_height) + { + $this->height = $a_height; + } + + /** + * Get parameters. + * + * @return array Parameters + */ + public function getParameters() + { + return $this->parameters; + } + + /** + * Set parameters. + * + * @param array $a_parameters Parameters + */ + public function setParameters($a_parameters) + { + $this->parameters = $a_parameters; + } - /** - * Add parameter. - * - * @param string $name Parameter name - * @param string $value Parameter value - */ - function addParameter($name, $value) - { - $this->parameters[$name] = $value; - } - - /** - * Remove parameter. - * - * @param string $name Parameter name - */ - function removeParameter($name) - { - unset($this->parameters[$name]); - } + /** + * Add parameter. + * + * @param string $name Parameter name + * @param string $value Parameter value + */ + public function addParameter($name, $value) + { + $this->parameters[$name] = $value; + } + + /** + * Remove parameter. + * + * @param string $name Parameter name + */ + public function removeParameter($name) + { + unset($this->parameters[$name]); + } - /** - * Remove all parameters - */ - function clearParameters() - { - $this->parameters = array(); - } - - /** - * Insert property html - */ - function insert($a_tpl) - { - $lng = $this->lng; - - $template = new ilTemplate("tpl.prop_flashfile.html", true, true, "Services/Form"); - if ($this->getApplet() != "") - { - $this->outputSuffixes($template); - if (count($this->getParameters())) - { - $index = 0; - $params = array(); - foreach ($this->getParameters() as $name => $value) - { - array_push($params, urlencode($name) . "=" . urlencode($value)); - $template->setCurrentBlock("applet_param_input"); - $template->setVariable("TEXT_NAME", $lng->txt("name")); - $template->setVariable("TEXT_VALUE", $lng->txt("value")); - $template->setVariable("PARAM_INDEX", $index); - $template->setVariable("POST_VAR_P", $this->getPostVar()); - $template->setVariable("VALUE_NAME", "value=\"" . ilUtil::prepareFormOutput($name) . "\""); - $template->setVariable("VALUE_VALUE", "value=\"" . ilUtil::prepareFormOutput($value) . "\""); - $template->setVariable("TEXT_DELETE_PARAM", $lng->txt("delete_parameter")); - $template->parseCurrentBlock(); - $index++; - } - $template->setCurrentBlock("applet_parameter"); - $template->setVariable("PARAM_VALUE", join($params, "&")); - $template->parseCurrentBlock(); - $template->setCurrentBlock("flash_vars"); - $template->setVariable("PARAM_VALUE", join($params, "&")); - $template->parseCurrentBlock(); - } - $template->setCurrentBlock("applet"); - $template->setVariable("TEXT_ADD_PARAM", $lng->txt("add_parameter")); - $template->setVariable("APPLET_WIDTH", $this->getWidth()); - $template->setVariable("APPLET_HEIGHT", $this->getHeight()); - $template->setVariable("POST_VAR_D", $this->getPostVar()); - $template->setVariable("FILENAME", $this->getApplet()); - $template->setVariable("TEXT_WIDTH", $lng->txt("width")); - $template->setVariable("TEXT_HEIGHT", $lng->txt("height")); - $template->setVariable("APPLET_FILE", $this->getApplet()); - $template->setVariable("APPLET_PATH", $this->getAppletPathWeb().$this->getApplet()); - if ($this->getWidth()) $template->setVariable("VALUE_WIDTH", "value=\"" . $this->getWidth() . "\""); - if ($this->getHeight()) $template->setVariable("VALUE_HEIGHT", "value=\"" . $this->getHeight() . "\""); - $template->setVariable("ID", $this->getFieldId()); - $template->setVariable("TXT_DELETE_EXISTING", - $lng->txt("delete_existing_file")); - $template->parseCurrentBlock(); - } - - $js_tpl = new ilTemplate('tpl.flashAddParam.js', true, true, 'Services/Form'); - $js_tpl->setVariable("TEXT_NAME", $lng->txt("name")); - $js_tpl->setVariable("TEXT_VALUE", $lng->txt("value")); - $js_tpl->setVariable("POST_VAR", $this->getPostVar()); - $js_tpl->setVariable("TEXT_DELETE_PARAM", $lng->txt("delete_parameter")); - $js_tpl->setVariable("TEXT_CONFIRM_DELETE_PARAMETER", $lng->txt("confirm_delete_parameter")); - - $template->setVariable("POST_VAR", $this->getPostVar()); - $template->setVariable("ID", $this->getFieldId()); - $template->setVariable("TXT_MAX_SIZE", $lng->txt("file_notice")." ".$this->getMaxFileSizeString()); - $template->setVariable("JAVASCRIPT_FLASH", $js_tpl->get()); + /** + * Remove all parameters + */ + public function clearParameters() + { + $this->parameters = array(); + } + + /** + * Insert property html + */ + public function insert($a_tpl) + { + $lng = $this->lng; + + $template = new ilTemplate("tpl.prop_flashfile.html", true, true, "Services/Form"); + if ($this->getApplet() != "") { + $this->outputSuffixes($template); + if (count($this->getParameters())) { + $index = 0; + $params = array(); + foreach ($this->getParameters() as $name => $value) { + array_push($params, urlencode($name) . "=" . urlencode($value)); + $template->setCurrentBlock("applet_param_input"); + $template->setVariable("TEXT_NAME", $lng->txt("name")); + $template->setVariable("TEXT_VALUE", $lng->txt("value")); + $template->setVariable("PARAM_INDEX", $index); + $template->setVariable("POST_VAR_P", $this->getPostVar()); + $template->setVariable("VALUE_NAME", "value=\"" . ilUtil::prepareFormOutput($name) . "\""); + $template->setVariable("VALUE_VALUE", "value=\"" . ilUtil::prepareFormOutput($value) . "\""); + $template->setVariable("TEXT_DELETE_PARAM", $lng->txt("delete_parameter")); + $template->parseCurrentBlock(); + $index++; + } + $template->setCurrentBlock("applet_parameter"); + $template->setVariable("PARAM_VALUE", join($params, "&")); + $template->parseCurrentBlock(); + $template->setCurrentBlock("flash_vars"); + $template->setVariable("PARAM_VALUE", join($params, "&")); + $template->parseCurrentBlock(); + } + $template->setCurrentBlock("applet"); + $template->setVariable("TEXT_ADD_PARAM", $lng->txt("add_parameter")); + $template->setVariable("APPLET_WIDTH", $this->getWidth()); + $template->setVariable("APPLET_HEIGHT", $this->getHeight()); + $template->setVariable("POST_VAR_D", $this->getPostVar()); + $template->setVariable("FILENAME", $this->getApplet()); + $template->setVariable("TEXT_WIDTH", $lng->txt("width")); + $template->setVariable("TEXT_HEIGHT", $lng->txt("height")); + $template->setVariable("APPLET_FILE", $this->getApplet()); + $template->setVariable("APPLET_PATH", $this->getAppletPathWeb() . $this->getApplet()); + if ($this->getWidth()) { + $template->setVariable("VALUE_WIDTH", "value=\"" . $this->getWidth() . "\""); + } + if ($this->getHeight()) { + $template->setVariable("VALUE_HEIGHT", "value=\"" . $this->getHeight() . "\""); + } + $template->setVariable("ID", $this->getFieldId()); + $template->setVariable( + "TXT_DELETE_EXISTING", + $lng->txt("delete_existing_file") + ); + $template->parseCurrentBlock(); + } + + $js_tpl = new ilTemplate('tpl.flashAddParam.js', true, true, 'Services/Form'); + $js_tpl->setVariable("TEXT_NAME", $lng->txt("name")); + $js_tpl->setVariable("TEXT_VALUE", $lng->txt("value")); + $js_tpl->setVariable("POST_VAR", $this->getPostVar()); + $js_tpl->setVariable("TEXT_DELETE_PARAM", $lng->txt("delete_parameter")); + $js_tpl->setVariable("TEXT_CONFIRM_DELETE_PARAMETER", $lng->txt("confirm_delete_parameter")); + + $template->setVariable("POST_VAR", $this->getPostVar()); + $template->setVariable("ID", $this->getFieldId()); + $template->setVariable("TXT_MAX_SIZE", $lng->txt("file_notice") . " " . $this->getMaxFileSizeString()); + $template->setVariable("JAVASCRIPT_FLASH", $js_tpl->get()); - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $template->get()); - $a_tpl->parseCurrentBlock(); - - include_once "./Services/YUI/classes/class.ilYuiUtil.php"; - ilYuiUtil::initConnectionWithAnimation(); - } - - /** - * Get deletion flag - */ - function getDeletionFlag() - { - if ($_POST[$this->getPostVar()."_delete"]) - { - return true; - } - return false; - } + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $template->get()); + $a_tpl->parseCurrentBlock(); + + include_once "./Services/YUI/classes/class.ilYuiUtil.php"; + ilYuiUtil::initConnectionWithAnimation(); + } + /** + * Get deletion flag + */ + public function getDeletionFlag() + { + if ($_POST[$this->getPostVar() . "_delete"]) { + return true; + } + return false; + } } -?> \ No newline at end of file diff --git a/Services/Form/classes/class.ilFormGUI.php b/Services/Form/classes/class.ilFormGUI.php index e69da7098fbf751a335e9b8fa14a918752badb75..5dbbec96e5ecd45f5c3ee71143fd146e65d4219d 100644 --- a/Services/Form/classes/class.ilFormGUI.php +++ b/Services/Form/classes/class.ilFormGUI.php @@ -8,277 +8,268 @@ /** * This class represents a form user interface * -* @author Alex Killing +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilFormGUI { - protected $formaction; - protected $multipart = false; - protected $keepopen = false; - protected $opentag = true; - protected $id; - protected $name; - protected $prevent_double_submission = false; + protected $formaction; + protected $multipart = false; + protected $keepopen = false; + protected $opentag = true; + protected $id; + protected $name; + protected $prevent_double_submission = false; - /** - * Set FormAction. - * - * @param string $a_formaction FormAction - */ - function setFormAction($a_formaction) - { - $this->formaction = $a_formaction; - } + /** + * Set FormAction. + * + * @param string $a_formaction FormAction + */ + public function setFormAction($a_formaction) + { + $this->formaction = $a_formaction; + } - /** - * Get FormAction. - * - * @return string FormAction - */ - function getFormAction() - { - return $this->formaction; - } + /** + * Get FormAction. + * + * @return string FormAction + */ + public function getFormAction() + { + return $this->formaction; + } - /** - * Set Target. - * - * @param string $a_target Target - */ - function setTarget($a_target) - { - $this->target = $a_target; - } + /** + * Set Target. + * + * @param string $a_target Target + */ + public function setTarget($a_target) + { + $this->target = $a_target; + } - /** - * Get Target. - * - * @return string Target - */ - function getTarget() - { - return $this->target; - } + /** + * Get Target. + * + * @return string Target + */ + public function getTarget() + { + return $this->target; + } - /** - * Set Enctype Multipart/Formdata true/false. - * - * @param boolean $a_multipart Enctype Multipart/Formdata true/false - */ - function setMultipart($a_multipart) - { - $this->multipart = $a_multipart; - } + /** + * Set Enctype Multipart/Formdata true/false. + * + * @param boolean $a_multipart Enctype Multipart/Formdata true/false + */ + public function setMultipart($a_multipart) + { + $this->multipart = $a_multipart; + } - /** - * Get Enctype Multipart/Formdata true/false. - * - * @return boolean Enctype Multipart/Formdata true/false - */ - function getMultipart() - { - return $this->multipart; - } + /** + * Get Enctype Multipart/Formdata true/false. + * + * @return boolean Enctype Multipart/Formdata true/false + */ + public function getMultipart() + { + return $this->multipart; + } - /** - * Set Id. If you use multiple forms on a screen you should set this value. - * - * @param string $a_id Id - */ - function setId($a_id) - { - $this->id = $a_id; - } + /** + * Set Id. If you use multiple forms on a screen you should set this value. + * + * @param string $a_id Id + */ + public function setId($a_id) + { + $this->id = $a_id; + } - /** - * Get Id. - * - * @return string Id - */ - function getId() - { - return $this->id; - } - - /** - * Set Name. Useful for Javascript - * - * @param string $a_name Name - */ - function setName($a_name) - { - $this->name = $a_name; - } + /** + * Get Id. + * + * @return string Id + */ + public function getId() + { + return $this->id; + } + + /** + * Set Name. Useful for Javascript + * + * @param string $a_name Name + */ + public function setName($a_name) + { + $this->name = $a_name; + } - /** - * Get Name. - * - * @return string Name - */ - function getName() - { - return $this->name; - } + /** + * Get Name. + * + * @return string Name + */ + public function getName() + { + return $this->name; + } - /** - * Set Keep Form Tag Open. - * - * @param boolean $a_keepopen Keep Form Tag Open - */ - function setKeepOpen($a_keepopen) - { - $this->keepopen = $a_keepopen; - } + /** + * Set Keep Form Tag Open. + * + * @param boolean $a_keepopen Keep Form Tag Open + */ + public function setKeepOpen($a_keepopen) + { + $this->keepopen = $a_keepopen; + } - /** - * Get Keep Form Tag Open. - * - * @return boolean Keep Form Tag Open - */ - function getKeepOpen() - { - return $this->keepopen; - } + /** + * Get Keep Form Tag Open. + * + * @return boolean Keep Form Tag Open + */ + public function getKeepOpen() + { + return $this->keepopen; + } - /** - * Enable/Disable Open Form Tag. - * - * @param boolean $a_keepopen enable/disable form open tag - */ - function setOpenTag($a_open) - { - $this->opentag = $a_open; - } + /** + * Enable/Disable Open Form Tag. + * + * @param boolean $a_keepopen enable/disable form open tag + */ + public function setOpenTag($a_open) + { + $this->opentag = $a_open; + } - /** - * Get Open Form Tag Enabled. - * - * @return boolean open form tag enabled - */ - function getOpenTag() - { - return $this->opentag; - } - - /** - * Set close tag - * - * @param boolean close tag true/false - */ - function setCloseTag($a_val) - { - $this->setKeepOpen(!$a_val); - } - - /** - * Get close tag - * - * @return boolean close tag true/false - */ - function getCloseTag() - { - return !$this->getKeepOpen(); - } - - /** - * Set prevent double submission - * - * @param bool $a_val prevent double submission - */ - function setPreventDoubleSubmission($a_val) - { - $this->prevent_double_submission = $a_val; - } - - /** - * Get prevent double submission - * - * @return bool prevent double submission - */ - function getPreventDoubleSubmission() - { - return $this->prevent_double_submission; - } - - /** - * Get HTML. - */ - function getHTML() - { - $tpl = new ilTemplate("tpl.form.html", true, true, "Services/Form"); - - // this line also sets multipart, so it must be before the multipart check - $content = $this->getContent(); - if ($this->getOpenTag()) - { - $opentpl = new ilTemplate('tpl.form_open.html', true, true, "Services/Form"); - if ($this->getTarget() != "") - { - $opentpl->setCurrentBlock("form_target"); - $opentpl->setVariable("FORM_TARGET", $this->getTarget()); - $opentpl->parseCurrentBlock(); - } - if ($this->getName() != "") - { - $opentpl->setCurrentBlock("form_name"); - $opentpl->setVariable("FORM_NAME", $this->getName()); - $opentpl->parseCurrentBlock(); - } - if ($this->getPreventDoubleSubmission()) - { - $opentpl->setVariable("FORM_CLASS", "preventDoubleSubmission"); - } + /** + * Get Open Form Tag Enabled. + * + * @return boolean open form tag enabled + */ + public function getOpenTag() + { + return $this->opentag; + } + + /** + * Set close tag + * + * @param boolean close tag true/false + */ + public function setCloseTag($a_val) + { + $this->setKeepOpen(!$a_val); + } + + /** + * Get close tag + * + * @return boolean close tag true/false + */ + public function getCloseTag() + { + return !$this->getKeepOpen(); + } + + /** + * Set prevent double submission + * + * @param bool $a_val prevent double submission + */ + public function setPreventDoubleSubmission($a_val) + { + $this->prevent_double_submission = $a_val; + } + + /** + * Get prevent double submission + * + * @return bool prevent double submission + */ + public function getPreventDoubleSubmission() + { + return $this->prevent_double_submission; + } + + /** + * Get HTML. + */ + public function getHTML() + { + $tpl = new ilTemplate("tpl.form.html", true, true, "Services/Form"); + + // this line also sets multipart, so it must be before the multipart check + $content = $this->getContent(); + if ($this->getOpenTag()) { + $opentpl = new ilTemplate('tpl.form_open.html', true, true, "Services/Form"); + if ($this->getTarget() != "") { + $opentpl->setCurrentBlock("form_target"); + $opentpl->setVariable("FORM_TARGET", $this->getTarget()); + $opentpl->parseCurrentBlock(); + } + if ($this->getName() != "") { + $opentpl->setCurrentBlock("form_name"); + $opentpl->setVariable("FORM_NAME", $this->getName()); + $opentpl->parseCurrentBlock(); + } + if ($this->getPreventDoubleSubmission()) { + $opentpl->setVariable("FORM_CLASS", "preventDoubleSubmission"); + } - if ($this->getMultipart()) - { - $opentpl->touchBlock("multipart"); - /*if (function_exists("apc_fetch")) - // - // Progress bar would need additional browser window (popup) - // to not be stopped, when form is submitted (we can't work - // with an iframe or httprequest solution here) - // - { - $tpl->touchBlock("onsubmit"); - - //onsubmit="postForm('{ON_ACT}','form_{F_ID}',1); return false;" - $tpl->setCurrentBlock("onsubmit"); - $tpl->setVariable("ON_ACT", $this->getFormAction()); - $tpl->setVariable("F_ID", $this->getId()); - $tpl->setVariable("F_ID", $this->getId()); - $tpl->parseCurrentBlock(); - - $tpl->setCurrentBlock("hidden_progress"); - $tpl->setVariable("APC_PROGRESS_ID", uniqid()); - $tpl->setVariable("APC_FORM_ID", $this->getId()); - $tpl->parseCurrentBlock(); - }*/ - } - $opentpl->setVariable("FORM_ACTION", $this->getFormAction()); - if ($this->getId() != "") - { - $opentpl->setVariable("FORM_ID", $this->getId()); - } - $opentpl->parseCurrentBlock(); - $tpl->setVariable('FORM_OPEN_TAG', $opentpl->get()); - } - $tpl->setVariable("FORM_CONTENT", $content); - if (!$this->getKeepOpen()) - { - $tpl->setVariable("FORM_CLOSE_TAG", ""); - } - return $tpl->get(); - } + if ($this->getMultipart()) { + $opentpl->touchBlock("multipart"); + /*if (function_exists("apc_fetch")) + // + // Progress bar would need additional browser window (popup) + // to not be stopped, when form is submitted (we can't work + // with an iframe or httprequest solution here) + // + { + $tpl->touchBlock("onsubmit"); - /** - * Get Content. - */ - function getContent() - { - return ""; - } + //onsubmit="postForm('{ON_ACT}','form_{F_ID}',1); return false;" + $tpl->setCurrentBlock("onsubmit"); + $tpl->setVariable("ON_ACT", $this->getFormAction()); + $tpl->setVariable("F_ID", $this->getId()); + $tpl->setVariable("F_ID", $this->getId()); + $tpl->parseCurrentBlock(); + $tpl->setCurrentBlock("hidden_progress"); + $tpl->setVariable("APC_PROGRESS_ID", uniqid()); + $tpl->setVariable("APC_FORM_ID", $this->getId()); + $tpl->parseCurrentBlock(); + }*/ + } + $opentpl->setVariable("FORM_ACTION", $this->getFormAction()); + if ($this->getId() != "") { + $opentpl->setVariable("FORM_ID", $this->getId()); + } + $opentpl->parseCurrentBlock(); + $tpl->setVariable('FORM_OPEN_TAG', $opentpl->get()); + } + $tpl->setVariable("FORM_CONTENT", $content); + if (!$this->getKeepOpen()) { + $tpl->setVariable("FORM_CLOSE_TAG", ""); + } + return $tpl->get(); + } + + /** + * Get Content. + */ + public function getContent() + { + return ""; + } } -?> \ No newline at end of file diff --git a/Services/Form/classes/class.ilFormPropertyDispatchGUI.php b/Services/Form/classes/class.ilFormPropertyDispatchGUI.php index 50722152f144aff5a7bb090f10a9437f720e45de..981eb1a0c5dfc4484e3000f1e7a5524ccff6db45 100644 --- a/Services/Form/classes/class.ilFormPropertyDispatchGUI.php +++ b/Services/Form/classes/class.ilFormPropertyDispatchGUI.php @@ -8,62 +8,60 @@ * @author Alex Killing * @version $Id$ * @ilCtrl_Calls ilFormPropertyDispatchGUI: -* @ingroup +* @ingroup */ class ilFormPropertyDispatchGUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * Constructor - */ - function __construct() - { - global $DIC; + /** + * Constructor + */ + public function __construct() + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - } + $this->ctrl = $DIC->ctrl(); + } - /** - * Set item - * - * @param object item - */ - function setItem($a_val) - { - $this->item = $a_val; - } - - /** - * Get item - * - * @return object item - */ - function getItem() - { - return $this->item; - } - - /** - * Execute command. - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd(); - - if (strtolower(get_class($this->getItem())) != $next_class) - { - die("ilFormPropertyDispatch: Forward Error. (".get_class($this->getItem())."-".$next_class.")"); - } - - return $ilCtrl->forwardCommand($this->getItem()); - } + /** + * Set item + * + * @param object item + */ + public function setItem($a_val) + { + $this->item = $a_val; + } + + /** + * Get item + * + * @return object item + */ + public function getItem() + { + return $this->item; + } + + /** + * Execute command. + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd(); + if (strtolower(get_class($this->getItem())) != $next_class) { + die("ilFormPropertyDispatch: Forward Error. (" . get_class($this->getItem()) . "-" . $next_class . ")"); + } + + return $ilCtrl->forwardCommand($this->getItem()); + } } diff --git a/Services/Form/classes/class.ilFormPropertyGUI.php b/Services/Form/classes/class.ilFormPropertyGUI.php index 1a4eb2d0865a1f13fa157745fa709cd0eb4e18a0..d484b7baf3397f5d5c55eb06373e84dd7081f810 100755 --- a/Services/Form/classes/class.ilFormPropertyGUI.php +++ b/Services/Form/classes/class.ilFormPropertyGUI.php @@ -4,528 +4,512 @@ /** * This class represents a property in a property form. * -* @author Alex Killing +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilFormPropertyGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - protected $type; - protected $title; - protected $postvar; - protected $info; - protected $alert; - protected $required = false; - protected $parentgui; - protected $parentform; - protected $hidden_title = ""; - protected $multi = false; - protected $multi_sortable = false; - protected $multi_addremove = true; - protected $multi_values; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->setTitle($a_title); - $this->setPostVar($a_postvar); - $this->setDisabled(false); - } - - /** - * Execute command. - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd(); - - return $this->$cmd(); - } - - /** - * Set Type. - * - * @param string $a_type Type - */ - protected function setType($a_type) - { - $this->type = $a_type; - } - - /** - * Get Type. - * - * @return string Type - */ - function getType() - { - return $this->type; - } - - /** - * Set Title. - * - * @param string $a_title Title - */ - function setTitle($a_title) - { - $this->title = $a_title; - } - - /** - * Get Title. - * - * @return string Title - */ - function getTitle() - { - return $this->title; - } - - /** - * Set Post Variable. - * - * @param string $a_postvar Post Variable - */ - function setPostVar($a_postvar) - { - $this->postvar = $a_postvar; - } - - /** - * Get Post Variable. - * - * @return string Post Variable - */ - function getPostVar() - { - return $this->postvar; - } - - /** - * Get Post Variable. - * - * @return string Post Variable - */ - function getFieldId() - { - $id = str_replace("[", "__", $this->getPostVar()); - $id = str_replace("]", "__", $id); - - return $id; - } - - /** - * Set Information Text. - * - * @param string $a_info Information Text - */ - function setInfo($a_info) - { - $this->info = $a_info; - } - - /** - * Get Information Text. - * - * @return string Information Text - */ - function getInfo() - { - return $this->info; - } - - /** - * Set Alert Text. - * - * @param string $a_alert Alert Text - */ - function setAlert($a_alert) - { - $this->alert = $a_alert; - } - - /** - * Get Alert Text. - * - * @return string Alert Text - */ - function getAlert() - { - return $this->alert; - } - - /** - * Set Required. - * - * @param boolean $a_required Required - */ - function setRequired($a_required) - { - $this->required = $a_required; - } - - /** - * Get Required. - * - * @return boolean Required - */ - function getRequired() - { - return $this->required; - } - - /** - * Set Disabled. - * - * @param boolean $a_disabled Disabled - */ - function setDisabled($a_disabled) - { - $this->disabled = $a_disabled; - } - - /** - * Get Disabled. - * - * @return boolean Disabled - */ - function getDisabled() - { - return $this->disabled; - } - - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - return false; // please overwrite - } - - /** - * Set Parent Form. - * - * @param object $a_parentform Parent Form - */ - function setParentForm($a_parentform) - { - $this->setParent($a_parentform); - } - - /** - * Get Parent Form. - * - * @return object Parent Form - */ - function getParentForm() - { - return $this->getParent(); - } - - /** - * Set Parent GUI object. - * - * @param object parent gui object - */ - function setParent($a_val) - { - $this->parent_gui = $a_val; - } - - /** - * Get Parent GUI object. - * - * @return object parent gui object - */ - function getParent() - { - return $this->parent_gui; - } - - /** - * Get sub form html - * - */ - public function getSubForm() - { - return ""; - } - - /** - * Sub form hidden on init? - * - */ - public function hideSubForm() - { - return false; - } - - /** - * Set hidden title (for screenreaders) - * - * @param string hidden title - */ - function setHiddenTitle($a_val) - { - $this->hidden_title = $a_val; - } - - /** - * Get hidden title - * - * @return string hidden title - */ - function getHiddenTitle() - { - return $this->hidden_title; - } - - /** - * Get item by post var - * - * @return mixed false or item object - */ - function getItemByPostVar($a_post_var) - { - if ($this->getPostVar() == $a_post_var) - { - return $this; - } - - return false; - } - - /** - * serialize data - */ - function serializeData() - { - return serialize($this->getValue()); - } - - /** - * unserialize data - */ - function unserializeData($a_data) - { - $data = unserialize($a_data); - - if ($data) - { - $this->setValue($data); - } - else - { - $this->setValue(false); - } - } - - /** - * Write to session - */ - function writeToSession() - { - $parent = $this->getParent(); - if (!is_object($parent)) - { - die("You must set parent for ".get_class($this)." to use serialize feature."); - } - $_SESSION["form_".$parent->getId()][$this->getFieldId()] = - $this->serializeData(); - } - - /** - * Clear session value - */ - function clearFromSession() - { - $parent = $this->getParent(); - if (!is_object($parent)) - { - die("You must set parent for ".get_class($this)." to use serialize feature."); - } - $_SESSION["form_".$parent->getId()][$this->getFieldId()] = false; - } - - /** - * Read from session - */ - function readFromSession() - { - $parent = $this->getParent(); - if (!is_object($parent)) - { - die("You must set parent for ".get_class($this)." to use serialize feature."); - } - $this->unserializeData($_SESSION["form_".$parent->getId()][$this->getFieldId()]); - } - - /** - * Get hidden tag (used for disabled properties) - */ - function getHiddenTag($a_post_var, $a_value) - { - return ''; - } - - /** - * Set Multi - * - * @param bool $a_multi Multi - */ - public function setMulti($a_multi, $a_sortable = false, $a_addremove = true) - { - if(!$this instanceof ilMultiValuesItem) - { - require_once 'Services/Form/exceptions/class.ilFormException.php'; - throw new ilFormException(sprintf( - "%s not supported for form property type %s", - __FUNCTION__, get_class($this) - )); - } - - $this->multi = (bool)$a_multi; - $this->multi_sortable = (bool)$a_sortable; - $this->multi_addremove = (bool)$a_addremove; - } - - /** - * Get Multi - * - * @return bool Multi - */ - public function getMulti() - { - return $this->multi; - } - - /** - * Set multi values - * - * @param array $a_values - */ - public function setMultiValues(array $a_values) - { - $this->multi_values = array_unique($a_values); - } - - /** - * Get multi values - * - * @return array - */ - public function getMultiValues() - { - return $this->multi_values; - } - - /** - * Get HTML for multiple value icons - * - * @param bool $a_sortable - * @return string; - */ - protected function getMultiIconsHTML() - { - $lng = $this->lng; - - $id = $this->getFieldId(); - - $tpl = new ilTemplate("tpl.multi_icons.html", true, true, "Services/Form"); - - $html = ""; - if ($this->multi_addremove) - { - $tpl->setCurrentBlock("addremove"); - $tpl->setVariable("ID", $id); - $tpl->setVariable("TXT_ADD", $lng->txt("add")); - $tpl->setVariable("TXT_REMOVE", $lng->txt("remove")); - include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); - $tpl->setVariable("SRC_ADD", ilGlyphGUI::get(ilGlyphGUI::ADD)); - $tpl->setVariable("SRC_REMOVE", ilGlyphGUI::get(ilGlyphGUI::REMOVE)); - $tpl->parseCurrentBlock(); - } - - if ($this->multi_sortable) - { - - $tpl->setCurrentBlock("sortable"); - $tpl->setVariable("ID", $id); - $tpl->setVariable("TXT_DOWN", $lng->txt("down")); - $tpl->setVariable("TXT_UP", $lng->txt("up")); - include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); - $tpl->setVariable("SRC_UP", ilGlyphGUI::get(ilGlyphGUI::UP)); - $tpl->setVariable("SRC_DOWN", ilGlyphGUI::get(ilGlyphGUI::DOWN)); - $tpl->parseCurrentBlock(); - } - - return $tpl->get(); - } - - /** - * Get content that has to reside outside of the parent form tag, e.g. panels/layers - * - * @return string - */ - public function getContentOutsideFormTag() - { - - } - - /** - * Remove prohibited characters - * see #19159 - * - * @param string $a_text - * @return string - */ - static function removeProhibitedCharacters($a_text) - { - return str_replace("\x0B", "", $a_text); - } - - /** - * Strip slashes with add space fallback, see https://www.ilias.de/mantis/view.php?id=19727 - * - * @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; - } - - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + protected $type; + protected $title; + protected $postvar; + protected $info; + protected $alert; + protected $required = false; + protected $parentgui; + protected $parentform; + protected $hidden_title = ""; + protected $multi = false; + protected $multi_sortable = false; + protected $multi_addremove = true; + protected $multi_values; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->setTitle($a_title); + $this->setPostVar($a_postvar); + $this->setDisabled(false); + } + + /** + * Execute command. + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd(); + + return $this->$cmd(); + } + + /** + * Set Type. + * + * @param string $a_type Type + */ + protected function setType($a_type) + { + $this->type = $a_type; + } + + /** + * Get Type. + * + * @return string Type + */ + public function getType() + { + return $this->type; + } + + /** + * Set Title. + * + * @param string $a_title Title + */ + public function setTitle($a_title) + { + $this->title = $a_title; + } + + /** + * Get Title. + * + * @return string Title + */ + public function getTitle() + { + return $this->title; + } + + /** + * Set Post Variable. + * + * @param string $a_postvar Post Variable + */ + public function setPostVar($a_postvar) + { + $this->postvar = $a_postvar; + } + + /** + * Get Post Variable. + * + * @return string Post Variable + */ + public function getPostVar() + { + return $this->postvar; + } + + /** + * Get Post Variable. + * + * @return string Post Variable + */ + public function getFieldId() + { + $id = str_replace("[", "__", $this->getPostVar()); + $id = str_replace("]", "__", $id); + + return $id; + } + + /** + * Set Information Text. + * + * @param string $a_info Information Text + */ + public function setInfo($a_info) + { + $this->info = $a_info; + } + + /** + * Get Information Text. + * + * @return string Information Text + */ + public function getInfo() + { + return $this->info; + } + + /** + * Set Alert Text. + * + * @param string $a_alert Alert Text + */ + public function setAlert($a_alert) + { + $this->alert = $a_alert; + } + + /** + * Get Alert Text. + * + * @return string Alert Text + */ + public function getAlert() + { + return $this->alert; + } + + /** + * Set Required. + * + * @param boolean $a_required Required + */ + public function setRequired($a_required) + { + $this->required = $a_required; + } + + /** + * Get Required. + * + * @return boolean Required + */ + public function getRequired() + { + return $this->required; + } + + /** + * Set Disabled. + * + * @param boolean $a_disabled Disabled + */ + public function setDisabled($a_disabled) + { + $this->disabled = $a_disabled; + } + + /** + * Get Disabled. + * + * @return boolean Disabled + */ + public function getDisabled() + { + return $this->disabled; + } + + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + return false; // please overwrite + } + + /** + * Set Parent Form. + * + * @param object $a_parentform Parent Form + */ + public function setParentForm($a_parentform) + { + $this->setParent($a_parentform); + } + + /** + * Get Parent Form. + * + * @return object Parent Form + */ + public function getParentForm() + { + return $this->getParent(); + } + + /** + * Set Parent GUI object. + * + * @param object parent gui object + */ + public function setParent($a_val) + { + $this->parent_gui = $a_val; + } + + /** + * Get Parent GUI object. + * + * @return object parent gui object + */ + public function getParent() + { + return $this->parent_gui; + } + + /** + * Get sub form html + * + */ + public function getSubForm() + { + return ""; + } + + /** + * Sub form hidden on init? + * + */ + public function hideSubForm() + { + return false; + } + + /** + * Set hidden title (for screenreaders) + * + * @param string hidden title + */ + public function setHiddenTitle($a_val) + { + $this->hidden_title = $a_val; + } + + /** + * Get hidden title + * + * @return string hidden title + */ + public function getHiddenTitle() + { + return $this->hidden_title; + } + + /** + * Get item by post var + * + * @return mixed false or item object + */ + public function getItemByPostVar($a_post_var) + { + if ($this->getPostVar() == $a_post_var) { + return $this; + } + + return false; + } + + /** + * serialize data + */ + public function serializeData() + { + return serialize($this->getValue()); + } + + /** + * unserialize data + */ + public function unserializeData($a_data) + { + $data = unserialize($a_data); + + if ($data) { + $this->setValue($data); + } else { + $this->setValue(false); + } + } + + /** + * Write to session + */ + public function writeToSession() + { + $parent = $this->getParent(); + if (!is_object($parent)) { + die("You must set parent for " . get_class($this) . " to use serialize feature."); + } + $_SESSION["form_" . $parent->getId()][$this->getFieldId()] = + $this->serializeData(); + } + + /** + * Clear session value + */ + public function clearFromSession() + { + $parent = $this->getParent(); + if (!is_object($parent)) { + die("You must set parent for " . get_class($this) . " to use serialize feature."); + } + $_SESSION["form_" . $parent->getId()][$this->getFieldId()] = false; + } + + /** + * Read from session + */ + public function readFromSession() + { + $parent = $this->getParent(); + if (!is_object($parent)) { + die("You must set parent for " . get_class($this) . " to use serialize feature."); + } + $this->unserializeData($_SESSION["form_" . $parent->getId()][$this->getFieldId()]); + } + + /** + * Get hidden tag (used for disabled properties) + */ + public function getHiddenTag($a_post_var, $a_value) + { + return ''; + } + + /** + * Set Multi + * + * @param bool $a_multi Multi + */ + public function setMulti($a_multi, $a_sortable = false, $a_addremove = true) + { + if (!$this instanceof ilMultiValuesItem) { + require_once 'Services/Form/exceptions/class.ilFormException.php'; + throw new ilFormException(sprintf( + "%s not supported for form property type %s", + __FUNCTION__, + get_class($this) + )); + } + + $this->multi = (bool) $a_multi; + $this->multi_sortable = (bool) $a_sortable; + $this->multi_addremove = (bool) $a_addremove; + } + + /** + * Get Multi + * + * @return bool Multi + */ + public function getMulti() + { + return $this->multi; + } + + /** + * Set multi values + * + * @param array $a_values + */ + public function setMultiValues(array $a_values) + { + $this->multi_values = array_unique($a_values); + } + + /** + * Get multi values + * + * @return array + */ + public function getMultiValues() + { + return $this->multi_values; + } + + /** + * Get HTML for multiple value icons + * + * @param bool $a_sortable + * @return string; + */ + protected function getMultiIconsHTML() + { + $lng = $this->lng; + + $id = $this->getFieldId(); + + $tpl = new ilTemplate("tpl.multi_icons.html", true, true, "Services/Form"); + + $html = ""; + if ($this->multi_addremove) { + $tpl->setCurrentBlock("addremove"); + $tpl->setVariable("ID", $id); + $tpl->setVariable("TXT_ADD", $lng->txt("add")); + $tpl->setVariable("TXT_REMOVE", $lng->txt("remove")); + include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); + $tpl->setVariable("SRC_ADD", ilGlyphGUI::get(ilGlyphGUI::ADD)); + $tpl->setVariable("SRC_REMOVE", ilGlyphGUI::get(ilGlyphGUI::REMOVE)); + $tpl->parseCurrentBlock(); + } + + if ($this->multi_sortable) { + $tpl->setCurrentBlock("sortable"); + $tpl->setVariable("ID", $id); + $tpl->setVariable("TXT_DOWN", $lng->txt("down")); + $tpl->setVariable("TXT_UP", $lng->txt("up")); + include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); + $tpl->setVariable("SRC_UP", ilGlyphGUI::get(ilGlyphGUI::UP)); + $tpl->setVariable("SRC_DOWN", ilGlyphGUI::get(ilGlyphGUI::DOWN)); + $tpl->parseCurrentBlock(); + } + + return $tpl->get(); + } + + /** + * Get content that has to reside outside of the parent form tag, e.g. panels/layers + * + * @return string + */ + public function getContentOutsideFormTag() + { + } + + /** + * Remove prohibited characters + * see #19159 + * + * @param string $a_text + * @return string + */ + public static function removeProhibitedCharacters($a_text) + { + return str_replace("\x0B", "", $a_text); + } + + /** + * Strip slashes with add space fallback, see https://www.ilias.de/mantis/view.php?id=19727 + * + * @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/Services/Form/classes/class.ilFormSectionHeaderGUI.php b/Services/Form/classes/class.ilFormSectionHeaderGUI.php index 496086e3a2f19137e887eb9a2c895e30b024032f..340f1682356d4869fc3190046367866a864fa524 100755 --- a/Services/Form/classes/class.ilFormSectionHeaderGUI.php +++ b/Services/Form/classes/class.ilFormSectionHeaderGUI.php @@ -1,208 +1,208 @@ +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilFormSectionHeaderGUI { - protected $type; - protected $title; - protected $info; - protected $section_icon; - protected $section_anchor; - - /** - * Constructor - * - * @param - */ - function __construct() - { - $this->setType("section_header"); - } - - function checkInput() - { - return true; - } + protected $type; + protected $title; + protected $info; + protected $section_icon; + protected $section_anchor; + + /** + * Constructor + * + * @param + */ + public function __construct() + { + $this->setType("section_header"); + } + + public function checkInput() + { + return true; + } - /** - * Set Type. - * - * @param string $a_type Type - */ - function setType($a_type) - { - $this->type = $a_type; - } + /** + * Set Type. + * + * @param string $a_type Type + */ + public function setType($a_type) + { + $this->type = $a_type; + } - /** - * Get Type. - * - * @return string Type - */ - function getType() - { - return $this->type; - } - - /** - * Set section icon - * - * @access public - * @param string path to icon - * @param string alternative text - * - */ - public function setSectionIcon($a_file,$a_alt) - { - $this->section_icon['file'] = $a_file; - $this->section_icon['alt'] = $a_alt; - } - - /** - * Get section icon - * - * @access public - * - */ - public function getSectionIcon() - { - return $this->section_icon ? $this->section_icon : array(); - } + /** + * Get Type. + * + * @return string Type + */ + public function getType() + { + return $this->type; + } + + /** + * Set section icon + * + * @access public + * @param string path to icon + * @param string alternative text + * + */ + public function setSectionIcon($a_file, $a_alt) + { + $this->section_icon['file'] = $a_file; + $this->section_icon['alt'] = $a_alt; + } + + /** + * Get section icon + * + * @access public + * + */ + public function getSectionIcon() + { + return $this->section_icon ? $this->section_icon : array(); + } - /** - * Set Title. - * - * @param string $a_title Title - */ - function setTitle($a_title) - { - $this->title = $a_title; - } + /** + * Set Title. + * + * @param string $a_title Title + */ + public function setTitle($a_title) + { + $this->title = $a_title; + } - /** - * Get Title. - * - * @return string Title - */ - function getTitle() - { - return $this->title; - } + /** + * Get Title. + * + * @return string Title + */ + public function getTitle() + { + return $this->title; + } - /** - * Set Information Text. - * - * @param string $a_info Information Text - */ - function setInfo($a_info) - { - $this->info = $a_info; - } + /** + * Set Information Text. + * + * @param string $a_info Information Text + */ + public function setInfo($a_info) + { + $this->info = $a_info; + } - /** - * Get Information Text. - * - * @return string Information Text - */ - function getInfo() - { - return $this->info; - } + /** + * Get Information Text. + * + * @return string Information Text + */ + public function getInfo() + { + return $this->info; + } - /** - * Set Parent Form. - * - * @param object $a_parentform Parent Form - */ - function setParentForm($a_parentform) - { - $this->parentform = $a_parentform; - } + /** + * Set Parent Form. + * + * @param object $a_parentform Parent Form + */ + public function setParentForm($a_parentform) + { + $this->parentform = $a_parentform; + } - /** - * Get Parent Form. - * - * @return object Parent Form - */ - function getParentForm() - { - return $this->parentform; - } - - /** - * set section label; - * - * @param unknown_type $value - */ - function setSectionAnchor($value) { - $this->section_anchor = $value; - } - - /** - * Insert property html - * - */ - function insert($a_tpl) - { - $section_icon = $this->getSectionIcon(); - - if(isset($section_icon['file']) && is_file($section_icon['file'])) - { - $a_tpl->setCurrentBlock("title_icon"); - $a_tpl->setVariable("IMG_ICON",$section_icon['file']); - $a_tpl->setVariable('IMG_ALT',$section_icon['alt']); - $a_tpl->parseCurrentBlock(); - } - - $a_tpl->setCurrentBlock("header"); - $a_tpl->setVariable("TXT_TITLE", $this->getTitle()); - $a_tpl->setVariable("TXT_DESCRIPTION", $this->getInfo()); - $a_tpl->setVariable('HEAD_COLSPAN',2); - if (isset($this->section_anchor)) - $a_tpl->setVariable('LABEL', $this->section_anchor); - $a_tpl->parseCurrentBlock(); - } - - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - // nothing to do since is a header - } - - function getPostVar() - { - // nothing to do since is a header - } + /** + * Get Parent Form. + * + * @return object Parent Form + */ + public function getParentForm() + { + return $this->parentform; + } + + /** + * set section label; + * + * @param unknown_type $value + */ + public function setSectionAnchor($value) + { + $this->section_anchor = $value; + } + /** + * Insert property html + * + */ + public function insert($a_tpl) + { + $section_icon = $this->getSectionIcon(); + + if (isset($section_icon['file']) && is_file($section_icon['file'])) { + $a_tpl->setCurrentBlock("title_icon"); + $a_tpl->setVariable("IMG_ICON", $section_icon['file']); + $a_tpl->setVariable('IMG_ALT', $section_icon['alt']); + $a_tpl->parseCurrentBlock(); + } + + $a_tpl->setCurrentBlock("header"); + $a_tpl->setVariable("TXT_TITLE", $this->getTitle()); + $a_tpl->setVariable("TXT_DESCRIPTION", $this->getInfo()); + $a_tpl->setVariable('HEAD_COLSPAN', 2); + if (isset($this->section_anchor)) { + $a_tpl->setVariable('LABEL', $this->section_anchor); + } + $a_tpl->parseCurrentBlock(); + } + + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + // nothing to do since is a header + } + + public function getPostVar() + { + // nothing to do since is a header + } } diff --git a/Services/Form/classes/class.ilFormSubmitRecursiveSlashesStripper.php b/Services/Form/classes/class.ilFormSubmitRecursiveSlashesStripper.php index da1a68a349a817a4778acca6de7791af48693b9e..8d35c2cae02dc7c9549235f271ca161c5b514753 100644 --- a/Services/Form/classes/class.ilFormSubmitRecursiveSlashesStripper.php +++ b/Services/Form/classes/class.ilFormSubmitRecursiveSlashesStripper.php @@ -11,34 +11,32 @@ require_once 'Services/Form/interfaces/interface.ilFormValuesManipulator.php'; */ class ilFormSubmitRecursiveSlashesStripper implements ilFormValuesManipulator { - /** - * @param array $inputValues - * @return array - */ - public function manipulateFormInputValues($inputValues) - { - return $inputValues; - } - - /** - * @param array $submitValues - * @return array|mixed|string - * @throws ilFormException - */ - public function manipulateFormSubmitValues($submitValues) - { - foreach($submitValues as $identifier => $value) - { - if( is_object($value) ) - { - // post submit does not support objects, so when - // object building happened, sanitizing did also - continue; - } - - $submitValues[$identifier] = ilUtil::stripSlashesRecursive($value); - } - - return $submitValues; - } -} \ No newline at end of file + /** + * @param array $inputValues + * @return array + */ + public function manipulateFormInputValues($inputValues) + { + return $inputValues; + } + + /** + * @param array $submitValues + * @return array|mixed|string + * @throws ilFormException + */ + public function manipulateFormSubmitValues($submitValues) + { + foreach ($submitValues as $identifier => $value) { + if (is_object($value)) { + // post submit does not support objects, so when + // object building happened, sanitizing did also + continue; + } + + $submitValues[$identifier] = ilUtil::stripSlashesRecursive($value); + } + + return $submitValues; + } +} diff --git a/Services/Form/classes/class.ilFormulaInputGUI.php b/Services/Form/classes/class.ilFormulaInputGUI.php index 08eb3f0b884772604447f3f983fa16926cb7d5f0..270931d545efea8df62d0939ff290573ee521949 100755 --- a/Services/Form/classes/class.ilFormulaInputGUI.php +++ b/Services/Form/classes/class.ilFormulaInputGUI.php @@ -7,63 +7,58 @@ include_once("./Services/Math/classes/class.EvalMath.php"); /** * This class represents a formula text property in a property form. * -* @author Helmut Schottmüller +* @author Helmut Schottmüller * @version $Id$ * @ingroup ServicesForm */ class ilFormulaInputGUI extends ilTextInputGUI { - /** - * Constructor - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; - parent::__construct($a_title, $a_postvar); + /** + * Constructor + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; + parent::__construct($a_title, $a_postvar); - $this->lng = $DIC->language(); - } + $this->lng = $DIC->language(); + } - /** - * Set Value. - * - * @param string $a_value Value - */ - function setValue($a_value) - { - $this->value = str_replace(',', '.', $a_value); - } + /** + * Set Value. + * + * @param string $a_value Value + */ + public function setValue($a_value) + { + $this->value = str_replace(',', '.', $a_value); + } - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - $_POST[$this->getPostVar()] = ilUtil::stripSlashes($_POST[$this->getPostVar()]); - if ($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") - { - $this->setAlert($lng->txt("msg_input_is_required")); + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + $_POST[$this->getPostVar()] = ilUtil::stripSlashes($_POST[$this->getPostVar()]); + if ($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") { + $this->setAlert($lng->txt("msg_input_is_required")); - return false; - } - else - { - $eval = new EvalMath(); - $eval->suppress_errors = true; - $result = $eval->e(str_replace(",", ".", ilUtil::stripSlashes($_POST[$this->getPostVar()], FALSE))); - if ($result === false) - { - $this->setAlert($lng->txt("form_msg_formula_is_required")); - return false; - } - } - - return $this->checkSubItemsInput(); - } + return false; + } else { + $eval = new EvalMath(); + $eval->suppress_errors = true; + $result = $eval->e(str_replace(",", ".", ilUtil::stripSlashes($_POST[$this->getPostVar()], false))); + if ($result === false) { + $this->setAlert($lng->txt("form_msg_formula_is_required")); + return false; + } + } + + return $this->checkSubItemsInput(); + } } -?> \ No newline at end of file diff --git a/Services/Form/classes/class.ilHiddenInputGUI.php b/Services/Form/classes/class.ilHiddenInputGUI.php index e439e11f5b0542114cb6418fae4cdb432d857f1a..00d0029fd7873b214f492c9bfbf8317f6111b0ff 100644 --- a/Services/Form/classes/class.ilHiddenInputGUI.php +++ b/Services/Form/classes/class.ilHiddenInputGUI.php @@ -1,114 +1,114 @@ -setType("hidden"); - } - - /** - * Set Value. - * - * @param string $a_value Value - */ - function setValue($a_value) - { - $this->value = $a_value; - } - - /** - * Get Value. - * - * @return string Value - */ - function getValue() - { - return $this->value; - } - - - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - return true; // please overwrite - } - - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $this->setValue($a_values[$this->getPostVar()]); - } - - /** - * Insert property html - * - * @return int Size - */ - function insert($a_tpl) - { - $a_tpl->setCurrentBlock("hidden"); - $a_tpl->setVariable('PROP_INPUT_TYPE','hidden'); - $a_tpl->setVariable("POST_VAR", $this->getPostVar()); - $a_tpl->setVariable("ID", $this->getFieldId()); - $a_tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($this->getValue())); - $a_tpl->parseCurrentBlock(); - } - - /** - * Get HTML for toolbar - */ - function getToolbarHTML() - { - return "getPostVar()."\"". - " value=\"".ilUtil::prepareFormOutput($this->getValue())."\"". - " id=\"".$this->getFieldId()."\" />"; - } -} -?> \ No newline at end of file +setType("hidden"); + } + + /** + * Set Value. + * + * @param string $a_value Value + */ + public function setValue($a_value) + { + $this->value = $a_value; + } + + /** + * Get Value. + * + * @return string Value + */ + public function getValue() + { + return $this->value; + } + + + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + return true; // please overwrite + } + + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $this->setValue($a_values[$this->getPostVar()]); + } + + /** + * Insert property html + * + * @return int Size + */ + public function insert($a_tpl) + { + $a_tpl->setCurrentBlock("hidden"); + $a_tpl->setVariable('PROP_INPUT_TYPE', 'hidden'); + $a_tpl->setVariable("POST_VAR", $this->getPostVar()); + $a_tpl->setVariable("ID", $this->getFieldId()); + $a_tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($this->getValue())); + $a_tpl->parseCurrentBlock(); + } + + /** + * Get HTML for toolbar + */ + public function getToolbarHTML() + { + return "getPostVar() . "\"" . + " value=\"" . ilUtil::prepareFormOutput($this->getValue()) . "\"" . + " id=\"" . $this->getFieldId() . "\" />"; + } +} diff --git a/Services/Form/classes/class.ilHierarchyFormGUI.php b/Services/Form/classes/class.ilHierarchyFormGUI.php index 3e69e09b2abf4f9248e5affdd9fe8bd1b2506313..8d44d7a77a68eb78bb977b2985556ff911e6b35e 100755 --- a/Services/Form/classes/class.ilHierarchyFormGUI.php +++ b/Services/Form/classes/class.ilHierarchyFormGUI.php @@ -7,1202 +7,1126 @@ include_once("./Services/Form/classes/class.ilFormGUI.php"); * This class represents a hierarchical form. These forms are used for * quick editing, where each node is represented by it's title. * -* @author Alex Killing +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilHierarchyFormGUI extends ilFormGUI { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilTemplate + */ + protected $tpl; - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * Constructor - * - * @param - */ - function __construct() - { - global $DIC; + /** + * Constructor + * + * @param + */ + public function __construct() + { + global $DIC; - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - $this->ctrl = $DIC->ctrl(); - $lng = $DIC->language(); - $tpl = $DIC["tpl"]; - - $this->maxdepth = -1; - $this->multi_commands = array(); - $this->commands = array(); - $this->drag_target[] = array(); - $this->drag_content[] = array(); - $lng->loadLanguageModule("form"); - $this->setCheckboxName("cbox"); - $this->help_items = array(); - - include_once("./Services/YUI/classes/class.ilYuiUtil.php"); - ilYuiUtil::initDragDrop(); - $tpl->addJavascript("./Services/Form/js/ServiceFormHierarchyForm.js"); - } + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + $this->ctrl = $DIC->ctrl(); + $lng = $DIC->language(); + $tpl = $DIC["tpl"]; + + $this->maxdepth = -1; + $this->multi_commands = array(); + $this->commands = array(); + $this->drag_target[] = array(); + $this->drag_content[] = array(); + $lng->loadLanguageModule("form"); + $this->setCheckboxName("cbox"); + $this->help_items = array(); + + include_once("./Services/YUI/classes/class.ilYuiUtil.php"); + ilYuiUtil::initDragDrop(); + $tpl->addJavascript("./Services/Form/js/ServiceFormHierarchyForm.js"); + } - /** - * Set parent gui object/cmd - * - * This is needed, if the expand feature is used. - */ - function setParentCommand($a_parent_obj, $a_parent_cmd) - { - $this->parent_obj = $a_parent_obj; - $this->parent_cmd = $a_parent_cmd; - } - - /** - * Get Parent object - * - * @return object parent gui object - */ - function getParentObject() - { - return $this->parent_obj; - } - - /** - * Get parent command - * - * @return string parent command - */ - function getParentCommand() - { - return $this->parent_cmd; - } + /** + * Set parent gui object/cmd + * + * This is needed, if the expand feature is used. + */ + public function setParentCommand($a_parent_obj, $a_parent_cmd) + { + $this->parent_obj = $a_parent_obj; + $this->parent_cmd = $a_parent_cmd; + } + + /** + * Get Parent object + * + * @return object parent gui object + */ + public function getParentObject() + { + return $this->parent_obj; + } + + /** + * Get parent command + * + * @return string parent command + */ + public function getParentCommand() + { + return $this->parent_cmd; + } - /** - * Set Id. Currently not possible, due to js handling (ID must always be "hform") - * - * @param string $a_id Id - */ - function setId($a_id) - { - die("ilHierarchyFormGUI does currently not support multiple forms (multiple IDs). ID is always hform."); - } + /** + * Set Id. Currently not possible, due to js handling (ID must always be "hform") + * + * @param string $a_id Id + */ + public function setId($a_id) + { + die("ilHierarchyFormGUI does currently not support multiple forms (multiple IDs). ID is always hform."); + } - /** - * Get Id. - * - * @return string Id - */ - function getId() - { - return "hform"; - } + /** + * Get Id. + * + * @return string Id + */ + public function getId() + { + return "hform"; + } - /** - * Set Tree Object. - * - * @param object $a_tree Tree Object - */ - function setTree($a_tree) - { - $this->tree = $a_tree; - } + /** + * Set Tree Object. + * + * @param object $a_tree Tree Object + */ + public function setTree($a_tree) + { + $this->tree = $a_tree; + } - /** - * Get Tree Object. - * - * @return object Tree Object - */ - function getTree() - { - return $this->tree; - } + /** + * Get Tree Object. + * + * @return object Tree Object + */ + public function getTree() + { + return $this->tree; + } - /** - * Set Current Top Node ID. - * - * @param string $a_currenttopnodeid Current Top Node ID - */ - function setCurrentTopNodeId($a_currenttopnodeid) - { - $this->currenttopnodeid = $a_currenttopnodeid; - } + /** + * Set Current Top Node ID. + * + * @param string $a_currenttopnodeid Current Top Node ID + */ + public function setCurrentTopNodeId($a_currenttopnodeid) + { + $this->currenttopnodeid = $a_currenttopnodeid; + } - /** - * Get Current Top Node ID. - * - * @return string Current Top Node ID - */ - function getCurrentTopNodeId() - { - return $this->currenttopnodeid; - } + /** + * Get Current Top Node ID. + * + * @return string Current Top Node ID + */ + public function getCurrentTopNodeId() + { + return $this->currenttopnodeid; + } - /** - * Set Title. - * - * @param string $a_title Title - */ - function setTitle($a_title) - { - $this->title = $a_title; - } + /** + * Set Title. + * + * @param string $a_title Title + */ + public function setTitle($a_title) + { + $this->title = $a_title; + } - /** - * Get Title. - * - * @return string Title - */ - function getTitle() - { - return $this->title; - } + /** + * Get Title. + * + * @return string Title + */ + public function getTitle() + { + return $this->title; + } - /** - * Set Icon. - * - * @param string $a_icon Icon - */ - function setIcon($a_icon) - { - $this->icon = $a_icon; - } + /** + * Set Icon. + * + * @param string $a_icon Icon + */ + public function setIcon($a_icon) + { + $this->icon = $a_icon; + } - /** - * Get Icon. - * - * @return string Icon - */ - function getIcon() - { - return $this->icon; - } + /** + * Get Icon. + * + * @return string Icon + */ + public function getIcon() + { + return $this->icon; + } - /** - * Set Checkbox Name. - * - * @param string $a_checkboxname Checkbox Name - */ - function setCheckboxName($a_checkboxname) - { - $this->checkboxname = $a_checkboxname; - } + /** + * Set Checkbox Name. + * + * @param string $a_checkboxname Checkbox Name + */ + public function setCheckboxName($a_checkboxname) + { + $this->checkboxname = $a_checkboxname; + } - /** - * Get Checkbox Name. - * - * @return string Checkbox Name - */ - function getCheckboxName() - { - return $this->checkboxname; - } + /** + * Get Checkbox Name. + * + * @return string Checkbox Name + */ + public function getCheckboxName() + { + return $this->checkboxname; + } - /** - * Set Drag Icon Path. - * - * @param string $a_dragicon Drag Icon Path - */ - function setDragIcon($a_dragicon) - { - $this->dragicon = $a_dragicon; - } + /** + * Set Drag Icon Path. + * + * @param string $a_dragicon Drag Icon Path + */ + public function setDragIcon($a_dragicon) + { + $this->dragicon = $a_dragicon; + } - /** - * Get Drag Icon Path. - * - * @return string Drag Icon Path - */ - function getDragIcon() - { - return $this->dragicon; - } + /** + * Get Drag Icon Path. + * + * @return string Drag Icon Path + */ + public function getDragIcon() + { + return $this->dragicon; + } - /** - * Set Maximum Depth. - * - * @param int $a_maxdepth Maximum Depth - */ - function setMaxDepth($a_maxdepth) - { - $this->maxdepth = $a_maxdepth; - } + /** + * Set Maximum Depth. + * + * @param int $a_maxdepth Maximum Depth + */ + public function setMaxDepth($a_maxdepth) + { + $this->maxdepth = $a_maxdepth; + } - /** - * Get Maximum Depth. - * - * @return int Maximum Depth - */ - function getMaxDepth() - { - return $this->maxdepth; - } + /** + * Get Maximum Depth. + * + * @return int Maximum Depth + */ + public function getMaxDepth() + { + return $this->maxdepth; + } - /** - * Set Explorer Updater - * - * @param object $a_tree Tree Object - */ - function setExplorerUpdater($a_exp_frame, $a_exp_id, $a_exp_target_script) - { - $this->exp_frame = $a_exp_frame; - $this->exp_id = $a_exp_id; - $this->exp_target_script = $a_exp_target_script; - } - - /** - * Set Explorer Updater - * - * @param object $a_tree Tree Object - */ - function setTriggeredUpdateCommand($a_triggered_update_command) - { - $this->triggered_update_command = $a_triggered_update_command; - } + /** + * Set Explorer Updater + * + * @param object $a_tree Tree Object + */ + public function setExplorerUpdater($a_exp_frame, $a_exp_id, $a_exp_target_script) + { + $this->exp_frame = $a_exp_frame; + $this->exp_id = $a_exp_id; + $this->exp_target_script = $a_exp_target_script; + } + + /** + * Set Explorer Updater + * + * @param object $a_tree Tree Object + */ + public function setTriggeredUpdateCommand($a_triggered_update_command) + { + $this->triggered_update_command = $a_triggered_update_command; + } - /** - * Get all help items - */ - function addHelpItem($a_text, $a_image = "") - { - $this->help_items[] = array("text" => $a_text, - "image" => $a_image); - } + /** + * Get all help items + */ + public function addHelpItem($a_text, $a_image = "") + { + $this->help_items[] = array("text" => $a_text, + "image" => $a_image); + } - /** - * Get all help items - */ - function getHelpItems() - { - return $this->help_items; - } - - /** - * Makes a nodes (following droparea) a drag target - * - * @param string $a_id node ID - * @param string $a_group drag and drop group - */ - function makeDragTarget($a_id, $a_group, $a_first_child_drop_area = false, $a_as_subitem = false, $a_diss_text = "") - { - if ($a_first_child_drop_area == true) // first child drop areas only insert as subitems - { - $a_as_subitem = true; - } - - if ($a_id != "") - { - if ($a_first_child_drop_area) - { - $a_id.= "fc"; - } - - $this->drag_target[] = array("id" => $a_id, "group" => $a_group); - $this->diss_menues[$a_id][$a_group][] = array("subitem" => $a_as_subitem, "text" => $a_diss_text); - } - } - - /** - * Makes a node a drag content - * - * @param string $a_id node ID - * @param string $a_group drag and drop group - */ - function makeDragContent($a_id, $a_group) - { - if ($a_id != "") - { - $this->drag_content[] = array("id" => $a_id, "group" => $a_group); - } - } + /** + * Get all help items + */ + public function getHelpItems() + { + return $this->help_items; + } + + /** + * Makes a nodes (following droparea) a drag target + * + * @param string $a_id node ID + * @param string $a_group drag and drop group + */ + public function makeDragTarget($a_id, $a_group, $a_first_child_drop_area = false, $a_as_subitem = false, $a_diss_text = "") + { + if ($a_first_child_drop_area == true) { // first child drop areas only insert as subitems + $a_as_subitem = true; + } + + if ($a_id != "") { + if ($a_first_child_drop_area) { + $a_id.= "fc"; + } + + $this->drag_target[] = array("id" => $a_id, "group" => $a_group); + $this->diss_menues[$a_id][$a_group][] = array("subitem" => $a_as_subitem, "text" => $a_diss_text); + } + } + + /** + * Makes a node a drag content + * + * @param string $a_id node ID + * @param string $a_group drag and drop group + */ + public function makeDragContent($a_id, $a_group) + { + if ($a_id != "") { + $this->drag_content[] = array("id" => $a_id, "group" => $a_group); + } + } - /** - * Add a multi command (for selection of items) - * - * @param string $a_txt command text - * @param string $a_cmd command - */ - function addMultiCommand($a_txt, $a_cmd) - { - $this->multi_commands[] = array("text" => $a_txt, "cmd" => $a_cmd); - } + /** + * Add a multi command (for selection of items) + * + * @param string $a_txt command text + * @param string $a_cmd command + */ + public function addMultiCommand($a_txt, $a_cmd) + { + $this->multi_commands[] = array("text" => $a_txt, "cmd" => $a_cmd); + } - /** - * Add a command - * - * @param string $a_txt command text - * @param string $a_cmd command - */ - function addCommand($a_txt, $a_cmd) - { - $this->commands[] = array("text" => $a_txt, "cmd" => $a_cmd); - } - - /** - * Set highlighted nodes - * - * @param array highlighted nodes - */ - function setHighlightedNodes($a_val) - { - $this->highlighted_nodes = $a_val; - } - - /** - * Get highlighted nodes. - * - * @return array highlighted nodes - */ - function getHighlightedNodes() - { - return $this->highlighted_nodes; - } - - /** - * Set focus if - * - * @param int node id - */ - function setFocusId($a_val) - { - $this->focus_id = $a_val; - } - - /** - * Get focus id - * - * @return int node id - */ - function getFocusId() - { - return $this->focus_id; - } - - /** - * Set expand variable - * - * @param - */ - function setExpandVariable($a_val) - { - $this->expand_variable = $a_val; - } - - /** - * Get expand variable - * - * @return - */ - function getExpandVariable() - { - return $this->expand_variable; - } - - /** - * Set expanded Array - * - * @param array expanded array - */ - function setExpanded($a_val) - { - $this->expanded = $a_val; - } - - /** - * Get expanded array - * - * @return array expanded array - */ - function getExpanded() - { - return $this->expanded; - } - - /** - * Update expand information in session - * - * @param string node id - */ - function updateExpanded() - { - $ev = $this->getExpandVariable(); + /** + * Add a command + * + * @param string $a_txt command text + * @param string $a_cmd command + */ + public function addCommand($a_txt, $a_cmd) + { + $this->commands[] = array("text" => $a_txt, "cmd" => $a_cmd); + } + + /** + * Set highlighted nodes + * + * @param array highlighted nodes + */ + public function setHighlightedNodes($a_val) + { + $this->highlighted_nodes = $a_val; + } + + /** + * Get highlighted nodes. + * + * @return array highlighted nodes + */ + public function getHighlightedNodes() + { + return $this->highlighted_nodes; + } + + /** + * Set focus if + * + * @param int node id + */ + public function setFocusId($a_val) + { + $this->focus_id = $a_val; + } + + /** + * Get focus id + * + * @return int node id + */ + public function getFocusId() + { + return $this->focus_id; + } + + /** + * Set expand variable + * + * @param + */ + public function setExpandVariable($a_val) + { + $this->expand_variable = $a_val; + } + + /** + * Get expand variable + * + * @return + */ + public function getExpandVariable() + { + return $this->expand_variable; + } + + /** + * Set expanded Array + * + * @param array expanded array + */ + public function setExpanded($a_val) + { + $this->expanded = $a_val; + } + + /** + * Get expanded array + * + * @return array expanded array + */ + public function getExpanded() + { + return $this->expanded; + } + + /** + * Update expand information in session + * + * @param string node id + */ + public function updateExpanded() + { + $ev = $this->getExpandVariable(); - if ($ev == "") - { - return; - } - - // init empty session - if (!is_array($_SESSION[$ev])) - { - $_SESSION[$ev] = array($this->getTree()->getRootId()); - } + if ($ev == "") { + return; + } + + // init empty session + if (!is_array($_SESSION[$ev])) { + $_SESSION[$ev] = array($this->getTree()->getRootId()); + } - if ($_POST["il_hform_expand"] != "") - { - $node_id = $_POST["il_hform_expand"]; - } - if ($_GET[$ev] != "") - { - $node_id = $_GET[$ev]; - } - - // if positive => expand this node - if ($node_id > 0 && !in_array($node_id,$_SESSION[$ev])) - { - array_push($_SESSION[$ev], $node_id); - } - // if negative => compress this node - if ($node_id < 0) - { - $key = array_keys($_SESSION[$ev],-(int) $node_id); - unset($_SESSION[$ev][$key[0]]); - } - $this->setExpanded($_SESSION[$ev]); - } + if ($_POST["il_hform_expand"] != "") { + $node_id = $_POST["il_hform_expand"]; + } + if ($_GET[$ev] != "") { + $node_id = $_GET[$ev]; + } + + // if positive => expand this node + if ($node_id > 0 && !in_array($node_id, $_SESSION[$ev])) { + array_push($_SESSION[$ev], $node_id); + } + // if negative => compress this node + if ($node_id < 0) { + $key = array_keys($_SESSION[$ev], -(int) $node_id); + unset($_SESSION[$ev][$key[0]]); + } + $this->setExpanded($_SESSION[$ev]); + } - /** - * Set type whitelist - * - * @param array $a_val white list of types - */ - function setTypeWhiteList($a_val) - { - $this->white_list = $a_val; - } - - /** - * Get type whitelist - * - * @return array white list of types - */ - function getTypeWhiteList() - { - return $this->white_list; - } + /** + * Set type whitelist + * + * @param array $a_val white list of types + */ + public function setTypeWhiteList($a_val) + { + $this->white_list = $a_val; + } + + /** + * Get type whitelist + * + * @return array white list of types + */ + public function getTypeWhiteList() + { + return $this->white_list; + } - /** - * Get all childs of current node. Standard implementation uses - * tree object. - */ - function getChilds($a_node_id = false) - { - if ($a_node_id == false) - { - $a_node_id = $this->getCurrentTopNodeId(); - } - - $tree_childs = $this->getTree()->getChilds($a_node_id); - $childs = array(); - foreach($tree_childs as $tree_child) - { - - if (!is_array($this->white_list) || in_array($tree_child["type"], $this->white_list)) - { - $childs[] = array("node_id" => $tree_child["child"], - "title" => $tree_child["title"], - "type" => $tree_child["type"], - "depth" => $tree_child["depth"] - ); - } - } - - return $childs; - } - - /** - * Get Form Content - */ - function getContent() - { - $lng = $this->lng; - - if ($this->getExpandVariable() != "") - { - $this->updateExpanded(); - } - - $ttpl = new ilTemplate("tpl.hierarchy_form.html", true, true, "Services/Form"); - $ttpl->setVariable("TXT_SAVING", $lng->txt("saving")); - $top_node_data = $this->getTree()->getNodeData($this->getCurrentTopNodeId()); - $top_node = array("node_id" => $top_node_data["child"], - "title" => $top_node_data["title"], - "type" => $top_node_data["type"]); + /** + * Get all childs of current node. Standard implementation uses + * tree object. + */ + public function getChilds($a_node_id = false) + { + if ($a_node_id == false) { + $a_node_id = $this->getCurrentTopNodeId(); + } + + $tree_childs = $this->getTree()->getChilds($a_node_id); + $childs = array(); + foreach ($tree_childs as $tree_child) { + if (!is_array($this->white_list) || in_array($tree_child["type"], $this->white_list)) { + $childs[] = array("node_id" => $tree_child["child"], + "title" => $tree_child["title"], + "type" => $tree_child["type"], + "depth" => $tree_child["depth"] + ); + } + } + + return $childs; + } + + /** + * Get Form Content + */ + public function getContent() + { + $lng = $this->lng; + + if ($this->getExpandVariable() != "") { + $this->updateExpanded(); + } + + $ttpl = new ilTemplate("tpl.hierarchy_form.html", true, true, "Services/Form"); + $ttpl->setVariable("TXT_SAVING", $lng->txt("saving")); + $top_node_data = $this->getTree()->getNodeData($this->getCurrentTopNodeId()); + $top_node = array("node_id" => $top_node_data["child"], + "title" => $top_node_data["title"], + "type" => $top_node_data["type"]); - $childs = null; - $nodes_html = $this->getLevelHTML($top_node, 0, $childs); + $childs = null; + $nodes_html = $this->getLevelHTML($top_node, 0, $childs); - // commands - $secs = array("1", "2"); - foreach ($secs as $sec) - { - reset($this->commands); - reset($this->multi_commands); - if (count($this->multi_commands) > 0 || count($this->commands) > 0) - { - if (count($childs) > 0) - { - $single = false; - foreach($this->commands as $cmd) - { - $ttpl->setCurrentBlock("cmd".$sec); - $ttpl->setVariable("CMD", $cmd["cmd"]); - $ttpl->setVariable("CMD_TXT", $cmd["text"]); - $ttpl->parseCurrentBlock(); - $single = true; - } - - $multi = false; - foreach($this->multi_commands as $cmd) - { - $ttpl->setCurrentBlock("multi_cmd".$sec); - $ttpl->setVariable("MULTI_CMD", $cmd["cmd"]); - $ttpl->setVariable("MULTI_CMD_TXT", $cmd["text"]); - $ttpl->parseCurrentBlock(); - $multi = true; - } - if ($multi) - { - $ttpl->setCurrentBlock("multi_cmds".$sec); - $ttpl->setVariable("MCMD_ALT", $lng->txt("commands")); - if ($sec == "1") - { - $ttpl->setVariable("MCMD_IMG", ilUtil::getImagePath("arrow_downright.svg")); - } - else - { - $ttpl->setVariable("MCMD_IMG", ilUtil::getImagePath("arrow_upright.svg")); - } - $ttpl->parseCurrentBlock(); - } - } - - if ($single || $multi) - { - $ttpl->setCurrentBlock("commands".$sec); - $ttpl->parseCurrentBlock(); - } - $single = true; - } - } + // commands + $secs = array("1", "2"); + foreach ($secs as $sec) { + reset($this->commands); + reset($this->multi_commands); + if (count($this->multi_commands) > 0 || count($this->commands) > 0) { + if (count($childs) > 0) { + $single = false; + foreach ($this->commands as $cmd) { + $ttpl->setCurrentBlock("cmd" . $sec); + $ttpl->setVariable("CMD", $cmd["cmd"]); + $ttpl->setVariable("CMD_TXT", $cmd["text"]); + $ttpl->parseCurrentBlock(); + $single = true; + } + + $multi = false; + foreach ($this->multi_commands as $cmd) { + $ttpl->setCurrentBlock("multi_cmd" . $sec); + $ttpl->setVariable("MULTI_CMD", $cmd["cmd"]); + $ttpl->setVariable("MULTI_CMD_TXT", $cmd["text"]); + $ttpl->parseCurrentBlock(); + $multi = true; + } + if ($multi) { + $ttpl->setCurrentBlock("multi_cmds" . $sec); + $ttpl->setVariable("MCMD_ALT", $lng->txt("commands")); + if ($sec == "1") { + $ttpl->setVariable("MCMD_IMG", ilUtil::getImagePath("arrow_downright.svg")); + } else { + $ttpl->setVariable("MCMD_IMG", ilUtil::getImagePath("arrow_upright.svg")); + } + $ttpl->parseCurrentBlock(); + } + } + + if ($single || $multi) { + $ttpl->setCurrentBlock("commands" . $sec); + $ttpl->parseCurrentBlock(); + } + $single = true; + } + } - // explorer updater - if ($this->exp_frame != "") - { - $ttpl->setCurrentBlock("updater"); - $ttpl->setVariable("UPDATER_FRAME", $this->exp_frame); - $ttpl->setVariable("EXP_ID_UPDATER", $this->exp_id); - $ttpl->setVariable("HREF_UPDATER", $this->exp_target_script); - $ttpl->parseCurrentBlock(); - } + // explorer updater + if ($this->exp_frame != "") { + $ttpl->setCurrentBlock("updater"); + $ttpl->setVariable("UPDATER_FRAME", $this->exp_frame); + $ttpl->setVariable("EXP_ID_UPDATER", $this->exp_id); + $ttpl->setVariable("HREF_UPDATER", $this->exp_target_script); + $ttpl->parseCurrentBlock(); + } - // drag and drop initialisation - foreach($this->drag_target as $drag_target) - { - $ttpl->setCurrentBlock("dragtarget"); - $ttpl->setVariable("EL_ID", $drag_target["id"]); - $ttpl->setVariable("GROUP", $drag_target["group"]); - $ttpl->parseCurrentBlock(); - } - foreach($this->drag_content as $drag_content) - { - $ttpl->setCurrentBlock("dragcontent"); - $ttpl->setVariable("EL_ID", $drag_content["id"]); - $ttpl->setVariable("GROUP", $drag_content["group"]); - $ttpl->parseCurrentBlock(); - } - - // disambiguation menues and "insert as first child" flags - if (is_array($this->diss_menues)) - { - foreach($this->diss_menues as $node_id => $d_menu) - { - foreach($d_menu as $group => $menu) - { - if (count($menu) > 1) - { - foreach($menu as $menu_item) - { - $ttpl->setCurrentBlock("dmenu_cmd"); - $ttpl->setVariable("SUBITEM", (int) $menu_item["subitem"]); - $ttpl->setVariable("TXT_MENU_CMD", $menu_item["text"]); - $ttpl->parseCurrentBlock(); - } - - $ttpl->setCurrentBlock("disambiguation_menu"); - $ttpl->setVariable("DNODE_ID", $node_id); - $ttpl->setVariable("GRP", $group); - $ttpl->parseCurrentBlock(); - } - else if (count($menu) == 1) - { - // set first child flag - $ttpl->setCurrentBlock("as_subitem_flag"); - $ttpl->setVariable("SI_NODE_ID", $node_id); - $ttpl->setVariable("SI_GRP", $group); - $ttpl->setVariable("SI_SI", (int) $menu[0]["subitem"]); - $ttpl->parseCurrentBlock(); - - } - } - } - } - $this->diss_menues[$a_id][$a_group][] = array("type" => $a_type, "text" => $a_diss_text); + // drag and drop initialisation + foreach ($this->drag_target as $drag_target) { + $ttpl->setCurrentBlock("dragtarget"); + $ttpl->setVariable("EL_ID", $drag_target["id"]); + $ttpl->setVariable("GROUP", $drag_target["group"]); + $ttpl->parseCurrentBlock(); + } + foreach ($this->drag_content as $drag_content) { + $ttpl->setCurrentBlock("dragcontent"); + $ttpl->setVariable("EL_ID", $drag_content["id"]); + $ttpl->setVariable("GROUP", $drag_content["group"]); + $ttpl->parseCurrentBlock(); + } + + // disambiguation menues and "insert as first child" flags + if (is_array($this->diss_menues)) { + foreach ($this->diss_menues as $node_id => $d_menu) { + foreach ($d_menu as $group => $menu) { + if (count($menu) > 1) { + foreach ($menu as $menu_item) { + $ttpl->setCurrentBlock("dmenu_cmd"); + $ttpl->setVariable("SUBITEM", (int) $menu_item["subitem"]); + $ttpl->setVariable("TXT_MENU_CMD", $menu_item["text"]); + $ttpl->parseCurrentBlock(); + } + + $ttpl->setCurrentBlock("disambiguation_menu"); + $ttpl->setVariable("DNODE_ID", $node_id); + $ttpl->setVariable("GRP", $group); + $ttpl->parseCurrentBlock(); + } elseif (count($menu) == 1) { + // set first child flag + $ttpl->setCurrentBlock("as_subitem_flag"); + $ttpl->setVariable("SI_NODE_ID", $node_id); + $ttpl->setVariable("SI_GRP", $group); + $ttpl->setVariable("SI_SI", (int) $menu[0]["subitem"]); + $ttpl->parseCurrentBlock(); + } + } + } + } + $this->diss_menues[$a_id][$a_group][] = array("type" => $a_type, "text" => $a_diss_text); - if ($this->triggered_update_command != "") - { - $ttpl->setCurrentBlock("tr_update"); - $ttpl->setVariable("UPDATE_CMD", $this->triggered_update_command); - $ttpl->parseCurrentBlock(); - } + if ($this->triggered_update_command != "") { + $ttpl->setCurrentBlock("tr_update"); + $ttpl->setVariable("UPDATE_CMD", $this->triggered_update_command); + $ttpl->parseCurrentBlock(); + } - // disambiguation menues and "insert as first child" flags - if (is_array($this->diss_menues)) - { - foreach($this->diss_menues as $node_id => $d_menu) - { - foreach($d_menu as $group => $menu) - { - if (count($menu) > 1) - { - foreach($menu as $menu_item) - { - $ttpl->setCurrentBlock("dmenu_cmd"); - $ttpl->setVariable("SUBITEM", (int) $menu_item["subitem"]); - $ttpl->setVariable("TXT_MENU_CMD", $menu_item["text"]); - $ttpl->parseCurrentBlock(); - } - - $ttpl->setCurrentBlock("disambiguation_menu"); - $ttpl->setVariable("DNODE_ID", $node_id); - $ttpl->setVariable("GRP", $group); - $ttpl->parseCurrentBlock(); - } - else if (count($menu) == 1) - { - // set first child flag - $ttpl->setCurrentBlock("as_subitem_flag"); - $ttpl->setVariable("SI_NODE_ID", $node_id); - $ttpl->setVariable("SI_GRP", $group); - $ttpl->setVariable("SI_SI", (int) $menu[0]["subitem"]); - $ttpl->parseCurrentBlock(); - - } - } - } - } - $this->diss_menues[$a_id][$a_group][] = array("type" => $a_type, "text" => $a_diss_text); - - // nodes - $ttpl->setVariable("NODES", $nodes_html); - - // title -//echo "
                  ".htmlentities($this->getTitle())." --- ".htmlentities(ilUtil::prepareFormOutput($this->getTitle())); - $ttpl->setVariable("TITLE", $this->getTitle()); - - - return $ttpl->get(); - } + // disambiguation menues and "insert as first child" flags + if (is_array($this->diss_menues)) { + foreach ($this->diss_menues as $node_id => $d_menu) { + foreach ($d_menu as $group => $menu) { + if (count($menu) > 1) { + foreach ($menu as $menu_item) { + $ttpl->setCurrentBlock("dmenu_cmd"); + $ttpl->setVariable("SUBITEM", (int) $menu_item["subitem"]); + $ttpl->setVariable("TXT_MENU_CMD", $menu_item["text"]); + $ttpl->parseCurrentBlock(); + } + + $ttpl->setCurrentBlock("disambiguation_menu"); + $ttpl->setVariable("DNODE_ID", $node_id); + $ttpl->setVariable("GRP", $group); + $ttpl->parseCurrentBlock(); + } elseif (count($menu) == 1) { + // set first child flag + $ttpl->setCurrentBlock("as_subitem_flag"); + $ttpl->setVariable("SI_NODE_ID", $node_id); + $ttpl->setVariable("SI_GRP", $group); + $ttpl->setVariable("SI_SI", (int) $menu[0]["subitem"]); + $ttpl->parseCurrentBlock(); + } + } + } + } + $this->diss_menues[$a_id][$a_group][] = array("type" => $a_type, "text" => $a_diss_text); + + // nodes + $ttpl->setVariable("NODES", $nodes_html); + + // title + //echo "
                  ".htmlentities($this->getTitle())." --- ".htmlentities(ilUtil::prepareFormOutput($this->getTitle())); + $ttpl->setVariable("TITLE", $this->getTitle()); + + + return $ttpl->get(); + } - /** - * Get Legend - * - * @return string legend html - */ - function getLegend() - { - $lng = $this->lng; + /** + * Get Legend + * + * @return string legend html + */ + public function getLegend() + { + $lng = $this->lng; - include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); + include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); - $ttpl = new ilTemplate("tpl.hierarchy_form_legend.html", true, true, "Services/Form"); - if ($this->getDragIcon() != "") - { - $ttpl->setCurrentBlock("help_drag"); - $ttpl->setVariable("IMG_DRAG", $this->getDragIcon()); - $ttpl->setVariable("DRAG_ARROW", - ilGlyphGUI::get(ilGlyphGUI::DRAG)); - $ttpl->setVariable("TXT_DRAG", - $lng->txt("form_hierarchy_drag_drop_help")); - $ttpl->setVariable("PLUS", ilGlyphGUI::get(ilGlyphGUI::ADD)); - $ttpl->parseCurrentBlock(); - } + $ttpl = new ilTemplate("tpl.hierarchy_form_legend.html", true, true, "Services/Form"); + if ($this->getDragIcon() != "") { + $ttpl->setCurrentBlock("help_drag"); + $ttpl->setVariable("IMG_DRAG", $this->getDragIcon()); + $ttpl->setVariable( + "DRAG_ARROW", + ilGlyphGUI::get(ilGlyphGUI::DRAG) + ); + $ttpl->setVariable( + "TXT_DRAG", + $lng->txt("form_hierarchy_drag_drop_help") + ); + $ttpl->setVariable("PLUS", ilGlyphGUI::get(ilGlyphGUI::ADD)); + $ttpl->parseCurrentBlock(); + } - // additional help items - foreach ($this->getHelpItems() as $help) - { - if ($help["image"] != "") - { - $ttpl->setCurrentBlock("help_img"); - $ttpl->setVariable("IMG_HELP", $help["image"]); - $ttpl->parseCurrentBlock(); - } - $ttpl->setCurrentBlock("help_item"); - $ttpl->setVariable("TXT_HELP", $help["text"]); - $ttpl->parseCurrentBlock(); - } + // additional help items + foreach ($this->getHelpItems() as $help) { + if ($help["image"] != "") { + $ttpl->setCurrentBlock("help_img"); + $ttpl->setVariable("IMG_HELP", $help["image"]); + $ttpl->parseCurrentBlock(); + } + $ttpl->setCurrentBlock("help_item"); + $ttpl->setVariable("TXT_HELP", $help["text"]); + $ttpl->parseCurrentBlock(); + } - $ttpl->setVariable("TXT_ADD_EL", - $lng->txt("form_hierarchy_add_elements")); - $ttpl->setVariable("PLUS2", ilGlyphGUI::get(ilGlyphGUI::ADD)); + $ttpl->setVariable( + "TXT_ADD_EL", + $lng->txt("form_hierarchy_add_elements") + ); + $ttpl->setVariable("PLUS2", ilGlyphGUI::get(ilGlyphGUI::ADD)); - return $ttpl->get(); - } + return $ttpl->get(); + } - /** - * Get Form HTML - */ - function getLevelHTML($a_par_node, $a_depth, &$a_childs) - { - $lng = $this->lng; - - if ($this->getMaxDepth() > -1 && $this->getMaxDepth() < $a_depth) - { - return ""; - } + /** + * Get Form HTML + */ + public function getLevelHTML($a_par_node, $a_depth, &$a_childs) + { + $lng = $this->lng; + + if ($this->getMaxDepth() > -1 && $this->getMaxDepth() < $a_depth) { + return ""; + } - $childs = $this->getChilds($a_par_node["node_id"]); - $a_childs = $childs; - $html = ""; - $last_child = null; - $ttpl = new ilTemplate("tpl.hierarchy_form_nodes.html", true, true, "Services/Form"); + $childs = $this->getChilds($a_par_node["node_id"]); + $a_childs = $childs; + $html = ""; + $last_child = null; + $ttpl = new ilTemplate("tpl.hierarchy_form_nodes.html", true, true, "Services/Form"); - // prepended drop area - if ($this->nodeAllowsChilds($a_par_node) && (count($childs) > 0 || $a_depth == 0)) - { - $ttpl->setCurrentBlock("drop_area"); - $ttpl->setVariable("DNODE_ID", $a_par_node["node_id"]."fc"); // fc means "first child" - $ttpl->setVariable("IMG_BLANK", ilUtil::getImagePath("spacer.png")); - if (count($childs) == 0) - { - $ttpl->setVariable("NO_CONTENT_CLASS", "ilCOPGNoPageContent"); - $ttpl->setVariable("NO_CONTENT_TXT", "  ".$lng->txt("form_hier_click_to_add")); - } - $ttpl->parseCurrentBlock(); - - $this->manageDragAndDrop($a_par_node, $a_depth, true, null, $childs); - $menu_items = $this->getMenuItems($a_par_node, $a_depth, true, null, $childs); -//var_dump($menu_items); - if (count($menu_items) > 0) - { - // determine maximum of multi add numbers - $max = 1; - foreach($menu_items as $menu_item) - { - if ($menu_item["multi"] > $max) - { - $max = $menu_item["multi"]; - } - } - - reset($menu_items); - $mcnt = 1; - foreach($menu_items as $menu_item) - { - if ($menu_item["multi"] > 1) - { - for($i = 1; $i <= $menu_item["multi"]; $i++) - { - $ttpl->setCurrentBlock("multi_add"); - $ttpl->setVariable("MA_NUM", $i); - $ttpl->setVariable("MENU_CMD", $menu_item["cmd"]); - $ttpl->setVariable("FC", "1"); - $ttpl->setVariable("CMD_NODE", $a_par_node["node_id"]); - $ttpl->setVariable("MCNT", $mcnt."fc"); - $ttpl->parseCurrentBlock(); - } - } - - // buffer td for lower multis - if ($max > $menu_item["multi"]) - { - $ttpl->setCurrentBlock("multi_buffer"); - $ttpl->setVariable("BUF_SPAN", $max - $menu_item["multi"]); - $ttpl->parseCurrentBlock(); - } - $ttpl->setCurrentBlock("menu_cmd"); - $ttpl->setVariable("TXT_MENU_CMD", $menu_item["text"]); - $ttpl->setVariable("MENU_CMD", $menu_item["cmd"]); - $ttpl->setVariable("CMD_NODE", $a_par_node["node_id"]); - $ttpl->setVariable("FC", "1"); - $ttpl->setVariable("MCNT", $mcnt."fc"); - $ttpl->parseCurrentBlock(); - $mcnt++; - } - $ttpl->setCurrentBlock("drop_area_menu"); - $ttpl->setVariable("MNODE_ID", $a_par_node["node_id"]."fc"); - $ttpl->parseCurrentBlock(); - - $ttpl->setCurrentBlock("element"); - $ttpl->parseCurrentBlock(); - } - } - - // insert childs - if (count($childs) > 0) - { - for($i = 0; $i < count($childs); $i++) - { - $next_sibling = ($i < (count($childs) - 1)) - ? $next_sibling = $childs[$i+1] - : null; + // prepended drop area + if ($this->nodeAllowsChilds($a_par_node) && (count($childs) > 0 || $a_depth == 0)) { + $ttpl->setCurrentBlock("drop_area"); + $ttpl->setVariable("DNODE_ID", $a_par_node["node_id"] . "fc"); // fc means "first child" + $ttpl->setVariable("IMG_BLANK", ilUtil::getImagePath("spacer.png")); + if (count($childs) == 0) { + $ttpl->setVariable("NO_CONTENT_CLASS", "ilCOPGNoPageContent"); + $ttpl->setVariable("NO_CONTENT_TXT", "  " . $lng->txt("form_hier_click_to_add")); + } + $ttpl->parseCurrentBlock(); + + $this->manageDragAndDrop($a_par_node, $a_depth, true, null, $childs); + $menu_items = $this->getMenuItems($a_par_node, $a_depth, true, null, $childs); + //var_dump($menu_items); + if (count($menu_items) > 0) { + // determine maximum of multi add numbers + $max = 1; + foreach ($menu_items as $menu_item) { + if ($menu_item["multi"] > $max) { + $max = $menu_item["multi"]; + } + } + + reset($menu_items); + $mcnt = 1; + foreach ($menu_items as $menu_item) { + if ($menu_item["multi"] > 1) { + for ($i = 1; $i <= $menu_item["multi"]; $i++) { + $ttpl->setCurrentBlock("multi_add"); + $ttpl->setVariable("MA_NUM", $i); + $ttpl->setVariable("MENU_CMD", $menu_item["cmd"]); + $ttpl->setVariable("FC", "1"); + $ttpl->setVariable("CMD_NODE", $a_par_node["node_id"]); + $ttpl->setVariable("MCNT", $mcnt . "fc"); + $ttpl->parseCurrentBlock(); + } + } + + // buffer td for lower multis + if ($max > $menu_item["multi"]) { + $ttpl->setCurrentBlock("multi_buffer"); + $ttpl->setVariable("BUF_SPAN", $max - $menu_item["multi"]); + $ttpl->parseCurrentBlock(); + } + $ttpl->setCurrentBlock("menu_cmd"); + $ttpl->setVariable("TXT_MENU_CMD", $menu_item["text"]); + $ttpl->setVariable("MENU_CMD", $menu_item["cmd"]); + $ttpl->setVariable("CMD_NODE", $a_par_node["node_id"]); + $ttpl->setVariable("FC", "1"); + $ttpl->setVariable("MCNT", $mcnt . "fc"); + $ttpl->parseCurrentBlock(); + $mcnt++; + } + $ttpl->setCurrentBlock("drop_area_menu"); + $ttpl->setVariable("MNODE_ID", $a_par_node["node_id"] . "fc"); + $ttpl->parseCurrentBlock(); + + $ttpl->setCurrentBlock("element"); + $ttpl->parseCurrentBlock(); + } + } + + // insert childs + if (count($childs) > 0) { + for ($i = 0; $i < count($childs); $i++) { + $next_sibling = ($i < (count($childs) - 1)) + ? $next_sibling = $childs[$i+1] + : null; - $this->renderChild($ttpl, $childs[$i], $a_depth, $next_sibling); - $last_child = $child; - } - } + $this->renderChild($ttpl, $childs[$i], $a_depth, $next_sibling); + $last_child = $child; + } + } - $html = $ttpl->get(); - unset($ttpl); - - return $html; - } - - /** - * Render a single child (including grandchilds) - */ - function renderChild($a_tpl, $a_child, $a_depth, $next_sibling = null) - { - $ilCtrl = $this->ctrl; - - // image - $a_tpl->setCurrentBlock("img"); - $a_tpl->setVariable("IMGPATH", $this->getChildIcon($a_child)); - $a_tpl->setVariable("IMGALT", $this->getChildIconAlt($a_child)); - $a_tpl->setVariable("IMG_NODE", $a_child["node_id"]); - $a_tpl->setVariable("NODE_ID", $a_child["node_id"]); - $a_tpl->setVariable("TYPE", $a_child["type"]); - $a_tpl->parseCurrentBlock(); - - // checkbox - $a_tpl->setCurrentBlock("cbox"); - $a_tpl->setVariable("CNODE_ID", $a_child["node_id"]); - $a_tpl->setVariable("CBOX_NAME", $this->getCheckboxName()); - $a_tpl->parseCurrentBlock(); - - // node info - if (($info = $this->getChildInfo($a_child)) != "") - { - $a_tpl->setCurrentBlock("node_info"); - $a_tpl->setVariable("NODE_INFO", $info); - $a_tpl->parseCurrentBlock(); - } - - // commands of child node - $child_commands = $this->getChildCommands($a_child); - if (is_array($child_commands)) - { - foreach($child_commands as $command) - { - $a_tpl->setCurrentBlock("node_cmd"); - $a_tpl->setVariable("HREF_NODE_CMD", $command["link"]); - $a_tpl->setVariable("TXT_NODE_CMD", $command["text"]); - $a_tpl->parseCurrentBlock(); - } - } - - // title - $a_tpl->setCurrentBlock("text"); - $hl = $this->getHighlightedNodes(); - if (is_array($hl) && in_array($a_child["node_id"], $hl)) - { - $a_tpl->setVariable("CLASS", ' class="ilHFormHighlighted" '); - } - $a_tpl->setVariable("VAL_TITLE", ilUtil::prepareFormOutput($this->getChildTitle($a_child))); - $a_tpl->setVariable("TNODE_ID", $a_child["node_id"]); - $a_tpl->parseCurrentBlock(); - $grandchilds = null; - $grandchilds_html = $this->getLevelHTML($a_child, $a_depth + 1, $grandchilds); - - // focus - if ($this->getFocusId() == $a_child["node_id"]) - { - $a_tpl->setCurrentBlock("focus"); - $a_tpl->setVariable("FNODE_ID", $a_child["node_id"]); - $a_tpl->parseCurrentBlock(); - } - - // expander - if ($this->getExpandVariable() != "") - { - $a_tpl->setCurrentBlock("expand_icon"); - if (!is_null($grandchilds) && count($grandchilds) > 0) - { - if (!in_array($a_child["node_id"],$this->getExpanded())) - { - $ilCtrl->setParameter($this->getParentObject(), $this->getExpandVariable(), $a_child["node_id"]); - $a_tpl->setVariable("IMG_EXPAND", ilUtil::getImagePath("browser/plus.png")); - $a_tpl->setVariable("HREF_NAME", "n".$a_child["node_id"]); - $a_tpl->setVariable("HREF_EXPAND", - $ilCtrl->getLinkTarget($this->getParentObject(), $this->getParentCommand(), "n".$a_child["node_id"])); - $grandchilds_html = ""; - } - else - { - $ilCtrl->setParameter($this->getParentObject(), $this->getExpandVariable(), -$a_child["node_id"]); - $a_tpl->setVariable("IMG_EXPAND", ilUtil::getImagePath("browser/minus.png")); - $a_tpl->setVariable("HREF_NAME", "n".$a_child["node_id"]); - $a_tpl->setVariable("HREF_EXPAND", - $ilCtrl->getLinkTarget($this->getParentObject(), $this->getParentCommand(), "n".$a_child["node_id"])); - } - $ilCtrl->setParameter($this->getParentObject(), $this->getExpandVariable(), ""); - } - else - { - $a_tpl->setVariable("IMG_EXPAND", ilUtil::getImagePath("spacer.png")); - } - $a_tpl->parseCurrentBlock(); - } - - // childs - $a_tpl->setCurrentBlock("list_item"); - $a_tpl->setVariable("CHILDS", $grandchilds_html); - $a_tpl->parseCurrentBlock(); - - $a_tpl->setCurrentBlock("element"); - $a_tpl->parseCurrentBlock(); - - // drop area after child - $a_tpl->setCurrentBlock("drop_area"); - $a_tpl->setVariable("DNODE_ID", $a_child["node_id"]); - $a_tpl->setVariable("IMG_BLANK", ilUtil::getImagePath("spacer.png")); - $a_tpl->parseCurrentBlock(); + $html = $ttpl->get(); + unset($ttpl); + + return $html; + } + + /** + * Render a single child (including grandchilds) + */ + public function renderChild($a_tpl, $a_child, $a_depth, $next_sibling = null) + { + $ilCtrl = $this->ctrl; + + // image + $a_tpl->setCurrentBlock("img"); + $a_tpl->setVariable("IMGPATH", $this->getChildIcon($a_child)); + $a_tpl->setVariable("IMGALT", $this->getChildIconAlt($a_child)); + $a_tpl->setVariable("IMG_NODE", $a_child["node_id"]); + $a_tpl->setVariable("NODE_ID", $a_child["node_id"]); + $a_tpl->setVariable("TYPE", $a_child["type"]); + $a_tpl->parseCurrentBlock(); + + // checkbox + $a_tpl->setCurrentBlock("cbox"); + $a_tpl->setVariable("CNODE_ID", $a_child["node_id"]); + $a_tpl->setVariable("CBOX_NAME", $this->getCheckboxName()); + $a_tpl->parseCurrentBlock(); + + // node info + if (($info = $this->getChildInfo($a_child)) != "") { + $a_tpl->setCurrentBlock("node_info"); + $a_tpl->setVariable("NODE_INFO", $info); + $a_tpl->parseCurrentBlock(); + } + + // commands of child node + $child_commands = $this->getChildCommands($a_child); + if (is_array($child_commands)) { + foreach ($child_commands as $command) { + $a_tpl->setCurrentBlock("node_cmd"); + $a_tpl->setVariable("HREF_NODE_CMD", $command["link"]); + $a_tpl->setVariable("TXT_NODE_CMD", $command["text"]); + $a_tpl->parseCurrentBlock(); + } + } + + // title + $a_tpl->setCurrentBlock("text"); + $hl = $this->getHighlightedNodes(); + if (is_array($hl) && in_array($a_child["node_id"], $hl)) { + $a_tpl->setVariable("CLASS", ' class="ilHFormHighlighted" '); + } + $a_tpl->setVariable("VAL_TITLE", ilUtil::prepareFormOutput($this->getChildTitle($a_child))); + $a_tpl->setVariable("TNODE_ID", $a_child["node_id"]); + $a_tpl->parseCurrentBlock(); + $grandchilds = null; + $grandchilds_html = $this->getLevelHTML($a_child, $a_depth + 1, $grandchilds); + + // focus + if ($this->getFocusId() == $a_child["node_id"]) { + $a_tpl->setCurrentBlock("focus"); + $a_tpl->setVariable("FNODE_ID", $a_child["node_id"]); + $a_tpl->parseCurrentBlock(); + } + + // expander + if ($this->getExpandVariable() != "") { + $a_tpl->setCurrentBlock("expand_icon"); + if (!is_null($grandchilds) && count($grandchilds) > 0) { + if (!in_array($a_child["node_id"], $this->getExpanded())) { + $ilCtrl->setParameter($this->getParentObject(), $this->getExpandVariable(), $a_child["node_id"]); + $a_tpl->setVariable("IMG_EXPAND", ilUtil::getImagePath("browser/plus.png")); + $a_tpl->setVariable("HREF_NAME", "n" . $a_child["node_id"]); + $a_tpl->setVariable( + "HREF_EXPAND", + $ilCtrl->getLinkTarget($this->getParentObject(), $this->getParentCommand(), "n" . $a_child["node_id"]) + ); + $grandchilds_html = ""; + } else { + $ilCtrl->setParameter($this->getParentObject(), $this->getExpandVariable(), -$a_child["node_id"]); + $a_tpl->setVariable("IMG_EXPAND", ilUtil::getImagePath("browser/minus.png")); + $a_tpl->setVariable("HREF_NAME", "n" . $a_child["node_id"]); + $a_tpl->setVariable( + "HREF_EXPAND", + $ilCtrl->getLinkTarget($this->getParentObject(), $this->getParentCommand(), "n" . $a_child["node_id"]) + ); + } + $ilCtrl->setParameter($this->getParentObject(), $this->getExpandVariable(), ""); + } else { + $a_tpl->setVariable("IMG_EXPAND", ilUtil::getImagePath("spacer.png")); + } + $a_tpl->parseCurrentBlock(); + } + + // childs + $a_tpl->setCurrentBlock("list_item"); + $a_tpl->setVariable("CHILDS", $grandchilds_html); + $a_tpl->parseCurrentBlock(); + + $a_tpl->setCurrentBlock("element"); + $a_tpl->parseCurrentBlock(); + + // drop area after child + $a_tpl->setCurrentBlock("drop_area"); + $a_tpl->setVariable("DNODE_ID", $a_child["node_id"]); + $a_tpl->setVariable("IMG_BLANK", ilUtil::getImagePath("spacer.png")); + $a_tpl->parseCurrentBlock(); - // manage drag and drop areas - $this->manageDragAndDrop($a_child, $a_depth, false, $next_sibling, $grandchilds); - - // drop area menu - $menu_items = $this->getMenuItems($a_child, $a_depth, false, $next_sibling, $grandchilds); - if (count($menu_items) > 0) - { - // determine maximum of multi add numbers - $max = 1; - foreach($menu_items as $menu_item) - { - if ($menu_item["multi"] > $max) - { - $max = $menu_item["multi"]; - } - } - - reset($menu_items); - $mcnt = 1; - foreach($menu_items as $menu_item) - { - if ($menu_item["multi"] > 1 ) - { - for($i = 1; $i <= $menu_item["multi"]; $i++) - { - $a_tpl->setCurrentBlock("multi_add"); - $a_tpl->setVariable("MA_NUM", $i); - $a_tpl->setVariable("MENU_CMD", $menu_item["cmd"]); - if ($menu_item["as_subitem"]) - { - $a_tpl->setVariable("FC", "1"); - $a_tpl->setVariable("MCNT", $mcnt."fc"); - } - else - { - $a_tpl->setVariable("FC", "0"); - $a_tpl->setVariable("MCNT", $mcnt); - } - $a_tpl->setVariable("CMD_NODE", $a_child["node_id"]); - $a_tpl->parseCurrentBlock(); - } - } - - // buffer td for lower multis - if ($max > $menu_item["multi"]) - { - $a_tpl->setCurrentBlock("multi_buffer"); - $a_tpl->setVariable("BUF_SPAN", $max - $menu_item["multi"]); - $a_tpl->parseCurrentBlock(); - } - - $a_tpl->setCurrentBlock("menu_cmd"); - $a_tpl->setVariable("TXT_MENU_CMD", $menu_item["text"]); - $a_tpl->setVariable("MENU_CMD", $menu_item["cmd"]); - if ($menu_item["as_subitem"]) - { - $a_tpl->setVariable("FC", "1"); - $a_tpl->setVariable("MCNT", $mcnt."fc"); - } - else - { - $a_tpl->setVariable("FC", "0"); - $a_tpl->setVariable("MCNT", $mcnt); - } - $a_tpl->setVariable("CMD_NODE", $a_child["node_id"]); - $a_tpl->parseCurrentBlock(); - $mcnt++; - } - $a_tpl->setCurrentBlock("drop_area_menu"); - $a_tpl->setVariable("MNODE_ID", $a_child["node_id"]); - $a_tpl->parseCurrentBlock(); - } - - $a_tpl->setCurrentBlock("element"); - $a_tpl->parseCurrentBlock(); - } - - /** - * Get icon path for an item. - * - * @param array item array - * @return string icon path - */ - function getChildIcon($a_item) - { - return ilUtil::getImagePath("icon_".$a_item["type"].".svg"); - } - - /** - * Get icon alt text for an item. - * - * @param array item array - * @return string icon alt text - */ - function getChildIconAlt($a_item) - { - $lng = $this->lng; - - return $lng->txt($a_item["type"]); - } + // manage drag and drop areas + $this->manageDragAndDrop($a_child, $a_depth, false, $next_sibling, $grandchilds); + + // drop area menu + $menu_items = $this->getMenuItems($a_child, $a_depth, false, $next_sibling, $grandchilds); + if (count($menu_items) > 0) { + // determine maximum of multi add numbers + $max = 1; + foreach ($menu_items as $menu_item) { + if ($menu_item["multi"] > $max) { + $max = $menu_item["multi"]; + } + } + + reset($menu_items); + $mcnt = 1; + foreach ($menu_items as $menu_item) { + if ($menu_item["multi"] > 1) { + for ($i = 1; $i <= $menu_item["multi"]; $i++) { + $a_tpl->setCurrentBlock("multi_add"); + $a_tpl->setVariable("MA_NUM", $i); + $a_tpl->setVariable("MENU_CMD", $menu_item["cmd"]); + if ($menu_item["as_subitem"]) { + $a_tpl->setVariable("FC", "1"); + $a_tpl->setVariable("MCNT", $mcnt . "fc"); + } else { + $a_tpl->setVariable("FC", "0"); + $a_tpl->setVariable("MCNT", $mcnt); + } + $a_tpl->setVariable("CMD_NODE", $a_child["node_id"]); + $a_tpl->parseCurrentBlock(); + } + } + + // buffer td for lower multis + if ($max > $menu_item["multi"]) { + $a_tpl->setCurrentBlock("multi_buffer"); + $a_tpl->setVariable("BUF_SPAN", $max - $menu_item["multi"]); + $a_tpl->parseCurrentBlock(); + } + + $a_tpl->setCurrentBlock("menu_cmd"); + $a_tpl->setVariable("TXT_MENU_CMD", $menu_item["text"]); + $a_tpl->setVariable("MENU_CMD", $menu_item["cmd"]); + if ($menu_item["as_subitem"]) { + $a_tpl->setVariable("FC", "1"); + $a_tpl->setVariable("MCNT", $mcnt . "fc"); + } else { + $a_tpl->setVariable("FC", "0"); + $a_tpl->setVariable("MCNT", $mcnt); + } + $a_tpl->setVariable("CMD_NODE", $a_child["node_id"]); + $a_tpl->parseCurrentBlock(); + $mcnt++; + } + $a_tpl->setCurrentBlock("drop_area_menu"); + $a_tpl->setVariable("MNODE_ID", $a_child["node_id"]); + $a_tpl->parseCurrentBlock(); + } + + $a_tpl->setCurrentBlock("element"); + $a_tpl->parseCurrentBlock(); + } + + /** + * Get icon path for an item. + * + * @param array item array + * @return string icon path + */ + public function getChildIcon($a_item) + { + return ilUtil::getImagePath("icon_" . $a_item["type"] . ".svg"); + } + + /** + * Get icon alt text for an item. + * + * @param array item array + * @return string icon alt text + */ + public function getChildIconAlt($a_item) + { + $lng = $this->lng; + + return $lng->txt($a_item["type"]); + } - /** - * Get item commands - * - * @param array item array - * @return array array of arrays("text", "link") - */ - function getChildCommands($a_item) - { - return false; - } + /** + * Get item commands + * + * @param array item array + * @return array array of arrays("text", "link") + */ + public function getChildCommands($a_item) + { + return false; + } - /** - * Get child title - * - * @param array $a_child node array - * @return string node title - */ - function getChildTitle($a_child) - { - return $a_child["title"]; - } - - /** - * Get child info - * - * @param array $a_child node array - * @return string node title - */ - function getChildInfo($a_child) - { - return ""; - } - - /** - * Get menu items for drop area of node. - * - * This function will be most likely overwritten by sub class - * - * @param array $a_child node array ("title", "node_id", "type") - * @param boolean $a_first_child if false, the menu of the drop area - * right after the node (same level) is set - * if true, the menu of the drop area before - * the first child (if nodes are allowed) - * of the node is set - */ - function getMenuItems($a_node, $a_depth, $a_first_child = false, $a_next_sibling = null, $a_childs = null) - { - return array(); - } - - /** - * Checks, whether current nodes allows childs at all. - * Should be overwritten. - */ - function nodeAllowsChilds($a_node) - { - return true; - } - - /** - * Makes nodes drag and drop content and targets. - * Must be overwritten to support drag and drop. - * - * @param object $a_node node array - */ - function manageDragAndDrop($a_node, $a_depth, $a_first_child = false, $a_next_sibling = null, $a_childs = null) - { - //$this->makeDragTarget($a_node["id"], $a_group); - //$this->makeDragTarget($a_node["id"], $a_group); - } + /** + * Get child title + * + * @param array $a_child node array + * @return string node title + */ + public function getChildTitle($a_child) + { + return $a_child["title"]; + } + + /** + * Get child info + * + * @param array $a_child node array + * @return string node title + */ + public function getChildInfo($a_child) + { + return ""; + } + + /** + * Get menu items for drop area of node. + * + * This function will be most likely overwritten by sub class + * + * @param array $a_child node array ("title", "node_id", "type") + * @param boolean $a_first_child if false, the menu of the drop area + * right after the node (same level) is set + * if true, the menu of the drop area before + * the first child (if nodes are allowed) + * of the node is set + */ + public function getMenuItems($a_node, $a_depth, $a_first_child = false, $a_next_sibling = null, $a_childs = null) + { + return array(); + } + + /** + * Checks, whether current nodes allows childs at all. + * Should be overwritten. + */ + public function nodeAllowsChilds($a_node) + { + return true; + } + + /** + * Makes nodes drag and drop content and targets. + * Must be overwritten to support drag and drop. + * + * @param object $a_node node array + */ + public function manageDragAndDrop($a_node, $a_depth, $a_first_child = false, $a_next_sibling = null, $a_childs = null) + { + //$this->makeDragTarget($a_node["id"], $a_group); + //$this->makeDragTarget($a_node["id"], $a_group); + } - /** - * Get multi number of _POST input - */ - static function getPostMulti() - { - return (int) ($_POST["il_hform_multi"] > 1 - ? $_POST["il_hform_multi"] - : 1); - } - - /** - * Get node ID of _POST input - */ - static function getPostNodeId() - { - return $_POST["il_hform_node"]; - } + /** + * Get multi number of _POST input + */ + public static function getPostMulti() + { + return (int) ($_POST["il_hform_multi"] > 1 + ? $_POST["il_hform_multi"] + : 1); + } + + /** + * Get node ID of _POST input + */ + public static function getPostNodeId() + { + return $_POST["il_hform_node"]; + } - /** - * Should node be inserted as first child of target node (true) or as successor (false) - */ - static function getPostFirstChild() - { - return (((int) $_POST["il_hform_fc"]) == 1); - } + /** + * Should node be inserted as first child of target node (true) or as successor (false) + */ + public static function getPostFirstChild() + { + return (((int) $_POST["il_hform_fc"]) == 1); + } - /** - * Get HTML - * - * @param - * @return - */ - function getHTML() - { - return parent::getHTML().$this->getLegend(); - } + /** + * Get HTML + * + * @param + * @return + */ + public function getHTML() + { + return parent::getHTML() . $this->getLegend(); + } - /** - * Get all post fields - */ - static function getPostFields() - { - return array ( - "il_hform_node" => $_POST["il_hform_node"], - "il_hform_fc" => $_POST["il_hform_fc"], - "il_hform_as_subitem" => $_POST["il_hform_as_subitem"], - "il_hform_multi" => $_POST["il_hform_multi"], - "il_hform_source_id" => $_POST["il_hform_source_id"], - "il_hform_target_id" => $_POST["il_hform_target_id"] - ); - } - + /** + * Get all post fields + */ + public static function getPostFields() + { + return array( + "il_hform_node" => $_POST["il_hform_node"], + "il_hform_fc" => $_POST["il_hform_fc"], + "il_hform_as_subitem" => $_POST["il_hform_as_subitem"], + "il_hform_multi" => $_POST["il_hform_multi"], + "il_hform_source_id" => $_POST["il_hform_source_id"], + "il_hform_target_id" => $_POST["il_hform_target_id"] + ); + } } diff --git a/Services/Form/classes/class.ilIdentifiedMultiFilesJsPositionIndexRemover.php b/Services/Form/classes/class.ilIdentifiedMultiFilesJsPositionIndexRemover.php index 22e44b735ac473ac42414a62d0cf3803de686ce8..47b6b02d887103a385bd3155d6528d7d715ba1e5 100644 --- a/Services/Form/classes/class.ilIdentifiedMultiFilesJsPositionIndexRemover.php +++ b/Services/Form/classes/class.ilIdentifiedMultiFilesJsPositionIndexRemover.php @@ -11,63 +11,59 @@ require_once 'Services/Form/classes/class.ilIdentifiedMultiValuesJsPositionIndex */ class ilIdentifiedMultiFilesJsPositionIndexRemover extends ilIdentifiedMultiValuesJsPositionIndexRemover { - protected $postVar = null; - - public function getPostVar() - { - return $this->postVar; - } - - public function setPostVar($postVar) - { - $this->postVar = $postVar; - } - - public function manipulateFormInputValues($inputValues) - { - // KEEP THIS INTERFACE METHOD OVERWRITTEN THIS LIKE (!) - return $inputValues; - } + protected $postVar = null; + + public function getPostVar() + { + return $this->postVar; + } + + public function setPostVar($postVar) + { + $this->postVar = $postVar; + } + + public function manipulateFormInputValues($inputValues) + { + // KEEP THIS INTERFACE METHOD OVERWRITTEN THIS LIKE (!) + return $inputValues; + } - public function manipulateFormSubmitValues($values) - { - if( $this->isFileSubmitAvailable() ) - { - $this->prepareFileSubmit(); - } - - return $values; - } - - protected function isFileSubmitAvailable() - { - if( !isset($_FILES[$this->getPostVar()]) ) - { - return false; - } - - if( !is_array($_FILES[$this->getPostVar()]) ) - { - return false; - } - - if( !in_array('tmp_name', array_keys($_FILES[$this->getPostVar()])) ) - { - return false; - } - - return true; - } - - protected function prepareFileSubmit() - { - $_FILES[$this->getPostVar()] = $this->prepareMultiFilesSubmitValues( - $_FILES[$this->getPostVar()] - ); - } - - protected function prepareMultiFilesSubmitValues($filesSubmitValues) - { - return $this->removePositionIndexLevels($filesSubmitValues); - } -} \ No newline at end of file + public function manipulateFormSubmitValues($values) + { + if ($this->isFileSubmitAvailable()) { + $this->prepareFileSubmit(); + } + + return $values; + } + + protected function isFileSubmitAvailable() + { + if (!isset($_FILES[$this->getPostVar()])) { + return false; + } + + if (!is_array($_FILES[$this->getPostVar()])) { + return false; + } + + if (!in_array('tmp_name', array_keys($_FILES[$this->getPostVar()]))) { + return false; + } + + return true; + } + + protected function prepareFileSubmit() + { + $_FILES[$this->getPostVar()] = $this->prepareMultiFilesSubmitValues( + $_FILES[$this->getPostVar()] + ); + } + + protected function prepareMultiFilesSubmitValues($filesSubmitValues) + { + return $this->removePositionIndexLevels($filesSubmitValues); + } +} diff --git a/Services/Form/classes/class.ilIdentifiedMultiValuesInputGUI.php b/Services/Form/classes/class.ilIdentifiedMultiValuesInputGUI.php index 1380b4ffa2c17ce63c1ff058db1ac810f3d8cc80..0be8fc57ef91f8c468e5e8dc8667588d83249947 100644 --- a/Services/Form/classes/class.ilIdentifiedMultiValuesInputGUI.php +++ b/Services/Form/classes/class.ilIdentifiedMultiValuesInputGUI.php @@ -12,284 +12,280 @@ require_once 'Services/Form/interfaces/interface.ilMultiValuesItem.php'; */ abstract class ilIdentifiedMultiValuesInputGUI extends ilTextInputGUI implements ilMultiValuesItem { - const ELEMENT_DEFAULT_ADD_CMD = 'addElement'; - const ELEMENT_DEFAULT_REMOVE_CMD = 'removeElement'; - const ELEMENT_DEFAULT_MOVE_UP_CMD = 'moveUpElement'; - const ELEMENT_DEFAULT_MOVE_DOWN_CMD = 'moveDownElement'; - - protected $elementAddCmd = self::ELEMENT_DEFAULT_ADD_CMD; - protected $elementRemoveCmd = self::ELEMENT_DEFAULT_REMOVE_CMD; - protected $elementMoveUpCommand = self::ELEMENT_DEFAULT_MOVE_UP_CMD; - protected $elementMoveDownCommand = self::ELEMENT_DEFAULT_MOVE_DOWN_CMD; + const ELEMENT_DEFAULT_ADD_CMD = 'addElement'; + const ELEMENT_DEFAULT_REMOVE_CMD = 'removeElement'; + const ELEMENT_DEFAULT_MOVE_UP_CMD = 'moveUpElement'; + const ELEMENT_DEFAULT_MOVE_DOWN_CMD = 'moveDownElement'; + + protected $elementAddCmd = self::ELEMENT_DEFAULT_ADD_CMD; + protected $elementRemoveCmd = self::ELEMENT_DEFAULT_REMOVE_CMD; + protected $elementMoveUpCommand = self::ELEMENT_DEFAULT_MOVE_UP_CMD; + protected $elementMoveDownCommand = self::ELEMENT_DEFAULT_MOVE_DOWN_CMD; - protected $identified_multi_values = array(); - - protected $formValuesManipulationChain = array(); + protected $identified_multi_values = array(); + + protected $formValuesManipulationChain = array(); - public function __construct($a_title = "", $a_postvar = "") - { - parent::__construct($a_title, $a_postvar); - - require_once 'Services/Form/classes/class.ilFormSubmitRecursiveSlashesStripper.php'; - $this->addFormValuesManipulator(new ilFormSubmitRecursiveSlashesStripper()); - - require_once 'Services/Form/classes/class.ilIdentifiedMultiValuesJsPositionIndexRemover.php'; - $this->addFormValuesManipulator(new ilIdentifiedMultiValuesJsPositionIndexRemover()); - - //$this->setMulti(true); // this is another planet, do not enable (!) - } - - public function getElementAddCmd() - { - return $this->elementAddCmd; - } - - /** - * @param string $elementAddCmd - */ - public function setElementAddCmd($elementAddCmd) - { - $this->elementAddCmd = $elementAddCmd; - } - - public function getElementRemoveCmd() - { - return $this->elementRemoveCmd; - } - - public function setElementRemoveCmd($elementRemoveCmd) - { - $this->elementRemoveCmd = $elementRemoveCmd; - } - - public function getElementMoveUpCommand() - { - return $this->elementMoveUpCommand; - } - - public function setElementMoveUpCommand($elementMoveUpCommand) - { - $this->elementMoveUpCommand = $elementMoveUpCommand; - } - - public function getElementMoveDownCommand() - { - return $this->elementMoveDownCommand; - } - - public function setElementMoveDownCommand($elementMoveDownCommand) - { - $this->elementMoveDownCommand = $elementMoveDownCommand; - } - - public function setValues($values) - { - require_once 'Services/Form/exceptions/class.ilFormException.php'; - throw new ilFormException('setter unsupported, use setIdentifiedMultiValues() instead!'); - } - - public function getValues() - { - require_once 'Services/Form/exceptions/class.ilFormException.php'; - throw new ilFormException('setter unsupported, use setIdentifiedMultiValues() instead!'); - } - - public function setValue($value) - { - require_once 'Services/Form/exceptions/class.ilFormException.php'; - throw new ilFormException('setter unsupported, use setIdentifiedMultiValues() instead!'); - } - - public function getValue() - { - require_once 'Services/Form/exceptions/class.ilFormException.php'; - throw new ilFormException('setter unsupported, use setIdentifiedMultiValues() instead!'); - } - - public function setMultiValues(array $values) - { - require_once 'Services/Form/exceptions/class.ilFormException.php'; - throw new ilFormException('setter unsupported, use setIdentifiedMultiValues() instead!'); - } - - public function getMultiValues() - { - require_once 'Services/Form/exceptions/class.ilFormException.php'; - throw new ilFormException('setter unsupported, use setIdentifiedMultiValues() instead!'); - } - - final public function setIdentifiedMultiValues($values) - { - $this->identified_multi_values = $this->prepareMultiValuesInput($values); - } - - final public function getIdentifiedMultiValues() - { - return $this->identified_multi_values; - } - - protected function getMultiValueSubFieldId($identifier, $subFieldIndex) - { - $tempPostVar = $this->getMultiValuePostVarSubField($identifier, $subFieldIndex); - $multiValueFieldId = $this->getFieldIdFromPostVar($tempPostVar); - - return $multiValueFieldId; - } - - protected function getMultiValuePosIndexedFieldId($identifier, $positionIndex) - { - $tempPostVar = $this->getMultiValuePostVarPosIndexed($identifier, $positionIndex); - $multiValueFieldId = $this->getFieldIdFromPostVar($tempPostVar); - - return $multiValueFieldId; - } - - protected function getMultiValuePosIndexedSubFieldId($identifier, $subFieldIndex, $positionIndex) - { - $tempPostVar = $this->getMultiValuePostVarSubFieldPosIndexed($identifier, $subFieldIndex, $positionIndex); - $multiValueFieldId = $this->getFieldIdFromPostVar($tempPostVar); - - return $multiValueFieldId; - } - - protected function getFieldIdFromPostVar($tempPostVar) - { - $basicPostVar = $this->getPostVar(); - $this->setPostVar($tempPostVar); - - // uses getPostVar() internally, our postvar does not have the counter included - $multiValueFieldId = $this->getFieldId(); - // now ALL brackets ("[", "]") are escaped, even the ones for the counter - - $this->setPostVar($basicPostVar); - return $multiValueFieldId; - } - - protected function getPostVarSubField($subFieldIndex) - { - return $this->getSubFieldCompletedPostVar($subFieldIndex, $this->getPostVar()); - } - - protected function getMultiValuePostVarSubField($identifier, $subFieldIndex) - { - $elemPostVar = $this->getMultiValuePostVar($identifier); - $elemPostVar = $this->getSubFieldCompletedPostVar($subFieldIndex, $elemPostVar); - - return $elemPostVar; - } - - protected function getMultiValuePostVarSubFieldPosIndexed($identifier, $subFieldIndex, $positionIndex) - { - $elemPostVar = $this->getMultiValuePostVarPosIndexed($identifier, $positionIndex); - $elemPostVar = $this->getSubFieldCompletedPostVar($subFieldIndex, $elemPostVar); - - return $elemPostVar; - } - - protected function getMultiValuePostVarPosIndexed($identifier, $positionIndex) - { - $elemPostVar = $this->getMultiValuePostVar($identifier); - $elemPostVar .= "[$positionIndex]"; - - return $elemPostVar; - } - - protected function getMultiValuePostVar($identifier) - { - $elemPostVar = $this->getPostVar(); - $elemPostVar .= "[$identifier]"; - return $elemPostVar; - } - - protected function buildMultiValueSubmitVar($identifier, $positionIndex, $submitCommand) - { - $elemSubmitVar = "cmd[{$submitCommand}][{$this->getFieldId()}]"; - $elemSubmitVar .= "[$identifier][$positionIndex]"; - - return $elemSubmitVar; - } - - final public function setValueByArray($a_values) - { - if( !is_array($a_values[$this->getPostVar()]) ) - { - $a_values[$this->getPostVar()] = array(); - } - - $a_values[$this->getPostVar()] = $this->prepareMultiValuesSubmit( - $a_values[$this->getPostVar()] - ); - - $this->setIdentifiedMultiValuesByArray($a_values); - } - - protected function setIdentifiedMultiValuesByArray($a_values) - { - $this->identified_multi_values = $a_values[$this->getPostVar()]; - } - - final public function checkInput() - { - if( !is_array($_POST[$this->getPostVar()]) ) - { - $_POST[$this->getPostVar()] = array(); - } - - $_POST[$this->getPostVar()] = $this->prepareMultiValuesSubmit( - $_POST[$this->getPostVar()] - ); - - return $this->onCheckInput(); - } - - abstract public function onCheckInput(); - - final protected function prepareMultiValuesInput($values) - { - foreach($this->getFormValuesManipulators() as $manipulator) - { - /* @var ilFormValuesManipulator $manipulator */ - $values = $manipulator->manipulateFormInputValues($values); - } - - return $values; - } - - final protected function prepareMultiValuesSubmit($values) - { - foreach($this->getFormValuesManipulators() as $manipulator) - { - /* @var ilFormValuesManipulator $manipulator */ - $values = $manipulator->manipulateFormSubmitValues($values); - } - - return $values; - } - - protected function getFormValuesManipulators() - { - return $this->formValuesManipulationChain; - } - - protected function addFormValuesManipulator(ilFormValuesManipulator $manipulator) - { - $this->formValuesManipulationChain[] = $manipulator; - } - - /** - * @param $subFieldIndex - * @param $elemPostVar - * @return mixed - */ - protected function getSubFieldCompletedPostVar($subFieldIndex, $elemPostVar) - { - $fieldPostVar = "{$this->getPostVar()}[$subFieldIndex]"; - $elemPostVar = str_replace($this->getPostVar(), $fieldPostVar, $elemPostVar); - return $elemPostVar; - } - - public function prepareReprintable(assQuestion $question) - { - $this->setIdentifiedMultiValues( $this->getIdentifiedMultiValues() ); - } -} \ No newline at end of file + public function __construct($a_title = "", $a_postvar = "") + { + parent::__construct($a_title, $a_postvar); + + require_once 'Services/Form/classes/class.ilFormSubmitRecursiveSlashesStripper.php'; + $this->addFormValuesManipulator(new ilFormSubmitRecursiveSlashesStripper()); + + require_once 'Services/Form/classes/class.ilIdentifiedMultiValuesJsPositionIndexRemover.php'; + $this->addFormValuesManipulator(new ilIdentifiedMultiValuesJsPositionIndexRemover()); + + //$this->setMulti(true); // this is another planet, do not enable (!) + } + + public function getElementAddCmd() + { + return $this->elementAddCmd; + } + + /** + * @param string $elementAddCmd + */ + public function setElementAddCmd($elementAddCmd) + { + $this->elementAddCmd = $elementAddCmd; + } + + public function getElementRemoveCmd() + { + return $this->elementRemoveCmd; + } + + public function setElementRemoveCmd($elementRemoveCmd) + { + $this->elementRemoveCmd = $elementRemoveCmd; + } + + public function getElementMoveUpCommand() + { + return $this->elementMoveUpCommand; + } + + public function setElementMoveUpCommand($elementMoveUpCommand) + { + $this->elementMoveUpCommand = $elementMoveUpCommand; + } + + public function getElementMoveDownCommand() + { + return $this->elementMoveDownCommand; + } + + public function setElementMoveDownCommand($elementMoveDownCommand) + { + $this->elementMoveDownCommand = $elementMoveDownCommand; + } + + public function setValues($values) + { + require_once 'Services/Form/exceptions/class.ilFormException.php'; + throw new ilFormException('setter unsupported, use setIdentifiedMultiValues() instead!'); + } + + public function getValues() + { + require_once 'Services/Form/exceptions/class.ilFormException.php'; + throw new ilFormException('setter unsupported, use setIdentifiedMultiValues() instead!'); + } + + public function setValue($value) + { + require_once 'Services/Form/exceptions/class.ilFormException.php'; + throw new ilFormException('setter unsupported, use setIdentifiedMultiValues() instead!'); + } + + public function getValue() + { + require_once 'Services/Form/exceptions/class.ilFormException.php'; + throw new ilFormException('setter unsupported, use setIdentifiedMultiValues() instead!'); + } + + public function setMultiValues(array $values) + { + require_once 'Services/Form/exceptions/class.ilFormException.php'; + throw new ilFormException('setter unsupported, use setIdentifiedMultiValues() instead!'); + } + + public function getMultiValues() + { + require_once 'Services/Form/exceptions/class.ilFormException.php'; + throw new ilFormException('setter unsupported, use setIdentifiedMultiValues() instead!'); + } + + final public function setIdentifiedMultiValues($values) + { + $this->identified_multi_values = $this->prepareMultiValuesInput($values); + } + + final public function getIdentifiedMultiValues() + { + return $this->identified_multi_values; + } + + protected function getMultiValueSubFieldId($identifier, $subFieldIndex) + { + $tempPostVar = $this->getMultiValuePostVarSubField($identifier, $subFieldIndex); + $multiValueFieldId = $this->getFieldIdFromPostVar($tempPostVar); + + return $multiValueFieldId; + } + + protected function getMultiValuePosIndexedFieldId($identifier, $positionIndex) + { + $tempPostVar = $this->getMultiValuePostVarPosIndexed($identifier, $positionIndex); + $multiValueFieldId = $this->getFieldIdFromPostVar($tempPostVar); + + return $multiValueFieldId; + } + + protected function getMultiValuePosIndexedSubFieldId($identifier, $subFieldIndex, $positionIndex) + { + $tempPostVar = $this->getMultiValuePostVarSubFieldPosIndexed($identifier, $subFieldIndex, $positionIndex); + $multiValueFieldId = $this->getFieldIdFromPostVar($tempPostVar); + + return $multiValueFieldId; + } + + protected function getFieldIdFromPostVar($tempPostVar) + { + $basicPostVar = $this->getPostVar(); + $this->setPostVar($tempPostVar); + + // uses getPostVar() internally, our postvar does not have the counter included + $multiValueFieldId = $this->getFieldId(); + // now ALL brackets ("[", "]") are escaped, even the ones for the counter + + $this->setPostVar($basicPostVar); + return $multiValueFieldId; + } + + protected function getPostVarSubField($subFieldIndex) + { + return $this->getSubFieldCompletedPostVar($subFieldIndex, $this->getPostVar()); + } + + protected function getMultiValuePostVarSubField($identifier, $subFieldIndex) + { + $elemPostVar = $this->getMultiValuePostVar($identifier); + $elemPostVar = $this->getSubFieldCompletedPostVar($subFieldIndex, $elemPostVar); + + return $elemPostVar; + } + + protected function getMultiValuePostVarSubFieldPosIndexed($identifier, $subFieldIndex, $positionIndex) + { + $elemPostVar = $this->getMultiValuePostVarPosIndexed($identifier, $positionIndex); + $elemPostVar = $this->getSubFieldCompletedPostVar($subFieldIndex, $elemPostVar); + + return $elemPostVar; + } + + protected function getMultiValuePostVarPosIndexed($identifier, $positionIndex) + { + $elemPostVar = $this->getMultiValuePostVar($identifier); + $elemPostVar .= "[$positionIndex]"; + + return $elemPostVar; + } + + protected function getMultiValuePostVar($identifier) + { + $elemPostVar = $this->getPostVar(); + $elemPostVar .= "[$identifier]"; + return $elemPostVar; + } + + protected function buildMultiValueSubmitVar($identifier, $positionIndex, $submitCommand) + { + $elemSubmitVar = "cmd[{$submitCommand}][{$this->getFieldId()}]"; + $elemSubmitVar .= "[$identifier][$positionIndex]"; + + return $elemSubmitVar; + } + + final public function setValueByArray($a_values) + { + if (!is_array($a_values[$this->getPostVar()])) { + $a_values[$this->getPostVar()] = array(); + } + + $a_values[$this->getPostVar()] = $this->prepareMultiValuesSubmit( + $a_values[$this->getPostVar()] + ); + + $this->setIdentifiedMultiValuesByArray($a_values); + } + + protected function setIdentifiedMultiValuesByArray($a_values) + { + $this->identified_multi_values = $a_values[$this->getPostVar()]; + } + + final public function checkInput() + { + if (!is_array($_POST[$this->getPostVar()])) { + $_POST[$this->getPostVar()] = array(); + } + + $_POST[$this->getPostVar()] = $this->prepareMultiValuesSubmit( + $_POST[$this->getPostVar()] + ); + + return $this->onCheckInput(); + } + + abstract public function onCheckInput(); + + final protected function prepareMultiValuesInput($values) + { + foreach ($this->getFormValuesManipulators() as $manipulator) { + /* @var ilFormValuesManipulator $manipulator */ + $values = $manipulator->manipulateFormInputValues($values); + } + + return $values; + } + + final protected function prepareMultiValuesSubmit($values) + { + foreach ($this->getFormValuesManipulators() as $manipulator) { + /* @var ilFormValuesManipulator $manipulator */ + $values = $manipulator->manipulateFormSubmitValues($values); + } + + return $values; + } + + protected function getFormValuesManipulators() + { + return $this->formValuesManipulationChain; + } + + protected function addFormValuesManipulator(ilFormValuesManipulator $manipulator) + { + $this->formValuesManipulationChain[] = $manipulator; + } + + /** + * @param $subFieldIndex + * @param $elemPostVar + * @return mixed + */ + protected function getSubFieldCompletedPostVar($subFieldIndex, $elemPostVar) + { + $fieldPostVar = "{$this->getPostVar()}[$subFieldIndex]"; + $elemPostVar = str_replace($this->getPostVar(), $fieldPostVar, $elemPostVar); + return $elemPostVar; + } + + public function prepareReprintable(assQuestion $question) + { + $this->setIdentifiedMultiValues($this->getIdentifiedMultiValues()); + } +} diff --git a/Services/Form/classes/class.ilIdentifiedMultiValuesJsPositionIndexRemover.php b/Services/Form/classes/class.ilIdentifiedMultiValuesJsPositionIndexRemover.php index c6c91e8ecf5750cdf1543c895efd2d478ae35753..e603b01196fd868c30c33a6311275ead8618b0de 100644 --- a/Services/Form/classes/class.ilIdentifiedMultiValuesJsPositionIndexRemover.php +++ b/Services/Form/classes/class.ilIdentifiedMultiValuesJsPositionIndexRemover.php @@ -11,123 +11,111 @@ require_once 'Services/Form/interfaces/interface.ilFormValuesManipulator.php'; */ class ilIdentifiedMultiValuesJsPositionIndexRemover implements ilFormValuesManipulator { - const IDENTIFIER_INDICATOR_PREFIX = 'IDENTIFIER~'; - - public function manipulateFormInputValues($inputValues) - { - return $this->brandIdentifiersWithIndicator($inputValues); - } - - protected function brandIdentifiersWithIndicator($origValues) - { - $brandedValues = array(); - - foreach($origValues as $identifier => $val) - { - $brandedValues[$this->getIndicatorBrandedIdentifier($identifier)] = $val; - } + const IDENTIFIER_INDICATOR_PREFIX = 'IDENTIFIER~'; + + public function manipulateFormInputValues($inputValues) + { + return $this->brandIdentifiersWithIndicator($inputValues); + } + + protected function brandIdentifiersWithIndicator($origValues) + { + $brandedValues = array(); + + foreach ($origValues as $identifier => $val) { + $brandedValues[$this->getIndicatorBrandedIdentifier($identifier)] = $val; + } - return $brandedValues; - } - - protected function getIndicatorBrandedIdentifier($identifier) - { - return self::IDENTIFIER_INDICATOR_PREFIX . $identifier; - } - - public function manipulateFormSubmitValues($submitValues) - { - $_POST['cmd'] = $this->cleanSubmitCommandFromPossibleIdentifierIndicators($_POST['cmd']); - return $this->removePositionIndexLevels($submitValues); - } - - protected function cleanSubmitCommandFromPossibleIdentifierIndicators($cmdArrayLevel) - { - if( is_array($cmdArrayLevel) ) - { - $currentKey = key($cmdArrayLevel); - $nextLevel = current($cmdArrayLevel); - - $nextLevel = $this->cleanSubmitCommandFromPossibleIdentifierIndicators($nextLevel); - - unset($cmdArrayLevel[$currentKey]); - - if( $this->isValueIdentifier($currentKey) ) - { - $currentKey = $this->removeIdentifierIndicator($currentKey); - } - - $cmdArrayLevel[$currentKey] = $nextLevel; - } - - return $cmdArrayLevel; - } - - protected function removePositionIndexLevels($values) - { - foreach($values as $key => $val) - { - unset($values[$key]); - - if( $this->isValueIdentifier($key) ) - { - $key = $this->removeIdentifierIndicator($key); - - if( $this->isPositionIndexLevel($val) ) - { - $val = $this->fetchPositionIndexedValue($val); - } - } - elseif( is_array($val) ) - { - $val = $this->removePositionIndexLevels($val); - } - - $values[$key] = $val; - } - - return $values; - } - - protected function isPositionIndexLevel($val) - { - if( !is_array($val) ) - { - return false; - } - - if( count($val) != 1 ) - { - return false; - } - - return true; - } - - protected function isValueIdentifier($key) - { - $indicatorPrefixLength = self::IDENTIFIER_INDICATOR_PREFIX; - - if( strlen($key) <= strlen($indicatorPrefixLength) ) - { - return false; - } - - if( substr($key, 0, strlen($indicatorPrefixLength)) != $indicatorPrefixLength ) - { - return false; - } - - return true; - } - - protected function removeIdentifierIndicator($key) - { - return str_replace(self::IDENTIFIER_INDICATOR_PREFIX, '', $key); - } - - protected function fetchPositionIndexedValue($value) - { - return current($value); - } -} \ No newline at end of file + return $brandedValues; + } + + protected function getIndicatorBrandedIdentifier($identifier) + { + return self::IDENTIFIER_INDICATOR_PREFIX . $identifier; + } + + public function manipulateFormSubmitValues($submitValues) + { + $_POST['cmd'] = $this->cleanSubmitCommandFromPossibleIdentifierIndicators($_POST['cmd']); + return $this->removePositionIndexLevels($submitValues); + } + + protected function cleanSubmitCommandFromPossibleIdentifierIndicators($cmdArrayLevel) + { + if (is_array($cmdArrayLevel)) { + $currentKey = key($cmdArrayLevel); + $nextLevel = current($cmdArrayLevel); + + $nextLevel = $this->cleanSubmitCommandFromPossibleIdentifierIndicators($nextLevel); + + unset($cmdArrayLevel[$currentKey]); + + if ($this->isValueIdentifier($currentKey)) { + $currentKey = $this->removeIdentifierIndicator($currentKey); + } + + $cmdArrayLevel[$currentKey] = $nextLevel; + } + + return $cmdArrayLevel; + } + + protected function removePositionIndexLevels($values) + { + foreach ($values as $key => $val) { + unset($values[$key]); + + if ($this->isValueIdentifier($key)) { + $key = $this->removeIdentifierIndicator($key); + + if ($this->isPositionIndexLevel($val)) { + $val = $this->fetchPositionIndexedValue($val); + } + } elseif (is_array($val)) { + $val = $this->removePositionIndexLevels($val); + } + + $values[$key] = $val; + } + + return $values; + } + + protected function isPositionIndexLevel($val) + { + if (!is_array($val)) { + return false; + } + + if (count($val) != 1) { + return false; + } + + return true; + } + + protected function isValueIdentifier($key) + { + $indicatorPrefixLength = self::IDENTIFIER_INDICATOR_PREFIX; + + if (strlen($key) <= strlen($indicatorPrefixLength)) { + return false; + } + + if (substr($key, 0, strlen($indicatorPrefixLength)) != $indicatorPrefixLength) { + return false; + } + + return true; + } + + protected function removeIdentifierIndicator($key) + { + return str_replace(self::IDENTIFIER_INDICATOR_PREFIX, '', $key); + } + + protected function fetchPositionIndexedValue($value) + { + return current($value); + } +} diff --git a/Services/Form/classes/class.ilImageFileInputGUI.php b/Services/Form/classes/class.ilImageFileInputGUI.php index aa720d7ce6313ce2dfe9ed22f7f47157d31bd9f9..b78d2be8d6204fc72f07c82e12462dfb0eb4ae1f 100755 --- a/Services/Form/classes/class.ilImageFileInputGUI.php +++ b/Services/Form/classes/class.ilImageFileInputGUI.php @@ -4,231 +4,214 @@ /** * This class represents an image file property in a property form. * -* @author Alex Killing +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilImageFileInputGUI extends ilFileInputGUI { - protected $cache; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + protected $cache; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - $lng = $DIC->language(); + $this->lng = $DIC->language(); + $lng = $DIC->language(); - parent::__construct($a_title, $a_postvar); - $this->setType("image_file"); - $this->setAllowDeletion(true); - $this->setSuffixes(array("jpg", "jpeg", "png", "gif")); - $this->setHiddenTitle("(".$lng->txt("form_image_file_input").")"); - $this->cache = true; - } + parent::__construct($a_title, $a_postvar); + $this->setType("image_file"); + $this->setAllowDeletion(true); + $this->setSuffixes(array("jpg", "jpeg", "png", "gif")); + $this->setHiddenTitle("(" . $lng->txt("form_image_file_input") . ")"); + $this->cache = true; + } - /** - * Set allow deletion - * - * @param boolean $a_val allow deletion - */ - function setALlowDeletion($a_val) - { - $this->allow_deletion = $a_val; - } - - /** - * Get allow deletion - * - * @return boolean allow deletion - */ - function getALlowDeletion() - { - return $this->allow_deletion; - } - /** - * Set cache - * - * @param boolean $a_cache If false, the image will be forced to reload in the browser - * by adding an URL parameter with the actual timestamp - */ - public function setUseCache($a_cache) - { - $this->cache = ($a_cache) ? true : false; - } - - /** - * Get cache - * - * @return boolean - */ - public function getUseCache() - { - return $this->cache; - } + /** + * Set allow deletion + * + * @param boolean $a_val allow deletion + */ + public function setALlowDeletion($a_val) + { + $this->allow_deletion = $a_val; + } + + /** + * Get allow deletion + * + * @return boolean allow deletion + */ + public function getALlowDeletion() + { + return $this->allow_deletion; + } + /** + * Set cache + * + * @param boolean $a_cache If false, the image will be forced to reload in the browser + * by adding an URL parameter with the actual timestamp + */ + public function setUseCache($a_cache) + { + $this->cache = ($a_cache) ? true : false; + } + + /** + * Get cache + * + * @return boolean + */ + public function getUseCache() + { + return $this->cache; + } - /** - * Set Image. - * - * @param string $a_image Image - */ - function setImage($a_image) - { - $this->image = $a_image; - } + /** + * Set Image. + * + * @param string $a_image Image + */ + public function setImage($a_image) + { + $this->image = $a_image; + } - /** - * Get Image. - * - * @return string Image - */ - function getImage() - { - return $this->image; - } + /** + * Get Image. + * + * @return string Image + */ + public function getImage() + { + return $this->image; + } - /** - * Set Alternative Text. - * - * @param string $a_alt Alternative Text - */ - function setAlt($a_alt) - { - $this->alt = $a_alt; - } + /** + * Set Alternative Text. + * + * @param string $a_alt Alternative Text + */ + public function setAlt($a_alt) + { + $this->alt = $a_alt; + } - /** - * Get Alternative Text. - * - * @return string Alternative Text - */ - function getAlt() - { - return $this->alt; - } + /** + * Get Alternative Text. + * + * @return string Alternative Text + */ + public function getAlt() + { + return $this->alt; + } - /** - * Insert property html - */ - function insert($a_tpl) - { - $lng = $this->lng; - - $quota_exceeded = $quota_legend = false; - if(self::$check_wsp_quota) - { - include_once "Services/DiskQuota/classes/class.ilDiskQuotaHandler.php"; - if(!ilDiskQuotaHandler::isUploadPossible()) - { - $lng->loadLanguageModule("file"); - $quota_exceeded = $lng->txt("personal_workspace_quota_exceeded_warning"); - } - else - { - $quota_legend = ilDiskQuotaHandler::getStatusLegend(); - if($quota_legend) - { - $quota_legend = "
                  ".$quota_legend; - } - } - } - - $i_tpl = new ilTemplate("tpl.prop_image_file.html", true, true, "Services/Form"); - - if ($this->getImage() != "") - { - if (!$this->getDisabled() && $this->getALlowDeletion()) - { - $i_tpl->setCurrentBlock("delete_bl"); - $i_tpl->setVariable("POST_VAR_D", $this->getPostVar()); - $i_tpl->setVariable("TXT_DELETE_EXISTING", - $lng->txt("delete_existing_file")); - $i_tpl->parseCurrentBlock(); - } - - if (strlen($this->getValue())) - { - $i_tpl->setCurrentBlock("has_value"); - $i_tpl->setVariable("TEXT_IMAGE_NAME", $this->getValue()); - $i_tpl->parseCurrentBlock(); - } - $i_tpl->setCurrentBlock("image"); - if (!$this->getUseCache()) - { - $pos = strpos($this->getImage(), '?'); - if ($pos !== false) - { - $i_tpl->setVariable("SRC_IMAGE", $this->getImage() . "&time=" . time()); - } - else - { - $i_tpl->setVariable("SRC_IMAGE", $this->getImage() . "?time=" . time()); - } - } - else - { - $i_tpl->setVariable("SRC_IMAGE", $this->getImage()); - } - $i_tpl->setVariable("ALT_IMAGE", $this->getAlt()); - $i_tpl->parseCurrentBlock(); - } - - $pending = $this->getPending(); - if($pending) - { - $i_tpl->setCurrentBlock("pending"); - $i_tpl->setVariable("TXT_PENDING", $lng->txt("file_upload_pending"). - ": ".$pending); - $i_tpl->parseCurrentBlock(); - } - - $i_tpl->setVariable("POST_VAR", $this->getPostVar()); - $i_tpl->setVariable("ID", $this->getFieldId()); - - - /* experimental: bootstrap'ed file upload */ - $i_tpl->setVariable("TXT_BROWSE", $lng->txt("select_file")); - - - if(!$quota_exceeded) - { - $i_tpl->setVariable("TXT_MAX_SIZE", $lng->txt("file_notice")." ". - $this->getMaxFileSizeString().$quota_legend); - - $this->outputSuffixes($i_tpl, "allowed_image_suffixes"); - } - else - { - $i_tpl->setVariable("TXT_MAX_SIZE", $quota_exceeded); - } - - if ($this->getDisabled() || $quota_exceeded) - { - $i_tpl->setVariable("DISABLED", - " disabled=\"disabled\""); - } - - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $i_tpl->get()); - $a_tpl->parseCurrentBlock(); - } - - /** - * Get deletion flag - */ - function getDeletionFlag() - { - if ($_POST[$this->getPostVar()."_delete"]) - { - return true; - } - return false; - } + /** + * Insert property html + */ + public function insert($a_tpl) + { + $lng = $this->lng; + + $quota_exceeded = $quota_legend = false; + if (self::$check_wsp_quota) { + include_once "Services/DiskQuota/classes/class.ilDiskQuotaHandler.php"; + if (!ilDiskQuotaHandler::isUploadPossible()) { + $lng->loadLanguageModule("file"); + $quota_exceeded = $lng->txt("personal_workspace_quota_exceeded_warning"); + } else { + $quota_legend = ilDiskQuotaHandler::getStatusLegend(); + if ($quota_legend) { + $quota_legend = "
                  " . $quota_legend; + } + } + } + + $i_tpl = new ilTemplate("tpl.prop_image_file.html", true, true, "Services/Form"); + + if ($this->getImage() != "") { + if (!$this->getDisabled() && $this->getALlowDeletion()) { + $i_tpl->setCurrentBlock("delete_bl"); + $i_tpl->setVariable("POST_VAR_D", $this->getPostVar()); + $i_tpl->setVariable( + "TXT_DELETE_EXISTING", + $lng->txt("delete_existing_file") + ); + $i_tpl->parseCurrentBlock(); + } + + if (strlen($this->getValue())) { + $i_tpl->setCurrentBlock("has_value"); + $i_tpl->setVariable("TEXT_IMAGE_NAME", $this->getValue()); + $i_tpl->parseCurrentBlock(); + } + $i_tpl->setCurrentBlock("image"); + if (!$this->getUseCache()) { + $pos = strpos($this->getImage(), '?'); + if ($pos !== false) { + $i_tpl->setVariable("SRC_IMAGE", $this->getImage() . "&time=" . time()); + } else { + $i_tpl->setVariable("SRC_IMAGE", $this->getImage() . "?time=" . time()); + } + } else { + $i_tpl->setVariable("SRC_IMAGE", $this->getImage()); + } + $i_tpl->setVariable("ALT_IMAGE", $this->getAlt()); + $i_tpl->parseCurrentBlock(); + } + + $pending = $this->getPending(); + if ($pending) { + $i_tpl->setCurrentBlock("pending"); + $i_tpl->setVariable("TXT_PENDING", $lng->txt("file_upload_pending") . + ": " . $pending); + $i_tpl->parseCurrentBlock(); + } + + $i_tpl->setVariable("POST_VAR", $this->getPostVar()); + $i_tpl->setVariable("ID", $this->getFieldId()); + + + /* experimental: bootstrap'ed file upload */ + $i_tpl->setVariable("TXT_BROWSE", $lng->txt("select_file")); + + + if (!$quota_exceeded) { + $i_tpl->setVariable("TXT_MAX_SIZE", $lng->txt("file_notice") . " " . + $this->getMaxFileSizeString() . $quota_legend); + + $this->outputSuffixes($i_tpl, "allowed_image_suffixes"); + } else { + $i_tpl->setVariable("TXT_MAX_SIZE", $quota_exceeded); + } + + if ($this->getDisabled() || $quota_exceeded) { + $i_tpl->setVariable( + "DISABLED", + " disabled=\"disabled\"" + ); + } + + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $i_tpl->get()); + $a_tpl->parseCurrentBlock(); + } + /** + * Get deletion flag + */ + public function getDeletionFlag() + { + if ($_POST[$this->getPostVar() . "_delete"]) { + return true; + } + return false; + } } diff --git a/Services/Form/classes/class.ilLinkInputGUI.php b/Services/Form/classes/class.ilLinkInputGUI.php index 4ab4a4fbc71f71065009c8cb9155e10eced1ffc8..0fba2c6c5719903ab4db8d5bf6c7aef019f010ab 100644 --- a/Services/Form/classes/class.ilLinkInputGUI.php +++ b/Services/Form/classes/class.ilLinkInputGUI.php @@ -1,663 +1,602 @@ - -* @version $Id$ -* -* @ilCtrl_IsCalledBy ilLinkInputGUI: ilFormPropertyDispatchGUI -* @ilCtrl_Calls ilLinkInputGUI: ilInternalLinkGUI -* -* @ingroup ServicesForm -*/ -class ilLinkInputGUI extends ilFormPropertyGUI -{ - const EXTERNAL_LINK_MAX_LENGTH = 200; - - const BOTH = "both"; - const INT = "int"; - const EXT = "ext"; - protected $allowed_link_types = self::BOTH; - protected $int_link_default_type = "RepositoryItem"; - protected $int_link_default_obj = 0; - protected $int_link_filter_types = array("RepositoryItem"); - protected $filter_white_list = true; - - protected $external_link_max_length = self::EXTERNAL_LINK_MAX_LENGTH; - - static protected $iltypemap = array( - "page" => "PageObject", - "chap" => "StructureObject", - "term" => "GlossaryItem", - "wpage" => "WikiPage" - ); - - /** - * @var ilObjectDefinition - */ - protected $obj_definition; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - - parent::__construct($a_title, $a_postvar); - $this->setType("link"); - - $this->obj_definition = $DIC["objDefinition"]; - } - - /** - * Set allowed link types (BOTH, INT, EXT) - * - * @param string $a_val self::BOTH|self::INT|self::EXT - */ - function setAllowedLinkTypes($a_val) - { - $this->allowed_link_types = $a_val; - } - - /** - * Get allowed link types (BOTH, INT, EXT) - * - * @return string self::BOTH|self::INT|self::EXT - */ - function getAllowedLinkTypes() - { - return $this->allowed_link_types; - } - - /** - * Set internal link default - * - * @param string $a_type link type - * @param int $a_obj object id - */ - function setInternalLinkDefault($a_type, $a_obj = 0) - { - $this->int_link_default_type = $a_type; - $this->int_link_default_obj = $a_obj; - } - - /** - * Set internal link filter types - * - * @param array $a_val filter types - */ - function setInternalLinkFilterTypes(array $a_val) - { - $this->int_link_filter_types = $a_val; - } - - /** - * Get internal types to xml attribute types map - * - * @return string[] - */ - static function getTypeToAttrType() - { - return self::$iltypemap; - } - - /** - * Get internal types to xml attribute types map (reverse) - * - * @return string[] - */ - static function getAttrTypeToType() - { - return array_flip(self::$iltypemap); - } - - /** - * Set filter white list - * - * @param bool $a_val filter list is white list - */ - function setFilterWhiteList($a_val) - { - $this->filter_white_list = $a_val; - } - - /** - * Get filter white list - * - * @return bool filter list is white list - */ - function getFilterWhiteList() - { - return $this->filter_white_list; - } - - /** - * @param int max length for external links - */ - public function setExternalLinkMaxLength($a_max) - { - $this->external_link_max_length = $a_max; - } - - /** - * @return int - */ - public function getExternalLinkMaxLength() - { - return $this->external_link_max_length; - } - - /** - * Execute current command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd(); - - switch($next_class) - { - case "ilinternallinkgui": - $lng->loadLanguageModule("content"); - require_once("./Services/Link/classes/class.ilInternalLinkGUI.php"); - $link_gui = new ilInternalLinkGUI($this->int_link_default_type, - $this->int_link_default_obj); - foreach ($this->int_link_filter_types as $t) - { - $link_gui->filterLinkType($t); - } - $link_gui->setFilterWhiteList($this->getFilterWhiteList()); - $link_gui->setMode("asynch"); - - $ret = $ilCtrl->forwardCommand($link_gui); - break; - - default: - var_dump($cmd); - //exit(); - } - - return $ret; - } - - /** - * Set Value. - * - * @param string $a_value Value - */ - function setValue($a_value) - { - $this->value = $a_value; - } - - /** - * Get Value. - * - * @return string Value - */ - function getValue() - { - return $this->value; - } - - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - switch($a_values[$this->getPostVar()."_mode"]) - { - case "int": - if($a_values[$this->getPostVar()."_ajax_type"] && - $a_values[$this->getPostVar()."_ajax_id"]) - { - $val = $a_values[$this->getPostVar()."_ajax_type"]."|". - $a_values[$this->getPostVar()."_ajax_id"]; - if ($a_values[$this->getPostVar()."_ajax_target"] != "") - { - $val.= "|".$a_values[$this->getPostVar()."_ajax_target"]; - } - $this->setValue($val); - } - break; - - case "no": - break; - - default: - if($a_values[$this->getPostVar()]) - { - $this->setValue($a_values[$this->getPostVar()]); - } - break; - } - } - - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - // debugging - // return false; - - if($this->getRequired()) - { - switch($_POST[$this->getPostVar()."_mode"]) - { - case "ext": - if(!$_POST[$this->getPostVar()]) - { - $this->setAlert($lng->txt("msg_input_is_required")); - return false; - } - break; - - case "int": - if(!$_POST[$this->getPostVar()."_ajax_type"] || - !$_POST[$this->getPostVar()."_ajax_id"]) - { - $this->setAlert($lng->txt("msg_input_is_required")); - return false; - } - break; - - case "no": - default: - $this->setAlert($lng->txt("msg_input_is_required")); - return false; - } - } - - if($_POST[$this->getPostVar()."_mode"] == "int") - { - $_POST[$this->getPostVar()."_ajax_type"] = ilUtil::stripSlashes($_POST[$this->getPostVar()."_ajax_type"]); - $_POST[$this->getPostVar()."_ajax_id"] = ilUtil::stripSlashes($_POST[$this->getPostVar()."_ajax_id"]); - $_POST[$this->getPostVar()."_ajax_target"] = ilUtil::stripSlashes($_POST[$this->getPostVar()."_ajax_target"]); - - // overwriting post-data so getInput() will work - $val = $_POST[$this->getPostVar()."_ajax_type"]."|". - $_POST[$this->getPostVar()."_ajax_id"]; - if ($_POST[$this->getPostVar()."_ajax_target"] != "") - { - $val.= "|".$_POST[$this->getPostVar()."_ajax_target"]; - } - - $_POST[$this->getPostVar()] = $val; - } - else if($_POST[$this->getPostVar()."_mode"] == "no") - { - $_POST[$this->getPostVar()] = ""; - } - else - { - $_POST[$this->getPostVar()] = ilUtil::stripSlashes($_POST[$this->getPostVar()]); - } - - return true; - } - - /** - * Render item - */ - function render() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - // parse settings - $has_int = $has_ext = $has_radio = false; - switch($this->getAllowedLinkTypes()) - { - case self::EXT: - $has_ext = true; - break; - - case self::INT: - $has_int = true; - break; - - case self::BOTH: - $has_int = true; - $has_ext = true; - $has_radio = true; - break; - } - if (!$this->getRequired()) - { - // see #0021274 -// $has_radio = true; - } - - // external - if($has_ext) - { - $title = $has_radio ? $lng->txt("url") : ""; - - // external - $ti = new ilTextInputGUI($title, $this->getPostVar()); - $ti->setMaxLength($this->getExternalLinkMaxLength()); - } - - // internal - if($has_int) - { - $ilCtrl->setParameterByClass("ilformpropertydispatchgui", "postvar", $this->getPostVar()); - $link = array(get_class($this->getParent()), "ilformpropertydispatchgui", get_class($this), "ilinternallinkgui"); - $link = $ilCtrl->getLinkTargetByClass($link, "", false, true, false); - $ilCtrl->setParameterByClass("ilformpropertydispatchgui", "postvar", $_REQUEST["postvar"]); - - $no_disp_class = (strpos($this->getValue(), "|")) - ? "" - : " ilNoDisplay"; - - $itpl = new ilTemplate('tpl.prop_link.html',true,true,'Services/Form'); - $itpl->setVariable("VAL_ID", $this->getPostVar()); - $itpl->setVariable("URL_EDIT", $link); - $itpl->setVariable("TXT_EDIT", $lng->txt("form_get_link")); - $itpl->setVariable("CSS_REMOVE", $no_disp_class); - $itpl->setVariable("TXT_REMOVE", $lng->txt("remove")); - - $ne = new ilNonEditableValueGUI($lng->txt("object"), $this->getPostVar()."_val", true); - - // hidden field for selected value - $hidden_type = new ilHiddenInputGUI($this->getPostVar()."_ajax_type"); - $hidden_id = new ilHiddenInputGUI($this->getPostVar()."_ajax_id"); - $hidden_target = new ilHiddenInputGUI($this->getPostVar()."_ajax_target"); - } - - // mode - if ($has_radio) - { - $ext = new ilRadioOption($lng->txt("form_link_external"), "ext"); - $ext->addSubItem($ti); - - $int = new ilRadioOption($lng->txt("form_link_internal"), "int"); - $int->addSubItem($ne); - - $mode = new ilRadioGroupInputGUI("", $this->getPostVar()."_mode"); - if (!$this->getRequired()) - { - $no = new ilRadioOption($lng->txt("form_no_link"), "no"); - $mode->addOption($no); - } - $mode->addOption($ext); - $mode->addOption($int); - } - else - { - $mode = new ilHiddenInputGUI($this->getPostVar()."_mode"); - if ($has_int) - { - $mode->setValue("int"); - } - else - { - $mode->setValue("ext"); - } - } - - // value - $value = $this->getValue(); - if($value) - { - // #15647 - if($has_int && self::isInternalLink($value)) - { - $mode->setValue("int"); - - $value_trans = self::getTranslatedValue($value); - - $value = explode("|", $value); - $hidden_type->setValue($value[0]); - $hidden_id->setValue($value[1]); - $hidden_target->setValue($value[2]); - - $itpl->setVariable("VAL_OBJECT_TYPE", $value_trans["type"]); - $itpl->setVariable("VAL_OBJECT_NAME", $value_trans["name"]); - if ($value[2] != "") - { - $itpl->setVariable("VAL_TARGET_FRAME", "(" . $value[2].")"); - } - } - else if($has_ext) - { - $mode->setValue("ext"); - - $ti->setValue($value); - } - } - else if (!$this->getRequired()) - { - $mode->setValue("no"); - } - - // #10185 - default for external urls - if($has_ext && !$ti->getValue()) - { - $ti->setValue("http://"); - } - - $ne->setValue($itpl->get()); - - // to html - if ($has_radio) - { - $html = $mode->render(); - } - else - { - $html = $mode->getToolbarHTML(); - - if ($has_ext) - { - $html.= $ti->getToolbarHTML(); - } - else - { - $html.= $ne->render(). - '
                  '.$ne->getInfo().'
                  '; - } - } - - // js for internal link - if($has_int) - { - include_once("./Services/Link/classes/class.ilInternalLinkGUI.php"); - $html.= $hidden_type->getToolbarHTML(). - $hidden_id->getToolbarHTML(). - $hidden_target->getToolbarHTML(); - } - - return $html; - } - - public function getContentOutsideFormTag() - { - if($this->getAllowedLinkTypes() == self::INT || - $this->getAllowedLinkTypes() == self::BOTH) - { - // as the ajax-panel uses a form it has to be outside of the parent form! - return ilInternalLinkGUI::getInitHTML(""); - } - } - - public static function isInternalLink($a_value) - { - if(strpos($a_value, "|")) - { - $parts = explode("|", $a_value); - if(sizeof($parts) == 2 || sizeof($parts) == 3) - { - // numeric id - if(is_numeric($parts[1])) - { - // simple type - if(preg_match("/^[a-zA-Z_]+$/", $parts[0], $matches)) - { - return true; - } - } - } - } - return false; - } - - public static function getTranslatedValue($a_value) - { - global $DIC; - - $lng = $DIC->language(); - - $value = explode("|", $a_value); - - switch($value[0]) - { - case "media": - $type = $lng->txt("obj_mob"); - $name = ilObject::_lookupTitle($value[1]); - break; - - case "page": - include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); - $type = $lng->txt("obj_pg"); - $name = ilLMPageObject::_lookupTitle($value[1]); - break; - - case "chap": - include_once("./Modules/LearningModule/classes/class.ilStructureObject.php"); - $type = $lng->txt("obj_st"); - $name = ilStructureObject::_lookupTitle($value[1]); - break; - - case "term": - include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - $type = $lng->txt("term"); - $name = ilGlossaryTerm::_lookGlossaryTerm($value[1]); - break; - - default: - $type = $lng->txt("obj_".$value[0]); - $name = ilObject::_lookupTitle(ilObject::_lookupObjId($value[1])); - break; - } - - return array("type"=>$type, "name"=>$name); - } - - /** - * Insert property html - * - * @return int Size - */ - function insert($a_tpl) - { - $html = $this->render(); - - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $html); - $a_tpl->parseCurrentBlock(); - } - - /** - * Get value as internal link attributes - * - * @return array (with keys "Type", "Target" and "TargetFrame") - */ - function getIntLinkAttributes() - { - $val = explode("|", $_POST[$this->getPostVar()]); - - $ret = false; - $type = ""; - $target = ""; - if (self::isInternalLink($_POST[$this->getPostVar()])) - { - $target_frame = $val[2]; - $map = self::getTypeToAttrType(); - if (isset($map[$val[0]])) - { - $type = $map[$val[0]]; - $target_type = $val[0]; - if ($val[0] == "chap") - { - $target_type = "st"; - } - if ($val[0] == "term") - { - $target_type = "git"; - } - if ($val[0] == "page") - { - $target_type = "pg"; - } - $target = "il__".$target_type."_".$val[1]; - } - else if ($this->obj_definition->isRBACObject($val[0])) - { - $type = "RepositoryItem"; - $target = "il__obj_".$val[1]; - } - if ($type != "") - { - $ret = array( - "Target" => $target, - "Type" => $type, - "TargetFrame" => $target_frame - ); - } - } - return $ret; - } - - /** - * Set value by internal links attributes - * - * @param - * @return - */ - function setValueByIntLinkAttributes($a_type, $a_target, $a_target_frame = "") - { - $t = explode("_", $a_target); - $target_id = $t[3]; - $type = ""; - $map = self::getAttrTypeToType(); - if ($a_type == "RepositoryItem") - { - $type = ilObject::_lookupType($target_id, true); - } - else if (isset($map[$a_type])) - { - $type = $map[$a_type]; - } - if ($type != "" && $target_id != "") - { - $val = $type."|".$target_id; - if ($a_target_frame != "") - { - $val.= "|".$a_target_frame; - } - $this->setValue($val); - } - } - - -} + +* @version $Id$ +* +* @ilCtrl_IsCalledBy ilLinkInputGUI: ilFormPropertyDispatchGUI +* @ilCtrl_Calls ilLinkInputGUI: ilInternalLinkGUI +* +* @ingroup ServicesForm +*/ +class ilLinkInputGUI extends ilFormPropertyGUI +{ + const EXTERNAL_LINK_MAX_LENGTH = 200; + + const BOTH = "both"; + const INT = "int"; + const EXT = "ext"; + protected $allowed_link_types = self::BOTH; + protected $int_link_default_type = "RepositoryItem"; + protected $int_link_default_obj = 0; + protected $int_link_filter_types = array("RepositoryItem"); + protected $filter_white_list = true; + + protected $external_link_max_length = self::EXTERNAL_LINK_MAX_LENGTH; + + protected static $iltypemap = array( + "page" => "PageObject", + "chap" => "StructureObject", + "term" => "GlossaryItem", + "wpage" => "WikiPage" + ); + + /** + * @var ilObjectDefinition + */ + protected $obj_definition; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + + parent::__construct($a_title, $a_postvar); + $this->setType("link"); + + $this->obj_definition = $DIC["objDefinition"]; + } + + /** + * Set allowed link types (BOTH, INT, EXT) + * + * @param string $a_val self::BOTH|self::INT|self::EXT + */ + public function setAllowedLinkTypes($a_val) + { + $this->allowed_link_types = $a_val; + } + + /** + * Get allowed link types (BOTH, INT, EXT) + * + * @return string self::BOTH|self::INT|self::EXT + */ + public function getAllowedLinkTypes() + { + return $this->allowed_link_types; + } + + /** + * Set internal link default + * + * @param string $a_type link type + * @param int $a_obj object id + */ + public function setInternalLinkDefault($a_type, $a_obj = 0) + { + $this->int_link_default_type = $a_type; + $this->int_link_default_obj = $a_obj; + } + + /** + * Set internal link filter types + * + * @param array $a_val filter types + */ + public function setInternalLinkFilterTypes(array $a_val) + { + $this->int_link_filter_types = $a_val; + } + + /** + * Get internal types to xml attribute types map + * + * @return string[] + */ + public static function getTypeToAttrType() + { + return self::$iltypemap; + } + + /** + * Get internal types to xml attribute types map (reverse) + * + * @return string[] + */ + public static function getAttrTypeToType() + { + return array_flip(self::$iltypemap); + } + + /** + * Set filter white list + * + * @param bool $a_val filter list is white list + */ + public function setFilterWhiteList($a_val) + { + $this->filter_white_list = $a_val; + } + + /** + * Get filter white list + * + * @return bool filter list is white list + */ + public function getFilterWhiteList() + { + return $this->filter_white_list; + } + + /** + * @param int max length for external links + */ + public function setExternalLinkMaxLength($a_max) + { + $this->external_link_max_length = $a_max; + } + + /** + * @return int + */ + public function getExternalLinkMaxLength() + { + return $this->external_link_max_length; + } + + /** + * Execute current command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd(); + + switch ($next_class) { + case "ilinternallinkgui": + $lng->loadLanguageModule("content"); + require_once("./Services/Link/classes/class.ilInternalLinkGUI.php"); + $link_gui = new ilInternalLinkGUI( + $this->int_link_default_type, + $this->int_link_default_obj + ); + foreach ($this->int_link_filter_types as $t) { + $link_gui->filterLinkType($t); + } + $link_gui->setFilterWhiteList($this->getFilterWhiteList()); + $link_gui->setMode("asynch"); + + $ret = $ilCtrl->forwardCommand($link_gui); + break; + + default: + var_dump($cmd); + //exit(); + } + + return $ret; + } + + /** + * Set Value. + * + * @param string $a_value Value + */ + public function setValue($a_value) + { + $this->value = $a_value; + } + + /** + * Get Value. + * + * @return string Value + */ + public function getValue() + { + return $this->value; + } + + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + switch ($a_values[$this->getPostVar() . "_mode"]) { + case "int": + if ($a_values[$this->getPostVar() . "_ajax_type"] && + $a_values[$this->getPostVar() . "_ajax_id"]) { + $val = $a_values[$this->getPostVar() . "_ajax_type"] . "|" . + $a_values[$this->getPostVar() . "_ajax_id"]; + if ($a_values[$this->getPostVar() . "_ajax_target"] != "") { + $val.= "|" . $a_values[$this->getPostVar() . "_ajax_target"]; + } + $this->setValue($val); + } + break; + + case "no": + break; + + default: + if ($a_values[$this->getPostVar()]) { + $this->setValue($a_values[$this->getPostVar()]); + } + break; + } + } + + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + // debugging + // return false; + + if ($this->getRequired()) { + switch ($_POST[$this->getPostVar() . "_mode"]) { + case "ext": + if (!$_POST[$this->getPostVar()]) { + $this->setAlert($lng->txt("msg_input_is_required")); + return false; + } + break; + + case "int": + if (!$_POST[$this->getPostVar() . "_ajax_type"] || + !$_POST[$this->getPostVar() . "_ajax_id"]) { + $this->setAlert($lng->txt("msg_input_is_required")); + return false; + } + break; + + case "no": + default: + $this->setAlert($lng->txt("msg_input_is_required")); + return false; + } + } + + if ($_POST[$this->getPostVar() . "_mode"] == "int") { + $_POST[$this->getPostVar() . "_ajax_type"] = ilUtil::stripSlashes($_POST[$this->getPostVar() . "_ajax_type"]); + $_POST[$this->getPostVar() . "_ajax_id"] = ilUtil::stripSlashes($_POST[$this->getPostVar() . "_ajax_id"]); + $_POST[$this->getPostVar() . "_ajax_target"] = ilUtil::stripSlashes($_POST[$this->getPostVar() . "_ajax_target"]); + + // overwriting post-data so getInput() will work + $val = $_POST[$this->getPostVar() . "_ajax_type"] . "|" . + $_POST[$this->getPostVar() . "_ajax_id"]; + if ($_POST[$this->getPostVar() . "_ajax_target"] != "") { + $val.= "|" . $_POST[$this->getPostVar() . "_ajax_target"]; + } + + $_POST[$this->getPostVar()] = $val; + } elseif ($_POST[$this->getPostVar() . "_mode"] == "no") { + $_POST[$this->getPostVar()] = ""; + } else { + $_POST[$this->getPostVar()] = ilUtil::stripSlashes($_POST[$this->getPostVar()]); + } + + return true; + } + + /** + * Render item + */ + public function render() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + // parse settings + $has_int = $has_ext = $has_radio = false; + switch ($this->getAllowedLinkTypes()) { + case self::EXT: + $has_ext = true; + break; + + case self::INT: + $has_int = true; + break; + + case self::BOTH: + $has_int = true; + $has_ext = true; + $has_radio = true; + break; + } + if (!$this->getRequired()) { + // see #0021274 +// $has_radio = true; + } + + // external + if ($has_ext) { + $title = $has_radio ? $lng->txt("url") : ""; + + // external + $ti = new ilTextInputGUI($title, $this->getPostVar()); + $ti->setMaxLength($this->getExternalLinkMaxLength()); + } + + // internal + if ($has_int) { + $ilCtrl->setParameterByClass("ilformpropertydispatchgui", "postvar", $this->getPostVar()); + $link = array(get_class($this->getParent()), "ilformpropertydispatchgui", get_class($this), "ilinternallinkgui"); + $link = $ilCtrl->getLinkTargetByClass($link, "", false, true, false); + $ilCtrl->setParameterByClass("ilformpropertydispatchgui", "postvar", $_REQUEST["postvar"]); + + $no_disp_class = (strpos($this->getValue(), "|")) + ? "" + : " ilNoDisplay"; + + $itpl = new ilTemplate('tpl.prop_link.html', true, true, 'Services/Form'); + $itpl->setVariable("VAL_ID", $this->getPostVar()); + $itpl->setVariable("URL_EDIT", $link); + $itpl->setVariable("TXT_EDIT", $lng->txt("form_get_link")); + $itpl->setVariable("CSS_REMOVE", $no_disp_class); + $itpl->setVariable("TXT_REMOVE", $lng->txt("remove")); + + $ne = new ilNonEditableValueGUI($lng->txt("object"), $this->getPostVar() . "_val", true); + + // hidden field for selected value + $hidden_type = new ilHiddenInputGUI($this->getPostVar() . "_ajax_type"); + $hidden_id = new ilHiddenInputGUI($this->getPostVar() . "_ajax_id"); + $hidden_target = new ilHiddenInputGUI($this->getPostVar() . "_ajax_target"); + } + + // mode + if ($has_radio) { + $ext = new ilRadioOption($lng->txt("form_link_external"), "ext"); + $ext->addSubItem($ti); + + $int = new ilRadioOption($lng->txt("form_link_internal"), "int"); + $int->addSubItem($ne); + + $mode = new ilRadioGroupInputGUI("", $this->getPostVar() . "_mode"); + if (!$this->getRequired()) { + $no = new ilRadioOption($lng->txt("form_no_link"), "no"); + $mode->addOption($no); + } + $mode->addOption($ext); + $mode->addOption($int); + } else { + $mode = new ilHiddenInputGUI($this->getPostVar() . "_mode"); + if ($has_int) { + $mode->setValue("int"); + } else { + $mode->setValue("ext"); + } + } + + // value + $value = $this->getValue(); + if ($value) { + // #15647 + if ($has_int && self::isInternalLink($value)) { + $mode->setValue("int"); + + $value_trans = self::getTranslatedValue($value); + + $value = explode("|", $value); + $hidden_type->setValue($value[0]); + $hidden_id->setValue($value[1]); + $hidden_target->setValue($value[2]); + + $itpl->setVariable("VAL_OBJECT_TYPE", $value_trans["type"]); + $itpl->setVariable("VAL_OBJECT_NAME", $value_trans["name"]); + if ($value[2] != "") { + $itpl->setVariable("VAL_TARGET_FRAME", "(" . $value[2] . ")"); + } + } elseif ($has_ext) { + $mode->setValue("ext"); + + $ti->setValue($value); + } + } elseif (!$this->getRequired()) { + $mode->setValue("no"); + } + + // #10185 - default for external urls + if ($has_ext && !$ti->getValue()) { + $ti->setValue("http://"); + } + + $ne->setValue($itpl->get()); + + // to html + if ($has_radio) { + $html = $mode->render(); + } else { + $html = $mode->getToolbarHTML(); + + if ($has_ext) { + $html.= $ti->getToolbarHTML(); + } else { + $html.= $ne->render() . + '
                  ' . $ne->getInfo() . '
                  '; + } + } + + // js for internal link + if ($has_int) { + include_once("./Services/Link/classes/class.ilInternalLinkGUI.php"); + $html.= $hidden_type->getToolbarHTML() . + $hidden_id->getToolbarHTML() . + $hidden_target->getToolbarHTML(); + } + + return $html; + } + + public function getContentOutsideFormTag() + { + if ($this->getAllowedLinkTypes() == self::INT || + $this->getAllowedLinkTypes() == self::BOTH) { + // as the ajax-panel uses a form it has to be outside of the parent form! + return ilInternalLinkGUI::getInitHTML(""); + } + } + + public static function isInternalLink($a_value) + { + if (strpos($a_value, "|")) { + $parts = explode("|", $a_value); + if (sizeof($parts) == 2 || sizeof($parts) == 3) { + // numeric id + if (is_numeric($parts[1])) { + // simple type + if (preg_match("/^[a-zA-Z_]+$/", $parts[0], $matches)) { + return true; + } + } + } + } + return false; + } + + public static function getTranslatedValue($a_value) + { + global $DIC; + + $lng = $DIC->language(); + + $value = explode("|", $a_value); + + switch ($value[0]) { + case "media": + $type = $lng->txt("obj_mob"); + $name = ilObject::_lookupTitle($value[1]); + break; + + case "page": + include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); + $type = $lng->txt("obj_pg"); + $name = ilLMPageObject::_lookupTitle($value[1]); + break; + + case "chap": + include_once("./Modules/LearningModule/classes/class.ilStructureObject.php"); + $type = $lng->txt("obj_st"); + $name = ilStructureObject::_lookupTitle($value[1]); + break; + + case "term": + include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + $type = $lng->txt("term"); + $name = ilGlossaryTerm::_lookGlossaryTerm($value[1]); + break; + + default: + $type = $lng->txt("obj_" . $value[0]); + $name = ilObject::_lookupTitle(ilObject::_lookupObjId($value[1])); + break; + } + + return array("type"=>$type, "name"=>$name); + } + + /** + * Insert property html + * + * @return int Size + */ + public function insert($a_tpl) + { + $html = $this->render(); + + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $html); + $a_tpl->parseCurrentBlock(); + } + + /** + * Get value as internal link attributes + * + * @return array (with keys "Type", "Target" and "TargetFrame") + */ + public function getIntLinkAttributes() + { + $val = explode("|", $_POST[$this->getPostVar()]); + + $ret = false; + $type = ""; + $target = ""; + if (self::isInternalLink($_POST[$this->getPostVar()])) { + $target_frame = $val[2]; + $map = self::getTypeToAttrType(); + if (isset($map[$val[0]])) { + $type = $map[$val[0]]; + $target_type = $val[0]; + if ($val[0] == "chap") { + $target_type = "st"; + } + if ($val[0] == "term") { + $target_type = "git"; + } + if ($val[0] == "page") { + $target_type = "pg"; + } + $target = "il__" . $target_type . "_" . $val[1]; + } elseif ($this->obj_definition->isRBACObject($val[0])) { + $type = "RepositoryItem"; + $target = "il__obj_" . $val[1]; + } + if ($type != "") { + $ret = array( + "Target" => $target, + "Type" => $type, + "TargetFrame" => $target_frame + ); + } + } + return $ret; + } + + /** + * Set value by internal links attributes + * + * @param + * @return + */ + public function setValueByIntLinkAttributes($a_type, $a_target, $a_target_frame = "") + { + $t = explode("_", $a_target); + $target_id = $t[3]; + $type = ""; + $map = self::getAttrTypeToType(); + if ($a_type == "RepositoryItem") { + $type = ilObject::_lookupType($target_id, true); + } elseif (isset($map[$a_type])) { + $type = $map[$a_type]; + } + if ($type != "" && $target_id != "") { + $val = $type . "|" . $target_id; + if ($a_target_frame != "") { + $val.= "|" . $a_target_frame; + } + $this->setValue($val); + } + } +} diff --git a/Services/Form/classes/class.ilLocationInputGUI.php b/Services/Form/classes/class.ilLocationInputGUI.php index 39d330f7d694bbcecbe0327c3c3f2dfcc0bfae8d..8e00790f9654f7ae07c4c135858e4a3bbbf0f667 100755 --- a/Services/Form/classes/class.ilLocationInputGUI.php +++ b/Services/Form/classes/class.ilLocationInputGUI.php @@ -1,263 +1,272 @@ +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilLocationInputGUI extends ilFormPropertyGUI { - /** - * @var ilRbacSystem - */ - protected $rbacsystem; + /** + * @var ilRbacSystem + */ + protected $rbacsystem; - protected $latitude; - protected $longitude; - protected $zoom; - protected $address; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + protected $latitude; + protected $longitude; + protected $zoom; + protected $address; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - $this->rbacsystem = $DIC->rbac()->system(); - parent::__construct($a_title, $a_postvar); - $this->setType("location"); - } + $this->lng = $DIC->language(); + $this->rbacsystem = $DIC->rbac()->system(); + parent::__construct($a_title, $a_postvar); + $this->setType("location"); + } - /** - * Set Latitude. - * - * @param real $a_latitude Latitude - */ - function setLatitude($a_latitude) - { - $this->latitude = $a_latitude; - } + /** + * Set Latitude. + * + * @param real $a_latitude Latitude + */ + public function setLatitude($a_latitude) + { + $this->latitude = $a_latitude; + } - /** - * Get Latitude. - * - * @return real Latitude - */ - function getLatitude() - { - return $this->latitude; - } + /** + * Get Latitude. + * + * @return real Latitude + */ + public function getLatitude() + { + return $this->latitude; + } - /** - * Set Longitude. - * - * @param real $a_longitude Longitude - */ - function setLongitude($a_longitude) - { - $this->longitude = $a_longitude; - } + /** + * Set Longitude. + * + * @param real $a_longitude Longitude + */ + public function setLongitude($a_longitude) + { + $this->longitude = $a_longitude; + } - /** - * Get Longitude. - * - * @return real Longitude - */ - function getLongitude() - { - return $this->longitude; - } + /** + * Get Longitude. + * + * @return real Longitude + */ + public function getLongitude() + { + return $this->longitude; + } - /** - * Set Zoom. - * - * @param int $a_zoom Zoom - */ - function setZoom($a_zoom) - { - $this->zoom = $a_zoom; - } + /** + * Set Zoom. + * + * @param int $a_zoom Zoom + */ + public function setZoom($a_zoom) + { + $this->zoom = $a_zoom; + } - /** - * Get Zoom. - * - * @return int Zoom - */ - function getZoom() - { - return $this->zoom; - } + /** + * Get Zoom. + * + * @return int Zoom + */ + public function getZoom() + { + return $this->zoom; + } - /** - * Set Address. - * - * @param string $a_Address Address - */ - function setAddress($a_address) - { - $this->address = $a_address; - } - - /** - * Get Address. - * - * @return string Address - */ - function getAddress() - { - return $this->address; - } + /** + * Set Address. + * + * @param string $a_Address Address + */ + public function setAddress($a_address) + { + $this->address = $a_address; + } + + /** + * Get Address. + * + * @return string Address + */ + public function getAddress() + { + return $this->address; + } - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $this->setLatitude($a_values[$this->getPostVar()]["latitude"]); - $this->setLongitude($a_values[$this->getPostVar()]["longitude"]); - $this->setZoom($a_values[$this->getPostVar()]["zoom"]); - } + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $this->setLatitude($a_values[$this->getPostVar()]["latitude"]); + $this->setLongitude($a_values[$this->getPostVar()]["longitude"]); + $this->setZoom($a_values[$this->getPostVar()]["zoom"]); + } - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - $_POST[$this->getPostVar()]["latitude"] = - ilUtil::stripSlashes($_POST[$this->getPostVar()]["latitude"]); - $_POST[$this->getPostVar()]["longitude"] = - ilUtil::stripSlashes($_POST[$this->getPostVar()]["longitude"]); - if ($this->getRequired() && - (trim($_POST[$this->getPostVar()]["latitude"]) == "" || trim($_POST[$this->getPostVar()]["longitude"]) == "")) - { - $this->setAlert($lng->txt("msg_input_is_required")); + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + $_POST[$this->getPostVar()]["latitude"] = + ilUtil::stripSlashes($_POST[$this->getPostVar()]["latitude"]); + $_POST[$this->getPostVar()]["longitude"] = + ilUtil::stripSlashes($_POST[$this->getPostVar()]["longitude"]); + if ($this->getRequired() && + (trim($_POST[$this->getPostVar()]["latitude"]) == "" || trim($_POST[$this->getPostVar()]["longitude"]) == "")) { + $this->setAlert($lng->txt("msg_input_is_required")); - return false; - } - return true; - } + return false; + } + return true; + } - /** - * Insert property html - * - */ - function insert($a_tpl) - { - $lng = $this->lng; - $rbacsystem = $this->rbacsystem; - - $lng->loadLanguageModule("maps"); - $tpl = new ilTemplate("tpl.prop_location.html", true, true, "Services/Form"); - $tpl->setVariable("POST_VAR", $this->getPostVar()); - $tpl->setVariable("TXT_ZOOM", $lng->txt("maps_zoom_level")); - $tpl->setVariable("TXT_LATITUDE", $lng->txt("maps_latitude")); - $tpl->setVariable("TXT_LONGITUDE", $lng->txt("maps_longitude")); - $tpl->setVariable("LOC_DESCRIPTION", $lng->txt("maps_std_location_desc")); - - $lat = is_numeric($this->getLatitude()) - ? $this->getLatitude() - : 0; - $long = is_numeric($this->getLongitude()) - ? $this->getLongitude() - : 0; - $tpl->setVariable("PROPERTY_VALUE_LAT", $lat); - $tpl->setVariable("PROPERTY_VALUE_LONG", $long); - for($i = 0; $i <= 18; $i++) - { - $levels[$i] = $i; - } - - $map_id = "map_".md5(uniqid()); - - $tpl->setVariable("ZOOM_SELECT", - ilUtil::formSelect($this->getZoom(), $this->getPostVar()."[zoom]", - $levels, false, true, 0, "", array("id" => $map_id."_zoom", - "onchange" => "ilUpdateMap('".$map_id."');"))); - $tpl->setVariable("MAP_ID", $map_id); - $tpl->setVariable("ID", $this->getPostVar()); + /** + * Insert property html + * + */ + public function insert($a_tpl) + { + $lng = $this->lng; + $rbacsystem = $this->rbacsystem; + + $lng->loadLanguageModule("maps"); + $tpl = new ilTemplate("tpl.prop_location.html", true, true, "Services/Form"); + $tpl->setVariable("POST_VAR", $this->getPostVar()); + $tpl->setVariable("TXT_ZOOM", $lng->txt("maps_zoom_level")); + $tpl->setVariable("TXT_LATITUDE", $lng->txt("maps_latitude")); + $tpl->setVariable("TXT_LONGITUDE", $lng->txt("maps_longitude")); + $tpl->setVariable("LOC_DESCRIPTION", $lng->txt("maps_std_location_desc")); + + $lat = is_numeric($this->getLatitude()) + ? $this->getLatitude() + : 0; + $long = is_numeric($this->getLongitude()) + ? $this->getLongitude() + : 0; + $tpl->setVariable("PROPERTY_VALUE_LAT", $lat); + $tpl->setVariable("PROPERTY_VALUE_LONG", $long); + for ($i = 0; $i <= 18; $i++) { + $levels[$i] = $i; + } + + $map_id = "map_" . md5(uniqid()); + + $tpl->setVariable( + "ZOOM_SELECT", + ilUtil::formSelect( + $this->getZoom(), + $this->getPostVar() . "[zoom]", + $levels, + false, + true, + 0, + "", + array("id" => $map_id . "_zoom", + "onchange" => "ilUpdateMap('" . $map_id . "');") + ) + ); + $tpl->setVariable("MAP_ID", $map_id); + $tpl->setVariable("ID", $this->getPostVar()); - // only show address input if geolocation url available - // else, if admin: show warning. + // only show address input if geolocation url available + // else, if admin: show warning. - if($this->geolocationAvailiable()) { - $tpl->setVariable("TXT_ADDR", $lng->txt("address")); - $tpl->setVariable("TXT_LOOKUP", $lng->txt("maps_lookup_address")); - $tpl->setVariable("TXT_ADDRESS", $this->getAddress()); - $tpl->setVariable("MAP_ID_ADDR", $map_id); - $tpl->setVariable("POST_VAR_ADDR", $this->getPostVar()); - } else { - if($rbacsystem->checkAccess("visible", SYSTEM_FOLDER_ID)) { - $tpl->setVariable("TEXT", $lng->txt("configure_geolocation")); - } - } + if ($this->geolocationAvailiable()) { + $tpl->setVariable("TXT_ADDR", $lng->txt("address")); + $tpl->setVariable("TXT_LOOKUP", $lng->txt("maps_lookup_address")); + $tpl->setVariable("TXT_ADDRESS", $this->getAddress()); + $tpl->setVariable("MAP_ID_ADDR", $map_id); + $tpl->setVariable("POST_VAR_ADDR", $this->getPostVar()); + } else { + if ($rbacsystem->checkAccess("visible", SYSTEM_FOLDER_ID)) { + $tpl->setVariable("TEXT", $lng->txt("configure_geolocation")); + } + } - include_once("./Services/Maps/classes/class.ilMapUtil.php"); - $map_gui = ilMapUtil::getMapGUI(); - $map_gui->setMapId($map_id) - ->setLatitude($lat) - ->setLongitude($long) - ->setZoom($this->getZoom()) - ->setEnableTypeControl(true) - ->setEnableLargeMapControl(true) - ->setEnableUpdateListener(true) - ->setEnableCentralMarker(true); + include_once("./Services/Maps/classes/class.ilMapUtil.php"); + $map_gui = ilMapUtil::getMapGUI(); + $map_gui->setMapId($map_id) + ->setLatitude($lat) + ->setLongitude($long) + ->setZoom($this->getZoom()) + ->setEnableTypeControl(true) + ->setEnableLargeMapControl(true) + ->setEnableUpdateListener(true) + ->setEnableCentralMarker(true); - $tpl->setVariable("MAP", $map_gui->getHtml()); - - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $tpl->get()); - $a_tpl->parseCurrentBlock(); - } + $tpl->setVariable("MAP", $map_gui->getHtml()); + + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $tpl->get()); + $a_tpl->parseCurrentBlock(); + } - /** - * Is geolocation configured? - * @return bool - */ - protected function geolocationAvailiable() { - include_once("./Services/Maps/classes/class.ilMapUtil.php"); - switch(ilMapUtil::getType()) { - case 'openlayers': - return ilMapUtil::getStdGeolocationServer() ? true : false; - case 'googlemaps': - return true; - default: - return false; - } - } -} \ No newline at end of file + /** + * Is geolocation configured? + * @return bool + */ + protected function geolocationAvailiable() + { + include_once("./Services/Maps/classes/class.ilMapUtil.php"); + switch (ilMapUtil::getType()) { + case 'openlayers': + return ilMapUtil::getStdGeolocationServer() ? true : false; + case 'googlemaps': + return true; + default: + return false; + } + } +} diff --git a/Services/Form/classes/class.ilMultiFilesSubmitRecursiveSlashesStripper.php b/Services/Form/classes/class.ilMultiFilesSubmitRecursiveSlashesStripper.php index b9f70a501b974021a890f7d329c60db586dfbfd0..8aaf0d77474d8c7c1856d9f8fa0313a4739896d1 100644 --- a/Services/Form/classes/class.ilMultiFilesSubmitRecursiveSlashesStripper.php +++ b/Services/Form/classes/class.ilMultiFilesSubmitRecursiveSlashesStripper.php @@ -11,56 +11,55 @@ require_once 'Services/Form/classes/class.ilFormSubmitRecursiveSlashesStripper.p */ class ilMultiFilesSubmitRecursiveSlashesStripper implements ilFormValuesManipulator { - /** - * @var string - */ - protected $postVar = null; - - /** - * @return string - */ - public function getPostVar() - { - return $this->postVar; - } - - /** - * @param string $postVar - */ - public function setPostVar($postVar) - { - $this->postVar = $postVar; - } - - /** - * @param array $inputValues - * @return array $inputValues - */ - public function manipulateFormInputValues($inputValues) - { - return $inputValues; - } - - /** - * @param array $submitValues - * @return array $submitValues - */ - public function manipulateFormSubmitValues($submitValues) - { - $this->manipulateFileSubmitValues(); - return $submitValues; - } - - /** - * perform the strip slashing on files submit - */ - protected function manipulateFileSubmitValues() - { - if($_FILES) - { - $_FILES[$this->getPostVar()] = ilUtil::stripSlashesRecursive( - $_FILES[$this->getPostVar()] - ); - } - } -} \ No newline at end of file + /** + * @var string + */ + protected $postVar = null; + + /** + * @return string + */ + public function getPostVar() + { + return $this->postVar; + } + + /** + * @param string $postVar + */ + public function setPostVar($postVar) + { + $this->postVar = $postVar; + } + + /** + * @param array $inputValues + * @return array $inputValues + */ + public function manipulateFormInputValues($inputValues) + { + return $inputValues; + } + + /** + * @param array $submitValues + * @return array $submitValues + */ + public function manipulateFormSubmitValues($submitValues) + { + $this->manipulateFileSubmitValues(); + return $submitValues; + } + + /** + * perform the strip slashing on files submit + */ + protected function manipulateFileSubmitValues() + { + if ($_FILES) { + $_FILES[$this->getPostVar()] = ilUtil::stripSlashesRecursive( + $_FILES[$this->getPostVar()] + ); + } + } +} diff --git a/Services/Form/classes/class.ilMultiSelectInputGUI.php b/Services/Form/classes/class.ilMultiSelectInputGUI.php index 2323cbae002e7b7a2f345acd7b10ee35ebb36c7c..93b2cadc1e3c08339928586274f0cb405e521743 100755 --- a/Services/Form/classes/class.ilMultiSelectInputGUI.php +++ b/Services/Form/classes/class.ilMultiSelectInputGUI.php @@ -1,24 +1,24 @@ +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilMultiSelectInputGUI extends ilFormPropertyGUI implements ilTableFilterItem { - protected $options; - protected $value; - protected $select_all; // [bool] - protected $selected_first; // [bool] - - /** - * Width for this field - * - * @access private - * @var integer width - */ - private $width = 160; - - /** - * Height for this field - * - * @access private - * @var integer height - */ - private $height = 100; - - /** - * @var string - */ - protected $widthUnit = 'px'; - - /** - * @var string - */ - protected $heightUnit = 'px'; - - /** - * @var array - */ - protected $custom_attributes = array(); - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; - - $this->lng = $DIC->language(); - parent::__construct($a_title, $a_postvar); - $this->setType("multi_select"); - $this->setValue(array()); - } - - /** - * Sets the width of this field - * - * @access public - * @param integer $a_width - */ - public function setWidth($a_width) - { - $this->width = (int)$a_width; - } - - /** - * Returns the width currently set for this field - * - * @access public - * @return integer width - */ - public function getWidth() - { - return $this->width; - } - - /** - * Sets the height of this field - * - * @access public - * @param integer $a_height - */ - public function setHeight($a_height) - { - $this->height = (int)$a_height; - } - - /** - * Returns the height currently set for this field - * - * @access public - * @return integer height - */ - public function getHeight() - { - return $this->height; - } - - /** - * Set Options. - * - * @param array $a_options Options. Array ("value" => "option_text") - */ - function setOptions($a_options) - { - $this->options = $a_options; - } - - /** - * Get Options. - * - * @return array Options. Array ("value" => "option_text") - */ - function getOptions() - { - return $this->options; - } - - /** - * Set Value. - * - * @param array array with all activated selections - */ - function setValue($a_array) - { - $this->value = $a_array; - } - - /** - * Get Value. - * - * @return array array with all activated selections - */ - function getValue() - { - return is_array($this->value) ? $this->value : array(); - } - - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $this->setValue($a_values[$this->getPostVar()]); - } - - - function enableSelectAll($a_value) - { - $this->select_all = (bool)$a_value; - } - - function enableSelectedFirst($a_value) - { - $this->selected_first = (bool)$a_value; - } - - - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - if (is_array($_POST[$this->getPostVar()])) - { - foreach ($_POST[$this->getPostVar()] as $k => $v) - { - $_POST[$this->getPostVar()][$k] = - ilUtil::stripSlashes($v); - } - } - else - { - $_POST[$this->getPostVar()] = array(); - } - if ($this->getRequired() && count($_POST[$this->getPostVar()]) == 0) - { - $this->setAlert($lng->txt("msg_input_is_required")); - - return false; - } - return true; - } - - /** - * Render item - */ - function render() - { - $lng = $this->lng; - - $tpl = new ilTemplate("tpl.prop_multi_select.html", true, true, "Services/Form"); - $values = $this->getValue(); - - $options = $this->getOptions(); - if($options) - { - if($this->select_all) - { - // enable select all toggle - $tpl->setCurrentBlock("item"); - $tpl->setVariable("VAL", ""); - $tpl->setVariable("ID_VAL", ilUtil::prepareFormOutput("all__toggle")); - $tpl->setVariable("IID", $this->getFieldId()); - $tpl->setVariable("TXT_OPTION" ,"".$lng->txt("select_all").""); - $tpl->setVariable("POST_VAR", $this->getPostVar()); - $tpl->parseCurrentBlock(); - - $tpl->setVariable("TOGGLE_FIELD_ID", $this->getFieldId()); - $tpl->setVariable("TOGGLE_ALL_ID", $this->getFieldId()."_all__toggle"); - $tpl->setVariable("TOGGLE_ALL_CBOX_ID", $this->getFieldId()."_"); - } - - if($this->selected_first) - { - // move selected values to top - $tmp_checked = $tmp_unchecked = array(); - foreach($options as $option_value => $option_text) - { - if (in_array($option_value, $values)) - { - $tmp_checked[$option_value] = $option_text; - } - else - { - $tmp_unchecked[$option_value] = $option_text; - } - } - $options = $tmp_checked + $tmp_unchecked; - unset($tmp_checked); - unset($tmp_unchecked); - } - - foreach($options as $option_value => $option_text) - { - $tpl->setCurrentBlock("item"); - if ($this->getDisabled()) - { - $tpl->setVariable("DISABLED", - " disabled=\"disabled\""); - } - if (in_array($option_value, $values)) - { - $tpl->setVariable("CHECKED", - " checked=\"checked\""); - } - - $tpl->setVariable("VAL", ilUtil::prepareFormOutput($option_value)); - $tpl->setVariable("ID_VAL", ilUtil::prepareFormOutput($option_value)); - $tpl->setVariable("IID", $this->getFieldId()); - $tpl->setVariable("TXT_OPTION", $option_text); - $tpl->setVariable("POST_VAR", $this->getPostVar()); - $tpl->parseCurrentBlock(); - } - } - - $tpl->setVariable("ID", $this->getFieldId()); - $tpl->setVariable("CUSTOM_ATTRIBUTES", implode(' ', $this->getCustomAttributes())); - - if($this->getWidth()) - { - $tpl->setVariable("WIDTH", $this->getWidth().($this->getWidthUnit()?$this->getWidthUnit():'')); - } - if($this->getHeight()) - { - $tpl->setVariable("HEIGHT", $this->getHeight().($this->getHeightUnit()?$this->getHeightUnit():'')); - } - - return $tpl->get(); - } - - /** - * Insert property html - * - * @return int Size - */ - function insert($a_tpl) - { - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $this->render()); - $a_tpl->parseCurrentBlock(); - } - - /** - * Get HTML for table filter - */ - function getTableFilterHTML() - { - $html = $this->render(); - return $html; - } - - - /** - * @return array - */ - public function getCustomAttributes() { - return $this->custom_attributes; - } - - - /** - * @param array $custom_attributes - */ - public function setCustomAttributes($custom_attributes) { - $this->custom_attributes = $custom_attributes; - } - - - /** - * @param array $custom_attribute - */ - public function addCustomAttribute($custom_attribute) { - $this->custom_attributes[] = $custom_attribute; - } - - /** - * @return string - */ - public function getWidthUnit() { - return $this->widthUnit; - } - - /** - * @param string $widthUnit - */ - public function setWidthUnit($widthUnit) { - $this->widthUnit = $widthUnit; - } - - /** - * @return string - */ - public function getHeightUnit() { - return $this->heightUnit; - } - - /** - * @param string $heightUnit - */ - public function setHeightUnit($heightUnit) { - $this->heightUnit = $heightUnit; - } + protected $options; + protected $value; + protected $select_all; // [bool] + protected $selected_first; // [bool] + + /** + * Width for this field + * + * @access private + * @var integer width + */ + private $width = 160; + + /** + * Height for this field + * + * @access private + * @var integer height + */ + private $height = 100; + + /** + * @var string + */ + protected $widthUnit = 'px'; + + /** + * @var string + */ + protected $heightUnit = 'px'; + + /** + * @var array + */ + protected $custom_attributes = array(); + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; + + $this->lng = $DIC->language(); + parent::__construct($a_title, $a_postvar); + $this->setType("multi_select"); + $this->setValue(array()); + } + + /** + * Sets the width of this field + * + * @access public + * @param integer $a_width + */ + public function setWidth($a_width) + { + $this->width = (int) $a_width; + } + + /** + * Returns the width currently set for this field + * + * @access public + * @return integer width + */ + public function getWidth() + { + return $this->width; + } + + /** + * Sets the height of this field + * + * @access public + * @param integer $a_height + */ + public function setHeight($a_height) + { + $this->height = (int) $a_height; + } + + /** + * Returns the height currently set for this field + * + * @access public + * @return integer height + */ + public function getHeight() + { + return $this->height; + } + + /** + * Set Options. + * + * @param array $a_options Options. Array ("value" => "option_text") + */ + public function setOptions($a_options) + { + $this->options = $a_options; + } + + /** + * Get Options. + * + * @return array Options. Array ("value" => "option_text") + */ + public function getOptions() + { + return $this->options; + } + + /** + * Set Value. + * + * @param array array with all activated selections + */ + public function setValue($a_array) + { + $this->value = $a_array; + } + + /** + * Get Value. + * + * @return array array with all activated selections + */ + public function getValue() + { + return is_array($this->value) ? $this->value : array(); + } + + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $this->setValue($a_values[$this->getPostVar()]); + } + + + public function enableSelectAll($a_value) + { + $this->select_all = (bool) $a_value; + } + + public function enableSelectedFirst($a_value) + { + $this->selected_first = (bool) $a_value; + } + + + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + if (is_array($_POST[$this->getPostVar()])) { + foreach ($_POST[$this->getPostVar()] as $k => $v) { + $_POST[$this->getPostVar()][$k] = + ilUtil::stripSlashes($v); + } + } else { + $_POST[$this->getPostVar()] = array(); + } + if ($this->getRequired() && count($_POST[$this->getPostVar()]) == 0) { + $this->setAlert($lng->txt("msg_input_is_required")); + + return false; + } + return true; + } + + /** + * Render item + */ + public function render() + { + $lng = $this->lng; + + $tpl = new ilTemplate("tpl.prop_multi_select.html", true, true, "Services/Form"); + $values = $this->getValue(); + + $options = $this->getOptions(); + if ($options) { + if ($this->select_all) { + // enable select all toggle + $tpl->setCurrentBlock("item"); + $tpl->setVariable("VAL", ""); + $tpl->setVariable("ID_VAL", ilUtil::prepareFormOutput("all__toggle")); + $tpl->setVariable("IID", $this->getFieldId()); + $tpl->setVariable("TXT_OPTION", "" . $lng->txt("select_all") . ""); + $tpl->setVariable("POST_VAR", $this->getPostVar()); + $tpl->parseCurrentBlock(); + + $tpl->setVariable("TOGGLE_FIELD_ID", $this->getFieldId()); + $tpl->setVariable("TOGGLE_ALL_ID", $this->getFieldId() . "_all__toggle"); + $tpl->setVariable("TOGGLE_ALL_CBOX_ID", $this->getFieldId() . "_"); + } + + if ($this->selected_first) { + // move selected values to top + $tmp_checked = $tmp_unchecked = array(); + foreach ($options as $option_value => $option_text) { + if (in_array($option_value, $values)) { + $tmp_checked[$option_value] = $option_text; + } else { + $tmp_unchecked[$option_value] = $option_text; + } + } + $options = $tmp_checked + $tmp_unchecked; + unset($tmp_checked); + unset($tmp_unchecked); + } + + foreach ($options as $option_value => $option_text) { + $tpl->setCurrentBlock("item"); + if ($this->getDisabled()) { + $tpl->setVariable( + "DISABLED", + " disabled=\"disabled\"" + ); + } + if (in_array($option_value, $values)) { + $tpl->setVariable( + "CHECKED", + " checked=\"checked\"" + ); + } + + $tpl->setVariable("VAL", ilUtil::prepareFormOutput($option_value)); + $tpl->setVariable("ID_VAL", ilUtil::prepareFormOutput($option_value)); + $tpl->setVariable("IID", $this->getFieldId()); + $tpl->setVariable("TXT_OPTION", $option_text); + $tpl->setVariable("POST_VAR", $this->getPostVar()); + $tpl->parseCurrentBlock(); + } + } + + $tpl->setVariable("ID", $this->getFieldId()); + $tpl->setVariable("CUSTOM_ATTRIBUTES", implode(' ', $this->getCustomAttributes())); + + if ($this->getWidth()) { + $tpl->setVariable("WIDTH", $this->getWidth() . ($this->getWidthUnit()?$this->getWidthUnit():'')); + } + if ($this->getHeight()) { + $tpl->setVariable("HEIGHT", $this->getHeight() . ($this->getHeightUnit()?$this->getHeightUnit():'')); + } + + return $tpl->get(); + } + + /** + * Insert property html + * + * @return int Size + */ + public function insert($a_tpl) + { + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $this->render()); + $a_tpl->parseCurrentBlock(); + } + + /** + * Get HTML for table filter + */ + public function getTableFilterHTML() + { + $html = $this->render(); + return $html; + } + + + /** + * @return array + */ + public function getCustomAttributes() + { + return $this->custom_attributes; + } + + + /** + * @param array $custom_attributes + */ + public function setCustomAttributes($custom_attributes) + { + $this->custom_attributes = $custom_attributes; + } + + + /** + * @param array $custom_attribute + */ + public function addCustomAttribute($custom_attribute) + { + $this->custom_attributes[] = $custom_attribute; + } + + /** + * @return string + */ + public function getWidthUnit() + { + return $this->widthUnit; + } + + /** + * @param string $widthUnit + */ + public function setWidthUnit($widthUnit) + { + $this->widthUnit = $widthUnit; + } + + /** + * @return string + */ + public function getHeightUnit() + { + return $this->heightUnit; + } + + /** + * @param string $heightUnit + */ + public function setHeightUnit($heightUnit) + { + $this->heightUnit = $heightUnit; + } } diff --git a/Services/Form/classes/class.ilMultipleImagesAdditionalIndexLevelRemover.php b/Services/Form/classes/class.ilMultipleImagesAdditionalIndexLevelRemover.php index 0997feef71d466cafabc752d289203b64eb6b572..895b71a3d1bb474611a4aea5ad33a1467dc4011f 100644 --- a/Services/Form/classes/class.ilMultipleImagesAdditionalIndexLevelRemover.php +++ b/Services/Form/classes/class.ilMultipleImagesAdditionalIndexLevelRemover.php @@ -11,132 +11,120 @@ require_once 'Services/Form/interfaces/interface.ilFormValuesManipulator.php'; */ class ilMultipleImagesAdditionalIndexLevelRemover implements ilFormValuesManipulator { - protected $filesSubmissionProperties = array( - 'name', 'tmp_name', 'type', 'error', 'size' - ); - - protected $postVar; - - public function getPostVar() - { - return $this->postVar; - } - - public function setPostVar($postVar) - { - $this->postVar = $postVar; - } + protected $filesSubmissionProperties = array( + 'name', 'tmp_name', 'type', 'error', 'size' + ); + + protected $postVar; + + public function getPostVar() + { + return $this->postVar; + } + + public function setPostVar($postVar) + { + $this->postVar = $postVar; + } - protected function getFilesSubmissionProperties() - { - return $this->filesSubmissionProperties; - } - public function manipulateFormInputValues($inputValues) - { - return $inputValues; - } - - public function manipulateFormSubmitValues($submitValues) - { - $submitValues = $this->removeAdditionalSubFieldsLevelFromSubmitValues($submitValues); + protected function getFilesSubmissionProperties() + { + return $this->filesSubmissionProperties; + } + public function manipulateFormInputValues($inputValues) + { + return $inputValues; + } + + public function manipulateFormSubmitValues($submitValues) + { + $submitValues = $this->removeAdditionalSubFieldsLevelFromSubmitValues($submitValues); - if($_FILES) - { - $_FILES[$this->getPostVar()] = $this->removeAdditionalSubFieldsLevelFromFilesSubmit( - $_FILES[$this->getPostVar()] - ); - } + if ($_FILES) { + $_FILES[$this->getPostVar()] = $this->removeAdditionalSubFieldsLevelFromFilesSubmit( + $_FILES[$this->getPostVar()] + ); + } - return $submitValues; - } - protected function isSubFieldAvailable($values, $subFieldName) - { - if( !is_array($values) ) - { - return false; - } - - if( !isset($values[$subFieldName]) ) - { - return false; - } - - if( !is_array($values[$subFieldName]) ) - { - return false; - } - - return true; - } - - protected function isIteratorSubfieldAvailable($values) - { - return $this->isSubFieldAvailable($values, ilMultipleImagesInputGUI::ITERATOR_SUBFIELD_NAME); - } - - protected function isUploadSubfieldAvailable($values) - { - return $this->isSubFieldAvailable($values, ilMultipleImagesInputGUI::IMAGE_UPLOAD_SUBFIELD_NAME); - } - - protected function removeAdditionalSubFieldsLevelFromSubmitValues($values) - { - if( !$this->isIteratorSubfieldAvailable($values) ) - { - return $values; - } - - $storedImages = $values[ilMultipleImagesInputGUI::STORED_IMAGE_SUBFIELD_NAME]; - $actualValues = array(); - - foreach($values[ilMultipleImagesInputGUI::ITERATOR_SUBFIELD_NAME] as $index => $value) - { - if( !isset($storedImages[$index]) ) - { - $actualValues[$index] = ''; - continue; - } - - $actualValues[$index] = $storedImages[$index]; - } - - return $actualValues; - } - - protected function removeAdditionalSubFieldsLevelFromFilesSubmitProperty($uploadProperty) - { - if( !$this->isUploadSubfieldAvailable($uploadProperty) ) - { - return $uploadProperty; - } - - foreach($uploadProperty as $subField => $submittedFile ) - { - foreach($submittedFile as $identifier => $uploadValue) - { - $uploadProperty[$identifier] = $uploadValue; - } - - unset($uploadProperty[$subField]); - } - - return $uploadProperty; - } - - protected function removeAdditionalSubFieldsLevelFromFilesSubmit($filesSubmit) - { - foreach($this->getFilesSubmissionProperties() as $uploadProperty) - { - if( !isset($filesSubmit[$uploadProperty]) ) - { - continue; - } + return $submitValues; + } + protected function isSubFieldAvailable($values, $subFieldName) + { + if (!is_array($values)) { + return false; + } + + if (!isset($values[$subFieldName])) { + return false; + } + + if (!is_array($values[$subFieldName])) { + return false; + } + + return true; + } + + protected function isIteratorSubfieldAvailable($values) + { + return $this->isSubFieldAvailable($values, ilMultipleImagesInputGUI::ITERATOR_SUBFIELD_NAME); + } + + protected function isUploadSubfieldAvailable($values) + { + return $this->isSubFieldAvailable($values, ilMultipleImagesInputGUI::IMAGE_UPLOAD_SUBFIELD_NAME); + } + + protected function removeAdditionalSubFieldsLevelFromSubmitValues($values) + { + if (!$this->isIteratorSubfieldAvailable($values)) { + return $values; + } + + $storedImages = $values[ilMultipleImagesInputGUI::STORED_IMAGE_SUBFIELD_NAME]; + $actualValues = array(); + + foreach ($values[ilMultipleImagesInputGUI::ITERATOR_SUBFIELD_NAME] as $index => $value) { + if (!isset($storedImages[$index])) { + $actualValues[$index] = ''; + continue; + } + + $actualValues[$index] = $storedImages[$index]; + } + + return $actualValues; + } + + protected function removeAdditionalSubFieldsLevelFromFilesSubmitProperty($uploadProperty) + { + if (!$this->isUploadSubfieldAvailable($uploadProperty)) { + return $uploadProperty; + } + + foreach ($uploadProperty as $subField => $submittedFile) { + foreach ($submittedFile as $identifier => $uploadValue) { + $uploadProperty[$identifier] = $uploadValue; + } + + unset($uploadProperty[$subField]); + } + + return $uploadProperty; + } + + protected function removeAdditionalSubFieldsLevelFromFilesSubmit($filesSubmit) + { + foreach ($this->getFilesSubmissionProperties() as $uploadProperty) { + if (!isset($filesSubmit[$uploadProperty])) { + continue; + } - $filesSubmit[$uploadProperty] = $this->removeAdditionalSubFieldsLevelFromFilesSubmitProperty( - $filesSubmit[$uploadProperty] - ); - } - - return $filesSubmit; - } -} \ No newline at end of file + $filesSubmit[$uploadProperty] = $this->removeAdditionalSubFieldsLevelFromFilesSubmitProperty( + $filesSubmit[$uploadProperty] + ); + } + + return $filesSubmit; + } +} diff --git a/Services/Form/classes/class.ilMultipleImagesFileSubmissionDataCompletion.php b/Services/Form/classes/class.ilMultipleImagesFileSubmissionDataCompletion.php index 614631339ab76f3e8472c3747ec0acad8115a107..1ff7bf53cd9cfbd6dfd235541c6c9296bbc818e8 100644 --- a/Services/Form/classes/class.ilMultipleImagesFileSubmissionDataCompletion.php +++ b/Services/Form/classes/class.ilMultipleImagesFileSubmissionDataCompletion.php @@ -11,41 +11,41 @@ require_once 'Services/Form/interfaces/interface.ilFormValuesManipulator.php'; */ class ilMultipleImagesFileSubmissionDataCompletion implements ilFormValuesManipulator { - protected $postVar; - - public function getPostVar() - { - return $this->postVar; - } - - public function setPostVar($postVar) - { - $this->postVar = $postVar; - } - - public function manipulateFormInputValues($inputValues) - { - return $inputValues; - } - - public function manipulateFormSubmitValues($submitValues) - { - $_REQUEST[$this->getPostVar()] = $this->populateStoredFileCustomUploadProperty( - $_REQUEST[$this->getPostVar()], $submitValues - ); + protected $postVar; + + public function getPostVar() + { + return $this->postVar; + } + + public function setPostVar($postVar) + { + $this->postVar = $postVar; + } + + public function manipulateFormInputValues($inputValues) + { + return $inputValues; + } + + public function manipulateFormSubmitValues($submitValues) + { + $_REQUEST[$this->getPostVar()] = $this->populateStoredFileCustomUploadProperty( + $_REQUEST[$this->getPostVar()], + $submitValues + ); - return $submitValues; - } - - protected function populateStoredFileCustomUploadProperty($submitFiles, $submitValues) - { - $submitFiles['dodging_file'] = array(); - - foreach($submitValues as $identifier => $storedFilename) - { - $submitFiles['dodging_file'][$identifier] = $storedFilename; - } - - return $submitFiles; - } -} \ No newline at end of file + return $submitValues; + } + + protected function populateStoredFileCustomUploadProperty($submitFiles, $submitValues) + { + $submitFiles['dodging_file'] = array(); + + foreach ($submitValues as $identifier => $storedFilename) { + $submitFiles['dodging_file'][$identifier] = $storedFilename; + } + + return $submitFiles; + } +} diff --git a/Services/Form/classes/class.ilMultipleImagesInputGUI.php b/Services/Form/classes/class.ilMultipleImagesInputGUI.php index dffac1559f77bf599abe06631426167be451fde1..e6576479c7197aae229ed78f265cce81d05affe3 100644 --- a/Services/Form/classes/class.ilMultipleImagesInputGUI.php +++ b/Services/Form/classes/class.ilMultipleImagesInputGUI.php @@ -12,436 +12,413 @@ require_once 'Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php'; */ abstract class ilMultipleImagesInputGUI extends ilIdentifiedMultiValuesInputGUI { - const RENDERING_TEMPLATE = 'tpl.prop_multi_image_inp.html'; - - const ITERATOR_SUBFIELD_NAME = 'iteratorfield'; - const STORED_IMAGE_SUBFIELD_NAME = 'storedimage'; - const IMAGE_UPLOAD_SUBFIELD_NAME = 'imageupload'; - - const FILE_DATA_INDEX_DODGING_FILE = 'dodging_file'; - /** - * @var bool - */ - protected $editElementOccuranceEnabled = false; - - /** - * @var bool - */ - protected $editElementOrderEnabled = false; - - /** - * @var array - */ - protected $suffixes = array(); - - protected $imageRemovalCommand = 'removeImage'; - - protected $imageUploadCommand = 'uploadImage'; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + const RENDERING_TEMPLATE = 'tpl.prop_multi_image_inp.html'; + + const ITERATOR_SUBFIELD_NAME = 'iteratorfield'; + const STORED_IMAGE_SUBFIELD_NAME = 'storedimage'; + const IMAGE_UPLOAD_SUBFIELD_NAME = 'imageupload'; + + const FILE_DATA_INDEX_DODGING_FILE = 'dodging_file'; + /** + * @var bool + */ + protected $editElementOccuranceEnabled = false; + + /** + * @var bool + */ + protected $editElementOrderEnabled = false; + + /** + * @var array + */ + protected $suffixes = array(); + + protected $imageRemovalCommand = 'removeImage'; + + protected $imageUploadCommand = 'uploadImage'; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - parent::__construct($a_title, $a_postvar); - - $this->setSuffixes(array("jpg", "jpeg", "png", "gif")); - $this->setSize('25'); - $this->validationRegexp = ""; + $this->lng = $DIC->language(); + parent::__construct($a_title, $a_postvar); + + $this->setSuffixes(array("jpg", "jpeg", "png", "gif")); + $this->setSize('25'); + $this->validationRegexp = ""; - require_once 'Services/Form/classes/class.ilMultipleImagesAdditionalIndexLevelRemover.php'; - $manipulator = new ilMultipleImagesAdditionalIndexLevelRemover(); - $manipulator->setPostVar($this->getPostVar()); - $this->addFormValuesManipulator($manipulator); + require_once 'Services/Form/classes/class.ilMultipleImagesAdditionalIndexLevelRemover.php'; + $manipulator = new ilMultipleImagesAdditionalIndexLevelRemover(); + $manipulator->setPostVar($this->getPostVar()); + $this->addFormValuesManipulator($manipulator); - require_once 'Services/Form/classes/class.ilMultipleImagesFileSubmissionDataCompletion.php'; - $manipulator = new ilMultipleImagesFileSubmissionDataCompletion(); - $manipulator->setPostVar($this->getPostVar()); - $this->addFormValuesManipulator($manipulator); - - require_once 'Services/Form/classes/class.ilIdentifiedMultiFilesJsPositionIndexRemover.php'; - $manipulator = new ilIdentifiedMultiFilesJsPositionIndexRemover(); - $manipulator->setPostVar($this->getPostVar()); - $this->addFormValuesManipulator($manipulator); - - require_once 'Services/Form/classes/class.ilMultiFilesSubmitRecursiveSlashesStripper.php'; - $manipulator = new ilMultiFilesSubmitRecursiveSlashesStripper(); - $manipulator->setPostVar($this->getPostVar()); - $this->addFormValuesManipulator($manipulator); - } - - /** - * Set Accepted Suffixes. - * - * @param array $a_suffixes Accepted Suffixes - */ - function setSuffixes($a_suffixes) - { - $this->suffixes = $a_suffixes; - } - - /** - * Get Accepted Suffixes. - * - * @return array Accepted Suffixes - */ - function getSuffixes() - { - return $this->suffixes; - } - - /** - * @return string - */ - public function getImageRemovalCommand() - { - return $this->imageRemovalCommand; - } - - /** - * @param string $imageRemovalCommand - */ - public function setImageRemovalCommand($imageRemovalCommand) - { - $this->imageRemovalCommand = $imageRemovalCommand; - } - - /** - * @return string - */ - public function getImageUploadCommand() - { - return $this->imageUploadCommand; - } - - /** - * @param string $imageUploadCommand - */ - public function setImageUploadCommand($imageUploadCommand) - { - $this->imageUploadCommand = $imageUploadCommand; - } - - /** - * @return boolean $editElementOccuranceEnabled - */ - public function isEditElementOccuranceEnabled() - { - return $this->editElementOccuranceEnabled; - } - - /** - * @param boolean $editElementOccuranceEnabled - */ - public function setEditElementOccuranceEnabled($editElementOccuranceEnabled) - { - $this->editElementOccuranceEnabled = $editElementOccuranceEnabled; - } - - /** - * @return boolean - */ - public function isEditElementOrderEnabled() - { - return $this->editElementOrderEnabled; - } - - /** - * @param boolean $editElementOrderEnabled - */ - public function setEditElementOrderEnabled($editElementOrderEnabled) - { - $this->editElementOrderEnabled = $editElementOrderEnabled; - } - - /** - * @param mixed $value - * @return bool - */ - abstract protected function isValidFilenameInput($filenameInput); - - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean $validationSuccess - */ - function onCheckInput() - { - $lng = $GLOBALS['DIC'] ? $GLOBALS['DIC']['lng'] : $GLOBALS['lng']; - $F = $_FILES[$this->getPostVar()]; - if($F && isset($_REQUEST[$this->getPostVar()][self::FILE_DATA_INDEX_DODGING_FILE])) - { - $F = array_merge(array(self::FILE_DATA_INDEX_DODGING_FILE => $_REQUEST[$this->getPostVar()][self::FILE_DATA_INDEX_DODGING_FILE]), $F); - } + require_once 'Services/Form/classes/class.ilMultipleImagesFileSubmissionDataCompletion.php'; + $manipulator = new ilMultipleImagesFileSubmissionDataCompletion(); + $manipulator->setPostVar($this->getPostVar()); + $this->addFormValuesManipulator($manipulator); + + require_once 'Services/Form/classes/class.ilIdentifiedMultiFilesJsPositionIndexRemover.php'; + $manipulator = new ilIdentifiedMultiFilesJsPositionIndexRemover(); + $manipulator->setPostVar($this->getPostVar()); + $this->addFormValuesManipulator($manipulator); + + require_once 'Services/Form/classes/class.ilMultiFilesSubmitRecursiveSlashesStripper.php'; + $manipulator = new ilMultiFilesSubmitRecursiveSlashesStripper(); + $manipulator->setPostVar($this->getPostVar()); + $this->addFormValuesManipulator($manipulator); + } + + /** + * Set Accepted Suffixes. + * + * @param array $a_suffixes Accepted Suffixes + */ + public function setSuffixes($a_suffixes) + { + $this->suffixes = $a_suffixes; + } + + /** + * Get Accepted Suffixes. + * + * @return array Accepted Suffixes + */ + public function getSuffixes() + { + return $this->suffixes; + } + + /** + * @return string + */ + public function getImageRemovalCommand() + { + return $this->imageRemovalCommand; + } + + /** + * @param string $imageRemovalCommand + */ + public function setImageRemovalCommand($imageRemovalCommand) + { + $this->imageRemovalCommand = $imageRemovalCommand; + } + + /** + * @return string + */ + public function getImageUploadCommand() + { + return $this->imageUploadCommand; + } + + /** + * @param string $imageUploadCommand + */ + public function setImageUploadCommand($imageUploadCommand) + { + $this->imageUploadCommand = $imageUploadCommand; + } + + /** + * @return boolean $editElementOccuranceEnabled + */ + public function isEditElementOccuranceEnabled() + { + return $this->editElementOccuranceEnabled; + } + + /** + * @param boolean $editElementOccuranceEnabled + */ + public function setEditElementOccuranceEnabled($editElementOccuranceEnabled) + { + $this->editElementOccuranceEnabled = $editElementOccuranceEnabled; + } + + /** + * @return boolean + */ + public function isEditElementOrderEnabled() + { + return $this->editElementOrderEnabled; + } + + /** + * @param boolean $editElementOrderEnabled + */ + public function setEditElementOrderEnabled($editElementOrderEnabled) + { + $this->editElementOrderEnabled = $editElementOrderEnabled; + } + + /** + * @param mixed $value + * @return bool + */ + abstract protected function isValidFilenameInput($filenameInput); + + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean $validationSuccess + */ + public function onCheckInput() + { + $lng = $GLOBALS['DIC'] ? $GLOBALS['DIC']['lng'] : $GLOBALS['lng']; + $F = $_FILES[$this->getPostVar()]; + if ($F && isset($_REQUEST[$this->getPostVar()][self::FILE_DATA_INDEX_DODGING_FILE])) { + $F = array_merge(array(self::FILE_DATA_INDEX_DODGING_FILE => $_REQUEST[$this->getPostVar()][self::FILE_DATA_INDEX_DODGING_FILE]), $F); + } - if( $this->getRequired() && !is_array($F['error']) ) - { - $this->setAlert($lng->txt("form_msg_file_no_upload")); - return false; - } - else foreach( $F['error'] as $index => $error ) - { - // error handling - if ($error > 0) - { - switch ($error) - { - case UPLOAD_ERR_INI_SIZE: - $this->setAlert($lng->txt("form_msg_file_size_exceeds")); - return false; - break; - - case UPLOAD_ERR_FORM_SIZE: - $this->setAlert($lng->txt("form_msg_file_size_exceeds")); - return false; - break; - - case UPLOAD_ERR_PARTIAL: - $this->setAlert($lng->txt("form_msg_file_partially_uploaded")); - return false; - break; - - case UPLOAD_ERR_NO_FILE: - if( !$this->getRequired() ) - { - break; - } - elseif( strlen($F[self::FILE_DATA_INDEX_DODGING_FILE][$index]) ) - { - break; - } - $this->setAlert($lng->txt("form_msg_file_no_upload")); - return false; - break; - - case UPLOAD_ERR_NO_TMP_DIR: - $this->setAlert($lng->txt("form_msg_file_missing_tmp_dir")); - return false; - break; - - case UPLOAD_ERR_CANT_WRITE: - $this->setAlert($lng->txt("form_msg_file_cannot_write_to_disk")); - return false; - break; - - case UPLOAD_ERR_EXTENSION: - $this->setAlert($lng->txt("form_msg_file_upload_stopped_ext")); - return false; - break; - } - } - } - - if (is_array($F['tmp_name'])) - { - foreach ($F['tmp_name'] as $index => $tmpname) - { - $filename = $F['name'][$index]; - $filename_arr = pathinfo($filename); - $suffix = $filename_arr["extension"]; - $mimetype = $F['type'][$index]; - $size_bytes = $F['size'][$index]; - // check suffixes - if (strlen($tmpname) && is_array($this->getSuffixes())) - { - if (!in_array(strtolower($suffix), $this->getSuffixes())) - { - $this->setAlert($lng->txt("form_msg_file_wrong_file_type")); - return false; - } - } - } - } - - foreach ($F['tmp_name'] as $index => $tmpname) - { - $filename = $F['name'][$index]; - $filename_arr = pathinfo($filename); - $suffix = $filename_arr["extension"]; - $mimetype = $F['type'][$index]; - $size_bytes = $F['size'][$index]; - // virus handling - if (strlen($tmpname)) - { - $vir = ilUtil::virusHandling($tmpname, $filename); - if ($vir[0] == false) - { - $this->setAlert($lng->txt("form_msg_file_virus_found")."
                  ".$vir[1]); - return false; - } - } - } - - return $this->checkSubItemsInput(); - } - - /** - * @param string $mode - * @return string - */ - public function render($a_mode = "") - { - $lng = $this->lng; - - $tpl = $this->getTemplate(); - $i = 0; - foreach ($this->getIdentifiedMultiValues() as $identifier => $value) - { - if( $this->valueHasContentImageSource($value) ) - { - $tpl->setCurrentBlock('image'); - - $tpl->setVariable('STORED_IMAGE_SRC', $this->fetchContentImageSourceFromValue($value)); - $tpl->setVariable('STORED_IMAGE_ALT', ilUtil::prepareFormOutput($this->fetchContentImageTitleFromValue($value))); - $tpl->setVariable('STORED_IMAGE_FILENAME', $this->fetchContentImageTitleFromValue($value)); - $tpl->setVariable("STORED_IMAGE_POST_VAR", $this->getMultiValuePostVarSubFieldPosIndexed($identifier, self::STORED_IMAGE_SUBFIELD_NAME, $i)); - - $tpl->setVariable("TXT_DELETE_EXISTING", $lng->txt("delete_existing_file")); - $tpl->setVariable("IMAGE_CMD_REMOVE", $this->buildMultiValueSubmitVar($identifier, $i, $this->getImageRemovalCommand())); - - $tpl->parseCurrentBlock(); - } - - $tpl->setCurrentBlock('addimage'); - - $tpl->setVariable("IMAGE_BROWSE", $lng->txt('select_file')); - $tpl->setVariable("IMAGE_ID", $this->getMultiValuePosIndexedSubFieldId($identifier, self::IMAGE_UPLOAD_SUBFIELD_NAME, $i)); - $tpl->setVariable("TXT_IMAGE_SUBMIT", $lng->txt("upload")); - $tpl->setVariable("IMAGE_CMD_UPLOAD", $this->buildMultiValueSubmitVar($identifier, $i, $this->getImageUploadCommand())); - $tpl->setVariable("UPLOAD_IMAGE_POST_VAR", $this->getMultiValuePostVarSubFieldPosIndexed($identifier, self::IMAGE_UPLOAD_SUBFIELD_NAME, $i)); - $tpl->setVariable("COUNT_POST_VAR", $this->getMultiValuePostVarSubFieldPosIndexed($identifier, self::ITERATOR_SUBFIELD_NAME, $i)); - - $tpl->parseCurrentBlock(); - - if( $this->isEditElementOrderEnabled() ) - { - $tpl->setCurrentBlock("move"); - $tpl->setVariable("ID_UP", $this->getMultiValuePosIndexedSubFieldId($identifier, 'up', $i)); - $tpl->setVariable("ID_DOWN", $this->getMultiValuePosIndexedSubFieldId($identifier, 'down', $i)); - $tpl->setVariable("CMD_UP", $this->buildMultiValueSubmitVar($identifier, $i, 'up')); - $tpl->setVariable("CMD_DOWN", $this->buildMultiValueSubmitVar($identifier, $i, 'down')); - $tpl->setVariable("UP_BUTTON", ilGlyphGUI::get(ilGlyphGUI::UP)); - $tpl->setVariable("DOWN_BUTTON", ilGlyphGUI::get(ilGlyphGUI::DOWN)); - $tpl->parseCurrentBlock(); - } - - if( $this->isEditElementOccuranceEnabled() ) - { - $tpl->setCurrentBlock("row"); - $tpl->setVariable("ID_ADD", $this->getMultiValuePosIndexedSubFieldId($identifier, 'add', $i)); - $tpl->setVariable("ID_REMOVE", $this->getMultiValuePosIndexedSubFieldId($identifier, 'remove', $i)); - $tpl->setVariable("CMD_ADD", $this->buildMultiValueSubmitVar($identifier, $i, 'add')); - $tpl->setVariable("CMD_REMOVE", $this->buildMultiValueSubmitVar($identifier, $i, 'remove')); - $tpl->setVariable("ADD_BUTTON", ilGlyphGUI::get(ilGlyphGUI::ADD)); - $tpl->setVariable("REMOVE_BUTTON", ilGlyphGUI::get(ilGlyphGUI::REMOVE)); - $tpl->parseCurrentBlock(); - } - - $i++; - } - - if (is_array($this->getSuffixes())) - { - $suff_str = $delim = ""; - foreach($this->getSuffixes() as $suffix) - { - $suff_str.= $delim.".".$suffix; - $delim = ", "; - } - $tpl->setCurrentBlock('allowed_image_suffixes'); - $tpl->setVariable("TXT_ALLOWED_SUFFIXES", $lng->txt("file_allowed_suffixes")." ".$suff_str); - $tpl->parseCurrentBlock(); - } - /* - $tpl->setCurrentBlock("image_heading"); - $tpl->setVariable("ANSWER_IMAGE", $lng->txt('answer_image')); - $tpl->parseCurrentBlock(); - */ - - $tpl->setVariable("TXT_MAX_SIZE", ilUtil::getFileSizeInfo()); - $tpl->setVariable("ELEMENT_ID", $this->getPostVar()); - $tpl->setVariable("TEXT_YES", $lng->txt('yes')); - $tpl->setVariable("TEXT_NO", $lng->txt('no')); - $tpl->setVariable("DELETE_IMAGE_HEADER", $lng->txt('delete_image_header')); - $tpl->setVariable("DELETE_IMAGE_QUESTION", $lng->txt('delete_image_question')); - $tpl->setVariable("ANSWER_TEXT", $lng->txt('answer_text')); - $tpl->setVariable("COMMANDS_TEXT", $lng->txt('actions')); - - if (!$this->getDisabled()) - { - $tpl->setCurrentBlock('js_engine_initialisation'); - $tpl->setVariable('UPLOAD_CMD', $this->getImageUploadCommand()); - $tpl->setVariable('REMOVE_CMD', $this->getImageRemovalCommand()); - $tpl->setVariable('ITERATOR', self::ITERATOR_SUBFIELD_NAME); - $tpl->setVariable('STORED_IMAGE_POSTVAR', self::STORED_IMAGE_SUBFIELD_NAME); - $tpl->setVariable('UPLOAD_IMAGE_POSTVAR', self::IMAGE_UPLOAD_SUBFIELD_NAME); - $tpl->parseCurrentBlock(); + if ($this->getRequired() && !is_array($F['error'])) { + $this->setAlert($lng->txt("form_msg_file_no_upload")); + return false; + } else { + foreach ($F['error'] as $index => $error) { + // error handling + if ($error > 0) { + switch ($error) { + case UPLOAD_ERR_INI_SIZE: + $this->setAlert($lng->txt("form_msg_file_size_exceeds")); + return false; + break; + + case UPLOAD_ERR_FORM_SIZE: + $this->setAlert($lng->txt("form_msg_file_size_exceeds")); + return false; + break; + + case UPLOAD_ERR_PARTIAL: + $this->setAlert($lng->txt("form_msg_file_partially_uploaded")); + return false; + break; + + case UPLOAD_ERR_NO_FILE: + if (!$this->getRequired()) { + break; + } elseif (strlen($F[self::FILE_DATA_INDEX_DODGING_FILE][$index])) { + break; + } + $this->setAlert($lng->txt("form_msg_file_no_upload")); + return false; + break; + + case UPLOAD_ERR_NO_TMP_DIR: + $this->setAlert($lng->txt("form_msg_file_missing_tmp_dir")); + return false; + break; + + case UPLOAD_ERR_CANT_WRITE: + $this->setAlert($lng->txt("form_msg_file_cannot_write_to_disk")); + return false; + break; + + case UPLOAD_ERR_EXTENSION: + $this->setAlert($lng->txt("form_msg_file_upload_stopped_ext")); + return false; + break; + } + } + } + } + + if (is_array($F['tmp_name'])) { + foreach ($F['tmp_name'] as $index => $tmpname) { + $filename = $F['name'][$index]; + $filename_arr = pathinfo($filename); + $suffix = $filename_arr["extension"]; + $mimetype = $F['type'][$index]; + $size_bytes = $F['size'][$index]; + // check suffixes + if (strlen($tmpname) && is_array($this->getSuffixes())) { + if (!in_array(strtolower($suffix), $this->getSuffixes())) { + $this->setAlert($lng->txt("form_msg_file_wrong_file_type")); + return false; + } + } + } + } + + foreach ($F['tmp_name'] as $index => $tmpname) { + $filename = $F['name'][$index]; + $filename_arr = pathinfo($filename); + $suffix = $filename_arr["extension"]; + $mimetype = $F['type'][$index]; + $size_bytes = $F['size'][$index]; + // virus handling + if (strlen($tmpname)) { + $vir = ilUtil::virusHandling($tmpname, $filename); + if ($vir[0] == false) { + $this->setAlert($lng->txt("form_msg_file_virus_found") . "
                  " . $vir[1]); + return false; + } + } + } + + return $this->checkSubItemsInput(); + } + + /** + * @param string $mode + * @return string + */ + public function render($a_mode = "") + { + $lng = $this->lng; + + $tpl = $this->getTemplate(); + $i = 0; + foreach ($this->getIdentifiedMultiValues() as $identifier => $value) { + if ($this->valueHasContentImageSource($value)) { + $tpl->setCurrentBlock('image'); + + $tpl->setVariable('STORED_IMAGE_SRC', $this->fetchContentImageSourceFromValue($value)); + $tpl->setVariable('STORED_IMAGE_ALT', ilUtil::prepareFormOutput($this->fetchContentImageTitleFromValue($value))); + $tpl->setVariable('STORED_IMAGE_FILENAME', $this->fetchContentImageTitleFromValue($value)); + $tpl->setVariable("STORED_IMAGE_POST_VAR", $this->getMultiValuePostVarSubFieldPosIndexed($identifier, self::STORED_IMAGE_SUBFIELD_NAME, $i)); + + $tpl->setVariable("TXT_DELETE_EXISTING", $lng->txt("delete_existing_file")); + $tpl->setVariable("IMAGE_CMD_REMOVE", $this->buildMultiValueSubmitVar($identifier, $i, $this->getImageRemovalCommand())); + + $tpl->parseCurrentBlock(); + } + + $tpl->setCurrentBlock('addimage'); + + $tpl->setVariable("IMAGE_BROWSE", $lng->txt('select_file')); + $tpl->setVariable("IMAGE_ID", $this->getMultiValuePosIndexedSubFieldId($identifier, self::IMAGE_UPLOAD_SUBFIELD_NAME, $i)); + $tpl->setVariable("TXT_IMAGE_SUBMIT", $lng->txt("upload")); + $tpl->setVariable("IMAGE_CMD_UPLOAD", $this->buildMultiValueSubmitVar($identifier, $i, $this->getImageUploadCommand())); + $tpl->setVariable("UPLOAD_IMAGE_POST_VAR", $this->getMultiValuePostVarSubFieldPosIndexed($identifier, self::IMAGE_UPLOAD_SUBFIELD_NAME, $i)); + $tpl->setVariable("COUNT_POST_VAR", $this->getMultiValuePostVarSubFieldPosIndexed($identifier, self::ITERATOR_SUBFIELD_NAME, $i)); + + $tpl->parseCurrentBlock(); + + if ($this->isEditElementOrderEnabled()) { + $tpl->setCurrentBlock("move"); + $tpl->setVariable("ID_UP", $this->getMultiValuePosIndexedSubFieldId($identifier, 'up', $i)); + $tpl->setVariable("ID_DOWN", $this->getMultiValuePosIndexedSubFieldId($identifier, 'down', $i)); + $tpl->setVariable("CMD_UP", $this->buildMultiValueSubmitVar($identifier, $i, 'up')); + $tpl->setVariable("CMD_DOWN", $this->buildMultiValueSubmitVar($identifier, $i, 'down')); + $tpl->setVariable("UP_BUTTON", ilGlyphGUI::get(ilGlyphGUI::UP)); + $tpl->setVariable("DOWN_BUTTON", ilGlyphGUI::get(ilGlyphGUI::DOWN)); + $tpl->parseCurrentBlock(); + } + + if ($this->isEditElementOccuranceEnabled()) { + $tpl->setCurrentBlock("row"); + $tpl->setVariable("ID_ADD", $this->getMultiValuePosIndexedSubFieldId($identifier, 'add', $i)); + $tpl->setVariable("ID_REMOVE", $this->getMultiValuePosIndexedSubFieldId($identifier, 'remove', $i)); + $tpl->setVariable("CMD_ADD", $this->buildMultiValueSubmitVar($identifier, $i, 'add')); + $tpl->setVariable("CMD_REMOVE", $this->buildMultiValueSubmitVar($identifier, $i, 'remove')); + $tpl->setVariable("ADD_BUTTON", ilGlyphGUI::get(ilGlyphGUI::ADD)); + $tpl->setVariable("REMOVE_BUTTON", ilGlyphGUI::get(ilGlyphGUI::REMOVE)); + $tpl->parseCurrentBlock(); + } + + $i++; + } + + if (is_array($this->getSuffixes())) { + $suff_str = $delim = ""; + foreach ($this->getSuffixes() as $suffix) { + $suff_str.= $delim . "." . $suffix; + $delim = ", "; + } + $tpl->setCurrentBlock('allowed_image_suffixes'); + $tpl->setVariable("TXT_ALLOWED_SUFFIXES", $lng->txt("file_allowed_suffixes") . " " . $suff_str); + $tpl->parseCurrentBlock(); + } + /* + $tpl->setCurrentBlock("image_heading"); + $tpl->setVariable("ANSWER_IMAGE", $lng->txt('answer_image')); + $tpl->parseCurrentBlock(); + */ + + $tpl->setVariable("TXT_MAX_SIZE", ilUtil::getFileSizeInfo()); + $tpl->setVariable("ELEMENT_ID", $this->getPostVar()); + $tpl->setVariable("TEXT_YES", $lng->txt('yes')); + $tpl->setVariable("TEXT_NO", $lng->txt('no')); + $tpl->setVariable("DELETE_IMAGE_HEADER", $lng->txt('delete_image_header')); + $tpl->setVariable("DELETE_IMAGE_QUESTION", $lng->txt('delete_image_question')); + $tpl->setVariable("ANSWER_TEXT", $lng->txt('answer_text')); + $tpl->setVariable("COMMANDS_TEXT", $lng->txt('actions')); + + if (!$this->getDisabled()) { + $tpl->setCurrentBlock('js_engine_initialisation'); + $tpl->setVariable('UPLOAD_CMD', $this->getImageUploadCommand()); + $tpl->setVariable('REMOVE_CMD', $this->getImageRemovalCommand()); + $tpl->setVariable('ITERATOR', self::ITERATOR_SUBFIELD_NAME); + $tpl->setVariable('STORED_IMAGE_POSTVAR', self::STORED_IMAGE_SUBFIELD_NAME); + $tpl->setVariable('UPLOAD_IMAGE_POSTVAR', self::IMAGE_UPLOAD_SUBFIELD_NAME); + $tpl->parseCurrentBlock(); - $globalTpl = $GLOBALS['DIC'] ? $GLOBALS['DIC']['tpl'] : $GLOBALS['tpl']; - $globalTpl->addJavascript("./Services/Form/js/ServiceFormWizardInput.js"); - $globalTpl->addJavascript("./Services/Form/js/ServiceFormIdentifiedWizardInputExtend.js"); - //$globalTpl->addJavascript("./Services/Form/js/ServiceFormIdentifiedImageWizardInputConcrete.js"); - } - - return $tpl->get(); - } - - /** - * @param $value - * @return bool - */ - protected function valueHasContentImageSource($value) - { - return isset($value['src']) && strlen($value['src']); - } - - /** - * @param $value - * @return string - */ - protected function fetchContentImageSourceFromValue($value) - { - if( $this->valueHasContentImageSource($value) ) - { - return $value['src']; - } - - return null; - } - - /** - * @param $value - * @return bool - */ - protected function valueHasContentImageTitle($value) - { - return isset($value['title']) && strlen($value['title']); - } - - /** - * @param string $value - */ - protected function fetchContentImageTitleFromValue($value) - { - if( $this->valueHasContentImageTitle($value) ) - { - return $value['title']; - } - - return $this->fetchContentImageSourceFromValue($value); - } - - /** - * @return ilTemplate - */ - protected function getTemplate() - { - return new ilTemplate(self::RENDERING_TEMPLATE, true, true, "Services/Form"); - } -} \ No newline at end of file + $globalTpl = $GLOBALS['DIC'] ? $GLOBALS['DIC']['tpl'] : $GLOBALS['tpl']; + $globalTpl->addJavascript("./Services/Form/js/ServiceFormWizardInput.js"); + $globalTpl->addJavascript("./Services/Form/js/ServiceFormIdentifiedWizardInputExtend.js"); + //$globalTpl->addJavascript("./Services/Form/js/ServiceFormIdentifiedImageWizardInputConcrete.js"); + } + + return $tpl->get(); + } + + /** + * @param $value + * @return bool + */ + protected function valueHasContentImageSource($value) + { + return isset($value['src']) && strlen($value['src']); + } + + /** + * @param $value + * @return string + */ + protected function fetchContentImageSourceFromValue($value) + { + if ($this->valueHasContentImageSource($value)) { + return $value['src']; + } + + return null; + } + + /** + * @param $value + * @return bool + */ + protected function valueHasContentImageTitle($value) + { + return isset($value['title']) && strlen($value['title']); + } + + /** + * @param string $value + */ + protected function fetchContentImageTitleFromValue($value) + { + if ($this->valueHasContentImageTitle($value)) { + return $value['title']; + } + + return $this->fetchContentImageSourceFromValue($value); + } + + /** + * @return ilTemplate + */ + protected function getTemplate() + { + return new ilTemplate(self::RENDERING_TEMPLATE, true, true, "Services/Form"); + } +} diff --git a/Services/Form/classes/class.ilMultipleNestedOrderingElementsAdditionalIndexLevelRemover.php b/Services/Form/classes/class.ilMultipleNestedOrderingElementsAdditionalIndexLevelRemover.php index 4a58e5c182c63a3e76e929954bdd611387ad409c..98caf5116e43a245162b1dfb39bd1be9bc14b04c 100644 --- a/Services/Form/classes/class.ilMultipleNestedOrderingElementsAdditionalIndexLevelRemover.php +++ b/Services/Form/classes/class.ilMultipleNestedOrderingElementsAdditionalIndexLevelRemover.php @@ -11,58 +11,51 @@ require_once 'Services/Form/interfaces/interface.ilFormValuesManipulator.php'; */ class ilMultipleNestedOrderingElementsAdditionalIndexLevelRemover implements ilFormValuesManipulator { - public function manipulateFormInputValues($inputValues) - { - return $inputValues; - } - - public function manipulateFormSubmitValues($submitValues) - { - return $this->fetchIndentationsFromSubmitValues($submitValues); - } - - protected function hasContentSubLevel($values) - { - if( !is_array($values) || !isset($values['content']) ) - { - return false; - } - - return true; - } - - protected function hasIndentationsSubLevel($values) - { - if( !is_array($values) || !isset($values['indentation']) ) - { - return false; - } - - return true; - } - - protected function fetchIndentationsFromSubmitValues($values) - { - if( $this->hasContentSubLevel($values) && $this->hasIndentationsSubLevel($values) ) - { - $actualValues = array(); - - foreach($values['content'] as $key => $value) - { - if( !isset($values['indentation'][$key]) ) - { - $actualValues[$key] = null; - continue; - } - - $actualValues[$key] = $values['indentation'][$key]; - } - } - else - { - $actualValues = $values; - } - - return $actualValues; - } -} \ No newline at end of file + public function manipulateFormInputValues($inputValues) + { + return $inputValues; + } + + public function manipulateFormSubmitValues($submitValues) + { + return $this->fetchIndentationsFromSubmitValues($submitValues); + } + + protected function hasContentSubLevel($values) + { + if (!is_array($values) || !isset($values['content'])) { + return false; + } + + return true; + } + + protected function hasIndentationsSubLevel($values) + { + if (!is_array($values) || !isset($values['indentation'])) { + return false; + } + + return true; + } + + protected function fetchIndentationsFromSubmitValues($values) + { + if ($this->hasContentSubLevel($values) && $this->hasIndentationsSubLevel($values)) { + $actualValues = array(); + + foreach ($values['content'] as $key => $value) { + if (!isset($values['indentation'][$key])) { + $actualValues[$key] = null; + continue; + } + + $actualValues[$key] = $values['indentation'][$key]; + } + } else { + $actualValues = $values; + } + + return $actualValues; + } +} diff --git a/Services/Form/classes/class.ilMultipleNestedOrderingElementsInputGUI.php b/Services/Form/classes/class.ilMultipleNestedOrderingElementsInputGUI.php index 8cba24f52b035b2802c9e8c8b716de055ffd2f32..48ba630ae93b87b0306ca8fb5e5ccf03d5c438f2 100644 --- a/Services/Form/classes/class.ilMultipleNestedOrderingElementsInputGUI.php +++ b/Services/Form/classes/class.ilMultipleNestedOrderingElementsInputGUI.php @@ -12,502 +12,466 @@ require_once 'Modules/Test/classes/inc.AssessmentConstants.php'; abstract class ilMultipleNestedOrderingElementsInputGUI extends ilIdentifiedMultiValuesInputGUI { - const HTML_LIST_TAG_UL = 'ul'; - const HTML_LIST_TAG_OL = 'ol'; - - const CSS_LIST_CLASS = 'dd-list'; - const CSS_ITEM_CLASS = 'dd-item'; - const CSS_HANDLE_CLASS = 'dd-handle'; - - const POSTVAR_SUBFIELD_NEST_ELEM = 'content'; - const POSTVAR_SUBFIELD_NEST_INDENT = 'indentation'; - - const DEFAULT_INSTANCE_ID = 'default'; - - protected $instanceId = self::DEFAULT_INSTANCE_ID; - - protected $interactionEnabled = true; - - protected $nestingEnabled = true; - - protected $stylingDisabled = false; - - protected $listTpl = null; - - protected $cssListClass = self::CSS_LIST_CLASS; - - protected $cssItemClass = self::CSS_ITEM_CLASS; - - protected $cssHandleClass = self::CSS_HANDLE_CLASS; - - protected $htmlListTag = self::HTML_LIST_TAG_OL; - - public function __construct($a_title = '', $a_postvar = '') - { - parent::__construct($a_title, $a_postvar); - - require_once 'Services/Form/classes/class.ilMultipleNestedOrderingElementsAdditionalIndexLevelRemover.php'; - $manipulator = new ilMultipleNestedOrderingElementsAdditionalIndexLevelRemover(); - $this->addFormValuesManipulator($manipulator); - } + const HTML_LIST_TAG_UL = 'ul'; + const HTML_LIST_TAG_OL = 'ol'; + + const CSS_LIST_CLASS = 'dd-list'; + const CSS_ITEM_CLASS = 'dd-item'; + const CSS_HANDLE_CLASS = 'dd-handle'; + + const POSTVAR_SUBFIELD_NEST_ELEM = 'content'; + const POSTVAR_SUBFIELD_NEST_INDENT = 'indentation'; + + const DEFAULT_INSTANCE_ID = 'default'; + + protected $instanceId = self::DEFAULT_INSTANCE_ID; + + protected $interactionEnabled = true; + + protected $nestingEnabled = true; + + protected $stylingDisabled = false; + + protected $listTpl = null; + + protected $cssListClass = self::CSS_LIST_CLASS; + + protected $cssItemClass = self::CSS_ITEM_CLASS; + + protected $cssHandleClass = self::CSS_HANDLE_CLASS; + + protected $htmlListTag = self::HTML_LIST_TAG_OL; + + public function __construct($a_title = '', $a_postvar = '') + { + parent::__construct($a_title, $a_postvar); + + require_once 'Services/Form/classes/class.ilMultipleNestedOrderingElementsAdditionalIndexLevelRemover.php'; + $manipulator = new ilMultipleNestedOrderingElementsAdditionalIndexLevelRemover(); + $this->addFormValuesManipulator($manipulator); + } - public function setInstanceId($instanceId) - { - $this->instanceId = $instanceId; - } + public function setInstanceId($instanceId) + { + $this->instanceId = $instanceId; + } - public function getInstanceId() - { - return $this->instanceId; - } - - public function setInteractionEnabled($interactionEnabled) - { - $this->interactionEnabled = $interactionEnabled; - } - - public function isInteractionEnabled() - { - return $this->interactionEnabled; - } - - public function isNestingEnabled() - { - return $this->nestingEnabled; - } - - public function setNestingEnabled($nestingEnabled) - { - $this->nestingEnabled = $nestingEnabled; - } - - public function isStylingDisabled() - { - return $this->stylingDisabled; - } - - public function setStylingDisabled($stylingDisabled) - { - $this->stylingDisabled = $stylingDisabled; - } - - protected function isStylingEnabled() - { - return !$this->isStylingDisabled(); - } - - /** - * @return string - */ - public function getCssListClass() - { - return $this->cssListClass; - } - - /** - * @param string $cssListClass - */ - public function setCssListClass($cssListClass) - { - $this->cssListClass = $cssListClass; - } - - /** - * @return string - */ - public function getCssItemClass() - { - return $this->cssItemClass; - } - - /** - * @return string - */ - public function getCssHandleClass() - { - return $this->cssHandleClass; - } - - /** - * @param string $cssHandleClass - */ - public function setCssHandleClass($cssHandleClass) - { - $this->cssHandleClass = $cssHandleClass; - } - - /** - * @param string $cssItemClass - */ - public function setCssItemClass($cssItemClass) - { - $this->cssItemClass = $cssItemClass; - } - - /** - * @return string - */ - public function getHtmlListTag() - { - return $this->htmlListTag; - } - - /** - * @param string $htmlListTag - */ - public function setHtmlListTag($htmlListTag) - { - $this->htmlListTag = $htmlListTag; - } - - /** - * @return ilTemplate - */ - protected function getGlobalTpl() - { - return isset($GLOBALS['DIC']) ? $GLOBALS['DIC']['tpl'] : $GLOBALS['tpl']; - } - - /** - * @return ilTemplate - */ - public function getListTpl() - { - return $this->listTpl; - } - - /** - * @param ilTemplate $listTpl - */ - public function setListTpl($listTpl) - { - $this->listTpl = $listTpl; - } - - protected function initListTemplate() - { - $this->setListTpl( - new ilTemplate('tpl.prop_nested_ordering_list.html', true, true, 'Services/Form') - ); - } - - protected function fetchListHtml() - { - return $this->getListTpl()->get(); - } - - protected function renderListContainer() - { - $this->getListTpl()->setCurrentBlock('list_container'); - $this->getListTpl()->setVariable('INSTANCE_ID', $this->getInstanceId()); - $this->getListTpl()->parseCurrentBlock(); - } - - protected function renderListSnippet() - { - $this->getListTpl()->setCurrentBlock('list_snippet'); - $this->getListTpl()->parseCurrentBlock(); - } + public function getInstanceId() + { + return $this->instanceId; + } + + public function setInteractionEnabled($interactionEnabled) + { + $this->interactionEnabled = $interactionEnabled; + } + + public function isInteractionEnabled() + { + return $this->interactionEnabled; + } + + public function isNestingEnabled() + { + return $this->nestingEnabled; + } + + public function setNestingEnabled($nestingEnabled) + { + $this->nestingEnabled = $nestingEnabled; + } + + public function isStylingDisabled() + { + return $this->stylingDisabled; + } + + public function setStylingDisabled($stylingDisabled) + { + $this->stylingDisabled = $stylingDisabled; + } + + protected function isStylingEnabled() + { + return !$this->isStylingDisabled(); + } + + /** + * @return string + */ + public function getCssListClass() + { + return $this->cssListClass; + } + + /** + * @param string $cssListClass + */ + public function setCssListClass($cssListClass) + { + $this->cssListClass = $cssListClass; + } + + /** + * @return string + */ + public function getCssItemClass() + { + return $this->cssItemClass; + } + + /** + * @return string + */ + public function getCssHandleClass() + { + return $this->cssHandleClass; + } + + /** + * @param string $cssHandleClass + */ + public function setCssHandleClass($cssHandleClass) + { + $this->cssHandleClass = $cssHandleClass; + } + + /** + * @param string $cssItemClass + */ + public function setCssItemClass($cssItemClass) + { + $this->cssItemClass = $cssItemClass; + } + + /** + * @return string + */ + public function getHtmlListTag() + { + return $this->htmlListTag; + } + + /** + * @param string $htmlListTag + */ + public function setHtmlListTag($htmlListTag) + { + $this->htmlListTag = $htmlListTag; + } + + /** + * @return ilTemplate + */ + protected function getGlobalTpl() + { + return isset($GLOBALS['DIC']) ? $GLOBALS['DIC']['tpl'] : $GLOBALS['tpl']; + } + + /** + * @return ilTemplate + */ + public function getListTpl() + { + return $this->listTpl; + } + + /** + * @param ilTemplate $listTpl + */ + public function setListTpl($listTpl) + { + $this->listTpl = $listTpl; + } + + protected function initListTemplate() + { + $this->setListTpl( + new ilTemplate('tpl.prop_nested_ordering_list.html', true, true, 'Services/Form') + ); + } + + protected function fetchListHtml() + { + return $this->getListTpl()->get(); + } + + protected function renderListContainer() + { + $this->getListTpl()->setCurrentBlock('list_container'); + $this->getListTpl()->setVariable('INSTANCE_ID', $this->getInstanceId()); + $this->getListTpl()->parseCurrentBlock(); + } + + protected function renderListSnippet() + { + $this->getListTpl()->setCurrentBlock('list_snippet'); + $this->getListTpl()->parseCurrentBlock(); + } - protected function renderListItem($value, $identifier, $position) - { - $subPostVar = $this->getMultiValuePostVarSubField($identifier, self::POSTVAR_SUBFIELD_NEST_ELEM); - $subFieldId = $this->getMultiValueSubFieldId($identifier, self::POSTVAR_SUBFIELD_NEST_ELEM); - - $this->getListTpl()->setCurrentBlock('item_value'); - - $this->getListTpl()->setVariable('ILC_HANDLE_CSS_CLASS', $this->getCssHandleClass()); - - $this->getListTpl()->setVariable('LIST_ITEM_VALUE', $this->getItemHtml( - $value, $identifier, $position, $subPostVar, $subFieldId - )); - - $this->getListTpl()->parseCurrentBlock(); - - $this->renderListSnippet(); - } - - /** - * @param $value - * @param $identifier - * @param $position - * @param $itemSubFieldPostVar - * @param $itemSubFieldId - * @return mixed - */ - abstract protected function getItemHtml($value, $identifier, $position, $itemSubFieldPostVar, $itemSubFieldId); - - protected function renderBeginListItem($identifier) - { - $this->getListTpl()->setCurrentBlock('begin_list_item'); - $this->getListTpl()->setVariable('LIST_ITEM_ID', $identifier); - $this->getListTpl()->setVariable('ILC_ITEM_CSS_CLASS', $this->getCssItemClass()); - $this->getListTpl()->parseCurrentBlock(); - $this->renderListSnippet(); - } - - protected function renderEndListItem() - { - $this->getListTpl()->setCurrentBlock('end_list_item'); - $this->getListTpl()->touchBlock('end_list_item'); - $this->getListTpl()->parseCurrentBlock(); - $this->renderListSnippet(); - } - - protected function renderBeginSubList() - { - $this->getListTpl()->setCurrentBlock('begin_sublist'); - $this->getListTpl()->setVariable('BEGIN_HTML_LIST_TAG', $this->getHtmlListTag()); - $this->getListTpl()->setVariable('ILC_LIST_CSS_CLASS', $this->getCssListClass()); - $this->getListTpl()->parseCurrentBlock(); - $this->renderListSnippet(); - } - - protected function renderEndSubList() - { - $this->getListTpl()->setCurrentBlock('end_sublist'); - $this->getListTpl()->setVariable('END_HTML_LIST_TAG', $this->getHtmlListTag()); - $this->getListTpl()->parseCurrentBlock(); - $this->renderListSnippet(); - } - - /** - * @param array $elementValues - * @param integer $elementCounter - * @return integer $currentDepth - */ - abstract protected function getCurrentIndentation($elementValues, $elementCounter); - - /** - * @param array $elementValues - * @param integer $elementCounter - * @return integer $nextDepth - */ - abstract protected function getNextIndentation($elementValues, $elementCounter); - - protected function renderMainList() - { - $this->initListTemplate(); - $this->renderBeginSubList(); - - - $values = array_values($this->getIdentifiedMultiValues()); - $keys = array_keys($this->getIdentifiedMultiValues()); - $prevIndent = 0; - - foreach($values as $counter => $value) - { - $identifier = $keys[$counter]; - - if( $this->isNestingEnabled() ) - { - $curIndent = $this->getCurrentIndentation($values, $counter); - $nextIndent = $this->getNextIndentation($values, $counter); - } - else - { - $curIndent = $nextIndent = 0; - } - - if($prevIndent == $curIndent) - { - // pcn = Previous, Current, Next -> Depth - // pcn: 000, 001, 110, 220 - if($curIndent == $nextIndent) - { - // (1) pcn: 000 - // echo"(1)"; - $this->renderBeginListItem($identifier); - $this->renderListItem($value, $identifier, $counter); - $this->renderEndListItem(); - } - else if($curIndent > $nextIndent) - { - if($prevIndent == $nextIndent) - { - // wenn prev = cur ist und cur > next, wie soll prev = next sein !? - - // (8) pcn: 110 - // echo"(8)"; - $this->renderBeginListItem($identifier); - $this->renderListItem($value, $identifier, $counter); - $this->renderEndListItem(); - $this->renderEndSubList(); - $this->renderEndListItem(); - } - else if($prevIndent > $nextIndent) - { - // (12) pcn: 220 - // echo"(12)"; - $this->renderBeginListItem($identifier); - $this->renderListItem($value, $identifier, $counter); - - for($openlists = $nextIndent; $openlists < $curIndent; $openlists++) - { - $this->renderEndListItem(); - $this->renderEndSubList(); - $this->renderEndListItem(); - } - } - } - else if($curIndent < $nextIndent) - { - // (2) pcn: 001 - // echo"(2)"; - $this->renderBeginListItem($identifier); - $this->renderListItem($value, $identifier, $counter); - $this->renderBeginSubList(); - } - } - else if($prevIndent > $curIndent) - { - if($curIndent == $nextIndent) - { - // (6) pcn: 100 - // echo"(6)"; - $this->renderBeginListItem($identifier); - $this->renderListItem($value, $identifier, $counter); - $this->renderEndListItem(); - } - else if($curIndent > $nextIndent) - { - // (11) pcn: 210 - // echo"(11)"; - $this->renderBeginListItem($identifier); - $this->renderListItem($value, $identifier, $counter); - $this->renderEndListItem(); - $this->renderEndSubList(); - } - else if($curIndent < $nextIndent) - { - if($prevIndent == $nextIndent) - { - // (7) pcn: 101 - // echo"(7)"; - $this->renderBeginListItem($identifier); - $this->renderListItem($value, $identifier, $counter); - $this->renderBeginSubList(); - } - else if($prevIndent > $nextIndent) - { - // (10) pcn: 201 - // echo"(10)"; - $this->renderBeginListItem($identifier); - $this->renderListItem($value, $identifier, $counter); - for($openlists = $nextIndent; $openlists < $curIndent; $openlists++) - { - $this->renderEndSubList(); - } - $this->renderBeginSubList(); - } - } - } - else if($prevIndent < $curIndent) - { - if($curIndent == $nextIndent) - { - // (4) pcn: 011 - // echo"(4)"; - $this->renderBeginListItem($identifier); - $this->renderListItem($value, $identifier, $counter); - $this->renderEndListItem(); - } - else if($curIndent > $nextIndent) - { - if($prevIndent == $nextIndent) - { - // (3) pcn: 010, - // echo"(3)"; - $this->renderBeginListItem($identifier); - $this->renderListItem($value, $identifier, $counter); - $this->renderEndListItem(); - $this->renderEndSubList(); - $this->renderEndListItem(); - - } - else if($prevIndent > $nextIndent) - { - // (9) pcn: 120 - // echo"(9)"; - $this->renderBeginListItem($identifier); - $this->renderListItem($value, $identifier, $counter); - for($openlists = $nextIndent; $openlists < $curIndent; $openlists++) - { - $this->renderEndListItem(); - $this->renderEndSubList(); - } - } - } - else if($curIndent < $nextIndent) - { - // (5) pcn: 012 - // echo"(5)"; - $this->renderBeginListItem($identifier); - $this->renderListItem($value, $identifier, $counter); - $this->renderBeginSubList(); - } - } - - $prevIndent = $curIndent; - } - - $this->renderEndSubList(); - $this->renderListContainer(); - - return $this->fetchListHtml(); - } - - protected function renderJsInit() - { - $jsTpl = new ilTemplate('tpl.prop_nested_ordering_js.html', true, true, 'Services/Form'); - - if( !$this->isNestingEnabled() ) - { - $jsTpl->setCurrentBlock('avoid_nesting'); - $jsTpl->touchBlock('avoid_nesting'); - $jsTpl->parseCurrentBlock(); - } - - $jsTpl->setCurrentBlock('nested_ordering_init'); - $jsTpl->setVariable('INSTANCE_ID', $this->getInstanceId()); - $jsTpl->setVariable('INDENTATION_POSTVAR', $this->getPostVarSubField('indentation')); - $jsTpl->setVariable('HTML_LIST_TAG', $this->getHtmlListTag()); - $jsTpl->setVariable('CSS_LIST_CLASS', $this->getCssListClass()); - $jsTpl->setVariable('CSS_ITEM_CLASS', $this->getCssItemClass()); - $jsTpl->parseCurrentBlock(); - - return $jsTpl->get(); - } - - public function render($a_mode = "") - { - if( $this->isStylingEnabled() ) - { - $this->getGlobalTpl()->addCss('Services/Form/css/nested_ordering.css'); - } - - if( $this->isInteractionEnabled() ) - { - require_once 'Services/jQuery/classes/class.iljQueryUtil.php'; - - iljQueryUtil::initjQuery(); - iljQueryUtil::initjQueryUI(); - - $this->getGlobalTpl()->addJavaScript('./libs/bower/bower_components/nestable2/jquery.nestable.js'); - - return $this->renderMainList() . $this->renderJsInit(); - } - - return $this->renderMainList(); - } - - public function onCheckInput() - { - return true; - } - - public function getHTML() - { - return $this->render(); - } -} \ No newline at end of file + protected function renderListItem($value, $identifier, $position) + { + $subPostVar = $this->getMultiValuePostVarSubField($identifier, self::POSTVAR_SUBFIELD_NEST_ELEM); + $subFieldId = $this->getMultiValueSubFieldId($identifier, self::POSTVAR_SUBFIELD_NEST_ELEM); + + $this->getListTpl()->setCurrentBlock('item_value'); + + $this->getListTpl()->setVariable('ILC_HANDLE_CSS_CLASS', $this->getCssHandleClass()); + + $this->getListTpl()->setVariable('LIST_ITEM_VALUE', $this->getItemHtml( + $value, + $identifier, + $position, + $subPostVar, + $subFieldId + )); + + $this->getListTpl()->parseCurrentBlock(); + + $this->renderListSnippet(); + } + + /** + * @param $value + * @param $identifier + * @param $position + * @param $itemSubFieldPostVar + * @param $itemSubFieldId + * @return mixed + */ + abstract protected function getItemHtml($value, $identifier, $position, $itemSubFieldPostVar, $itemSubFieldId); + + protected function renderBeginListItem($identifier) + { + $this->getListTpl()->setCurrentBlock('begin_list_item'); + $this->getListTpl()->setVariable('LIST_ITEM_ID', $identifier); + $this->getListTpl()->setVariable('ILC_ITEM_CSS_CLASS', $this->getCssItemClass()); + $this->getListTpl()->parseCurrentBlock(); + $this->renderListSnippet(); + } + + protected function renderEndListItem() + { + $this->getListTpl()->setCurrentBlock('end_list_item'); + $this->getListTpl()->touchBlock('end_list_item'); + $this->getListTpl()->parseCurrentBlock(); + $this->renderListSnippet(); + } + + protected function renderBeginSubList() + { + $this->getListTpl()->setCurrentBlock('begin_sublist'); + $this->getListTpl()->setVariable('BEGIN_HTML_LIST_TAG', $this->getHtmlListTag()); + $this->getListTpl()->setVariable('ILC_LIST_CSS_CLASS', $this->getCssListClass()); + $this->getListTpl()->parseCurrentBlock(); + $this->renderListSnippet(); + } + + protected function renderEndSubList() + { + $this->getListTpl()->setCurrentBlock('end_sublist'); + $this->getListTpl()->setVariable('END_HTML_LIST_TAG', $this->getHtmlListTag()); + $this->getListTpl()->parseCurrentBlock(); + $this->renderListSnippet(); + } + + /** + * @param array $elementValues + * @param integer $elementCounter + * @return integer $currentDepth + */ + abstract protected function getCurrentIndentation($elementValues, $elementCounter); + + /** + * @param array $elementValues + * @param integer $elementCounter + * @return integer $nextDepth + */ + abstract protected function getNextIndentation($elementValues, $elementCounter); + + protected function renderMainList() + { + $this->initListTemplate(); + $this->renderBeginSubList(); + + + $values = array_values($this->getIdentifiedMultiValues()); + $keys = array_keys($this->getIdentifiedMultiValues()); + $prevIndent = 0; + + foreach ($values as $counter => $value) { + $identifier = $keys[$counter]; + + if ($this->isNestingEnabled()) { + $curIndent = $this->getCurrentIndentation($values, $counter); + $nextIndent = $this->getNextIndentation($values, $counter); + } else { + $curIndent = $nextIndent = 0; + } + + if ($prevIndent == $curIndent) { + // pcn = Previous, Current, Next -> Depth + // pcn: 000, 001, 110, 220 + if ($curIndent == $nextIndent) { + // (1) pcn: 000 + // echo"(1)"; + $this->renderBeginListItem($identifier); + $this->renderListItem($value, $identifier, $counter); + $this->renderEndListItem(); + } elseif ($curIndent > $nextIndent) { + if ($prevIndent == $nextIndent) { + // wenn prev = cur ist und cur > next, wie soll prev = next sein !? + + // (8) pcn: 110 + // echo"(8)"; + $this->renderBeginListItem($identifier); + $this->renderListItem($value, $identifier, $counter); + $this->renderEndListItem(); + $this->renderEndSubList(); + $this->renderEndListItem(); + } elseif ($prevIndent > $nextIndent) { + // (12) pcn: 220 + // echo"(12)"; + $this->renderBeginListItem($identifier); + $this->renderListItem($value, $identifier, $counter); + + for ($openlists = $nextIndent; $openlists < $curIndent; $openlists++) { + $this->renderEndListItem(); + $this->renderEndSubList(); + $this->renderEndListItem(); + } + } + } elseif ($curIndent < $nextIndent) { + // (2) pcn: 001 + // echo"(2)"; + $this->renderBeginListItem($identifier); + $this->renderListItem($value, $identifier, $counter); + $this->renderBeginSubList(); + } + } elseif ($prevIndent > $curIndent) { + if ($curIndent == $nextIndent) { + // (6) pcn: 100 + // echo"(6)"; + $this->renderBeginListItem($identifier); + $this->renderListItem($value, $identifier, $counter); + $this->renderEndListItem(); + } elseif ($curIndent > $nextIndent) { + // (11) pcn: 210 + // echo"(11)"; + $this->renderBeginListItem($identifier); + $this->renderListItem($value, $identifier, $counter); + $this->renderEndListItem(); + $this->renderEndSubList(); + } elseif ($curIndent < $nextIndent) { + if ($prevIndent == $nextIndent) { + // (7) pcn: 101 + // echo"(7)"; + $this->renderBeginListItem($identifier); + $this->renderListItem($value, $identifier, $counter); + $this->renderBeginSubList(); + } elseif ($prevIndent > $nextIndent) { + // (10) pcn: 201 + // echo"(10)"; + $this->renderBeginListItem($identifier); + $this->renderListItem($value, $identifier, $counter); + for ($openlists = $nextIndent; $openlists < $curIndent; $openlists++) { + $this->renderEndSubList(); + } + $this->renderBeginSubList(); + } + } + } elseif ($prevIndent < $curIndent) { + if ($curIndent == $nextIndent) { + // (4) pcn: 011 + // echo"(4)"; + $this->renderBeginListItem($identifier); + $this->renderListItem($value, $identifier, $counter); + $this->renderEndListItem(); + } elseif ($curIndent > $nextIndent) { + if ($prevIndent == $nextIndent) { + // (3) pcn: 010, + // echo"(3)"; + $this->renderBeginListItem($identifier); + $this->renderListItem($value, $identifier, $counter); + $this->renderEndListItem(); + $this->renderEndSubList(); + $this->renderEndListItem(); + } elseif ($prevIndent > $nextIndent) { + // (9) pcn: 120 + // echo"(9)"; + $this->renderBeginListItem($identifier); + $this->renderListItem($value, $identifier, $counter); + for ($openlists = $nextIndent; $openlists < $curIndent; $openlists++) { + $this->renderEndListItem(); + $this->renderEndSubList(); + } + } + } elseif ($curIndent < $nextIndent) { + // (5) pcn: 012 + // echo"(5)"; + $this->renderBeginListItem($identifier); + $this->renderListItem($value, $identifier, $counter); + $this->renderBeginSubList(); + } + } + + $prevIndent = $curIndent; + } + + $this->renderEndSubList(); + $this->renderListContainer(); + + return $this->fetchListHtml(); + } + + protected function renderJsInit() + { + $jsTpl = new ilTemplate('tpl.prop_nested_ordering_js.html', true, true, 'Services/Form'); + + if (!$this->isNestingEnabled()) { + $jsTpl->setCurrentBlock('avoid_nesting'); + $jsTpl->touchBlock('avoid_nesting'); + $jsTpl->parseCurrentBlock(); + } + + $jsTpl->setCurrentBlock('nested_ordering_init'); + $jsTpl->setVariable('INSTANCE_ID', $this->getInstanceId()); + $jsTpl->setVariable('INDENTATION_POSTVAR', $this->getPostVarSubField('indentation')); + $jsTpl->setVariable('HTML_LIST_TAG', $this->getHtmlListTag()); + $jsTpl->setVariable('CSS_LIST_CLASS', $this->getCssListClass()); + $jsTpl->setVariable('CSS_ITEM_CLASS', $this->getCssItemClass()); + $jsTpl->parseCurrentBlock(); + + return $jsTpl->get(); + } + + public function render($a_mode = "") + { + if ($this->isStylingEnabled()) { + $this->getGlobalTpl()->addCss('Services/Form/css/nested_ordering.css'); + } + + if ($this->isInteractionEnabled()) { + require_once 'Services/jQuery/classes/class.iljQueryUtil.php'; + + iljQueryUtil::initjQuery(); + iljQueryUtil::initjQueryUI(); + + $this->getGlobalTpl()->addJavaScript('./libs/bower/bower_components/nestable2/jquery.nestable.js'); + + return $this->renderMainList() . $this->renderJsInit(); + } + + return $this->renderMainList(); + } + + public function onCheckInput() + { + return true; + } + + public function getHTML() + { + return $this->render(); + } +} diff --git a/Services/Form/classes/class.ilMultipleTextsInputGUI.php b/Services/Form/classes/class.ilMultipleTextsInputGUI.php index 18091c9bff64b4a8a2b175b3604d9b0896ae9a09..e4457d1e973d8b48813634b5a0285a67087f0ccd 100644 --- a/Services/Form/classes/class.ilMultipleTextsInputGUI.php +++ b/Services/Form/classes/class.ilMultipleTextsInputGUI.php @@ -11,198 +11,186 @@ require_once 'Services/Form/classes/class.ilIdentifiedMultiValuesInputGUI.php'; */ abstract class ilMultipleTextsInputGUI extends ilIdentifiedMultiValuesInputGUI { - /** - * @var bool - */ - protected $editElementOccuranceEnabled = false; - - /** - * @var bool - */ - protected $editElementOrderEnabled = false; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + /** + * @var bool + */ + protected $editElementOccuranceEnabled = false; + + /** + * @var bool + */ + protected $editElementOrderEnabled = false; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - parent::__construct($a_title, $a_postvar); - $this->validationRegexp = ""; - } - - /** - * @return boolean $editElementOccuranceEnabled - */ - public function isEditElementOccuranceEnabled() - { - return $this->editElementOccuranceEnabled; - } - - /** - * @param boolean $editElementOccuranceEnabled - */ - public function setEditElementOccuranceEnabled($editElementOccuranceEnabled) - { - $this->editElementOccuranceEnabled = $editElementOccuranceEnabled; - } - - /** - * @return boolean - */ - public function isEditElementOrderEnabled() - { - return $this->editElementOrderEnabled; - } - - /** - * @param boolean $editElementOrderEnabled - */ - public function setEditElementOrderEnabled($editElementOrderEnabled) - { - $this->editElementOrderEnabled = $editElementOrderEnabled; - } - - /** - * Check input, strip slashes etc. set alert, if input is not ok. - *fetchImageTitle - * @return boolean Input ok, true/false - */ - function onCheckInput() - { - $lng = $this->lng; - - $submittedElements = $_POST[$this->getPostVar()]; - - if( !is_array($submittedElements) && $this->getRequired() ) - { - $this->setAlert($lng->txt("msg_input_is_required")); - return false; - } - - foreach($submittedElements as $submittedValue) - { - $submittedContentText = $this->fetchContentTextFromValue($submittedValue); - - if ($this->getRequired() && trim($submittedContentText) == "") - { - $this->setAlert($lng->txt('msg_input_is_required')); - return false; - } - - if( strlen($this->getValidationRegexp()) ) - { - if( !preg_match($this->getValidationRegexp(), $submittedContentText) ) - { - $this->setAlert($lng->txt('msg_wrong_format')); - return false; - } - } - } + $this->lng = $DIC->language(); + parent::__construct($a_title, $a_postvar); + $this->validationRegexp = ""; + } + + /** + * @return boolean $editElementOccuranceEnabled + */ + public function isEditElementOccuranceEnabled() + { + return $this->editElementOccuranceEnabled; + } + + /** + * @param boolean $editElementOccuranceEnabled + */ + public function setEditElementOccuranceEnabled($editElementOccuranceEnabled) + { + $this->editElementOccuranceEnabled = $editElementOccuranceEnabled; + } + + /** + * @return boolean + */ + public function isEditElementOrderEnabled() + { + return $this->editElementOrderEnabled; + } + + /** + * @param boolean $editElementOrderEnabled + */ + public function setEditElementOrderEnabled($editElementOrderEnabled) + { + $this->editElementOrderEnabled = $editElementOrderEnabled; + } + + /** + * Check input, strip slashes etc. set alert, if input is not ok. + *fetchImageTitle + * @return boolean Input ok, true/false + */ + public function onCheckInput() + { + $lng = $this->lng; + + $submittedElements = $_POST[$this->getPostVar()]; + + if (!is_array($submittedElements) && $this->getRequired()) { + $this->setAlert($lng->txt("msg_input_is_required")); + return false; + } + + foreach ($submittedElements as $submittedValue) { + $submittedContentText = $this->fetchContentTextFromValue($submittedValue); + + if ($this->getRequired() && trim($submittedContentText) == "") { + $this->setAlert($lng->txt('msg_input_is_required')); + return false; + } + + if (strlen($this->getValidationRegexp())) { + if (!preg_match($this->getValidationRegexp(), $submittedContentText)) { + $this->setAlert($lng->txt('msg_wrong_format')); + return false; + } + } + } - return $this->checkSubItemsInput(); - } - - /** - * @param string $mode - * @return string - */ - public function render($a_mode = "") - { - $tpl = new ilTemplate("tpl.prop_multi_text_inp.html", true, true, "Services/Form"); - $i = 0; - foreach ($this->getIdentifiedMultiValues() as $identifier => $value) - { - if (strlen($value)) - { - $tpl->setCurrentBlock("prop_text_propval"); - $tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($value)); - $tpl->parseCurrentBlock(); - } - if ($this->isEditElementOrderEnabled()) - { - $tpl->setCurrentBlock("move"); - $tpl->setVariable("ID_UP", $this->getMultiValuePosIndexedSubFieldId($identifier, 'up', $i)); - $tpl->setVariable("ID_DOWN", $this->getMultiValuePosIndexedSubFieldId($identifier, 'down', $i)); - $tpl->setVariable("CMD_UP", $this->buildMultiValueSubmitVar($identifier, $i, 'up')); - $tpl->setVariable("CMD_DOWN", $this->buildMultiValueSubmitVar($identifier, $i, 'down')); - $tpl->setVariable("ID", $this->getMultiValuePosIndexedFieldId($identifier, $i)); - include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); - $tpl->setVariable("UP_BUTTON", ilGlyphGUI::get(ilGlyphGUI::UP)); - $tpl->setVariable("DOWN_BUTTON", ilGlyphGUI::get(ilGlyphGUI::DOWN)); - $tpl->parseCurrentBlock(); - } - $tpl->setCurrentBlock("row"); - $tpl->setVariable("POST_VAR", $this->getMultiValuePostVarPosIndexed($identifier, $i)); - $tpl->setVariable("ID", $this->getMultiValuePosIndexedFieldId($identifier, $i)); - $tpl->setVariable("SIZE", $this->getSize()); - $tpl->setVariable("MAXLENGTH", $this->getMaxLength()); - - if ($this->getDisabled()) - { - $tpl->setVariable("DISABLED", - " disabled=\"disabled\""); - } - elseif( $this->isEditElementOccuranceEnabled() ) - { - $tpl->setVariable("ID_ADD", $this->getMultiValuePosIndexedSubFieldId($identifier, 'add', $i)); - $tpl->setVariable("ID_REMOVE", $this->getMultiValuePosIndexedSubFieldId($identifier, 'remove', $i)); - $tpl->setVariable("CMD_ADD", $this->buildMultiValueSubmitVar($identifier, $i, 'add')); - $tpl->setVariable("CMD_REMOVE", $this->buildMultiValueSubmitVar($identifier, $i, 'remove')); - include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); - $tpl->setVariable("ADD_BUTTON", ilGlyphGUI::get(ilGlyphGUI::ADD)); - $tpl->setVariable("REMOVE_BUTTON", ilGlyphGUI::get(ilGlyphGUI::REMOVE)); - } - - $tpl->parseCurrentBlock(); - $i++; - } - $tpl->setVariable("ELEMENT_ID", $this->getFieldId()); - - if (!$this->getDisabled()) - { - $tpl->setCurrentBlock('js_engine_initialisation'); - $tpl->touchBlock('js_engine_initialisation'); - $tpl->parseCurrentBlock(); - - $globalTpl = $GLOBALS['DIC'] ? $GLOBALS['DIC']['tpl'] : $GLOBALS['tpl']; - $globalTpl->addJavascript("./Services/Form/js/ServiceFormWizardInput.js"); - $globalTpl->addJavascript("./Services/Form/js/ServiceFormIdentifiedWizardInputExtend.js"); - } - - return $tpl->get(); - } - - /** - * @param $value - * @return bool - */ - protected function valueHasContentText($value) - { - if( $value === null || is_array($value) || is_object($value) ) - { - return false; - } - - return (bool)strlen($value); - } - - /** - * @param $value - * @return string - */ - protected function fetchContentTextFromValue($value) - { - if( $this->valueHasContentText($value) ) - { - return $value; - } - - return null; - } + return $this->checkSubItemsInput(); + } + + /** + * @param string $mode + * @return string + */ + public function render($a_mode = "") + { + $tpl = new ilTemplate("tpl.prop_multi_text_inp.html", true, true, "Services/Form"); + $i = 0; + foreach ($this->getIdentifiedMultiValues() as $identifier => $value) { + if (strlen($value)) { + $tpl->setCurrentBlock("prop_text_propval"); + $tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($value)); + $tpl->parseCurrentBlock(); + } + if ($this->isEditElementOrderEnabled()) { + $tpl->setCurrentBlock("move"); + $tpl->setVariable("ID_UP", $this->getMultiValuePosIndexedSubFieldId($identifier, 'up', $i)); + $tpl->setVariable("ID_DOWN", $this->getMultiValuePosIndexedSubFieldId($identifier, 'down', $i)); + $tpl->setVariable("CMD_UP", $this->buildMultiValueSubmitVar($identifier, $i, 'up')); + $tpl->setVariable("CMD_DOWN", $this->buildMultiValueSubmitVar($identifier, $i, 'down')); + $tpl->setVariable("ID", $this->getMultiValuePosIndexedFieldId($identifier, $i)); + include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); + $tpl->setVariable("UP_BUTTON", ilGlyphGUI::get(ilGlyphGUI::UP)); + $tpl->setVariable("DOWN_BUTTON", ilGlyphGUI::get(ilGlyphGUI::DOWN)); + $tpl->parseCurrentBlock(); + } + $tpl->setCurrentBlock("row"); + $tpl->setVariable("POST_VAR", $this->getMultiValuePostVarPosIndexed($identifier, $i)); + $tpl->setVariable("ID", $this->getMultiValuePosIndexedFieldId($identifier, $i)); + $tpl->setVariable("SIZE", $this->getSize()); + $tpl->setVariable("MAXLENGTH", $this->getMaxLength()); + + if ($this->getDisabled()) { + $tpl->setVariable( + "DISABLED", + " disabled=\"disabled\"" + ); + } elseif ($this->isEditElementOccuranceEnabled()) { + $tpl->setVariable("ID_ADD", $this->getMultiValuePosIndexedSubFieldId($identifier, 'add', $i)); + $tpl->setVariable("ID_REMOVE", $this->getMultiValuePosIndexedSubFieldId($identifier, 'remove', $i)); + $tpl->setVariable("CMD_ADD", $this->buildMultiValueSubmitVar($identifier, $i, 'add')); + $tpl->setVariable("CMD_REMOVE", $this->buildMultiValueSubmitVar($identifier, $i, 'remove')); + include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); + $tpl->setVariable("ADD_BUTTON", ilGlyphGUI::get(ilGlyphGUI::ADD)); + $tpl->setVariable("REMOVE_BUTTON", ilGlyphGUI::get(ilGlyphGUI::REMOVE)); + } + + $tpl->parseCurrentBlock(); + $i++; + } + $tpl->setVariable("ELEMENT_ID", $this->getFieldId()); + + if (!$this->getDisabled()) { + $tpl->setCurrentBlock('js_engine_initialisation'); + $tpl->touchBlock('js_engine_initialisation'); + $tpl->parseCurrentBlock(); + + $globalTpl = $GLOBALS['DIC'] ? $GLOBALS['DIC']['tpl'] : $GLOBALS['tpl']; + $globalTpl->addJavascript("./Services/Form/js/ServiceFormWizardInput.js"); + $globalTpl->addJavascript("./Services/Form/js/ServiceFormIdentifiedWizardInputExtend.js"); + } + + return $tpl->get(); + } + + /** + * @param $value + * @return bool + */ + protected function valueHasContentText($value) + { + if ($value === null || is_array($value) || is_object($value)) { + return false; + } + + return (bool) strlen($value); + } + + /** + * @param $value + * @return string + */ + protected function fetchContentTextFromValue($value) + { + if ($this->valueHasContentText($value)) { + return $value; + } + + return null; + } } diff --git a/Services/Form/classes/class.ilNestedListInputGUI.php b/Services/Form/classes/class.ilNestedListInputGUI.php index 7eab6b106ae9680b9730464b2c50258860da4403..9d8835f014a341474e513258be8eb9ca1cee7cd3 100644 --- a/Services/Form/classes/class.ilNestedListInputGUI.php +++ b/Services/Form/classes/class.ilNestedListInputGUI.php @@ -7,137 +7,142 @@ include_once 'Services/UIComponent/Toolbar/interfaces/interface.ilToolbarItem.ph /** * This class represents a (nested) list of checkboxes (could be extended for radio items, too) * -* @author Alex Killing +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilNestedListInputGUI extends ilFormPropertyGUI { - protected $value = "1"; - protected $checked; - protected $list_nodes = array(); - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + protected $value = "1"; + protected $checked; + protected $list_nodes = array(); + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - parent::__construct($a_title, $a_postvar); - $this->setType("nested_list"); + $this->lng = $DIC->language(); + parent::__construct($a_title, $a_postvar); + $this->setType("nested_list"); - include_once("./Services/UIComponent/NestedList/classes/class.ilNestedList.php"); - $this->list = new ilNestedList(); - $this->list->setListClass("il_Explorer"); - } + include_once("./Services/UIComponent/NestedList/classes/class.ilNestedList.php"); + $this->list = new ilNestedList(); + $this->list->setListClass("il_Explorer"); + } - /** - * Add list node - * - * @param - */ - function addListNode($a_id, $a_text, $a_parent = 0, $a_checked = false, $a_disabled = false, - $a_img_src = "", $a_img_alt = "", $a_post_var = "") - { - $this->list_nodes[$a_id] = array("text" => $a_text, - "parent" => $a_parent, "checked" => $a_checked, "disabled" => $a_disabled, - "img_src" => $a_img_src, "img_alt" => $a_img_alt, "post_var" => $a_post_var); - } + /** + * Add list node + * + * @param + */ + public function addListNode( + $a_id, + $a_text, + $a_parent = 0, + $a_checked = false, + $a_disabled = false, + $a_img_src = "", + $a_img_alt = "", + $a_post_var = "" + ) { + $this->list_nodes[$a_id] = array("text" => $a_text, + "parent" => $a_parent, "checked" => $a_checked, "disabled" => $a_disabled, + "img_src" => $a_img_src, "img_alt" => $a_img_alt, "post_var" => $a_post_var); + } - /** - * Set Value. - * - * @param string $a_value Value - */ - function setValue($a_value) - { - $this->value = $a_value; - } + /** + * Set Value. + * + * @param string $a_value Value + */ + public function setValue($a_value) + { + $this->value = $a_value; + } - /** - * Get Value. - * - * @return string Value - */ - function getValue() - { - return $this->value; - } + /** + * Get Value. + * + * @return string Value + */ + public function getValue() + { + return $this->value; + } - /** - * Set value by array - * - * @param object $a_item Item - */ - function setValueByArray($a_values) - { -// $this->setChecked($a_values[$this->getPostVar()]); + /** + * Set value by array + * + * @param object $a_item Item + */ + public function setValueByArray($a_values) + { + // $this->setChecked($a_values[$this->getPostVar()]); // foreach($this->getSubItems() as $item) // { // $item->setValueByArray($a_values); // } - } - - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - return true; - } - - /** - * Render item - */ - function render() - { - foreach ($this->list_nodes as $id => $n) - { - if ($n["post_var"] == "") - { - $post_var = $this->getPostVar()."[]"; - $value = $id; - } - else - { - $post_var = $n["post_var"]; - $value = $id; - } - $item_html = ilUtil::formCheckbox($n["checked"], $post_var, $value, - $n["disabled"]); - if ($n["img_src"] != "") - { - $item_html.= ilUtil::img($n["img_src"], $n["img_alt"])." "; - } - $item_html.= $n["text"]; + } + + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + return true; + } + + /** + * Render item + */ + public function render() + { + foreach ($this->list_nodes as $id => $n) { + if ($n["post_var"] == "") { + $post_var = $this->getPostVar() . "[]"; + $value = $id; + } else { + $post_var = $n["post_var"]; + $value = $id; + } + $item_html = ilUtil::formCheckbox( + $n["checked"], + $post_var, + $value, + $n["disabled"] + ); + if ($n["img_src"] != "") { + $item_html.= ilUtil::img($n["img_src"], $n["img_alt"]) . " "; + } + $item_html.= $n["text"]; - $this->list->addListNode($item_html, $id, $n["parent"]); - } + $this->list->addListNode($item_html, $id, $n["parent"]); + } - return $this->list->getHTML(); - } + return $this->list->getHTML(); + } - /** - * Insert property html - * - * @return int Size - */ - function insert($a_tpl) - { - $html = $this->render(); - - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $html); - $a_tpl->parseCurrentBlock(); - } + /** + * Insert property html + * + * @return int Size + */ + public function insert($a_tpl) + { + $html = $this->render(); + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $html); + $a_tpl->parseCurrentBlock(); + } } diff --git a/Services/Form/classes/class.ilNonEditableValueGUI.php b/Services/Form/classes/class.ilNonEditableValueGUI.php index 410a0ef07367f2f00c0e6086c6551c5ad76bab4e..4859c9e88e6c6037e2868fdb1c5986c012e3c30e 100755 --- a/Services/Form/classes/class.ilNonEditableValueGUI.php +++ b/Services/Form/classes/class.ilNonEditableValueGUI.php @@ -6,198 +6,190 @@ include_once 'Services/Form/interfaces/interface.ilMultiValuesItem.php'; /** * This class represents a non editable value in a property form. * -* @author Alex Killing +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilNonEditableValueGUI extends ilSubEnabledFormPropertyGUI implements ilTableFilterItem, ilMultiValuesItem { - protected $type; - protected $value; - protected $title; - protected $info; - protected $section_icon; - protected $disable_escaping; - - /** - * Constructor - * - * @param - */ - function __construct($a_title = "", $a_id = "", $a_disable_escaping = false) - { - parent::__construct($a_title, $a_id); - $this->setTitle($a_title); - $this->setType("non_editable_value"); - $this->disable_escaping = (bool)$a_disable_escaping; - } - - function checkInput() - { - if(!is_array($_POST[$this->getPostVar()])) - { - $_POST[$this->getPostVar()] = ilUtil::stripSlashes($_POST[$this->getPostVar()]); - } - return $this->checkSubItemsInput(); - } + protected $type; + protected $value; + protected $title; + protected $info; + protected $section_icon; + protected $disable_escaping; + + /** + * Constructor + * + * @param + */ + public function __construct($a_title = "", $a_id = "", $a_disable_escaping = false) + { + parent::__construct($a_title, $a_id); + $this->setTitle($a_title); + $this->setType("non_editable_value"); + $this->disable_escaping = (bool) $a_disable_escaping; + } + + public function checkInput() + { + if (!is_array($_POST[$this->getPostVar()])) { + $_POST[$this->getPostVar()] = ilUtil::stripSlashes($_POST[$this->getPostVar()]); + } + return $this->checkSubItemsInput(); + } - /** - * Set Type. - * - * @param string $a_type Type - */ - function setType($a_type) - { - $this->type = $a_type; - } + /** + * Set Type. + * + * @param string $a_type Type + */ + public function setType($a_type) + { + $this->type = $a_type; + } - /** - * Get Type. - * - * @return string Type - */ - function getType() - { - return $this->type; - } - - /** - * Set Title. - * - * @param string $a_title Title - */ - function setTitle($a_title) - { - $this->title = $a_title; - } + /** + * Get Type. + * + * @return string Type + */ + public function getType() + { + return $this->type; + } + + /** + * Set Title. + * + * @param string $a_title Title + */ + public function setTitle($a_title) + { + $this->title = $a_title; + } - /** - * Get Title. - * - * @return string Title - */ - function getTitle() - { - return $this->title; - } + /** + * Get Title. + * + * @return string Title + */ + public function getTitle() + { + return $this->title; + } - /** - * Set Information Text. - * - * @param string $a_info Information Text - */ - function setInfo($a_info) - { - $this->info = $a_info; - } + /** + * Set Information Text. + * + * @param string $a_info Information Text + */ + public function setInfo($a_info) + { + $this->info = $a_info; + } - /** - * Get Information Text. - * - * @return string Information Text - */ - function getInfo() - { - return $this->info; - } + /** + * Get Information Text. + * + * @return string Information Text + */ + public function getInfo() + { + return $this->info; + } - /** - * Set Value. - * - * @param string $a_value Value - */ - function setValue($a_value) - { - if($this->getMulti() && is_array($a_value)) - { - $this->setMultiValues($a_value); - $a_value = array_shift($a_value); - } - $this->value = $a_value; - } + /** + * Set Value. + * + * @param string $a_value Value + */ + public function setValue($a_value) + { + if ($this->getMulti() && is_array($a_value)) { + $this->setMultiValues($a_value); + $a_value = array_shift($a_value); + } + $this->value = $a_value; + } - /** - * Get Value. - * - * @return string Value - */ - function getValue() - { - return $this->value; - } + /** + * Get Value. + * + * @return string Value + */ + public function getValue() + { + return $this->value; + } - /** - * render - */ - function render() - { - $tpl = new ilTemplate("tpl.non_editable_value.html", true, true, "Services/Form"); - if ($this->getPostVar() != "") - { - $postvar = $this->getPostVar(); - if($this->getMulti() && substr($postvar, -2) != "[]") - { - $postvar .= "[]"; - } - - $tpl->setCurrentBlock("hidden"); - $tpl->setVariable('NON_EDITABLE_ID', $postvar); - $tpl->setVariable('MULTI_HIDDEN_ID', $this->getFieldId()); - $tpl->setVariable("HVALUE", ilUtil::prepareFormOutput($this->getValue())); - $tpl->parseCurrentBlock(); - } - $value = $this->getValue(); - if(!$this->disable_escaping) - { - $value = ilUtil::prepareFormOutput($value); - } - $tpl->setVariable("VALUE", $value); - $tpl->setVariable("ID", $this->getFieldId()); - $tpl->parseCurrentBlock(); - - if ($this->getMulti() && $postvar!= "" && !$this->getDisabled()) - { - $tpl->setVariable("MULTI_ICONS", $this->getMultiIconsHTML()); - } + /** + * render + */ + public function render() + { + $tpl = new ilTemplate("tpl.non_editable_value.html", true, true, "Services/Form"); + if ($this->getPostVar() != "") { + $postvar = $this->getPostVar(); + if ($this->getMulti() && substr($postvar, -2) != "[]") { + $postvar .= "[]"; + } + + $tpl->setCurrentBlock("hidden"); + $tpl->setVariable('NON_EDITABLE_ID', $postvar); + $tpl->setVariable('MULTI_HIDDEN_ID', $this->getFieldId()); + $tpl->setVariable("HVALUE", ilUtil::prepareFormOutput($this->getValue())); + $tpl->parseCurrentBlock(); + } + $value = $this->getValue(); + if (!$this->disable_escaping) { + $value = ilUtil::prepareFormOutput($value); + } + $tpl->setVariable("VALUE", $value); + $tpl->setVariable("ID", $this->getFieldId()); + $tpl->parseCurrentBlock(); + + if ($this->getMulti() && $postvar!= "" && !$this->getDisabled()) { + $tpl->setVariable("MULTI_ICONS", $this->getMultiIconsHTML()); + } - - return $tpl->get(); - } - - /** - * Insert property html - * - */ - function insert($a_tpl) - { - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $this->render()); - $a_tpl->parseCurrentBlock(); - } - - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - if ($this->getPostVar() && isset($a_values[$this->getPostVar()])) - { - $this->setValue($a_values[$this->getPostVar()]); - } - foreach($this->getSubItems() as $item) - { - $item->setValueByArray($a_values); - } - } - - /** - * Get HTML for table filter - */ - function getTableFilterHTML() - { - $html = $this->render(); - return $html; - } + + return $tpl->get(); + } + + /** + * Insert property html + * + */ + public function insert($a_tpl) + { + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $this->render()); + $a_tpl->parseCurrentBlock(); + } + + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + if ($this->getPostVar() && isset($a_values[$this->getPostVar()])) { + $this->setValue($a_values[$this->getPostVar()]); + } + foreach ($this->getSubItems() as $item) { + $item->setValueByArray($a_values); + } + } + + /** + * Get HTML for table filter + */ + public function getTableFilterHTML() + { + $html = $this->render(); + return $html; + } } diff --git a/Services/Form/classes/class.ilNumberInputGUI.php b/Services/Form/classes/class.ilNumberInputGUI.php index 8b9d2c7abe0c6a259d44946cd902f46fc3701a9e..e863ecddcddf2d07ef6a1c2b06f7a17b70bd6aeb 100755 --- a/Services/Form/classes/class.ilNumberInputGUI.php +++ b/Services/Form/classes/class.ilNumberInputGUI.php @@ -7,439 +7,418 @@ include_once("./Services/Form/classes/class.ilSubEnabledFormPropertyGUI.php"); /** * This class represents a number property in a property form. * -* @author Alex Killing +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilNumberInputGUI extends ilSubEnabledFormPropertyGUI { - protected $value; - protected $maxlength = 200; - protected $size = 40; - protected $suffix; - protected $minvalue = false; - protected $minvalueShouldBeGreater = false; - protected $minvalue_visible = false; - protected $maxvalue = false; - protected $maxvalueShouldBeLess = false; - protected $maxvalue_visible = false; - protected $decimals; - protected $allow_decimals = false; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + protected $value; + protected $maxlength = 200; + protected $size = 40; + protected $suffix; + protected $minvalue = false; + protected $minvalueShouldBeGreater = false; + protected $minvalue_visible = false; + protected $maxvalue = false; + protected $maxvalueShouldBeLess = false; + protected $maxvalue_visible = false; + protected $decimals; + protected $allow_decimals = false; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - parent::__construct($a_title, $a_postvar); - } + $this->lng = $DIC->language(); + parent::__construct($a_title, $a_postvar); + } - /** - * Set suffix. - * - * @param string $a_value suffix - */ - function setSuffix($a_value) - { - $this->suffix = $a_value; - } + /** + * Set suffix. + * + * @param string $a_value suffix + */ + public function setSuffix($a_value) + { + $this->suffix = $a_value; + } - /** - * Get suffix. - * - * @return string suffix - */ - function getSuffix() - { - return $this->suffix; - } + /** + * Get suffix. + * + * @return string suffix + */ + public function getSuffix() + { + return $this->suffix; + } - /** - * Set Value. - * - * @param string $a_value Value - */ - function setValue($a_value) - { - $this->value = str_replace(',', '.', $a_value); - - // empty strings are allowed - if($this->value != "") - { - // integer - if(!$this->areDecimalsAllowed()) - { - $this->value = round($this->value); - } - // float - else if($this->getDecimals() > 0) - { - // get rid of unwanted decimals - $this->value = round($this->value, $this->getDecimals()); + /** + * Set Value. + * + * @param string $a_value Value + */ + public function setValue($a_value) + { + $this->value = str_replace(',', '.', $a_value); + + // empty strings are allowed + if ($this->value != "") { + // integer + if (!$this->areDecimalsAllowed()) { + $this->value = round($this->value); + } + // float + elseif ($this->getDecimals() > 0) { + // get rid of unwanted decimals + $this->value = round($this->value, $this->getDecimals()); - // pad value to specified format - $this->value = number_format($this->value, $this->getDecimals(), ".", ""); - } - } - } + // pad value to specified format + $this->value = number_format($this->value, $this->getDecimals(), ".", ""); + } + } + } - /** - * Get Value. - * - * @return string Value - */ - function getValue() - { - return $this->value; - } + /** + * Get Value. + * + * @return string Value + */ + public function getValue() + { + return $this->value; + } - /** - * Set Max Length. - * - * @param int $a_maxlength Max Length - */ - function setMaxLength($a_maxlength) - { - $this->maxlength = $a_maxlength; - } + /** + * Set Max Length. + * + * @param int $a_maxlength Max Length + */ + public function setMaxLength($a_maxlength) + { + $this->maxlength = $a_maxlength; + } - /** - * Get Max Length. - * - * @return int Max Length - */ - function getMaxLength() - { - return $this->maxlength; - } + /** + * Get Max Length. + * + * @return int Max Length + */ + public function getMaxLength() + { + return $this->maxlength; + } - /** - * Set minvalueShouldBeGreater - * - * @param boolean $a_bool true if the minimum value should be greater than minvalue - */ - function setMinvalueShouldBeGreater($a_bool) - { - $this->minvalueShouldBeGreater = $a_bool; - } - - /** - * Get minvalueShouldBeGreater - * - * @return boolean true if the minimum value should be greater than minvalue - */ - function minvalueShouldBeGreater() - { - return $this->minvalueShouldBeGreater; - } + /** + * Set minvalueShouldBeGreater + * + * @param boolean $a_bool true if the minimum value should be greater than minvalue + */ + public function setMinvalueShouldBeGreater($a_bool) + { + $this->minvalueShouldBeGreater = $a_bool; + } + + /** + * Get minvalueShouldBeGreater + * + * @return boolean true if the minimum value should be greater than minvalue + */ + public function minvalueShouldBeGreater() + { + return $this->minvalueShouldBeGreater; + } - /** - * Set maxvalueShouldBeLess - * - * @param boolean $a_bool true if the maximum value should be less than maxvalue - */ - function setMaxvalueShouldBeLess($a_bool) - { - $this->maxvalueShouldBeLess = $a_bool; - } - - /** - * Get maxvalueShouldBeLess - * - * @return boolean true if the maximum value should be less than maxvalue - */ - function maxvalueShouldBeLess() - { - return $this->maxvalueShouldBeLess; - } - - /** - * Set Size. - * - * @param int $a_size Size - */ - function setSize($a_size) - { - $this->size = $a_size; - } + /** + * Set maxvalueShouldBeLess + * + * @param boolean $a_bool true if the maximum value should be less than maxvalue + */ + public function setMaxvalueShouldBeLess($a_bool) + { + $this->maxvalueShouldBeLess = $a_bool; + } + + /** + * Get maxvalueShouldBeLess + * + * @return boolean true if the maximum value should be less than maxvalue + */ + public function maxvalueShouldBeLess() + { + return $this->maxvalueShouldBeLess; + } + + /** + * Set Size. + * + * @param int $a_size Size + */ + public function setSize($a_size) + { + $this->size = $a_size; + } - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $this->setValue($a_values[$this->getPostVar()]); - } + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $this->setValue($a_values[$this->getPostVar()]); + } - /** - * Get Size. - * - * @return int Size - */ - function getSize() - { - return $this->size; - } - - /** - * Set Minimum Value. - * - * @param float $a_minvalue Minimum Value - * @param bool $a_display_always - */ - function setMinValue($a_minvalue, $a_display_always = false) - { - $this->minvalue = $a_minvalue; - $this->minvalue_visible = (bool)$a_display_always; - } + /** + * Get Size. + * + * @return int Size + */ + public function getSize() + { + return $this->size; + } + + /** + * Set Minimum Value. + * + * @param float $a_minvalue Minimum Value + * @param bool $a_display_always + */ + public function setMinValue($a_minvalue, $a_display_always = false) + { + $this->minvalue = $a_minvalue; + $this->minvalue_visible = (bool) $a_display_always; + } - /** - * Get Minimum Value. - * - * @return float Minimum Value - */ - function getMinValue() - { - return $this->minvalue; - } + /** + * Get Minimum Value. + * + * @return float Minimum Value + */ + public function getMinValue() + { + return $this->minvalue; + } - /** - * Set Maximum Value. - * - * @param float $a_maxvalue Maximum Value - * @param bool $a_display_always - */ - function setMaxValue($a_maxvalue, $a_display_always = false) - { - $this->maxvalue = $a_maxvalue; - $this->maxvalue_visible = (bool)$a_display_always; - } + /** + * Set Maximum Value. + * + * @param float $a_maxvalue Maximum Value + * @param bool $a_display_always + */ + public function setMaxValue($a_maxvalue, $a_display_always = false) + { + $this->maxvalue = $a_maxvalue; + $this->maxvalue_visible = (bool) $a_display_always; + } - /** - * Get Maximum Value. - * - * @return float Maximum Value - */ - function getMaxValue() - { - return $this->maxvalue; - } + /** + * Get Maximum Value. + * + * @return float Maximum Value + */ + public function getMaxValue() + { + return $this->maxvalue; + } - /** - * Set Decimal Places. - * - * @param int $a_decimals Decimal Places - */ - function setDecimals($a_decimals) - { - $this->decimals = (int)$a_decimals; - if($this->decimals) - { - $this->allowDecimals(true); - } - } + /** + * Set Decimal Places. + * + * @param int $a_decimals Decimal Places + */ + public function setDecimals($a_decimals) + { + $this->decimals = (int) $a_decimals; + if ($this->decimals) { + $this->allowDecimals(true); + } + } - /** - * Get Decimal Places. - * - * @return int Decimal Places - */ - function getDecimals() - { - return $this->decimals; - } - - /** - * Toggle Decimals - * - * @param bool $a_value - */ - function allowDecimals($a_value) - { - $this->allow_decimals = (bool)$a_value; - } - - /** - * - * - * @return bool - */ - function areDecimalsAllowed() - { - return $this->allow_decimals; - } + /** + * Get Decimal Places. + * + * @return int Decimal Places + */ + public function getDecimals() + { + return $this->decimals; + } + + /** + * Toggle Decimals + * + * @param bool $a_value + */ + public function allowDecimals($a_value) + { + $this->allow_decimals = (bool) $a_value; + } + + /** + * + * + * @return bool + */ + public function areDecimalsAllowed() + { + return $this->allow_decimals; + } - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - $_POST[$this->getPostVar()] = ilUtil::stripSlashes($_POST[$this->getPostVar()]); - if ($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") - { - $this->setAlert($lng->txt("msg_input_is_required")); - return false; - } + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + $_POST[$this->getPostVar()] = ilUtil::stripSlashes($_POST[$this->getPostVar()]); + if ($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") { + $this->setAlert($lng->txt("msg_input_is_required")); + return false; + } - if (trim($_POST[$this->getPostVar()]) != "" && - ! is_numeric(str_replace(',', '.', $_POST[$this->getPostVar()]))) - { - $this->minvalue_visible = true; - $this->maxvalue_visible = true; - $this->setAlert($lng->txt("form_msg_numeric_value_required")); - return false; - } + if (trim($_POST[$this->getPostVar()]) != "" && + !is_numeric(str_replace(',', '.', $_POST[$this->getPostVar()]))) { + $this->minvalue_visible = true; + $this->maxvalue_visible = true; + $this->setAlert($lng->txt("form_msg_numeric_value_required")); + return false; + } - if ($this->minvalueShouldBeGreater()) - { - if (trim($_POST[$this->getPostVar()]) != "" && - $this->getMinValue() !== false && - $_POST[$this->getPostVar()] <= $this->getMinValue()) - { - $this->minvalue_visible = true; - $this->setAlert($lng->txt("form_msg_value_too_low")); - return false; - } - } - else - { - if (trim($_POST[$this->getPostVar()]) != "" && - $this->getMinValue() !== false && - $_POST[$this->getPostVar()] < $this->getMinValue()) - { - $this->minvalue_visible = true; - $this->setAlert($lng->txt("form_msg_value_too_low")); - return false; - } - } + if ($this->minvalueShouldBeGreater()) { + if (trim($_POST[$this->getPostVar()]) != "" && + $this->getMinValue() !== false && + $_POST[$this->getPostVar()] <= $this->getMinValue()) { + $this->minvalue_visible = true; + $this->setAlert($lng->txt("form_msg_value_too_low")); + return false; + } + } else { + if (trim($_POST[$this->getPostVar()]) != "" && + $this->getMinValue() !== false && + $_POST[$this->getPostVar()] < $this->getMinValue()) { + $this->minvalue_visible = true; + $this->setAlert($lng->txt("form_msg_value_too_low")); + return false; + } + } - if ($this->maxvalueShouldBeLess()) - { - if (trim($_POST[$this->getPostVar()]) != "" && - $this->getMaxValue() !== false && - $_POST[$this->getPostVar()] >= $this->getMaxValue()) - { - $this->maxvalue_visible = true; - $this->setAlert($lng->txt("form_msg_value_too_high")); - return false; - } - } - else - { - if (trim($_POST[$this->getPostVar()]) != "" && - $this->getMaxValue() !== false && - $_POST[$this->getPostVar()] > $this->getMaxValue()) - { - $this->maxvalue_visible = true; - $this->setAlert($lng->txt("form_msg_value_too_high")); - return false; - } - } - - return $this->checkSubItemsInput(); - } + if ($this->maxvalueShouldBeLess()) { + if (trim($_POST[$this->getPostVar()]) != "" && + $this->getMaxValue() !== false && + $_POST[$this->getPostVar()] >= $this->getMaxValue()) { + $this->maxvalue_visible = true; + $this->setAlert($lng->txt("form_msg_value_too_high")); + return false; + } + } else { + if (trim($_POST[$this->getPostVar()]) != "" && + $this->getMaxValue() !== false && + $_POST[$this->getPostVar()] > $this->getMaxValue()) { + $this->maxvalue_visible = true; + $this->setAlert($lng->txt("form_msg_value_too_high")); + return false; + } + } + + return $this->checkSubItemsInput(); + } - /** - * Insert property html - * - * @return int Size - */ - function insert($a_tpl) - { - $html = $this->render(); + /** + * Insert property html + * + * @return int Size + */ + public function insert($a_tpl) + { + $html = $this->render(); - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $html); - $a_tpl->parseCurrentBlock(); - } + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $html); + $a_tpl->parseCurrentBlock(); + } - /** - * Insert property html - */ - function render() - { - $lng = $this->lng; + /** + * Insert property html + */ + public function render() + { + $lng = $this->lng; - $tpl = new ilTemplate("tpl.prop_number.html", true, true, "Services/Form"); + $tpl = new ilTemplate("tpl.prop_number.html", true, true, "Services/Form"); - if (strlen($this->getValue())) - { - $tpl->setCurrentBlock("prop_number_propval"); - $tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($this->getValue())); - $tpl->parseCurrentBlock(); - } - $tpl->setCurrentBlock("prop_number"); - - $tpl->setVariable("POST_VAR", $this->getPostVar()); - $tpl->setVariable("ID", $this->getFieldId()); - $tpl->setVariable("SIZE", $this->getSize()); - $tpl->setVariable("MAXLENGTH", $this->getMaxLength()); - if (strlen($this->getSuffix())) $tpl->setVariable("INPUT_SUFFIX", $this->getSuffix()); - if ($this->getDisabled()) - { - $tpl->setVariable("DISABLED", - " disabled=\"disabled\""); - } - - /* - $tpl->setVariable("JS_DECIMALS_ALLOWED", (int)$this->areDecimalsAllowed()); - */ - - // constraints - if ($this->areDecimalsAllowed() && $this->getDecimals() > 0) - { - $constraints = $lng->txt("form_format").": ###.".str_repeat("#", $this->getDecimals()); - $delim = ", "; - } - if ($this->getMinValue() !== false && $this->minvalue_visible) - { - $constraints.= $delim.$lng->txt("form_min_value").": ".(($this->minvalueShouldBeGreater()) ? "> " : "").$this->getMinValue(); - $delim = ", "; - } - if ($this->getMaxValue() !== false && $this->maxvalue_visible) - { - $constraints.= $delim.$lng->txt("form_max_value").": ".(($this->maxvalueShouldBeLess()) ? "< " : "").$this->getMaxValue(); - $delim = ", "; - } - if ($constraints != "") - { - $tpl->setVariable("TXT_NUMBER_CONSTRAINTS", $constraints); - } - - if($this->getRequired()) - { - $tpl->setVariable("REQUIRED", "required=\"required\""); - } - - $tpl->parseCurrentBlock(); + if (strlen($this->getValue())) { + $tpl->setCurrentBlock("prop_number_propval"); + $tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($this->getValue())); + $tpl->parseCurrentBlock(); + } + $tpl->setCurrentBlock("prop_number"); + + $tpl->setVariable("POST_VAR", $this->getPostVar()); + $tpl->setVariable("ID", $this->getFieldId()); + $tpl->setVariable("SIZE", $this->getSize()); + $tpl->setVariable("MAXLENGTH", $this->getMaxLength()); + if (strlen($this->getSuffix())) { + $tpl->setVariable("INPUT_SUFFIX", $this->getSuffix()); + } + if ($this->getDisabled()) { + $tpl->setVariable( + "DISABLED", + " disabled=\"disabled\"" + ); + } + + /* + $tpl->setVariable("JS_DECIMALS_ALLOWED", (int)$this->areDecimalsAllowed()); + */ + + // constraints + if ($this->areDecimalsAllowed() && $this->getDecimals() > 0) { + $constraints = $lng->txt("form_format") . ": ###." . str_repeat("#", $this->getDecimals()); + $delim = ", "; + } + if ($this->getMinValue() !== false && $this->minvalue_visible) { + $constraints.= $delim . $lng->txt("form_min_value") . ": " . (($this->minvalueShouldBeGreater()) ? "> " : "") . $this->getMinValue(); + $delim = ", "; + } + if ($this->getMaxValue() !== false && $this->maxvalue_visible) { + $constraints.= $delim . $lng->txt("form_max_value") . ": " . (($this->maxvalueShouldBeLess()) ? "< " : "") . $this->getMaxValue(); + $delim = ", "; + } + if ($constraints != "") { + $tpl->setVariable("TXT_NUMBER_CONSTRAINTS", $constraints); + } + + if ($this->getRequired()) { + $tpl->setVariable("REQUIRED", "required=\"required\""); + } + + $tpl->parseCurrentBlock(); - return $tpl->get(); - } + return $tpl->get(); + } - /** - * parse post value to make it comparable - * - * used by combination input gui - */ - function getPostValueForComparison() - { - $value = ilUtil::stripSlashes($_POST[$this->getPostVar()]); - if($value != "") - { - return (int)$value; - } - } + /** + * parse post value to make it comparable + * + * used by combination input gui + */ + public function getPostValueForComparison() + { + $value = ilUtil::stripSlashes($_POST[$this->getPostVar()]); + if ($value != "") { + return (int) $value; + } + } } -?> \ No newline at end of file diff --git a/Services/Form/classes/class.ilPasswordInputGUI.php b/Services/Form/classes/class.ilPasswordInputGUI.php index 9b5e1596b0533f22f8ab2b96966c23095a3908c0..9b3562a7a9ecf54c1ab13913a95e8d6fa9dbfdc6 100755 --- a/Services/Form/classes/class.ilPasswordInputGUI.php +++ b/Services/Form/classes/class.ilPasswordInputGUI.php @@ -4,388 +4,380 @@ /** * This class represents a password property in a property form. * -* @author Alex Killing +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilPasswordInputGUI extends ilSubEnabledFormPropertyGUI { - protected $value; - protected $size = 20; - protected $validateauthpost = ""; - protected $requiredonauth = false; - protected $maxlength = false; - protected $use_strip_slashes = true; + protected $value; + protected $size = 20; + protected $validateauthpost = ""; + protected $requiredonauth = false; + protected $maxlength = false; + protected $use_strip_slashes = true; - /** - * @var bool Flag whether the html autocomplete attribute should be set to "off" or not - */ - protected $autocomplete_disabled = true; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + /** + * @var bool Flag whether the html autocomplete attribute should be set to "off" or not + */ + protected $autocomplete_disabled = true; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - parent::__construct($a_title, $a_postvar); - $this->setRetype(true); - $this->setSkipSyntaxCheck(false); - } + $this->lng = $DIC->language(); + parent::__construct($a_title, $a_postvar); + $this->setRetype(true); + $this->setSkipSyntaxCheck(false); + } - /** - * Set Value. - * - * @param string $a_value Value - */ - function setValue($a_value) - { - $this->value = $a_value; - } + /** + * Set Value. + * + * @param string $a_value Value + */ + public function setValue($a_value) + { + $this->value = $a_value; + } - /** - * Get Value. - * - * @return string Value - */ - function getValue() - { - return $this->value; - } + /** + * Get Value. + * + * @return string Value + */ + public function getValue() + { + return $this->value; + } - /** - * Set retype on/off - * - * @param boolean retype - */ - function setRetype($a_val) - { - $this->retype = $a_val; - } - - /** - * Get retype on/off - * - * @return boolean retype - */ - function getRetype() - { - return $this->retype; - } - - /** - * Set Retype Value. - * - * @param string $a_retypevalue Retype Value - */ - function setRetypeValue($a_retypevalue) - { - $this->retypevalue = $a_retypevalue; - } + /** + * Set retype on/off + * + * @param boolean retype + */ + public function setRetype($a_val) + { + $this->retype = $a_val; + } + + /** + * Get retype on/off + * + * @return boolean retype + */ + public function getRetype() + { + return $this->retype; + } + + /** + * Set Retype Value. + * + * @param string $a_retypevalue Retype Value + */ + public function setRetypeValue($a_retypevalue) + { + $this->retypevalue = $a_retypevalue; + } - /** - * Get Retype Value. - * - * @return string Retype Value - */ - function getRetypeValue() - { - return $this->retypevalue; - } + /** + * Get Retype Value. + * + * @return string Retype Value + */ + public function getRetypeValue() + { + return $this->retypevalue; + } - /** - * Set Max Length. - * - * @param int $a_maxlength Max Length - */ - function setMaxLength($a_maxlength) - { - $this->maxlength = $a_maxlength; - } + /** + * Set Max Length. + * + * @param int $a_maxlength Max Length + */ + public function setMaxLength($a_maxlength) + { + $this->maxlength = $a_maxlength; + } - /** - * Get Max Length. - * - * @return int Max Length - */ - function getMaxLength() - { - return $this->maxlength; - } + /** + * Get Max Length. + * + * @return int Max Length + */ + public function getMaxLength() + { + return $this->maxlength; + } - /** - * Set Size. - * - * @param int $a_size Size - */ - function setSize($a_size) - { - $this->size = $a_size; - } + /** + * Set Size. + * + * @param int $a_size Size + */ + public function setSize($a_size) + { + $this->size = $a_size; + } - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $this->setValue($a_values[$this->getPostVar()]); - $this->setRetypeValue($a_values[$this->getPostVar()."_retype"]); - } + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $this->setValue($a_values[$this->getPostVar()]); + $this->setRetypeValue($a_values[$this->getPostVar() . "_retype"]); + } - /** - * Get Size. - * - * @return int Size - */ - function getSize() - { - return $this->size; - } + /** + * Get Size. + * + * @return int Size + */ + public function getSize() + { + return $this->size; + } - /** - * Set Validate required status against authentication POST var. - * - * @param string $a_validateauthpost POST var - */ - function setValidateAuthPost($a_validateauthpost) - { - $this->validateauthpost = $a_validateauthpost; - } + /** + * Set Validate required status against authentication POST var. + * + * @param string $a_validateauthpost POST var + */ + public function setValidateAuthPost($a_validateauthpost) + { + $this->validateauthpost = $a_validateauthpost; + } - /** - * Get Validate required status against authentication POST var. - * - * @return string POST var - */ - function getValidateAuthPost() - { - return $this->validateauthpost; - } + /** + * Get Validate required status against authentication POST var. + * + * @return string POST var + */ + public function getValidateAuthPost() + { + return $this->validateauthpost; + } - /** - * Set input required, if authentication mode allows password setting. - * - * @param boolean $a_requiredonauth require input - */ - function setRequiredOnAuth($a_requiredonauth) - { - $this->requiredonauth = $a_requiredonauth; - } + /** + * Set input required, if authentication mode allows password setting. + * + * @param boolean $a_requiredonauth require input + */ + public function setRequiredOnAuth($a_requiredonauth) + { + $this->requiredonauth = $a_requiredonauth; + } - /** - * Get input required, if authentication mode allows password setting. - * - * @return boolean require input - */ - function getRequiredOnAuth() - { - return $this->requiredonauth; - } + /** + * Get input required, if authentication mode allows password setting. + * + * @return boolean require input + */ + public function getRequiredOnAuth() + { + return $this->requiredonauth; + } - /** - * Set skip syntax check - * - * @param boolean skip syntax check - */ - function setSkipSyntaxCheck($a_val) - { - $this->skip_syntax_check = $a_val; - } - - /** - * Get skip syntax check - * - * @return boolean skip syntax check - */ - function getSkipSyntaxCheck() - { - return $this->skip_syntax_check; - } - - /** - * Set autocomplete - * - * @param bool $a_value Value - */ - function setDisableHtmlAutoComplete($a_value) - { - $this->autocomplete_disabled = (bool)$a_value; - } + /** + * Set skip syntax check + * + * @param boolean skip syntax check + */ + public function setSkipSyntaxCheck($a_val) + { + $this->skip_syntax_check = $a_val; + } + + /** + * Get skip syntax check + * + * @return boolean skip syntax check + */ + public function getSkipSyntaxCheck() + { + return $this->skip_syntax_check; + } + + /** + * Set autocomplete + * + * @param bool $a_value Value + */ + public function setDisableHtmlAutoComplete($a_value) + { + $this->autocomplete_disabled = (bool) $a_value; + } - /** - * Get autocomplete - * - * @return bool Value - */ - function isHtmlAutoCompleteDisabled() - { - return $this->autocomplete_disabled; - } - - /** - * En/disable use of stripslashes. e.g on login screen. - * Otherwise passwords containing "<" are stripped and therefor authentication - * fails against external authentication services. - * @param type $a_stat - */ - public function setUseStripSlashes($a_stat) - { - $this->use_strip_slashes = $a_stat; - } - - /** - * - * @return type - */ - public function getUseStripSlashes() - { - return $this->use_strip_slashes; - } - - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - if($this->getUseStripSlashes()) - { - $_POST[$this->getPostVar()] = ilUtil::stripSlashes($_POST[$this->getPostVar()]); - $_POST[$this->getPostVar()."_retype"] = ilUtil::stripSlashes($_POST[$this->getPostVar()."_retype"]); - } - if ($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") - { - $this->setAlert($lng->txt("msg_input_is_required")); + /** + * Get autocomplete + * + * @return bool Value + */ + public function isHtmlAutoCompleteDisabled() + { + return $this->autocomplete_disabled; + } + + /** + * En/disable use of stripslashes. e.g on login screen. + * Otherwise passwords containing "<" are stripped and therefor authentication + * fails against external authentication services. + * @param type $a_stat + */ + public function setUseStripSlashes($a_stat) + { + $this->use_strip_slashes = $a_stat; + } + + /** + * + * @return type + */ + public function getUseStripSlashes() + { + return $this->use_strip_slashes; + } + + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + if ($this->getUseStripSlashes()) { + $_POST[$this->getPostVar()] = ilUtil::stripSlashes($_POST[$this->getPostVar()]); + $_POST[$this->getPostVar() . "_retype"] = ilUtil::stripSlashes($_POST[$this->getPostVar() . "_retype"]); + } + if ($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") { + $this->setAlert($lng->txt("msg_input_is_required")); - return false; - } - if ($this->getValidateAuthPost() != "") - { - $auth = ilAuthUtils::_getAuthMode($_POST[$this->getValidateAuthPost()]); + return false; + } + if ($this->getValidateAuthPost() != "") { + $auth = ilAuthUtils::_getAuthMode($_POST[$this->getValidateAuthPost()]); - // check, if password is required dependent on auth mode - if ($this->getRequiredOnAuth() && ilAuthUtils::_allowPasswordModificationByAuthMode($auth) - && trim($_POST[$this->getPostVar()]) == "") - { - $this->setAlert($lng->txt("form_password_required_for_auth")); - - return false; - } - - // check, if password is allowed to be set for given auth mode - if (trim($_POST[$this->getPostVar()]) != "" && - !ilAuthUtils::_allowPasswordModificationByAuthMode($auth)) - { - $this->setAlert($lng->txt("form_password_not_allowed_for_auth")); - - return false; - } - } - if ($this->getRetype() && - ($_POST[$this->getPostVar()] != $_POST[$this->getPostVar()."_retype"])) - { - $this->setAlert($lng->txt("passwd_not_match")); + // check, if password is required dependent on auth mode + if ($this->getRequiredOnAuth() && ilAuthUtils::_allowPasswordModificationByAuthMode($auth) + && trim($_POST[$this->getPostVar()]) == "") { + $this->setAlert($lng->txt("form_password_required_for_auth")); + + return false; + } + + // check, if password is allowed to be set for given auth mode + if (trim($_POST[$this->getPostVar()]) != "" && + !ilAuthUtils::_allowPasswordModificationByAuthMode($auth)) { + $this->setAlert($lng->txt("form_password_not_allowed_for_auth")); + + return false; + } + } + if ($this->getRetype() && + ($_POST[$this->getPostVar()] != $_POST[$this->getPostVar() . "_retype"])) { + $this->setAlert($lng->txt("passwd_not_match")); - return false; - } - if (!$this->getSkipSyntaxCheck() && - !ilUtil::isPassword($_POST[$this->getPostVar()],$custom_error) && - $_POST[$this->getPostVar()] != "") - { - if($custom_error != '') $this->setAlert($custom_error); - else $this->setAlert($lng->txt("passwd_invalid")); + return false; + } + if (!$this->getSkipSyntaxCheck() && + !ilUtil::isPassword($_POST[$this->getPostVar()], $custom_error) && + $_POST[$this->getPostVar()] != "") { + if ($custom_error != '') { + $this->setAlert($custom_error); + } else { + $this->setAlert($lng->txt("passwd_invalid")); + } - return false; - } - - return $this->checkSubItemsInput(); - } + return false; + } + + return $this->checkSubItemsInput(); + } - /** - * Render item - */ - function render() - { - $lng = $this->lng; - - $ptpl = new ilTemplate("tpl.prop_password.html", true, true, "Services/Form"); - - if ($this->getRetype()) - { - $ptpl->setCurrentBlock("retype"); - $ptpl->setVariable("RSIZE", $this->getSize()); - $ptpl->setVariable("RID", $this->getFieldId()); - $ptpl->setVariable("RMAXLENGTH", $this->getMaxLength()); - $ptpl->setVariable("RPOST_VAR", $this->getPostVar()); + /** + * Render item + */ + public function render() + { + $lng = $this->lng; + + $ptpl = new ilTemplate("tpl.prop_password.html", true, true, "Services/Form"); + + if ($this->getRetype()) { + $ptpl->setCurrentBlock("retype"); + $ptpl->setVariable("RSIZE", $this->getSize()); + $ptpl->setVariable("RID", $this->getFieldId()); + $ptpl->setVariable("RMAXLENGTH", $this->getMaxLength()); + $ptpl->setVariable("RPOST_VAR", $this->getPostVar()); - if($this->isHtmlAutoCompleteDisabled()) - { - $ptpl->setVariable("RAUTOCOMPLETE", "autocomplete=\"off\""); - } + if ($this->isHtmlAutoCompleteDisabled()) { + $ptpl->setVariable("RAUTOCOMPLETE", "autocomplete=\"off\""); + } - // this is creating an "auto entry" in the setup, if the retype is missing - /*$retype_value = ($this->getRetypeValue() != "") - ? $this->getRetypeValue() - : $this->getValue();*/ - $retype_value = $this->getRetypeValue(); - $ptpl->setVariable("PROPERTY_RETYPE_VALUE", ilUtil::prepareFormOutput($retype_value)); - if ($this->getDisabled()) - { - $ptpl->setVariable("RDISABLED", - " disabled=\"disabled\""); - } - $ptpl->setVariable("TXT_RETYPE", $lng->txt("form_retype_password")); - $ptpl->parseCurrentBlock(); - } + // this is creating an "auto entry" in the setup, if the retype is missing + /*$retype_value = ($this->getRetypeValue() != "") + ? $this->getRetypeValue() + : $this->getValue();*/ + $retype_value = $this->getRetypeValue(); + $ptpl->setVariable("PROPERTY_RETYPE_VALUE", ilUtil::prepareFormOutput($retype_value)); + if ($this->getDisabled()) { + $ptpl->setVariable( + "RDISABLED", + " disabled=\"disabled\"" + ); + } + $ptpl->setVariable("TXT_RETYPE", $lng->txt("form_retype_password")); + $ptpl->parseCurrentBlock(); + } - if (strlen($this->getValue())) - { - $ptpl->setCurrentBlock("prop_password_propval"); - $ptpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($this->getValue())); - $ptpl->parseCurrentBlock(); - } - $ptpl->setVariable("POST_VAR", $this->getPostVar()); - $ptpl->setVariable("ID", $this->getFieldId()); - $ptpl->setVariable("SIZE", $this->getSize()); - $ptpl->setVariable("MAXLENGTH", $this->getMaxLength()); - if ($this->getDisabled()) - { - $ptpl->setVariable("DISABLED", - " disabled=\"disabled\""); - } - if($this->isHtmlAutoCompleteDisabled()) - { - $ptpl->setVariable("AUTOCOMPLETE", "autocomplete=\"off\""); - } - if($this->getRequired()) - { - $ptpl->setVariable("REQUIRED", "required=\"required\""); - } - return $ptpl->get(); - } - - /** - * Insert property html - * - * @return int Size - */ - function insert($a_tpl) - { - $html = $this->render(); + if (strlen($this->getValue())) { + $ptpl->setCurrentBlock("prop_password_propval"); + $ptpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($this->getValue())); + $ptpl->parseCurrentBlock(); + } + $ptpl->setVariable("POST_VAR", $this->getPostVar()); + $ptpl->setVariable("ID", $this->getFieldId()); + $ptpl->setVariable("SIZE", $this->getSize()); + $ptpl->setVariable("MAXLENGTH", $this->getMaxLength()); + if ($this->getDisabled()) { + $ptpl->setVariable( + "DISABLED", + " disabled=\"disabled\"" + ); + } + if ($this->isHtmlAutoCompleteDisabled()) { + $ptpl->setVariable("AUTOCOMPLETE", "autocomplete=\"off\""); + } + if ($this->getRequired()) { + $ptpl->setVariable("REQUIRED", "required=\"required\""); + } + return $ptpl->get(); + } + + /** + * Insert property html + * + * @return int Size + */ + public function insert($a_tpl) + { + $html = $this->render(); - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $html); - $a_tpl->parseCurrentBlock(); - } + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $html); + $a_tpl->parseCurrentBlock(); + } } -?> \ No newline at end of file diff --git a/Services/Form/classes/class.ilPropertyFormGUI.php b/Services/Form/classes/class.ilPropertyFormGUI.php index 8285a8d5c04273d917ee4aebc7c73c06c43551aa..e7a2d19cf2610e265fb8948303cf34e7e7ab360f 100644 --- a/Services/Form/classes/class.ilPropertyFormGUI.php +++ b/Services/Form/classes/class.ilPropertyFormGUI.php @@ -39,1207 +39,1108 @@ include_once './Services/Form/classes/class.ilBirthdayInputGUI.php'; /** * This class represents a property form user interface * -* @author Alex Killing +* @author Alex Killing * @version $Id$ * @ilCtrl_Calls ilPropertyFormGUI: ilFormPropertyDispatchGUI * @ingroup ServicesForm */ class ilPropertyFormGUI extends ilFormGUI { - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilSetting - */ - protected $settings; - - private $buttons = array(); - private $items = array(); - protected $mode = "std"; - protected $check_input_called = false; - protected $disable_standard_message = false; - protected $top_anchor = "il_form_top"; - protected $titleicon = false; - protected $description = ""; - protected $tbl_width = false; - protected $show_top_buttons = true; - protected $hide_labels = false; - - - /** - * Constructor - * - * @param - */ - function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - - $this->user = null; - if (isset($DIC["ilUser"])) - { - $this->user = $DIC["ilUser"]; - } - - $this->settings = null; - if (isset($DIC["ilSetting"])) - { - $this->settings = $DIC["ilSetting"]; - } - - $lng = $DIC->language(); - - $lng->loadLanguageModule("form"); - - // avoid double submission - $this->setPreventDoubleSubmission(true); - - // do it as early as possible - $this->rebuildUploadedFiles(); - } - - /** - * Execute command. - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd(); - - switch($next_class) - { - case 'ilformpropertydispatchgui': - $ilCtrl->saveParameter($this, 'postvar'); - include_once './Services/Form/classes/class.ilFormPropertyDispatchGUI.php'; - $form_prop_dispatch = new ilFormPropertyDispatchGUI(); - $item = $this->getItemByPostVar($_REQUEST["postvar"]); - $form_prop_dispatch->setItem($item); - return $ilCtrl->forwardCommand($form_prop_dispatch); - break; - - } - return false; - } - - /** - * Set table width - * - * @access public - * @param string table width - * - */ - final public function setTableWidth($a_width) - { - $this->tbl_width = $a_width; - } - - /** - * get table width - * - * @access public - * - */ - final public function getTableWidth() - { - return $this->tbl_width; - } - - /** - * Set Mode ('std', 'subform'). - * - * @param string $a_mode Mode ('std', 'subform') - */ - function setMode($a_mode) - { - $this->mode = $a_mode; - } - - /** - * Get Mode ('std', 'subform'). - * - * @return string Mode ('std', 'subform') - */ - function getMode() - { - return $this->mode; - } - - /** - * Set Title. - * - * @param string $a_title Title - */ - function setTitle($a_title) - { - $this->title = $a_title; - } - - /** - * Get Title. - * - * @return string Title - */ - function getTitle() - { - return $this->title; - } - - /** - * Set TitleIcon. - * - * @param string $a_titleicon TitleIcon - */ - function setTitleIcon($a_titleicon) - { - $this->titleicon = $a_titleicon; - } - - /** - * Get TitleIcon. - * - * @return string TitleIcon - */ - function getTitleIcon() - { - return $this->titleicon; - } - - /** - * Set description - * - * @param string description - */ - function setDescription($a_val) - { - $this->description = $a_val; - } - - /** - * Get description - * - * @return string description - */ - function getDescription() - { - return $this->description; - } - - /** - * Set top anchor - * - * @param string top anchor - */ - function setTopAnchor($a_val) - { - $this->top_anchor = $a_val; - } - - /** - * Get top anchor - * - * @return string top anchor - */ - function getTopAnchor() - { - return $this->top_anchor; - } - - /** - * Get show top buttons - */ - public function setShowTopButtons($a_val) - { - $this->show_top_buttons = $a_val; - } - - /** - * Set show top buttons - */ - public function getShowTopButtons() - { - return $this->show_top_buttons; - } - - /** - * Add Item (Property, SectionHeader). - * - * @param object $a_property Item object - */ - function addItem($a_item) - { - $a_item->setParentForm($this); - return $this->items[] = $a_item; - } - - /** - * Remove Item. - * - * @param string $a_postvar Post Var - */ - function removeItemByPostVar($a_post_var, $a_remove_unused_headers = false) - { - foreach ($this->items as $key => $item) - { - if (method_exists($item, "getPostVar") && $item->getPostVar() == $a_post_var) - { - unset($this->items[$key]); - } - } - - // remove section headers if they do not contain any items anymore - if ($a_remove_unused_headers) - { - $unset_keys = array(); - $last_item = null; - $last_key = null; - foreach ($this->items as $key => $item) - { - if ($item instanceof ilFormSectionHeaderGUI && $last_item instanceof ilFormSectionHeaderGUI) - { - $unset_keys[] = $last_key; - } - $last_item = $item; - $last_key = $key; - } - if ($last_item instanceof ilFormSectionHeaderGUI) - { - $unset_keys[] = $last_key; - } - foreach ($unset_keys as $key) - { - unset($this->items[$key]); - } - } - } - - /** - * Get Item by POST variable. - * - * @param string $a_postvar Post Var - */ - function getItemByPostVar($a_post_var) - { - foreach ($this->items as $key => $item) - { - if ($item->getType() != "section_header") - { - //if ($item->getPostVar() == $a_post_var) - $ret = $item->getItemByPostVar($a_post_var); - if (is_object($ret)) - { - return $ret; - } - } - } - - return false; - } - - /** - * Set Items - * - * @param array $a_items array of item objects - */ - function setItems($a_items) - { - $this->items = $a_items; - } - - /** - * Get Items - * - * @return array array of item objects - */ - function getItems() - { - return $this->items; - } - - /** - * returns a flat array of all input items including - * the possibly existing subitems recursively - * - * @return array - */ - public function getInputItemsRecursive() - { - $inputItems = array(); - - foreach($this->items as $item) - { - if( $item->getType() == 'section_header' ) - { - continue; - } - - $inputItems[] = $item; - - if( $item instanceof ilSubEnabledFormPropertyGUI ) - { - $inputItems = array_merge( $inputItems, $item->getSubInputItemsRecursive() ); - } - } - - return $inputItems; - } - - /** - * Set disable standard message - * - * @param boolean disable standard message - */ - function setDisableStandardMessage($a_val) - { - $this->disable_standard_message = $a_val; - } - - /** - * Get disable standard message - * - * @return boolean disable standard message - */ - function getDisableStandardMessage() - { - return $this->disable_standard_message; - } - - /** - * Get a value indicating whether the labels should be hidden or not. - * - * @return boolean true, to hide the labels; otherwise, false. - */ - function getHideLabels() - { - return $this->hide_labels; - } - - /** - * Set a value indicating whether the labels should be hidden or not. - * - * @param boolean $a_value Indicates whether the labels should be hidden. - */ - function setHideLabels($a_value = true) - { - $this->hide_labels = $a_value; - } - - /** - * Set form values from an array - * - * @param array $a_values Value array (key is post variable name, value is value) - */ - function setValuesByArray($a_values, $a_restrict_to_value_keys = false) - { - foreach($this->items as $item) - { - if(!($a_restrict_to_value_keys) || - in_array($item->getPostVar(), array_keys($a_values))) - { - $item->setValueByArray($a_values); - } - } - } - - /** - * Set form values from POST values - * - */ - function setValuesByPost() - { - foreach ($this->items as $item) - { - $item->setValueByArray($_POST); - } - } - - /** - * Check Post Input. This method also strips slashes and html from - * input and sets the alert texts for the items, if the input was not ok. - * - * @return boolean ok true/false - */ - function checkInput() - { - global $DIC; - - if ($this->check_input_called) - { - die ("Error: ilPropertyFormGUI->checkInput() called twice."); - } - - $ok = true; - foreach($this->items as $item) - { - $item_ok = $item->checkInput(); - if(!$item_ok) - { - $ok = false; - } - } - - // check if POST is missint completely (if post_max_size exceeded) - if (count($this->items) > 0 && !is_array($_POST)) - { - $ok = false; - } - - $this->check_input_called = true; - - - - // try to keep uploads for another try - if(!$ok && $_POST["ilfilehash"] && sizeof($_FILES)) - { - $hash = $_POST["ilfilehash"]; - - foreach($_FILES as $field => $data) - { - // only try to keep files that are ok - // see 25484: Wrong error handling when uploading icon instead of tile - $item = $this->getItemByPostVar($field); - if (!$item->checkInput()) - { - continue; - } - // we support up to 2 nesting levels (see test/assesment) - if(is_array($data["tmp_name"])) - { - foreach($data["tmp_name"] as $idx => $upload) - { - if(is_array($upload)) - { - foreach($upload as $idx2 => $file) - { - if($file && is_uploaded_file($file)) - { - $file_name = $data["name"][$idx][$idx2]; - $file_type = $data["type"][$idx][$idx2]; - $this->keepFileUpload($hash, $field, $file, $file_name, $file_type, $idx, $idx2); - } - } - } - else if($upload && is_uploaded_file($upload)) - { - $file_name = $data["name"][$idx]; - $file_type = $data["type"][$idx]; - $this->keepFileUpload($hash, $field, $upload, $file_name, $file_type, $idx); - } - } - } - else - { - $this->keepFileUpload($hash, $field, $data["tmp_name"], $data["name"], $data["type"]); - } - } - } - $http = $DIC->http(); - $txt = $DIC->language()->txt("form_input_not_valid"); - switch ($http->request()->getHeaderLine('Accept')) { - // When JS asks for a valid JSON-Response, we send the success and message as JSON - case 'application/json': - $stream = \ILIAS\Filesystem\Stream\Streams::ofString(json_encode([ - 'success' => $ok, - 'message' => $txt, - ])); - $http->saveResponse($http->response()->withBody($stream)); - - return $ok; - - // Otherwise we send it using ilUtil and it will be rendered in the Template - default: - - if (!$ok && !$this->getDisableStandardMessage()) { - ilUtil::sendFailure($txt); - } - - return $ok; - } - } - - /** - * - * Returns the value of a HTTP-POST variable, identified by the passed id - * - * @param string The key used for value determination - * @param boolean A flag whether the form input has to be validated before calling this method - * @return string The value of a HTTP-POST variable, identified by the passed id - * @access public - * - */ - public function getInput($a_post_var, $ensureValidation = true) - { - // this check ensures, that checkInput has been called (incl. stripSlashes()) - if (!$this->check_input_called && $ensureValidation) - { - die ("Error: ilPropertyFormGUI->getInput() called without calling checkInput() first."); - } - - return $_POST[$a_post_var]; - } - - /** - * Add a custom property. - * - * @param string Title - * @param string HTML. - * @param string Info text. - * @param string Alert text. - * @param boolean Required field. (Default false) - */ - function addCustomProperty($a_title, $a_html, $a_info = "", - $a_alert = "", $a_required = false) - { - $this->properties[] = array ("type" => "custom", - "title" => $a_title, - "html" => $a_html, - "info" => $a_info); - } - - /** - * Add Command button - * - * @param string Command - * @param string Text - */ - function addCommandButton($a_cmd, $a_text, $a_id = "") - { - $this->buttons[] = array("cmd" => $a_cmd, "text" => $a_text, "id" => $a_id); - } - - - /** - * Return all Command buttons - * - * @return array - */ - public function getCommandButtons() { - return $this->buttons; - } - - /** - * Remove all command buttons - */ - function clearCommandButtons() - { - $this->buttons = array(); - } - - /** - * Get Content. - */ - function getContent() - { - global $DIC; - $lng = $this->lng; - $tpl = $DIC["tpl"]; - $ilSetting = $this->settings; - - include_once("./Services/YUI/classes/class.ilYuiUtil.php"); - ilYuiUtil::initEvent(); - ilYuiUtil::initDom(); - ilYuiUtil::initAnimation(); - - $tpl->addJavaScript("./Services/JavaScript/js/Basic.js"); - $tpl->addJavaScript("Services/Form/js/Form.js"); - - $this->tpl = new ilTemplate("tpl.property_form.html", true, true, "Services/Form"); - - // check if form has not title and first item is a section header - // -> use section header for title and remove section header - // -> command buttons are presented on top - $fi = $this->items[0]; - if ($this->getMode() == "std" && - $this->getTitle() == "" && - is_object($fi) && $fi->getType() == "section_header" - ) - { - $this->setTitle($fi->getTitle()); - unset($this->items[0]); - } - - - // title icon - if ($this->getTitleIcon() != "" && @is_file($this->getTitleIcon())) - { - $this->tpl->setCurrentBlock("title_icon"); - $this->tpl->setVariable("IMG_ICON", $this->getTitleIcon()); - $this->tpl->parseCurrentBlock(); - } - - // title - if ($this->getTitle() != "") - { - // commands on top - if (count($this->buttons) > 0 && $this->getShowTopButtons() && count($this->items) > 2) - { - // command buttons - foreach($this->buttons as $button) - { - $this->tpl->setCurrentBlock("cmd2"); - $this->tpl->setVariable("CMD", $button["cmd"]); - $this->tpl->setVariable("CMD_TXT", $button["text"]); - if ($button["id"] != "") - { - $this->tpl->setVariable("CMD2_ID", " id='".$button["id"]."_top'"); - } - $this->tpl->parseCurrentBlock(); - } - $this->tpl->setCurrentBlock("commands2"); - $this->tpl->parseCurrentBlock(); - } - - if (is_object($ilSetting)) - { - if ($ilSetting->get('char_selector_availability') > 0) - { - require_once 'Services/UIComponent/CharSelector/classes/class.ilCharSelectorGUI.php'; - if (ilCharSelectorGUI::_isAllowed()) - { - $char_selector = ilCharSelectorGUI::_getCurrentGUI(); - if ($char_selector->getConfig()->getAvailability() == ilCharSelectorConfig::ENABLED) - { - $char_selector->addToPage(); - $this->tpl->TouchBlock('char_selector'); - } - } - } - } - - $this->tpl->setCurrentBlock("header"); - $this->tpl->setVariable("TXT_TITLE", $this->getTitle()); - $this->tpl->setVariable("LABEL", $this->getTopAnchor()); - $this->tpl->setVariable("TXT_DESCRIPTION", $this->getDescription()); - $this->tpl->parseCurrentBlock(); - } - $this->tpl->touchBlock("item"); - - // properties - $this->required_text = false; - foreach($this->items as $item) - { - if ($item->getType() != "hidden") - { - $this->insertItem($item); - } - } - - // required - if ($this->required_text && $this->getMode() == "std") - { - $this->tpl->setCurrentBlock("required_text"); - $this->tpl->setVariable("TXT_REQUIRED", $lng->txt("required_field")); - $this->tpl->parseCurrentBlock(); - } - - // command buttons - foreach($this->buttons as $button) - { - $this->tpl->setCurrentBlock("cmd"); - $this->tpl->setVariable("CMD", $button["cmd"]); - $this->tpl->setVariable("CMD_TXT", $button["text"]); - - if ($button["id"] != "") - { - $this->tpl->setVariable("CMD_ID", " id='".$button["id"]."'"); - } - - $this->tpl->parseCurrentBlock(); - } - - // #18808 - if ($this->getMode() != "subform") - { - // try to keep uploads even if checking input fails - if($this->getMultipart()) - { - $hash = $_POST["ilfilehash"]; - if(!$hash) - { - $hash = md5(uniqid(mt_rand(), true)); - } - $fhash = new ilHiddenInputGUI("ilfilehash"); - $fhash->setValue($hash); - $this->addItem($fhash); - } - } - - // hidden properties - $hidden_fields = false; - foreach($this->items as $item) - { - if ($item->getType() == "hidden") - { - $item->insert($this->tpl); - $hidden_fields = true; - } - } - - if ($this->required_text || count($this->buttons) > 0 || $hidden_fields) - { - $this->tpl->setCurrentBlock("commands"); - $this->tpl->parseCurrentBlock(); - } - - - if ($this->getMode() == "subform") - { - $this->tpl->touchBlock("sub_table"); - } - else - { - $this->tpl->touchBlock("std_table"); - $this->tpl->setVariable('STD_TABLE_WIDTH',$this->getTableWidth()); - } - - return $this->tpl->get(); - } - - protected function hideRequired($a_type) - { - // #15818 - return in_array($a_type, array("non_editable_value")); - } - - function insertItem($item, $a_sub_item = false) - { - global $DIC; - $tpl = $DIC["tpl"];; - $lng = $this->lng; - - - $cfg = array(); - - //if(method_exists($item, "getMulti") && $item->getMulti()) - if ($item instanceof ilMultiValuesItem && $item->getMulti()) - { - $tpl->addJavascript("./Services/Form/js/ServiceFormMulti.js"); - - $this->tpl->setCurrentBlock("multi_in"); - $this->tpl->setVariable("ID", $item->getFieldId()); - $this->tpl->parseCurrentBlock(); - - $this->tpl->touchBlock("multi_out"); - - - // add hidden item to enable preset multi items - // not used yet, should replace hidden field stuff - $multi_values = $item->getMultiValues(); - if(is_array($multi_values) && sizeof($multi_values) > 1) - { - $multi_value = new ilHiddenInputGUI("ilMultiValues~".$item->getPostVar()); - $multi_value->setValue(implode("~", $multi_values)); - $this->addItem($multi_value); - } - $cfg["multi_values"] = $multi_values; - } - - $item->insert($this->tpl); - - if ($item->getType() == "file" || $item->getType() == "image_file") - { - $this->setMultipart(true); - } - - if ($item->getType() != "section_header") - { - $cfg["id"] = $item->getFieldId(); - - // info text - if ($item->getInfo() != "") - { - $this->tpl->setCurrentBlock("description"); - $this->tpl->setVariable("PROPERTY_DESCRIPTION", - $item->getInfo()); - $this->tpl->parseCurrentBlock(); - } - - if ($this->getMode() == "subform") - { - // required - if (!$this->hideRequired($item->getType())) - { - if ($item->getRequired()) - { - $this->tpl->touchBlock("sub_required"); - $this->required_text = true; - } - } - - // hidden title (for accessibility, e.g. file upload) - if ($item->getHiddenTitle() != "") - { - $this->tpl->setCurrentBlock("sub_hid_title"); - $this->tpl->setVariable("SPHID_TITLE", - $item->getHiddenTitle()); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setCurrentBlock("sub_prop_start"); - $this->tpl->setVariable("PROPERTY_TITLE", $item->getTitle()); - $this->tpl->setVariable("PROPERTY_CLASS", "il_".$item->getType()); - if ($item->getType() != "non_editable_value") - { - $this->tpl->setVariable("LAB_ID", $item->getFieldId()); - } - $this->tpl->parseCurrentBlock(); - } - else - { - // required - if (!$this->hideRequired($item->getType())) - { - if ($item->getRequired()) - { - $this->tpl->touchBlock("required"); - $this->required_text = true; - } - } - - // hidden title (for accessibility, e.g. file upload) - if ($item->getHiddenTitle() != "") - { - $this->tpl->setCurrentBlock("std_hid_title"); - $this->tpl->setVariable("PHID_TITLE", - $item->getHiddenTitle()); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setCurrentBlock("std_prop_start"); - $this->tpl->setVariable("PROPERTY_TITLE", $item->getTitle()); - if ($item->getType() != "non_editable_value") - { - $this->tpl->setVariable("LAB_ID", $item->getFieldId()); - } - if ($this->getHideLabels()) - { - $this->tpl->setVariable("HIDE_LABELS_STYLE", " ilFormOptionHidden"); - } - $this->tpl->parseCurrentBlock(); - } - - // alert - if ($item->getType() != "non_editable_value" && $item->getAlert() != "") - { - $this->tpl->setCurrentBlock("alert"); - $this->tpl->setVariable("IMG_ALERT", - ilUtil::getImagePath("icon_alert.svg")); - $this->tpl->setVariable("ALT_ALERT", - $lng->txt("alert")); - $this->tpl->setVariable("TXT_ALERT", - $item->getAlert()); - $this->tpl->parseCurrentBlock(); - } - - // subitems - $sf = null; - if ($item->getType() != "non_editable_value" or 1) - { - $sf = $item->getSubForm(); - if ($item->hideSubForm() && is_object($sf)) - { - $this->tpl->setCurrentBlock("sub_form_hide"); - $this->tpl->setVariable("DSFID", $item->getFieldId()); - $this->tpl->parseCurrentBlock(); - } - } - - - $sf_content = ""; - if (is_object($sf)) - { - $sf_content = $sf->getContent(); - if ($sf->getMultipart()) - { - $this->setMultipart(true); - } - $this->tpl->setCurrentBlock("sub_form"); - $this->tpl->setVariable("PROP_SUB_FORM", $sf_content); - $this->tpl->setVariable("SFID", $item->getFieldId()); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setCurrentBlock("prop"); - /* not used yet - $this->tpl->setVariable("ID", $item->getFieldId()); - $this->tpl->setVariable("CFG", ilJsonUtil::encode($cfg));*/ - $this->tpl->parseCurrentBlock(); - } - - - $this->tpl->touchBlock("item"); - } - - public function getHTML() - { - $html = parent::getHTML(); - - // #13531 - get content that has to reside outside of the parent form tag, e.g. panels/layers - foreach($this->items as $item) - { - // #13536 - ilFormSectionHeaderGUI does NOT extend ilFormPropertyGUI ?! - if(method_exists($item, "getContentOutsideFormTag")) - { - $outside = $item->getContentOutsideFormTag(); - if($outside) - { - $html .= $outside; - } - } - } - - return $html; - } - - - // - // UPLOAD HANDLING - // - - /** - * Import upload into temp directory - * - * @param string $a_hash unique form hash - * @param string $a_field form field - * @param string $a_tmp_name temp file name - * @param string $a_name original file name - * @param string $a_type file mime type - * @param mixed $a_index form field index (if array) - * @param mixed $a_sub_index form field subindex (if array) - * @return bool - */ - protected function keepFileUpload($a_hash, $a_field, $a_tmp_name, $a_name, $a_type, $a_index = null, $a_sub_index = null) - { - if (trim($a_tmp_name) == "") - { - return; - } - - $a_name = ilUtil::getAsciiFileName($a_name); - - $tmp_file_name = implode("~~", array(session_id(), - $a_hash, - $a_field, - $a_index, - $a_sub_index, - str_replace("/", "~~", $a_type), - str_replace("~~", "_", $a_name))); - - // make sure temp directory exists - $temp_path = ilUtil::getDataDir() . "/temp"; - if (!is_dir($temp_path)) - { - ilUtil::createDirectory($temp_path); - } - - ilUtil::moveUploadedFile($a_tmp_name, $tmp_file_name, $temp_path . "/" . $tmp_file_name); - - /** @var ilFileInputGUI $file_input */ - $file_input = $this->getItemByPostVar($a_field); - $file_input->setPending($a_name); - } - - /** - * Get file upload data - * - * @param string $a_field form field - * @param mixed $a_index form field index (if array) - * @param mixed $a_sub_index form field subindex (if array) - * @return array (tmp_name, name, type, error, size, is_upload) - */ - function getFileUpload($a_field, $a_index = null, $a_sub_index = null) - { - $res = array(); - if($a_index) - { - if($_FILES[$a_field]["tmp_name"][$a_index][$a_sub_index]) - { - $res = array( - "tmp_name" => $_FILES[$a_field]["tmp_name"][$a_index][$a_sub_index], - "name" => $_FILES[$a_field]["name"][$a_index][$a_sub_index], - "type" => $_FILES[$a_field]["type"][$a_index][$a_sub_index], - "error" => $_FILES[$a_field]["error"][$a_index][$a_sub_index], - "size" => $_FILES[$a_field]["size"][$a_index][$a_sub_index], - "is_upload" => true - ); - } - } - else if($a_sub_index) - { - if($_FILES[$a_field]["tmp_name"][$a_index]) - { - $res = array( - "tmp_name" => $_FILES[$a_field]["tmp_name"][$a_index], - "name" => $_FILES[$a_field]["name"][$a_index], - "type" => $_FILES[$a_field]["type"][$a_index], - "error" => $_FILES[$a_field]["error"][$a_index], - "size" => $_FILES[$a_field]["size"][$a_index], - "is_upload" => true - ); - } - } - else - { - if($_FILES[$a_field]["tmp_name"]) - { - $res = array( - "tmp_name" => $_FILES[$a_field]["tmp_name"], - "name" => $_FILES[$a_field]["name"], - "type" => $_FILES[$a_field]["type"], - "error" => $_FILES[$a_field]["error"], - "size" => $_FILES[$a_field]["size"], - "is_upload" => true - ); - } - } - return $res; - } - - /** - * Was any file uploaded? - * - * @param string $a_field form field - * @param mixed $a_index form field index (if array) - * @param mixed $a_sub_index form field subindex (if array) - * @return bool - */ - function hasFileUpload($a_field, $a_index = null, $a_sub_index = null) - { - $data = $this->getFileUpload($a_field, $a_index, $a_sub_index); - return (bool)$data["tmp_name"]; - } - - /** - * Move upload to target directory - * - * @param string $a_target_directory target directory (without filename!) - * @param string $a_field form field - * @param string $a_target_name target file name (if different from uploaded file) - * @param mixed $a_index form field index (if array) - * @param mixed $a_sub_index form field subindex (if array) - * @return string target file name incl. path - */ - function moveFileUpload($a_target_directory, $a_field, $a_target_name = null, $a_index = null, $a_sub_index = null) - { - if(!is_dir($a_target_directory)) - { - return; - } - - $data = $this->getFileUpload($a_field, $a_index, $a_sub_index); - if($data["tmp_name"] && file_exists($data["tmp_name"])) - { - if($a_target_name) - { - $data["name"] = $a_target_name; - } - - $target_file = $a_target_directory."/".$data["name"]; - $target_file = str_replace("//", "/", $target_file); - - if($data["is_upload"]) - { - if (!ilUtil::moveUploadedFile($data["tmp_name"], $data["name"], $target_file)) - { - return; - } - } - else - { - if (!rename($data["tmp_name"], $target_file)) - { - return; - } - } - - return $target_file; - } - } - - /** - * try to rebuild files - */ - protected function rebuildUploadedFiles() - { - if(isset($_POST["ilfilehash"]) && $_POST["ilfilehash"]) - { - $temp_path = ilUtil::getDataDir() . "/temp"; - if(is_dir($temp_path)) - { - $reload = array(); - - $temp_files = glob($temp_path."/".session_id()."~~".$_POST["ilfilehash"]."~~*"); - if(is_array($temp_files)) - { - foreach($temp_files as $full_file) - { - $file = explode("~~", basename($full_file)); - $field = $file[2]; - $idx = $file[3]; - $idx2 = $file[4]; - $type = $file[5]."/".$file[6]; - $name = $file[7]; - - if($idx2 != "") - { - if(!$_FILES[$field]["tmp_name"][$idx][$idx2]) - { - $_FILES[$field]["tmp_name"][$idx][$idx2] = $full_file; - $_FILES[$field]["name"][$idx][$idx2] = $name; - $_FILES[$field]["type"][$idx][$idx2] = $type; - $_FILES[$field]["error"][$idx][$idx2] = 0; - $_FILES[$field]["size"][$idx][$idx2] = filesize($full_file); - } - } - else if($idx != "") - { - if(!$_FILES[$field]["tmp_name"][$idx]) - { - $_FILES[$field]["tmp_name"][$idx] = $full_file; - $_FILES[$field]["name"][$idx] = $name; - $_FILES[$field]["type"][$idx] = $type; - $_FILES[$field]["error"][$idx] = 0; - $_FILES[$field]["size"][$idx] = filesize($full_file); - } - } - else - { - if(!$_FILES[$field]["tmp_name"]) - { - $_FILES[$field]["tmp_name"] = $full_file; - $_FILES[$field]["name"] = $name; - $_FILES[$field]["type"] = $type; - $_FILES[$field]["error"] = 0; - $_FILES[$field]["size"] = filesize($full_file); - } - } - } - } - } - } - } + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilSetting + */ + protected $settings; + + private $buttons = array(); + private $items = array(); + protected $mode = "std"; + protected $check_input_called = false; + protected $disable_standard_message = false; + protected $top_anchor = "il_form_top"; + protected $titleicon = false; + protected $description = ""; + protected $tbl_width = false; + protected $show_top_buttons = true; + protected $hide_labels = false; + + + /** + * Constructor + * + * @param + */ + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + + $this->user = null; + if (isset($DIC["ilUser"])) { + $this->user = $DIC["ilUser"]; + } + + $this->settings = null; + if (isset($DIC["ilSetting"])) { + $this->settings = $DIC["ilSetting"]; + } + + $lng = $DIC->language(); + + $lng->loadLanguageModule("form"); + + // avoid double submission + $this->setPreventDoubleSubmission(true); + + // do it as early as possible + $this->rebuildUploadedFiles(); + } + + /** + * Execute command. + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd(); + + switch ($next_class) { + case 'ilformpropertydispatchgui': + $ilCtrl->saveParameter($this, 'postvar'); + include_once './Services/Form/classes/class.ilFormPropertyDispatchGUI.php'; + $form_prop_dispatch = new ilFormPropertyDispatchGUI(); + $item = $this->getItemByPostVar($_REQUEST["postvar"]); + $form_prop_dispatch->setItem($item); + return $ilCtrl->forwardCommand($form_prop_dispatch); + break; + + } + return false; + } + + /** + * Set table width + * + * @access public + * @param string table width + * + */ + final public function setTableWidth($a_width) + { + $this->tbl_width = $a_width; + } + + /** + * get table width + * + * @access public + * + */ + final public function getTableWidth() + { + return $this->tbl_width; + } + + /** + * Set Mode ('std', 'subform'). + * + * @param string $a_mode Mode ('std', 'subform') + */ + public function setMode($a_mode) + { + $this->mode = $a_mode; + } + + /** + * Get Mode ('std', 'subform'). + * + * @return string Mode ('std', 'subform') + */ + public function getMode() + { + return $this->mode; + } + + /** + * Set Title. + * + * @param string $a_title Title + */ + public function setTitle($a_title) + { + $this->title = $a_title; + } + + /** + * Get Title. + * + * @return string Title + */ + public function getTitle() + { + return $this->title; + } + + /** + * Set TitleIcon. + * + * @param string $a_titleicon TitleIcon + */ + public function setTitleIcon($a_titleicon) + { + $this->titleicon = $a_titleicon; + } + + /** + * Get TitleIcon. + * + * @return string TitleIcon + */ + public function getTitleIcon() + { + return $this->titleicon; + } + + /** + * Set description + * + * @param string description + */ + public function setDescription($a_val) + { + $this->description = $a_val; + } + + /** + * Get description + * + * @return string description + */ + public function getDescription() + { + return $this->description; + } + + /** + * Set top anchor + * + * @param string top anchor + */ + public function setTopAnchor($a_val) + { + $this->top_anchor = $a_val; + } + + /** + * Get top anchor + * + * @return string top anchor + */ + public function getTopAnchor() + { + return $this->top_anchor; + } + + /** + * Get show top buttons + */ + public function setShowTopButtons($a_val) + { + $this->show_top_buttons = $a_val; + } + + /** + * Set show top buttons + */ + public function getShowTopButtons() + { + return $this->show_top_buttons; + } + + /** + * Add Item (Property, SectionHeader). + * + * @param object $a_property Item object + */ + public function addItem($a_item) + { + $a_item->setParentForm($this); + return $this->items[] = $a_item; + } + + /** + * Remove Item. + * + * @param string $a_postvar Post Var + */ + public function removeItemByPostVar($a_post_var, $a_remove_unused_headers = false) + { + foreach ($this->items as $key => $item) { + if (method_exists($item, "getPostVar") && $item->getPostVar() == $a_post_var) { + unset($this->items[$key]); + } + } + + // remove section headers if they do not contain any items anymore + if ($a_remove_unused_headers) { + $unset_keys = array(); + $last_item = null; + $last_key = null; + foreach ($this->items as $key => $item) { + if ($item instanceof ilFormSectionHeaderGUI && $last_item instanceof ilFormSectionHeaderGUI) { + $unset_keys[] = $last_key; + } + $last_item = $item; + $last_key = $key; + } + if ($last_item instanceof ilFormSectionHeaderGUI) { + $unset_keys[] = $last_key; + } + foreach ($unset_keys as $key) { + unset($this->items[$key]); + } + } + } + + /** + * Get Item by POST variable. + * + * @param string $a_postvar Post Var + */ + public function getItemByPostVar($a_post_var) + { + foreach ($this->items as $key => $item) { + if ($item->getType() != "section_header") { + //if ($item->getPostVar() == $a_post_var) + $ret = $item->getItemByPostVar($a_post_var); + if (is_object($ret)) { + return $ret; + } + } + } + + return false; + } + + /** + * Set Items + * + * @param array $a_items array of item objects + */ + public function setItems($a_items) + { + $this->items = $a_items; + } + + /** + * Get Items + * + * @return array array of item objects + */ + public function getItems() + { + return $this->items; + } + + /** + * returns a flat array of all input items including + * the possibly existing subitems recursively + * + * @return array + */ + public function getInputItemsRecursive() + { + $inputItems = array(); + + foreach ($this->items as $item) { + if ($item->getType() == 'section_header') { + continue; + } + + $inputItems[] = $item; + + if ($item instanceof ilSubEnabledFormPropertyGUI) { + $inputItems = array_merge($inputItems, $item->getSubInputItemsRecursive()); + } + } + + return $inputItems; + } + + /** + * Set disable standard message + * + * @param boolean disable standard message + */ + public function setDisableStandardMessage($a_val) + { + $this->disable_standard_message = $a_val; + } + + /** + * Get disable standard message + * + * @return boolean disable standard message + */ + public function getDisableStandardMessage() + { + return $this->disable_standard_message; + } + + /** + * Get a value indicating whether the labels should be hidden or not. + * + * @return boolean true, to hide the labels; otherwise, false. + */ + public function getHideLabels() + { + return $this->hide_labels; + } + + /** + * Set a value indicating whether the labels should be hidden or not. + * + * @param boolean $a_value Indicates whether the labels should be hidden. + */ + public function setHideLabels($a_value = true) + { + $this->hide_labels = $a_value; + } + + /** + * Set form values from an array + * + * @param array $a_values Value array (key is post variable name, value is value) + */ + public function setValuesByArray($a_values, $a_restrict_to_value_keys = false) + { + foreach ($this->items as $item) { + if (!($a_restrict_to_value_keys) || + in_array($item->getPostVar(), array_keys($a_values))) { + $item->setValueByArray($a_values); + } + } + } + + /** + * Set form values from POST values + * + */ + public function setValuesByPost() + { + foreach ($this->items as $item) { + $item->setValueByArray($_POST); + } + } + + /** + * Check Post Input. This method also strips slashes and html from + * input and sets the alert texts for the items, if the input was not ok. + * + * @return boolean ok true/false + */ + public function checkInput() + { + global $DIC; + + if ($this->check_input_called) { + die("Error: ilPropertyFormGUI->checkInput() called twice."); + } + + $ok = true; + foreach ($this->items as $item) { + $item_ok = $item->checkInput(); + if (!$item_ok) { + $ok = false; + } + } + + // check if POST is missint completely (if post_max_size exceeded) + if (count($this->items) > 0 && !is_array($_POST)) { + $ok = false; + } + + $this->check_input_called = true; + + + + // try to keep uploads for another try + if (!$ok && $_POST["ilfilehash"] && sizeof($_FILES)) { + $hash = $_POST["ilfilehash"]; + + foreach ($_FILES as $field => $data) { + // only try to keep files that are ok + // see 25484: Wrong error handling when uploading icon instead of tile + $item = $this->getItemByPostVar($field); + if (!$item->checkInput()) { + continue; + } + // we support up to 2 nesting levels (see test/assesment) + if (is_array($data["tmp_name"])) { + foreach ($data["tmp_name"] as $idx => $upload) { + if (is_array($upload)) { + foreach ($upload as $idx2 => $file) { + if ($file && is_uploaded_file($file)) { + $file_name = $data["name"][$idx][$idx2]; + $file_type = $data["type"][$idx][$idx2]; + $this->keepFileUpload($hash, $field, $file, $file_name, $file_type, $idx, $idx2); + } + } + } elseif ($upload && is_uploaded_file($upload)) { + $file_name = $data["name"][$idx]; + $file_type = $data["type"][$idx]; + $this->keepFileUpload($hash, $field, $upload, $file_name, $file_type, $idx); + } + } + } else { + $this->keepFileUpload($hash, $field, $data["tmp_name"], $data["name"], $data["type"]); + } + } + } + $http = $DIC->http(); + $txt = $DIC->language()->txt("form_input_not_valid"); + switch ($http->request()->getHeaderLine('Accept')) { + // When JS asks for a valid JSON-Response, we send the success and message as JSON + case 'application/json': + $stream = \ILIAS\Filesystem\Stream\Streams::ofString(json_encode([ + 'success' => $ok, + 'message' => $txt, + ])); + $http->saveResponse($http->response()->withBody($stream)); + + return $ok; + + // Otherwise we send it using ilUtil and it will be rendered in the Template + default: + + if (!$ok && !$this->getDisableStandardMessage()) { + ilUtil::sendFailure($txt); + } + + return $ok; + } + } + + /** + * + * Returns the value of a HTTP-POST variable, identified by the passed id + * + * @param string The key used for value determination + * @param boolean A flag whether the form input has to be validated before calling this method + * @return string The value of a HTTP-POST variable, identified by the passed id + * @access public + * + */ + public function getInput($a_post_var, $ensureValidation = true) + { + // this check ensures, that checkInput has been called (incl. stripSlashes()) + if (!$this->check_input_called && $ensureValidation) { + die("Error: ilPropertyFormGUI->getInput() called without calling checkInput() first."); + } + + return $_POST[$a_post_var]; + } + + /** + * Add a custom property. + * + * @param string Title + * @param string HTML. + * @param string Info text. + * @param string Alert text. + * @param boolean Required field. (Default false) + */ + public function addCustomProperty( + $a_title, + $a_html, + $a_info = "", + $a_alert = "", + $a_required = false + ) { + $this->properties[] = array("type" => "custom", + "title" => $a_title, + "html" => $a_html, + "info" => $a_info); + } + + /** + * Add Command button + * + * @param string Command + * @param string Text + */ + public function addCommandButton($a_cmd, $a_text, $a_id = "") + { + $this->buttons[] = array("cmd" => $a_cmd, "text" => $a_text, "id" => $a_id); + } + + + /** + * Return all Command buttons + * + * @return array + */ + public function getCommandButtons() + { + return $this->buttons; + } + + /** + * Remove all command buttons + */ + public function clearCommandButtons() + { + $this->buttons = array(); + } + + /** + * Get Content. + */ + public function getContent() + { + global $DIC; + $lng = $this->lng; + $tpl = $DIC["tpl"]; + $ilSetting = $this->settings; + + include_once("./Services/YUI/classes/class.ilYuiUtil.php"); + ilYuiUtil::initEvent(); + ilYuiUtil::initDom(); + ilYuiUtil::initAnimation(); + + $tpl->addJavaScript("./Services/JavaScript/js/Basic.js"); + $tpl->addJavaScript("Services/Form/js/Form.js"); + + $this->tpl = new ilTemplate("tpl.property_form.html", true, true, "Services/Form"); + + // check if form has not title and first item is a section header + // -> use section header for title and remove section header + // -> command buttons are presented on top + $fi = $this->items[0]; + if ($this->getMode() == "std" && + $this->getTitle() == "" && + is_object($fi) && $fi->getType() == "section_header" + ) { + $this->setTitle($fi->getTitle()); + unset($this->items[0]); + } + + + // title icon + if ($this->getTitleIcon() != "" && @is_file($this->getTitleIcon())) { + $this->tpl->setCurrentBlock("title_icon"); + $this->tpl->setVariable("IMG_ICON", $this->getTitleIcon()); + $this->tpl->parseCurrentBlock(); + } + + // title + if ($this->getTitle() != "") { + // commands on top + if (count($this->buttons) > 0 && $this->getShowTopButtons() && count($this->items) > 2) { + // command buttons + foreach ($this->buttons as $button) { + $this->tpl->setCurrentBlock("cmd2"); + $this->tpl->setVariable("CMD", $button["cmd"]); + $this->tpl->setVariable("CMD_TXT", $button["text"]); + if ($button["id"] != "") { + $this->tpl->setVariable("CMD2_ID", " id='" . $button["id"] . "_top'"); + } + $this->tpl->parseCurrentBlock(); + } + $this->tpl->setCurrentBlock("commands2"); + $this->tpl->parseCurrentBlock(); + } + + if (is_object($ilSetting)) { + if ($ilSetting->get('char_selector_availability') > 0) { + require_once 'Services/UIComponent/CharSelector/classes/class.ilCharSelectorGUI.php'; + if (ilCharSelectorGUI::_isAllowed()) { + $char_selector = ilCharSelectorGUI::_getCurrentGUI(); + if ($char_selector->getConfig()->getAvailability() == ilCharSelectorConfig::ENABLED) { + $char_selector->addToPage(); + $this->tpl->TouchBlock('char_selector'); + } + } + } + } + + $this->tpl->setCurrentBlock("header"); + $this->tpl->setVariable("TXT_TITLE", $this->getTitle()); + $this->tpl->setVariable("LABEL", $this->getTopAnchor()); + $this->tpl->setVariable("TXT_DESCRIPTION", $this->getDescription()); + $this->tpl->parseCurrentBlock(); + } + $this->tpl->touchBlock("item"); + + // properties + $this->required_text = false; + foreach ($this->items as $item) { + if ($item->getType() != "hidden") { + $this->insertItem($item); + } + } + + // required + if ($this->required_text && $this->getMode() == "std") { + $this->tpl->setCurrentBlock("required_text"); + $this->tpl->setVariable("TXT_REQUIRED", $lng->txt("required_field")); + $this->tpl->parseCurrentBlock(); + } + + // command buttons + foreach ($this->buttons as $button) { + $this->tpl->setCurrentBlock("cmd"); + $this->tpl->setVariable("CMD", $button["cmd"]); + $this->tpl->setVariable("CMD_TXT", $button["text"]); + + if ($button["id"] != "") { + $this->tpl->setVariable("CMD_ID", " id='" . $button["id"] . "'"); + } + + $this->tpl->parseCurrentBlock(); + } + + // #18808 + if ($this->getMode() != "subform") { + // try to keep uploads even if checking input fails + if ($this->getMultipart()) { + $hash = $_POST["ilfilehash"]; + if (!$hash) { + $hash = md5(uniqid(mt_rand(), true)); + } + $fhash = new ilHiddenInputGUI("ilfilehash"); + $fhash->setValue($hash); + $this->addItem($fhash); + } + } + + // hidden properties + $hidden_fields = false; + foreach ($this->items as $item) { + if ($item->getType() == "hidden") { + $item->insert($this->tpl); + $hidden_fields = true; + } + } + + if ($this->required_text || count($this->buttons) > 0 || $hidden_fields) { + $this->tpl->setCurrentBlock("commands"); + $this->tpl->parseCurrentBlock(); + } + + + if ($this->getMode() == "subform") { + $this->tpl->touchBlock("sub_table"); + } else { + $this->tpl->touchBlock("std_table"); + $this->tpl->setVariable('STD_TABLE_WIDTH', $this->getTableWidth()); + } + + return $this->tpl->get(); + } + + protected function hideRequired($a_type) + { + // #15818 + return in_array($a_type, array("non_editable_value")); + } + + public function insertItem($item, $a_sub_item = false) + { + global $DIC; + $tpl = $DIC["tpl"]; + ; + $lng = $this->lng; + + + $cfg = array(); + + //if(method_exists($item, "getMulti") && $item->getMulti()) + if ($item instanceof ilMultiValuesItem && $item->getMulti()) { + $tpl->addJavascript("./Services/Form/js/ServiceFormMulti.js"); + + $this->tpl->setCurrentBlock("multi_in"); + $this->tpl->setVariable("ID", $item->getFieldId()); + $this->tpl->parseCurrentBlock(); + + $this->tpl->touchBlock("multi_out"); + + + // add hidden item to enable preset multi items + // not used yet, should replace hidden field stuff + $multi_values = $item->getMultiValues(); + if (is_array($multi_values) && sizeof($multi_values) > 1) { + $multi_value = new ilHiddenInputGUI("ilMultiValues~" . $item->getPostVar()); + $multi_value->setValue(implode("~", $multi_values)); + $this->addItem($multi_value); + } + $cfg["multi_values"] = $multi_values; + } + + $item->insert($this->tpl); + + if ($item->getType() == "file" || $item->getType() == "image_file") { + $this->setMultipart(true); + } + + if ($item->getType() != "section_header") { + $cfg["id"] = $item->getFieldId(); + + // info text + if ($item->getInfo() != "") { + $this->tpl->setCurrentBlock("description"); + $this->tpl->setVariable( + "PROPERTY_DESCRIPTION", + $item->getInfo() + ); + $this->tpl->parseCurrentBlock(); + } + + if ($this->getMode() == "subform") { + // required + if (!$this->hideRequired($item->getType())) { + if ($item->getRequired()) { + $this->tpl->touchBlock("sub_required"); + $this->required_text = true; + } + } + + // hidden title (for accessibility, e.g. file upload) + if ($item->getHiddenTitle() != "") { + $this->tpl->setCurrentBlock("sub_hid_title"); + $this->tpl->setVariable( + "SPHID_TITLE", + $item->getHiddenTitle() + ); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setCurrentBlock("sub_prop_start"); + $this->tpl->setVariable("PROPERTY_TITLE", $item->getTitle()); + $this->tpl->setVariable("PROPERTY_CLASS", "il_" . $item->getType()); + if ($item->getType() != "non_editable_value") { + $this->tpl->setVariable("LAB_ID", $item->getFieldId()); + } + $this->tpl->parseCurrentBlock(); + } else { + // required + if (!$this->hideRequired($item->getType())) { + if ($item->getRequired()) { + $this->tpl->touchBlock("required"); + $this->required_text = true; + } + } + + // hidden title (for accessibility, e.g. file upload) + if ($item->getHiddenTitle() != "") { + $this->tpl->setCurrentBlock("std_hid_title"); + $this->tpl->setVariable( + "PHID_TITLE", + $item->getHiddenTitle() + ); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setCurrentBlock("std_prop_start"); + $this->tpl->setVariable("PROPERTY_TITLE", $item->getTitle()); + if ($item->getType() != "non_editable_value") { + $this->tpl->setVariable("LAB_ID", $item->getFieldId()); + } + if ($this->getHideLabels()) { + $this->tpl->setVariable("HIDE_LABELS_STYLE", " ilFormOptionHidden"); + } + $this->tpl->parseCurrentBlock(); + } + + // alert + if ($item->getType() != "non_editable_value" && $item->getAlert() != "") { + $this->tpl->setCurrentBlock("alert"); + $this->tpl->setVariable( + "IMG_ALERT", + ilUtil::getImagePath("icon_alert.svg") + ); + $this->tpl->setVariable( + "ALT_ALERT", + $lng->txt("alert") + ); + $this->tpl->setVariable( + "TXT_ALERT", + $item->getAlert() + ); + $this->tpl->parseCurrentBlock(); + } + + // subitems + $sf = null; + if ($item->getType() != "non_editable_value" or 1) { + $sf = $item->getSubForm(); + if ($item->hideSubForm() && is_object($sf)) { + $this->tpl->setCurrentBlock("sub_form_hide"); + $this->tpl->setVariable("DSFID", $item->getFieldId()); + $this->tpl->parseCurrentBlock(); + } + } + + + $sf_content = ""; + if (is_object($sf)) { + $sf_content = $sf->getContent(); + if ($sf->getMultipart()) { + $this->setMultipart(true); + } + $this->tpl->setCurrentBlock("sub_form"); + $this->tpl->setVariable("PROP_SUB_FORM", $sf_content); + $this->tpl->setVariable("SFID", $item->getFieldId()); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setCurrentBlock("prop"); + /* not used yet + $this->tpl->setVariable("ID", $item->getFieldId()); + $this->tpl->setVariable("CFG", ilJsonUtil::encode($cfg));*/ + $this->tpl->parseCurrentBlock(); + } + + + $this->tpl->touchBlock("item"); + } + + public function getHTML() + { + $html = parent::getHTML(); + + // #13531 - get content that has to reside outside of the parent form tag, e.g. panels/layers + foreach ($this->items as $item) { + // #13536 - ilFormSectionHeaderGUI does NOT extend ilFormPropertyGUI ?! + if (method_exists($item, "getContentOutsideFormTag")) { + $outside = $item->getContentOutsideFormTag(); + if ($outside) { + $html .= $outside; + } + } + } + + return $html; + } + + + // + // UPLOAD HANDLING + // + + /** + * Import upload into temp directory + * + * @param string $a_hash unique form hash + * @param string $a_field form field + * @param string $a_tmp_name temp file name + * @param string $a_name original file name + * @param string $a_type file mime type + * @param mixed $a_index form field index (if array) + * @param mixed $a_sub_index form field subindex (if array) + * @return bool + */ + protected function keepFileUpload($a_hash, $a_field, $a_tmp_name, $a_name, $a_type, $a_index = null, $a_sub_index = null) + { + if (trim($a_tmp_name) == "") { + return; + } + + $a_name = ilUtil::getAsciiFileName($a_name); + + $tmp_file_name = implode("~~", array(session_id(), + $a_hash, + $a_field, + $a_index, + $a_sub_index, + str_replace("/", "~~", $a_type), + str_replace("~~", "_", $a_name))); + + // make sure temp directory exists + $temp_path = ilUtil::getDataDir() . "/temp"; + if (!is_dir($temp_path)) { + ilUtil::createDirectory($temp_path); + } + + ilUtil::moveUploadedFile($a_tmp_name, $tmp_file_name, $temp_path . "/" . $tmp_file_name); + + /** @var ilFileInputGUI $file_input */ + $file_input = $this->getItemByPostVar($a_field); + $file_input->setPending($a_name); + } + + /** + * Get file upload data + * + * @param string $a_field form field + * @param mixed $a_index form field index (if array) + * @param mixed $a_sub_index form field subindex (if array) + * @return array (tmp_name, name, type, error, size, is_upload) + */ + public function getFileUpload($a_field, $a_index = null, $a_sub_index = null) + { + $res = array(); + if ($a_index) { + if ($_FILES[$a_field]["tmp_name"][$a_index][$a_sub_index]) { + $res = array( + "tmp_name" => $_FILES[$a_field]["tmp_name"][$a_index][$a_sub_index], + "name" => $_FILES[$a_field]["name"][$a_index][$a_sub_index], + "type" => $_FILES[$a_field]["type"][$a_index][$a_sub_index], + "error" => $_FILES[$a_field]["error"][$a_index][$a_sub_index], + "size" => $_FILES[$a_field]["size"][$a_index][$a_sub_index], + "is_upload" => true + ); + } + } elseif ($a_sub_index) { + if ($_FILES[$a_field]["tmp_name"][$a_index]) { + $res = array( + "tmp_name" => $_FILES[$a_field]["tmp_name"][$a_index], + "name" => $_FILES[$a_field]["name"][$a_index], + "type" => $_FILES[$a_field]["type"][$a_index], + "error" => $_FILES[$a_field]["error"][$a_index], + "size" => $_FILES[$a_field]["size"][$a_index], + "is_upload" => true + ); + } + } else { + if ($_FILES[$a_field]["tmp_name"]) { + $res = array( + "tmp_name" => $_FILES[$a_field]["tmp_name"], + "name" => $_FILES[$a_field]["name"], + "type" => $_FILES[$a_field]["type"], + "error" => $_FILES[$a_field]["error"], + "size" => $_FILES[$a_field]["size"], + "is_upload" => true + ); + } + } + return $res; + } + + /** + * Was any file uploaded? + * + * @param string $a_field form field + * @param mixed $a_index form field index (if array) + * @param mixed $a_sub_index form field subindex (if array) + * @return bool + */ + public function hasFileUpload($a_field, $a_index = null, $a_sub_index = null) + { + $data = $this->getFileUpload($a_field, $a_index, $a_sub_index); + return (bool) $data["tmp_name"]; + } + + /** + * Move upload to target directory + * + * @param string $a_target_directory target directory (without filename!) + * @param string $a_field form field + * @param string $a_target_name target file name (if different from uploaded file) + * @param mixed $a_index form field index (if array) + * @param mixed $a_sub_index form field subindex (if array) + * @return string target file name incl. path + */ + public function moveFileUpload($a_target_directory, $a_field, $a_target_name = null, $a_index = null, $a_sub_index = null) + { + if (!is_dir($a_target_directory)) { + return; + } + + $data = $this->getFileUpload($a_field, $a_index, $a_sub_index); + if ($data["tmp_name"] && file_exists($data["tmp_name"])) { + if ($a_target_name) { + $data["name"] = $a_target_name; + } + + $target_file = $a_target_directory . "/" . $data["name"]; + $target_file = str_replace("//", "/", $target_file); + + if ($data["is_upload"]) { + if (!ilUtil::moveUploadedFile($data["tmp_name"], $data["name"], $target_file)) { + return; + } + } else { + if (!rename($data["tmp_name"], $target_file)) { + return; + } + } + + return $target_file; + } + } + + /** + * try to rebuild files + */ + protected function rebuildUploadedFiles() + { + if (isset($_POST["ilfilehash"]) && $_POST["ilfilehash"]) { + $temp_path = ilUtil::getDataDir() . "/temp"; + if (is_dir($temp_path)) { + $reload = array(); + + $temp_files = glob($temp_path . "/" . session_id() . "~~" . $_POST["ilfilehash"] . "~~*"); + if (is_array($temp_files)) { + foreach ($temp_files as $full_file) { + $file = explode("~~", basename($full_file)); + $field = $file[2]; + $idx = $file[3]; + $idx2 = $file[4]; + $type = $file[5] . "/" . $file[6]; + $name = $file[7]; + + if ($idx2 != "") { + if (!$_FILES[$field]["tmp_name"][$idx][$idx2]) { + $_FILES[$field]["tmp_name"][$idx][$idx2] = $full_file; + $_FILES[$field]["name"][$idx][$idx2] = $name; + $_FILES[$field]["type"][$idx][$idx2] = $type; + $_FILES[$field]["error"][$idx][$idx2] = 0; + $_FILES[$field]["size"][$idx][$idx2] = filesize($full_file); + } + } elseif ($idx != "") { + if (!$_FILES[$field]["tmp_name"][$idx]) { + $_FILES[$field]["tmp_name"][$idx] = $full_file; + $_FILES[$field]["name"][$idx] = $name; + $_FILES[$field]["type"][$idx] = $type; + $_FILES[$field]["error"][$idx] = 0; + $_FILES[$field]["size"][$idx] = filesize($full_file); + } + } else { + if (!$_FILES[$field]["tmp_name"]) { + $_FILES[$field]["tmp_name"] = $full_file; + $_FILES[$field]["name"] = $name; + $_FILES[$field]["type"] = $type; + $_FILES[$field]["error"] = 0; + $_FILES[$field]["size"] = filesize($full_file); + } + } + } + } + } + } + } } - -?> \ No newline at end of file diff --git a/Services/Form/classes/class.ilRadioGroupInputGUI.php b/Services/Form/classes/class.ilRadioGroupInputGUI.php index 0255034e0f221a110d7e4d7556ae9efe97a975e3..b68b8a6bc7420f373bb8831f8ff1c181533be845 100755 --- a/Services/Form/classes/class.ilRadioGroupInputGUI.php +++ b/Services/Form/classes/class.ilRadioGroupInputGUI.php @@ -1,24 +1,24 @@ +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilRadioGroupInputGUI extends ilSubEnabledFormPropertyGUI implements ilTableFilterItem { - protected $options = array(); - protected $value; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + protected $options = array(); + protected $value; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - parent::__construct($a_title, $a_postvar); - $this->setType("radio"); - } - - /** - * Add Option. - * - * @param object $a_option RadioOption object - */ - function addOption($a_option) - { - $this->options[] = $a_option; - } + $this->lng = $DIC->language(); + parent::__construct($a_title, $a_postvar); + $this->setType("radio"); + } + + /** + * Add Option. + * + * @param object $a_option RadioOption object + */ + public function addOption($a_option) + { + $this->options[] = $a_option; + } - /** - * Get Options. - * - * @return array Array of RadioOption objects - */ - function getOptions() - { - return $this->options; - } + /** + * Get Options. + * + * @return array Array of RadioOption objects + */ + public function getOptions() + { + return $this->options; + } - /** - * Set Value. - * - * @param string $a_value Value - */ - function setValue($a_value) - { - $this->value = $a_value; - } + /** + * Set Value. + * + * @param string $a_value Value + */ + public function setValue($a_value) + { + $this->value = $a_value; + } - /** - * Get Value. - * - * @return string Value - */ - function getValue() - { - return $this->value; - } - - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $this->setValue($a_values[$this->getPostVar()]); - foreach($this->getOptions() as $option) - { - foreach($option->getSubItems() as $item) - { - $item->setValueByArray($a_values); - } - } - } + /** + * Get Value. + * + * @return string Value + */ + public function getValue() + { + return $this->value; + } + + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $this->setValue($a_values[$this->getPostVar()]); + foreach ($this->getOptions() as $option) { + foreach ($option->getSubItems() as $item) { + $item->setValueByArray($a_values); + } + } + } - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - $_POST[$this->getPostVar()] = - ilUtil::stripSlashes($_POST[$this->getPostVar()]); - if ($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") - { - $this->setAlert($lng->txt("msg_input_is_required")); + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + $_POST[$this->getPostVar()] = + ilUtil::stripSlashes($_POST[$this->getPostVar()]); + if ($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") { + $this->setAlert($lng->txt("msg_input_is_required")); - return false; - } - - $ok = true; - foreach($this->getOptions() as $option) - { - foreach($option->getSubItems() as $item) - { - if ($_POST[$this->getPostVar()] == $option->getValue()) - { - if (!$item->checkInput()) { - $ok = false; - } - } - } - } - return $ok; - } + return false; + } + + $ok = true; + foreach ($this->getOptions() as $option) { + foreach ($option->getSubItems() as $item) { + if ($_POST[$this->getPostVar()] == $option->getValue()) { + if (!$item->checkInput()) { + $ok = false; + } + } + } + } + return $ok; + } - /** - * Insert property html - * - * @return int Size - */ - function insert($a_tpl) - { - $html = $this->render(); + /** + * Insert property html + * + * @return int Size + */ + public function insert($a_tpl) + { + $html = $this->render(); - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $html); - $a_tpl->parseCurrentBlock(); - } + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $html); + $a_tpl->parseCurrentBlock(); + } - /** - * Insert property html - */ - function render() - { - $tpl = new ilTemplate("tpl.prop_radio.html", true, true, "Services/Form"); - - foreach($this->getOptions() as $option) - { - // information text for option - if ($option->getInfo() != "") - { - $tpl->setCurrentBlock("radio_option_desc"); - $tpl->setVariable("RADIO_OPTION_DESC", $option->getInfo()); - $tpl->parseCurrentBlock(); - } - - - if (count($option->getSubItems()) > 0) - { - if ($option->getValue() != $this->getValue()) - { - // #10930 - $tpl->setCurrentBlock("prop_radio_opt_hide"); - $tpl->setVariable("HOP_ID", $this->getFieldId()."_".$option->getValue()); - $tpl->parseCurrentBlock(); - } - $tpl->setCurrentBlock("radio_option_subform"); - $pf = new ilPropertyFormGUI(); - $pf->setMode("subform"); - $pf->setItems($option->getSubItems()); - $tpl->setVariable("SUB_FORM", $pf->getContent()); - $tpl->setVariable("SOP_ID", $this->getFieldId()."_".$option->getValue()); - if ($pf->getMultipart()) - { - $this->getParentForm()->setMultipart(true); - } - $tpl->parseCurrentBlock(); - if ($pf->getMultipart()) - { - $this->getParentForm()->setMultipart(true); - } - } + /** + * Insert property html + */ + public function render() + { + $tpl = new ilTemplate("tpl.prop_radio.html", true, true, "Services/Form"); + + foreach ($this->getOptions() as $option) { + // information text for option + if ($option->getInfo() != "") { + $tpl->setCurrentBlock("radio_option_desc"); + $tpl->setVariable("RADIO_OPTION_DESC", $option->getInfo()); + $tpl->parseCurrentBlock(); + } + + + if (count($option->getSubItems()) > 0) { + if ($option->getValue() != $this->getValue()) { + // #10930 + $tpl->setCurrentBlock("prop_radio_opt_hide"); + $tpl->setVariable("HOP_ID", $this->getFieldId() . "_" . $option->getValue()); + $tpl->parseCurrentBlock(); + } + $tpl->setCurrentBlock("radio_option_subform"); + $pf = new ilPropertyFormGUI(); + $pf->setMode("subform"); + $pf->setItems($option->getSubItems()); + $tpl->setVariable("SUB_FORM", $pf->getContent()); + $tpl->setVariable("SOP_ID", $this->getFieldId() . "_" . $option->getValue()); + if ($pf->getMultipart()) { + $this->getParentForm()->setMultipart(true); + } + $tpl->parseCurrentBlock(); + if ($pf->getMultipart()) { + $this->getParentForm()->setMultipart(true); + } + } - $tpl->setCurrentBlock("prop_radio_option"); - if (!$this->getDisabled()) - { - $tpl->setVariable("POST_VAR", $this->getPostVar()); - } - $tpl->setVariable("VAL_RADIO_OPTION", $option->getValue()); - $tpl->setVariable("OP_ID", $this->getFieldId()."_".$option->getValue()); - $tpl->setVariable("FID", $this->getFieldId()); - if($this->getDisabled() or $option->getDisabled()) - { - $tpl->setVariable('DISABLED','disabled="disabled" '); - } - if ($option->getValue() == $this->getValue()) - { - $tpl->setVariable("CHK_RADIO_OPTION", - 'checked="checked"'); - } - $tpl->setVariable("TXT_RADIO_OPTION", $option->getTitle()); - - - $tpl->parseCurrentBlock(); - } - $tpl->setVariable("ID", $this->getFieldId()); - - if ($this->getDisabled()) - { - $tpl->setVariable("HIDDEN_INPUT", - $this->getHiddenTag($this->getPostVar(), $this->getValue())); - } + $tpl->setCurrentBlock("prop_radio_option"); + if (!$this->getDisabled()) { + $tpl->setVariable("POST_VAR", $this->getPostVar()); + } + $tpl->setVariable("VAL_RADIO_OPTION", $option->getValue()); + $tpl->setVariable("OP_ID", $this->getFieldId() . "_" . $option->getValue()); + $tpl->setVariable("FID", $this->getFieldId()); + if ($this->getDisabled() or $option->getDisabled()) { + $tpl->setVariable('DISABLED', 'disabled="disabled" '); + } + if ($option->getValue() == $this->getValue()) { + $tpl->setVariable( + "CHK_RADIO_OPTION", + 'checked="checked"' + ); + } + $tpl->setVariable("TXT_RADIO_OPTION", $option->getTitle()); + + + $tpl->parseCurrentBlock(); + } + $tpl->setVariable("ID", $this->getFieldId()); + + if ($this->getDisabled()) { + $tpl->setVariable( + "HIDDEN_INPUT", + $this->getHiddenTag($this->getPostVar(), $this->getValue()) + ); + } - return $tpl->get(); - } + return $tpl->get(); + } - /** - * Get item by post var - * - * @return mixed false or item object - */ - function getItemByPostVar($a_post_var) - { - if ($this->getPostVar() == $a_post_var) - { - return $this; - } + /** + * Get item by post var + * + * @return mixed false or item object + */ + public function getItemByPostVar($a_post_var) + { + if ($this->getPostVar() == $a_post_var) { + return $this; + } - foreach($this->getOptions() as $option) - { - foreach($option->getSubItems() as $item) - { - if ($item->getType() != "section_header") - { - $ret = $item->getItemByPostVar($a_post_var); - if (is_object($ret)) - { - return $ret; - } - } - } - } - - return false; - } + foreach ($this->getOptions() as $option) { + foreach ($option->getSubItems() as $item) { + if ($item->getType() != "section_header") { + $ret = $item->getItemByPostVar($a_post_var); + if (is_object($ret)) { + return $ret; + } + } + } + } + + return false; + } - function getTableFilterHTML() - { - return $this->render(); - } + public function getTableFilterHTML() + { + return $this->render(); + } - /** - * returns a flat array of possibly existing subitems recursively - * - * @return array - */ - public function getSubInputItemsRecursive() - { - $subInputItems = parent::getSubInputItemsRecursive(); - foreach($this->getOptions() as $option) - { - /** - * @var $option ilRadioOption - */ - $subInputItems = array_merge( $subInputItems, $option->getSubInputItemsRecursive() ); - } + /** + * returns a flat array of possibly existing subitems recursively + * + * @return array + */ + public function getSubInputItemsRecursive() + { + $subInputItems = parent::getSubInputItemsRecursive(); + foreach ($this->getOptions() as $option) { + /** + * @var $option ilRadioOption + */ + $subInputItems = array_merge($subInputItems, $option->getSubInputItemsRecursive()); + } - return $subInputItems; - } + return $subInputItems; + } } diff --git a/Services/Form/classes/class.ilRadioOption.php b/Services/Form/classes/class.ilRadioOption.php index 175d721ae66f7dbaa3545cc503e3bb6bf5e65612..8b2c53cf5e7eb98ac89b02467157a6bdbf567816 100755 --- a/Services/Form/classes/class.ilRadioOption.php +++ b/Services/Form/classes/class.ilRadioOption.php @@ -1,157 +1,154 @@ +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilRadioOption { - protected $title; - protected $value; - protected $info; - protected $sub_items = array(); - protected $disabled; - - function __construct($a_title = "", $a_value = "", $a_info = "") - { - $this->setTitle($a_title); - $this->setValue($a_value); - $this->setInfo($a_info); - } - - /** - * Set Title. - * - * @param string $a_title Title - */ - function setTitle($a_title) - { - $this->title = $a_title; - } + protected $title; + protected $value; + protected $info; + protected $sub_items = array(); + protected $disabled; + + public function __construct($a_title = "", $a_value = "", $a_info = "") + { + $this->setTitle($a_title); + $this->setValue($a_value); + $this->setInfo($a_info); + } + + /** + * Set Title. + * + * @param string $a_title Title + */ + public function setTitle($a_title) + { + $this->title = $a_title; + } - /** - * Get Title. - * - * @return string Title - */ - function getTitle() - { - return $this->title; - } + /** + * Get Title. + * + * @return string Title + */ + public function getTitle() + { + return $this->title; + } - /** - * Set Info. - * - * @param string $a_info Info - */ - function setInfo($a_info) - { - $this->info = $a_info; - } + /** + * Set Info. + * + * @param string $a_info Info + */ + public function setInfo($a_info) + { + $this->info = $a_info; + } - /** - * Get Info. - * - * @return string Info - */ - function getInfo() - { - return $this->info; - } + /** + * Get Info. + * + * @return string Info + */ + public function getInfo() + { + return $this->info; + } - /** - * Set Value. - * - * @param string $a_value Value - */ - function setValue($a_value) - { - $this->value = $a_value; - } + /** + * Set Value. + * + * @param string $a_value Value + */ + public function setValue($a_value) + { + $this->value = $a_value; + } - /** - * Get Value. - * - * @return string Value - */ - function getValue() - { - return $this->value; - } - - public function setDisabled($a_disabled) - { - $this->disabled = $a_disabled; - } - - public function getDisabled() - { - return $this->disabled; - } + /** + * Get Value. + * + * @return string Value + */ + public function getValue() + { + return $this->value; + } + + public function setDisabled($a_disabled) + { + $this->disabled = $a_disabled; + } + + public function getDisabled() + { + return $this->disabled; + } - /** - * Add Subitem - * - * @param object $a_item Item - */ - function addSubItem($a_item) - { - $this->sub_items[] = $a_item; - } + /** + * Add Subitem + * + * @param object $a_item Item + */ + public function addSubItem($a_item) + { + $this->sub_items[] = $a_item; + } - /** - * Get Subitems - * - * @return array Array of items - */ - function getSubItems() - { - return $this->sub_items; - } + /** + * Get Subitems + * + * @return array Array of items + */ + public function getSubItems() + { + return $this->sub_items; + } - public function getSubInputItemsRecursive() - { - $subInputItems = array(); + public function getSubInputItemsRecursive() + { + $subInputItems = array(); - foreach( $this->sub_items as $subItem ) - { - if( $subItem->getType() == 'section_header' ) - { - continue; - } + foreach ($this->sub_items as $subItem) { + if ($subItem->getType() == 'section_header') { + continue; + } - $subInputItems[] = $subItem; + $subInputItems[] = $subItem; - if( $subItem instanceof ilSubEnabledFormPropertyGUI ) - { - $subInputItems = array_merge( $subInputItems, $subItem->getSubInputItemsRecursive() ); - } - } + if ($subItem instanceof ilSubEnabledFormPropertyGUI) { + $subInputItems = array_merge($subInputItems, $subItem->getSubInputItemsRecursive()); + } + } - return $subInputItems; - } + return $subInputItems; + } } diff --git a/Services/Form/classes/class.ilRegExpInputGUI.php b/Services/Form/classes/class.ilRegExpInputGUI.php index aca1eea5598d13791a377efc7d7b40546e1a99cd..d15592f3fbce688700c00addbdf344d8a2b3e497 100644 --- a/Services/Form/classes/class.ilRegExpInputGUI.php +++ b/Services/Form/classes/class.ilRegExpInputGUI.php @@ -1,132 +1,124 @@ +* @author Roland Küstermann * @version $Id$ * @ingroup ServicesForm */ class ilRegExpInputGUI extends ilTextInputGUI { - private $pattern; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + private $pattern; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - parent::__construct($a_title, $a_postvar); - $this->setType("feedurl"); - } + $this->lng = $DIC->language(); + parent::__construct($a_title, $a_postvar); + $this->setType("feedurl"); + } - /** - * Set Message, if input does not match. - * - * @param string $a_nomatchmessage Message, if input does not match - */ - function setNoMatchMessage($a_nomatchmessage) - { - $this->nomatchmessage = $a_nomatchmessage; - } + /** + * Set Message, if input does not match. + * + * @param string $a_nomatchmessage Message, if input does not match + */ + public function setNoMatchMessage($a_nomatchmessage) + { + $this->nomatchmessage = $a_nomatchmessage; + } - /** - * Get Message, if input does not match. - * - * @return string Message, if input does not match - */ - function getNoMatchMessage() - { - return $this->nomatchmessage; - } + /** + * Get Message, if input does not match. + * + * @return string Message, if input does not match + */ + public function getNoMatchMessage() + { + return $this->nomatchmessage; + } - /** - * set pattern - * - * @param string regular expression pattern - */ - function setPattern ($pattern) - { - $this->pattern = $pattern; - } - - /** - * return pattern - * - * @return string - */ - function getPattern () - { - return $this->pattern; - } + /** + * set pattern + * + * @param string regular expression pattern + */ + public function setPattern($pattern) + { + $this->pattern = $pattern; + } + + /** + * return pattern + * + * @return string + */ + public function getPattern() + { + return $this->pattern; + } - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - // this line is necessary, otherwise it is a security issue (Alex) - $_POST[$this->getPostVar()] = ilUtil::stripSlashes($_POST[$this->getPostVar()]); - - $value = $_POST[$this->getPostVar()]; - - if (!$this->getRequired() && strcasecmp($value, "") == 0) - { - return true; - } - - if ($this->getRequired() && trim($value) == "") - { - $this->setAlert($lng->txt("msg_input_is_required")); + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + // this line is necessary, otherwise it is a security issue (Alex) + $_POST[$this->getPostVar()] = ilUtil::stripSlashes($_POST[$this->getPostVar()]); + + $value = $_POST[$this->getPostVar()]; + + if (!$this->getRequired() && strcasecmp($value, "") == 0) { + return true; + } + + if ($this->getRequired() && trim($value) == "") { + $this->setAlert($lng->txt("msg_input_is_required")); - return false; - } - - $result = preg_match ($this->pattern, $value); - if (!$result) - { - if ($this->getNoMatchMessage() == "") - { - $this->setAlert($lng->txt("msg_input_does_not_match_regexp")); - } - else - { - $this->setAlert($this->getNoMatchMessage()); - } - } - return $result; - - } + return false; + } + $result = preg_match($this->pattern, $value); + if (!$result) { + if ($this->getNoMatchMessage() == "") { + $this->setAlert($lng->txt("msg_input_does_not_match_regexp")); + } else { + $this->setAlert($this->getNoMatchMessage()); + } + } + return $result; + } } diff --git a/Services/Form/classes/class.ilRepositorySelector2InputGUI.php b/Services/Form/classes/class.ilRepositorySelector2InputGUI.php index 0a30c10436dd4f7da22831c5de8b14cfeb108322..9d6176763a90c6e12f315939be10e4feff495b7d 100755 --- a/Services/Form/classes/class.ilRepositorySelector2InputGUI.php +++ b/Services/Form/classes/class.ilRepositorySelector2InputGUI.php @@ -15,117 +15,119 @@ include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php"); */ class ilRepositorySelector2InputGUI extends ilExplorerSelectInputGUI { - /** - * @var callable - */ - protected $title_modifier = null; + /** + * @var callable + */ + protected $title_modifier = null; - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - * @param string $form - */ - function __construct($a_title, $a_postvar, $a_multi = false, $form = ilPropertyFormGUI::class) - { - global $DIC; + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + * @param string $form + */ + public function __construct($a_title, $a_postvar, $a_multi = false, $form = ilPropertyFormGUI::class) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $ilCtrl = $DIC->ctrl(); - $this->multi_nodes = $a_multi; - $this->postvar = $a_postvar; + $this->ctrl = $DIC->ctrl(); + $ilCtrl = $DIC->ctrl(); + $this->multi_nodes = $a_multi; + $this->postvar = $a_postvar; - include_once("./Services/Repository/classes/class.ilRepositorySelectorExplorerGUI.php"); - $this->explorer_gui = new ilRepositorySelectorExplorerGUI([$form, ilFormPropertyDispatchGUI::class, ilRepositorySelector2InputGUI::class], - $this->getExplHandleCmd(), $this, "selectRepositoryItem", "root_id", "rep_exp_sel_".$a_postvar); -// $this->explorer_gui->setTypeWhiteList($this->getVisibleTypes()); -// $this->explorer_gui->setClickableTypes($this->getClickableTypes()); - $this->explorer_gui->setSelectMode($a_postvar."_sel", $this->multi_nodes); - //$this->explorer_gui = new ilTaxonomyExplorerGUI(array("ilformpropertydispatchgui", "iltaxselectinputgui"), $this->getExplHandleCmd(), $a_taxonomy_id, "", "", - // "tax_expl_".$a_postvar); + include_once("./Services/Repository/classes/class.ilRepositorySelectorExplorerGUI.php"); + $this->explorer_gui = new ilRepositorySelectorExplorerGUI( + [$form, ilFormPropertyDispatchGUI::class, ilRepositorySelector2InputGUI::class], + $this->getExplHandleCmd(), + $this, + "selectRepositoryItem", + "root_id", + "rep_exp_sel_" . $a_postvar + ); + // $this->explorer_gui->setTypeWhiteList($this->getVisibleTypes()); + // $this->explorer_gui->setClickableTypes($this->getClickableTypes()); + $this->explorer_gui->setSelectMode($a_postvar . "_sel", $this->multi_nodes); + //$this->explorer_gui = new ilTaxonomyExplorerGUI(array("ilformpropertydispatchgui", "iltaxselectinputgui"), $this->getExplHandleCmd(), $a_taxonomy_id, "", "", + // "tax_expl_".$a_postvar); - parent::__construct($a_title, $a_postvar, $this->explorer_gui, $this->multi_nodes); - $this->setType("rep_select"); - } + parent::__construct($a_title, $a_postvar, $this->explorer_gui, $this->multi_nodes); + $this->setType("rep_select"); + } - /** - * Set title modifier - * - * @param callable $a_val - */ - function setTitleModifier(callable $a_val) - { - $this->title_modifier = $a_val; - if ($a_val != null) - { - $this->explorer_gui->setNodeContentModifier(function ($a_node) use ($a_val) { - return $a_val($a_node["child"]); - }); - } - else - { - $this->explorer_gui->setNodeContentModifier(null); - } - } + /** + * Set title modifier + * + * @param callable $a_val + */ + public function setTitleModifier(callable $a_val) + { + $this->title_modifier = $a_val; + if ($a_val != null) { + $this->explorer_gui->setNodeContentModifier(function ($a_node) use ($a_val) { + return $a_val($a_node["child"]); + }); + } else { + $this->explorer_gui->setNodeContentModifier(null); + } + } - /** - * Get title modifier - * - * @return callable - */ - function getTitleModifier() - { - return $this->title_modifier; - } + /** + * Get title modifier + * + * @return callable + */ + public function getTitleModifier() + { + return $this->title_modifier; + } - /** - * Get title for node id (needs to be overwritten, if explorer is not a tree eplorer - * - * @param - * @return - */ - function getTitleForNodeId($a_id) - { - $c = $this->getTitleModifier(); - if (is_callable($c)) - { - return $c($a_id); - } - return ilObject::_lookupTitle(ilObject::_lookupObjId($a_id)); - } + /** + * Get title for node id (needs to be overwritten, if explorer is not a tree eplorer + * + * @param + * @return + */ + public function getTitleForNodeId($a_id) + { + $c = $this->getTitleModifier(); + if (is_callable($c)) { + return $c($a_id); + } + return ilObject::_lookupTitle(ilObject::_lookupObjId($a_id)); + } - /** - * @return ilRepositorySelectorExplorerGUI - */ - function getExplorerGUI() - { - return $this->explorer_gui; - } + /** + * @return ilRepositorySelectorExplorerGUI + */ + public function getExplorerGUI() + { + return $this->explorer_gui; + } - /** - * Get HTML - * - * @param - * @return - */ - function getHTML() - { - $ilCtrl = $this->ctrl; - $ilCtrl->setParameterByClass("ilformpropertydispatchgui", "postvar", $this->postvar); - $html = parent::getHTML(); - $ilCtrl->setParameterByClass("ilformpropertydispatchgui", "postvar", $_REQUEST["postvar"]); - return $html; - } + /** + * Get HTML + * + * @param + * @return + */ + public function getHTML() + { + $ilCtrl = $this->ctrl; + $ilCtrl->setParameterByClass("ilformpropertydispatchgui", "postvar", $this->postvar); + $html = parent::getHTML(); + $ilCtrl->setParameterByClass("ilformpropertydispatchgui", "postvar", $_REQUEST["postvar"]); + return $html; + } - /** - * Render item - */ - function render($a_mode = "property_form") - { - $ilCtrl = $this->ctrl; - $ilCtrl->setParameterByClass("ilformpropertydispatchgui", "postvar", $this->postvar); - return parent::render($a_mode); - $ilCtrl->setParameterByClass("ilformpropertydispatchgui", "postvar", $_REQUEST["postvar"]); - } + /** + * Render item + */ + public function render($a_mode = "property_form") + { + $ilCtrl = $this->ctrl; + $ilCtrl->setParameterByClass("ilformpropertydispatchgui", "postvar", $this->postvar); + return parent::render($a_mode); + $ilCtrl->setParameterByClass("ilformpropertydispatchgui", "postvar", $_REQUEST["postvar"]); + } } diff --git a/Services/Form/classes/class.ilRepositorySelectorInputGUI.php b/Services/Form/classes/class.ilRepositorySelectorInputGUI.php index 99cc0412f719a3ce90e356eb94f6e21c29dab237..f6ccfb16ea0415edc113efe9f14ea7ff754e28e0 100755 --- a/Services/Form/classes/class.ilRepositorySelectorInputGUI.php +++ b/Services/Form/classes/class.ilRepositorySelectorInputGUI.php @@ -1,24 +1,24 @@ +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm * @ilCtrl_IsCalledBy ilRepositorySelectorInputGUI: ilFormPropertyDispatchGUI */ class ilRepositorySelectorInputGUI extends ilFormPropertyGUI implements ilTableFilterItem { - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilTree - */ - protected $tree; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilObjectDataCache - */ - protected $obj_data_cache; - - protected $options; - protected $value; - protected $container_types = array("root", "cat", "grp", "fold", "crs"); - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; - - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - $this->ctrl = $DIC->ctrl(); - $this->tree = $DIC->repositoryTree(); - $this->user = $DIC->user(); - $this->obj_data_cache = $DIC["ilObjDataCache"]; - $lng = $DIC->language(); - - parent::__construct($a_title, $a_postvar); - $this->setClickableTypes($this->container_types); - $this->setHeaderMessage($lng->txt('search_area_info')); - $this->setType("rep_select"); - $this->setSelectText($lng->txt("select")); - } - - /** - * Set Value. - * - * @param int ref id of selected repository item - */ - function setValue($a_value) - { - $this->value = $a_value; - } - - /** - * Get Value. - * - * @return int ref id of selected repository item - */ - function getValue() - { - return $this->value; - } - - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $this->setValue($a_values[$this->getPostVar()]); - } - - /** - * Set select link text - * - * @param string select link text - */ - function setSelectText($a_val) - { - $this->select_text = $a_val; - } - - /** - * Get select link text - * - * @return string select link text - */ - function getSelectText() - { - return $this->select_text; - } - - /** - * Set header message - * - * @param string header message - */ - function setHeaderMessage($a_val) - { - $this->hm = $a_val; - } - - /** - * Get header message - * - * @return string header message - */ - function getHeaderMessage() - { - return $this->hm; - } - - /** - * Set clickable types - * - * @param array clickable types - */ - function setClickableTypes($a_types) - { - $this->clickable_types = $a_types; - } - - /** - * Get clickable types - * - * @return array clickable types - */ - function getClickableTypes() - { - return $this->clickable_types; - } - - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - $_POST[$this->getPostVar()] = - ilUtil::stripSlashes($_POST[$this->getPostVar()]); - - if ($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") - { - $this->setAlert($lng->txt("msg_input_is_required")); - - return false; - } - return true; - } - - /** - * Select Repository Item - */ - function showRepositorySelection() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $tree = $this->tree; - $ilUser = $this->user; - - include_once 'Services/Repository/classes/class.ilRepositorySelectorExplorerGUI.php'; - $ilCtrl->setParameter($this, "postvar", $this->getPostVar()); - - ilUtil::sendInfo($this->getHeaderMessage()); - - $exp = new ilRepositorySelectorExplorerGUI($this, "showRepositorySelection", - $this, "selectRepositoryItem", "root_id"); - $exp->setTypeWhiteList($this->getVisibleTypes()); - $exp->setClickableTypes($this->getClickableTypes()); - - if($this->getValue()) - { - $exp->setPathOpen($this->getValue()); - $exp->setHighlightedNode($this->getHighlightedNode()); - } - - if ($exp->handleCommand()) - { - return; - } - // build html-output - $tpl->setContent($exp->getHTML()); - } - - /** - * Select repository item - */ - function selectRepositoryItem() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - $anchor = $ilUser->prefs["screen_reader_optimization"] - ? $this->getFieldId()."_anchor" - : ""; - - $this->setValue($_GET["root_id"]); - $this->writeToSession(); - - $ilCtrl->returnToParent($this, $anchor); - } - - /** - * Reset - */ - function reset() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - $anchor = $ilUser->prefs["screen_reader_optimization"] - ? $this->getFieldId()."_anchor" - : ""; - - $this->setValue(""); - $this->writeToSession(); - - $ilCtrl->returnToParent($this, $anchor); - } - - /** - * Render item - */ - function render($a_mode = "property_form") - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilObjDataCache = $this->obj_data_cache; - $tree = $this->tree; - - $tpl = new ilTemplate("tpl.prop_rep_select.html", true, true, "Services/Form"); - - $tpl->setVariable("POST_VAR", $this->getPostVar()); - $tpl->setVariable("ID", $this->getFieldId()); - $tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($this->getValue())); - $tpl->setVariable("TXT_SELECT", $this->getSelectText()); - $tpl->setVariable("TXT_RESET", $lng->txt("reset")); - switch ($a_mode) - { - case "property_form": - $parent_gui = "ilpropertyformgui"; - break; - - case "table_filter": - $parent_gui = get_class($this->getParent()); - break; - } - - $ilCtrl->setParameterByClass("ilrepositoryselectorinputgui", - "postvar", $this->getPostVar()); - $tpl->setVariable("HREF_SELECT", - $ilCtrl->getLinkTargetByClass(array($parent_gui, "ilformpropertydispatchgui", "ilrepositoryselectorinputgui"), - "showRepositorySelection")); - $tpl->setVariable("HREF_RESET", - $ilCtrl->getLinkTargetByClass(array($parent_gui, "ilformpropertydispatchgui", "ilrepositoryselectorinputgui"), - "reset")); - - if ($this->getValue() > 0 && $this->getValue() != ROOT_FOLDER_ID) - { - $tpl->setVariable("TXT_ITEM", - $ilObjDataCache->lookupTitle($ilObjDataCache->lookupObjId($this->getValue()))); - } - else - { - $nd = $tree->getNodeData(ROOT_FOLDER_ID); - $title = $nd["title"]; - if ($title == "ILIAS") - { - $title = $lng->txt("repository"); - } - if (in_array($nd["type"], $this->getClickableTypes())) - { - $tpl->setVariable("TXT_ITEM", $title); - } - } - return $tpl->get(); - } - - /** - * Insert property html - * - * @return int Size - */ - function insert($a_tpl) - { - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $this->render()); - $a_tpl->parseCurrentBlock(); - } - - /** - * Get HTML for table filter - */ - function getTableFilterHTML() - { - $html = $this->render("table_filter"); - return $html; - } - - /** - * Returns the highlighted object - * - * @return int ref_id (node) - */ - protected function getHighlightedNode() - { - $tree = $this->tree; - - if(!in_array(ilObject::_lookupType($this->getValue(),true), $this->getVisibleTypes())) - { - return $tree->getParentId($this->getValue()); - } - - return $this->getValue(); - } - - /** - * returns all visible types like container and clickable types - * - * @return array - */ - protected function getVisibleTypes() - { - return array_merge((array)$this->container_types, (array)$this->getClickableTypes()); - } - + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilTree + */ + protected $tree; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilObjectDataCache + */ + protected $obj_data_cache; + + protected $options; + protected $value; + protected $container_types = array("root", "cat", "grp", "fold", "crs"); + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; + + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + $this->ctrl = $DIC->ctrl(); + $this->tree = $DIC->repositoryTree(); + $this->user = $DIC->user(); + $this->obj_data_cache = $DIC["ilObjDataCache"]; + $lng = $DIC->language(); + + parent::__construct($a_title, $a_postvar); + $this->setClickableTypes($this->container_types); + $this->setHeaderMessage($lng->txt('search_area_info')); + $this->setType("rep_select"); + $this->setSelectText($lng->txt("select")); + } + + /** + * Set Value. + * + * @param int ref id of selected repository item + */ + public function setValue($a_value) + { + $this->value = $a_value; + } + + /** + * Get Value. + * + * @return int ref id of selected repository item + */ + public function getValue() + { + return $this->value; + } + + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $this->setValue($a_values[$this->getPostVar()]); + } + + /** + * Set select link text + * + * @param string select link text + */ + public function setSelectText($a_val) + { + $this->select_text = $a_val; + } + + /** + * Get select link text + * + * @return string select link text + */ + public function getSelectText() + { + return $this->select_text; + } + + /** + * Set header message + * + * @param string header message + */ + public function setHeaderMessage($a_val) + { + $this->hm = $a_val; + } + + /** + * Get header message + * + * @return string header message + */ + public function getHeaderMessage() + { + return $this->hm; + } + + /** + * Set clickable types + * + * @param array clickable types + */ + public function setClickableTypes($a_types) + { + $this->clickable_types = $a_types; + } + + /** + * Get clickable types + * + * @return array clickable types + */ + public function getClickableTypes() + { + return $this->clickable_types; + } + + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + $_POST[$this->getPostVar()] = + ilUtil::stripSlashes($_POST[$this->getPostVar()]); + + if ($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") { + $this->setAlert($lng->txt("msg_input_is_required")); + + return false; + } + return true; + } + + /** + * Select Repository Item + */ + public function showRepositorySelection() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $tree = $this->tree; + $ilUser = $this->user; + + include_once 'Services/Repository/classes/class.ilRepositorySelectorExplorerGUI.php'; + $ilCtrl->setParameter($this, "postvar", $this->getPostVar()); + + ilUtil::sendInfo($this->getHeaderMessage()); + + $exp = new ilRepositorySelectorExplorerGUI( + $this, + "showRepositorySelection", + $this, + "selectRepositoryItem", + "root_id" + ); + $exp->setTypeWhiteList($this->getVisibleTypes()); + $exp->setClickableTypes($this->getClickableTypes()); + + if ($this->getValue()) { + $exp->setPathOpen($this->getValue()); + $exp->setHighlightedNode($this->getHighlightedNode()); + } + + if ($exp->handleCommand()) { + return; + } + // build html-output + $tpl->setContent($exp->getHTML()); + } + + /** + * Select repository item + */ + public function selectRepositoryItem() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + $anchor = $ilUser->prefs["screen_reader_optimization"] + ? $this->getFieldId() . "_anchor" + : ""; + + $this->setValue($_GET["root_id"]); + $this->writeToSession(); + + $ilCtrl->returnToParent($this, $anchor); + } + + /** + * Reset + */ + public function reset() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + $anchor = $ilUser->prefs["screen_reader_optimization"] + ? $this->getFieldId() . "_anchor" + : ""; + + $this->setValue(""); + $this->writeToSession(); + + $ilCtrl->returnToParent($this, $anchor); + } + + /** + * Render item + */ + public function render($a_mode = "property_form") + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilObjDataCache = $this->obj_data_cache; + $tree = $this->tree; + + $tpl = new ilTemplate("tpl.prop_rep_select.html", true, true, "Services/Form"); + + $tpl->setVariable("POST_VAR", $this->getPostVar()); + $tpl->setVariable("ID", $this->getFieldId()); + $tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($this->getValue())); + $tpl->setVariable("TXT_SELECT", $this->getSelectText()); + $tpl->setVariable("TXT_RESET", $lng->txt("reset")); + switch ($a_mode) { + case "property_form": + $parent_gui = "ilpropertyformgui"; + break; + + case "table_filter": + $parent_gui = get_class($this->getParent()); + break; + } + + $ilCtrl->setParameterByClass( + "ilrepositoryselectorinputgui", + "postvar", + $this->getPostVar() + ); + $tpl->setVariable( + "HREF_SELECT", + $ilCtrl->getLinkTargetByClass( + array($parent_gui, "ilformpropertydispatchgui", "ilrepositoryselectorinputgui"), + "showRepositorySelection" + ) + ); + $tpl->setVariable( + "HREF_RESET", + $ilCtrl->getLinkTargetByClass( + array($parent_gui, "ilformpropertydispatchgui", "ilrepositoryselectorinputgui"), + "reset" + ) + ); + + if ($this->getValue() > 0 && $this->getValue() != ROOT_FOLDER_ID) { + $tpl->setVariable( + "TXT_ITEM", + $ilObjDataCache->lookupTitle($ilObjDataCache->lookupObjId($this->getValue())) + ); + } else { + $nd = $tree->getNodeData(ROOT_FOLDER_ID); + $title = $nd["title"]; + if ($title == "ILIAS") { + $title = $lng->txt("repository"); + } + if (in_array($nd["type"], $this->getClickableTypes())) { + $tpl->setVariable("TXT_ITEM", $title); + } + } + return $tpl->get(); + } + + /** + * Insert property html + * + * @return int Size + */ + public function insert($a_tpl) + { + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $this->render()); + $a_tpl->parseCurrentBlock(); + } + + /** + * Get HTML for table filter + */ + public function getTableFilterHTML() + { + $html = $this->render("table_filter"); + return $html; + } + + /** + * Returns the highlighted object + * + * @return int ref_id (node) + */ + protected function getHighlightedNode() + { + $tree = $this->tree; + + if (!in_array(ilObject::_lookupType($this->getValue(), true), $this->getVisibleTypes())) { + return $tree->getParentId($this->getValue()); + } + + return $this->getValue(); + } + + /** + * returns all visible types like container and clickable types + * + * @return array + */ + protected function getVisibleTypes() + { + return array_merge((array) $this->container_types, (array) $this->getClickableTypes()); + } } diff --git a/Services/Form/classes/class.ilRoleAutoCompleteInputGUI.php b/Services/Form/classes/class.ilRoleAutoCompleteInputGUI.php index 4364b128aecd8f10e973eb649d0f149e3b6beb39..e08621b4e2b4325a96088e86bd66df857b3bf578 100644 --- a/Services/Form/classes/class.ilRoleAutoCompleteInputGUI.php +++ b/Services/Form/classes/class.ilRoleAutoCompleteInputGUI.php @@ -12,41 +12,40 @@ include_once("./Services/Form/classes/class.ilTextInputGUI.php"); */ class ilRoleAutoCompleteInputGUI extends ilTextInputGUI { - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title, $a_postvar, $a_class, $a_autocomplete_cmd) - { - global $DIC; + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title, $a_postvar, $a_class, $a_autocomplete_cmd) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $ilCtrl = $DIC->ctrl(); - - if (is_object($a_class)) - { - $a_class = get_class($a_class); - } - $a_class = strtolower($a_class); - - parent::__construct($a_title, $a_postvar); - $this->setInputType("raci"); - $this->setMaxLength(70); - $this->setSize(30); - $this->setDataSource($ilCtrl->getLinkTargetByClass($a_class, $a_autocomplete_cmd, "", true)); - } + $this->ctrl = $DIC->ctrl(); + $ilCtrl = $DIC->ctrl(); + + if (is_object($a_class)) { + $a_class = get_class($a_class); + } + $a_class = strtolower($a_class); + + parent::__construct($a_title, $a_postvar); + $this->setInputType("raci"); + $this->setMaxLength(70); + $this->setSize(30); + $this->setDataSource($ilCtrl->getLinkTargetByClass($a_class, $a_autocomplete_cmd, "", true)); + } - /** - * Static asynchronous default auto complete function. - */ - static function echoAutoCompleteList() - { - $q = $_REQUEST["term"]; - include_once("./Services/AccessControl/classes/class.ilRoleAutoComplete.php"); - $list = ilRoleAutoComplete::getList($q); - echo $list; - exit; - } + /** + * Static asynchronous default auto complete function. + */ + public static function echoAutoCompleteList() + { + $q = $_REQUEST["term"]; + include_once("./Services/AccessControl/classes/class.ilRoleAutoComplete.php"); + $list = ilRoleAutoComplete::getList($q); + echo $list; + exit; + } } diff --git a/Services/Form/classes/class.ilSelectBuilderInputGUI.php b/Services/Form/classes/class.ilSelectBuilderInputGUI.php index 0d9a35ddc969f4a6dc3a0170ef479f1354705347..e98fbac38a25dd71f49585ef3e2d71530d4559e6 100644 --- a/Services/Form/classes/class.ilSelectBuilderInputGUI.php +++ b/Services/Form/classes/class.ilSelectBuilderInputGUI.php @@ -2,7 +2,7 @@ /* Copyright (c) 1998-2009 ILIAS open source, Extended GPL, see docs/LICENSE */ /** - * Input GUI for the configuration of select input elements. E.g course custum field, + * Input GUI for the configuration of select input elements. E.g course custum field, * udf field, ... * * @author Stefan Meyer @@ -11,198 +11,181 @@ */ class ilSelectBuilderInputGUI extends ilTextWizardInputGUI { - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilTemplate + */ + protected $tpl; - - protected $open_answer_indexes = array(); - - - // constructor - public function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + + protected $open_answer_indexes = array(); + + + // constructor + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - parent::__construct($a_title, $a_postvar); - } - - - /** - * Get open answer indexes - */ - public function getOpenAnswerIndexes() - { - return $this->open_answer_indexes; - } - - /** - * Set open answer indexes - */ - public function setOpenAnswerIndexes($a_indexes) - { - $this->open_answer_indexes = $a_indexes; - } - - /** - * Mark an index as open answer - */ - public function addOpenAnswerIndex($a_idx) - { - $this->open_answer_indexes[] = $a_idx; - } - - /** - * Check if an index is an open answer index - * @param type $a_idx - * @return type - */ - public function isOpenAnswerIndex($a_idx) - { - return in_array($a_idx,(array) $this->open_answer_indexes); - } + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + parent::__construct($a_title, $a_postvar); + } + + + /** + * Get open answer indexes + */ + public function getOpenAnswerIndexes() + { + return $this->open_answer_indexes; + } + + /** + * Set open answer indexes + */ + public function setOpenAnswerIndexes($a_indexes) + { + $this->open_answer_indexes = $a_indexes; + } + + /** + * Mark an index as open answer + */ + public function addOpenAnswerIndex($a_idx) + { + $this->open_answer_indexes[] = $a_idx; + } + + /** + * Check if an index is an open answer index + * @param type $a_idx + * @return type + */ + public function isOpenAnswerIndex($a_idx) + { + return in_array($a_idx, (array) $this->open_answer_indexes); + } - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - public function checkInput() - { - $lng = $this->lng; - - $foundvalues = $_POST[$this->getPostVar()]; - - - - $this->setOpenAnswerIndexes(array()); - if (is_array($foundvalues)) - { - foreach ($foundvalues as $idx => $value) - { - $_POST[$this->getPostVar()][$idx] = ilUtil::stripSlashes($value); - if ($this->getRequired() && trim($value) == "") - { - $this->setAlert($lng->txt("msg_input_is_required")); + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + $foundvalues = $_POST[$this->getPostVar()]; + + + + $this->setOpenAnswerIndexes(array()); + if (is_array($foundvalues)) { + foreach ($foundvalues as $idx => $value) { + $_POST[$this->getPostVar()][$idx] = ilUtil::stripSlashes($value); + if ($this->getRequired() && trim($value) == "") { + $this->setAlert($lng->txt("msg_input_is_required")); - return false; - } - else if (strlen($this->getValidationRegexp())) - { - if (!preg_match($this->getValidationRegexp(), $value)) - { - $this->setAlert($lng->txt("msg_wrong_format")); - return FALSE; - } - } - } - } - else - { - $this->setAlert($lng->txt("msg_input_is_required")); - return FALSE; - } - - foreach((array) $_POST[$this->getPostVar().'_open'] as $oindex => $ovalue) - { - $this->addOpenAnswerIndex($oindex); - } - - - return $this->checkSubItemsInput(); - } - - public function setValueByArray($a_values) - { - parent::setValueByArray($a_values); - - foreach((array) $_POST[$this->getPostVar().'_open'] as $oindex => $ovalue) - { - $this->addOpenAnswerIndex($oindex); - } - } - - /** - * Insert property html - * - * @return int Size - */ - public function insert($a_tpl) - { - $lng = $this->lng; - - $tpl = new ilTemplate("tpl.prop_selectbuilder.html", true, true, "Services/Form"); - $i = 0; - foreach ($this->values as $value) - { - if(!is_string($value)) - { - continue; - } - - if (strlen((string) $value)) - { - $tpl->setCurrentBlock("prop_text_propval"); - $tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput((string) $value)); - $tpl->parseCurrentBlock(); - } - if ($this->getAllowMove()) - { - $tpl->setCurrentBlock("move"); - $tpl->setVariable("CMD_UP", "cmd[up" . $this->getFieldId() . "][$i]"); - $tpl->setVariable("CMD_DOWN", "cmd[down" . $this->getFieldId() . "][$i]"); - $tpl->setVariable("ID", $this->getFieldId() . "[$i]"); - include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); - $tpl->setVariable("UP_BUTTON", ilGlyphGUI::get(ilGlyphGUI::UP)); - $tpl->setVariable("DOWN_BUTTON", ilGlyphGUI::get(ilGlyphGUI::DOWN)); + return false; + } elseif (strlen($this->getValidationRegexp())) { + if (!preg_match($this->getValidationRegexp(), $value)) { + $this->setAlert($lng->txt("msg_wrong_format")); + return false; + } + } + } + } else { + $this->setAlert($lng->txt("msg_input_is_required")); + return false; + } + + foreach ((array) $_POST[$this->getPostVar() . '_open'] as $oindex => $ovalue) { + $this->addOpenAnswerIndex($oindex); + } + + + return $this->checkSubItemsInput(); + } + + public function setValueByArray($a_values) + { + parent::setValueByArray($a_values); + + foreach ((array) $_POST[$this->getPostVar() . '_open'] as $oindex => $ovalue) { + $this->addOpenAnswerIndex($oindex); + } + } + + /** + * Insert property html + * + * @return int Size + */ + public function insert($a_tpl) + { + $lng = $this->lng; + + $tpl = new ilTemplate("tpl.prop_selectbuilder.html", true, true, "Services/Form"); + $i = 0; + foreach ($this->values as $value) { + if (!is_string($value)) { + continue; + } + + if (strlen((string) $value)) { + $tpl->setCurrentBlock("prop_text_propval"); + $tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput((string) $value)); + $tpl->parseCurrentBlock(); + } + if ($this->getAllowMove()) { + $tpl->setCurrentBlock("move"); + $tpl->setVariable("CMD_UP", "cmd[up" . $this->getFieldId() . "][$i]"); + $tpl->setVariable("CMD_DOWN", "cmd[down" . $this->getFieldId() . "][$i]"); + $tpl->setVariable("ID", $this->getFieldId() . "[$i]"); + include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); + $tpl->setVariable("UP_BUTTON", ilGlyphGUI::get(ilGlyphGUI::UP)); + $tpl->setVariable("DOWN_BUTTON", ilGlyphGUI::get(ilGlyphGUI::DOWN)); - $tpl->parseCurrentBlock(); - } - $tpl->setCurrentBlock("row"); - $tpl->setVariable("POST_VAR", $this->getPostVar() . "[$i]"); - #$tpl->setVariable('POST_VAR_OPEN',$this->getPostVar().'[open]'.'['.$i.']'); - $tpl->setVariable('POST_VAR_OPEN',$this->getPostVar().'_open'.'['.$i.']'); - $tpl->setVariable('POST_VAR_OPEN_ID', $this->getPostVar().'_open['.$i.']'); - $tpl->setVariable('TXT_OPEN', $lng->txt("form_open_answer")); - - if($this->isOpenAnswerIndex($i)) - { - $tpl->setVariable('PROP_OPEN_CHECKED','checked="checked"'); - } - if($this->getDisabled()) - { - $tpl->setVariable('PROP_OPEN_DISABLED','disabled="disabled"'); - } - - $tpl->setVariable("ID", $this->getFieldId() . "[$i]"); - $tpl->setVariable("CMD_ADD", "cmd[add" . $this->getFieldId() . "][$i]"); - $tpl->setVariable("CMD_REMOVE", "cmd[remove" . $this->getFieldId() . "][$i]"); - $tpl->setVariable("SIZE", $this->getSize()); - $tpl->setVariable("MAXLENGTH", $this->getMaxLength()); - if ($this->getDisabled()) - { - $tpl->setVariable("DISABLED", - " disabled=\"disabled\""); - } - include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); - $tpl->setVariable("ADD_BUTTON", ilGlyphGUI::get(ilGlyphGUI::ADD)); - $tpl->setVariable("REMOVE_BUTTON", ilGlyphGUI::get(ilGlyphGUI::REMOVE)); - $tpl->parseCurrentBlock(); - $i++; - } - $tpl->setVariable("ELEMENT_ID", $this->getFieldId()); + $tpl->parseCurrentBlock(); + } + $tpl->setCurrentBlock("row"); + $tpl->setVariable("POST_VAR", $this->getPostVar() . "[$i]"); + #$tpl->setVariable('POST_VAR_OPEN',$this->getPostVar().'[open]'.'['.$i.']'); + $tpl->setVariable('POST_VAR_OPEN', $this->getPostVar() . '_open' . '[' . $i . ']'); + $tpl->setVariable('POST_VAR_OPEN_ID', $this->getPostVar() . '_open[' . $i . ']'); + $tpl->setVariable('TXT_OPEN', $lng->txt("form_open_answer")); + + if ($this->isOpenAnswerIndex($i)) { + $tpl->setVariable('PROP_OPEN_CHECKED', 'checked="checked"'); + } + if ($this->getDisabled()) { + $tpl->setVariable('PROP_OPEN_DISABLED', 'disabled="disabled"'); + } + + $tpl->setVariable("ID", $this->getFieldId() . "[$i]"); + $tpl->setVariable("CMD_ADD", "cmd[add" . $this->getFieldId() . "][$i]"); + $tpl->setVariable("CMD_REMOVE", "cmd[remove" . $this->getFieldId() . "][$i]"); + $tpl->setVariable("SIZE", $this->getSize()); + $tpl->setVariable("MAXLENGTH", $this->getMaxLength()); + if ($this->getDisabled()) { + $tpl->setVariable( + "DISABLED", + " disabled=\"disabled\"" + ); + } + include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); + $tpl->setVariable("ADD_BUTTON", ilGlyphGUI::get(ilGlyphGUI::ADD)); + $tpl->setVariable("REMOVE_BUTTON", ilGlyphGUI::get(ilGlyphGUI::REMOVE)); + $tpl->parseCurrentBlock(); + $i++; + } + $tpl->setVariable("ELEMENT_ID", $this->getFieldId()); - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $tpl->get()); - $a_tpl->parseCurrentBlock(); - - $tpl = $this->tpl; - $tpl->addJavascript("./Services/Form/js/ServiceFormWizardInput.js"); - $tpl->addJavascript("./Services/Form/templates/default/textwizard.js"); - } - - + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $tpl->get()); + $a_tpl->parseCurrentBlock(); + + $tpl = $this->tpl; + $tpl->addJavascript("./Services/Form/js/ServiceFormWizardInput.js"); + $tpl->addJavascript("./Services/Form/templates/default/textwizard.js"); + } } diff --git a/Services/Form/classes/class.ilSelectInputGUI.php b/Services/Form/classes/class.ilSelectInputGUI.php index 460ff52f2d40078b6074fe160a143a7752fe8942..2f03ca50c44ba231efdf924a0d661a34bbd5c4ca 100755 --- a/Services/Form/classes/class.ilSelectInputGUI.php +++ b/Services/Form/classes/class.ilSelectInputGUI.php @@ -10,292 +10,263 @@ include_once 'Services/Form/interfaces/interface.ilMultiValuesItem.php'; /** * This class represents a selection list property in a property form. * -* @author Alex Killing +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilSelectInputGUI extends ilSubEnabledFormPropertyGUI implements ilTableFilterItem, ilToolbarItem, ilMultiValuesItem { - protected $cust_attr = array(); - protected $options = array(); - protected $value; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + protected $cust_attr = array(); + protected $options = array(); + protected $value; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - parent::__construct($a_title, $a_postvar); - $this->setType("select"); - } + $this->lng = $DIC->language(); + parent::__construct($a_title, $a_postvar); + $this->setType("select"); + } - /** - * Set Options. - * - * @param array $a_options Options. Array ("value" => "option_text") - */ - function setOptions($a_options) - { - $this->options = $a_options; - } + /** + * Set Options. + * + * @param array $a_options Options. Array ("value" => "option_text") + */ + public function setOptions($a_options) + { + $this->options = $a_options; + } - /** - * Get Options. - * - * @return array Options. Array ("value" => "option_text") - */ - function getOptions() - { - return $this->options ? $this->options : array(); - } + /** + * Get Options. + * + * @return array Options. Array ("value" => "option_text") + */ + public function getOptions() + { + return $this->options ? $this->options : array(); + } - /** - * Set Value. - * - * @param string $a_value Value - */ - function setValue($a_value) - { - if($this->getMulti() && is_array($a_value)) - { - $this->setMultiValues($a_value); - $a_value = array_shift($a_value); - } - $this->value = $a_value; - } + /** + * Set Value. + * + * @param string $a_value Value + */ + public function setValue($a_value) + { + if ($this->getMulti() && is_array($a_value)) { + $this->setMultiValues($a_value); + $a_value = array_shift($a_value); + } + $this->value = $a_value; + } - /** - * Get Value. - * - * @return string Value - */ - function getValue() - { - return $this->value; - } - - - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $this->setValue($a_values[$this->getPostVar()]); - foreach($this->getSubItems() as $item) - { - $item->setValueByArray($a_values); - } - } + /** + * Get Value. + * + * @return string Value + */ + public function getValue() + { + return $this->value; + } + + + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $this->setValue($a_values[$this->getPostVar()]); + foreach ($this->getSubItems() as $item) { + $item->setValueByArray($a_values); + } + } - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; - $valid = true; - if(!$this->getMulti()) - { - $_POST[$this->getPostVar()] = ilUtil::stripSlashes($_POST[$this->getPostVar()]); - if($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") - { - $valid = false; - } - else if(!array_key_exists($_POST[$this->getPostVar()], (array) $this->getOptions())) - { - $this->setAlert($lng->txt('msg_invalid_post_input')); - return false; - } - } - else - { - foreach($_POST[$this->getPostVar()] as $idx => $value) - { - $_POST[$this->getPostVar()][$idx] = ilUtil::stripSlashes($value); - if(!array_key_exists($value, (array) $this->getOptions())) - { - $this->setAlert($lng->txt('msg_invalid_post_input')); - return false; - } - } - $_POST[$this->getPostVar()] = array_unique($_POST[$this->getPostVar()]); + $valid = true; + if (!$this->getMulti()) { + $_POST[$this->getPostVar()] = ilUtil::stripSlashes($_POST[$this->getPostVar()]); + if ($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") { + $valid = false; + } elseif (!array_key_exists($_POST[$this->getPostVar()], (array) $this->getOptions())) { + $this->setAlert($lng->txt('msg_invalid_post_input')); + return false; + } + } else { + foreach ($_POST[$this->getPostVar()] as $idx => $value) { + $_POST[$this->getPostVar()][$idx] = ilUtil::stripSlashes($value); + if (!array_key_exists($value, (array) $this->getOptions())) { + $this->setAlert($lng->txt('msg_invalid_post_input')); + return false; + } + } + $_POST[$this->getPostVar()] = array_unique($_POST[$this->getPostVar()]); - if($this->getRequired() && !trim(implode("", $_POST[$this->getPostVar()]))) - { - $valid = false; - } - } - if (!$valid) - { - $this->setAlert($lng->txt("msg_input_is_required")); - return false; - } - return $this->checkSubItemsInput(); - } - - public function addCustomAttribute($a_attr) - { - $this->cust_attr[] = $a_attr; - } - - public function getCustomAttributes() - { - return (array) $this->cust_attr; - } + if ($this->getRequired() && !trim(implode("", $_POST[$this->getPostVar()]))) { + $valid = false; + } + } + if (!$valid) { + $this->setAlert($lng->txt("msg_input_is_required")); + return false; + } + return $this->checkSubItemsInput(); + } + + public function addCustomAttribute($a_attr) + { + $this->cust_attr[] = $a_attr; + } + + public function getCustomAttributes() + { + return (array) $this->cust_attr; + } - /** - * Render item - */ - function render($a_mode = "") - { - $tpl = new ilTemplate("tpl.prop_select.html", true, true, "Services/Form"); - - foreach($this->getCustomAttributes() as $attr) - { - $tpl->setCurrentBlock('cust_attr'); - $tpl->setVariable('CUSTOM_ATTR',$attr); - $tpl->parseCurrentBlock(); - } - - // determin value to select. Due to accessibility reasons we - // should always select a value (per default the first one) - $first = true; - foreach($this->getOptions() as $option_value => $option_text) - { - if ($first) - { - $sel_value = $option_value; - } - $first = false; - if ((string) $option_value == (string) $this->getValue()) - { - $sel_value = $option_value; - } - } - foreach($this->getOptions() as $option_value => $option_text) - { - $tpl->setCurrentBlock("prop_select_option"); - $tpl->setVariable("VAL_SELECT_OPTION", ilUtil::prepareFormOutput($option_value)); - if((string) $sel_value == (string) $option_value) - { - $tpl->setVariable("CHK_SEL_OPTION", - 'selected="selected"'); - } - $tpl->setVariable("TXT_SELECT_OPTION", $option_text); - $tpl->parseCurrentBlock(); - } - $tpl->setVariable("ID", $this->getFieldId()); - - $postvar = $this->getPostVar(); - if($this->getMulti() && substr($postvar, -2) != "[]") - { - $postvar .= "[]"; - } - - if ($this->getDisabled()) - { - if($this->getMulti()) - { - $value = $this->getMultiValues(); - $hidden = ""; - if(is_array($value)) - { - foreach($value as $item) - { - $hidden .= $this->getHiddenTag($postvar, $item); - } - } - } - else - { - $hidden = $this->getHiddenTag($postvar, $this->getValue()); - } - if($hidden) - { - $tpl->setVariable("DISABLED", " disabled=\"disabled\""); - $tpl->setVariable("HIDDEN_INPUT", $hidden); - } - } - else - { - $tpl->setVariable("POST_VAR", $postvar); - } - - // multi icons - if($this->getMulti() && !$a_mode && !$this->getDisabled()) - { - $tpl->touchBlock("inline_in_bl"); - $tpl->setVariable("MULTI_ICONS", $this->getMultiIconsHTML()); - } + /** + * Render item + */ + public function render($a_mode = "") + { + $tpl = new ilTemplate("tpl.prop_select.html", true, true, "Services/Form"); + + foreach ($this->getCustomAttributes() as $attr) { + $tpl->setCurrentBlock('cust_attr'); + $tpl->setVariable('CUSTOM_ATTR', $attr); + $tpl->parseCurrentBlock(); + } + + // determin value to select. Due to accessibility reasons we + // should always select a value (per default the first one) + $first = true; + foreach ($this->getOptions() as $option_value => $option_text) { + if ($first) { + $sel_value = $option_value; + } + $first = false; + if ((string) $option_value == (string) $this->getValue()) { + $sel_value = $option_value; + } + } + foreach ($this->getOptions() as $option_value => $option_text) { + $tpl->setCurrentBlock("prop_select_option"); + $tpl->setVariable("VAL_SELECT_OPTION", ilUtil::prepareFormOutput($option_value)); + if ((string) $sel_value == (string) $option_value) { + $tpl->setVariable( + "CHK_SEL_OPTION", + 'selected="selected"' + ); + } + $tpl->setVariable("TXT_SELECT_OPTION", $option_text); + $tpl->parseCurrentBlock(); + } + $tpl->setVariable("ID", $this->getFieldId()); + + $postvar = $this->getPostVar(); + if ($this->getMulti() && substr($postvar, -2) != "[]") { + $postvar .= "[]"; + } + + if ($this->getDisabled()) { + if ($this->getMulti()) { + $value = $this->getMultiValues(); + $hidden = ""; + if (is_array($value)) { + foreach ($value as $item) { + $hidden .= $this->getHiddenTag($postvar, $item); + } + } + } else { + $hidden = $this->getHiddenTag($postvar, $this->getValue()); + } + if ($hidden) { + $tpl->setVariable("DISABLED", " disabled=\"disabled\""); + $tpl->setVariable("HIDDEN_INPUT", $hidden); + } + } else { + $tpl->setVariable("POST_VAR", $postvar); + } + + // multi icons + if ($this->getMulti() && !$a_mode && !$this->getDisabled()) { + $tpl->touchBlock("inline_in_bl"); + $tpl->setVariable("MULTI_ICONS", $this->getMultiIconsHTML()); + } - $tpl->setVariable("ARIA_LABEL", ilUtil::prepareFormOutput($this->getTitle())); + $tpl->setVariable("ARIA_LABEL", ilUtil::prepareFormOutput($this->getTitle())); - return $tpl->get(); - } - - /** - * Insert property html - * - * @return int Size - */ - function insert($a_tpl) - { - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $this->render()); - $a_tpl->parseCurrentBlock(); - } + return $tpl->get(); + } + + /** + * Insert property html + * + * @return int Size + */ + public function insert($a_tpl) + { + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $this->render()); + $a_tpl->parseCurrentBlock(); + } - /** - * Get HTML for table filter - */ - function getTableFilterHTML() - { - $html = $this->render(); - return $html; - } + /** + * Get HTML for table filter + */ + public function getTableFilterHTML() + { + $html = $this->render(); + return $html; + } - /** - * Get HTML for toolbar - */ - function getToolbarHTML() - { - $html = $this->render("toolbar"); - return $html; - } - - /** - * Set initial sub form visibility, optionally add dynamic value-based condition - * - * @see ilObjBookingPoolGUI - * @param bool $a_value - * @param string $a_condition - */ - function setHideSubForm($a_value, $a_condition = null) - { - $this->hide_sub = (bool)$a_value; - - if($a_condition) - { - $this->addCustomAttribute('onchange="if(this.value '.$a_condition.')'. - ' { il.Form.showSubForm(\'subform_'.$this->getFieldId().'\', \'il_prop_cont_'.$this->getFieldId().'\'); }'. - ' else { il.Form.hideSubForm(\'subform_'.$this->getFieldId().'\'); };"'); - } - } - - function hideSubForm() - { - return (bool)$this->hide_sub; - } + /** + * Get HTML for toolbar + */ + public function getToolbarHTML() + { + $html = $this->render("toolbar"); + return $html; + } + + /** + * Set initial sub form visibility, optionally add dynamic value-based condition + * + * @see ilObjBookingPoolGUI + * @param bool $a_value + * @param string $a_condition + */ + public function setHideSubForm($a_value, $a_condition = null) + { + $this->hide_sub = (bool) $a_value; + + if ($a_condition) { + $this->addCustomAttribute('onchange="if(this.value ' . $a_condition . ')' . + ' { il.Form.showSubForm(\'subform_' . $this->getFieldId() . '\', \'il_prop_cont_' . $this->getFieldId() . '\'); }' . + ' else { il.Form.hideSubForm(\'subform_' . $this->getFieldId() . '\'); };"'); + } + } + public function hideSubForm() + { + return (bool) $this->hide_sub; + } } diff --git a/Services/Form/classes/class.ilSubEnabledFormPropertyGUI.php b/Services/Form/classes/class.ilSubEnabledFormPropertyGUI.php index 8a2ea35e8745b4087adedb4b07df8add2d9db2ab..fc149523f431d91869960cf72db03182e059e38d 100755 --- a/Services/Form/classes/class.ilSubEnabledFormPropertyGUI.php +++ b/Services/Form/classes/class.ilSubEnabledFormPropertyGUI.php @@ -1,24 +1,24 @@ +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilSubEnabledFormPropertyGUI extends ilFormPropertyGUI { - protected $sub_items = array(); - - /** - * Add Subitem - * - * @param object $a_item Item - */ - function addSubItem($a_item) - { - $a_item->setParent($this); - $this->sub_items[] = $a_item; - } + protected $sub_items = array(); + + /** + * Add Subitem + * + * @param object $a_item Item + */ + public function addSubItem($a_item) + { + $a_item->setParent($this); + $this->sub_items[] = $a_item; + } - /** - * Get Subitems - * - * @return array Array of items - */ - function getSubItems() - { - return $this->sub_items; - } - - /** - * returns a flat array of possibly existing subitems recursively - * - * @return array - */ - public function getSubInputItemsRecursive() - { - $subInputItems = array(); - - foreach( $this->sub_items as $subItem ) - { - if( $subItem->getType() == 'section_header' ) - { - continue; - } - - $subInputItems[] = $subItem; - - if( $subItem instanceof ilSubEnabledFormPropertyGUI ) - { - $subInputItems = array_merge( $subInputItems, $subItem->getSubInputItemsRecursive() ); - } - } - - return $subInputItems; - } + /** + * Get Subitems + * + * @return array Array of items + */ + public function getSubItems() + { + return $this->sub_items; + } + + /** + * returns a flat array of possibly existing subitems recursively + * + * @return array + */ + public function getSubInputItemsRecursive() + { + $subInputItems = array(); + + foreach ($this->sub_items as $subItem) { + if ($subItem->getType() == 'section_header') { + continue; + } + + $subInputItems[] = $subItem; + + if ($subItem instanceof ilSubEnabledFormPropertyGUI) { + $subInputItems = array_merge($subInputItems, $subItem->getSubInputItemsRecursive()); + } + } + + return $subInputItems; + } - /** - * Check SubItems - * - * @return boolean Input ok, true/false - */ - final function checkSubItemsInput() - { - $ok = true; - foreach($this->getSubItems() as $item) - { - $item_ok = $item->checkInput(); - if(!$item_ok) - { - $ok = false; - } - } - return $ok; - } + /** + * Check SubItems + * + * @return boolean Input ok, true/false + */ + final public function checkSubItemsInput() + { + $ok = true; + foreach ($this->getSubItems() as $item) { + $item_ok = $item->checkInput(); + if (!$item_ok) { + $ok = false; + } + } + return $ok; + } - /** - * Get sub form html - * - */ - final function getSubForm() - { - // subitems - $pf = null; - if (count($this->getSubItems()) > 0) - { - $pf = new ilPropertyFormGUI(); - $pf->setMode("subform"); - $pf->setItems($this->getSubItems()); - } + /** + * Get sub form html + * + */ + final public function getSubForm() + { + // subitems + $pf = null; + if (count($this->getSubItems()) > 0) { + $pf = new ilPropertyFormGUI(); + $pf->setMode("subform"); + $pf->setItems($this->getSubItems()); + } - return $pf; - } + return $pf; + } - /** - * Get item by post var - * - * @return mixed false or item object - */ - function getItemByPostVar($a_post_var) - { - if ($this->getPostVar() == $a_post_var) - { - return $this; - } - - foreach($this->getSubItems() as $item) - { - if ($item->getType() != "section_header") - { - $ret = $item->getItemByPostVar($a_post_var); - if (is_object($ret)) - { - return $ret; - } - } - } - - return false; - } + /** + * Get item by post var + * + * @return mixed false or item object + */ + public function getItemByPostVar($a_post_var) + { + if ($this->getPostVar() == $a_post_var) { + return $this; + } + foreach ($this->getSubItems() as $item) { + if ($item->getType() != "section_header") { + $ret = $item->getItemByPostVar($a_post_var); + if (is_object($ret)) { + return $ret; + } + } + } + + return false; + } } diff --git a/Services/Form/classes/class.ilTagInputGUI.php b/Services/Form/classes/class.ilTagInputGUI.php index 323253da66f0a6f08e154020fd608514e23909b1..c1f0395b56a3b014243883017fcdd17333d9d539 100755 --- a/Services/Form/classes/class.ilTagInputGUI.php +++ b/Services/Form/classes/class.ilTagInputGUI.php @@ -4,258 +4,241 @@ /** * This class represents a tag list property in a property form. * -* @author Guido Vollbach +* @author Guido Vollbach * @version $Id$ * @ingroup ServicesForm */ class ilTagInputGUI extends ilSubEnabledFormPropertyGUI { - /** - * @var ilTemplate - */ - protected $tpl; - - protected $options = array(); - protected $max_tags = 0; - protected $max_chars = 0; - protected $allow_duplicates = false; - protected $js_self_init = true; - - protected $type_ahead = false; - protected $type_ahead_ignore_case = true; - protected $type_ahead_list = array(); - protected $type_ahead_min_length = 2; - protected $type_ahead_limit = 30; - protected $type_ahead_highlight = true; - - /** - * @param int $max_tags - */ - public function setMaxTags($max_tags) - { - $this->max_tags = $max_tags; - } - - /** - * @param int $max_chars - */ - public function setMaxChars($max_chars) - { - $this->max_chars = $max_chars; - } - - /** - * @param boolean $allow_duplicates - */ - public function setAllowDuplicates($allow_duplicates) - { - $this->allow_duplicates = $allow_duplicates; - } - - /** - * @param boolean $js_self_init - */ - public function setJsSelfInit($js_self_init) - { - $this->js_self_init = $js_self_init; - } - - /** - * @param boolean $type_ahead - */ - public function setTypeAhead($type_ahead) - { - $this->type_ahead = $type_ahead; - } - - /** - * @param boolean $type_ahead_ignore_case - */ - public function setTypeAheadIgnoreCase($type_ahead_ignore_case) - { - $this->type_ahead_ignore_case = $type_ahead_ignore_case; - } - - /** - * @param int $min_length - */ - public function setTypeAheadMinLength($min_length) - { - $this->type_ahead_min_length = $min_length; - } - - /** - * @param int $limit - */ - public function setTypeAheadLimit($limit) - { - $this->type_ahead_limit = $limit; - } - - /** - * @param boolean $highlight - */ - public function setTypeAheadHighlight($highlight) - { - $this->type_ahead_highlight = $highlight; - } - - /** - * @param array $type_ahead_list - */ - public function setTypeAheadList($type_ahead_list) - { - $this->type_ahead_list = $type_ahead_list; - } - - /** - * Set Options. - * - * @param array $a_options Options. - */ - function setOptions($a_options) - { - $this->options = $a_options; - } - - /** - * Get Options. - * - * @return array Options. Array - */ - function getOptions() - { - return $this->options ? $this->options : array(); - } - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; - - $this->tpl = $DIC["tpl"]; - $this->lng = $DIC->language(); - parent::__construct($a_title, $a_postvar); - $this->setType("tag_input"); - $tpl = $DIC["tpl"]; - $tpl->addJavaScript('./Services/Form/js/bootstrap-tagsinput_2015_25_03.js'); - $tpl->addJavaScript('./Services/Form/js/typeahead_0.11.1.js'); - $tpl->addCss('./Services/Form/css/bootstrap-tagsinput_2015_25_03.css'); - - } - - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $this->setOptions($a_values[$this->getPostVar()]); - foreach($this->getSubItems() as $item) - { - $item->setValueByArray($a_values); - } - } - - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - $valid = true; - if(array_key_exists($this->getPostVar(), $_POST)) - { - foreach($_POST[$this->getPostVar()] as $idx => $value) - { - $_POST[$this->getPostVar()][$idx] = ilUtil::stripSlashes($value); - } - $_POST[$this->getPostVar()] = array_unique($_POST[$this->getPostVar()]); - - if($this->getRequired() && !trim(implode("", $_POST[$this->getPostVar()]))) - { - $valid = false; - } - } - else if($this->getRequired()) - { - $valid = false; - } - if (!$valid) - { - $this->setAlert($lng->txt("msg_input_is_required")); - return false; - } - return $this->checkSubItemsInput(); - } - - /** - * @param string $a_mode - * @return string - */ - function render($a_mode = "") - { - - if($this->type_ahead) - { - $tpl = new ilTemplate("tpl.prop_tag_typeahead.html", true, true, "Services/Form"); - $tpl->setVariable("MIN_LENGTH", $this->type_ahead_min_length); - $tpl->setVariable("LIMIT", $this->type_ahead_limit); - $tpl->setVariable("HIGHLIGHT", $this->type_ahead_highlight); - if($this->type_ahead_ignore_case) - { - $tpl->setVariable("CASE", 'i'); - } - $tpl->setVariable("TERMS", json_encode($this->type_ahead_list)); - } - else - { - $tpl = new ilTemplate("tpl.prop_tag.html", true, true, "Services/Form"); - } - - $tpl->setVariable("MAXTAGS", $this->max_tags); - $tpl->setVariable("MAXCHARS", $this->max_chars); - $tpl->setVariable("ALLOW_DUPLICATES", $this->allow_duplicates); - - foreach($this->getOptions() as $option_value => $option_text) - { - $tpl->setCurrentBlock("prop_select_option"); - $tpl->setVariable("VAL_SELECT_OPTION", ilUtil::prepareFormOutput($option_text)); - $tpl->setVariable("TXT_SELECT_OPTION", $option_text); - $tpl->parseCurrentBlock(); - } - - $tpl->setVariable("ID", $this->getFieldId()); - - $tpl->setVariable("POST_VAR", $this->getPostVar() . "[]"); - - if($this->js_self_init) - { - $tpl->setCurrentBlock("initialize_on_page_load"); - $tpl->parseCurrentBlock(); - } - $tpl->setVariable("ID",$this->getFieldId()); - return $tpl->get(); - } - - /** - * @param $a_tpl - */ - function insert($a_tpl) - { - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $this->render()); - $a_tpl->parseCurrentBlock(); - } - - + /** + * @var ilTemplate + */ + protected $tpl; + + protected $options = array(); + protected $max_tags = 0; + protected $max_chars = 0; + protected $allow_duplicates = false; + protected $js_self_init = true; + + protected $type_ahead = false; + protected $type_ahead_ignore_case = true; + protected $type_ahead_list = array(); + protected $type_ahead_min_length = 2; + protected $type_ahead_limit = 30; + protected $type_ahead_highlight = true; + + /** + * @param int $max_tags + */ + public function setMaxTags($max_tags) + { + $this->max_tags = $max_tags; + } + + /** + * @param int $max_chars + */ + public function setMaxChars($max_chars) + { + $this->max_chars = $max_chars; + } + + /** + * @param boolean $allow_duplicates + */ + public function setAllowDuplicates($allow_duplicates) + { + $this->allow_duplicates = $allow_duplicates; + } + + /** + * @param boolean $js_self_init + */ + public function setJsSelfInit($js_self_init) + { + $this->js_self_init = $js_self_init; + } + + /** + * @param boolean $type_ahead + */ + public function setTypeAhead($type_ahead) + { + $this->type_ahead = $type_ahead; + } + + /** + * @param boolean $type_ahead_ignore_case + */ + public function setTypeAheadIgnoreCase($type_ahead_ignore_case) + { + $this->type_ahead_ignore_case = $type_ahead_ignore_case; + } + + /** + * @param int $min_length + */ + public function setTypeAheadMinLength($min_length) + { + $this->type_ahead_min_length = $min_length; + } + + /** + * @param int $limit + */ + public function setTypeAheadLimit($limit) + { + $this->type_ahead_limit = $limit; + } + + /** + * @param boolean $highlight + */ + public function setTypeAheadHighlight($highlight) + { + $this->type_ahead_highlight = $highlight; + } + + /** + * @param array $type_ahead_list + */ + public function setTypeAheadList($type_ahead_list) + { + $this->type_ahead_list = $type_ahead_list; + } + + /** + * Set Options. + * + * @param array $a_options Options. + */ + public function setOptions($a_options) + { + $this->options = $a_options; + } + + /** + * Get Options. + * + * @return array Options. Array + */ + public function getOptions() + { + return $this->options ? $this->options : array(); + } + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; + + $this->tpl = $DIC["tpl"]; + $this->lng = $DIC->language(); + parent::__construct($a_title, $a_postvar); + $this->setType("tag_input"); + $tpl = $DIC["tpl"]; + $tpl->addJavaScript('./Services/Form/js/bootstrap-tagsinput_2015_25_03.js'); + $tpl->addJavaScript('./Services/Form/js/typeahead_0.11.1.js'); + $tpl->addCss('./Services/Form/css/bootstrap-tagsinput_2015_25_03.css'); + } + + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $this->setOptions($a_values[$this->getPostVar()]); + foreach ($this->getSubItems() as $item) { + $item->setValueByArray($a_values); + } + } + + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + $valid = true; + if (array_key_exists($this->getPostVar(), $_POST)) { + foreach ($_POST[$this->getPostVar()] as $idx => $value) { + $_POST[$this->getPostVar()][$idx] = ilUtil::stripSlashes($value); + } + $_POST[$this->getPostVar()] = array_unique($_POST[$this->getPostVar()]); + + if ($this->getRequired() && !trim(implode("", $_POST[$this->getPostVar()]))) { + $valid = false; + } + } elseif ($this->getRequired()) { + $valid = false; + } + if (!$valid) { + $this->setAlert($lng->txt("msg_input_is_required")); + return false; + } + return $this->checkSubItemsInput(); + } + + /** + * @param string $a_mode + * @return string + */ + public function render($a_mode = "") + { + if ($this->type_ahead) { + $tpl = new ilTemplate("tpl.prop_tag_typeahead.html", true, true, "Services/Form"); + $tpl->setVariable("MIN_LENGTH", $this->type_ahead_min_length); + $tpl->setVariable("LIMIT", $this->type_ahead_limit); + $tpl->setVariable("HIGHLIGHT", $this->type_ahead_highlight); + if ($this->type_ahead_ignore_case) { + $tpl->setVariable("CASE", 'i'); + } + $tpl->setVariable("TERMS", json_encode($this->type_ahead_list)); + } else { + $tpl = new ilTemplate("tpl.prop_tag.html", true, true, "Services/Form"); + } + + $tpl->setVariable("MAXTAGS", $this->max_tags); + $tpl->setVariable("MAXCHARS", $this->max_chars); + $tpl->setVariable("ALLOW_DUPLICATES", $this->allow_duplicates); + + foreach ($this->getOptions() as $option_value => $option_text) { + $tpl->setCurrentBlock("prop_select_option"); + $tpl->setVariable("VAL_SELECT_OPTION", ilUtil::prepareFormOutput($option_text)); + $tpl->setVariable("TXT_SELECT_OPTION", $option_text); + $tpl->parseCurrentBlock(); + } + + $tpl->setVariable("ID", $this->getFieldId()); + + $tpl->setVariable("POST_VAR", $this->getPostVar() . "[]"); + + if ($this->js_self_init) { + $tpl->setCurrentBlock("initialize_on_page_load"); + $tpl->parseCurrentBlock(); + } + $tpl->setVariable("ID", $this->getFieldId()); + return $tpl->get(); + } + + /** + * @param $a_tpl + */ + public function insert($a_tpl) + { + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $this->render()); + $a_tpl->parseCurrentBlock(); + } } diff --git a/Services/Form/classes/class.ilTextAreaInputGUI.php b/Services/Form/classes/class.ilTextAreaInputGUI.php index bdc9ded0ee6c2f4cb2d569f9fef57d3db9ce9e57..52109c1acb2091b316f8c29f9226978807bd10e9 100755 --- a/Services/Form/classes/class.ilTextAreaInputGUI.php +++ b/Services/Form/classes/class.ilTextAreaInputGUI.php @@ -1,24 +1,24 @@ +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilTextAreaInputGUI extends ilSubEnabledFormPropertyGUI { - protected $value; - protected $cols; - protected $rows; - protected $usert; - protected $rtetags; - protected $plugins; - protected $removeplugins; - protected $buttons; - protected $rtesupport; - protected $use_tags_for_rte_only = true; - protected $max_num_chars; - protected $min_num_chars; - - /** - * @var int - */ - protected $initial_rte_width = 795; - - /** - * Array of tinymce buttons which should be disabled - * - * @var Array - * @type Array - * @access protected - * - */ - protected $disabled_buttons = array(); - - /** - * Use purifier or not - * - * @var boolean - * @type boolean - * @access protected - * - */ - protected $usePurifier = false; - - /** - * Instance of ilHtmlPurifierInterface - * - * @var ilHtmlPurifierInterface - * @type ilHtmlPurifierInterface - * @access protected - * - */ - protected $Purifier = null; - - /** - * TinyMCE root block element which surrounds the generated html - * - * @var string - * @type string - * @access protected - */ - protected $root_block_element = null; - - protected $rte_tag_set = array( - "mini" => array("strong", "em", "u", "ol", "li", "ul", "blockquote", "a", "p", "span", "br"), // #13286/#17981 - "standard" => array ("strong", "em", "u", "ol", "li", "ul", "p", "div", - "i", "b", "code", "sup", "sub", "pre", "strike", "gap"), - "extended" => array ( - "a","blockquote","br","cite","code","div","em","h1","h2","h3", - "h4","h5","h6","hr","li","ol","p", - "pre","span","strike","strong","sub","sup","u","ul", - "i", "b", "gap"), - "extended_img" => array ( - "a","blockquote","br","cite","code","div","em","h1","h2","h3", - "h4","h5","h6","hr","img","li","ol","p", - "pre","span","strike","strong","sub","sup","u","ul", - "i", "b", "gap"), - "extended_table" => array ( - "a","blockquote","br","cite","code","div","em","h1","h2","h3", - "h4","h5","h6","hr","li","ol","p", - "pre","span","strike","strong","sub","sup","table","td", - "tr","u","ul", "i", "b", "gap"), - "extended_table_img" => array ( - "a","blockquote","br","cite","code","div","em","h1","h2","h3", - "h4","h5","h6","hr","img","li","ol","p", - "pre","span","strike","strong","sub","sup","table","td", - "tr","u","ul", "i", "b", "gap"), - "full" => array ( - "a","blockquote","br","cite","code","div","em","h1","h2","h3", - "h4","h5","h6","hr","img","li","ol","p", - "pre","span","strike","strong","sub","sup","table","td", - "tr","u","ul","ruby","rbc","rtc","rb","rt","rp", "i", "b", "gap")); - - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; - - $this->lng = $DIC->language(); - parent::__construct($a_title, $a_postvar); - $this->setType("textarea"); - $this->setRteTagSet("standard"); - $this->plugins = array(); - $this->removeplugins = array(); - $this->buttons = array(); - $this->rteSupport = array(); - } - - /** - * Set Value. - * - * @param string $a_value Value - */ - function setValue($a_value) - { - $this->value = $a_value; - } - - /** - * Get Value. - * - * @return string Value - */ - function getValue() - { - return $this->value; - } - - /** - * Set Cols. - * - * @deprecated - * @param int $a_cols Cols - */ - function setCols($a_cols) - { - // obsolete because of bootstrap - $this->cols = $a_cols; - } - - /** - * Get Cols. - * - * @return int Cols - */ - function getCols() - { - return $this->cols; - } - - /** - * Set Rows. - * - * @param int $a_rows Rows - */ - function setRows($a_rows) - { - $this->rows = $a_rows; - } - - /** - * Get Rows. - * - * @return int Rows - */ - function getRows() - { - return $this->rows; - } - - /** - * Set Maximum number of characters allowed. - * - * @param int $a_number Characters - */ - function setMaxNumOfChars($a_number) - { - $this->max_num_chars = $a_number; - } - - /** - * Get Maximum number of characters allowed. - */ - function getMaxNumOfChars() - { - return $this->max_num_chars; - } - - /** - * Set Minimum number of characters allowed. - * - * @param int $a_number Characters - */ - function setMinNumOfChars($a_number) - { - $this->min_num_chars = $a_number; - } - - /** - * Get Minimum number of characters allowed. - */ - function getMinNumOfChars() - { - return $this->min_num_chars; - } - - /** - * Set Use Rich Text Editing. - * - * @param int $a_usert Use Rich Text Editing - * @param string $version - */ - public function setUseRte($a_usert, $version = '') - { - $this->usert = $a_usert; - - if(strlen($version)) - { - $this->rteSupport['version'] = $version; - } - } - - /** - * Get Use Rich Text Editing. - * - * @return int Use Rich Text Editing - */ - function getUseRte() - { - return $this->usert; - } - - /** - * Add RTE plugin. - * - * @param string $a_plugin Plugin name - */ - function addPlugin($a_plugin) - { - $this->plugins[$a_plugin] = $a_plugin; - } - - /** - * Remove RTE plugin. - * - * @param string $a_plugin Plugin name - */ - function removePlugin($a_plugin) - { - $this->removeplugins[$a_plugin] = $a_plugin; - } - - /** - * Add RTE button. - * - * @param string $a_button Button name - */ - function addButton($a_button) - { - $this->buttons[$a_button] = $a_button; - } - - /** - * Remove RTE button. - * - * @param string $a_button Button name - */ - function removeButton($a_button) - { - unset($this->buttons[$a_button]); - } - - /** - * Set RTE support for a special module - * - * @param int $obj_id Object ID - * @param string $obj_type Object Type - * @param string $module ILIAS module - */ - function setRTESupport($obj_id, $obj_type, $module, $cfg_template = null, $hide_switch = false, $version = null) - { - $this->rteSupport = array("obj_id" => $obj_id, "obj_type" => $obj_type, "module" => $module, 'cfg_template' => $cfg_template, 'hide_switch' => $hide_switch, 'version' => $version); - } - - /** - * Remove RTE support for a special module - */ - function removeRTESupport() - { - $this->rteSupport = array(); - } - - /** - * Set Valid RTE Tags. - * - * @param array $a_rtetags Valid RTE Tags - */ - function setRteTags($a_rtetags) - { - $this->rtetags = $a_rtetags; - } - - /** - * Get Valid RTE Tags. - * - * @return array Valid RTE Tags - */ - function getRteTags() - { - return $this->rtetags; - } - - /** - * Set Set of Valid RTE Tags - * - * @return array Set name "standard", "extended", "extended_img", - * "extended_table", "extended_table_img", "full" - */ - function setRteTagSet($a_set_name) - { - $this->setRteTags($this->rte_tag_set[$a_set_name]); - } - - /** - * Get Set of Valid RTE Tags - * - * @return array Set name "standard", "extended", "extended_img", - * "extended_table", "extended_table_img", "full" - */ - function getRteTagSet($a_set_name) - { - return $this->rte_tag_set[$a_set_name]; - } - - - /** - * RTE Tag string - */ - function getRteTagString() - { - $result = ""; - foreach ($this->getRteTags() as $tag) - { - $result .= "<$tag>"; - } - return $result; - } - - /** - * Set use tags for RTE only (default is true) - * - * @param boolean $a_val use tags for RTE only - */ - function setUseTagsForRteOnly($a_val) - { - $this->use_tags_for_rte_only = $a_val; - } - - /** - * Get use tags for RTE only (default is true) - * - * @return boolean use tags for RTE only - */ - function getUseTagsForRteOnly() - { - return $this->use_tags_for_rte_only; - } - - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $this->setValue($a_values[$this->getPostVar()]); - - foreach($this->getSubItems() as $item) - { - $item->setValueByArray($a_values); - } - } - - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - include_once("./Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php"); - - if($this->usePurifier() && $this->getPurifier()) - { - $_POST[$this->getPostVar()] = ilUtil::stripOnlySlashes($_POST[$this->getPostVar()]); - $_POST[$this->getPostVar()] = $this->getPurifier()->purify($_POST[$this->getPostVar()]); - } - else - { - $allowed = $this->getRteTagString(); - if ($this->plugins["latex"] == "latex" && !is_int(strpos($allowed, ""))) - { - $allowed.= ""; - } - $_POST[$this->getPostVar()] = ($this->getUseRte() || !$this->getUseTagsForRteOnly()) - ? ilUtil::stripSlashes($_POST[$this->getPostVar()], true, $allowed) - : $this->stripSlashesAddSpaceFallback($_POST[$this->getPostVar()]); - } - - $_POST[$this->getPostVar()] = self::removeProhibitedCharacters($_POST[$this->getPostVar()]); - - if ($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") - { - $this->setAlert($lng->txt("msg_input_is_required")); - - return false; - } - - if($this->isCharLimited()) - { - //avoid whitespace surprises. #20630, #20674 - $ascii_whitespaces = chr(194).chr(160); - $ascii_breaklines = chr(13).chr(10); - - $to_replace = array ($ascii_whitespaces, $ascii_breaklines, "<", ">", "&"); - $replace_to = array (' ', '', "_", "_", "_"); - - #20630 mbstring extension is mandatory for 5.4 - $chars_entered = mb_strlen(strip_tags(str_replace($to_replace, $replace_to, $_POST[$this->getPostVar()]))); - - if($this->getMaxNumOfChars() && ($chars_entered > $this->getMaxNumOfChars())) - { - $this->setAlert($lng->txt("msg_input_char_limit_max")); - - return false; - } - elseif($this->getMinNumOfChars() && ($chars_entered < $this->getMinNumOfChars())) - { - $this->setAlert($lng->txt("msg_input_char_limit_min")); - - return false; - } - } - - return $this->checkSubItemsInput(); - } - - /** - * Insert property html - * - * @return int Size - */ - function insert($a_tpl) - { - $lng = $this->lng; - - $ttpl = new ilTemplate("tpl.prop_textarea.html", true, true, "Services/Form"); - - // disabled rte - if ($this->getUseRte() && $this->getDisabled()) - { - $ttpl->setCurrentBlock("disabled_rte"); - $ttpl->setVariable("DR_VAL", $this->getValue()); - $ttpl->parseCurrentBlock(); - } - else - { - if ($this->getUseRte()) - { - $rtestring = ilRTE::_getRTEClassname(); - include_once "./Services/RTE/classes/class.$rtestring.php"; - $rte = new $rtestring($this->rteSupport['version']); - - $rte->setInitialWidth($this->getInitialRteWidth()); - - // @todo: Check this. - $rte->addPlugin("emotions"); - foreach ($this->plugins as $plugin) - { - if (strlen($plugin)) - { - $rte->addPlugin($plugin); - } - } - foreach ($this->removeplugins as $plugin) - { - if (strlen($plugin)) - { - $rte->removePlugin($plugin); - } - } - - foreach ($this->buttons as $button) - { - if (strlen($button)) - { - $rte->addButton($button); - } - } - - $rte->disableButtons($this->getDisabledButtons()); - - if($this->getRTERootBlockElement() !== null) - { - $rte->setRTERootBlockElement($this->getRTERootBlockElement()); - } - - if (count($this->rteSupport) >= 3) - { - $rte->addRTESupport($this->rteSupport["obj_id"], $this->rteSupport["obj_type"], $this->rteSupport["module"], false, $this->rteSupport['cfg_template'], $this->rteSupport['hide_switch']); - } - else - { - // disable all plugins for mini-tagset - if(!array_diff($this->getRteTags(), $this->getRteTagSet("mini"))) - { - $rte->removeAllPlugins(); - - // #13603 - "paste from word" is essential - $rte->addPlugin("paste"); - - // #11980 - p-tag is mandatory but we do not want the icons it comes with - $rte->disableButtons(array("anchor", "justifyleft", "justifycenter", - "justifyright", "justifyfull", "formatselect", "removeformat", - "cut", "copy", "paste", "pastetext")); // JF, 2013-12-09 - } - - $rte->addCustomRTESupport(0, "", $this->getRteTags()); - } - - $ttpl->touchBlock("prop_ta_w"); - $ttpl->setCurrentBlock("prop_textarea"); - $ttpl->setVariable("ROWS", $this->getRows()); - } - else - { - $ttpl->touchBlock("no_rteditor"); - - if ($this->getCols() > 5) - { - $ttpl->setCurrentBlock("prop_ta_c"); - $ttpl->setVariable("COLS", $this->getCols()); - $ttpl->parseCurrentBlock(); - } - else - { - $ttpl->touchBlock("prop_ta_w"); - } - - $ttpl->setCurrentBlock("prop_textarea"); - $ttpl->setVariable("ROWS", $this->getRows()); - } - if (!$this->getDisabled()) - { - $ttpl->setVariable("POST_VAR", - $this->getPostVar()); - } - $ttpl->setVariable("ID", $this->getFieldId()); - if ($this->getDisabled()) - { - $ttpl->setVariable('DISABLED','disabled="disabled" '); - } - $ttpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($this->getValue())); - - if($this->getRequired()) - { - $ttpl->setVariable("REQUIRED", "required=\"required\""); - } - - if($this->isCharLimited()) - { - $ttpl->setVariable("MAXCHARS", $this->getMaxNumOfChars()); - $ttpl->setVariable("MINCHARS", $this->getMinNumOfChars()); - - $lng->toJS("form_chars_remaining"); - } - - $ttpl->parseCurrentBlock(); - } - - if($this->isCharLimited()) - { - $ttpl->setVariable("FEEDBACK_MAX_LIMIT", $this->getMaxNumOfChars()); - $ttpl->setVariable("FEEDBACK_ID", $this->getFieldId()); - $ttpl->setVariable("CHARS_REMAINING", $lng->txt("form_chars_remaining")); - } - - if ($this->getDisabled()) - { - $ttpl->setVariable("HIDDEN_INPUT", - $this->getHiddenTag($this->getPostVar(), $this->getValue())); - } - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $ttpl->get()); - $a_tpl->parseCurrentBlock(); - - } - - /** - * Setter/Getter for the html purifier usage - * - * @param boolean $a_flag Use purifier or not - * @return mixed Returns instance of ilTextAreaInputGUI or boolean - * @access public - */ - public function usePurifier($a_flag = null) - { - if(null === $a_flag) - { - return $this->usePurifier; - } - - $this->usePurifier = $a_flag; - return $this; - } - - /** - * Setter for the html purifier - * - * @param ilHtmlPurifierInterface Instance of ilHtmlPurifierInterface - * @return ilTextAreaInputGUI Instance of ilTextAreaInputGUI - * @access public - */ - public function setPurifier(ilHtmlPurifierInterface $Purifier) - { - $this->Purifier = $Purifier; - return $this; - } - - /** - * Getter for the html purifier - * - * @return ilHtmlPurifierInterface Instance of ilHtmlPurifierInterface - * @access public - */ - public function getPurifier() - { - return $this->Purifier; - } - - /** - * Setter for the TinyMCE root block element - * - * @param string $a_root_block_element root block element - * @return ilTextAreaInputGUI Instance of ilTextAreaInputGUI - * @access public - */ - public function setRTERootBlockElement($a_root_block_element) - { - $this->root_block_element = $a_root_block_element; - return $this; - } - - /** - * Getter for the TinyMCE root block element - * - * @return string Root block element of TinyMCE - * @access public - */ - public function getRTERootBlockElement() - { - return $this->root_block_element; - } - - /** - * Sets buttons which should be disabled in TinyMCE - * - * @param mixed $a_button Either a button string or an array of button strings - * @return ilTextAreaInputGUI Instance of ilTextAreaInputGUI - * @access public - * - */ - public function disableButtons($a_button) - { - if(is_array($a_button)) - { - $this->disabled_buttons = array_unique(array_merge($this->disabled_buttons, $a_button)); - } - else - { - $this->disabled_buttons = array_unique(array_merge($this->disabled_buttons, array($a_button))); - } - - return $this; - } - - /** - * Returns the disabled TinyMCE buttons - * - * @param boolean $as_array Should the disabled buttons be returned as a string or as an array - * @return Array Array of disabled buttons - * @access public - * - */ - public function getDisabledButtons($as_array = true) - { - if(!$as_array) - { - return implode(',', $this->disabled_buttons); - } - else - { - return $this->disabled_buttons; - } - } - - /** - * @return int - */ - public function getInitialRteWidth() - { - return $this->initial_rte_width; - } - - /** - * @param int $initial_rte_width - */ - public function setInitialRteWidth($initial_rte_width) - { - $this->initial_rte_width = $initial_rte_width; - } - - public function isCharLimited() - { - if ($this->getMaxNumOfChars() || $this->getMinNumOfChars()) - { - return true; - } - - return false; - - } + protected $value; + protected $cols; + protected $rows; + protected $usert; + protected $rtetags; + protected $plugins; + protected $removeplugins; + protected $buttons; + protected $rtesupport; + protected $use_tags_for_rte_only = true; + protected $max_num_chars; + protected $min_num_chars; + + /** + * @var int + */ + protected $initial_rte_width = 795; + + /** + * Array of tinymce buttons which should be disabled + * + * @var Array + * @type Array + * @access protected + * + */ + protected $disabled_buttons = array(); + + /** + * Use purifier or not + * + * @var boolean + * @type boolean + * @access protected + * + */ + protected $usePurifier = false; + + /** + * Instance of ilHtmlPurifierInterface + * + * @var ilHtmlPurifierInterface + * @type ilHtmlPurifierInterface + * @access protected + * + */ + protected $Purifier = null; + + /** + * TinyMCE root block element which surrounds the generated html + * + * @var string + * @type string + * @access protected + */ + protected $root_block_element = null; + + protected $rte_tag_set = array( + "mini" => array("strong", "em", "u", "ol", "li", "ul", "blockquote", "a", "p", "span", "br"), // #13286/#17981 + "standard" => array("strong", "em", "u", "ol", "li", "ul", "p", "div", + "i", "b", "code", "sup", "sub", "pre", "strike", "gap"), + "extended" => array( + "a","blockquote","br","cite","code","div","em","h1","h2","h3", + "h4","h5","h6","hr","li","ol","p", + "pre","span","strike","strong","sub","sup","u","ul", + "i", "b", "gap"), + "extended_img" => array( + "a","blockquote","br","cite","code","div","em","h1","h2","h3", + "h4","h5","h6","hr","img","li","ol","p", + "pre","span","strike","strong","sub","sup","u","ul", + "i", "b", "gap"), + "extended_table" => array( + "a","blockquote","br","cite","code","div","em","h1","h2","h3", + "h4","h5","h6","hr","li","ol","p", + "pre","span","strike","strong","sub","sup","table","td", + "tr","u","ul", "i", "b", "gap"), + "extended_table_img" => array( + "a","blockquote","br","cite","code","div","em","h1","h2","h3", + "h4","h5","h6","hr","img","li","ol","p", + "pre","span","strike","strong","sub","sup","table","td", + "tr","u","ul", "i", "b", "gap"), + "full" => array( + "a","blockquote","br","cite","code","div","em","h1","h2","h3", + "h4","h5","h6","hr","img","li","ol","p", + "pre","span","strike","strong","sub","sup","table","td", + "tr","u","ul","ruby","rbc","rtc","rb","rt","rp", "i", "b", "gap")); + + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; + + $this->lng = $DIC->language(); + parent::__construct($a_title, $a_postvar); + $this->setType("textarea"); + $this->setRteTagSet("standard"); + $this->plugins = array(); + $this->removeplugins = array(); + $this->buttons = array(); + $this->rteSupport = array(); + } + + /** + * Set Value. + * + * @param string $a_value Value + */ + public function setValue($a_value) + { + $this->value = $a_value; + } + + /** + * Get Value. + * + * @return string Value + */ + public function getValue() + { + return $this->value; + } + + /** + * Set Cols. + * + * @deprecated + * @param int $a_cols Cols + */ + public function setCols($a_cols) + { + // obsolete because of bootstrap + $this->cols = $a_cols; + } + + /** + * Get Cols. + * + * @return int Cols + */ + public function getCols() + { + return $this->cols; + } + + /** + * Set Rows. + * + * @param int $a_rows Rows + */ + public function setRows($a_rows) + { + $this->rows = $a_rows; + } + + /** + * Get Rows. + * + * @return int Rows + */ + public function getRows() + { + return $this->rows; + } + + /** + * Set Maximum number of characters allowed. + * + * @param int $a_number Characters + */ + public function setMaxNumOfChars($a_number) + { + $this->max_num_chars = $a_number; + } + + /** + * Get Maximum number of characters allowed. + */ + public function getMaxNumOfChars() + { + return $this->max_num_chars; + } + + /** + * Set Minimum number of characters allowed. + * + * @param int $a_number Characters + */ + public function setMinNumOfChars($a_number) + { + $this->min_num_chars = $a_number; + } + + /** + * Get Minimum number of characters allowed. + */ + public function getMinNumOfChars() + { + return $this->min_num_chars; + } + + /** + * Set Use Rich Text Editing. + * + * @param int $a_usert Use Rich Text Editing + * @param string $version + */ + public function setUseRte($a_usert, $version = '') + { + $this->usert = $a_usert; + + if (strlen($version)) { + $this->rteSupport['version'] = $version; + } + } + + /** + * Get Use Rich Text Editing. + * + * @return int Use Rich Text Editing + */ + public function getUseRte() + { + return $this->usert; + } + + /** + * Add RTE plugin. + * + * @param string $a_plugin Plugin name + */ + public function addPlugin($a_plugin) + { + $this->plugins[$a_plugin] = $a_plugin; + } + + /** + * Remove RTE plugin. + * + * @param string $a_plugin Plugin name + */ + public function removePlugin($a_plugin) + { + $this->removeplugins[$a_plugin] = $a_plugin; + } + + /** + * Add RTE button. + * + * @param string $a_button Button name + */ + public function addButton($a_button) + { + $this->buttons[$a_button] = $a_button; + } + + /** + * Remove RTE button. + * + * @param string $a_button Button name + */ + public function removeButton($a_button) + { + unset($this->buttons[$a_button]); + } + + /** + * Set RTE support for a special module + * + * @param int $obj_id Object ID + * @param string $obj_type Object Type + * @param string $module ILIAS module + */ + public function setRTESupport($obj_id, $obj_type, $module, $cfg_template = null, $hide_switch = false, $version = null) + { + $this->rteSupport = array("obj_id" => $obj_id, "obj_type" => $obj_type, "module" => $module, 'cfg_template' => $cfg_template, 'hide_switch' => $hide_switch, 'version' => $version); + } + + /** + * Remove RTE support for a special module + */ + public function removeRTESupport() + { + $this->rteSupport = array(); + } + + /** + * Set Valid RTE Tags. + * + * @param array $a_rtetags Valid RTE Tags + */ + public function setRteTags($a_rtetags) + { + $this->rtetags = $a_rtetags; + } + + /** + * Get Valid RTE Tags. + * + * @return array Valid RTE Tags + */ + public function getRteTags() + { + return $this->rtetags; + } + + /** + * Set Set of Valid RTE Tags + * + * @return array Set name "standard", "extended", "extended_img", + * "extended_table", "extended_table_img", "full" + */ + public function setRteTagSet($a_set_name) + { + $this->setRteTags($this->rte_tag_set[$a_set_name]); + } + + /** + * Get Set of Valid RTE Tags + * + * @return array Set name "standard", "extended", "extended_img", + * "extended_table", "extended_table_img", "full" + */ + public function getRteTagSet($a_set_name) + { + return $this->rte_tag_set[$a_set_name]; + } + + + /** + * RTE Tag string + */ + public function getRteTagString() + { + $result = ""; + foreach ($this->getRteTags() as $tag) { + $result .= "<$tag>"; + } + return $result; + } + + /** + * Set use tags for RTE only (default is true) + * + * @param boolean $a_val use tags for RTE only + */ + public function setUseTagsForRteOnly($a_val) + { + $this->use_tags_for_rte_only = $a_val; + } + + /** + * Get use tags for RTE only (default is true) + * + * @return boolean use tags for RTE only + */ + public function getUseTagsForRteOnly() + { + return $this->use_tags_for_rte_only; + } + + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $this->setValue($a_values[$this->getPostVar()]); + + foreach ($this->getSubItems() as $item) { + $item->setValueByArray($a_values); + } + } + + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + include_once("./Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php"); + + if ($this->usePurifier() && $this->getPurifier()) { + $_POST[$this->getPostVar()] = ilUtil::stripOnlySlashes($_POST[$this->getPostVar()]); + $_POST[$this->getPostVar()] = $this->getPurifier()->purify($_POST[$this->getPostVar()]); + } else { + $allowed = $this->getRteTagString(); + if ($this->plugins["latex"] == "latex" && !is_int(strpos($allowed, ""))) { + $allowed.= ""; + } + $_POST[$this->getPostVar()] = ($this->getUseRte() || !$this->getUseTagsForRteOnly()) + ? ilUtil::stripSlashes($_POST[$this->getPostVar()], true, $allowed) + : $this->stripSlashesAddSpaceFallback($_POST[$this->getPostVar()]); + } + + $_POST[$this->getPostVar()] = self::removeProhibitedCharacters($_POST[$this->getPostVar()]); + + if ($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") { + $this->setAlert($lng->txt("msg_input_is_required")); + + return false; + } + + if ($this->isCharLimited()) { + //avoid whitespace surprises. #20630, #20674 + $ascii_whitespaces = chr(194) . chr(160); + $ascii_breaklines = chr(13) . chr(10); + + $to_replace = array($ascii_whitespaces, $ascii_breaklines, "<", ">", "&"); + $replace_to = array(' ', '', "_", "_", "_"); + + #20630 mbstring extension is mandatory for 5.4 + $chars_entered = mb_strlen(strip_tags(str_replace($to_replace, $replace_to, $_POST[$this->getPostVar()]))); + + if ($this->getMaxNumOfChars() && ($chars_entered > $this->getMaxNumOfChars())) { + $this->setAlert($lng->txt("msg_input_char_limit_max")); + + return false; + } elseif ($this->getMinNumOfChars() && ($chars_entered < $this->getMinNumOfChars())) { + $this->setAlert($lng->txt("msg_input_char_limit_min")); + + return false; + } + } + + return $this->checkSubItemsInput(); + } + + /** + * Insert property html + * + * @return int Size + */ + public function insert($a_tpl) + { + $lng = $this->lng; + + $ttpl = new ilTemplate("tpl.prop_textarea.html", true, true, "Services/Form"); + + // disabled rte + if ($this->getUseRte() && $this->getDisabled()) { + $ttpl->setCurrentBlock("disabled_rte"); + $ttpl->setVariable("DR_VAL", $this->getValue()); + $ttpl->parseCurrentBlock(); + } else { + if ($this->getUseRte()) { + $rtestring = ilRTE::_getRTEClassname(); + include_once "./Services/RTE/classes/class.$rtestring.php"; + $rte = new $rtestring($this->rteSupport['version']); + + $rte->setInitialWidth($this->getInitialRteWidth()); + + // @todo: Check this. + $rte->addPlugin("emotions"); + foreach ($this->plugins as $plugin) { + if (strlen($plugin)) { + $rte->addPlugin($plugin); + } + } + foreach ($this->removeplugins as $plugin) { + if (strlen($plugin)) { + $rte->removePlugin($plugin); + } + } + + foreach ($this->buttons as $button) { + if (strlen($button)) { + $rte->addButton($button); + } + } + + $rte->disableButtons($this->getDisabledButtons()); + + if ($this->getRTERootBlockElement() !== null) { + $rte->setRTERootBlockElement($this->getRTERootBlockElement()); + } + + if (count($this->rteSupport) >= 3) { + $rte->addRTESupport($this->rteSupport["obj_id"], $this->rteSupport["obj_type"], $this->rteSupport["module"], false, $this->rteSupport['cfg_template'], $this->rteSupport['hide_switch']); + } else { + // disable all plugins for mini-tagset + if (!array_diff($this->getRteTags(), $this->getRteTagSet("mini"))) { + $rte->removeAllPlugins(); + + // #13603 - "paste from word" is essential + $rte->addPlugin("paste"); + + // #11980 - p-tag is mandatory but we do not want the icons it comes with + $rte->disableButtons(array("anchor", "justifyleft", "justifycenter", + "justifyright", "justifyfull", "formatselect", "removeformat", + "cut", "copy", "paste", "pastetext")); // JF, 2013-12-09 + } + + $rte->addCustomRTESupport(0, "", $this->getRteTags()); + } + + $ttpl->touchBlock("prop_ta_w"); + $ttpl->setCurrentBlock("prop_textarea"); + $ttpl->setVariable("ROWS", $this->getRows()); + } else { + $ttpl->touchBlock("no_rteditor"); + + if ($this->getCols() > 5) { + $ttpl->setCurrentBlock("prop_ta_c"); + $ttpl->setVariable("COLS", $this->getCols()); + $ttpl->parseCurrentBlock(); + } else { + $ttpl->touchBlock("prop_ta_w"); + } + + $ttpl->setCurrentBlock("prop_textarea"); + $ttpl->setVariable("ROWS", $this->getRows()); + } + if (!$this->getDisabled()) { + $ttpl->setVariable( + "POST_VAR", + $this->getPostVar() + ); + } + $ttpl->setVariable("ID", $this->getFieldId()); + if ($this->getDisabled()) { + $ttpl->setVariable('DISABLED', 'disabled="disabled" '); + } + $ttpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($this->getValue())); + + if ($this->getRequired()) { + $ttpl->setVariable("REQUIRED", "required=\"required\""); + } + + if ($this->isCharLimited()) { + $ttpl->setVariable("MAXCHARS", $this->getMaxNumOfChars()); + $ttpl->setVariable("MINCHARS", $this->getMinNumOfChars()); + + $lng->toJS("form_chars_remaining"); + } + + $ttpl->parseCurrentBlock(); + } + + if ($this->isCharLimited()) { + $ttpl->setVariable("FEEDBACK_MAX_LIMIT", $this->getMaxNumOfChars()); + $ttpl->setVariable("FEEDBACK_ID", $this->getFieldId()); + $ttpl->setVariable("CHARS_REMAINING", $lng->txt("form_chars_remaining")); + } + + if ($this->getDisabled()) { + $ttpl->setVariable( + "HIDDEN_INPUT", + $this->getHiddenTag($this->getPostVar(), $this->getValue()) + ); + } + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $ttpl->get()); + $a_tpl->parseCurrentBlock(); + } + + /** + * Setter/Getter for the html purifier usage + * + * @param boolean $a_flag Use purifier or not + * @return mixed Returns instance of ilTextAreaInputGUI or boolean + * @access public + */ + public function usePurifier($a_flag = null) + { + if (null === $a_flag) { + return $this->usePurifier; + } + + $this->usePurifier = $a_flag; + return $this; + } + + /** + * Setter for the html purifier + * + * @param ilHtmlPurifierInterface Instance of ilHtmlPurifierInterface + * @return ilTextAreaInputGUI Instance of ilTextAreaInputGUI + * @access public + */ + public function setPurifier(ilHtmlPurifierInterface $Purifier) + { + $this->Purifier = $Purifier; + return $this; + } + + /** + * Getter for the html purifier + * + * @return ilHtmlPurifierInterface Instance of ilHtmlPurifierInterface + * @access public + */ + public function getPurifier() + { + return $this->Purifier; + } + + /** + * Setter for the TinyMCE root block element + * + * @param string $a_root_block_element root block element + * @return ilTextAreaInputGUI Instance of ilTextAreaInputGUI + * @access public + */ + public function setRTERootBlockElement($a_root_block_element) + { + $this->root_block_element = $a_root_block_element; + return $this; + } + + /** + * Getter for the TinyMCE root block element + * + * @return string Root block element of TinyMCE + * @access public + */ + public function getRTERootBlockElement() + { + return $this->root_block_element; + } + + /** + * Sets buttons which should be disabled in TinyMCE + * + * @param mixed $a_button Either a button string or an array of button strings + * @return ilTextAreaInputGUI Instance of ilTextAreaInputGUI + * @access public + * + */ + public function disableButtons($a_button) + { + if (is_array($a_button)) { + $this->disabled_buttons = array_unique(array_merge($this->disabled_buttons, $a_button)); + } else { + $this->disabled_buttons = array_unique(array_merge($this->disabled_buttons, array($a_button))); + } + + return $this; + } + + /** + * Returns the disabled TinyMCE buttons + * + * @param boolean $as_array Should the disabled buttons be returned as a string or as an array + * @return Array Array of disabled buttons + * @access public + * + */ + public function getDisabledButtons($as_array = true) + { + if (!$as_array) { + return implode(',', $this->disabled_buttons); + } else { + return $this->disabled_buttons; + } + } + + /** + * @return int + */ + public function getInitialRteWidth() + { + return $this->initial_rte_width; + } + + /** + * @param int $initial_rte_width + */ + public function setInitialRteWidth($initial_rte_width) + { + $this->initial_rte_width = $initial_rte_width; + } + + public function isCharLimited() + { + if ($this->getMaxNumOfChars() || $this->getMinNumOfChars()) { + return true; + } + + return false; + } } diff --git a/Services/Form/classes/class.ilTextInputGUI.php b/Services/Form/classes/class.ilTextInputGUI.php index d3ad5f5df425401ac9a3062986f3945c3bae13e8..d2c8f07c302f139e8e5f322f517e544d8a35aa74 100755 --- a/Services/Form/classes/class.ilTextInputGUI.php +++ b/Services/Form/classes/class.ilTextInputGUI.php @@ -9,595 +9,549 @@ include_once 'Services/Form/interfaces/interface.ilMultiValuesItem.php'; /** * This class represents a text property in a property form. * -* @author Alex Killing +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilTextInputGUI extends ilSubEnabledFormPropertyGUI implements ilTableFilterItem, ilToolbarItem, ilMultiValuesItem { - protected $value; - protected $maxlength = 200; - protected $size = 40; - protected $validationRegexp; - protected $validationFailureMessage = ''; - protected $suffix; - protected $style_css; - protected $css_class; - protected $ajax_datasource; - protected $ajax_datasource_delimiter; - protected $ajax_datasource_commit = FALSE; - protected $ajax_datasource_commit_url; - protected $submit_form_on_enter = false; - - /** - * @var bool Flag whether the html autocomplete attribute should be set to "off" or not - */ - protected $autocomplete_disabled = false; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; - - $this->lng = $DIC->language(); - parent::__construct($a_title, $a_postvar); - $this->setInputType("text"); - $this->setType("text"); - $this->validationRegexp = ""; - } - - /** - * Set Value. - * - * @param string $a_value Value - */ - function setValue($a_value) - { - if($this->getMulti() && is_array($a_value)) - { - $this->setMultiValues($a_value); - $a_value = array_shift($a_value); - } - $this->value = $a_value; - } - - /** - * Get Value. - * - * @return string Value - */ - function getValue() - { - return $this->value; - } - - - /** - * Set message string for validation failure - * @return - * @param string $a_msg - */ - public function setValidationFailureMessage($a_msg) - { - $this->validationFailureMessage = $a_msg; - } - - public function getValidationFailureMessage() - { - return $this->validationFailureMessage; - } - - /** - * Set validation regexp. - * - * @param string $a_value regexp - */ - public function setValidationRegexp($a_value) - { - $this->validationRegexp = $a_value; - } - - /** - * Get validation regexp. - * - * @return string regexp - */ - function getValidationRegexp() - { - return $this->validationRegexp; - } - - /** - * Set Max Length. - * - * @param int $a_maxlength Max Length - */ - function setMaxLength($a_maxlength) - { - $this->maxlength = $a_maxlength; - } - - /** - * Get Max Length. - * - * @return int Max Length - */ - function getMaxLength() - { - return $this->maxlength; - } - - /** - * Set Size. - * - * @param int $a_size Size - */ - function setSize($a_size) - { - $this->size = $a_size; - } - - /** - * Set inline style. - * - * @param string $a_style style - */ - function setInlineStyle($a_style) - { - $this->style_css = $a_style; - } - - /** - * Get inline style. - * - * @return string style - */ - function getInlineStyle() - { - return $this->style_css; - } - - public function setCssClass($a_class) - { - $this->css_class = $a_class; - } - - public function getCssClass() - { - return $this->css_class; - } - - - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $this->setValue($a_values[$this->getPostVar()]); - } - - /** - * Get Size. - * - * @return int Size - */ - function getSize() - { - return $this->size; - } - - /** - * Set suffix. - * - * @param string $a_value suffix - */ - function setSuffix($a_value) - { - $this->suffix = $a_value; - } - - /** - * Get suffix. - * - * @return string suffix - */ - function getSuffix() - { - return $this->suffix; - } - - /** - * set input type - * - * @access public - * @param string input type password | text - * - */ - public function setInputType($a_type) - { - $this->input_type = $a_type; - } - - /** - * get input type - * - * @access public - */ - public function getInputType() - { - return $this->input_type; - } - - /** - * Set submit form on enter - * - * @param boolean - */ - function setSubmitFormOnEnter($a_val) - { - $this->submit_form_on_enter = $a_val; - } - - /** - * Get submit form on enter - * - * @return boolean - */ - function getSubmitFormOnEnter() - { - return $this->submit_form_on_enter; - } - - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - if(!$this->getMulti()) - { - //$_POST[$this->getPostVar()] = ilUtil::stripSlashes($_POST[$this->getPostVar()]); - $_POST[$this->getPostVar()] = $this->stripSlashesAddSpaceFallback($_POST[$this->getPostVar()]); - if ($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") - { - $this->setAlert($lng->txt("msg_input_is_required")); - - return false; - } - else if (strlen($this->getValidationRegexp())) - { - if (!preg_match($this->getValidationRegexp(), $_POST[$this->getPostVar()])) - { - $this->setAlert( - $this->getValidationFailureMessage() ? - $this->getValidationFailureMessage() : - $lng->txt('msg_wrong_format') - ); - return FALSE; - } - } - } - else - { - // #17296 - if(!is_array($_POST[$this->getPostVar()])) - { - $_POST[$this->getPostVar()] = array(); - } - foreach($_POST[$this->getPostVar()] as $idx => $value) - { - //$_POST[$this->getPostVar()][$idx] = ilUtil::stripSlashes($value); - $_POST[$this->getPostVar()][$idx] = $this->stripSlashesAddSpaceFallback($value); - } - $_POST[$this->getPostVar()] = array_unique($_POST[$this->getPostVar()]); - - if ($this->getRequired() && !trim(implode("", $_POST[$this->getPostVar()]))) - { - $this->setAlert($lng->txt("msg_input_is_required")); - - return false; - } - else if (strlen($this->getValidationRegexp())) - { - $reg_valid = true; - foreach($_POST[$this->getPostVar()] as $value) - { - if (!preg_match($this->getValidationRegexp(), $value)) - { - $reg_valid = false; - break; - } - } - if(!$reg_valid) - { - $this->setAlert( - $this->getValidationFailureMessage() ? - $this->getValidationFailureMessage() : - $lng->txt('msg_wrong_format') - ); - return false; - } - } - } - - return $this->checkSubItemsInput(); - } - - /** - * get datasource link for js autocomplete - * @return String link to data generation script - */ - function getDataSource() - { - return $this->ajax_datasource; - } - - /** - * set datasource link for js autocomplete - * @param String link to data generation script - */ - function setDataSource($href, $a_delimiter = null) - { - $this->ajax_datasource = $href; - $this->ajax_datasource_delimiter = $a_delimiter; - } - - public function setDataSourceSubmitOnSelection($a_stat) - { - $this->ajax_datasource_commit = $a_stat; - } - - public function getDataSourceSubmitOnSelection() - { - return $this->ajax_datasource_commit; - } - - public function setDataSourceSubmitUrl($a_url) - { - $this->ajax_datasource_commit_url = $a_url; - } - public function getDataSourceSubmitUrl() - { - return $this->ajax_datasource_commit_url; - } - - - public function setMultiValues(array $a_values) - { - foreach($a_values as $idx => $value) - { - $a_values[$idx] = trim($value); - if($a_values[$idx] == "") - { - unset($a_values[$idx]); - } - } - parent::setMultiValues($a_values); - } - - /** - * Render item - */ - public function render($a_mode = "") - { - /** - * @var $lng ilLanguage - */ - $lng = $this->lng; - - $tpl = new ilTemplate("tpl.prop_textinput.html", true, true, "Services/Form"); - if (strlen($this->getValue())) - { - $tpl->setCurrentBlock("prop_text_propval"); - $tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($this->getValue())); - $tpl->parseCurrentBlock(); - } - if (strlen($this->getInlineStyle())) - { - $tpl->setCurrentBlock("stylecss"); - $tpl->setVariable("CSS_STYLE", ilUtil::prepareFormOutput($this->getInlineStyle())); - $tpl->parseCurrentBlock(); - } - if(strlen($this->getCssClass())) - { - $tpl->setCurrentBlock("classcss"); - $tpl->setVariable('CLASS_CSS', ilUtil::prepareFormOutput($this->getCssClass())); - $tpl->parseCurrentBlock(); - } - if ($this->getSubmitFormOnEnter()) - { - $tpl->touchBlock("submit_form_on_enter"); - } - - switch($this->getInputType()) - { - case 'password': - $tpl->setVariable('PROP_INPUT_TYPE','password'); - break; - case 'hidden': - $tpl->setVariable('PROP_INPUT_TYPE','hidden'); - break; - case 'text': - default: - $tpl->setVariable('PROP_INPUT_TYPE','text'); - } - $tpl->setVariable("ID", $this->getFieldId()); - $tpl->setVariable("SIZE", $this->getSize()); - if($this->getMaxLength() != null) - $tpl->setVariable("MAXLENGTH", $this->getMaxLength()); - if (strlen($this->getSuffix())) $tpl->setVariable("INPUT_SUFFIX", $this->getSuffix()); - - $postvar = $this->getPostVar(); - if($this->getMulti() && substr($postvar, -2) != "[]") - { - $postvar .= "[]"; - } - - if ($this->getDisabled()) - { - if($this->getMulti()) - { - $value = $this->getMultiValues(); - $hidden = ""; - if(is_array($value)) - { - foreach($value as $item) - { - $hidden .= $this->getHiddenTag($postvar, $item); - } - } - } - else - { - $hidden = $this->getHiddenTag($postvar, $this->getValue()); - } - if($hidden) - { - $tpl->setVariable("HIDDEN_INPUT", $hidden); - } - $tpl->setVariable("DISABLED", " disabled=\"disabled\""); - } - else - { - $tpl->setVariable("POST_VAR", $postvar); - } - - // use autocomplete feature? - if ($this->getDataSource()) - { - include_once "Services/jQuery/classes/class.iljQueryUtil.php"; - iljQueryUtil::initjQuery(); - iljQueryUtil::initjQueryUI(); - - if ($this->getMulti()) - { - $tpl->setCurrentBlock("ac_multi"); - $tpl->setVariable('MURL_AUTOCOMPLETE', $this->getDataSource()); - $tpl->setVariable('ID_AUTOCOMPLETE', $this->getFieldId()); - $tpl->parseCurrentBlock(); - - // set to fields that start with autocomplete selector - $sel_auto = '[id^="'.$this->getFieldId().'"]'; - } - else - { - // use id for autocomplete selector - $sel_auto = "#".$this->getFieldId(); - } - - $tpl->setCurrentBlock("autocomplete_bl"); - if(!$this->ajax_datasource_delimiter and !$this->getDataSourceSubmitOnSelection()) - { - $tpl->setVariable('SEL_AUTOCOMPLETE', $sel_auto); - $tpl->setVariable('URL_AUTOCOMPLETE', $this->getDataSource()); - } - elseif($this->getDataSourceSubmitOnSelection()) - { - $tpl->setVariable('SEL_AUTOCOMPLETE_AUTOSUBMIT', $sel_auto); - $tpl->setVariable('URL_AUTOCOMPLETE_AUTOSUBMIT_REQ', $this->getDataSource()); - $tpl->setVariable('URL_AUTOCOMPLETE_AUTOSUBMIT_RESP', $this->getDataSourceSubmitUrl()); - } - else - { - $tpl->setVariable('AUTOCOMPLETE_DELIMITER', $this->ajax_datasource_delimiter); - $tpl->setVariable('SEL_AUTOCOMPLETE_DELIMITER', $sel_auto); - $tpl->setVariable('URL_AUTOCOMPLETE_DELIMITER', $this->getDataSource()); - } - $tpl->parseCurrentBlock(); - - $tpl->setVariable('MORE_TXT', $lng->txt('autocomplete_more')); - } - - if ($a_mode == "toolbar") - { - // block-inline hack, see: http://blog.mozilla.com/webdev/2009/02/20/cross-browser-inline-block/ - // -moz-inline-stack for FF2 - // zoom 1; *display:inline for IE6 & 7 - $tpl->setVariable("STYLE_PAR", 'display: -moz-inline-stack; display:inline-block; zoom: 1; *display:inline;'); - } - else - { - $tpl->setVariable("STYLE_PAR", ''); - } - - if($this->isHtmlAutoCompleteDisabled()) - { - $tpl->setVariable("AUTOCOMPLETE", "autocomplete=\"off\""); - } - - if($this->getRequired()) - { - $tpl->setVariable("REQUIRED", "required=\"required\""); - } - - // multi icons - if($this->getMulti() && !$a_mode && !$this->getDisabled()) - { - $tpl->touchBlock("inline_in_bl"); - $tpl->setVariable("MULTI_ICONS", $this->getMultiIconsHTML()); - } - - $tpl->setVariable("ARIA_LABEL", ilUtil::prepareFormOutput($this->getTitle())); - - return $tpl->get(); - } - - /** - * Insert property html - * - * @return int Size - */ - function insert($a_tpl) - { - $html = $this->render(); - - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $html); - $a_tpl->parseCurrentBlock(); - } - - /** - * Get HTML for table filter - */ - function getTableFilterHTML() - { - $html = $this->render(); - return $html; - } - - /** - * Get HTML for toolbar - */ - function getToolbarHTML() - { - $html = $this->render("toolbar"); - return $html; - } - - /** - * @param boolean $autocomplete - */ - public function setDisableHtmlAutoComplete($autocomplete) - { - $this->autocomplete_disabled = $autocomplete; - } - - /** - * @return boolean - */ - public function isHtmlAutoCompleteDisabled() - { - return $this->autocomplete_disabled; - } + protected $value; + protected $maxlength = 200; + protected $size = 40; + protected $validationRegexp; + protected $validationFailureMessage = ''; + protected $suffix; + protected $style_css; + protected $css_class; + protected $ajax_datasource; + protected $ajax_datasource_delimiter; + protected $ajax_datasource_commit = false; + protected $ajax_datasource_commit_url; + protected $submit_form_on_enter = false; + + /** + * @var bool Flag whether the html autocomplete attribute should be set to "off" or not + */ + protected $autocomplete_disabled = false; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; + + $this->lng = $DIC->language(); + parent::__construct($a_title, $a_postvar); + $this->setInputType("text"); + $this->setType("text"); + $this->validationRegexp = ""; + } + + /** + * Set Value. + * + * @param string $a_value Value + */ + public function setValue($a_value) + { + if ($this->getMulti() && is_array($a_value)) { + $this->setMultiValues($a_value); + $a_value = array_shift($a_value); + } + $this->value = $a_value; + } + + /** + * Get Value. + * + * @return string Value + */ + public function getValue() + { + return $this->value; + } + + + /** + * Set message string for validation failure + * @return + * @param string $a_msg + */ + public function setValidationFailureMessage($a_msg) + { + $this->validationFailureMessage = $a_msg; + } + + public function getValidationFailureMessage() + { + return $this->validationFailureMessage; + } + + /** + * Set validation regexp. + * + * @param string $a_value regexp + */ + public function setValidationRegexp($a_value) + { + $this->validationRegexp = $a_value; + } + + /** + * Get validation regexp. + * + * @return string regexp + */ + public function getValidationRegexp() + { + return $this->validationRegexp; + } + + /** + * Set Max Length. + * + * @param int $a_maxlength Max Length + */ + public function setMaxLength($a_maxlength) + { + $this->maxlength = $a_maxlength; + } + + /** + * Get Max Length. + * + * @return int Max Length + */ + public function getMaxLength() + { + return $this->maxlength; + } + + /** + * Set Size. + * + * @param int $a_size Size + */ + public function setSize($a_size) + { + $this->size = $a_size; + } + + /** + * Set inline style. + * + * @param string $a_style style + */ + public function setInlineStyle($a_style) + { + $this->style_css = $a_style; + } + + /** + * Get inline style. + * + * @return string style + */ + public function getInlineStyle() + { + return $this->style_css; + } + + public function setCssClass($a_class) + { + $this->css_class = $a_class; + } + + public function getCssClass() + { + return $this->css_class; + } + + + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $this->setValue($a_values[$this->getPostVar()]); + } + + /** + * Get Size. + * + * @return int Size + */ + public function getSize() + { + return $this->size; + } + + /** + * Set suffix. + * + * @param string $a_value suffix + */ + public function setSuffix($a_value) + { + $this->suffix = $a_value; + } + + /** + * Get suffix. + * + * @return string suffix + */ + public function getSuffix() + { + return $this->suffix; + } + + /** + * set input type + * + * @access public + * @param string input type password | text + * + */ + public function setInputType($a_type) + { + $this->input_type = $a_type; + } + + /** + * get input type + * + * @access public + */ + public function getInputType() + { + return $this->input_type; + } + + /** + * Set submit form on enter + * + * @param boolean + */ + public function setSubmitFormOnEnter($a_val) + { + $this->submit_form_on_enter = $a_val; + } + + /** + * Get submit form on enter + * + * @return boolean + */ + public function getSubmitFormOnEnter() + { + return $this->submit_form_on_enter; + } + + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + if (!$this->getMulti()) { + //$_POST[$this->getPostVar()] = ilUtil::stripSlashes($_POST[$this->getPostVar()]); + $_POST[$this->getPostVar()] = $this->stripSlashesAddSpaceFallback($_POST[$this->getPostVar()]); + if ($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") { + $this->setAlert($lng->txt("msg_input_is_required")); + + return false; + } elseif (strlen($this->getValidationRegexp())) { + if (!preg_match($this->getValidationRegexp(), $_POST[$this->getPostVar()])) { + $this->setAlert( + $this->getValidationFailureMessage() ? + $this->getValidationFailureMessage() : + $lng->txt('msg_wrong_format') + ); + return false; + } + } + } else { + // #17296 + if (!is_array($_POST[$this->getPostVar()])) { + $_POST[$this->getPostVar()] = array(); + } + foreach ($_POST[$this->getPostVar()] as $idx => $value) { + //$_POST[$this->getPostVar()][$idx] = ilUtil::stripSlashes($value); + $_POST[$this->getPostVar()][$idx] = $this->stripSlashesAddSpaceFallback($value); + } + $_POST[$this->getPostVar()] = array_unique($_POST[$this->getPostVar()]); + + if ($this->getRequired() && !trim(implode("", $_POST[$this->getPostVar()]))) { + $this->setAlert($lng->txt("msg_input_is_required")); + + return false; + } elseif (strlen($this->getValidationRegexp())) { + $reg_valid = true; + foreach ($_POST[$this->getPostVar()] as $value) { + if (!preg_match($this->getValidationRegexp(), $value)) { + $reg_valid = false; + break; + } + } + if (!$reg_valid) { + $this->setAlert( + $this->getValidationFailureMessage() ? + $this->getValidationFailureMessage() : + $lng->txt('msg_wrong_format') + ); + return false; + } + } + } + + return $this->checkSubItemsInput(); + } + + /** + * get datasource link for js autocomplete + * @return String link to data generation script + */ + public function getDataSource() + { + return $this->ajax_datasource; + } + + /** + * set datasource link for js autocomplete + * @param String link to data generation script + */ + public function setDataSource($href, $a_delimiter = null) + { + $this->ajax_datasource = $href; + $this->ajax_datasource_delimiter = $a_delimiter; + } + + public function setDataSourceSubmitOnSelection($a_stat) + { + $this->ajax_datasource_commit = $a_stat; + } + + public function getDataSourceSubmitOnSelection() + { + return $this->ajax_datasource_commit; + } + + public function setDataSourceSubmitUrl($a_url) + { + $this->ajax_datasource_commit_url = $a_url; + } + public function getDataSourceSubmitUrl() + { + return $this->ajax_datasource_commit_url; + } + + + public function setMultiValues(array $a_values) + { + foreach ($a_values as $idx => $value) { + $a_values[$idx] = trim($value); + if ($a_values[$idx] == "") { + unset($a_values[$idx]); + } + } + parent::setMultiValues($a_values); + } + + /** + * Render item + */ + public function render($a_mode = "") + { + /** + * @var $lng ilLanguage + */ + $lng = $this->lng; + + $tpl = new ilTemplate("tpl.prop_textinput.html", true, true, "Services/Form"); + if (strlen($this->getValue())) { + $tpl->setCurrentBlock("prop_text_propval"); + $tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($this->getValue())); + $tpl->parseCurrentBlock(); + } + if (strlen($this->getInlineStyle())) { + $tpl->setCurrentBlock("stylecss"); + $tpl->setVariable("CSS_STYLE", ilUtil::prepareFormOutput($this->getInlineStyle())); + $tpl->parseCurrentBlock(); + } + if (strlen($this->getCssClass())) { + $tpl->setCurrentBlock("classcss"); + $tpl->setVariable('CLASS_CSS', ilUtil::prepareFormOutput($this->getCssClass())); + $tpl->parseCurrentBlock(); + } + if ($this->getSubmitFormOnEnter()) { + $tpl->touchBlock("submit_form_on_enter"); + } + + switch ($this->getInputType()) { + case 'password': + $tpl->setVariable('PROP_INPUT_TYPE', 'password'); + break; + case 'hidden': + $tpl->setVariable('PROP_INPUT_TYPE', 'hidden'); + break; + case 'text': + default: + $tpl->setVariable('PROP_INPUT_TYPE', 'text'); + } + $tpl->setVariable("ID", $this->getFieldId()); + $tpl->setVariable("SIZE", $this->getSize()); + if ($this->getMaxLength() != null) { + $tpl->setVariable("MAXLENGTH", $this->getMaxLength()); + } + if (strlen($this->getSuffix())) { + $tpl->setVariable("INPUT_SUFFIX", $this->getSuffix()); + } + + $postvar = $this->getPostVar(); + if ($this->getMulti() && substr($postvar, -2) != "[]") { + $postvar .= "[]"; + } + + if ($this->getDisabled()) { + if ($this->getMulti()) { + $value = $this->getMultiValues(); + $hidden = ""; + if (is_array($value)) { + foreach ($value as $item) { + $hidden .= $this->getHiddenTag($postvar, $item); + } + } + } else { + $hidden = $this->getHiddenTag($postvar, $this->getValue()); + } + if ($hidden) { + $tpl->setVariable("HIDDEN_INPUT", $hidden); + } + $tpl->setVariable("DISABLED", " disabled=\"disabled\""); + } else { + $tpl->setVariable("POST_VAR", $postvar); + } + + // use autocomplete feature? + if ($this->getDataSource()) { + include_once "Services/jQuery/classes/class.iljQueryUtil.php"; + iljQueryUtil::initjQuery(); + iljQueryUtil::initjQueryUI(); + + if ($this->getMulti()) { + $tpl->setCurrentBlock("ac_multi"); + $tpl->setVariable('MURL_AUTOCOMPLETE', $this->getDataSource()); + $tpl->setVariable('ID_AUTOCOMPLETE', $this->getFieldId()); + $tpl->parseCurrentBlock(); + + // set to fields that start with autocomplete selector + $sel_auto = '[id^="' . $this->getFieldId() . '"]'; + } else { + // use id for autocomplete selector + $sel_auto = "#" . $this->getFieldId(); + } + + $tpl->setCurrentBlock("autocomplete_bl"); + if (!$this->ajax_datasource_delimiter and !$this->getDataSourceSubmitOnSelection()) { + $tpl->setVariable('SEL_AUTOCOMPLETE', $sel_auto); + $tpl->setVariable('URL_AUTOCOMPLETE', $this->getDataSource()); + } elseif ($this->getDataSourceSubmitOnSelection()) { + $tpl->setVariable('SEL_AUTOCOMPLETE_AUTOSUBMIT', $sel_auto); + $tpl->setVariable('URL_AUTOCOMPLETE_AUTOSUBMIT_REQ', $this->getDataSource()); + $tpl->setVariable('URL_AUTOCOMPLETE_AUTOSUBMIT_RESP', $this->getDataSourceSubmitUrl()); + } else { + $tpl->setVariable('AUTOCOMPLETE_DELIMITER', $this->ajax_datasource_delimiter); + $tpl->setVariable('SEL_AUTOCOMPLETE_DELIMITER', $sel_auto); + $tpl->setVariable('URL_AUTOCOMPLETE_DELIMITER', $this->getDataSource()); + } + $tpl->parseCurrentBlock(); + + $tpl->setVariable('MORE_TXT', $lng->txt('autocomplete_more')); + } + + if ($a_mode == "toolbar") { + // block-inline hack, see: http://blog.mozilla.com/webdev/2009/02/20/cross-browser-inline-block/ + // -moz-inline-stack for FF2 + // zoom 1; *display:inline for IE6 & 7 + $tpl->setVariable("STYLE_PAR", 'display: -moz-inline-stack; display:inline-block; zoom: 1; *display:inline;'); + } else { + $tpl->setVariable("STYLE_PAR", ''); + } + + if ($this->isHtmlAutoCompleteDisabled()) { + $tpl->setVariable("AUTOCOMPLETE", "autocomplete=\"off\""); + } + + if ($this->getRequired()) { + $tpl->setVariable("REQUIRED", "required=\"required\""); + } + + // multi icons + if ($this->getMulti() && !$a_mode && !$this->getDisabled()) { + $tpl->touchBlock("inline_in_bl"); + $tpl->setVariable("MULTI_ICONS", $this->getMultiIconsHTML()); + } + + $tpl->setVariable("ARIA_LABEL", ilUtil::prepareFormOutput($this->getTitle())); + + return $tpl->get(); + } + + /** + * Insert property html + * + * @return int Size + */ + public function insert($a_tpl) + { + $html = $this->render(); + + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $html); + $a_tpl->parseCurrentBlock(); + } + + /** + * Get HTML for table filter + */ + public function getTableFilterHTML() + { + $html = $this->render(); + return $html; + } + + /** + * Get HTML for toolbar + */ + public function getToolbarHTML() + { + $html = $this->render("toolbar"); + return $html; + } + + /** + * @param boolean $autocomplete + */ + public function setDisableHtmlAutoComplete($autocomplete) + { + $this->autocomplete_disabled = $autocomplete; + } + + /** + * @return boolean + */ + public function isHtmlAutoCompleteDisabled() + { + return $this->autocomplete_disabled; + } } -?> \ No newline at end of file diff --git a/Services/Form/classes/class.ilTextWizardInputGUI.php b/Services/Form/classes/class.ilTextWizardInputGUI.php index 3f9a6a7bcf66302d6b5ce2f9f664d6c8f5a0f42c..25db15938e84f3c267a476c0596e6f7cbc3fbfe0 100755 --- a/Services/Form/classes/class.ilTextWizardInputGUI.php +++ b/Services/Form/classes/class.ilTextWizardInputGUI.php @@ -1,215 +1,201 @@ +* @author Helmut Schottmüller * @version $Id$ * @ingroup ServicesForm */ class ilTextWizardInputGUI extends ilTextInputGUI { - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilTemplate + */ + protected $tpl; - protected $values = array(); - protected $allowMove = false; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + protected $values = array(); + protected $allowMove = false; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - parent::__construct($a_title, $a_postvar); - $this->validationRegexp = ""; - } + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + parent::__construct($a_title, $a_postvar); + $this->validationRegexp = ""; + } - /** - * Set Values - * - * @param array $a_value Value - */ - function setValues($a_values) - { - $this->values = $a_values; - } - - /** - * Set Value - * - * @param array $a_value Value - */ - function setValue($a_value) - { - $this->values = $a_value; - } + /** + * Set Values + * + * @param array $a_value Value + */ + public function setValues($a_values) + { + $this->values = $a_values; + } + + /** + * Set Value + * + * @param array $a_value Value + */ + public function setValue($a_value) + { + $this->values = $a_value; + } - /** - * Get Values - * - * @return array Values - */ - function getValues() - { - return $this->values; - } + /** + * Get Values + * + * @return array Values + */ + public function getValues() + { + return $this->values; + } - /** - * Set allow move - * - * @param boolean $a_allow_move Allow move - */ - function setAllowMove($a_allow_move) - { - $this->allowMove = $a_allow_move; - } + /** + * Set allow move + * + * @param boolean $a_allow_move Allow move + */ + public function setAllowMove($a_allow_move) + { + $this->allowMove = $a_allow_move; + } - /** - * Get allow move - * - * @return boolean Allow move - */ - function getAllowMove() - { - return $this->allowMove; - } + /** + * Get allow move + * + * @return boolean Allow move + */ + public function getAllowMove() + { + return $this->allowMove; + } - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - $foundvalues = $_POST[$this->getPostVar()]; - if (is_array($foundvalues)) - { - foreach ($foundvalues as $idx => $value) - { - $_POST[$this->getPostVar()][$idx] = ilUtil::stripSlashes($value); - if ($this->getRequired() && trim($value) == "") - { - $this->setAlert($lng->txt("msg_input_is_required")); + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + $foundvalues = $_POST[$this->getPostVar()]; + if (is_array($foundvalues)) { + foreach ($foundvalues as $idx => $value) { + $_POST[$this->getPostVar()][$idx] = ilUtil::stripSlashes($value); + if ($this->getRequired() && trim($value) == "") { + $this->setAlert($lng->txt("msg_input_is_required")); - return false; - } - else if (strlen($this->getValidationRegexp())) - { - if (!preg_match($this->getValidationRegexp(), $value)) - { - $this->setAlert($lng->txt("msg_wrong_format")); - return FALSE; - } - } - } - } - else if($this->getRequired()) - { - $this->setAlert($lng->txt("msg_input_is_required")); - return FALSE; - } - - return $this->checkSubItemsInput(); - } + return false; + } elseif (strlen($this->getValidationRegexp())) { + if (!preg_match($this->getValidationRegexp(), $value)) { + $this->setAlert($lng->txt("msg_wrong_format")); + return false; + } + } + } + } elseif ($this->getRequired()) { + $this->setAlert($lng->txt("msg_input_is_required")); + return false; + } + + return $this->checkSubItemsInput(); + } - /** - * Insert property html - * - * @return int Size - */ - function insert($a_tpl) - { - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $this->render()); - $a_tpl->parseCurrentBlock(); - - } - - public function render($a_mode = "") - { - $tpl = new ilTemplate("tpl.prop_textwizardinput.html", true, true, "Services/Form"); - $i = 0; - foreach ($this->values as $value) - { - if (strlen($value)) - { - $tpl->setCurrentBlock("prop_text_propval"); - $tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($value)); - $tpl->parseCurrentBlock(); - } - if ($this->getAllowMove()) - { - $tpl->setCurrentBlock("move"); - $tpl->setVariable("CMD_UP", "cmd[up" . $this->getFieldId() . "][$i]"); - $tpl->setVariable("CMD_DOWN", "cmd[down" . $this->getFieldId() . "][$i]"); - $tpl->setVariable("ID", $this->getFieldId() . "[$i]"); - $tpl->setVariable("UP_BUTTON", ilGlyphGUI::get(ilGlyphGUI::UP)); - $tpl->setVariable("DOWN_BUTTON", ilGlyphGUI::get(ilGlyphGUI::DOWN)); - $tpl->parseCurrentBlock(); - } - $tpl->setCurrentBlock("row"); - $tpl->setVariable("POST_VAR", $this->getPostVar() . "[$i]"); - $tpl->setVariable("ID", $this->getFieldId() . "[$i]"); - $tpl->setVariable("SIZE", $this->getSize()); - $tpl->setVariable("MAXLENGTH", $this->getMaxLength()); - - if ($this->getDisabled()) - { - $tpl->setVariable("DISABLED", - " disabled=\"disabled\""); - } - else - { - $tpl->setVariable("CMD_ADD", "cmd[add" . $this->getFieldId() . "][$i]"); - $tpl->setVariable("CMD_REMOVE", "cmd[remove" . $this->getFieldId() . "][$i]"); - $tpl->setVariable("ADD_BUTTON", ilGlyphGUI::get(ilGlyphGUI::ADD)); - $tpl->setVariable("REMOVE_BUTTON", ilGlyphGUI::get(ilGlyphGUI::REMOVE)); - } - - $tpl->parseCurrentBlock(); - $i++; - } + /** + * Insert property html + * + * @return int Size + */ + public function insert($a_tpl) + { + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $this->render()); + $a_tpl->parseCurrentBlock(); + } + + public function render($a_mode = "") + { + $tpl = new ilTemplate("tpl.prop_textwizardinput.html", true, true, "Services/Form"); + $i = 0; + foreach ($this->values as $value) { + if (strlen($value)) { + $tpl->setCurrentBlock("prop_text_propval"); + $tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($value)); + $tpl->parseCurrentBlock(); + } + if ($this->getAllowMove()) { + $tpl->setCurrentBlock("move"); + $tpl->setVariable("CMD_UP", "cmd[up" . $this->getFieldId() . "][$i]"); + $tpl->setVariable("CMD_DOWN", "cmd[down" . $this->getFieldId() . "][$i]"); + $tpl->setVariable("ID", $this->getFieldId() . "[$i]"); + $tpl->setVariable("UP_BUTTON", ilGlyphGUI::get(ilGlyphGUI::UP)); + $tpl->setVariable("DOWN_BUTTON", ilGlyphGUI::get(ilGlyphGUI::DOWN)); + $tpl->parseCurrentBlock(); + } + $tpl->setCurrentBlock("row"); + $tpl->setVariable("POST_VAR", $this->getPostVar() . "[$i]"); + $tpl->setVariable("ID", $this->getFieldId() . "[$i]"); + $tpl->setVariable("SIZE", $this->getSize()); + $tpl->setVariable("MAXLENGTH", $this->getMaxLength()); + + if ($this->getDisabled()) { + $tpl->setVariable( + "DISABLED", + " disabled=\"disabled\"" + ); + } else { + $tpl->setVariable("CMD_ADD", "cmd[add" . $this->getFieldId() . "][$i]"); + $tpl->setVariable("CMD_REMOVE", "cmd[remove" . $this->getFieldId() . "][$i]"); + $tpl->setVariable("ADD_BUTTON", ilGlyphGUI::get(ilGlyphGUI::ADD)); + $tpl->setVariable("REMOVE_BUTTON", ilGlyphGUI::get(ilGlyphGUI::REMOVE)); + } + + $tpl->parseCurrentBlock(); + $i++; + } - $tpl->setVariable("ELEMENT_ID", $this->getFieldId()); - - if (!$this->getDisabled()) - { - $this->tpl->addJavascript("./Services/Form/js/ServiceFormWizardInput.js"); - $this->tpl->addJavascript("./Services/Form/templates/default/textwizard.js"); - } - - return $tpl->get(); - } + $tpl->setVariable("ELEMENT_ID", $this->getFieldId()); + + if (!$this->getDisabled()) { + $this->tpl->addJavascript("./Services/Form/js/ServiceFormWizardInput.js"); + $this->tpl->addJavascript("./Services/Form/templates/default/textwizard.js"); + } + + return $tpl->get(); + } } diff --git a/Services/Form/classes/class.ilUserLoginInputGUI.php b/Services/Form/classes/class.ilUserLoginInputGUI.php index 5b861f0d24180968b14d5879416fbed9028957d5..3b2c18febd6877aa7b86d30f56b5463b14fbc9fd 100755 --- a/Services/Form/classes/class.ilUserLoginInputGUI.php +++ b/Services/Form/classes/class.ilUserLoginInputGUI.php @@ -4,167 +4,162 @@ /** * This class represents a user login property in a property form. * -* @author Alex Killing +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilUserLoginInputGUI extends ilFormPropertyGUI { - protected $value; - protected $size = 40; - protected $max_length = 80; - protected $checkunused = 0; + protected $value; + protected $size = 40; + protected $max_length = 80; + protected $checkunused = 0; - /** - * @var bool Flag whether the html autocomplete attribute should be set to "off" or not - */ - protected $autocomplete_disabled = false; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + /** + * @var bool Flag whether the html autocomplete attribute should be set to "off" or not + */ + protected $autocomplete_disabled = false; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - parent::__construct($a_title, $a_postvar); - } + $this->lng = $DIC->language(); + parent::__construct($a_title, $a_postvar); + } - /** - * Set Value. - * - * @param string $a_value Value - */ - function setValue($a_value) - { - $this->value = $a_value; - } + /** + * Set Value. + * + * @param string $a_value Value + */ + public function setValue($a_value) + { + $this->value = $a_value; + } - /** - * Get Value. - * - * @return string Value - */ - function getValue() - { - return $this->value; - } + /** + * Get Value. + * + * @return string Value + */ + public function getValue() + { + return $this->value; + } - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $this->setValue($a_values[$this->getPostVar()]); - } + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $this->setValue($a_values[$this->getPostVar()]); + } - /** - * Set Check whether login is unused. - * - * @param int $a_checkunused user id of current user - */ - function setCurrentUserId($a_user_id) - { - $this->checkunused = $a_user_id; - } + /** + * Set Check whether login is unused. + * + * @param int $a_checkunused user id of current user + */ + public function setCurrentUserId($a_user_id) + { + $this->checkunused = $a_user_id; + } - /** - * Get Check whether login is unused. - * - * @return boolean Check whether login is unused - */ - function getCurrentUserId() - { - return $this->checkunused; - } + /** + * Get Check whether login is unused. + * + * @return boolean Check whether login is unused + */ + public function getCurrentUserId() + { + return $this->checkunused; + } - /** - * Set autocomplete - * - * @param bool $a_value Value - */ - function setDisableHtmlAutoComplete($a_value) - { - $this->autocomplete_disabled = (bool)$a_value; - } + /** + * Set autocomplete + * + * @param bool $a_value Value + */ + public function setDisableHtmlAutoComplete($a_value) + { + $this->autocomplete_disabled = (bool) $a_value; + } - /** - * Get autocomplete - * - * @return bool Value - */ - function isHtmlAutoCompleteDisabled() - { - return $this->autocomplete_disabled; - } - - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - $_POST[$this->getPostVar()] = ilUtil::stripSlashes($_POST[$this->getPostVar()]); - if ($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") - { - $this->setAlert($lng->txt("msg_input_is_required")); + /** + * Get autocomplete + * + * @return bool Value + */ + public function isHtmlAutoCompleteDisabled() + { + return $this->autocomplete_disabled; + } + + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + $_POST[$this->getPostVar()] = ilUtil::stripSlashes($_POST[$this->getPostVar()]); + if ($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") { + $this->setAlert($lng->txt("msg_input_is_required")); - return false; - } - if (!ilUtil::isLogin($_POST[$this->getPostVar()])) - { - $this->setAlert($lng->txt("login_invalid")); + return false; + } + if (!ilUtil::isLogin($_POST[$this->getPostVar()])) { + $this->setAlert($lng->txt("login_invalid")); - return false; - } - - if (ilObjUser::_loginExists($_POST[$this->getPostVar()],$this->getCurrentUserId())) - { - $this->setAlert($lng->txt("login_exists")); + return false; + } + + if (ilObjUser::_loginExists($_POST[$this->getPostVar()], $this->getCurrentUserId())) { + $this->setAlert($lng->txt("login_exists")); - return false; - } + return false; + } - - return true; - } + + return true; + } - /** - * Insert property html - */ - function insert($a_tpl) - { - $lng = $this->lng; - - $a_tpl->setCurrentBlock("prop_login"); - $a_tpl->setVariable("POST_VAR", $this->getPostVar()); - $a_tpl->setVariable("ID", $this->getFieldId()); - $a_tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($this->getValue())); - $a_tpl->setVariable("SIZE", $this->size); - $a_tpl->setVariable("MAXLENGTH", $this->max_length); - if ($this->getDisabled()) - { - $a_tpl->setVariable("DISABLED", - " disabled=\"disabled\""); - } - if($this->isHtmlAutoCompleteDisabled()) - { - $a_tpl->setVariable("AUTOCOMPLETE", "autocomplete=\"off\""); - } - if($this->getRequired()) - { - $a_tpl->setVariable("REQUIRED", "required=\"required\""); - } - $a_tpl->parseCurrentBlock(); - } + /** + * Insert property html + */ + public function insert($a_tpl) + { + $lng = $this->lng; + + $a_tpl->setCurrentBlock("prop_login"); + $a_tpl->setVariable("POST_VAR", $this->getPostVar()); + $a_tpl->setVariable("ID", $this->getFieldId()); + $a_tpl->setVariable("PROPERTY_VALUE", ilUtil::prepareFormOutput($this->getValue())); + $a_tpl->setVariable("SIZE", $this->size); + $a_tpl->setVariable("MAXLENGTH", $this->max_length); + if ($this->getDisabled()) { + $a_tpl->setVariable( + "DISABLED", + " disabled=\"disabled\"" + ); + } + if ($this->isHtmlAutoCompleteDisabled()) { + $a_tpl->setVariable("AUTOCOMPLETE", "autocomplete=\"off\""); + } + if ($this->getRequired()) { + $a_tpl->setVariable("REQUIRED", "required=\"required\""); + } + $a_tpl->parseCurrentBlock(); + } } -?> \ No newline at end of file diff --git a/Services/Form/exceptions/class.ilFormException.php b/Services/Form/exceptions/class.ilFormException.php index 37bafdea5e32f6a6330fbed9723f95c9a2194deb..8a43730d43904e1f2095c0bf72966c314fb34e49 100644 --- a/Services/Form/exceptions/class.ilFormException.php +++ b/Services/Form/exceptions/class.ilFormException.php @@ -8,4 +8,4 @@ require_once 'Services/Exceptions/classes/class.ilException.php'; */ class ilFormException extends ilException { -} \ No newline at end of file +} diff --git a/Services/Form/interfaces/interface.ilFormValuesManipulator.php b/Services/Form/interfaces/interface.ilFormValuesManipulator.php index b61da3bd5355a832c0374ec8cb7ea043cc062e63..9eac99eee82391fd87ed7e17075eb6524026e12a 100644 --- a/Services/Form/interfaces/interface.ilFormValuesManipulator.php +++ b/Services/Form/interfaces/interface.ilFormValuesManipulator.php @@ -9,15 +9,15 @@ */ interface ilFormValuesManipulator { - /** - * @param array $inputValues - * @return array $inputValues - */ - public function manipulateFormInputValues($inputValues); - - /** - * @param array $submitValues - * @return array $submitValues - */ - public function manipulateFormSubmitValues($submitValues); -} \ No newline at end of file + /** + * @param array $inputValues + * @return array $inputValues + */ + public function manipulateFormInputValues($inputValues); + + /** + * @param array $submitValues + * @return array $submitValues + */ + public function manipulateFormSubmitValues($submitValues); +} diff --git a/Services/Form/interfaces/interface.ilMultiValuesItem.php b/Services/Form/interfaces/interface.ilMultiValuesItem.php index 30f267b81f9519c5264dd2b95afdf363d7a5672b..fb999d784d08a7830538d8b9c45a225f600832b7 100644 --- a/Services/Form/interfaces/interface.ilMultiValuesItem.php +++ b/Services/Form/interfaces/interface.ilMultiValuesItem.php @@ -1,16 +1,13 @@ * @version $Id$ */ interface ilMultiValuesItem { - - } -?> \ No newline at end of file diff --git a/Services/Frameset/classes/class.ilFramesetGUI.php b/Services/Frameset/classes/class.ilFramesetGUI.php index ea6d6e7896a5372f3f2c73d0e049791ed4bf2f15..117f5673885ad5bd92e2f90669fa3c23e84b5a33 100644 --- a/Services/Frameset/classes/class.ilFramesetGUI.php +++ b/Services/Frameset/classes/class.ilFramesetGUI.php @@ -10,192 +10,186 @@ */ class ilFramesetGUI { - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilSetting - */ - protected $settings; - - - /** - * Constructor - * @access public - */ - function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - $this->settings = $DIC->settings(); - $lng = $DIC->language(); - - $this->setMainWidth("*"); - $this->setSideWidth("25%"); - - // default titles (accessibility revision) - // should not been overwritten, if no good reason is given - $this->setSideFrameTitle($lng->txt("side_frame")); - $this->setMainFrameTitle($lng->txt("content_frame")); - } - - /** - * set title for frameset (is normally shown by browser) - */ - function setFramesetTitle($a_fs_title) - { - $this->frameset_title = $a_fs_title; - } - - /** - * source url for main frame - */ - function setMainFrameSource($a_main_source) - { - $this->main_frame_source = $a_main_source; - } - - /** - * title for main frame - */ - function setMainFrameTitle($a_main_title) - { - $this->main_frame_title = $a_main_title; - } - - /** - * name for main frame - */ - function setMainFrameName($a_main_name) - { - $this->main_frame_name = $a_main_name; - } - - /** - * source url for side frame - */ - function setSideFrameSource($a_side_source) - { - $this->side_frame_source = $a_side_source; - } - - /** - * title for side frame - */ - function setSideFrameTitle($a_side_title) - { - $this->side_frame_title = $a_side_title; - } - - /** - * name for main frame - */ - function setSideFrameName($a_side_name) - { - $this->side_frame_name = $a_side_name; - } - - /** - * Set Main Width. - * - * @param string $a_mainwidth Main Width - */ - function setMainWidth($a_mainwidth) - { - $this->mainwidth = $a_mainwidth; - } - - /** - * Get Main Width. - * - * @return string Main Width - */ - function getMainWidth() - { - return $this->mainwidth; - } - - /** - * Set Side Width. - * - * @param string $a_sidewidth Side Width - */ - function setSideWidth($a_sidewidth) - { - $this->sidewidth = $a_sidewidth; - } - - /** - * Get Side Width. - * - * @return string Side Width - */ - function getSideWidth() - { - return $this->sidewidth; - } - - /** - * Get - */ - function get() - { - return $this->show(true); - } - - - /** - * Show frameset - */ - function show($a_get_only = false) - { - $ilSetting = $this->settings; - - if ($ilSetting->get("tree_frame") == "right") - { - $main = "LEFT"; - $side = "RIGHT"; - } - else - { - $main = "RIGHT"; - $side = "LEFT"; - } - - $tpl = new ilTemplate("tpl.frameset.html", true, false); - $tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); - - $tpl->setVariable("PAGETITLE", "- ".ilUtil::stripScriptHTML($this->frameset_title)); - $tpl->setVariable("SRC_".$main, $this->main_frame_source); - $tpl->setVariable("SRC_".$side, $this->side_frame_source); - $tpl->setVariable("TITLE_".$main, $this->main_frame_title); - $tpl->setVariable("TITLE_".$side, $this->side_frame_title); - $tpl->setVariable("NAME_".$main, $this->main_frame_name); - $tpl->setVariable("NAME_".$side, $this->side_frame_name); - $tpl->setVariable("WIDTH_".$main, $this->getMainWidth()); - $tpl->setVariable("WIDTH_".$side, $this->getSideWidth()); - if ($ilSetting->get('short_inst_name') != "") - { - $tpl->setVariable("WINDOW_TITLE", - $ilSetting->get('short_inst_name')); - } - else - { - $tpl->setVariable("WINDOW_TITLE", - "ILIAS"); - } - - if ($a_get_only) - { - return $tpl->get(); - } - else - { - $tpl->show("DEFAULT", false); - } - } - + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilSetting + */ + protected $settings; + + + /** + * Constructor + * @access public + */ + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + $this->settings = $DIC->settings(); + $lng = $DIC->language(); + + $this->setMainWidth("*"); + $this->setSideWidth("25%"); + + // default titles (accessibility revision) + // should not been overwritten, if no good reason is given + $this->setSideFrameTitle($lng->txt("side_frame")); + $this->setMainFrameTitle($lng->txt("content_frame")); + } + + /** + * set title for frameset (is normally shown by browser) + */ + public function setFramesetTitle($a_fs_title) + { + $this->frameset_title = $a_fs_title; + } + + /** + * source url for main frame + */ + public function setMainFrameSource($a_main_source) + { + $this->main_frame_source = $a_main_source; + } + + /** + * title for main frame + */ + public function setMainFrameTitle($a_main_title) + { + $this->main_frame_title = $a_main_title; + } + + /** + * name for main frame + */ + public function setMainFrameName($a_main_name) + { + $this->main_frame_name = $a_main_name; + } + + /** + * source url for side frame + */ + public function setSideFrameSource($a_side_source) + { + $this->side_frame_source = $a_side_source; + } + + /** + * title for side frame + */ + public function setSideFrameTitle($a_side_title) + { + $this->side_frame_title = $a_side_title; + } + + /** + * name for main frame + */ + public function setSideFrameName($a_side_name) + { + $this->side_frame_name = $a_side_name; + } + + /** + * Set Main Width. + * + * @param string $a_mainwidth Main Width + */ + public function setMainWidth($a_mainwidth) + { + $this->mainwidth = $a_mainwidth; + } + + /** + * Get Main Width. + * + * @return string Main Width + */ + public function getMainWidth() + { + return $this->mainwidth; + } + + /** + * Set Side Width. + * + * @param string $a_sidewidth Side Width + */ + public function setSideWidth($a_sidewidth) + { + $this->sidewidth = $a_sidewidth; + } + + /** + * Get Side Width. + * + * @return string Side Width + */ + public function getSideWidth() + { + return $this->sidewidth; + } + + /** + * Get + */ + public function get() + { + return $this->show(true); + } + + + /** + * Show frameset + */ + public function show($a_get_only = false) + { + $ilSetting = $this->settings; + + if ($ilSetting->get("tree_frame") == "right") { + $main = "LEFT"; + $side = "RIGHT"; + } else { + $main = "RIGHT"; + $side = "LEFT"; + } + + $tpl = new ilTemplate("tpl.frameset.html", true, false); + $tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); + + $tpl->setVariable("PAGETITLE", "- " . ilUtil::stripScriptHTML($this->frameset_title)); + $tpl->setVariable("SRC_" . $main, $this->main_frame_source); + $tpl->setVariable("SRC_" . $side, $this->side_frame_source); + $tpl->setVariable("TITLE_" . $main, $this->main_frame_title); + $tpl->setVariable("TITLE_" . $side, $this->side_frame_title); + $tpl->setVariable("NAME_" . $main, $this->main_frame_name); + $tpl->setVariable("NAME_" . $side, $this->side_frame_name); + $tpl->setVariable("WIDTH_" . $main, $this->getMainWidth()); + $tpl->setVariable("WIDTH_" . $side, $this->getSideWidth()); + if ($ilSetting->get('short_inst_name') != "") { + $tpl->setVariable( + "WINDOW_TITLE", + $ilSetting->get('short_inst_name') + ); + } else { + $tpl->setVariable( + "WINDOW_TITLE", + "ILIAS" + ); + } + + if ($a_get_only) { + return $tpl->get(); + } else { + $tpl->show("DEFAULT", false); + } + } } diff --git a/Services/Help/classes/class.ilHelp.php b/Services/Help/classes/class.ilHelp.php index 3bc240733daf82d8b8e61ca86501db0515519fbe..5906826f5bcbf4e3747dbbd1f60de6c9040d3d0a 100644 --- a/Services/Help/classes/class.ilHelp.php +++ b/Services/Help/classes/class.ilHelp.php @@ -10,273 +10,255 @@ */ class ilHelp { - /** - * Get tooltip for id - * - * @param - * @return - */ - static function getTooltipPresentationText($a_tt_id) - { - global $DIC; + /** + * Get tooltip for id + * + * @param + * @return + */ + public static function getTooltipPresentationText($a_tt_id) + { + global $DIC; - $ilDB = $DIC->database(); - $ilSetting = $DIC->settings(); - $ilUser = $DIC->user(); - - - if ($ilUser->getLanguage() != "de") - { - return ""; - } - - if ($ilSetting->get("help_mode") == "1") - { - return ""; - } - - if (OH_REF_ID > 0) - { - $module_id = 0; - } - else - { - $module_id = (int) $ilSetting->get("help_module"); - if ($module_id == 0) - { - return ""; - } - } - - $set = $ilDB->query("SELECT tt_text FROM help_tooltip ". - " WHERE tt_id = ".$ilDB->quote($a_tt_id, "text"). - " AND module_id = ".$ilDB->quote($module_id, "integer") - ); - $rec = $ilDB->fetchAssoc($set); - if ($rec["tt_text"] != "") - { - $t = $rec["tt_text"]; - if ($module_id == 0) - { - $t.="
                  ".$a_tt_id.""; - } - return $t; - } - else // try to get general version - { - $fu = strpos($a_tt_id, "_"); - $gen_tt_id = "*".substr($a_tt_id, $fu); - $set = $ilDB->query("SELECT tt_text FROM help_tooltip ". - " WHERE tt_id = ".$ilDB->quote($gen_tt_id, "text"). - " AND module_id = ".$ilDB->quote($module_id, "integer") - ); - $rec = $ilDB->fetchAssoc($set); - if ($rec["tt_text"] != "") - { - $t = $rec["tt_text"]; - if ($module_id == 0) - { - $t.="
                  ".$a_tt_id.""; - } - return $t; - } - } - if ($module_id == 0) - { - return "".$a_tt_id.""; - } - return ""; - } + $ilDB = $DIC->database(); + $ilSetting = $DIC->settings(); + $ilUser = $DIC->user(); + + + if ($ilUser->getLanguage() != "de") { + return ""; + } + + if ($ilSetting->get("help_mode") == "1") { + return ""; + } + + if (OH_REF_ID > 0) { + $module_id = 0; + } else { + $module_id = (int) $ilSetting->get("help_module"); + if ($module_id == 0) { + return ""; + } + } + + $set = $ilDB->query( + "SELECT tt_text FROM help_tooltip " . + " WHERE tt_id = " . $ilDB->quote($a_tt_id, "text") . + " AND module_id = " . $ilDB->quote($module_id, "integer") + ); + $rec = $ilDB->fetchAssoc($set); + if ($rec["tt_text"] != "") { + $t = $rec["tt_text"]; + if ($module_id == 0) { + $t.="
                  " . $a_tt_id . ""; + } + return $t; + } else { // try to get general version + $fu = strpos($a_tt_id, "_"); + $gen_tt_id = "*" . substr($a_tt_id, $fu); + $set = $ilDB->query( + "SELECT tt_text FROM help_tooltip " . + " WHERE tt_id = " . $ilDB->quote($gen_tt_id, "text") . + " AND module_id = " . $ilDB->quote($module_id, "integer") + ); + $rec = $ilDB->fetchAssoc($set); + if ($rec["tt_text"] != "") { + $t = $rec["tt_text"]; + if ($module_id == 0) { + $t.="
                  " . $a_tt_id . ""; + } + return $t; + } + } + if ($module_id == 0) { + return "" . $a_tt_id . ""; + } + return ""; + } - /** - * Get object_creation tooltip tab text - * - * @param string $a_tab_id tab id - * @return string tooltip text - */ - static function getObjCreationTooltipText($a_type) - { - return self::getTooltipPresentationText($a_type."_create"); - } + /** + * Get object_creation tooltip tab text + * + * @param string $a_tab_id tab id + * @return string tooltip text + */ + public static function getObjCreationTooltipText($a_type) + { + return self::getTooltipPresentationText($a_type . "_create"); + } - /** - * Get main menu tooltip - * - * @param string $a_mm_id - * @return string tooltip text - */ - static function getMainMenuTooltip($a_item_id) - { - return self::getTooltipPresentationText($a_item_id); - } + /** + * Get main menu tooltip + * + * @param string $a_mm_id + * @return string tooltip text + */ + public static function getMainMenuTooltip($a_item_id) + { + return self::getTooltipPresentationText($a_item_id); + } - - /** - * Get all tooltips - * - * @param - * @return - */ - static function getAllTooltips($a_comp = "", $a_module_id = 0) - { - global $DIC; + + /** + * Get all tooltips + * + * @param + * @return + */ + public static function getAllTooltips($a_comp = "", $a_module_id = 0) + { + global $DIC; - $ilDB = $DIC->database(); - - $q = "SELECT * FROM help_tooltip"; - $q.= " WHERE module_id = ".$ilDB->quote($a_module_id, "integer"); - if ($a_comp != "") - { - $q.= " AND comp = ".$ilDB->quote($a_comp, "text"); - } - $set = $ilDB->query($q); - $tts = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $tts[$rec["id"]] = array("id" => $rec["id"], "text" => $rec["tt_text"], - "tt_id" => $rec["tt_id"]); - } - return $tts; - } - - /** - * Add tooltip - * - * @param - * @return - */ - static function addTooltip($a_tt_id, $a_text, $a_module_id = 0) - { - global $DIC; + $ilDB = $DIC->database(); + + $q = "SELECT * FROM help_tooltip"; + $q.= " WHERE module_id = " . $ilDB->quote($a_module_id, "integer"); + if ($a_comp != "") { + $q.= " AND comp = " . $ilDB->quote($a_comp, "text"); + } + $set = $ilDB->query($q); + $tts = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $tts[$rec["id"]] = array("id" => $rec["id"], "text" => $rec["tt_text"], + "tt_id" => $rec["tt_id"]); + } + return $tts; + } + + /** + * Add tooltip + * + * @param + * @return + */ + public static function addTooltip($a_tt_id, $a_text, $a_module_id = 0) + { + global $DIC; - $ilDB = $DIC->database(); - - $fu = strpos($a_tt_id, "_"); - $comp = substr($a_tt_id, 0, $fu); - - $nid = $ilDB->nextId("help_tooltip"); - $ilDB->manipulate("INSERT INTO help_tooltip ". - "(id, tt_text, tt_id, comp,module_id) VALUES (". - $ilDB->quote($nid, "integer").",". - $ilDB->quote($a_text, "text").",". - $ilDB->quote($a_tt_id, "text").",". - $ilDB->quote($comp, "text").",". - $ilDB->quote($a_module_id, "integer"). - ")"); - } - - /** - * Update tooltip - * - * @param - * @return - */ - static function updateTooltip($a_id, $a_text, $a_tt_id) - { - global $DIC; + $ilDB = $DIC->database(); + + $fu = strpos($a_tt_id, "_"); + $comp = substr($a_tt_id, 0, $fu); + + $nid = $ilDB->nextId("help_tooltip"); + $ilDB->manipulate("INSERT INTO help_tooltip " . + "(id, tt_text, tt_id, comp,module_id) VALUES (" . + $ilDB->quote($nid, "integer") . "," . + $ilDB->quote($a_text, "text") . "," . + $ilDB->quote($a_tt_id, "text") . "," . + $ilDB->quote($comp, "text") . "," . + $ilDB->quote($a_module_id, "integer") . + ")"); + } + + /** + * Update tooltip + * + * @param + * @return + */ + public static function updateTooltip($a_id, $a_text, $a_tt_id) + { + global $DIC; - $ilDB = $DIC->database(); + $ilDB = $DIC->database(); - $fu = strpos($a_tt_id, "_"); - $comp = substr($a_tt_id, 0, $fu); - - $ilDB->manipulate("UPDATE help_tooltip SET ". - " tt_text = ".$ilDB->quote($a_text, "text").", ". - " tt_id = ".$ilDB->quote($a_tt_id, "text").", ". - " comp = ".$ilDB->quote($comp, "text"). - " WHERE id = ".$ilDB->quote($a_id, "integer") - ); - } - - - /** - * Get all tooltip components - * - * @param - * @return - */ - static function getTooltipComponents($a_module_id = 0) - { - global $DIC; + $fu = strpos($a_tt_id, "_"); + $comp = substr($a_tt_id, 0, $fu); + + $ilDB->manipulate( + "UPDATE help_tooltip SET " . + " tt_text = " . $ilDB->quote($a_text, "text") . ", " . + " tt_id = " . $ilDB->quote($a_tt_id, "text") . ", " . + " comp = " . $ilDB->quote($comp, "text") . + " WHERE id = " . $ilDB->quote($a_id, "integer") + ); + } + + + /** + * Get all tooltip components + * + * @param + * @return + */ + public static function getTooltipComponents($a_module_id = 0) + { + global $DIC; - $ilDB = $DIC->database(); - $lng = $DIC->language(); - - $set = $ilDB->query("SELECT DISTINCT comp FROM help_tooltip ". - " WHERE module_id = ".$ilDB->quote($a_module_id, "integer"). - " ORDER BY comp "); - $comps[""] = "- ".$lng->txt("help_all")." -"; - while ($rec = $ilDB->fetchAssoc($set)) - { - $comps[$rec["comp"]] = $rec["comp"]; - } - return $comps; - } - - /** - * Delete tooltip - * - * @param - * @return - */ - static function deleteTooltip($a_id) - { - global $DIC; + $ilDB = $DIC->database(); + $lng = $DIC->language(); + + $set = $ilDB->query("SELECT DISTINCT comp FROM help_tooltip " . + " WHERE module_id = " . $ilDB->quote($a_module_id, "integer") . + " ORDER BY comp "); + $comps[""] = "- " . $lng->txt("help_all") . " -"; + while ($rec = $ilDB->fetchAssoc($set)) { + $comps[$rec["comp"]] = $rec["comp"]; + } + return $comps; + } + + /** + * Delete tooltip + * + * @param + * @return + */ + public static function deleteTooltip($a_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $ilDB->manipulate("DELETE FROM help_tooltip WHERE ". - " id = ".$ilDB->quote($a_id, "integer") - ); - } - - /** - * Delete tooltips of module - * - * @param - * @return - */ - static function deleteTooltipsOfModule($a_id) - { - global $DIC; + $ilDB = $DIC->database(); + + $ilDB->manipulate( + "DELETE FROM help_tooltip WHERE " . + " id = " . $ilDB->quote($a_id, "integer") + ); + } + + /** + * Delete tooltips of module + * + * @param + * @return + */ + public static function deleteTooltipsOfModule($a_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $ilDB->manipulate("DELETE FROM help_tooltip WHERE ". - " module_id = ".$ilDB->quote($a_id, "integer") - ); - - } + $ilDB = $DIC->database(); + + $ilDB->manipulate( + "DELETE FROM help_tooltip WHERE " . + " module_id = " . $ilDB->quote($a_id, "integer") + ); + } - /** - * Get help lm id - * - * @return int help learning module id - */ - static function getHelpLMId() - { - global $DIC; + /** + * Get help lm id + * + * @return int help learning module id + */ + public static function getHelpLMId() + { + global $DIC; - $ilSetting = $DIC->settings(); + $ilSetting = $DIC->settings(); - $lm_id = 0; + $lm_id = 0; - if (OH_REF_ID > 0) - { - $lm_id = ilObject::_lookupObjId(OH_REF_ID); - } - else - { - $hm = (int) $ilSetting->get("help_module"); - if ($hm > 0) - { - include_once("./Services/Help/classes/class.ilObjHelpSettings.php"); - $lm_id = ilObjHelpSettings::lookupModuleLmId($hm); - } - } + if (OH_REF_ID > 0) { + $lm_id = ilObject::_lookupObjId(OH_REF_ID); + } else { + $hm = (int) $ilSetting->get("help_module"); + if ($hm > 0) { + include_once("./Services/Help/classes/class.ilObjHelpSettings.php"); + $lm_id = ilObjHelpSettings::lookupModuleLmId($hm); + } + } - return $lm_id; - } - + return $lm_id; + } } -?> \ No newline at end of file diff --git a/Services/Help/classes/class.ilHelpDataSet.php b/Services/Help/classes/class.ilHelpDataSet.php index 838ebbe34ff548331928b4793a7ce5e0abaa5d21..a1446dfc742127907e759a92707057cc0378a5a5 100644 --- a/Services/Help/classes/class.ilHelpDataSet.php +++ b/Services/Help/classes/class.ilHelpDataSet.php @@ -6,179 +6,169 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); /** * Help system data set class - * + * * @author Alex Killing * @version $Id$ * @ingroup ServicesHelp */ class ilHelpDataSet extends ilDataSet -{ +{ - /** - * Get supported versions - * - * @param - * @return - */ - public function getSupportedVersions() - { - return array("4.3.0"); - } - - /** - * Get xml namespace - * - * @param - * @return - */ - function getXmlNamespace($a_entity, $a_schema_version) - { - return "http://www.ilias.de/xml/Services/Help/".$a_entity; - } - - /** - * Get field types for entity - * - * @param - * @return - */ - protected function getTypes($a_entity, $a_version) - { - if ($a_entity == "help_map") - { - switch ($a_version) - { - case "4.3.0": - return array( - "Chap" => "integer", - "Component" => "text", - "ScreenId" => "text", - "ScreenSubId" => "text", - "Perm" => "text" - ); - } - } + /** + * Get supported versions + * + * @param + * @return + */ + public function getSupportedVersions() + { + return array("4.3.0"); + } + + /** + * Get xml namespace + * + * @param + * @return + */ + public function getXmlNamespace($a_entity, $a_schema_version) + { + return "http://www.ilias.de/xml/Services/Help/" . $a_entity; + } + + /** + * Get field types for entity + * + * @param + * @return + */ + protected function getTypes($a_entity, $a_version) + { + if ($a_entity == "help_map") { + switch ($a_version) { + case "4.3.0": + return array( + "Chap" => "integer", + "Component" => "text", + "ScreenId" => "text", + "ScreenSubId" => "text", + "Perm" => "text" + ); + } + } - if ($a_entity == "help_tooltip") - { - switch ($a_version) - { - case "4.3.0": - return array( - "Id" => "integer", - "TtText" => "text", - "TtId" => "text", - "Comp" => "text", - "Lang" => "text" - ); - } - } + if ($a_entity == "help_tooltip") { + switch ($a_version) { + case "4.3.0": + return array( + "Id" => "integer", + "TtText" => "text", + "TtId" => "text", + "Comp" => "text", + "Lang" => "text" + ); + } + } + } - } + /** + * Read data + * + * @param + * @return + */ + public function readData($a_entity, $a_version, $a_ids, $a_field = "") + { + $ilDB = $this->db; - /** - * Read data - * - * @param - * @return - */ - 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 == "help_map") { + switch ($a_version) { + case "4.3.0": + $this->getDirectDataFromQuery("SELECT chap, component, screen_id, screen_sub_id, perm " . + " FROM help_map " . + "WHERE " . + $ilDB->in("chap", $a_ids, false, "integer")); + break; + } + } + + if ($a_entity == "help_tooltip") { + switch ($a_version) { + case "4.3.0": + $this->getDirectDataFromQuery("SELECT id, tt_text, tt_id, comp, lang FROM help_tooltip"); + break; + } + } + } + + /** + * Determine the dependent sets of data + */ + protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) + { + return false; + } + + + /** + * Import record + * + * @param + * @return + */ + public function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) + { + switch ($a_entity) { + case "help_map": + + include_once("./Services/Help/classes/class.ilHelpMapping.php"); + + // without module ID we do nothing + $module_id = $a_mapping->getMapping('Services/Help', 'help_module', 0); + $t = $a_mapping->getAllMappings(); + if ($module_id) { + $new_chap = $a_mapping->getMapping( + 'Services/Help', + 'help_chap', + $a_rec["Chap"] + ); - if (!is_array($a_ids)) - { - $a_ids = array($a_ids); - } - - if ($a_entity == "help_map") - { - switch ($a_version) - { - case "4.3.0": - $this->getDirectDataFromQuery("SELECT chap, component, screen_id, screen_sub_id, perm ". - " FROM help_map ". - "WHERE ". - $ilDB->in("chap", $a_ids, false, "integer")); - break; - } - } - - if ($a_entity == "help_tooltip") - { - switch ($a_version) - { - case "4.3.0": - $this->getDirectDataFromQuery("SELECT id, tt_text, tt_id, comp, lang FROM help_tooltip"); - break; - } - } + // new import (5.1): get chapter from learning module import mapping + if ($new_chap == 0) { + $new_chap = $a_mapping->getMapping( + 'Modules/LearningModule', + 'lm_tree', + $a_rec["Chap"] + ); + } - } - - /** - * Determine the dependent sets of data - */ - protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) - { - return false; - } - - - /** - * Import record - * - * @param - * @return - */ - function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) - { - switch ($a_entity) - { - case "help_map": - - include_once("./Services/Help/classes/class.ilHelpMapping.php"); - - // without module ID we do nothing - $module_id = $a_mapping->getMapping('Services/Help','help_module', 0); - $t = $a_mapping->getAllMappings(); - if ($module_id) - { - $new_chap = $a_mapping->getMapping('Services/Help', 'help_chap', - $a_rec["Chap"]); - - // new import (5.1): get chapter from learning module import mapping - if ($new_chap == 0) - { - $new_chap = $a_mapping->getMapping('Modules/LearningModule', 'lm_tree', - $a_rec["Chap"]); - } - - if ($new_chap > 0) - { - ilHelpMapping::saveMappingEntry($new_chap, - $a_rec["Component"], - $a_rec["ScreenId"], - $a_rec["ScreenSubId"], - $a_rec["Perm"], - $module_id - ); - } - } - break; - - case "help_tooltip": - - include_once("./Services/Help/classes/class.ilHelp.php"); - - // without module ID we do nothing - $module_id = $a_mapping->getMapping('Services/Help','help_module',0); - if ($module_id) - { - ilHelp::addTooltip($a_rec["TtId"], $a_rec["TtText"], $module_id); - } - break; - } - } + if ($new_chap > 0) { + ilHelpMapping::saveMappingEntry( + $new_chap, + $a_rec["Component"], + $a_rec["ScreenId"], + $a_rec["ScreenSubId"], + $a_rec["Perm"], + $module_id + ); + } + } + break; + + case "help_tooltip": + + include_once("./Services/Help/classes/class.ilHelp.php"); + + // without module ID we do nothing + $module_id = $a_mapping->getMapping('Services/Help', 'help_module', 0); + if ($module_id) { + ilHelp::addTooltip($a_rec["TtId"], $a_rec["TtText"], $module_id); + } + break; + } + } } -?> \ No newline at end of file diff --git a/Services/Help/classes/class.ilHelpExporter.php b/Services/Help/classes/class.ilHelpExporter.php index 5ac7aca89d399e0a2e75549318e01d0e925d62ae..af643cb31e7da008928dd77569a210876f269416 100644 --- a/Services/Help/classes/class.ilHelpExporter.php +++ b/Services/Help/classes/class.ilHelpExporter.php @@ -12,90 +12,84 @@ include_once("./Services/Export/classes/class.ilXmlExporter.php"); */ class ilHelpExporter extends ilXmlExporter { - private $ds; + private $ds; - /** - * Initialisation - */ - function init() - { - include_once("./Services/Help/classes/class.ilHelpDataSet.php"); - $this->ds = new ilHelpDataSet(); - $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); - $this->ds->setDSPrefix("ds"); - } + /** + * Initialisation + */ + public function init() + { + include_once("./Services/Help/classes/class.ilHelpDataSet.php"); + $this->ds = new ilHelpDataSet(); + $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); + $this->ds->setDSPrefix("ds"); + } - /** - * Get tail dependencies - * - * @param string entity - * @param string target release - * @param array ids - * @return array array of array with keys "component", entity", "ids" - */ - function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) - { - if ($a_entity == "help") - { - $lm_node_ids = array(); - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - foreach($a_ids as $lm_id) - { - $chaps = ilLMObject::getObjectList($lm_id, "st"); - foreach ($chaps as $chap) - { - $lm_node_ids[] = $chap["obj_id"]; - } - } + /** + * Get tail dependencies + * + * @param string entity + * @param string target release + * @param array ids + * @return array array of array with keys "component", entity", "ids" + */ + public function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) + { + if ($a_entity == "help") { + $lm_node_ids = array(); + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + foreach ($a_ids as $lm_id) { + $chaps = ilLMObject::getObjectList($lm_id, "st"); + foreach ($chaps as $chap) { + $lm_node_ids[] = $chap["obj_id"]; + } + } - return array ( - array( - "component" => "Services/Help", - "entity" => "help_map", - "ids" => $lm_node_ids), - array( - "component" => "Services/Help", - "entity" => "help_tooltip", - "ids" => $a_ids) - ); - } + return array( + array( + "component" => "Services/Help", + "entity" => "help_map", + "ids" => $lm_node_ids), + array( + "component" => "Services/Help", + "entity" => "help_tooltip", + "ids" => $a_ids) + ); + } - return array(); - } + return array(); + } - /** - * Get xml representation - * - * @param string entity - * @param string target release - * @param string id - * @return string xml string - */ - public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) - { - return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); - } - - /** - * Returns schema versions that the component can export to. - * ILIAS chooses the first one, that has min/max constraints which - * fit to the target release. Please put the newest on top. - * - * @return - */ - function getValidSchemaVersions($a_entity) - { - return array ( - "4.3.0" => array( - "namespace" => "http://www.ilias.de/Services/Help/help/4_3", - "xsd_file" => "ilias_help_4_3.xsd", - "uses_dataset" => true, - "min" => "4.3.0", - "max" => "") - ); - } + /** + * Get xml representation + * + * @param string entity + * @param string target release + * @param string id + * @return string xml string + */ + public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) + { + return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); + } + /** + * Returns schema versions that the component can export to. + * ILIAS chooses the first one, that has min/max constraints which + * fit to the target release. Please put the newest on top. + * + * @return + */ + public function getValidSchemaVersions($a_entity) + { + return array( + "4.3.0" => array( + "namespace" => "http://www.ilias.de/Services/Help/help/4_3", + "xsd_file" => "ilias_help_4_3.xsd", + "uses_dataset" => true, + "min" => "4.3.0", + "max" => "") + ); + } } - -?> \ No newline at end of file diff --git a/Services/Help/classes/class.ilHelpGUI.php b/Services/Help/classes/class.ilHelpGUI.php index 13527b9f37f961f08a56a6877d03691a4d7d2e97..92e69a4ad050cb56b50626205080ce71fa9afe02 100644 --- a/Services/Help/classes/class.ilHelpGUI.php +++ b/Services/Help/classes/class.ilHelpGUI.php @@ -2,7 +2,7 @@ /* Copyright (c) 1998-2011 ILIAS open source, Extended GPL, see docs/LICENSE */ -include_once ("Services/Help/classes/class.ilHelp.php"); +include_once("Services/Help/classes/class.ilHelp.php"); /** * Help GUI class. @@ -15,558 +15,545 @@ include_once ("Services/Help/classes/class.ilHelp.php"); */ class ilHelpGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilSetting - */ - protected $settings; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilObjUser - */ - protected $user; - - var $help_sections = array(); - const ID_PART_SCREEN = "screen"; - const ID_PART_SUB_SCREEN = "sub_screen"; - const ID_PART_COMPONENT = "component"; - var $def_screen_id = array(); - var $screen_id = array(); - - /** - * constructor - */ - function __construct() - { - global $DIC; - - $this->settings = $DIC->settings(); - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - $ilCtrl = $DIC->ctrl(); - - $this->ctrl = $ilCtrl; - } - - /** - * Set default screen id - * - * @param - * @return - */ - function setDefaultScreenId($a_part, $a_id) - { - $this->def_screen_id[$a_part] = $a_id; - } - - /** - * Set screen id - * - * @param - */ - function setScreenId($a_id) - { - $this->screen_id[self::ID_PART_SCREEN] = $a_id; - } - - /** - * Set sub screen id - * - * @param - */ - function setSubScreenId($a_id) - { - $this->screen_id[self::ID_PART_SUB_SCREEN] = $a_id; - } - - /** - * Set screen id component - * - * @param - * @return - */ - function setScreenIdComponent($a_comp) - { - $this->screen_id_component = $a_comp; - } - - - /** - * Get screen id - * - * @param - * @return - */ - function getScreenId() - { - $comp = ($this->screen_id_component != "") - ? $this->screen_id_component - : $this->def_screen_id[self::ID_PART_COMPONENT]; - - if ($comp == "") - { - return ""; - } - - $scr_id = ($this->screen_id[self::ID_PART_SCREEN] != "") - ? $this->screen_id[self::ID_PART_SCREEN] - : $this->def_screen_id[self::ID_PART_SCREEN]; - - $sub_scr_id = ($this->screen_id[self::ID_PART_SUB_SCREEN] != "") - ? $this->screen_id[self::ID_PART_SUB_SCREEN] - : $this->def_screen_id[self::ID_PART_SUB_SCREEN]; - - $screen_id = $comp."/". - $scr_id."/". - $sub_scr_id; - - return $screen_id; - } - - - /** - * Add help section - * - * @param - * @return - */ - function addHelpSection($a_help_id, $a_level = 1) - { - $this->help_sections[] = array("help_id" => $a_help_id, $a_level); - } - - /** - * Has sections? - * - * @param - * @return - */ - function hasSections() - { - $ilSetting = $this->settings; - - include_once("./Services/Help/classes/class.ilHelpMapping.php"); - return ilHelpMapping::hasScreenIdSections($this->getScreenId()); - } - - /** - * Get help sections - * - * @param - * @return - */ - function getHelpSections() - { - include_once("./Services/Help/classes/class.ilHelpMapping.php"); - return ilHelpMapping::getHelpSectionsForId($this->getScreenId(), (int) $_GET["ref_id"]); - } - - /** - * Get help section url parameter - * - * @param - * @return - */ - function setCtrlPar() - { - $ilCtrl = $this->ctrl; - - /*$h_ids = $sep = ""; - foreach ($this->getHelpSections() as $hs) - { - $h_ids.= $sep.$hs; - $sep = ","; - }*/ - $ilCtrl->setParameterByClass("ilhelpgui", "help_screen_id", $this->getScreenId().".".$_GET["ref_id"]); - } - - - /** - * execute command - */ - function executeCommand() - { - $cmd = $this->ctrl->getCmd("showHelp"); - $next_class = $this->ctrl->getNextClass($this); - - switch($next_class) - { - default: - return $this->$cmd(); - break; - } - } - - /** - * Show online help - */ - function showHelp() - { - $lng = $this->lng; - - if ($_GET["help_screen_id"] != "") - { - ilSession::set("help_screen_id", $_GET["help_screen_id"]); - $help_screen_id = $_GET["help_screen_id"]; - } - else - { - $help_screen_id = ilSession::get("help_screen_id"); - } - - ilSession::set("help_search_term", ""); - - $this->resetCurrentPage(); - - $id_arr = explode(".", $help_screen_id); - include_once("./Services/Help/classes/class.ilHelpMapping.php"); - include_once("./Services/Help/classes/class.ilHelp.php"); - - $help_arr = ilHelpMapping::getHelpSectionsForId($id_arr[0], $id_arr[1]); - $oh_lm_id = ilHelp::getHelpLMId(); - - if ($oh_lm_id > 0 && count($help_arr) > 0) - { - include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); - $acc = new ilAccordionGUI(); - $acc->setId("oh_acc_".$h_id); - $acc->setUseSessionStorage(true); - $acc->setBehaviour(ilAccordionGUI::FIRST_OPEN); - - foreach ($help_arr as $h_id) - { - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - $st_id = $h_id; - - if (!ilLMObject::_exists($st_id)) - { - continue; - } - - $pages = ilLMObject::getPagesOfChapter($oh_lm_id, $st_id); - include_once("./Services/UIComponent/GroupedList/classes/class.ilGroupedListGUI.php"); - $grp_list = new ilGroupedListGUI(); - foreach ($pages as $pg) - { - $grp_list->addEntry(ilLMObject::_lookupTitle($pg["child"]), "#", "", - "return il.Help.showPage(".$pg["child"].");"); - } - - $acc->addItem(ilLMObject::_lookupTitle($st_id), $grp_list->getHTML()); - } - $h_tpl = new ilTemplate("tpl.help.html", true, true, "Services/Help"); - $h_tpl->setVariable("HEAD", $lng->txt("help")); - - $h_tpl->setCurrentBlock("search"); - include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); - $h_tpl->setVariable("GL_SEARCH", ilGlyphGUI::get(ilGlyphGUI::SEARCH)); - $h_tpl->parseCurrentBlock(); - - $h_tpl->setVariable("CONTENT", $acc->getHTML()); - include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); - $h_tpl->setVariable("CLOSE_IMG", ilGlyphGUI::get(ilGlyphGUI::CLOSE)); - echo $h_tpl->get(); - } - exit; - } - - /** - * Show page - * - * @param - * @return - */ - function showPage() - { - $lng = $this->lng; - - $page_id = (int) $_GET["help_page"]; - - $h_tpl = new ilTemplate("tpl.help.html", true, true, "Services/Help"); - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - - - $h_tpl->setCurrentBlock("backlink"); - $h_tpl->setVariable("TXT_BACK", $lng->txt("back")); - if (($t =ilSession::get("help_search_term")) != "") - { - $h_tpl->setVariable("ONCLICK_BACK", - "return il.Help.search('".ilUtil::prepareFormOutput($t)."');"); - } - else - { - $h_tpl->setVariable("ONCLICK_BACK", - "return il.Help.listHelp(event, true);"); - } - $h_tpl->parseCurrentBlock(); - - - $h_tpl->setVariable("HEAD", $lng->txt("help")." - ". - ilLMObject::_lookupTitle($page_id)); - - include_once("./Services/COPage/classes/class.ilPageUtil.php"); - if (!ilPageUtil::_existsAndNotEmpty("lm", $page_id)) - { - exit; - } - include_once("./Services/COPage/classes/class.ilPageObject.php"); - include_once("./Services/COPage/classes/class.ilPageObjectGUI.php"); - - // get page object - include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); - include_once("./Modules/LearningModule/classes/class.ilLMPageGUI.php"); - $page_gui = new ilLMPageGUI($page_id); - $cfg = $page_gui->getPageConfig(); - $page_gui->setPresentationTitle(""); - $page_gui->setTemplateOutput(false); - $page_gui->setHeader(""); - $page_gui->setRawPageContent(true); - $cfg->setEnablePCType("Map", false); - $cfg->setEnablePCType("Tabs", false); - $cfg->setEnablePCType("FileList", false); - - $page_gui->getPageObject()->buildDom(); - $int_links = $page_gui->getPageObject()->getInternalLinks(); - $link_xml = $this->getLinkXML($int_links); - $link_xml.= $this->getLinkTargetsXML(); -//echo htmlentities($link_xml); - $page_gui->setLinkXML($link_xml); - - $ret = $page_gui->showPage(); - - $h_tpl->setVariable("CONTENT", $ret); - include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); - $h_tpl->setVariable("CLOSE_IMG", ilGlyphGUI::get(ilGlyphGUI::CLOSE)); - - ilSession::set("help_pg", $page_id); - - $page = $h_tpl->get(); - - // replace style classes - //$page = str_replace("ilc_text_inline_Strong", "ilHelpStrong", $page); - - echo $page; - exit; - } - - /** - * Hide help - * - * @param - * @return - */ - function resetCurrentPage() - { - ilSession::clear("help_pg"); - } - - - /** - * Get tab tooltip text - * - * @param string $a_tab_id tab id - * @return string tooltip text - */ - function getTabTooltipText($a_tab_id) - { - $lng = $this->lng; - - include_once("./Services/Help/classes/class.ilHelp.php"); - if ($this->screen_id_component != "") - { - return ilHelp::getTooltipPresentationText($this->screen_id_component."_".$a_tab_id); - //return $lng->txt("help_tt_".$this->screen_id_component."_".$a_tab_id); - } - return ""; - } - - /** - * Render current help page - * - * @param - * @return - */ - static function initHelp($a_tpl) - { - global $DIC; - - $ilUser = $DIC->user(); - $ilSetting = $DIC->settings(); - - $module_id = (int) $ilSetting->get("help_module"); - - if ((OH_REF_ID > 0 || $module_id > 0) && $ilUser->getLanguage() == "de") - { - if (ilSession::get("help_pg") > 0) - { - $a_tpl->addOnLoadCode("il.Help.showCurrentPage(".ilSession::get("help_pg").");", 3); - } - $a_tpl->addJavascript("./Services/Help/js/ilHelp.js"); - if ($ilUser->getPref("hide_help_tt")) - { - $a_tpl->addOnLoadCode("if (il && il.Help) {il.Help.switchTooltips();}", 3); - } - } - } - - /** - * Deactivate tooltips - * - * @param - * @return - */ - function deactivateTooltips() - { - $ilUser = $this->user; - - $ilUser->writePref("hide_help_tt", "1"); - } - - /** - * Activate tooltips - * - * @param - * @return - */ - function activateTooltips() - { - $ilUser = $this->user; - - $ilUser->writePref("hide_help_tt", "0"); - } - - /** - * get xml for links - */ - function getLinkXML($a_int_links) - { - $ilCtrl = $this->ctrl; - - $link_info = ""; - foreach ($a_int_links as $int_link) - { - $target = $int_link["Target"]; - if (substr($target, 0, 4) == "il__") - { - $target_arr = explode("_", $target); - $target_id = $target_arr[count($target_arr) - 1]; - $type = $int_link["Type"]; - $targetframe = "None"; - - // anchor - $anc = $anc_add = ""; - if ($int_link["Anchor"] != "") - { - $anc = $int_link["Anchor"]; - $anc_add = "_".rawurlencode($int_link["Anchor"]); - } - - switch($type) - { - case "PageObject": - case "StructureObject": - if ($type == "PageObject") - { - $href = "#pg_".$target_id; - } - else - { - $href = "#"; - } - break; - - } - - $link_info.=""; - } - } - $link_info.= ""; - - return $link_info; - } - - /** - * Get XMl for Link Targets - */ - function getLinkTargetsXML() - { - $link_info = ""; - $link_info.=""; - $link_info.= ""; - return $link_info; - } - - /** - * Search - * - * @param - * @return - */ - function search() - { - $lng = $this->lng; - - $term = $_GET["term"]; - - if ($term == "") - { - $term = ilSession::get("help_search_term"); - } - - $this->resetCurrentPage(); - - $h_tpl = new ilTemplate("tpl.help.html", true, true, "Services/Help"); - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - - $h_tpl->setCurrentBlock("backlink"); - $h_tpl->setVariable("TXT_BACK", $lng->txt("back")); - $h_tpl->setVariable("ONCLICK_BACK", - "return il.Help.listHelp(event, true);"); - $h_tpl->parseCurrentBlock(); - - - $h_tpl->setVariable("HEAD", $lng->txt("help")." - ". - $lng->txt("search_result")); - - $h_tpl->setCurrentBlock("search"); - include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); - $h_tpl->setVariable("GL_SEARCH", ilGlyphGUI::get(ilGlyphGUI::SEARCH)); - $h_tpl->setVariable("VAL_SEARCH", ilUtil::prepareFormOutput($term)); - $h_tpl->parseCurrentBlock(); - - include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); - $h_tpl->setVariable("CLOSE_IMG", ilGlyphGUI::get(ilGlyphGUI::CLOSE)); - - $lm_id = ilHelp::getHelpLMId(); - include_once("./Services/Search/classes/class.ilRepositoryObjectDetailSearch.php"); - $s = new ilRepositoryObjectDetailSearch($lm_id); - $s->setQueryString($term); - $result = $s->performSearch(); - - include_once("./Services/UIComponent/GroupedList/classes/class.ilGroupedListGUI.php"); - $grp_list = new ilGroupedListGUI(); - foreach ($result->getResults() as $r) - { - $grp_list->addEntry(ilLMObject::_lookupTitle($r["item_id"]), "#", "", - "return il.Help.showPage(".$r["item_id"].");"); - } - $h_tpl->setVariable("CONTENT", $grp_list->getHTML()); - - ilSession::set("help_search_term", $term); - - echo $h_tpl->get();; - exit; - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilObjUser + */ + protected $user; + + public $help_sections = array(); + const ID_PART_SCREEN = "screen"; + const ID_PART_SUB_SCREEN = "sub_screen"; + const ID_PART_COMPONENT = "component"; + public $def_screen_id = array(); + public $screen_id = array(); + + /** + * constructor + */ + public function __construct() + { + global $DIC; + + $this->settings = $DIC->settings(); + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + $ilCtrl = $DIC->ctrl(); + + $this->ctrl = $ilCtrl; + } + + /** + * Set default screen id + * + * @param + * @return + */ + public function setDefaultScreenId($a_part, $a_id) + { + $this->def_screen_id[$a_part] = $a_id; + } + + /** + * Set screen id + * + * @param + */ + public function setScreenId($a_id) + { + $this->screen_id[self::ID_PART_SCREEN] = $a_id; + } + + /** + * Set sub screen id + * + * @param + */ + public function setSubScreenId($a_id) + { + $this->screen_id[self::ID_PART_SUB_SCREEN] = $a_id; + } + + /** + * Set screen id component + * + * @param + * @return + */ + public function setScreenIdComponent($a_comp) + { + $this->screen_id_component = $a_comp; + } + + + /** + * Get screen id + * + * @param + * @return + */ + public function getScreenId() + { + $comp = ($this->screen_id_component != "") + ? $this->screen_id_component + : $this->def_screen_id[self::ID_PART_COMPONENT]; + + if ($comp == "") { + return ""; + } + + $scr_id = ($this->screen_id[self::ID_PART_SCREEN] != "") + ? $this->screen_id[self::ID_PART_SCREEN] + : $this->def_screen_id[self::ID_PART_SCREEN]; + + $sub_scr_id = ($this->screen_id[self::ID_PART_SUB_SCREEN] != "") + ? $this->screen_id[self::ID_PART_SUB_SCREEN] + : $this->def_screen_id[self::ID_PART_SUB_SCREEN]; + + $screen_id = $comp . "/" . + $scr_id . "/" . + $sub_scr_id; + + return $screen_id; + } + + + /** + * Add help section + * + * @param + * @return + */ + public function addHelpSection($a_help_id, $a_level = 1) + { + $this->help_sections[] = array("help_id" => $a_help_id, $a_level); + } + + /** + * Has sections? + * + * @param + * @return + */ + public function hasSections() + { + $ilSetting = $this->settings; + + include_once("./Services/Help/classes/class.ilHelpMapping.php"); + return ilHelpMapping::hasScreenIdSections($this->getScreenId()); + } + + /** + * Get help sections + * + * @param + * @return + */ + public function getHelpSections() + { + include_once("./Services/Help/classes/class.ilHelpMapping.php"); + return ilHelpMapping::getHelpSectionsForId($this->getScreenId(), (int) $_GET["ref_id"]); + } + + /** + * Get help section url parameter + * + * @param + * @return + */ + public function setCtrlPar() + { + $ilCtrl = $this->ctrl; + + /*$h_ids = $sep = ""; + foreach ($this->getHelpSections() as $hs) + { + $h_ids.= $sep.$hs; + $sep = ","; + }*/ + $ilCtrl->setParameterByClass("ilhelpgui", "help_screen_id", $this->getScreenId() . "." . $_GET["ref_id"]); + } + + + /** + * execute command + */ + public function executeCommand() + { + $cmd = $this->ctrl->getCmd("showHelp"); + $next_class = $this->ctrl->getNextClass($this); + + switch ($next_class) { + default: + return $this->$cmd(); + break; + } + } + + /** + * Show online help + */ + public function showHelp() + { + $lng = $this->lng; + + if ($_GET["help_screen_id"] != "") { + ilSession::set("help_screen_id", $_GET["help_screen_id"]); + $help_screen_id = $_GET["help_screen_id"]; + } else { + $help_screen_id = ilSession::get("help_screen_id"); + } + + ilSession::set("help_search_term", ""); + + $this->resetCurrentPage(); + + $id_arr = explode(".", $help_screen_id); + include_once("./Services/Help/classes/class.ilHelpMapping.php"); + include_once("./Services/Help/classes/class.ilHelp.php"); + + $help_arr = ilHelpMapping::getHelpSectionsForId($id_arr[0], $id_arr[1]); + $oh_lm_id = ilHelp::getHelpLMId(); + + if ($oh_lm_id > 0 && count($help_arr) > 0) { + include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); + $acc = new ilAccordionGUI(); + $acc->setId("oh_acc_" . $h_id); + $acc->setUseSessionStorage(true); + $acc->setBehaviour(ilAccordionGUI::FIRST_OPEN); + + foreach ($help_arr as $h_id) { + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + $st_id = $h_id; + + if (!ilLMObject::_exists($st_id)) { + continue; + } + + $pages = ilLMObject::getPagesOfChapter($oh_lm_id, $st_id); + include_once("./Services/UIComponent/GroupedList/classes/class.ilGroupedListGUI.php"); + $grp_list = new ilGroupedListGUI(); + foreach ($pages as $pg) { + $grp_list->addEntry( + ilLMObject::_lookupTitle($pg["child"]), + "#", + "", + "return il.Help.showPage(" . $pg["child"] . ");" + ); + } + + $acc->addItem(ilLMObject::_lookupTitle($st_id), $grp_list->getHTML()); + } + $h_tpl = new ilTemplate("tpl.help.html", true, true, "Services/Help"); + $h_tpl->setVariable("HEAD", $lng->txt("help")); + + $h_tpl->setCurrentBlock("search"); + include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); + $h_tpl->setVariable("GL_SEARCH", ilGlyphGUI::get(ilGlyphGUI::SEARCH)); + $h_tpl->parseCurrentBlock(); + + $h_tpl->setVariable("CONTENT", $acc->getHTML()); + include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); + $h_tpl->setVariable("CLOSE_IMG", ilGlyphGUI::get(ilGlyphGUI::CLOSE)); + echo $h_tpl->get(); + } + exit; + } + + /** + * Show page + * + * @param + * @return + */ + public function showPage() + { + $lng = $this->lng; + + $page_id = (int) $_GET["help_page"]; + + $h_tpl = new ilTemplate("tpl.help.html", true, true, "Services/Help"); + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + + + $h_tpl->setCurrentBlock("backlink"); + $h_tpl->setVariable("TXT_BACK", $lng->txt("back")); + if (($t =ilSession::get("help_search_term")) != "") { + $h_tpl->setVariable( + "ONCLICK_BACK", + "return il.Help.search('" . ilUtil::prepareFormOutput($t) . "');" + ); + } else { + $h_tpl->setVariable( + "ONCLICK_BACK", + "return il.Help.listHelp(event, true);" + ); + } + $h_tpl->parseCurrentBlock(); + + + $h_tpl->setVariable("HEAD", $lng->txt("help") . " - " . + ilLMObject::_lookupTitle($page_id)); + + include_once("./Services/COPage/classes/class.ilPageUtil.php"); + if (!ilPageUtil::_existsAndNotEmpty("lm", $page_id)) { + exit; + } + include_once("./Services/COPage/classes/class.ilPageObject.php"); + include_once("./Services/COPage/classes/class.ilPageObjectGUI.php"); + + // get page object + include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); + include_once("./Modules/LearningModule/classes/class.ilLMPageGUI.php"); + $page_gui = new ilLMPageGUI($page_id); + $cfg = $page_gui->getPageConfig(); + $page_gui->setPresentationTitle(""); + $page_gui->setTemplateOutput(false); + $page_gui->setHeader(""); + $page_gui->setRawPageContent(true); + $cfg->setEnablePCType("Map", false); + $cfg->setEnablePCType("Tabs", false); + $cfg->setEnablePCType("FileList", false); + + $page_gui->getPageObject()->buildDom(); + $int_links = $page_gui->getPageObject()->getInternalLinks(); + $link_xml = $this->getLinkXML($int_links); + $link_xml.= $this->getLinkTargetsXML(); + //echo htmlentities($link_xml); + $page_gui->setLinkXML($link_xml); + + $ret = $page_gui->showPage(); + + $h_tpl->setVariable("CONTENT", $ret); + include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); + $h_tpl->setVariable("CLOSE_IMG", ilGlyphGUI::get(ilGlyphGUI::CLOSE)); + + ilSession::set("help_pg", $page_id); + + $page = $h_tpl->get(); + + // replace style classes + //$page = str_replace("ilc_text_inline_Strong", "ilHelpStrong", $page); + + echo $page; + exit; + } + + /** + * Hide help + * + * @param + * @return + */ + public function resetCurrentPage() + { + ilSession::clear("help_pg"); + } + + + /** + * Get tab tooltip text + * + * @param string $a_tab_id tab id + * @return string tooltip text + */ + public function getTabTooltipText($a_tab_id) + { + $lng = $this->lng; + + include_once("./Services/Help/classes/class.ilHelp.php"); + if ($this->screen_id_component != "") { + return ilHelp::getTooltipPresentationText($this->screen_id_component . "_" . $a_tab_id); + //return $lng->txt("help_tt_".$this->screen_id_component."_".$a_tab_id); + } + return ""; + } + + /** + * Render current help page + * + * @param + * @return + */ + public static function initHelp($a_tpl) + { + global $DIC; + + $ilUser = $DIC->user(); + $ilSetting = $DIC->settings(); + + $module_id = (int) $ilSetting->get("help_module"); + + if ((OH_REF_ID > 0 || $module_id > 0) && $ilUser->getLanguage() == "de") { + if (ilSession::get("help_pg") > 0) { + $a_tpl->addOnLoadCode("il.Help.showCurrentPage(" . ilSession::get("help_pg") . ");", 3); + } + $a_tpl->addJavascript("./Services/Help/js/ilHelp.js"); + if ($ilUser->getPref("hide_help_tt")) { + $a_tpl->addOnLoadCode("if (il && il.Help) {il.Help.switchTooltips();}", 3); + } + } + } + + /** + * Deactivate tooltips + * + * @param + * @return + */ + public function deactivateTooltips() + { + $ilUser = $this->user; + + $ilUser->writePref("hide_help_tt", "1"); + } + + /** + * Activate tooltips + * + * @param + * @return + */ + public function activateTooltips() + { + $ilUser = $this->user; + + $ilUser->writePref("hide_help_tt", "0"); + } + + /** + * get xml for links + */ + public function getLinkXML($a_int_links) + { + $ilCtrl = $this->ctrl; + + $link_info = ""; + foreach ($a_int_links as $int_link) { + $target = $int_link["Target"]; + if (substr($target, 0, 4) == "il__") { + $target_arr = explode("_", $target); + $target_id = $target_arr[count($target_arr) - 1]; + $type = $int_link["Type"]; + $targetframe = "None"; + + // anchor + $anc = $anc_add = ""; + if ($int_link["Anchor"] != "") { + $anc = $int_link["Anchor"]; + $anc_add = "_" . rawurlencode($int_link["Anchor"]); + } + + switch ($type) { + case "PageObject": + case "StructureObject": + if ($type == "PageObject") { + $href = "#pg_" . $target_id; + } else { + $href = "#"; + } + break; + + } + + $link_info.=""; + } + } + $link_info.= ""; + + return $link_info; + } + + /** + * Get XMl for Link Targets + */ + public function getLinkTargetsXML() + { + $link_info = ""; + $link_info.=""; + $link_info.= ""; + return $link_info; + } + + /** + * Search + * + * @param + * @return + */ + public function search() + { + $lng = $this->lng; + + $term = $_GET["term"]; + + if ($term == "") { + $term = ilSession::get("help_search_term"); + } + + $this->resetCurrentPage(); + + $h_tpl = new ilTemplate("tpl.help.html", true, true, "Services/Help"); + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + + $h_tpl->setCurrentBlock("backlink"); + $h_tpl->setVariable("TXT_BACK", $lng->txt("back")); + $h_tpl->setVariable( + "ONCLICK_BACK", + "return il.Help.listHelp(event, true);" + ); + $h_tpl->parseCurrentBlock(); + + + $h_tpl->setVariable("HEAD", $lng->txt("help") . " - " . + $lng->txt("search_result")); + + $h_tpl->setCurrentBlock("search"); + include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); + $h_tpl->setVariable("GL_SEARCH", ilGlyphGUI::get(ilGlyphGUI::SEARCH)); + $h_tpl->setVariable("VAL_SEARCH", ilUtil::prepareFormOutput($term)); + $h_tpl->parseCurrentBlock(); + + include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); + $h_tpl->setVariable("CLOSE_IMG", ilGlyphGUI::get(ilGlyphGUI::CLOSE)); + + $lm_id = ilHelp::getHelpLMId(); + include_once("./Services/Search/classes/class.ilRepositoryObjectDetailSearch.php"); + $s = new ilRepositoryObjectDetailSearch($lm_id); + $s->setQueryString($term); + $result = $s->performSearch(); + + include_once("./Services/UIComponent/GroupedList/classes/class.ilGroupedListGUI.php"); + $grp_list = new ilGroupedListGUI(); + foreach ($result->getResults() as $r) { + $grp_list->addEntry( + ilLMObject::_lookupTitle($r["item_id"]), + "#", + "", + "return il.Help.showPage(" . $r["item_id"] . ");" + ); + } + $h_tpl->setVariable("CONTENT", $grp_list->getHTML()); + + ilSession::set("help_search_term", $term); + + echo $h_tpl->get(); + ; + exit; + } } -?> \ No newline at end of file diff --git a/Services/Help/classes/class.ilHelpImportConfig.php b/Services/Help/classes/class.ilHelpImportConfig.php index 43434526c10f2f7b227140cfd653766769732f19..4340da818c05208628853f9bdb7dabd3d5f095fd 100644 --- a/Services/Help/classes/class.ilHelpImportConfig.php +++ b/Services/Help/classes/class.ilHelpImportConfig.php @@ -12,27 +12,25 @@ include_once("./Services/Export/classes/class.ilImportConfig.php"); */ class ilHelpImportConfig extends ilImportConfig { - protected $module_id = 0; + protected $module_id = 0; - /** - * Set module id - * - * @param int $a_val module id - */ - function setModuleId($a_val) - { - $this->module_id = $a_val; - } + /** + * Set module id + * + * @param int $a_val module id + */ + public function setModuleId($a_val) + { + $this->module_id = $a_val; + } - /** - * Get module id - * - * @return int module id - */ - function getModuleId() - { - return $this->module_id; - } + /** + * Get module id + * + * @return int module id + */ + public function getModuleId() + { + return $this->module_id; + } } - -?> \ No newline at end of file diff --git a/Services/Help/classes/class.ilHelpImporter.php b/Services/Help/classes/class.ilHelpImporter.php index 6e56610d7c60c1906ceee93c268ebe469a07981e..892103b6b8185fcd478b775405687a402dfcb92c 100644 --- a/Services/Help/classes/class.ilHelpImporter.php +++ b/Services/Help/classes/class.ilHelpImporter.php @@ -12,51 +12,53 @@ include_once("./Services/Export/classes/class.ilXmlImporter.php"); */ class ilHelpImporter extends ilXmlImporter { - /** - * ilHelpImporterConfig - */ - protected $config = null; + /** + * ilHelpImporterConfig + */ + protected $config = null; - /** - * Initialisation - */ - function init() - { - include_once("./Services/Help/classes/class.ilHelpDataSet.php"); - $this->ds = new ilHelpDataSet(); - $this->ds->setDSPrefix("ds"); + /** + * Initialisation + */ + public function init() + { + include_once("./Services/Help/classes/class.ilHelpDataSet.php"); + $this->ds = new ilHelpDataSet(); + $this->ds->setDSPrefix("ds"); - $this->config = $this->getImport()->getConfig("Services/Help"); - $module_id = $this->config->getModuleId(); - if ($module_id > 0) - { - include_once("./Services/Export/classes/class.ilImport.php"); - $this->getImport()->getMapping()->addMapping('Services/Help', 'help_module', 0, $module_id); - /* not needed anymore, we now get mapping from learning module - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - $chaps = ilLMObject::getObjectList($this->getId(), "st"); - foreach ($chaps as $chap) - { - $chap_arr = explode("_", $chap["import_id"]); - $imp->getMapping()->addMapping('Services/Help', 'help_chap', - $chap_arr[count($chap_arr) - 1], $chap["obj_id"]); - }*/ - } - } + $this->config = $this->getImport()->getConfig("Services/Help"); + $module_id = $this->config->getModuleId(); + if ($module_id > 0) { + include_once("./Services/Export/classes/class.ilImport.php"); + $this->getImport()->getMapping()->addMapping('Services/Help', 'help_module', 0, $module_id); + /* not needed anymore, we now get mapping from learning module + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + $chaps = ilLMObject::getObjectList($this->getId(), "st"); + foreach ($chaps as $chap) + { + $chap_arr = explode("_", $chap["import_id"]); + $imp->getMapping()->addMapping('Services/Help', 'help_chap', + $chap_arr[count($chap_arr) - 1], $chap["obj_id"]); + }*/ + } + } - /** - * Import XML - * - * @param - * @return - */ - function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) - { - include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); - $parser = new ilDataSetImportParser($a_entity, $this->getSchemaVersion(), - $a_xml, $this->ds, $a_mapping); - } + /** + * Import XML + * + * @param + * @return + */ + public function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) + { + include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); + $parser = new ilDataSetImportParser( + $a_entity, + $this->getSchemaVersion(), + $a_xml, + $this->ds, + $a_mapping + ); + } } - -?> \ No newline at end of file diff --git a/Services/Help/classes/class.ilHelpMapping.php b/Services/Help/classes/class.ilHelpMapping.php index 87c2af60a05e9ea5feebbda08174b66adacf24cc..4a93cc2353a2914112762c52ab6bb2f7e69d494b 100644 --- a/Services/Help/classes/class.ilHelpMapping.php +++ b/Services/Help/classes/class.ilHelpMapping.php @@ -3,361 +3,325 @@ /* Copyright (c) 1998-2011 ILIAS open source, Extended GPL, see docs/LICENSE */ /** - * Help mapping + * Help mapping * * @author Alex Killing * @version $Id$ - * @ingroup + * @ingroup */ class ilHelpMapping { - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; - /** - * Constructor - */ - function __construct() - { - global $DIC; + /** + * Constructor + */ + public function __construct() + { + global $DIC; - $this->db = $DIC->database(); - } + $this->db = $DIC->database(); + } - /** - * Save screen ids for chapter - * - * @param - * @return - */ - static function saveScreenIdsForChapter($a_chap, $a_ids) - { - global $DIC; + /** + * Save screen ids for chapter + * + * @param + * @return + */ + public static function saveScreenIdsForChapter($a_chap, $a_ids) + { + global $DIC; - $ilDB = $DIC->database(); - - self::removeScreenIdsOfChapter($a_chap); - if (is_array($a_ids)) - { - foreach ($a_ids as $id) - { - $id = trim($id); - $id = explode("/", $id); - if ($id[0] != "") - { - if ($id[1] == "") - { - $id[1] = "-"; - } - $id2 = explode("#", $id[2]); - if ($id2[0] == "") - { - $id2[0] = "-"; - } - if ($id2[1] == "") - { - $id2[1] = "-"; - } - $ilDB->replace("help_map", - array("chap" => array("integer", $a_chap), - "component" => array("text", $id[0]), - "screen_id" => array("text", $id[1]), - "screen_sub_id" => array("text", $id2[0]), - "perm" => array("text", $id2[1]), - "module_id" => array("integer", 0) - ), - array() - ); - } - } - } - } - - /** - * Save mapping entry - * - * @param - * @return - */ - static function saveMappingEntry($a_chap, $a_comp, $a_screen_id, - $a_screen_sub_id, $a_perm, $a_module_id = 0) - { - global $DIC; + $ilDB = $DIC->database(); + + self::removeScreenIdsOfChapter($a_chap); + if (is_array($a_ids)) { + foreach ($a_ids as $id) { + $id = trim($id); + $id = explode("/", $id); + if ($id[0] != "") { + if ($id[1] == "") { + $id[1] = "-"; + } + $id2 = explode("#", $id[2]); + if ($id2[0] == "") { + $id2[0] = "-"; + } + if ($id2[1] == "") { + $id2[1] = "-"; + } + $ilDB->replace( + "help_map", + array("chap" => array("integer", $a_chap), + "component" => array("text", $id[0]), + "screen_id" => array("text", $id[1]), + "screen_sub_id" => array("text", $id2[0]), + "perm" => array("text", $id2[1]), + "module_id" => array("integer", 0) + ), + array() + ); + } + } + } + } + + /** + * Save mapping entry + * + * @param + * @return + */ + public static function saveMappingEntry( + $a_chap, + $a_comp, + $a_screen_id, + $a_screen_sub_id, + $a_perm, + $a_module_id = 0 + ) { + global $DIC; - $ilDB = $DIC->database(); - - $ilDB->replace("help_map", - array("chap" => array("integer", $a_chap), - "component" => array("text", $a_comp), - "screen_id" => array("text", $a_screen_id), - "screen_sub_id" => array("text", $a_screen_sub_id), - "perm" => array("text", $a_perm), - "module_id" => array("integer", $a_module_id) - ), - array() - ); - } - - - /** - * Remove screen ids of chapter - * - * @param - * @return - */ - static function removeScreenIdsOfChapter($a_chap, $a_module_id = 0) - { - global $DIC; + $ilDB = $DIC->database(); + + $ilDB->replace( + "help_map", + array("chap" => array("integer", $a_chap), + "component" => array("text", $a_comp), + "screen_id" => array("text", $a_screen_id), + "screen_sub_id" => array("text", $a_screen_sub_id), + "perm" => array("text", $a_perm), + "module_id" => array("integer", $a_module_id) + ), + array() + ); + } + + + /** + * Remove screen ids of chapter + * + * @param + * @return + */ + public static function removeScreenIdsOfChapter($a_chap, $a_module_id = 0) + { + global $DIC; - $ilDB = $DIC->database(); - - $ilDB->manipulate("DELETE FROM help_map WHERE ". - " chap = ".$ilDB->quote($a_chap, "integer"). - " AND module_id = ".$ilDB->quote($a_module_id, "integer") - ); - } - - /** - * Get screen ids of chapter - * - * @param - * @return - */ - static function getScreenIdsOfChapter($a_chap, $a_module_id = 0) - { - global $DIC; + $ilDB = $DIC->database(); + + $ilDB->manipulate( + "DELETE FROM help_map WHERE " . + " chap = " . $ilDB->quote($a_chap, "integer") . + " AND module_id = " . $ilDB->quote($a_module_id, "integer") + ); + } + + /** + * Get screen ids of chapter + * + * @param + * @return + */ + public static function getScreenIdsOfChapter($a_chap, $a_module_id = 0) + { + global $DIC; - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT * FROM help_map ". - " WHERE chap = ".$ilDB->quote($a_chap, "integer"). - " AND module_id = ".$ilDB->quote($a_module_id, "integer"). - " ORDER BY component, screen_id, screen_sub_id" - ); - $screen_ids = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - if ($rec["screen_id"] == "-") - { - $rec["screen_id"] = ""; - } - if ($rec["screen_sub_id"] == "-") - { - $rec["screen_sub_id"] = ""; - } - $id = $rec["component"]."/".$rec["screen_id"]."/".$rec["screen_sub_id"]; - if ($rec["perm"] != "" && $rec["perm"] != "-") - { - $id.= "#".$rec["perm"]; - } - $screen_ids[] = $id; - } - return $screen_ids; - } - - /** - * Get help sections for screen id - * - * @param - * @return - */ - static function getHelpSectionsForId($a_screen_id, $a_ref_id) - { - global $DIC; + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT * FROM help_map " . + " WHERE chap = " . $ilDB->quote($a_chap, "integer") . + " AND module_id = " . $ilDB->quote($a_module_id, "integer") . + " ORDER BY component, screen_id, screen_sub_id" + ); + $screen_ids = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + if ($rec["screen_id"] == "-") { + $rec["screen_id"] = ""; + } + if ($rec["screen_sub_id"] == "-") { + $rec["screen_sub_id"] = ""; + } + $id = $rec["component"] . "/" . $rec["screen_id"] . "/" . $rec["screen_sub_id"]; + if ($rec["perm"] != "" && $rec["perm"] != "-") { + $id.= "#" . $rec["perm"]; + } + $screen_ids[] = $id; + } + return $screen_ids; + } + + /** + * Get help sections for screen id + * + * @param + * @return + */ + public static function getHelpSectionsForId($a_screen_id, $a_ref_id) + { + global $DIC; - $ilDB = $DIC->database(); - $ilAccess = $DIC->access(); - $ilSetting = $DIC->settings(); - $rbacreview = $DIC->rbac()->review(); - $ilUser = $DIC->user(); - $ilObjDataCache = $DIC["ilObjDataCache"]; + $ilDB = $DIC->database(); + $ilAccess = $DIC->access(); + $ilSetting = $DIC->settings(); + $rbacreview = $DIC->rbac()->review(); + $ilUser = $DIC->user(); + $ilObjDataCache = $DIC["ilObjDataCache"]; - if (OH_REF_ID > 0) - { - $module = 0; - } - else - { - $module = (int) $ilSetting->get("help_module"); - if ($module == 0) - { - return array(); - } - } + if (OH_REF_ID > 0) { + $module = 0; + } else { + $module = (int) $ilSetting->get("help_module"); + if ($module == 0) { + return array(); + } + } - $sc_id = explode("/", $a_screen_id); - $chaps = array(); - if ($sc_id[0] != "") - { - if ($sc_id[1] == "") - { - $sc_id[1] = "-"; - } - if ($sc_id[2] == "") - { - $sc_id[2] = "-"; - } - $set = $ilDB->query("SELECT chap, perm FROM help_map JOIN lm_tree". - " ON (help_map.chap = lm_tree.child) ". - " WHERE (component = ".$ilDB->quote($sc_id[0], "text"). - " OR component = ".$ilDB->quote("*", "text").")". - " AND screen_id = ".$ilDB->quote($sc_id[1], "text"). - " AND screen_sub_id = ".$ilDB->quote($sc_id[2], "text"). - " AND module_id = ".$ilDB->quote($module, "integer"). - " ORDER BY lm_tree.lft" - ); - while ($rec = $ilDB->fetchAssoc($set)) - { - if ($rec["perm"] != "" && $rec["perm"] != "-") - { - // check special "create*" permission - if ($rec["perm"] == "create*") - { - $has_create_perm = false; - - // check owner - if ($ilUser->getId() == $ilObjDataCache->lookupOwner(ilObject::_lookupObjId($a_ref_id))) - { - $has_create_perm = true; - } - else if ($rbacreview->isAssigned($ilUser->getId(), SYSTEM_ROLE_ID)) // check admin - { - $has_create_perm = true; - } - else if ($ilAccess->checkAccess("read", "", (int) $a_ref_id)) - { - $perm = $rbacreview->getUserPermissionsOnObject($ilUser->getId(), (int) $a_ref_id); - foreach ($perm as $p) - { - if (substr($p, 0, 7) == "create_") - { - $has_create_perm = true; - } - } - } - if ($has_create_perm) - { - $chaps[] = $rec["chap"]; - } - } - else if ($ilAccess->checkAccess($rec["perm"], "", (int) $a_ref_id)) - { - $chaps[] = $rec["chap"]; - } - } - else - { - $chaps[] = $rec["chap"]; - } - } - } - return $chaps; - } - - /** - * Has given screen Id any sections? - * - * Note: We removed the "ref_id" parameter here, since this method - * should be fast. It is used to decide whether the help button should - * appear or not. We assume that there is at least one section for - * users with the "read" permission. - * - * @param - * @return - */ - static function hasScreenIdSections($a_screen_id) - { - global $DIC; + $sc_id = explode("/", $a_screen_id); + $chaps = array(); + if ($sc_id[0] != "") { + if ($sc_id[1] == "") { + $sc_id[1] = "-"; + } + if ($sc_id[2] == "") { + $sc_id[2] = "-"; + } + $set = $ilDB->query( + "SELECT chap, perm FROM help_map JOIN lm_tree" . + " ON (help_map.chap = lm_tree.child) " . + " WHERE (component = " . $ilDB->quote($sc_id[0], "text") . + " OR component = " . $ilDB->quote("*", "text") . ")" . + " AND screen_id = " . $ilDB->quote($sc_id[1], "text") . + " AND screen_sub_id = " . $ilDB->quote($sc_id[2], "text") . + " AND module_id = " . $ilDB->quote($module, "integer") . + " ORDER BY lm_tree.lft" + ); + while ($rec = $ilDB->fetchAssoc($set)) { + if ($rec["perm"] != "" && $rec["perm"] != "-") { + // check special "create*" permission + if ($rec["perm"] == "create*") { + $has_create_perm = false; + + // check owner + if ($ilUser->getId() == $ilObjDataCache->lookupOwner(ilObject::_lookupObjId($a_ref_id))) { + $has_create_perm = true; + } elseif ($rbacreview->isAssigned($ilUser->getId(), SYSTEM_ROLE_ID)) { // check admin + $has_create_perm = true; + } elseif ($ilAccess->checkAccess("read", "", (int) $a_ref_id)) { + $perm = $rbacreview->getUserPermissionsOnObject($ilUser->getId(), (int) $a_ref_id); + foreach ($perm as $p) { + if (substr($p, 0, 7) == "create_") { + $has_create_perm = true; + } + } + } + if ($has_create_perm) { + $chaps[] = $rec["chap"]; + } + } elseif ($ilAccess->checkAccess($rec["perm"], "", (int) $a_ref_id)) { + $chaps[] = $rec["chap"]; + } + } else { + $chaps[] = $rec["chap"]; + } + } + } + return $chaps; + } + + /** + * Has given screen Id any sections? + * + * Note: We removed the "ref_id" parameter here, since this method + * should be fast. It is used to decide whether the help button should + * appear or not. We assume that there is at least one section for + * users with the "read" permission. + * + * @param + * @return + */ + public static function hasScreenIdSections($a_screen_id) + { + global $DIC; - $ilDB = $DIC->database(); - $ilAccess = $DIC->access(); - $ilSetting = $DIC->settings(); - $ilUser = $DIC->user(); - - if ($ilUser->getLanguage() != "de") - { - return false; - } - - if ($ilSetting->get("help_mode") == "2") - { - return false; - } + $ilDB = $DIC->database(); + $ilAccess = $DIC->access(); + $ilSetting = $DIC->settings(); + $ilUser = $DIC->user(); + + if ($ilUser->getLanguage() != "de") { + return false; + } + + if ($ilSetting->get("help_mode") == "2") { + return false; + } - if (OH_REF_ID > 0) - { - $module = 0; - } - else - { - $module = (int) $ilSetting->get("help_module"); - if ($module == 0) - { - return false; - } - } + if (OH_REF_ID > 0) { + $module = 0; + } else { + $module = (int) $ilSetting->get("help_module"); + if ($module == 0) { + return false; + } + } - $sc_id = explode("/", $a_screen_id); - if ($sc_id[0] != "") - { - if ($sc_id[1] == "") - { - $sc_id[1] = "-"; - } - if ($sc_id[2] == "") - { - $sc_id[2] = "-"; - } - $set = $ilDB->query("SELECT chap, perm FROM help_map ". - " WHERE (component = ".$ilDB->quote($sc_id[0], "text"). - " OR component = ".$ilDB->quote("*", "text").")". - " AND screen_id = ".$ilDB->quote($sc_id[1], "text"). - " AND screen_sub_id = ".$ilDB->quote($sc_id[2], "text"). - " AND module_id = ".$ilDB->quote($module, "integer") - ); - while ($rec = $ilDB->fetchAssoc($set)) - { - return true; - - // no permission check, since it takes to much performance - // getHelpSectionsForId() does the permission checks. - /*if ($rec["perm"] != "" && $rec["perm"] != "-") - { - if ($ilAccess->checkAccess($rec["perm"], "", (int) $a_ref_id)) - { - return true; - } - } - else - { - return true; - }*/ - } - } - return false; - } - - /** - * Delete entries of module - * - * @param - * @return - */ - static function deleteEntriesOfModule($a_id) - { - global $DIC; + $sc_id = explode("/", $a_screen_id); + if ($sc_id[0] != "") { + if ($sc_id[1] == "") { + $sc_id[1] = "-"; + } + if ($sc_id[2] == "") { + $sc_id[2] = "-"; + } + $set = $ilDB->query( + "SELECT chap, perm FROM help_map " . + " WHERE (component = " . $ilDB->quote($sc_id[0], "text") . + " OR component = " . $ilDB->quote("*", "text") . ")" . + " AND screen_id = " . $ilDB->quote($sc_id[1], "text") . + " AND screen_sub_id = " . $ilDB->quote($sc_id[2], "text") . + " AND module_id = " . $ilDB->quote($module, "integer") + ); + while ($rec = $ilDB->fetchAssoc($set)) { + return true; + + // no permission check, since it takes to much performance + // getHelpSectionsForId() does the permission checks. + /*if ($rec["perm"] != "" && $rec["perm"] != "-") + { + if ($ilAccess->checkAccess($rec["perm"], "", (int) $a_ref_id)) + { + return true; + } + } + else + { + return true; + }*/ + } + } + return false; + } + + /** + * Delete entries of module + * + * @param + * @return + */ + public static function deleteEntriesOfModule($a_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $ilDB->manipulate("DELETE FROM help_map WHERE ". - " module_id = ".$ilDB->quote($a_id, "integer")); - - } - - + $ilDB = $DIC->database(); + + $ilDB->manipulate("DELETE FROM help_map WHERE " . + " module_id = " . $ilDB->quote($a_id, "integer")); + } } - -?> diff --git a/Services/Help/classes/class.ilHelpModuleTableGUI.php b/Services/Help/classes/class.ilHelpModuleTableGUI.php index 6f103bb94e9691e59fe13611aa8166be672a3eb6..192e9253da6581891bc508495c6b14d1fc00fb44 100644 --- a/Services/Help/classes/class.ilHelpModuleTableGUI.php +++ b/Services/Help/classes/class.ilHelpModuleTableGUI.php @@ -14,107 +14,106 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilHelpModuleTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * @var ilSetting - */ - protected $settings; + /** + * @var ilSetting + */ + protected $settings; - /** - * @var bool - */ - protected $has_write_permission; + /** + * @var bool + */ + protected $has_write_permission; - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_has_write_permission = false) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_has_write_permission = false) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $this->settings = $DIC->settings(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilAccess = $DIC->access(); - $lng = $DIC->language(); - $this->has_write_permission = $a_has_write_permission; - - $this->setId("help_mods"); - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->getHelpModules(); - $this->setTitle($lng->txt("help_modules")); - - $this->addColumn("", "", "1"); - $this->addColumn($this->lng->txt("title")); - $this->addColumn($this->lng->txt("help_imported_on")); - $this->addColumn($this->lng->txt("actions")); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.help_module_row.html", "Services/Help"); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->settings = $DIC->settings(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilAccess = $DIC->access(); + $lng = $DIC->language(); + $this->has_write_permission = $a_has_write_permission; + + $this->setId("help_mods"); + + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->getHelpModules(); + $this->setTitle($lng->txt("help_modules")); + + $this->addColumn("", "", "1"); + $this->addColumn($this->lng->txt("title")); + $this->addColumn($this->lng->txt("help_imported_on")); + $this->addColumn($this->lng->txt("actions")); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.help_module_row.html", "Services/Help"); - if ($this->has_write_permission) - { - $this->addMultiCommand("confirmHelpModulesDeletion", $lng->txt("delete")); - } - //$this->addCommandButton("", $lng->txt("")); - } - - /** - * Get help modules - */ - function getHelpModules() - { - $this->setData($this->parent_obj->object->getHelpModules()); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilSetting = $this->settings; - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameter($this->parent_obj, "hm_id", $a_set["id"]); - if ($this->has_write_permission) - { - if ($a_set["id"] == $ilSetting->get("help_module")) - { - $this->tpl->setCurrentBlock("cmd"); - $this->tpl->setVariable("HREF_CMD", - $ilCtrl->getLinkTarget($this->parent_obj, "deactivateModule")); - $this->tpl->setVariable("TXT_CMD", $lng->txt("deactivate")); - $this->tpl->parseCurrentBlock(); - } else - { - $this->tpl->setCurrentBlock("cmd"); - $this->tpl->setVariable("HREF_CMD", - $ilCtrl->getLinkTarget($this->parent_obj, "activateModule")); - $this->tpl->setVariable("TXT_CMD", $lng->txt("activate")); - $this->tpl->parseCurrentBlock(); - } - } - $ilCtrl->setParameter($this->parent_obj, "hm_id", ""); - $this->tpl->setVariable("TITLE", $a_set["title"]); - $this->tpl->setVariable("CREATION_DATE", - ilDatePresentation::formatDate(new ilDateTime($a_set["create_date"],IL_CAL_DATETIME))); - $this->tpl->setVariable("ID", $a_set["id"]); - - } + if ($this->has_write_permission) { + $this->addMultiCommand("confirmHelpModulesDeletion", $lng->txt("delete")); + } + //$this->addCommandButton("", $lng->txt("")); + } + + /** + * Get help modules + */ + public function getHelpModules() + { + $this->setData($this->parent_obj->object->getHelpModules()); + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilSetting = $this->settings; + $ilCtrl = $this->ctrl; + $ilCtrl->setParameter($this->parent_obj, "hm_id", $a_set["id"]); + if ($this->has_write_permission) { + if ($a_set["id"] == $ilSetting->get("help_module")) { + $this->tpl->setCurrentBlock("cmd"); + $this->tpl->setVariable( + "HREF_CMD", + $ilCtrl->getLinkTarget($this->parent_obj, "deactivateModule") + ); + $this->tpl->setVariable("TXT_CMD", $lng->txt("deactivate")); + $this->tpl->parseCurrentBlock(); + } else { + $this->tpl->setCurrentBlock("cmd"); + $this->tpl->setVariable( + "HREF_CMD", + $ilCtrl->getLinkTarget($this->parent_obj, "activateModule") + ); + $this->tpl->setVariable("TXT_CMD", $lng->txt("activate")); + $this->tpl->parseCurrentBlock(); + } + } + $ilCtrl->setParameter($this->parent_obj, "hm_id", ""); + $this->tpl->setVariable("TITLE", $a_set["title"]); + $this->tpl->setVariable( + "CREATION_DATE", + ilDatePresentation::formatDate(new ilDateTime($a_set["create_date"], IL_CAL_DATETIME)) + ); + $this->tpl->setVariable("ID", $a_set["id"]); + } } -?> diff --git a/Services/Help/classes/class.ilObjHelpSettings.php b/Services/Help/classes/class.ilObjHelpSettings.php index 73d9091e166aa3812fc5ac111e7b8b470669aaa0..87ec8d7adb72231204753ae18d1b2a45c7777786 100755 --- a/Services/Help/classes/class.ilObjHelpSettings.php +++ b/Services/Help/classes/class.ilObjHelpSettings.php @@ -6,306 +6,305 @@ require_once "./Services/Object/classes/class.ilObject2.php"; /** * Help settings application class - * - * @author Alex Killing + * + * @author Alex Killing * @version $Id$ * * @ingroup ServicesHelp */ class ilObjHelpSettings extends ilObject2 { - /** - * @var ilDB - */ - protected $db; - - /** - * @var ilSetting - */ - protected $settings; + /** + * @var ilDB + */ + protected $db; + /** + * @var ilSetting + */ + protected $settings; - /** - * Constructor - */ - function __construct() - { - parent::__construct(); - global $DIC; - $this->db = $DIC->database(); - $this->settings = $DIC->settings(); - } + /** + * Constructor + */ + public function __construct() + { + parent::__construct(); + global $DIC; - /** - * Init type - */ - function initType() - { - $this->type = "hlps"; - } + $this->db = $DIC->database(); + $this->settings = $DIC->settings(); + } - /** - * Create help module - * - * @param - * @return - */ - static function createHelpModule() - { - global $DIC; + /** + * Init type + */ + public function initType() + { + $this->type = "hlps"; + } - $ilDB = $DIC->database(); - - $id = $ilDB->nextId("help_module"); - - $ilDB->manipulate("INSERT INTO help_module ". - "(id) VALUES (". - $ilDB->quote($id, "integer"). - ")"); - - return $id; - } - - /** - * Write help module lm id - * - * @param - * @return - */ - static function writeHelpModuleLmId($a_id, $a_lm_id) - { - global $DIC; + /** + * Create help module + * + * @param + * @return + */ + public static function createHelpModule() + { + global $DIC; - $ilDB = $DIC->database(); - - $ilDB->manipulate("UPDATE help_module SET ". - " lm_id = ".$ilDB->quote($a_lm_id, "integer"). - " WHERE id = ".$ilDB->quote($a_id, "integer") - ); - } - - - /** - * Upload help file - * - * @param - * @return - */ - function uploadHelpModule($a_file) - { - $id = $this->createHelpModule(); - - // create and insert object in objecttree - /*include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); - $newObj = new ilObjContentObject(); - $newObj->setType("lm"); - $newObj->setTitle("Help Module"); - $newObj->create(true); - $newObj->createLMTree();*/ + $ilDB = $DIC->database(); + + $id = $ilDB->nextId("help_module"); + + $ilDB->manipulate("INSERT INTO help_module " . + "(id) VALUES (" . + $ilDB->quote($id, "integer") . + ")"); + + return $id; + } + + /** + * Write help module lm id + * + * @param + * @return + */ + public static function writeHelpModuleLmId($a_id, $a_lm_id) + { + global $DIC; - try - { - include_once("./Services/Export/classes/class.ilImport.php"); - $imp = new ilImport(); - $conf = $imp->getConfig("Services/Help"); - $conf->setModuleId($id); - $new_id = $imp->importObject("", $a_file["tmp_name"], $a_file["name"], "lm", "Modules/LearningModule"); - $newObj = new ilObjLearningModule($new_id, false); + $ilDB = $DIC->database(); + + $ilDB->manipulate( + "UPDATE help_module SET " . + " lm_id = " . $ilDB->quote($a_lm_id, "integer") . + " WHERE id = " . $ilDB->quote($a_id, "integer") + ); + } + + + /** + * Upload help file + * + * @param + * @return + */ + public function uploadHelpModule($a_file) + { + $id = $this->createHelpModule(); + + // create and insert object in objecttree + /*include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); + $newObj = new ilObjContentObject(); + $newObj->setType("lm"); + $newObj->setTitle("Help Module"); + $newObj->create(true); + $newObj->createLMTree();*/ - self::writeHelpModuleLmId($id, $newObj->getId()); - } - catch (ilManifestFileNotFoundImportException $e) - { - // old import - $t = $imp->getTemporaryImportDir(); + try { + include_once("./Services/Export/classes/class.ilImport.php"); + $imp = new ilImport(); + $conf = $imp->getConfig("Services/Help"); + $conf->setModuleId($id); + $new_id = $imp->importObject("", $a_file["tmp_name"], $a_file["name"], "lm", "Modules/LearningModule"); + $newObj = new ilObjLearningModule($new_id, false); - // create and insert object in objecttree - include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); - $newObj = new ilObjContentObject(); - $newObj->setType("lm"); - $newObj->setTitle("Help Module"); - $newObj->create(true); - $newObj->createLMTree(); + self::writeHelpModuleLmId($id, $newObj->getId()); + } catch (ilManifestFileNotFoundImportException $e) { + // old import + $t = $imp->getTemporaryImportDir(); - $mess = $newObj->importFromDirectory($t, false); + // create and insert object in objecttree + include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); + $newObj = new ilObjContentObject(); + $newObj->setType("lm"); + $newObj->setTitle("Help Module"); + $newObj->create(true); + $newObj->createLMTree(); - // this should only be true for help modules - // search the zip file - $dir = $t; - $files = ilUtil::getDir($dir); - foreach ($files as $file) - { - if (is_int(strpos($file["entry"], "__help_")) && - is_int(strpos($file["entry"], ".zip"))) - { - include_once("./Services/Export/classes/class.ilImport.php"); - $imp = new ilImport(); - $imp->getMapping()->addMapping('Services/Help', 'help_module', 0, $id); - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - $chaps = ilLMObject::getObjectList($newObj->getId(), "st"); - foreach ($chaps as $chap) - { - $chap_arr = explode("_", $chap["import_id"]); - $imp->getMapping()->addMapping('Services/Help', 'help_chap', - $chap_arr[count($chap_arr) - 1], $chap["obj_id"]); - } - $imp->importEntity($dir."/".$file["entry"], $file["entry"], - "help", "Services/Help", true); - } - } + $mess = $newObj->importFromDirectory($t, false); - // delete import directory - ilUtil::delDir($t); + // this should only be true for help modules + // search the zip file + $dir = $t; + $files = ilUtil::getDir($dir); + foreach ($files as $file) { + if (is_int(strpos($file["entry"], "__help_")) && + is_int(strpos($file["entry"], ".zip"))) { + include_once("./Services/Export/classes/class.ilImport.php"); + $imp = new ilImport(); + $imp->getMapping()->addMapping('Services/Help', 'help_module', 0, $id); + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + $chaps = ilLMObject::getObjectList($newObj->getId(), "st"); + foreach ($chaps as $chap) { + $chap_arr = explode("_", $chap["import_id"]); + $imp->getMapping()->addMapping( + 'Services/Help', + 'help_chap', + $chap_arr[count($chap_arr) - 1], + $chap["obj_id"] + ); + } + $imp->importEntity( + $dir . "/" . $file["entry"], + $file["entry"], + "help", + "Services/Help", + true + ); + } + } - self::writeHelpModuleLmId($id, $newObj->getId()); - } + // delete import directory + ilUtil::delDir($t); + self::writeHelpModuleLmId($id, $newObj->getId()); + } - $GLOBALS['ilAppEventHandler']->raise( - 'Services/Help', - 'create', - array( - 'obj_id' => $id, - 'obj_type' => 'lm' - ) - ); - } - - /** - * Get help modules - * - * @param - * @return - */ - function getHelpModules() - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT * FROM help_module"); - - $mods = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - if (ilObject::_lookupType($rec["lm_id"]) == "lm") - { - $rec["title"] = ilObject::_lookupTitle($rec["lm_id"]); - $rec["create_date"] = ilObject::_lookupCreationDate($rec["lm_id"]); - } - - $mods[] = $rec; - } - - return $mods; - } - - /** - * lookup module title - * - * @param - * @return - */ - static function lookupModuleTitle($a_id) - { - global $DIC; - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT * FROM help_module ". - " WHERE id = ".$ilDB->quote($a_id, "integer") - ); - $rec = $ilDB->fetchAssoc($set); - if (ilObject::_lookupType($rec["lm_id"]) == "lm") - { - return ilObject::_lookupTitle($rec["lm_id"]); - } - return ""; - } - - /** - * lookup module lm id - * - * @param - * @return - */ - static function lookupModuleLmId($a_id) - { - global $DIC; + $GLOBALS['ilAppEventHandler']->raise( + 'Services/Help', + 'create', + array( + 'obj_id' => $id, + 'obj_type' => 'lm' + ) + ); + } + + /** + * Get help modules + * + * @param + * @return + */ + public function getHelpModules() + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT * FROM help_module"); + + $mods = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + if (ilObject::_lookupType($rec["lm_id"]) == "lm") { + $rec["title"] = ilObject::_lookupTitle($rec["lm_id"]); + $rec["create_date"] = ilObject::_lookupCreationDate($rec["lm_id"]); + } + + $mods[] = $rec; + } + + return $mods; + } + + /** + * lookup module title + * + * @param + * @return + */ + public static function lookupModuleTitle($a_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT lm_id FROM help_module ". - " WHERE id = ".$ilDB->quote($a_id, "integer") - ); - $rec = $ilDB->fetchAssoc($set); - return $rec["lm_id"]; - } - - /** - * Delete module - * - * @param - * @return - */ - function deleteModule($a_id) - { - $ilDB = $this->db; - $ilSetting = $this->settings; - - // if this is the currently activated one, deactivate it first - if ($a_id == (int) $ilSetting->get("help_module")) - { - $ilSetting->set("help_module", ""); - } - - $set = $ilDB->query("SELECT * FROM help_module ". - " WHERE id = ".$ilDB->quote($a_id, "integer") - ); - $rec = $ilDB->fetchAssoc($set); + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT * FROM help_module " . + " WHERE id = " . $ilDB->quote($a_id, "integer") + ); + $rec = $ilDB->fetchAssoc($set); + if (ilObject::_lookupType($rec["lm_id"]) == "lm") { + return ilObject::_lookupTitle($rec["lm_id"]); + } + return ""; + } + + /** + * lookup module lm id + * + * @param + * @return + */ + public static function lookupModuleLmId($a_id) + { + global $DIC; - // delete learning module - if (ilObject::_lookupType($rec["lm_id"]) == "lm") - { - include_once("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); - $lm = new ilObjLearningModule($rec["lm_id"], false); - $lm->delete(); - } - - // delete mappings - include_once("./Services/Help/classes/class.ilHelpMapping.php"); - ilHelpMapping::deleteEntriesOfModule($a_id); - - // delete tooltips - include_once("./Services/Help/classes/class.ilHelp.php"); - ilHelp::deleteTooltipsOfModule($a_id); - - // delete help module record - $ilDB->manipulate("DELETE FROM help_module WHERE ". - " id = ".$ilDB->quote($a_id, "integer")); - - } + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT lm_id FROM help_module " . + " WHERE id = " . $ilDB->quote($a_id, "integer") + ); + $rec = $ilDB->fetchAssoc($set); + return $rec["lm_id"]; + } + + /** + * Delete module + * + * @param + * @return + */ + public function deleteModule($a_id) + { + $ilDB = $this->db; + $ilSetting = $this->settings; + + // if this is the currently activated one, deactivate it first + if ($a_id == (int) $ilSetting->get("help_module")) { + $ilSetting->set("help_module", ""); + } + + $set = $ilDB->query( + "SELECT * FROM help_module " . + " WHERE id = " . $ilDB->quote($a_id, "integer") + ); + $rec = $ilDB->fetchAssoc($set); - /** - * Check if LM is a help LM - * - * @param integer $a_lm_id lm id - * @return bool true/false - */ - static function isHelpLM($a_lm_id) - { - global $DIC; + // delete learning module + if (ilObject::_lookupType($rec["lm_id"]) == "lm") { + include_once("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); + $lm = new ilObjLearningModule($rec["lm_id"], false); + $lm->delete(); + } + + // delete mappings + include_once("./Services/Help/classes/class.ilHelpMapping.php"); + ilHelpMapping::deleteEntriesOfModule($a_id); + + // delete tooltips + include_once("./Services/Help/classes/class.ilHelp.php"); + ilHelp::deleteTooltipsOfModule($a_id); + + // delete help module record + $ilDB->manipulate("DELETE FROM help_module WHERE " . + " id = " . $ilDB->quote($a_id, "integer")); + } - $ilDB = $DIC->database(); + /** + * Check if LM is a help LM + * + * @param integer $a_lm_id lm id + * @return bool true/false + */ + public static function isHelpLM($a_lm_id) + { + global $DIC; - $set = $ilDB->query("SELECT id FROM help_module ". - " WHERE lm_id = ".$ilDB->quote($a_lm_id, "integer") - ); - if ($rec = $ilDB->fetchAssoc($set)) - { - return true; - } - return false; - } + $ilDB = $DIC->database(); + $set = $ilDB->query( + "SELECT id FROM help_module " . + " WHERE lm_id = " . $ilDB->quote($a_lm_id, "integer") + ); + if ($rec = $ilDB->fetchAssoc($set)) { + return true; + } + return false; + } } -?> diff --git a/Services/Help/classes/class.ilObjHelpSettingsAccess.php b/Services/Help/classes/class.ilObjHelpSettingsAccess.php index 0db29b8da230ee221e013cbda2e2e1b153fb140b..b98dcb8f980fdba666c80184d3e96ece505ef5df 100755 --- a/Services/Help/classes/class.ilObjHelpSettingsAccess.php +++ b/Services/Help/classes/class.ilObjHelpSettingsAccess.php @@ -15,8 +15,4 @@ include_once("./Services/Object/classes/class.ilObjectAccess.php"); */ class ilObjHelpSettingsAccess extends ilObjectAccess { - - } - -?> diff --git a/Services/Help/classes/class.ilObjHelpSettingsGUI.php b/Services/Help/classes/class.ilObjHelpSettingsGUI.php index 31db03bdb42061105ffa7050ac738e57a8dec8b7..4d764e5978ae4753a4f3a6edb4eacf1c476a4d64 100755 --- a/Services/Help/classes/class.ilObjHelpSettingsGUI.php +++ b/Services/Help/classes/class.ilObjHelpSettingsGUI.php @@ -16,333 +16,315 @@ include_once("./Services/Object/classes/class.ilObject2GUI.php"); */ class ilObjHelpSettingsGUI extends ilObject2GUI { - /** - * @var ilRbacSystem - */ - protected $rbacsystem; + /** + * @var ilRbacSystem + */ + protected $rbacsystem; - /** - * @var ilErrorHandling - */ - protected $error; + /** + * @var ilErrorHandling + */ + protected $error; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * @var ilSetting - */ - protected $settings; + /** + * @var ilSetting + */ + protected $settings; - /** - * @var ilTabsGUI - */ - protected $tabs; + /** + * @var ilTabsGUI + */ + protected $tabs; - /** - * @var ilToolbarGUI - */ - protected $toolbar; + /** + * @var ilToolbarGUI + */ + protected $toolbar; - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; - /** - * Constructor - */ - function __construct($a_id = 0, $a_id_type = self::REPOSITORY_NODE_ID, $a_parent_node_id = 0) - { - global $DIC; - parent::__construct($a_id, $a_id_type, $a_parent_node_id); + /** + * Constructor + */ + public function __construct($a_id = 0, $a_id_type = self::REPOSITORY_NODE_ID, $a_parent_node_id = 0) + { + global $DIC; + parent::__construct($a_id, $a_id_type, $a_parent_node_id); - $this->rbacsystem = $DIC->rbac()->system(); - $this->error = $DIC["ilErr"]; - $this->access = $DIC->access(); - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $this->settings = $DIC->settings(); - $this->tabs = $DIC->tabs(); - $this->toolbar = $DIC->toolbar(); - $this->tpl = $DIC["tpl"]; - $this->db = $DIC->database(); - } + $this->rbacsystem = $DIC->rbac()->system(); + $this->error = $DIC["ilErr"]; + $this->access = $DIC->access(); + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->settings = $DIC->settings(); + $this->tabs = $DIC->tabs(); + $this->toolbar = $DIC->toolbar(); + $this->tpl = $DIC["tpl"]; + $this->db = $DIC->database(); + } - /** - * Get type - */ - function getType() - { - return "hlps"; - } + /** + * Get type + */ + public function getType() + { + return "hlps"; + } - /** - * Execute command - * - * @access public - * - */ - public function executeCommand() - { - $ilErr = $this->error; - $ilAccess = $this->access; - $lng = $this->lng; - $lng->loadLanguageModule("help"); + /** + * Execute command + * + * @access public + * + */ + public function executeCommand() + { + $ilErr = $this->error; + $ilAccess = $this->access; + $lng = $this->lng; + $lng->loadLanguageModule("help"); - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); - $this->prepareOutput(); + $this->prepareOutput(); - if (!$ilAccess->checkAccess('read','',$this->object->getRefId())) - { - $ilErr->raiseError($this->lng->txt('no_permission'),$ilErr->WARNING); - } + if (!$ilAccess->checkAccess('read', '', $this->object->getRefId())) { + $ilErr->raiseError($this->lng->txt('no_permission'), $ilErr->WARNING); + } - switch($next_class) - { - case 'ilpermissiongui': - $this->tabs_gui->setTabActive('perm_settings'); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $ret = $this->ctrl->forwardCommand($perm_gui); - break; + switch ($next_class) { + case 'ilpermissiongui': + $this->tabs_gui->setTabActive('perm_settings'); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $ret = $this->ctrl->forwardCommand($perm_gui); + break; - default: - if(!$cmd || $cmd == 'view') - { - $cmd = "editSettings"; - } + default: + if (!$cmd || $cmd == 'view') { + $cmd = "editSettings"; + } - $this->$cmd(); - break; - } - return true; - } + $this->$cmd(); + break; + } + return true; + } - /** - * Edit news settings. - */ - public function editSettings() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilSetting = $this->settings; - $ilTabs = $this->tabs; - $ilToolbar = $this->toolbar; - - $ilTabs->activateTab("settings"); - - if (OH_REF_ID > 0) - { - ilUtil::sendInfo("This installation is used for online help authoring. Help modules cannot be imported."); - return; - } - - if ($this->checkPermissionBool("write")) - { - // help file - include_once("./Services/Form/classes/class.ilFileInputGUI.php"); - $fi = new ilFileInputGUI($lng->txt("help_help_file"), "help_file"); - $fi->setSuffixes(array("zip")); - $ilToolbar->addInputItem($fi, true); - $ilToolbar->addFormButton($lng->txt("upload"), "uploadHelpFile"); - $ilToolbar->addSeparator(); - - // help mode - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $options = array( - "" => $lng->txt("help_tooltips_and_help"), - "1" => $lng->txt("help_help_only"), - "2" => $lng->txt("help_tooltips_only") - ); - $si = new ilSelectInputGUI($this->lng->txt("help_mode"), "help_mode"); - $si->setOptions($options); - $si->setValue($ilSetting->get("help_mode")); - $ilToolbar->addInputItem($si); - - $ilToolbar->addFormButton($lng->txt("help_set_mode"), "setMode"); - - } - $ilToolbar->setFormAction($ilCtrl->getFormAction($this), true); - - include_once("./Services/Help/classes/class.ilHelpModuleTableGUI.php"); - $tab = new ilHelpModuleTableGUI($this, "editSettings", $this->checkPermissionBool("write")); - - $this->tpl->setContent($tab->getHTML()); - } + /** + * Edit news settings. + */ + public function editSettings() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilSetting = $this->settings; + $ilTabs = $this->tabs; + $ilToolbar = $this->toolbar; + + $ilTabs->activateTab("settings"); + + if (OH_REF_ID > 0) { + ilUtil::sendInfo("This installation is used for online help authoring. Help modules cannot be imported."); + return; + } + + if ($this->checkPermissionBool("write")) { + // help file + include_once("./Services/Form/classes/class.ilFileInputGUI.php"); + $fi = new ilFileInputGUI($lng->txt("help_help_file"), "help_file"); + $fi->setSuffixes(array("zip")); + $ilToolbar->addInputItem($fi, true); + $ilToolbar->addFormButton($lng->txt("upload"), "uploadHelpFile"); + $ilToolbar->addSeparator(); + + // help mode + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $options = array( + "" => $lng->txt("help_tooltips_and_help"), + "1" => $lng->txt("help_help_only"), + "2" => $lng->txt("help_tooltips_only") + ); + $si = new ilSelectInputGUI($this->lng->txt("help_mode"), "help_mode"); + $si->setOptions($options); + $si->setValue($ilSetting->get("help_mode")); + $ilToolbar->addInputItem($si); + + $ilToolbar->addFormButton($lng->txt("help_set_mode"), "setMode"); + } + $ilToolbar->setFormAction($ilCtrl->getFormAction($this), true); + + include_once("./Services/Help/classes/class.ilHelpModuleTableGUI.php"); + $tab = new ilHelpModuleTableGUI($this, "editSettings", $this->checkPermissionBool("write")); + + $this->tpl->setContent($tab->getHTML()); + } - /** - * administration tabs show only permissions and trash folder - */ - function getAdminTabs() - { - if ($this->checkPermissionBool("visible,read")) - { - $this->tabs_gui->addTab("settings", - $this->lng->txt("settings"), - $this->ctrl->getLinkTarget($this, "editSettings")); + /** + * administration tabs show only permissions and trash folder + */ + public function getAdminTabs() + { + if ($this->checkPermissionBool("visible,read")) { + $this->tabs_gui->addTab( + "settings", + $this->lng->txt("settings"), + $this->ctrl->getLinkTarget($this, "editSettings") + ); + } + + if ($this->checkPermissionBool("edit_permission")) { + $this->tabs_gui->addTab( + "perm_settings", + $this->lng->txt("perm_settings"), + $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm") + ); + } + } - } - - if ($this->checkPermissionBool("edit_permission")) - { - $this->tabs_gui->addTab("perm_settings", - $this->lng->txt("perm_settings"), - $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm") - ); - } - } + + + + /** + * Upload help file + * + * @param + * @return + */ + public function uploadHelpFile() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if ($this->checkPermissionBool("write")) { + $this->object->uploadHelpModule($_FILES["help_file"]); + ilUtil::sendSuccess($lng->txt("help_module_uploaded"), true); + } + + $ilCtrl->redirect($this, "editSettings"); + } + + /** + * Confirm help modules deletion + */ + public function confirmHelpModulesDeletion() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; - - - - /** - * Upload help file - * - * @param - * @return - */ - function uploadHelpFile() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if ($this->checkPermissionBool("write")) - { - $this->object->uploadHelpModule($_FILES["help_file"]); - ilUtil::sendSuccess($lng->txt("help_module_uploaded"), true); - } - - $ilCtrl->redirect($this, "editSettings"); - } - - /** - * Confirm help modules deletion - */ - function confirmHelpModulesDeletion() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; + $this->checkPermission("write"); + + if (!is_array($_POST["id"]) || count($_POST["id"]) == 0) { + ilUtil::sendInfo($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "editSettings"); + } else { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("help_sure_delete_help_modules")); + $cgui->setCancel($lng->txt("cancel"), "editSettings"); + $cgui->setConfirm($lng->txt("delete"), "deleteHelpModules"); + + foreach ($_POST["id"] as $i) { + $cgui->addItem("id[]", $i, $this->object->lookupModuleTitle($i)); + } + + $tpl->setContent($cgui->getHTML()); + } + } + + /** + * Delete help modules + * + * @param + * @return + */ + public function deleteHelpModules() + { + $ilDB = $this->db; + $ilCtrl = $this->ctrl; - $this->checkPermission("write"); - - if (!is_array($_POST["id"]) || count($_POST["id"]) == 0) - { - ilUtil::sendInfo($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "editSettings"); - } - else - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("help_sure_delete_help_modules")); - $cgui->setCancel($lng->txt("cancel"), "editSettings"); - $cgui->setConfirm($lng->txt("delete"), "deleteHelpModules"); - - foreach ($_POST["id"] as $i) - { - $cgui->addItem("id[]", $i, $this->object->lookupModuleTitle($i)); - } - - $tpl->setContent($cgui->getHTML()); - } - } - - /** - * Delete help modules - * - * @param - * @return - */ - function deleteHelpModules() - { - $ilDB = $this->db; - $ilCtrl = $this->ctrl; + $this->checkPermission("write"); + + if (is_array($_POST["id"])) { + foreach ($_POST["id"] as $i) { + $this->object->deleteModule((int) $i); + } + } + + $ilCtrl->redirect($this, "editSettings"); + } + + /** + * Activate module + * + * @param + * @return + */ + public function activateModule() + { + $ilSetting = $this->settings; + $lng = $this->lng; + $ilCtrl = $this->ctrl; - $this->checkPermission("write"); - - if (is_array($_POST["id"])) - { - foreach ($_POST["id"] as $i) - { - $this->object->deleteModule((int) $i); - } - } - - $ilCtrl->redirect($this, "editSettings"); - } - - /** - * Activate module - * - * @param - * @return - */ - function activateModule() - { - $ilSetting = $this->settings; - $lng = $this->lng; - $ilCtrl = $this->ctrl; + $this->checkPermission("write"); + + $ilSetting->set("help_module", (int) $_GET["hm_id"]); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "editSettings"); + } + + /** + * Deactivate module + * + * @param + * @return + */ + public function deactivateModule() + { + $ilSetting = $this->settings; + $lng = $this->lng; + $ilCtrl = $this->ctrl; - $this->checkPermission("write"); - - $ilSetting->set("help_module", (int) $_GET["hm_id"]); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "editSettings"); - } - - /** - * Deactivate module - * - * @param - * @return - */ - function deactivateModule() - { - $ilSetting = $this->settings; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->checkPermission("write"); - - if ($ilSetting->get("help_module") == (int) $_GET["hm_id"]) - { - $ilSetting->set("help_module", ""); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - } - $ilCtrl->redirect($this, "editSettings"); - } - - /** - * Set mode - * - * @param - * @return - */ - function setMode() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilSetting = $this->settings; - - $this->checkPermission("write"); - - if ($this->checkPermissionBool("write")) - { - $ilSetting->set("help_mode", ilUtil::stripSlashes($_POST["help_mode"])); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - } - - $ilCtrl->redirect($this, "editSettings"); - } - + $this->checkPermission("write"); + + if ($ilSetting->get("help_module") == (int) $_GET["hm_id"]) { + $ilSetting->set("help_module", ""); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + } + $ilCtrl->redirect($this, "editSettings"); + } + + /** + * Set mode + * + * @param + * @return + */ + public function setMode() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilSetting = $this->settings; + $this->checkPermission("write"); + + if ($this->checkPermissionBool("write")) { + $ilSetting->set("help_mode", ilUtil::stripSlashes($_POST["help_mode"])); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + } + + $ilCtrl->redirect($this, "editSettings"); + } } -?> \ No newline at end of file diff --git a/Services/History/classes/class.ilHistory.php b/Services/History/classes/class.ilHistory.php index 42f5cb1d582a60fdebc8ad9e17496202d1341dcb..5033b3ff2e9cbf7ad7cd780cfeb5a7af6da7a1c2 100755 --- a/Services/History/classes/class.ilHistory.php +++ b/Services/History/classes/class.ilHistory.php @@ -10,314 +10,304 @@ class ilHistory { - /** - * Creates a new history entry for an object. The information text parameters - * have to be separated by comma. The information text has to be stored - * in a langage variable "hist__". This text can contain - * placeholders %1, %2, ... for each parameter. The placehoders are replaced - * by the parameters in ilHistoryTableGUI. - * - * Please note that the object type must be specified, if the object is not - * derived from ilObject. - * - * @param int $a_obj_id object id - * @param string $a_action action - * @param string $a_info_params information text parameters, separated by comma - * or as an array - * @param string $a_obj_type object type (must only be set, if object is not - * in object_data table) - * @param string $a_user_comment user comment - */ - static function _createEntry($a_obj_id, $a_action, $a_info_params = "", $a_obj_type = "", - $a_user_comment = "", $a_update_last = false) - { - global $DIC; + /** + * Creates a new history entry for an object. The information text parameters + * have to be separated by comma. The information text has to be stored + * in a langage variable "hist__". This text can contain + * placeholders %1, %2, ... for each parameter. The placehoders are replaced + * by the parameters in ilHistoryTableGUI. + * + * Please note that the object type must be specified, if the object is not + * derived from ilObject. + * + * @param int $a_obj_id object id + * @param string $a_action action + * @param string $a_info_params information text parameters, separated by comma + * or as an array + * @param string $a_obj_type object type (must only be set, if object is not + * in object_data table) + * @param string $a_user_comment user comment + */ + public static function _createEntry( + $a_obj_id, + $a_action, + $a_info_params = "", + $a_obj_type = "", + $a_user_comment = "", + $a_update_last = false + ) { + global $DIC; - $ilDB = $DIC->database(); - $ilUser = $DIC->user(); - - if ($a_obj_type == "") - { - $a_obj_type = ilObject::_lookupType($a_obj_id); - } - - if (is_array($a_info_params)) - { - foreach($a_info_params as $key => $param) - { - $a_info_params[$key] = str_replace(",", ",", $param); - } - $a_info_params = implode(",", $a_info_params); - } - - // get last entry of object - $last_entry_sql = "SELECT * FROM history WHERE ". - " obj_id = ".$ilDB->quote($a_obj_id, "integer")." AND ". - " obj_type = ".$ilDB->quote($a_obj_type, "text")." ORDER BY hdate DESC"; - $last_entry_set = $ilDB->query($last_entry_sql); - $last_entry = $ilDB->fetchAssoc($last_entry_set); - - // note: insert is forced if last entry already has a comment and a - // new comment is given too OR - // if entry should not be updated OR - // if current action or user id are not equal with last entry - if (($a_user_comment != "" && $last_entry["user_comment"] != "") - || !$a_update_last || $a_action != $last_entry["action"] - || $ilUser->getId() != $last_entry["usr_id"]) - { - $id = $ilDB->nextId("history"); - $ilDB->insert("history", array( - "id" => array("integer", $id), - "obj_id" => array("integer", $a_obj_id), - "obj_type" => array("text", $a_obj_type), - "action" => array("text", $a_action), - "hdate" => array("timestamp", ilUtil::now()), - "usr_id" => array("integer", $ilUser->getId()), - "info_params" => array("text", $a_info_params), - "user_comment" => array("clob", $a_user_comment) - )); - - /*$query = "INSERT INTO history (id, obj_id, obj_type, action, hdate, usr_id, info_params, user_comment) VALUES ". - "(". - $ilDB->quote($id).", ". - $ilDB->quote($a_obj_id).", ". - $ilDB->quote($a_obj_type).", ". - $ilDB->quote($a_action).", ". - "now(), ". - $ilDB->quote($ilUser->getId()).", ". - $ilDB->quote($a_info_params).", ". - $ilDB->quote($a_user_comment). - ")"; - $ilDB->query($query);*/ - } - else - { - // if entry should be updated, update user comment only - // if it is set (this means, user comment has been empty - // because if old and new comment are given, an INSERT is forced - // see if statement above) - //$uc_str = ($a_user_comment != "") - // ? ", user_comment = ".$ilDB->quote($a_user_comment) - // : ""; - /*$query = "UPDATE history SET ". - " hdate = now() ". - $uc_str. - " WHERE id = ".$ilDB->quote($last_entry["id"]); - $ilDB->query($query);*/ - - $fields = array( - "hdate" => array("timestamp", ilUtil::now()) - ); - if ($a_user_comment != "") - { - $fields["user_comment"] = array("clob", $a_user_comment); - } + $ilDB = $DIC->database(); + $ilUser = $DIC->user(); + + if ($a_obj_type == "") { + $a_obj_type = ilObject::_lookupType($a_obj_id); + } + + if (is_array($a_info_params)) { + foreach ($a_info_params as $key => $param) { + $a_info_params[$key] = str_replace(",", ",", $param); + } + $a_info_params = implode(",", $a_info_params); + } + + // get last entry of object + $last_entry_sql = "SELECT * FROM history WHERE " . + " obj_id = " . $ilDB->quote($a_obj_id, "integer") . " AND " . + " obj_type = " . $ilDB->quote($a_obj_type, "text") . " ORDER BY hdate DESC"; + $last_entry_set = $ilDB->query($last_entry_sql); + $last_entry = $ilDB->fetchAssoc($last_entry_set); + + // note: insert is forced if last entry already has a comment and a + // new comment is given too OR + // if entry should not be updated OR + // if current action or user id are not equal with last entry + if (($a_user_comment != "" && $last_entry["user_comment"] != "") + || !$a_update_last || $a_action != $last_entry["action"] + || $ilUser->getId() != $last_entry["usr_id"]) { + $id = $ilDB->nextId("history"); + $ilDB->insert("history", array( + "id" => array("integer", $id), + "obj_id" => array("integer", $a_obj_id), + "obj_type" => array("text", $a_obj_type), + "action" => array("text", $a_action), + "hdate" => array("timestamp", ilUtil::now()), + "usr_id" => array("integer", $ilUser->getId()), + "info_params" => array("text", $a_info_params), + "user_comment" => array("clob", $a_user_comment) + )); + + /*$query = "INSERT INTO history (id, obj_id, obj_type, action, hdate, usr_id, info_params, user_comment) VALUES ". + "(". + $ilDB->quote($id).", ". + $ilDB->quote($a_obj_id).", ". + $ilDB->quote($a_obj_type).", ". + $ilDB->quote($a_action).", ". + "now(), ". + $ilDB->quote($ilUser->getId()).", ". + $ilDB->quote($a_info_params).", ". + $ilDB->quote($a_user_comment). + ")"; + $ilDB->query($query);*/ + } else { + // if entry should be updated, update user comment only + // if it is set (this means, user comment has been empty + // because if old and new comment are given, an INSERT is forced + // see if statement above) + //$uc_str = ($a_user_comment != "") + // ? ", user_comment = ".$ilDB->quote($a_user_comment) + // : ""; + /*$query = "UPDATE history SET ". + " hdate = now() ". + $uc_str. + " WHERE id = ".$ilDB->quote($last_entry["id"]); + $ilDB->query($query);*/ + + $fields = array( + "hdate" => array("timestamp", ilUtil::now()) + ); + if ($a_user_comment != "") { + $fields["user_comment"] = array("clob", $a_user_comment); + } - $ilDB->update("history", $fields, array( - "id" => array("integer", $id) - )); + $ilDB->update("history", $fields, array( + "id" => array("integer", $id) + )); + } + } + + /** + * get all history entries for an object + * + * @param int $a_obj_id object id + * + * @return array array of history entries (arrays with keys + * "date", "user_id", "obj_id", "action", "info_params") + */ + public static function _getEntriesForObject($a_obj_id, $a_obj_type = "") + { + global $DIC; - } - - } - - /** - * get all history entries for an object - * - * @param int $a_obj_id object id - * - * @return array array of history entries (arrays with keys - * "date", "user_id", "obj_id", "action", "info_params") - */ - static function _getEntriesForObject($a_obj_id, $a_obj_type = "") - { - global $DIC; + $ilDB = $DIC->database(); - $ilDB = $DIC->database(); + if ($a_obj_type == "") { + $a_obj_type = ilObject::_lookupType($a_obj_id); + } + + $query = "SELECT * FROM history WHERE obj_id = " . + $ilDB->quote($a_obj_id, "integer") . " AND " . + "obj_type = " . $ilDB->quote($a_obj_type, "text") . + " ORDER BY hdate DESC"; - if ($a_obj_type == "") - { - $a_obj_type = ilObject::_lookupType($a_obj_id); - } - - $query = "SELECT * FROM history WHERE obj_id = ". - $ilDB->quote($a_obj_id, "integer")." AND ". - "obj_type = ".$ilDB->quote($a_obj_type, "text"). - " ORDER BY hdate DESC"; + $hist_set = $ilDB->query($query); - $hist_set = $ilDB->query($query); + $hist_items = array(); + while ($hist_rec = $ilDB->fetchAssoc($hist_set)) { + $hist_items[] = array("date" => $hist_rec["hdate"], + "user_id" => $hist_rec["usr_id"], + "obj_id" => $hist_rec["obj_id"], + "obj_type" => $hist_rec["obj_type"], + "action" => $hist_rec["action"], + "info_params" => $hist_rec["info_params"], + "user_comment" => $hist_rec["user_comment"], + "hist_entry_id" => $hist_rec["id"], + "title" => $hist_rec["title"]); + } - $hist_items = array(); - while ($hist_rec = $ilDB->fetchAssoc($hist_set)) - { - $hist_items[] = array("date" => $hist_rec["hdate"], - "user_id" => $hist_rec["usr_id"], - "obj_id" => $hist_rec["obj_id"], - "obj_type" => $hist_rec["obj_type"], - "action" => $hist_rec["action"], - "info_params" => $hist_rec["info_params"], - "user_comment" => $hist_rec["user_comment"], - "hist_entry_id" => $hist_rec["id"], - "title" => $hist_rec["title"]); - } + if ($a_obj_type == "lm") { + $query = "SELECT h.*, l.title as title FROM history h, lm_data l WHERE " . + " l.lm_id = " . $ilDB->quote($a_obj_id, "integer") . " AND " . + " l.obj_id = h.obj_id AND " . + " (h.obj_type=" . $ilDB->quote($a_obj_type . ":pg", "text") . " OR h.obj_type=" . $ilDB->quote($a_obj_type . ":st", "text") . ") " . + " ORDER BY h.hdate DESC"; + + $hist_set = $ilDB->query($query); + while ($hist_rec = $ilDB->fetchAssoc($hist_set)) { + $hist_items[] = array("date" => $hist_rec["hdate"], + "user_id" => $hist_rec["usr_id"], + "obj_id" => $hist_rec["obj_id"], + "obj_type" => $hist_rec["obj_type"], + "action" => $hist_rec["action"], + "info_params" => $hist_rec["info_params"], + "user_comment" => $hist_rec["user_comment"], + "hist_entry_id" => $hist_rec["id"], + "title" => $hist_rec["title"]); + } + usort($hist_items, array("ilHistory", "_compareHistArray")); + $hist_items2 = array_reverse($hist_items); + return $hist_items2; + } - if ($a_obj_type == "lm") - { - $query = "SELECT h.*, l.title as title FROM history h, lm_data l WHERE ". - " l.lm_id = ".$ilDB->quote($a_obj_id, "integer")." AND ". - " l.obj_id = h.obj_id AND ". - " (h.obj_type=".$ilDB->quote($a_obj_type.":pg", "text")." OR h.obj_type=".$ilDB->quote($a_obj_type.":st", "text").") ". - " ORDER BY h.hdate DESC"; - - $hist_set = $ilDB->query($query); - while ($hist_rec = $ilDB->fetchAssoc($hist_set)) - { - $hist_items[] = array("date" => $hist_rec["hdate"], - "user_id" => $hist_rec["usr_id"], - "obj_id" => $hist_rec["obj_id"], - "obj_type" => $hist_rec["obj_type"], - "action" => $hist_rec["action"], - "info_params" => $hist_rec["info_params"], - "user_comment" => $hist_rec["user_comment"], - "hist_entry_id" => $hist_rec["id"], - "title" => $hist_rec["title"]); - } - usort($hist_items, array("ilHistory", "_compareHistArray")); - $hist_items2 = array_reverse($hist_items); - return $hist_items2; - } + return $hist_items; + } - return $hist_items; - } + public static function _compareHistArray($a, $b) + { + if ($a["date"] == $b["date"]) { + return 0; + } + return ($a["date"] < $b["date"]) ? -1 : 1; + } - static function _compareHistArray($a, $b) - { - if ($a["date"] == $b["date"]) - { - return 0; - } - return ($a["date"] < $b["date"]) ? -1 : 1; - } + /** + * remove all history entries for an object + * + * @param int $a_obj_id object id + * + * @return boolean + */ + public static function _removeEntriesForObject($a_obj_id) + { + global $DIC; - /** - * remove all history entries for an object - * - * @param int $a_obj_id object id - * - * @return boolean - */ - static function _removeEntriesForObject($a_obj_id) - { - global $DIC; + $ilDB = $DIC->database(); - $ilDB = $DIC->database(); + $q = "DELETE FROM history WHERE obj_id = " . + $ilDB->quote($a_obj_id, "integer"); + $r = $ilDB->manipulate($q); + + return true; + } + + /** + * copy all history entries for an object + * + * @param integer $a_src_id source object id + * @param integer $a_dst_id destination object id + * @return boolean + */ + public static function _copyEntriesForObject($a_src_id, $a_dst_id) + { + global $DIC; - $q = "DELETE FROM history WHERE obj_id = ". - $ilDB->quote($a_obj_id, "integer"); - $r = $ilDB->manipulate($q); - - return true; - } - - /** - * copy all history entries for an object - * - * @param integer $a_src_id source object id - * @param integer $a_dst_id destination object id - * @return boolean - */ - static function _copyEntriesForObject($a_src_id,$a_dst_id) - { - global $DIC; + $ilDB = $DIC->database(); - $ilDB = $DIC->database(); + $q = "SELECT * FROM history WHERE obj_id = " . + $ilDB->quote($a_src_id, "integer"); + $r = $ilDB->query($q); + + while ($row = $ilDB->fetchObject($r)) { + $id = $ilDB->nextId("history"); + $ilDB->insert("history", array( + "id" => array("integer", $id), + "obj_id" => array("integer", $a_dst_id), + "obj_type" => array("text", $row->obj_type), + "action" => array("text", $row->action), + "hdate" => array("timestamp", ilUtil::now()), + "usr_id" => array("integer", $row->usr_id), + "info_params" => array("text", $row->info_params), + "user_comment" => array("clob", $row->user_comment) + )); - $q = "SELECT * FROM history WHERE obj_id = ". - $ilDB->quote($a_src_id, "integer"); - $r = $ilDB->query($q); - - while ($row = $ilDB->fetchObject($r)) - { - $id = $ilDB->nextId("history"); - $ilDB->insert("history", array( - "id" => array("integer", $id), - "obj_id" => array("integer", $a_dst_id), - "obj_type" => array("text", $row->obj_type), - "action" => array("text", $row->action), - "hdate" => array("timestamp", ilUtil::now()), - "usr_id" => array("integer", $row->usr_id), - "info_params" => array("text", $row->info_params), - "user_comment" => array("clob", $row->user_comment) - )); + /* + $q = "INSERT INTO history (obj_id, obj_type, action, hdate, usr_id, info_params, user_comment) VALUES ". + "(". + $ilDB->quote($a_dst_id).", ". + $ilDB->quote($row->obj_type).", ". + $ilDB->quote($row->action).", ". + $ilDB->quote($row->hdate).", ". + $ilDB->quote($row->usr_id).", ". + $ilDB->quote($row->info_params).", ". + $ilDB->quote($row->user_comment). + ")"; - /* - $q = "INSERT INTO history (obj_id, obj_type, action, hdate, usr_id, info_params, user_comment) VALUES ". - "(". - $ilDB->quote($a_dst_id).", ". - $ilDB->quote($row->obj_type).", ". - $ilDB->quote($row->action).", ". - $ilDB->quote($row->hdate).", ". - $ilDB->quote($row->usr_id).", ". - $ilDB->quote($row->info_params).", ". - $ilDB->quote($row->user_comment). - ")"; + $ilDB->query($q);*/ + } + + return true; + } + + /** + * returns a single history entry + * + * + */ + public static function _getEntryByHistoryID($a_hist_entry_id) + { + global $DIC; - $ilDB->query($q);*/ - } - - return true; - } - - /** - * returns a single history entry - * - * - */ - static function _getEntryByHistoryID($a_hist_entry_id) - { - global $DIC; + $ilDB = $DIC->database(); - $ilDB = $DIC->database(); + $q = "SELECT * FROM history WHERE id = " . + $ilDB->quote($a_hist_entry_id, "integer"); + $r = $ilDB->query($q); + + return $ilDB->fetchAssoc($r); + } + + /** + * Removes a single entry from the history. + * + * @param int $a_hist_entry_id The id of the entry to remove. + */ + public static function _removeEntryByHistoryID($a_hist_entry_id) + { + global $DIC; - $q = "SELECT * FROM history WHERE id = ". - $ilDB->quote($a_hist_entry_id, "integer"); - $r = $ilDB->query($q); - - return $ilDB->fetchAssoc($r); - } - - /** - * Removes a single entry from the history. - * - * @param int $a_hist_entry_id The id of the entry to remove. - */ - public static function _removeEntryByHistoryID($a_hist_entry_id) - { - global $DIC; + $ilDB = $DIC->database(); - $ilDB = $DIC->database(); + $q = "DELETE FROM history WHERE id = " . + $ilDB->quote($a_hist_entry_id, "integer"); + $ilDB->manipulate($q); + } + + /** + * Changes the user id of the specified history entry. + * + * @param int $a_hist_entry_id The history entry to change the user id. + * @param int $new_user_id The new user id. + */ + public static function _changeUserId($a_hist_entry_id, $new_user_id) + { + global $DIC; - $q = "DELETE FROM history WHERE id = ". - $ilDB->quote($a_hist_entry_id, "integer"); - $ilDB->manipulate($q); - } - - /** - * Changes the user id of the specified history entry. - * - * @param int $a_hist_entry_id The history entry to change the user id. - * @param int $new_user_id The new user id. - */ - public static function _changeUserId($a_hist_entry_id, $new_user_id) - { - global $DIC; + $ilDB = $DIC->database(); - $ilDB = $DIC->database(); - - $ilDB->update("history", - array("usr_id" => array("integer", $new_user_id)), - array("id" => array("integer", $a_hist_entry_id))); - } - + $ilDB->update( + "history", + array("usr_id" => array("integer", $new_user_id)), + array("id" => array("integer", $a_hist_entry_id)) + ); + } } // END class.ilHistory -?> diff --git a/Services/History/classes/class.ilHistoryTableGUI.php b/Services/History/classes/class.ilHistoryTableGUI.php index 5a173f53d272907620453aa13238b0ccba606163..ab89c15752146f789b8471a39709d165dc70a565 100644 --- a/Services/History/classes/class.ilHistoryTableGUI.php +++ b/Services/History/classes/class.ilHistoryTableGUI.php @@ -1,219 +1,216 @@ - -* @version $Id$ -* -* @ingroup ModuleHistory -*/ -class ilHistoryTableGUI extends ilTable2GUI -{ - protected $obj_id; - protected $obj_type; - protected $ref_id; - protected $ilCtrl; - - protected $comment_visibility = false; - - - function __construct($a_parent_obj, $a_parent_cmd, $a_obj_id, $a_obj_type = null) - { - global $DIC; - - $ilCtrl = $DIC->ctrl(); - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setObjId($a_obj_id); - $this->setObjType($a_obj_type); - $this->ilCtrl = $ilCtrl; - } - - /** - * Get data and put it into an array - */ - public function getDataFromDb() - { - $entries = ilHistory::_getEntriesForObject($this->getObjId(), $this->getObjType()); - $this->setData($entries); - } - - /** - * init table - */ - public function initTable() - { - $this->setRowTemplate("tpl.history_row.html", "Services/History"); - $this->setFormAction($this->ilCtrl->getFormAction($this->getParentObject())); - - $this->setTitle($this->lng->txt("history")); - $this->addColumn($this->lng->txt("user"), "", "25%"); - $this->addColumn($this->lng->txt("date"), "", "25%"); - $this->addColumn($this->lng->txt("action"), "", "50%"); - - $this->getDataFromDb(); - } - - /** - * Fill a single data row. - */ - protected function fillRow($a_set) - { - $this->tpl->setVariable("TXT_USER",ilUserUtil::getNamePresentation($a_set["user_id"], false,false)); - $this->tpl->setVariable('TXT_DATE', - ilDatePresentation::formatDate(new ilDateTime($a_set["date"],IL_CAL_DATETIME))); - $this->tpl->setVariable("TXT_ACTION", $this->createInfoText($a_set)); - - if ($this->getObjType() == "lm") - { - $obj_arr = explode(":", $a_set["obj_type"]); - switch ($obj_arr[1]) - { - case "st": - $img_type = "st"; - $class = "ilstructureobjectgui"; - $cmd = "view"; - break; - - case "pg": - $img_type = "pg"; - $class = "illmpageobjectgui"; - $cmd = "edit"; - break; - - default: - $img_type = $obj_arr[0]; - $class = ""; - $cmd = "view"; - break; - } - - $this->tpl->setCurrentBlock("item_icon"); - $this->tpl->setVariable("SRC_ICON", ilUtil::getImagePath("icon_".$img_type.".svg")); - $this->tpl->parseCurrentBlock(); - - if ($class != "") - { - $this->tpl->setCurrentBlock("item_link"); - $this->ilCtrl->setParameterByClass($class, "obj_id", $a_set["obj_id"]); - $this->tpl->setVariable("HREF_LINK", - $this->ilCtrl->getLinkTargetByClass($class, $cmd)); - $this->tpl->setVariable("TXT_LINK", $a_set["title"]); - $this->tpl->parseCurrentBlock(); - } - else - { - $this->tpl->setCurrentBlock("item_title"); - $this->tpl->setVariable("TXT_TITLE", - ilObject::_lookupTitle($a_set["obj_id"])); - $this->tpl->parseCurrentBlock(); - } - } - - if ($this->isCommentVisible() && $a_set["user_comment"] != "") - { - $this->tpl->setCurrentBlock("user_comment"); - $this->tpl->setVariable("TXT_COMMENT", $this->lng->txt("comment")); - $this->tpl->setVariable("TXT_USER_COMMENT", $a_set["user_comment"]); - $this->tpl->parseCurrentBlock(); - } - } - - /** - * format info parameters into info text - * @param $a_set - * @return mixed|string - */ - protected function createInfoText($a_set) - { - $info_params = explode(",", $a_set["info_params"]); - - switch($this->getObjType()) - { - case "lm": - $info_text = $this->lng->txt("hist_".str_replace(":", "_", $a_set["obj_type"]). - "_".$a_set["action"]); - break; - default: - $info_text = $this->lng->txt("hist_".str_replace(":", "_", $this->getObjType()). - "_".$a_set["action"]); - break; - } - - $i=1; - foreach($info_params as $info_param) - { - $info_text = str_replace("%".$i, $info_param, $info_text); - $i++; - } - - return $info_text; - } - - /** - * set comments visible - * - * @param $a_visible - */ - public function setCommentVisibility($a_visible) - { - $this->comment_visibility = (bool)$a_visible; - } - - /** - * comments visible? - * @return bool - */ - public function isCommentVisible() - { - return $this->comment_visibility; - } - - /** - * set object id - * @param $a_obj_id - */ - public function setObjId($a_obj_id) - { - $this->obj_id = $a_obj_id; - } - - /** - * get object id - * @return mixed - */ - public function getObjId() - { - return $this->obj_id; - } - - /** - * set object type (not required) - * @param $a_obj_type - */ - public function setObjType($a_obj_type) - { - $this->obj_type = $a_obj_type; - } - - /** - * get object type (if not set, it will be set via object id) - * @return mixed - */ - public function getObjType() - { - if(!$this->obj_type) - { - $this->setObjType(ilObject::_lookupType($this->getObjId())); - } - return $this->obj_type; - } -} \ No newline at end of file + +* @version $Id$ +* +* @ingroup ModuleHistory +*/ +class ilHistoryTableGUI extends ilTable2GUI +{ + protected $obj_id; + protected $obj_type; + protected $ref_id; + protected $ilCtrl; + + protected $comment_visibility = false; + + + public function __construct($a_parent_obj, $a_parent_cmd, $a_obj_id, $a_obj_type = null) + { + global $DIC; + + $ilCtrl = $DIC->ctrl(); + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setObjId($a_obj_id); + $this->setObjType($a_obj_type); + $this->ilCtrl = $ilCtrl; + } + + /** + * Get data and put it into an array + */ + public function getDataFromDb() + { + $entries = ilHistory::_getEntriesForObject($this->getObjId(), $this->getObjType()); + $this->setData($entries); + } + + /** + * init table + */ + public function initTable() + { + $this->setRowTemplate("tpl.history_row.html", "Services/History"); + $this->setFormAction($this->ilCtrl->getFormAction($this->getParentObject())); + + $this->setTitle($this->lng->txt("history")); + $this->addColumn($this->lng->txt("user"), "", "25%"); + $this->addColumn($this->lng->txt("date"), "", "25%"); + $this->addColumn($this->lng->txt("action"), "", "50%"); + + $this->getDataFromDb(); + } + + /** + * Fill a single data row. + */ + protected function fillRow($a_set) + { + $this->tpl->setVariable("TXT_USER", ilUserUtil::getNamePresentation($a_set["user_id"], false, false)); + $this->tpl->setVariable( + 'TXT_DATE', + ilDatePresentation::formatDate(new ilDateTime($a_set["date"], IL_CAL_DATETIME)) + ); + $this->tpl->setVariable("TXT_ACTION", $this->createInfoText($a_set)); + + if ($this->getObjType() == "lm") { + $obj_arr = explode(":", $a_set["obj_type"]); + switch ($obj_arr[1]) { + case "st": + $img_type = "st"; + $class = "ilstructureobjectgui"; + $cmd = "view"; + break; + + case "pg": + $img_type = "pg"; + $class = "illmpageobjectgui"; + $cmd = "edit"; + break; + + default: + $img_type = $obj_arr[0]; + $class = ""; + $cmd = "view"; + break; + } + + $this->tpl->setCurrentBlock("item_icon"); + $this->tpl->setVariable("SRC_ICON", ilUtil::getImagePath("icon_" . $img_type . ".svg")); + $this->tpl->parseCurrentBlock(); + + if ($class != "") { + $this->tpl->setCurrentBlock("item_link"); + $this->ilCtrl->setParameterByClass($class, "obj_id", $a_set["obj_id"]); + $this->tpl->setVariable( + "HREF_LINK", + $this->ilCtrl->getLinkTargetByClass($class, $cmd) + ); + $this->tpl->setVariable("TXT_LINK", $a_set["title"]); + $this->tpl->parseCurrentBlock(); + } else { + $this->tpl->setCurrentBlock("item_title"); + $this->tpl->setVariable( + "TXT_TITLE", + ilObject::_lookupTitle($a_set["obj_id"]) + ); + $this->tpl->parseCurrentBlock(); + } + } + + if ($this->isCommentVisible() && $a_set["user_comment"] != "") { + $this->tpl->setCurrentBlock("user_comment"); + $this->tpl->setVariable("TXT_COMMENT", $this->lng->txt("comment")); + $this->tpl->setVariable("TXT_USER_COMMENT", $a_set["user_comment"]); + $this->tpl->parseCurrentBlock(); + } + } + + /** + * format info parameters into info text + * @param $a_set + * @return mixed|string + */ + protected function createInfoText($a_set) + { + $info_params = explode(",", $a_set["info_params"]); + + switch ($this->getObjType()) { + case "lm": + $info_text = $this->lng->txt("hist_" . str_replace(":", "_", $a_set["obj_type"]) . + "_" . $a_set["action"]); + break; + default: + $info_text = $this->lng->txt("hist_" . str_replace(":", "_", $this->getObjType()) . + "_" . $a_set["action"]); + break; + } + + $i=1; + foreach ($info_params as $info_param) { + $info_text = str_replace("%" . $i, $info_param, $info_text); + $i++; + } + + return $info_text; + } + + /** + * set comments visible + * + * @param $a_visible + */ + public function setCommentVisibility($a_visible) + { + $this->comment_visibility = (bool) $a_visible; + } + + /** + * comments visible? + * @return bool + */ + public function isCommentVisible() + { + return $this->comment_visibility; + } + + /** + * set object id + * @param $a_obj_id + */ + public function setObjId($a_obj_id) + { + $this->obj_id = $a_obj_id; + } + + /** + * get object id + * @return mixed + */ + public function getObjId() + { + return $this->obj_id; + } + + /** + * set object type (not required) + * @param $a_obj_type + */ + public function setObjType($a_obj_type) + { + $this->obj_type = $a_obj_type; + } + + /** + * get object type (if not set, it will be set via object id) + * @return mixed + */ + public function getObjType() + { + if (!$this->obj_type) { + $this->setObjType(ilObject::_lookupType($this->getObjId())); + } + return $this->obj_type; + } +} diff --git a/Services/Imprint/classes/class.ilImprint.php b/Services/Imprint/classes/class.ilImprint.php index 1417ea5eb756e41fd6e2d036d240da1da0e81d82..d5abe25256f61e8024b61e36adca06ec80744f42 100644 --- a/Services/Imprint/classes/class.ilImprint.php +++ b/Services/Imprint/classes/class.ilImprint.php @@ -12,20 +12,18 @@ include_once("./Services/COPage/classes/class.ilPageObject.php"); */ class ilImprint extends ilPageObject { - /** - * Get parent type - * - * @return string parent type - */ - function getParentType() - { - return "impr"; - } + /** + * Get parent type + * + * @return string parent type + */ + public function getParentType() + { + return "impr"; + } - public static function isActive() - { - return self::_lookupActive(1, "impr"); - } + public static function isActive() + { + return self::_lookupActive(1, "impr"); + } } - -?> \ No newline at end of file diff --git a/Services/Imprint/classes/class.ilImprintConfig.php b/Services/Imprint/classes/class.ilImprintConfig.php index 22deec6a96e76c536e7d3717ac689db39c4ed45c..21adb187b79a443091878cdb97fee3a7cff6eedd 100644 --- a/Services/Imprint/classes/class.ilImprintConfig.php +++ b/Services/Imprint/classes/class.ilImprintConfig.php @@ -5,7 +5,7 @@ include_once("./Services/COPage/classes/class.ilPageConfig.php"); /** - * Imprint page configuration + * Imprint page configuration * * @author Alex Killing * @version $Id$ @@ -13,17 +13,14 @@ include_once("./Services/COPage/classes/class.ilPageConfig.php"); */ class ilImprintConfig extends ilPageConfig { - /** - * Init - */ - function init() - { - $this->setPreventHTMLUnmasking(true); - $this->setEnableInternalLinks(false); - $this->setEnableWikiLinks(false); - $this->setEnableActivation(true); - } - + /** + * Init + */ + public function init() + { + $this->setPreventHTMLUnmasking(true); + $this->setEnableInternalLinks(false); + $this->setEnableWikiLinks(false); + $this->setEnableActivation(true); + } } - -?> diff --git a/Services/Imprint/classes/class.ilImprintGUI.php b/Services/Imprint/classes/class.ilImprintGUI.php index 015634dba9bbcedba45dafcc83c976eed6113632..ec631efd0456e45e5692725ad5e2ac678b81dce0 100644 --- a/Services/Imprint/classes/class.ilImprintGUI.php +++ b/Services/Imprint/classes/class.ilImprintGUI.php @@ -8,139 +8,137 @@ require_once("./Services/Imprint/classes/class.ilImprint.php"); * Class ilImprintGUI * * @author Jörg Lützenkirchen -* +* * @ilCtrl_Calls ilImprintGUI: ilPageEditorGUI, ilEditClipboardGUI, ilMediaPoolTargetSelector * @ilCtrl_Calls ilImprintGUI: ilPublicUserProfileGUI, ilPageObjectGUI -* +* * @ingroup ModulesImprint */ class ilImprintGUI extends ilPageObjectGUI { - /** - * @var ilLocatorGUI - */ - protected $locator; + /** + * @var ilLocatorGUI + */ + protected $locator; - /** - * @var ilMainMenuGUI - */ - protected $main_menu; + /** + * @var ilMainMenuGUI + */ + protected $main_menu; - /** - * Constructor - */ - public function __construct() - { - global $DIC; + /** + * Constructor + */ + public function __construct() + { + global $DIC; - $this->tpl = $DIC["tpl"]; - $this->ctrl = $DIC->ctrl(); - $this->locator = $DIC["ilLocator"]; - $this->lng = $DIC->language(); - $this->main_menu = $DIC["ilMainMenu"]; - $tpl = $DIC["tpl"]; - - if(!ilImprint::_exists("impr", 1)) - { - $page = new ilImprint("impr"); - $page->setId(1); - $page->create(); - } + $this->tpl = $DIC["tpl"]; + $this->ctrl = $DIC->ctrl(); + $this->locator = $DIC["ilLocator"]; + $this->lng = $DIC->language(); + $this->main_menu = $DIC["ilMainMenu"]; + $tpl = $DIC["tpl"]; + + if (!ilImprint::_exists("impr", 1)) { + $page = new ilImprint("impr"); + $page->setId(1); + $page->create(); + } - // there is only 1 imprint page - parent::__construct("impr", 1); - - // content style (using system defaults) - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - - $tpl->setCurrentBlock("SyntaxStyle"); - $tpl->setVariable("LOCATION_SYNTAX_STYLESHEET", - ilObjStyleSheet::getSyntaxStylePath()); - $tpl->parseCurrentBlock(); - - $tpl->setCurrentBlock("ContentStyle"); - $tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath(0)); - $tpl->parseCurrentBlock(); - } - - /** - * execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - $ilLocator = $this->locator; - $lng = $this->lng; - - if($_REQUEST["baseClass"] == "ilImprintGUI") - { - $this->renderFullscreen(); - } - - $next_class = $ilCtrl->getNextClass($this); - - $title = $lng->txt("adm_imprint"); - - switch($next_class) - { - case "ilpageobjectgui": - die("Deprecated. ilImprintGUI gui forwarding to ilpageobject"); - return; - - default: - $this->setPresentationTitle($title); + // there is only 1 imprint page + parent::__construct("impr", 1); + + // content style (using system defaults) + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + + $tpl->setCurrentBlock("SyntaxStyle"); + $tpl->setVariable( + "LOCATION_SYNTAX_STYLESHEET", + ilObjStyleSheet::getSyntaxStylePath() + ); + $tpl->parseCurrentBlock(); + + $tpl->setCurrentBlock("ContentStyle"); + $tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath(0) + ); + $tpl->parseCurrentBlock(); + } + + /** + * execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $ilLocator = $this->locator; + $lng = $this->lng; + + if ($_REQUEST["baseClass"] == "ilImprintGUI") { + $this->renderFullscreen(); + } + + $next_class = $ilCtrl->getNextClass($this); + + $title = $lng->txt("adm_imprint"); + + switch ($next_class) { + case "ilpageobjectgui": + die("Deprecated. ilImprintGUI gui forwarding to ilpageobject"); + return; + + default: + $this->setPresentationTitle($title); - $ilLocator->addItem($title, - $ilCtrl->getLinkTarget($this, "preview")); - - return parent::executeCommand(); - } - } - - function postOutputProcessing($a_output) - { - $lng = $this->lng; - - if($this->getOutputMode() == IL_PAGE_PREVIEW) - { - if(!$this->getPageObject()->getActive()) - { - ilUtil::sendInfo($lng->txt("adm_imprint_inactive")); - } - } - - return $a_output; - } - - protected function renderFullscreen() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilMainMenu = $this->main_menu; - - if(!ilImprint::isActive()) - { - ilUtil::redirect("ilias.php?baseClass=ilPersonalDesktopGUI"); - } - - $tpl->getStandardTemplate(); - - $this->setRawPageContent(true); - $html = $this->showPage(); - - $itpl = new ilTemplate("tpl.imprint.html", true, true, "Services/Imprint"); - $itpl->setVariable("PAGE_TITLE", $lng->txt("imprint")); - $itpl->setVariable("IMPRINT", $html); - unset($html); - - $tpl->setContent($itpl->get()); - - $ilMainMenu->showLogoOnly(true); - - echo $tpl->show("DEFAULT", true, false); - exit(); - } + $ilLocator->addItem( + $title, + $ilCtrl->getLinkTarget($this, "preview") + ); + + return parent::executeCommand(); + } + } + + public function postOutputProcessing($a_output) + { + $lng = $this->lng; + + if ($this->getOutputMode() == IL_PAGE_PREVIEW) { + if (!$this->getPageObject()->getActive()) { + ilUtil::sendInfo($lng->txt("adm_imprint_inactive")); + } + } + + return $a_output; + } + + protected function renderFullscreen() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilMainMenu = $this->main_menu; + + if (!ilImprint::isActive()) { + ilUtil::redirect("ilias.php?baseClass=ilPersonalDesktopGUI"); + } + + $tpl->getStandardTemplate(); + + $this->setRawPageContent(true); + $html = $this->showPage(); + + $itpl = new ilTemplate("tpl.imprint.html", true, true, "Services/Imprint"); + $itpl->setVariable("PAGE_TITLE", $lng->txt("imprint")); + $itpl->setVariable("IMPRINT", $html); + unset($html); + + $tpl->setContent($itpl->get()); + + $ilMainMenu->showLogoOnly(true); + + echo $tpl->show("DEFAULT", true, false); + exit(); + } } - -?> \ No newline at end of file diff --git a/Services/InfoScreen/classes/class.ilInfoScreenGUI.php b/Services/InfoScreen/classes/class.ilInfoScreenGUI.php index 7e4cd6028a510e5850080917d8308be91ab206fa..89645fcfefebd23dbf711aa6be5c0c17ea8b5427 100644 --- a/Services/InfoScreen/classes/class.ilInfoScreenGUI.php +++ b/Services/InfoScreen/classes/class.ilInfoScreenGUI.php @@ -17,1321 +17,1242 @@ */ class ilInfoScreenGUI { - /** - * @var ilTabsGUI - */ - protected $tabs_gui; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilTree - */ - protected $tree; - - /** - * @var ilSetting - */ - protected $settings; - - var $lng; - var $ctrl; - var $gui_object; - var $top_buttons = array(); - var $top_formbuttons = array(); - var $hiddenelements = array(); - var $table_class = "il_InfoScreen"; - var $open_form_tag = true; - var $close_form_tag = true; - - /** - * @var int|null - */ - protected $contextRefId = null; - - /** - * @var int|null - */ - protected $contextObjId = null; - - /** - * @var string|null - */ - protected $contentObjType = null; - - /** - * a form action parameter. if set a form is generated - */ - var $form_action; - - /** - * Constructor - * - * @param object $a_gui_object GUI instance of related object - * (ilCouseGUI, ilTestGUI, ...) - */ - function __construct($a_gui_object) - { - global $DIC; - - $this->rbacsystem = $DIC->rbac()->system(); - $this->tpl = $DIC["tpl"]; - $this->access = $DIC->access(); - $this->user = $DIC->user(); - $this->tree = $DIC->repositoryTree(); - $this->settings = $DIC->settings(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilTabs = $DIC->tabs(); - - $this->ctrl = $ilCtrl; - $this->lng = $lng; - $this->tabs_gui = $ilTabs; - $this->gui_object = $a_gui_object; - $this->sec_nr = 0; - $this->private_notes_enabled = false; - $this->news_enabled = false; - $this->feedback_enabled = false; - $this->learning_progress_enabled = false; - $this->form_action = ""; - $this->top_formbuttons = array(); - $this->hiddenelements = array(); - } - - /** - * execute command - */ - function executeCommand() - { - $rbacsystem = $this->rbacsystem; - $tpl = $this->tpl; - $ilAccess = $this->access; - - $next_class = $this->ctrl->getNextClass($this); - - $cmd = $this->ctrl->getCmd("showSummary"); - $this->ctrl->setReturn($this, "showSummary"); - - $this->setTabs(); - - switch($next_class) - { - case "ilnotegui": - $this->showSummary(); // forwards command - break; - - case "ilcolumngui": - $this->showSummary(); - break; - - case "ilpublicuserprofilegui": - include_once("./Services/User/classes/class.ilPublicUserProfileGUI.php"); - $user_profile = new ilPublicUserProfileGUI($_GET["user_id"]); - $user_profile->setBackUrl($this->ctrl->getLinkTarget($this, "showSummary")); - $html = $this->ctrl->forwardCommand($user_profile); - $tpl->setContent($html); - break; - - case "ilcommonactiondispatchergui": - include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); - $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); - $this->ctrl->forwardCommand($gui); - break; - - default: - return $this->$cmd(); - break; - } - return true; - } - - /** - * Set table class - * - * @param string table class - */ - function setTableClass($a_val) - { - $this->table_class = $a_val; - } - - /** - * Get table class - * - * @return string table class - */ - function getTableClass() - { - return $this->table_class; - } - - /** - * enable notes - */ - function enablePrivateNotes($a_enable = true) - { - $this->private_notes_enabled = $a_enable; - } - - /** - * enable learning progress - */ - function enableLearningProgress($a_enable = true) - { - $this->learning_progress_enabled = $a_enable; - } - - - /** - * enable feedback - */ - function enableFeedback($a_enable = true) - { - $this->feedback_enabled = $a_enable; - } - - /** - * enable news - */ - function enableNews($a_enable = true) - { - $this->news_enabled = $a_enable; - } - - /** - * enable news editing - */ - function enableNewsEditing($a_enable = true) - { - $this->news_editing = $a_enable; - } - - /** - * This function is supposed to be used for block type specific - * properties, that should be passed to ilBlockGUI->setProperty - * - * @param string $a_property property name - * @param string $a_value property value - */ - function setBlockProperty($a_block_type, $a_property, $a_value) - { - $this->block_property[$a_block_type][$a_property] = $a_value; - } - - function getAllBlockProperties() - { - return $this->block_property; - } - - /** - * add a new section - */ - function addSection($a_title) - { - $this->sec_nr++; - $this->section[$this->sec_nr]["title"] = $a_title; - $this->section[$this->sec_nr]["hidden"] = (bool)$this->hidden; - } - - /** - * set a form action - */ - function setFormAction($a_form_action) - { - $this->form_action = $a_form_action; - } - - /** - * remove form action - */ - function removeFormAction() - { - $this->form_action = ""; - } - - /** - * add a property to current section - * - * @param string $a_name property name string - * @param string $a_value property value - * @param string $a_link link (will link the property value string) - */ - function addProperty($a_name, $a_value, $a_link = "") - { - $this->section[$this->sec_nr]["properties"][] = - array("name" => $a_name, "value" => $a_value, - "link" => $a_link); - } - - /** - * add a property to current section - */ - function addPropertyCheckbox($a_name, $a_checkbox_name, $a_checkbox_value, $a_checkbox_label = "", $a_checkbox_checked = false) - { - $checkbox = "$a_checkbox_label"; - } - $this->section[$this->sec_nr]["properties"][] = - array("name" => $a_name, "value" => $checkbox); - } - - /** - * add a property to current section - */ - function addPropertyTextinput($a_name, $a_input_name, $a_input_value = "", $a_input_size = "", $direct_button_command = "", $direct_button_label = "", $direct_button_primary = false) - { - $input = ""; - } - $input .= ""; - $this->section[$this->sec_nr]["properties"][] = - array("name" => "", "value" => $input); - } - - /** - * add a property to current section - */ - function addButton($a_title, $a_link, $a_frame = "", $a_position = "top", $a_primary = false) - { - if ($a_position == "top") - { - $this->top_buttons[] = - array("title" => $a_title,"link" => $a_link,"target" => $a_frame,"primary" => $a_primary); - } - } - - /** - * add a form button to the info screen - * the form buttons are only valid if a form action is set - */ - function addFormButton($a_command, $a_title, $a_position = "top") - { - if ($a_position == "top") - { - array_push($this->top_formbuttons, - array("command" => $a_command, "title" => $a_title) - ); - } - } - - function addHiddenElement($a_name, $a_value) - { - array_push($this->hiddenelements, array("name" => $a_name, "value" => $a_value)); - } - - /** - * add standard meta data sections - */ - function addMetaDataSections($a_rep_obj_id,$a_obj_id, $a_type) - { - $lng = $this->lng; - - $lng->loadLanguageModule("meta"); - - include_once("./Services/MetaData/classes/class.ilMD.php"); - $md = new ilMD($a_rep_obj_id,$a_obj_id, $a_type); - - if ($md_gen = $md->getGeneral()) - { - // get first descrption - // The description is shown on the top of the page. - // Thus it is not necessary to show it again. - foreach($md_gen->getDescriptionIds() as $id) - { - $md_des = $md_gen->getDescription($id); - $description = $md_des->getDescription(); - break; - } - - // get language(s) - $langs = array(); - foreach($ids = $md_gen->getLanguageIds() as $id) - { - $md_lan = $md_gen->getLanguage($id); - if ($md_lan->getLanguageCode() != "") - { - $langs[] = $lng->txt("meta_l_".$md_lan->getLanguageCode()); - } - } - $langs = implode($langs, ", "); - - // keywords - $keywords = array(); - foreach($ids = $md_gen->getKeywordIds() as $id) - { - $md_key = $md_gen->getKeyword($id); - $keywords[] = $md_key->getKeyword(); - } - $keywords = implode($keywords, ", "); - } - - // authors - if(is_object($lifecycle = $md->getLifecycle())) - { - $sep = $author = ""; - foreach(($ids = $lifecycle->getContributeIds()) as $con_id) - { - $md_con = $lifecycle->getContribute($con_id); - if ($md_con->getRole() == "Author") - { - foreach($ent_ids = $md_con->getEntityIds() as $ent_id) - { - $md_ent = $md_con->getEntity($ent_id); - $author = $author.$sep.$md_ent->getEntity(); - $sep = ", "; - } - } - } - } - - // copyright - $copyright = ""; - if(is_object($rights = $md->getRights())) - { - include_once('Services/MetaData/classes/class.ilMDUtils.php'); - $copyright = ilMDUtils::_parseCopyright($rights->getDescription()); - } - - // learning time - #if(is_object($educational = $md->getEducational())) - #{ - # $learning_time = $educational->getTypicalLearningTime(); - #} - $learning_time = ""; - if(is_object($educational = $md->getEducational())) - { - if($seconds = $educational->getTypicalLearningTimeSeconds()) - { - $learning_time = ilDatePresentation::secondsToString($seconds); - } - } - - - // output - - // description - if ($description != "") - { - $this->addSection($lng->txt("description")); - $this->addProperty("", nl2br($description)); - } - - // general section - $this->addSection($lng->txt("meta_general")); - if ($langs != "") // language - { - $this->addProperty($lng->txt("language"), - $langs); - } - if ($keywords != "") // keywords - { - $this->addProperty($lng->txt("keywords"), - $keywords); - } - if ($author != "") // author - { - $this->addProperty($lng->txt("author"), - $author); - } - if ($copyright != "") // copyright - { - $this->addProperty($lng->txt("meta_copyright"), - $copyright); - } - if ($learning_time != "") // typical learning time - { - $this->addProperty($lng->txt("meta_typical_learning_time"), - $learning_time); - } - } - - /** - * add standard object section - */ - function addObjectSections() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - $ilAccess = $this->access; - $tree = $this->tree; - - $this->addSection($lng->txt("additional_info")); - $a_obj = $this->gui_object->object; + /** + * @var ilTabsGUI + */ + protected $tabs_gui; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilTree + */ + protected $tree; + + /** + * @var ilSetting + */ + protected $settings; + + public $lng; + public $ctrl; + public $gui_object; + public $top_buttons = array(); + public $top_formbuttons = array(); + public $hiddenelements = array(); + public $table_class = "il_InfoScreen"; + public $open_form_tag = true; + public $close_form_tag = true; + + /** + * @var int|null + */ + protected $contextRefId = null; + + /** + * @var int|null + */ + protected $contextObjId = null; + + /** + * @var string|null + */ + protected $contentObjType = null; + + /** + * a form action parameter. if set a form is generated + */ + public $form_action; + + /** + * Constructor + * + * @param object $a_gui_object GUI instance of related object + * (ilCouseGUI, ilTestGUI, ...) + */ + public function __construct($a_gui_object) + { + global $DIC; + + $this->rbacsystem = $DIC->rbac()->system(); + $this->tpl = $DIC["tpl"]; + $this->access = $DIC->access(); + $this->user = $DIC->user(); + $this->tree = $DIC->repositoryTree(); + $this->settings = $DIC->settings(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilTabs = $DIC->tabs(); + + $this->ctrl = $ilCtrl; + $this->lng = $lng; + $this->tabs_gui = $ilTabs; + $this->gui_object = $a_gui_object; + $this->sec_nr = 0; + $this->private_notes_enabled = false; + $this->news_enabled = false; + $this->feedback_enabled = false; + $this->learning_progress_enabled = false; + $this->form_action = ""; + $this->top_formbuttons = array(); + $this->hiddenelements = array(); + } + + /** + * execute command + */ + public function executeCommand() + { + $rbacsystem = $this->rbacsystem; + $tpl = $this->tpl; + $ilAccess = $this->access; + + $next_class = $this->ctrl->getNextClass($this); + + $cmd = $this->ctrl->getCmd("showSummary"); + $this->ctrl->setReturn($this, "showSummary"); + + $this->setTabs(); + + switch ($next_class) { + case "ilnotegui": + $this->showSummary(); // forwards command + break; + + case "ilcolumngui": + $this->showSummary(); + break; + + case "ilpublicuserprofilegui": + include_once("./Services/User/classes/class.ilPublicUserProfileGUI.php"); + $user_profile = new ilPublicUserProfileGUI($_GET["user_id"]); + $user_profile->setBackUrl($this->ctrl->getLinkTarget($this, "showSummary")); + $html = $this->ctrl->forwardCommand($user_profile); + $tpl->setContent($html); + break; + + case "ilcommonactiondispatchergui": + include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); + $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); + $this->ctrl->forwardCommand($gui); + break; - // links to the object - if (is_object($a_obj)) - { - // permanent link - $type = $a_obj->getType(); - $ref_id = $a_obj->getRefId(); - - if($ref_id) - { - include_once 'Services/WebServices/ECS/classes/class.ilECSServerSettings.php'; - if(ilECSServerSettings::getInstance()->activeServerExists()) - { - $this->addProperty($lng->txt("object_id"), - $a_obj->getId() - ); - } - - include_once 'Services/PermanentLink/classes/class.ilPermanentLinkGUI.php'; - $pm = new ilPermanentLinkGUI($type, $ref_id); - $pm->setIncludePermanentLinkText(false); - $pm->setAlignCenter(false); - $this->addProperty($lng->txt("perma_link"), - $pm->getHTML(), - "" - ); - - // bookmarks - - // links to resource - if ($ilAccess->checkAccess("write", "", $ref_id) || - $ilAccess->checkAccess("edit_permissions", "", $ref_id)) - { - $obj_id = $a_obj->getId(); - $rs = ilObject::_getAllReferences($obj_id); - $refs = array(); - foreach($rs as $r) - { - if ($tree->isInTree($r)) - { - $refs[] = $r; - } - } - if (count($refs) > 1) - { - $links = $sep = ""; - foreach($refs as $r) - { - $cont_loc = new ilLocatorGUI(); - $cont_loc->addContextItems($r, true); - $links.= $sep.$cont_loc->getHTML(); - $sep = "
                  "; - } - - $this->addProperty($lng->txt("res_links"), - '
                  '.$links.'
                  ' - ); - } - } - } - } + default: + return $this->$cmd(); + break; + } + return true; + } + + /** + * Set table class + * + * @param string table class + */ + public function setTableClass($a_val) + { + $this->table_class = $a_val; + } + + /** + * Get table class + * + * @return string table class + */ + public function getTableClass() + { + return $this->table_class; + } + + /** + * enable notes + */ + public function enablePrivateNotes($a_enable = true) + { + $this->private_notes_enabled = $a_enable; + } + + /** + * enable learning progress + */ + public function enableLearningProgress($a_enable = true) + { + $this->learning_progress_enabled = $a_enable; + } + + + /** + * enable feedback + */ + public function enableFeedback($a_enable = true) + { + $this->feedback_enabled = $a_enable; + } + + /** + * enable news + */ + public function enableNews($a_enable = true) + { + $this->news_enabled = $a_enable; + } + + /** + * enable news editing + */ + public function enableNewsEditing($a_enable = true) + { + $this->news_editing = $a_enable; + } + + /** + * This function is supposed to be used for block type specific + * properties, that should be passed to ilBlockGUI->setProperty + * + * @param string $a_property property name + * @param string $a_value property value + */ + public function setBlockProperty($a_block_type, $a_property, $a_value) + { + $this->block_property[$a_block_type][$a_property] = $a_value; + } + + public function getAllBlockProperties() + { + return $this->block_property; + } + + /** + * add a new section + */ + public function addSection($a_title) + { + $this->sec_nr++; + $this->section[$this->sec_nr]["title"] = $a_title; + $this->section[$this->sec_nr]["hidden"] = (bool) $this->hidden; + } + + /** + * set a form action + */ + public function setFormAction($a_form_action) + { + $this->form_action = $a_form_action; + } + + /** + * remove form action + */ + public function removeFormAction() + { + $this->form_action = ""; + } + + /** + * add a property to current section + * + * @param string $a_name property name string + * @param string $a_value property value + * @param string $a_link link (will link the property value string) + */ + public function addProperty($a_name, $a_value, $a_link = "") + { + $this->section[$this->sec_nr]["properties"][] = + array("name" => $a_name, "value" => $a_value, + "link" => $a_link); + } + + /** + * add a property to current section + */ + public function addPropertyCheckbox($a_name, $a_checkbox_name, $a_checkbox_value, $a_checkbox_label = "", $a_checkbox_checked = false) + { + $checkbox = "$a_checkbox_label"; + } + $this->section[$this->sec_nr]["properties"][] = + array("name" => $a_name, "value" => $checkbox); + } + + /** + * add a property to current section + */ + public function addPropertyTextinput($a_name, $a_input_name, $a_input_value = "", $a_input_size = "", $direct_button_command = "", $direct_button_label = "", $direct_button_primary = false) + { + $input = ""; + } + $input .= ""; + $this->section[$this->sec_nr]["properties"][] = + array("name" => "", "value" => $input); + } + + /** + * add a property to current section + */ + public function addButton($a_title, $a_link, $a_frame = "", $a_position = "top", $a_primary = false) + { + if ($a_position == "top") { + $this->top_buttons[] = + array("title" => $a_title,"link" => $a_link,"target" => $a_frame,"primary" => $a_primary); + } + } + + /** + * add a form button to the info screen + * the form buttons are only valid if a form action is set + */ + public function addFormButton($a_command, $a_title, $a_position = "top") + { + if ($a_position == "top") { + array_push( + $this->top_formbuttons, + array("command" => $a_command, "title" => $a_title) + ); + } + } + + public function addHiddenElement($a_name, $a_value) + { + array_push($this->hiddenelements, array("name" => $a_name, "value" => $a_value)); + } + + /** + * add standard meta data sections + */ + public function addMetaDataSections($a_rep_obj_id, $a_obj_id, $a_type) + { + $lng = $this->lng; + + $lng->loadLanguageModule("meta"); + + include_once("./Services/MetaData/classes/class.ilMD.php"); + $md = new ilMD($a_rep_obj_id, $a_obj_id, $a_type); + + if ($md_gen = $md->getGeneral()) { + // get first descrption + // The description is shown on the top of the page. + // Thus it is not necessary to show it again. + foreach ($md_gen->getDescriptionIds() as $id) { + $md_des = $md_gen->getDescription($id); + $description = $md_des->getDescription(); + break; + } + + // get language(s) + $langs = array(); + foreach ($ids = $md_gen->getLanguageIds() as $id) { + $md_lan = $md_gen->getLanguage($id); + if ($md_lan->getLanguageCode() != "") { + $langs[] = $lng->txt("meta_l_" . $md_lan->getLanguageCode()); + } + } + $langs = implode($langs, ", "); + + // keywords + $keywords = array(); + foreach ($ids = $md_gen->getKeywordIds() as $id) { + $md_key = $md_gen->getKeyword($id); + $keywords[] = $md_key->getKeyword(); + } + $keywords = implode($keywords, ", "); + } + + // authors + if (is_object($lifecycle = $md->getLifecycle())) { + $sep = $author = ""; + foreach (($ids = $lifecycle->getContributeIds()) as $con_id) { + $md_con = $lifecycle->getContribute($con_id); + if ($md_con->getRole() == "Author") { + foreach ($ent_ids = $md_con->getEntityIds() as $ent_id) { + $md_ent = $md_con->getEntity($ent_id); + $author = $author . $sep . $md_ent->getEntity(); + $sep = ", "; + } + } + } + } + + // copyright + $copyright = ""; + if (is_object($rights = $md->getRights())) { + include_once('Services/MetaData/classes/class.ilMDUtils.php'); + $copyright = ilMDUtils::_parseCopyright($rights->getDescription()); + } + + // learning time + #if(is_object($educational = $md->getEducational())) + #{ + # $learning_time = $educational->getTypicalLearningTime(); + #} + $learning_time = ""; + if (is_object($educational = $md->getEducational())) { + if ($seconds = $educational->getTypicalLearningTimeSeconds()) { + $learning_time = ilDatePresentation::secondsToString($seconds); + } + } + + + // output + + // description + if ($description != "") { + $this->addSection($lng->txt("description")); + $this->addProperty("", nl2br($description)); + } + + // general section + $this->addSection($lng->txt("meta_general")); + if ($langs != "") { // language + $this->addProperty( + $lng->txt("language"), + $langs + ); + } + if ($keywords != "") { // keywords + $this->addProperty( + $lng->txt("keywords"), + $keywords + ); + } + if ($author != "") { // author + $this->addProperty( + $lng->txt("author"), + $author + ); + } + if ($copyright != "") { // copyright + $this->addProperty( + $lng->txt("meta_copyright"), + $copyright + ); + } + if ($learning_time != "") { // typical learning time + $this->addProperty( + $lng->txt("meta_typical_learning_time"), + $learning_time + ); + } + } + + /** + * add standard object section + */ + public function addObjectSections() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + $ilAccess = $this->access; + $tree = $this->tree; + + $this->addSection($lng->txt("additional_info")); + $a_obj = $this->gui_object->object; + + // links to the object + if (is_object($a_obj)) { + // permanent link + $type = $a_obj->getType(); + $ref_id = $a_obj->getRefId(); + + if ($ref_id) { + include_once 'Services/WebServices/ECS/classes/class.ilECSServerSettings.php'; + if (ilECSServerSettings::getInstance()->activeServerExists()) { + $this->addProperty( + $lng->txt("object_id"), + $a_obj->getId() + ); + } + + include_once 'Services/PermanentLink/classes/class.ilPermanentLinkGUI.php'; + $pm = new ilPermanentLinkGUI($type, $ref_id); + $pm->setIncludePermanentLinkText(false); + $pm->setAlignCenter(false); + $this->addProperty( + $lng->txt("perma_link"), + $pm->getHTML(), + "" + ); + + // bookmarks + + // links to resource + if ($ilAccess->checkAccess("write", "", $ref_id) || + $ilAccess->checkAccess("edit_permissions", "", $ref_id)) { + $obj_id = $a_obj->getId(); + $rs = ilObject::_getAllReferences($obj_id); + $refs = array(); + foreach ($rs as $r) { + if ($tree->isInTree($r)) { + $refs[] = $r; + } + } + if (count($refs) > 1) { + $links = $sep = ""; + foreach ($refs as $r) { + $cont_loc = new ilLocatorGUI(); + $cont_loc->addContextItems($r, true); + $links.= $sep . $cont_loc->getHTML(); + $sep = "
                  "; + } + + $this->addProperty( + $lng->txt("res_links"), + '
                  ' . $links . '
                  ' + ); + } + } + } + } - // creation date - $this->addProperty( - $lng->txt("create_date"), - ilDatePresentation::formatDate(new ilDateTime($a_obj->getCreateDate(),IL_CAL_DATETIME))); - - // owner - if ($ilUser->getId() != ANONYMOUS_USER_ID and $a_obj->getOwner()) - { - include_once './Services/Object/classes/class.ilObjectFactory.php'; - include_once './Services/User/classes/class.ilObjUser.php'; - - if(ilObjUser::userExists(array($a_obj->getOwner()))) - { - $ownerObj = ilObjectFactory::getInstanceByObjId($a_obj->getOwner(),false); - } - else - { - $ownerObj = ilObjectFactory::getInstanceByObjId(6, false); - } - - if (!is_object($ownerObj) || $ownerObj->getType() != "usr") // root user deleted - { - $this->addProperty($lng->txt("owner"), $lng->txt("no_owner")); - } - else if ($ownerObj->hasPublicProfile()) - { - $ilCtrl->setParameterByClass("ilpublicuserprofilegui", "user_id", $ownerObj->getId()); - $this->addProperty($lng->txt("owner"),$ownerObj->getPublicName(),$ilCtrl->getLinkTargetByClass("ilpublicuserprofilegui", "getHTML")); - } - else - { - $this->addProperty($lng->txt("owner"),$ownerObj->getPublicName()); - } - } - - // disk usage - require_once 'Services/WebDAV/classes/class.ilDiskQuotaActivationChecker.php'; - if ($ilUser->getId() != ANONYMOUS_USER_ID && - ilDiskQuotaActivationChecker::_isActive()) - { - $size = $a_obj->getDiskUsage(); - if ($size !== null) { - $this->addProperty($lng->txt("disk_usage"),ilUtil::formatSize($size,'long')); - } - } - // change event - require_once 'Services/Tracking/classes/class.ilChangeEvent.php'; - if (ilChangeEvent::_isActive()) - { - if ($ilUser->getId() != ANONYMOUS_USER_ID) - { - $readEvents = ilChangeEvent::_lookupReadEvents($a_obj->getId()); - $count_users = 0; - $count_members = 0; - $count_user_reads = 0; - $count_anonymous_reads = 0; - foreach ($readEvents as $evt) - { - if ($evt['usr_id'] == ANONYMOUS_USER_ID) - { - $count_anonymous_reads += $evt['read_count']; - } - else - { - $count_user_reads += $evt['read_count']; - $count_users++; - /* to do: if ($evt['user_id'] is member of $this->getRefId()) - { - $count_members++; - }*/ - } - } - if ($count_anonymous_reads > 0) - { - $this->addProperty($this->lng->txt("readcount_anonymous_users"),$count_anonymous_reads); - } - if ($count_user_reads > 0) - { - $this->addProperty($this->lng->txt("readcount_users"),$count_user_reads); + // creation date + $this->addProperty( + $lng->txt("create_date"), + ilDatePresentation::formatDate(new ilDateTime($a_obj->getCreateDate(), IL_CAL_DATETIME)) + ); + + // owner + if ($ilUser->getId() != ANONYMOUS_USER_ID and $a_obj->getOwner()) { + include_once './Services/Object/classes/class.ilObjectFactory.php'; + include_once './Services/User/classes/class.ilObjUser.php'; + + if (ilObjUser::userExists(array($a_obj->getOwner()))) { + $ownerObj = ilObjectFactory::getInstanceByObjId($a_obj->getOwner(), false); + } else { + $ownerObj = ilObjectFactory::getInstanceByObjId(6, false); + } + + if (!is_object($ownerObj) || $ownerObj->getType() != "usr") { // root user deleted + $this->addProperty($lng->txt("owner"), $lng->txt("no_owner")); + } elseif ($ownerObj->hasPublicProfile()) { + $ilCtrl->setParameterByClass("ilpublicuserprofilegui", "user_id", $ownerObj->getId()); + $this->addProperty($lng->txt("owner"), $ownerObj->getPublicName(), $ilCtrl->getLinkTargetByClass("ilpublicuserprofilegui", "getHTML")); + } else { + $this->addProperty($lng->txt("owner"), $ownerObj->getPublicName()); + } + } + + // disk usage + require_once 'Services/WebDAV/classes/class.ilDiskQuotaActivationChecker.php'; + if ($ilUser->getId() != ANONYMOUS_USER_ID && + ilDiskQuotaActivationChecker::_isActive()) { + $size = $a_obj->getDiskUsage(); + if ($size !== null) { + $this->addProperty($lng->txt("disk_usage"), ilUtil::formatSize($size, 'long')); + } + } + // change event + require_once 'Services/Tracking/classes/class.ilChangeEvent.php'; + if (ilChangeEvent::_isActive()) { + if ($ilUser->getId() != ANONYMOUS_USER_ID) { + $readEvents = ilChangeEvent::_lookupReadEvents($a_obj->getId()); + $count_users = 0; + $count_members = 0; + $count_user_reads = 0; + $count_anonymous_reads = 0; + foreach ($readEvents as $evt) { + if ($evt['usr_id'] == ANONYMOUS_USER_ID) { + $count_anonymous_reads += $evt['read_count']; + } else { + $count_user_reads += $evt['read_count']; + $count_users++; + /* to do: if ($evt['user_id'] is member of $this->getRefId()) + { + $count_members++; + }*/ + } + } + if ($count_anonymous_reads > 0) { + $this->addProperty($this->lng->txt("readcount_anonymous_users"), $count_anonymous_reads); + } + if ($count_user_reads > 0) { + $this->addProperty($this->lng->txt("readcount_users"), $count_user_reads); + } + if ($count_users > 0) { + $this->addProperty($this->lng->txt("accesscount_registered_users"), $count_users); + } + } + } + // END ChangeEvent: Display change event info + + // WebDAV: Display locking information + require_once('Services/WebDAV/classes/class.ilDAVActivationChecker.php'); + if (ilDAVActivationChecker::_isActive()) { + if ($ilUser->getId() != ANONYMOUS_USER_ID) { + require_once 'Services/WebDAV/classes/lock/class.ilWebDAVLockBackend.php'; + $webdav_lock_backend = new ilWebDAVLockBackend(); + + // Show lock info + if ($ilUser->getId() != ANONYMOUS_USER_ID) { + if ($lock = $webdav_lock_backend->getLocksOnObjectId($this->gui_object->object->getId())) { + $lock_user = new ilObjUser($lock->getIliasOwner()); + $this->addProperty( + $this->lng->txt("in_use_by"), + $lock_user->getPublicName(), + "./ilias.php?user=" . $lock_user->getId() . '&cmd=showUserProfile&cmdClass=ilpersonaldesktopgui&cmdNode=1&baseClass=ilPersonalDesktopGUI' + ); + } } - if ($count_users > 0) - { - $this->addProperty($this->lng->txt("accesscount_registered_users"),$count_users); - } - } - } - // END ChangeEvent: Display change event info - - // WebDAV: Display locking information - require_once ('Services/WebDAV/classes/class.ilDAVActivationChecker.php'); - if (ilDAVActivationChecker::_isActive()) - { - if ($ilUser->getId() != ANONYMOUS_USER_ID) - { - require_once 'Services/WebDAV/classes/lock/class.ilWebDAVLockBackend.php'; - $webdav_lock_backend = new ilWebDAVLockBackend(); - - // Show lock info - if ($ilUser->getId() != ANONYMOUS_USER_ID) - { - if ($lock = $webdav_lock_backend->getLocksOnObjectId($this->gui_object->object->getId())) - { - $lock_user = new ilObjUser($lock->getIliasOwner()); - $this->addProperty($this->lng->txt("in_use_by"), - $lock_user->getPublicName() - , - "./ilias.php?user=".$lock_user->getId().'&cmd=showUserProfile&cmdClass=ilpersonaldesktopgui&cmdNode=1&baseClass=ilPersonalDesktopGUI' - ); - } - } - } - } - } - // END ChangeEvent: Display standard object info - /** - * show summary page - */ - function showSummary() - { - $tpl = $this->tpl; - $ilAccess = $this->access; - - $tpl->setContent($this->getCenterColumnHTML()); - $tpl->setRightContent($this->getRightColumnHTML()); - } - - - /** - * Display center column - */ - function getCenterColumnHTML() - { - $ilCtrl = $this->ctrl; - - include_once("Services/Block/classes/class.ilColumnGUI.php"); - $column_gui = new ilColumnGUI("info", IL_COL_CENTER); - $this->setColumnSettings($column_gui); - - if (!$ilCtrl->isAsynch()) - { - if ($column_gui->getScreenMode() != IL_SCREEN_SIDE) - { - // right column wants center - if ($column_gui->getCmdSide() == IL_COL_RIGHT) - { - $column_gui = new ilColumnGUI("info", IL_COL_RIGHT); - $this->setColumnSettings($column_gui); - $html = $ilCtrl->forwardCommand($column_gui); - } - // left column wants center - if ($column_gui->getCmdSide() == IL_COL_LEFT) - { - $column_gui = new ilColumnGUI("info", IL_COL_LEFT); - $this->setColumnSettings($column_gui); - $html = $ilCtrl->forwardCommand($column_gui); - } - } - else - { - $html = $this->getHTML(); - } - } - - return $html; - } - - /** - * Display right column - */ - function getRightColumnHTML() - { - $ilUser = $this->user; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Block/classes/class.ilColumnGUI.php"); - $column_gui = new ilColumnGUI("info", IL_COL_RIGHT); - $this->setColumnSettings($column_gui); - - if ($ilCtrl->getNextClass() == "ilcolumngui" && - $column_gui->getCmdSide() == IL_COL_RIGHT && - $column_gui->getScreenMode() == IL_SCREEN_SIDE) - { - $html = $ilCtrl->forwardCommand($column_gui); - } - else - { - if (!$ilCtrl->isAsynch()) - { - if ($this->news_enabled) - { - $html = $ilCtrl->getHTML($column_gui); - } - } - } - - return $html; - } - - /** - * Set column settings. - */ - function setColumnSettings($column_gui) - { - $lng = $this->lng; - $ilAccess = $this->access; - - $column_gui->setEnableEdit($this->news_editing); - $column_gui->setRepositoryMode(true); - $column_gui->setAllBlockProperties($this->getAllBlockProperties()); - } - - function setOpenFormTag($a_val) - { - $this->open_form_tag = $a_val; - } - - function setCloseFormTag($a_val) - { - $this->close_form_tag = $a_val; - } - - /** - * get html - */ - function getHTML() - { - $lng = $this->lng; - $ilSetting = $this->settings; - $tree = $this->tree; - $ilAccess = $this->access; - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - $tpl = new ilTemplate("tpl.infoscreen.html" ,true, true, "Services/InfoScreen"); - - // other class handles form action (@todo: this is not implemented/tested) - if ($this->form_action == "") - { - $this->setFormAction($ilCtrl->getFormAction($this)); - } - - require_once 'Services/jQuery/classes/class.iljQueryUtil.php'; - iljQueryUtil::initjQuery(); - - if($this->hidden) - { - $tpl->touchBlock("hidden_js"); - if($this->show_hidden_toggle) - { - $this->addButton($lng->txt("show_hidden_sections"), "JavaScript:toggleSections(this, '".$lng->txt("show_hidden_sections") ."', '".$lng->txt("hide_visible_sections") ."');"); - } - } - - - // DEPRECATED - use ilToolbarGUI - - // add top buttons - if (count($this->top_buttons) > 0) - { - $tpl->addBlockfile("TOP_BUTTONS", "top_buttons", "tpl.buttons.html"); - - foreach($this->top_buttons as $button) - { - // view button - $tpl->setCurrentBlock("btn_cell"); - $tpl->setVariable("BTN_LINK", $button["link"]); - $tpl->setVariable("BTN_TARGET", $button["target"]); - $tpl->setVariable("BTN_TXT", $button["title"]); - if($button["primary"]) - { - $tpl->setVariable("BTN_CLASS", " btn-primary"); - } - $tpl->parseCurrentBlock(); - } - } - - // add top formbuttons - if ((count($this->top_formbuttons) > 0) && (strlen($this->form_action) > 0)) - { - $tpl->addBlockfile("TOP_FORMBUTTONS", "top_submitbuttons", "tpl.submitbuttons.html", "Services/InfoScreen"); - - foreach($this->top_formbuttons as $button) - { - // view button - $tpl->setCurrentBlock("btn_submit_cell"); - $tpl->setVariable("BTN_COMMAND", $button["command"]); - $tpl->setVariable("BTN_NAME", $button["title"]); - $tpl->parseCurrentBlock(); - } - } - - // add form action - if (strlen($this->form_action) > 0) - { - if($this->open_form_tag) - { - $tpl->setCurrentBlock("formtop"); - $tpl->setVariable("FORMACTION", $this->form_action); - $tpl->parseCurrentBlock(); - } - - if($this->close_form_tag) - { - $tpl->touchBlock("formbottom"); - } - } - - if (count($this->hiddenelements)) - { - foreach ($this->hiddenelements as $hidden) - { - $tpl->setCurrentBlock("hidden_element"); - $tpl->setVariable("HIDDEN_NAME", $hidden["name"]); - $tpl->setVariable("HIDDEN_VALUE", $hidden["value"]); - $tpl->parseCurrentBlock(); - } - } - - - // learning progress - if($this->learning_progress_enabled and $html = $this->showLearningProgress($tpl)) - { - $tpl->setCurrentBlock("learning_progress"); - $tpl->setVariable("LP_TABLE",$html); - $tpl->parseCurrentBlock(); - } - - // notes section - if ($this->private_notes_enabled && !$ilSetting->get('disable_notes')) - { - $html = $this->showNotesSection(); - $tpl->setCurrentBlock("notes"); - $tpl->setVariable("NOTES", $html); - $tpl->parseCurrentBlock(); - } - - // tagging - if (is_object($this->gui_object->object)) - { - $tags_set = new ilSetting("tags"); - if ($tags_set->get("enable") && $ilUser->getId() != ANONYMOUS_USER_ID) - { - $this->addTagging(); - } - } - - if(is_object($this->gui_object->object)) - { - $this->addObjectSections(); - } + } + } + } + // END ChangeEvent: Display standard object info + /** + * show summary page + */ + public function showSummary() + { + $tpl = $this->tpl; + $ilAccess = $this->access; + + $tpl->setContent($this->getCenterColumnHTML()); + $tpl->setRightContent($this->getRightColumnHTML()); + } + + + /** + * Display center column + */ + public function getCenterColumnHTML() + { + $ilCtrl = $this->ctrl; + + include_once("Services/Block/classes/class.ilColumnGUI.php"); + $column_gui = new ilColumnGUI("info", IL_COL_CENTER); + $this->setColumnSettings($column_gui); + + if (!$ilCtrl->isAsynch()) { + if ($column_gui->getScreenMode() != IL_SCREEN_SIDE) { + // right column wants center + if ($column_gui->getCmdSide() == IL_COL_RIGHT) { + $column_gui = new ilColumnGUI("info", IL_COL_RIGHT); + $this->setColumnSettings($column_gui); + $html = $ilCtrl->forwardCommand($column_gui); + } + // left column wants center + if ($column_gui->getCmdSide() == IL_COL_LEFT) { + $column_gui = new ilColumnGUI("info", IL_COL_LEFT); + $this->setColumnSettings($column_gui); + $html = $ilCtrl->forwardCommand($column_gui); + } + } else { + $html = $this->getHTML(); + } + } + + return $html; + } + + /** + * Display right column + */ + public function getRightColumnHTML() + { + $ilUser = $this->user; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Block/classes/class.ilColumnGUI.php"); + $column_gui = new ilColumnGUI("info", IL_COL_RIGHT); + $this->setColumnSettings($column_gui); + + if ($ilCtrl->getNextClass() == "ilcolumngui" && + $column_gui->getCmdSide() == IL_COL_RIGHT && + $column_gui->getScreenMode() == IL_SCREEN_SIDE) { + $html = $ilCtrl->forwardCommand($column_gui); + } else { + if (!$ilCtrl->isAsynch()) { + if ($this->news_enabled) { + $html = $ilCtrl->getHTML($column_gui); + } + } + } + + return $html; + } + + /** + * Set column settings. + */ + public function setColumnSettings($column_gui) + { + $lng = $this->lng; + $ilAccess = $this->access; + + $column_gui->setEnableEdit($this->news_editing); + $column_gui->setRepositoryMode(true); + $column_gui->setAllBlockProperties($this->getAllBlockProperties()); + } + + public function setOpenFormTag($a_val) + { + $this->open_form_tag = $a_val; + } + + public function setCloseFormTag($a_val) + { + $this->close_form_tag = $a_val; + } + + /** + * get html + */ + public function getHTML() + { + $lng = $this->lng; + $ilSetting = $this->settings; + $tree = $this->tree; + $ilAccess = $this->access; + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + $tpl = new ilTemplate("tpl.infoscreen.html", true, true, "Services/InfoScreen"); + + // other class handles form action (@todo: this is not implemented/tested) + if ($this->form_action == "") { + $this->setFormAction($ilCtrl->getFormAction($this)); + } + + require_once 'Services/jQuery/classes/class.iljQueryUtil.php'; + iljQueryUtil::initjQuery(); + + if ($this->hidden) { + $tpl->touchBlock("hidden_js"); + if ($this->show_hidden_toggle) { + $this->addButton($lng->txt("show_hidden_sections"), "JavaScript:toggleSections(this, '" . $lng->txt("show_hidden_sections") . "', '" . $lng->txt("hide_visible_sections") . "');"); + } + } + + + // DEPRECATED - use ilToolbarGUI + + // add top buttons + if (count($this->top_buttons) > 0) { + $tpl->addBlockfile("TOP_BUTTONS", "top_buttons", "tpl.buttons.html"); + + foreach ($this->top_buttons as $button) { + // view button + $tpl->setCurrentBlock("btn_cell"); + $tpl->setVariable("BTN_LINK", $button["link"]); + $tpl->setVariable("BTN_TARGET", $button["target"]); + $tpl->setVariable("BTN_TXT", $button["title"]); + if ($button["primary"]) { + $tpl->setVariable("BTN_CLASS", " btn-primary"); + } + $tpl->parseCurrentBlock(); + } + } + + // add top formbuttons + if ((count($this->top_formbuttons) > 0) && (strlen($this->form_action) > 0)) { + $tpl->addBlockfile("TOP_FORMBUTTONS", "top_submitbuttons", "tpl.submitbuttons.html", "Services/InfoScreen"); + + foreach ($this->top_formbuttons as $button) { + // view button + $tpl->setCurrentBlock("btn_submit_cell"); + $tpl->setVariable("BTN_COMMAND", $button["command"]); + $tpl->setVariable("BTN_NAME", $button["title"]); + $tpl->parseCurrentBlock(); + } + } + + // add form action + if (strlen($this->form_action) > 0) { + if ($this->open_form_tag) { + $tpl->setCurrentBlock("formtop"); + $tpl->setVariable("FORMACTION", $this->form_action); + $tpl->parseCurrentBlock(); + } + + if ($this->close_form_tag) { + $tpl->touchBlock("formbottom"); + } + } + + if (count($this->hiddenelements)) { + foreach ($this->hiddenelements as $hidden) { + $tpl->setCurrentBlock("hidden_element"); + $tpl->setVariable("HIDDEN_NAME", $hidden["name"]); + $tpl->setVariable("HIDDEN_VALUE", $hidden["value"]); + $tpl->parseCurrentBlock(); + } + } + + + // learning progress + if ($this->learning_progress_enabled and $html = $this->showLearningProgress($tpl)) { + $tpl->setCurrentBlock("learning_progress"); + $tpl->setVariable("LP_TABLE", $html); + $tpl->parseCurrentBlock(); + } + + // notes section + if ($this->private_notes_enabled && !$ilSetting->get('disable_notes')) { + $html = $this->showNotesSection(); + $tpl->setCurrentBlock("notes"); + $tpl->setVariable("NOTES", $html); + $tpl->parseCurrentBlock(); + } + + // tagging + if (is_object($this->gui_object->object)) { + $tags_set = new ilSetting("tags"); + if ($tags_set->get("enable") && $ilUser->getId() != ANONYMOUS_USER_ID) { + $this->addTagging(); + } + } + + if (is_object($this->gui_object->object)) { + $this->addObjectSections(); + } // render all sections - for($i = 1; $i <= $this->sec_nr; $i++) - { - if (is_array($this->section[$i]["properties"])) - { - // section properties - foreach($this->section[$i]["properties"] as $property) - { - if ($property["name"] != "") - { - if ($property["link"] == "") - { - $tpl->setCurrentBlock("pv"); - $tpl->setVariable("TXT_PROPERTY_VALUE", $property["value"]); - $tpl->parseCurrentBlock(); - } - else - { - $tpl->setCurrentBlock("lpv"); - $tpl->setVariable("TXT_PROPERTY_LVALUE", $property["value"]); - $tpl->setVariable("LINK_PROPERTY_VALUE", $property["link"]); - $tpl->parseCurrentBlock(); - } - $tpl->setCurrentBlock("property_row"); - $tpl->setVariable("TXT_PROPERTY", $property["name"]); - $tpl->parseCurrentBlock(); - } - else - { - $tpl->setCurrentBlock("property_full_row"); - $tpl->setVariable("TXT_PROPERTY_FULL_VALUE", $property["value"]); - $tpl->parseCurrentBlock(); - } - } - - // section header - if($this->section[$i]["hidden"]) - { - $tpl->setVariable("SECTION_HIDDEN", " style=\"display:none;\""); - $tpl->setVariable("SECTION_ID", "hidable_".$i); - } - else - { - $tpl->setVariable("SECTION_ID", $i); - } - $tpl->setVariable("TCLASS", $this->getTableClass()); - $tpl->setVariable("TXT_SECTION", $this->section[$i]["title"]); - $tpl->touchBlock("row"); - } - } - - return $tpl->get(); - } - - /** - * @return int|null - */ - public function getContextRefId(): int - { - if ($this->contextRefId !== null) { - return $this->contextRefId; - } - - return $this->gui_object->object->getRefId(); - } - - /** - * @param int|null $contextRefId - */ - public function setContextRefId(int $contextRefId) - { - $this->contextRefId = $contextRefId; - } - - /** - * @return int|null - */ - public function getContextObjId(): int - { - if ($this->contextObjId !== null) { - return $this->contextObjId; - } - - return $this->gui_object->object->getId(); - } - - /** - * @param int|null $contextObjId - */ - public function setContextObjId(int $contextObjId) - { - $this->contextObjId = $contextObjId; - } - - /** - * @return null|string - */ - public function getContentObjType(): string - { - if ($this->contentObjType !== null) { - return $this->contentObjType; - } - - return $this->gui_object->object->getType(); - } - - /** - * @param null|string $contentObjType - */ - public function setContentObjType(string $contentObjType) - { - $this->contentObjType = $contentObjType; - } - - function showLearningProgress($a_tpl) - { - $ilUser = $this->user; - $rbacsystem = $this->rbacsystem; - - if(!$rbacsystem->checkAccess('read', $this->getContextRefId())) - { - return false; - } - if($ilUser->getId() == ANONYMOUS_USER_ID) - { - return false; - } - - include_once("Services/Tracking/classes/class.ilObjUserTracking.php"); - if (!ilObjUserTracking::_enabledLearningProgress()) - { - return false; - } - - include_once './Services/Object/classes/class.ilObjectLP.php'; - $olp = ilObjectLP::getInstance($this->getContextObjId()); - if($olp->getCurrentMode() != ilLPObjSettings::LP_MODE_MANUAL) - { - return false; - } - - include_once 'Services/Tracking/classes/class.ilLPMarks.php'; - - $this->lng->loadLanguageModule('trac'); - - // section header -// $a_tpl->setCurrentBlock("header_row"); - $a_tpl->setVariable("TXT_SECTION", - $this->lng->txt('learning_progress')); - $a_tpl->parseCurrentBlock(); - // $a_tpl->touchBlock("row"); - - // status - $i_tpl = new ilTemplate("tpl.lp_edit_manual_info_page.html", true, true, "Services/Tracking"); - $i_tpl->setVariable("INFO_EDITED", $this->lng->txt("trac_info_edited")); - $i_tpl->setVariable("SELECT_STATUS", ilUtil::formSelect((int) ilLPMarks::_hasCompleted($ilUser->getId(), - $this->getContextObjId()), - 'lp_edit', - array(0 => $this->lng->txt('trac_not_completed'), - 1 => $this->lng->txt('trac_completed')), - false, - true)); - $i_tpl->setVariable("TXT_SAVE", $this->lng->txt("save")); - $a_tpl->setCurrentBlock("pv"); - $a_tpl->setVariable("TXT_PROPERTY_VALUE", $i_tpl->get()); - $a_tpl->parseCurrentBlock(); - $a_tpl->setCurrentBlock("property_row"); - $a_tpl->setVariable("TXT_PROPERTY", $this->lng->txt('trac_status')); - $a_tpl->parseCurrentBlock(); - // $a_tpl->touchBlock("row"); - - - // More infos for lm's - if($this->getContentObjType() == 'lm' || - $this->getContentObjType() == 'htlm') - { - $a_tpl->setCurrentBlock("pv"); - - include_once 'Services/Tracking/classes/class.ilLearningProgress.php'; - $progress = ilLearningProgress::_getProgress($ilUser->getId(), $this->getContextObjId()); - if($progress['access_time']) - { - $a_tpl->setVariable("TXT_PROPERTY_VALUE", - ilDatePresentation::formatDate(new ilDateTime($progress['access_time'],IL_CAL_UNIX))); - } - else - { - $a_tpl->setVariable("TXT_PROPERTY_VALUE", - $this->lng->txt('trac_not_accessed')); - } - - $a_tpl->parseCurrentBlock(); - $a_tpl->setCurrentBlock("property_row"); - $a_tpl->setVariable("TXT_PROPERTY", $this->lng->txt('trac_last_access')); - $a_tpl->parseCurrentBlock(); - // $a_tpl->touchBlock("row"); - - // tags of all users - $a_tpl->setCurrentBlock("pv"); - $a_tpl->setVariable("TXT_PROPERTY_VALUE", - (int) $progress['visits']); - $a_tpl->parseCurrentBlock(); - $a_tpl->setCurrentBlock("property_row"); - $a_tpl->setVariable("TXT_PROPERTY", $this->lng->txt('trac_visits')); - $a_tpl->parseCurrentBlock(); - // $a_tpl->touchBlock("row"); - - - if($this->getContentObjType() == 'lm') - { - // tags of all users - $a_tpl->setCurrentBlock("pv"); - $a_tpl->setVariable("TXT_PROPERTY_VALUE", - ilDatePresentation::secondsToString($progress['spent_seconds'])); - $a_tpl->parseCurrentBlock(); - $a_tpl->setCurrentBlock("property_row"); - $a_tpl->setVariable("TXT_PROPERTY", $this->lng->txt('trac_spent_time')); - $a_tpl->parseCurrentBlock(); - // $a_tpl->touchBlock("row"); - } - } - - // #10493 - $a_tpl->touchBlock("row"); - } - - function saveProgress($redirect = true) - { - $ilUser = $this->user; - - include_once 'Services/Tracking/classes/class.ilLPMarks.php'; - - $lp_marks = new ilLPMarks($this->getContextObjId(), $ilUser->getId()); - $lp_marks->setCompleted((bool) $_POST['lp_edit']); - $lp_marks->update(); - - require_once 'Services/Tracking/classes/class.ilLPStatusWrapper.php'; - ilLPStatusWrapper::_updateStatus($this->getContextObjId(), $ilUser->getId()); - - $this->lng->loadLanguageModule('trac'); - ilUtil::sendSuccess($this->lng->txt('trac_updated_status'), true); - - if ($redirect) { - $this->ctrl->redirect($this, ""); // #14993 - } - } - - - /** - * show notes section - */ - function showNotesSection() - { - $ilAccess = $this->access; - $ilSetting = $this->settings; - - $next_class = $this->ctrl->getNextClass($this); - include_once("Services/Notes/classes/class.ilNoteGUI.php"); - $notes_gui = new ilNoteGUI($this->gui_object->object->getId(), 0, - $this->gui_object->object->getType()); - - // global switch - if($ilSetting->get("disable_comments")) - { - $notes_gui->enablePublicNotes(false); - } - else - { - $ref_id = $this->gui_object->object->getRefId(); - $has_write = $ilAccess->checkAccess("write", "", $ref_id); - - if($has_write && $ilSetting->get("comments_del_tutor", 1)) - { - $notes_gui->enablePublicNotesDeletion(true); - } - - /* should probably be discussed further - for now this will only work properly with comments settings - (see ilNoteGUI constructor) - */ - if ($has_write || - $ilAccess->checkAccess("edit_permissions", "", $ref_id)) - { - $notes_gui->enableCommentsSettings(); - } - } - - /* moved to action menu - $notes_gui->enablePrivateNotes(); - */ - - if ($next_class == "ilnotegui") - { - $html = $this->ctrl->forwardCommand($notes_gui); - } - else - { - $html = $notes_gui->getNotesHTML(); - } - - return $html; - } - - /** - * show LDAP role group mapping info - * - * @access public - * @param string section name. Leave empty to place this info string inside a section - * - */ - public function showLDAPRoleGroupMappingInfo($a_section = '') - { - if(strlen($a_section)) - { - $this->addSection($a_section); - } - include_once('Services/LDAP/classes/class.ilLDAPRoleGroupMapping.php'); - $ldap_mapping = ilLDAPRoleGroupMapping::_getInstance(); - if($infos = $ldap_mapping->getInfoStrings($this->gui_object->object->getId())) - { - $info_combined = '
                  '; - $counter = 0; - foreach($infos as $info_string) - { - if($counter++) - { - $info_combined .= '
                  '; - } - $info_combined .= $info_string; - } - $info_combined .= '
                  '; - $this->addProperty($this->lng->txt('applications'),$info_combined); - } - return true; - } - - function setTabs() - { - $tpl = $this->tpl; - - $this->getTabs($this->tabs_gui); - } - - /** - * get tabs - */ - function getTabs(&$tabs_gui) - { - $rbacsystem = $this->rbacsystem; - $ilUser = $this->user; - $ilAccess = $this->access; - - $next_class = $this->ctrl->getNextClass($this); - $force_active = ($next_class == "ilnotegui") - ? true - : false; - - $tabs_gui->addSubTabTarget('summary', - $this->ctrl->getLinkTarget($this, "showSummary"), - array("showSummary", ""), - get_class($this), "", $force_active); - } - - - /** - * Add tagging - */ - function addTagging() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $lng->loadLanguageModule("tagging"); - $tags_set = new ilSetting("tags"); - - include_once("Services/Tagging/classes/class.ilTaggingGUI.php"); - $tagging_gui = new ilTaggingGUI(); - $tagging_gui->setObject($this->gui_object->object->getId(), - $this->gui_object->object->getType()); - - $this->addSection($lng->txt("tagging_tags")); - - if ($tags_set->get("enable_all_users")) - { - $this->addProperty($lng->txt("tagging_all_users"), - $tagging_gui->getAllUserTagsForObjectHTML()); - } - - $this->addProperty($lng->txt("tagging_my_tags"), - $tagging_gui->getTaggingInputHTML()); - } - - function saveTags() - { - include_once("Services/Tagging/classes/class.ilTaggingGUI.php"); - $tagging_gui = new ilTaggingGUI(); - $tagging_gui->setObject($this->gui_object->object->getId(), - $this->gui_object->object->getType()); - $tagging_gui->saveInput(); - - ilUtil::sendSuccess($this->lng->txt('msg_obj_modified'), true); - $this->ctrl->redirect($this, ""); // #14993 - - // return $this->showSummary(); - } - - function hideFurtherSections($a_add_toggle = true) - { - $this->hidden = true; - $this->show_hidden_toggle = (bool)$a_add_toggle; - } - - function getHiddenToggleButton() - { - $lng = $this->lng; - - return "
                  txt("show_hidden_sections") ."', '".$lng->txt("hide_visible_sections") ."'); return false;\" href=\"#\">".$lng->txt("show_hidden_sections").""; - } -} + for ($i = 1; $i <= $this->sec_nr; $i++) { + if (is_array($this->section[$i]["properties"])) { + // section properties + foreach ($this->section[$i]["properties"] as $property) { + if ($property["name"] != "") { + if ($property["link"] == "") { + $tpl->setCurrentBlock("pv"); + $tpl->setVariable("TXT_PROPERTY_VALUE", $property["value"]); + $tpl->parseCurrentBlock(); + } else { + $tpl->setCurrentBlock("lpv"); + $tpl->setVariable("TXT_PROPERTY_LVALUE", $property["value"]); + $tpl->setVariable("LINK_PROPERTY_VALUE", $property["link"]); + $tpl->parseCurrentBlock(); + } + $tpl->setCurrentBlock("property_row"); + $tpl->setVariable("TXT_PROPERTY", $property["name"]); + $tpl->parseCurrentBlock(); + } else { + $tpl->setCurrentBlock("property_full_row"); + $tpl->setVariable("TXT_PROPERTY_FULL_VALUE", $property["value"]); + $tpl->parseCurrentBlock(); + } + } -?> + // section header + if ($this->section[$i]["hidden"]) { + $tpl->setVariable("SECTION_HIDDEN", " style=\"display:none;\""); + $tpl->setVariable("SECTION_ID", "hidable_" . $i); + } else { + $tpl->setVariable("SECTION_ID", $i); + } + $tpl->setVariable("TCLASS", $this->getTableClass()); + $tpl->setVariable("TXT_SECTION", $this->section[$i]["title"]); + $tpl->touchBlock("row"); + } + } + + return $tpl->get(); + } + + /** + * @return int|null + */ + public function getContextRefId() : int + { + if ($this->contextRefId !== null) { + return $this->contextRefId; + } + + return $this->gui_object->object->getRefId(); + } + + /** + * @param int|null $contextRefId + */ + public function setContextRefId(int $contextRefId) + { + $this->contextRefId = $contextRefId; + } + + /** + * @return int|null + */ + public function getContextObjId() : int + { + if ($this->contextObjId !== null) { + return $this->contextObjId; + } + + return $this->gui_object->object->getId(); + } + + /** + * @param int|null $contextObjId + */ + public function setContextObjId(int $contextObjId) + { + $this->contextObjId = $contextObjId; + } + + /** + * @return null|string + */ + public function getContentObjType() : string + { + if ($this->contentObjType !== null) { + return $this->contentObjType; + } + + return $this->gui_object->object->getType(); + } + + /** + * @param null|string $contentObjType + */ + public function setContentObjType(string $contentObjType) + { + $this->contentObjType = $contentObjType; + } + + public function showLearningProgress($a_tpl) + { + $ilUser = $this->user; + $rbacsystem = $this->rbacsystem; + + if (!$rbacsystem->checkAccess('read', $this->getContextRefId())) { + return false; + } + if ($ilUser->getId() == ANONYMOUS_USER_ID) { + return false; + } + + include_once("Services/Tracking/classes/class.ilObjUserTracking.php"); + if (!ilObjUserTracking::_enabledLearningProgress()) { + return false; + } + + include_once './Services/Object/classes/class.ilObjectLP.php'; + $olp = ilObjectLP::getInstance($this->getContextObjId()); + if ($olp->getCurrentMode() != ilLPObjSettings::LP_MODE_MANUAL) { + return false; + } + + include_once 'Services/Tracking/classes/class.ilLPMarks.php'; + + $this->lng->loadLanguageModule('trac'); + + // section header + // $a_tpl->setCurrentBlock("header_row"); + $a_tpl->setVariable( + "TXT_SECTION", + $this->lng->txt('learning_progress') + ); + $a_tpl->parseCurrentBlock(); + // $a_tpl->touchBlock("row"); + + // status + $i_tpl = new ilTemplate("tpl.lp_edit_manual_info_page.html", true, true, "Services/Tracking"); + $i_tpl->setVariable("INFO_EDITED", $this->lng->txt("trac_info_edited")); + $i_tpl->setVariable("SELECT_STATUS", ilUtil::formSelect( + (int) ilLPMarks::_hasCompleted( + $ilUser->getId(), + $this->getContextObjId() + ), + 'lp_edit', + array(0 => $this->lng->txt('trac_not_completed'), + 1 => $this->lng->txt('trac_completed')), + false, + true + )); + $i_tpl->setVariable("TXT_SAVE", $this->lng->txt("save")); + $a_tpl->setCurrentBlock("pv"); + $a_tpl->setVariable("TXT_PROPERTY_VALUE", $i_tpl->get()); + $a_tpl->parseCurrentBlock(); + $a_tpl->setCurrentBlock("property_row"); + $a_tpl->setVariable("TXT_PROPERTY", $this->lng->txt('trac_status')); + $a_tpl->parseCurrentBlock(); + // $a_tpl->touchBlock("row"); + + + // More infos for lm's + if ($this->getContentObjType() == 'lm' || + $this->getContentObjType() == 'htlm') { + $a_tpl->setCurrentBlock("pv"); + + include_once 'Services/Tracking/classes/class.ilLearningProgress.php'; + $progress = ilLearningProgress::_getProgress($ilUser->getId(), $this->getContextObjId()); + if ($progress['access_time']) { + $a_tpl->setVariable( + "TXT_PROPERTY_VALUE", + ilDatePresentation::formatDate(new ilDateTime($progress['access_time'], IL_CAL_UNIX)) + ); + } else { + $a_tpl->setVariable( + "TXT_PROPERTY_VALUE", + $this->lng->txt('trac_not_accessed') + ); + } + + $a_tpl->parseCurrentBlock(); + $a_tpl->setCurrentBlock("property_row"); + $a_tpl->setVariable("TXT_PROPERTY", $this->lng->txt('trac_last_access')); + $a_tpl->parseCurrentBlock(); + // $a_tpl->touchBlock("row"); + + // tags of all users + $a_tpl->setCurrentBlock("pv"); + $a_tpl->setVariable( + "TXT_PROPERTY_VALUE", + (int) $progress['visits'] + ); + $a_tpl->parseCurrentBlock(); + $a_tpl->setCurrentBlock("property_row"); + $a_tpl->setVariable("TXT_PROPERTY", $this->lng->txt('trac_visits')); + $a_tpl->parseCurrentBlock(); + // $a_tpl->touchBlock("row"); + + + if ($this->getContentObjType() == 'lm') { + // tags of all users + $a_tpl->setCurrentBlock("pv"); + $a_tpl->setVariable( + "TXT_PROPERTY_VALUE", + ilDatePresentation::secondsToString($progress['spent_seconds']) + ); + $a_tpl->parseCurrentBlock(); + $a_tpl->setCurrentBlock("property_row"); + $a_tpl->setVariable("TXT_PROPERTY", $this->lng->txt('trac_spent_time')); + $a_tpl->parseCurrentBlock(); + // $a_tpl->touchBlock("row"); + } + } + + // #10493 + $a_tpl->touchBlock("row"); + } + + public function saveProgress($redirect = true) + { + $ilUser = $this->user; + + include_once 'Services/Tracking/classes/class.ilLPMarks.php'; + + $lp_marks = new ilLPMarks($this->getContextObjId(), $ilUser->getId()); + $lp_marks->setCompleted((bool) $_POST['lp_edit']); + $lp_marks->update(); + + require_once 'Services/Tracking/classes/class.ilLPStatusWrapper.php'; + ilLPStatusWrapper::_updateStatus($this->getContextObjId(), $ilUser->getId()); + + $this->lng->loadLanguageModule('trac'); + ilUtil::sendSuccess($this->lng->txt('trac_updated_status'), true); + + if ($redirect) { + $this->ctrl->redirect($this, ""); // #14993 + } + } + + + /** + * show notes section + */ + public function showNotesSection() + { + $ilAccess = $this->access; + $ilSetting = $this->settings; + + $next_class = $this->ctrl->getNextClass($this); + include_once("Services/Notes/classes/class.ilNoteGUI.php"); + $notes_gui = new ilNoteGUI( + $this->gui_object->object->getId(), + 0, + $this->gui_object->object->getType() + ); + + // global switch + if ($ilSetting->get("disable_comments")) { + $notes_gui->enablePublicNotes(false); + } else { + $ref_id = $this->gui_object->object->getRefId(); + $has_write = $ilAccess->checkAccess("write", "", $ref_id); + + if ($has_write && $ilSetting->get("comments_del_tutor", 1)) { + $notes_gui->enablePublicNotesDeletion(true); + } + + /* should probably be discussed further + for now this will only work properly with comments settings + (see ilNoteGUI constructor) + */ + if ($has_write || + $ilAccess->checkAccess("edit_permissions", "", $ref_id)) { + $notes_gui->enableCommentsSettings(); + } + } + + /* moved to action menu + $notes_gui->enablePrivateNotes(); + */ + + if ($next_class == "ilnotegui") { + $html = $this->ctrl->forwardCommand($notes_gui); + } else { + $html = $notes_gui->getNotesHTML(); + } + + return $html; + } + + /** + * show LDAP role group mapping info + * + * @access public + * @param string section name. Leave empty to place this info string inside a section + * + */ + public function showLDAPRoleGroupMappingInfo($a_section = '') + { + if (strlen($a_section)) { + $this->addSection($a_section); + } + include_once('Services/LDAP/classes/class.ilLDAPRoleGroupMapping.php'); + $ldap_mapping = ilLDAPRoleGroupMapping::_getInstance(); + if ($infos = $ldap_mapping->getInfoStrings($this->gui_object->object->getId())) { + $info_combined = '
                  '; + $counter = 0; + foreach ($infos as $info_string) { + if ($counter++) { + $info_combined .= '
                  '; + } + $info_combined .= $info_string; + } + $info_combined .= '
                  '; + $this->addProperty($this->lng->txt('applications'), $info_combined); + } + return true; + } + + public function setTabs() + { + $tpl = $this->tpl; + + $this->getTabs($this->tabs_gui); + } + + /** + * get tabs + */ + public function getTabs(&$tabs_gui) + { + $rbacsystem = $this->rbacsystem; + $ilUser = $this->user; + $ilAccess = $this->access; + + $next_class = $this->ctrl->getNextClass($this); + $force_active = ($next_class == "ilnotegui") + ? true + : false; + + $tabs_gui->addSubTabTarget( + 'summary', + $this->ctrl->getLinkTarget($this, "showSummary"), + array("showSummary", ""), + get_class($this), + "", + $force_active + ); + } + + + /** + * Add tagging + */ + public function addTagging() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $lng->loadLanguageModule("tagging"); + $tags_set = new ilSetting("tags"); + + include_once("Services/Tagging/classes/class.ilTaggingGUI.php"); + $tagging_gui = new ilTaggingGUI(); + $tagging_gui->setObject( + $this->gui_object->object->getId(), + $this->gui_object->object->getType() + ); + + $this->addSection($lng->txt("tagging_tags")); + + if ($tags_set->get("enable_all_users")) { + $this->addProperty( + $lng->txt("tagging_all_users"), + $tagging_gui->getAllUserTagsForObjectHTML() + ); + } + + $this->addProperty( + $lng->txt("tagging_my_tags"), + $tagging_gui->getTaggingInputHTML() + ); + } + + public function saveTags() + { + include_once("Services/Tagging/classes/class.ilTaggingGUI.php"); + $tagging_gui = new ilTaggingGUI(); + $tagging_gui->setObject( + $this->gui_object->object->getId(), + $this->gui_object->object->getType() + ); + $tagging_gui->saveInput(); + + ilUtil::sendSuccess($this->lng->txt('msg_obj_modified'), true); + $this->ctrl->redirect($this, ""); // #14993 + + // return $this->showSummary(); + } + + public function hideFurtherSections($a_add_toggle = true) + { + $this->hidden = true; + $this->show_hidden_toggle = (bool) $a_add_toggle; + } + + public function getHiddenToggleButton() + { + $lng = $this->lng; + + return "txt("show_hidden_sections") . "', '" . $lng->txt("hide_visible_sections") . "'); return false;\" href=\"#\">" . $lng->txt("show_hidden_sections") . ""; + } +} diff --git a/Services/LearningHistory/classes/class.ilFirstLoginLearningHistoryProvider.php b/Services/LearningHistory/classes/class.ilFirstLoginLearningHistoryProvider.php index e911de4f1ce38f6c1b9110a423c3177af0e7116e..50121e09d2c99c9766475ef2e2e8392cd307c77b 100644 --- a/Services/LearningHistory/classes/class.ilFirstLoginLearningHistoryProvider.php +++ b/Services/LearningHistory/classes/class.ilFirstLoginLearningHistoryProvider.php @@ -11,48 +11,48 @@ class ilFirstLoginLearningHistoryProvider extends ilAbstractLearningHistoryProvider implements ilLearningHistoryProviderInterface { - /** - * @inheritdoc - */ - public function isActive() - { - return true; - } - - /** - * @inheritdoc - */ - public function getEntries($ts_start, $ts_end) - { - $entries = []; - $ts = ilObjUser::_lookupFirstLogin($this->getUserId()); - if ($ts != "") - { - $ts = new ilDateTime($ts, IL_CAL_DATETIME); - $ts = $ts->get(IL_CAL_UNIX); - - $lng = $this->getLanguage(); - $lng->loadLanguageModule("lhist"); - - $text1 = $lng->txt("lhist_first_login"); - $entries[] = $this->getFactory()->entry($text1, $text1, - ilUtil::getImagePath("icon_rate_on_user.svg"), - $ts, - 0); - } - return $entries; - } - - /** - * @inheritdoc - */ - public function getName(): string - { - $lng = $this->getLanguage(); - $lng->loadLanguageModule("lhist"); - - return $lng->txt("lhist_first_login"); - } - - -} \ No newline at end of file + /** + * @inheritdoc + */ + public function isActive() + { + return true; + } + + /** + * @inheritdoc + */ + public function getEntries($ts_start, $ts_end) + { + $entries = []; + $ts = ilObjUser::_lookupFirstLogin($this->getUserId()); + if ($ts != "") { + $ts = new ilDateTime($ts, IL_CAL_DATETIME); + $ts = $ts->get(IL_CAL_UNIX); + + $lng = $this->getLanguage(); + $lng->loadLanguageModule("lhist"); + + $text1 = $lng->txt("lhist_first_login"); + $entries[] = $this->getFactory()->entry( + $text1, + $text1, + ilUtil::getImagePath("icon_rate_on_user.svg"), + $ts, + 0 + ); + } + return $entries; + } + + /** + * @inheritdoc + */ + public function getName() : string + { + $lng = $this->getLanguage(); + $lng->loadLanguageModule("lhist"); + + return $lng->txt("lhist_first_login"); + } +} diff --git a/Services/LearningHistory/classes/class.ilLearningHistoryEntry.php b/Services/LearningHistory/classes/class.ilLearningHistoryEntry.php index ec4fddd1f7e1ec12a6d2a1c49390c01f28986da2..2978696dabd9e934bb333d49668ca9e249b921d1 100644 --- a/Services/LearningHistory/classes/class.ilLearningHistoryEntry.php +++ b/Services/LearningHistory/classes/class.ilLearningHistoryEntry.php @@ -10,114 +10,112 @@ */ class ilLearningHistoryEntry { - /** - * @var string - */ - protected $achieve_text; - - /** - * @var string - */ - protected $achieve_in_text; - - /** - * @var string - */ - protected $icon_path; - - /** - * @var int - */ - protected $ts; - - /** - * @var int - */ - protected $obj_id; - - /** - * @var int - */ - protected $ref_id; - - /** - * Constructor - * @param string $achieve_text - * @param string $achieve_in_text - * @param string $icon_path - * @param int $ts - * @param int $obj_id - * @param int $ref_id - */ - public function __construct($achieve_text, $achieve_in_text, $icon_path, $ts, $obj_id, $ref_id = 0) - { - $this->achieve_text = $achieve_text; - $this->achieve_in_text = $achieve_in_text; - $this->icon_path = $icon_path; - $this->ts = $ts; - $this->obj_id = $obj_id; - $this->ref_id = $ref_id; - } - - /** - * Get timestamp - * - * @return int - */ - public function getTimestamp() - { - return $this->ts; - } - - /** - * Get obj id - * - * @return int - */ - public function getObjId() - { - return $this->obj_id; - } - - /** - * Get ref id - * - * @return int - */ - public function getRefId() - { - return $this->ref_id; - } - - /** - * Get achieve text - * - * @return string - */ - public function getAchieveText() - { - return $this->achieve_text; - } - - /** - * Get achieve in text - * - * @return string - */ - public function getAchieveInText() - { - return $this->achieve_in_text; - } - - /** - * Get Icon path - * - * @return string - */ - public function getIconPath() - { - return $this->icon_path; - } - - -} \ No newline at end of file + /** + * @var string + */ + protected $achieve_text; + + /** + * @var string + */ + protected $achieve_in_text; + + /** + * @var string + */ + protected $icon_path; + + /** + * @var int + */ + protected $ts; + + /** + * @var int + */ + protected $obj_id; + + /** + * @var int + */ + protected $ref_id; + + /** + * Constructor + * @param string $achieve_text + * @param string $achieve_in_text + * @param string $icon_path + * @param int $ts + * @param int $obj_id + * @param int $ref_id + */ + public function __construct($achieve_text, $achieve_in_text, $icon_path, $ts, $obj_id, $ref_id = 0) + { + $this->achieve_text = $achieve_text; + $this->achieve_in_text = $achieve_in_text; + $this->icon_path = $icon_path; + $this->ts = $ts; + $this->obj_id = $obj_id; + $this->ref_id = $ref_id; + } + + /** + * Get timestamp + * + * @return int + */ + public function getTimestamp() + { + return $this->ts; + } + + /** + * Get obj id + * + * @return int + */ + public function getObjId() + { + return $this->obj_id; + } + + /** + * Get ref id + * + * @return int + */ + public function getRefId() + { + return $this->ref_id; + } + + /** + * Get achieve text + * + * @return string + */ + public function getAchieveText() + { + return $this->achieve_text; + } + + /** + * Get achieve in text + * + * @return string + */ + public function getAchieveInText() + { + return $this->achieve_in_text; + } + + /** + * Get Icon path + * + * @return string + */ + public function getIconPath() + { + return $this->icon_path; + } +} diff --git a/Services/LearningHistory/classes/class.ilLearningHistoryEntryCollector.php b/Services/LearningHistory/classes/class.ilLearningHistoryEntryCollector.php index e6913471b3370e12dc0385f0bd25cde346d976ed..c4e9d938802a073c6100a15e587e72c08c3cc783 100644 --- a/Services/LearningHistory/classes/class.ilLearningHistoryEntryCollector.php +++ b/Services/LearningHistory/classes/class.ilLearningHistoryEntryCollector.php @@ -10,77 +10,75 @@ */ class ilLearningHistoryEntryCollector { - /** - * @var ilLearningHistoryService - */ - protected $service; + /** + * @var ilLearningHistoryService + */ + protected $service; - /** - * Constructor - * @param ilLearningHistoryService $service - */ - public function __construct(ilLearningHistoryService $service) - { - $this->service = $service; - } - - /** - * Get entries - * - * @param int $from unix timestamp - * @param int $to unix timestamp - * @param int $user_id user id - * @param array $classes - * @return ilLearningHistoryEntry[] - */ - public function getEntries(int $from = null, int $to = null, int $user_id = null, array $classes = null) - { - $entries = array(); - $lng = $this->service->language(); + /** + * Constructor + * @param ilLearningHistoryService $service + */ + public function __construct(ilLearningHistoryService $service) + { + $this->service = $service; + } + + /** + * Get entries + * + * @param int $from unix timestamp + * @param int $to unix timestamp + * @param int $user_id user id + * @param array $classes + * @return ilLearningHistoryEntry[] + */ + public function getEntries(int $from = null, int $to = null, int $user_id = null, array $classes = null) + { + $entries = array(); + $lng = $this->service->language(); - $to = (is_null($to)) - ? time() - : $to; - $from = (is_null($from)) - ? time() - (365 * 24 * 60 * 60) - : $from; + $to = (is_null($to)) + ? time() + : $to; + $from = (is_null($from)) + ? time() - (365 * 24 * 60 * 60) + : $from; - $sort_array = []; - foreach ($this->service->provider()->getAllProviders(true, $user_id) as $provider) - { - if (is_array($classes) && !in_array(get_class($provider), $classes)) { - continue; - } + $sort_array = []; + foreach ($this->service->provider()->getAllProviders(true, $user_id) as $provider) { + if (is_array($classes) && !in_array(get_class($provider), $classes)) { + continue; + } - foreach ($provider->getEntries($from, $to) as $e) - { - $sort_array[] = array("entry" => $e,"ts" => $e->getTimestamp()); - } - } + foreach ($provider->getEntries($from, $to) as $e) { + $sort_array[] = array("entry" => $e,"ts" => $e->getTimestamp()); + } + } - $sort_array = ilUtil::sortArray($sort_array, "ts", "desc"); + $sort_array = ilUtil::sortArray($sort_array, "ts", "desc"); - // add today entry - $entries = []; + // add today entry + $entries = []; - if (date("Y-m-d", $to) == date("Y-m-d", time())) - { - if (count($sort_array) == 0 || - date("Y-m-d", (current($sort_array)["ts"])) != date("Y-m-d", time())) - { - $entries[] = $this->service->factory()->entry($lng->txt("lhist_no_entries"), $lng->txt("lhist_no_entries"), - ilUtil::getImagePath("spacer.png"), time(), 0); - } - } + if (date("Y-m-d", $to) == date("Y-m-d", time())) { + if (count($sort_array) == 0 || + date("Y-m-d", (current($sort_array)["ts"])) != date("Y-m-d", time())) { + $entries[] = $this->service->factory()->entry( + $lng->txt("lhist_no_entries"), + $lng->txt("lhist_no_entries"), + ilUtil::getImagePath("spacer.png"), + time(), + 0 + ); + } + } - foreach ($sort_array as $s) - { - $entries[] = $s["entry"]; - } + foreach ($sort_array as $s) { + $entries[] = $s["entry"]; + } - return $entries; - } - - -} \ No newline at end of file + return $entries; + } +} diff --git a/Services/LearningHistory/classes/class.ilLearningHistoryFactory.php b/Services/LearningHistory/classes/class.ilLearningHistoryFactory.php index 78d9bdf815cbfe0cfa53475c94fb0ec6a87a7349..b3bf04a644e76617f54ebf706259fa9d9f881eea 100644 --- a/Services/LearningHistory/classes/class.ilLearningHistoryFactory.php +++ b/Services/LearningHistory/classes/class.ilLearningHistoryFactory.php @@ -10,43 +10,40 @@ */ class ilLearningHistoryFactory { - /** - * @var ilLearningHistoryService - */ - protected $service; - - /** - * Constructor - */ - public function __construct(ilLearningHistoryService $service) - { - $this->service = $service; - } - - /** - * Create entry - * - * @param $title - * @param $icon_path - * @param int $ts unix timestamp - * @return ilLearningHistoryEntry - */ - public function entry($achieve_text, $achieve_in_text, $icon_path, $ts, $obj_id, $ref_id = 0) - { - return new ilLearningHistoryEntry($achieve_text, $achieve_in_text, $icon_path, $ts, $obj_id, $ref_id); - } - - /** - * Entry collector - * - * @param - * @return - */ - public function collector() - { - return new ilLearningHistoryEntryCollector($this->service); - } - - - -} \ No newline at end of file + /** + * @var ilLearningHistoryService + */ + protected $service; + + /** + * Constructor + */ + public function __construct(ilLearningHistoryService $service) + { + $this->service = $service; + } + + /** + * Create entry + * + * @param $title + * @param $icon_path + * @param int $ts unix timestamp + * @return ilLearningHistoryEntry + */ + public function entry($achieve_text, $achieve_in_text, $icon_path, $ts, $obj_id, $ref_id = 0) + { + return new ilLearningHistoryEntry($achieve_text, $achieve_in_text, $icon_path, $ts, $obj_id, $ref_id); + } + + /** + * Entry collector + * + * @param + * @return + */ + public function collector() + { + return new ilLearningHistoryEntryCollector($this->service); + } +} diff --git a/Services/LearningHistory/classes/class.ilLearningHistoryGUI.php b/Services/LearningHistory/classes/class.ilLearningHistoryGUI.php index 547161e83cb0670db23a31086d0e4afb30b7d82b..2a59aac930aa48553faebaf71ef1e10282e78c6d 100644 --- a/Services/LearningHistory/classes/class.ilLearningHistoryGUI.php +++ b/Services/LearningHistory/classes/class.ilLearningHistoryGUI.php @@ -10,260 +10,254 @@ */ class ilLearningHistoryGUI { - const TAB_ID_LEARNING_HISTORY = 'lhist_learning_history'; - const TAB_ID_MY_CERTIFICATES = 'certificates'; - const MAX = 50; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTemplate - */ - protected $main_tpl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var \ILIAS\DI\UIServices - */ - protected $ui; - - /** @var ilSetting */ - protected $certificateSettings; - - /** @var ilTabsGUI */ - protected $tabs; - - /** @var bool */ - protected $show_more = false; - - /** @var int */ - protected $last_ts = 0; - - /** - * Constructor - */ - public function __construct() - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - - $this->lhist_service = $DIC->learningHistory(); - $this->ui = $this->lhist_service->ui(); - $this->main_tpl = $this->ui->mainTemplate(); - $this->lng = $this->lhist_service->language(); - $this->access = $this->lhist_service->access(); - $this->tabs = $DIC->tabs(); - - $this->lng->loadLanguageModule("lhist"); - - $this->user_id = $this->lhist_service->user()->getId(); - - $this->certificateSettings = new ilSetting("certificate"); - - $this->from = null; - $this->to = ((int) $_GET["to_ts"] > 0) - ? (int) $_GET["to_ts"] - : null; - - $this->main_tpl->addJavaScript("./Services/LearningHistory/js/LearningHistory.js"); - } - - /** - * Set user id - * - * @param int $user_id - */ - public function setUserId($user_id) - { - $this->user_id = $user_id; - } - - - /** - * Execute command - */ - function executeCommand() - { - $ctrl = $this->ctrl; - - $next_class = $ctrl->getNextClass($this); - $cmd = $ctrl->getCmd("show"); - - switch ($next_class) - { - default: - if (in_array($cmd, array("show", "renderAsync"))) - { - $this->$cmd(); - } - } - } - - - /** - * Show - */ - protected function show() - { - $main_tpl = $this->main_tpl; - $lng = $this->lng; - $f = $this->ui->factory(); - $renderer = $this->ui->renderer(); - - $html = $this->getHistoryHtml($this->from, $this->to); - - if ($html != "") - { - $main_tpl->setContent($html); - } - else - { - $main_tpl->setContent( - $renderer->render($f->messageBox()->info($lng->txt("lhist_no_entries")) - )); - } - } - - /** - * Render Async - */ - protected function renderAsync() - { - $response["timeline"] = $this->renderTimeline($this->from, $this->to); - $response["more"] = $this->show_more ? $this->renderButton() : ""; - echo json_encode($response); - exit; - } - - /** - * Get HTML - * - * @param null $from - * @param null $to - * @param null $classes - * @return string - * @throws ilCtrlException - */ - public function getEmbeddedHTML($from = null, $to = null, $classes = null, $a_mode = null) - { - $ctrl = $this->ctrl; - - return $ctrl->getHTML($this, ["from" => $from, "to" => $to, "classes" => $classes, "mode" => $a_mode]); - } - - /** - * Get HTML - * - * @param - * @return string - */ - public function getHTML($par) - { - return $this->getHistoryHtml($par["from"], $par["to"], $par["classes"], $par["mode"]); - } - - /** - * Get history html - * - * @return string - */ - protected function getHistoryHtml($from = null, $to = null, $classes = null, $mode = null) - { - $tpl = new ilTemplate("tpl.timeline.html", true, true, "Services/LearningHistory"); - - $tpl->setVariable("TIMELINE", $this->renderTimeline($from, $to, $classes, $mode)); - - if ($this->show_more && $mode != "print") - { - $tpl->setCurrentBlock("show_more"); - $tpl->setVariable("SHOW_MORE_BUTTON", $this->renderButton()); - $tpl->parseCurrentBlock(); - } - - return $tpl->get(); - } - - /** - * render timeline - * - * @param int $from unix timestamp - * @param int $to unix timestamp - * @param array $classes - * @return string - */ - protected function renderTimeline(int $from = null, int $to = null, array $classes = null, string $mode = null): string - { - $collector = $this->lhist_service->factory()->collector(); - $ctrl = $this->ctrl; - - $to = (is_null($to)) - ? time() - : $to; - $from = (is_null($from)) - ? $to - (365 * 24 * 60 * 60) - : $from; - - $entries = $collector->getEntries($from, $to, $this->user_id, $classes); - - $timeline = ilTimelineGUI::getInstance(); - $cnt = 0; - - reset($entries); - /** @var ilLearningHistoryEntry $e */ - while (($e = current($entries)) && $cnt < self::MAX) { - $timeline->addItem(new ilLearningHistoryTimelineItem($e, $this->ui, $this->user_id, $this->access, - $this->lhist_service->repositoryTree())); - $this->last_ts = $e->getTimestamp(); - next($entries); - $cnt++; - } - - $html = ""; - if (count($entries) > 0) - { - $html = $timeline->render($ctrl->isAsynch()); - } - - $this->show_more = (count($entries) > $cnt); - - return $html; - } - - - /** - * render Button - */ - protected function renderButton() - { - $ctrl = $this->ctrl; - $f = $this->ui->factory(); - $renderer = $this->ui->renderer(); - $ctrl->setParameter($this, "to_ts", $this->last_ts - 1); - $url = $ctrl->getLinkTarget($this, "renderAsync", "", true); - - $button = $f->button()->standard($this->lng->txt("lhist_show_more"), "") - ->withLoadingAnimationOnClick(true) - ->withOnLoadCode(function ($id) use ($url) { - return "il.LearningHistory.initShowMore('$id', '" . $url . "');"; - }); - if ($ctrl->isAsynch()) - { - return $renderer->renderAsync($button); - } else - { - return $renderer->render($button); - } - } - - - - -} \ No newline at end of file + const TAB_ID_LEARNING_HISTORY = 'lhist_learning_history'; + const TAB_ID_MY_CERTIFICATES = 'certificates'; + const MAX = 50; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTemplate + */ + protected $main_tpl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var \ILIAS\DI\UIServices + */ + protected $ui; + + /** @var ilSetting */ + protected $certificateSettings; + + /** @var ilTabsGUI */ + protected $tabs; + + /** @var bool */ + protected $show_more = false; + + /** @var int */ + protected $last_ts = 0; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + + $this->lhist_service = $DIC->learningHistory(); + $this->ui = $this->lhist_service->ui(); + $this->main_tpl = $this->ui->mainTemplate(); + $this->lng = $this->lhist_service->language(); + $this->access = $this->lhist_service->access(); + $this->tabs = $DIC->tabs(); + + $this->lng->loadLanguageModule("lhist"); + + $this->user_id = $this->lhist_service->user()->getId(); + + $this->certificateSettings = new ilSetting("certificate"); + + $this->from = null; + $this->to = ((int) $_GET["to_ts"] > 0) + ? (int) $_GET["to_ts"] + : null; + + $this->main_tpl->addJavaScript("./Services/LearningHistory/js/LearningHistory.js"); + } + + /** + * Set user id + * + * @param int $user_id + */ + public function setUserId($user_id) + { + $this->user_id = $user_id; + } + + + /** + * Execute command + */ + public function executeCommand() + { + $ctrl = $this->ctrl; + + $next_class = $ctrl->getNextClass($this); + $cmd = $ctrl->getCmd("show"); + + switch ($next_class) { + default: + if (in_array($cmd, array("show", "renderAsync"))) { + $this->$cmd(); + } + } + } + + + /** + * Show + */ + protected function show() + { + $main_tpl = $this->main_tpl; + $lng = $this->lng; + $f = $this->ui->factory(); + $renderer = $this->ui->renderer(); + + $html = $this->getHistoryHtml($this->from, $this->to); + + if ($html != "") { + $main_tpl->setContent($html); + } else { + $main_tpl->setContent( + $renderer->render( + $f->messageBox()->info($lng->txt("lhist_no_entries")) + ) + ); + } + } + + /** + * Render Async + */ + protected function renderAsync() + { + $response["timeline"] = $this->renderTimeline($this->from, $this->to); + $response["more"] = $this->show_more ? $this->renderButton() : ""; + echo json_encode($response); + exit; + } + + /** + * Get HTML + * + * @param null $from + * @param null $to + * @param null $classes + * @return string + * @throws ilCtrlException + */ + public function getEmbeddedHTML($from = null, $to = null, $classes = null, $a_mode = null) + { + $ctrl = $this->ctrl; + + return $ctrl->getHTML($this, ["from" => $from, "to" => $to, "classes" => $classes, "mode" => $a_mode]); + } + + /** + * Get HTML + * + * @param + * @return string + */ + public function getHTML($par) + { + return $this->getHistoryHtml($par["from"], $par["to"], $par["classes"], $par["mode"]); + } + + /** + * Get history html + * + * @return string + */ + protected function getHistoryHtml($from = null, $to = null, $classes = null, $mode = null) + { + $tpl = new ilTemplate("tpl.timeline.html", true, true, "Services/LearningHistory"); + + $tpl->setVariable("TIMELINE", $this->renderTimeline($from, $to, $classes, $mode)); + + if ($this->show_more && $mode != "print") { + $tpl->setCurrentBlock("show_more"); + $tpl->setVariable("SHOW_MORE_BUTTON", $this->renderButton()); + $tpl->parseCurrentBlock(); + } + + return $tpl->get(); + } + + /** + * render timeline + * + * @param int $from unix timestamp + * @param int $to unix timestamp + * @param array $classes + * @return string + */ + protected function renderTimeline(int $from = null, int $to = null, array $classes = null, string $mode = null) : string + { + $collector = $this->lhist_service->factory()->collector(); + $ctrl = $this->ctrl; + + $to = (is_null($to)) + ? time() + : $to; + $from = (is_null($from)) + ? $to - (365 * 24 * 60 * 60) + : $from; + + $entries = $collector->getEntries($from, $to, $this->user_id, $classes); + + $timeline = ilTimelineGUI::getInstance(); + $cnt = 0; + + reset($entries); + /** @var ilLearningHistoryEntry $e */ + while (($e = current($entries)) && $cnt < self::MAX) { + $timeline->addItem(new ilLearningHistoryTimelineItem( + $e, + $this->ui, + $this->user_id, + $this->access, + $this->lhist_service->repositoryTree() + )); + $this->last_ts = $e->getTimestamp(); + next($entries); + $cnt++; + } + + $html = ""; + if (count($entries) > 0) { + $html = $timeline->render($ctrl->isAsynch()); + } + + $this->show_more = (count($entries) > $cnt); + + return $html; + } + + + /** + * render Button + */ + protected function renderButton() + { + $ctrl = $this->ctrl; + $f = $this->ui->factory(); + $renderer = $this->ui->renderer(); + $ctrl->setParameter($this, "to_ts", $this->last_ts - 1); + $url = $ctrl->getLinkTarget($this, "renderAsync", "", true); + + $button = $f->button()->standard($this->lng->txt("lhist_show_more"), "") + ->withLoadingAnimationOnClick(true) + ->withOnLoadCode(function ($id) use ($url) { + return "il.LearningHistory.initShowMore('$id', '" . $url . "');"; + }); + if ($ctrl->isAsynch()) { + return $renderer->renderAsync($button); + } else { + return $renderer->render($button); + } + } +} diff --git a/Services/LearningHistory/classes/class.ilLearningHistoryGlobalScreenProvider.php b/Services/LearningHistory/classes/class.ilLearningHistoryGlobalScreenProvider.php index 41ea2de6a252e5cd599e084cd8741b1ec4789f29..df07470adacb20f7701b541279d072e3ce6c1e47 100644 --- a/Services/LearningHistory/classes/class.ilLearningHistoryGlobalScreenProvider.php +++ b/Services/LearningHistory/classes/class.ilLearningHistoryGlobalScreenProvider.php @@ -8,50 +8,54 @@ use ILIAS\GlobalScreen\Scope\MainMenu\Provider\AbstractStaticMainMenuProvider; * * @author Fabian Schmid */ -class ilLearningHistoryGlobalScreenProvider extends AbstractStaticMainMenuProvider { - - /** - * @var IdentificationInterface - */ - protected $top_item; - - - public function __construct(\ILIAS\DI\Container $dic) { - parent::__construct($dic); - $this->top_item = (new ilPDGlobalScreenProvider($dic))->getTopItem(); - } - - - /** - * @inheritDoc - */ - public function getStaticTopItems(): array { - return []; - } - - - /** - * @inheritDoc - */ - public function getStaticSubItems(): array { - $dic = $this->dic; - - $dic->language()->loadLanguageModule('lhist'); - - return [$this->mainmenu->link($this->if->identifier('mm_pd_lhist')) - ->withTitle($this->dic->language()->txt("lhist_learning_history")) - ->withAction($dic->ctrl()->getLinkTargetByClass(["ilPersonalDesktopGUI", "ilLearningHistoryGUI"])) - ->withParent($this->top_item) - ->withNonAvailableReason($this->dic->ui()->factory()->legacy("{$this->dic->language()->txt('component_not_active')}")) - ->withAvailableCallable( - function () use ($dic) { - return (bool)($dic->learningHistory()->isActive()); - } - ) - ->withVisibilityCallable( - function () use ($dic) { - return (bool)($dic->learningHistory()->isActive($dic->user()->getId())); - } - )]; - } +class ilLearningHistoryGlobalScreenProvider extends AbstractStaticMainMenuProvider +{ + + /** + * @var IdentificationInterface + */ + protected $top_item; + + + public function __construct(\ILIAS\DI\Container $dic) + { + parent::__construct($dic); + $this->top_item = (new ilPDGlobalScreenProvider($dic))->getTopItem(); + } + + + /** + * @inheritDoc + */ + public function getStaticTopItems() : array + { + return []; + } + + + /** + * @inheritDoc + */ + public function getStaticSubItems() : array + { + $dic = $this->dic; + + $dic->language()->loadLanguageModule('lhist'); + + return [$this->mainmenu->link($this->if->identifier('mm_pd_lhist')) + ->withTitle($this->dic->language()->txt("lhist_learning_history")) + ->withAction($dic->ctrl()->getLinkTargetByClass(["ilPersonalDesktopGUI", "ilLearningHistoryGUI"])) + ->withParent($this->top_item) + ->withNonAvailableReason($this->dic->ui()->factory()->legacy("{$this->dic->language()->txt('component_not_active')}")) + ->withAvailableCallable( + function () use ($dic) { + return (bool) ($dic->learningHistory()->isActive()); + } + ) + ->withVisibilityCallable( + function () use ($dic) { + return (bool) ($dic->learningHistory()->isActive($dic->user()->getId())); + } + )]; + } } diff --git a/Services/LearningHistory/classes/class.ilLearningHistoryProviderFactory.php b/Services/LearningHistory/classes/class.ilLearningHistoryProviderFactory.php index 767ab6ee4578ca897aee4009c8928e143b78ceda..76bfd1232bdcf55b1436e57114f8d51d610c6eca 100644 --- a/Services/LearningHistory/classes/class.ilLearningHistoryProviderFactory.php +++ b/Services/LearningHistory/classes/class.ilLearningHistoryProviderFactory.php @@ -10,54 +10,54 @@ */ class ilLearningHistoryProviderFactory { - /** - * @var ilLearningHistoryService - */ - protected $service; - - /** - * @var array - */ - protected static $providers = array( - ilTrackingLearningHistoryProvider::class, - ilBadgeLearningHistoryProvider::class, - ilCourseLearningHistoryProvider::class, - ilFirstLoginLearningHistoryProvider::class, - ilCertificateLearningHistoryProvider::class, - ilSkillLearningHistoryProvider::class - ); - - /** - * Constructor - */ - public function __construct($service) - { - $this->service = $service; - } - - /** - * Get all learning history providers - * - * @param bool $active_only get only active providers - * @param int $user_id get instances for user with user id - * @return ilLearningHistoryProviderInterface[] - */ - public function getAllProviders($active_only = false, $user_id = null) - { - $providers = array(); - - if ($user_id == 0) { - $user_id = $this->service->user()->getId(); - } - - foreach (self::$providers as $provider) { - /** @var ilLearningHistoryProviderInterface $provider */ - $providerInstance = new $provider($user_id, $this->service->factory(), $this->service->language()); - if (!$active_only || $providerInstance->isActive()) { - $providers[] = $providerInstance; - } - } - - return $providers; - } + /** + * @var ilLearningHistoryService + */ + protected $service; + + /** + * @var array + */ + protected static $providers = array( + ilTrackingLearningHistoryProvider::class, + ilBadgeLearningHistoryProvider::class, + ilCourseLearningHistoryProvider::class, + ilFirstLoginLearningHistoryProvider::class, + ilCertificateLearningHistoryProvider::class, + ilSkillLearningHistoryProvider::class + ); + + /** + * Constructor + */ + public function __construct($service) + { + $this->service = $service; + } + + /** + * Get all learning history providers + * + * @param bool $active_only get only active providers + * @param int $user_id get instances for user with user id + * @return ilLearningHistoryProviderInterface[] + */ + public function getAllProviders($active_only = false, $user_id = null) + { + $providers = array(); + + if ($user_id == 0) { + $user_id = $this->service->user()->getId(); + } + + foreach (self::$providers as $provider) { + /** @var ilLearningHistoryProviderInterface $provider */ + $providerInstance = new $provider($user_id, $this->service->factory(), $this->service->language()); + if (!$active_only || $providerInstance->isActive()) { + $providers[] = $providerInstance; + } + } + + return $providers; + } } diff --git a/Services/LearningHistory/classes/class.ilLearningHistoryService.php b/Services/LearningHistory/classes/class.ilLearningHistoryService.php index 736b20ddde15ac9adae181b27502664c85b169ff..a3546b8d64f03b546663f89f35e3abb0093ef389 100644 --- a/Services/LearningHistory/classes/class.ilLearningHistoryService.php +++ b/Services/LearningHistory/classes/class.ilLearningHistoryService.php @@ -10,145 +10,138 @@ */ class ilLearningHistoryService { - /** - * @var ilObjUser - */ - protected $current_user; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var \ILIAS\DI\UIServices - */ - protected $ui; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilTree - */ - protected $tree; - - /** - * Constructor - * @param ilObjUser $user - * @param ilLanguage $lng - * @param \ILIAS\DI\UIServices $ui - * @param ilAccessHandler $access - */ - public function __construct(ilObjUser $user, ilLanguage $lng, \ILIAS\DI\UIServices $ui, ilAccessHandler $access, ilTree $tree) - { - $this->current_user = $user; - $this->lng = $lng; - $this->ui = $ui; - $this->access = $access; - $this->tree = $tree; - } - - /** - * Get tree - * - * @return ilTree - */ - public function repositoryTree() - { - return $this->tree; - } - - /** - * Get access - * - * @return ilAccessHandler - */ - public function access() - { - return $this->access; - } - - /** - * Get current user - * - * @return ilObjUser - */ - public function user() - { - return $this->current_user; - } - - /** - * Get language object - * - * @return ilLanguage - */ - public function language() - { - return $this->lng; - } - - /** - * Get ui service - * - * @return \ILIAS\DI\UIServices - */ - public function ui() - { - return $this->ui; - } - - /** - * Factory for learning history entries - * - * @return ilLearningHistoryFactory - */ - public function factory() - { - return new ilLearningHistoryFactory($this); - } - - /** - * Provider - * - * @return ilLearningHistoryProviderFactory - */ - public function provider() - { - return new ilLearningHistoryProviderFactory($this); - } - - /** - * Is the service active? The service will be active, if any of its providers are active. - * - * @param int $user_id - * @return bool - */ - public function isActive(int $user_id = 0) - { - global $DIC; - - $setting = $DIC->settings(); - if ($setting->get("enable_learning_history") !== "1") - { - return false; - } - - if ($user_id = 0) - { - $user_id = $this->user()->getId(); - } - foreach ($this->provider()->getAllProviders(true, $user_id) as $p) - { - return true; - } - return false; - } - - - - -} \ No newline at end of file + /** + * @var ilObjUser + */ + protected $current_user; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var \ILIAS\DI\UIServices + */ + protected $ui; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilTree + */ + protected $tree; + + /** + * Constructor + * @param ilObjUser $user + * @param ilLanguage $lng + * @param \ILIAS\DI\UIServices $ui + * @param ilAccessHandler $access + */ + public function __construct(ilObjUser $user, ilLanguage $lng, \ILIAS\DI\UIServices $ui, ilAccessHandler $access, ilTree $tree) + { + $this->current_user = $user; + $this->lng = $lng; + $this->ui = $ui; + $this->access = $access; + $this->tree = $tree; + } + + /** + * Get tree + * + * @return ilTree + */ + public function repositoryTree() + { + return $this->tree; + } + + /** + * Get access + * + * @return ilAccessHandler + */ + public function access() + { + return $this->access; + } + + /** + * Get current user + * + * @return ilObjUser + */ + public function user() + { + return $this->current_user; + } + + /** + * Get language object + * + * @return ilLanguage + */ + public function language() + { + return $this->lng; + } + + /** + * Get ui service + * + * @return \ILIAS\DI\UIServices + */ + public function ui() + { + return $this->ui; + } + + /** + * Factory for learning history entries + * + * @return ilLearningHistoryFactory + */ + public function factory() + { + return new ilLearningHistoryFactory($this); + } + + /** + * Provider + * + * @return ilLearningHistoryProviderFactory + */ + public function provider() + { + return new ilLearningHistoryProviderFactory($this); + } + + /** + * Is the service active? The service will be active, if any of its providers are active. + * + * @param int $user_id + * @return bool + */ + public function isActive(int $user_id = 0) + { + global $DIC; + + $setting = $DIC->settings(); + if ($setting->get("enable_learning_history") !== "1") { + return false; + } + + if ($user_id = 0) { + $user_id = $this->user()->getId(); + } + foreach ($this->provider()->getAllProviders(true, $user_id) as $p) { + return true; + } + return false; + } +} diff --git a/Services/LearningHistory/classes/class.ilLearningHistoryTimelineItem.php b/Services/LearningHistory/classes/class.ilLearningHistoryTimelineItem.php index f51819784582bc48a4bf03e012639dce37103f30..9b383111502adc7156c93fff044b8dd313fd85bb 100644 --- a/Services/LearningHistory/classes/class.ilLearningHistoryTimelineItem.php +++ b/Services/LearningHistory/classes/class.ilLearningHistoryTimelineItem.php @@ -10,147 +10,133 @@ */ class ilLearningHistoryTimelineItem implements ilTimelineItemInt { - /** - * @var ilLearningHistoryEntry - */ - protected $lh_entry; - - /** - * @var \ILIAS\DI\UIServices - */ - protected $ui; - - /** - * @var int - */ - protected $user_id; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilTree - */ - protected $tree; - - /** - * Constructor - * ilLearningHistoryTimelineItem constructor. - * @param ilLearningHistoryEntry $lh_entry - */ - public function __construct( - ilLearningHistoryEntry $lh_entry, - \ILIAS\DI\UIServices $ui, - $user_id, - ilAccessHandler $access, - ilTree $tree - ) - { - $this->access = $access; - $this->lh_entry = $lh_entry; - $this->ui = $ui; - $this->user_id = $user_id; - $this->tree = $tree; - } - - /** - * @inheritdoc - */ - public function getDatetime() - { - return new ilDateTime($this->lh_entry->getTimestamp(), IL_CAL_UNIX); - } - - /** - * @inheritdoc - */ - public function render() - { - $access = $this->access; - - $tpl = new ilTemplate("tpl.timeline_item_inner.html", true, true, "Services/LearningHistory"); - - $f = $this->ui->factory(); - $r = $this->ui->renderer(); - - $ico = $f->icon()->custom($this->lh_entry->getIconPath(), '')->withSize(\ILIAS\UI\Component\Icon\Custom::MEDIUM); - - $obj_id = $this->lh_entry->getObjId(); - $title = ilObject::_lookupTitle($obj_id); - if ($this->lh_entry->getRefId() == 0) - { - $ref_ids = ilObject::_getAllReferences($obj_id); - } - else - { - $ref_ids = [$this->lh_entry->getRefId()]; - } - $readable_ref_id = 0; - foreach ($ref_ids as $ref_id) - { - if ($readable_ref_id == 0 && $access->checkAccessOfUser($this->user_id, "read", "", $ref_id)) - { - $readable_ref_id = $ref_id; - } - } - - if ($readable_ref_id > 0) - { - if (ilObject::_lookupType(ilObject::_lookupObjId($readable_ref_id)) == "crs") - { - $parent_ref_id = $readable_ref_id; - } - else - { - $parent_ref_id = $this->tree->checkForParentType($readable_ref_id, "crs", true); - } - } - - if ($parent_ref_id > 0) - { - $text = $this->lh_entry->getAchieveInText(); - $obj_placeholder = "" . - $this->getEmphasizedTitle(ilObject::_lookupTitle(ilObject::_lookupObjId($parent_ref_id))) . ""; - $text = str_replace("$2$", $obj_placeholder, $text); - } - else - { - $text = $this->lh_entry->getAchieveText(); - } - - $obj_placeholder = ($readable_ref_id > 0) - ? "" . $this->getEmphasizedTitle($title) . "" - : $this->getEmphasizedTitle($title); - $text = str_replace("$1$", $obj_placeholder, $text); - - $tpl->setVariable("TEXT", $text); - $tpl->setVariable("ICON", $r->render($ico)); - - return $tpl->get(); - } - - /** - * Get emphasized title - * - * @param string - * @return string - */ - protected function getEmphasizedTitle($title) - { - $tpl = new ilTemplate("tpl.emphasized_title.php", true, true, "Services/LearningHistory"); - $tpl->setVariable("TITLE", $title);; - return $tpl->get(); - } - - /** - * Render footer - * @throws ilCtrlException - */ - function renderFooter() - { - } - - - } \ No newline at end of file + /** + * @var ilLearningHistoryEntry + */ + protected $lh_entry; + + /** + * @var \ILIAS\DI\UIServices + */ + protected $ui; + + /** + * @var int + */ + protected $user_id; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilTree + */ + protected $tree; + + /** + * Constructor + * ilLearningHistoryTimelineItem constructor. + * @param ilLearningHistoryEntry $lh_entry + */ + public function __construct( + ilLearningHistoryEntry $lh_entry, + \ILIAS\DI\UIServices $ui, + $user_id, + ilAccessHandler $access, + ilTree $tree + ) { + $this->access = $access; + $this->lh_entry = $lh_entry; + $this->ui = $ui; + $this->user_id = $user_id; + $this->tree = $tree; + } + + /** + * @inheritdoc + */ + public function getDatetime() + { + return new ilDateTime($this->lh_entry->getTimestamp(), IL_CAL_UNIX); + } + + /** + * @inheritdoc + */ + public function render() + { + $access = $this->access; + + $tpl = new ilTemplate("tpl.timeline_item_inner.html", true, true, "Services/LearningHistory"); + + $f = $this->ui->factory(); + $r = $this->ui->renderer(); + + $ico = $f->icon()->custom($this->lh_entry->getIconPath(), '')->withSize(\ILIAS\UI\Component\Icon\Custom::MEDIUM); + + $obj_id = $this->lh_entry->getObjId(); + $title = ilObject::_lookupTitle($obj_id); + if ($this->lh_entry->getRefId() == 0) { + $ref_ids = ilObject::_getAllReferences($obj_id); + } else { + $ref_ids = [$this->lh_entry->getRefId()]; + } + $readable_ref_id = 0; + foreach ($ref_ids as $ref_id) { + if ($readable_ref_id == 0 && $access->checkAccessOfUser($this->user_id, "read", "", $ref_id)) { + $readable_ref_id = $ref_id; + } + } + + if ($readable_ref_id > 0) { + if (ilObject::_lookupType(ilObject::_lookupObjId($readable_ref_id)) == "crs") { + $parent_ref_id = $readable_ref_id; + } else { + $parent_ref_id = $this->tree->checkForParentType($readable_ref_id, "crs", true); + } + } + + if ($parent_ref_id > 0) { + $text = $this->lh_entry->getAchieveInText(); + $obj_placeholder = "" . + $this->getEmphasizedTitle(ilObject::_lookupTitle(ilObject::_lookupObjId($parent_ref_id))) . ""; + $text = str_replace("$2$", $obj_placeholder, $text); + } else { + $text = $this->lh_entry->getAchieveText(); + } + + $obj_placeholder = ($readable_ref_id > 0) + ? "" . $this->getEmphasizedTitle($title) . "" + : $this->getEmphasizedTitle($title); + $text = str_replace("$1$", $obj_placeholder, $text); + + $tpl->setVariable("TEXT", $text); + $tpl->setVariable("ICON", $r->render($ico)); + + return $tpl->get(); + } + + /** + * Get emphasized title + * + * @param string + * @return string + */ + protected function getEmphasizedTitle($title) + { + $tpl = new ilTemplate("tpl.emphasized_title.php", true, true, "Services/LearningHistory"); + $tpl->setVariable("TITLE", $title); + ; + return $tpl->get(); + } + + /** + * Render footer + * @throws ilCtrlException + */ + public function renderFooter() + { + } +} diff --git a/Services/LearningHistory/classes/class.ilPCLearningHistory.php b/Services/LearningHistory/classes/class.ilPCLearningHistory.php index f0c826164071284ad5d7fc4952320d04f5b3d56d..bb9d1f514d937a5f406506463d0690447e14ecab 100644 --- a/Services/LearningHistory/classes/class.ilPCLearningHistory.php +++ b/Services/LearningHistory/classes/class.ilPCLearningHistory.php @@ -1,277 +1,263 @@ -user = $DIC->user(); - $this->setType("lhist"); - } - - /** - * Set node - */ - function setNode($a_node) - { - parent::setNode($a_node); // this is the PageContent node - $this->lhist_node = $a_node->first_child(); // this is the skill node - } - - /** - * Create learning history node - * - * @param ilPageObject $a_pg_obj - * @param string $a_hier_id - * @param string $a_pc_id - */ - function create(ilPageObject $a_pg_obj, string $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->lhist_node = $this->dom->create_element("LearningHistory"); - $this->lhist_node = $this->node->append_child($this->lhist_node); - } - - /** - * Set from - * - * @param string $a_val from - */ - function setFrom($a_val) - { - $this->lhist_node->set_attribute("From", $a_val); - } - - /** - * Get from - * - * @return string from - */ - function getFrom() - { - return $this->lhist_node->get_attribute("From"); - } - - /** - * Set to - * - * @param string $a_val to - */ - function setTo($a_val) - { - $this->lhist_node->set_attribute("To", $a_val); - } - - /** - * Get to - * - * @return string to - */ - function getTo() - { - return $this->lhist_node->get_attribute("To"); - } - - /** - * Set classes - * - * @param array $a_val classes - */ - function setClasses($a_val) - { - // delete properties - $children = $this->lhist_node->child_nodes(); - for($i=0; $ilhist_node->remove_child($children[$i]); - } - // set classes - foreach($a_val as $key => $class) - { - $prop_node = $this->dom->create_element("LearningHistoryProvider"); - $prop_node = $this->lhist_node->append_child($prop_node); - $prop_node->set_attribute("Name", $class); - } - } - - /** - * Get classes - * - * @return array classes - */ - function getClasses() - { - $classes = []; - // delete properties - $children = $this->lhist_node->child_nodes(); - for($i=0; $iget_attribute("Name"); - } - return $classes; - } - - - /** - * After page has been updated (or created) - * - * @param object $a_page page object - * @param DOMDocument $a_domdoc dom document - * @param string $a_xml xml - * @param bool $a_creation true on creation, otherwise false - */ - static function afterPageUpdate($a_page, DOMDocument $a_domdoc, $a_xml, $a_creation) - { - } - - /** - * Before page is being deleted - * - * @param object $a_page page object - */ - static function beforePageDelete($a_page) - { - } - - /** - * After page history entry has been created - * - * @param object $a_page page object - * @param DOMDocument $a_old_domdoc old dom document - * @param string $a_old_xml old xml - * @param integer $a_old_nr history number - */ - static function afterPageHistoryEntry($a_page, DOMDocument $a_old_domdoc, $a_old_xml, $a_old_nr) - { - } - - /** - * Get lang vars needed for editing - * @return array array of lang var keys - */ - static function getLangVars() - { - return array("ed_insert_learning_history", "pc_learning_history"); - } - - /** - * Modify page content after xsl - * - * @param string $a_output - * @return string - */ - function modifyPageContentPostXsl($a_html, $a_mode) - { - $lng = $this->lng; - $ilPluginAdmin = $this->plugin_admin; - - $start = strpos($a_html, "{{{{{LearningHistory"); - if (is_int($start)) - { - $end = strpos($a_html, "}}}}}", $start); - } - - while ($end > 0) - { - $param = substr($a_html, $start + 5, $end - $start - 5); - $param = str_replace(' xmlns:xhtml="http://www.w3.org/1999/xhtml"', "", $param); - $param = explode("#", $param); - $from = $param[1]; - $to = $param[2]; - $classes = explode(";", $param[3]); - $classes = array_map(function($i) { - return trim($i); - }, $classes); - - - $a_html = substr($a_html, 0, $start). - $this->getPresentation($from, $to, $classes, $a_mode). - substr($a_html, $end + 5); - - if (strlen($a_html) > $start + 5) - { - $start = strpos($a_html, "{{{{{LearningHistory", $start + 5); - } - else - { - $start = false; - } - $end = 0; - if (is_int($start)) - { - $end = strpos($a_html, "}}}}}", $start); - } - } - - return $a_html; - } - - /** - * Get presentation - * - * @param int $from unix timestamp - * @param int $to unix timestamp - * @param array $classes - * @param string $mode - * @return string - * @throws ilCtrlException - */ - protected function getPresentation($from, $to, $classes, $a_mode): string - { - if ($a_mode == "preview" || $a_mode == "presentation" || $a_mode == "print") - { - if ($this->getPage()->getParentType() == "prtf") - { - $user_id = ilObject::_lookupOwner($this->getPage()->getPortfolioId()); - } - } - if ($user_id > 0) - { - $tpl = new ilTemplate("tpl.pc_lhist.html", true, true, "Services/LearningHistory"); - $hist_gui = new ilLearningHistoryGUI(); - $hist_gui->setUserId($user_id); - $from_unix = ($from != "") - ? (new ilDateTime($from." 00:00:00", IL_CAL_DATETIME))->get(IL_CAL_UNIX) - : null; - $to_unix = ($to != "") - ? (new ilDateTime($to." 23:59:59", IL_CAL_DATETIME))->get(IL_CAL_UNIX) - : null; - $classes = (is_array($classes)) - ? array_filter($classes, function($i) {return ($i != "");}) - : null; - if (count($classes) == 0) - { - $classes = null; - } - $tpl->setVariable("LHIST", $hist_gui->getEmbeddedHtml($from_unix, $to_unix, $classes, $a_mode)); - return $tpl->get(); - } - - return ilPCLearningHistoryGUI::getPlaceHolderPresentation(); - } - - -} -?> +user = $DIC->user(); + $this->setType("lhist"); + } + + /** + * Set node + */ + public function setNode($a_node) + { + parent::setNode($a_node); // this is the PageContent node + $this->lhist_node = $a_node->first_child(); // this is the skill node + } + + /** + * Create learning history node + * + * @param ilPageObject $a_pg_obj + * @param string $a_hier_id + * @param string $a_pc_id + */ + public function create(ilPageObject $a_pg_obj, string $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->lhist_node = $this->dom->create_element("LearningHistory"); + $this->lhist_node = $this->node->append_child($this->lhist_node); + } + + /** + * Set from + * + * @param string $a_val from + */ + public function setFrom($a_val) + { + $this->lhist_node->set_attribute("From", $a_val); + } + + /** + * Get from + * + * @return string from + */ + public function getFrom() + { + return $this->lhist_node->get_attribute("From"); + } + + /** + * Set to + * + * @param string $a_val to + */ + public function setTo($a_val) + { + $this->lhist_node->set_attribute("To", $a_val); + } + + /** + * Get to + * + * @return string to + */ + public function getTo() + { + return $this->lhist_node->get_attribute("To"); + } + + /** + * Set classes + * + * @param array $a_val classes + */ + public function setClasses($a_val) + { + // delete properties + $children = $this->lhist_node->child_nodes(); + for ($i=0; $ilhist_node->remove_child($children[$i]); + } + // set classes + foreach ($a_val as $key => $class) { + $prop_node = $this->dom->create_element("LearningHistoryProvider"); + $prop_node = $this->lhist_node->append_child($prop_node); + $prop_node->set_attribute("Name", $class); + } + } + + /** + * Get classes + * + * @return array classes + */ + public function getClasses() + { + $classes = []; + // delete properties + $children = $this->lhist_node->child_nodes(); + for ($i=0; $iget_attribute("Name"); + } + return $classes; + } + + + /** + * After page has been updated (or created) + * + * @param object $a_page page object + * @param DOMDocument $a_domdoc dom document + * @param string $a_xml xml + * @param bool $a_creation true on creation, otherwise false + */ + public static function afterPageUpdate($a_page, DOMDocument $a_domdoc, $a_xml, $a_creation) + { + } + + /** + * Before page is being deleted + * + * @param object $a_page page object + */ + public static function beforePageDelete($a_page) + { + } + + /** + * After page history entry has been created + * + * @param object $a_page page object + * @param DOMDocument $a_old_domdoc old dom document + * @param string $a_old_xml old xml + * @param integer $a_old_nr history number + */ + public static function afterPageHistoryEntry($a_page, DOMDocument $a_old_domdoc, $a_old_xml, $a_old_nr) + { + } + + /** + * Get lang vars needed for editing + * @return array array of lang var keys + */ + public static function getLangVars() + { + return array("ed_insert_learning_history", "pc_learning_history"); + } + + /** + * Modify page content after xsl + * + * @param string $a_output + * @return string + */ + public function modifyPageContentPostXsl($a_html, $a_mode) + { + $lng = $this->lng; + $ilPluginAdmin = $this->plugin_admin; + + $start = strpos($a_html, "{{{{{LearningHistory"); + if (is_int($start)) { + $end = strpos($a_html, "}}}}}", $start); + } + + while ($end > 0) { + $param = substr($a_html, $start + 5, $end - $start - 5); + $param = str_replace(' xmlns:xhtml="http://www.w3.org/1999/xhtml"', "", $param); + $param = explode("#", $param); + $from = $param[1]; + $to = $param[2]; + $classes = explode(";", $param[3]); + $classes = array_map(function ($i) { + return trim($i); + }, $classes); + + + $a_html = substr($a_html, 0, $start) . + $this->getPresentation($from, $to, $classes, $a_mode) . + substr($a_html, $end + 5); + + if (strlen($a_html) > $start + 5) { + $start = strpos($a_html, "{{{{{LearningHistory", $start + 5); + } else { + $start = false; + } + $end = 0; + if (is_int($start)) { + $end = strpos($a_html, "}}}}}", $start); + } + } + + return $a_html; + } + + /** + * Get presentation + * + * @param int $from unix timestamp + * @param int $to unix timestamp + * @param array $classes + * @param string $mode + * @return string + * @throws ilCtrlException + */ + protected function getPresentation($from, $to, $classes, $a_mode) : string + { + if ($a_mode == "preview" || $a_mode == "presentation" || $a_mode == "print") { + if ($this->getPage()->getParentType() == "prtf") { + $user_id = ilObject::_lookupOwner($this->getPage()->getPortfolioId()); + } + } + if ($user_id > 0) { + $tpl = new ilTemplate("tpl.pc_lhist.html", true, true, "Services/LearningHistory"); + $hist_gui = new ilLearningHistoryGUI(); + $hist_gui->setUserId($user_id); + $from_unix = ($from != "") + ? (new ilDateTime($from . " 00:00:00", IL_CAL_DATETIME))->get(IL_CAL_UNIX) + : null; + $to_unix = ($to != "") + ? (new ilDateTime($to . " 23:59:59", IL_CAL_DATETIME))->get(IL_CAL_UNIX) + : null; + $classes = (is_array($classes)) + ? array_filter($classes, function ($i) { + return ($i != ""); + }) + : null; + if (count($classes) == 0) { + $classes = null; + } + $tpl->setVariable("LHIST", $hist_gui->getEmbeddedHtml($from_unix, $to_unix, $classes, $a_mode)); + return $tpl->get(); + } + + return ilPCLearningHistoryGUI::getPlaceHolderPresentation(); + } +} diff --git a/Services/LearningHistory/classes/class.ilPCLearningHistoryGUI.php b/Services/LearningHistory/classes/class.ilPCLearningHistoryGUI.php index d5b89b6343f0201e38ea12a695a6f7769f7e9cb8..8aa18f85f831a5c8766b73e6427ad7aa627a2c88 100644 --- a/Services/LearningHistory/classes/class.ilPCLearningHistoryGUI.php +++ b/Services/LearningHistory/classes/class.ilPCLearningHistoryGUI.php @@ -1,309 +1,290 @@ -tpl = $DIC["tpl"]; - $this->ctrl = $DIC->ctrl(); - $this->user = $DIC->user(); - $this->lng = $DIC->language(); - $this->lng->loadLanguageModule("lhist"); - parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); - $this->service = $DIC->learningHistory(); - $this->ui = $DIC->ui(); - } - - /** - * 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 learning history form - * - * @param ilPropertyFormGUI $a_form - */ - function insert(ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - - $this->displayValidationError(); - - if(!$a_form) - { - $a_form = $this->initForm(true); - } - $tpl->setContent($a_form->getHTML()); - - } - - /** - * Edit skills form - * - * @param ilPropertyFormGUI $a_form - */ - function edit(ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - - $this->displayValidationError(); - - if(!$a_form) - { - $a_form = $this->initForm(); - } - $tpl->setContent($a_form->getHTML()); - } - - /** - * Init learning history edit form - * - * @param bool $a_insert - * @return ilPropertyFormGUI - */ - protected function initForm($a_insert = false) - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - $lng = $this->lng; - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this)); - if ($a_insert) - { - $form->setTitle($this->lng->txt("cont_create_lhist")); - } - else - { - $form->setTitle($this->lng->txt("cont_update_lhist")); - } - - // duration - $du = new ilDateDurationInputGUI($lng->txt("lhist_period"), "period"); - if (!$a_insert) { - if ($this->content_obj->getFrom() != "") { - $du->setStart(new ilDate($this->content_obj->getFrom(), IL_CAL_DATE)); - } - if ($this->content_obj->getTo() != "") { - $du->setEnd(new ilDate($this->content_obj->getTo(), IL_CAL_DATE)); - } - } - $du->setAllowOpenIntervals(true); - $form->addItem($du); - - // - $radg = new ilRadioGroupInputGUI($lng->txt("lhist_type_of_achievement"), "mode"); - //$radg->setValue(); - $op1 = new ilRadioOption($lng->txt("lhist_all"), 0); - $radg->addOption($op1); - $op2 = new ilRadioOption($lng->txt("lhist_selected"), 1); - $radg->addOption($op2); - $form->addItem($radg); - - - // select type - $options = []; - foreach ($this->service->provider()->getAllProviders(true) as $p) - { - $options[get_class($p)] = $p->getName(); - } - $si = new ilMultiSelectInputGUI($lng->txt(""), "class"); - $si->setHeight(130); - if (!$a_insert) { - $si->setValue($this->content_obj->getClasses()); - if (count($this->content_obj->getClasses()) > 0) { - $radg->setValue(1); - } - } - $si->setOptions($options); - $op2->addSubItem($si); - - - - if ($a_insert) - { - $form->addCommandButton("create_lhist", $this->lng->txt("insert")); - $form->addCommandButton("cancelCreate", $this->lng->txt("cancel")); - } - else - { - $form->addCommandButton("update", $this->lng->txt("save")); - $form->addCommandButton("cancelUpdate", $this->lng->txt("cancel")); - } - - return $form; - } - - - /** - * Create new learning history component - */ - function create() - { - $valid = false; - - $form = $this->initForm(true); - if($form->checkInput()) - { - //$data = $form->getInput("skill_id"); - $valid = true; - } - - if($valid) - { - $this->content_obj = new ilPCLearningHistory($this->getPage()); - $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); - $this->setAttributesFromInput($form); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - } - - $form->setValuesByPost(); - return $this->insert($form); - } - - /** - * Update learning history component - */ - function update() - { - $form = $this->initForm(); - if($form->checkInput()) - { - $this->setAttributesFromInput($form); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - ilUtil::sendInfo($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - } - - $this->pg_obj->addHierIDs(); - $form->setValuesByPost(); - return $this->edit($form); - } - - /** - * - * - * @param - * @return - */ - protected function setAttributesFromInput($form) - { - /** @var ilDurationInputGUI $item */ - $item = $form->getItemByPostVar("period"); - $from = (is_null($item->getStart())) - ? "" - : $item->getStart()->get(IL_CAL_DATE); - $to = (is_null($item->getEnd())) - ? "" - : $item->getEnd()->get(IL_CAL_DATE); - - $this->content_obj->setFrom($from); - $this->content_obj->setTo($to); - $classes = ($form->getInput("mode") == "1" && is_array($form->getInput("class"))) - ? $form->getInput("class") - : array(); - $this->content_obj->setClasses($classes); - } - - /** - * Get placeholder presentation - * - * @param - * @return - */ - static public function getPlaceholderPresentation() - { - global $DIC; - - $lng = $DIC->language(); - $lng->loadLanguageModule("lhist"); - - // @todo we need a ks element for this - $content = '

                  '.$lng->txt("lhist_lhist").'

                  '. - $lng->txt("lhist_cont_placeholder_text").'
                  '; - - return $content; - } - -} - -?> \ No newline at end of file +tpl = $DIC["tpl"]; + $this->ctrl = $DIC->ctrl(); + $this->user = $DIC->user(); + $this->lng = $DIC->language(); + $this->lng->loadLanguageModule("lhist"); + parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); + $this->service = $DIC->learningHistory(); + $this->ui = $DIC->ui(); + } + + /** + * 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 learning history form + * + * @param ilPropertyFormGUI $a_form + */ + public function insert(ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + + $this->displayValidationError(); + + if (!$a_form) { + $a_form = $this->initForm(true); + } + $tpl->setContent($a_form->getHTML()); + } + + /** + * Edit skills form + * + * @param ilPropertyFormGUI $a_form + */ + public function edit(ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + + $this->displayValidationError(); + + if (!$a_form) { + $a_form = $this->initForm(); + } + $tpl->setContent($a_form->getHTML()); + } + + /** + * Init learning history edit form + * + * @param bool $a_insert + * @return ilPropertyFormGUI + */ + protected function initForm($a_insert = false) + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + $lng = $this->lng; + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this)); + if ($a_insert) { + $form->setTitle($this->lng->txt("cont_create_lhist")); + } else { + $form->setTitle($this->lng->txt("cont_update_lhist")); + } + + // duration + $du = new ilDateDurationInputGUI($lng->txt("lhist_period"), "period"); + if (!$a_insert) { + if ($this->content_obj->getFrom() != "") { + $du->setStart(new ilDate($this->content_obj->getFrom(), IL_CAL_DATE)); + } + if ($this->content_obj->getTo() != "") { + $du->setEnd(new ilDate($this->content_obj->getTo(), IL_CAL_DATE)); + } + } + $du->setAllowOpenIntervals(true); + $form->addItem($du); + + // + $radg = new ilRadioGroupInputGUI($lng->txt("lhist_type_of_achievement"), "mode"); + //$radg->setValue(); + $op1 = new ilRadioOption($lng->txt("lhist_all"), 0); + $radg->addOption($op1); + $op2 = new ilRadioOption($lng->txt("lhist_selected"), 1); + $radg->addOption($op2); + $form->addItem($radg); + + + // select type + $options = []; + foreach ($this->service->provider()->getAllProviders(true) as $p) { + $options[get_class($p)] = $p->getName(); + } + $si = new ilMultiSelectInputGUI($lng->txt(""), "class"); + $si->setHeight(130); + if (!$a_insert) { + $si->setValue($this->content_obj->getClasses()); + if (count($this->content_obj->getClasses()) > 0) { + $radg->setValue(1); + } + } + $si->setOptions($options); + $op2->addSubItem($si); + + + + if ($a_insert) { + $form->addCommandButton("create_lhist", $this->lng->txt("insert")); + $form->addCommandButton("cancelCreate", $this->lng->txt("cancel")); + } else { + $form->addCommandButton("update", $this->lng->txt("save")); + $form->addCommandButton("cancelUpdate", $this->lng->txt("cancel")); + } + + return $form; + } + + + /** + * Create new learning history component + */ + public function create() + { + $valid = false; + + $form = $this->initForm(true); + if ($form->checkInput()) { + //$data = $form->getInput("skill_id"); + $valid = true; + } + + if ($valid) { + $this->content_obj = new ilPCLearningHistory($this->getPage()); + $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id); + $this->setAttributesFromInput($form); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + } + + $form->setValuesByPost(); + return $this->insert($form); + } + + /** + * Update learning history component + */ + public function update() + { + $form = $this->initForm(); + if ($form->checkInput()) { + $this->setAttributesFromInput($form); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + ilUtil::sendInfo($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } + } + + $this->pg_obj->addHierIDs(); + $form->setValuesByPost(); + return $this->edit($form); + } + + /** + * + * + * @param + * @return + */ + protected function setAttributesFromInput($form) + { + /** @var ilDurationInputGUI $item */ + $item = $form->getItemByPostVar("period"); + $from = (is_null($item->getStart())) + ? "" + : $item->getStart()->get(IL_CAL_DATE); + $to = (is_null($item->getEnd())) + ? "" + : $item->getEnd()->get(IL_CAL_DATE); + + $this->content_obj->setFrom($from); + $this->content_obj->setTo($to); + $classes = ($form->getInput("mode") == "1" && is_array($form->getInput("class"))) + ? $form->getInput("class") + : array(); + $this->content_obj->setClasses($classes); + } + + /** + * Get placeholder presentation + * + * @param + * @return + */ + public static function getPlaceholderPresentation() + { + global $DIC; + + $lng = $DIC->language(); + $lng->loadLanguageModule("lhist"); + + // @todo we need a ks element for this + $content = '

                  ' . $lng->txt("lhist_lhist") . '

                  ' . + $lng->txt("lhist_cont_placeholder_text") . '
                  '; + + return $content; + } +} diff --git a/Services/LearningHistory/interfaces/class.ilAbstractLearningHistoryProvider.php b/Services/LearningHistory/interfaces/class.ilAbstractLearningHistoryProvider.php index 130f9e183851ca80acd5e5152772a5b466e5173b..81cde65a0a5605275ea400551bbf0412b9e02cc6 100644 --- a/Services/LearningHistory/interfaces/class.ilAbstractLearningHistoryProvider.php +++ b/Services/LearningHistory/interfaces/class.ilAbstractLearningHistoryProvider.php @@ -10,99 +10,97 @@ */ abstract class ilAbstractLearningHistoryProvider { - /** - * User id. This is the user the history will be retrieved for. - * - * @var int - */ - protected $user_id; + /** + * User id. This is the user the history will be retrieved for. + * + * @var int + */ + protected $user_id; - /** - * @var ilLearningHistoryFactory - */ - protected $factory; + /** + * @var ilLearningHistoryFactory + */ + protected $factory; - /** - * @var iLanguage - */ - protected $lng; + /** + * @var iLanguage + */ + protected $lng; - /** - * @var ilTemplate|null - */ - private $template; + /** + * @var ilTemplate|null + */ + private $template; - /** - * Constructor - * @param int $user_id - * @param ilLearningHistoryFactory $factory - * @param ilLanguage $lng - * @param ilTemplate|null $template - */ - public function __construct( - $user_id, - ilLearningHistoryFactory $factory, - ilLanguage $lng, - ilTemplate $template = null - ) { - $this->user_id = $user_id; - $this->factory = $factory; - $this->lng = $lng; + /** + * Constructor + * @param int $user_id + * @param ilLearningHistoryFactory $factory + * @param ilLanguage $lng + * @param ilTemplate|null $template + */ + public function __construct( + $user_id, + ilLearningHistoryFactory $factory, + ilLanguage $lng, + ilTemplate $template = null + ) { + $this->user_id = $user_id; + $this->factory = $factory; + $this->lng = $lng; - if ($template === null) { - $template = new ilTemplate( - 'tpl.emphasized_title.php', - true, - true, - 'Services/LearningHistory' - ); - } - $this->template = $template; - } + if ($template === null) { + $template = new ilTemplate( + 'tpl.emphasized_title.php', + true, + true, + 'Services/LearningHistory' + ); + } + $this->template = $template; + } - /** - * Get user id - * - * @param - * @return - */ - protected function getUserId() - { - return $this->user_id; - } + /** + * Get user id + * + * @param + * @return + */ + protected function getUserId() + { + return $this->user_id; + } - /** - * Get factory - * - * @return ilLearningHistoryFactory - */ - protected function getFactory() - { - return $this->factory; - } - - /** - * Get language object - * - * @return ilLanguage - */ - protected function getLanguage() - { - return $this->lng; - } - - /** - * Get emphasized title - * - * @param string - * @return string - */ - protected function getEmphasizedTitle($title) - { - $clone = clone $this->template; - $clone->setVariable("TITLE", $title); - return $clone->get(); - } + /** + * Get factory + * + * @return ilLearningHistoryFactory + */ + protected function getFactory() + { + return $this->factory; + } + /** + * Get language object + * + * @return ilLanguage + */ + protected function getLanguage() + { + return $this->lng; + } + /** + * Get emphasized title + * + * @param string + * @return string + */ + protected function getEmphasizedTitle($title) + { + $clone = clone $this->template; + $clone->setVariable("TITLE", $title); + return $clone->get(); + } } diff --git a/Services/LearningHistory/interfaces/interface.ilLearningHistoryProvider.php b/Services/LearningHistory/interfaces/interface.ilLearningHistoryProvider.php index 4447229a1d1fa115cbe1d1bb6b96207f3e254fa0..4bdd1c879d4d61d68dd15c17f5b684335b0f5162 100644 --- a/Services/LearningHistory/interfaces/interface.ilLearningHistoryProvider.php +++ b/Services/LearningHistory/interfaces/interface.ilLearningHistoryProvider.php @@ -12,26 +12,25 @@ */ interface ilLearningHistoryProviderInterface { - /** - * Is active? - * - * @return bool - */ - function isActive(); + /** + * Is active? + * + * @return bool + */ + public function isActive(); - /** - * Get entries - * - * @param int $ts_start - * @param int $ts_end - * @return ilLearningHistoryEntry[] - */ - function getEntries($ts_start, $ts_end); + /** + * Get entries + * + * @param int $ts_start + * @param int $ts_end + * @return ilLearningHistoryEntry[] + */ + public function getEntries($ts_start, $ts_end); - /** - * Get name of provider (in user language) - * @return string - */ - function getName(): string; - -} \ No newline at end of file + /** + * Get name of provider (in user language) + * @return string + */ + public function getName() : string; +} diff --git a/Services/Like/classes/class.ilLikeData.php b/Services/Like/classes/class.ilLikeData.php index bc0d03b4b8828bd175bceb1ca5dc6726ca86e90a..2f4e7d42fd96777a4b4502d003d026bb0af5b8a1 100644 --- a/Services/Like/classes/class.ilLikeData.php +++ b/Services/Like/classes/class.ilLikeData.php @@ -18,331 +18,324 @@ */ class ilLikeData { - const TYPE_LIKE = 0; - const TYPE_DISLIKE = 1; - const TYPE_LOVE = 2; - const TYPE_LAUGH = 3; - const TYPE_ASTOUNDED = 4; - const TYPE_SAD = 5; - const TYPE_ANGRY = 6; - - /** - * - * @var array - */ - protected $data = array(); - - /** - * @var ilDB - */ - protected $db; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * Constructor - * @param ilDB $db - */ - function __construct(array $a_obj_ids = array(), ilDB $db = null, $lng = null) - { - global $DIC; - - $this->db = ($db == null) - ? $DIC->database() - : $db; - - $this->lng = ($lng == null) - ? $DIC->language() - : $lng; - $this->loadDataForObjects($a_obj_ids); - $this->lng->loadLanguageModule("like"); - } - - /** - * Get types - * - * @param - * @return array - */ - public function getExpressionTypes() - { - return array( - self::TYPE_LIKE => $this->lng->txt("like_like"), - self::TYPE_DISLIKE => $this->lng->txt("like_dislike"), - self::TYPE_LOVE => $this->lng->txt("like_love"), - self::TYPE_LAUGH => $this->lng->txt("like_laugh"), - self::TYPE_ASTOUNDED => $this->lng->txt("like_astounded"), - self::TYPE_SAD => $this->lng->txt("like_sad"), - self::TYPE_ANGRY => $this->lng->txt("like_angry") - ); - } - - - /** - * Add expression for a user and object - * - * @param int $a_user_id user id (who is liking) - * @param int $a_like_type one of self::TYPE_LIKE to self::TYPE_ANGRY - * @param int $a_obj_id object id (must be an repository object id) - * @param string $a_obj_type object type (redundant, for performance reasons) - * @param int $a_sub_obj_id subobject id (as defined by the module being responsible for main object type) - * @param string $a_sub_obj_type subobject type (as defined by the module being responsible for main object type) - * @param int $a_news_id news is (optional news id, if like action is dedicated to a news for the object/subobject) - */ - public function addExpression($a_user_id, $a_like_type, $a_obj_id, $a_obj_type, $a_sub_obj_id = 0, $a_sub_obj_type = "", - $a_news_id = 0) - { - $ilDB = $this->db; - - if ($a_user_id == ANONYMOUS_USER_ID) - { - return; - } - - $this->data[$a_obj_id][$a_sub_obj_id][$a_sub_obj_type][$a_news_id][$a_like_type][$a_user_id] = 1; - - if ($a_sub_obj_type == "") - { - $a_sub_obj_type = "-"; - } - - $ilDB->replace("like_data", - array( - "user_id" => array("integer", (int) $a_user_id), - "obj_id" => array("integer", (int) $a_obj_id), - "obj_type" => array("text", $a_obj_type), - "sub_obj_id" => array("integer", (int) $a_sub_obj_id), - "sub_obj_type" => array("text", $a_sub_obj_type), - "news_id" => array("integer", (int) $a_news_id), - "like_type" => array("integer", (int) $a_like_type) - ), - array( - "exp_ts" => array("timestamp", ilUtil::now()) - )); - } - - /** - * Remove expression for a user and object - * - * @param int $a_user_id user id (who is liking) - * @param int $a_like_type one of self::TYPE_LIKE to self::TYPE_ANGRY - * @param int $a_obj_id object id (must be an repository object id) - * @param string $a_obj_type object type (redundant, for performance reasons) - * @param int $a_sub_obj_id subobject id (as defined by the module being responsible for main object type) - * @param string $a_sub_obj_type subobject type (as defined by the module being responsible for main object type) - * @param int $a_news_id news is (optional news id, if like action is dedicated to a news for the object/subobject) - */ - public function removeExpression($a_user_id, $a_like_type, $a_obj_id, $a_obj_type, $a_sub_obj_id = 0, $a_sub_obj_type = "", - $a_news_id = 0) - { - $ilDB = $this->db; - - if ($a_user_id == ANONYMOUS_USER_ID) - { - return; - } - - if (isset($this->data[$a_obj_id][$a_sub_obj_id][$a_sub_obj_type][$a_news_id][$a_like_type][$a_user_id])) - { - unset($this->data[$a_obj_id][$a_sub_obj_id][$a_sub_obj_type][$a_news_id][$a_like_type][$a_user_id]); - } - - if ($a_sub_obj_type == "") - { - $a_sub_obj_type = "-"; - } - - $ilDB->manipulate("DELETE FROM like_data WHERE ". - " user_id = ".$ilDB->quote($a_user_id, "integer"). - " AND obj_id = ".$ilDB->quote($a_obj_id, "integer"). - " AND obj_type = ".$ilDB->quote($a_obj_type, "text"). - " AND sub_obj_id = ".$ilDB->quote($a_sub_obj_id, "integer"). - " AND sub_obj_type = ".$ilDB->quote($a_sub_obj_type, "text"). - " AND news_id = ".$ilDB->quote($a_news_id, "integer"). - " AND like_type = ".$ilDB->quote($a_like_type, "integer") - ); - } - - /** - * Load data (for objects) - * - * @param int[] load data for objects - */ - protected function loadDataForObjects($a_obj_ids = array()) - { - $ilDB = $this->db; - - foreach ($a_obj_ids as $id) - { - $this->data[$id] = array(); - } - - $set = $ilDB->query("SELECT * FROM like_data ". - " WHERE ".$ilDB->in("obj_id", $a_obj_ids, false, "integer"). - " ORDER by exp_ts DESC"); - while ($rec = $ilDB->fetchAssoc($set)) - { - $subtype = $rec["sub_obj_type"] == "-" - ? "" - : $rec["sub_obj_type"]; - $this->data[$rec["obj_id"]][$rec["sub_obj_id"]][$subtype][$rec["news_id"]][$rec["like_type"]][$rec["user_id"]] = - $rec["exp_ts"]; - } - } - - /** - * Get expression counts for obj/subobj/news - * - * @param int $obj_id - * @param string $obj_type - * @param int $sub_obj_id - * @param string $sub_obj_type - * @param int $news_id - * @return int[] $news_id - * @throws ilLikeDataException - */ - public function getExpressionCounts($obj_id, $obj_type, $sub_obj_id, $sub_obj_type, $news_id) - { - if (!is_array($this->data[$obj_id])) - { - include_once("./Services/Like/exceptions/class.ilLikeDataException.php"); - throw new ilLikeDataException("No data loaded for object $obj_id."); - } - - if ($sub_obj_type == "-") - { - $sub_obj_type = ""; - } - - $cnt = array(); - foreach ($this->getExpressionTypes() as $k => $txt) - { - $cnt[$k] = 0; - if (is_array($this->data[$obj_id][$sub_obj_id][$sub_obj_type][$news_id][$k])) - { - $cnt[$k] = count($this->data[$obj_id][$sub_obj_id][$sub_obj_type][$news_id][$k]); - } - } - return $cnt; - } - - /** - * Is expression set for a user and object? - * - * @param int $a_user_id user id (who is liking) - * @param int $a_like_type one of self::TYPE_LIKE to self::TYPE_ANGRY - * @param int $a_obj_id object id (must be an repository object id) - * @param string $a_obj_type object type (redundant, for performance reasons) - * @param int $a_sub_obj_id subobject id (as defined by the module being responsible for main object type) - * @param string $a_sub_obj_type subobject type (as defined by the module being responsible for main object type) - * @param int $a_news_id news is (optional news id, if like action is dedicated to a news for the object/subobject) - * @return bool - */ - public function isExpressionSet($a_user_id, $a_like_type, $a_obj_id, $a_obj_type, $a_sub_obj_id = 0, $a_sub_obj_type = "", - $a_news_id = 0) - { - if (isset($this->data[$a_obj_id][$a_sub_obj_id][$a_sub_obj_type][$a_news_id][$a_like_type][$a_user_id])) - { - return true; - } - return false; - } - - /** - * Get expression entries for obj/subobj/news - * - * @param int $obj_id - * @param string $obj_type - * @param int $sub_obj_id - * @param string $sub_obj_type - * @param int $news_id - * @return int[] $news_id - * @throws ilLikeDataException - */ - public function getExpressionEntries($obj_id, $obj_type, $sub_obj_id, $sub_obj_type, $news_id) - { - if (!is_array($this->data[$obj_id])) - { - include_once("./Services/Like/exceptions/class.ilLikeDataException.php"); - throw new ilLikeDataException("No data loaded for object $obj_id."); - } - - if ($sub_obj_type == "-") - { - $sub_obj_type = ""; - } - - $exp = array(); - foreach ($this->getExpressionTypes() as $k => $txt) - { - if (is_array($this->data[$obj_id][$sub_obj_id][$sub_obj_type][$news_id][$k])) - { - foreach ($this->data[$obj_id][$sub_obj_id][$sub_obj_type][$news_id][$k] as $user => $ts) - { - $exp[] = array( - "expression" => $k, - "user_id" => $user, - "timestamp" => $ts - ); - } - } - } - - $exp = ilUtil::sortArray($exp, "timestamp", "desc"); - return $exp; - } - - /** - * Get expression entries for obj/subobj/news - * - * @param int $obj_id - * @param int $since_ts timestamp (show only data since...) - * @return array - * @throws ilLikeDataException - */ - public function getExpressionEntriesForObject($obj_id, $since_ts = null) - { - if (!is_array($this->data[$obj_id])) - { - include_once("./Services/Like/exceptions/class.ilLikeDataException.php"); - throw new ilLikeDataException("No data loaded for object $obj_id."); - } - $exp = array(); - foreach ($this->data[$obj_id] as $sub_obj_id => $si) - { - foreach ($si as $sub_obj_type => $so) - { - foreach ($so as $news_id => $ni) - { - foreach ($ni as $exp_type => $entry) - { - foreach ($entry as $user => $ts) - { - if ($since_ts == null || $ts > $since_ts) - { - $exp[] = array( - "sub_obj_id" => $sub_obj_id, - "sub_obj_type" => $sub_obj_type, - "news_id" => $news_id, - "expression" => $exp_type, - "user_id" => $user, - "timestamp" => $ts - ); - } - } - } - } - } - } - - $exp = ilUtil::sortArray($exp, "timestamp", "desc"); - return $exp; - } - - + const TYPE_LIKE = 0; + const TYPE_DISLIKE = 1; + const TYPE_LOVE = 2; + const TYPE_LAUGH = 3; + const TYPE_ASTOUNDED = 4; + const TYPE_SAD = 5; + const TYPE_ANGRY = 6; + + /** + * + * @var array + */ + protected $data = array(); + + /** + * @var ilDB + */ + protected $db; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * Constructor + * @param ilDB $db + */ + public function __construct(array $a_obj_ids = array(), ilDB $db = null, $lng = null) + { + global $DIC; + + $this->db = ($db == null) + ? $DIC->database() + : $db; + + $this->lng = ($lng == null) + ? $DIC->language() + : $lng; + $this->loadDataForObjects($a_obj_ids); + $this->lng->loadLanguageModule("like"); + } + + /** + * Get types + * + * @param + * @return array + */ + public function getExpressionTypes() + { + return array( + self::TYPE_LIKE => $this->lng->txt("like_like"), + self::TYPE_DISLIKE => $this->lng->txt("like_dislike"), + self::TYPE_LOVE => $this->lng->txt("like_love"), + self::TYPE_LAUGH => $this->lng->txt("like_laugh"), + self::TYPE_ASTOUNDED => $this->lng->txt("like_astounded"), + self::TYPE_SAD => $this->lng->txt("like_sad"), + self::TYPE_ANGRY => $this->lng->txt("like_angry") + ); + } + + + /** + * Add expression for a user and object + * + * @param int $a_user_id user id (who is liking) + * @param int $a_like_type one of self::TYPE_LIKE to self::TYPE_ANGRY + * @param int $a_obj_id object id (must be an repository object id) + * @param string $a_obj_type object type (redundant, for performance reasons) + * @param int $a_sub_obj_id subobject id (as defined by the module being responsible for main object type) + * @param string $a_sub_obj_type subobject type (as defined by the module being responsible for main object type) + * @param int $a_news_id news is (optional news id, if like action is dedicated to a news for the object/subobject) + */ + public function addExpression( + $a_user_id, + $a_like_type, + $a_obj_id, + $a_obj_type, + $a_sub_obj_id = 0, + $a_sub_obj_type = "", + $a_news_id = 0 + ) { + $ilDB = $this->db; + + if ($a_user_id == ANONYMOUS_USER_ID) { + return; + } + + $this->data[$a_obj_id][$a_sub_obj_id][$a_sub_obj_type][$a_news_id][$a_like_type][$a_user_id] = 1; + + if ($a_sub_obj_type == "") { + $a_sub_obj_type = "-"; + } + + $ilDB->replace( + "like_data", + array( + "user_id" => array("integer", (int) $a_user_id), + "obj_id" => array("integer", (int) $a_obj_id), + "obj_type" => array("text", $a_obj_type), + "sub_obj_id" => array("integer", (int) $a_sub_obj_id), + "sub_obj_type" => array("text", $a_sub_obj_type), + "news_id" => array("integer", (int) $a_news_id), + "like_type" => array("integer", (int) $a_like_type) + ), + array( + "exp_ts" => array("timestamp", ilUtil::now()) + ) + ); + } + + /** + * Remove expression for a user and object + * + * @param int $a_user_id user id (who is liking) + * @param int $a_like_type one of self::TYPE_LIKE to self::TYPE_ANGRY + * @param int $a_obj_id object id (must be an repository object id) + * @param string $a_obj_type object type (redundant, for performance reasons) + * @param int $a_sub_obj_id subobject id (as defined by the module being responsible for main object type) + * @param string $a_sub_obj_type subobject type (as defined by the module being responsible for main object type) + * @param int $a_news_id news is (optional news id, if like action is dedicated to a news for the object/subobject) + */ + public function removeExpression( + $a_user_id, + $a_like_type, + $a_obj_id, + $a_obj_type, + $a_sub_obj_id = 0, + $a_sub_obj_type = "", + $a_news_id = 0 + ) { + $ilDB = $this->db; + + if ($a_user_id == ANONYMOUS_USER_ID) { + return; + } + + if (isset($this->data[$a_obj_id][$a_sub_obj_id][$a_sub_obj_type][$a_news_id][$a_like_type][$a_user_id])) { + unset($this->data[$a_obj_id][$a_sub_obj_id][$a_sub_obj_type][$a_news_id][$a_like_type][$a_user_id]); + } + + if ($a_sub_obj_type == "") { + $a_sub_obj_type = "-"; + } + + $ilDB->manipulate( + "DELETE FROM like_data WHERE " . + " user_id = " . $ilDB->quote($a_user_id, "integer") . + " AND obj_id = " . $ilDB->quote($a_obj_id, "integer") . + " AND obj_type = " . $ilDB->quote($a_obj_type, "text") . + " AND sub_obj_id = " . $ilDB->quote($a_sub_obj_id, "integer") . + " AND sub_obj_type = " . $ilDB->quote($a_sub_obj_type, "text") . + " AND news_id = " . $ilDB->quote($a_news_id, "integer") . + " AND like_type = " . $ilDB->quote($a_like_type, "integer") + ); + } + + /** + * Load data (for objects) + * + * @param int[] load data for objects + */ + protected function loadDataForObjects($a_obj_ids = array()) + { + $ilDB = $this->db; + + foreach ($a_obj_ids as $id) { + $this->data[$id] = array(); + } + + $set = $ilDB->query("SELECT * FROM like_data " . + " WHERE " . $ilDB->in("obj_id", $a_obj_ids, false, "integer") . + " ORDER by exp_ts DESC"); + while ($rec = $ilDB->fetchAssoc($set)) { + $subtype = $rec["sub_obj_type"] == "-" + ? "" + : $rec["sub_obj_type"]; + $this->data[$rec["obj_id"]][$rec["sub_obj_id"]][$subtype][$rec["news_id"]][$rec["like_type"]][$rec["user_id"]] = + $rec["exp_ts"]; + } + } + + /** + * Get expression counts for obj/subobj/news + * + * @param int $obj_id + * @param string $obj_type + * @param int $sub_obj_id + * @param string $sub_obj_type + * @param int $news_id + * @return int[] $news_id + * @throws ilLikeDataException + */ + public function getExpressionCounts($obj_id, $obj_type, $sub_obj_id, $sub_obj_type, $news_id) + { + if (!is_array($this->data[$obj_id])) { + include_once("./Services/Like/exceptions/class.ilLikeDataException.php"); + throw new ilLikeDataException("No data loaded for object $obj_id."); + } + + if ($sub_obj_type == "-") { + $sub_obj_type = ""; + } + + $cnt = array(); + foreach ($this->getExpressionTypes() as $k => $txt) { + $cnt[$k] = 0; + if (is_array($this->data[$obj_id][$sub_obj_id][$sub_obj_type][$news_id][$k])) { + $cnt[$k] = count($this->data[$obj_id][$sub_obj_id][$sub_obj_type][$news_id][$k]); + } + } + return $cnt; + } + + /** + * Is expression set for a user and object? + * + * @param int $a_user_id user id (who is liking) + * @param int $a_like_type one of self::TYPE_LIKE to self::TYPE_ANGRY + * @param int $a_obj_id object id (must be an repository object id) + * @param string $a_obj_type object type (redundant, for performance reasons) + * @param int $a_sub_obj_id subobject id (as defined by the module being responsible for main object type) + * @param string $a_sub_obj_type subobject type (as defined by the module being responsible for main object type) + * @param int $a_news_id news is (optional news id, if like action is dedicated to a news for the object/subobject) + * @return bool + */ + public function isExpressionSet( + $a_user_id, + $a_like_type, + $a_obj_id, + $a_obj_type, + $a_sub_obj_id = 0, + $a_sub_obj_type = "", + $a_news_id = 0 + ) { + if (isset($this->data[$a_obj_id][$a_sub_obj_id][$a_sub_obj_type][$a_news_id][$a_like_type][$a_user_id])) { + return true; + } + return false; + } + + /** + * Get expression entries for obj/subobj/news + * + * @param int $obj_id + * @param string $obj_type + * @param int $sub_obj_id + * @param string $sub_obj_type + * @param int $news_id + * @return int[] $news_id + * @throws ilLikeDataException + */ + public function getExpressionEntries($obj_id, $obj_type, $sub_obj_id, $sub_obj_type, $news_id) + { + if (!is_array($this->data[$obj_id])) { + include_once("./Services/Like/exceptions/class.ilLikeDataException.php"); + throw new ilLikeDataException("No data loaded for object $obj_id."); + } + + if ($sub_obj_type == "-") { + $sub_obj_type = ""; + } + + $exp = array(); + foreach ($this->getExpressionTypes() as $k => $txt) { + if (is_array($this->data[$obj_id][$sub_obj_id][$sub_obj_type][$news_id][$k])) { + foreach ($this->data[$obj_id][$sub_obj_id][$sub_obj_type][$news_id][$k] as $user => $ts) { + $exp[] = array( + "expression" => $k, + "user_id" => $user, + "timestamp" => $ts + ); + } + } + } + + $exp = ilUtil::sortArray($exp, "timestamp", "desc"); + return $exp; + } + + /** + * Get expression entries for obj/subobj/news + * + * @param int $obj_id + * @param int $since_ts timestamp (show only data since...) + * @return array + * @throws ilLikeDataException + */ + public function getExpressionEntriesForObject($obj_id, $since_ts = null) + { + if (!is_array($this->data[$obj_id])) { + include_once("./Services/Like/exceptions/class.ilLikeDataException.php"); + throw new ilLikeDataException("No data loaded for object $obj_id."); + } + $exp = array(); + foreach ($this->data[$obj_id] as $sub_obj_id => $si) { + foreach ($si as $sub_obj_type => $so) { + foreach ($so as $news_id => $ni) { + foreach ($ni as $exp_type => $entry) { + foreach ($entry as $user => $ts) { + if ($since_ts == null || $ts > $since_ts) { + $exp[] = array( + "sub_obj_id" => $sub_obj_id, + "sub_obj_type" => $sub_obj_type, + "news_id" => $news_id, + "expression" => $exp_type, + "user_id" => $user, + "timestamp" => $ts + ); + } + } + } + } + } + } + + $exp = ilUtil::sortArray($exp, "timestamp", "desc"); + return $exp; + } } - -?> \ No newline at end of file diff --git a/Services/Like/classes/class.ilLikeFactoryGUI.php b/Services/Like/classes/class.ilLikeFactoryGUI.php index 89a18f494a825185a50a6a8eb3e1f15c96f976d6..3a6303d44bfd99214623f86740ad1b12eefcf64f 100644 --- a/Services/Like/classes/class.ilLikeFactoryGUI.php +++ b/Services/Like/classes/class.ilLikeFactoryGUI.php @@ -10,30 +10,27 @@ */ class ilLikeFactoryGUI { - /** - * - * - * @param - */ - public function __construct() - { - - } - - /** - * Get widget - * - * @param array $a_obj_ids - * @return ilLikeGUI - */ - public function widget(array $a_obj_ids) - { - include_once("./Services/Like/classes/class.ilLikeGUI.php"); - include_once("./Services/Like/classes/class.ilLikeData.php"); - $data = new ilLikeData($a_obj_ids); - $like_gui = new ilLikeGUI($data); - return $like_gui; - } - + /** + * + * + * @param + */ + public function __construct() + { + } + /** + * Get widget + * + * @param array $a_obj_ids + * @return ilLikeGUI + */ + public function widget(array $a_obj_ids) + { + include_once("./Services/Like/classes/class.ilLikeGUI.php"); + include_once("./Services/Like/classes/class.ilLikeData.php"); + $data = new ilLikeData($a_obj_ids); + $like_gui = new ilLikeGUI($data); + return $like_gui; + } } diff --git a/Services/Like/classes/class.ilLikeGUI.php b/Services/Like/classes/class.ilLikeGUI.php index 436fec4bf1da4747a3c3ffac195000382f3f74d3..0ab180d61f8eafc1e705e435de979bcb135f9721 100644 --- a/Services/Like/classes/class.ilLikeGUI.php +++ b/Services/Like/classes/class.ilLikeGUI.php @@ -12,399 +12,413 @@ */ class ilLikeGUI { - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var int - */ - protected $obj_id; - - /** - * @var string - */ - protected $obj_type; - - /** - * @var int - */ - protected $sub_obj_id; - - /** - * @var string - */ - protected $sub_obj_type; - - /** - * @var int - */ - protected $news_id; - - /** - * @var string dom id - */ - protected $dom_id; - - /** - * @var ilLanguage - */ - protected $language; - - /** - * ilLikeGUI constructor. - * @param ilLikeData $data - * @param ilTemplate|null $main_tpl - */ - function __construct(\ilLikeData $data, \ilTemplate $main_tpl = null) - { - global $DIC; - - $this->main_tpl = ($main_tpl == null) - ? $DIC->ui()->mainTemplate() - : $main_tpl; - - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $this->user = $DIC->user(); - $this->ui = $DIC->ui(); - $this->lng = $DIC->language(); - - $this->data = $data; - - $this->lng->loadLanguageModule("like"); - - $this->initJavascript(); - } - - /** - * Init javascript - */ - protected function initJavascript() - { - $this->main_tpl->addJavaScript("./Services/Like/js/Like.js"); - } - - - /** - * Set Object. - * - * @param int $a_obj_id Object ID - * @param string $a_obj_type Object Type - * @param int $a_sub_obj_id Subobject ID - * @param string $a_sub_obj_type Subobject Type - */ - function setObject($a_obj_id, $a_obj_type, $a_sub_obj_id = 0, $a_sub_obj_type = "", $a_news_id = 0) - { - $this->obj_id = $a_obj_id; - $this->obj_type = $a_obj_type; - $this->sub_obj_id = $a_sub_obj_id; - $this->sub_obj_type = $a_sub_obj_type; - $this->news_id = $a_news_id; - $this->dom_id = "like_".$this->obj_id."_".$this->obj_type."_".$this->sub_obj_id."_". - $this->sub_obj_type."_".$this->news_id; - } - - /** - * Execute command - * @return string - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd("getHTML"); - - switch($next_class) - { - default: - if (in_array($cmd, array("getHTML", "renderEmoticons", "renderModal", "saveExpression"))) - { - return $this->$cmd(); - } - break; - } - return ""; - } - - /** - * Get HTML - * - * @param $a_obj_id - * @param $a_obj_type - * @param int $a_sub_obj_id - * @param string $a_sub_obj_type - * @param int $a_news_id - * @return string - * @throws ilLikeDataException - */ - function getHTML() - { - $f = $this->ui->factory(); - $r = $this->ui->renderer(); - $ctrl = $this->ctrl; - $lng = $this->lng; - - $tpl = new ilTemplate("tpl.like.html", true, true, "Services/Like"); - - // modal - $modal_asyn_url = $ctrl->getLinkTarget($this, "renderModal", "", true, false); - $modal = $f->modal()->roundtrip('', $f->legacy("")) - ->withAsyncRenderUrl($modal_asyn_url); - - $modal_show_sig_id = $modal->getShowSignal()->getId(); - $this->ctrl->setParameter($this, "modal_show_sig_id", $modal_show_sig_id); - $emo_counters = $this->renderEmoCounters($modal->getShowSignal()); - $tpl->setVariable("EMO_COUNTERS", $emo_counters.$r->render($modal)); - - - - // emoticon popover - $popover = $f->popover()->standard($f->legacy(''))->withTitle(''); - $ctrl->setParameter($this, "repl_sig", $popover->getReplaceContentSignal()->getId()); - $asyn_url = $ctrl->getLinkTarget($this, "renderEmoticons", "", true, false); - $popover = $popover->withAsyncContentUrl($asyn_url); - $button = $f->button()->shy($lng->txt("like"), '#') - ->withOnClick($popover->getShowSignal()); - - $tpl->setVariable("LIKE", $r->render([$popover, $button])); - - return $tpl->get(); - } - - /** - * Render emo counters - * - * @param $modal_signal - * @return string - * @throws ilLikeDataException - */ - protected function renderEmoCounters($modal_signal = null) - { - $ilCtrl = $this->ctrl; - - $tpl = new ilTemplate("tpl.emo_counters.html", true, true, "Services/Like"); - $f = $this->ui->factory(); - $r = $this->ui->renderer(); - - $cnts = $this->data->getExpressionCounts($this->obj_id, $this->obj_type, - $this->sub_obj_id, $this->sub_obj_type, $this->news_id); - $comps = array(); - foreach ($this->data->getExpressionTypes() as $k => $txt) - { - if ($cnts[$k] > 0) - { - $glyph = $this->getGlyphForConst($k); - if ($modal_signal !== null) - { - $glyph = $glyph->withOnClick($modal_signal); - } - $comps[] = $glyph->withCounter($f->counter()->status($cnts[$k])); - } - } - - if ($ilCtrl->isAsynch()) - { - $tpl->setVariable("MODAL_TRIGGER", $r->renderAsync($comps)); - } - else - { - $tpl->setVariable("MODAL_TRIGGER", $r->render($comps)); - } - if ($modal_signal !== null) - { - $tpl->setVariable("ID", $this->dom_id); - } - - if (count($comps) > 0 && $modal_signal !== null) - { - $tpl->setVariable("SEP", $r->render($f->divider()->vertical())); - } - - return $tpl->get(); - } - - - /** - * Get glyph for const - * - * @param int $a_const - * @return \ILIAS\UI\Component\Glyph\Glyph|null - */ - protected function getGlyphForConst($a_const) - { - $f = $this->ui->factory(); - $like = null; - switch ($a_const) - { - case ilLikeData::TYPE_LIKE: $like = $f->glyph()->like(); break; - case ilLikeData::TYPE_DISLIKE: $like = $f->glyph()->dislike(); break; - case ilLikeData::TYPE_LOVE: $like = $f->glyph()->love(); break; - case ilLikeData::TYPE_LAUGH: $like = $f->glyph()->laugh(); break; - case ilLikeData::TYPE_ASTOUNDED: $like = $f->glyph()->astounded(); break; - case ilLikeData::TYPE_SAD: $like = $f->glyph()->sad(); break; - case ilLikeData::TYPE_ANGRY: $like = $f->glyph()->angry(); break; - } - return $like; - } - - - - /** - * Render emoticons - */ - function renderEmoticons() - { - $ilCtrl = $this->ctrl; - $r = $this->ui->renderer(); - - $ilCtrl->saveParameter($this, "modal_show_sig_id"); - - $tpl = new ilTemplate("tpl.emoticons.html", true, true, "Services/Like"); - $tpl->setVariable("ID", $this->dom_id); - - $url = $ilCtrl->getLinkTarget($this, "", "", true); - foreach ($this->data->getExpressionTypes() as $k => $txt) - { - $g = $this->getGlyphForConst($k); - - if ($this->data->isExpressionSet($this->user->getId(), $k, $this->obj_id, $this->obj_type, - $this->sub_obj_id, $this->sub_obj_type, $this->news_id)) - { - $g = $g->withHighlight(); - } - - $g = $g->withAdditionalOnLoadCode(function($id) use ($k, $url) { - return - "$('#".$id."').click(function() { il.Like.toggle('".$url."','".$id."','".$this->dom_id."',".$k.");});"; - }); - $glyphs[] = $g; - } - - $tpl->setVariable("GLYPHS", $r->renderAsync($glyphs)); - - echo $tpl->get(); - exit; - } - - /** - * Save expresseion - * - * @throws ilLikeDataException - */ - protected function saveExpression() - { - $exp_key = (int) $_GET["exp"]; - $exp_val = (int) $_GET["val"]; - $modal_show_sig_id = ilUtil::stripSlashes($_GET["modal_show_sig_id"]); - $show_signal = new \ILIAS\UI\Implementation\Component\Signal($modal_show_sig_id); - - if ($exp_val) { - $this->data->addExpression($this->user->getId(), $exp_key, $this->obj_id, $this->obj_type, - $this->sub_obj_id, $this->sub_obj_type, $this->news_id); - } else { - $this->data->removeExpression($this->user->getId(), $exp_key, $this->obj_id, $this->obj_type, - $this->sub_obj_id, $this->sub_obj_type, $this->news_id); - } - echo $this->renderEmoCounters($show_signal); - exit; - } - - - /** - * Render modal - * @throws ilLikeDataException - */ - function renderModal() - { - $user = $this->user; - - $f = $this->ui->factory(); - $r = $this->ui->renderer(); - - - $list_items = []; - foreach ($this->data->getExpressionEntries($this->obj_id, $this->obj_type, - $this->sub_obj_id, $this->sub_obj_type, $this->news_id) as $exp) - { - $name = ilUserUtil::getNamePresentation($exp["user_id"]); - - $image = $f->image()->responsive( - ilObjUser::_getPersonalPicturePath($exp["user_id"]), - $name); - - $g = $this->getGlyphForConst($exp["expression"]); - - $list_items[] = $f->item()->standard($name) - ->withDescription($r->render($g)." ". - ilDatePresentation::formatDate(new ilDateTime($exp["timestamp"], IL_CAL_DATETIME))) - ->withLeadImage($image); - } - - $std_list = $f->panel()->listing()->standard("", array( - $f->item()->group("", $list_items) - )); - - $header = $f->legacy($this->renderEmoCounters()); - //$header = $f->legacy("---"); - - $modal = $f->modal()->roundtrip('', [$header, $std_list]); - echo $r->render($modal); - exit; - } - - - /** - * Get unicode for const - * - * @param int $a_const - * @return string - */ - /* - static public function getCharacter($a_const) - { - $tpl = new ilTemplate("tpl.unicodes.html", true, true, "Services/Like"); - $tpl->touchBlock("u".$a_const); - return $tpl->get(); - }*/ - - /** - * Get expresseion text for const - * - * @param int $a_const - * @return string - */ - static public function getExpressionText($a_const) - { - global $DIC; - - $lng = $DIC->language(); - - switch ($a_const) - { - case ilLikeData::TYPE_LIKE: return $lng->txt("like"); break; - case ilLikeData::TYPE_DISLIKE: return $lng->txt("dislike"); break; - case ilLikeData::TYPE_LOVE: return $lng->txt("love"); break; - case ilLikeData::TYPE_LAUGH: return $lng->txt("laugh"); break; - case ilLikeData::TYPE_ASTOUNDED: return $lng->txt("astounded"); break; - case ilLikeData::TYPE_SAD: return $lng->txt("sad"); break; - case ilLikeData::TYPE_ANGRY: return $lng->txt("angry"); break; - } - return ""; - } - + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var int + */ + protected $obj_id; + + /** + * @var string + */ + protected $obj_type; + + /** + * @var int + */ + protected $sub_obj_id; + + /** + * @var string + */ + protected $sub_obj_type; + + /** + * @var int + */ + protected $news_id; + + /** + * @var string dom id + */ + protected $dom_id; + + /** + * @var ilLanguage + */ + protected $language; + + /** + * ilLikeGUI constructor. + * @param ilLikeData $data + * @param ilTemplate|null $main_tpl + */ + public function __construct(\ilLikeData $data, \ilTemplate $main_tpl = null) + { + global $DIC; + + $this->main_tpl = ($main_tpl == null) + ? $DIC->ui()->mainTemplate() + : $main_tpl; + + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->user = $DIC->user(); + $this->ui = $DIC->ui(); + $this->lng = $DIC->language(); + + $this->data = $data; + + $this->lng->loadLanguageModule("like"); + + $this->initJavascript(); + } + + /** + * Init javascript + */ + protected function initJavascript() + { + $this->main_tpl->addJavaScript("./Services/Like/js/Like.js"); + } + + + /** + * Set Object. + * + * @param int $a_obj_id Object ID + * @param string $a_obj_type Object Type + * @param int $a_sub_obj_id Subobject ID + * @param string $a_sub_obj_type Subobject Type + */ + public function setObject($a_obj_id, $a_obj_type, $a_sub_obj_id = 0, $a_sub_obj_type = "", $a_news_id = 0) + { + $this->obj_id = $a_obj_id; + $this->obj_type = $a_obj_type; + $this->sub_obj_id = $a_sub_obj_id; + $this->sub_obj_type = $a_sub_obj_type; + $this->news_id = $a_news_id; + $this->dom_id = "like_" . $this->obj_id . "_" . $this->obj_type . "_" . $this->sub_obj_id . "_" . + $this->sub_obj_type . "_" . $this->news_id; + } + + /** + * Execute command + * @return string + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd("getHTML"); + + switch ($next_class) { + default: + if (in_array($cmd, array("getHTML", "renderEmoticons", "renderModal", "saveExpression"))) { + return $this->$cmd(); + } + break; + } + return ""; + } + + /** + * Get HTML + * + * @param $a_obj_id + * @param $a_obj_type + * @param int $a_sub_obj_id + * @param string $a_sub_obj_type + * @param int $a_news_id + * @return string + * @throws ilLikeDataException + */ + public function getHTML() + { + $f = $this->ui->factory(); + $r = $this->ui->renderer(); + $ctrl = $this->ctrl; + $lng = $this->lng; + + $tpl = new ilTemplate("tpl.like.html", true, true, "Services/Like"); + + // modal + $modal_asyn_url = $ctrl->getLinkTarget($this, "renderModal", "", true, false); + $modal = $f->modal()->roundtrip('', $f->legacy("")) + ->withAsyncRenderUrl($modal_asyn_url); + + $modal_show_sig_id = $modal->getShowSignal()->getId(); + $this->ctrl->setParameter($this, "modal_show_sig_id", $modal_show_sig_id); + $emo_counters = $this->renderEmoCounters($modal->getShowSignal()); + $tpl->setVariable("EMO_COUNTERS", $emo_counters . $r->render($modal)); + + + + // emoticon popover + $popover = $f->popover()->standard($f->legacy(''))->withTitle(''); + $ctrl->setParameter($this, "repl_sig", $popover->getReplaceContentSignal()->getId()); + $asyn_url = $ctrl->getLinkTarget($this, "renderEmoticons", "", true, false); + $popover = $popover->withAsyncContentUrl($asyn_url); + $button = $f->button()->shy($lng->txt("like"), '#') + ->withOnClick($popover->getShowSignal()); + + $tpl->setVariable("LIKE", $r->render([$popover, $button])); + + return $tpl->get(); + } + + /** + * Render emo counters + * + * @param $modal_signal + * @return string + * @throws ilLikeDataException + */ + protected function renderEmoCounters($modal_signal = null) + { + $ilCtrl = $this->ctrl; + + $tpl = new ilTemplate("tpl.emo_counters.html", true, true, "Services/Like"); + $f = $this->ui->factory(); + $r = $this->ui->renderer(); + + $cnts = $this->data->getExpressionCounts( + $this->obj_id, + $this->obj_type, + $this->sub_obj_id, + $this->sub_obj_type, + $this->news_id + ); + $comps = array(); + foreach ($this->data->getExpressionTypes() as $k => $txt) { + if ($cnts[$k] > 0) { + $glyph = $this->getGlyphForConst($k); + if ($modal_signal !== null) { + $glyph = $glyph->withOnClick($modal_signal); + } + $comps[] = $glyph->withCounter($f->counter()->status($cnts[$k])); + } + } + + if ($ilCtrl->isAsynch()) { + $tpl->setVariable("MODAL_TRIGGER", $r->renderAsync($comps)); + } else { + $tpl->setVariable("MODAL_TRIGGER", $r->render($comps)); + } + if ($modal_signal !== null) { + $tpl->setVariable("ID", $this->dom_id); + } + + if (count($comps) > 0 && $modal_signal !== null) { + $tpl->setVariable("SEP", $r->render($f->divider()->vertical())); + } + + return $tpl->get(); + } + + + /** + * Get glyph for const + * + * @param int $a_const + * @return \ILIAS\UI\Component\Glyph\Glyph|null + */ + protected function getGlyphForConst($a_const) + { + $f = $this->ui->factory(); + $like = null; + switch ($a_const) { + case ilLikeData::TYPE_LIKE: $like = $f->glyph()->like(); break; + case ilLikeData::TYPE_DISLIKE: $like = $f->glyph()->dislike(); break; + case ilLikeData::TYPE_LOVE: $like = $f->glyph()->love(); break; + case ilLikeData::TYPE_LAUGH: $like = $f->glyph()->laugh(); break; + case ilLikeData::TYPE_ASTOUNDED: $like = $f->glyph()->astounded(); break; + case ilLikeData::TYPE_SAD: $like = $f->glyph()->sad(); break; + case ilLikeData::TYPE_ANGRY: $like = $f->glyph()->angry(); break; + } + return $like; + } + + + + /** + * Render emoticons + */ + public function renderEmoticons() + { + $ilCtrl = $this->ctrl; + $r = $this->ui->renderer(); + + $ilCtrl->saveParameter($this, "modal_show_sig_id"); + + $tpl = new ilTemplate("tpl.emoticons.html", true, true, "Services/Like"); + $tpl->setVariable("ID", $this->dom_id); + + $url = $ilCtrl->getLinkTarget($this, "", "", true); + foreach ($this->data->getExpressionTypes() as $k => $txt) { + $g = $this->getGlyphForConst($k); + + if ($this->data->isExpressionSet( + $this->user->getId(), + $k, + $this->obj_id, + $this->obj_type, + $this->sub_obj_id, + $this->sub_obj_type, + $this->news_id + )) { + $g = $g->withHighlight(); + } + + $g = $g->withAdditionalOnLoadCode(function ($id) use ($k, $url) { + return + "$('#" . $id . "').click(function() { il.Like.toggle('" . $url . "','" . $id . "','" . $this->dom_id . "'," . $k . ");});"; + }); + $glyphs[] = $g; + } + + $tpl->setVariable("GLYPHS", $r->renderAsync($glyphs)); + + echo $tpl->get(); + exit; + } + + /** + * Save expresseion + * + * @throws ilLikeDataException + */ + protected function saveExpression() + { + $exp_key = (int) $_GET["exp"]; + $exp_val = (int) $_GET["val"]; + $modal_show_sig_id = ilUtil::stripSlashes($_GET["modal_show_sig_id"]); + $show_signal = new \ILIAS\UI\Implementation\Component\Signal($modal_show_sig_id); + + if ($exp_val) { + $this->data->addExpression( + $this->user->getId(), + $exp_key, + $this->obj_id, + $this->obj_type, + $this->sub_obj_id, + $this->sub_obj_type, + $this->news_id + ); + } else { + $this->data->removeExpression( + $this->user->getId(), + $exp_key, + $this->obj_id, + $this->obj_type, + $this->sub_obj_id, + $this->sub_obj_type, + $this->news_id + ); + } + echo $this->renderEmoCounters($show_signal); + exit; + } + + + /** + * Render modal + * @throws ilLikeDataException + */ + public function renderModal() + { + $user = $this->user; + + $f = $this->ui->factory(); + $r = $this->ui->renderer(); + + + $list_items = []; + foreach ($this->data->getExpressionEntries( + $this->obj_id, + $this->obj_type, + $this->sub_obj_id, + $this->sub_obj_type, + $this->news_id + ) as $exp) { + $name = ilUserUtil::getNamePresentation($exp["user_id"]); + + $image = $f->image()->responsive( + ilObjUser::_getPersonalPicturePath($exp["user_id"]), + $name + ); + + $g = $this->getGlyphForConst($exp["expression"]); + + $list_items[] = $f->item()->standard($name) + ->withDescription($r->render($g) . " " . + ilDatePresentation::formatDate(new ilDateTime($exp["timestamp"], IL_CAL_DATETIME))) + ->withLeadImage($image); + } + + $std_list = $f->panel()->listing()->standard("", array( + $f->item()->group("", $list_items) + )); + + $header = $f->legacy($this->renderEmoCounters()); + //$header = $f->legacy("---"); + + $modal = $f->modal()->roundtrip('', [$header, $std_list]); + echo $r->render($modal); + exit; + } + + + /** + * Get unicode for const + * + * @param int $a_const + * @return string + */ + /* + static public function getCharacter($a_const) + { + $tpl = new ilTemplate("tpl.unicodes.html", true, true, "Services/Like"); + $tpl->touchBlock("u".$a_const); + return $tpl->get(); + }*/ + + /** + * Get expresseion text for const + * + * @param int $a_const + * @return string + */ + public static function getExpressionText($a_const) + { + global $DIC; + + $lng = $DIC->language(); + + switch ($a_const) { + case ilLikeData::TYPE_LIKE: return $lng->txt("like"); break; + case ilLikeData::TYPE_DISLIKE: return $lng->txt("dislike"); break; + case ilLikeData::TYPE_LOVE: return $lng->txt("love"); break; + case ilLikeData::TYPE_LAUGH: return $lng->txt("laugh"); break; + case ilLikeData::TYPE_ASTOUNDED: return $lng->txt("astounded"); break; + case ilLikeData::TYPE_SAD: return $lng->txt("sad"); break; + case ilLikeData::TYPE_ANGRY: return $lng->txt("angry"); break; + } + return ""; + } } - -?> \ No newline at end of file diff --git a/Services/Like/exceptions/class.ilLikeDataException.php b/Services/Like/exceptions/class.ilLikeDataException.php index 1eb3e78373d70851e593e1eba109aa88672d2865..85ae76005aaefecbe23104cf56a2f66ba51e7d12 100644 --- a/Services/Like/exceptions/class.ilLikeDataException.php +++ b/Services/Like/exceptions/class.ilLikeDataException.php @@ -7,4 +7,4 @@ */ class ilLikeDataException extends ilException { -} \ No newline at end of file +} diff --git a/Services/Link/classes/class.ilIntLinkRepItemExplorerGUI.php b/Services/Link/classes/class.ilIntLinkRepItemExplorerGUI.php index 33c3d017fafd6ba9ae2911c0b115a8d10816917b..ea4b7ea1df5e2f46787f5ee777e5af10912a5e61 100644 --- a/Services/Link/classes/class.ilIntLinkRepItemExplorerGUI.php +++ b/Services/Link/classes/class.ilIntLinkRepItemExplorerGUI.php @@ -14,65 +14,61 @@ include_once("./Services/Repository/classes/class.ilRepositorySelectorExplorerGU */ class ilIntLinkRepItemExplorerGUI extends ilRepositorySelectorExplorerGUI { - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd) - { - parent::__construct($a_parent_obj, $a_parent_cmd, null, "", ""); - - // #14587 - ilRepositorySelectorExplorerGUI::__construct() does NOT include side blocks! - $list = $this->getTypeWhiteList(); - $list[] = "poll"; - $this->setTypeWhiteList($list); - } + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd) + { + parent::__construct($a_parent_obj, $a_parent_cmd, null, "", ""); + + // #14587 - ilRepositorySelectorExplorerGUI::__construct() does NOT include side blocks! + $list = $this->getTypeWhiteList(); + $list[] = "poll"; + $this->setTypeWhiteList($list); + } - /** - * Set "set link target" script - * - * @param $a_script - */ - function setSetLinkTargetScript($a_script) - { - $this->link_target_script = $a_script; - } + /** + * Set "set link target" script + * + * @param $a_script + */ + public function setSetLinkTargetScript($a_script) + { + $this->link_target_script = $a_script; + } - /** - * Get "set link target" script - */ - function getSetLinkTargetScript() - { - return $this->link_target_script; - } + /** + * Get "set link target" script + */ + public function getSetLinkTargetScript() + { + return $this->link_target_script; + } - function getNodeHref($a_node) - { - if ($this->getSetLinkTargetScript() == "") - { - return "#"; - } - else - { - $link = - ilUtil::appendUrlParameterString($this->getSetLinkTargetScript(), - "linktype=RepositoryItem". - "&linktarget=il__".$a_node["type"]."_".$a_node["child"]); + public function getNodeHref($a_node) + { + if ($this->getSetLinkTargetScript() == "") { + return "#"; + } else { + $link = + ilUtil::appendUrlParameterString( + $this->getSetLinkTargetScript(), + "linktype=RepositoryItem" . + "&linktarget=il__" . $a_node["type"] . "_" . $a_node["child"] + ); - return ($link); - } - } - - /** - * get onclick event handling - */ - function getNodeOnClick($a_node) - { - if ($this->getSetLinkTargetScript() == "") - { - return "return il.IntLink.addInternalLink('[iln ".$a_node['type']."="".$a_node['child'].""]','[/iln]', event);"; - } - return ""; - } + return ($link); + } + } + /** + * get onclick event handling + */ + public function getNodeOnClick($a_node) + { + if ($this->getSetLinkTargetScript() == "") { + return "return il.IntLink.addInternalLink('[iln " . $a_node['type'] . "="" . $a_node['child'] . ""]','[/iln]', event);"; + } + return ""; + } } -?> diff --git a/Services/Link/classes/class.ilInternalLink.php b/Services/Link/classes/class.ilInternalLink.php index 09289ec1897686945bda090c36068b13c14a7b30..89f77a9810a2ef21c52795a0a229752e646ac622 100755 --- a/Services/Link/classes/class.ilInternalLink.php +++ b/Services/Link/classes/class.ilInternalLink.php @@ -13,403 +13,388 @@ */ class ilInternalLink { - /** - * Delete all links of a given source - * - * @param string $a_source_type source type - * @param int $a_source_if source id - * @param int $a_lang source language - */ - static function _deleteAllLinksOfSource($a_source_type, $a_source_id, $a_lang = "-") - { - global $DIC; - - $ilDB = $DIC->database(); - - $lang_where = ""; - if ($a_lang != "") - { - $lang_where = " AND source_lang = ".$ilDB->quote($a_lang, "text"); - } - - $q = "DELETE FROM int_link WHERE source_type = ". - $ilDB->quote($a_source_type, "text")." AND source_id=". - $ilDB->quote((int) $a_source_id, "integer"). - $lang_where; - $ilDB->manipulate($q); - } - - /** - * Delete all links to a given target - * - * @param string $a_target_type target type - * @param int $a_target_id target id - * @param int $a_target_inst target installation id - */ - static function _deleteAllLinksToTarget($a_target_type, $a_target_id, $a_target_inst = 0) - { - global $DIC; - - $ilDB = $DIC->database(); - - $ilDB->manipulateF("DELETE FROM int_link WHERE target_type = %s ". - " AND target_id = %s AND target_inst = %s ", - array("text", "integer", "integer"), - array($a_target_type, (int) $a_target_id, (int) $a_target_inst)); - } - - /** - * save internal link information - * - * @param string $a_source_type source type - * @param int $a_source_if source id - * @param string $a_target_type target type - * @param int $a_target_id target id - * @param int $a_target_inst target installation id - */ - static function _saveLink($a_source_type, $a_source_id, $a_target_type, $a_target_id, $a_target_inst = 0, - $a_source_lang = "-") - { - global $DIC; - - $ilDB = $DIC->database(); - - $ilDB->replace("int_link", - array( - "source_type" => array("text", $a_source_type), - "source_id" => array("integer", (int) $a_source_id), - "source_lang" => array("text", $a_source_lang), - "target_type" => array("text", $a_target_type), - "target_id" => array("integer", (int) $a_target_id), - "target_inst" => array("integer", (int) $a_target_inst) - ), - array() - ); - } - - /** - * get all sources of a link target - * - * @param string $a_target_type target type - * @param int $a_target_id target id - * @param int $a_target_inst target installation id - * - * @return array sources (array of array("type", "id")) - */ - static function _getSourcesOfTarget($a_target_type, $a_target_id, $a_target_inst) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "SELECT * FROM int_link WHERE ". - "target_type = ".$ilDB->quote($a_target_type, "text")." AND ". - "target_id = ".$ilDB->quote((int) $a_target_id, "integer")." AND ". - "target_inst = ".$ilDB->quote((int) $a_target_inst, "integer"); - $source_set = $ilDB->query($q); - $sources = array(); - while ($source_rec = $ilDB->fetchAssoc($source_set)) - { - $sources[$source_rec["source_type"].":".$source_rec["source_id"].":".$source_rec["source_lang"]] = - array("type" => $source_rec["source_type"], "id" => $source_rec["source_id"], - "lang" => $source_rec["source_lang"]); - } - - return $sources; - } - - /** - * Get all targets of a source object (e.g., a page) - * - * @param string $a_source_type source type (e.g. "lm:pg" | "dbk:pg") - * @param int $a_source_id source id - * - * @return array targets (array of array("type", "id", "inst")) - */ - static function _getTargetsOfSource($a_source_type, $a_source_id, $a_source_lang = "-") - { - global $DIC; - - $ilDB = $DIC->database(); - - $lang_where = ""; - if ($a_source_lang != "") - { - $lang_where = " AND source_lang = ".$ilDB->quote($a_source_lang, "text"); - } - - $q = "SELECT * FROM int_link WHERE ". - "source_type = ".$ilDB->quote($a_source_type, "text")." AND ". - "source_id = ".$ilDB->quote((int) $a_source_id, "integer"). - $lang_where; - - $target_set = $ilDB->query($q); - $targets = array(); - while ($target_rec = $ilDB->fetchAssoc($target_set)) - { - $targets[$target_rec["target_type"].":".$target_rec["target_id"].":".$target_rec["target_inst"]] = - array("type" => $target_rec["target_type"], "id" => $target_rec["target_id"], - "inst" => $target_rec["target_inst"]); - } - - return $targets; - } - - /** - * Get current id for an import id - * - * @param string $a_type target type ("PageObject" | "StructureObject" | - * "GlossaryItem" | "MediaObject") - * @param string $a_target import target id (e.g. "il_2_pg_22") - * - * @return string current target id (e.g. "il__pg_244") - */ - static function _getIdForImportId($a_type, $a_target) - { - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - switch($a_type) - { - case "PageObject": - $id = ilLMObject::_getIdForImportId($a_target); - if($id > 0) - { - return "il__pg_".$id; - } - break; - - case "StructureObject": - $id = ilLMObject::_getIdForImportId($a_target); - if($id > 0) - { - return "il__st_".$id; - } - break; - - case "GlossaryItem": - include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - $id = ilGlossaryTerm::_getIdForImportId($a_target); - //echo "+".$id."+".$a_target."+"; - if($id > 0) - { - return "il__git_".$id; - } - break; - - case "WikiPage": - // no import IDs for wiki pages (yet) - //$id = ilGlossaryTerm::_getIdForImportId($a_target); - $id = 0; - if($id > 0) - { - return "il__wpage_".$id; - } - break; - - case "MediaObject": - $id = ilObjMediaObject::_getIdForImportId($a_target); - if($id > 0) - { - return "il__mob_".$id; - } - break; - - case "RepositoryItem": - - $tarr = explode("_", $a_target); - $import_id = $a_target; - - // if a ref id part is given, strip this - // since this will not be part of an import id - // see also bug #6685 - if ($tarr[4] != "") - { - $import_id = $tarr[0]."_".$tarr[1]."_".$tarr[2]."_".$tarr[3]; - } - - $id = ilObject::_getIdForImportId($import_id); - - // get ref id for object id - // (see ilPageObject::insertInstIntoIDs for the export procedure) - if($id > 0) - { - $refs = ilObject::_getAllReferences($id); - foreach ($refs as $ref) - { - return "il__obj_".$ref; - } - } - - // 26 Sep 2018: moved this under the import id handling above - // If an imported object is found, this is always preferred. - // see also bug #23324 - if (ilInternalLink::_extractInstOfTarget($a_target) == IL_INST_ID - && IL_INST_ID > 0) - { - // does it have a ref id part? - if ($tarr[4] != "") - { - return "il__obj_".$tarr[4]; - } - } - - break; - - } - return false; - } - - /** - * Check if internal link refers to a valid target - * - * @param string $a_type target type ("PageObject" | "StructureObject" | - * "GlossaryItem" | "MediaObject") - * @param string $a_target target id, e.g. "il__pg_244") - * - * @return boolean true/false - */ - static function _exists($a_type, $a_target) - { - global $DIC; - - $tree = $DIC->repositoryTree(); - - switch($a_type) - { - case "PageObject": - case "StructureObject": - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - return ilLMObject::_exists($a_target); - break; - - case "GlossaryItem": - include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - return ilGlossaryTerm::_exists($a_target); - break; - - case "MediaObject": - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - return ilObjMediaObject::_exists($a_target); - break; - - case "WikiPage": - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - return ilWikiPage::_exists("wiki", (int)$a_target); - break; - - case "RepositoryItem": - if (is_int(strpos($a_target, "_"))) - { - $ref_id = ilInternalLink::_extractObjIdOfTarget($a_target); - return $tree->isInTree($ref_id); - } - break; - } - return false; - } - - - /** - * Extract installation id out of target - * - * @param string $a_target import target id (e.g. "il_2_pg_22") - */ - static function _extractInstOfTarget($a_target) - { - if (!is_int(strpos($a_target, "__"))) - { - $target = explode("_", $a_target); - if ($target[1] > 0) - { - return $target[1]; - } - } - return false; - } - - /** - * Removes installation id from target string - * - * @param string $a_target import target id (e.g. "il_2_pg_22") - */ - static function _removeInstFromTarget($a_target) - { - if (!is_int(strpos($a_target, "__"))) - { - $target = explode("_", $a_target); - if ($target[1] > 0) - { - return "il__".$target[2]."_".$target[3]; - } - } - return false; - } - - /** - * Extract object id out of target - * - * @param string $a_target import target id (e.g. "il_2_pg_22") - */ - static function _extractObjIdOfTarget($a_target) - { - $target = explode("_", $a_target); - return $target[count($target) - 1]; - } - - /** - * Extract type out of target - * - * @param string $a_target import target id (e.g. "il_2_pg_22") - */ - static function _extractTypeOfTarget($a_target) - { - $target = explode("_", $a_target); - return $target[count($target) - 2]; - } - - /** - * Search users - * - * @param - * @return - */ - static function searchUsers($a_search_str) - { - $result = new ilSearchResult(); - - $query_parser = new ilQueryParser($a_search_str, '%_'); - $query_parser->setCombination(QP_COMBINATION_AND); - $query_parser->setMinWordLength(3); - $query_parser->parse(); - - $user_search = ilObjectSearchFactory::_getUserSearchInstance($query_parser); - $user_search->enableActiveCheck(true); - $user_search->setFields(array('login')); - $result_obj = $user_search->performSearch(); - $result->mergeEntries($result_obj); - - $user_search->setFields(array('firstname')); - $result_obj = $user_search->performSearch(); - $result->mergeEntries($result_obj); - - $user_search->setFields(array('lastname')); - $result_obj = $user_search->performSearch(); - $result->mergeEntries($result_obj); - - $result->setMaxHits(100000); - $result->preventOverwritingMaxhits(true); - $result->filter(ROOT_FOLDER_ID, true); - - // Filter users (depends on setting in user accounts) - include_once 'Services/User/classes/class.ilUserFilter.php'; - $users = ilUserFilter::getInstance()->filter($result->getResultIds()); - - include_once("./Services/User/classes/class.ilObjUser.php"); - $p = ilObjUser::getProfileStatusOfUsers($users); - - $users = array_intersect($users, $p["public"]); - - return $users; - } - + /** + * Delete all links of a given source + * + * @param string $a_source_type source type + * @param int $a_source_if source id + * @param int $a_lang source language + */ + public static function _deleteAllLinksOfSource($a_source_type, $a_source_id, $a_lang = "-") + { + global $DIC; + + $ilDB = $DIC->database(); + + $lang_where = ""; + if ($a_lang != "") { + $lang_where = " AND source_lang = " . $ilDB->quote($a_lang, "text"); + } + + $q = "DELETE FROM int_link WHERE source_type = " . + $ilDB->quote($a_source_type, "text") . " AND source_id=" . + $ilDB->quote((int) $a_source_id, "integer") . + $lang_where; + $ilDB->manipulate($q); + } + + /** + * Delete all links to a given target + * + * @param string $a_target_type target type + * @param int $a_target_id target id + * @param int $a_target_inst target installation id + */ + public static function _deleteAllLinksToTarget($a_target_type, $a_target_id, $a_target_inst = 0) + { + global $DIC; + + $ilDB = $DIC->database(); + + $ilDB->manipulateF( + "DELETE FROM int_link WHERE target_type = %s " . + " AND target_id = %s AND target_inst = %s ", + array("text", "integer", "integer"), + array($a_target_type, (int) $a_target_id, (int) $a_target_inst) + ); + } + + /** + * save internal link information + * + * @param string $a_source_type source type + * @param int $a_source_if source id + * @param string $a_target_type target type + * @param int $a_target_id target id + * @param int $a_target_inst target installation id + */ + public static function _saveLink( + $a_source_type, + $a_source_id, + $a_target_type, + $a_target_id, + $a_target_inst = 0, + $a_source_lang = "-" + ) { + global $DIC; + + $ilDB = $DIC->database(); + + $ilDB->replace( + "int_link", + array( + "source_type" => array("text", $a_source_type), + "source_id" => array("integer", (int) $a_source_id), + "source_lang" => array("text", $a_source_lang), + "target_type" => array("text", $a_target_type), + "target_id" => array("integer", (int) $a_target_id), + "target_inst" => array("integer", (int) $a_target_inst) + ), + array() + ); + } + + /** + * get all sources of a link target + * + * @param string $a_target_type target type + * @param int $a_target_id target id + * @param int $a_target_inst target installation id + * + * @return array sources (array of array("type", "id")) + */ + public static function _getSourcesOfTarget($a_target_type, $a_target_id, $a_target_inst) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "SELECT * FROM int_link WHERE " . + "target_type = " . $ilDB->quote($a_target_type, "text") . " AND " . + "target_id = " . $ilDB->quote((int) $a_target_id, "integer") . " AND " . + "target_inst = " . $ilDB->quote((int) $a_target_inst, "integer"); + $source_set = $ilDB->query($q); + $sources = array(); + while ($source_rec = $ilDB->fetchAssoc($source_set)) { + $sources[$source_rec["source_type"] . ":" . $source_rec["source_id"] . ":" . $source_rec["source_lang"]] = + array("type" => $source_rec["source_type"], "id" => $source_rec["source_id"], + "lang" => $source_rec["source_lang"]); + } + + return $sources; + } + + /** + * Get all targets of a source object (e.g., a page) + * + * @param string $a_source_type source type (e.g. "lm:pg" | "dbk:pg") + * @param int $a_source_id source id + * + * @return array targets (array of array("type", "id", "inst")) + */ + public static function _getTargetsOfSource($a_source_type, $a_source_id, $a_source_lang = "-") + { + global $DIC; + + $ilDB = $DIC->database(); + + $lang_where = ""; + if ($a_source_lang != "") { + $lang_where = " AND source_lang = " . $ilDB->quote($a_source_lang, "text"); + } + + $q = "SELECT * FROM int_link WHERE " . + "source_type = " . $ilDB->quote($a_source_type, "text") . " AND " . + "source_id = " . $ilDB->quote((int) $a_source_id, "integer") . + $lang_where; + + $target_set = $ilDB->query($q); + $targets = array(); + while ($target_rec = $ilDB->fetchAssoc($target_set)) { + $targets[$target_rec["target_type"] . ":" . $target_rec["target_id"] . ":" . $target_rec["target_inst"]] = + array("type" => $target_rec["target_type"], "id" => $target_rec["target_id"], + "inst" => $target_rec["target_inst"]); + } + + return $targets; + } + + /** + * Get current id for an import id + * + * @param string $a_type target type ("PageObject" | "StructureObject" | + * "GlossaryItem" | "MediaObject") + * @param string $a_target import target id (e.g. "il_2_pg_22") + * + * @return string current target id (e.g. "il__pg_244") + */ + public static function _getIdForImportId($a_type, $a_target) + { + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + switch ($a_type) { + case "PageObject": + $id = ilLMObject::_getIdForImportId($a_target); + if ($id > 0) { + return "il__pg_" . $id; + } + break; + + case "StructureObject": + $id = ilLMObject::_getIdForImportId($a_target); + if ($id > 0) { + return "il__st_" . $id; + } + break; + + case "GlossaryItem": + include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + $id = ilGlossaryTerm::_getIdForImportId($a_target); + //echo "+".$id."+".$a_target."+"; + if ($id > 0) { + return "il__git_" . $id; + } + break; + + case "WikiPage": + // no import IDs for wiki pages (yet) + //$id = ilGlossaryTerm::_getIdForImportId($a_target); + $id = 0; + if ($id > 0) { + return "il__wpage_" . $id; + } + break; + + case "MediaObject": + $id = ilObjMediaObject::_getIdForImportId($a_target); + if ($id > 0) { + return "il__mob_" . $id; + } + break; + + case "RepositoryItem": + + $tarr = explode("_", $a_target); + $import_id = $a_target; + + // if a ref id part is given, strip this + // since this will not be part of an import id + // see also bug #6685 + if ($tarr[4] != "") { + $import_id = $tarr[0] . "_" . $tarr[1] . "_" . $tarr[2] . "_" . $tarr[3]; + } + + $id = ilObject::_getIdForImportId($import_id); + + // get ref id for object id + // (see ilPageObject::insertInstIntoIDs for the export procedure) + if ($id > 0) { + $refs = ilObject::_getAllReferences($id); + foreach ($refs as $ref) { + return "il__obj_" . $ref; + } + } + + // 26 Sep 2018: moved this under the import id handling above + // If an imported object is found, this is always preferred. + // see also bug #23324 + if (ilInternalLink::_extractInstOfTarget($a_target) == IL_INST_ID + && IL_INST_ID > 0) { + // does it have a ref id part? + if ($tarr[4] != "") { + return "il__obj_" . $tarr[4]; + } + } + + break; + + } + return false; + } + + /** + * Check if internal link refers to a valid target + * + * @param string $a_type target type ("PageObject" | "StructureObject" | + * "GlossaryItem" | "MediaObject") + * @param string $a_target target id, e.g. "il__pg_244") + * + * @return boolean true/false + */ + public static function _exists($a_type, $a_target) + { + global $DIC; + + $tree = $DIC->repositoryTree(); + + switch ($a_type) { + case "PageObject": + case "StructureObject": + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + return ilLMObject::_exists($a_target); + break; + + case "GlossaryItem": + include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + return ilGlossaryTerm::_exists($a_target); + break; + + case "MediaObject": + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + return ilObjMediaObject::_exists($a_target); + break; + + case "WikiPage": + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + return ilWikiPage::_exists("wiki", (int) $a_target); + break; + + case "RepositoryItem": + if (is_int(strpos($a_target, "_"))) { + $ref_id = ilInternalLink::_extractObjIdOfTarget($a_target); + return $tree->isInTree($ref_id); + } + break; + } + return false; + } + + + /** + * Extract installation id out of target + * + * @param string $a_target import target id (e.g. "il_2_pg_22") + */ + public static function _extractInstOfTarget($a_target) + { + if (!is_int(strpos($a_target, "__"))) { + $target = explode("_", $a_target); + if ($target[1] > 0) { + return $target[1]; + } + } + return false; + } + + /** + * Removes installation id from target string + * + * @param string $a_target import target id (e.g. "il_2_pg_22") + */ + public static function _removeInstFromTarget($a_target) + { + if (!is_int(strpos($a_target, "__"))) { + $target = explode("_", $a_target); + if ($target[1] > 0) { + return "il__" . $target[2] . "_" . $target[3]; + } + } + return false; + } + + /** + * Extract object id out of target + * + * @param string $a_target import target id (e.g. "il_2_pg_22") + */ + public static function _extractObjIdOfTarget($a_target) + { + $target = explode("_", $a_target); + return $target[count($target) - 1]; + } + + /** + * Extract type out of target + * + * @param string $a_target import target id (e.g. "il_2_pg_22") + */ + public static function _extractTypeOfTarget($a_target) + { + $target = explode("_", $a_target); + return $target[count($target) - 2]; + } + + /** + * Search users + * + * @param + * @return + */ + public static function searchUsers($a_search_str) + { + $result = new ilSearchResult(); + + $query_parser = new ilQueryParser($a_search_str, '%_'); + $query_parser->setCombination(QP_COMBINATION_AND); + $query_parser->setMinWordLength(3); + $query_parser->parse(); + + $user_search = ilObjectSearchFactory::_getUserSearchInstance($query_parser); + $user_search->enableActiveCheck(true); + $user_search->setFields(array('login')); + $result_obj = $user_search->performSearch(); + $result->mergeEntries($result_obj); + + $user_search->setFields(array('firstname')); + $result_obj = $user_search->performSearch(); + $result->mergeEntries($result_obj); + + $user_search->setFields(array('lastname')); + $result_obj = $user_search->performSearch(); + $result->mergeEntries($result_obj); + + $result->setMaxHits(100000); + $result->preventOverwritingMaxhits(true); + $result->filter(ROOT_FOLDER_ID, true); + + // Filter users (depends on setting in user accounts) + include_once 'Services/User/classes/class.ilUserFilter.php'; + $users = ilUserFilter::getInstance()->filter($result->getResultIds()); + + include_once("./Services/User/classes/class.ilObjUser.php"); + $p = ilObjUser::getProfileStatusOfUsers($users); + + $users = array_intersect($users, $p["public"]); + + return $users; + } } -?> diff --git a/Services/Link/classes/class.ilInternalLinkGUI.php b/Services/Link/classes/class.ilInternalLinkGUI.php index f11c97429da49d4288291d461f984b4524c1d62c..2bebf8580f67b09258c612be2be335cdb602f41b 100755 --- a/Services/Link/classes/class.ilInternalLinkGUI.php +++ b/Services/Link/classes/class.ilInternalLinkGUI.php @@ -16,1197 +16,1189 @@ require_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); */ class ilInternalLinkGUI { - /** - * @var string - */ - protected $default_link_type; - - /** - * @var int - */ - protected $default_parent_ref_id; - - /** - * @var int - */ - protected $default_parent_obj_id; - - /** - * @var int - */ - protected $parent_ref_id; - - /** - * @var int - */ - protected $parent_obj_id; - - protected $link_type; // "PageObject_New" - protected $link_target; // "New" - protected $base_link_type; // "PageObject" - - - var $set_link_script; - - /** - * @var array link types - */ - protected $ltypes = array(); - - /** - * @var array parent object types for link base types - */ - protected $parent_type = array(); - - /** - * @var ilCtrl - */ - var $ctrl; - - /** - * @var bool - */ - protected $filter_white_list = false; - - /** - * @var array - */ - protected $filter_link_types = array(); - - /** - * @var ilTree - */ - protected $tree; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilObjUser - */ - protected $user; - - function __construct($a_default_link_type, $a_default_parent_id, $a_is_ref = true) - { - global $DIC; - $this->tree = $DIC->repositoryTree(); - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $this->user = $DIC->user(); - - $this->lng->loadLanguageModule("link"); - $this->lng->loadLanguageModule("content"); - //$this->ctrl->saveParameter($this, array("linkmode", "target_type", "link_par_ref_id", "link_par_obj_id", - // "link_par_fold_id", "link_type")); - $this->ctrl->saveParameter($this, array("linkmode", "link_par_ref_id", "link_par_obj_id", - "link_par_fold_id", "link_type")); - - // default type and parent - $this->default_link_type = $a_default_link_type; - if ($a_is_ref) - { - $this->default_parent_ref_id = $a_default_parent_id; - $this->default_parent_obj_id = ilObject::_lookupObjId($a_default_parent_id); - } - else - { - $this->default_parent_ref_id = 0; - $this->default_parent_obj_id = $a_default_parent_id; - } - $this->default_parent_obj_type = ($this->default_parent_obj_id > 0) - ? ilObject::_lookupType($this->default_parent_obj_id) - : ""; - - // current parent object - $this->parent_ref_id = (int) $_GET["link_par_ref_id"]; - $this->parent_fold_id = (int) $_GET["link_par_fold_id"]; // e.g. media pool folder - if ($this->parent_ref_id > 0) - { - $this->parent_obj_id = ilObject::_lookupObjId($this->parent_ref_id); - } - else - { - $this->parent_obj_id = (int) $_GET["link_par_obj_id"]; - } - } - - /** - * Init (first in execute command) - */ - function init() - { - $lng = $this->lng; - $tree = $this->tree; - $ctrl = $this->ctrl; - - if ($this->parent_ref_id > 0 && !$tree->isInTree($this->parent_ref_id)) - { - $this->resetLinkList(); - } - - $this->parent_type = array( - "StructureObject" => "lm", - "PageObject" => "lm", - "GlossaryItem" => "glo", - "Media" => "mep", - "WikiPage" => "wiki", - "PortfolioPage" => "prtf", - "PortfolioTemplatePage" => "prtt", - "File" => "", - "RepositoryItem" => "", - "User" => "" - ); - - // filter link types - $this->ltypes = array( - "StructureObject" => $lng->txt("cont_lk_chapter"), - "StructureObject_New" => $lng->txt("cont_lk_chapter_new"), - "PageObject" => $lng->txt("cont_lk_page"), - "PageObject_FAQ" => $lng->txt("cont_lk_page_faq"), - "PageObject_New" => $lng->txt("cont_lk_page_new"), - "GlossaryItem" => $lng->txt("cont_lk_term"), - "GlossaryItem_New" => $lng->txt("cont_lk_term_new"), - "Media" => $lng->txt("cont_lk_media_inline"), - "Media_Media" => $lng->txt("cont_lk_media_media"), - "Media_FAQ" => $lng->txt("cont_lk_media_faq"), - "Media_New" => $lng->txt("cont_lk_media_new"), - "WikiPage" => $lng->txt("cont_wiki_page"), - "PortfolioPage" => $lng->txt("cont_prtf_page"), - "PortfolioTemplatePage" => $lng->txt("cont_prtt_page"), - "File" => $lng->txt("cont_lk_file"), - "RepositoryItem" => $lng->txt("cont_repository_item"), - "User" => $lng->txt("cont_user") - ); - if (!$this->filter_white_list) - { - foreach($this->filter_link_types as $link_type) - { - unset($this->ltypes[$link_type]); - } - } - else - { - $ltypes = array(); - foreach($this->ltypes as $k => $l) - { - if (in_array($k, $this->filter_link_types)) - { - $ltypes[$k] = $l; - } - } - $this->ltypes = $ltypes; - } - // determine link type and target - $this->link_type = ($_GET["link_type"] == "") - ? $this->default_link_type - : $_GET["link_type"]; - $ltype_arr = explode("_", $this->link_type); - $this->base_link_type = $ltype_arr[0]; - $this->link_target = $ltype_arr[1]; - - - $def_type = ilObject::_lookupType($this->default_parent_obj_id); - - // determine content object id - switch($this->base_link_type) - { - case "PageObject": - case "StructureObject": - case "GlossaryItem": - case "Media": - case "WikiPage": - case "PortfolioPage": - case "PortfolioTemplatePage": - if ($this->parent_ref_id == 0 && $this->parent_obj_id == 0 - && $def_type == $this->parent_type[$this->base_link_type]) - { - $this->parent_ref_id = $this->default_parent_ref_id; - $this->parent_obj_id = $this->default_parent_obj_id; - $ctrl->setParameter($this, "link_par_obj_id", $this->parent_obj_id); - $ctrl->setParameter($this, "link_par_ref_id", $this->parent_ref_id); - } - break; - } - - - } - - - /** - * Set mode - * @deprecated - */ - function setMode($a_mode = "text") - { - } - - function setSetLinkTargetScript($a_script) - { - $this->set_link_script = $a_script; - } - - function setReturn($a_return) - { - $this->return = $a_return; - } - - function getSetLinkTargetScript() - { - return $this->set_link_script; - } - - function filterLinkType($a_link_type) - { - $this->filter_link_types[] = $a_link_type; - } - - /** - * Set filter list as white list (per detault it is a black list) - * - * @return boolean white list - */ - function setFilterWhiteList($a_white_list) - { - $this->filter_white_list = $a_white_list; - } - - - function executeCommand() - { - $this->init(); - $next_class = $this->ctrl->getNextClass($this); - - $cmd = $this->ctrl->getCmd("showLinkHelp"); - switch($next_class) - { - default: - $ret = $this->$cmd(); - break; - } - - return $ret; - } - - function resetLinkList() - { - $ctrl = $this->ctrl; - - $ctrl->setParameter($this, "link_par_ref_id", ""); - $ctrl->setParameter($this, "link_par_obj_id", ""); - $ctrl->setParameter($this, "link_par_fold_id", ""); - $ctrl->setParameter($this, "link_type", ""); - - $ctrl->redirect($this, "showLinkHelp", "", true); - } - - function closeLinkHelp() - { - if ($this->return == "") - { - $this->ctrl->returnToParent($this); - } - else - { - ilUtil::redirect($this->return); - } - } - - /** - * Prepare output for JS enabled editing - */ - function prepareJavascriptOutput($str) - { - return htmlspecialchars($str, ENT_QUOTES); - } - - - /** - * Show link help list - */ - function showLinkHelp() - { - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - - - $parent_type = $this->parent_type[$this->base_link_type]; - if ((in_array($this->base_link_type, array("GlossaryItem", "WikiPage", "PageObject", "StructureObject")) && - ($this->parent_ref_id == 0)) - || - (($this->parent_ref_id > 0) && - !in_array(ilObject::_lookupType($this->parent_ref_id, true), array($parent_type)))) - { - if ($parent_type != "") - { - $this->changeTargetObject($parent_type); - } - } - if ($ilCtrl->isAsynch()) - { - $tpl = new ilTemplate("tpl.link_help_asynch.html", true, true, "Services/Link"); - $tpl->setVariable("NEW_LINK_URL", $this->ctrl->getLinkTarget($this, - "", false, true, false)); - } - else - { - $tpl = new ilTemplate("tpl.link_help.html", true, true, "Services/Link"); - $tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); - } - - $tpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this, "changeLinkType", "", true)); - $tpl->setVariable("FORMACTION2", $this->ctrl->getFormAction($this)); - $tpl->setVariable("TXT_HELP_HEADER", $this->lng->txt("cont_link_select")); - $tpl->setVariable("TXT_TYPE", $this->lng->txt("cont_link_type")); - - - $select_ltype = ilUtil::formSelect ($this->link_type, - "ltype", $this->ltypes, false, true, "0", "", array("id" => "ilIntLinkTypeSelector")); - $tpl->setVariable("SELECT_TYPE", $select_ltype); - $tpl->setVariable("CMD_CHANGETYPE", "changeLinkType"); - $tpl->setVariable("BTN_CHANGETYPE", $this->lng->txt("cont_change_type")); - - $tpl->setVariable("CMD_CLOSE", "closeLinkHelp"); - $tpl->setVariable("BTN_CLOSE", $this->lng->txt("close")); - - $chapterRowBlock = "chapter_row_js"; - - // switch link type - switch($this->base_link_type) - { - // page link - case "PageObject": - require_once("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); - include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); - - $cont_obj = new ilObjLearningModule($this->parent_ref_id, true); - - // get all chapters - $ctree = $cont_obj->getLMTree(); - $nodes = $ctree->getSubtree($ctree->getNodeData($ctree->getRootId())); - $tpl->setCurrentBlock("chapter_list"); - $tpl->setVariable("TXT_CONTENT_OBJECT", $this->lng->txt("obj_lm")); - $tpl->setVariable("TXT_CONT_TITLE", $cont_obj->getTitle()); - $tpl->setVariable("THEAD", $this->lng->txt("pages")); - - - $tpl->setCurrentBlock("change_cont_obj"); - $tpl->setVariable("CMD_CHANGE_CONT_OBJ", "changeTargetObject"); - $tpl->setVariable("BTN_CHANGE_CONT_OBJ", $this->lng->txt("change")); - $tpl->parseCurrentBlock(); - - foreach($nodes as $node) - { - if($node["type"] == "st") - { - $tpl->setCurrentBlock("header_row"); - $tpl->setVariable("TXT_HEADER", $node["title"]); - $tpl->parseCurrentBlock(); - $tpl->setCurrentBlock("row"); - $tpl->parseCurrentBlock(); - } - - if($node["type"] == "pg") - { - include_once("./Services/COPage/classes/class.ilPCParagraph.php"); - $this->renderLink($tpl, $node["title"], $node["obj_id"], - "PageObject", "pg", "page", - ilPCParagraph::_readAnchors("lm", $node["obj_id"], "")); - } - } - - // get all free pages - $pages = ilLMPageObject::getPageList($cont_obj->getId()); - $free_pages = array(); - foreach ($pages as $page) - { - if (!$ctree->isInTree($page["obj_id"])) - { - $free_pages[] = $page; - } - } - if(count($free_pages) > 0) - { - $tpl->setCurrentBlock("header_row"); - $tpl->setVariable("TXT_HEADER", $this->lng->txt("cont_free_pages")); - $tpl->parseCurrentBlock(); - - foreach ($free_pages as $node) - { - include_once("./Services/COPage/classes/class.ilPCParagraph.php"); - $this->renderLink($tpl, $node["title"], $node["obj_id"], - "PageObject", "pg", "page", - ilPCParagraph::_readAnchors("lm", $node["obj_id"], "")); - } - } - - $tpl->setCurrentBlock("chapter_list"); - $tpl->parseCurrentBlock(); - - break; - - // chapter link - case "StructureObject": - - // check whether current object matchs to type - if (!in_array(ilObject::_lookupType($this->parent_ref_id, true), - array("lm"))) - { - $this->changeTargetObject("lm"); - } - - require_once("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); - $cont_obj = new ilObjLearningModule($this->parent_ref_id, true); - - // get all chapters - $ctree =& $cont_obj->getLMTree(); - $nodes = $ctree->getSubtree($ctree->getNodeData($ctree->getRootId())); - $tpl->setCurrentBlock("chapter_list"); - $tpl->setVariable("TXT_CONTENT_OBJECT", $this->lng->txt("obj_lm")); - $tpl->setVariable("TXT_CONT_TITLE", $cont_obj->getTitle()); - $tpl->setVariable("THEAD", $this->lng->txt("link_chapters")); - $tpl->setCurrentBlock("change_cont_obj"); - $tpl->setVariable("CMD_CHANGE_CONT_OBJ", "changeTargetObject"); - $tpl->setVariable("BTN_CHANGE_CONT_OBJ", $this->lng->txt("change")); - $tpl->parseCurrentBlock(); - - foreach($nodes as $node) - { - if($node["type"] == "st") - { - $this->renderLink($tpl, $node["title"], $node["obj_id"], - "StructureObject", "st", "chap"); - } - } - $tpl->setCurrentBlock("chapter_list"); - $tpl->parseCurrentBlock(); - break; - - // glossary item link - case "GlossaryItem": - require_once("./Modules/Glossary/classes/class.ilObjGlossary.php"); - $glossary = new ilObjGlossary($this->parent_ref_id, true); - - // get all glossary items - $terms = $glossary->getTermList(); - $tpl->setCurrentBlock("chapter_list"); - $tpl->setVariable("TXT_CONTENT_OBJECT", $this->lng->txt("glossary")); - $tpl->setVariable("TXT_CONT_TITLE", $glossary->getTitle()); - $tpl->setVariable("THEAD", $this->lng->txt("link_terms")); - $tpl->setCurrentBlock("change_cont_obj"); - $tpl->setVariable("CMD_CHANGE_CONT_OBJ", "changeTargetObject"); - $tpl->setVariable("BTN_CHANGE_CONT_OBJ", $this->lng->txt("change")); - $tpl->parseCurrentBlock(); - - foreach($terms as $term) - { - $this->renderLink($tpl, $term["term"], $term["id"], - "GlossaryItem", "git", "term"); - } - - $tpl->setCurrentBlock("chapter_list"); - $tpl->parseCurrentBlock(); - break; - - // media object - case "Media": - include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); - //$tpl->setVariable("TARGET2", " target=\"content\" "); - // content object id = 0 --> get clipboard objects - if ($this->parent_ref_id == 0) - { - $tpl->setCurrentBlock("change_cont_obj"); - $tpl->setVariable("CMD_CHANGE_CONT_OBJ", "changeTargetObject"); - $tpl->setVariable("BTN_CHANGE_CONT_OBJ", $this->lng->txt("change")); - $tpl->parseCurrentBlock(); - $mobjs = $ilUser->getClipboardObjects("mob"); - // sort by name - $objs = array(); - foreach ($mobjs as $obj) - { - $objs[$obj["title"].":".$obj["id"]] = $obj; - } - ksort($objs); - $tpl->setCurrentBlock("chapter_list"); - $tpl->setVariable("TXT_CONTENT_OBJECT", $this->lng->txt("cont_media_source")); - $tpl->setVariable("TXT_CONT_TITLE", $this->lng->txt("cont_personal_clipboard")); - $tpl->setVariable("THEAD", $this->lng->txt("link_mobs")); - $tpl->setVariable("COLSPAN", "2"); - - foreach($objs as $obj) - { - $this->renderLink($tpl, $obj["title"], $obj["id"], - "MediaObject", "mob", "media"); - } - $tpl->setCurrentBlock("chapter_list"); - $tpl->parseCurrentBlock(); - } - else - { - require_once("./Modules/MediaPool/classes/class.ilObjMediaPool.php"); - $med_pool = new ilObjMediaPool($this->parent_ref_id, true); - // get current folders - $fobjs = $med_pool->getChilds($this->parent_fold_id, "fold"); - $f2objs = array(); - foreach ($fobjs as $obj) - { - $f2objs[$obj["title"].":".$obj["child"]] = $obj; - } - ksort($f2objs); - // get current media objects - $mobjs = $med_pool->getChilds($this->parent_fold_id, "mob"); - $m2objs = array(); - foreach ($mobjs as $obj) - { - $m2objs[$obj["title"].":".$obj["child"]] = $obj; - } - ksort($m2objs); - - // merge everything together - $objs = array_merge($f2objs, $m2objs); - - $tpl->setCurrentBlock("chapter_list"); - $tpl->setVariable("TXT_CONTENT_OBJECT", $this->lng->txt("mep")); - $tpl->setVariable("TXT_CONT_TITLE", $med_pool->getTitle()); - $tpl->setVariable("THEAD", $this->lng->txt("link_mobs")); - $tpl->setCurrentBlock("change_cont_obj"); - $tpl->setVariable("CMD_CHANGE_CONT_OBJ", "changeTargetObject"); - $tpl->setVariable("BTN_CHANGE_CONT_OBJ", $this->lng->txt("change")); - $tpl->setVariable("COLSPAN", "2"); - $tpl->parseCurrentBlock(); - if ($parent_id = $med_pool->getParentId($this->parent_fold_id)) - { - $css_row = "tblrow1"; - $tpl->setCurrentBlock("icon"); - $tpl->setVariable("ICON_SRC", ilUtil::getImagePath("icon_fold.svg")); - $tpl->parseCurrentBlock(); - $tpl->setCurrentBlock("link_row"); - $tpl->setVariable("ROWCLASS", $css_row); - $tpl->setVariable("TXT_CHAPTER", ".."); - $this->ctrl->setParameter($this, "mep_fold", $parent_id); - if ($ilCtrl->isAsynch()) - { - $tpl->setVariable("LINK", "#"); - $tpl->setVariable("LR_ONCLICK", - " onclick=\"return il.IntLink.setMepPoolFolder('".$parent_id."');\" "); - - } - else - { - $tpl->setVariable("LINK", - $this->ctrl->getLinkTarget($this, "setMedPoolFolder")); - } - $tpl->parseCurrentBlock(); - $tpl->setCurrentBlock("row"); - $tpl->parseCurrentBlock(); - } - foreach($objs as $obj) - { - if($obj["type"] == "fold") - { - $css_row = ($css_row == "tblrow2") - ? "tblrow1" - : "tblrow2"; - $tpl->setCurrentBlock("icon"); - $tpl->setVariable("ICON_SRC", ilUtil::getImagePath("icon_fold.svg")); - $tpl->parseCurrentBlock(); - $tpl->setCurrentBlock("link_row"); - $tpl->setVariable("ROWCLASS", $css_row); - $tpl->setVariable("TXT_CHAPTER", $obj["title"]); - $this->ctrl->setParameter($this, "mep_fold", $obj["child"]); - if ($ilCtrl->isAsynch()) - { - $tpl->setVariable("LINK", "#"); - $tpl->setVariable("LR_ONCLICK", - " onclick=\"return il.IntLink.setMepPoolFolder('".$obj["child"]."');\" "); - - } - else - { - $tpl->setVariable("LINK", - $this->ctrl->getLinkTarget($this, "setMedPoolFolder")); - } - $tpl->parseCurrentBlock(); - } - else - { - $fid = ilMediaPoolItem::lookupForeignId($obj["child"]); - if (ilObject::_lookupType($fid) == "mob") - { - $this->renderLink($tpl, $obj["title"], $fid, - "MediaObject", "mob", "media"); - } - } - $tpl->setCurrentBlock("row"); - $tpl->parseCurrentBlock(); - } - $tpl->setCurrentBlock("chapter_list"); - $tpl->parseCurrentBlock(); - } - break; - - // wiki page link - case "WikiPage": - $wiki_id = ilObject::_lookupObjId($this->parent_ref_id); - require_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $wpages = ilWikiPage::getAllWikiPages($wiki_id); - - // get all glossary items - $tpl->setCurrentBlock("chapter_list"); - $tpl->setVariable("TXT_CONTENT_OBJECT", $this->lng->txt("obj_wiki")); - $tpl->setVariable("TXT_CONT_TITLE", ilObject::_lookupTitle($wiki_id)); - $tpl->setVariable("THEAD", $this->lng->txt("link_wpages")); - $tpl->setCurrentBlock("change_cont_obj"); - $tpl->setVariable("CMD_CHANGE_CONT_OBJ", "changeTargetObject"); - $tpl->setVariable("BTN_CHANGE_CONT_OBJ", $this->lng->txt("change")); - $tpl->parseCurrentBlock(); - - foreach($wpages as $wpage) - { - $this->renderLink($tpl, $wpage["title"], $wpage["id"], - "WikiPage", "wpage", "wpage"); - } - - $tpl->setCurrentBlock("chapter_list"); - $tpl->parseCurrentBlock(); - break; - - // Portfolio page link - case "PortfolioPage": - case "PortfolioTemplatePage": - $prtf_id = $this->parent_obj_id; - require_once("./Modules/Portfolio/classes/class.ilPortfolioPage.php"); - $ppages = ilPortfolioPage::getAllPortfolioPages($prtf_id); - - // get all glossary items - $tpl->setCurrentBlock("chapter_list"); - $tpl->setVariable("TXT_CONTENT_OBJECT", $this->lng->txt("obj_".ilObject::_lookupType($prtf_id))); - $tpl->setVariable("TXT_CONT_TITLE", ilObject::_lookupTitle($prtf_id)); - $tpl->setVariable("THEAD", $this->lng->txt("pages")); - - foreach($ppages as $ppage) - { - $this->renderLink($tpl, $ppage["title"], $ppage["id"], - "PortfolioPage", "ppage", "ppage", array(), $ppage["title"]); - } - - $tpl->setCurrentBlock("chapter_list"); - $tpl->parseCurrentBlock(); - break; - - // repository item - case "RepositoryItem": - $tpl->setVariable("LINK_HELP_CONTENT", $this->selectRepositoryItem()); - break; - - // file download link - case "File": - if (!is_object($this->uploaded_file)) - { - $tpl->setVariable("LINK_HELP_CONTENT", $this->getFileLinkHTML()); - } - else - { - echo $this->getFileLinkHTML(); - exit; - } - break; - - // file download link - case "User": - $tpl->setVariable("LINK_HELP_CONTENT", $this->addUser()); - break; - - } - - if ($ilCtrl->isAsynch()) - { - echo $tpl->get(); - exit; - } - - exit; - } - - /** - * Get HTML for file link - * @return string file link html - */ - function getFileLinkHTML() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if (!is_object($this->uploaded_file)) - { - $tpl = new ilTemplate("tpl.link_file.html", true, true, "Services/Link"); - $tpl->setCurrentBlock("form"); - $tpl->setVariable("FORM_ACTION", - $ilCtrl->getFormAction($this, "saveFileLink", "", true)); - $tpl->setVariable("TXT_SELECT_FILE", $lng->txt("cont_select_file")); - $tpl->setVariable("TXT_SAVE_LINK", $lng->txt("cont_create_link")); - $tpl->setVariable("CMD_SAVE_LINK", "saveFileLink"); - include_once("./Services/Form/classes/class.ilFileInputGUI.php"); - $fi = new ilFileInputGUI("", "link_file"); - $fi->setSize(15); - $tpl->setVariable("INPUT", $fi->getToolbarHTML()); - $tpl->parseCurrentBlock(); - return $tpl->get(); - } - else - { - $tpl = new ilTemplate("tpl.link_file.html", true, true, "Services/Link"); - $tpl->setCurrentBlock("link_js"); -// $tpl->setVariable("LINK_FILE", -// $this->prepareJavascriptOutput("[iln dfile=\"".$this->uploaded_file->getId()."\"] [/iln]") -// ); - $tpl->setVariable("TAG_B", - '[iln dfile=\x22'.$this->uploaded_file->getId().'\x22]'); - $tpl->setVariable("TAG_E", - "[/iln]"); - $tpl->setVariable("TXT_FILE", - $this->uploaded_file->getTitle()); -// $tpl->parseCurrentBlock(); - return $tpl->get(); - } - } - - /** - * Save file link - */ - function saveFileLink() - { - if ($_FILES["link_file"]["name"] != "") - { - include_once("./Modules/File/classes/class.ilObjFile.php"); - $fileObj = new ilObjFile(); - $fileObj->setType("file"); - $fileObj->setTitle($_FILES["link_file"]["name"]); - $fileObj->setDescription(""); - $fileObj->setFileName($_FILES["link_file"]["name"]); - $fileObj->setFileType($_FILES["link_file"]["type"]); - $fileObj->setFileSize($_FILES["link_file"]["size"]); - $fileObj->setMode("filelist"); - $fileObj->create(); - // upload file to filesystem - $fileObj->createDirectory(); - $fileObj->raiseUploadError(false); - $fileObj->getUploadFile($_FILES["link_file"]["tmp_name"], - $_FILES["link_file"]["name"]); - $this->uploaded_file = $fileObj; - - } - $this->showLinkHelp(); - } - - /** - * output thumbnail - */ - function outputThumbnail(&$tpl, $a_id, $a_mode = "") - { - // output thumbnail - $mob = new ilObjMediaObject($a_id); - $med =& $mob->getMediaItem("Standard"); - $target = $med->getThumbnailTarget("small"); - $suff = ""; - if ($this->getSetLinkTargetScript() != "") - { - $tpl->setCurrentBlock("thumbnail_link"); - $suff = "_link"; - } - else - { - $tpl->setCurrentBlock("thumbnail_js"); - $suff = "_js"; - } - - if ($target != "") - { - $tpl->setCurrentBlock("thumb".$suff); - $tpl->setVariable("SRC_THUMB", $target); - $tpl->parseCurrentBlock(); - } - else - { - $tpl->setVariable("NO_THUMB", " "); - } - - if ($this->getSetLinkTargetScript() != "") - { - $tpl->setCurrentBlock("thumbnail_link"); - } - else - { - $tpl->setCurrentBlock("thumbnail_js"); - } - $tpl->parseCurrentBlock(); - } - - - /** - * change link type - */ - function changeLinkType() - { - $ctrl = $this->ctrl; - - $ctrl->setParameter($this, "link_type", $_GET["link_type"]); - $base_type = explode("_", $_GET["link_type"])[0]; - if ($this->parent_type[$base_type] != ilObject::_lookupType($this->parent_ref_id, true)) - { - $ctrl->setParameter($this, "link_par_ref_id", 0); - $ctrl->setParameter($this, "link_par_obj_id", 0); - } - - $ctrl->redirect($this, "showLinkHelp", "", true); - } - - /** - * select media pool folder - */ - function setMedPoolFolder() - { - $ctrl = $this->ctrl; - $ctrl->setParameter($this, "link_par_fold_id", $_GET["mep_fold"]); - $ctrl->redirect($this, "showLinkHelp", "", true); - } - - /** - * Cange target object - */ - function getTargetExplorer() - { - //$ilCtrl->setParameter($this, "target_type", $a_type); - include_once("./Services/Link/classes/class.ilLinkTargetObjectExplorerGUI.php"); - $exp = new ilLinkTargetObjectExplorerGUI($this, "getTargetExplorer", $this->link_type); - - $a_type = $this->parent_type[$this->base_link_type]; - - $white = array("root", "cat", "crs", "fold", "grp"); - - $white[] = $a_type; - $exp->setClickableType($a_type); - if ($a_type == "prtf") - { - $white[] = "prtt"; - $exp->setClickableType("prtt"); - } - - $exp->setTypeWhiteList($white); - - - if (!$exp->handleCommand()) - { - return $exp->getHTML(); - } - } - - /** - * Cange target object - */ - function changeTargetObject($a_type = "") - { - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameter($this, "link_par_fold_id", ""); - if($_GET["do"] == "set") - { - $ilCtrl->setParameter($this, "link_par_ref_id", $_GET["sel_id"]); - $ilCtrl->redirect($this, "showLinkHelp", "", true); - return; - } - - $ilCtrl->setParameter($this, "link_type", $this->link_type); - - $tpl = new ilTemplate("tpl.link_help_explorer.html", true, true, "Services/Link"); - - $output = $this->getTargetExplorer(); - - $tpl->setVariable("TXT_EXPLORER_HEADER", $this->lng->txt("cont_choose_".$this->parent_type[$this->base_link_type])); - - $tpl->setVariable("EXPLORER",$output); - $tpl->setVariable("ACTION", $this->ctrl->getFormAction($this, "resetLinkList", "", true)); - $tpl->setVariable("BTN_RESET", "resetLinkList"); - $tpl->setVariable("TXT_RESET", $this->lng->txt("back")); - - if ($this->parent_type[$this->base_link_type] == "mep") - { - $tpl->setCurrentBlock("sel_clipboard"); - $this->ctrl->setParameter($this, "do", "set"); - if ($ilCtrl->isAsynch()) - { - $tpl->setVariable("LINK_CLIPBOARD", "#"); - $tpl->setVariable("CLIPBOARD_ONCLICK", - " onclick=\"return il.IntLink.selectLinkTargetObject('mep', 0, '".$this->link_type."');\" "); - - } - else - { - $tpl->setVariable("LINK_CLIPBOARD", $this->ctrl->getLinkTarget($this, "changeTargetObject")); - } - $tpl->setVariable("TXT_PERS_CLIPBOARD", $this->lng->txt("clipboard")); - $tpl->parseCurrentBlock(); - } - - $tpl->parseCurrentBlock(); - - echo $tpl->get(); - exit; - } - - - /** - * select repository item explorer - */ - function selectRepositoryItem() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameter($this, "link_par_fold_id", ""); - - //$ilCtrl->setParameter($this, "target_type", $a_type); - include_once("./Services/Link/classes/class.ilIntLinkRepItemExplorerGUI.php"); - $exp = new ilIntLinkRepItemExplorerGUI($this, "selectRepositoryItem"); - $exp->setSetLinkTargetScript($this->getSetLinkTargetScript()); - - if (!$exp->handleCommand()) - { - return $exp->getHTML(); - } - } - - /** - * Refresh Repository Selector - */ - function refreshRepositorySelector() - { - $output = $this->selectRepositoryItem(); - echo $output; - exit; - } - - - /** - * Get initialisation HTML to use interna link editing - */ - static function getInitHTML($a_url) - { - global $DIC; - - $lng = $DIC->language(); - $tpl = $DIC["tpl"]; - - $lng->loadLanguageModule("link"); - - $tpl->addJavaScript("./Services/UIComponent/Explorer/js/ilExplorer.js"); - include_once("./Services/UIComponent/Explorer2/classes/class.ilExplorerBaseGUI.php"); - ilExplorerBaseGUI::init(); - - include_once("./Services/YUI/classes/class.ilYuiUtil.php"); - ilYuiUtil::initConnection(); - - $tpl->addJavascript("./Services/Link/js/ilIntLink.js"); - - // #18721 - $tpl->addJavaScript("Services/Form/js/Form.js"); - - include_once("./Services/UIComponent/Modal/classes/class.ilModalGUI.php"); - $modal = ilModalGUI::getInstance(); - $modal->setHeading($lng->txt("link_link")); - $modal->setId("ilIntLinkModal"); - $modal->setBody("
                  "); - - $ltpl = new ilTemplate("tpl.int_link_panel.html", true, true, "Services/Link"); - $ltpl->setVariable("MODAL", $modal->getHTML()); - - $ltpl->setVariable("IL_INT_LINK_URL", $a_url); - - return $ltpl->get(); - } - - /** - * Render internal link item - */ - function renderLink($tpl, $a_title, $a_obj_id, $a_type, $a_type_short, $a_bb_type, - $a_anchors = array(), $a_link_content = "") - { - $chapterRowBlock = "chapter_row_js"; - $anchor_row_block = "anchor_link_js"; - - $target_str = ($this->link_target == "") - ? "" - : " target=\"".$this->link_target."\""; - - if (count($a_anchors) > 0) - { - foreach ($a_anchors as $anchor) - { - if ($this->getSetLinkTargetScript() != "") - { - // not implemented yet (anchors that work with map areas) - - /*$tpl->setCurrentBlock("anchor_link"); - $tpl->setVariable("ALINK", - ilUtil::appendUrlParameterString($this->getSetLinkTargetScript(), - "linktype=".$a_type. - "&linktarget=il__".$a_type_short."_".$a_obj_id. - "&linktargetframe=".$this->link_target). - "&linkanchor=".$anchor); - $tpl->setVariable("TXT_ALINK", "#" . $anchor); - $tpl->parseCurrentBlock();*/ - } - else - { - $tpl->setCurrentBlock($anchor_row_block); - $tpl->setVariable("ALINK_BEGIN", - $this->prepareJavascriptOutput("[iln " . $a_bb_type . "=\"" . $a_obj_id . "\"" . $target_str . " anchor=\"$anchor\"]")); - $tpl->setVariable("ALINK_END", "[/iln]"); - $tpl->setVariable("TXT_LINK", "#" . $anchor); - $tpl->parseCurrentBlock(); - } - } - } - - $this->css_row = ($this->css_row == "tblrow1") - ? "tblrow2" - : "tblrow1"; - - if ($this->getSetLinkTargetScript() != "") - { - require_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); - require_once("./Services/MediaObjects/classes/class.ilImageMapEditorGUI.php"); - ilImageMapEditorGUI::_recoverParameters(); - if ($a_type == "MediaObject") - { - $this->outputThumbnail($tpl, $a_obj_id); - } - $tpl->setCurrentBlock("link_row"); - $tpl->setVariable("ROWCLASS", $this->css_row); - $tpl->setVariable("TXT_CHAPTER", $a_title); - $tpl->setVariable("LINK", - ilUtil::appendUrlParameterString($this->getSetLinkTargetScript(), - "linktype=".$a_type. - "&linktarget=il__".$a_type_short."_".$a_obj_id. - "&linktargetframe=".$this->link_target)); - $tpl->parseCurrentBlock(); - } - else - { - $tpl->setCurrentBlock($chapterRowBlock); - if ($a_type == "MediaObject") - { - $this->outputThumbnail($tpl, $a_obj_id); - $tpl->setCurrentBlock($chapterRowBlock); - } - $tpl->setVariable("ROWCLASS", $this->css_row); - $tpl->setVariable("TXT_CHAPTER", $a_title); - if ($a_type == "MediaObject" && empty($target_str)) - { - $tpl->setVariable("LINK_BEGIN", - $this->prepareJavascriptOutput("[iln ".$a_bb_type."=\"".$a_obj_id."\"/]")); - $tpl->setVariable("LINK_END", ""); - } - else - { - $tpl->setVariable("LINK_BEGIN", - $this->prepareJavascriptOutput("[iln ".$a_bb_type."=\"".$a_obj_id."\"".$target_str."]")); - $tpl->setVariable("LINK_CONTENT", $a_link_content); - $tpl->setVariable("LINK_END", "[/iln]"); - } - $tpl->parseCurrentBlock(); - } - - $tpl->setCurrentBlock("row"); - $tpl->parseCurrentBlock(); - - } - - /** - * Add user - * - * @param - * @return - */ - function addUser() - { - $form = $this->initUserSearchForm(); - return $form->getHTML().$this->getUserSearchResult(); - } - - /** - * Init user search form. - */ - public function initUserSearchForm() - { - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setId("link_user_search_form"); - - // user search - $ti = new ilTextInputGUI($this->lng->txt("obj_user"), "usr_search_str"); - $ti->setValue($_POST["usr_search_str"]); - $form->addItem($ti); - - $form->addCommandButton("searchUser", $this->lng->txt("search")); - - return $form; - } - - /** - * Search user - * - * @param - * @return - */ - function getUserSearchResult() - { - global $DIC; - - $tpl = $DIC["tpl"]; - $lng = $DIC->language(); - - if (strlen($_POST["usr_search_str"]) < 3) - { - if (strlen($_POST["usr_search_str"]) > 0) - { - $lng->loadLanguageModule("search"); - return $tpl->getMessageHTML($lng->txt("search_minimum_three"), "info"); - } - - return ""; - } - - $form = $this->initUserSearchForm(); - $form->checkInput(); - - $users = ilInternalLink::searchUsers($form->getInput("usr_search_str")); - if (count($users) == 0) - { - return $tpl->getMessageHTML($lng->txt("cont_user_search_did_not_match"), "info"); - } - - $f = $DIC->ui()->factory(); - $r = $DIC->ui()->renderer(); - $lng = $DIC->language(); - $cards = array(); - foreach ($users as $user) - { - $b = $f->button()->standard($lng->txt("insert"),"#") - ->withOnLoadCode(function($id) use ($user){ - return - '$("#'.$id."\").click(function(ev) { il.IntLink.addInternalLink('[iln user=\"". - ilObjUser::_lookupLogin($user)."\"/]', '', ev); return false;});"; - }); - $name = ilUserUtil::getNamePresentation($user); - $cards[] = $f->card()->standard($name, $f->image()->responsive(ilObjUser::_getPersonalPicturePath($user, "small") , $name)) - ->withSections(array($b)); - } - $deck = $f->deck($cards)->withLargeCardsSize(); - - return $r->renderAsync($deck); - } - - + /** + * @var string + */ + protected $default_link_type; + + /** + * @var int + */ + protected $default_parent_ref_id; + + /** + * @var int + */ + protected $default_parent_obj_id; + + /** + * @var int + */ + protected $parent_ref_id; + + /** + * @var int + */ + protected $parent_obj_id; + + protected $link_type; // "PageObject_New" + protected $link_target; // "New" + protected $base_link_type; // "PageObject" + + + public $set_link_script; + + /** + * @var array link types + */ + protected $ltypes = array(); + + /** + * @var array parent object types for link base types + */ + protected $parent_type = array(); + + /** + * @var ilCtrl + */ + public $ctrl; + + /** + * @var bool + */ + protected $filter_white_list = false; + + /** + * @var array + */ + protected $filter_link_types = array(); + + /** + * @var ilTree + */ + protected $tree; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilObjUser + */ + protected $user; + + public function __construct($a_default_link_type, $a_default_parent_id, $a_is_ref = true) + { + global $DIC; + $this->tree = $DIC->repositoryTree(); + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->user = $DIC->user(); + + $this->lng->loadLanguageModule("link"); + $this->lng->loadLanguageModule("content"); + //$this->ctrl->saveParameter($this, array("linkmode", "target_type", "link_par_ref_id", "link_par_obj_id", + // "link_par_fold_id", "link_type")); + $this->ctrl->saveParameter($this, array("linkmode", "link_par_ref_id", "link_par_obj_id", + "link_par_fold_id", "link_type")); + + // default type and parent + $this->default_link_type = $a_default_link_type; + if ($a_is_ref) { + $this->default_parent_ref_id = $a_default_parent_id; + $this->default_parent_obj_id = ilObject::_lookupObjId($a_default_parent_id); + } else { + $this->default_parent_ref_id = 0; + $this->default_parent_obj_id = $a_default_parent_id; + } + $this->default_parent_obj_type = ($this->default_parent_obj_id > 0) + ? ilObject::_lookupType($this->default_parent_obj_id) + : ""; + + // current parent object + $this->parent_ref_id = (int) $_GET["link_par_ref_id"]; + $this->parent_fold_id = (int) $_GET["link_par_fold_id"]; // e.g. media pool folder + if ($this->parent_ref_id > 0) { + $this->parent_obj_id = ilObject::_lookupObjId($this->parent_ref_id); + } else { + $this->parent_obj_id = (int) $_GET["link_par_obj_id"]; + } + } + + /** + * Init (first in execute command) + */ + public function init() + { + $lng = $this->lng; + $tree = $this->tree; + $ctrl = $this->ctrl; + + if ($this->parent_ref_id > 0 && !$tree->isInTree($this->parent_ref_id)) { + $this->resetLinkList(); + } + + $this->parent_type = array( + "StructureObject" => "lm", + "PageObject" => "lm", + "GlossaryItem" => "glo", + "Media" => "mep", + "WikiPage" => "wiki", + "PortfolioPage" => "prtf", + "PortfolioTemplatePage" => "prtt", + "File" => "", + "RepositoryItem" => "", + "User" => "" + ); + + // filter link types + $this->ltypes = array( + "StructureObject" => $lng->txt("cont_lk_chapter"), + "StructureObject_New" => $lng->txt("cont_lk_chapter_new"), + "PageObject" => $lng->txt("cont_lk_page"), + "PageObject_FAQ" => $lng->txt("cont_lk_page_faq"), + "PageObject_New" => $lng->txt("cont_lk_page_new"), + "GlossaryItem" => $lng->txt("cont_lk_term"), + "GlossaryItem_New" => $lng->txt("cont_lk_term_new"), + "Media" => $lng->txt("cont_lk_media_inline"), + "Media_Media" => $lng->txt("cont_lk_media_media"), + "Media_FAQ" => $lng->txt("cont_lk_media_faq"), + "Media_New" => $lng->txt("cont_lk_media_new"), + "WikiPage" => $lng->txt("cont_wiki_page"), + "PortfolioPage" => $lng->txt("cont_prtf_page"), + "PortfolioTemplatePage" => $lng->txt("cont_prtt_page"), + "File" => $lng->txt("cont_lk_file"), + "RepositoryItem" => $lng->txt("cont_repository_item"), + "User" => $lng->txt("cont_user") + ); + if (!$this->filter_white_list) { + foreach ($this->filter_link_types as $link_type) { + unset($this->ltypes[$link_type]); + } + } else { + $ltypes = array(); + foreach ($this->ltypes as $k => $l) { + if (in_array($k, $this->filter_link_types)) { + $ltypes[$k] = $l; + } + } + $this->ltypes = $ltypes; + } + // determine link type and target + $this->link_type = ($_GET["link_type"] == "") + ? $this->default_link_type + : $_GET["link_type"]; + $ltype_arr = explode("_", $this->link_type); + $this->base_link_type = $ltype_arr[0]; + $this->link_target = $ltype_arr[1]; + + + $def_type = ilObject::_lookupType($this->default_parent_obj_id); + + // determine content object id + switch ($this->base_link_type) { + case "PageObject": + case "StructureObject": + case "GlossaryItem": + case "Media": + case "WikiPage": + case "PortfolioPage": + case "PortfolioTemplatePage": + if ($this->parent_ref_id == 0 && $this->parent_obj_id == 0 + && $def_type == $this->parent_type[$this->base_link_type]) { + $this->parent_ref_id = $this->default_parent_ref_id; + $this->parent_obj_id = $this->default_parent_obj_id; + $ctrl->setParameter($this, "link_par_obj_id", $this->parent_obj_id); + $ctrl->setParameter($this, "link_par_ref_id", $this->parent_ref_id); + } + break; + } + } + + + /** + * Set mode + * @deprecated + */ + public function setMode($a_mode = "text") + { + } + + public function setSetLinkTargetScript($a_script) + { + $this->set_link_script = $a_script; + } + + public function setReturn($a_return) + { + $this->return = $a_return; + } + + public function getSetLinkTargetScript() + { + return $this->set_link_script; + } + + public function filterLinkType($a_link_type) + { + $this->filter_link_types[] = $a_link_type; + } + + /** + * Set filter list as white list (per detault it is a black list) + * + * @return boolean white list + */ + public function setFilterWhiteList($a_white_list) + { + $this->filter_white_list = $a_white_list; + } + + + public function executeCommand() + { + $this->init(); + $next_class = $this->ctrl->getNextClass($this); + + $cmd = $this->ctrl->getCmd("showLinkHelp"); + switch ($next_class) { + default: + $ret = $this->$cmd(); + break; + } + + return $ret; + } + + public function resetLinkList() + { + $ctrl = $this->ctrl; + + $ctrl->setParameter($this, "link_par_ref_id", ""); + $ctrl->setParameter($this, "link_par_obj_id", ""); + $ctrl->setParameter($this, "link_par_fold_id", ""); + $ctrl->setParameter($this, "link_type", ""); + + $ctrl->redirect($this, "showLinkHelp", "", true); + } + + public function closeLinkHelp() + { + if ($this->return == "") { + $this->ctrl->returnToParent($this); + } else { + ilUtil::redirect($this->return); + } + } + + /** + * Prepare output for JS enabled editing + */ + public function prepareJavascriptOutput($str) + { + return htmlspecialchars($str, ENT_QUOTES); + } + + + /** + * Show link help list + */ + public function showLinkHelp() + { + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + + + $parent_type = $this->parent_type[$this->base_link_type]; + if ((in_array($this->base_link_type, array("GlossaryItem", "WikiPage", "PageObject", "StructureObject")) && + ($this->parent_ref_id == 0)) + || + (($this->parent_ref_id > 0) && + !in_array(ilObject::_lookupType($this->parent_ref_id, true), array($parent_type)))) { + if ($parent_type != "") { + $this->changeTargetObject($parent_type); + } + } + if ($ilCtrl->isAsynch()) { + $tpl = new ilTemplate("tpl.link_help_asynch.html", true, true, "Services/Link"); + $tpl->setVariable("NEW_LINK_URL", $this->ctrl->getLinkTarget( + $this, + "", + false, + true, + false + )); + } else { + $tpl = new ilTemplate("tpl.link_help.html", true, true, "Services/Link"); + $tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); + } + + $tpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this, "changeLinkType", "", true)); + $tpl->setVariable("FORMACTION2", $this->ctrl->getFormAction($this)); + $tpl->setVariable("TXT_HELP_HEADER", $this->lng->txt("cont_link_select")); + $tpl->setVariable("TXT_TYPE", $this->lng->txt("cont_link_type")); + + + $select_ltype = ilUtil::formSelect( + $this->link_type, + "ltype", + $this->ltypes, + false, + true, + "0", + "", + array("id" => "ilIntLinkTypeSelector") + ); + $tpl->setVariable("SELECT_TYPE", $select_ltype); + $tpl->setVariable("CMD_CHANGETYPE", "changeLinkType"); + $tpl->setVariable("BTN_CHANGETYPE", $this->lng->txt("cont_change_type")); + + $tpl->setVariable("CMD_CLOSE", "closeLinkHelp"); + $tpl->setVariable("BTN_CLOSE", $this->lng->txt("close")); + + $chapterRowBlock = "chapter_row_js"; + + // switch link type + switch ($this->base_link_type) { + // page link + case "PageObject": + require_once("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); + include_once("./Modules/LearningModule/classes/class.ilLMPage.php"); + + $cont_obj = new ilObjLearningModule($this->parent_ref_id, true); + + // get all chapters + $ctree = $cont_obj->getLMTree(); + $nodes = $ctree->getSubtree($ctree->getNodeData($ctree->getRootId())); + $tpl->setCurrentBlock("chapter_list"); + $tpl->setVariable("TXT_CONTENT_OBJECT", $this->lng->txt("obj_lm")); + $tpl->setVariable("TXT_CONT_TITLE", $cont_obj->getTitle()); + $tpl->setVariable("THEAD", $this->lng->txt("pages")); + + + $tpl->setCurrentBlock("change_cont_obj"); + $tpl->setVariable("CMD_CHANGE_CONT_OBJ", "changeTargetObject"); + $tpl->setVariable("BTN_CHANGE_CONT_OBJ", $this->lng->txt("change")); + $tpl->parseCurrentBlock(); + + foreach ($nodes as $node) { + if ($node["type"] == "st") { + $tpl->setCurrentBlock("header_row"); + $tpl->setVariable("TXT_HEADER", $node["title"]); + $tpl->parseCurrentBlock(); + $tpl->setCurrentBlock("row"); + $tpl->parseCurrentBlock(); + } + + if ($node["type"] == "pg") { + include_once("./Services/COPage/classes/class.ilPCParagraph.php"); + $this->renderLink( + $tpl, + $node["title"], + $node["obj_id"], + "PageObject", + "pg", + "page", + ilPCParagraph::_readAnchors("lm", $node["obj_id"], "") + ); + } + } + + // get all free pages + $pages = ilLMPageObject::getPageList($cont_obj->getId()); + $free_pages = array(); + foreach ($pages as $page) { + if (!$ctree->isInTree($page["obj_id"])) { + $free_pages[] = $page; + } + } + if (count($free_pages) > 0) { + $tpl->setCurrentBlock("header_row"); + $tpl->setVariable("TXT_HEADER", $this->lng->txt("cont_free_pages")); + $tpl->parseCurrentBlock(); + + foreach ($free_pages as $node) { + include_once("./Services/COPage/classes/class.ilPCParagraph.php"); + $this->renderLink( + $tpl, + $node["title"], + $node["obj_id"], + "PageObject", + "pg", + "page", + ilPCParagraph::_readAnchors("lm", $node["obj_id"], "") + ); + } + } + + $tpl->setCurrentBlock("chapter_list"); + $tpl->parseCurrentBlock(); + + break; + + // chapter link + case "StructureObject": + + // check whether current object matchs to type + if (!in_array( + ilObject::_lookupType($this->parent_ref_id, true), + array("lm") + )) { + $this->changeTargetObject("lm"); + } + + require_once("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); + $cont_obj = new ilObjLearningModule($this->parent_ref_id, true); + + // get all chapters + $ctree =&$cont_obj->getLMTree(); + $nodes = $ctree->getSubtree($ctree->getNodeData($ctree->getRootId())); + $tpl->setCurrentBlock("chapter_list"); + $tpl->setVariable("TXT_CONTENT_OBJECT", $this->lng->txt("obj_lm")); + $tpl->setVariable("TXT_CONT_TITLE", $cont_obj->getTitle()); + $tpl->setVariable("THEAD", $this->lng->txt("link_chapters")); + $tpl->setCurrentBlock("change_cont_obj"); + $tpl->setVariable("CMD_CHANGE_CONT_OBJ", "changeTargetObject"); + $tpl->setVariable("BTN_CHANGE_CONT_OBJ", $this->lng->txt("change")); + $tpl->parseCurrentBlock(); + + foreach ($nodes as $node) { + if ($node["type"] == "st") { + $this->renderLink( + $tpl, + $node["title"], + $node["obj_id"], + "StructureObject", + "st", + "chap" + ); + } + } + $tpl->setCurrentBlock("chapter_list"); + $tpl->parseCurrentBlock(); + break; + + // glossary item link + case "GlossaryItem": + require_once("./Modules/Glossary/classes/class.ilObjGlossary.php"); + $glossary = new ilObjGlossary($this->parent_ref_id, true); + + // get all glossary items + $terms = $glossary->getTermList(); + $tpl->setCurrentBlock("chapter_list"); + $tpl->setVariable("TXT_CONTENT_OBJECT", $this->lng->txt("glossary")); + $tpl->setVariable("TXT_CONT_TITLE", $glossary->getTitle()); + $tpl->setVariable("THEAD", $this->lng->txt("link_terms")); + $tpl->setCurrentBlock("change_cont_obj"); + $tpl->setVariable("CMD_CHANGE_CONT_OBJ", "changeTargetObject"); + $tpl->setVariable("BTN_CHANGE_CONT_OBJ", $this->lng->txt("change")); + $tpl->parseCurrentBlock(); + + foreach ($terms as $term) { + $this->renderLink( + $tpl, + $term["term"], + $term["id"], + "GlossaryItem", + "git", + "term" + ); + } + + $tpl->setCurrentBlock("chapter_list"); + $tpl->parseCurrentBlock(); + break; + + // media object + case "Media": + include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); + //$tpl->setVariable("TARGET2", " target=\"content\" "); + // content object id = 0 --> get clipboard objects + if ($this->parent_ref_id == 0) { + $tpl->setCurrentBlock("change_cont_obj"); + $tpl->setVariable("CMD_CHANGE_CONT_OBJ", "changeTargetObject"); + $tpl->setVariable("BTN_CHANGE_CONT_OBJ", $this->lng->txt("change")); + $tpl->parseCurrentBlock(); + $mobjs = $ilUser->getClipboardObjects("mob"); + // sort by name + $objs = array(); + foreach ($mobjs as $obj) { + $objs[$obj["title"] . ":" . $obj["id"]] = $obj; + } + ksort($objs); + $tpl->setCurrentBlock("chapter_list"); + $tpl->setVariable("TXT_CONTENT_OBJECT", $this->lng->txt("cont_media_source")); + $tpl->setVariable("TXT_CONT_TITLE", $this->lng->txt("cont_personal_clipboard")); + $tpl->setVariable("THEAD", $this->lng->txt("link_mobs")); + $tpl->setVariable("COLSPAN", "2"); + + foreach ($objs as $obj) { + $this->renderLink( + $tpl, + $obj["title"], + $obj["id"], + "MediaObject", + "mob", + "media" + ); + } + $tpl->setCurrentBlock("chapter_list"); + $tpl->parseCurrentBlock(); + } else { + require_once("./Modules/MediaPool/classes/class.ilObjMediaPool.php"); + $med_pool = new ilObjMediaPool($this->parent_ref_id, true); + // get current folders + $fobjs = $med_pool->getChilds($this->parent_fold_id, "fold"); + $f2objs = array(); + foreach ($fobjs as $obj) { + $f2objs[$obj["title"] . ":" . $obj["child"]] = $obj; + } + ksort($f2objs); + // get current media objects + $mobjs = $med_pool->getChilds($this->parent_fold_id, "mob"); + $m2objs = array(); + foreach ($mobjs as $obj) { + $m2objs[$obj["title"] . ":" . $obj["child"]] = $obj; + } + ksort($m2objs); + + // merge everything together + $objs = array_merge($f2objs, $m2objs); + + $tpl->setCurrentBlock("chapter_list"); + $tpl->setVariable("TXT_CONTENT_OBJECT", $this->lng->txt("mep")); + $tpl->setVariable("TXT_CONT_TITLE", $med_pool->getTitle()); + $tpl->setVariable("THEAD", $this->lng->txt("link_mobs")); + $tpl->setCurrentBlock("change_cont_obj"); + $tpl->setVariable("CMD_CHANGE_CONT_OBJ", "changeTargetObject"); + $tpl->setVariable("BTN_CHANGE_CONT_OBJ", $this->lng->txt("change")); + $tpl->setVariable("COLSPAN", "2"); + $tpl->parseCurrentBlock(); + if ($parent_id = $med_pool->getParentId($this->parent_fold_id)) { + $css_row = "tblrow1"; + $tpl->setCurrentBlock("icon"); + $tpl->setVariable("ICON_SRC", ilUtil::getImagePath("icon_fold.svg")); + $tpl->parseCurrentBlock(); + $tpl->setCurrentBlock("link_row"); + $tpl->setVariable("ROWCLASS", $css_row); + $tpl->setVariable("TXT_CHAPTER", ".."); + $this->ctrl->setParameter($this, "mep_fold", $parent_id); + if ($ilCtrl->isAsynch()) { + $tpl->setVariable("LINK", "#"); + $tpl->setVariable( + "LR_ONCLICK", + " onclick=\"return il.IntLink.setMepPoolFolder('" . $parent_id . "');\" " + ); + } else { + $tpl->setVariable( + "LINK", + $this->ctrl->getLinkTarget($this, "setMedPoolFolder") + ); + } + $tpl->parseCurrentBlock(); + $tpl->setCurrentBlock("row"); + $tpl->parseCurrentBlock(); + } + foreach ($objs as $obj) { + if ($obj["type"] == "fold") { + $css_row = ($css_row == "tblrow2") + ? "tblrow1" + : "tblrow2"; + $tpl->setCurrentBlock("icon"); + $tpl->setVariable("ICON_SRC", ilUtil::getImagePath("icon_fold.svg")); + $tpl->parseCurrentBlock(); + $tpl->setCurrentBlock("link_row"); + $tpl->setVariable("ROWCLASS", $css_row); + $tpl->setVariable("TXT_CHAPTER", $obj["title"]); + $this->ctrl->setParameter($this, "mep_fold", $obj["child"]); + if ($ilCtrl->isAsynch()) { + $tpl->setVariable("LINK", "#"); + $tpl->setVariable( + "LR_ONCLICK", + " onclick=\"return il.IntLink.setMepPoolFolder('" . $obj["child"] . "');\" " + ); + } else { + $tpl->setVariable( + "LINK", + $this->ctrl->getLinkTarget($this, "setMedPoolFolder") + ); + } + $tpl->parseCurrentBlock(); + } else { + $fid = ilMediaPoolItem::lookupForeignId($obj["child"]); + if (ilObject::_lookupType($fid) == "mob") { + $this->renderLink( + $tpl, + $obj["title"], + $fid, + "MediaObject", + "mob", + "media" + ); + } + } + $tpl->setCurrentBlock("row"); + $tpl->parseCurrentBlock(); + } + $tpl->setCurrentBlock("chapter_list"); + $tpl->parseCurrentBlock(); + } + break; + + // wiki page link + case "WikiPage": + $wiki_id = ilObject::_lookupObjId($this->parent_ref_id); + require_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + $wpages = ilWikiPage::getAllWikiPages($wiki_id); + + // get all glossary items + $tpl->setCurrentBlock("chapter_list"); + $tpl->setVariable("TXT_CONTENT_OBJECT", $this->lng->txt("obj_wiki")); + $tpl->setVariable("TXT_CONT_TITLE", ilObject::_lookupTitle($wiki_id)); + $tpl->setVariable("THEAD", $this->lng->txt("link_wpages")); + $tpl->setCurrentBlock("change_cont_obj"); + $tpl->setVariable("CMD_CHANGE_CONT_OBJ", "changeTargetObject"); + $tpl->setVariable("BTN_CHANGE_CONT_OBJ", $this->lng->txt("change")); + $tpl->parseCurrentBlock(); + + foreach ($wpages as $wpage) { + $this->renderLink( + $tpl, + $wpage["title"], + $wpage["id"], + "WikiPage", + "wpage", + "wpage" + ); + } + + $tpl->setCurrentBlock("chapter_list"); + $tpl->parseCurrentBlock(); + break; + + // Portfolio page link + case "PortfolioPage": + case "PortfolioTemplatePage": + $prtf_id = $this->parent_obj_id; + require_once("./Modules/Portfolio/classes/class.ilPortfolioPage.php"); + $ppages = ilPortfolioPage::getAllPortfolioPages($prtf_id); + + // get all glossary items + $tpl->setCurrentBlock("chapter_list"); + $tpl->setVariable("TXT_CONTENT_OBJECT", $this->lng->txt("obj_" . ilObject::_lookupType($prtf_id))); + $tpl->setVariable("TXT_CONT_TITLE", ilObject::_lookupTitle($prtf_id)); + $tpl->setVariable("THEAD", $this->lng->txt("pages")); + + foreach ($ppages as $ppage) { + $this->renderLink( + $tpl, + $ppage["title"], + $ppage["id"], + "PortfolioPage", + "ppage", + "ppage", + array(), + $ppage["title"] + ); + } + + $tpl->setCurrentBlock("chapter_list"); + $tpl->parseCurrentBlock(); + break; + + // repository item + case "RepositoryItem": + $tpl->setVariable("LINK_HELP_CONTENT", $this->selectRepositoryItem()); + break; + + // file download link + case "File": + if (!is_object($this->uploaded_file)) { + $tpl->setVariable("LINK_HELP_CONTENT", $this->getFileLinkHTML()); + } else { + echo $this->getFileLinkHTML(); + exit; + } + break; + + // file download link + case "User": + $tpl->setVariable("LINK_HELP_CONTENT", $this->addUser()); + break; + + } + + if ($ilCtrl->isAsynch()) { + echo $tpl->get(); + exit; + } + + exit; + } + + /** + * Get HTML for file link + * @return string file link html + */ + public function getFileLinkHTML() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if (!is_object($this->uploaded_file)) { + $tpl = new ilTemplate("tpl.link_file.html", true, true, "Services/Link"); + $tpl->setCurrentBlock("form"); + $tpl->setVariable( + "FORM_ACTION", + $ilCtrl->getFormAction($this, "saveFileLink", "", true) + ); + $tpl->setVariable("TXT_SELECT_FILE", $lng->txt("cont_select_file")); + $tpl->setVariable("TXT_SAVE_LINK", $lng->txt("cont_create_link")); + $tpl->setVariable("CMD_SAVE_LINK", "saveFileLink"); + include_once("./Services/Form/classes/class.ilFileInputGUI.php"); + $fi = new ilFileInputGUI("", "link_file"); + $fi->setSize(15); + $tpl->setVariable("INPUT", $fi->getToolbarHTML()); + $tpl->parseCurrentBlock(); + return $tpl->get(); + } else { + $tpl = new ilTemplate("tpl.link_file.html", true, true, "Services/Link"); + $tpl->setCurrentBlock("link_js"); + // $tpl->setVariable("LINK_FILE", + // $this->prepareJavascriptOutput("[iln dfile=\"".$this->uploaded_file->getId()."\"] [/iln]") + // ); + $tpl->setVariable( + "TAG_B", + '[iln dfile=\x22' . $this->uploaded_file->getId() . '\x22]' + ); + $tpl->setVariable( + "TAG_E", + "[/iln]" + ); + $tpl->setVariable( + "TXT_FILE", + $this->uploaded_file->getTitle() + ); + // $tpl->parseCurrentBlock(); + return $tpl->get(); + } + } + + /** + * Save file link + */ + public function saveFileLink() + { + if ($_FILES["link_file"]["name"] != "") { + include_once("./Modules/File/classes/class.ilObjFile.php"); + $fileObj = new ilObjFile(); + $fileObj->setType("file"); + $fileObj->setTitle($_FILES["link_file"]["name"]); + $fileObj->setDescription(""); + $fileObj->setFileName($_FILES["link_file"]["name"]); + $fileObj->setFileType($_FILES["link_file"]["type"]); + $fileObj->setFileSize($_FILES["link_file"]["size"]); + $fileObj->setMode("filelist"); + $fileObj->create(); + // upload file to filesystem + $fileObj->createDirectory(); + $fileObj->raiseUploadError(false); + $fileObj->getUploadFile( + $_FILES["link_file"]["tmp_name"], + $_FILES["link_file"]["name"] + ); + $this->uploaded_file = $fileObj; + } + $this->showLinkHelp(); + } + + /** + * output thumbnail + */ + public function outputThumbnail(&$tpl, $a_id, $a_mode = "") + { + // output thumbnail + $mob = new ilObjMediaObject($a_id); + $med =&$mob->getMediaItem("Standard"); + $target = $med->getThumbnailTarget("small"); + $suff = ""; + if ($this->getSetLinkTargetScript() != "") { + $tpl->setCurrentBlock("thumbnail_link"); + $suff = "_link"; + } else { + $tpl->setCurrentBlock("thumbnail_js"); + $suff = "_js"; + } + + if ($target != "") { + $tpl->setCurrentBlock("thumb" . $suff); + $tpl->setVariable("SRC_THUMB", $target); + $tpl->parseCurrentBlock(); + } else { + $tpl->setVariable("NO_THUMB", " "); + } + + if ($this->getSetLinkTargetScript() != "") { + $tpl->setCurrentBlock("thumbnail_link"); + } else { + $tpl->setCurrentBlock("thumbnail_js"); + } + $tpl->parseCurrentBlock(); + } + + + /** + * change link type + */ + public function changeLinkType() + { + $ctrl = $this->ctrl; + + $ctrl->setParameter($this, "link_type", $_GET["link_type"]); + $base_type = explode("_", $_GET["link_type"])[0]; + if ($this->parent_type[$base_type] != ilObject::_lookupType($this->parent_ref_id, true)) { + $ctrl->setParameter($this, "link_par_ref_id", 0); + $ctrl->setParameter($this, "link_par_obj_id", 0); + } + + $ctrl->redirect($this, "showLinkHelp", "", true); + } + + /** + * select media pool folder + */ + public function setMedPoolFolder() + { + $ctrl = $this->ctrl; + $ctrl->setParameter($this, "link_par_fold_id", $_GET["mep_fold"]); + $ctrl->redirect($this, "showLinkHelp", "", true); + } + + /** + * Cange target object + */ + public function getTargetExplorer() + { + //$ilCtrl->setParameter($this, "target_type", $a_type); + include_once("./Services/Link/classes/class.ilLinkTargetObjectExplorerGUI.php"); + $exp = new ilLinkTargetObjectExplorerGUI($this, "getTargetExplorer", $this->link_type); + + $a_type = $this->parent_type[$this->base_link_type]; + + $white = array("root", "cat", "crs", "fold", "grp"); + + $white[] = $a_type; + $exp->setClickableType($a_type); + if ($a_type == "prtf") { + $white[] = "prtt"; + $exp->setClickableType("prtt"); + } + + $exp->setTypeWhiteList($white); + + + if (!$exp->handleCommand()) { + return $exp->getHTML(); + } + } + + /** + * Cange target object + */ + public function changeTargetObject($a_type = "") + { + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameter($this, "link_par_fold_id", ""); + if ($_GET["do"] == "set") { + $ilCtrl->setParameter($this, "link_par_ref_id", $_GET["sel_id"]); + $ilCtrl->redirect($this, "showLinkHelp", "", true); + return; + } + + $ilCtrl->setParameter($this, "link_type", $this->link_type); + + $tpl = new ilTemplate("tpl.link_help_explorer.html", true, true, "Services/Link"); + + $output = $this->getTargetExplorer(); + + $tpl->setVariable("TXT_EXPLORER_HEADER", $this->lng->txt("cont_choose_" . $this->parent_type[$this->base_link_type])); + + $tpl->setVariable("EXPLORER", $output); + $tpl->setVariable("ACTION", $this->ctrl->getFormAction($this, "resetLinkList", "", true)); + $tpl->setVariable("BTN_RESET", "resetLinkList"); + $tpl->setVariable("TXT_RESET", $this->lng->txt("back")); + + if ($this->parent_type[$this->base_link_type] == "mep") { + $tpl->setCurrentBlock("sel_clipboard"); + $this->ctrl->setParameter($this, "do", "set"); + if ($ilCtrl->isAsynch()) { + $tpl->setVariable("LINK_CLIPBOARD", "#"); + $tpl->setVariable( + "CLIPBOARD_ONCLICK", + " onclick=\"return il.IntLink.selectLinkTargetObject('mep', 0, '" . $this->link_type . "');\" " + ); + } else { + $tpl->setVariable("LINK_CLIPBOARD", $this->ctrl->getLinkTarget($this, "changeTargetObject")); + } + $tpl->setVariable("TXT_PERS_CLIPBOARD", $this->lng->txt("clipboard")); + $tpl->parseCurrentBlock(); + } + + $tpl->parseCurrentBlock(); + + echo $tpl->get(); + exit; + } + + + /** + * select repository item explorer + */ + public function selectRepositoryItem() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameter($this, "link_par_fold_id", ""); + + //$ilCtrl->setParameter($this, "target_type", $a_type); + include_once("./Services/Link/classes/class.ilIntLinkRepItemExplorerGUI.php"); + $exp = new ilIntLinkRepItemExplorerGUI($this, "selectRepositoryItem"); + $exp->setSetLinkTargetScript($this->getSetLinkTargetScript()); + + if (!$exp->handleCommand()) { + return $exp->getHTML(); + } + } + + /** + * Refresh Repository Selector + */ + public function refreshRepositorySelector() + { + $output = $this->selectRepositoryItem(); + echo $output; + exit; + } + + + /** + * Get initialisation HTML to use interna link editing + */ + public static function getInitHTML($a_url) + { + global $DIC; + + $lng = $DIC->language(); + $tpl = $DIC["tpl"]; + + $lng->loadLanguageModule("link"); + + $tpl->addJavaScript("./Services/UIComponent/Explorer/js/ilExplorer.js"); + include_once("./Services/UIComponent/Explorer2/classes/class.ilExplorerBaseGUI.php"); + ilExplorerBaseGUI::init(); + + include_once("./Services/YUI/classes/class.ilYuiUtil.php"); + ilYuiUtil::initConnection(); + + $tpl->addJavascript("./Services/Link/js/ilIntLink.js"); + + // #18721 + $tpl->addJavaScript("Services/Form/js/Form.js"); + + include_once("./Services/UIComponent/Modal/classes/class.ilModalGUI.php"); + $modal = ilModalGUI::getInstance(); + $modal->setHeading($lng->txt("link_link")); + $modal->setId("ilIntLinkModal"); + $modal->setBody("
                  "); + + $ltpl = new ilTemplate("tpl.int_link_panel.html", true, true, "Services/Link"); + $ltpl->setVariable("MODAL", $modal->getHTML()); + + $ltpl->setVariable("IL_INT_LINK_URL", $a_url); + + return $ltpl->get(); + } + + /** + * Render internal link item + */ + public function renderLink( + $tpl, + $a_title, + $a_obj_id, + $a_type, + $a_type_short, + $a_bb_type, + $a_anchors = array(), + $a_link_content = "" + ) { + $chapterRowBlock = "chapter_row_js"; + $anchor_row_block = "anchor_link_js"; + + $target_str = ($this->link_target == "") + ? "" + : " target=\"" . $this->link_target . "\""; + + if (count($a_anchors) > 0) { + foreach ($a_anchors as $anchor) { + if ($this->getSetLinkTargetScript() != "") { + // not implemented yet (anchors that work with map areas) + + /*$tpl->setCurrentBlock("anchor_link"); + $tpl->setVariable("ALINK", + ilUtil::appendUrlParameterString($this->getSetLinkTargetScript(), + "linktype=".$a_type. + "&linktarget=il__".$a_type_short."_".$a_obj_id. + "&linktargetframe=".$this->link_target). + "&linkanchor=".$anchor); + $tpl->setVariable("TXT_ALINK", "#" . $anchor); + $tpl->parseCurrentBlock();*/ + } else { + $tpl->setCurrentBlock($anchor_row_block); + $tpl->setVariable( + "ALINK_BEGIN", + $this->prepareJavascriptOutput("[iln " . $a_bb_type . "=\"" . $a_obj_id . "\"" . $target_str . " anchor=\"$anchor\"]") + ); + $tpl->setVariable("ALINK_END", "[/iln]"); + $tpl->setVariable("TXT_LINK", "#" . $anchor); + $tpl->parseCurrentBlock(); + } + } + } + + $this->css_row = ($this->css_row == "tblrow1") + ? "tblrow2" + : "tblrow1"; + + if ($this->getSetLinkTargetScript() != "") { + require_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); + require_once("./Services/MediaObjects/classes/class.ilImageMapEditorGUI.php"); + ilImageMapEditorGUI::_recoverParameters(); + if ($a_type == "MediaObject") { + $this->outputThumbnail($tpl, $a_obj_id); + } + $tpl->setCurrentBlock("link_row"); + $tpl->setVariable("ROWCLASS", $this->css_row); + $tpl->setVariable("TXT_CHAPTER", $a_title); + $tpl->setVariable( + "LINK", + ilUtil::appendUrlParameterString( + $this->getSetLinkTargetScript(), + "linktype=" . $a_type . + "&linktarget=il__" . $a_type_short . "_" . $a_obj_id . + "&linktargetframe=" . $this->link_target + ) + ); + $tpl->parseCurrentBlock(); + } else { + $tpl->setCurrentBlock($chapterRowBlock); + if ($a_type == "MediaObject") { + $this->outputThumbnail($tpl, $a_obj_id); + $tpl->setCurrentBlock($chapterRowBlock); + } + $tpl->setVariable("ROWCLASS", $this->css_row); + $tpl->setVariable("TXT_CHAPTER", $a_title); + if ($a_type == "MediaObject" && empty($target_str)) { + $tpl->setVariable( + "LINK_BEGIN", + $this->prepareJavascriptOutput("[iln " . $a_bb_type . "=\"" . $a_obj_id . "\"/]") + ); + $tpl->setVariable("LINK_END", ""); + } else { + $tpl->setVariable( + "LINK_BEGIN", + $this->prepareJavascriptOutput("[iln " . $a_bb_type . "=\"" . $a_obj_id . "\"" . $target_str . "]") + ); + $tpl->setVariable("LINK_CONTENT", $a_link_content); + $tpl->setVariable("LINK_END", "[/iln]"); + } + $tpl->parseCurrentBlock(); + } + + $tpl->setCurrentBlock("row"); + $tpl->parseCurrentBlock(); + } + + /** + * Add user + * + * @param + * @return + */ + public function addUser() + { + $form = $this->initUserSearchForm(); + return $form->getHTML() . $this->getUserSearchResult(); + } + + /** + * Init user search form. + */ + public function initUserSearchForm() + { + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setId("link_user_search_form"); + + // user search + $ti = new ilTextInputGUI($this->lng->txt("obj_user"), "usr_search_str"); + $ti->setValue($_POST["usr_search_str"]); + $form->addItem($ti); + + $form->addCommandButton("searchUser", $this->lng->txt("search")); + + return $form; + } + + /** + * Search user + * + * @param + * @return + */ + public function getUserSearchResult() + { + global $DIC; + + $tpl = $DIC["tpl"]; + $lng = $DIC->language(); + + if (strlen($_POST["usr_search_str"]) < 3) { + if (strlen($_POST["usr_search_str"]) > 0) { + $lng->loadLanguageModule("search"); + return $tpl->getMessageHTML($lng->txt("search_minimum_three"), "info"); + } + + return ""; + } + + $form = $this->initUserSearchForm(); + $form->checkInput(); + + $users = ilInternalLink::searchUsers($form->getInput("usr_search_str")); + if (count($users) == 0) { + return $tpl->getMessageHTML($lng->txt("cont_user_search_did_not_match"), "info"); + } + + $f = $DIC->ui()->factory(); + $r = $DIC->ui()->renderer(); + $lng = $DIC->language(); + $cards = array(); + foreach ($users as $user) { + $b = $f->button()->standard($lng->txt("insert"), "#") + ->withOnLoadCode(function ($id) use ($user) { + return + '$("#' . $id . "\").click(function(ev) { il.IntLink.addInternalLink('[iln user=\"" . + ilObjUser::_lookupLogin($user) . "\"/]', '', ev); return false;});"; + }); + $name = ilUserUtil::getNamePresentation($user); + $cards[] = $f->card()->standard($name, $f->image()->responsive(ilObjUser::_getPersonalPicturePath($user, "small"), $name)) + ->withSections(array($b)); + } + $deck = $f->deck($cards)->withLargeCardsSize(); + + return $r->renderAsync($deck); + } } -?> diff --git a/Services/Link/classes/class.ilLink.php b/Services/Link/classes/class.ilLink.php index d929c93ba26e273797ecabf9b9c42346e9baeb49..2a885d063e932297378ded0747a5f250b630d570 100644 --- a/Services/Link/classes/class.ilLink.php +++ b/Services/Link/classes/class.ilLink.php @@ -1,7 +1,7 @@ lookupType($ilObjDataCache->lookupObjId($a_ref_id)); - } - $param_string = ''; - if(is_array($a_params) && count($a_params)) - { - foreach($a_params as $name => $value) - { - $param_string .= ('&'.$name.'='.$value); - } - } - switch($a_type) - { - case 'git': - //case 'pg': - return ILIAS_HTTP_PATH.'/'.IL_INTERNAL_LINK_SCRIPT.'?client_id='.CLIENT_ID.$param_string.$append; - - default: - return ILIAS_HTTP_PATH.'/'.IL_INTERNAL_LINK_SCRIPT.'?target='.$a_type.'_'.$a_ref_id.$append.'&client_id='.CLIENT_ID.$param_string; - } - } + if (!strlen($a_type)) { + $a_type = $ilObjDataCache->lookupType($ilObjDataCache->lookupObjId($a_ref_id)); + } + $param_string = ''; + if (is_array($a_params) && count($a_params)) { + foreach ($a_params as $name => $value) { + $param_string .= ('&' . $name . '=' . $value); + } + } + switch ($a_type) { + case 'git': + //case 'pg': + return ILIAS_HTTP_PATH . '/' . IL_INTERNAL_LINK_SCRIPT . '?client_id=' . CLIENT_ID . $param_string . $append; + + default: + return ILIAS_HTTP_PATH . '/' . IL_INTERNAL_LINK_SCRIPT . '?target=' . $a_type . '_' . $a_ref_id . $append . '&client_id=' . CLIENT_ID . $param_string; + } + } - /** - * Get static link - * - * @access public - * @static - * - * @param int reference id - * @param string object type - * @param bool fallback to goto.php if robots are disabled - * @return string goto.html or goto.php link - */ - public static function _getStaticLink($a_ref_id,$a_type = '',$a_fallback_goto = true, - $append = "") - { - global $DIC; + /** + * Get static link + * + * @access public + * @static + * + * @param int reference id + * @param string object type + * @param bool fallback to goto.php if robots are disabled + * @return string goto.html or goto.php link + */ + public static function _getStaticLink( + $a_ref_id, + $a_type = '', + $a_fallback_goto = true, + $append = "" + ) { + global $DIC; - $ilObjDataCache = $DIC["ilObjDataCache"]; + $ilObjDataCache = $DIC["ilObjDataCache"]; - if(!strlen($a_type)) - { - $a_type = $ilObjDataCache->lookupType($ilObjDataCache->lookupObjId($a_ref_id)); - } - - include_once('Services/PrivacySecurity/classes/class.ilRobotSettings.php'); - $robot_settings = ilRobotSettings::_getInstance(); - if(!$robot_settings->robotSupportEnabled()) - { - if($a_fallback_goto) - { - return ilLink::_getLink($a_ref_id,$a_type,array(),$append); - } - else - { - return false; - } - } - - // urlencode for append is needed e.g. to process "/" in wiki page names correctly - return ILIAS_HTTP_PATH.'/goto_'.urlencode(CLIENT_ID).'_'.$a_type.'_'.$a_ref_id.urlencode($append).'.html'; - } + if (!strlen($a_type)) { + $a_type = $ilObjDataCache->lookupType($ilObjDataCache->lookupObjId($a_ref_id)); + } + + include_once('Services/PrivacySecurity/classes/class.ilRobotSettings.php'); + $robot_settings = ilRobotSettings::_getInstance(); + if (!$robot_settings->robotSupportEnabled()) { + if ($a_fallback_goto) { + return ilLink::_getLink($a_ref_id, $a_type, array(), $append); + } else { + return false; + } + } + + // urlencode for append is needed e.g. to process "/" in wiki page names correctly + return ILIAS_HTTP_PATH . '/goto_' . urlencode(CLIENT_ID) . '_' . $a_type . '_' . $a_ref_id . urlencode($append) . '.html'; + } } -?> diff --git a/Services/Link/classes/class.ilLinkTargetObjectExplorerGUI.php b/Services/Link/classes/class.ilLinkTargetObjectExplorerGUI.php index 08437432a1f917760d4f192a85c45bb0e794ea35..8101afe6a916c987d1948b016e04301e8a749016 100644 --- a/Services/Link/classes/class.ilLinkTargetObjectExplorerGUI.php +++ b/Services/Link/classes/class.ilLinkTargetObjectExplorerGUI.php @@ -13,74 +13,70 @@ include_once("./Services/Repository/classes/class.ilRepositorySelectorExplorerGU */ class ilLinkTargetObjectExplorerGUI extends ilRepositorySelectorExplorerGUI { - /** - * @var string - */ - protected $link_type; + /** + * @var string + */ + protected $link_type; - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_link_type) - { - $this->link_type = $a_link_type; - parent::__construct($a_parent_obj, $a_parent_cmd, null, "", ""); - } + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_link_type) + { + $this->link_type = $a_link_type; + parent::__construct($a_parent_obj, $a_parent_cmd, null, "", ""); + } - /** - * Set clickable type - * - * @param string $a_val clickable type - */ - function setClickableType($a_val) - { - $this->clickable_type = $a_val; - } - - /** - * Get clickable type - * - * @return string clickable type - */ - function getClickableType() - { - return $this->clickable_type; - } + /** + * Set clickable type + * + * @param string $a_val clickable type + */ + public function setClickableType($a_val) + { + $this->clickable_type = $a_val; + } + + /** + * Get clickable type + * + * @return string clickable type + */ + public function getClickableType() + { + return $this->clickable_type; + } - /** - * Get onclick attribute - */ - function getNodeOnClick($a_node) - { - return "il.IntLink.selectLinkTargetObject('".$a_node["type"]."','".$a_node["child"]."','".$this->link_type."'); return(false);"; - } + /** + * Get onclick attribute + */ + public function getNodeOnClick($a_node) + { + return "il.IntLink.selectLinkTargetObject('" . $a_node["type"] . "','" . $a_node["child"] . "','" . $this->link_type . "'); return(false);"; + } - /** - * Get href for node - * - * @param mixed $a_node node object/array - * @return string href attribute - */ - function getNodeHref($a_node) - { - return "#"; - } - - /** - * Is node clickable? - * - * @param array $a_node node data - * @return boolean node clickable true/false - */ - function isNodeClickable($a_node) - { - if ($a_node["type"] == $this->getClickableType()) - { - return true; - } - return false; - } + /** + * Get href for node + * + * @param mixed $a_node node object/array + * @return string href attribute + */ + public function getNodeHref($a_node) + { + return "#"; + } + /** + * Is node clickable? + * + * @param array $a_node node data + * @return boolean node clickable true/false + */ + public function isNodeClickable($a_node) + { + if ($a_node["type"] == $this->getClickableType()) { + return true; + } + return false; + } } - -?> diff --git a/Services/Link/classes/class.ilLinkifyUtil.php b/Services/Link/classes/class.ilLinkifyUtil.php index 720059d428058d4a8c74a8dd43ed96bbb412a045..f2747ad45089716df3e20b750b38d824b5782740 100644 --- a/Services/Link/classes/class.ilLinkifyUtil.php +++ b/Services/Link/classes/class.ilLinkifyUtil.php @@ -8,41 +8,38 @@ * @version $Id$ */ class ilLinkifyUtil -{ - private static $ver = "1_1"; - private static $min = ".min"; +{ + private static $ver = "1_1"; + private static $min = ".min"; - /** - * Init Linkify - * - * @param ilTemplate $a_tpl template - */ - static function initLinkify($a_tpl = null) - { - global $DIC; + /** + * Init Linkify + * + * @param ilTemplate $a_tpl template + */ + public static function initLinkify($a_tpl = null) + { + global $DIC; - $tpl = $DIC["tpl"]; - - if ($a_tpl == null) - { - $a_tpl = $tpl; - } + $tpl = $DIC["tpl"]; + + if ($a_tpl == null) { + $a_tpl = $tpl; + } - foreach (self::getLocalJsPaths() as $p) - { - $a_tpl->addJavaScript($p); - } - } + foreach (self::getLocalJsPaths() as $p) { + $a_tpl->addJavaScript($p); + } + } - /** - * Get paths of necessary js files - */ - static function getLocalJsPaths() - { - return array( - "./Services/Link/lib/linkify/".self::$ver."/jquery.linkify".self::$min.".js", - "./Services/Link/js/ilExtLink.js" - ); - } + /** + * Get paths of necessary js files + */ + public static function getLocalJsPaths() + { + return array( + "./Services/Link/lib/linkify/" . self::$ver . "/jquery.linkify" . self::$min . ".js", + "./Services/Link/js/ilExtLink.js" + ); + } } -?> \ No newline at end of file diff --git a/Services/Locator/classes/class.ilLocatorGUI.php b/Services/Locator/classes/class.ilLocatorGUI.php index e81b5a2ee689e3023844811212588bb2d1decd51..4791f1e22d8243cf0033948a457073a6be4a07b3 100755 --- a/Services/Locator/classes/class.ilLocatorGUI.php +++ b/Services/Locator/classes/class.ilLocatorGUI.php @@ -10,431 +10,396 @@ * * @author Arjan Ammerlaan * @version $Id$ -* +* */ class ilLocatorGUI { - /** - * @var ilTree - */ - protected $tree; - - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilTree + */ + protected $tree; - /** - * @var ilObjectDefinition - */ - protected $obj_definition; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilObjectDefinition + */ + protected $obj_definition; - /** - * @var ilSetting - */ - protected $settings; + /** + * @var ilAccessHandler + */ + protected $access; - protected $lng; - protected $entries; - - /** - * Constructor - * - */ - function __construct() - { - global $DIC; + /** + * @var ilSetting + */ + protected $settings; - $this->tree = $DIC->repositoryTree(); - $this->ctrl = $DIC->ctrl(); - $this->obj_definition = $DIC["objDefinition"]; - $this->access = $DIC->access(); - $this->settings = $DIC->settings(); - $lng = $DIC->language(); + protected $lng; + protected $entries; + + /** + * Constructor + * + */ + public function __construct() + { + global $DIC; - $this->lng = $lng; - $this->entries = array(); - $this->setTextOnly(false); - $this->offline = false; - } + $this->tree = $DIC->repositoryTree(); + $this->ctrl = $DIC->ctrl(); + $this->obj_definition = $DIC["objDefinition"]; + $this->access = $DIC->access(); + $this->settings = $DIC->settings(); + $lng = $DIC->language(); - /** - * Set Only text, no HTML. - * - * @param boolean $a_textonly Only text, no HTML - */ - function setTextOnly($a_textonly) - { - $this->textonly = $a_textonly; - } - - function setOffline($a_offline) - { - $this->offline = $a_offline; - } + $this->lng = $lng; + $this->entries = array(); + $this->setTextOnly(false); + $this->offline = false; + } - function getOffline() - { - return $this->offline; - } + /** + * Set Only text, no HTML. + * + * @param boolean $a_textonly Only text, no HTML + */ + public function setTextOnly($a_textonly) + { + $this->textonly = $a_textonly; + } + + public function setOffline($a_offline) + { + $this->offline = $a_offline; + } - /** - * Get Only text, no HTML. - * - * @return boolean Only text, no HTML - */ - function getTextOnly() - { - return $this->textonly; - } + public function getOffline() + { + return $this->offline; + } - /** - * add repository item - * - * @param int $a_ref_id current ref id (optional); - * if empty $_GET["ref_id"] is used - */ - function addRepositoryItems($a_ref_id = 0) - { - $setting = $this->settings; - $tree = $this->tree; - $ilCtrl = $this->ctrl; + /** + * Get Only text, no HTML. + * + * @return boolean Only text, no HTML + */ + public function getTextOnly() + { + return $this->textonly; + } - if ($a_ref_id == 0) - { - $a_ref_id = $_GET["ref_id"]; - } - - include_once './Services/Container/classes/class.ilMemberViewSettings.php'; - if(ilMemberViewSettings::getInstance()->isActive() and $a_ref_id != ROOT_FOLDER_ID) - { - $a_start = ilMemberViewSettings::getInstance()->getContainer(); - } - else - { - $a_start = ROOT_FOLDER_ID; - } - - if ($a_ref_id > 0) - { - $path = $tree->getPathFull($a_ref_id,$a_start); + /** + * add repository item + * + * @param int $a_ref_id current ref id (optional); + * if empty $_GET["ref_id"] is used + */ + public function addRepositoryItems($a_ref_id = 0) + { + $setting = $this->settings; + $tree = $this->tree; + $ilCtrl = $this->ctrl; - // check if path contains crs - $crs_ref_id = 0; - foreach ($path as $k => $v) - { - if ($v["type"] == "crs") - { - $crs_ref_id = $v["child"]; - } - } - if (!$setting->get("rep_breadcr_crs")) // no overwrite - { - $crs_ref_id = 0; - } - else if ($setting->get("rep_breadcr_crs_overwrite")) // overwrite - { - // course wants full path - if (ilContainer::_lookupContainerSetting(ilObject::_lookupObjId($crs_ref_id), "rep_breacrumb") == ilObjCourseGUI::BREADCRUMB_FULL_PATH) - { - $crs_ref_id = 0; - } - // course wants default and default wants full path - if (ilContainer::_lookupContainerSetting(ilObject::_lookupObjId($crs_ref_id), "rep_breacrumb") == ilObjCourseGUI::BREADCRUMB_DEFAULT && !$setting->get("rep_breadcr_crs_default")) - { - $crs_ref_id = 0; - } - } + if ($a_ref_id == 0) { + $a_ref_id = $_GET["ref_id"]; + } + + include_once './Services/Container/classes/class.ilMemberViewSettings.php'; + if (ilMemberViewSettings::getInstance()->isActive() and $a_ref_id != ROOT_FOLDER_ID) { + $a_start = ilMemberViewSettings::getInstance()->getContainer(); + } else { + $a_start = ROOT_FOLDER_ID; + } + + if ($a_ref_id > 0) { + $path = $tree->getPathFull($a_ref_id, $a_start); - // add item for each node on path - foreach ((array) $path as $key => $row) - { - if (!in_array($row["type"], array("root", "cat", "crs", "fold", "grp", "prg", "lso"))) - { - continue; - } - if ($crs_ref_id > 0 && $row["child"] == $crs_ref_id) - { - $crs_ref_id = 0; - } - if ($crs_ref_id > 0) - { - continue; - } + // check if path contains crs + $crs_ref_id = 0; + foreach ($path as $k => $v) { + if ($v["type"] == "crs") { + $crs_ref_id = $v["child"]; + } + } + if (!$setting->get("rep_breadcr_crs")) { // no overwrite + $crs_ref_id = 0; + } elseif ($setting->get("rep_breadcr_crs_overwrite")) { // overwrite + // course wants full path + if (ilContainer::_lookupContainerSetting(ilObject::_lookupObjId($crs_ref_id), "rep_breacrumb") == ilObjCourseGUI::BREADCRUMB_FULL_PATH) { + $crs_ref_id = 0; + } + // course wants default and default wants full path + if (ilContainer::_lookupContainerSetting(ilObject::_lookupObjId($crs_ref_id), "rep_breacrumb") == ilObjCourseGUI::BREADCRUMB_DEFAULT && !$setting->get("rep_breadcr_crs_default")) { + $crs_ref_id = 0; + } + } - if ($row["title"] == "ILIAS" && $row["type"] == "root") - { - $row["title"] = $this->lng->txt("repository"); - } - - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $row["child"]); - $this->addItem($row["title"], - $ilCtrl->getLinkTargetByClass("ilrepositorygui", "frameset"), - ilFrameTargetInfo::_getFrame("MainContent"), $row["child"]); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - } - } - } - - /** - * add administration tree items - * - * @param int $a_ref_id current ref id (optional); - * if empty $_GET["ref_id"] is used - */ - function addAdministrationItems($a_ref_id = 0) - { - $tree = $this->tree; - $ilCtrl = $this->ctrl; - $objDefinition = $this->obj_definition; - $lng = $this->lng; + // add item for each node on path + foreach ((array) $path as $key => $row) { + if (!in_array($row["type"], array("root", "cat", "crs", "fold", "grp", "prg", "lso"))) { + continue; + } + if ($crs_ref_id > 0 && $row["child"] == $crs_ref_id) { + $crs_ref_id = 0; + } + if ($crs_ref_id > 0) { + continue; + } - if ($a_ref_id == 0) - { - $a_ref_id = $_GET["ref_id"]; - } + if ($row["title"] == "ILIAS" && $row["type"] == "root") { + $row["title"] = $this->lng->txt("repository"); + } + + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $row["child"]); + $this->addItem( + $row["title"], + $ilCtrl->getLinkTargetByClass("ilrepositorygui", "frameset"), + ilFrameTargetInfo::_getFrame("MainContent"), + $row["child"] + ); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + } + } + } + + /** + * add administration tree items + * + * @param int $a_ref_id current ref id (optional); + * if empty $_GET["ref_id"] is used + */ + public function addAdministrationItems($a_ref_id = 0) + { + $tree = $this->tree; + $ilCtrl = $this->ctrl; + $objDefinition = $this->obj_definition; + $lng = $this->lng; - if ($a_ref_id > 0) - { - $path = $tree->getPathFull($a_ref_id); - - // add item for each node on path - foreach ($path as $key => $row) - { - if (!in_array($row["type"], array("root", "cat", "crs", "fold", "grp"))) - { - continue; - } - - if ($row["child"] == ROOT_FOLDER_ID) - { - $row["title"] = $lng->txt("repository"); - } - - $class_name = $objDefinition->getClassName($row["type"]); - $class = strtolower("ilObj".$class_name."GUI"); - $ilCtrl->setParameterByClass($class, "ref_id", $row["child"]); - $this->addItem($row["title"], - $ilCtrl->getLinkTargetbyClass($class, "view"), "", $row["child"]); - } - } - } - - function addContextItems($a_ref_id, $a_omit_node = false, $a_stop = 0) - { - $tree = $this->tree; - - if ($a_ref_id > 0) - { - $path = $tree->getPathFull($a_ref_id); - - // we want to show the full path, from the major container to the item - // (folders are not! treated as containers here), at least one parent item - $r_path = array_reverse($path); - $first = ""; - $omit = array(); - $do_omit = false; - foreach ($r_path as $key => $row) - { - if ($first == "") - { - if (in_array($row["type"], array("root", "cat", "grp", "crs")) && - $row["child"] != $a_ref_id) - { - $first = $row["child"]; - } - } - if ($a_stop == $row["child"]) - { - $do_omit = true; - } - $omit[$row["child"]] = $do_omit; - } + if ($a_ref_id == 0) { + $a_ref_id = $_GET["ref_id"]; + } - $add_it = false; - foreach ($path as $key => $row) - { - if ($first == $row["child"]) - { - $add_it = true; - } - - - if ($add_it && !$omit[$row["child"]] && - (!$a_omit_node || ($row["child"] != $a_ref_id))) - { -//echo "-".ilObject::_lookupTitle($row["obj_id"])."-"; - if ($row["title"] == "ILIAS" && $row["type"] == "root") - { - $row["title"] = $this->lng->txt("repository"); - } - $this->addItem($row["title"], - "./goto.php?client_id=".rawurlencode(CLIENT_ID)."&target=".$row["type"]."_".$row["child"], - "_top", $row["child"], $row["type"]); - } - } - } - } - - /** - * add locator item - * - * @param string $a_title item title - * @param string $a_link item link - * @param string $a_frame frame target - */ - function addItem($a_title, $a_link, $a_frame = "", $a_ref_id = 0, $type = null) - { - // LTI - global $DIC; - $ltiview = $DIC['lti']; - - $ilAccess = $this->access; + if ($a_ref_id > 0) { + $path = $tree->getPathFull($a_ref_id); + + // add item for each node on path + foreach ($path as $key => $row) { + if (!in_array($row["type"], array("root", "cat", "crs", "fold", "grp"))) { + continue; + } + + if ($row["child"] == ROOT_FOLDER_ID) { + $row["title"] = $lng->txt("repository"); + } + + $class_name = $objDefinition->getClassName($row["type"]); + $class = strtolower("ilObj" . $class_name . "GUI"); + $ilCtrl->setParameterByClass($class, "ref_id", $row["child"]); + $this->addItem( + $row["title"], + $ilCtrl->getLinkTargetbyClass($class, "view"), + "", + $row["child"] + ); + } + } + } + + public function addContextItems($a_ref_id, $a_omit_node = false, $a_stop = 0) + { + $tree = $this->tree; + + if ($a_ref_id > 0) { + $path = $tree->getPathFull($a_ref_id); + + // we want to show the full path, from the major container to the item + // (folders are not! treated as containers here), at least one parent item + $r_path = array_reverse($path); + $first = ""; + $omit = array(); + $do_omit = false; + foreach ($r_path as $key => $row) { + if ($first == "") { + if (in_array($row["type"], array("root", "cat", "grp", "crs")) && + $row["child"] != $a_ref_id) { + $first = $row["child"]; + } + } + if ($a_stop == $row["child"]) { + $do_omit = true; + } + $omit[$row["child"]] = $do_omit; + } - if ($a_ref_id > 0 && !$ilAccess->checkAccess("visible", "", $a_ref_id)) - { - return; - } - // LTI - if ($ltiview->isActive()) { - $a_frame = "_self"; - } - $this->entries[] = array("title" => $a_title, - "link" => $a_link, "frame" => $a_frame, "ref_id" => $a_ref_id, "type" => $type); - } - - /** - * Clear all Items - */ - function clearItems() - { - $this->entries = array(); - } - - /** - * Get all locator entries. - */ - function getItems() - { - return $this->entries; - } - - /** - * Get locator HTML - */ - function getHTML() - { - global $DIC; - $ltiview = $DIC["lti"]; - if ($ltiview->isActive() && !$ltiview->show_locator) - { - return ""; - } - $lng = $this->lng; - $ilSetting = $this->settings; - - if ($this->getTextOnly()) - { - $loc_tpl = new ilTemplate("tpl.locator_text_only.html", true, true, "Services/Locator"); - } - else - { - $loc_tpl = new ilTemplate("tpl.locator.html", true, true, "Services/Locator"); - } - - $items = $this->getItems(); - $first = true; + $add_it = false; + foreach ($path as $key => $row) { + if ($first == $row["child"]) { + $add_it = true; + } + + + if ($add_it && !$omit[$row["child"]] && + (!$a_omit_node || ($row["child"] != $a_ref_id))) { + //echo "-".ilObject::_lookupTitle($row["obj_id"])."-"; + if ($row["title"] == "ILIAS" && $row["type"] == "root") { + $row["title"] = $this->lng->txt("repository"); + } + $this->addItem( + $row["title"], + "./goto.php?client_id=" . rawurlencode(CLIENT_ID) . "&target=" . $row["type"] . "_" . $row["child"], + "_top", + $row["child"], + $row["type"] + ); + } + } + } + } + + /** + * add locator item + * + * @param string $a_title item title + * @param string $a_link item link + * @param string $a_frame frame target + */ + public function addItem($a_title, $a_link, $a_frame = "", $a_ref_id = 0, $type = null) + { + // LTI + global $DIC; + $ltiview = $DIC['lti']; + + $ilAccess = $this->access; - if (is_array($items)) - { - foreach($items as $item) - { - if (!$first) - { - $loc_tpl->touchBlock("locator_separator_prefix"); - } - - if ($item["ref_id"] > 0) - { - $obj_id = ilObject::_lookupObjId($item["ref_id"]); - $type = ilObject::_lookupType($obj_id); - - if (!$this->getTextOnly()) - { - $icon_path = ilObject::_getIcon($obj_id, "tiny", $type, - $this->getOffline()); - } - - $loc_tpl->setCurrentBlock("locator_img"); - $loc_tpl->setVariable("IMG_SRC", $icon_path); - $loc_tpl->setVariable("IMG_ALT", - $lng->txt("obj_".$type)); - $loc_tpl->parseCurrentBlock(); - } - - $loc_tpl->setCurrentBlock("locator_item"); - if ($item["link"] != "") - { - $loc_tpl->setVariable("LINK_ITEM", $item["link"]); - if ($item["frame"] != "") - { - $loc_tpl->setVariable("LINK_TARGET", ' target="'.$item["frame"].'" '); - } - $loc_tpl->setVariable("ITEM", $item["title"]); - } - else - { - $loc_tpl->setVariable("PREFIX", $item["title"]); - } - $loc_tpl->parseCurrentBlock(); - - $first = false; - } - } - else - { - $loc_tpl->setVariable("NOITEM", " "); - $loc_tpl->touchBlock("locator"); - } - $loc_tpl->setVariable("TXT_BREADCRUMBS", $lng->txt("breadcrumb_navigation")); - - return trim($loc_tpl->get()); - } + if ($a_ref_id > 0 && !$ilAccess->checkAccess("visible", "", $a_ref_id)) { + return; + } + // LTI + if ($ltiview->isActive()) { + $a_frame = "_self"; + } + $this->entries[] = array("title" => $a_title, + "link" => $a_link, "frame" => $a_frame, "ref_id" => $a_ref_id, "type" => $type); + } + + /** + * Clear all Items + */ + public function clearItems() + { + $this->entries = array(); + } + + /** + * Get all locator entries. + */ + public function getItems() + { + return $this->entries; + } + + /** + * Get locator HTML + */ + public function getHTML() + { + global $DIC; + $ltiview = $DIC["lti"]; + if ($ltiview->isActive() && !$ltiview->show_locator) { + return ""; + } + $lng = $this->lng; + $ilSetting = $this->settings; + + if ($this->getTextOnly()) { + $loc_tpl = new ilTemplate("tpl.locator_text_only.html", true, true, "Services/Locator"); + } else { + $loc_tpl = new ilTemplate("tpl.locator.html", true, true, "Services/Locator"); + } + + $items = $this->getItems(); + $first = true; - /** - * Get text version - */ - function getTextVersion() - { - $lng = $this->lng; - $ilSetting = $this->settings; - - $items = $this->getItems(); - $first = true; + if (is_array($items)) { + foreach ($items as $item) { + if (!$first) { + $loc_tpl->touchBlock("locator_separator_prefix"); + } + + if ($item["ref_id"] > 0) { + $obj_id = ilObject::_lookupObjId($item["ref_id"]); + $type = ilObject::_lookupType($obj_id); + + if (!$this->getTextOnly()) { + $icon_path = ilObject::_getIcon( + $obj_id, + "tiny", + $type, + $this->getOffline() + ); + } + + $loc_tpl->setCurrentBlock("locator_img"); + $loc_tpl->setVariable("IMG_SRC", $icon_path); + $loc_tpl->setVariable( + "IMG_ALT", + $lng->txt("obj_" . $type) + ); + $loc_tpl->parseCurrentBlock(); + } + + $loc_tpl->setCurrentBlock("locator_item"); + if ($item["link"] != "") { + $loc_tpl->setVariable("LINK_ITEM", $item["link"]); + if ($item["frame"] != "") { + $loc_tpl->setVariable("LINK_TARGET", ' target="' . $item["frame"] . '" '); + } + $loc_tpl->setVariable("ITEM", $item["title"]); + } else { + $loc_tpl->setVariable("PREFIX", $item["title"]); + } + $loc_tpl->parseCurrentBlock(); + + $first = false; + } + } else { + $loc_tpl->setVariable("NOITEM", " "); + $loc_tpl->touchBlock("locator"); + } + $loc_tpl->setVariable("TXT_BREADCRUMBS", $lng->txt("breadcrumb_navigation")); + + return trim($loc_tpl->get()); + } - $str = ""; - if (is_array($items)) - { - foreach($items as $item) - { - if (!$first) - { - $str.= " > "; - } - - $str.= $item["title"]; - - $first = false; - } - } - - return $str; - } + /** + * Get text version + */ + public function getTextVersion() + { + $lng = $this->lng; + $ilSetting = $this->settings; + + $items = $this->getItems(); + $first = true; + $str = ""; + if (is_array($items)) { + foreach ($items as $item) { + if (!$first) { + $str.= " > "; + } + + $str.= $item["title"]; + + $first = false; + } + } + + return $str; + } } // END class.LocatorGUI -?> diff --git a/Services/MediaObjects/classes/class.ilExternalMediaAnalyzer.php b/Services/MediaObjects/classes/class.ilExternalMediaAnalyzer.php index db4a8df34fd29aee6cd8c3a1b2b3ab62bfe16b71..6c59d1ec00bfe6152c6d618eb543c3d00c1dee1b 100755 --- a/Services/MediaObjects/classes/class.ilExternalMediaAnalyzer.php +++ b/Services/MediaObjects/classes/class.ilExternalMediaAnalyzer.php @@ -1,24 +1,24 @@ 0 || - strpos($a_location, "youtu.be") > 0) - { - return true; - } - return false; - } - - /** - * Extract YouTube Parameter - */ - static function extractYouTubeParameters($a_location) - { - $par = array(); - $pos1 = strpos($a_location, "v="); - $pos2 = strpos($a_location, "&", $pos1); - if ($pos1 > 0) - { - $len = ($pos2 > 0) - ? $pos2 - : strlen($a_location); - $par["v"] = substr($a_location, $pos1+2, $len - ($pos1+2)); - } - else if (strpos($a_location, "youtu.be") > 0) - { - $par["v"] = substr($a_location, strrpos($a_location, "/") + 1); - } + /** + * Identify YouTube links + */ + public static function isYouTube($a_location) + { + if (strpos($a_location, "youtube.com") > 0 || + strpos($a_location, "youtu.be") > 0) { + return true; + } + return false; + } + + /** + * Extract YouTube Parameter + */ + public static function extractYouTubeParameters($a_location) + { + $par = array(); + $pos1 = strpos($a_location, "v="); + $pos2 = strpos($a_location, "&", $pos1); + if ($pos1 > 0) { + $len = ($pos2 > 0) + ? $pos2 + : strlen($a_location); + $par["v"] = substr($a_location, $pos1+2, $len - ($pos1+2)); + } elseif (strpos($a_location, "youtu.be") > 0) { + $par["v"] = substr($a_location, strrpos($a_location, "/") + 1); + } - return $par; - } + return $par; + } - /** - * Identify Flickr links - */ - static function isFlickr($a_location) - { - if (strpos($a_location, "flickr.com") > 0) - { - return true; - } - return false; - } + /** + * Identify Flickr links + */ + public static function isFlickr($a_location) + { + if (strpos($a_location, "flickr.com") > 0) { + return true; + } + return false; + } - /** - * Extract Flickr Parameter - */ - static function extractFlickrParameters($a_location) - { - $par = array(); - $pos1 = strpos($a_location, "flickr.com/photos/"); - $pos2 = strpos($a_location, "/", $pos1+18); - if ($pos1 > 0) - { - $len = ($pos2 > 0) - ? $pos2 - : $a_location; - $par["user_id"] = substr($a_location, $pos1+18, $len - ($pos1+18)); - } - - // tags - $pos1 = strpos($a_location, "/tags/"); - $pos2 = strpos($a_location, "/", $pos1+6); - if ($pos1 > 0) - { - $len = ($pos2 > 0) - ? $pos2 - : strlen($a_location); - $par["tags"] = substr($a_location, $pos1+6, $len - ($pos1+6)); - } + /** + * Extract Flickr Parameter + */ + public static function extractFlickrParameters($a_location) + { + $par = array(); + $pos1 = strpos($a_location, "flickr.com/photos/"); + $pos2 = strpos($a_location, "/", $pos1+18); + if ($pos1 > 0) { + $len = ($pos2 > 0) + ? $pos2 + : $a_location; + $par["user_id"] = substr($a_location, $pos1+18, $len - ($pos1+18)); + } + + // tags + $pos1 = strpos($a_location, "/tags/"); + $pos2 = strpos($a_location, "/", $pos1+6); + if ($pos1 > 0) { + $len = ($pos2 > 0) + ? $pos2 + : strlen($a_location); + $par["tags"] = substr($a_location, $pos1+6, $len - ($pos1+6)); + } - // sets - $pos1 = strpos($a_location, "/sets/"); - $pos2 = strpos($a_location, "/", $pos1+6); - if ($pos1 > 0) - { - $len = ($pos2 > 0) - ? $pos2 - : $a_location; - $par["sets"] = substr($a_location, $pos1+6, $len - ($pos1+6)); - } + // sets + $pos1 = strpos($a_location, "/sets/"); + $pos2 = strpos($a_location, "/", $pos1+6); + if ($pos1 > 0) { + $len = ($pos2 > 0) + ? $pos2 + : $a_location; + $par["sets"] = substr($a_location, $pos1+6, $len - ($pos1+6)); + } - return $par; - } + return $par; + } - /** - * Identify GoogleVideo links - */ - static function isGoogleVideo($a_location) - { - if (strpos($a_location, "video.google") > 0) - { - return true; - } - return false; - } - - /** - * Extract GoogleVideo Parameter - */ - static function extractGoogleVideoParameters($a_location) - { - $par = array(); - $pos1 = strpos($a_location, "docid="); - $pos2 = strpos($a_location, "&", $pos1 + 6); - if ($pos1 > 0) - { - $len = ($pos2 > 0) - ? $pos2 - : strlen($a_location); - $par["docid"] = substr($a_location, $pos1+6, $len - ($pos1+6)); - } + /** + * Identify GoogleVideo links + */ + public static function isGoogleVideo($a_location) + { + if (strpos($a_location, "video.google") > 0) { + return true; + } + return false; + } + + /** + * Extract GoogleVideo Parameter + */ + public static function extractGoogleVideoParameters($a_location) + { + $par = array(); + $pos1 = strpos($a_location, "docid="); + $pos2 = strpos($a_location, "&", $pos1 + 6); + if ($pos1 > 0) { + $len = ($pos2 > 0) + ? $pos2 + : strlen($a_location); + $par["docid"] = substr($a_location, $pos1+6, $len - ($pos1+6)); + } - return $par; - } + return $par; + } - /** - * Identify Vimeo links - */ - static function isVimeo($a_location) - { - if (strpos($a_location, "vimeo.com") > 0) - { - return true; - } - return false; - } + /** + * Identify Vimeo links + */ + public static function isVimeo($a_location) + { + if (strpos($a_location, "vimeo.com") > 0) { + return true; + } + return false; + } - /** - * Extract Vimeo Parameter - */ - static function extractVimeoParameters($a_location) - { - $par = array(); - $pos1 = strpos($a_location, "vimeo.com/"); - $pos2 = strpos($a_location, "&", $pos1 + 10); - if ($pos1 > 0) - { - $len = ($pos2 > 0) - ? $pos2 - : strlen($a_location); - $par["id"] = substr($a_location, $pos1+10, $len - ($pos1+10)); - } + /** + * Extract Vimeo Parameter + */ + public static function extractVimeoParameters($a_location) + { + $par = array(); + $pos1 = strpos($a_location, "vimeo.com/"); + $pos2 = strpos($a_location, "&", $pos1 + 10); + if ($pos1 > 0) { + $len = ($pos2 > 0) + ? $pos2 + : strlen($a_location); + $par["id"] = substr($a_location, $pos1+10, $len - ($pos1+10)); + } - return $par; - } + return $par; + } - /** - * Identify Google Document links - */ - static function isGoogleDocument($a_location) - { - if (strpos($a_location, "docs.google") > 0) - { - return true; - } - return false; - } - - /** - * Extract GoogleDocument Parameter - */ - static function extractGoogleDocumentParameters($a_location) - { - $par = array(); - $pos1 = strpos($a_location, "id="); - $pos2 = strpos($a_location, "&", $pos1 + 3); - if ($pos1 > 0) - { - $len = ($pos2 > 0) - ? $pos2 - : strlen($a_location); - $par["docid"] = substr($a_location, $pos1+3, $len - ($pos1+3)); - } - $pos1 = strpos($a_location, "docID="); - $pos2 = strpos($a_location, "&", $pos1 + 6); - if ($pos1 > 0) - { - $len = ($pos2 > 0) - ? $pos2 - : strlen($a_location); - $par["docid"] = substr($a_location, $pos1+6, $len - ($pos1+6)); - } - if (strpos($a_location, "Presentation?") > 0) - { - $par["type"] = "Presentation"; - } - if (strpos($a_location, "View?") > 0) - { - $par["type"] = "Document"; - } + /** + * Identify Google Document links + */ + public static function isGoogleDocument($a_location) + { + if (strpos($a_location, "docs.google") > 0) { + return true; + } + return false; + } + + /** + * Extract GoogleDocument Parameter + */ + public static function extractGoogleDocumentParameters($a_location) + { + $par = array(); + $pos1 = strpos($a_location, "id="); + $pos2 = strpos($a_location, "&", $pos1 + 3); + if ($pos1 > 0) { + $len = ($pos2 > 0) + ? $pos2 + : strlen($a_location); + $par["docid"] = substr($a_location, $pos1+3, $len - ($pos1+3)); + } + $pos1 = strpos($a_location, "docID="); + $pos2 = strpos($a_location, "&", $pos1 + 6); + if ($pos1 > 0) { + $len = ($pos2 > 0) + ? $pos2 + : strlen($a_location); + $par["docid"] = substr($a_location, $pos1+6, $len - ($pos1+6)); + } + if (strpos($a_location, "Presentation?") > 0) { + $par["type"] = "Presentation"; + } + if (strpos($a_location, "View?") > 0) { + $par["type"] = "Document"; + } - return $par; - } - - /** - * Extract URL information to parameter array - */ - static function extractUrlParameters($a_location, $a_parameter) - { - if (!is_array($a_parameter)) - { - $a_parameter = array(); - } - - $ext_par = array(); - - // YouTube - if (ilExternalMediaAnalyzer::isYouTube($a_location)) - { - $ext_par = ilExternalMediaAnalyzer::extractYouTubeParameters($a_location); - $a_parameter = array(); - } + return $par; + } + + /** + * Extract URL information to parameter array + */ + public static function extractUrlParameters($a_location, $a_parameter) + { + if (!is_array($a_parameter)) { + $a_parameter = array(); + } + + $ext_par = array(); + + // YouTube + if (ilExternalMediaAnalyzer::isYouTube($a_location)) { + $ext_par = ilExternalMediaAnalyzer::extractYouTubeParameters($a_location); + $a_parameter = array(); + } - // Flickr - if (ilExternalMediaAnalyzer::isFlickr($a_location)) - { - $ext_par = ilExternalMediaAnalyzer::extractFlickrParameters($a_location); - $a_parameter = array(); - } + // Flickr + if (ilExternalMediaAnalyzer::isFlickr($a_location)) { + $ext_par = ilExternalMediaAnalyzer::extractFlickrParameters($a_location); + $a_parameter = array(); + } - // GoogleVideo - if (ilExternalMediaAnalyzer::isGoogleVideo($a_location)) - { - $ext_par = ilExternalMediaAnalyzer::extractGoogleVideoParameters($a_location); - $a_parameter = array(); - } + // GoogleVideo + if (ilExternalMediaAnalyzer::isGoogleVideo($a_location)) { + $ext_par = ilExternalMediaAnalyzer::extractGoogleVideoParameters($a_location); + $a_parameter = array(); + } - // GoogleDocs - if (ilExternalMediaAnalyzer::isGoogleDocument($a_location)) - { - $ext_par = ilExternalMediaAnalyzer::extractGoogleDocumentParameters($a_location); - $a_parameter = array(); - } + // GoogleDocs + if (ilExternalMediaAnalyzer::isGoogleDocument($a_location)) { + $ext_par = ilExternalMediaAnalyzer::extractGoogleDocumentParameters($a_location); + $a_parameter = array(); + } - foreach($ext_par as $name => $value) - { - $a_parameter[$name] = $value; - } + foreach ($ext_par as $name => $value) { + $a_parameter[$name] = $value; + } - return $a_parameter; - } + return $a_parameter; + } } -?> diff --git a/Services/MediaObjects/classes/class.ilFFmpeg.php b/Services/MediaObjects/classes/class.ilFFmpeg.php index 8d46efb7f4c567bd8d8d9d6c2446d5c03365873e..43f015c821a75f36ecc129e9ace817e6b971bcfe 100644 --- a/Services/MediaObjects/classes/class.ilFFmpeg.php +++ b/Services/MediaObjects/classes/class.ilFFmpeg.php @@ -3,7 +3,7 @@ /* Copyright (c) 1998-2012 ILIAS open source, Extended GPL, see docs/LICENSE */ /** - * FFmpeg wrapper + * FFmpeg wrapper * * @author Alex Killing * @version $Id$ @@ -11,287 +11,271 @@ */ class ilFFmpeg { - /** - * Formats handled by ILIAS. Note: In general the mime types - * do not reflect the complexity of media container/codec variants. - * For source formats no specification is needed here. For target formats - * we use fixed parameters that should result in best web media practice. - */ - static $formats = array( - "video/3pgg" => array( - "source" => true, - "target" => false - ), - "video/x-flv" => array( - "source" => true, - "target" => false - ), - "video/mp4" => array( - "source" => true, - "target" => true, - "parameters" => "-vcodec libx264 -strict experimental -acodec aac -sameq -ab 56k -ar 48000", - "suffix" => "mp4" - ), - "video/webm" => array( - "source" => true, - "target" => true, - "parameters" => "-strict experimental -vcodec libvpx -acodec vorbis -ac 2 -sameq -ab 56k -ar 48000", - "suffix" => "webm" - ) - ); - - static $last_return = array(); - - /** - * Checks, whether FFmpeg support is enabled (path is set in the setup) - * - * @param - * @return - */ - static function enabled() - { - if (defined("PATH_TO_FFMPEG") && PATH_TO_FFMPEG != "") - { - return true; - } - return false; - } - - /** - * Get target mime types - * - * (Please note, that we do not list all possible encoders here, - * only the ones that are desired for the use in ILIAS) - * - * @param - * @return - */ - static function getTargetMimeTypes() - { - $ttypes = array(); - foreach (self::$formats as $k => $f) - { - if ($f["target"] == true) - { - $ttypes[] = $k; - } - } - return $ttypes; - } - - /** - * Get source mime types - * - * @param - * @return - */ - static function getSourceMimeTypes() - { - $ttypes = array(); - foreach (self::$formats as $k => $f) - { - if ($f["source"] == true) - { - $ttypes[] = $k; - } - } - return $ttypes; - } - - /** - * Check if mime type supports image extraction - * - * @param string $a_mime mime type - */ - static function supportsImageExtraction($a_mime) - { - if (in_array($a_mime, self::getSourceMimeTypes())) - { - return true; - } - return false; - } - - /** - * Get possible target formats - * - * @param - * @return - */ - static function getPossibleTargetMimeTypes($a_source_mime_type) - { - $pt = array(); - if (in_array($a_source_mime_type, self::getSourceMimeTypes())) - { - foreach (self::getTargetMimeTypes() as $tm) - { - if ($tm != $a_source_mime_type) - { - $pt[$tm] = $tm; - } - } - } - return $pt; - } - - - /** - * Get ffmpeg command - */ - private static function getCmd() - { - return PATH_TO_FFMPEG; - } + /** + * Formats handled by ILIAS. Note: In general the mime types + * do not reflect the complexity of media container/codec variants. + * For source formats no specification is needed here. For target formats + * we use fixed parameters that should result in best web media practice. + */ + public static $formats = array( + "video/3pgg" => array( + "source" => true, + "target" => false + ), + "video/x-flv" => array( + "source" => true, + "target" => false + ), + "video/mp4" => array( + "source" => true, + "target" => true, + "parameters" => "-vcodec libx264 -strict experimental -acodec aac -sameq -ab 56k -ar 48000", + "suffix" => "mp4" + ), + "video/webm" => array( + "source" => true, + "target" => true, + "parameters" => "-strict experimental -vcodec libvpx -acodec vorbis -ac 2 -sameq -ab 56k -ar 48000", + "suffix" => "webm" + ) + ); + + public static $last_return = array(); + + /** + * Checks, whether FFmpeg support is enabled (path is set in the setup) + * + * @param + * @return + */ + public static function enabled() + { + if (defined("PATH_TO_FFMPEG") && PATH_TO_FFMPEG != "") { + return true; + } + return false; + } + + /** + * Get target mime types + * + * (Please note, that we do not list all possible encoders here, + * only the ones that are desired for the use in ILIAS) + * + * @param + * @return + */ + public static function getTargetMimeTypes() + { + $ttypes = array(); + foreach (self::$formats as $k => $f) { + if ($f["target"] == true) { + $ttypes[] = $k; + } + } + return $ttypes; + } + + /** + * Get source mime types + * + * @param + * @return + */ + public static function getSourceMimeTypes() + { + $ttypes = array(); + foreach (self::$formats as $k => $f) { + if ($f["source"] == true) { + $ttypes[] = $k; + } + } + return $ttypes; + } + + /** + * Check if mime type supports image extraction + * + * @param string $a_mime mime type + */ + public static function supportsImageExtraction($a_mime) + { + if (in_array($a_mime, self::getSourceMimeTypes())) { + return true; + } + return false; + } + + /** + * Get possible target formats + * + * @param + * @return + */ + public static function getPossibleTargetMimeTypes($a_source_mime_type) + { + $pt = array(); + if (in_array($a_source_mime_type, self::getSourceMimeTypes())) { + foreach (self::getTargetMimeTypes() as $tm) { + if ($tm != $a_source_mime_type) { + $pt[$tm] = $tm; + } + } + } + return $pt; + } + + + /** + * Get ffmpeg command + */ + private static function getCmd() + { + return PATH_TO_FFMPEG; + } - /** - * Execute ffmpeg - * - * @param - * @return - */ - static function exec($args) - { - return ilUtil::execQuoted(self::getCmd(), $args); - } - - /** - * Get all supported codecs - * - * @return - */ - static function getSupportedCodecsInfo() - { - $codecs = self::exec("-codecs"); - - return $codecs; - } + /** + * Execute ffmpeg + * + * @param + * @return + */ + public static function exec($args) + { + return ilUtil::execQuoted(self::getCmd(), $args); + } + + /** + * Get all supported codecs + * + * @return + */ + public static function getSupportedCodecsInfo() + { + $codecs = self::exec("-codecs"); + + return $codecs; + } - /** - * Get all supported formats - * - * @return - */ - static function getSupportedFormatsInfo() - { - $formats = self::exec("-formats"); - - return $formats; - } - - /** - * Get file info - * - * @param - * @return - */ - function getFileInfo() - { - //$info = `ffmpeg -i $path$file 2>&1 /dev/null`; - //@fields = split(/\n/, $info); - } - - /** - * Convert file to target mime type - * - * @param string $a_file source file (full path included) - * @param string $a_target_mime target mime type - * @param string $a_target_dir target directory (no trailing "/") - * @param string $a_target_filename target file name (no path!) - * - * @return string new file (full path) - */ - static function convert($a_file, $a_target_mime, $a_target_dir = "", $a_target_filename = "") - { - return; // currently not supported + /** + * Get all supported formats + * + * @return + */ + public static function getSupportedFormatsInfo() + { + $formats = self::exec("-formats"); + + return $formats; + } + + /** + * Get file info + * + * @param + * @return + */ + public function getFileInfo() + { + //$info = `ffmpeg -i $path$file 2>&1 /dev/null`; + //@fields = split(/\n/, $info); + } + + /** + * Convert file to target mime type + * + * @param string $a_file source file (full path included) + * @param string $a_target_mime target mime type + * @param string $a_target_dir target directory (no trailing "/") + * @param string $a_target_filename target file name (no path!) + * + * @return string new file (full path) + */ + public static function convert($a_file, $a_target_mime, $a_target_dir = "", $a_target_filename = "") + { + return; // currently not supported - if (self::$formats[$a_target_mime]["target"] != true) - { - include_once("./Services/MediaObjects/exceptions/class.ilFFmpegException.php"); - throw new ilFFmpegException("Format ".$a_target_mime." is not supported"); - } - $pars = self::$formats[$a_target_mime]["parameters"]; - $spi = pathinfo($a_file); - - // use source directory if no target directory is passed - $target_dir = ($a_target_dir != "") - ? $a_target_dir - : $spi['dirname']; - - // use source filename if no target filename is passed - $target_filename = ($a_target_filename != "") - ? $a_target_filename - : $spi['filename'].".".self::$formats[$a_target_mime]["suffix"]; - - $target_file = $target_dir."/".$target_filename; - - $cmd = "-y -i ".ilUtil::escapeShellArg($a_file)." ".$pars." ".ilUtil::escapeShellArg($target_file); + if (self::$formats[$a_target_mime]["target"] != true) { + include_once("./Services/MediaObjects/exceptions/class.ilFFmpegException.php"); + throw new ilFFmpegException("Format " . $a_target_mime . " is not supported"); + } + $pars = self::$formats[$a_target_mime]["parameters"]; + $spi = pathinfo($a_file); + + // use source directory if no target directory is passed + $target_dir = ($a_target_dir != "") + ? $a_target_dir + : $spi['dirname']; + + // use source filename if no target filename is passed + $target_filename = ($a_target_filename != "") + ? $a_target_filename + : $spi['filename'] . "." . self::$formats[$a_target_mime]["suffix"]; + + $target_file = $target_dir . "/" . $target_filename; + + $cmd = "-y -i " . ilUtil::escapeShellArg($a_file) . " " . $pars . " " . ilUtil::escapeShellArg($target_file); - $ret = self::exec($cmd." 2>&1"); - self::$last_return = $ret; - - if (is_file($target_file)) - { - return $target_file; - } - else - { - include_once("./Services/MediaObjects/exceptions/class.ilFFmpegException.php"); - throw new ilFFmpegException("It was not possible to convert file ".basename($a_file)."."); - } - //ffmpeg -i MOV012.3gp -vcodec libx264 -strict experimental -acodec aac -sameq -ab 64k -ar 44100 MOV012.mp4 - } - - /** - * Get last return values - * - * @param - * @return - */ - static function getLastReturnValues() - { - return self::$last_return; - } - - /** - * Extract image from video file - * - * @param string $a_file source file (full path included) - * @param string $a_target_dir target directory (no trailing "/") - * @param string $a_target_filename target file name (no path!) - * - * @return string new file (full path) - */ - static function extractImage($a_file, $a_target_filename, $a_target_dir = "", - $a_sec = 1) - { -//echo "-$a_file-$a_target_filename-$a_target_dir-$a_sec-
                  "; - - $spi = pathinfo($a_file); - - // use source directory if no target directory is passed - $target_dir = ($a_target_dir != "") - ? $a_target_dir - : $spi['dirname']; - - $target_file = $target_dir."/".$a_target_filename; - - $sec = (int) $a_sec; - $cmd = "-y -i ".ilUtil::escapeShellArg($a_file)." -r 1 -f image2 -vframes 1 -ss ".$sec." ".ilUtil::escapeShellArg($target_file); -//echo "-$cmd-"; exit; - $ret = self::exec($cmd." 2>&1"); - self::$last_return = $ret; - - if (is_file($target_file)) - { - return $target_file; - } - else - { - include_once("./Services/MediaObjects/exceptions/class.ilFFmpegException.php"); - throw new ilFFmpegException("It was not possible to extract an image from ".basename($a_file)."."); - } - } + $ret = self::exec($cmd . " 2>&1"); + self::$last_return = $ret; + + if (is_file($target_file)) { + return $target_file; + } else { + include_once("./Services/MediaObjects/exceptions/class.ilFFmpegException.php"); + throw new ilFFmpegException("It was not possible to convert file " . basename($a_file) . "."); + } + //ffmpeg -i MOV012.3gp -vcodec libx264 -strict experimental -acodec aac -sameq -ab 64k -ar 44100 MOV012.mp4 + } + + /** + * Get last return values + * + * @param + * @return + */ + public static function getLastReturnValues() + { + return self::$last_return; + } + + /** + * Extract image from video file + * + * @param string $a_file source file (full path included) + * @param string $a_target_dir target directory (no trailing "/") + * @param string $a_target_filename target file name (no path!) + * + * @return string new file (full path) + */ + public static function extractImage( + $a_file, + $a_target_filename, + $a_target_dir = "", + $a_sec = 1 + ) { + //echo "-$a_file-$a_target_filename-$a_target_dir-$a_sec-
                  "; + $spi = pathinfo($a_file); + + // use source directory if no target directory is passed + $target_dir = ($a_target_dir != "") + ? $a_target_dir + : $spi['dirname']; + + $target_file = $target_dir . "/" . $a_target_filename; + + $sec = (int) $a_sec; + $cmd = "-y -i " . ilUtil::escapeShellArg($a_file) . " -r 1 -f image2 -vframes 1 -ss " . $sec . " " . ilUtil::escapeShellArg($target_file); + //echo "-$cmd-"; exit; + $ret = self::exec($cmd . " 2>&1"); + self::$last_return = $ret; + + if (is_file($target_file)) { + return $target_file; + } else { + include_once("./Services/MediaObjects/exceptions/class.ilFFmpegException.php"); + throw new ilFFmpegException("It was not possible to extract an image from " . basename($a_file) . "."); + } + } } - -?> diff --git a/Services/MediaObjects/classes/class.ilImageMapEditorGUI.php b/Services/MediaObjects/classes/class.ilImageMapEditorGUI.php index 5e14ec6a7f58b1b721df6289886e639431f7c8cf..b8dd947bf52f2a605da6b1f8fbdd508c8e49ae3d 100755 --- a/Services/MediaObjects/classes/class.ilImageMapEditorGUI.php +++ b/Services/MediaObjects/classes/class.ilImageMapEditorGUI.php @@ -13,1200 +13,1134 @@ */ class ilImageMapEditorGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * Constructor - */ - function __construct($a_media_object) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->tpl = $DIC["tpl"]; - $this->lng = $DIC->language(); - $this->toolbar = $DIC->toolbar(); - $this->media_object = $a_media_object; - } - - /** - * Execute current command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd(); - - switch($next_class) - { - case "ilinternallinkgui": - require_once("./Services/Link/classes/class.ilInternalLinkGUI.php"); - $link_gui = new ilInternalLinkGUI("Media_Media", 0); - $link_gui->setSetLinkTargetScript( - $ilCtrl->getLinkTarget($this, - "setInternalLink")); - $link_gui->filterLinkType("File"); - $ret = $ilCtrl->forwardCommand($link_gui); - break; - - default: - require_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); - ilObjMediaObjectGUI::includePresentationJS(); - if (isset($_POST["editImagemapForward"]) || - isset($_POST["editImagemapForward_x"]) || - isset($_POST["editImagemapForward_y"])) - { - $cmd = "editImagemapForward"; - } - $ret = $this->$cmd(); - break; - } - - return $ret; - } - - /** - * Show map areas - */ - function editMapAreas() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilToolbar = $this->toolbar; - - $_SESSION["il_map_edit_target_script"] = $ilCtrl->getLinkTarget($this, "addArea", - "", false, false); - $this->handleMapParameters(); - - $this->tpl = new ilTemplate("tpl.map_edit.html", true, true, "Services/MediaObjects"); - $this->tpl->setVariable("FORMACTION", $ilCtrl->getFormAction($this)); - - // create/update imagemap work copy - $this->makeMapWorkCopy(); - - $output = $this->getImageMapOutput(); - $this->tpl->setVariable("IMAGE_MAP", $output); - - $this->tpl->setVariable("TOOLBAR", $this->getToolbar()->getHTML()); - - // table - $this->tpl->setVariable("MAP_AREA_TABLE", $this->getImageMapTableHTML()); - - return $this->tpl->get(); - } - - /** - * Get toolbar - * - * @return object toolbar - */ - function getToolbar() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - - // toolbar - $tb = new ilToolbarGUI(); - $tb->setFormAction($ilCtrl->getFormAction($this)); - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $options = array( - "WholePicture" => $lng->txt("cont_WholePicture"), - "Rect" => $lng->txt("cont_Rect"), - "Circle" => $lng->txt("cont_Circle"), - "Poly" => $lng->txt("cont_Poly"), - ); - $si = new ilSelectInputGUI($lng->txt("cont_shape"), "shape"); - $si->setOptions($options); - $tb->addInputItem($si, true); - $tb->addFormButton($lng->txt("cont_add_area"), "addNewArea"); - - - // highlight mode -/* if (strtolower(get_class($this)) == "ilimagemapeditorgui") - { - $st_item = $this->media_object->getMediaItem("Standard"); - $tb->addSeparator(); - $options = ilMapArea::getAllHighlightModes(); - $hl = new ilSelectInputGUI($lng->txt("cont_highlight_mode"), "highlight_mode"); - $hl->setOptions($options); -// $hl->setValue($st_item->getHighlightMode()); - $tb->addInputItem($hl, true); - $options = ilMapArea::getAllHighlightClasses(); - $hc = new ilSelectInputGUI($lng->txt("cont_highlight_class"), "highlight_class"); - $hc->setOptions($options); -// $hc->setValue($st_item->getHighlightClass()); - $tb->addInputItem($hc, false); - $tb->addFormButton($lng->txt("cont_set"), "setHighlight"); - }*/ - - return $tb; - } - - - /** - * Get editor title - * - * @return string editor title - */ - function getEditorTitle() - { - $lng = $this->lng; - - return $lng->txt("cont_imagemap"); - } - - - /** - * Get table HTML - */ - function getImageMapTableHTML() - { - include_once("./Services/MediaObjects/classes/class.ilImageMapTableGUI.php"); - $image_map_table = new ilImageMapTableGUI($this, "editMapAreas", $this->media_object); - return $image_map_table->getHTML(); - } - - /** - * handle parameter during map area editing (storing to session) - */ - function handleMapParameters() - { - if($_GET["ref_id"] != "") - { - $_SESSION["il_map_edit_ref_id"] = $_GET["ref_id"]; - } - - if($_GET["obj_id"] != "") - { - $_SESSION["il_map_edit_obj_id"] = $_GET["obj_id"]; - } - - if($_GET["hier_id"] != "") - { - $_SESSION["il_map_edit_hier_id"] = $_GET["hier_id"]; - } - - if($_GET["pc_id"] != "") - { - $_SESSION["il_map_edit_pc_id"] = $_GET["pc_id"]; - } - } - - /** - * show image map - */ - function showImageMap() - { - $item = new ilMediaItem($_GET["item_id"]); - $item->outputMapWorkCopy(); - } - - /** - * Update map areas - */ - function updateAreas() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $st_item = $this->media_object->getMediaItem("Standard"); - $max = ilMapArea::_getMaxNr($st_item->getId()); - for ($i=1; $i<=$max; $i++) - { - $area = new ilMapArea($st_item->getId(), $i); - $area->setTitle(ilUtil::stripSlashes($_POST["name_".$i])); - $area->setHighlightMode(ilUtil::stripSlashes($_POST["hl_mode_".$i])); - $area->setHighlightClass(ilUtil::stripSlashes($_POST["hl_class_".$i])); - $area->update(); - } - - ilUtil::sendSuccess($lng->txt("cont_saved_map_data"), true); - $ilCtrl->redirect($this, "editMapAreas"); - } - - /** - * Add area - */ - function addNewArea() - { - switch ($_POST["shape"]) - { - case "WholePicture": return $this->linkWholePicture(); - case "Rect": return $this->addRectangle(); - case "Circle": return $this->addCircle(); - case "Poly": return $this->addPolygon(); - } - } - - - /** - * Link the whole picture - */ - function linkWholePicture() - { - $this->clearSessionVars(); - $_SESSION["il_map_edit_area_type"] = "WholePicture"; - - return $this->editMapArea(false, false, true); - } - - /** - * Add a new rectangle - */ - function addRectangle() - { - $this->clearSessionVars(); - $_SESSION["il_map_edit_area_type"] = "Rect"; - return $this->addArea(false); - } - - /** - * Add a new circle - */ - function addCircle() - { - $this->clearSessionVars(); - $_SESSION["il_map_edit_area_type"] = "Circle"; - return $this->addArea(false); - } - - /** - * Add a new polygon - */ - function addPolygon() - { - $this->clearSessionVars(); - $_SESSION["il_map_edit_area_type"] = "Poly"; - return $this->addArea(false); - } - - /** - * Clear Session Vars - */ - function clearSessionVars() - { - $_SESSION["il_map_area_nr"] = ""; - $_SESSION["il_map_edit_coords"] = ""; - $_SESSION["il_map_edit_mode"] = ""; - $_SESSION["il_map_el_href"] = ""; - $_SESSION["il_map_il_type"] = ""; - $_SESSION["il_map_il_ltype"] = ""; - $_SESSION["il_map_il_target"] = ""; - $_SESSION["il_map_il_targetframe"] = ""; - $_SESSION["il_map_edit_area_type"] = ""; - } - - /** - * Handle adding new area process - */ - function addArea($a_handle = true) - { - - // handle map parameters - if($a_handle) - { - $this->handleMapParameters(); - } - - $area_type = $_SESSION["il_map_edit_area_type"]; - $coords = $_SESSION["il_map_edit_coords"]; - include_once("./Services/MediaObjects/classes/class.ilMapArea.php"); - $cnt_coords = ilMapArea::countCoords($coords); - - // decide what to do next - switch ($area_type) - { - // Rectangle - case "Rect" : - if ($cnt_coords < 2) - { - $html = $this->editMapArea(true, false, false); - return $html; - } - else if ($cnt_coords == 2) - { - return $this->editMapArea(false, true, true); - } - break; - - // Circle - case "Circle": - if ($cnt_coords <= 1) - { - return $this->editMapArea(true, false, false); - } - else - { - if ($cnt_coords == 2) - { - $c = explode(",",$coords); - $coords = $c[0].",".$c[1].","; // determine radius - $coords .= round(sqrt(pow(abs($c[3]-$c[1]),2)+pow(abs($c[2]-$c[0]),2))); - } - $_SESSION["il_map_edit_coords"] = $coords; - - return $this->editMapArea(false, true, true); - } - break; - - // Polygon - case "Poly": - if ($cnt_coords < 1) - { - return $this->editMapArea(true, false, false); - } - else if ($cnt_coords < 3) - { - return $this->editMapArea(true, true, false); - } - else - { - return $this->editMapArea(true, true, true); - } - break; - - // Whole picture - case "WholePicture": - return $this->editMapArea(false, false, true); - break; - } - } - - /** - * Edit a single map area - * - * @param boolean $a_get_next_coordinate enable next coordinate input - * @param boolean $a_output_new_area output the new area - * @param boolean $a_save_from output save form - * @param string $a_edit_property "" | "link" | "shape" - */ - function editMapArea($a_get_next_coordinate = false, $a_output_new_area = false, - $a_save_form = false, $a_edit_property = "", $a_area_nr = 0) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - - $area_type = $_SESSION["il_map_edit_area_type"]; - $coords = $_SESSION["il_map_edit_coords"]; - include_once("./Services/MediaObjects/classes/class.ilMapArea.php"); - $cnt_coords = ilMapArea::countCoords($coords); - - $this->tpl = new ilTemplate("tpl.map_edit.html", true, true, "Services/MediaObjects"); - - $this->tpl->setVariable("FORMACTION", $ilCtrl->getFormAction($this)); - - if ($a_edit_property != "link") - { - switch ($area_type) - { - // rectangle - case "Rect" : - if ($cnt_coords == 0) - { - ilUtil::sendInfo($lng->txt("cont_click_tl_corner")); - } - if ($cnt_coords == 1) - { - ilUtil::sendInfo($lng->txt("cont_click_br_corner")); - } - break; - - // circle - case "Circle" : - if ($cnt_coords == 0) - { - ilUtil::sendInfo($lng->txt("cont_click_center")); - } - if ($cnt_coords == 1) - { - ilUtil::sendInfo($lng->txt("cont_click_circle")); - } - break; - - // polygon - case "Poly" : - if ($cnt_coords == 0) - { - ilUtil::sendInfo($lng->txt("cont_click_starting_point")); - } - else if ($cnt_coords < 3) - { - ilUtil::sendInfo($lng->txt("cont_click_next_point")); - } - else - { - ilUtil::sendInfo($lng->txt("cont_click_next_or_save")); - } - break; - } - } - - - // map properties input fields (name and link) - if ($a_save_form) - { - if ($a_edit_property != "shape") - { - // prepare link gui - $ilCtrl->setParameter($this, "linkmode", "map"); - include_once("./Services/Link/classes/class.ilInternalLinkGUI.php"); - $this->tpl->setCurrentBlock("int_link_prep"); - $this->tpl->setVariable("INT_LINK_PREP", ilInternalLinkGUI::getInitHTML( - $ilCtrl->getLinkTargetByClass("ilinternallinkgui", - "", false, true, false))); - $this->tpl->parseCurrentBlock(); - } - $form = $this->initAreaEditingForm($a_edit_property); - $this->tpl->setVariable("FORM", $form->getHTML()); - } - - $this->makeMapWorkCopy($a_edit_property, $a_area_nr, - $a_output_new_area, $area_type, $coords); - - $edit_mode = ($a_get_next_coordinate) - ? "get_coords" - : (($a_output_new_area) - ? "new_area" - :""); - $output = $this->getImageMapOutput($edit_mode); - $this->tpl->setVariable("IMAGE_MAP", $output); - - return $this->tpl->get(); - } - - /** - * Init area editing form. - * - * @param int $a_mode Edit Mode - */ - public function initAreaEditingForm($a_edit_property) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setOpenTag(false); - $form->setCloseTag(false); - - // link - if ($a_edit_property != "shape") - { - // - $radg = new ilRadioGroupInputGUI($lng->txt("cont_link"), "area_link_type"); - if ($_SESSION["il_map_il_ltype"] != "int") - { - if ($_SESSION["il_map_el_href"] == "") - { - $radg->setValue("no"); - } - else - { - $radg->setValue("ext"); - } - } - else - { - $radg->setValue("int"); - } - - // external link - $ext = new ilRadioOption($lng->txt("cont_link_ext"), "ext"); - $radg->addOption($ext); - - $ti = new ilTextInputGUI("", "area_link_ext"); - $ti->setMaxLength(800); - $ti->setSize(50); - if ($_SESSION["il_map_el_href"] != "") - { - $ti->setValue($_SESSION["il_map_el_href"]); - } - else - { - $ti->setValue("http://"); - } - $ext->addSubItem($ti); - - // internal link - $int = new ilRadioOption($lng->txt("cont_link_int"), "int"); - $radg->addOption($int); - - $ne = new ilNonEditableValueGUI("", "", true); - $link_str = ""; - if($_SESSION["il_map_il_target"] != "") - { - $link_str = $this->getMapAreaLinkString($_SESSION["il_map_il_target"], - $_SESSION["il_map_il_type"], $_SESSION["il_map_il_targetframe"]); - } - $ne->setValue($link_str. - ' '. - "[".$lng->txt("cont_get_link")."]". - '' - ); - $int->addSubItem($ne); - - // no link - $no = new ilRadioOption($lng->txt("cont_link_no"), "no"); - $radg->addOption($no); - - $form->addItem($radg); - } - - - // name - if ($a_edit_property != "link" && $a_edit_property != "shape") - { - $ti = new ilTextInputGUI($lng->txt("cont_name"), "area_name"); - $ti->setMaxLength(200); - $ti->setSize(20); - $form->addItem($ti); - } - - // save and cancel commands - if ($a_edit_property == "") - { - $form->setTitle($lng->txt("cont_new_area")); - $form->addCommandButton("saveArea", $lng->txt("save")); - } - else - { - $form->setTitle($lng->txt("cont_new_area")); - $form->addCommandButton("saveArea", $lng->txt("save")); - } - -// $form->setFormAction($ilCtrl->getFormAction($this)); - - return $form; - } - - /** - * Make work file for editing - */ - function makeMapWorkCopy($a_edit_property = "", $a_area_nr = 0, - $a_output_new_area = false, $a_area_type = "", $a_coords = "") - { - // create/update imagemap work copy - $st_item = $this->media_object->getMediaItem("Standard"); - - if ($a_edit_property == "shape") - { - $st_item->makeMapWorkCopy($a_area_nr, true); // exclude area currently being edited - } - else - { - $st_item->makeMapWorkCopy($a_area_nr, false); - } - - if ($a_output_new_area) - { - $st_item->addAreaToMapWorkCopy($a_area_type, $a_coords); - } - } - - /** - * Render the image map. - */ - function getImageMapOutput($a_map_edit_mode = "") - { - $ilCtrl = $this->ctrl; - - $st_item = $this->media_object->getMediaItem("Standard"); - - // output image map - $xml = ""; - $xml.= $this->getAliasXML(); - $xml.= $this->media_object->getXML(IL_MODE_OUTPUT); - $xml.= $this->getAdditionalPageXML(); - $xml.=""; - $xsl = file_get_contents("./Services/COPage/xsl/page.xsl"); -//echo htmlentities($xml); exit; - $args = array( '/_xml' => $xml, '/_xsl' => $xsl ); - $xh = xslt_create(); - $wb_path = ilUtil::getWebspaceDir("output")."/"; - $mode = "media"; -//echo htmlentities($ilCtrl->getLinkTarget($this, "showImageMap")); - $params = array ('map_edit_mode' => $a_map_edit_mode, - 'map_item' => $st_item->getId(), - 'map_mob_id' => $this->media_object->getId(), - 'mode' => $mode, - 'media_mode' => 'enable', - 'image_map_link' => $ilCtrl->getLinkTarget($this, "showImageMap", "", false, false), - 'link_params' => "ref_id=".$_GET["ref_id"]."&rand=".rand(1,999999), - 'ref_id' => $_GET["ref_id"], - 'pg_frame' => "", - 'enlarge_path' => ilUtil::getImagePath("enlarge.svg"), - 'webspace_path' => $wb_path); - $output = xslt_process($xh,"arg:/_xml","arg:/_xsl",NULL,$args, $params); - echo xslt_error($xh); - xslt_free($xh); - - $output = $this->outputPostProcessing($output); - - return $output; - } - - /** - * Get additional page xml (to be overwritten) - * - * @return string additional page xml - */ - function getAdditionalPageXML() - { - return ""; - } - - /** - * Output post processing - * - * @param - * @return - */ - function outputPostProcessing($a_output) - { - return $a_output; - } - - function getAliasXML() - { - return $this->media_object->getXML(IL_MODE_ALIAS); - } - - /** - * Get text name of internal link - * - * @param string $a_target target object link id - * @param string $a_type type - * @param string $a_frame target frame - * - * @access private - */ - function getMapAreaLinkString($a_target, $a_type, $a_frame) - { - $lng = $this->lng; - - $t_arr = explode("_", $a_target); - if ($a_frame != "") - { - $frame_str = " (".$a_frame." Frame)"; - } - switch($a_type) - { - case "StructureObject": - require_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - $title = ilLMObject::_lookupTitle($t_arr[count($t_arr) - 1]); - $link_str = $lng->txt("chapter"). - ": ".$title." [".$t_arr[count($t_arr) - 1]."]".$frame_str; - break; - - case "PageObject": - require_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - $title = ilLMObject::_lookupTitle($t_arr[count($t_arr) - 1]); - $link_str = $lng->txt("page"). - ": ".$title." [".$t_arr[count($t_arr) - 1]."]".$frame_str; - break; - - case "GlossaryItem": - require_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - $term = new ilGlossaryTerm($t_arr[count($t_arr) - 1]); - $link_str = $lng->txt("term"). - ": ".$term->getTerm()." [".$t_arr[count($t_arr) - 1]."]".$frame_str; - break; - - case "MediaObject": - require_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $mob = new ilObjMediaObject($t_arr[count($t_arr) - 1]); - $link_str = $lng->txt("mob"). - ": ".$mob->getTitle()." [".$t_arr[count($t_arr) - 1]."]".$frame_str; - break; - - case "RepositoryItem": - $title = ilObject::_lookupTitle( - ilObject::_lookupObjId($t_arr[count($t_arr) - 1])); - $link_str = $lng->txt("obj_".$t_arr[count($t_arr) - 2]). - ": ".$title." [".$t_arr[count($t_arr) - 1]."]".$frame_str; - break; - } - - return $link_str; - } - - /** - * Get image map coordinates. - */ - function editImagemapForward() - { - ilImageMapEditorGUI::_recoverParameters(); - - if ($_SESSION["il_map_edit_coords"] != "") - { - $_SESSION["il_map_edit_coords"] .= ","; - } - - $_SESSION["il_map_edit_coords"] .= $_POST["editImagemapForward_x"].",". - $_POST["editImagemapForward_y"]; - - // call editing script - ilUtil::redirect($_SESSION["il_map_edit_target_script"]); - } - - /** - * Recover parameters from session variables (static) - */ - static function _recoverParameters() - { - $_GET["ref_id"] = $_SESSION["il_map_edit_ref_id"]; - $_GET["obj_id"] = $_SESSION["il_map_edit_obj_id"]; - $_GET["hier_id"] = $_SESSION["il_map_edit_hier_id"]; - $_GET["pc_id"] = $_SESSION["il_map_edit_pc_id"]; - } - - /** - * Save new or updated map area - */ - function saveArea() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - switch ($_SESSION["il_map_edit_mode"]) - { - // save edited link - case "edit_link": - $st_item = $this->media_object->getMediaItem("Standard"); - $max = ilMapArea::_getMaxNr($st_item->getId()); - $area = new ilMapArea($st_item->getId(), $_SESSION["il_map_area_nr"]); - - if ($_POST["area_link_type"] == IL_INT_LINK) - { - $area->setLinkType(IL_INT_LINK); - $area->setType($_SESSION["il_map_il_type"]); - $area->setTarget($_SESSION["il_map_il_target"]); - $area->setTargetFrame($_SESSION["il_map_il_targetframe"]); - } - else - { - $area->setLinkType(IL_EXT_LINK); - if ($_POST["area_link_type"] != IL_NO_LINK) - { - $area->setHref(ilUtil::stripSlashes($_POST["area_link_ext"])); - } - else - { - $area->setHref(""); - } - } - $area->update(); - break; - - // save edited shape - case "edit_shape": - $st_item = $this->media_object->getMediaItem("Standard"); - $max = ilMapArea::_getMaxNr($st_item->getId()); - $area = new ilMapArea($st_item->getId(), $_SESSION["il_map_area_nr"]); - - $area->setShape($_SESSION["il_map_edit_area_type"]); - $area->setCoords($_SESSION["il_map_edit_coords"]); - $area->update(); - break; - - // save new area - default: - $area_type = $_SESSION["il_map_edit_area_type"]; - $coords = $_SESSION["il_map_edit_coords"]; - - $st_item = $this->media_object->getMediaItem("Standard"); - $max = ilMapArea::_getMaxNr($st_item->getId()); - - // make new area object - $area = new ilMapArea(); - $area->setItemId($st_item->getId()); - $area->setShape($area_type); - $area->setCoords($coords); - $area->setNr($max + 1); - $area->setTitle(ilUtil::stripSlashes($_POST["area_name"])); - switch($_POST["area_link_type"]) - { - case "ext": - $area->setLinkType(IL_EXT_LINK); - $area->setHref($_POST["area_link_ext"]); - break; - - case "int": - $area->setLinkType(IL_INT_LINK); - $area->setType($_SESSION["il_map_il_type"]); - $area->setTarget($_SESSION["il_map_il_target"]); - $area->setTargetFrame($_SESSION["il_map_il_targetframe"]); - break; - } - - // put area into item and update media object - $st_item->addMapArea($area); - $this->media_object->update(); - break; - } - - //$this->initMapParameters(); - ilUtil::sendSuccess($lng->txt("cont_saved_map_area"), true); - $ilCtrl->redirect($this, "editMapAreas"); - } - - /** - * Set internal link - */ - function setInternalLink() - { - $_SESSION["il_map_il_type"] = $_GET["linktype"]; - $_SESSION["il_map_il_ltype"] = "int"; - - $_SESSION["il_map_il_target"] = $_GET["linktarget"]; - $_SESSION["il_map_il_targetframe"] = $_GET["linktargetframe"]; - $_SESSION["il_map_il_anchor"] = $_GET["linkanchor"]; - switch ($_SESSION["il_map_edit_mode"]) - { - case "edit_link": - return $this->setLink(); - break; - - default: - return $this->addArea(); - break; - } - } - - /** - * Set link - */ - function setLink($a_handle = true) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if($a_handle) - { - $this->handleMapParameters(); - } - if ($_SESSION["il_map_area_nr"] != "") - { - $_POST["area"][0] = $_SESSION["il_map_area_nr"]; - } - if (!isset($_POST["area"])) - { - ilUtil::sendFailure($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "editMapAreas"); - } - - if (count($_POST["area"]) > 1) - { - //$this->ilias->raiseError($this->lng->txt("cont_select_max_one_item"),$this->ilias->error_obj->MESSAGE); - ilUtil::sendFailure($lng->txt("cont_select_max_one_item"), true); - $ilCtrl->redirect($this, "editMapAreas"); - } - - - if ($_SESSION["il_map_edit_mode"] != "edit_link") - { - $_SESSION["il_map_area_nr"] = $_POST["area"][0]; - $_SESSION["il_map_il_ltype"] = $this->getLinkTypeOfArea($_POST["area"][0]); - $_SESSION["il_map_edit_mode"] = "edit_link"; - $_SESSION["il_map_edit_target_script"] = $ilCtrl->getLinkTarget($this, "setLink"); - if ($_SESSION["il_map_il_ltype"] == IL_INT_LINK) - { - $_SESSION["il_map_il_type"] = $this->getTypeOfArea($_POST["area"][0]); - $_SESSION["il_map_il_target"] = $this->getTargetOfArea($_POST["area"][0]); - $_SESSION["il_map_il_targetframe"] = $this->getTargetFrameOfArea($_POST["area"][0]); - } - else - { - $_SESSION["il_map_el_href"] = $this->getHrefOfArea($_POST["area"][0]); - } - } - - return $this->editMapArea(false, false, true, "link", $_POST["area"][0]); - } - - /** - * Get Link Type of Area - */ - function getLinkTypeOfArea($a_nr) - { - $st_item = $this->media_object->getMediaItem("Standard"); - $area = $st_item->getMapArea($a_nr); - return $area->getLinkType(); - } - - /** - * Get Type of Area (only internal link) - */ - function getTypeOfArea($a_nr) - { - $st_item = $this->media_object->getMediaItem("Standard"); - $area = $st_item->getMapArea($a_nr); - return $area->getType(); - } - - /** - * Get Target of Area (only internal link) - */ - function getTargetOfArea($a_nr) - { - $st_item = $this->media_object->getMediaItem("Standard"); - $area = $st_item->getMapArea($a_nr); - return $area->getTarget(); - } - - /** - * Get TargetFrame of Area (only internal link) - */ - function getTargetFrameOfArea($a_nr) - { - $st_item = $this->media_object->getMediaItem("Standard"); - $area = $st_item->getMapArea($a_nr); - return $area->getTargetFrame(); - } - - /** - * Get Href of Area (only external link) - */ - function getHrefOfArea($a_nr) - { - $st_item = $this->media_object->getMediaItem("Standard"); - $area = $st_item->getMapArea($a_nr); - return $area->getHref(); - } - - /** - * Delete map areas - */ - function deleteAreas() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if (!isset($_POST["area"])) - { - ilUtil::sendFailure($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "editMapAreas"); - } - - $st_item = $this->media_object->getMediaItem("Standard"); - $max = ilMapArea::_getMaxNr($st_item->getId()); - - if (count($_POST["area"]) > 0) - { - $i = 0; - - foreach ($_POST["area"] as $area_nr) - { - $st_item->deleteMapArea($area_nr - $i); - $i++; - } - - $this->media_object->update(); - ilUtil::sendSuccess($lng->txt("cont_areas_deleted"), true); - } - - $ilCtrl->redirect($this, "editMapAreas"); - } - - /** - * Edit existing link - */ - function editLink() - { - $_SESSION["il_map_edit_coords"] = ""; - $_SESSION["il_map_edit_mode"] = ""; - $_SESSION["il_map_el_href"] = ""; - $_SESSION["il_map_il_type"] = ""; - $_SESSION["il_map_il_ltype"] = ""; - $_SESSION["il_map_il_target"] = ""; - $_SESSION["il_map_il_targetframe"] = ""; - $_SESSION["il_map_area_nr"] = ""; - return $this->setLink(false); - } - - /** - * Edit an existing shape (make it a whole picture link) - */ - function editShapeWholePicture() - { - $this->clearSessionVars(); - $_SESSION["il_map_edit_area_type"] = "WholePicture"; - return $this->setShape(false); - } - - /** - * Edit an existing shape (make it a rectangle) - */ - function editShapeRectangle() - { - $this->clearSessionVars(); - $_SESSION["il_map_edit_area_type"] = "Rect"; - return $this->setShape(false); - } - - /** - * Edit an existing shape (make it a circle) - */ - function editShapeCircle() - { - $this->clearSessionVars(); - $_SESSION["il_map_edit_area_type"] = "Circle"; - return $this->setShape(false); - } - - /** - * Edit an existing shape (make it a polygon) - */ - function editShapePolygon() - { - $this->clearSessionVars(); - $_SESSION["il_map_edit_area_type"] = "Poly"; - return $this->setShape(false); - } - - /** - * edit shape of existing map area - */ - function setShape($a_handle = true) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if($a_handle) - { - $this->handleMapParameters(); - } - if($_POST["areatype2"] != "") - { - $_SESSION["il_map_edit_area_type"] = $_POST["areatype2"]; - } - if ($_SESSION["il_map_area_nr"] != "") - { - $_POST["area"][0] = $_SESSION["il_map_area_nr"]; - } - if (!isset($_POST["area"])) - { - ilUtil::sendFailure($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "editMapAreas"); - } - - if (count($_POST["area"]) > 1) - { - ilUtil::sendFailure($lng->txt("cont_select_max_one_item"), true); - $ilCtrl->redirect($this, "editMapAreas"); - } - - if ($_SESSION["il_map_edit_mode"] != "edit_shape") - { - $_SESSION["il_map_area_nr"] = $_POST["area"][0]; - $_SESSION["il_map_edit_mode"] = "edit_shape"; - $_SESSION["il_map_edit_target_script"] = $ilCtrl->getLinkTarget($this, "setShape", "", false, false); - } - - - $area_type = $_SESSION["il_map_edit_area_type"]; - $coords = $_SESSION["il_map_edit_coords"]; - $cnt_coords = ilMapArea::countCoords($coords); - - // decide what to do next - switch ($area_type) - { - // Rectangle - case "Rect" : - if ($cnt_coords < 2) - { - return $this->editMapArea(true, false, false, "shape", $_POST["area"][0]); - } - else if ($cnt_coords == 2) - { - return $this->saveArea(); - } - break; - - // Circle - case "Circle": - if ($cnt_coords <= 1) - { - return $this->editMapArea(true, false, false, "shape", $_POST["area"][0]); - } - else - { - if ($cnt_coords == 2) - { - $c = explode(",",$coords); - $coords = $c[0].",".$c[1].","; // determine radius - $coords .= round(sqrt(pow(abs($c[3]-$c[1]),2)+pow(abs($c[2]-$c[0]),2))); - } - $_SESSION["il_map_edit_coords"] = $coords; - - return $this->saveArea(); - } - break; - - // Polygon - case "Poly": - if ($cnt_coords < 1) - { - return $this->editMapArea(true, false, false, "shape", $_POST["area"][0]); - } - else if ($cnt_coords < 3) - { - return $this->editMapArea(true, true, false, "shape", $_POST["area"][0]); - } - else - { - return $this->editMapArea(true, true, true, "shape", $_POST["area"][0]); - } - break; - - // Whole Picture - case "WholePicture": - return $this->saveArea(); - } - - } - - /** - * Set highlight settings - * - * @param - * @return - */ - function setHighlight() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $st_item = $this->media_object->getMediaItem("Standard"); - $st_item->setHighlightMode(ilUtil::stripSlashes($_POST["highlight_mode"])); - $st_item->setHighlightClass(ilUtil::stripSlashes($_POST["highlight_class"])); - $st_item->update(); - - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "editMapAreas"); - } + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * Constructor + */ + public function __construct($a_media_object) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->tpl = $DIC["tpl"]; + $this->lng = $DIC->language(); + $this->toolbar = $DIC->toolbar(); + $this->media_object = $a_media_object; + } + + /** + * Execute current command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd(); + + switch ($next_class) { + case "ilinternallinkgui": + require_once("./Services/Link/classes/class.ilInternalLinkGUI.php"); + $link_gui = new ilInternalLinkGUI("Media_Media", 0); + $link_gui->setSetLinkTargetScript( + $ilCtrl->getLinkTarget( + $this, + "setInternalLink" + ) + ); + $link_gui->filterLinkType("File"); + $ret = $ilCtrl->forwardCommand($link_gui); + break; + + default: + require_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); + ilObjMediaObjectGUI::includePresentationJS(); + if (isset($_POST["editImagemapForward"]) || + isset($_POST["editImagemapForward_x"]) || + isset($_POST["editImagemapForward_y"])) { + $cmd = "editImagemapForward"; + } + $ret = $this->$cmd(); + break; + } + + return $ret; + } + + /** + * Show map areas + */ + public function editMapAreas() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilToolbar = $this->toolbar; + + $_SESSION["il_map_edit_target_script"] = $ilCtrl->getLinkTarget( + $this, + "addArea", + "", + false, + false + ); + $this->handleMapParameters(); + + $this->tpl = new ilTemplate("tpl.map_edit.html", true, true, "Services/MediaObjects"); + $this->tpl->setVariable("FORMACTION", $ilCtrl->getFormAction($this)); + + // create/update imagemap work copy + $this->makeMapWorkCopy(); + + $output = $this->getImageMapOutput(); + $this->tpl->setVariable("IMAGE_MAP", $output); + + $this->tpl->setVariable("TOOLBAR", $this->getToolbar()->getHTML()); + + // table + $this->tpl->setVariable("MAP_AREA_TABLE", $this->getImageMapTableHTML()); + + return $this->tpl->get(); + } + + /** + * Get toolbar + * + * @return object toolbar + */ + public function getToolbar() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + + // toolbar + $tb = new ilToolbarGUI(); + $tb->setFormAction($ilCtrl->getFormAction($this)); + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $options = array( + "WholePicture" => $lng->txt("cont_WholePicture"), + "Rect" => $lng->txt("cont_Rect"), + "Circle" => $lng->txt("cont_Circle"), + "Poly" => $lng->txt("cont_Poly"), + ); + $si = new ilSelectInputGUI($lng->txt("cont_shape"), "shape"); + $si->setOptions($options); + $tb->addInputItem($si, true); + $tb->addFormButton($lng->txt("cont_add_area"), "addNewArea"); + + + // highlight mode + /* if (strtolower(get_class($this)) == "ilimagemapeditorgui") + { + $st_item = $this->media_object->getMediaItem("Standard"); + $tb->addSeparator(); + $options = ilMapArea::getAllHighlightModes(); + $hl = new ilSelectInputGUI($lng->txt("cont_highlight_mode"), "highlight_mode"); + $hl->setOptions($options); + // $hl->setValue($st_item->getHighlightMode()); + $tb->addInputItem($hl, true); + $options = ilMapArea::getAllHighlightClasses(); + $hc = new ilSelectInputGUI($lng->txt("cont_highlight_class"), "highlight_class"); + $hc->setOptions($options); + // $hc->setValue($st_item->getHighlightClass()); + $tb->addInputItem($hc, false); + $tb->addFormButton($lng->txt("cont_set"), "setHighlight"); + }*/ + + return $tb; + } + + + /** + * Get editor title + * + * @return string editor title + */ + public function getEditorTitle() + { + $lng = $this->lng; + + return $lng->txt("cont_imagemap"); + } + + + /** + * Get table HTML + */ + public function getImageMapTableHTML() + { + include_once("./Services/MediaObjects/classes/class.ilImageMapTableGUI.php"); + $image_map_table = new ilImageMapTableGUI($this, "editMapAreas", $this->media_object); + return $image_map_table->getHTML(); + } + + /** + * handle parameter during map area editing (storing to session) + */ + public function handleMapParameters() + { + if ($_GET["ref_id"] != "") { + $_SESSION["il_map_edit_ref_id"] = $_GET["ref_id"]; + } + + if ($_GET["obj_id"] != "") { + $_SESSION["il_map_edit_obj_id"] = $_GET["obj_id"]; + } + + if ($_GET["hier_id"] != "") { + $_SESSION["il_map_edit_hier_id"] = $_GET["hier_id"]; + } + + if ($_GET["pc_id"] != "") { + $_SESSION["il_map_edit_pc_id"] = $_GET["pc_id"]; + } + } + + /** + * show image map + */ + public function showImageMap() + { + $item = new ilMediaItem($_GET["item_id"]); + $item->outputMapWorkCopy(); + } + + /** + * Update map areas + */ + public function updateAreas() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $st_item = $this->media_object->getMediaItem("Standard"); + $max = ilMapArea::_getMaxNr($st_item->getId()); + for ($i=1; $i<=$max; $i++) { + $area = new ilMapArea($st_item->getId(), $i); + $area->setTitle(ilUtil::stripSlashes($_POST["name_" . $i])); + $area->setHighlightMode(ilUtil::stripSlashes($_POST["hl_mode_" . $i])); + $area->setHighlightClass(ilUtil::stripSlashes($_POST["hl_class_" . $i])); + $area->update(); + } + + ilUtil::sendSuccess($lng->txt("cont_saved_map_data"), true); + $ilCtrl->redirect($this, "editMapAreas"); + } + + /** + * Add area + */ + public function addNewArea() + { + switch ($_POST["shape"]) { + case "WholePicture": return $this->linkWholePicture(); + case "Rect": return $this->addRectangle(); + case "Circle": return $this->addCircle(); + case "Poly": return $this->addPolygon(); + } + } + + + /** + * Link the whole picture + */ + public function linkWholePicture() + { + $this->clearSessionVars(); + $_SESSION["il_map_edit_area_type"] = "WholePicture"; + + return $this->editMapArea(false, false, true); + } + + /** + * Add a new rectangle + */ + public function addRectangle() + { + $this->clearSessionVars(); + $_SESSION["il_map_edit_area_type"] = "Rect"; + return $this->addArea(false); + } + + /** + * Add a new circle + */ + public function addCircle() + { + $this->clearSessionVars(); + $_SESSION["il_map_edit_area_type"] = "Circle"; + return $this->addArea(false); + } + + /** + * Add a new polygon + */ + public function addPolygon() + { + $this->clearSessionVars(); + $_SESSION["il_map_edit_area_type"] = "Poly"; + return $this->addArea(false); + } + + /** + * Clear Session Vars + */ + public function clearSessionVars() + { + $_SESSION["il_map_area_nr"] = ""; + $_SESSION["il_map_edit_coords"] = ""; + $_SESSION["il_map_edit_mode"] = ""; + $_SESSION["il_map_el_href"] = ""; + $_SESSION["il_map_il_type"] = ""; + $_SESSION["il_map_il_ltype"] = ""; + $_SESSION["il_map_il_target"] = ""; + $_SESSION["il_map_il_targetframe"] = ""; + $_SESSION["il_map_edit_area_type"] = ""; + } + + /** + * Handle adding new area process + */ + public function addArea($a_handle = true) + { + + // handle map parameters + if ($a_handle) { + $this->handleMapParameters(); + } + + $area_type = $_SESSION["il_map_edit_area_type"]; + $coords = $_SESSION["il_map_edit_coords"]; + include_once("./Services/MediaObjects/classes/class.ilMapArea.php"); + $cnt_coords = ilMapArea::countCoords($coords); + + // decide what to do next + switch ($area_type) { + // Rectangle + case "Rect": + if ($cnt_coords < 2) { + $html = $this->editMapArea(true, false, false); + return $html; + } elseif ($cnt_coords == 2) { + return $this->editMapArea(false, true, true); + } + break; + + // Circle + case "Circle": + if ($cnt_coords <= 1) { + return $this->editMapArea(true, false, false); + } else { + if ($cnt_coords == 2) { + $c = explode(",", $coords); + $coords = $c[0] . "," . $c[1] . ","; // determine radius + $coords .= round(sqrt(pow(abs($c[3]-$c[1]), 2)+pow(abs($c[2]-$c[0]), 2))); + } + $_SESSION["il_map_edit_coords"] = $coords; + + return $this->editMapArea(false, true, true); + } + break; + + // Polygon + case "Poly": + if ($cnt_coords < 1) { + return $this->editMapArea(true, false, false); + } elseif ($cnt_coords < 3) { + return $this->editMapArea(true, true, false); + } else { + return $this->editMapArea(true, true, true); + } + break; + + // Whole picture + case "WholePicture": + return $this->editMapArea(false, false, true); + break; + } + } + + /** + * Edit a single map area + * + * @param boolean $a_get_next_coordinate enable next coordinate input + * @param boolean $a_output_new_area output the new area + * @param boolean $a_save_from output save form + * @param string $a_edit_property "" | "link" | "shape" + */ + public function editMapArea( + $a_get_next_coordinate = false, + $a_output_new_area = false, + $a_save_form = false, + $a_edit_property = "", + $a_area_nr = 0 + ) { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + + $area_type = $_SESSION["il_map_edit_area_type"]; + $coords = $_SESSION["il_map_edit_coords"]; + include_once("./Services/MediaObjects/classes/class.ilMapArea.php"); + $cnt_coords = ilMapArea::countCoords($coords); + + $this->tpl = new ilTemplate("tpl.map_edit.html", true, true, "Services/MediaObjects"); + + $this->tpl->setVariable("FORMACTION", $ilCtrl->getFormAction($this)); + + if ($a_edit_property != "link") { + switch ($area_type) { + // rectangle + case "Rect": + if ($cnt_coords == 0) { + ilUtil::sendInfo($lng->txt("cont_click_tl_corner")); + } + if ($cnt_coords == 1) { + ilUtil::sendInfo($lng->txt("cont_click_br_corner")); + } + break; + + // circle + case "Circle": + if ($cnt_coords == 0) { + ilUtil::sendInfo($lng->txt("cont_click_center")); + } + if ($cnt_coords == 1) { + ilUtil::sendInfo($lng->txt("cont_click_circle")); + } + break; + + // polygon + case "Poly": + if ($cnt_coords == 0) { + ilUtil::sendInfo($lng->txt("cont_click_starting_point")); + } elseif ($cnt_coords < 3) { + ilUtil::sendInfo($lng->txt("cont_click_next_point")); + } else { + ilUtil::sendInfo($lng->txt("cont_click_next_or_save")); + } + break; + } + } + + + // map properties input fields (name and link) + if ($a_save_form) { + if ($a_edit_property != "shape") { + // prepare link gui + $ilCtrl->setParameter($this, "linkmode", "map"); + include_once("./Services/Link/classes/class.ilInternalLinkGUI.php"); + $this->tpl->setCurrentBlock("int_link_prep"); + $this->tpl->setVariable("INT_LINK_PREP", ilInternalLinkGUI::getInitHTML( + $ilCtrl->getLinkTargetByClass( + "ilinternallinkgui", + "", + false, + true, + false + ) + )); + $this->tpl->parseCurrentBlock(); + } + $form = $this->initAreaEditingForm($a_edit_property); + $this->tpl->setVariable("FORM", $form->getHTML()); + } + + $this->makeMapWorkCopy( + $a_edit_property, + $a_area_nr, + $a_output_new_area, + $area_type, + $coords + ); + + $edit_mode = ($a_get_next_coordinate) + ? "get_coords" + : (($a_output_new_area) + ? "new_area" + :""); + $output = $this->getImageMapOutput($edit_mode); + $this->tpl->setVariable("IMAGE_MAP", $output); + + return $this->tpl->get(); + } + + /** + * Init area editing form. + * + * @param int $a_mode Edit Mode + */ + public function initAreaEditingForm($a_edit_property) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setOpenTag(false); + $form->setCloseTag(false); + + // link + if ($a_edit_property != "shape") { + // + $radg = new ilRadioGroupInputGUI($lng->txt("cont_link"), "area_link_type"); + if ($_SESSION["il_map_il_ltype"] != "int") { + if ($_SESSION["il_map_el_href"] == "") { + $radg->setValue("no"); + } else { + $radg->setValue("ext"); + } + } else { + $radg->setValue("int"); + } + + // external link + $ext = new ilRadioOption($lng->txt("cont_link_ext"), "ext"); + $radg->addOption($ext); + + $ti = new ilTextInputGUI("", "area_link_ext"); + $ti->setMaxLength(800); + $ti->setSize(50); + if ($_SESSION["il_map_el_href"] != "") { + $ti->setValue($_SESSION["il_map_el_href"]); + } else { + $ti->setValue("http://"); + } + $ext->addSubItem($ti); + + // internal link + $int = new ilRadioOption($lng->txt("cont_link_int"), "int"); + $radg->addOption($int); + + $ne = new ilNonEditableValueGUI("", "", true); + $link_str = ""; + if ($_SESSION["il_map_il_target"] != "") { + $link_str = $this->getMapAreaLinkString( + $_SESSION["il_map_il_target"], + $_SESSION["il_map_il_type"], + $_SESSION["il_map_il_targetframe"] + ); + } + $ne->setValue( + $link_str . + ' ' . + "[" . $lng->txt("cont_get_link") . "]" . + '' + ); + $int->addSubItem($ne); + + // no link + $no = new ilRadioOption($lng->txt("cont_link_no"), "no"); + $radg->addOption($no); + + $form->addItem($radg); + } + + + // name + if ($a_edit_property != "link" && $a_edit_property != "shape") { + $ti = new ilTextInputGUI($lng->txt("cont_name"), "area_name"); + $ti->setMaxLength(200); + $ti->setSize(20); + $form->addItem($ti); + } + + // save and cancel commands + if ($a_edit_property == "") { + $form->setTitle($lng->txt("cont_new_area")); + $form->addCommandButton("saveArea", $lng->txt("save")); + } else { + $form->setTitle($lng->txt("cont_new_area")); + $form->addCommandButton("saveArea", $lng->txt("save")); + } + + // $form->setFormAction($ilCtrl->getFormAction($this)); + + return $form; + } + + /** + * Make work file for editing + */ + public function makeMapWorkCopy( + $a_edit_property = "", + $a_area_nr = 0, + $a_output_new_area = false, + $a_area_type = "", + $a_coords = "" + ) { + // create/update imagemap work copy + $st_item = $this->media_object->getMediaItem("Standard"); + + if ($a_edit_property == "shape") { + $st_item->makeMapWorkCopy($a_area_nr, true); // exclude area currently being edited + } else { + $st_item->makeMapWorkCopy($a_area_nr, false); + } + + if ($a_output_new_area) { + $st_item->addAreaToMapWorkCopy($a_area_type, $a_coords); + } + } + + /** + * Render the image map. + */ + public function getImageMapOutput($a_map_edit_mode = "") + { + $ilCtrl = $this->ctrl; + + $st_item = $this->media_object->getMediaItem("Standard"); + + // output image map + $xml = ""; + $xml.= $this->getAliasXML(); + $xml.= $this->media_object->getXML(IL_MODE_OUTPUT); + $xml.= $this->getAdditionalPageXML(); + $xml.=""; + $xsl = file_get_contents("./Services/COPage/xsl/page.xsl"); + //echo htmlentities($xml); exit; + $args = array( '/_xml' => $xml, '/_xsl' => $xsl ); + $xh = xslt_create(); + $wb_path = ilUtil::getWebspaceDir("output") . "/"; + $mode = "media"; + //echo htmlentities($ilCtrl->getLinkTarget($this, "showImageMap")); + $params = array('map_edit_mode' => $a_map_edit_mode, + 'map_item' => $st_item->getId(), + 'map_mob_id' => $this->media_object->getId(), + 'mode' => $mode, + 'media_mode' => 'enable', + 'image_map_link' => $ilCtrl->getLinkTarget($this, "showImageMap", "", false, false), + 'link_params' => "ref_id=" . $_GET["ref_id"] . "&rand=" . rand(1, 999999), + 'ref_id' => $_GET["ref_id"], + 'pg_frame' => "", + 'enlarge_path' => ilUtil::getImagePath("enlarge.svg"), + 'webspace_path' => $wb_path); + $output = xslt_process($xh, "arg:/_xml", "arg:/_xsl", null, $args, $params); + echo xslt_error($xh); + xslt_free($xh); + + $output = $this->outputPostProcessing($output); + + return $output; + } + + /** + * Get additional page xml (to be overwritten) + * + * @return string additional page xml + */ + public function getAdditionalPageXML() + { + return ""; + } + + /** + * Output post processing + * + * @param + * @return + */ + public function outputPostProcessing($a_output) + { + return $a_output; + } + + public function getAliasXML() + { + return $this->media_object->getXML(IL_MODE_ALIAS); + } + + /** + * Get text name of internal link + * + * @param string $a_target target object link id + * @param string $a_type type + * @param string $a_frame target frame + * + * @access private + */ + public function getMapAreaLinkString($a_target, $a_type, $a_frame) + { + $lng = $this->lng; + + $t_arr = explode("_", $a_target); + if ($a_frame != "") { + $frame_str = " (" . $a_frame . " Frame)"; + } + switch ($a_type) { + case "StructureObject": + require_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + $title = ilLMObject::_lookupTitle($t_arr[count($t_arr) - 1]); + $link_str = $lng->txt("chapter") . + ": " . $title . " [" . $t_arr[count($t_arr) - 1] . "]" . $frame_str; + break; + + case "PageObject": + require_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + $title = ilLMObject::_lookupTitle($t_arr[count($t_arr) - 1]); + $link_str = $lng->txt("page") . + ": " . $title . " [" . $t_arr[count($t_arr) - 1] . "]" . $frame_str; + break; + + case "GlossaryItem": + require_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + $term = new ilGlossaryTerm($t_arr[count($t_arr) - 1]); + $link_str = $lng->txt("term") . + ": " . $term->getTerm() . " [" . $t_arr[count($t_arr) - 1] . "]" . $frame_str; + break; + + case "MediaObject": + require_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $mob = new ilObjMediaObject($t_arr[count($t_arr) - 1]); + $link_str = $lng->txt("mob") . + ": " . $mob->getTitle() . " [" . $t_arr[count($t_arr) - 1] . "]" . $frame_str; + break; + + case "RepositoryItem": + $title = ilObject::_lookupTitle( + ilObject::_lookupObjId($t_arr[count($t_arr) - 1]) + ); + $link_str = $lng->txt("obj_" . $t_arr[count($t_arr) - 2]) . + ": " . $title . " [" . $t_arr[count($t_arr) - 1] . "]" . $frame_str; + break; + } + + return $link_str; + } + + /** + * Get image map coordinates. + */ + public function editImagemapForward() + { + ilImageMapEditorGUI::_recoverParameters(); + + if ($_SESSION["il_map_edit_coords"] != "") { + $_SESSION["il_map_edit_coords"] .= ","; + } + + $_SESSION["il_map_edit_coords"] .= $_POST["editImagemapForward_x"] . "," . + $_POST["editImagemapForward_y"]; + + // call editing script + ilUtil::redirect($_SESSION["il_map_edit_target_script"]); + } + + /** + * Recover parameters from session variables (static) + */ + public static function _recoverParameters() + { + $_GET["ref_id"] = $_SESSION["il_map_edit_ref_id"]; + $_GET["obj_id"] = $_SESSION["il_map_edit_obj_id"]; + $_GET["hier_id"] = $_SESSION["il_map_edit_hier_id"]; + $_GET["pc_id"] = $_SESSION["il_map_edit_pc_id"]; + } + + /** + * Save new or updated map area + */ + public function saveArea() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + switch ($_SESSION["il_map_edit_mode"]) { + // save edited link + case "edit_link": + $st_item = $this->media_object->getMediaItem("Standard"); + $max = ilMapArea::_getMaxNr($st_item->getId()); + $area = new ilMapArea($st_item->getId(), $_SESSION["il_map_area_nr"]); + + if ($_POST["area_link_type"] == IL_INT_LINK) { + $area->setLinkType(IL_INT_LINK); + $area->setType($_SESSION["il_map_il_type"]); + $area->setTarget($_SESSION["il_map_il_target"]); + $area->setTargetFrame($_SESSION["il_map_il_targetframe"]); + } else { + $area->setLinkType(IL_EXT_LINK); + if ($_POST["area_link_type"] != IL_NO_LINK) { + $area->setHref(ilUtil::stripSlashes($_POST["area_link_ext"])); + } else { + $area->setHref(""); + } + } + $area->update(); + break; + + // save edited shape + case "edit_shape": + $st_item = $this->media_object->getMediaItem("Standard"); + $max = ilMapArea::_getMaxNr($st_item->getId()); + $area = new ilMapArea($st_item->getId(), $_SESSION["il_map_area_nr"]); + + $area->setShape($_SESSION["il_map_edit_area_type"]); + $area->setCoords($_SESSION["il_map_edit_coords"]); + $area->update(); + break; + + // save new area + default: + $area_type = $_SESSION["il_map_edit_area_type"]; + $coords = $_SESSION["il_map_edit_coords"]; + + $st_item = $this->media_object->getMediaItem("Standard"); + $max = ilMapArea::_getMaxNr($st_item->getId()); + + // make new area object + $area = new ilMapArea(); + $area->setItemId($st_item->getId()); + $area->setShape($area_type); + $area->setCoords($coords); + $area->setNr($max + 1); + $area->setTitle(ilUtil::stripSlashes($_POST["area_name"])); + switch ($_POST["area_link_type"]) { + case "ext": + $area->setLinkType(IL_EXT_LINK); + $area->setHref($_POST["area_link_ext"]); + break; + + case "int": + $area->setLinkType(IL_INT_LINK); + $area->setType($_SESSION["il_map_il_type"]); + $area->setTarget($_SESSION["il_map_il_target"]); + $area->setTargetFrame($_SESSION["il_map_il_targetframe"]); + break; + } + + // put area into item and update media object + $st_item->addMapArea($area); + $this->media_object->update(); + break; + } + + //$this->initMapParameters(); + ilUtil::sendSuccess($lng->txt("cont_saved_map_area"), true); + $ilCtrl->redirect($this, "editMapAreas"); + } + + /** + * Set internal link + */ + public function setInternalLink() + { + $_SESSION["il_map_il_type"] = $_GET["linktype"]; + $_SESSION["il_map_il_ltype"] = "int"; + + $_SESSION["il_map_il_target"] = $_GET["linktarget"]; + $_SESSION["il_map_il_targetframe"] = $_GET["linktargetframe"]; + $_SESSION["il_map_il_anchor"] = $_GET["linkanchor"]; + switch ($_SESSION["il_map_edit_mode"]) { + case "edit_link": + return $this->setLink(); + break; + + default: + return $this->addArea(); + break; + } + } + + /** + * Set link + */ + public function setLink($a_handle = true) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if ($a_handle) { + $this->handleMapParameters(); + } + if ($_SESSION["il_map_area_nr"] != "") { + $_POST["area"][0] = $_SESSION["il_map_area_nr"]; + } + if (!isset($_POST["area"])) { + ilUtil::sendFailure($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "editMapAreas"); + } + + if (count($_POST["area"]) > 1) { + //$this->ilias->raiseError($this->lng->txt("cont_select_max_one_item"),$this->ilias->error_obj->MESSAGE); + ilUtil::sendFailure($lng->txt("cont_select_max_one_item"), true); + $ilCtrl->redirect($this, "editMapAreas"); + } + + + if ($_SESSION["il_map_edit_mode"] != "edit_link") { + $_SESSION["il_map_area_nr"] = $_POST["area"][0]; + $_SESSION["il_map_il_ltype"] = $this->getLinkTypeOfArea($_POST["area"][0]); + $_SESSION["il_map_edit_mode"] = "edit_link"; + $_SESSION["il_map_edit_target_script"] = $ilCtrl->getLinkTarget($this, "setLink"); + if ($_SESSION["il_map_il_ltype"] == IL_INT_LINK) { + $_SESSION["il_map_il_type"] = $this->getTypeOfArea($_POST["area"][0]); + $_SESSION["il_map_il_target"] = $this->getTargetOfArea($_POST["area"][0]); + $_SESSION["il_map_il_targetframe"] = $this->getTargetFrameOfArea($_POST["area"][0]); + } else { + $_SESSION["il_map_el_href"] = $this->getHrefOfArea($_POST["area"][0]); + } + } + + return $this->editMapArea(false, false, true, "link", $_POST["area"][0]); + } + + /** + * Get Link Type of Area + */ + public function getLinkTypeOfArea($a_nr) + { + $st_item = $this->media_object->getMediaItem("Standard"); + $area = $st_item->getMapArea($a_nr); + return $area->getLinkType(); + } + + /** + * Get Type of Area (only internal link) + */ + public function getTypeOfArea($a_nr) + { + $st_item = $this->media_object->getMediaItem("Standard"); + $area = $st_item->getMapArea($a_nr); + return $area->getType(); + } + + /** + * Get Target of Area (only internal link) + */ + public function getTargetOfArea($a_nr) + { + $st_item = $this->media_object->getMediaItem("Standard"); + $area = $st_item->getMapArea($a_nr); + return $area->getTarget(); + } + + /** + * Get TargetFrame of Area (only internal link) + */ + public function getTargetFrameOfArea($a_nr) + { + $st_item = $this->media_object->getMediaItem("Standard"); + $area = $st_item->getMapArea($a_nr); + return $area->getTargetFrame(); + } + + /** + * Get Href of Area (only external link) + */ + public function getHrefOfArea($a_nr) + { + $st_item = $this->media_object->getMediaItem("Standard"); + $area = $st_item->getMapArea($a_nr); + return $area->getHref(); + } + + /** + * Delete map areas + */ + public function deleteAreas() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if (!isset($_POST["area"])) { + ilUtil::sendFailure($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "editMapAreas"); + } + + $st_item = $this->media_object->getMediaItem("Standard"); + $max = ilMapArea::_getMaxNr($st_item->getId()); + + if (count($_POST["area"]) > 0) { + $i = 0; + + foreach ($_POST["area"] as $area_nr) { + $st_item->deleteMapArea($area_nr - $i); + $i++; + } + + $this->media_object->update(); + ilUtil::sendSuccess($lng->txt("cont_areas_deleted"), true); + } + + $ilCtrl->redirect($this, "editMapAreas"); + } + + /** + * Edit existing link + */ + public function editLink() + { + $_SESSION["il_map_edit_coords"] = ""; + $_SESSION["il_map_edit_mode"] = ""; + $_SESSION["il_map_el_href"] = ""; + $_SESSION["il_map_il_type"] = ""; + $_SESSION["il_map_il_ltype"] = ""; + $_SESSION["il_map_il_target"] = ""; + $_SESSION["il_map_il_targetframe"] = ""; + $_SESSION["il_map_area_nr"] = ""; + return $this->setLink(false); + } + + /** + * Edit an existing shape (make it a whole picture link) + */ + public function editShapeWholePicture() + { + $this->clearSessionVars(); + $_SESSION["il_map_edit_area_type"] = "WholePicture"; + return $this->setShape(false); + } + + /** + * Edit an existing shape (make it a rectangle) + */ + public function editShapeRectangle() + { + $this->clearSessionVars(); + $_SESSION["il_map_edit_area_type"] = "Rect"; + return $this->setShape(false); + } + + /** + * Edit an existing shape (make it a circle) + */ + public function editShapeCircle() + { + $this->clearSessionVars(); + $_SESSION["il_map_edit_area_type"] = "Circle"; + return $this->setShape(false); + } + + /** + * Edit an existing shape (make it a polygon) + */ + public function editShapePolygon() + { + $this->clearSessionVars(); + $_SESSION["il_map_edit_area_type"] = "Poly"; + return $this->setShape(false); + } + + /** + * edit shape of existing map area + */ + public function setShape($a_handle = true) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if ($a_handle) { + $this->handleMapParameters(); + } + if ($_POST["areatype2"] != "") { + $_SESSION["il_map_edit_area_type"] = $_POST["areatype2"]; + } + if ($_SESSION["il_map_area_nr"] != "") { + $_POST["area"][0] = $_SESSION["il_map_area_nr"]; + } + if (!isset($_POST["area"])) { + ilUtil::sendFailure($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "editMapAreas"); + } + + if (count($_POST["area"]) > 1) { + ilUtil::sendFailure($lng->txt("cont_select_max_one_item"), true); + $ilCtrl->redirect($this, "editMapAreas"); + } + + if ($_SESSION["il_map_edit_mode"] != "edit_shape") { + $_SESSION["il_map_area_nr"] = $_POST["area"][0]; + $_SESSION["il_map_edit_mode"] = "edit_shape"; + $_SESSION["il_map_edit_target_script"] = $ilCtrl->getLinkTarget($this, "setShape", "", false, false); + } + + + $area_type = $_SESSION["il_map_edit_area_type"]; + $coords = $_SESSION["il_map_edit_coords"]; + $cnt_coords = ilMapArea::countCoords($coords); + + // decide what to do next + switch ($area_type) { + // Rectangle + case "Rect": + if ($cnt_coords < 2) { + return $this->editMapArea(true, false, false, "shape", $_POST["area"][0]); + } elseif ($cnt_coords == 2) { + return $this->saveArea(); + } + break; + + // Circle + case "Circle": + if ($cnt_coords <= 1) { + return $this->editMapArea(true, false, false, "shape", $_POST["area"][0]); + } else { + if ($cnt_coords == 2) { + $c = explode(",", $coords); + $coords = $c[0] . "," . $c[1] . ","; // determine radius + $coords .= round(sqrt(pow(abs($c[3]-$c[1]), 2)+pow(abs($c[2]-$c[0]), 2))); + } + $_SESSION["il_map_edit_coords"] = $coords; + + return $this->saveArea(); + } + break; + + // Polygon + case "Poly": + if ($cnt_coords < 1) { + return $this->editMapArea(true, false, false, "shape", $_POST["area"][0]); + } elseif ($cnt_coords < 3) { + return $this->editMapArea(true, true, false, "shape", $_POST["area"][0]); + } else { + return $this->editMapArea(true, true, true, "shape", $_POST["area"][0]); + } + break; + + // Whole Picture + case "WholePicture": + return $this->saveArea(); + } + } + + /** + * Set highlight settings + * + * @param + * @return + */ + public function setHighlight() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $st_item = $this->media_object->getMediaItem("Standard"); + $st_item->setHighlightMode(ilUtil::stripSlashes($_POST["highlight_mode"])); + $st_item->setHighlightClass(ilUtil::stripSlashes($_POST["highlight_class"])); + $st_item->update(); + + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "editMapAreas"); + } } -?> diff --git a/Services/MediaObjects/classes/class.ilImageMapTableGUI.php b/Services/MediaObjects/classes/class.ilImageMapTableGUI.php index 8418de8382d9f858c9a852333cf9928dbe27096d..6449e161e5da4785dc86995a3fcdef8f0e8deae9 100755 --- a/Services/MediaObjects/classes/class.ilImageMapTableGUI.php +++ b/Services/MediaObjects/classes/class.ilImageMapTableGUI.php @@ -14,149 +14,165 @@ include_once("Services/Table/classes/class.ilTable2GUI.php"); */ class ilImageMapTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_media_object) - { - global $DIC; + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_media_object) + { + 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(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->media_object = $a_media_object; - - include_once("./Services/MediaObjects/classes/class.ilMapArea.php"); - $this->highl_modes = ilMapArea::getAllHighlightModes(); - $this->highl_classes = ilMapArea::getAllHighlightClasses(); - - $this->initColumns(); - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.image_map_table_row.html", "Services/MediaObjects"); - $this->getItems(); + $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); + $this->media_object = $a_media_object; + + include_once("./Services/MediaObjects/classes/class.ilMapArea.php"); + $this->highl_modes = ilMapArea::getAllHighlightModes(); + $this->highl_classes = ilMapArea::getAllHighlightClasses(); + + $this->initColumns(); + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.image_map_table_row.html", "Services/MediaObjects"); + $this->getItems(); - // action commands - $this->initActions(); + // action commands + $this->initActions(); - $this->setDefaultOrderField("title"); - $this->setDefaultOrderDirection("asc"); - $this->setEnableTitle(false); - } - - /** - * Init columns - */ - function initColumns() - { - $this->addColumn("", "", "1"); // checkbox - $this->addColumn($this->lng->txt("cont_name"), "title", ""); - $this->addColumn($this->lng->txt("cont_shape"), "", ""); - $this->addColumn($this->lng->txt("cont_coords"), "", ""); - $this->addColumn($this->lng->txt("cont_highlight_mode")); - $this->addColumn($this->lng->txt("cont_highlight_class")); - $this->addColumn($this->lng->txt("cont_link"), "", ""); - } - - /** - * Init actions - */ - function initActions() - { - $lng = $this->lng; - - // action commands - $this->addMultiCommand("deleteAreas", $lng->txt("delete")); - $this->addMultiCommand("editLink", $lng->txt("cont_set_link")); - $this->addMultiCommand("editShapeWholePicture", $lng->txt("cont_edit_shape_whole_picture")); - $this->addMultiCommand("editShapeRectangle", $lng->txt("cont_edit_shape_rectangle")); - $this->addMultiCommand("editShapeCircle", $lng->txt("cont_edit_shape_circle")); - $this->addMultiCommand("editShapePolygon", $lng->txt("cont_edit_shape_polygon")); - - $data = $this->getData(); - if (count($data) > 0) - { - $this->addCommandButton("updateAreas", $lng->txt("save")); - } - } - + $this->setDefaultOrderField("title"); + $this->setDefaultOrderDirection("asc"); + $this->setEnableTitle(false); + } + + /** + * Init columns + */ + public function initColumns() + { + $this->addColumn("", "", "1"); // checkbox + $this->addColumn($this->lng->txt("cont_name"), "title", ""); + $this->addColumn($this->lng->txt("cont_shape"), "", ""); + $this->addColumn($this->lng->txt("cont_coords"), "", ""); + $this->addColumn($this->lng->txt("cont_highlight_mode")); + $this->addColumn($this->lng->txt("cont_highlight_class")); + $this->addColumn($this->lng->txt("cont_link"), "", ""); + } + + /** + * Init actions + */ + public function initActions() + { + $lng = $this->lng; + + // action commands + $this->addMultiCommand("deleteAreas", $lng->txt("delete")); + $this->addMultiCommand("editLink", $lng->txt("cont_set_link")); + $this->addMultiCommand("editShapeWholePicture", $lng->txt("cont_edit_shape_whole_picture")); + $this->addMultiCommand("editShapeRectangle", $lng->txt("cont_edit_shape_rectangle")); + $this->addMultiCommand("editShapeCircle", $lng->txt("cont_edit_shape_circle")); + $this->addMultiCommand("editShapePolygon", $lng->txt("cont_edit_shape_polygon")); + + $data = $this->getData(); + if (count($data) > 0) { + $this->addCommandButton("updateAreas", $lng->txt("save")); + } + } + - /** - * Get items of current folder - */ - function getItems() - { - $st_item = $this->media_object->getMediaItem("Standard"); - $max = ilMapArea::_getMaxNr($st_item->getId()); - $areas = array(); - - include_once("./Services/MediaObjects/classes/class.ilMapArea.php"); - for ($i=1; $i<=$max; $i++) - { - $area = new ilMapArea($st_item->getId(), $i); - $areas[] = array("nr" => $i, "area" => $area, "title" => $area->getTitle()); - } + /** + * Get items of current folder + */ + public function getItems() + { + $st_item = $this->media_object->getMediaItem("Standard"); + $max = ilMapArea::_getMaxNr($st_item->getId()); + $areas = array(); + + include_once("./Services/MediaObjects/classes/class.ilMapArea.php"); + for ($i=1; $i<=$max; $i++) { + $area = new ilMapArea($st_item->getId(), $i); + $areas[] = array("nr" => $i, "area" => $area, "title" => $area->getTitle()); + } - $this->setData($areas); - } - - /** - * Standard Version of Fill Row. Most likely to - * be overwritten by derived class. - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; + $this->setData($areas); + } + + /** + * Standard Version of Fill Row. Most likely to + * be overwritten by derived class. + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; - $area = $a_set["area"]; - $i = $a_set["nr"]; - $this->tpl->setVariable("CHECKBOX", - ilUtil::formCheckBox("", "area[]", $i)); - $this->tpl->setVariable("VAR_NAME", "name_".$i); - $this->tpl->setVariable("VAL_NAME", ilUtil::prepareFormOutput($area->getTitle())); - $this->tpl->setVariable("VAL_SHAPE", $area->getShape()); - - $this->tpl->setVariable("VAL_HIGHL_MODE", - ilUtil::formSelect($area->getHighlightMode(), "hl_mode_".$i, - $this->highl_modes, false, true)); - $this->tpl->setVariable("VAL_HIGHL_CLASS", - ilUtil::formSelect($area->getHighlightClass(), "hl_class_".$i, - $this->highl_classes, false, true)); - - $this->tpl->setVariable("VAL_COORDS", - implode(explode(",", $area->getCoords()), ", ")); - switch ($area->getLinkType()) - { - case "ext": - $this->tpl->setVariable("VAL_LINK", $area->getHRef()); - break; - - case "int": - $link_str = $this->parent_obj->getMapAreaLinkString($area->getTarget(), - $area->getType(), $area->getTargetFrame()); - $this->tpl->setVariable("VAL_LINK", $link_str); - break; - } - } + $area = $a_set["area"]; + $i = $a_set["nr"]; + $this->tpl->setVariable( + "CHECKBOX", + ilUtil::formCheckBox("", "area[]", $i) + ); + $this->tpl->setVariable("VAR_NAME", "name_" . $i); + $this->tpl->setVariable("VAL_NAME", ilUtil::prepareFormOutput($area->getTitle())); + $this->tpl->setVariable("VAL_SHAPE", $area->getShape()); + + $this->tpl->setVariable( + "VAL_HIGHL_MODE", + ilUtil::formSelect( + $area->getHighlightMode(), + "hl_mode_" . $i, + $this->highl_modes, + false, + true + ) + ); + $this->tpl->setVariable( + "VAL_HIGHL_CLASS", + ilUtil::formSelect( + $area->getHighlightClass(), + "hl_class_" . $i, + $this->highl_classes, + false, + true + ) + ); + + $this->tpl->setVariable( + "VAL_COORDS", + implode(explode(",", $area->getCoords()), ", ") + ); + switch ($area->getLinkType()) { + case "ext": + $this->tpl->setVariable("VAL_LINK", $area->getHRef()); + break; + case "int": + $link_str = $this->parent_obj->getMapAreaLinkString( + $area->getTarget(), + $area->getType(), + $area->getTargetFrame() + ); + $this->tpl->setVariable("VAL_LINK", $link_str); + break; + } + } } -?> diff --git a/Services/MediaObjects/classes/class.ilMapArea.php b/Services/MediaObjects/classes/class.ilMapArea.php index a80d8f88178f8a7a9e3b336900e6cc975f8998cc..ccfe467b76d55129b57324c3d8801c9709ac1958 100755 --- a/Services/MediaObjects/classes/class.ilMapArea.php +++ b/Services/MediaObjects/classes/class.ilMapArea.php @@ -35,706 +35,767 @@ define("IL_TF_NEW", "New"); */ class ilMapArea { - /** - * @var ilDB - */ - protected $db; - - const HL_NONE = ""; - const HL_HOVER = "Hover"; - const HL_ALWAYS = "Always"; - const HLCL_ACCENTED = ""; - const HLCL_LIGHT = "Light"; - const HLCL_DARK = "Dark"; - - var $item_id; - var $nr; - var $shape; - var $coords; - var $title; - var $linktype; - var $xl_title; - var $xl_href; - var $il_target; - var $il_type; - var $il_target_frame; - - - /** - * map area - * - * @param int $a_item_id parent media item id - * @param int $a_nr map area number within media item - */ - function __construct($a_item_id = 0, $a_nr = 0) - { - global $DIC; - - $this->db = $DIC->database(); - $this->title = ""; - if ($a_item_id !=0 && $a_nr != 0) - { - $this->setItemId($a_item_id); - $this->setNr($a_nr); - $this->read(); - } - } - - /** - * create persistent map area object in db - */ - function create() - { - $ilDB = $this->db; - - $q = "INSERT INTO map_area (item_id, nr, shape, ". - "coords, link_type, title, href, target, type, highlight_mode, highlight_class, target_frame) ". - " VALUES (". - $ilDB->quote($this->getItemId(), "integer").",". - $ilDB->quote($this->getNr(), "integer").",". - $ilDB->quote($this->getShape(), "text").",". - $ilDB->quote($this->getCoords(), "text").",". - $ilDB->quote($this->getLinkType(), "text").",". - $ilDB->quote($this->getTitle(), "text").",". - $ilDB->quote($this->getHref(), "text").",". - $ilDB->quote($this->getTarget(), "text").",". - $ilDB->quote($this->getType(), "text").",". - $ilDB->quote($this->getHighlightMode(), "text").",". - $ilDB->quote($this->getHighlightClass(), "text").",". - $ilDB->quote($this->getTargetFrame(), "text").")"; - $ilDB->manipulate($q); - } - - /** - * get maximum nr of media item (static) - * - * @param int $a_item_id item id - * - * @return int maximum nr - */ - static function _getMaxNr($a_item_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "SELECT max(nr) AS max_nr FROM map_area WHERE item_id = ". - $ilDB->quote($a_item_id, "integer"); - $max_set = $ilDB->query($q); - $max_rec = $ilDB->fetchAssoc($max_set); - - return $max_rec["max_nr"]; - } - - /** - * read map area data into object (item id and nr must be set) - */ - function read() - { - $ilDB = $this->db; - - $q = "SELECT * FROM map_area WHERE item_id = ". - $ilDB->quote($this->getItemId(), "integer"). - " AND nr = ".$ilDB->quote($this->getNr(), "integer"); - $area_set = $ilDB->query($q); - $area_rec = $ilDB->fetchAssoc($area_set); - - $this->setShape($area_rec["shape"]); -//echo $area_rec["Shape"]; - $this->setNr($area_rec["nr"]); - $this->setCoords($area_rec["coords"]); - $this->setLinkType($area_rec["link_type"]); - $this->setTitle($area_rec["title"]); - $this->setHref($area_rec["href"]); - $this->setTarget($area_rec["target"]); - $this->setType($area_rec["type"]); - $this->setTargetFrame($area_rec["target_frame"]); - $this->setHighlightMode($area_rec["highlight_mode"]); - $this->setHighlightClass($area_rec["highlight_class"]); - - } - - /** - * update map area - */ - function update() - { - $ilDB = $this->db; - - $q = "UPDATE map_area SET shape = ".$ilDB->quote($this->getShape(), "text"). - ", coords = ".$ilDB->quote($this->getCoords(), "text"). - ", link_type = ".$ilDB->quote($this->getLinkType(), "text"). - ", title = ".$ilDB->quote($this->getTitle(), "text"). - ", href = ".$ilDB->quote($this->getHref(), "text"). - ", target = ".$ilDB->quote($this->getTarget(), "text"). - ", type = ".$ilDB->quote($this->getType(), "text"). - ", highlight_mode = ".$ilDB->quote($this->getHighlightMode(), "text"). - ", highlight_class = ".$ilDB->quote($this->getHighlightClass(), "text"). - ", target_frame = ".$ilDB->quote($this->getTargetFrame(), "text"). - " WHERE item_id = ".$ilDB->quote($this->getItemId(), "integer"). - " AND nr = ".$ilDB->quote($this->getNr(), "integer"); - $ilDB->manipulate($q); - } - - /** - * resolve internal links of an item id - */ - static function _resolveIntLinks($a_item_id) - { - global $DIC; - - $ilDB = $DIC->database(); - -//echo "maparea::resolve
                  "; - $q = "SELECT * FROM map_area WHERE item_id = ". - $ilDB->quote($a_item_id, "integer"); - $area_set = $ilDB->query($q); - while ($area_rec = $ilDB->fetchAssoc($area_set)) - { - $target = $area_rec["target"]; - $type = $area_rec["type"]; - $item_id = $area_rec["item_id"]; - $nr = $area_rec["nr"]; - - if (($area_rec["link_type"] == IL_INT_LINK) && (!is_int(strpos($target, "__")))) - { - $new_target = ilInternalLink::_getIdForImportId($type, $target); - if ($new_target !== false) - { - $query = "UPDATE map_area SET ". - "target = ".$ilDB->quote($new_target, "text")." ". - "WHERE item_id = ".$ilDB->quote($item_id, "integer"). - " AND nr = ".$ilDB->quote($nr, "integer"); - $ilDB->manipulate($query); - } - } - } - } - - /** - * get all internal links of a media items map areas - * - * @param int $a_item_id media item id - */ - static function _getIntLinks($a_item_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "SELECT * FROM map_area WHERE item_id = ". - $ilDB->quote($a_item_id, "integer"); - $area_set = $ilDB->query($q); - - $links = array(); - - while ($area_rec = $ilDB->fetchAssoc($area_set)) - { - $target = $area_rec["target"]; - $type = $area_rec["type"]; - $targetframe = $area_rec["target_frame"]; - - if (($area_rec["link_type"] == IL_INT_LINK) && (is_int(strpos($target, "__")))) - { - $links[$target.":".$type.":".$targetframe] = - array("Target" => $target, "Type" => $type, - "TargetFrame" => $targetframe); - } - } - return $links; - } - - /** - * Get areas for a certain target - */ - static function _getMobsForTarget($a_type, $a_target) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "SELECT * FROM map_area WHERE ". - " link_type = ".$ilDB->quote($a_type, "text"). - " AND target = ".$ilDB->quote($a_target, "text"); - $set = $ilDB->query($q); - - $mobs = array(); - while($rec = $ilDB->fetchAssoc($set)) - { - $mob_id = ilMediaItem::_lookupMobId($rec["item_id"]); - $mobs[$mob_id] = $mob_id; - } - - return $mobs; - } - - /** - * Get all highlight modes - * - * @param - * @return - */ - static function getAllHighlightModes() - { - global $DIC; - - $lng = $DIC->language(); - - return array( - self::HL_NONE => $lng->txt("cont_none"), - self::HL_HOVER => $lng->txt("cont_hover"), - self::HL_ALWAYS => $lng->txt("cont_always") - ); - - } - - - /** - * Set highlight mode - * - * @param string $a_val highlight mode - */ - function setHighlightMode($a_val) - { - $this->highlight_mode = $a_val; - } - - /** - * Get highlight mode - * - * @return string highlight mode - */ - function getHighlightMode() - { - return $this->highlight_mode; - } - - /** - * Get all highlight classes - * - * @return array - */ - static function getAllHighlightClasses() - { - global $DIC; - - $lng = $DIC->language(); - - return array( - self::HLCL_ACCENTED => $lng->txt("cont_accented"), - self::HLCL_LIGHT => $lng->txt("cont_light"), - self::HLCL_DARK => $lng->txt("cont_dark"), - ); - } - - /** - * Set highlight class - * - * @param string $a_val highlight class - */ - function setHighlightClass($a_val) - { - $this->highlight_class = $a_val; - } - - /** - * Get highlight class - * - * @return string highlight class - */ - function getHighlightClass() - { - return $this->highlight_class; - } - - /** - * set media item id - * - * @param int $a_item_id media item id - */ - function setItemId($a_item_id) - { - $this->item_id = $a_item_id; - } - - /** - * get item id - * - * @return int media item id - */ - function getItemId() - { - return $this->item_id; - } - - /** - * set area number - * - * @param int $a_nr number (of area within parent media object) - */ - function setNr($a_nr) - { - $this->nr = $a_nr; - } - - /** - * get area number - * - * @return int number (of area within parent media object) - */ - function getNr() - { - return $this->nr; - } - - /** - * set shape (IL_AREA_RECT, IL_AREA_CIRCLE, IL_AREA_POLY, IL_AREA_WHOLE_PICTURE) - * - * @param string $a_shape shape of map area - */ - function setShape($a_shape) - { - $this->shape = $a_shape; - } - - /** - * get shape - * - * @return string (IL_AREA_RECT, IL_AREA_CIRCLE, IL_AREA_POLY, IL_AREA_WHOLE_PICTURE) - */ - function getShape() - { - return $this->shape; - } - - /** - * set coords of area - * - * @param string $a_coords coords (comma separated integers) - */ - function setCoords($a_coords) - { - $this->coords = $a_coords; - } - - /** - * get coords - * - * @return string coords (comma separated integers) - */ - function getCoords() - { - return $this->coords; - } - - /** - * set (tooltip)title of area - * - * @param string $a_title title - */ - function setTitle($a_title) - { - $this->title = $a_title; - } - - /** - * append string to (tooltip) title of area - * - * @param string $a_title_str title string - */ - function appendTitle($a_title_str) - { - $this->title.= $a_title_str; - } - - /** - * get (tooltip) title - * - * @return string title - */ - function getTitle() - { - return $this->title; - } - - /** - * set link type - * - * @param string $a_linktype link type (IL_INT_LINK, IL_EXT_LINK) - */ - function setLinkType($a_link_type) - { - $this->linktype = $a_link_type; - } - - /** - * get link type - * - * @return int link type (IL_INT_LINK, IL_EXT_LINK) - */ - function getLinkType() - { - return $this->linktype; - } - - /** - * set hyper reference (external link only) - * - * @param string $a_href hyper ref url - */ - function setHref($a_href) - { - $this->xl_href = $a_href; - } - - /** - * get hyper reference url (external link only) - * - * @param string hyper ref url - */ - function getHref() - { - return $this->xl_href; - } - - /** - * set link text (external link only) - * - * @param string $a_title link text - */ - function setExtTitle($a_title) - { - $this->xl_title = $a_title; - } - - /** - * get link text (external link only) - * - * @return string link text - */ - function getExtTitle() - { - return $this->xl_title; - } - - /** - * set link target (internal link only) - * - * @param string $a_target link target (e.g. "il__pg_23") - */ - function setTarget($a_target) - { - $this->il_target = $a_target; - } - - /** - * get link target (internal link only) - * - * @return string link target - */ - function getTarget($a_insert_inst = false) - { - $target = $this->il_target; - - if ((substr($target, 0, 4) == "il__") && $a_insert_inst) - { - $target = "il_".IL_INST_ID."_".substr($target, 4, strlen($target) - 4); - } - - return $target; - } - - /** - * set link type (internal link only) - * - * @param string $a_type link type - * (IL_LT_STRUCTURE | IL_LT_PAGE | IL_LT_MEDIA | IL_LT_GLITEM) - */ - function setType($a_type) - { - $this->il_type = $a_type; - } - - /** - * get link type (internal link only) - * - * @return string (IL_LT_STRUCTURE | IL_LT_PAGE | IL_LT_MEDIA | IL_LT_GLITEM) - */ - function getType() - { - return $this->il_type; - } - - /** - * set link target frame (internal link only) - * - * @param string $a_target_frame target frame (IL_TF_MEDIA | - * IL_TF_FAQ | IL_TF_GLOSSARY | IL_TF_NEW) - */ - function setTargetFrame($a_target_frame) - { - $this->il_target_frame = $a_target_frame; - } - - /** - * get link target frame (internal link only) - * - * @return string link target frame target frame (IL_TF_MEDIA | - * IL_TF_FAQ | IL_TF_GLOSSARY | IL_TF_NEW) - */ - function getTargetFrame() - { - return $this->il_target_frame; - } - - /** - * draw image to - * - * @param boolean $a_close_poly close polygon - */ - function draw(&$a_image, $a_col1, $a_col2, $a_close_poly = true, - $a_x_ratio = 1, $a_y_ratio = 1) - { - switch ($this->getShape()) - { - case "Rect" : - $this->drawRect($a_image, $this->getCoords(), $a_col1, $a_col2, - $a_x_ratio, $a_y_ratio); - break; - - case "Circle" : - $this->drawCircle($a_image, $this->getCoords(), $a_col1, $a_col2, - $a_x_ratio, $a_y_ratio); - break; - - case "Poly" : - $this->drawPoly($a_image, $this->getCoords(), $a_col1, $a_col2, $a_close_poly, - $a_x_ratio, $a_y_ratio); - break; - } - } - - /** - * draws an outlined two color line in an image - * - * @param int $im image identifier as returned by ImageCreateFromGIF() etc. - * @param int $x1 x-coordinate of starting point - * @param int $y1 y-coordinate of starting point - * @param int $x2 x-coordinate of ending point - * @param int $y2 y-coordinate of ending point - * @param int $c1 color identifier 1 - * @param int $c2 color identifier 2 - */ - function drawLine(&$im, $x1, $y1, $x2, $y2, $c1, $c2) - { - imageline($im, $x1+1, $y1, $x2+1, $y2, $c1); - imageline($im, $x1-1, $y1, $x2-1, $y2, $c1); - imageline($im, $x1, $y1+1, $x2, $y2+1, $c1); - imageline($im, $x1, $y1-1, $x2, $y2-1, $c1); - imageline($im, $x1, $y1, $x2, $y2, $c2); - } - - /** - * draws an outlined two color rectangle - * - * @param int $im image identifier as returned by ImageCreateFromGIF() etc. - * @param string $coords coordinate string, format : "x1,y1,x2,y2" with (x1,y1) is top left - * and (x2,y2) is bottom right point of the rectangle - * @param int $c1 color identifier 1 - * @param int $c2 color identifier 2 - */ - function drawRect(&$im,$coords,$c1,$c2,$a_x_ratio = 1, $a_y_ratio = 1) - { - $coord=explode(",", $coords); - - $this->drawLine($im, $coord[0] / $a_x_ratio, $coord[1] / $a_y_ratio, - $coord[0] / $a_x_ratio, $coord[3] / $a_y_ratio, $c1, $c2); - $this->drawLine($im, $coord[0] / $a_x_ratio, $coord[3] / $a_y_ratio, - $coord[2] / $a_x_ratio, $coord[3] / $a_y_ratio, $c1, $c2); - $this->drawLine($im, $coord[2] / $a_x_ratio, $coord[3] / $a_y_ratio, - $coord[2] / $a_x_ratio, $coord[1] / $a_y_ratio, $c1, $c2); - $this->drawLine($im, $coord[2] / $a_x_ratio, $coord[1] / $a_y_ratio, - $coord[0] / $a_x_ratio, $coord[1] / $a_y_ratio, $c1, $c2); - } - - - /** - * draws an outlined two color polygon - * - * @param int $im image identifier as returned by ImageCreateFromGIF() etc. - * @param string $coords coordinate string, format : "x1,y1,x2,y2,..." with every (x,y) pair is - * an ending point of a line of the polygon - * @param int $c1 color identifier 1 - * @param int $c3 color identifier 2 - * @param boolean $closed true: the first and the last point will be connected with a line - */ - function drawPoly(&$im, $coords, $c1, $c2, $closed,$a_x_ratio = 1, $a_y_ratio = 1) - { - if ($closed) - { - $p = 0; - } - else - { - $p = 1; - } - - $anz = ilMapArea::countCoords($coords); - - if ($anz < (3 - $p)) - { - return; - } - - $c = explode(",", $coords); - - for($i=0; $i<$anz-$p; $i++) - { - $this->drawLine($im, $c[$i*2] / $a_x_ratio, $c[$i*2+1] / $a_y_ratio, - $c[($i*2+2)%(2*$anz)] / $a_x_ratio, - $c[($i*2+3)%(2*$anz)] / $a_y_ratio, $c1, $c2); - } - } - - - /** - * draws an outlined two colored circle - * - * @param int $im image identifier as returned by ImageCreateFromGIF() - * @param string $coords coordinate string, format : "x,y,r" with (x,y) as center point - * and r as radius - * @param int $c1 color identifier 1 - * @param int $c3 color identifier 2 - */ - function drawCircle(&$im, $coords, $c1, $c2,$a_x_ratio = 1, $a_y_ratio = 1) - { - $c = explode(",", $coords); - imagearc($im, $c[0] / $a_x_ratio, $c[1] / $a_y_ratio, - ($c[2]+1)*2 / $a_x_ratio, ($c[2]+1)*2 / $a_y_ratio, 1, 360, $c1); - imagearc($im, $c[0] / $a_x_ratio, $c[1] / $a_y_ratio, - ($c[2]-1)*2 / $a_x_ratio, ($c[2]-1)*2 / $a_y_ratio, 1, 360, $c1); - imagearc($im, $c[0] / $a_x_ratio, $c[1] / $a_y_ratio, - $c[2]*2 / $a_x_ratio, $c[2]*2 / $a_y_ratio, 1, 360, $c2); - } - - /** - * count the number of coordinates (x,y) in a coordinate string (format: "x1,y1,x2,y2,x3,y3,...") - * - * @param string $c coordinate string - * @return int number of coordinates - */ - static function countCoords($c) - { - if ($c == "") - { - return 0; - } - else - { - $coord_array = explode(",", $c); - return (count($coord_array) / 2); - } - } - + /** + * @var ilDB + */ + protected $db; + + const HL_NONE = ""; + const HL_HOVER = "Hover"; + const HL_ALWAYS = "Always"; + const HLCL_ACCENTED = ""; + const HLCL_LIGHT = "Light"; + const HLCL_DARK = "Dark"; + + public $item_id; + public $nr; + public $shape; + public $coords; + public $title; + public $linktype; + public $xl_title; + public $xl_href; + public $il_target; + public $il_type; + public $il_target_frame; + + + /** + * map area + * + * @param int $a_item_id parent media item id + * @param int $a_nr map area number within media item + */ + public function __construct($a_item_id = 0, $a_nr = 0) + { + global $DIC; + + $this->db = $DIC->database(); + $this->title = ""; + if ($a_item_id !=0 && $a_nr != 0) { + $this->setItemId($a_item_id); + $this->setNr($a_nr); + $this->read(); + } + } + + /** + * create persistent map area object in db + */ + public function create() + { + $ilDB = $this->db; + + $q = "INSERT INTO map_area (item_id, nr, shape, " . + "coords, link_type, title, href, target, type, highlight_mode, highlight_class, target_frame) " . + " VALUES (" . + $ilDB->quote($this->getItemId(), "integer") . "," . + $ilDB->quote($this->getNr(), "integer") . "," . + $ilDB->quote($this->getShape(), "text") . "," . + $ilDB->quote($this->getCoords(), "text") . "," . + $ilDB->quote($this->getLinkType(), "text") . "," . + $ilDB->quote($this->getTitle(), "text") . "," . + $ilDB->quote($this->getHref(), "text") . "," . + $ilDB->quote($this->getTarget(), "text") . "," . + $ilDB->quote($this->getType(), "text") . "," . + $ilDB->quote($this->getHighlightMode(), "text") . "," . + $ilDB->quote($this->getHighlightClass(), "text") . "," . + $ilDB->quote($this->getTargetFrame(), "text") . ")"; + $ilDB->manipulate($q); + } + + /** + * get maximum nr of media item (static) + * + * @param int $a_item_id item id + * + * @return int maximum nr + */ + public static function _getMaxNr($a_item_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "SELECT max(nr) AS max_nr FROM map_area WHERE item_id = " . + $ilDB->quote($a_item_id, "integer"); + $max_set = $ilDB->query($q); + $max_rec = $ilDB->fetchAssoc($max_set); + + return $max_rec["max_nr"]; + } + + /** + * read map area data into object (item id and nr must be set) + */ + public function read() + { + $ilDB = $this->db; + + $q = "SELECT * FROM map_area WHERE item_id = " . + $ilDB->quote($this->getItemId(), "integer") . + " AND nr = " . $ilDB->quote($this->getNr(), "integer"); + $area_set = $ilDB->query($q); + $area_rec = $ilDB->fetchAssoc($area_set); + + $this->setShape($area_rec["shape"]); + //echo $area_rec["Shape"]; + $this->setNr($area_rec["nr"]); + $this->setCoords($area_rec["coords"]); + $this->setLinkType($area_rec["link_type"]); + $this->setTitle($area_rec["title"]); + $this->setHref($area_rec["href"]); + $this->setTarget($area_rec["target"]); + $this->setType($area_rec["type"]); + $this->setTargetFrame($area_rec["target_frame"]); + $this->setHighlightMode($area_rec["highlight_mode"]); + $this->setHighlightClass($area_rec["highlight_class"]); + } + + /** + * update map area + */ + public function update() + { + $ilDB = $this->db; + + $q = "UPDATE map_area SET shape = " . $ilDB->quote($this->getShape(), "text") . + ", coords = " . $ilDB->quote($this->getCoords(), "text") . + ", link_type = " . $ilDB->quote($this->getLinkType(), "text") . + ", title = " . $ilDB->quote($this->getTitle(), "text") . + ", href = " . $ilDB->quote($this->getHref(), "text") . + ", target = " . $ilDB->quote($this->getTarget(), "text") . + ", type = " . $ilDB->quote($this->getType(), "text") . + ", highlight_mode = " . $ilDB->quote($this->getHighlightMode(), "text") . + ", highlight_class = " . $ilDB->quote($this->getHighlightClass(), "text") . + ", target_frame = " . $ilDB->quote($this->getTargetFrame(), "text") . + " WHERE item_id = " . $ilDB->quote($this->getItemId(), "integer") . + " AND nr = " . $ilDB->quote($this->getNr(), "integer"); + $ilDB->manipulate($q); + } + + /** + * resolve internal links of an item id + */ + public static function _resolveIntLinks($a_item_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + //echo "maparea::resolve
                  "; + $q = "SELECT * FROM map_area WHERE item_id = " . + $ilDB->quote($a_item_id, "integer"); + $area_set = $ilDB->query($q); + while ($area_rec = $ilDB->fetchAssoc($area_set)) { + $target = $area_rec["target"]; + $type = $area_rec["type"]; + $item_id = $area_rec["item_id"]; + $nr = $area_rec["nr"]; + + if (($area_rec["link_type"] == IL_INT_LINK) && (!is_int(strpos($target, "__")))) { + $new_target = ilInternalLink::_getIdForImportId($type, $target); + if ($new_target !== false) { + $query = "UPDATE map_area SET " . + "target = " . $ilDB->quote($new_target, "text") . " " . + "WHERE item_id = " . $ilDB->quote($item_id, "integer") . + " AND nr = " . $ilDB->quote($nr, "integer"); + $ilDB->manipulate($query); + } + } + } + } + + /** + * get all internal links of a media items map areas + * + * @param int $a_item_id media item id + */ + public static function _getIntLinks($a_item_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "SELECT * FROM map_area WHERE item_id = " . + $ilDB->quote($a_item_id, "integer"); + $area_set = $ilDB->query($q); + + $links = array(); + + while ($area_rec = $ilDB->fetchAssoc($area_set)) { + $target = $area_rec["target"]; + $type = $area_rec["type"]; + $targetframe = $area_rec["target_frame"]; + + if (($area_rec["link_type"] == IL_INT_LINK) && (is_int(strpos($target, "__")))) { + $links[$target . ":" . $type . ":" . $targetframe] = + array("Target" => $target, "Type" => $type, + "TargetFrame" => $targetframe); + } + } + return $links; + } + + /** + * Get areas for a certain target + */ + public static function _getMobsForTarget($a_type, $a_target) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "SELECT * FROM map_area WHERE " . + " link_type = " . $ilDB->quote($a_type, "text") . + " AND target = " . $ilDB->quote($a_target, "text"); + $set = $ilDB->query($q); + + $mobs = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $mob_id = ilMediaItem::_lookupMobId($rec["item_id"]); + $mobs[$mob_id] = $mob_id; + } + + return $mobs; + } + + /** + * Get all highlight modes + * + * @param + * @return + */ + public static function getAllHighlightModes() + { + global $DIC; + + $lng = $DIC->language(); + + return array( + self::HL_NONE => $lng->txt("cont_none"), + self::HL_HOVER => $lng->txt("cont_hover"), + self::HL_ALWAYS => $lng->txt("cont_always") + ); + } + + + /** + * Set highlight mode + * + * @param string $a_val highlight mode + */ + public function setHighlightMode($a_val) + { + $this->highlight_mode = $a_val; + } + + /** + * Get highlight mode + * + * @return string highlight mode + */ + public function getHighlightMode() + { + return $this->highlight_mode; + } + + /** + * Get all highlight classes + * + * @return array + */ + public static function getAllHighlightClasses() + { + global $DIC; + + $lng = $DIC->language(); + + return array( + self::HLCL_ACCENTED => $lng->txt("cont_accented"), + self::HLCL_LIGHT => $lng->txt("cont_light"), + self::HLCL_DARK => $lng->txt("cont_dark"), + ); + } + + /** + * Set highlight class + * + * @param string $a_val highlight class + */ + public function setHighlightClass($a_val) + { + $this->highlight_class = $a_val; + } + + /** + * Get highlight class + * + * @return string highlight class + */ + public function getHighlightClass() + { + return $this->highlight_class; + } + + /** + * set media item id + * + * @param int $a_item_id media item id + */ + public function setItemId($a_item_id) + { + $this->item_id = $a_item_id; + } + + /** + * get item id + * + * @return int media item id + */ + public function getItemId() + { + return $this->item_id; + } + + /** + * set area number + * + * @param int $a_nr number (of area within parent media object) + */ + public function setNr($a_nr) + { + $this->nr = $a_nr; + } + + /** + * get area number + * + * @return int number (of area within parent media object) + */ + public function getNr() + { + return $this->nr; + } + + /** + * set shape (IL_AREA_RECT, IL_AREA_CIRCLE, IL_AREA_POLY, IL_AREA_WHOLE_PICTURE) + * + * @param string $a_shape shape of map area + */ + public function setShape($a_shape) + { + $this->shape = $a_shape; + } + + /** + * get shape + * + * @return string (IL_AREA_RECT, IL_AREA_CIRCLE, IL_AREA_POLY, IL_AREA_WHOLE_PICTURE) + */ + public function getShape() + { + return $this->shape; + } + + /** + * set coords of area + * + * @param string $a_coords coords (comma separated integers) + */ + public function setCoords($a_coords) + { + $this->coords = $a_coords; + } + + /** + * get coords + * + * @return string coords (comma separated integers) + */ + public function getCoords() + { + return $this->coords; + } + + /** + * set (tooltip)title of area + * + * @param string $a_title title + */ + public function setTitle($a_title) + { + $this->title = $a_title; + } + + /** + * append string to (tooltip) title of area + * + * @param string $a_title_str title string + */ + public function appendTitle($a_title_str) + { + $this->title.= $a_title_str; + } + + /** + * get (tooltip) title + * + * @return string title + */ + public function getTitle() + { + return $this->title; + } + + /** + * set link type + * + * @param string $a_linktype link type (IL_INT_LINK, IL_EXT_LINK) + */ + public function setLinkType($a_link_type) + { + $this->linktype = $a_link_type; + } + + /** + * get link type + * + * @return int link type (IL_INT_LINK, IL_EXT_LINK) + */ + public function getLinkType() + { + return $this->linktype; + } + + /** + * set hyper reference (external link only) + * + * @param string $a_href hyper ref url + */ + public function setHref($a_href) + { + $this->xl_href = $a_href; + } + + /** + * get hyper reference url (external link only) + * + * @param string hyper ref url + */ + public function getHref() + { + return $this->xl_href; + } + + /** + * set link text (external link only) + * + * @param string $a_title link text + */ + public function setExtTitle($a_title) + { + $this->xl_title = $a_title; + } + + /** + * get link text (external link only) + * + * @return string link text + */ + public function getExtTitle() + { + return $this->xl_title; + } + + /** + * set link target (internal link only) + * + * @param string $a_target link target (e.g. "il__pg_23") + */ + public function setTarget($a_target) + { + $this->il_target = $a_target; + } + + /** + * get link target (internal link only) + * + * @return string link target + */ + public function getTarget($a_insert_inst = false) + { + $target = $this->il_target; + + if ((substr($target, 0, 4) == "il__") && $a_insert_inst) { + $target = "il_" . IL_INST_ID . "_" . substr($target, 4, strlen($target) - 4); + } + + return $target; + } + + /** + * set link type (internal link only) + * + * @param string $a_type link type + * (IL_LT_STRUCTURE | IL_LT_PAGE | IL_LT_MEDIA | IL_LT_GLITEM) + */ + public function setType($a_type) + { + $this->il_type = $a_type; + } + + /** + * get link type (internal link only) + * + * @return string (IL_LT_STRUCTURE | IL_LT_PAGE | IL_LT_MEDIA | IL_LT_GLITEM) + */ + public function getType() + { + return $this->il_type; + } + + /** + * set link target frame (internal link only) + * + * @param string $a_target_frame target frame (IL_TF_MEDIA | + * IL_TF_FAQ | IL_TF_GLOSSARY | IL_TF_NEW) + */ + public function setTargetFrame($a_target_frame) + { + $this->il_target_frame = $a_target_frame; + } + + /** + * get link target frame (internal link only) + * + * @return string link target frame target frame (IL_TF_MEDIA | + * IL_TF_FAQ | IL_TF_GLOSSARY | IL_TF_NEW) + */ + public function getTargetFrame() + { + return $this->il_target_frame; + } + + /** + * draw image to + * + * @param boolean $a_close_poly close polygon + */ + public function draw( + &$a_image, + $a_col1, + $a_col2, + $a_close_poly = true, + $a_x_ratio = 1, + $a_y_ratio = 1 + ) { + switch ($this->getShape()) { + case "Rect": + $this->drawRect( + $a_image, + $this->getCoords(), + $a_col1, + $a_col2, + $a_x_ratio, + $a_y_ratio + ); + break; + + case "Circle": + $this->drawCircle( + $a_image, + $this->getCoords(), + $a_col1, + $a_col2, + $a_x_ratio, + $a_y_ratio + ); + break; + + case "Poly": + $this->drawPoly( + $a_image, + $this->getCoords(), + $a_col1, + $a_col2, + $a_close_poly, + $a_x_ratio, + $a_y_ratio + ); + break; + } + } + + /** + * draws an outlined two color line in an image + * + * @param int $im image identifier as returned by ImageCreateFromGIF() etc. + * @param int $x1 x-coordinate of starting point + * @param int $y1 y-coordinate of starting point + * @param int $x2 x-coordinate of ending point + * @param int $y2 y-coordinate of ending point + * @param int $c1 color identifier 1 + * @param int $c2 color identifier 2 + */ + public function drawLine(&$im, $x1, $y1, $x2, $y2, $c1, $c2) + { + imageline($im, $x1+1, $y1, $x2+1, $y2, $c1); + imageline($im, $x1-1, $y1, $x2-1, $y2, $c1); + imageline($im, $x1, $y1+1, $x2, $y2+1, $c1); + imageline($im, $x1, $y1-1, $x2, $y2-1, $c1); + imageline($im, $x1, $y1, $x2, $y2, $c2); + } + + /** + * draws an outlined two color rectangle + * + * @param int $im image identifier as returned by ImageCreateFromGIF() etc. + * @param string $coords coordinate string, format : "x1,y1,x2,y2" with (x1,y1) is top left + * and (x2,y2) is bottom right point of the rectangle + * @param int $c1 color identifier 1 + * @param int $c2 color identifier 2 + */ + public function drawRect(&$im, $coords, $c1, $c2, $a_x_ratio = 1, $a_y_ratio = 1) + { + $coord=explode(",", $coords); + + $this->drawLine( + $im, + $coord[0] / $a_x_ratio, + $coord[1] / $a_y_ratio, + $coord[0] / $a_x_ratio, + $coord[3] / $a_y_ratio, + $c1, + $c2 + ); + $this->drawLine( + $im, + $coord[0] / $a_x_ratio, + $coord[3] / $a_y_ratio, + $coord[2] / $a_x_ratio, + $coord[3] / $a_y_ratio, + $c1, + $c2 + ); + $this->drawLine( + $im, + $coord[2] / $a_x_ratio, + $coord[3] / $a_y_ratio, + $coord[2] / $a_x_ratio, + $coord[1] / $a_y_ratio, + $c1, + $c2 + ); + $this->drawLine( + $im, + $coord[2] / $a_x_ratio, + $coord[1] / $a_y_ratio, + $coord[0] / $a_x_ratio, + $coord[1] / $a_y_ratio, + $c1, + $c2 + ); + } + + + /** + * draws an outlined two color polygon + * + * @param int $im image identifier as returned by ImageCreateFromGIF() etc. + * @param string $coords coordinate string, format : "x1,y1,x2,y2,..." with every (x,y) pair is + * an ending point of a line of the polygon + * @param int $c1 color identifier 1 + * @param int $c3 color identifier 2 + * @param boolean $closed true: the first and the last point will be connected with a line + */ + public function drawPoly(&$im, $coords, $c1, $c2, $closed, $a_x_ratio = 1, $a_y_ratio = 1) + { + if ($closed) { + $p = 0; + } else { + $p = 1; + } + + $anz = ilMapArea::countCoords($coords); + + if ($anz < (3 - $p)) { + return; + } + + $c = explode(",", $coords); + + for ($i=0; $i<$anz-$p; $i++) { + $this->drawLine( + $im, + $c[$i*2] / $a_x_ratio, + $c[$i*2+1] / $a_y_ratio, + $c[($i*2+2)%(2*$anz)] / $a_x_ratio, + $c[($i*2+3)%(2*$anz)] / $a_y_ratio, + $c1, + $c2 + ); + } + } + + + /** + * draws an outlined two colored circle + * + * @param int $im image identifier as returned by ImageCreateFromGIF() + * @param string $coords coordinate string, format : "x,y,r" with (x,y) as center point + * and r as radius + * @param int $c1 color identifier 1 + * @param int $c3 color identifier 2 + */ + public function drawCircle(&$im, $coords, $c1, $c2, $a_x_ratio = 1, $a_y_ratio = 1) + { + $c = explode(",", $coords); + imagearc( + $im, + $c[0] / $a_x_ratio, + $c[1] / $a_y_ratio, + ($c[2]+1)*2 / $a_x_ratio, + ($c[2]+1)*2 / $a_y_ratio, + 1, + 360, + $c1 + ); + imagearc( + $im, + $c[0] / $a_x_ratio, + $c[1] / $a_y_ratio, + ($c[2]-1)*2 / $a_x_ratio, + ($c[2]-1)*2 / $a_y_ratio, + 1, + 360, + $c1 + ); + imagearc( + $im, + $c[0] / $a_x_ratio, + $c[1] / $a_y_ratio, + $c[2]*2 / $a_x_ratio, + $c[2]*2 / $a_y_ratio, + 1, + 360, + $c2 + ); + } + + /** + * count the number of coordinates (x,y) in a coordinate string (format: "x1,y1,x2,y2,x3,y3,...") + * + * @param string $c coordinate string + * @return int number of coordinates + */ + public static function countCoords($c) + { + if ($c == "") { + return 0; + } else { + $coord_array = explode(",", $c); + return (count($coord_array) / 2); + } + } } -?> diff --git a/Services/MediaObjects/classes/class.ilMediaAnalyzer.php b/Services/MediaObjects/classes/class.ilMediaAnalyzer.php index 479bae948c6bb0e7ac2d1dbc66baf868d47f22a8..288968418635895c44b0a6003fda3ac574dfce31 100755 --- a/Services/MediaObjects/classes/class.ilMediaAnalyzer.php +++ b/Services/MediaObjects/classes/class.ilMediaAnalyzer.php @@ -1,24 +1,24 @@ getid3 = new getID3(); - } + public function __construct() + { + $this->getid3 = new getID3(); + } - /** - * Set Full File Path. - * - * @param string $a_file Full File Path - */ - function setFile($a_file) - { - $this->file = $a_file; - } + /** + * Set Full File Path. + * + * @param string $a_file Full File Path + */ + public function setFile($a_file) + { + $this->file = $a_file; + } - /** - * Get Full File Path. - * - * @return string Full File Path - */ - function getFile() - { - return $this->file; - } - - /** - * Get PlaytimeString. - * - * @return string PlaytimeString - */ - function getPlaytimeString() - { - return $this->file_info["playtime_string"]; - } + /** + * Get Full File Path. + * + * @return string Full File Path + */ + public function getFile() + { + return $this->file; + } + + /** + * Get PlaytimeString. + * + * @return string PlaytimeString + */ + public function getPlaytimeString() + { + return $this->file_info["playtime_string"]; + } - /** - * Get PlaytimeSeconds. - * - * @return double PlaytimeSeconds - */ - function getPlaytimeSeconds() - { - return $this->file_info["playtime_seconds"]; - } - - /** - * Analyze current file. - */ - function analyzeFile() - { - $this->file_info = $this->getid3->analyze($this->getFile()); - } + /** + * Get PlaytimeSeconds. + * + * @return double PlaytimeSeconds + */ + public function getPlaytimeSeconds() + { + return $this->file_info["playtime_seconds"]; + } + /** + * Analyze current file. + */ + public function analyzeFile() + { + $this->file_info = $this->getid3->analyze($this->getFile()); + } } -?> diff --git a/Services/MediaObjects/classes/class.ilMediaImageUtil.php b/Services/MediaObjects/classes/class.ilMediaImageUtil.php index 08c8b2a8409ecc7b82cfd4e0037c6f1dbbc40e75..dddf463f3881484471e7f6db92aa8a7ea2241984 100644 --- a/Services/MediaObjects/classes/class.ilMediaImageUtil.php +++ b/Services/MediaObjects/classes/class.ilMediaImageUtil.php @@ -7,67 +7,56 @@ * * @author Alex Killing * @version $Id$ - * @ingroup + * @ingroup */ class ilMediaImageUtil { - /** - * Get image size from location - * - * @param string $a_location - * @return array - */ - static function getImageSize($a_location) - { - if (substr($a_location, 0, 4) == "http") - { - include_once("./Services/WebServices/Curl/classes/class.ilCurlConnection.php"); - if (ilCurlConnection::_isCurlExtensionLoaded()) - { - $dir = ilUtil::getDataDir() . "/temp/mob/remote_img"; - ilUtil::makeDirParents($dir); - $filename = $dir."/".uniqid(); - $file = fopen($filename, "w"); - $c = new ilCurlConnection($a_location); - $c->init(); - require_once './Services/Http/classes/class.ilProxySettings.php'; - if (ilProxySettings::_getInstance()->isActive()) - { - $proxy = ilProxySettings::_getInstance()->getHost(); - if (($p = ilProxySettings::_getInstance()->getPort()) != "") - { - $proxy .= ":" . $p; - } - $c->setOpt(CURLOPT_PROXY, $proxy); - } - $c->setOpt(CURLOPT_SSL_VERIFYHOST, 0); - $c->setOpt(CURLOPT_SSL_VERIFYPEER, 0); - $c->setOpt(CURLOPT_MAXREDIRS, 3); - $c->setOpt(CURLOPT_HEADER, 0); - $c->setOpt(CURLOPT_RETURNTRANSFER, 1); - $c->setOpt(CURLOPT_FILE, $file); - try { - $c->exec(); - $size = @getimagesize($filename); - } - catch (ilCurlConnectionException $e) { - $size = false; - } - $c->close(); - fclose($file); - unlink($filename); - } - else - { - $size = @getimagesize($a_location); - } - } - else - { - $size = @getimagesize($a_location); - } - return $size; - } + /** + * Get image size from location + * + * @param string $a_location + * @return array + */ + public static function getImageSize($a_location) + { + if (substr($a_location, 0, 4) == "http") { + include_once("./Services/WebServices/Curl/classes/class.ilCurlConnection.php"); + if (ilCurlConnection::_isCurlExtensionLoaded()) { + $dir = ilUtil::getDataDir() . "/temp/mob/remote_img"; + ilUtil::makeDirParents($dir); + $filename = $dir . "/" . uniqid(); + $file = fopen($filename, "w"); + $c = new ilCurlConnection($a_location); + $c->init(); + require_once './Services/Http/classes/class.ilProxySettings.php'; + if (ilProxySettings::_getInstance()->isActive()) { + $proxy = ilProxySettings::_getInstance()->getHost(); + if (($p = ilProxySettings::_getInstance()->getPort()) != "") { + $proxy .= ":" . $p; + } + $c->setOpt(CURLOPT_PROXY, $proxy); + } + $c->setOpt(CURLOPT_SSL_VERIFYHOST, 0); + $c->setOpt(CURLOPT_SSL_VERIFYPEER, 0); + $c->setOpt(CURLOPT_MAXREDIRS, 3); + $c->setOpt(CURLOPT_HEADER, 0); + $c->setOpt(CURLOPT_RETURNTRANSFER, 1); + $c->setOpt(CURLOPT_FILE, $file); + try { + $c->exec(); + $size = @getimagesize($filename); + } catch (ilCurlConnectionException $e) { + $size = false; + } + $c->close(); + fclose($file); + unlink($filename); + } else { + $size = @getimagesize($a_location); + } + } else { + $size = @getimagesize($a_location); + } + return $size; + } } - -?> diff --git a/Services/MediaObjects/classes/class.ilMediaItem.php b/Services/MediaObjects/classes/class.ilMediaItem.php index 71c5eb63c7a52239dae7c029a0c546fc4dd94d05..1fa7f32a5a8def31208ba09644043af76c36dcb4 100755 --- a/Services/MediaObjects/classes/class.ilMediaItem.php +++ b/Services/MediaObjects/classes/class.ilMediaItem.php @@ -15,1283 +15,1222 @@ require_once("Services/MediaObjects/classes/class.ilMapArea.php"); */ class ilMediaItem { - /** - * @var ilDB - */ - protected $db; - - /** - * @var ilLanguage - */ - protected $lng; - - var $id; - var $purpose; - var $location; - var $location_type; - var $format; - var $width; - var $height; - var $caption; - var $halign; - var $parameters; - var $mob_id; - var $nr; - var $mapareas; - var $map_cnt; - var $map_image; // image map work copy image - var $color1; // map area line color 1 - var $color2; // map area line color 2 - - /** - * @var string - */ - protected $upload_hash; - - function __construct($a_id = 0) - { - global $DIC; - - $this->db = $DIC->database(); - $this->lng = $DIC->language(); - $this->parameters = array(); - $this->mapareas = array(); - $this->map_cnt = 0; - - if ($a_id != 0) - { - $this->setId($a_id); - $this->read(); - } - } - - /** - * set media item id - * - * @param int $a_id media item id - */ - function setId($a_id) - { - $this->id = $a_id; - } - - /** - * get media item id - * - * @return int media item id - */ - function getId() - { - return $this->id; - } - - /** - * set id of parent media object - * - * @param int $a_mob_id media object id - */ - function setMobId($a_mob_id) - { - $this->mob_id = $a_mob_id; - } - - /** - * get id of parent media object - * - * @return int media object id - */ - function getMobId() - { - return $this->mob_id; - } - - /** - * set number of media item within media object - */ - function setNr($a_nr) - { - $this->nr = $a_nr; - } - - function getNr() - { - return $this->nr; - } - - /** - * Set text representation - * - * @param string text representation - */ - function setTextRepresentation($a_val) - { - $this->text_representation = $a_val; - } - - /** - * Get text representation - * - * @return string text representation - */ - function getTextRepresentation() - { - return $this->text_representation; - } - - /** - * Set upload hash - * - * @param string $a_val upload hash - */ - function setUploadHash($a_val) - { - $this->upload_hash = $a_val; - } - - /** - * Get upload hash - * - * @return string upload hash - */ - function getUploadHash() - { - return $this->upload_hash; - } - - - /** - * create persistent media item - */ - function create() - { - $ilDB = $this->db; - - $item_id = $ilDB->nextId("media_item"); - $query = "INSERT INTO media_item (id,mob_id, purpose, location, ". - "location_type, format, width, ". - "height, halign, caption, nr, text_representation, upload_hash) VALUES ". - "(". - $ilDB->quote($item_id, "integer").",". - $ilDB->quote($this->getMobId(), "integer").",". - $ilDB->quote($this->getPurpose(), "text").",". - $ilDB->quote($this->getLocation(), "text").",". - $ilDB->quote($this->getLocationType(), "text").",". - $ilDB->quote($this->getFormat(), "text").",". - $ilDB->quote($this->getWidth(), "text").",". - $ilDB->quote($this->getHeight(), "text").",". - $ilDB->quote($this->getHAlign(), "text").",". - $ilDB->quote($this->getCaption(), "text").",". - $ilDB->quote($this->getNr(), "integer").",". - $ilDB->quote($this->getTextRepresentation(), "text").",". - $ilDB->quote($this->getUploadHash(), "text"). - ")"; - $ilDB->manipulate($query); - - $this->setId($item_id); - - // create mob parameters - $params = $this->getParameters(); - foreach($params as $name => $value) - { - $query = "INSERT INTO mob_parameter (med_item_id, name, value) VALUES ". - "(".$ilDB->quote($item_id, "integer").",". - $ilDB->quote($name, "text").",". - $ilDB->quote($value, "text").")"; - $ilDB->manipulate($query); - } - - // create map areas - for ($i=0; $i < count($this->mapareas); $i++) - { - if (is_object($this->mapareas[$i])) - { - $this->mapareas[$i]->setItemId($this->getId()); - $this->mapareas[$i]->setNr($i + 1); - $this->mapareas[$i]->create(); - } - } - } - - /** - * update media item data (without map areas!) - */ - function update() - { - $ilDB = $this->db; - - $query = "UPDATE media_item SET ". - " mob_id = ".$ilDB->quote($this->getMobId(), "integer").",". - " purpose = ".$ilDB->quote($this->getPurpose(), "text").",". - " location = ".$ilDB->quote($this->getLocation(), "text").",". - " location_type = ".$ilDB->quote($this->getLocationType(), "text").",". - " format = ".$ilDB->quote($this->getFormat(), "text").",". - " width = ".$ilDB->quote($this->getWidth(), "text").",". - " height = ".$ilDB->quote($this->getHeight(), "text").",". - " halign = ".$ilDB->quote($this->getHAlign(), "text").",". - " caption = ".$ilDB->quote($this->getCaption(), "text").",". - " nr = ".$ilDB->quote($this->getNr(), "integer").",". - " text_representation = ".$ilDB->quote($this->getTextRepresentation(), "text").",". - " upload_hash = ".$ilDB->quote($this->getUploadHash(), "text"). - " WHERE id = ".$ilDB->quote($this->getId(), "integer"); - $ilDB->manipulate($query); - - // delete mob parameters - $query = "DELETE FROM mob_parameter WHERE med_item_id = ". - $ilDB->quote($this->getId(), "integer"); - - // create mob parameters - $params = $this->getParameters(); - foreach($params as $name => $value) - { - $query = "INSERT INTO mob_parameter (med_item_id, name, value) VALUES ". - "(".$ilDB->quote($this->getId(), "integer").",". - $ilDB->quote($name, "text").",". - $ilDB->quote($value, "text").")"; - $ilDB->manipulate($query); - } - } - - /** - * Write parameter - * - * @param - * @return - */ - function writeParameter($a_name, $a_value) - { - $ilDB = $this->db; - - $query = "INSERT INTO mob_parameter (med_item_id, name, value) VALUES ". - "(".$ilDB->quote($this->getId(), "integer").",". - $ilDB->quote($a_name, "text").",". - $ilDB->quote($a_value, "text").")"; - $ilDB->manipulate($query); - } - - /** - * read media item data (item id or (mob_id and nr) must be set) - */ - function read() - { - $ilDB = $this->db; - - $item_id = $this->getId(); - $mob_id = $this->getMobId(); - $nr = $this->getNr(); - $query = ""; - if($item_id > 0) - { - $query = "SELECT * FROM media_item WHERE id = ". - $ilDB->quote($this->getId(), "integer"); - } - else if ($mob_id > 0 && $nr > 0) - { - $query = "SELECT * FROM media_item WHERE mob_id = ". - $ilDB->quote($this->getMobId(), "integer")." ". - "AND nr=".$ilDB->quote($this->getNr(), "integer"); - } - if ($query != "") - { - $item_set = $ilDB->query($query); - $item_rec = $ilDB->fetchAssoc($item_set); - - $this->setLocation($item_rec["location"]); - $this->setLocationType($item_rec["location_type"]); - $this->setFormat($item_rec["format"]); - $this->setWidth($item_rec["width"]); - $this->setHeight($item_rec["height"]); - $this->setHAlign($item_rec["halign"]); - $this->setCaption($item_rec["caption"]); - $this->setPurpose($item_rec["purpose"]); - $this->setNr($item_rec["nr"]); - $this->setMobId($item_rec["mob_id"]); - $this->setId($item_rec["id"]); - $this->setThumbTried($item_rec["tried_thumb"]); - $this->setTextRepresentation($item_rec["text_representation"]); - $this->setUploadHash($item_rec["upload_hash"]); - - // get item parameter - $query = "SELECT * FROM mob_parameter WHERE med_item_id = ". - $ilDB->quote($this->getId(), "integer"); - $par_set = $ilDB->query($query); - while ($par_rec = $ilDB->fetchAssoc($par_set)) - { - $this->setParameter($par_rec["name"], $par_rec["value"]); - } - - // get item map areas - $max = ilMapArea::_getMaxNr($this->getId()); - for ($i = 1; $i <= $max; $i++) - { - $area = new ilMapArea($this->getId(), $i); - $this->addMapArea($area); - } - } - - } - - /** - * write thumbnail creation try data ("y"/"n") - */ - function writeThumbTried($a_tried) - { - $ilDB = $this->db; - - $q = "UPDATE media_item SET tried_thumb = ". - $ilDB->quote($a_tried, "text"). - " WHERE id = ".$ilDB->quote($this->getId(), "integer"); - - $ilDB->manipulate($q); - } - - /** - * Lookup location for mob id - * - * @param int $a_mob_id media object id - * @param string $a_purpose purpose - */ - static function _lookupLocationForMobId($a_mob_id, $a_purpose) - { - global $DIC; - - $ilDB = $DIC->database(); - - // read media_object record - $query = "SELECT * FROM media_item WHERE mob_id = ". - $ilDB->quote($a_mob_id, "integer")." ". - "AND purpose = ".$ilDB->quote($a_purpose, "text"); - $set = $ilDB->query($query); - if ($rec = $ilDB->fetchAssoc($set)) - { - return $rec["location"]; - } - - return ""; - } - - /** - * Lookup Mob ID - * - * @param int $a_med_id media item id - */ - static function _lookupMobId($a_med_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - // read media_object record - $query = "SELECT * FROM media_item WHERE id = ". - $ilDB->quote($a_med_id, "integer"); - $set = $ilDB->query($query); - if ($rec = $ilDB->fetchAssoc($set)) - { - return $rec["mob_id"]; - } - - return ""; - } - - /* read media item with specific purpose and mobId - * - * @param integer $a_mobId media object id - * @param string $a_purpose media object purpose - * @return array $mob media object - */ - static function _getMediaItemsOfMObId($a_mobId, $a_purpose) - { - global $DIC; - - $ilDB = $DIC->database(); - - // read media_object record - $query = "SELECT * FROM media_item WHERE mob_id = ". - $ilDB->quote($a_mobId, "integer")." ". - "AND purpose=" . $ilDB->quote($a_purpose, "text")." ORDER BY nr"; - $item_set = $ilDB->query($query); - - while ($item_rec = $ilDB->fetchAssoc($item_set)) - { - return $item_rec; - } - return false; - } - - /** - * read media items into media objects (static) - * - * @param object $a_mob media object - */ - static function _getMediaItemsOfMOb(&$a_mob) - { - global $DIC; - - $ilDB = $DIC->database(); - - // read media_object record - $query = "SELECT * FROM media_item WHERE mob_id = ". - $ilDB->quote($a_mob->getId(), "integer")." ". - "ORDER BY nr"; - $item_set = $ilDB->query($query); - while ($item_rec = $ilDB->fetchAssoc($item_set)) - { - $media_item = new ilMediaItem(); - $media_item->setNr($item_rec["nr"]); - $media_item->setId($item_rec["id"]); - $media_item->setLocation($item_rec["location"]); - $media_item->setLocationType($item_rec["location_type"]); - $media_item->setFormat($item_rec["format"]); - $media_item->setWidth($item_rec["width"]); - $media_item->setHeight($item_rec["height"]); - $media_item->setHAlign($item_rec["halign"]); - $media_item->setCaption($item_rec["caption"]); - $media_item->setPurpose($item_rec["purpose"]); - $media_item->setMobId($item_rec["mob_id"]); - $media_item->setThumbTried($item_rec["tried_thumb"]); - $media_item->setTextRepresentation($item_rec["text_representation"]); - $media_item->setUploadHash($item_rec["upload_hash"]); - - // get item parameter - $query = "SELECT * FROM mob_parameter WHERE med_item_id = ". - $ilDB->quote($item_rec["id"], "integer"); - $par_set = $ilDB->query($query); - while ($par_rec = $ilDB->fetchAssoc($par_set)) - { - $media_item->setParameter($par_rec["name"], $par_rec["value"]); - } - - // get item map areas - $max = ilMapArea::_getMaxNr($media_item->getId()); - for ($i = 1; $i <= $max; $i++) - { - $area = new ilMapArea($media_item->getId(), $i); - $media_item->addMapArea($area); - } - - // add media item to media object - $a_mob->addMediaItem($media_item); - } - } - - /** - * Delete all items of a mob - * - * @param int $a_mob_id media object id - */ - static function deleteAllItemsOfMob($a_mob_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - // iterate all media items ob mob - $query = "SELECT * FROM media_item WHERE mob_id = ". - $ilDB->quote($a_mob_id, "integer"); - $item_set = $ilDB->query($query); - while ($item_rec = $ilDB->fetchAssoc($item_set)) - { - // delete all parameters of media item - $query = "DELETE FROM mob_parameter WHERE med_item_id = ". - $ilDB->quote($item_rec["id"], "integer"); - $ilDB->manipulate($query); - - // delete all map areas of media item - $query = "DELETE FROM map_area WHERE item_id = ". - $ilDB->quote($item_rec["id"], "integer"); - $ilDB->manipulate($query); - } - - // delete media items - $query = "DELETE FROM media_item WHERE mob_id = ". - $ilDB->quote($a_mob_id, "integer"); - $ilDB->manipulate($query); - } - - function setPurpose($a_purpose) - { - $this->purpose = $a_purpose; - } - - function getPurpose() - { - return $this->purpose; - } - - function setLocation($a_location) - { - $this->location = $a_location; - } - - function getLocation() - { - return $this->location; - } - - function setLocationType($a_type) - { - $this->location_type = $a_type; - } - - function getLocationType() - { - return $this->location_type; - } - - function setFormat($a_format) - { - $this->format = $a_format; - } - - function getFormat() - { - return $this->format; - } - - function setThumbTried($a_tried) - { - $this->tried_thumb = $a_tried; - } - - function getThumbTried() - { - return $this->tried_thumb; - } - - function addMapArea(&$a_map_area) - { - $this->mapareas[$this->map_cnt] = $a_map_area; - $this->map_cnt++; - } - - /** - * delete map area - */ - function deleteMapArea($nr) - { - for ($i=1; $i<=$this->map_cnt; $i++) - { - if($i > $nr) - { - $this->mapareas[$i-2] = $this->mapareas[$i-1]; - $this->mapareas[$i-2]->setNr($i-1); - } - } - if($nr <= $this->map_cnt) - { - unset($this->mapareas[$this->map_cnt - 1]); - $this->map_cnt--; - } - } - - /** - * get map area - */ - function &getMapArea($nr) - { - return $this->mapareas[$nr-1]; - } - - /** - * get map areas - */ - function getMapAreas() - { - return $this->mapareas; - } - - /** - * get width - */ - function getWidth() - { - return $this->width; - } - - /** - * set width - */ - function setWidth($a_width) - { - $this->width = $a_width; - } - - /** - * get height - */ - function getHeight() - { - return $this->height; - } - - /** - * set height - */ - function setHeight($a_height) - { - $this->height = $a_height; - } - - /** - * get original size - */ - function getOriginalSize() - { - $mob_dir = ilObjMediaObject::_getDirectory($this->getMobId()); - - if (ilUtil::deducibleSize($this->getFormat())) - { - if ($this->getLocationType() == "LocalFile") - { - $loc = $mob_dir."/".$this->getLocation(); - } - else - { - $loc = $this->getLocation(); - } - - include_once("./Services/MediaObjects/classes/class.ilMediaImageUtil.php"); - $size = ilMediaImageUtil::getImageSize($loc); - if ($size[0] > 0 && $size[1] > 0) - { - return array("width" => $size[0], "height" => $size[1]); - } - } - - return false; - } - - /** - * set caption - */ - function setCaption($a_caption) - { - $this->caption = $a_caption; - } - - /** - * get caption - */ - function getCaption() - { - return $this->caption; - } - - /** - * set horizontal align - */ - function setHAlign($a_halign) - { - $this->halign = $a_halign; - } - - /** - * get horizontal align - */ - function getHAlign() - { - return $this->halign; - } - - - /** - * set parameter - * - * @param string $a_name parameter name - * @param string $a_value parameter value - */ - function setParameter($a_name, $a_value) - { - if (self::checkParameter($a_name, $a_value)) - { - $this->parameters[$a_name] = $a_value; - } - } - - /** - * reset parameters - */ - function resetParameters() - { - $this->parameters = array(); - } - - /** - * set alle parameters via parameter string (format: par1="value1", par2="value2", ...) - * - * @param string $a_par parameter string - */ - function setParameters($a_par) - { - $this->resetParameters(); - $par_arr = ilUtil::extractParameterString($a_par); - if(is_array($par_arr)) - { - foreach($par_arr as $par => $val) - { - $this->setParameter($par, $val); - } - } - } - - /** - * Check parameter (filter javascript related and other unsafe parameters/values) - * - * @param string $a_par parameter - * @param string $a_val value - * @return bool - */ - static function checkParameter($a_par, $a_val) - { - // do not allow event attributes - if (substr(strtolower(trim($a_par)), 0, 2) == "on") - { - return false; - } - // no javascript in value - if (is_int(strpos(strtolower($a_val), "javascript"))) - { - return false; - } - // do not allow to change the src attribute - if (in_array(strtolower(trim($a_par)), array("src"))) - { - return false; - } - - return true; - } - - - /** - * get all parameters (in array) - */ - function getParameters() - { - return $this->parameters; - } - - - /** - * get all parameters (as string) - */ - function getParameterString() - { - return ilUtil::assembleParameterString($this->parameters); - } - - - /** - * get a single parameter - */ - function getParameter($a_name) - { - return $this->parameters[$a_name]; - } - - /** - * get work directory for image map editing - */ - function getWorkDirectory() - { - return ilUtil::getDataDir()."/map_workfiles/item_".$this->getId(); - } - - /** - * create work directory for image map editing - */ - function createWorkDirectory() - { - if(!@is_dir(ilUtil::getDataDir()."/map_workfiles")) - { - ilUtil::createDirectory(ilUtil::getDataDir()."/map_workfiles"); - } - $work_dir = $this->getWorkDirectory(); - if(!@is_dir($work_dir)) - { - ilUtil::createDirectory($work_dir); - } - } - - /** - * get location suffix - */ - function getSuffix() - { - $loc_arr = explode(".", $this->getLocation()); - - return $loc_arr[count($loc_arr) - 1]; - } - - /** - * get image type of image map work copy - */ - function getMapWorkCopyType() - { - return ilUtil::getGDSupportedImageType($this->getSuffix()); - } - - /** - * Get name of image map work copy file - * - * @param string Get name, for copy of external referenced image - */ - function getMapWorkCopyName($a_reference_copy = false) - { - $file_arr = explode("/", $this->getLocation()); - $o_file = $file_arr[count($file_arr) - 1]; - $file_arr = explode(".", $o_file); - unset($file_arr[count($file_arr) - 1]); - $file = implode($file_arr, "."); - - if (!$a_reference_copy) - { - return $this->getWorkDirectory()."/".$file.".".$this->getMapWorkCopyType(); - } - else - { - return $this->getWorkDirectory()."/l_copy_".$o_file; - } - } - - /** - * get media file directory - */ - function getDirectory() - { - return ilObjMediaObject::_getDirectory($this->getMobId()); - } - - /** - * get media file directory - */ - function getThumbnailDirectory($a_mode = "filesystem") - { - return ilObjMediaObject::_getThumbnailDirectory($this->getMobId(), $a_mode); - } - - /** - * get thumbnail target - */ - function getThumbnailTarget($a_size = "") - { - if (is_int(strpos($this->getFormat(), "image"))) - { - $thumb_file = $this->getThumbnailDirectory()."/". - $this->getPurpose().".jpeg"; - - $thumb_file_small = $this->getThumbnailDirectory()."/". - $this->getPurpose()."_small.jpeg"; - - // generate thumbnail (if not tried before) - if ($this->getThumbTried() == "n" && $this->getLocationType() == "LocalFile") - { - if (is_file($thumb_file)) - { - unlink($thumb_file); - } - if (is_file($thumb_file_small)) - { - unlink($thumb_file_small); - } - $this->writeThumbTried("y"); - ilObjMediaObject::_createThumbnailDirectory($this->getMobId()); - $med_file = $this->getDirectory()."/".$this->getLocation(); - - if (is_file($med_file)) - { - ilUtil::convertImage($med_file, $thumb_file, "jpeg", "80"); - ilUtil::convertImage($med_file, $thumb_file_small, "jpeg", "40"); - } - } - - if ($a_size == "small") - { - if (is_file($thumb_file_small)) - { - return $this->getThumbnailDirectory("output")."/". - $this->getPurpose()."_small.jpeg?dummy=".rand(1, 999999); - } - } - else - { - if (is_file($thumb_file)) - { - return $this->getThumbnailDirectory("output")."/". - $this->getPurpose().".jpeg?dummy=".rand(1, 999999); - } - } - } - - return ""; - } - - - /** - * Copy the orginal file - */ - function copyOriginal() - { - $lng = $this->lng; - $this->createWorkDirectory(); - - $geom = ($this->getWidth() != "" && $this->getHeight() != "") - ? $this->getWidth()."x".$this->getHeight() - : ""; - - if ($this->getLocationType() != "Reference") - { - ilUtil::convertImage($this->getDirectory()."/".$this->getLocation(), - $this->getMapWorkCopyName(), - $this->getMapWorkCopyType(), $geom); - } - else - { - // first copy the external file, if necessary - if (!is_file($this->getMapWorkCopyName(true)) || (filesize($this->getMapWorkCopyName(true)) == 0)) - { - $handle = @fopen($this->getLocation(), "r"); - $lcopy = fopen($this->getMapWorkCopyName(true), "w"); - if ($handle && $lcopy) - { - while (!feof($handle)) - { - $content = fread($handle, 4096); - fwrite($lcopy, $content); - } - } - @fclose($lcopy); - @fclose($handle); - } - - // now, create working copy - ilUtil::convertImage($this->getMapWorkCopyName(true), - $this->getMapWorkCopyName(), - $this->getMapWorkCopyType(), $geom); - } - - if (!is_file($this->getMapWorkCopyName())) - { - - ilUtil::sendFailure($lng->txt("cont_map_file_not_generated")); - return false; - } - return true; - } - - /** - * make map work copy of image - * - * @param int $a_area_nr draw area $a_area_nr only - * @param boolean $a_exclude true: draw all areas but area $a_area_nr - */ - function makeMapWorkCopy($a_area_nr = 0, $a_exclude = false) - { - $lng = $this->lng; - - if (!$this->copyOriginal()) - { - return false; - } - $this->buildMapWorkImage(); - - // determine ratios - $size = @getimagesize($this->getMapWorkCopyName()); - $x_ratio = 1; - if ($size[0] > 0 && $this->getWidth() > 0) - { - $x_ratio = $this->getWidth() / $size[0]; - } - $y_ratio = 1; - if ($size[1] > 0 && $this->getHeight() > 0) - { - $y_ratio = $this->getHeight() / $size[1]; - } - - // draw map areas - for ($i=0; $i < count($this->mapareas); $i++) - { - if ( ((($i+1) == $a_area_nr) && !$a_exclude) || - ((($i+1) != $a_area_nr) && $a_exclude) || - ($a_area_nr == 0) - ) - { - $area = $this->mapareas[$i]; - $area->draw($this->getMapWorkImage(), $this->color1, $this->color2, true, - $x_ratio, $y_ratio); - } - } - - $this->saveMapWorkImage(); - - return true; - } - - - /** - * draw a new area in work image - * - * @param string $a_shape shape - * @param string $a_coords coordinates string - */ - function addAreaToMapWorkCopy($a_shape, $a_coords) - { - $this->buildMapWorkImage(); - - // determine ratios - $size = @getimagesize($this->getMapWorkCopyName()); - $x_ratio = 1; - if ($size[0] > 0 && $this->getWidth() > 0) - { - $x_ratio = $this->getWidth() / $size[0]; - } - $y_ratio = 1; - if ($size[1] > 0 && $this->getHeight() > 0) - { - $y_ratio = $this->getHeight() / $size[1]; - } - - // add new area to work image - $area = new ilMapArea(); - $area->setShape($a_shape); - $area->setCoords($a_coords); - $area->draw($this->getMapWorkImage(), $this->color1, $this->color2, false, - $x_ratio, $y_ratio); - - $this->saveMapWorkImage(); - } - - /** - * output raw map work copy file - */ - function outputMapWorkCopy() - { - if ($this->getMapWorkCopyType() != "") - { - header("Pragma: no-cache"); - header("Expires: 0"); - header("Content-type: image/".strtolower($this->getMapWorkCopyType())); - readfile($this->getMapWorkCopyName()); - } - exit; - } - - /** - * build image map work image - */ - function buildMapWorkImage() - { - $im_type = strtolower($this->getMapWorkCopyType()); - - switch ($im_type) - { - case "gif": - $this->map_image = ImageCreateFromGIF($this->getMapWorkCopyName()); - break; - - case "jpg": - case "jpeg": - $this->map_image = ImageCreateFromJPEG($this->getMapWorkCopyName()); - break; - - case "png": - $this->map_image = ImageCreateFromPNG($this->getMapWorkCopyName()); - break; - } - - // try to allocate black and white as color. if this is not possible, get the closest colors - if (imagecolorstotal($this->map_image) > 250) - { - $this->color1 = imagecolorclosest($this->map_image, 0, 0, 0); - $this->color2 = imagecolorclosest($this->map_image, 255, 255, 255); - } - else - { - $this->color1 = imagecolorallocate($this->map_image, 0, 0, 0); - $this->color2 = imagecolorallocate($this->map_image, 255, 255, 255); - } - } - - /** - * save image map work image - */ - function saveMapWorkImage() - { - $im_type = strtolower($this->getMapWorkCopyType()); - - // save image work-copy and free memory - switch ($im_type) - { - case "gif": - ImageGIF($this->map_image, $this->getMapWorkCopyName()); - break; - - case "jpg": - case "jpeg": - ImageJPEG($this->map_image, $this->getMapWorkCopyName()); - break; - - case "png": - ImagePNG($this->map_image, $this->getMapWorkCopyName()); - break; - } - - ImageDestroy($this->map_image); - } - - /** - * get image map work image - */ - function &getMapWorkImage() - { - return $this->map_image; - } - - - /** - * get xml code of media items' areas - */ - function getMapAreasXML($a_insert_inst = false, $a_inst = 0) - { - $xml = ""; - - // build xml of map areas - for ($i=0; $i < count($this->mapareas); $i++) - { - $area = $this->mapareas[$i]; - - // highlight mode - $hm = ""; - if ($area->getHighlightMode() != "") - { - $hm = ' HighlightMode="'.$area->getHighlightMode().'" '; - $hcl = ($area->getHighlightClass() != "") - ? $area->getHighlightClass() - : "Accented"; - $hm.= 'HighlightClass="'.$hcl.'" '; - } - - $xml .= "getShape()."\" Coords=\"".$area->getCoords()."\" ".$hm.">"; - if ($area->getLinkType() == IL_INT_LINK) - { - $target_frame = $area->getTargetFrame(); - - if ($area->getType() == "GlossaryItem" && $target_frame == "") - { - $target_frame = "Glossary"; - } - - $tf_str = ($target_frame == "") - ? "" - : "TargetFrame=\"".$target_frame."\""; - - $xml .= "getTarget($a_insert_inst, $a_inst)."\" Type=\"". - $area->getType()."\" $tf_str>"; - // see bug 17893 and http://stackoverflow.com/questions/4026502/xml-error-at-ampersand - $xml .= htmlspecialchars($area->getTitle(), ENT_QUOTES); - $xml .=""; - } - else - { - $xml .= "getHref())."\" Title=\"". - str_replace("&", "&",$area->getExtTitle())."\">"; - $xml .= str_replace("&", "&", $area->getTitle()); - $xml .=""; - } - $xml .= ""; - } - return $xml; - } - - - /** - * resolve internal links of all media items of a media object - * - * @param int $a_mob_id media object id - */ - static function _resolveMapAreaLinks($a_mob_id) - { - global $DIC; - - $ilDB = $DIC->database(); - -//echo "mediaItems::resolve
                  "; - // read media_object record - $query = "SELECT * FROM media_item WHERE mob_id = ". - $ilDB->quote($a_mob_id, "integer")." ". - "ORDER BY nr"; - $item_set = $ilDB->query($query); - while ($item_rec = $ilDB->fetchAssoc($item_set)) - { - ilMapArea::_resolveIntLinks($item_rec["id"]); - } - } - - /** - * get all internal links of map areas of a mob - * - * @param int $a_mob_id media object id - */ - static function _getMapAreasIntLinks($a_mob_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - // read media_items records - $query = "SELECT * FROM media_item WHERE mob_id = ". - $ilDB->quote($a_mob_id, "integer")." ORDER BY nr"; - - $item_set = $ilDB->query($query); - $links = array(); - while ($item_rec = $ilDB->fetchAssoc($item_set)) - { - $map_links = ilMapArea::_getIntLinks($item_rec["id"]); - foreach($map_links as $key => $map_link) - { - $links[$key] = $map_link; - } - } - return $links; - } - - /** - * Extract parameters of special external references to parameter array - */ - function extractUrlParameters() - { - include_once("./Services/MediaObjects/classes/class.ilExternalMediaAnalyzer.php"); - $par = ilExternalMediaAnalyzer::extractUrlParameters( - $this->getLocation(), $this->getParameters()); - foreach ($par as $k => $v) - { - $this->setParameter($k, $v); - } - } - - /** - * Get media items for upload hash - * - * @param string $a_hash upload hash - * @return array - */ - static public function getMediaItemsForUploadHash($a_hash) - { - global $DIC; - - $db = $DIC->database(); - - $set = $db->queryF("SELECT * FROM media_item ". - " WHERE upload_hash = %s ", - array("text"), - array($a_hash) - ); - $media_items = array(); - while ($rec = $db->fetchAssoc($set)) - { - $media_items[] = $rec; - } - return $media_items; - } - + /** + * @var ilDB + */ + protected $db; + + /** + * @var ilLanguage + */ + protected $lng; + + public $id; + public $purpose; + public $location; + public $location_type; + public $format; + public $width; + public $height; + public $caption; + public $halign; + public $parameters; + public $mob_id; + public $nr; + public $mapareas; + public $map_cnt; + public $map_image; // image map work copy image + public $color1; // map area line color 1 + public $color2; // map area line color 2 + + /** + * @var string + */ + protected $upload_hash; + + public function __construct($a_id = 0) + { + global $DIC; + + $this->db = $DIC->database(); + $this->lng = $DIC->language(); + $this->parameters = array(); + $this->mapareas = array(); + $this->map_cnt = 0; + + if ($a_id != 0) { + $this->setId($a_id); + $this->read(); + } + } + + /** + * set media item id + * + * @param int $a_id media item id + */ + public function setId($a_id) + { + $this->id = $a_id; + } + + /** + * get media item id + * + * @return int media item id + */ + public function getId() + { + return $this->id; + } + + /** + * set id of parent media object + * + * @param int $a_mob_id media object id + */ + public function setMobId($a_mob_id) + { + $this->mob_id = $a_mob_id; + } + + /** + * get id of parent media object + * + * @return int media object id + */ + public function getMobId() + { + return $this->mob_id; + } + + /** + * set number of media item within media object + */ + public function setNr($a_nr) + { + $this->nr = $a_nr; + } + + public function getNr() + { + return $this->nr; + } + + /** + * Set text representation + * + * @param string text representation + */ + public function setTextRepresentation($a_val) + { + $this->text_representation = $a_val; + } + + /** + * Get text representation + * + * @return string text representation + */ + public function getTextRepresentation() + { + return $this->text_representation; + } + + /** + * Set upload hash + * + * @param string $a_val upload hash + */ + public function setUploadHash($a_val) + { + $this->upload_hash = $a_val; + } + + /** + * Get upload hash + * + * @return string upload hash + */ + public function getUploadHash() + { + return $this->upload_hash; + } + + + /** + * create persistent media item + */ + public function create() + { + $ilDB = $this->db; + + $item_id = $ilDB->nextId("media_item"); + $query = "INSERT INTO media_item (id,mob_id, purpose, location, " . + "location_type, format, width, " . + "height, halign, caption, nr, text_representation, upload_hash) VALUES " . + "(" . + $ilDB->quote($item_id, "integer") . "," . + $ilDB->quote($this->getMobId(), "integer") . "," . + $ilDB->quote($this->getPurpose(), "text") . "," . + $ilDB->quote($this->getLocation(), "text") . "," . + $ilDB->quote($this->getLocationType(), "text") . "," . + $ilDB->quote($this->getFormat(), "text") . "," . + $ilDB->quote($this->getWidth(), "text") . "," . + $ilDB->quote($this->getHeight(), "text") . "," . + $ilDB->quote($this->getHAlign(), "text") . "," . + $ilDB->quote($this->getCaption(), "text") . "," . + $ilDB->quote($this->getNr(), "integer") . "," . + $ilDB->quote($this->getTextRepresentation(), "text") . "," . + $ilDB->quote($this->getUploadHash(), "text") . + ")"; + $ilDB->manipulate($query); + + $this->setId($item_id); + + // create mob parameters + $params = $this->getParameters(); + foreach ($params as $name => $value) { + $query = "INSERT INTO mob_parameter (med_item_id, name, value) VALUES " . + "(" . $ilDB->quote($item_id, "integer") . "," . + $ilDB->quote($name, "text") . "," . + $ilDB->quote($value, "text") . ")"; + $ilDB->manipulate($query); + } + + // create map areas + for ($i=0; $i < count($this->mapareas); $i++) { + if (is_object($this->mapareas[$i])) { + $this->mapareas[$i]->setItemId($this->getId()); + $this->mapareas[$i]->setNr($i + 1); + $this->mapareas[$i]->create(); + } + } + } + + /** + * update media item data (without map areas!) + */ + public function update() + { + $ilDB = $this->db; + + $query = "UPDATE media_item SET " . + " mob_id = " . $ilDB->quote($this->getMobId(), "integer") . "," . + " purpose = " . $ilDB->quote($this->getPurpose(), "text") . "," . + " location = " . $ilDB->quote($this->getLocation(), "text") . "," . + " location_type = " . $ilDB->quote($this->getLocationType(), "text") . "," . + " format = " . $ilDB->quote($this->getFormat(), "text") . "," . + " width = " . $ilDB->quote($this->getWidth(), "text") . "," . + " height = " . $ilDB->quote($this->getHeight(), "text") . "," . + " halign = " . $ilDB->quote($this->getHAlign(), "text") . "," . + " caption = " . $ilDB->quote($this->getCaption(), "text") . "," . + " nr = " . $ilDB->quote($this->getNr(), "integer") . "," . + " text_representation = " . $ilDB->quote($this->getTextRepresentation(), "text") . "," . + " upload_hash = " . $ilDB->quote($this->getUploadHash(), "text") . + " WHERE id = " . $ilDB->quote($this->getId(), "integer"); + $ilDB->manipulate($query); + + // delete mob parameters + $query = "DELETE FROM mob_parameter WHERE med_item_id = " . + $ilDB->quote($this->getId(), "integer"); + + // create mob parameters + $params = $this->getParameters(); + foreach ($params as $name => $value) { + $query = "INSERT INTO mob_parameter (med_item_id, name, value) VALUES " . + "(" . $ilDB->quote($this->getId(), "integer") . "," . + $ilDB->quote($name, "text") . "," . + $ilDB->quote($value, "text") . ")"; + $ilDB->manipulate($query); + } + } + + /** + * Write parameter + * + * @param + * @return + */ + public function writeParameter($a_name, $a_value) + { + $ilDB = $this->db; + + $query = "INSERT INTO mob_parameter (med_item_id, name, value) VALUES " . + "(" . $ilDB->quote($this->getId(), "integer") . "," . + $ilDB->quote($a_name, "text") . "," . + $ilDB->quote($a_value, "text") . ")"; + $ilDB->manipulate($query); + } + + /** + * read media item data (item id or (mob_id and nr) must be set) + */ + public function read() + { + $ilDB = $this->db; + + $item_id = $this->getId(); + $mob_id = $this->getMobId(); + $nr = $this->getNr(); + $query = ""; + if ($item_id > 0) { + $query = "SELECT * FROM media_item WHERE id = " . + $ilDB->quote($this->getId(), "integer"); + } elseif ($mob_id > 0 && $nr > 0) { + $query = "SELECT * FROM media_item WHERE mob_id = " . + $ilDB->quote($this->getMobId(), "integer") . " " . + "AND nr=" . $ilDB->quote($this->getNr(), "integer"); + } + if ($query != "") { + $item_set = $ilDB->query($query); + $item_rec = $ilDB->fetchAssoc($item_set); + + $this->setLocation($item_rec["location"]); + $this->setLocationType($item_rec["location_type"]); + $this->setFormat($item_rec["format"]); + $this->setWidth($item_rec["width"]); + $this->setHeight($item_rec["height"]); + $this->setHAlign($item_rec["halign"]); + $this->setCaption($item_rec["caption"]); + $this->setPurpose($item_rec["purpose"]); + $this->setNr($item_rec["nr"]); + $this->setMobId($item_rec["mob_id"]); + $this->setId($item_rec["id"]); + $this->setThumbTried($item_rec["tried_thumb"]); + $this->setTextRepresentation($item_rec["text_representation"]); + $this->setUploadHash($item_rec["upload_hash"]); + + // get item parameter + $query = "SELECT * FROM mob_parameter WHERE med_item_id = " . + $ilDB->quote($this->getId(), "integer"); + $par_set = $ilDB->query($query); + while ($par_rec = $ilDB->fetchAssoc($par_set)) { + $this->setParameter($par_rec["name"], $par_rec["value"]); + } + + // get item map areas + $max = ilMapArea::_getMaxNr($this->getId()); + for ($i = 1; $i <= $max; $i++) { + $area = new ilMapArea($this->getId(), $i); + $this->addMapArea($area); + } + } + } + + /** + * write thumbnail creation try data ("y"/"n") + */ + public function writeThumbTried($a_tried) + { + $ilDB = $this->db; + + $q = "UPDATE media_item SET tried_thumb = " . + $ilDB->quote($a_tried, "text") . + " WHERE id = " . $ilDB->quote($this->getId(), "integer"); + + $ilDB->manipulate($q); + } + + /** + * Lookup location for mob id + * + * @param int $a_mob_id media object id + * @param string $a_purpose purpose + */ + public static function _lookupLocationForMobId($a_mob_id, $a_purpose) + { + global $DIC; + + $ilDB = $DIC->database(); + + // read media_object record + $query = "SELECT * FROM media_item WHERE mob_id = " . + $ilDB->quote($a_mob_id, "integer") . " " . + "AND purpose = " . $ilDB->quote($a_purpose, "text"); + $set = $ilDB->query($query); + if ($rec = $ilDB->fetchAssoc($set)) { + return $rec["location"]; + } + + return ""; + } + + /** + * Lookup Mob ID + * + * @param int $a_med_id media item id + */ + public static function _lookupMobId($a_med_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + // read media_object record + $query = "SELECT * FROM media_item WHERE id = " . + $ilDB->quote($a_med_id, "integer"); + $set = $ilDB->query($query); + if ($rec = $ilDB->fetchAssoc($set)) { + return $rec["mob_id"]; + } + + return ""; + } + + /* read media item with specific purpose and mobId + * + * @param integer $a_mobId media object id + * @param string $a_purpose media object purpose + * @return array $mob media object + */ + public static function _getMediaItemsOfMObId($a_mobId, $a_purpose) + { + global $DIC; + + $ilDB = $DIC->database(); + + // read media_object record + $query = "SELECT * FROM media_item WHERE mob_id = " . + $ilDB->quote($a_mobId, "integer") . " " . + "AND purpose=" . $ilDB->quote($a_purpose, "text") . " ORDER BY nr"; + $item_set = $ilDB->query($query); + + while ($item_rec = $ilDB->fetchAssoc($item_set)) { + return $item_rec; + } + return false; + } + + /** + * read media items into media objects (static) + * + * @param object $a_mob media object + */ + public static function _getMediaItemsOfMOb(&$a_mob) + { + global $DIC; + + $ilDB = $DIC->database(); + + // read media_object record + $query = "SELECT * FROM media_item WHERE mob_id = " . + $ilDB->quote($a_mob->getId(), "integer") . " " . + "ORDER BY nr"; + $item_set = $ilDB->query($query); + while ($item_rec = $ilDB->fetchAssoc($item_set)) { + $media_item = new ilMediaItem(); + $media_item->setNr($item_rec["nr"]); + $media_item->setId($item_rec["id"]); + $media_item->setLocation($item_rec["location"]); + $media_item->setLocationType($item_rec["location_type"]); + $media_item->setFormat($item_rec["format"]); + $media_item->setWidth($item_rec["width"]); + $media_item->setHeight($item_rec["height"]); + $media_item->setHAlign($item_rec["halign"]); + $media_item->setCaption($item_rec["caption"]); + $media_item->setPurpose($item_rec["purpose"]); + $media_item->setMobId($item_rec["mob_id"]); + $media_item->setThumbTried($item_rec["tried_thumb"]); + $media_item->setTextRepresentation($item_rec["text_representation"]); + $media_item->setUploadHash($item_rec["upload_hash"]); + + // get item parameter + $query = "SELECT * FROM mob_parameter WHERE med_item_id = " . + $ilDB->quote($item_rec["id"], "integer"); + $par_set = $ilDB->query($query); + while ($par_rec = $ilDB->fetchAssoc($par_set)) { + $media_item->setParameter($par_rec["name"], $par_rec["value"]); + } + + // get item map areas + $max = ilMapArea::_getMaxNr($media_item->getId()); + for ($i = 1; $i <= $max; $i++) { + $area = new ilMapArea($media_item->getId(), $i); + $media_item->addMapArea($area); + } + + // add media item to media object + $a_mob->addMediaItem($media_item); + } + } + + /** + * Delete all items of a mob + * + * @param int $a_mob_id media object id + */ + public static function deleteAllItemsOfMob($a_mob_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + // iterate all media items ob mob + $query = "SELECT * FROM media_item WHERE mob_id = " . + $ilDB->quote($a_mob_id, "integer"); + $item_set = $ilDB->query($query); + while ($item_rec = $ilDB->fetchAssoc($item_set)) { + // delete all parameters of media item + $query = "DELETE FROM mob_parameter WHERE med_item_id = " . + $ilDB->quote($item_rec["id"], "integer"); + $ilDB->manipulate($query); + + // delete all map areas of media item + $query = "DELETE FROM map_area WHERE item_id = " . + $ilDB->quote($item_rec["id"], "integer"); + $ilDB->manipulate($query); + } + + // delete media items + $query = "DELETE FROM media_item WHERE mob_id = " . + $ilDB->quote($a_mob_id, "integer"); + $ilDB->manipulate($query); + } + + public function setPurpose($a_purpose) + { + $this->purpose = $a_purpose; + } + + public function getPurpose() + { + return $this->purpose; + } + + public function setLocation($a_location) + { + $this->location = $a_location; + } + + public function getLocation() + { + return $this->location; + } + + public function setLocationType($a_type) + { + $this->location_type = $a_type; + } + + public function getLocationType() + { + return $this->location_type; + } + + public function setFormat($a_format) + { + $this->format = $a_format; + } + + public function getFormat() + { + return $this->format; + } + + public function setThumbTried($a_tried) + { + $this->tried_thumb = $a_tried; + } + + public function getThumbTried() + { + return $this->tried_thumb; + } + + public function addMapArea(&$a_map_area) + { + $this->mapareas[$this->map_cnt] = $a_map_area; + $this->map_cnt++; + } + + /** + * delete map area + */ + public function deleteMapArea($nr) + { + for ($i=1; $i<=$this->map_cnt; $i++) { + if ($i > $nr) { + $this->mapareas[$i-2] = $this->mapareas[$i-1]; + $this->mapareas[$i-2]->setNr($i-1); + } + } + if ($nr <= $this->map_cnt) { + unset($this->mapareas[$this->map_cnt - 1]); + $this->map_cnt--; + } + } + + /** + * get map area + */ + public function &getMapArea($nr) + { + return $this->mapareas[$nr-1]; + } + + /** + * get map areas + */ + public function getMapAreas() + { + return $this->mapareas; + } + + /** + * get width + */ + public function getWidth() + { + return $this->width; + } + + /** + * set width + */ + public function setWidth($a_width) + { + $this->width = $a_width; + } + + /** + * get height + */ + public function getHeight() + { + return $this->height; + } + + /** + * set height + */ + public function setHeight($a_height) + { + $this->height = $a_height; + } + + /** + * get original size + */ + public function getOriginalSize() + { + $mob_dir = ilObjMediaObject::_getDirectory($this->getMobId()); + + if (ilUtil::deducibleSize($this->getFormat())) { + if ($this->getLocationType() == "LocalFile") { + $loc = $mob_dir . "/" . $this->getLocation(); + } else { + $loc = $this->getLocation(); + } + + include_once("./Services/MediaObjects/classes/class.ilMediaImageUtil.php"); + $size = ilMediaImageUtil::getImageSize($loc); + if ($size[0] > 0 && $size[1] > 0) { + return array("width" => $size[0], "height" => $size[1]); + } + } + + return false; + } + + /** + * set caption + */ + public function setCaption($a_caption) + { + $this->caption = $a_caption; + } + + /** + * get caption + */ + public function getCaption() + { + return $this->caption; + } + + /** + * set horizontal align + */ + public function setHAlign($a_halign) + { + $this->halign = $a_halign; + } + + /** + * get horizontal align + */ + public function getHAlign() + { + return $this->halign; + } + + + /** + * set parameter + * + * @param string $a_name parameter name + * @param string $a_value parameter value + */ + public function setParameter($a_name, $a_value) + { + if (self::checkParameter($a_name, $a_value)) { + $this->parameters[$a_name] = $a_value; + } + } + + /** + * reset parameters + */ + public function resetParameters() + { + $this->parameters = array(); + } + + /** + * set alle parameters via parameter string (format: par1="value1", par2="value2", ...) + * + * @param string $a_par parameter string + */ + public function setParameters($a_par) + { + $this->resetParameters(); + $par_arr = ilUtil::extractParameterString($a_par); + if (is_array($par_arr)) { + foreach ($par_arr as $par => $val) { + $this->setParameter($par, $val); + } + } + } + + /** + * Check parameter (filter javascript related and other unsafe parameters/values) + * + * @param string $a_par parameter + * @param string $a_val value + * @return bool + */ + public static function checkParameter($a_par, $a_val) + { + // do not allow event attributes + if (substr(strtolower(trim($a_par)), 0, 2) == "on") { + return false; + } + // no javascript in value + if (is_int(strpos(strtolower($a_val), "javascript"))) { + return false; + } + // do not allow to change the src attribute + if (in_array(strtolower(trim($a_par)), array("src"))) { + return false; + } + + return true; + } + + + /** + * get all parameters (in array) + */ + public function getParameters() + { + return $this->parameters; + } + + + /** + * get all parameters (as string) + */ + public function getParameterString() + { + return ilUtil::assembleParameterString($this->parameters); + } + + + /** + * get a single parameter + */ + public function getParameter($a_name) + { + return $this->parameters[$a_name]; + } + + /** + * get work directory for image map editing + */ + public function getWorkDirectory() + { + return ilUtil::getDataDir() . "/map_workfiles/item_" . $this->getId(); + } + + /** + * create work directory for image map editing + */ + public function createWorkDirectory() + { + if (!@is_dir(ilUtil::getDataDir() . "/map_workfiles")) { + ilUtil::createDirectory(ilUtil::getDataDir() . "/map_workfiles"); + } + $work_dir = $this->getWorkDirectory(); + if (!@is_dir($work_dir)) { + ilUtil::createDirectory($work_dir); + } + } + + /** + * get location suffix + */ + public function getSuffix() + { + $loc_arr = explode(".", $this->getLocation()); + + return $loc_arr[count($loc_arr) - 1]; + } + + /** + * get image type of image map work copy + */ + public function getMapWorkCopyType() + { + return ilUtil::getGDSupportedImageType($this->getSuffix()); + } + + /** + * Get name of image map work copy file + * + * @param string Get name, for copy of external referenced image + */ + public function getMapWorkCopyName($a_reference_copy = false) + { + $file_arr = explode("/", $this->getLocation()); + $o_file = $file_arr[count($file_arr) - 1]; + $file_arr = explode(".", $o_file); + unset($file_arr[count($file_arr) - 1]); + $file = implode($file_arr, "."); + + if (!$a_reference_copy) { + return $this->getWorkDirectory() . "/" . $file . "." . $this->getMapWorkCopyType(); + } else { + return $this->getWorkDirectory() . "/l_copy_" . $o_file; + } + } + + /** + * get media file directory + */ + public function getDirectory() + { + return ilObjMediaObject::_getDirectory($this->getMobId()); + } + + /** + * get media file directory + */ + public function getThumbnailDirectory($a_mode = "filesystem") + { + return ilObjMediaObject::_getThumbnailDirectory($this->getMobId(), $a_mode); + } + + /** + * get thumbnail target + */ + public function getThumbnailTarget($a_size = "") + { + if (is_int(strpos($this->getFormat(), "image"))) { + $thumb_file = $this->getThumbnailDirectory() . "/" . + $this->getPurpose() . ".jpeg"; + + $thumb_file_small = $this->getThumbnailDirectory() . "/" . + $this->getPurpose() . "_small.jpeg"; + + // generate thumbnail (if not tried before) + if ($this->getThumbTried() == "n" && $this->getLocationType() == "LocalFile") { + if (is_file($thumb_file)) { + unlink($thumb_file); + } + if (is_file($thumb_file_small)) { + unlink($thumb_file_small); + } + $this->writeThumbTried("y"); + ilObjMediaObject::_createThumbnailDirectory($this->getMobId()); + $med_file = $this->getDirectory() . "/" . $this->getLocation(); + + if (is_file($med_file)) { + ilUtil::convertImage($med_file, $thumb_file, "jpeg", "80"); + ilUtil::convertImage($med_file, $thumb_file_small, "jpeg", "40"); + } + } + + if ($a_size == "small") { + if (is_file($thumb_file_small)) { + return $this->getThumbnailDirectory("output") . "/" . + $this->getPurpose() . "_small.jpeg?dummy=" . rand(1, 999999); + } + } else { + if (is_file($thumb_file)) { + return $this->getThumbnailDirectory("output") . "/" . + $this->getPurpose() . ".jpeg?dummy=" . rand(1, 999999); + } + } + } + + return ""; + } + + + /** + * Copy the orginal file + */ + public function copyOriginal() + { + $lng = $this->lng; + $this->createWorkDirectory(); + + $geom = ($this->getWidth() != "" && $this->getHeight() != "") + ? $this->getWidth() . "x" . $this->getHeight() + : ""; + + if ($this->getLocationType() != "Reference") { + ilUtil::convertImage( + $this->getDirectory() . "/" . $this->getLocation(), + $this->getMapWorkCopyName(), + $this->getMapWorkCopyType(), + $geom + ); + } else { + // first copy the external file, if necessary + if (!is_file($this->getMapWorkCopyName(true)) || (filesize($this->getMapWorkCopyName(true)) == 0)) { + $handle = @fopen($this->getLocation(), "r"); + $lcopy = fopen($this->getMapWorkCopyName(true), "w"); + if ($handle && $lcopy) { + while (!feof($handle)) { + $content = fread($handle, 4096); + fwrite($lcopy, $content); + } + } + @fclose($lcopy); + @fclose($handle); + } + + // now, create working copy + ilUtil::convertImage( + $this->getMapWorkCopyName(true), + $this->getMapWorkCopyName(), + $this->getMapWorkCopyType(), + $geom + ); + } + + if (!is_file($this->getMapWorkCopyName())) { + ilUtil::sendFailure($lng->txt("cont_map_file_not_generated")); + return false; + } + return true; + } + + /** + * make map work copy of image + * + * @param int $a_area_nr draw area $a_area_nr only + * @param boolean $a_exclude true: draw all areas but area $a_area_nr + */ + public function makeMapWorkCopy($a_area_nr = 0, $a_exclude = false) + { + $lng = $this->lng; + + if (!$this->copyOriginal()) { + return false; + } + $this->buildMapWorkImage(); + + // determine ratios + $size = @getimagesize($this->getMapWorkCopyName()); + $x_ratio = 1; + if ($size[0] > 0 && $this->getWidth() > 0) { + $x_ratio = $this->getWidth() / $size[0]; + } + $y_ratio = 1; + if ($size[1] > 0 && $this->getHeight() > 0) { + $y_ratio = $this->getHeight() / $size[1]; + } + + // draw map areas + for ($i=0; $i < count($this->mapareas); $i++) { + if (((($i+1) == $a_area_nr) && !$a_exclude) || + ((($i+1) != $a_area_nr) && $a_exclude) || + ($a_area_nr == 0) + ) { + $area = $this->mapareas[$i]; + $area->draw( + $this->getMapWorkImage(), + $this->color1, + $this->color2, + true, + $x_ratio, + $y_ratio + ); + } + } + + $this->saveMapWorkImage(); + + return true; + } + + + /** + * draw a new area in work image + * + * @param string $a_shape shape + * @param string $a_coords coordinates string + */ + public function addAreaToMapWorkCopy($a_shape, $a_coords) + { + $this->buildMapWorkImage(); + + // determine ratios + $size = @getimagesize($this->getMapWorkCopyName()); + $x_ratio = 1; + if ($size[0] > 0 && $this->getWidth() > 0) { + $x_ratio = $this->getWidth() / $size[0]; + } + $y_ratio = 1; + if ($size[1] > 0 && $this->getHeight() > 0) { + $y_ratio = $this->getHeight() / $size[1]; + } + + // add new area to work image + $area = new ilMapArea(); + $area->setShape($a_shape); + $area->setCoords($a_coords); + $area->draw( + $this->getMapWorkImage(), + $this->color1, + $this->color2, + false, + $x_ratio, + $y_ratio + ); + + $this->saveMapWorkImage(); + } + + /** + * output raw map work copy file + */ + public function outputMapWorkCopy() + { + if ($this->getMapWorkCopyType() != "") { + header("Pragma: no-cache"); + header("Expires: 0"); + header("Content-type: image/" . strtolower($this->getMapWorkCopyType())); + readfile($this->getMapWorkCopyName()); + } + exit; + } + + /** + * build image map work image + */ + public function buildMapWorkImage() + { + $im_type = strtolower($this->getMapWorkCopyType()); + + switch ($im_type) { + case "gif": + $this->map_image = ImageCreateFromGIF($this->getMapWorkCopyName()); + break; + + case "jpg": + case "jpeg": + $this->map_image = ImageCreateFromJPEG($this->getMapWorkCopyName()); + break; + + case "png": + $this->map_image = ImageCreateFromPNG($this->getMapWorkCopyName()); + break; + } + + // try to allocate black and white as color. if this is not possible, get the closest colors + if (imagecolorstotal($this->map_image) > 250) { + $this->color1 = imagecolorclosest($this->map_image, 0, 0, 0); + $this->color2 = imagecolorclosest($this->map_image, 255, 255, 255); + } else { + $this->color1 = imagecolorallocate($this->map_image, 0, 0, 0); + $this->color2 = imagecolorallocate($this->map_image, 255, 255, 255); + } + } + + /** + * save image map work image + */ + public function saveMapWorkImage() + { + $im_type = strtolower($this->getMapWorkCopyType()); + + // save image work-copy and free memory + switch ($im_type) { + case "gif": + ImageGIF($this->map_image, $this->getMapWorkCopyName()); + break; + + case "jpg": + case "jpeg": + ImageJPEG($this->map_image, $this->getMapWorkCopyName()); + break; + + case "png": + ImagePNG($this->map_image, $this->getMapWorkCopyName()); + break; + } + + ImageDestroy($this->map_image); + } + + /** + * get image map work image + */ + public function &getMapWorkImage() + { + return $this->map_image; + } + + + /** + * get xml code of media items' areas + */ + public function getMapAreasXML($a_insert_inst = false, $a_inst = 0) + { + $xml = ""; + + // build xml of map areas + for ($i=0; $i < count($this->mapareas); $i++) { + $area = $this->mapareas[$i]; + + // highlight mode + $hm = ""; + if ($area->getHighlightMode() != "") { + $hm = ' HighlightMode="' . $area->getHighlightMode() . '" '; + $hcl = ($area->getHighlightClass() != "") + ? $area->getHighlightClass() + : "Accented"; + $hm.= 'HighlightClass="' . $hcl . '" '; + } + + $xml .= "getShape() . "\" Coords=\"" . $area->getCoords() . "\" " . $hm . ">"; + if ($area->getLinkType() == IL_INT_LINK) { + $target_frame = $area->getTargetFrame(); + + if ($area->getType() == "GlossaryItem" && $target_frame == "") { + $target_frame = "Glossary"; + } + + $tf_str = ($target_frame == "") + ? "" + : "TargetFrame=\"" . $target_frame . "\""; + + $xml .= "getTarget($a_insert_inst, $a_inst) . "\" Type=\"" . + $area->getType() . "\" $tf_str>"; + // see bug 17893 and http://stackoverflow.com/questions/4026502/xml-error-at-ampersand + $xml .= htmlspecialchars($area->getTitle(), ENT_QUOTES); + $xml .=""; + } else { + $xml .= "getHref()) . "\" Title=\"" . + str_replace("&", "&", $area->getExtTitle()) . "\">"; + $xml .= str_replace("&", "&", $area->getTitle()); + $xml .=""; + } + $xml .= ""; + } + return $xml; + } + + + /** + * resolve internal links of all media items of a media object + * + * @param int $a_mob_id media object id + */ + public static function _resolveMapAreaLinks($a_mob_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + //echo "mediaItems::resolve
                  "; + // read media_object record + $query = "SELECT * FROM media_item WHERE mob_id = " . + $ilDB->quote($a_mob_id, "integer") . " " . + "ORDER BY nr"; + $item_set = $ilDB->query($query); + while ($item_rec = $ilDB->fetchAssoc($item_set)) { + ilMapArea::_resolveIntLinks($item_rec["id"]); + } + } + + /** + * get all internal links of map areas of a mob + * + * @param int $a_mob_id media object id + */ + public static function _getMapAreasIntLinks($a_mob_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + // read media_items records + $query = "SELECT * FROM media_item WHERE mob_id = " . + $ilDB->quote($a_mob_id, "integer") . " ORDER BY nr"; + + $item_set = $ilDB->query($query); + $links = array(); + while ($item_rec = $ilDB->fetchAssoc($item_set)) { + $map_links = ilMapArea::_getIntLinks($item_rec["id"]); + foreach ($map_links as $key => $map_link) { + $links[$key] = $map_link; + } + } + return $links; + } + + /** + * Extract parameters of special external references to parameter array + */ + public function extractUrlParameters() + { + include_once("./Services/MediaObjects/classes/class.ilExternalMediaAnalyzer.php"); + $par = ilExternalMediaAnalyzer::extractUrlParameters( + $this->getLocation(), + $this->getParameters() + ); + foreach ($par as $k => $v) { + $this->setParameter($k, $v); + } + } + + /** + * Get media items for upload hash + * + * @param string $a_hash upload hash + * @return array + */ + public static function getMediaItemsForUploadHash($a_hash) + { + global $DIC; + + $db = $DIC->database(); + + $set = $db->queryF( + "SELECT * FROM media_item " . + " WHERE upload_hash = %s ", + array("text"), + array($a_hash) + ); + $media_items = array(); + while ($rec = $db->fetchAssoc($set)) { + $media_items[] = $rec; + } + return $media_items; + } } -?> diff --git a/Services/MediaObjects/classes/class.ilMediaObjectDataSet.php b/Services/MediaObjects/classes/class.ilMediaObjectDataSet.php index d23393c16cc26fd5772c0f27f05763d51b9089c5..90c1d4e0d738a04957f98389515dc6dec54cffd8 100644 --- a/Services/MediaObjects/classes/class.ilMediaObjectDataSet.php +++ b/Services/MediaObjects/classes/class.ilMediaObjectDataSet.php @@ -5,7 +5,7 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); /** * Media Pool Data set class - * + * * This class implements the following entities: * - mob: object data * - mob_media_item: data from table media_item @@ -18,481 +18,442 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); */ class ilMediaObjectDataSet extends ilDataSet { - protected $use_previous_import_ids = false; - - /** - * Constructor - */ - function __construct() - { - parent::__construct(); - $this->mob_log = ilLoggerFactory::getLogger('mob'); - } - - /** - * Set use previous import ids - * - * @param bool $a_val use previous import ids - */ - function setUsePreviousImportIds($a_val) - { - $this->use_previous_import_ids = $a_val; - } - - /** - * Get use previous import ids - * - * @return bool use previous import ids - */ - function getUsePreviousImportIds() - { - return $this->use_previous_import_ids; - } - - /** - * Get supported versions - * - * @param - * @return - */ - public function getSupportedVersions() - { - return array("5.1.0", "4.3.0", "4.1.0"); - } - - /** - * Get xml namespace - * - * @param - * @return - */ - function getXmlNamespace($a_entity, $a_schema_version) - { - return "http://www.ilias.de/xml/Services/MediaObject/".$a_entity; - } - - /** - * Get field types for entity - * - * @param - * @return - */ - protected function getTypes($a_entity, $a_version) - { - // mob - if ($a_entity == "mob") - { - switch ($a_version) - { - case "4.1.0": - case "4.3.0": - return array( - "Id" => "integer", - "Title" => "text", - "Description" => "text", - "Dir" => "directory" - ); - - case "5.1.0": - return array( - "Id" => "integer", - "Title" => "text", - "Description" => "text", - "Dir" => "directory", - "ImportId" => "text" - ); - } - } - - // media item - if ($a_entity == "mob_media_item") - { - switch ($a_version) - { - case "4.1.0": - return array( - "Id" => "integer", - "MobId" => "integer", - "Width" => "integer", - "Height" => "integer", - "Halign" => "text", - "Caption" => "text", - "Nr" => "integer", - "Purpose" => "text", - "Location" => "text", - "LocationType" => "text", - "Format" => "text", - "TextRepresentation" => "text" - ); - - case "4.3.0": - case "5.1.0": - return array( - "Id" => "integer", - "MobId" => "integer", - "Width" => "integer", - "Height" => "integer", - "Halign" => "text", - "Caption" => "text", - "Nr" => "integer", - "Purpose" => "text", - "Location" => "text", - "LocationType" => "text", - "Format" => "text", - "TextRepresentation" => "text" - ); - } - } - - // map areas - if ($a_entity == "mob_mi_map_area") - { - switch ($a_version) - { - case "4.1.0": - case "4.3.0": - case "5.1.0": - return array( - "MiId" => "integer", - "Nr" => "integer", - "Shape" => "text", - "Coords" => "text", - "LinkType" => "text", - "Title" => "text", - "Href" => "text", - "Target" => "text", - "Type" => "text", - "TargetFrame" => "text", - "HighlightMode" => "text", - "HighlightText" => "text" - ); - } - } - - // media item parameter - if ($a_entity == "mob_mi_parameter") - { - switch ($a_version) - { - case "4.1.0": - case "4.3.0": - case "5.1.0": - return array( - "MiId" => "integer", - "Name" => "text", - "Value" => "text" - ); - } - } - } - - /** - * Read data - * - * @param - * @return - */ - function readData($a_entity, $a_version, $a_ids, $a_field = "") - { - $ilDB = $this->db; - - if (!is_array($a_ids)) - { - $a_ids = array($a_ids); - } - - // mob - if ($a_entity == "mob") - { - $this->data = array(); - - switch ($a_version) - { - case "4.1.0": - case "4.3.0": - foreach ($a_ids as $mob_id) - { - if (ilObject::_lookupType($mob_id) == "mob") - { - $this->data[] = array ("Id" => $mob_id, - "Title" => ilObject::_lookupTitle($mob_id), - "Description" => ilObject::_lookupDescription($mob_id) - ); - } - } - break; - - case "5.1.0": - foreach ($a_ids as $mob_id) - { - if (ilObject::_lookupType($mob_id) == "mob") - { - $this->data[] = array ("Id" => $mob_id, - "Title" => ilObject::_lookupTitle($mob_id), - "Description" => ilObject::_lookupDescription($mob_id), - "ImportId" => ilObject::_lookupImportId($mob_id) - ); - } - } - break; - } - } - - // media item - if ($a_entity == "mob_media_item") - { - switch ($a_version) - { - case "4.1.0": - $this->getDirectDataFromQuery("SELECT id, mob_id, width, height, halign,". - "caption, nr, purpose, location, location_type, format, text_representation". - " FROM media_item WHERE ". - $ilDB->in("mob_id", $a_ids, false, "integer")); - break; - - case "4.3.0": - case "5.1.0": - $this->getDirectDataFromQuery("SELECT id, mob_id, width, height, halign,". - "caption, nr, purpose, location, location_type, format, text_representation". - " FROM media_item WHERE ". - $ilDB->in("mob_id", $a_ids, false, "integer")); - break; - } - } - - - // media item map area - if ($a_entity == "mob_mi_map_area") - { - switch ($a_version) - { - case "4.1.0": - case "4.3.0": - case "5.1.0": - foreach ($this->getDirectDataFromQuery("SELECT item_id mi_id, nr". - " ,shape, coords, link_type, title, href, target, type, target_frame, ". - " highlight_mode, highlight_class". - " FROM map_area ". - " WHERE ". - $ilDB->in("item_id", $a_ids, false, "integer"). - " ORDER BY nr", true, false) as $r) - { - $r["Target"] = ilUtil::insertInstIntoID($r["Target"]); - - // see ilPageObject::insertInstIntoIDs - if ($r["Type"] == "RepositoryItem") - { - $id_arr = explode("_", $r["Target"]); - $ref_id = $id_arr[3]; - $obj_id = ilObject::_lookupObjId($id_arr[3]); - - $otype = ilObject::_lookupType($obj_id); - if ($obj_id > 0) - { - $id = $otype."_".$obj_id."_".$ref_id; - $r["Target"] = "il_".$id_arr[1]."_".$id; - } - } - - $this->data[] = $r; - } - break; - } - } - - // media item parameter - if ($a_entity == "mob_mi_parameter") - { - switch ($a_version) - { - case "4.1.0": - case "4.3.0": - case "5.1.0": - $this->getDirectDataFromQuery("SELECT med_item_id mi_id, name, value". - " FROM mob_parameter ". - " WHERE ". - $ilDB->in("med_item_id", $a_ids, false, "integer")); - break; - } - } - - } - - /** - * Determine the dependent sets of data - */ - protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) - { - switch ($a_entity) - { - case "mob": - return array ( - "mob_media_item" => array("ids" => $a_rec["Id"]) - ); - - case "mob_media_item": - return array ( - "mob_mi_map_area" => array("ids" => $a_rec["Id"]), - "mob_mi_parameter" => array("ids" => $a_rec["Id"]) - ); - } - return false; - } - - /** - * Get xml record - * - * @param - * @return - */ - function getXmlRecord($a_entity, $a_version, $a_set) - { - if ($a_entity == "mob") - { - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $dir = ilObjMediaObject::_getDirectory($a_set["Id"]); - $a_set["Dir"] = $dir; - } - - return $a_set; - } - - /** - * Import record - * - * @param - * @return - */ - function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) - { -//echo $a_entity; -//var_dump($a_rec); - - switch ($a_entity) - { - case "mob": + protected $use_previous_import_ids = false; + + /** + * Constructor + */ + public function __construct() + { + parent::__construct(); + $this->mob_log = ilLoggerFactory::getLogger('mob'); + } + + /** + * Set use previous import ids + * + * @param bool $a_val use previous import ids + */ + public function setUsePreviousImportIds($a_val) + { + $this->use_previous_import_ids = $a_val; + } + + /** + * Get use previous import ids + * + * @return bool use previous import ids + */ + public function getUsePreviousImportIds() + { + return $this->use_previous_import_ids; + } + + /** + * Get supported versions + * + * @param + * @return + */ + public function getSupportedVersions() + { + return array("5.1.0", "4.3.0", "4.1.0"); + } + + /** + * Get xml namespace + * + * @param + * @return + */ + public function getXmlNamespace($a_entity, $a_schema_version) + { + return "http://www.ilias.de/xml/Services/MediaObject/" . $a_entity; + } + + /** + * Get field types for entity + * + * @param + * @return + */ + protected function getTypes($a_entity, $a_version) + { + // mob + if ($a_entity == "mob") { + switch ($a_version) { + case "4.1.0": + case "4.3.0": + return array( + "Id" => "integer", + "Title" => "text", + "Description" => "text", + "Dir" => "directory" + ); + + case "5.1.0": + return array( + "Id" => "integer", + "Title" => "text", + "Description" => "text", + "Dir" => "directory", + "ImportId" => "text" + ); + } + } + + // media item + if ($a_entity == "mob_media_item") { + switch ($a_version) { + case "4.1.0": + return array( + "Id" => "integer", + "MobId" => "integer", + "Width" => "integer", + "Height" => "integer", + "Halign" => "text", + "Caption" => "text", + "Nr" => "integer", + "Purpose" => "text", + "Location" => "text", + "LocationType" => "text", + "Format" => "text", + "TextRepresentation" => "text" + ); + + case "4.3.0": + case "5.1.0": + return array( + "Id" => "integer", + "MobId" => "integer", + "Width" => "integer", + "Height" => "integer", + "Halign" => "text", + "Caption" => "text", + "Nr" => "integer", + "Purpose" => "text", + "Location" => "text", + "LocationType" => "text", + "Format" => "text", + "TextRepresentation" => "text" + ); + } + } + + // map areas + if ($a_entity == "mob_mi_map_area") { + switch ($a_version) { + case "4.1.0": + case "4.3.0": + case "5.1.0": + return array( + "MiId" => "integer", + "Nr" => "integer", + "Shape" => "text", + "Coords" => "text", + "LinkType" => "text", + "Title" => "text", + "Href" => "text", + "Target" => "text", + "Type" => "text", + "TargetFrame" => "text", + "HighlightMode" => "text", + "HighlightText" => "text" + ); + } + } + + // media item parameter + if ($a_entity == "mob_mi_parameter") { + switch ($a_version) { + case "4.1.0": + case "4.3.0": + case "5.1.0": + return array( + "MiId" => "integer", + "Name" => "text", + "Value" => "text" + ); + } + } + } + + /** + * 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); + } + + // mob + if ($a_entity == "mob") { + $this->data = array(); + + switch ($a_version) { + case "4.1.0": + case "4.3.0": + foreach ($a_ids as $mob_id) { + if (ilObject::_lookupType($mob_id) == "mob") { + $this->data[] = array("Id" => $mob_id, + "Title" => ilObject::_lookupTitle($mob_id), + "Description" => ilObject::_lookupDescription($mob_id) + ); + } + } + break; + + case "5.1.0": + foreach ($a_ids as $mob_id) { + if (ilObject::_lookupType($mob_id) == "mob") { + $this->data[] = array("Id" => $mob_id, + "Title" => ilObject::_lookupTitle($mob_id), + "Description" => ilObject::_lookupDescription($mob_id), + "ImportId" => ilObject::_lookupImportId($mob_id) + ); + } + } + break; + } + } + + // media item + if ($a_entity == "mob_media_item") { + switch ($a_version) { + case "4.1.0": + $this->getDirectDataFromQuery("SELECT id, mob_id, width, height, halign," . + "caption, nr, purpose, location, location_type, format, text_representation" . + " FROM media_item WHERE " . + $ilDB->in("mob_id", $a_ids, false, "integer")); + break; + + case "4.3.0": + case "5.1.0": + $this->getDirectDataFromQuery("SELECT id, mob_id, width, height, halign," . + "caption, nr, purpose, location, location_type, format, text_representation" . + " FROM media_item WHERE " . + $ilDB->in("mob_id", $a_ids, false, "integer")); + break; + } + } + + + // media item map area + if ($a_entity == "mob_mi_map_area") { + switch ($a_version) { + case "4.1.0": + case "4.3.0": + case "5.1.0": + foreach ($this->getDirectDataFromQuery("SELECT item_id mi_id, nr" . + " ,shape, coords, link_type, title, href, target, type, target_frame, " . + " highlight_mode, highlight_class" . + " FROM map_area " . + " WHERE " . + $ilDB->in("item_id", $a_ids, false, "integer") . + " ORDER BY nr", true, false) as $r) { + $r["Target"] = ilUtil::insertInstIntoID($r["Target"]); + + // see ilPageObject::insertInstIntoIDs + if ($r["Type"] == "RepositoryItem") { + $id_arr = explode("_", $r["Target"]); + $ref_id = $id_arr[3]; + $obj_id = ilObject::_lookupObjId($id_arr[3]); + + $otype = ilObject::_lookupType($obj_id); + if ($obj_id > 0) { + $id = $otype . "_" . $obj_id . "_" . $ref_id; + $r["Target"] = "il_" . $id_arr[1] . "_" . $id; + } + } + + $this->data[] = $r; + } + break; + } + } + + // media item parameter + if ($a_entity == "mob_mi_parameter") { + switch ($a_version) { + case "4.1.0": + case "4.3.0": + case "5.1.0": + $this->getDirectDataFromQuery("SELECT med_item_id mi_id, name, value" . + " FROM mob_parameter " . + " WHERE " . + $ilDB->in("med_item_id", $a_ids, false, "integer")); + break; + } + } + } + + /** + * Determine the dependent sets of data + */ + protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) + { + switch ($a_entity) { + case "mob": + return array( + "mob_media_item" => array("ids" => $a_rec["Id"]) + ); + + case "mob_media_item": + return array( + "mob_mi_map_area" => array("ids" => $a_rec["Id"]), + "mob_mi_parameter" => array("ids" => $a_rec["Id"]) + ); + } + return false; + } + + /** + * Get xml record + * + * @param + * @return + */ + public function getXmlRecord($a_entity, $a_version, $a_set) + { + if ($a_entity == "mob") { + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $dir = ilObjMediaObject::_getDirectory($a_set["Id"]); + $a_set["Dir"] = $dir; + } + + return $a_set; + } + + /** + * Import record + * + * @param + * @return + */ + public function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) + { + //echo $a_entity; + //var_dump($a_rec); + + switch ($a_entity) { + case "mob": //var_dump($a_rec); - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $newObj = new ilObjMediaObject(); - $newObj->setType("mob"); - $newObj->setTitle($a_rec["Title"]); - $newObj->setDescription($a_rec["Description"]); - // on translation re-import we are interested in the "previous" import id - if ($this->getUsePreviousImportIds()) - { - $newObj->setImportId($a_rec["ImportId"]); - } - else - { - $newObj->setImportId("il_".$this->getCurrentInstallationId()."_mob_".$a_rec["Id"]); - } - $newObj->create(); - $newObj->createDirectory(); - ilObjMediaObject::_createThumbnailDirectory($newObj->getId()); - $this->current_mob = $newObj; - - $dir = str_replace("..", "", $a_rec["Dir"]); - if ($dir != "" && $this->getImportDirectory() != "") - { - $source_dir = $this->getImportDirectory()."/".$dir; - $target_dir = $dir = ilObjMediaObject::_getDirectory($newObj->getId()); - $this->mob_log->debug("s:-$source_dir-,t:-$target_dir-"); - ilUtil::rCopy($source_dir, $target_dir); - ilObjMediaObject::renameExecutables($target_dir); - include_once("./Services/MediaObjects/classes/class.ilMediaSvgSanitizer.php"); - ilMediaSvgSanitizer::sanitizeDir($target_dir); // see #20339 - } - - $a_mapping->addMapping("Services/MediaObjects", "mob", $a_rec["Id"], $newObj->getId()); + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $newObj = new ilObjMediaObject(); + $newObj->setType("mob"); + $newObj->setTitle($a_rec["Title"]); + $newObj->setDescription($a_rec["Description"]); + // on translation re-import we are interested in the "previous" import id + if ($this->getUsePreviousImportIds()) { + $newObj->setImportId($a_rec["ImportId"]); + } else { + $newObj->setImportId("il_" . $this->getCurrentInstallationId() . "_mob_" . $a_rec["Id"]); + } + $newObj->create(); + $newObj->createDirectory(); + ilObjMediaObject::_createThumbnailDirectory($newObj->getId()); + $this->current_mob = $newObj; + + $dir = str_replace("..", "", $a_rec["Dir"]); + if ($dir != "" && $this->getImportDirectory() != "") { + $source_dir = $this->getImportDirectory() . "/" . $dir; + $target_dir = $dir = ilObjMediaObject::_getDirectory($newObj->getId()); + $this->mob_log->debug("s:-$source_dir-,t:-$target_dir-"); + ilUtil::rCopy($source_dir, $target_dir); + ilObjMediaObject::renameExecutables($target_dir); + include_once("./Services/MediaObjects/classes/class.ilMediaSvgSanitizer.php"); + ilMediaSvgSanitizer::sanitizeDir($target_dir); // see #20339 + } + + $a_mapping->addMapping("Services/MediaObjects", "mob", $a_rec["Id"], $newObj->getId()); //echo "
                  ++add++"."0:".$a_rec["Id"].":mob+0:".$newObj->getId().":mob"."+"; - $a_mapping->addMapping("Services/MetaData", "md", - "0:".$a_rec["Id"].":mob", "0:".$newObj->getId().":mob"); - break; - - case "mob_media_item": - - // determine parent mob - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $mob_id = (int) $a_mapping->getMapping("Services/MediaObjects", "mob", $a_rec["MobId"]); - if (is_object($this->current_mob) && $this->current_mob->getId() == $mob_id) - { - $mob = $this->current_mob; - } - else - { - $mob = new ilObjMediaObject($mob_id); - } - - include_once("./Services/MediaObjects/classes/class.ilMediaItem.php"); - $newObj = new ilMediaItem(); - $newObj->setMobId($mob_id); - $newObj->setWidth($a_rec["Width"]); - $newObj->setHeight($a_rec["Height"]); - $newObj->setCaption($a_rec["Caption"]); - $newObj->setNr($a_rec["Nr"]); - $newObj->setPurpose($a_rec["Purpose"]); - $newObj->setLocation($a_rec["Location"]); - $newObj->setLocationType($a_rec["LocationType"]); - $newObj->setFormat($a_rec["Format"]); - $newObj->setTextRepresentation($a_rec["TextRepresentation"]); - $newObj->create(); - $this->current_media_item = $newObj; - - $a_mapping->addMapping("Services/MediaObjects", "mob_media_item", $a_rec["Id"], $newObj->getId()); - - break; - - case "mob_mi_parameter": - - // get media item - include_once("./Services/MediaObjects/classes/class.ilMediaItem.php"); - $med_id = (int) $a_mapping->getMapping("Services/MediaObjects", "mob_media_item", $a_rec["MiId"]); - if (is_object($this->current_media_item) && $this->current_media_item->getId() == $med_id) - { - $med = $this->current_media_item; - } - else - { - $med = new ilMediaItem($med_id); - } - $med->writeParameter($a_rec["Name"], $a_rec["Value"]); - - break; - - case "mob_mi_map_area": - // get media item - include_once("./Services/MediaObjects/classes/class.ilMediaItem.php"); - $med_id = (int) $a_mapping->getMapping("Services/MediaObjects", "mob_media_item", $a_rec["MiId"]); - if (is_object($this->current_media_item) && $this->current_media_item->getId() == $med_id) - { - $med = $this->current_media_item; - } - else - { - $med = new ilMediaItem($med_id); - } - - include_once("./Services/MediaObjects/classes/class.ilMapArea.php"); - $map_area = new ilMapArea(); - $map_area->setItemId($med_id); - $map_area->setNr($a_rec["Nr"]); - $map_area->setShape($a_rec["Shape"]); - $map_area->setCoords($a_rec["Coords"]); - $map_area->setLinkType($a_rec["LinkType"]); - $map_area->setTitle($a_rec["Title"]); - $map_area->setHref($a_rec["Href"]); - $map_area->setTarget($a_rec["Target"]); - $map_area->setType($a_rec["Type"]); - $map_area->setTargetFrame($a_rec["TargetFrame"]); - $map_area->setHighlightMode($a_rec["HighlightMode"]); - $map_area->setHighlightClass($a_rec["HighlightClass"]); - $map_area->create(); - - break; - } - } - + $a_mapping->addMapping( + "Services/MetaData", + "md", + "0:" . $a_rec["Id"] . ":mob", + "0:" . $newObj->getId() . ":mob" + ); + break; + + case "mob_media_item": + + // determine parent mob + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $mob_id = (int) $a_mapping->getMapping("Services/MediaObjects", "mob", $a_rec["MobId"]); + if (is_object($this->current_mob) && $this->current_mob->getId() == $mob_id) { + $mob = $this->current_mob; + } else { + $mob = new ilObjMediaObject($mob_id); + } + + include_once("./Services/MediaObjects/classes/class.ilMediaItem.php"); + $newObj = new ilMediaItem(); + $newObj->setMobId($mob_id); + $newObj->setWidth($a_rec["Width"]); + $newObj->setHeight($a_rec["Height"]); + $newObj->setCaption($a_rec["Caption"]); + $newObj->setNr($a_rec["Nr"]); + $newObj->setPurpose($a_rec["Purpose"]); + $newObj->setLocation($a_rec["Location"]); + $newObj->setLocationType($a_rec["LocationType"]); + $newObj->setFormat($a_rec["Format"]); + $newObj->setTextRepresentation($a_rec["TextRepresentation"]); + $newObj->create(); + $this->current_media_item = $newObj; + + $a_mapping->addMapping("Services/MediaObjects", "mob_media_item", $a_rec["Id"], $newObj->getId()); + + break; + + case "mob_mi_parameter": + + // get media item + include_once("./Services/MediaObjects/classes/class.ilMediaItem.php"); + $med_id = (int) $a_mapping->getMapping("Services/MediaObjects", "mob_media_item", $a_rec["MiId"]); + if (is_object($this->current_media_item) && $this->current_media_item->getId() == $med_id) { + $med = $this->current_media_item; + } else { + $med = new ilMediaItem($med_id); + } + $med->writeParameter($a_rec["Name"], $a_rec["Value"]); + + break; + + case "mob_mi_map_area": + // get media item + include_once("./Services/MediaObjects/classes/class.ilMediaItem.php"); + $med_id = (int) $a_mapping->getMapping("Services/MediaObjects", "mob_media_item", $a_rec["MiId"]); + if (is_object($this->current_media_item) && $this->current_media_item->getId() == $med_id) { + $med = $this->current_media_item; + } else { + $med = new ilMediaItem($med_id); + } + + include_once("./Services/MediaObjects/classes/class.ilMapArea.php"); + $map_area = new ilMapArea(); + $map_area->setItemId($med_id); + $map_area->setNr($a_rec["Nr"]); + $map_area->setShape($a_rec["Shape"]); + $map_area->setCoords($a_rec["Coords"]); + $map_area->setLinkType($a_rec["LinkType"]); + $map_area->setTitle($a_rec["Title"]); + $map_area->setHref($a_rec["Href"]); + $map_area->setTarget($a_rec["Target"]); + $map_area->setType($a_rec["Type"]); + $map_area->setTargetFrame($a_rec["TargetFrame"]); + $map_area->setHighlightMode($a_rec["HighlightMode"]); + $map_area->setHighlightClass($a_rec["HighlightClass"]); + $map_area->create(); + + break; + } + } } -?> \ No newline at end of file diff --git a/Services/MediaObjects/classes/class.ilMediaObjectUsagesTableGUI.php b/Services/MediaObjects/classes/class.ilMediaObjectUsagesTableGUI.php index 2f623142f88afc708060e554f793d388ececa4a0..263e37d866dd501691e6370c9d4aa94aa98e4bb8 100755 --- a/Services/MediaObjects/classes/class.ilMediaObjectUsagesTableGUI.php +++ b/Services/MediaObjects/classes/class.ilMediaObjectUsagesTableGUI.php @@ -14,310 +14,269 @@ include_once("Services/Table/classes/class.ilTable2GUI.php"); */ class ilMediaObjectUsagesTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_media_object, - $a_include_hist = false) - { - global $DIC; + + /** + * Constructor + */ + public function __construct( + $a_parent_obj, + $a_parent_cmd, + $a_media_object, + $a_include_hist = false + ) { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->media_object = $a_media_object; - $this->include_hist = $a_include_hist; - $this->addColumn($lng->txt("mob_object")); - $this->addColumn($this->lng->txt("type")); - if ($a_include_hist) - { - $this->addColumn($this->lng->txt("cont_versions")); - } - //$this->setEnableHeader(false); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.mob_usage_row.html", "Services/MediaObjects"); - $this->getItems(); - $this->setTitle($lng->txt("cont_mob_usages")); - } + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->media_object = $a_media_object; + $this->include_hist = $a_include_hist; + $this->addColumn($lng->txt("mob_object")); + $this->addColumn($this->lng->txt("type")); + if ($a_include_hist) { + $this->addColumn($this->lng->txt("cont_versions")); + } + //$this->setEnableHeader(false); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.mob_usage_row.html", "Services/MediaObjects"); + $this->getItems(); + $this->setTitle($lng->txt("cont_mob_usages")); + } - /** - * Get items of current folder - */ - function getItems() - { - $usages = $this->media_object->getUsages($this->include_hist); - - $clip_cnt = 0; - $to_del = array(); - $agg_usages = array(); - foreach($usages as $k => $usage) - { - if ($usage["type"] == "clip") - { - $clip_cnt++; - } - else - { - if (empty($agg_usages[$usage["type"].":".$usage["id"]])) - { - $usage["hist_nr"] = array($usage["hist_nr"]); - $agg_usages[$usage["type"].":".$usage["id"]] = $usage; - } - else - { - $agg_usages[$usage["type"].":".$usage["id"]]["hist_nr"][] = - $usage["hist_nr"]; - } - } - } + /** + * Get items of current folder + */ + public function getItems() + { + $usages = $this->media_object->getUsages($this->include_hist); + + $clip_cnt = 0; + $to_del = array(); + $agg_usages = array(); + foreach ($usages as $k => $usage) { + if ($usage["type"] == "clip") { + $clip_cnt++; + } else { + if (empty($agg_usages[$usage["type"] . ":" . $usage["id"]])) { + $usage["hist_nr"] = array($usage["hist_nr"]); + $agg_usages[$usage["type"] . ":" . $usage["id"]] = $usage; + } else { + $agg_usages[$usage["type"] . ":" . $usage["id"]]["hist_nr"][] = + $usage["hist_nr"]; + } + } + } - // usages in clipboards - if ($clip_cnt > 0) - { - $agg_usages[] = array("type" => "clip", "cnt" => $clip_cnt); - } + // usages in clipboards + if ($clip_cnt > 0) { + $agg_usages[] = array("type" => "clip", "cnt" => $clip_cnt); + } - $this->setData($agg_usages); - } - - /** - * Standard Version of Fill Row. Most likely to - * be overwritten by derived class. - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; + $this->setData($agg_usages); + } + + /** + * Standard Version of Fill Row. Most likely to + * be overwritten by derived class. + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; - $usage = $a_set; - -//var_dump($usage); + $usage = $a_set; + + //var_dump($usage); - if(is_int(strpos($usage["type"], ":"))) - { - $us_arr = explode(":", $usage["type"]); - $usage["type"] = $us_arr[1]; - $cont_type = $us_arr[0]; - } + if (is_int(strpos($usage["type"], ":"))) { + $us_arr = explode(":", $usage["type"]); + $usage["type"] = $us_arr[1]; + $cont_type = $us_arr[0]; + } - include_once('./Services/Link/classes/class.ilLink.php'); + include_once('./Services/Link/classes/class.ilLink.php'); - switch($usage["type"]) - { - case "pg": - include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); - $page_obj = ilPageObjectFactory::getInstance($cont_type, $usage["id"]); + switch ($usage["type"]) { + case "pg": + include_once("./Services/COPage/classes/class.ilPageObjectFactory.php"); + $page_obj = ilPageObjectFactory::getInstance($cont_type, $usage["id"]); - $item = array(); + $item = array(); - //$this->tpl->setVariable("TXT_OBJECT", $usage["type"].":".$usage["id"]); - switch ($cont_type) - { - case "lm": - require_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); - require_once("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); - require_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - if (ilObject::_lookupType($page_obj->getParentId()) == "lm") - { - $lm_obj = new ilObjLearningModule($page_obj->getParentId(), false); - $item["obj_type_txt"] = $this->lng->txt("obj_".$cont_type); - $item["obj_title"] = $lm_obj->getTitle(); - $item["sub_txt"] = $this->lng->txt("pg"); - $item["sub_title"] = ilLMObject::_lookupTitle($page_obj->getId()); - $ref_id = $this->getFirstWritableRefId($lm_obj->getId()); - if ($ref_id > 0) - { - $item["obj_link"] = ilLink::_getStaticLink($page_obj->getId()."_".$ref_id, "pg"); - } - } - break; + //$this->tpl->setVariable("TXT_OBJECT", $usage["type"].":".$usage["id"]); + switch ($cont_type) { + case "lm": + require_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); + require_once("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); + require_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + if (ilObject::_lookupType($page_obj->getParentId()) == "lm") { + $lm_obj = new ilObjLearningModule($page_obj->getParentId(), false); + $item["obj_type_txt"] = $this->lng->txt("obj_" . $cont_type); + $item["obj_title"] = $lm_obj->getTitle(); + $item["sub_txt"] = $this->lng->txt("pg"); + $item["sub_title"] = ilLMObject::_lookupTitle($page_obj->getId()); + $ref_id = $this->getFirstWritableRefId($lm_obj->getId()); + if ($ref_id > 0) { + $item["obj_link"] = ilLink::_getStaticLink($page_obj->getId() . "_" . $ref_id, "pg"); + } + } + break; - case "wpg": - require_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $item["obj_type_txt"] = $this->lng->txt("obj_wiki"); - $item["obj_title"] = ilObject::_lookupTitle($page_obj->getParentId()); - $item["sub_txt"] = $this->lng->txt("pg"); - $item["sub_title"] = ilWikiPage::lookupTitle($page_obj->getId()); - $ref_id = $this->getFirstWritableRefId($page_obj->getParentId()); - if ($ref_id > 0) - { - $item["obj_link"] = ilLink::_getStaticLink($ref_id, "wiki"); - } - break; + case "wpg": + require_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + $item["obj_type_txt"] = $this->lng->txt("obj_wiki"); + $item["obj_title"] = ilObject::_lookupTitle($page_obj->getParentId()); + $item["sub_txt"] = $this->lng->txt("pg"); + $item["sub_title"] = ilWikiPage::lookupTitle($page_obj->getId()); + $ref_id = $this->getFirstWritableRefId($page_obj->getParentId()); + if ($ref_id > 0) { + $item["obj_link"] = ilLink::_getStaticLink($ref_id, "wiki"); + } + break; - case "gdf": - require_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - require_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); - $term_id = ilGlossaryDefinition::_lookupTermId($page_obj->getId()); - $glo_id = ilGlossaryTerm::_lookGlossaryId($term_id); - $item["obj_type_txt"] = $this->lng->txt("obj_glo"); - $item["obj_title"] = ilObject::_lookupTitle($glo_id); - $item["sub_txt"] = $this->lng->txt("cont_term"); - $item["sub_title"] = ilGlossaryTerm::_lookGlossaryTerm($term_id); - $ref_id = $this->getFirstWritableRefId($page_obj->getParentId()); - if ($ref_id > 0) - { - $item["obj_link"] = ilLink::_getStaticLink($ref_id, "glo"); - } - break; + case "gdf": + require_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + require_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); + $term_id = ilGlossaryDefinition::_lookupTermId($page_obj->getId()); + $glo_id = ilGlossaryTerm::_lookGlossaryId($term_id); + $item["obj_type_txt"] = $this->lng->txt("obj_glo"); + $item["obj_title"] = ilObject::_lookupTitle($glo_id); + $item["sub_txt"] = $this->lng->txt("cont_term"); + $item["sub_title"] = ilGlossaryTerm::_lookGlossaryTerm($term_id); + $ref_id = $this->getFirstWritableRefId($page_obj->getParentId()); + if ($ref_id > 0) { + $item["obj_link"] = ilLink::_getStaticLink($ref_id, "glo"); + } + break; - case "cont": - $otype = ilObject::_lookupType($page_obj->getId()); - $item["obj_type_txt"] = $this->lng->txt("obj_".$otype); - $item["obj_title"] = ilObject::_lookupTitle($page_obj->getId()); - $ref_id = $this->getFirstWritableRefId($page_obj->getId()); - if ($ref_id > 0) - { - $item["obj_link"] = ilLink::_getStaticLink($ref_id, $otype); - } - break; + case "cont": + $otype = ilObject::_lookupType($page_obj->getId()); + $item["obj_type_txt"] = $this->lng->txt("obj_" . $otype); + $item["obj_title"] = ilObject::_lookupTitle($page_obj->getId()); + $ref_id = $this->getFirstWritableRefId($page_obj->getId()); + if ($ref_id > 0) { + $item["obj_link"] = ilLink::_getStaticLink($ref_id, $otype); + } + break; - default: - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $oid = ilObjMediaObject::getParentObjectIdForUsage($a_set); - if ($oid > 0) - { - $type = ilObject::_lookupType($oid); - $item["obj_type_txt"] = $this->lng->txt("obj_".$type); - $item["obj_title"] = ilObject::_lookupTitle($oid); - $ref_id = $this->getFirstWritableRefId($oid); - if ($ref_id > 0) - { - $item["obj_link"] = ilLink::_getStaticLink($ref_id, $type); - } - } - break; - } - break; + default: + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $oid = ilObjMediaObject::getParentObjectIdForUsage($a_set); + if ($oid > 0) { + $type = ilObject::_lookupType($oid); + $item["obj_type_txt"] = $this->lng->txt("obj_" . $type); + $item["obj_title"] = ilObject::_lookupTitle($oid); + $ref_id = $this->getFirstWritableRefId($oid); + if ($ref_id > 0) { + $item["obj_link"] = ilLink::_getStaticLink($ref_id, $type); + } + } + break; + } + break; - case "mep": - $item["obj_type_txt"] = $this->lng->txt("obj_mep"); - $item["obj_title"] = ilObject::_lookupTitle($usage["id"]); - $ref_id = $this->getFirstWritableRefId($usage["id"]); - if ($ref_id > 0) - { - $item["obj_link"] = ilLink::_getStaticLink($ref_id, "mep"); - } - break; + case "mep": + $item["obj_type_txt"] = $this->lng->txt("obj_mep"); + $item["obj_title"] = ilObject::_lookupTitle($usage["id"]); + $ref_id = $this->getFirstWritableRefId($usage["id"]); + if ($ref_id > 0) { + $item["obj_link"] = ilLink::_getStaticLink($ref_id, "mep"); + } + break; - case "map": - $item["obj_type_txt"] = $this->lng->txt("obj_mob"); - $item["obj_title"] = ilObject::_lookupTitle($usage["id"]); - $item["sub_txt"] = $this->lng->txt("cont_link_area"); - break; - } - - // show versions - if ($this->include_hist) - { - $ver = ""; - if (is_array($usage["hist_nr"]) && - (count($usage["hist_nr"]) > 1 || $usage["hist_nr"][0] > 0)) - { - asort($usage["hist_nr"]); - $ver = $sep = ""; - if ($usage["hist_nr"][0] == 0) - { - array_shift($usage["hist_nr"]); - $usage["hist_nr"][] = 0; - } - if (count($usage["hist_nr"]) > 5) - { - $ver.= "..., "; - $cnt = count($usage["hist_nr"]) - 5; - for ($i = 0; $i < $cnt; $i++) - { - unset($usage["hist_nr"][$i]); - } - } + case "map": + $item["obj_type_txt"] = $this->lng->txt("obj_mob"); + $item["obj_title"] = ilObject::_lookupTitle($usage["id"]); + $item["sub_txt"] = $this->lng->txt("cont_link_area"); + break; + } + + // show versions + if ($this->include_hist) { + $ver = ""; + if (is_array($usage["hist_nr"]) && + (count($usage["hist_nr"]) > 1 || $usage["hist_nr"][0] > 0)) { + asort($usage["hist_nr"]); + $ver = $sep = ""; + if ($usage["hist_nr"][0] == 0) { + array_shift($usage["hist_nr"]); + $usage["hist_nr"][] = 0; + } + if (count($usage["hist_nr"]) > 5) { + $ver.= "..., "; + $cnt = count($usage["hist_nr"]) - 5; + for ($i = 0; $i < $cnt; $i++) { + unset($usage["hist_nr"][$i]); + } + } - foreach ($usage["hist_nr"] as $nr) - { - if ($nr > 0) - { - $ver.= $sep.$nr; - } - else - { - $ver.= $sep.$this->lng->txt("cont_current_version"); - } - $sep = ", "; - } + foreach ($usage["hist_nr"] as $nr) { + if ($nr > 0) { + $ver.= $sep . $nr; + } else { + $ver.= $sep . $this->lng->txt("cont_current_version"); + } + $sep = ", "; + } + } + $this->tpl->setCurrentBlock("versions"); + $this->tpl->setVariable("VAL_VERSIONS", $ver); + $this->tpl->parseCurrentBlock(); + } - } - $this->tpl->setCurrentBlock("versions"); - $this->tpl->setVariable("VAL_VERSIONS", $ver); - $this->tpl->parseCurrentBlock(); - } + if ($item["obj_type_txt"] != "") { + $this->tpl->setVariable("VAL_TYPE", $item["obj_type_txt"]); + } - if ($item["obj_type_txt"] != "") - { - $this->tpl->setVariable("VAL_TYPE", $item["obj_type_txt"]); - } + if ($usage["type"] != "clip") { + if ($item["obj_link"]) { + $this->tpl->setCurrentBlock("linked_item"); + $this->tpl->setVariable("TXT_OBJECT", $item["obj_title"]); + $this->tpl->setVariable("HREF_LINK", $item["obj_link"]); + $this->tpl->parseCurrentBlock(); + } else { + $this->tpl->setVariable("TXT_OBJECT_NO_LINK", $item["obj_title"]); + } + + if ($item["sub_txt"] != "") { + $this->tpl->setVariable("SEP", ", "); + $this->tpl->setVariable("SUB_TXT", $item["sub_txt"]); + if ($item["sub_title"] != "") { + $this->tpl->setVariable("SEP2", ": "); + $this->tpl->setVariable("SUB_TITLE", $item["sub_title"]); + } + } + } else { + $this->tpl->setVariable("TXT_OBJECT_NO_LINK", $this->lng->txt("cont_users_have_mob_in_clip1") . + " " . $usage["cnt"] . " " . $this->lng->txt("cont_users_have_mob_in_clip2")); + } + } - if ($usage["type"] != "clip") - { - if ($item["obj_link"]) - { - $this->tpl->setCurrentBlock("linked_item"); - $this->tpl->setVariable("TXT_OBJECT", $item["obj_title"]); - $this->tpl->setVariable("HREF_LINK", $item["obj_link"]); - $this->tpl->parseCurrentBlock(); - } - else - { - $this->tpl->setVariable("TXT_OBJECT_NO_LINK", $item["obj_title"]); - } - - if ($item["sub_txt"] != "") - { - $this->tpl->setVariable("SEP", ", "); - $this->tpl->setVariable("SUB_TXT", $item["sub_txt"]); - if ($item["sub_title"] != "") - { - $this->tpl->setVariable("SEP2", ": "); - $this->tpl->setVariable("SUB_TITLE", $item["sub_title"]); - } - } - - } - else - { - $this->tpl->setVariable("TXT_OBJECT_NO_LINK", $this->lng->txt("cont_users_have_mob_in_clip1"). - " ".$usage["cnt"]." ".$this->lng->txt("cont_users_have_mob_in_clip2")); - - } - } - - function getFirstWritableRefId($a_obj_id) - { - $ilAccess = $this->access; - - $ref_ids = ilObject::_getAllReferences($a_obj_id); - foreach ($ref_ids as $ref_id) - { - if ($ilAccess->checkAccess("write", "", $ref_id)) - { - return $ref_id; - } - } - return 0; - } + public function getFirstWritableRefId($a_obj_id) + { + $ilAccess = $this->access; + + $ref_ids = ilObject::_getAllReferences($a_obj_id); + foreach ($ref_ids as $ref_id) { + if ($ilAccess->checkAccess("write", "", $ref_id)) { + return $ref_id; + } + } + return 0; + } } -?> diff --git a/Services/MediaObjects/classes/class.ilMediaObjectsExporter.php b/Services/MediaObjects/classes/class.ilMediaObjectsExporter.php index 91e1522601a1d0eda8583c9847bc580272dd0769..103eedf1658b7bab5f362586057d3e489919e5b0 100644 --- a/Services/MediaObjects/classes/class.ilMediaObjectsExporter.php +++ b/Services/MediaObjects/classes/class.ilMediaObjectsExporter.php @@ -12,88 +12,84 @@ include_once("./Services/Export/classes/class.ilXmlExporter.php"); */ class ilMediaObjectsExporter extends ilXmlExporter { - private $ds; + private $ds; - /** - * Initialisation - */ - function init() - { - include_once("./Services/MediaObjects/classes/class.ilMediaObjectDataSet.php"); - $this->ds = new ilMediaObjectDataSet(); - $this->ds->setDSPrefix("ds"); - } + /** + * Initialisation + */ + public function init() + { + include_once("./Services/MediaObjects/classes/class.ilMediaObjectDataSet.php"); + $this->ds = new ilMediaObjectDataSet(); + $this->ds->setDSPrefix("ds"); + } - /** - * Get tail dependencies - * - * @param string entity - * @param string target release - * @param array ids - * @return array array of array with keys "component", entity", "ids" - */ - public function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) - { - $md_ids = array(); - foreach ($a_ids as $mob_id) - { - $md_ids[] = "0:".$mob_id.":mob"; - } + /** + * Get tail dependencies + * + * @param string entity + * @param string target release + * @param array ids + * @return array array of array with keys "component", entity", "ids" + */ + public function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) + { + $md_ids = array(); + foreach ($a_ids as $mob_id) { + $md_ids[] = "0:" . $mob_id . ":mob"; + } - return array ( - array( - "component" => "Services/MetaData", - "entity" => "md", - "ids" => $md_ids) - ); - } + return array( + array( + "component" => "Services/MetaData", + "entity" => "md", + "ids" => $md_ids) + ); + } - /** - * Get xml representation - * - * @param string entity - * @param string schema version - * @param string id - * @return string xml string - */ - public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) - { - ilUtil::makeDirParents($this->getAbsoluteExportDirectory()); - $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); - return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); - } - - /** - * Returns schema versions that the component can export to. - * ILIAS chooses the first one, that has min/max constraints which - * fit to the target release. Please put the newest on top. - * - * @return - */ - function getValidSchemaVersions($a_entity) - { - return array ( - "5.1.0" => array( - "namespace" => "http://www.ilias.de/Services/MediaObjects/mob/5_1", - "xsd_file" => "ilias_mob_5_1.xsd", - "uses_dataset" => true, - "min" => "5.1.0", - "max" => ""), - "4.3.0" => array( - "namespace" => "http://www.ilias.de/Services/MediaObjects/mob/4_3", - "xsd_file" => "ilias_mob_4_3.xsd", - "uses_dataset" => true, - "min" => "4.3.0", - "max" => ""), - "4.1.0" => array( - "namespace" => "http://www.ilias.de/Services/MediaObjects/mob/4_1", - "xsd_file" => "ilias_mob_4_1.xsd", - "uses_dataset" => true, - "min" => "4.1.0", - "max" => "") - ); - } + /** + * Get xml representation + * + * @param string entity + * @param string schema version + * @param string id + * @return string xml string + */ + public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) + { + ilUtil::makeDirParents($this->getAbsoluteExportDirectory()); + $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); + return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); + } + /** + * Returns schema versions that the component can export to. + * ILIAS chooses the first one, that has min/max constraints which + * fit to the target release. Please put the newest on top. + * + * @return + */ + public function getValidSchemaVersions($a_entity) + { + return array( + "5.1.0" => array( + "namespace" => "http://www.ilias.de/Services/MediaObjects/mob/5_1", + "xsd_file" => "ilias_mob_5_1.xsd", + "uses_dataset" => true, + "min" => "5.1.0", + "max" => ""), + "4.3.0" => array( + "namespace" => "http://www.ilias.de/Services/MediaObjects/mob/4_3", + "xsd_file" => "ilias_mob_4_3.xsd", + "uses_dataset" => true, + "min" => "4.3.0", + "max" => ""), + "4.1.0" => array( + "namespace" => "http://www.ilias.de/Services/MediaObjects/mob/4_1", + "xsd_file" => "ilias_mob_4_1.xsd", + "uses_dataset" => true, + "min" => "4.1.0", + "max" => "") + ); + } } - -?> \ No newline at end of file diff --git a/Services/MediaObjects/classes/class.ilMediaObjectsImportConfig.php b/Services/MediaObjects/classes/class.ilMediaObjectsImportConfig.php index c42b314ea2b17749f66c68c0c588a5dc174cc584..c50a5dbbba6adc67bb1934090b01b39bbe3760e4 100644 --- a/Services/MediaObjects/classes/class.ilMediaObjectsImportConfig.php +++ b/Services/MediaObjects/classes/class.ilMediaObjectsImportConfig.php @@ -12,28 +12,25 @@ include_once("./Services/Export/classes/class.ilImportConfig.php"); */ class ilMediaObjectsImportConfig extends ilImportConfig { - protected $use_previous_import_ids = false; + protected $use_previous_import_ids = false; - /** - * Set use previous import ids - * - * @param bool $a_val use previous import ids - */ - function setUsePreviousImportIds($a_val) - { - $this->use_previous_import_ids = $a_val; - } - - /** - * Get use previous import ids - * - * @return bool use previous import ids - */ - function getUsePreviousImportIds() - { - return $this->use_previous_import_ids; - } + /** + * Set use previous import ids + * + * @param bool $a_val use previous import ids + */ + public function setUsePreviousImportIds($a_val) + { + $this->use_previous_import_ids = $a_val; + } + /** + * Get use previous import ids + * + * @return bool use previous import ids + */ + public function getUsePreviousImportIds() + { + return $this->use_previous_import_ids; + } } - -?> \ No newline at end of file diff --git a/Services/MediaObjects/classes/class.ilMediaObjectsImporter.php b/Services/MediaObjects/classes/class.ilMediaObjectsImporter.php index 789bf3e1445dc4a01b4d87428cf49035c5113197..ba4b6096a129427987650574358f1f1d197e3b46 100644 --- a/Services/MediaObjects/classes/class.ilMediaObjectsImporter.php +++ b/Services/MediaObjects/classes/class.ilMediaObjectsImporter.php @@ -13,40 +13,41 @@ include_once("./Services/Export/classes/class.ilXmlImporter.php"); class ilMediaObjectsImporter extends ilXmlImporter { - /** - * Init - * - * @param - * @return - */ - function init() - { - include_once("./Services/MediaObjects/classes/class.ilMediaObjectDataSet.php"); - $this->ds = new ilMediaObjectDataSet(); - $this->ds->setDSPrefix("ds"); - $this->ds->setImportDirectory($this->getImportDirectory()); + /** + * Init + * + * @param + * @return + */ + public function init() + { + include_once("./Services/MediaObjects/classes/class.ilMediaObjectDataSet.php"); + $this->ds = new ilMediaObjectDataSet(); + $this->ds->setDSPrefix("ds"); + $this->ds->setImportDirectory($this->getImportDirectory()); - $this->config = $this->getImport()->getConfig("Services/MediaObjects"); - if ($this->config->getUsePreviousImportIds()) - { - $this->ds->setUsePreviousImportIds(true); - } - } + $this->config = $this->getImport()->getConfig("Services/MediaObjects"); + if ($this->config->getUsePreviousImportIds()) { + $this->ds->setUsePreviousImportIds(true); + } + } - /** - * Import XML - * - * @param - * @return - */ - function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) - { - include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); - $parser = new ilDataSetImportParser($a_entity, $this->getSchemaVersion(), - $a_xml, $this->ds, $a_mapping); - } - + /** + * Import XML + * + * @param + * @return + */ + public function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) + { + include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); + $parser = new ilDataSetImportParser( + $a_entity, + $this->getSchemaVersion(), + $a_xml, + $this->ds, + $a_mapping + ); + } } - -?> \ No newline at end of file diff --git a/Services/MediaObjects/classes/class.ilMediaPlayerGUI.php b/Services/MediaObjects/classes/class.ilMediaPlayerGUI.php index c5e3fd9250ce04d64249e9fbd1c1a9108548ccf5..6fa7a0bfdba9843080c5a781bcd9e864d2fda14b 100755 --- a/Services/MediaObjects/classes/class.ilMediaPlayerGUI.php +++ b/Services/MediaObjects/classes/class.ilMediaPlayerGUI.php @@ -12,591 +12,553 @@ */ class ilMediaPlayerGUI { - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilLanguage - */ - protected $lng; - - protected $file; - protected $displayHeight = "480"; - protected $displayWidth = "640"; - protected $mimeType; - protected static $nr = 1; - protected static $lightbox_initialized = false; - protected $current_nr; - protected $title; - protected $description; - protected $event_callback_url = ""; - protected $download_link = ""; - - function __construct($a_id = "", $a_event_callback_url = "") - { - global $DIC; - - $this->tpl = $DIC["tpl"]; - $this->lng = $DIC->language(); - $this->id = $a_id; - $this->event_callback_url = $a_event_callback_url; - $this->current_nr = self::$nr; - self::$nr++; - } - - /** - * Set File. - * - * @param string $a_file File - */ - function setFile($a_file) - { - $this->file = $a_file; - } - - /** - * Get File. - * - * @return string File - */ - function getFile() - { - return $this->file; - } - - /** - * Set alternative video file - * - * @param string $a_val alternative video file - */ - function setAlternativeVideoFile($a_val) - { - $this->alt_video_file = $a_val; - } - - /** - * Get alternative video file - * - * @return string alternative video file - */ - function getAlternativeVideoFile() - { - return $this->alt_video_file; - } - - /** - * Set alternative video mime type - * - * @param string $a_val alternative video mime type - */ - function setAlternativeVideoMimeType($a_val) - { - $this->alt_video_mime = $a_val; - } - - /** - * Get alternative video mime type - * - * @return string alternative video mime type - */ - function getAlternativeVideoMimeType() - { - return $this->alt_video_mime; - } - - /** - * set display height - * - * @param int $dHeight - */ - function setDisplayHeight ($dHeight) { - $this->displayHeight = $dHeight; - } - - /** - * return display height of player. - * - * @return int - */ - function getDisplayHeight () { - return $this->displayHeight; - } - - /** - * Set display width - * - * @param string $a_val display width - */ - function setDisplayWidth($a_val) - { - $this->displayWidth = $a_val; - } - - /** - * Get display width - * - * @return string display width - */ - function getDisplayWidth() - { - return $this->displayWidth; - } - - function setMimeType ($value) { - $this->mimeType = $value; - } - - /** - * Set video preview picture - * - * @param string $a_val video preview picture - */ - function setVideoPreviewPic($a_val, $a_alt = "") - { - $this->video_preview_pic = $a_val; - $this->video_preview_pic_alt = $a_alt; - } - - /** - * Get video preview picture - * - * @return string video preview picture - */ - function getVideoPreviewPic() - { - return $this->video_preview_pic; - } - - /** - * Set Title - * - * @param string $a_val title - */ - function setTitle($a_val) - { - $this->title = $a_val; - } - - /** - * Get Title - * - * @return string title - */ - function getTitle() - { - return $this->title; - } - - /** - * Set description - * - * @param string $a_val description - */ - function setDescription($a_val) - { - $this->description = $a_val; - } - - /** - * Get description - * - * @return string description - */ - function getDescription() - { - return $this->description; - } - - /** - * Set force audio preview - * - * @param boolean $a_val force audio preview picture - */ - function setForceAudioPreview($a_val) - { - $this->force_audio_preview = $a_val; - } - - /** - * Get force audio preview - * - * @return boolean force audio preview picture - */ - function getForceAudioPreview() - { - return $this->force_audio_preview; - } - - /** - * Set download link - * - * @param string $a_val download link - */ - function setDownloadLink($a_val) - { - $this->download_link = $a_val; - } - - /** - * Get download link - * - * @return string download link - */ - function getDownloadLink() - { - return $this->download_link; - } - - /** - * Init Javascript - * @param null $a_tpl - */ - public static function initJavascript($a_tpl = null) - { - global $DIC; - - $tpl = $DIC["tpl"]; - - if ($a_tpl == null) - { - $a_tpl = $tpl; - } - - include_once("./Services/YUI/classes/class.ilYuiUtil.php"); - ilYuiUtil::initConnection(); - - $a_tpl->addJavascript("./Services/MediaObjects/js/MediaObjects.js"); - - include_once("./Services/MediaObjects/classes/class.ilPlayerUtil.php"); - ilPlayerUtil::initMediaElementJs($a_tpl); - } - - - /** - * Get Html for MP3 Player - */ - function getMp3PlayerHtml($a_preview = false) - { - $tpl = $this->tpl; - $lng = $this->lng; - - self::initJavascript($tpl); - - if (!self::$lightbox_initialized && $a_preview) - { - include_once("./Services/UIComponent/Lightbox/classes/class.ilLightboxGUI.php"); - $lb = new ilLightboxGUI("media_lightbox"); - $lb->setWidth("660px"); - $lb->addLightbox(); - self::$lightbox_initialized = true; - } - - require_once 'Services/MediaObjects/classes/class.ilObjMediaObject.php'; - include_once("./Services/MediaObjects/classes/class.ilExternalMediaAnalyzer.php"); - - // youtube - if (ilExternalMediaAnalyzer::isYouTube($this->getFile())) - { - $p = ilExternalMediaAnalyzer::extractYouTubeParameters($this->getFile()); - /* - $html = ''. - ''. - ''. - ''. - ''; - return $html;*/ - $mp_tpl = new ilTemplate("tpl.flv_player.html", true, true, "Services/MediaObjects"); - if ($a_preview) - { - if ($this->getDownloadLink() != "") - { - $mp_tpl->setCurrentBlock("ytdownload"); - $mp_tpl->setVariable("TXT_DOWNLOAD", $lng->txt("download")); - $mp_tpl->setVariable("HREF_DOWNLOAD", $this->getDownloadLink()); - $mp_tpl->parseCurrentBlock(); - } - - $mp_tpl->setCurrentBlock("ytpreview"); - if ($this->getVideoPreviewPic() != "") - { - $mp_tpl->setVariable("IMG_SRC", $this->getVideoPreviewPic()); - } - else - { - $mp_tpl->setVariable("IMG_SRC", ilUtil::getImagePath("mcst_preview.svg")); - } - $height = $this->getDisplayHeight(); - $width = $this->getDisplayWidth(); - $mp_tpl->setVariable("DISPLAY_HEIGHT", $height); - $mp_tpl->setVariable("DISPLAY_WIDTH", $width); - $mp_tpl->setVariable("IMG_ALT", $this->video_preview_pic_alt); - $mp_tpl->setVariable("PTITLE", $this->getTitle()); - $mp_tpl->parseCurrentBlock(); - } - $mp_tpl->setCurrentBlock("youtube"); - if ($a_preview) - { - $mp_tpl->setVariable("CLASS", "ilNoDisplay"); - } - $mp_tpl->setVariable("PV", $p["v"]); - $mp_tpl->setVariable("PLAYER_NR", $this->id."_".$this->current_nr); - $mp_tpl->setVariable("TITLE", $this->getTitle()); - $mp_tpl->setVariable("DESCRIPTION", $this->getDescription()); - include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); - if ($a_preview) - { - $mp_tpl->setVariable("CLOSE", ilGlyphGUI::get(ilGlyphGUI::CLOSE)); - } - $mp_tpl->parseCurrentBlock(); - return $mp_tpl->get(); - } - - // vimeo - if (ilExternalMediaAnalyzer::isVimeo($this->getFile())) - { - $p = ilExternalMediaAnalyzer::extractVimeoParameters($this->getFile()); - - $html = ''; - - return $html; - } - - $mimeType = $this->mimeType == "" ? ilObjMediaObject::getMimeType(basename($this->getFile())) : $this->mimeType; - include_once("./Services/MediaObjects/classes/class.ilPlayerUtil.php"); - - // video tag - if (in_array($mimeType, array("video/mp4", "video/m4v", "video/rtmp", - "video/x-flv", "video/webm", "video/youtube", "video/vimeo", "video/ogg"))) - { - - if ($mimeType == "video/quicktime") - { - $mimeType = "video/mov"; - } - - $mp_tpl = new ilTemplate("tpl.flv_player.html", true, true, "Services/MediaObjects"); - - // preview - if ($a_preview) - { - if ($this->getDownloadLink() != "") - { - $mp_tpl->setCurrentBlock("download"); - $mp_tpl->setVariable("TXT_DOWNLOAD", $lng->txt("download")); - $mp_tpl->setVariable("HREF_DOWNLOAD", $this->getDownloadLink()); - $mp_tpl->parseCurrentBlock(); - } - - $mp_tpl->setCurrentBlock("preview"); - if ($this->getVideoPreviewPic() != "") - { - $mp_tpl->setVariable("IMG_SRC", $this->getVideoPreviewPic()); - } - else - { - $mp_tpl->setVariable("IMG_SRC", ilUtil::getImagePath("mcst_preview.svg")); - } - $mp_tpl->setVariable("IMG_ALT", $this->video_preview_pic_alt); - $mp_tpl->setVariable("PTITLE", $this->getTitle()); - $mp_tpl->parseCurrentBlock(); - } - - // sources - $mp_tpl->setCurrentBlock("source"); - $mp_tpl->setVariable("FILE", $this->getFile()); - $mp_tpl->setVariable("MIME", $mimeType); - $mp_tpl->parseCurrentBlock(); - - if (in_array($this->getAlternativeVideoMimeType(), array("video/mp4", "video/webm"))) - { - $mp_tpl->setCurrentBlock("source"); - $mp_tpl->setVariable("FILE", $this->getAlternativeVideoFile()); - $mp_tpl->setVariable("MIME", $this->getAlternativeVideoMimeType()); - $mp_tpl->parseCurrentBlock(); - } - - $mp_tpl->setCurrentBlock("mejs_video"); - - if ($a_preview) - { - $mp_tpl->setVariable("CLASS", "ilNoDisplay"); - } - - $mp_tpl->setVariable("PLAYER_NR", $this->id."_".$this->current_nr); - $mp_tpl->setVariable("EVENT_URL", $this->event_callback_url); - $height = $this->getDisplayHeight(); - $width = $this->getDisplayWidth(); - if (is_int(strpos($mimeType,"audio/mpeg"))) - { - $height = "30"; - } - - $mp_tpl->setVariable("DISPLAY_HEIGHT", $height); - $mp_tpl->setVariable("DISPLAY_WIDTH", $width); - $mp_tpl->setVariable("PREVIEW_PIC", $this->getVideoPreviewPic()); - $mp_tpl->setVariable("SWF_FILE", ilPlayerUtil::getFlashVideoPlayerFilename(true)); - $mp_tpl->setVariable("FFILE", $this->getFile()); - $mp_tpl->setVariable("TITLE", $this->getTitle()); - $mp_tpl->setVariable("DESCRIPTION", $this->getDescription()); - include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); - if ($a_preview) - { - $mp_tpl->setVariable("CLOSE", ilGlyphGUI::get(ilGlyphGUI::CLOSE)); - } - $mp_tpl->parseCurrentBlock(); - $r = $mp_tpl->get(); - - if (!$a_preview) - { - $tpl->addOnLoadCode("new MediaElementPlayer('#player_".$this->id."_".$this->current_nr."');"); - } - -//echo htmlentities($r); exit; - return $r; - } - - // audio/mpeg - if (is_int(strpos($mimeType,"audio/mpeg")) || - in_array($mimeType, array("application/ogg", "audio/ogg"))) - { - ilPlayerUtil::initMediaElementJs(); - $mp_tpl = new ilTemplate("tpl.flv_player.html", true, true, "Services/MediaObjects"); - $preview_output = false; - if ($this->getVideoPreviewPic() != "" || $this->getForceAudioPreview()) - { - if ($this->getDownloadLink() != "") - { - $mp_tpl->setCurrentBlock("adownload"); - $mp_tpl->setVariable("TXT_DOWNLOAD", $lng->txt("download")); - $mp_tpl->setVariable("HREF_DOWNLOAD", $this->getDownloadLink()); - $mp_tpl->parseCurrentBlock(); - } - - $mp_tpl->setCurrentBlock("apreview"); - if ($this->getVideoPreviewPic() != "") - { - $mp_tpl->setVariable("IMG_SRC", $this->getVideoPreviewPic()); - } - else - { - $mp_tpl->setVariable("IMG_SRC", ilUtil::getImagePath("mcst_preview.svg")); - } - $mp_tpl->setVariable("PTITLE", $this->getTitle()); - $mp_tpl->parseCurrentBlock(); - $preview_output = true; - } - $mp_tpl->setCurrentBlock("audio"); - if ($preview_output) - { - $mp_tpl->setVariable("ASTYLE", "margin-top:-30px"); - } - $mp_tpl->setVariable("AFILE", $this->getFile()); - $mp_tpl->setVariable("APLAYER_NR", $this->id."_".$this->current_nr); - $mp_tpl->setVariable("AEVENT_URL", $this->event_callback_url); - $mp_tpl->setVariable("AHEIGHT", "30"); - $mp_tpl->setVariable("AWIDTH", "320"); - $mp_tpl->parseCurrentBlock(); - return $mp_tpl->get(); - } - - // images - if (is_int(strpos($mimeType,"image/"))) - { - $mp_tpl = new ilTemplate("tpl.flv_player.html", true, true, "Services/MediaObjects"); - - if ($this->getDownloadLink() != "") - { - $mp_tpl->setCurrentBlock("idownload"); - $mp_tpl->setVariable("TXT_DOWNLOAD", $lng->txt("download")); - $mp_tpl->setVariable("HREF_DOWNLOAD", $this->getDownloadLink()); - $mp_tpl->parseCurrentBlock(); - } - - $mp_tpl->setCurrentBlock("ipreview"); - if ($this->getVideoPreviewPic() != "") - { - $mp_tpl->setVariable("IMG_SRC", $this->getVideoPreviewPic()); - } - else - { - $mp_tpl->setVariable("IMG_SRC", $this->getFile()); - } - $mp_tpl->setVariable("PTITLE", $this->getTitle()); - $mp_tpl->parseCurrentBlock(); - - $mp_tpl->setCurrentBlock("image"); - $mp_tpl->setVariable("IFILE", $this->getFile()); - $mp_tpl->setVariable("IPLAYER_NR", $this->id."_".$this->current_nr); - $mp_tpl->setVariable("ITITLE", $this->getTitle()); - $mp_tpl->setVariable("IDESCRIPTION", $this->getDescription()); - include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); - $mp_tpl->setVariable("ICLOSE", ilGlyphGUI::get(ilGlyphGUI::CLOSE)); - - if($this->event_callback_url) - { - $mp_tpl->setVariable("IMG_CALLBACK_URL", $this->event_callback_url); - $mp_tpl->setVariable("IMG_CALLBACK_PLAYER_NR", $this->id."_".$this->current_nr); - } - - $mp_tpl->setVariable("IHEIGHT", $this->getDisplayHeight()); - $mp_tpl->setVariable("IWIDTH", $this->getDisplayWidth()); - $mp_tpl->parseCurrentBlock(); - - return $mp_tpl->get(); - } - - // fallback, no preview mode - $mimeType = $this->mimeType == "" ? ilObjMediaObject::getMimeType(basename($this->getFile())) : $this->mimeType; - if (strpos($mimeType,"flv") === false - && strpos($mimeType,"audio/mpeg") === false - && strpos($mimeType,"image/png") === false - && strpos($mimeType,"image/gif") === false) - { - - $html = ''; - return $html; - } - -return; - $tpl->addJavaScript("./Services/MediaObjects/flash_flv_player/swfobject.js"); - $mp_tpl = new ilTemplate("tpl.flv_player.html", true, true, "Services/MediaObjects"); - $mp_tpl->setCurrentBlock("default"); - $mp_tpl->setVariable("FILE", urlencode($this->getFile())); - $mp_tpl->setVariable("PLAYER_NR", $this->current_nr); - $mp_tpl->setVariable("DISPLAY_HEIGHT", strpos($mimeType,"audio/mpeg") === false ? "240" : "20"); - $mp_tpl->setVariable("DISPLAY_WIDTH", "320"); - $mp_tpl->parseCurrentBlock(); - return $mp_tpl->get(); - } - - /** - * Get preview html - * - * @return string html - */ - function getPreviewHtml() - { - return $this->getMp3PlayerHtml(true); - } - - /** - * Get HTML (no preview) for media player integration - * - * @return string html - */ - function getMediaPlayerHtml() - { - return $this->getMp3PlayerHtml(false); - } - + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilLanguage + */ + protected $lng; + + protected $file; + protected $displayHeight = "480"; + protected $displayWidth = "640"; + protected $mimeType; + protected static $nr = 1; + protected static $lightbox_initialized = false; + protected $current_nr; + protected $title; + protected $description; + protected $event_callback_url = ""; + protected $download_link = ""; + + public function __construct($a_id = "", $a_event_callback_url = "") + { + global $DIC; + + $this->tpl = $DIC["tpl"]; + $this->lng = $DIC->language(); + $this->id = $a_id; + $this->event_callback_url = $a_event_callback_url; + $this->current_nr = self::$nr; + self::$nr++; + } + + /** + * Set File. + * + * @param string $a_file File + */ + public function setFile($a_file) + { + $this->file = $a_file; + } + + /** + * Get File. + * + * @return string File + */ + public function getFile() + { + return $this->file; + } + + /** + * Set alternative video file + * + * @param string $a_val alternative video file + */ + public function setAlternativeVideoFile($a_val) + { + $this->alt_video_file = $a_val; + } + + /** + * Get alternative video file + * + * @return string alternative video file + */ + public function getAlternativeVideoFile() + { + return $this->alt_video_file; + } + + /** + * Set alternative video mime type + * + * @param string $a_val alternative video mime type + */ + public function setAlternativeVideoMimeType($a_val) + { + $this->alt_video_mime = $a_val; + } + + /** + * Get alternative video mime type + * + * @return string alternative video mime type + */ + public function getAlternativeVideoMimeType() + { + return $this->alt_video_mime; + } + + /** + * set display height + * + * @param int $dHeight + */ + public function setDisplayHeight($dHeight) + { + $this->displayHeight = $dHeight; + } + + /** + * return display height of player. + * + * @return int + */ + public function getDisplayHeight() + { + return $this->displayHeight; + } + + /** + * Set display width + * + * @param string $a_val display width + */ + public function setDisplayWidth($a_val) + { + $this->displayWidth = $a_val; + } + + /** + * Get display width + * + * @return string display width + */ + public function getDisplayWidth() + { + return $this->displayWidth; + } + + public function setMimeType($value) + { + $this->mimeType = $value; + } + + /** + * Set video preview picture + * + * @param string $a_val video preview picture + */ + public function setVideoPreviewPic($a_val, $a_alt = "") + { + $this->video_preview_pic = $a_val; + $this->video_preview_pic_alt = $a_alt; + } + + /** + * Get video preview picture + * + * @return string video preview picture + */ + public function getVideoPreviewPic() + { + return $this->video_preview_pic; + } + + /** + * Set Title + * + * @param string $a_val title + */ + public function setTitle($a_val) + { + $this->title = $a_val; + } + + /** + * Get Title + * + * @return string title + */ + public function getTitle() + { + return $this->title; + } + + /** + * Set description + * + * @param string $a_val description + */ + public function setDescription($a_val) + { + $this->description = $a_val; + } + + /** + * Get description + * + * @return string description + */ + public function getDescription() + { + return $this->description; + } + + /** + * Set force audio preview + * + * @param boolean $a_val force audio preview picture + */ + public function setForceAudioPreview($a_val) + { + $this->force_audio_preview = $a_val; + } + + /** + * Get force audio preview + * + * @return boolean force audio preview picture + */ + public function getForceAudioPreview() + { + return $this->force_audio_preview; + } + + /** + * Set download link + * + * @param string $a_val download link + */ + public function setDownloadLink($a_val) + { + $this->download_link = $a_val; + } + + /** + * Get download link + * + * @return string download link + */ + public function getDownloadLink() + { + return $this->download_link; + } + + /** + * Init Javascript + * @param null $a_tpl + */ + public static function initJavascript($a_tpl = null) + { + global $DIC; + + $tpl = $DIC["tpl"]; + + if ($a_tpl == null) { + $a_tpl = $tpl; + } + + include_once("./Services/YUI/classes/class.ilYuiUtil.php"); + ilYuiUtil::initConnection(); + + $a_tpl->addJavascript("./Services/MediaObjects/js/MediaObjects.js"); + + include_once("./Services/MediaObjects/classes/class.ilPlayerUtil.php"); + ilPlayerUtil::initMediaElementJs($a_tpl); + } + + + /** + * Get Html for MP3 Player + */ + public function getMp3PlayerHtml($a_preview = false) + { + $tpl = $this->tpl; + $lng = $this->lng; + + self::initJavascript($tpl); + + if (!self::$lightbox_initialized && $a_preview) { + include_once("./Services/UIComponent/Lightbox/classes/class.ilLightboxGUI.php"); + $lb = new ilLightboxGUI("media_lightbox"); + $lb->setWidth("660px"); + $lb->addLightbox(); + self::$lightbox_initialized = true; + } + + require_once 'Services/MediaObjects/classes/class.ilObjMediaObject.php'; + include_once("./Services/MediaObjects/classes/class.ilExternalMediaAnalyzer.php"); + + // youtube + if (ilExternalMediaAnalyzer::isYouTube($this->getFile())) { + $p = ilExternalMediaAnalyzer::extractYouTubeParameters($this->getFile()); + /* + $html = ''. + ''. + ''. + ''. + ''; + return $html;*/ + $mp_tpl = new ilTemplate("tpl.flv_player.html", true, true, "Services/MediaObjects"); + if ($a_preview) { + if ($this->getDownloadLink() != "") { + $mp_tpl->setCurrentBlock("ytdownload"); + $mp_tpl->setVariable("TXT_DOWNLOAD", $lng->txt("download")); + $mp_tpl->setVariable("HREF_DOWNLOAD", $this->getDownloadLink()); + $mp_tpl->parseCurrentBlock(); + } + + $mp_tpl->setCurrentBlock("ytpreview"); + if ($this->getVideoPreviewPic() != "") { + $mp_tpl->setVariable("IMG_SRC", $this->getVideoPreviewPic()); + } else { + $mp_tpl->setVariable("IMG_SRC", ilUtil::getImagePath("mcst_preview.svg")); + } + $height = $this->getDisplayHeight(); + $width = $this->getDisplayWidth(); + $mp_tpl->setVariable("DISPLAY_HEIGHT", $height); + $mp_tpl->setVariable("DISPLAY_WIDTH", $width); + $mp_tpl->setVariable("IMG_ALT", $this->video_preview_pic_alt); + $mp_tpl->setVariable("PTITLE", $this->getTitle()); + $mp_tpl->parseCurrentBlock(); + } + $mp_tpl->setCurrentBlock("youtube"); + if ($a_preview) { + $mp_tpl->setVariable("CLASS", "ilNoDisplay"); + } + $mp_tpl->setVariable("PV", $p["v"]); + $mp_tpl->setVariable("PLAYER_NR", $this->id . "_" . $this->current_nr); + $mp_tpl->setVariable("TITLE", $this->getTitle()); + $mp_tpl->setVariable("DESCRIPTION", $this->getDescription()); + include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); + if ($a_preview) { + $mp_tpl->setVariable("CLOSE", ilGlyphGUI::get(ilGlyphGUI::CLOSE)); + } + $mp_tpl->parseCurrentBlock(); + return $mp_tpl->get(); + } + + // vimeo + if (ilExternalMediaAnalyzer::isVimeo($this->getFile())) { + $p = ilExternalMediaAnalyzer::extractVimeoParameters($this->getFile()); + + $html = ''; + + return $html; + } + + $mimeType = $this->mimeType == "" ? ilObjMediaObject::getMimeType(basename($this->getFile())) : $this->mimeType; + include_once("./Services/MediaObjects/classes/class.ilPlayerUtil.php"); + + // video tag + if (in_array($mimeType, array("video/mp4", "video/m4v", "video/rtmp", + "video/x-flv", "video/webm", "video/youtube", "video/vimeo", "video/ogg"))) { + if ($mimeType == "video/quicktime") { + $mimeType = "video/mov"; + } + + $mp_tpl = new ilTemplate("tpl.flv_player.html", true, true, "Services/MediaObjects"); + + // preview + if ($a_preview) { + if ($this->getDownloadLink() != "") { + $mp_tpl->setCurrentBlock("download"); + $mp_tpl->setVariable("TXT_DOWNLOAD", $lng->txt("download")); + $mp_tpl->setVariable("HREF_DOWNLOAD", $this->getDownloadLink()); + $mp_tpl->parseCurrentBlock(); + } + + $mp_tpl->setCurrentBlock("preview"); + if ($this->getVideoPreviewPic() != "") { + $mp_tpl->setVariable("IMG_SRC", $this->getVideoPreviewPic()); + } else { + $mp_tpl->setVariable("IMG_SRC", ilUtil::getImagePath("mcst_preview.svg")); + } + $mp_tpl->setVariable("IMG_ALT", $this->video_preview_pic_alt); + $mp_tpl->setVariable("PTITLE", $this->getTitle()); + $mp_tpl->parseCurrentBlock(); + } + + // sources + $mp_tpl->setCurrentBlock("source"); + $mp_tpl->setVariable("FILE", $this->getFile()); + $mp_tpl->setVariable("MIME", $mimeType); + $mp_tpl->parseCurrentBlock(); + + if (in_array($this->getAlternativeVideoMimeType(), array("video/mp4", "video/webm"))) { + $mp_tpl->setCurrentBlock("source"); + $mp_tpl->setVariable("FILE", $this->getAlternativeVideoFile()); + $mp_tpl->setVariable("MIME", $this->getAlternativeVideoMimeType()); + $mp_tpl->parseCurrentBlock(); + } + + $mp_tpl->setCurrentBlock("mejs_video"); + + if ($a_preview) { + $mp_tpl->setVariable("CLASS", "ilNoDisplay"); + } + + $mp_tpl->setVariable("PLAYER_NR", $this->id . "_" . $this->current_nr); + $mp_tpl->setVariable("EVENT_URL", $this->event_callback_url); + $height = $this->getDisplayHeight(); + $width = $this->getDisplayWidth(); + if (is_int(strpos($mimeType, "audio/mpeg"))) { + $height = "30"; + } + + $mp_tpl->setVariable("DISPLAY_HEIGHT", $height); + $mp_tpl->setVariable("DISPLAY_WIDTH", $width); + $mp_tpl->setVariable("PREVIEW_PIC", $this->getVideoPreviewPic()); + $mp_tpl->setVariable("SWF_FILE", ilPlayerUtil::getFlashVideoPlayerFilename(true)); + $mp_tpl->setVariable("FFILE", $this->getFile()); + $mp_tpl->setVariable("TITLE", $this->getTitle()); + $mp_tpl->setVariable("DESCRIPTION", $this->getDescription()); + include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); + if ($a_preview) { + $mp_tpl->setVariable("CLOSE", ilGlyphGUI::get(ilGlyphGUI::CLOSE)); + } + $mp_tpl->parseCurrentBlock(); + $r = $mp_tpl->get(); + + if (!$a_preview) { + $tpl->addOnLoadCode("new MediaElementPlayer('#player_" . $this->id . "_" . $this->current_nr . "');"); + } + + //echo htmlentities($r); exit; + return $r; + } + + // audio/mpeg + if (is_int(strpos($mimeType, "audio/mpeg")) || + in_array($mimeType, array("application/ogg", "audio/ogg"))) { + ilPlayerUtil::initMediaElementJs(); + $mp_tpl = new ilTemplate("tpl.flv_player.html", true, true, "Services/MediaObjects"); + $preview_output = false; + if ($this->getVideoPreviewPic() != "" || $this->getForceAudioPreview()) { + if ($this->getDownloadLink() != "") { + $mp_tpl->setCurrentBlock("adownload"); + $mp_tpl->setVariable("TXT_DOWNLOAD", $lng->txt("download")); + $mp_tpl->setVariable("HREF_DOWNLOAD", $this->getDownloadLink()); + $mp_tpl->parseCurrentBlock(); + } + + $mp_tpl->setCurrentBlock("apreview"); + if ($this->getVideoPreviewPic() != "") { + $mp_tpl->setVariable("IMG_SRC", $this->getVideoPreviewPic()); + } else { + $mp_tpl->setVariable("IMG_SRC", ilUtil::getImagePath("mcst_preview.svg")); + } + $mp_tpl->setVariable("PTITLE", $this->getTitle()); + $mp_tpl->parseCurrentBlock(); + $preview_output = true; + } + $mp_tpl->setCurrentBlock("audio"); + if ($preview_output) { + $mp_tpl->setVariable("ASTYLE", "margin-top:-30px"); + } + $mp_tpl->setVariable("AFILE", $this->getFile()); + $mp_tpl->setVariable("APLAYER_NR", $this->id . "_" . $this->current_nr); + $mp_tpl->setVariable("AEVENT_URL", $this->event_callback_url); + $mp_tpl->setVariable("AHEIGHT", "30"); + $mp_tpl->setVariable("AWIDTH", "320"); + $mp_tpl->parseCurrentBlock(); + return $mp_tpl->get(); + } + + // images + if (is_int(strpos($mimeType, "image/"))) { + $mp_tpl = new ilTemplate("tpl.flv_player.html", true, true, "Services/MediaObjects"); + + if ($this->getDownloadLink() != "") { + $mp_tpl->setCurrentBlock("idownload"); + $mp_tpl->setVariable("TXT_DOWNLOAD", $lng->txt("download")); + $mp_tpl->setVariable("HREF_DOWNLOAD", $this->getDownloadLink()); + $mp_tpl->parseCurrentBlock(); + } + + $mp_tpl->setCurrentBlock("ipreview"); + if ($this->getVideoPreviewPic() != "") { + $mp_tpl->setVariable("IMG_SRC", $this->getVideoPreviewPic()); + } else { + $mp_tpl->setVariable("IMG_SRC", $this->getFile()); + } + $mp_tpl->setVariable("PTITLE", $this->getTitle()); + $mp_tpl->parseCurrentBlock(); + + $mp_tpl->setCurrentBlock("image"); + $mp_tpl->setVariable("IFILE", $this->getFile()); + $mp_tpl->setVariable("IPLAYER_NR", $this->id . "_" . $this->current_nr); + $mp_tpl->setVariable("ITITLE", $this->getTitle()); + $mp_tpl->setVariable("IDESCRIPTION", $this->getDescription()); + include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); + $mp_tpl->setVariable("ICLOSE", ilGlyphGUI::get(ilGlyphGUI::CLOSE)); + + if ($this->event_callback_url) { + $mp_tpl->setVariable("IMG_CALLBACK_URL", $this->event_callback_url); + $mp_tpl->setVariable("IMG_CALLBACK_PLAYER_NR", $this->id . "_" . $this->current_nr); + } + + $mp_tpl->setVariable("IHEIGHT", $this->getDisplayHeight()); + $mp_tpl->setVariable("IWIDTH", $this->getDisplayWidth()); + $mp_tpl->parseCurrentBlock(); + + return $mp_tpl->get(); + } + + // fallback, no preview mode + $mimeType = $this->mimeType == "" ? ilObjMediaObject::getMimeType(basename($this->getFile())) : $this->mimeType; + if (strpos($mimeType, "flv") === false + && strpos($mimeType, "audio/mpeg") === false + && strpos($mimeType, "image/png") === false + && strpos($mimeType, "image/gif") === false) { + $html = ''; + return $html; + } + + return; + $tpl->addJavaScript("./Services/MediaObjects/flash_flv_player/swfobject.js"); + $mp_tpl = new ilTemplate("tpl.flv_player.html", true, true, "Services/MediaObjects"); + $mp_tpl->setCurrentBlock("default"); + $mp_tpl->setVariable("FILE", urlencode($this->getFile())); + $mp_tpl->setVariable("PLAYER_NR", $this->current_nr); + $mp_tpl->setVariable("DISPLAY_HEIGHT", strpos($mimeType, "audio/mpeg") === false ? "240" : "20"); + $mp_tpl->setVariable("DISPLAY_WIDTH", "320"); + $mp_tpl->parseCurrentBlock(); + return $mp_tpl->get(); + } + + /** + * Get preview html + * + * @return string html + */ + public function getPreviewHtml() + { + return $this->getMp3PlayerHtml(true); + } + + /** + * Get HTML (no preview) for media player integration + * + * @return string html + */ + public function getMediaPlayerHtml() + { + return $this->getMp3PlayerHtml(false); + } } -?> diff --git a/Services/MediaObjects/classes/class.ilMediaSvgSanitizer.php b/Services/MediaObjects/classes/class.ilMediaSvgSanitizer.php index cba57a29c5e5a45e9942d0ea960dae7f79093681..15f3c792eab883c3683ff306b9eded5521ba2e8f 100644 --- a/Services/MediaObjects/classes/class.ilMediaSvgSanitizer.php +++ b/Services/MediaObjects/classes/class.ilMediaSvgSanitizer.php @@ -14,43 +14,39 @@ use enshrined\svgSanitize\Sanitizer; */ class ilMediaSvgSanitizer { - /** - * Sanitize (temporary solution for sec issue 20339, ILIAS 5.0-5.2, not using composer autoloading yet) - * - * @param string $a_file file to be sanitized - */ - static function sanitizeFile($a_file) - { - /*include_once("./Services/MediaObjects/lib/svg-sanitizer-master/src/data/AttributeInterface.php"); - include_once("./Services/MediaObjects/lib/svg-sanitizer-master/src/data/TagInterface.php"); - include_once("./Services/MediaObjects/lib/svg-sanitizer-master/src/data/AllowedTags.php"); - include_once("./Services/MediaObjects/lib/svg-sanitizer-master/src/data/AllowedAttributes.php"); - include_once("./Services/MediaObjects/lib/svg-sanitizer-master/src/Sanitizer.php");*/ + /** + * Sanitize (temporary solution for sec issue 20339, ILIAS 5.0-5.2, not using composer autoloading yet) + * + * @param string $a_file file to be sanitized + */ + public static function sanitizeFile($a_file) + { + /*include_once("./Services/MediaObjects/lib/svg-sanitizer-master/src/data/AttributeInterface.php"); + include_once("./Services/MediaObjects/lib/svg-sanitizer-master/src/data/TagInterface.php"); + include_once("./Services/MediaObjects/lib/svg-sanitizer-master/src/data/AllowedTags.php"); + include_once("./Services/MediaObjects/lib/svg-sanitizer-master/src/data/AllowedAttributes.php"); + include_once("./Services/MediaObjects/lib/svg-sanitizer-master/src/Sanitizer.php");*/ - $sanitizer = new Sanitizer(); - $dirtySVG = file_get_contents($a_file); - $cleanSVG = $sanitizer->sanitize($dirtySVG); - file_put_contents($a_file, $cleanSVG); - } + $sanitizer = new Sanitizer(); + $dirtySVG = file_get_contents($a_file); + $cleanSVG = $sanitizer->sanitize($dirtySVG); + file_put_contents($a_file, $cleanSVG); + } - /** - * Sanitize directory recursively - * - * @param $a_path - */ - static function sanitizeDir($a_path) - { - $path = realpath($a_path); + /** + * Sanitize directory recursively + * + * @param $a_path + */ + public static function sanitizeDir($a_path) + { + $path = realpath($a_path); - $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST); - foreach($objects as $name => $object) - { - if (strtolower(pathinfo($name, PATHINFO_EXTENSION)) == "svg") - { - self::sanitizeFile($name); - } - } - } + $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST); + foreach ($objects as $name => $object) { + if (strtolower(pathinfo($name, PATHINFO_EXTENSION)) == "svg") { + self::sanitizeFile($name); + } + } + } } - -?> \ No newline at end of file diff --git a/Services/MediaObjects/classes/class.ilMobMultiSrtConfirmationTable2GUI.php b/Services/MediaObjects/classes/class.ilMobMultiSrtConfirmationTable2GUI.php index 96a7155431311b345f255c8e2596773f7d653575..695f618d81354c8f682607bc9139188452187b61 100644 --- a/Services/MediaObjects/classes/class.ilMobMultiSrtConfirmationTable2GUI.php +++ b/Services/MediaObjects/classes/class.ilMobMultiSrtConfirmationTable2GUI.php @@ -14,68 +14,62 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilMobMultiSrtConfirmationTable2GUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - protected $mob; + protected $mob; - /** - * Constructor - */ - public function __construct($a_parent_obj, $a_parent_cmd) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd) + { + global $DIC; - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); - $this->lng = $lng; - $this->ctrl = $ilCtrl; + $this->lng = $lng; + $this->ctrl = $ilCtrl; - $this->multi_srt = $a_parent_obj->multi_srt; - $this->lng->loadLanguageModule("meta"); + $this->multi_srt = $a_parent_obj->multi_srt; + $this->lng->loadLanguageModule("meta"); - $this->setId("mob_msrt_upload"); - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setLimit(9999); - $this->setData($this->multi_srt->getMultiSrtFiles()); - $this->setTitle($this->lng->txt("cont_multi_srt_files")); + $this->setId("mob_msrt_upload"); + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setLimit(9999); + $this->setData($this->multi_srt->getMultiSrtFiles()); + $this->setTitle($this->lng->txt("cont_multi_srt_files")); - $this->addColumn($this->lng->txt("filename")); - $this->addColumn($this->lng->txt("language")); - $this->addColumn($this->lng->txt("mob")); + $this->addColumn($this->lng->txt("filename")); + $this->addColumn($this->lng->txt("language")); + $this->addColumn($this->lng->txt("mob")); - $this->setFormAction($this->ctrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.mob_multi_srt_confirmation_row.html", "Services/MediaObjects"); + $this->setFormAction($this->ctrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.mob_multi_srt_confirmation_row.html", "Services/MediaObjects"); - $this->addCommandButton("saveMultiSrt", $this->lng->txt("save")); - $this->addCommandButton("cancelMultiSrt", $this->lng->txt("cancel")); - } + $this->addCommandButton("saveMultiSrt", $this->lng->txt("save")); + $this->addCommandButton("cancelMultiSrt", $this->lng->txt("cancel")); + } - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - - if ($a_set["lang"] != "") - { - $language = $lng->txt("meta_l_".$a_set["lang"]); - $this->tpl->setVariable("LANGUAGE", $language); - } - if ($a_set["mob"] != "") - { - $this->tpl->setVariable("MEDIA_OBJECT", $a_set["mob_title"]); - } - else - { - $this->tpl->setVariable("MEDIA_OBJECT", "-"); - } - $this->tpl->setVariable("FILENAME", $a_set["filename"]); - } + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + if ($a_set["lang"] != "") { + $language = $lng->txt("meta_l_" . $a_set["lang"]); + $this->tpl->setVariable("LANGUAGE", $language); + } + if ($a_set["mob"] != "") { + $this->tpl->setVariable("MEDIA_OBJECT", $a_set["mob_title"]); + } else { + $this->tpl->setVariable("MEDIA_OBJECT", "-"); + } + $this->tpl->setVariable("FILENAME", $a_set["filename"]); + } } -?> diff --git a/Services/MediaObjects/classes/class.ilMobMultiSrtUpload.php b/Services/MediaObjects/classes/class.ilMobMultiSrtUpload.php index b37aef1f75ab349f8e77ac7b2d90a8e201c6067d..ee826108ceb0f05dd9214046332028603e28d682 100644 --- a/Services/MediaObjects/classes/class.ilMobMultiSrtUpload.php +++ b/Services/MediaObjects/classes/class.ilMobMultiSrtUpload.php @@ -11,150 +11,136 @@ */ class ilMobMultiSrtUpload { - /** - * @var ilLanguage - */ - protected $lng; - - protected $lm; - - /** - * Construcotr - * - * @param ilMobMultiSrtInt $a_multi_srt adapter implementation - */ - function __construct(ilMobMultiSrtInt $a_multi_srt) - { - global $DIC; - - $lng = $DIC->language(); - - $this->lng = $lng; - $this->multi_srt = $a_multi_srt; - } - - /** - * Get directory for multi srt upload - * - * @return string diretory - */ - function getMultiSrtUploadDir() - { - return $this->multi_srt->getUploadDir(); - } - - - /** - * Upload multi srt file - * - * @param array $a_file file info array - * @throws ilLMException - */ - function uploadMultipleSubtitleFile($a_file) - { - include_once("./Services/MediaObjects/exceptions/class.ilMobSrtUploadException.php"); - if (!is_file($a_file["tmp_name"])) - { - throw new ilMobSrtUploadException($this->lng->txt("cont_srt_zip_file_could_not_be_uploaded")); - } - - $dir = $this->getMultiSrtUploadDir(); - ilUtil::delDir($dir, true); - ilUtil::makeDirParents($dir); - ilUtil::moveUploadedFile($a_file["tmp_name"], "multi_srt.zip", $dir."/"."multi_srt.zip"); - ilUtil::unzip($dir."/multi_srt.zip", true); - } - - /** - * Clear multi feedback directory - */ - function clearMultiSrtDirectory() - { - ilUtil::delDir($this->getMultiSrtUploadDir()); - } - - /** - * Get all srt files of srt multi upload - */ - function getMultiSrtFiles() - { - $items = array(); - - include_once("./Services/MetaData/classes/class.ilMDLanguageItem.php"); - $lang_codes = ilMDLanguageItem::_getPossibleLanguageCodes(); - - $dir = $this->getMultiSrtUploadDir(); - $files = ilUtil::getDir($dir); - foreach ($files as $k => $i) - { - // check directory - if ($i["type"] == "file" && !in_array($k, array(".", ".."))) - { - if (pathinfo($k, PATHINFO_EXTENSION) == "srt") - { - $lang = ""; - if (substr($k, strlen($k) - 7, 1) == "_") - { - $lang = substr($k, strlen($k) - 6, 2); - if (!in_array($lang, $lang_codes)) - { - $lang = ""; - } - } - $items[] = array("filename" => $k, "lang" => $lang); - } - } - } - - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - foreach ($this->multi_srt->getMobIds() as $mob) - { - $m = new ilObjMediaObject($mob); - $mi = $m->getMediaItem("Standard"); - if ($mi->getLocationType() == "LocalFile" && is_int(strpos($mi->getFormat(), "video"))) - { - // $loc is e.g. "echo-hereweare.mp4", we not look for - // "echo-hereweare_.srt" files - $loc = pathinfo($mi->getLocation(), PATHINFO_FILENAME); - foreach ($items as $i => $item) - { - if (substr($item["filename"], 0, strlen($loc)) == $loc && - substr($item["filename"], strlen($loc), 1) == "_" && - pathinfo($item["filename"], PATHINFO_EXTENSION) == "srt") - { - $l = substr($item["filename"], strlen($loc)+1, 2); - if (in_array($l, $lang_codes)) - { - $items[$i]["lang"] = $l; - $items[$i]["mob"] = $mob; - $items[$i]["mob_title"] = $m->getTitle(); - } - } - } - } - - } - - return $items; - } - - /** - * Move all srt files that could be mapped to media objects - */ - function moveMultiSrtFiles() - { - $items = $this->getMultiSrtFiles(); - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $cnt = 0; - foreach ($items as $i) - { - if ($i["mob"] > 0 && $i["lang"] != "") - { - $mob = new ilObjMediaObject($i["mob"]); - $mob->uploadSrtFile($this->getMultiSrtUploadDir()."/".$i["filename"], $i["lang"], "rename"); - $cnt++; - } - } - return $cnt; - } -} \ No newline at end of file + /** + * @var ilLanguage + */ + protected $lng; + + protected $lm; + + /** + * Construcotr + * + * @param ilMobMultiSrtInt $a_multi_srt adapter implementation + */ + public function __construct(ilMobMultiSrtInt $a_multi_srt) + { + global $DIC; + + $lng = $DIC->language(); + + $this->lng = $lng; + $this->multi_srt = $a_multi_srt; + } + + /** + * Get directory for multi srt upload + * + * @return string diretory + */ + public function getMultiSrtUploadDir() + { + return $this->multi_srt->getUploadDir(); + } + + + /** + * Upload multi srt file + * + * @param array $a_file file info array + * @throws ilLMException + */ + public function uploadMultipleSubtitleFile($a_file) + { + include_once("./Services/MediaObjects/exceptions/class.ilMobSrtUploadException.php"); + if (!is_file($a_file["tmp_name"])) { + throw new ilMobSrtUploadException($this->lng->txt("cont_srt_zip_file_could_not_be_uploaded")); + } + + $dir = $this->getMultiSrtUploadDir(); + ilUtil::delDir($dir, true); + ilUtil::makeDirParents($dir); + ilUtil::moveUploadedFile($a_file["tmp_name"], "multi_srt.zip", $dir . "/" . "multi_srt.zip"); + ilUtil::unzip($dir . "/multi_srt.zip", true); + } + + /** + * Clear multi feedback directory + */ + public function clearMultiSrtDirectory() + { + ilUtil::delDir($this->getMultiSrtUploadDir()); + } + + /** + * Get all srt files of srt multi upload + */ + public function getMultiSrtFiles() + { + $items = array(); + + include_once("./Services/MetaData/classes/class.ilMDLanguageItem.php"); + $lang_codes = ilMDLanguageItem::_getPossibleLanguageCodes(); + + $dir = $this->getMultiSrtUploadDir(); + $files = ilUtil::getDir($dir); + foreach ($files as $k => $i) { + // check directory + if ($i["type"] == "file" && !in_array($k, array(".", ".."))) { + if (pathinfo($k, PATHINFO_EXTENSION) == "srt") { + $lang = ""; + if (substr($k, strlen($k) - 7, 1) == "_") { + $lang = substr($k, strlen($k) - 6, 2); + if (!in_array($lang, $lang_codes)) { + $lang = ""; + } + } + $items[] = array("filename" => $k, "lang" => $lang); + } + } + } + + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + foreach ($this->multi_srt->getMobIds() as $mob) { + $m = new ilObjMediaObject($mob); + $mi = $m->getMediaItem("Standard"); + if ($mi->getLocationType() == "LocalFile" && is_int(strpos($mi->getFormat(), "video"))) { + // $loc is e.g. "echo-hereweare.mp4", we not look for + // "echo-hereweare_.srt" files + $loc = pathinfo($mi->getLocation(), PATHINFO_FILENAME); + foreach ($items as $i => $item) { + if (substr($item["filename"], 0, strlen($loc)) == $loc && + substr($item["filename"], strlen($loc), 1) == "_" && + pathinfo($item["filename"], PATHINFO_EXTENSION) == "srt") { + $l = substr($item["filename"], strlen($loc)+1, 2); + if (in_array($l, $lang_codes)) { + $items[$i]["lang"] = $l; + $items[$i]["mob"] = $mob; + $items[$i]["mob_title"] = $m->getTitle(); + } + } + } + } + } + + return $items; + } + + /** + * Move all srt files that could be mapped to media objects + */ + public function moveMultiSrtFiles() + { + $items = $this->getMultiSrtFiles(); + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $cnt = 0; + foreach ($items as $i) { + if ($i["mob"] > 0 && $i["lang"] != "") { + $mob = new ilObjMediaObject($i["mob"]); + $mob->uploadSrtFile($this->getMultiSrtUploadDir() . "/" . $i["filename"], $i["lang"], "rename"); + $cnt++; + } + } + return $cnt; + } +} diff --git a/Services/MediaObjects/classes/class.ilMobMultiSrtUploadGUI.php b/Services/MediaObjects/classes/class.ilMobMultiSrtUploadGUI.php index fa12f599c49d55720290681dd1bf66775b2a5bcd..344d67444c9d43924fbed77d07cbe221454a07a1 100644 --- a/Services/MediaObjects/classes/class.ilMobMultiSrtUploadGUI.php +++ b/Services/MediaObjects/classes/class.ilMobMultiSrtUploadGUI.php @@ -11,128 +11,121 @@ */ class ilMobMultiSrtUploadGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilTemplate - */ - protected $tpl; - - public $multi_srt; - - /** - * Constructor - * - * @param ilObjLearningModule $a_lm learning module object - */ - public function __construct(ilMobMultiSrtInt $a_multi_srt) - { - global $DIC; - - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilToolbar = $DIC->toolbar(); - $tpl = $DIC["tpl"]; - - $this->tpl = $tpl; - $this->lng = $lng; - $this->ctrl = $ilCtrl; - include_once("./Services/MediaObjects/classes/class.ilMobMultiSrtUpload.php"); - $this->multi_srt = new ilMobMultiSrtUpload($a_multi_srt); - $this->toolbar = $ilToolbar; - } - - /** - * Execute command - */ - function executeCommand() - { - $cmd = $this->ctrl->getCmd("uploadMultipleSubtitleFileForm"); - - if (in_array($cmd, array("uploadMultipleSubtitleFileForm", "uploadMultipleSubtitleFile", "showMultiSubtitleConfirmationTable", "cancelMultiSrt", "saveMultiSrt"))) - { - $this->$cmd(); - } - } - - /** - * Upload multiple stubtitles - */ - function uploadMultipleSubtitleFileForm() - { - ilUtil::sendInfo($this->lng->txt("cont_upload_multi_srt_howto")); - - // upload file - $this->toolbar->setFormAction($this->ctrl->getFormAction($this), true); - include_once("./Services/Form/classes/class.ilFileInputGUI.php"); - $fi = new ilFileInputGUI($this->lng->txt("cont_subtitle_file")." (.zip)", "subtitle_file"); - $fi->setSuffixes(array("zip")); - $this->toolbar->addInputItem($fi, true); - - $this->toolbar->addFormButton($this->lng->txt("upload"), "uploadMultipleSubtitleFile"); - } - - /** - * Upload multiple subtitles - */ - function uploadMultipleSubtitleFile() - { - try - { - $this->multi_srt->uploadMultipleSubtitleFile(ilUtil::stripSlashesArray($_FILES["subtitle_file"])); - $this->ctrl->redirect($this, "showMultiSubtitleConfirmationTable"); - } - catch (ilLMException $e) - { - ilUtil::sendFailure($e->getMessage(), true); - $this->ctrl->redirect($this, "uploadMultipleSubtitleFileForm"); - } - - } - - /** - * List of srt files in zip file - */ - function showMultiSubtitleConfirmationTable() - { - include_once("./Services/MediaObjects/classes/class.ilMobMultiSrtConfirmationTable2GUI.php"); - $tab = new ilMobMultiSrtConfirmationTable2GUI($this, "showMultiSubtitleConfirmationTable"); - $this->tpl->setContent($tab->getHTML()); - } - - /** - * Cancel Multi Feedback - */ - function cancelMultiSrt() - { - $this->multi_srt->clearMultiSrtDirectory(); - $this->ctrl->redirect($this, "uploadMultipleSubtitleFileForm"); - } - - /** - * Save selected srt files as new srt files - */ - function saveMultiSrt() - { - $cnt = $this->multi_srt->moveMultiSrtFiles(); - $this->multi_srt->clearMultiSrtDirectory(); - - ilUtil::sendSuccess($this->lng->txt("cont_moved_srt_files")." (".$cnt.")", true); - $this->ctrl->redirect($this, "uploadMultipleSubtitleFileForm"); - } + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilTemplate + */ + protected $tpl; + + public $multi_srt; + + /** + * Constructor + * + * @param ilObjLearningModule $a_lm learning module object + */ + public function __construct(ilMobMultiSrtInt $a_multi_srt) + { + global $DIC; + + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilToolbar = $DIC->toolbar(); + $tpl = $DIC["tpl"]; + + $this->tpl = $tpl; + $this->lng = $lng; + $this->ctrl = $ilCtrl; + include_once("./Services/MediaObjects/classes/class.ilMobMultiSrtUpload.php"); + $this->multi_srt = new ilMobMultiSrtUpload($a_multi_srt); + $this->toolbar = $ilToolbar; + } + + /** + * Execute command + */ + public function executeCommand() + { + $cmd = $this->ctrl->getCmd("uploadMultipleSubtitleFileForm"); + + if (in_array($cmd, array("uploadMultipleSubtitleFileForm", "uploadMultipleSubtitleFile", "showMultiSubtitleConfirmationTable", "cancelMultiSrt", "saveMultiSrt"))) { + $this->$cmd(); + } + } + + /** + * Upload multiple stubtitles + */ + public function uploadMultipleSubtitleFileForm() + { + ilUtil::sendInfo($this->lng->txt("cont_upload_multi_srt_howto")); + + // upload file + $this->toolbar->setFormAction($this->ctrl->getFormAction($this), true); + include_once("./Services/Form/classes/class.ilFileInputGUI.php"); + $fi = new ilFileInputGUI($this->lng->txt("cont_subtitle_file") . " (.zip)", "subtitle_file"); + $fi->setSuffixes(array("zip")); + $this->toolbar->addInputItem($fi, true); + + $this->toolbar->addFormButton($this->lng->txt("upload"), "uploadMultipleSubtitleFile"); + } + + /** + * Upload multiple subtitles + */ + public function uploadMultipleSubtitleFile() + { + try { + $this->multi_srt->uploadMultipleSubtitleFile(ilUtil::stripSlashesArray($_FILES["subtitle_file"])); + $this->ctrl->redirect($this, "showMultiSubtitleConfirmationTable"); + } catch (ilLMException $e) { + ilUtil::sendFailure($e->getMessage(), true); + $this->ctrl->redirect($this, "uploadMultipleSubtitleFileForm"); + } + } + + /** + * List of srt files in zip file + */ + public function showMultiSubtitleConfirmationTable() + { + include_once("./Services/MediaObjects/classes/class.ilMobMultiSrtConfirmationTable2GUI.php"); + $tab = new ilMobMultiSrtConfirmationTable2GUI($this, "showMultiSubtitleConfirmationTable"); + $this->tpl->setContent($tab->getHTML()); + } + + /** + * Cancel Multi Feedback + */ + public function cancelMultiSrt() + { + $this->multi_srt->clearMultiSrtDirectory(); + $this->ctrl->redirect($this, "uploadMultipleSubtitleFileForm"); + } + + /** + * Save selected srt files as new srt files + */ + public function saveMultiSrt() + { + $cnt = $this->multi_srt->moveMultiSrtFiles(); + $this->multi_srt->clearMultiSrtDirectory(); + + ilUtil::sendSuccess($this->lng->txt("cont_moved_srt_files") . " (" . $cnt . ")", true); + $this->ctrl->redirect($this, "uploadMultipleSubtitleFileForm"); + } } - -?> \ No newline at end of file diff --git a/Services/MediaObjects/classes/class.ilMobSubtitleTableGUI.php b/Services/MediaObjects/classes/class.ilMobSubtitleTableGUI.php index d71cdccb4d9c0b6dc60119d2daf27e0e9216456f..1db5a79b28b0363f7efeadaba35c9c30caaebd3a 100644 --- a/Services/MediaObjects/classes/class.ilMobSubtitleTableGUI.php +++ b/Services/MediaObjects/classes/class.ilMobSubtitleTableGUI.php @@ -14,58 +14,56 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilMobSubtitleTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_mob) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_mob) + { + 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->mob = $a_mob; - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setData($a_mob->getSrtFiles()); - $this->setTitle($lng->txt("mob_subtitle_files")); - - $this->addColumn("", "", 1); - $this->addColumn($this->lng->txt("mob_file")); - $this->addColumn($this->lng->txt("mob_language")); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.srt_files_row.html", "Services/MediaObjects"); + $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->mob = $a_mob; + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setData($a_mob->getSrtFiles()); + $this->setTitle($lng->txt("mob_subtitle_files")); + + $this->addColumn("", "", 1); + $this->addColumn($this->lng->txt("mob_file")); + $this->addColumn($this->lng->txt("mob_language")); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.srt_files_row.html", "Services/MediaObjects"); - $this->addMultiCommand("confirmSrtDeletion", $lng->txt("delete")); - //$this->addCommandButton("", $lng->txt("")); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - - $this->tpl->setVariable("FILE_NAME", $a_set["full_path"]); - $this->tpl->setVariable("LANGUAGE", $lng->txt("meta_l_".$a_set["language"])); - $this->tpl->setVariable("LANG_KEY", $a_set["language"]); - } + $this->addMultiCommand("confirmSrtDeletion", $lng->txt("delete")); + //$this->addCommandButton("", $lng->txt("")); + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $this->tpl->setVariable("FILE_NAME", $a_set["full_path"]); + $this->tpl->setVariable("LANGUAGE", $lng->txt("meta_l_" . $a_set["language"])); + $this->tpl->setVariable("LANG_KEY", $a_set["language"]); + } } -?> diff --git a/Services/MediaObjects/classes/class.ilMultiSrtConfirmationTable2GUI.php b/Services/MediaObjects/classes/class.ilMultiSrtConfirmationTable2GUI.php index dbdeb213e51ea7ecc44c2afe3dbe7ef631dbcb44..59e4015dd1989739ee6049c322d107b477017424 100644 --- a/Services/MediaObjects/classes/class.ilMultiSrtConfirmationTable2GUI.php +++ b/Services/MediaObjects/classes/class.ilMultiSrtConfirmationTable2GUI.php @@ -14,78 +14,75 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilMultiSrtConfirmationTable2GUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilObjUser - */ - protected $user; - - protected $mob; - - /** - * Constructor - */ - public function __construct($a_parent_obj, $a_parent_cmd) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $this->user = $DIC->user(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilAccess = $DIC->access(); - $lng = $DIC->language(); - $ilUser = $DIC->user(); - - $this->mob = $a_parent_obj->object; - $lng->loadLanguageModule("meta"); - - $this->setId("mob_msrt_upload"); - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setLimit(9999); - $this->setData($this->mob->getMultiSrtFiles()); - $this->setTitle($lng->txt("mob_multi_srt_files")); - $this->setSelectAllCheckbox("file"); - - $this->addColumn("", "", "1px", true); - $this->addColumn($this->lng->txt("filename"), "filename"); - $this->addColumn($this->lng->txt("language"), "language"); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.multi_srt_confirmation_row.html", "Services/MediaObjects"); - - $this->addCommandButton("saveMultiSrt", $lng->txt("save")); - $this->addCommandButton("cancelMultiSrt", $lng->txt("cancel")); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - - if ($a_set["lang"] != "") - { - $this->tpl->setCurrentBlock("cb"); - $language = $lng->txt("meta_l_".$a_set["lang"]); - $this->tpl->setVariable("LANGUAGE", $language); - $this->tpl->setVariable("POST_FILE", ilUtil::prepareFormOutput($a_set["filename"])); - $this->tpl->parseCurrentBlock(); - } - $this->tpl->setVariable("FILENAME", $a_set["filename"]); - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilObjUser + */ + protected $user; + + protected $mob; + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->user = $DIC->user(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilAccess = $DIC->access(); + $lng = $DIC->language(); + $ilUser = $DIC->user(); + + $this->mob = $a_parent_obj->object; + $lng->loadLanguageModule("meta"); + + $this->setId("mob_msrt_upload"); + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setLimit(9999); + $this->setData($this->mob->getMultiSrtFiles()); + $this->setTitle($lng->txt("mob_multi_srt_files")); + $this->setSelectAllCheckbox("file"); + + $this->addColumn("", "", "1px", true); + $this->addColumn($this->lng->txt("filename"), "filename"); + $this->addColumn($this->lng->txt("language"), "language"); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.multi_srt_confirmation_row.html", "Services/MediaObjects"); + + $this->addCommandButton("saveMultiSrt", $lng->txt("save")); + $this->addCommandButton("cancelMultiSrt", $lng->txt("cancel")); + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + + if ($a_set["lang"] != "") { + $this->tpl->setCurrentBlock("cb"); + $language = $lng->txt("meta_l_" . $a_set["lang"]); + $this->tpl->setVariable("LANGUAGE", $language); + $this->tpl->setVariable("POST_FILE", ilUtil::prepareFormOutput($a_set["filename"])); + $this->tpl->parseCurrentBlock(); + } + $this->tpl->setVariable("FILENAME", $a_set["filename"]); + } } -?> diff --git a/Services/MediaObjects/classes/class.ilObjMediaObject.php b/Services/MediaObjects/classes/class.ilObjMediaObject.php index 3cb332baebc0b85d670efacdb5882575123e98ee..cc7ed0680357857d9e3f7cfa42f57dbecdf23c0e 100755 --- a/Services/MediaObjects/classes/class.ilObjMediaObject.php +++ b/Services/MediaObjects/classes/class.ilObjMediaObject.php @@ -1,9 +1,9 @@ user = $DIC->user(); - $this->app_event_handler = $DIC["ilAppEventHandler"]; - $this->lng = $DIC->language(); - $this->is_alias = false; - $this->media_items = array(); - $this->contains_int_link = false; - $this->type = "mob"; - parent::__construct($a_id, false); - } - - function setRefId($a_id) - { - $this->ilias->raiseError("Operation ilObjMedia::setRefId() not allowed.",$this->ilias->error_obj->FATAL); - } - - function getRefId() - { - return false; - } - - function putInTree($a_parent_ref) - { - $this->ilias->raiseError("Operation ilObjMedia::putInTree() not allowed.",$this->ilias->error_obj->FATAL); - } - - function createReference() - { - $this->ilias->raiseError("Operation ilObjMedia::createReference() not allowed.",$this->ilias->error_obj->FATAL); - } - - function setTitle($a_title) - { - parent::setTitle($a_title); - } - - function getTitle() - { - return parent::getTitle(); - } - - /** - * checks wether a lm content object with specified id exists or not - * - * @param int $id id - * - * @return boolean true, if lm content object exists - */ - public static function _exists($a_id, $a_reference = false, $a_type = NULL) - { - global $DIC; - - $ilDB = $DIC->database(); - - include_once("./Services/Link/classes/class.ilInternalLink.php"); - if (is_int(strpos($a_id, "_"))) - { - $a_id = ilInternalLink::_extractObjIdOfTarget($a_id); - } - - if (parent::_exists($a_id, false) && ilObject::_lookupType($a_id) == "mob") - { - return true; - } - return false; - } - - /** - * delete media object - */ - function delete() - { - $mob_logger = ilLoggerFactory::getLogger('mob'); - $mob_logger->debug("ilObjMediaObject: Delete called for media object ID '".$this->getId()."'."); - - if (!($this->getId() > 0)) - { - return; - } - - $usages = $this->getUsages(); - - $mob_logger->debug("ilObjMediaObject: ... Found ".count($usages)." usages."); - - if (count($usages) == 0) - { - // remove directory - ilUtil::delDir(ilObjMediaObject::_getDirectory($this->getId())); - - // remove thumbnail directory - ilUtil::delDir(ilObjMediaObject::_getThumbnailDirectory($this->getId())); - - // delete meta data of mob - $this->deleteMetaData(); - - // delete media items - ilMediaItem::deleteAllItemsOfMob($this->getId()); - - // this is just to make sure, there should be no entries left at - // this point as they depend on the usage - self::handleQuotaUpdate($this); - - // delete object - parent::delete(); - - $mob_logger->debug("ilObjMediaObject: ... deleted."); - } - else - { - foreach ($usages as $u) - { - $mob_logger->debug("ilObjMediaObject: ... usage type:".$u["type"]. - ", id:".$u["id"]. - ", lang:".$u["lang"]. - ", hist_nr:".$u["hist_nr"]."."); - } - $mob_logger->debug("ilObjMediaObject: ... not deleted."); - } - } - - /** - * get description of media object - * - * @return string description - */ - function getDescription() - { - return parent::getDescription(); - } - - /** - * set description of media object - */ - function setDescription($a_description) - { - parent::setDescription($a_description); - } - - /** - * Meta data update listener - * - * Important note: Do never call create() or update() - * method of ilObject here. It would result in an - * endless loop: update object -> update meta -> update - * object -> ... - * Use static _writeTitle() ... methods instead. - * - * @param string $a_element - */ - function MDUpdateListener($a_element) - { - include_once 'Services/MetaData/classes/class.ilMD.php'; - - switch($a_element) - { - case 'General': - - // Update Title and description - $md = new ilMD(0, $this->getId(), $this->getType()); - $md_gen = $md->getGeneral(); - - if (is_object($md_gen)) - { - ilObject::_writeTitle($this->getId(),$md_gen->getTitle()); - $this->setTitle($md_gen->getTitle()); - - foreach($md_gen->getDescriptionIds() as $id) - { - $md_des = $md_gen->getDescription($id); - ilObject::_writeDescription($this->getId(),$md_des->getDescription()); - $this->setDescription($md_des->getDescription()); - break; - } - } - - break; - - default: - } - return true; - } - - /** - * create meta data entry - */ - function createMetaData() - { - include_once 'Services/MetaData/classes/class.ilMDCreator.php'; - - $ilUser = $this->user; - - $md_creator = new ilMDCreator(0, $this->getId(), $this->getType()); - $md_creator->setTitle($this->getTitle()); - $md_creator->setTitleLanguage($ilUser->getPref('language')); - $md_creator->setDescription($this->getDescription()); - $md_creator->setDescriptionLanguage($ilUser->getPref('language')); - $md_creator->setKeywordLanguage($ilUser->getPref('language')); - $md_creator->setLanguage($ilUser->getPref('language')); - $md_creator->create(); - - return true; - } - - /** - * update meta data entry - */ - function updateMetaData() - { - include_once("Services/MetaData/classes/class.ilMD.php"); - include_once("Services/MetaData/classes/class.ilMDGeneral.php"); - include_once("Services/MetaData/classes/class.ilMDDescription.php"); - - $md = new ilMD(0, $this->getId(), $this->getType()); - $md_gen = $md->getGeneral(); - $md_gen->setTitle($this->getTitle()); - - // sets first description (maybe not appropriate) - $md_des_ids = $md_gen->getDescriptionIds(); - if (count($md_des_ids) > 0) - { - $md_des = $md_gen->getDescription($md_des_ids[0]); - $md_des->setDescription($this->getDescription()); - $md_des->update(); - } - $md_gen->update(); - - } - - /** - * delete meta data entry - */ - function deleteMetaData() - { - // Delete meta data - include_once('Services/MetaData/classes/class.ilMD.php'); - $md = new ilMD(0, $this->getId(), $this->getType()); - $md->deleteAll(); - } - - - /** - * add media item to media object - * - * @param object $a_item media item object - */ - function addMediaItem($a_item) - { - $this->media_items[] = $a_item; - } - - - /** - * get all media items - * - * @return array array of media item objects - */ - function &getMediaItems() - { - return $this->media_items; - } - - /** - * get item for media purpose - * - * @param string $a_purpose - * @return ilMediaItem - */ - function &getMediaItem($a_purpose) - { - foreach ($this->media_items as $media_item) - { - if($media_item->getPurpose() == $a_purpose) - { - return $media_item; - } - } - return false; - } - - - /** - * - */ - function removeMediaItem($a_purpose) - { - foreach ($this->media_items as $key => $media_item) - { - if($media_item->getPurpose() == $a_purpose) - { - unset($this->media_items[$key]); - } - } - // update numbers and keys - $i = 1; - $media_items = array(); - foreach ($this->media_items as $media_item) - { - $media_items [$i] = $media_item; - $media_item->setMobId($this->getId()); - $media_item->setNr($i); - $i++; - } - $this->media_items = $media_items; - } - - /** - * remove all media items - */ - function removeAllMediaItems() - { - $this->media_items = array(); - } - - - function getMediaItemNr($a_purpose) - { - for($i=0; $imedia_items); $i++) - { - if($this->media_items[$i]->getPurpose() == $a_purpose) - { - return $i + 1; - } - } - return false; - } - - - function hasFullscreenItem() - { - return $this->hasPurposeItem("Fullscreen"); - } - - /** - * returns wether object has media item with specific purpose - * - * @param string $purpose - * @return boolean - */ - function hasPurposeItem($purpose) - { - if(is_object($this->getMediaItem($purpose))) - { - return true; - } - else - { - return false; - } - } - - - - /** - * read media object data from db - */ - function read() - { -//echo "
                  ilObjMediaObject:read"; - parent::read(); - - // get media items - ilMediaItem::_getMediaItemsOfMOb($this); - } - - /** - * set id - */ - function setId($a_id) - { - $this->id = $a_id; - } - - function getId() - { - return $this->id; - } - - /** - * set wether page object is an alias - */ - function setAlias($a_is_alias) - { - $this->is_alias = $a_is_alias; - } - - function isAlias() - { - return $this->is_alias; - } - - function setOriginID($a_id) - { - return $this->origin_id = $a_id; - } - - function getOriginID() - { - return $this->origin_id; - } - - /* - function getimportId() - { - return $this->meta_data->getImportIdentifierEntryID(); - }*/ - - - /** - * get import id - */ - function getImportId() - { - return $this->import_id; - } - - function setImportId($a_id) - { - $this->import_id = $a_id; - } - - /** - * create media object in db - */ - function create($a_create_meta_data = false, $a_save_media_items = true) - { - parent::create(); - - if (!$a_create_meta_data) - { - $this->createMetaData(); - } - - if ($a_save_media_items) - { - $media_items = $this->getMediaItems(); - for($i=0; $isetMobId($this->getId()); - $item->setNr($i+1); - $item->create(); - } - } - - self::handleQuotaUpdate($this); - - $ilAppEventHandler = $this->app_event_handler; - $ilAppEventHandler->raise('Services/MediaObjects', - 'create', - array('object' => $this, - 'obj_type' => 'mob', - 'obj_id' => $this->getId()) - ); - } - - - /** - * update media object in db - */ - function update($a_upload=false) - { - parent::update(); - - if(!$a_upload) - { - $this->updateMetaData(); - } - - ilMediaItem::deleteAllItemsOfMob($this->getId()); - - // iterate all items - $media_items = $this->getMediaItems(); - $j = 1; - foreach($media_items as $key => $val) - { - $item = $media_items[$key]; - if (is_object($item)) - { - $item->setMobId($this->getId()); - $item->setNr($j); - if ($item->getLocationType() == "Reference") - { - $item->extractUrlParameters(); - } - $item->create(); - $j++; - } - } - - self::handleQuotaUpdate($this); - $ilAppEventHandler = $this->app_event_handler; - $ilAppEventHandler->raise('Services/MediaObjects', - 'update', - array('object' => $this, - 'obj_type' => 'mob', - 'obj_id' => $this->getId()) - ); - } - - protected static function handleQuotaUpdate(ilObjMediaObject $a_mob) - { - global $DIC; - - $ilSetting = $DIC->settings(); - - // if neither workspace nor portfolios are activated, we skip - // the quota update here. this due to performance reasons on installations - // that do not use workspace/portfolios, but heavily copy content. - // in extreme cases (media object in pool and personal blog, deactivate workspace, change media object, - // this may lead to incorrect data in the quota calculation) - if ($ilSetting->get("disable_personal_workspace") && !$ilSetting->get('user_portfolios')) - { - return; - } - - $parent_obj_ids = array(); - foreach($a_mob->getUsages() as $item) - { - $parent_obj_id = $a_mob->getParentObjectIdForUsage($item); - if($parent_obj_id && - !in_array($parent_obj_id, $parent_obj_ids)) - { - $parent_obj_ids[]= $parent_obj_id; - } - } - - // we could suppress this if object is present in a (repository) media pool - // but this would lead to "quota-breaches" when the pool item is deleted - // and "suddenly" all workspace owners get filesize added to their - // respective quotas, regardless of current status - - include_once "Services/DiskQuota/classes/class.ilDiskQuotaHandler.php"; - ilDiskQuotaHandler::handleUpdatedSourceObject($a_mob->getType(), - $a_mob->getId(), - ilUtil::dirSize($a_mob->getDataDirectory()), - $parent_obj_ids); - } - - /** - * Get absolute directory - * - * @param int $a_mob_id - * @return string - */ - static public function _getDirectory($a_mob_id) - { - return ilUtil::getWebspaceDir()."/".self::_getRelativeDirectory($a_mob_id); - } - - /** - * Get relative (to webspace dir) directory - * - * @param int $a_mob_id - * @return string - */ - static public function _getRelativeDirectory($a_mob_id) - { - return "mobs/mm_".$a_mob_id; - } - - - /** - * get directory for files of media object (static) - * @param int $a_mob_id media object id - * @return string - */ - public static function _getURL($a_mob_id) - { - return ilUtil::getHtmlPath(ilUtil::getWebspaceDir()."/mobs/mm_".$a_mob_id); - } - - /** - * get directory for files of media object (static) - * - * @param int $a_mob_id media object id - */ - static function _getThumbnailDirectory($a_mob_id, $a_mode = "filesystem") - { - return ilUtil::getWebspaceDir($a_mode)."/thumbs/mm_".$a_mob_id; - } - - /** - * Get path for standard item. - * - * @param int $a_mob_id media object id - */ - static function _lookupStandardItemPath($a_mob_id, $a_url_encode = false, - $a_web = true) - { - return ilObjMediaObject::_lookupItemPath($a_mob_id, $a_url_encode, $a_web, "Standard"); - } - - /** - * Get path for item with specific purpose. - * - * @param int $a_mob_id media object id - */ - static function _lookupItemPath($a_mob_id, $a_url_encode = false, - $a_web = true, $a_purpose = "") - { - if ($a_purpose == "") - { - $a_purpose = "Standard"; - } - $location = ilMediaItem::_lookupLocationForMobId($a_mob_id, $a_purpose); - if (preg_match("/https?\:/i",$location)) - return $location; - - if ($a_url_encode) - $location = rawurlencode($location); - - $path = ($a_web) - ? ILIAS_HTTP_PATH - : "."; - - return $path."/data/".CLIENT_ID."/mobs/mm_".$a_mob_id."/".$location; - } - - /** - * Create file directory of media object - */ - function createDirectory() - { - $path = ilObjMediaObject::_getDirectory($this->getId()); - ilUtil::createDirectory($path); - if (!is_dir($path)) { - $this->ilias->raiseError("Failed to create directory $path.", $this->ilias->error_obj->FATAL); - } - } - - /** - * Create thumbnail directory - */ - static function _createThumbnailDirectory($a_obj_id) - { - ilUtil::createDirectory(ilUtil::getWebspaceDir()."/thumbs"); - ilUtil::createDirectory(ilUtil::getWebspaceDir()."/thumbs/mm_".$a_obj_id); - } - - /** - * Get files of directory - * - * @param string $a_subdir subdirectry - * @return array array of files - */ - function getFilesOfDirectory($a_subdir = "") - { - $a_subdir = str_replace("..", "", $a_subdir); - $dir = ilObjMediaObject::_getDirectory($this->getId()); - if ($a_subdir != "") - { - $dir.= "/".$a_subdir; - } - - $files = array(); - if (is_dir($dir)) - { - $entries = ilUtil::getDir($dir); - foreach ($entries as $e) - { - if (is_file($dir."/".$e["entry"]) && $e["entry"] != "." && $e["entry"] != "..") - { - $files[] = $e["entry"]; - } - } - } + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilAppEventHandler + */ + protected $app_event_handler; + + public $is_alias; + public $origin_id; + public $id; + public $media_items; + public $contains_int_link; + + /** + * Constructor + * @access public + */ + public function __construct($a_id = 0) + { + global $DIC; + + $this->user = $DIC->user(); + $this->app_event_handler = $DIC["ilAppEventHandler"]; + $this->lng = $DIC->language(); + $this->is_alias = false; + $this->media_items = array(); + $this->contains_int_link = false; + $this->type = "mob"; + parent::__construct($a_id, false); + } + + public function setRefId($a_id) + { + $this->ilias->raiseError("Operation ilObjMedia::setRefId() not allowed.", $this->ilias->error_obj->FATAL); + } + + public function getRefId() + { + return false; + } + + public function putInTree($a_parent_ref) + { + $this->ilias->raiseError("Operation ilObjMedia::putInTree() not allowed.", $this->ilias->error_obj->FATAL); + } + + public function createReference() + { + $this->ilias->raiseError("Operation ilObjMedia::createReference() not allowed.", $this->ilias->error_obj->FATAL); + } + + public function setTitle($a_title) + { + parent::setTitle($a_title); + } + + public function getTitle() + { + return parent::getTitle(); + } + + /** + * checks wether a lm content object with specified id exists or not + * + * @param int $id id + * + * @return boolean true, if lm content object exists + */ + public static function _exists($a_id, $a_reference = false, $a_type = null) + { + global $DIC; + + $ilDB = $DIC->database(); + + include_once("./Services/Link/classes/class.ilInternalLink.php"); + if (is_int(strpos($a_id, "_"))) { + $a_id = ilInternalLink::_extractObjIdOfTarget($a_id); + } + + if (parent::_exists($a_id, false) && ilObject::_lookupType($a_id) == "mob") { + return true; + } + return false; + } + + /** + * delete media object + */ + public function delete() + { + $mob_logger = ilLoggerFactory::getLogger('mob'); + $mob_logger->debug("ilObjMediaObject: Delete called for media object ID '" . $this->getId() . "'."); + + if (!($this->getId() > 0)) { + return; + } + + $usages = $this->getUsages(); + + $mob_logger->debug("ilObjMediaObject: ... Found " . count($usages) . " usages."); + + if (count($usages) == 0) { + // remove directory + ilUtil::delDir(ilObjMediaObject::_getDirectory($this->getId())); + + // remove thumbnail directory + ilUtil::delDir(ilObjMediaObject::_getThumbnailDirectory($this->getId())); + + // delete meta data of mob + $this->deleteMetaData(); + + // delete media items + ilMediaItem::deleteAllItemsOfMob($this->getId()); + + // this is just to make sure, there should be no entries left at + // this point as they depend on the usage + self::handleQuotaUpdate($this); + + // delete object + parent::delete(); + + $mob_logger->debug("ilObjMediaObject: ... deleted."); + } else { + foreach ($usages as $u) { + $mob_logger->debug("ilObjMediaObject: ... usage type:" . $u["type"] . + ", id:" . $u["id"] . + ", lang:" . $u["lang"] . + ", hist_nr:" . $u["hist_nr"] . "."); + } + $mob_logger->debug("ilObjMediaObject: ... not deleted."); + } + } + + /** + * get description of media object + * + * @return string description + */ + public function getDescription() + { + return parent::getDescription(); + } + + /** + * set description of media object + */ + public function setDescription($a_description) + { + parent::setDescription($a_description); + } + + /** + * Meta data update listener + * + * Important note: Do never call create() or update() + * method of ilObject here. It would result in an + * endless loop: update object -> update meta -> update + * object -> ... + * Use static _writeTitle() ... methods instead. + * + * @param string $a_element + */ + public function MDUpdateListener($a_element) + { + include_once 'Services/MetaData/classes/class.ilMD.php'; + + switch ($a_element) { + case 'General': + + // Update Title and description + $md = new ilMD(0, $this->getId(), $this->getType()); + $md_gen = $md->getGeneral(); + + if (is_object($md_gen)) { + ilObject::_writeTitle($this->getId(), $md_gen->getTitle()); + $this->setTitle($md_gen->getTitle()); + + foreach ($md_gen->getDescriptionIds() as $id) { + $md_des = $md_gen->getDescription($id); + ilObject::_writeDescription($this->getId(), $md_des->getDescription()); + $this->setDescription($md_des->getDescription()); + break; + } + } + + break; + + default: + } + return true; + } + + /** + * create meta data entry + */ + public function createMetaData() + { + include_once 'Services/MetaData/classes/class.ilMDCreator.php'; + + $ilUser = $this->user; + + $md_creator = new ilMDCreator(0, $this->getId(), $this->getType()); + $md_creator->setTitle($this->getTitle()); + $md_creator->setTitleLanguage($ilUser->getPref('language')); + $md_creator->setDescription($this->getDescription()); + $md_creator->setDescriptionLanguage($ilUser->getPref('language')); + $md_creator->setKeywordLanguage($ilUser->getPref('language')); + $md_creator->setLanguage($ilUser->getPref('language')); + $md_creator->create(); + + return true; + } + + /** + * update meta data entry + */ + public function updateMetaData() + { + include_once("Services/MetaData/classes/class.ilMD.php"); + include_once("Services/MetaData/classes/class.ilMDGeneral.php"); + include_once("Services/MetaData/classes/class.ilMDDescription.php"); + + $md = new ilMD(0, $this->getId(), $this->getType()); + $md_gen = $md->getGeneral(); + $md_gen->setTitle($this->getTitle()); + + // sets first description (maybe not appropriate) + $md_des_ids = $md_gen->getDescriptionIds(); + if (count($md_des_ids) > 0) { + $md_des = $md_gen->getDescription($md_des_ids[0]); + $md_des->setDescription($this->getDescription()); + $md_des->update(); + } + $md_gen->update(); + } + + /** + * delete meta data entry + */ + public function deleteMetaData() + { + // Delete meta data + include_once('Services/MetaData/classes/class.ilMD.php'); + $md = new ilMD(0, $this->getId(), $this->getType()); + $md->deleteAll(); + } + + + /** + * add media item to media object + * + * @param object $a_item media item object + */ + public function addMediaItem($a_item) + { + $this->media_items[] = $a_item; + } + + + /** + * get all media items + * + * @return array array of media item objects + */ + public function &getMediaItems() + { + return $this->media_items; + } + + /** + * get item for media purpose + * + * @param string $a_purpose + * @return ilMediaItem + */ + public function &getMediaItem($a_purpose) + { + foreach ($this->media_items as $media_item) { + if ($media_item->getPurpose() == $a_purpose) { + return $media_item; + } + } + return false; + } + + + /** + * + */ + public function removeMediaItem($a_purpose) + { + foreach ($this->media_items as $key => $media_item) { + if ($media_item->getPurpose() == $a_purpose) { + unset($this->media_items[$key]); + } + } + // update numbers and keys + $i = 1; + $media_items = array(); + foreach ($this->media_items as $media_item) { + $media_items [$i] = $media_item; + $media_item->setMobId($this->getId()); + $media_item->setNr($i); + $i++; + } + $this->media_items = $media_items; + } + + /** + * remove all media items + */ + public function removeAllMediaItems() + { + $this->media_items = array(); + } + + + public function getMediaItemNr($a_purpose) + { + for ($i=0; $imedia_items); $i++) { + if ($this->media_items[$i]->getPurpose() == $a_purpose) { + return $i + 1; + } + } + return false; + } + + + public function hasFullscreenItem() + { + return $this->hasPurposeItem("Fullscreen"); + } + + /** + * returns wether object has media item with specific purpose + * + * @param string $purpose + * @return boolean + */ + public function hasPurposeItem($purpose) + { + if (is_object($this->getMediaItem($purpose))) { + return true; + } else { + return false; + } + } + + + + /** + * read media object data from db + */ + public function read() + { + //echo "
                  ilObjMediaObject:read"; + parent::read(); + + // get media items + ilMediaItem::_getMediaItemsOfMOb($this); + } + + /** + * set id + */ + public function setId($a_id) + { + $this->id = $a_id; + } + + public function getId() + { + return $this->id; + } + + /** + * set wether page object is an alias + */ + public function setAlias($a_is_alias) + { + $this->is_alias = $a_is_alias; + } + + public function isAlias() + { + return $this->is_alias; + } + + public function setOriginID($a_id) + { + return $this->origin_id = $a_id; + } + + public function getOriginID() + { + return $this->origin_id; + } + + /* + function getimportId() + { + return $this->meta_data->getImportIdentifierEntryID(); + }*/ + + + /** + * get import id + */ + public function getImportId() + { + return $this->import_id; + } + + public function setImportId($a_id) + { + $this->import_id = $a_id; + } + + /** + * create media object in db + */ + public function create($a_create_meta_data = false, $a_save_media_items = true) + { + parent::create(); + + if (!$a_create_meta_data) { + $this->createMetaData(); + } + + if ($a_save_media_items) { + $media_items = $this->getMediaItems(); + for ($i=0; $isetMobId($this->getId()); + $item->setNr($i+1); + $item->create(); + } + } + + self::handleQuotaUpdate($this); + + $ilAppEventHandler = $this->app_event_handler; + $ilAppEventHandler->raise( + 'Services/MediaObjects', + 'create', + array('object' => $this, + 'obj_type' => 'mob', + 'obj_id' => $this->getId()) + ); + } + + + /** + * update media object in db + */ + public function update($a_upload=false) + { + parent::update(); + + if (!$a_upload) { + $this->updateMetaData(); + } + + ilMediaItem::deleteAllItemsOfMob($this->getId()); + + // iterate all items + $media_items = $this->getMediaItems(); + $j = 1; + foreach ($media_items as $key => $val) { + $item = $media_items[$key]; + if (is_object($item)) { + $item->setMobId($this->getId()); + $item->setNr($j); + if ($item->getLocationType() == "Reference") { + $item->extractUrlParameters(); + } + $item->create(); + $j++; + } + } + + self::handleQuotaUpdate($this); + $ilAppEventHandler = $this->app_event_handler; + $ilAppEventHandler->raise( + 'Services/MediaObjects', + 'update', + array('object' => $this, + 'obj_type' => 'mob', + 'obj_id' => $this->getId()) + ); + } + + protected static function handleQuotaUpdate(ilObjMediaObject $a_mob) + { + global $DIC; + + $ilSetting = $DIC->settings(); + + // if neither workspace nor portfolios are activated, we skip + // the quota update here. this due to performance reasons on installations + // that do not use workspace/portfolios, but heavily copy content. + // in extreme cases (media object in pool and personal blog, deactivate workspace, change media object, + // this may lead to incorrect data in the quota calculation) + if ($ilSetting->get("disable_personal_workspace") && !$ilSetting->get('user_portfolios')) { + return; + } + + $parent_obj_ids = array(); + foreach ($a_mob->getUsages() as $item) { + $parent_obj_id = $a_mob->getParentObjectIdForUsage($item); + if ($parent_obj_id && + !in_array($parent_obj_id, $parent_obj_ids)) { + $parent_obj_ids[]= $parent_obj_id; + } + } + + // we could suppress this if object is present in a (repository) media pool + // but this would lead to "quota-breaches" when the pool item is deleted + // and "suddenly" all workspace owners get filesize added to their + // respective quotas, regardless of current status + + include_once "Services/DiskQuota/classes/class.ilDiskQuotaHandler.php"; + ilDiskQuotaHandler::handleUpdatedSourceObject( + $a_mob->getType(), + $a_mob->getId(), + ilUtil::dirSize($a_mob->getDataDirectory()), + $parent_obj_ids + ); + } + + /** + * Get absolute directory + * + * @param int $a_mob_id + * @return string + */ + public static function _getDirectory($a_mob_id) + { + return ilUtil::getWebspaceDir() . "/" . self::_getRelativeDirectory($a_mob_id); + } + + /** + * Get relative (to webspace dir) directory + * + * @param int $a_mob_id + * @return string + */ + public static function _getRelativeDirectory($a_mob_id) + { + return "mobs/mm_" . $a_mob_id; + } + + + /** + * get directory for files of media object (static) + * @param int $a_mob_id media object id + * @return string + */ + public static function _getURL($a_mob_id) + { + return ilUtil::getHtmlPath(ilUtil::getWebspaceDir() . "/mobs/mm_" . $a_mob_id); + } + + /** + * get directory for files of media object (static) + * + * @param int $a_mob_id media object id + */ + public static function _getThumbnailDirectory($a_mob_id, $a_mode = "filesystem") + { + return ilUtil::getWebspaceDir($a_mode) . "/thumbs/mm_" . $a_mob_id; + } + + /** + * Get path for standard item. + * + * @param int $a_mob_id media object id + */ + public static function _lookupStandardItemPath( + $a_mob_id, + $a_url_encode = false, + $a_web = true + ) { + return ilObjMediaObject::_lookupItemPath($a_mob_id, $a_url_encode, $a_web, "Standard"); + } + + /** + * Get path for item with specific purpose. + * + * @param int $a_mob_id media object id + */ + public static function _lookupItemPath( + $a_mob_id, + $a_url_encode = false, + $a_web = true, + $a_purpose = "" + ) { + if ($a_purpose == "") { + $a_purpose = "Standard"; + } + $location = ilMediaItem::_lookupLocationForMobId($a_mob_id, $a_purpose); + if (preg_match("/https?\:/i", $location)) { + return $location; + } + + if ($a_url_encode) { + $location = rawurlencode($location); + } + + $path = ($a_web) + ? ILIAS_HTTP_PATH + : "."; + + return $path . "/data/" . CLIENT_ID . "/mobs/mm_" . $a_mob_id . "/" . $location; + } + + /** + * Create file directory of media object + */ + public function createDirectory() + { + $path = ilObjMediaObject::_getDirectory($this->getId()); + ilUtil::createDirectory($path); + if (!is_dir($path)) { + $this->ilias->raiseError("Failed to create directory $path.", $this->ilias->error_obj->FATAL); + } + } + + /** + * Create thumbnail directory + */ + public static function _createThumbnailDirectory($a_obj_id) + { + ilUtil::createDirectory(ilUtil::getWebspaceDir() . "/thumbs"); + ilUtil::createDirectory(ilUtil::getWebspaceDir() . "/thumbs/mm_" . $a_obj_id); + } + + /** + * Get files of directory + * + * @param string $a_subdir subdirectry + * @return array array of files + */ + public function getFilesOfDirectory($a_subdir = "") + { + $a_subdir = str_replace("..", "", $a_subdir); + $dir = ilObjMediaObject::_getDirectory($this->getId()); + if ($a_subdir != "") { + $dir.= "/" . $a_subdir; + } + + $files = array(); + if (is_dir($dir)) { + $entries = ilUtil::getDir($dir); + foreach ($entries as $e) { + if (is_file($dir . "/" . $e["entry"]) && $e["entry"] != "." && $e["entry"] != "..") { + $files[] = $e["entry"]; + } + } + } - return $files; - } - - - /** - * get MediaObject XLM Tag - * @param int $a_mode IL_MODE_ALIAS | IL_MODE_OUTPUT | IL_MODE_FULL - */ - function getXML($a_mode = IL_MODE_FULL, $a_inst = 0, $a_sign_locals = false) - { - $ilUser = $this->user; - - // TODO: full implementation of all parameters -//echo "-".$a_mode."-"; - switch ($a_mode) - { - case IL_MODE_ALIAS: - $xml = ""; - $xml .= "getId()."\"/>"; - $media_items = $this->getMediaItems(); - for($i=0; $igetPurpose()."\">"; - - // Layout - $width = ($item->getWidth() != "") - ? "Width=\"".$item->getWidth()."\"" - : ""; - $height = ($item->getHeight() != "") - ? "Height=\"".$item->getHeight()."\"" - : ""; - $halign = ($item->getHAlign() != "") - ? "HorizontalAlign=\"".$item->getHAlign()."\"" - : ""; - $xml .= ""; - - // Caption - if ($item->getCaption() != "") - { - $xml .= "". - $this->escapeProperty($item->getCaption()).""; - } - - // Text Representation - if ($item->getTextRepresentation() != "") - { - $xml .= "". - $this->escapeProperty($item->getTextRepresentation()).""; - } - - // Parameter - $parameters = $item->getParameters(); - foreach ($parameters as $name => $value) - { - $xml .= ""; - } - $xml .= $item->getMapAreasXML(); - $xml .= ""; - } - break; - - // for output we need technical sections of meta data - case IL_MODE_OUTPUT: - - // get first technical section + return $files; + } + + + /** + * get MediaObject XLM Tag + * @param int $a_mode IL_MODE_ALIAS | IL_MODE_OUTPUT | IL_MODE_FULL + */ + public function getXML($a_mode = IL_MODE_FULL, $a_inst = 0, $a_sign_locals = false) + { + $ilUser = $this->user; + + // TODO: full implementation of all parameters + //echo "-".$a_mode."-"; + switch ($a_mode) { + case IL_MODE_ALIAS: + $xml = ""; + $xml .= "getId() . "\"/>"; + $media_items = $this->getMediaItems(); + for ($i=0; $igetPurpose() . "\">"; + + // Layout + $width = ($item->getWidth() != "") + ? "Width=\"" . $item->getWidth() . "\"" + : ""; + $height = ($item->getHeight() != "") + ? "Height=\"" . $item->getHeight() . "\"" + : ""; + $halign = ($item->getHAlign() != "") + ? "HorizontalAlign=\"" . $item->getHAlign() . "\"" + : ""; + $xml .= ""; + + // Caption + if ($item->getCaption() != "") { + $xml .= "" . + $this->escapeProperty($item->getCaption()) . ""; + } + + // Text Representation + if ($item->getTextRepresentation() != "") { + $xml .= "" . + $this->escapeProperty($item->getTextRepresentation()) . ""; + } + + // Parameter + $parameters = $item->getParameters(); + foreach ($parameters as $name => $value) { + $xml .= ""; + } + $xml .= $item->getMapAreasXML(); + $xml .= ""; + } + break; + + // for output we need technical sections of meta data + case IL_MODE_OUTPUT: + + // get first technical section // $meta = $this->getMetaData(); - $xml = "getId()."\">"; - - $media_items = $this->getMediaItems(); - for($i=0; $igetPurpose()."\">"; - - if ($a_sign_locals && $item->getLocationType() == "LocalFile") - { - require_once 'Services/WebAccessChecker/classes/class.ilWACSignedPath.php'; - $location = ilWACSignedPath::signFile($this->getDataDirectory()."/".$item->getLocation()); - $location = substr($location, strrpos($location, "/") + 1); - } - else - { + $xml = "getId() . "\">"; + + $media_items = $this->getMediaItems(); + for ($i=0; $igetPurpose() . "\">"; + + if ($a_sign_locals && $item->getLocationType() == "LocalFile") { + require_once 'Services/WebAccessChecker/classes/class.ilWACSignedPath.php'; + $location = ilWACSignedPath::signFile($this->getDataDirectory() . "/" . $item->getLocation()); + $location = substr($location, strrpos($location, "/") + 1); + } else { $location = $item->getLocation(); - if($item->getLocationType() != "LocalFile") { //#25941 + if ($item->getLocationType() != "LocalFile") { //#25941 $location = ilUtil::secureUrl($location); //#23518 } - } - - $xml.= "getLocationType()."\">". - $this->handleAmps($location).""; - - // Format - $xml.= "".$item->getFormat().""; - - // Layout - $width = ($item->getWidth() != "") - ? "Width=\"".$item->getWidth()."\"" - : ""; - $height = ($item->getHeight() != "") - ? "Height=\"".$item->getHeight()."\"" - : ""; - $halign = ($item->getHAlign() != "") - ? "HorizontalAlign=\"".$item->getHAlign()."\"" - : ""; - $xml .= ""; - - // Caption - if ($item->getCaption() != "") - { - $xml .= "". - $this->escapeProperty($item->getCaption()).""; - } - - // Text Representation - if ($item->getTextRepresentation() != "") - { - $xml .= "". - $this->escapeProperty($item->getTextRepresentation()).""; - } - - // Title - if ($this->getTitle() != "") - { - $xml .= "". - str_replace("&", "&", $this->getTitle()).""; - } - - // Parameter - $parameters = $item->getParameters(); - foreach ($parameters as $name => $value) - { - $xml .= ""; - } - $xml .= $item->getMapAreasXML(); - - // Subtitles - if ($item->getPurpose() == "Standard") - { - $srts = $this->getSrtFiles(); - foreach ($srts as $srt) - { - $def = ""; - $meta_lang = ""; - if ($ilUser->getLanguage() != $meta_lang && - $ilUser->getLanguage() == $srt["language"]) - { - $def = ' Default="true" '; - } - $xml .= ""; - } - } - $xml .= ""; - } - break; - - // full xml for export - case IL_MODE_FULL: + } + + $xml.= "getLocationType() . "\">" . + $this->handleAmps($location) . ""; + + // Format + $xml.= "" . $item->getFormat() . ""; + + // Layout + $width = ($item->getWidth() != "") + ? "Width=\"" . $item->getWidth() . "\"" + : ""; + $height = ($item->getHeight() != "") + ? "Height=\"" . $item->getHeight() . "\"" + : ""; + $halign = ($item->getHAlign() != "") + ? "HorizontalAlign=\"" . $item->getHAlign() . "\"" + : ""; + $xml .= ""; + + // Caption + if ($item->getCaption() != "") { + $xml .= "" . + $this->escapeProperty($item->getCaption()) . ""; + } + + // Text Representation + if ($item->getTextRepresentation() != "") { + $xml .= "" . + $this->escapeProperty($item->getTextRepresentation()) . ""; + } + + // Title + if ($this->getTitle() != "") { + $xml .= "" . + str_replace("&", "&", $this->getTitle()) . ""; + } + + // Parameter + $parameters = $item->getParameters(); + foreach ($parameters as $name => $value) { + $xml .= ""; + } + $xml .= $item->getMapAreasXML(); + + // Subtitles + if ($item->getPurpose() == "Standard") { + $srts = $this->getSrtFiles(); + foreach ($srts as $srt) { + $def = ""; + $meta_lang = ""; + if ($ilUser->getLanguage() != $meta_lang && + $ilUser->getLanguage() == $srt["language"]) { + $def = ' Default="true" '; + } + $xml .= ""; + } + } + $xml .= ""; + } + break; + + // full xml for export + case IL_MODE_FULL: // $meta = $this->getMetaData(); - $xml = ""; - - // meta data - include_once("Services/MetaData/classes/class.ilMD2XML.php"); - $md2xml = new ilMD2XML(0, $this->getId(), $this->getType()); - $md2xml->setExportMode(true); - $md2xml->startExport(); - $xml.= $md2xml->getXML(); - - $media_items = $this->getMediaItems(); - for($i=0; $igetPurpose()."\">"; - - // Location - $xml.= "getLocationType()."\">". - $this->handleAmps($item->getLocation()).""; - - // Format - $xml.= "".$item->getFormat().""; - - // Layout - $width = ($item->getWidth() != "") - ? "Width=\"".$item->getWidth()."\"" - : ""; - $height = ($item->getHeight() != "") - ? "Height=\"".$item->getHeight()."\"" - : ""; - $halign = ($item->getHAlign() != "") - ? "HorizontalAlign=\"".$item->getHAlign()."\"" - : ""; - $xml .= ""; - - // Caption - if ($item->getCaption() != "") - { - $xml .= "". - str_replace("&", "&", $item->getCaption()).""; - } - - // Text Representation - if ($item->getTextRepresentation() != "") - { - $xml .= "". - str_replace("&", "&", $item->getTextRepresentation()).""; - } - - // Parameter - $parameters = $item->getParameters(); - foreach ($parameters as $name => $value) - { - $xml .= ""; - } - $xml .= $item->getMapAreasXML(true, $a_inst); - $xml .= ""; - } - break; - } - $xml .= ""; - return $xml; - } - - /** - * Escape property (e.g. title, caption) to XSLT -> HTML output - * - * @param string $a_value - * @return string - */ - protected function escapeProperty($a_value) - { - return htmlspecialchars($a_value); - } - - - /** - * Replace "&" (if not an "&") with "&" - */ - function handleAmps($a_str) - { - $a_str = str_replace("&", "&", $a_str); - $a_str = str_replace("&", "&", $a_str); - return $a_str; - } - - /** - * export XML - */ - function exportXML(&$a_xml_writer, $a_inst = 0) - { - $a_xml_writer->appendXML($this->getXML(IL_MODE_FULL, $a_inst)); - } - - - /** - * export all media files of object to target directory - * note: target directory must be the export target directory, - * "/objects/il__mob_/..." will be appended to this directory - * - * @param string $a_target_dir target directory - */ - function exportFiles($a_target_dir) - { - $subdir = "il_".IL_INST_ID."_mob_".$this->getId(); - ilUtil::makeDir($a_target_dir."/objects/".$subdir); - - $mobdir = ilUtil::getWebspaceDir()."/mobs/mm_".$this->getId(); - ilUtil::rCopy($mobdir, $a_target_dir."/objects/".$subdir); -//echo "from:$mobdir:to:".$a_target_dir."/objects/".$subdir.":
                  "; - } - - function exportMediaFullscreen($a_target_dir, $pg_obj) - { - $subdir = "il_".IL_INST_ID."_mob_".$this->getId(); - $a_target_dir = $a_target_dir."/objects/".$subdir; - ilUtil::makeDir($a_target_dir); - $tpl = new ilTemplate("tpl.fullscreen.html", true, true, "Modules/LearningModule"); - $tpl->setCurrentBlock("ilMedia"); - - //$int_links = $page_object->getInternalLinks(); - $med_links = ilMediaItem::_getMapAreasIntLinks($this->getId()); - - // @todo - //$link_xml = $this->getLinkXML($med_links, $this->getLayoutLinkTargets()); - - require_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - //$media_obj = new ilObjMediaObject($_GET["mob_id"]); - require_once("./Services/COPage/classes/class.ilPageObject.php"); - - $xml = ""; - // todo: we get always the first alias now (problem if mob is used multiple - // times in page) - $xml.= $pg_obj->getMediaAliasElement($this->getId()); - $xml.= $this->getXML(IL_MODE_OUTPUT); - //$xml.= $link_xml; - $xml.=""; - - //die(htmlspecialchars($xml)); - - $xsl = file_get_contents("./Services/COPage/xsl/page.xsl"); - $args = array( '/_xml' => $xml, '/_xsl' => $xsl ); - $xh = xslt_create(); - - //echo "XML:".htmlentities($xml); - // determine target frames for internal links - $wb_path = ""; - $enlarge_path = ""; - $params = array ('mode' => "fullscreen", 'enlarge_path' => $enlarge_path, - 'link_params' => "ref_id=".$_GET["ref_id"],'fullscreen_link' => "", - 'ref_id' => $_GET["ref_id"], 'webspace_path' => $wb_path); - $output = xslt_process($xh,"arg:/_xml","arg:/_xsl",NULL,$args, $params); - //echo xslt_error($xh); - xslt_free($xh); - - // unmask user html - include_once("./Services/MediaObjects/classes/class.ilPlayerUtil.php"); - $tpl->setVariable("LOCATION_CONTENT_STYLESHEET", "../../css/style.css"); - $tpl->setVariable("LOCATION_STYLESHEET", "../../css/system.css"); - $tpl->setVariable("MEDIA_CONTENT", $output); - $output = $tpl->get(); - //$output = preg_replace("/\/mobs\/mm_(\d+)\/([^\"]+)/i","$2",$output); - $output = preg_replace("/mobs\/mm_(\d+)\/([^\"]+)/i","$2",$output); - $output = preg_replace("/\.\/Services\/MediaObjects\/flash_mp3_player/i","../../players",$output); - $output = preg_replace("/\.\/".str_replace("/", "\/", ilPlayerUtil::getFlashVideoPlayerDirectory())."/i","../../players",$output); - $output = preg_replace("/file=..\/..\/..\//i","file=../objects/".$subdir."/",$output); - //die(htmlspecialchars($output)); - fwrite(fopen($a_target_dir.'/fullscreen.html','w'), $output ); - } - - function modifyExportIdentifier($a_tag, $a_param, $a_value) - { - if ($a_tag == "Identifier" && $a_param == "Entry") - { - $a_value = ilUtil::insertInstIntoID($a_value); - } - - return $a_value; - } - - - ////// - // EDIT METHODS: these methods act on the media alias in the dom - ////// - - /** - * content parser set this flag to true, if the media object contains internal links - * (this method should only be called by the import parser) - * - * @param boolean $a_contains_link true, if page contains intern link tag(s) - */ - function setContainsIntLink($a_contains_link) - { - $this->contains_int_link = $a_contains_link; - } - - /** - * returns true, if mob was marked as containing an intern link (via setContainsIntLink) - * (this method should only be called by the import parser) - */ - function containsIntLink() - { - return $this->contains_int_link; - } - - /** - * static - */ - static function _deleteAllUsages($a_type, $a_id, $a_usage_hist_nr = 0, $a_lang = "-") - { - global $DIC; - - $ilDB = $DIC->database(); - - $and_hist = ""; - if ($a_usage_hist_nr !== false) - { - $and_hist = " AND usage_hist_nr = ".$ilDB->quote($a_usage_hist_nr, "integer"); - } - - $mob_ids = array(); - $set = $ilDB->query("SELECT id FROM mob_usage". - " WHERE usage_type = ".$ilDB->quote($a_type, "text"). - " AND usage_id = ".$ilDB->quote($a_id, "integer"). - " AND usage_lang = ".$ilDB->quote($a_lang, "text"). - $and_hist); - while($row = $ilDB->fetchAssoc($set)) - { - $mob_ids[] = $row["id"]; - } - - $q = "DELETE FROM mob_usage WHERE usage_type = ". - $ilDB->quote($a_type, "text"). - " AND usage_id= ".$ilDB->quote($a_id, "integer"). - " AND usage_lang = ".$ilDB->quote($a_lang, "text"). - $and_hist; - $ilDB->manipulate($q); - - foreach($mob_ids as $mob_id) - { - self::handleQuotaUpdate(new self($mob_id)); - } - } - - /** - * get mobs of object - */ - static function _getMobsOfObject($a_type, $a_id, $a_usage_hist_nr = 0, $a_lang = "-") - { - global $DIC; - - $ilDB = $DIC->database(); - - $lstr = ""; - if ($a_lang != "") - { - $lstr = " AND usage_lang = ".$ilDB->quote($a_lang, "text"); - } - $hist_str = ""; - if ($a_usage_hist_nr !== false) - { - $hist_str = " AND usage_hist_nr = ".$ilDB->quote($a_usage_hist_nr, "integer"); - } - - $q = "SELECT * FROM mob_usage WHERE ". - "usage_type = ".$ilDB->quote($a_type, "text")." AND ". - "usage_id = ".$ilDB->quote($a_id, "integer"). - $lstr.$hist_str; - $mobs = array(); - $mob_set = $ilDB->query($q); - while($mob_rec = $ilDB->fetchAssoc($mob_set)) - { - if (ilObject::_lookupType($mob_rec["id"]) == "mob") - { - $mobs[$mob_rec["id"]] = $mob_rec["id"]; - } - } - - return $mobs; - } - - /** - * Save usage of mob within another container (e.g. page) - */ - static function _saveUsage($a_mob_id, $a_type, $a_id, $a_usage_hist_nr = 0, $a_lang = "-") - { - global $DIC; - - $ilDB = $DIC->database(); - - $ilDB->replace("mob_usage", - array( - "id" => array("integer", (int) $a_mob_id), - "usage_type" => array("text", $a_type), - "usage_id" => array("integer", $a_id), - "usage_lang" => array("text", $a_lang), - "usage_hist_nr" => array("integer", (int) $a_usage_hist_nr) - ), - array() - ); - - self::handleQuotaUpdate(new self($a_mob_id)); - } - - /** - * Remove usage of mob in another container - */ - static function _removeUsage($a_mob_id, $a_type, $a_id, $a_usage_hist_nr = 0, $a_lang = "-") - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "DELETE FROM mob_usage WHERE ". - " id = ".$ilDB->quote((int) $a_mob_id, "integer")." AND ". - " usage_type = ".$ilDB->quote($a_type, "text")." AND ". - " usage_id = ".$ilDB->quote((int) $a_id, "integer")." AND ". - " usage_lang = ".$ilDB->quote($a_lang, "text")." AND ". - " usage_hist_nr = ".$ilDB->quote((int) $a_usage_hist_nr, "integer"); - $ilDB->manipulate($q); - - self::handleQuotaUpdate(new self($a_mob_id)); - } - - /** - * get all usages of current media object - */ - function getUsages($a_include_history = true) - { - return self::lookupUsages($this->getId(), $a_include_history); - } - - /** - * Lookup usages of media object - * - * @todo: This should be all in one context -> mob id table - */ - static function lookupUsages($a_id, $a_include_history = true) - { - global $DIC; - - $ilDB = $DIC->database(); - - $hist_str = ""; - if ($a_include_history) - { - $hist_str = ", usage_hist_nr"; - } - - // get usages in pages - $q = "SELECT DISTINCT usage_type, usage_id, usage_lang".$hist_str." FROM mob_usage WHERE id = ". - $ilDB->quote($a_id, "integer"); - - if (!$a_include_history) - { - $q.= " AND usage_hist_nr = ".$ilDB->quote(0, "integer"); - } - - $us_set = $ilDB->query($q); - $ret = array(); - while($us_rec = $ilDB->fetchAssoc($us_set)) - { - $ut = ""; - if(is_int(strpos($us_rec["usage_type"], ":"))) - { - $us_arr = explode(":", $us_rec["usage_type"]); - $ut = $us_arr[1]; - $ct = $us_arr[0]; - } - - // check whether page exists - $skip = false; - if ($ut == "pg") - { - include_once("./Services/COPage/classes/class.ilPageObject.php"); - if (!ilPageObject::_exists($ct, $us_rec["usage_id"])) - { - $skip = true; - } - } - - if (!$skip) - { - $ret[] = array("type" => $us_rec["usage_type"], - "id" => $us_rec["usage_id"], - "lang" => $us_rec["usage_lang"], - "hist_nr" => $us_rec["usage_hist_nr"]); - } - } - - // get usages in media pools - $q = "SELECT DISTINCT mep_id FROM mep_tree JOIN mep_item ON (child = obj_id) WHERE mep_item.foreign_id = ". - $ilDB->quote($a_id, "integer")." AND mep_item.type = ".$ilDB->quote("mob", "text"); - $us_set = $ilDB->query($q); - while($us_rec = $ilDB->fetchAssoc($us_set)) - { - $ret[] = array("type" => "mep", - "id" => $us_rec["mep_id"]); - } - - // get usages in news items (media casts) - include_once("./Services/News/classes/class.ilNewsItem.php"); - $news_usages = ilNewsItem::_lookupMediaObjectUsages($a_id); - foreach($news_usages as $nu) - { - $ret[] = $nu; - } - - - // get usages in map areas - $q = "SELECT DISTINCT mob_id FROM media_item it, map_area area ". - " WHERE area.item_id = it.id ". - " AND area.link_type = ".$ilDB->quote("int", "text")." ". - " AND area.target = ".$ilDB->quote("il__mob_".$a_id, "text"); - $us_set = $ilDB->query($q); - while($us_rec = $ilDB->fetchAssoc($us_set)) - { - $ret[] = array("type" => "map", - "id" => $us_rec["mob_id"]); - } - - // get usages in personal clipboards - $users = ilObjUser::_getUsersForClipboadObject("mob", $a_id); - foreach ($users as $user) - { - $ret[] = array("type" => "clip", - "id" => $user); - } - - return $ret; - } - - /** - * Get's the repository object ID of a parent object, if possible - * - * see ilWebAccessChecker - */ - static function getParentObjectIdForUsage($a_usage, $a_include_all_access_obj_ids = false) - { - if(is_int(strpos($a_usage["type"], ":"))) - { - $us_arr = explode(":", $a_usage["type"]); - $type = $us_arr[1]; - $cont_type = $us_arr[0]; - } - else - { - $type = $a_usage["type"]; - } - - $id = $a_usage["id"]; - $obj_id = false; - - switch($type) - { - // RTE / tiny mce - case "html": - - switch($cont_type) - { - case "qpl": - // Question Pool *Question* Text (Test) - include_once("./Modules/TestQuestionPool/classes/class.assQuestion.php"); - $qinfo = assQuestion::_getQuestionInfo($id); - if ($qinfo["original_id"] > 0) - { - include_once("./Modules/Test/classes/class.ilObjTest.php"); - $obj_id = ilObjTest::_lookupTestObjIdForQuestionId($id); // usage in test - } - else - { - $obj_id = $qinfo["obj_fi"]; // usage in pool - } - break; - - case "spl": - // Question Pool *Question* Text (Survey) - include_once("./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"); - $quest = SurveyQuestion::_instanciateQuestion($id); - if ($quest) - { - $parent_id = $quest->getObjId(); - - // pool question copy - find survey, do not use pool itself - if ($quest->getOriginalId() && - ilObject::_lookupType($parent_id) == "spl") - { - $obj_id = SurveyQuestion::_lookupSurveyObjId($id); - } - // original question (in pool or survey) - else - { - $obj_id = $parent_id; - } - - unset($quest); - } - break; - - case "exca": - // Exercise assignment - $returned_pk = $a_usage['id']; - // #15995 - we are just checking against exercise object - include_once 'Modules/Exercise/classes/class.ilExSubmission.php'; - $obj_id = ilExSubmission::lookupExerciseIdForReturnedId($returned_pk); - break; - - case "frm": - // Forum - $post_pk = $a_usage['id']; - include_once 'Modules/Forum/classes/class.ilForumPost.php'; - include_once 'Modules/Forum/classes/class.ilForum.php'; - $oPost = new ilForumPost($post_pk); - $frm_pk = $oPost->getForumId(); - $obj_id = ilForum::_lookupObjIdForForumId($frm_pk); - break; - - - case "frm~d": - $draft_id = $a_usage['id']; - include_once 'Modules/Forum/classes/class.ilForumPostDraft.php'; - include_once 'Modules/Forum/classes/class.ilForum.php'; - $oDraft = ilForumPostDraft::newInstanceByDraftId($draft_id); - - $frm_pk = $oDraft->getForumId(); - $obj_id = ilForum::_lookupObjIdForForumId($frm_pk); - break; - case "frm~h": - $history_id = $a_usage['id']; - include_once 'Modules/Forum/classes/class.ilForumDraftsHistory.php'; - include_once 'Modules/Forum/classes/class.ilForumPostDraft.php'; - include_once 'Modules/Forum/classes/class.ilForum.php'; - $oHistoryDraft = new ilForumDraftsHistory($history_id); - $oDraft = ilForumPostDraft::newInstanceByDraftId($oHistoryDraft->getDraftId()); - - $frm_pk = $oDraft->getForumId(); - $obj_id = ilForum::_lookupObjIdForForumId($frm_pk); - break; - // temporary items (per user) - case "frm~": - case "exca~": - $obj_id = $a_usage['id']; - break; - - // "old" category pages - case "cat": - // InfoScreen Text - case "tst": - case "svy": - // data collection - case "dcl": - $obj_id = $id; - break; - } - break; - - // page editor - case "pg": - - switch($cont_type) - { - // question feedback // parent obj id is q id - case "qfbg": - include_once('./Services/COPage/classes/class.ilPageObject.php'); - $id = ilPageObject::lookupParentId($id, 'qfbg'); - // note: no break here, we only altered the $id to the question id - - case "qpl": - // Question Pool Question Pages - include_once("./Modules/TestQuestionPool/classes/class.assQuestion.php"); - $qinfo = assQuestion::_getQuestionInfo($id); - if ($qinfo["original_id"] > 0) - { - include_once("./Modules/Test/classes/class.ilObjTest.php"); - $obj_id = ilObjTest::_lookupTestObjIdForQuestionId($id); // usage in test - } - else - { - $obj_id = $qinfo["obj_fi"]; // usage in pool - } - if ($obj_id == 0) // this is the case, if question is in learning module -> get lm id - { - include_once("./Services/COPage/classes/class.ilPCQuestion.php"); - $pinfo = ilPCQuestion::_getPageForQuestionId($id, "lm"); - if ($pinfo && $pinfo["parent_type"] == "lm") - { - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - $obj_id = ilLMObject::_lookupContObjID($pinfo["page_id"]); - } - $pinfo = ilPCQuestion::_getPageForQuestionId($id, "sahs"); - if ($pinfo && $pinfo["parent_type"] == "sahs") - { - include_once("./Modules/Scorm2004/classes/class.ilSCORM2004Node.php"); - $obj_id = ilSCORM2004Node::_lookupSLMID($pinfo["page_id"]); - } - } - break; - - case "lm": - // learning modules - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - $obj_id = ilLMObject::_lookupContObjID($id); - break; - - case "gdf": - // glossary definition - include_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); - include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - $term_id = ilGlossaryDefinition::_lookupTermId($id); - $obj_id = ilGlossaryTerm::_lookGlossaryID($term_id); - break; - - case "wpg": - // wiki page - include_once 'Modules/Wiki/classes/class.ilWikiPage.php'; - $obj_id = ilWikiPage::lookupObjIdByPage($id); - break; - - case "sahs": - // sahs page - // can this implementation be used for other content types, too? - include_once('./Services/COPage/classes/class.ilPageObject.php'); - $obj_id = ilPageObject::lookupParentId($id, 'sahs'); - break; - - case "prtf": - // portfolio - include_once "Modules/Portfolio/classes/class.ilPortfolioPage.php"; - $obj_id = ilPortfolioPage::findPortfolioForPage($id); - break; - - case "prtt": - // portfolio template - include_once "Modules/Portfolio/classes/class.ilPortfolioTemplatePage.php"; - $obj_id = ilPortfolioTemplatePage::findPortfolioForPage($id); - break; - - case "blp": - // blog - include_once('./Services/COPage/classes/class.ilPageObject.php'); - $obj_id = ilPageObject::lookupParentId($id, 'blp'); - break; - - case "impr": - // imprint page - always id 1 - // fallthrough - - case "crs": - case "grp": - case "cat": - case "fold": - case "root": - case "cont": - case "copa": - case "cstr": - // repository pages - $obj_id = $id; - break; - } - break; - - // Media Pool - case "mep": - $obj_id = $id; - break; - - // News Context Object (e.g. MediaCast) - case "news": - include_once("./Services/News/classes/class.ilNewsItem.php"); - $obj_id = ilNewsItem::_lookupContextObjId($id); - break; - } - - return $obj_id; - } - - /** - * resize image and return new image file ("_width_height" string appended) - * - * @param string $a_file full file name - * @param int $a_width width - * @param int $a_height height - */ - static function _resizeImage($a_file, $a_width, $a_height, $a_constrain_prop = false) - { - $file_path = pathinfo($a_file); - $location = substr($file_path["basename"],0,strlen($file_path["basename"]) - - strlen($file_path["extension"]) - 1)."_". - $a_width."_". - $a_height.".".$file_path["extension"]; - $target_file = $file_path["dirname"]."/". - $location; - ilUtil::resizeImage($a_file, $target_file, - (int) $a_width, (int) $a_height, $a_constrain_prop); - - return $location; - } - - /** - * get mime type for file - * - * @param string $a_file file name - * @return string mime type - * static - */ - static function getMimeType($a_file, $a_external = null) - { - include_once("./Services/Utilities/classes/class.ilMimeTypeUtil.php"); - $mime = ilMimeTypeUtil::lookupMimeType($a_file, ilMimeTypeUtil::APPLICATION__OCTET_STREAM, $a_external); - return $mime; - } - - /** - * Determine width and height - */ - static function _determineWidthHeight($a_format, $a_type, - $a_file, $a_reference, $a_constrain_proportions, $a_use_original, - $a_user_width, $a_user_height) - { - global $DIC; - - $lng = $DIC->language(); - - // determine width and height of known image types - //$width = 640; - //$height = 360; - $info = ""; - - if ($a_format == "audio/mpeg") - { - $width = 300; - $height = 20; - } - - if (ilUtil::deducibleSize($a_format)) - { - include_once("./Services/MediaObjects/classes/class.ilMediaImageUtil.php"); - if ($a_type == "File") - { - $size = ilMediaImageUtil::getImageSize($a_file); - } - else - { - $size = ilMediaImageUtil::getImageSize($a_reference); - } - } - - if ($a_use_original) - { - if ($size[0] > 0 && $size[1] > 0) - { - //$width = $size[0]; - //$height = $size[1]; - $width = ""; - $height = ""; - } - else - { - $info = $lng->txt("cont_could_not_determine_resource_size"); - } - } - else - { - $w = (int) $a_user_width; - $h = (int) $a_user_height; - $width = $w; - $height = $h; -//echo "
                  C-$width-$height-"; - if (ilUtil::deducibleSize($a_format) && $a_constrain_proportions) - { - if ($size[0] > 0 && $size[1] > 0) - { - if ($w > 0) - { - $wr = $size[0] / $w; - } - if ($h > 0) - { - $hr = $size[1] / $h; - } -//echo "
                  +".$wr."+".$size[0]."+".$w."+"; -//echo "
                  +".$hr."+".$size[1]."+".$h."+"; - $r = max($wr, $hr); - if ($r > 0) - { - $width = (int) ($size[0]/$r); - $height = (int) ($size[1]/$r); - } - } - } -//echo "
                  D-$width-$height-"; - } -//echo "
                  E-$width-$height-"; - - if ($width == 0 && $a_user_width === "") - { - $width = ""; - } - if ($height == 0 && $a_user_height === "") - { - $height = ""; - } - - return array("width" => $width, "height" => $height, "info" => $info); - } - - /** - * Get simple mime types that deactivate parameter property - * files tab in ILIAS - */ - static function _getSimpleMimeTypes() - { - return array("image/x-ms-bmp", "image/gif", "image/jpeg", "image/x-portable-bitmap", - "image/png", "image/psd", "image/tiff", "application/pdf"); - } - - function getDataDirectory() - { - return ilUtil::getWebspaceDir()."/mobs/mm_".$this->getId(); - } - - /** - * Check whether only autostart parameter should be supported (instead - * of parameters input field. - * - * This should be the same behaviour as mp3/flv in page.xsl - */ - static function _useAutoStartParameterOnly($a_loc, $a_format) - { - $lpath = pathinfo($a_loc); - if ($lpath["extension"] == "mp3" && $a_format == "audio/mpeg") - { - return true; - } - if ($lpath["extension"] == "flv") - { - return true; - } - if (in_array($a_format, array("video/mp4", "video/webm"))) - { - return true; - } - return false; - } - - /** - * Create new media object and update page in db and return new media object - */ - public static function _saveTempFileAsMediaObject($name, $tmp_name, $upload = TRUE) - { - // create dummy object in db (we need an id) - $media_object = new ilObjMediaObject(); - $media_object->setTitle($name); - $media_object->setDescription(""); - $media_object->create(); - - // determine and create mob directory, move uploaded file to directory - $media_object->createDirectory(); - $mob_dir = ilObjMediaObject::_getDirectory($media_object->getId()); - - $media_item = new ilMediaItem(); - $media_object->addMediaItem($media_item); - $media_item->setPurpose("Standard"); - - $file = $mob_dir."/".$name; - if ($upload) - { - ilUtil::moveUploadedFile($tmp_name,$name, $file); - } - else - { - copy($tmp_name, $file); - } - // get mime type - $format = ilObjMediaObject::getMimeType($file); - $location = $name; - // set real meta and object data - $media_item->setFormat($format); - $media_item->setLocation($location); - $media_item->setLocationType("LocalFile"); - $media_object->setTitle($name); - $media_object->setDescription($format); - - if (ilUtil::deducibleSize($format)) - { - include_once("./Services/MediaObjects/classes/class.ilMediaImageUtil.php"); - $size = ilMediaImageUtil::getImageSize($file); - $media_item->setWidth($size[0]); - $media_item->setHeight($size[1]); - } - $media_item->setHAlign("Left"); - - self::renameExecutables($mob_dir); - include_once("./Services/MediaObjects/classes/class.ilMediaSvgSanitizer.php"); - ilMediaSvgSanitizer::sanitizeDir($mob_dir); // see #20339 - - $media_object->update(); - - return $media_object; - } - - /** - * Create new media object and update page in db and return new media object - */ - function uploadAdditionalFile($a_name, $tmp_name, $a_subdir = "", $a_mode = "move_uploaded") - { - $a_subdir = str_replace("..", "", $a_subdir); - $dir = $mob_dir = ilObjMediaObject::_getDirectory($this->getId()); - if ($a_subdir != "") - { - $dir.= "/".$a_subdir; - } - ilUtil::makeDirParents($dir); - if ($a_mode == "rename") - { - rename($tmp_name, $dir . "/" . $a_name); - } - else - { - ilUtil::moveUploadedFile($tmp_name, $a_name, $dir . "/" . $a_name, true, $a_mode); - } - self::renameExecutables($mob_dir); - include_once("./Services/MediaObjects/classes/class.ilMediaSvgSanitizer.php"); - ilMediaSvgSanitizer::sanitizeDir($mob_dir); // see #20339 - - } - - /** - * Upload srt file - * - * @param - * @return - */ - function uploadSrtFile($a_tmp_name, $a_language, $a_mode = "move_uploaded") - { - if (is_file($a_tmp_name) && $a_language != "") - { - $this->uploadAdditionalFile("subtitle_".$a_language.".srt", $a_tmp_name, "srt", $a_mode); - return true; - } - return false; - } - - /** - * Get srt files - */ - function getSrtFiles() - { - $srt_dir = ilObjMediaObject::_getDirectory($this->getId())."/srt"; - - if (!is_dir($srt_dir)) - { - return array(); - } - - $items = ilUtil::getDir($srt_dir); - - $srt_files = array(); - foreach ($items as $i) - { - if (!in_array($i["entry"], array(".", "..")) && $i["type"] == "file") - { - $name = explode(".", $i["entry"]); - if ($name[1] == "srt" && substr($name[0], 0, 9) == "subtitle_") - { - $srt_files[] = array("file" => $i["entry"], - "full_path" => "srt/".$i["entry"], "language" => substr($name[0], 9, 2)); - } - } - } - - return $srt_files; - } - - /** - * Make thumbnail - */ - function makeThumbnail($a_file, $a_thumbname, $a_format = "png", - $a_size = "80") - { - $m_dir = ilObjMediaObject::_getDirectory($this->getId()); - $t_dir = ilObjMediaObject::_getThumbnailDirectory($this->getId()); - self::_createThumbnailDirectory($this->getId()); - ilUtil::convertImage($m_dir."/".$a_file, - $t_dir."/".$a_thumbname, $a_format, $a_size); - } - - /** - * Get thumbnail path - * - * @param string $a_thumbname thumbnail file name - * @return string thumbnail path - */ - static function getThumbnailPath($a_mob_id, $a_thumbname) - { - $t_dir = ilObjMediaObject::_getThumbnailDirectory($a_mob_id); - return $t_dir."/".$a_thumbname; - } - - - /** - * Remove additional file - */ - function removeAdditionalFile($a_file) - { - $file = str_replace("..", "", $a_file); - $file = ilObjMediaObject::_getDirectory($this->getId())."/".$file; - if (is_file($file)) - { - unlink($file); - } - } - - - /** - * Get all media objects linked in map areas of this media object - */ - function getLinkedMediaObjects($a_ignore = "") - { - $linked = array(); - - if (!is_array($a_ignore)) - { - $a_ignore = array(); - } - - // get linked media objects (map areas) - $med_items = $this->getMediaItems(); - - foreach($med_items as $med_item) - { - $int_links = ilMapArea::_getIntLinks($med_item->getId()); - foreach ($int_links as $k => $int_link) - { - if ($int_link["Type"] == "MediaObject") - { - include_once("./Services/Link/classes/class.ilInternalLink.php"); - $l_id = ilInternalLink::_extractObjIdOfTarget($int_link["Target"]); - if (ilObject::_exists($l_id)) - { - if (!in_array($l_id, $linked) && - !in_array($l_id, $a_ignore)) - { - $linked[] = $l_id; - } - } - } - } - } -//var_dump($linked); - return $linked; - } - - /** - * Get restricted file types (this is for the input form, this list will be empty, if "allowed list" is empty) - */ - static function getRestrictedFileTypes() - { - return array_filter(self::getAllowedFileTypes(), function ($v) { - return !in_array($v, self::getForbiddenFileTypes()); - }); - } - - /** - * Get forbidden file types - * - * @return array - */ - static function getForbiddenFileTypes() - { - $mset = new ilSetting("mobs"); - if (trim($mset->get("black_list_file_types")) == "") - { - return array(); - } - return array_map(function ($v) - { - return strtolower(trim($v)); - }, - explode(",", $mset->get("black_list_file_types"))); - } - - /** - * Get allowed file types - * - * @return array - */ - static function getAllowedFileTypes() - { - $mset = new ilSetting("mobs"); - if (trim($mset->get("restricted_file_types")) == "") - { - return array(); - } - return array_map(function ($v) - { - return strtolower(trim($v)); - }, - explode(",", $mset->get("restricted_file_types"))); - } - - /** - * Is type allowed - * - * @param string $a_type - * @return bool - */ - static function isTypeAllowed($a_type) - { - if (in_array($a_type, self::getForbiddenFileTypes())) - { - return false; - } - if (count(self::getAllowedFileTypes()) == 0 || in_array($a_type, self::getAllowedFileTypes())) - { - return true; - } - return false; - } - - - /** - * Duplicate media object, return new media object - */ - function duplicate() - { - $new_obj = new ilObjMediaObject(); - $new_obj->setTitle($this->getTitle()); - $new_obj->setDescription($this->getDescription()); - - // media items - foreach($this->getMediaItems() as $key => $val) - { - $new_obj->addMediaItem($val); - } - - $new_obj->create(false, true); - - // files - $new_obj->createDirectory(); - self::_createThumbnailDirectory($new_obj->getId()); - ilUtil::rCopy(ilObjMediaObject::_getDirectory($this->getId()), - ilObjMediaObject::_getDirectory($new_obj->getId())); - ilUtil::rCopy(ilObjMediaObject::_getThumbnailDirectory($this->getId()), - ilObjMediaObject::_getThumbnailDirectory($new_obj->getId())); - - // meta data - include_once("Services/MetaData/classes/class.ilMD.php"); - $md = new ilMD(0, $this->getId(), "mob"); - $new_md = $md->cloneMD(0, $new_obj->getId(), "mob"); - - return $new_obj; - } - - /** - * Upload video preview picture - * - * @param - * @return - */ - function uploadVideoPreviewPic($a_prevpic) - { - // remove old one - if ($this->getVideoPreviewPic(true) != "") - { - $this->removeAdditionalFile($this->getVideoPreviewPic(true)); - } - - $pi = pathinfo($a_prevpic["name"]); - $ext = $pi["extension"]; - if (in_array($ext, array("jpg", "jpeg", "png"))) - { - $this->uploadAdditionalFile("mob_vpreview.".$ext, $a_prevpic["tmp_name"]); - } - } - - /** - * Upload video preview picture - * - * @param - * @return - */ - function generatePreviewPic($a_width, $a_height) - { - $item = $this->getMediaItem("Standard"); - - if ($item->getLocationType() == "LocalFile" && - is_int(strpos($item->getFormat(), "image/"))) - { - $dir = ilObjMediaObject::_getDirectory($this->getId()); - $file = $dir."/". - $item->getLocation(); - if (is_file($file)) - { - if(ilUtil::isConvertVersionAtLeast("6.3.8-3")) - { - ilUtil::execConvert(ilUtil::escapeShellArg($file)."[0] -geometry ".$a_width."x".$a_height."^ -gravity center -extent ".$a_width."x".$a_height." PNG:".$dir."/mob_vpreview.png"); - } - else - { - ilUtil::convertImage($file, $dir."/mob_vpreview.png", "PNG", $a_width."x".$a_height); - } - } - } - } - - /** - * Get video preview pic - * - * @param - * @return - */ - function getVideoPreviewPic($a_filename_only = false) - { - $dir = ilObjMediaObject::_getDirectory($this->getId()); - $ppics = array("mob_vpreview.jpg", - "mob_vpreview.jpeg", - "mob_vpreview.png"); - foreach ($ppics as $p) - { - if (is_file($dir."/".$p)) - { - if ($a_filename_only) - { - return $p; - } - else - { - return $dir."/".$p; - } - } - } - return ""; - } - - /** - * Fix filename of uploaded file - * - * @param string $a_name upload file name - * @return string fixed file name - */ - static function fixFilename($a_name) - { - $a_name = ilUtil::getASCIIFilename($a_name); - - $rchars = array("`", "=", "$", "{", "}", "'", ";", " ", "(", ")"); - $a_name = str_replace($rchars, "_", $a_name); - $a_name = str_replace("__", "_", $a_name); - return $a_name; - } - - - /** - * Get directory for multi srt upload - * - * @param - * @return - */ - function getMultiSrtUploadDir() - { - return ilObjMediaObject::_getDirectory($this->getId()."/srt/tmp"); - } - - - /** - * Upload multi srt file - * - * @param array $a_file file info array - * @throws ilMediaObjectsException - */ - function uploadMultipleSubtitleFile($a_file) - { - $lng = $this->lng; - $ilUser = $this->user; - - include_once("./Services/MediaObjects/exceptions/class.ilMediaObjectsException.php"); - if (!is_file($a_file["tmp_name"])) - { - throw new ilMediaObjectsException($lng->txt("mob_file_could_not_be_uploaded")); - } - - $dir = $this->getMultiSrtUploadDir(); - ilUtil::delDir($dir, true); - ilUtil::makeDirParents($dir); - ilUtil::moveUploadedFile($a_file["tmp_name"], "multi_srt.zip", $dir."/"."multi_srt.zip"); - ilUtil::unzip($dir."/multi_srt.zip", true); - } - - /** - * Clear multi feedback directory - */ - function clearMultiSrtDirectory() - { - ilUtil::delDir($this->getMultiSrtUploadDir()); - } - - /** - * Get all srt files of srt multi upload - */ - function getMultiSrtFiles() - { - $items = array(); - - include_once("./Services/MetaData/classes/class.ilMDLanguageItem.php"); - $lang_codes = ilMDLanguageItem::_getPossibleLanguageCodes(); - - $dir = $this->getMultiSrtUploadDir(); - $files = ilUtil::getDir($dir); - foreach ($files as $k => $i) - { - // check directory - if ($i["type"] == "file" && !in_array($k, array(".", ".."))) - { - if (pathinfo($k, PATHINFO_EXTENSION) == "srt") - { - $lang = ""; - if (substr($k, strlen($k) - 7, 1) == "_") - { - $lang = substr($k, strlen($k) - 6, 2); - if (!in_array($lang, $lang_codes)) - { - $lang = ""; - } - } - $items[] = array("filename" => $k, "lang" => $lang); - } - } - } - return $items; - } - - /** - * Rename executables - * - * @param string - */ - static function renameExecutables($a_dir) - { - ilUtil::renameExecutables($a_dir); - if (!self::isTypeAllowed("html")) - { - ilUtil::rRenameSuffix($a_dir, "html", "sec"); // see #20187 - } - } + $xml = ""; + + // meta data + include_once("Services/MetaData/classes/class.ilMD2XML.php"); + $md2xml = new ilMD2XML(0, $this->getId(), $this->getType()); + $md2xml->setExportMode(true); + $md2xml->startExport(); + $xml.= $md2xml->getXML(); + + $media_items = $this->getMediaItems(); + for ($i=0; $igetPurpose() . "\">"; + + // Location + $xml.= "getLocationType() . "\">" . + $this->handleAmps($item->getLocation()) . ""; + + // Format + $xml.= "" . $item->getFormat() . ""; + + // Layout + $width = ($item->getWidth() != "") + ? "Width=\"" . $item->getWidth() . "\"" + : ""; + $height = ($item->getHeight() != "") + ? "Height=\"" . $item->getHeight() . "\"" + : ""; + $halign = ($item->getHAlign() != "") + ? "HorizontalAlign=\"" . $item->getHAlign() . "\"" + : ""; + $xml .= ""; + + // Caption + if ($item->getCaption() != "") { + $xml .= "" . + str_replace("&", "&", $item->getCaption()) . ""; + } + + // Text Representation + if ($item->getTextRepresentation() != "") { + $xml .= "" . + str_replace("&", "&", $item->getTextRepresentation()) . ""; + } + + // Parameter + $parameters = $item->getParameters(); + foreach ($parameters as $name => $value) { + $xml .= ""; + } + $xml .= $item->getMapAreasXML(true, $a_inst); + $xml .= ""; + } + break; + } + $xml .= ""; + return $xml; + } + + /** + * Escape property (e.g. title, caption) to XSLT -> HTML output + * + * @param string $a_value + * @return string + */ + protected function escapeProperty($a_value) + { + return htmlspecialchars($a_value); + } + + + /** + * Replace "&" (if not an "&") with "&" + */ + public function handleAmps($a_str) + { + $a_str = str_replace("&", "&", $a_str); + $a_str = str_replace("&", "&", $a_str); + return $a_str; + } + + /** + * export XML + */ + public function exportXML(&$a_xml_writer, $a_inst = 0) + { + $a_xml_writer->appendXML($this->getXML(IL_MODE_FULL, $a_inst)); + } + + + /** + * export all media files of object to target directory + * note: target directory must be the export target directory, + * "/objects/il__mob_/..." will be appended to this directory + * + * @param string $a_target_dir target directory + */ + public function exportFiles($a_target_dir) + { + $subdir = "il_" . IL_INST_ID . "_mob_" . $this->getId(); + ilUtil::makeDir($a_target_dir . "/objects/" . $subdir); + + $mobdir = ilUtil::getWebspaceDir() . "/mobs/mm_" . $this->getId(); + ilUtil::rCopy($mobdir, $a_target_dir . "/objects/" . $subdir); + //echo "from:$mobdir:to:".$a_target_dir."/objects/".$subdir.":
                  "; + } + + public function exportMediaFullscreen($a_target_dir, $pg_obj) + { + $subdir = "il_" . IL_INST_ID . "_mob_" . $this->getId(); + $a_target_dir = $a_target_dir . "/objects/" . $subdir; + ilUtil::makeDir($a_target_dir); + $tpl = new ilTemplate("tpl.fullscreen.html", true, true, "Modules/LearningModule"); + $tpl->setCurrentBlock("ilMedia"); + + //$int_links = $page_object->getInternalLinks(); + $med_links = ilMediaItem::_getMapAreasIntLinks($this->getId()); + + // @todo + //$link_xml = $this->getLinkXML($med_links, $this->getLayoutLinkTargets()); + + require_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + //$media_obj = new ilObjMediaObject($_GET["mob_id"]); + require_once("./Services/COPage/classes/class.ilPageObject.php"); + + $xml = ""; + // todo: we get always the first alias now (problem if mob is used multiple + // times in page) + $xml.= $pg_obj->getMediaAliasElement($this->getId()); + $xml.= $this->getXML(IL_MODE_OUTPUT); + //$xml.= $link_xml; + $xml.=""; + + //die(htmlspecialchars($xml)); + + $xsl = file_get_contents("./Services/COPage/xsl/page.xsl"); + $args = array( '/_xml' => $xml, '/_xsl' => $xsl ); + $xh = xslt_create(); + + //echo "XML:".htmlentities($xml); + // determine target frames for internal links + $wb_path = ""; + $enlarge_path = ""; + $params = array('mode' => "fullscreen", 'enlarge_path' => $enlarge_path, + 'link_params' => "ref_id=" . $_GET["ref_id"],'fullscreen_link' => "", + 'ref_id' => $_GET["ref_id"], 'webspace_path' => $wb_path); + $output = xslt_process($xh, "arg:/_xml", "arg:/_xsl", null, $args, $params); + //echo xslt_error($xh); + xslt_free($xh); + + // unmask user html + include_once("./Services/MediaObjects/classes/class.ilPlayerUtil.php"); + $tpl->setVariable("LOCATION_CONTENT_STYLESHEET", "../../css/style.css"); + $tpl->setVariable("LOCATION_STYLESHEET", "../../css/system.css"); + $tpl->setVariable("MEDIA_CONTENT", $output); + $output = $tpl->get(); + //$output = preg_replace("/\/mobs\/mm_(\d+)\/([^\"]+)/i","$2",$output); + $output = preg_replace("/mobs\/mm_(\d+)\/([^\"]+)/i", "$2", $output); + $output = preg_replace("/\.\/Services\/MediaObjects\/flash_mp3_player/i", "../../players", $output); + $output = preg_replace("/\.\/" . str_replace("/", "\/", ilPlayerUtil::getFlashVideoPlayerDirectory()) . "/i", "../../players", $output); + $output = preg_replace("/file=..\/..\/..\//i", "file=../objects/" . $subdir . "/", $output); + //die(htmlspecialchars($output)); + fwrite(fopen($a_target_dir . '/fullscreen.html', 'w'), $output); + } + + public function modifyExportIdentifier($a_tag, $a_param, $a_value) + { + if ($a_tag == "Identifier" && $a_param == "Entry") { + $a_value = ilUtil::insertInstIntoID($a_value); + } + + return $a_value; + } + + + ////// + // EDIT METHODS: these methods act on the media alias in the dom + ////// + + /** + * content parser set this flag to true, if the media object contains internal links + * (this method should only be called by the import parser) + * + * @param boolean $a_contains_link true, if page contains intern link tag(s) + */ + public function setContainsIntLink($a_contains_link) + { + $this->contains_int_link = $a_contains_link; + } + + /** + * returns true, if mob was marked as containing an intern link (via setContainsIntLink) + * (this method should only be called by the import parser) + */ + public function containsIntLink() + { + return $this->contains_int_link; + } + + /** + * static + */ + public static function _deleteAllUsages($a_type, $a_id, $a_usage_hist_nr = 0, $a_lang = "-") + { + global $DIC; + + $ilDB = $DIC->database(); + + $and_hist = ""; + if ($a_usage_hist_nr !== false) { + $and_hist = " AND usage_hist_nr = " . $ilDB->quote($a_usage_hist_nr, "integer"); + } + + $mob_ids = array(); + $set = $ilDB->query("SELECT id FROM mob_usage" . + " WHERE usage_type = " . $ilDB->quote($a_type, "text") . + " AND usage_id = " . $ilDB->quote($a_id, "integer") . + " AND usage_lang = " . $ilDB->quote($a_lang, "text") . + $and_hist); + while ($row = $ilDB->fetchAssoc($set)) { + $mob_ids[] = $row["id"]; + } + + $q = "DELETE FROM mob_usage WHERE usage_type = " . + $ilDB->quote($a_type, "text") . + " AND usage_id= " . $ilDB->quote($a_id, "integer") . + " AND usage_lang = " . $ilDB->quote($a_lang, "text") . + $and_hist; + $ilDB->manipulate($q); + + foreach ($mob_ids as $mob_id) { + self::handleQuotaUpdate(new self($mob_id)); + } + } + + /** + * get mobs of object + */ + public static function _getMobsOfObject($a_type, $a_id, $a_usage_hist_nr = 0, $a_lang = "-") + { + global $DIC; + + $ilDB = $DIC->database(); + + $lstr = ""; + if ($a_lang != "") { + $lstr = " AND usage_lang = " . $ilDB->quote($a_lang, "text"); + } + $hist_str = ""; + if ($a_usage_hist_nr !== false) { + $hist_str = " AND usage_hist_nr = " . $ilDB->quote($a_usage_hist_nr, "integer"); + } + + $q = "SELECT * FROM mob_usage WHERE " . + "usage_type = " . $ilDB->quote($a_type, "text") . " AND " . + "usage_id = " . $ilDB->quote($a_id, "integer") . + $lstr . $hist_str; + $mobs = array(); + $mob_set = $ilDB->query($q); + while ($mob_rec = $ilDB->fetchAssoc($mob_set)) { + if (ilObject::_lookupType($mob_rec["id"]) == "mob") { + $mobs[$mob_rec["id"]] = $mob_rec["id"]; + } + } + + return $mobs; + } + + /** + * Save usage of mob within another container (e.g. page) + */ + public static function _saveUsage($a_mob_id, $a_type, $a_id, $a_usage_hist_nr = 0, $a_lang = "-") + { + global $DIC; + + $ilDB = $DIC->database(); + + $ilDB->replace( + "mob_usage", + array( + "id" => array("integer", (int) $a_mob_id), + "usage_type" => array("text", $a_type), + "usage_id" => array("integer", $a_id), + "usage_lang" => array("text", $a_lang), + "usage_hist_nr" => array("integer", (int) $a_usage_hist_nr) + ), + array() + ); + + self::handleQuotaUpdate(new self($a_mob_id)); + } + + /** + * Remove usage of mob in another container + */ + public static function _removeUsage($a_mob_id, $a_type, $a_id, $a_usage_hist_nr = 0, $a_lang = "-") + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "DELETE FROM mob_usage WHERE " . + " id = " . $ilDB->quote((int) $a_mob_id, "integer") . " AND " . + " usage_type = " . $ilDB->quote($a_type, "text") . " AND " . + " usage_id = " . $ilDB->quote((int) $a_id, "integer") . " AND " . + " usage_lang = " . $ilDB->quote($a_lang, "text") . " AND " . + " usage_hist_nr = " . $ilDB->quote((int) $a_usage_hist_nr, "integer"); + $ilDB->manipulate($q); + + self::handleQuotaUpdate(new self($a_mob_id)); + } + + /** + * get all usages of current media object + */ + public function getUsages($a_include_history = true) + { + return self::lookupUsages($this->getId(), $a_include_history); + } + + /** + * Lookup usages of media object + * + * @todo: This should be all in one context -> mob id table + */ + public static function lookupUsages($a_id, $a_include_history = true) + { + global $DIC; + + $ilDB = $DIC->database(); + + $hist_str = ""; + if ($a_include_history) { + $hist_str = ", usage_hist_nr"; + } + + // get usages in pages + $q = "SELECT DISTINCT usage_type, usage_id, usage_lang" . $hist_str . " FROM mob_usage WHERE id = " . + $ilDB->quote($a_id, "integer"); + + if (!$a_include_history) { + $q.= " AND usage_hist_nr = " . $ilDB->quote(0, "integer"); + } + + $us_set = $ilDB->query($q); + $ret = array(); + while ($us_rec = $ilDB->fetchAssoc($us_set)) { + $ut = ""; + if (is_int(strpos($us_rec["usage_type"], ":"))) { + $us_arr = explode(":", $us_rec["usage_type"]); + $ut = $us_arr[1]; + $ct = $us_arr[0]; + } + + // check whether page exists + $skip = false; + if ($ut == "pg") { + include_once("./Services/COPage/classes/class.ilPageObject.php"); + if (!ilPageObject::_exists($ct, $us_rec["usage_id"])) { + $skip = true; + } + } + + if (!$skip) { + $ret[] = array("type" => $us_rec["usage_type"], + "id" => $us_rec["usage_id"], + "lang" => $us_rec["usage_lang"], + "hist_nr" => $us_rec["usage_hist_nr"]); + } + } + + // get usages in media pools + $q = "SELECT DISTINCT mep_id FROM mep_tree JOIN mep_item ON (child = obj_id) WHERE mep_item.foreign_id = " . + $ilDB->quote($a_id, "integer") . " AND mep_item.type = " . $ilDB->quote("mob", "text"); + $us_set = $ilDB->query($q); + while ($us_rec = $ilDB->fetchAssoc($us_set)) { + $ret[] = array("type" => "mep", + "id" => $us_rec["mep_id"]); + } + + // get usages in news items (media casts) + include_once("./Services/News/classes/class.ilNewsItem.php"); + $news_usages = ilNewsItem::_lookupMediaObjectUsages($a_id); + foreach ($news_usages as $nu) { + $ret[] = $nu; + } + + + // get usages in map areas + $q = "SELECT DISTINCT mob_id FROM media_item it, map_area area " . + " WHERE area.item_id = it.id " . + " AND area.link_type = " . $ilDB->quote("int", "text") . " " . + " AND area.target = " . $ilDB->quote("il__mob_" . $a_id, "text"); + $us_set = $ilDB->query($q); + while ($us_rec = $ilDB->fetchAssoc($us_set)) { + $ret[] = array("type" => "map", + "id" => $us_rec["mob_id"]); + } + + // get usages in personal clipboards + $users = ilObjUser::_getUsersForClipboadObject("mob", $a_id); + foreach ($users as $user) { + $ret[] = array("type" => "clip", + "id" => $user); + } + + return $ret; + } + + /** + * Get's the repository object ID of a parent object, if possible + * + * see ilWebAccessChecker + */ + public static function getParentObjectIdForUsage($a_usage, $a_include_all_access_obj_ids = false) + { + if (is_int(strpos($a_usage["type"], ":"))) { + $us_arr = explode(":", $a_usage["type"]); + $type = $us_arr[1]; + $cont_type = $us_arr[0]; + } else { + $type = $a_usage["type"]; + } + + $id = $a_usage["id"]; + $obj_id = false; + + switch ($type) { + // RTE / tiny mce + case "html": + + switch ($cont_type) { + case "qpl": + // Question Pool *Question* Text (Test) + include_once("./Modules/TestQuestionPool/classes/class.assQuestion.php"); + $qinfo = assQuestion::_getQuestionInfo($id); + if ($qinfo["original_id"] > 0) { + include_once("./Modules/Test/classes/class.ilObjTest.php"); + $obj_id = ilObjTest::_lookupTestObjIdForQuestionId($id); // usage in test + } else { + $obj_id = $qinfo["obj_fi"]; // usage in pool + } + break; + + case "spl": + // Question Pool *Question* Text (Survey) + include_once("./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"); + $quest = SurveyQuestion::_instanciateQuestion($id); + if ($quest) { + $parent_id = $quest->getObjId(); + + // pool question copy - find survey, do not use pool itself + if ($quest->getOriginalId() && + ilObject::_lookupType($parent_id) == "spl") { + $obj_id = SurveyQuestion::_lookupSurveyObjId($id); + } + // original question (in pool or survey) + else { + $obj_id = $parent_id; + } + + unset($quest); + } + break; + + case "exca": + // Exercise assignment + $returned_pk = $a_usage['id']; + // #15995 - we are just checking against exercise object + include_once 'Modules/Exercise/classes/class.ilExSubmission.php'; + $obj_id = ilExSubmission::lookupExerciseIdForReturnedId($returned_pk); + break; + + case "frm": + // Forum + $post_pk = $a_usage['id']; + include_once 'Modules/Forum/classes/class.ilForumPost.php'; + include_once 'Modules/Forum/classes/class.ilForum.php'; + $oPost = new ilForumPost($post_pk); + $frm_pk = $oPost->getForumId(); + $obj_id = ilForum::_lookupObjIdForForumId($frm_pk); + break; + + + case "frm~d": + $draft_id = $a_usage['id']; + include_once 'Modules/Forum/classes/class.ilForumPostDraft.php'; + include_once 'Modules/Forum/classes/class.ilForum.php'; + $oDraft = ilForumPostDraft::newInstanceByDraftId($draft_id); + + $frm_pk = $oDraft->getForumId(); + $obj_id = ilForum::_lookupObjIdForForumId($frm_pk); + break; + case "frm~h": + $history_id = $a_usage['id']; + include_once 'Modules/Forum/classes/class.ilForumDraftsHistory.php'; + include_once 'Modules/Forum/classes/class.ilForumPostDraft.php'; + include_once 'Modules/Forum/classes/class.ilForum.php'; + $oHistoryDraft = new ilForumDraftsHistory($history_id); + $oDraft = ilForumPostDraft::newInstanceByDraftId($oHistoryDraft->getDraftId()); + + $frm_pk = $oDraft->getForumId(); + $obj_id = ilForum::_lookupObjIdForForumId($frm_pk); + break; + // temporary items (per user) + case "frm~": + case "exca~": + $obj_id = $a_usage['id']; + break; + + // "old" category pages + case "cat": + // InfoScreen Text + case "tst": + case "svy": + // data collection + case "dcl": + $obj_id = $id; + break; + } + break; + + // page editor + case "pg": + + switch ($cont_type) { + // question feedback // parent obj id is q id + case "qfbg": + include_once('./Services/COPage/classes/class.ilPageObject.php'); + $id = ilPageObject::lookupParentId($id, 'qfbg'); + // note: no break here, we only altered the $id to the question id + + // no break + case "qpl": + // Question Pool Question Pages + include_once("./Modules/TestQuestionPool/classes/class.assQuestion.php"); + $qinfo = assQuestion::_getQuestionInfo($id); + if ($qinfo["original_id"] > 0) { + include_once("./Modules/Test/classes/class.ilObjTest.php"); + $obj_id = ilObjTest::_lookupTestObjIdForQuestionId($id); // usage in test + } else { + $obj_id = $qinfo["obj_fi"]; // usage in pool + } + if ($obj_id == 0) { // this is the case, if question is in learning module -> get lm id + include_once("./Services/COPage/classes/class.ilPCQuestion.php"); + $pinfo = ilPCQuestion::_getPageForQuestionId($id, "lm"); + if ($pinfo && $pinfo["parent_type"] == "lm") { + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + $obj_id = ilLMObject::_lookupContObjID($pinfo["page_id"]); + } + $pinfo = ilPCQuestion::_getPageForQuestionId($id, "sahs"); + if ($pinfo && $pinfo["parent_type"] == "sahs") { + include_once("./Modules/Scorm2004/classes/class.ilSCORM2004Node.php"); + $obj_id = ilSCORM2004Node::_lookupSLMID($pinfo["page_id"]); + } + } + break; + + case "lm": + // learning modules + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + $obj_id = ilLMObject::_lookupContObjID($id); + break; + + case "gdf": + // glossary definition + include_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); + include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + $term_id = ilGlossaryDefinition::_lookupTermId($id); + $obj_id = ilGlossaryTerm::_lookGlossaryID($term_id); + break; + + case "wpg": + // wiki page + include_once 'Modules/Wiki/classes/class.ilWikiPage.php'; + $obj_id = ilWikiPage::lookupObjIdByPage($id); + break; + + case "sahs": + // sahs page + // can this implementation be used for other content types, too? + include_once('./Services/COPage/classes/class.ilPageObject.php'); + $obj_id = ilPageObject::lookupParentId($id, 'sahs'); + break; + + case "prtf": + // portfolio + include_once "Modules/Portfolio/classes/class.ilPortfolioPage.php"; + $obj_id = ilPortfolioPage::findPortfolioForPage($id); + break; + + case "prtt": + // portfolio template + include_once "Modules/Portfolio/classes/class.ilPortfolioTemplatePage.php"; + $obj_id = ilPortfolioTemplatePage::findPortfolioForPage($id); + break; + + case "blp": + // blog + include_once('./Services/COPage/classes/class.ilPageObject.php'); + $obj_id = ilPageObject::lookupParentId($id, 'blp'); + break; + + case "impr": + // imprint page - always id 1 + // fallthrough + + case "crs": + case "grp": + case "cat": + case "fold": + case "root": + case "cont": + case "copa": + case "cstr": + // repository pages + $obj_id = $id; + break; + } + break; + + // Media Pool + case "mep": + $obj_id = $id; + break; + + // News Context Object (e.g. MediaCast) + case "news": + include_once("./Services/News/classes/class.ilNewsItem.php"); + $obj_id = ilNewsItem::_lookupContextObjId($id); + break; + } + + return $obj_id; + } + + /** + * resize image and return new image file ("_width_height" string appended) + * + * @param string $a_file full file name + * @param int $a_width width + * @param int $a_height height + */ + public static function _resizeImage($a_file, $a_width, $a_height, $a_constrain_prop = false) + { + $file_path = pathinfo($a_file); + $location = substr($file_path["basename"], 0, strlen($file_path["basename"]) - + strlen($file_path["extension"]) - 1) . "_" . + $a_width . "_" . + $a_height . "." . $file_path["extension"]; + $target_file = $file_path["dirname"] . "/" . + $location; + ilUtil::resizeImage( + $a_file, + $target_file, + (int) $a_width, + (int) $a_height, + $a_constrain_prop + ); + + return $location; + } + + /** + * get mime type for file + * + * @param string $a_file file name + * @return string mime type + * static + */ + public static function getMimeType($a_file, $a_external = null) + { + include_once("./Services/Utilities/classes/class.ilMimeTypeUtil.php"); + $mime = ilMimeTypeUtil::lookupMimeType($a_file, ilMimeTypeUtil::APPLICATION__OCTET_STREAM, $a_external); + return $mime; + } + + /** + * Determine width and height + */ + public static function _determineWidthHeight( + $a_format, + $a_type, + $a_file, + $a_reference, + $a_constrain_proportions, + $a_use_original, + $a_user_width, + $a_user_height + ) { + global $DIC; + + $lng = $DIC->language(); + + // determine width and height of known image types + //$width = 640; + //$height = 360; + $info = ""; + + if ($a_format == "audio/mpeg") { + $width = 300; + $height = 20; + } + + if (ilUtil::deducibleSize($a_format)) { + include_once("./Services/MediaObjects/classes/class.ilMediaImageUtil.php"); + if ($a_type == "File") { + $size = ilMediaImageUtil::getImageSize($a_file); + } else { + $size = ilMediaImageUtil::getImageSize($a_reference); + } + } + + if ($a_use_original) { + if ($size[0] > 0 && $size[1] > 0) { + //$width = $size[0]; + //$height = $size[1]; + $width = ""; + $height = ""; + } else { + $info = $lng->txt("cont_could_not_determine_resource_size"); + } + } else { + $w = (int) $a_user_width; + $h = (int) $a_user_height; + $width = $w; + $height = $h; + //echo "
                  C-$width-$height-"; + if (ilUtil::deducibleSize($a_format) && $a_constrain_proportions) { + if ($size[0] > 0 && $size[1] > 0) { + if ($w > 0) { + $wr = $size[0] / $w; + } + if ($h > 0) { + $hr = $size[1] / $h; + } + //echo "
                  +".$wr."+".$size[0]."+".$w."+"; + //echo "
                  +".$hr."+".$size[1]."+".$h."+"; + $r = max($wr, $hr); + if ($r > 0) { + $width = (int) ($size[0]/$r); + $height = (int) ($size[1]/$r); + } + } + } + //echo "
                  D-$width-$height-"; + } + //echo "
                  E-$width-$height-"; + + if ($width == 0 && $a_user_width === "") { + $width = ""; + } + if ($height == 0 && $a_user_height === "") { + $height = ""; + } + + return array("width" => $width, "height" => $height, "info" => $info); + } + + /** + * Get simple mime types that deactivate parameter property + * files tab in ILIAS + */ + public static function _getSimpleMimeTypes() + { + return array("image/x-ms-bmp", "image/gif", "image/jpeg", "image/x-portable-bitmap", + "image/png", "image/psd", "image/tiff", "application/pdf"); + } + + public function getDataDirectory() + { + return ilUtil::getWebspaceDir() . "/mobs/mm_" . $this->getId(); + } + + /** + * Check whether only autostart parameter should be supported (instead + * of parameters input field. + * + * This should be the same behaviour as mp3/flv in page.xsl + */ + public static function _useAutoStartParameterOnly($a_loc, $a_format) + { + $lpath = pathinfo($a_loc); + if ($lpath["extension"] == "mp3" && $a_format == "audio/mpeg") { + return true; + } + if ($lpath["extension"] == "flv") { + return true; + } + if (in_array($a_format, array("video/mp4", "video/webm"))) { + return true; + } + return false; + } + + /** + * Create new media object and update page in db and return new media object + */ + public static function _saveTempFileAsMediaObject($name, $tmp_name, $upload = true) + { + // create dummy object in db (we need an id) + $media_object = new ilObjMediaObject(); + $media_object->setTitle($name); + $media_object->setDescription(""); + $media_object->create(); + + // determine and create mob directory, move uploaded file to directory + $media_object->createDirectory(); + $mob_dir = ilObjMediaObject::_getDirectory($media_object->getId()); + + $media_item = new ilMediaItem(); + $media_object->addMediaItem($media_item); + $media_item->setPurpose("Standard"); + + $file = $mob_dir . "/" . $name; + if ($upload) { + ilUtil::moveUploadedFile($tmp_name, $name, $file); + } else { + copy($tmp_name, $file); + } + // get mime type + $format = ilObjMediaObject::getMimeType($file); + $location = $name; + // set real meta and object data + $media_item->setFormat($format); + $media_item->setLocation($location); + $media_item->setLocationType("LocalFile"); + $media_object->setTitle($name); + $media_object->setDescription($format); + + if (ilUtil::deducibleSize($format)) { + include_once("./Services/MediaObjects/classes/class.ilMediaImageUtil.php"); + $size = ilMediaImageUtil::getImageSize($file); + $media_item->setWidth($size[0]); + $media_item->setHeight($size[1]); + } + $media_item->setHAlign("Left"); + + self::renameExecutables($mob_dir); + include_once("./Services/MediaObjects/classes/class.ilMediaSvgSanitizer.php"); + ilMediaSvgSanitizer::sanitizeDir($mob_dir); // see #20339 + + $media_object->update(); + + return $media_object; + } + + /** + * Create new media object and update page in db and return new media object + */ + public function uploadAdditionalFile($a_name, $tmp_name, $a_subdir = "", $a_mode = "move_uploaded") + { + $a_subdir = str_replace("..", "", $a_subdir); + $dir = $mob_dir = ilObjMediaObject::_getDirectory($this->getId()); + if ($a_subdir != "") { + $dir.= "/" . $a_subdir; + } + ilUtil::makeDirParents($dir); + if ($a_mode == "rename") { + rename($tmp_name, $dir . "/" . $a_name); + } else { + ilUtil::moveUploadedFile($tmp_name, $a_name, $dir . "/" . $a_name, true, $a_mode); + } + self::renameExecutables($mob_dir); + include_once("./Services/MediaObjects/classes/class.ilMediaSvgSanitizer.php"); + ilMediaSvgSanitizer::sanitizeDir($mob_dir); // see #20339 + } + + /** + * Upload srt file + * + * @param + * @return + */ + public function uploadSrtFile($a_tmp_name, $a_language, $a_mode = "move_uploaded") + { + if (is_file($a_tmp_name) && $a_language != "") { + $this->uploadAdditionalFile("subtitle_" . $a_language . ".srt", $a_tmp_name, "srt", $a_mode); + return true; + } + return false; + } + + /** + * Get srt files + */ + public function getSrtFiles() + { + $srt_dir = ilObjMediaObject::_getDirectory($this->getId()) . "/srt"; + + if (!is_dir($srt_dir)) { + return array(); + } + + $items = ilUtil::getDir($srt_dir); + + $srt_files = array(); + foreach ($items as $i) { + if (!in_array($i["entry"], array(".", "..")) && $i["type"] == "file") { + $name = explode(".", $i["entry"]); + if ($name[1] == "srt" && substr($name[0], 0, 9) == "subtitle_") { + $srt_files[] = array("file" => $i["entry"], + "full_path" => "srt/" . $i["entry"], "language" => substr($name[0], 9, 2)); + } + } + } + + return $srt_files; + } + + /** + * Make thumbnail + */ + public function makeThumbnail( + $a_file, + $a_thumbname, + $a_format = "png", + $a_size = "80" + ) { + $m_dir = ilObjMediaObject::_getDirectory($this->getId()); + $t_dir = ilObjMediaObject::_getThumbnailDirectory($this->getId()); + self::_createThumbnailDirectory($this->getId()); + ilUtil::convertImage( + $m_dir . "/" . $a_file, + $t_dir . "/" . $a_thumbname, + $a_format, + $a_size + ); + } + + /** + * Get thumbnail path + * + * @param string $a_thumbname thumbnail file name + * @return string thumbnail path + */ + public static function getThumbnailPath($a_mob_id, $a_thumbname) + { + $t_dir = ilObjMediaObject::_getThumbnailDirectory($a_mob_id); + return $t_dir . "/" . $a_thumbname; + } + + + /** + * Remove additional file + */ + public function removeAdditionalFile($a_file) + { + $file = str_replace("..", "", $a_file); + $file = ilObjMediaObject::_getDirectory($this->getId()) . "/" . $file; + if (is_file($file)) { + unlink($file); + } + } + + + /** + * Get all media objects linked in map areas of this media object + */ + public function getLinkedMediaObjects($a_ignore = "") + { + $linked = array(); + + if (!is_array($a_ignore)) { + $a_ignore = array(); + } + + // get linked media objects (map areas) + $med_items = $this->getMediaItems(); + + foreach ($med_items as $med_item) { + $int_links = ilMapArea::_getIntLinks($med_item->getId()); + foreach ($int_links as $k => $int_link) { + if ($int_link["Type"] == "MediaObject") { + include_once("./Services/Link/classes/class.ilInternalLink.php"); + $l_id = ilInternalLink::_extractObjIdOfTarget($int_link["Target"]); + if (ilObject::_exists($l_id)) { + if (!in_array($l_id, $linked) && + !in_array($l_id, $a_ignore)) { + $linked[] = $l_id; + } + } + } + } + } + //var_dump($linked); + return $linked; + } + + /** + * Get restricted file types (this is for the input form, this list will be empty, if "allowed list" is empty) + */ + public static function getRestrictedFileTypes() + { + return array_filter(self::getAllowedFileTypes(), function ($v) { + return !in_array($v, self::getForbiddenFileTypes()); + }); + } + + /** + * Get forbidden file types + * + * @return array + */ + public static function getForbiddenFileTypes() + { + $mset = new ilSetting("mobs"); + if (trim($mset->get("black_list_file_types")) == "") { + return array(); + } + return array_map( + function ($v) { + return strtolower(trim($v)); + }, + explode(",", $mset->get("black_list_file_types")) + ); + } + + /** + * Get allowed file types + * + * @return array + */ + public static function getAllowedFileTypes() + { + $mset = new ilSetting("mobs"); + if (trim($mset->get("restricted_file_types")) == "") { + return array(); + } + return array_map( + function ($v) { + return strtolower(trim($v)); + }, + explode(",", $mset->get("restricted_file_types")) + ); + } + + /** + * Is type allowed + * + * @param string $a_type + * @return bool + */ + public static function isTypeAllowed($a_type) + { + if (in_array($a_type, self::getForbiddenFileTypes())) { + return false; + } + if (count(self::getAllowedFileTypes()) == 0 || in_array($a_type, self::getAllowedFileTypes())) { + return true; + } + return false; + } + + + /** + * Duplicate media object, return new media object + */ + public function duplicate() + { + $new_obj = new ilObjMediaObject(); + $new_obj->setTitle($this->getTitle()); + $new_obj->setDescription($this->getDescription()); + + // media items + foreach ($this->getMediaItems() as $key => $val) { + $new_obj->addMediaItem($val); + } + + $new_obj->create(false, true); + + // files + $new_obj->createDirectory(); + self::_createThumbnailDirectory($new_obj->getId()); + ilUtil::rCopy( + ilObjMediaObject::_getDirectory($this->getId()), + ilObjMediaObject::_getDirectory($new_obj->getId()) + ); + ilUtil::rCopy( + ilObjMediaObject::_getThumbnailDirectory($this->getId()), + ilObjMediaObject::_getThumbnailDirectory($new_obj->getId()) + ); + + // meta data + include_once("Services/MetaData/classes/class.ilMD.php"); + $md = new ilMD(0, $this->getId(), "mob"); + $new_md = $md->cloneMD(0, $new_obj->getId(), "mob"); + + return $new_obj; + } + + /** + * Upload video preview picture + * + * @param + * @return + */ + public function uploadVideoPreviewPic($a_prevpic) + { + // remove old one + if ($this->getVideoPreviewPic(true) != "") { + $this->removeAdditionalFile($this->getVideoPreviewPic(true)); + } + + $pi = pathinfo($a_prevpic["name"]); + $ext = $pi["extension"]; + if (in_array($ext, array("jpg", "jpeg", "png"))) { + $this->uploadAdditionalFile("mob_vpreview." . $ext, $a_prevpic["tmp_name"]); + } + } + + /** + * Upload video preview picture + * + * @param + * @return + */ + public function generatePreviewPic($a_width, $a_height) + { + $item = $this->getMediaItem("Standard"); + + if ($item->getLocationType() == "LocalFile" && + is_int(strpos($item->getFormat(), "image/"))) { + $dir = ilObjMediaObject::_getDirectory($this->getId()); + $file = $dir . "/" . + $item->getLocation(); + if (is_file($file)) { + if (ilUtil::isConvertVersionAtLeast("6.3.8-3")) { + ilUtil::execConvert(ilUtil::escapeShellArg($file) . "[0] -geometry " . $a_width . "x" . $a_height . "^ -gravity center -extent " . $a_width . "x" . $a_height . " PNG:" . $dir . "/mob_vpreview.png"); + } else { + ilUtil::convertImage($file, $dir . "/mob_vpreview.png", "PNG", $a_width . "x" . $a_height); + } + } + } + } + + /** + * Get video preview pic + * + * @param + * @return + */ + public function getVideoPreviewPic($a_filename_only = false) + { + $dir = ilObjMediaObject::_getDirectory($this->getId()); + $ppics = array("mob_vpreview.jpg", + "mob_vpreview.jpeg", + "mob_vpreview.png"); + foreach ($ppics as $p) { + if (is_file($dir . "/" . $p)) { + if ($a_filename_only) { + return $p; + } else { + return $dir . "/" . $p; + } + } + } + return ""; + } + + /** + * Fix filename of uploaded file + * + * @param string $a_name upload file name + * @return string fixed file name + */ + public static function fixFilename($a_name) + { + $a_name = ilUtil::getASCIIFilename($a_name); + + $rchars = array("`", "=", "$", "{", "}", "'", ";", " ", "(", ")"); + $a_name = str_replace($rchars, "_", $a_name); + $a_name = str_replace("__", "_", $a_name); + return $a_name; + } + + + /** + * Get directory for multi srt upload + * + * @param + * @return + */ + public function getMultiSrtUploadDir() + { + return ilObjMediaObject::_getDirectory($this->getId() . "/srt/tmp"); + } + + + /** + * Upload multi srt file + * + * @param array $a_file file info array + * @throws ilMediaObjectsException + */ + public function uploadMultipleSubtitleFile($a_file) + { + $lng = $this->lng; + $ilUser = $this->user; + + include_once("./Services/MediaObjects/exceptions/class.ilMediaObjectsException.php"); + if (!is_file($a_file["tmp_name"])) { + throw new ilMediaObjectsException($lng->txt("mob_file_could_not_be_uploaded")); + } + + $dir = $this->getMultiSrtUploadDir(); + ilUtil::delDir($dir, true); + ilUtil::makeDirParents($dir); + ilUtil::moveUploadedFile($a_file["tmp_name"], "multi_srt.zip", $dir . "/" . "multi_srt.zip"); + ilUtil::unzip($dir . "/multi_srt.zip", true); + } + + /** + * Clear multi feedback directory + */ + public function clearMultiSrtDirectory() + { + ilUtil::delDir($this->getMultiSrtUploadDir()); + } + + /** + * Get all srt files of srt multi upload + */ + public function getMultiSrtFiles() + { + $items = array(); + + include_once("./Services/MetaData/classes/class.ilMDLanguageItem.php"); + $lang_codes = ilMDLanguageItem::_getPossibleLanguageCodes(); + + $dir = $this->getMultiSrtUploadDir(); + $files = ilUtil::getDir($dir); + foreach ($files as $k => $i) { + // check directory + if ($i["type"] == "file" && !in_array($k, array(".", ".."))) { + if (pathinfo($k, PATHINFO_EXTENSION) == "srt") { + $lang = ""; + if (substr($k, strlen($k) - 7, 1) == "_") { + $lang = substr($k, strlen($k) - 6, 2); + if (!in_array($lang, $lang_codes)) { + $lang = ""; + } + } + $items[] = array("filename" => $k, "lang" => $lang); + } + } + } + return $items; + } + + /** + * Rename executables + * + * @param string + */ + public static function renameExecutables($a_dir) + { + ilUtil::renameExecutables($a_dir); + if (!self::isTypeAllowed("html")) { + ilUtil::rRenameSuffix($a_dir, "html", "sec"); // see #20187 + } + } } -?> diff --git a/Services/MediaObjects/classes/class.ilObjMediaObjectAccess.php b/Services/MediaObjects/classes/class.ilObjMediaObjectAccess.php index ca0c374296c0fea447dd0a953c3a678188309c2c..cda0bba555f81bf575620f90201094cb08aa1af5 100644 --- a/Services/MediaObjects/classes/class.ilObjMediaObjectAccess.php +++ b/Services/MediaObjects/classes/class.ilObjMediaObjectAccess.php @@ -8,388 +8,393 @@ require_once('./Services/MediaObjects/classes/class.ilObjMediaObject.php'); * @author Fabian Schmid * @version 1.0.0 */ -class ilObjMediaObjectAccess implements ilWACCheckingClass { - /** - * @var ilObjectDataCache - */ - protected $obj_data_cache; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilAccessHandler - */ - protected $access; - - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->obj_data_cache = $DIC["ilObjDataCache"]; - $this->user = $DIC->user(); - $this->access = $DIC->access(); - } - - - /** - * @param ilWACPath $ilWACPath - * - * @return bool - */ - public function canBeDelivered(ilWACPath $ilWACPath) { - preg_match("/.\\/data\\/.*\\/mm_([0-9]*)\\/.*/ui", $ilWACPath->getPath(), $matches); - $obj_id = $matches[1]; - - return $this->checkAccessMob($obj_id); - } - - - /** - * @param $obj_id - * - * @return bool - */ - protected function checkAccessMob($obj_id) { - foreach (ilObjMediaObject::lookupUsages($obj_id) as $usage) { - $oid = ilObjMediaObject::getParentObjectIdForUsage($usage, true); - - // for content snippets we must get their usages and check them - switch ($usage["type"]) { - case "auth:pg": - // Mobs on the Loginpage should always be delivered - return true; - case "mep:pg": - include_once("./Modules/MediaPool/classes/class.ilMediaPoolPage.php"); - $usages2 = ilMediaPoolPage::lookupUsages($usage["id"]); - foreach ($usages2 as $usage2) { - $oid2 = ilObjMediaObject::getParentObjectIdForUsage($usage2, true); - if ($this->checkAccessMobUsage($usage2, $oid2)) { - return true; - } - } - break; - - default: - if ($this->checkAccessMobUsage($usage, $oid)) { - return true; - } - break; - } - } - - return false; - } - - - /** - * @param $usage - * @param $oid - * - * @return bool - */ - protected function checkAccessMobUsage($usage, $oid) { - /** - * @var $ilObjDataCache ilObjectDataCache - */ - $ilObjDataCache = $this->obj_data_cache; - $ilUser = $this->user; - $user_id = $ilUser->getId(); - - switch ($usage['type']) { - case 'lm:pg': - if ($this->checkAccessObject($oid, 'lm')) { - return true; - } - break; - - case 'news': - // media objects in news (media casts) - include_once("./Modules/MediaCast/classes/class.ilObjMediaCastAccess.php"); - include_once("./Services/News/classes/class.ilNewsItem.php"); - if ($this->checkAccessObject($oid)) { - return true; - } elseif (ilObjMediaCastAccess::_lookupPublicFiles($oid) && ilNewsItem::_lookupVisibility($usage["id"]) == NEWS_PUBLIC) { - return true; - } - break; - - case 'frm~:html': - case 'exca~:html': - // $oid = userid - // foreach ($this->check_users as $user_id) { - if ($ilObjDataCache->lookupType($oid) == 'usr' && $oid == $user_id) { - return true; - } - // } - break; - - case 'frm~d:html': - $draft_id = $usage['id']; - - include_once 'Modules/Forum/classes/class.ilForumPostDraft.php'; - $oDraft = ilForumPostDraft::newInstanceByDraftId($draft_id); - if($user_id == $oDraft->getPostAuthorId()) - { - return true; - } - break; - case 'frm~h:html': - $history_id = $usage['id']; - include_once 'Modules/Forum/classes/class.ilForumDraftsHistory.php'; - include_once 'Modules/Forum/classes/class.ilForumPostDraft.php'; - - $oHistoryDraft = new ilForumDraftsHistory($history_id); - $oDraft = ilForumPostDraft::newInstanceByDraftId($oHistoryDraft->getDraftId()); - if($user_id == $oDraft->getPostAuthorId()) - { - return true; - } - break; - case 'qpl:pg': - case 'qpl:html': - // test questions - if ($this->checkAccessTestQuestion($oid, $usage['id'])) { - return true; - } - break; - - case 'gdf:pg': - // special check for glossary terms - if ($this->checkAccessGlossaryTerm($oid, $usage['id'])) { - return true; - } - break; - - case 'sahs:pg': - // check for scorm pages - if ($this->checkAccessObject($oid, 'sahs')) { - return true; - } - break; - - case 'prtf:pg': - // special check for portfolio pages - if ($this->checkAccessPortfolioPage($oid, $usage['id'])) { - return true; - } - break; - - case 'blp:pg': - // special check for blog pages - if ($this->checkAccessBlogPage($oid, $usage['id'])) { - return true; - } - break; - - case 'lobj:pg': - // special check for learning objective pages - if ($this->checkAccessLearningObjectivePage($oid, $usage['id'])) { - return true; - } - break; - - case 'impr:pg': - include_once 'Services/Imprint/classes/class.ilImprint.php'; - - return (ilImprint::isActive() || $this->checkAccessObject(SYSTEM_FOLDER_ID, 'adm')); - - case 'cstr:pg': - default: - // standard object check - if ($this->checkAccessObject($oid)) { - - return true; - } - break; - } - - return false; - } - - - /** - * Check access rights for an object by its object id - * - * @param int object id - * - * @return boolean access given (true/false) - */ - protected function checkAccessObject($obj_id, $obj_type = '') { - $ilAccess = $this->access; - $ilUser = $this->user; - $user_id = $ilUser->getId(); - - if (! $obj_type) { - $obj_type = ilObject::_lookupType($obj_id); - } - $ref_ids = ilObject::_getAllReferences($obj_id); - - foreach ($ref_ids as $ref_id) { - // foreach ($this->check_users as $user_id) { - if ($ilAccess->checkAccessOfUser($user_id, "read", "view", $ref_id, $obj_type, $obj_id)) { - return true; - } - // } - } - - return false; - } - - - /** - * Check access rights for a test question - * This checks also tests with random selection of questions - * - * @param int object id (question pool or test) - * @param int usage id (not yet used) - * - * @return boolean access given (true/false) - */ - protected function checkAccessTestQuestion($obj_id, $usage_id = 0) { - $ilAccess = $this->access; - - // give access if direct usage is readable - if ($this->checkAccessObject($obj_id)) { - return true; - } - - $obj_type = ilObject::_lookupType($obj_id); - if ($obj_type == 'qpl') { - // give access if question pool is used by readable test - // for random selection of questions - include_once('./Modules/Test/classes/class.ilObjTestAccess.php'); - $tests = ilObjTestAccess::_getRandomTestsForQuestionPool($obj_id); - foreach ($tests as $test_id) { - if ($this->checkAccessObject($test_id, 'tst')) { - return true; - } - } - } - - return false; - } - - - /** - * Check access rights for glossary terms - * This checks also learning modules linking the term - * - * @param int object id (glossary) - * @param int page id (definition) - * - * @return boolean access given (true/false) - */ - protected function checkAccessGlossaryTerm($obj_id, $page_id) { - // give access if glossary is readable - if ($this->checkAccessObject($obj_id)) { - return true; - } - - include_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); - include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - $term_id = ilGlossaryDefinition::_lookupTermId($page_id); - - include_once('./Services/Link/classes/class.ilInternalLink.php'); - $sources = ilInternalLink::_getSourcesOfTarget('git', $term_id, 0); - - if ($sources) { - foreach ($sources as $src) { - switch ($src['type']) { - // Give access if term is linked by a learning module with read access. - // The term including media is shown by the learning module presentation! - case 'lm:pg': - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - $src_obj_id = ilLMObject::_lookupContObjID($src['id']); - if ($this->checkAccessObject($src_obj_id, 'lm')) { - return true; - } - break; - - // Don't yet give access if the term is linked by another glossary - // The link will lead to the origin glossary which is already checked - /* - case 'gdf:pg': - $src_term_id = ilGlossaryDefinition::_lookupTermId($src['id']); - $src_obj_id = ilGlossaryTerm::_lookGlossaryID($src_term_id); - if ($this->checkAccessObject($src_obj_id, 'glo')) - { - return true; - } - break; - */ - } - } - } - } - - - /** - * Check access rights for portfolio pages - * - * @param int object id (glossary) - * @param int page id (definition) - * - * @return boolean access given (true/false) - */ - protected function checkAccessPortfolioPage($obj_id, $page_id) { - $ilUser = $this->user; - include_once "Modules/Portfolio/classes/class.ilPortfolioAccessHandler.php"; - $access_handler = new ilPortfolioAccessHandler(); - if ($access_handler->checkAccessOfUser($ilUser->getId(), "read", "view", $obj_id, "prtf")) { - return true; - } - - return false; - } - - - /** - * Check access rights for blog pages - * - * @param int object id (glossary) - * @param int page id (definition) - * - * @return boolean access given (true/false) - */ - protected function checkAccessBlogPage($obj_id) { - $ilUser = $this->user; - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - $tree = new ilWorkspaceTree(0); - $node_id = $tree->lookupNodeId($obj_id); - if (! $node_id) { - return $this->checkAccessObject($obj_id); - } else { - 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; - } - } - - return false; - } - - - /** - * @param $obj_id - * @param $page_id - * - * @return bool - */ - protected function checkAccessLearningObjectivePage($obj_id, $page_id) { - include_once "Modules/Course/classes/class.ilCourseObjective.php"; - $crs_obj_id = ilCourseObjective::_lookupContainerIdByObjectiveId($page_id); - - return $this->checkAccessObject($crs_obj_id, 'crs'); - } +class ilObjMediaObjectAccess implements ilWACCheckingClass +{ + /** + * @var ilObjectDataCache + */ + protected $obj_data_cache; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilAccessHandler + */ + protected $access; + + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->obj_data_cache = $DIC["ilObjDataCache"]; + $this->user = $DIC->user(); + $this->access = $DIC->access(); + } + + + /** + * @param ilWACPath $ilWACPath + * + * @return bool + */ + public function canBeDelivered(ilWACPath $ilWACPath) + { + preg_match("/.\\/data\\/.*\\/mm_([0-9]*)\\/.*/ui", $ilWACPath->getPath(), $matches); + $obj_id = $matches[1]; + + return $this->checkAccessMob($obj_id); + } + + + /** + * @param $obj_id + * + * @return bool + */ + protected function checkAccessMob($obj_id) + { + foreach (ilObjMediaObject::lookupUsages($obj_id) as $usage) { + $oid = ilObjMediaObject::getParentObjectIdForUsage($usage, true); + + // for content snippets we must get their usages and check them + switch ($usage["type"]) { + case "auth:pg": + // Mobs on the Loginpage should always be delivered + return true; + case "mep:pg": + include_once("./Modules/MediaPool/classes/class.ilMediaPoolPage.php"); + $usages2 = ilMediaPoolPage::lookupUsages($usage["id"]); + foreach ($usages2 as $usage2) { + $oid2 = ilObjMediaObject::getParentObjectIdForUsage($usage2, true); + if ($this->checkAccessMobUsage($usage2, $oid2)) { + return true; + } + } + break; + + default: + if ($this->checkAccessMobUsage($usage, $oid)) { + return true; + } + break; + } + } + + return false; + } + + + /** + * @param $usage + * @param $oid + * + * @return bool + */ + protected function checkAccessMobUsage($usage, $oid) + { + /** + * @var $ilObjDataCache ilObjectDataCache + */ + $ilObjDataCache = $this->obj_data_cache; + $ilUser = $this->user; + $user_id = $ilUser->getId(); + + switch ($usage['type']) { + case 'lm:pg': + if ($this->checkAccessObject($oid, 'lm')) { + return true; + } + break; + + case 'news': + // media objects in news (media casts) + include_once("./Modules/MediaCast/classes/class.ilObjMediaCastAccess.php"); + include_once("./Services/News/classes/class.ilNewsItem.php"); + if ($this->checkAccessObject($oid)) { + return true; + } elseif (ilObjMediaCastAccess::_lookupPublicFiles($oid) && ilNewsItem::_lookupVisibility($usage["id"]) == NEWS_PUBLIC) { + return true; + } + break; + + case 'frm~:html': + case 'exca~:html': + // $oid = userid + // foreach ($this->check_users as $user_id) { + if ($ilObjDataCache->lookupType($oid) == 'usr' && $oid == $user_id) { + return true; + } + // } + break; + + case 'frm~d:html': + $draft_id = $usage['id']; + + include_once 'Modules/Forum/classes/class.ilForumPostDraft.php'; + $oDraft = ilForumPostDraft::newInstanceByDraftId($draft_id); + if ($user_id == $oDraft->getPostAuthorId()) { + return true; + } + break; + case 'frm~h:html': + $history_id = $usage['id']; + include_once 'Modules/Forum/classes/class.ilForumDraftsHistory.php'; + include_once 'Modules/Forum/classes/class.ilForumPostDraft.php'; + + $oHistoryDraft = new ilForumDraftsHistory($history_id); + $oDraft = ilForumPostDraft::newInstanceByDraftId($oHistoryDraft->getDraftId()); + if ($user_id == $oDraft->getPostAuthorId()) { + return true; + } + break; + case 'qpl:pg': + case 'qpl:html': + // test questions + if ($this->checkAccessTestQuestion($oid, $usage['id'])) { + return true; + } + break; + + case 'gdf:pg': + // special check for glossary terms + if ($this->checkAccessGlossaryTerm($oid, $usage['id'])) { + return true; + } + break; + + case 'sahs:pg': + // check for scorm pages + if ($this->checkAccessObject($oid, 'sahs')) { + return true; + } + break; + + case 'prtf:pg': + // special check for portfolio pages + if ($this->checkAccessPortfolioPage($oid, $usage['id'])) { + return true; + } + break; + + case 'blp:pg': + // special check for blog pages + if ($this->checkAccessBlogPage($oid, $usage['id'])) { + return true; + } + break; + + case 'lobj:pg': + // special check for learning objective pages + if ($this->checkAccessLearningObjectivePage($oid, $usage['id'])) { + return true; + } + break; + + case 'impr:pg': + include_once 'Services/Imprint/classes/class.ilImprint.php'; + + return (ilImprint::isActive() || $this->checkAccessObject(SYSTEM_FOLDER_ID, 'adm')); + + case 'cstr:pg': + default: + // standard object check + if ($this->checkAccessObject($oid)) { + return true; + } + break; + } + + return false; + } + + + /** + * Check access rights for an object by its object id + * + * @param int object id + * + * @return boolean access given (true/false) + */ + protected function checkAccessObject($obj_id, $obj_type = '') + { + $ilAccess = $this->access; + $ilUser = $this->user; + $user_id = $ilUser->getId(); + + if (!$obj_type) { + $obj_type = ilObject::_lookupType($obj_id); + } + $ref_ids = ilObject::_getAllReferences($obj_id); + + foreach ($ref_ids as $ref_id) { + // foreach ($this->check_users as $user_id) { + if ($ilAccess->checkAccessOfUser($user_id, "read", "view", $ref_id, $obj_type, $obj_id)) { + return true; + } + // } + } + + return false; + } + + + /** + * Check access rights for a test question + * This checks also tests with random selection of questions + * + * @param int object id (question pool or test) + * @param int usage id (not yet used) + * + * @return boolean access given (true/false) + */ + protected function checkAccessTestQuestion($obj_id, $usage_id = 0) + { + $ilAccess = $this->access; + + // give access if direct usage is readable + if ($this->checkAccessObject($obj_id)) { + return true; + } + + $obj_type = ilObject::_lookupType($obj_id); + if ($obj_type == 'qpl') { + // give access if question pool is used by readable test + // for random selection of questions + include_once('./Modules/Test/classes/class.ilObjTestAccess.php'); + $tests = ilObjTestAccess::_getRandomTestsForQuestionPool($obj_id); + foreach ($tests as $test_id) { + if ($this->checkAccessObject($test_id, 'tst')) { + return true; + } + } + } + + return false; + } + + + /** + * Check access rights for glossary terms + * This checks also learning modules linking the term + * + * @param int object id (glossary) + * @param int page id (definition) + * + * @return boolean access given (true/false) + */ + protected function checkAccessGlossaryTerm($obj_id, $page_id) + { + // give access if glossary is readable + if ($this->checkAccessObject($obj_id)) { + return true; + } + + include_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); + include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); + $term_id = ilGlossaryDefinition::_lookupTermId($page_id); + + include_once('./Services/Link/classes/class.ilInternalLink.php'); + $sources = ilInternalLink::_getSourcesOfTarget('git', $term_id, 0); + + if ($sources) { + foreach ($sources as $src) { + switch ($src['type']) { + // Give access if term is linked by a learning module with read access. + // The term including media is shown by the learning module presentation! + case 'lm:pg': + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + $src_obj_id = ilLMObject::_lookupContObjID($src['id']); + if ($this->checkAccessObject($src_obj_id, 'lm')) { + return true; + } + break; + + // Don't yet give access if the term is linked by another glossary + // The link will lead to the origin glossary which is already checked + /* + case 'gdf:pg': + $src_term_id = ilGlossaryDefinition::_lookupTermId($src['id']); + $src_obj_id = ilGlossaryTerm::_lookGlossaryID($src_term_id); + if ($this->checkAccessObject($src_obj_id, 'glo')) + { + return true; + } + break; + */ + } + } + } + } + + + /** + * Check access rights for portfolio pages + * + * @param int object id (glossary) + * @param int page id (definition) + * + * @return boolean access given (true/false) + */ + protected function checkAccessPortfolioPage($obj_id, $page_id) + { + $ilUser = $this->user; + include_once "Modules/Portfolio/classes/class.ilPortfolioAccessHandler.php"; + $access_handler = new ilPortfolioAccessHandler(); + if ($access_handler->checkAccessOfUser($ilUser->getId(), "read", "view", $obj_id, "prtf")) { + return true; + } + + return false; + } + + + /** + * Check access rights for blog pages + * + * @param int object id (glossary) + * @param int page id (definition) + * + * @return boolean access given (true/false) + */ + protected function checkAccessBlogPage($obj_id) + { + $ilUser = $this->user; + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + $tree = new ilWorkspaceTree(0); + $node_id = $tree->lookupNodeId($obj_id); + if (!$node_id) { + return $this->checkAccessObject($obj_id); + } else { + 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; + } + } + + return false; + } + + + /** + * @param $obj_id + * @param $page_id + * + * @return bool + */ + protected function checkAccessLearningObjectivePage($obj_id, $page_id) + { + include_once "Modules/Course/classes/class.ilCourseObjective.php"; + $crs_obj_id = ilCourseObjective::_lookupContainerIdByObjectiveId($page_id); + + return $this->checkAccessObject($crs_obj_id, 'crs'); + } } - -?> diff --git a/Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php b/Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php index 44b399842ba3d9b01a0bc887d483c4c6d9f72ce2..0f60da51aa4de79096b954c9a252c25f8c2d527e 100755 --- a/Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php +++ b/Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php @@ -1,9 +1,9 @@ object, but the - // context may set another object (e.g. media pool for media objects) - /** - * @var int - */ - protected $adv_ref_id = null; - /** - * @var string - */ - protected $adv_type = null; - /** - * @var string - */ - protected $adv_subtype = null; - - - var $ctrl; - var $header; - var $target_script; - var $enabledmapareas = true; - - function __construct($a_data, $a_id = 0, $a_call_by_reference = false, $a_prepare_output = false) - { - global $DIC; - - $this->tpl = $DIC["tpl"]; - $this->access = $DIC->access(); - $this->error = $DIC["ilErr"]; - $this->help = $DIC["ilHelp"]; - $this->tabs = $DIC->tabs(); - $this->toolbar = $DIC->toolbar(); - $this->user = $DIC->user(); - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - - $this->ctrl = $ilCtrl; - parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); - $this->lng = $lng; - $this->back_title = ""; - $this->type = "mob"; - - $lng->loadLanguageModule("mob"); - } - - /** - * Set object, that defines the adv md records being used. Default is $this->object, but the - * context may set another object (e.g. media pool for media objects) - * - * @param string $a_val adv type - */ - function setAdvMdRecordObject($a_adv_ref_id, $a_adv_type, $a_adv_subtype = "-") - { - $this->adv_ref_id = $a_adv_ref_id; - $this->adv_type = $a_adv_type; - $this->adv_subtype = $a_adv_subtype; - } - - /** - * Get adv md record type - * - * @return array adv type - */ - function getAdvMdRecordObject() - { - if ($this->adv_type == null) - { - return [$this->ref_id, $this->obj_type, $this->sub_type]; - } - return [$this->adv_ref_id, $this->adv_type, $this->adv_subtype]; - } - - function setHeader($a_title = "") - { - $this->header = $a_title; - } - - function getHeader() - { - return $this->header; - } - - /** - * Set Enable map areas. - * - * @param boolean $a_enabledmapareas Enable map areas - */ - function setEnabledMapAreas($a_enabledmapareas) - { - $this->enabledmapareas = $a_enabledmapareas; - } - - /** - * Get Enable map areas. - * - * @return boolean Enable map areas - */ - function getEnabledMapAreas() - { - return $this->enabledmapareas; - } - - /** - * Set width preset - * - * @param int width preset - */ - function setWidthPreset($a_val) - { - $this->width_preset = $a_val; - } - - /** - * Get width preset - * - * @return int width preset - */ - function getWidthPreset() - { - return $this->width_preset; - } - - /** - * Set height preset - * - * @param int height preset - */ - function setHeightPreset($a_val) - { - $this->height_preset = $a_val; - } - - /** - * Get height preset - * - * @return int height preset - */ - function getHeightPreset() - { - return $this->height_preset; - } - - /** - * Get form - * - * @return object form gui class - */ - function getForm() - { - return $this->form_gui; - } - - function assignObject() - { - if ($this->id != 0) - { - $this->object = new ilObjMediaObject($this->id); - } - } - - function returnToContextObject() - { - $this->ctrl->returnToParent($this); - } - - - /** - * Execute current command - * @return bool|mixed - * @throws ilCtrlException - */ - function executeCommand() - { - $tpl = $this->tpl; - $ilAccess = $this->access; - $ilErr = $this->error; - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - switch($next_class) - { - case 'ilobjectmetadatagui': - include_once 'Services/Object/classes/class.ilObjectMetaDataGUI.php'; - $md_gui = new ilObjectMetaDataGUI(null, $this->object->getType(), $this->object->getId()); - // object is subtype, so we have to do it ourselves - $md_gui->addMDObserver($this->object, 'MDUpdateListener', 'General'); - - // set adv metadata record dobject - if ($this->adv_type != "") - { - $md_gui->setAdvMdRecordObject($this->adv_ref_id, $this->adv_type, $this->adv_subtype); - } - - $this->ctrl->forwardCommand($md_gui); - break; - - case "ilimagemapeditorgui": - require_once("./Services/MediaObjects/classes/class.ilImageMapEditorGUI.php"); - $image_map_edit = new ilImageMapEditorGUI($this->object); - $ret = $this->ctrl->forwardCommand($image_map_edit); - $tpl->setContent($ret); - $this->checkFixSize(); - break; - - case "ilfilesystemgui": - include_once("./Services/FileSystem/classes/class.ilFileSystemGUI.php"); - $fs_gui = new ilFileSystemGUI(ilUtil::getWebspaceDir()."/mobs/mm_".$this->object->getId()); - $fs_gui->setAllowedSuffixes(ilObjMediaObject::getRestrictedFileTypes()); - $fs_gui->setForbiddenSuffixes(ilObjMediaObject::getForbiddenFileTypes()); - $fs_gui->activateLabels(true, $this->lng->txt("cont_purpose")); - $fs_gui->setTableId("mobfs".$this->object->getId()); - $fs_gui->labelFile($this->object->getMediaItem("Standard")->getLocation(), - $this->lng->txt("cont_std_view")); - if($this->object->hasFullscreenItem()) - { - $fs_gui->labelFile($this->object->getMediaItem("Fullscreen")->getLocation(), - $this->lng->txt("cont_fullscreen")); - } - $fs_gui->addCommand($this, "assignStandardObject", $this->lng->txt("cont_assign_std")); - $fs_gui->addCommand($this, "assignFullscreenObject", $this->lng->txt("cont_assign_full")); - ilObjMediaObject::renameExecutables(ilObjMediaObject::_getDirectory($this->object->getId())); // see #20187 - $ret = $this->ctrl->forwardCommand($fs_gui); - ilObjMediaObject::renameExecutables(ilObjMediaObject::_getDirectory($this->object->getId())); // see #20187 - include_once("./Services/MediaObjects/classes/class.ilMediaSvgSanitizer.php"); - ilMediaSvgSanitizer::sanitizeDir(ilObjMediaObject::_getDirectory($this->object->getId())); // see #20339 - break; - - - default: - if (isset($_POST["editImagemapForward"]) || - isset($_POST["editImagemapForward_x"]) || - isset($_POST["editImagemapForward_y"])) - { - $cmd = "editImagemapForward"; - } - $cmd.= "Object"; - $ret = $this->$cmd(); - break; - } - - return $ret; - } - - /** - * set title for back tab - */ - function setBackTitle($a_title) - { - $this->back_title = $a_title; - } - - /** - * create new media object form - */ - function createObject() - { - $tpl = $this->tpl; - $ilHelp = $this->help; - - $ilHelp->setScreenId("create"); - $this->initForm(); - $tpl->setContent($this->form_gui->getHTML()); - } - - /** - * Init creation form - */ - function initForm($a_mode = "create") - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - - if ($a_mode == "edit") - { - $std_item = $this->object->getMediaItem("Standard"); - } - - $this->form_gui = new ilPropertyFormGUI(); - - // standard view resource - $title = new ilTextInputGUI($lng->txt("title"), "standard_title"); - $title->setSize(40); - $title->setMaxLength(120); - $this->form_gui->addItem($title); - $radio_prop = new ilRadioGroupInputGUI($lng->txt("cont_resource"), "standard_type"); - $op1 = new ilRadioOption($lng->txt("cont_file"), "File"); - $up = new ilFileInputGUI("", "standard_file"); - $up->setSuffixes(ilObjMediaObject::getRestrictedFileTypes()); - $up->setForbiddenSuffixes(ilObjMediaObject::getForbiddenFileTypes()); - $up->setInfo(""); - if ($a_mode == "create" || $std_item->getLocationType() != "LocalFile") - { - $up->setRequired(true); - } - $op1->addSubItem($up); - $radio_prop->addOption($op1); - $op2 = new ilRadioOption($lng->txt("url"), "Reference"); - $ref = new ilTextInputGUI("", "standard_reference"); - $ref->setInfo($lng->txt("cont_ref_helptext")); - $ref->setRequired(true); - $op2->addSubItem($ref); - $radio_prop->addOption($op2); - $radio_prop->setValue("File"); - $this->form_gui->addItem($radio_prop); - - // standard format - if ($a_mode == "edit") - { - $format = new ilNonEditableValueGUI($lng->txt("cont_format"), "standard_format"); - $format->setValue($std_item->getFormat()); - $this->form_gui->addItem($format); - } - - // standard size - $radio_size = new ilRadioGroupInputGUI($lng->txt("size"), "standard_size"); - if ($a_mode == "edit") - { - if ($orig_size = $std_item->getOriginalSize()) - { - $add_str = " (".$orig_size["width"]." x ".$orig_size["height"].")"; - } - $op1 = new ilRadioOption($lng->txt("cont_resource_size").$add_str, "original"); - $op1->setInfo($lng->txt("cont_resource_size_info")); - $op2 = new ilRadioOption($lng->txt("cont_custom_size"), "selected"); - } - else - { - $op1 = new ilRadioOption($lng->txt("cont_orig_size"), "original"); - $op1->setInfo($lng->txt("cont_resource_size_info")); - $op2 = new ilRadioOption($lng->txt("cont_adjust_size"), "selected"); - } - $radio_size->addOption($op1); - - // width height - include_once("./Services/MediaObjects/classes/class.ilWidthHeightInputGUI.php"); - $width_height = new ilWidthHeightInputGUI($lng->txt("cont_width"). - " / ".$lng->txt("cont_height"), "standard_width_height"); - $width_height->setConstrainProportions(true); - $op2->addSubItem($width_height); - - // resize image - if ($a_mode == "edit") - { - $std_item = $this->object->getMediaItem("Standard"); - if (is_int(strpos($std_item->getFormat(), "image")) - && $std_item->getLocationType() == "LocalFile") - { - $resize = new ilCheckboxInputGUI($lng->txt("cont_resize_img") - , "standard_resize"); - $op2->addSubItem($resize); - } - } - - $radio_size->setValue("original"); - if ($a_mode == "create" && ($this->getHeightPreset() > 0 || $this->getWidthPreset() > 0)) - { - $radio_size->setValue("selected"); - $width_height->setWidth($this->getWidthPreset()); - $width_height->setHeight($this->getHeightPreset()); - } - $radio_size->addOption($op2); - $this->form_gui->addItem($radio_size); - - // standard caption - $caption = new ilTextAreaInputGUI($lng->txt("cont_caption"), "standard_caption"); - $caption->setCols(30); - $caption->setRows(2); - $this->form_gui->addItem($caption); - - /*$caption = new ilTextInputGUI($lng->txt("cont_caption"), "standard_caption"); - $caption->setSize(40); - $caption->setMaxLength(200); - $this->form_gui->addItem($caption);*/ - - // text representation (alt text) - if ($a_mode == "edit" && is_int(strpos($std_item->getFormat(), "image"))) - { - $ta = new ilTextAreaInputGUI($lng->txt("text_repr"), "text_representation"); - $ta->setCols(30); - $ta->setRows(2); - $ta->setInfo($lng->txt("text_repr_info")); - $this->form_gui->addItem($ta); - } - - // standard parameters - if ($a_mode == "edit" && - !in_array($std_item->getFormat(), ilObjMediaObject::_getSimpleMimeTypes())) - { - if (ilObjMediaObject::_useAutoStartParameterOnly($std_item->getLocation(), - $std_item->getFormat())) // autostart - { - $auto = new ilCheckboxInputGUI($lng->txt("cont_autostart"), "standard_autostart"); - $this->form_gui->addItem($auto); - } - else // parameters - { - $par = new ilTextAreaInputGUI($lng->txt("cont_parameter"), "standard_parameters"); - $par->setRows(5); - $par->setCols(50); - $this->form_gui->addItem($par); - } - } - - if ($a_mode == "edit") - { - $full_item = $this->object->getMediaItem("Fullscreen"); - } - - // fullscreen view resource - $fs_sec = new ilFormSectionHeaderGUI(); - $fs_sec->setTitle($lng->txt("cont_fullscreen")); - $this->form_gui->addItem($fs_sec); - - $radio_prop2 = new ilRadioGroupInputGUI($lng->txt("cont_resource"), "full_type"); - $op1 = new ilRadioOption($lng->txt("cont_none"), "None"); - $radio_prop2->addOption($op1); - $op4 = new ilRadioOption($lng->txt("cont_use_same_resource_as_above"), "Standard"); - $radio_prop2->addOption($op4); - $op2 = new ilRadioOption($lng->txt("cont_file"), "File"); - $up = new ilFileInputGUI("", "full_file"); - $up->setSuffixes(ilObjMediaObject::getRestrictedFileTypes()); - $up->setForbiddenSuffixes(ilObjMediaObject::getForbiddenFileTypes()); - $up->setInfo(""); - if ($a_mode == "create" || !$full_item || $full_item->getLocationType() != "LocalFile") - { - $up->setRequired(true); - } - $op2->addSubItem($up); - $radio_prop2->addOption($op2); - $op3 = new ilRadioOption($lng->txt("url"), "Reference"); - $ref = new ilTextInputGUI("", "full_reference"); - $ref->setInfo($lng->txt("cont_ref_helptext")); - $ref->setRequired(true); - $op3->addSubItem($ref); - $radio_prop2->addOption($op3); - $radio_prop2->setValue("None"); - $this->form_gui->addItem($radio_prop2); - - // fullscreen format - if ($a_mode == "edit") - { - if ($this->object->hasFullscreenItem()) - { - $format = new ilNonEditableValueGUI($lng->txt("cont_format"), "full_format"); - $format->setValue($full_item->getFormat()); - $this->form_gui->addItem($format); - } - } - - // fullscreen size - $radio_size = new ilRadioGroupInputGUI($lng->txt("size"), "full_size"); - if ($a_mode == "edit") - { - $add_str = ""; - if ($this->object->hasFullscreenItem() && ($orig_size = $full_item->getOriginalSize())) - { - $add_str = " (".$orig_size["width"]." x ".$orig_size["height"].")"; - } - $op1 = new ilRadioOption($lng->txt("cont_resource_size").$add_str, "original"); - $op1->setInfo($lng->txt("cont_resource_size_info")); - $op2 = new ilRadioOption($lng->txt("cont_custom_size"), "selected"); - } - else - { - $op1 = new ilRadioOption($lng->txt("cont_orig_size"), "original"); - $op1->setInfo($lng->txt("cont_resource_size_info")); - $op2 = new ilRadioOption($lng->txt("cont_adjust_size"), "selected"); - } - $radio_size->addOption($op1); - - // width/height - $width_height = new ilWidthHeightInputGUI($lng->txt("cont_width"). - " / ".$lng->txt("cont_height"), "full_width_height"); - $width_height->setConstrainProportions(true); - $op2->addSubItem($width_height); - - // resize image - if ($a_mode == "edit") - { - $full_item = $this->object->getMediaItem("Fullscreen"); - if ($this->object->hasFullscreenItem() && - is_int(strpos($full_item->getFormat(), "image")) && - $full_item->getLocationType() == "LocalFile") - { - $resize = new ilCheckboxInputGUI($lng->txt("cont_resize_img"), - "full_resize"); - $op2->addSubItem($resize); - } - } - - $radio_size->setValue("original"); - $radio_size->addOption($op2); - $this->form_gui->addItem($radio_size); - - // fullscreen caption - $caption = new ilTextAreaInputGUI($lng->txt("cont_caption"), "full_caption"); - $caption->setCols(30); - $caption->setRows(2); - $this->form_gui->addItem($caption); - - /*$caption = new ilTextInputGUI($lng->txt("cont_caption"), "full_caption"); - $caption->setSize(40); - $caption->setMaxLength(200); - $this->form_gui->addItem($caption);*/ - - // text representation (alt text) - if ($a_mode == "edit" && $this->object->hasFullscreenItem() && is_int(strpos($std_item->getFormat(), "image"))) - { - $ta = new ilTextAreaInputGUI($lng->txt("text_repr"), "full_text_representation"); - $ta->setCols(30); - $ta->setRows(2); - $ta->setInfo($lng->txt("text_repr_info")); - $this->form_gui->addItem($ta); - } - - - // fullscreen parameters - if ($a_mode == "edit" && $this->object->hasFullscreenItem() && - !in_array($full_item->getFormat(), ilObjMediaObject::_getSimpleMimeTypes())) - { - if (ilObjMediaObject::_useAutoStartParameterOnly($full_item->getLocation(), - $full_item->getFormat())) - { - $auto = new ilCheckboxInputGUI($lng->txt("cont_autostart"), "full_autostart"); - $this->form_gui->addItem($auto); - } - else - { - $par = new ilTextAreaInputGUI($lng->txt("cont_parameter"), "full_parameters"); - $par->setRows(5); - $par->setCols(50); - $this->form_gui->addItem($par); - } - } - - $this->form_gui->setTitle($lng->txt("cont_insert_mob")); - if ($a_mode == "edit") - { - $this->form_gui->addCommandButton("saveProperties", $lng->txt("save")); - } - else - { - $this->form_gui->addCommandButton("save", $lng->txt("save")); - $this->form_gui->addCommandButton("cancel", $lng->txt("cancel")); - } - $this->form_gui->setFormAction($ilCtrl->getFormAction($this)); - - } - - /** - * Check fix size - * - * @param - * @return - */ - protected function checkFixSize() - { - $std_item = $this->object->getMediaItem("Standard"); - if ($std_item->getWidth() == "" || $std_item->getHeight() == "") - { - ilUtil::sendFailure($this->lng->txt("mob_no_fixed_size_map_editing")); - } - } - - - /** - * Get values for form - * - */ - public function getValues() - { - $values = array(); - - $values["standard_title"] = $this->object->getTitle(); - - $std_item = $this->object->getMediaItem("Standard"); - if ($std_item->getLocationType() == "LocalFile") - { - $values["standard_type"] = "File"; - $values["standard_file"] = $std_item->getLocation(); - } - else - { - $values["standard_type"] = "Reference"; - $values["standard_reference"] = $std_item->getLocation(); - } - $values["standard_format"] = $std_item->getFormat(); - $values["standard_width_height"]["width"] = $std_item->getWidth(); - $values["standard_width_height"]["height"] = $std_item->getHeight(); - $values["standard_width_height"]["constr_prop"] = true; - - $values["standard_size"] = "selected"; - - $orig_size = $std_item->getOriginalSize(); - if ($std_item->getWidth() == "" && $std_item->getHeight() == "") - { - $values["standard_size"] = "original"; - $values["standard_width_height"]["width"] = $orig_size["width"]; - $values["standard_width_height"]["height"] = $orig_size["height"]; - } - - $values["standard_caption"] = $std_item->getCaption(); - $values["text_representation"] = $std_item->getTextRepresentation(); - if (ilObjMediaObject::_useAutoStartParameterOnly($std_item->getLocation(), - $std_item->getFormat())) - { - $par = $std_item->getParameters(); - if ($par["autostart"]) - { - $values["standard_autostart"] = true; - } - } - else - { - $values["standard_parameters"] = $std_item->getParameterString(); - } - - $values["full_type"] = "None"; - $values["full_size"] = "original"; - if ($this->object->hasFullScreenItem()) - { - $full_item = $this->object->getMediaItem("Fullscreen"); - if ($full_item->getLocationType() == "LocalFile") - { - $values["full_type"] = "File"; - $values["full_file"] = $full_item->getLocation(); - } - else - { - $values["full_type"] = "Reference"; - $values["full_reference"] = $full_item->getLocation(); - } - $values["full_format"] = $full_item->getFormat(); - $values["full_width_height"]["width"] = $full_item->getWidth(); - $values["full_width_height"]["height"] = $full_item->getHeight(); - $values["full_width_height"]["constr_prop"] = true; - - $values["full_size"] = "selected"; - - $orig_size = $full_item->getOriginalSize(); - if ($full_item->getWidth() == "" && - $full_item->getHeight() == "") - { - $values["full_size"] = "original"; - $values["full_width_height"]["width"] = $orig_size["width"]; - $values["full_width_height"]["height"] = $orig_size["height"]; - } - $values["full_caption"] = $full_item->getCaption(); - if (ilObjMediaObject::_useAutoStartParameterOnly($full_item->getLocation(), - $full_item->getFormat())) - { - $par = $full_item->getParameters(); - if ($par["autostart"]) - { - $values["full_autostart"] = true; - } - } - else - { - $values["full_parameters"] = $full_item->getParameterString(); - } - $values["full_text_representation"] = $full_item->getTextRepresentation(); - } - - $this->form_gui->setValuesByArray($values); - } - - /** - * create new media object in dom and update page in db - */ - function saveObject() - { - $tpl = $this->tpl; - $lng = $this->lng; - - $this->initForm(); - if ($this->form_gui->checkInput()) - { - $this->object = new ilObjMediaObject(); - ilObjMediaObjectGUI::setObjectPerCreationForm($this->object); - ilUtil::sendSuccess($lng->txt("saved_media_object"), true); - return $this->object; - } - else - { - $this->form_gui->setValuesByPost(); - $tpl->setContent($this->form_gui->getHTML()); - return false; - } - } - - /** - * chechInputForm - * - * @param - * @return - */ - function checkFormInput() - { - if (!$this->form_gui->checkInput()) - { - $this->form_gui->setValuesByPost(); - return false; - } - return true; - } - - - /** - * Set media object values from creation form - */ - static function setObjectPerCreationForm($a_mob) - { - // determinte title and format - if (trim($_POST["standard_title"]) != "") - { - $title = trim($_POST["standard_title"]); - } - else - { - if ($_POST["standard_type"] == "File") - { - $title = $_FILES['standard_file']['name']; - } - else - { - $title = ilUtil::stripSlashes($_POST["standard_reference"]); - } - } - - $a_mob->setTitle($title); - $a_mob->setDescription(""); - $a_mob->create(); - - // determine and create mob directory, move uploaded file to directory - //$mob_dir = ilUtil::getWebspaceDir()."/mobs/mm_".$a_mob->getId(); - $a_mob->createDirectory(); - $mob_dir = ilObjMediaObject::_getDirectory($a_mob->getId()); - - $media_item = new ilMediaItem(); - $a_mob->addMediaItem($media_item); - $media_item->setPurpose("Standard"); - - if ($_POST["standard_type"] == "File") - { - $file_name = ilObjMediaObject::fixFilename($_FILES['standard_file']['name']); - $file = $mob_dir."/".$file_name; - ilUtil::moveUploadedFile($_FILES['standard_file']['tmp_name'], - $file_name, $file); - - // get mime type - $format = ilObjMediaObject::getMimeType($file); - $location = $file_name; - - // resize standard images - if ($_POST["standard_size"] != "original" && - is_int(strpos($format, "image"))) - { - $location = ilObjMediaObject::_resizeImage($file, (int) $_POST["standard_width_height"]["width"], - (int) $_POST["standard_width_height"]["height"], (boolean) $_POST["standard_width_height"]["contr_prop"]); - } - - // set real meta and object data - $media_item->setFormat($format); - $media_item->setLocation($location); - $media_item->setLocationType("LocalFile"); - } - else // standard type: reference - { - $format = ilObjMediaObject::getMimeType(ilUtil::stripSlashes($_POST["standard_reference"]), true); - $media_item->setFormat($format); - $media_item->setLocation(ilUtil::secureLink(ilUtil::stripSlashes($_POST["standard_reference"]))); - $media_item->setLocationType("Reference"); - } - $a_mob->setDescription($format); - - // determine width and height of known image types - $wh = ilObjMediaObject::_determineWidthHeight($format, - $_POST["standard_type"], $mob_dir."/".$location, $media_item->getLocation(), - $_POST["standard_width_height"]["constr_prop"], ($_POST["standard_size"] == "original"), - $_POST["standard_width_height"]["width"], $_POST["standard_width_height"]["height"]); - $media_item->setWidth($wh["width"]); - $media_item->setHeight($wh["height"]); - if ($wh["info"] != "") - { - ilUtil::sendInfo($wh["info"], true); - } - - if ($_POST["standard_caption"] != "") - { - $media_item->setCaption(ilUtil::stripSlashes($_POST["standard_caption"])); - } - - - $media_item->setHAlign("Left"); - - // fullscreen view - if ($_POST["full_type"] != "None") - { - $media_item2 = new ilMediaItem(); - $a_mob->addMediaItem($media_item2); - $media_item2->setPurpose("Fullscreen"); - - // move file / set format and location - if ($_POST["full_type"] == "File") - { - $format = $location = ""; - if ($_FILES['full_file']['name'] != "") - { - $full_file_name = ilObjMediaObject::fixFilename($_FILES['full_file']['name']); - $file = $mob_dir."/".$full_file_name; - ilUtil::moveUploadedFile($_FILES['full_file']['tmp_name'], - $full_file_name, $file); - $format = ilObjMediaObject::getMimeType($file); - $location = $full_file_name; - } - } - else if ($_POST["full_type"] == "Standard" && $_POST["standard_type"] == "File") - { - $location = $file_name; - } - - // resize file - if ($_POST["full_type"] == "File" || - ($_POST["full_type"] == "Standard" && $_POST["standard_type"] == "File")) - { - if (($_POST["full_size"] != "original" && - is_int(strpos($format, "image"))) - ) - { - $location = ilObjMediaObject::_resizeImage($file, (int) $_POST["full_width_height"]["width"], - (int) $_POST["full_width_height"]["height"], (boolean) $_POST["full_width_height"]["constr_prop"]); - } - - $media_item2->setFormat($format); - $media_item2->setLocation($location); - $media_item2->setLocationType("LocalFile"); - $type = "File"; - } - - if ($_POST["full_type"] == "Reference") - { - $format = $location = ""; - if ($_POST["full_reference"] != "") - { - $format = ilObjMediaObject::getMimeType($_POST["full_reference"], true); - $location = ilUtil::stripSlashes($_POST["full_reference"]); - } - } - - if ($_POST["full_type"] == "Reference" || - ($_POST["full_type"] == "Standard" && $_POST["standard_type"] == "Reference")) - { - $media_item2->setFormat($format); - $media_item2->setLocation($location); - $media_item2->setLocationType("Reference"); - $type = "Reference"; - } - - // determine width and height of known image types - $wh = ilObjMediaObject::_determineWidthHeight($format, - $type, $mob_dir."/".$location, $media_item2->getLocation(), - $_POST["full_width_height"]["constr_prop"], ($_POST["full_size"] == "original"), - $_POST["full_width_height"]["width"], $_POST["full_width_height"]["height"]); - - $media_item2->setWidth($wh["width"]); - $media_item2->setHeight($wh["height"]); - - if ($_POST["full_caption"] != "") - { - $media_item2->setCaption(ilUtil::stripSlashes($_POST["full_caption"])); - } - - } - - ilObjMediaObject::renameExecutables($mob_dir); - include_once("./Services/MediaObjects/classes/class.ilMediaSvgSanitizer.php"); - ilMediaSvgSanitizer::sanitizeDir($mob_dir); // see #20339 - $a_mob->update(); - } - - - /** - * Cancel saving - */ - function cancelObject() - { - $this->ctrl->returnToParent($this); - } - - /** - * edit media object properties - */ - function editObject() - { - $tpl = $this->tpl; - - $this->setPropertiesSubTabs("general"); - - $this->initForm("edit"); - $this->getValues(); - $tpl->setContent($this->form_gui->getHTML()); - } - - - /** - * resize images to specified size - */ - function resizeImagesObject() - { - // directory - $mob_dir = ilObjMediaObject::_getDirectory($this->object->getId()); - - // standard item - $std_item = $this->object->getMediaItem("Standard"); - if ($std_item->getLocationType() == "LocalFile" && - is_int(strpos($std_item->getFormat(), "image")) - ) - { - $file = $mob_dir."/".$std_item->getLocation(); - $location = ilObjMediaObject::_resizeImage($file, $std_item->getWidth(), - $std_item->getHeight()); - $std_item->setLocation($location); - $std_item->update(); - } - - // fullscreen item - if($this->object->hasFullScreenItem()) - { - $full_item = $this->object->getMediaItem("Fullscreen"); - if ($full_item->getLocationType() == "LocalFile" && - is_int(strpos($full_item->getFormat(), "image")) - ) - { - $file = $mob_dir."/".$full_item->getLocation(); - $location = ilObjMediaObject::_resizeImage($file, $full_item->getWidth(), - $full_item->getHeight()); - $full_item->setLocation($location); - $full_item->update(); - } - } - - $this->ctrl->redirect($this, "edit"); - } - - - /** - * set original size of standard file - */ - function getStandardSizeObject() - { - $std_item = $this->object->getMediaItem("Standard"); - $mob_dir = ilObjMediaObject::_getDirectory($this->object->getId()); - - if ($std_item->getLocationType() == "LocalFile") - { - $file = $mob_dir."/".$std_item->getLocation(); - - include_once("./Services/MediaObjects/classes/class.ilMediaImageUtil.php"); - $size = ilMediaImageUtil::getImageSize($file); - - $std_item->setWidth($size[0]); - $std_item->setHeight($size[1]); - $this->object->update(); - } - $this->ctrl->redirect($this, "edit"); - } - - - /** - * set original size of fullscreen file - */ - function getFullscreenSizeObject() - { - $full_item = $this->object->getMediaItem("Fullscreen"); - $mob_dir = ilObjMediaObject::_getDirectory($this->object->getId()); - - if ($full_item->getLocationType() == "LocalFile") - { - $file = $mob_dir."/".$full_item->getLocation(); - include_once("./Services/MediaObjects/classes/class.ilMediaImageUtil.php"); - $size = ilMediaImageUtil::getImageSize($file); - $full_item->setWidth($size[0]); - $full_item->setHeight($size[1]); - $this->object->update(); - } - $this->ctrl->redirect($this, "edit"); - } - - /** - * save properties in db and return to page edit screen - */ - function savePropertiesObject() - { - $lng = $this->lng; - $tpl = $this->tpl; - - $this->initForm("edit"); - if ($this->form_gui->checkInput()) - { - $title = trim($_POST["standard_title"]); - $this->object->setTitle($title); - - $std_item = $this->object->getMediaItem("Standard"); - $location = $std_item->getLocation(); - $format = $std_item->getFormat(); - if ($_POST["standard_type"] == "Reference") - { - $format = ilObjMediaObject::getMimeType(ilUtil::stripSlashes($_POST["standard_reference"]), true); - $std_item->setFormat($format); - $std_item->setLocation(ilUtil::secureLink(ilUtil::stripSlashes($_POST["standard_reference"]))); - $std_item->setLocationType("Reference"); - } - $mob_dir = ilObjMediaObject::_getDirectory($this->object->getId()); - if ($_POST["standard_type"] == "File") - { - $resize = false; - if ($_FILES['standard_file']['name'] != "") - { - $file_name = ilObjMediaObject::fixFilename($_FILES['standard_file']['name']); - $file = $mob_dir."/".$file_name; - ilUtil::moveUploadedFile($_FILES['standard_file']['tmp_name'], - $file_name, $file); - - // get mime type - $format = ilObjMediaObject::getMimeType($file); - $location = $file_name; - - $resize = true; - } - else if ($_POST["standard_resize"]) - { - $file = $mob_dir."/".$location; - $resize = true; - } - - // resize - if ($resize) - { - if ($_POST["standard_size"] != "original" && - is_int(strpos($format, "image"))) - { - $location = ilObjMediaObject::_resizeImage($file, (int) $_POST["standard_width_height"]["width"], - (int) $_POST["standard_width_height"]["height"], (boolean) $_POST["standard_width_height"]["contr_prop"]); - } - $std_item->setFormat($format); - $std_item->setLocation($location); - } - - $std_item->setLocationType("LocalFile"); - } - $this->object->setDescription($format); - // determine width and height of known image types - $wh = ilObjMediaObject::_determineWidthHeight($format, - $_POST["standard_type"], $mob_dir."/".$location, $std_item->getLocation(), - $_POST["standard_width_height"]["constr_prop"], ($_POST["standard_size"] == "original"), - $_POST["standard_width_height"]["width"], $_POST["standard_width_height"]["height"]); - if ($wh["info"] != "") - { - ilUtil::sendInfo($wh["info"], true); - } - $std_item->setWidth($wh["width"]); - $std_item->setHeight($wh["height"]); - - // set caption - $std_item->setCaption(ilUtil::stripSlashes($_POST["standard_caption"])); - - // text representation - $std_item->setTextRepresentation(ilUtil::stripSlashes($_POST["text_representation"])); - - // set parameters - if (!in_array($std_item->getFormat(), ilObjMediaObject::_getSimpleMimeTypes())) - { - if (ilObjMediaObject::_useAutoStartParameterOnly($std_item->getLocation(), - $std_item->getFormat())) - { - if ($_POST["standard_autostart"]) // save only autostart flag - { - $std_item->setParameters('autostart="true"'); - } - else - { - $std_item->setParameters(""); - } - } - else - { - $std_item->setParameters(ilUtil::stripSlashes(utf8_decode($_POST["standard_parameters"]))); - } - } - - // "None" selected - if ($_POST["full_type"] == "None") - { - if ($this->object->hasFullscreenItem()) // delete existing - { - $this->object->removeMediaItem("Fullscreen"); - } - } - else // Not "None" -> we need one - { - if ($this->object->hasFullscreenItem()) // take existing one - { - $full_item = $this->object->getMediaItem("Fullscreen"); - } - else // create one - { - $full_item = new ilMediaItem(); - $this->object->addMediaItem($full_item); - $full_item->setPurpose("Fullscreen"); - } - $location = $full_item->getLocation(); - $format = $full_item->getFormat(); - if ($_POST["full_type"] == "Reference") - { - $format = ilObjMediaObject::getMimeType(ilUtil::stripSlashes($_POST["full_reference"]), true); - $full_item->setFormat($format); - $full_item->setLocationType("Reference"); - $location = ilUtil::stripSlashes($_POST["full_reference"]); - $type = "Reference"; - } - $mob_dir = ilObjMediaObject::_getDirectory($this->object->getId()); - if ($_POST["full_type"] == "File") - { - $resize = false; - if ($_FILES['full_file']['name'] != "") - { - $full_file_name = ilObjMediaObject::fixFilename($_FILES['full_file']['name']); - $file = $mob_dir."/".$full_file_name; - ilUtil::moveUploadedFile($_FILES['full_file']['tmp_name'], - $full_file_name, $file); - - $format = ilObjMediaObject::getMimeType($file); - $location = $full_file_name; - - $resize = true; - } - else if ($_POST["full_resize"]) - { - $file = $mob_dir."/".$location; - $resize = true; - } - - // resize - if ($resize) - { - if ($_POST["full_size"] != "original" && - is_int(strpos($format, "image"))) - { - $location = ilObjMediaObject::_resizeImage($file, (int) $_POST["full_width_height"]["width"], - (int) $_POST["full_width_height"]["height"], (boolean) $_POST["full_width_height"]["contr_prop"]); - } - $full_item->setFormat($format); - $full_item->setLocation($location); - } - - $full_item->setLocationType("LocalFile"); - $type = "File"; - } - if ($_POST["full_type"] == "Standard") - { - $format = $std_item->getFormat(); - $location = $std_item->getLocation(); - $full_item->setLocationType($std_item->getLocationType()); - $full_item->setFormat($format); - $full_item->setLocation($location); - $type = $std_item->getLocationType(); - if ($type == "LocalFile") - { - $type = "File"; - } - // resize image -//echo "-".$_POST["full_size"]."-".is_int(strpos($format, "image"))."-".$full_item->getLocationType()."-"; - if ($_POST["full_size"] != "original" && - is_int(strpos($format, "image")) && - $full_item->getLocationType() == "LocalFile") - { - $file = $mob_dir."/".$location; - $location = ilObjMediaObject::_resizeImage($file, (int) $_POST["full_width_height"]["width"], - (int) $_POST["full_width_height"]["height"], (boolean) $_POST["full_width_height"]["contr_prop"]); - } - } - - // determine width and height of known image types - $wh = ilObjMediaObject::_determineWidthHeight($format, - $type, $mob_dir."/".$location, $full_item->getLocation(), - $_POST["full_width_height"]["constr_prop"], ($_POST["full_size"] == "original"), - $_POST["full_width_height"]["width"], $_POST["full_width_height"]["height"]); - if ($wh["info"] != "") - { - ilUtil::sendInfo($wh["info"], true); - } - - $full_item->setWidth($wh["width"]); - $full_item->setHeight($wh["height"]); - $full_item->setLocation($location); - - $full_item->setCaption(ilUtil::stripSlashes($_POST["full_caption"])); - - // text representation - $full_item->setTextRepresentation(ilUtil::stripSlashes($_POST["full_text_representation"])); - - - // set parameters - if (!in_array($std_item->getFormat(), ilObjMediaObject::_getSimpleMimeTypes())) - { - if (ilObjMediaObject::_useAutoStartParameterOnly($std_item->getLocation(), - $std_item->getFormat())) - { - if ($_POST["full_autostart"]) // save only autostart flag - { - $full_item->setParameters('autostart="true"'); - } - else - { - $full_item->setParameters(""); - } - } - else - { - $full_item->setParameters(ilUtil::stripSlashes(utf8_decode($_POST["full_parameters"]))); - } - } - } - - ilObjMediaObject::renameExecutables(ilObjMediaObject::_getDirectory($this->object->getId())); - include_once("./Services/MediaObjects/classes/class.ilMediaSvgSanitizer.php"); - ilMediaSvgSanitizer::sanitizeDir(ilObjMediaObject::_getDirectory($this->object->getId())); // see #20339 - - $this->object->update(); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "edit"); - } - else - { - $this->form_gui->setValuesByPost(); - $tpl->setContent($this->form_gui->getHTML()); - } - } - - - /** - * administrate files of media object - */ - function editFilesObject() - { - // standard item - $std_item = $this->object->getMediaItem("Standard"); - if($this->object->hasFullscreenItem()) - { - $full_item = $this->object->getMediaItem("Fullscreen"); - } - - // create table - require_once("./Services/Table/classes/class.ilTableGUI.php"); - $tbl = new ilTableGUI(); - - // determine directory - $cur_subdir = $_GET["cdir"]; - if($_GET["newdir"] == "..") - { - $cur_subdir = substr($cur_subdir, 0, strrpos($cur_subdir, "/")); - } - else - { - if (!empty($_GET["newdir"])) - { - if (!empty($cur_subdir)) - { - $cur_subdir = $cur_subdir."/".$_GET["newdir"]; - } - else - { - $cur_subdir = $_GET["newdir"]; - } - } - } - - $cur_subdir = str_replace(".", "", $cur_subdir); - $mob_dir = ilUtil::getWebspaceDir()."/mobs/mm_".$this->object->getId(); - $cur_dir = (!empty($cur_subdir)) - ? $mob_dir."/".$cur_subdir - : $mob_dir; - - // load files templates - $this->tpl->addBlockfile("ADM_CONTENT", "adm_content", "tpl.mob_files.html", "Services/MediaObjects"); - - $this->ctrl->setParameter($this, "cdir", urlencode($cur_subdir)); - $this->tpl->setVariable("FORMACTION1", $this->ctrl->getFormAction($this)); -//echo "--".$this->getTargetScript(). - //"&hier_id=".$_GET["hier_id"]."&cdir=".$cur_subdir."&cmd=post"."--
                  "; - $this->tpl->setVariable("TXT_NEW_DIRECTORY", $this->lng->txt("cont_new_dir")); - $this->tpl->setVariable("TXT_NEW_FILE", $this->lng->txt("cont_new_file")); - $this->tpl->setVariable("CMD_NEW_DIR", "createDirectory"); - $this->tpl->setVariable("CMD_NEW_FILE", "uploadFile"); - $this->tpl->setVariable("BTN_NEW_DIR", $this->lng->txt("create")); - $this->tpl->setVariable("BTN_NEW_FILE", $this->lng->txt("upload")); - - // - $this->tpl->addBlockfile("FILE_TABLE", "files", "tpl.table.html"); - - // load template for table content data - $this->tpl->addBlockfile("TBL_CONTENT", "tbl_content", "tpl.mob_file_row.html", "Services/MediaObjects"); - - $num = 0; - - $obj_str = ($this->call_by_reference) ? "" : "&obj_id=".$this->obj_id; - $this->tpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this)); - - $tbl->setTitle($this->lng->txt("cont_files")." ".$cur_subdir); - //$tbl->setHelp("tbl_help.php","icon_help.gif",$this->lng->txt("help")); - - $tbl->setHeaderNames(array("", "", $this->lng->txt("cont_dir_file"), - $this->lng->txt("cont_size"), $this->lng->txt("cont_purpose"))); - - $cols = array("", "", "dir_file", "size", "purpose"); - $header_params = array("ref_id" => $_GET["ref_id"], "obj_id" => $_GET["obj_id"], - "cmd" => "editFiles", "hier_id" => $_GET["hier_id"], "item_id" => $_GET["item_id"]); - $tbl->setHeaderVars($cols, $header_params); - $tbl->setColumnWidth(array("1%", "1%", "33%", "33%", "32%")); - - // control - $tbl->setOrderColumn($_GET["sort_by"]); - $tbl->setOrderDirection($_GET["sort_order"]); - $tbl->setLimit($_GET["limit"]); - $tbl->setOffset($_GET["offset"]); - $tbl->setMaxCount($this->maxcount); // ??? - //$tbl->setMaxCount(30); // ??? - - $this->tpl->setVariable("COLUMN_COUNTS", 5); - - // delete button - $this->tpl->setVariable("IMG_ARROW", ilUtil::getImagePath("arrow_downright.svg")); - $this->tpl->setCurrentBlock("tbl_action_btn"); - $this->tpl->setVariable("BTN_NAME", "deleteFile"); - $this->tpl->setVariable("BTN_VALUE", $this->lng->txt("delete")); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setCurrentBlock("tbl_action_btn"); - $this->tpl->setVariable("BTN_NAME", "assignStandard"); - $this->tpl->setVariable("BTN_VALUE", $this->lng->txt("cont_assign_std")); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setCurrentBlock("tbl_action_btn"); - $this->tpl->setVariable("BTN_NAME", "assignFullscreen"); - $this->tpl->setVariable("BTN_VALUE", $this->lng->txt("cont_assign_full")); - $this->tpl->parseCurrentBlock(); - - // footer - $tbl->setFooter("tblfooter",$this->lng->txt("previous"),$this->lng->txt("next")); - //$tbl->disable("footer"); - - $entries = ilUtil::getDir($cur_dir); - - //$objs = ilUtil::sortArray($objs, $_GET["sort_by"], $_GET["sort_order"]); - $tbl->setMaxCount(count($entries)); - $entries = array_slice($entries, $_GET["offset"], $_GET["limit"]); - - $tbl->render(); - if(count($entries) > 0) - { - $i=0; - foreach($entries as $entry) - { - if(($entry["entry"] == ".") || ($entry["entry"] == ".." && empty($cur_subdir))) - { - continue; - } - - //$this->tpl->setVariable("ICON", $obj["title"]); - if($entry["type"] == "dir") - { - $this->tpl->setCurrentBlock("FileLink"); - $this->ctrl->setParameter($this, "cdir", $cur_subdir); - $this->ctrl->setParameter($this, "newdir", rawurlencode($entry["entry"])); - $this->tpl->setVariable("LINK_FILENAME", $this->ctrl->getLinkTarget($this, "editFiles")); - $this->tpl->setVariable("TXT_FILENAME", $entry["entry"]); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setVariable("ICON", ""); - } - else - { - $this->tpl->setCurrentBlock("File"); - $this->tpl->setVariable("TXT_FILENAME2", $entry["entry"]); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setCurrentBlock("tbl_content"); - $css_row = ilUtil::switchColor($i++, "tblrow1", "tblrow2"); - $this->tpl->setVariable("CSS_ROW", $css_row); - - $this->tpl->setVariable("TXT_SIZE", $entry["size"]); - $this->tpl->setVariable("CHECKBOX_ID", $entry["entry"]); - $compare = (!empty($cur_subdir)) - ? $cur_subdir."/".$entry["entry"] - : $entry["entry"]; - $purpose = array(); - if ($std_item->getLocation() == $compare) - { - $purpose[] = $this->lng->txt("cont_std_view"); - } - if($this->object->hasFullscreenItem()) - { - if ($full_item->getLocation() == $compare) - { - $purpose[] = $this->lng->txt("cont_fullscreen"); - } - } - $this->tpl->setVariable("TXT_PURPOSE", implode($purpose, ", ")); - - $this->tpl->parseCurrentBlock(); - } - } //if is_array - else - { - $this->tpl->setCurrentBlock("notfound"); - $this->tpl->setVariable("TXT_OBJECT_NOT_FOUND", $this->lng->txt("obj_not_found")); - $this->tpl->setVariable("NUM_COLS", 4); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->parseCurrentBlock(); - } - - - /** - * create directory - */ - function createDirectoryObject() - { -//echo "cdir:".$_GET["cdir"].":
                  "; - // determine directory - $cur_subdir = str_replace(".", "", $_GET["cdir"]); - $mob_dir = ilUtil::getWebspaceDir()."/mobs/mm_".$this->object->getId(); - $cur_dir = (!empty($cur_subdir)) - ? $mob_dir."/".$cur_subdir - : $mob_dir; - - $new_dir = str_replace(".", "", $_POST["new_dir"]); - $new_dir = str_replace("/", "", $new_dir); - - if (!empty($new_dir)) - { - ilUtil::makeDir($cur_dir."/".$new_dir); - } - $this->ctrl->saveParameter($this, "cdir"); - $this->ctrl->redirect($this, "editFiles"); - } - - /** - * upload file - */ - function uploadFileObject() - { - // determine directory - $cur_subdir = str_replace(".", "", $_GET["cdir"]); - $mob_dir = ilUtil::getWebspaceDir()."/mobs/mm_".$this->object->getId(); - $cur_dir = (!empty($cur_subdir)) - ? $mob_dir."/".$cur_subdir - : $mob_dir; - if (is_file($_FILES["new_file"]["tmp_name"])) - { - $file_name = ilObjMediaObject::fixFilename($_FILES["new_file"]["name"]); - $file = $cur_dir."/".$file_name; - ilUtil::moveUploadedFile($_FILES['new_file']['tmp_name'], - $file_name, $file); - - } - ilObjMediaObject::renameExecutables($mob_dir); - include_once("./Services/MediaObjects/classes/class.ilMediaSvgSanitizer.php"); - ilMediaSvgSanitizer::sanitizeDir($mob_dir); // see #20339 - - $this->ctrl->saveParameter($this, "cdir"); - $this->ctrl->redirect($this, "editFiles"); - } - - /** - * assign file to standard view - */ - function assignStandardObject($a_file) - { - // determine directory - $cur_subdir = dirname($a_file); - $mob_dir = ilUtil::getWebspaceDir()."/mobs/mm_".$this->object->getId(); - $cur_dir = (!empty($cur_subdir)) - ? $mob_dir."/".$cur_subdir - : $mob_dir; - $file = $cur_dir."/".basename($a_file); - $location = $a_file; - - if(!is_file($file)) - { - $this->ilias->raiseError($this->lng->txt("cont_select_file"),$this->ilias->error_obj->MESSAGE); - } - - $std_item = $this->object->getMediaItem("Standard"); - $std_item->setLocationType("LocalFile"); - $std_item->setLocation($location); - $format = ilObjMediaObject::getMimeType($file); - $std_item->setFormat($format); - $this->object->update(); -// $this->ctrl->saveParameter($this, "cdir"); - $this->ctrl->redirectByClass("ilfilesystemgui", "listFiles"); - } - - - /** - * assign file to fullscreen view - */ - function assignFullscreenObject($a_file) - { - // determine directory - $cur_subdir = dirname($a_file); - $mob_dir = ilUtil::getWebspaceDir()."/mobs/mm_".$this->object->getId(); - $cur_dir = (!empty($cur_subdir)) - ? $mob_dir."/".$cur_subdir - : $mob_dir; - $file = $cur_dir."/".basename($a_file); - $location = $a_file; - - if(!is_file($file)) - { - $this->ilias->raiseError($this->lng->txt("cont_select_file"),$this->ilias->error_obj->MESSAGE); - } - - if(!$this->object->hasFullScreenItem()) - { // create new fullscreen item - $std_item = $this->object->getMediaItem("Standard"); - $mob_dir = ilUtil::getWebspaceDir()."/mobs/mm_".$this->object->getId(); - $file = $mob_dir."/".$location; - $full_item = new ilMediaItem(); - $full_item->setMobId($std_item->getMobId()); - $full_item->setLocation($location); - $full_item->setLocationType("LocalFile"); - $full_item->setFormat(ilObjMediaObject::getMimeType($file)); - $full_item->setPurpose("Fullscreen"); - $this->object->addMediaItem($full_item); - } - else // alter existing fullscreen item - { - $full_item = $this->object->getMediaItem("Fullscreen"); - - $full_item->setLocationType("LocalFile"); - $full_item->setLocation($location); - $format = ilObjMediaObject::getMimeType($file); - $full_item->setFormat($format); - } - $this->object->update(); -// $this->ctrl->saveParameter($this, "cdir"); - $this->ctrl->redirectByClass("ilfilesystemgui", "listFiles"); - } - - - /** - * remove fullscreen view - */ - function removeFullscreenObject() - { - $this->object->removeMediaItem("Fullscreen"); - $this->object->update(); - - $this->ctrl->redirect($this, "edit"); - } - - - /** - * add fullscreen view - */ - function addFullscreenObject() - { - if (!$this->object->hasFullScreenItem()) - { - $std_item = $this->object->getMediaItem("Standard"); - $full_item = new ilMediaItem(); - $full_item->setMobId($std_item->getMobId()); - $full_item->setLocation($std_item->getLocation()); - $full_item->setLocationType($std_item->getLocationType()); - $full_item->setFormat($std_item->getFormat()); - $full_item->setWidth($std_item->getWidth()); - $full_item->setHeight($std_item->getHeight()); - $full_item->setCaption($std_item->getCaption()); - $full_item->setTextRepresentation($std_item->getTextRepresentation()); - $full_item->setPurpose("Fullscreen"); - $this->object->addMediaItem($full_item); - - $this->object->update(); - } - - $this->ctrl->redirect($this, "edit"); - } - - - /** - * delete object file - */ - function deleteFileObject() - { - if (!isset($_POST["file"])) - { - $this->ilias->raiseError($this->lng->txt("no_checkbox"),$this->ilias->error_obj->MESSAGE); - } - - if (count($_POST["file"]) > 1) - { - $this->ilias->raiseError($this->lng->txt("cont_select_max_one_item"),$this->ilias->error_obj->MESSAGE); - } - - if ($_POST["file"][0] == "..") - { - $this->ilias->raiseError($this->lng->txt("no_checkbox"),$this->ilias->error_obj->MESSAGE); - } - - $cur_subdir = str_replace(".", "", $_GET["cdir"]); - $mob_dir = ilUtil::getWebspaceDir()."/mobs/mm_".$this->object->getId(); - $cur_dir = (!empty($cur_subdir)) - ? $mob_dir."/".$cur_subdir - : $mob_dir; - $file = $cur_dir."/".$_POST["file"][0]; - $location = (!empty($cur_subdir)) - ? $cur_subdir."/".$_POST["file"][0] - : $_POST["file"][0]; - - $full_item = $this->object->getMediaItem("Fullscreen"); - $std_item = $this->object->getMediaItem("Standard"); - - if ($location == $std_item->getLocation()) - { - $this->ilias->raiseError($this->lng->txt("cont_cant_del_std"),$this->ilias->error_obj->MESSAGE); - } - - if($this->object->hasFullScreenItem()) - { - if ($location == $full_item->getLocation()) - { - $this->ilias->raiseError($this->lng->txt("cont_cant_del_full"),$this->ilias->error_obj->MESSAGE); - } - } - - if (@is_dir($file)) - { - if (substr($std_item->getLocation(), 0 ,strlen($location)) == $location) - { - $this->ilias->raiseError($this->lng->txt("cont_std_is_in_dir"),$this->ilias->error_obj->MESSAGE); - } - - if($this->object->hasFullScreenItem()) - { - if (substr($full_item->getLocation(), 0 ,strlen($location)) == $location) - { - $this->ilias->raiseError($this->lng->txt("cont_full_is_in_dir"),$this->ilias->error_obj->MESSAGE); - } - } - } - - if (@is_file($file)) - { - unlink($file); - } - - if (@is_dir($file)) - { - ilUtil::delDir($file); - } - - $this->ctrl->saveParameter($this, "cdir"); - $this->ctrl->redirect($this, "editFiles"); - } - - /** - * Show all media object usages (incl history) - */ - function showAllUsagesObject() - { - $this->showUsagesObject(true); - } - - - /** - * show all usages of mob - */ - function showUsagesObject($a_all = false) - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; - $ilTabs = $this->tabs; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $ilTabs->addSubTab("current_usages", $lng->txt("cont_current_usages"), - $ilCtrl->getLinkTarget($this, "showUsages")); - - $ilTabs->addSubTab("all_usages", $lng->txt("cont_all_usages"), - $ilCtrl->getLinkTarget($this, "showAllUsages")); - - if ($a_all) - { - $ilTabs->activateSubTab("all_usages"); - $cmd = "showAllUsages"; - } - else - { - $ilTabs->activateSubTab("current_usages"); - $cmd = "showUsages"; - } - - include_once("./Services/MediaObjects/classes/class.ilMediaObjectUsagesTableGUI.php"); - $usages_table = new ilMediaObjectUsagesTableGUI($this, $cmd, - $this->object, $a_all); - $tpl->setContent($usages_table->getHTML()); - } - - /** - * get media info as html - */ - static function _getMediaInfoHTML(&$a_mob) - { - global $DIC; - - $lng = $DIC->language(); - - $tpl = new ilTemplate("tpl.media_info.html", true, true, "Services/MediaObjects"); - $types = array("Standard", "Fullscreen"); - foreach ($types as $type) - { - if($type == "Fullscreen" && !$a_mob->hasFullScreenItem()) - { - continue; - } - - $med = $a_mob->getMediaItem($type); - if (!$med) - { - return ""; - } - - $tpl->setCurrentBlock("media_info"); - if ($type == "Standard") - { - $tpl->setVariable("TXT_PURPOSE", $lng->txt("cont_std_view")); - } - else - { - $tpl->setVariable("TXT_PURPOSE", $lng->txt("cont_fullscreen")); - } - $tpl->setVariable("TXT_TYPE", $lng->txt("cont_".strtolower($med->getLocationType()))); - $tpl->setVariable("VAL_LOCATION", $med->getLocation()); - if ($med->getLocationType() == "LocalFile") - { - $file = ilObjMediaObject::_getDirectory($med->getMobId())."/".$med->getLocation(); - if (is_file($file)) - { - $size = filesize($file); - } - else - { - $size = 0; - } - $tpl->setVariable("VAL_FILE_SIZE", " ($size ".$lng->txt("bytes").")"); - } - $tpl->setVariable("TXT_FORMAT", $lng->txt("cont_format")); - $tpl->setVariable("VAL_FORMAT", $med->getFormat()); - if ($med->getWidth() != "" && $med->getHeight() != "") - { - $tpl->setCurrentBlock("size"); - $tpl->setVariable("TXT_SIZE", $lng->txt("size")); - $tpl->setVariable("VAL_SIZE", $med->getWidth()."x".$med->getHeight()); - $tpl->parseCurrentBlock(); - } - - // original size - if ($orig_size = $med->getOriginalSize()) - { - if ($orig_size["width"] != $med->getWidth() || - $orig_size["height"] != $med->getHeight()) - { - $tpl->setCurrentBlock("orig_size"); - $tpl->setVariable("TXT_ORIG_SIZE", $lng->txt("cont_orig_size")); - $tpl->setVariable("ORIG_WIDTH", $orig_size["width"]); - $tpl->setVariable("ORIG_HEIGHT", $orig_size["height"]); - $tpl->parseCurrentBlock(); - } - } - - // output caption - if($med && strlen($med->getCaption())) - { - $tpl->setCurrentBlock('additional_info'); - $tpl->setVariable('ADD_INFO',$lng->txt('cont_caption').': '.$med->getCaption()); - $tpl->parseCurrentBlock(); - } - - // output keywords - if ($type == "Standard") - { - include_once './Services/MetaData/classes/class.ilMDKeyword.php'; - if(count($kws = ilMDKeyword::lookupKeywords(0, $med->getMobId()))) - { - $tpl->setCurrentBlock('additional_info'); - $tpl->setVariable('ADD_INFO',$lng->txt('keywords').': '.implode(', ',$kws)); - $tpl->parseCurrentBlock(); - } - } - - $tpl->setCurrentBlock("media_info"); - $tpl->parseCurrentBlock(); - } - - return $tpl->get(); - } - - /** - * set admin tabs - */ - //function setAdminTabs() - function setTabs() - { -//echo "setAdminTabs should not be called."; - - // catch feedback message - $this->getTabs(); - - $this->tpl->clearHeader(); - if (is_object($this->object) && strtolower(get_class($this->object)) == "ilobjmediaobject") - { - $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_mob.svg")); - $this->tpl->setTitle($this->object->getTitle()); - } - else - { - //$title = $this->object->getTitle(); - $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_mob.svg")); - $this->tpl->setTitle($this->lng->txt("cont_create_mob")); - } - } - - - /** - * Get Tabs - */ - function getTabs() - { - $ilHelp = $this->help; - - $ilHelp->setScreenIdComponent("mob"); - - if (is_object($this->object) && strtolower(get_class($this->object)) == "ilobjmediaobject" - && $this->object->getId() > 0) - { - // object properties - $this->tabs_gui->addTarget("cont_mob_def_prop", - $this->ctrl->getLinkTarget($this, "edit"), "edit", - get_class($this)); - - $st_item = $this->object->getMediaItem("Standard"); - - // link areas - - if (is_object($st_item) && $this->getEnabledMapAreas()) - { - $format = $st_item->getFormat(); - if (substr($format, 0, 5) == "image" && !is_int(strpos($format, "svg"))) - { - $this->tabs_gui->addTarget("cont_def_map_areas", - $this->ctrl->getLinkTargetByClass( - array("ilobjmediaobjectgui", "ilimagemapeditorgui"), "editMapAreas"), "editMapAreas", - "ilimagemapeditorgui"); - } - } - - // object usages - $this->tabs_gui->addTarget("cont_mob_usages", - $this->ctrl->getLinkTarget($this, "showUsages"), "showUsages", - get_class($this)); - - // object files - $std_item = $this->object->getMediaItem("Standard"); - $full_item = $this->object->getMediaItem("Fullscreen"); - $mset = new ilSetting("mobs"); - if ($mset->get("file_manager_always") || - (!in_array($std_item->getFormat(), ilObjMediaObject::_getSimpleMimeTypes()) || - (is_object($full_item) && !in_array($full_item->getFormat(), ilObjMediaObject::_getSimpleMimeTypes()))) - ) - { -// $ilTabs->addTarget("cont_files", -// $this->ctrl->getLinkTarget($this, "editFiles"), "editFiles", -// get_class($this)); - - $this->tabs_gui->addTarget("cont_files", - $this->ctrl->getLinkTargetByClass( - array("ilobjmediaobjectgui", "ilfilesystemgui"), "listFiles"), "", - "ilfilesystemgui"); - } - - include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php"; - $mdgui = new ilObjectMetaDataGUI(null, $this->object->getType(), $this->object->getId()); - $mdtab = $mdgui->getTab("ilobjmediaobjectgui"); - if($mdtab) - { - $this->tabs_gui->addTarget("meta_data", - $mdtab, - "", "ilmdeditorgui"); - } - - } - - // back to upper context - if ($this->back_title != "") - { - $this->tabs_gui->setBackTarget($this->back_title, - $this->ctrl->getParentReturn($this)); - } - } - - /** - * Show video tools - * - * @param - * @return - */ - function showVideoToolObject() - { - $tpl = $this->tpl; - - include_once("./Services/MediaObjects/classes/class.ilFFmpeg.php"); - - /*$codecs = ilFFmpeg::getSupportedCodecsInfo(); - $codec_str = implode($codecs, "
                  "); - $tpl->setContent($codec_str);*/ - - $formats = ilFFmpeg::getSupportedFormatsInfo(); - $formats_str = implode($formats, "
                  "); - $tpl->setContent($formats_str); - } - - - /** - * Include media object presentation JS - */ - static function includePresentationJS($a_tpl = null) - { - global $DIC; - - $tpl = $DIC["tpl"]; - - if ($a_tpl == null) - { - $a_tpl = $tpl; - } - - include_once("./Services/jQuery/classes/class.iljQueryUtil.php"); - iljQueryUtil::initjQUery($a_tpl); - include_once("./Services/jQuery/classes/class.iljQueryUtil.php"); - $a_tpl->addJavascript(iljQueryUtil::getLocalMaphilightPath()); - $a_tpl->addJavascript("./Services/COPage/js/ilCOPagePres.js"); - - include_once("./Services/MediaObjects/classes/class.ilPlayerUtil.php"); - ilPlayerUtil::initMediaElementJs($a_tpl); - } - - /** - * Set subtabs for properties - * - * @param string $a_active active tab id - */ - function setPropertiesSubTabs($a_active) - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $ilTabs->activateTab("cont_mob_def_prop"); - - $ilTabs->addSubTab("general", - $lng->txt("mob_general"), - $ilCtrl->getLinkTarget($this, "edit")); - - if ($this->object->getMediaItem("Standard")->getFormat() == "video/webm" || - $this->object->getMediaItem("Standard")->getFormat() == "video/mp4") - { - $ilTabs->addSubTab("subtitles", - $lng->txt("mob_subtitles"), - $ilCtrl->getLinkTarget($this, "listSubtitleFiles")); - } - - $ilTabs->activateSubTab($a_active); - } - - /** - * List subtitls files - * - * @param - * @return - */ - function listSubtitleFilesObject() - { - $ilToolbar = $this->toolbar; - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilUser = $this->user; - - $this->setPropertiesSubTabs("subtitles"); - - // upload file - $ilToolbar->setFormAction($ilCtrl->getFormAction($this), true); - include_once("./Services/Form/classes/class.ilFileInputGUI.php"); - $fi = new ilFileInputGUI($lng->txt("mob_subtitle_file")." (.srt)", "subtitle_file"); - $fi->setSuffixes(array("srt")); - $ilToolbar->addInputItem($fi, true); - - // language - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - include_once("./Services/MetaData/classes/class.ilMDLanguageItem.php"); - $options = ilMDLanguageItem::_getLanguages(); - $si = new ilSelectInputGUI($this->lng->txt("mob_language"), "language"); - $si->setOptions($options); - $si->setValue($ilUser->getLanguage()); - $ilToolbar->addInputItem($si, true); - - $ilToolbar->addFormButton($lng->txt("upload"), "uploadSubtitleFile"); - - $ilToolbar->addSeparator(); - $ilToolbar->addFormButton($lng->txt("mob_upload_multi_srt"), "uploadMultipleSubtitleFileForm"); - - include_once("./Services/MediaObjects/classes/class.ilMobSubtitleTableGUI.php"); - $tab = new ilMobSubtitleTableGUI($this, "listSubtitleFiles", $this->object); - - $tpl->setContent($tab->getHTML()); - } - - /** - * Upload srt file - * - * @param - * @return - */ - function uploadSubtitleFileObject() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if ($this->object->uploadSrtFile($_FILES["subtitle_file"]["tmp_name"], ilUtil::stripSlashes($_POST["language"]))) - { - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - } - $ilCtrl->redirect($this, "listSubtitleFiles"); - } - - /** - * Confirm srt file deletion - */ - function confirmSrtDeletionObject() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - $lng->loadLanguageModule("meta"); - - if (!is_array($_POST["srt"]) || count($_POST["srt"]) == 0) - { - ilUtil::sendInfo($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "listSubtitleFiles"); - } - else - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("mob_really_delete_srt")); - $cgui->setCancel($lng->txt("cancel"), "listSubtitleFiles"); - $cgui->setConfirm($lng->txt("delete"), "deleteSrtFiles"); - - foreach ($_POST["srt"] as $i) - { - $cgui->addItem("srt[]", $i, "subtitle_".$i.".srt (".$lng->txt("meta_l_".$i).")"); - } - - $tpl->setContent($cgui->getHTML()); - } - } - - /** - * Delete srt files - */ - function deleteSrtFilesObject() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - foreach ($_POST["srt"] as $i) - { - if (strlen($i) == 2 && !is_int(strpos($i, "."))) - { - $this->object->removeAdditionalFile("srt/subtitle_".$i.".srt"); - } - } - ilUtil::sendSuccess($lng->txt("mob_srt_files_deleted"), true); - $ilCtrl->redirect($this, "listSubtitleFiles"); - } - - /** - * Upload multiple stubtitles - * - * @param - * @return - */ - function uploadMultipleSubtitleFileFormObject() - { - $ilToolbar = $this->toolbar; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - ilUtil::sendInfo($lng->txt("mob_upload_multi_srt_howto")); - - $this->setPropertiesSubTabs("subtitles"); - - // upload file - $ilToolbar->setFormAction($ilCtrl->getFormAction($this), true); - include_once("./Services/Form/classes/class.ilFileInputGUI.php"); - $fi = new ilFileInputGUI($lng->txt("mob_subtitle_file")." (.zip)", "subtitle_file"); - $fi->setSuffixes(array("zip")); - $ilToolbar->addInputItem($fi, true); - - $ilToolbar->addFormButton($lng->txt("upload"), "uploadMultipleSubtitleFile"); - } - - /** - * Upload multiple subtitles - */ - function uploadMultipleSubtitleFileObject() - { - try - { - $this->object->uploadMultipleSubtitleFile(ilUtil::stripSlashesArray($_FILES["subtitle_file"])); - $this->ctrl->redirect($this, "showMultiSubtitleConfirmationTable"); - } - catch (ilMediaObjectsException $e) - { - ilUtil::sendFailure($e->getMessage(), true); - $this->ctrl->redirect($this, "uploadMultipleSubtitleFileForm"); - } - - } - - /** - * List of srt files in zip file - */ - function showMultiSubtitleConfirmationTableObject() - { - $tpl = $this->tpl; - - $this->setPropertiesSubTabs("subtitles"); - - include_once("./Services/MediaObjects/classes/class.ilMultiSrtConfirmationTable2GUI.php"); - $tab = new ilMultiSrtConfirmationTable2GUI($this, "showMultiSubtitleConfirmationTable"); - $tpl->setContent($tab->getHTML()); - } - - /** - * Cancel Multi Feedback - */ - function cancelMultiSrtObject() - { - $this->object->clearMultiSrtDirectory(); - $this->ctrl->redirect($this, "listSubtitleFiles"); - } - - /** - * Save selected srt files as new srt files - */ - function saveMultiSrtObject() - { - $ilCtrl = $this->ctrl; - $srt_files = $this->object->getMultiSrtFiles(); - if (is_array($_POST["file"])) - { - foreach ($_POST["file"] as $f) - { - foreach ($srt_files as $srt_file) - { - if ($f == $srt_file["filename"]) - { - $this->object->uploadSrtFile($this->object->getMultiSrtUploadDir()."/".$srt_file["filename"], $srt_file["lang"], "rename"); - } - } - } - } - $this->object->clearMultiSrtDirectory(); - $ilCtrl->redirect($this, "listSubtitleFiles"); - } - - + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilObjUser + */ + protected $user; + + // $adv_ref_id - $adv_type - $adv_subtype: + // Object, that defines the adv md records being used. Default is $this->object, but the + // context may set another object (e.g. media pool for media objects) + /** + * @var int + */ + protected $adv_ref_id = null; + /** + * @var string + */ + protected $adv_type = null; + /** + * @var string + */ + protected $adv_subtype = null; + + + public $ctrl; + public $header; + public $target_script; + public $enabledmapareas = true; + + public function __construct($a_data, $a_id = 0, $a_call_by_reference = false, $a_prepare_output = false) + { + global $DIC; + + $this->tpl = $DIC["tpl"]; + $this->access = $DIC->access(); + $this->error = $DIC["ilErr"]; + $this->help = $DIC["ilHelp"]; + $this->tabs = $DIC->tabs(); + $this->toolbar = $DIC->toolbar(); + $this->user = $DIC->user(); + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + + $this->ctrl = $ilCtrl; + parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); + $this->lng = $lng; + $this->back_title = ""; + $this->type = "mob"; + + $lng->loadLanguageModule("mob"); + } + + /** + * Set object, that defines the adv md records being used. Default is $this->object, but the + * context may set another object (e.g. media pool for media objects) + * + * @param string $a_val adv type + */ + public function setAdvMdRecordObject($a_adv_ref_id, $a_adv_type, $a_adv_subtype = "-") + { + $this->adv_ref_id = $a_adv_ref_id; + $this->adv_type = $a_adv_type; + $this->adv_subtype = $a_adv_subtype; + } + + /** + * Get adv md record type + * + * @return array adv type + */ + public function getAdvMdRecordObject() + { + if ($this->adv_type == null) { + return [$this->ref_id, $this->obj_type, $this->sub_type]; + } + return [$this->adv_ref_id, $this->adv_type, $this->adv_subtype]; + } + + public function setHeader($a_title = "") + { + $this->header = $a_title; + } + + public function getHeader() + { + return $this->header; + } + + /** + * Set Enable map areas. + * + * @param boolean $a_enabledmapareas Enable map areas + */ + public function setEnabledMapAreas($a_enabledmapareas) + { + $this->enabledmapareas = $a_enabledmapareas; + } + + /** + * Get Enable map areas. + * + * @return boolean Enable map areas + */ + public function getEnabledMapAreas() + { + return $this->enabledmapareas; + } + + /** + * Set width preset + * + * @param int width preset + */ + public function setWidthPreset($a_val) + { + $this->width_preset = $a_val; + } + + /** + * Get width preset + * + * @return int width preset + */ + public function getWidthPreset() + { + return $this->width_preset; + } + + /** + * Set height preset + * + * @param int height preset + */ + public function setHeightPreset($a_val) + { + $this->height_preset = $a_val; + } + + /** + * Get height preset + * + * @return int height preset + */ + public function getHeightPreset() + { + return $this->height_preset; + } + + /** + * Get form + * + * @return object form gui class + */ + public function getForm() + { + return $this->form_gui; + } + + public function assignObject() + { + if ($this->id != 0) { + $this->object = new ilObjMediaObject($this->id); + } + } + + public function returnToContextObject() + { + $this->ctrl->returnToParent($this); + } + + + /** + * Execute current command + * @return bool|mixed + * @throws ilCtrlException + */ + public function executeCommand() + { + $tpl = $this->tpl; + $ilAccess = $this->access; + $ilErr = $this->error; + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + switch ($next_class) { + case 'ilobjectmetadatagui': + include_once 'Services/Object/classes/class.ilObjectMetaDataGUI.php'; + $md_gui = new ilObjectMetaDataGUI(null, $this->object->getType(), $this->object->getId()); + // object is subtype, so we have to do it ourselves + $md_gui->addMDObserver($this->object, 'MDUpdateListener', 'General'); + + // set adv metadata record dobject + if ($this->adv_type != "") { + $md_gui->setAdvMdRecordObject($this->adv_ref_id, $this->adv_type, $this->adv_subtype); + } + + $this->ctrl->forwardCommand($md_gui); + break; + + case "ilimagemapeditorgui": + require_once("./Services/MediaObjects/classes/class.ilImageMapEditorGUI.php"); + $image_map_edit = new ilImageMapEditorGUI($this->object); + $ret = $this->ctrl->forwardCommand($image_map_edit); + $tpl->setContent($ret); + $this->checkFixSize(); + break; + + case "ilfilesystemgui": + include_once("./Services/FileSystem/classes/class.ilFileSystemGUI.php"); + $fs_gui = new ilFileSystemGUI(ilUtil::getWebspaceDir() . "/mobs/mm_" . $this->object->getId()); + $fs_gui->setAllowedSuffixes(ilObjMediaObject::getRestrictedFileTypes()); + $fs_gui->setForbiddenSuffixes(ilObjMediaObject::getForbiddenFileTypes()); + $fs_gui->activateLabels(true, $this->lng->txt("cont_purpose")); + $fs_gui->setTableId("mobfs" . $this->object->getId()); + $fs_gui->labelFile( + $this->object->getMediaItem("Standard")->getLocation(), + $this->lng->txt("cont_std_view") + ); + if ($this->object->hasFullscreenItem()) { + $fs_gui->labelFile( + $this->object->getMediaItem("Fullscreen")->getLocation(), + $this->lng->txt("cont_fullscreen") + ); + } + $fs_gui->addCommand($this, "assignStandardObject", $this->lng->txt("cont_assign_std")); + $fs_gui->addCommand($this, "assignFullscreenObject", $this->lng->txt("cont_assign_full")); + ilObjMediaObject::renameExecutables(ilObjMediaObject::_getDirectory($this->object->getId())); // see #20187 + $ret = $this->ctrl->forwardCommand($fs_gui); + ilObjMediaObject::renameExecutables(ilObjMediaObject::_getDirectory($this->object->getId())); // see #20187 + include_once("./Services/MediaObjects/classes/class.ilMediaSvgSanitizer.php"); + ilMediaSvgSanitizer::sanitizeDir(ilObjMediaObject::_getDirectory($this->object->getId())); // see #20339 + break; + + + default: + if (isset($_POST["editImagemapForward"]) || + isset($_POST["editImagemapForward_x"]) || + isset($_POST["editImagemapForward_y"])) { + $cmd = "editImagemapForward"; + } + $cmd.= "Object"; + $ret = $this->$cmd(); + break; + } + + return $ret; + } + + /** + * set title for back tab + */ + public function setBackTitle($a_title) + { + $this->back_title = $a_title; + } + + /** + * create new media object form + */ + public function createObject() + { + $tpl = $this->tpl; + $ilHelp = $this->help; + + $ilHelp->setScreenId("create"); + $this->initForm(); + $tpl->setContent($this->form_gui->getHTML()); + } + + /** + * Init creation form + */ + public function initForm($a_mode = "create") + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + + if ($a_mode == "edit") { + $std_item = $this->object->getMediaItem("Standard"); + } + + $this->form_gui = new ilPropertyFormGUI(); + + // standard view resource + $title = new ilTextInputGUI($lng->txt("title"), "standard_title"); + $title->setSize(40); + $title->setMaxLength(120); + $this->form_gui->addItem($title); + $radio_prop = new ilRadioGroupInputGUI($lng->txt("cont_resource"), "standard_type"); + $op1 = new ilRadioOption($lng->txt("cont_file"), "File"); + $up = new ilFileInputGUI("", "standard_file"); + $up->setSuffixes(ilObjMediaObject::getRestrictedFileTypes()); + $up->setForbiddenSuffixes(ilObjMediaObject::getForbiddenFileTypes()); + $up->setInfo(""); + if ($a_mode == "create" || $std_item->getLocationType() != "LocalFile") { + $up->setRequired(true); + } + $op1->addSubItem($up); + $radio_prop->addOption($op1); + $op2 = new ilRadioOption($lng->txt("url"), "Reference"); + $ref = new ilTextInputGUI("", "standard_reference"); + $ref->setInfo($lng->txt("cont_ref_helptext")); + $ref->setRequired(true); + $op2->addSubItem($ref); + $radio_prop->addOption($op2); + $radio_prop->setValue("File"); + $this->form_gui->addItem($radio_prop); + + // standard format + if ($a_mode == "edit") { + $format = new ilNonEditableValueGUI($lng->txt("cont_format"), "standard_format"); + $format->setValue($std_item->getFormat()); + $this->form_gui->addItem($format); + } + + // standard size + $radio_size = new ilRadioGroupInputGUI($lng->txt("size"), "standard_size"); + if ($a_mode == "edit") { + if ($orig_size = $std_item->getOriginalSize()) { + $add_str = " (" . $orig_size["width"] . " x " . $orig_size["height"] . ")"; + } + $op1 = new ilRadioOption($lng->txt("cont_resource_size") . $add_str, "original"); + $op1->setInfo($lng->txt("cont_resource_size_info")); + $op2 = new ilRadioOption($lng->txt("cont_custom_size"), "selected"); + } else { + $op1 = new ilRadioOption($lng->txt("cont_orig_size"), "original"); + $op1->setInfo($lng->txt("cont_resource_size_info")); + $op2 = new ilRadioOption($lng->txt("cont_adjust_size"), "selected"); + } + $radio_size->addOption($op1); + + // width height + include_once("./Services/MediaObjects/classes/class.ilWidthHeightInputGUI.php"); + $width_height = new ilWidthHeightInputGUI($lng->txt("cont_width") . + " / " . $lng->txt("cont_height"), "standard_width_height"); + $width_height->setConstrainProportions(true); + $op2->addSubItem($width_height); + + // resize image + if ($a_mode == "edit") { + $std_item = $this->object->getMediaItem("Standard"); + if (is_int(strpos($std_item->getFormat(), "image")) + && $std_item->getLocationType() == "LocalFile") { + $resize = new ilCheckboxInputGUI($lng->txt("cont_resize_img"), "standard_resize"); + $op2->addSubItem($resize); + } + } + + $radio_size->setValue("original"); + if ($a_mode == "create" && ($this->getHeightPreset() > 0 || $this->getWidthPreset() > 0)) { + $radio_size->setValue("selected"); + $width_height->setWidth($this->getWidthPreset()); + $width_height->setHeight($this->getHeightPreset()); + } + $radio_size->addOption($op2); + $this->form_gui->addItem($radio_size); + + // standard caption + $caption = new ilTextAreaInputGUI($lng->txt("cont_caption"), "standard_caption"); + $caption->setCols(30); + $caption->setRows(2); + $this->form_gui->addItem($caption); + + /*$caption = new ilTextInputGUI($lng->txt("cont_caption"), "standard_caption"); + $caption->setSize(40); + $caption->setMaxLength(200); + $this->form_gui->addItem($caption);*/ + + // text representation (alt text) + if ($a_mode == "edit" && is_int(strpos($std_item->getFormat(), "image"))) { + $ta = new ilTextAreaInputGUI($lng->txt("text_repr"), "text_representation"); + $ta->setCols(30); + $ta->setRows(2); + $ta->setInfo($lng->txt("text_repr_info")); + $this->form_gui->addItem($ta); + } + + // standard parameters + if ($a_mode == "edit" && + !in_array($std_item->getFormat(), ilObjMediaObject::_getSimpleMimeTypes())) { + if (ilObjMediaObject::_useAutoStartParameterOnly( + $std_item->getLocation(), + $std_item->getFormat() + )) { // autostart + $auto = new ilCheckboxInputGUI($lng->txt("cont_autostart"), "standard_autostart"); + $this->form_gui->addItem($auto); + } else { // parameters + $par = new ilTextAreaInputGUI($lng->txt("cont_parameter"), "standard_parameters"); + $par->setRows(5); + $par->setCols(50); + $this->form_gui->addItem($par); + } + } + + if ($a_mode == "edit") { + $full_item = $this->object->getMediaItem("Fullscreen"); + } + + // fullscreen view resource + $fs_sec = new ilFormSectionHeaderGUI(); + $fs_sec->setTitle($lng->txt("cont_fullscreen")); + $this->form_gui->addItem($fs_sec); + + $radio_prop2 = new ilRadioGroupInputGUI($lng->txt("cont_resource"), "full_type"); + $op1 = new ilRadioOption($lng->txt("cont_none"), "None"); + $radio_prop2->addOption($op1); + $op4 = new ilRadioOption($lng->txt("cont_use_same_resource_as_above"), "Standard"); + $radio_prop2->addOption($op4); + $op2 = new ilRadioOption($lng->txt("cont_file"), "File"); + $up = new ilFileInputGUI("", "full_file"); + $up->setSuffixes(ilObjMediaObject::getRestrictedFileTypes()); + $up->setForbiddenSuffixes(ilObjMediaObject::getForbiddenFileTypes()); + $up->setInfo(""); + if ($a_mode == "create" || !$full_item || $full_item->getLocationType() != "LocalFile") { + $up->setRequired(true); + } + $op2->addSubItem($up); + $radio_prop2->addOption($op2); + $op3 = new ilRadioOption($lng->txt("url"), "Reference"); + $ref = new ilTextInputGUI("", "full_reference"); + $ref->setInfo($lng->txt("cont_ref_helptext")); + $ref->setRequired(true); + $op3->addSubItem($ref); + $radio_prop2->addOption($op3); + $radio_prop2->setValue("None"); + $this->form_gui->addItem($radio_prop2); + + // fullscreen format + if ($a_mode == "edit") { + if ($this->object->hasFullscreenItem()) { + $format = new ilNonEditableValueGUI($lng->txt("cont_format"), "full_format"); + $format->setValue($full_item->getFormat()); + $this->form_gui->addItem($format); + } + } + + // fullscreen size + $radio_size = new ilRadioGroupInputGUI($lng->txt("size"), "full_size"); + if ($a_mode == "edit") { + $add_str = ""; + if ($this->object->hasFullscreenItem() && ($orig_size = $full_item->getOriginalSize())) { + $add_str = " (" . $orig_size["width"] . " x " . $orig_size["height"] . ")"; + } + $op1 = new ilRadioOption($lng->txt("cont_resource_size") . $add_str, "original"); + $op1->setInfo($lng->txt("cont_resource_size_info")); + $op2 = new ilRadioOption($lng->txt("cont_custom_size"), "selected"); + } else { + $op1 = new ilRadioOption($lng->txt("cont_orig_size"), "original"); + $op1->setInfo($lng->txt("cont_resource_size_info")); + $op2 = new ilRadioOption($lng->txt("cont_adjust_size"), "selected"); + } + $radio_size->addOption($op1); + + // width/height + $width_height = new ilWidthHeightInputGUI($lng->txt("cont_width") . + " / " . $lng->txt("cont_height"), "full_width_height"); + $width_height->setConstrainProportions(true); + $op2->addSubItem($width_height); + + // resize image + if ($a_mode == "edit") { + $full_item = $this->object->getMediaItem("Fullscreen"); + if ($this->object->hasFullscreenItem() && + is_int(strpos($full_item->getFormat(), "image")) && + $full_item->getLocationType() == "LocalFile") { + $resize = new ilCheckboxInputGUI( + $lng->txt("cont_resize_img"), + "full_resize" + ); + $op2->addSubItem($resize); + } + } + + $radio_size->setValue("original"); + $radio_size->addOption($op2); + $this->form_gui->addItem($radio_size); + + // fullscreen caption + $caption = new ilTextAreaInputGUI($lng->txt("cont_caption"), "full_caption"); + $caption->setCols(30); + $caption->setRows(2); + $this->form_gui->addItem($caption); + + /*$caption = new ilTextInputGUI($lng->txt("cont_caption"), "full_caption"); + $caption->setSize(40); + $caption->setMaxLength(200); + $this->form_gui->addItem($caption);*/ + + // text representation (alt text) + if ($a_mode == "edit" && $this->object->hasFullscreenItem() && is_int(strpos($std_item->getFormat(), "image"))) { + $ta = new ilTextAreaInputGUI($lng->txt("text_repr"), "full_text_representation"); + $ta->setCols(30); + $ta->setRows(2); + $ta->setInfo($lng->txt("text_repr_info")); + $this->form_gui->addItem($ta); + } + + + // fullscreen parameters + if ($a_mode == "edit" && $this->object->hasFullscreenItem() && + !in_array($full_item->getFormat(), ilObjMediaObject::_getSimpleMimeTypes())) { + if (ilObjMediaObject::_useAutoStartParameterOnly( + $full_item->getLocation(), + $full_item->getFormat() + )) { + $auto = new ilCheckboxInputGUI($lng->txt("cont_autostart"), "full_autostart"); + $this->form_gui->addItem($auto); + } else { + $par = new ilTextAreaInputGUI($lng->txt("cont_parameter"), "full_parameters"); + $par->setRows(5); + $par->setCols(50); + $this->form_gui->addItem($par); + } + } + + $this->form_gui->setTitle($lng->txt("cont_insert_mob")); + if ($a_mode == "edit") { + $this->form_gui->addCommandButton("saveProperties", $lng->txt("save")); + } else { + $this->form_gui->addCommandButton("save", $lng->txt("save")); + $this->form_gui->addCommandButton("cancel", $lng->txt("cancel")); + } + $this->form_gui->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * Check fix size + * + * @param + * @return + */ + protected function checkFixSize() + { + $std_item = $this->object->getMediaItem("Standard"); + if ($std_item->getWidth() == "" || $std_item->getHeight() == "") { + ilUtil::sendFailure($this->lng->txt("mob_no_fixed_size_map_editing")); + } + } + + + /** + * Get values for form + * + */ + public function getValues() + { + $values = array(); + + $values["standard_title"] = $this->object->getTitle(); + + $std_item = $this->object->getMediaItem("Standard"); + if ($std_item->getLocationType() == "LocalFile") { + $values["standard_type"] = "File"; + $values["standard_file"] = $std_item->getLocation(); + } else { + $values["standard_type"] = "Reference"; + $values["standard_reference"] = $std_item->getLocation(); + } + $values["standard_format"] = $std_item->getFormat(); + $values["standard_width_height"]["width"] = $std_item->getWidth(); + $values["standard_width_height"]["height"] = $std_item->getHeight(); + $values["standard_width_height"]["constr_prop"] = true; + + $values["standard_size"] = "selected"; + + $orig_size = $std_item->getOriginalSize(); + if ($std_item->getWidth() == "" && $std_item->getHeight() == "") { + $values["standard_size"] = "original"; + $values["standard_width_height"]["width"] = $orig_size["width"]; + $values["standard_width_height"]["height"] = $orig_size["height"]; + } + + $values["standard_caption"] = $std_item->getCaption(); + $values["text_representation"] = $std_item->getTextRepresentation(); + if (ilObjMediaObject::_useAutoStartParameterOnly( + $std_item->getLocation(), + $std_item->getFormat() + )) { + $par = $std_item->getParameters(); + if ($par["autostart"]) { + $values["standard_autostart"] = true; + } + } else { + $values["standard_parameters"] = $std_item->getParameterString(); + } + + $values["full_type"] = "None"; + $values["full_size"] = "original"; + if ($this->object->hasFullScreenItem()) { + $full_item = $this->object->getMediaItem("Fullscreen"); + if ($full_item->getLocationType() == "LocalFile") { + $values["full_type"] = "File"; + $values["full_file"] = $full_item->getLocation(); + } else { + $values["full_type"] = "Reference"; + $values["full_reference"] = $full_item->getLocation(); + } + $values["full_format"] = $full_item->getFormat(); + $values["full_width_height"]["width"] = $full_item->getWidth(); + $values["full_width_height"]["height"] = $full_item->getHeight(); + $values["full_width_height"]["constr_prop"] = true; + + $values["full_size"] = "selected"; + + $orig_size = $full_item->getOriginalSize(); + if ($full_item->getWidth() == "" && + $full_item->getHeight() == "") { + $values["full_size"] = "original"; + $values["full_width_height"]["width"] = $orig_size["width"]; + $values["full_width_height"]["height"] = $orig_size["height"]; + } + $values["full_caption"] = $full_item->getCaption(); + if (ilObjMediaObject::_useAutoStartParameterOnly( + $full_item->getLocation(), + $full_item->getFormat() + )) { + $par = $full_item->getParameters(); + if ($par["autostart"]) { + $values["full_autostart"] = true; + } + } else { + $values["full_parameters"] = $full_item->getParameterString(); + } + $values["full_text_representation"] = $full_item->getTextRepresentation(); + } + + $this->form_gui->setValuesByArray($values); + } + + /** + * create new media object in dom and update page in db + */ + public function saveObject() + { + $tpl = $this->tpl; + $lng = $this->lng; + + $this->initForm(); + if ($this->form_gui->checkInput()) { + $this->object = new ilObjMediaObject(); + ilObjMediaObjectGUI::setObjectPerCreationForm($this->object); + ilUtil::sendSuccess($lng->txt("saved_media_object"), true); + return $this->object; + } else { + $this->form_gui->setValuesByPost(); + $tpl->setContent($this->form_gui->getHTML()); + return false; + } + } + + /** + * chechInputForm + * + * @param + * @return + */ + public function checkFormInput() + { + if (!$this->form_gui->checkInput()) { + $this->form_gui->setValuesByPost(); + return false; + } + return true; + } + + + /** + * Set media object values from creation form + */ + public static function setObjectPerCreationForm($a_mob) + { + // determinte title and format + if (trim($_POST["standard_title"]) != "") { + $title = trim($_POST["standard_title"]); + } else { + if ($_POST["standard_type"] == "File") { + $title = $_FILES['standard_file']['name']; + } else { + $title = ilUtil::stripSlashes($_POST["standard_reference"]); + } + } + + $a_mob->setTitle($title); + $a_mob->setDescription(""); + $a_mob->create(); + + // determine and create mob directory, move uploaded file to directory + //$mob_dir = ilUtil::getWebspaceDir()."/mobs/mm_".$a_mob->getId(); + $a_mob->createDirectory(); + $mob_dir = ilObjMediaObject::_getDirectory($a_mob->getId()); + + $media_item = new ilMediaItem(); + $a_mob->addMediaItem($media_item); + $media_item->setPurpose("Standard"); + + if ($_POST["standard_type"] == "File") { + $file_name = ilObjMediaObject::fixFilename($_FILES['standard_file']['name']); + $file = $mob_dir . "/" . $file_name; + ilUtil::moveUploadedFile( + $_FILES['standard_file']['tmp_name'], + $file_name, + $file + ); + + // get mime type + $format = ilObjMediaObject::getMimeType($file); + $location = $file_name; + + // resize standard images + if ($_POST["standard_size"] != "original" && + is_int(strpos($format, "image"))) { + $location = ilObjMediaObject::_resizeImage( + $file, + (int) $_POST["standard_width_height"]["width"], + (int) $_POST["standard_width_height"]["height"], + (boolean) $_POST["standard_width_height"]["contr_prop"] + ); + } + + // set real meta and object data + $media_item->setFormat($format); + $media_item->setLocation($location); + $media_item->setLocationType("LocalFile"); + } else { // standard type: reference + $format = ilObjMediaObject::getMimeType(ilUtil::stripSlashes($_POST["standard_reference"]), true); + $media_item->setFormat($format); + $media_item->setLocation(ilUtil::secureLink(ilUtil::stripSlashes($_POST["standard_reference"]))); + $media_item->setLocationType("Reference"); + } + $a_mob->setDescription($format); + + // determine width and height of known image types + $wh = ilObjMediaObject::_determineWidthHeight( + $format, + $_POST["standard_type"], + $mob_dir . "/" . $location, + $media_item->getLocation(), + $_POST["standard_width_height"]["constr_prop"], + ($_POST["standard_size"] == "original"), + $_POST["standard_width_height"]["width"], + $_POST["standard_width_height"]["height"] + ); + $media_item->setWidth($wh["width"]); + $media_item->setHeight($wh["height"]); + if ($wh["info"] != "") { + ilUtil::sendInfo($wh["info"], true); + } + + if ($_POST["standard_caption"] != "") { + $media_item->setCaption(ilUtil::stripSlashes($_POST["standard_caption"])); + } + + + $media_item->setHAlign("Left"); + + // fullscreen view + if ($_POST["full_type"] != "None") { + $media_item2 = new ilMediaItem(); + $a_mob->addMediaItem($media_item2); + $media_item2->setPurpose("Fullscreen"); + + // move file / set format and location + if ($_POST["full_type"] == "File") { + $format = $location = ""; + if ($_FILES['full_file']['name'] != "") { + $full_file_name = ilObjMediaObject::fixFilename($_FILES['full_file']['name']); + $file = $mob_dir . "/" . $full_file_name; + ilUtil::moveUploadedFile( + $_FILES['full_file']['tmp_name'], + $full_file_name, + $file + ); + $format = ilObjMediaObject::getMimeType($file); + $location = $full_file_name; + } + } elseif ($_POST["full_type"] == "Standard" && $_POST["standard_type"] == "File") { + $location = $file_name; + } + + // resize file + if ($_POST["full_type"] == "File" || + ($_POST["full_type"] == "Standard" && $_POST["standard_type"] == "File")) { + if (($_POST["full_size"] != "original" && + is_int(strpos($format, "image"))) + ) { + $location = ilObjMediaObject::_resizeImage( + $file, + (int) $_POST["full_width_height"]["width"], + (int) $_POST["full_width_height"]["height"], + (boolean) $_POST["full_width_height"]["constr_prop"] + ); + } + + $media_item2->setFormat($format); + $media_item2->setLocation($location); + $media_item2->setLocationType("LocalFile"); + $type = "File"; + } + + if ($_POST["full_type"] == "Reference") { + $format = $location = ""; + if ($_POST["full_reference"] != "") { + $format = ilObjMediaObject::getMimeType($_POST["full_reference"], true); + $location = ilUtil::stripSlashes($_POST["full_reference"]); + } + } + + if ($_POST["full_type"] == "Reference" || + ($_POST["full_type"] == "Standard" && $_POST["standard_type"] == "Reference")) { + $media_item2->setFormat($format); + $media_item2->setLocation($location); + $media_item2->setLocationType("Reference"); + $type = "Reference"; + } + + // determine width and height of known image types + $wh = ilObjMediaObject::_determineWidthHeight( + $format, + $type, + $mob_dir . "/" . $location, + $media_item2->getLocation(), + $_POST["full_width_height"]["constr_prop"], + ($_POST["full_size"] == "original"), + $_POST["full_width_height"]["width"], + $_POST["full_width_height"]["height"] + ); + + $media_item2->setWidth($wh["width"]); + $media_item2->setHeight($wh["height"]); + + if ($_POST["full_caption"] != "") { + $media_item2->setCaption(ilUtil::stripSlashes($_POST["full_caption"])); + } + } + + ilObjMediaObject::renameExecutables($mob_dir); + include_once("./Services/MediaObjects/classes/class.ilMediaSvgSanitizer.php"); + ilMediaSvgSanitizer::sanitizeDir($mob_dir); // see #20339 + $a_mob->update(); + } + + + /** + * Cancel saving + */ + public function cancelObject() + { + $this->ctrl->returnToParent($this); + } + + /** + * edit media object properties + */ + public function editObject() + { + $tpl = $this->tpl; + + $this->setPropertiesSubTabs("general"); + + $this->initForm("edit"); + $this->getValues(); + $tpl->setContent($this->form_gui->getHTML()); + } + + + /** + * resize images to specified size + */ + public function resizeImagesObject() + { + // directory + $mob_dir = ilObjMediaObject::_getDirectory($this->object->getId()); + + // standard item + $std_item = $this->object->getMediaItem("Standard"); + if ($std_item->getLocationType() == "LocalFile" && + is_int(strpos($std_item->getFormat(), "image")) + ) { + $file = $mob_dir . "/" . $std_item->getLocation(); + $location = ilObjMediaObject::_resizeImage( + $file, + $std_item->getWidth(), + $std_item->getHeight() + ); + $std_item->setLocation($location); + $std_item->update(); + } + + // fullscreen item + if ($this->object->hasFullScreenItem()) { + $full_item = $this->object->getMediaItem("Fullscreen"); + if ($full_item->getLocationType() == "LocalFile" && + is_int(strpos($full_item->getFormat(), "image")) + ) { + $file = $mob_dir . "/" . $full_item->getLocation(); + $location = ilObjMediaObject::_resizeImage( + $file, + $full_item->getWidth(), + $full_item->getHeight() + ); + $full_item->setLocation($location); + $full_item->update(); + } + } + + $this->ctrl->redirect($this, "edit"); + } + + + /** + * set original size of standard file + */ + public function getStandardSizeObject() + { + $std_item = $this->object->getMediaItem("Standard"); + $mob_dir = ilObjMediaObject::_getDirectory($this->object->getId()); + + if ($std_item->getLocationType() == "LocalFile") { + $file = $mob_dir . "/" . $std_item->getLocation(); + + include_once("./Services/MediaObjects/classes/class.ilMediaImageUtil.php"); + $size = ilMediaImageUtil::getImageSize($file); + + $std_item->setWidth($size[0]); + $std_item->setHeight($size[1]); + $this->object->update(); + } + $this->ctrl->redirect($this, "edit"); + } + + + /** + * set original size of fullscreen file + */ + public function getFullscreenSizeObject() + { + $full_item = $this->object->getMediaItem("Fullscreen"); + $mob_dir = ilObjMediaObject::_getDirectory($this->object->getId()); + + if ($full_item->getLocationType() == "LocalFile") { + $file = $mob_dir . "/" . $full_item->getLocation(); + include_once("./Services/MediaObjects/classes/class.ilMediaImageUtil.php"); + $size = ilMediaImageUtil::getImageSize($file); + $full_item->setWidth($size[0]); + $full_item->setHeight($size[1]); + $this->object->update(); + } + $this->ctrl->redirect($this, "edit"); + } + + /** + * save properties in db and return to page edit screen + */ + public function savePropertiesObject() + { + $lng = $this->lng; + $tpl = $this->tpl; + + $this->initForm("edit"); + if ($this->form_gui->checkInput()) { + $title = trim($_POST["standard_title"]); + $this->object->setTitle($title); + + $std_item = $this->object->getMediaItem("Standard"); + $location = $std_item->getLocation(); + $format = $std_item->getFormat(); + if ($_POST["standard_type"] == "Reference") { + $format = ilObjMediaObject::getMimeType(ilUtil::stripSlashes($_POST["standard_reference"]), true); + $std_item->setFormat($format); + $std_item->setLocation(ilUtil::secureLink(ilUtil::stripSlashes($_POST["standard_reference"]))); + $std_item->setLocationType("Reference"); + } + $mob_dir = ilObjMediaObject::_getDirectory($this->object->getId()); + if ($_POST["standard_type"] == "File") { + $resize = false; + if ($_FILES['standard_file']['name'] != "") { + $file_name = ilObjMediaObject::fixFilename($_FILES['standard_file']['name']); + $file = $mob_dir . "/" . $file_name; + ilUtil::moveUploadedFile( + $_FILES['standard_file']['tmp_name'], + $file_name, + $file + ); + + // get mime type + $format = ilObjMediaObject::getMimeType($file); + $location = $file_name; + + $resize = true; + } elseif ($_POST["standard_resize"]) { + $file = $mob_dir . "/" . $location; + $resize = true; + } + + // resize + if ($resize) { + if ($_POST["standard_size"] != "original" && + is_int(strpos($format, "image"))) { + $location = ilObjMediaObject::_resizeImage( + $file, + (int) $_POST["standard_width_height"]["width"], + (int) $_POST["standard_width_height"]["height"], + (boolean) $_POST["standard_width_height"]["contr_prop"] + ); + } + $std_item->setFormat($format); + $std_item->setLocation($location); + } + + $std_item->setLocationType("LocalFile"); + } + $this->object->setDescription($format); + // determine width and height of known image types + $wh = ilObjMediaObject::_determineWidthHeight( + $format, + $_POST["standard_type"], + $mob_dir . "/" . $location, + $std_item->getLocation(), + $_POST["standard_width_height"]["constr_prop"], + ($_POST["standard_size"] == "original"), + $_POST["standard_width_height"]["width"], + $_POST["standard_width_height"]["height"] + ); + if ($wh["info"] != "") { + ilUtil::sendInfo($wh["info"], true); + } + $std_item->setWidth($wh["width"]); + $std_item->setHeight($wh["height"]); + + // set caption + $std_item->setCaption(ilUtil::stripSlashes($_POST["standard_caption"])); + + // text representation + $std_item->setTextRepresentation(ilUtil::stripSlashes($_POST["text_representation"])); + + // set parameters + if (!in_array($std_item->getFormat(), ilObjMediaObject::_getSimpleMimeTypes())) { + if (ilObjMediaObject::_useAutoStartParameterOnly( + $std_item->getLocation(), + $std_item->getFormat() + )) { + if ($_POST["standard_autostart"]) { // save only autostart flag + $std_item->setParameters('autostart="true"'); + } else { + $std_item->setParameters(""); + } + } else { + $std_item->setParameters(ilUtil::stripSlashes(utf8_decode($_POST["standard_parameters"]))); + } + } + + // "None" selected + if ($_POST["full_type"] == "None") { + if ($this->object->hasFullscreenItem()) { // delete existing + $this->object->removeMediaItem("Fullscreen"); + } + } else { // Not "None" -> we need one + if ($this->object->hasFullscreenItem()) { // take existing one + $full_item = $this->object->getMediaItem("Fullscreen"); + } else { // create one + $full_item = new ilMediaItem(); + $this->object->addMediaItem($full_item); + $full_item->setPurpose("Fullscreen"); + } + $location = $full_item->getLocation(); + $format = $full_item->getFormat(); + if ($_POST["full_type"] == "Reference") { + $format = ilObjMediaObject::getMimeType(ilUtil::stripSlashes($_POST["full_reference"]), true); + $full_item->setFormat($format); + $full_item->setLocationType("Reference"); + $location = ilUtil::stripSlashes($_POST["full_reference"]); + $type = "Reference"; + } + $mob_dir = ilObjMediaObject::_getDirectory($this->object->getId()); + if ($_POST["full_type"] == "File") { + $resize = false; + if ($_FILES['full_file']['name'] != "") { + $full_file_name = ilObjMediaObject::fixFilename($_FILES['full_file']['name']); + $file = $mob_dir . "/" . $full_file_name; + ilUtil::moveUploadedFile( + $_FILES['full_file']['tmp_name'], + $full_file_name, + $file + ); + + $format = ilObjMediaObject::getMimeType($file); + $location = $full_file_name; + + $resize = true; + } elseif ($_POST["full_resize"]) { + $file = $mob_dir . "/" . $location; + $resize = true; + } + + // resize + if ($resize) { + if ($_POST["full_size"] != "original" && + is_int(strpos($format, "image"))) { + $location = ilObjMediaObject::_resizeImage( + $file, + (int) $_POST["full_width_height"]["width"], + (int) $_POST["full_width_height"]["height"], + (boolean) $_POST["full_width_height"]["contr_prop"] + ); + } + $full_item->setFormat($format); + $full_item->setLocation($location); + } + + $full_item->setLocationType("LocalFile"); + $type = "File"; + } + if ($_POST["full_type"] == "Standard") { + $format = $std_item->getFormat(); + $location = $std_item->getLocation(); + $full_item->setLocationType($std_item->getLocationType()); + $full_item->setFormat($format); + $full_item->setLocation($location); + $type = $std_item->getLocationType(); + if ($type == "LocalFile") { + $type = "File"; + } + // resize image + //echo "-".$_POST["full_size"]."-".is_int(strpos($format, "image"))."-".$full_item->getLocationType()."-"; + if ($_POST["full_size"] != "original" && + is_int(strpos($format, "image")) && + $full_item->getLocationType() == "LocalFile") { + $file = $mob_dir . "/" . $location; + $location = ilObjMediaObject::_resizeImage( + $file, + (int) $_POST["full_width_height"]["width"], + (int) $_POST["full_width_height"]["height"], + (boolean) $_POST["full_width_height"]["contr_prop"] + ); + } + } + + // determine width and height of known image types + $wh = ilObjMediaObject::_determineWidthHeight( + $format, + $type, + $mob_dir . "/" . $location, + $full_item->getLocation(), + $_POST["full_width_height"]["constr_prop"], + ($_POST["full_size"] == "original"), + $_POST["full_width_height"]["width"], + $_POST["full_width_height"]["height"] + ); + if ($wh["info"] != "") { + ilUtil::sendInfo($wh["info"], true); + } + + $full_item->setWidth($wh["width"]); + $full_item->setHeight($wh["height"]); + $full_item->setLocation($location); + + $full_item->setCaption(ilUtil::stripSlashes($_POST["full_caption"])); + + // text representation + $full_item->setTextRepresentation(ilUtil::stripSlashes($_POST["full_text_representation"])); + + + // set parameters + if (!in_array($std_item->getFormat(), ilObjMediaObject::_getSimpleMimeTypes())) { + if (ilObjMediaObject::_useAutoStartParameterOnly( + $std_item->getLocation(), + $std_item->getFormat() + )) { + if ($_POST["full_autostart"]) { // save only autostart flag + $full_item->setParameters('autostart="true"'); + } else { + $full_item->setParameters(""); + } + } else { + $full_item->setParameters(ilUtil::stripSlashes(utf8_decode($_POST["full_parameters"]))); + } + } + } + + ilObjMediaObject::renameExecutables(ilObjMediaObject::_getDirectory($this->object->getId())); + include_once("./Services/MediaObjects/classes/class.ilMediaSvgSanitizer.php"); + ilMediaSvgSanitizer::sanitizeDir(ilObjMediaObject::_getDirectory($this->object->getId())); // see #20339 + + $this->object->update(); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "edit"); + } else { + $this->form_gui->setValuesByPost(); + $tpl->setContent($this->form_gui->getHTML()); + } + } + + + /** + * administrate files of media object + */ + public function editFilesObject() + { + // standard item + $std_item = $this->object->getMediaItem("Standard"); + if ($this->object->hasFullscreenItem()) { + $full_item = $this->object->getMediaItem("Fullscreen"); + } + + // create table + require_once("./Services/Table/classes/class.ilTableGUI.php"); + $tbl = new ilTableGUI(); + + // determine directory + $cur_subdir = $_GET["cdir"]; + if ($_GET["newdir"] == "..") { + $cur_subdir = substr($cur_subdir, 0, strrpos($cur_subdir, "/")); + } else { + if (!empty($_GET["newdir"])) { + if (!empty($cur_subdir)) { + $cur_subdir = $cur_subdir . "/" . $_GET["newdir"]; + } else { + $cur_subdir = $_GET["newdir"]; + } + } + } + + $cur_subdir = str_replace(".", "", $cur_subdir); + $mob_dir = ilUtil::getWebspaceDir() . "/mobs/mm_" . $this->object->getId(); + $cur_dir = (!empty($cur_subdir)) + ? $mob_dir . "/" . $cur_subdir + : $mob_dir; + + // load files templates + $this->tpl->addBlockfile("ADM_CONTENT", "adm_content", "tpl.mob_files.html", "Services/MediaObjects"); + + $this->ctrl->setParameter($this, "cdir", urlencode($cur_subdir)); + $this->tpl->setVariable("FORMACTION1", $this->ctrl->getFormAction($this)); + //echo "--".$this->getTargetScript(). + //"&hier_id=".$_GET["hier_id"]."&cdir=".$cur_subdir."&cmd=post"."--
                  "; + $this->tpl->setVariable("TXT_NEW_DIRECTORY", $this->lng->txt("cont_new_dir")); + $this->tpl->setVariable("TXT_NEW_FILE", $this->lng->txt("cont_new_file")); + $this->tpl->setVariable("CMD_NEW_DIR", "createDirectory"); + $this->tpl->setVariable("CMD_NEW_FILE", "uploadFile"); + $this->tpl->setVariable("BTN_NEW_DIR", $this->lng->txt("create")); + $this->tpl->setVariable("BTN_NEW_FILE", $this->lng->txt("upload")); + + // + $this->tpl->addBlockfile("FILE_TABLE", "files", "tpl.table.html"); + + // load template for table content data + $this->tpl->addBlockfile("TBL_CONTENT", "tbl_content", "tpl.mob_file_row.html", "Services/MediaObjects"); + + $num = 0; + + $obj_str = ($this->call_by_reference) ? "" : "&obj_id=" . $this->obj_id; + $this->tpl->setVariable("FORMACTION", $this->ctrl->getFormAction($this)); + + $tbl->setTitle($this->lng->txt("cont_files") . " " . $cur_subdir); + //$tbl->setHelp("tbl_help.php","icon_help.gif",$this->lng->txt("help")); + + $tbl->setHeaderNames(array("", "", $this->lng->txt("cont_dir_file"), + $this->lng->txt("cont_size"), $this->lng->txt("cont_purpose"))); + + $cols = array("", "", "dir_file", "size", "purpose"); + $header_params = array("ref_id" => $_GET["ref_id"], "obj_id" => $_GET["obj_id"], + "cmd" => "editFiles", "hier_id" => $_GET["hier_id"], "item_id" => $_GET["item_id"]); + $tbl->setHeaderVars($cols, $header_params); + $tbl->setColumnWidth(array("1%", "1%", "33%", "33%", "32%")); + + // control + $tbl->setOrderColumn($_GET["sort_by"]); + $tbl->setOrderDirection($_GET["sort_order"]); + $tbl->setLimit($_GET["limit"]); + $tbl->setOffset($_GET["offset"]); + $tbl->setMaxCount($this->maxcount); // ??? + //$tbl->setMaxCount(30); // ??? + + $this->tpl->setVariable("COLUMN_COUNTS", 5); + + // delete button + $this->tpl->setVariable("IMG_ARROW", ilUtil::getImagePath("arrow_downright.svg")); + $this->tpl->setCurrentBlock("tbl_action_btn"); + $this->tpl->setVariable("BTN_NAME", "deleteFile"); + $this->tpl->setVariable("BTN_VALUE", $this->lng->txt("delete")); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setCurrentBlock("tbl_action_btn"); + $this->tpl->setVariable("BTN_NAME", "assignStandard"); + $this->tpl->setVariable("BTN_VALUE", $this->lng->txt("cont_assign_std")); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setCurrentBlock("tbl_action_btn"); + $this->tpl->setVariable("BTN_NAME", "assignFullscreen"); + $this->tpl->setVariable("BTN_VALUE", $this->lng->txt("cont_assign_full")); + $this->tpl->parseCurrentBlock(); + + // footer + $tbl->setFooter("tblfooter", $this->lng->txt("previous"), $this->lng->txt("next")); + //$tbl->disable("footer"); + + $entries = ilUtil::getDir($cur_dir); + + //$objs = ilUtil::sortArray($objs, $_GET["sort_by"], $_GET["sort_order"]); + $tbl->setMaxCount(count($entries)); + $entries = array_slice($entries, $_GET["offset"], $_GET["limit"]); + + $tbl->render(); + if (count($entries) > 0) { + $i=0; + foreach ($entries as $entry) { + if (($entry["entry"] == ".") || ($entry["entry"] == ".." && empty($cur_subdir))) { + continue; + } + + //$this->tpl->setVariable("ICON", $obj["title"]); + if ($entry["type"] == "dir") { + $this->tpl->setCurrentBlock("FileLink"); + $this->ctrl->setParameter($this, "cdir", $cur_subdir); + $this->ctrl->setParameter($this, "newdir", rawurlencode($entry["entry"])); + $this->tpl->setVariable("LINK_FILENAME", $this->ctrl->getLinkTarget($this, "editFiles")); + $this->tpl->setVariable("TXT_FILENAME", $entry["entry"]); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setVariable("ICON", ""); + } else { + $this->tpl->setCurrentBlock("File"); + $this->tpl->setVariable("TXT_FILENAME2", $entry["entry"]); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setCurrentBlock("tbl_content"); + $css_row = ilUtil::switchColor($i++, "tblrow1", "tblrow2"); + $this->tpl->setVariable("CSS_ROW", $css_row); + + $this->tpl->setVariable("TXT_SIZE", $entry["size"]); + $this->tpl->setVariable("CHECKBOX_ID", $entry["entry"]); + $compare = (!empty($cur_subdir)) + ? $cur_subdir . "/" . $entry["entry"] + : $entry["entry"]; + $purpose = array(); + if ($std_item->getLocation() == $compare) { + $purpose[] = $this->lng->txt("cont_std_view"); + } + if ($this->object->hasFullscreenItem()) { + if ($full_item->getLocation() == $compare) { + $purpose[] = $this->lng->txt("cont_fullscreen"); + } + } + $this->tpl->setVariable("TXT_PURPOSE", implode($purpose, ", ")); + + $this->tpl->parseCurrentBlock(); + } + } //if is_array + else { + $this->tpl->setCurrentBlock("notfound"); + $this->tpl->setVariable("TXT_OBJECT_NOT_FOUND", $this->lng->txt("obj_not_found")); + $this->tpl->setVariable("NUM_COLS", 4); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->parseCurrentBlock(); + } + + + /** + * create directory + */ + public function createDirectoryObject() + { + //echo "cdir:".$_GET["cdir"].":
                  "; + // determine directory + $cur_subdir = str_replace(".", "", $_GET["cdir"]); + $mob_dir = ilUtil::getWebspaceDir() . "/mobs/mm_" . $this->object->getId(); + $cur_dir = (!empty($cur_subdir)) + ? $mob_dir . "/" . $cur_subdir + : $mob_dir; + + $new_dir = str_replace(".", "", $_POST["new_dir"]); + $new_dir = str_replace("/", "", $new_dir); + + if (!empty($new_dir)) { + ilUtil::makeDir($cur_dir . "/" . $new_dir); + } + $this->ctrl->saveParameter($this, "cdir"); + $this->ctrl->redirect($this, "editFiles"); + } + + /** + * upload file + */ + public function uploadFileObject() + { + // determine directory + $cur_subdir = str_replace(".", "", $_GET["cdir"]); + $mob_dir = ilUtil::getWebspaceDir() . "/mobs/mm_" . $this->object->getId(); + $cur_dir = (!empty($cur_subdir)) + ? $mob_dir . "/" . $cur_subdir + : $mob_dir; + if (is_file($_FILES["new_file"]["tmp_name"])) { + $file_name = ilObjMediaObject::fixFilename($_FILES["new_file"]["name"]); + $file = $cur_dir . "/" . $file_name; + ilUtil::moveUploadedFile( + $_FILES['new_file']['tmp_name'], + $file_name, + $file + ); + } + ilObjMediaObject::renameExecutables($mob_dir); + include_once("./Services/MediaObjects/classes/class.ilMediaSvgSanitizer.php"); + ilMediaSvgSanitizer::sanitizeDir($mob_dir); // see #20339 + + $this->ctrl->saveParameter($this, "cdir"); + $this->ctrl->redirect($this, "editFiles"); + } + + /** + * assign file to standard view + */ + public function assignStandardObject($a_file) + { + // determine directory + $cur_subdir = dirname($a_file); + $mob_dir = ilUtil::getWebspaceDir() . "/mobs/mm_" . $this->object->getId(); + $cur_dir = (!empty($cur_subdir)) + ? $mob_dir . "/" . $cur_subdir + : $mob_dir; + $file = $cur_dir . "/" . basename($a_file); + $location = $a_file; + + if (!is_file($file)) { + $this->ilias->raiseError($this->lng->txt("cont_select_file"), $this->ilias->error_obj->MESSAGE); + } + + $std_item = $this->object->getMediaItem("Standard"); + $std_item->setLocationType("LocalFile"); + $std_item->setLocation($location); + $format = ilObjMediaObject::getMimeType($file); + $std_item->setFormat($format); + $this->object->update(); + // $this->ctrl->saveParameter($this, "cdir"); + $this->ctrl->redirectByClass("ilfilesystemgui", "listFiles"); + } + + + /** + * assign file to fullscreen view + */ + public function assignFullscreenObject($a_file) + { + // determine directory + $cur_subdir = dirname($a_file); + $mob_dir = ilUtil::getWebspaceDir() . "/mobs/mm_" . $this->object->getId(); + $cur_dir = (!empty($cur_subdir)) + ? $mob_dir . "/" . $cur_subdir + : $mob_dir; + $file = $cur_dir . "/" . basename($a_file); + $location = $a_file; + + if (!is_file($file)) { + $this->ilias->raiseError($this->lng->txt("cont_select_file"), $this->ilias->error_obj->MESSAGE); + } + + if (!$this->object->hasFullScreenItem()) { // create new fullscreen item + $std_item = $this->object->getMediaItem("Standard"); + $mob_dir = ilUtil::getWebspaceDir() . "/mobs/mm_" . $this->object->getId(); + $file = $mob_dir . "/" . $location; + $full_item = new ilMediaItem(); + $full_item->setMobId($std_item->getMobId()); + $full_item->setLocation($location); + $full_item->setLocationType("LocalFile"); + $full_item->setFormat(ilObjMediaObject::getMimeType($file)); + $full_item->setPurpose("Fullscreen"); + $this->object->addMediaItem($full_item); + } else { // alter existing fullscreen item + $full_item = $this->object->getMediaItem("Fullscreen"); + + $full_item->setLocationType("LocalFile"); + $full_item->setLocation($location); + $format = ilObjMediaObject::getMimeType($file); + $full_item->setFormat($format); + } + $this->object->update(); + // $this->ctrl->saveParameter($this, "cdir"); + $this->ctrl->redirectByClass("ilfilesystemgui", "listFiles"); + } + + + /** + * remove fullscreen view + */ + public function removeFullscreenObject() + { + $this->object->removeMediaItem("Fullscreen"); + $this->object->update(); + + $this->ctrl->redirect($this, "edit"); + } + + + /** + * add fullscreen view + */ + public function addFullscreenObject() + { + if (!$this->object->hasFullScreenItem()) { + $std_item = $this->object->getMediaItem("Standard"); + $full_item = new ilMediaItem(); + $full_item->setMobId($std_item->getMobId()); + $full_item->setLocation($std_item->getLocation()); + $full_item->setLocationType($std_item->getLocationType()); + $full_item->setFormat($std_item->getFormat()); + $full_item->setWidth($std_item->getWidth()); + $full_item->setHeight($std_item->getHeight()); + $full_item->setCaption($std_item->getCaption()); + $full_item->setTextRepresentation($std_item->getTextRepresentation()); + $full_item->setPurpose("Fullscreen"); + $this->object->addMediaItem($full_item); + + $this->object->update(); + } + + $this->ctrl->redirect($this, "edit"); + } + + + /** + * delete object file + */ + public function deleteFileObject() + { + if (!isset($_POST["file"])) { + $this->ilias->raiseError($this->lng->txt("no_checkbox"), $this->ilias->error_obj->MESSAGE); + } + + if (count($_POST["file"]) > 1) { + $this->ilias->raiseError($this->lng->txt("cont_select_max_one_item"), $this->ilias->error_obj->MESSAGE); + } + + if ($_POST["file"][0] == "..") { + $this->ilias->raiseError($this->lng->txt("no_checkbox"), $this->ilias->error_obj->MESSAGE); + } + + $cur_subdir = str_replace(".", "", $_GET["cdir"]); + $mob_dir = ilUtil::getWebspaceDir() . "/mobs/mm_" . $this->object->getId(); + $cur_dir = (!empty($cur_subdir)) + ? $mob_dir . "/" . $cur_subdir + : $mob_dir; + $file = $cur_dir . "/" . $_POST["file"][0]; + $location = (!empty($cur_subdir)) + ? $cur_subdir . "/" . $_POST["file"][0] + : $_POST["file"][0]; + + $full_item = $this->object->getMediaItem("Fullscreen"); + $std_item = $this->object->getMediaItem("Standard"); + + if ($location == $std_item->getLocation()) { + $this->ilias->raiseError($this->lng->txt("cont_cant_del_std"), $this->ilias->error_obj->MESSAGE); + } + + if ($this->object->hasFullScreenItem()) { + if ($location == $full_item->getLocation()) { + $this->ilias->raiseError($this->lng->txt("cont_cant_del_full"), $this->ilias->error_obj->MESSAGE); + } + } + + if (@is_dir($file)) { + if (substr($std_item->getLocation(), 0, strlen($location)) == $location) { + $this->ilias->raiseError($this->lng->txt("cont_std_is_in_dir"), $this->ilias->error_obj->MESSAGE); + } + + if ($this->object->hasFullScreenItem()) { + if (substr($full_item->getLocation(), 0, strlen($location)) == $location) { + $this->ilias->raiseError($this->lng->txt("cont_full_is_in_dir"), $this->ilias->error_obj->MESSAGE); + } + } + } + + if (@is_file($file)) { + unlink($file); + } + + if (@is_dir($file)) { + ilUtil::delDir($file); + } + + $this->ctrl->saveParameter($this, "cdir"); + $this->ctrl->redirect($this, "editFiles"); + } + + /** + * Show all media object usages (incl history) + */ + public function showAllUsagesObject() + { + $this->showUsagesObject(true); + } + + + /** + * show all usages of mob + */ + public function showUsagesObject($a_all = false) + { + $tpl = $this->tpl; + $ilTabs = $this->tabs; + $ilTabs = $this->tabs; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $ilTabs->addSubTab( + "current_usages", + $lng->txt("cont_current_usages"), + $ilCtrl->getLinkTarget($this, "showUsages") + ); + + $ilTabs->addSubTab( + "all_usages", + $lng->txt("cont_all_usages"), + $ilCtrl->getLinkTarget($this, "showAllUsages") + ); + + if ($a_all) { + $ilTabs->activateSubTab("all_usages"); + $cmd = "showAllUsages"; + } else { + $ilTabs->activateSubTab("current_usages"); + $cmd = "showUsages"; + } + + include_once("./Services/MediaObjects/classes/class.ilMediaObjectUsagesTableGUI.php"); + $usages_table = new ilMediaObjectUsagesTableGUI( + $this, + $cmd, + $this->object, + $a_all + ); + $tpl->setContent($usages_table->getHTML()); + } + + /** + * get media info as html + */ + public static function _getMediaInfoHTML(&$a_mob) + { + global $DIC; + + $lng = $DIC->language(); + + $tpl = new ilTemplate("tpl.media_info.html", true, true, "Services/MediaObjects"); + $types = array("Standard", "Fullscreen"); + foreach ($types as $type) { + if ($type == "Fullscreen" && !$a_mob->hasFullScreenItem()) { + continue; + } + + $med = $a_mob->getMediaItem($type); + if (!$med) { + return ""; + } + + $tpl->setCurrentBlock("media_info"); + if ($type == "Standard") { + $tpl->setVariable("TXT_PURPOSE", $lng->txt("cont_std_view")); + } else { + $tpl->setVariable("TXT_PURPOSE", $lng->txt("cont_fullscreen")); + } + $tpl->setVariable("TXT_TYPE", $lng->txt("cont_" . strtolower($med->getLocationType()))); + $tpl->setVariable("VAL_LOCATION", $med->getLocation()); + if ($med->getLocationType() == "LocalFile") { + $file = ilObjMediaObject::_getDirectory($med->getMobId()) . "/" . $med->getLocation(); + if (is_file($file)) { + $size = filesize($file); + } else { + $size = 0; + } + $tpl->setVariable("VAL_FILE_SIZE", " ($size " . $lng->txt("bytes") . ")"); + } + $tpl->setVariable("TXT_FORMAT", $lng->txt("cont_format")); + $tpl->setVariable("VAL_FORMAT", $med->getFormat()); + if ($med->getWidth() != "" && $med->getHeight() != "") { + $tpl->setCurrentBlock("size"); + $tpl->setVariable("TXT_SIZE", $lng->txt("size")); + $tpl->setVariable("VAL_SIZE", $med->getWidth() . "x" . $med->getHeight()); + $tpl->parseCurrentBlock(); + } + + // original size + if ($orig_size = $med->getOriginalSize()) { + if ($orig_size["width"] != $med->getWidth() || + $orig_size["height"] != $med->getHeight()) { + $tpl->setCurrentBlock("orig_size"); + $tpl->setVariable("TXT_ORIG_SIZE", $lng->txt("cont_orig_size")); + $tpl->setVariable("ORIG_WIDTH", $orig_size["width"]); + $tpl->setVariable("ORIG_HEIGHT", $orig_size["height"]); + $tpl->parseCurrentBlock(); + } + } + + // output caption + if ($med && strlen($med->getCaption())) { + $tpl->setCurrentBlock('additional_info'); + $tpl->setVariable('ADD_INFO', $lng->txt('cont_caption') . ': ' . $med->getCaption()); + $tpl->parseCurrentBlock(); + } + + // output keywords + if ($type == "Standard") { + include_once './Services/MetaData/classes/class.ilMDKeyword.php'; + if (count($kws = ilMDKeyword::lookupKeywords(0, $med->getMobId()))) { + $tpl->setCurrentBlock('additional_info'); + $tpl->setVariable('ADD_INFO', $lng->txt('keywords') . ': ' . implode(', ', $kws)); + $tpl->parseCurrentBlock(); + } + } + + $tpl->setCurrentBlock("media_info"); + $tpl->parseCurrentBlock(); + } + + return $tpl->get(); + } + + /** + * set admin tabs + */ + //function setAdminTabs() + public function setTabs() + { + //echo "setAdminTabs should not be called."; + + // catch feedback message + $this->getTabs(); + + $this->tpl->clearHeader(); + if (is_object($this->object) && strtolower(get_class($this->object)) == "ilobjmediaobject") { + $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_mob.svg")); + $this->tpl->setTitle($this->object->getTitle()); + } else { + //$title = $this->object->getTitle(); + $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_mob.svg")); + $this->tpl->setTitle($this->lng->txt("cont_create_mob")); + } + } + + + /** + * Get Tabs + */ + public function getTabs() + { + $ilHelp = $this->help; + + $ilHelp->setScreenIdComponent("mob"); + + if (is_object($this->object) && strtolower(get_class($this->object)) == "ilobjmediaobject" + && $this->object->getId() > 0) { + // object properties + $this->tabs_gui->addTarget( + "cont_mob_def_prop", + $this->ctrl->getLinkTarget($this, "edit"), + "edit", + get_class($this) + ); + + $st_item = $this->object->getMediaItem("Standard"); + + // link areas + + if (is_object($st_item) && $this->getEnabledMapAreas()) { + $format = $st_item->getFormat(); + if (substr($format, 0, 5) == "image" && !is_int(strpos($format, "svg"))) { + $this->tabs_gui->addTarget( + "cont_def_map_areas", + $this->ctrl->getLinkTargetByClass( + array("ilobjmediaobjectgui", "ilimagemapeditorgui"), + "editMapAreas" + ), + "editMapAreas", + "ilimagemapeditorgui" + ); + } + } + + // object usages + $this->tabs_gui->addTarget( + "cont_mob_usages", + $this->ctrl->getLinkTarget($this, "showUsages"), + "showUsages", + get_class($this) + ); + + // object files + $std_item = $this->object->getMediaItem("Standard"); + $full_item = $this->object->getMediaItem("Fullscreen"); + $mset = new ilSetting("mobs"); + if ($mset->get("file_manager_always") || + (!in_array($std_item->getFormat(), ilObjMediaObject::_getSimpleMimeTypes()) || + (is_object($full_item) && !in_array($full_item->getFormat(), ilObjMediaObject::_getSimpleMimeTypes()))) + ) { + // $ilTabs->addTarget("cont_files", + // $this->ctrl->getLinkTarget($this, "editFiles"), "editFiles", + // get_class($this)); + + $this->tabs_gui->addTarget( + "cont_files", + $this->ctrl->getLinkTargetByClass( + array("ilobjmediaobjectgui", "ilfilesystemgui"), + "listFiles" + ), + "", + "ilfilesystemgui" + ); + } + + include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php"; + $mdgui = new ilObjectMetaDataGUI(null, $this->object->getType(), $this->object->getId()); + $mdtab = $mdgui->getTab("ilobjmediaobjectgui"); + if ($mdtab) { + $this->tabs_gui->addTarget( + "meta_data", + $mdtab, + "", + "ilmdeditorgui" + ); + } + } + + // back to upper context + if ($this->back_title != "") { + $this->tabs_gui->setBackTarget( + $this->back_title, + $this->ctrl->getParentReturn($this) + ); + } + } + + /** + * Show video tools + * + * @param + * @return + */ + public function showVideoToolObject() + { + $tpl = $this->tpl; + + include_once("./Services/MediaObjects/classes/class.ilFFmpeg.php"); + + /*$codecs = ilFFmpeg::getSupportedCodecsInfo(); + $codec_str = implode($codecs, "
                  "); + $tpl->setContent($codec_str);*/ + + $formats = ilFFmpeg::getSupportedFormatsInfo(); + $formats_str = implode($formats, "
                  "); + $tpl->setContent($formats_str); + } + + + /** + * Include media object presentation JS + */ + public static function includePresentationJS($a_tpl = null) + { + global $DIC; + + $tpl = $DIC["tpl"]; + + if ($a_tpl == null) { + $a_tpl = $tpl; + } + + include_once("./Services/jQuery/classes/class.iljQueryUtil.php"); + iljQueryUtil::initjQUery($a_tpl); + include_once("./Services/jQuery/classes/class.iljQueryUtil.php"); + $a_tpl->addJavascript(iljQueryUtil::getLocalMaphilightPath()); + $a_tpl->addJavascript("./Services/COPage/js/ilCOPagePres.js"); + + include_once("./Services/MediaObjects/classes/class.ilPlayerUtil.php"); + ilPlayerUtil::initMediaElementJs($a_tpl); + } + + /** + * Set subtabs for properties + * + * @param string $a_active active tab id + */ + public function setPropertiesSubTabs($a_active) + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $ilTabs->activateTab("cont_mob_def_prop"); + + $ilTabs->addSubTab( + "general", + $lng->txt("mob_general"), + $ilCtrl->getLinkTarget($this, "edit") + ); + + if ($this->object->getMediaItem("Standard")->getFormat() == "video/webm" || + $this->object->getMediaItem("Standard")->getFormat() == "video/mp4") { + $ilTabs->addSubTab( + "subtitles", + $lng->txt("mob_subtitles"), + $ilCtrl->getLinkTarget($this, "listSubtitleFiles") + ); + } + + $ilTabs->activateSubTab($a_active); + } + + /** + * List subtitls files + * + * @param + * @return + */ + public function listSubtitleFilesObject() + { + $ilToolbar = $this->toolbar; + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilUser = $this->user; + + $this->setPropertiesSubTabs("subtitles"); + + // upload file + $ilToolbar->setFormAction($ilCtrl->getFormAction($this), true); + include_once("./Services/Form/classes/class.ilFileInputGUI.php"); + $fi = new ilFileInputGUI($lng->txt("mob_subtitle_file") . " (.srt)", "subtitle_file"); + $fi->setSuffixes(array("srt")); + $ilToolbar->addInputItem($fi, true); + + // language + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + include_once("./Services/MetaData/classes/class.ilMDLanguageItem.php"); + $options = ilMDLanguageItem::_getLanguages(); + $si = new ilSelectInputGUI($this->lng->txt("mob_language"), "language"); + $si->setOptions($options); + $si->setValue($ilUser->getLanguage()); + $ilToolbar->addInputItem($si, true); + + $ilToolbar->addFormButton($lng->txt("upload"), "uploadSubtitleFile"); + + $ilToolbar->addSeparator(); + $ilToolbar->addFormButton($lng->txt("mob_upload_multi_srt"), "uploadMultipleSubtitleFileForm"); + + include_once("./Services/MediaObjects/classes/class.ilMobSubtitleTableGUI.php"); + $tab = new ilMobSubtitleTableGUI($this, "listSubtitleFiles", $this->object); + + $tpl->setContent($tab->getHTML()); + } + + /** + * Upload srt file + * + * @param + * @return + */ + public function uploadSubtitleFileObject() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if ($this->object->uploadSrtFile($_FILES["subtitle_file"]["tmp_name"], ilUtil::stripSlashes($_POST["language"]))) { + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + } + $ilCtrl->redirect($this, "listSubtitleFiles"); + } + + /** + * Confirm srt file deletion + */ + public function confirmSrtDeletionObject() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + $lng->loadLanguageModule("meta"); + + if (!is_array($_POST["srt"]) || count($_POST["srt"]) == 0) { + ilUtil::sendInfo($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "listSubtitleFiles"); + } else { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("mob_really_delete_srt")); + $cgui->setCancel($lng->txt("cancel"), "listSubtitleFiles"); + $cgui->setConfirm($lng->txt("delete"), "deleteSrtFiles"); + + foreach ($_POST["srt"] as $i) { + $cgui->addItem("srt[]", $i, "subtitle_" . $i . ".srt (" . $lng->txt("meta_l_" . $i) . ")"); + } + + $tpl->setContent($cgui->getHTML()); + } + } + + /** + * Delete srt files + */ + public function deleteSrtFilesObject() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + foreach ($_POST["srt"] as $i) { + if (strlen($i) == 2 && !is_int(strpos($i, "."))) { + $this->object->removeAdditionalFile("srt/subtitle_" . $i . ".srt"); + } + } + ilUtil::sendSuccess($lng->txt("mob_srt_files_deleted"), true); + $ilCtrl->redirect($this, "listSubtitleFiles"); + } + + /** + * Upload multiple stubtitles + * + * @param + * @return + */ + public function uploadMultipleSubtitleFileFormObject() + { + $ilToolbar = $this->toolbar; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + ilUtil::sendInfo($lng->txt("mob_upload_multi_srt_howto")); + + $this->setPropertiesSubTabs("subtitles"); + + // upload file + $ilToolbar->setFormAction($ilCtrl->getFormAction($this), true); + include_once("./Services/Form/classes/class.ilFileInputGUI.php"); + $fi = new ilFileInputGUI($lng->txt("mob_subtitle_file") . " (.zip)", "subtitle_file"); + $fi->setSuffixes(array("zip")); + $ilToolbar->addInputItem($fi, true); + + $ilToolbar->addFormButton($lng->txt("upload"), "uploadMultipleSubtitleFile"); + } + + /** + * Upload multiple subtitles + */ + public function uploadMultipleSubtitleFileObject() + { + try { + $this->object->uploadMultipleSubtitleFile(ilUtil::stripSlashesArray($_FILES["subtitle_file"])); + $this->ctrl->redirect($this, "showMultiSubtitleConfirmationTable"); + } catch (ilMediaObjectsException $e) { + ilUtil::sendFailure($e->getMessage(), true); + $this->ctrl->redirect($this, "uploadMultipleSubtitleFileForm"); + } + } + + /** + * List of srt files in zip file + */ + public function showMultiSubtitleConfirmationTableObject() + { + $tpl = $this->tpl; + + $this->setPropertiesSubTabs("subtitles"); + + include_once("./Services/MediaObjects/classes/class.ilMultiSrtConfirmationTable2GUI.php"); + $tab = new ilMultiSrtConfirmationTable2GUI($this, "showMultiSubtitleConfirmationTable"); + $tpl->setContent($tab->getHTML()); + } + + /** + * Cancel Multi Feedback + */ + public function cancelMultiSrtObject() + { + $this->object->clearMultiSrtDirectory(); + $this->ctrl->redirect($this, "listSubtitleFiles"); + } + + /** + * Save selected srt files as new srt files + */ + public function saveMultiSrtObject() + { + $ilCtrl = $this->ctrl; + $srt_files = $this->object->getMultiSrtFiles(); + if (is_array($_POST["file"])) { + foreach ($_POST["file"] as $f) { + foreach ($srt_files as $srt_file) { + if ($f == $srt_file["filename"]) { + $this->object->uploadSrtFile($this->object->getMultiSrtUploadDir() . "/" . $srt_file["filename"], $srt_file["lang"], "rename"); + } + } + } + } + $this->object->clearMultiSrtDirectory(); + $ilCtrl->redirect($this, "listSubtitleFiles"); + } } -?> diff --git a/Services/MediaObjects/classes/class.ilObjMediaObjectsSettings.php b/Services/MediaObjects/classes/class.ilObjMediaObjectsSettings.php index de8dc99266cd8756022c2b8a0a0c8933b6e17007..ed26731e783e529309d1d8b88d07d4a75a7ecd43 100644 --- a/Services/MediaObjects/classes/class.ilObjMediaObjectsSettings.php +++ b/Services/MediaObjects/classes/class.ilObjMediaObjectsSettings.php @@ -5,85 +5,81 @@ require_once "./Services/Object/classes/class.ilObject.php"; /** * Class ilObjMediaObjectsSettings -* -* @author Alex Killing +* +* @author Alex Killing * @version $Id$ * * @ingroup ServicesMediaObjects */ class ilObjMediaObjectsSettings extends ilObject { - /** - * @var ilDB - */ - protected $db; - - - /** - * Constructor - * @access public - * @param integer reference_id or object_id - * @param boolean treat the id as reference_id (true) or object_id (false) - */ - function __construct($a_id = 0,$a_call_by_reference = true) - { - global $DIC; + /** + * @var ilDB + */ + protected $db; - $this->db = $DIC->database(); - $this->type = "mobs"; - parent::__construct($a_id,$a_call_by_reference); - } + + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + global $DIC; - /** - * update object data - * - * @access public - * @return boolean - */ - function update() - { - $ilDB = $this->db; - - if (!parent::update()) - { - return false; - } + $this->db = $DIC->database(); + $this->type = "mobs"; + parent::__construct($a_id, $a_call_by_reference); + } - return true; - } - - /** - * read - */ - function read() - { - $ilDB = $this->db; + /** + * update object data + * + * @access public + * @return boolean + */ + public function update() + { + $ilDB = $this->db; + + if (!parent::update()) { + return false; + } - parent::read(); + return true; + } + + /** + * read + */ + public function read() + { + $ilDB = $this->db; - } - + parent::read(); + } + - - + + - /** - * delete object and all related data - * - * @access public - * @return boolean true if all object data were removed; false if only a references were removed - */ - function delete() - { - // always call parent delete function first!! - if (!parent::delete()) - { - return false; - } - - //put here your module specific stuff - - return true; - } + /** + * delete object and all related data + * + * @access public + * @return boolean true if all object data were removed; false if only a references were removed + */ + public function delete() + { + // always call parent delete function first!! + if (!parent::delete()) { + return false; + } + + //put here your module specific stuff + + return true; + } } -?> diff --git a/Services/MediaObjects/classes/class.ilObjMediaObjectsSettingsAccess.php b/Services/MediaObjects/classes/class.ilObjMediaObjectsSettingsAccess.php index 73787e3a8e27d772a4319cab63ce258dd7f1fbb3..55c837c75fcc3937e1a1695532ad0d7f0ef4edf3 100644 --- a/Services/MediaObjects/classes/class.ilObjMediaObjectsSettingsAccess.php +++ b/Services/MediaObjects/classes/class.ilObjMediaObjectsSettingsAccess.php @@ -13,8 +13,4 @@ include_once("./Services/Object/classes/class.ilObjectAccess.php"); */ class ilObjMediaObjectsSettingsAccess extends ilObjectAccess { - - } - -?> \ No newline at end of file diff --git a/Services/MediaObjects/classes/class.ilObjMediaObjectsSettingsGUI.php b/Services/MediaObjects/classes/class.ilObjMediaObjectsSettingsGUI.php index 89e4f96d028d1d75df363234bf5fd5f0b64709f3..bc85f3e8fc5eab8c22f0fbae995c50d8b4cc65b3 100644 --- a/Services/MediaObjects/classes/class.ilObjMediaObjectsSettingsGUI.php +++ b/Services/MediaObjects/classes/class.ilObjMediaObjectsSettingsGUI.php @@ -16,231 +16,228 @@ include_once("./Services/Object/classes/class.ilObjectGUI.php"); */ class ilObjMediaObjectsSettingsGUI extends ilObjectGUI { - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * Contructor - * - * @access public - */ - public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) - { - global $DIC; - - $this->rbacsystem = $DIC->rbac()->system(); - $this->error = $DIC["ilErr"]; - $this->access = $DIC->access(); - $this->tabs = $DIC->tabs(); - $this->tpl = $DIC["tpl"]; - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $this->type = 'mobs'; - parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); - - $this->lng->loadLanguageModule('mob'); - $this->lng->loadLanguageModule('mep'); - $this->lng->loadLanguageModule('content'); - } - - /** - * Execute command - * - * @access public - * - */ - public function executeCommand() - { - $rbacsystem = $this->rbacsystem; - $ilErr = $this->error; - $ilAccess = $this->access; - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - $this->prepareOutput(); - - if(!$ilAccess->checkAccess('read','',$this->object->getRefId())) - { - $ilErr->raiseError($this->lng->txt('no_permission'),$ilErr->WARNING); - } - - switch($next_class) - { - case 'ilpermissiongui': - $this->tabs_gui->setTabActive('perm_settings'); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $ret = $this->ctrl->forwardCommand($perm_gui); - break; - - default: - if(!$cmd || $cmd == 'view') - { - $cmd = "editSettings"; - } - - $this->$cmd(); - break; - } - return true; - } - - /** - * Get tabs - * - * @access public - * - */ - public function getAdminTabs() - { - $rbacsystem = $this->rbacsystem; - $ilAccess = $this->access; - $ilTabs = $this->tabs; - - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - $ilTabs->addTarget("settings", - $this->ctrl->getLinkTarget($this, "editSettings"), - array("editSettings", "view")); - } - - if ($ilAccess->checkAccess('edit_permission', "", $this->object->getRefId())) - { - $ilTabs->addTarget("perm_settings", - $this->ctrl->getLinkTargetByClass('ilpermissiongui',"perm"), - array(),'ilpermissiongui'); - } - } - - /** - * Edit settings - */ - function editSettings($a_omit_init = false) - { - $tpl = $this->tpl; - - if (!$a_omit_init) - { - $this->initMediaObjectsSettingsForm(); - $this->getSettingsValues(); - } - $tpl->setContent($this->form->getHTML()); - } - - /** - * Save settings - */ - public function saveSettings() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->checkPermission("write"); - - $this->initMediaObjectsSettingsForm(); - if ($this->form->checkInput()) - { - // perform save - $mset = new ilSetting("mobs"); - $mset->set("mep_activate_pages", $_POST["activate_pages"]); - $mset->set("file_manager_always", $_POST["file_manager_always"]); - $mset->set("restricted_file_types", $_POST["restricted_file_types"]); - $mset->set("black_list_file_types", $_POST["black_list_file_types"]); - $mset->set("upload_dir", $_POST["mob_upload_dir"]); - - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "editSettings"); - } - - $this->form->setValuesByPost(); - $this->editSettings(true); - } - - /** - * Init media objects settings form. - */ - public function initMediaObjectsSettingsForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - // activate page in media pool - $cb = new ilCheckboxInputGUI($lng->txt("mobs_activate_pages"), "activate_pages"); - $cb->setInfo($lng->txt("mobs_activate_pages_info")); - $this->form->addItem($cb); - - // activate page in media pool - $cb = new ilCheckboxInputGUI($lng->txt("mobs_always_show_file_manager"), "file_manager_always"); - $cb->setInfo($lng->txt("mobs_always_show_file_manager_info")); - $this->form->addItem($cb); - - // allowed file types - $ta = new ilTextAreaInputGUI($this->lng->txt("mobs_restrict_file_types"), "restricted_file_types"); - //$ta->setCols(); - //$ta->setRows(); - $ta->setInfo($this->lng->txt("mobs_restrict_file_types_info")); - $this->form->addItem($ta); - - // black lis file types - $ta = new ilTextAreaInputGUI($this->lng->txt("mobs_black_list_file_types"), "black_list_file_types"); - $ta->setInfo($this->lng->txt("mobs_black_list_file_types_info")); - $this->form->addItem($ta); - - // Upload dir for learning resources - $tx_prop = new ilTextInputGUI($lng->txt("mob_upload_dir"), - "mob_upload_dir"); - $tx_prop->setInfo($lng->txt("mob_upload_dir_info")); - $this->form->addItem($tx_prop); - - if($ilAccess->checkAccess('write','',$this->object->getRefId())) - { - $this->form->addCommandButton("saveSettings", $lng->txt("save")); - } - - $this->form->setTitle($lng->txt("settings")); - $this->form->setFormAction($ilCtrl->getFormAction($this)); - } - - /** - * Get current values for form from - */ - public function getSettingsValues() - { - $values = array(); - - $mset = new ilSetting("mobs"); - $values["activate_pages"] = $mset->get("mep_activate_pages"); - $values["file_manager_always"] = $mset->get("file_manager_always"); - $values["restricted_file_types"] = $mset->get("restricted_file_types"); - $values["black_list_file_types"] = $mset->get("black_list_file_types"); - $values["mob_upload_dir"] = $mset->get("upload_dir"); - - $this->form->setValuesByArray($values); - } - + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * Contructor + * + * @access public + */ + public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) + { + global $DIC; + + $this->rbacsystem = $DIC->rbac()->system(); + $this->error = $DIC["ilErr"]; + $this->access = $DIC->access(); + $this->tabs = $DIC->tabs(); + $this->tpl = $DIC["tpl"]; + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->type = 'mobs'; + parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); + + $this->lng->loadLanguageModule('mob'); + $this->lng->loadLanguageModule('mep'); + $this->lng->loadLanguageModule('content'); + } + + /** + * Execute command + * + * @access public + * + */ + public function executeCommand() + { + $rbacsystem = $this->rbacsystem; + $ilErr = $this->error; + $ilAccess = $this->access; + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + $this->prepareOutput(); + + if (!$ilAccess->checkAccess('read', '', $this->object->getRefId())) { + $ilErr->raiseError($this->lng->txt('no_permission'), $ilErr->WARNING); + } + + switch ($next_class) { + case 'ilpermissiongui': + $this->tabs_gui->setTabActive('perm_settings'); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $ret = $this->ctrl->forwardCommand($perm_gui); + break; + + default: + if (!$cmd || $cmd == 'view') { + $cmd = "editSettings"; + } + + $this->$cmd(); + break; + } + return true; + } + + /** + * Get tabs + * + * @access public + * + */ + public function getAdminTabs() + { + $rbacsystem = $this->rbacsystem; + $ilAccess = $this->access; + $ilTabs = $this->tabs; + + if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) { + $ilTabs->addTarget( + "settings", + $this->ctrl->getLinkTarget($this, "editSettings"), + array("editSettings", "view") + ); + } + + if ($ilAccess->checkAccess('edit_permission', "", $this->object->getRefId())) { + $ilTabs->addTarget( + "perm_settings", + $this->ctrl->getLinkTargetByClass('ilpermissiongui', "perm"), + array(), + 'ilpermissiongui' + ); + } + } + + /** + * Edit settings + */ + public function editSettings($a_omit_init = false) + { + $tpl = $this->tpl; + + if (!$a_omit_init) { + $this->initMediaObjectsSettingsForm(); + $this->getSettingsValues(); + } + $tpl->setContent($this->form->getHTML()); + } + + /** + * Save settings + */ + public function saveSettings() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $this->checkPermission("write"); + + $this->initMediaObjectsSettingsForm(); + if ($this->form->checkInput()) { + // perform save + $mset = new ilSetting("mobs"); + $mset->set("mep_activate_pages", $_POST["activate_pages"]); + $mset->set("file_manager_always", $_POST["file_manager_always"]); + $mset->set("restricted_file_types", $_POST["restricted_file_types"]); + $mset->set("black_list_file_types", $_POST["black_list_file_types"]); + $mset->set("upload_dir", $_POST["mob_upload_dir"]); + + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "editSettings"); + } + + $this->form->setValuesByPost(); + $this->editSettings(true); + } + + /** + * Init media objects settings form. + */ + public function initMediaObjectsSettingsForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + // activate page in media pool + $cb = new ilCheckboxInputGUI($lng->txt("mobs_activate_pages"), "activate_pages"); + $cb->setInfo($lng->txt("mobs_activate_pages_info")); + $this->form->addItem($cb); + + // activate page in media pool + $cb = new ilCheckboxInputGUI($lng->txt("mobs_always_show_file_manager"), "file_manager_always"); + $cb->setInfo($lng->txt("mobs_always_show_file_manager_info")); + $this->form->addItem($cb); + + // allowed file types + $ta = new ilTextAreaInputGUI($this->lng->txt("mobs_restrict_file_types"), "restricted_file_types"); + //$ta->setCols(); + //$ta->setRows(); + $ta->setInfo($this->lng->txt("mobs_restrict_file_types_info")); + $this->form->addItem($ta); + + // black lis file types + $ta = new ilTextAreaInputGUI($this->lng->txt("mobs_black_list_file_types"), "black_list_file_types"); + $ta->setInfo($this->lng->txt("mobs_black_list_file_types_info")); + $this->form->addItem($ta); + + // Upload dir for learning resources + $tx_prop = new ilTextInputGUI( + $lng->txt("mob_upload_dir"), + "mob_upload_dir" + ); + $tx_prop->setInfo($lng->txt("mob_upload_dir_info")); + $this->form->addItem($tx_prop); + + if ($ilAccess->checkAccess('write', '', $this->object->getRefId())) { + $this->form->addCommandButton("saveSettings", $lng->txt("save")); + } + + $this->form->setTitle($lng->txt("settings")); + $this->form->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * Get current values for form from + */ + public function getSettingsValues() + { + $values = array(); + + $mset = new ilSetting("mobs"); + $values["activate_pages"] = $mset->get("mep_activate_pages"); + $values["file_manager_always"] = $mset->get("file_manager_always"); + $values["restricted_file_types"] = $mset->get("restricted_file_types"); + $values["black_list_file_types"] = $mset->get("black_list_file_types"); + $values["mob_upload_dir"] = $mset->get("upload_dir"); + + $this->form->setValuesByArray($values); + } } -?> \ No newline at end of file diff --git a/Services/MediaObjects/classes/class.ilPlayerUtil.php b/Services/MediaObjects/classes/class.ilPlayerUtil.php index c8aa286bdff277acf3aa3d72946b891483ed61bb..b252739fe711c57e4e029c7ee309bf06d5fb9d6e 100644 --- a/Services/MediaObjects/classes/class.ilPlayerUtil.php +++ b/Services/MediaObjects/classes/class.ilPlayerUtil.php @@ -3,114 +3,110 @@ /* Copyright (c) 1998-2011 ILIAS open source, Extended GPL, see docs/LICENSE */ /** - * Audio/Video Player Utility + * Audio/Video Player Utility * * @author Alex Killing * @version $Id$ - * @ingroup + * @ingroup */ class ilPlayerUtil { - /** - * Get local path of jQuery file - */ - static function getLocalMediaElementJsPath() - { - return "./libs/bower/bower_components/mediaelement/build/mediaelement-and-player.min.js"; - } + /** + * Get local path of jQuery file + */ + public static function getLocalMediaElementJsPath() + { + return "./libs/bower/bower_components/mediaelement/build/mediaelement-and-player.min.js"; + } - /** - * Get local path of jQuery file - */ - static function getLocalMediaElementCssPath() - { - return "./libs/bower/bower_components/mediaelement/build/mediaelementplayer.min.css"; - } + /** + * Get local path of jQuery file + */ + public static function getLocalMediaElementCssPath() + { + return "./libs/bower/bower_components/mediaelement/build/mediaelementplayer.min.css"; + } - /** - * Init mediaelement.js scripts - */ - static function initMediaElementJs($a_tpl = null) - { - global $DIC; + /** + * Init mediaelement.js scripts + */ + public static function initMediaElementJs($a_tpl = null) + { + global $DIC; - $tpl = $DIC["tpl"]; - - if ($a_tpl == null) - { - $a_tpl = $tpl; - } - - foreach (self::getJsFilePaths() as $js_path) - { - $a_tpl->addJavaScript($js_path); - } - foreach (self::getCssFilePaths() as $css_path) - { - $a_tpl->addCss($css_path); - } - } - - /** - * Get css file paths - * - * @param - * @return - */ - static function getCssFilePaths() - { - return array(self::getLocalMediaElementCssPath()); - } - - /** - * Get js file paths - * - * @param - * @return - */ - static function getJsFilePaths() - { - return array(self::getLocalMediaElementJsPath()); - } - + $tpl = $DIC["tpl"]; + + if ($a_tpl == null) { + $a_tpl = $tpl; + } + + foreach (self::getJsFilePaths() as $js_path) { + $a_tpl->addJavaScript($js_path); + } + foreach (self::getCssFilePaths() as $css_path) { + $a_tpl->addCss($css_path); + } + } + + /** + * Get css file paths + * + * @param + * @return + */ + public static function getCssFilePaths() + { + return array(self::getLocalMediaElementCssPath()); + } + + /** + * Get js file paths + * + * @param + * @return + */ + public static function getJsFilePaths() + { + return array(self::getLocalMediaElementJsPath()); + } + - /** - * Get flash video player directory - * - * @return - */ - static function getFlashVideoPlayerDirectory() - { - return "libs/bower/bower_components/mediaelement/build"; - } - - - /** - * Get flash video player file name - * - * @return - */ - static function getFlashVideoPlayerFilename($a_fullpath = false) - { - $file = "flashmediaelement.swf"; - if ($a_fullpath) - { - return self::getFlashVideoPlayerDirectory()."/".$file; - } - return $file; - } - - /** - * Copy css files to target dir - * - * @param - * @return - */ - static function copyPlayerFilesToTargetDirectory($a_target_dir) - { - ilUtil::rCopy("./libs/bower/bower_components/mediaelement/build", - $a_target_dir); - } - + /** + * Get flash video player directory + * + * @return + */ + public static function getFlashVideoPlayerDirectory() + { + return "libs/bower/bower_components/mediaelement/build"; + } + + + /** + * Get flash video player file name + * + * @return + */ + public static function getFlashVideoPlayerFilename($a_fullpath = false) + { + $file = "flashmediaelement.swf"; + if ($a_fullpath) { + return self::getFlashVideoPlayerDirectory() . "/" . $file; + } + return $file; + } + + /** + * Copy css files to target dir + * + * @param + * @return + */ + public static function copyPlayerFilesToTargetDirectory($a_target_dir) + { + ilUtil::rCopy( + "./libs/bower/bower_components/mediaelement/build", + $a_target_dir + ); + } } - diff --git a/Services/MediaObjects/classes/class.ilWidthHeightInputGUI.php b/Services/MediaObjects/classes/class.ilWidthHeightInputGUI.php index a68165b252eb40468be83d7667c500e6f244614d..021da4fe55cfabbd5ab87f41f34f188fea6e5adb 100755 --- a/Services/MediaObjects/classes/class.ilWidthHeightInputGUI.php +++ b/Services/MediaObjects/classes/class.ilWidthHeightInputGUI.php @@ -5,185 +5,176 @@ /** * This class represents a width/height item in a property form. * -* @author Alex Killing +* @author Alex Killing * @version $Id$ * @ingroup ServicesMediaObjects */ class ilWidthHeightInputGUI extends ilFormPropertyGUI { - /** - * @var ilObjUser - */ - protected $user; - - protected $value; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; - - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - parent::__construct($a_title, $a_postvar); - $this->setType("width_height"); - $this->dirs = array("width", "height"); - } - - /** - * Set Width. - * - * @param integer $a_width Width - */ - function setWidth($a_width) - { - $this->width = $a_width; - } - - /** - * Get Width. - * - * @return integer Width - */ - function getWidth() - { - return $this->width; - } - - /** - * Set Height. - * - * @param integer $a_height Height - */ - function setHeight($a_height) - { - $this->height = $a_height; - } - - /** - * Get Height. - * - * @return integer Height - */ - function getHeight() - { - return $this->height; - } - - /** - * Set Constrain Proportions. - * - * @param boolean $a_constrainproportions Constrain Proportions - */ - function setConstrainProportions($a_constrainproportions) - { - $this->constrainproportions = $a_constrainproportions; - } - - /** - * Get Constrain Proportions. - * - * @return boolean Constrain Proportions - */ - function getConstrainProportions() - { - return $this->constrainproportions; - } - - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - foreach ($this->dirs as $dir) - { - $pre_value = $_POST[$this->getPostVar()][$dir] = - ilUtil::stripSlashes($_POST[$this->getPostVar()][$dir]); - - /* - if ($this->getRequired() && trim($num_value) == "") - { - $this->setAlert($lng->txt("msg_input_is_required")); - - return false; - }*/ - - $value = $pre_value; - - if (trim($value) != "") - { - switch ($dir) - { - case "width": $this->setWidth($value); break; - case "height": $this->setHeight($value); break; - } - } - - } - - return true; - } - - /** - * Insert property html - */ - function insert($a_tpl) - { - $lng = $this->lng; - - $tpl = new ilTemplate("tpl.prop_width_height.html", true, true, "Services/MediaObjects"); - - foreach ($this->dirs as $dir) - { - switch($dir) - { - case "width": $value = strtolower(trim($this->getWidth())); break; - case "height": $value = strtolower(trim($this->getHeight())); break; - } - $tpl->setVariable("VAL_".strtoupper($dir), $value); - } - if ($this->getConstrainProportions()) - { - $tpl->setVariable("CHECKED", 'checked="checked"'); - } - - $tpl->setVariable("POST_VAR", $this->getPostVar()); - $tpl->setVariable("TXT_CONSTR_PROP", $lng->txt("cont_constrain_proportions")); - $wh_ratio = 0; - if ((int) $this->getHeight() > 0) - { - $wh_ratio = (int) $this->getWidth() / (int) $this->getHeight(); - } - $tpl->setVariable("WH_RATIO", str_replace(",", ".", round($wh_ratio, 6))); - - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $tpl->get()); - $a_tpl->parseCurrentBlock(); - - $GLOBALS["tpl"]->addJavascript("./Services/MediaObjects/js/ServiceMediaObjectPropWidthHeight.js"); - } - - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $ilUser = $this->user; -//var_dump($a_values[$this->getPostVar()]); - $this->setWidth($a_values[$this->getPostVar()]["width"]); - $this->setHeight($a_values[$this->getPostVar()]["height"]); - $this->setConstrainProportions($a_values[$this->getPostVar()]["constr_prop"]); - } - + /** + * @var ilObjUser + */ + protected $user; + + protected $value; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; + + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + parent::__construct($a_title, $a_postvar); + $this->setType("width_height"); + $this->dirs = array("width", "height"); + } + + /** + * Set Width. + * + * @param integer $a_width Width + */ + public function setWidth($a_width) + { + $this->width = $a_width; + } + + /** + * Get Width. + * + * @return integer Width + */ + public function getWidth() + { + return $this->width; + } + + /** + * Set Height. + * + * @param integer $a_height Height + */ + public function setHeight($a_height) + { + $this->height = $a_height; + } + + /** + * Get Height. + * + * @return integer Height + */ + public function getHeight() + { + return $this->height; + } + + /** + * Set Constrain Proportions. + * + * @param boolean $a_constrainproportions Constrain Proportions + */ + public function setConstrainProportions($a_constrainproportions) + { + $this->constrainproportions = $a_constrainproportions; + } + + /** + * Get Constrain Proportions. + * + * @return boolean Constrain Proportions + */ + public function getConstrainProportions() + { + return $this->constrainproportions; + } + + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + foreach ($this->dirs as $dir) { + $pre_value = $_POST[$this->getPostVar()][$dir] = + ilUtil::stripSlashes($_POST[$this->getPostVar()][$dir]); + + /* + if ($this->getRequired() && trim($num_value) == "") + { + $this->setAlert($lng->txt("msg_input_is_required")); + + return false; + }*/ + + $value = $pre_value; + + if (trim($value) != "") { + switch ($dir) { + case "width": $this->setWidth($value); break; + case "height": $this->setHeight($value); break; + } + } + } + + return true; + } + + /** + * Insert property html + */ + public function insert($a_tpl) + { + $lng = $this->lng; + + $tpl = new ilTemplate("tpl.prop_width_height.html", true, true, "Services/MediaObjects"); + + foreach ($this->dirs as $dir) { + switch ($dir) { + case "width": $value = strtolower(trim($this->getWidth())); break; + case "height": $value = strtolower(trim($this->getHeight())); break; + } + $tpl->setVariable("VAL_" . strtoupper($dir), $value); + } + if ($this->getConstrainProportions()) { + $tpl->setVariable("CHECKED", 'checked="checked"'); + } + + $tpl->setVariable("POST_VAR", $this->getPostVar()); + $tpl->setVariable("TXT_CONSTR_PROP", $lng->txt("cont_constrain_proportions")); + $wh_ratio = 0; + if ((int) $this->getHeight() > 0) { + $wh_ratio = (int) $this->getWidth() / (int) $this->getHeight(); + } + $tpl->setVariable("WH_RATIO", str_replace(",", ".", round($wh_ratio, 6))); + + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $tpl->get()); + $a_tpl->parseCurrentBlock(); + + $GLOBALS["tpl"]->addJavascript("./Services/MediaObjects/js/ServiceMediaObjectPropWidthHeight.js"); + } + + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $ilUser = $this->user; + //var_dump($a_values[$this->getPostVar()]); + $this->setWidth($a_values[$this->getPostVar()]["width"]); + $this->setHeight($a_values[$this->getPostVar()]["height"]); + $this->setConstrainProportions($a_values[$this->getPostVar()]["constr_prop"]); + } } diff --git a/Services/MediaObjects/exceptions/class.ilFFmpegException.php b/Services/MediaObjects/exceptions/class.ilFFmpegException.php index f0cff298afee764321d56f2291fe0bf6ef6ac820..cdae4a69babe48582f000bfbc34e360de0b6d671 100644 --- a/Services/MediaObjects/exceptions/class.ilFFmpegException.php +++ b/Services/MediaObjects/exceptions/class.ilFFmpegException.php @@ -1,27 +1,26 @@ - * @version $Id$ - * + * @version $Id$ + * */ class ilFFmpegException extends ilException { - /** - * Constructor - * - * A message is not optional as in build in class Exception - * - * @param string $a_message message - */ - public function __construct($a_message) - { - parent::__construct($a_message); - } + /** + * Constructor + * + * A message is not optional as in build in class Exception + * + * @param string $a_message message + */ + public function __construct($a_message) + { + parent::__construct($a_message); + } } -?> diff --git a/Services/MediaObjects/exceptions/class.ilMediaObjectsException.php b/Services/MediaObjects/exceptions/class.ilMediaObjectsException.php index a9c843ba726188a97ae2acd1f741a1b0f5103bd1..245ff5b0fb5633ff8a2102bdbc7b1981aa65f837 100644 --- a/Services/MediaObjects/exceptions/class.ilMediaObjectsException.php +++ b/Services/MediaObjects/exceptions/class.ilMediaObjectsException.php @@ -12,16 +12,15 @@ require_once 'Services/Exceptions/classes/class.ilException.php'; */ class ilMediaObjectsException extends ilException { - /** - * Constructor - * - * A message is not optional as in build in class Exception - * - * @param string $a_message message - */ - public function __construct($a_message) - { - parent::__construct($a_message); - } + /** + * Constructor + * + * A message is not optional as in build in class Exception + * + * @param string $a_message message + */ + public function __construct($a_message) + { + parent::__construct($a_message); + } } -?> \ No newline at end of file diff --git a/Services/MediaObjects/exceptions/class.ilMobSrtUploadException.php b/Services/MediaObjects/exceptions/class.ilMobSrtUploadException.php index 9033b5f868b13c02a224cdc3ec5b5ede400e18da..dd6f95209d9c15ac048dcdcebe3b8bdacef9cd56 100644 --- a/Services/MediaObjects/exceptions/class.ilMobSrtUploadException.php +++ b/Services/MediaObjects/exceptions/class.ilMobSrtUploadException.php @@ -13,4 +13,3 @@ require_once 'Services/Exceptions/classes/class.ilException.php'; class ilMobSrtUploadException extends ilException { } -?> diff --git a/Services/MediaObjects/interfaces/interface.ilMobMultiSrtInt.php b/Services/MediaObjects/interfaces/interface.ilMobMultiSrtInt.php index b223b5f301b4ac416ea477f7db172ae3994e5100..246d6133ce03a21db2f060a65ce43fdcd16a8f4c 100644 --- a/Services/MediaObjects/interfaces/interface.ilMobMultiSrtInt.php +++ b/Services/MediaObjects/interfaces/interface.ilMobMultiSrtInt.php @@ -7,13 +7,13 @@ */ interface ilMobMultiSrtInt { - /** - * @return string upload directory - */ - function getUploadDir(); + /** + * @return string upload directory + */ + public function getUploadDir(); - /** - * @return array array of target media objects ids - */ - function getMobIds(); -} \ No newline at end of file + /** + * @return array array of target media objects ids + */ + public function getMobIds(); +} diff --git a/Services/Multilingualism/classes/class.ilMultilingualism.php b/Services/Multilingualism/classes/class.ilMultilingualism.php index 3b89f9f5633aada2087e3313e86bcf12b0deee5d..da583230d4f3d78ad347b5af637f2fe3f48b98f4 100644 --- a/Services/Multilingualism/classes/class.ilMultilingualism.php +++ b/Services/Multilingualism/classes/class.ilMultilingualism.php @@ -28,348 +28,326 @@ */ class ilMultilingualism { - /** - * @var ilLanguage - */ - protected $lng; - - protected $db; - protected $obj_id; - protected $languages = array(); - protected $type = ""; - static protected $instances = array(); - - /** - * Constructor - * - * @param int $a_obj_id object id - * @param string $a_type id type - * @throws ilObjectException - */ - private function __construct($a_obj_id, $a_type) - { - global $DIC; - - $this->lng = $DIC->language(); - $ilDB = $DIC->database(); - - $this->db = $ilDB; - - $this->setObjId($a_obj_id); - $this->setType($a_type); - - if ($this->getObjId() <= 0) - { - include_once("./Services/Object/exceptions/class.ilObjectException.php"); - throw new ilObjectException("ilObjectTranslation: No object ID passed."); - } - - $this->read(); - } - - /** - * Get instance - * - * @param integer $a_obj_id (repository) object id - * @return ilMultilingualism translation object - */ - static function getInstance($a_obj_id, $a_type) - { - if (!isset(self::$instances[$a_type][$a_obj_id])) - { - self::$instances[$a_type][$a_obj_id] = new self($a_obj_id, $a_type); - } - - return self::$instances[$a_type][$a_obj_id]; - } - - - /** - * Set object id - * - * @param int $a_val object id - */ - function setObjId($a_val) - { - $this->obj_id = $a_val; - } - - /** - * Get object id - * - * @return int object id - */ - function getObjId() - { - return $this->obj_id; - } - - /** - * Set languages - * - * @param array $a_val array of language codes - */ - function setLanguages(array $a_val) - { - $this->languages = $a_val; - } - - /** - * Get languages - * - * @return array array of language codes - */ - function getLanguages() - { - return $this->languages; - } - - /** - * @return string - */ - public function getType() - { - return $this->type; - } - - /** - * @param string $type - */ - public function setType($type) - { - $this->type = $type; - } - - public function getDefaultLanguage() - { - $lng = $this->lng; - - foreach($this->languages as $k => $v) - { - if($v["lang_default"]) - { - return $k; - } - } - - return $lng->getDefaultLanguage(); - } - - - /** - * Add language - * - * @param string $a_lang language - * @param string $a_title title - * @param string $a_description description - * @param bool $a_default default language? - */ - function addLanguage($a_lang, $a_title, $a_description, $a_default, $a_force = false) - { - if ($a_lang != "" && (!isset($this->languages[$a_lang]) || $a_force)) - { - if ($a_default) - { - foreach ($this->languages as $k => $l) - { - $this->languages[$k]["lang_default"] = false; - } - } - $this->languages[$a_lang] = array("lang_code" => $a_lang, "lang_default" => $a_default, - "title" => $a_title, "description" => $a_description); - } - } - - /** - * Get default title - * - * @return string title of default language - */ - function getDefaultTitle() - { - foreach ($this->languages as $l) - { - if ($l["lang_default"]) - { - return $l["title"]; - } - } - return ""; - } - - /** - * Set default title - * - * @param string $a_title title - */ - function setDefaultTitle($a_title) - { - foreach ($this->languages as $k => $l) - { - if ($l["lang_default"]) - { - $this->languages[$k]["title"] = $a_title; - } - } - } - - /** - * Get default description - * - * @return string description of default language - */ - function getDefaultDescription() - { - foreach ($this->languages as $l) - { - if ($l["lang_default"]) - { - return $l["description"]; - } - } - return ""; - } - - /** - * Set default description - * - * @param string $a_description description - */ - function setDefaultDescription($a_description) - { - foreach ($this->languages as $k => $l) - { - if ($l["lang_default"]) - { - $this->languages[$k]["description"] = $a_description; - } - } - } - - - /** - * Remove language - * - * @param string $a_lang language code - */ - function removeLanguage($a_lang) - { - if($a_lang != $this->getDefaultLanguage()) - { - unset($this->languages[$a_lang]); - } - } - - /** - * Read - */ - function read() - { - $this->setLanguages(array()); - $set = $this->db->query("SELECT * FROM il_translations ". - " WHERE id = ".$this->db->quote($this->getObjId(), "integer") . - " AND id_type = " . $this->db->quote($this->getType(), "text") - ); - while ($rec = $this->db->fetchAssoc($set)) - { - $this->addLanguage($rec["lang_code"], $rec["title"], $rec["description"], $rec["lang_default"]); - } - } - - /** - * Delete - */ - function delete() - { - $this->db->manipulate("DELETE FROM il_translations ". - " WHERE id = ".$this->db->quote($this->getObjId(), "integer"). - " AND id_type = " . $this->db->quote($this->getType(), "text") - ); - } - - /** - * Save - */ - function save() - { - $this->delete(); - - foreach ($this->getLanguages() as $l => $trans) - { - $this->db->manipulate($t = "INSERT INTO il_translations ". - "(id, id_type, title, description, lang_code, lang_default) VALUES (". - $this->db->quote($this->getObjId(), "integer").",". - $this->db->quote($this->getType(), "text").",". - $this->db->quote($trans["title"], "text").",". - $this->db->quote($trans["description"], "text").",". - $this->db->quote($l, "text").",". - $this->db->quote($trans["lang_default"], "integer"). - ")"); - } - } - - /** - * Copy multilinguality settings - * - * @param string $a_type parent object type - * @param int $a_obj_id parent object id - * @return ilObjectTranslation target multilang object - */ - function copy($a_obj_id) - { - $target_ml = new self($a_obj_id, $this->getType()); - $target_ml->setLanguages($this->getLanguages()); - $target_ml->save(); - return $target_ml; - } - - - - /** - * Export - * @param ilXmlWriter $writer - * @return ilXmlWriter - */ - public function toXml(ilXmlWriter $writer) - { - $writer->xmlStartTag('translations'); - - foreach ($this->getLanguages() as $k => $v) - { - $writer->xmlStartTag('translation',array('language' => $k, 'default' => $v['lang_default'] ? 1 : 0)); - $writer->xmlElement('title',array(),$v['title']); - $writer->xmlElement('description', array(), $v['description']); - $writer->xmlEndTag('translation'); - } - $writer->xmlEndTag('translations'); - - return $writer; - } - - /** - * xml import - * - * @param SimpleXMLElement $root - * @return mixed - */ - public function fromXML(SimpleXMLElement $root) - { - if($root->translations) - { - $root = $root->translations; - } - - foreach($root->translation as $trans) - { - $this->addLanguage( - (string)trim($trans["language"]), - (string)trim($trans->title), - (string)trim($trans->description), - (int)$trans["default"] != 0?true:false - ); - } - } - + /** + * @var ilLanguage + */ + protected $lng; + + protected $db; + protected $obj_id; + protected $languages = array(); + protected $type = ""; + protected static $instances = array(); + + /** + * Constructor + * + * @param int $a_obj_id object id + * @param string $a_type id type + * @throws ilObjectException + */ + private function __construct($a_obj_id, $a_type) + { + global $DIC; + + $this->lng = $DIC->language(); + $ilDB = $DIC->database(); + + $this->db = $ilDB; + + $this->setObjId($a_obj_id); + $this->setType($a_type); + + if ($this->getObjId() <= 0) { + include_once("./Services/Object/exceptions/class.ilObjectException.php"); + throw new ilObjectException("ilObjectTranslation: No object ID passed."); + } + + $this->read(); + } + + /** + * Get instance + * + * @param integer $a_obj_id (repository) object id + * @return ilMultilingualism translation object + */ + public static function getInstance($a_obj_id, $a_type) + { + if (!isset(self::$instances[$a_type][$a_obj_id])) { + self::$instances[$a_type][$a_obj_id] = new self($a_obj_id, $a_type); + } + + return self::$instances[$a_type][$a_obj_id]; + } + + + /** + * Set object id + * + * @param int $a_val object id + */ + public function setObjId($a_val) + { + $this->obj_id = $a_val; + } + + /** + * Get object id + * + * @return int object id + */ + public function getObjId() + { + return $this->obj_id; + } + + /** + * Set languages + * + * @param array $a_val array of language codes + */ + public function setLanguages(array $a_val) + { + $this->languages = $a_val; + } + + /** + * Get languages + * + * @return array array of language codes + */ + public function getLanguages() + { + return $this->languages; + } + + /** + * @return string + */ + public function getType() + { + return $this->type; + } + + /** + * @param string $type + */ + public function setType($type) + { + $this->type = $type; + } + + public function getDefaultLanguage() + { + $lng = $this->lng; + + foreach ($this->languages as $k => $v) { + if ($v["lang_default"]) { + return $k; + } + } + + return $lng->getDefaultLanguage(); + } + + + /** + * Add language + * + * @param string $a_lang language + * @param string $a_title title + * @param string $a_description description + * @param bool $a_default default language? + */ + public function addLanguage($a_lang, $a_title, $a_description, $a_default, $a_force = false) + { + if ($a_lang != "" && (!isset($this->languages[$a_lang]) || $a_force)) { + if ($a_default) { + foreach ($this->languages as $k => $l) { + $this->languages[$k]["lang_default"] = false; + } + } + $this->languages[$a_lang] = array("lang_code" => $a_lang, "lang_default" => $a_default, + "title" => $a_title, "description" => $a_description); + } + } + + /** + * Get default title + * + * @return string title of default language + */ + public function getDefaultTitle() + { + foreach ($this->languages as $l) { + if ($l["lang_default"]) { + return $l["title"]; + } + } + return ""; + } + + /** + * Set default title + * + * @param string $a_title title + */ + public function setDefaultTitle($a_title) + { + foreach ($this->languages as $k => $l) { + if ($l["lang_default"]) { + $this->languages[$k]["title"] = $a_title; + } + } + } + + /** + * Get default description + * + * @return string description of default language + */ + public function getDefaultDescription() + { + foreach ($this->languages as $l) { + if ($l["lang_default"]) { + return $l["description"]; + } + } + return ""; + } + + /** + * Set default description + * + * @param string $a_description description + */ + public function setDefaultDescription($a_description) + { + foreach ($this->languages as $k => $l) { + if ($l["lang_default"]) { + $this->languages[$k]["description"] = $a_description; + } + } + } + + + /** + * Remove language + * + * @param string $a_lang language code + */ + public function removeLanguage($a_lang) + { + if ($a_lang != $this->getDefaultLanguage()) { + unset($this->languages[$a_lang]); + } + } + + /** + * Read + */ + public function read() + { + $this->setLanguages(array()); + $set = $this->db->query( + "SELECT * FROM il_translations " . + " WHERE id = " . $this->db->quote($this->getObjId(), "integer") . + " AND id_type = " . $this->db->quote($this->getType(), "text") + ); + while ($rec = $this->db->fetchAssoc($set)) { + $this->addLanguage($rec["lang_code"], $rec["title"], $rec["description"], $rec["lang_default"]); + } + } + + /** + * Delete + */ + public function delete() + { + $this->db->manipulate( + "DELETE FROM il_translations " . + " WHERE id = " . $this->db->quote($this->getObjId(), "integer") . + " AND id_type = " . $this->db->quote($this->getType(), "text") + ); + } + + /** + * Save + */ + public function save() + { + $this->delete(); + + foreach ($this->getLanguages() as $l => $trans) { + $this->db->manipulate($t = "INSERT INTO il_translations " . + "(id, id_type, title, description, lang_code, lang_default) VALUES (" . + $this->db->quote($this->getObjId(), "integer") . "," . + $this->db->quote($this->getType(), "text") . "," . + $this->db->quote($trans["title"], "text") . "," . + $this->db->quote($trans["description"], "text") . "," . + $this->db->quote($l, "text") . "," . + $this->db->quote($trans["lang_default"], "integer") . + ")"); + } + } + + /** + * Copy multilinguality settings + * + * @param string $a_type parent object type + * @param int $a_obj_id parent object id + * @return ilObjectTranslation target multilang object + */ + public function copy($a_obj_id) + { + $target_ml = new self($a_obj_id, $this->getType()); + $target_ml->setLanguages($this->getLanguages()); + $target_ml->save(); + return $target_ml; + } + + + + /** + * Export + * @param ilXmlWriter $writer + * @return ilXmlWriter + */ + public function toXml(ilXmlWriter $writer) + { + $writer->xmlStartTag('translations'); + + foreach ($this->getLanguages() as $k => $v) { + $writer->xmlStartTag('translation', array('language' => $k, 'default' => $v['lang_default'] ? 1 : 0)); + $writer->xmlElement('title', array(), $v['title']); + $writer->xmlElement('description', array(), $v['description']); + $writer->xmlEndTag('translation'); + } + $writer->xmlEndTag('translations'); + + return $writer; + } + + /** + * xml import + * + * @param SimpleXMLElement $root + * @return mixed + */ + public function fromXML(SimpleXMLElement $root) + { + if ($root->translations) { + $root = $root->translations; + } + + foreach ($root->translation as $trans) { + $this->addLanguage( + (string) trim($trans["language"]), + (string) trim($trans->title), + (string) trim($trans->description), + (int) $trans["default"] != 0?true:false + ); + } + } } - -?> \ No newline at end of file diff --git a/Services/Multilingualism/classes/class.ilMultilingualismGUI.php b/Services/Multilingualism/classes/class.ilMultilingualismGUI.php index 4e6514ab45ec9e20df57d3adadbc92154fa417e6..8443956762ed8d751027503958be54151eab1b66 100644 --- a/Services/Multilingualism/classes/class.ilMultilingualismGUI.php +++ b/Services/Multilingualism/classes/class.ilMultilingualismGUI.php @@ -13,454 +13,409 @@ */ class ilMultilingualismGUI { - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilObjUser - */ - protected $user; - - protected $obj_trans; - protected $title_descr_only = true; - protected $start_title = ""; - protected $start_description = ""; - - /** - * ilTranslationGUI constructor. - * @param int $a_obj_id - * @param stirng $a_type - */ - function __construct($a_obj_id, $a_type) - { - global $DIC; - - $this->toolbar = $DIC->toolbar(); - $this->user = $DIC->user(); - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $tpl = $DIC["tpl"]; - - $this->lng = $lng; - $this->ctrl = $ilCtrl; - $this->tpl = $tpl; - - include_once("./Services/Multilingualism/classes/class.ilMultilingualism.php"); - $this->obj_trans = ilMultilingualism::getInstance($a_obj_id, $a_type); - } - - /** - * Set enable title/description only mode - * - * @param bool $a_val enable title/description only mode - */ - function setTitleDescrOnlyMode($a_val) - { - $this->title_descr_only = $a_val; - } - - /** - * Get enable title/description only mode - * - * @return bool enable title/description only mode - */ - function getTitleDescrOnlyMode() - { - return $this->title_descr_only; - } - - /** - * Execute command - */ - function executeCommand() - { - $next_class = $this->ctrl->getNextClass($this); - - switch ($next_class) - { - default: - $cmd = $this->ctrl->getCmd("listTranslations"); - if (in_array($cmd, array("listTranslations", "saveTranslations", - "addTranslation", "deleteTranslations", "activateContentMultilinguality", - "confirmRemoveLanguages", "removeLanguages", "confirmDeactivateContentMultiLang", "saveLanguages", - "saveContentTranslationActivation", "deactivateContentMultiLang", "addLanguages"))) - { - $this->$cmd(); - } - break; - } - } - - /** - * List translations - */ - function listTranslations($a_get_post_values = false, $a_add = false) - { - $this->lng->loadLanguageModule("translation"); - - - $this->addToolbar(); - - include_once("./Services/Multilingualism/classes/class.ilMultilingualismTableGUI.php"); - $table = new ilMultilingualismTableGUI($this, "listTranslations", true, - "Translation"); - 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->obj_trans->getLanguages(); - foreach($data as $k => $v) - { - $data[$k]["default"] = $v["lang_default"]; - $data[$k]["desc"] = $v["description"]; - $data[$k]["lang"] = $v["lang_code"]; - } - if($a_add) - { - $data["Fobject"][++$k]["title"] = ""; - } - $table->setData($data); - } - $this->tpl->setContent($table->getHTML()); - - } - - function addToolbar() - { - $ilToolbar = $this->toolbar; - if ($this->getTitleDescrOnlyMode()) - { - $ilToolbar->addButton($this->lng->txt("obj_add_languages"), - $this->ctrl->getLinkTarget($this, "addLanguages")); - } - } - - /** - * Save translations - */ - function saveTranslations() - { - // default language set? - if (!isset($_POST["default"])) - { - ilUtil::sendFailure($this->lng->txt("msg_no_default_language")); - $this->listTranslations(true); - return; - } - - // all languages set? - if (array_key_exists("",$_POST["lang"])) - { - ilUtil::sendFailure($this->lng->txt("msg_no_language_selected")); - $this->listTranslations(true); - return; - } - - // no single language is selected more than once? - if (count(array_unique($_POST["lang"])) < count($_POST["lang"])) - { - ilUtil::sendFailure($this->lng->txt("msg_multi_language_selected")); - $this->listTranslations(true); - return; - } - - // save the stuff - $this->obj_trans->setLanguages(array()); - - foreach($_POST["title"] as $k => $v) - { - // update object data if default - $is_default = ($_POST["default"] == $k); - - $this->obj_trans->addLanguage(ilUtil::stripSlashes($_POST["lang"][$k]), - ilUtil::stripSlashes($v), - ilUtil::stripSlashes($_POST["desc"][$k]), - $is_default - ); - } - $this->obj_trans->save(); - - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "listTranslations"); - - } - - /** - * Remove translation - */ - function deleteTranslations() - { - foreach($_POST["title"] as $k => $v) - { - if ($_POST["check"][$k]) - { - // default translation cannot be deleted - if($k != $_POST["default"]) - { - unset($_POST["title"][$k]); - unset($_POST["desc"][$k]); - unset($_POST["lang"][$k]); - } - else - { - ilUtil::sendFailure($this->lng->txt("msg_no_default_language")); - $this->listTranslations(); - return; - } - } - } - $this->saveTranslations(); - } - - //// - //// Content translation - //// - - /** - * Get multi language form - */ - function getMultiLangForm($a_add = false) - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - - // master language - if (!$a_add) - { - include_once("./Services/MetaData/classes/class.ilMDLanguageItem.php"); - $options = ilMDLanguageItem::_getLanguages(); - $si = new ilSelectInputGUI($lng->txt("obj_master_lang"), "master_lang"); - $si->setOptions($options); - $si->setValue($ilUser->getLanguage()); - $form->addItem($si); - } - - // additional languages - if ($a_add) - { - include_once("./Services/MetaData/classes/class.ilMDLanguageItem.php"); - $options = ilMDLanguageItem::_getLanguages(); - $options = array("" => $lng->txt("please_select")) + $options; - $si = new ilSelectInputGUI($lng->txt("obj_additional_langs"), "additional_langs"); - $si->setOptions($options); - $si->setMulti(true); - $form->addItem($si); - } - - if ($a_add) - { - $form->setTitle($lng->txt("obj_add_languages")); - $form->addCommandButton("saveLanguages", $lng->txt("save")); - $form->addCommandButton("listTranslations", $lng->txt("cancel")); - } - else - { - if ($this->getTitleDescrOnlyMode()) - { - $form->setTitle($lng->txt("obj_activate_content_lang")); - } - else - { - $form->setTitle($lng->txt("obj_activate_multilang")); - } - $form->addCommandButton("saveContentTranslationActivation", $lng->txt("save")); - $form->addCommandButton("listTranslations", $lng->txt("cancel")); - } - $form->setFormAction($ilCtrl->getFormAction($this)); - - return $form; - } - - /** - * Confirm page translation creation - */ - function confirmDeactivateContentMultiLang() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - if ($this->getTitleDescrOnlyMode()) - { - $cgui->setHeaderText($lng->txt("obj_deactivate_content_transl_conf")); - } - else - { - $cgui->setHeaderText($lng->txt("obj_deactivate_multilang_conf")); - } - - $cgui->setCancel($lng->txt("cancel"), "listTranslations"); - $cgui->setConfirm($lng->txt("confirm"), "deactivateContentMultiLang"); - $tpl->setContent($cgui->getHTML()); - } - - /** - * Add language - */ - function addLanguages(ilPropertyFormGUI $form = null) - { - $tpl = $this->tpl; - - if(!$form instanceof ilPropertyFormGUI) - { - $form = $this->getMultiLangForm(true); - } - $tpl->setContent($form->getHTML()); - } - - /** - * Save languages - */ - function saveLanguages() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - ilLoggerFactory::getLogger('otpl')->debug('Save languages'); - - $form = $this->getMultiLangForm(true); - if($form->checkInput()) - { - $ad = $form->getInput("additional_langs"); - - ilLoggerFactory::getLogger('otpl')->dump($ad); - - if (is_array($ad)) - { - - foreach ($ad as $l) - { - if ($l != "") - { - $std = false; - - //if no other language is set, set this one as standard - if(!count($this->obj_trans->getLanguages())) - { - $std = true; - } - - $this->obj_trans->addLanguage($l, $this->start_title, $this->start_description,$std); - } - } - } - $this->obj_trans->save(); - ilUtil::sendInfo($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "listTranslations"); - } - else - { - $form->setValuesByPost(); - ilUtil::sendFailure($lng->txt('err_check_input')); - $this->addLanguages($form); - } - - } - - /** - * Confirm remove languages - */ - function confirmRemoveLanguages() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - $lng->loadLanguageModule("meta"); - - if (!is_array($_POST["lang"]) || count($_POST["lang"]) == 0) - { - ilUtil::sendInfo($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "listTranslations"); - } - else - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("obj_conf_delete_lang")); - $cgui->setCancel($lng->txt("cancel"), "listTranslations"); - $cgui->setConfirm($lng->txt("remove"), "removeLanguages"); - - foreach ($_POST["lang"] as $i) - { - $cgui->addItem("lang[]", $i, $lng->txt("meta_l_".$i)); - } - - $tpl->setContent($cgui->getHTML()); - } - } - - /** - * Remove languages - */ - function removeLanguages() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if (is_array($_POST["lang"])) - { - $langs = $this->obj_trans->getLanguages(); - foreach ($langs as $k => $l) - { - if (in_array($l, $_POST["lang"])) - { - $this->obj_trans->removeLanguage(); - } - } - $this->obj_trans->save(); - ilUtil::sendInfo($lng->txt("msg_obj_modified"), true); - } - $ilCtrl->redirect($this, "listTranslations"); - } - - /** - * @param string $a_title - * @param string $a_description - */ - public function setStartValues($a_title, $a_description) - { - $this->start_title = $a_title; - $this->start_description = $a_description; - } - - + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilObjUser + */ + protected $user; + + protected $obj_trans; + protected $title_descr_only = true; + protected $start_title = ""; + protected $start_description = ""; + + /** + * ilTranslationGUI constructor. + * @param int $a_obj_id + * @param stirng $a_type + */ + public function __construct($a_obj_id, $a_type) + { + global $DIC; + + $this->toolbar = $DIC->toolbar(); + $this->user = $DIC->user(); + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $tpl = $DIC["tpl"]; + + $this->lng = $lng; + $this->ctrl = $ilCtrl; + $this->tpl = $tpl; + + include_once("./Services/Multilingualism/classes/class.ilMultilingualism.php"); + $this->obj_trans = ilMultilingualism::getInstance($a_obj_id, $a_type); + } + + /** + * Set enable title/description only mode + * + * @param bool $a_val enable title/description only mode + */ + public function setTitleDescrOnlyMode($a_val) + { + $this->title_descr_only = $a_val; + } + + /** + * Get enable title/description only mode + * + * @return bool enable title/description only mode + */ + public function getTitleDescrOnlyMode() + { + return $this->title_descr_only; + } + + /** + * Execute command + */ + public function executeCommand() + { + $next_class = $this->ctrl->getNextClass($this); + + switch ($next_class) { + default: + $cmd = $this->ctrl->getCmd("listTranslations"); + if (in_array($cmd, array("listTranslations", "saveTranslations", + "addTranslation", "deleteTranslations", "activateContentMultilinguality", + "confirmRemoveLanguages", "removeLanguages", "confirmDeactivateContentMultiLang", "saveLanguages", + "saveContentTranslationActivation", "deactivateContentMultiLang", "addLanguages"))) { + $this->$cmd(); + } + break; + } + } + + /** + * List translations + */ + public function listTranslations($a_get_post_values = false, $a_add = false) + { + $this->lng->loadLanguageModule("translation"); + + + $this->addToolbar(); + + include_once("./Services/Multilingualism/classes/class.ilMultilingualismTableGUI.php"); + $table = new ilMultilingualismTableGUI( + $this, + "listTranslations", + true, + "Translation" + ); + 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->obj_trans->getLanguages(); + foreach ($data as $k => $v) { + $data[$k]["default"] = $v["lang_default"]; + $data[$k]["desc"] = $v["description"]; + $data[$k]["lang"] = $v["lang_code"]; + } + if ($a_add) { + $data["Fobject"][++$k]["title"] = ""; + } + $table->setData($data); + } + $this->tpl->setContent($table->getHTML()); + } + + public function addToolbar() + { + $ilToolbar = $this->toolbar; + if ($this->getTitleDescrOnlyMode()) { + $ilToolbar->addButton( + $this->lng->txt("obj_add_languages"), + $this->ctrl->getLinkTarget($this, "addLanguages") + ); + } + } + + /** + * Save translations + */ + public function saveTranslations() + { + // default language set? + if (!isset($_POST["default"])) { + ilUtil::sendFailure($this->lng->txt("msg_no_default_language")); + $this->listTranslations(true); + return; + } + + // all languages set? + if (array_key_exists("", $_POST["lang"])) { + ilUtil::sendFailure($this->lng->txt("msg_no_language_selected")); + $this->listTranslations(true); + return; + } + + // no single language is selected more than once? + if (count(array_unique($_POST["lang"])) < count($_POST["lang"])) { + ilUtil::sendFailure($this->lng->txt("msg_multi_language_selected")); + $this->listTranslations(true); + return; + } + + // save the stuff + $this->obj_trans->setLanguages(array()); + + foreach ($_POST["title"] as $k => $v) { + // update object data if default + $is_default = ($_POST["default"] == $k); + + $this->obj_trans->addLanguage( + ilUtil::stripSlashes($_POST["lang"][$k]), + ilUtil::stripSlashes($v), + ilUtil::stripSlashes($_POST["desc"][$k]), + $is_default + ); + } + $this->obj_trans->save(); + + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "listTranslations"); + } + + /** + * Remove translation + */ + public function deleteTranslations() + { + foreach ($_POST["title"] as $k => $v) { + if ($_POST["check"][$k]) { + // default translation cannot be deleted + if ($k != $_POST["default"]) { + unset($_POST["title"][$k]); + unset($_POST["desc"][$k]); + unset($_POST["lang"][$k]); + } else { + ilUtil::sendFailure($this->lng->txt("msg_no_default_language")); + $this->listTranslations(); + return; + } + } + } + $this->saveTranslations(); + } + + //// + //// Content translation + //// + + /** + * Get multi language form + */ + public function getMultiLangForm($a_add = false) + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + + // master language + if (!$a_add) { + include_once("./Services/MetaData/classes/class.ilMDLanguageItem.php"); + $options = ilMDLanguageItem::_getLanguages(); + $si = new ilSelectInputGUI($lng->txt("obj_master_lang"), "master_lang"); + $si->setOptions($options); + $si->setValue($ilUser->getLanguage()); + $form->addItem($si); + } + + // additional languages + if ($a_add) { + include_once("./Services/MetaData/classes/class.ilMDLanguageItem.php"); + $options = ilMDLanguageItem::_getLanguages(); + $options = array("" => $lng->txt("please_select")) + $options; + $si = new ilSelectInputGUI($lng->txt("obj_additional_langs"), "additional_langs"); + $si->setOptions($options); + $si->setMulti(true); + $form->addItem($si); + } + + if ($a_add) { + $form->setTitle($lng->txt("obj_add_languages")); + $form->addCommandButton("saveLanguages", $lng->txt("save")); + $form->addCommandButton("listTranslations", $lng->txt("cancel")); + } else { + if ($this->getTitleDescrOnlyMode()) { + $form->setTitle($lng->txt("obj_activate_content_lang")); + } else { + $form->setTitle($lng->txt("obj_activate_multilang")); + } + $form->addCommandButton("saveContentTranslationActivation", $lng->txt("save")); + $form->addCommandButton("listTranslations", $lng->txt("cancel")); + } + $form->setFormAction($ilCtrl->getFormAction($this)); + + return $form; + } + + /** + * Confirm page translation creation + */ + public function confirmDeactivateContentMultiLang() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + if ($this->getTitleDescrOnlyMode()) { + $cgui->setHeaderText($lng->txt("obj_deactivate_content_transl_conf")); + } else { + $cgui->setHeaderText($lng->txt("obj_deactivate_multilang_conf")); + } + + $cgui->setCancel($lng->txt("cancel"), "listTranslations"); + $cgui->setConfirm($lng->txt("confirm"), "deactivateContentMultiLang"); + $tpl->setContent($cgui->getHTML()); + } + + /** + * Add language + */ + public function addLanguages(ilPropertyFormGUI $form = null) + { + $tpl = $this->tpl; + + if (!$form instanceof ilPropertyFormGUI) { + $form = $this->getMultiLangForm(true); + } + $tpl->setContent($form->getHTML()); + } + + /** + * Save languages + */ + public function saveLanguages() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + ilLoggerFactory::getLogger('otpl')->debug('Save languages'); + + $form = $this->getMultiLangForm(true); + if ($form->checkInput()) { + $ad = $form->getInput("additional_langs"); + + ilLoggerFactory::getLogger('otpl')->dump($ad); + + if (is_array($ad)) { + foreach ($ad as $l) { + if ($l != "") { + $std = false; + + //if no other language is set, set this one as standard + if (!count($this->obj_trans->getLanguages())) { + $std = true; + } + + $this->obj_trans->addLanguage($l, $this->start_title, $this->start_description, $std); + } + } + } + $this->obj_trans->save(); + ilUtil::sendInfo($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "listTranslations"); + } else { + $form->setValuesByPost(); + ilUtil::sendFailure($lng->txt('err_check_input')); + $this->addLanguages($form); + } + } + + /** + * Confirm remove languages + */ + public function confirmRemoveLanguages() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + $lng->loadLanguageModule("meta"); + + if (!is_array($_POST["lang"]) || count($_POST["lang"]) == 0) { + ilUtil::sendInfo($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "listTranslations"); + } else { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("obj_conf_delete_lang")); + $cgui->setCancel($lng->txt("cancel"), "listTranslations"); + $cgui->setConfirm($lng->txt("remove"), "removeLanguages"); + + foreach ($_POST["lang"] as $i) { + $cgui->addItem("lang[]", $i, $lng->txt("meta_l_" . $i)); + } + + $tpl->setContent($cgui->getHTML()); + } + } + + /** + * Remove languages + */ + public function removeLanguages() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if (is_array($_POST["lang"])) { + $langs = $this->obj_trans->getLanguages(); + foreach ($langs as $k => $l) { + if (in_array($l, $_POST["lang"])) { + $this->obj_trans->removeLanguage(); + } + } + $this->obj_trans->save(); + ilUtil::sendInfo($lng->txt("msg_obj_modified"), true); + } + $ilCtrl->redirect($this, "listTranslations"); + } + + /** + * @param string $a_title + * @param string $a_description + */ + public function setStartValues($a_title, $a_description) + { + $this->start_title = $a_title; + $this->start_description = $a_description; + } } - -?> \ No newline at end of file diff --git a/Services/Multilingualism/classes/class.ilMultilingualismTableGUI.php b/Services/Multilingualism/classes/class.ilMultilingualismTableGUI.php index f1ed6f3729352761da9d0c91af7273ef250815aa..2b3645714a77e0779a29906322c9b490c3bbd495 100644 --- a/Services/Multilingualism/classes/class.ilMultilingualismTableGUI.php +++ b/Services/Multilingualism/classes/class.ilMultilingualismTableGUI.php @@ -13,122 +13,123 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilMultilingualismTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilAccessHandler - */ - protected $access; - - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_incl_desc = true, $a_base_cmd = "HeaderTitle", - $a_master_lang = "") - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $ilCtrl = $DIC->ctrl(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->incl_desc = $a_incl_desc; - $this->base_cmd = $a_base_cmd; - $this->master_lang = $a_master_lang; - - $this->setLimit(9999); - - $this->addColumn("", "", "1"); - $this->addColumn($this->lng->txt("language"), "", ""); - $this->addColumn($this->lng->txt("default"), "", ""); - $this->addColumn($this->lng->txt("title"), "", ""); - if ($a_incl_desc) - { - $this->addColumn($this->lng->txt("description"), "", ""); - } -// $this->addColumn($this->lng->txt("actions"), "", ""); - - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.obj_translation2_row.html", "Services/Object"); - $this->disable("footer"); - $this->setEnableTitle(true); - - $this->nr = 0; - } - - /** - * Prepare output - */ - function prepareOutput() - { - $lng = $this->lng; - - $this->addMultiCommand("delete".$this->base_cmd."s", $lng->txt("remove")); - if ($this->dataExists()) - { - $this->addCommandButton("save".$this->base_cmd."s", $lng->txt("save")); - } - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - - $this->nr++; - - - if (!$a_set["default"] && $a_set["lang"] != $this->master_lang) - { - $this->tpl->setCurrentBlock("cb"); - $this->tpl->setVariable("CB_NR", $this->nr); - $this->tpl->parseCurrentBlock(); - } - - if ($this->master_lang == "") - { - $this->tpl->setCurrentBlock("rb"); - $this->tpl->setVariable("RB_NR", $this->nr); - if ($a_set["default"]) - { - $this->tpl->setVariable("DEF_CHECKED", "checked=\"checked\""); - } - $this->tpl->parseCurrentBlock(); - } - else if ($a_set["lang"] == $this->master_lang) - { - $this->tpl->setVariable("MASTER_LANG", $lng->txt("obj_master_lang")); - } - - if ($this->incl_desc) - { - $this->tpl->setCurrentBlock("desc_row"); - $this->tpl->setVariable("VAL_DESC", ilUtil::prepareFormOutput($a_set["desc"])); - $this->tpl->setVariable("DNR", $this->nr); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setVariable("NR", $this->nr); - - // lang selection - include_once('Services/MetaData/classes/class.ilMDLanguageItem.php'); - $languages = ilMDLanguageItem::_getLanguages(); - $this->tpl->setVariable("LANG_SELECT", - ilUtil::formSelect($a_set["lang"], "lang[".$this->nr."]", $languages, - false, true)); - - - $this->tpl->setVariable("VAL_TITLE", ilUtil::prepareFormOutput($a_set["title"])); - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilAccessHandler + */ + protected $access; + + + /** + * Constructor + */ + public function __construct( + $a_parent_obj, + $a_parent_cmd, + $a_incl_desc = true, + $a_base_cmd = "HeaderTitle", + $a_master_lang = "" + ) { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $ilCtrl = $DIC->ctrl(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->incl_desc = $a_incl_desc; + $this->base_cmd = $a_base_cmd; + $this->master_lang = $a_master_lang; + + $this->setLimit(9999); + + $this->addColumn("", "", "1"); + $this->addColumn($this->lng->txt("language"), "", ""); + $this->addColumn($this->lng->txt("default"), "", ""); + $this->addColumn($this->lng->txt("title"), "", ""); + if ($a_incl_desc) { + $this->addColumn($this->lng->txt("description"), "", ""); + } + // $this->addColumn($this->lng->txt("actions"), "", ""); + + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.obj_translation2_row.html", "Services/Object"); + $this->disable("footer"); + $this->setEnableTitle(true); + + $this->nr = 0; + } + + /** + * Prepare output + */ + public function prepareOutput() + { + $lng = $this->lng; + + $this->addMultiCommand("delete" . $this->base_cmd . "s", $lng->txt("remove")); + if ($this->dataExists()) { + $this->addCommandButton("save" . $this->base_cmd . "s", $lng->txt("save")); + } + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + + $this->nr++; + + + if (!$a_set["default"] && $a_set["lang"] != $this->master_lang) { + $this->tpl->setCurrentBlock("cb"); + $this->tpl->setVariable("CB_NR", $this->nr); + $this->tpl->parseCurrentBlock(); + } + + if ($this->master_lang == "") { + $this->tpl->setCurrentBlock("rb"); + $this->tpl->setVariable("RB_NR", $this->nr); + if ($a_set["default"]) { + $this->tpl->setVariable("DEF_CHECKED", "checked=\"checked\""); + } + $this->tpl->parseCurrentBlock(); + } elseif ($a_set["lang"] == $this->master_lang) { + $this->tpl->setVariable("MASTER_LANG", $lng->txt("obj_master_lang")); + } + + if ($this->incl_desc) { + $this->tpl->setCurrentBlock("desc_row"); + $this->tpl->setVariable("VAL_DESC", ilUtil::prepareFormOutput($a_set["desc"])); + $this->tpl->setVariable("DNR", $this->nr); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setVariable("NR", $this->nr); + + // lang selection + include_once('Services/MetaData/classes/class.ilMDLanguageItem.php'); + $languages = ilMDLanguageItem::_getLanguages(); + $this->tpl->setVariable( + "LANG_SELECT", + ilUtil::formSelect( + $a_set["lang"], + "lang[" . $this->nr . "]", + $languages, + false, + true + ) + ); + + + $this->tpl->setVariable("VAL_TITLE", ilUtil::prepareFormOutput($a_set["title"])); + } } -?> diff --git a/Services/Navigation/classes/class.ilNavigationHistory.php b/Services/Navigation/classes/class.ilNavigationHistory.php index 25a6e6651d6231311d1be310eb332aa7ab91b4f8..d8fac44659729fd1e58485d092f997d1155bbfd7 100755 --- a/Services/Navigation/classes/class.ilNavigationHistory.php +++ b/Services/Navigation/classes/class.ilNavigationHistory.php @@ -11,227 +11,225 @@ */ class ilNavigationHistory { - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilDB - */ - protected $db; - - /** - * @var ilTree - */ - protected $tree; - - /** - * @var ilObjectDefinition - */ - protected $obj_definition; - - /** - * @var ilPluginAdmin - */ - protected $plugin_admin; - - - private $items; - - /** - * Constructor. - * - * @param int $a_id - */ - public function __construct() - { - global $DIC; - - $this->user = $DIC->user(); - $this->db = $DIC->database(); - $this->tree = $DIC->repositoryTree(); - $this->obj_definition = $DIC["objDefinition"]; - $this->plugin_admin = $DIC["ilPluginAdmin"]; - $this->items = array(); - $items = null; - if (isset($_SESSION["il_nav_history"])) - { - $items = unserialize($_SESSION["il_nav_history"]); - } - if (is_array($items)) - { - $this->items = $items; - } - } - - /** - * Add an item to the stack. If ref_id is already used, - * the item is moved to the top. - */ - public function addItem($a_ref_id, $a_link, $a_type, $a_title = "", $a_sub_obj_id = "", - $a_goto_link = "") - { - $ilUser = $this->user; - $ilDB = $this->db; - - // never store? - if ($ilUser->prefs["store_last_visited"] == 2) - { - return; - } - - $a_sub_obj_id = $a_sub_obj_id.""; - - if ($a_title == "" && $a_ref_id > 0) - { - $obj_id = ilObject::_lookupObjId($a_ref_id); - if (ilObject::_exists($obj_id)) - { - $a_title = ilObject::_lookupTitle($obj_id); - } - } - - $id = $a_ref_id.":".$a_sub_obj_id; - - $new_items[$id] = array("id" => $id,"ref_id" => $a_ref_id, "link" => $a_link, "title" => $a_title, - "type" => $a_type, "sub_obj_id" => $a_sub_obj_id, "goto_link" => $a_goto_link); - - $cnt = 1; - foreach($this->items as $key => $item) - { - if ($item["id"] != $id && $cnt <= 10) - { - $new_items[$item["id"]] = $item; - $cnt++; - } - } - - // put items in session - $this->items = $new_items; - - $items = serialize($this->items); - $_SESSION["il_nav_history"] = $items; -//var_dump($this->getItems()); - - - // only store in session? - if ($ilUser->prefs["store_last_visited"] == 1) - { - return; - } - - - // update entries in db - $ilDB->update("usr_data", - array( - "last_visited" => array("clob", serialize($this->getItems()))), - array( - "usr_id" => array("integer", $ilUser->getId())) - ); - } - - /** - * Get navigation item stack. - */ - public function getItems() - { - $tree = $this->tree; - $ilDB = $this->db; - $ilUser = $this->user; - $objDefinition = $this->obj_definition; - $ilPluginAdmin = $this->plugin_admin; - - $items = array(); - - foreach ($this->items as $it) - { - if ($tree->isInTree($it["ref_id"]) && - (!$objDefinition->isPluginTypeName($it["type"]) || - $ilPluginAdmin->isActive(IL_COMP_SERVICE, "Repository", "robj", - ilPlugin::lookupNameForId(IL_COMP_SERVICE, "Repository", "robj", $it["type"])) - )) - { - $items[$it["ref_id"].":".$it["sub_obj_id"]] = $it; - } - } - // less than 10? -> get items from db - if (count($items) < 10 && $ilUser->getId() != ANONYMOUS_USER_ID) - { - $set = $ilDB->query("SELECT last_visited FROM usr_data ". - " WHERE usr_id = ".$ilDB->quote($ilUser->getId(), "integer") - ); - $rec = $ilDB->fetchAssoc($set); - $db_entries = unserialize($rec["last_visited"]); - $cnt = count($items); - if (is_array($db_entries)) - { - foreach ($db_entries as $rec) - { - include_once("./Services/Link/classes/class.ilLink.php"); - - if ($cnt <= 10 && ! isset($items[$rec["ref_id"].":".$rec["sub_obj_id"]])) - { - if ($tree->isInTree($rec["ref_id"]) && - (!$objDefinition->isPluginTypeName($rec["type"]) || - $ilPluginAdmin->isActive(IL_COMP_SERVICE, "Repository", "robj", - ilPlugin::lookupNameForId(IL_COMP_SERVICE, "Repository", "robj", $rec["type"])) - )) - { - $link = ($rec["goto_link"] != "") - ? $rec["goto_link"] - : ilLink::_getLink($rec["ref_id"]); - if ($rec["sub_obj_id"] != "") - { - $title = $rec["title"]; - } - else - { - $title = ilObject::_lookupTitle(ilObject::_lookupObjId($rec["ref_id"])); - } - $items[$rec["ref_id"].":".$rec["sub_obj_id"]] = array("id" => $rec["ref_id"].":".$rec["sub_obj_id"], - "ref_id" => $rec["ref_id"], "link" => $link, "title" => $title, - "type" => $rec["type"], "sub_obj_id" => $rec["sub_obj_id"], "goto_link" => $rec["goto_link"]); - $cnt++; - } - } - } - } - } -//var_dump($items); - return $items; - } - - /** - * Delete DB entries - * - * @param - * @return - */ - function deleteDBEntries() - { - $ilUser = $this->user; - $ilDB = $this->db; - - // update entries in db - $ilDB->update("usr_data", - array( - "last_visited" => array("clob", serialize(array()))), - array( - "usr_id" => array("integer", $ilUser->getId())) - ); - } - - /** - * Delete session entries - * - * @param - * @return - */ - function deleteSessionEntries() - { - $_SESSION["il_nav_history"] = serialize(array()); - } - + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilDB + */ + protected $db; + + /** + * @var ilTree + */ + protected $tree; + + /** + * @var ilObjectDefinition + */ + protected $obj_definition; + + /** + * @var ilPluginAdmin + */ + protected $plugin_admin; + + + private $items; + + /** + * Constructor. + * + * @param int $a_id + */ + public function __construct() + { + global $DIC; + + $this->user = $DIC->user(); + $this->db = $DIC->database(); + $this->tree = $DIC->repositoryTree(); + $this->obj_definition = $DIC["objDefinition"]; + $this->plugin_admin = $DIC["ilPluginAdmin"]; + $this->items = array(); + $items = null; + if (isset($_SESSION["il_nav_history"])) { + $items = unserialize($_SESSION["il_nav_history"]); + } + if (is_array($items)) { + $this->items = $items; + } + } + + /** + * Add an item to the stack. If ref_id is already used, + * the item is moved to the top. + */ + public function addItem( + $a_ref_id, + $a_link, + $a_type, + $a_title = "", + $a_sub_obj_id = "", + $a_goto_link = "" + ) { + $ilUser = $this->user; + $ilDB = $this->db; + + // never store? + if ($ilUser->prefs["store_last_visited"] == 2) { + return; + } + + $a_sub_obj_id = $a_sub_obj_id . ""; + + if ($a_title == "" && $a_ref_id > 0) { + $obj_id = ilObject::_lookupObjId($a_ref_id); + if (ilObject::_exists($obj_id)) { + $a_title = ilObject::_lookupTitle($obj_id); + } + } + + $id = $a_ref_id . ":" . $a_sub_obj_id; + + $new_items[$id] = array("id" => $id,"ref_id" => $a_ref_id, "link" => $a_link, "title" => $a_title, + "type" => $a_type, "sub_obj_id" => $a_sub_obj_id, "goto_link" => $a_goto_link); + + $cnt = 1; + foreach ($this->items as $key => $item) { + if ($item["id"] != $id && $cnt <= 10) { + $new_items[$item["id"]] = $item; + $cnt++; + } + } + + // put items in session + $this->items = $new_items; + + $items = serialize($this->items); + $_SESSION["il_nav_history"] = $items; + //var_dump($this->getItems()); + + + // only store in session? + if ($ilUser->prefs["store_last_visited"] == 1) { + return; + } + + + // update entries in db + $ilDB->update( + "usr_data", + array( + "last_visited" => array("clob", serialize($this->getItems()))), + array( + "usr_id" => array("integer", $ilUser->getId())) + ); + } + + /** + * Get navigation item stack. + */ + public function getItems() + { + $tree = $this->tree; + $ilDB = $this->db; + $ilUser = $this->user; + $objDefinition = $this->obj_definition; + $ilPluginAdmin = $this->plugin_admin; + + $items = array(); + + foreach ($this->items as $it) { + if ($tree->isInTree($it["ref_id"]) && + ( + !$objDefinition->isPluginTypeName($it["type"]) || + $ilPluginAdmin->isActive( + IL_COMP_SERVICE, + "Repository", + "robj", + ilPlugin::lookupNameForId(IL_COMP_SERVICE, "Repository", "robj", $it["type"]) + ) + )) { + $items[$it["ref_id"] . ":" . $it["sub_obj_id"]] = $it; + } + } + // less than 10? -> get items from db + if (count($items) < 10 && $ilUser->getId() != ANONYMOUS_USER_ID) { + $set = $ilDB->query( + "SELECT last_visited FROM usr_data " . + " WHERE usr_id = " . $ilDB->quote($ilUser->getId(), "integer") + ); + $rec = $ilDB->fetchAssoc($set); + $db_entries = unserialize($rec["last_visited"]); + $cnt = count($items); + if (is_array($db_entries)) { + foreach ($db_entries as $rec) { + include_once("./Services/Link/classes/class.ilLink.php"); + + if ($cnt <= 10 && !isset($items[$rec["ref_id"] . ":" . $rec["sub_obj_id"]])) { + if ($tree->isInTree($rec["ref_id"]) && + ( + !$objDefinition->isPluginTypeName($rec["type"]) || + $ilPluginAdmin->isActive( + IL_COMP_SERVICE, + "Repository", + "robj", + ilPlugin::lookupNameForId(IL_COMP_SERVICE, "Repository", "robj", $rec["type"]) + ) + )) { + $link = ($rec["goto_link"] != "") + ? $rec["goto_link"] + : ilLink::_getLink($rec["ref_id"]); + if ($rec["sub_obj_id"] != "") { + $title = $rec["title"]; + } else { + $title = ilObject::_lookupTitle(ilObject::_lookupObjId($rec["ref_id"])); + } + $items[$rec["ref_id"] . ":" . $rec["sub_obj_id"]] = array("id" => $rec["ref_id"] . ":" . $rec["sub_obj_id"], + "ref_id" => $rec["ref_id"], "link" => $link, "title" => $title, + "type" => $rec["type"], "sub_obj_id" => $rec["sub_obj_id"], "goto_link" => $rec["goto_link"]); + $cnt++; + } + } + } + } + } + //var_dump($items); + return $items; + } + + /** + * Delete DB entries + * + * @param + * @return + */ + public function deleteDBEntries() + { + $ilUser = $this->user; + $ilDB = $this->db; + + // update entries in db + $ilDB->update( + "usr_data", + array( + "last_visited" => array("clob", serialize(array()))), + array( + "usr_id" => array("integer", $ilUser->getId())) + ); + } + + /** + * Delete session entries + * + * @param + * @return + */ + public function deleteSessionEntries() + { + $_SESSION["il_nav_history"] = serialize(array()); + } } -?> diff --git a/Services/Navigation/classes/class.ilNavigationHistoryGUI.php b/Services/Navigation/classes/class.ilNavigationHistoryGUI.php index e33ad82495313b128a9b13cb50d6029e3280f474..949570292838294ed24a1731acdbddaf9207aefb 100755 --- a/Services/Navigation/classes/class.ilNavigationHistoryGUI.php +++ b/Services/Navigation/classes/class.ilNavigationHistoryGUI.php @@ -8,157 +8,167 @@ * @author Alex Killing * @version $Id$ * -* @ilCtrl_Calls ilNavigationHistoryGUI: +* @ilCtrl_Calls ilNavigationHistoryGUI: */ class ilNavigationHistoryGUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilNavigationHistory - */ - protected $nav_history; + /** + * @var ilNavigationHistory + */ + protected $nav_history; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - private $items; + private $items; - /** - * Constructor. - * - */ - public function __construct() - { - global $DIC; + /** + * Constructor. + * + */ + public function __construct() + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->nav_history = $DIC["ilNavigationHistory"]; - $this->lng = $DIC->language(); - } + $this->ctrl = $DIC->ctrl(); + $this->nav_history = $DIC["ilNavigationHistory"]; + $this->lng = $DIC->language(); + } - /** - * Execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; + /** + * Execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; - $next_class = $ilCtrl->getNextClass(); - $cmd = $ilCtrl->getCmd(); + $next_class = $ilCtrl->getNextClass(); + $cmd = $ilCtrl->getCmd(); - switch($next_class) - { - default: - $this->$cmd(); - break; - } - } + switch ($next_class) { + default: + $this->$cmd(); + break; + } + } - /** - * Get HTML for navigation history - */ - function getHTML() - { - $ilNavigationHistory = $this->nav_history; - $lng = $this->lng; - - include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"); - $selection = new ilAdvancedSelectionListGUI(); - $selection->setFormSelectMode("url_ref_id", "ilNavHistorySelect", true, - "goto.php?target=navi_request", "ilNavHistory", "ilNavHistoryForm", - "_top", $lng->txt("go"), "ilNavHistorySubmit"); - $selection->setListTitle($lng->txt("last_visited")); - $selection->setId("lastvisited"); - $selection->setSelectionHeaderClass("MMInactive"); - $selection->setHeaderIcon(ilAdvancedSelectionListGUI::NO_ICON); - $selection->setItemLinkClass("small"); - $selection->setUseImages(true); - include_once("./Services/Accessibility/classes/class.ilAccessKey.php"); - $selection->setAccessKey(ilAccessKey::LAST_VISITED); - - $items = $ilNavigationHistory->getItems(); - //$sel_arr = array(0 => "-- ".$lng->txt("last_visited")." --"); - reset($items); - $cnt = 0; - foreach($items as $k => $item) - { - if ($cnt++ > 20) break; - if (!isset($item["ref_id"]) || !isset($_GET["ref_id"]) || - $item["ref_id"] != $_GET["ref_id"] || $k > 0) // do not list current item - { - $obj_id = ilObject::_lookupObjId($item["ref_id"]); - $selection->addItem($item["title"], $item["ref_id"], $item["link"], - ilObject::_getIcon($obj_id, "tiny", $item["type"]), - $lng->txt("obj_".$item["type"]), "_top"); - } - } - $html = $selection->getHTML(); - - if ($html == "") - { - $selection->addItem($lng->txt("no_items"), "", "#", - "", "", "_top"); - $selection->setUseImages(false); - $html = $selection->getHTML(); - } - return $html; - } - - /** - * Handle navigation request - */ - function handleNavigationRequest() - { - $ilNavigationHistory = $this->nav_history; - $ilCtrl = $this->ctrl; - - if ($_GET["target"] == "navi_request") - { - $items = $ilNavigationHistory->getItems(); - foreach($items as $item) - { - if ($item["ref_id"] == $_POST["url_ref_id"]) - { - ilUtil::redirect($item["link"]); - } - } - reset($items); - $item = current($items); - if ($_POST["url_ref_id"] == 0 && $item["ref_id"] == $_GET["ref_id"]) - { - $item = next($items); // omit current item - } - if ($_POST["url_ref_id"] == 0 && $item["link"] != "") - { - ilUtil::redirect($item["link"]); - } - - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", ""); - $ilCtrl->setParameterByClass("ilrepositorygui", "getlast", "true"); - $ilCtrl->redirectByClass("ilrepositorygui", "frameset"); - } - } - - /** - * Remove all entries form list - * - * @param - * @return - */ - function removeEntries() - { - $ilNavigationHistory = $this->nav_history; - - $ilNavigationHistory->deleteDBEntries(); - $ilNavigationHistory->deleteSessionEntries(); - } - + /** + * Get HTML for navigation history + */ + public function getHTML() + { + $ilNavigationHistory = $this->nav_history; + $lng = $this->lng; + + include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"); + $selection = new ilAdvancedSelectionListGUI(); + $selection->setFormSelectMode( + "url_ref_id", + "ilNavHistorySelect", + true, + "goto.php?target=navi_request", + "ilNavHistory", + "ilNavHistoryForm", + "_top", + $lng->txt("go"), + "ilNavHistorySubmit" + ); + $selection->setListTitle($lng->txt("last_visited")); + $selection->setId("lastvisited"); + $selection->setSelectionHeaderClass("MMInactive"); + $selection->setHeaderIcon(ilAdvancedSelectionListGUI::NO_ICON); + $selection->setItemLinkClass("small"); + $selection->setUseImages(true); + include_once("./Services/Accessibility/classes/class.ilAccessKey.php"); + $selection->setAccessKey(ilAccessKey::LAST_VISITED); + + $items = $ilNavigationHistory->getItems(); + //$sel_arr = array(0 => "-- ".$lng->txt("last_visited")." --"); + reset($items); + $cnt = 0; + foreach ($items as $k => $item) { + if ($cnt++ > 20) { + break; + } + if (!isset($item["ref_id"]) || !isset($_GET["ref_id"]) || + $item["ref_id"] != $_GET["ref_id"] || $k > 0) { // do not list current item + $obj_id = ilObject::_lookupObjId($item["ref_id"]); + $selection->addItem( + $item["title"], + $item["ref_id"], + $item["link"], + ilObject::_getIcon($obj_id, "tiny", $item["type"]), + $lng->txt("obj_" . $item["type"]), + "_top" + ); + } + } + $html = $selection->getHTML(); + + if ($html == "") { + $selection->addItem( + $lng->txt("no_items"), + "", + "#", + "", + "", + "_top" + ); + $selection->setUseImages(false); + $html = $selection->getHTML(); + } + return $html; + } + + /** + * Handle navigation request + */ + public function handleNavigationRequest() + { + $ilNavigationHistory = $this->nav_history; + $ilCtrl = $this->ctrl; + + if ($_GET["target"] == "navi_request") { + $items = $ilNavigationHistory->getItems(); + foreach ($items as $item) { + if ($item["ref_id"] == $_POST["url_ref_id"]) { + ilUtil::redirect($item["link"]); + } + } + reset($items); + $item = current($items); + if ($_POST["url_ref_id"] == 0 && $item["ref_id"] == $_GET["ref_id"]) { + $item = next($items); // omit current item + } + if ($_POST["url_ref_id"] == 0 && $item["link"] != "") { + ilUtil::redirect($item["link"]); + } + + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", ""); + $ilCtrl->setParameterByClass("ilrepositorygui", "getlast", "true"); + $ilCtrl->redirectByClass("ilrepositorygui", "frameset"); + } + } + + /** + * Remove all entries form list + * + * @param + * @return + */ + public function removeEntries() + { + $ilNavigationHistory = $this->nav_history; + + $ilNavigationHistory->deleteDBEntries(); + $ilNavigationHistory->deleteSessionEntries(); + } } -?> diff --git a/Services/News/Timeline/classes/class.ilTimelineGUI.php b/Services/News/Timeline/classes/class.ilTimelineGUI.php index ca1c7b5ee8a81003965f3844611ca36fb0454bab..ee3fcabe4badefb685deeec9bad2b989ee1ef48e 100644 --- a/Services/News/Timeline/classes/class.ilTimelineGUI.php +++ b/Services/News/Timeline/classes/class.ilTimelineGUI.php @@ -9,102 +9,94 @@ include_once("./Services/News/Timeline/interfaces/interface.ilTimelineItemInt.ph * * @author Alex Killing * @version $Id$ - * @ingroup + * @ingroup */ class ilTimelineGUI { - protected $items = array(); + protected $items = array(); - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilTemplate + */ + protected $tpl; - /** - * Construct - * - * @param - * @return - */ - protected function __construct() - { - global $DIC; + /** + * Construct + * + * @param + * @return + */ + protected function __construct() + { + global $DIC; - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - } + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + } - /** - * Get instance - * - * @param - * @return - */ - static function getInstance() - { - return new self(); - } + /** + * Get instance + * + * @param + * @return + */ + public static function getInstance() + { + return new self(); + } - /** - * Add item - * - * @param - * @return - */ - function addItem(ilTimelineItemInt $a_item) - { - $this->items[] = $a_item; - } + /** + * Add item + * + * @param + * @return + */ + public function addItem(ilTimelineItemInt $a_item) + { + $this->items[] = $a_item; + } - /** - * Render - * - * @param - * @return - */ - function render($a_items_only = false) - { - $this->tpl->addJavaScript("./Services/News/Timeline/js/Timeline.js"); - $this->tpl->addJavaScript("./Services/News/Timeline/libs/jquery-dynamic-max-height-master/src/jquery.dynamicmaxheight.js"); + /** + * Render + * + * @param + * @return + */ + public function render($a_items_only = false) + { + $this->tpl->addJavaScript("./Services/News/Timeline/js/Timeline.js"); + $this->tpl->addJavaScript("./Services/News/Timeline/libs/jquery-dynamic-max-height-master/src/jquery.dynamicmaxheight.js"); - $t = new ilTemplate("tpl.timeline.html", true, true, "Services/News/Timeline"); - if (!$a_items_only) - { - $t->touchBlock("list_start"); - $t->touchBlock("list_end"); - } - $keys = array_keys($this->items); - foreach ($this->items as $k => $i) - { - $next = null; - if (isset($this->items[$keys[$k+1]])) - { - $next = $this->items[$keys[$k+1]]; - } + $t = new ilTemplate("tpl.timeline.html", true, true, "Services/News/Timeline"); + if (!$a_items_only) { + $t->touchBlock("list_start"); + $t->touchBlock("list_end"); + } + $keys = array_keys($this->items); + foreach ($this->items as $k => $i) { + $next = null; + if (isset($this->items[$keys[$k+1]])) { + $next = $this->items[$keys[$k+1]]; + } - $dt = $i->getDateTime(); - if (is_null($next) || $dt->get(IL_CAL_FKT_DATE, "Y-m-d") != $next->getDateTime()->get(IL_CAL_FKT_DATE, "Y-m-d")) - { - $t->setCurrentBlock("badge"); - $t->setVariable("DAY", $dt->get(IL_CAL_FKT_DATE, "d")); - $t->setVariable("MONTH", $this->lng->txt("month_" . $dt->get(IL_CAL_FKT_DATE, "m") . "_short")); - $t->parseCurrentBlock(); - } - - $t->setCurrentBlock("item"); - $t->setVariable("CONTENT", $i->render()); - $t->setVariable("FOOTER", $i->renderFooter()); - $t->parseCurrentBlock(); - } - return $t->get(); - } - + $dt = $i->getDateTime(); + if (is_null($next) || $dt->get(IL_CAL_FKT_DATE, "Y-m-d") != $next->getDateTime()->get(IL_CAL_FKT_DATE, "Y-m-d")) { + $t->setCurrentBlock("badge"); + $t->setVariable("DAY", $dt->get(IL_CAL_FKT_DATE, "d")); + $t->setVariable("MONTH", $this->lng->txt("month_" . $dt->get(IL_CAL_FKT_DATE, "m") . "_short")); + $t->parseCurrentBlock(); + } + $t->setCurrentBlock("item"); + $t->setVariable("CONTENT", $i->render()); + $t->setVariable("FOOTER", $i->renderFooter()); + $t->parseCurrentBlock(); + } + return $t->get(); + } } - -?> \ No newline at end of file diff --git a/Services/News/Timeline/interfaces/interface.ilTimelineItemInt.php b/Services/News/Timeline/interfaces/interface.ilTimelineItemInt.php index 31d4f3b4531c44b896d97495cdf65201908eef8a..d735ab3b17c83b28d463d5a2cc1439640bad03c3 100644 --- a/Services/News/Timeline/interfaces/interface.ilTimelineItemInt.php +++ b/Services/News/Timeline/interfaces/interface.ilTimelineItemInt.php @@ -7,24 +7,21 @@ * * @author Alex Killing * @version $Id$ - * @ingroup + * @ingroup */ interface ilTimelineItemInt { - /** - * Render item - * - * @return string html - */ - public function render(); - - /** - * Get datetime - * - * @return ilDateTime timestamp - */ - public function getDateTime(); + /** + * Render item + * + * @return string html + */ + public function render(); + /** + * Get datetime + * + * @return ilDateTime timestamp + */ + public function getDateTime(); } - -?> \ No newline at end of file diff --git a/Services/News/classes/class.ilContextNewsData.php b/Services/News/classes/class.ilContextNewsData.php index a81dcabee514103b271bf188720a578677b6d586..37afbb1309ebf2e86fd573fcf39358080efea2a9 100644 --- a/Services/News/classes/class.ilContextNewsData.php +++ b/Services/News/classes/class.ilContextNewsData.php @@ -10,24 +10,22 @@ */ class ilContextNewsData { - /** - * @var ilNewsServiceDependencies - */ - protected $_deps; + /** + * @var ilNewsServiceDependencies + */ + protected $_deps; - /** - * @var ilNewsService - */ - protected $service; + /** + * @var ilNewsService + */ + protected $service; - /** - * Constructor - */ - public function __construct(int $obj_id, string $obj_type, int $subtype, string $subid, ilNewsService $service, $_deps) - { - $this->service = $service; - $this->_deps = $_deps; - } - - -} \ No newline at end of file + /** + * Constructor + */ + public function __construct(int $obj_id, string $obj_type, int $subtype, string $subid, ilNewsService $service, $_deps) + { + $this->service = $service; + $this->_deps = $_deps; + } +} diff --git a/Services/News/classes/class.ilNewsCache.php b/Services/News/classes/class.ilNewsCache.php index 1a17c4f548315eb669ddcd7e19797c1985d0b91f..88987a65e522e06ad71eae342dd0237110619e33 100644 --- a/Services/News/classes/class.ilNewsCache.php +++ b/Services/News/classes/class.ilNewsCache.php @@ -12,71 +12,72 @@ include_once("./Services/Cache/classes/class.ilCache.php"); */ class ilNewsCache extends ilCache { - /** - * @var ilSetting - */ - protected $settings; + /** + * @var ilSetting + */ + protected $settings; - static $disabled = false; - - /** - * Constructor - * - * @param - * @return - */ - function __construct() - { - global $DIC; + public static $disabled = false; + + /** + * Constructor + * + * @param + * @return + */ + public function __construct() + { + global $DIC; - $this->settings = $DIC->settings(); - $ilSetting = $DIC->settings(); - - $news_set = new ilSetting("news"); - $news_set->get("acc_cache_mins"); - - parent::__construct("ServicesNews", "News", true); - $this->setExpiresAfter($news_set->get("acc_cache_mins") * 60); - if ((int) $news_set->get("acc_cache_mins") == 0) - { - self::$disabled = true; - } - } - - /** - * Check if cache is disabled - * @return - */ - public function isDisabled() - { - return self::$disabled or parent::isDisabled(); - } - - - /** - * Read an entry - */ - function readEntry($a_id) - { - if (!$this->isDisabled()) - { - return parent::readEntry($a_id); - } - return false; - } - - - /** - * Id is user_id:ref_id, we store ref_if additionally - */ - function storeEntry($a_id, $a_value, $a_int_key1 = null, $a_int_key2 = null, - $a_text_key1 = null, $a_text_key2 = null) - { - $ilSetting = $this->settings; - if(!$this->isDisabled()) - { - parent::storeEntry($a_id, $a_value); - } - } + $this->settings = $DIC->settings(); + $ilSetting = $DIC->settings(); + + $news_set = new ilSetting("news"); + $news_set->get("acc_cache_mins"); + + parent::__construct("ServicesNews", "News", true); + $this->setExpiresAfter($news_set->get("acc_cache_mins") * 60); + if ((int) $news_set->get("acc_cache_mins") == 0) { + self::$disabled = true; + } + } + + /** + * Check if cache is disabled + * @return + */ + public function isDisabled() + { + return self::$disabled or parent::isDisabled(); + } + + + /** + * Read an entry + */ + public function readEntry($a_id) + { + if (!$this->isDisabled()) { + return parent::readEntry($a_id); + } + return false; + } + + + /** + * Id is user_id:ref_id, we store ref_if additionally + */ + public function storeEntry( + $a_id, + $a_value, + $a_int_key1 = null, + $a_int_key2 = null, + $a_text_key1 = null, + $a_text_key2 = null + ) { + $ilSetting = $this->settings; + if (!$this->isDisabled()) { + parent::storeEntry($a_id, $a_value); + } + } } -?> \ No newline at end of file diff --git a/Services/News/classes/class.ilNewsContext.php b/Services/News/classes/class.ilNewsContext.php index 75cd9452d395d5cb7c8d1a1a3006f7900f5dc636..a7588568f293b87aa5c2b907cac4e3098dbe84fd 100644 --- a/Services/News/classes/class.ilNewsContext.php +++ b/Services/News/classes/class.ilNewsContext.php @@ -10,75 +10,74 @@ */ class ilNewsContext { - /** - * @var int - */ - protected $obj_id; + /** + * @var int + */ + protected $obj_id; - /** - * @var string - */ - protected $obj_type; + /** + * @var string + */ + protected $obj_type; - /** - * @var int - */ - protected $sub_id; + /** + * @var int + */ + protected $sub_id; - /** - * @var string - */ - protected $sub_type; + /** + * @var string + */ + protected $sub_type; - /** - * Constructor - */ - public function __construct(int $obj_id, string $obj_type, int $sub_id, string $sub_type) - { - $this->obj_id = $obj_id; - $this->obj_type = $obj_type; - $this->sub_id = $sub_id; - $this->sub_type = $sub_type; - } + /** + * Constructor + */ + public function __construct(int $obj_id, string $obj_type, int $sub_id, string $sub_type) + { + $this->obj_id = $obj_id; + $this->obj_type = $obj_type; + $this->sub_id = $sub_id; + $this->sub_type = $sub_type; + } - /** - * Get Obj Id - * - * @return int - */ - public function getObjId(): int - { - return $this->obj_id; - } + /** + * Get Obj Id + * + * @return int + */ + public function getObjId() : int + { + return $this->obj_id; + } - /** - * Get Obj Type. - * - * @return string - */ - public function getObjType(): string - { - return $this->obj_type; - } + /** + * Get Obj Type. + * + * @return string + */ + public function getObjType() : string + { + return $this->obj_type; + } - /** - * Get Sub Obj Id. - * - * @return int - */ - public function getSubId(): int - { - return $this->sub_id; - } + /** + * Get Sub Obj Id. + * + * @return int + */ + public function getSubId() : int + { + return $this->sub_id; + } - /** - * Get Sub Obj Type. - * - * @return string - */ - public function getSubType(): string - { - return $this->sub_type; - } - -} \ No newline at end of file + /** + * Get Sub Obj Type. + * + * @return string + */ + public function getSubType() : string + { + return $this->sub_type; + } +} diff --git a/Services/News/classes/class.ilNewsData.php b/Services/News/classes/class.ilNewsData.php index 104e8c1b5fdb9f5f00b5eecb7e2df3ff6f0bc40f..70b9d9695aed3a190127e1813ef0ffbebb64e352 100644 --- a/Services/News/classes/class.ilNewsData.php +++ b/Services/News/classes/class.ilNewsData.php @@ -10,64 +10,63 @@ */ class ilNewsData { - /** - * @var ilNewsServiceDependencies - */ - protected $_deps; + /** + * @var ilNewsServiceDependencies + */ + protected $_deps; - /** - * @var ilNewsService - */ - protected $service; + /** + * @var ilNewsService + */ + protected $service; - /** - * Constructor - */ - public function __construct(ilNewsService $service, $_deps) - { - $this->service = $service; - $this->_deps = $_deps; - } + /** + * Constructor + */ + public function __construct(ilNewsService $service, $_deps) + { + $this->service = $service; + $this->_deps = $_deps; + } - /** - * Save news item - * - * @param ilNewsItem $news_item - * @return int - */ - public function save(ilNewsItem $news_item): int - { - if ($news_item->getId() > 0) - { - $news_item->update(true); - } - else - { - $news_item->create(); - } - return $news_item->getId(); - } + /** + * Save news item + * + * @param ilNewsItem $news_item + * @return int + */ + public function save(ilNewsItem $news_item) : int + { + if ($news_item->getId() > 0) { + $news_item->update(true); + } else { + $news_item->create(); + } + return $news_item->getId(); + } - /** - * Get news of context - * - * @param ilNewsContext $context - * @return ilNewsItem[] - */ - public function getNewsOfContext(ilNewsContext $context): array - { - return ilNewsItem::getNewsOfContext($context->getObjId(), - $context->getObjType(), $context->getSubId(), $context->getSubType()); - } + /** + * Get news of context + * + * @param ilNewsContext $context + * @return ilNewsItem[] + */ + public function getNewsOfContext(ilNewsContext $context) : array + { + return ilNewsItem::getNewsOfContext( + $context->getObjId(), + $context->getObjType(), + $context->getSubId(), + $context->getSubType() + ); + } - /** - * Delete a news item - * @param ilNewsItem $news_item - */ - public function delete(ilNewsItem $news_item) - { - $news_item->delete(); - } - - -} \ No newline at end of file + /** + * Delete a news item + * @param ilNewsItem $news_item + */ + public function delete(ilNewsItem $news_item) + { + $news_item->delete(); + } +} diff --git a/Services/News/classes/class.ilNewsDataSet.php b/Services/News/classes/class.ilNewsDataSet.php index 38c0b0cf8d4f7d5b8293dbb371997fa9191371aa..7107ec07a7d5f0f902f4471746bd366335175447 100644 --- a/Services/News/classes/class.ilNewsDataSet.php +++ b/Services/News/classes/class.ilNewsDataSet.php @@ -5,154 +5,144 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); /** * News data set class - * + * * @author Alex Killing * @version $Id$ * @ingroup ingroup ServicesNews */ class ilNewsDataSet extends ilDataSet { - /** - * Get supported versions - * - * @param - * @return - */ - public function getSupportedVersions() - { - return array("4.1.0"); - } - - /** - * Get xml namespace - * - * @param - * @return - */ - function getXmlNamespace($a_entity, $a_schema_version) - { - return "http://www.ilias.de/xml/Services/News/".$a_entity; - } - - /** - * Get field types for entity - * - * @param - * @return - */ - protected function getTypes($a_entity, $a_version) - { - if ($a_entity == "news") - { - switch ($a_version) - { - case "4.1.0": - return array( - "Id" => "integer", - "Title" => "text", - "Content" => "text", - "Priority" => "integer", - "ContextObjId" => "integer", - "ContextObjType" => "text", - "ContextSubObjId" => "integer", - "ContextSubObjType" => "text", - "ContentType" => "text", - "Visibility" => "text", - "ContentLong" => "text", - "ContentIsLangVar" => "integer", - "MobId" => "integer", - "Playtime" => "text" - ); - } - } + /** + * Get supported versions + * + * @param + * @return + */ + public function getSupportedVersions() + { + return array("4.1.0"); + } + + /** + * Get xml namespace + * + * @param + * @return + */ + public function getXmlNamespace($a_entity, $a_schema_version) + { + return "http://www.ilias.de/xml/Services/News/" . $a_entity; + } + + /** + * Get field types for entity + * + * @param + * @return + */ + protected function getTypes($a_entity, $a_version) + { + if ($a_entity == "news") { + switch ($a_version) { + case "4.1.0": + return array( + "Id" => "integer", + "Title" => "text", + "Content" => "text", + "Priority" => "integer", + "ContextObjId" => "integer", + "ContextObjType" => "text", + "ContextSubObjId" => "integer", + "ContextSubObjType" => "text", + "ContentType" => "text", + "Visibility" => "text", + "ContentLong" => "text", + "ContentIsLangVar" => "integer", + "MobId" => "integer", + "Playtime" => "text" + ); + } + } + } - } + /** + * Read data + * + * @param + * @return + */ + public function readData($a_entity, $a_version, $a_ids, $a_field = "") + { + $ilDB = $this->db; - /** - * Read data - * - * @param - * @return - */ - 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 == "news") { + switch ($a_version) { + case "4.1.0": + $this->getDirectDataFromQuery("SELECT id, title, content, priority," . + " context_obj_id, context_obj_type, context_sub_obj_id, context_sub_obj_type, " . + " content_type, visibility, content_long, content_is_lang_var, mob_id, playtime" . + " FROM il_news_item " . + "WHERE " . + $ilDB->in("id", $a_ids, false, "integer")); + break; + } + } + } + + /** + * Determine the dependent sets of data + */ + protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) + { + return false; + } + + + /** + * Import record + * + * @param + * @return + */ + public function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) + { + //echo $a_entity; + //var_dump($a_rec); - if (!is_array($a_ids)) - { - $a_ids = array($a_ids); - } - - if ($a_entity == "news") - { - switch ($a_version) - { - case "4.1.0": - $this->getDirectDataFromQuery("SELECT id, title, content, priority,". - " context_obj_id, context_obj_type, context_sub_obj_id, context_sub_obj_type, ". - " content_type, visibility, content_long, content_is_lang_var, mob_id, playtime". - " FROM il_news_item ". - "WHERE ". - $ilDB->in("id", $a_ids, false, "integer")); - break; - } - } - - } - - /** - * Determine the dependent sets of data - */ - protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) - { - return false; - } - - - /** - * Import record - * - * @param - * @return - */ - function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) - { -//echo $a_entity; -//var_dump($a_rec); - - switch ($a_entity) - { - case "news": - $mob_id = null; - if ($a_rec["MobId"] > 0) - { - $mob_id = $a_mapping->getMapping("Services/MediaObjects", "mob", $a_rec["MobId"]); - } - $c = (int)$a_rec["ContextObjId"].":".$a_rec["ContextObjType"].":".(int)$a_rec["ContextSubObjId"]. - ":".$a_rec["ContextSubObjType"]; - $context = $a_mapping->getMapping("Services/News", "news_context", $c); - $context = explode(":", $context); + switch ($a_entity) { + case "news": + $mob_id = null; + if ($a_rec["MobId"] > 0) { + $mob_id = $a_mapping->getMapping("Services/MediaObjects", "mob", $a_rec["MobId"]); + } + $c = (int) $a_rec["ContextObjId"] . ":" . $a_rec["ContextObjType"] . ":" . (int) $a_rec["ContextSubObjId"] . + ":" . $a_rec["ContextSubObjType"]; + $context = $a_mapping->getMapping("Services/News", "news_context", $c); + $context = explode(":", $context); //var_dump($c); //var_dump($a_mapping->mappings["Services/News"]["news_context"]); - include_once("./Services/News/classes/class.ilNewsItem.php"); - $newObj = new ilNewsItem(); - $newObj->setTitle($a_rec["Title"]); - $newObj->setContent($a_rec["Content"]); - $newObj->setPriority($a_rec["Priority"]); - $newObj->setContextObjId($context[0]); - $newObj->setContextObjType($context[1]); - $newObj->setContextSubObjId($context[2]); - $newObj->setContextSubObjType($context[3]); - $newObj->setContentType($a_rec["ContentType"]); - $newObj->setVisibility($a_rec["Visibility"]); - $newObj->setContentLong($a_rec["ContentLong"]); - $newObj->setContentIsLangVar($a_rec["ContentIsLangVar"]); - $newObj->setMobId($mob_id); - $newObj->setPlaytime($a_rec["Playtime"]); - $newObj->create(); - $a_mapping->addMapping("Services/News", "news", $a_rec["Id"], $newObj->getId()); - break; - } - } + include_once("./Services/News/classes/class.ilNewsItem.php"); + $newObj = new ilNewsItem(); + $newObj->setTitle($a_rec["Title"]); + $newObj->setContent($a_rec["Content"]); + $newObj->setPriority($a_rec["Priority"]); + $newObj->setContextObjId($context[0]); + $newObj->setContextObjType($context[1]); + $newObj->setContextSubObjId($context[2]); + $newObj->setContextSubObjType($context[3]); + $newObj->setContentType($a_rec["ContentType"]); + $newObj->setVisibility($a_rec["Visibility"]); + $newObj->setContentLong($a_rec["ContentLong"]); + $newObj->setContentIsLangVar($a_rec["ContentIsLangVar"]); + $newObj->setMobId($mob_id); + $newObj->setPlaytime($a_rec["Playtime"]); + $newObj->create(); + $a_mapping->addMapping("Services/News", "news", $a_rec["Id"], $newObj->getId()); + break; + } + } } -?> \ No newline at end of file diff --git a/Services/News/classes/class.ilNewsDefaultRendererGUI.php b/Services/News/classes/class.ilNewsDefaultRendererGUI.php index b4978cff0d3bc8c57270ff129abb67155ec2a13d..6f42860951bbdc578600ab6dd739a12f32a4657e 100644 --- a/Services/News/classes/class.ilNewsDefaultRendererGUI.php +++ b/Services/News/classes/class.ilNewsDefaultRendererGUI.php @@ -12,149 +12,145 @@ include_once("./Services/News/interfaces/interface.ilNewsRendererGUI.php"); */ class ilNewsDefaultRendererGUI implements ilNewsRendererGUI { - protected $lng_key; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilNewsItem - */ - protected $news_item; - - /** - * @var int - */ - protected $news_ref_id; - - /** - * Constructor - * - * @param - * @return - */ - function __construct() - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - } - - /** - * @inheritdoc - */ - function setNewsItem(ilNewsItem $a_news_item, $a_news_ref_id) - { - $this->news_item = $a_news_item; - $this->news_ref_id = $a_news_ref_id; - } - - /** - * Get news item - * - * @return ilNewsItem - */ - function getNewsItem() - { - return $this->news_item; - } - - /** - * Get news ref id - * - * @return int ref id - */ - function getNewsRefId() - { - return $this->news_ref_id; - } - - - /** - * @inheritdoc - */ - function setLanguage($a_lang_key) - { - $this->lng_key = $a_lang_key; - } - - - /** - * @inheritdoc - */ - public function getTimelineContent() - { - return $this->getDetailContent(); - } - - /** - * @inheritdoc - */ - function getDetailContent() - { - if ($this->news_item->getContentTextIsLangVar()) - { - $this->lng->loadLanguageModule($this->news_item->getContextObjType()); - return ilNewsItem::determineNewsContent($this->news_item->getContextObjType(), $this->news_item->getContent(), - $this->news_item->getContentTextIsLangVar()); - } - - $content = $this->makeClickable($this->news_item->getContent()); - if (!$this->news_item->getContentHtml()) - { - $content = "

                  ".nl2br($content)."

                  "; - } - $content.= $this->news_item->getContentLong(); - - return $content; - } - - /** - * Make clickable - * - * @param - * @return - */ - function makeClickable($a_str) - { - // this fixes bug 8744. - // If the string already contains a tags our makeClickable does not work - if (is_int(strpos($a_str, "")) && is_int(strpos($a_str, "getNewsRefId()); - } - + protected $lng_key; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilNewsItem + */ + protected $news_item; + + /** + * @var int + */ + protected $news_ref_id; + + /** + * Constructor + * + * @param + * @return + */ + public function __construct() + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + } + + /** + * @inheritdoc + */ + public function setNewsItem(ilNewsItem $a_news_item, $a_news_ref_id) + { + $this->news_item = $a_news_item; + $this->news_ref_id = $a_news_ref_id; + } + + /** + * Get news item + * + * @return ilNewsItem + */ + public function getNewsItem() + { + return $this->news_item; + } + + /** + * Get news ref id + * + * @return int ref id + */ + public function getNewsRefId() + { + return $this->news_ref_id; + } + + + /** + * @inheritdoc + */ + public function setLanguage($a_lang_key) + { + $this->lng_key = $a_lang_key; + } + + + /** + * @inheritdoc + */ + public function getTimelineContent() + { + return $this->getDetailContent(); + } + + /** + * @inheritdoc + */ + public function getDetailContent() + { + if ($this->news_item->getContentTextIsLangVar()) { + $this->lng->loadLanguageModule($this->news_item->getContextObjType()); + return ilNewsItem::determineNewsContent( + $this->news_item->getContextObjType(), + $this->news_item->getContent(), + $this->news_item->getContentTextIsLangVar() + ); + } + + $content = $this->makeClickable($this->news_item->getContent()); + if (!$this->news_item->getContentHtml()) { + $content = "

                  " . nl2br($content) . "

                  "; + } + $content.= $this->news_item->getContentLong(); + + return $content; + } + + /** + * Make clickable + * + * @param + * @return + */ + public function makeClickable($a_str) + { + // this fixes bug 8744. + // If the string already contains a tags our makeClickable does not work + if (is_int(strpos($a_str, "")) && is_int(strpos($a_str, "getNewsRefId()); + } } - -?> \ No newline at end of file diff --git a/Services/News/classes/class.ilNewsExporter.php b/Services/News/classes/class.ilNewsExporter.php index 72d2fe14033a056a384d73a7416041f960fcfcb6..2f976a2ff5e60cf9d206f021f1992301e2d8fd6b 100644 --- a/Services/News/classes/class.ilNewsExporter.php +++ b/Services/News/classes/class.ilNewsExporter.php @@ -12,83 +12,77 @@ include_once("./Services/Export/classes/class.ilXmlExporter.php"); */ class ilNewsExporter extends ilXmlExporter { - private $ds; + private $ds; - /** - * Initialisation - */ - function init() - { - include_once("./Services/News/classes/class.ilNewsDataSet.php"); - $this->ds = new ilNewsDataSet(); - $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); - $this->ds->setDSPrefix("ds"); - } + /** + * Initialisation + */ + public function init() + { + include_once("./Services/News/classes/class.ilNewsDataSet.php"); + $this->ds = new ilNewsDataSet(); + $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); + $this->ds->setDSPrefix("ds"); + } - /** - * Get tail dependencies - * - * @param string entity - * @param string target release - * @param array ids - * @return array array of array with keys "component", entity", "ids" - */ - function getXmlExportHeadDependencies($a_entity, $a_target_release, $a_ids) - { + /** + * Get tail dependencies + * + * @param string entity + * @param string target release + * @param array ids + * @return array array of array with keys "component", entity", "ids" + */ + public function getXmlExportHeadDependencies($a_entity, $a_target_release, $a_ids) + { + include_once("./Services/News/classes/class.ilNewsItem.php"); + $mob_ids = array(); - include_once("./Services/News/classes/class.ilNewsItem.php"); - $mob_ids = array(); + foreach ($a_ids as $id) { + $mob_id = ilNewsItem::_lookupMobId($id); + if ($mob_id > 0) { + $mob_ids[$mob_id] = $mob_id; + } + } - foreach ($a_ids as $id) - { - $mob_id = ilNewsItem::_lookupMobId($id); - if ($mob_id > 0) - { - $mob_ids[$mob_id] = $mob_id; - } - } + return array( + array( + "component" => "Services/MediaObjects", + "entity" => "mob", + "ids" => $mob_ids) + ); + } - return array ( - array( - "component" => "Services/MediaObjects", - "entity" => "mob", - "ids" => $mob_ids) - ); - } - - /** - * Get xml representation - * - * @param string entity - * @param string target release - * @param string id - * @return string xml string - */ - public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) - { - return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); - } - - /** - * Returns schema versions that the component can export to. - * ILIAS chooses the first one, that has min/max constraints which - * fit to the target release. Please put the newest on top. - * - * @return - */ - function getValidSchemaVersions($a_entity) - { - return array ( - "4.1.0" => array( - "namespace" => "http://www.ilias.de/Services/News/news/4_1", - "xsd_file" => "ilias_news_4_1.xsd", - "uses_dataset" => true, - "min" => "4.1.0", - "max" => "") - ); - } + /** + * Get xml representation + * + * @param string entity + * @param string target release + * @param string id + * @return string xml string + */ + public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) + { + return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); + } + /** + * Returns schema versions that the component can export to. + * ILIAS chooses the first one, that has min/max constraints which + * fit to the target release. Please put the newest on top. + * + * @return + */ + public function getValidSchemaVersions($a_entity) + { + return array( + "4.1.0" => array( + "namespace" => "http://www.ilias.de/Services/News/news/4_1", + "xsd_file" => "ilias_news_4_1.xsd", + "uses_dataset" => true, + "min" => "4.1.0", + "max" => "") + ); + } } - -?> \ No newline at end of file diff --git a/Services/News/classes/class.ilNewsForContextBlockGUI.php b/Services/News/classes/class.ilNewsForContextBlockGUI.php index c4a54c007aa917b33c0b50fd3ef036bc0c6ea781..4c2efb80ce5bf078ffe83319980c7de31c9c5f05 100755 --- a/Services/News/classes/class.ilNewsForContextBlockGUI.php +++ b/Services/News/classes/class.ilNewsForContextBlockGUI.php @@ -17,1448 +17,1528 @@ include_once("Services/Block/classes/class.ilBlockGUI.php"); */ class ilNewsForContextBlockGUI extends ilBlockGUI { - /** - * object type names with settings->news settings subtab - */ - const OBJECTS_WITH_NEWS_SUBTAB = ["category", "course", "group", "forum"]; - - /** - * @var ilHelpGUI - */ - protected $help; - - /** - * @var ilSetting - */ - protected $settings; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - static $block_type = "news"; - static $st_data; - - protected $obj_definition; - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - $this->help = $DIC["ilHelp"]; - $this->access = $DIC->access(); - $this->settings = $DIC->settings(); - $this->tabs = $DIC->tabs(); - $this->obj_definition = $DIC["objDefinition"]; - - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilUser = $DIC->user(); - $ilHelp = $DIC["ilHelp"]; - - parent::__construct(); - - $lng->loadLanguageModule("news"); - $ilHelp->addHelpSection("news_block"); - - include_once("./Services/News/classes/class.ilNewsItem.php"); - $this->setBlockId($ilCtrl->getContextObjId()); - $this->setLimit(5); - $this->setAvailableDetailLevels(3); - $this->setEnableNumInfo(true); - - $this->dynamic = false; - include_once("./Services/News/classes/class.ilNewsCache.php"); - $this->acache = new ilNewsCache(); - $cres = unserialize($this->acache->getEntry($ilUser->getId().":".$_GET["ref_id"])); - $this->cache_hit = false; - - if ($this->acache->getLastAccessStatus() == "hit" && is_array($cres)) - { - self::$st_data = ilNewsItem::prepareNewsDataFromCache($cres); - $this->cache_hit = true; - } - if ($this->getDynamic() && !$this->cache_hit) - { - $this->dynamic = true; - $data = array(); - } - else if ($this->getCurrentDetailLevel() > 0) - { - if (!empty(self::$st_data)) - { - $data = self::$st_data; - } - else - { - $data = $this->getNewsData(); - self::$st_data = $data; - } - } - else - { - $data = array(); - } - - $this->setTitle($lng->txt("news_internal_news")); - $this->setRowTemplate("tpl.block_row_news_for_context.html", "Services/News"); - $this->setData($data); - $this->allow_moving = false; - $this->handleView(); - } - - /** - * Get news for context - */ - function getNewsData() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - include_once("./Services/News/classes/class.ilNewsCache.php"); - $this->acache = new ilNewsCache(); -/* $cres = $this->acache->getEntry($ilUser->getId().":".$_GET["ref_id"]); - if ($this->acache->getLastAccessStatus() == "hit" && false) - { - $news_data = unserialize($cres); - } - else - {*/ - $news_item = new ilNewsItem(); - $news_item->setContextObjId($ilCtrl->getContextObjId()); - $news_item->setContextObjType($ilCtrl->getContextObjType()); - - // workaround, better: reduce constructor and introduce - //$prevent_aggregation = $this->getProperty("prevent_aggregation"); - $prevent_aggregation = true; - if ($ilCtrl->getContextObjType() != "frm") - { - $forum_grouping = true; - } - else - { - $forum_grouping = false; - } - - - $news_data = $news_item->getNewsForRefId($_GET["ref_id"], false, false, 0, - $prevent_aggregation, $forum_grouping); - - $this->acache->storeEntry($ilUser->getId().":".$_GET["ref_id"], - serialize($news_data)); - -// } -//var_dump($news_data); - return $news_data; - } - - /** - * @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() - { - global $DIC; - - $ilCtrl = $DIC->ctrl(); - - if ($ilCtrl->getCmdClass() == "ilnewsitemgui") - { - return IL_SCREEN_FULL; - } - - switch($ilCtrl->getCmd()) - { - case "showNews": - case "showFeedUrl": - return IL_SCREEN_CENTER; - break; - - case "editSettings": - case "saveSettings": - return IL_SCREEN_FULL; - break; - - default: - return IL_SCREEN_SIDE; - break; - } - } - - /** - * execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - - $next_class = $ilCtrl->getNextClass(); - $cmd = $ilCtrl->getCmd("getHTML"); - - switch ($next_class) - { - case "ilnewsitemgui": - include_once("./Services/News/classes/class.ilNewsItemGUI.php"); - $news_item_gui = new ilNewsItemGUI(); - $news_item_gui->setEnableEdit($this->getEnableEdit()); - $html = $ilCtrl->forwardCommand($news_item_gui); - return $html; - - default: - return $this->$cmd(); - } - } - - /** - * Set EnableEdit. - * - * @param boolean $a_enable_edit Edit mode on/off - */ - public function setEnableEdit($a_enable_edit = 0) - { - $this->enable_edit = $a_enable_edit; - } - - /** - * Get EnableEdit. - * - * @return boolean Edit mode on/off - */ - public function getEnableEdit() - { - return $this->enable_edit; - } - - /** - * Fill data section - */ - function fillDataSection() - { - if ($this->dynamic) - { - $this->setDataSection($this->getDynamicReload()); - } - else if ($this->getCurrentDetailLevel() > 1 && count($this->getData()) > 0) - { - parent::fillDataSection(); - } - else - { - $this->setDataSection($this->getOverview()); - } - } - - /** - * Get bloch HTML code. - */ - function getHTML() - { - global $DIC; - - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilUser = $this->user; - - $news_set = new ilSetting("news"); - $enable_internal_rss = $news_set->get("enable_rss_for_internal"); - - $hide_block = ilBlockSetting::_lookup($this->getBlockType(), "hide_news_block", - 0, $this->block_id); - if ($hide_block) - { - $this->setFooterInfo($lng->txt("news_hidden_news_block")); - } - - if ($this->getProperty("title") != "") - { - $this->setTitle($this->getProperty("title")); - } - - $public_feed = ilBlockSetting::_lookup($this->getBlockType(), "public_feed", - 0, $this->block_id); - if ($public_feed) - { - if ($enable_internal_rss) - { - include_once("./Services/News/classes/class.ilRSSButtonGUI.php"); - $this->addBlockCommand( - ILIAS_HTTP_PATH."/feed.php?client_id=".rawurlencode(CLIENT_ID)."&". - "ref_id=".$_GET["ref_id"], - $lng->txt("news_feed_url"), "", "", true, false, ilRSSButtonGUI::get(ilRSSButtonGUI::ICON_RSS)); - - } - } - -/* Subscription Concept is abandonded for now (Alex) - // subscribe/unsibscribe link - include_once("./Services/News/classes/class.ilNewsSubscription.php"); - if (ilNewsSubscription::_hasSubscribed($_GET["ref_id"], $ilUser->getId())) - { - $this->addBlockCommand( - $ilCtrl->getLinkTarget($this, "unsubscribeNews"), - $lng->txt("news_unsubscribe")); - } - else - { - $this->addBlockCommand( - $ilCtrl->getLinkTarget($this, "subscribeNews"), - $lng->txt("news_subscribe")); - } -*/ - - // add edit commands - if ($this->getEnableEdit()) - { - $this->addBlockCommand( - $ilCtrl->getLinkTargetByClass("ilnewsitemgui", "editNews"), - $lng->txt("edit")); - - $ilCtrl->setParameter($this, "add_mode", "block"); - $this->addBlockCommand( - $ilCtrl->getLinkTargetByClass("ilnewsitemgui", "createNewsItem"), - $lng->txt("add")); - $ilCtrl->setParameter($this, "add_mode", ""); - } - - if ($this->getProperty("settings") == true) - { - $ref_id = $_GET["ref_id"]; - $obj_def = $DIC["objDefinition"]; - $obj_id = ilObject::_lookupObjectId($ref_id); - $obj_type = ilObject::_lookupType($ref_id, true); - $obj_class= strtolower($obj_def->getClassName($obj_type)); - $parent_gui = "ilobj".$obj_class."gui"; - - $ilCtrl->setParameterByClass("ilcontainernewssettingsgui", "ref_id", $ref_id); - - if (in_array($obj_class, ilNewsForContextBlockGUI::OBJECTS_WITH_NEWS_SUBTAB)) - { - $this->addBlockCommand( - $ilCtrl->getLinkTargetByClass(array("ilrepositorygui", $parent_gui, "ilcontainernewssettingsgui"), "show"), - $lng->txt("settings")); - } - else - { - $this->addBlockCommand( - $ilCtrl->getLinkTarget($this, "editSettings"), - $lng->txt("settings")); - } - } - - // do not display hidden repository news blocks for users - // who do not have write permission - if (!$this->getEnableEdit() && $this->getRepositoryMode() && - ilBlockSetting::_lookup($this->getBlockType(), "hide_news_block", - 0, $this->block_id)) - { - return ""; - } - - // do not display empty news blocks for users - // who do not have write permission - if (count($this->getData()) == 0 && !$this->getEnableEdit() && - $this->getRepositoryMode() && !$this->dynamic - && (!$news_set->get("enable_rss_for_internal") || - !ilBlockSetting::_lookup($this->getBlockType(), "public_feed", - 0, $this->block_id))) - { - return ""; - } - - $en = ""; - if ($ilUser->getPref("il_feed_js") == "n") - { -// $en = getJSEnabler(); - } - - return parent::getHTML().$en; - } - - /** - * Handles show/hide notification view and removes notifications if hidden. - */ - function handleView() - { - $ilUser = $this->user; - - include_once("Services/Block/classes/class.ilBlockSetting.php"); - $this->view = ilBlockSetting::_lookup($this->getBlockType(), "view", - $ilUser->getId(), $this->block_id); - - // check whether notices and messages exist - $got_notices = $got_messages = false; - foreach($this->data as $row) - { - if ($row["priority"] == 0) $got_notices = true; - if ($row["priority"] == 1) $got_messages = true; - } - $this->show_view_selection = false; - - if ($got_notices && $got_messages) - { - $this->show_view_selection = true; - } - else if ($got_notices) - { - $this->view = ""; - } - - // remove notifications if hidden + /** + * object type names with settings->news settings subtab + */ + const OBJECTS_WITH_NEWS_SUBTAB = ["category", "course", "group", "forum"]; + + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + public static $block_type = "news"; + public static $st_data; + + protected $obj_definition; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + $this->help = $DIC["ilHelp"]; + $this->access = $DIC->access(); + $this->settings = $DIC->settings(); + $this->tabs = $DIC->tabs(); + $this->obj_definition = $DIC["objDefinition"]; + + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilUser = $DIC->user(); + $ilHelp = $DIC["ilHelp"]; + + parent::__construct(); + + $lng->loadLanguageModule("news"); + $ilHelp->addHelpSection("news_block"); + + include_once("./Services/News/classes/class.ilNewsItem.php"); + $this->setBlockId($ilCtrl->getContextObjId()); + $this->setLimit(5); + $this->setAvailableDetailLevels(3); + $this->setEnableNumInfo(true); + + $this->dynamic = false; + include_once("./Services/News/classes/class.ilNewsCache.php"); + $this->acache = new ilNewsCache(); + $cres = unserialize($this->acache->getEntry($ilUser->getId() . ":" . $_GET["ref_id"])); + $this->cache_hit = false; + + if ($this->acache->getLastAccessStatus() == "hit" && is_array($cres)) { + self::$st_data = ilNewsItem::prepareNewsDataFromCache($cres); + $this->cache_hit = true; + } + if ($this->getDynamic() && !$this->cache_hit) { + $this->dynamic = true; + $data = array(); + } elseif ($this->getCurrentDetailLevel() > 0) { + if (!empty(self::$st_data)) { + $data = self::$st_data; + } else { + $data = $this->getNewsData(); + self::$st_data = $data; + } + } else { + $data = array(); + } + + $this->setTitle($lng->txt("news_internal_news")); + $this->setRowTemplate("tpl.block_row_news_for_context.html", "Services/News"); + $this->setData($data); + $this->allow_moving = false; + $this->handleView(); + } + + /** + * Get news for context + */ + public function getNewsData() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + include_once("./Services/News/classes/class.ilNewsCache.php"); + $this->acache = new ilNewsCache(); + /* $cres = $this->acache->getEntry($ilUser->getId().":".$_GET["ref_id"]); + if ($this->acache->getLastAccessStatus() == "hit" && false) + { + $news_data = unserialize($cres); + } + else + {*/ + $news_item = new ilNewsItem(); + $news_item->setContextObjId($ilCtrl->getContextObjId()); + $news_item->setContextObjType($ilCtrl->getContextObjType()); + + // workaround, better: reduce constructor and introduce + //$prevent_aggregation = $this->getProperty("prevent_aggregation"); + $prevent_aggregation = true; + if ($ilCtrl->getContextObjType() != "frm") { + $forum_grouping = true; + } else { + $forum_grouping = false; + } + + + $news_data = $news_item->getNewsForRefId( + $_GET["ref_id"], + false, + false, + 0, + $prevent_aggregation, + $forum_grouping + ); + + $this->acache->storeEntry( + $ilUser->getId() . ":" . $_GET["ref_id"], + serialize($news_data) + ); + + // } + //var_dump($news_data); + return $news_data; + } + + /** + * @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() + { + global $DIC; + + $ilCtrl = $DIC->ctrl(); + + if ($ilCtrl->getCmdClass() == "ilnewsitemgui") { + return IL_SCREEN_FULL; + } + + switch ($ilCtrl->getCmd()) { + case "showNews": + case "showFeedUrl": + return IL_SCREEN_CENTER; + break; + + case "editSettings": + case "saveSettings": + return IL_SCREEN_FULL; + break; + + default: + return IL_SCREEN_SIDE; + break; + } + } + + /** + * execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $next_class = $ilCtrl->getNextClass(); + $cmd = $ilCtrl->getCmd("getHTML"); + + switch ($next_class) { + case "ilnewsitemgui": + include_once("./Services/News/classes/class.ilNewsItemGUI.php"); + $news_item_gui = new ilNewsItemGUI(); + $news_item_gui->setEnableEdit($this->getEnableEdit()); + $html = $ilCtrl->forwardCommand($news_item_gui); + return $html; + + default: + return $this->$cmd(); + } + } + + /** + * Set EnableEdit. + * + * @param boolean $a_enable_edit Edit mode on/off + */ + public function setEnableEdit($a_enable_edit = 0) + { + $this->enable_edit = $a_enable_edit; + } + + /** + * Get EnableEdit. + * + * @return boolean Edit mode on/off + */ + public function getEnableEdit() + { + return $this->enable_edit; + } + + /** + * Fill data section + */ + public function fillDataSection() + { + if ($this->dynamic) { + $this->setDataSection($this->getDynamicReload()); + } elseif ($this->getCurrentDetailLevel() > 1 && count($this->getData()) > 0) { + parent::fillDataSection(); + } else { + $this->setDataSection($this->getOverview()); + } + } + + /** + * Get bloch HTML code. + */ + public function getHTML() + { + global $DIC; + + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilUser = $this->user; + + $news_set = new ilSetting("news"); + $enable_internal_rss = $news_set->get("enable_rss_for_internal"); + + $hide_block = ilBlockSetting::_lookup( + $this->getBlockType(), + "hide_news_block", + 0, + $this->block_id + ); + if ($hide_block) { + $this->setFooterInfo($lng->txt("news_hidden_news_block")); + } + + if ($this->getProperty("title") != "") { + $this->setTitle($this->getProperty("title")); + } + + $public_feed = ilBlockSetting::_lookup( + $this->getBlockType(), + "public_feed", + 0, + $this->block_id + ); + if ($public_feed) { + if ($enable_internal_rss) { + include_once("./Services/News/classes/class.ilRSSButtonGUI.php"); + $this->addBlockCommand( + ILIAS_HTTP_PATH . "/feed.php?client_id=" . rawurlencode(CLIENT_ID) . "&" . + "ref_id=" . $_GET["ref_id"], + $lng->txt("news_feed_url"), + "", + "", + true, + false, + ilRSSButtonGUI::get(ilRSSButtonGUI::ICON_RSS) + ); + } + } + + /* Subscription Concept is abandonded for now (Alex) + // subscribe/unsibscribe link + include_once("./Services/News/classes/class.ilNewsSubscription.php"); + if (ilNewsSubscription::_hasSubscribed($_GET["ref_id"], $ilUser->getId())) + { + $this->addBlockCommand( + $ilCtrl->getLinkTarget($this, "unsubscribeNews"), + $lng->txt("news_unsubscribe")); + } + else + { + $this->addBlockCommand( + $ilCtrl->getLinkTarget($this, "subscribeNews"), + $lng->txt("news_subscribe")); + } + */ + + // add edit commands + if ($this->getEnableEdit()) { + $this->addBlockCommand( + $ilCtrl->getLinkTargetByClass("ilnewsitemgui", "editNews"), + $lng->txt("edit") + ); + + $ilCtrl->setParameter($this, "add_mode", "block"); + $this->addBlockCommand( + $ilCtrl->getLinkTargetByClass("ilnewsitemgui", "createNewsItem"), + $lng->txt("add") + ); + $ilCtrl->setParameter($this, "add_mode", ""); + } + + if ($this->getProperty("settings") == true) { + $ref_id = $_GET["ref_id"]; + $obj_def = $DIC["objDefinition"]; + $obj_id = ilObject::_lookupObjectId($ref_id); + $obj_type = ilObject::_lookupType($ref_id, true); + $obj_class= strtolower($obj_def->getClassName($obj_type)); + $parent_gui = "ilobj" . $obj_class . "gui"; + + $ilCtrl->setParameterByClass("ilcontainernewssettingsgui", "ref_id", $ref_id); + + if (in_array($obj_class, ilNewsForContextBlockGUI::OBJECTS_WITH_NEWS_SUBTAB)) { + $this->addBlockCommand( + $ilCtrl->getLinkTargetByClass(array("ilrepositorygui", $parent_gui, "ilcontainernewssettingsgui"), "show"), + $lng->txt("settings") + ); + } else { + $this->addBlockCommand( + $ilCtrl->getLinkTarget($this, "editSettings"), + $lng->txt("settings") + ); + } + } + + // do not display hidden repository news blocks for users + // who do not have write permission + if (!$this->getEnableEdit() && $this->getRepositoryMode() && + ilBlockSetting::_lookup( + $this->getBlockType(), + "hide_news_block", + 0, + $this->block_id + )) { + return ""; + } + + // do not display empty news blocks for users + // who do not have write permission + if (count($this->getData()) == 0 && !$this->getEnableEdit() && + $this->getRepositoryMode() && !$this->dynamic + && (!$news_set->get("enable_rss_for_internal") || + !ilBlockSetting::_lookup( + $this->getBlockType(), + "public_feed", + 0, + $this->block_id + ))) { + return ""; + } + + $en = ""; + if ($ilUser->getPref("il_feed_js") == "n") { + // $en = getJSEnabler(); + } + + return parent::getHTML() . $en; + } + + /** + * Handles show/hide notification view and removes notifications if hidden. + */ + public function handleView() + { + $ilUser = $this->user; + + include_once("Services/Block/classes/class.ilBlockSetting.php"); + $this->view = ilBlockSetting::_lookup( + $this->getBlockType(), + "view", + $ilUser->getId(), + $this->block_id + ); + + // check whether notices and messages exist + $got_notices = $got_messages = false; + foreach ($this->data as $row) { + if ($row["priority"] == 0) { + $got_notices = true; + } + if ($row["priority"] == 1) { + $got_messages = true; + } + } + $this->show_view_selection = false; + + if ($got_notices && $got_messages) { + $this->show_view_selection = true; + } elseif ($got_notices) { + $this->view = ""; + } + + // remove notifications if hidden /* - if (($this->view == "hide_notifications") && $this->show_view_selection) - { - $rset = array(); - foreach($this->data as $k => $row) - { - if ($row["priority"] == 1) - { - $rset[$k] = $row; - } - } - $this->data = $rset; - } + if (($this->view == "hide_notifications") && $this->show_view_selection) + { + $rset = array(); + foreach($this->data as $k => $row) + { + if ($row["priority"] == 1) + { + $rset[$k] = $row; + } + } + $this->data = $rset; + } */ - } - - /** - * get flat bookmark list for personal desktop - */ - function fillRow($news) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $obj_definition = $this->obj_definition; - - if ($this->getCurrentDetailLevel() > 2) - { - $this->tpl->setCurrentBlock("long"); - //$this->tpl->setVariable("VAL_CONTENT", $news["content"]); - $this->tpl->setVariable("VAL_CREATION_DATE", - ilDatePresentation::formatDate(new ilDateTime($news["creation_date"],IL_CAL_DATETIME))); - $this->tpl->parseCurrentBlock(); - } - - // title image type - if ($news["ref_id"] > 0) - { - if ($news["agg_ref_id"] > 0) - { - $obj_id = ilObject::_lookupObjId($news["agg_ref_id"]); - $type = ilObject::_lookupType($obj_id); - $context_ref = $news["agg_ref_id"]; - } - else - { - $obj_id = $news["context_obj_id"]; - $type = $news["context_obj_type"]; - $context_ref = $news["ref_id"]; - } - - $lang_type = in_array($type, array("sahs", "lm", "htlm")) - ? "lres" - : "obj_".$type; - - $type_txt = ($obj_definition->isPlugin($news["context_obj_type"])) - ? ilObjectPlugin::lookupTxtById($news["context_obj_type"], $lang_type) - : $lng->txt($lang_type); - - $this->tpl->setCurrentBlock("news_context"); - $this->tpl->setVariable("TYPE", $type_txt); - $this->tpl->setVariable("IMG_TYPE", - ilObject::_getIcon($obj_id, "tiny", $type)); - $this->tpl->setVariable("TITLE", - ilUtil::shortenWords(ilObject::_lookupTitle($obj_id))); - if ($news["user_read"] > 0) - { - $this->tpl->setVariable("TITLE_CLASS", 'class="light"'); - } - - $this->tpl->parseCurrentBlock(); - $ilCtrl->setParameter($this, "news_context", $context_ref); - } - else - { - $ilCtrl->setParameter($this, "news_context", ""); - } - - // title - $this->tpl->setVariable("VAL_TITLE", - ilUtil::shortenWords(ilNewsItem::determineNewsTitle - ($news["context_obj_type"], $news["title"], $news["content_is_lang_var"], - $news["agg_ref_id"], $news["aggregation"]))); - - - if ($news["user_read"] > 0) - { - $this->tpl->setVariable("A_CLASS", 'class="light"'); - } - - $ilCtrl->setParameter($this, "news_id", $news["id"]); - $this->tpl->setVariable("HREF_SHOW", - $ilCtrl->getLinkTarget($this, "showNews")); - $ilCtrl->clearParameters($this); - } - - /** - * Get overview. - */ - function getOverview() - { - $ilUser = $this->user; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - return '
                  '.((int) count($this->getData()))." ".$lng->txt("news_news_items")."
                  "; - } - - /** - * show news - */ - function showNews() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - $ilAccess = $this->access; - - // workaround for dynamic mode (if cache is disabled, showNews has no data) - if (empty(self::$st_data)) - { - $this->setData($this->getNewsData()); - } - - $news_set = new ilSetting("news"); - $enable_internal_rss = $news_set->get("enable_rss_for_internal"); - - include_once("./Services/News/classes/class.ilNewsItem.php"); - $news = new ilNewsItem((int) $_GET["news_id"]); - - $tpl = new ilTemplate("tpl.show_news.html", true, true, "Services/News"); - - // get current item in data set - $previous = $next = ""; - reset($this->data); - $c = current($this->data); - $curr_cnt = 1; - - while($c["id"] > 0 && - $c["id"] != $_GET["news_id"]) - { - $previous = $c; - $c = next($this->data); - $curr_cnt++; - } - - if (!is_array($c) && is_object($news) && $news->getId() > 0 - && ilNewsItem::_lookupContextObjId($news->getId()) != $ilCtrl->getContextObjId()) - { - throw new ilException("News ID does not match object context."); - } - - - // collect news items to show - $news_list = array(); - if (is_array($c["aggregation"])) // we have an aggregation - { - $news_list[] = array("ref_id" => $c["agg_ref_id"], - "agg_ref_id" => $c["agg_ref_id"], - "aggregation" => $c["aggregation"], - "user_id" => "", - "content_type" => "text", - "mob_id" => 0, - "visibility" => "", - "content" => "", - "content_long" => "", - "update_date" => $news->getUpdateDate(), - "creation_date" => "", - "content_is_lang_var" => false, - "loc_context" => $_GET["news_context"], - "context_obj_type" => $news->getContextObjType(), + } + + /** + * get flat bookmark list for personal desktop + */ + public function fillRow($news) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $obj_definition = $this->obj_definition; + + if ($this->getCurrentDetailLevel() > 2) { + $this->tpl->setCurrentBlock("long"); + //$this->tpl->setVariable("VAL_CONTENT", $news["content"]); + $this->tpl->setVariable( + "VAL_CREATION_DATE", + ilDatePresentation::formatDate(new ilDateTime($news["creation_date"], IL_CAL_DATETIME)) + ); + $this->tpl->parseCurrentBlock(); + } + + // title image type + if ($news["ref_id"] > 0) { + if ($news["agg_ref_id"] > 0) { + $obj_id = ilObject::_lookupObjId($news["agg_ref_id"]); + $type = ilObject::_lookupType($obj_id); + $context_ref = $news["agg_ref_id"]; + } else { + $obj_id = $news["context_obj_id"]; + $type = $news["context_obj_type"]; + $context_ref = $news["ref_id"]; + } + + $lang_type = in_array($type, array("sahs", "lm", "htlm")) + ? "lres" + : "obj_" . $type; + + $type_txt = ($obj_definition->isPlugin($news["context_obj_type"])) + ? ilObjectPlugin::lookupTxtById($news["context_obj_type"], $lang_type) + : $lng->txt($lang_type); + + $this->tpl->setCurrentBlock("news_context"); + $this->tpl->setVariable("TYPE", $type_txt); + $this->tpl->setVariable( + "IMG_TYPE", + ilObject::_getIcon($obj_id, "tiny", $type) + ); + $this->tpl->setVariable( + "TITLE", + ilUtil::shortenWords(ilObject::_lookupTitle($obj_id)) + ); + if ($news["user_read"] > 0) { + $this->tpl->setVariable("TITLE_CLASS", 'class="light"'); + } + + $this->tpl->parseCurrentBlock(); + $ilCtrl->setParameter($this, "news_context", $context_ref); + } else { + $ilCtrl->setParameter($this, "news_context", ""); + } + + // title + $this->tpl->setVariable( + "VAL_TITLE", + ilUtil::shortenWords(ilNewsItem::determineNewsTitle( + $news["context_obj_type"], + $news["title"], + $news["content_is_lang_var"], + $news["agg_ref_id"], + $news["aggregation"] + )) + ); + + + if ($news["user_read"] > 0) { + $this->tpl->setVariable("A_CLASS", 'class="light"'); + } + + $ilCtrl->setParameter($this, "news_id", $news["id"]); + $this->tpl->setVariable( + "HREF_SHOW", + $ilCtrl->getLinkTarget($this, "showNews") + ); + $ilCtrl->clearParameters($this); + } + + /** + * Get overview. + */ + public function getOverview() + { + $ilUser = $this->user; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + return '
                  ' . ((int) count($this->getData())) . " " . $lng->txt("news_news_items") . "
                  "; + } + + /** + * show news + */ + public function showNews() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + $ilAccess = $this->access; + + // workaround for dynamic mode (if cache is disabled, showNews has no data) + if (empty(self::$st_data)) { + $this->setData($this->getNewsData()); + } + + $news_set = new ilSetting("news"); + $enable_internal_rss = $news_set->get("enable_rss_for_internal"); + + include_once("./Services/News/classes/class.ilNewsItem.php"); + $news = new ilNewsItem((int) $_GET["news_id"]); + + $tpl = new ilTemplate("tpl.show_news.html", true, true, "Services/News"); + + // get current item in data set + $previous = $next = ""; + reset($this->data); + $c = current($this->data); + $curr_cnt = 1; + + while ($c["id"] > 0 && + $c["id"] != $_GET["news_id"]) { + $previous = $c; + $c = next($this->data); + $curr_cnt++; + } + + if (!is_array($c) && is_object($news) && $news->getId() > 0 + && ilNewsItem::_lookupContextObjId($news->getId()) != $ilCtrl->getContextObjId()) { + throw new ilException("News ID does not match object context."); + } + + + // collect news items to show + $news_list = array(); + if (is_array($c["aggregation"])) { // we have an aggregation + $news_list[] = array("ref_id" => $c["agg_ref_id"], + "agg_ref_id" => $c["agg_ref_id"], + "aggregation" => $c["aggregation"], + "user_id" => "", + "content_type" => "text", + "mob_id" => 0, + "visibility" => "", + "content" => "", + "content_long" => "", + "update_date" => $news->getUpdateDate(), + "creation_date" => "", + "content_is_lang_var" => false, + "loc_context" => $_GET["news_context"], + "context_obj_type" => $news->getContextObjType(), "title" => ""); - foreach($c["aggregation"] as $c_item) - { - ilNewsItem::_setRead($ilUser->getId(), $c_item["id"]); - $c_item["loc_context"] = $c_item["ref_id"]; - $c_item["loc_stop"] = $_GET["news_context"]; - $news_list[] = $c_item; - } - } - else // no aggregation, simple news item - { - $news_list[] = array( - "id" => $news->getId(), - "ref_id" => $_GET["news_context"], - "user_id" => $news->getUserId(), - "content_type" => $news->getContentType(), - "mob_id" => $news->getMobId(), - "visibility" => $news->getVisibility(), - "priority" => $news->getPriority(), - "content" => $news->getContent(), - "content_long" => $news->getContentLong(), - "update_date" => $news->getUpdateDate(), - "creation_date" => $news->getCreationDate(), - "context_sub_obj_type" => $news->getContextSubObjType(), - "context_obj_type" => $news->getContextObjType(), - "context_sub_obj_id" => $news->getContextSubObjId(), - "content_is_lang_var" => $news->getContentIsLangVar(), - "content_text_is_lang_var" => $news->getContentTextIsLangVar(), - "loc_context" => $_GET["news_context"], + foreach ($c["aggregation"] as $c_item) { + ilNewsItem::_setRead($ilUser->getId(), $c_item["id"]); + $c_item["loc_context"] = $c_item["ref_id"]; + $c_item["loc_stop"] = $_GET["news_context"]; + $news_list[] = $c_item; + } + } else { // no aggregation, simple news item + $news_list[] = array( + "id" => $news->getId(), + "ref_id" => $_GET["news_context"], + "user_id" => $news->getUserId(), + "content_type" => $news->getContentType(), + "mob_id" => $news->getMobId(), + "visibility" => $news->getVisibility(), + "priority" => $news->getPriority(), + "content" => $news->getContent(), + "content_long" => $news->getContentLong(), + "update_date" => $news->getUpdateDate(), + "creation_date" => $news->getCreationDate(), + "context_sub_obj_type" => $news->getContextSubObjType(), + "context_obj_type" => $news->getContextObjType(), + "context_sub_obj_id" => $news->getContextSubObjId(), + "content_is_lang_var" => $news->getContentIsLangVar(), + "content_text_is_lang_var" => $news->getContentTextIsLangVar(), + "loc_context" => $_GET["news_context"], "title" => $news->getTitle()); - ilNewsItem::_setRead($ilUser->getId(), $_GET["news_id"]); - } - - $row_css = ""; - $cache_deleted = false; - foreach ($news_list as $item) - { - $row_css = ($row_css != "tblrow1") - ? "tblrow1" - : "tblrow2"; - - if ($item["ref_id"] > 0 && !$ilAccess->checkAccess("read", "", $item["ref_id"])) - { - $tpl->setCurrentBlock("content"); - $tpl->setVariable("VAL_CONTENT", $lng->txt("news_sorry_not_accessible_anymore")); - $tpl->parseCurrentBlock(); - $tpl->setCurrentBlock("item"); - $tpl->setVariable("ITEM_ROW_CSS", $row_css); - $tpl->parseCurrentBlock(); - if (!$cache_deleted) - { - $this->acache->deleteEntry($ilUser->getId() . ":" . $_GET["ref_id"]); - $cache_deleted = true; - } - continue; - } - - // user - if ($item["user_id"] > 0 && ilObject::_exists($item["user_id"])) - { - // get login - if (ilObjUser::_exists($item["user_id"])) - { - $user = new ilObjUser($item["user_id"]); - $displayname = $user->getLogin(); - } else - { - // this should actually not happen, since news entries - // should be deleted when the user is going to be removed - $displayname = "<". strtolower($lng->txt("deleted")) .">"; - } - - $tpl->setCurrentBlock("user_info"); - $tpl->setVariable("VAL_AUTHOR", $displayname); - $tpl->setVariable("TXT_AUTHOR", $lng->txt("author")); - $tpl->parseCurrentBlock(); - } - - // media player - if ($item["content_type"] == NEWS_AUDIO && - $item["mob_id"] > 0 && ilObject::_exists($item["mob_id"])) - { - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - include_once("./Services/MediaObjects/classes/class.ilMediaPlayerGUI.php"); - $mob = new ilObjMediaObject($item["mob_id"]); - $med = $mob->getMediaItem("Standard"); - $mpl = new ilMediaPlayerGUI("news_pl_".$item["mob_id"]); - if (strcasecmp("Reference", $med->getLocationType()) == 0) - $mpl->setFile($med->getLocation()); - else - $mpl->setFile(ilObjMediaObject::_getURL($mob->getId())."/".$med->getLocation()); - $mpl->setDisplayHeight($med->getHeight()); - $tpl->setCurrentBlock("player"); - $tpl->setVariable("PLAYER", - $mpl->getMp3PlayerHtml()); - $tpl->parseCurrentBlock(); - } - - // access - if ($enable_internal_rss && $item["visibility"] != "") - { - $obj_id = ilObject::_lookupObjId($item["ref_id"]); - $tpl->setCurrentBlock("access"); - $tpl->setVariable("TXT_ACCESS", $lng->txt("news_news_item_visibility")); - if ($item["visibility"] == NEWS_PUBLIC || - ($item["priority"] == 0 && - ilBlockSetting::_lookup("news", "public_notifications", - 0, $obj_id))) - { - $tpl->setVariable("VAL_ACCESS", $lng->txt("news_visibility_public")); - } - else - { - $tpl->setVariable("VAL_ACCESS", $lng->txt("news_visibility_users")); - } - $tpl->parseCurrentBlock(); - } - - // content - include_once("./Services/News/classes/class.ilNewsRendererFactory.php"); - $renderer = ilNewsRendererFactory::getRenderer($item["context_obj_type"]); - if (trim($item["content"]) != "") // content - { - $it = new ilNewsItem($item["id"]); - $renderer->setNewsItem($it, $item["ref_id"]); - $tpl->setCurrentBlock("content"); - $tpl->setVariable("VAL_CONTENT", $renderer->getDetailContent()); - $tpl->parseCurrentBlock(); - } - if ($item["update_date"] != $item["creation_date"]) // update date - { - $tpl->setCurrentBlock("ni_update"); - $tpl->setVariable("TXT_LAST_UPDATE", $lng->txt("last_update")); - $tpl->setVariable("VAL_LAST_UPDATE", - ilDatePresentation::formatDate(new ilDateTime($item["update_date"],IL_CAL_DATETIME))); - $tpl->parseCurrentBlock(); - } - - // creation date - if ($item["creation_date"] != "") - { - $tpl->setCurrentBlock("ni_update"); - $tpl->setVariable("VAL_CREATION_DATE", - ilDatePresentation::formatDate(new ilDateTime($item["creation_date"],IL_CAL_DATETIME))); - $tpl->setVariable("TXT_CREATED", $lng->txt("created")); - $tpl->parseCurrentBlock(); - } - - - // context / title - if ($_GET["news_context"] > 0) - { - //$obj_id = ilObject::_lookupObjId($_GET["news_context"]); - $obj_id = ilObject::_lookupObjId($item["ref_id"]); - $obj_type = ilObject::_lookupType($obj_id); - $obj_title = ilObject::_lookupTitle($obj_id); - - // file hack, not nice - if ($obj_type == "file") - { - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $item["ref_id"]); - $url = $ilCtrl->getLinkTargetByClass("ilrepositorygui", "sendfile"); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - - include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; - $button = ilLinkButton::getInstance(); - $button->setUrl($url); - $button->setCaption("download"); - - $tpl->setCurrentBlock("download"); - $tpl->setVariable("BUTTON_DOWNLOAD", $button->render()); - $tpl->parseCurrentBlock(); - } - - // forum hack, not nice - $add = ""; - if ($obj_type == "frm" && $item["context_sub_obj_type"] == "pos" - && $item["context_sub_obj_id"] > 0) - { - include_once("./Modules/Forum/classes/class.ilObjForumAccess.php"); - $pos = $item["context_sub_obj_id"]; - $thread = ilObjForumAccess::_getThreadForPosting($pos); - if ($thread > 0) - { - $add = "_".$thread."_".$pos; - } - } - - // wiki hack, not nice - if ($obj_type == "wiki" && $item["context_sub_obj_type"] == "wpg" - && $item["context_sub_obj_id"] > 0) - { - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $wptitle = ilWikiPage::lookupTitle($item["context_sub_obj_id"]); - if ($wptitle != "") - { - $add = "_".ilWikiUtil::makeUrlTitle($wptitle); - } - } - - $url_target = "./goto.php?client_id=".rawurlencode(CLIENT_ID)."&target=". - $obj_type."_".$item["ref_id"].$add; - - // lm page hack, not nice - if (in_array($obj_type, array("lm")) && $item["context_sub_obj_type"] == "pg" - && $item["context_sub_obj_id"] > 0) - { - $url_target = "./goto.php?client_id=".rawurlencode(CLIENT_ID)."&target=". - "pg_".$item["context_sub_obj_id"]."_".$item["ref_id"]; - } - - // blog posting hack, not nice - if ($obj_type == "blog" && $item["context_sub_obj_type"] == "blp" - && $item["context_sub_obj_id"] > 0) - { - $url_target = "./goto.php?client_id=".rawurlencode(CLIENT_ID)."&target=". - "blog_".$item["ref_id"]."_".$item["context_sub_obj_id"]; - } - - $context_opened = false; - if ($item["loc_context"] != null && $item["loc_context"] != $item["loc_stop"]) - { - - $tpl->setCurrentBlock("context"); - $context_opened = true; - $cont_loc = new ilLocatorGUI(); - $cont_loc->addContextItems($item["loc_context"], true, $item["loc_stop"]); - $tpl->setVariable("CONTEXT_LOCATOR", $cont_loc->getHTML()); - } - -//var_dump($item); - if ($item["no_context_title"] !== true) - { - if (!$context_opened) - { - $tpl->setCurrentBlock("context"); - } - $tpl->setVariable("HREF_CONTEXT_TITLE", $url_target); - $tpl->setVariable("CONTEXT_TITLE", $obj_title); - $tpl->setVariable("IMG_CONTEXT_TITLE", ilObject::_getIcon($obj_id, "big", $obj_type)); - } - if ($context_opened) - { - $tpl->parseCurrentBlock(); - } - - $tpl->setVariable("HREF_TITLE", $url_target); - } - - // title - $tpl->setVariable("VAL_TITLE", - ilNewsItem::determineNewsTitle($item["context_obj_type"], - $item["title"], $item["content_is_lang_var"], $item["agg_ref_id"], - $item["aggregation"])); - - - $tpl->setCurrentBlock("item"); - $tpl->setVariable("ITEM_ROW_CSS", $row_css); - $tpl->parseCurrentBlock(); - } - - include_once("./Services/PersonalDesktop/classes/class.ilPDContentBlockGUI.php"); - $content_block = new ilPDContentBlockGUI(); - $content_block->setContent($tpl->get()); - if ($this->getProperty("title") != "") - { - $content_block->setTitle($this->getProperty("title")); - } - else - { - $content_block->setTitle($lng->txt("news_internal_news")); - } - $this->addCloseCommand($content_block); - - // previous - if ($previous != "") - { - if ($previous["ref_id"] > 0) - { - $ilCtrl->setParameter($this, "news_context", $previous["ref_id"]); - } - $ilCtrl->setParameter($this, "news_id", $previous["id"]); - $content_block->addFooterLink($lng->txt("previous"), - $ilCtrl->getLinkTarget($this, "showNews"), "", "", true); - $ilCtrl->setParameter($this, "news_context", ""); - } - - // next - if ($c = next($this->data)) - { - if ($c["ref_id"] > 0) - { - $ilCtrl->setParameter($this, "news_context", $c["ref_id"]); - } - $ilCtrl->setParameter($this, "news_id", $c["id"]); - $content_block->addFooterLink($lng->txt("next"), - $ilCtrl->getLinkTarget($this, "showNews"), "", "", true); - } - $ilCtrl->setParameter($this, "news_context", ""); - $ilCtrl->setParameter($this, "news_id", ""); - $content_block->setCurrentItemNumber($curr_cnt); - $content_block->setEnableNumInfo(true); - $content_block->setData($this->getData()); - - return $content_block->getHTML(); - } - - /** - * Make clickable - * - * @param - * @return - */ - function makeClickable($a_str) - { - // this fixes bug 8744. We assume that strings that contain < and > - // already contain html, we do not handle these - if (is_int(strpos($a_str, ">")) && is_int(strpos($a_str, "<"))) - { - return $a_str; - } - - return ilUtil::makeClickable($a_str); - } - - - /** - * Unsubscribe current user from news - */ - function unsubscribeNews() - { - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - - include_once("./Services/News/classes/class.ilNewsSubscription.php"); - ilNewsSubscription::_unsubscribe($_GET["ref_id"], $ilUser->getId()); - $ilCtrl->returnToParent($this); - } - - /** - * Subscribe current user from news - */ - function subscribeNews() - { - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - - include_once("./Services/News/classes/class.ilNewsSubscription.php"); - ilNewsSubscription::_subscribe($_GET["ref_id"], $ilUser->getId()); - $ilCtrl->returnToParent($this); - } - - /** - * block footer - */ - function fillFooter() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilUser = $this->user; - - parent::fillFooter(); - - if ($this->show_view_selection) - { - $this->showViewFooter(); - } - } - - /** - * Show additional footer for show/hide notifications - */ - function showViewFooter() - { - $ilUser = $this->user; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - return; // notifications always shown - - $this->clearFooterLinks(); - $this->addFooterLink("[".$lng->txt("news_first_letter_of_word_notification")."] ". - $lng->txt("news_notifications").": ", "", "", "", false, true); - if ($this->view == "hide_notifications") - { - $this->addFooterLink($lng->txt("show"), - $ilCtrl->getLinkTarget($this, - "showNotifications"), - $ilCtrl->getLinkTarget($this, - "showNotifications", "", true), - "block_".$this->getBlockType()."_".$this->block_id - ); - $this->addFooterLink($lng->txt("hide")); - } - else - { - $this->addFooterLink($lng->txt("show")); - $this->addFooterLink($lng->txt("hide"), - $ilCtrl->getLinkTarget($this, - "hideNotifications"), - $ilCtrl->getLinkTarget($this, - "hideNotifications", "", true), - "block_".$this->getBlockType()."_".$this->block_id - ); - } - - $this->fillFooterLinks(); - } - - function showNotifications() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - include_once("Services/Block/classes/class.ilBlockSetting.php"); - $view = ilBlockSetting::_write($this->getBlockType(), "view", "", - $ilUser->getId(), $this->block_id); - - // reload data - $data = $this->getNewsData(); - $this->setData($data); - $this->handleView(); - - if ($ilCtrl->isAsynch()) - { - echo $this->getHTML(); - exit; - } - else - { - $ilCtrl->returnToParent($this); - } - } - - function hideNotifications() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - include_once("Services/Block/classes/class.ilBlockSetting.php"); - $view = ilBlockSetting::_write($this->getBlockType(), "view", "hide_notifications", - $ilUser->getId(), $this->block_id); - - // reload data - $data = $this->getNewsData(); - $this->setData($data); - $this->handleView(); - - if ($ilCtrl->isAsynch()) - { - echo $this->getHTML(); - exit; - } - else - { - $ilCtrl->returnToParent($this); - } - } - - /** - * Show settings screen. - */ - function editSettings() - { - $this->initSettingsForm(); - return $this->settings_form->getHTML(); - } - - /** - * Init setting form - */ - function initSettingsForm() - { - $ilUser = $this->user; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilSetting = $this->settings; - $ilTabs = $this->tabs; - - $ilTabs->clearTargets(); - - $news_set = new ilSetting("news"); - $enable_internal_rss = $news_set->get("enable_rss_for_internal"); - - $public = ilBlockSetting::_lookup($this->getBlockType(), "public_notifications", - 0, $this->block_id); - $public_feed = ilBlockSetting::_lookup($this->getBlockType(), "public_feed", - 0, $this->block_id); - $hide_block = ilBlockSetting::_lookup($this->getBlockType(), "hide_news_block", - 0, $this->block_id); - $hide_news_per_date = ilBlockSetting::_lookup($this->getBlockType(), "hide_news_per_date", - 0, $this->block_id); - $hide_news_date = ilBlockSetting::_lookup($this->getBlockType(), "hide_news_date", - 0, $this->block_id); - - if ($hide_news_date != "") - { - $hide_news_date = explode(" ", $hide_news_date); - } - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->settings_form = new ilPropertyFormGUI(); - $this->settings_form->setTitle($lng->txt("news_settings")); - - // hide news block for learners - if ($this->getProperty("hide_news_block_option")) - { - $ch = new ilCheckboxInputGUI($lng->txt("news_hide_news_block"), - "hide_news_block"); - $ch->setInfo($lng->txt("news_hide_news_block_info")); - $ch->setChecked($hide_block); - $this->settings_form->addItem($ch); - - $hnpd = new ilCheckboxInputGUI($lng->txt("news_hide_news_per_date"), - "hide_news_per_date"); - $hnpd->setInfo($lng->txt("news_hide_news_per_date_info")); - $hnpd->setChecked($hide_news_per_date); - - $dt_prop = new ilDateTimeInputGUI($lng->txt("news_hide_news_date"), - "hide_news_date"); - $dt_prop->setRequired(true); - if ($hide_news_date != "") - { - $dt_prop->setDate(new ilDateTime($hide_news_date[0].' '.$hide_news_date[1],IL_CAL_DATETIME)); - } - #$dt_prop->setDate($hide_news_date[0]); - #$dt_prop->setTime($hide_news_date[1]); - $dt_prop->setShowTime(true); - //$dt_prop->setInfo($lng->txt("news_hide_news_date_info")); - $hnpd->addSubItem($dt_prop); - - $this->settings_form->addItem($hnpd); - - } - - // default visibility - if ($this->getProperty("default_visibility_option") && - $enable_internal_rss) - { - $default_visibility = ilBlockSetting::_lookup($this->getBlockType(), "default_visibility", - 0, $this->block_id); - if ($default_visibility == "") - { - $default_visibility = - ilNewsItem::_getDefaultVisibilityForRefId($_GET["ref_id"]); - } - - // Default Visibility - $radio_group = new ilRadioGroupInputGUI($lng->txt("news_default_visibility"), "default_visibility"); - $radio_option = new ilRadioOption($lng->txt("news_visibility_users"), "users"); - $radio_group->addOption($radio_option); - $radio_option = new ilRadioOption($lng->txt("news_visibility_public"), "public"); - $radio_group->addOption($radio_option); - $radio_group->setInfo($lng->txt("news_news_item_visibility_info")); - $radio_group->setRequired(false); - $radio_group->setValue($default_visibility); - $this->settings_form->addItem($radio_group); - } - - // public notifications - if ($this->getProperty("public_notifications_option") && - $enable_internal_rss) - { - $ch = new ilCheckboxInputGUI($lng->txt("news_notifications_public"), - "notifications_public"); - $ch->setInfo($lng->txt("news_notifications_public_info")); - $ch->setChecked($public); - $this->settings_form->addItem($ch); - } - - // extra rss feed - if ($enable_internal_rss) - { - $ch = new ilCheckboxInputGUI($lng->txt("news_public_feed"), - "notifications_public_feed"); - $ch->setInfo($lng->txt("news_public_feed_info")); - $ch->setChecked($public_feed); - $this->settings_form->addItem($ch); - } - - - //$this->settings_form->addCheckboxProperty($lng->txt("news_public_feed"), "notifications_public_feed", - // "1", $public_feed, $lng->txt("news_public_feed_info")); - //if ($this->getProperty("public_notifications_option")) - //{ - // $this->settings_form->addCheckboxProperty($lng->txt("news_notifications_public"), "notifications_public", - // "1", $public, $lng->txt("news_notifications_public_info")); - //} - $this->settings_form->addCommandButton("saveSettings", $lng->txt("save")); - $this->settings_form->addCommandButton("cancelSettings", $lng->txt("cancel")); - $this->settings_form->setFormAction($ilCtrl->getFormaction($this)); - } - - /** - * Add inputs to the container news settings form to configure also the contextBlock options. - * @param ilFormPropertyGUI $a_input - */ - static function addToSettingsForm(ilFormPropertyGUI $a_input) - { - global $DIC; - - $lng = $DIC->language(); - $block_id = $DIC->ctrl()->getContextObjId(); - - $news_set = new ilSetting("news"); - $enable_internal_rss = $news_set->get("enable_rss_for_internal"); - - //$public_notification = ilBlockSetting::_lookup(self::$block_type, "public_notifications",0, $block_id); - $public_feed = ilBlockSetting::_lookup(self::$block_type, "public_feed", - 0, $block_id); - - $default_visibility = ilBlockSetting::_lookup(self::$block_type, "default_visibility_option", 0, $block_id); - if ($default_visibility == "") - { - $default_visibility = - ilNewsItem::_getDefaultVisibilityForRefId($_GET["ref_id"]); - } - - $radio_group = new ilRadioGroupInputGUI($lng->txt("news_default_visibility"), "default_visibility"); - $radio_option = new ilRadioOption($lng->txt("news_visibility_users"), "users"); - $radio_group->addOption($radio_option); - $radio_option = new ilRadioOption($lng->txt("news_visibility_public"), "public"); - $radio_group->addOption($radio_option); - $radio_group->setInfo($lng->txt("news_news_item_visibility_info")); - $radio_group->setRequired(false); - $radio_group->setValue($default_visibility); - $a_input->addSubItem($radio_group); - - // extra rss feed - if ($enable_internal_rss) - { - $radio_rss = new ilCheckboxInputGUI($lng->txt("news_public_feed"), - "notifications_public_feed"); - $radio_rss->setInfo($lng->txt("news_public_feed_info")); - $radio_rss->setChecked($public_feed); - $a_input->addSubItem($radio_rss); - } - } - - static function writeSettings($a_values) - { - global $DIC; - - $block_id = $DIC->ctrl()->getContextObjId(); - - foreach($a_values as $key=>$value) - { - ilBlockSetting::_write(self::$block_type, $key, $value, 0, $block_id); - } - } - - /** - * Cancel settings. - */ - function cancelSettings() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->returnToParent($this); - } - - /** - * Save settings. - */ - function saveSettings() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - $this->initSettingsForm(); - - if ($this->settings_form->checkInput()) - { - $news_set = new ilSetting("news"); - $enable_internal_rss = $news_set->get("enable_rss_for_internal"); - - if ($enable_internal_rss) - { - ilBlockSetting::_write($this->getBlockType(), "public_notifications", $_POST["notifications_public"], - 0, $this->block_id); - ilBlockSetting::_write($this->getBlockType(), "public_feed", $_POST["notifications_public_feed"], - 0, $this->block_id); - ilBlockSetting::_write($this->getBlockType(), "default_visibility", $_POST["default_visibility"], - 0, $this->block_id); - } - - if ($this->getProperty("hide_news_block_option")) - { - ilBlockSetting::_write($this->getBlockType(), "hide_news_block", $_POST["hide_news_block"], - 0, $this->block_id); - ilBlockSetting::_write($this->getBlockType(), "hide_news_per_date", $_POST["hide_news_per_date"], - 0, $this->block_id); - - // hide date - $hd = $this->settings_form->getItemByPostVar("hide_news_date"); - $hide_date = $hd->getDate(); - if ($_POST["hide_news_per_date"] && $hide_date != null) - { - ilBlockSetting::_write($this->getBlockType(), "hide_news_date", - $hide_date->get(IL_CAL_DATETIME), - 0, $this->block_id); - } - else - { - ilBlockSetting::_write($this->getBlockType(), "hide_news_date", - "", - 0, $this->block_id); - } - } - - include_once("./Services/News/classes/class.ilNewsCache.php"); - $cache = new ilNewsCache(); - $cache->deleteEntry($ilUser->getId().":".$_GET["ref_id"]); - - $ilCtrl->returnToParent($this); - } - else - { - $this->settings_form->setValuesByPost(); - return $this->settings_form->getHtml(); - } - } - - /** - * Show feed URL. - */ - function showFeedUrl() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - include_once("./Services/News/classes/class.ilNewsItem.php"); - - $title = ilObject::_lookupTitle($this->block_id); - - $tpl = new ilTemplate("tpl.show_feed_url.html", true, true, "Services/News"); - $tpl->setVariable("TXT_TITLE", - sprintf($lng->txt("news_feed_url_for"), $title)); - $tpl->setVariable("TXT_INFO", $lng->txt("news_get_feed_info")); - $tpl->setVariable("TXT_FEED_URL", $lng->txt("news_feed_url")); - $tpl->setVariable("VAL_FEED_URL", - ILIAS_HTTP_PATH."/feed.php?client_id=".rawurlencode(CLIENT_ID)."&user_id=".$ilUser->getId(). - "&obj_id=".$this->block_id. - "&hash=".ilObjUser::_lookupFeedHash($ilUser->getId(), true)); - $tpl->setVariable("VAL_FEED_URL_TXT", - ILIAS_HTTP_PATH."/feed.php?client_id=".rawurlencode(CLIENT_ID)."&
                  user_id=".$ilUser->getId(). - "&obj_id=".$this->block_id. - "&hash=".ilObjUser::_lookupFeedHash($ilUser->getId(), true)); - - include_once("./Services/PersonalDesktop/classes/class.ilPDContentBlockGUI.php"); - $content_block = new ilPDContentBlockGUI(); - $content_block->setContent($tpl->get()); - $content_block->setTitle($lng->txt("news_internal_news")); - $content_block->addHeaderCommand($ilCtrl->getParentReturn($this), - $lng->txt("close"), true); - - return $content_block->getHTML(); - } - - function addCloseCommand($a_content_block) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $a_content_block->addHeaderCommand($ilCtrl->getParentReturn($this), - $lng->txt("close"), true); - } - - function getDynamic() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - if ($ilCtrl->getCmd() == "hideNotifications" || - $ilCtrl->getCmd() == "showNotifications") - { - return false; - } - - if ($ilCtrl->getCmdClass() != "ilcolumngui" && $ilCtrl->getCmd() != "enableJS") - { - $sess_feed_js = ""; - if (isset($_SESSION["il_feed_js"])) - { - $sess_feed_js = $_SESSION["il_feed_js"]; - } - - if ($sess_feed_js != "n" && - ($ilUser->getPref("il_feed_js") != "n" || $sess_feed_js == "y")) - { - // do not get feed dynamically, if cache hit is given. -// if (!$this->feed->checkCacheHit()) -// { - return true; -// } - } - } - - return false; - } - - function getDynamicReload() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $ilCtrl->setParameterByClass("ilcolumngui", "block_id", - "block_".$this->getBlockType()."_".$this->getBlockId()); - - $rel_tpl = new ilTemplate("tpl.dynamic_reload.html", true, true, "Services/News"); - $rel_tpl->setVariable("TXT_LOADING", $lng->txt("news_loading_news")); - $rel_tpl->setVariable("BLOCK_ID", "block_".$this->getBlockType()."_".$this->getBlockId()); - $rel_tpl->setVariable("TARGET", - $ilCtrl->getLinkTargetByClass("ilcolumngui", "updateBlock", "", true)); - - // no JS - $rel_tpl->setVariable("TXT_NEWS_CLICK_HERE", $lng->txt("news_no_js_click_here")); - $rel_tpl->setVariable("TARGET_NO_JS", - $ilCtrl->getLinkTargetByClass(strtolower(get_class($this)), "disableJS")); - - return $rel_tpl->get(); - } - - function getJSEnabler() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $ilCtrl->setParameterByClass("ilcolumngui", "block_id", - "block_".$this->getBlockType()."_".$this->getBlockId()); -//echo "hh"; - $rel_tpl = new ilTemplate("tpl.js_enabler.html", true, true, "Services/News"); - $rel_tpl->setVariable("BLOCK_ID", "block_".$this->getBlockType()."_".$this->getBlockId()); - $rel_tpl->setVariable("TARGET", - $ilCtrl->getLinkTargetByClass(strtolower(get_class($this)), "enableJS", true, "", false)); - - return $rel_tpl->get(); - } - - - function disableJS() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - $_SESSION["il_feed_js"] = "n"; - $ilUser->writePref("il_feed_js", "n"); -$ilCtrl->returnToParent($this); - //$ilCtrl->redirectByClass("ilpersonaldesktopgui", "show"); - } - - function enableJS() - { - $ilUser = $this->user; -//echo "enableJS"; - $_SESSION["il_feed_js"] = "y"; - $ilUser->writePref("il_feed_js", "y"); - echo $this->getHTML(); - exit; - } - + ilNewsItem::_setRead($ilUser->getId(), $_GET["news_id"]); + } + + $row_css = ""; + $cache_deleted = false; + foreach ($news_list as $item) { + $row_css = ($row_css != "tblrow1") + ? "tblrow1" + : "tblrow2"; + + if ($item["ref_id"] > 0 && !$ilAccess->checkAccess("read", "", $item["ref_id"])) { + $tpl->setCurrentBlock("content"); + $tpl->setVariable("VAL_CONTENT", $lng->txt("news_sorry_not_accessible_anymore")); + $tpl->parseCurrentBlock(); + $tpl->setCurrentBlock("item"); + $tpl->setVariable("ITEM_ROW_CSS", $row_css); + $tpl->parseCurrentBlock(); + if (!$cache_deleted) { + $this->acache->deleteEntry($ilUser->getId() . ":" . $_GET["ref_id"]); + $cache_deleted = true; + } + continue; + } + + // user + if ($item["user_id"] > 0 && ilObject::_exists($item["user_id"])) { + // get login + if (ilObjUser::_exists($item["user_id"])) { + $user = new ilObjUser($item["user_id"]); + $displayname = $user->getLogin(); + } else { + // this should actually not happen, since news entries + // should be deleted when the user is going to be removed + $displayname = "<" . strtolower($lng->txt("deleted")) . ">"; + } + + $tpl->setCurrentBlock("user_info"); + $tpl->setVariable("VAL_AUTHOR", $displayname); + $tpl->setVariable("TXT_AUTHOR", $lng->txt("author")); + $tpl->parseCurrentBlock(); + } + + // media player + if ($item["content_type"] == NEWS_AUDIO && + $item["mob_id"] > 0 && ilObject::_exists($item["mob_id"])) { + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + include_once("./Services/MediaObjects/classes/class.ilMediaPlayerGUI.php"); + $mob = new ilObjMediaObject($item["mob_id"]); + $med = $mob->getMediaItem("Standard"); + $mpl = new ilMediaPlayerGUI("news_pl_" . $item["mob_id"]); + if (strcasecmp("Reference", $med->getLocationType()) == 0) { + $mpl->setFile($med->getLocation()); + } else { + $mpl->setFile(ilObjMediaObject::_getURL($mob->getId()) . "/" . $med->getLocation()); + } + $mpl->setDisplayHeight($med->getHeight()); + $tpl->setCurrentBlock("player"); + $tpl->setVariable( + "PLAYER", + $mpl->getMp3PlayerHtml() + ); + $tpl->parseCurrentBlock(); + } + + // access + if ($enable_internal_rss && $item["visibility"] != "") { + $obj_id = ilObject::_lookupObjId($item["ref_id"]); + $tpl->setCurrentBlock("access"); + $tpl->setVariable("TXT_ACCESS", $lng->txt("news_news_item_visibility")); + if ($item["visibility"] == NEWS_PUBLIC || + ($item["priority"] == 0 && + ilBlockSetting::_lookup( + "news", + "public_notifications", + 0, + $obj_id + ))) { + $tpl->setVariable("VAL_ACCESS", $lng->txt("news_visibility_public")); + } else { + $tpl->setVariable("VAL_ACCESS", $lng->txt("news_visibility_users")); + } + $tpl->parseCurrentBlock(); + } + + // content + include_once("./Services/News/classes/class.ilNewsRendererFactory.php"); + $renderer = ilNewsRendererFactory::getRenderer($item["context_obj_type"]); + if (trim($item["content"]) != "") { // content + $it = new ilNewsItem($item["id"]); + $renderer->setNewsItem($it, $item["ref_id"]); + $tpl->setCurrentBlock("content"); + $tpl->setVariable("VAL_CONTENT", $renderer->getDetailContent()); + $tpl->parseCurrentBlock(); + } + if ($item["update_date"] != $item["creation_date"]) { // update date + $tpl->setCurrentBlock("ni_update"); + $tpl->setVariable("TXT_LAST_UPDATE", $lng->txt("last_update")); + $tpl->setVariable( + "VAL_LAST_UPDATE", + ilDatePresentation::formatDate(new ilDateTime($item["update_date"], IL_CAL_DATETIME)) + ); + $tpl->parseCurrentBlock(); + } + + // creation date + if ($item["creation_date"] != "") { + $tpl->setCurrentBlock("ni_update"); + $tpl->setVariable( + "VAL_CREATION_DATE", + ilDatePresentation::formatDate(new ilDateTime($item["creation_date"], IL_CAL_DATETIME)) + ); + $tpl->setVariable("TXT_CREATED", $lng->txt("created")); + $tpl->parseCurrentBlock(); + } + + + // context / title + if ($_GET["news_context"] > 0) { + //$obj_id = ilObject::_lookupObjId($_GET["news_context"]); + $obj_id = ilObject::_lookupObjId($item["ref_id"]); + $obj_type = ilObject::_lookupType($obj_id); + $obj_title = ilObject::_lookupTitle($obj_id); + + // file hack, not nice + if ($obj_type == "file") { + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $item["ref_id"]); + $url = $ilCtrl->getLinkTargetByClass("ilrepositorygui", "sendfile"); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + + include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; + $button = ilLinkButton::getInstance(); + $button->setUrl($url); + $button->setCaption("download"); + + $tpl->setCurrentBlock("download"); + $tpl->setVariable("BUTTON_DOWNLOAD", $button->render()); + $tpl->parseCurrentBlock(); + } + + // forum hack, not nice + $add = ""; + if ($obj_type == "frm" && $item["context_sub_obj_type"] == "pos" + && $item["context_sub_obj_id"] > 0) { + include_once("./Modules/Forum/classes/class.ilObjForumAccess.php"); + $pos = $item["context_sub_obj_id"]; + $thread = ilObjForumAccess::_getThreadForPosting($pos); + if ($thread > 0) { + $add = "_" . $thread . "_" . $pos; + } + } + + // wiki hack, not nice + if ($obj_type == "wiki" && $item["context_sub_obj_type"] == "wpg" + && $item["context_sub_obj_id"] > 0) { + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + $wptitle = ilWikiPage::lookupTitle($item["context_sub_obj_id"]); + if ($wptitle != "") { + $add = "_" . ilWikiUtil::makeUrlTitle($wptitle); + } + } + + $url_target = "./goto.php?client_id=" . rawurlencode(CLIENT_ID) . "&target=" . + $obj_type . "_" . $item["ref_id"] . $add; + + // lm page hack, not nice + if (in_array($obj_type, array("lm")) && $item["context_sub_obj_type"] == "pg" + && $item["context_sub_obj_id"] > 0) { + $url_target = "./goto.php?client_id=" . rawurlencode(CLIENT_ID) . "&target=" . + "pg_" . $item["context_sub_obj_id"] . "_" . $item["ref_id"]; + } + + // blog posting hack, not nice + if ($obj_type == "blog" && $item["context_sub_obj_type"] == "blp" + && $item["context_sub_obj_id"] > 0) { + $url_target = "./goto.php?client_id=" . rawurlencode(CLIENT_ID) . "&target=" . + "blog_" . $item["ref_id"] . "_" . $item["context_sub_obj_id"]; + } + + $context_opened = false; + if ($item["loc_context"] != null && $item["loc_context"] != $item["loc_stop"]) { + $tpl->setCurrentBlock("context"); + $context_opened = true; + $cont_loc = new ilLocatorGUI(); + $cont_loc->addContextItems($item["loc_context"], true, $item["loc_stop"]); + $tpl->setVariable("CONTEXT_LOCATOR", $cont_loc->getHTML()); + } + + //var_dump($item); + if ($item["no_context_title"] !== true) { + if (!$context_opened) { + $tpl->setCurrentBlock("context"); + } + $tpl->setVariable("HREF_CONTEXT_TITLE", $url_target); + $tpl->setVariable("CONTEXT_TITLE", $obj_title); + $tpl->setVariable("IMG_CONTEXT_TITLE", ilObject::_getIcon($obj_id, "big", $obj_type)); + } + if ($context_opened) { + $tpl->parseCurrentBlock(); + } + + $tpl->setVariable("HREF_TITLE", $url_target); + } + + // title + $tpl->setVariable( + "VAL_TITLE", + ilNewsItem::determineNewsTitle( + $item["context_obj_type"], + $item["title"], + $item["content_is_lang_var"], + $item["agg_ref_id"], + $item["aggregation"] + ) + ); + + + $tpl->setCurrentBlock("item"); + $tpl->setVariable("ITEM_ROW_CSS", $row_css); + $tpl->parseCurrentBlock(); + } + + include_once("./Services/PersonalDesktop/classes/class.ilPDContentBlockGUI.php"); + $content_block = new ilPDContentBlockGUI(); + $content_block->setContent($tpl->get()); + if ($this->getProperty("title") != "") { + $content_block->setTitle($this->getProperty("title")); + } else { + $content_block->setTitle($lng->txt("news_internal_news")); + } + $this->addCloseCommand($content_block); + + // previous + if ($previous != "") { + if ($previous["ref_id"] > 0) { + $ilCtrl->setParameter($this, "news_context", $previous["ref_id"]); + } + $ilCtrl->setParameter($this, "news_id", $previous["id"]); + $content_block->addFooterLink( + $lng->txt("previous"), + $ilCtrl->getLinkTarget($this, "showNews"), + "", + "", + true + ); + $ilCtrl->setParameter($this, "news_context", ""); + } + + // next + if ($c = next($this->data)) { + if ($c["ref_id"] > 0) { + $ilCtrl->setParameter($this, "news_context", $c["ref_id"]); + } + $ilCtrl->setParameter($this, "news_id", $c["id"]); + $content_block->addFooterLink( + $lng->txt("next"), + $ilCtrl->getLinkTarget($this, "showNews"), + "", + "", + true + ); + } + $ilCtrl->setParameter($this, "news_context", ""); + $ilCtrl->setParameter($this, "news_id", ""); + $content_block->setCurrentItemNumber($curr_cnt); + $content_block->setEnableNumInfo(true); + $content_block->setData($this->getData()); + + return $content_block->getHTML(); + } + + /** + * Make clickable + * + * @param + * @return + */ + public function makeClickable($a_str) + { + // this fixes bug 8744. We assume that strings that contain < and > + // already contain html, we do not handle these + if (is_int(strpos($a_str, ">")) && is_int(strpos($a_str, "<"))) { + return $a_str; + } + + return ilUtil::makeClickable($a_str); + } + + + /** + * Unsubscribe current user from news + */ + public function unsubscribeNews() + { + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + + include_once("./Services/News/classes/class.ilNewsSubscription.php"); + ilNewsSubscription::_unsubscribe($_GET["ref_id"], $ilUser->getId()); + $ilCtrl->returnToParent($this); + } + + /** + * Subscribe current user from news + */ + public function subscribeNews() + { + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + + include_once("./Services/News/classes/class.ilNewsSubscription.php"); + ilNewsSubscription::_subscribe($_GET["ref_id"], $ilUser->getId()); + $ilCtrl->returnToParent($this); + } + + /** + * block footer + */ + public function fillFooter() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilUser = $this->user; + + parent::fillFooter(); + + if ($this->show_view_selection) { + $this->showViewFooter(); + } + } + + /** + * Show additional footer for show/hide notifications + */ + public function showViewFooter() + { + $ilUser = $this->user; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + return; // notifications always shown + + $this->clearFooterLinks(); + $this->addFooterLink("[" . $lng->txt("news_first_letter_of_word_notification") . "] " . + $lng->txt("news_notifications") . ": ", "", "", "", false, true); + if ($this->view == "hide_notifications") { + $this->addFooterLink( + $lng->txt("show"), + $ilCtrl->getLinkTarget( + $this, + "showNotifications" + ), + $ilCtrl->getLinkTarget( + $this, + "showNotifications", + "", + true + ), + "block_" . $this->getBlockType() . "_" . $this->block_id + ); + $this->addFooterLink($lng->txt("hide")); + } else { + $this->addFooterLink($lng->txt("show")); + $this->addFooterLink( + $lng->txt("hide"), + $ilCtrl->getLinkTarget( + $this, + "hideNotifications" + ), + $ilCtrl->getLinkTarget( + $this, + "hideNotifications", + "", + true + ), + "block_" . $this->getBlockType() . "_" . $this->block_id + ); + } + + $this->fillFooterLinks(); + } + + public function showNotifications() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + include_once("Services/Block/classes/class.ilBlockSetting.php"); + $view = ilBlockSetting::_write( + $this->getBlockType(), + "view", + "", + $ilUser->getId(), + $this->block_id + ); + + // reload data + $data = $this->getNewsData(); + $this->setData($data); + $this->handleView(); + + if ($ilCtrl->isAsynch()) { + echo $this->getHTML(); + exit; + } else { + $ilCtrl->returnToParent($this); + } + } + + public function hideNotifications() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + include_once("Services/Block/classes/class.ilBlockSetting.php"); + $view = ilBlockSetting::_write( + $this->getBlockType(), + "view", + "hide_notifications", + $ilUser->getId(), + $this->block_id + ); + + // reload data + $data = $this->getNewsData(); + $this->setData($data); + $this->handleView(); + + if ($ilCtrl->isAsynch()) { + echo $this->getHTML(); + exit; + } else { + $ilCtrl->returnToParent($this); + } + } + + /** + * Show settings screen. + */ + public function editSettings() + { + $this->initSettingsForm(); + return $this->settings_form->getHTML(); + } + + /** + * Init setting form + */ + public function initSettingsForm() + { + $ilUser = $this->user; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilSetting = $this->settings; + $ilTabs = $this->tabs; + + $ilTabs->clearTargets(); + + $news_set = new ilSetting("news"); + $enable_internal_rss = $news_set->get("enable_rss_for_internal"); + + $public = ilBlockSetting::_lookup( + $this->getBlockType(), + "public_notifications", + 0, + $this->block_id + ); + $public_feed = ilBlockSetting::_lookup( + $this->getBlockType(), + "public_feed", + 0, + $this->block_id + ); + $hide_block = ilBlockSetting::_lookup( + $this->getBlockType(), + "hide_news_block", + 0, + $this->block_id + ); + $hide_news_per_date = ilBlockSetting::_lookup( + $this->getBlockType(), + "hide_news_per_date", + 0, + $this->block_id + ); + $hide_news_date = ilBlockSetting::_lookup( + $this->getBlockType(), + "hide_news_date", + 0, + $this->block_id + ); + + if ($hide_news_date != "") { + $hide_news_date = explode(" ", $hide_news_date); + } + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->settings_form = new ilPropertyFormGUI(); + $this->settings_form->setTitle($lng->txt("news_settings")); + + // hide news block for learners + if ($this->getProperty("hide_news_block_option")) { + $ch = new ilCheckboxInputGUI( + $lng->txt("news_hide_news_block"), + "hide_news_block" + ); + $ch->setInfo($lng->txt("news_hide_news_block_info")); + $ch->setChecked($hide_block); + $this->settings_form->addItem($ch); + + $hnpd = new ilCheckboxInputGUI( + $lng->txt("news_hide_news_per_date"), + "hide_news_per_date" + ); + $hnpd->setInfo($lng->txt("news_hide_news_per_date_info")); + $hnpd->setChecked($hide_news_per_date); + + $dt_prop = new ilDateTimeInputGUI( + $lng->txt("news_hide_news_date"), + "hide_news_date" + ); + $dt_prop->setRequired(true); + if ($hide_news_date != "") { + $dt_prop->setDate(new ilDateTime($hide_news_date[0] . ' ' . $hide_news_date[1], IL_CAL_DATETIME)); + } + #$dt_prop->setDate($hide_news_date[0]); + #$dt_prop->setTime($hide_news_date[1]); + $dt_prop->setShowTime(true); + //$dt_prop->setInfo($lng->txt("news_hide_news_date_info")); + $hnpd->addSubItem($dt_prop); + + $this->settings_form->addItem($hnpd); + } + + // default visibility + if ($this->getProperty("default_visibility_option") && + $enable_internal_rss) { + $default_visibility = ilBlockSetting::_lookup( + $this->getBlockType(), + "default_visibility", + 0, + $this->block_id + ); + if ($default_visibility == "") { + $default_visibility = + ilNewsItem::_getDefaultVisibilityForRefId($_GET["ref_id"]); + } + + // Default Visibility + $radio_group = new ilRadioGroupInputGUI($lng->txt("news_default_visibility"), "default_visibility"); + $radio_option = new ilRadioOption($lng->txt("news_visibility_users"), "users"); + $radio_group->addOption($radio_option); + $radio_option = new ilRadioOption($lng->txt("news_visibility_public"), "public"); + $radio_group->addOption($radio_option); + $radio_group->setInfo($lng->txt("news_news_item_visibility_info")); + $radio_group->setRequired(false); + $radio_group->setValue($default_visibility); + $this->settings_form->addItem($radio_group); + } + + // public notifications + if ($this->getProperty("public_notifications_option") && + $enable_internal_rss) { + $ch = new ilCheckboxInputGUI( + $lng->txt("news_notifications_public"), + "notifications_public" + ); + $ch->setInfo($lng->txt("news_notifications_public_info")); + $ch->setChecked($public); + $this->settings_form->addItem($ch); + } + + // extra rss feed + if ($enable_internal_rss) { + $ch = new ilCheckboxInputGUI( + $lng->txt("news_public_feed"), + "notifications_public_feed" + ); + $ch->setInfo($lng->txt("news_public_feed_info")); + $ch->setChecked($public_feed); + $this->settings_form->addItem($ch); + } + + + //$this->settings_form->addCheckboxProperty($lng->txt("news_public_feed"), "notifications_public_feed", + // "1", $public_feed, $lng->txt("news_public_feed_info")); + //if ($this->getProperty("public_notifications_option")) + //{ + // $this->settings_form->addCheckboxProperty($lng->txt("news_notifications_public"), "notifications_public", + // "1", $public, $lng->txt("news_notifications_public_info")); + //} + $this->settings_form->addCommandButton("saveSettings", $lng->txt("save")); + $this->settings_form->addCommandButton("cancelSettings", $lng->txt("cancel")); + $this->settings_form->setFormAction($ilCtrl->getFormaction($this)); + } + + /** + * Add inputs to the container news settings form to configure also the contextBlock options. + * @param ilFormPropertyGUI $a_input + */ + public static function addToSettingsForm(ilFormPropertyGUI $a_input) + { + global $DIC; + + $lng = $DIC->language(); + $block_id = $DIC->ctrl()->getContextObjId(); + + $news_set = new ilSetting("news"); + $enable_internal_rss = $news_set->get("enable_rss_for_internal"); + + //$public_notification = ilBlockSetting::_lookup(self::$block_type, "public_notifications",0, $block_id); + $public_feed = ilBlockSetting::_lookup( + self::$block_type, + "public_feed", + 0, + $block_id + ); + + $default_visibility = ilBlockSetting::_lookup(self::$block_type, "default_visibility_option", 0, $block_id); + if ($default_visibility == "") { + $default_visibility = + ilNewsItem::_getDefaultVisibilityForRefId($_GET["ref_id"]); + } + + $radio_group = new ilRadioGroupInputGUI($lng->txt("news_default_visibility"), "default_visibility"); + $radio_option = new ilRadioOption($lng->txt("news_visibility_users"), "users"); + $radio_group->addOption($radio_option); + $radio_option = new ilRadioOption($lng->txt("news_visibility_public"), "public"); + $radio_group->addOption($radio_option); + $radio_group->setInfo($lng->txt("news_news_item_visibility_info")); + $radio_group->setRequired(false); + $radio_group->setValue($default_visibility); + $a_input->addSubItem($radio_group); + + // extra rss feed + if ($enable_internal_rss) { + $radio_rss = new ilCheckboxInputGUI( + $lng->txt("news_public_feed"), + "notifications_public_feed" + ); + $radio_rss->setInfo($lng->txt("news_public_feed_info")); + $radio_rss->setChecked($public_feed); + $a_input->addSubItem($radio_rss); + } + } + + public static function writeSettings($a_values) + { + global $DIC; + + $block_id = $DIC->ctrl()->getContextObjId(); + + foreach ($a_values as $key=>$value) { + ilBlockSetting::_write(self::$block_type, $key, $value, 0, $block_id); + } + } + + /** + * Cancel settings. + */ + public function cancelSettings() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->returnToParent($this); + } + + /** + * Save settings. + */ + public function saveSettings() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + $this->initSettingsForm(); + + if ($this->settings_form->checkInput()) { + $news_set = new ilSetting("news"); + $enable_internal_rss = $news_set->get("enable_rss_for_internal"); + + if ($enable_internal_rss) { + ilBlockSetting::_write( + $this->getBlockType(), + "public_notifications", + $_POST["notifications_public"], + 0, + $this->block_id + ); + ilBlockSetting::_write( + $this->getBlockType(), + "public_feed", + $_POST["notifications_public_feed"], + 0, + $this->block_id + ); + ilBlockSetting::_write( + $this->getBlockType(), + "default_visibility", + $_POST["default_visibility"], + 0, + $this->block_id + ); + } + + if ($this->getProperty("hide_news_block_option")) { + ilBlockSetting::_write( + $this->getBlockType(), + "hide_news_block", + $_POST["hide_news_block"], + 0, + $this->block_id + ); + ilBlockSetting::_write( + $this->getBlockType(), + "hide_news_per_date", + $_POST["hide_news_per_date"], + 0, + $this->block_id + ); + + // hide date + $hd = $this->settings_form->getItemByPostVar("hide_news_date"); + $hide_date = $hd->getDate(); + if ($_POST["hide_news_per_date"] && $hide_date != null) { + ilBlockSetting::_write( + $this->getBlockType(), + "hide_news_date", + $hide_date->get(IL_CAL_DATETIME), + 0, + $this->block_id + ); + } else { + ilBlockSetting::_write( + $this->getBlockType(), + "hide_news_date", + "", + 0, + $this->block_id + ); + } + } + + include_once("./Services/News/classes/class.ilNewsCache.php"); + $cache = new ilNewsCache(); + $cache->deleteEntry($ilUser->getId() . ":" . $_GET["ref_id"]); + + $ilCtrl->returnToParent($this); + } else { + $this->settings_form->setValuesByPost(); + return $this->settings_form->getHtml(); + } + } + + /** + * Show feed URL. + */ + public function showFeedUrl() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + include_once("./Services/News/classes/class.ilNewsItem.php"); + + $title = ilObject::_lookupTitle($this->block_id); + + $tpl = new ilTemplate("tpl.show_feed_url.html", true, true, "Services/News"); + $tpl->setVariable( + "TXT_TITLE", + sprintf($lng->txt("news_feed_url_for"), $title) + ); + $tpl->setVariable("TXT_INFO", $lng->txt("news_get_feed_info")); + $tpl->setVariable("TXT_FEED_URL", $lng->txt("news_feed_url")); + $tpl->setVariable( + "VAL_FEED_URL", + ILIAS_HTTP_PATH . "/feed.php?client_id=" . rawurlencode(CLIENT_ID) . "&user_id=" . $ilUser->getId() . + "&obj_id=" . $this->block_id . + "&hash=" . ilObjUser::_lookupFeedHash($ilUser->getId(), true) + ); + $tpl->setVariable( + "VAL_FEED_URL_TXT", + ILIAS_HTTP_PATH . "/feed.php?client_id=" . rawurlencode(CLIENT_ID) . "&
                  user_id=" . $ilUser->getId() . + "&obj_id=" . $this->block_id . + "&hash=" . ilObjUser::_lookupFeedHash($ilUser->getId(), true) + ); + + include_once("./Services/PersonalDesktop/classes/class.ilPDContentBlockGUI.php"); + $content_block = new ilPDContentBlockGUI(); + $content_block->setContent($tpl->get()); + $content_block->setTitle($lng->txt("news_internal_news")); + $content_block->addHeaderCommand( + $ilCtrl->getParentReturn($this), + $lng->txt("close"), + true + ); + + return $content_block->getHTML(); + } + + public function addCloseCommand($a_content_block) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $a_content_block->addHeaderCommand( + $ilCtrl->getParentReturn($this), + $lng->txt("close"), + true + ); + } + + public function getDynamic() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + if ($ilCtrl->getCmd() == "hideNotifications" || + $ilCtrl->getCmd() == "showNotifications") { + return false; + } + + if ($ilCtrl->getCmdClass() != "ilcolumngui" && $ilCtrl->getCmd() != "enableJS") { + $sess_feed_js = ""; + if (isset($_SESSION["il_feed_js"])) { + $sess_feed_js = $_SESSION["il_feed_js"]; + } + + if ($sess_feed_js != "n" && + ($ilUser->getPref("il_feed_js") != "n" || $sess_feed_js == "y")) { + // do not get feed dynamically, if cache hit is given. + // if (!$this->feed->checkCacheHit()) + // { + return true; + // } + } + } + + return false; + } + + public function getDynamicReload() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $ilCtrl->setParameterByClass( + "ilcolumngui", + "block_id", + "block_" . $this->getBlockType() . "_" . $this->getBlockId() + ); + + $rel_tpl = new ilTemplate("tpl.dynamic_reload.html", true, true, "Services/News"); + $rel_tpl->setVariable("TXT_LOADING", $lng->txt("news_loading_news")); + $rel_tpl->setVariable("BLOCK_ID", "block_" . $this->getBlockType() . "_" . $this->getBlockId()); + $rel_tpl->setVariable( + "TARGET", + $ilCtrl->getLinkTargetByClass("ilcolumngui", "updateBlock", "", true) + ); + + // no JS + $rel_tpl->setVariable("TXT_NEWS_CLICK_HERE", $lng->txt("news_no_js_click_here")); + $rel_tpl->setVariable( + "TARGET_NO_JS", + $ilCtrl->getLinkTargetByClass(strtolower(get_class($this)), "disableJS") + ); + + return $rel_tpl->get(); + } + + public function getJSEnabler() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $ilCtrl->setParameterByClass( + "ilcolumngui", + "block_id", + "block_" . $this->getBlockType() . "_" . $this->getBlockId() + ); + //echo "hh"; + $rel_tpl = new ilTemplate("tpl.js_enabler.html", true, true, "Services/News"); + $rel_tpl->setVariable("BLOCK_ID", "block_" . $this->getBlockType() . "_" . $this->getBlockId()); + $rel_tpl->setVariable( + "TARGET", + $ilCtrl->getLinkTargetByClass(strtolower(get_class($this)), "enableJS", true, "", false) + ); + + return $rel_tpl->get(); + } + + + public function disableJS() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + $_SESSION["il_feed_js"] = "n"; + $ilUser->writePref("il_feed_js", "n"); + $ilCtrl->returnToParent($this); + //$ilCtrl->redirectByClass("ilpersonaldesktopgui", "show"); + } + + public function enableJS() + { + $ilUser = $this->user; + //echo "enableJS"; + $_SESSION["il_feed_js"] = "y"; + $ilUser->writePref("il_feed_js", "y"); + echo $this->getHTML(); + exit; + } } - -?> diff --git a/Services/News/classes/class.ilNewsForContextTableGUI.php b/Services/News/classes/class.ilNewsForContextTableGUI.php index 2bb29992ba31edc368765f771185412415347c18..06c60d13d231d08aa4fac3e6936c540dfb0d0837 100755 --- a/Services/News/classes/class.ilNewsForContextTableGUI.php +++ b/Services/News/classes/class.ilNewsForContextTableGUI.php @@ -13,134 +13,141 @@ include_once("Services/Table/classes/class.ilTable2GUI.php"); */ class ilNewsForContextTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilAccessHandler - */ - protected $access; - - - function __construct($a_parent_obj, $a_parent_cmd = "", $a_perm_ref_id = 0) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->perm_ref_id = $a_perm_ref_id; - - $this->addColumn("", "f", "1"); - $this->addColumn($lng->txt("news_news_item_content")); - $this->addColumn($lng->txt("news_attached_to")); - $this->addColumn($lng->txt("access")); - $this->addColumn($lng->txt("author")); - $this->addColumn($lng->txt("created")); - $this->addColumn($lng->txt("last_update")); - $this->addColumn($lng->txt("actions")); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.table_row_news_for_context.html", - "Services/News"); - } - - /** - * Standard Version of Fill Row. Most likely to - * be overwritten by derived class. - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - - $news_set = new ilSetting("news"); - $enable_internal_rss = $news_set->get("enable_rss_for_internal"); - - // user - if ($a_set["user_id"] > 0) - { - $this->tpl->setCurrentBlock("user_info"); - $user_obj = new ilObjUser($a_set["user_id"]); - $this->tpl->setVariable("VAL_AUTHOR", $user_obj->getLogin()); - $this->tpl->setVariable("TXT_AUTHOR", $lng->txt("author")); - $this->tpl->parseCurrentBlock(); - } - - // access - if ($enable_internal_rss) - { - $this->tpl->setCurrentBlock("access"); - $this->tpl->setVariable("TXT_ACCESS", $lng->txt("news_news_item_visibility")); - if ($a_set["visibility"] == NEWS_PUBLIC || - ($a_set["priority"] == 0 && - ilBlockSetting::_lookup("news", "public_notifications", - 0, $a_set["context_obj_id"]))) - { - $this->tpl->setVariable("VAL_ACCESS", $lng->txt("news_visibility_public")); - } - else - { - $this->tpl->setVariable("VAL_ACCESS", $lng->txt("news_visibility_users")); - } - $this->tpl->parseCurrentBlock(); - } - - // last update - if ($a_set["creation_date"] != $a_set["update_date"]) - { - $this->tpl->setCurrentBlock("ni_update"); - $this->tpl->setVariable("TXT_LAST_UPDATE", $lng->txt("last_update")); - $this->tpl->setVariable("VAL_LAST_UPDATE", - ilDatePresentation::formatDate(new ilDateTime($a_set["update_date"],IL_CAL_DATETIME))); - $this->tpl->parseCurrentBlock(); - } - - // creation date - $this->tpl->setVariable("VAL_CREATION_DATE", - ilDatePresentation::formatDate(new ilDateTime($a_set["creation_date"],IL_CAL_DATETIME))); - $this->tpl->setVariable("TXT_CREATED", $lng->txt("created")); - - // title - $this->tpl->setVariable("VAL_TITLE", $a_set["title"]); - - // content - if ($a_set["content"] != "") - { - $this->tpl->setCurrentBlock("content"); - $this->tpl->setVariable("VAL_CONTENT", - ilUtil::shortenText($a_set["content"], 80, true, true), true); - $this->tpl->parseCurrentBlock(); - } - - $perm_ref_id = ($this->perm_ref_id > 0) - ? $this->perm_ref_id - : $a_set["ref_id"]; - - if ($ilAccess->checkAccess("write", "", $perm_ref_id)) - { - $this->tpl->setCurrentBlock("edit"); - $this->tpl->setVariable("TXT_EDIT", $lng->txt("edit")); - $ilCtrl->setParameterByClass("ilnewsitemgui", "news_item_id", $a_set["id"]); - $this->tpl->setVariable("CMD_EDIT", - $ilCtrl->getLinkTargetByClass("ilnewsitemgui", "editNewsItem")); - $this->tpl->parseCurrentBlock(); - } - - // context - $this->tpl->setVariable("CONTEXT", - $lng->txt("obj_".$a_set["context_obj_type"]).":
                  ". - ilObject::_lookupTitle($a_set["context_obj_id"])); - - $this->tpl->setVariable("VAL_ID", $a_set["id"]); - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilAccessHandler + */ + protected $access; + + + public function __construct($a_parent_obj, $a_parent_cmd = "", $a_perm_ref_id = 0) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->perm_ref_id = $a_perm_ref_id; + + $this->addColumn("", "f", "1"); + $this->addColumn($lng->txt("news_news_item_content")); + $this->addColumn($lng->txt("news_attached_to")); + $this->addColumn($lng->txt("access")); + $this->addColumn($lng->txt("author")); + $this->addColumn($lng->txt("created")); + $this->addColumn($lng->txt("last_update")); + $this->addColumn($lng->txt("actions")); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate( + "tpl.table_row_news_for_context.html", + "Services/News" + ); + } + + /** + * Standard Version of Fill Row. Most likely to + * be overwritten by derived class. + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + + $news_set = new ilSetting("news"); + $enable_internal_rss = $news_set->get("enable_rss_for_internal"); + + // user + if ($a_set["user_id"] > 0) { + $this->tpl->setCurrentBlock("user_info"); + $user_obj = new ilObjUser($a_set["user_id"]); + $this->tpl->setVariable("VAL_AUTHOR", $user_obj->getLogin()); + $this->tpl->setVariable("TXT_AUTHOR", $lng->txt("author")); + $this->tpl->parseCurrentBlock(); + } + + // access + if ($enable_internal_rss) { + $this->tpl->setCurrentBlock("access"); + $this->tpl->setVariable("TXT_ACCESS", $lng->txt("news_news_item_visibility")); + if ($a_set["visibility"] == NEWS_PUBLIC || + ($a_set["priority"] == 0 && + ilBlockSetting::_lookup( + "news", + "public_notifications", + 0, + $a_set["context_obj_id"] + ))) { + $this->tpl->setVariable("VAL_ACCESS", $lng->txt("news_visibility_public")); + } else { + $this->tpl->setVariable("VAL_ACCESS", $lng->txt("news_visibility_users")); + } + $this->tpl->parseCurrentBlock(); + } + + // last update + if ($a_set["creation_date"] != $a_set["update_date"]) { + $this->tpl->setCurrentBlock("ni_update"); + $this->tpl->setVariable("TXT_LAST_UPDATE", $lng->txt("last_update")); + $this->tpl->setVariable( + "VAL_LAST_UPDATE", + ilDatePresentation::formatDate(new ilDateTime($a_set["update_date"], IL_CAL_DATETIME)) + ); + $this->tpl->parseCurrentBlock(); + } + + // creation date + $this->tpl->setVariable( + "VAL_CREATION_DATE", + ilDatePresentation::formatDate(new ilDateTime($a_set["creation_date"], IL_CAL_DATETIME)) + ); + $this->tpl->setVariable("TXT_CREATED", $lng->txt("created")); + + // title + $this->tpl->setVariable("VAL_TITLE", $a_set["title"]); + + // content + if ($a_set["content"] != "") { + $this->tpl->setCurrentBlock("content"); + $this->tpl->setVariable( + "VAL_CONTENT", + ilUtil::shortenText($a_set["content"], 80, true, true), + true + ); + $this->tpl->parseCurrentBlock(); + } + + $perm_ref_id = ($this->perm_ref_id > 0) + ? $this->perm_ref_id + : $a_set["ref_id"]; + + if ($ilAccess->checkAccess("write", "", $perm_ref_id)) { + $this->tpl->setCurrentBlock("edit"); + $this->tpl->setVariable("TXT_EDIT", $lng->txt("edit")); + $ilCtrl->setParameterByClass("ilnewsitemgui", "news_item_id", $a_set["id"]); + $this->tpl->setVariable( + "CMD_EDIT", + $ilCtrl->getLinkTargetByClass("ilnewsitemgui", "editNewsItem") + ); + $this->tpl->parseCurrentBlock(); + } + + // context + $this->tpl->setVariable( + "CONTEXT", + $lng->txt("obj_" . $a_set["context_obj_type"]) . ":
                  " . + ilObject::_lookupTitle($a_set["context_obj_id"]) + ); + + $this->tpl->setVariable("VAL_ID", $a_set["id"]); + } } -?> diff --git a/Services/News/classes/class.ilNewsGlobalScreenProvider.php b/Services/News/classes/class.ilNewsGlobalScreenProvider.php index 7b5e74c6981bcd386927ff95affda433fc4f4b67..a535d5151e607e5338b6b26970a2559be5bef8b2 100644 --- a/Services/News/classes/class.ilNewsGlobalScreenProvider.php +++ b/Services/News/classes/class.ilNewsGlobalScreenProvider.php @@ -8,56 +8,61 @@ use ILIAS\GlobalScreen\Scope\MainMenu\Provider\AbstractStaticMainMenuProvider; * * @author Fabian Schmid */ -class ilNewsGlobalScreenProvider extends AbstractStaticMainMenuProvider { - - /** - * @var IdentificationInterface - */ - protected $top_item; - - - public function __construct(\ILIAS\DI\Container $dic) { - parent::__construct($dic); - $this->top_item = (new ilPDGlobalScreenProvider($dic))->getTopItem(); - } - - - /** - * Some other components want to provide Items for the main menu which are - * located at the PD TopTitem by default. Therefore we have to provide our - * TopTitem Identification for others - * - * @return IdentificationInterface - */ - public function getTopItem(): IdentificationInterface { - return $this->top_item; - } - - - /** - * @inheritDoc - */ - public function getStaticTopItems(): array { - return []; - } - - - /** - * @inheritDoc - */ - public function getStaticSubItems(): array { - $dic = $this->dic; - - return [$this->mainmenu->link($this->if->identifier('mm_pd_news')) - ->withTitle($this->dic->language()->txt("news")) - ->withAction("ilias.php?baseClass=ilPersonalDesktopGUI&cmd=jumpToNews") - ->withParent($this->getTopItem()) - ->withPosition(10) - ->withNonAvailableReason($this->dic->ui()->factory()->legacy("{$this->dic->language()->txt('component_not_active')}")) - ->withAvailableCallable( - function () use ($dic) { - return ($dic->settings()->get("block_activated_news")); - } - )]; - } +class ilNewsGlobalScreenProvider extends AbstractStaticMainMenuProvider +{ + + /** + * @var IdentificationInterface + */ + protected $top_item; + + + public function __construct(\ILIAS\DI\Container $dic) + { + parent::__construct($dic); + $this->top_item = (new ilPDGlobalScreenProvider($dic))->getTopItem(); + } + + + /** + * Some other components want to provide Items for the main menu which are + * located at the PD TopTitem by default. Therefore we have to provide our + * TopTitem Identification for others + * + * @return IdentificationInterface + */ + public function getTopItem() : IdentificationInterface + { + return $this->top_item; + } + + + /** + * @inheritDoc + */ + public function getStaticTopItems() : array + { + return []; + } + + + /** + * @inheritDoc + */ + public function getStaticSubItems() : array + { + $dic = $this->dic; + + return [$this->mainmenu->link($this->if->identifier('mm_pd_news')) + ->withTitle($this->dic->language()->txt("news")) + ->withAction("ilias.php?baseClass=ilPersonalDesktopGUI&cmd=jumpToNews") + ->withParent($this->getTopItem()) + ->withPosition(10) + ->withNonAvailableReason($this->dic->ui()->factory()->legacy("{$this->dic->language()->txt('component_not_active')}")) + ->withAvailableCallable( + function () use ($dic) { + return ($dic->settings()->get("block_activated_news")); + } + )]; + } } diff --git a/Services/News/classes/class.ilNewsImporter.php b/Services/News/classes/class.ilNewsImporter.php index 8d0642793a047e1ae3a65006a3e19ca0b3755dea..79c5c9ecb6ab0aff2e0bb6b4529a37c1775da7d5 100644 --- a/Services/News/classes/class.ilNewsImporter.php +++ b/Services/News/classes/class.ilNewsImporter.php @@ -13,29 +13,32 @@ include_once("./Services/Export/classes/class.ilXmlImporter.php"); class ilNewsImporter extends ilXmlImporter { - /** - * Initialisation - */ - function init() - { - include_once("./Services/News/classes/class.ilNewsDataSet.php"); - $this->ds = new ilNewsDataSet(); - $this->ds->setDSPrefix("ds"); - } + /** + * Initialisation + */ + public function init() + { + include_once("./Services/News/classes/class.ilNewsDataSet.php"); + $this->ds = new ilNewsDataSet(); + $this->ds->setDSPrefix("ds"); + } - /** - * Import XML - * - * @param - * @return - */ - function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) - { - include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); - $parser = new ilDataSetImportParser($a_entity, $this->getSchemaVersion(), - $a_xml, $this->ds, $a_mapping); - } + /** + * Import XML + * + * @param + * @return + */ + public function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) + { + include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); + $parser = new ilDataSetImportParser( + $a_entity, + $this->getSchemaVersion(), + $a_xml, + $this->ds, + $a_mapping + ); + } } - -?> \ No newline at end of file diff --git a/Services/News/classes/class.ilNewsItem.php b/Services/News/classes/class.ilNewsItem.php index eb2389affefaed32f2bd5816ce638250ef421591..640de156615c2acd4528914866e3faf0d5b3bea4 100755 --- a/Services/News/classes/class.ilNewsItem.php +++ b/Services/News/classes/class.ilNewsItem.php @@ -31,2227 +31,2217 @@ define("NEWS_PUBLIC", "public"); */ class ilNewsItem { - /** - * @var ilDB - */ - protected $db; - - /** - * @var ilTree - */ - protected $tree; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilObjectDataCache - */ - protected $obj_data_cache; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilCtrl - */ - protected $ctrl; - - protected $id; - protected $title; - protected $content; - /** - * @var bool - */ - protected $content_html; - protected $context_obj_id; - protected $context_obj_type; - protected $context_sub_obj_id; - protected $context_sub_obj_type; - protected $content_type = "text"; - protected $creation_date; - protected $update_date; - protected $user_id; - /** - * @var int - */ - protected $update_user_id; - protected $visibility = "users"; - protected $content_long; - protected $priority = 1; - protected $content_is_lang_var = 0; - protected $mob_id; - protected $playtime; - - private static $privFeedId = false; - private $limitation; - - /** - * Constructor. - * - * @param int $a_id - */ - public function __construct($a_id = 0) - { - global $DIC; - - $this->db = $DIC->database(); - $this->tree = $DIC->repositoryTree(); - $this->access = $DIC->access(); - $this->obj_data_cache = $DIC["ilObjDataCache"]; - $this->user = $DIC->user(); - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - if ($a_id > 0) - { - $this->setId($a_id); - $this->read(); - } - $this->limitation = true; - } - - /** - * Set Id. - * - * @param int $a_id - */ - public function setId($a_id) - { - $this->id = $a_id; - } - - /** - * Get Id. - * - * @return int - */ - public function getId() - { - return $this->id; - } - - /** - * Set Title. - * - * @param string $a_title Title of news item. - */ - public function setTitle($a_title) - { - $this->title = $a_title; - } - - /** - * Get Title. - * - * @return string Title of news item. - */ - public function getTitle() - { - return $this->title; - } - - /** - * Set Content. - * - * @param string $a_content Content of news. - */ - public function setContent($a_content) - { - $this->content = $a_content; - } - - /** - * Get Content. - * - * @return string Content of news. - */ - public function getContent() - { - return $this->content; - } - - /** - * Set ContextObjId. - * - * @param int $a_context_obj_id - */ - public function setContextObjId($a_context_obj_id) - { - $this->context_obj_id = $a_context_obj_id; - } - - /** - * Get ContextObjId. - * - * @return int - */ - public function getContextObjId() - { - return $this->context_obj_id; - } - - /** - * Set ContextObjType. - * - * @param int $a_context_obj_type - */ - public function setContextObjType($a_context_obj_type) - { - $this->context_obj_type = $a_context_obj_type; - } - - /** - * Get ContextObjType. - * - * @return int - */ - public function getContextObjType() - { - return $this->context_obj_type; - } - - /** - * Set ContextSubObjId. - * - * @param int $a_context_sub_obj_id - */ - public function setContextSubObjId($a_context_sub_obj_id) - { - $this->context_sub_obj_id = $a_context_sub_obj_id; - } - - /** - * Get ContextSubObjId. - * - * @return int - */ - public function getContextSubObjId() - { - return $this->context_sub_obj_id; - } - - /** - * Set ContextSubObjType. - * - * @param int $a_context_sub_obj_type - */ - public function setContextSubObjType($a_context_sub_obj_type) - { - $this->context_sub_obj_type = $a_context_sub_obj_type; - } - - /** - * Get ContextSubObjType. - * - * @return int - */ - public function getContextSubObjType() - { - return $this->context_sub_obj_type; - } - - /** - * Set ContentType. - * - * @param string $a_content_type Content type. - */ - public function setContentType($a_content_type = "text") - { - $this->content_type = $a_content_type; - } - - /** - * Get ContentType. - * - * @return string Content type. - */ - public function getContentType() - { - return $this->content_type; - } - - /** - * Set CreationDate. - * - * @param string $a_creation_date Date of creation. - */ - public function setCreationDate($a_creation_date) - { - $this->creation_date = $a_creation_date; - } - - /** - * Get CreationDate. - * - * @return string Date of creation. - */ - public function getCreationDate() - { - return $this->creation_date; - } - - /** - * Set UpdateDate. - * - * @param string $a_update_date Date of last update. - */ - public function setUpdateDate($a_update_date) - { - $this->update_date = $a_update_date; - } - - /** - * Get UpdateDate. - * - * @return string Date of last update. - */ - public function getUpdateDate() - { - return $this->update_date; - } - - /** - * Set UserId. - * - * @param int $a_user_id User Id of last update. - */ - public function setUserId($a_user_id) - { - $this->user_id = $a_user_id; - } - - /** - * Get UserId. - * - * @return int User Id of last update. - */ - public function getUserId() - { - return $this->user_id; - } - - /** - * Set update user id - * - * @param int $a_val update user id - */ - function setUpdateUserId($a_val) - { - $this->update_user_id = $a_val; - } - - /** - * Get update user id - * - * @return int update user id - */ - function getUpdateUserId() - { - return $this->update_user_id; - } - - /** - * Set Visibility. - * - * @param string $a_visibility Access level of news. - */ - public function setVisibility($a_visibility = "users") - { - $this->visibility = $a_visibility; - } - - /** - * Get Visibility. - * - * @return string Access level of news. - */ - public function getVisibility() - { - return $this->visibility; - } - - /** - * Set ContentLong. - * - * @param string $a_content_long Long content of news - */ - public function setContentLong($a_content_long) - { - $this->content_long = $a_content_long; - } - - /** - * Get ContentLong. - * - * @return string Long content of news - */ - public function getContentLong() - { - return $this->content_long; - } - - /** - * Set Priority. - * - * @param int $a_priority News Priority - */ - public function setPriority($a_priority = 1) - { - $this->priority = $a_priority; - } - - /** - * Get Priority. - * - * @return int News Priority - */ - public function getPriority() - { - return $this->priority; - } - - /** - * Set ContentIsLangVar. - * - * @param boolean $a_content_is_lang_var - */ - public function setContentIsLangVar($a_content_is_lang_var = 0) - { - $this->content_is_lang_var = $a_content_is_lang_var; - } - - /** - * Get ContentIsLangVar. - * - * @return boolean - */ - public function getContentIsLangVar() - { - return $this->content_is_lang_var; - } - - /** - * Set MobId. - * - * @param int $a_mob_id Media Object ID (if news includes attachement) - */ - public function setMobId($a_mob_id) - { - $this->mob_id = $a_mob_id; - } - - /** - * Get MobId. - * - * @return int Media Object ID (if news includes attachement) - */ - public function getMobId() - { - return $this->mob_id; - } - - /** - * Set Playtime. - * - * @param string $a_playtime Play Time, hh:mm:ss (of attached media file) - */ - public function setPlaytime($a_playtime) - { - $this->playtime = $a_playtime; - } - - /** - * Get Playtime. - * - * @return string Play Time, hh:mm:ss (of attached media file) - */ - public function getPlaytime() - { - return $this->playtime; - } - - - /** - * Set Limitation for number of items. - * - * @param boolean $a_limitation Limitation for number of items - */ - function setLimitation($a_limitation) - { - $this->limitation = $a_limitation; - } - - /** - * Get Limitation for number of items. - * - * @return boolean Limitation for number of items - */ - function getLimitation() - { - return $this->limitation; - } - - /** - * Set content text ist lang var - * - * @param boolean $a_content_is_lang_var - */ - public function setContentTextIsLangVar($a_val = 0) - { - $this->content_text_is_lang_var = $a_val; - } - - /** - * Get content text ist lang var - * - * @return boolean - */ - public function getContentTextIsLangVar() - { - return $this->content_text_is_lang_var; - } - - /** - * Set mob play counter - * - * @param int $a_val counter - */ - function setMobPlayCounter($a_val) - { - $this->mob_cnt_play = $a_val; - } - - /** - * Get mob play counter - * - * @return int counter - */ - function getMobPlayCounter() - { - return $this->mob_cnt_play; - } - - /** - * Set mob download counter - * - * @param int $a_val counter - */ - function setMobDownloadCounter($a_val) - { - $this->mob_cnt_download = $a_val; - } - - /** - * Get mob download counter - * - * @return int counter - */ - function getMobDownloadCounter() - { - return $this->mob_cnt_download; - } - - /** - * Is content HTML (tiny used?) - * - * @param bool $a_val - */ - function setContentHtml($a_val) - { - $this->content_html = $a_val; - } - - /** - * Get content as html - * - * @return bool - */ - function getContentHtml() - { - return $this->content_html; - } - - /** - * Read item from database. - * @deprecated (will migrate to ilNewsData or other class taking care of persistence) - */ - public function read() - { - $ilDB = $this->db; - - $query = "SELECT * FROM il_news_item WHERE id = ". - $ilDB->quote($this->getId(), "integer"); - $set = $ilDB->query($query); - $rec = $ilDB->fetchAssoc($set); - - $this->setTitle($rec["title"]); - $this->setContent($rec["content"]); - $this->setContextObjId((int) $rec["context_obj_id"]); - $this->setContextObjType($rec["context_obj_type"]); - $this->setContextSubObjId((int) $rec["context_sub_obj_id"]); - $this->setContextSubObjType($rec["context_sub_obj_type"]); - $this->setContentType($rec["content_type"]); - $this->setCreationDate($rec["creation_date"]); - $this->setUpdateDate($rec["update_date"]); - $this->setUserId($rec["user_id"]); - $this->setUpdateUserId($rec["update_user_id"]); - $this->setVisibility($rec["visibility"]); - $this->setContentLong($rec["content_long"]); - $this->setPriority($rec["priority"]); - $this->setContentIsLangVar($rec["content_is_lang_var"]); - $this->setContentTextIsLangVar((int) $rec["content_text_is_lang_var"]); - $this->setMobId($rec["mob_id"]); - $this->setPlaytime($rec["playtime"]); - $this->setMobPlayCounter($rec["mob_cnt_play"]); - $this->setMobDownloadCounter($rec["mob_cnt_download"]); - $this->setContentHtml($rec["content_html"]); - - } - - /** - * Create - * @deprecated (will migrate to ilNewsData or other class taking care of persistence) - */ - function create() - { - $ilDB = $this->db; - - // insert new record into db - $this->setId($ilDB->nextId("il_news_item")); - $ilDB->insert("il_news_item", array( - "id" => array("integer", $this->getId()), - "title" => array("text", $this->getTitle()), - "content" => array("clob", $this->getContent()), - "content_html" => array("integer", (int) $this->getContentHtml()), - "context_obj_id" => array("integer", (int) $this->getContextObjId()), - "context_obj_type" => array("text", $this->getContextObjType()), - "context_sub_obj_id" => array("integer", (int) $this->getContextSubObjId()), - "context_sub_obj_type" => array("text", $this->getContextSubObjType()), - "content_type" => array("text", $this->getContentType()), - "creation_date" => array("timestamp", ilUtil::now()), - "update_date" => array("timestamp", ilUtil::now()), - "user_id" => array("integer", $this->getUserId()), - "update_user_id" => array("integer", (int) $this->getUpdateUserId()), - "visibility" => array("text", $this->getVisibility()), - "content_long" => array("clob", $this->getContentLong()), - "priority" => array("integer", $this->getPriority()), - "content_is_lang_var" => array("integer", $this->getContentIsLangVar()), - "content_text_is_lang_var" => array("integer", (int) $this->getContentTextIsLangVar()), - "mob_id" => array("integer", $this->getMobId()), + /** + * @var ilDB + */ + protected $db; + + /** + * @var ilTree + */ + protected $tree; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilObjectDataCache + */ + protected $obj_data_cache; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilCtrl + */ + protected $ctrl; + + protected $id; + protected $title; + protected $content; + /** + * @var bool + */ + protected $content_html; + protected $context_obj_id; + protected $context_obj_type; + protected $context_sub_obj_id; + protected $context_sub_obj_type; + protected $content_type = "text"; + protected $creation_date; + protected $update_date; + protected $user_id; + /** + * @var int + */ + protected $update_user_id; + protected $visibility = "users"; + protected $content_long; + protected $priority = 1; + protected $content_is_lang_var = 0; + protected $mob_id; + protected $playtime; + + private static $privFeedId = false; + private $limitation; + + /** + * Constructor. + * + * @param int $a_id + */ + public function __construct($a_id = 0) + { + global $DIC; + + $this->db = $DIC->database(); + $this->tree = $DIC->repositoryTree(); + $this->access = $DIC->access(); + $this->obj_data_cache = $DIC["ilObjDataCache"]; + $this->user = $DIC->user(); + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + if ($a_id > 0) { + $this->setId($a_id); + $this->read(); + } + $this->limitation = true; + } + + /** + * Set Id. + * + * @param int $a_id + */ + public function setId($a_id) + { + $this->id = $a_id; + } + + /** + * Get Id. + * + * @return int + */ + public function getId() + { + return $this->id; + } + + /** + * Set Title. + * + * @param string $a_title Title of news item. + */ + public function setTitle($a_title) + { + $this->title = $a_title; + } + + /** + * Get Title. + * + * @return string Title of news item. + */ + public function getTitle() + { + return $this->title; + } + + /** + * Set Content. + * + * @param string $a_content Content of news. + */ + public function setContent($a_content) + { + $this->content = $a_content; + } + + /** + * Get Content. + * + * @return string Content of news. + */ + public function getContent() + { + return $this->content; + } + + /** + * Set ContextObjId. + * + * @param int $a_context_obj_id + */ + public function setContextObjId($a_context_obj_id) + { + $this->context_obj_id = $a_context_obj_id; + } + + /** + * Get ContextObjId. + * + * @return int + */ + public function getContextObjId() + { + return $this->context_obj_id; + } + + /** + * Set ContextObjType. + * + * @param int $a_context_obj_type + */ + public function setContextObjType($a_context_obj_type) + { + $this->context_obj_type = $a_context_obj_type; + } + + /** + * Get ContextObjType. + * + * @return int + */ + public function getContextObjType() + { + return $this->context_obj_type; + } + + /** + * Set ContextSubObjId. + * + * @param int $a_context_sub_obj_id + */ + public function setContextSubObjId($a_context_sub_obj_id) + { + $this->context_sub_obj_id = $a_context_sub_obj_id; + } + + /** + * Get ContextSubObjId. + * + * @return int + */ + public function getContextSubObjId() + { + return $this->context_sub_obj_id; + } + + /** + * Set ContextSubObjType. + * + * @param int $a_context_sub_obj_type + */ + public function setContextSubObjType($a_context_sub_obj_type) + { + $this->context_sub_obj_type = $a_context_sub_obj_type; + } + + /** + * Get ContextSubObjType. + * + * @return int + */ + public function getContextSubObjType() + { + return $this->context_sub_obj_type; + } + + /** + * Set ContentType. + * + * @param string $a_content_type Content type. + */ + public function setContentType($a_content_type = "text") + { + $this->content_type = $a_content_type; + } + + /** + * Get ContentType. + * + * @return string Content type. + */ + public function getContentType() + { + return $this->content_type; + } + + /** + * Set CreationDate. + * + * @param string $a_creation_date Date of creation. + */ + public function setCreationDate($a_creation_date) + { + $this->creation_date = $a_creation_date; + } + + /** + * Get CreationDate. + * + * @return string Date of creation. + */ + public function getCreationDate() + { + return $this->creation_date; + } + + /** + * Set UpdateDate. + * + * @param string $a_update_date Date of last update. + */ + public function setUpdateDate($a_update_date) + { + $this->update_date = $a_update_date; + } + + /** + * Get UpdateDate. + * + * @return string Date of last update. + */ + public function getUpdateDate() + { + return $this->update_date; + } + + /** + * Set UserId. + * + * @param int $a_user_id User Id of last update. + */ + public function setUserId($a_user_id) + { + $this->user_id = $a_user_id; + } + + /** + * Get UserId. + * + * @return int User Id of last update. + */ + public function getUserId() + { + return $this->user_id; + } + + /** + * Set update user id + * + * @param int $a_val update user id + */ + public function setUpdateUserId($a_val) + { + $this->update_user_id = $a_val; + } + + /** + * Get update user id + * + * @return int update user id + */ + public function getUpdateUserId() + { + return $this->update_user_id; + } + + /** + * Set Visibility. + * + * @param string $a_visibility Access level of news. + */ + public function setVisibility($a_visibility = "users") + { + $this->visibility = $a_visibility; + } + + /** + * Get Visibility. + * + * @return string Access level of news. + */ + public function getVisibility() + { + return $this->visibility; + } + + /** + * Set ContentLong. + * + * @param string $a_content_long Long content of news + */ + public function setContentLong($a_content_long) + { + $this->content_long = $a_content_long; + } + + /** + * Get ContentLong. + * + * @return string Long content of news + */ + public function getContentLong() + { + return $this->content_long; + } + + /** + * Set Priority. + * + * @param int $a_priority News Priority + */ + public function setPriority($a_priority = 1) + { + $this->priority = $a_priority; + } + + /** + * Get Priority. + * + * @return int News Priority + */ + public function getPriority() + { + return $this->priority; + } + + /** + * Set ContentIsLangVar. + * + * @param boolean $a_content_is_lang_var + */ + public function setContentIsLangVar($a_content_is_lang_var = 0) + { + $this->content_is_lang_var = $a_content_is_lang_var; + } + + /** + * Get ContentIsLangVar. + * + * @return boolean + */ + public function getContentIsLangVar() + { + return $this->content_is_lang_var; + } + + /** + * Set MobId. + * + * @param int $a_mob_id Media Object ID (if news includes attachement) + */ + public function setMobId($a_mob_id) + { + $this->mob_id = $a_mob_id; + } + + /** + * Get MobId. + * + * @return int Media Object ID (if news includes attachement) + */ + public function getMobId() + { + return $this->mob_id; + } + + /** + * Set Playtime. + * + * @param string $a_playtime Play Time, hh:mm:ss (of attached media file) + */ + public function setPlaytime($a_playtime) + { + $this->playtime = $a_playtime; + } + + /** + * Get Playtime. + * + * @return string Play Time, hh:mm:ss (of attached media file) + */ + public function getPlaytime() + { + return $this->playtime; + } + + + /** + * Set Limitation for number of items. + * + * @param boolean $a_limitation Limitation for number of items + */ + public function setLimitation($a_limitation) + { + $this->limitation = $a_limitation; + } + + /** + * Get Limitation for number of items. + * + * @return boolean Limitation for number of items + */ + public function getLimitation() + { + return $this->limitation; + } + + /** + * Set content text ist lang var + * + * @param boolean $a_content_is_lang_var + */ + public function setContentTextIsLangVar($a_val = 0) + { + $this->content_text_is_lang_var = $a_val; + } + + /** + * Get content text ist lang var + * + * @return boolean + */ + public function getContentTextIsLangVar() + { + return $this->content_text_is_lang_var; + } + + /** + * Set mob play counter + * + * @param int $a_val counter + */ + public function setMobPlayCounter($a_val) + { + $this->mob_cnt_play = $a_val; + } + + /** + * Get mob play counter + * + * @return int counter + */ + public function getMobPlayCounter() + { + return $this->mob_cnt_play; + } + + /** + * Set mob download counter + * + * @param int $a_val counter + */ + public function setMobDownloadCounter($a_val) + { + $this->mob_cnt_download = $a_val; + } + + /** + * Get mob download counter + * + * @return int counter + */ + public function getMobDownloadCounter() + { + return $this->mob_cnt_download; + } + + /** + * Is content HTML (tiny used?) + * + * @param bool $a_val + */ + public function setContentHtml($a_val) + { + $this->content_html = $a_val; + } + + /** + * Get content as html + * + * @return bool + */ + public function getContentHtml() + { + return $this->content_html; + } + + /** + * Read item from database. + * @deprecated (will migrate to ilNewsData or other class taking care of persistence) + */ + public function read() + { + $ilDB = $this->db; + + $query = "SELECT * FROM il_news_item WHERE id = " . + $ilDB->quote($this->getId(), "integer"); + $set = $ilDB->query($query); + $rec = $ilDB->fetchAssoc($set); + + $this->setTitle($rec["title"]); + $this->setContent($rec["content"]); + $this->setContextObjId((int) $rec["context_obj_id"]); + $this->setContextObjType($rec["context_obj_type"]); + $this->setContextSubObjId((int) $rec["context_sub_obj_id"]); + $this->setContextSubObjType($rec["context_sub_obj_type"]); + $this->setContentType($rec["content_type"]); + $this->setCreationDate($rec["creation_date"]); + $this->setUpdateDate($rec["update_date"]); + $this->setUserId($rec["user_id"]); + $this->setUpdateUserId($rec["update_user_id"]); + $this->setVisibility($rec["visibility"]); + $this->setContentLong($rec["content_long"]); + $this->setPriority($rec["priority"]); + $this->setContentIsLangVar($rec["content_is_lang_var"]); + $this->setContentTextIsLangVar((int) $rec["content_text_is_lang_var"]); + $this->setMobId($rec["mob_id"]); + $this->setPlaytime($rec["playtime"]); + $this->setMobPlayCounter($rec["mob_cnt_play"]); + $this->setMobDownloadCounter($rec["mob_cnt_download"]); + $this->setContentHtml($rec["content_html"]); + } + + /** + * Create + * @deprecated (will migrate to ilNewsData or other class taking care of persistence) + */ + public function create() + { + $ilDB = $this->db; + + // insert new record into db + $this->setId($ilDB->nextId("il_news_item")); + $ilDB->insert("il_news_item", array( + "id" => array("integer", $this->getId()), + "title" => array("text", $this->getTitle()), + "content" => array("clob", $this->getContent()), + "content_html" => array("integer", (int) $this->getContentHtml()), + "context_obj_id" => array("integer", (int) $this->getContextObjId()), + "context_obj_type" => array("text", $this->getContextObjType()), + "context_sub_obj_id" => array("integer", (int) $this->getContextSubObjId()), + "context_sub_obj_type" => array("text", $this->getContextSubObjType()), + "content_type" => array("text", $this->getContentType()), + "creation_date" => array("timestamp", ilUtil::now()), + "update_date" => array("timestamp", ilUtil::now()), + "user_id" => array("integer", $this->getUserId()), + "update_user_id" => array("integer", (int) $this->getUpdateUserId()), + "visibility" => array("text", $this->getVisibility()), + "content_long" => array("clob", $this->getContentLong()), + "priority" => array("integer", $this->getPriority()), + "content_is_lang_var" => array("integer", $this->getContentIsLangVar()), + "content_text_is_lang_var" => array("integer", (int) $this->getContentTextIsLangVar()), + "mob_id" => array("integer", $this->getMobId()), "playtime" => array("text", $this->getPlaytime()) - )); - - - $news_set = new ilSetting("news"); - $max_items = $news_set->get("max_items"); - if ($max_items <= 0) - { - $max_items = 50; - } - - // limit number of news - if ($this->getLimitation()) - { - // Determine how many rows should be deleted - $query = "SELECT count(*) cnt ". - "FROM il_news_item ". - "WHERE ". - "context_obj_id = ".$ilDB->quote($this->getContextObjId(), "integer"). - " AND context_obj_type = ".$ilDB->quote($this->getContextObjType(), "text"). - " AND context_sub_obj_id = ".$ilDB->quote($this->getContextSubObjId(), "integer"). - " AND ".$ilDB->equals("context_sub_obj_type", $this->getContextSubObjType(), "text", true)." "; - - $set = $ilDB->query($query); - $rec = $ilDB->fetchAssoc($set); - - // if we have more records than allowed, delete them - if (($rec["cnt"] > $max_items) && $this->getContextObjId() > 0) - { - $query = "SELECT * ". - "FROM il_news_item ". - "WHERE ". - "context_obj_id = ".$ilDB->quote($this->getContextObjId(), "integer"). - " AND context_obj_type = ".$ilDB->quote($this->getContextObjType(), "text"). - " AND context_sub_obj_id = ".$ilDB->quote($this->getContextSubObjId(), "integer"). - " AND ".$ilDB->equals("context_sub_obj_type", $this->getContextSubObjType(), "text", true). + )); + + + $news_set = new ilSetting("news"); + $max_items = $news_set->get("max_items"); + if ($max_items <= 0) { + $max_items = 50; + } + + // limit number of news + if ($this->getLimitation()) { + // Determine how many rows should be deleted + $query = "SELECT count(*) cnt " . + "FROM il_news_item " . + "WHERE " . + "context_obj_id = " . $ilDB->quote($this->getContextObjId(), "integer") . + " AND context_obj_type = " . $ilDB->quote($this->getContextObjType(), "text") . + " AND context_sub_obj_id = " . $ilDB->quote($this->getContextSubObjId(), "integer") . + " AND " . $ilDB->equals("context_sub_obj_type", $this->getContextSubObjType(), "text", true) . " "; + + $set = $ilDB->query($query); + $rec = $ilDB->fetchAssoc($set); + + // if we have more records than allowed, delete them + if (($rec["cnt"] > $max_items) && $this->getContextObjId() > 0) { + $query = "SELECT * " . + "FROM il_news_item " . + "WHERE " . + "context_obj_id = " . $ilDB->quote($this->getContextObjId(), "integer") . + " AND context_obj_type = " . $ilDB->quote($this->getContextObjType(), "text") . + " AND context_sub_obj_id = " . $ilDB->quote($this->getContextSubObjId(), "integer") . + " AND " . $ilDB->equals("context_sub_obj_type", $this->getContextSubObjType(), "text", true) . " ORDER BY creation_date ASC"; - - $ilDB->setLimit($rec["cnt"] - $max_items); - $del_set = $ilDB->query($query); - while ($del_item = $ilDB->fetchAssoc($del_set)) - { - $del_news = new ilNewsItem($del_item["id"]); - $del_news->delete(); - } - } - } - } - - /** - * Update item in database - * - * @deprecated (will migrate to ilNewsData or other class taking care of persistence) - * @param boolean $a_as_new If true, creation date is set "now" - */ - public function update($a_as_new = false) - { - $ilDB = $this->db; - - $fields = array( - "title" => array("text", $this->getTitle()), - "content" => array("clob", $this->getContent()), - "content_html" => array("integer", (int) $this->getContentHtml()), - "context_obj_id" => array("integer", $this->getContextObjId()), - "context_obj_type" => array("text", $this->getContextObjType()), - "context_sub_obj_id" => array("integer", $this->getContextSubObjId()), - "context_sub_obj_type" => array("text", $this->getContextSubObjType()), - "content_type" => array("text", $this->getContentType()), - "user_id" => array("integer", $this->getUserId()), - "update_user_id" => array("integer", (int) $this->getUpdateUserId()), - "visibility" => array("text", $this->getVisibility()), - "content_long" => array("clob", $this->getContentLong()), - "priority" => array("integer", $this->getPriority()), - "content_is_lang_var" => array("integer", $this->getContentIsLangVar()), - "content_text_is_lang_var" => array("integer", (int) $this->getContentTextIsLangVar()), - "mob_id" => array("integer", $this->getMobId()), - "mob_cnt_play" => array("integer", $this->getMobPlayCounter()), - "mob_cnt_download" => array("integer", $this->getMobDownloadCounter()), + + $ilDB->setLimit($rec["cnt"] - $max_items); + $del_set = $ilDB->query($query); + while ($del_item = $ilDB->fetchAssoc($del_set)) { + $del_news = new ilNewsItem($del_item["id"]); + $del_news->delete(); + } + } + } + } + + /** + * Update item in database + * + * @deprecated (will migrate to ilNewsData or other class taking care of persistence) + * @param boolean $a_as_new If true, creation date is set "now" + */ + public function update($a_as_new = false) + { + $ilDB = $this->db; + + $fields = array( + "title" => array("text", $this->getTitle()), + "content" => array("clob", $this->getContent()), + "content_html" => array("integer", (int) $this->getContentHtml()), + "context_obj_id" => array("integer", $this->getContextObjId()), + "context_obj_type" => array("text", $this->getContextObjType()), + "context_sub_obj_id" => array("integer", $this->getContextSubObjId()), + "context_sub_obj_type" => array("text", $this->getContextSubObjType()), + "content_type" => array("text", $this->getContentType()), + "user_id" => array("integer", $this->getUserId()), + "update_user_id" => array("integer", (int) $this->getUpdateUserId()), + "visibility" => array("text", $this->getVisibility()), + "content_long" => array("clob", $this->getContentLong()), + "priority" => array("integer", $this->getPriority()), + "content_is_lang_var" => array("integer", $this->getContentIsLangVar()), + "content_text_is_lang_var" => array("integer", (int) $this->getContentTextIsLangVar()), + "mob_id" => array("integer", $this->getMobId()), + "mob_cnt_play" => array("integer", $this->getMobPlayCounter()), + "mob_cnt_download" => array("integer", $this->getMobDownloadCounter()), "playtime" => array("text", $this->getPlaytime()) - ); - - $now = ilUtil::now(); - if ($a_as_new) - { - $fields["creation_date"] = array("timestamp", $now); - $fields["update_date"] = array("timestamp", $now); - } - else - { - $fields["update_date"] = array("timestamp", $now); - } - - $ilDB->update("il_news_item", $fields, array( - "id" => array("integer", $this->getId()) - )); - - } - - - /** - * Get all news items for a user. - * @deprecated (will migrate to ilNewsData) - */ - static function _getNewsItemsOfUser($a_user_id, $a_only_public = false, - $a_prevent_aggregation = false, $a_per = 0, &$a_cnt = NULL) - { - global $DIC; - - $ilAccess = $DIC->access(); - - $news_item = new ilNewsItem(); - $news_set = new ilSetting("news"); - - $per = $a_per; - - include_once("./Services/News/classes/class.ilNewsSubscription.php"); - include_once("./Services/Block/classes/class.ilBlockSetting.php"); - - // this is currently not used - $ref_ids = ilNewsSubscription::_getSubscriptionsOfUser($a_user_id); - - if (ilObjUser::_lookupPref($a_user_id, "pd_items_news") != "n") - { - // get all items of the personal desktop - $pd_items = ilObjUser::_lookupDesktopItems($a_user_id); - foreach($pd_items as $item) - { - if (!in_array($item["ref_id"], $ref_ids)) - { - $ref_ids[] = $item["ref_id"]; - } - } - - // get all memberships - include_once 'Services/Membership/classes/class.ilParticipants.php'; - $crs_mbs = ilParticipants::_getMembershipByType($a_user_id, 'crs'); - $grp_mbs = ilParticipants::_getMembershipByType($a_user_id, 'grp'); - $items = array_merge($crs_mbs, $grp_mbs); - foreach($items as $i) - { - $item_references = ilObject::_getAllReferences($i); - if(is_array($item_references) && count($item_references)) - { - foreach($item_references as $ref_id) - { - if (!in_array($ref_id, $ref_ids)) - { - $ref_ids[] = $ref_id; - } - } - } - } - } - - $data = array(); - - foreach($ref_ids as $ref_id) - { - if (!$a_only_public) - { - // this loop should not cost too much performance - $acc = $ilAccess->checkAccessOfUser($a_user_id, "read", "", $ref_id); - - if (!$acc) - { - continue; - } - } - if (ilNewsItem::getPrivateFeedId() != false) { - global $DIC; - - $rbacsystem = $DIC->rbac()->system(); - $acc = $rbacsystem->checkAccessOfUser(ilNewsItem::getPrivateFeedId(),"read", $ref_id); - - if (!$acc) - { - continue; - } - } - - $obj_id = ilObject::_lookupObjId($ref_id); - $obj_type = ilObject::_lookupType($obj_id); - $news = $news_item->getNewsForRefId($ref_id, $a_only_public, false, - $per, $a_prevent_aggregation, false, false, false, $a_user_id); - - // counter - if (!is_null($a_cnt)) - { - $a_cnt[$ref_id] = count($news); - } - - $data = ilNewsItem::mergeNews($data, $news); - } + ); + + $now = ilUtil::now(); + if ($a_as_new) { + $fields["creation_date"] = array("timestamp", $now); + $fields["update_date"] = array("timestamp", $now); + } else { + $fields["update_date"] = array("timestamp", $now); + } + + $ilDB->update("il_news_item", $fields, array( + "id" => array("integer", $this->getId()) + )); + } + + + /** + * Get all news items for a user. + * @deprecated (will migrate to ilNewsData) + */ + public static function _getNewsItemsOfUser( + $a_user_id, + $a_only_public = false, + $a_prevent_aggregation = false, + $a_per = 0, + &$a_cnt = null + ) { + global $DIC; + + $ilAccess = $DIC->access(); + + $news_item = new ilNewsItem(); + $news_set = new ilSetting("news"); + + $per = $a_per; + + include_once("./Services/News/classes/class.ilNewsSubscription.php"); + include_once("./Services/Block/classes/class.ilBlockSetting.php"); + + // this is currently not used + $ref_ids = ilNewsSubscription::_getSubscriptionsOfUser($a_user_id); + + if (ilObjUser::_lookupPref($a_user_id, "pd_items_news") != "n") { + // get all items of the personal desktop + $pd_items = ilObjUser::_lookupDesktopItems($a_user_id); + foreach ($pd_items as $item) { + if (!in_array($item["ref_id"], $ref_ids)) { + $ref_ids[] = $item["ref_id"]; + } + } + + // get all memberships + include_once 'Services/Membership/classes/class.ilParticipants.php'; + $crs_mbs = ilParticipants::_getMembershipByType($a_user_id, 'crs'); + $grp_mbs = ilParticipants::_getMembershipByType($a_user_id, 'grp'); + $items = array_merge($crs_mbs, $grp_mbs); + foreach ($items as $i) { + $item_references = ilObject::_getAllReferences($i); + if (is_array($item_references) && count($item_references)) { + foreach ($item_references as $ref_id) { + if (!in_array($ref_id, $ref_ids)) { + $ref_ids[] = $ref_id; + } + } + } + } + } + + $data = array(); + + foreach ($ref_ids as $ref_id) { + if (!$a_only_public) { + // this loop should not cost too much performance + $acc = $ilAccess->checkAccessOfUser($a_user_id, "read", "", $ref_id); + + if (!$acc) { + continue; + } + } + if (ilNewsItem::getPrivateFeedId() != false) { + global $DIC; + + $rbacsystem = $DIC->rbac()->system(); + $acc = $rbacsystem->checkAccessOfUser(ilNewsItem::getPrivateFeedId(), "read", $ref_id); + + if (!$acc) { + continue; + } + } + + $obj_id = ilObject::_lookupObjId($ref_id); + $obj_type = ilObject::_lookupType($obj_id); + $news = $news_item->getNewsForRefId( + $ref_id, + $a_only_public, + false, + $per, + $a_prevent_aggregation, + false, + false, + false, + $a_user_id + ); + + // counter + if (!is_null($a_cnt)) { + $a_cnt[$ref_id] = count($news); + } + + $data = ilNewsItem::mergeNews($data, $news); + } $data = ilUtil::sortArray($data, "creation_date", "desc", false, true); - return $data; - } - - /** - * Get News For Ref Id. - * - * @deprecated (will migrate to ilNewsData) - * - * @param int $a_ref_id - * @param bool $a_only_public - * @param bool $a_stopnesting - * @param int $a_time_period - * @param bool $a_prevent_aggregation - * @param bool $a_forum_group_sequences - * @param bool $a_no_auto_generated - * @param bool $a_ignore_date_filter - * @param null $a_user_id - * @param int $a_limit currently only supported for groups and courses - * @param int[] $a_excluded currently only supported for groups and courses (news ids) - * @return array|mixed - */ - function getNewsForRefId($a_ref_id, $a_only_public = false, $a_stopnesting = false, - $a_time_period = 0, $a_prevent_aggregation = true, $a_forum_group_sequences = false, - $a_no_auto_generated = false, $a_ignore_date_filter = false, $a_user_id = null, $a_limit = 0, $a_excluded = array()) - { - $obj_id = ilObject::_lookupObjId($a_ref_id); - $obj_type = ilObject::_lookupType($obj_id); - - // get starting date + return $data; + } + + /** + * Get News For Ref Id. + * + * @deprecated (will migrate to ilNewsData) + * + * @param int $a_ref_id + * @param bool $a_only_public + * @param bool $a_stopnesting + * @param int $a_time_period + * @param bool $a_prevent_aggregation + * @param bool $a_forum_group_sequences + * @param bool $a_no_auto_generated + * @param bool $a_ignore_date_filter + * @param null $a_user_id + * @param int $a_limit currently only supported for groups and courses + * @param int[] $a_excluded currently only supported for groups and courses (news ids) + * @return array|mixed + */ + public function getNewsForRefId( + $a_ref_id, + $a_only_public = false, + $a_stopnesting = false, + $a_time_period = 0, + $a_prevent_aggregation = true, + $a_forum_group_sequences = false, + $a_no_auto_generated = false, + $a_ignore_date_filter = false, + $a_user_id = null, + $a_limit = 0, + $a_excluded = array() + ) { + $obj_id = ilObject::_lookupObjId($a_ref_id); + $obj_type = ilObject::_lookupType($obj_id); + + // get starting date $starting_date = ""; - if ($obj_type == "grp" || $obj_type == "crs" || $obj_type == "cat") - { - include_once("./Services/Block/classes/class.ilBlockSetting.php"); - $hide_news_per_date = ilBlockSetting::_lookup("news", "hide_news_per_date", - 0, $obj_id); - if ($hide_news_per_date && !$a_ignore_date_filter) - { - $starting_date = ilBlockSetting::_lookup("news", "hide_news_date", - 0, $obj_id); - } - } - - if ($obj_type == "cat" && !$a_stopnesting) - { - $news = $this->getAggregatedChildNewsData($a_ref_id, $a_only_public, $a_time_period, - $a_prevent_aggregation, $starting_date, $a_no_auto_generated); - } - else if (($obj_type == "grp" || $obj_type == "crs") && - !$a_stopnesting) - { - $news = $this->getAggregatedNewsData($a_ref_id, $a_only_public, $a_time_period, - $a_prevent_aggregation, $starting_date, $a_no_auto_generated, $a_user_id, $a_limit, $a_excluded); - } - else - { - $news_item = new ilNewsItem(); - $news_item->setContextObjId($obj_id); - $news_item->setContextObjType($obj_type); - $news = $news_item->queryNewsForContext($a_only_public, $a_time_period, - $starting_date, $a_no_auto_generated); - $unset = array(); - foreach ($news as $k => $v) - { - if (!$a_only_public || $v["visibility"] == NEWS_PUBLIC || + if ($obj_type == "grp" || $obj_type == "crs" || $obj_type == "cat") { + include_once("./Services/Block/classes/class.ilBlockSetting.php"); + $hide_news_per_date = ilBlockSetting::_lookup( + "news", + "hide_news_per_date", + 0, + $obj_id + ); + if ($hide_news_per_date && !$a_ignore_date_filter) { + $starting_date = ilBlockSetting::_lookup( + "news", + "hide_news_date", + 0, + $obj_id + ); + } + } + + if ($obj_type == "cat" && !$a_stopnesting) { + $news = $this->getAggregatedChildNewsData( + $a_ref_id, + $a_only_public, + $a_time_period, + $a_prevent_aggregation, + $starting_date, + $a_no_auto_generated + ); + } elseif (($obj_type == "grp" || $obj_type == "crs") && + !$a_stopnesting) { + $news = $this->getAggregatedNewsData( + $a_ref_id, + $a_only_public, + $a_time_period, + $a_prevent_aggregation, + $starting_date, + $a_no_auto_generated, + $a_user_id, + $a_limit, + $a_excluded + ); + } else { + $news_item = new ilNewsItem(); + $news_item->setContextObjId($obj_id); + $news_item->setContextObjType($obj_type); + $news = $news_item->queryNewsForContext( + $a_only_public, + $a_time_period, + $starting_date, + $a_no_auto_generated + ); + $unset = array(); + foreach ($news as $k => $v) { + if (!$a_only_public || $v["visibility"] == NEWS_PUBLIC || ($v["priority"] == 0 && - ilBlockSetting::_lookup("news", "public_notifications", - 0, $obj_id))) - { - $news[$k]["ref_id"] = $a_ref_id; - } - else - { - $unset[] = $k; - } - } - foreach ($unset as $un) - { - unset($news[$un]); - } - } - - if (!$a_prevent_aggregation) - { - $news = $this->aggregateForums($news); - } - else if ($a_forum_group_sequences) - { - $news = $this->aggregateForums($news, true); - } - - return $news; - } - - /** - * Get news aggregation (e.g. for courses, groups) - * @deprecated (will migrate to ilNewsData) - */ - function getAggregatedNewsData($a_ref_id, $a_only_public = false, $a_time_period = 0, - $a_prevent_aggregation = false, $a_starting_date = "", $a_no_auto_generated = false, - $a_user_id = null, $a_limit = 0, $a_exclude = array()) - { - $tree = $this->tree; - $ilAccess = $this->access; - $ilObjDataCache = $this->obj_data_cache; - - // get news of parent object - - $data = array(); - - // get subtree - $cur_node = $tree->getNodeData($a_ref_id); - - // do not check for lft (materialized path) - if($cur_node) - { - $nodes = (array) $tree->getSubTree($cur_node,true); - } - else - { - $nodes = array(); - } - - // preload object data cache - $ref_ids = array(); - $obj_ids = array(); - foreach($nodes as $node) - { - $ref_ids[] = $node["child"]; - $obj_ids[] = $node["obj_id"]; - } - - $ilObjDataCache->preloadReferenceCache($ref_ids); - if (!$a_only_public) - { - include_once "Services/Object/classes/class.ilObjectActivation.php"; - ilObjectActivation::preloadData($ref_ids); - } - - // no check, for which of the objects any news are available + ilBlockSetting::_lookup( + "news", + "public_notifications", + 0, + $obj_id + ))) { + $news[$k]["ref_id"] = $a_ref_id; + } else { + $unset[] = $k; + } + } + foreach ($unset as $un) { + unset($news[$un]); + } + } + + if (!$a_prevent_aggregation) { + $news = $this->aggregateForums($news); + } elseif ($a_forum_group_sequences) { + $news = $this->aggregateForums($news, true); + } + + return $news; + } + + /** + * Get news aggregation (e.g. for courses, groups) + * @deprecated (will migrate to ilNewsData) + */ + public function getAggregatedNewsData( + $a_ref_id, + $a_only_public = false, + $a_time_period = 0, + $a_prevent_aggregation = false, + $a_starting_date = "", + $a_no_auto_generated = false, + $a_user_id = null, + $a_limit = 0, + $a_exclude = array() + ) { + $tree = $this->tree; + $ilAccess = $this->access; + $ilObjDataCache = $this->obj_data_cache; + + // get news of parent object + + $data = array(); + + // get subtree + $cur_node = $tree->getNodeData($a_ref_id); + + // do not check for lft (materialized path) + if ($cur_node) { + $nodes = (array) $tree->getSubTree($cur_node, true); + } else { + $nodes = array(); + } + + // preload object data cache + $ref_ids = array(); + $obj_ids = array(); + foreach ($nodes as $node) { + $ref_ids[] = $node["child"]; + $obj_ids[] = $node["obj_id"]; + } + + $ilObjDataCache->preloadReferenceCache($ref_ids); + if (!$a_only_public) { + include_once "Services/Object/classes/class.ilObjectActivation.php"; + ilObjectActivation::preloadData($ref_ids); + } + + // no check, for which of the objects any news are available $news_obj_ids = ilNewsItem::filterObjIdsPerNews($obj_ids, $a_time_period, $a_starting_date); - //$news_obj_ids = $obj_ids; - - // get news for all subtree nodes - $contexts = array(); - foreach($nodes as $node) - { - // only go on, if news are available - if (!in_array($node["obj_id"], $news_obj_ids)) - { - continue; - } - - if (!$a_only_public) - { - if(!$a_user_id) - { - $acc = $ilAccess->checkAccess("read", "", $node["child"]); - } - else - { - $acc = $ilAccess->checkAccessOfUser($a_user_id, "read", "", - $node["child"]); - } - if (!$acc) - { - continue; - } - } - - $ref_id[$node["obj_id"]] = $node["child"]; - $contexts[] = array("obj_id" => $node["obj_id"], - "obj_type" => $node["type"]); - } - - // sort and return - $news = $this->queryNewsForMultipleContexts($contexts, $a_only_public, $a_time_period, - $a_starting_date, $a_no_auto_generated, $a_user_id, $a_limit, $a_exclude); - - $to_del = array(); - foreach ($news as $k => $v) - { - $news[$k]["ref_id"] = $ref_id[$v["context_obj_id"]]; - } - - $data = ilNewsItem::mergeNews($data, $news); + //$news_obj_ids = $obj_ids; + + // get news for all subtree nodes + $contexts = array(); + foreach ($nodes as $node) { + // only go on, if news are available + if (!in_array($node["obj_id"], $news_obj_ids)) { + continue; + } + + if (!$a_only_public) { + if (!$a_user_id) { + $acc = $ilAccess->checkAccess("read", "", $node["child"]); + } else { + $acc = $ilAccess->checkAccessOfUser( + $a_user_id, + "read", + "", + $node["child"] + ); + } + if (!$acc) { + continue; + } + } + + $ref_id[$node["obj_id"]] = $node["child"]; + $contexts[] = array("obj_id" => $node["obj_id"], + "obj_type" => $node["type"]); + } + + // sort and return + $news = $this->queryNewsForMultipleContexts( + $contexts, + $a_only_public, + $a_time_period, + $a_starting_date, + $a_no_auto_generated, + $a_user_id, + $a_limit, + $a_exclude + ); + + $to_del = array(); + foreach ($news as $k => $v) { + $news[$k]["ref_id"] = $ref_id[$v["context_obj_id"]]; + } + + $data = ilNewsItem::mergeNews($data, $news); $data = ilUtil::sortArray($data, "creation_date", "desc", false, true); - - if (!$a_prevent_aggregation) - { - $data = $this->aggregateFiles($data, $a_ref_id); - } - - return $data; - } - - /** - * @deprecated will move to ilNewsData - * @param $news - * @param bool $a_group_posting_sequence - * @return mixed - */ - protected function aggregateForums($news, $a_group_posting_sequence = false) - { - $to_del = array(); - $forums = array(); - - // aggregate - foreach ($news as $k => $v) - { - if ($a_group_posting_sequence && $last_aggregation_forum > 0 && - $last_aggregation_forum != $news[$k]["context_obj_id"]) - { - $forums[$last_aggregation_forum] = ""; - } - - if ($news[$k]["context_obj_type"] == "frm") - { - if ($forums[$news[$k]["context_obj_id"]] == "") - { - // $forums[forum_id] = news_id; - $forums[$news[$k]["context_obj_id"]] = $k; - $last_aggregation_forum = $news[$k]["context_obj_id"]; - } - else - { - $to_del[] = $k; - } - - $news[$k]["no_context_title"] = true; - - // aggregate every forum into it's "k" news - $news[$forums[$news[$k]["context_obj_id"]]]["aggregation"][$k] - = $news[$k]; - $news[$k]["agg_ref_id"] - = $news[$k]["ref_id"]; - $news[$k]["content"] = ""; - $news[$k]["content_long"] = ""; - } - } - - // delete double entries - foreach($to_del as $k) - { - unset($news[$k]); - } -//var_dump($news[14]["aggregation"]); - - - return $news; - } - - /** - * @deprecated will move to ilNewsData - * @param $news - * @param $a_ref_id - * @return mixed - */ - protected function aggregateFiles($news, $a_ref_id) - { - $first_file = ""; - $to_del = array(); - foreach ($news as $k => $v) - { - // aggregate file related news - if ($news[$k]["context_obj_type"] == "file") - { - if ($first_file == "") - { - $first_file = $k; - } - else - { - $to_del[] = $k; - } - $news[$first_file]["aggregation"][$k] = $news[$k]; - $news[$first_file]["agg_ref_id"] = $a_ref_id; - $news[$first_file]["ref_id"] = $a_ref_id; - } - } - - foreach($to_del as $v) - { - unset($news[$v]); - } - - return $news; - } - - - /** - * Get news aggregation for child objects (e.g. for categories) - * @deprecated will move to ilNewsData - * @param $a_ref_id - * @param bool $a_only_public - * @param int $a_time_period - * @param bool $a_prevent_aggregation - * @param string $a_starting_date - * @param bool $a_no_auto_generated - * @return array|mixed - */ - protected function getAggregatedChildNewsData($a_ref_id, $a_only_public = false, - $a_time_period = 0, $a_prevent_aggregation = false, $a_starting_date = "", - $a_no_auto_generated = false) - { - $tree = $this->tree; - $ilAccess = $this->access; - - // get news of parent object - $data = $this->getNewsForRefId($a_ref_id, $a_only_public, true, $a_time_period, - true, false, false, $a_no_auto_generated); - foreach ($data as $k => $v) - { - $data[$k]["ref_id"] = $a_ref_id; - } - - // get childs - $nodes = $tree->getChilds($a_ref_id); - - // no check, for which of the objects any news are available - $obj_ids = array(); - foreach($nodes as $node) - { - $obj_ids[] = $node["obj_id"]; - } + + if (!$a_prevent_aggregation) { + $data = $this->aggregateFiles($data, $a_ref_id); + } + + return $data; + } + + /** + * @deprecated will move to ilNewsData + * @param $news + * @param bool $a_group_posting_sequence + * @return mixed + */ + protected function aggregateForums($news, $a_group_posting_sequence = false) + { + $to_del = array(); + $forums = array(); + + // aggregate + foreach ($news as $k => $v) { + if ($a_group_posting_sequence && $last_aggregation_forum > 0 && + $last_aggregation_forum != $news[$k]["context_obj_id"]) { + $forums[$last_aggregation_forum] = ""; + } + + if ($news[$k]["context_obj_type"] == "frm") { + if ($forums[$news[$k]["context_obj_id"]] == "") { + // $forums[forum_id] = news_id; + $forums[$news[$k]["context_obj_id"]] = $k; + $last_aggregation_forum = $news[$k]["context_obj_id"]; + } else { + $to_del[] = $k; + } + + $news[$k]["no_context_title"] = true; + + // aggregate every forum into it's "k" news + $news[$forums[$news[$k]["context_obj_id"]]]["aggregation"][$k] + = $news[$k]; + $news[$k]["agg_ref_id"] + = $news[$k]["ref_id"]; + $news[$k]["content"] = ""; + $news[$k]["content_long"] = ""; + } + } + + // delete double entries + foreach ($to_del as $k) { + unset($news[$k]); + } + //var_dump($news[14]["aggregation"]); + + + return $news; + } + + /** + * @deprecated will move to ilNewsData + * @param $news + * @param $a_ref_id + * @return mixed + */ + protected function aggregateFiles($news, $a_ref_id) + { + $first_file = ""; + $to_del = array(); + foreach ($news as $k => $v) { + // aggregate file related news + if ($news[$k]["context_obj_type"] == "file") { + if ($first_file == "") { + $first_file = $k; + } else { + $to_del[] = $k; + } + $news[$first_file]["aggregation"][$k] = $news[$k]; + $news[$first_file]["agg_ref_id"] = $a_ref_id; + $news[$first_file]["ref_id"] = $a_ref_id; + } + } + + foreach ($to_del as $v) { + unset($news[$v]); + } + + return $news; + } + + + /** + * Get news aggregation for child objects (e.g. for categories) + * @deprecated will move to ilNewsData + * @param $a_ref_id + * @param bool $a_only_public + * @param int $a_time_period + * @param bool $a_prevent_aggregation + * @param string $a_starting_date + * @param bool $a_no_auto_generated + * @return array|mixed + */ + protected function getAggregatedChildNewsData( + $a_ref_id, + $a_only_public = false, + $a_time_period = 0, + $a_prevent_aggregation = false, + $a_starting_date = "", + $a_no_auto_generated = false + ) { + $tree = $this->tree; + $ilAccess = $this->access; + + // get news of parent object + $data = $this->getNewsForRefId( + $a_ref_id, + $a_only_public, + true, + $a_time_period, + true, + false, + false, + $a_no_auto_generated + ); + foreach ($data as $k => $v) { + $data[$k]["ref_id"] = $a_ref_id; + } + + // get childs + $nodes = $tree->getChilds($a_ref_id); + + // no check, for which of the objects any news are available + $obj_ids = array(); + foreach ($nodes as $node) { + $obj_ids[] = $node["obj_id"]; + } $news_obj_ids = ilNewsItem::filterObjIdsPerNews($obj_ids, $a_time_period, $a_starting_date); - //$news_obj_ids = $obj_ids; - - // get news for all subtree nodes - $contexts = array(); - foreach($nodes as $node) - { - // only go on, if news are available - if (!in_array($node["obj_id"], $news_obj_ids)) - { - continue; - } - - if (!$a_only_public && !$ilAccess->checkAccess("read", "", $node["child"])) - { - continue; - } - $ref_id[$node["obj_id"]] = $node["child"]; - $contexts[] = array("obj_id" => $node["obj_id"], - "obj_type" => $node["type"]); - } - - $news = $this->queryNewsForMultipleContexts($contexts, $a_only_public, $a_time_period, - $a_starting_date, $a_no_auto_generated); - foreach ($news as $k => $v) - { - $news[$k]["ref_id"] = $ref_id[$v["context_obj_id"]]; - } - $data = ilNewsItem::mergeNews($data, $news); - - // sort and return + //$news_obj_ids = $obj_ids; + + // get news for all subtree nodes + $contexts = array(); + foreach ($nodes as $node) { + // only go on, if news are available + if (!in_array($node["obj_id"], $news_obj_ids)) { + continue; + } + + if (!$a_only_public && !$ilAccess->checkAccess("read", "", $node["child"])) { + continue; + } + $ref_id[$node["obj_id"]] = $node["child"]; + $contexts[] = array("obj_id" => $node["obj_id"], + "obj_type" => $node["type"]); + } + + $news = $this->queryNewsForMultipleContexts( + $contexts, + $a_only_public, + $a_time_period, + $a_starting_date, + $a_no_auto_generated + ); + foreach ($news as $k => $v) { + $news[$k]["ref_id"] = $ref_id[$v["context_obj_id"]]; + } + $data = ilNewsItem::mergeNews($data, $news); + + // sort and return $data = ilUtil::sortArray($data, "creation_date", "desc", false, true); - - if (!$a_prevent_aggregation) - { - $data = $this->aggregateFiles($data, $a_ref_id); - } - - return $data; - } - - /** - * Set context for news - * - * @param int $a_obj_id - * @param int $a_obj_type - * @param int $a_sub_obj_id - * @param string $a_sub_obj_type - */ - public function setContext(int $a_obj_id, string $a_obj_type, int $a_sub_obj_id = 0, string $a_sub_obj_type = "") - { - $this->setContextObjId($a_obj_id); - $this->setContextObjType($a_obj_type); - $this->setContextSubObjId($a_sub_obj_id); - $this->setContextSubObjType($a_sub_obj_type); - } - - /** - * Convert time period for DB-queries - * - * @param mixed $a_time_period - * @return string - */ - protected static function handleTimePeriod($a_time_period) - { - // time period is number of days - if(is_numeric($a_time_period)) - { - if($a_time_period > 0) - { - return date('Y-m-d H:i:s', time() - ($a_time_period * 24 * 60 * 60)); - } - } - // time period is datetime - else if(preg_match("/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/", $a_time_period)) - { - return $a_time_period; - } - // :TODO: what to return? - } - - /** - * Query news for a context - * - * @deprecated will move to ilNewsData + + if (!$a_prevent_aggregation) { + $data = $this->aggregateFiles($data, $a_ref_id); + } + + return $data; + } + + /** + * Set context for news + * + * @param int $a_obj_id + * @param int $a_obj_type + * @param int $a_sub_obj_id + * @param string $a_sub_obj_type + */ + public function setContext(int $a_obj_id, string $a_obj_type, int $a_sub_obj_id = 0, string $a_sub_obj_type = "") + { + $this->setContextObjId($a_obj_id); + $this->setContextObjType($a_obj_type); + $this->setContextSubObjId($a_sub_obj_id); + $this->setContextSubObjType($a_sub_obj_type); + } + + /** + * Convert time period for DB-queries + * + * @param mixed $a_time_period + * @return string + */ + protected static function handleTimePeriod($a_time_period) + { + // time period is number of days + if (is_numeric($a_time_period)) { + if ($a_time_period > 0) { + return date('Y-m-d H:i:s', time() - ($a_time_period * 24 * 60 * 60)); + } + } + // time period is datetime + elseif (preg_match("/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/", $a_time_period)) { + return $a_time_period; + } + // :TODO: what to return? + } + + /** + * Query news for a context + * + * @deprecated will move to ilNewsData * @param boolean query for outgoing rss feed * @param int time period in seconds * @param string startind date * @param boolean do not include auto generated news items - */ - public function queryNewsForContext($a_for_rss_use = false, $a_time_period = 0, - $a_starting_date = "", $a_no_auto_generated = false, $a_oldest_first = false, $a_limit = 0) - { - $ilDB = $this->db; - $ilUser = $this->user; - $lng = $this->lng; - - $and = ""; - if ($a_time_period > 0) - { - $limit_ts = self::handleTimePeriod($a_time_period); - $and = " AND creation_date >= ".$ilDB->quote($limit_ts, "timestamp")." "; - } - - if ($a_starting_date != "") - { - $and.= " AND creation_date > ".$ilDB->quote($a_starting_date, "timestamp")." "; - } - - if ($a_no_auto_generated) - { - $and.= " AND priority = 1 AND content_type = ".$ilDB->quote("text", "text")." "; - } - - // this is changed with 4.1 (news table for lm pages) - if ($this->getContextSubObjId() > 0) - { - $and.= " AND context_sub_obj_id = ".$ilDB->quote($this->getContextSubObjId(), "integer"). - " AND context_sub_obj_type = ".$ilDB->quote($this->getContextSubObjType(), "text"); - } - - $ordering = ($a_oldest_first) + */ + public function queryNewsForContext( + $a_for_rss_use = false, + $a_time_period = 0, + $a_starting_date = "", + $a_no_auto_generated = false, + $a_oldest_first = false, + $a_limit = 0 + ) { + $ilDB = $this->db; + $ilUser = $this->user; + $lng = $this->lng; + + $and = ""; + if ($a_time_period > 0) { + $limit_ts = self::handleTimePeriod($a_time_period); + $and = " AND creation_date >= " . $ilDB->quote($limit_ts, "timestamp") . " "; + } + + if ($a_starting_date != "") { + $and.= " AND creation_date > " . $ilDB->quote($a_starting_date, "timestamp") . " "; + } + + if ($a_no_auto_generated) { + $and.= " AND priority = 1 AND content_type = " . $ilDB->quote("text", "text") . " "; + } + + // this is changed with 4.1 (news table for lm pages) + if ($this->getContextSubObjId() > 0) { + $and.= " AND context_sub_obj_id = " . $ilDB->quote($this->getContextSubObjId(), "integer") . + " AND context_sub_obj_type = " . $ilDB->quote($this->getContextSubObjType(), "text"); + } + + $ordering = ($a_oldest_first) ? " creation_date ASC, id ASC " : " creation_date DESC, id DESC "; - if ($a_for_rss_use && ilNewsItem::getPrivateFeedId() == false) - { - $query = "SELECT * ". - "FROM il_news_item ". - " WHERE ". - "context_obj_id = ".$ilDB->quote($this->getContextObjId(), "integer"). - " AND context_obj_type = ".$ilDB->quote($this->getContextObjType(), "text"). - $and. - " ORDER BY ".$ordering; - } - elseif (ilNewsItem::getPrivateFeedId() != false) - { - $query = "SELECT il_news_item.* ". - ", il_news_read.user_id user_read ". - "FROM il_news_item LEFT JOIN il_news_read ". - "ON il_news_item.id = il_news_read.news_id AND ". - " il_news_read.user_id = ".$ilDB->quote(ilNewsItem::getPrivateFeedId(), "integer"). - " WHERE ". - "context_obj_id = ".$ilDB->quote($this->getContextObjId(), "integer"). - " AND context_obj_type = ".$ilDB->quote($this->getContextObjType(), "text"). - $and. - " ORDER BY ".$ordering; - } - else - { - $query = "SELECT il_news_item.* ". - ", il_news_read.user_id as user_read ". - "FROM il_news_item LEFT JOIN il_news_read ". - "ON il_news_item.id = il_news_read.news_id AND ". - " il_news_read.user_id = ".$ilDB->quote($ilUser->getId(), "integer"). - " WHERE ". - "context_obj_id = ".$ilDB->quote($this->getContextObjId(), "integer"). - " AND context_obj_type = ".$ilDB->quote($this->getContextObjType(), "text"). - $and. - " ORDER BY ".$ordering; - } -//echo $query; - $set = $ilDB->query($query); - $result = array(); - while($rec = $ilDB->fetchAssoc($set)) - { - if ($a_limit > 0 && count($result) >= $a_limit) - { - continue; - } - if (!$a_for_rss_use || (ilNewsItem::getPrivateFeedId() != false) || ($rec["visibility"] == NEWS_PUBLIC || - ($rec["priority"] == 0 && - ilBlockSetting::_lookup("news", "public_notifications", - 0, $rec["context_obj_id"])))) - { - $result[$rec["id"]] = $rec; - } - } - - // do we get data for rss and may the time limit by an issue? - // do a second query without time limit. - // this is not very performant, but I do not have a better - // idea. The keep_rss_min setting is currently (Jul 2012) only set - // by mediacasts - if ($a_time_period != "" && $a_for_rss_use) - { - include_once("./Services/Block/classes/class.ilBlockSetting.php"); - $keep_rss_min = ilBlockSetting::_lookup("news", "keep_rss_min", - 0, $this->getContextObjId()); - if ($keep_rss_min > 0) - { - return $this->queryNewsForContext(true, 0, - $a_starting_date, $a_no_auto_generated, $a_oldest_first, $keep_rss_min); - } - } - - return $result; - - } - - /** - * Query news data by news ids - * - * @param int[] $a_news_ids - * @return array[] - */ - static public function queryNewsByIds(array $a_news_ids) - { - global $DIC; - $ilDB = $DIC->database(); - $news = array(); - $set = $ilDB->query("SELECT * FROM il_news_item ". - " WHERE ".$ilDB->in("id", $a_news_ids, false, "integer")); - while ($rec = $ilDB->fetchAssoc($set)) - { - $news[$rec["id"]] = $rec; - } - return $news; - } - - /** - * - * @deprecated will move to ilNewsData - * @param int $a_ref_id - * @param int $a_time_period hours - * @return array news item ids - */ - public function checkNewsExistsForObjects($objects, $a_time_period = 1) - { - $ilDB = $this->db; - - $all = array(); - - $limit_ts = self::handleTimePeriod($a_time_period); - - // are there any news items for relevant objects and? - $query = $ilDB->query("SELECT id,context_obj_id,context_obj_type". - " FROM il_news_item". - " WHERE ".$ilDB->in("context_obj_id", array_keys($objects), false, "integer"). - " AND creation_date >= ".$ilDB->quote($limit_ts, "timestamp")); - while($rec = $ilDB->fetchAssoc($query)) - { - if ($objects[$rec["context_obj_id"]]["type"] == $rec["context_obj_type"]) - { - $all[] = $rec["id"]; - } - } - - return $all; - } - - /** - * Query News for multiple Contexts - * @deprecated will move to ilNewsData - * @param array $a_contexts - * @param bool $a_for_rss_use - * @param int $a_time_period - * @param string $a_starting_date - * @param bool $a_no_auto_generated - * @param null $a_user_id - * @param int $a_limit - * @param int[] $a_exclude - * @return array - */ - public function queryNewsForMultipleContexts($a_contexts, $a_for_rss_use = false, - $a_time_period = 0, $a_starting_date = "", $a_no_auto_generated = false, - $a_user_id = null, $a_limit = 0, $a_exclude = array()) - { - $ilDB = $this->db; - $ilUser = $this->user; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $and = ""; - if ($a_time_period > 0) - { - $limit_ts = self::handleTimePeriod($a_time_period); - $and = " AND creation_date >= ".$ilDB->quote($limit_ts, "timestamp")." "; - } - - if ($a_starting_date != "") - { - $and.= " AND creation_date > ".$ilDB->quote($a_starting_date, "timestamp")." "; - } - - if ($a_no_auto_generated) - { - $and.= " AND priority = 1 AND content_type = ".$ilDB->quote("text", "text")." "; - } - - if ($a_limit > 0) - { - $ilDB->setLimit($a_limit, 0); - } - - if (is_array($a_exclude) && count($a_exclude) > 0) - { - $and.= " AND ".$ilDB->in("id", $a_exclude, true, "integer")." "; - } - - $ids = array(); - $type = array(); - - foreach($a_contexts as $cont) - { - $ids[] = $cont["obj_id"]; - $type[$cont["obj_id"]] = $cont["obj_type"]; - } - - if ($a_for_rss_use && ilNewsItem::getPrivateFeedId() == false) - { - $query = "SELECT * ". - "FROM il_news_item ". - " WHERE ". - $ilDB->in("context_obj_id", $ids, false, "integer")." ". - $and. + if ($a_for_rss_use && ilNewsItem::getPrivateFeedId() == false) { + $query = "SELECT * " . + "FROM il_news_item " . + " WHERE " . + "context_obj_id = " . $ilDB->quote($this->getContextObjId(), "integer") . + " AND context_obj_type = " . $ilDB->quote($this->getContextObjType(), "text") . + $and . + " ORDER BY " . $ordering; + } elseif (ilNewsItem::getPrivateFeedId() != false) { + $query = "SELECT il_news_item.* " . + ", il_news_read.user_id user_read " . + "FROM il_news_item LEFT JOIN il_news_read " . + "ON il_news_item.id = il_news_read.news_id AND " . + " il_news_read.user_id = " . $ilDB->quote(ilNewsItem::getPrivateFeedId(), "integer") . + " WHERE " . + "context_obj_id = " . $ilDB->quote($this->getContextObjId(), "integer") . + " AND context_obj_type = " . $ilDB->quote($this->getContextObjType(), "text") . + $and . + " ORDER BY " . $ordering; + } else { + $query = "SELECT il_news_item.* " . + ", il_news_read.user_id as user_read " . + "FROM il_news_item LEFT JOIN il_news_read " . + "ON il_news_item.id = il_news_read.news_id AND " . + " il_news_read.user_id = " . $ilDB->quote($ilUser->getId(), "integer") . + " WHERE " . + "context_obj_id = " . $ilDB->quote($this->getContextObjId(), "integer") . + " AND context_obj_type = " . $ilDB->quote($this->getContextObjType(), "text") . + $and . + " ORDER BY " . $ordering; + } + //echo $query; + $set = $ilDB->query($query); + $result = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + if ($a_limit > 0 && count($result) >= $a_limit) { + continue; + } + if (!$a_for_rss_use || (ilNewsItem::getPrivateFeedId() != false) || ($rec["visibility"] == NEWS_PUBLIC || + ($rec["priority"] == 0 && + ilBlockSetting::_lookup( + "news", + "public_notifications", + 0, + $rec["context_obj_id"] + )))) { + $result[$rec["id"]] = $rec; + } + } + + // do we get data for rss and may the time limit by an issue? + // do a second query without time limit. + // this is not very performant, but I do not have a better + // idea. The keep_rss_min setting is currently (Jul 2012) only set + // by mediacasts + if ($a_time_period != "" && $a_for_rss_use) { + include_once("./Services/Block/classes/class.ilBlockSetting.php"); + $keep_rss_min = ilBlockSetting::_lookup( + "news", + "keep_rss_min", + 0, + $this->getContextObjId() + ); + if ($keep_rss_min > 0) { + return $this->queryNewsForContext( + true, + 0, + $a_starting_date, + $a_no_auto_generated, + $a_oldest_first, + $keep_rss_min + ); + } + } + + return $result; + } + + /** + * Query news data by news ids + * + * @param int[] $a_news_ids + * @return array[] + */ + public static function queryNewsByIds(array $a_news_ids) + { + global $DIC; + $ilDB = $DIC->database(); + $news = array(); + $set = $ilDB->query("SELECT * FROM il_news_item " . + " WHERE " . $ilDB->in("id", $a_news_ids, false, "integer")); + while ($rec = $ilDB->fetchAssoc($set)) { + $news[$rec["id"]] = $rec; + } + return $news; + } + + /** + * + * @deprecated will move to ilNewsData + * @param int $a_ref_id + * @param int $a_time_period hours + * @return array news item ids + */ + public function checkNewsExistsForObjects($objects, $a_time_period = 1) + { + $ilDB = $this->db; + + $all = array(); + + $limit_ts = self::handleTimePeriod($a_time_period); + + // are there any news items for relevant objects and? + $query = $ilDB->query("SELECT id,context_obj_id,context_obj_type" . + " FROM il_news_item" . + " WHERE " . $ilDB->in("context_obj_id", array_keys($objects), false, "integer") . + " AND creation_date >= " . $ilDB->quote($limit_ts, "timestamp")); + while ($rec = $ilDB->fetchAssoc($query)) { + if ($objects[$rec["context_obj_id"]]["type"] == $rec["context_obj_type"]) { + $all[] = $rec["id"]; + } + } + + return $all; + } + + /** + * Query News for multiple Contexts + * @deprecated will move to ilNewsData + * @param array $a_contexts + * @param bool $a_for_rss_use + * @param int $a_time_period + * @param string $a_starting_date + * @param bool $a_no_auto_generated + * @param null $a_user_id + * @param int $a_limit + * @param int[] $a_exclude + * @return array + */ + public function queryNewsForMultipleContexts( + $a_contexts, + $a_for_rss_use = false, + $a_time_period = 0, + $a_starting_date = "", + $a_no_auto_generated = false, + $a_user_id = null, + $a_limit = 0, + $a_exclude = array() + ) { + $ilDB = $this->db; + $ilUser = $this->user; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $and = ""; + if ($a_time_period > 0) { + $limit_ts = self::handleTimePeriod($a_time_period); + $and = " AND creation_date >= " . $ilDB->quote($limit_ts, "timestamp") . " "; + } + + if ($a_starting_date != "") { + $and.= " AND creation_date > " . $ilDB->quote($a_starting_date, "timestamp") . " "; + } + + if ($a_no_auto_generated) { + $and.= " AND priority = 1 AND content_type = " . $ilDB->quote("text", "text") . " "; + } + + if ($a_limit > 0) { + $ilDB->setLimit($a_limit, 0); + } + + if (is_array($a_exclude) && count($a_exclude) > 0) { + $and.= " AND " . $ilDB->in("id", $a_exclude, true, "integer") . " "; + } + + $ids = array(); + $type = array(); + + foreach ($a_contexts as $cont) { + $ids[] = $cont["obj_id"]; + $type[$cont["obj_id"]] = $cont["obj_type"]; + } + + if ($a_for_rss_use && ilNewsItem::getPrivateFeedId() == false) { + $query = "SELECT * " . + "FROM il_news_item " . + " WHERE " . + $ilDB->in("context_obj_id", $ids, false, "integer") . " " . + $and . " ORDER BY creation_date DESC "; - } - elseif (ilNewsItem::getPrivateFeedId() != false) - { - $query = "SELECT il_news_item.* ". - ", il_news_read.user_id as user_read ". - "FROM il_news_item LEFT JOIN il_news_read ". - "ON il_news_item.id = il_news_read.news_id AND ". - " il_news_read.user_id = ".$ilDB->quote(ilNewsItem::getPrivateFeedId(), "integer"). - " WHERE ". - $ilDB->in("context_obj_id", $ids, false, "integer")." ". - $and. + } elseif (ilNewsItem::getPrivateFeedId() != false) { + $query = "SELECT il_news_item.* " . + ", il_news_read.user_id as user_read " . + "FROM il_news_item LEFT JOIN il_news_read " . + "ON il_news_item.id = il_news_read.news_id AND " . + " il_news_read.user_id = " . $ilDB->quote(ilNewsItem::getPrivateFeedId(), "integer") . + " WHERE " . + $ilDB->in("context_obj_id", $ids, false, "integer") . " " . + $and . " ORDER BY creation_date DESC "; - } - else - { - if($a_user_id) - { - $user_id = $a_user_id; - } - else - { - $user_id = $ilUser->getId(); - } - $query = "SELECT il_news_item.* ". - ", il_news_read.user_id as user_read ". - "FROM il_news_item LEFT JOIN il_news_read ". - "ON il_news_item.id = il_news_read.news_id AND ". - " il_news_read.user_id = ".$ilDB->quote($user_id, "integer"). - " WHERE ". - $ilDB->in("context_obj_id", $ids, false, "integer")." ". - $and. + } else { + if ($a_user_id) { + $user_id = $a_user_id; + } else { + $user_id = $ilUser->getId(); + } + $query = "SELECT il_news_item.* " . + ", il_news_read.user_id as user_read " . + "FROM il_news_item LEFT JOIN il_news_read " . + "ON il_news_item.id = il_news_read.news_id AND " . + " il_news_read.user_id = " . $ilDB->quote($user_id, "integer") . + " WHERE " . + $ilDB->in("context_obj_id", $ids, false, "integer") . " " . + $and . " ORDER BY creation_date DESC "; - } - - $set = $ilDB->query($query); - $result = array(); - while($rec = $ilDB->fetchAssoc($set)) - { - if ($type[$rec["context_obj_id"]] == $rec["context_obj_type"]) - { - if (!$a_for_rss_use || ilNewsItem::getPrivateFeedId() != false || ($rec["visibility"] == NEWS_PUBLIC || - ($rec["priority"] == 0 && - ilBlockSetting::_lookup("news", "public_notifications", - 0, $rec["context_obj_id"])))) - { - $result[$rec["id"]] = $rec; - } - } - } - - return $result; - - } - - - /** - * Set item read. - * @deprecated will move to ilNewsData - */ - static function _setRead($a_user_id, $a_news_id) - { - global $DIC; - - $ilDB = $DIC->database(); - $ilAppEventHandler = $DIC["ilAppEventHandler"]; - - $ilDB->replace("il_news_read", - array( - "user_id" => array("integer", $a_user_id), - "news_id" => array("integer", $a_news_id) - ), - array() - ); - - /* - $ilDB->manipulate("DELETE FROM il_news_read WHERE ". - "user_id = ".$ilDB->quote($a_user_id, "integer"). - " AND news_id = ".$ilDB->quote($a_news_id, "integer")); - $ilDB->manipulate("INSERT INTO il_news_read (user_id, news_id) VALUES (". - $ilDB->quote($a_user_id, "integer").",". - $ilDB->quote($a_news_id, "integer").")");*/ - - $ilAppEventHandler->raise("Services/News", "readNews", - array("user_id" => $a_user_id, "news_ids" => array($a_news_id))); - } - - /** - * Set item unread. - * @deprecated will move to ilNewsData - */ - static function _setUnread($a_user_id, $a_news_id) - { - global $DIC; - - $ilDB = $DIC->database(); - $ilAppEventHandler = $DIC["ilAppEventHandler"]; - - $ilDB->manipulate("DELETE FROM il_news_read (user_id, news_id) VALUES (". - " WHERE user_id = ".$ilDB->quote($a_user_id, "integer"). - " AND news_id = ".$ilDB->quote($a_news_id, "integer")); - - $ilAppEventHandler->raise("Services/News", "unreadNews", - array("user_id" => $a_user_id, "news_ids" => array($a_news_id))); - } - - /** - * Merges two sets of news - * @deprecated will move to ilNewsData - * @param array $n1 Array of news - * @param array $n2 Array of news - * - * @return array Array of news - */ - static function mergeNews($n1, $n2) - { - foreach($n2 as $id => $news) - { - $n1[$id] = $news; - } - - return $n1; - } - - /** - * Get default visibility for reference id - * @deprecated will move to ilNewsData - * @param $a_ref_id reference id - */ - static function _getDefaultVisibilityForRefId($a_ref_id) - { - global $DIC; - - $tree = $DIC->repositoryTree(); - $ilSetting = $DIC->settings(); - - include_once("./Services/Block/classes/class.ilBlockSetting.php"); - - $news_set = new ilSetting("news"); - $default_visibility = ($news_set->get("default_visibility") != "") - ? $news_set->get("default_visibility") - : "users"; - - if ($tree->isInTree($a_ref_id)) - { - $path = $tree->getPathFull($a_ref_id); - - foreach ($path as $key => $row) - { - if (!in_array($row["type"], array("root", "cat","crs", "fold", "grp"))) - { - continue; - } - - $visibility = ilBlockSetting::_lookup("news", "default_visibility", - 0, $row["obj_id"]); - - if ($visibility != "") - { - $default_visibility = $visibility; - } - } - } - - return $default_visibility; - } - - - /** - * Delete news item - * @deprecated will move to ilNewsData - */ - public function delete() - { - $ilDB = $this->db; - - // delete il_news_read entries - $ilDB->manipulate("DELETE FROM il_news_read ". - " WHERE news_id = ".$ilDB->quote($this->getId(), "integer")); - - // delete multimedia object - $mob = $this->getMobId(); - - // delete - $query = "DELETE FROM il_news_item". - " WHERE id = ".$ilDB->quote($this->getId(), "integer"); - $ilDB->manipulate($query); - - // delete mob after news, to have a "mob usage" of 0 - if ($mob > 0 and ilObject::_exists($mob)) - { - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $mob = new ilObjMediaObject($mob); - $mob->delete(); - } - } - - /** - * Get all news of a context - * @deprecated will move to ilNewsData - */ - static public function getNewsOfContext($a_context_obj_id, - $a_context_obj_type, $a_context_sub_obj_id = 0, $a_context_sub_obj_type = "") - { - global $DIC; - - $ilDB = $DIC->database(); - - if ($a_context_obj_id == 0 || $a_context_obj_type == "") - { - return []; - } - - if ($a_context_sub_obj_id > 0) - { - $and = " AND context_sub_obj_id = ".$ilDB->quote($a_context_sub_obj_id, "integer"). - " AND context_sub_obj_type = ".$ilDB->quote($a_context_sub_obj_type, "text"); - } - - // get news records - $query = "SELECT * FROM il_news_item". - " WHERE context_obj_id = ".$ilDB->quote($a_context_obj_id, "integer"). - " AND context_obj_type = ".$ilDB->quote($a_context_obj_type, "text"). - $and; - - $news_set = $ilDB->query($query); - - $news_arr = []; - while ($news = $ilDB->fetchAssoc($news_set)) - { - $news_arr[] = new ilNewsItem($news["id"]); - } - return $news_arr; - } - - /** - * Delete all news of a context - * @deprecated will move to ilNewsData - */ - static public function deleteNewsOfContext($a_context_obj_id, - $a_context_obj_type, $a_context_sub_obj_id = 0, $a_context_sub_obj_type = "") - { - foreach (self::getNewsOfContext($a_context_obj_id, - $a_context_obj_type, $a_context_sub_obj_id, $a_context_sub_obj_type) as $n) - { - $n->delete(); - } - } - - /** - * Lookup News Title - * @deprecated will move to ilNewsData - */ - static function _lookupTitle($a_news_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT title FROM il_news_item WHERE id = ". - $ilDB->quote($a_news_id, "integer"); - $set = $ilDB->query($query); - $rec = $ilDB->fetchAssoc($set); - return $rec["title"]; - } - - /** - * Lookup News Visibility - * @deprecated will move to ilNewsData - */ - static function _lookupVisibility($a_news_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT visibility FROM il_news_item WHERE id = ". - $ilDB->quote($a_news_id, "integer"); - $set = $ilDB->query($query); - $rec = $ilDB->fetchAssoc($set); - - return $rec["visibility"]; - } - - /** - * Lookup mob id - * @deprecated will move to ilNewsData - */ - static function _lookupMobId($a_news_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT mob_id FROM il_news_item WHERE id = ". - $ilDB->quote($a_news_id, "integer"); - $set = $ilDB->query($query); - $rec = $ilDB->fetchAssoc($set); - return $rec["mob_id"]; - } - - /** - * Checks whether news are available for - * @deprecated will move to ilNewsData - */ - static function filterObjIdsPerNews($a_obj_ids, $a_time_period = 0, $a_starting_date = "",$a_ending_date = '', $ignore_period = false) - { - global $DIC; - - $ilDB = $DIC->database(); - - $and = ""; - if ($a_time_period > 0) - { - $limit_ts = self::handleTimePeriod($a_time_period); - $and = " AND creation_date >= ".$ilDB->quote($limit_ts, "timestamp")." "; - } - - if ($a_starting_date != "") - { - $and.= " AND creation_date >= ".$ilDB->quote($a_starting_date, "timestamp"); - } - - $query = "SELECT DISTINCT(context_obj_id) AS obj_id FROM il_news_item". - " WHERE ".$ilDB->in("context_obj_id", $a_obj_ids, false, "integer")." ".$and; - //" WHERE context_obj_id IN (".implode(ilUtil::quoteArray($a_obj_ids),",").")".$and; - - $set = $ilDB->query($query); - $objs = array(); - while($rec = $ilDB->fetchAssoc($set)) - { - $objs[] = $rec["obj_id"]; - } - - return $objs; - } - - /** - * Determine title for news item entry - */ - static function determineNewsTitleByNewsId($a_news_id, $a_agg_ref_id = 0, $a_aggregation = "") - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT context_obj_type, content_is_lang_var, title FROM il_news_item WHERE id = ". - $ilDB->quote($a_news_id, "integer"); - $set = $ilDB->query($query); - $rec = $ilDB->fetchAssoc($set); - - return self::determineNewsTitle($rec["context_obj_type"], $rec["title"], $rec["content_is_lang_var"], - $a_agg_ref_id, $a_aggregation); - } - - /** - * Determine title for news item entry - * @deprecated will move to util? - */ - static function determineNewsTitle($a_context_obj_type, $a_title, $a_content_is_lang_var, - $a_agg_ref_id = 0, $a_aggregation = "") - { - global $DIC; - - $lng = $DIC->language(); - $obj_definition = $DIC["objDefinition"]; - - if ($a_agg_ref_id > 0) - { - $cnt = count($a_aggregation); - - // forums - if ($a_context_obj_type == "frm") - { - if ($cnt > 1) - { - return sprintf($lng->txt("news_x_postings"), $cnt); - } - else - { - return $lng->txt("news_1_postings"); - } - } - else // files - { - $up_cnt = $cr_cnt = 0; - foreach($a_aggregation as $item) - { - if ($item["title"] == "file_updated") - { - $up_cnt++; - } - else - { - $cr_cnt++; - } - } - $sep = ""; - if ($cr_cnt == 1) - { - $tit = $lng->txt("news_1_file_created"); - $sep = "
                  "; - } - else if ($cr_cnt > 1) - { - $tit = sprintf($lng->txt("news_x_files_created"), $cr_cnt); - $sep = "
                  "; - } - if ($up_cnt == 1) - { - $tit .= $sep.$lng->txt("news_1_file_updated"); - } - else if ($up_cnt > 1) - { - $tit .= $sep.sprintf($lng->txt("news_x_files_updated"), $up_cnt); - } - return $tit; - } - } - else - { - if ($a_content_is_lang_var) - { - if($obj_definition->isPlugin($a_context_obj_type)) - { - return ilObjectPlugin::lookupTxtById($a_context_obj_type, $a_title); - } - return $lng->txt($a_title); - } - else - { - return $a_title; - } - } - - return ""; - } - - /** - * Determine new content - * @deprecated will move to util? - */ - static function determineNewsContent($a_context_obj_type, $a_content, $a_is_lang_var) - { - global $DIC; - - $lng = $DIC->language(); - $obj_definition = $DIC["objDefinition"]; - - if ($a_is_lang_var) - { - if($obj_definition->isPlugin($a_context_obj_type)) - { - return ilObjectPlugin::lookupTxtById($a_context_obj_type, $a_content); - } - $lng->loadLanguageModule($a_context_obj_type); - return $lng->txt($a_content); - } - else - { - return $a_content; - } - } - - - - /** - * Get first new id of news set related to a certain context - * @deprecated will move to ilNewsData - */ - static function getFirstNewsIdForContext($a_context_obj_id, - $a_context_obj_type, $a_context_sub_obj_id = "", $a_context_sub_obj_type = "") - { - global $DIC; - - $ilDB = $DIC->database(); - - // Determine how many rows should be deleted - $query = "SELECT * ". - "FROM il_news_item ". - "WHERE ". - "context_obj_id = ".$ilDB->quote($a_context_obj_id, "integer"). - " AND context_obj_type = ".$ilDB->quote($a_context_obj_type, "text"). - " AND context_sub_obj_id = ".$ilDB->quote($a_context_sub_obj_id, "integer"). - " AND ".$ilDB->equals("context_sub_obj_type", $a_context_sub_obj_type, "text", true); - - $set = $ilDB->query($query); - $rec = $ilDB->fetchAssoc($set); - - return $rec["id"]; - } - - /** - * Get last news id of news set related to a certain context - * @deprecated will move to ilNewsData - */ - static function getLastNewsIdForContext($a_context_obj_id, - $a_context_obj_type, $a_context_sub_obj_id = "", $a_context_sub_obj_type = "", - $a_only_today = false) - { - global $DIC; - - $ilDB = $DIC->database(); - - // Determine how many rows should be deleted - $query = "SELECT id, update_date ". - "FROM il_news_item ". - "WHERE ". - "context_obj_id = ".$ilDB->quote($a_context_obj_id, "integer"). - " AND context_obj_type = ".$ilDB->quote($a_context_obj_type, "text"). - " AND context_sub_obj_id = ".$ilDB->quote($a_context_sub_obj_id, "integer"). - " AND ".$ilDB->equals("context_sub_obj_type", $a_context_sub_obj_type, "text", true). - " ORDER BY update_date DESC"; - - $ilDB->setLimit(1); - $set = $ilDB->query($query); - $rec = $ilDB->fetchAssoc($set); - - $id = (int) $rec["id"]; - if ($a_only_today) - { - $now = ilUtil::now(); - if (substr($now, 0, 10) != substr($rec["update_date"], 0, 10)) - { - $id = 0; - } - } - - return $id; - } - - - /** - * Lookup media object usage(s) - * @deprecated will move to ilNewsData - */ - static function _lookupMediaObjectUsages($a_mob_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT * ". - "FROM il_news_item ". - "WHERE ". - " mob_id = ".$ilDB->quote($a_mob_id, "integer"); - - $usages = array(); - $set = $ilDB->query($query); - while ($rec = $ilDB->fetchAssoc($set)) - { - $usages[$rec["id"]] = array("type" => "news", "id" => $rec["id"]); - } - - return $usages; - } - - /** - * Context Object ID - * @deprecated will move to ilNewsData - */ - static function _lookupContextObjId($a_news_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT * ". - "FROM il_news_item ". - "WHERE ". - " id = ".$ilDB->quote($a_news_id, "integer"); - $set = $ilDB->query($query); - $rec = $ilDB->fetchAssoc($set); - - return $rec["context_obj_id"]; - } - - /** - * @deprecated will move to settings - */ - static function _lookupDefaultPDPeriod() - { - $news_set = new ilSetting("news"); - $per = $news_set->get("pd_period"); - if ($per == 0) - { - $per = 30; - } - - return $per; - } - - /** - * @deprecated will move to settings->user - */ - static function _lookupUserPDPeriod($a_user_id) - { - $news_set = new ilSetting("news"); - $allow_shorter_periods = $news_set->get("allow_shorter_periods"); - $allow_longer_periods = $news_set->get("allow_longer_periods"); - $default_per = ilNewsItem::_lookupDefaultPDPeriod(); - - include_once("./Services/Block/classes/class.ilBlockSetting.php"); - $per = ilBlockSetting::_lookup("pdnews", "news_pd_period", - $a_user_id, 0); - - // news period information - if ($per <= 0 || - (!$allow_shorter_periods && ($per < $default_per)) || - (!$allow_longer_periods && ($per > $default_per)) - ) - { - $per = $default_per; - } - - return $per; - } - - /** - * @deprecated will move to settings - */ - static function _lookupRSSPeriod() - { - $news_set = new ilSetting("news"); - $rss_period = $news_set->get("rss_period"); - if ($rss_period == 0) // default to two weeks - { - $rss_period = 14; - } - return $rss_period; - } - - /** - * @deprecated will move to settings->user - */ - static function setPrivateFeedId ($a_userId) - { - ilNewsItem::$privFeedId = $a_userId; - } - - /** - * @deprecated will move to settings->user - */ - static function getPrivateFeedId () { - - return ilNewsItem::$privFeedId; - } - - /** - * Deliver mob file - * - * @deprecated will move to ? - * @param string $a_purpose - * @param bool $a_increase_download_cnt - * @return bool - */ - function deliverMobFile($a_purpose = "Standard", $a_increase_download_cnt = false) - { - $mob = $this->getMobId(); - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $mob = new ilObjMediaObject($mob); - $mob_dir = ilObjMediaObject::_getDirectory($mob->getId()); - - // check purpose - if (!$mob->hasPurposeItem($a_purpose)) - { - return false; - } - - $m_item = $mob->getMediaItem($a_purpose); - if ($m_item->getLocationType() != "Reference") - { - $file = $mob_dir."/".$m_item->getLocation(); - if (file_exists($file) && is_file($file)) - { - if ($a_increase_download_cnt) - { - $this->increaseDownloadCounter(); - } - ilUtil::deliverFile($file, $m_item->getLocation(), "", false, false, false); - return true; - } - else - { - ilUtil::sendFailure("File not found!",true); - return false; - } - } - else - { - if ($a_increase_download_cnt) - { - $this->increaseDownloadCounter(); - } - ilUtil::redirect($m_item->getLocation()); - } - } - - /** - * Increase download counter - * @deprecated will move to data - */ - function increaseDownloadCounter() - { - $ilDB = $this->db; - - $cnt = $this->getMobDownloadCounter(); - $cnt++; - $this->setMobDownloadCounter($cnt); - $ilDB->manipulate("UPDATE il_news_item SET ". - " mob_cnt_download = ".$ilDB->quote($cnt, "integer"). - " WHERE id = ".$ilDB->quote($this->getId(), "integer") - ); - } - - /** - * Increase play counter - * - * @deprecated will move to data - */ - function increasePlayCounter() - { - $ilDB = $this->db; - - $cnt = $this->getMobPlayCounter(); - $cnt++; - $this->setMobPlayCounter($cnt); - $ilDB->manipulate("UPDATE il_news_item SET ". - " mob_cnt_play = ".$ilDB->quote($cnt, "integer"). - " WHERE id = ".$ilDB->quote($this->getId(), "integer") - ); - } - - /** - * Prepare news data from cache - * @deprecated will move to data - * @param string $a_cres cache string - * @return array news array - */ - static function prepareNewsDataFromCache($a_cres) - { - global $DIC; - - $ilDB = $DIC->database(); - - $data = $a_cres; - $news_ids = array_keys($data); - $set = $ilDB->query("SELECT id FROM il_news_item ". - " WHERE ".$ilDB->in("id", $news_ids, false, "integer")); - $existing_ids = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $existing_ids[] = $rec["id"]; - } - //var_dump($existing_ids); - $existing_news = array(); - foreach ($data as $k => $v) - { - if (in_array($k, $existing_ids)) - { - $existing_news[$k] = $v; - } - } - - //var_dump($data); - //var_dump($existing_news); - - return $existing_news; - } - + } + + $set = $ilDB->query($query); + $result = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + if ($type[$rec["context_obj_id"]] == $rec["context_obj_type"]) { + if (!$a_for_rss_use || ilNewsItem::getPrivateFeedId() != false || ($rec["visibility"] == NEWS_PUBLIC || + ($rec["priority"] == 0 && + ilBlockSetting::_lookup( + "news", + "public_notifications", + 0, + $rec["context_obj_id"] + )))) { + $result[$rec["id"]] = $rec; + } + } + } + + return $result; + } + + + /** + * Set item read. + * @deprecated will move to ilNewsData + */ + public static function _setRead($a_user_id, $a_news_id) + { + global $DIC; + + $ilDB = $DIC->database(); + $ilAppEventHandler = $DIC["ilAppEventHandler"]; + + $ilDB->replace( + "il_news_read", + array( + "user_id" => array("integer", $a_user_id), + "news_id" => array("integer", $a_news_id) + ), + array() + ); + + /* + $ilDB->manipulate("DELETE FROM il_news_read WHERE ". + "user_id = ".$ilDB->quote($a_user_id, "integer"). + " AND news_id = ".$ilDB->quote($a_news_id, "integer")); + $ilDB->manipulate("INSERT INTO il_news_read (user_id, news_id) VALUES (". + $ilDB->quote($a_user_id, "integer").",". + $ilDB->quote($a_news_id, "integer").")");*/ + + $ilAppEventHandler->raise( + "Services/News", + "readNews", + array("user_id" => $a_user_id, "news_ids" => array($a_news_id)) + ); + } + + /** + * Set item unread. + * @deprecated will move to ilNewsData + */ + public static function _setUnread($a_user_id, $a_news_id) + { + global $DIC; + + $ilDB = $DIC->database(); + $ilAppEventHandler = $DIC["ilAppEventHandler"]; + + $ilDB->manipulate("DELETE FROM il_news_read (user_id, news_id) VALUES (" . + " WHERE user_id = " . $ilDB->quote($a_user_id, "integer") . + " AND news_id = " . $ilDB->quote($a_news_id, "integer")); + + $ilAppEventHandler->raise( + "Services/News", + "unreadNews", + array("user_id" => $a_user_id, "news_ids" => array($a_news_id)) + ); + } + + /** + * Merges two sets of news + * @deprecated will move to ilNewsData + * @param array $n1 Array of news + * @param array $n2 Array of news + * + * @return array Array of news + */ + public static function mergeNews($n1, $n2) + { + foreach ($n2 as $id => $news) { + $n1[$id] = $news; + } + + return $n1; + } + + /** + * Get default visibility for reference id + * @deprecated will move to ilNewsData + * @param $a_ref_id reference id + */ + public static function _getDefaultVisibilityForRefId($a_ref_id) + { + global $DIC; + + $tree = $DIC->repositoryTree(); + $ilSetting = $DIC->settings(); + + include_once("./Services/Block/classes/class.ilBlockSetting.php"); + + $news_set = new ilSetting("news"); + $default_visibility = ($news_set->get("default_visibility") != "") + ? $news_set->get("default_visibility") + : "users"; + + if ($tree->isInTree($a_ref_id)) { + $path = $tree->getPathFull($a_ref_id); + + foreach ($path as $key => $row) { + if (!in_array($row["type"], array("root", "cat","crs", "fold", "grp"))) { + continue; + } + + $visibility = ilBlockSetting::_lookup( + "news", + "default_visibility", + 0, + $row["obj_id"] + ); + + if ($visibility != "") { + $default_visibility = $visibility; + } + } + } + + return $default_visibility; + } + + + /** + * Delete news item + * @deprecated will move to ilNewsData + */ + public function delete() + { + $ilDB = $this->db; + + // delete il_news_read entries + $ilDB->manipulate("DELETE FROM il_news_read " . + " WHERE news_id = " . $ilDB->quote($this->getId(), "integer")); + + // delete multimedia object + $mob = $this->getMobId(); + + // delete + $query = "DELETE FROM il_news_item" . + " WHERE id = " . $ilDB->quote($this->getId(), "integer"); + $ilDB->manipulate($query); + + // delete mob after news, to have a "mob usage" of 0 + if ($mob > 0 and ilObject::_exists($mob)) { + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $mob = new ilObjMediaObject($mob); + $mob->delete(); + } + } + + /** + * Get all news of a context + * @deprecated will move to ilNewsData + */ + public static function getNewsOfContext( + $a_context_obj_id, + $a_context_obj_type, + $a_context_sub_obj_id = 0, + $a_context_sub_obj_type = "" + ) { + global $DIC; + + $ilDB = $DIC->database(); + + if ($a_context_obj_id == 0 || $a_context_obj_type == "") { + return []; + } + + if ($a_context_sub_obj_id > 0) { + $and = " AND context_sub_obj_id = " . $ilDB->quote($a_context_sub_obj_id, "integer") . + " AND context_sub_obj_type = " . $ilDB->quote($a_context_sub_obj_type, "text"); + } + + // get news records + $query = "SELECT * FROM il_news_item" . + " WHERE context_obj_id = " . $ilDB->quote($a_context_obj_id, "integer") . + " AND context_obj_type = " . $ilDB->quote($a_context_obj_type, "text") . + $and; + + $news_set = $ilDB->query($query); + + $news_arr = []; + while ($news = $ilDB->fetchAssoc($news_set)) { + $news_arr[] = new ilNewsItem($news["id"]); + } + return $news_arr; + } + + /** + * Delete all news of a context + * @deprecated will move to ilNewsData + */ + public static function deleteNewsOfContext( + $a_context_obj_id, + $a_context_obj_type, + $a_context_sub_obj_id = 0, + $a_context_sub_obj_type = "" + ) { + foreach (self::getNewsOfContext( + $a_context_obj_id, + $a_context_obj_type, + $a_context_sub_obj_id, + $a_context_sub_obj_type + ) as $n) { + $n->delete(); + } + } + + /** + * Lookup News Title + * @deprecated will move to ilNewsData + */ + public static function _lookupTitle($a_news_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT title FROM il_news_item WHERE id = " . + $ilDB->quote($a_news_id, "integer"); + $set = $ilDB->query($query); + $rec = $ilDB->fetchAssoc($set); + return $rec["title"]; + } + + /** + * Lookup News Visibility + * @deprecated will move to ilNewsData + */ + public static function _lookupVisibility($a_news_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT visibility FROM il_news_item WHERE id = " . + $ilDB->quote($a_news_id, "integer"); + $set = $ilDB->query($query); + $rec = $ilDB->fetchAssoc($set); + + return $rec["visibility"]; + } + + /** + * Lookup mob id + * @deprecated will move to ilNewsData + */ + public static function _lookupMobId($a_news_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT mob_id FROM il_news_item WHERE id = " . + $ilDB->quote($a_news_id, "integer"); + $set = $ilDB->query($query); + $rec = $ilDB->fetchAssoc($set); + return $rec["mob_id"]; + } + + /** + * Checks whether news are available for + * @deprecated will move to ilNewsData + */ + public static function filterObjIdsPerNews($a_obj_ids, $a_time_period = 0, $a_starting_date = "", $a_ending_date = '', $ignore_period = false) + { + global $DIC; + + $ilDB = $DIC->database(); + + $and = ""; + if ($a_time_period > 0) { + $limit_ts = self::handleTimePeriod($a_time_period); + $and = " AND creation_date >= " . $ilDB->quote($limit_ts, "timestamp") . " "; + } + + if ($a_starting_date != "") { + $and.= " AND creation_date >= " . $ilDB->quote($a_starting_date, "timestamp"); + } + + $query = "SELECT DISTINCT(context_obj_id) AS obj_id FROM il_news_item" . + " WHERE " . $ilDB->in("context_obj_id", $a_obj_ids, false, "integer") . " " . $and; + //" WHERE context_obj_id IN (".implode(ilUtil::quoteArray($a_obj_ids),",").")".$and; + + $set = $ilDB->query($query); + $objs = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $objs[] = $rec["obj_id"]; + } + + return $objs; + } + + /** + * Determine title for news item entry + */ + public static function determineNewsTitleByNewsId($a_news_id, $a_agg_ref_id = 0, $a_aggregation = "") + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT context_obj_type, content_is_lang_var, title FROM il_news_item WHERE id = " . + $ilDB->quote($a_news_id, "integer"); + $set = $ilDB->query($query); + $rec = $ilDB->fetchAssoc($set); + + return self::determineNewsTitle( + $rec["context_obj_type"], + $rec["title"], + $rec["content_is_lang_var"], + $a_agg_ref_id, + $a_aggregation + ); + } + + /** + * Determine title for news item entry + * @deprecated will move to util? + */ + public static function determineNewsTitle( + $a_context_obj_type, + $a_title, + $a_content_is_lang_var, + $a_agg_ref_id = 0, + $a_aggregation = "" + ) { + global $DIC; + + $lng = $DIC->language(); + $obj_definition = $DIC["objDefinition"]; + + if ($a_agg_ref_id > 0) { + $cnt = count($a_aggregation); + + // forums + if ($a_context_obj_type == "frm") { + if ($cnt > 1) { + return sprintf($lng->txt("news_x_postings"), $cnt); + } else { + return $lng->txt("news_1_postings"); + } + } else { // files + $up_cnt = $cr_cnt = 0; + foreach ($a_aggregation as $item) { + if ($item["title"] == "file_updated") { + $up_cnt++; + } else { + $cr_cnt++; + } + } + $sep = ""; + if ($cr_cnt == 1) { + $tit = $lng->txt("news_1_file_created"); + $sep = "
                  "; + } elseif ($cr_cnt > 1) { + $tit = sprintf($lng->txt("news_x_files_created"), $cr_cnt); + $sep = "
                  "; + } + if ($up_cnt == 1) { + $tit .= $sep . $lng->txt("news_1_file_updated"); + } elseif ($up_cnt > 1) { + $tit .= $sep . sprintf($lng->txt("news_x_files_updated"), $up_cnt); + } + return $tit; + } + } else { + if ($a_content_is_lang_var) { + if ($obj_definition->isPlugin($a_context_obj_type)) { + return ilObjectPlugin::lookupTxtById($a_context_obj_type, $a_title); + } + return $lng->txt($a_title); + } else { + return $a_title; + } + } + + return ""; + } + + /** + * Determine new content + * @deprecated will move to util? + */ + public static function determineNewsContent($a_context_obj_type, $a_content, $a_is_lang_var) + { + global $DIC; + + $lng = $DIC->language(); + $obj_definition = $DIC["objDefinition"]; + + if ($a_is_lang_var) { + if ($obj_definition->isPlugin($a_context_obj_type)) { + return ilObjectPlugin::lookupTxtById($a_context_obj_type, $a_content); + } + $lng->loadLanguageModule($a_context_obj_type); + return $lng->txt($a_content); + } else { + return $a_content; + } + } + + + + /** + * Get first new id of news set related to a certain context + * @deprecated will move to ilNewsData + */ + public static function getFirstNewsIdForContext( + $a_context_obj_id, + $a_context_obj_type, + $a_context_sub_obj_id = "", + $a_context_sub_obj_type = "" + ) { + global $DIC; + + $ilDB = $DIC->database(); + + // Determine how many rows should be deleted + $query = "SELECT * " . + "FROM il_news_item " . + "WHERE " . + "context_obj_id = " . $ilDB->quote($a_context_obj_id, "integer") . + " AND context_obj_type = " . $ilDB->quote($a_context_obj_type, "text") . + " AND context_sub_obj_id = " . $ilDB->quote($a_context_sub_obj_id, "integer") . + " AND " . $ilDB->equals("context_sub_obj_type", $a_context_sub_obj_type, "text", true); + + $set = $ilDB->query($query); + $rec = $ilDB->fetchAssoc($set); + + return $rec["id"]; + } + + /** + * Get last news id of news set related to a certain context + * @deprecated will move to ilNewsData + */ + public static function getLastNewsIdForContext( + $a_context_obj_id, + $a_context_obj_type, + $a_context_sub_obj_id = "", + $a_context_sub_obj_type = "", + $a_only_today = false + ) { + global $DIC; + + $ilDB = $DIC->database(); + + // Determine how many rows should be deleted + $query = "SELECT id, update_date " . + "FROM il_news_item " . + "WHERE " . + "context_obj_id = " . $ilDB->quote($a_context_obj_id, "integer") . + " AND context_obj_type = " . $ilDB->quote($a_context_obj_type, "text") . + " AND context_sub_obj_id = " . $ilDB->quote($a_context_sub_obj_id, "integer") . + " AND " . $ilDB->equals("context_sub_obj_type", $a_context_sub_obj_type, "text", true) . + " ORDER BY update_date DESC"; + + $ilDB->setLimit(1); + $set = $ilDB->query($query); + $rec = $ilDB->fetchAssoc($set); + + $id = (int) $rec["id"]; + if ($a_only_today) { + $now = ilUtil::now(); + if (substr($now, 0, 10) != substr($rec["update_date"], 0, 10)) { + $id = 0; + } + } + + return $id; + } + + + /** + * Lookup media object usage(s) + * @deprecated will move to ilNewsData + */ + public static function _lookupMediaObjectUsages($a_mob_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT * " . + "FROM il_news_item " . + "WHERE " . + " mob_id = " . $ilDB->quote($a_mob_id, "integer"); + + $usages = array(); + $set = $ilDB->query($query); + while ($rec = $ilDB->fetchAssoc($set)) { + $usages[$rec["id"]] = array("type" => "news", "id" => $rec["id"]); + } + + return $usages; + } + + /** + * Context Object ID + * @deprecated will move to ilNewsData + */ + public static function _lookupContextObjId($a_news_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT * " . + "FROM il_news_item " . + "WHERE " . + " id = " . $ilDB->quote($a_news_id, "integer"); + $set = $ilDB->query($query); + $rec = $ilDB->fetchAssoc($set); + + return $rec["context_obj_id"]; + } + + /** + * @deprecated will move to settings + */ + public static function _lookupDefaultPDPeriod() + { + $news_set = new ilSetting("news"); + $per = $news_set->get("pd_period"); + if ($per == 0) { + $per = 30; + } + + return $per; + } + + /** + * @deprecated will move to settings->user + */ + public static function _lookupUserPDPeriod($a_user_id) + { + $news_set = new ilSetting("news"); + $allow_shorter_periods = $news_set->get("allow_shorter_periods"); + $allow_longer_periods = $news_set->get("allow_longer_periods"); + $default_per = ilNewsItem::_lookupDefaultPDPeriod(); + + include_once("./Services/Block/classes/class.ilBlockSetting.php"); + $per = ilBlockSetting::_lookup( + "pdnews", + "news_pd_period", + $a_user_id, + 0 + ); + + // news period information + if ($per <= 0 || + (!$allow_shorter_periods && ($per < $default_per)) || + (!$allow_longer_periods && ($per > $default_per)) + ) { + $per = $default_per; + } + + return $per; + } + + /** + * @deprecated will move to settings + */ + public static function _lookupRSSPeriod() + { + $news_set = new ilSetting("news"); + $rss_period = $news_set->get("rss_period"); + if ($rss_period == 0) { // default to two weeks + $rss_period = 14; + } + return $rss_period; + } + + /** + * @deprecated will move to settings->user + */ + public static function setPrivateFeedId($a_userId) + { + ilNewsItem::$privFeedId = $a_userId; + } + + /** + * @deprecated will move to settings->user + */ + public static function getPrivateFeedId() + { + return ilNewsItem::$privFeedId; + } + + /** + * Deliver mob file + * + * @deprecated will move to ? + * @param string $a_purpose + * @param bool $a_increase_download_cnt + * @return bool + */ + public function deliverMobFile($a_purpose = "Standard", $a_increase_download_cnt = false) + { + $mob = $this->getMobId(); + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $mob = new ilObjMediaObject($mob); + $mob_dir = ilObjMediaObject::_getDirectory($mob->getId()); + + // check purpose + if (!$mob->hasPurposeItem($a_purpose)) { + return false; + } + + $m_item = $mob->getMediaItem($a_purpose); + if ($m_item->getLocationType() != "Reference") { + $file = $mob_dir . "/" . $m_item->getLocation(); + if (file_exists($file) && is_file($file)) { + if ($a_increase_download_cnt) { + $this->increaseDownloadCounter(); + } + ilUtil::deliverFile($file, $m_item->getLocation(), "", false, false, false); + return true; + } else { + ilUtil::sendFailure("File not found!", true); + return false; + } + } else { + if ($a_increase_download_cnt) { + $this->increaseDownloadCounter(); + } + ilUtil::redirect($m_item->getLocation()); + } + } + + /** + * Increase download counter + * @deprecated will move to data + */ + public function increaseDownloadCounter() + { + $ilDB = $this->db; + + $cnt = $this->getMobDownloadCounter(); + $cnt++; + $this->setMobDownloadCounter($cnt); + $ilDB->manipulate( + "UPDATE il_news_item SET " . + " mob_cnt_download = " . $ilDB->quote($cnt, "integer") . + " WHERE id = " . $ilDB->quote($this->getId(), "integer") + ); + } + + /** + * Increase play counter + * + * @deprecated will move to data + */ + public function increasePlayCounter() + { + $ilDB = $this->db; + + $cnt = $this->getMobPlayCounter(); + $cnt++; + $this->setMobPlayCounter($cnt); + $ilDB->manipulate( + "UPDATE il_news_item SET " . + " mob_cnt_play = " . $ilDB->quote($cnt, "integer") . + " WHERE id = " . $ilDB->quote($this->getId(), "integer") + ); + } + + /** + * Prepare news data from cache + * @deprecated will move to data + * @param string $a_cres cache string + * @return array news array + */ + public static function prepareNewsDataFromCache($a_cres) + { + global $DIC; + + $ilDB = $DIC->database(); + + $data = $a_cres; + $news_ids = array_keys($data); + $set = $ilDB->query("SELECT id FROM il_news_item " . + " WHERE " . $ilDB->in("id", $news_ids, false, "integer")); + $existing_ids = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $existing_ids[] = $rec["id"]; + } + //var_dump($existing_ids); + $existing_news = array(); + foreach ($data as $k => $v) { + if (in_array($k, $existing_ids)) { + $existing_news[$k] = $v; + } + } + + //var_dump($data); + //var_dump($existing_news); + + return $existing_news; + } } -?> diff --git a/Services/News/classes/class.ilNewsItemGUI.php b/Services/News/classes/class.ilNewsItemGUI.php index 3e2c39a8eecddae80e736319a7802b1a0491d4e2..ff5f900ce98586bf606027a9958e8cb2972aabc8 100755 --- a/Services/News/classes/class.ilNewsItemGUI.php +++ b/Services/News/classes/class.ilNewsItemGUI.php @@ -19,750 +19,720 @@ define("IL_FORM_RE_CREATE", 3); */ class ilNewsItemGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - protected $enable_edit = 0; - protected $context_obj_id; - protected $context_obj_type; - protected $context_sub_obj_id; - protected $context_sub_obj_type; - protected $form_edit_mode; - - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - $this->tabs = $DIC->tabs(); - $this->user = $DIC->user(); - $this->toolbar = $DIC->toolbar(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->ctrl = $ilCtrl; - - include_once("Services/News/classes/class.ilNewsItem.php"); - if ($_GET["news_item_id"] > 0) - { - $this->news_item = new ilNewsItem($_GET["news_item_id"]); - } - - $this->ctrl->saveParameter($this, array("news_item_id")); - - // Init EnableEdit. - $this->setEnableEdit(false); - - // Init Context. - $this->setContextObjId($ilCtrl->getContextObjId()); - $this->setContextObjType($ilCtrl->getContextObjType()); - $this->setContextSubObjId($ilCtrl->getContextSubObjId()); - $this->setContextSubObjType($ilCtrl->getContextSubObjType()); - - $lng->loadLanguageModule("news"); - - $ilCtrl->saveParameter($this, "add_mode"); - } - - /** - * Get html - * - * @return string html - */ - function getHTML() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $lng->LoadLanguageModule("news"); - - return $this->getNewsForContextBlock(); - } - - /** - * Execute command. - * - */ - public function executeCommand() - { - $ilCtrl = $this->ctrl; - - // check, if news item id belongs to context - if (is_object($this->news_item) && $this->news_item->getId() > 0 - && ilNewsItem::_lookupContextObjId($this->news_item->getId()) != $this->getContextObjId()) - { - throw new ilException("News ID does not match object context."); - } - - - // get next class and command - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - switch ($next_class) - { - default: - $html = $this->$cmd(); - break; - } - - return $html; - - } - - /** - * Set EnableEdit. - * - * @param boolean $a_enable_edit Edit mode on/off - */ - public function setEnableEdit($a_enable_edit = 0) - { - $this->enable_edit = $a_enable_edit; - } - - /** - * Get EnableEdit. - * - * @return boolean Edit mode on/off - */ - public function getEnableEdit() - { - return $this->enable_edit; - } - - /** - * Set ContextObjId. - * - * @param int $a_context_obj_id - */ - public function setContextObjId($a_context_obj_id) - { - $this->context_obj_id = $a_context_obj_id; - } - - /** - * Get ContextObjId. - * - * @return int - */ - public function getContextObjId() - { - return $this->context_obj_id; - } - - /** - * Set ContextObjType. - * - * @param int $a_context_obj_type - */ - public function setContextObjType($a_context_obj_type) - { - $this->context_obj_type = $a_context_obj_type; - } - - /** - * Get ContextObjType. - * - * @return int - */ - public function getContextObjType() - { - return $this->context_obj_type; - } - - /** - * Set ContextSubObjId. - * - * @param int $a_context_sub_obj_id - */ - public function setContextSubObjId($a_context_sub_obj_id) - { - $this->context_sub_obj_id = $a_context_sub_obj_id; - } - - /** - * Get ContextSubObjId. - * - * @return int - */ - public function getContextSubObjId() - { - return $this->context_sub_obj_id; - } - - /** - * Set ContextSubObjType. - * - * @param int $a_context_sub_obj_type - */ - public function setContextSubObjType($a_context_sub_obj_type) - { - $this->context_sub_obj_type = $a_context_sub_obj_type; - } - - /** - * Get ContextSubObjType. - * - * @return int - */ - public function getContextSubObjType() - { - return $this->context_sub_obj_type; - } - - /** - * Set FormEditMode. - * - * @param int $a_form_edit_mode Form Edit Mode (IL_FORM_EDIT | IL_FORM_CREATE | IL_FORM_RE_EDIT | IL_FORM_RE_CREATE) - */ - public function setFormEditMode($a_form_edit_mode) - { - $this->form_edit_mode = $a_form_edit_mode; - } - - /** - * Get FormEditMode. - * - * @return int Form Edit Mode (IL_FORM_EDIT | IL_FORM_CREATE | IL_FORM_RE_EDIT | IL_FORM_RE_CREATE) - */ - public function getFormEditMode() - { - return $this->form_edit_mode; - } - - /** - * FORM NewsItem: Create NewsItem. - * - */ - public function createNewsItem() - { - $form = $this->initFormNewsItem(IL_FORM_CREATE); - return $form->getHtml(); - } - - /** - * FORM NewsItem: Edit form. - * - */ - public function editNewsItem() - { - $form = $this->initFormNewsItem(IL_FORM_EDIT); - $this->getValuesNewsItem($form); - return $form->getHtml(); - - } - - - /** - * FORM NewsItem: Init form. - * - * @param int $a_mode Form Edit Mode (IL_FORM_EDIT | IL_FORM_CREATE) - * @return ilPropertyFormGUI form - */ - protected function initFormNewsItem($a_mode) - { - $ilTabs = $this->tabs; - - $ilTabs->clearTargets(); - $form = self::getEditForm($a_mode, (int) $_GET["ref_id"]); - $form->setFormAction($this->ctrl->getFormAction($this)); - - return $form; - } - - /** - * FORM NewsItem: Init form. - * - * @param int $a_mode Form Edit Mode (IL_FORM_EDIT | IL_FORM_CREATE) - * @return ilPropertyFormGUI form - */ - static public function getEditForm($a_mode, $a_ref_id) - { - global $DIC; - - $lng = $DIC->language(); - - $lng->loadLanguageModule("news"); - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - - $form = new ilPropertyFormGUI(); - - // Property Title - $text_input = new ilTextInputGUI($lng->txt("news_news_item_title"), "news_title"); - $text_input->setInfo(""); - $text_input->setRequired(true); - $text_input->setMaxLength(200); - $form->addItem($text_input); - - // Property Content - $text_area = new ilTextAreaInputGUI($lng->txt("news_news_item_content"), "news_content"); - $text_area->setInfo(""); - $text_area->setRequired(false); - $text_area->setRows("4"); - $text_area->setUseRte(true); - $form->addItem($text_area); - - // Property Visibility - $radio_group = new ilRadioGroupInputGUI($lng->txt("news_news_item_visibility"), "news_visibility"); - $radio_option = new ilRadioOption($lng->txt("news_visibility_users"), "users"); - $radio_group->addOption($radio_option); - $radio_option = new ilRadioOption($lng->txt("news_visibility_public"), "public"); - $radio_group->addOption($radio_option); - $radio_group->setInfo($lng->txt("news_news_item_visibility_info")); - $radio_group->setRequired(false); - $radio_group->setValue("users"); - $form->addItem($radio_group); - - // media - $media = new ilFileInputGUI($lng->txt('news_media'), 'media'); - $media->setSuffixes(array("jpeg", "jpg", "png", "gif", "mp4", "mp3")); - $media->setRequired(false); - $media->setALlowDeletion(true); - $media->setValue(" "); - $form->addItem($media); - - // Property ContentLong - /* - $text_area = new ilTextAreaInputGUI($lng->txt("news_news_item_content_long"), "news_content_long"); - $text_area->setInfo($lng->txt("news_news_item_content_long_info")); - $text_area->setRequired(false); - $text_area->setCols("40"); - $text_area->setRows("8"); - $text_area->setUseRte(true); - $form->addItem($text_area);*/ - - - // save and cancel commands - if (in_array($a_mode, array(IL_FORM_CREATE,IL_FORM_RE_CREATE))) - { - $form->addCommandButton("saveNewsItem", $lng->txt("save"), "news_btn_create"); - $form->addCommandButton("cancelSaveNewsItem", $lng->txt("cancel"), "news_btn_cancel_create"); - } - else - { - $form->addCommandButton("updateNewsItem", $lng->txt("save"), "news_btn_update"); - $form->addCommandButton("cancelUpdateNewsItem", $lng->txt("cancel"), "news_btn_cancel_update"); - } - - $form->setTitle($lng->txt("news_news_item_head")); - - $news_set = new ilSetting("news"); - if (!$news_set->get("enable_rss_for_internal")) - { - $form->removeItemByPostVar("news_visibility"); - } - else - { - $nv = $form->getItemByPostVar("news_visibility"); - if (is_object($nv)) - { - $nv->setValue(ilNewsItem::_getDefaultVisibilityForRefId($a_ref_id)); - } - } - - return $form; - } - - /** - * FORM NewsItem: Get current values for NewsItem form. - * - */ - public function getValuesNewsItem($a_form) - { - $values = array(); - - $values["news_title"] = $this->news_item->getTitle(); - $values["news_content"] = $this->news_item->getContent().$this->news_item->getContentLong(); - $values["news_visibility"] = $this->news_item->getVisibility(); - //$values["news_content_long"] = $this->news_item->getContentLong(); - $values["news_content_long"] = ""; - - $a_form->setValuesByArray($values); - - } - - /** - * FORM NewsItem: Save NewsItem. - * - */ - function saveNewsItem() - { - $ilUser = $this->user; - - if (!$this->getEnableEdit()) - { - return; - } - - $form = $this->initFormNewsItem(IL_FORM_CREATE); - if ($form->checkInput()) - { - $this->news_item = new ilNewsItem(); - $this->news_item->setTitle($form->getInput("news_title")); - $this->news_item->setContent($form->getInput("news_content")); - $this->news_item->setVisibility($form->getInput("news_visibility")); - -// $data = $form->getInput('media'); -// var_dump($data); - - - - $this->news_item->setContentLong(""); - if (self::isRteActivated()) - { - $this->news_item->setContentHtml(true); - } - //$this->news_item->setContentLong($form->getInput("news_content_long")); - -// changed - //$this->news_item->setContextObjId($this->ctrl->getContextObjId()); - //$this->news_item->setContextObjType($this->ctrl->getContextObjType()); - $this->news_item->setContextObjId($this->getContextObjId()); - $this->news_item->setContextObjType($this->getContextObjType()); - $this->news_item->setContextSubObjId($this->getContextSubObjId()); - $this->news_item->setContextSubObjType($this->getContextSubObjType()); - $this->news_item->setUserId($ilUser->getId()); - - $news_set = new ilSetting("news"); - if (!$news_set->get("enable_rss_for_internal")) - { - $this->news_item->setVisibility("users"); - } - - $this->news_item->create(); - $this->exitSaveNewsItem(); - } - else - { - $form->setValuesByPost(); - return $form->getHtml(); - } - - } - - function exitSaveNewsItem() - { - $ilCtrl = $this->ctrl; - - if ($_GET["add_mode"] == "block") - { - $ilCtrl->returnToParent($this); - } - else - { - $ilCtrl->redirect($this, "editNews"); - } - } - - /** - * FORM NewsItem: Save NewsItem. - * - */ - function updateNewsItem() - { - $ilUser = $this->user; - - if (!$this->getEnableEdit()) - { - return ""; - } - - $form = $this->initFormNewsItem(IL_FORM_EDIT); - if ($form->checkInput()) - { - $this->news_item->setUpdateUserId($ilUser->getId()); - $this->news_item->setTitle($form->getInput("news_title")); - $this->news_item->setContent($form->getInput("news_content")); - $this->news_item->setVisibility($form->getInput("news_visibility")); - //$this->news_item->setContentLong($form->getInput("news_content_long")); - $this->news_item->setContentLong(""); - if (self::isRteActivated()) - { - $this->news_item->setContentHtml(true); - } - $this->news_item->update(); - $this->exitUpdateNewsItem(); - } - else - { - $form->setValuesByPost(); - return $form->getHtml(); - } - } - - function exitUpdateNewsItem() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirect($this, "editNews"); - } - - /** - * FORM NewsItem: Save NewsItem. - * - */ - function cancelUpdateNewsItem() - { - return $this->editNews(); - } - - /** - * FORM NewsItem: Save NewsItem. - * - */ - function cancelSaveNewsItem() - { - $ilCtrl = $this->ctrl; - - if ($_GET["add_mode"] == "block") - { - $ilCtrl->returnToParent($this); - } - else - { - return $this->editNews(); - } - } - - /** - * Edit news - * - * @return html - */ - function editNews() - { - $ilTabs = $this->tabs; - $ilToolbar = $this->toolbar; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->setTabs(); - - $ilToolbar->addButton($lng->txt("news_add_news"), - $ilCtrl->getLinkTarget($this, "createNewsItem")); - - if (!$this->getEnableEdit()) - { - return; - } - return $this->getNewsForContextTable(); - } - - /** - * Cancel update - */ - function cancelUpdate() - { - return $this->editNews(); - } - - /** - * Confirmation Screen. - */ - function confirmDeletionNewsItems() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilTabs = $this->tabs; - - if (!$this->getEnableEdit()) - { - return; - } - - // check whether at least one item is selected - if (count($_POST["news_id"]) == 0) - { - ilUtil::sendFailure($lng->txt("no_checkbox")); - return $this->editNews(); - } - - $ilTabs->clearTargets(); - - include_once("Services/Utilities/classes/class.ilConfirmationGUI.php"); - $c_gui = new ilConfirmationGUI(); - - // set confirm/cancel commands - $c_gui->setFormAction($ilCtrl->getFormAction($this, "deleteNewsItems")); - $c_gui->setHeaderText($lng->txt("info_delete_sure")); - $c_gui->setCancel($lng->txt("cancel"), "editNews"); - $c_gui->setConfirm($lng->txt("confirm"), "deleteNewsItems"); - - // add items to delete - foreach($_POST["news_id"] as $news_id) - { - $news = new ilNewsItem($news_id); - $c_gui->addItem("news_id[]", $news_id, $news->getTitle()); - } - - return $c_gui->getHTML(); - } - - /** - * Delete news items. - */ - function deleteNewsItems() - { - if (!$this->getEnableEdit()) - { - return; - } - // delete all selected news items - foreach($_POST["news_id"] as $news_id) - { - $news = new ilNewsItem($news_id); - $news->delete(); - } - - return $this->editNews(); - } - - /** - * BLOCK NewsForContext: Get block HTML. - * - */ - public function getNewsForContextBlock() - { - $lng = $this->lng; - - include_once("Services/News/classes/class.ilNewsForContextBlockGUI.php"); - $block_gui = new ilNewsForContextBlockGUI(get_class($this)); - - $block_gui->setParentClass("ilinfoscreengui"); - $block_gui->setParentCmd("showSummary"); - $block_gui->setEnableEdit($this->getEnableEdit()); - - - $news_item = new ilNewsItem(); - -// changed - //$news_item->setContextObjId($this->ctrl->getContextObjId()); - //$news_item->setContextObjType($this->ctrl->getContextObjType()); - $news_item->setContextObjId($this->getContextObjId()); - $news_item->setContextObjType($this->getContextObjType()); - $news_item->setContextSubObjId($this->getContextSubObjId()); - $news_item->setContextSubObjType($this->getContextSubObjType()); - - $data = $news_item->queryNewsForContext(); - - $block_gui->setTitle($lng->txt("news_block_news_for_context")); - $block_gui->setRowTemplate("tpl.block_row_news_for_context.html", "Services/News"); - $block_gui->setData($data); - - return $block_gui->getHTML(); - - } - - - /** - * TABLE NewsForContext: Get table HTML. - * - */ - public function getNewsForContextTable() - { - $lng = $this->lng; - - $news_item = new ilNewsItem(); - $news_item->setContextObjId($this->getContextObjId()); - $news_item->setContextObjType($this->getContextObjType()); - $news_item->setContextSubObjId($this->getContextSubObjId()); - $news_item->setContextSubObjType($this->getContextSubObjType()); - - $perm_ref_id = 0; - if (in_array($this->getContextObjType(), array("cat", "grp", "crs", "root"))) - { - $data = $news_item->getNewsForRefId($_GET["ref_id"], false, false, - 0, true, false, true, true); - } - else - { - $perm_ref_id = $_GET["ref_id"]; - if ($this->getContextSubObjId() > 0) - { - $data = $news_item->queryNewsForContext(false, 0, - "", true, true); - } - else - { - $data = $news_item->queryNewsForContext(); - } - } - - include_once("Services/News/classes/class.ilNewsForContextTableGUI.php"); - $table_gui = new ilNewsForContextTableGUI($this, "getNewsForContextTable", $perm_ref_id); - - $table_gui->setTitle($lng->txt("news_table_news_for_context")); - $table_gui->setRowTemplate("tpl.table_row_news_for_context.html", "Services/News"); - $table_gui->setData($data); - - $table_gui->setDefaultOrderField("creation_date"); - $table_gui->setDefaultOrderDirection("desc"); - $table_gui->addMultiCommand("confirmDeletionNewsItems", $lng->txt("delete")); - $table_gui->setTitle($lng->txt("news")); - $table_gui->setSelectAllCheckbox("news_id"); - - - return $table_gui->getHTML(); - - } - - /** - * Set tabs - * - * @param - * @return - */ - function setTabs() - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getParentReturn($this)); - } - - /** - * Is Rte activated - * - * @return bool - */ - static function isRteActivated() - { - include_once("./Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php"); - if (ilObjAdvancedEditing::_getRichTextEditor() == "") - { - return false; - } - return true; - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + protected $enable_edit = 0; + protected $context_obj_id; + protected $context_obj_type; + protected $context_sub_obj_id; + protected $context_sub_obj_type; + protected $form_edit_mode; + + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + $this->tabs = $DIC->tabs(); + $this->user = $DIC->user(); + $this->toolbar = $DIC->toolbar(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->ctrl = $ilCtrl; + + include_once("Services/News/classes/class.ilNewsItem.php"); + if ($_GET["news_item_id"] > 0) { + $this->news_item = new ilNewsItem($_GET["news_item_id"]); + } + + $this->ctrl->saveParameter($this, array("news_item_id")); + + // Init EnableEdit. + $this->setEnableEdit(false); + + // Init Context. + $this->setContextObjId($ilCtrl->getContextObjId()); + $this->setContextObjType($ilCtrl->getContextObjType()); + $this->setContextSubObjId($ilCtrl->getContextSubObjId()); + $this->setContextSubObjType($ilCtrl->getContextSubObjType()); + + $lng->loadLanguageModule("news"); + + $ilCtrl->saveParameter($this, "add_mode"); + } + + /** + * Get html + * + * @return string html + */ + public function getHTML() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $lng->LoadLanguageModule("news"); + + return $this->getNewsForContextBlock(); + } + + /** + * Execute command. + * + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + // check, if news item id belongs to context + if (is_object($this->news_item) && $this->news_item->getId() > 0 + && ilNewsItem::_lookupContextObjId($this->news_item->getId()) != $this->getContextObjId()) { + throw new ilException("News ID does not match object context."); + } + + + // get next class and command + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + switch ($next_class) { + default: + $html = $this->$cmd(); + break; + } + + return $html; + } + + /** + * Set EnableEdit. + * + * @param boolean $a_enable_edit Edit mode on/off + */ + public function setEnableEdit($a_enable_edit = 0) + { + $this->enable_edit = $a_enable_edit; + } + + /** + * Get EnableEdit. + * + * @return boolean Edit mode on/off + */ + public function getEnableEdit() + { + return $this->enable_edit; + } + + /** + * Set ContextObjId. + * + * @param int $a_context_obj_id + */ + public function setContextObjId($a_context_obj_id) + { + $this->context_obj_id = $a_context_obj_id; + } + + /** + * Get ContextObjId. + * + * @return int + */ + public function getContextObjId() + { + return $this->context_obj_id; + } + + /** + * Set ContextObjType. + * + * @param int $a_context_obj_type + */ + public function setContextObjType($a_context_obj_type) + { + $this->context_obj_type = $a_context_obj_type; + } + + /** + * Get ContextObjType. + * + * @return int + */ + public function getContextObjType() + { + return $this->context_obj_type; + } + + /** + * Set ContextSubObjId. + * + * @param int $a_context_sub_obj_id + */ + public function setContextSubObjId($a_context_sub_obj_id) + { + $this->context_sub_obj_id = $a_context_sub_obj_id; + } + + /** + * Get ContextSubObjId. + * + * @return int + */ + public function getContextSubObjId() + { + return $this->context_sub_obj_id; + } + + /** + * Set ContextSubObjType. + * + * @param int $a_context_sub_obj_type + */ + public function setContextSubObjType($a_context_sub_obj_type) + { + $this->context_sub_obj_type = $a_context_sub_obj_type; + } + + /** + * Get ContextSubObjType. + * + * @return int + */ + public function getContextSubObjType() + { + return $this->context_sub_obj_type; + } + + /** + * Set FormEditMode. + * + * @param int $a_form_edit_mode Form Edit Mode (IL_FORM_EDIT | IL_FORM_CREATE | IL_FORM_RE_EDIT | IL_FORM_RE_CREATE) + */ + public function setFormEditMode($a_form_edit_mode) + { + $this->form_edit_mode = $a_form_edit_mode; + } + + /** + * Get FormEditMode. + * + * @return int Form Edit Mode (IL_FORM_EDIT | IL_FORM_CREATE | IL_FORM_RE_EDIT | IL_FORM_RE_CREATE) + */ + public function getFormEditMode() + { + return $this->form_edit_mode; + } + + /** + * FORM NewsItem: Create NewsItem. + * + */ + public function createNewsItem() + { + $form = $this->initFormNewsItem(IL_FORM_CREATE); + return $form->getHtml(); + } + + /** + * FORM NewsItem: Edit form. + * + */ + public function editNewsItem() + { + $form = $this->initFormNewsItem(IL_FORM_EDIT); + $this->getValuesNewsItem($form); + return $form->getHtml(); + } + + + /** + * FORM NewsItem: Init form. + * + * @param int $a_mode Form Edit Mode (IL_FORM_EDIT | IL_FORM_CREATE) + * @return ilPropertyFormGUI form + */ + protected function initFormNewsItem($a_mode) + { + $ilTabs = $this->tabs; + + $ilTabs->clearTargets(); + $form = self::getEditForm($a_mode, (int) $_GET["ref_id"]); + $form->setFormAction($this->ctrl->getFormAction($this)); + + return $form; + } + + /** + * FORM NewsItem: Init form. + * + * @param int $a_mode Form Edit Mode (IL_FORM_EDIT | IL_FORM_CREATE) + * @return ilPropertyFormGUI form + */ + public static function getEditForm($a_mode, $a_ref_id) + { + global $DIC; + + $lng = $DIC->language(); + + $lng->loadLanguageModule("news"); + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + + $form = new ilPropertyFormGUI(); + + // Property Title + $text_input = new ilTextInputGUI($lng->txt("news_news_item_title"), "news_title"); + $text_input->setInfo(""); + $text_input->setRequired(true); + $text_input->setMaxLength(200); + $form->addItem($text_input); + + // Property Content + $text_area = new ilTextAreaInputGUI($lng->txt("news_news_item_content"), "news_content"); + $text_area->setInfo(""); + $text_area->setRequired(false); + $text_area->setRows("4"); + $text_area->setUseRte(true); + $form->addItem($text_area); + + // Property Visibility + $radio_group = new ilRadioGroupInputGUI($lng->txt("news_news_item_visibility"), "news_visibility"); + $radio_option = new ilRadioOption($lng->txt("news_visibility_users"), "users"); + $radio_group->addOption($radio_option); + $radio_option = new ilRadioOption($lng->txt("news_visibility_public"), "public"); + $radio_group->addOption($radio_option); + $radio_group->setInfo($lng->txt("news_news_item_visibility_info")); + $radio_group->setRequired(false); + $radio_group->setValue("users"); + $form->addItem($radio_group); + + // media + $media = new ilFileInputGUI($lng->txt('news_media'), 'media'); + $media->setSuffixes(array("jpeg", "jpg", "png", "gif", "mp4", "mp3")); + $media->setRequired(false); + $media->setALlowDeletion(true); + $media->setValue(" "); + $form->addItem($media); + + // Property ContentLong + /* + $text_area = new ilTextAreaInputGUI($lng->txt("news_news_item_content_long"), "news_content_long"); + $text_area->setInfo($lng->txt("news_news_item_content_long_info")); + $text_area->setRequired(false); + $text_area->setCols("40"); + $text_area->setRows("8"); + $text_area->setUseRte(true); + $form->addItem($text_area);*/ + + + // save and cancel commands + if (in_array($a_mode, array(IL_FORM_CREATE,IL_FORM_RE_CREATE))) { + $form->addCommandButton("saveNewsItem", $lng->txt("save"), "news_btn_create"); + $form->addCommandButton("cancelSaveNewsItem", $lng->txt("cancel"), "news_btn_cancel_create"); + } else { + $form->addCommandButton("updateNewsItem", $lng->txt("save"), "news_btn_update"); + $form->addCommandButton("cancelUpdateNewsItem", $lng->txt("cancel"), "news_btn_cancel_update"); + } + + $form->setTitle($lng->txt("news_news_item_head")); + + $news_set = new ilSetting("news"); + if (!$news_set->get("enable_rss_for_internal")) { + $form->removeItemByPostVar("news_visibility"); + } else { + $nv = $form->getItemByPostVar("news_visibility"); + if (is_object($nv)) { + $nv->setValue(ilNewsItem::_getDefaultVisibilityForRefId($a_ref_id)); + } + } + + return $form; + } + + /** + * FORM NewsItem: Get current values for NewsItem form. + * + */ + public function getValuesNewsItem($a_form) + { + $values = array(); + + $values["news_title"] = $this->news_item->getTitle(); + $values["news_content"] = $this->news_item->getContent() . $this->news_item->getContentLong(); + $values["news_visibility"] = $this->news_item->getVisibility(); + //$values["news_content_long"] = $this->news_item->getContentLong(); + $values["news_content_long"] = ""; + + $a_form->setValuesByArray($values); + } + + /** + * FORM NewsItem: Save NewsItem. + * + */ + public function saveNewsItem() + { + $ilUser = $this->user; + + if (!$this->getEnableEdit()) { + return; + } + + $form = $this->initFormNewsItem(IL_FORM_CREATE); + if ($form->checkInput()) { + $this->news_item = new ilNewsItem(); + $this->news_item->setTitle($form->getInput("news_title")); + $this->news_item->setContent($form->getInput("news_content")); + $this->news_item->setVisibility($form->getInput("news_visibility")); + + // $data = $form->getInput('media'); + // var_dump($data); + + + + $this->news_item->setContentLong(""); + if (self::isRteActivated()) { + $this->news_item->setContentHtml(true); + } + //$this->news_item->setContentLong($form->getInput("news_content_long")); + + // changed + //$this->news_item->setContextObjId($this->ctrl->getContextObjId()); + //$this->news_item->setContextObjType($this->ctrl->getContextObjType()); + $this->news_item->setContextObjId($this->getContextObjId()); + $this->news_item->setContextObjType($this->getContextObjType()); + $this->news_item->setContextSubObjId($this->getContextSubObjId()); + $this->news_item->setContextSubObjType($this->getContextSubObjType()); + $this->news_item->setUserId($ilUser->getId()); + + $news_set = new ilSetting("news"); + if (!$news_set->get("enable_rss_for_internal")) { + $this->news_item->setVisibility("users"); + } + + $this->news_item->create(); + $this->exitSaveNewsItem(); + } else { + $form->setValuesByPost(); + return $form->getHtml(); + } + } + + public function exitSaveNewsItem() + { + $ilCtrl = $this->ctrl; + + if ($_GET["add_mode"] == "block") { + $ilCtrl->returnToParent($this); + } else { + $ilCtrl->redirect($this, "editNews"); + } + } + + /** + * FORM NewsItem: Save NewsItem. + * + */ + public function updateNewsItem() + { + $ilUser = $this->user; + + if (!$this->getEnableEdit()) { + return ""; + } + + $form = $this->initFormNewsItem(IL_FORM_EDIT); + if ($form->checkInput()) { + $this->news_item->setUpdateUserId($ilUser->getId()); + $this->news_item->setTitle($form->getInput("news_title")); + $this->news_item->setContent($form->getInput("news_content")); + $this->news_item->setVisibility($form->getInput("news_visibility")); + //$this->news_item->setContentLong($form->getInput("news_content_long")); + $this->news_item->setContentLong(""); + if (self::isRteActivated()) { + $this->news_item->setContentHtml(true); + } + $this->news_item->update(); + $this->exitUpdateNewsItem(); + } else { + $form->setValuesByPost(); + return $form->getHtml(); + } + } + + public function exitUpdateNewsItem() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirect($this, "editNews"); + } + + /** + * FORM NewsItem: Save NewsItem. + * + */ + public function cancelUpdateNewsItem() + { + return $this->editNews(); + } + + /** + * FORM NewsItem: Save NewsItem. + * + */ + public function cancelSaveNewsItem() + { + $ilCtrl = $this->ctrl; + + if ($_GET["add_mode"] == "block") { + $ilCtrl->returnToParent($this); + } else { + return $this->editNews(); + } + } + + /** + * Edit news + * + * @return html + */ + public function editNews() + { + $ilTabs = $this->tabs; + $ilToolbar = $this->toolbar; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $this->setTabs(); + + $ilToolbar->addButton( + $lng->txt("news_add_news"), + $ilCtrl->getLinkTarget($this, "createNewsItem") + ); + + if (!$this->getEnableEdit()) { + return; + } + return $this->getNewsForContextTable(); + } + + /** + * Cancel update + */ + public function cancelUpdate() + { + return $this->editNews(); + } + + /** + * Confirmation Screen. + */ + public function confirmDeletionNewsItems() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilTabs = $this->tabs; + + if (!$this->getEnableEdit()) { + return; + } + + // check whether at least one item is selected + if (count($_POST["news_id"]) == 0) { + ilUtil::sendFailure($lng->txt("no_checkbox")); + return $this->editNews(); + } + + $ilTabs->clearTargets(); + + include_once("Services/Utilities/classes/class.ilConfirmationGUI.php"); + $c_gui = new ilConfirmationGUI(); + + // set confirm/cancel commands + $c_gui->setFormAction($ilCtrl->getFormAction($this, "deleteNewsItems")); + $c_gui->setHeaderText($lng->txt("info_delete_sure")); + $c_gui->setCancel($lng->txt("cancel"), "editNews"); + $c_gui->setConfirm($lng->txt("confirm"), "deleteNewsItems"); + + // add items to delete + foreach ($_POST["news_id"] as $news_id) { + $news = new ilNewsItem($news_id); + $c_gui->addItem("news_id[]", $news_id, $news->getTitle()); + } + + return $c_gui->getHTML(); + } + + /** + * Delete news items. + */ + public function deleteNewsItems() + { + if (!$this->getEnableEdit()) { + return; + } + // delete all selected news items + foreach ($_POST["news_id"] as $news_id) { + $news = new ilNewsItem($news_id); + $news->delete(); + } + + return $this->editNews(); + } + + /** + * BLOCK NewsForContext: Get block HTML. + * + */ + public function getNewsForContextBlock() + { + $lng = $this->lng; + + include_once("Services/News/classes/class.ilNewsForContextBlockGUI.php"); + $block_gui = new ilNewsForContextBlockGUI(get_class($this)); + + $block_gui->setParentClass("ilinfoscreengui"); + $block_gui->setParentCmd("showSummary"); + $block_gui->setEnableEdit($this->getEnableEdit()); + + + $news_item = new ilNewsItem(); + + // changed + //$news_item->setContextObjId($this->ctrl->getContextObjId()); + //$news_item->setContextObjType($this->ctrl->getContextObjType()); + $news_item->setContextObjId($this->getContextObjId()); + $news_item->setContextObjType($this->getContextObjType()); + $news_item->setContextSubObjId($this->getContextSubObjId()); + $news_item->setContextSubObjType($this->getContextSubObjType()); + + $data = $news_item->queryNewsForContext(); + + $block_gui->setTitle($lng->txt("news_block_news_for_context")); + $block_gui->setRowTemplate("tpl.block_row_news_for_context.html", "Services/News"); + $block_gui->setData($data); + + return $block_gui->getHTML(); + } + + + /** + * TABLE NewsForContext: Get table HTML. + * + */ + public function getNewsForContextTable() + { + $lng = $this->lng; + + $news_item = new ilNewsItem(); + $news_item->setContextObjId($this->getContextObjId()); + $news_item->setContextObjType($this->getContextObjType()); + $news_item->setContextSubObjId($this->getContextSubObjId()); + $news_item->setContextSubObjType($this->getContextSubObjType()); + + $perm_ref_id = 0; + if (in_array($this->getContextObjType(), array("cat", "grp", "crs", "root"))) { + $data = $news_item->getNewsForRefId( + $_GET["ref_id"], + false, + false, + 0, + true, + false, + true, + true + ); + } else { + $perm_ref_id = $_GET["ref_id"]; + if ($this->getContextSubObjId() > 0) { + $data = $news_item->queryNewsForContext( + false, + 0, + "", + true, + true + ); + } else { + $data = $news_item->queryNewsForContext(); + } + } + + include_once("Services/News/classes/class.ilNewsForContextTableGUI.php"); + $table_gui = new ilNewsForContextTableGUI($this, "getNewsForContextTable", $perm_ref_id); + + $table_gui->setTitle($lng->txt("news_table_news_for_context")); + $table_gui->setRowTemplate("tpl.table_row_news_for_context.html", "Services/News"); + $table_gui->setData($data); + + $table_gui->setDefaultOrderField("creation_date"); + $table_gui->setDefaultOrderDirection("desc"); + $table_gui->addMultiCommand("confirmDeletionNewsItems", $lng->txt("delete")); + $table_gui->setTitle($lng->txt("news")); + $table_gui->setSelectAllCheckbox("news_id"); + + + return $table_gui->getHTML(); + } + + /** + * Set tabs + * + * @param + * @return + */ + public function setTabs() + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getParentReturn($this) + ); + } + + /** + * Is Rte activated + * + * @return bool + */ + public static function isRteActivated() + { + include_once("./Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php"); + if (ilObjAdvancedEditing::_getRichTextEditor() == "") { + return false; + } + return true; + } } diff --git a/Services/News/classes/class.ilNewsObjectAdapter.php b/Services/News/classes/class.ilNewsObjectAdapter.php index 55bc7da6e2e0fe9ca3af916ba2b8143af529a11c..02018a8aff2f28fc65d836ec322c5d0403432c11 100644 --- a/Services/News/classes/class.ilNewsObjectAdapter.php +++ b/Services/News/classes/class.ilNewsObjectAdapter.php @@ -10,35 +10,32 @@ */ class ilNewsObjectAdapter implements ilNewsObjectAdapterInterface { - /** - * Constructor - */ - public function __construct() - { + /** + * Constructor + */ + public function __construct() + { + } - } + /** + * Get object id for reference id + * + * @param int $a_ref_id + * @return int + */ + public function getObjIdForRefId($a_ref_id) + { + return ilObject::_lookupObjId($a_ref_id); + } - /** - * Get object id for reference id - * - * @param int $a_ref_id - * @return int - */ - public function getObjIdForRefId($a_ref_id) - { - return ilObject::_lookupObjId($a_ref_id); - } - - /** - * Get object type for object id - * - * @param int $a_obj_id - * @return int - */ - public function getTypeForObjId($a_obj_id) - { - return ilObject::_lookupType($a_obj_id); - } - - -} \ No newline at end of file + /** + * Get object type for object id + * + * @param int $a_obj_id + * @return int + */ + public function getTypeForObjId($a_obj_id) + { + return ilObject::_lookupType($a_obj_id); + } +} diff --git a/Services/News/classes/class.ilNewsRendererFactory.php b/Services/News/classes/class.ilNewsRendererFactory.php index 7952925bd251250e0ca950a85d9c126fbf8ba42d..ecdd0cf74d605554cdcb2ddcf0d458d6eb8fd130 100644 --- a/Services/News/classes/class.ilNewsRendererFactory.php +++ b/Services/News/classes/class.ilNewsRendererFactory.php @@ -11,45 +11,39 @@ */ class ilNewsRendererFactory { - /** - * @var array of ilNewsRendererGUIs - */ - static protected $renderer = array(); - - /** - * Get renderer - * - * @param - * @return ilNewsRendererGUI - */ - static function getRenderer($a_context_obj_type) - { - global $DIC; - - if (!isset(self::$renderer[$a_context_obj_type])) - { - $obj_def = $DIC["objDefinition"]; - - $comp = $obj_def->getComponentForType($a_context_obj_type); - $class = $obj_def->getClassName($a_context_obj_type); - - $class = "il" . $class . "NewsRendererGUI"; - $type_renderer_path = "./" . $comp . "/classes/class." . $class . ".php"; - if (is_file($type_renderer_path)) - { - include_once($type_renderer_path); - $rend = new $class(); - } - else - { - include_once("./Services/News/classes/class.ilNewsDefaultRendererGUI.php"); - $rend = new ilNewsDefaultRendererGUI(); - } - self::$renderer[$a_context_obj_type] = $rend; - } - - return self::$renderer[$a_context_obj_type]; - } + /** + * @var array of ilNewsRendererGUIs + */ + protected static $renderer = array(); + + /** + * Get renderer + * + * @param + * @return ilNewsRendererGUI + */ + public static function getRenderer($a_context_obj_type) + { + global $DIC; + + if (!isset(self::$renderer[$a_context_obj_type])) { + $obj_def = $DIC["objDefinition"]; + + $comp = $obj_def->getComponentForType($a_context_obj_type); + $class = $obj_def->getClassName($a_context_obj_type); + + $class = "il" . $class . "NewsRendererGUI"; + $type_renderer_path = "./" . $comp . "/classes/class." . $class . ".php"; + if (is_file($type_renderer_path)) { + include_once($type_renderer_path); + $rend = new $class(); + } else { + include_once("./Services/News/classes/class.ilNewsDefaultRendererGUI.php"); + $rend = new ilNewsDefaultRendererGUI(); + } + self::$renderer[$a_context_obj_type] = $rend; + } + + return self::$renderer[$a_context_obj_type]; + } } - -?> \ No newline at end of file diff --git a/Services/News/classes/class.ilNewsService.php b/Services/News/classes/class.ilNewsService.php index d71e400df37bb45a57e4ee25630dc80139a5da60..e840d25bfccad86c2d404a4f5016bc4ad46f0009 100644 --- a/Services/News/classes/class.ilNewsService.php +++ b/Services/News/classes/class.ilNewsService.php @@ -10,60 +10,58 @@ */ class ilNewsService { - /** - * @var ilNewsServiceDependencies - */ - protected $_deps; + /** + * @var ilNewsServiceDependencies + */ + protected $_deps; - /** - * Constructor - * @param ilLanguage $lng - */ - public function __construct(ilLanguage $lng, ilSetting $settings, ilObjUser $user, ilNewsObjectAdapterInterface $obj_adapter = null) - { - if (is_null($obj_adapter)) - { - $obj_adapter = new ilNewsObjectAdapter(); - } - $this->_deps = new ilNewsServiceDependencies($lng, $settings, $user, $obj_adapter); - } + /** + * Constructor + * @param ilLanguage $lng + */ + public function __construct(ilLanguage $lng, ilSetting $settings, ilObjUser $user, ilNewsObjectAdapterInterface $obj_adapter = null) + { + if (is_null($obj_adapter)) { + $obj_adapter = new ilNewsObjectAdapter(); + } + $this->_deps = new ilNewsServiceDependencies($lng, $settings, $user, $obj_adapter); + } - /** - * @inheritdoc - */ - public function data(): ilNewsData - { - return new ilNewsData($this, $this->_deps); - } + /** + * @inheritdoc + */ + public function data() : ilNewsData + { + return new ilNewsData($this, $this->_deps); + } - /** - * Get a new news item for a context - * - * @param ilNewsContext $context - * @return ilNewsItem - */ - public function item(ilNewsContext $context): ilNewsItem - { - $news = new ilNewsItem(); - $news->setContext($context->getObjId(), $context->getObjType(), $context->getSubId(), $context->getSubType()); - $news->setPriority(NEWS_NOTICE); - $news->setUserId($this->_deps->user()->getId()); - return $news; - } + /** + * Get a new news item for a context + * + * @param ilNewsContext $context + * @return ilNewsItem + */ + public function item(ilNewsContext $context) : ilNewsItem + { + $news = new ilNewsItem(); + $news->setContext($context->getObjId(), $context->getObjType(), $context->getSubId(), $context->getSubType()); + $news->setPriority(NEWS_NOTICE); + $news->setUserId($this->_deps->user()->getId()); + return $news; + } - /** - * Get context object for news - * - * @param int $ref_id - * @param string $subtype - * @param int $subid - * @return ilNewsContext - */ - public function contextForRefId(int $ref_id, int $subid = 0, string $subtype = ""): ilNewsContext - { - $obj_id = $this->_deps->obj()->getObjIdForRefId($ref_id); - $obj_type = $this->_deps->obj()->getTypeForObjId($obj_id); - return new ilNewsContext($obj_id, $obj_type, $subid, $subtype); - } - -} \ No newline at end of file + /** + * Get context object for news + * + * @param int $ref_id + * @param string $subtype + * @param int $subid + * @return ilNewsContext + */ + public function contextForRefId(int $ref_id, int $subid = 0, string $subtype = "") : ilNewsContext + { + $obj_id = $this->_deps->obj()->getObjIdForRefId($ref_id); + $obj_type = $this->_deps->obj()->getTypeForObjId($obj_id); + return new ilNewsContext($obj_id, $obj_type, $subid, $subtype); + } +} diff --git a/Services/News/classes/class.ilNewsServiceDependencies.php b/Services/News/classes/class.ilNewsServiceDependencies.php index d1f3601baaab004febd79da95e95406fdf30bdc1..d6c5ac37830afd18d3a90b8f746f37edc17bf303 100644 --- a/Services/News/classes/class.ilNewsServiceDependencies.php +++ b/Services/News/classes/class.ilNewsServiceDependencies.php @@ -10,78 +10,76 @@ */ class ilNewsServiceDependencies { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilSetting - */ - protected $settings; + /** + * @var ilSetting + */ + protected $settings; - /** - * @var ilNewsObjectAdapterInterface - */ - protected $obj_adapter; + /** + * @var ilNewsObjectAdapterInterface + */ + protected $obj_adapter; - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - /** - * Constructor - * @param ilLanguage $lng - */ - public function __construct(ilLanguage $lng, ilSetting $settings, ilObjUser $user, ilNewsObjectAdapterInterface $obj_adapter) - { - $this->lng = $lng; - $this->settings = $settings; - $this->user = $user; - $this->obj_adapter = $obj_adapter; - } + /** + * Constructor + * @param ilLanguage $lng + */ + public function __construct(ilLanguage $lng, ilSetting $settings, ilObjUser $user, ilNewsObjectAdapterInterface $obj_adapter) + { + $this->lng = $lng; + $this->settings = $settings; + $this->user = $user; + $this->obj_adapter = $obj_adapter; + } - /** - * Get object adapter - * - * @return ilNewsObjectAdapterInterface - */ - public function obj() - { - return $this->obj_adapter; - } + /** + * Get object adapter + * + * @return ilNewsObjectAdapterInterface + */ + public function obj() + { + return $this->obj_adapter; + } - /** - * Get language object - * - * @return ilLanguage - */ - public function language(): ilLanguage - { - return $this->lng; - } + /** + * Get language object + * + * @return ilLanguage + */ + public function language() : ilLanguage + { + return $this->lng; + } - /** - * Get settings object - * - * @return ilSetting - */ - public function settings(): ilSetting - { - return $this->settings; - } + /** + * Get settings object + * + * @return ilSetting + */ + public function settings() : ilSetting + { + return $this->settings; + } - /** - * Get current user - * - * @return ilObjUser - */ - public function user(): ilObjUser - { - return $this->user; - } - - -} \ No newline at end of file + /** + * Get current user + * + * @return ilObjUser + */ + public function user() : ilObjUser + { + return $this->user; + } +} diff --git a/Services/News/classes/class.ilNewsSubscription.php b/Services/News/classes/class.ilNewsSubscription.php index dfc0708d1c63b155fa1d838357722f4c4bc64142..864eebc08232698590139fa6de3445f89c571667 100755 --- a/Services/News/classes/class.ilNewsSubscription.php +++ b/Services/News/classes/class.ilNewsSubscription.php @@ -12,93 +12,88 @@ */ class ilNewsSubscription { - /** - * Subscribe a user to an object (ref id). - * - * @param int $a_ref_id ref id - * @param int $a_user_id user id - */ - public static function _subscribe($a_ref_id, $a_user_id) - { - global $DIC; + /** + * Subscribe a user to an object (ref id). + * + * @param int $a_ref_id ref id + * @param int $a_user_id user id + */ + public static function _subscribe($a_ref_id, $a_user_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $ilDB->manipulate("DELETE FROM il_news_subscription WHERE ". - " ref_id = ".$ilDB->quote($a_ref_id, "integer")." ". - " AND user_id = ".$ilDB->quote($a_user_id, "integer")); - $ilDB->manipulate("INSERT INTO il_news_subscription (ref_id, user_id) VALUES (". - $ilDB->quote($a_ref_id, "integer").", ". - $ilDB->quote($a_user_id, "integer").")"); - } + $ilDB = $DIC->database(); + + $ilDB->manipulate("DELETE FROM il_news_subscription WHERE " . + " ref_id = " . $ilDB->quote($a_ref_id, "integer") . " " . + " AND user_id = " . $ilDB->quote($a_user_id, "integer")); + $ilDB->manipulate("INSERT INTO il_news_subscription (ref_id, user_id) VALUES (" . + $ilDB->quote($a_ref_id, "integer") . ", " . + $ilDB->quote($a_user_id, "integer") . ")"); + } - /** - * Unsubscribe a user from an object (ref id). - * - * @param int $a_ref_id ref id - * @param int $a_user_id user id - */ - public static function _unsubscribe($a_ref_id, $a_user_id) - { - global $DIC; + /** + * Unsubscribe a user from an object (ref id). + * + * @param int $a_ref_id ref id + * @param int $a_user_id user id + */ + public static function _unsubscribe($a_ref_id, $a_user_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $ilDB->manipulate("DELETE FROM il_news_subscription WHERE ref_id = ". - $ilDB->quote($a_ref_id, "integer")." AND user_id = ". - $ilDB->quote($a_user_id, "integer")); - } + $ilDB = $DIC->database(); + + $ilDB->manipulate("DELETE FROM il_news_subscription WHERE ref_id = " . + $ilDB->quote($a_ref_id, "integer") . " AND user_id = " . + $ilDB->quote($a_user_id, "integer")); + } - /** - * Check whether user has subscribed to an object. - * - * @param int $a_ref_id ref id - * @param int $a_user_id user id - * @return boolean has subscribed true/false - */ - public static function _hasSubscribed($a_ref_id, $a_user_id) - { - global $DIC; + /** + * Check whether user has subscribed to an object. + * + * @param int $a_ref_id ref id + * @param int $a_user_id user id + * @return boolean has subscribed true/false + */ + public static function _hasSubscribed($a_ref_id, $a_user_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $query = "SELECT * FROM il_news_subscription WHERE ref_id = ". - $ilDB->quote($a_ref_id, "integer")." AND user_id = ". - $ilDB->quote($a_user_id, "integer"); - $set = $ilDB->query($query); - if ($rec = $ilDB->fetchAssoc($set)) - { - return true; - } - else - { - return false; - } - } + $ilDB = $DIC->database(); + + $query = "SELECT * FROM il_news_subscription WHERE ref_id = " . + $ilDB->quote($a_ref_id, "integer") . " AND user_id = " . + $ilDB->quote($a_user_id, "integer"); + $set = $ilDB->query($query); + if ($rec = $ilDB->fetchAssoc($set)) { + return true; + } else { + return false; + } + } - /** - * Get subscriptions of user. - * - * @param int $a_ref_id ref id - * @param int $a_user_id user id - * @return boolean has subscribed true/false - */ - public static function _getSubscriptionsOfUser($a_user_id) - { - global $DIC; + /** + * Get subscriptions of user. + * + * @param int $a_ref_id ref id + * @param int $a_user_id user id + * @return boolean has subscribed true/false + */ + public static function _getSubscriptionsOfUser($a_user_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $query = "SELECT * FROM il_news_subscription WHERE user_id = ". - $ilDB->quote($a_user_id, "integer"); - $set = $ilDB->query($query); - $ref_ids = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $ref_ids[] = $rec["ref_id"]; - } + $ilDB = $DIC->database(); + + $query = "SELECT * FROM il_news_subscription WHERE user_id = " . + $ilDB->quote($a_user_id, "integer"); + $set = $ilDB->query($query); + $ref_ids = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $ref_ids[] = $rec["ref_id"]; + } - return $ref_ids; - } + return $ref_ids; + } } -?> diff --git a/Services/News/classes/class.ilNewsTimelineGUI.php b/Services/News/classes/class.ilNewsTimelineGUI.php index 72e399b7045840384a32cf43120990d9e9344a04..6a794e57722efe0f6d07ecedac4753f2a13b0263 100644 --- a/Services/News/classes/class.ilNewsTimelineGUI.php +++ b/Services/News/classes/class.ilNewsTimelineGUI.php @@ -14,496 +14,501 @@ */ class ilNewsTimelineGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var int - */ - protected $ref_id; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var int - */ - protected static $items_per_load = 10; - - /** - * @var bool - */ - protected $user_edit_all = false; - - /** - * Constructor - * - * @param int $a_ref_id reference id - */ - protected function __construct($a_ref_id, $a_include_auto_entries) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->tpl = $DIC["tpl"]; - $this->ref_id = $a_ref_id; - $this->lng = $DIC->language(); - $this->toolbar = $DIC->toolbar(); - $this->user = $DIC->user(); - $this->include_auto_entries = $a_include_auto_entries; - $this->access = $DIC->access(); - - $this->news_id = (int) $_GET["news_id"]; - - - $this->lng->loadLanguageModule("news"); - } - - /** - * Set user can edit other users postings - * - * @param bool $a_val user can edit all postings - */ - function setUserEditAll($a_val) - { - $this->user_edit_all = $a_val; - } - - /** - * Get user can edit other users postings - * - * @return bool user can edit all postings - */ - function getUserEditAll() - { - return $this->user_edit_all; - } - - /** - * Get instance - * - * @param int $a_ref_id reference id - * @return ilNewsTimelineGUI - */ - static function getInstance($a_ref_id, $a_include_auto_entries) - { - return new self($a_ref_id, $a_include_auto_entries); - } - - /** - * Execute command - * - * @throws ilCtrlException - */ - function executeCommand() - { - $ctrl = $this->ctrl; - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd("show"); - - switch ($next_class) - { - case "illikegui": - $i = new ilNewsItem($this->news_id); - include_once("./Services/Like/classes/class.ilLikeFactoryGUI.php"); - $likef = new ilLikeFactoryGUI(); - $like_gui = $likef->widget(array($i->getContextObjId())); - $ctrl->saveParameter($this,"news_id"); - $like_gui->setObject($i->getContextObjId(), $i->getContextObjType(), - $i->getContextSubObjId(), $i->getContextSubObjType(), $this->news_id); - $ret = $ctrl->forwardCommand($like_gui); - break; - - case "ilnotegui": - $i = new ilNewsItem($this->news_id); - $ctrl->saveParameter($this,"news_id"); - $notes_obj_type = ($i->getContextSubObjType() == "") - ? $i->getContextObjType() - : $i->getContextSubObjType(); - $note_gui = new ilNoteGUI($i->getContextObjId(), $i->getContextSubObjId(), - $notes_obj_type, false, $i->getId()); - $ret = $ctrl->forwardCommand($note_gui); - break; - - default: - if (in_array($cmd, array("show", "save", "update", "loadMore", "remove", "updateNewsItem"))) - { - $this->$cmd(); - } - } - } - - /** - * Show - * - * @param - * @return - */ - function show() - { - // toolbar - if ($this->access->checkAccess("news_add_news", "", $this->ref_id)) - { - $b = ilLinkButton::getInstance(); - $b->setCaption('news_add_news'); - $b->setOnClick("return il.News.create();"); - $b->setPrimary(true); - $this->toolbar->addButtonInstance($b); - } - - include_once("./Services/News/classes/class.ilNewsItem.php"); - $news_item = new ilNewsItem(); - $news_item->setContextObjId($this->ctrl->getContextObjId()); - $news_item->setContextObjType($this->ctrl->getContextObjType()); - - $news_data = $news_item->getNewsForRefId($this->ref_id, false, false, - 0, true, false, !$this->include_auto_entries, false, null, self::$items_per_load); - - include_once("./Services/News/Timeline/classes/class.ilTimelineGUI.php"); - include_once("./Services/News/classes/class.ilNewsTimelineItemGUI.php"); - $timeline = ilTimelineGUI::getInstance(); - - // get like widget - $obj_ids = array_unique(array_map(function ($a) { - return $a["context_obj_id"]; - }, $news_data)); - include_once("./Services/Like/classes/class.ilLikeFactoryGUI.php"); - $likef = new ilLikeFactoryGUI(); - $like_gui = $likef->widget($obj_ids); - - $js_items = array(); - foreach ($news_data as $d) - { - $news_item = new ilNewsItem($d["id"]); - $item = ilNewsTimelineItemGUI::getInstance($news_item, $d["ref_id"], $like_gui); - $item->setUserEditAll($this->getUserEditAll()); - $timeline->addItem($item); - $js_items[$d["id"]] = array( - "id" => $d["id"], - "user_id" => $d["user_id"], - "title" => $d["title"], - "content" => $d["content"].$d["content_long"], - "content_long" => "", - "priority" => $d["priority"], - "visibility" => $d["visibility"], - "content_type" => $d["content_type"], - "mob_id" => $d["mob_id"] - ); - } - - include_once("./Services/JSON/classes/class.ilJsonUtil.php"); - $this->tpl->addOnloadCode("il.News.setItems(".ilJsonUtil::encode($js_items).");"); - $this->tpl->addOnloadCode("il.News.setAjaxUrl('".$this->ctrl->getLinkTarget($this, "", "", true)."');"); - - if (count($news_data) > 0) - { - $ttpl = new ilTemplate("tpl.news_timeline.html", true, true, "Services/News"); - $ttpl->setVariable("NEWS", $timeline->render()); - $ttpl->setVariable("EDIT_MODAL", $this->getEditModal()); - $ttpl->setVariable("DELETE_MODAL", $this->getDeleteModal()); - $ttpl->setVariable("LOADER", ilUtil::getImagePath("loader.svg")); - $this->tpl->setContent($ttpl->get()); - - } - else - { - ilUtil::sendInfo($this->lng->txt("news_timline_add_entries_info")); - $this->tpl->setContent($this->getEditModal()); - } - - $this->lng->toJS("create"); - $this->lng->toJS("edit"); - $this->lng->toJS("update"); - $this->lng->toJS("save"); - - $this->tpl->addJavaScript("./Services/News/js/News.js"); - include_once("./Services/MediaObjects/classes/class.ilMediaPlayerGUI.php"); - ilMediaPlayerGUI::initJavascript($this->tpl); - } - - /** - * Load more - * - * @param - * @return - */ - function loadMore() - { - include_once("./Services/News/classes/class.ilNewsItem.php"); - $news_item = new ilNewsItem(); - $news_item->setContextObjId($this->ctrl->getContextObjId()); - $news_item->setContextObjType($this->ctrl->getContextObjType()); - - $excluded = $_POST["rendered_news"]; - - $news_data = $news_item->getNewsForRefId($this->ref_id, false, false, - 0, true, false, !$this->include_auto_entries, false, null, self::$items_per_load, $excluded); - - include_once("./Services/News/Timeline/classes/class.ilTimelineGUI.php"); - include_once("./Services/News/classes/class.ilNewsTimelineItemGUI.php"); - $timeline = ilTimelineGUI::getInstance(); - - // get like widget - $obj_ids = array_unique(array_map(function ($a) { - return $a["context_obj_id"]; - }, $news_data)); - include_once("./Services/Like/classes/class.ilLikeFactoryGUI.php"); - $likef = new ilLikeFactoryGUI(); - $like_gui = $likef->widget($obj_ids); - - $js_items = array(); - foreach ($news_data as $d) - { - $news_item = new ilNewsItem($d["id"]); - $item = ilNewsTimelineItemGUI::getInstance($news_item, $d["ref_id"], $like_gui); - $item->setUserEditAll($this->getUserEditAll()); - $timeline->addItem($item); - $js_items[$d["id"]] = array( - "id" => $d["id"], - "user_id" => $d["user_id"], - "title" => $d["title"], - "content" => $d["content"].$d["content_long"], - "content_long" => "", - "priority" => $d["priority"], - "visibility" => $d["visibility"], - "content_type" => $d["content_type"], - "mob_id" => $d["mob_id"] - ); - } - - include_once("./Services/JSON/classes/class.ilJsonUtil.php"); - $obj = new stdClass(); - $obj->data = $js_items; - $obj->html = $timeline->render(true); - - echo ilJsonUtil::encode($obj); - exit; - } - - - /** - * - * - * @param - */ - protected function updateNewsItem() - { - if ($_POST["news_action"] == "save") - { - $this->save(); - $this->ctrl->redirect($this, "show"); - } - if ($_POST["news_action"] == "update") - { - $this->update(); - $this->ctrl->redirect($this, "show"); - } - } - - - /** - * Save (ajax) - */ - function save() - { - include_once("./Services/News/classes/class.ilNewsItemGUI.php"); - $form = ilNewsItemGUI::getEditForm(IL_FORM_CREATE, $this->ref_id); - if ($form->checkInput()) - { - $news_item = new ilNewsItem(); - $news_item->setTitle($form->getInput("news_title")); - $news_item->setContent($form->getInput("news_content")); - $news_item->setVisibility($form->getInput("news_visibility")); - include_once("./Services/News/classes/class.ilNewsItemGUI.php"); - if (ilNewsItemGUI::isRteActivated()) - { - $news_item->setContentHtml(true); - } - //$news_item->setContentLong($form->getInput("news_content_long")); - $news_item->setContentLong(""); - - $obj_id = ilObject::_lookupObjectId($this->ref_id); - $obj_type = ilObject::_lookupType($obj_id); - $news_item->setContextObjId($obj_id); - $news_item->setContextObjType($obj_type); - $news_item->setUserId($this->user->getId()); - - $media = $_FILES["media"]; - if ($media["name"] != "") - { - $mob = ilObjMediaObject::_saveTempFileAsMediaObject($media["name"], $media["tmp_name"], true); - $news_item->setMobId($mob->getId()); - } - - $news_set = new ilSetting("news"); - if (!$news_set->get("enable_rss_for_internal")) - { - $news_item->setVisibility("users"); - } - - $news_item->create(); - } - } - - - - /** - * Update (ajax) - */ - function update() - { - include_once("./Services/News/classes/class.ilNewsItemGUI.php"); - $form = ilNewsItemGUI::getEditForm(IL_FORM_EDIT, $this->ref_id); - if ($form->checkInput()) - { - $news_item = new ilNewsItem((int) $_POST["id"]); - $news_item->setTitle($form->getInput("news_title")); - $news_item->setContent($form->getInput("news_content")); - $news_item->setVisibility($form->getInput("news_visibility")); - //$news_item->setContentLong($form->getInput("news_content_long")); - include_once("./Services/News/classes/class.ilNewsItemGUI.php"); - if (ilNewsItemGUI::isRteActivated()) - { - $news_item->setContentHtml(true); - } - $news_item->setContentLong(""); - - $media = $_FILES["media"]; - $old_mob_id = 0; - - // delete old media object - if ($media["name"] != "" || $_POST["media_delete"] != "") - { - if ($news_item->getMobId() > 0 && ilObject::_lookupType($news_item->getMobId()) == "mob") - { - $old_mob_id = $news_item->getMobId(); - } - $news_item->setMobId(0); - } - - if ($media["name"] != "") - { - $mob = ilObjMediaObject::_saveTempFileAsMediaObject($media["name"], $media["tmp_name"], true); - $news_item->setMobId($mob->getId()); - } - - $obj_id = ilObject::_lookupObjectId($this->ref_id); - - if ($news_item->getContextObjId() == $obj_id) - { - $news_item->setUpdateUserId($this->user->getId()); - $news_item->update(); - - if ($old_mob_id > 0) - { - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $old_mob = new ilObjMediaObject($old_mob_id); - $old_mob->delete(); - } - } - } - } - - /** - * Remove (ajax) - */ - function remove() - { - include_once("./Services/News/classes/class.ilNewsItemGUI.php"); - $news_item = new ilNewsItem((int) $_POST["id"]); - if ($this->user->getId() == $news_item->getUserId() || $this->getUserEditAll()) - { - $news_item->delete(); - } - exit; - } - - /** - * Get edit modal - * - * @return string modal html - */ - protected function getEditModal() - { - include_once("./Services/UIComponent/Modal/classes/class.ilModalGUI.php"); - $modal = ilModalGUI::getInstance(); - $modal->setHeading($this->lng->txt("edit")); - $modal->setId("ilNewsEditModal"); - $modal->setType(ilModalGUI::TYPE_LARGE); - - include_once("./Services/News/classes/class.ilNewsItemGUI.php"); - $form = ilNewsItemGUI::getEditForm(IL_FORM_EDIT, $this->ref_id); - $form->setShowTopButtons(false); - $form->setFormAction($this->ctrl->getFormAction($this)); - - - // - $hi = new ilHiddenInputGUI("id"); - $form->addItem($hi); - $act = new ilHiddenInputGUI("news_action"); - $form->addItem($act); - $form->setId("news_edit_form"); - - $modal->setBody($form->getHTML()); - - return $modal->getHTML(); - - } - - /** - * Get delete modal - * - * @return string modal html - */ - protected function getDeleteModal() - { - include_once("./Services/UIComponent/Modal/classes/class.ilModalGUI.php"); - $modal = ilModalGUI::getInstance(); - $modal->setHeading($this->lng->txt("delete")); - $modal->setId("ilNewsDeleteModal"); - $modal->setType(ilModalGUI::TYPE_LARGE); - - require_once 'Services/UIComponent/Button/classes/class.ilSubmitButton.php'; - $confirm = ilSubmitButton::getInstance(); - $confirm->setCaption("delete"); - $confirm->setId("news_btn_delete"); - $modal->addButton($confirm); - - $cancel = ilSubmitButton::getInstance(); - $cancel->setCaption("cancel"); - $cancel->setId("news_btn_cancel_delete"); - $modal->addButton($cancel); - - $modal->setBody("

                  ". - $this->tpl->getMessageHTML($this->lng->txt("news_really_delete_news"), "question")); - - return $modal->getHTML(); - - } + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var int + */ + protected $ref_id; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var int + */ + protected static $items_per_load = 10; + + /** + * @var bool + */ + protected $user_edit_all = false; + + /** + * Constructor + * + * @param int $a_ref_id reference id + */ + protected function __construct($a_ref_id, $a_include_auto_entries) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->tpl = $DIC["tpl"]; + $this->ref_id = $a_ref_id; + $this->lng = $DIC->language(); + $this->toolbar = $DIC->toolbar(); + $this->user = $DIC->user(); + $this->include_auto_entries = $a_include_auto_entries; + $this->access = $DIC->access(); + + $this->news_id = (int) $_GET["news_id"]; + + + $this->lng->loadLanguageModule("news"); + } + + /** + * Set user can edit other users postings + * + * @param bool $a_val user can edit all postings + */ + public function setUserEditAll($a_val) + { + $this->user_edit_all = $a_val; + } + + /** + * Get user can edit other users postings + * + * @return bool user can edit all postings + */ + public function getUserEditAll() + { + return $this->user_edit_all; + } + + /** + * Get instance + * + * @param int $a_ref_id reference id + * @return ilNewsTimelineGUI + */ + public static function getInstance($a_ref_id, $a_include_auto_entries) + { + return new self($a_ref_id, $a_include_auto_entries); + } + + /** + * Execute command + * + * @throws ilCtrlException + */ + public function executeCommand() + { + $ctrl = $this->ctrl; + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd("show"); + + switch ($next_class) { + case "illikegui": + $i = new ilNewsItem($this->news_id); + include_once("./Services/Like/classes/class.ilLikeFactoryGUI.php"); + $likef = new ilLikeFactoryGUI(); + $like_gui = $likef->widget(array($i->getContextObjId())); + $ctrl->saveParameter($this, "news_id"); + $like_gui->setObject( + $i->getContextObjId(), + $i->getContextObjType(), + $i->getContextSubObjId(), + $i->getContextSubObjType(), + $this->news_id + ); + $ret = $ctrl->forwardCommand($like_gui); + break; + + case "ilnotegui": + $i = new ilNewsItem($this->news_id); + $ctrl->saveParameter($this, "news_id"); + $notes_obj_type = ($i->getContextSubObjType() == "") + ? $i->getContextObjType() + : $i->getContextSubObjType(); + $note_gui = new ilNoteGUI( + $i->getContextObjId(), + $i->getContextSubObjId(), + $notes_obj_type, + false, + $i->getId() + ); + $ret = $ctrl->forwardCommand($note_gui); + break; + + default: + if (in_array($cmd, array("show", "save", "update", "loadMore", "remove", "updateNewsItem"))) { + $this->$cmd(); + } + } + } + + /** + * Show + * + * @param + * @return + */ + public function show() + { + // toolbar + if ($this->access->checkAccess("news_add_news", "", $this->ref_id)) { + $b = ilLinkButton::getInstance(); + $b->setCaption('news_add_news'); + $b->setOnClick("return il.News.create();"); + $b->setPrimary(true); + $this->toolbar->addButtonInstance($b); + } + + include_once("./Services/News/classes/class.ilNewsItem.php"); + $news_item = new ilNewsItem(); + $news_item->setContextObjId($this->ctrl->getContextObjId()); + $news_item->setContextObjType($this->ctrl->getContextObjType()); + + $news_data = $news_item->getNewsForRefId( + $this->ref_id, + false, + false, + 0, + true, + false, + !$this->include_auto_entries, + false, + null, + self::$items_per_load + ); + + include_once("./Services/News/Timeline/classes/class.ilTimelineGUI.php"); + include_once("./Services/News/classes/class.ilNewsTimelineItemGUI.php"); + $timeline = ilTimelineGUI::getInstance(); + + // get like widget + $obj_ids = array_unique(array_map(function ($a) { + return $a["context_obj_id"]; + }, $news_data)); + include_once("./Services/Like/classes/class.ilLikeFactoryGUI.php"); + $likef = new ilLikeFactoryGUI(); + $like_gui = $likef->widget($obj_ids); + + $js_items = array(); + foreach ($news_data as $d) { + $news_item = new ilNewsItem($d["id"]); + $item = ilNewsTimelineItemGUI::getInstance($news_item, $d["ref_id"], $like_gui); + $item->setUserEditAll($this->getUserEditAll()); + $timeline->addItem($item); + $js_items[$d["id"]] = array( + "id" => $d["id"], + "user_id" => $d["user_id"], + "title" => $d["title"], + "content" => $d["content"] . $d["content_long"], + "content_long" => "", + "priority" => $d["priority"], + "visibility" => $d["visibility"], + "content_type" => $d["content_type"], + "mob_id" => $d["mob_id"] + ); + } + + include_once("./Services/JSON/classes/class.ilJsonUtil.php"); + $this->tpl->addOnloadCode("il.News.setItems(" . ilJsonUtil::encode($js_items) . ");"); + $this->tpl->addOnloadCode("il.News.setAjaxUrl('" . $this->ctrl->getLinkTarget($this, "", "", true) . "');"); + + if (count($news_data) > 0) { + $ttpl = new ilTemplate("tpl.news_timeline.html", true, true, "Services/News"); + $ttpl->setVariable("NEWS", $timeline->render()); + $ttpl->setVariable("EDIT_MODAL", $this->getEditModal()); + $ttpl->setVariable("DELETE_MODAL", $this->getDeleteModal()); + $ttpl->setVariable("LOADER", ilUtil::getImagePath("loader.svg")); + $this->tpl->setContent($ttpl->get()); + } else { + ilUtil::sendInfo($this->lng->txt("news_timline_add_entries_info")); + $this->tpl->setContent($this->getEditModal()); + } + + $this->lng->toJS("create"); + $this->lng->toJS("edit"); + $this->lng->toJS("update"); + $this->lng->toJS("save"); + + $this->tpl->addJavaScript("./Services/News/js/News.js"); + include_once("./Services/MediaObjects/classes/class.ilMediaPlayerGUI.php"); + ilMediaPlayerGUI::initJavascript($this->tpl); + } + + /** + * Load more + * + * @param + * @return + */ + public function loadMore() + { + include_once("./Services/News/classes/class.ilNewsItem.php"); + $news_item = new ilNewsItem(); + $news_item->setContextObjId($this->ctrl->getContextObjId()); + $news_item->setContextObjType($this->ctrl->getContextObjType()); + + $excluded = $_POST["rendered_news"]; + + $news_data = $news_item->getNewsForRefId( + $this->ref_id, + false, + false, + 0, + true, + false, + !$this->include_auto_entries, + false, + null, + self::$items_per_load, + $excluded + ); + + include_once("./Services/News/Timeline/classes/class.ilTimelineGUI.php"); + include_once("./Services/News/classes/class.ilNewsTimelineItemGUI.php"); + $timeline = ilTimelineGUI::getInstance(); + + // get like widget + $obj_ids = array_unique(array_map(function ($a) { + return $a["context_obj_id"]; + }, $news_data)); + include_once("./Services/Like/classes/class.ilLikeFactoryGUI.php"); + $likef = new ilLikeFactoryGUI(); + $like_gui = $likef->widget($obj_ids); + + $js_items = array(); + foreach ($news_data as $d) { + $news_item = new ilNewsItem($d["id"]); + $item = ilNewsTimelineItemGUI::getInstance($news_item, $d["ref_id"], $like_gui); + $item->setUserEditAll($this->getUserEditAll()); + $timeline->addItem($item); + $js_items[$d["id"]] = array( + "id" => $d["id"], + "user_id" => $d["user_id"], + "title" => $d["title"], + "content" => $d["content"] . $d["content_long"], + "content_long" => "", + "priority" => $d["priority"], + "visibility" => $d["visibility"], + "content_type" => $d["content_type"], + "mob_id" => $d["mob_id"] + ); + } + + include_once("./Services/JSON/classes/class.ilJsonUtil.php"); + $obj = new stdClass(); + $obj->data = $js_items; + $obj->html = $timeline->render(true); + + echo ilJsonUtil::encode($obj); + exit; + } + + + /** + * + * + * @param + */ + protected function updateNewsItem() + { + if ($_POST["news_action"] == "save") { + $this->save(); + $this->ctrl->redirect($this, "show"); + } + if ($_POST["news_action"] == "update") { + $this->update(); + $this->ctrl->redirect($this, "show"); + } + } + + + /** + * Save (ajax) + */ + public function save() + { + include_once("./Services/News/classes/class.ilNewsItemGUI.php"); + $form = ilNewsItemGUI::getEditForm(IL_FORM_CREATE, $this->ref_id); + if ($form->checkInput()) { + $news_item = new ilNewsItem(); + $news_item->setTitle($form->getInput("news_title")); + $news_item->setContent($form->getInput("news_content")); + $news_item->setVisibility($form->getInput("news_visibility")); + include_once("./Services/News/classes/class.ilNewsItemGUI.php"); + if (ilNewsItemGUI::isRteActivated()) { + $news_item->setContentHtml(true); + } + //$news_item->setContentLong($form->getInput("news_content_long")); + $news_item->setContentLong(""); + + $obj_id = ilObject::_lookupObjectId($this->ref_id); + $obj_type = ilObject::_lookupType($obj_id); + $news_item->setContextObjId($obj_id); + $news_item->setContextObjType($obj_type); + $news_item->setUserId($this->user->getId()); + + $media = $_FILES["media"]; + if ($media["name"] != "") { + $mob = ilObjMediaObject::_saveTempFileAsMediaObject($media["name"], $media["tmp_name"], true); + $news_item->setMobId($mob->getId()); + } + + $news_set = new ilSetting("news"); + if (!$news_set->get("enable_rss_for_internal")) { + $news_item->setVisibility("users"); + } + + $news_item->create(); + } + } + + + + /** + * Update (ajax) + */ + public function update() + { + include_once("./Services/News/classes/class.ilNewsItemGUI.php"); + $form = ilNewsItemGUI::getEditForm(IL_FORM_EDIT, $this->ref_id); + if ($form->checkInput()) { + $news_item = new ilNewsItem((int) $_POST["id"]); + $news_item->setTitle($form->getInput("news_title")); + $news_item->setContent($form->getInput("news_content")); + $news_item->setVisibility($form->getInput("news_visibility")); + //$news_item->setContentLong($form->getInput("news_content_long")); + include_once("./Services/News/classes/class.ilNewsItemGUI.php"); + if (ilNewsItemGUI::isRteActivated()) { + $news_item->setContentHtml(true); + } + $news_item->setContentLong(""); + + $media = $_FILES["media"]; + $old_mob_id = 0; + + // delete old media object + if ($media["name"] != "" || $_POST["media_delete"] != "") { + if ($news_item->getMobId() > 0 && ilObject::_lookupType($news_item->getMobId()) == "mob") { + $old_mob_id = $news_item->getMobId(); + } + $news_item->setMobId(0); + } + + if ($media["name"] != "") { + $mob = ilObjMediaObject::_saveTempFileAsMediaObject($media["name"], $media["tmp_name"], true); + $news_item->setMobId($mob->getId()); + } + + $obj_id = ilObject::_lookupObjectId($this->ref_id); + + if ($news_item->getContextObjId() == $obj_id) { + $news_item->setUpdateUserId($this->user->getId()); + $news_item->update(); + + if ($old_mob_id > 0) { + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $old_mob = new ilObjMediaObject($old_mob_id); + $old_mob->delete(); + } + } + } + } + + /** + * Remove (ajax) + */ + public function remove() + { + include_once("./Services/News/classes/class.ilNewsItemGUI.php"); + $news_item = new ilNewsItem((int) $_POST["id"]); + if ($this->user->getId() == $news_item->getUserId() || $this->getUserEditAll()) { + $news_item->delete(); + } + exit; + } + + /** + * Get edit modal + * + * @return string modal html + */ + protected function getEditModal() + { + include_once("./Services/UIComponent/Modal/classes/class.ilModalGUI.php"); + $modal = ilModalGUI::getInstance(); + $modal->setHeading($this->lng->txt("edit")); + $modal->setId("ilNewsEditModal"); + $modal->setType(ilModalGUI::TYPE_LARGE); + + include_once("./Services/News/classes/class.ilNewsItemGUI.php"); + $form = ilNewsItemGUI::getEditForm(IL_FORM_EDIT, $this->ref_id); + $form->setShowTopButtons(false); + $form->setFormAction($this->ctrl->getFormAction($this)); + + + // + $hi = new ilHiddenInputGUI("id"); + $form->addItem($hi); + $act = new ilHiddenInputGUI("news_action"); + $form->addItem($act); + $form->setId("news_edit_form"); + + $modal->setBody($form->getHTML()); + + return $modal->getHTML(); + } + + /** + * Get delete modal + * + * @return string modal html + */ + protected function getDeleteModal() + { + include_once("./Services/UIComponent/Modal/classes/class.ilModalGUI.php"); + $modal = ilModalGUI::getInstance(); + $modal->setHeading($this->lng->txt("delete")); + $modal->setId("ilNewsDeleteModal"); + $modal->setType(ilModalGUI::TYPE_LARGE); + + require_once 'Services/UIComponent/Button/classes/class.ilSubmitButton.php'; + $confirm = ilSubmitButton::getInstance(); + $confirm->setCaption("delete"); + $confirm->setId("news_btn_delete"); + $modal->addButton($confirm); + + $cancel = ilSubmitButton::getInstance(); + $cancel->setCaption("cancel"); + $cancel->setId("news_btn_cancel_delete"); + $modal->addButton($cancel); + + $modal->setBody("

                  " . + $this->tpl->getMessageHTML($this->lng->txt("news_really_delete_news"), "question")); + + return $modal->getHTML(); + } } -?> \ No newline at end of file diff --git a/Services/News/classes/class.ilNewsTimelineItemGUI.php b/Services/News/classes/class.ilNewsTimelineItemGUI.php index 193576fb7afdc666fd7408c1783f8f6563c216ad..f4162c817a3cd14c6366d9f40754cbc3dc1aed8b 100644 --- a/Services/News/classes/class.ilNewsTimelineItemGUI.php +++ b/Services/News/classes/class.ilNewsTimelineItemGUI.php @@ -11,363 +11,384 @@ */ class ilNewsTimelineItemGUI implements ilTimelineItemInt { - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilNewsItem - */ - protected $news_item; - - /** - * @var ilObjectDefinition - */ - protected $obj_def; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var bool - */ - protected $user_edit_all; - - /** - * Ref ID of news item - * - * @var int - */ - protected $news_item_ref_id; - - /** - * Ref id of timeline container - * @var int - */ - protected $ref_id; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var \ilLikeGUI - */ - protected $like_gui; - - /** - * Constructor - * - * @param ilNewsItem $a_news_item - * @param $a_news_ref_id - * @param ilLikeGUI $a_like_gui - */ - protected function __construct(ilNewsItem $a_news_item, $a_news_ref_id, \ilLikeGUI $a_like_gui) - { - global $DIC; - - $this->like_gui = $a_like_gui; - - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $this->setNewsItem($a_news_item); - $this->user = $DIC->user(); - $this->obj_def = $DIC["objDefinition"]; - $this->news_item_ref_id = $a_news_ref_id; - - $this->ref_id = (int) $_GET["ref_id"]; - } - - /** - * Get instance - * - * @param ilNewsItem $a_news_item news item - * @return ilNewsTimelineItemGUI - */ - static function getInstance(ilNewsItem $a_news_item, $a_news_ref_id, \ilLikeGUI $a_like_gui) - { - return new self($a_news_item, $a_news_ref_id, $a_like_gui); - } - - - /** - * Set news item - * - * @param ilNewsItem $a_val news item - */ - function setNewsItem(ilNewsItem $a_val) - { - $this->news_item = $a_val; - } - - /** - * Get news item - * - * @return ilNewsItem news item - */ - function getNewsItem() - { - return $this->news_item; - } - - /** - * Set user can edit other users postings - * - * @param bool $a_val user can edit all postings - */ - function setUserEditAll($a_val) - { - $this->user_edit_all = $a_val; - } - - /** - * Get user can edit other users postings - * - * @return bool user can edit all postings - */ - function getUserEditAll() - { - return $this->user_edit_all; - } - - /** - * @inheritdoc - */ - function getDateTime() - { - $i = $this->getNewsItem(); - return new ilDateTime($i->getCreationDate(), IL_CAL_DATETIME); - } - - - /** - * @inheritdoc - */ - function render() - { - $i = $this->getNewsItem(); - $tpl = new ilTemplate("tpl.timeline_item.html", true, true, "Services/News"); - - include_once("./Services/News/classes/class.ilNewsRendererFactory.php"); - $news_renderer = ilNewsRendererFactory::getRenderer($i->getContextObjType()); - $news_renderer->setLanguage($this->lng->getLangKey()); - $news_renderer->setNewsItem($i, $this->news_item_ref_id); - - $obj_id = $i->getContextObjId(); - - // edited? - if ($i->getCreationDate() != $i->getUpdateDate()) - { - $tpl->setCurrentBlock("edited"); - $update_date = new ilDateTime($i->getUpdateDate(), IL_CAL_DATETIME); - $tpl->setVariable("TXT_EDITED", $this->lng->txt("cont_news_edited")); - if ($i->getUpdateUserId() > 0 && ($i->getUpdateUserId() != $i->getUserId())) - { - include_once("./Services/User/classes/class.ilUserUtil.php"); - $tpl->setVariable("TXT_USR_EDITED", ilUserUtil::getNamePresentation($i->getUpdateUserId(), false, true, - $this->ctrl->getLinkTargetByClass("ilnewstimelinegui")) . " - "); - } - include_once("./Services/Calendar/classes/class.ilDatePresentation.php"); - $tpl->setVariable("TIME_EDITED", ilDatePresentation::formatDate($update_date)); - $tpl->parseCurrentBlock(); - } - - - // context object link - include_once("./Services/Link/classes/class.ilLink.php"); - if ($this->news_item_ref_id > 0 && $this->ref_id != $this->news_item_ref_id) - { - $tpl->setCurrentBlock("object"); - $tpl->setVariable("OBJ_TITLE", ilObject::_lookupTitle($obj_id)); - $tpl->setVariable("OBJ_IMG", ilObject::_getIcon($obj_id)); - $tpl->setVariable("OBJ_HREF", $news_renderer->getObjectLink()); - $tpl->parseCurrentBlock(); - } - - // media - if ($i->getMobId() > 0 && ilObject::_exists($i->getMobId())) - { - $media = $this->renderMedia($i); - $tpl->setCurrentBlock("player"); - $tpl->setVariable("PLAYER", $media); - $tpl->parseCurrentBlock(); - } - - $tpl->setVariable("USER_IMAGE", ilObjUser::_getPersonalPicturePath($i->getUserId(), "xsmall")); - $tpl->setVariable("TITLE", - ilNewsItem::determineNewsTitle($i->getContextObjType(), $i->getTitle(), $i->getContentIsLangVar())); - - // content - $tpl->setVariable("CONTENT", $news_renderer->getTimelineContent()); - - include_once("./Services/User/classes/class.ilUserUtil.php"); - $tpl->setVariable("TXT_USR", ilUserUtil::getNamePresentation($i->getUserId(), false, true, - $this->ctrl->getLinkTargetByClass("ilnewstimelinegui"))); - - include_once("./Services/Calendar/classes/class.ilDatePresentation.php"); - $tpl->setVariable("TIME", ilDatePresentation::formatDate($this->getDateTime())); - - // actions - include_once("Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"); - $list = new ilAdvancedSelectionListGUI(); - $list->setListTitle(""); - $list->setId("news_tl_act_".$i->getId()); - //$list->setSelectionHeaderClass("small"); - //$list->setItemLinkClass("xsmall"); - //$list->setLinksMode("il_ContainerItemCommand2"); - $list->setHeaderIcon(ilAdvancedSelectionListGUI::DOWN_ARROW_DARK); - $list->setUseImages(false); - - if ($i->getPriority() == 1 && ($i->getUserId() == $this->user->getId() || $this->getUserEditAll())) - { - $list->addItem($this->lng->txt("edit"), "", "", "", "", "", - "", false, "il.News.edit(" . $i->getId() . ");"); - $list->addItem($this->lng->txt("delete"), "", "", "", "", "", - "", false, "il.News.delete(" . $i->getId() . ");"); - } - - $news_renderer->addTimelineActions($list); - - $tpl->setVariable("ACTIONS", $list->getHTML()); - - return $tpl->get(); - } - - /** - * Render media - * - * @param - * @return - */ - protected function renderMedia(ilNewsItem $i) - { - global $DIC; - - $media_path = $this->getMediaPath($i); - $mime = ilObjMediaObject::getMimeType($media_path); - - $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-news-modal-img-".$i->getId(); - $title = basename($media_path); - $image = $ui_renderer->render($ui_factory->image()->responsive($media_path, $title)); - - $img_tpl = new ilTemplate("tpl.news_timeline_image_file.html", true, true, "Services/News"); - $img_tpl->setVariable("ITEM_ID", $item_id); - $img_tpl->setVariable("IMAGE", $image); - - $html = $img_tpl->get(); - } - else if (in_array($mime, array("audio/mpeg", "audio/ogg", "video/mp4", "video/x-flv", "video/webm"))) - { - $mp = new ilMediaPlayerGUI(); - $mp->setFile($media_path); - $mp->setDisplayHeight(200); - $html = $mp->getMediaPlayerHtml(); - } - else - { - // download? - $html = ""; - } - return $html; - } - - /** - * Render media - * - * @param ilNewsItem - * @return string - */ - protected function renderMediaModal(ilNewsItem $i) - { - global $DIC; - - $media_path = $this->getMediaPath($i); - $mime = ilObjMediaObject::getMimeType($media_path); - - $ui_factory = $DIC->ui()->factory(); - $ui_renderer = $DIC->ui()->renderer(); - - $modal_html = ""; - - if (in_array($mime, array("image/jpeg", "image/svg+xml", "image/gif", "image/png"))) - { - $title = basename($media_path); - $item_id = "il-news-modal-img-".$i->getId(); - $image = $ui_renderer->render($ui_factory->image()->responsive($media_path, $title)); - $modal = ilModalGUI::getInstance(); - $modal->setId($item_id); - $modal->setType(ilModalGUI::TYPE_LARGE); - $modal->setBody($image); - $modal->setHeading($title); - $modal_html = $modal->getHTML(); - } - return $modal_html; - } - - - /** - * Render footer - * @throws ilCtrlException - */ - function renderFooter() - { - $i = $this->getNewsItem(); - - // like - $this->ctrl->setParameterByClass("ilnewstimelinegui", "news_id", $i->getId()); - $this->like_gui->setObject($i->getContextObjId(), $i->getContextObjType(), - $i->getContextSubObjId(), $i->getContextSubObjType(), $i->getId()); - $html = $this->ctrl->getHTML($this->like_gui); - - // comments - $notes_obj_type = ($i->getContextSubObjType() == "") - ? $i->getContextObjType() - : $i->getContextSubObjType(); - $note_gui = new ilNoteGUI($i->getContextObjId(), $i->getContextSubObjId(), - $notes_obj_type, false, $i->getId()); - $note_gui->setDefaultCommand("getWidget"); - - //ilNoteGUI::getListCommentsJSCall($this->ajax_hash, $redraw_js) - $html.= $this->ctrl->getHTML($note_gui); - - $this->ctrl->setParameterByClass("ilnewstimelinegui", "news_id", $_GET["news_id"]); - - return $html.$this->renderMediaModal($i); - } - - /** - * @param ilNewsItem $i - * @return string - */ - protected function getMediaPath(ilNewsItem $i) - { - $media_path = ""; - if ($i->getMobId() > 0) - { - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - include_once("./Services/MediaObjects/classes/class.ilMediaPlayerGUI.php"); - $mob = new ilObjMediaObject($i->getMobId()); - $med = $mob->getMediaItem("Standard"); - if (strcasecmp("Reference", $med->getLocationType()) == 0) - { - $media_path = $med->getLocation(); - } else - { - $media_path = ilObjMediaObject::_getURL($mob->getId()) . "/" . $med->getLocation(); - } - } - return $media_path; - } - + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilNewsItem + */ + protected $news_item; + + /** + * @var ilObjectDefinition + */ + protected $obj_def; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var bool + */ + protected $user_edit_all; + + /** + * Ref ID of news item + * + * @var int + */ + protected $news_item_ref_id; + + /** + * Ref id of timeline container + * @var int + */ + protected $ref_id; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var \ilLikeGUI + */ + protected $like_gui; + + /** + * Constructor + * + * @param ilNewsItem $a_news_item + * @param $a_news_ref_id + * @param ilLikeGUI $a_like_gui + */ + protected function __construct(ilNewsItem $a_news_item, $a_news_ref_id, \ilLikeGUI $a_like_gui) + { + global $DIC; + + $this->like_gui = $a_like_gui; + + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->setNewsItem($a_news_item); + $this->user = $DIC->user(); + $this->obj_def = $DIC["objDefinition"]; + $this->news_item_ref_id = $a_news_ref_id; + + $this->ref_id = (int) $_GET["ref_id"]; + } + + /** + * Get instance + * + * @param ilNewsItem $a_news_item news item + * @return ilNewsTimelineItemGUI + */ + public static function getInstance(ilNewsItem $a_news_item, $a_news_ref_id, \ilLikeGUI $a_like_gui) + { + return new self($a_news_item, $a_news_ref_id, $a_like_gui); + } + + + /** + * Set news item + * + * @param ilNewsItem $a_val news item + */ + public function setNewsItem(ilNewsItem $a_val) + { + $this->news_item = $a_val; + } + + /** + * Get news item + * + * @return ilNewsItem news item + */ + public function getNewsItem() + { + return $this->news_item; + } + + /** + * Set user can edit other users postings + * + * @param bool $a_val user can edit all postings + */ + public function setUserEditAll($a_val) + { + $this->user_edit_all = $a_val; + } + + /** + * Get user can edit other users postings + * + * @return bool user can edit all postings + */ + public function getUserEditAll() + { + return $this->user_edit_all; + } + + /** + * @inheritdoc + */ + public function getDateTime() + { + $i = $this->getNewsItem(); + return new ilDateTime($i->getCreationDate(), IL_CAL_DATETIME); + } + + + /** + * @inheritdoc + */ + public function render() + { + $i = $this->getNewsItem(); + $tpl = new ilTemplate("tpl.timeline_item.html", true, true, "Services/News"); + + include_once("./Services/News/classes/class.ilNewsRendererFactory.php"); + $news_renderer = ilNewsRendererFactory::getRenderer($i->getContextObjType()); + $news_renderer->setLanguage($this->lng->getLangKey()); + $news_renderer->setNewsItem($i, $this->news_item_ref_id); + + $obj_id = $i->getContextObjId(); + + // edited? + if ($i->getCreationDate() != $i->getUpdateDate()) { + $tpl->setCurrentBlock("edited"); + $update_date = new ilDateTime($i->getUpdateDate(), IL_CAL_DATETIME); + $tpl->setVariable("TXT_EDITED", $this->lng->txt("cont_news_edited")); + if ($i->getUpdateUserId() > 0 && ($i->getUpdateUserId() != $i->getUserId())) { + include_once("./Services/User/classes/class.ilUserUtil.php"); + $tpl->setVariable("TXT_USR_EDITED", ilUserUtil::getNamePresentation( + $i->getUpdateUserId(), + false, + true, + $this->ctrl->getLinkTargetByClass("ilnewstimelinegui") + ) . " - "); + } + include_once("./Services/Calendar/classes/class.ilDatePresentation.php"); + $tpl->setVariable("TIME_EDITED", ilDatePresentation::formatDate($update_date)); + $tpl->parseCurrentBlock(); + } + + + // context object link + include_once("./Services/Link/classes/class.ilLink.php"); + if ($this->news_item_ref_id > 0 && $this->ref_id != $this->news_item_ref_id) { + $tpl->setCurrentBlock("object"); + $tpl->setVariable("OBJ_TITLE", ilObject::_lookupTitle($obj_id)); + $tpl->setVariable("OBJ_IMG", ilObject::_getIcon($obj_id)); + $tpl->setVariable("OBJ_HREF", $news_renderer->getObjectLink()); + $tpl->parseCurrentBlock(); + } + + // media + if ($i->getMobId() > 0 && ilObject::_exists($i->getMobId())) { + $media = $this->renderMedia($i); + $tpl->setCurrentBlock("player"); + $tpl->setVariable("PLAYER", $media); + $tpl->parseCurrentBlock(); + } + + $tpl->setVariable("USER_IMAGE", ilObjUser::_getPersonalPicturePath($i->getUserId(), "xsmall")); + $tpl->setVariable( + "TITLE", + ilNewsItem::determineNewsTitle($i->getContextObjType(), $i->getTitle(), $i->getContentIsLangVar()) + ); + + // content + $tpl->setVariable("CONTENT", $news_renderer->getTimelineContent()); + + include_once("./Services/User/classes/class.ilUserUtil.php"); + $tpl->setVariable("TXT_USR", ilUserUtil::getNamePresentation( + $i->getUserId(), + false, + true, + $this->ctrl->getLinkTargetByClass("ilnewstimelinegui") + )); + + include_once("./Services/Calendar/classes/class.ilDatePresentation.php"); + $tpl->setVariable("TIME", ilDatePresentation::formatDate($this->getDateTime())); + + // actions + include_once("Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"); + $list = new ilAdvancedSelectionListGUI(); + $list->setListTitle(""); + $list->setId("news_tl_act_" . $i->getId()); + //$list->setSelectionHeaderClass("small"); + //$list->setItemLinkClass("xsmall"); + //$list->setLinksMode("il_ContainerItemCommand2"); + $list->setHeaderIcon(ilAdvancedSelectionListGUI::DOWN_ARROW_DARK); + $list->setUseImages(false); + + if ($i->getPriority() == 1 && ($i->getUserId() == $this->user->getId() || $this->getUserEditAll())) { + $list->addItem( + $this->lng->txt("edit"), + "", + "", + "", + "", + "", + "", + false, + "il.News.edit(" . $i->getId() . ");" + ); + $list->addItem( + $this->lng->txt("delete"), + "", + "", + "", + "", + "", + "", + false, + "il.News.delete(" . $i->getId() . ");" + ); + } + + $news_renderer->addTimelineActions($list); + + $tpl->setVariable("ACTIONS", $list->getHTML()); + + return $tpl->get(); + } + + /** + * Render media + * + * @param + * @return + */ + protected function renderMedia(ilNewsItem $i) + { + global $DIC; + + $media_path = $this->getMediaPath($i); + $mime = ilObjMediaObject::getMimeType($media_path); + + $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-news-modal-img-" . $i->getId(); + $title = basename($media_path); + $image = $ui_renderer->render($ui_factory->image()->responsive($media_path, $title)); + + $img_tpl = new ilTemplate("tpl.news_timeline_image_file.html", true, true, "Services/News"); + $img_tpl->setVariable("ITEM_ID", $item_id); + $img_tpl->setVariable("IMAGE", $image); + + $html = $img_tpl->get(); + } elseif (in_array($mime, array("audio/mpeg", "audio/ogg", "video/mp4", "video/x-flv", "video/webm"))) { + $mp = new ilMediaPlayerGUI(); + $mp->setFile($media_path); + $mp->setDisplayHeight(200); + $html = $mp->getMediaPlayerHtml(); + } else { + // download? + $html = ""; + } + return $html; + } + + /** + * Render media + * + * @param ilNewsItem + * @return string + */ + protected function renderMediaModal(ilNewsItem $i) + { + global $DIC; + + $media_path = $this->getMediaPath($i); + $mime = ilObjMediaObject::getMimeType($media_path); + + $ui_factory = $DIC->ui()->factory(); + $ui_renderer = $DIC->ui()->renderer(); + + $modal_html = ""; + + if (in_array($mime, array("image/jpeg", "image/svg+xml", "image/gif", "image/png"))) { + $title = basename($media_path); + $item_id = "il-news-modal-img-" . $i->getId(); + $image = $ui_renderer->render($ui_factory->image()->responsive($media_path, $title)); + $modal = ilModalGUI::getInstance(); + $modal->setId($item_id); + $modal->setType(ilModalGUI::TYPE_LARGE); + $modal->setBody($image); + $modal->setHeading($title); + $modal_html = $modal->getHTML(); + } + return $modal_html; + } + + + /** + * Render footer + * @throws ilCtrlException + */ + public function renderFooter() + { + $i = $this->getNewsItem(); + + // like + $this->ctrl->setParameterByClass("ilnewstimelinegui", "news_id", $i->getId()); + $this->like_gui->setObject( + $i->getContextObjId(), + $i->getContextObjType(), + $i->getContextSubObjId(), + $i->getContextSubObjType(), + $i->getId() + ); + $html = $this->ctrl->getHTML($this->like_gui); + + // comments + $notes_obj_type = ($i->getContextSubObjType() == "") + ? $i->getContextObjType() + : $i->getContextSubObjType(); + $note_gui = new ilNoteGUI( + $i->getContextObjId(), + $i->getContextSubObjId(), + $notes_obj_type, + false, + $i->getId() + ); + $note_gui->setDefaultCommand("getWidget"); + + //ilNoteGUI::getListCommentsJSCall($this->ajax_hash, $redraw_js) + $html.= $this->ctrl->getHTML($note_gui); + + $this->ctrl->setParameterByClass("ilnewstimelinegui", "news_id", $_GET["news_id"]); + + return $html . $this->renderMediaModal($i); + } + + /** + * @param ilNewsItem $i + * @return string + */ + protected function getMediaPath(ilNewsItem $i) + { + $media_path = ""; + if ($i->getMobId() > 0) { + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + include_once("./Services/MediaObjects/classes/class.ilMediaPlayerGUI.php"); + $mob = new ilObjMediaObject($i->getMobId()); + $med = $mob->getMediaItem("Standard"); + if (strcasecmp("Reference", $med->getLocationType()) == 0) { + $media_path = $med->getLocation(); + } else { + $media_path = ilObjMediaObject::_getURL($mob->getId()) . "/" . $med->getLocation(); + } + } + return $media_path; + } } - -?> \ No newline at end of file diff --git a/Services/News/classes/class.ilObjNewsSettings.php b/Services/News/classes/class.ilObjNewsSettings.php index 68c9bfbccccbbe90e1db41c3e092f1e93754705e..a3c36b9028844f1cb1d4d4c686d8e71a1efaa569 100755 --- a/Services/News/classes/class.ilObjNewsSettings.php +++ b/Services/News/classes/class.ilObjNewsSettings.php @@ -1,110 +1,105 @@ +* +* @author Alex Killing * @version $Id$ * * @ingroup ServicesNews */ class ilObjNewsSettings extends ilObject { - /** - * @var ilDB - */ - protected $db; - - - /** - * Constructor - * @access public - * @param integer reference_id or object_id - * @param boolean treat the id as reference_id (true) or object_id (false) - */ - function __construct($a_id = 0,$a_call_by_reference = true) - { - global $DIC; - - $this->db = $DIC->database(); - $this->type = "nwss"; - parent::__construct($a_id,$a_call_by_reference); - } + /** + * @var ilDB + */ + protected $db; - /** - * update object data - * - * @access public - * @return boolean - */ - function update() - { - $ilDB = $this->db; - - if (!parent::update()) - { - return false; - } + + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + global $DIC; - return true; - } - - /** - * read style folder data - */ - function read() - { - $ilDB = $this->db; + $this->db = $DIC->database(); + $this->type = "nwss"; + parent::__construct($a_id, $a_call_by_reference); + } - parent::read(); + /** + * update object data + * + * @access public + * @return boolean + */ + public function update() + { + $ilDB = $this->db; + + if (!parent::update()) { + return false; + } - } - + return true; + } + + /** + * read style folder data + */ + public function read() + { + $ilDB = $this->db; - - + parent::read(); + } + - /** - * delete object and all related data - * - * @access public - * @return boolean true if all object data were removed; false if only a references were removed - */ - function delete() - { - // always call parent delete function first!! - if (!parent::delete()) - { - return false; - } - - //put here your module specific stuff - - return true; - } + + + /** + * delete object and all related data + * + * @access public + * @return boolean true if all object data were removed; false if only a references were removed + */ + public function delete() + { + // always call parent delete function first!! + if (!parent::delete()) { + return false; + } + + //put here your module specific stuff + + return true; + } } -?> diff --git a/Services/News/classes/class.ilObjNewsSettingsAccess.php b/Services/News/classes/class.ilObjNewsSettingsAccess.php index e19c3e934d5edf9de10d0a48b16692ec53db693a..9e02b59bc503203dc6d60cc69b7971e130336db9 100755 --- a/Services/News/classes/class.ilObjNewsSettingsAccess.php +++ b/Services/News/classes/class.ilObjNewsSettingsAccess.php @@ -1,24 +1,24 @@ diff --git a/Services/News/classes/class.ilObjNewsSettingsGUI.php b/Services/News/classes/class.ilObjNewsSettingsGUI.php index a38bc472592e88d11cf99ffa73280352e2131ea6..386b2cc9b29877e49efd4d7530182202716f09f5 100755 --- a/Services/News/classes/class.ilObjNewsSettingsGUI.php +++ b/Services/News/classes/class.ilObjNewsSettingsGUI.php @@ -15,373 +15,381 @@ include_once("./Services/Object/classes/class.ilObjectGUI.php"); */ class ilObjNewsSettingsGUI extends ilObjectGUI { - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilSetting - */ - protected $settings; + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilSetting + */ + protected $settings; private static $ERROR_MESSAGE; - /** - * Contructor - * - * @access public - */ - public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) - { - global $DIC; - - $this->rbacsystem = $DIC->rbac()->system(); - $this->error = $DIC["ilErr"]; - $this->access = $DIC->access(); - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->settings = $DIC->settings(); - $this->type = 'nwss'; - parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); - - $this->lng->loadLanguageModule('news'); - $this->lng->loadLanguageModule('feed'); - - } - - /** - * Execute command - * - * @access public - * - */ - public function executeCommand() - { - $rbacsystem = $this->rbacsystem; - $ilErr = $this->error; - $ilAccess = $this->access; - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - $this->prepareOutput(); - - if(!$ilAccess->checkAccess('read','',$this->object->getRefId())) - { - $ilErr->raiseError($this->lng->txt('no_permission'),$ilErr->WARNING); - } - - switch($next_class) - { - case 'ilpermissiongui': - $this->tabs_gui->setTabActive('perm_settings'); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $ret = $this->ctrl->forwardCommand($perm_gui); - break; - - default: - if(!$cmd || $cmd == 'view') - { - $cmd = "editSettings"; - } - - $this->$cmd(); - break; - } - return true; - } - - /** - * Get tabs - * - * @access public - * - */ - public function getAdminTabs() - { - $rbacsystem = $this->rbacsystem; - $ilAccess = $this->access; - - if ($rbacsystem->checkAccess("visible,read",$this->object->getRefId())) - { - $this->tabs_gui->addTarget("news_edit_news_settings", - $this->ctrl->getLinkTarget($this, "editSettings"), - array("editSettings", "view")); - } - - if ($rbacsystem->checkAccess('edit_permission',$this->object->getRefId())) - { - $this->tabs_gui->addTarget("perm_settings", - $this->ctrl->getLinkTargetByClass('ilpermissiongui',"perm"), - array(),'ilpermissiongui'); - } - } - - /** - * Edit news settings. - */ - public function editSettings() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilSetting = $this->settings; - $ilAccess = $this->access; - - $news_set = new ilSetting("news"); - $feed_set = new ilSetting("feed"); - - $enable_internal_news = $ilSetting->get("block_activated_news"); - $enable_internal_rss = $news_set->get("enable_rss_for_internal"); - $rss_title_format = $news_set->get("rss_title_format"); - $enable_private_feed = $news_set->get("enable_private_feed"); - $news_default_visibility = ($news_set->get("default_visibility") != "") - ? $news_set->get("default_visibility") - : "users"; - $disable_repository_feeds = $feed_set->get("disable_rep_feeds"); - $nr_personal_desktop_feeds = $ilSetting->get("block_limit_pdfeed"); - - $allow_shorter_periods = $news_set->get("allow_shorter_periods"); - $allow_longer_periods = $news_set->get("allow_longer_periods"); - - include_once("./Services/News/classes/class.ilNewsItem.php"); - $rss_period = ilNewsItem::_lookupRSSPeriod(); - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this)); - $form->setTitle($lng->txt("news_settings")); - - // Enable internal news - $cb_prop = new ilCheckboxInputGUI($lng->txt("news_enable_internal_news"), - "enable_internal_news"); - $cb_prop->setValue("1"); - $cb_prop->setInfo($lng->txt("news_enable_internal_news_info")); - $cb_prop->setChecked($enable_internal_news); - $form->addItem($cb_prop); - - // Default Visibility - $radio_group = new ilRadioGroupInputGUI($lng->txt("news_default_visibility"), "news_default_visibility"); - $radio_option = new ilRadioOption($lng->txt("news_visibility_users"), "users"); - $radio_group->addOption($radio_option); - $radio_option = new ilRadioOption($lng->txt("news_visibility_public"), "public"); - $radio_group->addOption($radio_option); - $radio_group->setInfo($lng->txt("news_news_item_visibility_info")); - $radio_group->setRequired(false); - $radio_group->setValue($news_default_visibility); - $form->addItem($radio_group); - - // Number of news items per object - $nr_opts = array(50 => 50, 100 => 100, 200 => 200); - $nr_sel = new ilSelectInputGUI($lng->txt("news_nr_of_items"), - "news_max_items"); - $nr_sel->setInfo($lng->txt("news_nr_of_items_info")); - $nr_sel->setOptions($nr_opts); - $nr_sel->setValue($news_set->get("max_items")); - $form->addItem($nr_sel); - - // Access Cache - $min_opts = array(0 => 0, 1 => 1, 2 => 2, 5 => 5, 10 => 10, 20 => 20, 30 => 30, 60 => 60); - $min_sel = new ilSelectInputGUI($lng->txt("news_cache"), - "news_acc_cache_mins"); - $min_sel->setInfo($lng->txt("news_cache_info")); - $min_sel->setOptions($min_opts); - $min_sel->setValue($news_set->get("acc_cache_mins")); - $form->addItem($min_sel); - - // PD News Period - $per_opts = array( - 2 => "2 ".$lng->txt("days"), - 3 => "3 ".$lng->txt("days"), - 5 => "5 ".$lng->txt("days"), - 7 => "1 ".$lng->txt("week"), - 14 => "2 ".$lng->txt("weeks"), - 30 => "1 ".$lng->txt("month"), - 60 => "2 ".$lng->txt("months"), - 120 => "4 ".$lng->txt("months"), - 180 => "6 ".$lng->txt("months"), - 366 => "1 ".$lng->txt("year")); - $per_sel = new ilSelectInputGUI($lng->txt("news_pd_period"), - "news_pd_period"); - $per_sel->setInfo($lng->txt("news_pd_period_info")); - $per_sel->setOptions($per_opts); - $per_sel->setValue((int) ilNewsItem::_lookupDefaultPDPeriod()); - $form->addItem($per_sel); - - // Allow user to choose lower values - $sp_prop = new ilCheckboxInputGUI($lng->txt("news_allow_shorter_periods"), - "allow_shorter_periods"); - $sp_prop->setValue("1"); - $sp_prop->setInfo($lng->txt("news_allow_shorter_periods_info")); - $sp_prop->setChecked($allow_shorter_periods); - $form->addItem($sp_prop); - - // Allow user to choose higher values - $lp_prop = new ilCheckboxInputGUI($lng->txt("news_allow_longer_periods"), - "allow_longer_periods"); - $lp_prop->setValue("1"); - $lp_prop->setInfo($lng->txt("news_allow_longer_periods_info")); - $lp_prop->setChecked($allow_longer_periods); - $form->addItem($lp_prop); - - // Enable rss for internal news - $cb_prop = new ilCheckboxInputGUI($lng->txt("news_enable_internal_rss"), - "enable_internal_rss"); - $cb_prop->setValue("1"); - $cb_prop->setInfo($lng->txt("news_enable_internal_rss_info")); - $cb_prop->setChecked($enable_internal_rss); - - // RSS News Period - $rssp_opts = array( - 2 => "2 ".$lng->txt("days"), - 3 => "3 ".$lng->txt("days"), - 5 => "5 ".$lng->txt("days"), - 7 => "1 ".$lng->txt("week"), - 14 => "2 ".$lng->txt("weeks"), - 30 => "1 ".$lng->txt("month"), - 60 => "2 ".$lng->txt("months"), - 120 => "4 ".$lng->txt("months"), - 180 => "6 ".$lng->txt("months"), - 365 => "1 ".$lng->txt("year") - ); - $rssp_sel = new ilSelectInputGUI($lng->txt("news_rss_period"), - "news_rss_period"); - $rssp_sel->setOptions($rssp_opts); - $rssp_sel->setValue((int) $rss_period); - $cb_prop->addSubItem($rssp_sel); - - // Section Header: RSS - $sh = new ilFormSectionHeaderGUI(); - $sh->setTitle($lng->txt("news_rss")); - $form->addItem($sh); - - // title format for rss entries - $options = array( - "" => $lng->txt("news_rss_title_format_obj_news"), - "news_obj" => $lng->txt("news_rss_title_format_news_obj"), - ); - $si = new ilSelectInputGUI($lng->txt("news_rss_title_format"), "rss_title_format"); - $si->setOptions($options); - $si->setValue($rss_title_format); - $cb_prop->addSubItem($si); - - $form->addItem($cb_prop); - - // Enable private news feed - $cb_prop = new ilCheckboxInputGUI($lng->txt("news_enable_private_feed"), - "enable_private_feed"); - $cb_prop->setValue("1"); - $cb_prop->setInfo($lng->txt("news_enable_private_feed_info")); - $cb_prop->setChecked($enable_private_feed); - $form->addItem($cb_prop); - - - // Section Header: External Web Feeds Settings - $sh = new ilFormSectionHeaderGUI(); - $sh->setTitle($lng->txt("feed_settings")); - $form->addItem($sh); - - // Number of External Feeds on personal desktop - $sel = new ilSelectInputGUI($lng->txt("feed_nr_pd_feeds"), "nr_pd_feeds"); - $sel->setInfo($lng->txt("feed_nr_pd_feeds_info")); - $sel->setOptions(array(0 => "0", - 1 => "1", - 2 => "2", - 3 => "3", - 4 => "4", - 5 => "5")); - $sel->setValue($nr_personal_desktop_feeds); - $form->addItem($sel); - - // Disable External Web Feeds in catetegories - $cb_prop = new ilCheckboxInputGUI($lng->txt("feed_disable_rep_feeds"), - "disable_repository_feeds"); - $cb_prop->setValue("1"); - $cb_prop->setInfo($lng->txt("feed_disable_rep_feeds_info")); - $cb_prop->setChecked($disable_repository_feeds); - $form->addItem($cb_prop); - - if($ilAccess->checkAccess('write','',$this->object->getRefId())) - { - // command buttons - $form->addCommandButton("saveSettings", $lng->txt("save")); - $form->addCommandButton("view", $lng->txt("cancel")); - } - - $this->tpl->setContent($form->getHTML()); - } - - /** - * Save news and external webfeeds settings - */ - public function saveSettings() - { - $ilCtrl = $this->ctrl; - $ilSetting = $this->settings; - $ilAccess = $this->access; - - if(!$ilAccess->checkAccess('write','',$this->object->getRefId())) - { - $ilCtrl->redirect($this, "view"); - } - - // empty news cache - include_once("./Services/News/classes/class.ilNewsCache.php"); - $this->acache = new ilNewsCache(); - $this->acache->deleteAllEntries(); - - $news_set = new ilSetting("news"); - $feed_set = new ilSetting("feed"); - - - - $ilSetting->set("block_activated_news", $_POST["enable_internal_news"]); - $ilSetting->set("block_activated_pdnews", $_POST["enable_internal_news"]); - $news_set->set("enable_rss_for_internal", $_POST["enable_internal_rss"]); - $news_set->set("max_items", $_POST["news_max_items"]); - $news_set->set("acc_cache_mins", $_POST["news_acc_cache_mins"]); - $news_set->set("pd_period", $_POST["news_pd_period"]); - $news_set->set("default_visibility", $_POST["news_default_visibility"]); - $news_set->set("allow_shorter_periods", $_POST["allow_shorter_periods"]); - $news_set->set("allow_longer_periods", $_POST["allow_longer_periods"]); - $news_set->set("rss_period", $_POST["news_rss_period"]); - $news_set->set("rss_title_format", $_POST["rss_title_format"]); - - $feed_set->set("disable_rep_feeds", $_POST["disable_repository_feeds"]); - $ilSetting->set("block_limit_pdfeed", $_POST["nr_pd_feeds"]); - if ($_POST["nr_pd_feeds"] > 0) - { - $ilSetting->set("block_activated_pdfeed", 1); - } - else - { - $ilSetting->set("block_activated_pdfeed", 0); - } - - if ($_POST["enable_internal_rss"]!=0) - { - $news_set->set("enable_private_feed", $_POST["enable_private_feed"]); - } - else - { - $news_set->set("enable_private_feed", 0); - } - - ilUtil::sendSuccess($this->lng->txt("settings_saved"),true); - - $ilCtrl->redirect($this, "view"); - } - - + /** + * Contructor + * + * @access public + */ + public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) + { + global $DIC; + + $this->rbacsystem = $DIC->rbac()->system(); + $this->error = $DIC["ilErr"]; + $this->access = $DIC->access(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->settings = $DIC->settings(); + $this->type = 'nwss'; + parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); + + $this->lng->loadLanguageModule('news'); + $this->lng->loadLanguageModule('feed'); + } + + /** + * Execute command + * + * @access public + * + */ + public function executeCommand() + { + $rbacsystem = $this->rbacsystem; + $ilErr = $this->error; + $ilAccess = $this->access; + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + $this->prepareOutput(); + + if (!$ilAccess->checkAccess('read', '', $this->object->getRefId())) { + $ilErr->raiseError($this->lng->txt('no_permission'), $ilErr->WARNING); + } + + switch ($next_class) { + case 'ilpermissiongui': + $this->tabs_gui->setTabActive('perm_settings'); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $ret = $this->ctrl->forwardCommand($perm_gui); + break; + + default: + if (!$cmd || $cmd == 'view') { + $cmd = "editSettings"; + } + + $this->$cmd(); + break; + } + return true; + } + + /** + * Get tabs + * + * @access public + * + */ + public function getAdminTabs() + { + $rbacsystem = $this->rbacsystem; + $ilAccess = $this->access; + + if ($rbacsystem->checkAccess("visible,read", $this->object->getRefId())) { + $this->tabs_gui->addTarget( + "news_edit_news_settings", + $this->ctrl->getLinkTarget($this, "editSettings"), + array("editSettings", "view") + ); + } + + if ($rbacsystem->checkAccess('edit_permission', $this->object->getRefId())) { + $this->tabs_gui->addTarget( + "perm_settings", + $this->ctrl->getLinkTargetByClass('ilpermissiongui', "perm"), + array(), + 'ilpermissiongui' + ); + } + } + + /** + * Edit news settings. + */ + public function editSettings() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilSetting = $this->settings; + $ilAccess = $this->access; + + $news_set = new ilSetting("news"); + $feed_set = new ilSetting("feed"); + + $enable_internal_news = $ilSetting->get("block_activated_news"); + $enable_internal_rss = $news_set->get("enable_rss_for_internal"); + $rss_title_format = $news_set->get("rss_title_format"); + $enable_private_feed = $news_set->get("enable_private_feed"); + $news_default_visibility = ($news_set->get("default_visibility") != "") + ? $news_set->get("default_visibility") + : "users"; + $disable_repository_feeds = $feed_set->get("disable_rep_feeds"); + $nr_personal_desktop_feeds = $ilSetting->get("block_limit_pdfeed"); + + $allow_shorter_periods = $news_set->get("allow_shorter_periods"); + $allow_longer_periods = $news_set->get("allow_longer_periods"); + + include_once("./Services/News/classes/class.ilNewsItem.php"); + $rss_period = ilNewsItem::_lookupRSSPeriod(); + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this)); + $form->setTitle($lng->txt("news_settings")); + + // Enable internal news + $cb_prop = new ilCheckboxInputGUI( + $lng->txt("news_enable_internal_news"), + "enable_internal_news" + ); + $cb_prop->setValue("1"); + $cb_prop->setInfo($lng->txt("news_enable_internal_news_info")); + $cb_prop->setChecked($enable_internal_news); + $form->addItem($cb_prop); + + // Default Visibility + $radio_group = new ilRadioGroupInputGUI($lng->txt("news_default_visibility"), "news_default_visibility"); + $radio_option = new ilRadioOption($lng->txt("news_visibility_users"), "users"); + $radio_group->addOption($radio_option); + $radio_option = new ilRadioOption($lng->txt("news_visibility_public"), "public"); + $radio_group->addOption($radio_option); + $radio_group->setInfo($lng->txt("news_news_item_visibility_info")); + $radio_group->setRequired(false); + $radio_group->setValue($news_default_visibility); + $form->addItem($radio_group); + + // Number of news items per object + $nr_opts = array(50 => 50, 100 => 100, 200 => 200); + $nr_sel = new ilSelectInputGUI( + $lng->txt("news_nr_of_items"), + "news_max_items" + ); + $nr_sel->setInfo($lng->txt("news_nr_of_items_info")); + $nr_sel->setOptions($nr_opts); + $nr_sel->setValue($news_set->get("max_items")); + $form->addItem($nr_sel); + + // Access Cache + $min_opts = array(0 => 0, 1 => 1, 2 => 2, 5 => 5, 10 => 10, 20 => 20, 30 => 30, 60 => 60); + $min_sel = new ilSelectInputGUI( + $lng->txt("news_cache"), + "news_acc_cache_mins" + ); + $min_sel->setInfo($lng->txt("news_cache_info")); + $min_sel->setOptions($min_opts); + $min_sel->setValue($news_set->get("acc_cache_mins")); + $form->addItem($min_sel); + + // PD News Period + $per_opts = array( + 2 => "2 " . $lng->txt("days"), + 3 => "3 " . $lng->txt("days"), + 5 => "5 " . $lng->txt("days"), + 7 => "1 " . $lng->txt("week"), + 14 => "2 " . $lng->txt("weeks"), + 30 => "1 " . $lng->txt("month"), + 60 => "2 " . $lng->txt("months"), + 120 => "4 " . $lng->txt("months"), + 180 => "6 " . $lng->txt("months"), + 366 => "1 " . $lng->txt("year")); + $per_sel = new ilSelectInputGUI( + $lng->txt("news_pd_period"), + "news_pd_period" + ); + $per_sel->setInfo($lng->txt("news_pd_period_info")); + $per_sel->setOptions($per_opts); + $per_sel->setValue((int) ilNewsItem::_lookupDefaultPDPeriod()); + $form->addItem($per_sel); + + // Allow user to choose lower values + $sp_prop = new ilCheckboxInputGUI( + $lng->txt("news_allow_shorter_periods"), + "allow_shorter_periods" + ); + $sp_prop->setValue("1"); + $sp_prop->setInfo($lng->txt("news_allow_shorter_periods_info")); + $sp_prop->setChecked($allow_shorter_periods); + $form->addItem($sp_prop); + + // Allow user to choose higher values + $lp_prop = new ilCheckboxInputGUI( + $lng->txt("news_allow_longer_periods"), + "allow_longer_periods" + ); + $lp_prop->setValue("1"); + $lp_prop->setInfo($lng->txt("news_allow_longer_periods_info")); + $lp_prop->setChecked($allow_longer_periods); + $form->addItem($lp_prop); + + // Enable rss for internal news + $cb_prop = new ilCheckboxInputGUI( + $lng->txt("news_enable_internal_rss"), + "enable_internal_rss" + ); + $cb_prop->setValue("1"); + $cb_prop->setInfo($lng->txt("news_enable_internal_rss_info")); + $cb_prop->setChecked($enable_internal_rss); + + // RSS News Period + $rssp_opts = array( + 2 => "2 " . $lng->txt("days"), + 3 => "3 " . $lng->txt("days"), + 5 => "5 " . $lng->txt("days"), + 7 => "1 " . $lng->txt("week"), + 14 => "2 " . $lng->txt("weeks"), + 30 => "1 " . $lng->txt("month"), + 60 => "2 " . $lng->txt("months"), + 120 => "4 " . $lng->txt("months"), + 180 => "6 " . $lng->txt("months"), + 365 => "1 " . $lng->txt("year") + ); + $rssp_sel = new ilSelectInputGUI( + $lng->txt("news_rss_period"), + "news_rss_period" + ); + $rssp_sel->setOptions($rssp_opts); + $rssp_sel->setValue((int) $rss_period); + $cb_prop->addSubItem($rssp_sel); + + // Section Header: RSS + $sh = new ilFormSectionHeaderGUI(); + $sh->setTitle($lng->txt("news_rss")); + $form->addItem($sh); + + // title format for rss entries + $options = array( + "" => $lng->txt("news_rss_title_format_obj_news"), + "news_obj" => $lng->txt("news_rss_title_format_news_obj"), + ); + $si = new ilSelectInputGUI($lng->txt("news_rss_title_format"), "rss_title_format"); + $si->setOptions($options); + $si->setValue($rss_title_format); + $cb_prop->addSubItem($si); + + $form->addItem($cb_prop); + + // Enable private news feed + $cb_prop = new ilCheckboxInputGUI( + $lng->txt("news_enable_private_feed"), + "enable_private_feed" + ); + $cb_prop->setValue("1"); + $cb_prop->setInfo($lng->txt("news_enable_private_feed_info")); + $cb_prop->setChecked($enable_private_feed); + $form->addItem($cb_prop); + + + // Section Header: External Web Feeds Settings + $sh = new ilFormSectionHeaderGUI(); + $sh->setTitle($lng->txt("feed_settings")); + $form->addItem($sh); + + // Number of External Feeds on personal desktop + $sel = new ilSelectInputGUI($lng->txt("feed_nr_pd_feeds"), "nr_pd_feeds"); + $sel->setInfo($lng->txt("feed_nr_pd_feeds_info")); + $sel->setOptions(array(0 => "0", + 1 => "1", + 2 => "2", + 3 => "3", + 4 => "4", + 5 => "5")); + $sel->setValue($nr_personal_desktop_feeds); + $form->addItem($sel); + + // Disable External Web Feeds in catetegories + $cb_prop = new ilCheckboxInputGUI( + $lng->txt("feed_disable_rep_feeds"), + "disable_repository_feeds" + ); + $cb_prop->setValue("1"); + $cb_prop->setInfo($lng->txt("feed_disable_rep_feeds_info")); + $cb_prop->setChecked($disable_repository_feeds); + $form->addItem($cb_prop); + + if ($ilAccess->checkAccess('write', '', $this->object->getRefId())) { + // command buttons + $form->addCommandButton("saveSettings", $lng->txt("save")); + $form->addCommandButton("view", $lng->txt("cancel")); + } + + $this->tpl->setContent($form->getHTML()); + } + + /** + * Save news and external webfeeds settings + */ + public function saveSettings() + { + $ilCtrl = $this->ctrl; + $ilSetting = $this->settings; + $ilAccess = $this->access; + + if (!$ilAccess->checkAccess('write', '', $this->object->getRefId())) { + $ilCtrl->redirect($this, "view"); + } + + // empty news cache + include_once("./Services/News/classes/class.ilNewsCache.php"); + $this->acache = new ilNewsCache(); + $this->acache->deleteAllEntries(); + + $news_set = new ilSetting("news"); + $feed_set = new ilSetting("feed"); + + + + $ilSetting->set("block_activated_news", $_POST["enable_internal_news"]); + $ilSetting->set("block_activated_pdnews", $_POST["enable_internal_news"]); + $news_set->set("enable_rss_for_internal", $_POST["enable_internal_rss"]); + $news_set->set("max_items", $_POST["news_max_items"]); + $news_set->set("acc_cache_mins", $_POST["news_acc_cache_mins"]); + $news_set->set("pd_period", $_POST["news_pd_period"]); + $news_set->set("default_visibility", $_POST["news_default_visibility"]); + $news_set->set("allow_shorter_periods", $_POST["allow_shorter_periods"]); + $news_set->set("allow_longer_periods", $_POST["allow_longer_periods"]); + $news_set->set("rss_period", $_POST["news_rss_period"]); + $news_set->set("rss_title_format", $_POST["rss_title_format"]); + + $feed_set->set("disable_rep_feeds", $_POST["disable_repository_feeds"]); + $ilSetting->set("block_limit_pdfeed", $_POST["nr_pd_feeds"]); + if ($_POST["nr_pd_feeds"] > 0) { + $ilSetting->set("block_activated_pdfeed", 1); + } else { + $ilSetting->set("block_activated_pdfeed", 0); + } + + if ($_POST["enable_internal_rss"]!=0) { + $news_set->set("enable_private_feed", $_POST["enable_private_feed"]); + } else { + $news_set->set("enable_private_feed", 0); + } + + ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); + + $ilCtrl->redirect($this, "view"); + } } -?> \ No newline at end of file diff --git a/Services/News/classes/class.ilPDNewsBlockGUI.php b/Services/News/classes/class.ilPDNewsBlockGUI.php index 9bc80fea1f31d3f7315799abee4e4f63a4dc354f..1587218fab102220e4bcd2e2cb3e13de6d164f94 100755 --- a/Services/News/classes/class.ilPDNewsBlockGUI.php +++ b/Services/News/classes/class.ilPDNewsBlockGUI.php @@ -15,543 +15,531 @@ include_once("Services/News/classes/class.ilNewsForContextBlockGUI.php"); */ class ilPDNewsBlockGUI extends ilNewsForContextBlockGUI { - static $block_type = "pdnews"; - static $st_data; - protected $acc_results = false; - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - $this->access = $DIC->access(); - $this->ctrl = $DIC->ctrl(); - $this->settings = $DIC->settings(); - $lng = $DIC->language(); - $ilUser = $DIC->user(); - $ilAccess = $DIC->access(); - $this->obj_definition = $DIC["objDefinition"]; - - // NOT ilNewsForContextBlockGUI::__construct() ! - ilBlockGUI::__construct(); - - $lng->loadLanguageModule("news"); - include_once("./Services/News/classes/class.ilNewsItem.php"); - - $this->setLimit(5); - $this->setAvailableDetailLevels(3); - - $this->dynamic = false; - - include_once("./Services/News/classes/class.ilNewsCache.php"); - $this->acache = new ilNewsCache(); - $cres = unserialize($this->acache->getEntry($ilUser->getId().":0")); - $this->cache_hit = false; - if ($this->acache->getLastAccessStatus() == "hit" && is_array($cres)) - { - self::$st_data = ilNewsItem::prepareNewsDataFromCache($cres);; - $this->cache_hit = true; - } - - if ($this->getDynamic() && !$this->cache_hit) - { - $this->dynamic = true; - $data = array(); - } - else if ($this->getCurrentDetailLevel() > 0) - { - // do not ask two times for the data (e.g. if user displays a - // single item on the personal desktop and the news block is - // displayed at the same time) - if (empty(self::$st_data)) - { - self::$st_data = $this->getNewsData(); - $data = self::$st_data; - } - else - { - $data = self::$st_data; - } - } - else - { - $data = array(); - } - - $this->setTitle($lng->txt("news_internal_news")); - $this->setRowTemplate("tpl.block_row_news_for_context.html", "Services/News"); - - $this->setData($data); - - $this->handleView(); - - // reset access check results - $ilAccess->setResults($this->acc_results); - - } - - /** - * Get news for context - */ - function getNewsData() - { - $ilUser = $this->user; - - include_once("./Services/News/classes/class.ilNewsCache.php"); - $this->acache = new ilNewsCache(); - - $per = ilNewsItem::_lookupUserPDPeriod($ilUser->getId()); - $data = ilNewsItem::_getNewsItemsOfUser($ilUser->getId(), false, - false, $per); - - $this->acache->storeEntry($ilUser->getId().":0", - serialize($data)); - - return $data; - } - - /** - * @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() - { - global $DIC; - - $ilCtrl = $DIC->ctrl(); - - $cmd = $_GET["cmd"]; - if($cmd == "post" && is_array($_POST["cmd"])) - { - $cmd = array_pop(array_keys($_POST["cmd"])); - } - - switch($cmd) - { - case "showNews": - case "showFeedUrl": - case "editSettings": - case "changeFeedSettings": - return IL_SCREEN_CENTER; - - default: - 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(); - } - } - - /** - * Fill data section - */ - function fillDataSection() - { - - if ($this->dynamic) - { - $this->setDataSection($this->getDynamicReload()); - } - else if ($this->getCurrentDetailLevel() > 1 && count($this->getData()) > 0) - { - parent::fillDataSection(); - } - else - { - $this->setEnableNumInfo(false); - if (count($this->getData()) == 0) - { - $this->setEnableDetailRow(false); - } - $this->setDataSection($this->getOverview()); - } - } - - /** - * Get bloch HTML code. - */ - function getHTML() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilUser = $this->user; - - // set footer info - $this->setFooterInfo($lng->txt("news_block_information"), true); - - $news_set = new ilSetting("news"); - $enable_internal_rss = $news_set->get("enable_rss_for_internal"); - $allow_shorter_periods = $news_set->get("allow_shorter_periods"); - $allow_longer_periods = $news_set->get("allow_longer_periods"); - $enable_private_feed = $news_set->get("enable_private_feed"); - - // subscribe/unsibscribe link - include_once("./Services/News/classes/class.ilNewsSubscription.php"); - - // show feed url - if ($enable_internal_rss) - { - include_once("./Services/News/classes/class.ilRSSButtonGUI.php"); - $this->addBlockCommand( - $ilCtrl->getLinkTarget($this, "showFeedUrl"), - $lng->txt("news_get_feed_url"), "", "", true, false, ilRSSButtonGUI::get(ilRSSButtonGUI::ICON_RSS)); - } - - if ($allow_shorter_periods || $allow_longer_periods || $enable_private_feed) - { - $this->addBlockCommand( - $ilCtrl->getLinkTarget($this, "editSettings"), - $lng->txt("settings")); - } - - $per = ilNewsItem::_lookupUserPDPeriod($ilUser->getId()); - - if ($per > 0) - { - switch ($per) - { - case 2: - case 3: - case 5: $per_str = sprintf($lng->txt("news_period_x_days"), $per); break; - case 7: $per_str = $lng->txt("news_period_1_week"); break; - case 14: $per_str = sprintf($lng->txt("news_period_x_weeks"), 2); break; - case 30: $per_str = $lng->txt("news_period_1_month"); break; - case 60: $per_str = sprintf($lng->txt("news_period_x_months"), 2); break; - case 120: $per_str = sprintf($lng->txt("news_period_x_months"), 4); break; - case 180: $per_str = sprintf($lng->txt("news_period_x_months"), 6); break; - case 366: $per_str = $lng->txt("news_period_1_year"); break; - } - if ($per_str != "") - { - $this->setTitle($this->getTitle().' - '.$per_str.""); - } - } - - if ($this->getCurrentDetailLevel() == 0) - { - return ""; - } - - $en = ""; - if ($ilUser->getPref("il_feed_js") == "n") - { - $en = $this->getJSEnabler(); - } - - return ilBlockGUI::getHTML().$en; - } - - - /** - * Show feed URL. - */ - function showFeedUrl() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - $ilSetting = $this->settings; - - $news_set = new ilSetting("news"); - - - include_once("./Services/News/classes/class.ilNewsItem.php"); - - if ($news_set->get("enable_private_feed")) - { - $tpl = new ilTemplate("tpl.show_priv_feed_url.html", true, true, "Services/News"); - - $tpl->setVariable("TXT_PRIV_TITLE", $lng->txt("news_get_priv_feed_title")); - - // #14365 - if($ilUser->_getFeedPass($GLOBALS['DIC']['ilUser']->getId())) - { - $tpl->setVariable("TXT_PRIV_INFO", $lng->txt("news_get_priv_feed_info")); - $tpl->setVariable("TXT_PRIV_FEED_URL", $lng->txt("news_feed_url")); - $tpl->setVariable("VAL_PRIV_FEED_URL", - str_replace("://", "://" . $ilUser->getLogin() . ":-password-@", ILIAS_HTTP_PATH)."/privfeed.php?client_id=".rawurlencode(CLIENT_ID)."&user_id=".$ilUser->getId(). - "&hash=".ilObjUser::_lookupFeedHash($ilUser->getId(), true)); - $tpl->setVariable("VAL_PRIV_FEED_URL_TXT", - str_replace("://", "://" . $ilUser->getLogin() . ":-password-@", ILIAS_HTTP_PATH)."/privfeed.php?client_id=".rawurlencode(CLIENT_ID)."&
                  user_id=".$ilUser->getId(). - "&hash=".ilObjUser::_lookupFeedHash($ilUser->getId(), true)); - } - else - { - $tpl->setVariable("TXT_PRIV_INFO", $lng->txt("news_inactive_private_feed_info")); - $tpl->setVariable("EDIT_SETTINGS_URL", $ilCtrl->getLinkTarget($this, "editSettings")); - $tpl->setVariable("EDIT_SETTINGS_TXT", $lng->txt("news_edit_news_settings")); - } - } - else - { - $tpl = new ilTemplate("tpl.show_feed_url.html", true, true, "Services/News"); - } - $tpl->setVariable("TXT_TITLE", $lng->txt("news_get_feed_title")); - $tpl->setVariable("TXT_INFO", $lng->txt("news_get_feed_info")); - $tpl->setVariable("TXT_FEED_URL", $lng->txt("news_feed_url")); - $tpl->setVariable("VAL_FEED_URL", - ILIAS_HTTP_PATH."/feed.php?client_id=".rawurlencode(CLIENT_ID)."&user_id=".$ilUser->getId(). - "&hash=".ilObjUser::_lookupFeedHash($ilUser->getId(), true)); - $tpl->setVariable("VAL_FEED_URL_TXT", - ILIAS_HTTP_PATH."/feed.php?client_id=".rawurlencode(CLIENT_ID)."&
                  user_id=".$ilUser->getId(). - "&hash=".ilObjUser::_lookupFeedHash($ilUser->getId(), true)); - - include_once("./Services/PersonalDesktop/classes/class.ilPDContentBlockGUI.php"); - $content_block = new ilPDContentBlockGUI(); - $content_block->setContent($tpl->get()); - $content_block->setTitle($lng->txt("news_internal_news")); - $content_block->addHeaderCommand($ilCtrl->getParentReturn($this), - $lng->txt("selected_items_back")); - - return $content_block->getHTML(); - } - - function addCloseCommand($a_content_block) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $a_content_block->addHeaderCommand($ilCtrl->getParentReturn($this), - $lng->txt("selected_items_back")); - } - - - /** - * show news - */ - function showNews() - { - // workaround for dynamic mode (if cache is disabled, showNews has no data) -// if (empty(self::$st_data)) -// { -// $this->setData($this->getNewsData()); -// } - - return parent::showNews(); - } - - /** - * Show settings screen. - */ - function editSettings(ilPropertyFormGUI $a_private_form = null) - { - $ilUser = $this->user; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilSetting = $this->settings; - - $news_set = new ilSetting("news"); - $enable_internal_rss = $news_set->get("enable_rss_for_internal"); - $allow_shorter_periods = $news_set->get("allow_shorter_periods"); - $allow_longer_periods = $news_set->get("allow_longer_periods"); - $enable_private_feed = $news_set->get("enable_private_feed"); - - if (!$a_private_form && ($allow_shorter_periods || $allow_longer_periods)) - { - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormaction($this)); - $form->setTitle($lng->txt("news_settings")); - - include_once("./Services/News/classes/class.ilNewsItem.php"); - $default_per = ilNewsItem::_lookupDefaultPDPeriod(); - $per = ilNewsItem::_lookupUserPDPeriod($ilUser->getId()); - - $form->setTableWidth("100%"); - - $per_opts = array( - 2 => "2 ".$lng->txt("days"), - 3 => "3 ".$lng->txt("days"), - 5 => "5 ".$lng->txt("days"), - 7 => "1 ".$lng->txt("week"), - 14 => "2 ".$lng->txt("weeks"), - 30 => "1 ".$lng->txt("month"), - 60 => "2 ".$lng->txt("months"), - 120 => "4 ".$lng->txt("months"), - 180 => "6 ".$lng->txt("months"), - 366 => "1 ".$lng->txt("year")); - - $unset = array(); - foreach($per_opts as $k => $opt) - { - if (!$allow_shorter_periods && ($k < $default_per)) $unset[$k] = $k; - if (!$allow_longer_periods && ($k > $default_per)) $unset[$k] = $k; - } - foreach($unset as $k) - { - unset($per_opts[$k]); - } - - $per_sel = new ilSelectInputGUI($lng->txt("news_pd_period"), - "news_pd_period"); - //$per_sel->setInfo($lng->txt("news_pd_period_info")); - $per_sel->setOptions($per_opts); - $per_sel->setValue((int) $per); - $form->addItem($per_sel); - - //$form->addCheckboxProperty($lng->txt("news_public_feed"), "notifications_public_feed", - // "1", $public_feed, $lng->txt("news_public_feed_info")); - //if ($this->getProperty("public_notifications_option")) - //{ - // $form->addCheckboxProperty($lng->txt("news_notifications_public"), "notifications_public", - // "1", $public, $lng->txt("news_notifications_public_info")); - //} - $form->addCommandButton("saveSettings", $lng->txt("save")); - $form->addCommandButton("cancelSettings", $lng->txt("cancel")); - - $returnForm = $form->getHTML(); - } - - if ($enable_private_feed) - { - if(!$a_private_form) - { - $a_private_form = $this->initPrivateSettingsForm(); - } - $returnForm .= ($returnForm=="") - ? $a_private_form->getHTML() - : "
                  ".$a_private_form->getHTML(); - } - - return $returnForm; - } - - protected function initPrivateSettingsForm() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilUser = $this->user; - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $feed_form = new ilPropertyFormGUI(); - $feed_form->setFormAction($ilCtrl->getFormaction($this)); - $feed_form->setTitle($lng->txt("priv_feed_settings")); - - $feed_form->setTableWidth("100%"); - - $enable_private_feed = new ilCheckboxInputGUI($lng->txt("news_enable_private_feed"), "enable_private_feed"); - $enable_private_feed->setChecked($ilUser->_getFeedPass($ilUser->getId())); - $feed_form->addItem($enable_private_feed); - - $passwd = new ilPasswordInputGUI($lng->txt("password"), "desired_password"); - $passwd->setRequired(true); - $passwd->setInfo(ilUtil::getPasswordRequirementsInfo()); - $enable_private_feed->addSubItem($passwd); - - $feed_form->addCommandButton("changeFeedSettings", $lng->txt("save")); - $feed_form->addCommandButton("cancelSettings", $lng->txt("cancel")); - - return $feed_form; - } - - /** - * Cancel settings. - */ - function cancelSettings() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->returnToParent($this); - } - - /** - * Save settings. - */ - function saveSettings() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - $news_set = new ilSetting("news"); - $enable_internal_rss = $news_set->get("enable_rss_for_internal"); - - ilBlockSetting::_write($this->getBlockType(), "news_pd_period", - $_POST["news_pd_period"], - $ilUser->getId(), $this->block_id); - - include_once("./Services/News/classes/class.ilNewsCache.php"); - $cache = new ilNewsCache(); - $cache->deleteEntry($ilUser->getId().":0"); - - $ilCtrl->returnToParent($this); - } - - /** - * change user password - */ - function changeFeedSettings() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilUser = $this->user; - - $form = $this->initPrivateSettingsForm(); - if($form->checkInput()) - { - // Deactivate private Feed - just delete the password - if (!$form->getInput("enable_private_feed")) - { - $ilUser->_setFeedPass($ilUser->getId(), ""); - ilUtil::sendSuccess($lng->txt("priv_feed_disabled"),true); - // $ilCtrl->returnToParent($this); - $ilCtrl->redirect($this, "showFeedUrl"); - } - else - { - $passwd = $form->getInput("desired_password"); - require_once 'Services/User/classes/class.ilUserPasswordManager.php'; - if(ilUserPasswordManager::getInstance()->verifyPassword($ilUser, $passwd)) - { - $form->getItemByPostVar("desired_password")->setAlert($lng->txt("passwd_equals_ilpasswd")); - ilUtil::sendFailure($lng->txt("form_input_not_valid")); - } - else - { - $ilUser->_setFeedPass($ilUser->getId(), $passwd); - ilUtil::sendSuccess($lng->txt("saved_successfully"),true); - // $ilCtrl->returnToParent($this); - $ilCtrl->redirect($this, "showFeedUrl"); - } - } - } - - $form->setValuesByPost(); - return $this->editSettings($form); - } - + public static $block_type = "pdnews"; + public static $st_data; + protected $acc_results = false; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + $this->access = $DIC->access(); + $this->ctrl = $DIC->ctrl(); + $this->settings = $DIC->settings(); + $lng = $DIC->language(); + $ilUser = $DIC->user(); + $ilAccess = $DIC->access(); + $this->obj_definition = $DIC["objDefinition"]; + + // NOT ilNewsForContextBlockGUI::__construct() ! + ilBlockGUI::__construct(); + + $lng->loadLanguageModule("news"); + include_once("./Services/News/classes/class.ilNewsItem.php"); + + $this->setLimit(5); + $this->setAvailableDetailLevels(3); + + $this->dynamic = false; + + include_once("./Services/News/classes/class.ilNewsCache.php"); + $this->acache = new ilNewsCache(); + $cres = unserialize($this->acache->getEntry($ilUser->getId() . ":0")); + $this->cache_hit = false; + if ($this->acache->getLastAccessStatus() == "hit" && is_array($cres)) { + self::$st_data = ilNewsItem::prepareNewsDataFromCache($cres); + ; + $this->cache_hit = true; + } + + if ($this->getDynamic() && !$this->cache_hit) { + $this->dynamic = true; + $data = array(); + } elseif ($this->getCurrentDetailLevel() > 0) { + // do not ask two times for the data (e.g. if user displays a + // single item on the personal desktop and the news block is + // displayed at the same time) + if (empty(self::$st_data)) { + self::$st_data = $this->getNewsData(); + $data = self::$st_data; + } else { + $data = self::$st_data; + } + } else { + $data = array(); + } + + $this->setTitle($lng->txt("news_internal_news")); + $this->setRowTemplate("tpl.block_row_news_for_context.html", "Services/News"); + + $this->setData($data); + + $this->handleView(); + + // reset access check results + $ilAccess->setResults($this->acc_results); + } + + /** + * Get news for context + */ + public function getNewsData() + { + $ilUser = $this->user; + + include_once("./Services/News/classes/class.ilNewsCache.php"); + $this->acache = new ilNewsCache(); + + $per = ilNewsItem::_lookupUserPDPeriod($ilUser->getId()); + $data = ilNewsItem::_getNewsItemsOfUser( + $ilUser->getId(), + false, + false, + $per + ); + + $this->acache->storeEntry( + $ilUser->getId() . ":0", + serialize($data) + ); + + return $data; + } + + /** + * @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() + { + global $DIC; + + $ilCtrl = $DIC->ctrl(); + + $cmd = $_GET["cmd"]; + if ($cmd == "post" && is_array($_POST["cmd"])) { + $cmd = array_pop(array_keys($_POST["cmd"])); + } + + switch ($cmd) { + case "showNews": + case "showFeedUrl": + case "editSettings": + case "changeFeedSettings": + return IL_SCREEN_CENTER; + + default: + 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(); + } + } + + /** + * Fill data section + */ + public function fillDataSection() + { + if ($this->dynamic) { + $this->setDataSection($this->getDynamicReload()); + } elseif ($this->getCurrentDetailLevel() > 1 && count($this->getData()) > 0) { + parent::fillDataSection(); + } else { + $this->setEnableNumInfo(false); + if (count($this->getData()) == 0) { + $this->setEnableDetailRow(false); + } + $this->setDataSection($this->getOverview()); + } + } + + /** + * Get bloch HTML code. + */ + public function getHTML() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilUser = $this->user; + + // set footer info + $this->setFooterInfo($lng->txt("news_block_information"), true); + + $news_set = new ilSetting("news"); + $enable_internal_rss = $news_set->get("enable_rss_for_internal"); + $allow_shorter_periods = $news_set->get("allow_shorter_periods"); + $allow_longer_periods = $news_set->get("allow_longer_periods"); + $enable_private_feed = $news_set->get("enable_private_feed"); + + // subscribe/unsibscribe link + include_once("./Services/News/classes/class.ilNewsSubscription.php"); + + // show feed url + if ($enable_internal_rss) { + include_once("./Services/News/classes/class.ilRSSButtonGUI.php"); + $this->addBlockCommand( + $ilCtrl->getLinkTarget($this, "showFeedUrl"), + $lng->txt("news_get_feed_url"), + "", + "", + true, + false, + ilRSSButtonGUI::get(ilRSSButtonGUI::ICON_RSS) + ); + } + + if ($allow_shorter_periods || $allow_longer_periods || $enable_private_feed) { + $this->addBlockCommand( + $ilCtrl->getLinkTarget($this, "editSettings"), + $lng->txt("settings") + ); + } + + $per = ilNewsItem::_lookupUserPDPeriod($ilUser->getId()); + + if ($per > 0) { + switch ($per) { + case 2: + case 3: + case 5: $per_str = sprintf($lng->txt("news_period_x_days"), $per); break; + case 7: $per_str = $lng->txt("news_period_1_week"); break; + case 14: $per_str = sprintf($lng->txt("news_period_x_weeks"), 2); break; + case 30: $per_str = $lng->txt("news_period_1_month"); break; + case 60: $per_str = sprintf($lng->txt("news_period_x_months"), 2); break; + case 120: $per_str = sprintf($lng->txt("news_period_x_months"), 4); break; + case 180: $per_str = sprintf($lng->txt("news_period_x_months"), 6); break; + case 366: $per_str = $lng->txt("news_period_1_year"); break; + } + if ($per_str != "") { + $this->setTitle($this->getTitle() . ' - ' . $per_str . ""); + } + } + + if ($this->getCurrentDetailLevel() == 0) { + return ""; + } + + $en = ""; + if ($ilUser->getPref("il_feed_js") == "n") { + $en = $this->getJSEnabler(); + } + + return ilBlockGUI::getHTML() . $en; + } + + + /** + * Show feed URL. + */ + public function showFeedUrl() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + $ilSetting = $this->settings; + + $news_set = new ilSetting("news"); + + + include_once("./Services/News/classes/class.ilNewsItem.php"); + + if ($news_set->get("enable_private_feed")) { + $tpl = new ilTemplate("tpl.show_priv_feed_url.html", true, true, "Services/News"); + + $tpl->setVariable("TXT_PRIV_TITLE", $lng->txt("news_get_priv_feed_title")); + + // #14365 + if ($ilUser->_getFeedPass($GLOBALS['DIC']['ilUser']->getId())) { + $tpl->setVariable("TXT_PRIV_INFO", $lng->txt("news_get_priv_feed_info")); + $tpl->setVariable("TXT_PRIV_FEED_URL", $lng->txt("news_feed_url")); + $tpl->setVariable( + "VAL_PRIV_FEED_URL", + str_replace("://", "://" . $ilUser->getLogin() . ":-password-@", ILIAS_HTTP_PATH) . "/privfeed.php?client_id=" . rawurlencode(CLIENT_ID) . "&user_id=" . $ilUser->getId() . + "&hash=" . ilObjUser::_lookupFeedHash($ilUser->getId(), true) + ); + $tpl->setVariable( + "VAL_PRIV_FEED_URL_TXT", + str_replace("://", "://" . $ilUser->getLogin() . ":-password-@", ILIAS_HTTP_PATH) . "/privfeed.php?client_id=" . rawurlencode(CLIENT_ID) . "&
                  user_id=" . $ilUser->getId() . + "&hash=" . ilObjUser::_lookupFeedHash($ilUser->getId(), true) + ); + } else { + $tpl->setVariable("TXT_PRIV_INFO", $lng->txt("news_inactive_private_feed_info")); + $tpl->setVariable("EDIT_SETTINGS_URL", $ilCtrl->getLinkTarget($this, "editSettings")); + $tpl->setVariable("EDIT_SETTINGS_TXT", $lng->txt("news_edit_news_settings")); + } + } else { + $tpl = new ilTemplate("tpl.show_feed_url.html", true, true, "Services/News"); + } + $tpl->setVariable("TXT_TITLE", $lng->txt("news_get_feed_title")); + $tpl->setVariable("TXT_INFO", $lng->txt("news_get_feed_info")); + $tpl->setVariable("TXT_FEED_URL", $lng->txt("news_feed_url")); + $tpl->setVariable( + "VAL_FEED_URL", + ILIAS_HTTP_PATH . "/feed.php?client_id=" . rawurlencode(CLIENT_ID) . "&user_id=" . $ilUser->getId() . + "&hash=" . ilObjUser::_lookupFeedHash($ilUser->getId(), true) + ); + $tpl->setVariable( + "VAL_FEED_URL_TXT", + ILIAS_HTTP_PATH . "/feed.php?client_id=" . rawurlencode(CLIENT_ID) . "&
                  user_id=" . $ilUser->getId() . + "&hash=" . ilObjUser::_lookupFeedHash($ilUser->getId(), true) + ); + + include_once("./Services/PersonalDesktop/classes/class.ilPDContentBlockGUI.php"); + $content_block = new ilPDContentBlockGUI(); + $content_block->setContent($tpl->get()); + $content_block->setTitle($lng->txt("news_internal_news")); + $content_block->addHeaderCommand( + $ilCtrl->getParentReturn($this), + $lng->txt("selected_items_back") + ); + + return $content_block->getHTML(); + } + + public function addCloseCommand($a_content_block) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $a_content_block->addHeaderCommand( + $ilCtrl->getParentReturn($this), + $lng->txt("selected_items_back") + ); + } + + + /** + * show news + */ + public function showNews() + { + // workaround for dynamic mode (if cache is disabled, showNews has no data) + // if (empty(self::$st_data)) + // { + // $this->setData($this->getNewsData()); + // } + + return parent::showNews(); + } + + /** + * Show settings screen. + */ + public function editSettings(ilPropertyFormGUI $a_private_form = null) + { + $ilUser = $this->user; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilSetting = $this->settings; + + $news_set = new ilSetting("news"); + $enable_internal_rss = $news_set->get("enable_rss_for_internal"); + $allow_shorter_periods = $news_set->get("allow_shorter_periods"); + $allow_longer_periods = $news_set->get("allow_longer_periods"); + $enable_private_feed = $news_set->get("enable_private_feed"); + + if (!$a_private_form && ($allow_shorter_periods || $allow_longer_periods)) { + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormaction($this)); + $form->setTitle($lng->txt("news_settings")); + + include_once("./Services/News/classes/class.ilNewsItem.php"); + $default_per = ilNewsItem::_lookupDefaultPDPeriod(); + $per = ilNewsItem::_lookupUserPDPeriod($ilUser->getId()); + + $form->setTableWidth("100%"); + + $per_opts = array( + 2 => "2 " . $lng->txt("days"), + 3 => "3 " . $lng->txt("days"), + 5 => "5 " . $lng->txt("days"), + 7 => "1 " . $lng->txt("week"), + 14 => "2 " . $lng->txt("weeks"), + 30 => "1 " . $lng->txt("month"), + 60 => "2 " . $lng->txt("months"), + 120 => "4 " . $lng->txt("months"), + 180 => "6 " . $lng->txt("months"), + 366 => "1 " . $lng->txt("year")); + + $unset = array(); + foreach ($per_opts as $k => $opt) { + if (!$allow_shorter_periods && ($k < $default_per)) { + $unset[$k] = $k; + } + if (!$allow_longer_periods && ($k > $default_per)) { + $unset[$k] = $k; + } + } + foreach ($unset as $k) { + unset($per_opts[$k]); + } + + $per_sel = new ilSelectInputGUI( + $lng->txt("news_pd_period"), + "news_pd_period" + ); + //$per_sel->setInfo($lng->txt("news_pd_period_info")); + $per_sel->setOptions($per_opts); + $per_sel->setValue((int) $per); + $form->addItem($per_sel); + + //$form->addCheckboxProperty($lng->txt("news_public_feed"), "notifications_public_feed", + // "1", $public_feed, $lng->txt("news_public_feed_info")); + //if ($this->getProperty("public_notifications_option")) + //{ + // $form->addCheckboxProperty($lng->txt("news_notifications_public"), "notifications_public", + // "1", $public, $lng->txt("news_notifications_public_info")); + //} + $form->addCommandButton("saveSettings", $lng->txt("save")); + $form->addCommandButton("cancelSettings", $lng->txt("cancel")); + + $returnForm = $form->getHTML(); + } + + if ($enable_private_feed) { + if (!$a_private_form) { + $a_private_form = $this->initPrivateSettingsForm(); + } + $returnForm .= ($returnForm=="") + ? $a_private_form->getHTML() + : "
                  " . $a_private_form->getHTML(); + } + + return $returnForm; + } + + protected function initPrivateSettingsForm() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilUser = $this->user; + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $feed_form = new ilPropertyFormGUI(); + $feed_form->setFormAction($ilCtrl->getFormaction($this)); + $feed_form->setTitle($lng->txt("priv_feed_settings")); + + $feed_form->setTableWidth("100%"); + + $enable_private_feed = new ilCheckboxInputGUI($lng->txt("news_enable_private_feed"), "enable_private_feed"); + $enable_private_feed->setChecked($ilUser->_getFeedPass($ilUser->getId())); + $feed_form->addItem($enable_private_feed); + + $passwd = new ilPasswordInputGUI($lng->txt("password"), "desired_password"); + $passwd->setRequired(true); + $passwd->setInfo(ilUtil::getPasswordRequirementsInfo()); + $enable_private_feed->addSubItem($passwd); + + $feed_form->addCommandButton("changeFeedSettings", $lng->txt("save")); + $feed_form->addCommandButton("cancelSettings", $lng->txt("cancel")); + + return $feed_form; + } + + /** + * Cancel settings. + */ + public function cancelSettings() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->returnToParent($this); + } + + /** + * Save settings. + */ + public function saveSettings() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + $news_set = new ilSetting("news"); + $enable_internal_rss = $news_set->get("enable_rss_for_internal"); + + ilBlockSetting::_write( + $this->getBlockType(), + "news_pd_period", + $_POST["news_pd_period"], + $ilUser->getId(), + $this->block_id + ); + + include_once("./Services/News/classes/class.ilNewsCache.php"); + $cache = new ilNewsCache(); + $cache->deleteEntry($ilUser->getId() . ":0"); + + $ilCtrl->returnToParent($this); + } + + /** + * change user password + */ + public function changeFeedSettings() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilUser = $this->user; + + $form = $this->initPrivateSettingsForm(); + if ($form->checkInput()) { + // Deactivate private Feed - just delete the password + if (!$form->getInput("enable_private_feed")) { + $ilUser->_setFeedPass($ilUser->getId(), ""); + ilUtil::sendSuccess($lng->txt("priv_feed_disabled"), true); + // $ilCtrl->returnToParent($this); + $ilCtrl->redirect($this, "showFeedUrl"); + } else { + $passwd = $form->getInput("desired_password"); + require_once 'Services/User/classes/class.ilUserPasswordManager.php'; + if (ilUserPasswordManager::getInstance()->verifyPassword($ilUser, $passwd)) { + $form->getItemByPostVar("desired_password")->setAlert($lng->txt("passwd_equals_ilpasswd")); + ilUtil::sendFailure($lng->txt("form_input_not_valid")); + } else { + $ilUser->_setFeedPass($ilUser->getId(), $passwd); + ilUtil::sendSuccess($lng->txt("saved_successfully"), true); + // $ilCtrl->returnToParent($this); + $ilCtrl->redirect($this, "showFeedUrl"); + } + } + } + + $form->setValuesByPost(); + return $this->editSettings($form); + } } - -?> diff --git a/Services/News/classes/class.ilPDNewsGUI.php b/Services/News/classes/class.ilPDNewsGUI.php index 69de222c8e6bdbf2b5ec1f6312cd08f300ef829a..d8bcf9e7180517bc1dc1bd0ca2d092d199c29b4a 100755 --- a/Services/News/classes/class.ilPDNewsGUI.php +++ b/Services/News/classes/class.ilPDNewsGUI.php @@ -14,199 +14,199 @@ class ilPDNewsGUI { - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilHelpGUI - */ - protected $help; - - /** - * @var ilObjUser - */ - protected $user; - - - /** - * Constructor - * - * @access public - */ - function __construct() - { - global $DIC; - - $this->help = $DIC["ilHelp"]; - $this->user = $DIC->user(); - $tpl = $DIC["tpl"]; - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $ilHelp = $DIC["ilHelp"]; - - $ilHelp->setScreenIdComponent("news"); - - // initiate variables - $this->tpl = $tpl; - $this->lng = $lng; - $this->ctrl = $ilCtrl; - - $lng->loadLanguageModule("news"); - - $this->ctrl->saveParameter($this, "news_ref_id"); - } - - /** - * execute command - */ - function executeCommand() - { - $next_class = $this->ctrl->getNextClass(); - - switch($next_class) - { - - default: - $cmd = $this->ctrl->getCmd("view"); - $this->displayHeader(); - $this->$cmd(); - break; - } - $this->tpl->show(true); - return true; - } - - /** - * display header and locator - */ - function displayHeader() - { - $this->tpl->setTitle($this->lng->txt("news")); - - // display infopanel if something happened - ilUtil::infoPanel(); - } - - /* - * display notes - */ - function view() - { - $ilUser = $this->user; - $lng = $this->lng; - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - - $ref_ids = array(); - $obj_ids = array(); - $pd_items = $ilUser->getDesktopItems(); - foreach($pd_items as $item) - { - $ref_ids[] = $item["ref_id"]; - $obj_ids[] = $item["obj_id"]; - } - - $sel_ref_id = ($_GET["news_ref_id"] > 0) - ? $_GET["news_ref_id"] - : $ilUser->getPref("news_sel_ref_id"); - - include_once("./Services/News/classes/class.ilNewsItem.php"); - $per = ($_SESSION["news_pd_news_per"] != "") - ? $_SESSION["news_pd_news_per"] - : ilNewsItem::_lookupUserPDPeriod($ilUser->getId()); - $news_obj_ids = ilNewsItem::filterObjIdsPerNews($obj_ids, $per); - - // related objects (contexts) of news - $contexts[0] = $lng->txt("news_all_items"); - - $conts = array(); - $sel_has_news = false; - foreach ($ref_ids as $ref_id) - { - $obj_id = ilObject::_lookupObjId($ref_id); - $title = ilObject::_lookupTitle($obj_id); - - $conts[$ref_id] = $title; - if ($sel_ref_id == $ref_id) - { - $sel_has_news = true; - } - } - - $cnt = array(); - $nitem = new ilNewsItem(); - $news_items = $nitem->_getNewsItemsOfUser($ilUser->getId(), false, - true, $per, $cnt); - - // reset selected news ref id, if no news are given for id - if (!$sel_has_news) - { - $sel_ref_id = ""; - } - asort($conts); - foreach($conts as $ref_id => $title) - { - $contexts[$ref_id] = $title." (".(int) $cnt[$ref_id].")"; - } - - - if ($sel_ref_id > 0) - { - $obj_id = ilObject::_lookupObjId($sel_ref_id); - $obj_type = ilObject::_lookupType($obj_id); - $nitem->setContextObjId($obj_id); - $nitem->setContextObjType($obj_type); - $news_items = $nitem->getNewsForRefId($sel_ref_id, false, - false, $per, true); - } - - include_once("./Services/News/classes/class.ilPDNewsTableGUI.php"); - $pd_news_table = new ilPDNewsTableGUI($this, "view", $contexts, $sel_ref_id); - $pd_news_table->setData($news_items); - $pd_news_table->setNoEntriesText($lng->txt("news_no_news_items")); - - $tpl->setContent($pd_news_table->getHTML()); - } - - /** - * change related object - */ - function applyFilter() - { - $ilUser = $this->user; - - $this->ctrl->setParameter($this, "news_ref_id", $_POST["news_ref_id"]); - $ilUser->writePref("news_sel_ref_id", $_POST["news_ref_id"]); - if ($_POST["news_per"] > 0) - { - $_SESSION["news_pd_news_per"] = $_POST["news_per"]; - } - $this->ctrl->redirect($this, "view"); - } - - /** - * reset filter - */ - function resetFilter() - { - $ilUser = $this->user; - $this->ctrl->setParameter($this, "news_ref_id", 0); - $ilUser->writePref("news_sel_ref_id", 0); - $_SESSION["news_pd_news_per"] = ""; - $this->ctrl->redirect($this, "view"); - } - + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var ilObjUser + */ + protected $user; + + + /** + * Constructor + * + * @access public + */ + public function __construct() + { + global $DIC; + + $this->help = $DIC["ilHelp"]; + $this->user = $DIC->user(); + $tpl = $DIC["tpl"]; + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $ilHelp = $DIC["ilHelp"]; + + $ilHelp->setScreenIdComponent("news"); + + // initiate variables + $this->tpl = $tpl; + $this->lng = $lng; + $this->ctrl = $ilCtrl; + + $lng->loadLanguageModule("news"); + + $this->ctrl->saveParameter($this, "news_ref_id"); + } + + /** + * execute command + */ + public function executeCommand() + { + $next_class = $this->ctrl->getNextClass(); + + switch ($next_class) { + + default: + $cmd = $this->ctrl->getCmd("view"); + $this->displayHeader(); + $this->$cmd(); + break; + } + $this->tpl->show(true); + return true; + } + + /** + * display header and locator + */ + public function displayHeader() + { + $this->tpl->setTitle($this->lng->txt("news")); + + // display infopanel if something happened + ilUtil::infoPanel(); + } + + /* + * display notes + */ + public function view() + { + $ilUser = $this->user; + $lng = $this->lng; + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + + $ref_ids = array(); + $obj_ids = array(); + $pd_items = $ilUser->getDesktopItems(); + foreach ($pd_items as $item) { + $ref_ids[] = $item["ref_id"]; + $obj_ids[] = $item["obj_id"]; + } + + $sel_ref_id = ($_GET["news_ref_id"] > 0) + ? $_GET["news_ref_id"] + : $ilUser->getPref("news_sel_ref_id"); + + include_once("./Services/News/classes/class.ilNewsItem.php"); + $per = ($_SESSION["news_pd_news_per"] != "") + ? $_SESSION["news_pd_news_per"] + : ilNewsItem::_lookupUserPDPeriod($ilUser->getId()); + $news_obj_ids = ilNewsItem::filterObjIdsPerNews($obj_ids, $per); + + // related objects (contexts) of news + $contexts[0] = $lng->txt("news_all_items"); + + $conts = array(); + $sel_has_news = false; + foreach ($ref_ids as $ref_id) { + $obj_id = ilObject::_lookupObjId($ref_id); + $title = ilObject::_lookupTitle($obj_id); + + $conts[$ref_id] = $title; + if ($sel_ref_id == $ref_id) { + $sel_has_news = true; + } + } + + $cnt = array(); + $nitem = new ilNewsItem(); + $news_items = $nitem->_getNewsItemsOfUser( + $ilUser->getId(), + false, + true, + $per, + $cnt + ); + + // reset selected news ref id, if no news are given for id + if (!$sel_has_news) { + $sel_ref_id = ""; + } + asort($conts); + foreach ($conts as $ref_id => $title) { + $contexts[$ref_id] = $title . " (" . (int) $cnt[$ref_id] . ")"; + } + + + if ($sel_ref_id > 0) { + $obj_id = ilObject::_lookupObjId($sel_ref_id); + $obj_type = ilObject::_lookupType($obj_id); + $nitem->setContextObjId($obj_id); + $nitem->setContextObjType($obj_type); + $news_items = $nitem->getNewsForRefId( + $sel_ref_id, + false, + false, + $per, + true + ); + } + + include_once("./Services/News/classes/class.ilPDNewsTableGUI.php"); + $pd_news_table = new ilPDNewsTableGUI($this, "view", $contexts, $sel_ref_id); + $pd_news_table->setData($news_items); + $pd_news_table->setNoEntriesText($lng->txt("news_no_news_items")); + + $tpl->setContent($pd_news_table->getHTML()); + } + + /** + * change related object + */ + public function applyFilter() + { + $ilUser = $this->user; + + $this->ctrl->setParameter($this, "news_ref_id", $_POST["news_ref_id"]); + $ilUser->writePref("news_sel_ref_id", $_POST["news_ref_id"]); + if ($_POST["news_per"] > 0) { + $_SESSION["news_pd_news_per"] = $_POST["news_per"]; + } + $this->ctrl->redirect($this, "view"); + } + + /** + * reset filter + */ + public function resetFilter() + { + $ilUser = $this->user; + $this->ctrl->setParameter($this, "news_ref_id", 0); + $ilUser->writePref("news_sel_ref_id", 0); + $_SESSION["news_pd_news_per"] = ""; + $this->ctrl->redirect($this, "view"); + } } -?> diff --git a/Services/News/classes/class.ilPDNewsTableGUI.php b/Services/News/classes/class.ilPDNewsTableGUI.php index cd45a5a90f75b2a4110a2a0cbd03fefcc6ecf2d8..092ba91909be9f1f62b4f00b0b27a758cb8e4aed 100755 --- a/Services/News/classes/class.ilPDNewsTableGUI.php +++ b/Services/News/classes/class.ilPDNewsTableGUI.php @@ -1,24 +1,24 @@ ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - $ilCtrl = $DIC->ctrl(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + $ilCtrl = $DIC->ctrl(); - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->contexts = $a_contexts; - $this->selected_context = $a_selected_context; - $this->addColumn(""); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.table_row_pd_news.html", - "Services/News"); - $this->setDefaultOrderField("update_date"); - $this->setDefaultOrderDirection("desc"); - $this->setEnableTitle(false); - $this->setEnableHeader(false); - $this->setIsDataTable(false); - $this->initFilter(); - } - - /** - * Init Filter - */ - function initFilter() - { - $lng = $this->lng; - $ilUser = $this->user; - - // period - $per = ($_SESSION["news_pd_news_per"] != "") - ? $_SESSION["news_pd_news_per"] - : ilNewsItem::_lookupUserPDPeriod($ilUser->getId()); - $news_set = new ilSetting("news"); - $allow_shorter_periods = $news_set->get("allow_shorter_periods"); - $allow_longer_periods = $news_set->get("allow_longer_periods"); - $default_per = ilNewsItem::_lookupDefaultPDPeriod(); + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->contexts = $a_contexts; + $this->selected_context = $a_selected_context; + $this->addColumn(""); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate( + "tpl.table_row_pd_news.html", + "Services/News" + ); + $this->setDefaultOrderField("update_date"); + $this->setDefaultOrderDirection("desc"); + $this->setEnableTitle(false); + $this->setEnableHeader(false); + $this->setIsDataTable(false); + $this->initFilter(); + } + + /** + * Init Filter + */ + public function initFilter() + { + $lng = $this->lng; + $ilUser = $this->user; + + // period + $per = ($_SESSION["news_pd_news_per"] != "") + ? $_SESSION["news_pd_news_per"] + : ilNewsItem::_lookupUserPDPeriod($ilUser->getId()); + $news_set = new ilSetting("news"); + $allow_shorter_periods = $news_set->get("allow_shorter_periods"); + $allow_longer_periods = $news_set->get("allow_longer_periods"); + $default_per = ilNewsItem::_lookupDefaultPDPeriod(); - $options = array( - 2 => sprintf($lng->txt("news_period_x_days"), 2), - 3 => sprintf($lng->txt("news_period_x_days"), 3), - 5 => sprintf($lng->txt("news_period_x_days"), 5), - 7 => $lng->txt("news_period_1_week"), - 14 => sprintf($lng->txt("news_period_x_weeks"), 2), - 30 => $lng->txt("news_period_1_month"), - 60 => sprintf($lng->txt("news_period_x_months"), 2), - 120 => sprintf($lng->txt("news_period_x_months"), 4), - 180 => sprintf($lng->txt("news_period_x_months"), 6), - 366 => $lng->txt("news_period_1_year")); - - $unset = array(); - foreach($options as $k => $opt) - { - if (!$allow_shorter_periods && ($k < $default_per)) $unset[$k] = $k; - if (!$allow_longer_periods && ($k > $default_per)) $unset[$k] = $k; - } - foreach($unset as $k) - { - unset($options[$k]); - } + $options = array( + 2 => sprintf($lng->txt("news_period_x_days"), 2), + 3 => sprintf($lng->txt("news_period_x_days"), 3), + 5 => sprintf($lng->txt("news_period_x_days"), 5), + 7 => $lng->txt("news_period_1_week"), + 14 => sprintf($lng->txt("news_period_x_weeks"), 2), + 30 => $lng->txt("news_period_1_month"), + 60 => sprintf($lng->txt("news_period_x_months"), 2), + 120 => sprintf($lng->txt("news_period_x_months"), 4), + 180 => sprintf($lng->txt("news_period_x_months"), 6), + 366 => $lng->txt("news_period_1_year")); + + $unset = array(); + foreach ($options as $k => $opt) { + if (!$allow_shorter_periods && ($k < $default_per)) { + $unset[$k] = $k; + } + if (!$allow_longer_periods && ($k > $default_per)) { + $unset[$k] = $k; + } + } + foreach ($unset as $k) { + unset($options[$k]); + } - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $si = new ilSelectInputGUI($this->lng->txt("news_time_period"), "news_per"); - $si->setOptions($options); - $si->setValue($per); - $this->addFilterItem($si); - - // related to... - $si = new ilSelectInputGUI($this->lng->txt("context"), "news_ref_id"); - $si->setOptions($this->contexts); - $si->setValue($this->selected_context); - $this->addFilterItem($si); - } - - - /** - * Standard Version of Fill Row. Most likely to - * be overwritten by derived class. - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $news_set = new ilSetting("news"); - $enable_internal_rss = $news_set->get("enable_rss_for_internal"); + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $si = new ilSelectInputGUI($this->lng->txt("news_time_period"), "news_per"); + $si->setOptions($options); + $si->setValue($per); + $this->addFilterItem($si); + + // related to... + $si = new ilSelectInputGUI($this->lng->txt("context"), "news_ref_id"); + $si->setOptions($this->contexts); + $si->setValue($this->selected_context); + $this->addFilterItem($si); + } + + + /** + * Standard Version of Fill Row. Most likely to + * be overwritten by derived class. + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $news_set = new ilSetting("news"); + $enable_internal_rss = $news_set->get("enable_rss_for_internal"); - // context - $obj_id = ilObject::_lookupObjId($a_set["ref_id"]); - $obj_type = ilObject::_lookupType($obj_id); - $obj_title = ilObject::_lookupTitle($obj_id); - - // user - if ($a_set["user_id"] > 0) - { - $this->tpl->setCurrentBlock("user_info"); - if ($obj_type == "frm") - { - include_once("./Modules/Forum/classes/class.ilForumProperties.php"); - if (ilForumProperties::_isAnonymized($a_set["context_obj_id"])) - { - if ($a_set["context_sub_obj_type"] == "pos" && - $a_set["context_sub_obj_id"] > 0) - { - include_once("./Modules/Forum/classes/class.ilForumPost.php"); - $post = new ilForumPost($a_set["context_sub_obj_id"]); - if ($post->getUserAlias() != "") $this->tpl->setVariable("VAL_AUTHOR", ilUtil::stripSlashes($post->getUserAlias())); - else $this->tpl->setVariable("VAL_AUTHOR", $lng->txt("forums_anonymous")); - } - else - { - $this->tpl->setVariable("VAL_AUTHOR", $lng->txt("forums_anonymous")); - } - } - else - { - if (ilObject::_exists($a_set["user_id"])) - { - $user_obj = new ilObjUser($a_set["user_id"]); - $this->tpl->setVariable("VAL_AUTHOR", $user_obj->getLogin()); - } - } - } - else - { - if (ilObject::_exists($a_set["user_id"])) - { - $this->tpl->setVariable("VAL_AUTHOR", ilObjUser::_lookupLogin($a_set["user_id"])); - } - } - $this->tpl->setVariable("TXT_AUTHOR", $lng->txt("author")); - $this->tpl->parseCurrentBlock(); - } - - // media player - if ($a_set["content_type"] == NEWS_AUDIO && - $a_set["mob_id"] > 0 && ilObject::_exists($a_set["mob_id"])) - { - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - include_once("./Services/MediaObjects/classes/class.ilMediaPlayerGUI.php"); - $mob = new ilObjMediaObject($a_set["mob_id"]); - $med = $mob->getMediaItem("Standard"); - $mpl = new ilMediaPlayerGUI(); - $mpl->setFile(ilObjMediaObject::_getDirectory($a_set["mob_id"])."/". - $med->getLocation()); - $this->tpl->setCurrentBlock("player"); - $this->tpl->setVariable("PLAYER", - $mpl->getMp3PlayerHtml()); - $this->tpl->parseCurrentBlock(); - } - - // access - if ($enable_internal_rss) - { - $this->tpl->setCurrentBlock("access"); - include_once("./Services/Block/classes/class.ilBlockSetting.php"); - $this->tpl->setVariable("TXT_ACCESS", $lng->txt("news_news_item_visibility")); - if ($a_set["visibility"] == NEWS_PUBLIC || - ($a_set["priority"] == 0 && - ilBlockSetting::_lookup("news", "public_notifications", - 0, $obj_id))) - { - $this->tpl->setVariable("VAL_ACCESS", $lng->txt("news_visibility_public")); - } - else - { - $this->tpl->setVariable("VAL_ACCESS", $lng->txt("news_visibility_users")); - } - $this->tpl->parseCurrentBlock(); - } + // context + $obj_id = ilObject::_lookupObjId($a_set["ref_id"]); + $obj_type = ilObject::_lookupType($obj_id); + $obj_title = ilObject::_lookupTitle($obj_id); + + // user + if ($a_set["user_id"] > 0) { + $this->tpl->setCurrentBlock("user_info"); + if ($obj_type == "frm") { + include_once("./Modules/Forum/classes/class.ilForumProperties.php"); + if (ilForumProperties::_isAnonymized($a_set["context_obj_id"])) { + if ($a_set["context_sub_obj_type"] == "pos" && + $a_set["context_sub_obj_id"] > 0) { + include_once("./Modules/Forum/classes/class.ilForumPost.php"); + $post = new ilForumPost($a_set["context_sub_obj_id"]); + if ($post->getUserAlias() != "") { + $this->tpl->setVariable("VAL_AUTHOR", ilUtil::stripSlashes($post->getUserAlias())); + } else { + $this->tpl->setVariable("VAL_AUTHOR", $lng->txt("forums_anonymous")); + } + } else { + $this->tpl->setVariable("VAL_AUTHOR", $lng->txt("forums_anonymous")); + } + } else { + if (ilObject::_exists($a_set["user_id"])) { + $user_obj = new ilObjUser($a_set["user_id"]); + $this->tpl->setVariable("VAL_AUTHOR", $user_obj->getLogin()); + } + } + } else { + if (ilObject::_exists($a_set["user_id"])) { + $this->tpl->setVariable("VAL_AUTHOR", ilObjUser::_lookupLogin($a_set["user_id"])); + } + } + $this->tpl->setVariable("TXT_AUTHOR", $lng->txt("author")); + $this->tpl->parseCurrentBlock(); + } + + // media player + if ($a_set["content_type"] == NEWS_AUDIO && + $a_set["mob_id"] > 0 && ilObject::_exists($a_set["mob_id"])) { + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + include_once("./Services/MediaObjects/classes/class.ilMediaPlayerGUI.php"); + $mob = new ilObjMediaObject($a_set["mob_id"]); + $med = $mob->getMediaItem("Standard"); + $mpl = new ilMediaPlayerGUI(); + $mpl->setFile(ilObjMediaObject::_getDirectory($a_set["mob_id"]) . "/" . + $med->getLocation()); + $this->tpl->setCurrentBlock("player"); + $this->tpl->setVariable( + "PLAYER", + $mpl->getMp3PlayerHtml() + ); + $this->tpl->parseCurrentBlock(); + } + + // access + if ($enable_internal_rss) { + $this->tpl->setCurrentBlock("access"); + include_once("./Services/Block/classes/class.ilBlockSetting.php"); + $this->tpl->setVariable("TXT_ACCESS", $lng->txt("news_news_item_visibility")); + if ($a_set["visibility"] == NEWS_PUBLIC || + ($a_set["priority"] == 0 && + ilBlockSetting::_lookup( + "news", + "public_notifications", + 0, + $obj_id + ))) { + $this->tpl->setVariable("VAL_ACCESS", $lng->txt("news_visibility_public")); + } else { + $this->tpl->setVariable("VAL_ACCESS", $lng->txt("news_visibility_users")); + } + $this->tpl->parseCurrentBlock(); + } - // content - if ($a_set["content"] != "") - { - $this->tpl->setCurrentBlock("content"); - $this->tpl->setVariable("VAL_CONTENT", - nl2br($this->makeClickable( - ilNewsItem::determineNewsContent($a_set["context_obj_type"], $a_set["content"], $a_set["content_text_is_lang_var"]) - ))); - $this->tpl->parseCurrentBlock(); - } - if ($a_set["content_long"] != "") - { - $this->tpl->setCurrentBlock("long"); - $this->tpl->setVariable("VAL_LONG_CONTENT", ilUtil::makeClickable($a_set["content_long"], true)); - $this->tpl->parseCurrentBlock(); - } - if ($a_set["update_date"] != $a_set["creation_date"]) // update date - { - $this->tpl->setCurrentBlock("ni_update"); - $this->tpl->setVariable("TXT_LAST_UPDATE", $lng->txt("last_update")); - $this->tpl->setVariable("VAL_LAST_UPDATE", - ilDatePresentation::formatDate(new ilDateTime($a_set["update_date"],IL_CAL_DATETIME))); - $this->tpl->parseCurrentBlock(); - } + // content + if ($a_set["content"] != "") { + $this->tpl->setCurrentBlock("content"); + $this->tpl->setVariable( + "VAL_CONTENT", + nl2br($this->makeClickable( + ilNewsItem::determineNewsContent($a_set["context_obj_type"], $a_set["content"], $a_set["content_text_is_lang_var"]) + )) + ); + $this->tpl->parseCurrentBlock(); + } + if ($a_set["content_long"] != "") { + $this->tpl->setCurrentBlock("long"); + $this->tpl->setVariable("VAL_LONG_CONTENT", ilUtil::makeClickable($a_set["content_long"], true)); + $this->tpl->parseCurrentBlock(); + } + if ($a_set["update_date"] != $a_set["creation_date"]) { // update date + $this->tpl->setCurrentBlock("ni_update"); + $this->tpl->setVariable("TXT_LAST_UPDATE", $lng->txt("last_update")); + $this->tpl->setVariable( + "VAL_LAST_UPDATE", + ilDatePresentation::formatDate(new ilDateTime($a_set["update_date"], IL_CAL_DATETIME)) + ); + $this->tpl->parseCurrentBlock(); + } - // forum hack, not nice - $add = ""; - if ($obj_type == "frm" && $a_set["context_sub_obj_type"] == "pos" - && $a_set["context_sub_obj_id"] > 0) - { - include_once("./Modules/Forum/classes/class.ilObjForumAccess.php"); - $pos = $a_set["context_sub_obj_id"]; - $thread = ilObjForumAccess::_getThreadForPosting($pos); - if ($thread > 0) - { - $add = "_".$thread."_".$pos; - } - } + // forum hack, not nice + $add = ""; + if ($obj_type == "frm" && $a_set["context_sub_obj_type"] == "pos" + && $a_set["context_sub_obj_id"] > 0) { + include_once("./Modules/Forum/classes/class.ilObjForumAccess.php"); + $pos = $a_set["context_sub_obj_id"]; + $thread = ilObjForumAccess::_getThreadForPosting($pos); + if ($thread > 0) { + $add = "_" . $thread . "_" . $pos; + } + } - // file hack, not nice - if ($obj_type == "file") - { - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $a_set["ref_id"]); - $url = $ilCtrl->getLinkTargetByClass("ilrepositorygui", "sendfile"); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + // file hack, not nice + if ($obj_type == "file") { + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $a_set["ref_id"]); + $url = $ilCtrl->getLinkTargetByClass("ilrepositorygui", "sendfile"); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; - $button = ilLinkButton::getInstance(); - $button->setUrl($url); - $button->setCaption("download"); + include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; + $button = ilLinkButton::getInstance(); + $button->setUrl($url); + $button->setCaption("download"); - $this->tpl->setCurrentBlock("download"); - $this->tpl->setVariable("BUTTON_DOWNLOAD", $button->render()); - $this->tpl->parseCurrentBlock(); - } + $this->tpl->setCurrentBlock("download"); + $this->tpl->setVariable("BUTTON_DOWNLOAD", $button->render()); + $this->tpl->parseCurrentBlock(); + } - // wiki hack, not nice - if ($obj_type == "wiki" && $a_set["context_sub_obj_type"] == "wpg" - && $a_set["context_sub_obj_id"] > 0) - { - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $wptitle = ilWikiPage::lookupTitle($a_set["context_sub_obj_id"]); - if ($wptitle != "") - { - $add = "_".ilWikiUtil::makeUrlTitle($wptitle); - } - } + // wiki hack, not nice + if ($obj_type == "wiki" && $a_set["context_sub_obj_type"] == "wpg" + && $a_set["context_sub_obj_id"] > 0) { + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + $wptitle = ilWikiPage::lookupTitle($a_set["context_sub_obj_id"]); + if ($wptitle != "") { + $add = "_" . ilWikiUtil::makeUrlTitle($wptitle); + } + } - $url_target = "./goto.php?client_id=".rawurlencode(CLIENT_ID)."&target=". - $obj_type."_".$a_set["ref_id"].$add; + $url_target = "./goto.php?client_id=" . rawurlencode(CLIENT_ID) . "&target=" . + $obj_type . "_" . $a_set["ref_id"] . $add; - // lm page hack, not nice - if (in_array($obj_type, array("dbk", "lm")) && $a_set["context_sub_obj_type"] == "pg" - && $a_set["context_sub_obj_id"] > 0) - { - $url_target = "./goto.php?client_id=".rawurlencode(CLIENT_ID)."&target=". - "pg_".$a_set["context_sub_obj_id"]."_".$a_set["ref_id"]; - } + // lm page hack, not nice + if (in_array($obj_type, array("dbk", "lm")) && $a_set["context_sub_obj_type"] == "pg" + && $a_set["context_sub_obj_id"] > 0) { + $url_target = "./goto.php?client_id=" . rawurlencode(CLIENT_ID) . "&target=" . + "pg_" . $a_set["context_sub_obj_id"] . "_" . $a_set["ref_id"]; + } - $this->tpl->setCurrentBlock("context"); - $cont_loc = new ilLocatorGUI(); - $cont_loc->addContextItems($a_set["ref_id"], true); - $this->tpl->setVariable("CONTEXT_LOCATOR", - $cont_loc->getHTML()); - $this->tpl->setVariable("HREF_CONTEXT_TITLE", $url_target); - $this->tpl->setVariable("CONTEXT_TITLE", $obj_title); - $this->tpl->setVariable("ALT_CONTEXT_TITLE", - $lng->txt("icon")." ".$lng->txt("obj_".$obj_type)); - $this->tpl->setVariable("IMG_CONTEXT_TITLE", - ilObject::_getIcon($a_set["context_obj_id"])); - $this->tpl->parseCurrentBlock(); + $this->tpl->setCurrentBlock("context"); + $cont_loc = new ilLocatorGUI(); + $cont_loc->addContextItems($a_set["ref_id"], true); + $this->tpl->setVariable( + "CONTEXT_LOCATOR", + $cont_loc->getHTML() + ); + $this->tpl->setVariable("HREF_CONTEXT_TITLE", $url_target); + $this->tpl->setVariable("CONTEXT_TITLE", $obj_title); + $this->tpl->setVariable( + "ALT_CONTEXT_TITLE", + $lng->txt("icon") . " " . $lng->txt("obj_" . $obj_type) + ); + $this->tpl->setVariable( + "IMG_CONTEXT_TITLE", + ilObject::_getIcon($a_set["context_obj_id"]) + ); + $this->tpl->parseCurrentBlock(); - $this->tpl->setVariable("HREF_TITLE", $url_target); - - // title - $this->tpl->setVariable("VAL_TITLE", - ilNewsItem::determineNewsTitle($a_set["context_obj_type"], $a_set["title"], $a_set["content_is_lang_var"])); + $this->tpl->setVariable("HREF_TITLE", $url_target); + + // title + $this->tpl->setVariable( + "VAL_TITLE", + ilNewsItem::determineNewsTitle($a_set["context_obj_type"], $a_set["title"], $a_set["content_is_lang_var"]) + ); - // creation date - $this->tpl->setVariable("VAL_CREATION_DATE", - ilDatePresentation::formatDate(new ilDateTime($a_set["creation_date"],IL_CAL_DATETIME))); - $this->tpl->setVariable("TXT_CREATED", $lng->txt("created")); + // creation date + $this->tpl->setVariable( + "VAL_CREATION_DATE", + ilDatePresentation::formatDate(new ilDateTime($a_set["creation_date"], IL_CAL_DATETIME)) + ); + $this->tpl->setVariable("TXT_CREATED", $lng->txt("created")); - $this->tpl->parseCurrentBlock(); - } + $this->tpl->parseCurrentBlock(); + } - /** - * Make clickable - * - * @param - * @return - */ - function makeClickable($a_str) - { - // this fixes bug 8744. We assume that strings that contain < and > - // already contain html, we do not handle these - if (is_int(strpos($a_str, ">")) && is_int(strpos($a_str, "<"))) - { - return $a_str; - } - - return ilUtil::makeClickable($a_str); - } + /** + * Make clickable + * + * @param + * @return + */ + public function makeClickable($a_str) + { + // this fixes bug 8744. We assume that strings that contain < and > + // already contain html, we do not handle these + if (is_int(strpos($a_str, ">")) && is_int(strpos($a_str, "<"))) { + return $a_str; + } + return ilUtil::makeClickable($a_str); + } } -?> diff --git a/Services/News/classes/class.ilRSSButtonGUI.php b/Services/News/classes/class.ilRSSButtonGUI.php index 6f7c1b338776c3f1a5b7fda088245761c38f0e08..d077afc8b0fc26beac3b90db37b62710e5662c8d 100644 --- a/Services/News/classes/class.ilRSSButtonGUI.php +++ b/Services/News/classes/class.ilRSSButtonGUI.php @@ -3,79 +3,74 @@ /* Copyright (c) 1998-2014 ILIAS open source, Extended GPL, see docs/LICENSE */ /** - * + * * * @author Alex Killing * @version $Id\$ - * @ingroup + * @ingroup */ class ilRSSButtonGUI { - const ICON_RSS = "rss"; - const ICON_RSS_AUDIO = "rss audio"; - const ICON_RSS_VIDEO = "rss video"; - const ICON_ICAL = "ical"; - const ICON_ITUNES = "itunes"; - const ICON_ITUNES_AUDIO = "itunes audio"; - const ICON_ITUNES_VIDEO = "itunes video"; - - /** - * Get icon html - * - * @param string $a_type icons type ICON_RSS | ICON_ICAL - * @param string $a_href href - * @return string icon html - */ - static function get($a_type, $a_href = "") - { - $tpl = new ilTemplate("tpl.rss_icon.html", true, true, "Services/News"); - - if ($a_href != "") - { - $tpl->setCurrentBlock("a_start"); - $tpl->setVariable("HREF", $a_href); - $tpl->parseCurrentBlock(); - $tpl->touchBlock("a_end"); - } - - $text = ""; - - switch ($a_type) - { - case self::ICON_RSS: - $text = "RSS"; - break; - - case self::ICON_RSS_AUDIO: - $text = "RSS Audio"; - break; - - case self::ICON_RSS_VIDEO: - $text = "RSS Video"; - break; - - case self::ICON_ICAL: - $text = "iCal"; - break; - - case self::ICON_ITUNES: - $text = "iTunes"; - break; - - case self::ICON_ITUNES_AUDIO: - $text = "iTunes Audio"; - break; - - case self::ICON_ITUNES_VIDEO: - $text = "iTunes Video"; - break; - } - - $tpl->setVariable("TEXT", $text); - - return $tpl->get(); - } - + const ICON_RSS = "rss"; + const ICON_RSS_AUDIO = "rss audio"; + const ICON_RSS_VIDEO = "rss video"; + const ICON_ICAL = "ical"; + const ICON_ITUNES = "itunes"; + const ICON_ITUNES_AUDIO = "itunes audio"; + const ICON_ITUNES_VIDEO = "itunes video"; + + /** + * Get icon html + * + * @param string $a_type icons type ICON_RSS | ICON_ICAL + * @param string $a_href href + * @return string icon html + */ + public static function get($a_type, $a_href = "") + { + $tpl = new ilTemplate("tpl.rss_icon.html", true, true, "Services/News"); + + if ($a_href != "") { + $tpl->setCurrentBlock("a_start"); + $tpl->setVariable("HREF", $a_href); + $tpl->parseCurrentBlock(); + $tpl->touchBlock("a_end"); + } + + $text = ""; + + switch ($a_type) { + case self::ICON_RSS: + $text = "RSS"; + break; + + case self::ICON_RSS_AUDIO: + $text = "RSS Audio"; + break; + + case self::ICON_RSS_VIDEO: + $text = "RSS Video"; + break; + + case self::ICON_ICAL: + $text = "iCal"; + break; + + case self::ICON_ITUNES: + $text = "iTunes"; + break; + + case self::ICON_ITUNES_AUDIO: + $text = "iTunes Audio"; + break; + + case self::ICON_ITUNES_VIDEO: + $text = "iTunes Video"; + break; + } + + $tpl->setVariable("TEXT", $text); + + return $tpl->get(); + } } - -?> \ No newline at end of file diff --git a/Services/News/interfaces/interface.ilNewsObjectAdapterInterface.php b/Services/News/interfaces/interface.ilNewsObjectAdapterInterface.php index 8d600d05c7bb54c79cbe8ac20e2bc76648a840f4..4f7b6fb7284eb04e604b40bd124ac7eb589f1aba 100644 --- a/Services/News/interfaces/interface.ilNewsObjectAdapterInterface.php +++ b/Services/News/interfaces/interface.ilNewsObjectAdapterInterface.php @@ -10,19 +10,19 @@ */ interface ilNewsObjectAdapterInterface { - /** - * Get object id for reference id - * - * @param int $a_ref_id - * @return int - */ - public function getObjIdForRefId($a_ref_id); + /** + * Get object id for reference id + * + * @param int $a_ref_id + * @return int + */ + public function getObjIdForRefId($a_ref_id); - /** - * Get object type for object id - * - * @param int $a_obj_id - * @return string - */ - public function getTypeForObjId($a_obj_id); -} \ No newline at end of file + /** + * Get object type for object id + * + * @param int $a_obj_id + * @return string + */ + public function getTypeForObjId($a_obj_id); +} diff --git a/Services/News/interfaces/interface.ilNewsRendererGUI.php b/Services/News/interfaces/interface.ilNewsRendererGUI.php index 380cf48fede8bf4a73308cd487114839aec0bbdf..e02c8833036a284172e79588677256be527a13c2 100644 --- a/Services/News/interfaces/interface.ilNewsRendererGUI.php +++ b/Services/News/interfaces/interface.ilNewsRendererGUI.php @@ -11,52 +11,49 @@ */ interface ilNewsRendererGUI { - /** - * Constructor - */ - function __construct(); - - /** - * Language key - * - * @param $i ilNewsItem news item - */ - public function setLanguage($lang_key); - - /** - * Set news item - * - * @param ilNewsItem $a_news_item - * @param int $a_news_ref_id - */ - function setNewsItem(ilNewsItem $a_news_item, $a_news_ref_id); - - /** - * Render content for timeline - * - * @return string html - */ - public function getTimelineContent(); - - /** - * Render content for detail view - * - * @return string html - */ - public function getDetailContent(); - - /** - * @param ilAdvancedSelectionListGUI $list - */ - public function addTimelineActions(ilAdvancedSelectionListGUI $list); - - /** - * Get link href for object link - * - * @return string link href url - */ - public function getObjectLink(); - + /** + * Constructor + */ + public function __construct(); + + /** + * Language key + * + * @param $i ilNewsItem news item + */ + public function setLanguage($lang_key); + + /** + * Set news item + * + * @param ilNewsItem $a_news_item + * @param int $a_news_ref_id + */ + public function setNewsItem(ilNewsItem $a_news_item, $a_news_ref_id); + + /** + * Render content for timeline + * + * @return string html + */ + public function getTimelineContent(); + + /** + * Render content for detail view + * + * @return string html + */ + public function getDetailContent(); + + /** + * @param ilAdvancedSelectionListGUI $list + */ + public function addTimelineActions(ilAdvancedSelectionListGUI $list); + + /** + * Get link href for object link + * + * @return string link href url + */ + public function getObjectLink(); } - -?> \ No newline at end of file diff --git a/Services/Notes/classes/class.ilNote.php b/Services/Notes/classes/class.ilNote.php index 585c67265a55513309486e0b195658297167e185..c2398411a5b217b7eda6ce067398e3ff93a3225e 100644 --- a/Services/Notes/classes/class.ilNote.php +++ b/Services/Notes/classes/class.ilNote.php @@ -24,1033 +24,998 @@ define("IL_NOTE_CONTRA", 4); */ class ilNote { - /** - * @var ilDB - */ - protected $db; - - /** - * @var ilSetting - */ - protected $settings; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * object id (NOT ref_id!) of repository object (e.g for page objects - * the obj_id of the learning module; for personal desktop this is set to 0) - * - * @var int - */ - protected $rep_obj_id = 0; - - /** - * object id (e.g for page objects the obj_id of the page object) - * this is set to 0 for normal repository objects like forums ... - * - * @var int - */ - protected $obj_id; - - /** - * type of the object (e.g st,pg,crs ... NOT "news") - * - * @var string - */ - protected $obj_type; - - /** - * @var int - */ - protected $news_id; - - - /** - * constructor - */ - function __construct($a_id = 0) - { - global $DIC; - - $this->db = $DIC->database(); - $this->settings = $DIC->settings(); - $this->access = $DIC->access(); - if ($a_id > 0) - { - $this->id = $a_id; - $this->read(); - } - } - - /** - * set id - * - * @param int note id - */ - function setId($a_id) - { - $this->id = $a_id; - } - - /** - * get id - * - * @return int note id - */ - function getId() - { - return $this->id; - } - - /** - * set assigned object - * - * @param string $a_obj_type - * @param int $a_rep_obj_id - * @param int $a_obj_id - * @param int $a_news_id - */ - function setObject($a_obj_type, $a_rep_obj_id, $a_obj_id = 0, $a_news_id = 0) - { - $this->rep_obj_id = $a_rep_obj_id; - $this->obj_id = $a_obj_id; - $this->obj_type = $a_obj_type; - $this->news_id = $a_news_id; - } - - function getObject() - { - return array("rep_obj_id" => $this->rep_obj_id, - "obj_id" => $this->obj_id, - "obj_type" => $this->obj_type, - "news_id" => $this->news_id); - } - - - /** - * set type - * - * @param int IL_NOTE_PUBLIC | IL_NOTE_PRIVATE - */ - function setType($a_type) - { - $this->type = $a_type; - } - - /** - * get type - * - * @return int IL_NOTE_PUBLIC | IL_NOTE_PRIVATE - */ - function getType() - { - return $this->type; - } - - /** - * set author - * - * @param int author user id - */ - function setAuthor($a_user_id) - { - $this->author = $a_user_id; - } - - /** - * get author - * - * @return int user id - */ - function getAuthor() - { - return $this->author; - } - - /** - * set text - * - * @param string text - */ - function setText($a_text) - { - $this->text = $a_text; - } - - /** - * get text - * - * @return string text - */ - function getText() - { - return $this->text; - } - - /** - * set subject - * - * @param string text - */ - function setSubject($a_subject) - { - $this->subject = $a_subject; - } - - /** - * get subject - * - * @return string subject - */ - function getSubject() - { - return $this->subject; - } - - /** - * set creation date - * - * @param string creation date - */ - function setCreationDate($a_date) - { - $this->creation_date = $a_date; - } - - /** - * get creation date - * - * @return string creation date - */ - function getCreationDate() - { - return $this->creation_date; - } - - /** - * set update date - * - * @param string update date - */ - function setUpdateDate($a_date) - { - $this->update_date = $a_date; - } - - /** - * get update date - * - * @return string update date - */ - function getUpdateDate() - { - return $this->update_date; - } - - /** - * set label - * - * @param int IL_NOTE_UNLABELED | IL_NOTE_IMPORTANT | IL_NOTE_QUESTION - * | IL_NOTE_PRO | IL_NOTE_CONTRA - */ - function setLabel($a_label) - { - return $this->label = $a_label; - } - - /** - * get label - * - * @return int IL_NOTE_UNLABELED | IL_NOTE_IMPORTANT | IL_NOTE_QUESTION - * | IL_NOTE_PRO | IL_NOTE_CONTRA - */ - function getLabel() - { - return $this->label; - } - - /** - * Set news id - * - * @param int $a_val news id - */ - function setNewsId($a_val) - { - $this->news_id = $a_val; - } - - /** - * Get news id - * - * @return int news id - */ - function getNewsId() - { - return $this->news_id; - } - - /** - * set repository object status - * - * @param bool - */ - function setInRepository($a_value) - { - return $this->no_repository = !(bool)$a_value; - } - - /** - * belongs note to repository object? - * - * @return bool - */ - function isInRepository() - { - return !$this->no_repository; - } - - function create($a_use_provided_creation_date = false) - { - $ilDB = $this->db; - - $cd = ($a_use_provided_creation_date) - ? $this->getCreationDate() - : ilUtil::now(); - - $this->id = $ilDB->nextId("note"); - - $ilDB->insert("note", array( - "id" => array("integer", $this->id), - "rep_obj_id" => array("integer", (int) $this->rep_obj_id), - "obj_id" => array("integer", (int) $this->obj_id), - "obj_type" => array("text", (string) $this->obj_type), - "news_id" => array("integer", (int) $this->news_id), - "type" => array("integer", (int) $this->type), - "author" => array("integer", (int) $this->author), - "note_text" => array("clob", (string) $this->text), - "subject" => array("text", (string) $this->subject), - "label" => array("integer", (int) $this->label), - "creation_date" => array("timestamp", $cd), - "no_repository" => array("integer", $this->no_repository) - )); - - $this->sendNotifications(); - - $this->creation_date = ilNote::_lookupCreationDate($this->getId()); - } - - function update() - { - $ilDB = $this->db; - - $ilDB->update("note", array( - "rep_obj_id" => array("integer", (int) $this->rep_obj_id), - "obj_id" => array("integer", (int) $this->obj_id), - "news_id" => array("integer", (int) $this->news_id), - "obj_type" => array("text", (string) $this->obj_type), - "type" => array("integer", (int) $this->type), - "author" => array("integer", (int) $this->author), - "note_text" => array("clob", (string) $this->text), - "subject" => array("text", (string) $this->subject), - "label" => array("integer", (int) $this->label), - "update_date" => array("timestamp", ilUtil::now()), - "no_repository" => array("integer", $this->no_repository) - ), array( - "id" => array("integer", $this->getId()) - )); - - $this->update_date = ilNote::_lookupUpdateDate($this->getId()); - - $this->sendNotifications(true); - } - - function read() - { - $ilDB = $this->db; - - $q = "SELECT * FROM note WHERE id = ". - $ilDB->quote((int) $this->getId(), "integer"); - $set = $ilDB->query($q); - $note_rec = $ilDB->fetchAssoc($set); - $this->setAllData($note_rec); - } - - /** - * delete note - */ - function delete() - { - $ilDB = $this->db; - - $q = "DELETE FROM note WHERE id = ". - $ilDB->quote((int) $this->getId(), "integer"); - $ilDB->manipulate($q); - } - - /** - * set all note data by record array - */ - function setAllData($a_note_rec) - { - $this->setId($a_note_rec["id"]); - $this->setObject($a_note_rec["obj_type"], $a_note_rec["rep_obj_id"], $a_note_rec["obj_id"], - $a_note_rec["news_id"]); - $this->setType($a_note_rec["type"]); - $this->setAuthor($a_note_rec["author"]); - $this->setText($a_note_rec["note_text"]); - $this->setSubject($a_note_rec["subject"]); - $this->setLabel($a_note_rec["label"]); - $this->setCreationDate($a_note_rec["creation_date"]); - $this->setUpdateDate($a_note_rec["update_date"]); - $this->setInRepository(!(bool)$a_note_rec["no_repository"]); - } - - /** - * lookup creation date of note - */ - static function _lookupCreationDate($a_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "SELECT * FROM note WHERE id = ". - $ilDB->quote((int) $a_id, "integer"); - $set = $ilDB->query($q); - $note_rec = $ilDB->fetchAssoc($set); - - return $note_rec["creation_date"]; - } - - /** - * lookup update date of note - */ - static function _lookupUpdateDate($a_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "SELECT * FROM note WHERE id = ". - $ilDB->quote((int) $a_id, "integer"); - $set = $ilDB->query($q); - $note_rec = $ilDB->fetchAssoc($set); - - return $note_rec["update_date"]; - } - - /** - * get all notes related to a specific object - */ - static function _getNotesOfObject($a_rep_obj_id, $a_obj_id, $a_obj_type, - $a_type = IL_NOTE_PRIVATE, $a_incl_sub = false, $a_filter = "", - $a_all_public = "y", $a_repository_mode = true, $a_sort_ascending = false, $a_news_id = 0) - { - global $DIC; - - $ilDB = $DIC->database(); - $ilUser = $DIC->user(); - - $author_where = ($a_type == IL_NOTE_PRIVATE || $a_all_public == "n") - ? " AND author = ".$ilDB->quote((int) $ilUser->getId(), "integer") - : ""; - - $sub_where = (!$a_incl_sub) - ? " AND obj_id = ".$ilDB->quote((int) $a_obj_id, "integer"). - " AND obj_type = ".$ilDB->quote((string) $a_obj_type, "text") - : ""; - - $news_where = - " AND news_id = ".$ilDB->quote((int) $a_news_id, "integer"); - - - $sub_where .= " AND no_repository = ".$ilDB->quote(!$a_repository_mode, "integer"); - - $q = "SELECT * FROM note WHERE ". - " rep_obj_id = ".$ilDB->quote((int) $a_rep_obj_id, "integer"). - $sub_where. - " AND type = ".$ilDB->quote((int) $a_type, "integer"). - $author_where. - $news_where. - " ORDER BY creation_date "; - - $q .= ((bool)$a_sort_ascending) ? "ASC" : "DESC"; - - $set = $ilDB->query($q); - $notes = array(); - while($note_rec = $ilDB->fetchAssoc($set)) - { - if ($a_filter != "") - { - if (!is_array($a_filter)) - { - $a_filter = array($a_filter); - } - if (!in_array($note_rec["id"], $a_filter)) - { - continue; - } - } - $cnt = count($notes); - $notes[$cnt] = new ilNote(); - $notes[$cnt]->setAllData($note_rec); - } - - return $notes; - } - - /** - * get all notes related to a single repository object - */ - public static function _getAllNotesOfSingleRepObject($a_rep_obj_id, $a_type = IL_NOTE_PRIVATE, $a_incl_sub = false, $a_sort_ascending = false, - $a_since = "") - { - global $DIC; - - $ilDB = $DIC->database(); - - $sub_where = (!$a_incl_sub) - ? " AND obj_id = ".$ilDB->quote((int) 0, "integer") : ""; - - if ($a_since != "") { - $sub_where.=" AND creation_date > ".$ilDB->quote($a_since, "timestamp"); - } - - $sub_where .= " AND no_repository = ".$ilDB->quote(0, "integer"); - - $q = "SELECT * FROM note WHERE ". - " rep_obj_id = ".$ilDB->quote((int) $a_rep_obj_id, "integer"). - $sub_where. - " AND type = ".$ilDB->quote((int) $a_type, "integer"). - " ORDER BY creation_date "; - - $q .= ((bool)$a_sort_ascending) ? "ASC" : "DESC"; - $set = $ilDB->query($q); - $notes = array(); - while($note_rec = $ilDB->fetchAssoc($set)) - { - $cnt = count($notes); - $notes[$cnt] = new ilNote(); - $notes[$cnt]->setAllData($note_rec); - } - return $notes; - } - - /** - * get last notes of current user - */ - static function _getLastNotesOfUser() - { - global $DIC; - - $ilDB = $DIC->database(); - $ilUser = $DIC->user(); - - $q = "SELECT * FROM note WHERE ". - " type = ".$ilDB->quote((int) IL_NOTE_PRIVATE, "integer"). - " AND author = ".$ilDB->quote((int) $ilUser->getId(), "integer"). - " AND (no_repository IS NULL OR no_repository < ".$ilDB->quote(1, "integer").")". - " ORDER BY creation_date DESC"; - - $ilDB->quote($q); - $set = $ilDB->query($q); - $notes = array(); - while($note_rec = $ilDB->fetchAssoc($set)) - { - $cnt = count($notes); - $notes[$cnt] = new ilNote(); - $notes[$cnt]->setAllData($note_rec); - } - - return $notes; - } - - /** - * get all related objects for user - */ - static function _getRelatedObjectsOfUser($a_mode) - { - global $DIC; - - $ilDB = $DIC->database(); - $ilUser = $DIC->user(); - $tree = $DIC->repositoryTree(); - - if ($a_mode == ilPDNotesGUI::PRIVATE_NOTES) - { - $q = "SELECT DISTINCT rep_obj_id FROM note WHERE ". - " type = ".$ilDB->quote((int) IL_NOTE_PRIVATE, "integer"). - " AND author = ".$ilDB->quote($ilUser->getId(), "integer"). - " AND (no_repository IS NULL OR no_repository < ".$ilDB->quote(1, "integer").")". - " ORDER BY rep_obj_id"; - - $ilDB->quote($q); - $set = $ilDB->query($q); - $reps = array(); - while($rep_rec = $ilDB->fetchAssoc($set)) - { - // #9343: deleted objects - if(ilObject::_lookupType($rep_rec["rep_obj_id"])) - { - $reps[] = array("rep_obj_id" => $rep_rec["rep_obj_id"]); - } - } - } - else - { - // all objects where the user wrote at least one comment - $q = "SELECT DISTINCT rep_obj_id FROM note WHERE ". - " type = ".$ilDB->quote((int) IL_NOTE_PUBLIC, "integer"). - " AND author = ".$ilDB->quote($ilUser->getId(), "integer"). - " AND (no_repository IS NULL OR no_repository < ".$ilDB->quote(1, "integer").")". - " ORDER BY rep_obj_id"; - - $set = $ilDB->query($q); - $reps = array(); - while($rep_rec = $ilDB->fetchAssoc($set)) - { - // #9343: deleted objects - if ($type = ilObject::_lookupType($rep_rec["rep_obj_id"])) - { - if (ilNote::commentsActivated($rep_rec["rep_obj_id"], "", $type)) - { - $reps[] = array("rep_obj_id" => $rep_rec["rep_obj_id"]); - } - } - } - - // additionally all objects on the personal desktop of the user - // that have at least on comment - $dis = ilObjUser::_lookupDesktopItems($ilUser->getId()); - $obj_ids = array(); - foreach($dis as $di) - { - $obj_ids[] = $di["obj_id"]; - } - if (count($obj_ids) > 0) - { - $q = "SELECT DISTINCT rep_obj_id FROM note WHERE ". - $ilDB->in("rep_obj_id", $obj_ids, false, "integer"). - " AND (no_repository IS NULL OR no_repository < ".$ilDB->quote(1, "integer").")"; - - $set = $ilDB->query($q); - while($rec = $ilDB->fetchAssoc($set)) - { - $add = true; - reset($reps); - foreach ($reps as $r) - { - if ($r["rep_obj_id"] == $rec["rep_obj_id"]) - { - $add = false; - } - } - if ($add) - { - $type = ilObject::_lookupType($rec["rep_obj_id"]); - if (ilNote::commentsActivated($rec["rep_obj_id"], "", $type)) - { - $reps[] = array("rep_obj_id" => $rec["rep_obj_id"]); - } - } - } - } - } - - if(sizeof($reps)) - { - // check if notes/comments belong to objects in trash - // see ilNoteGUI::showTargets() - foreach($reps as $idx => $rep) - { - $has_active_ref = false; - - // repository? - $ref_ids = ilObject::_getAllReferences($rep["rep_obj_id"]); - if($ref_ids) - { - $reps[$idx]["ref_ids"] = array_values($ref_ids); - - foreach($ref_ids as $ref_id) - { - if(!$tree->isDeleted($ref_id)) - { - $has_active_ref = true; - break; - } - } - } - else - { - // personal workspace? - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; - $wsp_tree = new ilWorkspaceTree($ilUser->getId()); - $node_id = $wsp_tree->lookupNodeId($rep["rep_obj_id"]); - if($node_id) - { - $reps[$idx]["wsp_id"] = $node_id; - - $has_active_ref = true; - } - } - - if(!$has_active_ref) - { - unset($reps[$idx]); - } - } - } - - return $reps; - } - - /** - * How many users have attached a note/comment to a given object? - * - * @param int $a_rep_obj_id object id (as in object data) - * @param int $a_obj_id (sub) object id - * @param string $a_type (sub) object type - */ - static function getUserCount($a_rep_obj_id, $a_obj_id, $a_type) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->queryF("SELECT count(DISTINCT author) cnt FROM note WHERE ". - "rep_obj_id = %s AND obj_id = %s AND obj_type = %s", - array("integer", "integer", "text"), - array((int) $a_rep_obj_id, (int) $a_obj_id, (string)$a_type)); - $rec = $ilDB->fetchAssoc($set); - return (int) $rec["cnt"]; - } - - /** - * Get all notes related to multiple objcts - * - * @param array $a_rep_obj_ids repository object IDs array - * @param boolean $a_no_sub_objs include subobjects true/false - */ - static function _countNotesAndCommentsMultiple($a_rep_obj_ids, $a_no_sub_objs = false) - { - global $DIC; - - $ilDB = $DIC->database(); - $ilUser = $DIC->user(); - - $q = "SELECT count(id) c, rep_obj_id, type FROM note WHERE ". - " ((type = ".$ilDB->quote(IL_NOTE_PRIVATE, "integer")." AND ". - "author = ".$ilDB->quote((int) $ilUser->getId(), "integer").") OR ". - " type = ".$ilDB->quote(IL_NOTE_PUBLIC, "integer").") AND ". - $ilDB->in("rep_obj_id", $a_rep_obj_ids, false, "integer"); - - if ($a_no_sub_objs) - { - $q .= " AND obj_id = ".$ilDB->quote(0, "integer"); - } - - $q .= " GROUP BY rep_obj_id, type "; - - $cnt = array(); - $set = $ilDB->query($q); - while ($rec = $ilDB->fetchAssoc($set)) - { - $cnt[$rec["rep_obj_id"]][$rec["type"]] = $rec["c"]; - } - - return $cnt; - } - - /** - * Get all notes related to a specific object - * - * @param array $a_rep_obj_ids repository object IDs array - * @param int $a_sub_obj_id sub objects (if null, all comments are counted) - */ - static function _countNotesAndComments($a_rep_obj_id, $a_sub_obj_id = null, $a_obj_type = "", - $a_news_id = 0) - { - global $DIC; - - $ilDB = $DIC->database(); - $ilUser = $DIC->user(); - - $q = "SELECT count(id) c, rep_obj_id, type FROM note WHERE ". - " ((type = ".$ilDB->quote(IL_NOTE_PRIVATE, "integer")." AND ". - "author = ".$ilDB->quote((int) $ilUser->getId(), "integer").") OR ". - " type = ".$ilDB->quote(IL_NOTE_PUBLIC, "integer").") AND ". - " rep_obj_id = ".$ilDB->quote($a_rep_obj_id, "integer"); - - if ($a_sub_obj_id !== null) - { - $q .= " AND obj_id = ".$ilDB->quote($a_sub_obj_id, "integer"); - $q .= " AND obj_type = ".$ilDB->quote($a_obj_type, "text"); - } - - $q .= " AND news_id = ".$ilDB->quote($a_news_id, "integer"); - - $q .= " GROUP BY rep_obj_id, type "; - - $cnt = array(); - $set = $ilDB->query($q); - while ($rec = $ilDB->fetchAssoc($set)) - { - $cnt[$rec["rep_obj_id"]][$rec["type"]] = $rec["c"]; - } - - return $cnt; - } - - /** - * Activate notes feature - * - * @param - * @return - */ - static function activateComments($a_rep_obj_id, $a_obj_id, $a_obj_type, $a_activate = true) - { - global $DIC; - - $ilDB = $DIC->database(); - - if ($a_obj_type == "") - { - $a_obj_type = "-"; - } - $set = $ilDB->query("SELECT * FROM note_settings ". - " WHERE rep_obj_id = ".$ilDB->quote((int) $a_rep_obj_id, "integer"). - " AND obj_id = ".$ilDB->quote((int) $a_obj_id, "integer"). - " AND obj_type = ".$ilDB->quote($a_obj_type, "text") - ); - if ($rec = $ilDB->fetchAssoc($set)) - { - if (($rec["activated"] == 0 && $a_activate) || - ($rec["activated"] == 1 && !$a_activate)) - { - $ilDB->manipulate("UPDATE note_settings SET ". - " activated = ".$ilDB->quote((int) $a_activate, "integer"). - " WHERE rep_obj_id = ".$ilDB->quote((int) $a_rep_obj_id, "integer"). - " AND obj_id = ".$ilDB->quote((int) $a_obj_id, "integer"). - " AND obj_type = ".$ilDB->quote($a_obj_type, "text") - ); - } - } - else - { - if ($a_activate) - { - $q = "INSERT INTO note_settings ". - "(rep_obj_id, obj_id, obj_type, activated) VALUES (". - $ilDB->quote((int) $a_rep_obj_id, "integer").",". - $ilDB->quote((int) $a_obj_id, "integer").",". - $ilDB->quote($a_obj_type, "text").",". - $ilDB->quote(1, "integer"). - ")"; - $ilDB->manipulate($q); - } - } - } - - /** - * Are comments activated for object? - * - * @param - * @return - */ - static function commentsActivated($a_rep_obj_id, $a_obj_id, $a_obj_type, $a_news_id = 0) - { - global $DIC; - - $ilDB = $DIC->database(); - - if ($a_news_id > 0) - { - return true; - } - - if ($a_obj_type == "") - { - $a_obj_type = "-"; - } - $set = $ilDB->query("SELECT * FROM note_settings ". - " WHERE rep_obj_id = ".$ilDB->quote((int) $a_rep_obj_id, "integer"). - " AND obj_id = ".$ilDB->quote((int) $a_obj_id, "integer"). - " AND obj_type = ".$ilDB->quote($a_obj_type, "text") - ); - $rec = $ilDB->fetchAssoc($set); - return $rec["activated"]; - } - - /** - * Get activation for repository objects - * - * @param - * @return - */ - static function getRepObjActivation($a_rep_obj_ids) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT * FROM note_settings ". - " WHERE ".$ilDB->in("rep_obj_id", $a_rep_obj_ids, false, "integer"). - " AND obj_id = 0 "); - $activations = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - if ($rec["activated"]) - { - $activations[$rec["rep_obj_id"]][$rec["obj_type"]] = true; - } - } - - return $activations; - } - - - /** - * Send notifications - */ - function sendNotifications($a_changed = false) - { - $ilSetting = $this->settings; - $ilAccess = $this->access; - - // no notifications for notes - if ($this->getType() == IL_NOTE_PRIVATE) - { - return; - } - - $recipients = $ilSetting->get("comments_noti_recip"); - $recipients = explode(",", $recipients); - - // blog: blog_id, 0, "blog" - // lm: lm_id, page_id, "pg" (ok) - // sahs: sahs_id, node_id, node_type - // info_screen: obj_id, 0, obj_type (ok) - // portfolio: port_id, page_id, "portfolio_page" (ok) - // wiki: wiki_id, wiki_page_id, "wpg" (ok) - - $obj = $this->getObject(); - $rep_obj_id = $obj["rep_obj_id"]; - $sub_obj_id = $obj["obj_id"]; - $type = $obj["obj_type"]; - - include_once("./Services/Language/classes/class.ilLanguageFactory.php"); - include_once("./Services/User/classes/class.ilUserUtil.php"); - include_once("./Services/Mail/classes/class.ilMail.php"); - - // repository objects, no blogs - $ref_ids = array(); - if (($sub_obj_id == 0 and $type != "blp") || - in_array($type, array("pg", "wpg"))) - { - $obj_title = ilObject::_lookupTitle($rep_obj_id); - $type_lv = "obj_".$type; - $ref_ids = ilObject::_getAllReferences($rep_obj_id); - } - - if ($type == "wpg") - { - $type_lv = "obj_wiki"; - } - if ($type == "pg") - { - $type_lv = "obj_lm"; - } - if ($type == "blp") - { - $obj_title = ilObject::_lookupTitle($rep_obj_id); - $type_lv = "obj_blog"; - } - if ($type == "pfpg") - { - $obj_title = ilObject::_lookupTitle($rep_obj_id); - $type_lv = "portfolio"; - } - if ($type == "dcl") - { - $obj_title = ilObject::_lookupTitle($rep_obj_id); - $type_lv = "obj_dcl"; - } - - include_once("./Services/Link/classes/class.ilLink.php"); - foreach($recipients as $r) - { - $login = trim($r); - if (($user_id = ilObjUser::_lookupId($login)) > 0) - { - $link = ""; - foreach ($ref_ids as $r) - { - if ($ilAccess->checkAccessOfUser($user_id, "read", "", $r)) - { - if ($sub_obj_id == 0 and $type != "blog") - { - $link = ilLink::_getLink($r); - } - else if ($type == "wpg") - { - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - include_once("./Modules/Wiki/classes/class.ilWikiUtil.php"); - $title = ilWikiPage::lookupTitle($sub_obj_id); - $link = ilLink::_getStaticLink($r, "wiki", - true, "_".ilWikiUtil::makeUrlTitle($title)); - } - else if ($type == "pg") - { - $link = ILIAS_HTTP_PATH.'/goto.php?client_id='.CLIENT_ID."&target=pg_".$sub_obj_id."_".$r; - } - } - } - if ($type == "blp") - { - // todo - } - if ($type == "pfpg") - { - $link = ILIAS_HTTP_PATH.'/goto.php?client_id='.CLIENT_ID."&target=prtf_".$rep_obj_id; - } - - // use language of recipient to compose message - $ulng = ilLanguageFactory::_getLanguageOfUser($user_id); - $ulng->loadLanguageModule('note'); - - if ($a_changed) - { - $subject = sprintf($ulng->txt('note_comment_notification_subjectc'), $obj_title." (".$ulng->txt($type_lv).")"); - } - else - { - $subject = sprintf($ulng->txt('note_comment_notification_subject'), $obj_title." (".$ulng->txt($type_lv).")"); - } - $message = sprintf($ulng->txt('note_comment_notification_salutation'), ilObjUser::_lookupFullname($user_id))."\n\n"; - - $message.= sprintf($ulng->txt('note_comment_notification_user_has_written'), ilUserUtil::getNamePresentation($this->getAuthor()))."\n\n"; - - $message .= $this->getText()."\n\n"; - - if ($link != "") - { - $message .= $ulng->txt('note_comment_notification_link').": ".$link."\n\n"; - } - - $message .= $ulng->txt('note_comment_notification_reason')."\n\n"; - - $mail_obj = new ilMail(ANONYMOUS_USER_ID); - $mail_obj->appendInstallationSignature(true); - $mail_obj->sendMail(ilObjUser::_lookupLogin($user_id), - "", "", $subject, $message, array(), array("system")); - } - } - - } - + /** + * @var ilDB + */ + protected $db; + + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * object id (NOT ref_id!) of repository object (e.g for page objects + * the obj_id of the learning module; for personal desktop this is set to 0) + * + * @var int + */ + protected $rep_obj_id = 0; + + /** + * object id (e.g for page objects the obj_id of the page object) + * this is set to 0 for normal repository objects like forums ... + * + * @var int + */ + protected $obj_id; + + /** + * type of the object (e.g st,pg,crs ... NOT "news") + * + * @var string + */ + protected $obj_type; + + /** + * @var int + */ + protected $news_id; + + + /** + * constructor + */ + public function __construct($a_id = 0) + { + global $DIC; + + $this->db = $DIC->database(); + $this->settings = $DIC->settings(); + $this->access = $DIC->access(); + if ($a_id > 0) { + $this->id = $a_id; + $this->read(); + } + } + + /** + * set id + * + * @param int note id + */ + public function setId($a_id) + { + $this->id = $a_id; + } + + /** + * get id + * + * @return int note id + */ + public function getId() + { + return $this->id; + } + + /** + * set assigned object + * + * @param string $a_obj_type + * @param int $a_rep_obj_id + * @param int $a_obj_id + * @param int $a_news_id + */ + public function setObject($a_obj_type, $a_rep_obj_id, $a_obj_id = 0, $a_news_id = 0) + { + $this->rep_obj_id = $a_rep_obj_id; + $this->obj_id = $a_obj_id; + $this->obj_type = $a_obj_type; + $this->news_id = $a_news_id; + } + + public function getObject() + { + return array("rep_obj_id" => $this->rep_obj_id, + "obj_id" => $this->obj_id, + "obj_type" => $this->obj_type, + "news_id" => $this->news_id); + } + + + /** + * set type + * + * @param int IL_NOTE_PUBLIC | IL_NOTE_PRIVATE + */ + public function setType($a_type) + { + $this->type = $a_type; + } + + /** + * get type + * + * @return int IL_NOTE_PUBLIC | IL_NOTE_PRIVATE + */ + public function getType() + { + return $this->type; + } + + /** + * set author + * + * @param int author user id + */ + public function setAuthor($a_user_id) + { + $this->author = $a_user_id; + } + + /** + * get author + * + * @return int user id + */ + public function getAuthor() + { + return $this->author; + } + + /** + * set text + * + * @param string text + */ + public function setText($a_text) + { + $this->text = $a_text; + } + + /** + * get text + * + * @return string text + */ + public function getText() + { + return $this->text; + } + + /** + * set subject + * + * @param string text + */ + public function setSubject($a_subject) + { + $this->subject = $a_subject; + } + + /** + * get subject + * + * @return string subject + */ + public function getSubject() + { + return $this->subject; + } + + /** + * set creation date + * + * @param string creation date + */ + public function setCreationDate($a_date) + { + $this->creation_date = $a_date; + } + + /** + * get creation date + * + * @return string creation date + */ + public function getCreationDate() + { + return $this->creation_date; + } + + /** + * set update date + * + * @param string update date + */ + public function setUpdateDate($a_date) + { + $this->update_date = $a_date; + } + + /** + * get update date + * + * @return string update date + */ + public function getUpdateDate() + { + return $this->update_date; + } + + /** + * set label + * + * @param int IL_NOTE_UNLABELED | IL_NOTE_IMPORTANT | IL_NOTE_QUESTION + * | IL_NOTE_PRO | IL_NOTE_CONTRA + */ + public function setLabel($a_label) + { + return $this->label = $a_label; + } + + /** + * get label + * + * @return int IL_NOTE_UNLABELED | IL_NOTE_IMPORTANT | IL_NOTE_QUESTION + * | IL_NOTE_PRO | IL_NOTE_CONTRA + */ + public function getLabel() + { + return $this->label; + } + + /** + * Set news id + * + * @param int $a_val news id + */ + public function setNewsId($a_val) + { + $this->news_id = $a_val; + } + + /** + * Get news id + * + * @return int news id + */ + public function getNewsId() + { + return $this->news_id; + } + + /** + * set repository object status + * + * @param bool + */ + public function setInRepository($a_value) + { + return $this->no_repository = !(bool) $a_value; + } + + /** + * belongs note to repository object? + * + * @return bool + */ + public function isInRepository() + { + return !$this->no_repository; + } + + public function create($a_use_provided_creation_date = false) + { + $ilDB = $this->db; + + $cd = ($a_use_provided_creation_date) + ? $this->getCreationDate() + : ilUtil::now(); + + $this->id = $ilDB->nextId("note"); + + $ilDB->insert("note", array( + "id" => array("integer", $this->id), + "rep_obj_id" => array("integer", (int) $this->rep_obj_id), + "obj_id" => array("integer", (int) $this->obj_id), + "obj_type" => array("text", (string) $this->obj_type), + "news_id" => array("integer", (int) $this->news_id), + "type" => array("integer", (int) $this->type), + "author" => array("integer", (int) $this->author), + "note_text" => array("clob", (string) $this->text), + "subject" => array("text", (string) $this->subject), + "label" => array("integer", (int) $this->label), + "creation_date" => array("timestamp", $cd), + "no_repository" => array("integer", $this->no_repository) + )); + + $this->sendNotifications(); + + $this->creation_date = ilNote::_lookupCreationDate($this->getId()); + } + + public function update() + { + $ilDB = $this->db; + + $ilDB->update("note", array( + "rep_obj_id" => array("integer", (int) $this->rep_obj_id), + "obj_id" => array("integer", (int) $this->obj_id), + "news_id" => array("integer", (int) $this->news_id), + "obj_type" => array("text", (string) $this->obj_type), + "type" => array("integer", (int) $this->type), + "author" => array("integer", (int) $this->author), + "note_text" => array("clob", (string) $this->text), + "subject" => array("text", (string) $this->subject), + "label" => array("integer", (int) $this->label), + "update_date" => array("timestamp", ilUtil::now()), + "no_repository" => array("integer", $this->no_repository) + ), array( + "id" => array("integer", $this->getId()) + )); + + $this->update_date = ilNote::_lookupUpdateDate($this->getId()); + + $this->sendNotifications(true); + } + + public function read() + { + $ilDB = $this->db; + + $q = "SELECT * FROM note WHERE id = " . + $ilDB->quote((int) $this->getId(), "integer"); + $set = $ilDB->query($q); + $note_rec = $ilDB->fetchAssoc($set); + $this->setAllData($note_rec); + } + + /** + * delete note + */ + public function delete() + { + $ilDB = $this->db; + + $q = "DELETE FROM note WHERE id = " . + $ilDB->quote((int) $this->getId(), "integer"); + $ilDB->manipulate($q); + } + + /** + * set all note data by record array + */ + public function setAllData($a_note_rec) + { + $this->setId($a_note_rec["id"]); + $this->setObject( + $a_note_rec["obj_type"], + $a_note_rec["rep_obj_id"], + $a_note_rec["obj_id"], + $a_note_rec["news_id"] + ); + $this->setType($a_note_rec["type"]); + $this->setAuthor($a_note_rec["author"]); + $this->setText($a_note_rec["note_text"]); + $this->setSubject($a_note_rec["subject"]); + $this->setLabel($a_note_rec["label"]); + $this->setCreationDate($a_note_rec["creation_date"]); + $this->setUpdateDate($a_note_rec["update_date"]); + $this->setInRepository(!(bool) $a_note_rec["no_repository"]); + } + + /** + * lookup creation date of note + */ + public static function _lookupCreationDate($a_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "SELECT * FROM note WHERE id = " . + $ilDB->quote((int) $a_id, "integer"); + $set = $ilDB->query($q); + $note_rec = $ilDB->fetchAssoc($set); + + return $note_rec["creation_date"]; + } + + /** + * lookup update date of note + */ + public static function _lookupUpdateDate($a_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "SELECT * FROM note WHERE id = " . + $ilDB->quote((int) $a_id, "integer"); + $set = $ilDB->query($q); + $note_rec = $ilDB->fetchAssoc($set); + + return $note_rec["update_date"]; + } + + /** + * get all notes related to a specific object + */ + public static function _getNotesOfObject( + $a_rep_obj_id, + $a_obj_id, + $a_obj_type, + $a_type = IL_NOTE_PRIVATE, + $a_incl_sub = false, + $a_filter = "", + $a_all_public = "y", + $a_repository_mode = true, + $a_sort_ascending = false, + $a_news_id = 0 + ) { + global $DIC; + + $ilDB = $DIC->database(); + $ilUser = $DIC->user(); + + $author_where = ($a_type == IL_NOTE_PRIVATE || $a_all_public == "n") + ? " AND author = " . $ilDB->quote((int) $ilUser->getId(), "integer") + : ""; + + $sub_where = (!$a_incl_sub) + ? " AND obj_id = " . $ilDB->quote((int) $a_obj_id, "integer") . + " AND obj_type = " . $ilDB->quote((string) $a_obj_type, "text") + : ""; + + $news_where = + " AND news_id = " . $ilDB->quote((int) $a_news_id, "integer"); + + + $sub_where .= " AND no_repository = " . $ilDB->quote(!$a_repository_mode, "integer"); + + $q = "SELECT * FROM note WHERE " . + " rep_obj_id = " . $ilDB->quote((int) $a_rep_obj_id, "integer") . + $sub_where . + " AND type = " . $ilDB->quote((int) $a_type, "integer") . + $author_where . + $news_where . + " ORDER BY creation_date "; + + $q .= ((bool) $a_sort_ascending) ? "ASC" : "DESC"; + + $set = $ilDB->query($q); + $notes = array(); + while ($note_rec = $ilDB->fetchAssoc($set)) { + if ($a_filter != "") { + if (!is_array($a_filter)) { + $a_filter = array($a_filter); + } + if (!in_array($note_rec["id"], $a_filter)) { + continue; + } + } + $cnt = count($notes); + $notes[$cnt] = new ilNote(); + $notes[$cnt]->setAllData($note_rec); + } + + return $notes; + } + + /** + * get all notes related to a single repository object + */ + public static function _getAllNotesOfSingleRepObject( + $a_rep_obj_id, + $a_type = IL_NOTE_PRIVATE, + $a_incl_sub = false, + $a_sort_ascending = false, + $a_since = "" + ) { + global $DIC; + + $ilDB = $DIC->database(); + + $sub_where = (!$a_incl_sub) + ? " AND obj_id = " . $ilDB->quote((int) 0, "integer") : ""; + + if ($a_since != "") { + $sub_where.=" AND creation_date > " . $ilDB->quote($a_since, "timestamp"); + } + + $sub_where .= " AND no_repository = " . $ilDB->quote(0, "integer"); + + $q = "SELECT * FROM note WHERE " . + " rep_obj_id = " . $ilDB->quote((int) $a_rep_obj_id, "integer") . + $sub_where . + " AND type = " . $ilDB->quote((int) $a_type, "integer") . + " ORDER BY creation_date "; + + $q .= ((bool) $a_sort_ascending) ? "ASC" : "DESC"; + $set = $ilDB->query($q); + $notes = array(); + while ($note_rec = $ilDB->fetchAssoc($set)) { + $cnt = count($notes); + $notes[$cnt] = new ilNote(); + $notes[$cnt]->setAllData($note_rec); + } + return $notes; + } + + /** + * get last notes of current user + */ + public static function _getLastNotesOfUser() + { + global $DIC; + + $ilDB = $DIC->database(); + $ilUser = $DIC->user(); + + $q = "SELECT * FROM note WHERE " . + " type = " . $ilDB->quote((int) IL_NOTE_PRIVATE, "integer") . + " AND author = " . $ilDB->quote((int) $ilUser->getId(), "integer") . + " AND (no_repository IS NULL OR no_repository < " . $ilDB->quote(1, "integer") . ")" . + " ORDER BY creation_date DESC"; + + $ilDB->quote($q); + $set = $ilDB->query($q); + $notes = array(); + while ($note_rec = $ilDB->fetchAssoc($set)) { + $cnt = count($notes); + $notes[$cnt] = new ilNote(); + $notes[$cnt]->setAllData($note_rec); + } + + return $notes; + } + + /** + * get all related objects for user + */ + public static function _getRelatedObjectsOfUser($a_mode) + { + global $DIC; + + $ilDB = $DIC->database(); + $ilUser = $DIC->user(); + $tree = $DIC->repositoryTree(); + + if ($a_mode == ilPDNotesGUI::PRIVATE_NOTES) { + $q = "SELECT DISTINCT rep_obj_id FROM note WHERE " . + " type = " . $ilDB->quote((int) IL_NOTE_PRIVATE, "integer") . + " AND author = " . $ilDB->quote($ilUser->getId(), "integer") . + " AND (no_repository IS NULL OR no_repository < " . $ilDB->quote(1, "integer") . ")" . + " ORDER BY rep_obj_id"; + + $ilDB->quote($q); + $set = $ilDB->query($q); + $reps = array(); + while ($rep_rec = $ilDB->fetchAssoc($set)) { + // #9343: deleted objects + if (ilObject::_lookupType($rep_rec["rep_obj_id"])) { + $reps[] = array("rep_obj_id" => $rep_rec["rep_obj_id"]); + } + } + } else { + // all objects where the user wrote at least one comment + $q = "SELECT DISTINCT rep_obj_id FROM note WHERE " . + " type = " . $ilDB->quote((int) IL_NOTE_PUBLIC, "integer") . + " AND author = " . $ilDB->quote($ilUser->getId(), "integer") . + " AND (no_repository IS NULL OR no_repository < " . $ilDB->quote(1, "integer") . ")" . + " ORDER BY rep_obj_id"; + + $set = $ilDB->query($q); + $reps = array(); + while ($rep_rec = $ilDB->fetchAssoc($set)) { + // #9343: deleted objects + if ($type = ilObject::_lookupType($rep_rec["rep_obj_id"])) { + if (ilNote::commentsActivated($rep_rec["rep_obj_id"], "", $type)) { + $reps[] = array("rep_obj_id" => $rep_rec["rep_obj_id"]); + } + } + } + + // additionally all objects on the personal desktop of the user + // that have at least on comment + $dis = ilObjUser::_lookupDesktopItems($ilUser->getId()); + $obj_ids = array(); + foreach ($dis as $di) { + $obj_ids[] = $di["obj_id"]; + } + if (count($obj_ids) > 0) { + $q = "SELECT DISTINCT rep_obj_id FROM note WHERE " . + $ilDB->in("rep_obj_id", $obj_ids, false, "integer") . + " AND (no_repository IS NULL OR no_repository < " . $ilDB->quote(1, "integer") . ")"; + + $set = $ilDB->query($q); + while ($rec = $ilDB->fetchAssoc($set)) { + $add = true; + reset($reps); + foreach ($reps as $r) { + if ($r["rep_obj_id"] == $rec["rep_obj_id"]) { + $add = false; + } + } + if ($add) { + $type = ilObject::_lookupType($rec["rep_obj_id"]); + if (ilNote::commentsActivated($rec["rep_obj_id"], "", $type)) { + $reps[] = array("rep_obj_id" => $rec["rep_obj_id"]); + } + } + } + } + } + + if (sizeof($reps)) { + // check if notes/comments belong to objects in trash + // see ilNoteGUI::showTargets() + foreach ($reps as $idx => $rep) { + $has_active_ref = false; + + // repository? + $ref_ids = ilObject::_getAllReferences($rep["rep_obj_id"]); + if ($ref_ids) { + $reps[$idx]["ref_ids"] = array_values($ref_ids); + + foreach ($ref_ids as $ref_id) { + if (!$tree->isDeleted($ref_id)) { + $has_active_ref = true; + break; + } + } + } else { + // personal workspace? + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; + $wsp_tree = new ilWorkspaceTree($ilUser->getId()); + $node_id = $wsp_tree->lookupNodeId($rep["rep_obj_id"]); + if ($node_id) { + $reps[$idx]["wsp_id"] = $node_id; + + $has_active_ref = true; + } + } + + if (!$has_active_ref) { + unset($reps[$idx]); + } + } + } + + return $reps; + } + + /** + * How many users have attached a note/comment to a given object? + * + * @param int $a_rep_obj_id object id (as in object data) + * @param int $a_obj_id (sub) object id + * @param string $a_type (sub) object type + */ + public static function getUserCount($a_rep_obj_id, $a_obj_id, $a_type) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->queryF( + "SELECT count(DISTINCT author) cnt FROM note WHERE " . + "rep_obj_id = %s AND obj_id = %s AND obj_type = %s", + array("integer", "integer", "text"), + array((int) $a_rep_obj_id, (int) $a_obj_id, (string) $a_type) + ); + $rec = $ilDB->fetchAssoc($set); + return (int) $rec["cnt"]; + } + + /** + * Get all notes related to multiple objcts + * + * @param array $a_rep_obj_ids repository object IDs array + * @param boolean $a_no_sub_objs include subobjects true/false + */ + public static function _countNotesAndCommentsMultiple($a_rep_obj_ids, $a_no_sub_objs = false) + { + global $DIC; + + $ilDB = $DIC->database(); + $ilUser = $DIC->user(); + + $q = "SELECT count(id) c, rep_obj_id, type FROM note WHERE " . + " ((type = " . $ilDB->quote(IL_NOTE_PRIVATE, "integer") . " AND " . + "author = " . $ilDB->quote((int) $ilUser->getId(), "integer") . ") OR " . + " type = " . $ilDB->quote(IL_NOTE_PUBLIC, "integer") . ") AND " . + $ilDB->in("rep_obj_id", $a_rep_obj_ids, false, "integer"); + + if ($a_no_sub_objs) { + $q .= " AND obj_id = " . $ilDB->quote(0, "integer"); + } + + $q .= " GROUP BY rep_obj_id, type "; + + $cnt = array(); + $set = $ilDB->query($q); + while ($rec = $ilDB->fetchAssoc($set)) { + $cnt[$rec["rep_obj_id"]][$rec["type"]] = $rec["c"]; + } + + return $cnt; + } + + /** + * Get all notes related to a specific object + * + * @param array $a_rep_obj_ids repository object IDs array + * @param int $a_sub_obj_id sub objects (if null, all comments are counted) + */ + public static function _countNotesAndComments( + $a_rep_obj_id, + $a_sub_obj_id = null, + $a_obj_type = "", + $a_news_id = 0 + ) { + global $DIC; + + $ilDB = $DIC->database(); + $ilUser = $DIC->user(); + + $q = "SELECT count(id) c, rep_obj_id, type FROM note WHERE " . + " ((type = " . $ilDB->quote(IL_NOTE_PRIVATE, "integer") . " AND " . + "author = " . $ilDB->quote((int) $ilUser->getId(), "integer") . ") OR " . + " type = " . $ilDB->quote(IL_NOTE_PUBLIC, "integer") . ") AND " . + " rep_obj_id = " . $ilDB->quote($a_rep_obj_id, "integer"); + + if ($a_sub_obj_id !== null) { + $q .= " AND obj_id = " . $ilDB->quote($a_sub_obj_id, "integer"); + $q .= " AND obj_type = " . $ilDB->quote($a_obj_type, "text"); + } + + $q .= " AND news_id = " . $ilDB->quote($a_news_id, "integer"); + + $q .= " GROUP BY rep_obj_id, type "; + + $cnt = array(); + $set = $ilDB->query($q); + while ($rec = $ilDB->fetchAssoc($set)) { + $cnt[$rec["rep_obj_id"]][$rec["type"]] = $rec["c"]; + } + + return $cnt; + } + + /** + * Activate notes feature + * + * @param + * @return + */ + public static function activateComments($a_rep_obj_id, $a_obj_id, $a_obj_type, $a_activate = true) + { + global $DIC; + + $ilDB = $DIC->database(); + + if ($a_obj_type == "") { + $a_obj_type = "-"; + } + $set = $ilDB->query( + "SELECT * FROM note_settings " . + " WHERE rep_obj_id = " . $ilDB->quote((int) $a_rep_obj_id, "integer") . + " AND obj_id = " . $ilDB->quote((int) $a_obj_id, "integer") . + " AND obj_type = " . $ilDB->quote($a_obj_type, "text") + ); + if ($rec = $ilDB->fetchAssoc($set)) { + if (($rec["activated"] == 0 && $a_activate) || + ($rec["activated"] == 1 && !$a_activate)) { + $ilDB->manipulate( + "UPDATE note_settings SET " . + " activated = " . $ilDB->quote((int) $a_activate, "integer") . + " WHERE rep_obj_id = " . $ilDB->quote((int) $a_rep_obj_id, "integer") . + " AND obj_id = " . $ilDB->quote((int) $a_obj_id, "integer") . + " AND obj_type = " . $ilDB->quote($a_obj_type, "text") + ); + } + } else { + if ($a_activate) { + $q = "INSERT INTO note_settings " . + "(rep_obj_id, obj_id, obj_type, activated) VALUES (" . + $ilDB->quote((int) $a_rep_obj_id, "integer") . "," . + $ilDB->quote((int) $a_obj_id, "integer") . "," . + $ilDB->quote($a_obj_type, "text") . "," . + $ilDB->quote(1, "integer") . + ")"; + $ilDB->manipulate($q); + } + } + } + + /** + * Are comments activated for object? + * + * @param + * @return + */ + public static function commentsActivated($a_rep_obj_id, $a_obj_id, $a_obj_type, $a_news_id = 0) + { + global $DIC; + + $ilDB = $DIC->database(); + + if ($a_news_id > 0) { + return true; + } + + if ($a_obj_type == "") { + $a_obj_type = "-"; + } + $set = $ilDB->query( + "SELECT * FROM note_settings " . + " WHERE rep_obj_id = " . $ilDB->quote((int) $a_rep_obj_id, "integer") . + " AND obj_id = " . $ilDB->quote((int) $a_obj_id, "integer") . + " AND obj_type = " . $ilDB->quote($a_obj_type, "text") + ); + $rec = $ilDB->fetchAssoc($set); + return $rec["activated"]; + } + + /** + * Get activation for repository objects + * + * @param + * @return + */ + public static function getRepObjActivation($a_rep_obj_ids) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query("SELECT * FROM note_settings " . + " WHERE " . $ilDB->in("rep_obj_id", $a_rep_obj_ids, false, "integer") . + " AND obj_id = 0 "); + $activations = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + if ($rec["activated"]) { + $activations[$rec["rep_obj_id"]][$rec["obj_type"]] = true; + } + } + + return $activations; + } + + + /** + * Send notifications + */ + public function sendNotifications($a_changed = false) + { + $ilSetting = $this->settings; + $ilAccess = $this->access; + + // no notifications for notes + if ($this->getType() == IL_NOTE_PRIVATE) { + return; + } + + $recipients = $ilSetting->get("comments_noti_recip"); + $recipients = explode(",", $recipients); + + // blog: blog_id, 0, "blog" + // lm: lm_id, page_id, "pg" (ok) + // sahs: sahs_id, node_id, node_type + // info_screen: obj_id, 0, obj_type (ok) + // portfolio: port_id, page_id, "portfolio_page" (ok) + // wiki: wiki_id, wiki_page_id, "wpg" (ok) + + $obj = $this->getObject(); + $rep_obj_id = $obj["rep_obj_id"]; + $sub_obj_id = $obj["obj_id"]; + $type = $obj["obj_type"]; + + include_once("./Services/Language/classes/class.ilLanguageFactory.php"); + include_once("./Services/User/classes/class.ilUserUtil.php"); + include_once("./Services/Mail/classes/class.ilMail.php"); + + // repository objects, no blogs + $ref_ids = array(); + if (($sub_obj_id == 0 and $type != "blp") || + in_array($type, array("pg", "wpg"))) { + $obj_title = ilObject::_lookupTitle($rep_obj_id); + $type_lv = "obj_" . $type; + $ref_ids = ilObject::_getAllReferences($rep_obj_id); + } + + if ($type == "wpg") { + $type_lv = "obj_wiki"; + } + if ($type == "pg") { + $type_lv = "obj_lm"; + } + if ($type == "blp") { + $obj_title = ilObject::_lookupTitle($rep_obj_id); + $type_lv = "obj_blog"; + } + if ($type == "pfpg") { + $obj_title = ilObject::_lookupTitle($rep_obj_id); + $type_lv = "portfolio"; + } + if ($type == "dcl") { + $obj_title = ilObject::_lookupTitle($rep_obj_id); + $type_lv = "obj_dcl"; + } + + include_once("./Services/Link/classes/class.ilLink.php"); + foreach ($recipients as $r) { + $login = trim($r); + if (($user_id = ilObjUser::_lookupId($login)) > 0) { + $link = ""; + foreach ($ref_ids as $r) { + if ($ilAccess->checkAccessOfUser($user_id, "read", "", $r)) { + if ($sub_obj_id == 0 and $type != "blog") { + $link = ilLink::_getLink($r); + } elseif ($type == "wpg") { + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + include_once("./Modules/Wiki/classes/class.ilWikiUtil.php"); + $title = ilWikiPage::lookupTitle($sub_obj_id); + $link = ilLink::_getStaticLink( + $r, + "wiki", + true, + "_" . ilWikiUtil::makeUrlTitle($title) + ); + } elseif ($type == "pg") { + $link = ILIAS_HTTP_PATH . '/goto.php?client_id=' . CLIENT_ID . "&target=pg_" . $sub_obj_id . "_" . $r; + } + } + } + if ($type == "blp") { + // todo + } + if ($type == "pfpg") { + $link = ILIAS_HTTP_PATH . '/goto.php?client_id=' . CLIENT_ID . "&target=prtf_" . $rep_obj_id; + } + + // use language of recipient to compose message + $ulng = ilLanguageFactory::_getLanguageOfUser($user_id); + $ulng->loadLanguageModule('note'); + + if ($a_changed) { + $subject = sprintf($ulng->txt('note_comment_notification_subjectc'), $obj_title . " (" . $ulng->txt($type_lv) . ")"); + } else { + $subject = sprintf($ulng->txt('note_comment_notification_subject'), $obj_title . " (" . $ulng->txt($type_lv) . ")"); + } + $message = sprintf($ulng->txt('note_comment_notification_salutation'), ilObjUser::_lookupFullname($user_id)) . "\n\n"; + + $message.= sprintf($ulng->txt('note_comment_notification_user_has_written'), ilUserUtil::getNamePresentation($this->getAuthor())) . "\n\n"; + + $message .= $this->getText() . "\n\n"; + + if ($link != "") { + $message .= $ulng->txt('note_comment_notification_link') . ": " . $link . "\n\n"; + } + + $message .= $ulng->txt('note_comment_notification_reason') . "\n\n"; + + $mail_obj = new ilMail(ANONYMOUS_USER_ID); + $mail_obj->appendInstallationSignature(true); + $mail_obj->sendMail( + ilObjUser::_lookupLogin($user_id), + "", + "", + $subject, + $message, + array(), + array("system") + ); + } + } + } } -?> \ No newline at end of file diff --git a/Services/Notes/classes/class.ilNoteGUI.php b/Services/Notes/classes/class.ilNoteGUI.php index 99fe6112592dea14b6c7a1098cee774bce5dd538..b5022f6be9a42b5303f4e823fb8c0132c5afff37 100644 --- a/Services/Notes/classes/class.ilNoteGUI.php +++ b/Services/Notes/classes/class.ilNoteGUI.php @@ -3,7 +3,7 @@ /* Copyright (c) 1998-2011 ILIAS open source, Extended GPL, see docs/LICENSE */ -include_once ("Services/Notes/classes/class.ilNote.php"); +include_once("Services/Notes/classes/class.ilNote.php"); /** @@ -17,1897 +17,1798 @@ include_once ("Services/Notes/classes/class.ilNote.php"); */ class ilNoteGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilSetting - */ - protected $settings; - - /** - * @var ilObjectDefinition - */ - protected $obj_definition; - - /** - * @var ilTree - */ - protected $tree; - - /** - * @var ilAccessHandler - */ - protected $access; - - var $public_deletion_enabled = false; - var $repository_mode = false; - var $old = false; - - protected $default_command = "getNotesHTML"; - - /** @var array */ - protected $observer = []; - - /** - * @var \ILIAS\DI\UIServices - */ - protected $ui; - - /** - * @var int - */ - protected $news_id = 0; - - /** - * hide new note/comment form - * @var bool - */ - protected $hide_new_form = false; - - /** - * Show only latest note/comment - * @var bool - */ - protected $only_latest = false; - - /** - * @var string - */ - protected $widget_header = ""; - - /** - * Do not show edit/delete actions - * @var bool - */ - protected $no_actions = false; - - /** - * constructor, specifies notes set - * - * @param $a_rep_obj_id int object id of repository object (0 for personal desktop) - * @param $a_obj_id int subobject id (0 for repository items, user id for personal desktop) - * @param $a_obj_type string "pd" for personal desktop - * @param $a_include_subobjects string include all subobjects of rep object (e.g. pages) - */ - function __construct($a_rep_obj_id = "", $a_obj_id = "", $a_obj_type = "", $a_include_subobjects = false, - $a_news_id = 0) - { - global $DIC; - - $this->user = $DIC->user(); - $this->settings = $DIC->settings(); - $this->obj_definition = $DIC["objDefinition"]; - $this->tree = $DIC->repositoryTree(); - $this->access = $DIC->access(); - $this->ui = $DIC->ui(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $lng->loadLanguageModule("notes"); - - $ilCtrl->saveParameter($this, "notes_only"); - $this->only = $_GET["notes_only"]; - - $this->rep_obj_id = $a_rep_obj_id; - $this->obj_id = $a_obj_id; - $this->obj_type = $a_obj_type; - $this->inc_sub = $a_include_subobjects; - $this->news_id = $a_news_id; - - // auto-detect object type - if(!$this->obj_type && $a_rep_obj_id) - { - $this->obj_type = ilObject::_lookupType($a_rep_obj_id); - } - - $this->ajax = $ilCtrl->isAsynch(); - - $this->ctrl = $ilCtrl; - $this->lng = $lng; - - $this->anchor_jump = true; - $this->add_note_form = false; - $this->edit_note_form = false; - $this->private_enabled = false; - - if (ilNote::commentsActivated($this->rep_obj_id, $this->obj_id, $this->obj_type, $this->news_id)) - { - $this->public_enabled = true; - } - else - { - $this->public_enabled = false; - } - $this->enable_hiding = false; - $this->targets_enabled = false; - $this->multi_selection = false; - $this->export_html = false; - $this->print = false; - $this->comments_settings = false; - - $this->note_img = array( - IL_NOTE_UNLABELED => array( - "img" => ilUtil::getImagePath("note_unlabeled.svg"), - "alt" => $lng->txt("note")), - IL_NOTE_IMPORTANT => array( - "img" => ilUtil::getImagePath("note_unlabeled.svg"), - "alt" => $lng->txt("note").", ".$lng->txt("important")), - IL_NOTE_QUESTION => array( - "img" => ilUtil::getImagePath("note_unlabeled.svg"), - "alt" => $lng->txt("note").", ".$lng->txt("question")), - IL_NOTE_PRO => array( - "img" => ilUtil::getImagePath("note_unlabeled.svg"), - "alt" => $lng->txt("note").", ".$lng->txt("pro")), - IL_NOTE_CONTRA => array( - "img" => ilUtil::getImagePath("note_unlabeled.svg"), - "alt" => $lng->txt("note").", ".$lng->txt("contra")) - ); - - $this->comment_img = array( - IL_NOTE_UNLABELED => array( - "img" => ilUtil::getImagePath("comment_unlabeled.svg"), - "alt" => $lng->txt("notes_comment")), - IL_NOTE_IMPORTANT => array( - "img" => ilUtil::getImagePath("comment_unlabeled.svg"), - "alt" => $lng->txt("notes_comment").", ".$lng->txt("important")), - IL_NOTE_QUESTION => array( - "img" => ilUtil::getImagePath("comment_unlabeled.svg"), - "alt" => $lng->txt("notes_comment").", ".$lng->txt("question")), - IL_NOTE_PRO => array( - "img" => ilUtil::getImagePath("comment_unlabeled.svg"), - "alt" => $lng->txt("notes_comment").", ".$lng->txt("pro")), - IL_NOTE_CONTRA => array( - "img" => ilUtil::getImagePath("comment_unlabeled.svg"), - "alt" => $lng->txt("notes_comment").", ".$lng->txt("contra")) - ); - - // default: notes for repository objects - $this->setRepositoryMode(true); - } - - /** - * Set default command - * - * @param string $a_val default command - */ - public function setDefaultCommand($a_val) - { - $this->default_command = $a_val; - } - - /** - * Get default command - * - * @return string default command - */ - public function getDefaultCommand() - { - return $this->default_command; - } - - /** - * execute command - */ - function executeCommand() - { - $cmd = $this->ctrl->getCmd($this->getDefaultCommand()); - $next_class = $this->ctrl->getNextClass($this); - - switch($next_class) - { - default: - return $this->$cmd(); - break; - } - } - - /** - * enable private notes - */ - function enablePrivateNotes($a_enable = true) - { - $this->private_enabled = $a_enable; - } - - /** - * enable public notes - */ - function enablePublicNotes($a_enable = true) - { - $this->public_enabled = $a_enable; - } - - /** - * enable private notes - */ - function enableCommentsSettings($a_enable = true) - { - $this->comments_settings = $a_enable; - } - - /** - * enable public notes - */ - function enablePublicNotesDeletion($a_enable = true) - { - $this->public_deletion_enabled = $a_enable; - } - - /** - * enable hiding - */ - function enableHiding($a_enable = true) - { - $this->enable_hiding = $a_enable; - } - - /** - * enable target objects - */ - function enableTargets($a_enable = true) - { - $this->targets_enabled = $a_enable; - } - - /** - * enable multi selection (checkboxes and commands) - */ - function enableMultiSelection($a_enable = true) - { - $this->multi_selection = $a_enable; - } - - /** - * enable anchor for form jump - */ - function enableAnchorJump($a_enable = true) - { - $this->anchor_jump = $a_enable; - } - - /** - * Set repository mode - * - * @param bool $a_value - */ - function setRepositoryMode($a_value) - { - $this->repository_mode = (bool)$a_value; - } - - - /** - * Get only notes html - * - * @param - * @return - */ - function getOnlyNotesHTML() - { - $ilCtrl = $this->ctrl; - $ilCtrl->setParameter($this, "notes_only", "notes"); - $this->only = "notes"; - return $this->getNotesHTML($a_init_form = true); - } - - /** - * Get only comments html - * - * @param - * @return - */ - function getOnlyCommentsHTML() - { - $ilCtrl = $this->ctrl; - $ilCtrl->setParameter($this, "notes_only", "comments"); - $this->only = "comments"; - return $this->getNotesHTML($a_init_form = true); - } - - - /*** - * get note lists html code - */ - function getNotesHTML($a_init_form = true) - { - $ilUser = $this->user; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilSetting = $this->settings; - - $lng->loadLanguageModule("notes"); - - $ntpl = new ilTemplate("tpl.notes_and_comments.html", true, true, - "Services/Notes"); - - // check, whether column is hidden due to processing in other column - $hide_comments = ($this->only == "notes"); - $hide_notes = ($this->only == "comments"); - switch($ilCtrl->getCmd()) - { - case "addNoteForm": - case "editNoteForm": - case "addNote": - case "updateNote": - if ($_GET["note_type"] == IL_NOTE_PRIVATE) - { - $hide_comments = true; - } - if ($_GET["note_type"] == IL_NOTE_PUBLIC) - { - $hide_notes = true; - } - break; - } - - -// temp workaround: only show comments (if both have been activated) -if ($this->private_enabled && $this->public_enabled - && $this->only != "notes") -{ - $this->private_enabled = false; -} - - $nodes_col = false; - if ($this->private_enabled && ($ilUser->getId() != ANONYMOUS_USER_ID) - && !$hide_notes) - { - $ntpl->setCurrentBlock("notes_col"); - $ntpl->setVariable("NOTES", $this->getNoteListHTML(IL_NOTE_PRIVATE, $a_init_form)); - $ntpl->parseCurrentBlock(); - $nodes_col = true; - } - - // #15948 - public enabled vs. comments_settings - $comments_col = false; - if ($this->public_enabled && (!$this->delete_note || $this->public_deletion_enabled || $ilSetting->get("comments_del_user", 0)) - && !$hide_comments /* && $ilUser->getId() != ANONYMOUS_USER_ID */) - { - $ntpl->setVariable("COMMENTS", $this->getNoteListHTML(IL_NOTE_PUBLIC, $a_init_form)); - $comments_col = true; - } - - // Comments Settings - if ($this->comments_settings && !$hide_comments && !$this->delete_note - && !$this->edit_note_form && !$this->add_note_form && $ilUser->getId() != ANONYMOUS_USER_ID) - { - //$active = $notes_settings->get("activate_".$id); - $active = ilNote::commentsActivated($this->rep_obj_id, $this->obj_id, $this->obj_type); - - if ($active) - { - if ($this->news_id == 0) - { - $this->renderLink($ntpl, "comments_settings", $lng->txt("notes_deactivate_comments"), - "deactivateComments", "notes_top"); - } - $ntpl->setCurrentBlock("comments_settings2"); - } - else - { - $this->renderLink($ntpl, "comments_settings", $lng->txt("notes_activate_comments"), - "activateComments", "notes_top"); - $ntpl->setCurrentBlock("comments_settings2"); - - if ($this->ajax && !$comments_col) - { - $ntpl->setVariable("COMMENTS_MESS", - $ntpl->getMessageHTML($lng->txt("comments_feature_currently_not_activated_for_object"), "info")); - } - } - $ntpl->parseCurrentBlock(); - - if (!$comments_col) - { - $ntpl->setVariable("COMMENTS", ""); - } - - $comments_col = true; - } - - if ($comments_col) - { - $ntpl->setCurrentBlock("comments_col"); - if ($nodes_col) - { -// $ntpl->touchBlock("comments_style"); - } - $ntpl->parseCurrentBlock(); - } - - if ($this->ajax) - { - echo $ntpl->get(); - exit; - } - - return $ntpl->get(); - } - - /** - * Activate Comments - */ - function activateComments() - { - $ilCtrl = $this->ctrl; - - if ($this->comments_settings) - { - ilNote::activateComments($this->rep_obj_id, $this->obj_id, $this->obj_type, true); - } - - $ilCtrl->redirectByClass("ilnotegui", "showNotes", "", $this->ajax); - } - - /** - * Deactivate Comments - */ - function deactivateComments() - { - $ilCtrl = $this->ctrl; - - if ($this->comments_settings) - { - ilNote::activateComments($this->rep_obj_id, $this->obj_id, $this->obj_type, false); - } - - $ilCtrl->redirectByClass("ilnotegui", "showNotes", "", $this->ajax); - } - - /** - * get notes/comments list as html code - */ - function getNoteListHTML($a_type = IL_NOTE_PRIVATE, $a_init_form = true) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - include_once("./Services/User/classes/class.ilUserUtil.php"); - - $suffix = ($a_type == IL_NOTE_PRIVATE) - ? "private" - : "public"; - - $user_setting_notes_public_all = "y"; - $user_setting_notes_by_type = "y"; - - if ($this->delete_note || $this->export_html || $this->print) - { - if ($_GET["note_id"] != "") - { - $filter = $_GET["note_id"]; - } - else - { - $filter = $_POST["note"]; - } - } - - $order = (bool) $_SESSION["comments_sort_asc"]; - if ($this->only_latest) - { - $order = false; - } - - - $notes = ilNote::_getNotesOfObject($this->rep_obj_id, $this->obj_id, - $this->obj_type, $a_type, $this->inc_sub, $filter, - $user_setting_notes_public_all, $this->repository_mode, $order, - $this->news_id); - - $tpl = new ilTemplate("tpl.notes_list.html", true, true, "Services/Notes"); - - if ($this->ajax) - { - include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); - $tpl->setCurrentBlock("close_img"); - $tpl->setVariable("CLOSE_IMG", ilGlyphGUI::get(ilGlyphGUI::CLOSE)); - $tpl->parseCurrentBlock(); - } - - // show counter if notes are hidden - $cnt_str = (count($notes) > 0) - ? " (".count($notes).")" - : ""; - - // title - if ($this->ajax && !$this->only_latest) - { - switch($this->obj_type) - { - case "grpr": - case "catr": - case "crsr": - include_once "Services/ContainerReference/classes/class.ilContainerReference.php"; - $title = ilContainerReference::_lookupTitle($this->rep_obj_id); - break; - - default: - $title = ilObject::_lookupTitle($this->rep_obj_id); - break; - } - - $img = ilUtil::img(ilObject::_getIcon($this->rep_obj_id, "tiny")); - - // add sub-object if given - if($this->obj_id) - { - $sub_title = $this->getSubObjectTitle($this->rep_obj_id, $this->obj_id); - if($sub_title) - { - $title .= " - ".$sub_title; - } - } - - $tpl->setCurrentBlock("title"); - $tpl->setVariable("TITLE", $img." ".$title); - $tpl->parseCurrentBlock(); - } - - if ($this->delete_note) - { - $cnt_str = ""; - } - if ($a_type == IL_NOTE_PRIVATE) - { - $tpl->setVariable("TXT_NOTES", $lng->txt("private_notes").$cnt_str); - $ilCtrl->setParameterByClass("ilnotegui", "note_type", IL_NOTE_PRIVATE); - } - else - { - $tpl->setVariable("TXT_NOTES", $lng->txt("notes_public_comments").$cnt_str); - $ilCtrl->setParameterByClass("ilnotegui", "note_type", IL_NOTE_PUBLIC); - } - $anch = $this->anchor_jump - ? "notes_top" - : ""; - if (!$this->only_latest) { - $tpl->setVariable("FORMACTION", $ilCtrl->getFormAction($this, "getNotesHTML", $anch)); - if ($this->ajax) - { - $os = "onsubmit = \"ilNotes.cmdAjaxForm(event, '". - $ilCtrl->getFormActionByClass("ilnotegui", "", "", true). - "'); return false;\""; - $tpl->setVariable("ON_SUBMIT_FORM", $os); - $tpl->setVariable("FORM_ID", "Ajax"); - } - } - - - if ($this->export_html || $this->print) - { - $tpl->touchBlock("print_style"); - } - - // show add new note button - if (!$this->add_note_form && !$this->edit_note_form && !$this->delete_note && - !$this->export_html && !$this->print && $ilUser->getId() != ANONYMOUS_USER_ID && !$this->hide_new_form) - { - if (!$this->inc_sub) // we cannot offer add button if aggregated notes - { // are displayed - if ($this->rep_obj_id > 0 || $a_type != IL_NOTE_PUBLIC) - { - $tpl->setCurrentBlock("add_note_btn"); - if ($a_type == IL_NOTE_PUBLIC) - { - $tpl->setVariable("TXT_ADD_NOTE", $lng->txt("notes_add_comment")); - } - else - { - $tpl->setVariable("TXT_ADD_NOTE", $lng->txt("add_note")); - } - $tpl->setVariable("LINK_ADD_NOTE", $ilCtrl->getLinkTargetByClass("ilnotegui", "addNoteForm"). - "#note_edit"); - $tpl->parseCurrentBlock(); - } - } - } - - // show show/hide button for note list - if (count($notes) > 0 && $this->enable_hiding && !$this->delete_note - && !$this->export_html && !$this->print && !$this->edit_note_form - && !$this->add_note_form) - { - if ($user_setting_notes_by_type == "n") - { - if ($a_type == IL_NOTE_PUBLIC) - { - $txt = $lng->txt("notes_show_comments"); - } - else - { - $txt = $lng->txt("show_".$suffix."_notes"); - } - $this->renderLink($tpl, "show_notes", $txt, "showNotes", "notes_top"); - } - else - { - // never individually hide for anonymous users - if (($ilUser->getId() != ANONYMOUS_USER_ID)) - { - if ($a_type == IL_NOTE_PUBLIC) - { - $txt = $lng->txt("notes_hide_comments"); - } - else - { - $txt = $lng->txt("hide_".$suffix."_notes"); - } - $this->renderLink($tpl, "hide_notes", $txt, "hideNotes", "notes_top"); - - // show all public notes / my notes only switch - if ($a_type == IL_NOTE_PUBLIC) - { - if ($user_setting_notes_public_all == "n") - { - $this->renderLink($tpl, "all_pub_notes", $lng->txt("notes_all_comments"), - "showAllPublicNotes", "notes_top"); - } - else - { - $this->renderLink($tpl, "my_pub_notes", $lng->txt("notes_my_comments"), - "showMyPublicNotes", "notes_top"); - } - } - } - } - } - - // show add new note text area - if (!$this->edit_note_form && $user_setting_notes_by_type != "n" && - !$this->delete_note && $ilUser->getId() != ANONYMOUS_USER_ID && !$this->hide_new_form) - { - if ($a_init_form) - { - $this->initNoteForm("create", $a_type); - } - - $tpl->setCurrentBlock("edit_note_form"); -// $tpl->setVariable("EDIT_FORM", $this->form->getHTML()); - $tpl->setVariable("EDIT_FORM", $this->form_tpl->get()); - $tpl->parseCurrentBlock(); - - $tpl->parseCurrentBlock(); - $tpl->setCurrentBlock("note_row"); - $tpl->parseCurrentBlock(); - } - - // list all notes - if ($user_setting_notes_by_type != "n" || !$this->enable_hiding) - { - $reldates = ilDatePresentation::useRelativeDates(); - ilDatePresentation::setUseRelativeDates(false); - - if(sizeof($notes) && !$this->only_latest) - { - if((int)$_SESSION["comments_sort_asc"] == 1) - { - $sort_txt = $lng->txt("notes_sort_desc"); - $sort_cmd = "listSortDesc"; - } - else - { - $sort_txt = $lng->txt("notes_sort_asc"); - $sort_cmd = "listSortAsc"; - } - $this->renderLink($tpl, "sort_list", $sort_txt, $sort_cmd, $anch); - } - - $notes_given = false; - foreach($notes as $note) - { - if ($this->only_latest && $notes_given) - { - continue; - } - - - if ($this->edit_note_form && ($note->getId() == $_GET["note_id"]) - && $a_type == $_GET["note_type"]) - { - if ($a_init_form) - { - $this->initNoteForm("edit", $a_type, $note); - } - $tpl->setCurrentBlock("edit_note_form"); -// $tpl->setVariable("EDIT_FORM", $this->form->getHTML()); - $tpl->setVariable("EDIT_FORM", $this->form_tpl->get()); - $tpl->parseCurrentBlock(); - } - else - { - $cnt_col = 2; - - // delete note stuff for all private notes - if ($this->checkDeletion($note) - && !$this->delete_note - && !$this->export_html && !$this->print - && !$this->edit_note_form && !$this->add_note_form && !$this->no_actions) - { - $ilCtrl->setParameterByClass("ilnotegui", "note_id", $note->getId()); - $this->renderLink($tpl, "delete_note", $lng->txt("delete"), - "deleteNote", "note_".$note->getId()); - } - - // checkboxes in multiselection mode - if ($this->multi_selection && !$this->delete_note) - { - $tpl->setCurrentBlock("checkbox_col"); - $tpl->setVariable("CHK_NOTE", "note[]"); - $tpl->setVariable("CHK_NOTE_ID", $note->getId()); - $tpl->parseCurrentBlock(); - $cnt_col = 1; - } - - // edit note stuff for all private notes - if ($this->checkEdit($note)) - { - - if (!$this->delete_note && !$this->export_html && !$this->print - && !$this->edit_note_form && !$this->add_note_form && !$this->no_actions) - { - $ilCtrl->setParameterByClass("ilnotegui", "note_id", $note->getId()); - $this->renderLink($tpl, "edit_note", $lng->txt("edit"), - "editNoteForm", "note_edit"); - } - } - - $tpl->setVariable("CNT_COL", $cnt_col); - - // output author account - if ($a_type == IL_NOTE_PUBLIC && ilObject::_exists($note->getAuthor())) - { - //$tpl->setCurrentBlock("author"); - //$tpl->setVariable("VAL_AUTHOR", ilObjUser::_lookupLogin($note->getAuthor())); - //$tpl->parseCurrentBlock(); - $tpl->setCurrentBlock("user_img"); - $tpl->setVariable("USR_IMG", - ilObjUser::_getPersonalPicturePath($note->getAuthor(), "xxsmall")); - $tpl->setVariable("USR_ALT", $lng->txt("user_image").": ". - ilObjUser::_lookupLogin($note->getAuthor())); - $tpl->parseCurrentBlock(); - $tpl->setVariable("TXT_USR", - ilUserUtil::getNamePresentation($note->getAuthor(), false, false)." - "); - } - - // last edited - if ($note->getUpdateDate() != null) - { - $tpl->setVariable("TXT_LAST_EDIT", $lng->txt("last_edited_on")); - $tpl->setVariable("DATE_LAST_EDIT", - ilDatePresentation::formatDate(new ilDate($note->getUpdateDate(), IL_CAL_DATETIME))); - } - else - { - $tpl->setVariable("VAL_DATE", - ilDatePresentation::formatDate(new ilDate($note->getCreationDate(), IL_CAL_DATETIME))); - } - - // hidden note ids for deletion - if ($this->delete_note) - { - $tpl->setCurrentBlock("delete_ids"); - $tpl->setVariable("HID_NOTE", "note[]"); - $tpl->setVariable("HID_NOTE_ID", $note->getId()); - $tpl->parseCurrentBlock(); - } - $target = $note->getObject(); - - - $tpl->setCurrentBlock("note"); - $text = (trim($note->getText()) != "") - ? nl2br($note->getText()) - : "

                  ".$lng->txt("note_content_removed")."

                  "; - $tpl->setVariable("NOTE_TEXT", $text); - $tpl->setVariable("VAL_SUBJECT", $note->getSubject()); - $tpl->setVariable("NOTE_ID", $note->getId()); - - // target objects - $tpl->setVariable("TARGET_OBJECTS", - $this->renderTargets($note)); - - $tpl->parseCurrentBlock(); - } - $tpl->setCurrentBlock("note_row"); - $tpl->parseCurrentBlock(); - $notes_given = true; - } - - if (!$notes_given) - { - $tpl->setCurrentBlock("no_notes"); - if ($a_type == IL_NOTE_PUBLIC && !$this->only_latest) - { - $tpl->setVariable("NO_NOTES", $lng->txt("notes_no_comments")); - } - $tpl->parseCurrentBlock(); - } - - ilDatePresentation::setUseRelativeDates($reldates); - - // multiple items commands - if ($this->multi_selection && !$this->delete_note && !$this->edit_note_form - && count($notes) > 0) - { - if ($a_type == IL_NOTE_PRIVATE) - { - $tpl->setCurrentBlock("delete_cmd"); - $tpl->setVariable("TXT_DELETE_NOTES", $this->lng->txt("delete")); - $tpl->parseCurrentBlock(); - } - - $tpl->setCurrentBlock("multiple_commands"); - $tpl->setVariable("TXT_SELECT_ALL", $this->lng->txt("select_all")); - $tpl->setVariable("IMG_ARROW", ilUtil::getImagePath("arrow_downright.svg")); - $tpl->setVariable("ALT_ARROW", $this->lng->txt("actions")); - $tpl->setVariable("TXT_PRINT_NOTES", $this->lng->txt("print")); - $tpl->setVariable("TXT_EXPORT_NOTES", $this->lng->txt("exp_html")); - $tpl->parseCurrentBlock(); - } - - // delete / cancel row - if ($this->delete_note) - { - $tpl->setCurrentBlock("delete_cancel"); - $tpl->setVariable("TXT_DEL_NOTES", $this->lng->txt("delete")); - $tpl->setVariable("TXT_CANCEL_DEL_NOTES", $this->lng->txt("cancel")); - $tpl->parseCurrentBlock(); - } - - // print - if ($this->print) - { - $tpl->touchBlock("print_js"); - $tpl->setCurrentBlock("print_back"); - $tpl->setVariable("LINK_BACK", $this->ctrl->getLinkTarget($this, "showNotes")); - $tpl->setVariable("TXT_BACK", $this->lng->txt("back")); - $tpl->parseCurrentBlock(); - } - } - - // message - switch($_GET["note_mess"] != "" ? $_GET["note_mess"] : $this->note_mess) - { - case "mod": - $mtype = "success"; - $mtxt = $lng->txt("msg_obj_modified"); - break; - - case "ntsdel": - $mtype = "success"; - $mtxt = ($a_type == IL_NOTE_PRIVATE) - ? $lng->txt("notes_notes_deleted") - : $lng->txt("notes_comments_deleted"); - break; - - case "ntdel": - $mtype = "success"; - $mtxt = ($a_type == IL_NOTE_PRIVATE) - ? $lng->txt("notes_note_deleted") - : $lng->txt("notes_comment_deleted"); - break; - - case "frmfld": - $mtype = "failure"; - $mtxt = $lng->txt("form_input_not_valid"); - break; - - case "qdel": - $mtype = "question"; - $mtxt = $lng->txt("info_delete_sure"); - break; - - case "noc": - $mtype = "failure"; - $mtxt = $lng->txt("no_checkbox"); - break; - } - if ($mtxt != "") - { - $tpl->setVariable("MESS", $tpl->getMessageHTML($mtxt, $mtype)); - } - else - { - $tpl->setVariable("MESS", ""); - } - - if ($this->widget_header != "") - { - $tpl->setVariable("WIDGET_HEADER", $this->widget_header); - } - - - if ($this->delete_note && count($notes) == 0) - { - return ""; - } - else - { - return $tpl->get(); - } - } - - /** - * Get sub object title if available with callback - * - * @param int $parent_obj_id - * @param int $sub_obj_id - * @return string - */ - protected function getSubObjectTitle($parent_obj_id, $sub_obj_id) - { - $objDefinition = $this->obj_definition; - $ilCtrl = $this->ctrl; - - $parent_type = ilObject::_lookupType($parent_obj_id); - $parent_class = "ilObj".$objDefinition->getClassName($parent_type)."GUI"; - $parent_path = $ilCtrl->lookupClassPath($parent_class); - include_once $parent_path; - if(method_exists($parent_class, "lookupSubObjectTitle")) - { - return call_user_func_array(array($parent_class, "lookupSubObjectTitle"), array($parent_obj_id, $sub_obj_id)); - } - } - - /** - * Check whether deletion is allowed - */ - function checkDeletion($a_note) - { - $ilUser = $this->user; - $ilSetting = $this->settings; - - if ($ilUser->getId() == ANONYMOUS_USER_ID) - { - return false; - } - - $is_author = ($a_note->getAuthor() == $ilUser->getId()); - - if ($a_note->getType() == IL_NOTE_PRIVATE && $is_author) - { - return true; - } - - if ($a_note->getType() == IL_NOTE_PUBLIC && $this->public_deletion_enabled) - { - return true; - } - - if ($a_note->getType() == IL_NOTE_PUBLIC && $is_author && $ilSetting->get("comments_del_user", 0)) - { - return true; - } - - return false; - } - - /** - * Check edit - */ - function checkEdit($a_note) - { - $ilUser = $this->user; - - if ($a_note->getAuthor() == $ilUser->getId() - && ($ilUser->getId() != ANONYMOUS_USER_ID)) - { - return true; - } - return false; - } - - - /** - * Init note form. - * - * @param int $a_mode Edit Mode - */ - public function initNoteForm($a_mode = "edit", $a_type, $a_note = null) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->form_tpl = new ilTemplate("tpl.notes_edit.html", true, true, "Services/Notes"); - if ($a_note) - { - $this->form_tpl->setVariable("VAL_NOTE", ilUtil::prepareFormOutput($a_note->getText())); - $this->form_tpl->setVariable("NOTE_ID", $a_note->getId()); - } - - if ($a_mode == "create") - { - $this->form_tpl->setVariable("TXT_CMD", ($a_type == IL_NOTE_PUBLIC) - ? $lng->txt("note_add_comment") - : $lng->txt("note_add_note")); - $this->form_tpl->setVariable("CMD", "addNote"); - } - else - { - $this->form_tpl->setVariable("TXT_CMD", ($a_type == IL_NOTE_PUBLIC) - ? $lng->txt("note_update_comment") - : $lng->txt("note_update_note")); - $this->form_tpl->setVariable("CMD", "updateNote"); - } - -return; - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - $this->form->setOpenTag(false); - $this->form->setCloseTag(false); - $this->form->setDisableStandardMessage(true); - - // subject -/* $ti = new ilTextInputGUI($this->lng->txt("subject"), "sub_note"); - $ti->setRequired(true); - $ti->setMaxLength(200); - $ti->setSize(40); - if ($a_note) - { - $ti->setValue($a_note->getSubject()); - } - $this->form->addItem($ti);*/ - - // text -// $ta = new ilTextAreaInputGUI(($a_type == IL_NOTE_PUBLIC) -// ? $lng->txt("notes_comment") -// : $lng->txt("note"), "note"); - $ta = new ilTextAreaInputGUI("", "note"); - $ta->setCols(40); - $ta->setRows(4); - if ($a_note) - { - $ta->setValue($a_note->getText()); - } - $this->form->addItem($ta); - - // label -/* $options = array( - IL_NOTE_UNLABELED => $lng->txt("unlabeled"), - IL_NOTE_QUESTION => $lng->txt("question"), - IL_NOTE_IMPORTANT => $lng->txt("important"), - IL_NOTE_PRO => $lng->txt("pro"), - IL_NOTE_CONTRA => $lng->txt("contra"), - ); - $si = new ilSelectInputGUI($this->lng->txt("notes_label"), "note_label"); - $si->setOptions($options); - if ($a_note) - { - $si->setValue($a_note->getLabel()); - } - $this->form->addItem($si); */ - - // hidden note id - if ($a_note) - { - $hi = new ilHiddenInputGUI("note_id"); - $hi->setValue($_GET["note_id"]); - $this->form->addItem($hi); - } - - // save and cancel commands - if ($a_mode == "create") - { - $this->form->addCommandButton("addNote", $lng->txt("save")); -/* $this->form->addCommandButton("cancelAddNote", $lng->txt("cancel")); - $this->form->setTitle($a_type == IL_NOTE_PUBLIC - ? $lng->txt("notes_add_comment") - : $lng->txt("notes_add_note"));*/ - } - else - { - $this->form->addCommandButton("updateNote", $lng->txt("save")); -/* $this->form->addCommandButton("cancelUpdateNote", $lng->txt("cancel")); - $this->form->setTitle($a_type == IL_NOTE_PUBLIC - ? $lng->txt("notes_edit_comment") - : $lng->txt("notes_edit_note"));*/ - } - - $ilCtrl->setParameter($this, "note_type", $a_type); - $this->form->setFormAction($this->ctrl->getFormAction($this)); - - } - - /** - * Note display for personal desktop - */ - function getPDNoteHTML($note_id) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - $tpl = new ilTemplate("tpl.pd_note.html", true, true, "Services/Notes"); - $note = new ilNote($note_id); - $target = $note->getObject(); - - if ($note->getAuthor() != $ilUser->getId()) - { - return; - } - - $tpl->setCurrentBlock("edit_note"); - $ilCtrl->setParameterByClass("ilnotegui", "rel_obj", $target["rep_obj_id"]); - $ilCtrl->setParameterByClass("ilnotegui", "note_id", $note_id); - $ilCtrl->setParameterByClass("ilnotegui", "note_type", $note->getType()); - $tpl->setVariable("LINK_EDIT_NOTE", - $ilCtrl->getLinkTargetByClass(array("ilpersonaldesktopgui", "ilpdnotesgui", "ilnotegui"), - "editNoteForm")); - $tpl->setVariable("TXT_EDIT_NOTE", $lng->txt("edit")); - $tpl->parseCurrentBlock(); - $ilCtrl->clearParametersByClass("ilnotegui"); - - // last edited - if ($note->getUpdateDate() != null) - { - $tpl->setVariable("TXT_LAST_EDIT", $lng->txt("last_edited_on")); - $tpl->setVariable("DATE_LAST_EDIT", - ilDatePresentation::formatDate(new ilDate($note->getUpdateDate(), IL_CAL_DATETIME))); - } - else - { - //$tpl->setVariable("TXT_CREATED", $lng->txt("create_date")); - $tpl->setVariable("VAL_DATE", - ilDatePresentation::formatDate(new ilDate($note->getCreationDate(), IL_CAL_DATETIME))); - } - - $tpl->setVariable("VAL_SUBJECT", $note->getSubject()); - $text = (trim($note->getText()) != "") - ? nl2br($note->getText()) - : "

                  ".$lng->txt("note_content_removed")."

                  "; - $tpl->setVariable("NOTE_TEXT", $text); - $tpl->setVariable("TARGET_OBJECTS", $this->renderTargets($note)); - return $tpl->get(); - } - - /** - * show related objects as links - */ - function renderTargets($a_note) - { - $tree = $this->tree; - $ilAccess = $this->access; - $objDefinition = $this->obj_definition; - $ilUser = $this->user; - - if (!$this->targets_enabled) - { - return ""; - } - - $a_note_id = $a_note->getId(); - $target = $a_note->getObject(); - $a_obj_type = $target["obj_type"]; - $a_obj_id = $target["obj_id"]; - - $target_tpl = new ilTemplate("tpl.note_target_object.html", true, true, "Services/Notes"); - - if ($target["rep_obj_id"] > 0) - { - // get all visible references of target object - - // repository - $ref_ids = ilObject::_getAllReferences($target["rep_obj_id"]); - if($ref_ids) - { - $vis_ref_ids = array(); - foreach($ref_ids as $ref_id) - { - if ($ilAccess->checkAccess("visible", "", $ref_id)) - { - $vis_ref_ids[] = $ref_id; - } - } - - // output links to targets - if (count($vis_ref_ids) > 0) - { - foreach($vis_ref_ids as $vis_ref_id) - { - $type = ilObject::_lookupType($vis_ref_id, true); - $title = ilObject::_lookupTitle($target["rep_obj_id"]); - - $sub_link = $sub_title = ""; - if ($type == "sahs") // bad hack, needs general procedure - { - $link = "goto.php?target=sahs_".$vis_ref_id; - if ($a_obj_type == "sco" || $a_obj_type == "seqc" || $a_obj_type == "chap" || $a_obj_type == "pg") - { - $sub_link = "goto.php?target=sahs_".$vis_ref_id."_".$a_obj_id; - include_once("./Modules/Scorm2004/classes/class.ilSCORM2004Node.php"); - $sub_title = ilSCORM2004Node::_lookupTitle($a_obj_id); - } - } - else if ($type == "poll") - { - include_once "Services/Link/classes/class.ilLink.php"; - $link = ilLink::_getLink($vis_ref_id, "poll"); - } - else if ($a_obj_type != "pg") - { - if (!is_object($this->item_list_gui[$type])) - { - $class = $objDefinition->getClassName($type); - $location = $objDefinition->getLocation($type); - $full_class = "ilObj".$class."ListGUI"; - include_once($location."/class.".$full_class.".php"); - $this->item_list_gui[$type] = new $full_class(); - } - - // for references, get original title - // (link will lead to orignal, which basically is wrong though) - if($a_obj_type == "crsr" || $a_obj_type == "catr" || $a_obj_type == "grpr") - { - include_once "Services/ContainerReference/classes/class.ilContainerReference.php"; - $tgt_obj_id = ilContainerReference::_lookupTargetId($target["rep_obj_id"]); - $title = ilObject::_lookupTitle($tgt_obj_id); - } - $this->item_list_gui[$type]->initItem($vis_ref_id, $target["rep_obj_id"], $title); - $link = $this->item_list_gui[$type]->getCommandLink("infoScreen"); - - // workaround, because # anchor can't be passed through frameset - $link = ilUtil::appendUrlParameterString($link, "anchor=note_".$a_note_id); - - $link = $this->item_list_gui[$type]->appendRepositoryFrameParameter($link)."#note_".$a_note_id; - } - else - { - $title = ilObject::_lookupTitle($target["rep_obj_id"]); - $link = "goto.php?target=pg_".$a_obj_id."_".$vis_ref_id; - } - - $par_id = $tree->getParentId($vis_ref_id); - - // sub object link - if ($sub_link != "") - { - if ($this->export_html || $this->print) - { - $target_tpl->setCurrentBlock("exp_target_sub_object"); - } - else - { - $target_tpl->setCurrentBlock("target_sub_object"); - $target_tpl->setVariable("LINK_SUB_TARGET", $sub_link); - } - $target_tpl->setVariable("TXT_SUB_TARGET", $sub_title); - $target_tpl->parseCurrentBlock(); - } - - // container and object link - if ($this->export_html || $this->print) - { - $target_tpl->setCurrentBlock("exp_target_object"); - } - else - { - $target_tpl->setCurrentBlock("target_object"); - $target_tpl->setVariable("LINK_TARGET", $link); - } - $target_tpl->setVariable("TXT_CONTAINER", - ilObject::_lookupTitle( - ilObject::_lookupObjId($par_id))); - $target_tpl->setVariable("TXT_TARGET", $title); - - $target_tpl->parseCurrentBlock(); - } - $target_tpl->touchBlock("target_objects"); - } - } - // personal workspace - else - { - // we only need 1 instance - if(!$this->wsp_tree) - { - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; - $this->wsp_tree = new ilWorkspaceTree($ilUser->getId()); - $this->wsp_access_handler = new ilWorkspaceAccessHandler($this->wsp_tree); - } - $node_id = $this->wsp_tree->lookupNodeId($target["rep_obj_id"]); - if($this->wsp_access_handler->checkAccess("visible", "", $node_id)) - { - $path = $this->wsp_tree->getPathFull($node_id); - if($path) - { - $item = array_pop($path); - $parent = array_pop($path); - - if(!$parent["title"]) - { - $parent["title"] = $this->lng->txt("wsp_personal_workspace"); - } - - // sub-objects - $additional = null; - if($a_obj_id) - { - $sub_title = $this->getSubObjectTitle($target["rep_obj_id"], $a_obj_id); - if($sub_title) - { - $item["title"] .= " (".$sub_title.")"; - $additional = "_".$a_obj_id; - } - } - - $link = ilWorkspaceAccessHandler::getGotoLink($node_id, $target["rep_obj_id"], $additional); - } - // shared resource - else - { - $owner = ilObject::_lookupOwner($target["rep_obj_id"]); - $parent["title"] = $this->lng->txt("wsp_tab_shared"). - " (".ilObject::_lookupOwnerName($owner).")"; - $item["title"] = ilObject::_lookupTitle($target["rep_obj_id"]); - $link = "ilias.php?baseClass=ilPersonalDesktopGUI&cmd=jumpToWorkspace&dsh=". - $owner; - } - - // container and object link - if ($this->export_html || $this->print) - { - $target_tpl->setCurrentBlock("exp_target_object"); - } - else - { - $target_tpl->setCurrentBlock("target_object"); - $target_tpl->setVariable("LINK_TARGET", $link); - } - - - // :TODO: no images in template ? - - $target_tpl->setVariable("TXT_CONTAINER", $parent["title"]); - - $target_tpl->setVariable("TXT_TARGET", $item["title"]); - - $target_tpl->parseCurrentBlock(); - } - } - } - return $target_tpl->get(); - } - - /** - * get notes list including add note area - */ - function addNoteForm($a_init_form = true) - { - $ilUser = $this->user; - - $suffix = ($_GET["note_type"] == IL_NOTE_PRIVATE) - ? "private" - : "public"; - $ilUser->setPref("notes_".$suffix, "y"); - - $this->add_note_form = true; - return $this->getNotesHTML($a_init_form); - } - - /** - * cancel add note - */ - function cancelAddNote() - { - return $this->getNotesHTML(); - } - - /** - * cancel edit note - */ - function cancelUpdateNote() - { - return $this->getNotesHTML(); - } - - /** - * add note - */ - function addNote() - { - $ilUser = $this->user; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - //ilLoggerFactory::getLogger("root")->notice("addNote"); - $this->initNoteForm("create", $_GET["note_type"]); - - //if ($this->form->checkInput()) - if ($_POST["note"] != "") - { - $note = new ilNote(); - $note->setObject($this->obj_type, $this->rep_obj_id, $this->obj_id, $this->news_id); - $note->setInRepository($this->repository_mode); - $note->setType($_GET["note_type"]); - $note->setAuthor($ilUser->getId()); - $note->setText(ilUtil::stripslashes($_POST["note"])); -// $note->setSubject($_POST["sub_note"]); -// $note->setLabel($_POST["note_label"]); - $note->create(); - - $this->notifyObserver("new", $note); - - $ilCtrl->setParameter($this, "note_mess", "mod"); -// $ilCtrl->redirect($this, "showNotes", "notes_top", $this->ajax); - } - $ilCtrl->redirect($this, "showNotes", "notes_top", $this->ajax); -// $this->note_mess = "frmfld"; + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var ilObjectDefinition + */ + protected $obj_definition; + + /** + * @var ilTree + */ + protected $tree; + + /** + * @var ilAccessHandler + */ + protected $access; + + public $public_deletion_enabled = false; + public $repository_mode = false; + public $old = false; + + protected $default_command = "getNotesHTML"; + + /** @var array */ + protected $observer = []; + + /** + * @var \ILIAS\DI\UIServices + */ + protected $ui; + + /** + * @var int + */ + protected $news_id = 0; + + /** + * hide new note/comment form + * @var bool + */ + protected $hide_new_form = false; + + /** + * Show only latest note/comment + * @var bool + */ + protected $only_latest = false; + + /** + * @var string + */ + protected $widget_header = ""; + + /** + * Do not show edit/delete actions + * @var bool + */ + protected $no_actions = false; + + /** + * constructor, specifies notes set + * + * @param $a_rep_obj_id int object id of repository object (0 for personal desktop) + * @param $a_obj_id int subobject id (0 for repository items, user id for personal desktop) + * @param $a_obj_type string "pd" for personal desktop + * @param $a_include_subobjects string include all subobjects of rep object (e.g. pages) + */ + public function __construct( + $a_rep_obj_id = "", + $a_obj_id = "", + $a_obj_type = "", + $a_include_subobjects = false, + $a_news_id = 0 + ) { + global $DIC; + + $this->user = $DIC->user(); + $this->settings = $DIC->settings(); + $this->obj_definition = $DIC["objDefinition"]; + $this->tree = $DIC->repositoryTree(); + $this->access = $DIC->access(); + $this->ui = $DIC->ui(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $lng->loadLanguageModule("notes"); + + $ilCtrl->saveParameter($this, "notes_only"); + $this->only = $_GET["notes_only"]; + + $this->rep_obj_id = $a_rep_obj_id; + $this->obj_id = $a_obj_id; + $this->obj_type = $a_obj_type; + $this->inc_sub = $a_include_subobjects; + $this->news_id = $a_news_id; + + // auto-detect object type + if (!$this->obj_type && $a_rep_obj_id) { + $this->obj_type = ilObject::_lookupType($a_rep_obj_id); + } + + $this->ajax = $ilCtrl->isAsynch(); + + $this->ctrl = $ilCtrl; + $this->lng = $lng; + + $this->anchor_jump = true; + $this->add_note_form = false; + $this->edit_note_form = false; + $this->private_enabled = false; + + if (ilNote::commentsActivated($this->rep_obj_id, $this->obj_id, $this->obj_type, $this->news_id)) { + $this->public_enabled = true; + } else { + $this->public_enabled = false; + } + $this->enable_hiding = false; + $this->targets_enabled = false; + $this->multi_selection = false; + $this->export_html = false; + $this->print = false; + $this->comments_settings = false; + + $this->note_img = array( + IL_NOTE_UNLABELED => array( + "img" => ilUtil::getImagePath("note_unlabeled.svg"), + "alt" => $lng->txt("note")), + IL_NOTE_IMPORTANT => array( + "img" => ilUtil::getImagePath("note_unlabeled.svg"), + "alt" => $lng->txt("note") . ", " . $lng->txt("important")), + IL_NOTE_QUESTION => array( + "img" => ilUtil::getImagePath("note_unlabeled.svg"), + "alt" => $lng->txt("note") . ", " . $lng->txt("question")), + IL_NOTE_PRO => array( + "img" => ilUtil::getImagePath("note_unlabeled.svg"), + "alt" => $lng->txt("note") . ", " . $lng->txt("pro")), + IL_NOTE_CONTRA => array( + "img" => ilUtil::getImagePath("note_unlabeled.svg"), + "alt" => $lng->txt("note") . ", " . $lng->txt("contra")) + ); + + $this->comment_img = array( + IL_NOTE_UNLABELED => array( + "img" => ilUtil::getImagePath("comment_unlabeled.svg"), + "alt" => $lng->txt("notes_comment")), + IL_NOTE_IMPORTANT => array( + "img" => ilUtil::getImagePath("comment_unlabeled.svg"), + "alt" => $lng->txt("notes_comment") . ", " . $lng->txt("important")), + IL_NOTE_QUESTION => array( + "img" => ilUtil::getImagePath("comment_unlabeled.svg"), + "alt" => $lng->txt("notes_comment") . ", " . $lng->txt("question")), + IL_NOTE_PRO => array( + "img" => ilUtil::getImagePath("comment_unlabeled.svg"), + "alt" => $lng->txt("notes_comment") . ", " . $lng->txt("pro")), + IL_NOTE_CONTRA => array( + "img" => ilUtil::getImagePath("comment_unlabeled.svg"), + "alt" => $lng->txt("notes_comment") . ", " . $lng->txt("contra")) + ); + + // default: notes for repository objects + $this->setRepositoryMode(true); + } + + /** + * Set default command + * + * @param string $a_val default command + */ + public function setDefaultCommand($a_val) + { + $this->default_command = $a_val; + } + + /** + * Get default command + * + * @return string default command + */ + public function getDefaultCommand() + { + return $this->default_command; + } + + /** + * execute command + */ + public function executeCommand() + { + $cmd = $this->ctrl->getCmd($this->getDefaultCommand()); + $next_class = $this->ctrl->getNextClass($this); + + switch ($next_class) { + default: + return $this->$cmd(); + break; + } + } + + /** + * enable private notes + */ + public function enablePrivateNotes($a_enable = true) + { + $this->private_enabled = $a_enable; + } + + /** + * enable public notes + */ + public function enablePublicNotes($a_enable = true) + { + $this->public_enabled = $a_enable; + } + + /** + * enable private notes + */ + public function enableCommentsSettings($a_enable = true) + { + $this->comments_settings = $a_enable; + } + + /** + * enable public notes + */ + public function enablePublicNotesDeletion($a_enable = true) + { + $this->public_deletion_enabled = $a_enable; + } + + /** + * enable hiding + */ + public function enableHiding($a_enable = true) + { + $this->enable_hiding = $a_enable; + } + + /** + * enable target objects + */ + public function enableTargets($a_enable = true) + { + $this->targets_enabled = $a_enable; + } + + /** + * enable multi selection (checkboxes and commands) + */ + public function enableMultiSelection($a_enable = true) + { + $this->multi_selection = $a_enable; + } + + /** + * enable anchor for form jump + */ + public function enableAnchorJump($a_enable = true) + { + $this->anchor_jump = $a_enable; + } + + /** + * Set repository mode + * + * @param bool $a_value + */ + public function setRepositoryMode($a_value) + { + $this->repository_mode = (bool) $a_value; + } + + + /** + * Get only notes html + * + * @param + * @return + */ + public function getOnlyNotesHTML() + { + $ilCtrl = $this->ctrl; + $ilCtrl->setParameter($this, "notes_only", "notes"); + $this->only = "notes"; + return $this->getNotesHTML($a_init_form = true); + } + + /** + * Get only comments html + * + * @param + * @return + */ + public function getOnlyCommentsHTML() + { + $ilCtrl = $this->ctrl; + $ilCtrl->setParameter($this, "notes_only", "comments"); + $this->only = "comments"; + return $this->getNotesHTML($a_init_form = true); + } + + + /*** + * get note lists html code + */ + public function getNotesHTML($a_init_form = true) + { + $ilUser = $this->user; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilSetting = $this->settings; + + $lng->loadLanguageModule("notes"); + + $ntpl = new ilTemplate( + "tpl.notes_and_comments.html", + true, + true, + "Services/Notes" + ); + + // check, whether column is hidden due to processing in other column + $hide_comments = ($this->only == "notes"); + $hide_notes = ($this->only == "comments"); + switch ($ilCtrl->getCmd()) { + case "addNoteForm": + case "editNoteForm": + case "addNote": + case "updateNote": + if ($_GET["note_type"] == IL_NOTE_PRIVATE) { + $hide_comments = true; + } + if ($_GET["note_type"] == IL_NOTE_PUBLIC) { + $hide_notes = true; + } + break; + } + + + // temp workaround: only show comments (if both have been activated) + if ($this->private_enabled && $this->public_enabled + && $this->only != "notes") { + $this->private_enabled = false; + } + + $nodes_col = false; + if ($this->private_enabled && ($ilUser->getId() != ANONYMOUS_USER_ID) + && !$hide_notes) { + $ntpl->setCurrentBlock("notes_col"); + $ntpl->setVariable("NOTES", $this->getNoteListHTML(IL_NOTE_PRIVATE, $a_init_form)); + $ntpl->parseCurrentBlock(); + $nodes_col = true; + } + + // #15948 - public enabled vs. comments_settings + $comments_col = false; + if ($this->public_enabled && (!$this->delete_note || $this->public_deletion_enabled || $ilSetting->get("comments_del_user", 0)) + && !$hide_comments /* && $ilUser->getId() != ANONYMOUS_USER_ID */) { + $ntpl->setVariable("COMMENTS", $this->getNoteListHTML(IL_NOTE_PUBLIC, $a_init_form)); + $comments_col = true; + } + + // Comments Settings + if ($this->comments_settings && !$hide_comments && !$this->delete_note + && !$this->edit_note_form && !$this->add_note_form && $ilUser->getId() != ANONYMOUS_USER_ID) { + //$active = $notes_settings->get("activate_".$id); + $active = ilNote::commentsActivated($this->rep_obj_id, $this->obj_id, $this->obj_type); + + if ($active) { + if ($this->news_id == 0) { + $this->renderLink( + $ntpl, + "comments_settings", + $lng->txt("notes_deactivate_comments"), + "deactivateComments", + "notes_top" + ); + } + $ntpl->setCurrentBlock("comments_settings2"); + } else { + $this->renderLink( + $ntpl, + "comments_settings", + $lng->txt("notes_activate_comments"), + "activateComments", + "notes_top" + ); + $ntpl->setCurrentBlock("comments_settings2"); + + if ($this->ajax && !$comments_col) { + $ntpl->setVariable( + "COMMENTS_MESS", + $ntpl->getMessageHTML($lng->txt("comments_feature_currently_not_activated_for_object"), "info") + ); + } + } + $ntpl->parseCurrentBlock(); + + if (!$comments_col) { + $ntpl->setVariable("COMMENTS", ""); + } + + $comments_col = true; + } + + if ($comments_col) { + $ntpl->setCurrentBlock("comments_col"); + if ($nodes_col) { + // $ntpl->touchBlock("comments_style"); + } + $ntpl->parseCurrentBlock(); + } + + if ($this->ajax) { + echo $ntpl->get(); + exit; + } + + return $ntpl->get(); + } + + /** + * Activate Comments + */ + public function activateComments() + { + $ilCtrl = $this->ctrl; + + if ($this->comments_settings) { + ilNote::activateComments($this->rep_obj_id, $this->obj_id, $this->obj_type, true); + } + + $ilCtrl->redirectByClass("ilnotegui", "showNotes", "", $this->ajax); + } + + /** + * Deactivate Comments + */ + public function deactivateComments() + { + $ilCtrl = $this->ctrl; + + if ($this->comments_settings) { + ilNote::activateComments($this->rep_obj_id, $this->obj_id, $this->obj_type, false); + } + + $ilCtrl->redirectByClass("ilnotegui", "showNotes", "", $this->ajax); + } + + /** + * get notes/comments list as html code + */ + public function getNoteListHTML($a_type = IL_NOTE_PRIVATE, $a_init_form = true) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + include_once("./Services/User/classes/class.ilUserUtil.php"); + + $suffix = ($a_type == IL_NOTE_PRIVATE) + ? "private" + : "public"; + + $user_setting_notes_public_all = "y"; + $user_setting_notes_by_type = "y"; + + if ($this->delete_note || $this->export_html || $this->print) { + if ($_GET["note_id"] != "") { + $filter = $_GET["note_id"]; + } else { + $filter = $_POST["note"]; + } + } + + $order = (bool) $_SESSION["comments_sort_asc"]; + if ($this->only_latest) { + $order = false; + } + + + $notes = ilNote::_getNotesOfObject( + $this->rep_obj_id, + $this->obj_id, + $this->obj_type, + $a_type, + $this->inc_sub, + $filter, + $user_setting_notes_public_all, + $this->repository_mode, + $order, + $this->news_id + ); + + $tpl = new ilTemplate("tpl.notes_list.html", true, true, "Services/Notes"); + + if ($this->ajax) { + include_once("./Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php"); + $tpl->setCurrentBlock("close_img"); + $tpl->setVariable("CLOSE_IMG", ilGlyphGUI::get(ilGlyphGUI::CLOSE)); + $tpl->parseCurrentBlock(); + } + + // show counter if notes are hidden + $cnt_str = (count($notes) > 0) + ? " (" . count($notes) . ")" + : ""; + + // title + if ($this->ajax && !$this->only_latest) { + switch ($this->obj_type) { + case "grpr": + case "catr": + case "crsr": + include_once "Services/ContainerReference/classes/class.ilContainerReference.php"; + $title = ilContainerReference::_lookupTitle($this->rep_obj_id); + break; + + default: + $title = ilObject::_lookupTitle($this->rep_obj_id); + break; + } + + $img = ilUtil::img(ilObject::_getIcon($this->rep_obj_id, "tiny")); + + // add sub-object if given + if ($this->obj_id) { + $sub_title = $this->getSubObjectTitle($this->rep_obj_id, $this->obj_id); + if ($sub_title) { + $title .= " - " . $sub_title; + } + } + + $tpl->setCurrentBlock("title"); + $tpl->setVariable("TITLE", $img . " " . $title); + $tpl->parseCurrentBlock(); + } + + if ($this->delete_note) { + $cnt_str = ""; + } + if ($a_type == IL_NOTE_PRIVATE) { + $tpl->setVariable("TXT_NOTES", $lng->txt("private_notes") . $cnt_str); + $ilCtrl->setParameterByClass("ilnotegui", "note_type", IL_NOTE_PRIVATE); + } else { + $tpl->setVariable("TXT_NOTES", $lng->txt("notes_public_comments") . $cnt_str); + $ilCtrl->setParameterByClass("ilnotegui", "note_type", IL_NOTE_PUBLIC); + } + $anch = $this->anchor_jump + ? "notes_top" + : ""; + if (!$this->only_latest) { + $tpl->setVariable("FORMACTION", $ilCtrl->getFormAction($this, "getNotesHTML", $anch)); + if ($this->ajax) { + $os = "onsubmit = \"ilNotes.cmdAjaxForm(event, '" . + $ilCtrl->getFormActionByClass("ilnotegui", "", "", true) . + "'); return false;\""; + $tpl->setVariable("ON_SUBMIT_FORM", $os); + $tpl->setVariable("FORM_ID", "Ajax"); + } + } + + + if ($this->export_html || $this->print) { + $tpl->touchBlock("print_style"); + } + + // show add new note button + if (!$this->add_note_form && !$this->edit_note_form && !$this->delete_note && + !$this->export_html && !$this->print && $ilUser->getId() != ANONYMOUS_USER_ID && !$this->hide_new_form) { + if (!$this->inc_sub) { // we cannot offer add button if aggregated notes + // are displayed + if ($this->rep_obj_id > 0 || $a_type != IL_NOTE_PUBLIC) { + $tpl->setCurrentBlock("add_note_btn"); + if ($a_type == IL_NOTE_PUBLIC) { + $tpl->setVariable("TXT_ADD_NOTE", $lng->txt("notes_add_comment")); + } else { + $tpl->setVariable("TXT_ADD_NOTE", $lng->txt("add_note")); + } + $tpl->setVariable("LINK_ADD_NOTE", $ilCtrl->getLinkTargetByClass("ilnotegui", "addNoteForm") . + "#note_edit"); + $tpl->parseCurrentBlock(); + } + } + } + + // show show/hide button for note list + if (count($notes) > 0 && $this->enable_hiding && !$this->delete_note + && !$this->export_html && !$this->print && !$this->edit_note_form + && !$this->add_note_form) { + if ($user_setting_notes_by_type == "n") { + if ($a_type == IL_NOTE_PUBLIC) { + $txt = $lng->txt("notes_show_comments"); + } else { + $txt = $lng->txt("show_" . $suffix . "_notes"); + } + $this->renderLink($tpl, "show_notes", $txt, "showNotes", "notes_top"); + } else { + // never individually hide for anonymous users + if (($ilUser->getId() != ANONYMOUS_USER_ID)) { + if ($a_type == IL_NOTE_PUBLIC) { + $txt = $lng->txt("notes_hide_comments"); + } else { + $txt = $lng->txt("hide_" . $suffix . "_notes"); + } + $this->renderLink($tpl, "hide_notes", $txt, "hideNotes", "notes_top"); + + // show all public notes / my notes only switch + if ($a_type == IL_NOTE_PUBLIC) { + if ($user_setting_notes_public_all == "n") { + $this->renderLink( + $tpl, + "all_pub_notes", + $lng->txt("notes_all_comments"), + "showAllPublicNotes", + "notes_top" + ); + } else { + $this->renderLink( + $tpl, + "my_pub_notes", + $lng->txt("notes_my_comments"), + "showMyPublicNotes", + "notes_top" + ); + } + } + } + } + } + + // show add new note text area + if (!$this->edit_note_form && $user_setting_notes_by_type != "n" && + !$this->delete_note && $ilUser->getId() != ANONYMOUS_USER_ID && !$this->hide_new_form) { + if ($a_init_form) { + $this->initNoteForm("create", $a_type); + } + + $tpl->setCurrentBlock("edit_note_form"); + // $tpl->setVariable("EDIT_FORM", $this->form->getHTML()); + $tpl->setVariable("EDIT_FORM", $this->form_tpl->get()); + $tpl->parseCurrentBlock(); + + $tpl->parseCurrentBlock(); + $tpl->setCurrentBlock("note_row"); + $tpl->parseCurrentBlock(); + } + + // list all notes + if ($user_setting_notes_by_type != "n" || !$this->enable_hiding) { + $reldates = ilDatePresentation::useRelativeDates(); + ilDatePresentation::setUseRelativeDates(false); + + if (sizeof($notes) && !$this->only_latest) { + if ((int) $_SESSION["comments_sort_asc"] == 1) { + $sort_txt = $lng->txt("notes_sort_desc"); + $sort_cmd = "listSortDesc"; + } else { + $sort_txt = $lng->txt("notes_sort_asc"); + $sort_cmd = "listSortAsc"; + } + $this->renderLink($tpl, "sort_list", $sort_txt, $sort_cmd, $anch); + } + + $notes_given = false; + foreach ($notes as $note) { + if ($this->only_latest && $notes_given) { + continue; + } + + + if ($this->edit_note_form && ($note->getId() == $_GET["note_id"]) + && $a_type == $_GET["note_type"]) { + if ($a_init_form) { + $this->initNoteForm("edit", $a_type, $note); + } + $tpl->setCurrentBlock("edit_note_form"); + // $tpl->setVariable("EDIT_FORM", $this->form->getHTML()); + $tpl->setVariable("EDIT_FORM", $this->form_tpl->get()); + $tpl->parseCurrentBlock(); + } else { + $cnt_col = 2; + + // delete note stuff for all private notes + if ($this->checkDeletion($note) + && !$this->delete_note + && !$this->export_html && !$this->print + && !$this->edit_note_form && !$this->add_note_form && !$this->no_actions) { + $ilCtrl->setParameterByClass("ilnotegui", "note_id", $note->getId()); + $this->renderLink( + $tpl, + "delete_note", + $lng->txt("delete"), + "deleteNote", + "note_" . $note->getId() + ); + } + + // checkboxes in multiselection mode + if ($this->multi_selection && !$this->delete_note) { + $tpl->setCurrentBlock("checkbox_col"); + $tpl->setVariable("CHK_NOTE", "note[]"); + $tpl->setVariable("CHK_NOTE_ID", $note->getId()); + $tpl->parseCurrentBlock(); + $cnt_col = 1; + } + + // edit note stuff for all private notes + if ($this->checkEdit($note)) { + if (!$this->delete_note && !$this->export_html && !$this->print + && !$this->edit_note_form && !$this->add_note_form && !$this->no_actions) { + $ilCtrl->setParameterByClass("ilnotegui", "note_id", $note->getId()); + $this->renderLink( + $tpl, + "edit_note", + $lng->txt("edit"), + "editNoteForm", + "note_edit" + ); + } + } + + $tpl->setVariable("CNT_COL", $cnt_col); + + // output author account + if ($a_type == IL_NOTE_PUBLIC && ilObject::_exists($note->getAuthor())) { + //$tpl->setCurrentBlock("author"); + //$tpl->setVariable("VAL_AUTHOR", ilObjUser::_lookupLogin($note->getAuthor())); + //$tpl->parseCurrentBlock(); + $tpl->setCurrentBlock("user_img"); + $tpl->setVariable( + "USR_IMG", + ilObjUser::_getPersonalPicturePath($note->getAuthor(), "xxsmall") + ); + $tpl->setVariable("USR_ALT", $lng->txt("user_image") . ": " . + ilObjUser::_lookupLogin($note->getAuthor())); + $tpl->parseCurrentBlock(); + $tpl->setVariable( + "TXT_USR", + ilUserUtil::getNamePresentation($note->getAuthor(), false, false) . " - " + ); + } + + // last edited + if ($note->getUpdateDate() != null) { + $tpl->setVariable("TXT_LAST_EDIT", $lng->txt("last_edited_on")); + $tpl->setVariable( + "DATE_LAST_EDIT", + ilDatePresentation::formatDate(new ilDate($note->getUpdateDate(), IL_CAL_DATETIME)) + ); + } else { + $tpl->setVariable( + "VAL_DATE", + ilDatePresentation::formatDate(new ilDate($note->getCreationDate(), IL_CAL_DATETIME)) + ); + } + + // hidden note ids for deletion + if ($this->delete_note) { + $tpl->setCurrentBlock("delete_ids"); + $tpl->setVariable("HID_NOTE", "note[]"); + $tpl->setVariable("HID_NOTE_ID", $note->getId()); + $tpl->parseCurrentBlock(); + } + $target = $note->getObject(); + + + $tpl->setCurrentBlock("note"); + $text = (trim($note->getText()) != "") + ? nl2br($note->getText()) + : "

                  " . $lng->txt("note_content_removed") . "

                  "; + $tpl->setVariable("NOTE_TEXT", $text); + $tpl->setVariable("VAL_SUBJECT", $note->getSubject()); + $tpl->setVariable("NOTE_ID", $note->getId()); + + // target objects + $tpl->setVariable( + "TARGET_OBJECTS", + $this->renderTargets($note) + ); + + $tpl->parseCurrentBlock(); + } + $tpl->setCurrentBlock("note_row"); + $tpl->parseCurrentBlock(); + $notes_given = true; + } + + if (!$notes_given) { + $tpl->setCurrentBlock("no_notes"); + if ($a_type == IL_NOTE_PUBLIC && !$this->only_latest) { + $tpl->setVariable("NO_NOTES", $lng->txt("notes_no_comments")); + } + $tpl->parseCurrentBlock(); + } + + ilDatePresentation::setUseRelativeDates($reldates); + + // multiple items commands + if ($this->multi_selection && !$this->delete_note && !$this->edit_note_form + && count($notes) > 0) { + if ($a_type == IL_NOTE_PRIVATE) { + $tpl->setCurrentBlock("delete_cmd"); + $tpl->setVariable("TXT_DELETE_NOTES", $this->lng->txt("delete")); + $tpl->parseCurrentBlock(); + } + + $tpl->setCurrentBlock("multiple_commands"); + $tpl->setVariable("TXT_SELECT_ALL", $this->lng->txt("select_all")); + $tpl->setVariable("IMG_ARROW", ilUtil::getImagePath("arrow_downright.svg")); + $tpl->setVariable("ALT_ARROW", $this->lng->txt("actions")); + $tpl->setVariable("TXT_PRINT_NOTES", $this->lng->txt("print")); + $tpl->setVariable("TXT_EXPORT_NOTES", $this->lng->txt("exp_html")); + $tpl->parseCurrentBlock(); + } + + // delete / cancel row + if ($this->delete_note) { + $tpl->setCurrentBlock("delete_cancel"); + $tpl->setVariable("TXT_DEL_NOTES", $this->lng->txt("delete")); + $tpl->setVariable("TXT_CANCEL_DEL_NOTES", $this->lng->txt("cancel")); + $tpl->parseCurrentBlock(); + } + + // print + if ($this->print) { + $tpl->touchBlock("print_js"); + $tpl->setCurrentBlock("print_back"); + $tpl->setVariable("LINK_BACK", $this->ctrl->getLinkTarget($this, "showNotes")); + $tpl->setVariable("TXT_BACK", $this->lng->txt("back")); + $tpl->parseCurrentBlock(); + } + } + + // message + switch ($_GET["note_mess"] != "" ? $_GET["note_mess"] : $this->note_mess) { + case "mod": + $mtype = "success"; + $mtxt = $lng->txt("msg_obj_modified"); + break; + + case "ntsdel": + $mtype = "success"; + $mtxt = ($a_type == IL_NOTE_PRIVATE) + ? $lng->txt("notes_notes_deleted") + : $lng->txt("notes_comments_deleted"); + break; + + case "ntdel": + $mtype = "success"; + $mtxt = ($a_type == IL_NOTE_PRIVATE) + ? $lng->txt("notes_note_deleted") + : $lng->txt("notes_comment_deleted"); + break; + + case "frmfld": + $mtype = "failure"; + $mtxt = $lng->txt("form_input_not_valid"); + break; + + case "qdel": + $mtype = "question"; + $mtxt = $lng->txt("info_delete_sure"); + break; + + case "noc": + $mtype = "failure"; + $mtxt = $lng->txt("no_checkbox"); + break; + } + if ($mtxt != "") { + $tpl->setVariable("MESS", $tpl->getMessageHTML($mtxt, $mtype)); + } else { + $tpl->setVariable("MESS", ""); + } + + if ($this->widget_header != "") { + $tpl->setVariable("WIDGET_HEADER", $this->widget_header); + } + + + if ($this->delete_note && count($notes) == 0) { + return ""; + } else { + return $tpl->get(); + } + } + + /** + * Get sub object title if available with callback + * + * @param int $parent_obj_id + * @param int $sub_obj_id + * @return string + */ + protected function getSubObjectTitle($parent_obj_id, $sub_obj_id) + { + $objDefinition = $this->obj_definition; + $ilCtrl = $this->ctrl; + + $parent_type = ilObject::_lookupType($parent_obj_id); + $parent_class = "ilObj" . $objDefinition->getClassName($parent_type) . "GUI"; + $parent_path = $ilCtrl->lookupClassPath($parent_class); + include_once $parent_path; + if (method_exists($parent_class, "lookupSubObjectTitle")) { + return call_user_func_array(array($parent_class, "lookupSubObjectTitle"), array($parent_obj_id, $sub_obj_id)); + } + } + + /** + * Check whether deletion is allowed + */ + public function checkDeletion($a_note) + { + $ilUser = $this->user; + $ilSetting = $this->settings; + + if ($ilUser->getId() == ANONYMOUS_USER_ID) { + return false; + } + + $is_author = ($a_note->getAuthor() == $ilUser->getId()); + + if ($a_note->getType() == IL_NOTE_PRIVATE && $is_author) { + return true; + } + + if ($a_note->getType() == IL_NOTE_PUBLIC && $this->public_deletion_enabled) { + return true; + } + + if ($a_note->getType() == IL_NOTE_PUBLIC && $is_author && $ilSetting->get("comments_del_user", 0)) { + return true; + } + + return false; + } + + /** + * Check edit + */ + public function checkEdit($a_note) + { + $ilUser = $this->user; + + if ($a_note->getAuthor() == $ilUser->getId() + && ($ilUser->getId() != ANONYMOUS_USER_ID)) { + return true; + } + return false; + } + + + /** + * Init note form. + * + * @param int $a_mode Edit Mode + */ + public function initNoteForm($a_mode = "edit", $a_type, $a_note = null) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $this->form_tpl = new ilTemplate("tpl.notes_edit.html", true, true, "Services/Notes"); + if ($a_note) { + $this->form_tpl->setVariable("VAL_NOTE", ilUtil::prepareFormOutput($a_note->getText())); + $this->form_tpl->setVariable("NOTE_ID", $a_note->getId()); + } + + if ($a_mode == "create") { + $this->form_tpl->setVariable("TXT_CMD", ($a_type == IL_NOTE_PUBLIC) + ? $lng->txt("note_add_comment") + : $lng->txt("note_add_note")); + $this->form_tpl->setVariable("CMD", "addNote"); + } else { + $this->form_tpl->setVariable("TXT_CMD", ($a_type == IL_NOTE_PUBLIC) + ? $lng->txt("note_update_comment") + : $lng->txt("note_update_note")); + $this->form_tpl->setVariable("CMD", "updateNote"); + } + + return; + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + $this->form->setOpenTag(false); + $this->form->setCloseTag(false); + $this->form->setDisableStandardMessage(true); + + // subject + /* $ti = new ilTextInputGUI($this->lng->txt("subject"), "sub_note"); + $ti->setRequired(true); + $ti->setMaxLength(200); + $ti->setSize(40); + if ($a_note) + { + $ti->setValue($a_note->getSubject()); + } + $this->form->addItem($ti);*/ + + // text + // $ta = new ilTextAreaInputGUI(($a_type == IL_NOTE_PUBLIC) + // ? $lng->txt("notes_comment") + // : $lng->txt("note"), "note"); + $ta = new ilTextAreaInputGUI("", "note"); + $ta->setCols(40); + $ta->setRows(4); + if ($a_note) { + $ta->setValue($a_note->getText()); + } + $this->form->addItem($ta); + + // label + /* $options = array( + IL_NOTE_UNLABELED => $lng->txt("unlabeled"), + IL_NOTE_QUESTION => $lng->txt("question"), + IL_NOTE_IMPORTANT => $lng->txt("important"), + IL_NOTE_PRO => $lng->txt("pro"), + IL_NOTE_CONTRA => $lng->txt("contra"), + ); + $si = new ilSelectInputGUI($this->lng->txt("notes_label"), "note_label"); + $si->setOptions($options); + if ($a_note) + { + $si->setValue($a_note->getLabel()); + } + $this->form->addItem($si); */ + + // hidden note id + if ($a_note) { + $hi = new ilHiddenInputGUI("note_id"); + $hi->setValue($_GET["note_id"]); + $this->form->addItem($hi); + } + + // save and cancel commands + if ($a_mode == "create") { + $this->form->addCommandButton("addNote", $lng->txt("save")); + /* $this->form->addCommandButton("cancelAddNote", $lng->txt("cancel")); + $this->form->setTitle($a_type == IL_NOTE_PUBLIC + ? $lng->txt("notes_add_comment") + : $lng->txt("notes_add_note"));*/ + } else { + $this->form->addCommandButton("updateNote", $lng->txt("save")); + /* $this->form->addCommandButton("cancelUpdateNote", $lng->txt("cancel")); + $this->form->setTitle($a_type == IL_NOTE_PUBLIC + ? $lng->txt("notes_edit_comment") + : $lng->txt("notes_edit_note"));*/ + } + + $ilCtrl->setParameter($this, "note_type", $a_type); + $this->form->setFormAction($this->ctrl->getFormAction($this)); + } + + /** + * Note display for personal desktop + */ + public function getPDNoteHTML($note_id) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + $tpl = new ilTemplate("tpl.pd_note.html", true, true, "Services/Notes"); + $note = new ilNote($note_id); + $target = $note->getObject(); + + if ($note->getAuthor() != $ilUser->getId()) { + return; + } + + $tpl->setCurrentBlock("edit_note"); + $ilCtrl->setParameterByClass("ilnotegui", "rel_obj", $target["rep_obj_id"]); + $ilCtrl->setParameterByClass("ilnotegui", "note_id", $note_id); + $ilCtrl->setParameterByClass("ilnotegui", "note_type", $note->getType()); + $tpl->setVariable( + "LINK_EDIT_NOTE", + $ilCtrl->getLinkTargetByClass( + array("ilpersonaldesktopgui", "ilpdnotesgui", "ilnotegui"), + "editNoteForm" + ) + ); + $tpl->setVariable("TXT_EDIT_NOTE", $lng->txt("edit")); + $tpl->parseCurrentBlock(); + $ilCtrl->clearParametersByClass("ilnotegui"); + + // last edited + if ($note->getUpdateDate() != null) { + $tpl->setVariable("TXT_LAST_EDIT", $lng->txt("last_edited_on")); + $tpl->setVariable( + "DATE_LAST_EDIT", + ilDatePresentation::formatDate(new ilDate($note->getUpdateDate(), IL_CAL_DATETIME)) + ); + } else { + //$tpl->setVariable("TXT_CREATED", $lng->txt("create_date")); + $tpl->setVariable( + "VAL_DATE", + ilDatePresentation::formatDate(new ilDate($note->getCreationDate(), IL_CAL_DATETIME)) + ); + } + + $tpl->setVariable("VAL_SUBJECT", $note->getSubject()); + $text = (trim($note->getText()) != "") + ? nl2br($note->getText()) + : "

                  " . $lng->txt("note_content_removed") . "

                  "; + $tpl->setVariable("NOTE_TEXT", $text); + $tpl->setVariable("TARGET_OBJECTS", $this->renderTargets($note)); + return $tpl->get(); + } + + /** + * show related objects as links + */ + public function renderTargets($a_note) + { + $tree = $this->tree; + $ilAccess = $this->access; + $objDefinition = $this->obj_definition; + $ilUser = $this->user; + + if (!$this->targets_enabled) { + return ""; + } + + $a_note_id = $a_note->getId(); + $target = $a_note->getObject(); + $a_obj_type = $target["obj_type"]; + $a_obj_id = $target["obj_id"]; + + $target_tpl = new ilTemplate("tpl.note_target_object.html", true, true, "Services/Notes"); + + if ($target["rep_obj_id"] > 0) { + // get all visible references of target object + + // repository + $ref_ids = ilObject::_getAllReferences($target["rep_obj_id"]); + if ($ref_ids) { + $vis_ref_ids = array(); + foreach ($ref_ids as $ref_id) { + if ($ilAccess->checkAccess("visible", "", $ref_id)) { + $vis_ref_ids[] = $ref_id; + } + } + + // output links to targets + if (count($vis_ref_ids) > 0) { + foreach ($vis_ref_ids as $vis_ref_id) { + $type = ilObject::_lookupType($vis_ref_id, true); + $title = ilObject::_lookupTitle($target["rep_obj_id"]); + + $sub_link = $sub_title = ""; + if ($type == "sahs") { // bad hack, needs general procedure + $link = "goto.php?target=sahs_" . $vis_ref_id; + if ($a_obj_type == "sco" || $a_obj_type == "seqc" || $a_obj_type == "chap" || $a_obj_type == "pg") { + $sub_link = "goto.php?target=sahs_" . $vis_ref_id . "_" . $a_obj_id; + include_once("./Modules/Scorm2004/classes/class.ilSCORM2004Node.php"); + $sub_title = ilSCORM2004Node::_lookupTitle($a_obj_id); + } + } elseif ($type == "poll") { + include_once "Services/Link/classes/class.ilLink.php"; + $link = ilLink::_getLink($vis_ref_id, "poll"); + } elseif ($a_obj_type != "pg") { + if (!is_object($this->item_list_gui[$type])) { + $class = $objDefinition->getClassName($type); + $location = $objDefinition->getLocation($type); + $full_class = "ilObj" . $class . "ListGUI"; + include_once($location . "/class." . $full_class . ".php"); + $this->item_list_gui[$type] = new $full_class(); + } + + // for references, get original title + // (link will lead to orignal, which basically is wrong though) + if ($a_obj_type == "crsr" || $a_obj_type == "catr" || $a_obj_type == "grpr") { + include_once "Services/ContainerReference/classes/class.ilContainerReference.php"; + $tgt_obj_id = ilContainerReference::_lookupTargetId($target["rep_obj_id"]); + $title = ilObject::_lookupTitle($tgt_obj_id); + } + $this->item_list_gui[$type]->initItem($vis_ref_id, $target["rep_obj_id"], $title); + $link = $this->item_list_gui[$type]->getCommandLink("infoScreen"); + + // workaround, because # anchor can't be passed through frameset + $link = ilUtil::appendUrlParameterString($link, "anchor=note_" . $a_note_id); + + $link = $this->item_list_gui[$type]->appendRepositoryFrameParameter($link) . "#note_" . $a_note_id; + } else { + $title = ilObject::_lookupTitle($target["rep_obj_id"]); + $link = "goto.php?target=pg_" . $a_obj_id . "_" . $vis_ref_id; + } + + $par_id = $tree->getParentId($vis_ref_id); + + // sub object link + if ($sub_link != "") { + if ($this->export_html || $this->print) { + $target_tpl->setCurrentBlock("exp_target_sub_object"); + } else { + $target_tpl->setCurrentBlock("target_sub_object"); + $target_tpl->setVariable("LINK_SUB_TARGET", $sub_link); + } + $target_tpl->setVariable("TXT_SUB_TARGET", $sub_title); + $target_tpl->parseCurrentBlock(); + } + + // container and object link + if ($this->export_html || $this->print) { + $target_tpl->setCurrentBlock("exp_target_object"); + } else { + $target_tpl->setCurrentBlock("target_object"); + $target_tpl->setVariable("LINK_TARGET", $link); + } + $target_tpl->setVariable( + "TXT_CONTAINER", + ilObject::_lookupTitle( + ilObject::_lookupObjId($par_id) + ) + ); + $target_tpl->setVariable("TXT_TARGET", $title); + + $target_tpl->parseCurrentBlock(); + } + $target_tpl->touchBlock("target_objects"); + } + } + // personal workspace + else { + // we only need 1 instance + if (!$this->wsp_tree) { + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; + $this->wsp_tree = new ilWorkspaceTree($ilUser->getId()); + $this->wsp_access_handler = new ilWorkspaceAccessHandler($this->wsp_tree); + } + $node_id = $this->wsp_tree->lookupNodeId($target["rep_obj_id"]); + if ($this->wsp_access_handler->checkAccess("visible", "", $node_id)) { + $path = $this->wsp_tree->getPathFull($node_id); + if ($path) { + $item = array_pop($path); + $parent = array_pop($path); + + if (!$parent["title"]) { + $parent["title"] = $this->lng->txt("wsp_personal_workspace"); + } + + // sub-objects + $additional = null; + if ($a_obj_id) { + $sub_title = $this->getSubObjectTitle($target["rep_obj_id"], $a_obj_id); + if ($sub_title) { + $item["title"] .= " (" . $sub_title . ")"; + $additional = "_" . $a_obj_id; + } + } + + $link = ilWorkspaceAccessHandler::getGotoLink($node_id, $target["rep_obj_id"], $additional); + } + // shared resource + else { + $owner = ilObject::_lookupOwner($target["rep_obj_id"]); + $parent["title"] = $this->lng->txt("wsp_tab_shared") . + " (" . ilObject::_lookupOwnerName($owner) . ")"; + $item["title"] = ilObject::_lookupTitle($target["rep_obj_id"]); + $link = "ilias.php?baseClass=ilPersonalDesktopGUI&cmd=jumpToWorkspace&dsh=" . + $owner; + } + + // container and object link + if ($this->export_html || $this->print) { + $target_tpl->setCurrentBlock("exp_target_object"); + } else { + $target_tpl->setCurrentBlock("target_object"); + $target_tpl->setVariable("LINK_TARGET", $link); + } + + + // :TODO: no images in template ? + + $target_tpl->setVariable("TXT_CONTAINER", $parent["title"]); + + $target_tpl->setVariable("TXT_TARGET", $item["title"]); + + $target_tpl->parseCurrentBlock(); + } + } + } + return $target_tpl->get(); + } + + /** + * get notes list including add note area + */ + public function addNoteForm($a_init_form = true) + { + $ilUser = $this->user; + + $suffix = ($_GET["note_type"] == IL_NOTE_PRIVATE) + ? "private" + : "public"; + $ilUser->setPref("notes_" . $suffix, "y"); + + $this->add_note_form = true; + return $this->getNotesHTML($a_init_form); + } + + /** + * cancel add note + */ + public function cancelAddNote() + { + return $this->getNotesHTML(); + } + + /** + * cancel edit note + */ + public function cancelUpdateNote() + { + return $this->getNotesHTML(); + } + + /** + * add note + */ + public function addNote() + { + $ilUser = $this->user; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + //ilLoggerFactory::getLogger("root")->notice("addNote"); + $this->initNoteForm("create", $_GET["note_type"]); + + //if ($this->form->checkInput()) + if ($_POST["note"] != "") { + $note = new ilNote(); + $note->setObject($this->obj_type, $this->rep_obj_id, $this->obj_id, $this->news_id); + $note->setInRepository($this->repository_mode); + $note->setType($_GET["note_type"]); + $note->setAuthor($ilUser->getId()); + $note->setText(ilUtil::stripslashes($_POST["note"])); + // $note->setSubject($_POST["sub_note"]); + // $note->setLabel($_POST["note_label"]); + $note->create(); + + $this->notifyObserver("new", $note); + + $ilCtrl->setParameter($this, "note_mess", "mod"); + // $ilCtrl->redirect($this, "showNotes", "notes_top", $this->ajax); + } + $ilCtrl->redirect($this, "showNotes", "notes_top", $this->ajax); + // $this->note_mess = "frmfld"; // $this->form->setValuesByPost(); // return $this->addNoteForm(false);; - } - - /** - * update note - */ - function updateNote() - { - $ilUser = $this->user; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $note = new ilNote(ilUtil::stripSlashes($_POST["note_id"])); - $this->initNoteForm("edit", $note->getType(), - $note); - -// if ($this->form->checkInput()) -// if ($_POST["note"] != "") -// { - $note->setText(ilUtil::stripSlashes($_POST["note"])); - $note->setSubject(ilUtil::stripSlashes($_POST["sub_note"])); - $note->setLabel(ilUtil::stripSlashes($_POST["note_label"])); - if ($this->checkEdit($note)) - { - $note->update(); - - $this->notifyObserver("update", $note); - - $ilCtrl->setParameter($this, "note_mess", "mod"); - } - $ilCtrl->redirect($this, "showNotes", "notes_top", $this->ajax); -// } -$ilCtrl->redirect($this, "showNotes", "notes_top", $this->ajax); - $this->note_mess = "frmfld"; - $this->form->setValuesByPost(); - $_GET["note_id"] = $note->getId(); - $_GET["note_type"] = $note->getType(); - return $this->editNoteForm(false); - } - - /** - * get notes list including add note area - */ - function editNoteForm($a_init_form = true) - { - $this->edit_note_form = true; - - return $this->getNotesHTML($a_init_form); - } - - /** - * delete note confirmation - */ - function deleteNote() - { - $this->delete_note = true; - $this->note_mess = "qdel"; - return $this->getNotesHTML(); - } - - /** - * delete notes confirmation - */ - function deleteNotes() - { - $lng = $this->lng; - - if (!$_POST["note"]) - { - $this->note_mess = "noc"; - } - else - { - $this->delete_note = true; - $this->note_mess = "qdel"; - } - - return $this->getNotesHTML(); - } - - /** - * cancel deletion of note - */ - function cancelDelete() - { - return $this->getNotesHTML(); - } - - /** - * cancel deletion of note - */ - function confirmDelete() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilUser = $this->user; - - $cnt = 0; - foreach($_POST["note"] as $id) - { - $note = new ilNote($id); - if ($this->checkDeletion($note)) - { - $note->delete(); - $cnt++; - } - } - if ($cnt > 1) - { - $ilCtrl->setParameter($this, "note_mess", "ntsdel"); - } - else - { - $ilCtrl->setParameter($this, "note_mess", "ntdel"); - } - $ilCtrl->redirect($this, "showNotes", "notes_top", $this->ajax); - } - - /** - * export selected notes to html - */ - function exportNotesHTML() - { - $tpl = new ilTemplate("tpl.main.html", true, true); - - $this->export_html = true; - $this->multi_selection = false; - $tpl->setVariable("CONTENT", $this->getNotesHTML()); - ilUtil::deliverData($tpl->get(), "notes.html"); - } - - /** - * notes print view screen - */ - function printNotes() - { - $tpl = new ilTemplate("tpl.main.html", true, true); - - $this->print = true; - $this->multi_selection = false; - $tpl->setVariable("CONTENT", $this->getNotesHTML()); - echo $tpl->get(); exit; - } - - /** - * show notes - */ - function showNotes() - { - $ilUser = $this->user; - - $suffix = ($_GET["note_type"] == IL_NOTE_PRIVATE) - ? "private" - : "public"; - $ilUser->writePref("notes_".$suffix, "y"); - - return $this->getNotesHTML(); - } - - /** - * hide notes - */ - function hideNotes() - { - $ilUser = $this->user; - - $suffix = ($_GET["note_type"] == IL_NOTE_PRIVATE) - ? "private" - : "public"; - $ilUser->writePref("notes_".$suffix, "n"); - - return $this->getNotesHTML(); - } - - /** - * show all public notes to user - */ - function showAllPublicNotes() - { - $ilUser = $this->user; - - $ilUser->writePref("notes_pub_all", "y"); - - return $this->getNotesHTML(); - } - - /** - * show only public notes of user - */ - function showMyPublicNotes() - { - $ilUser = $this->user; - - $ilUser->writePref("notes_pub_all", "n"); - - return $this->getNotesHTML(); - } - - /** - * Init javascript - */ - static function initJavascript($a_ajax_url, $a_type = IL_NOTE_PRIVATE, ilTemplate $a_main_tpl = null) - { - global $DIC; - - if ($a_main_tpl != null) - { - $tpl = $a_main_tpl; - } - else - { - $tpl = $DIC["tpl"]; - } - $lng = $DIC->language(); - - $lng->loadLanguageModule("notes"); - - include_once("./Services/UIComponent/Modal/classes/class.ilModalGUI.php"); - ilModalGUI::initJS($tpl); - - $lng->toJs(array("private_notes", "notes_public_comments"), $tpl); - - include_once("./Services/YUI/classes/class.ilYuiUtil.php"); - ilYuiUtil::initPanel(false, $tpl); - include_once("./Services/jQuery/classes/class.iljQueryUtil.php"); - iljQueryUtil::initjQuery($tpl); - $tpl->addJavascript("./Services/Notes/js/ilNotes.js"); - - $tpl->addOnLoadCode("ilNotes.setAjaxUrl('".$a_ajax_url."');"); - } - - /** - * Get list notes js call - * - * @param string $a_hash - * @param string $a_update_code - * @return string - */ - static function getListNotesJSCall($a_hash, $a_update_code = null) - { - if ($a_update_code === null) - { - $a_update_code = "null"; - } - else - { - $a_update_code = "'".$a_update_code."'"; - } - - return "ilNotes.listNotes(event, '".$a_hash."', ".$a_update_code.");"; - } - - /** - * Get list comments js call - * - * @param string $a_hash - * @param string $a_update_code - * @return string - */ - static function getListCommentsJSCall($a_hash, $a_update_code = null) - { - if ($a_update_code === null) - { - $a_update_code = "null"; - } - else - { - $a_update_code = "'".$a_update_code."'"; - } - - return "ilNotes.listComments(event, '".$a_hash."', ".$a_update_code.");"; - } - - /** - * Combine properties to hash - * - * @param string $a_node_type - * @param int $a_node_id - * @param int $a_sub_id - * @param string $a_sub_type - * @return string - */ - protected static function buildAjaxHash($a_node_type, $a_node_id, $a_sub_id, $a_sub_type) - { - return $a_node_type.";".$a_node_id.";".$a_sub_id.";".$a_sub_type; - } - - /** - * Render a link - */ - function renderLink($a_tpl, $a_var, $a_txt, $a_cmd, $a_anchor = "") - { - $ilCtrl = $this->ctrl; - - $low_var = strtolower($a_var); - $up_var = strtoupper($a_var); - - if ($this->ajax) - { - $a_tpl->setVariable("LINK_".$up_var, "#"); - $oc = "onclick = \"ilNotes.cmdAjaxLink(event, '". - $ilCtrl->getLinkTargetByClass("ilnotegui", $a_cmd, "", true). - "');\""; - $a_tpl->setVariable("ON_CLICK_".$up_var, $oc); - } - else - { - $a_tpl->setVariable("LINK_".$up_var, - $ilCtrl->getLinkTargetByClass("ilnotegui", $a_cmd, $a_anchor)); - } - - $a_tpl->setCurrentBlock($low_var); - $a_tpl->setVariable("TXT_".$up_var, $a_txt); - $a_tpl->parseCurrentBlock(); - } - - /** - * Add observer - * - * @param string|array $a_callback - */ - function addObserver($a_callback) - { - $this->observer[] = $a_callback; - } - - /** - * Notify observers on update/create - * - * @param string $a_action - * @param ilNote $a_note - */ - protected function notifyObserver($a_action, $a_note) - { - if (is_array($this->observer) && count($this->observer) > 0) { - foreach ($this->observer as $item) { - $param = $a_note->getObject(); - $param["action"] = $a_action; - $param["note_id"] = $a_note->getId(); - - call_user_func_array($item, $param); - } - } - } - - protected function listSortAsc() - { - $_SESSION["comments_sort_asc"] = 1; - return $this->getNotesHtml(); - } - - protected function listSortDesc() - { - $_SESSION["comments_sort_asc"] = 0; - return $this->getNotesHtml(); - } - - /** - * Get HTML - * - * @param - * @return string - */ - public function getHTML() - { - return $this->getCommentsWidget(); - } - - - /** - * Get widget - * - * @param - * @return string - */ - protected function getCommentsWidget() - { - $f = $this->ui->factory(); - $r = $this->ui->renderer(); - - $lng = $this->lng; - $ctrl = $this->ctrl; - $ctrl->setParameter($this, "news_id", $this->news_id); - $hash = ilCommonActionDispatcherGUI::buildAjaxHash( - ilCommonActionDispatcherGUI::TYPE_REPOSITORY, - null , ilObject::_lookupType($this->rep_obj_id), $this->rep_obj_id, $this->obj_type, $this->obj_id, $this->news_id); - - $cnt = ilNote::_countNotesAndComments($this->rep_obj_id, $this->obj_id, $this->obj_type, $this->news_id); - $cnt = $cnt[$this->rep_obj_id][IL_NOTE_PUBLIC]; - - $tpl = new ilTemplate("tpl.note_widget_header.html", true, true, "Services/Notes"); - $widget_el_id = "notew_".str_replace(";","_", $hash); - $ctrl->setParameter($this, "hash", $hash); - $update_url = $ctrl->getLinkTarget($this, "updateWidget","",true,false); - $comps = array(); - if ($cnt > 0) - { - $c = $f->counter()->status((int) $cnt); - $comps[] = $f->glyph()->comment()->withCounter($c)->withAdditionalOnLoadCode(function($id) use ($hash, $update_url, $widget_el_id) { - return "$(\"#$id\").click(function(event) { ".self::getListCommentsJSCall($hash, "ilNotes.updateWidget(\"".$widget_el_id."\",\"".$update_url."\");")."});"; - }); - $comps[] = $f->divider()->vertical(); - $tpl->setVariable("GLYPH", $r->render($comps)); - $tpl->setVariable("TXT_LATEST", $lng->txt("notes_latest_comment")); - } - - - $b = $f->button()->shy($lng->txt("notes_add_edit_comment"), "#")->withAdditionalOnLoadCode(function($id) use ($hash,$update_url,$widget_el_id) { - return "$(\"#$id\").click(function(event) { ".self::getListCommentsJSCall($hash, "ilNotes.updateWidget(\"".$widget_el_id."\",\"".$update_url."\");")."});"; - }); - if ($ctrl->isAsynch()) - { - $tpl->setVariable("SHY_BUTTON", $r->renderAsync($b)); - } - else - { - $tpl->setVariable("SHY_BUTTON", $r->render($b)); - } - - $this->widget_header = $tpl->get(); - - $this->hide_new_form = true; - $this->only_latest = true; - $this->no_actions = true; - $html = "
                  ".$this->getNoteListHTML(IL_NOTE_PUBLIC)."
                  "; - $ctrl->setParameter($this, "news_id", $_GET["news_id"]); - return $html; - - } - - /** - * Update widget - * - * @param - * @return - */ - protected function updateWidget() - { - echo $this->getCommentsWidget(); - exit; - } + } + + /** + * update note + */ + public function updateNote() + { + $ilUser = $this->user; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $note = new ilNote(ilUtil::stripSlashes($_POST["note_id"])); + $this->initNoteForm( + "edit", + $note->getType(), + $note + ); + + // if ($this->form->checkInput()) + // if ($_POST["note"] != "") + // { + $note->setText(ilUtil::stripSlashes($_POST["note"])); + $note->setSubject(ilUtil::stripSlashes($_POST["sub_note"])); + $note->setLabel(ilUtil::stripSlashes($_POST["note_label"])); + if ($this->checkEdit($note)) { + $note->update(); + + $this->notifyObserver("update", $note); + + $ilCtrl->setParameter($this, "note_mess", "mod"); + } + $ilCtrl->redirect($this, "showNotes", "notes_top", $this->ajax); + // } + $ilCtrl->redirect($this, "showNotes", "notes_top", $this->ajax); + $this->note_mess = "frmfld"; + $this->form->setValuesByPost(); + $_GET["note_id"] = $note->getId(); + $_GET["note_type"] = $note->getType(); + return $this->editNoteForm(false); + } + + /** + * get notes list including add note area + */ + public function editNoteForm($a_init_form = true) + { + $this->edit_note_form = true; + + return $this->getNotesHTML($a_init_form); + } + + /** + * delete note confirmation + */ + public function deleteNote() + { + $this->delete_note = true; + $this->note_mess = "qdel"; + return $this->getNotesHTML(); + } + + /** + * delete notes confirmation + */ + public function deleteNotes() + { + $lng = $this->lng; + + if (!$_POST["note"]) { + $this->note_mess = "noc"; + } else { + $this->delete_note = true; + $this->note_mess = "qdel"; + } + + return $this->getNotesHTML(); + } + + /** + * cancel deletion of note + */ + public function cancelDelete() + { + return $this->getNotesHTML(); + } + + /** + * cancel deletion of note + */ + public function confirmDelete() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilUser = $this->user; + + $cnt = 0; + foreach ($_POST["note"] as $id) { + $note = new ilNote($id); + if ($this->checkDeletion($note)) { + $note->delete(); + $cnt++; + } + } + if ($cnt > 1) { + $ilCtrl->setParameter($this, "note_mess", "ntsdel"); + } else { + $ilCtrl->setParameter($this, "note_mess", "ntdel"); + } + $ilCtrl->redirect($this, "showNotes", "notes_top", $this->ajax); + } + + /** + * export selected notes to html + */ + public function exportNotesHTML() + { + $tpl = new ilTemplate("tpl.main.html", true, true); + + $this->export_html = true; + $this->multi_selection = false; + $tpl->setVariable("CONTENT", $this->getNotesHTML()); + ilUtil::deliverData($tpl->get(), "notes.html"); + } + + /** + * notes print view screen + */ + public function printNotes() + { + $tpl = new ilTemplate("tpl.main.html", true, true); + + $this->print = true; + $this->multi_selection = false; + $tpl->setVariable("CONTENT", $this->getNotesHTML()); + echo $tpl->get(); + exit; + } + + /** + * show notes + */ + public function showNotes() + { + $ilUser = $this->user; + + $suffix = ($_GET["note_type"] == IL_NOTE_PRIVATE) + ? "private" + : "public"; + $ilUser->writePref("notes_" . $suffix, "y"); + + return $this->getNotesHTML(); + } + + /** + * hide notes + */ + public function hideNotes() + { + $ilUser = $this->user; + + $suffix = ($_GET["note_type"] == IL_NOTE_PRIVATE) + ? "private" + : "public"; + $ilUser->writePref("notes_" . $suffix, "n"); + + return $this->getNotesHTML(); + } + + /** + * show all public notes to user + */ + public function showAllPublicNotes() + { + $ilUser = $this->user; + + $ilUser->writePref("notes_pub_all", "y"); + + return $this->getNotesHTML(); + } + + /** + * show only public notes of user + */ + public function showMyPublicNotes() + { + $ilUser = $this->user; + + $ilUser->writePref("notes_pub_all", "n"); + + return $this->getNotesHTML(); + } + + /** + * Init javascript + */ + public static function initJavascript($a_ajax_url, $a_type = IL_NOTE_PRIVATE, ilTemplate $a_main_tpl = null) + { + global $DIC; + + if ($a_main_tpl != null) { + $tpl = $a_main_tpl; + } else { + $tpl = $DIC["tpl"]; + } + $lng = $DIC->language(); + + $lng->loadLanguageModule("notes"); + + include_once("./Services/UIComponent/Modal/classes/class.ilModalGUI.php"); + ilModalGUI::initJS($tpl); + + $lng->toJs(array("private_notes", "notes_public_comments"), $tpl); + + include_once("./Services/YUI/classes/class.ilYuiUtil.php"); + ilYuiUtil::initPanel(false, $tpl); + include_once("./Services/jQuery/classes/class.iljQueryUtil.php"); + iljQueryUtil::initjQuery($tpl); + $tpl->addJavascript("./Services/Notes/js/ilNotes.js"); + + $tpl->addOnLoadCode("ilNotes.setAjaxUrl('" . $a_ajax_url . "');"); + } + + /** + * Get list notes js call + * + * @param string $a_hash + * @param string $a_update_code + * @return string + */ + public static function getListNotesJSCall($a_hash, $a_update_code = null) + { + if ($a_update_code === null) { + $a_update_code = "null"; + } else { + $a_update_code = "'" . $a_update_code . "'"; + } + + return "ilNotes.listNotes(event, '" . $a_hash . "', " . $a_update_code . ");"; + } + + /** + * Get list comments js call + * + * @param string $a_hash + * @param string $a_update_code + * @return string + */ + public static function getListCommentsJSCall($a_hash, $a_update_code = null) + { + if ($a_update_code === null) { + $a_update_code = "null"; + } else { + $a_update_code = "'" . $a_update_code . "'"; + } + + return "ilNotes.listComments(event, '" . $a_hash . "', " . $a_update_code . ");"; + } + + /** + * Combine properties to hash + * + * @param string $a_node_type + * @param int $a_node_id + * @param int $a_sub_id + * @param string $a_sub_type + * @return string + */ + protected static function buildAjaxHash($a_node_type, $a_node_id, $a_sub_id, $a_sub_type) + { + return $a_node_type . ";" . $a_node_id . ";" . $a_sub_id . ";" . $a_sub_type; + } + + /** + * Render a link + */ + public function renderLink($a_tpl, $a_var, $a_txt, $a_cmd, $a_anchor = "") + { + $ilCtrl = $this->ctrl; + + $low_var = strtolower($a_var); + $up_var = strtoupper($a_var); + + if ($this->ajax) { + $a_tpl->setVariable("LINK_" . $up_var, "#"); + $oc = "onclick = \"ilNotes.cmdAjaxLink(event, '" . + $ilCtrl->getLinkTargetByClass("ilnotegui", $a_cmd, "", true) . + "');\""; + $a_tpl->setVariable("ON_CLICK_" . $up_var, $oc); + } else { + $a_tpl->setVariable( + "LINK_" . $up_var, + $ilCtrl->getLinkTargetByClass("ilnotegui", $a_cmd, $a_anchor) + ); + } + + $a_tpl->setCurrentBlock($low_var); + $a_tpl->setVariable("TXT_" . $up_var, $a_txt); + $a_tpl->parseCurrentBlock(); + } + + /** + * Add observer + * + * @param string|array $a_callback + */ + public function addObserver($a_callback) + { + $this->observer[] = $a_callback; + } + + /** + * Notify observers on update/create + * + * @param string $a_action + * @param ilNote $a_note + */ + protected function notifyObserver($a_action, $a_note) + { + if (is_array($this->observer) && count($this->observer) > 0) { + foreach ($this->observer as $item) { + $param = $a_note->getObject(); + $param["action"] = $a_action; + $param["note_id"] = $a_note->getId(); + + call_user_func_array($item, $param); + } + } + } + + protected function listSortAsc() + { + $_SESSION["comments_sort_asc"] = 1; + return $this->getNotesHtml(); + } + + protected function listSortDesc() + { + $_SESSION["comments_sort_asc"] = 0; + return $this->getNotesHtml(); + } + + /** + * Get HTML + * + * @param + * @return string + */ + public function getHTML() + { + return $this->getCommentsWidget(); + } + + + /** + * Get widget + * + * @param + * @return string + */ + protected function getCommentsWidget() + { + $f = $this->ui->factory(); + $r = $this->ui->renderer(); + + $lng = $this->lng; + $ctrl = $this->ctrl; + $ctrl->setParameter($this, "news_id", $this->news_id); + $hash = ilCommonActionDispatcherGUI::buildAjaxHash( + ilCommonActionDispatcherGUI::TYPE_REPOSITORY, + null, + ilObject::_lookupType($this->rep_obj_id), + $this->rep_obj_id, + $this->obj_type, + $this->obj_id, + $this->news_id + ); + + $cnt = ilNote::_countNotesAndComments($this->rep_obj_id, $this->obj_id, $this->obj_type, $this->news_id); + $cnt = $cnt[$this->rep_obj_id][IL_NOTE_PUBLIC]; + + $tpl = new ilTemplate("tpl.note_widget_header.html", true, true, "Services/Notes"); + $widget_el_id = "notew_" . str_replace(";", "_", $hash); + $ctrl->setParameter($this, "hash", $hash); + $update_url = $ctrl->getLinkTarget($this, "updateWidget", "", true, false); + $comps = array(); + if ($cnt > 0) { + $c = $f->counter()->status((int) $cnt); + $comps[] = $f->glyph()->comment()->withCounter($c)->withAdditionalOnLoadCode(function ($id) use ($hash, $update_url, $widget_el_id) { + return "$(\"#$id\").click(function(event) { " . self::getListCommentsJSCall($hash, "ilNotes.updateWidget(\"" . $widget_el_id . "\",\"" . $update_url . "\");") . "});"; + }); + $comps[] = $f->divider()->vertical(); + $tpl->setVariable("GLYPH", $r->render($comps)); + $tpl->setVariable("TXT_LATEST", $lng->txt("notes_latest_comment")); + } + + + $b = $f->button()->shy($lng->txt("notes_add_edit_comment"), "#")->withAdditionalOnLoadCode(function ($id) use ($hash,$update_url,$widget_el_id) { + return "$(\"#$id\").click(function(event) { " . self::getListCommentsJSCall($hash, "ilNotes.updateWidget(\"" . $widget_el_id . "\",\"" . $update_url . "\");") . "});"; + }); + if ($ctrl->isAsynch()) { + $tpl->setVariable("SHY_BUTTON", $r->renderAsync($b)); + } else { + $tpl->setVariable("SHY_BUTTON", $r->render($b)); + } + + $this->widget_header = $tpl->get(); + + $this->hide_new_form = true; + $this->only_latest = true; + $this->no_actions = true; + $html = "
                  " . $this->getNoteListHTML(IL_NOTE_PUBLIC) . "
                  "; + $ctrl->setParameter($this, "news_id", $_GET["news_id"]); + return $html; + } + + /** + * Update widget + * + * @param + * @return + */ + protected function updateWidget() + { + echo $this->getCommentsWidget(); + exit; + } } - -?> \ No newline at end of file diff --git a/Services/Notes/classes/class.ilNotesDataSet.php b/Services/Notes/classes/class.ilNotesDataSet.php index f9e5efbb9c85532b5fda9da446a68513dea32fb2..4e37816e302fdeeda4fffe4cc00c8b87aea2a5e8 100644 --- a/Services/Notes/classes/class.ilNotesDataSet.php +++ b/Services/Notes/classes/class.ilNotesDataSet.php @@ -7,148 +7,139 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); * Notes Data set class. Entities * - user_notes: All personal notes of a user (do not use this for object * related queries. Add a new entity for this purpose. - * + * * @author Alex Killing * @version $Id$ * @ingroup ingroup ServicesNotes */ class ilNotesDataSet extends ilDataSet { - /** - * Get supported versions - * - * @param - * @return - */ - public function getSupportedVersions() - { - return array("4.3.0"); - } - - /** - * Get xml namespace - * - * @param - * @return - */ - function getXmlNamespace($a_entity, $a_schema_version) - { - return "http://www.ilias.de/xml/Services/Notes/".$a_entity; - } - - /** - * Get field types for entity - * - * @param - * @return - */ - protected function getTypes($a_entity, $a_version) - { - // user notes - if ($a_entity == "user_notes") - { - switch ($a_version) - { - case "4.3.0": - return array( - "Id" => "integer", - "RepObjId" => "integer", - "ObjId" => "integer", - "ObjType" => "text", - "ObjType" => "text", - "Type" => "integer", - "Author" => "integer", - "CreationDate" => "timestamp", - "NoteText" => "text", - "Label" => "integer", - "Subject" => "text", - "NoRepository" => "integer" - ); - } - } - } + /** + * Get supported versions + * + * @param + * @return + */ + public function getSupportedVersions() + { + return array("4.3.0"); + } + + /** + * Get xml namespace + * + * @param + * @return + */ + public function getXmlNamespace($a_entity, $a_schema_version) + { + return "http://www.ilias.de/xml/Services/Notes/" . $a_entity; + } + + /** + * Get field types for entity + * + * @param + * @return + */ + protected function getTypes($a_entity, $a_version) + { + // user notes + if ($a_entity == "user_notes") { + switch ($a_version) { + case "4.3.0": + return array( + "Id" => "integer", + "RepObjId" => "integer", + "ObjId" => "integer", + "ObjType" => "text", + "ObjType" => "text", + "Type" => "integer", + "Author" => "integer", + "CreationDate" => "timestamp", + "NoteText" => "text", + "Label" => "integer", + "Subject" => "text", + "NoRepository" => "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 (!is_array($a_ids)) { + $a_ids = array($a_ids); + } - // user notes - if ($a_entity == "user_notes") - { - switch ($a_version) - { - case "4.3.0": - $this->getDirectDataFromQuery("SELECT id, rep_obj_id, obj_id, obj_type, type, ". - " author, note_text, creation_date, label, subject, no_repository ". - " FROM note ". - " WHERE ". - $ilDB->in("author", $a_ids, false, "integer"). - " AND obj_type = ".$ilDB->quote("pd" ,"text")); - break; - } - } - } - - /** - * Determine the dependent sets of data - */ - protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) - { - return false; - } - - //// - //// Needs abstraction (interface?) and version handling - //// - - - /** - * Import record - * - * @param - * @return - */ - function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) - { - switch ($a_entity) - { - case "user_notes": - $usr_id = $a_mapping->getMapping("Services/User", "usr", $a_rec["Author"]); - if ($usr_id > 0) - { - include_once("./Services/Notes/classes/class.ilNote.php"); - - // only import real user (assigned to personal desktop) notes - // here. - if ((int) $a_rec["RepObjId"] == 0 && - $a_rec["ObjId"] == $a_rec["Author"] && - $a_rec["Type"] == IL_NOTE_PRIVATE && - $a_rec["ObjType"] == "pd") - { - $note = new ilNote(); - $note->setObject("pd", 0, $usr_id); - $note->setType(IL_NOTE_PRIVATE); - $note->setAuthor($usr_id); - $note->setText($a_rec["NoteText"]); - $note->setSubject($a_rec["Subject"]); - $note->setCreationDate($a_rec["CreationDate"]); - $note->setLabel($a_rec["Label"]); - $note->create(true); - } - } - break; - } - } + // user notes + if ($a_entity == "user_notes") { + switch ($a_version) { + case "4.3.0": + $this->getDirectDataFromQuery("SELECT id, rep_obj_id, obj_id, obj_type, type, " . + " author, note_text, creation_date, label, subject, no_repository " . + " FROM note " . + " WHERE " . + $ilDB->in("author", $a_ids, false, "integer") . + " AND obj_type = " . $ilDB->quote("pd", "text")); + break; + } + } + } + + /** + * Determine the dependent sets of data + */ + protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) + { + return false; + } + + //// + //// Needs abstraction (interface?) and version handling + //// + + + /** + * Import record + * + * @param + * @return + */ + public function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) + { + switch ($a_entity) { + case "user_notes": + $usr_id = $a_mapping->getMapping("Services/User", "usr", $a_rec["Author"]); + if ($usr_id > 0) { + include_once("./Services/Notes/classes/class.ilNote.php"); + + // only import real user (assigned to personal desktop) notes + // here. + if ((int) $a_rec["RepObjId"] == 0 && + $a_rec["ObjId"] == $a_rec["Author"] && + $a_rec["Type"] == IL_NOTE_PRIVATE && + $a_rec["ObjType"] == "pd") { + $note = new ilNote(); + $note->setObject("pd", 0, $usr_id); + $note->setType(IL_NOTE_PRIVATE); + $note->setAuthor($usr_id); + $note->setText($a_rec["NoteText"]); + $note->setSubject($a_rec["Subject"]); + $note->setCreationDate($a_rec["CreationDate"]); + $note->setLabel($a_rec["Label"]); + $note->create(true); + } + } + break; + } + } } -?> \ No newline at end of file diff --git a/Services/Notes/classes/class.ilNotesExporter.php b/Services/Notes/classes/class.ilNotesExporter.php index 059fb9b51c8f4643b50ec9cf1506432196e9f4c3..62d558b3bcee602dc0e09e9438192134b095cb07 100644 --- a/Services/Notes/classes/class.ilNotesExporter.php +++ b/Services/Notes/classes/class.ilNotesExporter.php @@ -12,53 +12,49 @@ include_once("./Services/Export/classes/class.ilXmlExporter.php"); */ class ilNotesExporter extends ilXmlExporter { - private $ds; + private $ds; - /** - * Initialisation - */ - function init() - { - include_once("./Services/Notes/classes/class.ilNotesDataSet.php"); - $this->ds = new ilNotesDataSet(); - $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); - $this->ds->setDSPrefix("ds"); - } + /** + * Initialisation + */ + public function init() + { + include_once("./Services/Notes/classes/class.ilNotesDataSet.php"); + $this->ds = new ilNotesDataSet(); + $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); + $this->ds->setDSPrefix("ds"); + } - /** - * Get xml representation - * - * @param string entity - * @param string target release - * @param string id - * @return string xml string - */ - 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); - } + /** + * Get xml representation + * + * @param string entity + * @param string target release + * @param string id + * @return string xml string + */ + 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); + } - /** - * Returns schema versions that the component can export to. - * ILIAS chooses the first one, that has min/max constraints which - * fit to the target release. Please put the newest on top. - * - * @return - */ - function getValidSchemaVersions($a_entity) - { - return array ( - "4.3.0" => array( - "namespace" => "http://www.ilias.de/Services/Notes/note/4_3", - "xsd_file" => "ilias_usr_4_3.xsd", - "uses_dataset" => true, - "min" => "4.3.0", - "max" => "") - ); - } - - + /** + * Returns schema versions that the component can export to. + * ILIAS chooses the first one, that has min/max constraints which + * fit to the target release. Please put the newest on top. + * + * @return + */ + public function getValidSchemaVersions($a_entity) + { + return array( + "4.3.0" => array( + "namespace" => "http://www.ilias.de/Services/Notes/note/4_3", + "xsd_file" => "ilias_usr_4_3.xsd", + "uses_dataset" => true, + "min" => "4.3.0", + "max" => "") + ); + } } - -?> \ No newline at end of file diff --git a/Services/Notes/classes/class.ilNotesGlobalScreenProvider.php b/Services/Notes/classes/class.ilNotesGlobalScreenProvider.php index ddf17e38a46a068b101c27ff53ba7462ebb0279e..086c82631b1ef2156c4bc337540d34227d8c6bcc 100644 --- a/Services/Notes/classes/class.ilNotesGlobalScreenProvider.php +++ b/Services/Notes/classes/class.ilNotesGlobalScreenProvider.php @@ -8,79 +8,84 @@ use ILIAS\GlobalScreen\Scope\MainMenu\Provider\AbstractStaticMainMenuProvider; * * @author Fabian Schmid */ -class ilNotesGlobalScreenProvider extends AbstractStaticMainMenuProvider { +class ilNotesGlobalScreenProvider extends AbstractStaticMainMenuProvider +{ - /** - * @var IdentificationInterface - */ - protected $top_item; + /** + * @var IdentificationInterface + */ + protected $top_item; - public function __construct(\ILIAS\DI\Container $dic) { - parent::__construct($dic); - $this->top_item = (new ilPDGlobalScreenProvider($dic))->getTopItem(); - } + public function __construct(\ILIAS\DI\Container $dic) + { + parent::__construct($dic); + $this->top_item = (new ilPDGlobalScreenProvider($dic))->getTopItem(); + } - /** - * Some other components want to provide Items for the main menu which are - * located at the PD TopTitem by default. Therefore we have to provide our - * TopTitem Identification for others - * - * @return IdentificationInterface - */ - public function getTopItem(): IdentificationInterface { - return $this->top_item; - } + /** + * Some other components want to provide Items for the main menu which are + * located at the PD TopTitem by default. Therefore we have to provide our + * TopTitem Identification for others + * + * @return IdentificationInterface + */ + public function getTopItem() : IdentificationInterface + { + return $this->top_item; + } - /** - * @inheritDoc - */ - public function getStaticTopItems(): array { - return []; - } + /** + * @inheritDoc + */ + public function getStaticTopItems() : array + { + return []; + } - /** - * @inheritDoc - */ - public function getStaticSubItems(): array { - $dic = $this->dic; + /** + * @inheritDoc + */ + public function getStaticSubItems() : array + { + $dic = $this->dic; - $action = function () use ($dic): string { - $c = "jumpToNotes"; - if ($dic->settings()->get("disable_notes")) { - $c = "jumpToComments"; - } + $action = function () use ($dic) : string { + $c = "jumpToNotes"; + if ($dic->settings()->get("disable_notes")) { + $c = "jumpToComments"; + } - return "ilias.php?baseClass=ilPersonalDesktopGUI&cmd=" . $c; - }; - $action = $action(); - $title = function () use ($dic): string { - $dic->language()->loadLanguageModule("notes"); - $t = $dic->language()->txt("notes"); - if (!$dic->settings()->get("disable_notes") && !$dic->settings()->get("disable_comments")) { - $t = $dic->language()->txt("notes_and_comments"); - } - if ($dic->settings()->get("disable_notes")) { - $t = $dic->language()->txt("notes_comments"); - } + return "ilias.php?baseClass=ilPersonalDesktopGUI&cmd=" . $c; + }; + $action = $action(); + $title = function () use ($dic) : string { + $dic->language()->loadLanguageModule("notes"); + $t = $dic->language()->txt("notes"); + if (!$dic->settings()->get("disable_notes") && !$dic->settings()->get("disable_comments")) { + $t = $dic->language()->txt("notes_and_comments"); + } + if ($dic->settings()->get("disable_notes")) { + $t = $dic->language()->txt("notes_comments"); + } - return $t; - }; - $title = $title(); + return $t; + }; + $title = $title(); - return [$this->mainmenu->link($this->if->identifier('mm_pd_notes')) - ->withTitle($title) - ->withAction($action) - ->withParent($this->getTopItem()) - ->withPosition(11) - ->withNonAvailableReason($this->dic->ui()->factory()->legacy("{$this->dic->language()->txt('component_not_active')}")) - ->withAvailableCallable( - function () use ($dic) { - return (bool)(!$dic->settings()->get("disable_notes") || !$dic->settings()->get("disable_comments")); - } - )]; - } + return [$this->mainmenu->link($this->if->identifier('mm_pd_notes')) + ->withTitle($title) + ->withAction($action) + ->withParent($this->getTopItem()) + ->withPosition(11) + ->withNonAvailableReason($this->dic->ui()->factory()->legacy("{$this->dic->language()->txt('component_not_active')}")) + ->withAvailableCallable( + function () use ($dic) { + return (bool) (!$dic->settings()->get("disable_notes") || !$dic->settings()->get("disable_comments")); + } + )]; + } } diff --git a/Services/Notes/classes/class.ilNotesImporter.php b/Services/Notes/classes/class.ilNotesImporter.php index 4c07b550fa9ee425b752be21cf99e80a4d1f324b..115f7b4c4f0b422c2182a6ef761c9ccc256a0c9a 100644 --- a/Services/Notes/classes/class.ilNotesImporter.php +++ b/Services/Notes/classes/class.ilNotesImporter.php @@ -13,31 +13,32 @@ include_once("./Services/Export/classes/class.ilXmlImporter.php"); class ilNotesImporter extends ilXmlImporter { - /** - * Initialisation - */ - function init() - { - include_once("./Services/Notes/classes/class.ilNotesDataSet.php"); - $this->ds = new ilNotesDataSet(); - $this->ds->setDSPrefix("ds"); - } + /** + * Initialisation + */ + public function init() + { + include_once("./Services/Notes/classes/class.ilNotesDataSet.php"); + $this->ds = new ilNotesDataSet(); + $this->ds->setDSPrefix("ds"); + } - /** - * Import XML - * - * @param - * @return - */ - function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) - { - include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); - $parser = new ilDataSetImportParser($a_entity, $this->getSchemaVersion(), - $a_xml, $this->ds, $a_mapping); - } - - + /** + * Import XML + * + * @param + * @return + */ + public function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) + { + include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); + $parser = new ilDataSetImportParser( + $a_entity, + $this->getSchemaVersion(), + $a_xml, + $this->ds, + $a_mapping + ); + } } - -?> \ No newline at end of file diff --git a/Services/Notes/classes/class.ilPDNotesBlockGUI.php b/Services/Notes/classes/class.ilPDNotesBlockGUI.php index 2877274f192a47fa138e7a395790f8b3978af2d9..09d17f92ca4cbccd5b132f3ba4f3367a064b18b5 100755 --- a/Services/Notes/classes/class.ilPDNotesBlockGUI.php +++ b/Services/Notes/classes/class.ilPDNotesBlockGUI.php @@ -14,274 +14,267 @@ include_once("Services/Block/classes/class.ilBlockGUI.php"); */ class ilPDNotesBlockGUI extends ilBlockGUI { - static $block_type = "pdnotes"; - protected $note_gui = null; - - /** - * Constructor - */ - function __construct() - { - global $DIC; + public static $block_type = "pdnotes"; + protected $note_gui = null; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - $lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + $lng = $DIC->language(); - parent::__construct(); - - $this->setLimit(5); - $this->setTitle($lng->txt("notes")); - $this->setAvailableDetailLevels(3); - } + parent::__construct(); + + $this->setLimit(5); + $this->setTitle($lng->txt("notes")); + $this->setAvailableDetailLevels(3); + } - /** - * @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; - } + /** + * @inheritdoc + */ + protected function isRepositoryObject() : bool + { + return false; + } - /** - * Get Screen Mode for current command. - */ - static function getScreenMode() - { - switch($_GET["cmd"]) - { - case "showNote": - return IL_SCREEN_CENTER; - break; - - default: - return IL_SCREEN_SIDE; - break; - } - } + /** + * Get Screen Mode for current command. + */ + public static function getScreenMode() + { + switch ($_GET["cmd"]) { + case "showNote": + return IL_SCREEN_CENTER; + break; + + default: + return IL_SCREEN_SIDE; + break; + } + } - /** - * 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"); - return $this->$cmd(); - } + return $this->$cmd(); + } - function getHTML() - { - if ($this->getCurrentDetailLevel() == 0) - { - return ""; - } - else - { - return parent::getHTML(); - } - } - - /** - * Fill data section - */ - function fillDataSection() - { - $ilUser = $this->user; - - include_once("Services/Notes/classes/class.ilNote.php"); - $this->notes = ilNote::_getLastNotesOfUser(); + public function getHTML() + { + if ($this->getCurrentDetailLevel() == 0) { + return ""; + } else { + return parent::getHTML(); + } + } + + /** + * Fill data section + */ + public function fillDataSection() + { + $ilUser = $this->user; + + include_once("Services/Notes/classes/class.ilNote.php"); + $this->notes = ilNote::_getLastNotesOfUser(); - if ($this->getCurrentDetailLevel() > 1 && count($this->notes) > 0) - { - $this->setRowTemplate("tpl.pd_notes_overview.html", "Services/Notes"); - $this->getListRowData(); - //$this->setColSpan(2); - parent::fillDataSection(); - } - else - { - $this->setEnableNumInfo(false); - if (count($this->notes) == 0) - { - $this->setEnableDetailRow(false); - } - $this->setDataSection($this->getOverview()); - } - } - + if ($this->getCurrentDetailLevel() > 1 && count($this->notes) > 0) { + $this->setRowTemplate("tpl.pd_notes_overview.html", "Services/Notes"); + $this->getListRowData(); + //$this->setColSpan(2); + parent::fillDataSection(); + } else { + $this->setEnableNumInfo(false); + if (count($this->notes) == 0) { + $this->setEnableDetailRow(false); + } + $this->setDataSection($this->getOverview()); + } + } + - /** - * Get list data. - */ - function getListRowData() - { - $ilUser = $this->user; - $lng = $this->lng; - $ilCtrl = $this->ctrl; + /** + * Get list data. + */ + public function getListRowData() + { + $ilUser = $this->user; + $lng = $this->lng; + $ilCtrl = $this->ctrl; - $data = array(); - - foreach($this->notes as $note) - { - switch ($note->getLabel()) - { - case IL_NOTE_UNLABELED: - $img = ilUtil::getImagePath("note_unlabeled.svg"); - $alt = $lng->txt("note"); - break; - - case IL_NOTE_IMPORTANT: - $img = ilUtil::getImagePath("note_unlabeled.svg"); - $alt = $lng->txt("note").", ".$lng->txt("important"); - break; - - case IL_NOTE_QUESTION: - $img = ilUtil::getImagePath("note_unlabeled.svg"); - $alt = $lng->txt("note").", ".$lng->txt("question"); - break; - - case IL_NOTE_PRO: - $img = ilUtil::getImagePath("note_unlabeled.svg"); - $alt = $lng->txt("note").", ".$lng->txt("pro"); - break; - - case IL_NOTE_CONTRA: - $img = ilUtil::getImagePath("note_unlabeled.svg"); - $alt = $lng->txt("note").", ".$lng->txt("contra"); - break; - } + $data = array(); + + foreach ($this->notes as $note) { + switch ($note->getLabel()) { + case IL_NOTE_UNLABELED: + $img = ilUtil::getImagePath("note_unlabeled.svg"); + $alt = $lng->txt("note"); + break; + + case IL_NOTE_IMPORTANT: + $img = ilUtil::getImagePath("note_unlabeled.svg"); + $alt = $lng->txt("note") . ", " . $lng->txt("important"); + break; + + case IL_NOTE_QUESTION: + $img = ilUtil::getImagePath("note_unlabeled.svg"); + $alt = $lng->txt("note") . ", " . $lng->txt("question"); + break; + + case IL_NOTE_PRO: + $img = ilUtil::getImagePath("note_unlabeled.svg"); + $alt = $lng->txt("note") . ", " . $lng->txt("pro"); + break; + + case IL_NOTE_CONTRA: + $img = ilUtil::getImagePath("note_unlabeled.svg"); + $alt = $lng->txt("note") . ", " . $lng->txt("contra"); + break; + } - // details - $target = $note->getObject(); - - // new notes do not have subject anymore - $title = $note->getSubject(); - if(!$title) - { - $title = ilUtil::shortenText($note->getText(), 75, true, true); - } + // details + $target = $note->getObject(); + + // new notes do not have subject anymore + $title = $note->getSubject(); + if (!$title) { + $title = ilUtil::shortenText($note->getText(), 75, true, true); + } - $data[] = array( - "subject" => $title, - "img" => $img, - "alt" => $alt, - "text" => ilUtil::shortenText($note->getText(), 150, true, true), - "date" => $note->getCreationDate(), - "id" => $note->getId(), - "obj_type" => $target["obj_type"], - "obj_id" => $target["obj_id"], - "rep_obj_id" => $target["rep_obj_id"]); - } - - $this->setData($data); - } - - /** - * get flat bookmark list for personal desktop - */ - function fillRow($a_set) - { - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - include_once("Services/Notes/classes/class.ilNoteGUI.php"); - if (!is_object($this->note_gui)) - { - $this->note_gui = new ilNoteGUI(0,0,""); - $this->note_gui->enableTargets(); - } + $data[] = array( + "subject" => $title, + "img" => $img, + "alt" => $alt, + "text" => ilUtil::shortenText($note->getText(), 150, true, true), + "date" => $note->getCreationDate(), + "id" => $note->getId(), + "obj_type" => $target["obj_type"], + "obj_id" => $target["obj_id"], + "rep_obj_id" => $target["rep_obj_id"]); + } + + $this->setData($data); + } + + /** + * get flat bookmark list for personal desktop + */ + public function fillRow($a_set) + { + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + include_once("Services/Notes/classes/class.ilNoteGUI.php"); + if (!is_object($this->note_gui)) { + $this->note_gui = new ilNoteGUI(0, 0, ""); + $this->note_gui->enableTargets(); + } - $this->tpl->setVariable("VAL_SUBJECT", $a_set["subject"]); + $this->tpl->setVariable("VAL_SUBJECT", $a_set["subject"]); - // link subject to show note function - $ilCtrl->setParameter($this, "rel_obj", $a_set["rep_obj_id"]); - $ilCtrl->setParameter($this, "note_id", $a_set["id"]); - $ilCtrl->setParameter($this, "note_type", IL_NOTE_PRIVATE); - $this->tpl->setVariable("HREF_SHOW_NOTE", - $ilCtrl->getLinkTarget($this, "showNote")); - $this->tpl->setVariable("IMG_NOTE", $a_set["img"]); - $this->tpl->setVariable("ALT_NOTE", $a_set["alt"]); - $ilCtrl->clearParameters($this); - - // details - if ($this->getCurrentDetailLevel() > 2) - { - $this->tpl->setCurrentBlock("details"); - if (substr($a_set["text"], 0, 40) != substr($a_set["text"], 0, 40)) - { - $this->tpl->setVariable("NOTE_TEXT", $a_set["text"]); - } - $this->tpl->setVariable("VAL_DATE", - ilDatePresentation::formatDate(new ilDateTime($a_set["date"], IL_CAL_DATETIME))); - $this->tpl->parseCurrentBlock(); - - // target objects - $note = new ilNote($a_set["id"]); - $this->tpl->setVariable("TARGET_OBJECTS", - $this->note_gui->renderTargets($note)); + // link subject to show note function + $ilCtrl->setParameter($this, "rel_obj", $a_set["rep_obj_id"]); + $ilCtrl->setParameter($this, "note_id", $a_set["id"]); + $ilCtrl->setParameter($this, "note_type", IL_NOTE_PRIVATE); + $this->tpl->setVariable( + "HREF_SHOW_NOTE", + $ilCtrl->getLinkTarget($this, "showNote") + ); + $this->tpl->setVariable("IMG_NOTE", $a_set["img"]); + $this->tpl->setVariable("ALT_NOTE", $a_set["alt"]); + $ilCtrl->clearParameters($this); + + // details + if ($this->getCurrentDetailLevel() > 2) { + $this->tpl->setCurrentBlock("details"); + if (substr($a_set["text"], 0, 40) != substr($a_set["text"], 0, 40)) { + $this->tpl->setVariable("NOTE_TEXT", $a_set["text"]); + } + $this->tpl->setVariable( + "VAL_DATE", + ilDatePresentation::formatDate(new ilDateTime($a_set["date"], IL_CAL_DATETIME)) + ); + $this->tpl->parseCurrentBlock(); + + // target objects + $note = new ilNote($a_set["id"]); + $this->tpl->setVariable( + "TARGET_OBJECTS", + $this->note_gui->renderTargets($note) + ); - // edit button - $this->tpl->setCurrentBlock("edit_note"); - $this->tpl->setVariable("TXT_EDIT_NOTE", $lng->txt("edit")); - $ilCtrl->setParameterByClass("ilnotegui", "rel_obj", $a_set["rep_obj_id"]); - $ilCtrl->setParameterByClass("ilnotegui", "note_id", $a_set["id"]); - $ilCtrl->setParameterByClass("ilnotegui", "note_type", IL_NOTE_PRIVATE); - $this->tpl->setVariable("LINK_EDIT_NOTE", - $ilCtrl->getLinkTargetByClass(array("ilpersonaldesktopgui", "ilpdnotesgui", "ilnotegui"), "editNoteForm") - ."#note_edit"); - $this->tpl->parseCurrentBlock(); - } - $ilCtrl->clearParametersByClass("ilnotegui"); - } + // edit button + $this->tpl->setCurrentBlock("edit_note"); + $this->tpl->setVariable("TXT_EDIT_NOTE", $lng->txt("edit")); + $ilCtrl->setParameterByClass("ilnotegui", "rel_obj", $a_set["rep_obj_id"]); + $ilCtrl->setParameterByClass("ilnotegui", "note_id", $a_set["id"]); + $ilCtrl->setParameterByClass("ilnotegui", "note_type", IL_NOTE_PRIVATE); + $this->tpl->setVariable( + "LINK_EDIT_NOTE", + $ilCtrl->getLinkTargetByClass(array("ilpersonaldesktopgui", "ilpdnotesgui", "ilnotegui"), "editNoteForm") + . "#note_edit" + ); + $this->tpl->parseCurrentBlock(); + } + $ilCtrl->clearParametersByClass("ilnotegui"); + } - /** - * Get overview. - */ - function getOverview() - { - $ilUser = $this->user; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - return '
                  '.((int) count($this->notes))." ".$lng->txt("notes")."
                  "; - } - - /** - * show single note - */ - function showNote() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("./Services/Notes/classes/class.ilNoteGUI.php"); - $note_gui = new ilNoteGUI(); - $note_gui->enableTargets(); - include_once("./Services/PersonalDesktop/classes/class.ilPDContentBlockGUI.php"); - $content_block = new ilPDContentBlockGUI(); - $content_block->setContent($note_gui->getPDNoteHTML($_GET["note_id"])); - $content_block->setTitle($lng->txt("note")); - $content_block->setColSpan(2); - $content_block->addHeaderCommand($ilCtrl->getLinkTargetByClass("ilpersonaldesktopgui", "show"), - $lng->txt("selected_items_back")); - - return $content_block->getHTML(); - } + /** + * Get overview. + */ + public function getOverview() + { + $ilUser = $this->user; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + return '
                  ' . ((int) count($this->notes)) . " " . $lng->txt("notes") . "
                  "; + } + /** + * show single note + */ + public function showNote() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("./Services/Notes/classes/class.ilNoteGUI.php"); + $note_gui = new ilNoteGUI(); + $note_gui->enableTargets(); + include_once("./Services/PersonalDesktop/classes/class.ilPDContentBlockGUI.php"); + $content_block = new ilPDContentBlockGUI(); + $content_block->setContent($note_gui->getPDNoteHTML($_GET["note_id"])); + $content_block->setTitle($lng->txt("note")); + $content_block->setColSpan(2); + $content_block->addHeaderCommand( + $ilCtrl->getLinkTargetByClass("ilpersonaldesktopgui", "show"), + $lng->txt("selected_items_back") + ); + + return $content_block->getHTML(); + } } - -?> diff --git a/Services/Notes/classes/class.ilPDNotesGUI.php b/Services/Notes/classes/class.ilPDNotesGUI.php index b364f2bf6c45784075d28ca6a06c3bde283666ee..b8029bd157886491550a1b76a05ddf5e7a2ce9ad 100755 --- a/Services/Notes/classes/class.ilPDNotesGUI.php +++ b/Services/Notes/classes/class.ilPDNotesGUI.php @@ -16,378 +16,353 @@ include_once("Services/Notes/classes/class.ilNote.php"); */ class ilPDNotesGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilHelpGUI - */ - protected $help; - - /** - * @var ilSetting - */ - protected $settings; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - var $tpl; - var $lng; - - const PUBLIC_COMMENTS = "publiccomments"; - const PRIVATE_NOTES = "privatenotes"; - - /** - * Constructor - * - * @access public - */ - function __construct() - { - global $DIC; - - $this->user = $DIC->user(); - $this->tabs = $DIC->tabs(); - $this->help = $DIC["ilHelp"]; - $this->settings = $DIC->settings(); - $this->access = $DIC->access(); - $this->toolbar = $DIC->toolbar(); - $tpl = $DIC["tpl"]; - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $ilUser = $DIC->user(); - $ilTabs = $DIC->tabs(); - $ilHelp = $DIC["ilHelp"]; - - $ilHelp->setScreenIdComponent("note"); - - $lng->loadLanguageModule("notes"); - - // initiate variables - $this->tpl = $tpl; - $this->lng = $lng; - $this->ctrl = $ilCtrl; - - // link from ilPDNotesBlockGUI - if($_GET["rel_obj"]) - { - $mode = ($_GET["note_type"] == IL_NOTE_PRIVATE) ? self::PRIVATE_NOTES : self::PUBLIC_COMMENTS; - $ilUser->writePref("pd_notes_mode", $mode); - $ilUser->writePref("pd_notes_rel_obj".$mode, $_GET["rel_obj"]); - } - // edit link - else if($_REQUEST["note_id"]) - { - $note = new ilNote($_REQUEST["note_id"]); - $mode = ($note->getType() == IL_NOTE_PRIVATE) ? self::PRIVATE_NOTES : self::PUBLIC_COMMENTS; - $obj = $note->getObject(); - $ilUser->writePref("pd_notes_mode", $mode); - $ilUser->writePref("pd_notes_rel_obj".$mode, $obj["rep_obj_id"]); - } - } - - /** - * execute command - */ - function executeCommand() - { - $next_class = $this->ctrl->getNextClass(); - switch($next_class) - { - case "ilnotegui": - // scorm2004-start - $this->setTabs(); - // scorm2004-end - $this->displayHeader(); - $this->view(); // forwardCommand is invoked in view() method - break; - - default: - // scorm2004-start - $this->setTabs(); - // scorm2004-end - $cmd = $this->ctrl->getCmd("view"); - $this->displayHeader(); - $this->$cmd(); - break; - } - $this->tpl->show(true); - return true; - } - - /** - * display header and locator - */ - function displayHeader() - { - $ilSetting = $this->settings; - - $t = $this->lng->txt("notes"); - if (!$ilSetting->get("disable_notes") && !$ilSetting->get("disable_comments")) - { - $t = $this->lng->txt("notes_and_comments"); - } - if ($ilSetting->get("disable_notes")) - { - $t = $this->lng->txt("notes_comments"); - } - - $this->tpl->setTitle($t); - - // catch feedback message - // display infopanel if something happened - ilUtil::infoPanel(); - - } - - /* - * display notes - */ - function view() - { - $ilUser = $this->user; - $lng = $this->lng; - $ilSetting = $this->settings; - $ilAccess = $this->access; - $ilToolbar = $this->toolbar; - - //$this->tpl->addBlockFile("ADM_CONTENT", "objects", "tpl.table.html") - include_once("Services/Notes/classes/class.ilNoteGUI.php"); - - // output related item selection (if more than one) - include_once("Services/Notes/classes/class.ilNote.php"); - $rel_objs = ilNote::_getRelatedObjectsOfUser($this->getMode()); -//var_dump($rel_objs); - // prepend personal dektop, if first object -// if ($rel_objs[0]["rep_obj_id"] > 0 && $this->getMode() == ilPDNotesGUI::PRIVATE_NOTES) - if ($this->getMode() == ilPDNotesGUI::PRIVATE_NOTES) - { - - $rel_objs = array_merge(array(0), $rel_objs); - } - - // #9410 - if(!$rel_objs && $this->getMode() == ilPDNotesGUI::PUBLIC_COMMENTS) - { - $lng->loadLanguageModule("notes"); - ilUtil::sendInfo($lng->txt("msg_no_search_result")); - return; - } - - $first = true; - foreach ($rel_objs as $r) - { - if ($first) // take first one as default - { - $this->current_rel_obj = $r["rep_obj_id"]; - $current_ref_ids = $r["ref_ids"]; - } - if ($r["rep_obj_id"] == $ilUser->getPref("pd_notes_rel_obj".$this->getMode())) - { - $this->current_rel_obj = $r["rep_obj_id"]; - $current_ref_ids = $r["ref_ids"]; - } - $first = false; - } - if ($this->current_rel_obj > 0) - { - $notes_gui = new ilNoteGUI($this->current_rel_obj, 0, - ilObject::_lookupType($this->current_rel_obj),true); - } - else - { - $notes_gui = new ilNoteGUI(0, $ilUser->getId(), "pd"); - } - - if ($this->getMode() == ilPDNotesGUI::PRIVATE_NOTES) - { - $notes_gui->enablePrivateNotes(true); - $notes_gui->enablePublicNotes(false); - } - else - { - $notes_gui->enablePrivateNotes(false); - $notes_gui->enablePublicNotes(true); - - // #13707 - if ($this->current_rel_obj > 0 && - sizeof($current_ref_ids) && - $ilSetting->get("comments_del_tutor", 1)) - { - foreach($current_ref_ids as $ref_id) - { - if($ilAccess->checkAccess("write", "", $ref_id)) - { - $notes_gui->enablePublicNotesDeletion(true); - break; - } - } - } - } - $notes_gui->enableHiding(false); - $notes_gui->enableTargets(true); - $notes_gui->enableMultiSelection(true); - $notes_gui->enableAnchorJump(false); - - $next_class = $this->ctrl->getNextClass($this); - - if ($next_class == "ilnotegui") - { - $html = $this->ctrl->forwardCommand($notes_gui); - } - else - { - if ($this->getMode() == ilPDNotesGUI::PRIVATE_NOTES) - { - $html = $notes_gui->getOnlyNotesHTML(); - } - else - { - $html = $notes_gui->getOnlyCommentsHTML(); - } - } - - if (count($rel_objs) > 1 || - ($rel_objs[0]["rep_obj_id"] > 0)) - { - $ilToolbar->setFormAction($this->ctrl->getFormAction($this)); - - foreach($rel_objs as $obj) - { - if ($obj["rep_obj_id"] > 0) - { - $type = ilObject::_lookupType($obj["rep_obj_id"]); - $type_str = (in_array($type, array("lm", "htlm", "sahs"))) - ? $lng->txt("learning_module") - : $lng->txt("obj_".$type); - $caption = $type_str.": ".ilObject::_lookupTitle($obj["rep_obj_id"]); - } - else - { - $caption = $lng->txt("personal_desktop"); - } - - $options[$obj["rep_obj_id"]] = $caption; - } - - include_once "Services/Form/classes/class.ilSelectInputGUI.php"; - $rel = new ilSelectInputGUI($lng->txt("related_to"), "rel_obj"); - $rel->setOptions($options); - $rel->setValue($this->current_rel_obj); - $ilToolbar->addStickyItem($rel); - - $btn = ilSubmitButton::getInstance(); - $btn->setCaption('change'); - $btn->setCommand('changeRelatedObject'); - $ilToolbar->addStickyItem($btn); - } - - $this->tpl->setContent($html); - } - - /** - * change related object - */ - function changeRelatedObject() - { - $ilUser = $this->user; - - $ilUser->writePref("pd_notes_rel_obj".$this->getMode(), $_POST["rel_obj"]); - $this->ctrl->redirect($this); - } - - // scorm2004-start - /** - * Show subtabs - */ - function setTabs() - { - $ilTabs = $this->tabs; - $ilSetting = $this->settings; - $ilCtrl = $this->ctrl; - - if(!$ilSetting->get("disable_notes")) - { - $ilTabs->addTarget("private_notes", - $ilCtrl->getLinkTarget($this, "showPrivateNotes"), "", "", "", - ($this->getMode() == ilPDNotesGUI::PRIVATE_NOTES)); - } - - if(!$ilSetting->get("disable_comments")) - { - $ilTabs->addTarget("notes_public_comments", - $ilCtrl->getLinkTarget($this, "showPublicComments"), "", "", "", - ($this->getMode() == ilPDNotesGUI::PUBLIC_COMMENTS)); - } - } - - /** - * Show private notes - */ - function showPrivateNotes() - { - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - - $ilUser->writePref("pd_notes_mode", ilPDNotesGUI::PRIVATE_NOTES); - $ilCtrl->redirect($this, ""); - } - - /** - * Show public comments - */ - function showPublicComments() - { - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - $ilSetting = $this->settings; - - if($ilSetting->get("disable_comments")) - { - $ilCtrl->redirect($this, "showPrivateNotes"); - } - - $ilUser->writePref("pd_notes_mode", ilPDNotesGUI::PUBLIC_COMMENTS); - $ilCtrl->redirect($this, ""); - } - - /** - * Get current mode - */ - function getMode() - { - $ilUser = $this->user; - $ilSetting = $this->settings; - - if ($ilUser->getPref("pd_notes_mode") == ilPDNotesGUI::PUBLIC_COMMENTS && - !$ilSetting->get("disable_comments")) - { - return ilPDNotesGUI::PUBLIC_COMMENTS; - } - else - { - return ilPDNotesGUI::PRIVATE_NOTES; - } - } + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + public $tpl; + public $lng; + + const PUBLIC_COMMENTS = "publiccomments"; + const PRIVATE_NOTES = "privatenotes"; + + /** + * Constructor + * + * @access public + */ + public function __construct() + { + global $DIC; + + $this->user = $DIC->user(); + $this->tabs = $DIC->tabs(); + $this->help = $DIC["ilHelp"]; + $this->settings = $DIC->settings(); + $this->access = $DIC->access(); + $this->toolbar = $DIC->toolbar(); + $tpl = $DIC["tpl"]; + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $ilUser = $DIC->user(); + $ilTabs = $DIC->tabs(); + $ilHelp = $DIC["ilHelp"]; + + $ilHelp->setScreenIdComponent("note"); + + $lng->loadLanguageModule("notes"); + + // initiate variables + $this->tpl = $tpl; + $this->lng = $lng; + $this->ctrl = $ilCtrl; + + // link from ilPDNotesBlockGUI + if ($_GET["rel_obj"]) { + $mode = ($_GET["note_type"] == IL_NOTE_PRIVATE) ? self::PRIVATE_NOTES : self::PUBLIC_COMMENTS; + $ilUser->writePref("pd_notes_mode", $mode); + $ilUser->writePref("pd_notes_rel_obj" . $mode, $_GET["rel_obj"]); + } + // edit link + elseif ($_REQUEST["note_id"]) { + $note = new ilNote($_REQUEST["note_id"]); + $mode = ($note->getType() == IL_NOTE_PRIVATE) ? self::PRIVATE_NOTES : self::PUBLIC_COMMENTS; + $obj = $note->getObject(); + $ilUser->writePref("pd_notes_mode", $mode); + $ilUser->writePref("pd_notes_rel_obj" . $mode, $obj["rep_obj_id"]); + } + } + + /** + * execute command + */ + public function executeCommand() + { + $next_class = $this->ctrl->getNextClass(); + switch ($next_class) { + case "ilnotegui": + // scorm2004-start + $this->setTabs(); + // scorm2004-end + $this->displayHeader(); + $this->view(); // forwardCommand is invoked in view() method + break; + + default: + // scorm2004-start + $this->setTabs(); + // scorm2004-end + $cmd = $this->ctrl->getCmd("view"); + $this->displayHeader(); + $this->$cmd(); + break; + } + $this->tpl->show(true); + return true; + } + + /** + * display header and locator + */ + public function displayHeader() + { + $ilSetting = $this->settings; + + $t = $this->lng->txt("notes"); + if (!$ilSetting->get("disable_notes") && !$ilSetting->get("disable_comments")) { + $t = $this->lng->txt("notes_and_comments"); + } + if ($ilSetting->get("disable_notes")) { + $t = $this->lng->txt("notes_comments"); + } + + $this->tpl->setTitle($t); + + // catch feedback message + // display infopanel if something happened + ilUtil::infoPanel(); + } + + /* + * display notes + */ + public function view() + { + $ilUser = $this->user; + $lng = $this->lng; + $ilSetting = $this->settings; + $ilAccess = $this->access; + $ilToolbar = $this->toolbar; + + //$this->tpl->addBlockFile("ADM_CONTENT", "objects", "tpl.table.html") + include_once("Services/Notes/classes/class.ilNoteGUI.php"); + + // output related item selection (if more than one) + include_once("Services/Notes/classes/class.ilNote.php"); + $rel_objs = ilNote::_getRelatedObjectsOfUser($this->getMode()); + //var_dump($rel_objs); + // prepend personal dektop, if first object + // if ($rel_objs[0]["rep_obj_id"] > 0 && $this->getMode() == ilPDNotesGUI::PRIVATE_NOTES) + if ($this->getMode() == ilPDNotesGUI::PRIVATE_NOTES) { + $rel_objs = array_merge(array(0), $rel_objs); + } + + // #9410 + if (!$rel_objs && $this->getMode() == ilPDNotesGUI::PUBLIC_COMMENTS) { + $lng->loadLanguageModule("notes"); + ilUtil::sendInfo($lng->txt("msg_no_search_result")); + return; + } + + $first = true; + foreach ($rel_objs as $r) { + if ($first) { // take first one as default + $this->current_rel_obj = $r["rep_obj_id"]; + $current_ref_ids = $r["ref_ids"]; + } + if ($r["rep_obj_id"] == $ilUser->getPref("pd_notes_rel_obj" . $this->getMode())) { + $this->current_rel_obj = $r["rep_obj_id"]; + $current_ref_ids = $r["ref_ids"]; + } + $first = false; + } + if ($this->current_rel_obj > 0) { + $notes_gui = new ilNoteGUI( + $this->current_rel_obj, + 0, + ilObject::_lookupType($this->current_rel_obj), + true + ); + } else { + $notes_gui = new ilNoteGUI(0, $ilUser->getId(), "pd"); + } + + if ($this->getMode() == ilPDNotesGUI::PRIVATE_NOTES) { + $notes_gui->enablePrivateNotes(true); + $notes_gui->enablePublicNotes(false); + } else { + $notes_gui->enablePrivateNotes(false); + $notes_gui->enablePublicNotes(true); + + // #13707 + if ($this->current_rel_obj > 0 && + sizeof($current_ref_ids) && + $ilSetting->get("comments_del_tutor", 1)) { + foreach ($current_ref_ids as $ref_id) { + if ($ilAccess->checkAccess("write", "", $ref_id)) { + $notes_gui->enablePublicNotesDeletion(true); + break; + } + } + } + } + $notes_gui->enableHiding(false); + $notes_gui->enableTargets(true); + $notes_gui->enableMultiSelection(true); + $notes_gui->enableAnchorJump(false); + + $next_class = $this->ctrl->getNextClass($this); + + if ($next_class == "ilnotegui") { + $html = $this->ctrl->forwardCommand($notes_gui); + } else { + if ($this->getMode() == ilPDNotesGUI::PRIVATE_NOTES) { + $html = $notes_gui->getOnlyNotesHTML(); + } else { + $html = $notes_gui->getOnlyCommentsHTML(); + } + } + + if (count($rel_objs) > 1 || + ($rel_objs[0]["rep_obj_id"] > 0)) { + $ilToolbar->setFormAction($this->ctrl->getFormAction($this)); + + foreach ($rel_objs as $obj) { + if ($obj["rep_obj_id"] > 0) { + $type = ilObject::_lookupType($obj["rep_obj_id"]); + $type_str = (in_array($type, array("lm", "htlm", "sahs"))) + ? $lng->txt("learning_module") + : $lng->txt("obj_" . $type); + $caption = $type_str . ": " . ilObject::_lookupTitle($obj["rep_obj_id"]); + } else { + $caption = $lng->txt("personal_desktop"); + } + + $options[$obj["rep_obj_id"]] = $caption; + } + + include_once "Services/Form/classes/class.ilSelectInputGUI.php"; + $rel = new ilSelectInputGUI($lng->txt("related_to"), "rel_obj"); + $rel->setOptions($options); + $rel->setValue($this->current_rel_obj); + $ilToolbar->addStickyItem($rel); + + $btn = ilSubmitButton::getInstance(); + $btn->setCaption('change'); + $btn->setCommand('changeRelatedObject'); + $ilToolbar->addStickyItem($btn); + } + + $this->tpl->setContent($html); + } + + /** + * change related object + */ + public function changeRelatedObject() + { + $ilUser = $this->user; + + $ilUser->writePref("pd_notes_rel_obj" . $this->getMode(), $_POST["rel_obj"]); + $this->ctrl->redirect($this); + } + + // scorm2004-start + /** + * Show subtabs + */ + public function setTabs() + { + $ilTabs = $this->tabs; + $ilSetting = $this->settings; + $ilCtrl = $this->ctrl; + + if (!$ilSetting->get("disable_notes")) { + $ilTabs->addTarget( + "private_notes", + $ilCtrl->getLinkTarget($this, "showPrivateNotes"), + "", + "", + "", + ($this->getMode() == ilPDNotesGUI::PRIVATE_NOTES) + ); + } + + if (!$ilSetting->get("disable_comments")) { + $ilTabs->addTarget( + "notes_public_comments", + $ilCtrl->getLinkTarget($this, "showPublicComments"), + "", + "", + "", + ($this->getMode() == ilPDNotesGUI::PUBLIC_COMMENTS) + ); + } + } + + /** + * Show private notes + */ + public function showPrivateNotes() + { + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + + $ilUser->writePref("pd_notes_mode", ilPDNotesGUI::PRIVATE_NOTES); + $ilCtrl->redirect($this, ""); + } + + /** + * Show public comments + */ + public function showPublicComments() + { + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + $ilSetting = $this->settings; + + if ($ilSetting->get("disable_comments")) { + $ilCtrl->redirect($this, "showPrivateNotes"); + } + + $ilUser->writePref("pd_notes_mode", ilPDNotesGUI::PUBLIC_COMMENTS); + $ilCtrl->redirect($this, ""); + } + + /** + * Get current mode + */ + public function getMode() + { + $ilUser = $this->user; + $ilSetting = $this->settings; + + if ($ilUser->getPref("pd_notes_mode") == ilPDNotesGUI::PUBLIC_COMMENTS && + !$ilSetting->get("disable_comments")) { + return ilPDNotesGUI::PUBLIC_COMMENTS; + } else { + return ilPDNotesGUI::PRIVATE_NOTES; + } + } } -?> diff --git a/Services/Notification/classes/class.ilNotification.php b/Services/Notification/classes/class.ilNotification.php index 02d760c8f8dfde330d7f5a4dc761acf356a98ae2..c2d82e8dd815ab36ef92447ba55a61cae9b37e68 100644 --- a/Services/Notification/classes/class.ilNotification.php +++ b/Services/Notification/classes/class.ilNotification.php @@ -12,314 +12,288 @@ * * @ingroup ServicesNotification */ -class ilNotification +class ilNotification { - const TYPE_EXERCISE_SUBMISSION = 1; - const TYPE_WIKI = 2; - const TYPE_WIKI_PAGE = 3; - const TYPE_BLOG = 4; + const TYPE_EXERCISE_SUBMISSION = 1; + const TYPE_WIKI = 2; + const TYPE_WIKI_PAGE = 3; + const TYPE_BLOG = 4; const TYPE_DATA_COLLECTION = 5; const TYPE_POLL = 6; - const TYPE_LM_BLOCKED_USERS = 7; - const TYPE_BOOK = 8; - - const THRESHOLD = 180; // time between mails in minutes - - /** - * Check notification status for object and user - * - * @param int $type - * @param int $user_id - * @param int $id - * @return bool - */ - public static function hasNotification($type, $user_id, $id) - { - global $DIC; - - $ilDB = $DIC->database(); - $tree = $DIC->repositoryTree(); - - $notification = false; - - include_once("./Services/Notification/classes/class.ilObjNotificationSettings.php"); - $setting = new ilObjNotificationSettings($id); - if ($setting->getMode() != ilObjNotificationSettings::MODE_DEF_OFF_USER_ACTIVATION) - { - // check membership, members should be notidifed... - foreach (ilObject::_getAllReferences($id) as $ref_id) - { - $grp_ref_id = $tree->checkForParentType($ref_id, 'grp'); - if ($grp_ref_id > 0) - { - include_once("./Modules/Group/classes/class.ilGroupParticipants.php"); - if (ilGroupParticipants::_isParticipant($grp_ref_id, $user_id)) - { - $notification = true; - } - } - $crs_ref_id = $tree->checkForParentType($ref_id, 'crs'); - if ($crs_ref_id > 0) - { - include_once("./Modules/Course/classes/class.ilCourseParticipants.php"); - if (ilCourseParticipants::_isParticipant($crs_ref_id, $user_id)) - { - $notification = true; - } - } - } - - if ($notification && $setting->getMode() == ilObjNotificationSettings::MODE_DEF_ON_OPT_OUT) - { - $set = $ilDB->query("SELECT user_id FROM notification" . - " WHERE type = " . $ilDB->quote($type, "integer") . - " AND user_id = " . $ilDB->quote($user_id, "integer") . - " AND id = " . $ilDB->quote($id, "integer") . - " AND activated = " . $ilDB->quote(0, "integer")); - $rec = $ilDB->fetchAssoc($set); - // ... except when the opted out - if ($rec["user_id"] == $user_id) - { - return false; - } - return true; - } - - if ($notification && $setting->getMode() == ilObjNotificationSettings::MODE_DEF_ON_NO_OPT_OUT) - { - return true; - } - } - - - $set = $ilDB->query("SELECT user_id FROM notification". - " WHERE type = ".$ilDB->quote($type, "integer"). - " AND user_id = ".$ilDB->quote($user_id, "integer"). - " AND id = ".$ilDB->quote($id, "integer"). - " AND activated = ".$ilDB->quote(1, "integer")); - - return (bool)$ilDB->numRows($set); - } - - /** - * Is opt out (disable notification) allowed? - * - * @param int $obj_id - * @return bool - */ - public static function hasOptOut($obj_id) - { - include_once("./Services/Notification/classes/class.ilObjNotificationSettings.php"); - $setting = new ilObjNotificationSettings($obj_id); - if ($setting->getMode() == ilObjNotificationSettings::MODE_DEF_ON_NO_OPT_OUT) - { - return false; - } - return true; - } - - /** - * Get all users for given object - * - * @param int $type - * @param int $id - * @param int $page_id - * @param bool $ignore_threshold - * @return array - */ - public static function getNotificationsForObject($type, $id, $page_id = null, $ignore_threshold = false) - { - global $DIC; - - $ilDB = $DIC->database(); - $tree = $DIC->repositoryTree(); - - include_once("./Services/Notification/classes/class.ilObjNotificationSettings.php"); - - // currently done for blog - $recipients = array(); - $setting = new ilObjNotificationSettings($id); - if ($setting->getMode() != ilObjNotificationSettings::MODE_DEF_OFF_USER_ACTIVATION) - { - foreach (ilObject::_getAllReferences($id) as $ref_id) - { - $grp_ref_id = $tree->checkForParentType($ref_id, 'grp'); - if ($grp_ref_id > 0) - { - include_once("./Modules/Group/classes/class.ilGroupParticipants.php"); - $p = ilGroupParticipants::_getInstanceByObjId(ilObject::_lookupObjectId($grp_ref_id)); - foreach ($p->getMembers() as $user_id) - { - if (!in_array($user_id, $recipients)) - { - $recipients[$user_id] = $user_id; - } - } - } - $crs_ref_id = $tree->checkForParentType($ref_id, 'crs'); - if ($crs_ref_id > 0) - { - include_once("./Modules/Course/classes/class.ilCourseParticipants.php"); - $p = ilCourseParticipants::_getInstanceByObjId(ilObject::_lookupObjectId($crs_ref_id)); - foreach ($p->getMembers() as $user_id) - { - if (!in_array($user_id, $recipients)) - { - $recipients[$user_id] = $user_id; - } - } - } - } - } - - // remove all users that deactivated the feature - if ($setting->getMode() == ilObjNotificationSettings::MODE_DEF_ON_OPT_OUT) - { - $sql = "SELECT user_id FROM notification" . - " WHERE type = " . $ilDB->quote($type, "integer") . - " AND id = " . $ilDB->quote($id, "integer") . - " AND activated = " . $ilDB->quote(0, "integer"). - " AND ".$ilDB->in("user_id", $recipients, false, "integer"); - $set = $ilDB->query($sql); - while ($rec = $ilDB->fetchAssoc($set)) - { - unset($recipients[$rec["user_id"]]); - } - } - - // remove all users that got a mail - if ($setting->getMode() != ilObjNotificationSettings::MODE_DEF_OFF_USER_ACTIVATION && !$ignore_threshold) - { - $sql = "SELECT user_id FROM notification" . - " WHERE type = " . $ilDB->quote($type, "integer") . - " AND id = " . $ilDB->quote($id, "integer") . - " AND activated = " . $ilDB->quote(1, "integer"). - " AND ".$ilDB->in("user_id", $recipients, false, "integer"); - $sql .= " AND (last_mail > " . $ilDB->quote(date("Y-m-d H:i:s", - strtotime("-" . self::THRESHOLD . "minutes")), "timestamp"); - if ($page_id) - { - $sql .= " AND page_id = " . $ilDB->quote($page_id, "integer"); - } - $sql .= ")"; - - $set = $ilDB->query($sql); - while ($rec = $ilDB->fetchAssoc($set)) - { - unset($recipients[$rec["user_id"]]); - } - } - - // get single subscriptions - if ($setting->getMode() != ilObjNotificationSettings::MODE_DEF_ON_NO_OPT_OUT) - { - $sql = "SELECT user_id FROM notification" . - " WHERE type = " . $ilDB->quote($type, "integer") . - " AND id = " . $ilDB->quote($id, "integer") . - " AND activated = " . $ilDB->quote(1, "integer"); - if (!$ignore_threshold) - { - $sql .= " AND (last_mail < " . $ilDB->quote(date("Y-m-d H:i:s", - strtotime("-" . self::THRESHOLD . "minutes")), "timestamp") . - " OR last_mail IS NULL"; - if ($page_id) - { - $sql .= " OR page_id <> " . $ilDB->quote($page_id, "integer"); - } - $sql .= ")"; - } - $set = $ilDB->query($sql); - while ($row = $ilDB->fetchAssoc($set)) - { - $recipients[$row["user_id"]] = $row["user_id"]; - } - } - - return $recipients; - } - - /** - * Set notification status for object and user - * - * @param int $type - * @param int $user_id - * @param int $id - * @param bool $status - */ - public static function setNotification($type, $user_id, $id, $status = true) - { - global $DIC; - - $ilDB = $DIC->database(); - - $fields = array( - "type" => array("integer", $type), - "user_id" => array("integer", $user_id), - "id" => array("integer", $id) - ); - $ilDB->replace("notification", $fields, array("activated" => array("integer", (int) $status))); - } - - /** - * Update the last mail timestamp for given object and users - * - * @param int $type - * @param int $id - * @param array $user_ids - * @param int $page_id - */ - public static function updateNotificationTime($type, $id, array $user_ids, $page_id = false) - { - global $DIC; - - $ilDB = $DIC->database(); - - $sql = "UPDATE notification". - " SET last_mail = ".$ilDB->quote(date("Y-m-d H:i:s"), "timestamp"); - - if($page_id) - { - $sql .= ", page_id = ".$ilDB->quote($page_id, "integer"); - } - - $sql .= " WHERE type = ".$ilDB->quote($type, "integer"). - " AND id = ".$ilDB->quote($id, "integer"). - " AND ".$ilDB->in("user_id", $user_ids, false, "integer"); - - $ilDB->query($sql); - } - - /** - * Remove all notifications for given object - * - * @param int $type - * @param int $id - */ - public static function removeForObject($type, $id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $ilDB->query("DELETE FROM notification". - " WHERE type = ".$ilDB->quote($type, "integer"). - " AND id = ".$ilDB->quote($id, "integer")); - } - - /** - * Remove all notifications for given user - * - * @param int $user_id - */ - public static function removeForUser($user_id) + const TYPE_LM_BLOCKED_USERS = 7; + const TYPE_BOOK = 8; + + const THRESHOLD = 180; // time between mails in minutes + + /** + * Check notification status for object and user + * + * @param int $type + * @param int $user_id + * @param int $id + * @return bool + */ + public static function hasNotification($type, $user_id, $id) { - global $DIC; + global $DIC; + + $ilDB = $DIC->database(); + $tree = $DIC->repositoryTree(); + + $notification = false; + + include_once("./Services/Notification/classes/class.ilObjNotificationSettings.php"); + $setting = new ilObjNotificationSettings($id); + if ($setting->getMode() != ilObjNotificationSettings::MODE_DEF_OFF_USER_ACTIVATION) { + // check membership, members should be notidifed... + foreach (ilObject::_getAllReferences($id) as $ref_id) { + $grp_ref_id = $tree->checkForParentType($ref_id, 'grp'); + if ($grp_ref_id > 0) { + include_once("./Modules/Group/classes/class.ilGroupParticipants.php"); + if (ilGroupParticipants::_isParticipant($grp_ref_id, $user_id)) { + $notification = true; + } + } + $crs_ref_id = $tree->checkForParentType($ref_id, 'crs'); + if ($crs_ref_id > 0) { + include_once("./Modules/Course/classes/class.ilCourseParticipants.php"); + if (ilCourseParticipants::_isParticipant($crs_ref_id, $user_id)) { + $notification = true; + } + } + } + + if ($notification && $setting->getMode() == ilObjNotificationSettings::MODE_DEF_ON_OPT_OUT) { + $set = $ilDB->query("SELECT user_id FROM notification" . + " WHERE type = " . $ilDB->quote($type, "integer") . + " AND user_id = " . $ilDB->quote($user_id, "integer") . + " AND id = " . $ilDB->quote($id, "integer") . + " AND activated = " . $ilDB->quote(0, "integer")); + $rec = $ilDB->fetchAssoc($set); + // ... except when the opted out + if ($rec["user_id"] == $user_id) { + return false; + } + return true; + } + + if ($notification && $setting->getMode() == ilObjNotificationSettings::MODE_DEF_ON_NO_OPT_OUT) { + return true; + } + } + + + $set = $ilDB->query("SELECT user_id FROM notification" . + " WHERE type = " . $ilDB->quote($type, "integer") . + " AND user_id = " . $ilDB->quote($user_id, "integer") . + " AND id = " . $ilDB->quote($id, "integer") . + " AND activated = " . $ilDB->quote(1, "integer")); + + return (bool) $ilDB->numRows($set); + } + + /** + * Is opt out (disable notification) allowed? + * + * @param int $obj_id + * @return bool + */ + public static function hasOptOut($obj_id) + { + include_once("./Services/Notification/classes/class.ilObjNotificationSettings.php"); + $setting = new ilObjNotificationSettings($obj_id); + if ($setting->getMode() == ilObjNotificationSettings::MODE_DEF_ON_NO_OPT_OUT) { + return false; + } + return true; + } + + /** + * Get all users for given object + * + * @param int $type + * @param int $id + * @param int $page_id + * @param bool $ignore_threshold + * @return array + */ + public static function getNotificationsForObject($type, $id, $page_id = null, $ignore_threshold = false) + { + global $DIC; + + $ilDB = $DIC->database(); + $tree = $DIC->repositoryTree(); + + include_once("./Services/Notification/classes/class.ilObjNotificationSettings.php"); + + // currently done for blog + $recipients = array(); + $setting = new ilObjNotificationSettings($id); + if ($setting->getMode() != ilObjNotificationSettings::MODE_DEF_OFF_USER_ACTIVATION) { + foreach (ilObject::_getAllReferences($id) as $ref_id) { + $grp_ref_id = $tree->checkForParentType($ref_id, 'grp'); + if ($grp_ref_id > 0) { + include_once("./Modules/Group/classes/class.ilGroupParticipants.php"); + $p = ilGroupParticipants::_getInstanceByObjId(ilObject::_lookupObjectId($grp_ref_id)); + foreach ($p->getMembers() as $user_id) { + if (!in_array($user_id, $recipients)) { + $recipients[$user_id] = $user_id; + } + } + } + $crs_ref_id = $tree->checkForParentType($ref_id, 'crs'); + if ($crs_ref_id > 0) { + include_once("./Modules/Course/classes/class.ilCourseParticipants.php"); + $p = ilCourseParticipants::_getInstanceByObjId(ilObject::_lookupObjectId($crs_ref_id)); + foreach ($p->getMembers() as $user_id) { + if (!in_array($user_id, $recipients)) { + $recipients[$user_id] = $user_id; + } + } + } + } + } + + // remove all users that deactivated the feature + if ($setting->getMode() == ilObjNotificationSettings::MODE_DEF_ON_OPT_OUT) { + $sql = "SELECT user_id FROM notification" . + " WHERE type = " . $ilDB->quote($type, "integer") . + " AND id = " . $ilDB->quote($id, "integer") . + " AND activated = " . $ilDB->quote(0, "integer") . + " AND " . $ilDB->in("user_id", $recipients, false, "integer"); + $set = $ilDB->query($sql); + while ($rec = $ilDB->fetchAssoc($set)) { + unset($recipients[$rec["user_id"]]); + } + } + + // remove all users that got a mail + if ($setting->getMode() != ilObjNotificationSettings::MODE_DEF_OFF_USER_ACTIVATION && !$ignore_threshold) { + $sql = "SELECT user_id FROM notification" . + " WHERE type = " . $ilDB->quote($type, "integer") . + " AND id = " . $ilDB->quote($id, "integer") . + " AND activated = " . $ilDB->quote(1, "integer") . + " AND " . $ilDB->in("user_id", $recipients, false, "integer"); + $sql .= " AND (last_mail > " . $ilDB->quote(date( + "Y-m-d H:i:s", + strtotime("-" . self::THRESHOLD . "minutes") + ), "timestamp"); + if ($page_id) { + $sql .= " AND page_id = " . $ilDB->quote($page_id, "integer"); + } + $sql .= ")"; + + $set = $ilDB->query($sql); + while ($rec = $ilDB->fetchAssoc($set)) { + unset($recipients[$rec["user_id"]]); + } + } + + // get single subscriptions + if ($setting->getMode() != ilObjNotificationSettings::MODE_DEF_ON_NO_OPT_OUT) { + $sql = "SELECT user_id FROM notification" . + " WHERE type = " . $ilDB->quote($type, "integer") . + " AND id = " . $ilDB->quote($id, "integer") . + " AND activated = " . $ilDB->quote(1, "integer"); + if (!$ignore_threshold) { + $sql .= " AND (last_mail < " . $ilDB->quote(date( + "Y-m-d H:i:s", + strtotime("-" . self::THRESHOLD . "minutes") + ), "timestamp") . + " OR last_mail IS NULL"; + if ($page_id) { + $sql .= " OR page_id <> " . $ilDB->quote($page_id, "integer"); + } + $sql .= ")"; + } + $set = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($set)) { + $recipients[$row["user_id"]] = $row["user_id"]; + } + } + + return $recipients; + } + + /** + * Set notification status for object and user + * + * @param int $type + * @param int $user_id + * @param int $id + * @param bool $status + */ + public static function setNotification($type, $user_id, $id, $status = true) + { + global $DIC; + + $ilDB = $DIC->database(); + + $fields = array( + "type" => array("integer", $type), + "user_id" => array("integer", $user_id), + "id" => array("integer", $id) + ); + $ilDB->replace("notification", $fields, array("activated" => array("integer", (int) $status))); + } + + /** + * Update the last mail timestamp for given object and users + * + * @param int $type + * @param int $id + * @param array $user_ids + * @param int $page_id + */ + public static function updateNotificationTime($type, $id, array $user_ids, $page_id = false) + { + global $DIC; - $ilDB = $DIC->database(); + $ilDB = $DIC->database(); - $ilDB->query("DELETE FROM notification". - " WHERE user_id = ".$ilDB->quote($user_id, "integer")); - } -} + $sql = "UPDATE notification" . + " SET last_mail = " . $ilDB->quote(date("Y-m-d H:i:s"), "timestamp"); + + if ($page_id) { + $sql .= ", page_id = " . $ilDB->quote($page_id, "integer"); + } + + $sql .= " WHERE type = " . $ilDB->quote($type, "integer") . + " AND id = " . $ilDB->quote($id, "integer") . + " AND " . $ilDB->in("user_id", $user_ids, false, "integer"); + + $ilDB->query($sql); + } -?> \ No newline at end of file + /** + * Remove all notifications for given object + * + * @param int $type + * @param int $id + */ + public static function removeForObject($type, $id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $ilDB->query("DELETE FROM notification" . + " WHERE type = " . $ilDB->quote($type, "integer") . + " AND id = " . $ilDB->quote($id, "integer")); + } + + /** + * Remove all notifications for given user + * + * @param int $user_id + */ + public static function removeForUser($user_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $ilDB->query("DELETE FROM notification" . + " WHERE user_id = " . $ilDB->quote($user_id, "integer")); + } +} diff --git a/Services/Notification/classes/class.ilNotificationAppEventListener.php b/Services/Notification/classes/class.ilNotificationAppEventListener.php index c3b2ac00a79b2fbe9a34d55ed60bf4e4aa95a5b6..d1f6786a4545390fad89475b132bf5f297c088fe 100644 --- a/Services/Notification/classes/class.ilNotificationAppEventListener.php +++ b/Services/Notification/classes/class.ilNotificationAppEventListener.php @@ -14,35 +14,30 @@ include_once('./Services/EventHandling/interfaces/interface.ilAppEventListener.p */ class ilNotificationAppEventListener implements ilAppEventListener { - /** - * Handle events like create, update, delete - * - * @access public - * @param string $a_component component, e.g. "Modules/Forum" or "Services/User" - * @param string $a_event event e.g. "createUser", "updateUser", "deleteUser", ... - * @param array $a_parameter parameter array (assoc), array("name" => ..., "phone_office" => ...) * - * @static - */ - public static function handleEvent($a_component, $a_event, $a_parameter) - { - switch($a_component) - { - case 'Services/Object': - - switch ($a_event) - { - case 'delete': - if ($a_parameter['obj_id'] > 0) - { - include_once("./Services/Notification/classes/class.ilObjNotificationSettings.php"); - $set = new ilObjNotificationSettings($a_parameter['obj_id']); - $set->delete(); - break; - } - } - break; - } - } + /** + * Handle events like create, update, delete + * + * @access public + * @param string $a_component component, e.g. "Modules/Forum" or "Services/User" + * @param string $a_event event e.g. "createUser", "updateUser", "deleteUser", ... + * @param array $a_parameter parameter array (assoc), array("name" => ..., "phone_office" => ...) * + * @static + */ + public static function handleEvent($a_component, $a_event, $a_parameter) + { + switch ($a_component) { + case 'Services/Object': + switch ($a_event) { + case 'delete': + if ($a_parameter['obj_id'] > 0) { + include_once("./Services/Notification/classes/class.ilObjNotificationSettings.php"); + $set = new ilObjNotificationSettings($a_parameter['obj_id']); + $set->delete(); + break; + } + } + break; + } + } } -?> \ No newline at end of file diff --git a/Services/Notification/classes/class.ilObjNotificationSettings.php b/Services/Notification/classes/class.ilObjNotificationSettings.php index 90fca6bfb79045bc98913bc2a181cddeeb0d2cf0..860e8bf4fcad196bb0665cb8288082f37e18b9ec 100644 --- a/Services/Notification/classes/class.ilObjNotificationSettings.php +++ b/Services/Notification/classes/class.ilObjNotificationSettings.php @@ -11,99 +11,99 @@ */ class ilObjNotificationSettings { - const MODE_DEF_OFF_USER_ACTIVATION = 0; - const MODE_DEF_ON_OPT_OUT = 1; - const MODE_DEF_ON_NO_OPT_OUT = 2; - - /** - * @var int - */ - protected $obj_id; - - /** - * @var int - */ - protected $mode = 0; - - /** - * @var ilDB - */ - protected $db; - - /** - * Constructor - * - * @param int $a_obj_id object id - */ - function __construct($a_obj_id) - { - global $DIC; - - $this->obj_id = $a_obj_id; - $this->db = $DIC->database(); - $this->read(); - } - - /** - * Set mode - * - * @param $a_val - */ - function setMode($a_val) - { - $this->mode = $a_val; - } - - /** - * Get mode - * - * @return int mode - */ - function getMode() - { - return $this->mode; - } - - /** - * Save - */ - function save() - { - $db = $this->db; - - if ($this->obj_id > 0) - { - $db->replace("obj_noti_settings", - array("obj_id" => array("integer", $this->obj_id)), - array("noti_mode" => array("integer", (int) $this->getMode())) - ); - } - } - - /** - * Read - */ - function read() - { - $db = $this->db; - - $set = $db->query("SELECT * FROM obj_noti_settings ". - " WHERE obj_id = ".$db->quote($this->obj_id, "integer") - ); - $rec = $db->fetchAssoc($set); - $this->setMode((int) $rec["noti_mode"]); - } - - - /** - * Delete - */ - function delete() - { - $db = $this->db; - - $db->manipulate("DELETE FROM obj_noti_settings WHERE ". - " obj_id = ".$db->quote($this->obj_id, "integer")); - - } -} \ No newline at end of file + const MODE_DEF_OFF_USER_ACTIVATION = 0; + const MODE_DEF_ON_OPT_OUT = 1; + const MODE_DEF_ON_NO_OPT_OUT = 2; + + /** + * @var int + */ + protected $obj_id; + + /** + * @var int + */ + protected $mode = 0; + + /** + * @var ilDB + */ + protected $db; + + /** + * Constructor + * + * @param int $a_obj_id object id + */ + public function __construct($a_obj_id) + { + global $DIC; + + $this->obj_id = $a_obj_id; + $this->db = $DIC->database(); + $this->read(); + } + + /** + * Set mode + * + * @param $a_val + */ + public function setMode($a_val) + { + $this->mode = $a_val; + } + + /** + * Get mode + * + * @return int mode + */ + public function getMode() + { + return $this->mode; + } + + /** + * Save + */ + public function save() + { + $db = $this->db; + + if ($this->obj_id > 0) { + $db->replace( + "obj_noti_settings", + array("obj_id" => array("integer", $this->obj_id)), + array("noti_mode" => array("integer", (int) $this->getMode())) + ); + } + } + + /** + * Read + */ + public function read() + { + $db = $this->db; + + $set = $db->query( + "SELECT * FROM obj_noti_settings " . + " WHERE obj_id = " . $db->quote($this->obj_id, "integer") + ); + $rec = $db->fetchAssoc($set); + $this->setMode((int) $rec["noti_mode"]); + } + + + /** + * Delete + */ + public function delete() + { + $db = $this->db; + + $db->manipulate("DELETE FROM obj_noti_settings WHERE " . + " obj_id = " . $db->quote($this->obj_id, "integer")); + } +} diff --git a/Services/Notification/classes/class.ilObjNotificationSettingsGUI.php b/Services/Notification/classes/class.ilObjNotificationSettingsGUI.php index ec17872a659102e8eeb1c50784a4f14480b7f92f..04ffeda7e0fcc53f5f31f83702415ba4b4eb93cb 100644 --- a/Services/Notification/classes/class.ilObjNotificationSettingsGUI.php +++ b/Services/Notification/classes/class.ilObjNotificationSettingsGUI.php @@ -11,152 +11,140 @@ */ class ilObjNotificationSettingsGUI { - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var int - */ - protected $obj_id; - - /** - * Constructor - */ - public function __construct($a_ref_id) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - $this->ref_id = $a_ref_id; - $this->obj_id = ilObject::_lookupObjId($a_ref_id); - include_once("./Services/Notification/classes/class.ilObjNotificationSettings.php"); - $this->settings = new ilObjNotificationSettings($this->obj_id); - } - - /** - * Execute command - */ - public function executeCommand() - { - $ctrl = $this->ctrl; - - $next_class = $ctrl->getNextClass($this); - $cmd = $ctrl->getCmd("show"); - - switch ($next_class) - { - default: - if (in_array($cmd, array("show", "save"))) - { - $this->$cmd(); - } - } - } - - /** - * Show form - */ - protected function show() - { - $tpl = $this->tpl; - - $form = $this->initForm(); - $tpl->setContent($form->getHTML()); - } - - - /** - * Init settings form - * @return ilPropertyFormGUI - */ - protected function initForm() - { - $ctrl = $this->ctrl; - $lng = $this->lng; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - - $form->setFormAction($ctrl->getFormAction($this, 'save')); - $form->setTitle($lng->txt('obj_notification_settings')); - - $radio_grp = new ilRadioGroupInputGUI($lng->txt("obj_activation"),'notification_type'); - $radio_grp->setValue('0'); - - $opt_default = new ilRadioOption($lng->txt("obj_user_decides_notification"), '0'); - $opt_0 = new ilRadioOption($lng->txt("obj_settings_for_all_members"), '1'); - - $radio_grp->addOption($opt_default); - $radio_grp->addOption($opt_0); - - $chb_2 = new ilCheckboxInputGUI($lng->txt('obj_user_not_disable_not'), 'no_opt_out'); - $chb_2->setValue(1); - - $opt_0->addSubItem($chb_2); - $form->addItem($radio_grp); - - if ($this->settings->getMode() == ilObjNotificationSettings::MODE_DEF_ON_OPT_OUT) - { - $radio_grp->setValue('1'); - } - if ($this->settings->getMode() == ilObjNotificationSettings::MODE_DEF_ON_NO_OPT_OUT) - { - $radio_grp->setValue('1'); - $chb_2->setChecked(true); - } - - $form->addCommandButton("save", $lng->txt("save")); - - $form->setTitle($this->lng->txt("notifications")); - - return $form; - } - - /** - * Save - */ - protected function save() - { - $ctrl = $this->ctrl; - - $form = $this->initForm(); - if ($form->checkInput()) - { - $this->settings->setMode(ilObjNotificationSettings::MODE_DEF_OFF_USER_ACTIVATION); - if ($_POST['notification_type'] == "1") - { - if ((int) $form->getInput('no_opt_out')) - { - $this->settings->setMode(ilObjNotificationSettings::MODE_DEF_ON_NO_OPT_OUT); - } - else - { - $this->settings->setMode(ilObjNotificationSettings::MODE_DEF_ON_OPT_OUT); - } - } - $this->settings->save(); - ilUtil::sendSuccess($this->lng->txt('saved_successfully'), true); - $ctrl->redirect($this, "show"); - } - - $form->setValuesByPost(); - $this->show(); - } - + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var int + */ + protected $obj_id; + + /** + * Constructor + */ + public function __construct($a_ref_id) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + $this->ref_id = $a_ref_id; + $this->obj_id = ilObject::_lookupObjId($a_ref_id); + include_once("./Services/Notification/classes/class.ilObjNotificationSettings.php"); + $this->settings = new ilObjNotificationSettings($this->obj_id); + } + + /** + * Execute command + */ + public function executeCommand() + { + $ctrl = $this->ctrl; + + $next_class = $ctrl->getNextClass($this); + $cmd = $ctrl->getCmd("show"); + + switch ($next_class) { + default: + if (in_array($cmd, array("show", "save"))) { + $this->$cmd(); + } + } + } + + /** + * Show form + */ + protected function show() + { + $tpl = $this->tpl; + + $form = $this->initForm(); + $tpl->setContent($form->getHTML()); + } + + + /** + * Init settings form + * @return ilPropertyFormGUI + */ + protected function initForm() + { + $ctrl = $this->ctrl; + $lng = $this->lng; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + + $form->setFormAction($ctrl->getFormAction($this, 'save')); + $form->setTitle($lng->txt('obj_notification_settings')); + + $radio_grp = new ilRadioGroupInputGUI($lng->txt("obj_activation"), 'notification_type'); + $radio_grp->setValue('0'); + + $opt_default = new ilRadioOption($lng->txt("obj_user_decides_notification"), '0'); + $opt_0 = new ilRadioOption($lng->txt("obj_settings_for_all_members"), '1'); + + $radio_grp->addOption($opt_default); + $radio_grp->addOption($opt_0); + + $chb_2 = new ilCheckboxInputGUI($lng->txt('obj_user_not_disable_not'), 'no_opt_out'); + $chb_2->setValue(1); + + $opt_0->addSubItem($chb_2); + $form->addItem($radio_grp); + + if ($this->settings->getMode() == ilObjNotificationSettings::MODE_DEF_ON_OPT_OUT) { + $radio_grp->setValue('1'); + } + if ($this->settings->getMode() == ilObjNotificationSettings::MODE_DEF_ON_NO_OPT_OUT) { + $radio_grp->setValue('1'); + $chb_2->setChecked(true); + } + + $form->addCommandButton("save", $lng->txt("save")); + + $form->setTitle($this->lng->txt("notifications")); + + return $form; + } + + /** + * Save + */ + protected function save() + { + $ctrl = $this->ctrl; + + $form = $this->initForm(); + if ($form->checkInput()) { + $this->settings->setMode(ilObjNotificationSettings::MODE_DEF_OFF_USER_ACTIVATION); + if ($_POST['notification_type'] == "1") { + if ((int) $form->getInput('no_opt_out')) { + $this->settings->setMode(ilObjNotificationSettings::MODE_DEF_ON_NO_OPT_OUT); + } else { + $this->settings->setMode(ilObjNotificationSettings::MODE_DEF_ON_OPT_OUT); + } + } + $this->settings->save(); + ilUtil::sendSuccess($this->lng->txt('saved_successfully'), true); + $ctrl->redirect($this, "show"); + } + + $form->setValuesByPost(); + $this->show(); + } } - -?> \ No newline at end of file diff --git a/Services/Notification/classes/class.ilSystemNotification.php b/Services/Notification/classes/class.ilSystemNotification.php index 48bb9d5e42e5b3cb83a6c23c597c5bd4f1e3a0c5..79548b5887f74b815ec5a3f48c15c11bb9513b85 100644 --- a/Services/Notification/classes/class.ilSystemNotification.php +++ b/Services/Notification/classes/class.ilSystemNotification.php @@ -1,374 +1,332 @@ - - * $Id: class.ilObjExerciseGUI.php 24003 2010-05-26 14:35:42Z akill $ - * - * @ingroup ServicesNotification - */ -class ilSystemNotification extends ilMailNotification -{ - protected $subject_lang_id; // [string] - protected $subject_direct; // [string] - protected $introduction; // [string] - protected $introduction_direct; // [string] - protected $task; // [string] - protected $reason; // [string] - protected $additional; // [array] - protected $goto_caption; // [string] - protected $changed_by; // [int] - protected $all_ref_ids; // [array] - - /** - * Set subject lang id - * - * @param string $a_lang_id - */ - public function setSubjectLangId($a_lang_id) - { - $this->subject_lang_id = (string)$a_lang_id; - } - - /** - * Set subject text - * - * @param string $a_text - */ - public function setSubjectDirect($a_text) - { - $this->subject_direct = trim($a_text); - } - - /** - * Set introduction lang id - * - * @param string $a_lang_id - */ - public function setIntroductionLangId($a_lang_id) - { - $this->introduction = (string)$a_lang_id; - } - - /** - * Set introduction text - * - * @param string $a_text - */ - public function setIntroductionDirect($a_text) - { - $this->introduction_direct = trim($a_text); - } - - /** - * Set task lang id - * - * @param string $a_lang_id - */ - public function setTaskLangId($a_lang_id) - { - $this->task = (string)$a_lang_id; - } - - /** - * Set reason lang id - * - * @param string $a_lang_id - */ - public function setReasonLangId($a_lang_id) - { - $this->reason = (string)$a_lang_id; - } - - /** - * Set goto lang id - * - * @param string $a_lang_id - */ - public function setGotoLangId($a_lang_id) - { - $this->goto_caption = (string)$a_lang_id; - } - - /** - * Set changed by user id - * - * @param int $a_id - */ - public function setChangedByUserId($a_id) - { - $this->changed_by = (int)$a_id; - - include_once "Services/User/classes/class.ilUserUtil.php"; - } - - /** - * Add additional information - * - * @param string $a_lang_id - * @param mixed $a_value - * @param bool $a_multiline - * @param bool $a_lang_direct - */ - public function addAdditionalInfo($a_lang_id, $a_value, $a_multiline = false, $a_lang_direct = false) - { - $this->additional[$a_lang_id] = array(trim($a_value), (bool)$a_multiline, (bool)$a_lang_direct); - } - - /** - * Send notification(s) - * - * @param array $a_user_ids - * @param string $a_goto_additional - * @param string $a_permission - * @return array recipient ids - */ - public function sendMail(array $a_user_ids, $a_goto_additional = null, $a_permission = "read") - { - $this->all_ref_ids = null; - - // prepare object related info - if($this->getObjId()) - { - if(!$this->getRefId()) - { - // try to find ref_id(s) - if(!$this->is_in_wsp) - { - $ref_ids = ilObject::_getAllReferences($this->getObjId()); - if(sizeof($ref_ids) == 1) - { - $this->ref_id = array_shift($ref_ids); - } - else - { - $this->all_ref_ids = $ref_ids; - } - } - } - else if($this->is_in_wsp) // #11680 - { - $this->ref_id = $this->wsp_tree->lookupNodeId($this->getObjId()); - } - - // default values - if(!$this->goto_caption) - { - $this->goto_caption = "url"; - } - } - - $recipient_ids = array(); - foreach(array_unique($a_user_ids) as $user_id) - { - // author of change should not get notification - if($this->changed_by == $user_id) - { - continue; - } - if($this->composeAndSendMail($user_id, $a_goto_additional, $a_permission)) - { - $recipient_ids[] = $user_id; - } - } - - return $recipient_ids; - } - - /** - * Compose notification to single recipient - * - * @param mixed $a_rcp - * @param string $a_goto_additional - * @param string $a_permission - * @param bool $a_append_signature_direct - * @return bool - */ - public function compose($a_user_id, $a_goto_additional = null, $a_permission = "read", $a_append_signature_direct = false) - { - $this->initLanguage($a_user_id); - $this->initMail(); - - if($this->subject_direct) - { - $this->setSubject($this->subject_direct); - } - else { - $this->setSubject( - sprintf($this->getLanguageText($this->subject_lang_id), $this->getObjectTitle(true)) - ); - } - - $this->setBody(ilMail::getSalutation($a_user_id, $this->getLanguage())); - $this->appendBody("\n\n"); - - if($this->introduction) - { - $this->appendBody($this->getLanguageText($this->introduction)); - $this->appendBody("\n\n"); - } - - if($this->introduction_direct) - { - $this->appendBody($this->introduction_direct); - $this->appendBody("\n\n"); - } - - if($this->task) - { - $this->appendBody($this->getLanguageText($this->task)); - $this->appendBody("\n\n"); - } - - // details table - if($this->getObjId()) - { - $this->appendBody($this->getLanguageText("obj_".$this->getObjType()).": ". - $this->getObjectTitle()."\n"); - } - if(is_array($this->additional)) - { - foreach($this->additional as $lang_id => $item) - { - $caption = ""; - if($lang_id) - { - $caption = (!$item[2]) - ? $this->getLanguageText($lang_id) - : $lang_id; - } - if(!$item[1]) - { - if($caption) - { - $caption .= ": "; - } - $this->appendBody($caption.$item[0]."\n"); - } - else - { - if($caption) - { - $caption .= "\n"; - } - $this->appendBody("\n".$caption. - $this->getBlockBorder(). - $item[0]."\n". - $this->getBlockBorder()."\n"); - } - } - } - $this->body = trim($this->body); - $this->appendBody("\n\n"); - - if($this->changed_by) - { - $this->appendBody($this->getLanguageText("system_notification_installation_changed_by").": ". - ilUserUtil::getNamePresentation($this->changed_by)); - $this->appendBody("\n\n"); - } - - if($this->getObjId()) - { - // try to find accessible ref_id - if(!$this->getRefId() && $this->all_ref_ids) - { - $find_ref_id = true; - foreach($this->all_ref_ids as $ref_id) - { - if($this->isRefIdAccessible($a_user_id, $ref_id, $a_permission)) - { - $this->ref_id = $ref_id; - break; - } - } - } - - // check if initially given ref_id is accessible for current recipient - if($this->getRefId() && - !$find_ref_id && - !$this->isRefIdAccessible($a_user_id, $this->getRefId(), $a_permission)) - { - return false; - } - - $goto = $this->createPermanentLink(array(), $a_goto_additional); - if($goto) - { - $this->appendBody($this->getLanguageText($this->goto_caption).": ". - $goto); - $this->appendBody("\n\n"); - } - - if($find_ref_id) - { - $this->ref_id = null; - } - } - - if($this->reason) - { - $this->appendBody($this->getLanguageText($this->reason)); - $this->appendBody("\n\n"); - } - - $this->appendBody(ilMail::_getAutoGeneratedMessageString($this->language)); - - // signature will append new lines - $this->body = trim($this->body); - - if(!$a_append_signature_direct) - { - $this->getMail()->appendInstallationSignature(true); - } - else - { - $this->appendBody(ilMail::_getInstallationSignature()); - } - - return true; - } - - /** - * Send notification to single recipient - * - * @param mixed $a_rcp - * @param string $a_goto_additional - * @param string $a_permission - * @return bool - */ - protected function composeAndSendMail($a_user_id, $a_goto_additional = null, $a_permission = "read") - { - if($this->compose($a_user_id, $a_goto_additional, $a_permission)) - { - parent::sendMail(array($a_user_id), array('system'), is_numeric($a_user_id)); - return true; - } - return false; - } - - /** - * Compose notification to single recipient - * - * @param mixed $a_user_id - * @param string $a_goto_additional - * @param string $a_permission - * @param bool $a_append_signature_direct - * @return string - */ - public function composeAndGetMessage($a_user_id, $a_goto_additional = null, $a_permission = "read", $a_append_signature_direct = false) - { - if($this->compose($a_user_id, $a_goto_additional, $a_permission, $a_append_signature_direct)) - { - return $this->body; - } - } -} - -?> \ No newline at end of file + + * $Id: class.ilObjExerciseGUI.php 24003 2010-05-26 14:35:42Z akill $ + * + * @ingroup ServicesNotification + */ +class ilSystemNotification extends ilMailNotification +{ + protected $subject_lang_id; // [string] + protected $subject_direct; // [string] + protected $introduction; // [string] + protected $introduction_direct; // [string] + protected $task; // [string] + protected $reason; // [string] + protected $additional; // [array] + protected $goto_caption; // [string] + protected $changed_by; // [int] + protected $all_ref_ids; // [array] + + /** + * Set subject lang id + * + * @param string $a_lang_id + */ + public function setSubjectLangId($a_lang_id) + { + $this->subject_lang_id = (string) $a_lang_id; + } + + /** + * Set subject text + * + * @param string $a_text + */ + public function setSubjectDirect($a_text) + { + $this->subject_direct = trim($a_text); + } + + /** + * Set introduction lang id + * + * @param string $a_lang_id + */ + public function setIntroductionLangId($a_lang_id) + { + $this->introduction = (string) $a_lang_id; + } + + /** + * Set introduction text + * + * @param string $a_text + */ + public function setIntroductionDirect($a_text) + { + $this->introduction_direct = trim($a_text); + } + + /** + * Set task lang id + * + * @param string $a_lang_id + */ + public function setTaskLangId($a_lang_id) + { + $this->task = (string) $a_lang_id; + } + + /** + * Set reason lang id + * + * @param string $a_lang_id + */ + public function setReasonLangId($a_lang_id) + { + $this->reason = (string) $a_lang_id; + } + + /** + * Set goto lang id + * + * @param string $a_lang_id + */ + public function setGotoLangId($a_lang_id) + { + $this->goto_caption = (string) $a_lang_id; + } + + /** + * Set changed by user id + * + * @param int $a_id + */ + public function setChangedByUserId($a_id) + { + $this->changed_by = (int) $a_id; + + include_once "Services/User/classes/class.ilUserUtil.php"; + } + + /** + * Add additional information + * + * @param string $a_lang_id + * @param mixed $a_value + * @param bool $a_multiline + * @param bool $a_lang_direct + */ + public function addAdditionalInfo($a_lang_id, $a_value, $a_multiline = false, $a_lang_direct = false) + { + $this->additional[$a_lang_id] = array(trim($a_value), (bool) $a_multiline, (bool) $a_lang_direct); + } + + /** + * Send notification(s) + * + * @param array $a_user_ids + * @param string $a_goto_additional + * @param string $a_permission + * @return array recipient ids + */ + public function sendMail(array $a_user_ids, $a_goto_additional = null, $a_permission = "read") + { + $this->all_ref_ids = null; + + // prepare object related info + if ($this->getObjId()) { + if (!$this->getRefId()) { + // try to find ref_id(s) + if (!$this->is_in_wsp) { + $ref_ids = ilObject::_getAllReferences($this->getObjId()); + if (sizeof($ref_ids) == 1) { + $this->ref_id = array_shift($ref_ids); + } else { + $this->all_ref_ids = $ref_ids; + } + } + } elseif ($this->is_in_wsp) { // #11680 + $this->ref_id = $this->wsp_tree->lookupNodeId($this->getObjId()); + } + + // default values + if (!$this->goto_caption) { + $this->goto_caption = "url"; + } + } + + $recipient_ids = array(); + foreach (array_unique($a_user_ids) as $user_id) { + // author of change should not get notification + if ($this->changed_by == $user_id) { + continue; + } + if ($this->composeAndSendMail($user_id, $a_goto_additional, $a_permission)) { + $recipient_ids[] = $user_id; + } + } + + return $recipient_ids; + } + + /** + * Compose notification to single recipient + * + * @param mixed $a_rcp + * @param string $a_goto_additional + * @param string $a_permission + * @param bool $a_append_signature_direct + * @return bool + */ + public function compose($a_user_id, $a_goto_additional = null, $a_permission = "read", $a_append_signature_direct = false) + { + $this->initLanguage($a_user_id); + $this->initMail(); + + if ($this->subject_direct) { + $this->setSubject($this->subject_direct); + } else { + $this->setSubject( + sprintf($this->getLanguageText($this->subject_lang_id), $this->getObjectTitle(true)) + ); + } + + $this->setBody(ilMail::getSalutation($a_user_id, $this->getLanguage())); + $this->appendBody("\n\n"); + + if ($this->introduction) { + $this->appendBody($this->getLanguageText($this->introduction)); + $this->appendBody("\n\n"); + } + + if ($this->introduction_direct) { + $this->appendBody($this->introduction_direct); + $this->appendBody("\n\n"); + } + + if ($this->task) { + $this->appendBody($this->getLanguageText($this->task)); + $this->appendBody("\n\n"); + } + + // details table + if ($this->getObjId()) { + $this->appendBody($this->getLanguageText("obj_" . $this->getObjType()) . ": " . + $this->getObjectTitle() . "\n"); + } + if (is_array($this->additional)) { + foreach ($this->additional as $lang_id => $item) { + $caption = ""; + if ($lang_id) { + $caption = (!$item[2]) + ? $this->getLanguageText($lang_id) + : $lang_id; + } + if (!$item[1]) { + if ($caption) { + $caption .= ": "; + } + $this->appendBody($caption . $item[0] . "\n"); + } else { + if ($caption) { + $caption .= "\n"; + } + $this->appendBody("\n" . $caption . + $this->getBlockBorder() . + $item[0] . "\n" . + $this->getBlockBorder() . "\n"); + } + } + } + $this->body = trim($this->body); + $this->appendBody("\n\n"); + + if ($this->changed_by) { + $this->appendBody($this->getLanguageText("system_notification_installation_changed_by") . ": " . + ilUserUtil::getNamePresentation($this->changed_by)); + $this->appendBody("\n\n"); + } + + if ($this->getObjId()) { + // try to find accessible ref_id + if (!$this->getRefId() && $this->all_ref_ids) { + $find_ref_id = true; + foreach ($this->all_ref_ids as $ref_id) { + if ($this->isRefIdAccessible($a_user_id, $ref_id, $a_permission)) { + $this->ref_id = $ref_id; + break; + } + } + } + + // check if initially given ref_id is accessible for current recipient + if ($this->getRefId() && + !$find_ref_id && + !$this->isRefIdAccessible($a_user_id, $this->getRefId(), $a_permission)) { + return false; + } + + $goto = $this->createPermanentLink(array(), $a_goto_additional); + if ($goto) { + $this->appendBody($this->getLanguageText($this->goto_caption) . ": " . + $goto); + $this->appendBody("\n\n"); + } + + if ($find_ref_id) { + $this->ref_id = null; + } + } + + if ($this->reason) { + $this->appendBody($this->getLanguageText($this->reason)); + $this->appendBody("\n\n"); + } + + $this->appendBody(ilMail::_getAutoGeneratedMessageString($this->language)); + + // signature will append new lines + $this->body = trim($this->body); + + if (!$a_append_signature_direct) { + $this->getMail()->appendInstallationSignature(true); + } else { + $this->appendBody(ilMail::_getInstallationSignature()); + } + + return true; + } + + /** + * Send notification to single recipient + * + * @param mixed $a_rcp + * @param string $a_goto_additional + * @param string $a_permission + * @return bool + */ + protected function composeAndSendMail($a_user_id, $a_goto_additional = null, $a_permission = "read") + { + if ($this->compose($a_user_id, $a_goto_additional, $a_permission)) { + parent::sendMail(array($a_user_id), array('system'), is_numeric($a_user_id)); + return true; + } + return false; + } + + /** + * Compose notification to single recipient + * + * @param mixed $a_user_id + * @param string $a_goto_additional + * @param string $a_permission + * @param bool $a_append_signature_direct + * @return string + */ + public function composeAndGetMessage($a_user_id, $a_goto_additional = null, $a_permission = "read", $a_append_signature_direct = false) + { + if ($this->compose($a_user_id, $a_goto_additional, $a_permission, $a_append_signature_direct)) { + return $this->body; + } + } +} diff --git a/Services/Object/CommonSettings/TileImage/classes/class.ilObjectTileImage.php b/Services/Object/CommonSettings/TileImage/classes/class.ilObjectTileImage.php index 4770a3de6cd0528ad57a16b8e50a51f39f8a706b..c07e5fb4c558a6383417cdbcb6c9ab3ddcd8d162 100644 --- a/Services/Object/CommonSettings/TileImage/classes/class.ilObjectTileImage.php +++ b/Services/Object/CommonSettings/TileImage/classes/class.ilObjectTileImage.php @@ -10,226 +10,223 @@ */ class ilObjectTileImage implements ilObjectTileImageInterface { - /** - * @var ilObjectService - */ - protected $service; - - /** - * @var int - */ - protected $obj_id; - - /** - * @var \ILIAS\Filesystem\Filesystem - */ - protected $web; - - /** - * @var \ILIAS\FileUpload\FileUpload - */ - protected $upload; - - /** - * @var string file extension - */ - protected $ext; - - /** - * Constructor - */ - public function __construct(ilObjectService $service, int $obj_id) - { - $this->service = $service; - $this->obj_id = $obj_id; - $this->web = $service->filesystem()->web(); - $this->upload = $service->upload(); - $this->ext = ilContainer::_lookupContainerSetting($obj_id, 'tile_image'); - } - - /** - * @inheritdoc - */ - public function getExtension(): string - { - return $this->ext; - } - - /** - * @inheritdoc - */ - public function copy(int $target_obj_id) - { - if (!$this->exists()) { - ilContainer::_deleteContainerSettings($target_obj_id, 'tile_image'); - return; - } - - try { - $this->web->copy( - $this->getRelativePath(), - preg_replace( - '/(' . "tile_image_" . ')(\d*)\/(.*)$/', - '${1}' . $target_obj_id . '/${3}', - $this->getRelativePath() - ) - ); - - ilContainer::_writeContainerSetting($target_obj_id, 'tile_image', $this->getExtension()); - } catch (\Exception $e) { - ilContainer::_deleteContainerSettings($target_obj_id, 'tile_image'); - } - } - - /** - * @inheritdoc - */ - public function delete() - { - if ($this->exists()) { - try { - $this->web->deleteDir($this->getRelativeDirectory()); - } catch (\Exception $e) { - } - } - - ilContainer::_deleteContainerSettings($this->obj_id, 'tile_image'); - } - - /** - * @inheritdoc - */ - public function saveFromHttpRequest(string $tmpname) - { - $this->createDirectory(); - - // remove old file - $file_name = $this->getRelativePath(); - if ($this->web->has($file_name)) { - $this->web->delete($file_name); - } - - if ($this->upload->hasUploads()) { - if (!$this->upload->hasBeenProcessed()) - { - $this->upload->process(); - } - - /** @var \ILIAS\FileUpload\DTO\UploadResult $result */ - $results = $this->upload->getResults(); - if (isset($results[$tmpname])) - { - $result = $results[$tmpname]; - $this->ext = pathinfo($result->getName(), PATHINFO_EXTENSION); - $file_name = $this->getRelativePath(); - if ($result->getStatus() == \ILIAS\FileUpload\DTO\ProcessingStatus::OK) - { - $this->upload->moveOneFileTo( - $result, - $this->getRelativeDirectory(), - \ILIAS\FileUpload\Location::WEB, - $this->getFileName(), - true - ); - - - $fullpath = CLIENT_WEB_DIR . "/" . $this->getRelativeDirectory() . "/" . $this->getFileName(); - list($width, $height, $type, $attr) = getimagesize($fullpath); - $min = min($width, $height); - ilUtil::execConvert($fullpath . "[0] -geometry " . $min . "x" . $min . "^ -gravity center -extent " . $min . "x" . $min . " " . $fullpath); - } - } - } - $this->persistImageState($file_name); - } - - /** - * @param string $filename - */ - protected function persistImageState($filename) - { - $ext = pathinfo($filename, PATHINFO_EXTENSION); - - if ($this->web->has($filename)) { - ilContainer::_writeContainerSetting($this->obj_id, 'tile_image', $ext); - } else { - ilContainer::_deleteContainerSettings($this->obj_id, 'tile_image'); - } - } - - /** - * @throws \ILIAS\Filesystem\Exception\IOException - */ - protected function createDirectory() - { - $this->web->createDir($this->getRelativeDirectory()); - - /* - - $rel_directory = $this->getRelDirectory(); - - if (!$this->web->has(dirname($rel_directory))) { - $this->web->createDir(dirname($rel_directory)); - } - - if (!$this->web->has($rel_directory)) { - $this->web->createDir($rel_directory); - }*/ - } - - /** - * @return string - */ - public function getRelativeDirectory() - { - return implode(DIRECTORY_SEPARATOR, [ - "obj_data", - "tile_image", - "tile_image_".$this->obj_id - ]); - } - - /** - * @return string - */ - protected function getFileName() - { - return 'tile_image.'.$this->getExtension(); - } - - /** - * @return string - */ - protected function getRelativePath() - { - return implode(DIRECTORY_SEPARATOR, [ - $this->getRelativeDirectory(), - $this->getFileName() - ]); - } - - /** - * @inheritdoc - */ - public function exists(): bool - { - if (!\ilContainer::_lookupContainerSetting($this->obj_id, 'tile_image', 0)) { - return false; - } - return $this->web->has($this->getRelativePath()); - } - - /** - * @inheritdoc - */ - public function getFullPath(): string - { - // TODO: Currently there is no option to get the relative base directory of a filesystem - return implode(DIRECTORY_SEPARATOR, [ + /** + * @var ilObjectService + */ + protected $service; + + /** + * @var int + */ + protected $obj_id; + + /** + * @var \ILIAS\Filesystem\Filesystem + */ + protected $web; + + /** + * @var \ILIAS\FileUpload\FileUpload + */ + protected $upload; + + /** + * @var string file extension + */ + protected $ext; + + /** + * Constructor + */ + public function __construct(ilObjectService $service, int $obj_id) + { + $this->service = $service; + $this->obj_id = $obj_id; + $this->web = $service->filesystem()->web(); + $this->upload = $service->upload(); + $this->ext = ilContainer::_lookupContainerSetting($obj_id, 'tile_image'); + } + + /** + * @inheritdoc + */ + public function getExtension() : string + { + return $this->ext; + } + + /** + * @inheritdoc + */ + public function copy(int $target_obj_id) + { + if (!$this->exists()) { + ilContainer::_deleteContainerSettings($target_obj_id, 'tile_image'); + return; + } + + try { + $this->web->copy( + $this->getRelativePath(), + preg_replace( + '/(' . "tile_image_" . ')(\d*)\/(.*)$/', + '${1}' . $target_obj_id . '/${3}', + $this->getRelativePath() + ) + ); + + ilContainer::_writeContainerSetting($target_obj_id, 'tile_image', $this->getExtension()); + } catch (\Exception $e) { + ilContainer::_deleteContainerSettings($target_obj_id, 'tile_image'); + } + } + + /** + * @inheritdoc + */ + public function delete() + { + if ($this->exists()) { + try { + $this->web->deleteDir($this->getRelativeDirectory()); + } catch (\Exception $e) { + } + } + + ilContainer::_deleteContainerSettings($this->obj_id, 'tile_image'); + } + + /** + * @inheritdoc + */ + public function saveFromHttpRequest(string $tmpname) + { + $this->createDirectory(); + + // remove old file + $file_name = $this->getRelativePath(); + if ($this->web->has($file_name)) { + $this->web->delete($file_name); + } + + if ($this->upload->hasUploads()) { + if (!$this->upload->hasBeenProcessed()) { + $this->upload->process(); + } + + /** @var \ILIAS\FileUpload\DTO\UploadResult $result */ + $results = $this->upload->getResults(); + if (isset($results[$tmpname])) { + $result = $results[$tmpname]; + $this->ext = pathinfo($result->getName(), PATHINFO_EXTENSION); + $file_name = $this->getRelativePath(); + if ($result->getStatus() == \ILIAS\FileUpload\DTO\ProcessingStatus::OK) { + $this->upload->moveOneFileTo( + $result, + $this->getRelativeDirectory(), + \ILIAS\FileUpload\Location::WEB, + $this->getFileName(), + true + ); + + + $fullpath = CLIENT_WEB_DIR . "/" . $this->getRelativeDirectory() . "/" . $this->getFileName(); + list($width, $height, $type, $attr) = getimagesize($fullpath); + $min = min($width, $height); + ilUtil::execConvert($fullpath . "[0] -geometry " . $min . "x" . $min . "^ -gravity center -extent " . $min . "x" . $min . " " . $fullpath); + } + } + } + $this->persistImageState($file_name); + } + + /** + * @param string $filename + */ + protected function persistImageState($filename) + { + $ext = pathinfo($filename, PATHINFO_EXTENSION); + + if ($this->web->has($filename)) { + ilContainer::_writeContainerSetting($this->obj_id, 'tile_image', $ext); + } else { + ilContainer::_deleteContainerSettings($this->obj_id, 'tile_image'); + } + } + + /** + * @throws \ILIAS\Filesystem\Exception\IOException + */ + protected function createDirectory() + { + $this->web->createDir($this->getRelativeDirectory()); + + /* + + $rel_directory = $this->getRelDirectory(); + + if (!$this->web->has(dirname($rel_directory))) { + $this->web->createDir(dirname($rel_directory)); + } + + if (!$this->web->has($rel_directory)) { + $this->web->createDir($rel_directory); + }*/ + } + + /** + * @return string + */ + public function getRelativeDirectory() + { + return implode(DIRECTORY_SEPARATOR, [ + "obj_data", + "tile_image", + "tile_image_" . $this->obj_id + ]); + } + + /** + * @return string + */ + protected function getFileName() + { + return 'tile_image.' . $this->getExtension(); + } + + /** + * @return string + */ + protected function getRelativePath() + { + return implode(DIRECTORY_SEPARATOR, [ + $this->getRelativeDirectory(), + $this->getFileName() + ]); + } + + /** + * @inheritdoc + */ + public function exists() : bool + { + if (!\ilContainer::_lookupContainerSetting($this->obj_id, 'tile_image', 0)) { + return false; + } + return $this->web->has($this->getRelativePath()); + } + + /** + * @inheritdoc + */ + public function getFullPath() : string + { + // TODO: Currently there is no option to get the relative base directory of a filesystem + return implode(DIRECTORY_SEPARATOR, [ \ilUtil::getWebspaceDir(), $this->getRelativePath() ]); - } + } /** * @param $source_dir @@ -247,6 +244,4 @@ class ilObjectTileImage implements ilObjectTileImageInterface ilUtil::rCopy($source_dir, $target_dir); ilContainer::_writeContainerSetting($this->obj_id, 'tile_image', $ext); } - - -} \ No newline at end of file +} diff --git a/Services/Object/CommonSettings/TileImage/classes/class.ilObjectTileImageFactory.php b/Services/Object/CommonSettings/TileImage/classes/class.ilObjectTileImageFactory.php index 1b390885d2cc0b51c7f8cb41d6e097fb0f066c1a..4dc9d0858005f75e6eca04cb2170d7a4e0dd3556 100644 --- a/Services/Object/CommonSettings/TileImage/classes/class.ilObjectTileImageFactory.php +++ b/Services/Object/CommonSettings/TileImage/classes/class.ilObjectTileImageFactory.php @@ -10,33 +10,33 @@ */ class ilObjectTileImageFactory implements ilObjectTileImageFactoryInterface { - /** - * @var ilObjectService - */ - protected $service; + /** + * @var ilObjectService + */ + protected $service; - /** - * Constructor - * @param ilObjectService $service - */ - public function __construct(ilObjectService $service) - { - $this->service = $service; - } + /** + * Constructor + * @param ilObjectService $service + */ + public function __construct(ilObjectService $service) + { + $this->service = $service; + } - /** - * @inheritdoc - */ - public function getSupportedFileExtensions(): array - { - return ["png", "jpg", "jpeg"]; - } + /** + * @inheritdoc + */ + public function getSupportedFileExtensions() : array + { + return ["png", "jpg", "jpeg"]; + } - /** - * @inheritdoc - */ - public function getByObjId(int $obj_id): ilObjectTileImage - { - return new \ilObjectTileImage($this->service, $obj_id); - } -} \ No newline at end of file + /** + * @inheritdoc + */ + public function getByObjId(int $obj_id) : ilObjectTileImage + { + return new \ilObjectTileImage($this->service, $obj_id); + } +} diff --git a/Services/Object/CommonSettings/TileImage/interfaces/interface.ilObjectTileImageFactoryInterface.php b/Services/Object/CommonSettings/TileImage/interfaces/interface.ilObjectTileImageFactoryInterface.php index 777f09b364e352dee446d5234666433133b739c3..3c77d035323f05b3873c4ded41e91a4c159d6440 100644 --- a/Services/Object/CommonSettings/TileImage/interfaces/interface.ilObjectTileImageFactoryInterface.php +++ b/Services/Object/CommonSettings/TileImage/interfaces/interface.ilObjectTileImageFactoryInterface.php @@ -10,18 +10,18 @@ */ interface ilObjectTileImageFactoryInterface { - /** - * Get supported file extensions - * - * @return string[] - */ - public function getSupportedFileExtensions(): array; + /** + * Get supported file extensions + * + * @return string[] + */ + public function getSupportedFileExtensions() : array; - /** - * Get tile image by object id - * - * @param int $objId - * @return ilObjectTileImage - */ - public function getByObjId(int $obj_id): ilObjectTileImage; -} \ No newline at end of file + /** + * Get tile image by object id + * + * @param int $objId + * @return ilObjectTileImage + */ + public function getByObjId(int $obj_id) : ilObjectTileImage; +} diff --git a/Services/Object/CommonSettings/TileImage/interfaces/interface.ilObjectTileImageInterface.php b/Services/Object/CommonSettings/TileImage/interfaces/interface.ilObjectTileImageInterface.php index 204cfffd43030b35237a4d6f1fbadc3e0f3d8c38..2514b6da22bc29fef9b52fda7907e34744447aeb 100644 --- a/Services/Object/CommonSettings/TileImage/interfaces/interface.ilObjectTileImageInterface.php +++ b/Services/Object/CommonSettings/TileImage/interfaces/interface.ilObjectTileImageInterface.php @@ -10,45 +10,44 @@ */ interface ilObjectTileImageInterface { - /** - * Get extenstion - * - * @return string - */ - public function getExtension(): string; - - /** - * Copy tile image to repository object - * @param int $target_obj_id - */ - public function copy(int $target_obj_id); - - /** - * Delete tile image - */ - public function delete(); - - /** - * Save image from request - * - * @throws \ILIAS\FileUpload\Exception\IllegalStateException - * @throws \ILIAS\Filesystem\Exception\FileNotFoundException - * @throws \ILIAS\Filesystem\Exception\IOException - */ - public function saveFromHttpRequest(string $tmpname); - - /** - * Does tile image file exist? - * - * @return bool - */ - public function exists(): bool; - - /** - * Get full path of the tile image file - * - * @return string - */ - public function getFullPath(): string; - -} \ No newline at end of file + /** + * Get extenstion + * + * @return string + */ + public function getExtension() : string; + + /** + * Copy tile image to repository object + * @param int $target_obj_id + */ + public function copy(int $target_obj_id); + + /** + * Delete tile image + */ + public function delete(); + + /** + * Save image from request + * + * @throws \ILIAS\FileUpload\Exception\IllegalStateException + * @throws \ILIAS\Filesystem\Exception\FileNotFoundException + * @throws \ILIAS\Filesystem\Exception\IOException + */ + public function saveFromHttpRequest(string $tmpname); + + /** + * Does tile image file exist? + * + * @return bool + */ + public function exists() : bool; + + /** + * Get full path of the tile image file + * + * @return string + */ + public function getFullPath() : string; +} diff --git a/Services/Object/CommonSettings/classes/class.ilObjectCommonSettings.php b/Services/Object/CommonSettings/classes/class.ilObjectCommonSettings.php index 0b35ea4648b07e5488b9d379748f0e375d6b81f3..278d9dfe28667b0daf78500486fe1924c17cd941 100644 --- a/Services/Object/CommonSettings/classes/class.ilObjectCommonSettings.php +++ b/Services/Object/CommonSettings/classes/class.ilObjectCommonSettings.php @@ -6,36 +6,36 @@ * Common settings for objects * * @author @leifos.de - * @ingroup + * @ingroup */ class ilObjectCommonSettings implements ilObjectCommonSettingsInterface { - /** - * @var ilObjectService - */ - protected $service; + /** + * @var ilObjectService + */ + protected $service; - /** - * Constructor - */ - public function __construct(ilObjectService $service) - { - $this->service = $service; - } + /** + * Constructor + */ + public function __construct(ilObjectService $service) + { + $this->service = $service; + } - /** - * @inheritdoc - */ - public function tileImage(): ilObjectTileImageFactory - { - return new ilObjectTileImageFactory($this->service); - } + /** + * @inheritdoc + */ + public function tileImage() : ilObjectTileImageFactory + { + return new ilObjectTileImageFactory($this->service); + } - /** - * @inheritdoc - */ - public function legacyForm(ilPropertyFormGUI $form, ilObject $object): ilObjectCommonSettingFormAdapter - { - return new ilObjectCommonSettingFormAdapter($this->service, $object, $form); - } -} \ No newline at end of file + /** + * @inheritdoc + */ + public function legacyForm(ilPropertyFormGUI $form, ilObject $object) : ilObjectCommonSettingFormAdapter + { + return new ilObjectCommonSettingFormAdapter($this->service, $object, $form); + } +} diff --git a/Services/Object/CommonSettings/classes/class.ilObjectCommonSettingsFormAdapter.php b/Services/Object/CommonSettings/classes/class.ilObjectCommonSettingsFormAdapter.php index 5dd94519573dbb128e01311e85a0704ba3688862..58359a55abdd16d85ccdf695bbcbdabf99fd6f7b 100644 --- a/Services/Object/CommonSettings/classes/class.ilObjectCommonSettingsFormAdapter.php +++ b/Services/Object/CommonSettings/classes/class.ilObjectCommonSettingsFormAdapter.php @@ -10,182 +10,176 @@ */ class ilObjectCommonSettingFormAdapter implements ilObjectCommonSettingFormAdapterInterface { - /** - * @var ilObjectService - */ - protected $service; - - /** - * @var ilPropertyFormGUI - */ - protected $legacy_form; - - /** - * @var ilObject - */ - protected $object; - - /** - * Constructor - */ - public function __construct(ilObjectService $service, ilObject $object, ilPropertyFormGUI $legacy_form = null) - { - $this->service = $service; - $this->legacy_form = $legacy_form; - $this->object = $object; - } - - /** - * @inheritdoc - */ - public function addIcon(): ilPropertyFormGUI - { - global $DIC; - - if ($this->service->settings()->get('custom_icons')) - { - if (!is_null($this->legacy_form)) - { - // we do not clone for legacy forms, since initEditCustomForm relies on "call by reference" behaviour - //$this->legacy_form = clone $this->legacy_form; - require_once 'Services/Object/Icon/classes/class.ilObjectCustomIconConfigurationGUI.php'; - $gui = new \ilObjectCustomIconConfigurationGUI($DIC, null, $this->object); - $gui->addSettingsToForm($this->legacy_form); - } - } - return $this->legacy_form; - } - - /** - * @inheritdoc - */ - public function saveIcon() - { - global $DIC; - - if ($this->service->settings()->get('custom_icons')) - { - if (!is_null($this->legacy_form)) - { - $this->legacy_form = clone $this->legacy_form; - require_once 'Services/Object/Icon/classes/class.ilObjectCustomIconConfigurationGUI.php'; - $gui = new \ilObjectCustomIconConfigurationGUI($DIC, null, $this->object); - $gui->saveIcon($this->legacy_form); - } - } - - } - - /** - * @inheritdoc - */ - public function addTileImage(): ilPropertyFormGUI - { - $lng = $this->service->language(); - $lng->loadLanguageModule("obj"); - $tile_image_fac = $this->service->commonSettings()->tileImage(); - - if (!is_null($this->legacy_form)) - { - // we do not clone for legacy forms, since initEditCustomForm relies on "call by reference" behaviour - //$this->legacy_form = clone $this->legacy_form; - - $tile_image = $tile_image_fac->getByObjId($this->object->getId()); - $timg = new \ilImageFileInputGUI($lng->txt('obj_tile_image'), 'tile_image'); - $timg->setInfo($lng->txt('obj_tile_image_info')); - $timg->setSuffixes($tile_image_fac->getSupportedFileExtensions()); - $timg->setUseCache(false); - if ($tile_image->exists()) { - $timg->setImage($tile_image->getFullPath()); - } else { - $timg->setImage(''); - } - $this->legacy_form->addItem($timg); - - /* - $file = new ilFileStandardDropzoneInputGUI($lng->txt('obj_tile_image'), 'tile_image'); - $file->setRequired(false); - $file->setSuffixes($tile_image_fac->getSupportedFileExtensions()); - $this->legacy_form->addItem($file);*/ - } - - return $this->legacy_form; - } - - /** - * @inheritdoc - */ - public function saveTileImage() - { - $tile_image_fac = $this->service->commonSettings()->tileImage(); - - if (!is_null($this->legacy_form)) - { - $tile_image = $tile_image_fac->getByObjId($this->object->getId()); - - /** @var \ilImageFileInputGUI $item */ - $item = $this->legacy_form->getItemByPostVar('tile_image'); - if ($item->getDeletionFlag()) { - $tile_image->delete(); - } - - $file_data = $this->legacy_form->getInput('tile_image'); - if ($file_data['tmp_name']) { - $tile_image->saveFromHttpRequest($file_data['tmp_name']); - } - } - } - - /** - * @inheritdoc - */ - public function addTitleIconVisibility(): ilPropertyFormGUI - { - $lng = $this->service->language(); - $hide = new ilCheckboxInputGUI($lng->txt("obj_show_title_and_icon"), "show_header_icon_and_title"); - $hide->setChecked(!ilContainer::_lookupContainerSetting($this->object->getId(), "hide_header_icon_and_title")); - $this->legacy_form->addItem($hide); - return $this->legacy_form; - } - - /** - * @inheritdoc - */ - public function saveTitleIconVisibility() - { - if (!is_null($this->legacy_form)) - { - // hide icon/title - ilContainer::_writeContainerSetting($this->object->getId(), - "hide_header_icon_and_title", - !$this->legacy_form->getInput("show_header_icon_and_title")); - } - } - - /** - * @inheritdoc - */ - public function addTopActionsVisibility(): ilPropertyFormGUI - { - $lng = $this->service->language(); - $hide = new ilCheckboxInputGUI($lng->txt("obj_show_header_actions"), "show_top_actions"); - $hide->setChecked(!ilContainer::_lookupContainerSetting($this->object->getId(), "hide_top_actions")); - $this->legacy_form->addItem($hide); - return $this->legacy_form; - } - - /** - * @inheritdoc - */ - public function saveTopActionsVisibility() - { - if (!is_null($this->legacy_form)) - { - // hide icon/title - ilContainer::_writeContainerSetting($this->object->getId(), - "hide_top_actions", - !$this->legacy_form->getInput("show_top_actions")); - } - } - -} \ No newline at end of file + /** + * @var ilObjectService + */ + protected $service; + + /** + * @var ilPropertyFormGUI + */ + protected $legacy_form; + + /** + * @var ilObject + */ + protected $object; + + /** + * Constructor + */ + public function __construct(ilObjectService $service, ilObject $object, ilPropertyFormGUI $legacy_form = null) + { + $this->service = $service; + $this->legacy_form = $legacy_form; + $this->object = $object; + } + + /** + * @inheritdoc + */ + public function addIcon() : ilPropertyFormGUI + { + global $DIC; + + if ($this->service->settings()->get('custom_icons')) { + if (!is_null($this->legacy_form)) { + // we do not clone for legacy forms, since initEditCustomForm relies on "call by reference" behaviour + //$this->legacy_form = clone $this->legacy_form; + require_once 'Services/Object/Icon/classes/class.ilObjectCustomIconConfigurationGUI.php'; + $gui = new \ilObjectCustomIconConfigurationGUI($DIC, null, $this->object); + $gui->addSettingsToForm($this->legacy_form); + } + } + return $this->legacy_form; + } + + /** + * @inheritdoc + */ + public function saveIcon() + { + global $DIC; + + if ($this->service->settings()->get('custom_icons')) { + if (!is_null($this->legacy_form)) { + $this->legacy_form = clone $this->legacy_form; + require_once 'Services/Object/Icon/classes/class.ilObjectCustomIconConfigurationGUI.php'; + $gui = new \ilObjectCustomIconConfigurationGUI($DIC, null, $this->object); + $gui->saveIcon($this->legacy_form); + } + } + } + + /** + * @inheritdoc + */ + public function addTileImage() : ilPropertyFormGUI + { + $lng = $this->service->language(); + $lng->loadLanguageModule("obj"); + $tile_image_fac = $this->service->commonSettings()->tileImage(); + + if (!is_null($this->legacy_form)) { + // we do not clone for legacy forms, since initEditCustomForm relies on "call by reference" behaviour + //$this->legacy_form = clone $this->legacy_form; + + $tile_image = $tile_image_fac->getByObjId($this->object->getId()); + $timg = new \ilImageFileInputGUI($lng->txt('obj_tile_image'), 'tile_image'); + $timg->setInfo($lng->txt('obj_tile_image_info')); + $timg->setSuffixes($tile_image_fac->getSupportedFileExtensions()); + $timg->setUseCache(false); + if ($tile_image->exists()) { + $timg->setImage($tile_image->getFullPath()); + } else { + $timg->setImage(''); + } + $this->legacy_form->addItem($timg); + + /* + $file = new ilFileStandardDropzoneInputGUI($lng->txt('obj_tile_image'), 'tile_image'); + $file->setRequired(false); + $file->setSuffixes($tile_image_fac->getSupportedFileExtensions()); + $this->legacy_form->addItem($file);*/ + } + + return $this->legacy_form; + } + + /** + * @inheritdoc + */ + public function saveTileImage() + { + $tile_image_fac = $this->service->commonSettings()->tileImage(); + + if (!is_null($this->legacy_form)) { + $tile_image = $tile_image_fac->getByObjId($this->object->getId()); + + /** @var \ilImageFileInputGUI $item */ + $item = $this->legacy_form->getItemByPostVar('tile_image'); + if ($item->getDeletionFlag()) { + $tile_image->delete(); + } + + $file_data = $this->legacy_form->getInput('tile_image'); + if ($file_data['tmp_name']) { + $tile_image->saveFromHttpRequest($file_data['tmp_name']); + } + } + } + + /** + * @inheritdoc + */ + public function addTitleIconVisibility() : ilPropertyFormGUI + { + $lng = $this->service->language(); + $hide = new ilCheckboxInputGUI($lng->txt("obj_show_title_and_icon"), "show_header_icon_and_title"); + $hide->setChecked(!ilContainer::_lookupContainerSetting($this->object->getId(), "hide_header_icon_and_title")); + $this->legacy_form->addItem($hide); + return $this->legacy_form; + } + + /** + * @inheritdoc + */ + public function saveTitleIconVisibility() + { + if (!is_null($this->legacy_form)) { + // hide icon/title + ilContainer::_writeContainerSetting( + $this->object->getId(), + "hide_header_icon_and_title", + !$this->legacy_form->getInput("show_header_icon_and_title") + ); + } + } + + /** + * @inheritdoc + */ + public function addTopActionsVisibility() : ilPropertyFormGUI + { + $lng = $this->service->language(); + $hide = new ilCheckboxInputGUI($lng->txt("obj_show_header_actions"), "show_top_actions"); + $hide->setChecked(!ilContainer::_lookupContainerSetting($this->object->getId(), "hide_top_actions")); + $this->legacy_form->addItem($hide); + return $this->legacy_form; + } + + /** + * @inheritdoc + */ + public function saveTopActionsVisibility() + { + if (!is_null($this->legacy_form)) { + // hide icon/title + ilContainer::_writeContainerSetting( + $this->object->getId(), + "hide_top_actions", + !$this->legacy_form->getInput("show_top_actions") + ); + } + } +} diff --git a/Services/Object/CommonSettings/interfaces/interface.ilObjectCommonSettingsFormAdapterInterface.php b/Services/Object/CommonSettings/interfaces/interface.ilObjectCommonSettingsFormAdapterInterface.php index 013934427eec5656b8d6fa590c511b8a05de9921..0e191b8166ac10cab06aa10121bad9ebc53a9f3c 100644 --- a/Services/Object/CommonSettings/interfaces/interface.ilObjectCommonSettingsFormAdapterInterface.php +++ b/Services/Object/CommonSettings/interfaces/interface.ilObjectCommonSettingsFormAdapterInterface.php @@ -10,53 +10,51 @@ */ interface ilObjectCommonSettingFormAdapterInterface { - /** - * Add icon setting to form - * - * @return null|ilPropertyFormGUI - */ - public function addIcon(): ilPropertyFormGUI; - - /** - * Save icon setting from form - */ - public function saveIcon(); - - /** - * Add tile image setting to form - * - * @return null|ilPropertyFormGUI - */ - public function addTileImage(): ilPropertyFormGUI; - - /** - * Save tile image setting from form - */ - public function saveTileImage(); - - /** - * Add title icon visibility setting to form - * - * @return null|ilPropertyFormGUI - */ - public function addTitleIconVisibility(): ilPropertyFormGUI; - - /** - * Save title icon visibility setting from form - */ - public function saveTitleIconVisibility(); - - /** - * Add top actions visibility setting to form - * - * @return null|ilPropertyFormGUI - */ - public function addTopActionsVisibility(): ilPropertyFormGUI; - - /** - * Save top actions visibility setting from form - */ - public function saveTopActionsVisibility(); - - -} \ No newline at end of file + /** + * Add icon setting to form + * + * @return null|ilPropertyFormGUI + */ + public function addIcon() : ilPropertyFormGUI; + + /** + * Save icon setting from form + */ + public function saveIcon(); + + /** + * Add tile image setting to form + * + * @return null|ilPropertyFormGUI + */ + public function addTileImage() : ilPropertyFormGUI; + + /** + * Save tile image setting from form + */ + public function saveTileImage(); + + /** + * Add title icon visibility setting to form + * + * @return null|ilPropertyFormGUI + */ + public function addTitleIconVisibility() : ilPropertyFormGUI; + + /** + * Save title icon visibility setting from form + */ + public function saveTitleIconVisibility(); + + /** + * Add top actions visibility setting to form + * + * @return null|ilPropertyFormGUI + */ + public function addTopActionsVisibility() : ilPropertyFormGUI; + + /** + * Save top actions visibility setting from form + */ + public function saveTopActionsVisibility(); +} diff --git a/Services/Object/CommonSettings/interfaces/interface.ilObjectCommonSettingsInterface.php b/Services/Object/CommonSettings/interfaces/interface.ilObjectCommonSettingsInterface.php index 5f4092aa40b4cd53081fcd47c59872becdade63a..112ec1bb54eb479e77569fac735257849fc0cfbf 100644 --- a/Services/Object/CommonSettings/interfaces/interface.ilObjectCommonSettingsInterface.php +++ b/Services/Object/CommonSettings/interfaces/interface.ilObjectCommonSettingsInterface.php @@ -11,22 +11,22 @@ */ interface ilObjectCommonSettingsInterface { - /** - * Get form adapter (currently only for legacy form using ilPropertyFormGUI) for adding and saving - * common settings to and from forms. - * - * @todo In the future a method form() should also act on new ui form containers. - * - * @param ilPropertyFormGUI $form - * @param ilObject $object - * @return ilObjectCommonSettingFormAdapter - */ - public function legacyForm(ilPropertyFormGUI $form, ilObject $object): ilObjectCommonSettingFormAdapter; + /** + * Get form adapter (currently only for legacy form using ilPropertyFormGUI) for adding and saving + * common settings to and from forms. + * + * @todo In the future a method form() should also act on new ui form containers. + * + * @param ilPropertyFormGUI $form + * @param ilObject $object + * @return ilObjectCommonSettingFormAdapter + */ + public function legacyForm(ilPropertyFormGUI $form, ilObject $object) : ilObjectCommonSettingFormAdapter; - /** - * Tile image subservice. Tile images are used in deck of cards view of repository containers. - * - * @return ilObjectTileImageFactory - */ - public function tileImage(): ilObjectTileImageFactory; -} \ No newline at end of file + /** + * Tile image subservice. Tile images are used in deck of cards view of repository containers. + * + * @return ilObjectTileImageFactory + */ + public function tileImage() : ilObjectTileImageFactory; +} diff --git a/Services/Object/Icon/classes/class.ilContainerCustomIconConfiguration.php b/Services/Object/Icon/classes/class.ilContainerCustomIconConfiguration.php index 9a65114aa82c8290a28265f186088db90eeb2378..cd401caa0605e9e131a1e65e7d707953d984854a 100644 --- a/Services/Object/Icon/classes/class.ilContainerCustomIconConfiguration.php +++ b/Services/Object/Icon/classes/class.ilContainerCustomIconConfiguration.php @@ -8,11 +8,11 @@ require_once 'Services/Object/Icon/classes/class.ilObjectCustomIconConfiguration */ class ilContainerCustomIconConfiguration extends \ilObjectCustomIconConfiguration { - /** - * @return string - */ - public function getBaseDirectory(): string - { - return 'container_data'; - } -} \ No newline at end of file + /** + * @return string + */ + public function getBaseDirectory() : string + { + return 'container_data'; + } +} diff --git a/Services/Object/Icon/classes/class.ilObjectCustomIconConfiguration.php b/Services/Object/Icon/classes/class.ilObjectCustomIconConfiguration.php index 9c320251cfea7a5bda0976df4fe8cd98fed8673f..19dacbc572b664964cae71c26005f612040f8812 100644 --- a/Services/Object/Icon/classes/class.ilObjectCustomIconConfiguration.php +++ b/Services/Object/Icon/classes/class.ilObjectCustomIconConfiguration.php @@ -8,43 +8,43 @@ require_once 'Services/Object/Icon/interfaces/interface.ilCustomIconObjectConfig */ class ilObjectCustomIconConfiguration implements \ilCustomIconObjectConfiguration { - /** - * @return string[] - */ - public function getSupportedFileExtensions(): array - { - return ['svg']; - } + /** + * @return string[] + */ + public function getSupportedFileExtensions() : array + { + return ['svg']; + } - /** - * @return string - */ - public function getTargetFileExtension(): string - { - return 'svg'; - } + /** + * @return string + */ + public function getTargetFileExtension() : string + { + return 'svg'; + } - /** - * @return string - */ - public function getBaseDirectory(): string - { - return 'custom_icons'; - } + /** + * @return string + */ + public function getBaseDirectory() : string + { + return 'custom_icons'; + } - /** - * @return string - */ - public function getSubDirectoryPrefix(): string - { - return 'obj_'; - } + /** + * @return string + */ + public function getSubDirectoryPrefix() : string + { + return 'obj_'; + } - /** - * @inheritdoc - */ - public function getUploadPostProcessors(): array - { - return []; - } -} \ No newline at end of file + /** + * @inheritdoc + */ + public function getUploadPostProcessors() : array + { + return []; + } +} diff --git a/Services/Object/Icon/classes/class.ilObjectCustomIconConfigurationGUI.php b/Services/Object/Icon/classes/class.ilObjectCustomIconConfigurationGUI.php index 6d8ec20acf870bbcb4d53d8ee27f85b208331d60..7a8518426d7c5c740925df32b6829a6b3a2c082c 100644 --- a/Services/Object/Icon/classes/class.ilObjectCustomIconConfigurationGUI.php +++ b/Services/Object/Icon/classes/class.ilObjectCustomIconConfigurationGUI.php @@ -6,155 +6,153 @@ */ class ilObjectCustomIconConfigurationGUI { - /** @var string */ - const DEFAULT_CMD = 'showForm'; - - /** @var \ILIAS\DI\Container */ - protected $dic; - - /** @var \ilObject */ - protected $object; - - /** @var \ilObjectGUI|mixed */ - protected $parentGui; - - /** - * @var string|null - */ - protected $uploadFieldInformationText = null; - - /** - * ilObjectCustomIconConfigurationGUI constructor. - * @param \ILIAS\DI\Container $dic - * @param \ilObjectGUI|mixed $parentGui - * @param ilObject $object - */ - public function __construct(\ILIAS\DI\Container $dic, $parentGui, \ilObject $object) - { - $this->dic = $dic; - $this->parentGui = $parentGui; - $this->object = $object; - } - - /** - * @param null|string $uploadFieldInformationText - */ - public function setUploadFieldInformationText($uploadFieldInformationText) - { - $this->uploadFieldInformationText = $uploadFieldInformationText; - } - - public function executeCommand() - { - $nextClass = $this->dic->ctrl()->getNextClass($this); - $cmd = $this->dic->ctrl()->getCmd(self::DEFAULT_CMD); - - switch (true) { - case method_exists($this, $cmd): - $this->{$cmd}(); - break; - - default: - $this->{self::DEFAULT_CMD}(); - break; - } - } - - /** - * @param ilPropertyFormGUI|null $form - */ - protected function showForm(\ilPropertyFormGUI $form = null) - { - if (!$form) { - $form = $this->getForm(); - } - - $this->dic->ui()->mainTemplate()->setContent($form->getHTML()); - } - - /** - * @return \ilPropertyFormGUI - */ - protected function getForm(): \ilPropertyFormGUI - { - $this->dic->language()->loadLanguageModule('cntr'); - - $form = new \ilPropertyFormGUI(); - $form->setFormAction($this->dic->ctrl()->getFormAction($this, 'saveForm')); - $form->setTitle($this->dic->language()->txt('icon_settings')); - - $this->addSettingsToForm($form); - - $form->addCommandButton('saveForm', $this->dic->language()->txt('save')); - - return $form; - } - - /** - * Add settings to form - * - * @param ilPropertyFormGUI $form - */ - public function addSettingsToForm(ilPropertyFormGUI $form) - { - /** @var \ilObjectCustomIconFactory $customIconFactory */ - $customIconFactory = $this->dic['object.customicons.factory']; - $customIcon = $customIconFactory->getByObjId($this->object->getId(), $this->object->getType()); - - $icon = new \ilImageFileInputGUI($this->dic->language()->txt('cont_custom_icon'), 'icon'); - if (is_string($this->uploadFieldInformationText)) { - $icon->setInfo($this->uploadFieldInformationText); - } - $icon->setSuffixes($customIcon->getSupportedFileExtensions()); - $icon->setUseCache(false); - if ($customIcon->exists()) { - $icon->setImage($customIcon->getFullPath()); - } else { - $icon->setImage(''); - } - $form->addItem($icon); - } - - /** - * - */ - protected function saveForm() - { - $form = $this->getForm(); - if ($form->checkInput()) { - - $this->saveIcon($form); - - ilUtil::sendSuccess($this->dic->language()->txt('msg_obj_modified'), true); - $this->dic->ctrl()->redirect($this, 'showForm'); - } - - $form->setValuesByPost(); - $this->showForm($form); - } - - /** - * Save icon - * - * @param ilPropertyFormGUI $form - */ - public function saveIcon(ilPropertyFormGUI $form) - { - /** @var \ilObjectCustomIconFactory $customIconFactory */ - $customIconFactory = $this->dic['object.customicons.factory']; - $customIcon = $customIconFactory->getByObjId($this->object->getId(), $this->object->getType()); - - /** @var \ilImageFileInputGUI $item */ - $fileData = (array)$form->getInput('icon'); - $item = $form->getItemByPostVar('icon'); - - if ($item->getDeletionFlag()) { - $customIcon->remove(); - } - - if ($fileData['tmp_name']) { - $customIcon->saveFromHttpRequest(); - } - } - -} \ No newline at end of file + /** @var string */ + const DEFAULT_CMD = 'showForm'; + + /** @var \ILIAS\DI\Container */ + protected $dic; + + /** @var \ilObject */ + protected $object; + + /** @var \ilObjectGUI|mixed */ + protected $parentGui; + + /** + * @var string|null + */ + protected $uploadFieldInformationText = null; + + /** + * ilObjectCustomIconConfigurationGUI constructor. + * @param \ILIAS\DI\Container $dic + * @param \ilObjectGUI|mixed $parentGui + * @param ilObject $object + */ + public function __construct(\ILIAS\DI\Container $dic, $parentGui, \ilObject $object) + { + $this->dic = $dic; + $this->parentGui = $parentGui; + $this->object = $object; + } + + /** + * @param null|string $uploadFieldInformationText + */ + public function setUploadFieldInformationText($uploadFieldInformationText) + { + $this->uploadFieldInformationText = $uploadFieldInformationText; + } + + public function executeCommand() + { + $nextClass = $this->dic->ctrl()->getNextClass($this); + $cmd = $this->dic->ctrl()->getCmd(self::DEFAULT_CMD); + + switch (true) { + case method_exists($this, $cmd): + $this->{$cmd}(); + break; + + default: + $this->{self::DEFAULT_CMD}(); + break; + } + } + + /** + * @param ilPropertyFormGUI|null $form + */ + protected function showForm(\ilPropertyFormGUI $form = null) + { + if (!$form) { + $form = $this->getForm(); + } + + $this->dic->ui()->mainTemplate()->setContent($form->getHTML()); + } + + /** + * @return \ilPropertyFormGUI + */ + protected function getForm() : \ilPropertyFormGUI + { + $this->dic->language()->loadLanguageModule('cntr'); + + $form = new \ilPropertyFormGUI(); + $form->setFormAction($this->dic->ctrl()->getFormAction($this, 'saveForm')); + $form->setTitle($this->dic->language()->txt('icon_settings')); + + $this->addSettingsToForm($form); + + $form->addCommandButton('saveForm', $this->dic->language()->txt('save')); + + return $form; + } + + /** + * Add settings to form + * + * @param ilPropertyFormGUI $form + */ + public function addSettingsToForm(ilPropertyFormGUI $form) + { + /** @var \ilObjectCustomIconFactory $customIconFactory */ + $customIconFactory = $this->dic['object.customicons.factory']; + $customIcon = $customIconFactory->getByObjId($this->object->getId(), $this->object->getType()); + + $icon = new \ilImageFileInputGUI($this->dic->language()->txt('cont_custom_icon'), 'icon'); + if (is_string($this->uploadFieldInformationText)) { + $icon->setInfo($this->uploadFieldInformationText); + } + $icon->setSuffixes($customIcon->getSupportedFileExtensions()); + $icon->setUseCache(false); + if ($customIcon->exists()) { + $icon->setImage($customIcon->getFullPath()); + } else { + $icon->setImage(''); + } + $form->addItem($icon); + } + + /** + * + */ + protected function saveForm() + { + $form = $this->getForm(); + if ($form->checkInput()) { + $this->saveIcon($form); + + ilUtil::sendSuccess($this->dic->language()->txt('msg_obj_modified'), true); + $this->dic->ctrl()->redirect($this, 'showForm'); + } + + $form->setValuesByPost(); + $this->showForm($form); + } + + /** + * Save icon + * + * @param ilPropertyFormGUI $form + */ + public function saveIcon(ilPropertyFormGUI $form) + { + /** @var \ilObjectCustomIconFactory $customIconFactory */ + $customIconFactory = $this->dic['object.customicons.factory']; + $customIcon = $customIconFactory->getByObjId($this->object->getId(), $this->object->getType()); + + /** @var \ilImageFileInputGUI $item */ + $fileData = (array) $form->getInput('icon'); + $item = $form->getItemByPostVar('icon'); + + if ($item->getDeletionFlag()) { + $customIcon->remove(); + } + + if ($fileData['tmp_name']) { + $customIcon->saveFromHttpRequest(); + } + } +} diff --git a/Services/Object/Icon/classes/class.ilObjectCustomIconFactory.php b/Services/Object/Icon/classes/class.ilObjectCustomIconFactory.php index bbdf3264649ab3f225724e21201689e70febc022..d5350d46ecb9840d58d064b91785e8266da85101 100644 --- a/Services/Object/Icon/classes/class.ilObjectCustomIconFactory.php +++ b/Services/Object/Icon/classes/class.ilObjectCustomIconFactory.php @@ -6,113 +6,111 @@ */ class ilObjectCustomIconFactory { - /** - * @var \ILIAS\Filesystem\Filesystem - */ - protected $webDirectory; + /** + * @var \ILIAS\Filesystem\Filesystem + */ + protected $webDirectory; - /** - * @var \ILIAS\FileUpload\FileUpload - */ - protected $uploadService; + /** + * @var \ILIAS\FileUpload\FileUpload + */ + protected $uploadService; - /** - * @var \ilObjectDataCache - */ - protected $objectCache; + /** + * @var \ilObjectDataCache + */ + protected $objectCache; - /** - * ilObjectCustomIconFactory constructor. - * @param \ILIAS\Filesystem\Filesystem $webDirectory - * @param \ILIAS\FileUpload\FileUpload $uploadService - */ - public function __construct( - \ILIAS\Filesystem\Filesystem $webDirectory, - \ILIAS\FileUpload\FileUpload $uploadService, - \ilObjectDataCache $objectCache - ) - { - $this->webDirectory = $webDirectory; - $this->uploadService = $uploadService; - $this->objectCache = $objectCache; - } + /** + * ilObjectCustomIconFactory constructor. + * @param \ILIAS\Filesystem\Filesystem $webDirectory + * @param \ILIAS\FileUpload\FileUpload $uploadService + */ + public function __construct( + \ILIAS\Filesystem\Filesystem $webDirectory, + \ILIAS\FileUpload\FileUpload $uploadService, + \ilObjectDataCache $objectCache + ) { + $this->webDirectory = $webDirectory; + $this->uploadService = $uploadService; + $this->objectCache = $objectCache; + } - /** - * @var string $type - * @return \ilCustomIconObjectConfiguration - */ - public function getConfigurationByType(string $type) : \ilCustomIconObjectConfiguration - { - switch ($type) { - case 'grp': - case 'root': - case 'cat': - case 'fold': - case 'crs': - case 'prg': - require_once 'Services/Object/Icon/classes/class.ilContainerCustomIconConfiguration.php'; - $configuration = new \ilContainerCustomIconConfiguration(); - break; + /** + * @var string $type + * @return \ilCustomIconObjectConfiguration + */ + public function getConfigurationByType(string $type) : \ilCustomIconObjectConfiguration + { + switch ($type) { + case 'grp': + case 'root': + case 'cat': + case 'fold': + case 'crs': + case 'prg': + require_once 'Services/Object/Icon/classes/class.ilContainerCustomIconConfiguration.php'; + $configuration = new \ilContainerCustomIconConfiguration(); + break; - default: - require_once 'Services/Object/Icon/classes/class.ilObjectCustomIconConfiguration.php'; - $configuration = new \ilObjectCustomIconConfiguration(); - break; - } + default: + require_once 'Services/Object/Icon/classes/class.ilObjectCustomIconConfiguration.php'; + $configuration = new \ilObjectCustomIconConfiguration(); + break; + } - return $configuration; - } + return $configuration; + } - /** - * @param int $objId The obj_id of the ILIAS object. - * @param string $objType An optional type of the ILIAS object. If not passed, the type will be determined automatically. - * @return \ilObjectCustomIcon - */ - public function getByObjId(int $objId, string $objType = '') : \ilObjectCustomIcon - { - if (0 === strlen($objType)) { - $objType = (string)$this->objectCache->lookupType($objId); - } + /** + * @param int $objId The obj_id of the ILIAS object. + * @param string $objType An optional type of the ILIAS object. If not passed, the type will be determined automatically. + * @return \ilObjectCustomIcon + */ + public function getByObjId(int $objId, string $objType = '') : \ilObjectCustomIcon + { + if (0 === strlen($objType)) { + $objType = (string) $this->objectCache->lookupType($objId); + } - require_once 'Services/Object/Icon/classes/class.ilObjectCustomIconImpl.php'; - return new \ilObjectCustomIconImpl( - $this->webDirectory, - $this->uploadService, - $this->getConfigurationByType($objType), - $objId - ); - } + require_once 'Services/Object/Icon/classes/class.ilObjectCustomIconImpl.php'; + return new \ilObjectCustomIconImpl( + $this->webDirectory, + $this->uploadService, + $this->getConfigurationByType($objType), + $objId + ); + } - /** - * Get custom icon presenter - * - * @param int $objId - * @param string $objType - * - * @return \ilObjectCustomIconPresenter - */ - public function getPresenterByObjId(int $objId, string $objType) : \ilObjectCustomIconPresenter - { - if (0 === strlen($objType)) { - $objType = $this->objectCache->lookupType($objId); - } + /** + * Get custom icon presenter + * + * @param int $objId + * @param string $objType + * + * @return \ilObjectCustomIconPresenter + */ + public function getPresenterByObjId(int $objId, string $objType) : \ilObjectCustomIconPresenter + { + if (0 === strlen($objType)) { + $objType = $this->objectCache->lookupType($objId); + } - $presenter = null; - switch($objType) - { - case 'catr': - case 'grpr': - case 'crsr': - $presenter = new \ilObjectReferenceCustomIconPresenter($objId, $this); - $presenter->init(); - break; + $presenter = null; + switch ($objType) { + case 'catr': + case 'grpr': + case 'crsr': + $presenter = new \ilObjectReferenceCustomIconPresenter($objId, $this); + $presenter->init(); + break; - default: - $presenter = new \ilObjectCustomIconPresenterImpl($this->getByObjId((int)$objId, (string) $objType)); - break; + default: + $presenter = new \ilObjectCustomIconPresenterImpl($this->getByObjId((int) $objId, (string) $objType)); + break; - } - return $presenter; - } -} \ No newline at end of file + } + return $presenter; + } +} diff --git a/Services/Object/Icon/classes/class.ilObjectCustomIconImpl.php b/Services/Object/Icon/classes/class.ilObjectCustomIconImpl.php index be7da7fb89d77a2a58ce19928bd51e72c3e80b90..23f3580eef4fed618f3867ec8bf653d60416c457 100644 --- a/Services/Object/Icon/classes/class.ilObjectCustomIconImpl.php +++ b/Services/Object/Icon/classes/class.ilObjectCustomIconImpl.php @@ -10,242 +10,242 @@ use ILIAS\FileUpload\FileUpload; */ class ilObjectCustomIconImpl implements \ilObjectCustomIcon { - const ICON_BASENAME = 'icon_custom'; - - /** @var Filesystem */ - protected $webDirectory; - - /** @var FileUpload */ - protected $upload; - - /** @var \ilCustomIconObjectConfiguration */ - protected $config; - - /** @var int */ - protected $objId; - - /** - * ilObjectCustomIconImpl constructor. - * @param Filesystem $webDirectory - * @param FileUpload $uploadService - * @param ilCustomIconObjectConfiguration $config - * @param $objId - */ - public function __construct(Filesystem $webDirectory, FileUpload $uploadService, \ilCustomIconObjectConfiguration $config, int $objId) - { - $this->objId = $objId; - - $this->webDirectory = $webDirectory; - $this->upload = $uploadService; - $this->config = $config; - } - - /** - * @return int - */ - protected function getObjId(): int - { - return $this->objId; - } - - /** - * @inheritdoc - */ - public function copy(int $targetObjId) - { - if (!$this->exists()) { - \ilContainer::_writeContainerSetting($targetObjId, 'icon_custom', 0); - return; - } - - try { - $this->webDirectory->copy( - $this->getRelativePath(), - preg_replace( - '/(' . $this->config->getSubDirectoryPrefix() . ')(\d*)\/(.*)$/', - '${1}' . $targetObjId . '/${3}', - $this->getRelativePath() - ) - ); - - \ilContainer::_writeContainerSetting($targetObjId, 'icon_custom', 1); - } catch (\Exception $e) { - \ilContainer::_writeContainerSetting($targetObjId, 'icon_custom', 0); - } - } - - /** - * @inheritdoc - */ - public function delete() - { - if ($this->exists()) { - try { - $this->webDirectory->deleteDir($this->getIconDirectory()); - } catch (\Exception $e) { - } - } - - \ilContainer::_deleteContainerSettings($this->getObjId(), 'icon_custom'); - } - - /** - * @return string[] - */ - public function getSupportedFileExtensions(): array - { - return $this->config->getSupportedFileExtensions(); - } - - /** - * @inheritdoc - */ - public function saveFromSourceFile(string $sourceFilePath) - { - $this->createCustomIconDirectory(); - - $fileName = $this->getRelativePath(); - - if ($this->webDirectory->has($fileName)) { - $this->webDirectory->delete($fileName); - } - - $this->webDirectory->copy($sourceFilePath, $fileName); - - $this->persistIconState($fileName); - } - - /** - * @inheritdoc - */ - public function saveFromHttpRequest() - { - $this->createCustomIconDirectory(); - - $fileName = $this->getRelativePath(); - - if ($this->webDirectory->has($fileName)) { - $this->webDirectory->delete($fileName); - } - - if ($this->upload->hasUploads() && !$this->upload->hasBeenProcessed()) { - $this->upload->process(); - - /** @var \ILIAS\FileUpload\DTO\UploadResult $result */ - $result = array_values($this->upload->getResults())[0]; - if ($result->getStatus() == \ILIAS\FileUpload\DTO\ProcessingStatus::OK) { - $this->upload->moveOneFileTo( - $result, - $this->getIconDirectory(), - \ILIAS\FileUpload\Location::WEB, - $this->getIconFileName(), - true - ); - } - - foreach ($this->config->getUploadPostProcessors() as $processor) { - $processor->process($fileName); - } - } - - $this->persistIconState($fileName); - } - - /** - * @param string $fileName - */ - protected function persistIconState(string $fileName) - { - if ($this->webDirectory->has($fileName)) { - \ilContainer::_writeContainerSetting($this->getObjId(), 'icon_custom', 1); - } else { - \ilContainer::_writeContainerSetting($this->getObjId(), 'icon_custom', 0); - } - } - - /** - * @inheritdoc - */ - public function remove() - { - $fileName = $this->getRelativePath(); - - if ($this->webDirectory->has($fileName)) { - $this->webDirectory->delete($fileName); - } - - \ilContainer::_writeContainerSetting($this->getObjId(), 'icon_custom', 0); - } - - /** - * @throws \ILIAS\Filesystem\Exception\IOException - */ - protected function createCustomIconDirectory() - { - $iconDirectory = $this->getIconDirectory(); - - if (!$this->webDirectory->has(dirname($iconDirectory))) { - $this->webDirectory->createDir(dirname($iconDirectory)); - } - - if (!$this->webDirectory->has($iconDirectory)) { - $this->webDirectory->createDir($iconDirectory); - } - } - - /** - * @return string - */ - protected function getIconDirectory(): string - { - return implode(DIRECTORY_SEPARATOR, [ - $this->config->getBaseDirectory(), - $this->config->getSubDirectoryPrefix() . $this->getObjId() - ]); - } - - /** - * @return string - */ - protected function getIconFileName(): string - { - return self::ICON_BASENAME . '.' . $this->config->getTargetFileExtension(); - } - - /** - * @return string - */ - protected function getRelativePath(): string - { - return implode(DIRECTORY_SEPARATOR, [ - $this->getIconDirectory(), - $this->getIconFileName() - ]); - } - - /** - * @inheritdoc - */ - public function exists(): bool - { - if (!\ilContainer::_lookupContainerSetting($this->getObjId(), 'icon_custom', 0)) { - return false; - } - - return $this->webDirectory->has($this->getRelativePath()); - } - - /** - * @inheritdoc - */ - public function getFullPath(): string - { - // TODO: Currently there is no option to get the relative base directory of a filesystem - return implode(DIRECTORY_SEPARATOR, [ - \ilUtil::getWebspaceDir(), - $this->getRelativePath() - ]); - } + const ICON_BASENAME = 'icon_custom'; + + /** @var Filesystem */ + protected $webDirectory; + + /** @var FileUpload */ + protected $upload; + + /** @var \ilCustomIconObjectConfiguration */ + protected $config; + + /** @var int */ + protected $objId; + + /** + * ilObjectCustomIconImpl constructor. + * @param Filesystem $webDirectory + * @param FileUpload $uploadService + * @param ilCustomIconObjectConfiguration $config + * @param $objId + */ + public function __construct(Filesystem $webDirectory, FileUpload $uploadService, \ilCustomIconObjectConfiguration $config, int $objId) + { + $this->objId = $objId; + + $this->webDirectory = $webDirectory; + $this->upload = $uploadService; + $this->config = $config; + } + + /** + * @return int + */ + protected function getObjId() : int + { + return $this->objId; + } + + /** + * @inheritdoc + */ + public function copy(int $targetObjId) + { + if (!$this->exists()) { + \ilContainer::_writeContainerSetting($targetObjId, 'icon_custom', 0); + return; + } + + try { + $this->webDirectory->copy( + $this->getRelativePath(), + preg_replace( + '/(' . $this->config->getSubDirectoryPrefix() . ')(\d*)\/(.*)$/', + '${1}' . $targetObjId . '/${3}', + $this->getRelativePath() + ) + ); + + \ilContainer::_writeContainerSetting($targetObjId, 'icon_custom', 1); + } catch (\Exception $e) { + \ilContainer::_writeContainerSetting($targetObjId, 'icon_custom', 0); + } + } + + /** + * @inheritdoc + */ + public function delete() + { + if ($this->exists()) { + try { + $this->webDirectory->deleteDir($this->getIconDirectory()); + } catch (\Exception $e) { + } + } + + \ilContainer::_deleteContainerSettings($this->getObjId(), 'icon_custom'); + } + + /** + * @return string[] + */ + public function getSupportedFileExtensions() : array + { + return $this->config->getSupportedFileExtensions(); + } + + /** + * @inheritdoc + */ + public function saveFromSourceFile(string $sourceFilePath) + { + $this->createCustomIconDirectory(); + + $fileName = $this->getRelativePath(); + + if ($this->webDirectory->has($fileName)) { + $this->webDirectory->delete($fileName); + } + + $this->webDirectory->copy($sourceFilePath, $fileName); + + $this->persistIconState($fileName); + } + + /** + * @inheritdoc + */ + public function saveFromHttpRequest() + { + $this->createCustomIconDirectory(); + + $fileName = $this->getRelativePath(); + + if ($this->webDirectory->has($fileName)) { + $this->webDirectory->delete($fileName); + } + + if ($this->upload->hasUploads() && !$this->upload->hasBeenProcessed()) { + $this->upload->process(); + + /** @var \ILIAS\FileUpload\DTO\UploadResult $result */ + $result = array_values($this->upload->getResults())[0]; + if ($result->getStatus() == \ILIAS\FileUpload\DTO\ProcessingStatus::OK) { + $this->upload->moveOneFileTo( + $result, + $this->getIconDirectory(), + \ILIAS\FileUpload\Location::WEB, + $this->getIconFileName(), + true + ); + } + + foreach ($this->config->getUploadPostProcessors() as $processor) { + $processor->process($fileName); + } + } + + $this->persistIconState($fileName); + } + + /** + * @param string $fileName + */ + protected function persistIconState(string $fileName) + { + if ($this->webDirectory->has($fileName)) { + \ilContainer::_writeContainerSetting($this->getObjId(), 'icon_custom', 1); + } else { + \ilContainer::_writeContainerSetting($this->getObjId(), 'icon_custom', 0); + } + } + + /** + * @inheritdoc + */ + public function remove() + { + $fileName = $this->getRelativePath(); + + if ($this->webDirectory->has($fileName)) { + $this->webDirectory->delete($fileName); + } + + \ilContainer::_writeContainerSetting($this->getObjId(), 'icon_custom', 0); + } + + /** + * @throws \ILIAS\Filesystem\Exception\IOException + */ + protected function createCustomIconDirectory() + { + $iconDirectory = $this->getIconDirectory(); + + if (!$this->webDirectory->has(dirname($iconDirectory))) { + $this->webDirectory->createDir(dirname($iconDirectory)); + } + + if (!$this->webDirectory->has($iconDirectory)) { + $this->webDirectory->createDir($iconDirectory); + } + } + + /** + * @return string + */ + protected function getIconDirectory() : string + { + return implode(DIRECTORY_SEPARATOR, [ + $this->config->getBaseDirectory(), + $this->config->getSubDirectoryPrefix() . $this->getObjId() + ]); + } + + /** + * @return string + */ + protected function getIconFileName() : string + { + return self::ICON_BASENAME . '.' . $this->config->getTargetFileExtension(); + } + + /** + * @return string + */ + protected function getRelativePath() : string + { + return implode(DIRECTORY_SEPARATOR, [ + $this->getIconDirectory(), + $this->getIconFileName() + ]); + } + + /** + * @inheritdoc + */ + public function exists() : bool + { + if (!\ilContainer::_lookupContainerSetting($this->getObjId(), 'icon_custom', 0)) { + return false; + } + + return $this->webDirectory->has($this->getRelativePath()); + } + + /** + * @inheritdoc + */ + public function getFullPath() : string + { + // TODO: Currently there is no option to get the relative base directory of a filesystem + return implode(DIRECTORY_SEPARATOR, [ + \ilUtil::getWebspaceDir(), + $this->getRelativePath() + ]); + } /** * @param $source_dir @@ -263,5 +263,4 @@ class ilObjectCustomIconImpl implements \ilObjectCustomIcon ilUtil::rCopy($source_dir, $target_dir); $this->persistIconState($this->getRelativePath()); } - -} \ No newline at end of file +} diff --git a/Services/Object/Icon/classes/class.ilObjectCustomIconPresenterImpl.php b/Services/Object/Icon/classes/class.ilObjectCustomIconPresenterImpl.php index 4286a1cd33284bd4b46a76e379e70eae6c4982c7..f4bda7bfe9a959cff51d5ea40a2e94d047e0c639 100644 --- a/Services/Object/Icon/classes/class.ilObjectCustomIconPresenterImpl.php +++ b/Services/Object/Icon/classes/class.ilObjectCustomIconPresenterImpl.php @@ -6,31 +6,31 @@ */ class ilObjectCustomIconPresenterImpl implements \ilObjectCustomIconPresenter { - /** @var \ilObjectCustomIcon */ - private $icon = null; + /** @var \ilObjectCustomIcon */ + private $icon = null; - /** - * ilObjectCustomIconPresenter constructor. - * @param ilObjectCustomIcon $icon - */ - public function __construct(\ilObjectCustomIcon $icon) - { - $this->icon = $icon; - } + /** + * ilObjectCustomIconPresenter constructor. + * @param ilObjectCustomIcon $icon + */ + public function __construct(\ilObjectCustomIcon $icon) + { + $this->icon = $icon; + } - /** - * @inheritdoc - */ - public function exists(): bool - { - return $this->icon->exists(); - } + /** + * @inheritdoc + */ + public function exists() : bool + { + return $this->icon->exists(); + } - /** - * @inheritdoc - */ - public function getFullPath(): string - { - return $this->icon->getFullPath(); - } -} \ No newline at end of file + /** + * @inheritdoc + */ + public function getFullPath() : string + { + return $this->icon->getFullPath(); + } +} diff --git a/Services/Object/Icon/classes/class.ilObjectReferenceCustomIconPresenter.php b/Services/Object/Icon/classes/class.ilObjectReferenceCustomIconPresenter.php index b97b8d63773f0e374e309aac64a21edb7d059ca5..fcd3e11869ed24163b0f5d6a86a9f59870629a2e 100644 --- a/Services/Object/Icon/classes/class.ilObjectReferenceCustomIconPresenter.php +++ b/Services/Object/Icon/classes/class.ilObjectReferenceCustomIconPresenter.php @@ -6,62 +6,62 @@ */ class ilObjectReferenceCustomIconPresenter implements \ilObjectCustomIconPresenter { - /** @var \ilObjectCustomIconFactory*/ - private $factory = null; - - /** @var \ilObjectCustomIcon */ - private $icon = null; + /** @var \ilObjectCustomIconFactory*/ + private $factory = null; + + /** @var \ilObjectCustomIcon */ + private $icon = null; - /** @var int */ - private $obj_id = 0; + /** @var int */ + private $obj_id = 0; - /** - * ilObjectReferenceCustomIconPresenter constructor. - * @param int $obj_id - * @param ilObjectCustomIconFactory $factory - */ - public function __construct(int $obj_id, \ilObjectCustomIconFactory $factory) - { - $this->factory = $factory; - $this->obj_id = $obj_id; - } + /** + * ilObjectReferenceCustomIconPresenter constructor. + * @param int $obj_id + * @param ilObjectCustomIconFactory $factory + */ + public function __construct(int $obj_id, \ilObjectCustomIconFactory $factory) + { + $this->factory = $factory; + $this->obj_id = $obj_id; + } - /** - * Init \ilObjectCustomIconPresenter - * If the target is invalid the icon instance - * creation is based on the reference object obj_id - */ - public function init() - { - $target_obj_id = $this->lookupTargetId(); - $this->icon = $this->factory->getByObjId($target_obj_id); - } + /** + * Init \ilObjectCustomIconPresenter + * If the target is invalid the icon instance + * creation is based on the reference object obj_id + */ + public function init() + { + $target_obj_id = $this->lookupTargetId(); + $this->icon = $this->factory->getByObjId($target_obj_id); + } - /** - * @inheritdoc - */ - public function exists(): bool - { - return $this->icon->exists(); - } + /** + * @inheritdoc + */ + public function exists() : bool + { + return $this->icon->exists(); + } - /** - * @inheritdoc - */ - public function getFullPath(): string - { - return $this->icon->getFullPath(); - } + /** + * @inheritdoc + */ + public function getFullPath() : string + { + return $this->icon->getFullPath(); + } - /** - * Lookup target id of container reference - * @return int - */ - protected function lookupTargetId(): int - { - $target_obj_id = ilContainerReference::_lookupTargetId($this->obj_id); - return $target_obj_id; - } -} \ No newline at end of file + /** + * Lookup target id of container reference + * @return int + */ + protected function lookupTargetId() : int + { + $target_obj_id = ilContainerReference::_lookupTargetId($this->obj_id); + return $target_obj_id; + } +} diff --git a/Services/Object/Icon/interfaces/interface.ilCustomIconObjectConfiguration.php b/Services/Object/Icon/interfaces/interface.ilCustomIconObjectConfiguration.php index 550341b0ba069159bb67e0e1c5479c2f5ffeb06d..834e7d82884ba31057f9e90c5aa068ccabaa77c5 100644 --- a/Services/Object/Icon/interfaces/interface.ilCustomIconObjectConfiguration.php +++ b/Services/Object/Icon/interfaces/interface.ilCustomIconObjectConfiguration.php @@ -3,29 +3,29 @@ interface ilCustomIconObjectConfiguration { - /** - * @return string[] - */ - public function getSupportedFileExtensions(): array; + /** + * @return string[] + */ + public function getSupportedFileExtensions() : array; - /** - * @return string - */ - public function getTargetFileExtension(): string; + /** + * @return string + */ + public function getTargetFileExtension() : string; - /** - * @return string - */ - public function getBaseDirectory(): string; + /** + * @return string + */ + public function getBaseDirectory() : string; - /** - * @return string - */ - public function getSubDirectoryPrefix():string; + /** + * @return string + */ + public function getSubDirectoryPrefix() : string; - /** - * A collection of post processors which are invoked if a new icon has been uploaded - * @return ilObjectCustomIconUploadPostProcessor[] - */ - public function getUploadPostProcessors(): array; -} \ No newline at end of file + /** + * A collection of post processors which are invoked if a new icon has been uploaded + * @return ilObjectCustomIconUploadPostProcessor[] + */ + public function getUploadPostProcessors() : array; +} diff --git a/Services/Object/Icon/interfaces/interface.ilObjectCustomIcon.php b/Services/Object/Icon/interfaces/interface.ilObjectCustomIcon.php index 745ddd7ae7c54c7b6f42ca61830b376feb58bf54..0ebc7aa6817cfad0cd58c603e7d50f6c07f40581 100644 --- a/Services/Object/Icon/interfaces/interface.ilObjectCustomIcon.php +++ b/Services/Object/Icon/interfaces/interface.ilObjectCustomIcon.php @@ -6,50 +6,50 @@ */ interface ilObjectCustomIcon { - /** - * @return string[] - */ - public function getSupportedFileExtensions(): array ; - - /** - * @param string $sourceFilePath - * @throws \ILIAS\Filesystem\Exception\FileAlreadyExistsException - * @throws \ILIAS\Filesystem\Exception\FileNotFoundException - * @throws \ILIAS\Filesystem\Exception\IOException - */ - public function saveFromSourceFile(string $sourceFilePath); - - /** - * @throws \ILIAS\FileUpload\Exception\IllegalStateException - * @throws \ILIAS\Filesystem\Exception\FileNotFoundException - * @throws \ILIAS\Filesystem\Exception\IOException - */ - public function saveFromHttpRequest(); - - /** - * @param int $targetObjId - */ - public function copy(int $targetObjId); - - /** - * Should be called if a consuming object is removed from system. - * The implementer MUST delete all object specific custom icon data (folders, icons, persistent data) - */ - public function delete(); - - /** - * Should be called if a consuming object just wants to delete the icon - * The implementer MUST only delete the icon itself and corresponding persistent data (e.g. stored in a database) - */ - public function remove(); - - /** - * @return bool - */ - public function exists(): bool ; - - /** - * @return string - */ - public function getFullPath(): string ; -} \ No newline at end of file + /** + * @return string[] + */ + public function getSupportedFileExtensions() : array ; + + /** + * @param string $sourceFilePath + * @throws \ILIAS\Filesystem\Exception\FileAlreadyExistsException + * @throws \ILIAS\Filesystem\Exception\FileNotFoundException + * @throws \ILIAS\Filesystem\Exception\IOException + */ + public function saveFromSourceFile(string $sourceFilePath); + + /** + * @throws \ILIAS\FileUpload\Exception\IllegalStateException + * @throws \ILIAS\Filesystem\Exception\FileNotFoundException + * @throws \ILIAS\Filesystem\Exception\IOException + */ + public function saveFromHttpRequest(); + + /** + * @param int $targetObjId + */ + public function copy(int $targetObjId); + + /** + * Should be called if a consuming object is removed from system. + * The implementer MUST delete all object specific custom icon data (folders, icons, persistent data) + */ + public function delete(); + + /** + * Should be called if a consuming object just wants to delete the icon + * The implementer MUST only delete the icon itself and corresponding persistent data (e.g. stored in a database) + */ + public function remove(); + + /** + * @return bool + */ + public function exists() : bool ; + + /** + * @return string + */ + public function getFullPath() : string ; +} diff --git a/Services/Object/Icon/interfaces/interface.ilObjectCustomIconPresenter.php b/Services/Object/Icon/interfaces/interface.ilObjectCustomIconPresenter.php index 7855eeee9b9d477b150c13c0b00d45a239d4c11a..fb65fa3e909cba4a0a0daea6724daa13f84c1a90 100644 --- a/Services/Object/Icon/interfaces/interface.ilObjectCustomIconPresenter.php +++ b/Services/Object/Icon/interfaces/interface.ilObjectCustomIconPresenter.php @@ -6,13 +6,13 @@ */ interface ilObjectCustomIconPresenter { - /** - * @return bool - */ - public function exists(): bool; + /** + * @return bool + */ + public function exists() : bool; - /** - * @return string - */ - public function getFullPath(): string; -} \ No newline at end of file + /** + * @return string + */ + public function getFullPath() : string; +} diff --git a/Services/Object/Icon/interfaces/interface.ilObjectCustomIconUploadPostProcessor.php b/Services/Object/Icon/interfaces/interface.ilObjectCustomIconUploadPostProcessor.php index 5ae044168b8092b5bb46c4912a4741fce34753a8..32badd6c5ebb62d9eb3abb6fc022a00f8bd8119d 100644 --- a/Services/Object/Icon/interfaces/interface.ilObjectCustomIconUploadPostProcessor.php +++ b/Services/Object/Icon/interfaces/interface.ilObjectCustomIconUploadPostProcessor.php @@ -6,8 +6,8 @@ */ interface ilObjectCustomIconUploadPostProcessor { - /** - * @param string $fileName - */ - public function process(string $fileName); -} \ No newline at end of file + /** + * @param string $fileName + */ + public function process(string $fileName); +} diff --git a/Services/Object/Service/classes/class.ilObjectService.php b/Services/Object/Service/classes/class.ilObjectService.php index 599839f30bf279df9bac4a2ed7e2e3d01457903a..cf562576e755c42073b7c09cf836391dc560b4b2 100644 --- a/Services/Object/Service/classes/class.ilObjectService.php +++ b/Services/Object/Service/classes/class.ilObjectService.php @@ -10,78 +10,78 @@ */ class ilObjectService implements ilObjectServiceInterface { - /** + /** - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilSetting - */ - protected $settings; + /** + * @var ilSetting + */ + protected $settings; - /** - * @var \ILIAS\Filesystem\Filesystems - */ - protected $filesystem; + /** + * @var \ILIAS\Filesystem\Filesystems + */ + protected $filesystem; - /** - * Constructor - * @param ilLanguage $lng - */ - public function __construct(ilLanguage $lng, ilSetting $settings, \ILIAS\Filesystem\Filesystems $filesystem, \ILIAS\FileUpload\FileUpload $upload) - { - $this->lng = $lng; - $this->settings = $settings; - $this->filesystem = $filesystem; - $this->upload = $upload; - } + /** + * Constructor + * @param ilLanguage $lng + */ + public function __construct(ilLanguage $lng, ilSetting $settings, \ILIAS\Filesystem\Filesystems $filesystem, \ILIAS\FileUpload\FileUpload $upload) + { + $this->lng = $lng; + $this->settings = $settings; + $this->filesystem = $filesystem; + $this->upload = $upload; + } - /** - * Get language object - * - * @return ilLanguage - */ - public function language() - { - return $this->lng; - } + /** + * Get language object + * + * @return ilLanguage + */ + public function language() + { + return $this->lng; + } - /** - * Get settings object - * - * @return ilSetting - */ - public function settings() - { - return $this->settings; - } + /** + * Get settings object + * + * @return ilSetting + */ + public function settings() + { + return $this->settings; + } - /** - * Get filesystems - * @return \ILIAS\Filesystem\Filesystems - */ - public function filesystem() - { - return $this->filesystem; - } + /** + * Get filesystems + * @return \ILIAS\Filesystem\Filesystems + */ + public function filesystem() + { + return $this->filesystem; + } - /** - * Get filesystems - * @return \ILIAS\FileUpload\FileUpload - */ - public function upload() - { - return $this->upload; - } + /** + * Get filesystems + * @return \ILIAS\FileUpload\FileUpload + */ + public function upload() + { + return $this->upload; + } - /** - * @inheritdoc - */ - public function commonSettings(): ilObjectCommonSettings - { - return new ilObjectCommonSettings($this); - } -} \ No newline at end of file + /** + * @inheritdoc + */ + public function commonSettings() : ilObjectCommonSettings + { + return new ilObjectCommonSettings($this); + } +} diff --git a/Services/Object/Service/interfaces/interface.ilObjectServiceInterface.php b/Services/Object/Service/interfaces/interface.ilObjectServiceInterface.php index d1dba904ff507acafeb60ab21673f6384a978d17..9b8f7507fe84f78d026ee978f4873c177b61393e 100644 --- a/Services/Object/Service/interfaces/interface.ilObjectServiceInterface.php +++ b/Services/Object/Service/interfaces/interface.ilObjectServiceInterface.php @@ -10,10 +10,10 @@ */ interface ilObjectServiceInterface { - /** - * Get common settings subservice - * - * @return ilObjectCommonSettings - */ - public function commonSettings(): ilObjectCommonSettings; -} \ No newline at end of file + /** + * Get common settings subservice + * + * @return ilObjectCommonSettings + */ + public function commonSettings() : ilObjectCommonSettings; +} diff --git a/Services/Object/classes/class.ilCommonActionDispatcherGUI.php b/Services/Object/classes/class.ilCommonActionDispatcherGUI.php index da52788c12e2436917c4b152f0a5b4321c93f435..fba970a43db2e4287233c4a0d7f130ad7c9d70ee 100644 --- a/Services/Object/classes/class.ilCommonActionDispatcherGUI.php +++ b/Services/Object/classes/class.ilCommonActionDispatcherGUI.php @@ -13,315 +13,310 @@ * @ingroup ServicesObject */ class ilCommonActionDispatcherGUI -{ - /** - * @var ilCtrl - */ - protected $ctrl; +{ + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilSetting - */ - protected $settings; + /** + * @var ilSetting + */ + protected $settings; - protected $obj_type; // [string] - protected $node_id; // [int] - protected $node_type; // [string] - protected $obj_id; // [int] - protected $sub_type; // [string] - protected $sub_id; // [int] + protected $obj_type; // [string] + protected $node_id; // [int] + protected $node_type; // [string] + protected $obj_id; // [int] + protected $sub_type; // [string] + protected $sub_id; // [int] - /** - * @var int - */ - protected $news_id = 0; + /** + * @var int + */ + protected $news_id = 0; - protected $enable_comments_settings; // [bool] - protected $rating_callback; // [array] - - const TYPE_REPOSITORY = 1; - const TYPE_WORKSPACE = 2; - - /** - * Constructor - * - * @param int $a_node_type - * @param object $a_access_handler - * @param string $a_obj_type - * @param int $a_node_id - * @param int $a_obj_id - * @return object - */ - function __construct($a_node_type, $a_access_handler, $a_obj_type, $a_node_id, $a_obj_id, $a_news_id = 0) - { - global $DIC; + protected $enable_comments_settings; // [bool] + protected $rating_callback; // [array] + + const TYPE_REPOSITORY = 1; + const TYPE_WORKSPACE = 2; + + /** + * Constructor + * + * @param int $a_node_type + * @param object $a_access_handler + * @param string $a_obj_type + * @param int $a_node_id + * @param int $a_obj_id + * @return object + */ + public function __construct($a_node_type, $a_access_handler, $a_obj_type, $a_node_id, $a_obj_id, $a_news_id = 0) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->settings = $DIC->settings(); - $this->node_type = (int)$a_node_type; - $this->access_handler = $a_access_handler; - $this->obj_type = (string)$a_obj_type; - $this->node_id = (int)$a_node_id; - $this->obj_id = (int)$a_obj_id; - $this->news_id = (int) $a_news_id; - } - - /** - * Build ajax hash for current (object/node) properties - * - * @return string - */ - function getAjaxHash() - { - return self::buildAjaxHash($this->node_type, $this->node_id, $this->obj_type, - $this->obj_id, $this->sub_type, $this->sub_id, $this->news_id); - } - - /** - * Build ajax hash - * - * @param int $a_node_type - * @param int $a_node_id - * @param string $a_obj_type - * @param int $a_obj_id - * @param string $a_sub_type - * @param int $a_sub_id - * @return string - */ - static function buildAjaxHash($a_node_type, $a_node_id, $a_obj_type, $a_obj_id, $a_sub_type = null, $a_sub_id = null, - $a_news_id = 0) - { - return $a_node_type.";".$a_node_id.";".$a_obj_type.";". - $a_obj_id.";".$a_sub_type.";".$a_sub_id.";".$a_news_id; - } - - /** - * (Re-)Build instance from ajax call - * - * @return object - */ - static function getInstanceFromAjaxCall() - { - global $DIC; + $this->ctrl = $DIC->ctrl(); + $this->settings = $DIC->settings(); + $this->node_type = (int) $a_node_type; + $this->access_handler = $a_access_handler; + $this->obj_type = (string) $a_obj_type; + $this->node_id = (int) $a_node_id; + $this->obj_id = (int) $a_obj_id; + $this->news_id = (int) $a_news_id; + } + + /** + * Build ajax hash for current (object/node) properties + * + * @return string + */ + public function getAjaxHash() + { + return self::buildAjaxHash( + $this->node_type, + $this->node_id, + $this->obj_type, + $this->obj_id, + $this->sub_type, + $this->sub_id, + $this->news_id + ); + } + + /** + * Build ajax hash + * + * @param int $a_node_type + * @param int $a_node_id + * @param string $a_obj_type + * @param int $a_obj_id + * @param string $a_sub_type + * @param int $a_sub_id + * @return string + */ + public static function buildAjaxHash( + $a_node_type, + $a_node_id, + $a_obj_type, + $a_obj_id, + $a_sub_type = null, + $a_sub_id = null, + $a_news_id = 0 + ) { + return $a_node_type . ";" . $a_node_id . ";" . $a_obj_type . ";" . + $a_obj_id . ";" . $a_sub_type . ";" . $a_sub_id . ";" . $a_news_id; + } + + /** + * (Re-)Build instance from ajax call + * + * @return object + */ + public static function getInstanceFromAjaxCall() + { + global $DIC; - $ilAccess = $DIC->access(); - $ilUser = $DIC->user(); - if(isset($_GET["cadh"])) - { - $parts = explode(";", (string)$_GET["cadh"]); - - $node_type = $parts[0]; - $node_id = $parts[1]; - $obj_type = $parts[2]; - $obj_id = $parts[3]; - $sub_type = $parts[4]; - $sub_id = $parts[5]; - $news_id = $parts[6]; - - switch($node_type) - { - case self::TYPE_REPOSITORY: - $access_handler = $ilAccess; - break; - - case self::TYPE_WORKSPACE: - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - $tree = new ilWorkspaceTree($ilUser->getId()); - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; - $access_handler = new ilWorkspaceAccessHandler($tree); - break; - - default: - return null; - } - - $dispatcher = new self($node_type, $access_handler, $obj_type, $node_id, $obj_id, $news_id); - - if($sub_type && $sub_id) - { - $dispatcher->setSubObject($sub_type, $sub_id); - } + $ilAccess = $DIC->access(); + $ilUser = $DIC->user(); + if (isset($_GET["cadh"])) { + $parts = explode(";", (string) $_GET["cadh"]); + + $node_type = $parts[0]; + $node_id = $parts[1]; + $obj_type = $parts[2]; + $obj_id = $parts[3]; + $sub_type = $parts[4]; + $sub_id = $parts[5]; + $news_id = $parts[6]; + + switch ($node_type) { + case self::TYPE_REPOSITORY: + $access_handler = $ilAccess; + break; + + case self::TYPE_WORKSPACE: + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + $tree = new ilWorkspaceTree($ilUser->getId()); + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; + $access_handler = new ilWorkspaceAccessHandler($tree); + break; + + default: + return null; + } + + $dispatcher = new self($node_type, $access_handler, $obj_type, $node_id, $obj_id, $news_id); + + if ($sub_type && $sub_id) { + $dispatcher->setSubObject($sub_type, $sub_id); + } // poll comments have specific settings - if($node_type == self::TYPE_REPOSITORY && $obj_type != "poll") - { - $dispatcher->enableCommentsSettings(true); - } - - return $dispatcher; - } - } - - function executeCommand() - { - $ilCtrl = $this->ctrl; - $ilSetting = $this->settings; + if ($node_type == self::TYPE_REPOSITORY && $obj_type != "poll") { + $dispatcher->enableCommentsSettings(true); + } + + return $dispatcher; + } + } + + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $ilSetting = $this->settings; - // check access for object - if ($this->node_id && - !$this->access_handler->checkAccess("visible", "", $this->node_id) && - !$this->access_handler->checkAccess("read", "", $this->node_id)) - { - exit(); - } - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd(); - - $ilCtrl->saveParameter($this, "cadh"); - - switch($next_class) - { - case "ilnotegui": - - $obj_type = $this->obj_type; - if($this->sub_type) - { - $obj_type = $this->sub_type; - } - - include_once "Services/Notes/classes/class.ilNoteGUI.php"; - $note_gui = new ilNoteGUI($this->obj_id, $this->sub_id, $obj_type, false, $this->news_id); - $note_gui->enablePrivateNotes(true); - - $has_write = $this->access_handler->checkAccess("write", "", $this->node_id); - if($has_write && $ilSetting->get("comments_del_tutor", 1)) - { - $note_gui->enablePublicNotesDeletion(true); - } - - // comments cannot be turned off globally - if($this->enable_comments_settings) - { - // should only be shown if active or permission to toggle - if($has_write || - $this->access_handler->checkAccess("edit_permissions", "", $this->node_id)) - { - $note_gui->enableCommentsSettings(); - } - } - /* this is different to the info screen but we need this - for sub-object action menus, e.g. wiki page */ - else if($this->sub_id) - { - $note_gui->enablePublicNotes(true); - } + // check access for object + if ($this->node_id && + !$this->access_handler->checkAccess("visible", "", $this->node_id) && + !$this->access_handler->checkAccess("read", "", $this->node_id)) { + exit(); + } + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd(); + + $ilCtrl->saveParameter($this, "cadh"); + + switch ($next_class) { + case "ilnotegui": + + $obj_type = $this->obj_type; + if ($this->sub_type) { + $obj_type = $this->sub_type; + } + + include_once "Services/Notes/classes/class.ilNoteGUI.php"; + $note_gui = new ilNoteGUI($this->obj_id, $this->sub_id, $obj_type, false, $this->news_id); + $note_gui->enablePrivateNotes(true); + + $has_write = $this->access_handler->checkAccess("write", "", $this->node_id); + if ($has_write && $ilSetting->get("comments_del_tutor", 1)) { + $note_gui->enablePublicNotesDeletion(true); + } + + // comments cannot be turned off globally + if ($this->enable_comments_settings) { + // should only be shown if active or permission to toggle + if ($has_write || + $this->access_handler->checkAccess("edit_permissions", "", $this->node_id)) { + $note_gui->enableCommentsSettings(); + } + } + /* this is different to the info screen but we need this + for sub-object action menus, e.g. wiki page */ + elseif ($this->sub_id) { + $note_gui->enablePublicNotes(true); + } - $ilCtrl->forwardCommand($note_gui); - break; + $ilCtrl->forwardCommand($note_gui); + break; - case "iltagginggui": - include_once "Services/Tagging/classes/class.ilTaggingGUI.php"; - $tags_gui = new ilTaggingGUI($this->node_id); - $tags_gui->setObject($this->obj_id, $this->obj_type); - $ilCtrl->forwardCommand($tags_gui); - break; - - case "ilobjectactivationgui": - $ilCtrl->setParameter($this, "parent_id", (int)$_REQUEST['parent_id']); - include_once 'Services/Object/classes/class.ilObjectActivationGUI.php'; - $act_gui = new ilObjectActivationGUI((int)$_REQUEST['parent_id'],$this->node_id); - $ilCtrl->forwardCommand($act_gui); - break; - - case "ilratinggui": - include_once("./Services/Rating/classes/class.ilRatingGUI.php"); - $rating_gui = new ilRatingGUI(); - if(!$_GET["rnsb"]) - { - $rating_gui->setObject($this->obj_id, $this->obj_type, $this->sub_id, $this->sub_type); - } - else - { - // coming from headaction ignore sub-objects - $rating_gui->setObject($this->obj_id, $this->obj_type); - } - $ilCtrl->forwardCommand($rating_gui); - if($this->rating_callback) - { - // as rating in categories is form-based we need to redirect - // somewhere after saving - $ilCtrl->redirect($this->rating_callback[0], $this->rating_callback[1]); - } - break; - - default: - break; - } - - exit(); - } - - /** - * Set sub object attributes - * - * @param string $a_sub_obj_type - * @param int $a_sub_obj_id - */ - function setSubObject($a_sub_obj_type, $a_sub_obj_id) - { - $this->sub_type = (string)$a_sub_obj_type; - $this->sub_id = (int)$a_sub_obj_id; - } - - /** - * Toggle comments settings - * - * @param bool $a_value - */ - function enableCommentsSettings($a_value) - { - $this->enable_comments_settings = (bool)$a_value; - } - - /** - * Add callback for rating gui - * - * @param object $a_gui - * @param string $a_cmd - */ - function setRatingCallback($a_gui, $a_cmd) - { - $this->rating_callback = array($a_gui, $a_cmd); - } - - /** - * Set header action menu - */ - function initHeaderAction() - { - // check access for object - if ($this->node_id && - !$this->access_handler->checkAccess("visible", "", $this->node_id) && - !$this->access_handler->checkAccess("read", "", $this->node_id)) - { - return; - } - - include_once 'Services/Object/classes/class.ilObjectListGUIFactory.php'; - $this->header_action = ilObjectListGUIFactory::_getListGUIByType( - $this->obj_type, - ($this->node_type == self::TYPE_REPOSITORY) - ? ilObjectListGUI::CONTEXT_REPOSITORY - : ilObjectListGUI::CONTEXT_WORKSPACE - ); - - // remove all currently unwanted actions - $this->header_action->enableCopy(false); - $this->header_action->enableCut(false); - $this->header_action->enableDelete(false); - $this->header_action->enableLink(false); - $this->header_action->enableInfoscreen(false); - $this->header_action->enableTimings(false); - $this->header_action->enableSubscribe($this->node_type == self::TYPE_REPOSITORY); - - $this->header_action->initItem($this->node_id, $this->obj_id); - $this->header_action->setHeaderSubObject($this->sub_type, $this->sub_id); - $this->header_action->setAjaxHash($this->getAjaxHash()); - - return $this->header_action; - } + case "iltagginggui": + include_once "Services/Tagging/classes/class.ilTaggingGUI.php"; + $tags_gui = new ilTaggingGUI($this->node_id); + $tags_gui->setObject($this->obj_id, $this->obj_type); + $ilCtrl->forwardCommand($tags_gui); + break; + + case "ilobjectactivationgui": + $ilCtrl->setParameter($this, "parent_id", (int) $_REQUEST['parent_id']); + include_once 'Services/Object/classes/class.ilObjectActivationGUI.php'; + $act_gui = new ilObjectActivationGUI((int) $_REQUEST['parent_id'], $this->node_id); + $ilCtrl->forwardCommand($act_gui); + break; + + case "ilratinggui": + include_once("./Services/Rating/classes/class.ilRatingGUI.php"); + $rating_gui = new ilRatingGUI(); + if (!$_GET["rnsb"]) { + $rating_gui->setObject($this->obj_id, $this->obj_type, $this->sub_id, $this->sub_type); + } else { + // coming from headaction ignore sub-objects + $rating_gui->setObject($this->obj_id, $this->obj_type); + } + $ilCtrl->forwardCommand($rating_gui); + if ($this->rating_callback) { + // as rating in categories is form-based we need to redirect + // somewhere after saving + $ilCtrl->redirect($this->rating_callback[0], $this->rating_callback[1]); + } + break; + + default: + break; + } + + exit(); + } + + /** + * Set sub object attributes + * + * @param string $a_sub_obj_type + * @param int $a_sub_obj_id + */ + public function setSubObject($a_sub_obj_type, $a_sub_obj_id) + { + $this->sub_type = (string) $a_sub_obj_type; + $this->sub_id = (int) $a_sub_obj_id; + } + + /** + * Toggle comments settings + * + * @param bool $a_value + */ + public function enableCommentsSettings($a_value) + { + $this->enable_comments_settings = (bool) $a_value; + } + + /** + * Add callback for rating gui + * + * @param object $a_gui + * @param string $a_cmd + */ + public function setRatingCallback($a_gui, $a_cmd) + { + $this->rating_callback = array($a_gui, $a_cmd); + } + + /** + * Set header action menu + */ + public function initHeaderAction() + { + // check access for object + if ($this->node_id && + !$this->access_handler->checkAccess("visible", "", $this->node_id) && + !$this->access_handler->checkAccess("read", "", $this->node_id)) { + return; + } + + include_once 'Services/Object/classes/class.ilObjectListGUIFactory.php'; + $this->header_action = ilObjectListGUIFactory::_getListGUIByType( + $this->obj_type, + ($this->node_type == self::TYPE_REPOSITORY) + ? ilObjectListGUI::CONTEXT_REPOSITORY + : ilObjectListGUI::CONTEXT_WORKSPACE + ); + + // remove all currently unwanted actions + $this->header_action->enableCopy(false); + $this->header_action->enableCut(false); + $this->header_action->enableDelete(false); + $this->header_action->enableLink(false); + $this->header_action->enableInfoscreen(false); + $this->header_action->enableTimings(false); + $this->header_action->enableSubscribe($this->node_type == self::TYPE_REPOSITORY); + + $this->header_action->initItem($this->node_id, $this->obj_id); + $this->header_action->setHeaderSubObject($this->sub_type, $this->sub_id); + $this->header_action->setAjaxHash($this->getAjaxHash()); + + return $this->header_action; + } } - -?> \ No newline at end of file diff --git a/Services/Object/classes/class.ilDummyAccessHandler.php b/Services/Object/classes/class.ilDummyAccessHandler.php index f53572dc0dd22bfd6840d8bcb0306d1eec05056b..48c9f9f568d2a2c26f6d89ac9d3fb540331879e8 100644 --- a/Services/Object/classes/class.ilDummyAccessHandler.php +++ b/Services/Object/classes/class.ilDummyAccessHandler.php @@ -12,19 +12,17 @@ */ class ilDummyAccessHandler { - /** - * check access for an object - * - * @param string $a_permission - * @param string $a_cmd - * @param int $a_node_id - * @param string $a_type (optional) - * @return bool - */ - public function checkAccess($a_permission, $a_cmd, $a_node_id, $a_type = "") - { - return true; - } + /** + * check access for an object + * + * @param string $a_permission + * @param string $a_cmd + * @param int $a_node_id + * @param string $a_type (optional) + * @return bool + */ + public function checkAccess($a_permission, $a_cmd, $a_node_id, $a_type = "") + { + return true; + } } - -?> \ No newline at end of file diff --git a/Services/Object/classes/class.ilListItemAccessCache.php b/Services/Object/classes/class.ilListItemAccessCache.php index 01d10f76d6a5a675196005fbb78aa82d1ab21ffd..ac694c0312695bad6a4c6c9fcb463d6fb0205655 100644 --- a/Services/Object/classes/class.ilListItemAccessCache.php +++ b/Services/Object/classes/class.ilListItemAccessCache.php @@ -12,76 +12,77 @@ include_once("./Services/Cache/classes/class.ilCache.php"); */ class ilListItemAccessCache extends ilCache { - /** - * @var ilSetting - */ - protected $settings; + /** + * @var ilSetting + */ + protected $settings; - static $disabled = false; - - /** - * Constructor - * - * @param - * @return - */ - function __construct() - { - global $DIC; + public static $disabled = false; + + /** + * Constructor + * + * @param + * @return + */ + public function __construct() + { + global $DIC; - $this->settings = $DIC->settings(); - $ilSetting = $DIC->settings(); - parent::__construct("ServicesObject", "CheckAccess", false); -// $this->setExpiresAfter($ilSetting->get("rep_cache") * 60); - $this->setExpiresAfter(0); -// if ((int) $ilSetting->get("rep_cache") == 0) - if (true) - { - self::$disabled = true; - } - } - - /** - * Check if cache is disabled - * @return - */ - public function isDisabled() - { - return self::$disabled or parent::isDisabled(); - } - - - /** - * Read an entry - */ - function readEntry($a_id) - { - if (!$this->isDisabled()) - { - return parent::readEntry($a_id); - } - return false; - } - - - /** - * Id is user_id:ref_id, we store ref_if additionally - */ - function storeEntry($a_id, $a_value, $a_ref_id = 0, $a_int_key2 = null, - $a_text_key1 = null, $a_text_key2 = null) - { - if (!$this->isDisabled()) - { - parent::storeEntry($a_id, $a_value, $a_ref_id); - } - } + $this->settings = $DIC->settings(); + $ilSetting = $DIC->settings(); + parent::__construct("ServicesObject", "CheckAccess", false); + // $this->setExpiresAfter($ilSetting->get("rep_cache") * 60); + $this->setExpiresAfter(0); + // if ((int) $ilSetting->get("rep_cache") == 0) + if (true) { + self::$disabled = true; + } + } + + /** + * Check if cache is disabled + * @return + */ + public function isDisabled() + { + return self::$disabled or parent::isDisabled(); + } + + + /** + * Read an entry + */ + public function readEntry($a_id) + { + if (!$this->isDisabled()) { + return parent::readEntry($a_id); + } + return false; + } + + + /** + * Id is user_id:ref_id, we store ref_if additionally + */ + public function storeEntry( + $a_id, + $a_value, + $a_ref_id = 0, + $a_int_key2 = null, + $a_text_key1 = null, + $a_text_key2 = null + ) { + if (!$this->isDisabled()) { + parent::storeEntry($a_id, $a_value, $a_ref_id); + } + } - /** - * This one can be called, e.g. - */ - function deleteByRefId($a_ref_id) - { - parent::deleteByAdditionalKeys($a_ref_id); - } + /** + * This one can be called, e.g. + */ + public function deleteByRefId($a_ref_id) + { + parent::deleteByAdditionalKeys($a_ref_id); + } } -?> diff --git a/Services/Object/classes/class.ilObjClipboardTableGUI.php b/Services/Object/classes/class.ilObjClipboardTableGUI.php index 5380a76ab46f04708efc53b7e2750ac2f7ea5e6f..ae3938f0d8dcf05a01439c61f25b9269714f76f9 100644 --- a/Services/Object/classes/class.ilObjClipboardTableGUI.php +++ b/Services/Object/classes/class.ilObjClipboardTableGUI.php @@ -5,7 +5,7 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); /** - * TableGUI class for + * TableGUI class for * * @author Alex Killing * @version $Id\$ @@ -14,46 +14,46 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilObjClipboardTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd) - { - 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->setTitle($lng->txt("clipboard")); - - $this->addColumn("", "", "1"); - $this->addColumn($this->lng->txt("title"), "title"); - $this->addColumn($this->lng->txt("action")); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.obj_cliboard_row.html", "Services/Object"); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; -//var_dump($a_set); - $this->tpl->setVariable("ICON", ilUtil::img(ilObject::_getIcon($a_set["obj_id"], "tiny"), - $a_set["type_txt"])); - $this->tpl->setVariable("TITLE", $a_set["title"]); - $this->tpl->setVariable("CMD", $a_set["cmd"]); - } + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd) + { + 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->setTitle($lng->txt("clipboard")); + + $this->addColumn("", "", "1"); + $this->addColumn($this->lng->txt("title"), "title"); + $this->addColumn($this->lng->txt("action")); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.obj_cliboard_row.html", "Services/Object"); + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + //var_dump($a_set); + $this->tpl->setVariable("ICON", ilUtil::img( + ilObject::_getIcon($a_set["obj_id"], "tiny"), + $a_set["type_txt"] + )); + $this->tpl->setVariable("TITLE", $a_set["title"]); + $this->tpl->setVariable("CMD", $a_set["cmd"]); + } } -?> \ No newline at end of file diff --git a/Services/Object/classes/class.ilObjObjectFolder.php b/Services/Object/classes/class.ilObjObjectFolder.php index b77dc72375d405506e55db78460b7684200da722..6ec20f18abf91b092a4b79e0f302fa4ca44f6701 100755 --- a/Services/Object/classes/class.ilObjObjectFolder.php +++ b/Services/Object/classes/class.ilObjObjectFolder.php @@ -1,24 +1,24 @@ type = "objf"; - parent::__construct($a_id,$a_call_by_reference); - } + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id, $a_call_by_reference = true) + { + $this->type = "objf"; + parent::__construct($a_id, $a_call_by_reference); + } - /** - * delete objectfolder and all related data - * DISABLED - * @access public - * @return boolean true if all object data were removed; false if only a references were removed - */ - function delete() - { - // DISABLED - return false; + /** + * delete objectfolder and all related data + * DISABLED + * @access public + * @return boolean true if all object data were removed; false if only a references were removed + */ + public function delete() + { + // DISABLED + return false; - // always call parent delete function first!! - if (!parent::delete()) - { - return false; - } - - // put here objectfolder specific stuff - - // always call parent delete function at the end!! - return true; - } + // always call parent delete function first!! + if (!parent::delete()) { + return false; + } + + // put here objectfolder specific stuff + + // always call parent delete function at the end!! + return true; + } } // END class.ilObjObjectFolder -?> diff --git a/Services/Object/classes/class.ilObjObjectFolderAccess.php b/Services/Object/classes/class.ilObjObjectFolderAccess.php index a89812ea8e5f812fd1e2eac23995b7c1b3419852..36560e99dec8fc1f4b872520adcee686c66f7d79 100644 --- a/Services/Object/classes/class.ilObjObjectFolderAccess.php +++ b/Services/Object/classes/class.ilObjObjectFolderAccess.php @@ -1,24 +1,24 @@ diff --git a/Services/Object/classes/class.ilObjObjectFolderGUI.php b/Services/Object/classes/class.ilObjObjectFolderGUI.php index f0c528ca34a382bfc8ee2bfd9db32699e51d442d..2594d47fa371e4ea34503ffdcca7e7f4a9e6af6c 100755 --- a/Services/Object/classes/class.ilObjObjectFolderGUI.php +++ b/Services/Object/classes/class.ilObjObjectFolderGUI.php @@ -1,24 +1,24 @@ * $Id$ -* +* * @ilCtrl_Calls ilObjObjectFolderGUI: ilPermissionGUI * * @extends ilObjectGUI @@ -37,261 +37,260 @@ require_once "./Services/Object/classes/class.ilObjectGUI.php"; class ilObjObjectFolderGUI extends ilObjectGUI { - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * Constructor - * - * @param array basic object data - * @param integer ref_id or obj_id (depends on referenced-flag) - * @param boolean true: treat id as ref_id; false: treat id as obj_id - * @access public - */ - function __construct($a_data,$a_id,$a_call_by_reference) - { - global $DIC; - - $this->rbacsystem = $DIC->rbac()->system(); - $this->error = $DIC["ilErr"]; - $this->type = "objf"; - parent::__construct($a_data,$a_id,$a_call_by_reference,false); - } - - /** - * list childs of current object - * - * @access public - */ - function viewObject() - { - $rbacsystem = $this->rbacsystem; - $ilErr = $this->error; - - if (!$rbacsystem->checkAccess("visible,read",$this->object->getRefId())) - { - $ilErr->raiseError($this->lng->txt("permission_denied"), $ilErr->MESSAGE); - } - - //prepare objectlist - $this->data = array(); - $this->data["data"] = array(); - $this->data["ctrl"] = array(); - - $this->data["cols"] = array("type","title","last_change"); - - $this->maxcount = count($this->data["data"]); - - // now compute control information - foreach ($this->data["data"] as $key => $val) - { - $this->data["ctrl"][$key] = array( - "ref_id" => $this->id, - "obj_id" => $val["obj_id"], - "type" => $val["type"], - ); - - unset($this->data["data"][$key]["obj_id"]); - $this->data["data"][$key]["last_change"] = ilDatePresentation::formatDate(new ilDateTime($this->data["data"][$key]["last_change"],IL_CAL_DATETIME)); - } - - $this->displayList(); - } - - /** - * display object list - * - * @access public - */ - function displayList() - { - include_once "./Services/Table/classes/class.ilTableGUI.php"; - return; - - // load template for table - $this->tpl->addBlockfile("ADM_CONTENT", "adm_content", "tpl.table.html"); - - // load template for table content data - $this->tpl->addBlockfile("TBL_CONTENT", "tbl_content", "tpl.obj_tbl_rows.html"); - - $num = 0; - - $obj_str = ($this->call_by_reference) ? "" : "&obj_id=".$this->obj_id; - $this->tpl->setVariable("FORMACTION", - $this->ctrl->getFormAction($this)); - - // create table - $tbl = new ilTableGUI(); - - // title & header columns - $tbl->setTitle($this->object->getTitle()); - - foreach ($this->data["cols"] as $val) - { - $header_names[] = $this->lng->txt($val); - } - - $tbl->setHeaderNames($header_names); - - //$header_params = array("ref_id" => $this->ref_id); - $header_params = $this->ctrl->getParameterArray($this, "view"); - $tbl->setHeaderVars($this->data["cols"],$header_params); - $tbl->setColumnWidth(array("15","75%","25%")); - - // control - $tbl->setOrderColumn($_GET["sort_by"]); - $tbl->setOrderDirection($_GET["sort_order"]); - $tbl->setLimit($_GET["limit"]); - $tbl->setOffset($_GET["offset"]); - $tbl->setMaxCount($this->maxcount); - - // footer - $tbl->setFooter("tblfooter",$this->lng->txt("previous"),$this->lng->txt("next")); - //$tbl->disable("footer"); - - // render table - $tbl->render(); - - if (is_array($this->data["data"][0])) - { - //table cell - for ($i=0; $i < count($this->data["data"]); $i++) - { - $data = $this->data["data"][$i]; - $ctrl = $this->data["ctrl"][$i]; - - // color changing - $css_row = ilUtil::switchColor($i+1,"tblrow1","tblrow2"); - - $this->tpl->setCurrentBlock("table_cell"); - $this->tpl->setVariable("CELLSTYLE", "tblrow1"); - $this->tpl->parseCurrentBlock(); - - foreach ($data as $key => $val) - { - //build link - /* - - $n = 0; - - foreach ($ctrl as $key2 => $val2) - { - $link .= $key2."=".$val2; - - if ($n < count($ctrl)-1) - { - $link .= "&"; - $n++; - } - } - - if ($key == "title") - { - $name_field = explode("#separator#",$val); - } - - if ($key == "title" || $key == "type") - { - $this->tpl->setCurrentBlock("begin_link"); - $this->tpl->setVariable("LINK_TARGET", $link); - - $this->tpl->parseCurrentBlock(); - $this->tpl->touchBlock("end_link"); - } - - $this->tpl->setCurrentBlock("text"); - - if ($key == "type") - { - $val = ilUtil::getImageTagByType($val,$this->tpl->tplPath); - } - - if ($key == "title") - { - $this->tpl->setVariable("TEXT_CONTENT", $name_field[0]); - - $this->tpl->setCurrentBlock("subtitle"); - $this->tpl->setVariable("DESC", $name_field[1]); - $this->tpl->parseCurrentBlock(); - } - else - { - $this->tpl->setVariable("TEXT_CONTENT", $val); - } - - $this->tpl->parseCurrentBlock(); - - $this->tpl->setCurrentBlock("table_cell"); - $this->tpl->parseCurrentBlock(); - */ - } //foreach - - $this->tpl->setCurrentBlock("tbl_content"); - $this->tpl->setVariable("CSS_ROW", $css_row); - $this->tpl->parseCurrentBlock(); - } //for - - } //if is_array - else - { - $this->tpl->setCurrentBlock("notfound"); - $this->tpl->setVariable("TXT_OBJECT_NOT_FOUND", $this->lng->txt("obj_not_found")); - $this->tpl->setVariable("NUM_COLS", $num); - $this->tpl->parseCurrentBlock(); - } - } - - function executeCommand() - { - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - $this->prepareOutput(); - - switch($next_class) - { - case 'ilpermissiongui': - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $ret =& $this->ctrl->forwardCommand($perm_gui); - break; - - default: - if(!$cmd) - { - $cmd = "view"; - } - $cmd .= "Object"; - $this->$cmd(); - - break; - } - return true; - } - - /** - * get tabs - * @access public - * @param object tabs gui object - */ - function getTabs() - { - $rbacsystem = $this->rbacsystem; - - if ($rbacsystem->checkAccess('edit_permission',$this->object->getRefId())) - { - $this->tabs_gui->addTarget("settings", - $this->ctrl->getLinkTarget($this, "view"), array("view",""), "", ""); - - $this->tabs_gui->addTarget("perm_settings", - $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm"), array("perm","info","owner"), 'ilpermissiongui'); - } - } + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * Constructor + * + * @param array basic object data + * @param integer ref_id or obj_id (depends on referenced-flag) + * @param boolean true: treat id as ref_id; false: treat id as obj_id + * @access public + */ + public function __construct($a_data, $a_id, $a_call_by_reference) + { + global $DIC; + + $this->rbacsystem = $DIC->rbac()->system(); + $this->error = $DIC["ilErr"]; + $this->type = "objf"; + parent::__construct($a_data, $a_id, $a_call_by_reference, false); + } + + /** + * list childs of current object + * + * @access public + */ + public function viewObject() + { + $rbacsystem = $this->rbacsystem; + $ilErr = $this->error; + + if (!$rbacsystem->checkAccess("visible,read", $this->object->getRefId())) { + $ilErr->raiseError($this->lng->txt("permission_denied"), $ilErr->MESSAGE); + } + + //prepare objectlist + $this->data = array(); + $this->data["data"] = array(); + $this->data["ctrl"] = array(); + + $this->data["cols"] = array("type","title","last_change"); + + $this->maxcount = count($this->data["data"]); + + // now compute control information + foreach ($this->data["data"] as $key => $val) { + $this->data["ctrl"][$key] = array( + "ref_id" => $this->id, + "obj_id" => $val["obj_id"], + "type" => $val["type"], + ); + + unset($this->data["data"][$key]["obj_id"]); + $this->data["data"][$key]["last_change"] = ilDatePresentation::formatDate(new ilDateTime($this->data["data"][$key]["last_change"], IL_CAL_DATETIME)); + } + + $this->displayList(); + } + + /** + * display object list + * + * @access public + */ + public function displayList() + { + include_once "./Services/Table/classes/class.ilTableGUI.php"; + return; + + // load template for table + $this->tpl->addBlockfile("ADM_CONTENT", "adm_content", "tpl.table.html"); + + // load template for table content data + $this->tpl->addBlockfile("TBL_CONTENT", "tbl_content", "tpl.obj_tbl_rows.html"); + + $num = 0; + + $obj_str = ($this->call_by_reference) ? "" : "&obj_id=" . $this->obj_id; + $this->tpl->setVariable( + "FORMACTION", + $this->ctrl->getFormAction($this) + ); + + // create table + $tbl = new ilTableGUI(); + + // title & header columns + $tbl->setTitle($this->object->getTitle()); + + foreach ($this->data["cols"] as $val) { + $header_names[] = $this->lng->txt($val); + } + + $tbl->setHeaderNames($header_names); + + //$header_params = array("ref_id" => $this->ref_id); + $header_params = $this->ctrl->getParameterArray($this, "view"); + $tbl->setHeaderVars($this->data["cols"], $header_params); + $tbl->setColumnWidth(array("15","75%","25%")); + + // control + $tbl->setOrderColumn($_GET["sort_by"]); + $tbl->setOrderDirection($_GET["sort_order"]); + $tbl->setLimit($_GET["limit"]); + $tbl->setOffset($_GET["offset"]); + $tbl->setMaxCount($this->maxcount); + + // footer + $tbl->setFooter("tblfooter", $this->lng->txt("previous"), $this->lng->txt("next")); + //$tbl->disable("footer"); + + // render table + $tbl->render(); + + if (is_array($this->data["data"][0])) { + //table cell + for ($i=0; $i < count($this->data["data"]); $i++) { + $data = $this->data["data"][$i]; + $ctrl = $this->data["ctrl"][$i]; + + // color changing + $css_row = ilUtil::switchColor($i+1, "tblrow1", "tblrow2"); + + $this->tpl->setCurrentBlock("table_cell"); + $this->tpl->setVariable("CELLSTYLE", "tblrow1"); + $this->tpl->parseCurrentBlock(); + + foreach ($data as $key => $val) { + //build link + /* + + $n = 0; + + foreach ($ctrl as $key2 => $val2) + { + $link .= $key2."=".$val2; + + if ($n < count($ctrl)-1) + { + $link .= "&"; + $n++; + } + } + + if ($key == "title") + { + $name_field = explode("#separator#",$val); + } + + if ($key == "title" || $key == "type") + { + $this->tpl->setCurrentBlock("begin_link"); + $this->tpl->setVariable("LINK_TARGET", $link); + + $this->tpl->parseCurrentBlock(); + $this->tpl->touchBlock("end_link"); + } + + $this->tpl->setCurrentBlock("text"); + + if ($key == "type") + { + $val = ilUtil::getImageTagByType($val,$this->tpl->tplPath); + } + + if ($key == "title") + { + $this->tpl->setVariable("TEXT_CONTENT", $name_field[0]); + + $this->tpl->setCurrentBlock("subtitle"); + $this->tpl->setVariable("DESC", $name_field[1]); + $this->tpl->parseCurrentBlock(); + } + else + { + $this->tpl->setVariable("TEXT_CONTENT", $val); + } + + $this->tpl->parseCurrentBlock(); + + $this->tpl->setCurrentBlock("table_cell"); + $this->tpl->parseCurrentBlock(); + */ + } //foreach + + $this->tpl->setCurrentBlock("tbl_content"); + $this->tpl->setVariable("CSS_ROW", $css_row); + $this->tpl->parseCurrentBlock(); + } //for + } //if is_array + else { + $this->tpl->setCurrentBlock("notfound"); + $this->tpl->setVariable("TXT_OBJECT_NOT_FOUND", $this->lng->txt("obj_not_found")); + $this->tpl->setVariable("NUM_COLS", $num); + $this->tpl->parseCurrentBlock(); + } + } + + public function executeCommand() + { + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + $this->prepareOutput(); + + switch ($next_class) { + case 'ilpermissiongui': + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $ret =&$this->ctrl->forwardCommand($perm_gui); + break; + + default: + if (!$cmd) { + $cmd = "view"; + } + $cmd .= "Object"; + $this->$cmd(); + + break; + } + return true; + } + + /** + * get tabs + * @access public + * @param object tabs gui object + */ + public function getTabs() + { + $rbacsystem = $this->rbacsystem; + + if ($rbacsystem->checkAccess('edit_permission', $this->object->getRefId())) { + $this->tabs_gui->addTarget( + "settings", + $this->ctrl->getLinkTarget($this, "view"), + array("view",""), + "", + "" + ); + + $this->tabs_gui->addTarget( + "perm_settings", + $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm"), + array("perm","info","owner"), + 'ilpermissiongui' + ); + } + } } // END class.ilObjObjectFolderGUI -?> diff --git a/Services/Object/classes/class.ilObjTypeDefinition.php b/Services/Object/classes/class.ilObjTypeDefinition.php index 4770a91b4afcedcb87048f8bc581227ef6246c95..6d1b31b1731a7591b6ca43d9fcaea96708a5886d 100755 --- a/Services/Object/classes/class.ilObjTypeDefinition.php +++ b/Services/Object/classes/class.ilObjTypeDefinition.php @@ -1,35 +1,35 @@ +* @author Stefan Meyer * $Id$ -* +* * @extends ilObject */ @@ -37,14 +37,13 @@ require_once "./Services/Object/classes/class.ilObject.php"; class ilObjTypeDefinition extends ilObject { - /** - * Constructor - * @access public - */ - public function __construct($a_id = 0,$a_call_by_reference = false) - { - parent::__construct($a_id,$a_call_by_reference); - $this->type = "typ"; - } + /** + * Constructor + * @access public + */ + public function __construct($a_id = 0, $a_call_by_reference = false) + { + parent::__construct($a_id, $a_call_by_reference); + $this->type = "typ"; + } } -?> diff --git a/Services/Object/classes/class.ilObjTypeDefinitionGUI.php b/Services/Object/classes/class.ilObjTypeDefinitionGUI.php index 53fc67e644d4e3d8b07429dfb1bd91a5360620f0..54feffe6a51c1e25fb98866f77ac8124fd6d745b 100755 --- a/Services/Object/classes/class.ilObjTypeDefinitionGUI.php +++ b/Services/Object/classes/class.ilObjTypeDefinitionGUI.php @@ -4,9 +4,9 @@ /** * Class ilObjTypeDefinitionGUI -* +* * handles operation assignment to objects (ONLY FOR TESTING PURPOSES!) -* +* * @author Stefan Meyer * $Id$Id: class.ilObjTypeDefinitionGUI.php,v 1.14 2005/11/21 17:12:08 shofmann Exp $ * @@ -17,448 +17,417 @@ require_once "./Services/Object/classes/class.ilObjectGUI.php"; class ilObjTypeDefinitionGUI extends ilObjectGUI { - /** - * @var ilRbacAdmin - */ - protected $rbacadmin; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * Constructor - * - * @access public - */ - public function __construct($a_data,$a_id,$a_call_by_reference) - { - global $DIC; - - $this->rbacadmin = $DIC->rbac()->admin(); - $this->rbacreview = $DIC->rbac()->review(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->error = $DIC["ilErr"]; - $this->type = "typ"; - parent::__construct($a_data,$a_id,$a_call_by_reference); - } - - /** - * list operations of object type - * @access public - */ - function viewObject() - { - $rbacadmin = $this->rbacadmin; - $rbacreview = $this->rbacreview; - - //prepare objectlist - $this->data = array(); - $this->data["data"] = array(); - $this->data["ctrl"] = array(); - $this->data["cols"] = array("type", "operation", "description", "status"); - - $ops_valid = $rbacreview->getOperationsOnType($_GET["obj_id"]); - - if ($list = ilRbacReview::_getOperationList("",$_GET["order"], $_GET["direction"])) - { - foreach ($list as $key => $val) - { - - if (in_array($val["ops_id"],$ops_valid)) - { - $ops_status = 'enabled'; - } - else - { - $ops_status = 'disabled'; - } - - //visible data part - $this->data["data"][] = array( - "type" => "perm", - "operation" => $val["operation"], - "description" => $val["desc"], - "status" => $ops_status, - "obj_id" => $val["ops_id"] - ); - - } - } //if typedata - - $this->maxcount = count($this->data["data"]); - - // sorting array - $this->data["data"] = ilUtil::sortArray($this->data["data"],$_GET["sort_by"],$_GET["sort_order"]); - - // now compute control information - foreach ($this->data["data"] as $key => $val) - { - $this->data["ctrl"][$key] = array( - "obj_id" => $val["obj_id"], - "type" => $val["type"] - ); - - unset($this->data["data"][$key]["obj_id"]); - } - - $this->displayList(); - } - - /** - * display object list - * - * @access public - */ - function displayList() - { - include_once "./Services/Table/classes/class.ilTableGUI.php"; - - // load template for table - $this->tpl->addBlockfile("ADM_CONTENT", "adm_content", "tpl.table.html"); - // load template for table content data - $this->tpl->addBlockfile("TBL_CONTENT", "tbl_content", "tpl.obj_tbl_rows.html"); - - $num = 0; - - $obj_str = ($this->call_by_reference) ? "" : "&obj_id=".$this->obj_id; - $this->tpl->setVariable("FORMACTION", "adm_object.php?ref_id=".$this->ref_id."$obj_str&cmd=gateway"); - - // create table - $tbl = new ilTableGUI(); - - // title & header columns - $tbl->setTitle($this->lng->txt("obj_".$this->object->getType())." '".$this->object->getTitle()."'"); - - foreach ($this->data["cols"] as $val) - { - $header_names[] = $this->lng->txt($val); - } - - $tbl->setHeaderNames($header_names); - - $header_params = array("ref_id" => $this->ref_id,"obj_id" => $this->id); - $tbl->setHeaderVars($this->data["cols"],$header_params); - - // control - $tbl->setOrderColumn($_GET["sort_by"]); - $tbl->setOrderDirection($_GET["sort_order"]); - $tbl->setLimit(0); - $tbl->setOffset(0); - $tbl->setMaxCount($this->maxcount); - - // footer - $tbl->setFooter("tblfooter",$this->lng->txt("previous"),$this->lng->txt("next")); - //$tbl->disable("footer"); - - // render table - $tbl->render(); - - if (is_array($this->data["data"][0])) - { - //table cell - for ($i=0; $i < count($this->data["data"]); $i++) - { - $data = $this->data["data"][$i]; - $ctrl = $this->data["ctrl"][$i]; - - // color changing - $css_row = ilUtil::switchColor($i+1,"tblrow1","tblrow2"); - - $this->tpl->setCurrentBlock("table_cell"); - $this->tpl->setVariable("CELLSTYLE", "tblrow1"); - $this->tpl->parseCurrentBlock(); - - foreach ($data as $key => $val) - { - // color for status - if ($key == "status") - { - if ($val == "enabled") - { - $color = "green"; - } - else - { - $color = "red"; - } - - $val = "".$this->lng->txt($val).""; - } - - $this->tpl->setCurrentBlock("text"); - - if ($key == "type") - { - $val = ilUtil::getImageTagByType($val,$this->tpl->tplPath); - } - - $this->tpl->setVariable("TEXT_CONTENT", $val); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setCurrentBlock("table_cell"); - $this->tpl->parseCurrentBlock(); - - } //foreach - - $this->tpl->setCurrentBlock("tbl_content"); - $this->tpl->setVariable("CSS_ROW", $css_row); - $this->tpl->parseCurrentBlock(); - } //for - } //if is_array - } - - /** - * save (de-)activation of operations on object - * - * @access public - */ - function saveObject() - { - $rbacsystem = $this->rbacsystem; - $rbacadmin = $this->rbacadmin; - $rbacreview = $this->rbacreview; - $ilErr = $this->error; - - if (!$rbacsystem->checkAccess('edit_permission', $_GET["ref_id"])) - { - $ilErr->raiseError($this->lng->txt("permission_denied"),$ilErr->WARNING); - } - - $ops_valid = $rbacreview->getOperationsOnType($_GET["obj_id"]); - - foreach ($_POST["id"] as $ops_id => $status) - { - if ($status == 'enabled') - { - if (!in_array($ops_id,$ops_valid)) - { - $rbacadmin->assignOperationToObject($_GET["obj_id"],$ops_id); - } - } - - if ($status == 'disabled') - { - if (in_array($ops_id,$ops_valid)) - { - $rbacadmin->deassignOperationFromObject($_GET["obj_id"],$ops_id); - } - } - } - - $this->update = $this->object->update(); - - ilUtil::sendSuccess($this->lng->txt("saved_successfully"),true); - - header("Location: adm_object.php?ref_id=".$_GET["ref_id"]."&obj_id=".$_GET["obj_id"]); - exit(); - } - - - /** - * display edit form - * - * @access public - */ - function editObject() - { - $rbacsystem = $this->rbacsystem; - $rbacreview = $this->rbacreview; - $ilErr = $this->error; - - if (!$rbacsystem->checkAccess("edit_permission",$_GET["ref_id"])) - { - $ilErr->raiseError($this->lng->txt("permission_denied"), $ilErr->MESSAGE); - } - - //prepare objectlist - $this->data = array(); - $this->data["data"] = array(); - $this->data["ctrl"] = array(); - $this->data["cols"] = array("type", "operation", "description", "status"); - - $ops_valid = $rbacreview->getOperationsOnType($this->obj_id); - - if ($ops_arr = ilRbacReview::_getOperationList('', $a_order, $a_direction)) - { - $options = array("e" => "enabled","d" => "disabled"); - - foreach ($ops_arr as $key => $ops) - { - // BEGIN ROW - if (in_array($ops["ops_id"],$ops_valid)) - { - $ops_status = 'e'; - } - else - { - $ops_status = 'd'; - } - - $obj = $ops["ops_id"]; - $ops_options = ilUtil::formSelect($ops_status,"id[$obj]",$options); - - //visible data part - $this->data["data"][] = array( - "type" => "perm", - "operation" => $ops["operation"], - "description" => $ops["desc"], - "status" => $ops_status, - "status_html" => $ops_options, - "obj_id" => $val["ops_id"] - ); - } - } //if typedata - - $this->maxcount = count($this->data["data"]); - - // sorting array - $this->data["data"] = ilUtil::sortArray($this->data["data"],$_GET["sort_by"],$_GET["sort_order"]); - - // now compute control information - foreach ($this->data["data"] as $key => $val) - { - $this->data["ctrl"][$key] = array( - "obj_id" => $val["obj_id"], - "type" => $val["type"] - ); - - unset($this->data["data"][$key]["obj_id"]); - $this->data["data"][$key]["status"] = $this->data["data"][$key]["status_html"]; - unset($this->data["data"][$key]["status_html"]); - } - - // build table - include_once "./Services/Table/classes/class.ilTableGUI.php"; - - // load template for table - $this->tpl->addBlockfile("ADM_CONTENT", "adm_content", "tpl.table.html"); - // load template for table content data - $this->tpl->addBlockfile("TBL_CONTENT", "tbl_content", "tpl.obj_tbl_rows.html"); - - $num = 0; - - $obj_str = ($this->call_by_reference) ? "" : "&obj_id=".$this->obj_id; - $this->tpl->setVariable("FORMACTION", "adm_object.php?ref_id=".$this->ref_id."$obj_str&cmd=save"); - - // create table - $tbl = new ilTableGUI(); - - // title & header columns - $tbl->setTitle($this->lng->txt("edit_operations")." ".strtolower($this->lng->txt("of"))." '".$this->object->getTitle()."'"); - - foreach ($this->data["cols"] as $val) - { - $header_names[] = $this->lng->txt($val); - } - - $tbl->setHeaderNames($header_names); - - $header_params = array("ref_id" => $this->ref_id,"obj_id" => $this->id,"cmd" => "edit"); - $tbl->setHeaderVars($this->data["cols"],$header_params); - - // control - $tbl->setOrderColumn($_GET["sort_by"]); - $tbl->setOrderDirection($_GET["sort_order"]); - $tbl->setLimit(0); - $tbl->setOffset(0); - $tbl->setMaxCount($this->maxcount); - - // SHOW VALID ACTIONS - $this->tpl->setVariable("IMG_ARROW", ilUtil::getImagePath("arrow_downright.svg")); - $this->tpl->setVariable("COLUMN_COUNTS",count($this->data["cols"])); - - // footer - $tbl->setFooter("tblfooter",$this->lng->txt("previous"),$this->lng->txt("next")); - //$tbl->disable("footer"); - - // render table - $tbl->render(); - - if (is_array($this->data["data"][0])) - { - //table cell - for ($i=0; $i < count($this->data["data"]); $i++) - { - $data = $this->data["data"][$i]; - $ctrl = $this->data["ctrl"][$i]; - - // color changing - $css_row = ilUtil::switchColor($i+1,"tblrow1","tblrow2"); - - $this->tpl->setCurrentBlock("table_cell"); - $this->tpl->setVariable("CELLSTYLE", "tblrow1"); - $this->tpl->parseCurrentBlock(); - - foreach ($data as $key => $val) - { - $this->tpl->setCurrentBlock("text"); - - if ($key == "type") - { - $val = ilUtil::getImageTagByType($val,$this->tpl->tplPath); - } - - $this->tpl->setVariable("TEXT_CONTENT", $val); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setCurrentBlock("table_cell"); - $this->tpl->parseCurrentBlock(); - - } //foreach - - $this->tpl->setVariable("BTN_VALUE", $this->lng->txt("save")); - - $this->tpl->setCurrentBlock("tbl_content"); - $this->tpl->setVariable("CSS_ROW", $css_row); - $this->tpl->parseCurrentBlock(); - } //for - } //if is_array - } - - function executeCommand() - { - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - switch($next_class) - { - default: - if(!$cmd) - { - $cmd = "view"; - } - $cmd .= "Object"; - $this->$cmd(); - - break; - } - return true; - } - - /** - * get tabs - * @access public - * @param object tabs gui object - */ - function getTabs() - { - $rbacsystem = $this->rbacsystem; - - if ($rbacsystem->checkAccess('edit_permission',$this->object->getRefId())) - { - $this->tabs_gui->addTarget("settings", - $this->ctrl->getLinkTarget($this, "view"), array("view",""), "", ""); - - $this->tabs_gui->addTarget("edit_operations", - $this->ctrl->getLinkTarget($this, "edit"), "edit", "", ""); - } - } + /** + * @var ilRbacAdmin + */ + protected $rbacadmin; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * Constructor + * + * @access public + */ + public function __construct($a_data, $a_id, $a_call_by_reference) + { + global $DIC; + + $this->rbacadmin = $DIC->rbac()->admin(); + $this->rbacreview = $DIC->rbac()->review(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->error = $DIC["ilErr"]; + $this->type = "typ"; + parent::__construct($a_data, $a_id, $a_call_by_reference); + } + + /** + * list operations of object type + * @access public + */ + public function viewObject() + { + $rbacadmin = $this->rbacadmin; + $rbacreview = $this->rbacreview; + + //prepare objectlist + $this->data = array(); + $this->data["data"] = array(); + $this->data["ctrl"] = array(); + $this->data["cols"] = array("type", "operation", "description", "status"); + + $ops_valid = $rbacreview->getOperationsOnType($_GET["obj_id"]); + + if ($list = ilRbacReview::_getOperationList("", $_GET["order"], $_GET["direction"])) { + foreach ($list as $key => $val) { + if (in_array($val["ops_id"], $ops_valid)) { + $ops_status = 'enabled'; + } else { + $ops_status = 'disabled'; + } + + //visible data part + $this->data["data"][] = array( + "type" => "perm", + "operation" => $val["operation"], + "description" => $val["desc"], + "status" => $ops_status, + "obj_id" => $val["ops_id"] + ); + } + } //if typedata + + $this->maxcount = count($this->data["data"]); + + // sorting array + $this->data["data"] = ilUtil::sortArray($this->data["data"], $_GET["sort_by"], $_GET["sort_order"]); + + // now compute control information + foreach ($this->data["data"] as $key => $val) { + $this->data["ctrl"][$key] = array( + "obj_id" => $val["obj_id"], + "type" => $val["type"] + ); + + unset($this->data["data"][$key]["obj_id"]); + } + + $this->displayList(); + } + + /** + * display object list + * + * @access public + */ + public function displayList() + { + include_once "./Services/Table/classes/class.ilTableGUI.php"; + + // load template for table + $this->tpl->addBlockfile("ADM_CONTENT", "adm_content", "tpl.table.html"); + // load template for table content data + $this->tpl->addBlockfile("TBL_CONTENT", "tbl_content", "tpl.obj_tbl_rows.html"); + + $num = 0; + + $obj_str = ($this->call_by_reference) ? "" : "&obj_id=" . $this->obj_id; + $this->tpl->setVariable("FORMACTION", "adm_object.php?ref_id=" . $this->ref_id . "$obj_str&cmd=gateway"); + + // create table + $tbl = new ilTableGUI(); + + // title & header columns + $tbl->setTitle($this->lng->txt("obj_" . $this->object->getType()) . " '" . $this->object->getTitle() . "'"); + + foreach ($this->data["cols"] as $val) { + $header_names[] = $this->lng->txt($val); + } + + $tbl->setHeaderNames($header_names); + + $header_params = array("ref_id" => $this->ref_id,"obj_id" => $this->id); + $tbl->setHeaderVars($this->data["cols"], $header_params); + + // control + $tbl->setOrderColumn($_GET["sort_by"]); + $tbl->setOrderDirection($_GET["sort_order"]); + $tbl->setLimit(0); + $tbl->setOffset(0); + $tbl->setMaxCount($this->maxcount); + + // footer + $tbl->setFooter("tblfooter", $this->lng->txt("previous"), $this->lng->txt("next")); + //$tbl->disable("footer"); + + // render table + $tbl->render(); + + if (is_array($this->data["data"][0])) { + //table cell + for ($i=0; $i < count($this->data["data"]); $i++) { + $data = $this->data["data"][$i]; + $ctrl = $this->data["ctrl"][$i]; + + // color changing + $css_row = ilUtil::switchColor($i+1, "tblrow1", "tblrow2"); + + $this->tpl->setCurrentBlock("table_cell"); + $this->tpl->setVariable("CELLSTYLE", "tblrow1"); + $this->tpl->parseCurrentBlock(); + + foreach ($data as $key => $val) { + // color for status + if ($key == "status") { + if ($val == "enabled") { + $color = "green"; + } else { + $color = "red"; + } + + $val = "" . $this->lng->txt($val) . ""; + } + + $this->tpl->setCurrentBlock("text"); + + if ($key == "type") { + $val = ilUtil::getImageTagByType($val, $this->tpl->tplPath); + } + + $this->tpl->setVariable("TEXT_CONTENT", $val); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setCurrentBlock("table_cell"); + $this->tpl->parseCurrentBlock(); + } //foreach + + $this->tpl->setCurrentBlock("tbl_content"); + $this->tpl->setVariable("CSS_ROW", $css_row); + $this->tpl->parseCurrentBlock(); + } //for + } //if is_array + } + + /** + * save (de-)activation of operations on object + * + * @access public + */ + public function saveObject() + { + $rbacsystem = $this->rbacsystem; + $rbacadmin = $this->rbacadmin; + $rbacreview = $this->rbacreview; + $ilErr = $this->error; + + if (!$rbacsystem->checkAccess('edit_permission', $_GET["ref_id"])) { + $ilErr->raiseError($this->lng->txt("permission_denied"), $ilErr->WARNING); + } + + $ops_valid = $rbacreview->getOperationsOnType($_GET["obj_id"]); + + foreach ($_POST["id"] as $ops_id => $status) { + if ($status == 'enabled') { + if (!in_array($ops_id, $ops_valid)) { + $rbacadmin->assignOperationToObject($_GET["obj_id"], $ops_id); + } + } + + if ($status == 'disabled') { + if (in_array($ops_id, $ops_valid)) { + $rbacadmin->deassignOperationFromObject($_GET["obj_id"], $ops_id); + } + } + } + + $this->update = $this->object->update(); + + ilUtil::sendSuccess($this->lng->txt("saved_successfully"), true); + + header("Location: adm_object.php?ref_id=" . $_GET["ref_id"] . "&obj_id=" . $_GET["obj_id"]); + exit(); + } + + + /** + * display edit form + * + * @access public + */ + public function editObject() + { + $rbacsystem = $this->rbacsystem; + $rbacreview = $this->rbacreview; + $ilErr = $this->error; + + if (!$rbacsystem->checkAccess("edit_permission", $_GET["ref_id"])) { + $ilErr->raiseError($this->lng->txt("permission_denied"), $ilErr->MESSAGE); + } + + //prepare objectlist + $this->data = array(); + $this->data["data"] = array(); + $this->data["ctrl"] = array(); + $this->data["cols"] = array("type", "operation", "description", "status"); + + $ops_valid = $rbacreview->getOperationsOnType($this->obj_id); + + if ($ops_arr = ilRbacReview::_getOperationList('', $a_order, $a_direction)) { + $options = array("e" => "enabled","d" => "disabled"); + + foreach ($ops_arr as $key => $ops) { + // BEGIN ROW + if (in_array($ops["ops_id"], $ops_valid)) { + $ops_status = 'e'; + } else { + $ops_status = 'd'; + } + + $obj = $ops["ops_id"]; + $ops_options = ilUtil::formSelect($ops_status, "id[$obj]", $options); + + //visible data part + $this->data["data"][] = array( + "type" => "perm", + "operation" => $ops["operation"], + "description" => $ops["desc"], + "status" => $ops_status, + "status_html" => $ops_options, + "obj_id" => $val["ops_id"] + ); + } + } //if typedata + + $this->maxcount = count($this->data["data"]); + + // sorting array + $this->data["data"] = ilUtil::sortArray($this->data["data"], $_GET["sort_by"], $_GET["sort_order"]); + + // now compute control information + foreach ($this->data["data"] as $key => $val) { + $this->data["ctrl"][$key] = array( + "obj_id" => $val["obj_id"], + "type" => $val["type"] + ); + + unset($this->data["data"][$key]["obj_id"]); + $this->data["data"][$key]["status"] = $this->data["data"][$key]["status_html"]; + unset($this->data["data"][$key]["status_html"]); + } + + // build table + include_once "./Services/Table/classes/class.ilTableGUI.php"; + + // load template for table + $this->tpl->addBlockfile("ADM_CONTENT", "adm_content", "tpl.table.html"); + // load template for table content data + $this->tpl->addBlockfile("TBL_CONTENT", "tbl_content", "tpl.obj_tbl_rows.html"); + + $num = 0; + + $obj_str = ($this->call_by_reference) ? "" : "&obj_id=" . $this->obj_id; + $this->tpl->setVariable("FORMACTION", "adm_object.php?ref_id=" . $this->ref_id . "$obj_str&cmd=save"); + + // create table + $tbl = new ilTableGUI(); + + // title & header columns + $tbl->setTitle($this->lng->txt("edit_operations") . " " . strtolower($this->lng->txt("of")) . " '" . $this->object->getTitle() . "'"); + + foreach ($this->data["cols"] as $val) { + $header_names[] = $this->lng->txt($val); + } + + $tbl->setHeaderNames($header_names); + + $header_params = array("ref_id" => $this->ref_id,"obj_id" => $this->id,"cmd" => "edit"); + $tbl->setHeaderVars($this->data["cols"], $header_params); + + // control + $tbl->setOrderColumn($_GET["sort_by"]); + $tbl->setOrderDirection($_GET["sort_order"]); + $tbl->setLimit(0); + $tbl->setOffset(0); + $tbl->setMaxCount($this->maxcount); + + // SHOW VALID ACTIONS + $this->tpl->setVariable("IMG_ARROW", ilUtil::getImagePath("arrow_downright.svg")); + $this->tpl->setVariable("COLUMN_COUNTS", count($this->data["cols"])); + + // footer + $tbl->setFooter("tblfooter", $this->lng->txt("previous"), $this->lng->txt("next")); + //$tbl->disable("footer"); + + // render table + $tbl->render(); + + if (is_array($this->data["data"][0])) { + //table cell + for ($i=0; $i < count($this->data["data"]); $i++) { + $data = $this->data["data"][$i]; + $ctrl = $this->data["ctrl"][$i]; + + // color changing + $css_row = ilUtil::switchColor($i+1, "tblrow1", "tblrow2"); + + $this->tpl->setCurrentBlock("table_cell"); + $this->tpl->setVariable("CELLSTYLE", "tblrow1"); + $this->tpl->parseCurrentBlock(); + + foreach ($data as $key => $val) { + $this->tpl->setCurrentBlock("text"); + + if ($key == "type") { + $val = ilUtil::getImageTagByType($val, $this->tpl->tplPath); + } + + $this->tpl->setVariable("TEXT_CONTENT", $val); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setCurrentBlock("table_cell"); + $this->tpl->parseCurrentBlock(); + } //foreach + + $this->tpl->setVariable("BTN_VALUE", $this->lng->txt("save")); + + $this->tpl->setCurrentBlock("tbl_content"); + $this->tpl->setVariable("CSS_ROW", $css_row); + $this->tpl->parseCurrentBlock(); + } //for + } //if is_array + } + + public function executeCommand() + { + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + switch ($next_class) { + default: + if (!$cmd) { + $cmd = "view"; + } + $cmd .= "Object"; + $this->$cmd(); + + break; + } + return true; + } + + /** + * get tabs + * @access public + * @param object tabs gui object + */ + public function getTabs() + { + $rbacsystem = $this->rbacsystem; + + if ($rbacsystem->checkAccess('edit_permission', $this->object->getRefId())) { + $this->tabs_gui->addTarget( + "settings", + $this->ctrl->getLinkTarget($this, "view"), + array("view",""), + "", + "" + ); + + $this->tabs_gui->addTarget( + "edit_operations", + $this->ctrl->getLinkTarget($this, "edit"), + "edit", + "", + "" + ); + } + } } // END class.ilObjTypeDefinitionGUI -?> diff --git a/Services/Object/classes/class.ilObject.php b/Services/Object/classes/class.ilObject.php index 0ab3318302dc12e32095bb32e53907ee941814fa..16719241ca7699edc545af8910b87f04819fde0c 100755 --- a/Services/Object/classes/class.ilObject.php +++ b/Services/Object/classes/class.ilObject.php @@ -12,943 +12,899 @@ */ class ilObject { - /** - * @var ilObjectDefinition - */ - protected $objDefinition; - - /** - * @var ilDB - */ - protected $db; - - /** - * @var Logger - */ - protected $log; - - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * @var ilTree - */ - protected $tree; - - /** - * @var ilAppEventHandler - */ - protected $app_event_handler; - - /** - * @var ilRbacAdmin - */ - protected $rbacadmin; - - /** - * @var ilRbacReview - */ - protected $rbacreview; - - /** - * max length of object title - */ - const TITLE_LENGTH = 255; // title column max length in db - const DESC_LENGTH = 128; // (short) description column max length in db - - - /** - * lng object - * @var object language - * @access private - */ - var $lng; - - /** - * object id - * @var integer object id of object itself - * @access private - */ - var $id; // true object_id!!!! - var $ref_id;// reference_id - var $type; - var $title; - - /** - * Check if object is offline - * null means undefined - * - * @var null | int - */ - private $offline = null; - - - // BEGIN WebDAV: WebDAV needs to access the untranslated title of an object - var $untranslatedTitle; - // END WebDAV: WebDAV needs to access the untranslated title of an object - var $desc; - var $long_desc; - var $owner; - var $create_date; - var $last_update; - var $import_id; - var $register = false; // registering required for object? set to true to implement a subscription interface - - /** - * indicates if object is a referenced object - * @var boolean - * @access private - */ - var $referenced; - - /** - * object list - * @var array contains all child objects of current object - * @access private - */ - var $objectList; - - /** - * max title length - * @var integer - */ - var $max_title; - - /** - * max description length - * @var integer - */ - var $max_desc; - - /** - * add dots to shortened titles and descriptions - * @var boolean - */ - var $add_dots; - - - /** - * Constructor - * @access public - * @param integer reference_id or object_id - * @param boolean treat the id as reference_id (true) or object_id (false) - */ - function __construct($a_id = 0, $a_reference = true) - { - global $DIC; - - - $this->ilias = $DIC["ilias"]; - - $this->db = $DIC->database(); - $this->log = $DIC["ilLog"]; - $this->error = $DIC["ilErr"]; - $this->tree = $DIC->repositoryTree(); - $this->app_event_handler = $DIC["ilAppEventHandler"]; - $objDefinition = $DIC["objDefinition"]; - - if (DEBUG) - { - echo "
                  type(".$this->type.") id(".$a_id.") referenced(".$a_reference.")"; - } - - if (isset($DIC["lng"])) - { - $this->lng = $DIC["lng"]; - } - $this->objDefinition = $objDefinition; - - $this->max_title = self::TITLE_LENGTH; - $this->max_desc = self::DESC_LENGTH; - $this->add_dots = true; - - $this->referenced = $a_reference; - $this->call_by_reference = $a_reference; - - if ($a_id == 0) - { - $this->referenced = false; // newly created objects are never referenced - } // they will get referenced if createReference() is called - - if ($this->referenced) - { - $this->ref_id = $a_id; - } - else - { - $this->id = $a_id; - } - // read object data - if ($a_id != 0) - { - $this->read(); - } - - } - - /** - * determines wehter objects are referenced or not (got ref ids or not) - */ - function withReferences() - { - // both vars could differ. this method should always return true if one of them is true without changing their status - return ($this->call_by_reference) ? true : $this->referenced; - } - - - /** - * read object data from db into object - * @param boolean - * @access public - */ - public function read() - { - global $DIC; - - $objDefinition = $this->objDefinition; - $ilDB = $this->db; - $ilLog = $this->log; - $ilErr = $this->error; - try { - $ilUser = $DIC["ilUser"]; - } catch (\InvalidArgumentException $e) { - } - - if ($this->referenced) - { - // check reference id - if (!isset($this->ref_id)) - { - $message = "ilObject::read(): No ref_id given! (".$this->type.")"; - $ilErr->raiseError($message, $ilErr->WARNING); - } - - // read object data - - $q = "SELECT * FROM object_data, object_reference WHERE object_data.obj_id=object_reference.obj_id ". - "AND object_reference.ref_id= ".$ilDB->quote($this->ref_id, "integer"); - $object_set = $ilDB->query($q); - - // check number of records - if ($ilDB->numRows($object_set) == 0) - { - $message = "ilObject::read(): Object with ref_id ".$this->ref_id." not found! (".$this->type.")"; - $ilErr->raiseError($message,$ilErr->WARNING); - } - - $obj = $ilDB->fetchAssoc($object_set); - } - else - { - // check object id - if (!isset($this->id)) - { - $message = "ilObject::read(): No obj_id given! (".$this->type.")"; - $ilErr->raiseError($message,$ilErr->WARNING); - } - - // read object data - $q = "SELECT * FROM object_data ". - "WHERE obj_id = ".$ilDB->quote($this->id, "integer"); - $object_set = $ilDB->query($q); - - // check number of records - if ($ilDB->numRows($object_set) == 0) - { - include_once("./Services/Object/exceptions/class.ilObjectNotFoundException.php"); - throw new ilObjectNotFoundException("ilObject::read(): Object with obj_id: ".$this->id. - " (".$this->type.") not found!"); - return; - } - - $obj = $ilDB->fetchAssoc($object_set); - } - - $this->id = $obj["obj_id"]; - - // check type match (the "xxx" type is used for the unit test) - if ($this->type != $obj["type"] && $obj["type"] != "xxx") - { - $message = "ilObject::read(): Type mismatch. Object with obj_id: ".$this->id." ". - "was instantiated by type '".$this->type."'. DB type is: ".$obj["type"]; - - // write log entry - $ilLog->write($message); - - // raise error - include_once("./Services/Object/exceptions/class.ilObjectTypeMismatchException.php"); - throw new ilObjectTypeMismatchException($message); - return; - } - - $this->type = $obj["type"]; - $this->title = $obj["title"]; - // BEGIN WebDAV: WebDAV needs to access the untranslated title of an object - $this->untranslatedTitle = $obj["title"]; - // END WebDAV: WebDAV needs to access the untranslated title of an object - $this->desc = $obj["description"]; - $this->owner = $obj["owner"]; - $this->create_date = $obj["create_date"]; - $this->last_update = $obj["last_update"]; - $this->import_id = $obj["import_id"]; - - $this->setOfflineStatus($obj['offline']); - - if($objDefinition->isRBACObject($this->getType())) - { - // Read long description - $query = "SELECT * FROM object_description WHERE obj_id = ".$ilDB->quote($this->id,'integer'); - $res = $ilDB->query($query); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - if(strlen($row->description)) - { - $this->setDescription($row->description); - } - } - } - - // multilingual support systemobjects (sys) & categories (db) - $translation_type = $objDefinition->getTranslationType($this->type); - - if ($translation_type == "sys") - { - $this->title = $this->lng->txt("obj_".$this->type); - $this->setDescription($this->lng->txt("obj_".$this->type."_desc")); - } - elseif ($translation_type == "db") - { - $q = "SELECT title,description FROM object_translation ". - "WHERE obj_id = ".$ilDB->quote($this->id,'integer')." ". - "AND lang_code = ".$ilDB->quote($ilUser->getCurrentLanguage(),'text')." ". - "AND NOT lang_default = 1"; - $r = $ilDB->query($q); - $row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT); - if ($row) - { - $this->title = $row->title; - $this->setDescription($row->description); - #$this->desc = $row->description; - } - } - - } - - /** - * get object id - * @access public - * @return integer object id - */ - function getId() - { - return $this->id; - } - - /** - * set object id - * @access public - * @param integer $a_id object id - */ - function setId($a_id) - { - $this->id = $a_id; - } - - /** - * set reference id - * @access public - * @param integer $a_id reference id - */ - function setRefId($a_id) - { - $this->ref_id = $a_id; - $this->referenced = true; - } - - /** - * get reference id - * @access public - * @return integer reference id - */ - function getRefId() - { - return $this->ref_id; - } - - /** - * get object type - * @access public - * @return string object type - */ - function getType() - { - return $this->type; - } - - /** - * set object type - * @access public - * @param integer $a_type object type - */ - function setType($a_type) - { - $this->type = $a_type; - } - - /** - * get presentation title - * Normally same as title - * Overwritten for sessions - * - * @access public - * @param - * @return - */ - public function getPresentationTitle() - { - return $this->getTitle(); - } - - - /** - * get object title - * @access public - * @return string object title - */ - function getTitle() - { - return $this->title; - } - // BEGIN WebDAV: WebDAV needs to access the untranslated title of an object - /** - * get untranslated object title - * @access public - * @return string object title - */ - function getUntranslatedTitle() - { - return $this->untranslatedTitle; - } - // END WebDAV: WebDAV needs to access the untranslated title of an object - - /** - * set object title - * - * @access public - * @param string $a_title object title - */ - function setTitle($a_title) - { - $this->title = ilUtil::shortenText($a_title, $this->max_title, $this->add_dots); - // BEGIN WebDAV: WebDAV needs to access the untranslated title of an object - $this->untranslatedTitle = $this->title; - // END WebDAV: WebDAV needs to access the untranslated title of an object - } - - /** - * get object description - * - * @access public - * @return string object description - */ - function getDescription() - { - return $this->desc; - } - - /** - * set object description - * - * @access public - * @param string $a_desc object description - */ - function setDescription($a_desc) - { - // Shortened form is storted in object_data. Long form is stored in object_description - $this->desc = ilUtil::shortenText($a_desc, $this->max_desc, $this->add_dots); - - $this->long_desc = $a_desc; - - return true; - } - - /** - * get object long description (stored in object_description) - * - * @access public - * @return string object description - */ - function getLongDescription() - { - return strlen($this->long_desc) ? $this->long_desc : $this->desc; - } - - /** - * get import id - * - * @access public - * @return string import id - */ - function getImportId() - { - return $this->import_id; - } - - /** - * set import id - * - * @access public - * @param string $a_import_id import id - */ - function setImportId($a_import_id) - { - $this->import_id = $a_import_id; - } - - public static function _lookupObjIdByImportId($a_import_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT * FROM object_data ". - "WHERE import_id = ".$ilDB->quote($a_import_id, "text")." ". - "ORDER BY create_date DESC"; - $res = $ilDB->query($query); - while($row = $ilDB->fetchObject($res)) - { - return $row->obj_id; - } - return 0; - } - - /** - * Set offline status - * @param bool $a_status - */ - public function setOfflineStatus($a_status) - { - $this->offline = $a_status; - } - - /** - * Get offline status - * @return int|null - */ - public function getOfflineStatus() - { - return $this->offline; - } - - /** - * Check whether object supports offline handling - * @return bool - */ - public function supportsOfflineHandling() - { - global $DIC; - - return (bool) $DIC['objDefinition']->supportsOfflineHandling($this->getType()); - } - - - - - public static function _lookupImportId($a_obj_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT import_id FROM object_data ". - "WHERE obj_id = ".$ilDB->quote($a_obj_id, "integer"); - $res = $ilDB->query($query); - $row = $ilDB->fetchObject($res); - return $row->import_id; - } - - /** - * get object owner - * - * @access public - * @return integer owner id - */ - function getOwner() - { - return $this->owner; - } - - /* - * get full name of object owner - * - * @access public - * @return string owner name or unknown - */ - function getOwnerName() - { - return ilObject::_lookupOwnerName($this->getOwner()); - } - - /** - * lookup owner name for owner id - */ - static function _lookupOwnerName($a_owner_id) - { - global $DIC; - - $lng = $DIC->language(); - - if ($a_owner_id != -1) - { - if (ilObject::_exists($a_owner_id)) - { - $owner = new ilObjUser($a_owner_id); - } - } - - if (is_object($owner)) - { - $own_name = $owner->getFullname(); - } - else - { - $own_name = $lng->txt("unknown"); - } - - return $own_name; - } - - /** - * set object owner - * - * @access public - * @param integer $a_owner owner id - */ - function setOwner($a_owner) - { - $this->owner = $a_owner; - } - - - - /** - * get create date - * @access public - * @return string creation date - */ - function getCreateDate() - { - return $this->create_date; - } - - /** - * get last update date - * @access public - * @return string date of last update - */ - function getLastUpdateDate() - { - return $this->last_update; - } - - - /** - * Gets the disk usage of the object in bytes. + /** + * @var ilObjectDefinition + */ + protected $objDefinition; + + /** + * @var ilDB + */ + protected $db; + + /** + * @var Logger + */ + protected $log; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilTree + */ + protected $tree; + + /** + * @var ilAppEventHandler + */ + protected $app_event_handler; + + /** + * @var ilRbacAdmin + */ + protected $rbacadmin; + + /** + * @var ilRbacReview + */ + protected $rbacreview; + + /** + * max length of object title + */ + const TITLE_LENGTH = 255; // title column max length in db + const DESC_LENGTH = 128; // (short) description column max length in db + + + /** + * lng object + * @var object language + * @access private + */ + public $lng; + + /** + * object id + * @var integer object id of object itself + * @access private + */ + public $id; // true object_id!!!! + public $ref_id;// reference_id + public $type; + public $title; + + /** + * Check if object is offline + * null means undefined + * + * @var null | int + */ + private $offline = null; + + + // BEGIN WebDAV: WebDAV needs to access the untranslated title of an object + public $untranslatedTitle; + // END WebDAV: WebDAV needs to access the untranslated title of an object + public $desc; + public $long_desc; + public $owner; + public $create_date; + public $last_update; + public $import_id; + public $register = false; // registering required for object? set to true to implement a subscription interface + + /** + * indicates if object is a referenced object + * @var boolean + * @access private + */ + public $referenced; + + /** + * object list + * @var array contains all child objects of current object + * @access private + */ + public $objectList; + + /** + * max title length + * @var integer + */ + public $max_title; + + /** + * max description length + * @var integer + */ + public $max_desc; + + /** + * add dots to shortened titles and descriptions + * @var boolean + */ + public $add_dots; + + + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id = 0, $a_reference = true) + { + global $DIC; + + + $this->ilias = $DIC["ilias"]; + + $this->db = $DIC->database(); + $this->log = $DIC["ilLog"]; + $this->error = $DIC["ilErr"]; + $this->tree = $DIC->repositoryTree(); + $this->app_event_handler = $DIC["ilAppEventHandler"]; + $objDefinition = $DIC["objDefinition"]; + + if (DEBUG) { + echo "
                  type(" . $this->type . ") id(" . $a_id . ") referenced(" . $a_reference . ")"; + } + + if (isset($DIC["lng"])) { + $this->lng = $DIC["lng"]; + } + $this->objDefinition = $objDefinition; + + $this->max_title = self::TITLE_LENGTH; + $this->max_desc = self::DESC_LENGTH; + $this->add_dots = true; + + $this->referenced = $a_reference; + $this->call_by_reference = $a_reference; + + if ($a_id == 0) { + $this->referenced = false; // newly created objects are never referenced + } // they will get referenced if createReference() is called + + if ($this->referenced) { + $this->ref_id = $a_id; + } else { + $this->id = $a_id; + } + // read object data + if ($a_id != 0) { + $this->read(); + } + } + + /** + * determines wehter objects are referenced or not (got ref ids or not) + */ + public function withReferences() + { + // both vars could differ. this method should always return true if one of them is true without changing their status + return ($this->call_by_reference) ? true : $this->referenced; + } + + + /** + * read object data from db into object + * @param boolean + * @access public + */ + public function read() + { + global $DIC; + + $objDefinition = $this->objDefinition; + $ilDB = $this->db; + $ilLog = $this->log; + $ilErr = $this->error; + try { + $ilUser = $DIC["ilUser"]; + } catch (\InvalidArgumentException $e) { + } + + if ($this->referenced) { + // check reference id + if (!isset($this->ref_id)) { + $message = "ilObject::read(): No ref_id given! (" . $this->type . ")"; + $ilErr->raiseError($message, $ilErr->WARNING); + } + + // read object data + + $q = "SELECT * FROM object_data, object_reference WHERE object_data.obj_id=object_reference.obj_id " . + "AND object_reference.ref_id= " . $ilDB->quote($this->ref_id, "integer"); + $object_set = $ilDB->query($q); + + // check number of records + if ($ilDB->numRows($object_set) == 0) { + $message = "ilObject::read(): Object with ref_id " . $this->ref_id . " not found! (" . $this->type . ")"; + $ilErr->raiseError($message, $ilErr->WARNING); + } + + $obj = $ilDB->fetchAssoc($object_set); + } else { + // check object id + if (!isset($this->id)) { + $message = "ilObject::read(): No obj_id given! (" . $this->type . ")"; + $ilErr->raiseError($message, $ilErr->WARNING); + } + + // read object data + $q = "SELECT * FROM object_data " . + "WHERE obj_id = " . $ilDB->quote($this->id, "integer"); + $object_set = $ilDB->query($q); + + // check number of records + if ($ilDB->numRows($object_set) == 0) { + include_once("./Services/Object/exceptions/class.ilObjectNotFoundException.php"); + throw new ilObjectNotFoundException("ilObject::read(): Object with obj_id: " . $this->id . + " (" . $this->type . ") not found!"); + return; + } + + $obj = $ilDB->fetchAssoc($object_set); + } + + $this->id = $obj["obj_id"]; + + // check type match (the "xxx" type is used for the unit test) + if ($this->type != $obj["type"] && $obj["type"] != "xxx") { + $message = "ilObject::read(): Type mismatch. Object with obj_id: " . $this->id . " " . + "was instantiated by type '" . $this->type . "'. DB type is: " . $obj["type"]; + + // write log entry + $ilLog->write($message); + + // raise error + include_once("./Services/Object/exceptions/class.ilObjectTypeMismatchException.php"); + throw new ilObjectTypeMismatchException($message); + return; + } + + $this->type = $obj["type"]; + $this->title = $obj["title"]; + // BEGIN WebDAV: WebDAV needs to access the untranslated title of an object + $this->untranslatedTitle = $obj["title"]; + // END WebDAV: WebDAV needs to access the untranslated title of an object + $this->desc = $obj["description"]; + $this->owner = $obj["owner"]; + $this->create_date = $obj["create_date"]; + $this->last_update = $obj["last_update"]; + $this->import_id = $obj["import_id"]; + + $this->setOfflineStatus($obj['offline']); + + if ($objDefinition->isRBACObject($this->getType())) { + // Read long description + $query = "SELECT * FROM object_description WHERE obj_id = " . $ilDB->quote($this->id, 'integer'); + $res = $ilDB->query($query); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + if (strlen($row->description)) { + $this->setDescription($row->description); + } + } + } + + // multilingual support systemobjects (sys) & categories (db) + $translation_type = $objDefinition->getTranslationType($this->type); + + if ($translation_type == "sys") { + $this->title = $this->lng->txt("obj_" . $this->type); + $this->setDescription($this->lng->txt("obj_" . $this->type . "_desc")); + } elseif ($translation_type == "db") { + $q = "SELECT title,description FROM object_translation " . + "WHERE obj_id = " . $ilDB->quote($this->id, 'integer') . " " . + "AND lang_code = " . $ilDB->quote($ilUser->getCurrentLanguage(), 'text') . " " . + "AND NOT lang_default = 1"; + $r = $ilDB->query($q); + $row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT); + if ($row) { + $this->title = $row->title; + $this->setDescription($row->description); + #$this->desc = $row->description; + } + } + } + + /** + * get object id + * @access public + * @return integer object id + */ + public function getId() + { + return $this->id; + } + + /** + * set object id + * @access public + * @param integer $a_id object id + */ + public function setId($a_id) + { + $this->id = $a_id; + } + + /** + * set reference id + * @access public + * @param integer $a_id reference id + */ + public function setRefId($a_id) + { + $this->ref_id = $a_id; + $this->referenced = true; + } + + /** + * get reference id + * @access public + * @return integer reference id + */ + public function getRefId() + { + return $this->ref_id; + } + + /** + * get object type + * @access public + * @return string object type + */ + public function getType() + { + return $this->type; + } + + /** + * set object type + * @access public + * @param integer $a_type object type + */ + public function setType($a_type) + { + $this->type = $a_type; + } + + /** + * get presentation title + * Normally same as title + * Overwritten for sessions + * + * @access public + * @param + * @return + */ + public function getPresentationTitle() + { + return $this->getTitle(); + } + + + /** + * get object title + * @access public + * @return string object title + */ + public function getTitle() + { + return $this->title; + } + // BEGIN WebDAV: WebDAV needs to access the untranslated title of an object + /** + * get untranslated object title + * @access public + * @return string object title + */ + public function getUntranslatedTitle() + { + return $this->untranslatedTitle; + } + // END WebDAV: WebDAV needs to access the untranslated title of an object + + /** + * set object title + * + * @access public + * @param string $a_title object title + */ + public function setTitle($a_title) + { + $this->title = ilUtil::shortenText($a_title, $this->max_title, $this->add_dots); + // BEGIN WebDAV: WebDAV needs to access the untranslated title of an object + $this->untranslatedTitle = $this->title; + // END WebDAV: WebDAV needs to access the untranslated title of an object + } + + /** + * get object description + * + * @access public + * @return string object description + */ + public function getDescription() + { + return $this->desc; + } + + /** + * set object description + * + * @access public + * @param string $a_desc object description + */ + public function setDescription($a_desc) + { + // Shortened form is storted in object_data. Long form is stored in object_description + $this->desc = ilUtil::shortenText($a_desc, $this->max_desc, $this->add_dots); + + $this->long_desc = $a_desc; + + return true; + } + + /** + * get object long description (stored in object_description) + * + * @access public + * @return string object description + */ + public function getLongDescription() + { + return strlen($this->long_desc) ? $this->long_desc : $this->desc; + } + + /** + * get import id + * + * @access public + * @return string import id + */ + public function getImportId() + { + return $this->import_id; + } + + /** + * set import id + * + * @access public + * @param string $a_import_id import id + */ + public function setImportId($a_import_id) + { + $this->import_id = $a_import_id; + } + + public static function _lookupObjIdByImportId($a_import_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT * FROM object_data " . + "WHERE import_id = " . $ilDB->quote($a_import_id, "text") . " " . + "ORDER BY create_date DESC"; + $res = $ilDB->query($query); + while ($row = $ilDB->fetchObject($res)) { + return $row->obj_id; + } + return 0; + } + + /** + * Set offline status + * @param bool $a_status + */ + public function setOfflineStatus($a_status) + { + $this->offline = $a_status; + } + + /** + * Get offline status + * @return int|null + */ + public function getOfflineStatus() + { + return $this->offline; + } + + /** + * Check whether object supports offline handling + * @return bool + */ + public function supportsOfflineHandling() + { + global $DIC; + + return (bool) $DIC['objDefinition']->supportsOfflineHandling($this->getType()); + } + + + + + public static function _lookupImportId($a_obj_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT import_id FROM object_data " . + "WHERE obj_id = " . $ilDB->quote($a_obj_id, "integer"); + $res = $ilDB->query($query); + $row = $ilDB->fetchObject($res); + return $row->import_id; + } + + /** + * get object owner + * + * @access public + * @return integer owner id + */ + public function getOwner() + { + return $this->owner; + } + + /* + * get full name of object owner + * + * @access public + * @return string owner name or unknown + */ + public function getOwnerName() + { + return ilObject::_lookupOwnerName($this->getOwner()); + } + + /** + * lookup owner name for owner id + */ + public static function _lookupOwnerName($a_owner_id) + { + global $DIC; + + $lng = $DIC->language(); + + if ($a_owner_id != -1) { + if (ilObject::_exists($a_owner_id)) { + $owner = new ilObjUser($a_owner_id); + } + } + + if (is_object($owner)) { + $own_name = $owner->getFullname(); + } else { + $own_name = $lng->txt("unknown"); + } + + return $own_name; + } + + /** + * set object owner + * + * @access public + * @param integer $a_owner owner id + */ + public function setOwner($a_owner) + { + $this->owner = $a_owner; + } + + + + /** + * get create date + * @access public + * @return string creation date + */ + public function getCreateDate() + { + return $this->create_date; + } + + /** + * get last update date + * @access public + * @return string date of last update + */ + public function getLastUpdateDate() + { + return $this->last_update; + } + + + /** + * Gets the disk usage of the object in bytes. * Returns null, if the object does not use disk space at all. - * - * The implementation of class ilObject always returns null. - * Subclasses which use disk space can override this method to return a - * non-null value. * - * @access public - * @return integer the disk usage in bytes or null - */ - function getDiskUsage() - { - return null; - } - - /** - * create - * - * note: title, description and type should be set when this function is called - * - * @access public - * @return integer object id - */ - function create() - { - global $DIC; - - $app_event = $DIC->event(); - $ilDB = $this->db; - $ilLog = $this->log; - $ilUser = $DIC["ilUser"]; - $objDefinition = $this->objDefinition; - $ilErr = $this->error; - - if (!isset($this->type)) - { - $message = get_class($this)."::create(): No object type given!"; - $ilErr->raiseError($message,$ilErr->WARNING); - } - - // write log entry - $ilLog->write("ilObject::create(), start"); - - $this->title = ilUtil::shortenText($this->getTitle(), $this->max_title, $this->add_dots); - $this->desc = ilUtil::shortenText($this->getDescription(), $this->max_desc, $this->add_dots); - - // determine owner - if ($this->getOwner() > 0) - { - $owner = $this->getOwner(); - } - elseif(is_object($ilUser)) - { - $owner = $ilUser->getId(); - } - else - { - $owner = 0; - } - $this->id = $ilDB->nextId("object_data"); - $q = "INSERT INTO object_data " . - "(obj_id,type,title,description,offline,owner,create_date,last_update,import_id) " . - "VALUES " . - "(" . - $ilDB->quote($this->id, "integer") . "," . - $ilDB->quote($this->type, "text") . "," . - $ilDB->quote($this->getTitle(), "text") . "," . - $ilDB->quote($this->getDescription(), "text") . "," . - $ilDB->quote($this->supportsOfflineHandling() ? $this->getOfflineStatus() : null, 'integer').', '. - $ilDB->quote($owner, "integer") . "," . - $ilDB->now() . "," . - $ilDB->now() . "," . - $ilDB->quote($this->getImportId(), "text") . ")"; - - $ilDB->manipulate($q); - - - // Save long form of description if is rbac object - if($objDefinition->isRBACObject($this->getType())) - { - $values = array( - 'obj_id' => array('integer',$this->id), - 'description' => array('clob', $this->getLongDescription())); - $ilDB->insert('object_description',$values); - } - - if ($objDefinition->isOrgUnitPermissionType($this->type)) - { - ilOrgUnitGlobalSettings::getInstance()->saveDefaultPositionActivationStatus($this->id); - } - - // the line ($this->read();) messes up meta data handling: meta data, - // that is not saved at this time, gets lost, so we query for the dates alone - //$this->read(); - $q = "SELECT last_update, create_date FROM object_data". - " WHERE obj_id = ".$ilDB->quote($this->id, "integer"); - $obj_set = $ilDB->query($q); - $obj_rec = $ilDB->fetchAssoc($obj_set); - $this->last_update = $obj_rec["last_update"]; - $this->create_date = $obj_rec["create_date"]; - - // set owner for new objects - $this->setOwner($owner); - - // write log entry - $ilLog->write("ilObject::create(), finished, obj_id: ".$this->id.", type: ". - $this->type.", title: ".$this->getTitle()); - - $app_event->raise( - 'Services/Object', - 'create', - array('obj_id' => $this->id,'obj_type' => $this->type)); - - return $this->id; - } - - /** - * update object in db - * - * @access public - * @return boolean true on success - */ - function update() - { - global $DIC; - - $app_event = $DIC->event(); - - $objDefinition = $this->objDefinition; - $ilDB = $this->db; - - $q = "UPDATE object_data ". - "SET ". - "title = ".$ilDB->quote($this->getTitle(), "text").",". - "description = ".$ilDB->quote($this->getDescription(), "text").", ". - 'offline = '. $ilDB->quote($this->supportsOfflineHandling() ? $this->getOfflineStatus() : null, 'integer').', '. - "import_id = ".$ilDB->quote($this->getImportId(), "text").",". - "last_update = ".$ilDB->now()." ". - "WHERE obj_id = ".$ilDB->quote($this->getId(), "integer"); - $ilDB->manipulate($q); - - // the line ($this->read();) messes up meta data handling: meta data, - // that is not saved at this time, gets lost, so we query for the dates alone - //$this->read(); - $q = "SELECT last_update FROM object_data". - " WHERE obj_id = ".$ilDB->quote($this->getId(), "integer"); - $obj_set = $ilDB->query($q); - $obj_rec = $ilDB->fetchAssoc($obj_set); - $this->last_update = $obj_rec["last_update"]; - - if($objDefinition->isRBACObject($this->getType())) - { - // Update long description - $res = $ilDB->query("SELECT * FROM object_description WHERE obj_id = ". - $ilDB->quote($this->getId(),'integer')); - if($res->numRows()) - { - $values = array( - 'description' => array('clob',$this->getLongDescription()) - ); - $ilDB->update('object_description',$values,array('obj_id' => array('integer',$this->getId()))); - } - else - { - $values = array( - 'description' => array('clob',$this->getLongDescription()), - 'obj_id' => array('integer',$this->getId())); - $ilDB->insert('object_description',$values); - } - } - $app_event->raise( - 'Services/Object', - 'update', - array('obj_id' => $this->getId(), - 'obj_type' => $this->getType(), - 'ref_id' => $this->getRefId())); - - return true; - } - - /** - * Meta data update listener - * - * Important note: Do never call create() or update() - * method of ilObject here. It would result in an - * endless loop: update object -> update meta -> update - * object -> ... - * Use static _writeTitle() ... methods instead. - * - * @param string $a_element - */ - function MDUpdateListener($a_element) - { - global $DIC; - - $app_event = $DIC->event(); - - include_once 'Services/MetaData/classes/class.ilMD.php'; - - $app_event->raise( - 'Services/Object', - 'update', - array('obj_id' => $this->getId(), - 'obj_type' => $this->getType(), - 'ref_id' => $this->getRefId())); - - switch($a_element) - { - case 'General': - - // Update Title and description - $md = new ilMD($this->getId(),0, $this->getType()); - if(!is_object($md_gen = $md->getGeneral())) - { - return false; - } - $this->setTitle($md_gen->getTitle()); - - foreach($md_gen->getDescriptionIds() as $id) - { - $md_des = $md_gen->getDescription($id); - $this->setDescription($md_des->getDescription()); - break; - } - $this->update(); - break; - - default: - } - - return true; - } - - /** - * create meta data entry - */ - function createMetaData() - { - global $DIC; - - include_once 'Services/MetaData/classes/class.ilMDCreator.php'; - - $ilUser = $DIC["ilUser"]; - - $md_creator = new ilMDCreator($this->getId(),0,$this->getType()); - $md_creator->setTitle($this->getTitle()); - $md_creator->setTitleLanguage($ilUser->getPref('language')); - $md_creator->setDescription($this->getLongDescription()); - $md_creator->setDescriptionLanguage($ilUser->getPref('language')); - $md_creator->setKeywordLanguage($ilUser->getPref('language')); - $md_creator->setLanguage($ilUser->getPref('language')); - $md_creator->create(); - - return true; - } - - /** - * update meta data entry - */ - function updateMetaData() - { - $md = new ilMD($this->getId(), 0, $this->getType()); - $md_gen = $md->getGeneral(); - // BEGIN WebDAV: meta data can be missing sometimes. - if(!$md_gen instanceof ilMDGeneral) - { - $this->createMetaData(); - $md = new ilMD($this->getId(), 0, $this->getType()); - $md_gen = $md->getGeneral(); - } - // END WebDAV: meta data can be missing sometimes. - $md_gen->setTitle($this->getTitle()); - - // sets first description (maybe not appropriate) - $md_des_ids = $md_gen->getDescriptionIds(); - if (count($md_des_ids) > 0) - { - $md_des = $md_gen->getDescription($md_des_ids[0]); - $md_des->setDescription($this->getLongDescription()); - $md_des->update(); - } - $md_gen->update(); - } - - /** - * delete meta data entry - */ - function deleteMetaData() - { - // Delete meta data - include_once('Services/MetaData/classes/class.ilMD.php'); - $md = new ilMD($this->getId(), 0, $this->getType()); - $md->deleteAll(); - } + * The implementation of class ilObject always returns null. + * Subclasses which use disk space can override this method to return a + * non-null value. + * + * @access public + * @return integer the disk usage in bytes or null + */ + public function getDiskUsage() + { + return null; + } + + /** + * create + * + * note: title, description and type should be set when this function is called + * + * @access public + * @return integer object id + */ + public function create() + { + global $DIC; + + $app_event = $DIC->event(); + $ilDB = $this->db; + $ilLog = $this->log; + $ilUser = $DIC["ilUser"]; + $objDefinition = $this->objDefinition; + $ilErr = $this->error; + + if (!isset($this->type)) { + $message = get_class($this) . "::create(): No object type given!"; + $ilErr->raiseError($message, $ilErr->WARNING); + } + + // write log entry + $ilLog->write("ilObject::create(), start"); + + $this->title = ilUtil::shortenText($this->getTitle(), $this->max_title, $this->add_dots); + $this->desc = ilUtil::shortenText($this->getDescription(), $this->max_desc, $this->add_dots); + + // determine owner + if ($this->getOwner() > 0) { + $owner = $this->getOwner(); + } elseif (is_object($ilUser)) { + $owner = $ilUser->getId(); + } else { + $owner = 0; + } + $this->id = $ilDB->nextId("object_data"); + $q = "INSERT INTO object_data " . + "(obj_id,type,title,description,offline,owner,create_date,last_update,import_id) " . + "VALUES " . + "(" . + $ilDB->quote($this->id, "integer") . "," . + $ilDB->quote($this->type, "text") . "," . + $ilDB->quote($this->getTitle(), "text") . "," . + $ilDB->quote($this->getDescription(), "text") . "," . + $ilDB->quote($this->supportsOfflineHandling() ? $this->getOfflineStatus() : null, 'integer') . ', ' . + $ilDB->quote($owner, "integer") . "," . + $ilDB->now() . "," . + $ilDB->now() . "," . + $ilDB->quote($this->getImportId(), "text") . ")"; + + $ilDB->manipulate($q); + + + // Save long form of description if is rbac object + if ($objDefinition->isRBACObject($this->getType())) { + $values = array( + 'obj_id' => array('integer',$this->id), + 'description' => array('clob', $this->getLongDescription())); + $ilDB->insert('object_description', $values); + } + + if ($objDefinition->isOrgUnitPermissionType($this->type)) { + ilOrgUnitGlobalSettings::getInstance()->saveDefaultPositionActivationStatus($this->id); + } + + // the line ($this->read();) messes up meta data handling: meta data, + // that is not saved at this time, gets lost, so we query for the dates alone + //$this->read(); + $q = "SELECT last_update, create_date FROM object_data" . + " WHERE obj_id = " . $ilDB->quote($this->id, "integer"); + $obj_set = $ilDB->query($q); + $obj_rec = $ilDB->fetchAssoc($obj_set); + $this->last_update = $obj_rec["last_update"]; + $this->create_date = $obj_rec["create_date"]; + + // set owner for new objects + $this->setOwner($owner); + + // write log entry + $ilLog->write("ilObject::create(), finished, obj_id: " . $this->id . ", type: " . + $this->type . ", title: " . $this->getTitle()); + + $app_event->raise( + 'Services/Object', + 'create', + array('obj_id' => $this->id,'obj_type' => $this->type) + ); + + return $this->id; + } + + /** + * update object in db + * + * @access public + * @return boolean true on success + */ + public function update() + { + global $DIC; + + $app_event = $DIC->event(); + + $objDefinition = $this->objDefinition; + $ilDB = $this->db; + + $q = "UPDATE object_data " . + "SET " . + "title = " . $ilDB->quote($this->getTitle(), "text") . "," . + "description = " . $ilDB->quote($this->getDescription(), "text") . ", " . + 'offline = ' . $ilDB->quote($this->supportsOfflineHandling() ? $this->getOfflineStatus() : null, 'integer') . ', ' . + "import_id = " . $ilDB->quote($this->getImportId(), "text") . "," . + "last_update = " . $ilDB->now() . " " . + "WHERE obj_id = " . $ilDB->quote($this->getId(), "integer"); + $ilDB->manipulate($q); + + // the line ($this->read();) messes up meta data handling: meta data, + // that is not saved at this time, gets lost, so we query for the dates alone + //$this->read(); + $q = "SELECT last_update FROM object_data" . + " WHERE obj_id = " . $ilDB->quote($this->getId(), "integer"); + $obj_set = $ilDB->query($q); + $obj_rec = $ilDB->fetchAssoc($obj_set); + $this->last_update = $obj_rec["last_update"]; + + if ($objDefinition->isRBACObject($this->getType())) { + // Update long description + $res = $ilDB->query("SELECT * FROM object_description WHERE obj_id = " . + $ilDB->quote($this->getId(), 'integer')); + if ($res->numRows()) { + $values = array( + 'description' => array('clob',$this->getLongDescription()) + ); + $ilDB->update('object_description', $values, array('obj_id' => array('integer',$this->getId()))); + } else { + $values = array( + 'description' => array('clob',$this->getLongDescription()), + 'obj_id' => array('integer',$this->getId())); + $ilDB->insert('object_description', $values); + } + } + $app_event->raise( + 'Services/Object', + 'update', + array('obj_id' => $this->getId(), + 'obj_type' => $this->getType(), + 'ref_id' => $this->getRefId()) + ); + + return true; + } + + /** + * Meta data update listener + * + * Important note: Do never call create() or update() + * method of ilObject here. It would result in an + * endless loop: update object -> update meta -> update + * object -> ... + * Use static _writeTitle() ... methods instead. + * + * @param string $a_element + */ + public function MDUpdateListener($a_element) + { + global $DIC; + + $app_event = $DIC->event(); + + include_once 'Services/MetaData/classes/class.ilMD.php'; + + $app_event->raise( + 'Services/Object', + 'update', + array('obj_id' => $this->getId(), + 'obj_type' => $this->getType(), + 'ref_id' => $this->getRefId()) + ); + + switch ($a_element) { + case 'General': + + // Update Title and description + $md = new ilMD($this->getId(), 0, $this->getType()); + if (!is_object($md_gen = $md->getGeneral())) { + return false; + } + $this->setTitle($md_gen->getTitle()); + + foreach ($md_gen->getDescriptionIds() as $id) { + $md_des = $md_gen->getDescription($id); + $this->setDescription($md_des->getDescription()); + break; + } + $this->update(); + break; + + default: + } + + return true; + } + + /** + * create meta data entry + */ + public function createMetaData() + { + global $DIC; + + include_once 'Services/MetaData/classes/class.ilMDCreator.php'; + + $ilUser = $DIC["ilUser"]; + + $md_creator = new ilMDCreator($this->getId(), 0, $this->getType()); + $md_creator->setTitle($this->getTitle()); + $md_creator->setTitleLanguage($ilUser->getPref('language')); + $md_creator->setDescription($this->getLongDescription()); + $md_creator->setDescriptionLanguage($ilUser->getPref('language')); + $md_creator->setKeywordLanguage($ilUser->getPref('language')); + $md_creator->setLanguage($ilUser->getPref('language')); + $md_creator->create(); + + return true; + } + + /** + * update meta data entry + */ + public function updateMetaData() + { + $md = new ilMD($this->getId(), 0, $this->getType()); + $md_gen = $md->getGeneral(); + // BEGIN WebDAV: meta data can be missing sometimes. + if (!$md_gen instanceof ilMDGeneral) { + $this->createMetaData(); + $md = new ilMD($this->getId(), 0, $this->getType()); + $md_gen = $md->getGeneral(); + } + // END WebDAV: meta data can be missing sometimes. + $md_gen->setTitle($this->getTitle()); + + // sets first description (maybe not appropriate) + $md_des_ids = $md_gen->getDescriptionIds(); + if (count($md_des_ids) > 0) { + $md_des = $md_gen->getDescription($md_des_ids[0]); + $md_des->setDescription($this->getLongDescription()); + $md_des->update(); + } + $md_gen->update(); + } + + /** + * delete meta data entry + */ + public function deleteMetaData() + { + // Delete meta data + include_once('Services/MetaData/classes/class.ilMD.php'); + $md = new ilMD($this->getId(), 0, $this->getType()); + $md->deleteAll(); + } /** * update owner of object in db @@ -956,19 +912,19 @@ class ilObject * @access public * @return boolean true on success */ - function updateOwner() - { - $ilDB = $this->db; - - $q = "UPDATE object_data ". - "SET ". - "owner = ".$ilDB->quote($this->getOwner(), "integer").", ". - "last_update = ".$ilDB->now()." ". - "WHERE obj_id = ".$ilDB->quote($this->getId(), "integer"); + public function updateOwner() + { + $ilDB = $this->db; + + $q = "UPDATE object_data " . + "SET " . + "owner = " . $ilDB->quote($this->getOwner(), "integer") . ", " . + "last_update = " . $ilDB->now() . " " . + "WHERE obj_id = " . $ilDB->quote($this->getId(), "integer"); $ilDB->manipulate($q); - $q = "SELECT last_update FROM object_data". - " WHERE obj_id = ".$ilDB->quote($this->getId(), "integer"); + $q = "SELECT last_update FROM object_data" . + " WHERE obj_id = " . $ilDB->quote($this->getId(), "integer"); $obj_set = $ilDB->query($q); $obj_rec = $ilDB->fetchAssoc($obj_set); $this->last_update = $obj_rec["last_update"]; @@ -976,1443 +932,1355 @@ class ilObject return true; } - /** - * get current object id for import id (static) - * - * @param int $a_import_id import id - * - * @return int id - */ - static function _getIdForImportId($a_import_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $ilDB->setLimit(1,0); - $q = "SELECT * FROM object_data WHERE import_id = ".$ilDB->quote($a_import_id, "text"). - " ORDER BY create_date DESC"; - $obj_set = $ilDB->query($q); - - if ($obj_rec = $ilDB->fetchAssoc($obj_set)) - { - return $obj_rec["obj_id"]; - } - else - { - return 0; - } - } - - /** - * get all reference ids of object - * - * @param int $a_id object id - */ - public static function _getAllReferences($a_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT * FROM object_reference WHERE obj_id = ". - $ilDB->quote($a_id,'integer'); - - $res = $ilDB->query($query); - $ref = array(); - while($obj_rec = $ilDB->fetchAssoc($res)) - { - $ref[$obj_rec["ref_id"]] = $obj_rec["ref_id"]; - } - - return $ref; - } - - /** - * lookup object title - * - * @param int $a_id object id - */ - public static function _lookupTitle($a_id) - { - global $DIC; - - $ilObjDataCache = $DIC["ilObjDataCache"]; - - $tit = $ilObjDataCache->lookupTitle($a_id); -//echo "
                  LOOKING-$a_id-:$tit"; - return $tit; - } - - /** - * Lookup offline status using objectDataCache - * - * @static - * @param $a_obj_id - * @return null | bool - */ - public static function lookupOfflineStatus($a_obj_id) - { - global $DIC; - - return $DIC['ilObjDataCache']->lookupOfflineStatus($a_obj_id); - } - - - - /** - * lookup object owner - * - * @param int $a_id object id - */ - static function _lookupOwner($a_id) - { - global $DIC; - - $ilObjDataCache = $DIC["ilObjDataCache"]; - - $owner = $ilObjDataCache->lookupOwner($a_id); - return $owner; - } - - public static function _getIdsForTitle($title, $type = '', $partialmatch = false) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = (!$partialmatch) - ? "SELECT obj_id FROM object_data WHERE title = ".$ilDB->quote($title, "text") - : "SELECT obj_id FROM object_data WHERE ".$ilDB->like("title", "text", '%'.$title.'%'); - if($type != '') - { - $query .= " AND type = ".$ilDB->quote($type, "text"); - } - - $result = $ilDB->query($query); - - $object_ids = array(); - while($row = $ilDB->fetchAssoc($result)) - { - $object_ids[] = $row['obj_id']; - } - - return is_array($object_ids) ? $object_ids : array(); - } - - /** - * lookup object description - * - * @param int $a_id object id - */ - public static function _lookupDescription($a_id) - { - global $DIC; - - $ilObjDataCache = $DIC["ilObjDataCache"]; - - return $ilObjDataCache->lookupDescription($a_id); - } - - /** - * lookup last update - * - * @param int $a_id object id - */ - static function _lookupLastUpdate($a_id, $a_as_string = false) - { - global $DIC; - - $ilObjDataCache = $DIC["ilObjDataCache"]; - - if ($a_as_string) - { - return ilDatePresentation::formatDate(new ilDateTime($ilObjDataCache->lookupLastUpdate($a_id),IL_CAL_DATETIME)); - } - else - { - return $ilObjDataCache->lookupLastUpdate($a_id); - } - } - - /** - * Get last update for a set of media objects. - * - * @param array - */ - static function _getLastUpdateOfObjects($a_objs) - { - global $DIC; - - $ilDB = $DIC->database(); - - if (!is_array($a_objs)) - { - $a_objs = array($a_objs); - } - $types = array(); - $set = $ilDB->query("SELECT max(last_update) as last_update FROM object_data ". - "WHERE ".$ilDB->in("obj_id", $a_objs, false, "integer")." "); - $rec = $ilDB->fetchAssoc($set); - - return ($rec["last_update"]); - } - - public static function _lookupObjId($a_id) - { - global $DIC; - - $ilObjDataCache = $DIC["ilObjDataCache"]; - - return (int) $ilObjDataCache->lookupObjId($a_id); - } - - /** - * only called in ilTree::saveSubTree - */ - static function _setDeletedDate($a_ref_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "UPDATE object_reference SET deleted= ".$ilDB->now().' '. - "WHERE ref_id = ".$ilDB->quote($a_ref_id,'integer'); - $res = $ilDB->manipulate($query); - } - - /** - * Set deleted date - * @param type $a_ref_ids - * @return type - */ - public static function setDeletedDates($a_ref_ids) - { - global $DIC; - - $ilDB = $DIC->database(); - $log = $DIC->logger()->root(); - - $query = 'UPDATE object_reference SET deleted = '.$ilDB->now().' '. - 'WHERE '.$ilDB->in('ref_id',(array) $a_ref_ids,false,'integer'); - - $log->debug(__METHOD__.': Query is '. $query); - $ilDB->manipulate($query); - return; - } - - /** - * only called in ilObjectGUI::insertSavedNodes - */ - public static function _resetDeletedDate($a_ref_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "UPDATE object_reference SET deleted = ".$ilDB->quote(null,'timestamp'). - " WHERE ref_id = ".$ilDB->quote($a_ref_id,'integer'); - $ilDB->manipulate($query); - } - - /** - * only called in ilObjectGUI::insertSavedNodes - */ - static function _lookupDeletedDate($a_ref_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT deleted FROM object_reference". - " WHERE ref_id = ".$ilDB->quote($a_ref_id, "integer"); - $set = $ilDB->query($query); - $rec = $ilDB->fetchAssoc($set); - - return $rec["deleted"]; - } - - - /** - * write title to db (static) - * - * @param int $a_obj_id object id - * @param string $a_title title - * @access public - */ - static function _writeTitle($a_obj_id, $a_title) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "UPDATE object_data ". - "SET ". - "title = ".$ilDB->quote($a_title, "text").",". - "last_update = ".$ilDB->now()." ". - "WHERE obj_id = ".$ilDB->quote($a_obj_id, "integer"); - - $ilDB->manipulate($q); - } - - /** - * write description to db (static) - * - * @param int $a_obj_id object id - * @param string $a_desc description - * @access public - */ - static function _writeDescription($a_obj_id, $a_desc) - { - global $DIC; - - $ilDB = $DIC->database(); - $objDefinition = $DIC["objDefinition"]; - - - $desc = ilUtil::shortenText($a_desc,self::DESC_LENGTH,true); - - $q = "UPDATE object_data ". - "SET ". - "description = ".$ilDB->quote($desc, "text").",". - "last_update = ".$ilDB->now()." ". - "WHERE obj_id = ".$ilDB->quote($a_obj_id, "integer"); - - $ilDB->manipulate($q); - - if($objDefinition->isRBACObject(ilObject::_lookupType($a_obj_id))) - { - // Update long description - $res = $ilDB->query("SELECT * FROM object_description WHERE obj_id = ". - $ilDB->quote($a_obj_id,'integer')); - - if($res->numRows()) - { - $values = array( - 'description' => array('clob',$a_desc) - ); - $ilDB->update('object_description',$values,array('obj_id' => array('integer',$a_obj_id))); - } - else - { - $values = array( - 'description' => array('clob',$a_desc), - 'obj_id' => array('integer',$a_obj_id)); - $ilDB->insert('object_description',$values); - } - } - } - - /** - * write import id to db (static) - * - * @param int $a_obj_id object id - * @param string $a_import_id import id - * @access public - */ - static function _writeImportId($a_obj_id, $a_import_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "UPDATE object_data ". - "SET ". - "import_id = ".$ilDB->quote($a_import_id, "text").",". - "last_update = ".$ilDB->now()." ". - "WHERE obj_id = ".$ilDB->quote($a_obj_id, "integer"); - - $ilDB->manipulate($q); - } - - /** - * lookup object type - * - * @param int $a_id object id - */ - public static function _lookupType($a_id,$a_reference = false) - { - global $DIC; - - $ilObjDataCache = $DIC["ilObjDataCache"]; - - if($a_reference) - { - return $ilObjDataCache->lookupType($ilObjDataCache->lookupObjId($a_id)); - } - return $ilObjDataCache->lookupType($a_id); - } - - /** - * checks wether object is in trash - */ - public static function _isInTrash($a_ref_id) - { - global $DIC; - - $tree = $DIC->repositoryTree(); - - return $tree->isSaved($a_ref_id); - } - - /** - * checks wether an object has at least one reference that is not in trash - */ - static function _hasUntrashedReference($a_obj_id) - { - $ref_ids = ilObject::_getAllReferences($a_obj_id); - foreach($ref_ids as $ref_id) - { - if(!ilObject::_isInTrash($ref_id)) - { - return true; - } - } - - return false; - } - - /** - * lookup object id - * @static - * @param int $a_id object id - */ - public static function _lookupObjectId($a_ref_id) - { - global $DIC; - - $ilObjDataCache = $DIC["ilObjDataCache"]; - - return (int) $ilObjDataCache->lookupObjId($a_ref_id); - } - - /** - * get all objects of a certain type - * - * @param string $a_type desired object type - * @param boolean $a_omit_trash omit objects, that are in trash only - * (default: false) - * - * @return array array of object data arrays ("id", "title", "type", - * "description") - */ - static function _getObjectsDataForType($a_type, $a_omit_trash = false) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "SELECT * FROM object_data WHERE type = ".$ilDB->quote($a_type, "text"); - $obj_set = $ilDB->query($q); - - $objects = array(); - while ($obj_rec = $ilDB->fetchAssoc($obj_set)) - { - if ((!$a_omit_trash) || ilObject::_hasUntrashedReference($obj_rec["obj_id"])) - { - $objects[$obj_rec["title"].".".$obj_rec["obj_id"]] = array("id" => $obj_rec["obj_id"], - "type" => $obj_rec["type"], "title" => $obj_rec["title"], - "description" => $obj_rec["description"]); - } - } - ksort($objects); - return $objects; - } - - - /** - * maybe this method should be in tree object!? - * - * @todo role/rbac stuff - * - * @param int $a_parent_ref Ref-ID of the parent object - */ - function putInTree($a_parent_ref) - { - $tree = $this->tree; - $ilLog = $this->log; - $ilAppEventHandler = $this->app_event_handler; - - $tree->insertNode($this->getRefId(), $a_parent_ref); - - // write log entry - $ilLog->write("ilObject::putInTree(), parent_ref: $a_parent_ref, ref_id: ". - $this->getRefId().", obj_id: ".$this->getId().", type: ". - $this->getType().", title: ".$this->getTitle()); - - $ilAppEventHandler->raise('Services/Object', 'putObjectInTree', array( - 'object' => $this, - 'obj_type' => $this->getType(), - 'obj_id' => $this->getId(), - 'parent_ref_id' => $a_parent_ref, - ) - ); - } - - /** - * set permissions of object - * - * @param integer reference_id of parent object - * @access public - */ - function setPermissions($a_parent_ref) - { - $this->setParentRolePermissions($a_parent_ref); - $this->initDefaultRoles(); - } - - /** - * Initialize the permissions of parent roles (local roles of categories, global roles...) - * This method is overwritten in e.g courses, groups for building permission intersections with non_member templates. - */ - public function setParentRolePermissions($a_parent_ref) - { - global $DIC; - - $rbacadmin = $DIC["rbacadmin"]; - $rbacreview = $DIC["rbacreview"]; - - $parent_roles = $rbacreview->getParentRoleIds($a_parent_ref); - foreach((array) $parent_roles as $parent_role) - { - $operations = $rbacreview->getOperationsOfRole( - $parent_role['obj_id'], - $this->getType(), - $parent_role['parent'] - ); - $rbacadmin->grantPermission( - $parent_role['obj_id'], - $operations, - $this->getRefId() - ); - } - return true; - } - - /** - * creates reference for object - * - * @access public - * @return integer reference_id of object - */ - function createReference() - { - $ilDB = $this->db; - $ilErr = $this->error; - - if (!isset($this->id)) - { - $message = "ilObject::createNewReference(): No obj_id given!"; - $ilErr->raiseError($message,$ilErr->WARNING); - } - - $next_id = $ilDB->nextId('object_reference'); - $query = "INSERT INTO object_reference ". - "(ref_id, obj_id) VALUES (".$ilDB->quote($next_id,'integer').','.$ilDB->quote($this->id ,'integer').")"; - $ilDB->query($query); - - $this->ref_id = $next_id; - $this->referenced = true; - - return $this->ref_id; - } - - - /** - * count references of object - * - * @access public - * @return integer number of references for this object - */ - function countReferences() - { - $ilDB = $this->db; - $ilErr = $this->error; - - if (!isset($this->id)) - { - $message = "ilObject::countReferences(): No obj_id given!"; - $ilErr->raiseError($message,$ilErr->WARNING); - } - - $query = "SELECT COUNT(ref_id) num FROM object_reference ". - "WHERE obj_id = ".$ilDB->quote($this->id,'integer')." "; - $res = $ilDB->query($query); - $row = $ilDB->fetchObject($res); - - return $row->num; - } - - - /** - * delete object or referenced object - * (in the case of a referenced object, object data is only deleted - * if last reference is deleted) - * This function removes an object entirely from system!! - * - * @access public - * @return boolean true if object was removed completely; false if only a references was - * removed - */ - function delete() - { - global $DIC; - - $rbacadmin = $DIC["rbacadmin"]; - $ilLog = $this->log; - $ilDB = $this->db; - $ilAppEventHandler = $this->app_event_handler; - $ilErr = $this->error; - /** - * @var $ilAppEventHandler ilAppEventHandler - */ - - $remove = false; - - // delete object_data entry - if ((!$this->referenced) || ($this->countReferences() == 1)) - { - // check type match - $db_type = ilObject::_lookupType($this->getId()); - if ($this->type != $db_type) - { - $message = "ilObject::delete(): Type mismatch. Object with obj_id: ".$this->id." ". - "was instantiated by type '".$this->type."'. DB type is: ".$db_type; - - // write log entry - $ilLog->write($message); - - // raise error - $ilErr->raiseError("ilObject::delete(): Type mismatch. (".$this->type."/".$this->id.")",$ilErr->WARNING); - } - - $ilAppEventHandler->raise('Services/Object', 'beforeDeletion', array( 'object' => $this )); - - // delete entry in object_data - $q = "DELETE FROM object_data ". - "WHERE obj_id = ".$ilDB->quote($this->getId(), "integer"); - $ilDB->manipulate($q); - - // delete long description - $query = "DELETE FROM object_description WHERE obj_id = ". - $ilDB->quote($this->getId(), "integer"); - $ilDB->manipulate($query); - - // write log entry - $ilLog->write("ilObject::delete(), deleted object, obj_id: ".$this->getId().", type: ". - $this->getType().", title: ".$this->getTitle()); - - // keep log of core object data - include_once "Services/Object/classes/class.ilObjectDataDeletionLog.php"; - ilObjectDataDeletionLog::add($this); - - // remove news - include_once("./Services/News/classes/class.ilNewsItem.php"); - $news_item = new ilNewsItem(); - $news_item->deleteNewsOfContext($this->getId(), $this->getType()); - include_once("./Services/Block/classes/class.ilBlockSetting.php"); - ilBlockSetting::_deleteSettingsOfBlock($this->getId(), "news"); - - include_once './Services/DidacticTemplate/classes/class.ilDidacticTemplateObjSettings.php'; - ilDidacticTemplateObjSettings::deleteByObjId($this->getId()); - - /* remove notes (see infoscreen gui) - as they can be seen as personal data we are keeping them for now - include_once("Services/Notes/classes/class.ilNote.php"); - foreach(array(IL_NOTE_PRIVATE, IL_NOTE_PUBLIC) as $note_type) - { - foreach(ilNote::_getNotesOfObject($this->id, 0, $this->type, $note_type) as $note) - { - $note->delete(); - } - } - */ - - // BEGIN WebDAV: Delete WebDAV properties - $query = "DELETE FROM dav_property ". - "WHERE obj_id = ".$ilDB->quote($this->getId(),'integer'); - $res = $ilDB->manipulate($query); - // END WebDAV: Delete WebDAV properties - - include_once './Services/WebServices/ECS/classes/class.ilECSImport.php'; - ilECSImport::_deleteByObjId($this->getId()); - - include_once("Services/AdvancedMetaData/classes/class.ilAdvancedMDValues.php"); - ilAdvancedMDValues::_deleteByObjId($this->getId()); - - include_once("Services/Tracking/classes/class.ilLPObjSettings.php"); - ilLPObjSettings::_deleteByObjId($this->getId()); - - $remove = true; - } - else - { - // write log entry - $ilLog->write("ilObject::delete(), object not deleted, number of references: ". - $this->countReferences().", obj_id: ".$this->getId().", type: ". - $this->getType().", title: ".$this->getTitle()); - } - - // delete object_reference entry - if ($this->referenced) - { - include_once "Services/Object/classes/class.ilObjectActivation.php"; - ilObjectActivation::deleteAllEntries($this->getRefId()); - - // delete entry in object_reference - $query = "DELETE FROM object_reference ". - "WHERE ref_id = ".$ilDB->quote($this->getRefId(),'integer'); - $res = $ilDB->manipulate($query); - - // write log entry - $ilLog->write("ilObject::delete(), reference deleted, ref_id: ".$this->getRefId(). - ", obj_id: ".$this->getId().", type: ". - $this->getType().", title: ".$this->getTitle()); - - // DELETE PERMISSION ENTRIES IN RBAC_PA - // DONE: method overwritten in ilObjRole & ilObjUser. - // this call only applies for objects in rbac (not usr,role,rolt) - // TODO: Do this for role templates too - $rbacadmin->revokePermission($this->getRefId(),0,false); - - include_once "Services/AccessControl/classes/class.ilRbacLog.php"; - ilRbacLog::delete($this->getRefId()); - - // Remove applied didactic template setting - include_once './Services/DidacticTemplate/classes/class.ilDidacticTemplateObjSettings.php'; - ilDidacticTemplateObjSettings::deleteByRefId($this->getRefId()); - - // Remove desktop items - ilUtil::removeItemFromDesktops($this->getRefId()); - } - - // remove conditions - if ($this->referenced) - { - $ch = new ilConditionHandler(); - $ch->delete($this->getRefId()); - unset($ch); - } - - return $remove; - } - - /** - * init default roles settings - * Purpose of this function is to create a local role folder and local roles, that are needed depending on the object type - * If you want to setup default local roles you MUST overwrite this method in derived object classes (see ilObjForum for an example) - * @access public - * @return array empty array - */ - function initDefaultRoles() - { - return array(); - } - - - /** - * Apply template - * @param int $a_tpl_id - */ - public function applyDidacticTemplate($a_tpl_id) - { - ilLoggerFactory::getLogger('obj')->debug('Applying didactic template with id: ' . (int) $a_tpl_id); - if($a_tpl_id) - { - include_once './Services/DidacticTemplate/classes/class.ilDidacticTemplateActionFactory.php'; - foreach(ilDidacticTemplateActionFactory::getActionsByTemplateId($a_tpl_id) as $action) - { - $action->setRefId($this->getRefId()); - $action->apply(); - } - } - - include_once './Services/DidacticTemplate/classes/class.ilDidacticTemplateObjSettings.php'; - ilDidacticTemplateObjSettings::assignTemplate($this->getRefId(), $this->getId(), (int) $a_tpl_id); - return $a_tpl_id ? true : false; - } - - /** - * checks if an object exists in object_data - * @static - * @access public - * @param integer object id or reference id - * @param boolean true if id is a reference, else false (default) - * @param string restrict on a certain type. - * @return boolean true if object exists - */ - public static function _exists($a_id, $a_reference = false, $a_type = null) - { - global $DIC; - - $ilDB = $DIC->database(); - - if ($a_reference) - { - $q = "SELECT * FROM object_data ". - "LEFT JOIN object_reference ON object_reference.obj_id=object_data.obj_id ". - "WHERE object_reference.ref_id= ".$ilDB->quote($a_id, "integer"); - } - else - { - $q = "SELECT * FROM object_data WHERE obj_id=".$ilDB->quote($a_id, "integer"); - } - - if($a_type) - $q .= " AND object_data.type = ".$ilDB->quote($a_type, "text"); - - $r = $ilDB->query($q); - - return $ilDB->numRows($r) ? true : false; - } - -// toggle subscription interface - function setRegisterMode($a_bool) - { - $this->register = (bool) $a_bool; - } - - // check register status of current user - // abstract method; overwrite in object type class - function isUserRegistered($a_user_id = 0) - { - return false; - } - - function requireRegistration() - { - return $this->register; - } - - - function getXMLZip() - { - return false; - } - function getHTMLDirectory() - { - return false; - } - - /** - * Get objects by type - */ - static function _getObjectsByType($a_obj_type = "", $a_owner = "") - { - global $DIC; - - $ilDB = $DIC->database(); - - $order = " ORDER BY title"; - - // where clause - if ($a_obj_type) - { - $where_clause = "WHERE type = ". - $ilDB->quote($a_obj_type, "text"); - - if ($a_owner != "") - { - $where_clause.= " AND owner = ".$ilDB->quote($a_owner, "integer"); - } - } - - $q = "SELECT * FROM object_data ".$where_clause.$order; - $r = $ilDB->query($q); - - $arr = array(); - if ($ilDB->numRows($r) > 0) - { - while ($row = $ilDB->fetchAssoc($r)) - { - $row["desc"] = $row["description"]; - $arr[$row["obj_id"]] = $row; - } - } - - return $arr; - } - - /** - * Prepare copy wizard object selection - * - * This method should renamed. Currently used in ilObjsurvey and ilObjTest - * @deprecated since version 5.2 - * @static - * - * @param array $a_ref_ids - * @param string $new_type - * @param bool $show_path - * @return array - */ - public static function _prepareCloneSelection($a_ref_ids,$new_type,$show_path = true) - { - global $DIC; - - $ilDB = $DIC->database(); - $lng = $DIC->language(); - $objDefinition = $DIC["objDefinition"]; - - $query = "SELECT obj_data.title obj_title,path_data.title path_title,child FROM tree ". - "JOIN object_reference obj_ref ON child = obj_ref.ref_id ". - "JOIN object_data obj_data ON obj_ref.obj_id = obj_data.obj_id ". - "JOIN object_reference path_ref ON parent = path_ref.ref_id ". - "JOIN object_data path_data ON path_ref.obj_id = path_data.obj_id ". - "WHERE ".$ilDB->in("child", $a_ref_ids, false, "integer")." ". - "ORDER BY obj_data.title "; - $res = $ilDB->query($query); - - if (!$objDefinition->isPlugin($new_type)) - { - $options[0] = $lng->txt('obj_'.$new_type.'_select'); - } - else - { - require_once("Services/Repository/classes/class.ilObjectPlugin.php"); - $options[0] = ilObjectPlugin::lookupTxtById($new_type, "obj_".$new_type."_select"); - } - - while($row = $ilDB->fetchObject($res)) - { - if(strlen($title = $row->obj_title) > 40) - { - $title = substr($title,0,40).'...'; - } - - if($show_path) - { - if(strlen($path = $row->path_title) > 40) - { - $path = substr($path,0,40).'...'; - } - - $title .= ' ('.$lng->txt('path').': '.$path.')'; - } - - $options[$row->child] = $title; - } - return $options ? $options : array(); - } - - /** - * Clone object permissions, put in tree ... - * - * @access public - * @param int target id - * @param int copy id for class.ilCopyWizardOptions() - * @return object new object - * - */ - public function cloneObject($a_target_id,$a_copy_id = 0, $a_omit_tree = false) - { - global $DIC; - - $objDefinition = $this->objDefinition; - $ilUser = $DIC["ilUser"]; - $rbacadmin = $DIC["rbacadmin"]; - $ilDB = $this->db; - $ilAppEventHandler = $this->app_event_handler; - /** - * @var $ilAppEventHandler ilAppEventHandler - */ - - $location = $objDefinition->getLocation($this->getType()); - $class_name = ('ilObj'.$objDefinition->getClassName($this->getType())); - - include_once './Services/CopyWizard/classes/class.ilCopyWizardOptions.php'; - $options = ilCopyWizardOptions::_getInstance($a_copy_id); - - if(!$options->isTreeCopyDisabled() && !$a_omit_tree) - { - $title = $this->appendCopyInfo($a_target_id,$a_copy_id); - } - else - { - $title = $this->getTitle(); - } - - // create instance - include_once($location."/class.".$class_name.".php"); - $new_obj = new $class_name(0, false); - $new_obj->setOwner($ilUser->getId()); - $new_obj->setTitle($title); - $new_obj->setDescription($this->getLongDescription()); - $new_obj->setType($this->getType()); - - // Choose upload mode to avoid creation of additional settings, db entries ... - $new_obj->create(true); - - if($this->supportsOfflineHandling()) - { - $new_obj->setOffLineStatus($this->getOfflineStatus()); - $new_obj->update(); - } - - if(!$options->isTreeCopyDisabled() && !$a_omit_tree) - { - ilLoggerFactory::getLogger('obj')->debug('Tree copy is enabled'); - $new_obj->createReference(); - $new_obj->putInTree($a_target_id); - $new_obj->setPermissions($a_target_id); - - // when copying from personal workspace we have no current ref id - if($this->getRefId()) - { - // copy local roles - $rbacadmin->copyLocalRoles($this->getRefId(),$new_obj->getRefId()); - } - } - else - { - ilLoggerFactory::getLogger('obj')->debug('Tree copy is disabled'); - } - - include_once('./Services/AdvancedMetaData/classes/class.ilAdvancedMDValues.php'); - ilAdvancedMDValues::_cloneValues($this->getId(),$new_obj->getId()); - - // BEGIN WebDAV: Clone WebDAV properties - $query = "INSERT INTO dav_property (obj_id,node_id,ns,name,value) ". - "SELECT ".$ilDB->quote($new_obj->getId(),'integer').",node_id,ns,name,value ". - "FROM dav_property ". - "WHERE obj_id = ".$ilDB->quote($this->getId(),'integer'); - $res = $ilDB->manipulate($query); - // END WebDAV: Clone WebDAV properties - - /** @var \ilObjectCustomIconFactory $customIconFactory */ - $customIconFactory = $DIC['object.customicons.factory']; - $customIcon = $customIconFactory->getByObjId($this->getId(), $this->getType()); - $customIcon->copy($new_obj->getId()); + /** + * get current object id for import id (static) + * + * @param int $a_import_id import id + * + * @return int id + */ + public static function _getIdForImportId($a_import_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $ilDB->setLimit(1, 0); + $q = "SELECT * FROM object_data WHERE import_id = " . $ilDB->quote($a_import_id, "text") . + " ORDER BY create_date DESC"; + $obj_set = $ilDB->query($q); + + if ($obj_rec = $ilDB->fetchAssoc($obj_set)) { + return $obj_rec["obj_id"]; + } else { + return 0; + } + } + + /** + * get all reference ids of object + * + * @param int $a_id object id + */ + public static function _getAllReferences($a_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT * FROM object_reference WHERE obj_id = " . + $ilDB->quote($a_id, 'integer'); + + $res = $ilDB->query($query); + $ref = array(); + while ($obj_rec = $ilDB->fetchAssoc($res)) { + $ref[$obj_rec["ref_id"]] = $obj_rec["ref_id"]; + } + + return $ref; + } + + /** + * lookup object title + * + * @param int $a_id object id + */ + public static function _lookupTitle($a_id) + { + global $DIC; + + $ilObjDataCache = $DIC["ilObjDataCache"]; + + $tit = $ilObjDataCache->lookupTitle($a_id); + //echo "
                  LOOKING-$a_id-:$tit"; + return $tit; + } + + /** + * Lookup offline status using objectDataCache + * + * @static + * @param $a_obj_id + * @return null | bool + */ + public static function lookupOfflineStatus($a_obj_id) + { + global $DIC; + + return $DIC['ilObjDataCache']->lookupOfflineStatus($a_obj_id); + } + + + + /** + * lookup object owner + * + * @param int $a_id object id + */ + public static function _lookupOwner($a_id) + { + global $DIC; + + $ilObjDataCache = $DIC["ilObjDataCache"]; + + $owner = $ilObjDataCache->lookupOwner($a_id); + return $owner; + } + + public static function _getIdsForTitle($title, $type = '', $partialmatch = false) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = (!$partialmatch) + ? "SELECT obj_id FROM object_data WHERE title = " . $ilDB->quote($title, "text") + : "SELECT obj_id FROM object_data WHERE " . $ilDB->like("title", "text", '%' . $title . '%'); + if ($type != '') { + $query .= " AND type = " . $ilDB->quote($type, "text"); + } + + $result = $ilDB->query($query); + + $object_ids = array(); + while ($row = $ilDB->fetchAssoc($result)) { + $object_ids[] = $row['obj_id']; + } + + return is_array($object_ids) ? $object_ids : array(); + } + + /** + * lookup object description + * + * @param int $a_id object id + */ + public static function _lookupDescription($a_id) + { + global $DIC; + + $ilObjDataCache = $DIC["ilObjDataCache"]; + + return $ilObjDataCache->lookupDescription($a_id); + } + + /** + * lookup last update + * + * @param int $a_id object id + */ + public static function _lookupLastUpdate($a_id, $a_as_string = false) + { + global $DIC; + + $ilObjDataCache = $DIC["ilObjDataCache"]; + + if ($a_as_string) { + return ilDatePresentation::formatDate(new ilDateTime($ilObjDataCache->lookupLastUpdate($a_id), IL_CAL_DATETIME)); + } else { + return $ilObjDataCache->lookupLastUpdate($a_id); + } + } + + /** + * Get last update for a set of media objects. + * + * @param array + */ + public static function _getLastUpdateOfObjects($a_objs) + { + global $DIC; + + $ilDB = $DIC->database(); + + if (!is_array($a_objs)) { + $a_objs = array($a_objs); + } + $types = array(); + $set = $ilDB->query("SELECT max(last_update) as last_update FROM object_data " . + "WHERE " . $ilDB->in("obj_id", $a_objs, false, "integer") . " "); + $rec = $ilDB->fetchAssoc($set); + + return ($rec["last_update"]); + } + + public static function _lookupObjId($a_id) + { + global $DIC; + + $ilObjDataCache = $DIC["ilObjDataCache"]; + + return (int) $ilObjDataCache->lookupObjId($a_id); + } + + /** + * only called in ilTree::saveSubTree + */ + public static function _setDeletedDate($a_ref_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "UPDATE object_reference SET deleted= " . $ilDB->now() . ' ' . + "WHERE ref_id = " . $ilDB->quote($a_ref_id, 'integer'); + $res = $ilDB->manipulate($query); + } + + /** + * Set deleted date + * @param type $a_ref_ids + * @return type + */ + public static function setDeletedDates($a_ref_ids) + { + global $DIC; + + $ilDB = $DIC->database(); + $log = $DIC->logger()->root(); + + $query = 'UPDATE object_reference SET deleted = ' . $ilDB->now() . ' ' . + 'WHERE ' . $ilDB->in('ref_id', (array) $a_ref_ids, false, 'integer'); + + $log->debug(__METHOD__ . ': Query is ' . $query); + $ilDB->manipulate($query); + return; + } + + /** + * only called in ilObjectGUI::insertSavedNodes + */ + public static function _resetDeletedDate($a_ref_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "UPDATE object_reference SET deleted = " . $ilDB->quote(null, 'timestamp') . + " WHERE ref_id = " . $ilDB->quote($a_ref_id, 'integer'); + $ilDB->manipulate($query); + } + + /** + * only called in ilObjectGUI::insertSavedNodes + */ + public static function _lookupDeletedDate($a_ref_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT deleted FROM object_reference" . + " WHERE ref_id = " . $ilDB->quote($a_ref_id, "integer"); + $set = $ilDB->query($query); + $rec = $ilDB->fetchAssoc($set); + + return $rec["deleted"]; + } + + + /** + * write title to db (static) + * + * @param int $a_obj_id object id + * @param string $a_title title + * @access public + */ + public static function _writeTitle($a_obj_id, $a_title) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "UPDATE object_data " . + "SET " . + "title = " . $ilDB->quote($a_title, "text") . "," . + "last_update = " . $ilDB->now() . " " . + "WHERE obj_id = " . $ilDB->quote($a_obj_id, "integer"); + + $ilDB->manipulate($q); + } + + /** + * write description to db (static) + * + * @param int $a_obj_id object id + * @param string $a_desc description + * @access public + */ + public static function _writeDescription($a_obj_id, $a_desc) + { + global $DIC; + + $ilDB = $DIC->database(); + $objDefinition = $DIC["objDefinition"]; + + + $desc = ilUtil::shortenText($a_desc, self::DESC_LENGTH, true); + + $q = "UPDATE object_data " . + "SET " . + "description = " . $ilDB->quote($desc, "text") . "," . + "last_update = " . $ilDB->now() . " " . + "WHERE obj_id = " . $ilDB->quote($a_obj_id, "integer"); + + $ilDB->manipulate($q); + + if ($objDefinition->isRBACObject(ilObject::_lookupType($a_obj_id))) { + // Update long description + $res = $ilDB->query("SELECT * FROM object_description WHERE obj_id = " . + $ilDB->quote($a_obj_id, 'integer')); + + if ($res->numRows()) { + $values = array( + 'description' => array('clob',$a_desc) + ); + $ilDB->update('object_description', $values, array('obj_id' => array('integer',$a_obj_id))); + } else { + $values = array( + 'description' => array('clob',$a_desc), + 'obj_id' => array('integer',$a_obj_id)); + $ilDB->insert('object_description', $values); + } + } + } + + /** + * write import id to db (static) + * + * @param int $a_obj_id object id + * @param string $a_import_id import id + * @access public + */ + public static function _writeImportId($a_obj_id, $a_import_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "UPDATE object_data " . + "SET " . + "import_id = " . $ilDB->quote($a_import_id, "text") . "," . + "last_update = " . $ilDB->now() . " " . + "WHERE obj_id = " . $ilDB->quote($a_obj_id, "integer"); + + $ilDB->manipulate($q); + } + + /** + * lookup object type + * + * @param int $a_id object id + */ + public static function _lookupType($a_id, $a_reference = false) + { + global $DIC; + + $ilObjDataCache = $DIC["ilObjDataCache"]; + + if ($a_reference) { + return $ilObjDataCache->lookupType($ilObjDataCache->lookupObjId($a_id)); + } + return $ilObjDataCache->lookupType($a_id); + } + + /** + * checks wether object is in trash + */ + public static function _isInTrash($a_ref_id) + { + global $DIC; + + $tree = $DIC->repositoryTree(); + + return $tree->isSaved($a_ref_id); + } + + /** + * checks wether an object has at least one reference that is not in trash + */ + public static function _hasUntrashedReference($a_obj_id) + { + $ref_ids = ilObject::_getAllReferences($a_obj_id); + foreach ($ref_ids as $ref_id) { + if (!ilObject::_isInTrash($ref_id)) { + return true; + } + } + + return false; + } + + /** + * lookup object id + * @static + * @param int $a_id object id + */ + public static function _lookupObjectId($a_ref_id) + { + global $DIC; + + $ilObjDataCache = $DIC["ilObjDataCache"]; + + return (int) $ilObjDataCache->lookupObjId($a_ref_id); + } + + /** + * get all objects of a certain type + * + * @param string $a_type desired object type + * @param boolean $a_omit_trash omit objects, that are in trash only + * (default: false) + * + * @return array array of object data arrays ("id", "title", "type", + * "description") + */ + public static function _getObjectsDataForType($a_type, $a_omit_trash = false) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "SELECT * FROM object_data WHERE type = " . $ilDB->quote($a_type, "text"); + $obj_set = $ilDB->query($q); + + $objects = array(); + while ($obj_rec = $ilDB->fetchAssoc($obj_set)) { + if ((!$a_omit_trash) || ilObject::_hasUntrashedReference($obj_rec["obj_id"])) { + $objects[$obj_rec["title"] . "." . $obj_rec["obj_id"]] = array("id" => $obj_rec["obj_id"], + "type" => $obj_rec["type"], "title" => $obj_rec["title"], + "description" => $obj_rec["description"]); + } + } + ksort($objects); + return $objects; + } + + + /** + * maybe this method should be in tree object!? + * + * @todo role/rbac stuff + * + * @param int $a_parent_ref Ref-ID of the parent object + */ + public function putInTree($a_parent_ref) + { + $tree = $this->tree; + $ilLog = $this->log; + $ilAppEventHandler = $this->app_event_handler; + + $tree->insertNode($this->getRefId(), $a_parent_ref); + + // write log entry + $ilLog->write("ilObject::putInTree(), parent_ref: $a_parent_ref, ref_id: " . + $this->getRefId() . ", obj_id: " . $this->getId() . ", type: " . + $this->getType() . ", title: " . $this->getTitle()); + + $ilAppEventHandler->raise( + 'Services/Object', + 'putObjectInTree', + array( + 'object' => $this, + 'obj_type' => $this->getType(), + 'obj_id' => $this->getId(), + 'parent_ref_id' => $a_parent_ref, + ) + ); + } + + /** + * set permissions of object + * + * @param integer reference_id of parent object + * @access public + */ + public function setPermissions($a_parent_ref) + { + $this->setParentRolePermissions($a_parent_ref); + $this->initDefaultRoles(); + } + + /** + * Initialize the permissions of parent roles (local roles of categories, global roles...) + * This method is overwritten in e.g courses, groups for building permission intersections with non_member templates. + */ + public function setParentRolePermissions($a_parent_ref) + { + global $DIC; + + $rbacadmin = $DIC["rbacadmin"]; + $rbacreview = $DIC["rbacreview"]; + + $parent_roles = $rbacreview->getParentRoleIds($a_parent_ref); + foreach ((array) $parent_roles as $parent_role) { + $operations = $rbacreview->getOperationsOfRole( + $parent_role['obj_id'], + $this->getType(), + $parent_role['parent'] + ); + $rbacadmin->grantPermission( + $parent_role['obj_id'], + $operations, + $this->getRefId() + ); + } + return true; + } + + /** + * creates reference for object + * + * @access public + * @return integer reference_id of object + */ + public function createReference() + { + $ilDB = $this->db; + $ilErr = $this->error; + + if (!isset($this->id)) { + $message = "ilObject::createNewReference(): No obj_id given!"; + $ilErr->raiseError($message, $ilErr->WARNING); + } + + $next_id = $ilDB->nextId('object_reference'); + $query = "INSERT INTO object_reference " . + "(ref_id, obj_id) VALUES (" . $ilDB->quote($next_id, 'integer') . ',' . $ilDB->quote($this->id, 'integer') . ")"; + $ilDB->query($query); + + $this->ref_id = $next_id; + $this->referenced = true; + + return $this->ref_id; + } + + + /** + * count references of object + * + * @access public + * @return integer number of references for this object + */ + public function countReferences() + { + $ilDB = $this->db; + $ilErr = $this->error; + + if (!isset($this->id)) { + $message = "ilObject::countReferences(): No obj_id given!"; + $ilErr->raiseError($message, $ilErr->WARNING); + } + + $query = "SELECT COUNT(ref_id) num FROM object_reference " . + "WHERE obj_id = " . $ilDB->quote($this->id, 'integer') . " "; + $res = $ilDB->query($query); + $row = $ilDB->fetchObject($res); + + return $row->num; + } + + + /** + * delete object or referenced object + * (in the case of a referenced object, object data is only deleted + * if last reference is deleted) + * This function removes an object entirely from system!! + * + * @access public + * @return boolean true if object was removed completely; false if only a references was + * removed + */ + public function delete() + { + global $DIC; + + $rbacadmin = $DIC["rbacadmin"]; + $ilLog = $this->log; + $ilDB = $this->db; + $ilAppEventHandler = $this->app_event_handler; + $ilErr = $this->error; + /** + * @var $ilAppEventHandler ilAppEventHandler + */ + + $remove = false; + + // delete object_data entry + if ((!$this->referenced) || ($this->countReferences() == 1)) { + // check type match + $db_type = ilObject::_lookupType($this->getId()); + if ($this->type != $db_type) { + $message = "ilObject::delete(): Type mismatch. Object with obj_id: " . $this->id . " " . + "was instantiated by type '" . $this->type . "'. DB type is: " . $db_type; + + // write log entry + $ilLog->write($message); + + // raise error + $ilErr->raiseError("ilObject::delete(): Type mismatch. (" . $this->type . "/" . $this->id . ")", $ilErr->WARNING); + } + + $ilAppEventHandler->raise('Services/Object', 'beforeDeletion', array( 'object' => $this )); + + // delete entry in object_data + $q = "DELETE FROM object_data " . + "WHERE obj_id = " . $ilDB->quote($this->getId(), "integer"); + $ilDB->manipulate($q); + + // delete long description + $query = "DELETE FROM object_description WHERE obj_id = " . + $ilDB->quote($this->getId(), "integer"); + $ilDB->manipulate($query); + + // write log entry + $ilLog->write("ilObject::delete(), deleted object, obj_id: " . $this->getId() . ", type: " . + $this->getType() . ", title: " . $this->getTitle()); + + // keep log of core object data + include_once "Services/Object/classes/class.ilObjectDataDeletionLog.php"; + ilObjectDataDeletionLog::add($this); + + // remove news + include_once("./Services/News/classes/class.ilNewsItem.php"); + $news_item = new ilNewsItem(); + $news_item->deleteNewsOfContext($this->getId(), $this->getType()); + include_once("./Services/Block/classes/class.ilBlockSetting.php"); + ilBlockSetting::_deleteSettingsOfBlock($this->getId(), "news"); + + include_once './Services/DidacticTemplate/classes/class.ilDidacticTemplateObjSettings.php'; + ilDidacticTemplateObjSettings::deleteByObjId($this->getId()); + + /* remove notes (see infoscreen gui) + as they can be seen as personal data we are keeping them for now + include_once("Services/Notes/classes/class.ilNote.php"); + foreach(array(IL_NOTE_PRIVATE, IL_NOTE_PUBLIC) as $note_type) + { + foreach(ilNote::_getNotesOfObject($this->id, 0, $this->type, $note_type) as $note) + { + $note->delete(); + } + } + */ + + // BEGIN WebDAV: Delete WebDAV properties + $query = "DELETE FROM dav_property " . + "WHERE obj_id = " . $ilDB->quote($this->getId(), 'integer'); + $res = $ilDB->manipulate($query); + // END WebDAV: Delete WebDAV properties + + include_once './Services/WebServices/ECS/classes/class.ilECSImport.php'; + ilECSImport::_deleteByObjId($this->getId()); + + include_once("Services/AdvancedMetaData/classes/class.ilAdvancedMDValues.php"); + ilAdvancedMDValues::_deleteByObjId($this->getId()); + + include_once("Services/Tracking/classes/class.ilLPObjSettings.php"); + ilLPObjSettings::_deleteByObjId($this->getId()); + + $remove = true; + } else { + // write log entry + $ilLog->write("ilObject::delete(), object not deleted, number of references: " . + $this->countReferences() . ", obj_id: " . $this->getId() . ", type: " . + $this->getType() . ", title: " . $this->getTitle()); + } + + // delete object_reference entry + if ($this->referenced) { + include_once "Services/Object/classes/class.ilObjectActivation.php"; + ilObjectActivation::deleteAllEntries($this->getRefId()); + + // delete entry in object_reference + $query = "DELETE FROM object_reference " . + "WHERE ref_id = " . $ilDB->quote($this->getRefId(), 'integer'); + $res = $ilDB->manipulate($query); + + // write log entry + $ilLog->write("ilObject::delete(), reference deleted, ref_id: " . $this->getRefId() . + ", obj_id: " . $this->getId() . ", type: " . + $this->getType() . ", title: " . $this->getTitle()); + + // DELETE PERMISSION ENTRIES IN RBAC_PA + // DONE: method overwritten in ilObjRole & ilObjUser. + // this call only applies for objects in rbac (not usr,role,rolt) + // TODO: Do this for role templates too + $rbacadmin->revokePermission($this->getRefId(), 0, false); + + include_once "Services/AccessControl/classes/class.ilRbacLog.php"; + ilRbacLog::delete($this->getRefId()); + + // Remove applied didactic template setting + include_once './Services/DidacticTemplate/classes/class.ilDidacticTemplateObjSettings.php'; + ilDidacticTemplateObjSettings::deleteByRefId($this->getRefId()); + + // Remove desktop items + ilUtil::removeItemFromDesktops($this->getRefId()); + } + + // remove conditions + if ($this->referenced) { + $ch = new ilConditionHandler(); + $ch->delete($this->getRefId()); + unset($ch); + } + + return $remove; + } + + /** + * init default roles settings + * Purpose of this function is to create a local role folder and local roles, that are needed depending on the object type + * If you want to setup default local roles you MUST overwrite this method in derived object classes (see ilObjForum for an example) + * @access public + * @return array empty array + */ + public function initDefaultRoles() + { + return array(); + } + + + /** + * Apply template + * @param int $a_tpl_id + */ + public function applyDidacticTemplate($a_tpl_id) + { + ilLoggerFactory::getLogger('obj')->debug('Applying didactic template with id: ' . (int) $a_tpl_id); + if ($a_tpl_id) { + include_once './Services/DidacticTemplate/classes/class.ilDidacticTemplateActionFactory.php'; + foreach (ilDidacticTemplateActionFactory::getActionsByTemplateId($a_tpl_id) as $action) { + $action->setRefId($this->getRefId()); + $action->apply(); + } + } + + include_once './Services/DidacticTemplate/classes/class.ilDidacticTemplateObjSettings.php'; + ilDidacticTemplateObjSettings::assignTemplate($this->getRefId(), $this->getId(), (int) $a_tpl_id); + return $a_tpl_id ? true : false; + } + + /** + * checks if an object exists in object_data + * @static + * @access public + * @param integer object id or reference id + * @param boolean true if id is a reference, else false (default) + * @param string restrict on a certain type. + * @return boolean true if object exists + */ + public static function _exists($a_id, $a_reference = false, $a_type = null) + { + global $DIC; + + $ilDB = $DIC->database(); + + if ($a_reference) { + $q = "SELECT * FROM object_data " . + "LEFT JOIN object_reference ON object_reference.obj_id=object_data.obj_id " . + "WHERE object_reference.ref_id= " . $ilDB->quote($a_id, "integer"); + } else { + $q = "SELECT * FROM object_data WHERE obj_id=" . $ilDB->quote($a_id, "integer"); + } + + if ($a_type) { + $q .= " AND object_data.type = " . $ilDB->quote($a_type, "text"); + } + + $r = $ilDB->query($q); + + return $ilDB->numRows($r) ? true : false; + } + + // toggle subscription interface + public function setRegisterMode($a_bool) + { + $this->register = (bool) $a_bool; + } + + // check register status of current user + // abstract method; overwrite in object type class + public function isUserRegistered($a_user_id = 0) + { + return false; + } + + public function requireRegistration() + { + return $this->register; + } + + + public function getXMLZip() + { + return false; + } + public function getHTMLDirectory() + { + return false; + } + + /** + * Get objects by type + */ + public static function _getObjectsByType($a_obj_type = "", $a_owner = "") + { + global $DIC; + + $ilDB = $DIC->database(); + + $order = " ORDER BY title"; + + // where clause + if ($a_obj_type) { + $where_clause = "WHERE type = " . + $ilDB->quote($a_obj_type, "text"); + + if ($a_owner != "") { + $where_clause.= " AND owner = " . $ilDB->quote($a_owner, "integer"); + } + } + + $q = "SELECT * FROM object_data " . $where_clause . $order; + $r = $ilDB->query($q); + + $arr = array(); + if ($ilDB->numRows($r) > 0) { + while ($row = $ilDB->fetchAssoc($r)) { + $row["desc"] = $row["description"]; + $arr[$row["obj_id"]] = $row; + } + } + + return $arr; + } + + /** + * Prepare copy wizard object selection + * + * This method should renamed. Currently used in ilObjsurvey and ilObjTest + * @deprecated since version 5.2 + * @static + * + * @param array $a_ref_ids + * @param string $new_type + * @param bool $show_path + * @return array + */ + public static function _prepareCloneSelection($a_ref_ids, $new_type, $show_path = true) + { + global $DIC; + + $ilDB = $DIC->database(); + $lng = $DIC->language(); + $objDefinition = $DIC["objDefinition"]; + + $query = "SELECT obj_data.title obj_title,path_data.title path_title,child FROM tree " . + "JOIN object_reference obj_ref ON child = obj_ref.ref_id " . + "JOIN object_data obj_data ON obj_ref.obj_id = obj_data.obj_id " . + "JOIN object_reference path_ref ON parent = path_ref.ref_id " . + "JOIN object_data path_data ON path_ref.obj_id = path_data.obj_id " . + "WHERE " . $ilDB->in("child", $a_ref_ids, false, "integer") . " " . + "ORDER BY obj_data.title "; + $res = $ilDB->query($query); + + if (!$objDefinition->isPlugin($new_type)) { + $options[0] = $lng->txt('obj_' . $new_type . '_select'); + } else { + require_once("Services/Repository/classes/class.ilObjectPlugin.php"); + $options[0] = ilObjectPlugin::lookupTxtById($new_type, "obj_" . $new_type . "_select"); + } + + while ($row = $ilDB->fetchObject($res)) { + if (strlen($title = $row->obj_title) > 40) { + $title = substr($title, 0, 40) . '...'; + } + + if ($show_path) { + if (strlen($path = $row->path_title) > 40) { + $path = substr($path, 0, 40) . '...'; + } + + $title .= ' (' . $lng->txt('path') . ': ' . $path . ')'; + } + + $options[$row->child] = $title; + } + return $options ? $options : array(); + } + + /** + * Clone object permissions, put in tree ... + * + * @access public + * @param int target id + * @param int copy id for class.ilCopyWizardOptions() + * @return object new object + * + */ + public function cloneObject($a_target_id, $a_copy_id = 0, $a_omit_tree = false) + { + global $DIC; + + $objDefinition = $this->objDefinition; + $ilUser = $DIC["ilUser"]; + $rbacadmin = $DIC["rbacadmin"]; + $ilDB = $this->db; + $ilAppEventHandler = $this->app_event_handler; + /** + * @var $ilAppEventHandler ilAppEventHandler + */ + + $location = $objDefinition->getLocation($this->getType()); + $class_name = ('ilObj' . $objDefinition->getClassName($this->getType())); + + include_once './Services/CopyWizard/classes/class.ilCopyWizardOptions.php'; + $options = ilCopyWizardOptions::_getInstance($a_copy_id); + + if (!$options->isTreeCopyDisabled() && !$a_omit_tree) { + $title = $this->appendCopyInfo($a_target_id, $a_copy_id); + } else { + $title = $this->getTitle(); + } + + // create instance + include_once($location . "/class." . $class_name . ".php"); + $new_obj = new $class_name(0, false); + $new_obj->setOwner($ilUser->getId()); + $new_obj->setTitle($title); + $new_obj->setDescription($this->getLongDescription()); + $new_obj->setType($this->getType()); + + // Choose upload mode to avoid creation of additional settings, db entries ... + $new_obj->create(true); + + if ($this->supportsOfflineHandling()) { + $new_obj->setOffLineStatus($this->getOfflineStatus()); + $new_obj->update(); + } + + if (!$options->isTreeCopyDisabled() && !$a_omit_tree) { + ilLoggerFactory::getLogger('obj')->debug('Tree copy is enabled'); + $new_obj->createReference(); + $new_obj->putInTree($a_target_id); + $new_obj->setPermissions($a_target_id); + + // when copying from personal workspace we have no current ref id + if ($this->getRefId()) { + // copy local roles + $rbacadmin->copyLocalRoles($this->getRefId(), $new_obj->getRefId()); + } + } else { + ilLoggerFactory::getLogger('obj')->debug('Tree copy is disabled'); + } + + include_once('./Services/AdvancedMetaData/classes/class.ilAdvancedMDValues.php'); + ilAdvancedMDValues::_cloneValues($this->getId(), $new_obj->getId()); + + // BEGIN WebDAV: Clone WebDAV properties + $query = "INSERT INTO dav_property (obj_id,node_id,ns,name,value) " . + "SELECT " . $ilDB->quote($new_obj->getId(), 'integer') . ",node_id,ns,name,value " . + "FROM dav_property " . + "WHERE obj_id = " . $ilDB->quote($this->getId(), 'integer'); + $res = $ilDB->manipulate($query); + // END WebDAV: Clone WebDAV properties + + /** @var \ilObjectCustomIconFactory $customIconFactory */ + $customIconFactory = $DIC['object.customicons.factory']; + $customIcon = $customIconFactory->getByObjId($this->getId(), $this->getType()); + $customIcon->copy($new_obj->getId()); $tile_image = $DIC->object()->commonSettings()->tileImage()->getByObjId($this->getId()); $tile_image->copy($new_obj->getId()); - $ilAppEventHandler->raise('Services/Object', 'cloneObject', array( - 'object' => $new_obj, - 'cloned_from_object' => $this, - )); - - return $new_obj; - } - - /** - * Prepend Copy info if object with same name exists in that container - * - * @access public - * @param int copy_id - * - */ - public function appendCopyInfo($a_target_id,$a_copy_id) - { - $tree = $this->tree; - - include_once('Services/CopyWizard/classes/class.ilCopyWizardOptions.php'); - $cp_options = ilCopyWizardOptions::_getInstance($a_copy_id); - if(!$cp_options->isRootNode($this->getRefId())) - { - return $this->getTitle(); - } - $nodes = $tree->getChilds($a_target_id); - - $title_unique = false; - require_once 'Modules/File/classes/class.ilObjFileAccess.php'; - $numberOfCopy = 1; - $handleExtension = ($this->getType() == "file"); // #14883 - $title = ilObjFileAccess::_appendNumberOfCopyToFilename($this->getTitle(), $numberOfCopy, $handleExtension); - while(!$title_unique) - { - $found = 0; - foreach($nodes as $node) - { - if(($title == $node['title']) and ($this->getType() == $node['type'])) - { - $found++; - } - } - if($found > 0) - { - $title = ilObjFileAccess::_appendNumberOfCopyToFilename($this->getTitle(), ++$numberOfCopy, $handleExtension); - } - else - { - break; - } - } - return $title; - } - - /** - * Clone object dependencies - * - * This method allows to refresh any ref id references to other objects - * that are affected in the same copy process. Ask ilCopyWizardOptions for - * the mappings. - * - * @access public - * @param int ref_id of target object - * @param int copy_id - * - */ - public function cloneDependencies($a_target_id,$a_copy_id) - { - include_once './Services/Conditions/classes/class.ilConditionHandler.php' ; - ilConditionHandler::cloneDependencies($this->getRefId(),$a_target_id,$a_copy_id); - - include_once './Services/DidacticTemplate/classes/class.ilDidacticTemplateObjSettings.php'; - $tpl_id = ilDidacticTemplateObjSettings::lookupTemplateId($this->getRefId()); - if($tpl_id) - { - include_once './Services/Object/classes/class.ilObjectFactory.php'; - $factory = new ilObjectFactory(); - $obj = $factory->getInstanceByRefId($a_target_id, FALSE); - if($obj instanceof ilObject) - { - $obj->applyDidacticTemplate($tpl_id); - } - } - return true; - } - - /** - * Copy meta data - * - * @access public - * @param object target object - * - */ - public function cloneMetaData($target_obj) - { - $md = new ilMD($this->getId(),0,$this->getType()); - $md->cloneMD($target_obj->getId(),0,$target_obj->getType()); - return true; - } - - /** - * Get icon for repository item. - * - * @param int object id - * @param string size (big, small, tiny) - * @param string object type - * @param boolean true: offline, false: online - */ - public static function _getIcon( - $a_obj_id = "", - $a_size = "big", - $a_type = "", - $a_offline = false) - { - global $DIC; - - $ilSetting = $DIC->settings(); - $objDefinition = $DIC["objDefinition"]; - - if ($a_obj_id == "" && $a_type == "") - { - return ""; - } - - if ($a_type == "") - { - $a_type = ilObject::_lookupType($a_obj_id); - } - - if ($a_size == "") - { - $a_size = "big"; - } - - if( - $a_obj_id && - $ilSetting->get('custom_icons') - ) { - /** @var \ilObjectCustomIconFactory $customIconFactory */ - $customIconFactory = $DIC['object.customicons.factory']; - $customIcon = $customIconFactory->getPresenterByObjId((int)$a_obj_id, (string)$a_type); - if ($customIcon->exists()) { - $filename = $customIcon->getFullPath(); - return $filename . '?tmp=' . filemtime($filename); - } - } - - if (!$a_offline) - { - if ($objDefinition->isPluginTypeName($a_type)) - { - if ($objDefinition->getClassName($a_type) != "") - { - $class_name = "il".$objDefinition->getClassName($a_type).'Plugin'; - $location = $objDefinition->getLocation($a_type); - if (is_file($location."/class.".$class_name.".php")) - { - include_once($location."/class.".$class_name.".php"); - return call_user_func(array($class_name, "_getIcon"), $a_type, $a_size, $a_obj_id); - } - } - return ilUtil::getImagePath("icon_cmps.svg"); - } - - return ilUtil::getImagePath("icon_".$a_type.".svg"); - } - else - { - return "./images/icon_".$a_type.".svg"; - } - } - - /** - * Collect deletion dependencies. E.g. - * - * @param - * @return - */ - static function collectDeletionDependencies(&$deps, $a_ref_id, $a_obj_id, $a_type, $a_depth = 0) - { - global $DIC; - - $objDefinition = $DIC["objDefinition"]; - $tree = $DIC->repositoryTree(); - - if ($a_depth == 0) - { - $deps["dep"] = array(); - } - - $deps["del_ids"][$a_obj_id] = $a_obj_id; - - if (!$objDefinition->isPluginTypeName($a_type)) - { - $class_name = "ilObj".$objDefinition->getClassName($a_type); - $location = $objDefinition->getLocation($a_type); - include_once($location."/class.".$class_name.".php"); - $odeps = call_user_func(array($class_name, "getDeletionDependencies"), $a_obj_id); - if (is_array($odeps)) - { - foreach ($odeps as $id => $message) - { - $deps["dep"][$id][$a_obj_id][] = $message; - } - } - - // get deletion dependency of childs - foreach ($tree->getChilds($a_ref_id) as $c) - { - ilObject::collectDeletionDependencies($deps, $c["child"], $c["obj_id"], $c["type"], $a_depth + 1); - } - } - - // delete all dependencies to objects that will be deleted, too - if ($a_depth == 0) - { - foreach ($deps["del_ids"] as $obj_id) - { - unset($deps["dep"][$obj_id]); - } - $deps = $deps["dep"]; - } - } - - /** - * Get deletion dependencies - * - */ - static function getDeletionDependencies($a_obj_id) - { - return false; - } - - /** - * Get long description data - * - * @param array $a_obj_ids - * @return array - */ - static function getLongDescriptions(array $a_obj_ids) - { - global $DIC; - - $ilDB = $DIC->database(); - - $res = $ilDB->query("SELECT * FROM object_description". - " WHERE ".$ilDB->in("obj_id", $a_obj_ids, "", "integer")); - $all = array(); - while($row = $ilDB->fetchAssoc($res)) - { - $all[$row["obj_id"]] = $row["description"]; - } - return $all; - } - - /** - * Get all ids of objects user owns - * - * @param int $a_user_id - * @return array - */ - static function getAllOwnedRepositoryObjects($a_user_id) - { - global $DIC; - - $ilDB = $DIC->database(); - $objDefinition = $DIC["objDefinition"]; - - $all = array(); - - // restrict to repository - $types = array_keys($objDefinition->getSubObjectsRecursively("root")); - - $sql = "SELECT od.obj_id,od.type,od.title FROM object_data od". - " JOIN object_reference oref ON(oref.obj_id = od.obj_id)". - " JOIN tree ON (tree.child = oref.ref_id)"; - - if($a_user_id) - { - $sql .= " WHERE od.owner = ".$ilDB->quote($a_user_id, "integer"); - } - else - { - $sql .= " LEFT JOIN usr_data ud ON (ud.usr_id = od.owner)". - " WHERE (od.owner < ".$ilDB->quote(1, "integer"). - " OR od.owner IS NULL OR ud.login IS NULL)". - " AND od.owner <> ".$ilDB->quote(-1, "integer"); - } - - $sql .= " AND ".$ilDB->in("od.type", $types, "", "text"). - " AND tree.tree > ".$ilDB->quote(0, "integer"); // #12485 - - $res = $ilDB->query($sql); - while($row = $ilDB->fetchAssoc($res)) - { - $all[$row["type"]][$row["obj_id"]] = $row["title"]; - } - - return $all; - } - - /** - * Try to fix missing object titles - * - * @param type $a_type - * @param array &$a_obj_title_map - */ - static function fixMissingTitles($a_type, array &$a_obj_title_map) - { - global $DIC; - - $ilDB = $DIC->database(); - - if(!in_array($a_type, array("catr", "crsr", "sess", "grpr"))) - { - return; - } - - // any missing titles? - $missing_obj_ids = array(); - foreach($a_obj_title_map as $obj_id => $title) - { - if(!trim($title)) - { - $missing_obj_ids[] = $obj_id; - } - } - - if(!sizeof($missing_obj_ids)) - { - return; - } - - switch($a_type) - { - case "grpr": - case "catr": - case "crsr": - $set = $ilDB->query("SELECT oref.obj_id, od.type, od.title FROM object_data od". - " JOIN container_reference oref ON (od.obj_id = oref.target_obj_id)". - " AND ".$ilDB->in("oref.obj_id", $missing_obj_ids, "", "integer")); - while($row = $ilDB->fetchAssoc($set)) - { - $a_obj_title_map[$row["obj_id"]] = $row["title"]; - } - break; - - case "sess": - include_once "Modules/Session/classes/class.ilObjSession.php"; - foreach($missing_obj_ids as $obj_id) - { - $sess = new ilObjSession($obj_id, false); - $a_obj_title_map[$obj_id] = $sess->getFirstAppointment()->appointmentToString(); - } - break; - } - } - - /** - * Lookup creation date - * - * @param - * @return - */ - static function _lookupCreationDate($a_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT create_date FROM object_data ". - " WHERE obj_id = ".$ilDB->quote($a_id, "integer")); - $rec = $ilDB->fetchAssoc($set); - return $rec["create_date"]; - } - - /** - * Check if auto rating is active for parent group/course - * - * @param string $a_type - * @param int $a_ref_id - * @return bool - */ - public static function hasAutoRating($a_type, $a_ref_id) - { - global $DIC; - - $tree = $DIC->repositoryTree(); - - if(!$a_ref_id || - !in_array($a_type, array("file", "lm", "wiki"))) - { - return false; - } - - // find parent container - $parent_ref_id = $tree->checkForParentType($a_ref_id, "grp"); - if(!$parent_ref_id) - { - $parent_ref_id = $tree->checkForParentType($a_ref_id, "crs"); - } - if($parent_ref_id) - { - include_once './Services/Object/classes/class.ilObjectServiceSettingsGUI.php'; - - // get auto rate setting - $parent_obj_id = ilObject::_lookupObjId($parent_ref_id); - return ilContainer::_lookupContainerSetting( - $parent_obj_id, - ilObjectServiceSettingsGUI::AUTO_RATING_NEW_OBJECTS, - false - ); - } - return false; - } - - /** - * get all possible subobjects of this type - * the object can decide which types of subobjects are possible jut in time - * overwrite if the decision distinguish from standard model - * - * @param boolean filter disabled objects? ($a_filter = true) - * @access public - * @return array list of allowed object types - */ - function getPossibleSubObjects($a_filter = true) { - return $this->objDefinition->getSubObjects($this->type, $a_filter); - } + $ilAppEventHandler->raise('Services/Object', 'cloneObject', array( + 'object' => $new_obj, + 'cloned_from_object' => $this, + )); + + return $new_obj; + } + + /** + * Prepend Copy info if object with same name exists in that container + * + * @access public + * @param int copy_id + * + */ + public function appendCopyInfo($a_target_id, $a_copy_id) + { + $tree = $this->tree; + + include_once('Services/CopyWizard/classes/class.ilCopyWizardOptions.php'); + $cp_options = ilCopyWizardOptions::_getInstance($a_copy_id); + if (!$cp_options->isRootNode($this->getRefId())) { + return $this->getTitle(); + } + $nodes = $tree->getChilds($a_target_id); + + $title_unique = false; + require_once 'Modules/File/classes/class.ilObjFileAccess.php'; + $numberOfCopy = 1; + $handleExtension = ($this->getType() == "file"); // #14883 + $title = ilObjFileAccess::_appendNumberOfCopyToFilename($this->getTitle(), $numberOfCopy, $handleExtension); + while (!$title_unique) { + $found = 0; + foreach ($nodes as $node) { + if (($title == $node['title']) and ($this->getType() == $node['type'])) { + $found++; + } + } + if ($found > 0) { + $title = ilObjFileAccess::_appendNumberOfCopyToFilename($this->getTitle(), ++$numberOfCopy, $handleExtension); + } else { + break; + } + } + return $title; + } + + /** + * Clone object dependencies + * + * This method allows to refresh any ref id references to other objects + * that are affected in the same copy process. Ask ilCopyWizardOptions for + * the mappings. + * + * @access public + * @param int ref_id of target object + * @param int copy_id + * + */ + public function cloneDependencies($a_target_id, $a_copy_id) + { + include_once './Services/Conditions/classes/class.ilConditionHandler.php' ; + ilConditionHandler::cloneDependencies($this->getRefId(), $a_target_id, $a_copy_id); + + include_once './Services/DidacticTemplate/classes/class.ilDidacticTemplateObjSettings.php'; + $tpl_id = ilDidacticTemplateObjSettings::lookupTemplateId($this->getRefId()); + if ($tpl_id) { + include_once './Services/Object/classes/class.ilObjectFactory.php'; + $factory = new ilObjectFactory(); + $obj = $factory->getInstanceByRefId($a_target_id, false); + if ($obj instanceof ilObject) { + $obj->applyDidacticTemplate($tpl_id); + } + } + return true; + } + + /** + * Copy meta data + * + * @access public + * @param object target object + * + */ + public function cloneMetaData($target_obj) + { + $md = new ilMD($this->getId(), 0, $this->getType()); + $md->cloneMD($target_obj->getId(), 0, $target_obj->getType()); + return true; + } + + /** + * Get icon for repository item. + * + * @param int object id + * @param string size (big, small, tiny) + * @param string object type + * @param boolean true: offline, false: online + */ + public static function _getIcon( + $a_obj_id = "", + $a_size = "big", + $a_type = "", + $a_offline = false + ) { + global $DIC; + + $ilSetting = $DIC->settings(); + $objDefinition = $DIC["objDefinition"]; + + if ($a_obj_id == "" && $a_type == "") { + return ""; + } + + if ($a_type == "") { + $a_type = ilObject::_lookupType($a_obj_id); + } + + if ($a_size == "") { + $a_size = "big"; + } + + if ( + $a_obj_id && + $ilSetting->get('custom_icons') + ) { + /** @var \ilObjectCustomIconFactory $customIconFactory */ + $customIconFactory = $DIC['object.customicons.factory']; + $customIcon = $customIconFactory->getPresenterByObjId((int) $a_obj_id, (string) $a_type); + if ($customIcon->exists()) { + $filename = $customIcon->getFullPath(); + return $filename . '?tmp=' . filemtime($filename); + } + } + + if (!$a_offline) { + if ($objDefinition->isPluginTypeName($a_type)) { + if ($objDefinition->getClassName($a_type) != "") { + $class_name = "il" . $objDefinition->getClassName($a_type) . 'Plugin'; + $location = $objDefinition->getLocation($a_type); + if (is_file($location . "/class." . $class_name . ".php")) { + include_once($location . "/class." . $class_name . ".php"); + return call_user_func(array($class_name, "_getIcon"), $a_type, $a_size, $a_obj_id); + } + } + return ilUtil::getImagePath("icon_cmps.svg"); + } + + return ilUtil::getImagePath("icon_" . $a_type . ".svg"); + } else { + return "./images/icon_" . $a_type . ".svg"; + } + } + + /** + * Collect deletion dependencies. E.g. + * + * @param + * @return + */ + public static function collectDeletionDependencies(&$deps, $a_ref_id, $a_obj_id, $a_type, $a_depth = 0) + { + global $DIC; + + $objDefinition = $DIC["objDefinition"]; + $tree = $DIC->repositoryTree(); + + if ($a_depth == 0) { + $deps["dep"] = array(); + } + + $deps["del_ids"][$a_obj_id] = $a_obj_id; + + if (!$objDefinition->isPluginTypeName($a_type)) { + $class_name = "ilObj" . $objDefinition->getClassName($a_type); + $location = $objDefinition->getLocation($a_type); + include_once($location . "/class." . $class_name . ".php"); + $odeps = call_user_func(array($class_name, "getDeletionDependencies"), $a_obj_id); + if (is_array($odeps)) { + foreach ($odeps as $id => $message) { + $deps["dep"][$id][$a_obj_id][] = $message; + } + } + + // get deletion dependency of childs + foreach ($tree->getChilds($a_ref_id) as $c) { + ilObject::collectDeletionDependencies($deps, $c["child"], $c["obj_id"], $c["type"], $a_depth + 1); + } + } + + // delete all dependencies to objects that will be deleted, too + if ($a_depth == 0) { + foreach ($deps["del_ids"] as $obj_id) { + unset($deps["dep"][$obj_id]); + } + $deps = $deps["dep"]; + } + } + + /** + * Get deletion dependencies + * + */ + public static function getDeletionDependencies($a_obj_id) + { + return false; + } + + /** + * Get long description data + * + * @param array $a_obj_ids + * @return array + */ + public static function getLongDescriptions(array $a_obj_ids) + { + global $DIC; + + $ilDB = $DIC->database(); + + $res = $ilDB->query("SELECT * FROM object_description" . + " WHERE " . $ilDB->in("obj_id", $a_obj_ids, "", "integer")); + $all = array(); + while ($row = $ilDB->fetchAssoc($res)) { + $all[$row["obj_id"]] = $row["description"]; + } + return $all; + } + + /** + * Get all ids of objects user owns + * + * @param int $a_user_id + * @return array + */ + public static function getAllOwnedRepositoryObjects($a_user_id) + { + global $DIC; + + $ilDB = $DIC->database(); + $objDefinition = $DIC["objDefinition"]; + + $all = array(); + + // restrict to repository + $types = array_keys($objDefinition->getSubObjectsRecursively("root")); + + $sql = "SELECT od.obj_id,od.type,od.title FROM object_data od" . + " JOIN object_reference oref ON(oref.obj_id = od.obj_id)" . + " JOIN tree ON (tree.child = oref.ref_id)"; + + if ($a_user_id) { + $sql .= " WHERE od.owner = " . $ilDB->quote($a_user_id, "integer"); + } else { + $sql .= " LEFT JOIN usr_data ud ON (ud.usr_id = od.owner)" . + " WHERE (od.owner < " . $ilDB->quote(1, "integer") . + " OR od.owner IS NULL OR ud.login IS NULL)" . + " AND od.owner <> " . $ilDB->quote(-1, "integer"); + } + + $sql .= " AND " . $ilDB->in("od.type", $types, "", "text") . + " AND tree.tree > " . $ilDB->quote(0, "integer"); // #12485 + + $res = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($res)) { + $all[$row["type"]][$row["obj_id"]] = $row["title"]; + } + + return $all; + } + + /** + * Try to fix missing object titles + * + * @param type $a_type + * @param array &$a_obj_title_map + */ + public static function fixMissingTitles($a_type, array &$a_obj_title_map) + { + global $DIC; + + $ilDB = $DIC->database(); + + if (!in_array($a_type, array("catr", "crsr", "sess", "grpr"))) { + return; + } + + // any missing titles? + $missing_obj_ids = array(); + foreach ($a_obj_title_map as $obj_id => $title) { + if (!trim($title)) { + $missing_obj_ids[] = $obj_id; + } + } + + if (!sizeof($missing_obj_ids)) { + return; + } + + switch ($a_type) { + case "grpr": + case "catr": + case "crsr": + $set = $ilDB->query("SELECT oref.obj_id, od.type, od.title FROM object_data od" . + " JOIN container_reference oref ON (od.obj_id = oref.target_obj_id)" . + " AND " . $ilDB->in("oref.obj_id", $missing_obj_ids, "", "integer")); + while ($row = $ilDB->fetchAssoc($set)) { + $a_obj_title_map[$row["obj_id"]] = $row["title"]; + } + break; + + case "sess": + include_once "Modules/Session/classes/class.ilObjSession.php"; + foreach ($missing_obj_ids as $obj_id) { + $sess = new ilObjSession($obj_id, false); + $a_obj_title_map[$obj_id] = $sess->getFirstAppointment()->appointmentToString(); + } + break; + } + } + + /** + * Lookup creation date + * + * @param + * @return + */ + public static function _lookupCreationDate($a_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query("SELECT create_date FROM object_data " . + " WHERE obj_id = " . $ilDB->quote($a_id, "integer")); + $rec = $ilDB->fetchAssoc($set); + return $rec["create_date"]; + } + + /** + * Check if auto rating is active for parent group/course + * + * @param string $a_type + * @param int $a_ref_id + * @return bool + */ + public static function hasAutoRating($a_type, $a_ref_id) + { + global $DIC; + + $tree = $DIC->repositoryTree(); + + if (!$a_ref_id || + !in_array($a_type, array("file", "lm", "wiki"))) { + return false; + } + + // find parent container + $parent_ref_id = $tree->checkForParentType($a_ref_id, "grp"); + if (!$parent_ref_id) { + $parent_ref_id = $tree->checkForParentType($a_ref_id, "crs"); + } + if ($parent_ref_id) { + include_once './Services/Object/classes/class.ilObjectServiceSettingsGUI.php'; + + // get auto rate setting + $parent_obj_id = ilObject::_lookupObjId($parent_ref_id); + return ilContainer::_lookupContainerSetting( + $parent_obj_id, + ilObjectServiceSettingsGUI::AUTO_RATING_NEW_OBJECTS, + false + ); + } + return false; + } + + /** + * get all possible subobjects of this type + * the object can decide which types of subobjects are possible jut in time + * overwrite if the decision distinguish from standard model + * + * @param boolean filter disabled objects? ($a_filter = true) + * @access public + * @return array list of allowed object types + */ + public function getPossibleSubObjects($a_filter = true) + { + return $this->objDefinition->getSubObjects($this->type, $a_filter); + } } // END class.ilObject -?> diff --git a/Services/Object/classes/class.ilObject2.php b/Services/Object/classes/class.ilObject2.php index 8d8e27724f21dc95f7c6571d76075197f3f7c08d..81c0a045f08f354960756410a97a2e569efacd39 100755 --- a/Services/Object/classes/class.ilObject2.php +++ b/Services/Object/classes/class.ilObject2.php @@ -13,267 +13,423 @@ include_once("./Services/Object/classes/class.ilObject.php"); */ abstract class ilObject2 extends ilObject { - /** - * Constructor - * @access public - * @param integer reference_id or object_id - * @param boolean treat the id as reference_id (true) or object_id (false) - */ - function __construct($a_id = 0, $a_reference = true) - { - $this->initType(); - parent::__construct($a_id, $a_reference); - } + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id = 0, $a_reference = true) + { + $this->initType(); + parent::__construct($a_id, $a_reference); + } - abstract protected function initType(); - - final function withReferences() { return parent::withReferences(); } + abstract protected function initType(); + + final public function withReferences() + { + return parent::withReferences(); + } - /** - * Read data from db - */ - final public function read() - { - parent::read(); - $this->doRead(); - } - protected function doRead() - { - - } - - function getId() { return parent::getId(); } - function setId($a_id) { return parent::setId($a_id); } - final function setRefId($a_id) { return parent::setRefId($a_id); } - final function getRefId() { return parent::getRefId(); } - final function getType() { return parent::getType(); } - final function setType($a_type) { return parent::setType($a_type); } - final function getPresentationTitle() { return parent::getPresentationTitle(); } - final function getTitle() { return parent::getTitle(); } - final function getUntranslatedTitle() { return parent::getUntranslatedTitle(); } - final function setTitle($a_title) { return parent::setTitle($a_title); } - final function getDescription() { return parent::getDescription(); } - final function setDescription($a_desc) { return parent::setDescription($a_desc); } - final function getLongDescription() { return parent::getLongDescription(); } - final function getImportId() { return parent::getImportId(); } - final function setImportId($a_import_id) { return parent::setImportId($a_import_id); } - final static function _lookupObjIdByImportId($a_import_id) { return parent::_lookupObjIdByImportId($a_import_id); } - final function getOwner() { return parent::getOwner(); } - final function getOwnerName() { return parent::getOwnerName(); } - final static function _lookupOwnerName($a_owner_id) { return parent::_lookupOwnerName($a_owner_id); } - final function setOwner($a_owner) { return parent::setOwner($a_owner); } - final function getCreateDate() { return parent::getCreateDate(); } - final function getLastUpdateDate() { return parent::getLastUpdateDate(); } + /** + * Read data from db + */ + final public function read() + { + parent::read(); + $this->doRead(); + } + protected function doRead() + { + } + + public function getId() + { + return parent::getId(); + } + public function setId($a_id) + { + return parent::setId($a_id); + } + final public function setRefId($a_id) + { + return parent::setRefId($a_id); + } + final public function getRefId() + { + return parent::getRefId(); + } + final public function getType() + { + return parent::getType(); + } + final public function setType($a_type) + { + return parent::setType($a_type); + } + final public function getPresentationTitle() + { + return parent::getPresentationTitle(); + } + final public function getTitle() + { + return parent::getTitle(); + } + final public function getUntranslatedTitle() + { + return parent::getUntranslatedTitle(); + } + final public function setTitle($a_title) + { + return parent::setTitle($a_title); + } + final public function getDescription() + { + return parent::getDescription(); + } + final public function setDescription($a_desc) + { + return parent::setDescription($a_desc); + } + final public function getLongDescription() + { + return parent::getLongDescription(); + } + final public function getImportId() + { + return parent::getImportId(); + } + final public function setImportId($a_import_id) + { + return parent::setImportId($a_import_id); + } + final public static function _lookupObjIdByImportId($a_import_id) + { + return parent::_lookupObjIdByImportId($a_import_id); + } + final public function getOwner() + { + return parent::getOwner(); + } + final public function getOwnerName() + { + return parent::getOwnerName(); + } + final public static function _lookupOwnerName($a_owner_id) + { + return parent::_lookupOwnerName($a_owner_id); + } + final public function setOwner($a_owner) + { + return parent::setOwner($a_owner); + } + final public function getCreateDate() + { + return parent::getCreateDate(); + } + final public function getLastUpdateDate() + { + return parent::getLastUpdateDate(); + } - final function create($a_clone_mode = false) - { - if($this->beforeCreate()) - { - $id = parent::create(); - if($id) - { - $this->doCreate($a_clone_mode); - return $id; - } - } - } + final public function create($a_clone_mode = false) + { + if ($this->beforeCreate()) { + $id = parent::create(); + if ($id) { + $this->doCreate($a_clone_mode); + return $id; + } + } + } - protected function doCreate() - { - - } - - protected function beforeCreate() - { - return true; - } - - final function update() - { - if($this->beforeUpdate()) - { - if (!parent::update()) - { - return false; - } - $this->doUpdate(); - - return true; - } - - return false; - } + protected function doCreate() + { + } + + protected function beforeCreate() + { + return true; + } + + final public function update() + { + if ($this->beforeUpdate()) { + if (!parent::update()) { + return false; + } + $this->doUpdate(); + + return true; + } + + return false; + } - protected function doUpdate() - { - - } - - protected function beforeUpdate() - { - return true; - } + protected function doUpdate() + { + } + + protected function beforeUpdate() + { + return true; + } - final function MDUpdateListener($a_element) - { - if($this->beforeMDUpdateListener($a_element)) - { - if(parent::MDUpdateListener($a_element)) - { - $this->doMDUpdateListener($a_element); - return true; - } - } - return false; - } + final public function MDUpdateListener($a_element) + { + if ($this->beforeMDUpdateListener($a_element)) { + if (parent::MDUpdateListener($a_element)) { + $this->doMDUpdateListener($a_element); + return true; + } + } + return false; + } - protected function doMDUpdateListener($a_element) - { - - } + protected function doMDUpdateListener($a_element) + { + } - protected function beforeMDUpdateListener($a_element) - { - return true; - } + protected function beforeMDUpdateListener($a_element) + { + return true; + } - final function createMetaData() - { - if($this->beforeCreateMetaData()) - { - if(parent::createMetaData()) - { - $this->doCreateMetaData(); - return true; - } - } - return false; - } + final public function createMetaData() + { + if ($this->beforeCreateMetaData()) { + if (parent::createMetaData()) { + $this->doCreateMetaData(); + return true; + } + } + return false; + } - protected function doCreateMetaData() - { - - } + protected function doCreateMetaData() + { + } - protected function beforeCreateMetaData() - { - return true; - } + protected function beforeCreateMetaData() + { + return true; + } - final function updateMetaData() - { - if($this->beforeUpdateMetaData()) - { - if(parent::updateMetaData()) - { - $this->doUpdateMetaData(); - return true; - } - } - return false; - } + final public function updateMetaData() + { + if ($this->beforeUpdateMetaData()) { + if (parent::updateMetaData()) { + $this->doUpdateMetaData(); + return true; + } + } + return false; + } - protected function doUpdateMetaData() - { - - } + protected function doUpdateMetaData() + { + } - protected function beforeUpdateMetaData() - { - return true; - } - - final function deleteMetaData() { return parent::deleteMetaData(); } - final function updateOwner() { return parent::updateOwner(); } - final static function _getIdForImportId($a_import_id) { return parent::_getIdForImportId($a_import_id); } - static final function _getAllReferences($a_id) { return parent::_getAllReferences($a_id); } - final static function _lookupTitle($a_id) { return parent::_lookupTitle($a_id); } - final static function _lookupOwner($a_id) { return parent::_lookupOwner($a_id); } - final static function _getIdsForTitle($title, $type = '', $partialmatch = false) { return parent::_getIdsForTitle($title, $type, $partialmatch); } - final static function _lookupDescription($a_id) { return parent::_lookupDescription($a_id); } - final static function _lookupLastUpdate($a_id, $a_as_string = false) { return parent::_lookupLastUpdate($a_id, $a_as_string); } - final static function _getLastUpdateOfObjects($a_objs) { return parent::_getLastUpdateOfObjects($a_objs); } - final static function _lookupObjId($a_id) { return parent::_lookupObjId($a_id); } - final static function _setDeletedDate($a_ref_id) { return parent::_setDeletedDate($a_ref_id); } - final public static function _resetDeletedDate($a_ref_id) { return parent::_resetDeletedDate($a_ref_id); } - final static function _lookupDeletedDate($a_ref_id) { return parent::_lookupDeletedDate($a_ref_id); } - final static function _writeTitle($a_obj_id, $a_title) { return parent::_writeTitle($a_obj_id, $a_title); } - final static function _writeDescription($a_obj_id, $a_desc) { return parent::_writeDescription($a_obj_id, $a_desc); } - final static function _writeImportId($a_obj_id, $a_import_id) { return parent::_writeImportId($a_obj_id, $a_import_id); } - final static function _lookupType($a_id,$a_reference = false) { return parent::_lookupType($a_id,$a_reference); } - final public static function _isInTrash($a_ref_id) { return parent::_isInTrash($a_ref_id); } - final static function _hasUntrashedReference($a_obj_id) { return parent::_hasUntrashedReference($a_obj_id); } - final static function _lookupObjectId($a_ref_id) { return parent::_lookupObjectId($a_ref_id); } - final static function _getObjectsDataForType($a_type, $a_omit_trash = false) { return parent::_getObjectsDataForType($a_type, $a_omit_trash); } - final function putInTree($a_parent_ref) { return parent::putInTree($a_parent_ref); } - final function setPermissions($a_parent_ref) { return parent::setPermissions($a_parent_ref); } - final function createReference() { return parent::createReference(); } - final function countReferences() { return parent::countReferences(); } + protected function beforeUpdateMetaData() + { + return true; + } + + final public function deleteMetaData() + { + return parent::deleteMetaData(); + } + final public function updateOwner() + { + return parent::updateOwner(); + } + final public static function _getIdForImportId($a_import_id) + { + return parent::_getIdForImportId($a_import_id); + } + final public static function _getAllReferences($a_id) + { + return parent::_getAllReferences($a_id); + } + final public static function _lookupTitle($a_id) + { + return parent::_lookupTitle($a_id); + } + final public static function _lookupOwner($a_id) + { + return parent::_lookupOwner($a_id); + } + final public static function _getIdsForTitle($title, $type = '', $partialmatch = false) + { + return parent::_getIdsForTitle($title, $type, $partialmatch); + } + final public static function _lookupDescription($a_id) + { + return parent::_lookupDescription($a_id); + } + final public static function _lookupLastUpdate($a_id, $a_as_string = false) + { + return parent::_lookupLastUpdate($a_id, $a_as_string); + } + final public static function _getLastUpdateOfObjects($a_objs) + { + return parent::_getLastUpdateOfObjects($a_objs); + } + final public static function _lookupObjId($a_id) + { + return parent::_lookupObjId($a_id); + } + final public static function _setDeletedDate($a_ref_id) + { + return parent::_setDeletedDate($a_ref_id); + } + final public static function _resetDeletedDate($a_ref_id) + { + return parent::_resetDeletedDate($a_ref_id); + } + final public static function _lookupDeletedDate($a_ref_id) + { + return parent::_lookupDeletedDate($a_ref_id); + } + final public static function _writeTitle($a_obj_id, $a_title) + { + return parent::_writeTitle($a_obj_id, $a_title); + } + final public static function _writeDescription($a_obj_id, $a_desc) + { + return parent::_writeDescription($a_obj_id, $a_desc); + } + final public static function _writeImportId($a_obj_id, $a_import_id) + { + return parent::_writeImportId($a_obj_id, $a_import_id); + } + final public static function _lookupType($a_id, $a_reference = false) + { + return parent::_lookupType($a_id, $a_reference); + } + final public static function _isInTrash($a_ref_id) + { + return parent::_isInTrash($a_ref_id); + } + final public static function _hasUntrashedReference($a_obj_id) + { + return parent::_hasUntrashedReference($a_obj_id); + } + final public static function _lookupObjectId($a_ref_id) + { + return parent::_lookupObjectId($a_ref_id); + } + final public static function _getObjectsDataForType($a_type, $a_omit_trash = false) + { + return parent::_getObjectsDataForType($a_type, $a_omit_trash); + } + final public function putInTree($a_parent_ref) + { + return parent::putInTree($a_parent_ref); + } + final public function setPermissions($a_parent_ref) + { + return parent::setPermissions($a_parent_ref); + } + final public function createReference() + { + return parent::createReference(); + } + final public function countReferences() + { + return parent::countReferences(); + } - final function delete() - { - if($this->beforeDelete()) - { - if(parent::delete()) - { - $this->doDelete(); - $this->id = null; - return true; - } - } - return false; - } + final public function delete() + { + if ($this->beforeDelete()) { + if (parent::delete()) { + $this->doDelete(); + $this->id = null; + return true; + } + } + return false; + } - protected function doDelete() - { + protected function doDelete() + { + } + + protected function beforeDelete() + { + return true; + } - } - - protected function beforeDelete() - { - return true; - } - - function initDefaultRoles() { return array(); } - - final public static function _exists($a_id, $a_reference = false, $a_type = null) { return parent::_exists($a_id, $a_reference, $a_type); } - final function setRegisterMode($a_bool) { return parent::setRegisterMode($a_bool); } - final function isUserRegistered($a_user_id = 0) { return parent::isUserRegistered($a_user_id); } - final function requireRegistration() { return parent::requireRegistration(); } - //final function getXMLZip() { return parent::getXMLZip(); } - //final function getHTMLDirectory() { return parent::getHTMLDirectory(); } - final static function _getObjectsByType($a_obj_type = "", $a_owner = "") { return parent::_getObjectsByType($a_obj_type, $a_owner); } - - final static function _prepareCloneSelection($a_ref_ids,$new_type, $a_show_path = true) { return parent::_prepareCloneSelection($a_ref_ids,$new_type, $a_show_path); } - final function appendCopyInfo($a_target_id,$a_copy_id) { return parent::appendCopyInfo($a_target_id,$a_copy_id); } - final function cloneMetaData($target_obj) { return parent::cloneMetaData($target_obj); } - - final function cloneObject($a_target_id, $a_copy_id = null, $a_omit_tree = false) - { - if($this->beforeCloneObject()) - { - $new_obj = parent::cloneObject($a_target_id, $a_copy_id, $a_omit_tree); - if($new_obj) - { - $this->doCloneObject($new_obj, $a_target_id, $a_copy_id); - return $new_obj; - } - } - } - - protected function doCloneObject($new_obj, $a_target_id, $a_copy_id = null) - { - - } - - protected function beforeCloneObject() - { - return true; - } - - function cloneDependencies($a_target_id,$a_copy_id) { return parent::cloneDependencies($a_target_id,$a_copy_id); } - - final public static function _getIcon($a_obj_id = "", $a_size = "big", $a_type = "", $a_offline = false) { return parent::_getIcon($a_obj_id, $a_size, $a_type, $a_offline); } + public function initDefaultRoles() + { + return array(); + } + + final public static function _exists($a_id, $a_reference = false, $a_type = null) + { + return parent::_exists($a_id, $a_reference, $a_type); + } + final public function setRegisterMode($a_bool) + { + return parent::setRegisterMode($a_bool); + } + final public function isUserRegistered($a_user_id = 0) + { + return parent::isUserRegistered($a_user_id); + } + final public function requireRegistration() + { + return parent::requireRegistration(); + } + //final function getXMLZip() { return parent::getXMLZip(); } + //final function getHTMLDirectory() { return parent::getHTMLDirectory(); } + final public static function _getObjectsByType($a_obj_type = "", $a_owner = "") + { + return parent::_getObjectsByType($a_obj_type, $a_owner); + } + + final public static function _prepareCloneSelection($a_ref_ids, $new_type, $a_show_path = true) + { + return parent::_prepareCloneSelection($a_ref_ids, $new_type, $a_show_path); + } + final public function appendCopyInfo($a_target_id, $a_copy_id) + { + return parent::appendCopyInfo($a_target_id, $a_copy_id); + } + final public function cloneMetaData($target_obj) + { + return parent::cloneMetaData($target_obj); + } + + final public function cloneObject($a_target_id, $a_copy_id = null, $a_omit_tree = false) + { + if ($this->beforeCloneObject()) { + $new_obj = parent::cloneObject($a_target_id, $a_copy_id, $a_omit_tree); + if ($new_obj) { + $this->doCloneObject($new_obj, $a_target_id, $a_copy_id); + return $new_obj; + } + } + } + + protected function doCloneObject($new_obj, $a_target_id, $a_copy_id = null) + { + } + + protected function beforeCloneObject() + { + return true; + } + public function cloneDependencies($a_target_id, $a_copy_id) + { + return parent::cloneDependencies($a_target_id, $a_copy_id); + } + + final public static function _getIcon($a_obj_id = "", $a_size = "big", $a_type = "", $a_offline = false) + { + return parent::_getIcon($a_obj_id, $a_size, $a_type, $a_offline); + } } -?> diff --git a/Services/Object/classes/class.ilObject2GUI.php b/Services/Object/classes/class.ilObject2GUI.php index 3d5f5449334158085aa65ef57c19286d0d090e0e..929b9a4f5ec7b5419b3be4fefa7b44bb4597dcd0 100644 --- a/Services/Object/classes/class.ilObject2GUI.php +++ b/Services/Object/classes/class.ilObject2GUI.php @@ -26,864 +26,951 @@ include_once("./Services/Object/classes/class.ilObjectGUI.php"); */ abstract class ilObject2GUI extends ilObjectGUI { - protected $object_id; - protected $node_id; - protected $creation_forms = array(); - protected $id_type = array(); - protected $parent_id; - public $tree; - protected $access_handler; - - const OBJECT_ID = 0; - const REPOSITORY_NODE_ID = 1; - const WORKSPACE_NODE_ID = 2; - const REPOSITORY_OBJECT_ID = 3; - const WORKSPACE_OBJECT_ID = 4; - const PORTFOLIO_OBJECT_ID = 5; - - /** - * Constructor - * - * @param int $a_id - * @param int $a_id_type - * @param int $a_parent_node_id - */ - function __construct($a_id = 0, $a_id_type = self::REPOSITORY_NODE_ID, $a_parent_node_id = 0) - { - global $DIC; - - $objDefinition = $DIC["objDefinition"]; - $tpl = $DIC["tpl"]; - $ilCtrl = $DIC["ilCtrl"]; - $ilErr = $DIC["ilErr"]; - $lng = $DIC["lng"]; - $ilTabs = $DIC["ilTabs"]; - $tree = $DIC["tree"]; - $ilAccess = $DIC["ilAccess"]; - $this->object_service = $DIC->object(); - - if (!isset($ilErr)) - { - $ilErr = new ilErrorHandling(); - $ilErr->setErrorHandling(PEAR_ERROR_CALLBACK,array($ilErr,'errorHandler')); - } - else - { - $this->ilErr = $ilErr; - } - - $this->id_type = $a_id_type; - $this->parent_id = $a_parent_node_id; - $this->type = $this->getType(); - $this->html = ""; - - $this->tabs_gui = $ilTabs; - $this->objDefinition = $objDefinition; - $this->tpl = $tpl; - $this->ctrl = $ilCtrl; - $this->lng = $lng; - - // these are things that are initialised in ilObjectGUI constructor now - // and may miss here - $this->locator = $DIC["ilLocator"]; - $this->user = $DIC->user(); - $this->access = $DIC->access(); - //$this->settings = $DIC->settings(); - //$this->rbacreview = $DIC->rbac()->review(); - $this->toolbar = $DIC->toolbar(); - - - $params = array(); - switch($this->id_type) - { - case self::REPOSITORY_NODE_ID: - $this->node_id = $a_id; - $this->object_id = ilObject::_lookupObjectId($this->node_id); - $this->tree = $tree; - $this->access_handler = $ilAccess; - $this->call_by_reference = true; // needed for prepareOutput() - $params[] = "ref_id"; - break; - - case self::REPOSITORY_OBJECT_ID: - $this->object_id = $a_id; - $this->tree = $tree; - $this->access_handler = $ilAccess; - $params[] = "obj_id"; // ??? - break; - - case self::WORKSPACE_NODE_ID: - $ilUser = $DIC["ilUser"]; - $this->node_id = $a_id; - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - $this->tree = new ilWorkspaceTree($ilUser->getId()); - $this->object_id = $this->tree->lookupObjectId($this->node_id); - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; - $this->access_handler = new ilWorkspaceAccessHandler($this->tree); - $params[] = "wsp_id"; - break; - - case self::WORKSPACE_OBJECT_ID: - $ilUser = $DIC["ilUser"]; - $this->object_id = $a_id; - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - $this->tree = new ilWorkspaceTree($ilUser->getId()); - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; - $this->access_handler = new ilWorkspaceAccessHandler($this->tree); - $params[] = "obj_id"; // ??? - break; - - case self::PORTFOLIO_OBJECT_ID: - $this->object_id = $a_id; - include_once('./Modules/Portfolio/classes/class.ilPortfolioAccessHandler.php'); - $this->access_handler = new ilPortfolioAccessHandler(); - $params[] = "prt_id"; - break; - - case self::OBJECT_ID: - $this->object_id = $a_id; - include_once "Services/Object/classes/class.ilDummyAccessHandler.php"; - $this->access_handler = new ilDummyAccessHandler(); - $params[] = "obj_id"; - break; - } - $this->ctrl->saveParameter($this, $params); - - - - // old stuff for legacy code (obsolete?) - if(!$this->object_id) - { - $this->creation_mode = true; - } - if($this->node_id) - { - // add parent node id if missing - if(!$this->parent_id && $this->tree) - { - $this->parent_id = $this->tree->getParentId($this->node_id); - } - } - $this->ref_id = $this->node_id; - $this->obj_id = $this->object_id; - - - - $this->assignObject(); - - // set context - if (is_object($this->object)) - { - $this->ctrl->setContext($this->object->getId(), $this->object->getType()); - } - - $this->afterConstructor(); - } - - /** - * Do anything that should be done after constructor in here. - */ - protected function afterConstructor() - { - } - - /** - * execute command - */ - function executeCommand() - { - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - $this->prepareOutput(); - - switch($next_class) - { - case "ilworkspaceaccessgui"; - if($this->node_id) - { - $this->tabs_gui->activateTab("id_permissions"); - - include_once('./Services/PersonalWorkspace/classes/class.ilWorkspaceAccessGUI.php'); - $wspacc = new ilWorkspaceAccessGUI($this->node_id, $this->getAccessHandler()); - $this->ctrl->forwardCommand($wspacc); - break; - } - - default: - if(!$cmd) - { - $cmd = "render"; - } - return $this->$cmd(); - } - - return true; - } - - /** - * create object instance as internal property (repository/workspace switch) - */ - final protected function assignObject() - { - if ($this->object_id != 0) - { - switch($this->id_type) - { - case self::OBJECT_ID: - case self::REPOSITORY_OBJECT_ID: - case self::WORKSPACE_OBJECT_ID: - case self::PORTFOLIO_OBJECT_ID: - $this->object = ilObjectFactory::getInstanceByObjId($this->object_id); - break; - - case self::REPOSITORY_NODE_ID: - $this->object = ilObjectFactory::getInstanceByRefId($this->node_id); - break; - - case self::WORKSPACE_NODE_ID: - // to be discussed - $this->object = ilObjectFactory::getInstanceByObjId($this->object_id); - break; - } - } - } - - /** - * Get access handler - * - * @return object - */ - protected function getAccessHandler() - { - return $this->access_handler; - } - - /** - * set Locator - */ - protected function setLocator() - { - global $DIC; - - $ilLocator = $DIC["ilLocator"]; - $tpl = $DIC["tpl"]; - - if ($this->omit_locator) - { - return; - } - - switch($this->id_type) - { - case self::REPOSITORY_NODE_ID: - $ref_id = $this->node_id - ? $this->node_id - : $this->parent_id; - $ilLocator->addRepositoryItems($ref_id); - - // not so nice workaround: todo: handle $ilLocator as tabs in ilTemplate - if ($_GET["admin_mode"] == "" && - strtolower($this->ctrl->getCmdClass()) == "ilobjrolegui") - { - $this->ctrl->setParameterByClass("ilobjrolegui", - "rolf_ref_id", $_GET["rolf_ref_id"]); - $this->ctrl->setParameterByClass("ilobjrolegui", - "obj_id", $_GET["obj_id"]); - $ilLocator->addItem($this->lng->txt("role"), - $this->ctrl->getLinkTargetByClass(array("ilpermissiongui", - "ilobjrolegui"), "perm")); - } - - // in workspace this is done in ilPersonalWorkspaceGUI - if($this->object_id) - { - $this->addLocatorItems(); - } - $tpl->setLocator(); - - break; - - case self::WORKSPACE_NODE_ID: - // :TODO: - break; - } - - - } - - /** - * Display delete confirmation form (repository/workspace switch) - */ - public function delete() - { - switch($this->id_type) - { - case self::REPOSITORY_NODE_ID: - case self::REPOSITORY_OBJECT_ID: - return parent::deleteObject(); - - case self::WORKSPACE_NODE_ID: - case self::WORKSPACE_OBJECT_ID: - return $this->deleteConfirmation(); - - case self::OBJECT_ID: - case self::PORTFOLIO_OBJECT_ID: - // :TODO: should this ever occur? - break; - } - } - - /** - * Display delete confirmation form (workspace specific) - * - * This should probably be moved elsewhere as done with RepUtil - */ - protected function deleteConfirmation() - { - global $DIC; - - $tpl = $DIC["tpl"]; - $lng = $DIC["lng"]; - - $node_id = (int)$_REQUEST["item_ref_id"]; - if (!$node_id) - { - ilUtil::sendFailure($lng->txt("no_checkbox"), true); - $this->ctrl->redirect($this, ""); - } - - // on cancel or fail we return to parent node - $parent_node = $this->tree->getParentId($node_id); - $this->ctrl->setParameter($this, "wsp_id", $parent_node); - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setHeaderText($lng->txt("info_delete_sure")."
                  ". - $lng->txt("info_delete_warning_no_trash")); - - $cgui->setFormAction($this->ctrl->getFormAction($this)); - $cgui->setCancel($lng->txt("cancel"), "cancelDelete"); - $cgui->setConfirm($lng->txt("confirm"), "confirmedDelete"); - - $a_ids = array($node_id); - foreach ($a_ids as $node_id) - { - $children = $this->tree->getSubTree($this->tree->getNodeData($node_id)); - foreach($children as $child) - { - $node_id = $child["wsp_id"]; - $obj_id = $this->tree->lookupObjectId($node_id); - $type = ilObject::_lookupType($obj_id); - $title = call_user_func(array(ilObjectFactory::getClassByType($type),'_lookupTitle'), $obj_id); - - // if anything fails, abort the whole process - if(!$this->checkPermissionBool("delete", "", "", $node_id)) - { - ilUtil::sendFailure($lng->txt("msg_no_perm_delete")." ".$title, true); - $this->ctrl->redirect($this); - } - - $cgui->addItem("id[]", $node_id, $title, - ilObject::_getIcon($obj_id, "small", $type), - $lng->txt("icon")." ".$lng->txt("obj_".$type)); - } - } - - $tpl->setContent($cgui->getHTML()); - } - - /** - * Delete objects (repository/workspace switch) - */ - public function confirmedDelete() - { - switch($this->id_type) - { - case self::REPOSITORY_NODE_ID: - case self::REPOSITORY_OBJECT_ID: - return parent::confirmedDeleteObject(); - - case self::WORKSPACE_NODE_ID: - case self::WORKSPACE_OBJECT_ID: - return $this->deleteConfirmedObjects(); - - case self::OBJECT_ID: - case self::PORTFOLIO_OBJECT_ID: - // :TODO: should this ever occur? - break; - } - } - - /** - * Delete objects (workspace specific) - * - * This should probably be moved elsewhere as done with RepUtil - */ - protected function deleteConfirmedObjects() - { - global $DIC; - - $lng = $DIC["lng"]; - - - if(sizeof($_POST["id"])) - { - // #18797 - because of parent/child relations gather all nodes first - $del_nodes = array(); - foreach($_POST["id"] as $node_id) - { - $del_nodes[$node_id] = $this->tree->getNodeData($node_id); - } - - foreach($del_nodes as $node_id => $node) - { - // tree/reference - $this->tree->deleteReference($node_id); - if($this->tree->isInTree($node_id)) - { - $this->tree->deleteTree($node); - } - - // permission - $this->getAccessHandler()->removePermission($node_id); - - // object - $object = ilObjectFactory::getInstanceByObjId($node["obj_id"], false); - if($object) - { - $object->delete(); - } - } - - ilUtil::sendSuccess($lng->txt("msg_removed"), true); - } - else - { - ilUtil::sendFailure($lng->txt("no_checkbox"), true); - } - - $this->ctrl->redirect($this, ""); - } - - public function getHTML() { return parent::getHTML(); } - - /** - * Final/Private declaration of unchanged parent methods - */ - final public function withReferences() { return parent::withReferences(); } - final public function setCreationMode($a_mode = true) { return parent::setCreationMode($a_mode); } - final public function getCreationMode() { return parent::getCreationMode(); } - final public function prepareOutput($a_show_subobjects = true) { return parent::prepareOutput($a_show_subobjects); } - protected function setTitleAndDescription() { return parent::setTitleAndDescription(); } - final protected function showUpperIcon() { return parent::showUpperIcon(); } -// final private function showMountWebfolderIcon() { return parent::showMountWebfolderIcon(); } - final protected function omitLocator($a_omit = true) { return parent::omitLocator($a_omit); } - final protected function getTargetFrame($a_cmd, $a_target_frame = "") { return parent::getTargetFrame($a_cmd, $a_target_frame); } - final protected function setTargetFrame($a_cmd, $a_target_frame) { return parent::setTargetFrame($a_cmd, $a_target_frame); } - final public function isVisible($a_ref_id,$a_type) { return parent::isVisible($a_ref_id,$a_type); } - final protected function getCenterColumnHTML() { return parent::getCenterColumnHTML(); } - final protected function getRightColumnHTML() { return parent::getRightColumnHTML(); } - final protected function setColumnSettings(ilColumnGUI $column_gui) { return parent::setColumnSettings($column_gui); } - final protected function checkPermission($a_perm, $a_cmd = "", $a_type = "", $a_ref_id = null) { return parent::checkPermission($a_perm, $a_cmd, $a_type, $a_ref_id); } - - // -> ilContainerGUI - final protected function showPossibleSubObjects() { return parent::showPossibleSubObjects(); } - // -> ilRepUtilGUI - final public function trash() { return parent::trashObject(); } // done - // -> ilRepUtil - final public function undelete() { return parent::undeleteObject(); } // done - final public function cancelDelete() { return parent::cancelDeleteObject(); } // ok - final public function removeFromSystem() { return parent::removeFromSystemObject(); } // done - final protected function redirectToRefId($a_ref_id, $a_cmd = "") { return parent::redirectToRefId(); } // ok - - // -> stefan - final protected function fillCloneTemplate($a_tpl_varname,$a_type) { return parent::fillCloneTemplate($a_tpl_varname,$a_type); } - final protected function fillCloneSearchTemplate($a_tpl_varname,$a_type) { return parent::fillCloneSearchTemplate($a_tpl_varname,$a_type); } - final protected function searchCloneSource() { return parent::searchCloneSourceObject(); } - final public function cloneAll() { return parent::cloneAllObject(); } - final protected function buildCloneSelect($existing_objs) { return parent::buildCloneSelect($existing_objs); } - - // -> ilAdministration - final private function displayList() { return parent::displayList(); } -// final private function setAdminTabs() { return parent::setAdminTabs(); } -// final public function getAdminTabs() { return parent::getAdminTabs(); } - final protected function addAdminLocatorItems($a_do_not_add_object = false) { return parent::addAdminLocatorItems($a_do_not_add_object); } - - /** - * view object content (repository/workspace switch) - */ - public function view() - { - switch($this->id_type) - { - case self::REPOSITORY_NODE_ID: - case self::REPOSITORY_OBJECT_ID: - return parent::viewObject(); - - case self::WORKSPACE_NODE_ID: - case self::WORKSPACE_OBJECT_ID: - return $this->render(); - - case self::OBJECT_ID: - case self::PORTFOLIO_OBJECT_ID: - // :TODO: should this ever occur? do nothing or edit() ?! - break; - } - } - - /** - * create tabs (repository/workspace switch) - * - * this had to be moved here because of the context-specific permission tab - */ - protected function setTabs() - { - global $DIC; - - $ilTabs = $DIC["ilTabs"]; - $lng = $DIC["lng"]; - - - switch($this->id_type) - { - case self::REPOSITORY_NODE_ID: - case self::REPOSITORY_OBJECT_ID: - if ($this->checkPermissionBool("edit_permission")) - { - $ilTabs->addTab("id_permissions", - $lng->txt("perm_settings"), - $this->ctrl->getLinkTargetByClass(array(get_class($this), "ilpermissiongui"), "perm")); - } - break; - - case self::WORKSPACE_NODE_ID: - case self::WORKSPACE_OBJECT_ID: - // only files and blogs can be shared for now - if ($this->checkPermissionBool("edit_permission") && in_array($this->type, array("file", "blog")) && $this->node_id) - { - $ilTabs->addTab("id_permissions", - $lng->txt("wsp_permissions"), - $this->ctrl->getLinkTargetByClass(array(get_class($this), "ilworkspaceaccessgui"), "share")); - } - break; - } - } - - /** - * Deprecated functions - */ -// final private function setSubObjects($a_sub_objects = "") { die("ilObject2GUI::setSubObjects() is deprecated."); } -// final public function getFormAction($a_cmd, $a_formaction = "") { die("ilObject2GUI::getFormAction() is deprecated."); } -// final protected function setFormAction($a_cmd, $a_formaction) { die("ilObject2GUI::setFormAction() is deprecated."); } - final protected function getReturnLocation($a_cmd, $a_location ="") { die("ilObject2GUI::getReturnLocation() is deprecated."); } - final protected function setReturnLocation($a_cmd, $a_location) { die("ilObject2GUI::setReturnLocation() is deprecated."); } - final protected function showActions() { die("ilObject2GUI::showActions() is deprecated."); } - final protected function getTabs() {nj(); die("ilObject2GUI::getTabs() is deprecated."); } - final protected function __showButton($a_cmd,$a_text,$a_target = '') { die("ilObject2GUI::__showButton() is deprecated."); } - final protected function hitsperpageObject() { die("ilObject2GUI::hitsperpageObject() is deprecated."); } - final protected function &__initTableGUI() { die("ilObject2GUI::__initTableGUI() is deprecated."); } - final protected function __setTableGUIBasicData(&$tbl,&$result_set,$a_from = "") { die("ilObject2GUI::__setTableGUIBasicData() is deprecated."); } - - /** - * Functions to be overwritten - */ - protected function addLocatorItems() {} - - /** - * Functions that must be overwritten - */ - abstract function getType(); - - /** - * Deleted in ilObject - */ -// final private function permObject() { parent::permObject(); } -// final private function permSaveObject() { parent::permSaveObject(); } -// final private function infoObject() { parent::infoObject(); } -// final private function __buildRoleFilterSelect() { parent::__buildRoleFilterSelect(); } -// final private function __filterRoles() { parent::__filterRoles(); } -// final private function ownerObject() { parent::ownerObject(); } -// final private function changeOwnerObject() { parent::changeOwnerObject(); } -// final private function addRoleObject() { parent::addRoleObject(); } -// final private function setActions($a_actions = "") { die("ilObject2GUI::setActions() is deprecated."); } -// final protected function getActions() { die("ilObject2GUI::getActions() is deprecated."); } - - /** - * CRUD - */ - public function create() { parent::createObject(); } - public function save() { parent::saveObject(); } - public function edit() { parent::editObject(); } - public function update() { parent::updateObject(); } - public function cancel() { parent::cancelObject(); } - - /** - * Init creation froms - * - * this will create the default creation forms: new, import, clone - * - * @param string $a_new_type - * @return array - */ - protected function initCreationForms($a_new_type) - { - $forms = parent::initCreationForms($a_new_type); - - // cloning doesn't work in workspace yet - if($this->id_type == self::WORKSPACE_NODE_ID) - { - unset($forms[self::CFORM_CLONE]); - } - - return $forms; - } - - /** - * Import - * - * @access public - */ - function importFile() - { - parent::importFileObject($this->parent_id); - } - - /** - * Add object to tree at given position - * - * @param ilObject $a_obj - * @param int $a_parent_node_id - */ - public function putObjectInTree(ilObject $a_obj, $a_parent_node_id = null) - { - global $DIC; - - $rbacreview = $DIC["rbacreview"]; - $ilUser = $DIC["ilUser"]; - - - $this->object_id = $a_obj->getId(); - - if(!$a_parent_node_id) - { - $a_parent_node_id = $this->parent_id; - } - - // add new object to custom parent container - if((int)$_REQUEST["crtptrefid"]) - { - $a_parent_node_id = (int)$_REQUEST["crtptrefid"]; - } - - switch($this->id_type) - { - case self::REPOSITORY_NODE_ID: - case self::REPOSITORY_OBJECT_ID: - if(!$this->node_id) - { - $a_obj->createReference(); - $this->node_id = $a_obj->getRefId(); - } - $a_obj->putInTree($a_parent_node_id); - $a_obj->setPermissions($a_parent_node_id); - - // rbac log - include_once "Services/AccessControl/classes/class.ilRbacLog.php"; - $rbac_log_roles = $rbacreview->getParentRoleIds($this->node_id, false); - $rbac_log = ilRbacLog::gatherFaPa($this->node_id, array_keys($rbac_log_roles), true); - ilRbacLog::add(ilRbacLog::CREATE_OBJECT, $this->node_id, $rbac_log); - - $this->ctrl->setParameter($this, "ref_id", $this->node_id); - break; - - case self::WORKSPACE_NODE_ID: - case self::WORKSPACE_OBJECT_ID: - if(!$this->node_id) - { - $this->node_id = $this->tree->insertObject($a_parent_node_id, $this->object_id); - } - $this->getAccessHandler()->setPermissions($a_parent_node_id, $this->node_id); - - $this->ctrl->setParameter($this, "wsp_id", $this->node_id); - break; - - case self::OBJECT_ID: - case self::PORTFOLIO_OBJECT_ID: - // do nothing - break; - } - - // BEGIN ChangeEvent: Record save object. - require_once('Services/Tracking/classes/class.ilChangeEvent.php'); - ilChangeEvent::_recordWriteEvent($this->object_id, $ilUser->getId(), 'create'); - // END ChangeEvent: Record save object. - - // use forced callback after object creation - self::handleAfterSaveCallback($a_obj, $_REQUEST["crtcb"]); - } - - /** - * After creation callback - * - * @param ilObject $a_obj - * @param int $a_callback_ref_id - */ - public static function handleAfterSaveCallback(ilObject $a_obj, $a_callback_ref_id) - { - global $DIC; - - $objDefinition = $DIC["objDefinition"]; - - - $a_callback_ref_id = (int)$a_callback_ref_id; - if($a_callback_ref_id) - { - $callback_type = ilObject::_lookupType($a_callback_ref_id, true); - $class_name = "ilObj".$objDefinition->getClassName($callback_type)."GUI"; - $location = $objDefinition->getLocation($callback_type); - include_once($location."/class.".$class_name.".php"); - if (in_array(strtolower($class_name), array("ilobjitemgroupgui"))) - { - $callback_obj = new $class_name($a_callback_ref_id); - } - else - { - $callback_obj = new $class_name(null, $a_callback_ref_id, true, false); - } - $callback_obj->afterSaveCallback($a_obj); - } - } - - /** - * Check permission - * - * @param string $a_perm - * @param string $a_cmd - * @param string $a_type - * @param int $a_node_id - * @return bool - */ - protected function checkPermissionBool($a_perm, $a_cmd = "", $a_type = "", $a_node_id = null) - { - global $DIC; - - $ilUser = $DIC["ilUser"]; - - - if($a_perm == "create") - { - if(!$a_node_id) - { - $a_node_id = $this->parent_id; - } - if($a_node_id) - { - return $this->getAccessHandler()->checkAccess($a_perm."_".$a_type, $a_cmd, $a_node_id); - } - } - else - { - - if (!$a_node_id) - { - $a_node_id = $this->node_id; - } - if($a_node_id) - { - return $this->getAccessHandler()->checkAccess($a_perm, $a_cmd, $a_node_id); - } - } - - // if we do not have a node id, check if current user is owner - if($this->obj_id && $this->object->getOwner() == $ilUser->getId()) - { - return true; - } - return false; - } - - /** - * Add header action menu - * - * @param string $a_sub_type - * @param int $a_sub_id - * @return ilObjectListGUI - */ - protected function initHeaderAction($a_sub_type = null, $a_sub_id = null) - { - if($this->id_type == self::WORKSPACE_NODE_ID) - { - if(!$this->creation_mode && $this->object_id) - { - include_once "Services/Object/classes/class.ilCommonActionDispatcherGUI.php"; - $dispatcher = new ilCommonActionDispatcherGUI(ilCommonActionDispatcherGUI::TYPE_WORKSPACE, - $this->getAccessHandler(), $this->getType(), $this->node_id, $this->object_id); - - $dispatcher->setSubObject($a_sub_type, $a_sub_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(); - - if(is_object($lg)) - { - // to enable add to desktop / remove from desktop - if($this instanceof ilDesktopItemHandling) - { - $lg->setContainerObject($this); - } - - // for activation checks see ilObjectGUI - // $lg->enableComments(true); - $lg->enableNotes(true); - // $lg->enableTags(true); - } - - return $lg; - } - } - else - { - return parent::initHeaderAction(); - } - } - - /** - * Updating icons after ajax call - */ - protected function redrawHeaderAction() - { - parent::redrawHeaderActionObject(); - } - - protected function getPermanentLinkWidget($a_append = null, $a_center = false) - { - if($this->id_type == self::WORKSPACE_NODE_ID) - { - $a_append .= "_wsp"; - } - - include_once('Services/PermanentLink/classes/class.ilPermanentLinkGUI.php'); - $plink = new ilPermanentLinkGUI($this->getType(), $this->node_id , $a_append); - $plink->setIncludePermanentLinkText(false); - $plink->setAlignCenter($a_center); - return $plink->getHTML(); - } - - - /** - * @param \ilObject $a_new_obj - */ - protected function handleAutoRating(ilObject $a_new_obj) - { - // only needed in repository - if($this->id_type == self::REPOSITORY_NODE_ID) - { - parent::handleAutoRating($a_new_obj); - } - } + protected $object_id; + protected $node_id; + protected $creation_forms = array(); + protected $id_type = array(); + protected $parent_id; + public $tree; + protected $access_handler; + + const OBJECT_ID = 0; + const REPOSITORY_NODE_ID = 1; + const WORKSPACE_NODE_ID = 2; + const REPOSITORY_OBJECT_ID = 3; + const WORKSPACE_OBJECT_ID = 4; + const PORTFOLIO_OBJECT_ID = 5; + + /** + * Constructor + * + * @param int $a_id + * @param int $a_id_type + * @param int $a_parent_node_id + */ + public function __construct($a_id = 0, $a_id_type = self::REPOSITORY_NODE_ID, $a_parent_node_id = 0) + { + global $DIC; + + $objDefinition = $DIC["objDefinition"]; + $tpl = $DIC["tpl"]; + $ilCtrl = $DIC["ilCtrl"]; + $ilErr = $DIC["ilErr"]; + $lng = $DIC["lng"]; + $ilTabs = $DIC["ilTabs"]; + $tree = $DIC["tree"]; + $ilAccess = $DIC["ilAccess"]; + $this->object_service = $DIC->object(); + + if (!isset($ilErr)) { + $ilErr = new ilErrorHandling(); + $ilErr->setErrorHandling(PEAR_ERROR_CALLBACK, array($ilErr,'errorHandler')); + } else { + $this->ilErr = $ilErr; + } + + $this->id_type = $a_id_type; + $this->parent_id = $a_parent_node_id; + $this->type = $this->getType(); + $this->html = ""; + + $this->tabs_gui = $ilTabs; + $this->objDefinition = $objDefinition; + $this->tpl = $tpl; + $this->ctrl = $ilCtrl; + $this->lng = $lng; + + // these are things that are initialised in ilObjectGUI constructor now + // and may miss here + $this->locator = $DIC["ilLocator"]; + $this->user = $DIC->user(); + $this->access = $DIC->access(); + //$this->settings = $DIC->settings(); + //$this->rbacreview = $DIC->rbac()->review(); + $this->toolbar = $DIC->toolbar(); + + + $params = array(); + switch ($this->id_type) { + case self::REPOSITORY_NODE_ID: + $this->node_id = $a_id; + $this->object_id = ilObject::_lookupObjectId($this->node_id); + $this->tree = $tree; + $this->access_handler = $ilAccess; + $this->call_by_reference = true; // needed for prepareOutput() + $params[] = "ref_id"; + break; + + case self::REPOSITORY_OBJECT_ID: + $this->object_id = $a_id; + $this->tree = $tree; + $this->access_handler = $ilAccess; + $params[] = "obj_id"; // ??? + break; + + case self::WORKSPACE_NODE_ID: + $ilUser = $DIC["ilUser"]; + $this->node_id = $a_id; + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + $this->tree = new ilWorkspaceTree($ilUser->getId()); + $this->object_id = $this->tree->lookupObjectId($this->node_id); + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; + $this->access_handler = new ilWorkspaceAccessHandler($this->tree); + $params[] = "wsp_id"; + break; + + case self::WORKSPACE_OBJECT_ID: + $ilUser = $DIC["ilUser"]; + $this->object_id = $a_id; + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + $this->tree = new ilWorkspaceTree($ilUser->getId()); + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; + $this->access_handler = new ilWorkspaceAccessHandler($this->tree); + $params[] = "obj_id"; // ??? + break; + + case self::PORTFOLIO_OBJECT_ID: + $this->object_id = $a_id; + include_once('./Modules/Portfolio/classes/class.ilPortfolioAccessHandler.php'); + $this->access_handler = new ilPortfolioAccessHandler(); + $params[] = "prt_id"; + break; + + case self::OBJECT_ID: + $this->object_id = $a_id; + include_once "Services/Object/classes/class.ilDummyAccessHandler.php"; + $this->access_handler = new ilDummyAccessHandler(); + $params[] = "obj_id"; + break; + } + $this->ctrl->saveParameter($this, $params); + + + + // old stuff for legacy code (obsolete?) + if (!$this->object_id) { + $this->creation_mode = true; + } + if ($this->node_id) { + // add parent node id if missing + if (!$this->parent_id && $this->tree) { + $this->parent_id = $this->tree->getParentId($this->node_id); + } + } + $this->ref_id = $this->node_id; + $this->obj_id = $this->object_id; + + + + $this->assignObject(); + + // set context + if (is_object($this->object)) { + $this->ctrl->setContext($this->object->getId(), $this->object->getType()); + } + + $this->afterConstructor(); + } + + /** + * Do anything that should be done after constructor in here. + */ + protected function afterConstructor() + { + } + + /** + * execute command + */ + public function executeCommand() + { + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + $this->prepareOutput(); + + switch ($next_class) { + case "ilworkspaceaccessgui": + if ($this->node_id) { + $this->tabs_gui->activateTab("id_permissions"); + + include_once('./Services/PersonalWorkspace/classes/class.ilWorkspaceAccessGUI.php'); + $wspacc = new ilWorkspaceAccessGUI($this->node_id, $this->getAccessHandler()); + $this->ctrl->forwardCommand($wspacc); + break; + } + + // no break + default: + if (!$cmd) { + $cmd = "render"; + } + return $this->$cmd(); + } + + return true; + } + + /** + * create object instance as internal property (repository/workspace switch) + */ + final protected function assignObject() + { + if ($this->object_id != 0) { + switch ($this->id_type) { + case self::OBJECT_ID: + case self::REPOSITORY_OBJECT_ID: + case self::WORKSPACE_OBJECT_ID: + case self::PORTFOLIO_OBJECT_ID: + $this->object = ilObjectFactory::getInstanceByObjId($this->object_id); + break; + + case self::REPOSITORY_NODE_ID: + $this->object = ilObjectFactory::getInstanceByRefId($this->node_id); + break; + + case self::WORKSPACE_NODE_ID: + // to be discussed + $this->object = ilObjectFactory::getInstanceByObjId($this->object_id); + break; + } + } + } + + /** + * Get access handler + * + * @return object + */ + protected function getAccessHandler() + { + return $this->access_handler; + } + + /** + * set Locator + */ + protected function setLocator() + { + global $DIC; + + $ilLocator = $DIC["ilLocator"]; + $tpl = $DIC["tpl"]; + + if ($this->omit_locator) { + return; + } + + switch ($this->id_type) { + case self::REPOSITORY_NODE_ID: + $ref_id = $this->node_id + ? $this->node_id + : $this->parent_id; + $ilLocator->addRepositoryItems($ref_id); + + // not so nice workaround: todo: handle $ilLocator as tabs in ilTemplate + if ($_GET["admin_mode"] == "" && + strtolower($this->ctrl->getCmdClass()) == "ilobjrolegui") { + $this->ctrl->setParameterByClass( + "ilobjrolegui", + "rolf_ref_id", + $_GET["rolf_ref_id"] + ); + $this->ctrl->setParameterByClass( + "ilobjrolegui", + "obj_id", + $_GET["obj_id"] + ); + $ilLocator->addItem( + $this->lng->txt("role"), + $this->ctrl->getLinkTargetByClass(array("ilpermissiongui", + "ilobjrolegui"), "perm") + ); + } + + // in workspace this is done in ilPersonalWorkspaceGUI + if ($this->object_id) { + $this->addLocatorItems(); + } + $tpl->setLocator(); + + break; + + case self::WORKSPACE_NODE_ID: + // :TODO: + break; + } + } + + /** + * Display delete confirmation form (repository/workspace switch) + */ + public function delete() + { + switch ($this->id_type) { + case self::REPOSITORY_NODE_ID: + case self::REPOSITORY_OBJECT_ID: + return parent::deleteObject(); + + case self::WORKSPACE_NODE_ID: + case self::WORKSPACE_OBJECT_ID: + return $this->deleteConfirmation(); + + case self::OBJECT_ID: + case self::PORTFOLIO_OBJECT_ID: + // :TODO: should this ever occur? + break; + } + } + + /** + * Display delete confirmation form (workspace specific) + * + * This should probably be moved elsewhere as done with RepUtil + */ + protected function deleteConfirmation() + { + global $DIC; + + $tpl = $DIC["tpl"]; + $lng = $DIC["lng"]; + + $node_id = (int) $_REQUEST["item_ref_id"]; + if (!$node_id) { + ilUtil::sendFailure($lng->txt("no_checkbox"), true); + $this->ctrl->redirect($this, ""); + } + + // on cancel or fail we return to parent node + $parent_node = $this->tree->getParentId($node_id); + $this->ctrl->setParameter($this, "wsp_id", $parent_node); + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setHeaderText($lng->txt("info_delete_sure") . "
                  " . + $lng->txt("info_delete_warning_no_trash")); + + $cgui->setFormAction($this->ctrl->getFormAction($this)); + $cgui->setCancel($lng->txt("cancel"), "cancelDelete"); + $cgui->setConfirm($lng->txt("confirm"), "confirmedDelete"); + + $a_ids = array($node_id); + foreach ($a_ids as $node_id) { + $children = $this->tree->getSubTree($this->tree->getNodeData($node_id)); + foreach ($children as $child) { + $node_id = $child["wsp_id"]; + $obj_id = $this->tree->lookupObjectId($node_id); + $type = ilObject::_lookupType($obj_id); + $title = call_user_func(array(ilObjectFactory::getClassByType($type),'_lookupTitle'), $obj_id); + + // if anything fails, abort the whole process + if (!$this->checkPermissionBool("delete", "", "", $node_id)) { + ilUtil::sendFailure($lng->txt("msg_no_perm_delete") . " " . $title, true); + $this->ctrl->redirect($this); + } + + $cgui->addItem( + "id[]", + $node_id, + $title, + ilObject::_getIcon($obj_id, "small", $type), + $lng->txt("icon") . " " . $lng->txt("obj_" . $type) + ); + } + } + + $tpl->setContent($cgui->getHTML()); + } + + /** + * Delete objects (repository/workspace switch) + */ + public function confirmedDelete() + { + switch ($this->id_type) { + case self::REPOSITORY_NODE_ID: + case self::REPOSITORY_OBJECT_ID: + return parent::confirmedDeleteObject(); + + case self::WORKSPACE_NODE_ID: + case self::WORKSPACE_OBJECT_ID: + return $this->deleteConfirmedObjects(); + + case self::OBJECT_ID: + case self::PORTFOLIO_OBJECT_ID: + // :TODO: should this ever occur? + break; + } + } + + /** + * Delete objects (workspace specific) + * + * This should probably be moved elsewhere as done with RepUtil + */ + protected function deleteConfirmedObjects() + { + global $DIC; + + $lng = $DIC["lng"]; + + + if (sizeof($_POST["id"])) { + // #18797 - because of parent/child relations gather all nodes first + $del_nodes = array(); + foreach ($_POST["id"] as $node_id) { + $del_nodes[$node_id] = $this->tree->getNodeData($node_id); + } + + foreach ($del_nodes as $node_id => $node) { + // tree/reference + $this->tree->deleteReference($node_id); + if ($this->tree->isInTree($node_id)) { + $this->tree->deleteTree($node); + } + + // permission + $this->getAccessHandler()->removePermission($node_id); + + // object + $object = ilObjectFactory::getInstanceByObjId($node["obj_id"], false); + if ($object) { + $object->delete(); + } + } + + ilUtil::sendSuccess($lng->txt("msg_removed"), true); + } else { + ilUtil::sendFailure($lng->txt("no_checkbox"), true); + } + + $this->ctrl->redirect($this, ""); + } + + public function getHTML() + { + return parent::getHTML(); + } + + /** + * Final/Private declaration of unchanged parent methods + */ + final public function withReferences() + { + return parent::withReferences(); + } + final public function setCreationMode($a_mode = true) + { + return parent::setCreationMode($a_mode); + } + final public function getCreationMode() + { + return parent::getCreationMode(); + } + final public function prepareOutput($a_show_subobjects = true) + { + return parent::prepareOutput($a_show_subobjects); + } + protected function setTitleAndDescription() + { + return parent::setTitleAndDescription(); + } + final protected function showUpperIcon() + { + return parent::showUpperIcon(); + } + // final private function showMountWebfolderIcon() { return parent::showMountWebfolderIcon(); } + final protected function omitLocator($a_omit = true) + { + return parent::omitLocator($a_omit); + } + final protected function getTargetFrame($a_cmd, $a_target_frame = "") + { + return parent::getTargetFrame($a_cmd, $a_target_frame); + } + final protected function setTargetFrame($a_cmd, $a_target_frame) + { + return parent::setTargetFrame($a_cmd, $a_target_frame); + } + final public function isVisible($a_ref_id, $a_type) + { + return parent::isVisible($a_ref_id, $a_type); + } + final protected function getCenterColumnHTML() + { + return parent::getCenterColumnHTML(); + } + final protected function getRightColumnHTML() + { + return parent::getRightColumnHTML(); + } + final protected function setColumnSettings(ilColumnGUI $column_gui) + { + return parent::setColumnSettings($column_gui); + } + final protected function checkPermission($a_perm, $a_cmd = "", $a_type = "", $a_ref_id = null) + { + return parent::checkPermission($a_perm, $a_cmd, $a_type, $a_ref_id); + } + + // -> ilContainerGUI + final protected function showPossibleSubObjects() + { + return parent::showPossibleSubObjects(); + } + // -> ilRepUtilGUI + final public function trash() + { + return parent::trashObject(); + } // done + // -> ilRepUtil + final public function undelete() + { + return parent::undeleteObject(); + } // done + final public function cancelDelete() + { + return parent::cancelDeleteObject(); + } // ok + final public function removeFromSystem() + { + return parent::removeFromSystemObject(); + } // done + final protected function redirectToRefId($a_ref_id, $a_cmd = "") + { + return parent::redirectToRefId(); + } // ok + + // -> stefan + final protected function fillCloneTemplate($a_tpl_varname, $a_type) + { + return parent::fillCloneTemplate($a_tpl_varname, $a_type); + } + final protected function fillCloneSearchTemplate($a_tpl_varname, $a_type) + { + return parent::fillCloneSearchTemplate($a_tpl_varname, $a_type); + } + final protected function searchCloneSource() + { + return parent::searchCloneSourceObject(); + } + final public function cloneAll() + { + return parent::cloneAllObject(); + } + final protected function buildCloneSelect($existing_objs) + { + return parent::buildCloneSelect($existing_objs); + } + + // -> ilAdministration + final private function displayList() + { + return parent::displayList(); + } + // final private function setAdminTabs() { return parent::setAdminTabs(); } + // final public function getAdminTabs() { return parent::getAdminTabs(); } + final protected function addAdminLocatorItems($a_do_not_add_object = false) + { + return parent::addAdminLocatorItems($a_do_not_add_object); + } + + /** + * view object content (repository/workspace switch) + */ + public function view() + { + switch ($this->id_type) { + case self::REPOSITORY_NODE_ID: + case self::REPOSITORY_OBJECT_ID: + return parent::viewObject(); + + case self::WORKSPACE_NODE_ID: + case self::WORKSPACE_OBJECT_ID: + return $this->render(); + + case self::OBJECT_ID: + case self::PORTFOLIO_OBJECT_ID: + // :TODO: should this ever occur? do nothing or edit() ?! + break; + } + } + + /** + * create tabs (repository/workspace switch) + * + * this had to be moved here because of the context-specific permission tab + */ + protected function setTabs() + { + global $DIC; + + $ilTabs = $DIC["ilTabs"]; + $lng = $DIC["lng"]; + + + switch ($this->id_type) { + case self::REPOSITORY_NODE_ID: + case self::REPOSITORY_OBJECT_ID: + if ($this->checkPermissionBool("edit_permission")) { + $ilTabs->addTab( + "id_permissions", + $lng->txt("perm_settings"), + $this->ctrl->getLinkTargetByClass(array(get_class($this), "ilpermissiongui"), "perm") + ); + } + break; + + case self::WORKSPACE_NODE_ID: + case self::WORKSPACE_OBJECT_ID: + // only files and blogs can be shared for now + if ($this->checkPermissionBool("edit_permission") && in_array($this->type, array("file", "blog")) && $this->node_id) { + $ilTabs->addTab( + "id_permissions", + $lng->txt("wsp_permissions"), + $this->ctrl->getLinkTargetByClass(array(get_class($this), "ilworkspaceaccessgui"), "share") + ); + } + break; + } + } + + /** + * Deprecated functions + */ + // final private function setSubObjects($a_sub_objects = "") { die("ilObject2GUI::setSubObjects() is deprecated."); } + // final public function getFormAction($a_cmd, $a_formaction = "") { die("ilObject2GUI::getFormAction() is deprecated."); } + // final protected function setFormAction($a_cmd, $a_formaction) { die("ilObject2GUI::setFormAction() is deprecated."); } + final protected function getReturnLocation($a_cmd, $a_location ="") + { + die("ilObject2GUI::getReturnLocation() is deprecated."); + } + final protected function setReturnLocation($a_cmd, $a_location) + { + die("ilObject2GUI::setReturnLocation() is deprecated."); + } + final protected function showActions() + { + die("ilObject2GUI::showActions() is deprecated."); + } + final protected function getTabs() + { + nj(); + die("ilObject2GUI::getTabs() is deprecated."); + } + final protected function __showButton($a_cmd, $a_text, $a_target = '') + { + die("ilObject2GUI::__showButton() is deprecated."); + } + final protected function hitsperpageObject() + { + die("ilObject2GUI::hitsperpageObject() is deprecated."); + } + final protected function &__initTableGUI() + { + die("ilObject2GUI::__initTableGUI() is deprecated."); + } + final protected function __setTableGUIBasicData(&$tbl, &$result_set, $a_from = "") + { + die("ilObject2GUI::__setTableGUIBasicData() is deprecated."); + } + + /** + * Functions to be overwritten + */ + protected function addLocatorItems() + { + } + + /** + * Functions that must be overwritten + */ + abstract public function getType(); + + /** + * Deleted in ilObject + */ + // final private function permObject() { parent::permObject(); } + // final private function permSaveObject() { parent::permSaveObject(); } + // final private function infoObject() { parent::infoObject(); } + // final private function __buildRoleFilterSelect() { parent::__buildRoleFilterSelect(); } + // final private function __filterRoles() { parent::__filterRoles(); } + // final private function ownerObject() { parent::ownerObject(); } + // final private function changeOwnerObject() { parent::changeOwnerObject(); } + // final private function addRoleObject() { parent::addRoleObject(); } + // final private function setActions($a_actions = "") { die("ilObject2GUI::setActions() is deprecated."); } + // final protected function getActions() { die("ilObject2GUI::getActions() is deprecated."); } + + /** + * CRUD + */ + public function create() + { + parent::createObject(); + } + public function save() + { + parent::saveObject(); + } + public function edit() + { + parent::editObject(); + } + public function update() + { + parent::updateObject(); + } + public function cancel() + { + parent::cancelObject(); + } + + /** + * Init creation froms + * + * this will create the default creation forms: new, import, clone + * + * @param string $a_new_type + * @return array + */ + protected function initCreationForms($a_new_type) + { + $forms = parent::initCreationForms($a_new_type); + + // cloning doesn't work in workspace yet + if ($this->id_type == self::WORKSPACE_NODE_ID) { + unset($forms[self::CFORM_CLONE]); + } + + return $forms; + } + + /** + * Import + * + * @access public + */ + public function importFile() + { + parent::importFileObject($this->parent_id); + } + + /** + * Add object to tree at given position + * + * @param ilObject $a_obj + * @param int $a_parent_node_id + */ + public function putObjectInTree(ilObject $a_obj, $a_parent_node_id = null) + { + global $DIC; + + $rbacreview = $DIC["rbacreview"]; + $ilUser = $DIC["ilUser"]; + + + $this->object_id = $a_obj->getId(); + + if (!$a_parent_node_id) { + $a_parent_node_id = $this->parent_id; + } + + // add new object to custom parent container + if ((int) $_REQUEST["crtptrefid"]) { + $a_parent_node_id = (int) $_REQUEST["crtptrefid"]; + } + + switch ($this->id_type) { + case self::REPOSITORY_NODE_ID: + case self::REPOSITORY_OBJECT_ID: + if (!$this->node_id) { + $a_obj->createReference(); + $this->node_id = $a_obj->getRefId(); + } + $a_obj->putInTree($a_parent_node_id); + $a_obj->setPermissions($a_parent_node_id); + + // rbac log + include_once "Services/AccessControl/classes/class.ilRbacLog.php"; + $rbac_log_roles = $rbacreview->getParentRoleIds($this->node_id, false); + $rbac_log = ilRbacLog::gatherFaPa($this->node_id, array_keys($rbac_log_roles), true); + ilRbacLog::add(ilRbacLog::CREATE_OBJECT, $this->node_id, $rbac_log); + + $this->ctrl->setParameter($this, "ref_id", $this->node_id); + break; + + case self::WORKSPACE_NODE_ID: + case self::WORKSPACE_OBJECT_ID: + if (!$this->node_id) { + $this->node_id = $this->tree->insertObject($a_parent_node_id, $this->object_id); + } + $this->getAccessHandler()->setPermissions($a_parent_node_id, $this->node_id); + + $this->ctrl->setParameter($this, "wsp_id", $this->node_id); + break; + + case self::OBJECT_ID: + case self::PORTFOLIO_OBJECT_ID: + // do nothing + break; + } + + // BEGIN ChangeEvent: Record save object. + require_once('Services/Tracking/classes/class.ilChangeEvent.php'); + ilChangeEvent::_recordWriteEvent($this->object_id, $ilUser->getId(), 'create'); + // END ChangeEvent: Record save object. + + // use forced callback after object creation + self::handleAfterSaveCallback($a_obj, $_REQUEST["crtcb"]); + } + + /** + * After creation callback + * + * @param ilObject $a_obj + * @param int $a_callback_ref_id + */ + public static function handleAfterSaveCallback(ilObject $a_obj, $a_callback_ref_id) + { + global $DIC; + + $objDefinition = $DIC["objDefinition"]; + + + $a_callback_ref_id = (int) $a_callback_ref_id; + if ($a_callback_ref_id) { + $callback_type = ilObject::_lookupType($a_callback_ref_id, true); + $class_name = "ilObj" . $objDefinition->getClassName($callback_type) . "GUI"; + $location = $objDefinition->getLocation($callback_type); + include_once($location . "/class." . $class_name . ".php"); + if (in_array(strtolower($class_name), array("ilobjitemgroupgui"))) { + $callback_obj = new $class_name($a_callback_ref_id); + } else { + $callback_obj = new $class_name(null, $a_callback_ref_id, true, false); + } + $callback_obj->afterSaveCallback($a_obj); + } + } + + /** + * Check permission + * + * @param string $a_perm + * @param string $a_cmd + * @param string $a_type + * @param int $a_node_id + * @return bool + */ + protected function checkPermissionBool($a_perm, $a_cmd = "", $a_type = "", $a_node_id = null) + { + global $DIC; + + $ilUser = $DIC["ilUser"]; + + + if ($a_perm == "create") { + if (!$a_node_id) { + $a_node_id = $this->parent_id; + } + if ($a_node_id) { + return $this->getAccessHandler()->checkAccess($a_perm . "_" . $a_type, $a_cmd, $a_node_id); + } + } else { + if (!$a_node_id) { + $a_node_id = $this->node_id; + } + if ($a_node_id) { + return $this->getAccessHandler()->checkAccess($a_perm, $a_cmd, $a_node_id); + } + } + + // if we do not have a node id, check if current user is owner + if ($this->obj_id && $this->object->getOwner() == $ilUser->getId()) { + return true; + } + return false; + } + + /** + * Add header action menu + * + * @param string $a_sub_type + * @param int $a_sub_id + * @return ilObjectListGUI + */ + protected function initHeaderAction($a_sub_type = null, $a_sub_id = null) + { + if ($this->id_type == self::WORKSPACE_NODE_ID) { + if (!$this->creation_mode && $this->object_id) { + include_once "Services/Object/classes/class.ilCommonActionDispatcherGUI.php"; + $dispatcher = new ilCommonActionDispatcherGUI( + ilCommonActionDispatcherGUI::TYPE_WORKSPACE, + $this->getAccessHandler(), + $this->getType(), + $this->node_id, + $this->object_id + ); + + $dispatcher->setSubObject($a_sub_type, $a_sub_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(); + + if (is_object($lg)) { + // to enable add to desktop / remove from desktop + if ($this instanceof ilDesktopItemHandling) { + $lg->setContainerObject($this); + } + + // for activation checks see ilObjectGUI + // $lg->enableComments(true); + $lg->enableNotes(true); + // $lg->enableTags(true); + } + + return $lg; + } + } else { + return parent::initHeaderAction(); + } + } + + /** + * Updating icons after ajax call + */ + protected function redrawHeaderAction() + { + parent::redrawHeaderActionObject(); + } + + protected function getPermanentLinkWidget($a_append = null, $a_center = false) + { + if ($this->id_type == self::WORKSPACE_NODE_ID) { + $a_append .= "_wsp"; + } + + include_once('Services/PermanentLink/classes/class.ilPermanentLinkGUI.php'); + $plink = new ilPermanentLinkGUI($this->getType(), $this->node_id, $a_append); + $plink->setIncludePermanentLinkText(false); + $plink->setAlignCenter($a_center); + return $plink->getHTML(); + } + + + /** + * @param \ilObject $a_new_obj + */ + protected function handleAutoRating(ilObject $a_new_obj) + { + // only needed in repository + if ($this->id_type == self::REPOSITORY_NODE_ID) { + parent::handleAutoRating($a_new_obj); + } + } } diff --git a/Services/Object/classes/class.ilObjectAccess.php b/Services/Object/classes/class.ilObjectAccess.php index ef1264518c8769b6ec81a1f72b5ec28dc5946917..ade4f2169a6528e7303fc627100edbf4963b2349 100644 --- a/Services/Object/classes/class.ilObjectAccess.php +++ b/Services/Object/classes/class.ilObjectAccess.php @@ -15,133 +15,127 @@ */ class ilObjectAccess implements \ilWACCheckingClass { - /** - * Checks wether a user may invoke a command or not - * (this method is called by ilAccessHandler::checkAccess) - * - * Please do not check any preconditions handled by - * ilConditionHandler here. Also don't do any RBAC checks. - * - * @param string $a_cmd command (not permission!) - * @param string $a_permission permission - * @param int $a_ref_id reference id - * @param int $a_obj_id object id - * @param int $a_user_id user id (if not provided, current user is taken) - * - * @return boolean true, if everything is ok - */ - function _checkAccess($a_cmd, $a_permission, $a_ref_id, $a_obj_id, $a_user_id = "") - { + /** + * Checks wether a user may invoke a command or not + * (this method is called by ilAccessHandler::checkAccess) + * + * Please do not check any preconditions handled by + * ilConditionHandler here. Also don't do any RBAC checks. + * + * @param string $a_cmd command (not permission!) + * @param string $a_permission permission + * @param int $a_ref_id reference id + * @param int $a_obj_id object id + * @param int $a_user_id user id (if not provided, current user is taken) + * + * @return boolean true, if everything is ok + */ + public function _checkAccess($a_cmd, $a_permission, $a_ref_id, $a_obj_id, $a_user_id = "") + { - // add no access info item and return false if access is not granted - // $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $a_text, $a_data = ""); - // - // for all RBAC checks use checkAccessOfUser instead the normal checkAccess-method: - // $rbacsystem->checkAccessOfUser($a_user_id, $a_permission, $a_ref_id) + // add no access info item and return false if access is not granted + // $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $a_text, $a_data = ""); + // + // for all RBAC checks use checkAccessOfUser instead the normal checkAccess-method: + // $rbacsystem->checkAccessOfUser($a_user_id, $a_permission, $a_ref_id) - return true; - } + return true; + } - /** - * check condition - * - * this method is called by ilConditionHandler - */ - public function _checkCondition($a_obj_id, $a_operator, $a_value, $a_usr_id) - { - switch($a_operator) - { - default: - return true; - } - } - - /** - * 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() - ); - - return $commands; - } - - /** - * check whether goto script will succeed - */ - static function _checkGoto($a_target) - { - global $DIC; + /** + * check condition + * + * this method is called by ilConditionHandler + */ + public function _checkCondition($a_obj_id, $a_operator, $a_value, $a_usr_id) + { + switch ($a_operator) { + default: + return true; + } + } + + /** + * 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() + ); + + return $commands; + } + + /** + * check whether goto script will succeed + */ + public static function _checkGoto($a_target) + { + global $DIC; - $ilAccess = $DIC->access(); - - $t_arr = explode("_", $a_target); + $ilAccess = $DIC->access(); + + $t_arr = explode("_", $a_target); - if ($ilAccess->checkAccess("read", "", $t_arr[1])) - { - return true; - } - return false; - } + if ($ilAccess->checkAccess("read", "", $t_arr[1])) { + return true; + } + return false; + } - /** - * Type-specific implementation of general status, has to be overwritten if object type does - * not support centralized offline handling - * - * Used in ListGUI and Learning Progress - * - * @param int $a_obj_id - * @return bool - */ - static function _isOffline($a_obj_id) - { - global $DIC; + /** + * Type-specific implementation of general status, has to be overwritten if object type does + * not support centralized offline handling + * + * Used in ListGUI and Learning Progress + * + * @param int $a_obj_id + * @return bool + */ + public static function _isOffline($a_obj_id) + { + global $DIC; - $objDefinition = $DIC['objDefinition']; - if($objDefinition->supportsOfflineHandling(ilObject::_lookupType($a_obj_id))) - { - return ilObject::lookupOfflineStatus($a_obj_id); - } - return null; - } + $objDefinition = $DIC['objDefinition']; + if ($objDefinition->supportsOfflineHandling(ilObject::_lookupType($a_obj_id))) { + return ilObject::lookupOfflineStatus($a_obj_id); + } + return null; + } - /** - * Preload data - * - * @param array $a_obj_ids array of object ids - */ - static function _preloadData($a_obj_ids, $a_ref_ids) - { - - } + /** + * Preload data + * + * @param array $a_obj_ids array of object ids + */ + public static function _preloadData($a_obj_ids, $a_ref_ids) + { + } - /** - * @inheritdoc - */ - public function canBeDelivered(ilWACPath $ilWACPath) { - global $ilAccess; + /** + * @inheritdoc + */ + public function canBeDelivered(ilWACPath $ilWACPath) + { + global $ilAccess; - preg_match("/\\/obj_([\\d]*)\\//uism", $ilWACPath->getPath(), $results); - foreach (ilObject2::_getAllReferences($results[1]) as $ref_id) { - if ($ilAccess->checkAccess('visible', '', $ref_id) || $ilAccess->checkAccess('read', '', $ref_id)) { - return true; - } - } + preg_match("/\\/obj_([\\d]*)\\//uism", $ilWACPath->getPath(), $results); + foreach (ilObject2::_getAllReferences($results[1]) as $ref_id) { + if ($ilAccess->checkAccess('visible', '', $ref_id) || $ilAccess->checkAccess('read', '', $ref_id)) { + return true; + } + } - return false; - } + return false; + } } - -?> diff --git a/Services/Object/classes/class.ilObjectActivation.php b/Services/Object/classes/class.ilObjectActivation.php index 6d77b6e4234a8c271d98215a0bf0ae1f653ff6e0..ddc112ba45ec2b8925b9adea0f3c636225467d9e 100644 --- a/Services/Object/classes/class.ilObjectActivation.php +++ b/Services/Object/classes/class.ilObjectActivation.php @@ -1,965 +1,904 @@ - -* @version $Id: class.ilCourseItems.php 30321 2011-08-22 12:05:03Z jluetzen $ -* -* @extends Object -*/ -class ilObjectActivation -{ - - const ERR_SUG_START_END = 1; - - - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilDB - */ - protected $db; - - protected $timing_type; - protected $timing_start; - protected $timing_end; - protected $suggestion_start; - protected $suggestion_end; - protected $visible; - protected $changeable; - - protected $suggestion_start_rel; - protected $suggestion_end_rel; - - protected static $preloaded_data = array(); - - const TIMINGS_ACTIVATION = 0; - const TIMINGS_DEACTIVATED = 1; - const TIMINGS_PRESETTING = 2; - const TIMINGS_FIXED = 3; // session only => obsolete? - - function __construct() - { - global $DIC; - - $this->error = $DIC["ilErr"]; - $this->lng = $DIC->language(); - $this->db = $DIC->database(); - - } - - /** - * Set timing type - * - * @see class constants - * @param int $a_type - */ - function setTimingType($a_type) - { - $this->timing_type = $a_type; - } - - /** - * get timing type - * - * @see class constants - * @return int - */ - function getTimingType() - { - return $this->timing_type; - } - - /** - * Set timing start - * - * @param timestamp $a_start - */ - function setTimingStart($a_start) - { - $this->timing_start = $a_start; - } - - /** - * Get timing start - * - * @return timestamp - */ - function getTimingStart() - { - return $this->timing_start; - } - - /** - * Set timing end - * - * @param timestamp $a_end - */ - function setTimingEnd($a_end) - { - $this->timing_end = $a_end; - } - - /** - * Get timing end - * - * @return timestamp - */ - function getTimingEnd() - { - return $this->timing_end; - } - - /** - * Set suggestion start - * - * @param timestamp $a_start - */ - function setSuggestionStart($a_start) - { - $this->suggestion_start = $a_start; - } - - /** - * Get suggestion start - * - * @return timestamp - */ - function getSuggestionStart() - { - return $this->suggestion_start; - } - - public function getSuggestionStartRelative() - { - return $this->suggestion_start_rel; - } - - public function setSuggestionStartRelative($a_start) - { - $this->suggestion_start_rel = $a_start; - } - - public function getSuggestionEndRelative() - { - return $this->suggestion_end_rel; - } - - public function setSuggestionEndRelative($a_end) - { - $this->suggestion_end_rel = $a_end; - } - - public function getEaliestStartRelative() - { - return $this->earliest_start_rel; - } - - public function setEarliestStartRelative($a_start) - { - $this->earliest_start_rel = $a_start; - } - - /** - * Set suggestion end - * - * @param int $a_end - */ - function setSuggestionEnd($a_end) - { - $this->suggestion_end = $a_end; - } - - /** - * Get suggestion end - * - * @return int - */ - function getSuggestionEnd() - { - return $this->suggestion_end; - } - - /** - * Set earliest start - * - * @param int $a_start - */ - function setEarliestStart($a_start) - { - $this->earliest_start = $a_start; - } - - /** - * Get earliest start - * - * @return int - */ - function getEarliestStart() - { - return $this->earliest_start; - } - - - /** - * Set visible status - * - * @param bool $a_status - */ - function toggleVisible($a_status) - { - $this->visible = (int) $a_status; - } - - /** - * Get visible status - * - * @return bool - */ - function enabledVisible() - { - return (bool) $this->visible; - } - - /** - * Set changeable status - * - * @param bool $a_status - */ - function toggleChangeable($a_status) - { - $this->changeable = (int) $a_status; - } - - /** - * Get changeable status - * - * @return bool - */ - function enabledChangeable() - { - return (bool) $this->changeable; - } - - /** - * Validate current properties - * - * @return boolean - */ - function validateActivation() - { - $ilErr = $this->error; - $lng = $this->lng; - - $ilErr->setMessage(''); - - if($this->getTimingType() == self::TIMINGS_ACTIVATION) - { - if($this->getTimingStart() > $this->getTimingEnd()) - { - $ilErr->appendMessage($lng->txt("crs_activation_start_invalid")); - } - } - else if($this->getTimingType() == self::TIMINGS_PRESETTING) - { - if($this->getSuggestionStart() > $this->getSuggestionEnd()) - { - $ilErr->appendMessage($lng->txt('crs_timing_err_sug_start_end')); - } - } - - if($ilErr->getMessage()) - { - return false; - } - return true; - } - - /** - * @return array - */ - public function validateRelativePlaning() - { - $errors = array(); - - if($this->getSuggestionStartRelative() >= $this->getSuggestionEndRelative()) - { - $errors[] = self::ERR_SUG_START_END; - } - elseif($this->getSuggestionStartRelative() < 0) - { - $errors[] = self::ERR_SUG_START_END; - } - return $errors; - } - - /** - * Update db entry - * - * @param int $a_ref_id - * @param int $a_parent_id - */ - function update($a_ref_id, $a_parent_id = null) - { - $ilDB = $this->db; - - // #10110 - $query = "UPDATE crs_items SET ". - "timing_type = ".$ilDB->quote($this->getTimingType(),'integer').", ". - "timing_start = ".$ilDB->quote((int)$this->getTimingStart(),'integer').", ". - "timing_end = ".$ilDB->quote((int)$this->getTimingEnd(),'integer').", ". - "suggestion_start = ".$ilDB->quote((int)$this->getSuggestionStart(),'integer').", ". - "suggestion_end = ".$ilDB->quote((int)$this->getSuggestionEnd(),'integer').", ". - "changeable = ".$ilDB->quote($this->enabledChangeable(),'integer').", ". - 'suggestion_start_rel = '.$ilDB->quote($this->getSuggestionStartRelative(),'integer').', '. - 'suggestion_end_rel = '.$ilDB->quote($this->getSuggestionEndRelative(), 'integer').', '; - - if($a_parent_id) - { - $query .= "parent_id = ".$ilDB->quote($a_parent_id,'integer').", "; - } - - $query .= "visible = ".$ilDB->quote($this->enabledVisible(),'integer')." ". - "WHERE obj_id = ".$ilDB->quote($a_ref_id,'integer'); - $ilDB->manipulate($query); - - unset(self::$preloaded_data[$a_ref_id]); - - return true; - } - - /** - * Preload data to internal cache - * - * @param array $a_ref_ids - */ - public static function preloadData(array $a_ref_ids) - { - global $DIC; - - $ilDB = $DIC->database(); - - $sql = "SELECT * FROM crs_items". - " WHERE ".$ilDB->in("obj_id", $a_ref_ids, "", "integer"); - $set = $ilDB->query($sql); - while($row = $ilDB->fetchAssoc($set)) - { - self::$preloaded_data[$row["obj_id"]] = $row; - } - } - - /** - * Get item data - * - * @param int $a_ref_id - * @return array - */ - public static function getItem($a_ref_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - if(isset(self::$preloaded_data[$a_ref_id])) - { - return self::$preloaded_data[$a_ref_id]; - } - - $sql = "SELECT * FROM crs_items". - " WHERE obj_id = ".$ilDB->quote($a_ref_id, "integer"); - $set = $ilDB->query($sql); - $row = $ilDB->fetchAssoc($set); - - if(!isset($row["obj_id"])) - { - $row = self::createDefaultEntry($a_ref_id); - } - if($row["obj_id"]) - { - self::$preloaded_data[$row["obj_id"]] = $row; - } - return $row; - } - - /** - * Parse item data for list entries - * - * @param array &$a_item - */ - public static function addAdditionalSubItemInformation(array &$a_item) - { - global $DIC; - - $ilUser = $DIC->user(); - - $item = self::getItem($a_item['ref_id']); - - $a_item['obj_id'] = ($a_item['obj_id'] > 0) - ? $a_item['obj_id'] - : ilObject::_lookupObjId($a_item['ref_id']); - $a_item['type'] = ($a_item['type'] != '') - ? $a_item['type'] - : ilObject::_lookupType($a_item['obj_id']); - - $a_item['timing_type'] = $item['timing_type']; - - if($item['changeable'] && - $item['timing_type'] == self::TIMINGS_PRESETTING) - { - // cognos-blu-patch: begin - include_once './Modules/Course/classes/Timings/class.ilTimingUser.php'; - $user_data = new ilTimingUser($a_item['ref_id'], $ilUser->getId()); - if($user_data->isScheduled()) - { - $a_item['start'] = $user_data->getStart()->get(IL_CAL_UNIX); - $a_item['end'] = $user_data->getEnd()->get(IL_CAL_UNIX); - $a_item['activation_info'] = 'crs_timings_planed_info'; - } - else - { - $a_item['start'] = $item['suggestion_start']; - $a_item['end'] = $item['suggestion_end']; - $a_item['activation_info'] = 'crs_timings_suggested_info'; - } - // cognos-blu-patch: end - } - elseif($item['timing_type'] == self::TIMINGS_PRESETTING) - { - $a_item['start'] = $item['suggestion_start']; - $a_item['end'] = $item['suggestion_end']; - $a_item['activation_info'] = 'crs_timings_suggested_info'; - } - elseif($item['timing_type'] == self::TIMINGS_ACTIVATION) - { - $a_item['start'] = $item['timing_start']; - $a_item['end'] = $item['timing_end']; - $a_item['activation_info'] = 'obj_activation_list_gui'; - } - else - { - $a_item['start'] = 'abc'; - } - - // #7359 - session sorting should always base on appointment date - if($a_item['type'] == 'sess') - { - include_once('./Modules/Session/classes/class.ilSessionAppointment.php'); - $info = ilSessionAppointment::_lookupAppointment($a_item['obj_id']); - - // #11987 - $a_item['masked_start'] = $a_item['start']; - $a_item['masked_end'] = $a_item['end']; - $a_item['start'] = $info['start']; - $a_item['end'] = $info['end']; - } - } - - /** - * Get timing details for list gui - * - * @param ilObjectListGUI $a_list_gui - * @param array &$a_item - * @return array caption, value - */ - public static function addListGUIActivationProperty(ilObjectListGUI $a_list_gui, array &$a_item) - { - global $DIC; - - $lng = $DIC->language(); - - self::addAdditionalSubItemInformation($a_item); - if(isset($a_item['timing_type'])) - { - if(!isset($a_item['masked_start'])) - { - $start = $a_item['start']; - $end = $a_item['end']; - } - else - { - $start = $a_item['masked_start']; - $end = $a_item['masked_end']; - } - $activation = ''; - switch($a_item['timing_type']) - { - case ilObjectActivation::TIMINGS_ACTIVATION: - $activation = ilDatePresentation::formatPeriod( - new ilDateTime($start,IL_CAL_UNIX), - new ilDateTime($end,IL_CAL_UNIX)); - break; - - case ilObjectActivation::TIMINGS_PRESETTING: - $activation = ilDatePresentation::formatPeriod( - new ilDate($start,IL_CAL_UNIX), - new ilDate($end,IL_CAL_UNIX)); - break; - } - if ($activation != "") - { - global $DIC; - - $lng = $DIC->language(); - $lng->loadLanguageModule('crs'); - - $a_list_gui->addCustomProperty($lng->txt($a_item['activation_info']), - $activation, false, true); - } - } - } - - /** - * Create db entry with default values - * - * @param int $a_ref_id - * @return array - */ - protected static function createDefaultEntry($a_ref_id) - { - global $DIC; - - $ilDB = $DIC->database(); - $tree = $DIC->repositoryTree(); - - $parent_id = $tree->getParentId($a_ref_id); - if(!$parent_id) - { - return; - } - - - $ilAtomQuery = $ilDB->buildAtomQuery(); - $ilAtomQuery->addTableLock("crs_items"); - - $ilAtomQuery->addQueryCallable(function(ilDBInterface $ilDB) use ($a_ref_id, $parent_id, &$a_item){ - - $sql = "SELECT * FROM crs_items". - " WHERE obj_id = ".$ilDB->quote($a_ref_id, "integer"); - $set = $ilDB->query($sql); - if(!$ilDB->numRows($set)) - { - $now = time(); - $now_parts = getdate($now); - - $a_item = array(); - $a_item["timing_type"] = self::TIMINGS_DEACTIVATED; - $a_item["timing_start"] = $now; - $a_item["timing_end"] = $now; - $a_item["suggestion_start"] = $now; - $a_item["suggestion_end"] = $now; - $a_item['visible'] = 0; - $a_item['changeable'] = 0; - - $query = "INSERT INTO crs_items (parent_id,obj_id,timing_type,timing_start,timing_end," . - "suggestion_start,suggestion_end, ". - "changeable,visible,suggestion_start_rel, suggestion_end_rel, position) ". - "VALUES( ". - $ilDB->quote($parent_id,'integer').",". - $ilDB->quote($a_ref_id,'integer').",". - $ilDB->quote($a_item["timing_type"],'integer').",". - $ilDB->quote($a_item["timing_start"],'integer').",". - $ilDB->quote($a_item["timing_end"],'integer').",". - $ilDB->quote($a_item["suggestion_start"],'integer').",". - $ilDB->quote($a_item["suggestion_end"],'integer').",". - $ilDB->quote($a_item["changeable"],'integer').",". - $ilDB->quote($a_item["visible"],'integer').", ". - $ilDB->quote($a_item["suggestion_start_rel"],'integer').",". - $ilDB->quote($a_item['suggestion_end_rel'],'integer').", ". - $ilDB->quote(0,'integer').")"; - $ilDB->manipulate($query); - } - - }); - - $ilAtomQuery->run(); - - // #9982 - to make getItem()-cache work - $a_item["obj_id"] = $a_ref_id; - $a_item["parent_id"] = $parent_id; - - return $a_item; - } - - /** - * Delete all db entries for ref id - * - * @param int $a_ref_id - */ - public static function deleteAllEntries($a_ref_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - if(!$a_ref_id) - { - return; - } - - $query = "DELETE FROM crs_items ". - "WHERE obj_id = ".$ilDB->quote($a_ref_id,'integer'); - $ilDB->manipulate($query); - - $query = "DELETE FROM crs_items ". - "WHERE parent_id = ".$ilDB->quote($a_ref_id,'integer'); - $ilDB->manipulate($query); - - return true; - } - - /** - * Clone dependencies - * - * @param int $a_ref_id - * @param int $a_target_id - * @param int $a_copy_id - */ - public static function cloneDependencies($a_ref_id,$a_target_id,$a_copy_id) - { - global $DIC; - - $ilLog = $DIC["ilLog"]; - - $ilLog->write(__METHOD__.': Begin course items...'.$a_ref_id); - - $items = self::getItems($a_ref_id,FALSE); - if(!$items) - { - $ilLog->write(__METHOD__.': No course items found.'); - return true; - } - - // new course item object - if(!is_object($new_container = ilObjectFactory::getInstanceByRefId($a_target_id,false))) - { - $ilLog->write(__METHOD__.': Cannot create target object.'); - return false; - } - - include_once('Services/CopyWizard/classes/class.ilCopyWizardOptions.php'); - $cp_options = ilCopyWizardOptions::_getInstance($a_copy_id); - $mappings = $cp_options->getMappings(); - - foreach($items as $item) - { - if(!isset($mappings[$item['parent_id']]) or !$mappings[$item['parent_id']]) - { - $ilLog->write(__METHOD__.': No mapping for parent nr. '.$item['parent_id']); - continue; - } - if(!isset($mappings[$item['obj_id']]) or !$mappings[$item['obj_id']]) - { - $ilLog->write(__METHOD__.': No mapping for item nr. '.$item['obj_id']); - continue; - } - $new_item_id = $mappings[$item['obj_id']]; - $new_parent = $mappings[$item['parent_id']]; - - $new_item = new self(); - $new_item->setTimingType($item['timing_type']); - $new_item->setTimingStart($item['timing_start']); - $new_item->setTimingEnd($item['timing_end']); - $new_item->setSuggestionStart($item['suggestion_start']); - $new_item->setSuggestionEnd($item['suggestion_end']); - $new_item->toggleChangeable($item['changeable']); - $new_item->toggleVisible($item['visible']); - $new_item->update($new_item_id, $new_parent); - $new_item->setSuggestionStartRelative($item['suggestion_start_rel']); - $new_item->setSuggestionEndRelative($item['suggestion_end_rel']); - $new_item->createDefaultEntry($new_item_id); - $new_item->update($new_item_id); - } - } - - - // - // TIMINGS VIEW RELATED (COURSE ONLY) - // - - /** - * Check if there is any active timing (in subtree) - * - * @param int ref_id - * @return bool - */ - public static function hasTimings($a_ref_id) - { - global $DIC; - - $tree = $DIC->repositoryTree(); - $ilDB = $DIC->database(); - - $subtree = $tree->getSubTree($tree->getNodeData($a_ref_id)); - $ref_ids = array(); - foreach($subtree as $node) - { - $ref_ids[] = $node['ref_id']; - } - - $query = "SELECT * FROM crs_items ". - "WHERE timing_type = ".$ilDB->quote(self::TIMINGS_PRESETTING,'integer')." ". - "AND ".$ilDB->in('obj_id',$ref_ids,false,'integer'); - $res = $ilDB->query($query); - return $res->numRows() ? true :false; - } - - /** - * Check if there is any active changeable timing (in subtree) - * - * @param int ref_id - * @return bool - */ - public static function hasChangeableTimings($a_ref_id) - { - global $DIC; - - $tree = $DIC->repositoryTree(); - $ilDB = $DIC->database(); - - $subtree = $tree->getSubTree($tree->getNodeData($a_ref_id)); - $ref_ids = array(); - foreach($subtree as $node) - { - $ref_ids[] = $node['ref_id']; - } - - $query = "SELECT * FROM crs_items ". - "WHERE timing_type = ".$ilDB->quote(self::TIMINGS_PRESETTING,'integer')." ". - "AND changeable = ".$ilDB->quote(1,'integer')." ". - "AND ".$ilDB->in('obj_id',$ref_ids,false,'integer'); - $res = $ilDB->query($query); - return $res->numRows() ? true : false; - } - - /** - * Validate ref ids and add list data - * - * @param array $a_ref_ids - * @return array - */ - protected static function processListItems(array $a_ref_ids) - { - global $DIC; - - $tree = $DIC->repositoryTree(); - - $res = array(); - - foreach($a_ref_ids as $item_ref_id) - { - if($tree->isDeleted($item_ref_id)) - { - continue; - } - // #7571: when node is removed from system, e.g. inactive trashcan, an empty array is returned - $node = $tree->getNodeData($item_ref_id); - if($node["ref_id"] != $item_ref_id) - { - continue; - } - $res[$item_ref_id] = $node; - } - - if(sizeof($res)) - { - self::preloadData(array_keys($res)); - foreach($res as $idx => $item) - { - self::addAdditionalSubItemInformation($item); - $res[$idx] = $item; - } - } - - return array_values($res); - } - - /** - * Get session material / event items - * - * @param int $a_event_id (object id) - * @return array - */ - public static function getItemsByEvent($a_event_id) - { - include_once 'Modules/Session/classes/class.ilEventItems.php'; - $event_items = new ilEventItems($a_event_id); - return self::processListItems($event_items->getItems()); - } - - /** - * Get materials of item group - * - * @param int $a_item_group_id (object id) - * @return array - */ - public static function getItemsByItemGroup($a_item_group_ref_id) - { - include_once 'Modules/ItemGroup/classes/class.ilItemGroupItems.php'; - $ig_items = new ilItemGroupItems($a_item_group_ref_id); - $items = $ig_items->getValidItems(); - return self::processListItems($items); - } - - /** - * Get objective items - * - * @param int $a_objective_id - * @return array - */ - public static function getItemsByObjective($a_objective_id) - { - include_once('./Modules/Course/classes/class.ilCourseObjectiveMaterials.php'); - $item_ids = ilCourseObjectiveMaterials::_getAssignedMaterials($a_objective_id); - return self::processListItems($item_ids); - } - - /** - * Get sub item data - * - * @param int $a_parent_id - * @param bool $a_with_list_data - * @return array - */ - public static function getItems($a_parent_id, $a_with_list_data = true) - { - global $DIC; - - $tree = $DIC->repositoryTree(); - - $items = array(); - - $ref_ids = array(); - foreach($tree->getChilds($a_parent_id) as $item) - { - if($item['type'] != 'rolf') - { - $items[] = $item; - $ref_ids[] = $item['ref_id']; - } - } - - if($ref_ids) - { - self::preloadData($ref_ids); - - foreach($items as $idx => $item) - { - if(!$a_with_list_data) - { - $items[$idx] = array_merge($item, self::getItem($item['ref_id'])); - } - else - { - self::addAdditionalSubItemInformation($item); - $items[$idx] = $item; - } - } - } - return $items; - } - - /** - * Get (sub) item data for timings administration view (active/inactive) - * - * @param int $a_parent_id - * @return array - */ - public static function getTimingsAdministrationItems($a_parent_id) - { - $items = self::getItems($a_parent_id, false); - - if($items) - { - $active = $inactive = array(); - foreach($items as $item) - { - // active should be first in order - if($item['timing_type'] == self::TIMINGS_DEACTIVATED) - { - $inactive[] = $item; - } - else - { - $active[] = $item; - } - } - - $active = ilUtil::sortArray($active,'start','asc'); - $inactive = ilUtil::sortArray($inactive,'title','asc'); - $items = array_merge($active,$inactive); - } - - return $items; - } - - /** - * Get (sub) item data for timings view (no session material, no side blocks) - * - * @param int $a_container_ref_id - * @return array - */ - public static function getTimingsItems($a_container_ref_id) - { - global $DIC; - - $objDefinition = $DIC["objDefinition"]; - - $filtered = array(); - - include_once 'Modules/Session/classes/class.ilEventItems.php'; - $event_items = ilEventItems::_getItemsOfContainer($a_container_ref_id); - foreach(self::getTimingsAdministrationItems($a_container_ref_id) as $item) - { - if(!in_array($item['ref_id'],$event_items) && - !$objDefinition->isSideBlock($item['type'])) - { - $filtered[] = $item; - } - } - - return $filtered; - } - - /** - * @param $a_ref_id - * @param int $a_parent_id - * @throws ilDatabaseException - */ - public function read($a_ref_id, $a_parent_id = 0) - { - global $DIC; - $ilDB = $DIC->database(); - - $query = 'SELECT * FROM crs_items '. - 'WHERE obj_id = '.$ilDB->quote($a_ref_id,'integer').' '; - - if($a_parent_id) - { - $query .= ('AND parent_id = '.$ilDB->quote($a_parent_id,'integer').' '); - } - $res = $ilDB->query($query); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - $this->setSuggestionStart($row->suggestion_start); - $this->setSuggestionEnd($row->suggestion_end); - $this->setSuggestionStartRelative($row->suggestion_start_rel); - $this->setSuggestionEndRelative($row->suggestion_end_rel); - $this->toggleVisible($row->visible); - $this->toggleChangeable($row->changeable); - $this->setTimingType($row->timing_type); - $this->setTimingStart($row->timing_start); - $this->setTimingEnd($row->timing_end); - } - } -} -?> \ No newline at end of file + +* @version $Id: class.ilCourseItems.php 30321 2011-08-22 12:05:03Z jluetzen $ +* +* @extends Object +*/ +class ilObjectActivation +{ + const ERR_SUG_START_END = 1; + + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilDB + */ + protected $db; + + protected $timing_type; + protected $timing_start; + protected $timing_end; + protected $suggestion_start; + protected $suggestion_end; + protected $visible; + protected $changeable; + + protected $suggestion_start_rel; + protected $suggestion_end_rel; + + protected static $preloaded_data = array(); + + const TIMINGS_ACTIVATION = 0; + const TIMINGS_DEACTIVATED = 1; + const TIMINGS_PRESETTING = 2; + const TIMINGS_FIXED = 3; // session only => obsolete? + + public function __construct() + { + global $DIC; + + $this->error = $DIC["ilErr"]; + $this->lng = $DIC->language(); + $this->db = $DIC->database(); + } + + /** + * Set timing type + * + * @see class constants + * @param int $a_type + */ + public function setTimingType($a_type) + { + $this->timing_type = $a_type; + } + + /** + * get timing type + * + * @see class constants + * @return int + */ + public function getTimingType() + { + return $this->timing_type; + } + + /** + * Set timing start + * + * @param timestamp $a_start + */ + public function setTimingStart($a_start) + { + $this->timing_start = $a_start; + } + + /** + * Get timing start + * + * @return timestamp + */ + public function getTimingStart() + { + return $this->timing_start; + } + + /** + * Set timing end + * + * @param timestamp $a_end + */ + public function setTimingEnd($a_end) + { + $this->timing_end = $a_end; + } + + /** + * Get timing end + * + * @return timestamp + */ + public function getTimingEnd() + { + return $this->timing_end; + } + + /** + * Set suggestion start + * + * @param timestamp $a_start + */ + public function setSuggestionStart($a_start) + { + $this->suggestion_start = $a_start; + } + + /** + * Get suggestion start + * + * @return timestamp + */ + public function getSuggestionStart() + { + return $this->suggestion_start; + } + + public function getSuggestionStartRelative() + { + return $this->suggestion_start_rel; + } + + public function setSuggestionStartRelative($a_start) + { + $this->suggestion_start_rel = $a_start; + } + + public function getSuggestionEndRelative() + { + return $this->suggestion_end_rel; + } + + public function setSuggestionEndRelative($a_end) + { + $this->suggestion_end_rel = $a_end; + } + + public function getEaliestStartRelative() + { + return $this->earliest_start_rel; + } + + public function setEarliestStartRelative($a_start) + { + $this->earliest_start_rel = $a_start; + } + + /** + * Set suggestion end + * + * @param int $a_end + */ + public function setSuggestionEnd($a_end) + { + $this->suggestion_end = $a_end; + } + + /** + * Get suggestion end + * + * @return int + */ + public function getSuggestionEnd() + { + return $this->suggestion_end; + } + + /** + * Set earliest start + * + * @param int $a_start + */ + public function setEarliestStart($a_start) + { + $this->earliest_start = $a_start; + } + + /** + * Get earliest start + * + * @return int + */ + public function getEarliestStart() + { + return $this->earliest_start; + } + + + /** + * Set visible status + * + * @param bool $a_status + */ + public function toggleVisible($a_status) + { + $this->visible = (int) $a_status; + } + + /** + * Get visible status + * + * @return bool + */ + public function enabledVisible() + { + return (bool) $this->visible; + } + + /** + * Set changeable status + * + * @param bool $a_status + */ + public function toggleChangeable($a_status) + { + $this->changeable = (int) $a_status; + } + + /** + * Get changeable status + * + * @return bool + */ + public function enabledChangeable() + { + return (bool) $this->changeable; + } + + /** + * Validate current properties + * + * @return boolean + */ + public function validateActivation() + { + $ilErr = $this->error; + $lng = $this->lng; + + $ilErr->setMessage(''); + + if ($this->getTimingType() == self::TIMINGS_ACTIVATION) { + if ($this->getTimingStart() > $this->getTimingEnd()) { + $ilErr->appendMessage($lng->txt("crs_activation_start_invalid")); + } + } elseif ($this->getTimingType() == self::TIMINGS_PRESETTING) { + if ($this->getSuggestionStart() > $this->getSuggestionEnd()) { + $ilErr->appendMessage($lng->txt('crs_timing_err_sug_start_end')); + } + } + + if ($ilErr->getMessage()) { + return false; + } + return true; + } + + /** + * @return array + */ + public function validateRelativePlaning() + { + $errors = array(); + + if ($this->getSuggestionStartRelative() >= $this->getSuggestionEndRelative()) { + $errors[] = self::ERR_SUG_START_END; + } elseif ($this->getSuggestionStartRelative() < 0) { + $errors[] = self::ERR_SUG_START_END; + } + return $errors; + } + + /** + * Update db entry + * + * @param int $a_ref_id + * @param int $a_parent_id + */ + public function update($a_ref_id, $a_parent_id = null) + { + $ilDB = $this->db; + + // #10110 + $query = "UPDATE crs_items SET " . + "timing_type = " . $ilDB->quote($this->getTimingType(), 'integer') . ", " . + "timing_start = " . $ilDB->quote((int) $this->getTimingStart(), 'integer') . ", " . + "timing_end = " . $ilDB->quote((int) $this->getTimingEnd(), 'integer') . ", " . + "suggestion_start = " . $ilDB->quote((int) $this->getSuggestionStart(), 'integer') . ", " . + "suggestion_end = " . $ilDB->quote((int) $this->getSuggestionEnd(), 'integer') . ", " . + "changeable = " . $ilDB->quote($this->enabledChangeable(), 'integer') . ", " . + 'suggestion_start_rel = ' . $ilDB->quote($this->getSuggestionStartRelative(), 'integer') . ', ' . + 'suggestion_end_rel = ' . $ilDB->quote($this->getSuggestionEndRelative(), 'integer') . ', '; + + if ($a_parent_id) { + $query .= "parent_id = " . $ilDB->quote($a_parent_id, 'integer') . ", "; + } + + $query .= "visible = " . $ilDB->quote($this->enabledVisible(), 'integer') . " " . + "WHERE obj_id = " . $ilDB->quote($a_ref_id, 'integer'); + $ilDB->manipulate($query); + + unset(self::$preloaded_data[$a_ref_id]); + + return true; + } + + /** + * Preload data to internal cache + * + * @param array $a_ref_ids + */ + public static function preloadData(array $a_ref_ids) + { + global $DIC; + + $ilDB = $DIC->database(); + + $sql = "SELECT * FROM crs_items" . + " WHERE " . $ilDB->in("obj_id", $a_ref_ids, "", "integer"); + $set = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($set)) { + self::$preloaded_data[$row["obj_id"]] = $row; + } + } + + /** + * Get item data + * + * @param int $a_ref_id + * @return array + */ + public static function getItem($a_ref_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + if (isset(self::$preloaded_data[$a_ref_id])) { + return self::$preloaded_data[$a_ref_id]; + } + + $sql = "SELECT * FROM crs_items" . + " WHERE obj_id = " . $ilDB->quote($a_ref_id, "integer"); + $set = $ilDB->query($sql); + $row = $ilDB->fetchAssoc($set); + + if (!isset($row["obj_id"])) { + $row = self::createDefaultEntry($a_ref_id); + } + if ($row["obj_id"]) { + self::$preloaded_data[$row["obj_id"]] = $row; + } + return $row; + } + + /** + * Parse item data for list entries + * + * @param array &$a_item + */ + public static function addAdditionalSubItemInformation(array &$a_item) + { + global $DIC; + + $ilUser = $DIC->user(); + + $item = self::getItem($a_item['ref_id']); + + $a_item['obj_id'] = ($a_item['obj_id'] > 0) + ? $a_item['obj_id'] + : ilObject::_lookupObjId($a_item['ref_id']); + $a_item['type'] = ($a_item['type'] != '') + ? $a_item['type'] + : ilObject::_lookupType($a_item['obj_id']); + + $a_item['timing_type'] = $item['timing_type']; + + if ($item['changeable'] && + $item['timing_type'] == self::TIMINGS_PRESETTING) { + // cognos-blu-patch: begin + include_once './Modules/Course/classes/Timings/class.ilTimingUser.php'; + $user_data = new ilTimingUser($a_item['ref_id'], $ilUser->getId()); + if ($user_data->isScheduled()) { + $a_item['start'] = $user_data->getStart()->get(IL_CAL_UNIX); + $a_item['end'] = $user_data->getEnd()->get(IL_CAL_UNIX); + $a_item['activation_info'] = 'crs_timings_planed_info'; + } else { + $a_item['start'] = $item['suggestion_start']; + $a_item['end'] = $item['suggestion_end']; + $a_item['activation_info'] = 'crs_timings_suggested_info'; + } + // cognos-blu-patch: end + } elseif ($item['timing_type'] == self::TIMINGS_PRESETTING) { + $a_item['start'] = $item['suggestion_start']; + $a_item['end'] = $item['suggestion_end']; + $a_item['activation_info'] = 'crs_timings_suggested_info'; + } elseif ($item['timing_type'] == self::TIMINGS_ACTIVATION) { + $a_item['start'] = $item['timing_start']; + $a_item['end'] = $item['timing_end']; + $a_item['activation_info'] = 'obj_activation_list_gui'; + } else { + $a_item['start'] = 'abc'; + } + + // #7359 - session sorting should always base on appointment date + if ($a_item['type'] == 'sess') { + include_once('./Modules/Session/classes/class.ilSessionAppointment.php'); + $info = ilSessionAppointment::_lookupAppointment($a_item['obj_id']); + + // #11987 + $a_item['masked_start'] = $a_item['start']; + $a_item['masked_end'] = $a_item['end']; + $a_item['start'] = $info['start']; + $a_item['end'] = $info['end']; + } + } + + /** + * Get timing details for list gui + * + * @param ilObjectListGUI $a_list_gui + * @param array &$a_item + * @return array caption, value + */ + public static function addListGUIActivationProperty(ilObjectListGUI $a_list_gui, array &$a_item) + { + global $DIC; + + $lng = $DIC->language(); + + self::addAdditionalSubItemInformation($a_item); + if (isset($a_item['timing_type'])) { + if (!isset($a_item['masked_start'])) { + $start = $a_item['start']; + $end = $a_item['end']; + } else { + $start = $a_item['masked_start']; + $end = $a_item['masked_end']; + } + $activation = ''; + switch ($a_item['timing_type']) { + case ilObjectActivation::TIMINGS_ACTIVATION: + $activation = ilDatePresentation::formatPeriod( + new ilDateTime($start, IL_CAL_UNIX), + new ilDateTime($end, IL_CAL_UNIX) + ); + break; + + case ilObjectActivation::TIMINGS_PRESETTING: + $activation = ilDatePresentation::formatPeriod( + new ilDate($start, IL_CAL_UNIX), + new ilDate($end, IL_CAL_UNIX) + ); + break; + } + if ($activation != "") { + global $DIC; + + $lng = $DIC->language(); + $lng->loadLanguageModule('crs'); + + $a_list_gui->addCustomProperty( + $lng->txt($a_item['activation_info']), + $activation, + false, + true + ); + } + } + } + + /** + * Create db entry with default values + * + * @param int $a_ref_id + * @return array + */ + protected static function createDefaultEntry($a_ref_id) + { + global $DIC; + + $ilDB = $DIC->database(); + $tree = $DIC->repositoryTree(); + + $parent_id = $tree->getParentId($a_ref_id); + if (!$parent_id) { + return; + } + + + $ilAtomQuery = $ilDB->buildAtomQuery(); + $ilAtomQuery->addTableLock("crs_items"); + + $ilAtomQuery->addQueryCallable(function (ilDBInterface $ilDB) use ($a_ref_id, $parent_id, &$a_item) { + $sql = "SELECT * FROM crs_items" . + " WHERE obj_id = " . $ilDB->quote($a_ref_id, "integer"); + $set = $ilDB->query($sql); + if (!$ilDB->numRows($set)) { + $now = time(); + $now_parts = getdate($now); + + $a_item = array(); + $a_item["timing_type"] = self::TIMINGS_DEACTIVATED; + $a_item["timing_start"] = $now; + $a_item["timing_end"] = $now; + $a_item["suggestion_start"] = $now; + $a_item["suggestion_end"] = $now; + $a_item['visible'] = 0; + $a_item['changeable'] = 0; + + $query = "INSERT INTO crs_items (parent_id,obj_id,timing_type,timing_start,timing_end," . + "suggestion_start,suggestion_end, " . + "changeable,visible,suggestion_start_rel, suggestion_end_rel, position) " . + "VALUES( " . + $ilDB->quote($parent_id, 'integer') . "," . + $ilDB->quote($a_ref_id, 'integer') . "," . + $ilDB->quote($a_item["timing_type"], 'integer') . "," . + $ilDB->quote($a_item["timing_start"], 'integer') . "," . + $ilDB->quote($a_item["timing_end"], 'integer') . "," . + $ilDB->quote($a_item["suggestion_start"], 'integer') . "," . + $ilDB->quote($a_item["suggestion_end"], 'integer') . "," . + $ilDB->quote($a_item["changeable"], 'integer') . "," . + $ilDB->quote($a_item["visible"], 'integer') . ", " . + $ilDB->quote($a_item["suggestion_start_rel"], 'integer') . "," . + $ilDB->quote($a_item['suggestion_end_rel'], 'integer') . ", " . + $ilDB->quote(0, 'integer') . ")"; + $ilDB->manipulate($query); + } + }); + + $ilAtomQuery->run(); + + // #9982 - to make getItem()-cache work + $a_item["obj_id"] = $a_ref_id; + $a_item["parent_id"] = $parent_id; + + return $a_item; + } + + /** + * Delete all db entries for ref id + * + * @param int $a_ref_id + */ + public static function deleteAllEntries($a_ref_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + if (!$a_ref_id) { + return; + } + + $query = "DELETE FROM crs_items " . + "WHERE obj_id = " . $ilDB->quote($a_ref_id, 'integer'); + $ilDB->manipulate($query); + + $query = "DELETE FROM crs_items " . + "WHERE parent_id = " . $ilDB->quote($a_ref_id, 'integer'); + $ilDB->manipulate($query); + + return true; + } + + /** + * Clone dependencies + * + * @param int $a_ref_id + * @param int $a_target_id + * @param int $a_copy_id + */ + public static function cloneDependencies($a_ref_id, $a_target_id, $a_copy_id) + { + global $DIC; + + $ilLog = $DIC["ilLog"]; + + $ilLog->write(__METHOD__ . ': Begin course items...' . $a_ref_id); + + $items = self::getItems($a_ref_id, false); + if (!$items) { + $ilLog->write(__METHOD__ . ': No course items found.'); + return true; + } + + // new course item object + if (!is_object($new_container = ilObjectFactory::getInstanceByRefId($a_target_id, false))) { + $ilLog->write(__METHOD__ . ': Cannot create target object.'); + return false; + } + + include_once('Services/CopyWizard/classes/class.ilCopyWizardOptions.php'); + $cp_options = ilCopyWizardOptions::_getInstance($a_copy_id); + $mappings = $cp_options->getMappings(); + + foreach ($items as $item) { + if (!isset($mappings[$item['parent_id']]) or !$mappings[$item['parent_id']]) { + $ilLog->write(__METHOD__ . ': No mapping for parent nr. ' . $item['parent_id']); + continue; + } + if (!isset($mappings[$item['obj_id']]) or !$mappings[$item['obj_id']]) { + $ilLog->write(__METHOD__ . ': No mapping for item nr. ' . $item['obj_id']); + continue; + } + $new_item_id = $mappings[$item['obj_id']]; + $new_parent = $mappings[$item['parent_id']]; + + $new_item = new self(); + $new_item->setTimingType($item['timing_type']); + $new_item->setTimingStart($item['timing_start']); + $new_item->setTimingEnd($item['timing_end']); + $new_item->setSuggestionStart($item['suggestion_start']); + $new_item->setSuggestionEnd($item['suggestion_end']); + $new_item->toggleChangeable($item['changeable']); + $new_item->toggleVisible($item['visible']); + $new_item->update($new_item_id, $new_parent); + $new_item->setSuggestionStartRelative($item['suggestion_start_rel']); + $new_item->setSuggestionEndRelative($item['suggestion_end_rel']); + $new_item->createDefaultEntry($new_item_id); + $new_item->update($new_item_id); + } + } + + + // + // TIMINGS VIEW RELATED (COURSE ONLY) + // + + /** + * Check if there is any active timing (in subtree) + * + * @param int ref_id + * @return bool + */ + public static function hasTimings($a_ref_id) + { + global $DIC; + + $tree = $DIC->repositoryTree(); + $ilDB = $DIC->database(); + + $subtree = $tree->getSubTree($tree->getNodeData($a_ref_id)); + $ref_ids = array(); + foreach ($subtree as $node) { + $ref_ids[] = $node['ref_id']; + } + + $query = "SELECT * FROM crs_items " . + "WHERE timing_type = " . $ilDB->quote(self::TIMINGS_PRESETTING, 'integer') . " " . + "AND " . $ilDB->in('obj_id', $ref_ids, false, 'integer'); + $res = $ilDB->query($query); + return $res->numRows() ? true :false; + } + + /** + * Check if there is any active changeable timing (in subtree) + * + * @param int ref_id + * @return bool + */ + public static function hasChangeableTimings($a_ref_id) + { + global $DIC; + + $tree = $DIC->repositoryTree(); + $ilDB = $DIC->database(); + + $subtree = $tree->getSubTree($tree->getNodeData($a_ref_id)); + $ref_ids = array(); + foreach ($subtree as $node) { + $ref_ids[] = $node['ref_id']; + } + + $query = "SELECT * FROM crs_items " . + "WHERE timing_type = " . $ilDB->quote(self::TIMINGS_PRESETTING, 'integer') . " " . + "AND changeable = " . $ilDB->quote(1, 'integer') . " " . + "AND " . $ilDB->in('obj_id', $ref_ids, false, 'integer'); + $res = $ilDB->query($query); + return $res->numRows() ? true : false; + } + + /** + * Validate ref ids and add list data + * + * @param array $a_ref_ids + * @return array + */ + protected static function processListItems(array $a_ref_ids) + { + global $DIC; + + $tree = $DIC->repositoryTree(); + + $res = array(); + + foreach ($a_ref_ids as $item_ref_id) { + if ($tree->isDeleted($item_ref_id)) { + continue; + } + // #7571: when node is removed from system, e.g. inactive trashcan, an empty array is returned + $node = $tree->getNodeData($item_ref_id); + if ($node["ref_id"] != $item_ref_id) { + continue; + } + $res[$item_ref_id] = $node; + } + + if (sizeof($res)) { + self::preloadData(array_keys($res)); + foreach ($res as $idx => $item) { + self::addAdditionalSubItemInformation($item); + $res[$idx] = $item; + } + } + + return array_values($res); + } + + /** + * Get session material / event items + * + * @param int $a_event_id (object id) + * @return array + */ + public static function getItemsByEvent($a_event_id) + { + include_once 'Modules/Session/classes/class.ilEventItems.php'; + $event_items = new ilEventItems($a_event_id); + return self::processListItems($event_items->getItems()); + } + + /** + * Get materials of item group + * + * @param int $a_item_group_id (object id) + * @return array + */ + public static function getItemsByItemGroup($a_item_group_ref_id) + { + include_once 'Modules/ItemGroup/classes/class.ilItemGroupItems.php'; + $ig_items = new ilItemGroupItems($a_item_group_ref_id); + $items = $ig_items->getValidItems(); + return self::processListItems($items); + } + + /** + * Get objective items + * + * @param int $a_objective_id + * @return array + */ + public static function getItemsByObjective($a_objective_id) + { + include_once('./Modules/Course/classes/class.ilCourseObjectiveMaterials.php'); + $item_ids = ilCourseObjectiveMaterials::_getAssignedMaterials($a_objective_id); + return self::processListItems($item_ids); + } + + /** + * Get sub item data + * + * @param int $a_parent_id + * @param bool $a_with_list_data + * @return array + */ + public static function getItems($a_parent_id, $a_with_list_data = true) + { + global $DIC; + + $tree = $DIC->repositoryTree(); + + $items = array(); + + $ref_ids = array(); + foreach ($tree->getChilds($a_parent_id) as $item) { + if ($item['type'] != 'rolf') { + $items[] = $item; + $ref_ids[] = $item['ref_id']; + } + } + + if ($ref_ids) { + self::preloadData($ref_ids); + + foreach ($items as $idx => $item) { + if (!$a_with_list_data) { + $items[$idx] = array_merge($item, self::getItem($item['ref_id'])); + } else { + self::addAdditionalSubItemInformation($item); + $items[$idx] = $item; + } + } + } + return $items; + } + + /** + * Get (sub) item data for timings administration view (active/inactive) + * + * @param int $a_parent_id + * @return array + */ + public static function getTimingsAdministrationItems($a_parent_id) + { + $items = self::getItems($a_parent_id, false); + + if ($items) { + $active = $inactive = array(); + foreach ($items as $item) { + // active should be first in order + if ($item['timing_type'] == self::TIMINGS_DEACTIVATED) { + $inactive[] = $item; + } else { + $active[] = $item; + } + } + + $active = ilUtil::sortArray($active, 'start', 'asc'); + $inactive = ilUtil::sortArray($inactive, 'title', 'asc'); + $items = array_merge($active, $inactive); + } + + return $items; + } + + /** + * Get (sub) item data for timings view (no session material, no side blocks) + * + * @param int $a_container_ref_id + * @return array + */ + public static function getTimingsItems($a_container_ref_id) + { + global $DIC; + + $objDefinition = $DIC["objDefinition"]; + + $filtered = array(); + + include_once 'Modules/Session/classes/class.ilEventItems.php'; + $event_items = ilEventItems::_getItemsOfContainer($a_container_ref_id); + foreach (self::getTimingsAdministrationItems($a_container_ref_id) as $item) { + if (!in_array($item['ref_id'], $event_items) && + !$objDefinition->isSideBlock($item['type'])) { + $filtered[] = $item; + } + } + + return $filtered; + } + + /** + * @param $a_ref_id + * @param int $a_parent_id + * @throws ilDatabaseException + */ + public function read($a_ref_id, $a_parent_id = 0) + { + global $DIC; + $ilDB = $DIC->database(); + + $query = 'SELECT * FROM crs_items ' . + 'WHERE obj_id = ' . $ilDB->quote($a_ref_id, 'integer') . ' '; + + if ($a_parent_id) { + $query .= ('AND parent_id = ' . $ilDB->quote($a_parent_id, 'integer') . ' '); + } + $res = $ilDB->query($query); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + $this->setSuggestionStart($row->suggestion_start); + $this->setSuggestionEnd($row->suggestion_end); + $this->setSuggestionStartRelative($row->suggestion_start_rel); + $this->setSuggestionEndRelative($row->suggestion_end_rel); + $this->toggleVisible($row->visible); + $this->toggleChangeable($row->changeable); + $this->setTimingType($row->timing_type); + $this->setTimingStart($row->timing_start); + $this->setTimingEnd($row->timing_end); + } + } +} diff --git a/Services/Object/classes/class.ilObjectActivationGUI.php b/Services/Object/classes/class.ilObjectActivationGUI.php index a1bafcbf9a69d0046804788093e86ad68b6cfdd3..3eb618ac6ac44a654241d23c36df906ea373bf58 100644 --- a/Services/Object/classes/class.ilObjectActivationGUI.php +++ b/Services/Object/classes/class.ilObjectActivationGUI.php @@ -1,392 +1,378 @@ - - * - * @ilCtrl_Calls ilObjectActivationGUI: ilConditionHandlerGUI - */ -class ilObjectActivationGUI -{ - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * @var ilTabsGUI - */ - protected $tabs_gui; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilTree - */ - protected $tree; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilHelpGUI - */ - protected $help; - - /** - * @var int - */ - protected $parent_ref_id; - - /** - * @var int - */ - protected $item_id; - - /** - * @var \ilTemplate - */ - protected $tpl; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var \ilLanguage - */ - protected $lng; - - /** - * @var int|null - */ - protected $timing_mode = null; - - /** - * @var int|null - */ - protected $activation = null; - - /** - * ilObjectActivationGUI constructor. - * @param $a_ref_id - * @param $a_item_id - */ - public function __construct($a_ref_id,$a_item_id) - { - global $DIC; - - $this->tpl = $DIC->ui()->mainTemplate(); - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->lng->loadLanguageModule('crs'); - - $this->error = $DIC['ilErr']; - $this->tabs_gui = $DIC->tabs(); - $this->access = $DIC->access(); - $this->tree = $DIC->repositoryTree(); - $this->user = $DIC->user(); - $this->help = $DIC["ilHelp"]; - - - $this->parent_ref_id = $a_ref_id; - $this->item_id = $a_item_id; - - $this->ctrl->saveParameter($this,'item_id'); - - } - - /** - * Execute command - * @throws ilCtrlException - */ - public function executeCommand() - { - $tpl = $this->tpl; - - $this->__setTabs(); - - $cmd = $this->ctrl->getCmd(); - - // Check if item id is given and valid - if(!$this->item_id) - { - ilUtil::sendFailure($this->lng->txt("crs_no_item_id_given"),true); - $this->ctrl->returnToParent($this); - } - - $tpl->getStandardTemplate(); - - switch($this->ctrl->getNextClass($this)) - { - case 'ilconditionhandlergui': - // preconditions for single course items - $this->ctrl->saveParameter($this,'item_id',$_GET['item_id']); - $new_gui = new ilConditionHandlerGUI($this,(int) $_GET['item_id']); - $this->ctrl->forwardCommand($new_gui); - $this->tabs_gui->setTabActive('preconditions'); - break; - - default: - $this->initTimingMode(); - $this->initItem(); - $this->tabs_gui->setTabActive('timings'); - if(!$cmd) - { - $cmd = 'edit'; - } - $this->$cmd(); - $this->tabs_gui->setTabActive('timings'); - break; - } - - $tpl->show(); - } - - /** - * @return int - */ - public function getItemId() - { - return $this->item_id; - } - - public function getTimingMode() - { - return $this->timing_mode; - } - - /** - * Get parent ref_id - * @return int - */ - public function getParentId() - { - return $this->parent_ref_id; - } - - /** - * Get item object - * @return ilObjectActivation - */ - public function getActivation() - { - return $this->activation; - } - - - /** - * cancel action handler - */ - public function cancel() - { - $this->ctrl->setParameterByClass('ilrepositorygui', 'ref_id', $this->parent_ref_id); - $this->ctrl->redirectByClass('ilrepositorygui'); - } - - /** - * edit timings - * - * @access public - * @return - */ - public function edit(ilPropertyFormGUI $form = null) - { - $ilErr = $this->error; - $ilAccess = $this->access; - $tpl = $this->tpl; - - // #19997 - see ilObjectListGUI::insertTimingsCommand() - if( - !$ilAccess->checkAccess('write','',$this->parent_ref_id) && - !$ilAccess->checkAccess('write','',$this->getItemId())) - { - $ilErr->raiseError($this->lng->txt('permission_denied'),$ilErr->MESSAGE); - } - - if(!$form instanceof ilPropertyFormGUI) - { - // show edit warning if timings are on - if($GLOBALS['tree']->checkForParentType($this->getParentId(),'crs')) - { - if($this->getActivation()->getTimingType() == ilObjectActivation::TIMINGS_PRESETTING) - { - ilUtil::sendInfo($this->lng->txt('crs_timings_warning_timing_exists')); - } - } - - $form = $this->initFormEdit(); - - } - $tpl->setContent($form->getHTML()); - } - - /** - * init form edit - * - * @access protected - * @return - */ - protected function initFormEdit() - { - $tree = $this->tree; - - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - - $title = ilObject::_lookupTitle(ilObject::_lookupObjId($this->getItemId())); - $form->setTitle($title.': '.$this->lng->txt('crs_edit_timings')); - - - $availability = new ilCheckboxInputGUI($this->lng->txt('crs_timings_availability_enabled'),'availability'); - $availability->setValue(1); - $availability->setChecked($this->getActivation()->getTimingType() == ilObjectActivation::TIMINGS_ACTIVATION); - - $start = new ilDateTimeInputGUI($this->lng->txt('crs_timings_start'),'timing_start'); - $start->setDate(new ilDateTime($this->getActivation()->getTimingStart(),IL_CAL_UNIX)); - $start->setShowTime(true); - $availability->addSubItem($start); - - $end = new ilDateTimeInputGUI($this->lng->txt('crs_timings_end'),'timing_end'); - $end->setDate(new ilDateTime($this->getActivation()->getTimingEnd(),IL_CAL_UNIX)); - $end->setShowTime(true); - $availability->addSubItem($end); - - $isv = new ilCheckboxInputGUI($this->lng->txt('crs_timings_visibility_short'),'visible'); - $isv->setInfo($this->lng->txt('crs_timings_visibility')); - $isv->setValue(1); - $isv->setChecked((bool) $this->getActivation()->enabledVisible()); - $availability->addSubItem($isv); - - - $form->addItem($availability); - - $form->addCommandButton('update',$this->lng->txt('save')); - $form->addCommandButton('cancel',$this->lng->txt('cancel')); - - return $form; - } - - /** - * update - * - * @access public - * @return - */ - public function update() - { - $ilErr = $this->error; - $ilAccess = $this->access; - $tpl = $this->tpl; - $ilUser = $this->user; - - // #19997 - see ilObjectListGUI::insertTimingsCommand() - if( - !$ilAccess->checkAccess('write','',$this->parent_ref_id) && - !$ilAccess->checkAccess('write','',$this->getItemId())) - { - $ilErr->raiseError($this->lng->txt('permission_denied'),$ilErr->MESSAGE); - } - - $form = $this->initFormEdit(); - if($form->checkInput()) - { - $activation = new ilObjectActivation(); - $activation->read($this->getItemId()); - - if($form->getInput('availability')) - { - $this->getActivation()->setTimingType(ilObjectActivation::TIMINGS_ACTIVATION); - - $timing_start = $form->getItemByPostVar('timing_start')->getDate(); - $this->getActivation()->setTimingStart($timing_start ? $timing_start->get(IL_CAL_UNIX) : null); - - $timing_end = $form->getItemByPostVar('timing_end')->getDate(); - $this->getActivation()->setTimingEnd($timing_end ? $timing_end->get(IL_CAL_UNIX) : null); - - $this->getActivation()->toggleVisible((bool) $form->getInput('visible')); - } - elseif($this->getActivation()->getTimingType() != ilObjectActivation::TIMINGS_PRESETTING) - { - $this->getActivation()->setTimingType(ilObjectActivation::TIMINGS_DEACTIVATED); - } - - $this->getActivation()->update($this->getItemId(), $this->getParentId()); - ilUtil::sendSuccess($this->lng->txt('settings_saved'), true); - $this->ctrl->redirect($this, "edit"); - } - else - { - $form->setValuesByPost(); - $this->edit($form); - } - } - - /** - * @return bool - */ - protected function __setTabs() - { - $ilCtrl = $this->ctrl; - $ilHelp = $this->help; - - $this->tabs_gui->clearTargets(); - - $ilHelp->setScreenIdComponent("obj"); - - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $this->parent_ref_id); - $back_link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", ""); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - $this->tabs_gui->setBackTarget($this->lng->txt('btn_back'), $back_link); - - $this->tabs_gui->addTarget("timings", - $this->ctrl->getLinkTarget($this,'edit'), - "edit", get_class($this)); - - $this->ctrl->setParameterByClass('ilconditionhandlergui','item_id',$this->item_id); - $this->tabs_gui->addTarget("preconditions", - $this->ctrl->getLinkTargetByClass('ilConditionHandlerGUI','listConditions'), - "", "ilConditionHandlerGUI"); - return true; - } - - /** - * Init type of timing mode - */ - protected function initTimingMode() - { - // Check for parent course and if available read timing mode (abs | rel) - $crs_ref_id = $GLOBALS['tree']->checkForParentType( - $this->parent_ref_id, - 'crs' - ); - $crs_obj_id = ilObject::_lookupObjId($crs_ref_id); - - if($crs_obj_id) - { - $this->timing_mode = ilObjCourse::lookupTimingMode($crs_obj_id); - } - else - { - $this->timing_mode = ilCourseConstants::IL_CRS_VIEW_TIMING_ABSOLUTE; - } - } - - /** - * Init item - */ - protected function initItem() - { - $this->activation = new ilObjectActivation(); - $this->getActivation()->read($this->item_id, $this->getParentId()); - } -} -?> \ No newline at end of file + + * + * @ilCtrl_Calls ilObjectActivationGUI: ilConditionHandlerGUI + */ +class ilObjectActivationGUI +{ + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilTabsGUI + */ + protected $tabs_gui; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilTree + */ + protected $tree; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var int + */ + protected $parent_ref_id; + + /** + * @var int + */ + protected $item_id; + + /** + * @var \ilTemplate + */ + protected $tpl; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var \ilLanguage + */ + protected $lng; + + /** + * @var int|null + */ + protected $timing_mode = null; + + /** + * @var int|null + */ + protected $activation = null; + + /** + * ilObjectActivationGUI constructor. + * @param $a_ref_id + * @param $a_item_id + */ + public function __construct($a_ref_id, $a_item_id) + { + global $DIC; + + $this->tpl = $DIC->ui()->mainTemplate(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->lng->loadLanguageModule('crs'); + + $this->error = $DIC['ilErr']; + $this->tabs_gui = $DIC->tabs(); + $this->access = $DIC->access(); + $this->tree = $DIC->repositoryTree(); + $this->user = $DIC->user(); + $this->help = $DIC["ilHelp"]; + + + $this->parent_ref_id = $a_ref_id; + $this->item_id = $a_item_id; + + $this->ctrl->saveParameter($this, 'item_id'); + } + + /** + * Execute command + * @throws ilCtrlException + */ + public function executeCommand() + { + $tpl = $this->tpl; + + $this->__setTabs(); + + $cmd = $this->ctrl->getCmd(); + + // Check if item id is given and valid + if (!$this->item_id) { + ilUtil::sendFailure($this->lng->txt("crs_no_item_id_given"), true); + $this->ctrl->returnToParent($this); + } + + $tpl->getStandardTemplate(); + + switch ($this->ctrl->getNextClass($this)) { + case 'ilconditionhandlergui': + // preconditions for single course items + $this->ctrl->saveParameter($this, 'item_id', $_GET['item_id']); + $new_gui = new ilConditionHandlerGUI($this, (int) $_GET['item_id']); + $this->ctrl->forwardCommand($new_gui); + $this->tabs_gui->setTabActive('preconditions'); + break; + + default: + $this->initTimingMode(); + $this->initItem(); + $this->tabs_gui->setTabActive('timings'); + if (!$cmd) { + $cmd = 'edit'; + } + $this->$cmd(); + $this->tabs_gui->setTabActive('timings'); + break; + } + + $tpl->show(); + } + + /** + * @return int + */ + public function getItemId() + { + return $this->item_id; + } + + public function getTimingMode() + { + return $this->timing_mode; + } + + /** + * Get parent ref_id + * @return int + */ + public function getParentId() + { + return $this->parent_ref_id; + } + + /** + * Get item object + * @return ilObjectActivation + */ + public function getActivation() + { + return $this->activation; + } + + + /** + * cancel action handler + */ + public function cancel() + { + $this->ctrl->setParameterByClass('ilrepositorygui', 'ref_id', $this->parent_ref_id); + $this->ctrl->redirectByClass('ilrepositorygui'); + } + + /** + * edit timings + * + * @access public + * @return + */ + public function edit(ilPropertyFormGUI $form = null) + { + $ilErr = $this->error; + $ilAccess = $this->access; + $tpl = $this->tpl; + + // #19997 - see ilObjectListGUI::insertTimingsCommand() + if ( + !$ilAccess->checkAccess('write', '', $this->parent_ref_id) && + !$ilAccess->checkAccess('write', '', $this->getItemId())) { + $ilErr->raiseError($this->lng->txt('permission_denied'), $ilErr->MESSAGE); + } + + if (!$form instanceof ilPropertyFormGUI) { + // show edit warning if timings are on + if ($GLOBALS['tree']->checkForParentType($this->getParentId(), 'crs')) { + if ($this->getActivation()->getTimingType() == ilObjectActivation::TIMINGS_PRESETTING) { + ilUtil::sendInfo($this->lng->txt('crs_timings_warning_timing_exists')); + } + } + + $form = $this->initFormEdit(); + } + $tpl->setContent($form->getHTML()); + } + + /** + * init form edit + * + * @access protected + * @return + */ + protected function initFormEdit() + { + $tree = $this->tree; + + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this)); + + $title = ilObject::_lookupTitle(ilObject::_lookupObjId($this->getItemId())); + $form->setTitle($title . ': ' . $this->lng->txt('crs_edit_timings')); + + + $availability = new ilCheckboxInputGUI($this->lng->txt('crs_timings_availability_enabled'), 'availability'); + $availability->setValue(1); + $availability->setChecked($this->getActivation()->getTimingType() == ilObjectActivation::TIMINGS_ACTIVATION); + + $start = new ilDateTimeInputGUI($this->lng->txt('crs_timings_start'), 'timing_start'); + $start->setDate(new ilDateTime($this->getActivation()->getTimingStart(), IL_CAL_UNIX)); + $start->setShowTime(true); + $availability->addSubItem($start); + + $end = new ilDateTimeInputGUI($this->lng->txt('crs_timings_end'), 'timing_end'); + $end->setDate(new ilDateTime($this->getActivation()->getTimingEnd(), IL_CAL_UNIX)); + $end->setShowTime(true); + $availability->addSubItem($end); + + $isv = new ilCheckboxInputGUI($this->lng->txt('crs_timings_visibility_short'), 'visible'); + $isv->setInfo($this->lng->txt('crs_timings_visibility')); + $isv->setValue(1); + $isv->setChecked((bool) $this->getActivation()->enabledVisible()); + $availability->addSubItem($isv); + + + $form->addItem($availability); + + $form->addCommandButton('update', $this->lng->txt('save')); + $form->addCommandButton('cancel', $this->lng->txt('cancel')); + + return $form; + } + + /** + * update + * + * @access public + * @return + */ + public function update() + { + $ilErr = $this->error; + $ilAccess = $this->access; + $tpl = $this->tpl; + $ilUser = $this->user; + + // #19997 - see ilObjectListGUI::insertTimingsCommand() + if ( + !$ilAccess->checkAccess('write', '', $this->parent_ref_id) && + !$ilAccess->checkAccess('write', '', $this->getItemId())) { + $ilErr->raiseError($this->lng->txt('permission_denied'), $ilErr->MESSAGE); + } + + $form = $this->initFormEdit(); + if ($form->checkInput()) { + $activation = new ilObjectActivation(); + $activation->read($this->getItemId()); + + if ($form->getInput('availability')) { + $this->getActivation()->setTimingType(ilObjectActivation::TIMINGS_ACTIVATION); + + $timing_start = $form->getItemByPostVar('timing_start')->getDate(); + $this->getActivation()->setTimingStart($timing_start ? $timing_start->get(IL_CAL_UNIX) : null); + + $timing_end = $form->getItemByPostVar('timing_end')->getDate(); + $this->getActivation()->setTimingEnd($timing_end ? $timing_end->get(IL_CAL_UNIX) : null); + + $this->getActivation()->toggleVisible((bool) $form->getInput('visible')); + } elseif ($this->getActivation()->getTimingType() != ilObjectActivation::TIMINGS_PRESETTING) { + $this->getActivation()->setTimingType(ilObjectActivation::TIMINGS_DEACTIVATED); + } + + $this->getActivation()->update($this->getItemId(), $this->getParentId()); + ilUtil::sendSuccess($this->lng->txt('settings_saved'), true); + $this->ctrl->redirect($this, "edit"); + } else { + $form->setValuesByPost(); + $this->edit($form); + } + } + + /** + * @return bool + */ + protected function __setTabs() + { + $ilCtrl = $this->ctrl; + $ilHelp = $this->help; + + $this->tabs_gui->clearTargets(); + + $ilHelp->setScreenIdComponent("obj"); + + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $this->parent_ref_id); + $back_link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", ""); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + $this->tabs_gui->setBackTarget($this->lng->txt('btn_back'), $back_link); + + $this->tabs_gui->addTarget( + "timings", + $this->ctrl->getLinkTarget($this, 'edit'), + "edit", + get_class($this) + ); + + $this->ctrl->setParameterByClass('ilconditionhandlergui', 'item_id', $this->item_id); + $this->tabs_gui->addTarget( + "preconditions", + $this->ctrl->getLinkTargetByClass('ilConditionHandlerGUI', 'listConditions'), + "", + "ilConditionHandlerGUI" + ); + return true; + } + + /** + * Init type of timing mode + */ + protected function initTimingMode() + { + // Check for parent course and if available read timing mode (abs | rel) + $crs_ref_id = $GLOBALS['tree']->checkForParentType( + $this->parent_ref_id, + 'crs' + ); + $crs_obj_id = ilObject::_lookupObjId($crs_ref_id); + + if ($crs_obj_id) { + $this->timing_mode = ilObjCourse::lookupTimingMode($crs_obj_id); + } else { + $this->timing_mode = ilCourseConstants::IL_CRS_VIEW_TIMING_ABSOLUTE; + } + } + + /** + * Init item + */ + protected function initItem() + { + $this->activation = new ilObjectActivation(); + $this->getActivation()->read($this->item_id, $this->getParentId()); + } +} diff --git a/Services/Object/classes/class.ilObjectAddNewItemGUI.php b/Services/Object/classes/class.ilObjectAddNewItemGUI.php index e9b2b485a40ef73ba1f2f17116bd258b2965d74d..19cb71fe0e0c9609fd1c87f57f586d0c0a5f9608 100644 --- a/Services/Object/classes/class.ilObjectAddNewItemGUI.php +++ b/Services/Object/classes/class.ilObjectAddNewItemGUI.php @@ -1,437 +1,407 @@ - - * @version $Id: class.ilContainerGUI.php 43751 2013-07-30 10:07:45Z jluetzen $ - * - * @ingroup ServicesObject - */ -class ilObjectAddNewItemGUI -{ - /** - * @var ilLanguage - */ - protected $lng; + + * @version $Id: class.ilContainerGUI.php 43751 2013-07-30 10:07:45Z jluetzen $ + * + * @ingroup ServicesObject + */ +class ilObjectAddNewItemGUI +{ + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilSetting - */ - protected $settings; + /** + * @var ilObjectDefinition + */ + protected $obj_definition; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilSetting + */ + protected $settings; - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * @var ilToolbarGUI - */ - protected $toolbar; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilToolbarGUI + */ + protected $toolbar; - protected $mode; // [int] - protected $parent_ref_id; // [int] - protected $disabled_object_types; // [array] - protected $sub_objects; // [array] - protected $url_creation_callback; // [int] - protected $url_creation; // [string] - - /** - * Constructor - * - * @param int $a_parent_ref_id - * @return ilObjectAddNewItemGUI - */ - public function __construct($a_parent_ref_id) - { - global $DIC; + /** + * @var ilTemplate + */ + protected $tpl; - $this->lng = $DIC->language(); - $this->obj_definition = $DIC["objDefinition"]; - $this->settings = $DIC->settings(); - $this->access = $DIC->access(); - $this->ctrl = $DIC->ctrl(); - $this->toolbar = $DIC->toolbar(); - $this->tpl = $DIC["tpl"]; - $lng = $DIC->language(); - - $this->parent_ref_id = (int)$a_parent_ref_id; - $this->mode = ilObjectDefinition::MODE_REPOSITORY; - - $lng->loadLanguageModule("rep"); - $lng->loadLanguageModule("cntr"); - } - - public function setMode($a_mode) - { - $this->mode = (int)$a_mode; - } - - /** - * Set object types which may not be created - * - * @param array $a_types - */ - public function setDisabledObjectTypes(array $a_types) - { - $this->disabled_object_types = $a_types; - } - - /** - * Set after creation callback - * - * @param int $a_ref_id - */ - public function setAfterCreationCallback($a_ref_id) - { - $this->url_creation_callback = $a_ref_id; - } - - /** - * Set (custom) url for object creation - * - * @param string $a_url - */ - public function setCreationUrl($a_url) - { - $this->url_creation = $a_url; - } - - /** - * Parse creatable sub objects for personal workspace - * - * Grouping is not supported here, order is alphabetical (!) - * - * @return bool - */ - protected function parsePersonalWorkspace() - { - $objDefinition = $this->obj_definition; - $lng = $this->lng; - $ilSetting = $this->settings; - - $this->sub_objects = array(); - - $settings_map = array("blog" => "blogs", - "file" => "files", - "tstv" => "certificates", - "excv" => "certificates", - "crsv" => "certificates", - "scov" => "certificates", - "webr" => "links"); - - $subtypes = $objDefinition->getCreatableSubObjects("wfld", ilObjectDefinition::MODE_WORKSPACE); - if (count($subtypes) > 0) - { - foreach (array_keys($subtypes) as $type) - { - if (isset($settings_map[$type]) && - $ilSetting->get("disable_wsp_".$settings_map[$type])) - { - continue; - } - - $this->sub_objects[] = array("type" => "object", - "value" => $type, - "title" => $lng->txt("wsp_type_".$type)); - } - } - - $this->sub_objects = ilUtil::sortArray($this->sub_objects, "title", 1); - - return (bool)sizeof($this->sub_objects); - } - - /** - * Parse creatable sub objects for repository incl. grouping - * - * @return bool - */ - protected function parseRepository() - { - $objDefinition = $this->obj_definition; - $lng = $this->lng; - $ilAccess = $this->access; - - $this->sub_objects = array(); - - if(!is_array($this->disabled_object_types)) - { - $this->disabled_object_types = array(); - } - $this->disabled_object_types[] = "rolf"; - - $parent_type = ilObject::_lookupType($this->parent_ref_id, true); - $subtypes = $objDefinition->getCreatableSubObjects($parent_type, $this->mode, $this->parent_ref_id); - if (count($subtypes) > 0) - { - // grouping of object types - - $grp_map = $pos_group_map = array(); - - include_once("Services/Repository/classes/class.ilObjRepositorySettings.php"); - $groups = ilObjRepositorySettings::getNewItemGroups(); - - // no groups => use default - if(!$groups) - { - $default = ilObjRepositorySettings::getDefaultNewItemGrouping(); - $groups = $default["groups"]; - $grp_map = $default["items"]; - - // reset positions (9999 = "other"/unassigned) - $pos = 0; - foreach($subtypes as $item_type => $item) - { - // see ilObjectDefinition - if(substr($item_type, 0, 1) == "x") - { - $subtypes[$item_type]["pos"] = "99992000"; - } - else - { - $subtypes[$item_type]["pos"] = "9999".str_pad(++$pos, 4, "0", STR_PAD_LEFT); - } - } - - // assign default positions - foreach($default["sort"] as $item_type => $pos) - { - if(array_key_exists($item_type, $subtypes)) - { - $subtypes[$item_type]["pos"] = $pos; - } - } - - // sort by default positions - $subtypes = ilUtil::sortArray($subtypes, "pos", "asc", true, true); - } - // use group assignment - else - { - foreach(ilObjRepositorySettings::getNewItemGroupSubItems() as $grp_id => $subitems) - { - foreach($subitems as $subitem) - { - $grp_map[$subitem] = $grp_id; - } - } - } - - $group_separators = array(); - $pos_group_map[0] = $lng->txt("rep_new_item_group_other"); - $old_grp_ids = array(); - foreach($groups as $item) - { - if($item["type"] == ilObjRepositorySettings::NEW_ITEM_GROUP_TYPE_GROUP) - { - $pos_group_map[$item["id"]] = $item["title"]; - } - else if(sizeof($old_grp_ids)) - { - $group_separators[$item["id"]] = $old_grp_ids; - } - $old_grp_ids[] = $item["id"]; - } - - $current_grp = null; - foreach ($subtypes as $type => $subitem) - { - if (!in_array($type, $this->disabled_object_types)) - { - // #9950 - if ($ilAccess->checkAccess("create_".$type, "", $this->parent_ref_id, $parent_type)) - { - // if only assigned - do not add groups - if(sizeof($pos_group_map) > 1) - { - $obj_grp_id = (int)$grp_map[$type]; - if($obj_grp_id !== $current_grp) - { - // add seperator after last group? - $sdone = false; - foreach($group_separators as $idx => $spath) - { - // #11986 - all separators up to next group - if($current_grp && !in_array($obj_grp_id, $spath)) - { - // 1 only separator between groups - if(!$sdone) - { - $this->sub_objects[] = array("type" => "column_separator"); - $sdone = true; - } - unset($group_separators[$idx]); - } - } - - $title = $pos_group_map[$obj_grp_id]; - - $this->sub_objects[] = array("type" => "group", - "title" => $title); - - $current_grp = $obj_grp_id; - } - } - - if ($subitem["plugin"]) - { - include_once("./Services/Component/classes/class.ilPlugin.php"); - $title = ilObjectPlugin::lookupTxtById($type, "obj_".$type); - } - else - { - // #13088 - $title = $lng->txt("obj_".$type); - } - - $this->sub_objects[] = array("type" => "object", - "value" => $type, - "title" => $title); - } - } - } - } - - return (bool)sizeof($this->sub_objects); - } - - /** - * Get rendered html of sub object list - * - * @return string - */ - protected function getHTML() - { - $ilCtrl = $this->ctrl; - - if($this->mode != ilObjectDefinition::MODE_WORKSPACE && !isset($this->url_creation)) - { - $base_url = "ilias.php?baseClass=ilRepositoryGUI&ref_id=".$this->parent_ref_id."&cmd=create"; - } - else - { - $base_url = $this->url_creation; - } - $base_url = $ilCtrl->appendRequestTokenParameterString($base_url); - - if($this->url_creation_callback) - { - $base_url .= "&crtcb=".$this->url_creation_callback; - } - - include_once("./Services/UIComponent/GroupedList/classes/class.ilGroupedListGUI.php"); - $gl = new ilGroupedListGUI(); - $gl->setAsDropDown(true, true); - - foreach ($this->sub_objects as $item) - { - switch($item["type"]) - { - case "column_separator": - $gl->nextColumn(); - break; - - /* - case "separator": - $gl->addSeparator(); - break; - */ - - case "group": - $gl->addGroupHeader($item["title"]); - break; - - case "object": - $type = $item["value"]; - - $path = ilObject::_getIcon('', 'tiny', $type); - $icon = ($path != "") - ? ilUtil::img($path)." " - : ""; - - $url = $base_url . "&new_type=".$type; - - $ttip = ilHelp::getObjCreationTooltipText($type); - - $gl->addEntry($icon.$item["title"], $url, "_top", "", "", - $type, $ttip, "bottom center", "top center", false); - - break; - } - } - $this->gl = $gl; - - return $gl->getHTML(); - } - - /** - * Add new item selection to current page incl. toolbar (trigger) and overlay - */ - public function render() - { - $ilToolbar = $this->toolbar; - $tpl = $this->tpl; - $lng = $this->lng; - - if($this->mode == ilObjectDefinition::MODE_WORKSPACE) - { - if (!$this->parsePersonalWorkspace()) - { - return; - } - } - else if(!$this->parseRepository()) - { - return; - } - - $ov_id = "il_add_new_item_ov"; - $ov_trigger_id = $ov_id."_tr"; - - - include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"); - $adv = new ilAdvancedSelectionListGUI(); - $adv->setListTitle($lng->txt("cntr_add_new_item")); - $this->getHTML(); - $adv->setGroupedList($this->gl); - $adv->setStyle(ilAdvancedSelectionListGUI::STYLE_EMPH); - $tpl->setVariable("SELECT_OBJTYPE_REPOS", $adv->getHTML()); - //$ilToolbar->addDropDown($lng->txt("cntr_add_new_item"), $this->getHTML()); - - return; - - // toolbar - include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; - $button = ilLinkButton::getInstance(); - $button->setId($ov_trigger_id); - $button->setCaption("cntr_add_new_item"); - $button->setPrimary(true); - $ilToolbar->addButtonInstance($button); - - // css? - $tpl->setVariable("SELECT_OBJTYPE_REPOS", - ''); - } -} - -?> \ No newline at end of file + protected $mode; // [int] + protected $parent_ref_id; // [int] + protected $disabled_object_types; // [array] + protected $sub_objects; // [array] + protected $url_creation_callback; // [int] + protected $url_creation; // [string] + + /** + * Constructor + * + * @param int $a_parent_ref_id + * @return ilObjectAddNewItemGUI + */ + public function __construct($a_parent_ref_id) + { + global $DIC; + + $this->lng = $DIC->language(); + $this->obj_definition = $DIC["objDefinition"]; + $this->settings = $DIC->settings(); + $this->access = $DIC->access(); + $this->ctrl = $DIC->ctrl(); + $this->toolbar = $DIC->toolbar(); + $this->tpl = $DIC["tpl"]; + $lng = $DIC->language(); + + $this->parent_ref_id = (int) $a_parent_ref_id; + $this->mode = ilObjectDefinition::MODE_REPOSITORY; + + $lng->loadLanguageModule("rep"); + $lng->loadLanguageModule("cntr"); + } + + public function setMode($a_mode) + { + $this->mode = (int) $a_mode; + } + + /** + * Set object types which may not be created + * + * @param array $a_types + */ + public function setDisabledObjectTypes(array $a_types) + { + $this->disabled_object_types = $a_types; + } + + /** + * Set after creation callback + * + * @param int $a_ref_id + */ + public function setAfterCreationCallback($a_ref_id) + { + $this->url_creation_callback = $a_ref_id; + } + + /** + * Set (custom) url for object creation + * + * @param string $a_url + */ + public function setCreationUrl($a_url) + { + $this->url_creation = $a_url; + } + + /** + * Parse creatable sub objects for personal workspace + * + * Grouping is not supported here, order is alphabetical (!) + * + * @return bool + */ + protected function parsePersonalWorkspace() + { + $objDefinition = $this->obj_definition; + $lng = $this->lng; + $ilSetting = $this->settings; + + $this->sub_objects = array(); + + $settings_map = array("blog" => "blogs", + "file" => "files", + "tstv" => "certificates", + "excv" => "certificates", + "crsv" => "certificates", + "scov" => "certificates", + "webr" => "links"); + + $subtypes = $objDefinition->getCreatableSubObjects("wfld", ilObjectDefinition::MODE_WORKSPACE); + if (count($subtypes) > 0) { + foreach (array_keys($subtypes) as $type) { + if (isset($settings_map[$type]) && + $ilSetting->get("disable_wsp_" . $settings_map[$type])) { + continue; + } + + $this->sub_objects[] = array("type" => "object", + "value" => $type, + "title" => $lng->txt("wsp_type_" . $type)); + } + } + + $this->sub_objects = ilUtil::sortArray($this->sub_objects, "title", 1); + + return (bool) sizeof($this->sub_objects); + } + + /** + * Parse creatable sub objects for repository incl. grouping + * + * @return bool + */ + protected function parseRepository() + { + $objDefinition = $this->obj_definition; + $lng = $this->lng; + $ilAccess = $this->access; + + $this->sub_objects = array(); + + if (!is_array($this->disabled_object_types)) { + $this->disabled_object_types = array(); + } + $this->disabled_object_types[] = "rolf"; + + $parent_type = ilObject::_lookupType($this->parent_ref_id, true); + $subtypes = $objDefinition->getCreatableSubObjects($parent_type, $this->mode, $this->parent_ref_id); + if (count($subtypes) > 0) { + // grouping of object types + + $grp_map = $pos_group_map = array(); + + include_once("Services/Repository/classes/class.ilObjRepositorySettings.php"); + $groups = ilObjRepositorySettings::getNewItemGroups(); + + // no groups => use default + if (!$groups) { + $default = ilObjRepositorySettings::getDefaultNewItemGrouping(); + $groups = $default["groups"]; + $grp_map = $default["items"]; + + // reset positions (9999 = "other"/unassigned) + $pos = 0; + foreach ($subtypes as $item_type => $item) { + // see ilObjectDefinition + if (substr($item_type, 0, 1) == "x") { + $subtypes[$item_type]["pos"] = "99992000"; + } else { + $subtypes[$item_type]["pos"] = "9999" . str_pad(++$pos, 4, "0", STR_PAD_LEFT); + } + } + + // assign default positions + foreach ($default["sort"] as $item_type => $pos) { + if (array_key_exists($item_type, $subtypes)) { + $subtypes[$item_type]["pos"] = $pos; + } + } + + // sort by default positions + $subtypes = ilUtil::sortArray($subtypes, "pos", "asc", true, true); + } + // use group assignment + else { + foreach (ilObjRepositorySettings::getNewItemGroupSubItems() as $grp_id => $subitems) { + foreach ($subitems as $subitem) { + $grp_map[$subitem] = $grp_id; + } + } + } + + $group_separators = array(); + $pos_group_map[0] = $lng->txt("rep_new_item_group_other"); + $old_grp_ids = array(); + foreach ($groups as $item) { + if ($item["type"] == ilObjRepositorySettings::NEW_ITEM_GROUP_TYPE_GROUP) { + $pos_group_map[$item["id"]] = $item["title"]; + } elseif (sizeof($old_grp_ids)) { + $group_separators[$item["id"]] = $old_grp_ids; + } + $old_grp_ids[] = $item["id"]; + } + + $current_grp = null; + foreach ($subtypes as $type => $subitem) { + if (!in_array($type, $this->disabled_object_types)) { + // #9950 + if ($ilAccess->checkAccess("create_" . $type, "", $this->parent_ref_id, $parent_type)) { + // if only assigned - do not add groups + if (sizeof($pos_group_map) > 1) { + $obj_grp_id = (int) $grp_map[$type]; + if ($obj_grp_id !== $current_grp) { + // add seperator after last group? + $sdone = false; + foreach ($group_separators as $idx => $spath) { + // #11986 - all separators up to next group + if ($current_grp && !in_array($obj_grp_id, $spath)) { + // 1 only separator between groups + if (!$sdone) { + $this->sub_objects[] = array("type" => "column_separator"); + $sdone = true; + } + unset($group_separators[$idx]); + } + } + + $title = $pos_group_map[$obj_grp_id]; + + $this->sub_objects[] = array("type" => "group", + "title" => $title); + + $current_grp = $obj_grp_id; + } + } + + if ($subitem["plugin"]) { + include_once("./Services/Component/classes/class.ilPlugin.php"); + $title = ilObjectPlugin::lookupTxtById($type, "obj_" . $type); + } else { + // #13088 + $title = $lng->txt("obj_" . $type); + } + + $this->sub_objects[] = array("type" => "object", + "value" => $type, + "title" => $title); + } + } + } + } + + return (bool) sizeof($this->sub_objects); + } + + /** + * Get rendered html of sub object list + * + * @return string + */ + protected function getHTML() + { + $ilCtrl = $this->ctrl; + + if ($this->mode != ilObjectDefinition::MODE_WORKSPACE && !isset($this->url_creation)) { + $base_url = "ilias.php?baseClass=ilRepositoryGUI&ref_id=" . $this->parent_ref_id . "&cmd=create"; + } else { + $base_url = $this->url_creation; + } + $base_url = $ilCtrl->appendRequestTokenParameterString($base_url); + + if ($this->url_creation_callback) { + $base_url .= "&crtcb=" . $this->url_creation_callback; + } + + include_once("./Services/UIComponent/GroupedList/classes/class.ilGroupedListGUI.php"); + $gl = new ilGroupedListGUI(); + $gl->setAsDropDown(true, true); + + foreach ($this->sub_objects as $item) { + switch ($item["type"]) { + case "column_separator": + $gl->nextColumn(); + break; + + /* + case "separator": + $gl->addSeparator(); + break; + */ + + case "group": + $gl->addGroupHeader($item["title"]); + break; + + case "object": + $type = $item["value"]; + + $path = ilObject::_getIcon('', 'tiny', $type); + $icon = ($path != "") + ? ilUtil::img($path) . " " + : ""; + + $url = $base_url . "&new_type=" . $type; + + $ttip = ilHelp::getObjCreationTooltipText($type); + + $gl->addEntry( + $icon . $item["title"], + $url, + "_top", + "", + "", + $type, + $ttip, + "bottom center", + "top center", + false + ); + + break; + } + } + $this->gl = $gl; + + return $gl->getHTML(); + } + + /** + * Add new item selection to current page incl. toolbar (trigger) and overlay + */ + public function render() + { + $ilToolbar = $this->toolbar; + $tpl = $this->tpl; + $lng = $this->lng; + + if ($this->mode == ilObjectDefinition::MODE_WORKSPACE) { + if (!$this->parsePersonalWorkspace()) { + return; + } + } elseif (!$this->parseRepository()) { + return; + } + + $ov_id = "il_add_new_item_ov"; + $ov_trigger_id = $ov_id . "_tr"; + + + include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"); + $adv = new ilAdvancedSelectionListGUI(); + $adv->setListTitle($lng->txt("cntr_add_new_item")); + $this->getHTML(); + $adv->setGroupedList($this->gl); + $adv->setStyle(ilAdvancedSelectionListGUI::STYLE_EMPH); + $tpl->setVariable("SELECT_OBJTYPE_REPOS", $adv->getHTML()); + //$ilToolbar->addDropDown($lng->txt("cntr_add_new_item"), $this->getHTML()); + + return; + + // toolbar + include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php"; + $button = ilLinkButton::getInstance(); + $button->setId($ov_trigger_id); + $button->setCaption("cntr_add_new_item"); + $button->setPrimary(true); + $ilToolbar->addButtonInstance($button); + + // css? + $tpl->setVariable( + "SELECT_OBJTYPE_REPOS", + '' + ); + } +} diff --git a/Services/Object/classes/class.ilObjectAppEventListener.php b/Services/Object/classes/class.ilObjectAppEventListener.php index 48d4fe007766480b9b71f4b1233cd99061d0f1f5..69a6e71502b5c2ac6e88a24e2b9263ed907c05fb 100644 --- a/Services/Object/classes/class.ilObjectAppEventListener.php +++ b/Services/Object/classes/class.ilObjectAppEventListener.php @@ -7,18 +7,18 @@ */ class ilObjectAppEventListener implements \ilAppEventListener { - /** - * @inheritdoc - */ - public static function handleEvent($a_component, $a_event, $a_parameter) - { - global $DIC; + /** + * @inheritdoc + */ + public static function handleEvent($a_component, $a_event, $a_parameter) + { + global $DIC; - if ('Services/Object' === $a_component && 'beforeDeletion' === $a_event) { - /** @var \ilObjectCustomIconFactory $customIconFactory */ - $customIconFactory = $DIC['object.customicons.factory']; - $customIcon = $customIconFactory->getByObjId($a_parameter['object']->getId(), $a_parameter['object']->getType()); - $customIcon->delete(); - } - } -} \ No newline at end of file + if ('Services/Object' === $a_component && 'beforeDeletion' === $a_event) { + /** @var \ilObjectCustomIconFactory $customIconFactory */ + $customIconFactory = $DIC['object.customicons.factory']; + $customIcon = $customIconFactory->getByObjId($a_parameter['object']->getId(), $a_parameter['object']->getType()); + $customIcon->delete(); + } + } +} diff --git a/Services/Object/classes/class.ilObjectCopyCourseGroupSelectionTableGUI.php b/Services/Object/classes/class.ilObjectCopyCourseGroupSelectionTableGUI.php index 4be4bd450b06fc90d2d15200e7002f7229a03850..bb312ff639e4fcea5dc9d6985d8ff2692b727542 100644 --- a/Services/Object/classes/class.ilObjectCopyCourseGroupSelectionTableGUI.php +++ b/Services/Object/classes/class.ilObjectCopyCourseGroupSelectionTableGUI.php @@ -5,71 +5,69 @@ include_once './Services/Object/classes/class.ilObjectTableGUI.php'; /** * GUI class for the workflow of copying objects - * + * * @author Stefan Meyer * @version $Id$ - * + * * @ingroup ServicesObject */ class ilObjectCopyCourseGroupSelectionTableGUI extends ilObjectTableGUI { - /** - * Set objects - * @param type $a_obj_ids - */ - public function setObjects($a_obj_ids) - { - $ref_ids = array(); - foreach($a_obj_ids as $obj_id) - { - $all_ref_ids = ilObject::_getAllReferences($obj_id); - $ref_ids[] = end($all_ref_ids); - } - return parent::setObjects($ref_ids); - } - - /** - * Init table - */ - public function init() - { - global $DIC; + /** + * Set objects + * @param type $a_obj_ids + */ + public function setObjects($a_obj_ids) + { + $ref_ids = array(); + foreach ($a_obj_ids as $obj_id) { + $all_ref_ids = ilObject::_getAllReferences($obj_id); + $ref_ids[] = end($all_ref_ids); + } + return parent::setObjects($ref_ids); + } + + /** + * Init table + */ + public function init() + { + global $DIC; - $ilCtrl = $DIC->ctrl(); + $ilCtrl = $DIC->ctrl(); - $this->enableRowSelectionInput(TRUE); - - parent::init(); - - $this->setFormAction($ilCtrl->getFormAction($this->getParentObject())); - - $this->enableObjectPath(TRUE); - $this->addCommandButton('saveSourceMembership',$this->lng->txt('btn_next')); - $this->addCommandButton('cancel',$this->lng->txt('cancel')); - } - - /** - * Fill row selection input - * @param type $set - */ - public function fillRowSelectionInput($set) - { - $this->tpl->setCurrentBlock('row_selection_input'); - $this->tpl->setVariable('OBJ_INPUT_TYPE','radio'); - $this->tpl->setVariable('OBJ_INPUT_NAME','source'); - $this->tpl->setVariable('OBJ_INPUT_VALUE',$set['ref_id']); - } - - /** - * Customize path - * @param \ilPathGUI $path - * @return \ilPathGUI - */ - public function customizePath(\ilPathGUI $path) - { - $path->setUseImages(TRUE); - $path->enableTextOnly(FALSE); - return $path; - } + $this->enableRowSelectionInput(true); + + parent::init(); + + $this->setFormAction($ilCtrl->getFormAction($this->getParentObject())); + + $this->enableObjectPath(true); + $this->addCommandButton('saveSourceMembership', $this->lng->txt('btn_next')); + $this->addCommandButton('cancel', $this->lng->txt('cancel')); + } + + /** + * Fill row selection input + * @param type $set + */ + public function fillRowSelectionInput($set) + { + $this->tpl->setCurrentBlock('row_selection_input'); + $this->tpl->setVariable('OBJ_INPUT_TYPE', 'radio'); + $this->tpl->setVariable('OBJ_INPUT_NAME', 'source'); + $this->tpl->setVariable('OBJ_INPUT_VALUE', $set['ref_id']); + } + + /** + * Customize path + * @param \ilPathGUI $path + * @return \ilPathGUI + */ + public function customizePath(\ilPathGUI $path) + { + $path->setUseImages(true); + $path->enableTextOnly(false); + return $path; + } } -?> diff --git a/Services/Object/classes/class.ilObjectCopyGUI.php b/Services/Object/classes/class.ilObjectCopyGUI.php index 6ee78e5ac043f4c44b9959727bfbf0de82d8fc2a..cf02cc84dbe38bc1922e310f0bf22ea0fe6182cd 100644 --- a/Services/Object/classes/class.ilObjectCopyGUI.php +++ b/Services/Object/classes/class.ilObjectCopyGUI.php @@ -3,1385 +3,1295 @@ /** * GUI class for the workflow of copying objects - * + * * @author Stefan Meyer * @author Stefan Hecken * @version $Id$ - * - * @ilCtrl_Calls ilObjectCopyGUI: + * + * @ilCtrl_Calls ilObjectCopyGUI: * * @ingroup ServicesObject */ class ilObjectCopyGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTree - */ - protected $tree; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilObjectDefinition - */ - protected $obj_definition; - - /** - * @var ilObjectDataCache - */ - protected $obj_data_cache; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilRbacReview - */ - protected $rbacreview; - - const SOURCE_SELECTION = 1; - const TARGET_SELECTION = 2; - const SEARCH_SOURCE = 3; - - const SUBMODE_COMPLETE = 1; - const SUBMODE_CONTENT_ONLY = 2; - - // tabs - const TAB_SELECTION_TARGET_TREE = 1; - const TAB_SELECTION_SOURCE_TREE = 2; - const TAB_SELECTION_MEMBERSHIP = 3; - - // group selection of source or target - const TAB_GROUP_SC_SELECTION = 1; - - - private $mode = 0; - private $sub_mode = self::SUBMODE_COMPLETE; - - private $lng; - - private $parent_obj = null; - - private $type = ''; - - private $sources = array(); - - // begin-patch multi copy - private $targets = array(); - private $targets_copy_id = array(); - // end-patch multi copy - - /** - * @var ilLogger - */ - private $log = null; - - - /** - * Constructor - * @return - */ - public function __construct($a_parent_gui) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->tree = $DIC->repositoryTree(); - $this->tabs = $DIC->tabs(); - $this->toolbar = $DIC->toolbar(); - $this->tpl = $DIC["tpl"]; - $this->obj_definition = $DIC["objDefinition"]; - $this->obj_data_cache = $DIC["ilObjDataCache"]; - $this->access = $DIC->access(); - $this->error = $DIC["ilErr"]; - $this->rbacsystem = $DIC->rbac()->system(); - $this->user = $DIC->user(); - $this->rbacreview = $DIC->rbac()->review(); - $this->log = $DIC["ilLog"]; - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->lng = $lng; - $this->lng->loadLanguageModule('search'); - $this->lng->loadLanguageModule('obj'); - - $this->parent_obj = $a_parent_gui; - - $this->log = ilLoggerFactory::getLogger('obj'); - } - - /** - * Control class handling - * @return - */ - public function executeCommand() - { - $ilCtrl = $this->ctrl; - - $this->init(); - $this->initTabs(); - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd(); - - switch($next_class) - { - default: - $this->$cmd(); - break; - } - } - - /** - * Init return, mode - * @return - */ - protected function init() - { - $ilCtrl = $this->ctrl; - - if((int) $_REQUEST['smode']) - { - $this->setSubMode((int) $_REQUEST['smode']); - $ilCtrl->setParameter($this,'smode',$this->getSubMode()); - ilLoggerFactory::getLogger('obj')->debug('Submode is: '. $this->getSubMode()); - } - - // save sources - if($_REQUEST['source_ids']) - { - $this->setSource(explode('_',$_REQUEST['source_ids'])); - $ilCtrl->setParameter($this,'source_ids', implode('_', $this->getSources())); - ilLoggerFactory::getLogger('obj')->debug('Multiple sources: ' . implode('_',$this->getSources())); - } - if($_REQUEST['source_id']) - { - $this->setSource(array((int) $_REQUEST['source_id'])); - $ilCtrl->setParameter($this,'source_ids', implode('_', $this->getSources())); - ilLoggerFactory::getLogger('obj')->debug('source_id is set: '. implode('_',$this->getSources())); - } - if($this->getFirstSource()) - { - $this->setType( - ilObject::_lookupType(ilObject::_lookupObjId($this->getFirstSource())) - ); - } - - // creation screen: copy section - if($_REQUEST['new_type']) - { - $this->setMode(self::SEARCH_SOURCE); - $this->setType($_REQUEST['new_type']); - $this->setTarget((int) $_GET['ref_id']); - - $ilCtrl->setParameter($this, 'new_type', $this->getType()); - $ilCtrl->setParameterByClass(get_class($this->getParentObject()),'new_type', $this->getType()); - $ilCtrl->setParameterByClass(get_class($this->getParentObject()),'cpfl', 1); - $ilCtrl->setReturnByClass(get_class($this->getParentObject()),'create'); - - ilLoggerFactory::getLogger('obj')->debug('Copy from object creation for type: '. $this->getType()); - return TRUE; - } - // adopt content, and others? - elseif($_REQUEST['selectMode'] == self::SOURCE_SELECTION) - { - $this->setMode(self::SOURCE_SELECTION); - - $ilCtrl->setParameterByClass(get_class($this->parent_obj), 'selectMode', self::SOURCE_SELECTION); - $this->setTarget((int) $_GET['ref_id']); - $ilCtrl->setReturnByClass(get_class($this->parent_obj), ''); - - ilLoggerFactory::getLogger('obj')->debug('Source selection mode. Target is: '. $this->getFirstTarget()); - } - elseif($_REQUEST['selectMode'] == self::TARGET_SELECTION) - { - $this->setMode(self::TARGET_SELECTION); - $ilCtrl->setReturnByClass(get_class($this->parent_obj),''); - ilLoggerFactory::getLogger('obj')->debug('Target selection mode.'); - } - - - // save targets - if($_REQUEST['target_ids']) - { - $this->setTargets(explode('_',$_REQUEST['target_ids'])); - ilLoggerFactory::getLogger('obj')->debug('targets are: '. print_r($this->getTargets(),TRUE)); - } - - } - - /** - * Init tabs - * General - */ - protected function initTabs() - { - $lng = $this->lng; - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - - $lng->loadLanguageModule('cntr'); - $ilTabs->clearTargets(); - $ilTabs->setBackTarget( - $lng->txt('tab_back_to_repository'), - $ilCtrl->getParentReturn($this->parent_obj) - ); - } - - /** - * Set tabs - * @param type $a_tab_group - * @param type $a_active_tab - */ - protected function setTabs($a_tab_group, $a_active_tab) - { - $lng = $this->lng; - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - - if($a_tab_group == self::TAB_GROUP_SC_SELECTION) - { - if($this->getSubMode() == self::SUBMODE_CONTENT_ONLY) - { - if($this->getMode() == self::SOURCE_SELECTION) - { - $ilTabs->addTab( - self::TAB_SELECTION_SOURCE_TREE, - $lng->txt('cntr_copy_repo_tree'), - $ilCtrl->getLinkTarget($this,'initSourceSelection') - ); - $ilTabs->addTab( - self::TAB_SELECTION_MEMBERSHIP, - $lng->txt('cntr_copy_crs_grp'), - $ilCtrl->getLinkTarget($this,'showSourceSelectionMembership') - ); - } - } - } - $ilTabs->activateTab($a_active_tab); - } - - - /** - * Adopt content (crs in crs, grp in grp, crs in grp or grp in crs) - * @return type - */ - protected function adoptContent() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameter($this,'smode',self::SUBMODE_CONTENT_ONLY); - $ilCtrl->setParameter($this,'selectMode',self::SOURCE_SELECTION); - - - $this->setSubMode(self::SUBMODE_CONTENT_ONLY); - $this->setMode(self::SOURCE_SELECTION); - $this->setTarget((int) $_GET['ref_id']); - - - return $this->initSourceSelection(); - } - - /** - * Init copy from repository/search list commands - * @return - */ - protected function initTargetSelection() - { - $ilCtrl = $this->ctrl; - $tree = $this->tree; - $ilCtrl->setParameter($this, 'selectMode', self::TARGET_SELECTION); - // empty session on init - $_SESSION['paste_copy_repexpand'] = array(); - - // copy opened nodes from repository explorer - $_SESSION['paste_copy_repexpand'] = is_array($_SESSION['repexpand']) ? $_SESSION['repexpand'] : array(); - - // begin-patch mc - $this->setTargets(array()); - // cognos-blu-patch: end - - // open current position - - foreach($this->getSources() as $source_id) - { - if($source_id) - { - $path = $tree->getPathId($source_id); - foreach((array) $path as $node_id) - { - if(!in_array($node_id, $_SESSION['paste_copy_repexpand'])) - { - $_SESSION['paste_copy_repexpand'][] = $node_id; - } - } - - } - } - - $ilCtrl->setReturnByClass(get_class($this->parent_obj),''); - $this->showTargetSelectionTree(); - } - - /** - * Init source selection - * @return - */ - protected function initSourceSelection() - { - $ilCtrl = $this->ctrl; - $tree = $this->tree; - - // empty session on init - $_SESSION['paste_copy_repexpand'] = array(); - - // copy opened nodes from repository explorer - $_SESSION['paste_copy_repexpand'] = is_array($_SESSION['repexpand']) ? $_SESSION['repexpand'] : array(); - - $this->setTabs(self::TAB_GROUP_SC_SELECTION, self::TAB_SELECTION_SOURCE_TREE); - - - // open current position - // begin-patch mc - foreach($this->getTargets() as $target_ref_id) - { - $path = $tree->getPathId($target_ref_id); - foreach((array) $path as $node_id) - { - if(!in_array($node_id, $_SESSION['paste_copy_repexpand'])) - { - $_SESSION['paste_copy_repexpand'][] = $node_id; - } - } - } - // end-patch multi copy - $ilCtrl->setReturnByClass(get_class($this->parent_obj),''); - $this->showSourceSelectionTree(); - } - - - /** - * show target selection membership - */ - protected function showSourceSelectionMembership() - { - $user = $this->user; - $tpl = $this->tpl; - - ilUtil::sendInfo($this->lng->txt('msg_copy_clipboard_source')); - $this->setTabs(self::TAB_GROUP_SC_SELECTION, self::TAB_SELECTION_MEMBERSHIP); - - include_once './Services/Object/classes/class.ilObjectCopyCourseGroupSelectionTableGUI.php'; - $cgs = new ilObjectCopyCourseGroupSelectionTableGUI($this, 'showSourceSelectionMembership','copy_selection_membership'); - $cgs->init(); - $cgs->setObjects( - array_merge( - ilParticipants::_getMembershipByType($user->getId(), 'crs', FALSE), - ilParticipants::_getMembershipByType($user->getId(), 'grp', FALSE) - ) - ); - $cgs->parse(); - - $tpl->setContent($cgs->getHTML()); - } - - - /** - * Show target selection - */ - public function showTargetSelectionTree() - { - $ilTabs = $this->tabs; - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - $tree = $this->tree; - $tpl = $this->tpl; - $objDefinition = $this->obj_definition; - $lng = $this->lng; - - $this->tpl = $tpl; - - if($objDefinition->isContainer($this->getType())) - { - ilUtil::sendInfo($this->lng->txt('msg_copy_clipboard_container')); - } - else - { - ilUtil::sendInfo($this->lng->txt('msg_copy_clipboard')); - } - - // - include_once("./Services/Repository/classes/class.ilRepositorySelectorExplorerGUI.php"); - $exp = new ilRepositorySelectorExplorerGUI($this, "showTargetSelectionTree"); - $exp->setTypeWhiteList(array("root", "cat", "grp", "crs", "fold", "lso")); - $exp->setSelectMode("target", TRUE); - if ($exp->handleCommand()) - { - return; - } - $output = $exp->getHTML(); - - // toolbars - $t = new ilToolbarGUI(); - $t->setFormAction($ilCtrl->getFormAction($this, "saveTarget")); - if($objDefinition->isContainer($this->getType())) - { - $t->addFormButton($lng->txt("btn_next"), "saveTarget"); - } - else - { - $t->addFormButton($lng->txt("paste"), "saveTarget"); - } - $t->addSeparator(); - $t->addFormButton($lng->txt("obj_insert_into_clipboard"), "keepObjectsInClipboard"); - $t->addFormButton($lng->txt("cancel"), "cancel"); - $t->setCloseFormTag(false); - $t->setLeadingImage(ilUtil::getImagePath("arrow_upright.svg"), " "); - $output = $t->getHTML().$output; - $t->setLeadingImage(ilUtil::getImagePath("arrow_downright.svg"), " "); - $t->setCloseFormTag(true); - $t->setOpenFormTag(false); - $output.= "
                  ".$t->getHTML(); - - $this->tpl->setContent($output); - - return; - } - - /** - * Show target selection - */ - public function showSourceSelectionTree() - { - $ilTabs = $this->tabs; - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - $tree = $this->tree; - $tpl = $this->tpl; - $objDefinition = $this->obj_definition; - - $this->tpl = $tpl; - $this->tpl->addBlockfile('ADM_CONTENT', 'adm_content', 'tpl.paste_into_multiple_objects.html', - "Services/Object"); - - ilUtil::sendInfo($this->lng->txt('msg_copy_clipboard_source')); - include_once './Services/Object/classes/class.ilPasteIntoMultipleItemsExplorer.php'; - $exp = new ilPasteIntoMultipleItemsExplorer( - ilPasteIntoMultipleItemsExplorer::SEL_TYPE_RADIO, - 'ilias.php?baseClass=ilRepositoryGUI&cmd=goto', 'paste_copy_repexpand'); - $exp->setRequiredFormItemPermission('visible,read,copy'); - - $ilCtrl->setParameter($this, 'selectMode', self::SOURCE_SELECTION); - $exp->setExpandTarget($ilCtrl->getLinkTarget($this, 'showSourceSelectionTree')); - $exp->setTargetGet('ref_id'); - $exp->setPostVar('source'); - $exp->setCheckedItems($this->getSources()); - - // Filter to container - foreach(array('cat','root','fold') as $container) - { - $exp->removeFormItemForType($container); - } - - - if($_GET['paste_copy_repexpand'] == '') - { - $expanded = $tree->readRootId(); - } - else - { - $expanded = $_GET['paste_copy_repexpand']; - } - - $this->tpl->setVariable('FORM_TARGET', '_self'); - $this->tpl->setVariable('FORM_ACTION', $ilCtrl->getFormAction($this, 'copySelection')); - - $exp->setExpand($expanded); - // build html-output - $exp->setOutput(0); - $output = $exp->getOutput(); - - $this->tpl->setVariable('OBJECT_TREE', $output); - - $this->tpl->setVariable('CMD_SUBMIT', 'saveSource'); - $this->tpl->setVariable('TXT_SUBMIT', $this->lng->txt('btn_next')); - - $ilToolbar->addButton($this->lng->txt('cancel'), $ilCtrl->getLinkTarget($this,'cancel')); - } - - /** - * Save target selection - * @return - */ - protected function saveTarget() - { - $objDefinition = $this->obj_definition; - $tree = $this->tree; - $ilCtrl = $this->ctrl; - - - // begin-patch mc - if(is_array($_REQUEST['target']) and $_REQUEST['target']) - { - $this->setTargets($_REQUEST['target']); - $ilCtrl->setParameter($this,'target_ids', implode('_', $this->getTargets())); - } - // paste from clipboard - elseif((int) $_REQUEST['target']) - { - $this->setTarget($_REQUEST['target']); - $ilCtrl->setParameter($this,'target_ids', implode('_', $this->getTargets())); - } - // end-patch multi copy - else - { - $ilCtrl->setParameter($this, 'selectMode', self::TARGET_SELECTION); - ilUtil::sendFailure($this->lng->txt('select_one')); - $this->showTargetSelectionTree(); - return false; - } - - // validate allowed subtypes - foreach($this->getSources() as $source_ref_id) - { - foreach((array) $this->getTargets() as $target_ref_id) - { - $target_type = ilObject::_lookupType($target_ref_id, TRUE); - $target_class_name = ilObjectFactory::getClassByType($target_type); - $target_object = new $target_class_name($target_ref_id); - $possible_subtypes = $target_object->getPossibleSubObjects(); - - $source_type = ilObject::_lookupType($source_ref_id, TRUE); - - if(!array_key_exists($source_type, (array) $possible_subtypes)) - { - ilUtil::sendFailure( - sprintf( - $this->lng->txt('msg_obj_may_not_contain_objects_of_type'), - $this->lng->txt('obj_'.$target_type), - $this->lng->txt('obj_'.$source_type)) - ); - $this->showTargetSelectionTree(); - return FALSE; - } - } - } - - if(count($this->getSources()) == 1 && $objDefinition->isContainer($this->getType())) - { - // check, if object should be copied into itself - // begin-patch mc - $is_child = array(); - foreach($this->getTargets() as $target_ref_id) - { - if ($tree->isGrandChild($this->getFirstSource(), $target_ref_id)) - { - $is_child[] = ilObject::_lookupTitle(ilObject::_lookupObjId($this->getFirstSource())); - } - if ($this->getFirstSource() == $target_ref_id) - { - $is_child[] = ilObject::_lookupTitle(ilObject::_lookupObjId($this->getFirstSource())); - } - } - // end-patch multi copy - if (count($is_child) > 0) - { - ilUtil::sendFailure($this->lng->txt("msg_not_in_itself")." ".implode(',',$is_child)); - $this->showTargetSelectionTree(); - return false; - } - - $this->showItemSelection(); - } - else - { - if(count($this->getSources()) == 1) - { - $this->copySingleObject(); - } - else - { - $this->copyMultipleNonContainer($this->getSources()); - } - } - } - - /** - * set copy mode - * @param int $a_mode - * @return - */ - public function setMode($a_mode) - { - $this->mode = $a_mode; - } - - /** - * get copy mode - * @return - */ - public function getMode() - { - return $this->mode; - } - - public function setSubMode($a_mode) - { - $this->sub_mode = $a_mode; - } - - public function getSubMode() - { - return $this->sub_mode; - } - - /** - * Get parent gui object - * @return object parent gui - */ - public function getParentObject() - { - return $this->parent_obj; - } - - /** - * Returns $type. - * - * @see ilObjectCopyGUI::$type - */ - public function getType() - { - return $this->type; - } - - /** - * Sets $type. - * - * @param object $type - * @see ilObjectCopyGUI::$type - */ - public function setType($type) - { - $this->type = $type; - } - - /** - * Set source id - * @param array $a_source_id - * @return - */ - public function setSource(array $a_source_ids) - { - $this->sources = $a_source_ids; - } - - /** - * Get sources - * @return array - */ - public function getSources() - { - return (array) $this->sources; - } - - public function getFirstSource() - { - if(count($this->sources)) - { - return $this->sources[0]; - } - return 0; - } - - // begin-patch mc - - /** - * Set single object target - * @param type $a_ref_id - */ - public function setTarget($a_ref_id) - { - $this->setTargets(array($a_ref_id)); - } - - - /** - * Set target id - * @param int $a_target - * @return - */ - public function setTargets(array $a_target) - { - $this->targets = $a_target; - } - - /** - * Get copy target - * @return - */ - public function getTargets() - { - return (array) $this->targets; - } - - /** - * Get first target - * @return int - */ - public function getFirstTarget() - { - if(array_key_exists(0, $this->getTargets())) - { - $targets = $this->getTargets(); - return $targets[0]; - } - return 0; - } - // end-patch multi copy - - /** - * Cancel workflow - */ - protected function cancel() - { - $ilCtrl = $this->ctrl; - $ilCtrl->setReturnByClass(get_class($this->parent_obj),'cancel'); - $ilCtrl->returnToParent($this); - } - - /** - * Keep objects in clipboard - */ - function keepObjectsInClipboard() - { - ilUtil::sendSuccess($this->lng->txt("obj_inserted_clipboard"), true); - $ilCtrl = $this->ctrl; - $_SESSION['clipboard']['cmd'] = "copy"; - $_SESSION['clipboard']['ref_ids'] = $this->getSources(); - $ilCtrl->returnToParent($this); - } - - - /** - * Search source - * @return - */ - protected function searchSource() - { - $tree = $this->tree; - $ilObjDataCache = $this->obj_data_cache; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - - if(isset($_POST['tit'])) - { - ilUtil::sendInfo($this->lng->txt('wizard_search_list')); - $_SESSION['source_query'] = $_POST['tit']; - } - else - { - $_POST['tit'] = $_SESSION['source_query']; - } - - $this->initFormSearch(); - $this->form->setValuesByPost(); - - if(!$this->form->checkInput()) - { - ilUtil::sendFailure($lng->txt('msg_no_search_string'),true); - $ilCtrl->returnToParent($this); - return false; - } - - include_once './Services/Search/classes/class.ilQueryParser.php'; - $query_parser = new ilQueryParser($this->form->getInput('tit')); - $query_parser->setMinWordLength(1,true); - $query_parser->setCombination(QP_COMBINATION_AND); - $query_parser->parse(); - if(!$query_parser->validate()) - { - ilUtil::sendFailure($query_parser->getMessage(),true); - $ilCtrl->returnToParent($this); - } - - // only like search since fulltext does not support search with less than 3 characters - include_once 'Services/Search/classes/Like/class.ilLikeObjectSearch.php'; - $object_search = new ilLikeObjectSearch($query_parser); - $object_search->setFilter(array($_REQUEST['new_type'])); - $res = $object_search->performSearch(); - $res->setRequiredPermission('copy'); - $res->filter(ROOT_FOLDER_ID,true); - - if(!count($results = $res->getResultsByObjId())) - { - ilUtil::sendFailure($this->lng->txt('search_no_match'),true); - $ilCtrl->returnToParent($this); - } - - - include_once './Services/Object/classes/class.ilObjectCopySearchResultTableGUI.php'; - $table = new ilObjectCopySearchResultTableGUI($this,'searchSource',$this->getType()); - $table->setFormAction($ilCtrl->getFormAction($this)); - $table->setSelectedReference($this->getFirstSource()); - $table->parseSearchResults($results); - $tpl->setContent($table->getHTML()); - } - - /** - * select source object - * @return - */ - protected function saveSource() - { - $objDefinition = $this->obj_definition; - $ilCtrl = $this->ctrl; - - if(isset($_POST['source'])) - { - $this->setSource(array((int) $_REQUEST['source'])); - $this->setType(ilObject::_lookupType((int) $_REQUEST['source'], TRUE)); - $ilCtrl->setParameter($this,'source_id',(int) $_REQUEST['source']); - } - else - { - ilUtil::sendFailure($this->lng->txt('select_one')); - $this->searchSource(); - return false; - } - - // validate allowed subtypes - foreach($this->getSources() as $source_ref_id) - { - foreach((array) $this->getTargets() as $target_ref_id) - { - $target_type = ilObject::_lookupType($target_ref_id, TRUE); - $target_class_name = ilObjectFactory::getClassByType($target_type); - $target_object = new $target_class_name($target_ref_id); - $possible_subtypes = $target_object->getPossibleSubObjects(); - - $source_type = ilObject::_lookupType($source_ref_id, TRUE); - - if(!array_key_exists($source_type, $possible_subtypes)) - { - #ilLoggerFactory::getLogger('obj')->debug('Source type: '. $source_type); - #ilLoggerFactory::getLogger('obj')->debug('Target type: '. $target_type); - #ilLoggerFactory::getLogger('obj')->debug('Submode: '. $this->getSubMode()); - - // adopt content mode - if( - $this->getSubMode() != self::SUBMODE_CONTENT_ONLY and - ($source_type != 'crs' or $target_type != 'crs') - ) - { - ilUtil::sendFailure( - sprintf( - $this->lng->txt('msg_obj_may_not_contain_objects_of_type'), - $this->lng->txt('obj_'.$target_type), - $this->lng->txt('obj_'.$source_type)) - ); - $this->searchSource(); - return FALSE; - - } - } - } - } - - - if($objDefinition->isContainer($this->getType())) - { - $this->showItemSelection(); - } - else - { - $this->copySingleObject(); - } - } - - /** - * Save selected source from membership screen - */ - protected function saveSourceMembership() - { - $objDefinition = $this->obj_definition; - $ilCtrl = $this->ctrl; - - if(!isset($_REQUEST['source'])) - { - ilUtil::sendFailure($this->lng->txt('select_one')); - $ilCtrl->redirect($this,'showSourceSelectionMembership'); - return FALSE; - } - - $this->setSource(array((int) $_REQUEST['source'])); - $this->setType(ilObject::_lookupType((int) $this->getFirstSource(), TRUE)); - $ilCtrl->setParameter($this,'source_id',(int) $_REQUEST['source']); - - if($objDefinition->isContainer($this->getType())) - { - $this->showItemSelection(); - } - else - { - $this->copySingleObject(); - } - } - - /** - * - * @return - */ - protected function showItemSelection() - { - $tpl = $this->tpl; - - if(!count($this->getSources())) - { - ilUtil::sendFailure($this->lng->txt('select_one')); - $this->searchSource(); - return false; - } - - ilLoggerFactory::getLogger('obj')->debug('Source(s): '. print_r($this->getSources(),TRUE)); - ilLoggerFactory::getLogger('obj')->debug('Target(s): '. print_r($this->getTargets(),TRUE)); - - ilUtil::sendInfo($this->lng->txt($this->getType().'_copy_threads_info')); - include_once './Services/Object/classes/class.ilObjectCopySelectionTableGUI.php'; - - $tpl->addJavaScript('./Services/CopyWizard/js/ilContainer.js'); - $tpl->setVariable('BODY_ATTRIBUTES','onload="ilDisableChilds(\'cmd\');"'); - - switch($this->getMode()) - { - case self::SOURCE_SELECTION: - $back_cmd = 'showSourceSelectionTree'; - break; - - case self::TARGET_SELECTION: - $back_cmd = 'showTargetSelectionTree'; - break; - - case self::SEARCH_SOURCE: - $back_cmd = 'searchSource'; - break; - } - - $table = new ilObjectCopySelectionTableGUI($this,'showItemSelection',$this->getType(),$back_cmd); - $table->parseSource($this->getFirstSource()); - - $tpl->setContent($table->getHTML()); - } - - /** - * Start cloning a single (not container) object - * @return - */ - protected function copySingleObject() - { - include_once('./Services/Link/classes/class.ilLink.php'); - include_once('Services/CopyWizard/classes/class.ilCopyWizardOptions.php'); - - $ilAccess = $this->access; - $ilErr = $this->error; - $rbacsystem = $this->rbacsystem; - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - $rbacreview = $this->rbacreview; - - // Source defined - if(!count($this->getSources())) - { - ilUtil::sendFailure($this->lng->txt('select_one'),true); - $ilCtrl->returnToParent($this); - } - - $this->copyMultipleNonContainer($this->getSources()); - return; - } - - /** - * Copy multiple non container - * - * @param array $a_sources array of source ref ids - */ - function copyMultipleNonContainer($a_sources) - { - $ilAccess = $this->access; - $objDefinition = $this->obj_definition; - $rbacsystem = $this->rbacsystem; - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - $rbacreview = $this->rbacreview; - - - include_once('./Services/Link/classes/class.ilLink.php'); - include_once('Services/CopyWizard/classes/class.ilCopyWizardOptions.php'); - - // check permissions - foreach ($a_sources as $source_ref_id) - { - $source_type = ilObject::_lookupType($source_ref_id, true); - - // Create permission - // begin-patch mc - foreach($this->getTargets() as $target_ref_id) - { - if(!$rbacsystem->checkAccess('create', $target_ref_id, $source_type)) - { - $this->log->notice('Permission denied for target_id: ' . $target_ref_id.' source_type: ' . $source_type.' CREATE'); - ilUtil::sendFailure($this->lng->txt('permission_denied'),true); - $ilCtrl->returnToParent($this); - } - } - - // Copy permission - if(!$ilAccess->checkAccess('copy','',$source_ref_id)) - { - $this->log->notice('Permission denied for source_ref_id: ' . $source_ref_id.' COPY'); - ilUtil::sendFailure($this->lng->txt('permission_denied'),true); - $ilCtrl->returnToParent($this); - } - - // check that these objects are really not containers - if($objDefinition->isContainer($source_type) and $this->getSubMode() != self::SUBMODE_CONTENT_ONLY) - { - ilUtil::sendFailure($this->lng->txt('cntr_container_only_on_their_own'),true); - $ilCtrl->returnToParent($this); - } - } - - reset($a_sources); - - - ilLoggerFactory::getLogger('obj')->debug('Copy multiple non containers. Sources: ' . print_r($a_sources,TRUE)); - - // clone - foreach ($a_sources as $source_ref_id) - { - ilLoggerFactory::getLogger('obj')->debug('Copying source ref_id : ' . $source_ref_id); - - // begin-patch mc - foreach($this->getTargets() as $target_ref_id) - { - // Save wizard options - $copy_id = ilCopyWizardOptions::_allocateCopyId(); - $wizard_options = ilCopyWizardOptions::_getInstance($copy_id); - $wizard_options->saveOwner($ilUser->getId()); - $wizard_options->saveRoot((int) $source_ref_id); - $wizard_options->read(); - - $orig = ilObjectFactory::getInstanceByRefId((int) $source_ref_id); - $new_obj = $orig->cloneObject($target_ref_id,$copy_id); - - // Delete wizard options - $wizard_options->deleteAll(); - - // rbac log - include_once "Services/AccessControl/classes/class.ilRbacLog.php"; - if(ilRbacLog::isActive()) - { - $rbac_log_roles = $rbacreview->getParentRoleIds($new_obj->getRefId(), false); - $rbac_log = ilRbacLog::gatherFaPa($new_obj->getRefId(), array_keys($rbac_log_roles), true); - ilRbacLog::add(ilRbacLog::COPY_OBJECT, $new_obj->getRefId(), $rbac_log, (int)$source_ref_id); - } - } - } - - unset($_SESSION["clipboard"]["ref_ids"]); - unset($_SESSION["clipboard"]["cmd"]); - - if (count($a_sources) == 1) - { - ilLoggerFactory::getLogger('obj')->info('Object copy completed.'); - ilUtil::sendSuccess($this->lng->txt("object_duplicated"),true); - $ref_id = $new_obj->getRefId(); - } - else - { - ilLoggerFactory::getLogger('obj')->info('Object copy completed.'); - ilUtil::sendSuccess($this->lng->txt("objects_duplicated"),true); - $ref_id = $this->getFirstTarget(); - } - - ilUtil::sendSuccess($this->lng->txt("objects_duplicated"),true); - ilUtil::redirect(ilLink::_getLink($ref_id)); - - // see bug discussion 24472 - /* - $gui_fac = new ilObjectGUIFactory(); - $obj_gui = $gui_fac->getInstanceByRefId($ref_id); - $obj_gui->redirectAfterCreation(); - */ - } - - /** - * Copy to multiple targets - */ - protected function copyContainerToTargets() - { - $ilCtrl = $this->ctrl; - - ilLoggerFactory::getLogger('obj')->debug('Copy container to targets: '. print_r($_REQUEST,TRUE)); - ilLoggerFactory::getLogger('obj')->debug('Source(s): '. print_r($this->getSources(),TRUE)); - ilLoggerFactory::getLogger('obj')->debug('Target(s): '. print_r($this->getTargets(),TRUE)); - - - $last_target = 0; - $result = 1; - foreach($this->getTargets() as $target_ref_id) - { - $result = $this->copyContainer($target_ref_id); - $last_target = $target_ref_id; - } - - unset($_SESSION["clipboard"]["ref_ids"]); - unset($_SESSION["clipboard"]["cmd"]); - - include_once './Services/CopyWizard/classes/class.ilCopyWizardOptions.php'; - if(ilCopyWizardOptions::_isFinished($result['copy_id'])) - { - ilLoggerFactory::getLogger('obj')->info('Object copy completed.'); - ilUtil::sendSuccess($this->lng->txt("object_duplicated"),true); - if($this->getSubMode() == self::SUBMODE_CONTENT_ONLY) - { - // return to parent container - return $this->ctrl->returnToParent($this); - } - // return to last target - $link = ilLink::_getLink($result['ref_id']); - $ilCtrl->redirectToUrl($link); - } - else - { - // show progress - ilLoggerFactory::getLogger('obj')->debug('Object copy in progress.'); - return $this->showCopyProgress(); - } - } - - /** - * Show progress for copying - */ - protected function showCopyProgress() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - - include_once './Services/Object/classes/class.ilObjectCopyProgressTableGUI.php'; - $progress = new ilObjectCopyProgressTableGUI( - $this, - 'showCopyProgress', - (int) $_GET['ref_id'] - ); - $progress->setObjectInfo($this->targets_copy_id); - $progress->parse(); - $progress->init(); - $progress->setRedirectionUrl($ilCtrl->getParentReturn($this->parent_obj)); - - $tpl->setContent($progress->getHTML()); - } - - /** - * Update progress - */ - protected function updateProgress() - { - $json = new stdClass(); - $json->percentage = null; - $json->performed_steps = null; - - include_once './Services/CopyWizard/classes/class.ilCopyWizardOptions.php'; - $options = ilCopyWizardOptions::_getInstance((int) $_REQUEST['copy_id']); - $json->required_steps = $options->getRequiredSteps(); - $json->id = (int) $_REQUEST['copy_id']; - - ilLoggerFactory::getLogger('obj')->debug('Update copy progress: '. json_encode($json)); - - echo json_encode($json); - exit; - } - - - /** - * Copy a container - * @return - */ - protected function copyContainer($a_target) - { - $ilLog = $this->log; - $ilCtrl = $this->ctrl; - - include_once('./Services/Link/classes/class.ilLink.php'); - include_once('Services/CopyWizard/classes/class.ilCopyWizardOptions.php'); - - $ilAccess = $this->access; - $ilErr = $this->error; - $rbacsystem = $this->rbacsystem; - $tree = $this->tree; - $ilUser = $this->user; - $ilCtrl = $this->ctrl; - - // Workaround for course in course copy - - $target_type = ilObject::_lookupType(ilObject::_lookupObjId($a_target)); - $source_type = ilObject::_lookupType(ilObject::_lookupObjId($this->getFirstSource())); - - if($this->getSubMode() != self::SUBMODE_CONTENT_ONLY) - { - if(!$rbacsystem->checkAccess('create', $a_target,$this->getType())) - { - $this->log->notice('Permission denied for target: '. $a_target.' type: ' . $this->getType().' CREATE'); - ilUtil::sendFailure($this->lng->txt('permission_denied'),true); - $ilCtrl->returnToParent($this); - } - } - if(!$this->getFirstSource()) - { - ilUtil::sendFailure($this->lng->txt('select_one'),true); - $ilCtrl->returnToParent($this); - return false; - } - - $options = $_POST['cp_options'] ? $_POST['cp_options'] : array(); - - - ilLoggerFactory::getLogger('obj')->debug('Copy container (sources): '. print_r($this->getSources(),TRUE)); - - $orig = ilObjectFactory::getInstanceByRefId($this->getFirstSource()); - $result = $orig->cloneAllObject( - $_COOKIE[session_name()], - $_COOKIE['ilClientId'], - $this->getType(), - $a_target, - $this->getFirstSource(), - $options, - FALSE, - $this->getSubMode() - ); - - $this->targets_copy_id[$a_target] = $result['copy_id']; - - return $result; - } - - - - /** - * Show init screen - * Normally shown below the create and import form when creating a new object - * - * @param string $a_tplvar The tpl variable to fill - * @return - */ - public function showSourceSearch($a_tplvar) - { - $tpl = $this->tpl; - - // Disabled for performance - #if(!$this->sourceExists()) - #{ - # return false; - #} - - $this->unsetSession(); - $this->initFormSearch(); - - if($a_tplvar) - { - $tpl->setVariable($a_tplvar,$this->form->getHTML()); - } - else - { - return $this->form; - } - } - - - /** - * Check if there is any source object - * @return bool - */ - protected function sourceExists() - { - $ilUser = $this->user; - - return (bool) ilUtil::_getObjectsByOperations($this->getType(),'copy',$ilUser->getId(),1); - } - - /** - * Init search form - * @return - */ - protected function initFormSearch() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once './Services/Form/classes/class.ilPropertyFormGUI.php'; - $this->form = new ilPropertyFormGUI(); - $this->form->setTableWidth('600px'); - - $ilCtrl->setParameter($this,'new_type',$this->getType()); - - #$ilCtrl->setParameter($this, 'cp_mode', self::SOURCE_SELECTION); - $this->form->setFormAction($ilCtrl->getFormAction($this)); - $this->form->setTitle($lng->txt($this->getType().'_copy')); - - $this->form->addCommandButton('searchSource', $lng->txt('btn_next')); - $this->form->addCommandButton('cancel',$this->lng->txt('cancel')); - - $tit = new ilTextInputGUI($lng->txt('title'),'tit'); - $tit->setSize(40); - $tit->setMaxLength(70); - $tit->setRequired(true); - $tit->setInfo($lng->txt('wizard_title_info')); - $this->form->addItem($tit); - } - - /** - * Unset session variables - * @return - */ - protected function unsetSession() - { - unset($_SESSION['source_query']); - $this->setSource(array()); - } + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTree + */ + protected $tree; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilObjectDefinition + */ + protected $obj_definition; + + /** + * @var ilObjectDataCache + */ + protected $obj_data_cache; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilRbacReview + */ + protected $rbacreview; + + const SOURCE_SELECTION = 1; + const TARGET_SELECTION = 2; + const SEARCH_SOURCE = 3; + + const SUBMODE_COMPLETE = 1; + const SUBMODE_CONTENT_ONLY = 2; + + // tabs + const TAB_SELECTION_TARGET_TREE = 1; + const TAB_SELECTION_SOURCE_TREE = 2; + const TAB_SELECTION_MEMBERSHIP = 3; + + // group selection of source or target + const TAB_GROUP_SC_SELECTION = 1; + + + private $mode = 0; + private $sub_mode = self::SUBMODE_COMPLETE; + + private $lng; + + private $parent_obj = null; + + private $type = ''; + + private $sources = array(); + + // begin-patch multi copy + private $targets = array(); + private $targets_copy_id = array(); + // end-patch multi copy + + /** + * @var ilLogger + */ + private $log = null; + + + /** + * Constructor + * @return + */ + public function __construct($a_parent_gui) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->tree = $DIC->repositoryTree(); + $this->tabs = $DIC->tabs(); + $this->toolbar = $DIC->toolbar(); + $this->tpl = $DIC["tpl"]; + $this->obj_definition = $DIC["objDefinition"]; + $this->obj_data_cache = $DIC["ilObjDataCache"]; + $this->access = $DIC->access(); + $this->error = $DIC["ilErr"]; + $this->rbacsystem = $DIC->rbac()->system(); + $this->user = $DIC->user(); + $this->rbacreview = $DIC->rbac()->review(); + $this->log = $DIC["ilLog"]; + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->lng = $lng; + $this->lng->loadLanguageModule('search'); + $this->lng->loadLanguageModule('obj'); + + $this->parent_obj = $a_parent_gui; + + $this->log = ilLoggerFactory::getLogger('obj'); + } + + /** + * Control class handling + * @return + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $this->init(); + $this->initTabs(); + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd(); + + switch ($next_class) { + default: + $this->$cmd(); + break; + } + } + + /** + * Init return, mode + * @return + */ + protected function init() + { + $ilCtrl = $this->ctrl; + + if ((int) $_REQUEST['smode']) { + $this->setSubMode((int) $_REQUEST['smode']); + $ilCtrl->setParameter($this, 'smode', $this->getSubMode()); + ilLoggerFactory::getLogger('obj')->debug('Submode is: ' . $this->getSubMode()); + } + + // save sources + if ($_REQUEST['source_ids']) { + $this->setSource(explode('_', $_REQUEST['source_ids'])); + $ilCtrl->setParameter($this, 'source_ids', implode('_', $this->getSources())); + ilLoggerFactory::getLogger('obj')->debug('Multiple sources: ' . implode('_', $this->getSources())); + } + if ($_REQUEST['source_id']) { + $this->setSource(array((int) $_REQUEST['source_id'])); + $ilCtrl->setParameter($this, 'source_ids', implode('_', $this->getSources())); + ilLoggerFactory::getLogger('obj')->debug('source_id is set: ' . implode('_', $this->getSources())); + } + if ($this->getFirstSource()) { + $this->setType( + ilObject::_lookupType(ilObject::_lookupObjId($this->getFirstSource())) + ); + } + + // creation screen: copy section + if ($_REQUEST['new_type']) { + $this->setMode(self::SEARCH_SOURCE); + $this->setType($_REQUEST['new_type']); + $this->setTarget((int) $_GET['ref_id']); + + $ilCtrl->setParameter($this, 'new_type', $this->getType()); + $ilCtrl->setParameterByClass(get_class($this->getParentObject()), 'new_type', $this->getType()); + $ilCtrl->setParameterByClass(get_class($this->getParentObject()), 'cpfl', 1); + $ilCtrl->setReturnByClass(get_class($this->getParentObject()), 'create'); + + ilLoggerFactory::getLogger('obj')->debug('Copy from object creation for type: ' . $this->getType()); + return true; + } + // adopt content, and others? + elseif ($_REQUEST['selectMode'] == self::SOURCE_SELECTION) { + $this->setMode(self::SOURCE_SELECTION); + + $ilCtrl->setParameterByClass(get_class($this->parent_obj), 'selectMode', self::SOURCE_SELECTION); + $this->setTarget((int) $_GET['ref_id']); + $ilCtrl->setReturnByClass(get_class($this->parent_obj), ''); + + ilLoggerFactory::getLogger('obj')->debug('Source selection mode. Target is: ' . $this->getFirstTarget()); + } elseif ($_REQUEST['selectMode'] == self::TARGET_SELECTION) { + $this->setMode(self::TARGET_SELECTION); + $ilCtrl->setReturnByClass(get_class($this->parent_obj), ''); + ilLoggerFactory::getLogger('obj')->debug('Target selection mode.'); + } + + + // save targets + if ($_REQUEST['target_ids']) { + $this->setTargets(explode('_', $_REQUEST['target_ids'])); + ilLoggerFactory::getLogger('obj')->debug('targets are: ' . print_r($this->getTargets(), true)); + } + } + + /** + * Init tabs + * General + */ + protected function initTabs() + { + $lng = $this->lng; + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + + $lng->loadLanguageModule('cntr'); + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $lng->txt('tab_back_to_repository'), + $ilCtrl->getParentReturn($this->parent_obj) + ); + } + + /** + * Set tabs + * @param type $a_tab_group + * @param type $a_active_tab + */ + protected function setTabs($a_tab_group, $a_active_tab) + { + $lng = $this->lng; + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + + if ($a_tab_group == self::TAB_GROUP_SC_SELECTION) { + if ($this->getSubMode() == self::SUBMODE_CONTENT_ONLY) { + if ($this->getMode() == self::SOURCE_SELECTION) { + $ilTabs->addTab( + self::TAB_SELECTION_SOURCE_TREE, + $lng->txt('cntr_copy_repo_tree'), + $ilCtrl->getLinkTarget($this, 'initSourceSelection') + ); + $ilTabs->addTab( + self::TAB_SELECTION_MEMBERSHIP, + $lng->txt('cntr_copy_crs_grp'), + $ilCtrl->getLinkTarget($this, 'showSourceSelectionMembership') + ); + } + } + } + $ilTabs->activateTab($a_active_tab); + } + + + /** + * Adopt content (crs in crs, grp in grp, crs in grp or grp in crs) + * @return type + */ + protected function adoptContent() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameter($this, 'smode', self::SUBMODE_CONTENT_ONLY); + $ilCtrl->setParameter($this, 'selectMode', self::SOURCE_SELECTION); + + + $this->setSubMode(self::SUBMODE_CONTENT_ONLY); + $this->setMode(self::SOURCE_SELECTION); + $this->setTarget((int) $_GET['ref_id']); + + + return $this->initSourceSelection(); + } + + /** + * Init copy from repository/search list commands + * @return + */ + protected function initTargetSelection() + { + $ilCtrl = $this->ctrl; + $tree = $this->tree; + $ilCtrl->setParameter($this, 'selectMode', self::TARGET_SELECTION); + // empty session on init + $_SESSION['paste_copy_repexpand'] = array(); + + // copy opened nodes from repository explorer + $_SESSION['paste_copy_repexpand'] = is_array($_SESSION['repexpand']) ? $_SESSION['repexpand'] : array(); + + // begin-patch mc + $this->setTargets(array()); + // cognos-blu-patch: end + + // open current position + + foreach ($this->getSources() as $source_id) { + if ($source_id) { + $path = $tree->getPathId($source_id); + foreach ((array) $path as $node_id) { + if (!in_array($node_id, $_SESSION['paste_copy_repexpand'])) { + $_SESSION['paste_copy_repexpand'][] = $node_id; + } + } + } + } + + $ilCtrl->setReturnByClass(get_class($this->parent_obj), ''); + $this->showTargetSelectionTree(); + } + + /** + * Init source selection + * @return + */ + protected function initSourceSelection() + { + $ilCtrl = $this->ctrl; + $tree = $this->tree; + + // empty session on init + $_SESSION['paste_copy_repexpand'] = array(); + + // copy opened nodes from repository explorer + $_SESSION['paste_copy_repexpand'] = is_array($_SESSION['repexpand']) ? $_SESSION['repexpand'] : array(); + + $this->setTabs(self::TAB_GROUP_SC_SELECTION, self::TAB_SELECTION_SOURCE_TREE); + + + // open current position + // begin-patch mc + foreach ($this->getTargets() as $target_ref_id) { + $path = $tree->getPathId($target_ref_id); + foreach ((array) $path as $node_id) { + if (!in_array($node_id, $_SESSION['paste_copy_repexpand'])) { + $_SESSION['paste_copy_repexpand'][] = $node_id; + } + } + } + // end-patch multi copy + $ilCtrl->setReturnByClass(get_class($this->parent_obj), ''); + $this->showSourceSelectionTree(); + } + + + /** + * show target selection membership + */ + protected function showSourceSelectionMembership() + { + $user = $this->user; + $tpl = $this->tpl; + + ilUtil::sendInfo($this->lng->txt('msg_copy_clipboard_source')); + $this->setTabs(self::TAB_GROUP_SC_SELECTION, self::TAB_SELECTION_MEMBERSHIP); + + include_once './Services/Object/classes/class.ilObjectCopyCourseGroupSelectionTableGUI.php'; + $cgs = new ilObjectCopyCourseGroupSelectionTableGUI($this, 'showSourceSelectionMembership', 'copy_selection_membership'); + $cgs->init(); + $cgs->setObjects( + array_merge( + ilParticipants::_getMembershipByType($user->getId(), 'crs', false), + ilParticipants::_getMembershipByType($user->getId(), 'grp', false) + ) + ); + $cgs->parse(); + + $tpl->setContent($cgs->getHTML()); + } + + + /** + * Show target selection + */ + public function showTargetSelectionTree() + { + $ilTabs = $this->tabs; + $ilToolbar = $this->toolbar; + $ilCtrl = $this->ctrl; + $tree = $this->tree; + $tpl = $this->tpl; + $objDefinition = $this->obj_definition; + $lng = $this->lng; + + $this->tpl = $tpl; + + if ($objDefinition->isContainer($this->getType())) { + ilUtil::sendInfo($this->lng->txt('msg_copy_clipboard_container')); + } else { + ilUtil::sendInfo($this->lng->txt('msg_copy_clipboard')); + } + + // + include_once("./Services/Repository/classes/class.ilRepositorySelectorExplorerGUI.php"); + $exp = new ilRepositorySelectorExplorerGUI($this, "showTargetSelectionTree"); + $exp->setTypeWhiteList(array("root", "cat", "grp", "crs", "fold", "lso")); + $exp->setSelectMode("target", true); + if ($exp->handleCommand()) { + return; + } + $output = $exp->getHTML(); + + // toolbars + $t = new ilToolbarGUI(); + $t->setFormAction($ilCtrl->getFormAction($this, "saveTarget")); + if ($objDefinition->isContainer($this->getType())) { + $t->addFormButton($lng->txt("btn_next"), "saveTarget"); + } else { + $t->addFormButton($lng->txt("paste"), "saveTarget"); + } + $t->addSeparator(); + $t->addFormButton($lng->txt("obj_insert_into_clipboard"), "keepObjectsInClipboard"); + $t->addFormButton($lng->txt("cancel"), "cancel"); + $t->setCloseFormTag(false); + $t->setLeadingImage(ilUtil::getImagePath("arrow_upright.svg"), " "); + $output = $t->getHTML() . $output; + $t->setLeadingImage(ilUtil::getImagePath("arrow_downright.svg"), " "); + $t->setCloseFormTag(true); + $t->setOpenFormTag(false); + $output.= "
                  " . $t->getHTML(); + + $this->tpl->setContent($output); + + return; + } + + /** + * Show target selection + */ + public function showSourceSelectionTree() + { + $ilTabs = $this->tabs; + $ilToolbar = $this->toolbar; + $ilCtrl = $this->ctrl; + $tree = $this->tree; + $tpl = $this->tpl; + $objDefinition = $this->obj_definition; + + $this->tpl = $tpl; + $this->tpl->addBlockfile( + 'ADM_CONTENT', + 'adm_content', + 'tpl.paste_into_multiple_objects.html', + "Services/Object" + ); + + ilUtil::sendInfo($this->lng->txt('msg_copy_clipboard_source')); + include_once './Services/Object/classes/class.ilPasteIntoMultipleItemsExplorer.php'; + $exp = new ilPasteIntoMultipleItemsExplorer( + ilPasteIntoMultipleItemsExplorer::SEL_TYPE_RADIO, + 'ilias.php?baseClass=ilRepositoryGUI&cmd=goto', + 'paste_copy_repexpand' + ); + $exp->setRequiredFormItemPermission('visible,read,copy'); + + $ilCtrl->setParameter($this, 'selectMode', self::SOURCE_SELECTION); + $exp->setExpandTarget($ilCtrl->getLinkTarget($this, 'showSourceSelectionTree')); + $exp->setTargetGet('ref_id'); + $exp->setPostVar('source'); + $exp->setCheckedItems($this->getSources()); + + // Filter to container + foreach (array('cat','root','fold') as $container) { + $exp->removeFormItemForType($container); + } + + + if ($_GET['paste_copy_repexpand'] == '') { + $expanded = $tree->readRootId(); + } else { + $expanded = $_GET['paste_copy_repexpand']; + } + + $this->tpl->setVariable('FORM_TARGET', '_self'); + $this->tpl->setVariable('FORM_ACTION', $ilCtrl->getFormAction($this, 'copySelection')); + + $exp->setExpand($expanded); + // build html-output + $exp->setOutput(0); + $output = $exp->getOutput(); + + $this->tpl->setVariable('OBJECT_TREE', $output); + + $this->tpl->setVariable('CMD_SUBMIT', 'saveSource'); + $this->tpl->setVariable('TXT_SUBMIT', $this->lng->txt('btn_next')); + + $ilToolbar->addButton($this->lng->txt('cancel'), $ilCtrl->getLinkTarget($this, 'cancel')); + } + + /** + * Save target selection + * @return + */ + protected function saveTarget() + { + $objDefinition = $this->obj_definition; + $tree = $this->tree; + $ilCtrl = $this->ctrl; + + + // begin-patch mc + if (is_array($_REQUEST['target']) and $_REQUEST['target']) { + $this->setTargets($_REQUEST['target']); + $ilCtrl->setParameter($this, 'target_ids', implode('_', $this->getTargets())); + } + // paste from clipboard + elseif ((int) $_REQUEST['target']) { + $this->setTarget($_REQUEST['target']); + $ilCtrl->setParameter($this, 'target_ids', implode('_', $this->getTargets())); + } + // end-patch multi copy + else { + $ilCtrl->setParameter($this, 'selectMode', self::TARGET_SELECTION); + ilUtil::sendFailure($this->lng->txt('select_one')); + $this->showTargetSelectionTree(); + return false; + } + + // validate allowed subtypes + foreach ($this->getSources() as $source_ref_id) { + foreach ((array) $this->getTargets() as $target_ref_id) { + $target_type = ilObject::_lookupType($target_ref_id, true); + $target_class_name = ilObjectFactory::getClassByType($target_type); + $target_object = new $target_class_name($target_ref_id); + $possible_subtypes = $target_object->getPossibleSubObjects(); + + $source_type = ilObject::_lookupType($source_ref_id, true); + + if (!array_key_exists($source_type, (array) $possible_subtypes)) { + ilUtil::sendFailure( + sprintf( + $this->lng->txt('msg_obj_may_not_contain_objects_of_type'), + $this->lng->txt('obj_' . $target_type), + $this->lng->txt('obj_' . $source_type) + ) + ); + $this->showTargetSelectionTree(); + return false; + } + } + } + + if (count($this->getSources()) == 1 && $objDefinition->isContainer($this->getType())) { + // check, if object should be copied into itself + // begin-patch mc + $is_child = array(); + foreach ($this->getTargets() as $target_ref_id) { + if ($tree->isGrandChild($this->getFirstSource(), $target_ref_id)) { + $is_child[] = ilObject::_lookupTitle(ilObject::_lookupObjId($this->getFirstSource())); + } + if ($this->getFirstSource() == $target_ref_id) { + $is_child[] = ilObject::_lookupTitle(ilObject::_lookupObjId($this->getFirstSource())); + } + } + // end-patch multi copy + if (count($is_child) > 0) { + ilUtil::sendFailure($this->lng->txt("msg_not_in_itself") . " " . implode(',', $is_child)); + $this->showTargetSelectionTree(); + return false; + } + + $this->showItemSelection(); + } else { + if (count($this->getSources()) == 1) { + $this->copySingleObject(); + } else { + $this->copyMultipleNonContainer($this->getSources()); + } + } + } + + /** + * set copy mode + * @param int $a_mode + * @return + */ + public function setMode($a_mode) + { + $this->mode = $a_mode; + } + + /** + * get copy mode + * @return + */ + public function getMode() + { + return $this->mode; + } + + public function setSubMode($a_mode) + { + $this->sub_mode = $a_mode; + } + + public function getSubMode() + { + return $this->sub_mode; + } + + /** + * Get parent gui object + * @return object parent gui + */ + public function getParentObject() + { + return $this->parent_obj; + } + + /** + * Returns $type. + * + * @see ilObjectCopyGUI::$type + */ + public function getType() + { + return $this->type; + } + + /** + * Sets $type. + * + * @param object $type + * @see ilObjectCopyGUI::$type + */ + public function setType($type) + { + $this->type = $type; + } + + /** + * Set source id + * @param array $a_source_id + * @return + */ + public function setSource(array $a_source_ids) + { + $this->sources = $a_source_ids; + } + + /** + * Get sources + * @return array + */ + public function getSources() + { + return (array) $this->sources; + } + + public function getFirstSource() + { + if (count($this->sources)) { + return $this->sources[0]; + } + return 0; + } + + // begin-patch mc + + /** + * Set single object target + * @param type $a_ref_id + */ + public function setTarget($a_ref_id) + { + $this->setTargets(array($a_ref_id)); + } + + + /** + * Set target id + * @param int $a_target + * @return + */ + public function setTargets(array $a_target) + { + $this->targets = $a_target; + } + + /** + * Get copy target + * @return + */ + public function getTargets() + { + return (array) $this->targets; + } + + /** + * Get first target + * @return int + */ + public function getFirstTarget() + { + if (array_key_exists(0, $this->getTargets())) { + $targets = $this->getTargets(); + return $targets[0]; + } + return 0; + } + // end-patch multi copy + + /** + * Cancel workflow + */ + protected function cancel() + { + $ilCtrl = $this->ctrl; + $ilCtrl->setReturnByClass(get_class($this->parent_obj), 'cancel'); + $ilCtrl->returnToParent($this); + } + + /** + * Keep objects in clipboard + */ + public function keepObjectsInClipboard() + { + ilUtil::sendSuccess($this->lng->txt("obj_inserted_clipboard"), true); + $ilCtrl = $this->ctrl; + $_SESSION['clipboard']['cmd'] = "copy"; + $_SESSION['clipboard']['ref_ids'] = $this->getSources(); + $ilCtrl->returnToParent($this); + } + + + /** + * Search source + * @return + */ + protected function searchSource() + { + $tree = $this->tree; + $ilObjDataCache = $this->obj_data_cache; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + + if (isset($_POST['tit'])) { + ilUtil::sendInfo($this->lng->txt('wizard_search_list')); + $_SESSION['source_query'] = $_POST['tit']; + } else { + $_POST['tit'] = $_SESSION['source_query']; + } + + $this->initFormSearch(); + $this->form->setValuesByPost(); + + if (!$this->form->checkInput()) { + ilUtil::sendFailure($lng->txt('msg_no_search_string'), true); + $ilCtrl->returnToParent($this); + return false; + } + + include_once './Services/Search/classes/class.ilQueryParser.php'; + $query_parser = new ilQueryParser($this->form->getInput('tit')); + $query_parser->setMinWordLength(1, true); + $query_parser->setCombination(QP_COMBINATION_AND); + $query_parser->parse(); + if (!$query_parser->validate()) { + ilUtil::sendFailure($query_parser->getMessage(), true); + $ilCtrl->returnToParent($this); + } + + // only like search since fulltext does not support search with less than 3 characters + include_once 'Services/Search/classes/Like/class.ilLikeObjectSearch.php'; + $object_search = new ilLikeObjectSearch($query_parser); + $object_search->setFilter(array($_REQUEST['new_type'])); + $res = $object_search->performSearch(); + $res->setRequiredPermission('copy'); + $res->filter(ROOT_FOLDER_ID, true); + + if (!count($results = $res->getResultsByObjId())) { + ilUtil::sendFailure($this->lng->txt('search_no_match'), true); + $ilCtrl->returnToParent($this); + } + + + include_once './Services/Object/classes/class.ilObjectCopySearchResultTableGUI.php'; + $table = new ilObjectCopySearchResultTableGUI($this, 'searchSource', $this->getType()); + $table->setFormAction($ilCtrl->getFormAction($this)); + $table->setSelectedReference($this->getFirstSource()); + $table->parseSearchResults($results); + $tpl->setContent($table->getHTML()); + } + + /** + * select source object + * @return + */ + protected function saveSource() + { + $objDefinition = $this->obj_definition; + $ilCtrl = $this->ctrl; + + if (isset($_POST['source'])) { + $this->setSource(array((int) $_REQUEST['source'])); + $this->setType(ilObject::_lookupType((int) $_REQUEST['source'], true)); + $ilCtrl->setParameter($this, 'source_id', (int) $_REQUEST['source']); + } else { + ilUtil::sendFailure($this->lng->txt('select_one')); + $this->searchSource(); + return false; + } + + // validate allowed subtypes + foreach ($this->getSources() as $source_ref_id) { + foreach ((array) $this->getTargets() as $target_ref_id) { + $target_type = ilObject::_lookupType($target_ref_id, true); + $target_class_name = ilObjectFactory::getClassByType($target_type); + $target_object = new $target_class_name($target_ref_id); + $possible_subtypes = $target_object->getPossibleSubObjects(); + + $source_type = ilObject::_lookupType($source_ref_id, true); + + if (!array_key_exists($source_type, $possible_subtypes)) { + #ilLoggerFactory::getLogger('obj')->debug('Source type: '. $source_type); + #ilLoggerFactory::getLogger('obj')->debug('Target type: '. $target_type); + #ilLoggerFactory::getLogger('obj')->debug('Submode: '. $this->getSubMode()); + + // adopt content mode + if ( + $this->getSubMode() != self::SUBMODE_CONTENT_ONLY and + ($source_type != 'crs' or $target_type != 'crs') + ) { + ilUtil::sendFailure( + sprintf( + $this->lng->txt('msg_obj_may_not_contain_objects_of_type'), + $this->lng->txt('obj_' . $target_type), + $this->lng->txt('obj_' . $source_type) + ) + ); + $this->searchSource(); + return false; + } + } + } + } + + + if ($objDefinition->isContainer($this->getType())) { + $this->showItemSelection(); + } else { + $this->copySingleObject(); + } + } + + /** + * Save selected source from membership screen + */ + protected function saveSourceMembership() + { + $objDefinition = $this->obj_definition; + $ilCtrl = $this->ctrl; + + if (!isset($_REQUEST['source'])) { + ilUtil::sendFailure($this->lng->txt('select_one')); + $ilCtrl->redirect($this, 'showSourceSelectionMembership'); + return false; + } + + $this->setSource(array((int) $_REQUEST['source'])); + $this->setType(ilObject::_lookupType((int) $this->getFirstSource(), true)); + $ilCtrl->setParameter($this, 'source_id', (int) $_REQUEST['source']); + + if ($objDefinition->isContainer($this->getType())) { + $this->showItemSelection(); + } else { + $this->copySingleObject(); + } + } + + /** + * + * @return + */ + protected function showItemSelection() + { + $tpl = $this->tpl; + + if (!count($this->getSources())) { + ilUtil::sendFailure($this->lng->txt('select_one')); + $this->searchSource(); + return false; + } + + ilLoggerFactory::getLogger('obj')->debug('Source(s): ' . print_r($this->getSources(), true)); + ilLoggerFactory::getLogger('obj')->debug('Target(s): ' . print_r($this->getTargets(), true)); + + ilUtil::sendInfo($this->lng->txt($this->getType() . '_copy_threads_info')); + include_once './Services/Object/classes/class.ilObjectCopySelectionTableGUI.php'; + + $tpl->addJavaScript('./Services/CopyWizard/js/ilContainer.js'); + $tpl->setVariable('BODY_ATTRIBUTES', 'onload="ilDisableChilds(\'cmd\');"'); + + switch ($this->getMode()) { + case self::SOURCE_SELECTION: + $back_cmd = 'showSourceSelectionTree'; + break; + + case self::TARGET_SELECTION: + $back_cmd = 'showTargetSelectionTree'; + break; + + case self::SEARCH_SOURCE: + $back_cmd = 'searchSource'; + break; + } + + $table = new ilObjectCopySelectionTableGUI($this, 'showItemSelection', $this->getType(), $back_cmd); + $table->parseSource($this->getFirstSource()); + + $tpl->setContent($table->getHTML()); + } + + /** + * Start cloning a single (not container) object + * @return + */ + protected function copySingleObject() + { + include_once('./Services/Link/classes/class.ilLink.php'); + include_once('Services/CopyWizard/classes/class.ilCopyWizardOptions.php'); + + $ilAccess = $this->access; + $ilErr = $this->error; + $rbacsystem = $this->rbacsystem; + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + $rbacreview = $this->rbacreview; + + // Source defined + if (!count($this->getSources())) { + ilUtil::sendFailure($this->lng->txt('select_one'), true); + $ilCtrl->returnToParent($this); + } + + $this->copyMultipleNonContainer($this->getSources()); + return; + } + + /** + * Copy multiple non container + * + * @param array $a_sources array of source ref ids + */ + public function copyMultipleNonContainer($a_sources) + { + $ilAccess = $this->access; + $objDefinition = $this->obj_definition; + $rbacsystem = $this->rbacsystem; + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + $rbacreview = $this->rbacreview; + + + include_once('./Services/Link/classes/class.ilLink.php'); + include_once('Services/CopyWizard/classes/class.ilCopyWizardOptions.php'); + + // check permissions + foreach ($a_sources as $source_ref_id) { + $source_type = ilObject::_lookupType($source_ref_id, true); + + // Create permission + // begin-patch mc + foreach ($this->getTargets() as $target_ref_id) { + if (!$rbacsystem->checkAccess('create', $target_ref_id, $source_type)) { + $this->log->notice('Permission denied for target_id: ' . $target_ref_id . ' source_type: ' . $source_type . ' CREATE'); + ilUtil::sendFailure($this->lng->txt('permission_denied'), true); + $ilCtrl->returnToParent($this); + } + } + + // Copy permission + if (!$ilAccess->checkAccess('copy', '', $source_ref_id)) { + $this->log->notice('Permission denied for source_ref_id: ' . $source_ref_id . ' COPY'); + ilUtil::sendFailure($this->lng->txt('permission_denied'), true); + $ilCtrl->returnToParent($this); + } + + // check that these objects are really not containers + if ($objDefinition->isContainer($source_type) and $this->getSubMode() != self::SUBMODE_CONTENT_ONLY) { + ilUtil::sendFailure($this->lng->txt('cntr_container_only_on_their_own'), true); + $ilCtrl->returnToParent($this); + } + } + + reset($a_sources); + + + ilLoggerFactory::getLogger('obj')->debug('Copy multiple non containers. Sources: ' . print_r($a_sources, true)); + + // clone + foreach ($a_sources as $source_ref_id) { + ilLoggerFactory::getLogger('obj')->debug('Copying source ref_id : ' . $source_ref_id); + + // begin-patch mc + foreach ($this->getTargets() as $target_ref_id) { + // Save wizard options + $copy_id = ilCopyWizardOptions::_allocateCopyId(); + $wizard_options = ilCopyWizardOptions::_getInstance($copy_id); + $wizard_options->saveOwner($ilUser->getId()); + $wizard_options->saveRoot((int) $source_ref_id); + $wizard_options->read(); + + $orig = ilObjectFactory::getInstanceByRefId((int) $source_ref_id); + $new_obj = $orig->cloneObject($target_ref_id, $copy_id); + + // Delete wizard options + $wizard_options->deleteAll(); + + // rbac log + include_once "Services/AccessControl/classes/class.ilRbacLog.php"; + if (ilRbacLog::isActive()) { + $rbac_log_roles = $rbacreview->getParentRoleIds($new_obj->getRefId(), false); + $rbac_log = ilRbacLog::gatherFaPa($new_obj->getRefId(), array_keys($rbac_log_roles), true); + ilRbacLog::add(ilRbacLog::COPY_OBJECT, $new_obj->getRefId(), $rbac_log, (int) $source_ref_id); + } + } + } + + unset($_SESSION["clipboard"]["ref_ids"]); + unset($_SESSION["clipboard"]["cmd"]); + + if (count($a_sources) == 1) { + ilLoggerFactory::getLogger('obj')->info('Object copy completed.'); + ilUtil::sendSuccess($this->lng->txt("object_duplicated"), true); + $ref_id = $new_obj->getRefId(); + } else { + ilLoggerFactory::getLogger('obj')->info('Object copy completed.'); + ilUtil::sendSuccess($this->lng->txt("objects_duplicated"), true); + $ref_id = $this->getFirstTarget(); + } + + ilUtil::sendSuccess($this->lng->txt("objects_duplicated"), true); + ilUtil::redirect(ilLink::_getLink($ref_id)); + + // see bug discussion 24472 + /* + $gui_fac = new ilObjectGUIFactory(); + $obj_gui = $gui_fac->getInstanceByRefId($ref_id); + $obj_gui->redirectAfterCreation(); + */ + } + + /** + * Copy to multiple targets + */ + protected function copyContainerToTargets() + { + $ilCtrl = $this->ctrl; + + ilLoggerFactory::getLogger('obj')->debug('Copy container to targets: ' . print_r($_REQUEST, true)); + ilLoggerFactory::getLogger('obj')->debug('Source(s): ' . print_r($this->getSources(), true)); + ilLoggerFactory::getLogger('obj')->debug('Target(s): ' . print_r($this->getTargets(), true)); + + + $last_target = 0; + $result = 1; + foreach ($this->getTargets() as $target_ref_id) { + $result = $this->copyContainer($target_ref_id); + $last_target = $target_ref_id; + } + + unset($_SESSION["clipboard"]["ref_ids"]); + unset($_SESSION["clipboard"]["cmd"]); + + include_once './Services/CopyWizard/classes/class.ilCopyWizardOptions.php'; + if (ilCopyWizardOptions::_isFinished($result['copy_id'])) { + ilLoggerFactory::getLogger('obj')->info('Object copy completed.'); + ilUtil::sendSuccess($this->lng->txt("object_duplicated"), true); + if ($this->getSubMode() == self::SUBMODE_CONTENT_ONLY) { + // return to parent container + return $this->ctrl->returnToParent($this); + } + // return to last target + $link = ilLink::_getLink($result['ref_id']); + $ilCtrl->redirectToUrl($link); + } else { + // show progress + ilLoggerFactory::getLogger('obj')->debug('Object copy in progress.'); + return $this->showCopyProgress(); + } + } + + /** + * Show progress for copying + */ + protected function showCopyProgress() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + + include_once './Services/Object/classes/class.ilObjectCopyProgressTableGUI.php'; + $progress = new ilObjectCopyProgressTableGUI( + $this, + 'showCopyProgress', + (int) $_GET['ref_id'] + ); + $progress->setObjectInfo($this->targets_copy_id); + $progress->parse(); + $progress->init(); + $progress->setRedirectionUrl($ilCtrl->getParentReturn($this->parent_obj)); + + $tpl->setContent($progress->getHTML()); + } + + /** + * Update progress + */ + protected function updateProgress() + { + $json = new stdClass(); + $json->percentage = null; + $json->performed_steps = null; + + include_once './Services/CopyWizard/classes/class.ilCopyWizardOptions.php'; + $options = ilCopyWizardOptions::_getInstance((int) $_REQUEST['copy_id']); + $json->required_steps = $options->getRequiredSteps(); + $json->id = (int) $_REQUEST['copy_id']; + + ilLoggerFactory::getLogger('obj')->debug('Update copy progress: ' . json_encode($json)); + + echo json_encode($json); + exit; + } + + + /** + * Copy a container + * @return + */ + protected function copyContainer($a_target) + { + $ilLog = $this->log; + $ilCtrl = $this->ctrl; + + include_once('./Services/Link/classes/class.ilLink.php'); + include_once('Services/CopyWizard/classes/class.ilCopyWizardOptions.php'); + + $ilAccess = $this->access; + $ilErr = $this->error; + $rbacsystem = $this->rbacsystem; + $tree = $this->tree; + $ilUser = $this->user; + $ilCtrl = $this->ctrl; + + // Workaround for course in course copy + + $target_type = ilObject::_lookupType(ilObject::_lookupObjId($a_target)); + $source_type = ilObject::_lookupType(ilObject::_lookupObjId($this->getFirstSource())); + + if ($this->getSubMode() != self::SUBMODE_CONTENT_ONLY) { + if (!$rbacsystem->checkAccess('create', $a_target, $this->getType())) { + $this->log->notice('Permission denied for target: ' . $a_target . ' type: ' . $this->getType() . ' CREATE'); + ilUtil::sendFailure($this->lng->txt('permission_denied'), true); + $ilCtrl->returnToParent($this); + } + } + if (!$this->getFirstSource()) { + ilUtil::sendFailure($this->lng->txt('select_one'), true); + $ilCtrl->returnToParent($this); + return false; + } + + $options = $_POST['cp_options'] ? $_POST['cp_options'] : array(); + + + ilLoggerFactory::getLogger('obj')->debug('Copy container (sources): ' . print_r($this->getSources(), true)); + + $orig = ilObjectFactory::getInstanceByRefId($this->getFirstSource()); + $result = $orig->cloneAllObject( + $_COOKIE[session_name()], + $_COOKIE['ilClientId'], + $this->getType(), + $a_target, + $this->getFirstSource(), + $options, + false, + $this->getSubMode() + ); + + $this->targets_copy_id[$a_target] = $result['copy_id']; + + return $result; + } + + + + /** + * Show init screen + * Normally shown below the create and import form when creating a new object + * + * @param string $a_tplvar The tpl variable to fill + * @return + */ + public function showSourceSearch($a_tplvar) + { + $tpl = $this->tpl; + + // Disabled for performance + #if(!$this->sourceExists()) + #{ + # return false; + #} + + $this->unsetSession(); + $this->initFormSearch(); + + if ($a_tplvar) { + $tpl->setVariable($a_tplvar, $this->form->getHTML()); + } else { + return $this->form; + } + } + + + /** + * Check if there is any source object + * @return bool + */ + protected function sourceExists() + { + $ilUser = $this->user; + + return (bool) ilUtil::_getObjectsByOperations($this->getType(), 'copy', $ilUser->getId(), 1); + } + + /** + * Init search form + * @return + */ + protected function initFormSearch() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once './Services/Form/classes/class.ilPropertyFormGUI.php'; + $this->form = new ilPropertyFormGUI(); + $this->form->setTableWidth('600px'); + + $ilCtrl->setParameter($this, 'new_type', $this->getType()); + + #$ilCtrl->setParameter($this, 'cp_mode', self::SOURCE_SELECTION); + $this->form->setFormAction($ilCtrl->getFormAction($this)); + $this->form->setTitle($lng->txt($this->getType() . '_copy')); + + $this->form->addCommandButton('searchSource', $lng->txt('btn_next')); + $this->form->addCommandButton('cancel', $this->lng->txt('cancel')); + + $tit = new ilTextInputGUI($lng->txt('title'), 'tit'); + $tit->setSize(40); + $tit->setMaxLength(70); + $tit->setRequired(true); + $tit->setInfo($lng->txt('wizard_title_info')); + $this->form->addItem($tit); + } + + /** + * Unset session variables + * @return + */ + protected function unsetSession() + { + unset($_SESSION['source_query']); + $this->setSource(array()); + } } -?> diff --git a/Services/Object/classes/class.ilObjectCopyProgressTableGUI.php b/Services/Object/classes/class.ilObjectCopyProgressTableGUI.php index 5d73033fd98cc634c3a0b99fadf97e9afd6debc1..7dbcb3ae73d8f157061205d16212ebe50713e6d3 100644 --- a/Services/Object/classes/class.ilObjectCopyProgressTableGUI.php +++ b/Services/Object/classes/class.ilObjectCopyProgressTableGUI.php @@ -6,136 +6,133 @@ include_once './Services/Table/classes/class.ilTable2GUI.php'; /** * Table gui for copy progress - * + * * @author Stefan Meyer * @version $Id$ - * + * * * @ingroup ServicesObject */ class ilObjectCopyProgressTableGUI extends ilTable2GUI { - protected $objects = array(); - - /** - * Constructor - * @param type $a_parent_obj - * @param type $a_parent_cmd - * @param type $a_id - */ - public function __construct($a_parent_obj, $a_parent_cmd, $a_id) - { - $this->setId('obj_copy_progress_table_' . $a_id); - parent::__construct($a_parent_obj, $a_parent_cmd, ''); - } - - public function setObjectInfo($a_ref_ids) - { - $this->objects = $a_ref_ids; - } - - public function getObjects() - { - return $this->objects; - } - - public function setRedirectionUrl($a_url) - { - global $DIC; - $DIC->ui()->mainTemplate()->addOnLoadCode('il.CopyRedirection.setRedirectUrl("'.$a_url.'")'); - } - - /** - * Init Table - */ - public function init() - { - global $DIC; - - $tpl = $DIC->ui()->mainTemplate(); - $ctrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $tpl->addJavaScript('./Services/CopyWizard/js/ilCopyRedirection.js'); - $tpl->addOnLoadCode('il.CopyRedirection.checkDone()'); - $this->setExternalSorting(TRUE); - $this->setFormAction($ctrl->getFormAction($this->getParentObject())); - - $this->setRowTemplate('tpl.object_copy_progress_table_row.html', 'Services/Object'); - - $this->addColumn($lng->txt('obj_target_location'), ''); - $this->addColumn($lng->txt('obj_copy_progress'), ''); - } - - /** - * Fill row - * @param type $set - */ - public function fillRow($set) - { - global $DIC; - - $tpl = $DIC->ui()->mainTemplate(); - $ctrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->tpl->setVariable('VAL_ID', $set['ref_id']); - $this->tpl->setVariable('OBJ_TITLE', $set['title']); - - if (strlen($set['description'])) - { - $this->tpl->setVariable('VAL_DESC', $set['description']); - } - - $this->tpl->setVariable('TYPE_IMG', ilUtil::getTypeIconPath($set['type'], $set['obj_id'])); - $this->tpl->setVariable('TYPE_STR', $this->lng->txt('obj_' . $set['type'])); - - include_once './Services/UIComponent/ProgressBar/classes/class.ilProgressBar.php'; - $progress = ilProgressBar::getInstance(); - $progress->setType(ilProgressBar::TYPE_SUCCESS); - $progress->setMin(0); - $progress->setMax($set['max_steps']); - $progress->setCurrent(0); - $progress->setAnimated(TRUE); - $progress->setId($set['copy_id']); - - $ctrl->setParameter($this->getParentObject(), 'copy_id', $set['copy_id']); - $progress->setAsyncStatusUrl( - $ctrl->getLinkTarget( - $this->getParentObject(), - 'updateProgress', - '', - TRUE - ) - ); - - $progress->setAsynStatusTimeout(1); - $this->tpl->setVariable('PROGRESS_BAR', $progress->render()); - } - - /** - * Parse objects - */ - public function parse() - { - $counter = 0; - $set = array(); - foreach ($this->getObjects() as $ref_id => $copy_id) - { - $counter++; - $set[$counter]['ref_id'] = $ref_id; - $set[$counter]['copy_id'] = $copy_id; - $set[$counter]['obj_id'] = ilObject::_lookupObjId($ref_id); - $set[$counter]['type'] = ilObject::_lookupType(ilObject::_lookupObjId($ref_id)); - $set[$counter]['title'] = ilObject::_lookupTitle(ilObject::_lookupObjId($ref_id)); - $set[$counter]['description'] = ilObject::_lookupDescription(ilObject::_lookupObjId($ref_id)); - - include_once './Services/CopyWizard/classes/class.ilCopyWizardOptions.php'; - $copy_info = ilCopyWizardOptions::_getInstance($copy_id); - $copy_info->read(); - $set[$counter]['max_steps'] = $copy_info->getRequiredSteps(); - } - $this->setData($set); - } + protected $objects = array(); + + /** + * Constructor + * @param type $a_parent_obj + * @param type $a_parent_cmd + * @param type $a_id + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_id) + { + $this->setId('obj_copy_progress_table_' . $a_id); + parent::__construct($a_parent_obj, $a_parent_cmd, ''); + } + + public function setObjectInfo($a_ref_ids) + { + $this->objects = $a_ref_ids; + } + + public function getObjects() + { + return $this->objects; + } + + public function setRedirectionUrl($a_url) + { + global $DIC; + $DIC->ui()->mainTemplate()->addOnLoadCode('il.CopyRedirection.setRedirectUrl("' . $a_url . '")'); + } + + /** + * Init Table + */ + public function init() + { + global $DIC; + + $tpl = $DIC->ui()->mainTemplate(); + $ctrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $tpl->addJavaScript('./Services/CopyWizard/js/ilCopyRedirection.js'); + $tpl->addOnLoadCode('il.CopyRedirection.checkDone()'); + $this->setExternalSorting(true); + $this->setFormAction($ctrl->getFormAction($this->getParentObject())); + + $this->setRowTemplate('tpl.object_copy_progress_table_row.html', 'Services/Object'); + + $this->addColumn($lng->txt('obj_target_location'), ''); + $this->addColumn($lng->txt('obj_copy_progress'), ''); + } + + /** + * Fill row + * @param type $set + */ + public function fillRow($set) + { + global $DIC; + + $tpl = $DIC->ui()->mainTemplate(); + $ctrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->tpl->setVariable('VAL_ID', $set['ref_id']); + $this->tpl->setVariable('OBJ_TITLE', $set['title']); + + if (strlen($set['description'])) { + $this->tpl->setVariable('VAL_DESC', $set['description']); + } + + $this->tpl->setVariable('TYPE_IMG', ilUtil::getTypeIconPath($set['type'], $set['obj_id'])); + $this->tpl->setVariable('TYPE_STR', $this->lng->txt('obj_' . $set['type'])); + + include_once './Services/UIComponent/ProgressBar/classes/class.ilProgressBar.php'; + $progress = ilProgressBar::getInstance(); + $progress->setType(ilProgressBar::TYPE_SUCCESS); + $progress->setMin(0); + $progress->setMax($set['max_steps']); + $progress->setCurrent(0); + $progress->setAnimated(true); + $progress->setId($set['copy_id']); + + $ctrl->setParameter($this->getParentObject(), 'copy_id', $set['copy_id']); + $progress->setAsyncStatusUrl( + $ctrl->getLinkTarget( + $this->getParentObject(), + 'updateProgress', + '', + true + ) + ); + + $progress->setAsynStatusTimeout(1); + $this->tpl->setVariable('PROGRESS_BAR', $progress->render()); + } + + /** + * Parse objects + */ + public function parse() + { + $counter = 0; + $set = array(); + foreach ($this->getObjects() as $ref_id => $copy_id) { + $counter++; + $set[$counter]['ref_id'] = $ref_id; + $set[$counter]['copy_id'] = $copy_id; + $set[$counter]['obj_id'] = ilObject::_lookupObjId($ref_id); + $set[$counter]['type'] = ilObject::_lookupType(ilObject::_lookupObjId($ref_id)); + $set[$counter]['title'] = ilObject::_lookupTitle(ilObject::_lookupObjId($ref_id)); + $set[$counter]['description'] = ilObject::_lookupDescription(ilObject::_lookupObjId($ref_id)); + + include_once './Services/CopyWizard/classes/class.ilCopyWizardOptions.php'; + $copy_info = ilCopyWizardOptions::_getInstance($copy_id); + $copy_info->read(); + $set[$counter]['max_steps'] = $copy_info->getRequiredSteps(); + } + $this->setData($set); + } } -?> \ No newline at end of file diff --git a/Services/Object/classes/class.ilObjectCopySearchResultTableGUI.php b/Services/Object/classes/class.ilObjectCopySearchResultTableGUI.php index f20d591addfeda90f44d24a71dc620aff01e4fb9..bf8ccd041438d43bfb7bbed5cdd664019963d095 100644 --- a/Services/Object/classes/class.ilObjectCopySearchResultTableGUI.php +++ b/Services/Object/classes/class.ilObjectCopySearchResultTableGUI.php @@ -1,24 +1,24 @@ - * + * * @ingroup ServicesObject */ class ilObjectCopySearchResultTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - /** - * @var ilObjectDefinition - */ - protected $obj_definition; + /** + * @var ilObjectDefinition + */ + protected $obj_definition; - private $type = ''; - private $selected_reference = null; - - /** - * - * @param object $a_parent_class - * @param string $a_parent_cmd - * @return - */ - public function __construct($a_parent_class,$a_parent_cmd,$a_type) - { - global $DIC; + private $type = ''; + private $selected_reference = null; + + /** + * + * @param object $a_parent_class + * @param string $a_parent_cmd + * @return + */ + public function __construct($a_parent_class, $a_parent_cmd, $a_type) + { + global $DIC; - $this->user = $DIC->user(); - $this->obj_definition = $DIC["objDefinition"]; - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $ilUser = $DIC->user(); - $objDefinition = $DIC["objDefinition"]; - - $this->setId('obj_copy_'.$a_type); - parent::__construct($a_parent_class,$a_parent_cmd); - $this->type = $a_type; - - $this->lng = $lng; - $this->ctrl = $ilCtrl; - - if(!$objDefinition->isPlugin($this->type)) - { - $title = $this->lng->txt('obj_'.$this->type.'_duplicate'); - } - else - { - include_once "Services/Component/classes/class.ilPlugin.php"; - $plugin = ilObjectPlugin::getPluginObjectByType($this->type); - $title = $plugin->txt('obj_'.$this->type.'_duplicate'); - } - - $this->setTitle($title); - $ilUser->getPref('search_max_hits'); - - $this->addColumn($this->lng->txt('search_title_description'),'title','99%'); - - $this->setEnableHeader(true); - $this->setRowTemplate("tpl.obj_copy_search_result_row.html", "Services/Object"); - $this->setEnableTitle(true); - $this->setEnableNumInfo(true); - $this->setDefaultOrderField('title'); - $this->setShowRowsSelector(TRUE); - - if($objDefinition->isContainer($this->type)) - { - $this->addCommandButton('saveSource', $this->lng->txt('btn_next')); - } - else - { - $this->addCommandButton('saveSource', $title); - } - - $this->addCommandButton('cancel', $this->lng->txt('btn_back')); - } - - /** - * Set selected reference - * @param int $a_selected_reference - * @return - */ - public function setSelectedReference($a_selected_reference) - { - $this->selected_reference = $a_selected_reference; - } - - /** - * get selected reference - * @return - */ - public function getSelectedReference() - { - return $this->selected_reference; - } - - /** - * Parse search results - * @param object $a_res - * @return - */ - public function parseSearchResults($a_res) - { - foreach($a_res as $obj_id => $references) - { - $r['title'] = ilObject::_lookupTitle($obj_id); - $r['desc'] = ilObject::_lookupDescription($obj_id); - $r['obj_id'] = $obj_id; - $r['refs'] = $references; - - $rows[] = $r; - } - - $this->setData($rows ? $rows : array()); - } - - /** - * fill table rows - * @param array $set - * @return - */ - protected function fillRow($set) - { - $this->tpl->setVariable('VAL_TITLE',$set['title']); - if(strlen($set['desc'])) - { - $this->tpl->setVariable('VAL_DESC',$set['desc']); - } - $this->tpl->setVariable('TXT_PATHES',$this->lng->txt('pathes')); - - foreach((array) $set['refs'] as $reference) - { - include_once './Services/Tree/classes/class.ilPathGUI.php'; - $path = new ilPathGUI(); - - $this->tpl->setCurrentBlock('path'); - $this->tpl->setVariable('VAL_ID',$reference); - $this->tpl->setVariable('VAL_PATH',$path->getPath(ROOT_FOLDER_ID, $reference)); - - if($reference == $this->getSelectedReference()) - { - $this->tpl->setVariable('VAL_CHECKED','checked="checked"'); - } - - $this->tpl->parseCurrentBlock(); - } - } + $this->user = $DIC->user(); + $this->obj_definition = $DIC["objDefinition"]; + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $ilUser = $DIC->user(); + $objDefinition = $DIC["objDefinition"]; + + $this->setId('obj_copy_' . $a_type); + parent::__construct($a_parent_class, $a_parent_cmd); + $this->type = $a_type; + + $this->lng = $lng; + $this->ctrl = $ilCtrl; + + if (!$objDefinition->isPlugin($this->type)) { + $title = $this->lng->txt('obj_' . $this->type . '_duplicate'); + } else { + include_once "Services/Component/classes/class.ilPlugin.php"; + $plugin = ilObjectPlugin::getPluginObjectByType($this->type); + $title = $plugin->txt('obj_' . $this->type . '_duplicate'); + } + + $this->setTitle($title); + $ilUser->getPref('search_max_hits'); + + $this->addColumn($this->lng->txt('search_title_description'), 'title', '99%'); + + $this->setEnableHeader(true); + $this->setRowTemplate("tpl.obj_copy_search_result_row.html", "Services/Object"); + $this->setEnableTitle(true); + $this->setEnableNumInfo(true); + $this->setDefaultOrderField('title'); + $this->setShowRowsSelector(true); + + if ($objDefinition->isContainer($this->type)) { + $this->addCommandButton('saveSource', $this->lng->txt('btn_next')); + } else { + $this->addCommandButton('saveSource', $title); + } + + $this->addCommandButton('cancel', $this->lng->txt('btn_back')); + } + + /** + * Set selected reference + * @param int $a_selected_reference + * @return + */ + public function setSelectedReference($a_selected_reference) + { + $this->selected_reference = $a_selected_reference; + } + + /** + * get selected reference + * @return + */ + public function getSelectedReference() + { + return $this->selected_reference; + } + + /** + * Parse search results + * @param object $a_res + * @return + */ + public function parseSearchResults($a_res) + { + foreach ($a_res as $obj_id => $references) { + $r['title'] = ilObject::_lookupTitle($obj_id); + $r['desc'] = ilObject::_lookupDescription($obj_id); + $r['obj_id'] = $obj_id; + $r['refs'] = $references; + + $rows[] = $r; + } + + $this->setData($rows ? $rows : array()); + } + + /** + * fill table rows + * @param array $set + * @return + */ + protected function fillRow($set) + { + $this->tpl->setVariable('VAL_TITLE', $set['title']); + if (strlen($set['desc'])) { + $this->tpl->setVariable('VAL_DESC', $set['desc']); + } + $this->tpl->setVariable('TXT_PATHES', $this->lng->txt('pathes')); + + foreach ((array) $set['refs'] as $reference) { + include_once './Services/Tree/classes/class.ilPathGUI.php'; + $path = new ilPathGUI(); + + $this->tpl->setCurrentBlock('path'); + $this->tpl->setVariable('VAL_ID', $reference); + $this->tpl->setVariable('VAL_PATH', $path->getPath(ROOT_FOLDER_ID, $reference)); + + if ($reference == $this->getSelectedReference()) { + $this->tpl->setVariable('VAL_CHECKED', 'checked="checked"'); + } + + $this->tpl->parseCurrentBlock(); + } + } } diff --git a/Services/Object/classes/class.ilObjectCopySelectionTableGUI.php b/Services/Object/classes/class.ilObjectCopySelectionTableGUI.php index 61e59f3b7701aeea73f3b481d783f0a73f3bdf63..870a347fa882a7258af37d0d1aeaa499df0a7d82 100644 --- a/Services/Object/classes/class.ilObjectCopySelectionTableGUI.php +++ b/Services/Object/classes/class.ilObjectCopySelectionTableGUI.php @@ -6,242 +6,222 @@ include_once './Services/CopyWizard/classes/class.ilCopyWizardOptions.php'; /** * Selection of subitems - * + * * @version $Id$ * @author Stefan Meyer */ class ilObjectCopySelectionTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - /** - * @var ilObjectDefinition - */ - protected $obj_definition; + /** + * @var ilObjectDefinition + */ + protected $obj_definition; - /** - * @var ilTree - */ - protected $tree; + /** + * @var ilTree + */ + protected $tree; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - private $type = ''; - private $selected_reference = null; - - /** - * - * @param object $a_parent_class - * @param string $a_parent_cmd - * @return - */ - public function __construct($a_parent_class,$a_parent_cmd,$a_type,$a_back_cmd) - { - global $DIC; + private $type = ''; + private $selected_reference = null; + + /** + * + * @param object $a_parent_class + * @param string $a_parent_cmd + * @return + */ + public function __construct($a_parent_class, $a_parent_cmd, $a_type, $a_back_cmd) + { + global $DIC; - $this->user = $DIC->user(); - $this->obj_definition = $DIC["objDefinition"]; - $this->tree = $DIC->repositoryTree(); - $this->access = $DIC->access(); - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $ilUser = $DIC->user(); - $objDefinition = $DIC["objDefinition"]; - - parent::__construct($a_parent_class,$a_parent_cmd); - $this->type = $a_type; - - $this->lng = $lng; - $this->ctrl = $ilCtrl; - - $this->setTitle($this->lng->txt($this->type.'_wizard_page')); - - - $this->addColumn($this->lng->txt('title'),'','55%'); - $this->addColumn($this->lng->txt('copy'),'','15%'); - $this->addColumn($this->lng->txt('link'),'','15%'); - $this->addColumn($this->lng->txt('omit'),'','15%'); - - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($this->getParentObject())); - $this->setRowTemplate("tpl.obj_copy_selection_row.html", "Services/Object"); - $this->setEnableTitle(true); - $this->setEnableNumInfo(true); - $this->setLimit(999999); - - $this->setFormName('cmd'); + $this->user = $DIC->user(); + $this->obj_definition = $DIC["objDefinition"]; + $this->tree = $DIC->repositoryTree(); + $this->access = $DIC->access(); + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $ilUser = $DIC->user(); + $objDefinition = $DIC["objDefinition"]; + + parent::__construct($a_parent_class, $a_parent_cmd); + $this->type = $a_type; + + $this->lng = $lng; + $this->ctrl = $ilCtrl; + + $this->setTitle($this->lng->txt($this->type . '_wizard_page')); + + + $this->addColumn($this->lng->txt('title'), '', '55%'); + $this->addColumn($this->lng->txt('copy'), '', '15%'); + $this->addColumn($this->lng->txt('link'), '', '15%'); + $this->addColumn($this->lng->txt('omit'), '', '15%'); + + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($this->getParentObject())); + $this->setRowTemplate("tpl.obj_copy_selection_row.html", "Services/Object"); + $this->setEnableTitle(true); + $this->setEnableNumInfo(true); + $this->setLimit(999999); + + $this->setFormName('cmd'); - $this->addCommandButton('copyContainerToTargets', $this->lng->txt('obj_'.$this->type.'_duplicate')); + $this->addCommandButton('copyContainerToTargets', $this->lng->txt('obj_' . $this->type . '_duplicate')); if ($a_back_cmd == "") { // see bug #25991 $this->addCommandButton("cancel", $this->lng->txt('cancel')); } else { $this->addCommandButton($a_back_cmd, $this->lng->txt('btn_back')); } - } - - /** - * Get object type of source - * @return - */ - public function getType() - { - return $this->type; - } - - /** - * - * @param object $a_source - * @return - */ - public function parseSource($a_source) - { - $tree = $this->tree; - $objDefinition = $this->obj_definition; - $ilAccess = $this->access; - - $first = true; - foreach($tree->getSubTree($root = $tree->getNodeData($a_source)) as $node) - { - if($node['type'] == 'rolf') - { - continue; - } - if(!$ilAccess->checkAccess('visible','',$node['child'])) - { - continue; - } - - - $r = array(); - $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['copy'] = $objDefinition->allowCopy($node['type']); - $r['perm_copy'] = $ilAccess->checkAccess('copy','',$node['child']); - $r['link'] = $objDefinition->allowLink($node['type']); - $r['perm_link'] = true; - - // #11905 - if(!trim($r['title']) && $r['type'] == 'sess') - { - // use session date as title if no object title - include_once('./Modules/Session/classes/class.ilSessionAppointment.php'); - $app_info = ilSessionAppointment::_lookupAppointment($node["obj_id"]); - $r['title'] = ilSessionAppointment::_appointmentToString($app_info['start'], $app_info['end'],$app_info['fullday']); - } - - $rows[] = $r; - - $first = false; - } - $rows[] = array('last' => true); - $this->setData((array) $rows); - } - - /** - * @see ilTable2GUI::fillRow() - */ - protected function fillRow($s) - { - if($s['last']) - { - $this->tpl->setCurrentBlock('footer_copy'); - $this->tpl->setVariable('TXT_COPY_ALL',$this->lng->txt('copy_all')); - $this->tpl->parseCurrentBlock(); - $this->tpl->setCurrentBlock('footer_link'); - $this->tpl->setVariable('TXT_LINK_ALL',$this->lng->txt('link_all')); - $this->tpl->parseCurrentBlock(); - $this->tpl->setCurrentBlock('footer_omit'); - $this->tpl->setVariable('TXT_OMIT_ALL',$this->lng->txt('omit_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['source']) - { - return true; - } + } + + /** + * Get object type of source + * @return + */ + public function getType() + { + return $this->type; + } + + /** + * + * @param object $a_source + * @return + */ + public function parseSource($a_source) + { + $tree = $this->tree; + $objDefinition = $this->obj_definition; + $ilAccess = $this->access; + + $first = true; + foreach ($tree->getSubTree($root = $tree->getNodeData($a_source)) as $node) { + if ($node['type'] == 'rolf') { + continue; + } + if (!$ilAccess->checkAccess('visible', '', $node['child'])) { + continue; + } + + + $r = array(); + $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['copy'] = $objDefinition->allowCopy($node['type']); + $r['perm_copy'] = $ilAccess->checkAccess('copy', '', $node['child']); + $r['link'] = $objDefinition->allowLink($node['type']); + $r['perm_link'] = true; + + // #11905 + if (!trim($r['title']) && $r['type'] == 'sess') { + // use session date as title if no object title + include_once('./Modules/Session/classes/class.ilSessionAppointment.php'); + $app_info = ilSessionAppointment::_lookupAppointment($node["obj_id"]); + $r['title'] = ilSessionAppointment::_appointmentToString($app_info['start'], $app_info['end'], $app_info['fullday']); + } + + $rows[] = $r; + + $first = false; + } + $rows[] = array('last' => true); + $this->setData((array) $rows); + } - // Copy - if($s['perm_copy'] and $s['copy']) - { - $this->tpl->setCurrentBlock('radio_copy'); - $this->tpl->setVariable('TXT_COPY',$this->lng->txt('copy')); - $this->tpl->setVariable('NAME_COPY','cp_options['.$s['ref_id'].'][type]'); - $this->tpl->setVariable('VALUE_COPY',ilCopyWizardOptions::COPY_WIZARD_COPY); - $this->tpl->setVariable('ID_COPY',$s['depth'].'_'.$s['type'].'_'.$s['ref_id'].'_copy'); - $this->tpl->setVariable('COPY_CHECKED','checked="checked"'); - $this->tpl->parseCurrentBlock(); - } - elseif($s['copy']) - { - $this->tpl->setCurrentBlock('missing_copy_perm'); - $this->tpl->setVariable('TXT_MISSING_COPY_PERM',$this->lng->txt('missing_perm')); - $this->tpl->parseCurrentBlock(); - } + /** + * @see ilTable2GUI::fillRow() + */ + protected function fillRow($s) + { + if ($s['last']) { + $this->tpl->setCurrentBlock('footer_copy'); + $this->tpl->setVariable('TXT_COPY_ALL', $this->lng->txt('copy_all')); + $this->tpl->parseCurrentBlock(); + $this->tpl->setCurrentBlock('footer_link'); + $this->tpl->setVariable('TXT_LINK_ALL', $this->lng->txt('link_all')); + $this->tpl->parseCurrentBlock(); + $this->tpl->setCurrentBlock('footer_omit'); + $this->tpl->setVariable('TXT_OMIT_ALL', $this->lng->txt('omit_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['source']) { + return true; + } - - // Link - if($s['perm_link'] and $s['link']) - { - $this->tpl->setCurrentBlock('radio_link'); - $this->tpl->setVariable('TXT_LINK',$this->lng->txt('link')); - $this->tpl->setVariable('NAME_LINK','cp_options['.$s['ref_id'].'][type]'); - $this->tpl->setVariable('VALUE_LINK',ilCopyWizardOptions::COPY_WIZARD_LINK); - $this->tpl->setVariable('ID_LINK',$s['depth'].'_'.$s['type'].'_'.$s['ref_id'].'_link'); - if(!$s['copy'] or !$s['perm_copy']) - { - $this->tpl->setVariable('LINK_CHECKED','checked="checked"'); - } - $this->tpl->parseCurrentBlock(); - } - elseif($s['link']) - { - $this->tpl->setCurrentBlock('missing_link_perm'); - $this->tpl->setVariable('TXT_MISSING_LINK_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',ilCopyWizardOptions::COPY_WIZARD_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(); - - } + // Copy + if ($s['perm_copy'] and $s['copy']) { + $this->tpl->setCurrentBlock('radio_copy'); + $this->tpl->setVariable('TXT_COPY', $this->lng->txt('copy')); + $this->tpl->setVariable('NAME_COPY', 'cp_options[' . $s['ref_id'] . '][type]'); + $this->tpl->setVariable('VALUE_COPY', ilCopyWizardOptions::COPY_WIZARD_COPY); + $this->tpl->setVariable('ID_COPY', $s['depth'] . '_' . $s['type'] . '_' . $s['ref_id'] . '_copy'); + $this->tpl->setVariable('COPY_CHECKED', 'checked="checked"'); + $this->tpl->parseCurrentBlock(); + } elseif ($s['copy']) { + $this->tpl->setCurrentBlock('missing_copy_perm'); + $this->tpl->setVariable('TXT_MISSING_COPY_PERM', $this->lng->txt('missing_perm')); + $this->tpl->parseCurrentBlock(); + } - - + + // Link + if ($s['perm_link'] and $s['link']) { + $this->tpl->setCurrentBlock('radio_link'); + $this->tpl->setVariable('TXT_LINK', $this->lng->txt('link')); + $this->tpl->setVariable('NAME_LINK', 'cp_options[' . $s['ref_id'] . '][type]'); + $this->tpl->setVariable('VALUE_LINK', ilCopyWizardOptions::COPY_WIZARD_LINK); + $this->tpl->setVariable('ID_LINK', $s['depth'] . '_' . $s['type'] . '_' . $s['ref_id'] . '_link'); + if (!$s['copy'] or !$s['perm_copy']) { + $this->tpl->setVariable('LINK_CHECKED', 'checked="checked"'); + } + $this->tpl->parseCurrentBlock(); + } elseif ($s['link']) { + $this->tpl->setCurrentBlock('missing_link_perm'); + $this->tpl->setVariable('TXT_MISSING_LINK_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', ilCopyWizardOptions::COPY_WIZARD_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(); + } } -?> \ No newline at end of file diff --git a/Services/Object/classes/class.ilObjectDataCache.php b/Services/Object/classes/class.ilObjectDataCache.php index 40a0d4a1ee939defc1caf48a1323fc7c626b60f2..ba55207c96d5bc8eb04c97e2545459c38f07d298 100644 --- a/Services/Object/classes/class.ilObjectDataCache.php +++ b/Services/Object/classes/class.ilObjectDataCache.php @@ -12,350 +12,326 @@ */ class ilObjectDataCache { - - var $db = null; - var $reference_cache = array(); - var $object_data_cache = array(); - var $description_trans = array(); - - function __construct() - { - global $DIC; - - $ilDB = $DIC->database(); - - $this->db = $ilDB; - } - - function deleteCachedEntry($a_obj_id) - { - unset($this->object_data_cache[$a_obj_id]); - } - - function lookupObjId($a_ref_id) - { - if(!$this->__isReferenceCached($a_ref_id)) - { -//echo"-objidmissed-$a_ref_id-"; - $obj_id = $this->__storeReference($a_ref_id); - $this->__storeObjectData($obj_id); - } - return (int) @$this->reference_cache[$a_ref_id]; - } - - function lookupTitle($a_obj_id) - { - if(!$this->__isObjectCached($a_obj_id)) - { - $this->__storeObjectData($a_obj_id); - } - return @$this->object_data_cache[$a_obj_id]['title']; - } - - function lookupType($a_obj_id) - { - if(!$this->__isObjectCached($a_obj_id)) - { -//echo"-typemissed-$a_obj_id-"; - $this->__storeObjectData($a_obj_id); - } - return @$this->object_data_cache[$a_obj_id]['type']; - } - - function lookupOwner($a_obj_id) - { - if(!$this->__isObjectCached($a_obj_id)) - { - $this->__storeObjectData($a_obj_id); - } - return @$this->object_data_cache[$a_obj_id]['owner']; - } - - function lookupDescription($a_obj_id) - { - if(!$this->__isObjectCached($a_obj_id)) - { - $this->__storeObjectData($a_obj_id); - } - return @$this->object_data_cache[$a_obj_id]['description']; - } - - function lookupLastUpdate($a_obj_id) - { - if(!$this->__isObjectCached($a_obj_id)) - { - $this->__storeObjectData($a_obj_id); - } - return @$this->object_data_cache[$a_obj_id]['last_update']; - } - - /** - * Check if supports centralized offline handling and is offline - * @param $a_obj_id - * @return bool - */ - public function lookupOfflineStatus($a_obj_id) - { - if(!$this->__isObjectCached($a_obj_id)) - { - $this->__storeObjectData($a_obj_id); - } - return (bool) $this->object_data_cache[$a_obj_id]['offline']; - } - - // PRIVATE - - /** - * checks whether an reference id is already in cache or not - * - * @access private - * @param int $a_ref_id reference id - * @return boolean - */ - function __isReferenceCached($a_ref_id) - { - #return false; - #static $cached = 0; - #static $not_cached = 0; - - if(@$this->reference_cache[$a_ref_id]) - { - #echo "Reference ". ++$cached ."cached
                  "; - return true; - } - #echo "Reference ". ++$not_cached ." not cached
                  "; - return false; - - } - - /** - * checks whether an object is aleady in cache or not - * - * @access private - * @param int $a_obj_id object id - * @return boolean - */ - function __isObjectCached($a_obj_id) - { - static $cached = 0; - static $not_cached = 0; - - - if(@$this->object_data_cache[$a_obj_id]) - { - #echo "Object ". ++$cached ."cached
                  "; - return true; - } - #echo "Object ". ++$not_cached ." not cached
                  "; - return false; - } - - - /** - * Stores Reference in cache. - * Maybe it could be useful to find all references of that object andd store them also in the cache. - * But this would be an extra query. - * - * @access private - * @param int $a_ref_id reference id - * @return int $obj_id - */ - function __storeReference($a_ref_id) - { - $ilDB = $this->db; - - $query = "SELECT obj_id FROM object_reference WHERE ref_id = ".$ilDB->quote($a_ref_id,'integer'); - $res = $this->db->query($query); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_ASSOC)) - { - $this->reference_cache[$a_ref_id] = $row['obj_id']; - } - return (int) @$this->reference_cache[$a_ref_id]; - } - - /** - * Stores object data in cache - * - * @access private - * @param int $a_obj_id object id - * @return bool - */ - function __storeObjectData($a_obj_id, $a_lang = "") - { - global $DIC; - - $ilDB = $this->db; - $objDefinition = $DIC["objDefinition"]; - $ilUser = $DIC["ilUser"]; - - if (is_object($ilUser) && $a_lang == "") - { - $a_lang = $ilUser->getLanguage(); - } - - $query = "SELECT * FROM object_data WHERE obj_id = ". - $ilDB->quote($a_obj_id ,'integer'); - $res = $this->db->query($query); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - $this->object_data_cache[$a_obj_id]['title'] = $row->title; - $this->object_data_cache[$a_obj_id]['description'] = $row->description; - $this->object_data_cache[$a_obj_id]['type'] = $row->type; - $this->object_data_cache[$a_obj_id]['owner'] = $row->owner; - $this->object_data_cache[$a_obj_id]['last_update'] = $row->last_update; - $this->object_data_cache[$a_obj_id]['offline'] = $row->offline; - - if (is_object($objDefinition)) - { - $translation_type = $objDefinition->getTranslationType($row->type); - } - - if ($translation_type == "db") - { - if (!$this->trans_loaded[$a_obj_id]) - { - $q = "SELECT title,description FROM object_translation ". - "WHERE obj_id = ".$ilDB->quote($a_obj_id,'integer')." ". - "AND lang_code = ".$ilDB->quote($a_lang,'text')." ". - "AND NOT lang_default = 1"; - $r = $ilDB->query($q); - - $row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT); - if ($row) - { - $this->object_data_cache[$a_obj_id]['title'] = $row->title; - $this->object_data_cache[$a_obj_id]['description'] = $row->description; - $this->description_trans[] = $a_obj_id; - } - $this->trans_loaded[$a_obj_id] = true; - } - } - } - - return true; - } - - function isTranslatedDescription($a_obj_id) - { - return (is_array($this->description_trans) && - in_array($a_obj_id, $this->description_trans)); - } - - /** - * Stores object data in cache - * - * @access private - * @param int $a_obj_id object id - * @return bool - */ - function preloadObjectCache($a_obj_ids, $a_lang = "") - { - global $DIC; - - $ilDB = $this->db; - $objDefinition = $DIC["objDefinition"]; - $ilUser = $DIC["ilUser"]; - - if (is_object($ilUser) && $a_lang == "") - { - $a_lang = $ilUser->getLanguage(); - } - if (!is_array($a_obj_ids)) return; - if (count($a_obj_ids) == 0) return; - - - $query = "SELECT * FROM object_data ". - "WHERE ".$ilDB->in('obj_id',$a_obj_ids,false,'integer'); - $res = $ilDB->query($query); - $db_trans = array(); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - - // this if fixes #9960 - if (!$this->trans_loaded[$row->obj_id]) - { - $this->object_data_cache[$row->obj_id]['title'] = $row->title; - $this->object_data_cache[$row->obj_id]['description'] = $row->description; - } - $this->object_data_cache[$row->obj_id]['type'] = $row->type; - $this->object_data_cache[$row->obj_id]['owner'] = $row->owner; - $this->object_data_cache[$row->obj_id]['last_update'] = $row->last_update; - $this->object_data_cache[$row->obj_id]['offline'] = $row->offline; - - if (is_object($objDefinition)) - { - $translation_type = $objDefinition->getTranslationType($row->type); - } - - if ($translation_type == "db") - { - $db_trans[$row->obj_id] = $row->obj_id; - } - } - if (count($db_trans) > 0) - { - $this->preloadTranslations($db_trans, $a_lang); - } - } - - /** - * Preload translation informations - * - * @param array $a_obj_ids array of object ids - */ - function preloadTranslations($a_obj_ids, $a_lang) - { - $ilDB = $this->db; - - $obj_ids = array(); - foreach ($a_obj_ids as $id) - { - // do not load an id more than one time - if (!$this->trans_loaded[$id]) - { - $obj_ids[] = $id; - $this->trans_loaded[$id] = true; - } - } - if (count($obj_ids) > 0) - { - $q = "SELECT obj_id, title, description FROM object_translation ". - "WHERE ".$ilDB->in('obj_id', $obj_ids, false, 'integer')." ". - "AND lang_code = ".$ilDB->quote($a_lang, 'text')." ". - "AND NOT lang_default = 1"; - $r = $ilDB->query($q); - while ($row2 = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - $this->object_data_cache[$row2->obj_id]['title'] = $row2->title; - $this->object_data_cache[$row2->obj_id]['description'] = $row2->description; - $this->description_trans[] = $row2->obj_id; - } - } - } - - function preloadReferenceCache($a_ref_ids, $a_incl_obj = true) - { - $ilDB = $this->db; - - if (!is_array($a_ref_ids)) return; - if (count($a_ref_ids) == 0) return; - - $query = "SELECT ref_id, obj_id FROM object_reference ". - "WHERE ".$ilDB->in('ref_id',$a_ref_ids,false,'integer'); - $res = $ilDB->query($query); - - $obj_ids = array(); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_ASSOC)) - { - $this->reference_cache[$row['ref_id']] = $row['obj_id']; -//echo "
                  store_ref-".$row['ref_id']."-".$row['obj_id']."-"; - $obj_ids[] = $row['obj_id']; - } - if ($a_incl_obj) - { - $this->preloadObjectCache($obj_ids); - } - } - + public $db = null; + public $reference_cache = array(); + public $object_data_cache = array(); + public $description_trans = array(); + + public function __construct() + { + global $DIC; + + $ilDB = $DIC->database(); + + $this->db = $ilDB; + } + + public function deleteCachedEntry($a_obj_id) + { + unset($this->object_data_cache[$a_obj_id]); + } + + public function lookupObjId($a_ref_id) + { + if (!$this->__isReferenceCached($a_ref_id)) { + //echo"-objidmissed-$a_ref_id-"; + $obj_id = $this->__storeReference($a_ref_id); + $this->__storeObjectData($obj_id); + } + return (int) @$this->reference_cache[$a_ref_id]; + } + + public function lookupTitle($a_obj_id) + { + if (!$this->__isObjectCached($a_obj_id)) { + $this->__storeObjectData($a_obj_id); + } + return @$this->object_data_cache[$a_obj_id]['title']; + } + + public function lookupType($a_obj_id) + { + if (!$this->__isObjectCached($a_obj_id)) { + //echo"-typemissed-$a_obj_id-"; + $this->__storeObjectData($a_obj_id); + } + return @$this->object_data_cache[$a_obj_id]['type']; + } + + public function lookupOwner($a_obj_id) + { + if (!$this->__isObjectCached($a_obj_id)) { + $this->__storeObjectData($a_obj_id); + } + return @$this->object_data_cache[$a_obj_id]['owner']; + } + + public function lookupDescription($a_obj_id) + { + if (!$this->__isObjectCached($a_obj_id)) { + $this->__storeObjectData($a_obj_id); + } + return @$this->object_data_cache[$a_obj_id]['description']; + } + + public function lookupLastUpdate($a_obj_id) + { + if (!$this->__isObjectCached($a_obj_id)) { + $this->__storeObjectData($a_obj_id); + } + return @$this->object_data_cache[$a_obj_id]['last_update']; + } + + /** + * Check if supports centralized offline handling and is offline + * @param $a_obj_id + * @return bool + */ + public function lookupOfflineStatus($a_obj_id) + { + if (!$this->__isObjectCached($a_obj_id)) { + $this->__storeObjectData($a_obj_id); + } + return (bool) $this->object_data_cache[$a_obj_id]['offline']; + } + + // PRIVATE + + /** + * checks whether an reference id is already in cache or not + * + * @access private + * @param int $a_ref_id reference id + * @return boolean + */ + public function __isReferenceCached($a_ref_id) + { + #return false; + #static $cached = 0; + #static $not_cached = 0; + + if (@$this->reference_cache[$a_ref_id]) { + #echo "Reference ". ++$cached ."cached
                  "; + return true; + } + #echo "Reference ". ++$not_cached ." not cached
                  "; + return false; + } + + /** + * checks whether an object is aleady in cache or not + * + * @access private + * @param int $a_obj_id object id + * @return boolean + */ + public function __isObjectCached($a_obj_id) + { + static $cached = 0; + static $not_cached = 0; + + + if (@$this->object_data_cache[$a_obj_id]) { + #echo "Object ". ++$cached ."cached
                  "; + return true; + } + #echo "Object ". ++$not_cached ." not cached
                  "; + return false; + } + + + /** + * Stores Reference in cache. + * Maybe it could be useful to find all references of that object andd store them also in the cache. + * But this would be an extra query. + * + * @access private + * @param int $a_ref_id reference id + * @return int $obj_id + */ + public function __storeReference($a_ref_id) + { + $ilDB = $this->db; + + $query = "SELECT obj_id FROM object_reference WHERE ref_id = " . $ilDB->quote($a_ref_id, 'integer'); + $res = $this->db->query($query); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_ASSOC)) { + $this->reference_cache[$a_ref_id] = $row['obj_id']; + } + return (int) @$this->reference_cache[$a_ref_id]; + } + + /** + * Stores object data in cache + * + * @access private + * @param int $a_obj_id object id + * @return bool + */ + public function __storeObjectData($a_obj_id, $a_lang = "") + { + global $DIC; + + $ilDB = $this->db; + $objDefinition = $DIC["objDefinition"]; + $ilUser = $DIC["ilUser"]; + + if (is_object($ilUser) && $a_lang == "") { + $a_lang = $ilUser->getLanguage(); + } + + $query = "SELECT * FROM object_data WHERE obj_id = " . + $ilDB->quote($a_obj_id, 'integer'); + $res = $this->db->query($query); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + $this->object_data_cache[$a_obj_id]['title'] = $row->title; + $this->object_data_cache[$a_obj_id]['description'] = $row->description; + $this->object_data_cache[$a_obj_id]['type'] = $row->type; + $this->object_data_cache[$a_obj_id]['owner'] = $row->owner; + $this->object_data_cache[$a_obj_id]['last_update'] = $row->last_update; + $this->object_data_cache[$a_obj_id]['offline'] = $row->offline; + + if (is_object($objDefinition)) { + $translation_type = $objDefinition->getTranslationType($row->type); + } + + if ($translation_type == "db") { + if (!$this->trans_loaded[$a_obj_id]) { + $q = "SELECT title,description FROM object_translation " . + "WHERE obj_id = " . $ilDB->quote($a_obj_id, 'integer') . " " . + "AND lang_code = " . $ilDB->quote($a_lang, 'text') . " " . + "AND NOT lang_default = 1"; + $r = $ilDB->query($q); + + $row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT); + if ($row) { + $this->object_data_cache[$a_obj_id]['title'] = $row->title; + $this->object_data_cache[$a_obj_id]['description'] = $row->description; + $this->description_trans[] = $a_obj_id; + } + $this->trans_loaded[$a_obj_id] = true; + } + } + } + + return true; + } + + public function isTranslatedDescription($a_obj_id) + { + return (is_array($this->description_trans) && + in_array($a_obj_id, $this->description_trans)); + } + + /** + * Stores object data in cache + * + * @access private + * @param int $a_obj_id object id + * @return bool + */ + public function preloadObjectCache($a_obj_ids, $a_lang = "") + { + global $DIC; + + $ilDB = $this->db; + $objDefinition = $DIC["objDefinition"]; + $ilUser = $DIC["ilUser"]; + + if (is_object($ilUser) && $a_lang == "") { + $a_lang = $ilUser->getLanguage(); + } + if (!is_array($a_obj_ids)) { + return; + } + if (count($a_obj_ids) == 0) { + return; + } + + + $query = "SELECT * FROM object_data " . + "WHERE " . $ilDB->in('obj_id', $a_obj_ids, false, 'integer'); + $res = $ilDB->query($query); + $db_trans = array(); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + + // this if fixes #9960 + if (!$this->trans_loaded[$row->obj_id]) { + $this->object_data_cache[$row->obj_id]['title'] = $row->title; + $this->object_data_cache[$row->obj_id]['description'] = $row->description; + } + $this->object_data_cache[$row->obj_id]['type'] = $row->type; + $this->object_data_cache[$row->obj_id]['owner'] = $row->owner; + $this->object_data_cache[$row->obj_id]['last_update'] = $row->last_update; + $this->object_data_cache[$row->obj_id]['offline'] = $row->offline; + + if (is_object($objDefinition)) { + $translation_type = $objDefinition->getTranslationType($row->type); + } + + if ($translation_type == "db") { + $db_trans[$row->obj_id] = $row->obj_id; + } + } + if (count($db_trans) > 0) { + $this->preloadTranslations($db_trans, $a_lang); + } + } + + /** + * Preload translation informations + * + * @param array $a_obj_ids array of object ids + */ + public function preloadTranslations($a_obj_ids, $a_lang) + { + $ilDB = $this->db; + + $obj_ids = array(); + foreach ($a_obj_ids as $id) { + // do not load an id more than one time + if (!$this->trans_loaded[$id]) { + $obj_ids[] = $id; + $this->trans_loaded[$id] = true; + } + } + if (count($obj_ids) > 0) { + $q = "SELECT obj_id, title, description FROM object_translation " . + "WHERE " . $ilDB->in('obj_id', $obj_ids, false, 'integer') . " " . + "AND lang_code = " . $ilDB->quote($a_lang, 'text') . " " . + "AND NOT lang_default = 1"; + $r = $ilDB->query($q); + while ($row2 = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + $this->object_data_cache[$row2->obj_id]['title'] = $row2->title; + $this->object_data_cache[$row2->obj_id]['description'] = $row2->description; + $this->description_trans[] = $row2->obj_id; + } + } + } + + public function preloadReferenceCache($a_ref_ids, $a_incl_obj = true) + { + $ilDB = $this->db; + + if (!is_array($a_ref_ids)) { + return; + } + if (count($a_ref_ids) == 0) { + return; + } + + $query = "SELECT ref_id, obj_id FROM object_reference " . + "WHERE " . $ilDB->in('ref_id', $a_ref_ids, false, 'integer'); + $res = $ilDB->query($query); + + $obj_ids = array(); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_ASSOC)) { + $this->reference_cache[$row['ref_id']] = $row['obj_id']; + //echo "
                  store_ref-".$row['ref_id']."-".$row['obj_id']."-"; + $obj_ids[] = $row['obj_id']; + } + if ($a_incl_obj) { + $this->preloadObjectCache($obj_ids); + } + } } -?> diff --git a/Services/Object/classes/class.ilObjectDataDeletionLog.php b/Services/Object/classes/class.ilObjectDataDeletionLog.php index 384592d80baba587e821adfa77c705bb919ff133..f97cd2aae74f53f08d1eafee1e21d981bf75c6d6 100644 --- a/Services/Object/classes/class.ilObjectDataDeletionLog.php +++ b/Services/Object/classes/class.ilObjectDataDeletionLog.php @@ -3,37 +3,37 @@ /** * Class ilBadgeManagementGUI - * + * * @author Jörg Lützenkirchen * @version $Id:$ * * @package ServicesBadge */ class ilObjectDataDeletionLog -{ - public static function add(ilObject $a_object) - { - global $DIC; +{ + public static function add(ilObject $a_object) + { + global $DIC; - $ilDB = $DIC->database(); - - $ilDB->insert("object_data_del", array( - "obj_id" => array("integer", $a_object->getId()), - "type" => array("text", $a_object->getType()), - "title" => array("text", $a_object->getTitle()), - "description" => array("clob", $a_object->getLongDescription()), - "tstamp" => array("integer", time()) - )); - } - - public static function get($a_object_id) - { - global $DIC; + $ilDB = $DIC->database(); + + $ilDB->insert("object_data_del", array( + "obj_id" => array("integer", $a_object->getId()), + "type" => array("text", $a_object->getType()), + "title" => array("text", $a_object->getTitle()), + "description" => array("clob", $a_object->getLongDescription()), + "tstamp" => array("integer", time()) + )); + } + + public static function get($a_object_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT * FROM object_data_del". - " WHERE obj_id = ".$ilDB->quote($a_object_id, "integer")); - return $ilDB->fetchAssoc($set); - } + $ilDB = $DIC->database(); + + $set = $ilDB->query("SELECT * FROM object_data_del" . + " WHERE obj_id = " . $ilDB->quote($a_object_id, "integer")); + return $ilDB->fetchAssoc($set); + } } diff --git a/Services/Object/classes/class.ilObjectDataSet.php b/Services/Object/classes/class.ilObjectDataSet.php index c988812fc24d72cea322859f5a0401511c5fad10..b48caa1b4fc2fc08d26db5498c8e7b166970536f 100644 --- a/Services/Object/classes/class.ilObjectDataSet.php +++ b/Services/Object/classes/class.ilObjectDataSet.php @@ -5,7 +5,7 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); /** * Object data set class - * + * * This class implements the following entities: * - transl_entry: data from object_translation * - transl: data from obj_content_master_lang @@ -16,204 +16,181 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); */ class ilObjectDataSet extends ilDataSet { - /** - * Get supported versions - * - * @param - * @return - */ - public function getSupportedVersions() - { - return array("4.4.0", "5.1.0", "5.2.0", "5.4.0"); - } - - /** - * Get xml namespace - * - * @param - * @return - */ - function getXmlNamespace($a_entity, $a_schema_version) - { - return "http://www.ilias.de/xml/Services/Object/".$a_entity; - } - - /** - * Get field types for entity - * - * @param - * @return - */ - protected function getTypes($a_entity, $a_version) - { - if ($a_entity == "transl_entry") - { - switch ($a_version) - { - case "4.4.0": - case "5.1.0": - case "5.2.0": + /** + * Get supported versions + * + * @param + * @return + */ + public function getSupportedVersions() + { + return array("4.4.0", "5.1.0", "5.2.0", "5.4.0"); + } + + /** + * Get xml namespace + * + * @param + * @return + */ + public function getXmlNamespace($a_entity, $a_schema_version) + { + return "http://www.ilias.de/xml/Services/Object/" . $a_entity; + } + + /** + * Get field types for entity + * + * @param + * @return + */ + protected function getTypes($a_entity, $a_version) + { + if ($a_entity == "transl_entry") { + switch ($a_version) { + case "4.4.0": + case "5.1.0": + case "5.2.0": case "5.4.0": - return array( - "ObjId" => "integer", - "Title" => "text", - "Description" => "text", - "LangCode" => "text", - "LangDefault" => "integer"); - } - } - if ($a_entity == "transl") - { - switch ($a_version) - { - case "4.4.0": - case "5.1.0": - case "5.2.0": + return array( + "ObjId" => "integer", + "Title" => "text", + "Description" => "text", + "LangCode" => "text", + "LangDefault" => "integer"); + } + } + if ($a_entity == "transl") { + switch ($a_version) { + case "4.4.0": + case "5.1.0": + case "5.2.0": case "5.4.0": - return array( - "ObjId" => "integer", - "MasterLang" => "text"); - } - } - if ($a_entity == "service_settings") - { - switch ($a_version) - { - case "5.1.0": - case "5.2.0": + return array( + "ObjId" => "integer", + "MasterLang" => "text"); + } + } + if ($a_entity == "service_settings") { + switch ($a_version) { + case "5.1.0": + case "5.2.0": case "5.4.0": - return array( - "ObjId" => "integer", - "Setting" => "text", - "Value" => "text"); - } - } - if ($a_entity == "common") - { - switch ($a_version) - { + return array( + "ObjId" => "integer", + "Setting" => "text", + "Value" => "text"); + } + } + if ($a_entity == "common") { + switch ($a_version) { case "5.4.0": - return array( - "ObjId" => "integer" + return array( + "ObjId" => "integer" ); - } - } - if ($a_entity == "icon") - { - switch ($a_version) - { + } + } + if ($a_entity == "icon") { + switch ($a_version) { case "5.4.0": - return array( - "ObjId" => "integer", - "Filename" => "text", - "Dir" => "directory"); - } - } - if ($a_entity == "tile") - { - switch ($a_version) - { + return array( + "ObjId" => "integer", + "Filename" => "text", + "Dir" => "directory"); + } + } + if ($a_entity == "tile") { + switch ($a_version) { case "5.4.0": - return array( - "ObjId" => "integer", - "Extension" => "text", - "Dir" => "directory"); - } - } - } + return array( + "ObjId" => "integer", + "Extension" => "text", + "Dir" => "directory"); + } + } + } - /** - * Read data - * - * @param - * @return - */ - function readData($a_entity, $a_version, $a_ids, $a_field = "") - { - global $DIC; + /** + * Read data + * + * @param + * @return + */ + public function readData($a_entity, $a_version, $a_ids, $a_field = "") + { + global $DIC; - $ilDB = $this->db; + $ilDB = $this->db; - if (!is_array($a_ids)) - { - $a_ids = array($a_ids); - } - - if ($a_entity == "transl_entry") - { - switch ($a_version) - { - case "4.4.0": - case "5.1.0": - case "5.2.0": + if (!is_array($a_ids)) { + $a_ids = array($a_ids); + } + + if ($a_entity == "transl_entry") { + switch ($a_version) { + case "4.4.0": + case "5.1.0": + case "5.2.0": case "5.4.0": - $this->getDirectDataFromQuery("SELECT obj_id, title, description,". - " lang_code, lang_default". - " FROM object_translation". - " WHERE ".$ilDB->in("obj_id", $a_ids, false, "integer")); - break; - } - } + $this->getDirectDataFromQuery("SELECT obj_id, title, description," . + " lang_code, lang_default" . + " FROM object_translation" . + " WHERE " . $ilDB->in("obj_id", $a_ids, false, "integer")); + break; + } + } - if ($a_entity == "transl") - { - switch ($a_version) - { - case "4.4.0": - case "5.1.0": - case "5.2.0": + if ($a_entity == "transl") { + switch ($a_version) { + case "4.4.0": + case "5.1.0": + case "5.2.0": case "5.4.0": - $this->getDirectDataFromQuery("SELECT obj_id, master_lang". - " FROM obj_content_master_lng". - " WHERE ".$ilDB->in("obj_id", $a_ids, false, "integer")); - break; - } - } + $this->getDirectDataFromQuery("SELECT obj_id, master_lang" . + " FROM obj_content_master_lng" . + " WHERE " . $ilDB->in("obj_id", $a_ids, false, "integer")); + break; + } + } - if ($a_entity == "service_settings") - { - switch ($a_version) - { - case "5.1.0": - case "5.2.0": + if ($a_entity == "service_settings") { + switch ($a_version) { + case "5.1.0": + case "5.2.0": case "5.4.0": - include_once("./Services/Object/classes/class.ilObjectServiceSettingsGUI.php"); - include_once("./Services/Container/classes/class.ilContainer.php"); + include_once("./Services/Object/classes/class.ilObjectServiceSettingsGUI.php"); + include_once("./Services/Container/classes/class.ilContainer.php"); - $this->data = array(); - foreach ($a_ids as $id) - { - // info, news, custom metadata, tags, taxonomies, auto rating (all stored in container settings) - $settings = array( - ilObjectServiceSettingsGUI::INFO_TAB_VISIBILITY, - ilObjectServiceSettingsGUI::NEWS_VISIBILITY, - ilObjectServiceSettingsGUI::CUSTOM_METADATA, - ilObjectServiceSettingsGUI::TAG_CLOUD, - ilObjectServiceSettingsGUI::TAXONOMIES, - ilObjectServiceSettingsGUI::AUTO_RATING_NEW_OBJECTS, - ilObjectServiceSettingsGUI::CALENDAR_VISIBILITY - ); - if ($a_version == "5.2.0") - { - $settings[] = ilObjectServiceSettingsGUI::USE_NEWS; - } - foreach ($settings as $s) - { - $val = ilContainer::_lookupContainerSetting($id, $s); - if ($val) - { - $this->data[] = array( - "ObjId" => $id, - "Setting" => $s, - "Value" => $val - ); - } - } - } - break; - } - } - // common + $this->data = array(); + foreach ($a_ids as $id) { + // info, news, custom metadata, tags, taxonomies, auto rating (all stored in container settings) + $settings = array( + ilObjectServiceSettingsGUI::INFO_TAB_VISIBILITY, + ilObjectServiceSettingsGUI::NEWS_VISIBILITY, + ilObjectServiceSettingsGUI::CUSTOM_METADATA, + ilObjectServiceSettingsGUI::TAG_CLOUD, + ilObjectServiceSettingsGUI::TAXONOMIES, + ilObjectServiceSettingsGUI::AUTO_RATING_NEW_OBJECTS, + ilObjectServiceSettingsGUI::CALENDAR_VISIBILITY + ); + if ($a_version == "5.2.0") { + $settings[] = ilObjectServiceSettingsGUI::USE_NEWS; + } + foreach ($settings as $s) { + $val = ilContainer::_lookupContainerSetting($id, $s); + if ($val) { + $this->data[] = array( + "ObjId" => $id, + "Setting" => $s, + "Value" => $val + ); + } + } + } + break; + } + } + // common if ($a_entity == "common") { $this->data = []; foreach ($a_ids as $id) { @@ -222,7 +199,7 @@ class ilObjectDataSet extends ilDataSet ]; } } - // tile images + // tile images if ($a_entity == "tile") { $cs = $DIC->object()->commonSettings(); $this->data = []; @@ -254,52 +231,55 @@ class ilObjectDataSet extends ilDataSet } } } - } - /** - * Determine the dependent sets of data - */ - protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) - { - switch ($a_entity) - { + /** + * Determine the dependent sets of data + */ + protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) + { + switch ($a_entity) { case "common": - return array ( + return array( "transl" => array("ids" => $a_rec["ObjId"]), "service_settings" => array("ids" => $a_rec["ObjId"]), "tile" => array("ids" => $a_rec["ObjId"]), "icon" => array("ids" => $a_rec["ObjId"]) ); - case "transl": - return array ( - "transl_entry" => array("ids" => $a_rec["ObjId"]) - ); - } + case "transl": + return array( + "transl_entry" => array("ids" => $a_rec["ObjId"]) + ); + } - return false; - } - - - /** - * Import record - * - * @param - * @return - */ - function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) - { - global $DIC; + return false; + } + + + /** + * Import record + * + * @param + * @return + */ + public function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) + { + global $DIC; - switch ($a_entity) { + switch ($a_entity) { case "transl_entry": $new_id = $this->getNewObjId($a_mapping, $a_rec['ObjId']); if ($new_id > 0) { include_once("./Services/Object/classes/class.ilObjectTranslation.php"); $transl = ilObjectTranslation::getInstance($new_id); - $transl->addLanguage($a_rec["LangCode"], $a_rec["Title"], $a_rec["Description"], - $a_rec["LangDefault"], true); + $transl->addLanguage( + $a_rec["LangCode"], + $a_rec["Title"], + $a_rec["Description"], + $a_rec["LangDefault"], + true + ); $transl->save(); } break; @@ -360,7 +340,7 @@ class ilObjectDataSet extends ilDataSet } break; } - } + } /** * Get new object id @@ -376,14 +356,12 @@ class ilObjectDataSet extends ilDataSet /** @var ilObjectDefinition $objDefinition */ $objDefinition = $DIC["objDefinition"]; - $new_id = $a_mapping->getMapping('Services/Container','objs',$old_id); - if (!$new_id) - { - $new_id = $a_mapping->getMapping('Services/Object','objs',$old_id); + $new_id = $a_mapping->getMapping('Services/Container', 'objs', $old_id); + if (!$new_id) { + $new_id = $a_mapping->getMapping('Services/Object', 'objs', $old_id); } - if (!$new_id) - { - $new_id = $a_mapping->getMapping('Services/Object','obj',$old_id); + if (!$new_id) { + $new_id = $a_mapping->getMapping('Services/Object', 'obj', $old_id); } if (!$new_id) { foreach ($a_mapping->getAllMappings() as $k => $m) { @@ -391,7 +369,7 @@ class ilObjectDataSet extends ilDataSet foreach ($m as $type => $map) { if (!$new_id) { if ($objDefinition->isRBACObject($type)) { - $new_id = $a_mapping->getMapping($k,$type,$old_id); + $new_id = $a_mapping->getMapping($k, $type, $old_id); } } } @@ -401,4 +379,3 @@ class ilObjectDataSet extends ilDataSet return $new_id; } } -?> \ No newline at end of file diff --git a/Services/Object/classes/class.ilObjectDefinition.php b/Services/Object/classes/class.ilObjectDefinition.php index 99cdfcff6c5c43f39c0aa7d3ef9709c4bc00baaf..647a1c5a71e131bdd2dff96c1eaf8eee831bd742 100755 --- a/Services/Object/classes/class.ilObjectDefinition.php +++ b/Services/Object/classes/class.ilObjectDefinition.php @@ -10,1243 +10,1195 @@ require_once('./Services/Repository/classes/class.ilObjectPlugin.php'); * @author Alex Killing * @version $Id$ * -* @externalTableAccess ilObjDefReader on il_object_def, il_object_subobj, il_object_group +* @externalTableAccess ilObjDefReader on il_object_def, il_object_subobj, il_object_group */ -class ilObjectDefinition// extends ilSaxParser +class ilObjectDefinition // extends ilSaxParser { - /** - * @var ilPluginAdmin - */ - protected $plugin_admin; - - /** - * @var ilSetting - */ - protected $settings; - - /** - * // TODO: var is not used - * object id of specific object - * @var obj_id - * @access private - */ - var $obj_id; - - /** - * parent id of object - * @var parent id - * @access private - */ - var $parent; - - /** - * array representation of objects - * @var objects - * @access private - */ - var $obj_data; - - var $sub_types = array(); - - const MODE_REPOSITORY = 1; - const MODE_WORKSPACE = 2; - const MODE_ADMINISTRATION = 3; - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->plugin_admin = $DIC["ilPluginAdmin"]; - $this->settings = $DIC->settings(); - $this->readDefinitionData(); - } - - - protected function readDefinitionDataFromCache() { - $this->obj_data = array(); - $defIds = array(); - $global_cache = ilCachedComponentData::getInstance(); - foreach ($global_cache->getIlobjectDef() as $rec) { - $this->obj_data[$rec["id"]] = array( - "name" => $rec["id"], - "class_name" => $rec["class_name"], - "location" => $rec["location"], - "checkbox" => $rec["checkbox"], - "inherit" => $rec["inherit"], - "component" => $rec["component"], - "translate" => $rec["translate"], - "devmode" => $rec["devmode"], - "allow_link" => $rec["allow_link"], - "allow_copy" => $rec["allow_copy"], - "rbac" => $rec["rbac"], - "group" => $rec["grp"], - "system" => $rec["system"], - "default_pos" => "9999" . str_pad($rec["default_pos"], 4, "0", STR_PAD_LEFT), // "unassigned" group - "sideblock" => $rec["sideblock"], - 'export' => $rec['export'], - 'repository' => $rec['repository'], - 'workspace' => $rec['workspace'], - 'administration' => $rec['administration'], - 'amet' => $rec['amet'], - 'orgunit_permissions' => $rec['orgunit_permissions'], - 'lti_provider' => $rec['lti_provider'], - 'offline_handling' => $rec['offline_handling'] - ); - $this->obj_data[$rec["id"]]["subobjects"] = array(); - - $defIds[] = $rec["id"]; - } - - $subobj = $global_cache->lookupSubObjForParent($defIds); - - foreach ($subobj as $rec2) { - - $max = $rec2["mmax"]; - if ($max <= 0) { - $max = ""; - } - $this->obj_data[$rec2["parent"]]["subobjects"][$rec2["subobj"]] = array( - "name" => $rec2["subobj"], - "max" => $max, - "lng" => $rec2["subobj"] - ); - } - $this->obj_group = $global_cache->getIlObjectGroup(); - - $this->readPluginData(); - - $this->sub_types = $global_cache->getIlObjectSubType(); - } - - - protected function readDefinitionDataFromDB() { - global $DIC; - - $ilDB = $DIC->database(); - - $this->obj_data = array(); - - // Select all object_definitions and collect the definition id's in - // this array. - $defIds = array(); - $set = $ilDB->query("SELECT * FROM il_object_def"); - while ($rec = $ilDB->fetchAssoc($set)) { - $this->obj_data[$rec["id"]] = array( - "name" => $rec["id"], - "class_name" => $rec["class_name"], - "location" => $rec["location"], - "checkbox" => $rec["checkbox"], - "inherit" => $rec["inherit"], - "component" => $rec["component"], - "translate" => $rec["translate"], - "devmode" => $rec["devmode"], - "allow_link" => $rec["allow_link"], - "allow_copy" => $rec["allow_copy"], - "rbac" => $rec["rbac"], - "group" => $rec["grp"], - "system" => $rec["system"], - "default_pos" => "9999" . str_pad($rec["default_pos"], 4, "0", STR_PAD_LEFT), // "unassigned" group - "sideblock" => $rec["sideblock"], - 'export' => $rec['export'], - 'repository' => $rec['repository'], - 'workspace' => $rec['workspace'], - 'administration' => $rec['administration'], - 'amet' => $rec['amet'], - 'orgunit_permissions' => $rec['orgunit_permissions'], - 'lti_provider' => $rec['lti_provider'], - 'offline_handling' => $rec['offline_handling'] - ); - $this->obj_data[$rec["id"]]["subobjects"] = array(); - - $defIds[] = $rec["id"]; - } - - // get all subobject definitions in a single query - $set2 = $ilDB->query("SELECT * FROM il_object_subobj WHERE " . $ilDB->in('parent', $defIds, false, 'text')); - while ($rec2 = $ilDB->fetchAssoc($set2)) { - $max = $rec2["mmax"]; - if ($max <= 0) // for backward compliance - { - $max = ""; - } - $this->obj_data[$rec2["parent"]]["subobjects"][$rec2["subobj"]] = array( - "name" => $rec2["subobj"], - "max" => $max, - "lng" => $rec2["subobj"] - ); - } - - $set = $ilDB->query("SELECT * FROM il_object_group"); - $this->obj_group = array(); - while ($rec = $ilDB->fetchAssoc($set)) { - $this->obj_group[$rec["id"]] = $rec; - } - - $this->readPluginData(); - - $set = $ilDB->query("SELECT * FROM il_object_sub_type "); - $this->sub_types = array(); - while ($rec = $ilDB->fetchAssoc($set)) { - $this->sub_types[$rec["obj_type"]][] = $rec; - } - } - - - /** - * Read object definition data - */ - function readDefinitionData() - { - if(ilGlobalCache::getInstance(ilGlobalCache::COMP_COMPONENT)->isActive()) { - $this->readDefinitionDataFromCache(); - } else { - $this->readDefinitionDataFromDB(); - } - } - - /** - * @param $grouped_obj - * @param $component - * @param $slotName - * @param $slotId - * @param $plugin_id - * @return mixed - * @internal param $ilPluginAdmin - */ - protected static function getGroupedPluginObjectTypes($grouped_obj, $component, $slotName, $slotId) { - global $DIC; - - $ilPluginAdmin = $DIC["ilPluginAdmin"]; - $pl_names = $ilPluginAdmin->getActivePluginsForSlot($component, $slotName, $slotId); - foreach ($pl_names as $pl_name) { - include_once("./Services/Component/classes/class.ilPlugin.php"); - $pl_id = ilPlugin::lookupIdForName($component, $slotName, $slotId,$pl_name); - if (!isset($grouped_obj[$pl_id])) { - $grouped_obj[$pl_id] = array( - "pos" => "99992000", // "unassigned" group - "objs" => array(0 => $pl_id) - ); - } - } - return $grouped_obj; - } - - -// PUBLIC METHODS - - /** - * get class name by type - * - * @param string object type - * @access public - */ - function getClassName($a_obj_name) - { - return $this->obj_data[$a_obj_name]["class_name"]; - } - - - /** - * get location by type - * - * @param string object type - * @access public - */ - function getLocation($a_obj_name) - { - return $this->obj_data[$a_obj_name]["location"]; - } - - /** - * Get Group information - */ - function getGroup($a_id) - { - return $this->obj_group[$a_id]; - } - - /** - * Get Group of object type - */ - function getGroupOfObj($a_obj_name) - { - return $this->obj_data[$a_obj_name]["group"]; - } - - /** - * should the object get a checkbox (needed for 'cut','copy' ...) - * - * @param string object type - * @access public - */ - function hasCheckbox($a_obj_name) - { - return (bool) $this->obj_data[$a_obj_name]["checkbox"]; - } - - /** - * get translation type (sys, db or 0)s - * - * @param string object type - * @access public - */ - function getTranslationType($a_obj_name) - { - global $DIC; - - $ilDB = $DIC->database(); - - if ($a_obj_name == "root") - { - if (!isset($this->root_trans_type)) - { - $q = "SELECT count(obj_id) cnt FROM object_translation WHERE obj_id = ". - $ilDB->quote(ROOT_FOLDER_ID,'integer')." "; - $set = $ilDB->query($q); - $rec = $set->fetchRow(ilDBConstants::FETCHMODE_ASSOC); - if($rec["cnt"] > 0) - { - $this->root_trans_type = "db"; - } - else - { - $this->root_trans_type = $this->obj_data[$a_obj_name]["translate"]; - } - } - return $this->root_trans_type; - } - - if (isset($this->obj_data[$a_obj_name])) - { - return $this->obj_data[$a_obj_name]["translate"]; - } - - return ""; - } - - - /** - * Does object permits stopping inheritance? - * - * @param string object type - * @access public - */ - function stopInheritance($a_obj_name) - { - return (bool) $this->obj_data[$a_obj_name]["inherit"]; - } - - /** - * get devmode status by type - * - * @param string object type - * @access public - */ - function getDevMode($a_obj_name) - { - return (bool) $this->obj_data[$a_obj_name]["devmode"]; - } - - /** - * get all object types in devmode - * - * @access public - * @return array object types set to development - */ - function getDevModeAll() - { - $types = array_keys($this->obj_data); - - foreach ($types as $type) - { - if ($this->getDevMode($type)) - { - $devtypes[] = $type; - } - } - - return $devtypes ? $devtypes : array(); - } - - /** - * get RBAC status by type - * returns true if object type is a RBAC object type - * - * @param string object type - * @access public - */ - function isRBACObject($a_obj_name) - { - return (bool) $this->obj_data[$a_obj_name]["rbac"]; - } - - /** - * get RBAC status by type - * returns true if object type is an (activated) plugin type - * - * @param string object type - * @access public - */ - function isPlugin($a_obj_name) - { - return (bool) isset($this->obj_data[$a_obj_name]["plugin"]); - } - - /** - * Check if given type is a plugin type name (starts with an "x") - * - * @param string object type - * @access public - */ - function isPluginTypeName($a_str) - { - return (substr($a_str, 0, 1) == "x"); - } - - /** - * Returns true iff the given type is an active type of a repositoryObject or Organisation Unit Extension plugin. - * @param $type - * @return bool - */ - public function isActivePluginType($type) { - $ilPluginAdmin = $this->plugin_admin; - $isRepoPlugin = $ilPluginAdmin->isActive(IL_COMP_SERVICE, "Repository", "robj", - ilPlugin::lookupNameForId(IL_COMP_SERVICE, "Repository", "robj", $type)); - $isOrguPlugin = $ilPluginAdmin->isActive(IL_COMP_MODULE, "OrgUnit", "orguext", - ilPlugin::lookupNameForId(IL_COMP_MODULE, "OrgUnit", "orguext", $type)); - return $isRepoPlugin || $isOrguPlugin; - } - - /** - * get all RBAC object types - * - * @access public - * @return array object types set to development - */ - function getAllRBACObjects() - { - $types = array_keys($this->obj_data); - - foreach ($types as $type) - { - if ($this->isRBACObject($type)) - { - $rbactypes[] = $type; - } - } - - return $rbactypes ? $rbactypes : array(); - } - - /** - * get all object types - * - * @access public - * @return array object types - */ - function getAllObjects() - { - return array_keys($this->obj_data); - } - - /** - * checks if linking of an object type is allowed - * - * @param string object type - * @access public - */ - public function allowLink($a_obj_name) - { - return (bool) $this->obj_data[$a_obj_name]["allow_link"]; - } - - /** - * checks if copying of an object type is allowed - * - * @param string object type - * @access public - */ - public function allowCopy($a_obj_name) - { - return (bool) $this->obj_data[$a_obj_name]["allow_copy"]; - } - - public function allowExport($a_obj_name) - { - return (bool) $this->obj_data[$a_obj_name]['export']; - } - - /** - * Check whether the creation of local roles is allowed - * Currently disabled for type "root" and "adm" - * @return - */ - public function hasLocalRoles($a_obj_type) - { - switch($a_obj_type) - { - case 'root': - return FALSE; - - default: - return TRUE; - } - } - - /** - * get all subobjects by type - * - * @param string object type - * @param boolean filter disabled objects? (default: true) - * @access public - * @return array list of allowed object types - */ - function getSubObjects($a_obj_type,$a_filter = true) - { - $ilSetting = $this->settings; - - $subs = array(); - - if ($subobjects = $this->obj_data[$a_obj_type]["subobjects"]) - { - // Filter some objects e.g chat object are creatable if chat is active - if ($a_filter) - { - $this->__filterObjects($subobjects); - } - foreach ($subobjects as $data => $sub) - { - if ($sub["module"] != "n") - { - if (!($ilSetting->get("obj_dis_creation_".$data))) - { - $subs[$data] = $sub; - - // determine position - $pos = ($ilSetting->get("obj_add_new_pos_".$data) > 0) - ? (int) $ilSetting->get("obj_add_new_pos_".$data) - : (int) $this->obj_data[$data]["default_pos"]; - $subs[$data]["pos"] = $pos; - } - } - } - - $subs2 = ilUtil::sortArray($subs, "pos", 'ASC', true, true); - - return $subs2; - } - - return $subs; - } - - /** - * Get all subobjects by type. - * This function returns all subobjects allowed by the provided object type - * and all its subobject types recursively. - * - * This function is used to create local role templates. It is important, - * that we do not filter out any objects here! - * - * - * @param string object type - * @access public - * @return array list of allowed object types - */ - function getSubObjectsRecursively($a_obj_type,$a_include_source_obj = true, $a_add_admin_objects = false) - { - $ilSetting = $this->settings; - - // This associative array is used to collect all subobject types. - // key=>type, value=data - $recursivesubs = array(); - - // This array is used to keep track of the object types, we - // need to call function getSubobjects() for. - $to_do = array($a_obj_type); - - // This array is used to keep track of the object types, we - // have called function getSubobjects() already. This is to - // prevent endless loops, for object types that support - // themselves as subobject types either directly or indirectly. - $done = array(); - - while (count($to_do) > 0) - { - $type = array_pop($to_do); - $done[] = $type; - - // no recovery folder subitems - if($type == 'recf') - { - continue; - } - - // Hide administration if desired - if(!$a_add_admin_objects and $type == 'adm') - { - $subs = array(); - } - else - { - $subs = $this->getSubObjects($type); - } - #vd('xxxxxxxxxxxxx'.$type); - foreach ($subs as $subtype => $data) - { - #vd('------------------------->'.$subtype); - - // Hide role templates and folder from view - if($this->getDevMode($subtype) or !$this->isRBACObject($subtype)) - { - continue; - } - if($subtype == 'rolt') - { - continue; - } - if(!$a_add_admin_objects and $subtype == 'adm') - { - continue; - } - - $recursivesubs[$subtype] = $data; - if (! in_array($subtype, $done) - && ! in_array($subtype, $to_do)) - { - $to_do[] = $subtype; - } - } - } - - if($a_include_source_obj) - { - if(!isset($recursivesubs[$a_obj_type])) - { - $recursivesubs[$a_obj_type]['name'] = $a_obj_type; - $recursivesubs[$a_obj_type]['lng'] = $a_obj_type; - $recursivesubs[$a_obj_type]['max'] = 0; - $recursivesubs[$a_obj_type]['pos'] = -1; - } - } - return ilUtil::sortArray($recursivesubs, "pos", 'ASC', true, true); - } - - - /** - * get all subjects except (rolf) of the adm object - * This is necessary for filtering these objects in role perm view. - * e.g It it not necessary to view/edit role permission for the usrf object since it's not possible to create a new one - * - * @param string object type - * @access public - * @return array list of object types to filter - */ - function getSubobjectsToFilter($a_obj_type = "adm") - { - foreach($this->obj_data[$a_obj_type]["subobjects"] as $key => $value) - { - switch($key) - { - case "rolf": - case "orgu": - // DO NOTHING - break; - - default: - $tmp_subs[] = $key; - } - } - // ADD adm and root object - $tmp_subs[] = "adm"; - #$tmp_subs[] = "root"; - - return $tmp_subs ? $tmp_subs : array(); - } - - /** - * get only creatable subobjects by type - * - * @param string object type - * @param integer context - * @param integer parent_ref_id - * @access public - * @return array list of createable object types - */ - function getCreatableSubObjects($a_obj_type, $a_context = self::MODE_REPOSITORY, $a_parent_ref_id = null) - { - $subobjects = $this->getSubObjects($a_obj_type); - - // remove role folder object from list - unset($subobjects["rolf"]); - - $sub_types = array_keys($subobjects); - - // remove object types in development from list - foreach ($sub_types as $type) - { - if ($this->getDevMode($type) || $this->isSystemObject($type)) - { - unset($subobjects[$type]); - } - if ($a_context == self::MODE_REPOSITORY && !$this->isAllowedInRepository($type)) - { - unset($subobjects[$type]); - } - if ($a_context == self::MODE_WORKSPACE && !$this->isAllowedInWorkspace($type)) - { - unset($subobjects[$type]); - } - if ($a_context == self::MODE_ADMINISTRATION && !$this->isAdministrationObject($type)) - { - unset($subobjects[$type]); - } - } - - if ($a_obj_type == "prg") { - // ask study program which objects are allowed to create on the concrete node. - require_once("Modules/StudyProgramme/classes/class.ilObjStudyProgramme.php"); - return ilObjStudyProgramme::getCreatableSubObjects($subobjects, $a_parent_ref_id); - } - - return $subobjects; - } - - /** - * get a string of all subobjects by type - * - * @param string object type - * @access public - */ - function getSubObjectsAsString($a_obj_type) - { - $string = ""; - - if (is_array($this->obj_data[$a_obj_type]["subobjects"])) - { - $data = array_keys($this->obj_data[$a_obj_type]["subobjects"]); - - $string = "'".implode("','", $data)."'"; - } - - return $string; - } - - /** - * Check if object type is container ('crs','fold','grp' ...) - * - * @access public - * @param string object type - * @return bool - * - */ - public function isContainer($a_obj_name) - { - if(!is_array($this->obj_data[$a_obj_name]['subobjects'])) - { - return false; - } - return count($this->obj_data[$a_obj_name]['subobjects']) >= 1 ? true : false; - } - -// PRIVATE METHODS - - /** - * set event handler - * - * @param ressouce internal xml_parser_handler - * @access private - */ - 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 tag handler - * - * @param ressouce internal xml_parser_handler - * @param string element tag name - * @param array element attributes - * @access private - */ - function handlerBeginTag($a_xml_parser,$a_name,$a_attribs) - { - switch ($a_name) - { - case 'object': - $this->parent_tag_name = $a_attribs["name"]; - break; - case 'property': - $this->current_tag = "property"; - $this->current_tag_name = $a_attribs["name"]; + /** + * @var ilPluginAdmin + */ + protected $plugin_admin; + + /** + * @var ilSetting + */ + protected $settings; + + /** + * // TODO: var is not used + * object id of specific object + * @var obj_id + * @access private + */ + public $obj_id; + + /** + * parent id of object + * @var parent id + * @access private + */ + public $parent; + + /** + * array representation of objects + * @var objects + * @access private + */ + public $obj_data; + + public $sub_types = array(); + + const MODE_REPOSITORY = 1; + const MODE_WORKSPACE = 2; + const MODE_ADMINISTRATION = 3; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->plugin_admin = $DIC["ilPluginAdmin"]; + $this->settings = $DIC->settings(); + $this->readDefinitionData(); + } + + + protected function readDefinitionDataFromCache() + { + $this->obj_data = array(); + $defIds = array(); + $global_cache = ilCachedComponentData::getInstance(); + foreach ($global_cache->getIlobjectDef() as $rec) { + $this->obj_data[$rec["id"]] = array( + "name" => $rec["id"], + "class_name" => $rec["class_name"], + "location" => $rec["location"], + "checkbox" => $rec["checkbox"], + "inherit" => $rec["inherit"], + "component" => $rec["component"], + "translate" => $rec["translate"], + "devmode" => $rec["devmode"], + "allow_link" => $rec["allow_link"], + "allow_copy" => $rec["allow_copy"], + "rbac" => $rec["rbac"], + "group" => $rec["grp"], + "system" => $rec["system"], + "default_pos" => "9999" . str_pad($rec["default_pos"], 4, "0", STR_PAD_LEFT), // "unassigned" group + "sideblock" => $rec["sideblock"], + 'export' => $rec['export'], + 'repository' => $rec['repository'], + 'workspace' => $rec['workspace'], + 'administration' => $rec['administration'], + 'amet' => $rec['amet'], + 'orgunit_permissions' => $rec['orgunit_permissions'], + 'lti_provider' => $rec['lti_provider'], + 'offline_handling' => $rec['offline_handling'] + ); + $this->obj_data[$rec["id"]]["subobjects"] = array(); + + $defIds[] = $rec["id"]; + } + + $subobj = $global_cache->lookupSubObjForParent($defIds); + + foreach ($subobj as $rec2) { + $max = $rec2["mmax"]; + if ($max <= 0) { + $max = ""; + } + $this->obj_data[$rec2["parent"]]["subobjects"][$rec2["subobj"]] = array( + "name" => $rec2["subobj"], + "max" => $max, + "lng" => $rec2["subobj"] + ); + } + $this->obj_group = $global_cache->getIlObjectGroup(); + + $this->readPluginData(); + + $this->sub_types = $global_cache->getIlObjectSubType(); + } + + + protected function readDefinitionDataFromDB() + { + global $DIC; + + $ilDB = $DIC->database(); + + $this->obj_data = array(); + + // Select all object_definitions and collect the definition id's in + // this array. + $defIds = array(); + $set = $ilDB->query("SELECT * FROM il_object_def"); + while ($rec = $ilDB->fetchAssoc($set)) { + $this->obj_data[$rec["id"]] = array( + "name" => $rec["id"], + "class_name" => $rec["class_name"], + "location" => $rec["location"], + "checkbox" => $rec["checkbox"], + "inherit" => $rec["inherit"], + "component" => $rec["component"], + "translate" => $rec["translate"], + "devmode" => $rec["devmode"], + "allow_link" => $rec["allow_link"], + "allow_copy" => $rec["allow_copy"], + "rbac" => $rec["rbac"], + "group" => $rec["grp"], + "system" => $rec["system"], + "default_pos" => "9999" . str_pad($rec["default_pos"], 4, "0", STR_PAD_LEFT), // "unassigned" group + "sideblock" => $rec["sideblock"], + 'export' => $rec['export'], + 'repository' => $rec['repository'], + 'workspace' => $rec['workspace'], + 'administration' => $rec['administration'], + 'amet' => $rec['amet'], + 'orgunit_permissions' => $rec['orgunit_permissions'], + 'lti_provider' => $rec['lti_provider'], + 'offline_handling' => $rec['offline_handling'] + ); + $this->obj_data[$rec["id"]]["subobjects"] = array(); + + $defIds[] = $rec["id"]; + } + + // get all subobject definitions in a single query + $set2 = $ilDB->query("SELECT * FROM il_object_subobj WHERE " . $ilDB->in('parent', $defIds, false, 'text')); + while ($rec2 = $ilDB->fetchAssoc($set2)) { + $max = $rec2["mmax"]; + if ($max <= 0) { // for backward compliance + $max = ""; + } + $this->obj_data[$rec2["parent"]]["subobjects"][$rec2["subobj"]] = array( + "name" => $rec2["subobj"], + "max" => $max, + "lng" => $rec2["subobj"] + ); + } + + $set = $ilDB->query("SELECT * FROM il_object_group"); + $this->obj_group = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $this->obj_group[$rec["id"]] = $rec; + } + + $this->readPluginData(); + + $set = $ilDB->query("SELECT * FROM il_object_sub_type "); + $this->sub_types = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $this->sub_types[$rec["obj_type"]][] = $rec; + } + } + + + /** + * Read object definition data + */ + public function readDefinitionData() + { + if (ilGlobalCache::getInstance(ilGlobalCache::COMP_COMPONENT)->isActive()) { + $this->readDefinitionDataFromCache(); + } else { + $this->readDefinitionDataFromDB(); + } + } + + /** + * @param $grouped_obj + * @param $component + * @param $slotName + * @param $slotId + * @param $plugin_id + * @return mixed + * @internal param $ilPluginAdmin + */ + protected static function getGroupedPluginObjectTypes($grouped_obj, $component, $slotName, $slotId) + { + global $DIC; + + $ilPluginAdmin = $DIC["ilPluginAdmin"]; + $pl_names = $ilPluginAdmin->getActivePluginsForSlot($component, $slotName, $slotId); + foreach ($pl_names as $pl_name) { + include_once("./Services/Component/classes/class.ilPlugin.php"); + $pl_id = ilPlugin::lookupIdForName($component, $slotName, $slotId, $pl_name); + if (!isset($grouped_obj[$pl_id])) { + $grouped_obj[$pl_id] = array( + "pos" => "99992000", // "unassigned" group + "objs" => array(0 => $pl_id) + ); + } + } + return $grouped_obj; + } + + + // PUBLIC METHODS + + /** + * get class name by type + * + * @param string object type + * @access public + */ + public function getClassName($a_obj_name) + { + return $this->obj_data[$a_obj_name]["class_name"]; + } + + + /** + * get location by type + * + * @param string object type + * @access public + */ + public function getLocation($a_obj_name) + { + return $this->obj_data[$a_obj_name]["location"]; + } + + /** + * Get Group information + */ + public function getGroup($a_id) + { + return $this->obj_group[$a_id]; + } + + /** + * Get Group of object type + */ + public function getGroupOfObj($a_obj_name) + { + return $this->obj_data[$a_obj_name]["group"]; + } + + /** + * should the object get a checkbox (needed for 'cut','copy' ...) + * + * @param string object type + * @access public + */ + public function hasCheckbox($a_obj_name) + { + return (bool) $this->obj_data[$a_obj_name]["checkbox"]; + } + + /** + * get translation type (sys, db or 0)s + * + * @param string object type + * @access public + */ + public function getTranslationType($a_obj_name) + { + global $DIC; + + $ilDB = $DIC->database(); + + if ($a_obj_name == "root") { + if (!isset($this->root_trans_type)) { + $q = "SELECT count(obj_id) cnt FROM object_translation WHERE obj_id = " . + $ilDB->quote(ROOT_FOLDER_ID, 'integer') . " "; + $set = $ilDB->query($q); + $rec = $set->fetchRow(ilDBConstants::FETCHMODE_ASSOC); + if ($rec["cnt"] > 0) { + $this->root_trans_type = "db"; + } else { + $this->root_trans_type = $this->obj_data[$a_obj_name]["translate"]; + } + } + return $this->root_trans_type; + } + + if (isset($this->obj_data[$a_obj_name])) { + return $this->obj_data[$a_obj_name]["translate"]; + } + + return ""; + } + + + /** + * Does object permits stopping inheritance? + * + * @param string object type + * @access public + */ + public function stopInheritance($a_obj_name) + { + return (bool) $this->obj_data[$a_obj_name]["inherit"]; + } + + /** + * get devmode status by type + * + * @param string object type + * @access public + */ + public function getDevMode($a_obj_name) + { + return (bool) $this->obj_data[$a_obj_name]["devmode"]; + } + + /** + * get all object types in devmode + * + * @access public + * @return array object types set to development + */ + public function getDevModeAll() + { + $types = array_keys($this->obj_data); + + foreach ($types as $type) { + if ($this->getDevMode($type)) { + $devtypes[] = $type; + } + } + + return $devtypes ? $devtypes : array(); + } + + /** + * get RBAC status by type + * returns true if object type is a RBAC object type + * + * @param string object type + * @access public + */ + public function isRBACObject($a_obj_name) + { + return (bool) $this->obj_data[$a_obj_name]["rbac"]; + } + + /** + * get RBAC status by type + * returns true if object type is an (activated) plugin type + * + * @param string object type + * @access public + */ + public function isPlugin($a_obj_name) + { + return (bool) isset($this->obj_data[$a_obj_name]["plugin"]); + } + + /** + * Check if given type is a plugin type name (starts with an "x") + * + * @param string object type + * @access public + */ + public function isPluginTypeName($a_str) + { + return (substr($a_str, 0, 1) == "x"); + } + + /** + * Returns true iff the given type is an active type of a repositoryObject or Organisation Unit Extension plugin. + * @param $type + * @return bool + */ + public function isActivePluginType($type) + { + $ilPluginAdmin = $this->plugin_admin; + $isRepoPlugin = $ilPluginAdmin->isActive( + IL_COMP_SERVICE, + "Repository", + "robj", + ilPlugin::lookupNameForId(IL_COMP_SERVICE, "Repository", "robj", $type) + ); + $isOrguPlugin = $ilPluginAdmin->isActive( + IL_COMP_MODULE, + "OrgUnit", + "orguext", + ilPlugin::lookupNameForId(IL_COMP_MODULE, "OrgUnit", "orguext", $type) + ); + return $isRepoPlugin || $isOrguPlugin; + } + + /** + * get all RBAC object types + * + * @access public + * @return array object types set to development + */ + public function getAllRBACObjects() + { + $types = array_keys($this->obj_data); + + foreach ($types as $type) { + if ($this->isRBACObject($type)) { + $rbactypes[] = $type; + } + } + + return $rbactypes ? $rbactypes : array(); + } + + /** + * get all object types + * + * @access public + * @return array object types + */ + public function getAllObjects() + { + return array_keys($this->obj_data); + } + + /** + * checks if linking of an object type is allowed + * + * @param string object type + * @access public + */ + public function allowLink($a_obj_name) + { + return (bool) $this->obj_data[$a_obj_name]["allow_link"]; + } + + /** + * checks if copying of an object type is allowed + * + * @param string object type + * @access public + */ + public function allowCopy($a_obj_name) + { + return (bool) $this->obj_data[$a_obj_name]["allow_copy"]; + } + + public function allowExport($a_obj_name) + { + return (bool) $this->obj_data[$a_obj_name]['export']; + } + + /** + * Check whether the creation of local roles is allowed + * Currently disabled for type "root" and "adm" + * @return + */ + public function hasLocalRoles($a_obj_type) + { + switch ($a_obj_type) { + case 'root': + return false; + + default: + return true; + } + } + + /** + * get all subobjects by type + * + * @param string object type + * @param boolean filter disabled objects? (default: true) + * @access public + * @return array list of allowed object types + */ + public function getSubObjects($a_obj_type, $a_filter = true) + { + $ilSetting = $this->settings; + + $subs = array(); + + if ($subobjects = $this->obj_data[$a_obj_type]["subobjects"]) { + // Filter some objects e.g chat object are creatable if chat is active + if ($a_filter) { + $this->__filterObjects($subobjects); + } + foreach ($subobjects as $data => $sub) { + if ($sub["module"] != "n") { + if (!($ilSetting->get("obj_dis_creation_" . $data))) { + $subs[$data] = $sub; + + // determine position + $pos = ($ilSetting->get("obj_add_new_pos_" . $data) > 0) + ? (int) $ilSetting->get("obj_add_new_pos_" . $data) + : (int) $this->obj_data[$data]["default_pos"]; + $subs[$data]["pos"] = $pos; + } + } + } + + $subs2 = ilUtil::sortArray($subs, "pos", 'ASC', true, true); + + return $subs2; + } + + return $subs; + } + + /** + * Get all subobjects by type. + * This function returns all subobjects allowed by the provided object type + * and all its subobject types recursively. + * + * This function is used to create local role templates. It is important, + * that we do not filter out any objects here! + * + * + * @param string object type + * @access public + * @return array list of allowed object types + */ + public function getSubObjectsRecursively($a_obj_type, $a_include_source_obj = true, $a_add_admin_objects = false) + { + $ilSetting = $this->settings; + + // This associative array is used to collect all subobject types. + // key=>type, value=data + $recursivesubs = array(); + + // This array is used to keep track of the object types, we + // need to call function getSubobjects() for. + $to_do = array($a_obj_type); + + // This array is used to keep track of the object types, we + // have called function getSubobjects() already. This is to + // prevent endless loops, for object types that support + // themselves as subobject types either directly or indirectly. + $done = array(); + + while (count($to_do) > 0) { + $type = array_pop($to_do); + $done[] = $type; + + // no recovery folder subitems + if ($type == 'recf') { + continue; + } + + // Hide administration if desired + if (!$a_add_admin_objects and $type == 'adm') { + $subs = array(); + } else { + $subs = $this->getSubObjects($type); + } + #vd('xxxxxxxxxxxxx'.$type); + foreach ($subs as $subtype => $data) { + #vd('------------------------->'.$subtype); + + // Hide role templates and folder from view + if ($this->getDevMode($subtype) or !$this->isRBACObject($subtype)) { + continue; + } + if ($subtype == 'rolt') { + continue; + } + if (!$a_add_admin_objects and $subtype == 'adm') { + continue; + } + + $recursivesubs[$subtype] = $data; + if (!in_array($subtype, $done) + && !in_array($subtype, $to_do)) { + $to_do[] = $subtype; + } + } + } + + if ($a_include_source_obj) { + if (!isset($recursivesubs[$a_obj_type])) { + $recursivesubs[$a_obj_type]['name'] = $a_obj_type; + $recursivesubs[$a_obj_type]['lng'] = $a_obj_type; + $recursivesubs[$a_obj_type]['max'] = 0; + $recursivesubs[$a_obj_type]['pos'] = -1; + } + } + return ilUtil::sortArray($recursivesubs, "pos", 'ASC', true, true); + } + + + /** + * get all subjects except (rolf) of the adm object + * This is necessary for filtering these objects in role perm view. + * e.g It it not necessary to view/edit role permission for the usrf object since it's not possible to create a new one + * + * @param string object type + * @access public + * @return array list of object types to filter + */ + public function getSubobjectsToFilter($a_obj_type = "adm") + { + foreach ($this->obj_data[$a_obj_type]["subobjects"] as $key => $value) { + switch ($key) { + case "rolf": + case "orgu": + // DO NOTHING + break; + + default: + $tmp_subs[] = $key; + } + } + // ADD adm and root object + $tmp_subs[] = "adm"; + #$tmp_subs[] = "root"; + + return $tmp_subs ? $tmp_subs : array(); + } + + /** + * get only creatable subobjects by type + * + * @param string object type + * @param integer context + * @param integer parent_ref_id + * @access public + * @return array list of createable object types + */ + public function getCreatableSubObjects($a_obj_type, $a_context = self::MODE_REPOSITORY, $a_parent_ref_id = null) + { + $subobjects = $this->getSubObjects($a_obj_type); + + // remove role folder object from list + unset($subobjects["rolf"]); + + $sub_types = array_keys($subobjects); + + // remove object types in development from list + foreach ($sub_types as $type) { + if ($this->getDevMode($type) || $this->isSystemObject($type)) { + unset($subobjects[$type]); + } + if ($a_context == self::MODE_REPOSITORY && !$this->isAllowedInRepository($type)) { + unset($subobjects[$type]); + } + if ($a_context == self::MODE_WORKSPACE && !$this->isAllowedInWorkspace($type)) { + unset($subobjects[$type]); + } + if ($a_context == self::MODE_ADMINISTRATION && !$this->isAdministrationObject($type)) { + unset($subobjects[$type]); + } + } + + if ($a_obj_type == "prg") { + // ask study program which objects are allowed to create on the concrete node. + require_once("Modules/StudyProgramme/classes/class.ilObjStudyProgramme.php"); + return ilObjStudyProgramme::getCreatableSubObjects($subobjects, $a_parent_ref_id); + } + + return $subobjects; + } + + /** + * get a string of all subobjects by type + * + * @param string object type + * @access public + */ + public function getSubObjectsAsString($a_obj_type) + { + $string = ""; + + if (is_array($this->obj_data[$a_obj_type]["subobjects"])) { + $data = array_keys($this->obj_data[$a_obj_type]["subobjects"]); + + $string = "'" . implode("','", $data) . "'"; + } + + return $string; + } + + /** + * Check if object type is container ('crs','fold','grp' ...) + * + * @access public + * @param string object type + * @return bool + * + */ + public function isContainer($a_obj_name) + { + if (!is_array($this->obj_data[$a_obj_name]['subobjects'])) { + return false; + } + return count($this->obj_data[$a_obj_name]['subobjects']) >= 1 ? true : false; + } + + // PRIVATE METHODS + + /** + * set event handler + * + * @param ressouce internal xml_parser_handler + * @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 tag handler + * + * @param ressouce internal xml_parser_handler + * @param string element tag name + * @param array element attributes + * @access private + */ + public function handlerBeginTag($a_xml_parser, $a_name, $a_attribs) + { + switch ($a_name) { + case 'object': + $this->parent_tag_name = $a_attribs["name"]; + break; + case 'property': + $this->current_tag = "property"; + $this->current_tag_name = $a_attribs["name"]; // $this->obj_data[$this->parent_tag_name]["properties"][$this->current_tag_name]["name"] = $a_attribs["name"]; - $this->obj_data[$this->parent_tag_name]["properties"][$this->current_tag_name]["module"] = $a_attribs["module"]; + $this->obj_data[$this->parent_tag_name]["properties"][$this->current_tag_name]["module"] = $a_attribs["module"]; //echo '
                  $this->obj_data["'.$this->parent_tag_name.'"]["properties"]["'.$this->current_tag_name.'"]["module"] = "'.$a_attribs["module"].'";'; - break; - } - } - - /** - * end tag handler - * - * @param ressouce internal xml_parser_handler - * @param string data - * @access private - */ - function handlerCharacterData($a_xml_parser,$a_data) - { - } - - /** - * end tag handler - * - * @param ressouce internal xml_parser_handler - * @param string element tag name - * @access private - */ - function handlerEndTag($a_xml_parser,$a_name) - { - $this->current_tag = ''; - $this->current_tag_name = ''; - } - - - function __filterObjects(&$subobjects) - { - foreach($subobjects as $type => $data) - { - switch($type) - { - default: - // DO NOTHING - } - } - } - - /** - * checks if object type is a system object - * - * system objects are those object types that are only used for - * internal purposes and to keep the object type model consistent. - * Typically they are used in the administation, exist only once - * and may contain only specific object types. - * To mark an object type as a system object type, use 'system=1' - * in the object definition in objects.xml - * - * @param string object type - * @access public - */ - function isSystemObject($a_obj_name) - { - return (bool) $this->obj_data[$a_obj_name]["system"]; - } - - /** - * Check, whether object type is a side block. - * - * @param string object type - * @return boolean side block true/false - */ - function isSideBlock($a_obj_name) - { - return (bool) $this->obj_data[$a_obj_name]["sideblock"]; - } - - /** - * Get all repository object types of component - */ - static function getRepositoryObjectTypesForComponent($a_component_type, - $a_component_name) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->queryF("SELECT * FROM il_object_def WHERE component = %s", - array("text"), array($a_component_type."/".$a_component_name)); - - $types = array(); - while($rec = $ilDB->fetchAssoc($set)) - { - if ($rec["system"] != 1) - { - $types[] = $rec; - } - } - - return $types; - } - - /** - * Get component for object type - */ - static function getComponentForType($a_obj_type) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->queryF("SELECT component FROM il_object_def WHERE id = %s", - array("text"), array($a_obj_type)); - - if ($rec = $ilDB->fetchAssoc($set)) - { - return $rec["component"]; - } - - return ""; - } - - /** - * @param $a_parent_obj_type - * @return array - */ - static function getGroupedRepositoryObjectTypes($a_parent_obj_type) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT * FROM il_object_group"); - $groups = array(); - while ($gr_rec = $set->fetchRow(ilDBConstants::FETCHMODE_ASSOC)) - { - $groups[$gr_rec["id"]] = $gr_rec; - } - - $global_cache = ilCachedComponentData::getInstance(); - - $recs = $global_cache->lookupGroupedRepObj($a_parent_obj_type); - - $grouped_obj = array(); - foreach((array)$recs as $rec) - { - if ($rec["grp"] != "") - { - $grouped_obj[$rec["grp"]]["pos"] = (int) $groups[$rec["grp"]]["default_pres_pos"]; - $grouped_obj[$rec["grp"]]["objs"][] = $rec["id"]; - } - else - { - $grouped_obj[$rec["id"]]["pos"] = (int) $rec["default_pres_pos"]; - $grouped_obj[$rec["id"]]["objs"][] = $rec["id"]; - } - } - // now get objects from repository plugin - $grouped_obj = self::getGroupedPluginObjectTypes($grouped_obj, IL_COMP_SERVICE, "Repository", "robj"); - $grouped_obj = self::getGroupedPluginObjectTypes($grouped_obj, IL_COMP_MODULE, "OrgUnit", "orguext"); - - $ret = ilUtil::sortArray($grouped_obj, "pos", "asc", true, true); - return $ret; - } - - /** - * checks if object type can be used in repository context - * - * @param string object type - * @access public - * @return bool - */ - function isAllowedInRepository($a_obj_name) - { - return (bool) $this->obj_data[$a_obj_name]["repository"]; - } - - /** - * get all RBAC object types - * - * @access public - * @return array object types set to development - */ - function getAllRepositoryTypes($a_incl_adm = false) - { - $types = array_keys($this->obj_data); - - foreach ($types as $type) - { - if ($this->isAllowedInRepository($type) && - (!$this->isAdministrationObject($type) || $a_incl_adm)) - { - $rbactypes[] = $type; - } - } - - return $rbactypes ? $rbactypes : array(); - } - - - /** - * checks if object type can be used in workspace context - * - * @param string object type - * @access public - * @return bool - */ - function isAllowedInWorkspace($a_obj_name) - { - return (bool) $this->obj_data[$a_obj_name]["workspace"]; - } - - /** - * Check if administration object - * @param string $a_obj_name - * @return bool - */ - public function isAdministrationObject($a_obj_name) - { - return (bool) $this->obj_data[$a_obj_name]['administration']; - } - - /** - * Check whether type belongs to inactive plugin - * - * @param - * @return - */ - public function isInactivePlugin($a_type) - { - if (substr($a_type, 0, 1) == "x" && !$this->isPlugin($a_type)) - { - return true; - } - return false; - } - - /** - * Get advanced meta data objects - * - * @param - * @return - */ - function getAdvancedMetaDataTypes() - { - $amet = array(); - foreach ($this->obj_data as $k => $v) - { - if ($v["amet"]) - { - $amet[] = array("obj_type" => $k, "sub_type" => ""); - } - } - - foreach ($this->sub_types as $type => $sub_types) - { - foreach ($sub_types as $t) - { - if ($t["amet"]) - { - $amet[] = array("obj_type" => $type, "sub_type" => $t["sub_type"]); - } - } - } - - return $amet; - } - - /** - * Get object type with orgunit position permission support - * @return string[] $types - */ - public function getOrgUnitPermissionTypes() - { - $types = []; - foreach($this->obj_data as $type => $object_info) { - if($object_info['orgunit_permissions']) { - $types[] = $type; - } - } - return $types; - } - - /** - * Get object types which offer lti provider support. - * @return string[] $types - */ - public function getLTIProviderTypes() - { - $types = []; - foreach($this->obj_data as $type => $object_info) { - if($object_info['lti_provider']) { - $types[] = $type; - } - } - return $types; - - } - - /** - * Check if object type offers orgunit position support - * @param string $obj_type - * @return bool - */ - public function isOrgUnitPermissionType($a_obj_type) - { - return in_array($a_obj_type, $this->getOrgUnitPermissionTypes()); - } - - /** - * Get Position By Object Type - * - * @param $a_type - * @return int - */ - function getPositionByType($a_type) - { - $ilSetting = $this->settings; - - return ($ilSetting->get("obj_add_new_pos_".$a_type) > 0) - ? (int) $ilSetting->get("obj_add_new_pos_".$a_type) - : (int) $this->obj_data[$a_type]["default_pos"]; - } - - /** - * Get plugin object info - * @return type - */ - public function getPlugins() - { - $plugins = array(); - foreach((array) $this->obj_data as $type => $pl_data) - { - if($this->isPlugin($type)) - { - $plugins[$type] = $pl_data; - } - } - return $plugins; - } - - /** - * Get all object types which are defined as container in an explorer context - * - * @return array - */ - public function getExplorerContainerTypes() - { - $res = $grp_map = $cnt_grp = array(); - - // all repository object types - foreach ($this->getSubObjectsRecursively("root") as $rtype) - { - $type = $rtype["name"]; - - // obsolete - if($type == "rolf") - { - continue; - } - - // gather group data - $type_grp = $this->getGroupOfObj($type); - if($type_grp) - { - $grp_map[$type_grp][] = $type; - } - - // add basic container types - if($this->isContainer($type)) - { - // add to cnt_grp - if($type_grp) - { - $cnt_grp[] = $type_grp; - } - - $res[] = $type; - } - } - - // add complete groups (cat => rcat, catr; crs => rcrs, crsr; ...) - foreach($cnt_grp as $grp) - { - $res = array_merge($res, $grp_map[$grp]); - } - - // add very special case - // outcommented, see bug #25662 -// $res[] = "itgr"; - - return array_unique($res); - } - - /** - * check whether obj_type supports centralised offline handling - * - * @param $a_obj_type - * @return bool - */ - public function supportsOfflineHandling($a_obj_type) - { - return - isset($this->obj_data[$a_obj_type]) && - (bool) $this->obj_data[$a_obj_type]['offline_handling']; - } - - - /** - * Loads the different plugins into the object definition. - * @internal param $ilPluginAdmin - * @internal param $rec - */ - protected function readPluginData() { - $this->parsePluginData(IL_COMP_SERVICE, "Repository", "robj", false); - $this->parsePluginData(IL_COMP_MODULE, "OrgUnit", "orguext", true); - } - - /** - * loads a single plugin definition into the object definition - * @param $component The component e.g. IL_COMP_SERVICE - * @param $slotName The Slot name, e.g. Repository - * @param $slotId the slot id, e.g. robj - * @param $isInAdministration, can the object be created in the administration? - */ - protected function parsePluginData($component, $slotName, $slotId, $isInAdministration) { - $ilPluginAdmin = $this->plugin_admin; - $pl_names = $ilPluginAdmin->getActivePluginsForSlot($component, $slotName, $slotId); - foreach ($pl_names as $pl_name) { - include_once("./Services/Component/classes/class.ilPlugin.php"); - $pl_id = ilPlugin::lookupIdForName($component, $slotName, $slotId, $pl_name); - if ($pl_id != "" && !isset($this->obj_data[$pl_id])) { - include_once("./Services/Repository/classes/class.ilRepositoryObjectPlugin.php"); - $loc = ilPlugin::_getDirectory($component, $slotName, $slotId, $pl_name) . "/classes"; - // The plugin_id is the same as the type_id in repository object plugins. - $pl = ilObjectPlugin::getPluginObjectByType($pl_id); - - $this->obj_data[$pl_id] = array( - "name" => $pl_id, - "class_name" => $pl_name, - "plugin" => "1", - "location" => $loc, - "checkbox" => "1", - "inherit" => "0", - "component" => "", - "translate" => "0", - "devmode" => "0", - "allow_link" => "1", - "allow_copy" => $pl->allowCopy() ? '1' : '0', - "rbac" => "1", - "group" => NULL, - "system" => "0", - "default_pos" => "99992000", // "unassigned" group - 'repository' => '1', - 'workspace' => '0', - 'administration' => $isInAdministration?'1':'0', - "sideblock" => "0", - 'export' => $ilPluginAdmin->supportsExport($component, $slotName, $slotId, $pl_name), - 'offline_handling' => '0' - ); - $parent_types = $pl->getParentTypes(); - foreach($parent_types as $parent_type) { - $this->obj_data[$parent_type]["subobjects"][$pl_id] = array("name" => $pl_id, "max" => "", "lng" => $pl_id, "plugin" => true); - } - } - } - } - + break; + } + } + + /** + * end tag handler + * + * @param ressouce internal xml_parser_handler + * @param string data + * @access private + */ + public function handlerCharacterData($a_xml_parser, $a_data) + { + } + + /** + * end tag handler + * + * @param ressouce internal xml_parser_handler + * @param string element tag name + * @access private + */ + public function handlerEndTag($a_xml_parser, $a_name) + { + $this->current_tag = ''; + $this->current_tag_name = ''; + } + + + public function __filterObjects(&$subobjects) + { + foreach ($subobjects as $type => $data) { + switch ($type) { + default: + // DO NOTHING + } + } + } + + /** + * checks if object type is a system object + * + * system objects are those object types that are only used for + * internal purposes and to keep the object type model consistent. + * Typically they are used in the administation, exist only once + * and may contain only specific object types. + * To mark an object type as a system object type, use 'system=1' + * in the object definition in objects.xml + * + * @param string object type + * @access public + */ + public function isSystemObject($a_obj_name) + { + return (bool) $this->obj_data[$a_obj_name]["system"]; + } + + /** + * Check, whether object type is a side block. + * + * @param string object type + * @return boolean side block true/false + */ + public function isSideBlock($a_obj_name) + { + return (bool) $this->obj_data[$a_obj_name]["sideblock"]; + } + + /** + * Get all repository object types of component + */ + public static function getRepositoryObjectTypesForComponent( + $a_component_type, + $a_component_name + ) { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->queryF( + "SELECT * FROM il_object_def WHERE component = %s", + array("text"), + array($a_component_type . "/" . $a_component_name) + ); + + $types = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + if ($rec["system"] != 1) { + $types[] = $rec; + } + } + + return $types; + } + + /** + * Get component for object type + */ + public static function getComponentForType($a_obj_type) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->queryF( + "SELECT component FROM il_object_def WHERE id = %s", + array("text"), + array($a_obj_type) + ); + + if ($rec = $ilDB->fetchAssoc($set)) { + return $rec["component"]; + } + + return ""; + } + + /** + * @param $a_parent_obj_type + * @return array + */ + public static function getGroupedRepositoryObjectTypes($a_parent_obj_type) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query("SELECT * FROM il_object_group"); + $groups = array(); + while ($gr_rec = $set->fetchRow(ilDBConstants::FETCHMODE_ASSOC)) { + $groups[$gr_rec["id"]] = $gr_rec; + } + + $global_cache = ilCachedComponentData::getInstance(); + + $recs = $global_cache->lookupGroupedRepObj($a_parent_obj_type); + + $grouped_obj = array(); + foreach ((array) $recs as $rec) { + if ($rec["grp"] != "") { + $grouped_obj[$rec["grp"]]["pos"] = (int) $groups[$rec["grp"]]["default_pres_pos"]; + $grouped_obj[$rec["grp"]]["objs"][] = $rec["id"]; + } else { + $grouped_obj[$rec["id"]]["pos"] = (int) $rec["default_pres_pos"]; + $grouped_obj[$rec["id"]]["objs"][] = $rec["id"]; + } + } + // now get objects from repository plugin + $grouped_obj = self::getGroupedPluginObjectTypes($grouped_obj, IL_COMP_SERVICE, "Repository", "robj"); + $grouped_obj = self::getGroupedPluginObjectTypes($grouped_obj, IL_COMP_MODULE, "OrgUnit", "orguext"); + + $ret = ilUtil::sortArray($grouped_obj, "pos", "asc", true, true); + return $ret; + } + + /** + * checks if object type can be used in repository context + * + * @param string object type + * @access public + * @return bool + */ + public function isAllowedInRepository($a_obj_name) + { + return (bool) $this->obj_data[$a_obj_name]["repository"]; + } + + /** + * get all RBAC object types + * + * @access public + * @return array object types set to development + */ + public function getAllRepositoryTypes($a_incl_adm = false) + { + $types = array_keys($this->obj_data); + + foreach ($types as $type) { + if ($this->isAllowedInRepository($type) && + (!$this->isAdministrationObject($type) || $a_incl_adm)) { + $rbactypes[] = $type; + } + } + + return $rbactypes ? $rbactypes : array(); + } + + + /** + * checks if object type can be used in workspace context + * + * @param string object type + * @access public + * @return bool + */ + public function isAllowedInWorkspace($a_obj_name) + { + return (bool) $this->obj_data[$a_obj_name]["workspace"]; + } + + /** + * Check if administration object + * @param string $a_obj_name + * @return bool + */ + public function isAdministrationObject($a_obj_name) + { + return (bool) $this->obj_data[$a_obj_name]['administration']; + } + + /** + * Check whether type belongs to inactive plugin + * + * @param + * @return + */ + public function isInactivePlugin($a_type) + { + if (substr($a_type, 0, 1) == "x" && !$this->isPlugin($a_type)) { + return true; + } + return false; + } + + /** + * Get advanced meta data objects + * + * @param + * @return + */ + public function getAdvancedMetaDataTypes() + { + $amet = array(); + foreach ($this->obj_data as $k => $v) { + if ($v["amet"]) { + $amet[] = array("obj_type" => $k, "sub_type" => ""); + } + } + + foreach ($this->sub_types as $type => $sub_types) { + foreach ($sub_types as $t) { + if ($t["amet"]) { + $amet[] = array("obj_type" => $type, "sub_type" => $t["sub_type"]); + } + } + } + + return $amet; + } + + /** + * Get object type with orgunit position permission support + * @return string[] $types + */ + public function getOrgUnitPermissionTypes() + { + $types = []; + foreach ($this->obj_data as $type => $object_info) { + if ($object_info['orgunit_permissions']) { + $types[] = $type; + } + } + return $types; + } + + /** + * Get object types which offer lti provider support. + * @return string[] $types + */ + public function getLTIProviderTypes() + { + $types = []; + foreach ($this->obj_data as $type => $object_info) { + if ($object_info['lti_provider']) { + $types[] = $type; + } + } + return $types; + } + + /** + * Check if object type offers orgunit position support + * @param string $obj_type + * @return bool + */ + public function isOrgUnitPermissionType($a_obj_type) + { + return in_array($a_obj_type, $this->getOrgUnitPermissionTypes()); + } + + /** + * Get Position By Object Type + * + * @param $a_type + * @return int + */ + public function getPositionByType($a_type) + { + $ilSetting = $this->settings; + + return ($ilSetting->get("obj_add_new_pos_" . $a_type) > 0) + ? (int) $ilSetting->get("obj_add_new_pos_" . $a_type) + : (int) $this->obj_data[$a_type]["default_pos"]; + } + + /** + * Get plugin object info + * @return type + */ + public function getPlugins() + { + $plugins = array(); + foreach ((array) $this->obj_data as $type => $pl_data) { + if ($this->isPlugin($type)) { + $plugins[$type] = $pl_data; + } + } + return $plugins; + } + + /** + * Get all object types which are defined as container in an explorer context + * + * @return array + */ + public function getExplorerContainerTypes() + { + $res = $grp_map = $cnt_grp = array(); + + // all repository object types + foreach ($this->getSubObjectsRecursively("root") as $rtype) { + $type = $rtype["name"]; + + // obsolete + if ($type == "rolf") { + continue; + } + + // gather group data + $type_grp = $this->getGroupOfObj($type); + if ($type_grp) { + $grp_map[$type_grp][] = $type; + } + + // add basic container types + if ($this->isContainer($type)) { + // add to cnt_grp + if ($type_grp) { + $cnt_grp[] = $type_grp; + } + + $res[] = $type; + } + } + + // add complete groups (cat => rcat, catr; crs => rcrs, crsr; ...) + foreach ($cnt_grp as $grp) { + $res = array_merge($res, $grp_map[$grp]); + } + + // add very special case + // outcommented, see bug #25662 + // $res[] = "itgr"; + + return array_unique($res); + } + + /** + * check whether obj_type supports centralised offline handling + * + * @param $a_obj_type + * @return bool + */ + public function supportsOfflineHandling($a_obj_type) + { + return + isset($this->obj_data[$a_obj_type]) && + (bool) $this->obj_data[$a_obj_type]['offline_handling']; + } + + + /** + * Loads the different plugins into the object definition. + * @internal param $ilPluginAdmin + * @internal param $rec + */ + protected function readPluginData() + { + $this->parsePluginData(IL_COMP_SERVICE, "Repository", "robj", false); + $this->parsePluginData(IL_COMP_MODULE, "OrgUnit", "orguext", true); + } + + /** + * loads a single plugin definition into the object definition + * @param $component The component e.g. IL_COMP_SERVICE + * @param $slotName The Slot name, e.g. Repository + * @param $slotId the slot id, e.g. robj + * @param $isInAdministration, can the object be created in the administration? + */ + protected function parsePluginData($component, $slotName, $slotId, $isInAdministration) + { + $ilPluginAdmin = $this->plugin_admin; + $pl_names = $ilPluginAdmin->getActivePluginsForSlot($component, $slotName, $slotId); + foreach ($pl_names as $pl_name) { + include_once("./Services/Component/classes/class.ilPlugin.php"); + $pl_id = ilPlugin::lookupIdForName($component, $slotName, $slotId, $pl_name); + if ($pl_id != "" && !isset($this->obj_data[$pl_id])) { + include_once("./Services/Repository/classes/class.ilRepositoryObjectPlugin.php"); + $loc = ilPlugin::_getDirectory($component, $slotName, $slotId, $pl_name) . "/classes"; + // The plugin_id is the same as the type_id in repository object plugins. + $pl = ilObjectPlugin::getPluginObjectByType($pl_id); + + $this->obj_data[$pl_id] = array( + "name" => $pl_id, + "class_name" => $pl_name, + "plugin" => "1", + "location" => $loc, + "checkbox" => "1", + "inherit" => "0", + "component" => "", + "translate" => "0", + "devmode" => "0", + "allow_link" => "1", + "allow_copy" => $pl->allowCopy() ? '1' : '0', + "rbac" => "1", + "group" => null, + "system" => "0", + "default_pos" => "99992000", // "unassigned" group + 'repository' => '1', + 'workspace' => '0', + 'administration' => $isInAdministration?'1':'0', + "sideblock" => "0", + 'export' => $ilPluginAdmin->supportsExport($component, $slotName, $slotId, $pl_name), + 'offline_handling' => '0' + ); + $parent_types = $pl->getParentTypes(); + foreach ($parent_types as $parent_type) { + $this->obj_data[$parent_type]["subobjects"][$pl_id] = array("name" => $pl_id, "max" => "", "lng" => $pl_id, "plugin" => true); + } + } + } + } } -?> diff --git a/Services/Object/classes/class.ilObjectExporter.php b/Services/Object/classes/class.ilObjectExporter.php index f56ffbf531eb60fb3a12febbef51671040eea083..a4acafa799dfb82dad01449aaae8c7c71af67595 100644 --- a/Services/Object/classes/class.ilObjectExporter.php +++ b/Services/Object/classes/class.ilObjectExporter.php @@ -14,56 +14,56 @@ include_once("./Services/Export/classes/class.ilXmlExporter.php"); */ class ilObjectExporter extends ilXmlExporter { - private $ds; + private $ds; - /** - * Initialisation - */ - function init() - { - include_once("./Services/Object/classes/class.ilObjectDataSet.php"); - $this->ds = new ilObjectDataSet(); - $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); - $this->ds->setDSPrefix("ds"); - } + /** + * Initialisation + */ + public function init() + { + include_once("./Services/Object/classes/class.ilObjectDataSet.php"); + $this->ds = new ilObjectDataSet(); + $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); + $this->ds->setDSPrefix("ds"); + } - /** - * Get tail dependencies - * - * @param string entity - * @param string target release - * @param array ids - * @return array array of array with keys "component", entity", "ids" - */ - function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) - { - return array(); - } + /** + * Get tail dependencies + * + * @param string entity + * @param string target release + * @param array ids + * @return array array of array with keys "component", entity", "ids" + */ + public function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) + { + return array(); + } - /** - * Get xml representation - * - * @param string entity - * @param string target release - * @param string id - * @return string xml string - */ - public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) - { + /** + * Get xml representation + * + * @param string entity + * @param string target release + * @param string id + * @return string xml string + */ + 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); - } + return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); + } - /** - * Returns schema versions that the component can export to. - * ILIAS chooses the first one, that has min/max constraints which - * fit to the target release. Please put the newest on top. - * - * @return - */ - function getValidSchemaVersions($a_entity) - { - return array ( + /** + * Returns schema versions that the component can export to. + * ILIAS chooses the first one, that has min/max constraints which + * fit to the target release. Please put the newest on top. + * + * @return + */ + public function getValidSchemaVersions($a_entity) + { + return array( "5.4.0" => array( "namespace" => "http://www.ilias.de/Services/Object/obj/5_4", "xsd_file" => "ilias_obj_5_4.xsd", @@ -76,15 +76,12 @@ class ilObjectExporter extends ilXmlExporter "uses_dataset" => true, "min" => "5.1.0", "max" => "5.3.99"), - "4.4.0" => array( - "namespace" => "http://www.ilias.de/Services/Object/obj/4_4", - "xsd_file" => "ilias_obj_4_4.xsd", - "uses_dataset" => true, - "min" => "4.4.0", - "max" => "5.0.99") - ); - } - + "4.4.0" => array( + "namespace" => "http://www.ilias.de/Services/Object/obj/4_4", + "xsd_file" => "ilias_obj_4_4.xsd", + "uses_dataset" => true, + "min" => "4.4.0", + "max" => "5.0.99") + ); + } } - -?> \ No newline at end of file diff --git a/Services/Object/classes/class.ilObjectFactory.php b/Services/Object/classes/class.ilObjectFactory.php index e561ffd3c804a6c4725b341a91eafdd17154a547..ec964f68fed0938e99d75624caf095475b267ff3 100755 --- a/Services/Object/classes/class.ilObjectFactory.php +++ b/Services/Object/classes/class.ilObjectFactory.php @@ -19,264 +19,246 @@ */ class ilObjectFactory { - /** - * check if obj_id exists. To check for ref_ids use ilTree::isInTree() - * - * @param int $obj_id object id - * @return bool - */ - function ObjectIdExists($a_obj_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT * FROM object_data ". - "WHERE obj_id = ".$ilDB->quote($a_obj_id ,'integer'); - - $res = $ilDB->query($query); - - return $res->numRows() ? true : false; - } - - /** - * returns all objects of an owner, filtered by type, objects are not deleted! - * - * @param unknown_type $object_type - * @param unknown_type $owner_id - * @return unknown - */ - function getObjectsForOwner ($object_type, $owner_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT * FROM object_data,object_reference ". - "WHERE object_reference.obj_id = object_data.obj_id ". - " AND object_data.type=".$ilDB->quote($object_type,'text'). - " AND object_data.owner = ".$ilDB->quote($owner_id,'integer'); - $res = $ilDB->query($query); - - $obj_ids = array(); - while($object_rec = $res->fetchRow(ilDBConstants::FETCHMODE_ASSOC)) { - $obj_ids [] = $object_rec["obj_id"]; - } - - return $obj_ids; - - } - - /** - * get an instance of an Ilias object by object id - * @param $a_obj_id - * @param bool $stop_on_error - * @return bool|ilObject - * @throws ilDatabaseException - * @throws ilObjectNotFoundException - */ - static function getInstanceByObjId($a_obj_id,$stop_on_error = true) - { - global $DIC; - - $objDefinition = $DIC["objDefinition"]; - $ilDB = $DIC->database(); - - // check object id - if (!isset($a_obj_id)) - { - $message = "ilObjectFactory::getInstanceByObjId(): No obj_id given!"; - if ($stop_on_error === true) - { - throw new ilObjectNotFoundException($message); - } - - return false; - } - - // read object data - $q = "SELECT * FROM object_data ". - "WHERE obj_id = ".$ilDB->quote($a_obj_id ,'integer'); - $object_set = $ilDB->query($q); - // check number of records - if ($object_set->numRows() == 0) - { - $message = "ilObjectFactory::getInstanceByObjId(): Object with obj_id: ".$a_obj_id." not found!"; - if ($stop_on_error === true) - { - throw new ilObjectNotFoundException($message); - } - return false; - } - - $object_rec = $object_set->fetchRow(ilDBConstants::FETCHMODE_ASSOC); - $class_name = "ilObj".$objDefinition->getClassName($object_rec["type"]); - - // check class - if ($class_name == "ilObj") - { - $message = "ilObjectFactory::getInstanceByObjId(): Not able to determine object ". - "class for type".$object_rec["type"]."."; - if ($stop_on_error === true) - { - throw new ilObjectNotFoundException($message); - } - return false; - } - - // get location - $location = $objDefinition->getLocation($object_rec["type"]); - - // create instance - include_once($location."/class.".$class_name.".php"); - $obj = new $class_name(0, false); // this avoids reading of data - $obj->setId($a_obj_id); - $obj->read(); - - return $obj; - } - - - /** - * get an instance of an Ilias object by reference id - * @param $a_ref_id - * @param bool $stop_on_error - * @return bool|ilObject - * @throws ilDatabaseException - * @throws ilObjectNotFoundException - */ - static function getInstanceByRefId($a_ref_id,$stop_on_error = true) - { - global $DIC; - - $objDefinition = $DIC["objDefinition"]; - $ilDB = $DIC->database(); - - // check reference id - if (!isset($a_ref_id)) - { - if ($stop_on_error === true) - { - $message = "ilObjectFactory::getInstanceByRefId(): No ref_id given!"; - throw new ilObjectNotFoundException($message); - } - - return false; - } - - // read object data - - $query = "SELECT * FROM object_data,object_reference ". - "WHERE object_reference.obj_id = object_data.obj_id ". - "AND object_reference.ref_id = ".$ilDB->quote($a_ref_id,'integer'); - $object_set = $ilDB->query($query); - - // check number of records - if ($object_set->numRows() == 0) - { - if ($stop_on_error === true) - { - $message = "ilObjectFactory::getInstanceByRefId(): Object with ref_id ".$a_ref_id." not found!"; - throw new ilObjectNotFoundException($message); - } - - return false; - } - - $object_rec = $object_set->fetchRow(ilDBConstants::FETCHMODE_ASSOC); - $class_name = "ilObj".$objDefinition->getClassName($object_rec["type"]); - - // check class - if ($class_name == "ilObj") - { - if ($stop_on_error === true) - { - $message = "ilObjectFactory::getInstanceByRefId(): Not able to determine object ". - "class for type".$object_rec["type"]."."; - throw new ilObjectNotFoundException($message); - } - - return false; - } - - // get location - $location = $objDefinition->getLocation($object_rec["type"]); - - // create instance - include_once($location."/class.".$class_name.".php"); - $obj = new $class_name(0, false); // this avoids reading of data - $obj->setId($object_rec["obj_id"]); - $obj->setRefId($a_ref_id); - $obj->read(); - return $obj; - } - - /** - * get object type by reference id - * - * @deprecated since version 5.3 - * @param $a_ref_id - * @param bool $stop_on_error - * @return bool - * @throws ilDatabaseException - * @throws ilObjectNotFoundException - */ - public static function getTypeByRefId($a_ref_id, $stop_on_error = true) - { - global $DIC; - - $ilDB = $DIC->database(); - - // check reference id - if (!isset($a_ref_id)) - { - if ($stop_on_error === true) - { - $message = "ilObjectFactory::getTypeByRefId(): No ref_id given!"; - throw new ilObjectNotFoundException($message); - } - - return false; - } - - // read object data - $q = "SELECT * FROM object_data ". - "LEFT JOIN object_reference ON object_data.obj_id=object_reference.obj_id ". - "WHERE object_reference.ref_id=".$ilDB->quote($a_ref_id,'integer'); - $object_set = $ilDB->query($q); - - if ($object_set->numRows() == 0) - { - if ($stop_on_error === true) - { - $message = "ilObjectFactory::getTypeByRefId(): Object with ref_id ".$a_ref_id." not found!"; - throw new ilObjectNotFoundException($message); - } - - return false; - } - - $object_rec = $object_set->fetchRow(ilDBConstants::FETCHMODE_ASSOC); - return $object_rec["type"]; - } - - /** - * Get class by type - * - * @return - */ - public static function getClassByType($a_obj_type) - { - global $DIC; - - $objDefinition = $DIC["objDefinition"]; - - $location = $objDefinition->getLocation($a_obj_type); - $class_name = "ilObj".$objDefinition->getClassName($a_obj_type); - - // create instance - include_once($location."/class.".$class_name.".php"); - return $class_name; - } + /** + * check if obj_id exists. To check for ref_ids use ilTree::isInTree() + * + * @param int $obj_id object id + * @return bool + */ + public function ObjectIdExists($a_obj_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT * FROM object_data " . + "WHERE obj_id = " . $ilDB->quote($a_obj_id, 'integer'); + + $res = $ilDB->query($query); + + return $res->numRows() ? true : false; + } + + /** + * returns all objects of an owner, filtered by type, objects are not deleted! + * + * @param unknown_type $object_type + * @param unknown_type $owner_id + * @return unknown + */ + public function getObjectsForOwner($object_type, $owner_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT * FROM object_data,object_reference " . + "WHERE object_reference.obj_id = object_data.obj_id " . + " AND object_data.type=" . $ilDB->quote($object_type, 'text') . + " AND object_data.owner = " . $ilDB->quote($owner_id, 'integer'); + $res = $ilDB->query($query); + + $obj_ids = array(); + while ($object_rec = $res->fetchRow(ilDBConstants::FETCHMODE_ASSOC)) { + $obj_ids [] = $object_rec["obj_id"]; + } + + return $obj_ids; + } + + /** + * get an instance of an Ilias object by object id + * @param $a_obj_id + * @param bool $stop_on_error + * @return bool|ilObject + * @throws ilDatabaseException + * @throws ilObjectNotFoundException + */ + public static function getInstanceByObjId($a_obj_id, $stop_on_error = true) + { + global $DIC; + + $objDefinition = $DIC["objDefinition"]; + $ilDB = $DIC->database(); + + // check object id + if (!isset($a_obj_id)) { + $message = "ilObjectFactory::getInstanceByObjId(): No obj_id given!"; + if ($stop_on_error === true) { + throw new ilObjectNotFoundException($message); + } + + return false; + } + + // read object data + $q = "SELECT * FROM object_data " . + "WHERE obj_id = " . $ilDB->quote($a_obj_id, 'integer'); + $object_set = $ilDB->query($q); + // check number of records + if ($object_set->numRows() == 0) { + $message = "ilObjectFactory::getInstanceByObjId(): Object with obj_id: " . $a_obj_id . " not found!"; + if ($stop_on_error === true) { + throw new ilObjectNotFoundException($message); + } + return false; + } + + $object_rec = $object_set->fetchRow(ilDBConstants::FETCHMODE_ASSOC); + $class_name = "ilObj" . $objDefinition->getClassName($object_rec["type"]); + + // check class + if ($class_name == "ilObj") { + $message = "ilObjectFactory::getInstanceByObjId(): Not able to determine object " . + "class for type" . $object_rec["type"] . "."; + if ($stop_on_error === true) { + throw new ilObjectNotFoundException($message); + } + return false; + } + + // get location + $location = $objDefinition->getLocation($object_rec["type"]); + + // create instance + include_once($location . "/class." . $class_name . ".php"); + $obj = new $class_name(0, false); // this avoids reading of data + $obj->setId($a_obj_id); + $obj->read(); + + return $obj; + } + + + /** + * get an instance of an Ilias object by reference id + * @param $a_ref_id + * @param bool $stop_on_error + * @return bool|ilObject + * @throws ilDatabaseException + * @throws ilObjectNotFoundException + */ + public static function getInstanceByRefId($a_ref_id, $stop_on_error = true) + { + global $DIC; + + $objDefinition = $DIC["objDefinition"]; + $ilDB = $DIC->database(); + + // check reference id + if (!isset($a_ref_id)) { + if ($stop_on_error === true) { + $message = "ilObjectFactory::getInstanceByRefId(): No ref_id given!"; + throw new ilObjectNotFoundException($message); + } + + return false; + } + + // read object data + + $query = "SELECT * FROM object_data,object_reference " . + "WHERE object_reference.obj_id = object_data.obj_id " . + "AND object_reference.ref_id = " . $ilDB->quote($a_ref_id, 'integer'); + $object_set = $ilDB->query($query); + + // check number of records + if ($object_set->numRows() == 0) { + if ($stop_on_error === true) { + $message = "ilObjectFactory::getInstanceByRefId(): Object with ref_id " . $a_ref_id . " not found!"; + throw new ilObjectNotFoundException($message); + } + + return false; + } + + $object_rec = $object_set->fetchRow(ilDBConstants::FETCHMODE_ASSOC); + $class_name = "ilObj" . $objDefinition->getClassName($object_rec["type"]); + + // check class + if ($class_name == "ilObj") { + if ($stop_on_error === true) { + $message = "ilObjectFactory::getInstanceByRefId(): Not able to determine object " . + "class for type" . $object_rec["type"] . "."; + throw new ilObjectNotFoundException($message); + } + + return false; + } + + // get location + $location = $objDefinition->getLocation($object_rec["type"]); + + // create instance + include_once($location . "/class." . $class_name . ".php"); + $obj = new $class_name(0, false); // this avoids reading of data + $obj->setId($object_rec["obj_id"]); + $obj->setRefId($a_ref_id); + $obj->read(); + return $obj; + } + + /** + * get object type by reference id + * + * @deprecated since version 5.3 + * @param $a_ref_id + * @param bool $stop_on_error + * @return bool + * @throws ilDatabaseException + * @throws ilObjectNotFoundException + */ + public static function getTypeByRefId($a_ref_id, $stop_on_error = true) + { + global $DIC; + + $ilDB = $DIC->database(); + + // check reference id + if (!isset($a_ref_id)) { + if ($stop_on_error === true) { + $message = "ilObjectFactory::getTypeByRefId(): No ref_id given!"; + throw new ilObjectNotFoundException($message); + } + + return false; + } + + // read object data + $q = "SELECT * FROM object_data " . + "LEFT JOIN object_reference ON object_data.obj_id=object_reference.obj_id " . + "WHERE object_reference.ref_id=" . $ilDB->quote($a_ref_id, 'integer'); + $object_set = $ilDB->query($q); + + if ($object_set->numRows() == 0) { + if ($stop_on_error === true) { + $message = "ilObjectFactory::getTypeByRefId(): Object with ref_id " . $a_ref_id . " not found!"; + throw new ilObjectNotFoundException($message); + } + + return false; + } + + $object_rec = $object_set->fetchRow(ilDBConstants::FETCHMODE_ASSOC); + return $object_rec["type"]; + } + + /** + * Get class by type + * + * @return + */ + public static function getClassByType($a_obj_type) + { + global $DIC; + + $objDefinition = $DIC["objDefinition"]; + + $location = $objDefinition->getLocation($a_obj_type); + $class_name = "ilObj" . $objDefinition->getClassName($a_obj_type); + + // create instance + include_once($location . "/class." . $class_name . ".php"); + return $class_name; + } } -?> \ No newline at end of file diff --git a/Services/Object/classes/class.ilObjectGUI.php b/Services/Object/classes/class.ilObjectGUI.php index eedd3d7baa1eb9d7690f8f2d157bc0e7c36d4f8d..82ade7d22a83a581da9929ffc762997479909aa0 100755 --- a/Services/Object/classes/class.ilObjectGUI.php +++ b/Services/Object/classes/class.ilObjectGUI.php @@ -12,2250 +12,2098 @@ */ class ilObjectGUI { - /** - * @var ilErrorHandling - */ - protected $ilErr; - - /** - * @var ilLocatorGUI - */ - protected $locator; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilSetting - */ - protected $settings; - - /** - * @var ilRbacReview - */ - protected $rbacreview; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - const COPY_WIZARD_NEEDS_PAGE = 1; - - - /** - * object Definition Object - * @var object ilias - * @access private - */ - var $objDefinition; - - /** - * template object - * @var object ilias - * @access private - */ - var $tpl; - - /** - * tree object - * @var object ilias - * @access private - */ - var $tree; - - /** - * language object - * @var object language (of ilObject) - * @access private - */ - var $lng; - - /** - * output data - * @var data array - * @access private - */ - var $data; - - /** - * object - * @var object - * @access private - */ - var $object; - var $ref_id; - var $obj_id; - var $maxcount; // contains number of child objects - var $formaction; // special formation (array "cmd" => "formaction") - var $return_location; // special return location (array "cmd" => "location") - var $target_frame; // special target frame (array "cmd" => "location") - protected $tmp_import_dir; // directory used during import - - var $tab_target_script; - var $actions; - var $sub_objects; - var $omit_locator = false; - - /** - * @var ilTabsGUI - */ - protected $tabs_gui = null; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilObjectService - */ - protected $object_service; - - const CFORM_NEW = 1; - const CFORM_IMPORT = 2; - const CFORM_CLONE = 3; - - /** - * Constructor - * @access public - * @param array ?? - * @param integer object id - * @param boolean call be reference - */ - function __construct($a_data, $a_id = 0, $a_call_by_reference = true, $a_prepare_output = true) - { - global $DIC; - - $this->locator = $DIC["ilLocator"]; - $this->user = $DIC->user(); - $this->access = $DIC->access(); - $this->settings = $DIC->settings(); - $this->rbacreview = $DIC->rbac()->review(); - $this->toolbar = $DIC->toolbar(); - $this->object_service = $DIC->object(); - $objDefinition = $DIC["objDefinition"]; - $tpl = $DIC["tpl"]; - $tree = $DIC->repositoryTree(); - $ilCtrl = $DIC->ctrl(); - $ilErr = $DIC["ilErr"]; - $lng = $DIC->language(); - $ilTabs = $DIC->tabs(); - - $this->ilias = $DIC["ilias"]; - - /** - * @var ilTab - */ - $this->tabs_gui = $ilTabs; - - if (!isset($ilErr)) - { - $ilErr = new ilErrorHandling(); - $ilErr->setErrorHandling(PEAR_ERROR_CALLBACK,array($ilErr,'errorHandler')); - } - else - { - $this->ilErr = $ilErr; - } - - $this->objDefinition = $objDefinition; - $this->tpl = $tpl; - $this->html = ""; - $this->ctrl = $ilCtrl; - - $params = array("ref_id"); - - if (!$a_call_by_reference) - { - $params = array("ref_id","obj_id"); - } - - $this->ctrl->saveParameter($this, $params); - - $this->lng = $lng; - $this->tree = $tree; - $this->formaction = array(); - $this->return_location = array(); - $this->target_frame = array(); - $this->actions = ""; - $this->sub_objects = ""; - - $this->data = $a_data; - $this->id = $a_id; - $this->call_by_reference = $a_call_by_reference; - $this->prepare_output = $a_prepare_output; - $this->creation_mode = false; - - $this->ref_id = ($this->call_by_reference) ? $this->id : $_GET["ref_id"]; - $this->obj_id = ($this->call_by_reference) ? $_GET["obj_id"] : $this->id; - - if ($this->id != 0) - { - $this->link_params = "ref_id=".$this->ref_id; - } - - // get the object - $this->assignObject(); - - // set context - if (is_object($this->object)) - { - if ($this->call_by_reference && $this->ref_id == $_GET["ref_id"]) - { - $this->ctrl->setContext($this->object->getId(), - $this->object->getType()); - } - } - - //prepare output - if ($a_prepare_output) - { - $this->prepareOutput(); - } - } - - /** - * Get object service - * - * @return ilObjectService - */ - protected function getObjectService() - { - return $this->object_service; - } - - /** - * execute command - */ - function executeCommand() - { - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - switch($next_class) - { - default: - $this->prepareOutput(); - if(!$cmd) - { - $cmd = "view"; - } - $cmd .= "Object"; - $this->$cmd(); - - break; - } - - return true; - } - - - /** - * determines wether objects are referenced or not (got ref ids or not) - */ - public function withReferences() - { - return $this->call_by_reference; - } - - /** - * if true, a creation screen is displayed - * the current $_GET[ref_id] don't belong - * to the current class! - * the mode is determined in ilrepositorygui - */ - public function setCreationMode($a_mode = true) - { - $this->creation_mode = $a_mode; - } - - /** - * get creation mode - */ - public function getCreationMode() - { - return $this->creation_mode; - } - - protected function assignObject() - { - // TODO: it seems that we always have to pass only the ref_id -//echo "
                  ilObjectGUIassign:".get_class($this).":".$this->id.":
                  "; - if ($this->id != 0) - { - if ($this->call_by_reference) - { - $this->object = ilObjectFactory::getInstanceByRefId($this->id); - } - else - { - $this->object = ilObjectFactory::getInstanceByObjId($this->id); - } - } - } - - /** - * prepare output - */ - public function prepareOutput($a_show_subobjects = true) - { - $ilLocator = $this->locator; - $tpl = $this->tpl; - $ilUser = $this->user; - - $this->tpl->getStandardTemplate(); - // administration prepare output - if (strtolower($_GET["baseClass"]) == "iladministrationgui") - { - $this->addAdminLocatorItems(); - $tpl->setLocator(); - -// ilUtil::sendInfo(); - ilUtil::infoPanel(); - - $this->setTitleAndDescription(); - - if ($this->getCreationMode() != true) - { - $this->setAdminTabs(); - } - - return false; - } - // set locator - $this->setLocator(); - // catch feedback message -// ilUtil::sendInfo(); - ilUtil::infoPanel(); - - // in creation mode (parent) object and gui object - // do not fit - if ($this->getCreationMode() == true) - { - // repository vs. workspace - if($this->call_by_reference) - { - // get gui class of parent and call their title and description method - $obj_type = ilObject::_lookupType($_GET["ref_id"],true); - $class_name = $this->objDefinition->getClassName($obj_type); - $class = strtolower("ilObj".$class_name."GUI"); - $class_path = $this->ctrl->lookupClassPath($class); - include_once($class_path); - $class_name = $this->ctrl->getClassForClasspath($class_path); -//echo "
                  instantiating parent for title and description"; - $this->parent_gui_obj = new $class_name("", $_GET["ref_id"], true, false); - // the next line prevents the header action menu being shown - $this->parent_gui_obj->setCreationMode(true); - $this->parent_gui_obj->setTitleAndDescription(); - } - } - else - { - // set title and description and title icon - $this->setTitleAndDescription(); - - // set tabs - $this->setTabs(); - - // BEGIN WebDAV: Display Mount Webfolder icon. - if ($ilUser->getId() != ANONYMOUS_USER_ID) - { - require_once ('Services/WebDAV/classes/class.ilDAVActivationChecker.php'); - if (ilDAVActivationChecker::_isActive()) - { - $this->showMountWebfolderIcon(); - } - } - // END WebDAV: Display Mount Webfolder icon. - - // fileupload support - require_once './Services/FileUpload/classes/class.ilFileUploadUtil.php'; - if (ilFileUploadUtil::isUploadAllowed($this->ref_id, $this->object->getType())) - { - $this->enableDragDropFileUpload(); - } - } - - return true; - } - - /** - * called by prepare output - */ - protected function setTitleAndDescription() - { - if (!is_object($this->object)) - { - if ((int) $_REQUEST["crtptrefid"] > 0) - { - $cr_obj_id = ilObject::_lookupObjId((int) $_REQUEST["crtcb"]); - $this->tpl->setTitle(ilObject::_lookupTitle($cr_obj_id)); - $this->tpl->setTitleIcon(ilObject::_getIcon($cr_obj_id)); - } - return; - } - $this->tpl->setTitle($this->object->getPresentationTitle()); - $this->tpl->setDescription($this->object->getLongDescription()); - - if (strtolower($_GET["baseClass"]) == "iladministrationgui") - { - // alt text would be same as heading -> empty alt text - $this->tpl->setTitleIcon(ilObject::_getIcon("", "big", $this->object->getType())); - } - else - { - $this->tpl->setTitleIcon(ilObject::_getIcon("", "big", $this->object->getType()), - $this->lng->txt("obj_" . $this->object->getType())); - } - - include_once './Services/Object/classes/class.ilObjectListGUIFactory.php'; - $lgui = ilObjectListGUIFactory::_getListGUIByType($this->object->getType()); - $lgui->initItem($this->object->getRefId(), $this->object->getId()); - $this->tpl->setAlertProperties($lgui->getAlertProperties()); - } - - /** - * Add header action menu - * - * @param string $a_sub_type - * @param int $a_sub_id - * @return ilObjectListGUI - */ - protected function initHeaderAction($a_sub_type = null, $a_sub_id = null) - { - $ilAccess = $this->access; - - if(!$this->creation_mode && $this->object) - { - include_once "Services/Object/classes/class.ilCommonActionDispatcherGUI.php"; - $dispatcher = new ilCommonActionDispatcherGUI(ilCommonActionDispatcherGUI::TYPE_REPOSITORY, - $ilAccess, $this->object->getType(), $this->ref_id, $this->object->getId()); - - $dispatcher->setSubObject($a_sub_type, $a_sub_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(); - - if (is_object($lg)) - { - // to enable add to desktop / remove from desktop - if($this instanceof ilDesktopItemHandling) - { - $lg->setContainerObject($this); - } - - // enable multi download - $lg->enableMultiDownload(true); - - // comments settings are always on (for the repository) - // should only be shown if active or permission to toggle - include_once "Services/Notes/classes/class.ilNote.php"; - if($ilAccess->checkAccess("write", "", $this->ref_id) || - $ilAccess->checkAccess("edit_permissions", "", $this->ref_id) || - ilNote::commentsActivated($this->object->getId(), 0, $this->object->getType())) - { - $lg->enableComments(true); - } - - $lg->enableNotes(true); - $lg->enableTags(true); - } - - return $lg; - } - } - - /** - * Insert header action into main template - * - * @param ilObjectListGUI $a_list_gui - */ - protected function insertHeaderAction($a_list_gui) - { - if (!is_object($this->object) || ilContainer::_lookupContainerSetting($this->object->getId(), "hide_top_actions")) - { - return; - } - - if(is_object($a_list_gui)) - { - $this->tpl->setHeaderActionMenu($a_list_gui->getHeaderAction()); - } - } - - /** - * Add header action menu - */ - protected function addHeaderAction() - { - $this->insertHeaderAction($this->initHeaderAction()); - } - - /** - * Ajax call: redraw action header only - */ - protected function redrawHeaderActionObject() - { - $tpl = $this->tpl; - - $lg = $this->initHeaderAction(); - echo $lg->getHeaderAction(); - - // we need to add onload code manually (rating, comments, etc.) - echo $tpl->getOnLoadCodeForAsynch(); - - exit; - } - - // BEGIN WebDAV: Show Mount Webfolder Icon. - protected function showMountWebfolderIcon() - { - $tree = $this->tree; - $tpl = $this->tpl; - $objDefinition = $this->objDefinition; - - if ($this->object->getRefId() == "") - { - return; - } - - $tpl->setMountWebfolderIcon($this->object->getRefId()); - } - // END WebDAV: Show Mount Webfolder Icon. - - - /** - * set admin tabs - * @access public - */ - protected function setTabs() - { - $this->getTabs(); - } - - /** - * set admin tabs - * @access public - */ - protected final function setAdminTabs() - { - $this->getAdminTabs(); - } - - /** - * administration tabs show only permissions and trash folder - */ - function getAdminTabs() - { - $tree = $this->tree; - -/* if ($_GET["admin_mode"] == "repository") - { - $this->ctrl->setParameterByClass("iladministrationgui", "admin_mode", "settings"); - $this->tabs_gui->setBackTarget($this->lng->txt("administration"), - $this->ctrl->getLinkTargetByClass("iladministrationgui", "frameset"), - ilFrameTargetInfo::_getFrame("MainContent")); - $this->ctrl->setParameterByClass("iladministrationgui", "admin_mode", "repository"); - }*/ - - if ($this->checkPermissionBool("visible,read")) - { - $this->tabs_gui->addTarget("view", - $this->ctrl->getLinkTarget($this, "view"), array("", "view"), get_class($this)); - - } - - if ($this->checkPermissionBool("edit_permission")) - { - $this->tabs_gui->addTarget("perm_settings", - $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm"), "", "ilpermissiongui"); - } - - if ($tree->getSavedNodeData($this->object->getRefId())) - { - $this->tabs_gui->addTarget("trash", - $this->ctrl->getLinkTarget($this, "trash"), "trash", get_class($this)); - } - } - - - function getHTML() - { - return $this->html; - } - - - /** - * set possible actions for objects in list. if actions are set - * via this method, the values of objects.xml are ignored. - * - * @param array $a_actions array with $command => $lang_var pairs - */ - final private function setActions($a_actions = "") - { - if (is_array($a_actions)) - { - foreach ($a_actions as $name => $lng) - { - $this->actions[$name] = array("name" => $name, "lng" => $lng); - } - } - else - { - $this->actions = ""; - } - } - - /** - * set possible subobjects for this object. if subobjects are set - * via this method, the values of objects.xml are ignored. - * - * @param array $a_actions array with $command => $lang_var pairs - */ - final private function setSubObjects($a_sub_objects = "") - { - if (is_array($a_sub_objects)) - { - foreach ($a_sub_objects as $name => $options) - { - $this->sub_objects[$name] = array("name" => $name, "max" => $options["max"]); - } - } - else - { - $this->sub_objects = ""; - } - } - - /** - * set Locator - * - * @param object tree object - * @param integer reference id - * @param scriptanme that is used for linking; - * @access public - */ - protected function setLocator() - { - $ilLocator = $this->locator; - $tpl = $this->tpl; - - if ($this->omit_locator) - { - return; - } - - // repository vs. workspace - if($this->call_by_reference) - { - // todo: admin workaround - // in the future, objectgui classes should not be called in - // admin section anymore (rbac/trash handling in own classes) - $ref_id = ($_GET["ref_id"] != "") - ? $_GET["ref_id"] - : $this->object->getRefId(); - $ilLocator->addRepositoryItems($ref_id); - } - - if(!$this->creation_mode) - { - $this->addLocatorItems(); - } - - $tpl->setLocator(); - } - - /** - * should be overwritten to add object specific items - * (repository items are preloaded) - */ - protected function addLocatorItems() - { - } - - protected function omitLocator($a_omit = true) - { - $this->omit_locator = $a_omit; - } - - /** - * should be overwritten to add object specific items - * (repository items are preloaded) - * - * @param bool $a_do_not_add_object - */ - protected function addAdminLocatorItems($a_do_not_add_object = false) - { - $ilLocator = $this->locator; - - if ($_GET["admin_mode"] == "settings") // system settings - { - $this->ctrl->setParameterByClass("ilobjsystemfoldergui", - "ref_id", SYSTEM_FOLDER_ID); - $ilLocator->addItem($this->lng->txt("administration"), - $this->ctrl->getLinkTargetByClass(array("iladministrationgui", "ilobjsystemfoldergui"), "") - ); - if ($this->object && ($this->object->getRefId() != SYSTEM_FOLDER_ID && !$a_do_not_add_object)) - { - $ilLocator->addItem($this->object->getTitle(), - $this->ctrl->getLinkTarget($this, "view")); - } - } - else // repository administration - { - $this->ctrl->setParameterByClass("iladministrationgui", - "ref_id", ""); - $this->ctrl->setParameterByClass("iladministrationgui", - "admin_mode", "settings"); - //$ilLocator->addItem($this->lng->txt("administration"), - // $this->ctrl->getLinkTargetByClass("iladministrationgui", "frameset"), - // ilFrameTargetInfo::_getFrame("MainContent")); - $this->ctrl->clearParametersByClass("iladministrationgui"); - $ilLocator->addAdministrationItems(); - } - - } - - /** - * confirmed deletion of object -> objects are moved to trash or deleted - * immediately, if trash is disabled - */ - public function confirmedDeleteObject() - { - if(isset($_POST["mref_id"])) - { - $_SESSION["saved_post"] = array_unique(array_merge($_SESSION["saved_post"], $_POST["mref_id"])); - } - - include_once("./Services/Repository/classes/class.ilRepUtilGUI.php"); - $ru = new ilRepUtilGUI($this); - $ru->deleteObjects($_GET["ref_id"], ilSession::get("saved_post")); - ilSession::clear("saved_post"); - $this->ctrl->returnToParent($this); - } - - /** - * cancel deletion of object - * - * @access public - */ - public function cancelDeleteObject() - { - ilSession::clear("saved_post"); - $this->ctrl->returnToParent($this); - } - - - /** - * cancel action and go back to previous page - * @access public - * - */ - public function cancelObject() - { - ilSession::clear("saved_post"); - $this->ctrl->returnToParent($this); - } - - /** - * create new object form - * - * @access public - */ - public function createObject() - { - $tpl = $this->tpl; - $ilErr = $this->ilErr; - - $new_type = $_REQUEST["new_type"]; - - - // add new object to custom parent container - $this->ctrl->saveParameter($this, "crtptrefid"); - // use forced callback after object creation - $this->ctrl->saveParameter($this, "crtcb"); - - if (!$this->checkPermissionBool("create", "", $new_type)) - { - $ilErr->raiseError($this->lng->txt("permission_denied"),$ilErr->MESSAGE); - } - else - { - $this->lng->loadLanguageModule($new_type); - $this->ctrl->setParameter($this, "new_type", $new_type); - - $forms = $this->initCreationForms($new_type); - - // copy form validation error: do not show other creation forms - if($_GET["cpfl"] && isset($forms[self::CFORM_CLONE])) - { - $forms = array(self::CFORM_CLONE => $forms[self::CFORM_CLONE]); - } - $tpl->setContent($this->getCreationFormsHTML($forms)); - } - } - - /** - * Init creation froms - * - * this will create the default creation forms: new, import, clone - * - * @param string $a_new_type - * @return array - */ - protected function initCreationForms($a_new_type) - { - $forms = array( - self::CFORM_NEW => $this->initCreateForm($a_new_type), - self::CFORM_IMPORT => $this->initImportForm($a_new_type), - self::CFORM_CLONE => $this->fillCloneTemplate(null, $a_new_type) - ); - - return $forms; - } - - /** - * Get HTML for creation forms (accordion) - * - * @param array $a_forms - */ - final protected function getCreationFormsHTML(array $a_forms) - { - $tpl = $this->tpl; - - // #13168- sanity check - foreach($a_forms as $id => $form) - { - if(!$form instanceof ilPropertyFormGUI) - { - unset($a_forms[$id]); - } - } - - // no accordion if there is just one form - if(sizeof($a_forms) == 1) - { - $form_type = key($a_forms); - $a_forms = array_shift($a_forms); - - // see bug #0016217 - if(method_exists($this, "getCreationFormTitle")) - { - $form_title = $this->getCreationFormTitle($form_type); - if ($form_title != "") - { - $a_forms->setTitle($form_title); - } - } - return $a_forms->getHTML(); - } - else - { - include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); - - $acc = new ilAccordionGUI(); - $acc->setBehaviour(ilAccordionGUI::FIRST_OPEN); - $cnt = 1; - foreach ($a_forms as $form_type => $cf) - { - $htpl = new ilTemplate("tpl.creation_acc_head.html", true, true, "Services/Object"); - - // using custom form titles (used for repository plugins) - $form_title = ""; - if(method_exists($this, "getCreationFormTitle")) - { - $form_title = $this->getCreationFormTitle($form_type); - } - if(!$form_title) - { - $form_title = $cf->getTitle(); - } - - // move title from form to accordion - $htpl->setVariable("TITLE", $this->lng->txt("option")." ".$cnt.": ". - $form_title); - $cf->setTitle(null); - $cf->setTitleIcon(null); - $cf->setTableWidth("100%"); - - $acc->addItem($htpl->get(), $cf->getHTML()); - - $cnt++; - } - - return "
                  ".$acc->getHTML()."
                  "; - } - } - - /** - * Init object creation form - * - * @param string $a_new_type - * @return ilPropertyFormGUI - */ - protected function initCreateForm($a_new_type) - { - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setTarget("_top"); - $form->setFormAction($this->ctrl->getFormAction($this, "save")); - $form->setTitle($this->lng->txt($a_new_type."_new")); - - // title - $ti = new ilTextInputGUI($this->lng->txt("title"), "title"); - $ti->setSize(min(40, ilObject::TITLE_LENGTH)); - $ti->setMaxLength(ilObject::TITLE_LENGTH); - $ti->setRequired(true); - $form->addItem($ti); - - // description - $ta = new ilTextAreaInputGUI($this->lng->txt("description"), "desc"); - $ta->setCols(40); - $ta->setRows(2); - $form->addItem($ta); - - $form = $this->initDidacticTemplate($form); - - $form->addCommandButton("save", $this->lng->txt($a_new_type."_add")); - $form->addCommandButton("cancel", $this->lng->txt("cancel")); - - return $form; - } - - /** - * Show didactic template types - * @param ilPropertyFormGUI $form - * @return ilPropertyFormGUI $form - */ - protected function initDidacticTemplate(ilPropertyFormGUI $form) - { - $lng = $this->lng; - - $lng->loadLanguageModule('didactic'); - $existing_exclusive = false; - $options = array(); - $options['dtpl_0'] = array($this->lng->txt('didactic_default_type'), - sprintf( - $this->lng->txt('didactic_default_type_info'), - $this->lng->txt('objs_'.$this->type) - )); - - include_once './Services/DidacticTemplate/classes/class.ilDidacticTemplateSettings.php'; - $templates = ilDidacticTemplateSettings::getInstanceByObjectType($this->type)->getTemplates(); - if($templates) - { - foreach($templates as $template) - { - if($template->isEffective($_GET["ref_id"])) - { - $options["dtpl_".$template->getId()] = array( - $template->getPresentationTitle(), - $template->getPresentationDescription() - ); - - if($template->isExclusive()) - { - $existing_exclusive = true; - } - } - - } - } - - $this->addDidacticTemplateOptions($options); - - if(sizeof($options) > 1) - { - $type = new ilRadioGroupInputGUI( - $this->lng->txt('type'), - 'didactic_type' - ); - // workaround for containers in edit mode - if(!$this->getCreationMode()) - { - include_once './Services/DidacticTemplate/classes/class.ilDidacticTemplateObjSettings.php'; - $value = 'dtpl_'.ilDidacticTemplateObjSettings::lookupTemplateId($this->object->getRefId()); - - $type->setValue($value); - - if(!in_array($value, array_keys($options)) || ($existing_exclusive && $value == "dtpl_0")) - { - //add or rename actual value to not avaiable - $options[$value] = array($this->lng->txt('not_available')); - } - } - else - { - if($existing_exclusive) - { - //if an exclusive template exists use the second template as default value - $keys = array_keys($options); - $type->setValue($keys[1]); - } - else - { - $type->setValue('dtpl_0'); - } - - } - $form->addItem($type); - - foreach($options as $id => $data) - { - $option = new ilRadioOption($data[0], $id, $data[1]); - - if($existing_exclusive && $id == "dtpl_0" && $this->getCreationMode()) - { - //set default disabled if an exclusive template exists but just in creation screen - $option->setDisabled(true); - } - - $type->addOption($option); - } - } - - return $form; - } - - /** - * Add custom templates - * - * @param array $a_options - */ - protected function addDidacticTemplateOptions(array &$a_options) - { - - } - - /** - * cancel create action and go back to repository parent - */ - public function cancelCreation() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirectByClass("ilrepositorygui", "frameset"); - } - - /** - * save object - * - * @access public - */ - public function saveObject() - { - $objDefinition = $this->objDefinition; - $tpl = $this->tpl; - $ilErr = $this->ilErr; - - $new_type = $_REQUEST["new_type"]; - - // create permission is already checked in createObject. This check here is done to prevent hacking attempts - if (!$this->checkPermissionBool("create", "", $new_type)) - { - $ilErr->raiseError($this->lng->txt("no_create_permission"), $ilErr->MESSAGE); - } - - $this->lng->loadLanguageModule($new_type); - $this->ctrl->setParameter($this, "new_type", $new_type); - - $form = $this->initCreateForm($new_type); - if ($form->checkInput()) - { - $this->ctrl->setParameter($this, "new_type", ""); - - // create instance - $class_name = "ilObj".$objDefinition->getClassName($new_type); - $location = $objDefinition->getLocation($new_type); - include_once($location."/class.".$class_name.".php"); - $newObj = new $class_name(); - $newObj->setType($new_type); - $newObj->setTitle($form->getInput("title")); - $newObj->setDescription($form->getInput("desc")); - $newObj->create(); - - $this->putObjectInTree($newObj); - - // apply didactic template? - $dtpl = $this->getDidacticTemplateVar("dtpl"); - if($dtpl) - { - $newObj->applyDidacticTemplate($dtpl); - } - - // auto rating - $this->handleAutoRating($newObj); - - // additional paramters are added to afterSave() - $args = func_get_args(); - if($args) - { - $this->afterSave($newObj, $args); - } - else - { - $this->afterSave($newObj); - } - return; - } - - // display only this form to correct input - $form->setValuesByPost(); - $tpl->setContent($form->getHtml()); - } - - /** - * Get didactic template setting from creation screen - * - * @param string $a_type - * @return string - */ - public function getDidacticTemplateVar($a_type) - { - $tpl = $_POST["didactic_type"]; - if($tpl && substr($tpl, 0, strlen($a_type)+1) == $a_type."_") - { - return (int)substr($tpl, strlen($a_type)+1); - } - return 0; - } - - /** - * Add object to tree at given position - * - * @param ilObject $a_obj - * @param int $a_parent_node_id - */ - public function putObjectInTree(ilObject $a_obj, $a_parent_node_id = null) - { - $rbacreview = $this->rbacreview; - $ilUser = $this->user; - $objDefinition = $this->objDefinition; - - if(!$a_parent_node_id) - { - $a_parent_node_id = $_GET["ref_id"]; - } - - // add new object to custom parent container - if((int)$_REQUEST["crtptrefid"]) - { - $a_parent_node_id = (int)$_REQUEST["crtptrefid"]; - } - - $a_obj->createReference(); - $a_obj->putInTree($a_parent_node_id); - $a_obj->setPermissions($a_parent_node_id); - - $this->obj_id = $a_obj->getId(); - $this->ref_id = $a_obj->getRefId(); - - // BEGIN ChangeEvent: Record save object. - require_once('Services/Tracking/classes/class.ilChangeEvent.php'); - ilChangeEvent::_recordWriteEvent($this->obj_id, $ilUser->getId(), 'create'); - // END ChangeEvent: Record save object. - - // rbac log - include_once "Services/AccessControl/classes/class.ilRbacLog.php"; - $rbac_log_roles = $rbacreview->getParentRoleIds($this->ref_id, false); - $rbac_log = ilRbacLog::gatherFaPa($this->ref_id, array_keys($rbac_log_roles), true); - ilRbacLog::add(ilRbacLog::CREATE_OBJECT, $this->ref_id, $rbac_log); - - // use forced callback after object creation - if($_REQUEST["crtcb"]) - { - $callback_type = ilObject::_lookupType((int)$_REQUEST["crtcb"], true); - $class_name = "ilObj".$objDefinition->getClassName($callback_type)."GUI"; - $location = $objDefinition->getLocation($callback_type); - include_once($location."/class.".$class_name.".php"); - if (in_array(strtolower($class_name), array("ilobjitemgroupgui"))) - { - $callback_obj = new $class_name((int)$_REQUEST["crtcb"]); - } - else - { - // #10368 - $callback_obj = new $class_name(null, (int)$_REQUEST["crtcb"], true, false); - } - $callback_obj->afterSaveCallback($a_obj); - } - } - - /** - * Post (successful) object creation hook - * - * @param ilObject $a_new_object - */ - protected function afterSave(ilObject $a_new_object) - { - ilUtil::sendSuccess($this->lng->txt("object_added"), true); - $this->ctrl->returnToParent($this); - } - - /** - * edit object - * - * @access public - */ - public function editObject() - { - $tpl = $this->tpl; - $ilTabs = $this->tabs_gui; - $ilErr = $this->ilErr; - - if (!$this->checkPermissionBool("write")) - { - $ilErr->raiseError($this->lng->txt("msg_no_perm_write"),$ilErr->MESSAGE); - } - - $ilTabs->activateTab("settings"); - - $form = $this->initEditForm(); - $values = $this->getEditFormValues(); - if($values) - { - $form->setValuesByArray($values); - } - - $this->addExternalEditFormCustom($form); - - $tpl->setContent($form->getHTML()); - } - - public function addExternalEditFormCustom(ilPropertyFormGUI $a_form) - { - // has to be done AFTER setValuesByArray() ... - } - - /** - * Init object edit form - * - * @return ilPropertyFormGUI - */ - protected function initEditForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $lng->loadLanguageModule($this->object->getType()); - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this, "update")); - $form->setTitle($this->lng->txt($this->object->getType()."_edit")); - - // title - $ti = new ilTextInputGUI($this->lng->txt("title"), "title"); - $ti->setSize(min(40, ilObject::TITLE_LENGTH)); - $ti->setMaxLength(ilObject::TITLE_LENGTH); - $ti->setRequired(true); - $form->addItem($ti); - - // description - $ta = new ilTextAreaInputGUI($this->lng->txt("description"), "desc"); - $ta->setCols(40); - $ta->setRows(2); - $form->addItem($ta); - - $this->initEditCustomForm($form); - - $form->addCommandButton("update", $this->lng->txt("save")); - //$this->form->addCommandButton("cancelUpdate", $lng->txt("cancel")); - - return $form; - } - - /** - * Add custom fields to update form - * - * @param ilPropertyFormGUI $a_form - */ - protected function initEditCustomForm(ilPropertyFormGUI $a_form) - { - - } - - /** - * Get values for edit form - * - * @return array - */ - protected function getEditFormValues() - { - $values["title"] = $this->object->getTitle(); - $values["desc"] = $this->object->getLongDescription(); - $this->getEditFormCustomValues($values); - return $values; - } - - /** - * Add values to custom edit fields - * - * @param array $a_values - */ - protected function getEditFormCustomValues(array &$a_values) - { - - } - - /** - * updates object entry in object_data - */ - public function updateObject() - { - $ilTabs = $this->tabs_gui; - $tpl = $this->tpl; - $ilErr = $this->ilErr; - - if (!$this->checkPermissionBool("write")) - { - $ilErr->raiseError($this->lng->txt("permission_denied"),$ilErr->MESSAGE); - } - - $form = $this->initEditForm(); - if($form->checkInput() && - $this->validateCustom($form)) - { - $this->object->setTitle($form->getInput("title")); - $this->object->setDescription($form->getInput("desc")); - $this->updateCustom($form); - $this->object->update(); - - $this->afterUpdate(); - return; - } - - // display form again to correct errors - $ilTabs->activateTab("settings"); - $form->setValuesByPost(); - $tpl->setContent($form->getHtml()); - } - - /** - * Validate custom values (if not possible with checkInput()) - * - * @param ilPropertyFormGUI $a_form - * @return boolean - */ - protected function validateCustom(ilPropertyFormGUI $a_form) - { - return true; - } - - /** - * Insert custom update form values into object - * - * @param ilPropertyFormGUI $a_form - */ - protected function updateCustom(ilPropertyFormGUI $a_form) - { - - } - - /** - * Post (successful) object update hook - */ - protected function afterUpdate() - { - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"),true); - $this->ctrl->redirect($this, "edit"); - } - - /** - * Init object import form - * - * @param string new type - * @return ilPropertyFormGUI - */ - protected function initImportForm($a_new_type) - { - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setTarget("_top"); - $form->setFormAction($this->ctrl->getFormAction($this, "importFile")); - $form->setTitle($this->lng->txt($a_new_type."_import")); - - include_once("./Services/Form/classes/class.ilFileInputGUI.php"); - $fi = new ilFileInputGUI($this->lng->txt("import_file"), "importfile"); - $fi->setSuffixes(array("zip")); - $fi->setRequired(true); - $form->addItem($fi); - - $form->addCommandButton("importFile", $this->lng->txt("import")); - $form->addCommandButton("cancel", $this->lng->txt("cancel")); - - return $form; - } - - /** - * Import - */ - protected function importFileObject($parent_id = null, $a_catch_errors = true) - { - $objDefinition = $this->objDefinition; - $tpl = $this->tpl; - $ilErr = $this->ilErr; - - if(!$parent_id) - { - $parent_id = $_GET["ref_id"]; - } - $new_type = $_REQUEST["new_type"]; - - // create permission is already checked in createObject. This check here is done to prevent hacking attempts - if (!$this->checkPermissionBool("create", "", $new_type)) - { - $ilErr->raiseError($this->lng->txt("no_create_permission")); - } - - $this->lng->loadLanguageModule($new_type); - $this->ctrl->setParameter($this, "new_type", $new_type); - - $form = $this->initImportForm($new_type); - if ($form->checkInput()) - { - // :todo: make some check on manifest file - - if($objDefinition->isContainer($new_type)) - { - include_once './Services/Export/classes/class.ilImportContainer.php'; - $imp = new ilImportContainer((int)$parent_id); - } - else - { - include_once("./Services/Export/classes/class.ilImport.php"); - $imp = new ilImport((int)$parent_id); - } - - try - { - $new_id = $imp->importObject(null, $_FILES["importfile"]["tmp_name"], - $_FILES["importfile"]["name"], $new_type); - } - catch (ilException $e) - { - $this->tmp_import_dir = $imp->getTemporaryImportDir(); - if (!$a_catch_errors) - { - throw $e; - } - // display message and form again - ilUtil::sendFailure($this->lng->txt("obj_import_file_error")."
                  ".$e->getMessage()); - $form->setValuesByPost(); - $tpl->setContent($form->getHtml()); - return; - } - - if ($new_id > 0) - { - $this->ctrl->setParameter($this, "new_type", ""); - - $newObj = ilObjectFactory::getInstanceByObjId($new_id); - - // put new object id into tree - already done in import for containers - if(!$objDefinition->isContainer($new_type)) - { - $this->putObjectInTree($newObj); - } - - $this->afterImport($newObj); - } - // import failed - else - { - if($objDefinition->isContainer($new_type)) - { - ilUtil::sendFailure($this->lng->txt("container_import_zip_file_invalid")); - } - else - { - // not enough information here... - return; - } - } - } - - // display form to correct errors - $form->setValuesByPost(); - $tpl->setContent($form->getHtml()); - } - - /** - * Post (successful) object import hook - * - * @param ilObject $a_new_object - */ - protected function afterImport(ilObject $a_new_object) - { - ilUtil::sendSuccess($this->lng->txt("object_added"), true); - $this->ctrl->returnToParent($this); - } - - /** - * get form action for command (command is method name without "Object", e.g. "perm") - * @param string $a_cmd command - * @param string $a_formaction default formaction (is returned, if no special - * formaction was set) - * @access public - * @return string - */ - public function getFormAction($a_cmd, $a_formaction = "") - { - if ($this->formaction[$a_cmd] != "") - { - return $this->formaction[$a_cmd]; - } - else - { - return $a_formaction; - } - } - - /** - * set specific form action for command - * - * @param string $a_cmd command - * @param string $a_formaction default formaction (is returned, if no special - * formaction was set) - * @access public - */ - protected function setFormAction($a_cmd, $a_formaction) - { - $this->formaction[$a_cmd] = $a_formaction; - } - - /** - * get return location for command (command is method name without "Object", e.g. "perm") - * @param string $a_cmd command - * @param string $a_location default return location (is returned, if no special - * return location was set) - * @access public - */ - protected function getReturnLocation($a_cmd, $a_location ="") - { - if ($this->return_location[$a_cmd] != "") - { - return $this->return_location[$a_cmd]; - } - else - { - return $a_location; - } - } - - /** - * set specific return location for command - * @param string $a_cmd command - * @param string $a_location default return location (is returned, if no special - * return location was set) - * @access public - */ - protected function setReturnLocation($a_cmd, $a_location) - { -//echo "-".$a_cmd."-".$a_location."-"; - $this->return_location[$a_cmd] = $a_location; - } - - /** - * get target frame for command (command is method name without "Object", e.g. "perm") - * @param string $a_cmd command - * @param string $a_target_frame default target frame (is returned, if no special - * target frame was set) - * @access public - */ - protected function getTargetFrame($a_cmd, $a_target_frame = "") - { - if ($this->target_frame[$a_cmd] != "") - { - return $this->target_frame[$a_cmd]; - } - elseif (!empty($a_target_frame)) - { - return "target=\"".$a_target_frame."\""; - } - else - { - return; - } - } - - /** - * set specific target frame for command - * @param string $a_cmd command - * @param string $a_target_frame default target frame (is returned, if no special - * target frame was set) - * @access public - */ - protected function setTargetFrame($a_cmd, $a_target_frame) - { - $this->target_frame[$a_cmd] = "target=\"".$a_target_frame."\""; - } - - // BEGIN Security: Hide objects which aren't accessible by the user. - public function isVisible($a_ref_id,$a_type) - { - $visible = $this->checkPermissionBool("visible,read", "", "", $a_ref_id); - - if ($visible && $a_type == 'crs') { - $tree = $this->tree; - if($crs_id = $tree->checkForParentType($a_ref_id,'crs')) - { - if(!$this->checkPermissionBool("write", "", "", $crs_id)) - { - // Show only activated courses - $tmp_obj =& ilObjectFactory::getInstanceByRefId($crs_id,false); - - if(!$tmp_obj->isActivated()) - { - unset($tmp_obj); - $visible = false; - } - } - } - } - - return $visible; - } - // END Security: Hide objects which aren't accessible by the user. - - /** - * list childs of current object - * - * @access public - */ - public function viewObject() - { - $tpl = $this->tpl; - $ilErr = $this->ilErr; - - if (!$this->checkPermissionBool("visible,read")) - { - $ilErr->raiseError($this->lng->txt("permission_denied"),$ilErr->MESSAGE); - } - - // BEGIN ChangeEvent: record read event. - require_once('Services/Tracking/classes/class.ilChangeEvent.php'); - $ilUser = $this->user; - ilChangeEvent::_recordReadEvent( - $this->object->getType(), - $this->object->getRefId(), - $this->object->getId(), $ilUser->getId()); - // END ChangeEvent: record read event. - - include_once("./Services/Repository/classes/class.ilAdminSubItemsTableGUI.php"); - if (!$this->call_by_reference) - { - $this->ctrl->setParameter($this, "obj_id", $this->obj_id); - } - $itab = new ilAdminSubItemsTableGUI($this, "view", $_GET["ref_id"], - $this->checkPermissionBool('write')); - - $tpl->setContent($itab->getHTML()); - } - - /** - * Display deletion confirmation screen. - * Only for referenced objects. For user,role & rolt overwrite this function in the appropriate - * Object folders classes (ilObjUserFolderGUI,ilObjRoleFolderGUI) - * - * @access public - */ - public function deleteObject($a_error = false) - { - $ilCtrl = $this->ctrl; - - if ($_GET["item_ref_id"] != "") - { - $_POST["id"] = array($_GET["item_ref_id"]); - } - - if(is_array($_POST["id"])) - { - foreach($_POST["id"] as $idx => $id) - { - $_POST["id"][$idx] = (int)$id; - } - } - - // SAVE POST VALUES (get rid of this - ilSession::set("saved_post", $_POST["id"]); - - include_once("./Services/Repository/classes/class.ilRepUtilGUI.php"); - $ru = new ilRepUtilGUI($this); - if (!$ru->showDeleteConfirmation($_POST["id"], $a_error)) - { - $ilCtrl->returnToParent($this); - } - } - - /** - * show possible subobjects (pulldown menu) - * - * @access public - */ - protected function showPossibleSubObjects() - { - if ($this->sub_objects == "") - { - $d = $this->objDefinition->getCreatableSubObjects($this->object->getType(), ilObjectDefinition::MODE_REPOSITORY, $this->ref_id); - } - else - { - $d = $this->sub_objects; - } - - $import = false; - - if (count($d) > 0) - { - foreach ($d as $row) - { - $count = 0; - - if ($row["max"] > 0) - { - //how many elements are present? - for ($i=0; $idata["ctrl"]); $i++) - { - if ($this->data["ctrl"][$i]["type"] == $row["name"]) - { - $count++; - } - } - } - - if ($row["max"] == "" || $count < $row["max"]) - { - $subobj[] = $row["name"]; - } - } - } - - if (is_array($subobj)) - { - - //build form - $opts = ilUtil::formSelect(12,"new_type",$subobj); - $this->tpl->setCurrentBlock("add_object"); - $this->tpl->setVariable("SELECT_OBJTYPE", $opts); - $this->tpl->setVariable("BTN_NAME", "create"); - $this->tpl->setVariable("TXT_ADD", $this->lng->txt("add")); - $this->tpl->parseCurrentBlock(); - } - } - - /** - * get a template blockfile - * format: tpl._.html - * - * @param string command - * @param string object type definition - * @access public - */ - final protected function getTemplateFile($a_cmd,$a_type = "") - { - mk(); die("ilObjectGUI::getTemplateFile() is deprecated."); - } - - /** - * get tabs - * abstract method. - * @abstract overwrite in derived GUI class of your object type - * @access public - * @param object instance of ilTabsGUI - */ - protected function getTabs() - { - // please define your tabs here - - } - - // PROTECTED - protected function __showButton($a_cmd,$a_text,$a_target = '') - { - $ilToolbar = $this->toolbar; - - $ilToolbar->addButton($a_text, $this->ctrl->getLinkTarget($this, $a_cmd), $a_target); - } - - protected function hitsperpageObject() - { + /** + * @var ilErrorHandling + */ + protected $ilErr; + + /** + * @var ilLocatorGUI + */ + protected $locator; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var ilRbacReview + */ + protected $rbacreview; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + const COPY_WIZARD_NEEDS_PAGE = 1; + + + /** + * object Definition Object + * @var object ilias + * @access private + */ + public $objDefinition; + + /** + * template object + * @var object ilias + * @access private + */ + public $tpl; + + /** + * tree object + * @var object ilias + * @access private + */ + public $tree; + + /** + * language object + * @var object language (of ilObject) + * @access private + */ + public $lng; + + /** + * output data + * @var data array + * @access private + */ + public $data; + + /** + * object + * @var object + * @access private + */ + public $object; + public $ref_id; + public $obj_id; + public $maxcount; // contains number of child objects + public $formaction; // special formation (array "cmd" => "formaction") + public $return_location; // special return location (array "cmd" => "location") + public $target_frame; // special target frame (array "cmd" => "location") + protected $tmp_import_dir; // directory used during import + + public $tab_target_script; + public $actions; + public $sub_objects; + public $omit_locator = false; + + /** + * @var ilTabsGUI + */ + protected $tabs_gui = null; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilObjectService + */ + protected $object_service; + + const CFORM_NEW = 1; + const CFORM_IMPORT = 2; + const CFORM_CLONE = 3; + + /** + * Constructor + * @access public + * @param array ?? + * @param integer object id + * @param boolean call be reference + */ + public function __construct($a_data, $a_id = 0, $a_call_by_reference = true, $a_prepare_output = true) + { + global $DIC; + + $this->locator = $DIC["ilLocator"]; + $this->user = $DIC->user(); + $this->access = $DIC->access(); + $this->settings = $DIC->settings(); + $this->rbacreview = $DIC->rbac()->review(); + $this->toolbar = $DIC->toolbar(); + $this->object_service = $DIC->object(); + $objDefinition = $DIC["objDefinition"]; + $tpl = $DIC["tpl"]; + $tree = $DIC->repositoryTree(); + $ilCtrl = $DIC->ctrl(); + $ilErr = $DIC["ilErr"]; + $lng = $DIC->language(); + $ilTabs = $DIC->tabs(); + + $this->ilias = $DIC["ilias"]; + + /** + * @var ilTab + */ + $this->tabs_gui = $ilTabs; + + if (!isset($ilErr)) { + $ilErr = new ilErrorHandling(); + $ilErr->setErrorHandling(PEAR_ERROR_CALLBACK, array($ilErr,'errorHandler')); + } else { + $this->ilErr = $ilErr; + } + + $this->objDefinition = $objDefinition; + $this->tpl = $tpl; + $this->html = ""; + $this->ctrl = $ilCtrl; + + $params = array("ref_id"); + + if (!$a_call_by_reference) { + $params = array("ref_id","obj_id"); + } + + $this->ctrl->saveParameter($this, $params); + + $this->lng = $lng; + $this->tree = $tree; + $this->formaction = array(); + $this->return_location = array(); + $this->target_frame = array(); + $this->actions = ""; + $this->sub_objects = ""; + + $this->data = $a_data; + $this->id = $a_id; + $this->call_by_reference = $a_call_by_reference; + $this->prepare_output = $a_prepare_output; + $this->creation_mode = false; + + $this->ref_id = ($this->call_by_reference) ? $this->id : $_GET["ref_id"]; + $this->obj_id = ($this->call_by_reference) ? $_GET["obj_id"] : $this->id; + + if ($this->id != 0) { + $this->link_params = "ref_id=" . $this->ref_id; + } + + // get the object + $this->assignObject(); + + // set context + if (is_object($this->object)) { + if ($this->call_by_reference && $this->ref_id == $_GET["ref_id"]) { + $this->ctrl->setContext( + $this->object->getId(), + $this->object->getType() + ); + } + } + + //prepare output + if ($a_prepare_output) { + $this->prepareOutput(); + } + } + + /** + * Get object service + * + * @return ilObjectService + */ + protected function getObjectService() + { + return $this->object_service; + } + + /** + * execute command + */ + public function executeCommand() + { + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + switch ($next_class) { + default: + $this->prepareOutput(); + if (!$cmd) { + $cmd = "view"; + } + $cmd .= "Object"; + $this->$cmd(); + + break; + } + + return true; + } + + + /** + * determines wether objects are referenced or not (got ref ids or not) + */ + public function withReferences() + { + return $this->call_by_reference; + } + + /** + * if true, a creation screen is displayed + * the current $_GET[ref_id] don't belong + * to the current class! + * the mode is determined in ilrepositorygui + */ + public function setCreationMode($a_mode = true) + { + $this->creation_mode = $a_mode; + } + + /** + * get creation mode + */ + public function getCreationMode() + { + return $this->creation_mode; + } + + protected function assignObject() + { + // TODO: it seems that we always have to pass only the ref_id + //echo "
                  ilObjectGUIassign:".get_class($this).":".$this->id.":
                  "; + if ($this->id != 0) { + if ($this->call_by_reference) { + $this->object = ilObjectFactory::getInstanceByRefId($this->id); + } else { + $this->object = ilObjectFactory::getInstanceByObjId($this->id); + } + } + } + + /** + * prepare output + */ + public function prepareOutput($a_show_subobjects = true) + { + $ilLocator = $this->locator; + $tpl = $this->tpl; + $ilUser = $this->user; + + $this->tpl->getStandardTemplate(); + // administration prepare output + if (strtolower($_GET["baseClass"]) == "iladministrationgui") { + $this->addAdminLocatorItems(); + $tpl->setLocator(); + + // ilUtil::sendInfo(); + ilUtil::infoPanel(); + + $this->setTitleAndDescription(); + + if ($this->getCreationMode() != true) { + $this->setAdminTabs(); + } + + return false; + } + // set locator + $this->setLocator(); + // catch feedback message + // ilUtil::sendInfo(); + ilUtil::infoPanel(); + + // in creation mode (parent) object and gui object + // do not fit + if ($this->getCreationMode() == true) { + // repository vs. workspace + if ($this->call_by_reference) { + // get gui class of parent and call their title and description method + $obj_type = ilObject::_lookupType($_GET["ref_id"], true); + $class_name = $this->objDefinition->getClassName($obj_type); + $class = strtolower("ilObj" . $class_name . "GUI"); + $class_path = $this->ctrl->lookupClassPath($class); + include_once($class_path); + $class_name = $this->ctrl->getClassForClasspath($class_path); + //echo "
                  instantiating parent for title and description"; + $this->parent_gui_obj = new $class_name("", $_GET["ref_id"], true, false); + // the next line prevents the header action menu being shown + $this->parent_gui_obj->setCreationMode(true); + $this->parent_gui_obj->setTitleAndDescription(); + } + } else { + // set title and description and title icon + $this->setTitleAndDescription(); + + // set tabs + $this->setTabs(); + + // BEGIN WebDAV: Display Mount Webfolder icon. + if ($ilUser->getId() != ANONYMOUS_USER_ID) { + require_once('Services/WebDAV/classes/class.ilDAVActivationChecker.php'); + if (ilDAVActivationChecker::_isActive()) { + $this->showMountWebfolderIcon(); + } + } + // END WebDAV: Display Mount Webfolder icon. + + // fileupload support + require_once './Services/FileUpload/classes/class.ilFileUploadUtil.php'; + if (ilFileUploadUtil::isUploadAllowed($this->ref_id, $this->object->getType())) { + $this->enableDragDropFileUpload(); + } + } + + return true; + } + + /** + * called by prepare output + */ + protected function setTitleAndDescription() + { + if (!is_object($this->object)) { + if ((int) $_REQUEST["crtptrefid"] > 0) { + $cr_obj_id = ilObject::_lookupObjId((int) $_REQUEST["crtcb"]); + $this->tpl->setTitle(ilObject::_lookupTitle($cr_obj_id)); + $this->tpl->setTitleIcon(ilObject::_getIcon($cr_obj_id)); + } + return; + } + $this->tpl->setTitle($this->object->getPresentationTitle()); + $this->tpl->setDescription($this->object->getLongDescription()); + + if (strtolower($_GET["baseClass"]) == "iladministrationgui") { + // alt text would be same as heading -> empty alt text + $this->tpl->setTitleIcon(ilObject::_getIcon("", "big", $this->object->getType())); + } else { + $this->tpl->setTitleIcon( + ilObject::_getIcon("", "big", $this->object->getType()), + $this->lng->txt("obj_" . $this->object->getType()) + ); + } + + include_once './Services/Object/classes/class.ilObjectListGUIFactory.php'; + $lgui = ilObjectListGUIFactory::_getListGUIByType($this->object->getType()); + $lgui->initItem($this->object->getRefId(), $this->object->getId()); + $this->tpl->setAlertProperties($lgui->getAlertProperties()); + } + + /** + * Add header action menu + * + * @param string $a_sub_type + * @param int $a_sub_id + * @return ilObjectListGUI + */ + protected function initHeaderAction($a_sub_type = null, $a_sub_id = null) + { + $ilAccess = $this->access; + + if (!$this->creation_mode && $this->object) { + include_once "Services/Object/classes/class.ilCommonActionDispatcherGUI.php"; + $dispatcher = new ilCommonActionDispatcherGUI( + ilCommonActionDispatcherGUI::TYPE_REPOSITORY, + $ilAccess, + $this->object->getType(), + $this->ref_id, + $this->object->getId() + ); + + $dispatcher->setSubObject($a_sub_type, $a_sub_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(); + + if (is_object($lg)) { + // to enable add to desktop / remove from desktop + if ($this instanceof ilDesktopItemHandling) { + $lg->setContainerObject($this); + } + + // enable multi download + $lg->enableMultiDownload(true); + + // comments settings are always on (for the repository) + // should only be shown if active or permission to toggle + include_once "Services/Notes/classes/class.ilNote.php"; + if ($ilAccess->checkAccess("write", "", $this->ref_id) || + $ilAccess->checkAccess("edit_permissions", "", $this->ref_id) || + ilNote::commentsActivated($this->object->getId(), 0, $this->object->getType())) { + $lg->enableComments(true); + } + + $lg->enableNotes(true); + $lg->enableTags(true); + } + + return $lg; + } + } + + /** + * Insert header action into main template + * + * @param ilObjectListGUI $a_list_gui + */ + protected function insertHeaderAction($a_list_gui) + { + if (!is_object($this->object) || ilContainer::_lookupContainerSetting($this->object->getId(), "hide_top_actions")) { + return; + } + + if (is_object($a_list_gui)) { + $this->tpl->setHeaderActionMenu($a_list_gui->getHeaderAction()); + } + } + + /** + * Add header action menu + */ + protected function addHeaderAction() + { + $this->insertHeaderAction($this->initHeaderAction()); + } + + /** + * Ajax call: redraw action header only + */ + protected function redrawHeaderActionObject() + { + $tpl = $this->tpl; + + $lg = $this->initHeaderAction(); + echo $lg->getHeaderAction(); + + // we need to add onload code manually (rating, comments, etc.) + echo $tpl->getOnLoadCodeForAsynch(); + + exit; + } + + // BEGIN WebDAV: Show Mount Webfolder Icon. + protected function showMountWebfolderIcon() + { + $tree = $this->tree; + $tpl = $this->tpl; + $objDefinition = $this->objDefinition; + + if ($this->object->getRefId() == "") { + return; + } + + $tpl->setMountWebfolderIcon($this->object->getRefId()); + } + // END WebDAV: Show Mount Webfolder Icon. + + + /** + * set admin tabs + * @access public + */ + protected function setTabs() + { + $this->getTabs(); + } + + /** + * set admin tabs + * @access public + */ + final protected function setAdminTabs() + { + $this->getAdminTabs(); + } + + /** + * administration tabs show only permissions and trash folder + */ + public function getAdminTabs() + { + $tree = $this->tree; + + /* if ($_GET["admin_mode"] == "repository") + { + $this->ctrl->setParameterByClass("iladministrationgui", "admin_mode", "settings"); + $this->tabs_gui->setBackTarget($this->lng->txt("administration"), + $this->ctrl->getLinkTargetByClass("iladministrationgui", "frameset"), + ilFrameTargetInfo::_getFrame("MainContent")); + $this->ctrl->setParameterByClass("iladministrationgui", "admin_mode", "repository"); + }*/ + + if ($this->checkPermissionBool("visible,read")) { + $this->tabs_gui->addTarget( + "view", + $this->ctrl->getLinkTarget($this, "view"), + array("", "view"), + get_class($this) + ); + } + + if ($this->checkPermissionBool("edit_permission")) { + $this->tabs_gui->addTarget( + "perm_settings", + $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm"), + "", + "ilpermissiongui" + ); + } + + if ($tree->getSavedNodeData($this->object->getRefId())) { + $this->tabs_gui->addTarget( + "trash", + $this->ctrl->getLinkTarget($this, "trash"), + "trash", + get_class($this) + ); + } + } + + + public function getHTML() + { + return $this->html; + } + + + /** + * set possible actions for objects in list. if actions are set + * via this method, the values of objects.xml are ignored. + * + * @param array $a_actions array with $command => $lang_var pairs + */ + final private function setActions($a_actions = "") + { + if (is_array($a_actions)) { + foreach ($a_actions as $name => $lng) { + $this->actions[$name] = array("name" => $name, "lng" => $lng); + } + } else { + $this->actions = ""; + } + } + + /** + * set possible subobjects for this object. if subobjects are set + * via this method, the values of objects.xml are ignored. + * + * @param array $a_actions array with $command => $lang_var pairs + */ + final private function setSubObjects($a_sub_objects = "") + { + if (is_array($a_sub_objects)) { + foreach ($a_sub_objects as $name => $options) { + $this->sub_objects[$name] = array("name" => $name, "max" => $options["max"]); + } + } else { + $this->sub_objects = ""; + } + } + + /** + * set Locator + * + * @param object tree object + * @param integer reference id + * @param scriptanme that is used for linking; + * @access public + */ + protected function setLocator() + { + $ilLocator = $this->locator; + $tpl = $this->tpl; + + if ($this->omit_locator) { + return; + } + + // repository vs. workspace + if ($this->call_by_reference) { + // todo: admin workaround + // in the future, objectgui classes should not be called in + // admin section anymore (rbac/trash handling in own classes) + $ref_id = ($_GET["ref_id"] != "") + ? $_GET["ref_id"] + : $this->object->getRefId(); + $ilLocator->addRepositoryItems($ref_id); + } + + if (!$this->creation_mode) { + $this->addLocatorItems(); + } + + $tpl->setLocator(); + } + + /** + * should be overwritten to add object specific items + * (repository items are preloaded) + */ + protected function addLocatorItems() + { + } + + protected function omitLocator($a_omit = true) + { + $this->omit_locator = $a_omit; + } + + /** + * should be overwritten to add object specific items + * (repository items are preloaded) + * + * @param bool $a_do_not_add_object + */ + protected function addAdminLocatorItems($a_do_not_add_object = false) + { + $ilLocator = $this->locator; + + if ($_GET["admin_mode"] == "settings") { // system settings + $this->ctrl->setParameterByClass( + "ilobjsystemfoldergui", + "ref_id", + SYSTEM_FOLDER_ID + ); + $ilLocator->addItem( + $this->lng->txt("administration"), + $this->ctrl->getLinkTargetByClass(array("iladministrationgui", "ilobjsystemfoldergui"), "") + ); + if ($this->object && ($this->object->getRefId() != SYSTEM_FOLDER_ID && !$a_do_not_add_object)) { + $ilLocator->addItem( + $this->object->getTitle(), + $this->ctrl->getLinkTarget($this, "view") + ); + } + } else { // repository administration + $this->ctrl->setParameterByClass( + "iladministrationgui", + "ref_id", + "" + ); + $this->ctrl->setParameterByClass( + "iladministrationgui", + "admin_mode", + "settings" + ); + //$ilLocator->addItem($this->lng->txt("administration"), + // $this->ctrl->getLinkTargetByClass("iladministrationgui", "frameset"), + // ilFrameTargetInfo::_getFrame("MainContent")); + $this->ctrl->clearParametersByClass("iladministrationgui"); + $ilLocator->addAdministrationItems(); + } + } + + /** + * confirmed deletion of object -> objects are moved to trash or deleted + * immediately, if trash is disabled + */ + public function confirmedDeleteObject() + { + if (isset($_POST["mref_id"])) { + $_SESSION["saved_post"] = array_unique(array_merge($_SESSION["saved_post"], $_POST["mref_id"])); + } + + include_once("./Services/Repository/classes/class.ilRepUtilGUI.php"); + $ru = new ilRepUtilGUI($this); + $ru->deleteObjects($_GET["ref_id"], ilSession::get("saved_post")); + ilSession::clear("saved_post"); + $this->ctrl->returnToParent($this); + } + + /** + * cancel deletion of object + * + * @access public + */ + public function cancelDeleteObject() + { + ilSession::clear("saved_post"); + $this->ctrl->returnToParent($this); + } + + + /** + * cancel action and go back to previous page + * @access public + * + */ + public function cancelObject() + { + ilSession::clear("saved_post"); + $this->ctrl->returnToParent($this); + } + + /** + * create new object form + * + * @access public + */ + public function createObject() + { + $tpl = $this->tpl; + $ilErr = $this->ilErr; + + $new_type = $_REQUEST["new_type"]; + + + // add new object to custom parent container + $this->ctrl->saveParameter($this, "crtptrefid"); + // use forced callback after object creation + $this->ctrl->saveParameter($this, "crtcb"); + + if (!$this->checkPermissionBool("create", "", $new_type)) { + $ilErr->raiseError($this->lng->txt("permission_denied"), $ilErr->MESSAGE); + } else { + $this->lng->loadLanguageModule($new_type); + $this->ctrl->setParameter($this, "new_type", $new_type); + + $forms = $this->initCreationForms($new_type); + + // copy form validation error: do not show other creation forms + if ($_GET["cpfl"] && isset($forms[self::CFORM_CLONE])) { + $forms = array(self::CFORM_CLONE => $forms[self::CFORM_CLONE]); + } + $tpl->setContent($this->getCreationFormsHTML($forms)); + } + } + + /** + * Init creation froms + * + * this will create the default creation forms: new, import, clone + * + * @param string $a_new_type + * @return array + */ + protected function initCreationForms($a_new_type) + { + $forms = array( + self::CFORM_NEW => $this->initCreateForm($a_new_type), + self::CFORM_IMPORT => $this->initImportForm($a_new_type), + self::CFORM_CLONE => $this->fillCloneTemplate(null, $a_new_type) + ); + + return $forms; + } + + /** + * Get HTML for creation forms (accordion) + * + * @param array $a_forms + */ + final protected function getCreationFormsHTML(array $a_forms) + { + $tpl = $this->tpl; + + // #13168- sanity check + foreach ($a_forms as $id => $form) { + if (!$form instanceof ilPropertyFormGUI) { + unset($a_forms[$id]); + } + } + + // no accordion if there is just one form + if (sizeof($a_forms) == 1) { + $form_type = key($a_forms); + $a_forms = array_shift($a_forms); + + // see bug #0016217 + if (method_exists($this, "getCreationFormTitle")) { + $form_title = $this->getCreationFormTitle($form_type); + if ($form_title != "") { + $a_forms->setTitle($form_title); + } + } + return $a_forms->getHTML(); + } else { + include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); + + $acc = new ilAccordionGUI(); + $acc->setBehaviour(ilAccordionGUI::FIRST_OPEN); + $cnt = 1; + foreach ($a_forms as $form_type => $cf) { + $htpl = new ilTemplate("tpl.creation_acc_head.html", true, true, "Services/Object"); + + // using custom form titles (used for repository plugins) + $form_title = ""; + if (method_exists($this, "getCreationFormTitle")) { + $form_title = $this->getCreationFormTitle($form_type); + } + if (!$form_title) { + $form_title = $cf->getTitle(); + } + + // move title from form to accordion + $htpl->setVariable("TITLE", $this->lng->txt("option") . " " . $cnt . ": " . + $form_title); + $cf->setTitle(null); + $cf->setTitleIcon(null); + $cf->setTableWidth("100%"); + + $acc->addItem($htpl->get(), $cf->getHTML()); + + $cnt++; + } + + return "
                  " . $acc->getHTML() . "
                  "; + } + } + + /** + * Init object creation form + * + * @param string $a_new_type + * @return ilPropertyFormGUI + */ + protected function initCreateForm($a_new_type) + { + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setTarget("_top"); + $form->setFormAction($this->ctrl->getFormAction($this, "save")); + $form->setTitle($this->lng->txt($a_new_type . "_new")); + + // title + $ti = new ilTextInputGUI($this->lng->txt("title"), "title"); + $ti->setSize(min(40, ilObject::TITLE_LENGTH)); + $ti->setMaxLength(ilObject::TITLE_LENGTH); + $ti->setRequired(true); + $form->addItem($ti); + + // description + $ta = new ilTextAreaInputGUI($this->lng->txt("description"), "desc"); + $ta->setCols(40); + $ta->setRows(2); + $form->addItem($ta); + + $form = $this->initDidacticTemplate($form); + + $form->addCommandButton("save", $this->lng->txt($a_new_type . "_add")); + $form->addCommandButton("cancel", $this->lng->txt("cancel")); + + return $form; + } + + /** + * Show didactic template types + * @param ilPropertyFormGUI $form + * @return ilPropertyFormGUI $form + */ + protected function initDidacticTemplate(ilPropertyFormGUI $form) + { + $lng = $this->lng; + + $lng->loadLanguageModule('didactic'); + $existing_exclusive = false; + $options = array(); + $options['dtpl_0'] = array($this->lng->txt('didactic_default_type'), + sprintf( + $this->lng->txt('didactic_default_type_info'), + $this->lng->txt('objs_' . $this->type) + )); + + include_once './Services/DidacticTemplate/classes/class.ilDidacticTemplateSettings.php'; + $templates = ilDidacticTemplateSettings::getInstanceByObjectType($this->type)->getTemplates(); + if ($templates) { + foreach ($templates as $template) { + if ($template->isEffective($_GET["ref_id"])) { + $options["dtpl_" . $template->getId()] = array( + $template->getPresentationTitle(), + $template->getPresentationDescription() + ); + + if ($template->isExclusive()) { + $existing_exclusive = true; + } + } + } + } + + $this->addDidacticTemplateOptions($options); + + if (sizeof($options) > 1) { + $type = new ilRadioGroupInputGUI( + $this->lng->txt('type'), + 'didactic_type' + ); + // workaround for containers in edit mode + if (!$this->getCreationMode()) { + include_once './Services/DidacticTemplate/classes/class.ilDidacticTemplateObjSettings.php'; + $value = 'dtpl_' . ilDidacticTemplateObjSettings::lookupTemplateId($this->object->getRefId()); + + $type->setValue($value); + + if (!in_array($value, array_keys($options)) || ($existing_exclusive && $value == "dtpl_0")) { + //add or rename actual value to not avaiable + $options[$value] = array($this->lng->txt('not_available')); + } + } else { + if ($existing_exclusive) { + //if an exclusive template exists use the second template as default value + $keys = array_keys($options); + $type->setValue($keys[1]); + } else { + $type->setValue('dtpl_0'); + } + } + $form->addItem($type); + + foreach ($options as $id => $data) { + $option = new ilRadioOption($data[0], $id, $data[1]); + + if ($existing_exclusive && $id == "dtpl_0" && $this->getCreationMode()) { + //set default disabled if an exclusive template exists but just in creation screen + $option->setDisabled(true); + } + + $type->addOption($option); + } + } + + return $form; + } + + /** + * Add custom templates + * + * @param array $a_options + */ + protected function addDidacticTemplateOptions(array &$a_options) + { + } + + /** + * cancel create action and go back to repository parent + */ + public function cancelCreation() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirectByClass("ilrepositorygui", "frameset"); + } + + /** + * save object + * + * @access public + */ + public function saveObject() + { + $objDefinition = $this->objDefinition; + $tpl = $this->tpl; + $ilErr = $this->ilErr; + + $new_type = $_REQUEST["new_type"]; + + // create permission is already checked in createObject. This check here is done to prevent hacking attempts + if (!$this->checkPermissionBool("create", "", $new_type)) { + $ilErr->raiseError($this->lng->txt("no_create_permission"), $ilErr->MESSAGE); + } + + $this->lng->loadLanguageModule($new_type); + $this->ctrl->setParameter($this, "new_type", $new_type); + + $form = $this->initCreateForm($new_type); + if ($form->checkInput()) { + $this->ctrl->setParameter($this, "new_type", ""); + + // create instance + $class_name = "ilObj" . $objDefinition->getClassName($new_type); + $location = $objDefinition->getLocation($new_type); + include_once($location . "/class." . $class_name . ".php"); + $newObj = new $class_name(); + $newObj->setType($new_type); + $newObj->setTitle($form->getInput("title")); + $newObj->setDescription($form->getInput("desc")); + $newObj->create(); + + $this->putObjectInTree($newObj); + + // apply didactic template? + $dtpl = $this->getDidacticTemplateVar("dtpl"); + if ($dtpl) { + $newObj->applyDidacticTemplate($dtpl); + } + + // auto rating + $this->handleAutoRating($newObj); + + // additional paramters are added to afterSave() + $args = func_get_args(); + if ($args) { + $this->afterSave($newObj, $args); + } else { + $this->afterSave($newObj); + } + return; + } + + // display only this form to correct input + $form->setValuesByPost(); + $tpl->setContent($form->getHtml()); + } + + /** + * Get didactic template setting from creation screen + * + * @param string $a_type + * @return string + */ + public function getDidacticTemplateVar($a_type) + { + $tpl = $_POST["didactic_type"]; + if ($tpl && substr($tpl, 0, strlen($a_type)+1) == $a_type . "_") { + return (int) substr($tpl, strlen($a_type)+1); + } + return 0; + } + + /** + * Add object to tree at given position + * + * @param ilObject $a_obj + * @param int $a_parent_node_id + */ + public function putObjectInTree(ilObject $a_obj, $a_parent_node_id = null) + { + $rbacreview = $this->rbacreview; + $ilUser = $this->user; + $objDefinition = $this->objDefinition; + + if (!$a_parent_node_id) { + $a_parent_node_id = $_GET["ref_id"]; + } + + // add new object to custom parent container + if ((int) $_REQUEST["crtptrefid"]) { + $a_parent_node_id = (int) $_REQUEST["crtptrefid"]; + } + + $a_obj->createReference(); + $a_obj->putInTree($a_parent_node_id); + $a_obj->setPermissions($a_parent_node_id); + + $this->obj_id = $a_obj->getId(); + $this->ref_id = $a_obj->getRefId(); + + // BEGIN ChangeEvent: Record save object. + require_once('Services/Tracking/classes/class.ilChangeEvent.php'); + ilChangeEvent::_recordWriteEvent($this->obj_id, $ilUser->getId(), 'create'); + // END ChangeEvent: Record save object. + + // rbac log + include_once "Services/AccessControl/classes/class.ilRbacLog.php"; + $rbac_log_roles = $rbacreview->getParentRoleIds($this->ref_id, false); + $rbac_log = ilRbacLog::gatherFaPa($this->ref_id, array_keys($rbac_log_roles), true); + ilRbacLog::add(ilRbacLog::CREATE_OBJECT, $this->ref_id, $rbac_log); + + // use forced callback after object creation + if ($_REQUEST["crtcb"]) { + $callback_type = ilObject::_lookupType((int) $_REQUEST["crtcb"], true); + $class_name = "ilObj" . $objDefinition->getClassName($callback_type) . "GUI"; + $location = $objDefinition->getLocation($callback_type); + include_once($location . "/class." . $class_name . ".php"); + if (in_array(strtolower($class_name), array("ilobjitemgroupgui"))) { + $callback_obj = new $class_name((int) $_REQUEST["crtcb"]); + } else { + // #10368 + $callback_obj = new $class_name(null, (int) $_REQUEST["crtcb"], true, false); + } + $callback_obj->afterSaveCallback($a_obj); + } + } + + /** + * Post (successful) object creation hook + * + * @param ilObject $a_new_object + */ + protected function afterSave(ilObject $a_new_object) + { + ilUtil::sendSuccess($this->lng->txt("object_added"), true); + $this->ctrl->returnToParent($this); + } + + /** + * edit object + * + * @access public + */ + public function editObject() + { + $tpl = $this->tpl; + $ilTabs = $this->tabs_gui; + $ilErr = $this->ilErr; + + if (!$this->checkPermissionBool("write")) { + $ilErr->raiseError($this->lng->txt("msg_no_perm_write"), $ilErr->MESSAGE); + } + + $ilTabs->activateTab("settings"); + + $form = $this->initEditForm(); + $values = $this->getEditFormValues(); + if ($values) { + $form->setValuesByArray($values); + } + + $this->addExternalEditFormCustom($form); + + $tpl->setContent($form->getHTML()); + } + + public function addExternalEditFormCustom(ilPropertyFormGUI $a_form) + { + // has to be done AFTER setValuesByArray() ... + } + + /** + * Init object edit form + * + * @return ilPropertyFormGUI + */ + protected function initEditForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $lng->loadLanguageModule($this->object->getType()); + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this, "update")); + $form->setTitle($this->lng->txt($this->object->getType() . "_edit")); + + // title + $ti = new ilTextInputGUI($this->lng->txt("title"), "title"); + $ti->setSize(min(40, ilObject::TITLE_LENGTH)); + $ti->setMaxLength(ilObject::TITLE_LENGTH); + $ti->setRequired(true); + $form->addItem($ti); + + // description + $ta = new ilTextAreaInputGUI($this->lng->txt("description"), "desc"); + $ta->setCols(40); + $ta->setRows(2); + $form->addItem($ta); + + $this->initEditCustomForm($form); + + $form->addCommandButton("update", $this->lng->txt("save")); + //$this->form->addCommandButton("cancelUpdate", $lng->txt("cancel")); + + return $form; + } + + /** + * Add custom fields to update form + * + * @param ilPropertyFormGUI $a_form + */ + protected function initEditCustomForm(ilPropertyFormGUI $a_form) + { + } + + /** + * Get values for edit form + * + * @return array + */ + protected function getEditFormValues() + { + $values["title"] = $this->object->getTitle(); + $values["desc"] = $this->object->getLongDescription(); + $this->getEditFormCustomValues($values); + return $values; + } + + /** + * Add values to custom edit fields + * + * @param array $a_values + */ + protected function getEditFormCustomValues(array &$a_values) + { + } + + /** + * updates object entry in object_data + */ + public function updateObject() + { + $ilTabs = $this->tabs_gui; + $tpl = $this->tpl; + $ilErr = $this->ilErr; + + if (!$this->checkPermissionBool("write")) { + $ilErr->raiseError($this->lng->txt("permission_denied"), $ilErr->MESSAGE); + } + + $form = $this->initEditForm(); + if ($form->checkInput() && + $this->validateCustom($form)) { + $this->object->setTitle($form->getInput("title")); + $this->object->setDescription($form->getInput("desc")); + $this->updateCustom($form); + $this->object->update(); + + $this->afterUpdate(); + return; + } + + // display form again to correct errors + $ilTabs->activateTab("settings"); + $form->setValuesByPost(); + $tpl->setContent($form->getHtml()); + } + + /** + * Validate custom values (if not possible with checkInput()) + * + * @param ilPropertyFormGUI $a_form + * @return boolean + */ + protected function validateCustom(ilPropertyFormGUI $a_form) + { + return true; + } + + /** + * Insert custom update form values into object + * + * @param ilPropertyFormGUI $a_form + */ + protected function updateCustom(ilPropertyFormGUI $a_form) + { + } + + /** + * Post (successful) object update hook + */ + protected function afterUpdate() + { + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "edit"); + } + + /** + * Init object import form + * + * @param string new type + * @return ilPropertyFormGUI + */ + protected function initImportForm($a_new_type) + { + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setTarget("_top"); + $form->setFormAction($this->ctrl->getFormAction($this, "importFile")); + $form->setTitle($this->lng->txt($a_new_type . "_import")); + + include_once("./Services/Form/classes/class.ilFileInputGUI.php"); + $fi = new ilFileInputGUI($this->lng->txt("import_file"), "importfile"); + $fi->setSuffixes(array("zip")); + $fi->setRequired(true); + $form->addItem($fi); + + $form->addCommandButton("importFile", $this->lng->txt("import")); + $form->addCommandButton("cancel", $this->lng->txt("cancel")); + + return $form; + } + + /** + * Import + */ + protected function importFileObject($parent_id = null, $a_catch_errors = true) + { + $objDefinition = $this->objDefinition; + $tpl = $this->tpl; + $ilErr = $this->ilErr; + + if (!$parent_id) { + $parent_id = $_GET["ref_id"]; + } + $new_type = $_REQUEST["new_type"]; + + // create permission is already checked in createObject. This check here is done to prevent hacking attempts + if (!$this->checkPermissionBool("create", "", $new_type)) { + $ilErr->raiseError($this->lng->txt("no_create_permission")); + } + + $this->lng->loadLanguageModule($new_type); + $this->ctrl->setParameter($this, "new_type", $new_type); + + $form = $this->initImportForm($new_type); + if ($form->checkInput()) { + // :todo: make some check on manifest file + + if ($objDefinition->isContainer($new_type)) { + include_once './Services/Export/classes/class.ilImportContainer.php'; + $imp = new ilImportContainer((int) $parent_id); + } else { + include_once("./Services/Export/classes/class.ilImport.php"); + $imp = new ilImport((int) $parent_id); + } + + try { + $new_id = $imp->importObject( + null, + $_FILES["importfile"]["tmp_name"], + $_FILES["importfile"]["name"], + $new_type + ); + } catch (ilException $e) { + $this->tmp_import_dir = $imp->getTemporaryImportDir(); + if (!$a_catch_errors) { + throw $e; + } + // display message and form again + ilUtil::sendFailure($this->lng->txt("obj_import_file_error") . "
                  " . $e->getMessage()); + $form->setValuesByPost(); + $tpl->setContent($form->getHtml()); + return; + } + + if ($new_id > 0) { + $this->ctrl->setParameter($this, "new_type", ""); + + $newObj = ilObjectFactory::getInstanceByObjId($new_id); + + // put new object id into tree - already done in import for containers + if (!$objDefinition->isContainer($new_type)) { + $this->putObjectInTree($newObj); + } + + $this->afterImport($newObj); + } + // import failed + else { + if ($objDefinition->isContainer($new_type)) { + ilUtil::sendFailure($this->lng->txt("container_import_zip_file_invalid")); + } else { + // not enough information here... + return; + } + } + } + + // display form to correct errors + $form->setValuesByPost(); + $tpl->setContent($form->getHtml()); + } + + /** + * Post (successful) object import hook + * + * @param ilObject $a_new_object + */ + protected function afterImport(ilObject $a_new_object) + { + ilUtil::sendSuccess($this->lng->txt("object_added"), true); + $this->ctrl->returnToParent($this); + } + + /** + * get form action for command (command is method name without "Object", e.g. "perm") + * @param string $a_cmd command + * @param string $a_formaction default formaction (is returned, if no special + * formaction was set) + * @access public + * @return string + */ + public function getFormAction($a_cmd, $a_formaction = "") + { + if ($this->formaction[$a_cmd] != "") { + return $this->formaction[$a_cmd]; + } else { + return $a_formaction; + } + } + + /** + * set specific form action for command + * + * @param string $a_cmd command + * @param string $a_formaction default formaction (is returned, if no special + * formaction was set) + * @access public + */ + protected function setFormAction($a_cmd, $a_formaction) + { + $this->formaction[$a_cmd] = $a_formaction; + } + + /** + * get return location for command (command is method name without "Object", e.g. "perm") + * @param string $a_cmd command + * @param string $a_location default return location (is returned, if no special + * return location was set) + * @access public + */ + protected function getReturnLocation($a_cmd, $a_location ="") + { + if ($this->return_location[$a_cmd] != "") { + return $this->return_location[$a_cmd]; + } else { + return $a_location; + } + } + + /** + * set specific return location for command + * @param string $a_cmd command + * @param string $a_location default return location (is returned, if no special + * return location was set) + * @access public + */ + protected function setReturnLocation($a_cmd, $a_location) + { + //echo "-".$a_cmd."-".$a_location."-"; + $this->return_location[$a_cmd] = $a_location; + } + + /** + * get target frame for command (command is method name without "Object", e.g. "perm") + * @param string $a_cmd command + * @param string $a_target_frame default target frame (is returned, if no special + * target frame was set) + * @access public + */ + protected function getTargetFrame($a_cmd, $a_target_frame = "") + { + if ($this->target_frame[$a_cmd] != "") { + return $this->target_frame[$a_cmd]; + } elseif (!empty($a_target_frame)) { + return "target=\"" . $a_target_frame . "\""; + } else { + return; + } + } + + /** + * set specific target frame for command + * @param string $a_cmd command + * @param string $a_target_frame default target frame (is returned, if no special + * target frame was set) + * @access public + */ + protected function setTargetFrame($a_cmd, $a_target_frame) + { + $this->target_frame[$a_cmd] = "target=\"" . $a_target_frame . "\""; + } + + // BEGIN Security: Hide objects which aren't accessible by the user. + public function isVisible($a_ref_id, $a_type) + { + $visible = $this->checkPermissionBool("visible,read", "", "", $a_ref_id); + + if ($visible && $a_type == 'crs') { + $tree = $this->tree; + if ($crs_id = $tree->checkForParentType($a_ref_id, 'crs')) { + if (!$this->checkPermissionBool("write", "", "", $crs_id)) { + // Show only activated courses + $tmp_obj =&ilObjectFactory::getInstanceByRefId($crs_id, false); + + if (!$tmp_obj->isActivated()) { + unset($tmp_obj); + $visible = false; + } + } + } + } + + return $visible; + } + // END Security: Hide objects which aren't accessible by the user. + + /** + * list childs of current object + * + * @access public + */ + public function viewObject() + { + $tpl = $this->tpl; + $ilErr = $this->ilErr; + + if (!$this->checkPermissionBool("visible,read")) { + $ilErr->raiseError($this->lng->txt("permission_denied"), $ilErr->MESSAGE); + } + + // BEGIN ChangeEvent: record read event. + require_once('Services/Tracking/classes/class.ilChangeEvent.php'); + $ilUser = $this->user; + ilChangeEvent::_recordReadEvent( + $this->object->getType(), + $this->object->getRefId(), + $this->object->getId(), + $ilUser->getId() + ); + // END ChangeEvent: record read event. + + include_once("./Services/Repository/classes/class.ilAdminSubItemsTableGUI.php"); + if (!$this->call_by_reference) { + $this->ctrl->setParameter($this, "obj_id", $this->obj_id); + } + $itab = new ilAdminSubItemsTableGUI( + $this, + "view", + $_GET["ref_id"], + $this->checkPermissionBool('write') + ); + + $tpl->setContent($itab->getHTML()); + } + + /** + * Display deletion confirmation screen. + * Only for referenced objects. For user,role & rolt overwrite this function in the appropriate + * Object folders classes (ilObjUserFolderGUI,ilObjRoleFolderGUI) + * + * @access public + */ + public function deleteObject($a_error = false) + { + $ilCtrl = $this->ctrl; + + if ($_GET["item_ref_id"] != "") { + $_POST["id"] = array($_GET["item_ref_id"]); + } + + if (is_array($_POST["id"])) { + foreach ($_POST["id"] as $idx => $id) { + $_POST["id"][$idx] = (int) $id; + } + } + + // SAVE POST VALUES (get rid of this + ilSession::set("saved_post", $_POST["id"]); + + include_once("./Services/Repository/classes/class.ilRepUtilGUI.php"); + $ru = new ilRepUtilGUI($this); + if (!$ru->showDeleteConfirmation($_POST["id"], $a_error)) { + $ilCtrl->returnToParent($this); + } + } + + /** + * show possible subobjects (pulldown menu) + * + * @access public + */ + protected function showPossibleSubObjects() + { + if ($this->sub_objects == "") { + $d = $this->objDefinition->getCreatableSubObjects($this->object->getType(), ilObjectDefinition::MODE_REPOSITORY, $this->ref_id); + } else { + $d = $this->sub_objects; + } + + $import = false; + + if (count($d) > 0) { + foreach ($d as $row) { + $count = 0; + + if ($row["max"] > 0) { + //how many elements are present? + for ($i=0; $idata["ctrl"]); $i++) { + if ($this->data["ctrl"][$i]["type"] == $row["name"]) { + $count++; + } + } + } + + if ($row["max"] == "" || $count < $row["max"]) { + $subobj[] = $row["name"]; + } + } + } + + if (is_array($subobj)) { + + //build form + $opts = ilUtil::formSelect(12, "new_type", $subobj); + $this->tpl->setCurrentBlock("add_object"); + $this->tpl->setVariable("SELECT_OBJTYPE", $opts); + $this->tpl->setVariable("BTN_NAME", "create"); + $this->tpl->setVariable("TXT_ADD", $this->lng->txt("add")); + $this->tpl->parseCurrentBlock(); + } + } + + /** + * get a template blockfile + * format: tpl._.html + * + * @param string command + * @param string object type definition + * @access public + */ + final protected function getTemplateFile($a_cmd, $a_type = "") + { + mk(); + die("ilObjectGUI::getTemplateFile() is deprecated."); + } + + /** + * get tabs + * abstract method. + * @abstract overwrite in derived GUI class of your object type + * @access public + * @param object instance of ilTabsGUI + */ + protected function getTabs() + { + // please define your tabs here + } + + // PROTECTED + protected function __showButton($a_cmd, $a_text, $a_target = '') + { + $ilToolbar = $this->toolbar; + + $ilToolbar->addButton($a_text, $this->ctrl->getLinkTarget($this, $a_cmd), $a_target); + } + + protected function hitsperpageObject() + { ilSession::set("tbl_limit", $_POST["hitsperpage"]); $_GET["limit"] = $_POST["hitsperpage"]; - } - - - protected function &__initTableGUI() - { - include_once "./Services/Table/classes/class.ilTableGUI.php"; - - return new ilTableGUI(0,false); - } - - /** - * standard implementation for tables - * use 'from' variable use different initial setting of table - * - */ - protected function __setTableGUIBasicData(&$tbl,&$result_set,$a_from = "") - { - switch ($a_from) - { - case "clipboardObject": - $offset = $_GET["offset"]; - $order = $_GET["sort_by"]; - $direction = $_GET["sort_order"]; - $tbl->disable("footer"); - break; - - default: - $offset = $_GET["offset"]; - $order = $_GET["sort_by"]; - $direction = $_GET["sort_order"]; - break; - } - - $tbl->setOrderColumn($order); - $tbl->setOrderDirection($direction); - $tbl->setOffset($offset); - $tbl->setLimit($_GET["limit"]); - $tbl->setFooter("tblfooter",$this->lng->txt("previous"),$this->lng->txt("next")); - $tbl->setData($result_set); - } - - /** - * redirects to (repository) view per ref id - * usually to a container and usually used at - * the end of a save/import method where the object gui - * type (of the new object) doesn't match with the type - * of the current $_GET["ref_id"] value - * - * @param int $a_ref_id reference id - */ - protected function redirectToRefId($a_ref_id, $a_cmd = "") - { - $obj_type = ilObject::_lookupType($a_ref_id,true); - $class_name = $this->objDefinition->getClassName($obj_type); - $class = strtolower("ilObj".$class_name."GUI"); - $this->ctrl->setParameterByClass("ilrepositorygui", "ref_id", $a_ref_id); - $this->ctrl->redirectByClass(array("ilrepositorygui", $class), $a_cmd); - } - - // Object Cloning - /** - * Fill object clone template - * This method can be called from any object GUI class that wants to offer object cloning. - * - * @access public - * @param string template variable name that will be filled - * @param string type of new object - * - */ - protected function fillCloneTemplate($a_tpl_varname,$a_type) - { - include_once './Services/Object/classes/class.ilObjectCopyGUI.php'; - $cp = new ilObjectCopyGUI($this); - $cp->setType($a_type); - $cp->setTarget($_GET['ref_id']); - if($a_tpl_varname) - { - $cp->showSourceSearch($a_tpl_varname); - } - else - { - return $cp->showSourceSearch(null); - } - } - - /** - * Clone single (not container object) - * Method is overwritten in ilContainerGUI - * - * @access public - */ - public function cloneAllObject() - { - include_once('./Services/Link/classes/class.ilLink.php'); - include_once('Services/CopyWizard/classes/class.ilCopyWizardOptions.php'); - - $ilErr = $this->ilErr; - $ilUser = $this->user; - - $new_type = $_REQUEST['new_type']; - if(!$this->checkPermissionBool("create", "", $new_type)) - { - $ilErr->raiseError($this->lng->txt('permission_denied')); - } - if(!(int) $_REQUEST['clone_source']) - { - ilUtil::sendFailure($this->lng->txt('select_one')); - $this->createObject(); - return false; - } - if(!$this->checkPermissionBool("write", "", $new_type, (int)$_REQUEST['clone_source'])) - { - $ilErr->raiseError($this->lng->txt('permission_denied')); - } - - // Save wizard options - $copy_id = ilCopyWizardOptions::_allocateCopyId(); - $wizard_options = ilCopyWizardOptions::_getInstance($copy_id); - $wizard_options->saveOwner($ilUser->getId()); - $wizard_options->saveRoot((int) $_REQUEST['clone_source']); - - $options = $_POST['cp_options'] ? $_POST['cp_options'] : array(); - foreach($options as $source_id => $option) - { - $wizard_options->addEntry($source_id,$option); - } - $wizard_options->read(); - - $orig = ilObjectFactory::getInstanceByRefId((int) $_REQUEST['clone_source']); - $new_obj = $orig->cloneObject((int) $_GET['ref_id'],$copy_id); - - // Delete wizard options - $wizard_options->deleteAll(); - - ilUtil::sendSuccess($this->lng->txt("object_duplicated"),true); - ilUtil::redirect(ilLink::_getLink($new_obj->getRefId())); - } - - - /** - * Get center column - */ - protected function getCenterColumnHTML() - { - $ilCtrl = $this->ctrl; - - include_once("Services/Block/classes/class.ilColumnGUI.php"); - - $obj_id = ilObject::_lookupObjId($this->object->getRefId()); - $obj_type = ilObject::_lookupType($obj_id); - - if ($ilCtrl->getNextClass() != "ilcolumngui") - { - // normal command processing - return $this->getContent(); - } - else - { - if (!$ilCtrl->isAsynch()) - { - //if ($column_gui->getScreenMode() != IL_SCREEN_SIDE) - if (ilColumnGUI::getScreenMode() != IL_SCREEN_SIDE) - { - // right column wants center - if (ilColumnGUI::getCmdSide() == IL_COL_RIGHT) - { - $column_gui = new ilColumnGUI($obj_type, IL_COL_RIGHT); - $this->setColumnSettings($column_gui); - $this->html = $ilCtrl->forwardCommand($column_gui); - } - // left column wants center - if (ilColumnGUI::getCmdSide() == IL_COL_LEFT) - { - $column_gui = new ilColumnGUI($obj_type, IL_COL_LEFT); - $this->setColumnSettings($column_gui); - $this->html = $ilCtrl->forwardCommand($column_gui); - } - } - else - { - // normal command processing - return $this->getContent(); - } - } - } - } - - /** - * Display right column - */ - protected function getRightColumnHTML() - { - $ilUser = $this->user; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $obj_id = ilObject::_lookupObjId($this->object->getRefId()); - $obj_type = ilObject::_lookupType($obj_id); - - include_once("Services/Block/classes/class.ilColumnGUI.php"); - $column_gui = new ilColumnGUI($obj_type, IL_COL_RIGHT); - - if ($column_gui->getScreenMode() == IL_SCREEN_FULL) - { - return ""; - } - - $this->setColumnSettings($column_gui); - - if ($ilCtrl->getNextClass() == "ilcolumngui" && - $column_gui->getCmdSide() == IL_COL_RIGHT && - $column_gui->getScreenMode() == IL_SCREEN_SIDE) - { - $html = $ilCtrl->forwardCommand($column_gui); - } - else - { - if (!$ilCtrl->isAsynch()) - { - $html = $ilCtrl->getHTML($column_gui); - } - } - - return $html; - } - - /** - * May be overwritten in subclasses. - */ - protected function setColumnSettings(ilColumnGUI $column_gui) - { - $column_gui->setRepositoryMode(true); - $column_gui->setEnableEdit(false); - if ($this->checkPermissionBool("write")) - { - $column_gui->setEnableEdit(true); - } - } - - /** - * Check permission and redirect on error - * - * @param string $a_perm - * @param string $a_cmd - * @param string $a_type - * @param int $a_ref_id - * @throws ilObjectException - * @return bool - */ - protected function checkPermission($a_perm, $a_cmd = "", $a_type = "", $a_ref_id = null) - { - if (!$this->checkPermissionBool($a_perm, $a_cmd, $a_type, $a_ref_id)) - { - if (!is_int(strpos($_SERVER["PHP_SELF"], "goto.php"))) - { - // create: redirect to parent - if($a_perm == "create") - { - if(!$a_ref_id) - { - $a_ref_id = $_GET["ref_id"]; - } - $type = ilObject::_lookupType($a_ref_id, true); - } - else - { - // does this make sense? - if (!is_object($this->object)) - { - return; - } - if (!$a_ref_id) - { - $a_ref_id = $this->object->getRefId(); - } - $type = $this->object->getType(); - } - - ilSession::clear("il_rep_ref_id"); - - include_once "Services/Object/exceptions/class.ilObjectException.php"; - throw new ilObjectException($this->lng->txt("permission_denied")); - - /* - ilUtil::sendFailure($this->lng->txt("permission_denied"), true); - ilUtil::redirect("goto.php?target=".$type."_".$a_ref_id); - */ - } - // we should never be here - else - { - die("Permission Denied."); - } - } - } - - /** - * Check permission - * - * @param string $a_perm - * @param string $a_cmd - * @param string $a_type - * @param int $a_ref_id - * @return bool - */ - protected function checkPermissionBool($a_perm, $a_cmd = "", $a_type = "", $a_ref_id = null) - { - $ilAccess = $this->access; - - if($a_perm == "create") - { - if(!$a_ref_id) - { - $a_ref_id = $_GET["ref_id"]; - } - return $ilAccess->checkAccess($a_perm."_".$a_type, $a_cmd, $a_ref_id); - } - else - { - // does this make sense? - if (!is_object($this->object)) - { - return false; - } - if (!$a_ref_id) - { - $a_ref_id = $this->object->getRefId(); - } - return $ilAccess->checkAccess($a_perm, $a_cmd, $a_ref_id); - } - } - - /** - * Goto repository root - * - * @param - * @return - */ - static function _gotoRepositoryRoot($a_raise_error = false) - { - global $DIC; - - $ilAccess = $DIC->access(); - $ilErr = $DIC["ilErr"]; - $lng = $DIC->language(); - - if ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) - { - $_GET["cmd"] = "frameset"; - $_GET["target"] = ""; - $_GET["ref_id"] = ROOT_FOLDER_ID; - $_GET["baseClass"] = "ilRepositoryGUI"; - include("ilias.php"); - exit; - } - - if ($a_raise_error) - { - $ilErr->raiseError($lng->txt("msg_no_perm_read"), $ilErr->FATAL); - } - } - - /** - * Goto repository root - * - * @param - * @return - */ - static function _gotoRepositoryNode($a_ref_id, $a_cmd = "frameset") - { - global $DIC; - - $ilAccess = $DIC->access(); - $ilErr = $DIC["ilErr"]; - - $_GET["cmd"] = $a_cmd; - $_GET["target"] = ""; - $_GET["ref_id"] = $a_ref_id; - $_GET["baseClass"] = "ilRepositoryGUI"; - include("ilias.php"); - exit; - } - - /** - * Enables the file upload into this object by dropping files. - */ - protected function enableDragDropFileUpload() - { - include_once("./Services/FileUpload/classes/class.ilFileUploadGUI.php"); - ilFileUploadGUI::initFileUpload(); - - $this->tpl->enableDragDropFileUpload($this->ref_id); - } - - /** - * Activate rating automatically if parent container setting - * - * @param ilObject $a_new_obj - */ - protected function handleAutoRating(ilObject $a_new_obj) - { - if(ilObject::hasAutoRating($a_new_obj->getType(), $a_new_obj->getRefId()) && - method_exists($a_new_obj, "setRating")) - { - $a_new_obj->setRating(true); - $a_new_obj->update(); - } - } - - /** - * show edit section of custom icons for container - * - */ - protected function showCustomIconsEditing($a_input_colspan = 1, ilPropertyFormGUI $a_form = null, $a_as_section = true) - { - if ($this->settings->get("custom_icons")) { - if ($a_form) { - global $DIC; - /** @var \ilObjectCustomIconFactory $customIconFactory */ - $customIconFactory = $DIC['object.customicons.factory']; - - $customIcon = $customIconFactory->getByObjId($this->object->getId(), $this->object->getType()); - - if ($a_as_section) { - $title = new ilFormSectionHeaderGUI(); - $title->setTitle($this->lng->txt("icon_settings")); - } else { - $title = new ilCustomInputGUI($this->lng->txt("icon_settings"), ""); - } - $a_form->addItem($title); - - $caption = $this->lng->txt("cont_custom_icon"); - $icon = new ilImageFileInputGUI($caption, "cont_icon"); - - $icon->setSuffixes($customIcon->getSupportedFileExtensions()); - $icon->setUseCache(false); - if ($customIcon->exists()) { - $icon->setImage($customIcon->getFullPath()); - } else { - $icon->setImage(''); - } - if ($a_as_section) { - $a_form->addItem($icon); - } else { - $title->addSubItem($icon); - } - } - } - } - - /** - * Redirect after creation, see https://docu.ilias.de/goto_docu_wiki_wpage_5035_1357.html - * - * Should be overwritten and redirect to settings screen. - */ - public function redirectAfterCreation() - { - $ctrl = $this->ctrl; - $link = ilLink::_getLink($this->object->getRefId()); - $ctrl->redirectToURL($link); - } - + } + + + protected function &__initTableGUI() + { + include_once "./Services/Table/classes/class.ilTableGUI.php"; + + return new ilTableGUI(0, false); + } + + /** + * standard implementation for tables + * use 'from' variable use different initial setting of table + * + */ + protected function __setTableGUIBasicData(&$tbl, &$result_set, $a_from = "") + { + switch ($a_from) { + case "clipboardObject": + $offset = $_GET["offset"]; + $order = $_GET["sort_by"]; + $direction = $_GET["sort_order"]; + $tbl->disable("footer"); + break; + + default: + $offset = $_GET["offset"]; + $order = $_GET["sort_by"]; + $direction = $_GET["sort_order"]; + break; + } + + $tbl->setOrderColumn($order); + $tbl->setOrderDirection($direction); + $tbl->setOffset($offset); + $tbl->setLimit($_GET["limit"]); + $tbl->setFooter("tblfooter", $this->lng->txt("previous"), $this->lng->txt("next")); + $tbl->setData($result_set); + } + + /** + * redirects to (repository) view per ref id + * usually to a container and usually used at + * the end of a save/import method where the object gui + * type (of the new object) doesn't match with the type + * of the current $_GET["ref_id"] value + * + * @param int $a_ref_id reference id + */ + protected function redirectToRefId($a_ref_id, $a_cmd = "") + { + $obj_type = ilObject::_lookupType($a_ref_id, true); + $class_name = $this->objDefinition->getClassName($obj_type); + $class = strtolower("ilObj" . $class_name . "GUI"); + $this->ctrl->setParameterByClass("ilrepositorygui", "ref_id", $a_ref_id); + $this->ctrl->redirectByClass(array("ilrepositorygui", $class), $a_cmd); + } + + // Object Cloning + /** + * Fill object clone template + * This method can be called from any object GUI class that wants to offer object cloning. + * + * @access public + * @param string template variable name that will be filled + * @param string type of new object + * + */ + protected function fillCloneTemplate($a_tpl_varname, $a_type) + { + include_once './Services/Object/classes/class.ilObjectCopyGUI.php'; + $cp = new ilObjectCopyGUI($this); + $cp->setType($a_type); + $cp->setTarget($_GET['ref_id']); + if ($a_tpl_varname) { + $cp->showSourceSearch($a_tpl_varname); + } else { + return $cp->showSourceSearch(null); + } + } + + /** + * Clone single (not container object) + * Method is overwritten in ilContainerGUI + * + * @access public + */ + public function cloneAllObject() + { + include_once('./Services/Link/classes/class.ilLink.php'); + include_once('Services/CopyWizard/classes/class.ilCopyWizardOptions.php'); + + $ilErr = $this->ilErr; + $ilUser = $this->user; + + $new_type = $_REQUEST['new_type']; + if (!$this->checkPermissionBool("create", "", $new_type)) { + $ilErr->raiseError($this->lng->txt('permission_denied')); + } + if (!(int) $_REQUEST['clone_source']) { + ilUtil::sendFailure($this->lng->txt('select_one')); + $this->createObject(); + return false; + } + if (!$this->checkPermissionBool("write", "", $new_type, (int) $_REQUEST['clone_source'])) { + $ilErr->raiseError($this->lng->txt('permission_denied')); + } + + // Save wizard options + $copy_id = ilCopyWizardOptions::_allocateCopyId(); + $wizard_options = ilCopyWizardOptions::_getInstance($copy_id); + $wizard_options->saveOwner($ilUser->getId()); + $wizard_options->saveRoot((int) $_REQUEST['clone_source']); + + $options = $_POST['cp_options'] ? $_POST['cp_options'] : array(); + foreach ($options as $source_id => $option) { + $wizard_options->addEntry($source_id, $option); + } + $wizard_options->read(); + + $orig = ilObjectFactory::getInstanceByRefId((int) $_REQUEST['clone_source']); + $new_obj = $orig->cloneObject((int) $_GET['ref_id'], $copy_id); + + // Delete wizard options + $wizard_options->deleteAll(); + + ilUtil::sendSuccess($this->lng->txt("object_duplicated"), true); + ilUtil::redirect(ilLink::_getLink($new_obj->getRefId())); + } + + + /** + * Get center column + */ + protected function getCenterColumnHTML() + { + $ilCtrl = $this->ctrl; + + include_once("Services/Block/classes/class.ilColumnGUI.php"); + + $obj_id = ilObject::_lookupObjId($this->object->getRefId()); + $obj_type = ilObject::_lookupType($obj_id); + + if ($ilCtrl->getNextClass() != "ilcolumngui") { + // normal command processing + return $this->getContent(); + } else { + if (!$ilCtrl->isAsynch()) { + //if ($column_gui->getScreenMode() != IL_SCREEN_SIDE) + if (ilColumnGUI::getScreenMode() != IL_SCREEN_SIDE) { + // right column wants center + if (ilColumnGUI::getCmdSide() == IL_COL_RIGHT) { + $column_gui = new ilColumnGUI($obj_type, IL_COL_RIGHT); + $this->setColumnSettings($column_gui); + $this->html = $ilCtrl->forwardCommand($column_gui); + } + // left column wants center + if (ilColumnGUI::getCmdSide() == IL_COL_LEFT) { + $column_gui = new ilColumnGUI($obj_type, IL_COL_LEFT); + $this->setColumnSettings($column_gui); + $this->html = $ilCtrl->forwardCommand($column_gui); + } + } else { + // normal command processing + return $this->getContent(); + } + } + } + } + + /** + * Display right column + */ + protected function getRightColumnHTML() + { + $ilUser = $this->user; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $obj_id = ilObject::_lookupObjId($this->object->getRefId()); + $obj_type = ilObject::_lookupType($obj_id); + + include_once("Services/Block/classes/class.ilColumnGUI.php"); + $column_gui = new ilColumnGUI($obj_type, IL_COL_RIGHT); + + if ($column_gui->getScreenMode() == IL_SCREEN_FULL) { + return ""; + } + + $this->setColumnSettings($column_gui); + + if ($ilCtrl->getNextClass() == "ilcolumngui" && + $column_gui->getCmdSide() == IL_COL_RIGHT && + $column_gui->getScreenMode() == IL_SCREEN_SIDE) { + $html = $ilCtrl->forwardCommand($column_gui); + } else { + if (!$ilCtrl->isAsynch()) { + $html = $ilCtrl->getHTML($column_gui); + } + } + + return $html; + } + + /** + * May be overwritten in subclasses. + */ + protected function setColumnSettings(ilColumnGUI $column_gui) + { + $column_gui->setRepositoryMode(true); + $column_gui->setEnableEdit(false); + if ($this->checkPermissionBool("write")) { + $column_gui->setEnableEdit(true); + } + } + + /** + * Check permission and redirect on error + * + * @param string $a_perm + * @param string $a_cmd + * @param string $a_type + * @param int $a_ref_id + * @throws ilObjectException + * @return bool + */ + protected function checkPermission($a_perm, $a_cmd = "", $a_type = "", $a_ref_id = null) + { + if (!$this->checkPermissionBool($a_perm, $a_cmd, $a_type, $a_ref_id)) { + if (!is_int(strpos($_SERVER["PHP_SELF"], "goto.php"))) { + // create: redirect to parent + if ($a_perm == "create") { + if (!$a_ref_id) { + $a_ref_id = $_GET["ref_id"]; + } + $type = ilObject::_lookupType($a_ref_id, true); + } else { + // does this make sense? + if (!is_object($this->object)) { + return; + } + if (!$a_ref_id) { + $a_ref_id = $this->object->getRefId(); + } + $type = $this->object->getType(); + } + + ilSession::clear("il_rep_ref_id"); + + include_once "Services/Object/exceptions/class.ilObjectException.php"; + throw new ilObjectException($this->lng->txt("permission_denied")); + + /* + ilUtil::sendFailure($this->lng->txt("permission_denied"), true); + ilUtil::redirect("goto.php?target=".$type."_".$a_ref_id); + */ + } + // we should never be here + else { + die("Permission Denied."); + } + } + } + + /** + * Check permission + * + * @param string $a_perm + * @param string $a_cmd + * @param string $a_type + * @param int $a_ref_id + * @return bool + */ + protected function checkPermissionBool($a_perm, $a_cmd = "", $a_type = "", $a_ref_id = null) + { + $ilAccess = $this->access; + + if ($a_perm == "create") { + if (!$a_ref_id) { + $a_ref_id = $_GET["ref_id"]; + } + return $ilAccess->checkAccess($a_perm . "_" . $a_type, $a_cmd, $a_ref_id); + } else { + // does this make sense? + if (!is_object($this->object)) { + return false; + } + if (!$a_ref_id) { + $a_ref_id = $this->object->getRefId(); + } + return $ilAccess->checkAccess($a_perm, $a_cmd, $a_ref_id); + } + } + + /** + * Goto repository root + * + * @param + * @return + */ + public static function _gotoRepositoryRoot($a_raise_error = false) + { + global $DIC; + + $ilAccess = $DIC->access(); + $ilErr = $DIC["ilErr"]; + $lng = $DIC->language(); + + if ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) { + $_GET["cmd"] = "frameset"; + $_GET["target"] = ""; + $_GET["ref_id"] = ROOT_FOLDER_ID; + $_GET["baseClass"] = "ilRepositoryGUI"; + include("ilias.php"); + exit; + } + + if ($a_raise_error) { + $ilErr->raiseError($lng->txt("msg_no_perm_read"), $ilErr->FATAL); + } + } + + /** + * Goto repository root + * + * @param + * @return + */ + public static function _gotoRepositoryNode($a_ref_id, $a_cmd = "frameset") + { + global $DIC; + + $ilAccess = $DIC->access(); + $ilErr = $DIC["ilErr"]; + + $_GET["cmd"] = $a_cmd; + $_GET["target"] = ""; + $_GET["ref_id"] = $a_ref_id; + $_GET["baseClass"] = "ilRepositoryGUI"; + include("ilias.php"); + exit; + } + + /** + * Enables the file upload into this object by dropping files. + */ + protected function enableDragDropFileUpload() + { + include_once("./Services/FileUpload/classes/class.ilFileUploadGUI.php"); + ilFileUploadGUI::initFileUpload(); + + $this->tpl->enableDragDropFileUpload($this->ref_id); + } + + /** + * Activate rating automatically if parent container setting + * + * @param ilObject $a_new_obj + */ + protected function handleAutoRating(ilObject $a_new_obj) + { + if (ilObject::hasAutoRating($a_new_obj->getType(), $a_new_obj->getRefId()) && + method_exists($a_new_obj, "setRating")) { + $a_new_obj->setRating(true); + $a_new_obj->update(); + } + } + + /** + * show edit section of custom icons for container + * + */ + protected function showCustomIconsEditing($a_input_colspan = 1, ilPropertyFormGUI $a_form = null, $a_as_section = true) + { + if ($this->settings->get("custom_icons")) { + if ($a_form) { + global $DIC; + /** @var \ilObjectCustomIconFactory $customIconFactory */ + $customIconFactory = $DIC['object.customicons.factory']; + + $customIcon = $customIconFactory->getByObjId($this->object->getId(), $this->object->getType()); + + if ($a_as_section) { + $title = new ilFormSectionHeaderGUI(); + $title->setTitle($this->lng->txt("icon_settings")); + } else { + $title = new ilCustomInputGUI($this->lng->txt("icon_settings"), ""); + } + $a_form->addItem($title); + + $caption = $this->lng->txt("cont_custom_icon"); + $icon = new ilImageFileInputGUI($caption, "cont_icon"); + + $icon->setSuffixes($customIcon->getSupportedFileExtensions()); + $icon->setUseCache(false); + if ($customIcon->exists()) { + $icon->setImage($customIcon->getFullPath()); + } else { + $icon->setImage(''); + } + if ($a_as_section) { + $a_form->addItem($icon); + } else { + $title->addSubItem($icon); + } + } + } + } + + /** + * Redirect after creation, see https://docu.ilias.de/goto_docu_wiki_wpage_5035_1357.html + * + * Should be overwritten and redirect to settings screen. + */ + public function redirectAfterCreation() + { + $ctrl = $this->ctrl; + $link = ilLink::_getLink($this->object->getRefId()); + $ctrl->redirectToURL($link); + } } - -?> \ No newline at end of file diff --git a/Services/Object/classes/class.ilObjectGUIFactory.php b/Services/Object/classes/class.ilObjectGUIFactory.php index 595e5aa533a8919f86e089788b40636842af314d..4548e2b82ada2f0c47acad88a45d7a7104e880ed 100644 --- a/Services/Object/classes/class.ilObjectGUIFactory.php +++ b/Services/Object/classes/class.ilObjectGUIFactory.php @@ -15,84 +15,79 @@ */ class ilObjectGUIFactory { - /** - * @var ilObjectDefinition - */ - protected $obj_definition; + /** + * @var ilObjectDefinition + */ + protected $obj_definition; - /** - * @var ilDBInterface - */ - protected $db; + /** + * @var ilDBInterface + */ + protected $db; - /** - * Constructor - * @param ilObjectDefinition|null $obj_definition - * @param ilDBInterface|null $db - */ - public function __construct(ilObjectDefinition $obj_definition = null, ilDBInterface $db = null) - { - global $DIC; + /** + * Constructor + * @param ilObjectDefinition|null $obj_definition + * @param ilDBInterface|null $db + */ + public function __construct(ilObjectDefinition $obj_definition = null, ilDBInterface $db = null) + { + global $DIC; - if (is_null($obj_definition)) - { - $obj_definition = $DIC["objDefinition"]; - } - $this->obj_definition = $obj_definition; + if (is_null($obj_definition)) { + $obj_definition = $DIC["objDefinition"]; + } + $this->obj_definition = $obj_definition; - if (is_null($db)) - { - $db = $DIC->database(); - } - $this->db = $db; - } + if (is_null($db)) { + $db = $DIC->database(); + } + $this->db = $db; + } - /** - * Get ilObj...GUI instance by reference id - * - * @param $a_ref_id - * @return mixed - * @throws ilObjectException - * @throws ilObjectNotFoundException - */ - public function getInstanceByRefId($a_ref_id) - { - $obj_definition = $this->obj_definition; - $db = $this->db; + /** + * Get ilObj...GUI instance by reference id + * + * @param $a_ref_id + * @return mixed + * @throws ilObjectException + * @throws ilObjectNotFoundException + */ + public function getInstanceByRefId($a_ref_id) + { + $obj_definition = $this->obj_definition; + $db = $this->db; - // check reference id - if (!isset($a_ref_id)) - { - throw new ilObjectNotFoundException("ilObjectGUIFactory::getInstanceByRefId(): No ref_id given!"); - } + // check reference id + if (!isset($a_ref_id)) { + throw new ilObjectNotFoundException("ilObjectGUIFactory::getInstanceByRefId(): No ref_id given!"); + } - // check if object exists - $set = $db->queryF("SELECT * FROM object_data,object_reference ". - "WHERE object_reference.obj_id = object_data.obj_id ". - "AND object_reference.ref_id = %s ", - array("integer"), - array($a_ref_id) - ); - if (!($rec = $db->fetchAssoc($set))) - { - throw new ilObjectNotFoundException("ilObjectGUIFactory::getInstanceByRefId(): Object with ref_id ".$a_ref_id." not found!"); - } + // check if object exists + $set = $db->queryF( + "SELECT * FROM object_data,object_reference " . + "WHERE object_reference.obj_id = object_data.obj_id " . + "AND object_reference.ref_id = %s ", + array("integer"), + array($a_ref_id) + ); + if (!($rec = $db->fetchAssoc($set))) { + throw new ilObjectNotFoundException("ilObjectGUIFactory::getInstanceByRefId(): Object with ref_id " . $a_ref_id . " not found!"); + } - // check class name - $class_name = "ilObj".$obj_definition->getClassName($rec["type"])."GUI"; - if ($class_name == "ilObjGUI") - { - throw new ilObjectException("ilObjectGUIFactory::getInstanceByRefId(): Not able to determine object ". - "class for type".$rec["type"]."."); - } + // check class name + $class_name = "ilObj" . $obj_definition->getClassName($rec["type"]) . "GUI"; + if ($class_name == "ilObjGUI") { + throw new ilObjectException("ilObjectGUIFactory::getInstanceByRefId(): Not able to determine object " . + "class for type" . $rec["type"] . "."); + } - // create instance - $location = $obj_definition->getLocation($rec["type"]); - include_once($location."/class.".$class_name.".php"); - $gui_obj = new $class_name("", $a_ref_id, true, false); + // create instance + $location = $obj_definition->getLocation($rec["type"]); + include_once($location . "/class." . $class_name . ".php"); + $gui_obj = new $class_name("", $a_ref_id, true, false); - return $gui_obj; - } - -} \ No newline at end of file + return $gui_obj; + } +} diff --git a/Services/Object/classes/class.ilObjectImporter.php b/Services/Object/classes/class.ilObjectImporter.php index 50bfe3512266318db39626cceae8cf499468e972..333b6535faf20bda5ad6d4afd105d533989954d9 100644 --- a/Services/Object/classes/class.ilObjectImporter.php +++ b/Services/Object/classes/class.ilObjectImporter.php @@ -12,42 +12,44 @@ include_once("./Services/Export/classes/class.ilXmlImporter.php"); */ class ilObjectImporter extends ilXmlImporter { - private $logger = null; - - - /** - * Constructor - */ - public function __construct() - { - parent::__construct(); - $this->logger = $GLOBALS['DIC']->logger()->obj(); - } + private $logger = null; + + + /** + * Constructor + */ + public function __construct() + { + parent::__construct(); + $this->logger = $GLOBALS['DIC']->logger()->obj(); + } - /** - * Initialisation - */ - function init() - { - include_once("./Services/Object/classes/class.ilObjectDataSet.php"); - $this->ds = new ilObjectDataSet(); - $this->ds->setDSPrefix("ds"); + /** + * Initialisation + */ + public function init() + { + include_once("./Services/Object/classes/class.ilObjectDataSet.php"); + $this->ds = new ilObjectDataSet(); + $this->ds->setDSPrefix("ds"); $this->ds->setImportDirectory($this->getImportDirectory()); - } + } - /** - * Import XML - * - * @param - */ - function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) - { - include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); - $parser = new ilDataSetImportParser($a_entity, $this->getSchemaVersion(), - $a_xml, $this->ds, $a_mapping); - } - + /** + * Import XML + * + * @param + */ + public function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) + { + include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); + $parser = new ilDataSetImportParser( + $a_entity, + $this->getSchemaVersion(), + $a_xml, + $this->ds, + $a_mapping + ); + } } - -?> \ No newline at end of file diff --git a/Services/Object/classes/class.ilObjectLP.php b/Services/Object/classes/class.ilObjectLP.php index 236e0a0954d3b69be236760cbf89b1d23a97e473..37dbc60a4083259c431f5cf94d3d9cc7ba77843e 100644 --- a/Services/Object/classes/class.ilObjectLP.php +++ b/Services/Object/classes/class.ilObjectLP.php @@ -1,796 +1,727 @@ - - * @version $Id: class.ilLPStatusPlugin.php 43734 2013-07-29 15:27:58Z jluetzen $ - * @package ServicesTracking - */ -class ilObjectLP -{ - /** - * @var ilTree - */ - protected $tree; - - /** - * @var ilDB - */ - protected $db; - - protected $obj_id; // [int] - protected $collection_instance; // [ilLPCollection] - protected $mode; // [int] - - protected static $type_defaults; // [array] - - protected function __construct($a_obj_id) - { - global $DIC; - - $this->tree = $DIC->repositoryTree(); - $this->db = $DIC->database(); - $this->obj_id = (int)$a_obj_id; - } - - public static function getInstance($a_obj_id) - { - static $instances = array(); - - if(!isset($instances[$a_obj_id])) - { - $type = ilObject::_lookupType($a_obj_id); - $class = self::getTypeClass($type); - if($class) - { - $instance = new $class($a_obj_id); - } - else - { - // :TODO: should we return anything? - $instance = new self($a_obj_id); - } - $instances[$a_obj_id] = $instance; - } - - return $instances[$a_obj_id]; - } - - public static function getTypeClass($a_type) - { - global $DIC; - - $objDefinition = $DIC["objDefinition"]; - - if(self::isSupportedObjectType($a_type)) - { - switch($a_type) - { - // container - - case "crs": - include_once "Modules/Course/classes/class.ilCourseLP.php"; - return "ilCourseLP"; - - case "grp": - include_once "Modules/Group/classes/class.ilGroupLP.php"; - return "ilGroupLP"; - - case "fold": - include_once "Modules/Folder/classes/class.ilFolderLP.php"; - return "ilFolderLP"; - - case "lso": - include_once "Modules/LearningSequence/classes/LearnerProgress/class.ilLSLP.php"; - return "ilLSLP"; - - - // learning resources - - case "lm": - include_once "Modules/LearningModule/classes/class.ilLearningModuleLP.php"; - return "ilLearningModuleLP"; - - case "htlm": - include_once "Modules/HTMLLearningModule/classes/class.ilHTMLLearningModuleLP.php"; - return "ilHTMLLearningModuleLP"; - - case "sahs": - include_once "Modules/ScormAicc/classes/class.ilScormLP.php"; - return "ilScormLP"; - - - // misc - - case "tst": - include_once "Modules/Test/classes/class.ilTestLP.php"; - return "ilTestLP"; - - case "exc": - include_once "Modules/Exercise/classes/class.ilExerciseLP.php"; - return "ilExerciseLP"; - - case 'file': - require_once 'Modules/File/classes/class.ilFileLP.php'; - return 'ilFileLP'; - - case "mcst": - require_once "Modules/MediaCast/classes/class.ilMediaCastLP.php"; - return "ilMediaCastLP"; - - case "sess": - include_once "Modules/Session/classes/class.ilSessionLP.php"; - return "ilSessionLP"; - - case "svy": - include_once "Modules/Survey/classes/class.ilSurveyLP.php"; - return "ilSurveyLP"; - - case "prg": - include_once "Modules/StudyProgramme/classes/class.ilStudyProgrammeLP.php"; - return "ilStudyProgrammeLP"; - - case "iass": - include_once "Modules/IndividualAssessment/classes/class.ilIndividualAssessmentLP.php"; - return "ilIndividualAssessmentLP"; - - case "copa": - return "ilContentPageLP"; - - // plugin - case $objDefinition->isPluginTypeName($a_type): - include_once "Services/Component/classes/class.ilPluginLP.php"; - return "ilPluginLP"; - } - } - } - public static function isSupportedObjectType($a_type) - { - global $DIC; - - $objDefinition = $DIC["objDefinition"]; - - $valid = array("crs", "grp", "fold", "lm", "htlm", "sahs", "tst", "exc", - "sess", "svy", "file", "mcst", "prg", "iass", "copa", "lso"); - - if(in_array($a_type, $valid)) - { - return true; - } - - if($objDefinition->isPluginTypeName($a_type)) - { - include_once 'Services/Repository/classes/class.ilRepositoryObjectPluginSlot.php'; - return ilRepositoryObjectPluginSlot::isTypePluginWithLP($a_type); - } - - return false; - } - - public function resetCaches() - { - $this->mode = null; - $this->collection_instance = null; - } - - public function isAnonymized() - { - // see ilLPCollectionOfRepositoryObjects::validateEntry() - return false; - } - - - // - // MODE - // - - public function getDefaultMode() - { - - return ilLPObjSettings::LP_MODE_UNDEFINED; - } - - public function getValidModes() - { - return array(); - } - - public function getCurrentMode() - { - if($this->mode === null) - { - // using global type default if LP is inactive - include_once "Services/Tracking/classes/class.ilObjUserTracking.php"; - if(!ilObjUserTracking::_enabledLearningProgress()) - { - $mode = self::getTypeDefaultFromDB(ilObject::_lookupType($this->obj_id)); - if($mode === null) - { - // fallback: inactive as type default may not be suitable - $mode = ilLPObjSettings::LP_MODE_DEACTIVATED; - } - } - // use object LP setting - else - { - $mode = ilLPObjSettings::_lookupDBMode($this->obj_id); - if($mode === null) - { - // fallback: object type default - $mode = $this->getDefaultMode(); - } - } - $this->mode = (int)$mode; - } - - return $this->mode; - } - - public function isActive() - { - // :TODO: check LP activation? - - $mode = $this->getCurrentMode(); - if($mode == ilLPObjSettings::LP_MODE_DEACTIVATED || - $mode == ilLPObjSettings::LP_MODE_UNDEFINED) - { - return false; - } - return true; - } - - public function getModeText($a_mode) - { - return ilLPObjSettings::_mode2Text($a_mode); - } - - public function getModeInfoText($a_mode) - { - return ilLPObjSettings::_mode2InfoText($a_mode); - } - - public function getSettingsInfo() - { - // type-specific - } - - - // - // COLLECTION - // - - public function getCollectionInstance() - { - if($this->collection_instance === null) - { - include_once "Services/Tracking/classes/collection/class.ilLPCollection.php"; - $this->collection_instance = ilLPCollection::getInstanceByMode($this->obj_id, $this->getCurrentMode()); - } - - return $this->collection_instance; - } - - - // - // MEMBERS - // - - public function getMembers($a_search = true) - { - $tree = $this->tree; - - if(!$a_search) - { - return; - } - - $ref_ids = ilObject::_getAllReferences($this->obj_id); - $ref_id = current($ref_ids); - - // walk path to find parent with specific members - $path = $tree->getPathId($ref_id); - array_pop($path); - foreach(array_reverse($path) as $path_ref_id) - { - $olp = self::getInstance(ilObject::_lookupObjId($path_ref_id)); - $all = $olp->getMembers(false); - if(is_array($all)) - { - return $all; - } - } - } - - - // - // RESET - // - - final public function resetLPDataForCompleteObject($a_recursive = true) - { - $user_ids = $this->gatherLPUsers(); - if(sizeof($user_ids)) - { - $this->resetLPDataForUserIds(array_unique($user_ids), $a_recursive); - } - } - - final public function resetLPDataForUserIds(array $a_user_ids, $a_recursive = true) - { - if((bool)$a_recursive && - method_exists($this, "getPossibleCollectionItems")) // #15203 - { - $subitems = $this->getPossibleCollectionItems(); - if(is_array($subitems)) - { - foreach($subitems as $sub_ref_id) - { - $olp = self::getInstance(ilObject::_lookupObjId($sub_ref_id)); - $olp->resetLPDataForUserIds($a_user_ids, false); - } - } - } - - $this->resetCustomLPDataForUserIds($a_user_ids, (bool)$a_recursive); - - include_once "Services/Tracking/classes/class.ilLPMarks.php"; - ilLPMarks::_deleteForUsers($this->obj_id, $a_user_ids); - - include_once "Services/Tracking/classes/class.ilChangeEvent.php"; - ilChangeEvent::_deleteReadEventsForUsers($this->obj_id, $a_user_ids); - - // update LP status to get collections up-to-date - include_once "Services/Tracking/classes/class.ilLPStatusWrapper.php"; - foreach($a_user_ids as $user_id) - { - ilLPStatusWrapper::_updateStatus($this->obj_id, $user_id); - } - } - - protected function resetCustomLPDataForUserIds(array $a_user_ids, $a_recursive = true) - { - // this should delete all data that is relevant for the supported LP modes - } - - protected function gatherLPUsers() - { - include_once "Services/Tracking/classes/class.ilLPMarks.php"; - $user_ids = ilLPMarks::_getAllUserIds($this->obj_id); - - include_once "Services/Tracking/classes/class.ilChangeEvent.php"; - $user_ids = array_merge($user_ids, ilChangeEvent::_getAllUserIds($this->obj_id)); - - return $user_ids; - } - - - // - // EVENTS - // - - final static public function handleMove($a_source_ref_id) - { - global $DIC; - - $tree = $DIC->repositoryTree(); - $ilDB = $DIC->database(); - - $ref_ids = $tree->getSubTreeIds($a_source_ref_id); - $ref_ids[] = $a_source_ref_id; - - // get "parent" path to source node (not including source node) - $new_path = $tree->getPathId($a_source_ref_id); - array_pop($new_path); - $new_path = implode("/", $new_path); - - include_once("./Services/Tracking/classes/class.ilLPStatusWrapper.php"); - - // find collections with ref_ids - $set = $ilDB->query("SELECT DISTINCT(ut_lp_collections.obj_id) obj_id". - " FROM object_reference". - " JOIN ut_lp_collections ON". - " (".$ilDB->in("object_reference.ref_id", $ref_ids, "", "integer"). - " AND object_reference.ref_id = ut_lp_collections.item_id)"); - while ($rec = $ilDB->fetchAssoc($set)) - { - if (in_array(ilObject::_lookupType($rec["obj_id"]), array("crs", "grp", "fold"))) - { - $coll_ref_id = ilObject::_getAllReferences($rec["obj_id"]); - $coll_ref_id = array_pop($coll_ref_id); - - // #13402 - if($coll_ref_id == $a_source_ref_id) - { - continue; - } - - // #17703 - collection has also been moved - nothing todo - if($tree->isGrandChild($a_source_ref_id, $coll_ref_id)) - { - continue; - } - - // get path to collection (including collection "parent") - $coll_path = $tree->getPathId($coll_ref_id); - $coll_path = implode("/", $coll_path); - - // collection path is not inside new path - if(!stristr($new_path, $coll_path)) - { - // delete all items of moved (sub-)tree - $query = "DELETE FROM ut_lp_collections". - " WHERE obj_id = ".$ilDB->quote($rec["obj_id"], "integer"). - " AND ".$ilDB->in("item_id", $ref_ids, "", "integer"); - $ilDB->manipulate($query); - - ilLPStatusWrapper::_refreshStatus($rec["obj_id"]); - } - } - } - } - - final public function handleToTrash() - { - $this->updateParentCollections(); - } - - final public function handleDelete() - { - include_once "Services/Tracking/classes/class.ilLPMarks.php"; - ilLPMarks::deleteObject($this->obj_id); - - include_once "Services/Tracking/classes/class.ilChangeEvent.php"; - ilChangeEvent::_delete($this->obj_id); - - $collection = $this->getCollectionInstance(); - if($collection) - { - $collection->delete(); - } - - $this->updateParentCollections(); - } - - final protected function updateParentCollections() - { - $ilDB = $this->db; - - include_once("./Services/Tracking/classes/class.ilLPStatusWrapper.php"); - - // update parent collections? - $set = $ilDB->query("SELECT ut_lp_collections.obj_id obj_id FROM ". - "object_reference JOIN ut_lp_collections ON ". - "(object_reference.obj_id = ".$ilDB->quote($this->obj_id, "integer"). - " AND object_reference.ref_id = ut_lp_collections.item_id)"); - while ($rec = $ilDB->fetchAssoc($set)) - { - if (in_array(ilObject::_lookupType($rec["obj_id"]), array("crs", "grp", "fold"))) - { - // remove from parent collection - $query = "DELETE FROM ut_lp_collections". - " WHERE obj_id = ".$ilDB->quote($rec["obj_id"], "integer"). - " AND item_id = ".$ilDB->quote($this->obj_id, "integer"); - $ilDB->manipulate($query); - - ilLPStatusWrapper::_refreshStatus($rec["obj_id"]); - } - } - } - - - // - // LP-relevant memberships - // - - /** - * Find (lp-relevant) members for given object ids - * - * @param array $a_res - * @param int $a_usr_id - * @param array $a_obj_ids - */ - protected static function isLPMember(array &$a_res, $a_usr_id, $a_obj_ids) - { - // should be overwritten by object-type-specific class - return false; - } - - /** - * Find (lp-relevant) memberships by path - * - * @param array $a_res - * @param int $a_usr_id - * @param int $a_parent_ref_id - * @param array $a_obj_ids - * @param bool $a_mapped_ref_ids - * @return array - */ - protected static function findMembershipsByPath(array &$a_res, $a_usr_id, $a_parent_ref_id, array $a_obj_ids, $a_mapped_ref_ids = false) - { - global $DIC; - - $tree = $DIC->repositoryTree(); - - $found = array(); - - // walk path to find course or group object and check members of that object - $path = $tree->getPathId($a_parent_ref_id); - foreach(array_reverse($path) as $path_ref_id) - { - $type = ilObject::_lookupType($path_ref_id, true); - if($type == "crs" || - $type == "grp") - { - $class = self::getTypeClass($type); - $path_ob_id = ilObject::_lookupObjId($path_ref_id); - $chk = array(); - $class::isLPMember($chk, $a_usr_id, array($path_ob_id)); - if(!$a_mapped_ref_ids) - { - // we found a grp/crs in path of (single) parent - mark all objects - foreach($a_obj_ids as $obj_id) - { - $found[] = $obj_id; - if($chk[$path_ob_id]) - { - $a_res[$obj_id] = true; - } - } - } - else - { - // all children from current node are "lp-valid" - foreach($a_obj_ids as $obj_id => $ref_ids) - { - foreach($ref_ids as $ref_id) - { - if($tree->isGrandChild($path_ref_id, $ref_id)) - { - $found[$obj_id][] = $ref_id; - if($chk[$path_ob_id]) - { - $a_res[$obj_id] = true; - } - break; - } - } - } - } - break; - } - } - - return $found; - } - - /** - * Get all objects where given user is member (from LP POV) - * - * @param int $a_usr_id - * @param array $a_obj_ids - * @param int $a_parent_ref_id - * @param bool $a_mapped_ref_ids - * @return array - */ - public static function getLPMemberships($a_usr_id, array $a_obj_ids, $a_parent_ref_id = null, $a_mapped_ref_ids = false) - { - global $DIC; - - $ilDB = $DIC->database(); - $tree = $DIC->repositoryTree(); - - // see ilTrQuery::getParticipantsForObject() [single object only] - // this is optimized for larger number of objects, e.g. list GUIs - - $ref_map = []; - if((bool)$a_mapped_ref_ids) - { - $ref_map = $a_obj_ids; - $a_obj_ids = array_keys($a_obj_ids); - } - - $res = array(); - - // get object types - $types_map = array(); - $query = " SELECT obj_id, type". - " FROM object_data". - " WHERE ".$ilDB->in("obj_id", $a_obj_ids, "", "integer"); - $set = $ilDB->query($query); - while($row = $ilDB->fetchAssoc($set)) - { - $types_map[$row["type"]][] = $row["obj_id"]; - $res[$row["obj_id"]] = false; - } - - $find_by_parent = array(); - foreach($types_map as $type => $type_obj_ids) - { - $class = self::getTypeClass($type); - if($class) - { - // lp-supported type? - if(!$class::isLPMember($res, $a_usr_id, $type_obj_ids)) - { - $find_by_parent = array_merge($find_by_parent, $type_obj_ids); - } - } - } - - if(sizeof($find_by_parent)) - { - // single parent for all objects (repository/ilObjectListGUI) - if($a_parent_ref_id) - { - if(self::findMembershipsByPath($res, $a_usr_id, $a_parent_ref_id, $find_by_parent)) - { - // we found a crs/grp in path, so no need to check read_events - $find_by_parent = null; - } - } - // different parents (PD > LP) - else if(is_array($ref_map) && count($ref_map) > 0) - { - foreach($find_by_parent as $obj_id) - { - // maybe already found by path search from other object/reference - if($res[$obj_id] === false) - { - if(isset($ref_map[$obj_id]) && is_array($ref_map[$obj_id])) - { - // check all references - foreach($ref_map[$obj_id] as $ref_id) - { - $parent_ref_id = $tree->getParentId($ref_id); - if($parent_ref_id == ROOT_FOLDER_ID) - { - continue; - } - - // we are checking the complete ref_map - // to find all relevant objects in subtree of current ref_id - $found = self::findMembershipsByPath($res, $a_usr_id, $parent_ref_id, $ref_map, true); - if(is_array($found) && count($found) > 0) - { - // if any references were found in a crs/grp-subtree - // remove from "read-event"-last-resort-pool - foreach($found as $found_obj_id => $found_ref_ids) - { - $diff = array_diff($ref_map[$found_obj_id], $found_ref_ids); - if($diff) - { - // 1-n refs are in another subtree - // have to be checked separately - $ref_map[$found_obj_id] = $diff; - } - else - { - // all references found in subtree - // no need to check again - unset($ref_map[$found_obj_id]); - } - } - break; - } - } - } - } - } - - $find_by_parent = array_keys($ref_map); - } - - // last resort: use read_event? - if (is_array($find_by_parent) && count($find_by_parent) > 0) { - $set = $ilDB->query("SELECT obj_id". - " FROM read_event". - " WHERE ".$ilDB->in("obj_id", $find_by_parent, "", "integer"). - " AND usr_id = ".$ilDB->quote($a_usr_id, "integer")); - while($row = $ilDB->fetchAssoc($set)) - { - $res[$row["obj_id"]] = true; - } - } - } - - return $res; - } - - public function getMailTemplateId() - { - // type-specific - } - - - // - // type-specific support of features (should be enhanced) - // - - public static function supportsSpentSeconds($a_obj_type) - { - return !in_array($a_obj_type, array("exc", "file", "mcst", "mob", "htlm", "copa")); - } - - public static function supportsMark($a_obj_type) - { - return !in_array($a_obj_type, array("lm", "dbk")); - } - - public static function supportsMatrixView($a_obj_type) - { - return !in_array($a_obj_type, array('svy', 'tst', 'htlm', 'exc', 'sess', 'file', 'prg', 'copa')); - } - - - // type-wide default - - /** - * Get available type-specific default modes (no administration needed) - * @param bool $a_lp_active - * @return array - */ - public static function getDefaultModes($a_lp_active) - { - return array(ilLPObjSettings::LP_MODE_UNDEFINED); - } - - protected static function getTypeDefaultFromDB($a_type) - { - global $DIC; - - $ilDB = $DIC->database(); - - if(!is_array(self::$type_defaults)) - { - self::$type_defaults = array(); - $set = $ilDB->query("SELECT * FROM ut_lp_defaults"); - while($row = $ilDB->fetchAssoc($set)) - { - self::$type_defaults[$row["type_id"]] = $row["lp_mode"]; - } - } - return self::$type_defaults[$a_type]; - } - - public static function saveTypeDefaults(array $a_data) - { - global $DIC; - - $ilDB = $DIC->database(); - - $ilDB->manipulate("DELETE FROM ut_lp_defaults"); - foreach($a_data as $type => $mode) - { - $ilDB->insert("ut_lp_defaults", array( - "type_id" => array("text", $type), - "lp_mode" => array("integer", $mode) - )); - } - } - - /** - * Get current type default - * - * @param string $a_type - * @return int - */ - public static function getTypeDefault($a_type) - { - $db = self::getTypeDefaultFromDB($a_type); - if($db !== null) - { - return $db; - } - - $class = self::getTypeClass($a_type); - $olp = new $class(0); - return $olp->getDefaultMode(); - } -} - -?> \ No newline at end of file + + * @version $Id: class.ilLPStatusPlugin.php 43734 2013-07-29 15:27:58Z jluetzen $ + * @package ServicesTracking + */ +class ilObjectLP +{ + /** + * @var ilTree + */ + protected $tree; + + /** + * @var ilDB + */ + protected $db; + + protected $obj_id; // [int] + protected $collection_instance; // [ilLPCollection] + protected $mode; // [int] + + protected static $type_defaults; // [array] + + protected function __construct($a_obj_id) + { + global $DIC; + + $this->tree = $DIC->repositoryTree(); + $this->db = $DIC->database(); + $this->obj_id = (int) $a_obj_id; + } + + public static function getInstance($a_obj_id) + { + static $instances = array(); + + if (!isset($instances[$a_obj_id])) { + $type = ilObject::_lookupType($a_obj_id); + $class = self::getTypeClass($type); + if ($class) { + $instance = new $class($a_obj_id); + } else { + // :TODO: should we return anything? + $instance = new self($a_obj_id); + } + $instances[$a_obj_id] = $instance; + } + + return $instances[$a_obj_id]; + } + + public static function getTypeClass($a_type) + { + global $DIC; + + $objDefinition = $DIC["objDefinition"]; + + if (self::isSupportedObjectType($a_type)) { + switch ($a_type) { + // container + + case "crs": + include_once "Modules/Course/classes/class.ilCourseLP.php"; + return "ilCourseLP"; + + case "grp": + include_once "Modules/Group/classes/class.ilGroupLP.php"; + return "ilGroupLP"; + + case "fold": + include_once "Modules/Folder/classes/class.ilFolderLP.php"; + return "ilFolderLP"; + + case "lso": + include_once "Modules/LearningSequence/classes/LearnerProgress/class.ilLSLP.php"; + return "ilLSLP"; + + + // learning resources + + case "lm": + include_once "Modules/LearningModule/classes/class.ilLearningModuleLP.php"; + return "ilLearningModuleLP"; + + case "htlm": + include_once "Modules/HTMLLearningModule/classes/class.ilHTMLLearningModuleLP.php"; + return "ilHTMLLearningModuleLP"; + + case "sahs": + include_once "Modules/ScormAicc/classes/class.ilScormLP.php"; + return "ilScormLP"; + + + // misc + + case "tst": + include_once "Modules/Test/classes/class.ilTestLP.php"; + return "ilTestLP"; + + case "exc": + include_once "Modules/Exercise/classes/class.ilExerciseLP.php"; + return "ilExerciseLP"; + + case 'file': + require_once 'Modules/File/classes/class.ilFileLP.php'; + return 'ilFileLP'; + + case "mcst": + require_once "Modules/MediaCast/classes/class.ilMediaCastLP.php"; + return "ilMediaCastLP"; + + case "sess": + include_once "Modules/Session/classes/class.ilSessionLP.php"; + return "ilSessionLP"; + + case "svy": + include_once "Modules/Survey/classes/class.ilSurveyLP.php"; + return "ilSurveyLP"; + + case "prg": + include_once "Modules/StudyProgramme/classes/class.ilStudyProgrammeLP.php"; + return "ilStudyProgrammeLP"; + + case "iass": + include_once "Modules/IndividualAssessment/classes/class.ilIndividualAssessmentLP.php"; + return "ilIndividualAssessmentLP"; + + case "copa": + return "ilContentPageLP"; + + // plugin + case $objDefinition->isPluginTypeName($a_type): + include_once "Services/Component/classes/class.ilPluginLP.php"; + return "ilPluginLP"; + } + } + } + public static function isSupportedObjectType($a_type) + { + global $DIC; + + $objDefinition = $DIC["objDefinition"]; + + $valid = array("crs", "grp", "fold", "lm", "htlm", "sahs", "tst", "exc", + "sess", "svy", "file", "mcst", "prg", "iass", "copa", "lso"); + + if (in_array($a_type, $valid)) { + return true; + } + + if ($objDefinition->isPluginTypeName($a_type)) { + include_once 'Services/Repository/classes/class.ilRepositoryObjectPluginSlot.php'; + return ilRepositoryObjectPluginSlot::isTypePluginWithLP($a_type); + } + + return false; + } + + public function resetCaches() + { + $this->mode = null; + $this->collection_instance = null; + } + + public function isAnonymized() + { + // see ilLPCollectionOfRepositoryObjects::validateEntry() + return false; + } + + + // + // MODE + // + + public function getDefaultMode() + { + return ilLPObjSettings::LP_MODE_UNDEFINED; + } + + public function getValidModes() + { + return array(); + } + + public function getCurrentMode() + { + if ($this->mode === null) { + // using global type default if LP is inactive + include_once "Services/Tracking/classes/class.ilObjUserTracking.php"; + if (!ilObjUserTracking::_enabledLearningProgress()) { + $mode = self::getTypeDefaultFromDB(ilObject::_lookupType($this->obj_id)); + if ($mode === null) { + // fallback: inactive as type default may not be suitable + $mode = ilLPObjSettings::LP_MODE_DEACTIVATED; + } + } + // use object LP setting + else { + $mode = ilLPObjSettings::_lookupDBMode($this->obj_id); + if ($mode === null) { + // fallback: object type default + $mode = $this->getDefaultMode(); + } + } + $this->mode = (int) $mode; + } + + return $this->mode; + } + + public function isActive() + { + // :TODO: check LP activation? + + $mode = $this->getCurrentMode(); + if ($mode == ilLPObjSettings::LP_MODE_DEACTIVATED || + $mode == ilLPObjSettings::LP_MODE_UNDEFINED) { + return false; + } + return true; + } + + public function getModeText($a_mode) + { + return ilLPObjSettings::_mode2Text($a_mode); + } + + public function getModeInfoText($a_mode) + { + return ilLPObjSettings::_mode2InfoText($a_mode); + } + + public function getSettingsInfo() + { + // type-specific + } + + + // + // COLLECTION + // + + public function getCollectionInstance() + { + if ($this->collection_instance === null) { + include_once "Services/Tracking/classes/collection/class.ilLPCollection.php"; + $this->collection_instance = ilLPCollection::getInstanceByMode($this->obj_id, $this->getCurrentMode()); + } + + return $this->collection_instance; + } + + + // + // MEMBERS + // + + public function getMembers($a_search = true) + { + $tree = $this->tree; + + if (!$a_search) { + return; + } + + $ref_ids = ilObject::_getAllReferences($this->obj_id); + $ref_id = current($ref_ids); + + // walk path to find parent with specific members + $path = $tree->getPathId($ref_id); + array_pop($path); + foreach (array_reverse($path) as $path_ref_id) { + $olp = self::getInstance(ilObject::_lookupObjId($path_ref_id)); + $all = $olp->getMembers(false); + if (is_array($all)) { + return $all; + } + } + } + + + // + // RESET + // + + final public function resetLPDataForCompleteObject($a_recursive = true) + { + $user_ids = $this->gatherLPUsers(); + if (sizeof($user_ids)) { + $this->resetLPDataForUserIds(array_unique($user_ids), $a_recursive); + } + } + + final public function resetLPDataForUserIds(array $a_user_ids, $a_recursive = true) + { + if ((bool) $a_recursive && + method_exists($this, "getPossibleCollectionItems")) { // #15203 + $subitems = $this->getPossibleCollectionItems(); + if (is_array($subitems)) { + foreach ($subitems as $sub_ref_id) { + $olp = self::getInstance(ilObject::_lookupObjId($sub_ref_id)); + $olp->resetLPDataForUserIds($a_user_ids, false); + } + } + } + + $this->resetCustomLPDataForUserIds($a_user_ids, (bool) $a_recursive); + + include_once "Services/Tracking/classes/class.ilLPMarks.php"; + ilLPMarks::_deleteForUsers($this->obj_id, $a_user_ids); + + include_once "Services/Tracking/classes/class.ilChangeEvent.php"; + ilChangeEvent::_deleteReadEventsForUsers($this->obj_id, $a_user_ids); + + // update LP status to get collections up-to-date + include_once "Services/Tracking/classes/class.ilLPStatusWrapper.php"; + foreach ($a_user_ids as $user_id) { + ilLPStatusWrapper::_updateStatus($this->obj_id, $user_id); + } + } + + protected function resetCustomLPDataForUserIds(array $a_user_ids, $a_recursive = true) + { + // this should delete all data that is relevant for the supported LP modes + } + + protected function gatherLPUsers() + { + include_once "Services/Tracking/classes/class.ilLPMarks.php"; + $user_ids = ilLPMarks::_getAllUserIds($this->obj_id); + + include_once "Services/Tracking/classes/class.ilChangeEvent.php"; + $user_ids = array_merge($user_ids, ilChangeEvent::_getAllUserIds($this->obj_id)); + + return $user_ids; + } + + + // + // EVENTS + // + + final public static function handleMove($a_source_ref_id) + { + global $DIC; + + $tree = $DIC->repositoryTree(); + $ilDB = $DIC->database(); + + $ref_ids = $tree->getSubTreeIds($a_source_ref_id); + $ref_ids[] = $a_source_ref_id; + + // get "parent" path to source node (not including source node) + $new_path = $tree->getPathId($a_source_ref_id); + array_pop($new_path); + $new_path = implode("/", $new_path); + + include_once("./Services/Tracking/classes/class.ilLPStatusWrapper.php"); + + // find collections with ref_ids + $set = $ilDB->query("SELECT DISTINCT(ut_lp_collections.obj_id) obj_id" . + " FROM object_reference" . + " JOIN ut_lp_collections ON" . + " (" . $ilDB->in("object_reference.ref_id", $ref_ids, "", "integer") . + " AND object_reference.ref_id = ut_lp_collections.item_id)"); + while ($rec = $ilDB->fetchAssoc($set)) { + if (in_array(ilObject::_lookupType($rec["obj_id"]), array("crs", "grp", "fold"))) { + $coll_ref_id = ilObject::_getAllReferences($rec["obj_id"]); + $coll_ref_id = array_pop($coll_ref_id); + + // #13402 + if ($coll_ref_id == $a_source_ref_id) { + continue; + } + + // #17703 - collection has also been moved - nothing todo + if ($tree->isGrandChild($a_source_ref_id, $coll_ref_id)) { + continue; + } + + // get path to collection (including collection "parent") + $coll_path = $tree->getPathId($coll_ref_id); + $coll_path = implode("/", $coll_path); + + // collection path is not inside new path + if (!stristr($new_path, $coll_path)) { + // delete all items of moved (sub-)tree + $query = "DELETE FROM ut_lp_collections" . + " WHERE obj_id = " . $ilDB->quote($rec["obj_id"], "integer") . + " AND " . $ilDB->in("item_id", $ref_ids, "", "integer"); + $ilDB->manipulate($query); + + ilLPStatusWrapper::_refreshStatus($rec["obj_id"]); + } + } + } + } + + final public function handleToTrash() + { + $this->updateParentCollections(); + } + + final public function handleDelete() + { + include_once "Services/Tracking/classes/class.ilLPMarks.php"; + ilLPMarks::deleteObject($this->obj_id); + + include_once "Services/Tracking/classes/class.ilChangeEvent.php"; + ilChangeEvent::_delete($this->obj_id); + + $collection = $this->getCollectionInstance(); + if ($collection) { + $collection->delete(); + } + + $this->updateParentCollections(); + } + + final protected function updateParentCollections() + { + $ilDB = $this->db; + + include_once("./Services/Tracking/classes/class.ilLPStatusWrapper.php"); + + // update parent collections? + $set = $ilDB->query("SELECT ut_lp_collections.obj_id obj_id FROM " . + "object_reference JOIN ut_lp_collections ON " . + "(object_reference.obj_id = " . $ilDB->quote($this->obj_id, "integer") . + " AND object_reference.ref_id = ut_lp_collections.item_id)"); + while ($rec = $ilDB->fetchAssoc($set)) { + if (in_array(ilObject::_lookupType($rec["obj_id"]), array("crs", "grp", "fold"))) { + // remove from parent collection + $query = "DELETE FROM ut_lp_collections" . + " WHERE obj_id = " . $ilDB->quote($rec["obj_id"], "integer") . + " AND item_id = " . $ilDB->quote($this->obj_id, "integer"); + $ilDB->manipulate($query); + + ilLPStatusWrapper::_refreshStatus($rec["obj_id"]); + } + } + } + + + // + // LP-relevant memberships + // + + /** + * Find (lp-relevant) members for given object ids + * + * @param array $a_res + * @param int $a_usr_id + * @param array $a_obj_ids + */ + protected static function isLPMember(array &$a_res, $a_usr_id, $a_obj_ids) + { + // should be overwritten by object-type-specific class + return false; + } + + /** + * Find (lp-relevant) memberships by path + * + * @param array $a_res + * @param int $a_usr_id + * @param int $a_parent_ref_id + * @param array $a_obj_ids + * @param bool $a_mapped_ref_ids + * @return array + */ + protected static function findMembershipsByPath(array &$a_res, $a_usr_id, $a_parent_ref_id, array $a_obj_ids, $a_mapped_ref_ids = false) + { + global $DIC; + + $tree = $DIC->repositoryTree(); + + $found = array(); + + // walk path to find course or group object and check members of that object + $path = $tree->getPathId($a_parent_ref_id); + foreach (array_reverse($path) as $path_ref_id) { + $type = ilObject::_lookupType($path_ref_id, true); + if ($type == "crs" || + $type == "grp") { + $class = self::getTypeClass($type); + $path_ob_id = ilObject::_lookupObjId($path_ref_id); + $chk = array(); + $class::isLPMember($chk, $a_usr_id, array($path_ob_id)); + if (!$a_mapped_ref_ids) { + // we found a grp/crs in path of (single) parent - mark all objects + foreach ($a_obj_ids as $obj_id) { + $found[] = $obj_id; + if ($chk[$path_ob_id]) { + $a_res[$obj_id] = true; + } + } + } else { + // all children from current node are "lp-valid" + foreach ($a_obj_ids as $obj_id => $ref_ids) { + foreach ($ref_ids as $ref_id) { + if ($tree->isGrandChild($path_ref_id, $ref_id)) { + $found[$obj_id][] = $ref_id; + if ($chk[$path_ob_id]) { + $a_res[$obj_id] = true; + } + break; + } + } + } + } + break; + } + } + + return $found; + } + + /** + * Get all objects where given user is member (from LP POV) + * + * @param int $a_usr_id + * @param array $a_obj_ids + * @param int $a_parent_ref_id + * @param bool $a_mapped_ref_ids + * @return array + */ + public static function getLPMemberships($a_usr_id, array $a_obj_ids, $a_parent_ref_id = null, $a_mapped_ref_ids = false) + { + global $DIC; + + $ilDB = $DIC->database(); + $tree = $DIC->repositoryTree(); + + // see ilTrQuery::getParticipantsForObject() [single object only] + // this is optimized for larger number of objects, e.g. list GUIs + + $ref_map = []; + if ((bool) $a_mapped_ref_ids) { + $ref_map = $a_obj_ids; + $a_obj_ids = array_keys($a_obj_ids); + } + + $res = array(); + + // get object types + $types_map = array(); + $query = " SELECT obj_id, type" . + " FROM object_data" . + " WHERE " . $ilDB->in("obj_id", $a_obj_ids, "", "integer"); + $set = $ilDB->query($query); + while ($row = $ilDB->fetchAssoc($set)) { + $types_map[$row["type"]][] = $row["obj_id"]; + $res[$row["obj_id"]] = false; + } + + $find_by_parent = array(); + foreach ($types_map as $type => $type_obj_ids) { + $class = self::getTypeClass($type); + if ($class) { + // lp-supported type? + if (!$class::isLPMember($res, $a_usr_id, $type_obj_ids)) { + $find_by_parent = array_merge($find_by_parent, $type_obj_ids); + } + } + } + + if (sizeof($find_by_parent)) { + // single parent for all objects (repository/ilObjectListGUI) + if ($a_parent_ref_id) { + if (self::findMembershipsByPath($res, $a_usr_id, $a_parent_ref_id, $find_by_parent)) { + // we found a crs/grp in path, so no need to check read_events + $find_by_parent = null; + } + } + // different parents (PD > LP) + elseif (is_array($ref_map) && count($ref_map) > 0) { + foreach ($find_by_parent as $obj_id) { + // maybe already found by path search from other object/reference + if ($res[$obj_id] === false) { + if (isset($ref_map[$obj_id]) && is_array($ref_map[$obj_id])) { + // check all references + foreach ($ref_map[$obj_id] as $ref_id) { + $parent_ref_id = $tree->getParentId($ref_id); + if ($parent_ref_id == ROOT_FOLDER_ID) { + continue; + } + + // we are checking the complete ref_map + // to find all relevant objects in subtree of current ref_id + $found = self::findMembershipsByPath($res, $a_usr_id, $parent_ref_id, $ref_map, true); + if (is_array($found) && count($found) > 0) { + // if any references were found in a crs/grp-subtree + // remove from "read-event"-last-resort-pool + foreach ($found as $found_obj_id => $found_ref_ids) { + $diff = array_diff($ref_map[$found_obj_id], $found_ref_ids); + if ($diff) { + // 1-n refs are in another subtree + // have to be checked separately + $ref_map[$found_obj_id] = $diff; + } else { + // all references found in subtree + // no need to check again + unset($ref_map[$found_obj_id]); + } + } + break; + } + } + } + } + } + + $find_by_parent = array_keys($ref_map); + } + + // last resort: use read_event? + if (is_array($find_by_parent) && count($find_by_parent) > 0) { + $set = $ilDB->query("SELECT obj_id" . + " FROM read_event" . + " WHERE " . $ilDB->in("obj_id", $find_by_parent, "", "integer") . + " AND usr_id = " . $ilDB->quote($a_usr_id, "integer")); + while ($row = $ilDB->fetchAssoc($set)) { + $res[$row["obj_id"]] = true; + } + } + } + + return $res; + } + + public function getMailTemplateId() + { + // type-specific + } + + + // + // type-specific support of features (should be enhanced) + // + + public static function supportsSpentSeconds($a_obj_type) + { + return !in_array($a_obj_type, array("exc", "file", "mcst", "mob", "htlm", "copa")); + } + + public static function supportsMark($a_obj_type) + { + return !in_array($a_obj_type, array("lm", "dbk")); + } + + public static function supportsMatrixView($a_obj_type) + { + return !in_array($a_obj_type, array('svy', 'tst', 'htlm', 'exc', 'sess', 'file', 'prg', 'copa')); + } + + + // type-wide default + + /** + * Get available type-specific default modes (no administration needed) + * @param bool $a_lp_active + * @return array + */ + public static function getDefaultModes($a_lp_active) + { + return array(ilLPObjSettings::LP_MODE_UNDEFINED); + } + + protected static function getTypeDefaultFromDB($a_type) + { + global $DIC; + + $ilDB = $DIC->database(); + + if (!is_array(self::$type_defaults)) { + self::$type_defaults = array(); + $set = $ilDB->query("SELECT * FROM ut_lp_defaults"); + while ($row = $ilDB->fetchAssoc($set)) { + self::$type_defaults[$row["type_id"]] = $row["lp_mode"]; + } + } + return self::$type_defaults[$a_type]; + } + + public static function saveTypeDefaults(array $a_data) + { + global $DIC; + + $ilDB = $DIC->database(); + + $ilDB->manipulate("DELETE FROM ut_lp_defaults"); + foreach ($a_data as $type => $mode) { + $ilDB->insert("ut_lp_defaults", array( + "type_id" => array("text", $type), + "lp_mode" => array("integer", $mode) + )); + } + } + + /** + * Get current type default + * + * @param string $a_type + * @return int + */ + public static function getTypeDefault($a_type) + { + $db = self::getTypeDefaultFromDB($a_type); + if ($db !== null) { + return $db; + } + + $class = self::getTypeClass($a_type); + $olp = new $class(0); + return $olp->getDefaultMode(); + } +} diff --git a/Services/Object/classes/class.ilObjectListGUI.php b/Services/Object/classes/class.ilObjectListGUI.php index 644297faa74d64c1b517a71ee791db6dc2508948..6c0a194dd3e480fe51c4c81fda835a2763633a47 100644 --- a/Services/Object/classes/class.ilObjectListGUI.php +++ b/Services/Object/classes/class.ilObjectListGUI.php @@ -1,8 +1,8 @@ access = $DIC->access(); - $this->user = $DIC->user(); - $this->obj_definition = $DIC["objDefinition"]; - $this->tree = $DIC->repositoryTree(); - $this->settings = $DIC->settings(); - - $this->ui = $DIC->ui(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->mode = IL_LIST_FULL; - $this->path_enabled = false; - $this->context = $a_context; - - $this->enableComments(false); - $this->enableNotes(false); - $this->enableTags(false); - - // unique js-ids - $this->setParentRefId((int) $_REQUEST["ref_id"]); - -//echo "list"; - $this->init(); - - include_once('Services/LDAP/classes/class.ilLDAPRoleGroupMapping.php'); - $this->ldap_mapping = ilLDAPRoleGroupMapping::_getInstance(); - - $this->lng->loadLanguageModule("obj"); - } - - - /** - * set the container object (e.g categorygui) - * Used for link, delete ... commands - * - * this method should be overwritten by derived classes - */ - function setContainerObject($container_obj) - { - $this->container_obj = $container_obj; - } - - /** - * get container object - * - * @access public - * @param - * @return object container - */ - public function getContainerObject() - { - return $this->container_obj; - } - - - /** - * initialisation - * - * this method should be overwritten by derived classes - */ - function init() - { - // Create static links for default command (linked title) or not - $this->static_link_enabled = true; - $this->delete_enabled = true; - $this->cut_enabled = true; - $this->subscribe_enabled = true; - $this->link_enabled = false; - $this->copy_enabled = false; - $this->progress_enabled = false; - $this->notice_properties_enabled = true; - $this->info_screen_enabled = false; - $this->type = ""; // "cat", "course", ... - $this->gui_class_name = ""; // "ilobjcategorygui", "ilobjcoursegui", ... - - // general commands array, e.g. - include_once('./Services/Object/classes/class.ilObjectAccess.php'); - $this->commands = ilObjectAccess::_getCommands(); - } - - // Single get set methods - /** - * En/disable properties - * - * @param bool - * @return void - */ - function enableProperties($a_status) - { - $this->properties_enabled = $a_status; - - return; - } - /** - * - * - * @param bool - * @return bool - */ - function getPropertiesStatus() - { - return $this->properties_enabled; - } - /** - * En/disable preconditions - * - * @param bool - * @return void - */ - function enablePreconditions($a_status) - { - $this->preconditions_enabled = $a_status; - - return; - } - - function getNoticePropertiesStatus() - { - return $this->notice_properties_enabled; - } - - /** - * En/disable notices - * - * @param bool - * @return void - */ - function enableNoticeProperties($a_status) - { - $this->notice_properties_enabled = $a_status; - - return; - } - /** - * - * - * @param bool - * @return bool - */ - function getPreconditionsStatus() - { - return $this->preconditions_enabled; - } - /** - * En/disable description - * - * @param bool - * @return void - */ - function enableDescription($a_status) - { - $this->description_enabled = $a_status; - - return; - } - /** - * - * - * @param bool - * @return bool - */ - function getDescriptionStatus() - { - return $this->description_enabled; - } - - /** - * Show hide search result fragments - * - * @param bool - * @return bool - */ - function getSearchFragmentStatus() - { - return $this->search_fragment_enabled; - } - - /** - * En/disable description - * - * @param bool - * @return void - */ - function enableSearchFragments($a_status) - { - $this->search_fragment_enabled = $a_status; - - return; - } - - /** - * Enable linked path - * @param bool - * @return - */ - public function enableLinkedPath($a_status) - { - $this->path_linked = $a_status; - } - - /** - * enabled relevance - * @return - */ - public function enabledRelevance() - { - return $this->enabled_relevance; - } - - /** - * enable relevance - * @return - */ - public function enableRelevance($a_status) - { - $this->enabled_relevance = $a_status; - } - - /** - * set relevance - * @param int - * @return - */ - public function setRelevance($a_rel) - { - $this->relevance = $a_rel; - } - - /** - * get relevance - * @param - * @return - */ - public function getRelevance() - { - return $this->relevance; - } - - /** - * En/Dis-able icons - * - * @param boolean icons on/off - */ - function enableIcon($a_status) - { - $this->icons_enabled = $a_status; - } - - /** - * Are icons enabled? - * - * @return boolean icons enabled? - */ - function getIconStatus() - { - return $this->icons_enabled; - } - - /** - * En/Dis-able checkboxes - * - * @param boolean checkbox on/off - */ - function enableCheckbox($a_status) - { - $this->checkboxes_enabled = $a_status; - } - - /** - * Are checkboxes enabled? - * - * @return boolean icons enabled? - */ - function getCheckboxStatus() - { - return $this->checkboxes_enabled; - } - - /** - * En/Dis-able expand/collapse link - * - * @param boolean checkbox on/off - */ - function enableExpand($a_status) - { - $this->expand_enabled = $a_status; - } - - /** - * Is expand/collapse enabled - * - * @return boolean icons enabled? - */ - function getExpandStatus() - { - return $this->expand_enabled; - } - - function setExpanded($a_status) - { - $this->is_expanded = $a_status; - } - - function isExpanded() - { - return $this->is_expanded; - } - /** - * Set position input field - * - * @param string $a_field_index e.g. "[crs][34]" - * @param string $a_position_value e.g. "2.0" - */ - function setPositionInputField($a_field_index, $a_position_value) - { - $this->position_enabled = true; - $this->position_field_index = $a_field_index; - $this->position_value = $a_position_value; - } - - /** - * En/disable delete - * - * @param bool - * @return void - */ - function enableDelete($a_status) - { - $this->delete_enabled = $a_status; - - return; - } - /** - * - * - * @param bool - * @return bool - */ - function getDeleteStatus() - { - return $this->delete_enabled; - } - - /** - * En/disable cut - * - * @param bool - * @return void - */ - function enableCut($a_status) - { - $this->cut_enabled = $a_status; - - return; - } - /** - * - * @param bool - * @return bool - */ - function getCutStatus() - { - return $this->cut_enabled; - } - - /** - * En/disable copy - * - * @param bool - * @return void - */ - function enableCopy($a_status) - { - $this->copy_enabled = $a_status; - - return; - } - /** - * - * @param bool - * @return bool - */ - function getCopyStatus() - { - return $this->copy_enabled; - } - - /** - * En/disable subscribe - * - * @param bool - * @return void - */ - function enableSubscribe($a_status) - { - $this->subscribe_enabled = $a_status; - - return; - } - /** - * - * @param bool - * @return bool - */ - function getSubscribeStatus() - { - return $this->subscribe_enabled; - } - - /** - * En/disable link - * - * @param bool - * @return void - */ - function enableLink($a_status) - { - $this->link_enabled = $a_status; - - return; - } - /** - * - * @param bool - * @return bool - */ - function getLinkStatus() - { - return $this->link_enabled; - } - - /** - * En/disable path - * - * @param bool - * @param int - * @return void - */ - function enablePath($a_path, $a_start_node = null, \ilPathGUI $path_gui = null) - { - $this->path_enabled = $a_path; - $this->path_start_node = (int)$a_start_node; - $this->path_gui = $path_gui; - } - - /** - * - * @param bool - * @return bool - */ - function getPathStatus() - { - return $this->path_enabled; - } - - /** - * En/disable commands - * - * @param bool - * @return void - */ - function enableCommands($a_status, $a_std_only = false) - { - $this->commands_enabled = $a_status; - $this->std_cmd_only = $a_std_only; - } - /** - * - * @param bool - * @return bool - */ - function getCommandsStatus() - { - return $this->commands_enabled; - } - - /** - * En/disable path - * - * @param bool - * @return void - */ - function enableInfoScreen($a_info_screen) - { - $this->info_screen_enabled = $a_info_screen; - } - - /** - * Add HTML for subitem (used for sessions) - * - * @param string $a_html subitems HTML - */ - function addSubItemHTML($a_html) - { - $this->sub_item_html[] = $a_html; - } - - /** - * - * @param bool - * @return bool - */ - function getInfoScreenStatus() - { - return $this->info_screen_enabled; - } - - /** - * enable progress info - * - * @access public - * @param - * @return - */ - public function enableProgressInfo($a_status) - { - $this->progress_enabled = $a_status; - } - - /** - * get progress info status - * - * @access public - * @param - * @return - */ - public function getProgressInfoStatus() - { - return $this->progress_enabled; - } - - /** - * Enable substitutions - * - * @access public - * @param - * - */ - public function enableSubstitutions($a_status) - { - $this->substitutions_enabled = $a_status; - } - - /** - * Get substitution status - * - * @access public - * - */ - public function getSubstitutionStatus() - { - return $this->substitutions_enabled; - } - - /** - * enable item detail links - * E.g Direct links to chapters or pages - * - * @access public - * @param bool - * @return - */ - public function enableItemDetailLinks($a_status) - { - $this->item_detail_links_enabled = $a_status; - } - - /** - * get item detail link status - * - * @access public - * @return bool - */ - public function getItemDetailLinkStatus() - { - return $this->item_detail_links_enabled; - } - - /** - * set items detail links - * - * @access public - * @param array e.g. array(0 => array('desc' => 'Page: ','link' => 'ilias.php...','name' => 'Page XYZ') - * @return - */ - public function setItemDetailLinks($a_detail_links,$a_intro_txt = '') - { - $this->item_detail_links = $a_detail_links; - $this->item_detail_links_intro = $a_intro_txt; - } - - /** - * insert item detail links - * - * @access public - * @param - * @return - */ - public function insertItemDetailLinks() - { - if(!count($this->item_detail_links)) - { - return true; - } - if(strlen($this->item_detail_links_intro)) - { - $this->tpl->setCurrentBlock('item_detail_intro'); - $this->tpl->setVariable('ITEM_DETAIL_INTRO_TXT',$this->item_detail_links_intro); - $this->tpl->parseCurrentBlock(); - } - - foreach($this->item_detail_links as $info) - { - $this->tpl->setCurrentBlock('item_detail_link'); - $this->tpl->setVariable('ITEM_DETAIL_LINK_TARGET',$info['target']); - $this->tpl->setVariable('ITEM_DETAIL_LINK_DESC',$info['desc']); - $this->tpl->setVariable('ITEM_DETAIL_LINK_HREF',$info['link']); - $this->tpl->setVariable('ITEM_DETAIL_LINK_NAME',$info['name']); - $this->tpl->parseCurrentBlock(); - } - $this->tpl->setCurrentBlock('item_detail_links'); - $this->tpl->parseCurrentBlock(); - } - - - - /** - * @param string title - * @return bool - */ - function setTitle($a_title) - { - $this->title = $a_title; - } - - /** - * getTitle overwritten in class.ilObjLinkResourceList.php - * - * @return string title - */ - function getTitle() - { - return $this->title; - } - - /** - * @param string description - * @return bool - */ - function setDescription($a_description) - { - $this->description = $a_description; - } - - /** - * getDescription overwritten in class.ilObjLinkResourceList.php - * - * @return string description - */ - function getDescription() - { - return $this->description; - } - - /** - * set search fragment - * @param string $a_text highlighted search fragment - * @return - */ - public function setSearchFragment($a_text) - { - $this->search_fragment = $a_text; - } - - /** - * get search fragment - * @return - */ - public function getSearchFragment() - { - return $this->search_fragment; - } - - /** - * Set separate commands - * - * @param boolean separate commands - */ - function setSeparateCommands($a_val) - { - $this->separate_commands = $a_val; - } - - /** - * Get separate commands - * - * @return boolean separate commands - */ - function getSeparateCommands() - { - return $this->separate_commands; - } - /** - * get command id - * Normally the ref id. - * Overwritten for course and category references - * - * @access public - * @param - * @return - */ - public function getCommandId() - { - return $this->ref_id; - } - - /** - * Set additional information - * - * @param string additional information - */ - function setAdditionalInformation($a_val) - { - $this->additional_information = $a_val; - } - - /** - * Get additional information - * - * @return string additional information - */ - function getAdditionalInformation() - { - return $this->additional_information; - } - - /** - * Details level - * Currently used in Search which shows only limited properties of forums - * Currently used for Sessions (switch between minimal and extended view for each session) - * @param int $a_level - * @return - */ - public function setDetailsLevel($a_level) - { - $this->details_level = $a_level; - } - - /** - * Get current details level - * @return - */ - public function getDetailsLevel() - { - return $this->details_level; - } - - /** - * Enable copy/move to repository (from personal workspace) - * - * @param bool $a_value - */ - public function enableRepositoryTransfer($a_value) - { - $this->repository_transfer_enabled = (bool)$a_value; - } - - /** - * Restrict all actions/links to goto - * - * @param bool $a_value - */ - public function restrictToGoto($a_value) - { - $this->restrict_to_goto = (bool)$a_value; - } - - - /** - * Get default command - * - * @return array - */ - public function getDefaultCommand() - { - return $this->default_command; - } - - /** - * - * @param - * @return - */ - public function checkCommandAccess($a_permission,$a_cmd,$a_ref_id,$a_type,$a_obj_id="") - { - $ilAccess = $this->access; - - // e.g: subitems should not be readable since their parent sesssion is readonly. - if($a_permission != 'visible' and $this->isVisibleOnlyForced()) - { - return false; - } - - $cache_prefix = null; - if($this->context == self::CONTEXT_WORKSPACE || $this->context == self::CONTEXT_WORKSPACE_SHARING) - { - $cache_prefix = "wsp"; - if(!$this->ws_access) - { - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; - $this->ws_access = new ilWorkspaceAccessHandler(); - } - } - - if (isset($this->access_cache[$a_permission]["-".$a_cmd][$cache_prefix.$a_ref_id])) - { - return $this->access_cache[$a_permission]["-".$a_cmd][$cache_prefix.$a_ref_id]; - } - - if($this->context == self::CONTEXT_REPOSITORY) - { - $access = $ilAccess->checkAccess($a_permission,$a_cmd,$a_ref_id,$a_type,$a_obj_id); - if ($ilAccess->getPreventCachingLastResult()) - { - $this->prevent_access_caching = true; - } - } - else - { - $access = $this->ws_access->checkAccess($a_permission,$a_cmd,$a_ref_id,$a_type); - } - - $this->access_cache[$a_permission]["-".$a_cmd][$cache_prefix.$a_ref_id] = $access; - return $access; - } - - /** - * inititialize new item (is called by getItemHTML()) - * - * @param int $a_ref_id reference id - * @param int $a_obj_id object id - * @param string $a_title title - * @param string $a_description description - * @param int $a_context tree/workspace - */ - function initItem($a_ref_id, $a_obj_id, $a_title = "", $a_description = "") - { - $this->offline_mode = false; - if ($this->type == "sahs") { - include_once('Modules/ScormAicc/classes/class.ilObjSAHSLearningModuleAccess.php'); - $this->offline_mode = ilObjSAHSLearningModuleAccess::_lookupUserIsOfflineMode($a_obj_id); - } - $this->access_cache = array(); - $this->ref_id = $a_ref_id; - $this->obj_id = $a_obj_id; - $this->setTitle($a_title); - $this->setDescription($a_description); - #$this->description = $a_description; - - // checks, whether any admin commands are included in the output - $this->adm_commands_included = false; - $this->prevent_access_caching = false; - - } - - public function setConditionTarget($a_ref_id, $a_obj_id, $a_target_type) - { - $this->condition_target = array( - 'ref_id' => $a_ref_id, - 'obj_id' => $a_obj_id, - 'target_type' => $a_target_type - ); - } - - public function resetConditionTarget() - { - $this->condition_target = array(); - } - - public function disableTitleLink($a_status) - { - $this->title_link_disabled = $a_status; - } - // end-patch lok - - public function setDefaultCommandParameters(array $a_params) - { - $this->default_command_params = $a_params; - } - - /** - * Get default command link - * Overwritten for e.g categories,courses => they return a goto link - * If search engine visibility is enabled these object type return a goto_CLIENT_ID_cat_99.html link - * - * @access public - * @param int command link - * - */ - public function createDefaultCommand($command) - { - // begin-patch lok - if($this->static_link_enabled and !$this->default_command_params) - { - include_once('./Services/Link/classes/class.ilLink.php'); - if($link = ilLink::_getStaticLink($this->ref_id,$this->type,false)) - { - $command['link'] = $link; - $command['frame'] = '_top'; - } - } - if($this->default_command_params) - { - $params = array(); - foreach($this->default_command_params as $name => $value) - { - $params[] = $name.'='.$value; - } - $params = implode('&', $params); - - // #12370 - if(!stristr($command['link'], '?')) - { - $command['link'] .= '?'.$params; - } - else - { - $command['link'] .= '&'.$params; - } - } - return $command; - } - - /** - * Get command link url. - * - * Overwrite this method, if link target is not build by ctrl class - * (e.g. "forum.php"). This is the case - * for all links now, but bringing everything to ilCtrl should - * be realised in the future. - * - * @param string $a_cmd command - * - * @return string command link url - */ - function getCommandLink($a_cmd) - { - if($this->context == self::CONTEXT_REPOSITORY) - { - // BEGIN WebDAV Get mount webfolder link. - require_once ('Services/WebDAV/classes/class.ilDAVActivationChecker.php'); - if ($a_cmd == 'mount_webfolder' && ilDAVActivationChecker::_isActive()) - { - require_once ('Services/WebDAV/classes/class.ilWebDAVUtil.php'); - $dav_util = ilWebDAVUtil::getInstance(); - - // XXX: The following is a very dirty, ugly trick. - // To mount URI needs to be put into two attributes: - // href and folder. This hack returns both attributes - // like this: http://...mount_uri..." folder="http://...folder_uri... - return $dav_util->getMountURI($this->ref_id). - '" folder="'.$dav_util->getFolderURI($this->ref_id); - } - // END WebDAV Get mount webfolder link. - - $this->ctrl->setParameterByClass("ilrepositorygui", "ref_id", $this->getCommandId()); - $cmd_link = $this->ctrl->getLinkTargetByClass("ilrepositorygui", $a_cmd); - $this->ctrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - return $cmd_link; - - /* separate method for this line - $cmd_link = $this->ctrl->getLinkTargetByClass($this->gui_class_name, - $a_cmd); - return $cmd_link; - */ - } - else - { - $this->ctrl->setParameterByClass($this->gui_class_name, "ref_id", ""); - $this->ctrl->setParameterByClass($this->gui_class_name, "wsp_id", $this->ref_id); - return $this->ctrl->getLinkTargetByClass($this->gui_class_name, $a_cmd); - } - } - - - /** - * Get command target frame. - * - * Overwrite this method if link frame is not current frame - * - * @param string $a_cmd command - * - * @return string command target frame - */ - function getCommandFrame($a_cmd) - { - // BEGIN WebDAV Get mount webfolder link. - require_once ('Services/WebDAV/classes/class.ilDAVActivationChecker.php'); - if ($a_cmd == 'mount_webfolder' && ilDAVActivationChecker::_isActive()) - { - return '_blank'; - } - // begin-patch fm - if($a_cmd == 'fileManagerLaunch') - { - return '_blank'; - } - // end-patch fm - return ""; - } - - /** - * Get command icon image - * - * Overwrite this method if an icon is provided - * - * @param string $a_cmd command - * - * @return string image path - */ - function getCommandImage($a_cmd) - { - return ""; - } - - /** - * Get item properties - * - * Overwrite this method to add properties at - * the bottom of the item html - * - * @return array array of property arrays: - * "alert" (boolean) => display as an alert property (usually in red) - * "property" (string) => property name - * "value" (string) => property value - */ - public function getProperties() - { - $lng = $this->lng; - $ilUser = $this->user; - - $props = array(); - // please list alert properties first - // example (use $lng->txt instead of "Status"/"Offline" strings): - // $props[] = array("alert" => true, "property" => "Status", "value" => "Offline"); - // $props[] = array("alert" => false, "property" => ..., "value" => ...); - // ... - - // #8280: WebDav is only supported in repository - if($this->context == self::CONTEXT_REPOSITORY) - { - // add centralized offline status - if(ilObject::lookupOfflineStatus($this->obj_id)) - { - $props[] = - [ - 'alert' => true, - 'property' => $lng->txt("status"), - 'value' => $lng->txt("offline") - ]; - } - - // BEGIN WebDAV Display locking information - require_once ('Services/WebDAV/classes/class.ilDAVActivationChecker.php'); - if (ilDAVActivationChecker::_isActive()) - { - // Show lock info - require_once('Services/WebDAV/classes/lock/class.ilWebDAVLockBackend.php'); - $webdav_lock_backend = new ilWebDAVLockBackend(); - if ($ilUser->getId() != ANONYMOUS_USER_ID) - { - if ($lock = $webdav_lock_backend->getLocksOnObjectId($this->obj_id)) - { - $lock_user = new ilObjUser($lock->getIliasOwner()); - - $props[] = array( - "alert" => false, - "property" => $lng->txt("in_use_by"), - "value" => $lock_user->getLogin(), - "link" => "./ilias.php?user=".$lock_user->getId().'&cmd=showUserProfile&cmdClass=ilpersonaldesktopgui&baseClass=ilPersonalDesktopGUI', - ); - } - } - // END WebDAV Display locking information - - if($this->getDetailsLevel() == self::DETAILS_SEARCH) - { - return $props; - } - - // BEGIN WebDAV Display warning for invisible Unix files and files with special characters - if (preg_match('/^(\\.|\\.\\.)$/', $this->title)) - { - $props[] = array("alert" => false, "property" => $lng->txt("filename_interoperability"), - "value" => $lng->txt("filename_special_filename"), - 'propertyNameVisible' => false); - } - else if (preg_match('/^\\./', $this->title)) - { - $props[] = array("alert" => false, "property" => $lng->txt("filename_visibility"), - "value" => $lng->txt("filename_hidden_unix_file"), - 'propertyNameVisible' => false); - } - else if (preg_match('/~$/', $this->title)) - { - $props[] = array("alert" => false, "property" => $lng->txt("filename_visibility"), - "value" => $lng->txt("filename_hidden_backup_file"), - 'propertyNameVisible' => false); - } - else if (preg_match('/[\\/]/', $this->title)) - { - $props[] = array("alert" => false, "property" => $lng->txt("filename_interoperability"), - "value" => $lng->txt("filename_special_characters"), - 'propertyNameVisible' => false); - } - else if (preg_match('/[\\\\\\/:*?"<>|]/', $this->title)) - { - $props[] = array("alert" => false, "property" => $lng->txt("filename_interoperability"), - "value" => $lng->txt("filename_windows_special_characters"), - 'propertyNameVisible' => false); - } - else if (preg_match('/\\.$/', $this->title)) - { - $props[] = array("alert" => false, "property" => $lng->txt("filename_interoperability"), - "value" => $lng->txt("filename_windows_empty_extension"), - 'propertyNameVisible' => false); - } - else if (preg_match('/^(\\.|\\.\\.)$/', $this->title)) - { - $props[] = array("alert" => false, "property" => $lng->txt("filename_interoperability"), - "value" => $lng->txt("filename_special_filename"), - 'propertyNameVisible' => false); - } - else if (preg_match('/#/', $this->title)) - { - $props[] = array("alert" => false, "property" => $lng->txt("filename_interoperability"), - "value" => $lng->txt("filename_windows_webdav_issue"), - 'propertyNameVisible' => false); - } - } - // END WebDAV Display warning for invisible files and files with special characters - } - - return $props; - } - - /** - * add custom property - */ - function addCustomProperty($a_property = "", $a_value = "", - $a_alert = false, $a_newline = false) - { - $this->cust_prop[] = array("property" => $a_property, "value" => $a_value, - "alert" => $a_alert, "newline" => $a_newline); - } - - /** - * get custom properties - */ - function getCustomProperties($a_prop) - { - if (is_array($this->cust_prop)) - { - foreach($this->cust_prop as $prop) - { - $a_prop[] = $prop; - } - } - return $a_prop; - } - - /** - * get all alert properties - * @return array - */ - public function getAlertProperties() - { - $alert = array(); - foreach((array)$this->getProperties() as $prop) - { - if($prop['alert'] == true) - { - $alert[] = $prop; - } - } - return $alert; - } - - /** - * get notice properties - */ - function getNoticeProperties() - { - $this->notice_prop = array(); - if($infos = $this->ldap_mapping->getInfoStrings($this->obj_id,true)) - { - foreach($infos as $info) - { - $this->notice_prop[] = array('value' => $info); - } - } - return $this->notice_prop ? $this->notice_prop : array(); - } - /** - * add a custom command - */ - public function addCustomCommand($a_link, $a_lang_var, $a_frame = "", $onclick = "") - { - $this->cust_commands[] = - array("link" => $a_link, "lang_var" => $a_lang_var, - "frame" => $a_frame, "onclick" => $onclick); - } - - /** - * Force visible access only. - * @param type $a_stat - */ - public function forceVisibleOnly($a_stat) - { - $this->force_visible_only = $a_stat; - } - - /** - * Force unreadable - * @return type - */ - public function isVisibleOnlyForced() - { - return $this->force_visible_only; - } - - /** - * get all current commands for a specific ref id (in the permission - * context of the current user) - * - * !!!NOTE!!!: Please use getListHTML() if you want to display the item - * including all commands - * - * !!!NOTE 2!!!: Please do not overwrite this method in derived - * classes becaus it will get pretty large and much code will be simply - * copy-and-pasted. Insert smaller object type related method calls instead. - * (like getCommandLink() or getCommandFrame()) - * - * @access public - * @param int $a_ref_id ref id of object - * @return array array of command arrays including - * "permission" => permission name - * "cmd" => command - * "link" => command link url - * "frame" => command link frame - * "lang_var" => language variable of command - * "granted" => true/false: command granted or not - * "access_info" => access info object (to do: implementation) - */ - public function getCommands() - { - $ilAccess = $this->access; - $ilUser = $this->user; - - $ref_commands = array(); - foreach($this->commands as $command) - { - $permission = $command["permission"]; - $cmd = $command["cmd"]; - $lang_var = $command["lang_var"]; - $txt = ""; - $info_object = null; - - if (isset($command["txt"])) - { - $txt = $command["txt"]; - } - - // BEGIN WebDAV: Suppress commands that don't make sense for anonymous users. - // Suppress commands that don't make sense for anonymous users - if ($ilUser->getId() == ANONYMOUS_USER_ID && - $command['enable_anonymous'] == 'false') - { - continue; - } - // END WebDAV: Suppress commands that don't make sense for anonymous users. - - // all access checking should be made within $ilAccess and - // the checkAccess of the ilObj...Access classes - //$access = $ilAccess->checkAccess($permission, $cmd, $this->ref_id, $this->type); - $access = $this->checkCommandAccess($permission,$cmd,$this->ref_id,$this->type); - - if ($access) - { - $cmd_link = $this->getCommandLink($command["cmd"]); - $cmd_frame = $this->getCommandFrame($command["cmd"]); - $cmd_image = $this->getCommandImage($command["cmd"]); - $access_granted = true; - } - else - { - $access_granted = false; - $info_object = $ilAccess->getInfo(); - } - - if (!isset($command["default"])) - { - $command["default"] = ""; - } - $ref_commands[] = array( - "permission" => $permission, - "cmd" => $cmd, - "link" => $cmd_link, - "frame" => $cmd_frame, - "lang_var" => $lang_var, - "txt" => $txt, - "granted" => $access_granted, - "access_info" => $info_object, - "img" => $cmd_image, - "default" => $command["default"] - ); - } - - return $ref_commands; - } - - // BEGIN WebDAV: Visualize object state in its icon. - /** - * Returns the icon image type. - * For most objects, this is same as the object type, e.g. 'cat','fold'. - * We can return here other values, to express a specific state of an object, - * e.g. 'crs_offline", and/or to express a specific kind of object, e.g. - * 'file_inline'. - */ - public function getIconImageType() - { - if ($this->type == "sahs" && $this->offline_mode) { - return $this->type . "_offline"; - } - return $this->type; - } - // END WebDAV: Visualize object state in its icon. - - /** - * insert item title - * - * @access private - * @param object $a_tpl template object - * @param string $a_title item title - */ - public function insertTitle() - { - if($this->restrict_to_goto) - { - $this->default_command = array("frame" => "", - "link" => $this->buildGotoLink()); - } - // begin-patch lok - if ( - !$this->default_command || - (!$this->getCommandsStatus() && !$this->restrict_to_goto) || - $this->title_link_disabled - ) - // end-patch lok - { - $this->tpl->setCurrentBlock("item_title"); - $this->tpl->setVariable("TXT_TITLE", $this->getTitle()); - $this->tpl->parseCurrentBlock(); - } - else - { - $this->default_command['link'] = $this->modifyTitleLink($this->default_command['link']); - - $this->default_command["link"] = - $this->modifySAHSlaunch($this->default_command["link"],$this->default_command["frame"]); - - if ($this->default_command["frame"] != "") - { - $this->tpl->setCurrentBlock("title_linked_frame"); - $this->tpl->setVariable("TARGET_TITLE_LINKED", $this->default_command["frame"]); - $this->tpl->parseCurrentBlock(); - } - - // workaround for repository frameset - #var_dump("
                  ",$this->default_command['link'],"
                  "); - $this->default_command["link"] = - $this->appendRepositoryFrameParameter($this->default_command["link"]); - - #var_dump("
                  ",$this->default_command['link'],"
                  "); - - - // the default command is linked with the title - $this->tpl->setCurrentBlock("item_title_linked"); - $this->tpl->setVariable("TXT_TITLE_LINKED", $this->getTitle()); - $this->tpl->setVariable("HREF_TITLE_LINKED", $this->default_command["link"]); - - // has preview? - include_once("./Services/Preview/classes/class.ilPreview.php"); - if (ilPreview::hasPreview($this->obj_id, $this->type)) - { - include_once("./Services/Preview/classes/class.ilPreviewGUI.php"); - - // get context for access checks later on - $access_handler = null; - switch ($this->context) - { - case self::CONTEXT_WORKSPACE: - case self::CONTEXT_WORKSPACE_SHARING: - $context = ilPreviewGUI::CONTEXT_WORKSPACE; - include_once("./Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"); - $access_handler = new ilWorkspaceAccessHandler(); - break; - - default: - $ilAccess = $this->access; - $context = ilPreviewGUI::CONTEXT_REPOSITORY; - $access_handler = $ilAccess; - break; - } - - $preview = new ilPreviewGUI($this->ref_id, $context, $this->obj_id, $access_handler); - $preview_status = ilPreview::lookupRenderStatus($this->obj_id); - $preview_status_class = ""; - $preview_text_topic = "preview_show"; - if ($preview_status == ilPreview::RENDER_STATUS_NONE) - { - $preview_status_class = "ilPreviewStatusNone"; - $preview_text_topic = "preview_none"; - } - $this->tpl->setCurrentBlock("item_title_linked"); - $this->tpl->setVariable("PREVIEW_STATUS_CLASS", $preview_status_class); - $this->tpl->setVariable("SRC_PREVIEW_ICON", ilUtil::getImagePath("preview.png", "Services/Preview")); - $this->tpl->setVariable("TXT_PREVIEW", $this->lng->txt($preview_text_topic)); - $this->tpl->setVariable("SCRIPT_PREVIEW_CLICK", $preview->getJSCall($this->getUniqueItemId(true))); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->parseCurrentBlock(); - } - - if ($this->bold_title == true) - { - $this->tpl->touchBlock('bold_title_start'); - $this->tpl->touchBlock('bold_title_end'); - } - } - - protected function buildGotoLink() - { - switch($this->context) - { - case self::CONTEXT_WORKSPACE_SHARING: - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; - return ilWorkspaceAccessHandler::getGotoLink($this->ref_id, $this->obj_id); - - default: - // not implemented yet - break; - } - } - - /** - * Insert substitutions - * - * @access public - * - */ - public function insertSubstitutions() - { - $fields_shown = false; - foreach($this->substitutions->getParsedSubstitutions($this->ref_id,$this->obj_id) as $data) - { - if($data['bold']) - { - $data['name'] = ''.$data['name'].''; - $data['value'] = ''.$data['value'].''; - } - $this->tpl->touchBlock("std_prop"); - $this->tpl->setCurrentBlock('item_property'); - if($data['show_field']) - { - $this->tpl->setVariable('TXT_PROP',$data['name']); - } - $this->tpl->setVariable('VAL_PROP',$data['value']); - $this->tpl->parseCurrentBlock(); - - if($data['newline']) - { - $this->tpl->touchBlock('newline_prop'); - } - $fields_shown = false; - - } - if($fields_shown) - { - $this->tpl->touchBlock('newline_prop'); - } - } - - - /** - * insert item description - * - * @access private - * @param object $a_tpl template object - * @param string $a_desc item description - */ - function insertDescription() - { - if($this->getSubstitutionStatus()) - { - $this->insertSubstitutions(); - if(!$this->substitutions->isDescriptionEnabled()) - { - return true; - } - } - - // see bug #16519 - $d = $this->getDescription(); - $d = strip_tags($d, ""); - $this->tpl->setCurrentBlock("item_description"); - $this->tpl->setVariable("TXT_DESC", $d); - $this->tpl->parseCurrentBlock(); - } - - /** - * Insert highlighted search fragment - * @return - */ - public function insertSearchFragment() - { - if(strlen($this->getSearchFragment())) - { - $this->tpl->setCurrentBlock('search_fragment'); - $this->tpl->setVariable('TXT_SEARCH_FRAGMENT',$this->getSearchFragment().' ...'); - $this->tpl->parseCurrentBlock(); - } - } - - /** - * insert relevance - * @param - * @return - */ - public function insertRelevance() - { - - if(!$this->enabledRelevance() or !(int) $this->getRelevance()) - { - return false; - } - - include_once "Services/UIComponent/ProgressBar/classes/class.ilProgressBar.php"; - $pbar = ilProgressBar::getInstance(); - $pbar->setCurrent($this->getRelevance()); - - $this->tpl->setCurrentBlock('relevance'); - $this->tpl->setVariable('REL_PBAR', $pbar->render()); - $this->tpl->parseCurrentBlock(); - } - - /** - * set output mode - * - * @param string $a_mode output mode (IL_LIST_FULL | IL_LIST_AS_TRIGGER) - */ - function setMode($a_mode) - { - $this->mode = $a_mode; - } - - /** - * get output mode - * - * @return string output mode (IL_LIST_FULL | IL_LIST_AS_TRIGGER) - */ - function getMode() - { - return $this->mode; - } - - /** - * set depth for precondition output (stops at level 5) - */ - function setConditionDepth($a_depth) - { - $this->condition_depth = $a_depth; - } - - /** - * check current output mode - * - * @param string $a_mode (IL_LIST_FULL | IL_LIST_AS_TRIGGER) - * - * @return boolen true if current mode is $a_mode - */ - function isMode($a_mode) - { - if ($a_mode == $this->mode) - { - return true; - } - else - { - return false; - } - } - - /** - * Determine properties - * @return array - */ - public function determineProperties() - { - $ilAccess = $this->access; - $lng = $this->lng; - $ilUser = $this->user; - - $props = $this->getProperties(); - $props = $this->getCustomProperties($props); - - if ($this->context != self::CONTEXT_WORKSPACE && $this->context != self::CONTEXT_WORKSPACE_SHARING) - { - // add learning progress custom property - include_once "Services/Tracking/classes/class.ilLPStatus.php"; - $lp = ilLPStatus::getListGUIStatus($this->obj_id); - if ($lp) - { - $props[] = array("alert" => false, - "property" => $lng->txt("learning_progress"), - "value" => $lp, - "newline" => true); - } - - // add no item access note in public section - // for items that are visible but not readable - if ($ilUser->getId() == ANONYMOUS_USER_ID) - { - if (!$ilAccess->checkAccess("read", "", $this->ref_id, $this->type, $this->obj_id)) - { - $props[] = array("alert" => true, - "value" => $lng->txt("no_access_item_public"), - "newline" => true); - } - } - } - - // reference objects have translated ids, revert to originals - $note_ref_id = $this->ref_id; - $note_obj_id = $this->obj_id; - if ($this->reference_ref_id) - { - $note_ref_id = $this->reference_ref_id; - $note_obj_id = $this->reference_obj_id; - } - $redraw_js = "il.Object.redrawListItem(" . $note_ref_id . ");"; - - // add common properties (comments, notes, tags) - require_once 'Services/Notes/classes/class.ilNote.php'; - if ((self::$cnt_notes[$note_obj_id][IL_NOTE_PRIVATE] > 0 || - self::$cnt_notes[$note_obj_id][IL_NOTE_PUBLIC] > 0 || - self::$cnt_tags[$note_obj_id] > 0 || - is_array(self::$tags[$note_obj_id])) && - ($ilUser->getId() != ANONYMOUS_USER_ID)) - { - include_once("./Services/Notes/classes/class.ilNoteGUI.php"); - include_once("./Services/Tagging/classes/class.ilTaggingGUI.php"); - - $nl = true; - if ($this->isCommentsActivated($this->type, $this->ref_id, $this->obj_id, false, false) - && self::$cnt_notes[$note_obj_id][IL_NOTE_PUBLIC] > 0) - { - $props[] = array("alert" => false, - "property" => $lng->txt("notes_comments"), - "value" => "ajax_hash, $redraw_js) . "\">" . - self::$cnt_notes[$note_obj_id][IL_NOTE_PUBLIC] . "", - "newline" => $nl); - $nl = false; - } - - if ($this->notes_enabled && self::$cnt_notes[$note_obj_id][IL_NOTE_PRIVATE] > 0) - { - $props[] = array("alert" => false, - "property" => $lng->txt("notes"), - "value" => "ajax_hash, $redraw_js) . "\">" . - self::$cnt_notes[$note_obj_id][IL_NOTE_PRIVATE] . "", - "newline" => $nl); - $nl = false; - } - if ($this->tags_enabled && - (self::$cnt_tags[$note_obj_id] > 0 || - is_array(self::$tags[$note_obj_id]))) - { - $tags_set = new ilSetting("tags"); - if ($tags_set->get("enable")) - { - $tags_url = ilTaggingGUI::getListTagsJSCall($this->ajax_hash, $redraw_js); - - // list object tags - if (is_array(self::$tags[$note_obj_id])) - { - $tags_tmp = array(); - foreach (self::$tags[$note_obj_id] as $tag => $is_tag_owner) - { - if ($is_tag_owner) - { - $tags_tmp[] = "" . $tag . ""; - } else - { - $tags_tmp[] = "" . $tag . ""; - } - } - $tags_value = implode(" ", $tags_tmp); - $nl = true; - $prop_text = ""; - } // tags counter - else - { - $tags_value = "" . - self::$cnt_tags[$note_obj_id] . ""; - $prop_text = $lng->txt("tagging_tags"); - } - $props[] = array("alert" => false, - "property" => $prop_text, - "value" => $tags_value, - "newline" => $nl); - $nl = false; - } - } - } - if (!is_array($props)) - { - return []; - } - return $props; - } - - /** - * insert properties - * - * @access private - */ - function insertProperties() - { - $props = $this->determineProperties(); - $cnt = 1; - if (is_array($props) && count($props) > 0) - { - foreach($props as $prop) - { - // BEGIN WebDAV: Display a separator between properties. - if ($cnt > 1) - { - $this->tpl->touchBlock("separator_prop"); - } - // END WebDAV: Display a separator between properties. - - if ($prop["alert"] == true) - { - $this->tpl->touchBlock("alert_prop"); - } - else - { - $this->tpl->touchBlock("std_prop"); - } - if ($prop["newline"] == true && $cnt > 1) - { - $this->tpl->touchBlock("newline_prop"); - } - //BEGIN WebDAV: Support hidden property names. - if (isset($prop["property"]) && $prop['propertyNameVisible'] !== false && $prop["property"] != "") - //END WebDAV: Support hidden property names. - { - $this->tpl->setCurrentBlock("prop_name"); - $this->tpl->setVariable("TXT_PROP", $prop["property"]); - $this->tpl->parseCurrentBlock(); - } - $this->tpl->setCurrentBlock("item_property"); - //BEGIN WebDAV: Support links in property values. - if ($prop['link']) - { - $this->tpl->setVariable("LINK_PROP", $prop['link']); - $this->tpl->setVariable("LINK_VAL_PROP", $prop["value"]); - } - else - { - $this->tpl->setVariable("VAL_PROP", $prop["value"]); - } - //END WebDAV: Support links in property values. - $this->tpl->parseCurrentBlock(); - - $cnt++; - } - $this->tpl->setCurrentBlock("item_properties"); - $this->tpl->parseCurrentBlock(); - } - } - - function insertNoticeProperties() - { - $this->getNoticeProperties(); - foreach($this->notice_prop as $property) - { - $this->tpl->setCurrentBlock('notice_item'); - $this->tpl->setVariable('NOTICE_ITEM_VALUE',$property['value']); - $this->tpl->parseCurrentBlock(); - } - $this->tpl->setCurrentBlock('notice_property'); - $this->tpl->parseCurrentBlock(); - } - - protected function parseConditions($toggle_id,$conditions,$obligatory = true) - { - $lng = $this->lng; - $objDefinition = $this->obj_definition; - $tree = $this->tree; - - $num_required = ilConditionHandler::calculateEffectiveRequiredTriggers($this->ref_id, $this->obj_id); - $num_optional_required = - $num_required - count($conditions) + count(ilConditionHandler::getEffectiveOptionalConditionsOfTarget($this->ref_id, $this->obj_id)); - - // Check if all conditions are fullfilled - $visible_conditions = array(); - $passed_optional = 0; - foreach($conditions as $condition) - { - if($obligatory and !$condition['obligatory']) - { - continue; - } - if(!$obligatory and $condition['obligatory']) - { - continue; - } - - if($tree->isDeleted($condition['trigger_ref_id'])) - { - continue; - } - - include_once 'Services/Container/classes/class.ilMemberViewSettings.php'; - $ok = ilConditionHandler::_checkCondition($condition) and - !ilMemberViewSettings::getInstance()->isActive(); - - if(!$ok) - { - $visible_conditions[] = $condition['id']; - } - - if(!$obligatory and $ok) - { - ++$passed_optional; - // optional passed - if($passed_optional >= $num_optional_required) - { - return true; - } - } - } - - foreach($conditions as $condition) - { - if(!in_array($condition['id'], $visible_conditions)) - { - continue; - } - - include_once './Services/Conditions/classes/class.ilConditionHandlerGUI.php'; - $cond_txt = ilConditionHandlerGUI::translateOperator($condition['trigger_obj_id'],$condition['operator']).' '.$condition['value']; - - // display trigger item - $class = $objDefinition->getClassName($condition["trigger_type"]); - $location = $objDefinition->getLocation($condition["trigger_type"]); - if ($class == "" && $location == "") - { - continue; - } - $missing_cond_exist = true; - - $full_class = "ilObj".$class."ListGUI"; - include_once($location."/class.".$full_class.".php"); - $item_list_gui = new $full_class($this); - $item_list_gui->setMode(IL_LIST_AS_TRIGGER); - $item_list_gui->enablePath(false); - $item_list_gui->enableIcon(true); - $item_list_gui->setConditionDepth($this->condition_depth + 1); - $item_list_gui->setParentRefId($this->getUniqueItemId()); // yes we can - $item_list_gui->addCustomProperty($this->lng->txt("precondition_required_itemlist"), $cond_txt, false, true); - - $item_list_gui->enableCommands($this->commands_enabled, $this->std_cmd_only); - $item_list_gui->enableProperties($this->properties_enabled); - - $trigger_html = $item_list_gui->getListItemHTML($condition['trigger_ref_id'], - $condition['trigger_obj_id'], ilObject::_lookupTitle($condition["trigger_obj_id"]), - ""); - $this->tpl->setCurrentBlock("precondition"); - if ($trigger_html == "") - { - $trigger_html = $this->lng->txt("precondition_not_accessible"); - } - $this->tpl->setVariable("TXT_CONDITION", trim($cond_txt)); - $this->tpl->setVariable("TRIGGER_ITEM", $trigger_html); - $this->tpl->parseCurrentBlock(); - } - - if ($missing_cond_exist and $obligatory) - { - $this->tpl->setCurrentBlock("preconditions"); - $this->tpl->setVariable("CONDITION_TOGGLE_ID", "_obl_".$toggle_id); - $this->tpl->setVariable("TXT_PRECONDITIONS", $lng->txt("preconditions_obligatory_hint")); - $this->tpl->parseCurrentBlock(); - - } - elseif($missing_cond_exist and !$obligatory) - { - $this->tpl->setCurrentBlock("preconditions"); - $this->tpl->setVariable("CONDITION_TOGGLE_ID", "_opt_".$toggle_id); - $this->tpl->setVariable("TXT_PRECONDITIONS", sprintf($lng->txt("preconditions_optional_hint"),$num_optional_required)); - $this->tpl->parseCurrentBlock(); - } - - return !$missing_cond_exist; - } - - /** - * insert all missing preconditions - */ - function insertPreconditions() - { - include_once("./Services/Conditions/classes/class.ilConditionHandler.php"); - - // do not show multi level conditions (messes up layout) - if ($this->condition_depth > 0) - { - return; - } - - if($this->condition_target) - { - $conditions = ilConditionHandler::_getEffectiveConditionsOfTarget( - $this->condition_target['ref_id'], - $this->condition_target['obj_id'], - $this->condition_target['target_type'] - ); - } - else - { - $conditions = ilConditionHandler::_getEffectiveConditionsOfTarget($this->ref_id, $this->obj_id); - } - - if(sizeof($conditions)) - { - for($i = 0; $i < count($conditions); $i++) - { - $conditions[$i]['title'] = ilObject::_lookupTitle($conditions[$i]['trigger_obj_id']); - } - $conditions = ilUtil::sortArray($conditions,'title','DESC'); - - ++self::$js_unique_id; - - // Show obligatory and optional preconditions seperated - $all_done_obl = $this->parseConditions(self::$js_unique_id,$conditions,true); - $all_done_opt = $this->parseConditions(self::$js_unique_id,$conditions,false); - - if(!$all_done_obl || !$all_done_opt) - { - $this->tpl->setCurrentBlock("preconditions_toggle"); - $this->tpl->setVariable("PRECONDITION_TOGGLE_INTRO", $this->lng->txt("precondition_toggle")); - $this->tpl->setVariable("PRECONDITION_TOGGLE_TRIGGER", $this->lng->txt("show")); - $this->tpl->setVariable("PRECONDITION_TOGGLE_ID", self::$js_unique_id); - $this->tpl->setVariable("TXT_PRECONDITION_SHOW", $this->lng->txt("show")); - $this->tpl->setVariable("TXT_PRECONDITION_HIDE", $this->lng->txt("hide")); - $this->tpl->parseCurrentBlock(); - } - } - } - - /** - * insert command button - * - * @access private - * @param string $a_href link url target - * @param string $a_text link text - * @param string $a_frame link frame target - */ - function insertCommand($a_href, $a_text, $a_frame = "", $a_img = "", $a_cmd = "", $a_onclick = "") - { - // #11099 - $chksum = md5($a_href.$a_text); - if($a_href == "#" || - !in_array($chksum, $this->prevent_duplicate_commands)) - { - if($a_href != "#") - { - $this->prevent_duplicate_commands[] = $chksum; - } - - $prevent_background_click = false; - if ($a_cmd == 'mount_webfolder') - { - $prevent_background_click = true; - } - - if ($a_cmd == "downloadFolder") - { - include_once "Services/BackgroundTask/classes/class.ilFolderDownloadBackgroundTaskHandler.php"; - if(ilFolderDownloadBackgroundTaskHandler::isActive()) - { - $a_onclick = ilFolderDownloadBackgroundTaskHandler::getObjectListAction($this->ref_id); - $a_href = "#"; - } - } - - $this->current_selection_list->addItem($a_text, "", $a_href, $a_img, $a_text, $a_frame, - "", $prevent_background_click, $a_onclick); - } - } - - /** - * insert cut command - * - * @access private - * @param object $a_tpl template object - * @param int $a_ref_id item reference id - */ - function insertDeleteCommand() - { - if ($this->std_cmd_only) - { - return; - } - - if(is_object($this->getContainerObject()) and - $this->getContainerObject() instanceof ilAdministrationCommandHandling) - { - if($this->checkCommandAccess('delete','',$this->ref_id,$this->type)) - { - $this->ctrl->setParameter($this->getContainerObject(),'item_ref_id',$this->getCommandId()); - $cmd_link = $this->ctrl->getLinkTarget($this->getContainerObject(), "delete"); - $this->insertCommand($cmd_link, $this->lng->txt("delete")); - $this->adm_commands_included = true; - return true; - } - return false; - } - - if($this->checkCommandAccess('delete','',$this->ref_id,$this->type)) - { - $this->ctrl->setParameter($this->container_obj, "ref_id", - $this->container_obj->object->getRefId()); - $this->ctrl->setParameter($this->container_obj, "item_ref_id", $this->getCommandId()); - $cmd_link = $this->ctrl->getLinkTarget($this->container_obj, "delete"); - $this->insertCommand($cmd_link, $this->lng->txt("delete"), "", - ""); - $this->adm_commands_included = true; - } - } - - /** - * insert link command - * - * @access private - * @param object $a_tpl template object - * @param int $a_ref_id item reference id - */ - function insertLinkCommand() - { - $objDefinition = $this->obj_definition; - - if ($this->std_cmd_only) - { - return; - } - - // #17307 - if(!$this->checkCommandAccess('delete','',$this->ref_id,$this->type) or - !$objDefinition->allowLink($this->type)) - { - return false; - } - - // BEGIN PATCH Lucene search - - if(is_object($this->getContainerObject()) and - $this->getContainerObject() instanceof ilAdministrationCommandHandling) - { - $this->ctrl->setParameter($this->getContainerObject(),'item_ref_id',$this->getCommandId()); - $cmd_link = $this->ctrl->getLinkTarget($this->getContainerObject(), "link"); - $this->insertCommand($cmd_link, $this->lng->txt("link")); - $this->adm_commands_included = true; - return true; - } - // END PATCH Lucene Search - - // if the permission is changed here, it has - // also to be changed in ilContainerGUI, admin command check - $this->ctrl->setParameter($this->container_obj, "ref_id", - $this->container_obj->object->getRefId()); - $this->ctrl->setParameter($this->container_obj, "item_ref_id", $this->getCommandId()); - $cmd_link = $this->ctrl->getLinkTarget($this->container_obj, "link"); - $this->insertCommand($cmd_link, $this->lng->txt("link"), "", - ""); - $this->adm_commands_included = true; - return true; - } - - /** - * insert cut command - * - * @access protected - * @param bool $a_to_repository - */ - function insertCutCommand($a_to_repository = false) - { - if ($this->std_cmd_only) - { - return; - } - // BEGIN PATCH Lucene search - if(is_object($this->getContainerObject()) and - $this->getContainerObject() instanceof ilAdministrationCommandHandling) - { - if($this->checkCommandAccess('delete','',$this->ref_id,$this->type)) - { - $this->ctrl->setParameter($this->getContainerObject(),'item_ref_id',$this->getCommandId()); - $cmd_link = $this->ctrl->getLinkTarget($this->getContainerObject(), "cut"); - $this->insertCommand($cmd_link, $this->lng->txt("move")); - $this->adm_commands_included = true; - return true; - } - return false; - } - // END PATCH Lucene Search - - // if the permission is changed here, it has - // also to be changed in ilContainerContentGUI, determineAdminCommands - if($this->checkCommandAccess('delete','',$this->ref_id,$this->type) && - $this->container_obj->object) - { - $this->ctrl->setParameter($this->container_obj, "ref_id", - $this->container_obj->object->getRefId()); - $this->ctrl->setParameter($this->container_obj, "item_ref_id", $this->getCommandId()); - - if(!$a_to_repository) - { - $cmd_link = $this->ctrl->getLinkTarget($this->container_obj, "cut"); - $this->insertCommand($cmd_link, $this->lng->txt("move"), "", - ""); - } - else - { - $cmd_link = $this->ctrl->getLinkTarget($this->container_obj, "cut_for_repository"); - $this->insertCommand($cmd_link, $this->lng->txt("wsp_move_to_repository"), "", - ""); - } - - $this->adm_commands_included = true; - } - } - - /** - * Insert copy command - * - * @param bool $a_to_repository - */ - public function insertCopyCommand($a_to_repository = false) - { - $objDefinition = $this->obj_definition; - - if($this->std_cmd_only) - { - return; - } - - if($this->checkCommandAccess('copy', 'copy', $this->ref_id, $this->type) && - $objDefinition->allowCopy($this->type)) - { - if($this->context != self::CONTEXT_WORKSPACE && $this->context != self::CONTEXT_WORKSPACE_SHARING) - { - $this->ctrl->setParameterByClass('ilobjectcopygui','source_id',$this->getCommandId()); - $cmd_copy = $this->ctrl->getLinkTargetByClass('ilobjectcopygui','initTargetSelection'); - $this->insertCommand($cmd_copy, $this->lng->txt('copy')); - } - else - { - $this->ctrl->setParameter($this->container_obj, "ref_id", - $this->container_obj->object->getRefId()); - $this->ctrl->setParameter($this->container_obj, "item_ref_id", $this->getCommandId()); - - if(!$a_to_repository) - { - $cmd_copy = $this->ctrl->getLinkTarget($this->container_obj, 'copy'); - $this->insertCommand($cmd_copy, $this->lng->txt('copy')); - } - else - { - $cmd_copy = $this->ctrl->getLinkTarget($this->container_obj, 'copy_to_repository'); - $this->insertCommand($cmd_copy, $this->lng->txt('wsp_copy_to_repository')); - } - } - - $this->adm_commands_included = true; - } - return; - } - - - /** - * Insert paste command - */ - function insertPasteCommand() - { - $objDefinition = $this->obj_definition; - - if ($this->std_cmd_only) - { - return; - } - - if(!$objDefinition->isContainer(ilObject::_lookupType($this->obj_id))) - { - return false; - } - - if(is_object($this->getContainerObject()) and - $this->getContainerObject() instanceof ilAdministrationCommandHandling and - isset($_SESSION['clipboard'])) - { - $this->ctrl->setParameter($this->getContainerObject(),'item_ref_id',$this->getCommandId()); - $cmd_link = $this->ctrl->getLinkTarget($this->getContainerObject(), "paste"); - $this->insertCommand($cmd_link, $this->lng->txt("paste")); - $this->adm_commands_included = true; - return true; - } - return false; - } - - /** - * insert subscribe command - * - * @access private - * @param object $a_tpl template object - * @param int $a_ref_id item reference id - */ - function insertSubscribeCommand() - { - $ilSetting = $this->settings; - $ilUser = $this->user; - - if ($this->std_cmd_only) - { - return; - } - - if((int)$ilSetting->get('disable_my_offers')) - { - return; - } - - $type = ilObject::_lookupType(ilObject::_lookupObjId($this->getCommandId())); - - if ($ilUser->getId() != ANONYMOUS_USER_ID) - { - // #17467 - add ref_id to link (in repository only!) - if(is_object($this->container_obj) && - !($this->container_obj instanceof ilAdministrationCommandHandling) && - is_object($this->container_obj->object)) - { - $this->ctrl->setParameter($this->container_obj, "ref_id", $this->container_obj->object->getRefId()); - } - - if (!$ilUser->isDesktopItem($this->getCommandId(), $type)) - { - // Pass type and object ID to ilAccess to improve performance - if ($this->checkCommandAccess("read", "", $this->ref_id, $this->type, $this->obj_id)) - { - if($this->getContainerObject() instanceof ilDesktopItemHandling) - { - $this->ctrl->setParameter($this->container_obj, "type", $type); - $this->ctrl->setParameter($this->container_obj, "item_ref_id", $this->getCommandId()); - $cmd_link = $this->ctrl->getLinkTarget($this->container_obj, "addToDesk"); - $this->insertCommand($cmd_link, $this->lng->txt("to_desktop"), "", - ""); - } - } - } - else - { - if ($this->getContainerObject() instanceof ilDesktopItemHandling) - { - $this->ctrl->setParameter($this->container_obj, "type", $type); - $this->ctrl->setParameter($this->container_obj, "item_ref_id", $this->getCommandId()); - $cmd_link = $this->ctrl->getLinkTarget($this->container_obj, "removeFromDesk"); - $this->insertCommand($cmd_link, $this->lng->txt("unsubscribe"), "", - ""); - } - } - } - } - - /** - * insert info screen command - */ - function insertInfoScreenCommand() - { - if ($this->std_cmd_only) - { - return; - } - $cmd_link = $this->getCommandLink("infoScreen"); - $cmd_frame = $this->getCommandFrame("infoScreen"); - $this->insertCommand($cmd_link, $this->lng->txt("info_short"), $cmd_frame, - ilUtil::getImagePath("icon_info.svg")); - } - - /** - * Insert common social commands (comments, notes, tagging) - * - * @param - * @return - */ - function insertCommonSocialCommands($a_header_actions = false) - { - $lng = $this->lng; - $ilUser = $this->user; - - if ($this->std_cmd_only || - ($ilUser->getId() == ANONYMOUS_USER_ID)) - { - return; - } - $lng->loadLanguageModule("notes"); - $lng->loadLanguageModule("tagging"); - $cmd_frame = $this->getCommandFrame("infoScreen"); - include_once("./Services/Notes/classes/class.ilNoteGUI.php"); - - // reference objects have translated ids, revert to originals - $note_ref_id = $this->ref_id; - if($this->reference_ref_id) - { - $note_ref_id = $this->reference_ref_id; - } - - $js_updater = $a_header_actions - ? "il.Object.redrawActionHeader();" - : "il.Object.redrawListItem(".$note_ref_id.")"; - - $comments_enabled = $this->isCommentsActivated($this->type, $this->ref_id, $this->obj_id, $a_header_actions, true); - if($comments_enabled) - { - $this->insertCommand("#", $this->lng->txt("notes_comments"), $cmd_frame, - "", "", ilNoteGUI::getListCommentsJSCall($this->ajax_hash, $js_updater)); - } - - if($this->notes_enabled) - { - $this->insertCommand("#", $this->lng->txt("notes"), $cmd_frame, - "", "", ilNoteGUI::getListNotesJSCall($this->ajax_hash, $js_updater)); - } - - if ($this->tags_enabled) - { - include_once("./Services/Tagging/classes/class.ilTaggingGUI.php"); - //$this->insertCommand($cmd_tag_link, $this->lng->txt("tagging_set_tag"), $cmd_frame); - $this->insertCommand("#", $this->lng->txt("tagging_set_tag"), $cmd_frame, - "", "", ilTaggingGUI::getListTagsJSCall($this->ajax_hash, $js_updater)); - } - } - - /** - * insert edit timings command - * - * @access protected - */ - function insertTimingsCommand() - { - if ($this->std_cmd_only || !$this->container_obj->object) - { - return; - } - - $parent_ref_id = $this->container_obj->object->getRefId(); - $parent_type = $this->container_obj->object->getType(); - - // #18737 - if($this->reference_ref_id) - { - $this->ctrl->setParameterByClass('ilobjectactivationgui', 'ref_id', $this->reference_ref_id); - } - - if($this->checkCommandAccess('write','',$parent_ref_id,$parent_type) || - $this->checkCommandAccess('write','',$this->ref_id,$this->type)) - { - $this->ctrl->setParameterByClass('ilobjectactivationgui','cadh', - $this->ajax_hash); - $this->ctrl->setParameterByClass('ilobjectactivationgui','parent_id', - $parent_ref_id); - $cmd_lnk = $this->ctrl->getLinkTargetByClass(array($this->gui_class_name, 'ilcommonactiondispatchergui', 'ilobjectactivationgui'), - 'edit'); - - $this->insertCommand($cmd_lnk, $this->lng->txt('obj_activation_list_gui')); - } - - if($this->reference_ref_id) - { - $this->ctrl->setParameterByClass('ilobjectactivationgui', 'ref_id', $this->ref_id); - } - } - - /** - * insert all commands into html code - * - * @access private - * @param object $a_tpl template object - * @param int $a_ref_id item reference id - */ - function insertCommands($a_use_asynch = false, $a_get_asynch_commands = false, - $a_asynch_url = "", $a_header_actions = false) - { - $lng = $this->lng; - $ilUser = $this->user; - - if (!$this->getCommandsStatus()) - { - return; - } - - include_once("Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"); - $this->current_selection_list = new ilAdvancedSelectionListGUI(); - $this->current_selection_list->setAsynch($a_use_asynch && !$a_get_asynch_commands); - $this->current_selection_list->setAsynchUrl($a_asynch_url); - if ($a_header_actions) - { - $this->current_selection_list->setListTitle(""); - } - else - { - $this->current_selection_list->setListTitle(""); - } - $this->current_selection_list->setId("act_".$this->getUniqueItemId(false)); - $this->current_selection_list->setSelectionHeaderClass("small"); - $this->current_selection_list->setItemLinkClass("xsmall"); - $this->current_selection_list->setLinksMode("il_ContainerItemCommand2"); - $this->current_selection_list->setHeaderIcon(ilAdvancedSelectionListGUI::DOWN_ARROW_DARK); - $this->current_selection_list->setUseImages(false); - $this->current_selection_list->setAdditionalToggleElement($this->getUniqueItemId(true), "ilContainerListItemOuterHighlight"); - - $this->ctrl->setParameterByClass($this->gui_class_name, "ref_id", $this->ref_id); - - // only standard command? - $only_default = false; - if ($a_use_asynch && !$a_get_asynch_commands) - { - $only_default = true; - } - - $this->default_command = false; - $this->prevent_duplicate_commands = array(); - - // we only allow the following commands inside the header actions - $valid_header_commands = array("mount_webfolder"); - - $commands = $this->getCommands($this->ref_id, $this->obj_id); - foreach($commands as $command) - { - if($a_header_actions && !in_array($command["cmd"], $valid_header_commands)) - { - continue; - } - - if ($command["granted"] == true ) - { - if (!$command["default"] === true) - { - if (!$this->std_cmd_only && !$only_default) - { - // workaround for repository frameset - $command["link"] = - $this->appendRepositoryFrameParameter($command["link"]); - - $cmd_link = $command["link"]; - $txt = ($command["lang_var"] == "") - ? $command["txt"] - : $this->lng->txt($command["lang_var"]); - $this->insertCommand($cmd_link, $txt, - $command["frame"], $command["img"], $command["cmd"]); - } - } - else - { - $this->default_command = $this->createDefaultCommand($command); - //$this->default_command = $command; - } - } - } - - if (!$only_default) - { - // custom commands - if (is_array($this->cust_commands)) - { - foreach ($this->cust_commands as $command) - { - $this->insertCommand($command["link"], $this->lng->txt($command["lang_var"]), - $command["frame"], "", $command["cmd"], $command["onclick"]); - } - } - - // info screen commmand - if ($this->getInfoScreenStatus()) - { - $this->insertInfoScreenCommand(); - } - - if (!$this->isMode(IL_LIST_AS_TRIGGER)) - { - // edit timings - if($this->timings_enabled) - { - $this->insertTimingsCommand(); - } - - // delete - if ($this->delete_enabled) - { - $this->insertDeleteCommand(); - } - - // link - if ($this->link_enabled) - { - $this->insertLinkCommand(); - } - - // cut - if ($this->cut_enabled) - { - $this->insertCutCommand(); - } - - // copy - if ($this->copy_enabled) - { - $this->insertCopyCommand(); - } - - // cut/copy from workspace to repository - if ($this->repository_transfer_enabled) - { - $this->insertCutCommand(true); - $this->insertCopyCommand(true); - } - - // subscribe - if ($this->subscribe_enabled) - { - $this->insertSubscribeCommand(); - } - - // multi download - if ($this->multi_download_enabled && $a_header_actions) - { - $this->insertMultiDownloadCommand(); - } - - // BEGIN PATCH Lucene search - if($this->cut_enabled or $this->link_enabled) - { - $this->insertPasteCommand(); - } - // END PATCH Lucene Search - } - } - - // common social commands (comment, notes, tags) - if (!$only_default && !$this->isMode(IL_LIST_AS_TRIGGER)) - { - $this->insertCommonSocialCommands($a_header_actions); - } - - if(!$a_header_actions) - { - $this->ctrl->clearParametersByClass($this->gui_class_name); - } - - // fix bug #12417 - // there is one case, where no action menu should be displayed: - // public area, category, no info tab - // todo: make this faster and remove type specific implementation if possible - if ($a_use_asynch && !$a_get_asynch_commands && !$a_header_actions) - { - if ($ilUser->getId() == ANONYMOUS_USER_ID && $this->type == "cat") - { - include_once("./Services/Container/classes/class.ilContainer.php"); - include_once("./Services/Object/classes/class.ilObjectServiceSettingsGUI.php"); - if (!ilContainer::_lookupContainerSetting( - $this->obj_id, - ilObjectServiceSettingsGUI::INFO_TAB_VISIBILITY, - true)) - { - return; - } - } - } - - if ($a_use_asynch && $a_get_asynch_commands) - { - return $this->current_selection_list->getHTML(true); - } - - return $this->current_selection_list->getHTML(); - } - - /** - * Toogle comments action status - * - * @param boolean $a_value - */ - function enableComments($a_value, $a_enable_comments_settings = true) - { - $ilSetting = $this->settings; - - // global switch - if($ilSetting->get("disable_comments")) - { - $a_value = false; - } - - $this->comments_enabled = (bool)$a_value; - $this->comments_settings_enabled = (bool)$a_enable_comments_settings; - } - - /** - * Toogle notes action status - * - * @param boolean $a_value - */ - function enableNotes($a_value) - { - $ilSetting = $this->settings; - - // global switch - if($ilSetting->get("disable_notes")) - { - $a_value = false; - } - - $this->notes_enabled = (bool)$a_value; - } - - /** - * Toogle tags action status - * - * @param boolean $a_value - */ - function enableTags($a_value) - { - $tags_set = new ilSetting("tags"); - if (!$tags_set->get("enable")) - { - $a_value = false; - } - $this->tags_enabled = (bool)$a_value; - } - - /** - * Toogle rating action status - * - * @param boolean $a_value - * @param string $a_text - * @param boolean $a_categories - * @param array $a_ctrl_path - */ - function enableRating($a_value, $a_text = null, $a_categories = false, array $a_ctrl_path = null) - { - $this->rating_enabled = (bool)$a_value; - - if($this->rating_enabled) - { - $this->rating_categories_enabled = (bool)$a_categories; - $this->rating_text = $a_text; - $this->rating_ctrl_path = $a_ctrl_path; - } - } - - /** - * Toggles whether multiple objects can be downloaded at once or not. - * - * @param boolean $a_value true, to allow downloading of multiple objects; otherwise, false. - */ - function enableMultiDownload($a_value) - { - $folder_set = new ilSetting("fold"); - if (!$folder_set->get("enable_multi_download")) - { - $a_value = false; - } - $this->multi_download_enabled = (bool)$a_value; - } - - function insertMultiDownloadCommand() - { - $objDefinition = $this->obj_definition; - - if ($this->std_cmd_only) - return; - - if(!$objDefinition->isContainer(ilObject::_lookupType($this->obj_id))) - return false; - - if(is_object($this->getContainerObject()) && - $this->getContainerObject() instanceof ilContainerGUI) - { - $this->ctrl->setParameter($this->getContainerObject(), "type", ""); - $this->ctrl->setParameter($this->getContainerObject(), "item_ref_id", ""); - $this->ctrl->setParameter($this->getContainerObject(), "active_node", ""); - // bugfix mantis 24559 - // undoing an erroneous change inside mantis 23516 by adding "Download Multiple Objects"-functionality for non-admins - // as they don't have the possibility to use the multi-download-capability of the manage-tab - $user_id = $this->user->getId(); - $hasAdminAccess = $this->access->checkAccessOfUser($user_id, "crs_admin", $this->ctrl->getCmd(), $_GET['ref_id']); - // to still prevent duplicate download functions for admins the following if-else statement keeps the redirection for admins - // while letting other course members access the original multi-download functionality - if($hasAdminAccess) - { - $cmd = $_GET["cmd"] == "enableAdministrationPanel" ? "render" : "enableAdministrationPanel"; - } - else - { - $cmd = $_GET["cmd"] == "enableMultiDownload" ? "render" : "enableMultiDownload"; - } - $cmd_link = $this->ctrl->getLinkTarget($this->getContainerObject(), $cmd); - $this->insertCommand($cmd_link, $this->lng->txt("download_multiple_objects")); - return true; - } - - return false; - } - - function enableDownloadCheckbox($a_ref_id, $a_value) - { - $ilAccess = $this->access; - - // TODO: delegate to list object class! - if (!$this->getContainerObject()->isActiveAdministrationPanel() || $_SESSION["clipboard"]) - { - if (in_array($this->type, array("file", "fold")) && - $ilAccess->checkAccess("read", "", $a_ref_id, $this->type)) - { - $this->download_checkbox_state = self::DOWNLOAD_CHECKBOX_ENABLED; - } - else - { - $this->download_checkbox_state = self::DOWNLOAD_CHECKBOX_DISABLED; - } - } - else - { - $this->download_checkbox_state = self::DOWNLOAD_CHECKBOX_NONE; - } - } - - function getDownloadCheckboxState() - { - return $this->download_checkbox_state; - } - - /** - * Insert js/ajax links into template - */ - static function prepareJsLinks($a_redraw_url, $a_notes_url, $a_tags_url, $a_tpl = null) - { - global $DIC; - - $tpl = $DIC["tpl"]; - - if (is_null($a_tpl)) - { - $a_tpl = $tpl; - } - - if($a_notes_url) - { - include_once("./Services/Notes/classes/class.ilNoteGUI.php"); - ilNoteGUI::initJavascript($a_notes_url, IL_NOTE_PRIVATE, $a_tpl); - } - - if($a_tags_url) - { - include_once("./Services/Tagging/classes/class.ilTaggingGUI.php"); - ilTaggingGUI::initJavascript($a_tags_url, $a_tpl); - } - - if($a_redraw_url) - { - $a_tpl->addOnLoadCode("il.Object.setRedrawAHUrl('". - $a_redraw_url."');"); - } - } - - /** - * Set sub object identifier - * - * @param string $a_type - * @param int $a_id - */ - function setHeaderSubObject($a_type, $a_id) - { - $this->sub_obj_type = $a_type; - $this->sub_obj_id = (int)$a_id; - } - - /** - * - * @param string $a_id - * @param string $a_img - * @param string $a_tooltip - * @param string $a_onclick - * @param string $a_status_text - * @param string $a_href - */ - function addHeaderIcon($a_id, $a_img, $a_tooltip = null, $a_onclick = null, $a_status_text = null, $a_href = null) - { - $this->header_icons[$a_id] = array("img" => $a_img, - "tooltip" => $a_tooltip, - "onclick" => $a_onclick, - "status_text" => $a_status_text, - "href" => $a_href); - } - - /** - * - * @param string $a_id - * @param string $a_html - */ - function addHeaderIconHTML($a_id, $a_html) - { - $this->header_icons[$a_id] = $a_html; - } - - /** - * - * @param string $a_id - * @param string $a_html - */ - function addHeaderGlyph($a_id, $a_glyph, $a_onclick = null) - { - $this->header_icons[$a_id] = array("glyph" => $a_glyph, "onclick" => $a_onclick); - } - - function setAjaxHash($a_hash) - { - $this->ajax_hash = $a_hash; - } - - /** - * Get header action - * - * @return string - */ - function getHeaderAction(ilTemplate $a_main_tpl = null) - { - global $DIC; - - $ilUser = $this->user; - $lng = $this->lng; - - if ($a_main_tpl == null) - { - $main_tpl = $DIC["tpl"]; - } - else - { - $main_tpl = $a_main_tpl; - } - - $htpl = new ilTemplate("tpl.header_action.html", true, true, "Services/Repository"); - - $redraw_js = "il.Object.redrawActionHeader();"; - - // tags - if($this->tags_enabled) - { - include_once("./Services/Tagging/classes/class.ilTagging.php"); - $tags = ilTagging::getTagsForUserAndObject($this->obj_id, - ilObject::_lookupType($this->obj_id), 0, "", $ilUser->getId()); - if (count($tags) > 0) - { - include_once("./Services/Tagging/classes/class.ilTaggingGUI.php"); - $lng->loadLanguageModule("tagging"); - /*$this->addHeaderIcon("tags", - ilUtil::getImagePath("icon_tag.svg"), - $lng->txt("tagging_tags").": ".count($tags), - ilTaggingGUI::getListTagsJSCall($this->ajax_hash, $redraw_js), - count($tags));*/ - - $f = $this->ui->factory(); - $this->addHeaderGlyph("tags", $f->glyph()->tag("#") - ->withCounter($f->counter()->status((int) count($tags))), - ilTaggingGUI::getListTagsJSCall($this->ajax_hash, $redraw_js)); - - } - } - - // notes and comments - $comments_enabled = $this->isCommentsActivated($this->type, $this->ref_id, $this->obj_id, true, false); - if($this->notes_enabled || $comments_enabled) - { - include_once("./Services/Notes/classes/class.ilNote.php"); - include_once("./Services/Notes/classes/class.ilNoteGUI.php"); - $type = ($this->sub_obj_type == "") - ? $this->type - : $this->sub_obj_type; - $cnt = ilNote::_countNotesAndComments($this->obj_id, $this->sub_obj_id, $type); - - if($this->notes_enabled && $cnt[$this->obj_id][IL_NOTE_PRIVATE] > 0) - { - /*$this->addHeaderIcon("notes", - ilUtil::getImagePath("note_unlabeled.svg"), - $lng->txt("private_notes").": ".$cnt[$this->obj_id][IL_NOTE_PRIVATE], - ilNoteGUI::getListNotesJSCall($this->ajax_hash, $redraw_js), - $cnt[$this->obj_id][IL_NOTE_PRIVATE] - );*/ - - $f = $this->ui->factory(); - $this->addHeaderGlyph("notes", $f->glyph()->note("#") - ->withCounter($f->counter()->status((int) $cnt[$this->obj_id][IL_NOTE_PRIVATE])), - ilNoteGUI::getListNotesJSCall($this->ajax_hash, $redraw_js)); - - } - - if($comments_enabled && $cnt[$this->obj_id][IL_NOTE_PUBLIC] > 0) - { - $lng->loadLanguageModule("notes"); - - /*$this->addHeaderIcon("comments", - ilUtil::getImagePath("comment_unlabeled.svg"), - $lng->txt("notes_public_comments").": ".$cnt[$this->obj_id][IL_NOTE_PUBLIC], - ilNoteGUI::getListCommentsJSCall($this->ajax_hash, $redraw_js), - $cnt[$this->obj_id][IL_NOTE_PUBLIC]);*/ - - $f = $this->ui->factory(); - $this->addHeaderGlyph("comments", $f->glyph()->comment("#") - ->withCounter($f->counter()->status((int) $cnt[$this->obj_id][IL_NOTE_PUBLIC])), - ilNoteGUI::getListCommentsJSCall($this->ajax_hash, $redraw_js)); - - } - } - - // rating - if($this->rating_enabled) - { - include_once("./Services/Rating/classes/class.ilRatingGUI.php"); - $rating_gui = new ilRatingGUI(); - $rating_gui->enableCategories($this->rating_categories_enabled); - // never rate sub objects from header action! - $rating_gui->setObject($this->obj_id, $this->type); - if($this->rating_text) - { - $rating_gui->setYourRatingText($this->rating_text); - } - - $this->ctrl->setParameterByClass("ilRatingGUI", "cadh", $this->ajax_hash); - $this->ctrl->setParameterByClass("ilRatingGUI", "rnsb", true); - if($this->rating_ctrl_path) - { - $rating_gui->setCtrlPath($this->rating_ctrl_path); - $ajax_url = $this->ctrl->getLinkTargetByClass($this->rating_ctrl_path, "saveRating", "", true, false); - } - else - { - // ??? - $ajax_url = $this->ctrl->getLinkTargetByClass("ilRatingGUI", "saveRating", "", true, false); - } - $main_tpl->addOnLoadCode("il.Object.setRatingUrl('".$ajax_url."');"); - $this->addHeaderIconHTML("rating", - $rating_gui->getHtml(true, - $this->checkCommandAccess("read", "", $this->ref_id, $this->type), - "il.Object.saveRating(%rating%);")); - } - - if($this->header_icons) - { - include_once("./Services/UIComponent/Tooltip/classes/class.ilTooltipGUI.php"); - - $chunks = array(); - foreach($this->header_icons as $id => $attr) - { - $id = "headp_".$id; - - if(is_array($attr)) - { - if($attr["glyph"]) - { - if ($attr["onclick"]) - { - $htpl->setCurrentBlock("prop_glyph_oc"); - $htpl->setVariable("GLYPH_ONCLICK", $attr["onclick"]); - $htpl->parseCurrentBlock(); - } - $renderer = $this->ui->renderer(); - $html = $renderer->render($attr["glyph"]); - $htpl->setCurrentBlock("prop_glyph"); - $htpl->setVariable("GLYPH", $html); - $htpl->parseCurrentBlock(); - } - else - { - if ($attr["onclick"]) - { - $htpl->setCurrentBlock("onclick"); - $htpl->setVariable("PROP_ONCLICK", $attr["onclick"]); - $htpl->parseCurrentBlock(); - } - - if ($attr["status_text"]) - { - $htpl->setCurrentBlock("status"); - $htpl->setVariable("PROP_TXT", $attr["status_text"]); - $htpl->parseCurrentBlock(); - } - - - $htpl->setCurrentBlock("prop"); - if ($attr["href"] || $attr["onclick"]) - { - $htpl->setVariable("TAG", "a"); - } - else - { - $htpl->setVariable("TAG", "span"); - } - $htpl->setVariable("PROP_ID", $id); - $htpl->setVariable("IMG", ilUtil::img($attr["img"])); - if ($attr["href"] != "") - { - $htpl->setVariable("PROP_HREF", ' href="'.$attr["href"].'" '); - } - $htpl->parseCurrentBlock(); - - if ($attr["tooltip"]) - { - ilTooltipGUI::addTooltip($id, $attr["tooltip"]); - } - } - } - else - { - $chunks[] = $attr; - } - } - - if(sizeof($chunks)) - { - $htpl->setVariable("PROP_CHUNKS", - implode("   ", $chunks)."   "); - } - } - - $htpl->setVariable("ACTION_DROP_DOWN", - $this->insertCommands(false, false, "", true)); - - return $htpl->get(); - } - - - /** - * workaround: all links into the repository (from outside) - * must tell repository to setup the frameset - */ - function appendRepositoryFrameParameter($a_link) - { - // we should get rid of this nonsense with 4.4 (alex) - if ((strtolower($_GET["baseClass"]) != "ilrepositorygui") && - is_int(strpos($a_link,"baseClass=ilRepositoryGUI"))) - { - if ($this->type != "frm") - { - $a_link = - ilUtil::appendUrlParameterString($a_link, "rep_frame=1"); - } - } - - return $a_link; - } - - protected function modifyTitleLink($a_default_link) - { - if($this->default_command_params) - { - $params = array(); - foreach($this->default_command_params as $name => $value) - { - $params[] = $name.'='.$value; - } - $params = implode('&', $params); - - - // #12370 - if(!stristr($a_default_link, '?')) - { - $a_default_link = ($a_default_link.'?'.$params); - } - else - { - $a_default_link = ($a_default_link.'&'.$params); - } - } - return $a_default_link; - } - - /** - * workaround: SAHS in new javavasript-created window or iframe - */ - function modifySAHSlaunch($a_link,$wtarget) - { - global $DIC; - - if (strstr($a_link, 'ilSAHSPresentationGUI') && !$this->offline_mode) - { - include_once 'Modules/ScormAicc/classes/class.ilObjSAHSLearningModule.php'; - $sahs_obj = new ilObjSAHSLearningModule($this->ref_id); - $om = $sahs_obj->getOpenMode(); - $width = $sahs_obj->getWidth(); - $height = $sahs_obj->getHeight(); - if ( ($om == 5 || $om == 1) && $width > 0 && $height > 0) $om++; - if ($om != 0 && !$DIC['ilBrowser']->isMobile()) - { - $this->default_command["frame"]=""; - $a_link = "javascript:void(0); onclick=startSAHS('".$a_link."','".$wtarget."',".$om.",".$width.",".$height.");"; - } - } - return $a_link; - } - - /** - * insert path - */ - function insertPath() - { - $lng = $this->lng; - - if($this->getPathStatus() != false) - { - if(!$this->path_gui instanceof \ilPathGUI) { - $path_gui = new \ilPathGUI(); - } else { - $path_gui = $this->path_gui; - } - - $path_gui->enableTextOnly(!$this->path_linked); - $path_gui->setUseImages(false); - - $start_node = $this->path_start_node - ? $this->path_start_node - : ROOT_FOLDER_ID; - - $this->tpl->setCurrentBlock("path_item"); - $this->tpl->setVariable('PATH_ITEM',$path_gui->getPath($start_node,$this->ref_id)); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setCurrentBlock("path"); - $this->tpl->setVariable("TXT_LOCATION", $lng->txt("locator")); - $this->tpl->parseCurrentBlock(); - return true; - } - } - - /** - * insert progress info - * - * @access public - * @return - */ - public function insertProgressInfo() - { - return true; - } - - - /** - * Insert icons and checkboxes - */ - function insertIconsAndCheckboxes() - { - $lng = $this->lng; - $objDefinition = $this->obj_definition; - - $cnt = 0; - if ($this->getCheckboxStatus()) - { - $this->tpl->setCurrentBlock("check"); - $this->tpl->setVariable("VAL_ID", $this->getCommandId()); - $this->tpl->parseCurrentBlock(); - $cnt += 1; - } - else if ($this->getDownloadCheckboxState() != self::DOWNLOAD_CHECKBOX_NONE) - { - $this->tpl->setCurrentBlock("check_download"); - if ($this->getDownloadCheckboxState() == self::DOWNLOAD_CHECKBOX_ENABLED) - $this->tpl->setVariable("VAL_ID", $this->getCommandId()); - else - $this->tpl->setVariable("VAL_VISIBILITY", "visibility: hidden;\" disabled=\"disabled"); - $this->tpl->parseCurrentBlock(); - $cnt += 1; - } - elseif($this->getExpandStatus()) - { - $this->tpl->setCurrentBlock('expand'); - - if($this->isExpanded()) - { - $this->ctrl->setParameter($this->container_obj,'expand',-1 * $this->obj_id); - // "view" added, see #19922 - $this->tpl->setVariable('EXP_HREF',$this->ctrl->getLinkTarget($this->container_obj,'view',$this->getUniqueItemId(true))); - $this->ctrl->clearParameters($this->container_obj); - $this->tpl->setVariable('EXP_IMG',ilUtil::getImagePath('tree_exp.svg')); - $this->tpl->setVariable('EXP_ALT',$this->lng->txt('collapse')); - } - else - { - $this->ctrl->setParameter($this->container_obj,'expand',$this->obj_id); - // "view" added, see #19922 - $this->tpl->setVariable('EXP_HREF',$this->ctrl->getLinkTarget($this->container_obj,'view',$this->getUniqueItemId(true))); - $this->ctrl->clearParameters($this->container_obj); - $this->tpl->setVariable('EXP_IMG',ilUtil::getImagePath('tree_col.svg')); - $this->tpl->setVariable('EXP_ALT',$this->lng->txt('expand')); - } - - $this->tpl->parseCurrentBlock(); - $cnt += 1; - } - - if ($this->getIconStatus()) - { - if ($cnt == 1) - { - $this->tpl->touchBlock("i_1"); // indent - } - - // icon link - if ($this->title_link_disabled || !$this->default_command || (!$this->getCommandsStatus() && !$this->restrict_to_goto)) - { - } - else - { - $this->tpl->setCurrentBlock("icon_link_s"); - - if ($this->default_command["frame"] != "") - { - $this->tpl->setVariable("ICON_TAR", "target='".$this->default_command["frame"]."'"); - } - - $this->tpl->setVariable("ICON_HREF", - $this->default_command["link"]); - $this->tpl->parseCurrentBlock(); - $this->tpl->touchBlock("icon_link_e"); - } - - $this->tpl->setCurrentBlock("icon"); - if (!$objDefinition->isPlugin($this->getIconImageType())) - { - $this->tpl->setVariable("ALT_ICON", $lng->txt("icon")." ".$lng->txt("obj_".$this->getIconImageType())); - } - else - { - include_once("Services/Component/classes/class.ilPlugin.php"); - $this->tpl->setVariable("ALT_ICON", $lng->txt("icon")." ". - ilObjectPlugin::lookupTxtById($this->getIconImageType(), "obj_".$this->getIconImageType())); - } - - $this->tpl->setVariable( - "SRC_ICON", - $this->getTypeIcon() - ); - $this->tpl->parseCurrentBlock(); - $cnt += 1; - } - - $this->tpl->touchBlock("d_".$cnt); // indent main div - } - - /** - * Get object type specific type icon - * @return string - */ - public function getTypeIcon() - { - return ilObject::_getIcon( - $this->obj_id, - 'small', - $this->getIconImageType() - ); - } - - /** - * Insert subitems - */ - function insertSubItems() - { - foreach ($this->sub_item_html as $sub_html) - { - $this->tpl->setCurrentBlock("subitem"); - $this->tpl->setVariable("SUBITEM", $sub_html); - $this->tpl->parseCurrentBlock(); - } - } - - /** - * Insert field for positioning - */ - function insertPositionField() - { - if ($this->position_enabled) - { - $this->tpl->setCurrentBlock("position"); - $this->tpl->setVariable("POS_ID", $this->position_field_index); - $this->tpl->setVariable("POS_VAL", $this->position_value); - $this->tpl->parseCurrentBlock(); - } - } - - /** - * returns whether any admin commands (link, delete, cut) - * are included in the output - */ - function adminCommandsIncluded() - { - return $this->adm_commands_included; - } - - /** - * Store access cache - */ - function storeAccessCache() - { - $ilUser = $this->user; - if($this->acache->getLastAccessStatus() == "miss" && - !$this->prevent_access_caching) - { - $this->acache->storeEntry($ilUser->getId().":".$this->ref_id, - serialize($this->access_cache), $this->ref_id); - } - } - - /** - * Get all item information (title, commands, description) in HTML - * - * @access public - * @param int $a_ref_id item reference id - * @param int $a_obj_id item object id - * @param int $a_title item title - * @param int $a_description item description - * @param bool $a_use_asynch - * @param bool $a_get_asynch_commands - * @param string $a_asynch_url - * @param bool $a_context workspace/tree context - * @return string html code - */ - function getListItemHTML($a_ref_id, $a_obj_id, $a_title, $a_description, - $a_use_asynch = false, $a_get_asynch_commands = false, $a_asynch_url = "") - { - $ilUser = $this->user; - - // this variable stores wheter any admin commands - // are included in the output - $this->adm_commands_included = false; - - // only for permformance exploration - $type = ilObject::_lookupType($a_obj_id); - - // initialization - $this->initItem($a_ref_id, $a_obj_id, $a_title, $a_description); - - // prepare ajax calls - include_once "Services/Object/classes/class.ilCommonActionDispatcherGUI.php"; - if($this->context == self::CONTEXT_REPOSITORY) - { - $node_type = ilCommonActionDispatcherGUI::TYPE_REPOSITORY; - } - else - { - $node_type = ilCommonActionDispatcherGUI::TYPE_WORKSPACE; - } - $this->setAjaxHash(ilCommonActionDispatcherGUI::buildAjaxHash($node_type, $a_ref_id, $type, $a_obj_id)); - - if ($a_use_asynch && $a_get_asynch_commands) - { - return $this->insertCommands(true, true); - } - - if($this->rating_enabled) - { - if(ilRating::hasRatingInListGUI($this->obj_id, $this->type)) - { - $may_rate = $this->checkCommandAccess("read", "", $this->ref_id, $this->type); - - $rating = new ilRatingGUI(); - $rating->setObject($this->obj_id, $this->type); -/* $this->addCustomProperty( - $this->lng->txt("rating_average_rating"), - $rating->getListGUIProperty($this->ref_id, $may_rate, $this->ajax_hash, $this->parent_ref_id), - false, - true - );*/ - $this->addCustomProperty( - "", - $rating->getListGUIProperty($this->ref_id, $may_rate, $this->ajax_hash, $this->parent_ref_id), - false, - true - ); - } - } - - // read from cache - include_once("Services/Object/classes/class.ilListItemAccessCache.php"); - $this->acache = new ilListItemAccessCache(); - $cres = $this->acache->getEntry($ilUser->getId().":".$a_ref_id); - if($this->acache->getLastAccessStatus() == "hit") - { - $this->access_cache = unserialize($cres); - } - else - { - // write to cache - $this->storeAccessCache(); - } - - // visible check - if (!$this->checkCommandAccess("visible", "", $a_ref_id, "", $a_obj_id)) - { - $this->resetCustomData(); - return ""; - } - - // BEGIN WEBDAV - if($type=='file' AND ilObjFileAccess::_isFileHidden($a_title)) - { - $this->resetCustomData(); - return ""; - } - // END WEBDAV - - - $this->tpl = new ilTemplate(static::$tpl_file_name, true, true, - static::$tpl_component, "DEFAULT", false, true); - - if($this->getCommandsStatus()) - { - if (!$this->getSeparateCommands()) - { - $this->tpl->setVariable("COMMAND_SELECTION_LIST", - $this->insertCommands($a_use_asynch, $a_get_asynch_commands, $a_asynch_url)); - } - } - - if($this->getProgressInfoStatus()) - { - $this->insertProgressInfo(); - } - - // insert title and describtion - $this->insertTitle(); - if (!$this->isMode(IL_LIST_AS_TRIGGER)) - { - if ($this->getDescriptionStatus()) - { - $this->insertDescription(); - } - } - - if($this->getSearchFragmentStatus()) - { - $this->insertSearchFragment(); - } - if($this->enabledRelevance()) - { - $this->insertRelevance(); - } - - // properties - if ($this->getPropertiesStatus()) - { - $this->insertProperties(); - } - - // notice properties - if($this->getNoticePropertiesStatus()) - { - $this->insertNoticeProperties(); - } - - // preconditions - if ($this->getPreconditionsStatus()) - { - $this->insertPreconditions(); - } - - // path - $this->insertPath(); - - if($this->getItemDetailLinkStatus()) - { - $this->insertItemDetailLinks(); - } - - // icons and checkboxes - $this->insertIconsAndCheckboxes(); - - // input field for position - $this->insertPositionField(); - - // subitems - $this->insertSubItems(); - - // file upload - if ($this->isFileUploadAllowed()) - { - $this->insertFileUpload(); - } - - $this->resetCustomData(); - - $this->tpl->setVariable("DIV_CLASS",'ilContainerListItemOuter'); - $this->tpl->setVariable("DIV_ID", 'data-list-item-id="'.$this->getUniqueItemId(true).'" id = "'.$this->getUniqueItemId(true).'"'); - $this->tpl->setVariable("ADDITIONAL", $this->getAdditionalInformation()); - - // #11554 - make sure that internal ids are reset - if (is_object($this->getContainerObject())) - { - $this->ctrl->setParameter($this->getContainerObject(), "item_ref_id", ""); - } - - return $this->tpl->get(); - } - - /** - * reset properties and commands - */ - protected function resetCustomData() - { - // #15747 - $this->cust_prop = array(); - $this->cust_commands = array(); - $this->sub_item_html = array(); - $this->position_enabled = false; - } - - /** - * Set current parent ref id to enable unique js-ids (sessions, etc.) - * - * @param string $a_ref_id - */ - public function setParentRefId($a_ref_id) - { - $this->parent_ref_id = $a_ref_id; - } - - /** - * Get unique item identifier (for js-actions) - * - * @param bool $a_as_div - * @return string - */ - public function getUniqueItemId($a_as_div = false) - { - // use correct id for references - $id_ref = ($this->reference_ref_id > 0) - ? $this->reference_ref_id - : $this->ref_id; - - // add unique identifier for preconditions (objects can appear twice in same container) - if($this->condition_depth) - { - $id_ref .= "_pc".$this->condition_depth; - } - - // unique - $id_ref .= "_pref_".$this->parent_ref_id; - - if(!$a_as_div) - { - return $id_ref; - } - else - { - // action menu [yellow] toggle - return "lg_div_".$id_ref; - } - } - - /** - * Get commands HTML (must be called after get list item html) - */ - function getCommandsHTML() - { - return $this->insertCommands(); - } - - /** - * Returns whether current item is a block in a side column or not - */ - function isSideBlock() - { - return false; - } - - /** - * - * @access public - * @params boolean $a_bold_title set the item title bold - */ - public function setBoldTitle($a_bold_title) - { - $this->bold_title = $a_bold_title; - - } - - /** - * - * @access public - * @return boolean returns if the item title is bold or not - */ - public function isTitleBold() - { - return $this->bold_title; - } - - /** - * Preload common properties - * - * @param - * @return - */ - static function preloadCommonProperties($a_obj_ids, $a_context) - { - global $DIC; - - $lng = $DIC->language(); - $ilSetting = $DIC->settings(); - $ilUser = $DIC->user(); - - if($a_context == self::CONTEXT_REPOSITORY) - { - $active_notes = !$ilSetting->get("disable_notes"); - $active_comments = !$ilSetting->get("disable_comments"); - - if($active_notes || $active_comments) - { - include_once("./Services/Notes/classes/class.ilNote.php"); - } - - if($active_comments) - { - // needed for action - self::$comments_activation = ilNote::getRepObjActivation($a_obj_ids); - } - - // properties are optional - if($ilSetting->get('comments_tagging_in_lists')) - { - if($active_notes || $active_comments) - { - self::$cnt_notes = ilNote::_countNotesAndCommentsMultiple($a_obj_ids, true); - - $lng->loadLanguageModule("notes"); - } - - $tags_set = new ilSetting("tags"); - if($tags_set->get("enable")) - { - $all_users = $tags_set->get("enable_all_users"); - - include_once("./Services/Tagging/classes/class.ilTagging.php"); - if(!$ilSetting->get('comments_tagging_in_lists_tags')) - { - self::$cnt_tags = ilTagging::_countTags($a_obj_ids, $all_users); - } - else - { - $tag_user_id = null; - if(!$all_users) - { - $tag_user_id = $ilUser->getId(); - } - self::$tags = ilTagging::_getListTagsForObjects($a_obj_ids, $tag_user_id); - } - - $lng->loadLanguageModule("tagging"); - } - } - - $lng->loadLanguageModule("rating"); - } - - self::$preload_done = true; - } - - /** - * Check comments status against comments settings and context - * - * @param string $a_type - * @param int $a_ref_id - * @param int $a_obj_id - * @param bool $a_header_actions - * @param bool $a_check_write_access - * @return bool - */ - protected function isCommentsActivated($a_type, $a_ref_id, $a_obj_id, $a_header_actions, $a_check_write_access = true) - { - if($this->comments_enabled) - { - if(!$this->comments_settings_enabled) - { - return true; - } - if($a_check_write_access && $this->checkCommandAccess('write','', $a_ref_id, $a_type)) - { - return true; - } - // fallback to single object check if no preloaded data - // only the repository does preloadCommonProperties() yet - if(!$a_header_actions && self::$preload_done) - { - if(self::$comments_activation[$a_obj_id][$a_type]) - { - return true; - } - } - else - { - include_once("./Services/Notes/classes/class.ilNote.php"); - if(ilNote::commentsActivated($a_obj_id, 0, $a_type)) - { - return true; - } - } - } - return false; - } - - /** - * enable timings link - * - * @access public - * @param bool - * @return - */ - public function enableTimings($a_status) - { - $this->timings_enabled = (bool)$a_status; - } - - /** - * Gets a value indicating whether file uploads to this object are allowed or not. - * - * @return bool true, if file upload is allowed; otherwise, false. - */ - public function isFileUploadAllowed() - { - // check if file upload allowed - include_once("./Services/FileUpload/classes/class.ilFileUploadUtil.php"); - return ilFileUploadUtil::isUploadAllowed($this->ref_id, $this->type); - } - - /** - * Inserts a file upload component - */ - public function insertFileUpload() - { - include_once("./Services/FileUpload/classes/class.ilFileUploadGUI.php"); - ilFileUploadGUI::initFileUpload(); - - $upload = new ilFileUploadGUI($this->getUniqueItemId(true), $this->ref_id); - - $this->tpl->setCurrentBlock("fileupload"); - $this->tpl->setVariable("FILE_UPLOAD", $upload->getHTML()); - $this->tpl->parseCurrentBlock(); - } + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilObjectDefinition + */ + protected $obj_definition; + + /** + * @var ilTree + */ + protected $tree; + + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var ilTemplate + */ + protected $tpl; + + const DETAILS_MINIMAL = 10; + const DETAILS_SEARCH = 20 ; + const DETAILS_ALL = 30; + + const CONTEXT_REPOSITORY = 1; + const CONTEXT_WORKSPACE = 2; + const CONTEXT_WORKSPACE_SHARING = 4; + const CONTEXT_PERSONAL_DESKTOP = 5; + const CONTEXT_SEARCH = 6; + + const DOWNLOAD_CHECKBOX_NONE = 0; + const DOWNLOAD_CHECKBOX_ENABLED = 1; + const DOWNLOAD_CHECKBOX_DISABLED = 2; + + public $ctrl; + public $description_enabled = true; + public $preconditions_enabled = true; + public $properties_enabled = true; + public $notice_properties_enabled = true; + public $commands_enabled = true; + public $cust_prop = array(); + public $cust_commands = array(); + public $info_screen_enabled = false; + public $condition_depth = 0; + public $std_cmd_only = false; + public $sub_item_html = array(); + public $multi_download_enabled = false; + public $download_checkbox_state = self::DOWNLOAD_CHECKBOX_NONE; + + protected $obj_id; + protected $ref_id; + protected $type; + protected $sub_obj_id; + protected $sub_obj_type; + + protected $substitutions = null; + protected $substitutions_enabled = false; + + protected $icons_enabled = false; + protected $checkboxes_enabled = false; + protected $position_enabled = false; + protected $progress_enabled = false; + protected $item_detail_links_enabled = false; + protected $item_detail_links = array(); + protected $item_detail_links_intro = ''; + + protected $search_fragments_enabled = false; + protected $search_fragment = ''; + protected $path_linked = false; + + protected $enabled_relevance = false; + protected $relevance = 0; + + protected $expand_enabled = false; + protected $is_expanded = true; + protected $bold_title = false; + + protected $copy_enabled = true; + + protected $details_level = self::DETAILS_ALL; + + protected $reference_ref_id = false; + protected $separate_commands = false; + protected $search_fragment_enabled = false; + protected $additional_information = false; + protected $static_link_enabled = false; + + protected $repository_transfer_enabled = false; + protected $shared = false; + protected $restrict_to_goto = false; + + protected $comments_enabled = false; + protected $comments_settings_enabled = false; + protected $notes_enabled = false; + protected $tags_enabled = false; + + protected $rating_enabled = false; + protected $rating_categories_enabled = false; + protected $rating_text = false; + protected $rating_ctrl_path = false; + + protected $timings_enabled = true; + protected $force_visible_only = false; + protected $prevent_duplicate_commands = array(); + protected $parent_ref_id; + protected $context; + + protected static $cnt_notes = array(); + protected static $cnt_tags = array(); + protected static $tags = array(); + protected static $comments_activation = array(); + protected static $preload_done = false; + + protected $title_link = ''; + protected $title_link_disabled = false; + + protected static $js_unique_id = 0; + + + protected static $tpl_file_name = "tpl.container_list_item.html"; + protected static $tpl_component = "Services/Container"; + + /** + * @var ilPathGUI|null + */ + protected $path_gui = null; + + /** + * @var \ILIAS\DI\UIServices + */ + protected $ui; + + /** + * constructor + * + */ + public function __construct($a_context = self::CONTEXT_REPOSITORY) + { + global $DIC; + $this->access = $DIC->access(); + $this->user = $DIC->user(); + $this->obj_definition = $DIC["objDefinition"]; + $this->tree = $DIC->repositoryTree(); + $this->settings = $DIC->settings(); + + $this->ui = $DIC->ui(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->mode = IL_LIST_FULL; + $this->path_enabled = false; + $this->context = $a_context; + + $this->enableComments(false); + $this->enableNotes(false); + $this->enableTags(false); + + // unique js-ids + $this->setParentRefId((int) $_REQUEST["ref_id"]); + + //echo "list"; + $this->init(); + + include_once('Services/LDAP/classes/class.ilLDAPRoleGroupMapping.php'); + $this->ldap_mapping = ilLDAPRoleGroupMapping::_getInstance(); + + $this->lng->loadLanguageModule("obj"); + } + + + /** + * set the container object (e.g categorygui) + * Used for link, delete ... commands + * + * this method should be overwritten by derived classes + */ + public function setContainerObject($container_obj) + { + $this->container_obj = $container_obj; + } + + /** + * get container object + * + * @access public + * @param + * @return object container + */ + public function getContainerObject() + { + return $this->container_obj; + } + + + /** + * initialisation + * + * this method should be overwritten by derived classes + */ + public function init() + { + // Create static links for default command (linked title) or not + $this->static_link_enabled = true; + $this->delete_enabled = true; + $this->cut_enabled = true; + $this->subscribe_enabled = true; + $this->link_enabled = false; + $this->copy_enabled = false; + $this->progress_enabled = false; + $this->notice_properties_enabled = true; + $this->info_screen_enabled = false; + $this->type = ""; // "cat", "course", ... + $this->gui_class_name = ""; // "ilobjcategorygui", "ilobjcoursegui", ... + + // general commands array, e.g. + include_once('./Services/Object/classes/class.ilObjectAccess.php'); + $this->commands = ilObjectAccess::_getCommands(); + } + + // Single get set methods + /** + * En/disable properties + * + * @param bool + * @return void + */ + public function enableProperties($a_status) + { + $this->properties_enabled = $a_status; + + return; + } + /** + * + * + * @param bool + * @return bool + */ + public function getPropertiesStatus() + { + return $this->properties_enabled; + } + /** + * En/disable preconditions + * + * @param bool + * @return void + */ + public function enablePreconditions($a_status) + { + $this->preconditions_enabled = $a_status; + + return; + } + + public function getNoticePropertiesStatus() + { + return $this->notice_properties_enabled; + } + + /** + * En/disable notices + * + * @param bool + * @return void + */ + public function enableNoticeProperties($a_status) + { + $this->notice_properties_enabled = $a_status; + + return; + } + /** + * + * + * @param bool + * @return bool + */ + public function getPreconditionsStatus() + { + return $this->preconditions_enabled; + } + /** + * En/disable description + * + * @param bool + * @return void + */ + public function enableDescription($a_status) + { + $this->description_enabled = $a_status; + + return; + } + /** + * + * + * @param bool + * @return bool + */ + public function getDescriptionStatus() + { + return $this->description_enabled; + } + + /** + * Show hide search result fragments + * + * @param bool + * @return bool + */ + public function getSearchFragmentStatus() + { + return $this->search_fragment_enabled; + } + + /** + * En/disable description + * + * @param bool + * @return void + */ + public function enableSearchFragments($a_status) + { + $this->search_fragment_enabled = $a_status; + + return; + } + + /** + * Enable linked path + * @param bool + * @return + */ + public function enableLinkedPath($a_status) + { + $this->path_linked = $a_status; + } + + /** + * enabled relevance + * @return + */ + public function enabledRelevance() + { + return $this->enabled_relevance; + } + + /** + * enable relevance + * @return + */ + public function enableRelevance($a_status) + { + $this->enabled_relevance = $a_status; + } + + /** + * set relevance + * @param int + * @return + */ + public function setRelevance($a_rel) + { + $this->relevance = $a_rel; + } + + /** + * get relevance + * @param + * @return + */ + public function getRelevance() + { + return $this->relevance; + } + + /** + * En/Dis-able icons + * + * @param boolean icons on/off + */ + public function enableIcon($a_status) + { + $this->icons_enabled = $a_status; + } + + /** + * Are icons enabled? + * + * @return boolean icons enabled? + */ + public function getIconStatus() + { + return $this->icons_enabled; + } + + /** + * En/Dis-able checkboxes + * + * @param boolean checkbox on/off + */ + public function enableCheckbox($a_status) + { + $this->checkboxes_enabled = $a_status; + } + + /** + * Are checkboxes enabled? + * + * @return boolean icons enabled? + */ + public function getCheckboxStatus() + { + return $this->checkboxes_enabled; + } + + /** + * En/Dis-able expand/collapse link + * + * @param boolean checkbox on/off + */ + public function enableExpand($a_status) + { + $this->expand_enabled = $a_status; + } + + /** + * Is expand/collapse enabled + * + * @return boolean icons enabled? + */ + public function getExpandStatus() + { + return $this->expand_enabled; + } + + public function setExpanded($a_status) + { + $this->is_expanded = $a_status; + } + + public function isExpanded() + { + return $this->is_expanded; + } + /** + * Set position input field + * + * @param string $a_field_index e.g. "[crs][34]" + * @param string $a_position_value e.g. "2.0" + */ + public function setPositionInputField($a_field_index, $a_position_value) + { + $this->position_enabled = true; + $this->position_field_index = $a_field_index; + $this->position_value = $a_position_value; + } + + /** + * En/disable delete + * + * @param bool + * @return void + */ + public function enableDelete($a_status) + { + $this->delete_enabled = $a_status; + + return; + } + /** + * + * + * @param bool + * @return bool + */ + public function getDeleteStatus() + { + return $this->delete_enabled; + } + + /** + * En/disable cut + * + * @param bool + * @return void + */ + public function enableCut($a_status) + { + $this->cut_enabled = $a_status; + + return; + } + /** + * + * @param bool + * @return bool + */ + public function getCutStatus() + { + return $this->cut_enabled; + } + + /** + * En/disable copy + * + * @param bool + * @return void + */ + public function enableCopy($a_status) + { + $this->copy_enabled = $a_status; + + return; + } + /** + * + * @param bool + * @return bool + */ + public function getCopyStatus() + { + return $this->copy_enabled; + } + + /** + * En/disable subscribe + * + * @param bool + * @return void + */ + public function enableSubscribe($a_status) + { + $this->subscribe_enabled = $a_status; + + return; + } + /** + * + * @param bool + * @return bool + */ + public function getSubscribeStatus() + { + return $this->subscribe_enabled; + } + + /** + * En/disable link + * + * @param bool + * @return void + */ + public function enableLink($a_status) + { + $this->link_enabled = $a_status; + + return; + } + /** + * + * @param bool + * @return bool + */ + public function getLinkStatus() + { + return $this->link_enabled; + } + + /** + * En/disable path + * + * @param bool + * @param int + * @return void + */ + public function enablePath($a_path, $a_start_node = null, \ilPathGUI $path_gui = null) + { + $this->path_enabled = $a_path; + $this->path_start_node = (int) $a_start_node; + $this->path_gui = $path_gui; + } + + /** + * + * @param bool + * @return bool + */ + public function getPathStatus() + { + return $this->path_enabled; + } + + /** + * En/disable commands + * + * @param bool + * @return void + */ + public function enableCommands($a_status, $a_std_only = false) + { + $this->commands_enabled = $a_status; + $this->std_cmd_only = $a_std_only; + } + /** + * + * @param bool + * @return bool + */ + public function getCommandsStatus() + { + return $this->commands_enabled; + } + + /** + * En/disable path + * + * @param bool + * @return void + */ + public function enableInfoScreen($a_info_screen) + { + $this->info_screen_enabled = $a_info_screen; + } + + /** + * Add HTML for subitem (used for sessions) + * + * @param string $a_html subitems HTML + */ + public function addSubItemHTML($a_html) + { + $this->sub_item_html[] = $a_html; + } + + /** + * + * @param bool + * @return bool + */ + public function getInfoScreenStatus() + { + return $this->info_screen_enabled; + } + + /** + * enable progress info + * + * @access public + * @param + * @return + */ + public function enableProgressInfo($a_status) + { + $this->progress_enabled = $a_status; + } + + /** + * get progress info status + * + * @access public + * @param + * @return + */ + public function getProgressInfoStatus() + { + return $this->progress_enabled; + } + + /** + * Enable substitutions + * + * @access public + * @param + * + */ + public function enableSubstitutions($a_status) + { + $this->substitutions_enabled = $a_status; + } + + /** + * Get substitution status + * + * @access public + * + */ + public function getSubstitutionStatus() + { + return $this->substitutions_enabled; + } + + /** + * enable item detail links + * E.g Direct links to chapters or pages + * + * @access public + * @param bool + * @return + */ + public function enableItemDetailLinks($a_status) + { + $this->item_detail_links_enabled = $a_status; + } + + /** + * get item detail link status + * + * @access public + * @return bool + */ + public function getItemDetailLinkStatus() + { + return $this->item_detail_links_enabled; + } + + /** + * set items detail links + * + * @access public + * @param array e.g. array(0 => array('desc' => 'Page: ','link' => 'ilias.php...','name' => 'Page XYZ') + * @return + */ + public function setItemDetailLinks($a_detail_links, $a_intro_txt = '') + { + $this->item_detail_links = $a_detail_links; + $this->item_detail_links_intro = $a_intro_txt; + } + + /** + * insert item detail links + * + * @access public + * @param + * @return + */ + public function insertItemDetailLinks() + { + if (!count($this->item_detail_links)) { + return true; + } + if (strlen($this->item_detail_links_intro)) { + $this->tpl->setCurrentBlock('item_detail_intro'); + $this->tpl->setVariable('ITEM_DETAIL_INTRO_TXT', $this->item_detail_links_intro); + $this->tpl->parseCurrentBlock(); + } + + foreach ($this->item_detail_links as $info) { + $this->tpl->setCurrentBlock('item_detail_link'); + $this->tpl->setVariable('ITEM_DETAIL_LINK_TARGET', $info['target']); + $this->tpl->setVariable('ITEM_DETAIL_LINK_DESC', $info['desc']); + $this->tpl->setVariable('ITEM_DETAIL_LINK_HREF', $info['link']); + $this->tpl->setVariable('ITEM_DETAIL_LINK_NAME', $info['name']); + $this->tpl->parseCurrentBlock(); + } + $this->tpl->setCurrentBlock('item_detail_links'); + $this->tpl->parseCurrentBlock(); + } + + + + /** + * @param string title + * @return bool + */ + public function setTitle($a_title) + { + $this->title = $a_title; + } + + /** + * getTitle overwritten in class.ilObjLinkResourceList.php + * + * @return string title + */ + public function getTitle() + { + return $this->title; + } + + /** + * @param string description + * @return bool + */ + public function setDescription($a_description) + { + $this->description = $a_description; + } + + /** + * getDescription overwritten in class.ilObjLinkResourceList.php + * + * @return string description + */ + public function getDescription() + { + return $this->description; + } + + /** + * set search fragment + * @param string $a_text highlighted search fragment + * @return + */ + public function setSearchFragment($a_text) + { + $this->search_fragment = $a_text; + } + + /** + * get search fragment + * @return + */ + public function getSearchFragment() + { + return $this->search_fragment; + } + + /** + * Set separate commands + * + * @param boolean separate commands + */ + public function setSeparateCommands($a_val) + { + $this->separate_commands = $a_val; + } + + /** + * Get separate commands + * + * @return boolean separate commands + */ + public function getSeparateCommands() + { + return $this->separate_commands; + } + /** + * get command id + * Normally the ref id. + * Overwritten for course and category references + * + * @access public + * @param + * @return + */ + public function getCommandId() + { + return $this->ref_id; + } + + /** + * Set additional information + * + * @param string additional information + */ + public function setAdditionalInformation($a_val) + { + $this->additional_information = $a_val; + } + + /** + * Get additional information + * + * @return string additional information + */ + public function getAdditionalInformation() + { + return $this->additional_information; + } + + /** + * Details level + * Currently used in Search which shows only limited properties of forums + * Currently used for Sessions (switch between minimal and extended view for each session) + * @param int $a_level + * @return + */ + public function setDetailsLevel($a_level) + { + $this->details_level = $a_level; + } + + /** + * Get current details level + * @return + */ + public function getDetailsLevel() + { + return $this->details_level; + } + + /** + * Enable copy/move to repository (from personal workspace) + * + * @param bool $a_value + */ + public function enableRepositoryTransfer($a_value) + { + $this->repository_transfer_enabled = (bool) $a_value; + } + + /** + * Restrict all actions/links to goto + * + * @param bool $a_value + */ + public function restrictToGoto($a_value) + { + $this->restrict_to_goto = (bool) $a_value; + } + + + /** + * Get default command + * + * @return array + */ + public function getDefaultCommand() + { + return $this->default_command; + } + + /** + * + * @param + * @return + */ + public function checkCommandAccess($a_permission, $a_cmd, $a_ref_id, $a_type, $a_obj_id="") + { + $ilAccess = $this->access; + + // e.g: subitems should not be readable since their parent sesssion is readonly. + if ($a_permission != 'visible' and $this->isVisibleOnlyForced()) { + return false; + } + + $cache_prefix = null; + if ($this->context == self::CONTEXT_WORKSPACE || $this->context == self::CONTEXT_WORKSPACE_SHARING) { + $cache_prefix = "wsp"; + if (!$this->ws_access) { + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; + $this->ws_access = new ilWorkspaceAccessHandler(); + } + } + + if (isset($this->access_cache[$a_permission]["-" . $a_cmd][$cache_prefix . $a_ref_id])) { + return $this->access_cache[$a_permission]["-" . $a_cmd][$cache_prefix . $a_ref_id]; + } + + if ($this->context == self::CONTEXT_REPOSITORY) { + $access = $ilAccess->checkAccess($a_permission, $a_cmd, $a_ref_id, $a_type, $a_obj_id); + if ($ilAccess->getPreventCachingLastResult()) { + $this->prevent_access_caching = true; + } + } else { + $access = $this->ws_access->checkAccess($a_permission, $a_cmd, $a_ref_id, $a_type); + } + + $this->access_cache[$a_permission]["-" . $a_cmd][$cache_prefix . $a_ref_id] = $access; + return $access; + } + + /** + * inititialize new item (is called by getItemHTML()) + * + * @param int $a_ref_id reference id + * @param int $a_obj_id object id + * @param string $a_title title + * @param string $a_description description + * @param int $a_context tree/workspace + */ + public function initItem($a_ref_id, $a_obj_id, $a_title = "", $a_description = "") + { + $this->offline_mode = false; + if ($this->type == "sahs") { + include_once('Modules/ScormAicc/classes/class.ilObjSAHSLearningModuleAccess.php'); + $this->offline_mode = ilObjSAHSLearningModuleAccess::_lookupUserIsOfflineMode($a_obj_id); + } + $this->access_cache = array(); + $this->ref_id = $a_ref_id; + $this->obj_id = $a_obj_id; + $this->setTitle($a_title); + $this->setDescription($a_description); + #$this->description = $a_description; + + // checks, whether any admin commands are included in the output + $this->adm_commands_included = false; + $this->prevent_access_caching = false; + } + + public function setConditionTarget($a_ref_id, $a_obj_id, $a_target_type) + { + $this->condition_target = array( + 'ref_id' => $a_ref_id, + 'obj_id' => $a_obj_id, + 'target_type' => $a_target_type + ); + } + + public function resetConditionTarget() + { + $this->condition_target = array(); + } + + public function disableTitleLink($a_status) + { + $this->title_link_disabled = $a_status; + } + // end-patch lok + + public function setDefaultCommandParameters(array $a_params) + { + $this->default_command_params = $a_params; + } + + /** + * Get default command link + * Overwritten for e.g categories,courses => they return a goto link + * If search engine visibility is enabled these object type return a goto_CLIENT_ID_cat_99.html link + * + * @access public + * @param int command link + * + */ + public function createDefaultCommand($command) + { + // begin-patch lok + if ($this->static_link_enabled and !$this->default_command_params) { + include_once('./Services/Link/classes/class.ilLink.php'); + if ($link = ilLink::_getStaticLink($this->ref_id, $this->type, false)) { + $command['link'] = $link; + $command['frame'] = '_top'; + } + } + if ($this->default_command_params) { + $params = array(); + foreach ($this->default_command_params as $name => $value) { + $params[] = $name . '=' . $value; + } + $params = implode('&', $params); + + // #12370 + if (!stristr($command['link'], '?')) { + $command['link'] .= '?' . $params; + } else { + $command['link'] .= '&' . $params; + } + } + return $command; + } + + /** + * Get command link url. + * + * Overwrite this method, if link target is not build by ctrl class + * (e.g. "forum.php"). This is the case + * for all links now, but bringing everything to ilCtrl should + * be realised in the future. + * + * @param string $a_cmd command + * + * @return string command link url + */ + public function getCommandLink($a_cmd) + { + if ($this->context == self::CONTEXT_REPOSITORY) { + // BEGIN WebDAV Get mount webfolder link. + require_once('Services/WebDAV/classes/class.ilDAVActivationChecker.php'); + if ($a_cmd == 'mount_webfolder' && ilDAVActivationChecker::_isActive()) { + require_once('Services/WebDAV/classes/class.ilWebDAVUtil.php'); + $dav_util = ilWebDAVUtil::getInstance(); + + // XXX: The following is a very dirty, ugly trick. + // To mount URI needs to be put into two attributes: + // href and folder. This hack returns both attributes + // like this: http://...mount_uri..." folder="http://...folder_uri... + return $dav_util->getMountURI($this->ref_id) . + '" folder="' . $dav_util->getFolderURI($this->ref_id); + } + // END WebDAV Get mount webfolder link. + + $this->ctrl->setParameterByClass("ilrepositorygui", "ref_id", $this->getCommandId()); + $cmd_link = $this->ctrl->getLinkTargetByClass("ilrepositorygui", $a_cmd); + $this->ctrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + return $cmd_link; + + /* separate method for this line + $cmd_link = $this->ctrl->getLinkTargetByClass($this->gui_class_name, + $a_cmd); + return $cmd_link; + */ + } else { + $this->ctrl->setParameterByClass($this->gui_class_name, "ref_id", ""); + $this->ctrl->setParameterByClass($this->gui_class_name, "wsp_id", $this->ref_id); + return $this->ctrl->getLinkTargetByClass($this->gui_class_name, $a_cmd); + } + } + + + /** + * Get command target frame. + * + * Overwrite this method if link frame is not current frame + * + * @param string $a_cmd command + * + * @return string command target frame + */ + public function getCommandFrame($a_cmd) + { + // BEGIN WebDAV Get mount webfolder link. + require_once('Services/WebDAV/classes/class.ilDAVActivationChecker.php'); + if ($a_cmd == 'mount_webfolder' && ilDAVActivationChecker::_isActive()) { + return '_blank'; + } + // begin-patch fm + if ($a_cmd == 'fileManagerLaunch') { + return '_blank'; + } + // end-patch fm + return ""; + } + + /** + * Get command icon image + * + * Overwrite this method if an icon is provided + * + * @param string $a_cmd command + * + * @return string image path + */ + public function getCommandImage($a_cmd) + { + return ""; + } + + /** + * Get item properties + * + * Overwrite this method to add properties at + * the bottom of the item html + * + * @return array array of property arrays: + * "alert" (boolean) => display as an alert property (usually in red) + * "property" (string) => property name + * "value" (string) => property value + */ + public function getProperties() + { + $lng = $this->lng; + $ilUser = $this->user; + + $props = array(); + // please list alert properties first + // example (use $lng->txt instead of "Status"/"Offline" strings): + // $props[] = array("alert" => true, "property" => "Status", "value" => "Offline"); + // $props[] = array("alert" => false, "property" => ..., "value" => ...); + // ... + + // #8280: WebDav is only supported in repository + if ($this->context == self::CONTEXT_REPOSITORY) { + // add centralized offline status + if (ilObject::lookupOfflineStatus($this->obj_id)) { + $props[] = + [ + 'alert' => true, + 'property' => $lng->txt("status"), + 'value' => $lng->txt("offline") + ]; + } + + // BEGIN WebDAV Display locking information + require_once('Services/WebDAV/classes/class.ilDAVActivationChecker.php'); + if (ilDAVActivationChecker::_isActive()) { + // Show lock info + require_once('Services/WebDAV/classes/lock/class.ilWebDAVLockBackend.php'); + $webdav_lock_backend = new ilWebDAVLockBackend(); + if ($ilUser->getId() != ANONYMOUS_USER_ID) { + if ($lock = $webdav_lock_backend->getLocksOnObjectId($this->obj_id)) { + $lock_user = new ilObjUser($lock->getIliasOwner()); + + $props[] = array( + "alert" => false, + "property" => $lng->txt("in_use_by"), + "value" => $lock_user->getLogin(), + "link" => "./ilias.php?user=" . $lock_user->getId() . '&cmd=showUserProfile&cmdClass=ilpersonaldesktopgui&baseClass=ilPersonalDesktopGUI', + ); + } + } + // END WebDAV Display locking information + + if ($this->getDetailsLevel() == self::DETAILS_SEARCH) { + return $props; + } + + // BEGIN WebDAV Display warning for invisible Unix files and files with special characters + if (preg_match('/^(\\.|\\.\\.)$/', $this->title)) { + $props[] = array("alert" => false, "property" => $lng->txt("filename_interoperability"), + "value" => $lng->txt("filename_special_filename"), + 'propertyNameVisible' => false); + } elseif (preg_match('/^\\./', $this->title)) { + $props[] = array("alert" => false, "property" => $lng->txt("filename_visibility"), + "value" => $lng->txt("filename_hidden_unix_file"), + 'propertyNameVisible' => false); + } elseif (preg_match('/~$/', $this->title)) { + $props[] = array("alert" => false, "property" => $lng->txt("filename_visibility"), + "value" => $lng->txt("filename_hidden_backup_file"), + 'propertyNameVisible' => false); + } elseif (preg_match('/[\\/]/', $this->title)) { + $props[] = array("alert" => false, "property" => $lng->txt("filename_interoperability"), + "value" => $lng->txt("filename_special_characters"), + 'propertyNameVisible' => false); + } elseif (preg_match('/[\\\\\\/:*?"<>|]/', $this->title)) { + $props[] = array("alert" => false, "property" => $lng->txt("filename_interoperability"), + "value" => $lng->txt("filename_windows_special_characters"), + 'propertyNameVisible' => false); + } elseif (preg_match('/\\.$/', $this->title)) { + $props[] = array("alert" => false, "property" => $lng->txt("filename_interoperability"), + "value" => $lng->txt("filename_windows_empty_extension"), + 'propertyNameVisible' => false); + } elseif (preg_match('/^(\\.|\\.\\.)$/', $this->title)) { + $props[] = array("alert" => false, "property" => $lng->txt("filename_interoperability"), + "value" => $lng->txt("filename_special_filename"), + 'propertyNameVisible' => false); + } elseif (preg_match('/#/', $this->title)) { + $props[] = array("alert" => false, "property" => $lng->txt("filename_interoperability"), + "value" => $lng->txt("filename_windows_webdav_issue"), + 'propertyNameVisible' => false); + } + } + // END WebDAV Display warning for invisible files and files with special characters + } + + return $props; + } + + /** + * add custom property + */ + public function addCustomProperty( + $a_property = "", + $a_value = "", + $a_alert = false, + $a_newline = false + ) { + $this->cust_prop[] = array("property" => $a_property, "value" => $a_value, + "alert" => $a_alert, "newline" => $a_newline); + } + + /** + * get custom properties + */ + public function getCustomProperties($a_prop) + { + if (is_array($this->cust_prop)) { + foreach ($this->cust_prop as $prop) { + $a_prop[] = $prop; + } + } + return $a_prop; + } + + /** + * get all alert properties + * @return array + */ + public function getAlertProperties() + { + $alert = array(); + foreach ((array) $this->getProperties() as $prop) { + if ($prop['alert'] == true) { + $alert[] = $prop; + } + } + return $alert; + } + + /** + * get notice properties + */ + public function getNoticeProperties() + { + $this->notice_prop = array(); + if ($infos = $this->ldap_mapping->getInfoStrings($this->obj_id, true)) { + foreach ($infos as $info) { + $this->notice_prop[] = array('value' => $info); + } + } + return $this->notice_prop ? $this->notice_prop : array(); + } + /** + * add a custom command + */ + public function addCustomCommand($a_link, $a_lang_var, $a_frame = "", $onclick = "") + { + $this->cust_commands[] = + array("link" => $a_link, "lang_var" => $a_lang_var, + "frame" => $a_frame, "onclick" => $onclick); + } + + /** + * Force visible access only. + * @param type $a_stat + */ + public function forceVisibleOnly($a_stat) + { + $this->force_visible_only = $a_stat; + } + + /** + * Force unreadable + * @return type + */ + public function isVisibleOnlyForced() + { + return $this->force_visible_only; + } + + /** + * get all current commands for a specific ref id (in the permission + * context of the current user) + * + * !!!NOTE!!!: Please use getListHTML() if you want to display the item + * including all commands + * + * !!!NOTE 2!!!: Please do not overwrite this method in derived + * classes becaus it will get pretty large and much code will be simply + * copy-and-pasted. Insert smaller object type related method calls instead. + * (like getCommandLink() or getCommandFrame()) + * + * @access public + * @param int $a_ref_id ref id of object + * @return array array of command arrays including + * "permission" => permission name + * "cmd" => command + * "link" => command link url + * "frame" => command link frame + * "lang_var" => language variable of command + * "granted" => true/false: command granted or not + * "access_info" => access info object (to do: implementation) + */ + public function getCommands() + { + $ilAccess = $this->access; + $ilUser = $this->user; + + $ref_commands = array(); + foreach ($this->commands as $command) { + $permission = $command["permission"]; + $cmd = $command["cmd"]; + $lang_var = $command["lang_var"]; + $txt = ""; + $info_object = null; + + if (isset($command["txt"])) { + $txt = $command["txt"]; + } + + // BEGIN WebDAV: Suppress commands that don't make sense for anonymous users. + // Suppress commands that don't make sense for anonymous users + if ($ilUser->getId() == ANONYMOUS_USER_ID && + $command['enable_anonymous'] == 'false') { + continue; + } + // END WebDAV: Suppress commands that don't make sense for anonymous users. + + // all access checking should be made within $ilAccess and + // the checkAccess of the ilObj...Access classes + //$access = $ilAccess->checkAccess($permission, $cmd, $this->ref_id, $this->type); + $access = $this->checkCommandAccess($permission, $cmd, $this->ref_id, $this->type); + + if ($access) { + $cmd_link = $this->getCommandLink($command["cmd"]); + $cmd_frame = $this->getCommandFrame($command["cmd"]); + $cmd_image = $this->getCommandImage($command["cmd"]); + $access_granted = true; + } else { + $access_granted = false; + $info_object = $ilAccess->getInfo(); + } + + if (!isset($command["default"])) { + $command["default"] = ""; + } + $ref_commands[] = array( + "permission" => $permission, + "cmd" => $cmd, + "link" => $cmd_link, + "frame" => $cmd_frame, + "lang_var" => $lang_var, + "txt" => $txt, + "granted" => $access_granted, + "access_info" => $info_object, + "img" => $cmd_image, + "default" => $command["default"] + ); + } + + return $ref_commands; + } + + // BEGIN WebDAV: Visualize object state in its icon. + /** + * Returns the icon image type. + * For most objects, this is same as the object type, e.g. 'cat','fold'. + * We can return here other values, to express a specific state of an object, + * e.g. 'crs_offline", and/or to express a specific kind of object, e.g. + * 'file_inline'. + */ + public function getIconImageType() + { + if ($this->type == "sahs" && $this->offline_mode) { + return $this->type . "_offline"; + } + return $this->type; + } + // END WebDAV: Visualize object state in its icon. + + /** + * insert item title + * + * @access private + * @param object $a_tpl template object + * @param string $a_title item title + */ + public function insertTitle() + { + if ($this->restrict_to_goto) { + $this->default_command = array("frame" => "", + "link" => $this->buildGotoLink()); + } + // begin-patch lok + if ( + !$this->default_command || + (!$this->getCommandsStatus() && !$this->restrict_to_goto) || + $this->title_link_disabled + ) { + // end-patch lok + $this->tpl->setCurrentBlock("item_title"); + $this->tpl->setVariable("TXT_TITLE", $this->getTitle()); + $this->tpl->parseCurrentBlock(); + } else { + $this->default_command['link'] = $this->modifyTitleLink($this->default_command['link']); + + $this->default_command["link"] = + $this->modifySAHSlaunch($this->default_command["link"], $this->default_command["frame"]); + + if ($this->default_command["frame"] != "") { + $this->tpl->setCurrentBlock("title_linked_frame"); + $this->tpl->setVariable("TARGET_TITLE_LINKED", $this->default_command["frame"]); + $this->tpl->parseCurrentBlock(); + } + + // workaround for repository frameset + #var_dump("
                  ",$this->default_command['link'],"
                  "); + $this->default_command["link"] = + $this->appendRepositoryFrameParameter($this->default_command["link"]); + + #var_dump("
                  ",$this->default_command['link'],"
                  "); + + + // the default command is linked with the title + $this->tpl->setCurrentBlock("item_title_linked"); + $this->tpl->setVariable("TXT_TITLE_LINKED", $this->getTitle()); + $this->tpl->setVariable("HREF_TITLE_LINKED", $this->default_command["link"]); + + // has preview? + include_once("./Services/Preview/classes/class.ilPreview.php"); + if (ilPreview::hasPreview($this->obj_id, $this->type)) { + include_once("./Services/Preview/classes/class.ilPreviewGUI.php"); + + // get context for access checks later on + $access_handler = null; + switch ($this->context) { + case self::CONTEXT_WORKSPACE: + case self::CONTEXT_WORKSPACE_SHARING: + $context = ilPreviewGUI::CONTEXT_WORKSPACE; + include_once("./Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"); + $access_handler = new ilWorkspaceAccessHandler(); + break; + + default: + $ilAccess = $this->access; + $context = ilPreviewGUI::CONTEXT_REPOSITORY; + $access_handler = $ilAccess; + break; + } + + $preview = new ilPreviewGUI($this->ref_id, $context, $this->obj_id, $access_handler); + $preview_status = ilPreview::lookupRenderStatus($this->obj_id); + $preview_status_class = ""; + $preview_text_topic = "preview_show"; + if ($preview_status == ilPreview::RENDER_STATUS_NONE) { + $preview_status_class = "ilPreviewStatusNone"; + $preview_text_topic = "preview_none"; + } + $this->tpl->setCurrentBlock("item_title_linked"); + $this->tpl->setVariable("PREVIEW_STATUS_CLASS", $preview_status_class); + $this->tpl->setVariable("SRC_PREVIEW_ICON", ilUtil::getImagePath("preview.png", "Services/Preview")); + $this->tpl->setVariable("TXT_PREVIEW", $this->lng->txt($preview_text_topic)); + $this->tpl->setVariable("SCRIPT_PREVIEW_CLICK", $preview->getJSCall($this->getUniqueItemId(true))); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->parseCurrentBlock(); + } + + if ($this->bold_title == true) { + $this->tpl->touchBlock('bold_title_start'); + $this->tpl->touchBlock('bold_title_end'); + } + } + + protected function buildGotoLink() + { + switch ($this->context) { + case self::CONTEXT_WORKSPACE_SHARING: + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; + return ilWorkspaceAccessHandler::getGotoLink($this->ref_id, $this->obj_id); + + default: + // not implemented yet + break; + } + } + + /** + * Insert substitutions + * + * @access public + * + */ + public function insertSubstitutions() + { + $fields_shown = false; + foreach ($this->substitutions->getParsedSubstitutions($this->ref_id, $this->obj_id) as $data) { + if ($data['bold']) { + $data['name'] = '' . $data['name'] . ''; + $data['value'] = '' . $data['value'] . ''; + } + $this->tpl->touchBlock("std_prop"); + $this->tpl->setCurrentBlock('item_property'); + if ($data['show_field']) { + $this->tpl->setVariable('TXT_PROP', $data['name']); + } + $this->tpl->setVariable('VAL_PROP', $data['value']); + $this->tpl->parseCurrentBlock(); + + if ($data['newline']) { + $this->tpl->touchBlock('newline_prop'); + } + $fields_shown = false; + } + if ($fields_shown) { + $this->tpl->touchBlock('newline_prop'); + } + } + + + /** + * insert item description + * + * @access private + * @param object $a_tpl template object + * @param string $a_desc item description + */ + public function insertDescription() + { + if ($this->getSubstitutionStatus()) { + $this->insertSubstitutions(); + if (!$this->substitutions->isDescriptionEnabled()) { + return true; + } + } + + // see bug #16519 + $d = $this->getDescription(); + $d = strip_tags($d, ""); + $this->tpl->setCurrentBlock("item_description"); + $this->tpl->setVariable("TXT_DESC", $d); + $this->tpl->parseCurrentBlock(); + } + + /** + * Insert highlighted search fragment + * @return + */ + public function insertSearchFragment() + { + if (strlen($this->getSearchFragment())) { + $this->tpl->setCurrentBlock('search_fragment'); + $this->tpl->setVariable('TXT_SEARCH_FRAGMENT', $this->getSearchFragment() . ' ...'); + $this->tpl->parseCurrentBlock(); + } + } + + /** + * insert relevance + * @param + * @return + */ + public function insertRelevance() + { + if (!$this->enabledRelevance() or !(int) $this->getRelevance()) { + return false; + } + + include_once "Services/UIComponent/ProgressBar/classes/class.ilProgressBar.php"; + $pbar = ilProgressBar::getInstance(); + $pbar->setCurrent($this->getRelevance()); + + $this->tpl->setCurrentBlock('relevance'); + $this->tpl->setVariable('REL_PBAR', $pbar->render()); + $this->tpl->parseCurrentBlock(); + } + + /** + * set output mode + * + * @param string $a_mode output mode (IL_LIST_FULL | IL_LIST_AS_TRIGGER) + */ + public function setMode($a_mode) + { + $this->mode = $a_mode; + } + + /** + * get output mode + * + * @return string output mode (IL_LIST_FULL | IL_LIST_AS_TRIGGER) + */ + public function getMode() + { + return $this->mode; + } + + /** + * set depth for precondition output (stops at level 5) + */ + public function setConditionDepth($a_depth) + { + $this->condition_depth = $a_depth; + } + + /** + * check current output mode + * + * @param string $a_mode (IL_LIST_FULL | IL_LIST_AS_TRIGGER) + * + * @return boolen true if current mode is $a_mode + */ + public function isMode($a_mode) + { + if ($a_mode == $this->mode) { + return true; + } else { + return false; + } + } + + /** + * Determine properties + * @return array + */ + public function determineProperties() + { + $ilAccess = $this->access; + $lng = $this->lng; + $ilUser = $this->user; + + $props = $this->getProperties(); + $props = $this->getCustomProperties($props); + + if ($this->context != self::CONTEXT_WORKSPACE && $this->context != self::CONTEXT_WORKSPACE_SHARING) { + // add learning progress custom property + include_once "Services/Tracking/classes/class.ilLPStatus.php"; + $lp = ilLPStatus::getListGUIStatus($this->obj_id); + if ($lp) { + $props[] = array("alert" => false, + "property" => $lng->txt("learning_progress"), + "value" => $lp, + "newline" => true); + } + + // add no item access note in public section + // for items that are visible but not readable + if ($ilUser->getId() == ANONYMOUS_USER_ID) { + if (!$ilAccess->checkAccess("read", "", $this->ref_id, $this->type, $this->obj_id)) { + $props[] = array("alert" => true, + "value" => $lng->txt("no_access_item_public"), + "newline" => true); + } + } + } + + // reference objects have translated ids, revert to originals + $note_ref_id = $this->ref_id; + $note_obj_id = $this->obj_id; + if ($this->reference_ref_id) { + $note_ref_id = $this->reference_ref_id; + $note_obj_id = $this->reference_obj_id; + } + $redraw_js = "il.Object.redrawListItem(" . $note_ref_id . ");"; + + // add common properties (comments, notes, tags) + require_once 'Services/Notes/classes/class.ilNote.php'; + if ((self::$cnt_notes[$note_obj_id][IL_NOTE_PRIVATE] > 0 || + self::$cnt_notes[$note_obj_id][IL_NOTE_PUBLIC] > 0 || + self::$cnt_tags[$note_obj_id] > 0 || + is_array(self::$tags[$note_obj_id])) && + ($ilUser->getId() != ANONYMOUS_USER_ID)) { + include_once("./Services/Notes/classes/class.ilNoteGUI.php"); + include_once("./Services/Tagging/classes/class.ilTaggingGUI.php"); + + $nl = true; + if ($this->isCommentsActivated($this->type, $this->ref_id, $this->obj_id, false, false) + && self::$cnt_notes[$note_obj_id][IL_NOTE_PUBLIC] > 0) { + $props[] = array("alert" => false, + "property" => $lng->txt("notes_comments"), + "value" => "ajax_hash, $redraw_js) . "\">" . + self::$cnt_notes[$note_obj_id][IL_NOTE_PUBLIC] . "", + "newline" => $nl); + $nl = false; + } + + if ($this->notes_enabled && self::$cnt_notes[$note_obj_id][IL_NOTE_PRIVATE] > 0) { + $props[] = array("alert" => false, + "property" => $lng->txt("notes"), + "value" => "ajax_hash, $redraw_js) . "\">" . + self::$cnt_notes[$note_obj_id][IL_NOTE_PRIVATE] . "", + "newline" => $nl); + $nl = false; + } + if ($this->tags_enabled && + (self::$cnt_tags[$note_obj_id] > 0 || + is_array(self::$tags[$note_obj_id]))) { + $tags_set = new ilSetting("tags"); + if ($tags_set->get("enable")) { + $tags_url = ilTaggingGUI::getListTagsJSCall($this->ajax_hash, $redraw_js); + + // list object tags + if (is_array(self::$tags[$note_obj_id])) { + $tags_tmp = array(); + foreach (self::$tags[$note_obj_id] as $tag => $is_tag_owner) { + if ($is_tag_owner) { + $tags_tmp[] = "" . $tag . ""; + } else { + $tags_tmp[] = "" . $tag . ""; + } + } + $tags_value = implode(" ", $tags_tmp); + $nl = true; + $prop_text = ""; + } // tags counter + else { + $tags_value = "" . + self::$cnt_tags[$note_obj_id] . ""; + $prop_text = $lng->txt("tagging_tags"); + } + $props[] = array("alert" => false, + "property" => $prop_text, + "value" => $tags_value, + "newline" => $nl); + $nl = false; + } + } + } + if (!is_array($props)) { + return []; + } + return $props; + } + + /** + * insert properties + * + * @access private + */ + public function insertProperties() + { + $props = $this->determineProperties(); + $cnt = 1; + if (is_array($props) && count($props) > 0) { + foreach ($props as $prop) { + // BEGIN WebDAV: Display a separator between properties. + if ($cnt > 1) { + $this->tpl->touchBlock("separator_prop"); + } + // END WebDAV: Display a separator between properties. + + if ($prop["alert"] == true) { + $this->tpl->touchBlock("alert_prop"); + } else { + $this->tpl->touchBlock("std_prop"); + } + if ($prop["newline"] == true && $cnt > 1) { + $this->tpl->touchBlock("newline_prop"); + } + //BEGIN WebDAV: Support hidden property names. + if (isset($prop["property"]) && $prop['propertyNameVisible'] !== false && $prop["property"] != "") { + //END WebDAV: Support hidden property names. + $this->tpl->setCurrentBlock("prop_name"); + $this->tpl->setVariable("TXT_PROP", $prop["property"]); + $this->tpl->parseCurrentBlock(); + } + $this->tpl->setCurrentBlock("item_property"); + //BEGIN WebDAV: Support links in property values. + if ($prop['link']) { + $this->tpl->setVariable("LINK_PROP", $prop['link']); + $this->tpl->setVariable("LINK_VAL_PROP", $prop["value"]); + } else { + $this->tpl->setVariable("VAL_PROP", $prop["value"]); + } + //END WebDAV: Support links in property values. + $this->tpl->parseCurrentBlock(); + + $cnt++; + } + $this->tpl->setCurrentBlock("item_properties"); + $this->tpl->parseCurrentBlock(); + } + } + + public function insertNoticeProperties() + { + $this->getNoticeProperties(); + foreach ($this->notice_prop as $property) { + $this->tpl->setCurrentBlock('notice_item'); + $this->tpl->setVariable('NOTICE_ITEM_VALUE', $property['value']); + $this->tpl->parseCurrentBlock(); + } + $this->tpl->setCurrentBlock('notice_property'); + $this->tpl->parseCurrentBlock(); + } + + protected function parseConditions($toggle_id, $conditions, $obligatory = true) + { + $lng = $this->lng; + $objDefinition = $this->obj_definition; + $tree = $this->tree; + + $num_required = ilConditionHandler::calculateEffectiveRequiredTriggers($this->ref_id, $this->obj_id); + $num_optional_required = + $num_required - count($conditions) + count(ilConditionHandler::getEffectiveOptionalConditionsOfTarget($this->ref_id, $this->obj_id)); + + // Check if all conditions are fullfilled + $visible_conditions = array(); + $passed_optional = 0; + foreach ($conditions as $condition) { + if ($obligatory and !$condition['obligatory']) { + continue; + } + if (!$obligatory and $condition['obligatory']) { + continue; + } + + if ($tree->isDeleted($condition['trigger_ref_id'])) { + continue; + } + + include_once 'Services/Container/classes/class.ilMemberViewSettings.php'; + $ok = ilConditionHandler::_checkCondition($condition) and + !ilMemberViewSettings::getInstance()->isActive(); + + if (!$ok) { + $visible_conditions[] = $condition['id']; + } + + if (!$obligatory and $ok) { + ++$passed_optional; + // optional passed + if ($passed_optional >= $num_optional_required) { + return true; + } + } + } + + foreach ($conditions as $condition) { + if (!in_array($condition['id'], $visible_conditions)) { + continue; + } + + include_once './Services/Conditions/classes/class.ilConditionHandlerGUI.php'; + $cond_txt = ilConditionHandlerGUI::translateOperator($condition['trigger_obj_id'], $condition['operator']) . ' ' . $condition['value']; + + // display trigger item + $class = $objDefinition->getClassName($condition["trigger_type"]); + $location = $objDefinition->getLocation($condition["trigger_type"]); + if ($class == "" && $location == "") { + continue; + } + $missing_cond_exist = true; + + $full_class = "ilObj" . $class . "ListGUI"; + include_once($location . "/class." . $full_class . ".php"); + $item_list_gui = new $full_class($this); + $item_list_gui->setMode(IL_LIST_AS_TRIGGER); + $item_list_gui->enablePath(false); + $item_list_gui->enableIcon(true); + $item_list_gui->setConditionDepth($this->condition_depth + 1); + $item_list_gui->setParentRefId($this->getUniqueItemId()); // yes we can + $item_list_gui->addCustomProperty($this->lng->txt("precondition_required_itemlist"), $cond_txt, false, true); + + $item_list_gui->enableCommands($this->commands_enabled, $this->std_cmd_only); + $item_list_gui->enableProperties($this->properties_enabled); + + $trigger_html = $item_list_gui->getListItemHTML( + $condition['trigger_ref_id'], + $condition['trigger_obj_id'], + ilObject::_lookupTitle($condition["trigger_obj_id"]), + "" + ); + $this->tpl->setCurrentBlock("precondition"); + if ($trigger_html == "") { + $trigger_html = $this->lng->txt("precondition_not_accessible"); + } + $this->tpl->setVariable("TXT_CONDITION", trim($cond_txt)); + $this->tpl->setVariable("TRIGGER_ITEM", $trigger_html); + $this->tpl->parseCurrentBlock(); + } + + if ($missing_cond_exist and $obligatory) { + $this->tpl->setCurrentBlock("preconditions"); + $this->tpl->setVariable("CONDITION_TOGGLE_ID", "_obl_" . $toggle_id); + $this->tpl->setVariable("TXT_PRECONDITIONS", $lng->txt("preconditions_obligatory_hint")); + $this->tpl->parseCurrentBlock(); + } elseif ($missing_cond_exist and !$obligatory) { + $this->tpl->setCurrentBlock("preconditions"); + $this->tpl->setVariable("CONDITION_TOGGLE_ID", "_opt_" . $toggle_id); + $this->tpl->setVariable("TXT_PRECONDITIONS", sprintf($lng->txt("preconditions_optional_hint"), $num_optional_required)); + $this->tpl->parseCurrentBlock(); + } + + return !$missing_cond_exist; + } + + /** + * insert all missing preconditions + */ + public function insertPreconditions() + { + include_once("./Services/Conditions/classes/class.ilConditionHandler.php"); + + // do not show multi level conditions (messes up layout) + if ($this->condition_depth > 0) { + return; + } + + if ($this->condition_target) { + $conditions = ilConditionHandler::_getEffectiveConditionsOfTarget( + $this->condition_target['ref_id'], + $this->condition_target['obj_id'], + $this->condition_target['target_type'] + ); + } else { + $conditions = ilConditionHandler::_getEffectiveConditionsOfTarget($this->ref_id, $this->obj_id); + } + + if (sizeof($conditions)) { + for ($i = 0; $i < count($conditions); $i++) { + $conditions[$i]['title'] = ilObject::_lookupTitle($conditions[$i]['trigger_obj_id']); + } + $conditions = ilUtil::sortArray($conditions, 'title', 'DESC'); + + ++self::$js_unique_id; + + // Show obligatory and optional preconditions seperated + $all_done_obl = $this->parseConditions(self::$js_unique_id, $conditions, true); + $all_done_opt = $this->parseConditions(self::$js_unique_id, $conditions, false); + + if (!$all_done_obl || !$all_done_opt) { + $this->tpl->setCurrentBlock("preconditions_toggle"); + $this->tpl->setVariable("PRECONDITION_TOGGLE_INTRO", $this->lng->txt("precondition_toggle")); + $this->tpl->setVariable("PRECONDITION_TOGGLE_TRIGGER", $this->lng->txt("show")); + $this->tpl->setVariable("PRECONDITION_TOGGLE_ID", self::$js_unique_id); + $this->tpl->setVariable("TXT_PRECONDITION_SHOW", $this->lng->txt("show")); + $this->tpl->setVariable("TXT_PRECONDITION_HIDE", $this->lng->txt("hide")); + $this->tpl->parseCurrentBlock(); + } + } + } + + /** + * insert command button + * + * @access private + * @param string $a_href link url target + * @param string $a_text link text + * @param string $a_frame link frame target + */ + public function insertCommand($a_href, $a_text, $a_frame = "", $a_img = "", $a_cmd = "", $a_onclick = "") + { + // #11099 + $chksum = md5($a_href . $a_text); + if ($a_href == "#" || + !in_array($chksum, $this->prevent_duplicate_commands)) { + if ($a_href != "#") { + $this->prevent_duplicate_commands[] = $chksum; + } + + $prevent_background_click = false; + if ($a_cmd == 'mount_webfolder') { + $prevent_background_click = true; + } + + if ($a_cmd == "downloadFolder") { + include_once "Services/BackgroundTask/classes/class.ilFolderDownloadBackgroundTaskHandler.php"; + if (ilFolderDownloadBackgroundTaskHandler::isActive()) { + $a_onclick = ilFolderDownloadBackgroundTaskHandler::getObjectListAction($this->ref_id); + $a_href = "#"; + } + } + + $this->current_selection_list->addItem( + $a_text, + "", + $a_href, + $a_img, + $a_text, + $a_frame, + "", + $prevent_background_click, + $a_onclick + ); + } + } + + /** + * insert cut command + * + * @access private + * @param object $a_tpl template object + * @param int $a_ref_id item reference id + */ + public function insertDeleteCommand() + { + if ($this->std_cmd_only) { + return; + } + + if (is_object($this->getContainerObject()) and + $this->getContainerObject() instanceof ilAdministrationCommandHandling) { + if ($this->checkCommandAccess('delete', '', $this->ref_id, $this->type)) { + $this->ctrl->setParameter($this->getContainerObject(), 'item_ref_id', $this->getCommandId()); + $cmd_link = $this->ctrl->getLinkTarget($this->getContainerObject(), "delete"); + $this->insertCommand($cmd_link, $this->lng->txt("delete")); + $this->adm_commands_included = true; + return true; + } + return false; + } + + if ($this->checkCommandAccess('delete', '', $this->ref_id, $this->type)) { + $this->ctrl->setParameter( + $this->container_obj, + "ref_id", + $this->container_obj->object->getRefId() + ); + $this->ctrl->setParameter($this->container_obj, "item_ref_id", $this->getCommandId()); + $cmd_link = $this->ctrl->getLinkTarget($this->container_obj, "delete"); + $this->insertCommand( + $cmd_link, + $this->lng->txt("delete"), + "", + "" + ); + $this->adm_commands_included = true; + } + } + + /** + * insert link command + * + * @access private + * @param object $a_tpl template object + * @param int $a_ref_id item reference id + */ + public function insertLinkCommand() + { + $objDefinition = $this->obj_definition; + + if ($this->std_cmd_only) { + return; + } + + // #17307 + if (!$this->checkCommandAccess('delete', '', $this->ref_id, $this->type) or + !$objDefinition->allowLink($this->type)) { + return false; + } + + // BEGIN PATCH Lucene search + + if (is_object($this->getContainerObject()) and + $this->getContainerObject() instanceof ilAdministrationCommandHandling) { + $this->ctrl->setParameter($this->getContainerObject(), 'item_ref_id', $this->getCommandId()); + $cmd_link = $this->ctrl->getLinkTarget($this->getContainerObject(), "link"); + $this->insertCommand($cmd_link, $this->lng->txt("link")); + $this->adm_commands_included = true; + return true; + } + // END PATCH Lucene Search + + // if the permission is changed here, it has + // also to be changed in ilContainerGUI, admin command check + $this->ctrl->setParameter( + $this->container_obj, + "ref_id", + $this->container_obj->object->getRefId() + ); + $this->ctrl->setParameter($this->container_obj, "item_ref_id", $this->getCommandId()); + $cmd_link = $this->ctrl->getLinkTarget($this->container_obj, "link"); + $this->insertCommand( + $cmd_link, + $this->lng->txt("link"), + "", + "" + ); + $this->adm_commands_included = true; + return true; + } + + /** + * insert cut command + * + * @access protected + * @param bool $a_to_repository + */ + public function insertCutCommand($a_to_repository = false) + { + if ($this->std_cmd_only) { + return; + } + // BEGIN PATCH Lucene search + if (is_object($this->getContainerObject()) and + $this->getContainerObject() instanceof ilAdministrationCommandHandling) { + if ($this->checkCommandAccess('delete', '', $this->ref_id, $this->type)) { + $this->ctrl->setParameter($this->getContainerObject(), 'item_ref_id', $this->getCommandId()); + $cmd_link = $this->ctrl->getLinkTarget($this->getContainerObject(), "cut"); + $this->insertCommand($cmd_link, $this->lng->txt("move")); + $this->adm_commands_included = true; + return true; + } + return false; + } + // END PATCH Lucene Search + + // if the permission is changed here, it has + // also to be changed in ilContainerContentGUI, determineAdminCommands + if ($this->checkCommandAccess('delete', '', $this->ref_id, $this->type) && + $this->container_obj->object) { + $this->ctrl->setParameter( + $this->container_obj, + "ref_id", + $this->container_obj->object->getRefId() + ); + $this->ctrl->setParameter($this->container_obj, "item_ref_id", $this->getCommandId()); + + if (!$a_to_repository) { + $cmd_link = $this->ctrl->getLinkTarget($this->container_obj, "cut"); + $this->insertCommand( + $cmd_link, + $this->lng->txt("move"), + "", + "" + ); + } else { + $cmd_link = $this->ctrl->getLinkTarget($this->container_obj, "cut_for_repository"); + $this->insertCommand( + $cmd_link, + $this->lng->txt("wsp_move_to_repository"), + "", + "" + ); + } + + $this->adm_commands_included = true; + } + } + + /** + * Insert copy command + * + * @param bool $a_to_repository + */ + public function insertCopyCommand($a_to_repository = false) + { + $objDefinition = $this->obj_definition; + + if ($this->std_cmd_only) { + return; + } + + if ($this->checkCommandAccess('copy', 'copy', $this->ref_id, $this->type) && + $objDefinition->allowCopy($this->type)) { + if ($this->context != self::CONTEXT_WORKSPACE && $this->context != self::CONTEXT_WORKSPACE_SHARING) { + $this->ctrl->setParameterByClass('ilobjectcopygui', 'source_id', $this->getCommandId()); + $cmd_copy = $this->ctrl->getLinkTargetByClass('ilobjectcopygui', 'initTargetSelection'); + $this->insertCommand($cmd_copy, $this->lng->txt('copy')); + } else { + $this->ctrl->setParameter( + $this->container_obj, + "ref_id", + $this->container_obj->object->getRefId() + ); + $this->ctrl->setParameter($this->container_obj, "item_ref_id", $this->getCommandId()); + + if (!$a_to_repository) { + $cmd_copy = $this->ctrl->getLinkTarget($this->container_obj, 'copy'); + $this->insertCommand($cmd_copy, $this->lng->txt('copy')); + } else { + $cmd_copy = $this->ctrl->getLinkTarget($this->container_obj, 'copy_to_repository'); + $this->insertCommand($cmd_copy, $this->lng->txt('wsp_copy_to_repository')); + } + } + + $this->adm_commands_included = true; + } + return; + } + + + /** + * Insert paste command + */ + public function insertPasteCommand() + { + $objDefinition = $this->obj_definition; + + if ($this->std_cmd_only) { + return; + } + + if (!$objDefinition->isContainer(ilObject::_lookupType($this->obj_id))) { + return false; + } + + if (is_object($this->getContainerObject()) and + $this->getContainerObject() instanceof ilAdministrationCommandHandling and + isset($_SESSION['clipboard'])) { + $this->ctrl->setParameter($this->getContainerObject(), 'item_ref_id', $this->getCommandId()); + $cmd_link = $this->ctrl->getLinkTarget($this->getContainerObject(), "paste"); + $this->insertCommand($cmd_link, $this->lng->txt("paste")); + $this->adm_commands_included = true; + return true; + } + return false; + } + + /** + * insert subscribe command + * + * @access private + * @param object $a_tpl template object + * @param int $a_ref_id item reference id + */ + public function insertSubscribeCommand() + { + $ilSetting = $this->settings; + $ilUser = $this->user; + + if ($this->std_cmd_only) { + return; + } + + if ((int) $ilSetting->get('disable_my_offers')) { + return; + } + + $type = ilObject::_lookupType(ilObject::_lookupObjId($this->getCommandId())); + + if ($ilUser->getId() != ANONYMOUS_USER_ID) { + // #17467 - add ref_id to link (in repository only!) + if (is_object($this->container_obj) && + !($this->container_obj instanceof ilAdministrationCommandHandling) && + is_object($this->container_obj->object)) { + $this->ctrl->setParameter($this->container_obj, "ref_id", $this->container_obj->object->getRefId()); + } + + if (!$ilUser->isDesktopItem($this->getCommandId(), $type)) { + // Pass type and object ID to ilAccess to improve performance + if ($this->checkCommandAccess("read", "", $this->ref_id, $this->type, $this->obj_id)) { + if ($this->getContainerObject() instanceof ilDesktopItemHandling) { + $this->ctrl->setParameter($this->container_obj, "type", $type); + $this->ctrl->setParameter($this->container_obj, "item_ref_id", $this->getCommandId()); + $cmd_link = $this->ctrl->getLinkTarget($this->container_obj, "addToDesk"); + $this->insertCommand( + $cmd_link, + $this->lng->txt("to_desktop"), + "", + "" + ); + } + } + } else { + if ($this->getContainerObject() instanceof ilDesktopItemHandling) { + $this->ctrl->setParameter($this->container_obj, "type", $type); + $this->ctrl->setParameter($this->container_obj, "item_ref_id", $this->getCommandId()); + $cmd_link = $this->ctrl->getLinkTarget($this->container_obj, "removeFromDesk"); + $this->insertCommand( + $cmd_link, + $this->lng->txt("unsubscribe"), + "", + "" + ); + } + } + } + } + + /** + * insert info screen command + */ + public function insertInfoScreenCommand() + { + if ($this->std_cmd_only) { + return; + } + $cmd_link = $this->getCommandLink("infoScreen"); + $cmd_frame = $this->getCommandFrame("infoScreen"); + $this->insertCommand( + $cmd_link, + $this->lng->txt("info_short"), + $cmd_frame, + ilUtil::getImagePath("icon_info.svg") + ); + } + + /** + * Insert common social commands (comments, notes, tagging) + * + * @param + * @return + */ + public function insertCommonSocialCommands($a_header_actions = false) + { + $lng = $this->lng; + $ilUser = $this->user; + + if ($this->std_cmd_only || + ($ilUser->getId() == ANONYMOUS_USER_ID)) { + return; + } + $lng->loadLanguageModule("notes"); + $lng->loadLanguageModule("tagging"); + $cmd_frame = $this->getCommandFrame("infoScreen"); + include_once("./Services/Notes/classes/class.ilNoteGUI.php"); + + // reference objects have translated ids, revert to originals + $note_ref_id = $this->ref_id; + if ($this->reference_ref_id) { + $note_ref_id = $this->reference_ref_id; + } + + $js_updater = $a_header_actions + ? "il.Object.redrawActionHeader();" + : "il.Object.redrawListItem(" . $note_ref_id . ")"; + + $comments_enabled = $this->isCommentsActivated($this->type, $this->ref_id, $this->obj_id, $a_header_actions, true); + if ($comments_enabled) { + $this->insertCommand( + "#", + $this->lng->txt("notes_comments"), + $cmd_frame, + "", + "", + ilNoteGUI::getListCommentsJSCall($this->ajax_hash, $js_updater) + ); + } + + if ($this->notes_enabled) { + $this->insertCommand( + "#", + $this->lng->txt("notes"), + $cmd_frame, + "", + "", + ilNoteGUI::getListNotesJSCall($this->ajax_hash, $js_updater) + ); + } + + if ($this->tags_enabled) { + include_once("./Services/Tagging/classes/class.ilTaggingGUI.php"); + //$this->insertCommand($cmd_tag_link, $this->lng->txt("tagging_set_tag"), $cmd_frame); + $this->insertCommand( + "#", + $this->lng->txt("tagging_set_tag"), + $cmd_frame, + "", + "", + ilTaggingGUI::getListTagsJSCall($this->ajax_hash, $js_updater) + ); + } + } + + /** + * insert edit timings command + * + * @access protected + */ + public function insertTimingsCommand() + { + if ($this->std_cmd_only || !$this->container_obj->object) { + return; + } + + $parent_ref_id = $this->container_obj->object->getRefId(); + $parent_type = $this->container_obj->object->getType(); + + // #18737 + if ($this->reference_ref_id) { + $this->ctrl->setParameterByClass('ilobjectactivationgui', 'ref_id', $this->reference_ref_id); + } + + if ($this->checkCommandAccess('write', '', $parent_ref_id, $parent_type) || + $this->checkCommandAccess('write', '', $this->ref_id, $this->type)) { + $this->ctrl->setParameterByClass( + 'ilobjectactivationgui', + 'cadh', + $this->ajax_hash + ); + $this->ctrl->setParameterByClass( + 'ilobjectactivationgui', + 'parent_id', + $parent_ref_id + ); + $cmd_lnk = $this->ctrl->getLinkTargetByClass( + array($this->gui_class_name, 'ilcommonactiondispatchergui', 'ilobjectactivationgui'), + 'edit' + ); + + $this->insertCommand($cmd_lnk, $this->lng->txt('obj_activation_list_gui')); + } + + if ($this->reference_ref_id) { + $this->ctrl->setParameterByClass('ilobjectactivationgui', 'ref_id', $this->ref_id); + } + } + + /** + * insert all commands into html code + * + * @access private + * @param object $a_tpl template object + * @param int $a_ref_id item reference id + */ + public function insertCommands( + $a_use_asynch = false, + $a_get_asynch_commands = false, + $a_asynch_url = "", + $a_header_actions = false + ) { + $lng = $this->lng; + $ilUser = $this->user; + + if (!$this->getCommandsStatus()) { + return; + } + + include_once("Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"); + $this->current_selection_list = new ilAdvancedSelectionListGUI(); + $this->current_selection_list->setAsynch($a_use_asynch && !$a_get_asynch_commands); + $this->current_selection_list->setAsynchUrl($a_asynch_url); + if ($a_header_actions) { + $this->current_selection_list->setListTitle(""); + } else { + $this->current_selection_list->setListTitle(""); + } + $this->current_selection_list->setId("act_" . $this->getUniqueItemId(false)); + $this->current_selection_list->setSelectionHeaderClass("small"); + $this->current_selection_list->setItemLinkClass("xsmall"); + $this->current_selection_list->setLinksMode("il_ContainerItemCommand2"); + $this->current_selection_list->setHeaderIcon(ilAdvancedSelectionListGUI::DOWN_ARROW_DARK); + $this->current_selection_list->setUseImages(false); + $this->current_selection_list->setAdditionalToggleElement($this->getUniqueItemId(true), "ilContainerListItemOuterHighlight"); + + $this->ctrl->setParameterByClass($this->gui_class_name, "ref_id", $this->ref_id); + + // only standard command? + $only_default = false; + if ($a_use_asynch && !$a_get_asynch_commands) { + $only_default = true; + } + + $this->default_command = false; + $this->prevent_duplicate_commands = array(); + + // we only allow the following commands inside the header actions + $valid_header_commands = array("mount_webfolder"); + + $commands = $this->getCommands($this->ref_id, $this->obj_id); + foreach ($commands as $command) { + if ($a_header_actions && !in_array($command["cmd"], $valid_header_commands)) { + continue; + } + + if ($command["granted"] == true) { + if (!$command["default"] === true) { + if (!$this->std_cmd_only && !$only_default) { + // workaround for repository frameset + $command["link"] = + $this->appendRepositoryFrameParameter($command["link"]); + + $cmd_link = $command["link"]; + $txt = ($command["lang_var"] == "") + ? $command["txt"] + : $this->lng->txt($command["lang_var"]); + $this->insertCommand( + $cmd_link, + $txt, + $command["frame"], + $command["img"], + $command["cmd"] + ); + } + } else { + $this->default_command = $this->createDefaultCommand($command); + //$this->default_command = $command; + } + } + } + + if (!$only_default) { + // custom commands + if (is_array($this->cust_commands)) { + foreach ($this->cust_commands as $command) { + $this->insertCommand( + $command["link"], + $this->lng->txt($command["lang_var"]), + $command["frame"], + "", + $command["cmd"], + $command["onclick"] + ); + } + } + + // info screen commmand + if ($this->getInfoScreenStatus()) { + $this->insertInfoScreenCommand(); + } + + if (!$this->isMode(IL_LIST_AS_TRIGGER)) { + // edit timings + if ($this->timings_enabled) { + $this->insertTimingsCommand(); + } + + // delete + if ($this->delete_enabled) { + $this->insertDeleteCommand(); + } + + // link + if ($this->link_enabled) { + $this->insertLinkCommand(); + } + + // cut + if ($this->cut_enabled) { + $this->insertCutCommand(); + } + + // copy + if ($this->copy_enabled) { + $this->insertCopyCommand(); + } + + // cut/copy from workspace to repository + if ($this->repository_transfer_enabled) { + $this->insertCutCommand(true); + $this->insertCopyCommand(true); + } + + // subscribe + if ($this->subscribe_enabled) { + $this->insertSubscribeCommand(); + } + + // multi download + if ($this->multi_download_enabled && $a_header_actions) { + $this->insertMultiDownloadCommand(); + } + + // BEGIN PATCH Lucene search + if ($this->cut_enabled or $this->link_enabled) { + $this->insertPasteCommand(); + } + // END PATCH Lucene Search + } + } + + // common social commands (comment, notes, tags) + if (!$only_default && !$this->isMode(IL_LIST_AS_TRIGGER)) { + $this->insertCommonSocialCommands($a_header_actions); + } + + if (!$a_header_actions) { + $this->ctrl->clearParametersByClass($this->gui_class_name); + } + + // fix bug #12417 + // there is one case, where no action menu should be displayed: + // public area, category, no info tab + // todo: make this faster and remove type specific implementation if possible + if ($a_use_asynch && !$a_get_asynch_commands && !$a_header_actions) { + if ($ilUser->getId() == ANONYMOUS_USER_ID && $this->type == "cat") { + include_once("./Services/Container/classes/class.ilContainer.php"); + include_once("./Services/Object/classes/class.ilObjectServiceSettingsGUI.php"); + if (!ilContainer::_lookupContainerSetting( + $this->obj_id, + ilObjectServiceSettingsGUI::INFO_TAB_VISIBILITY, + true + )) { + return; + } + } + } + + if ($a_use_asynch && $a_get_asynch_commands) { + return $this->current_selection_list->getHTML(true); + } + + return $this->current_selection_list->getHTML(); + } + + /** + * Toogle comments action status + * + * @param boolean $a_value + */ + public function enableComments($a_value, $a_enable_comments_settings = true) + { + $ilSetting = $this->settings; + + // global switch + if ($ilSetting->get("disable_comments")) { + $a_value = false; + } + + $this->comments_enabled = (bool) $a_value; + $this->comments_settings_enabled = (bool) $a_enable_comments_settings; + } + + /** + * Toogle notes action status + * + * @param boolean $a_value + */ + public function enableNotes($a_value) + { + $ilSetting = $this->settings; + + // global switch + if ($ilSetting->get("disable_notes")) { + $a_value = false; + } + + $this->notes_enabled = (bool) $a_value; + } + + /** + * Toogle tags action status + * + * @param boolean $a_value + */ + public function enableTags($a_value) + { + $tags_set = new ilSetting("tags"); + if (!$tags_set->get("enable")) { + $a_value = false; + } + $this->tags_enabled = (bool) $a_value; + } + + /** + * Toogle rating action status + * + * @param boolean $a_value + * @param string $a_text + * @param boolean $a_categories + * @param array $a_ctrl_path + */ + public function enableRating($a_value, $a_text = null, $a_categories = false, array $a_ctrl_path = null) + { + $this->rating_enabled = (bool) $a_value; + + if ($this->rating_enabled) { + $this->rating_categories_enabled = (bool) $a_categories; + $this->rating_text = $a_text; + $this->rating_ctrl_path = $a_ctrl_path; + } + } + + /** + * Toggles whether multiple objects can be downloaded at once or not. + * + * @param boolean $a_value true, to allow downloading of multiple objects; otherwise, false. + */ + public function enableMultiDownload($a_value) + { + $folder_set = new ilSetting("fold"); + if (!$folder_set->get("enable_multi_download")) { + $a_value = false; + } + $this->multi_download_enabled = (bool) $a_value; + } + + public function insertMultiDownloadCommand() + { + $objDefinition = $this->obj_definition; + + if ($this->std_cmd_only) { + return; + } + + if (!$objDefinition->isContainer(ilObject::_lookupType($this->obj_id))) { + return false; + } + + if (is_object($this->getContainerObject()) && + $this->getContainerObject() instanceof ilContainerGUI) { + $this->ctrl->setParameter($this->getContainerObject(), "type", ""); + $this->ctrl->setParameter($this->getContainerObject(), "item_ref_id", ""); + $this->ctrl->setParameter($this->getContainerObject(), "active_node", ""); + // bugfix mantis 24559 + // undoing an erroneous change inside mantis 23516 by adding "Download Multiple Objects"-functionality for non-admins + // as they don't have the possibility to use the multi-download-capability of the manage-tab + $user_id = $this->user->getId(); + $hasAdminAccess = $this->access->checkAccessOfUser($user_id, "crs_admin", $this->ctrl->getCmd(), $_GET['ref_id']); + // to still prevent duplicate download functions for admins the following if-else statement keeps the redirection for admins + // while letting other course members access the original multi-download functionality + if ($hasAdminAccess) { + $cmd = $_GET["cmd"] == "enableAdministrationPanel" ? "render" : "enableAdministrationPanel"; + } else { + $cmd = $_GET["cmd"] == "enableMultiDownload" ? "render" : "enableMultiDownload"; + } + $cmd_link = $this->ctrl->getLinkTarget($this->getContainerObject(), $cmd); + $this->insertCommand($cmd_link, $this->lng->txt("download_multiple_objects")); + return true; + } + + return false; + } + + public function enableDownloadCheckbox($a_ref_id, $a_value) + { + $ilAccess = $this->access; + + // TODO: delegate to list object class! + if (!$this->getContainerObject()->isActiveAdministrationPanel() || $_SESSION["clipboard"]) { + if (in_array($this->type, array("file", "fold")) && + $ilAccess->checkAccess("read", "", $a_ref_id, $this->type)) { + $this->download_checkbox_state = self::DOWNLOAD_CHECKBOX_ENABLED; + } else { + $this->download_checkbox_state = self::DOWNLOAD_CHECKBOX_DISABLED; + } + } else { + $this->download_checkbox_state = self::DOWNLOAD_CHECKBOX_NONE; + } + } + + public function getDownloadCheckboxState() + { + return $this->download_checkbox_state; + } + + /** + * Insert js/ajax links into template + */ + public static function prepareJsLinks($a_redraw_url, $a_notes_url, $a_tags_url, $a_tpl = null) + { + global $DIC; + + $tpl = $DIC["tpl"]; + + if (is_null($a_tpl)) { + $a_tpl = $tpl; + } + + if ($a_notes_url) { + include_once("./Services/Notes/classes/class.ilNoteGUI.php"); + ilNoteGUI::initJavascript($a_notes_url, IL_NOTE_PRIVATE, $a_tpl); + } + + if ($a_tags_url) { + include_once("./Services/Tagging/classes/class.ilTaggingGUI.php"); + ilTaggingGUI::initJavascript($a_tags_url, $a_tpl); + } + + if ($a_redraw_url) { + $a_tpl->addOnLoadCode("il.Object.setRedrawAHUrl('" . + $a_redraw_url . "');"); + } + } + + /** + * Set sub object identifier + * + * @param string $a_type + * @param int $a_id + */ + public function setHeaderSubObject($a_type, $a_id) + { + $this->sub_obj_type = $a_type; + $this->sub_obj_id = (int) $a_id; + } + + /** + * + * @param string $a_id + * @param string $a_img + * @param string $a_tooltip + * @param string $a_onclick + * @param string $a_status_text + * @param string $a_href + */ + public function addHeaderIcon($a_id, $a_img, $a_tooltip = null, $a_onclick = null, $a_status_text = null, $a_href = null) + { + $this->header_icons[$a_id] = array("img" => $a_img, + "tooltip" => $a_tooltip, + "onclick" => $a_onclick, + "status_text" => $a_status_text, + "href" => $a_href); + } + + /** + * + * @param string $a_id + * @param string $a_html + */ + public function addHeaderIconHTML($a_id, $a_html) + { + $this->header_icons[$a_id] = $a_html; + } + + /** + * + * @param string $a_id + * @param string $a_html + */ + public function addHeaderGlyph($a_id, $a_glyph, $a_onclick = null) + { + $this->header_icons[$a_id] = array("glyph" => $a_glyph, "onclick" => $a_onclick); + } + + public function setAjaxHash($a_hash) + { + $this->ajax_hash = $a_hash; + } + + /** + * Get header action + * + * @return string + */ + public function getHeaderAction(ilTemplate $a_main_tpl = null) + { + global $DIC; + + $ilUser = $this->user; + $lng = $this->lng; + + if ($a_main_tpl == null) { + $main_tpl = $DIC["tpl"]; + } else { + $main_tpl = $a_main_tpl; + } + + $htpl = new ilTemplate("tpl.header_action.html", true, true, "Services/Repository"); + + $redraw_js = "il.Object.redrawActionHeader();"; + + // tags + if ($this->tags_enabled) { + include_once("./Services/Tagging/classes/class.ilTagging.php"); + $tags = ilTagging::getTagsForUserAndObject( + $this->obj_id, + ilObject::_lookupType($this->obj_id), + 0, + "", + $ilUser->getId() + ); + if (count($tags) > 0) { + include_once("./Services/Tagging/classes/class.ilTaggingGUI.php"); + $lng->loadLanguageModule("tagging"); + /*$this->addHeaderIcon("tags", + ilUtil::getImagePath("icon_tag.svg"), + $lng->txt("tagging_tags").": ".count($tags), + ilTaggingGUI::getListTagsJSCall($this->ajax_hash, $redraw_js), + count($tags));*/ + + $f = $this->ui->factory(); + $this->addHeaderGlyph( + "tags", + $f->glyph()->tag("#") + ->withCounter($f->counter()->status((int) count($tags))), + ilTaggingGUI::getListTagsJSCall($this->ajax_hash, $redraw_js) + ); + } + } + + // notes and comments + $comments_enabled = $this->isCommentsActivated($this->type, $this->ref_id, $this->obj_id, true, false); + if ($this->notes_enabled || $comments_enabled) { + include_once("./Services/Notes/classes/class.ilNote.php"); + include_once("./Services/Notes/classes/class.ilNoteGUI.php"); + $type = ($this->sub_obj_type == "") + ? $this->type + : $this->sub_obj_type; + $cnt = ilNote::_countNotesAndComments($this->obj_id, $this->sub_obj_id, $type); + + if ($this->notes_enabled && $cnt[$this->obj_id][IL_NOTE_PRIVATE] > 0) { + /*$this->addHeaderIcon("notes", + ilUtil::getImagePath("note_unlabeled.svg"), + $lng->txt("private_notes").": ".$cnt[$this->obj_id][IL_NOTE_PRIVATE], + ilNoteGUI::getListNotesJSCall($this->ajax_hash, $redraw_js), + $cnt[$this->obj_id][IL_NOTE_PRIVATE] + );*/ + + $f = $this->ui->factory(); + $this->addHeaderGlyph( + "notes", + $f->glyph()->note("#") + ->withCounter($f->counter()->status((int) $cnt[$this->obj_id][IL_NOTE_PRIVATE])), + ilNoteGUI::getListNotesJSCall($this->ajax_hash, $redraw_js) + ); + } + + if ($comments_enabled && $cnt[$this->obj_id][IL_NOTE_PUBLIC] > 0) { + $lng->loadLanguageModule("notes"); + + /*$this->addHeaderIcon("comments", + ilUtil::getImagePath("comment_unlabeled.svg"), + $lng->txt("notes_public_comments").": ".$cnt[$this->obj_id][IL_NOTE_PUBLIC], + ilNoteGUI::getListCommentsJSCall($this->ajax_hash, $redraw_js), + $cnt[$this->obj_id][IL_NOTE_PUBLIC]);*/ + + $f = $this->ui->factory(); + $this->addHeaderGlyph( + "comments", + $f->glyph()->comment("#") + ->withCounter($f->counter()->status((int) $cnt[$this->obj_id][IL_NOTE_PUBLIC])), + ilNoteGUI::getListCommentsJSCall($this->ajax_hash, $redraw_js) + ); + } + } + + // rating + if ($this->rating_enabled) { + include_once("./Services/Rating/classes/class.ilRatingGUI.php"); + $rating_gui = new ilRatingGUI(); + $rating_gui->enableCategories($this->rating_categories_enabled); + // never rate sub objects from header action! + $rating_gui->setObject($this->obj_id, $this->type); + if ($this->rating_text) { + $rating_gui->setYourRatingText($this->rating_text); + } + + $this->ctrl->setParameterByClass("ilRatingGUI", "cadh", $this->ajax_hash); + $this->ctrl->setParameterByClass("ilRatingGUI", "rnsb", true); + if ($this->rating_ctrl_path) { + $rating_gui->setCtrlPath($this->rating_ctrl_path); + $ajax_url = $this->ctrl->getLinkTargetByClass($this->rating_ctrl_path, "saveRating", "", true, false); + } else { + // ??? + $ajax_url = $this->ctrl->getLinkTargetByClass("ilRatingGUI", "saveRating", "", true, false); + } + $main_tpl->addOnLoadCode("il.Object.setRatingUrl('" . $ajax_url . "');"); + $this->addHeaderIconHTML( + "rating", + $rating_gui->getHtml( + true, + $this->checkCommandAccess("read", "", $this->ref_id, $this->type), + "il.Object.saveRating(%rating%);" + ) + ); + } + + if ($this->header_icons) { + include_once("./Services/UIComponent/Tooltip/classes/class.ilTooltipGUI.php"); + + $chunks = array(); + foreach ($this->header_icons as $id => $attr) { + $id = "headp_" . $id; + + if (is_array($attr)) { + if ($attr["glyph"]) { + if ($attr["onclick"]) { + $htpl->setCurrentBlock("prop_glyph_oc"); + $htpl->setVariable("GLYPH_ONCLICK", $attr["onclick"]); + $htpl->parseCurrentBlock(); + } + $renderer = $this->ui->renderer(); + $html = $renderer->render($attr["glyph"]); + $htpl->setCurrentBlock("prop_glyph"); + $htpl->setVariable("GLYPH", $html); + $htpl->parseCurrentBlock(); + } else { + if ($attr["onclick"]) { + $htpl->setCurrentBlock("onclick"); + $htpl->setVariable("PROP_ONCLICK", $attr["onclick"]); + $htpl->parseCurrentBlock(); + } + + if ($attr["status_text"]) { + $htpl->setCurrentBlock("status"); + $htpl->setVariable("PROP_TXT", $attr["status_text"]); + $htpl->parseCurrentBlock(); + } + + + $htpl->setCurrentBlock("prop"); + if ($attr["href"] || $attr["onclick"]) { + $htpl->setVariable("TAG", "a"); + } else { + $htpl->setVariable("TAG", "span"); + } + $htpl->setVariable("PROP_ID", $id); + $htpl->setVariable("IMG", ilUtil::img($attr["img"])); + if ($attr["href"] != "") { + $htpl->setVariable("PROP_HREF", ' href="' . $attr["href"] . '" '); + } + $htpl->parseCurrentBlock(); + + if ($attr["tooltip"]) { + ilTooltipGUI::addTooltip($id, $attr["tooltip"]); + } + } + } else { + $chunks[] = $attr; + } + } + + if (sizeof($chunks)) { + $htpl->setVariable( + "PROP_CHUNKS", + implode("   ", $chunks) . "   " + ); + } + } + + $htpl->setVariable( + "ACTION_DROP_DOWN", + $this->insertCommands(false, false, "", true) + ); + + return $htpl->get(); + } + + + /** + * workaround: all links into the repository (from outside) + * must tell repository to setup the frameset + */ + public function appendRepositoryFrameParameter($a_link) + { + // we should get rid of this nonsense with 4.4 (alex) + if ((strtolower($_GET["baseClass"]) != "ilrepositorygui") && + is_int(strpos($a_link, "baseClass=ilRepositoryGUI"))) { + if ($this->type != "frm") { + $a_link = + ilUtil::appendUrlParameterString($a_link, "rep_frame=1"); + } + } + + return $a_link; + } + + protected function modifyTitleLink($a_default_link) + { + if ($this->default_command_params) { + $params = array(); + foreach ($this->default_command_params as $name => $value) { + $params[] = $name . '=' . $value; + } + $params = implode('&', $params); + + + // #12370 + if (!stristr($a_default_link, '?')) { + $a_default_link = ($a_default_link . '?' . $params); + } else { + $a_default_link = ($a_default_link . '&' . $params); + } + } + return $a_default_link; + } + + /** + * workaround: SAHS in new javavasript-created window or iframe + */ + public function modifySAHSlaunch($a_link, $wtarget) + { + global $DIC; + + if (strstr($a_link, 'ilSAHSPresentationGUI') && !$this->offline_mode) { + include_once 'Modules/ScormAicc/classes/class.ilObjSAHSLearningModule.php'; + $sahs_obj = new ilObjSAHSLearningModule($this->ref_id); + $om = $sahs_obj->getOpenMode(); + $width = $sahs_obj->getWidth(); + $height = $sahs_obj->getHeight(); + if (($om == 5 || $om == 1) && $width > 0 && $height > 0) { + $om++; + } + if ($om != 0 && !$DIC['ilBrowser']->isMobile()) { + $this->default_command["frame"]=""; + $a_link = "javascript:void(0); onclick=startSAHS('" . $a_link . "','" . $wtarget . "'," . $om . "," . $width . "," . $height . ");"; + } + } + return $a_link; + } + + /** + * insert path + */ + public function insertPath() + { + $lng = $this->lng; + + if ($this->getPathStatus() != false) { + if (!$this->path_gui instanceof \ilPathGUI) { + $path_gui = new \ilPathGUI(); + } else { + $path_gui = $this->path_gui; + } + + $path_gui->enableTextOnly(!$this->path_linked); + $path_gui->setUseImages(false); + + $start_node = $this->path_start_node + ? $this->path_start_node + : ROOT_FOLDER_ID; + + $this->tpl->setCurrentBlock("path_item"); + $this->tpl->setVariable('PATH_ITEM', $path_gui->getPath($start_node, $this->ref_id)); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setCurrentBlock("path"); + $this->tpl->setVariable("TXT_LOCATION", $lng->txt("locator")); + $this->tpl->parseCurrentBlock(); + return true; + } + } + + /** + * insert progress info + * + * @access public + * @return + */ + public function insertProgressInfo() + { + return true; + } + + + /** + * Insert icons and checkboxes + */ + public function insertIconsAndCheckboxes() + { + $lng = $this->lng; + $objDefinition = $this->obj_definition; + + $cnt = 0; + if ($this->getCheckboxStatus()) { + $this->tpl->setCurrentBlock("check"); + $this->tpl->setVariable("VAL_ID", $this->getCommandId()); + $this->tpl->parseCurrentBlock(); + $cnt += 1; + } elseif ($this->getDownloadCheckboxState() != self::DOWNLOAD_CHECKBOX_NONE) { + $this->tpl->setCurrentBlock("check_download"); + if ($this->getDownloadCheckboxState() == self::DOWNLOAD_CHECKBOX_ENABLED) { + $this->tpl->setVariable("VAL_ID", $this->getCommandId()); + } else { + $this->tpl->setVariable("VAL_VISIBILITY", "visibility: hidden;\" disabled=\"disabled"); + } + $this->tpl->parseCurrentBlock(); + $cnt += 1; + } elseif ($this->getExpandStatus()) { + $this->tpl->setCurrentBlock('expand'); + + if ($this->isExpanded()) { + $this->ctrl->setParameter($this->container_obj, 'expand', -1 * $this->obj_id); + // "view" added, see #19922 + $this->tpl->setVariable('EXP_HREF', $this->ctrl->getLinkTarget($this->container_obj, 'view', $this->getUniqueItemId(true))); + $this->ctrl->clearParameters($this->container_obj); + $this->tpl->setVariable('EXP_IMG', ilUtil::getImagePath('tree_exp.svg')); + $this->tpl->setVariable('EXP_ALT', $this->lng->txt('collapse')); + } else { + $this->ctrl->setParameter($this->container_obj, 'expand', $this->obj_id); + // "view" added, see #19922 + $this->tpl->setVariable('EXP_HREF', $this->ctrl->getLinkTarget($this->container_obj, 'view', $this->getUniqueItemId(true))); + $this->ctrl->clearParameters($this->container_obj); + $this->tpl->setVariable('EXP_IMG', ilUtil::getImagePath('tree_col.svg')); + $this->tpl->setVariable('EXP_ALT', $this->lng->txt('expand')); + } + + $this->tpl->parseCurrentBlock(); + $cnt += 1; + } + + if ($this->getIconStatus()) { + if ($cnt == 1) { + $this->tpl->touchBlock("i_1"); // indent + } + + // icon link + if ($this->title_link_disabled || !$this->default_command || (!$this->getCommandsStatus() && !$this->restrict_to_goto)) { + } else { + $this->tpl->setCurrentBlock("icon_link_s"); + + if ($this->default_command["frame"] != "") { + $this->tpl->setVariable("ICON_TAR", "target='" . $this->default_command["frame"] . "'"); + } + + $this->tpl->setVariable( + "ICON_HREF", + $this->default_command["link"] + ); + $this->tpl->parseCurrentBlock(); + $this->tpl->touchBlock("icon_link_e"); + } + + $this->tpl->setCurrentBlock("icon"); + if (!$objDefinition->isPlugin($this->getIconImageType())) { + $this->tpl->setVariable("ALT_ICON", $lng->txt("icon") . " " . $lng->txt("obj_" . $this->getIconImageType())); + } else { + include_once("Services/Component/classes/class.ilPlugin.php"); + $this->tpl->setVariable("ALT_ICON", $lng->txt("icon") . " " . + ilObjectPlugin::lookupTxtById($this->getIconImageType(), "obj_" . $this->getIconImageType())); + } + + $this->tpl->setVariable( + "SRC_ICON", + $this->getTypeIcon() + ); + $this->tpl->parseCurrentBlock(); + $cnt += 1; + } + + $this->tpl->touchBlock("d_" . $cnt); // indent main div + } + + /** + * Get object type specific type icon + * @return string + */ + public function getTypeIcon() + { + return ilObject::_getIcon( + $this->obj_id, + 'small', + $this->getIconImageType() + ); + } + + /** + * Insert subitems + */ + public function insertSubItems() + { + foreach ($this->sub_item_html as $sub_html) { + $this->tpl->setCurrentBlock("subitem"); + $this->tpl->setVariable("SUBITEM", $sub_html); + $this->tpl->parseCurrentBlock(); + } + } + + /** + * Insert field for positioning + */ + public function insertPositionField() + { + if ($this->position_enabled) { + $this->tpl->setCurrentBlock("position"); + $this->tpl->setVariable("POS_ID", $this->position_field_index); + $this->tpl->setVariable("POS_VAL", $this->position_value); + $this->tpl->parseCurrentBlock(); + } + } + + /** + * returns whether any admin commands (link, delete, cut) + * are included in the output + */ + public function adminCommandsIncluded() + { + return $this->adm_commands_included; + } + + /** + * Store access cache + */ + public function storeAccessCache() + { + $ilUser = $this->user; + if ($this->acache->getLastAccessStatus() == "miss" && + !$this->prevent_access_caching) { + $this->acache->storeEntry( + $ilUser->getId() . ":" . $this->ref_id, + serialize($this->access_cache), + $this->ref_id + ); + } + } + + /** + * Get all item information (title, commands, description) in HTML + * + * @access public + * @param int $a_ref_id item reference id + * @param int $a_obj_id item object id + * @param int $a_title item title + * @param int $a_description item description + * @param bool $a_use_asynch + * @param bool $a_get_asynch_commands + * @param string $a_asynch_url + * @param bool $a_context workspace/tree context + * @return string html code + */ + public function getListItemHTML( + $a_ref_id, + $a_obj_id, + $a_title, + $a_description, + $a_use_asynch = false, + $a_get_asynch_commands = false, + $a_asynch_url = "" + ) { + $ilUser = $this->user; + + // this variable stores wheter any admin commands + // are included in the output + $this->adm_commands_included = false; + + // only for permformance exploration + $type = ilObject::_lookupType($a_obj_id); + + // initialization + $this->initItem($a_ref_id, $a_obj_id, $a_title, $a_description); + + // prepare ajax calls + include_once "Services/Object/classes/class.ilCommonActionDispatcherGUI.php"; + if ($this->context == self::CONTEXT_REPOSITORY) { + $node_type = ilCommonActionDispatcherGUI::TYPE_REPOSITORY; + } else { + $node_type = ilCommonActionDispatcherGUI::TYPE_WORKSPACE; + } + $this->setAjaxHash(ilCommonActionDispatcherGUI::buildAjaxHash($node_type, $a_ref_id, $type, $a_obj_id)); + + if ($a_use_asynch && $a_get_asynch_commands) { + return $this->insertCommands(true, true); + } + + if ($this->rating_enabled) { + if (ilRating::hasRatingInListGUI($this->obj_id, $this->type)) { + $may_rate = $this->checkCommandAccess("read", "", $this->ref_id, $this->type); + + $rating = new ilRatingGUI(); + $rating->setObject($this->obj_id, $this->type); + /* $this->addCustomProperty( + $this->lng->txt("rating_average_rating"), + $rating->getListGUIProperty($this->ref_id, $may_rate, $this->ajax_hash, $this->parent_ref_id), + false, + true + );*/ + $this->addCustomProperty( + "", + $rating->getListGUIProperty($this->ref_id, $may_rate, $this->ajax_hash, $this->parent_ref_id), + false, + true + ); + } + } + + // read from cache + include_once("Services/Object/classes/class.ilListItemAccessCache.php"); + $this->acache = new ilListItemAccessCache(); + $cres = $this->acache->getEntry($ilUser->getId() . ":" . $a_ref_id); + if ($this->acache->getLastAccessStatus() == "hit") { + $this->access_cache = unserialize($cres); + } else { + // write to cache + $this->storeAccessCache(); + } + + // visible check + if (!$this->checkCommandAccess("visible", "", $a_ref_id, "", $a_obj_id)) { + $this->resetCustomData(); + return ""; + } + + // BEGIN WEBDAV + if ($type=='file' and ilObjFileAccess::_isFileHidden($a_title)) { + $this->resetCustomData(); + return ""; + } + // END WEBDAV + + + $this->tpl = new ilTemplate( + static::$tpl_file_name, + true, + true, + static::$tpl_component, + "DEFAULT", + false, + true + ); + + if ($this->getCommandsStatus()) { + if (!$this->getSeparateCommands()) { + $this->tpl->setVariable( + "COMMAND_SELECTION_LIST", + $this->insertCommands($a_use_asynch, $a_get_asynch_commands, $a_asynch_url) + ); + } + } + + if ($this->getProgressInfoStatus()) { + $this->insertProgressInfo(); + } + + // insert title and describtion + $this->insertTitle(); + if (!$this->isMode(IL_LIST_AS_TRIGGER)) { + if ($this->getDescriptionStatus()) { + $this->insertDescription(); + } + } + + if ($this->getSearchFragmentStatus()) { + $this->insertSearchFragment(); + } + if ($this->enabledRelevance()) { + $this->insertRelevance(); + } + + // properties + if ($this->getPropertiesStatus()) { + $this->insertProperties(); + } + + // notice properties + if ($this->getNoticePropertiesStatus()) { + $this->insertNoticeProperties(); + } + + // preconditions + if ($this->getPreconditionsStatus()) { + $this->insertPreconditions(); + } + + // path + $this->insertPath(); + + if ($this->getItemDetailLinkStatus()) { + $this->insertItemDetailLinks(); + } + + // icons and checkboxes + $this->insertIconsAndCheckboxes(); + + // input field for position + $this->insertPositionField(); + + // subitems + $this->insertSubItems(); + + // file upload + if ($this->isFileUploadAllowed()) { + $this->insertFileUpload(); + } + + $this->resetCustomData(); + + $this->tpl->setVariable("DIV_CLASS", 'ilContainerListItemOuter'); + $this->tpl->setVariable("DIV_ID", 'data-list-item-id="' . $this->getUniqueItemId(true) . '" id = "' . $this->getUniqueItemId(true) . '"'); + $this->tpl->setVariable("ADDITIONAL", $this->getAdditionalInformation()); + + // #11554 - make sure that internal ids are reset + if (is_object($this->getContainerObject())) { + $this->ctrl->setParameter($this->getContainerObject(), "item_ref_id", ""); + } + + return $this->tpl->get(); + } + + /** + * reset properties and commands + */ + protected function resetCustomData() + { + // #15747 + $this->cust_prop = array(); + $this->cust_commands = array(); + $this->sub_item_html = array(); + $this->position_enabled = false; + } + + /** + * Set current parent ref id to enable unique js-ids (sessions, etc.) + * + * @param string $a_ref_id + */ + public function setParentRefId($a_ref_id) + { + $this->parent_ref_id = $a_ref_id; + } + + /** + * Get unique item identifier (for js-actions) + * + * @param bool $a_as_div + * @return string + */ + public function getUniqueItemId($a_as_div = false) + { + // use correct id for references + $id_ref = ($this->reference_ref_id > 0) + ? $this->reference_ref_id + : $this->ref_id; + + // add unique identifier for preconditions (objects can appear twice in same container) + if ($this->condition_depth) { + $id_ref .= "_pc" . $this->condition_depth; + } + + // unique + $id_ref .= "_pref_" . $this->parent_ref_id; + + if (!$a_as_div) { + return $id_ref; + } else { + // action menu [yellow] toggle + return "lg_div_" . $id_ref; + } + } + + /** + * Get commands HTML (must be called after get list item html) + */ + public function getCommandsHTML() + { + return $this->insertCommands(); + } + + /** + * Returns whether current item is a block in a side column or not + */ + public function isSideBlock() + { + return false; + } + + /** + * + * @access public + * @params boolean $a_bold_title set the item title bold + */ + public function setBoldTitle($a_bold_title) + { + $this->bold_title = $a_bold_title; + } + + /** + * + * @access public + * @return boolean returns if the item title is bold or not + */ + public function isTitleBold() + { + return $this->bold_title; + } + + /** + * Preload common properties + * + * @param + * @return + */ + public static function preloadCommonProperties($a_obj_ids, $a_context) + { + global $DIC; + + $lng = $DIC->language(); + $ilSetting = $DIC->settings(); + $ilUser = $DIC->user(); + + if ($a_context == self::CONTEXT_REPOSITORY) { + $active_notes = !$ilSetting->get("disable_notes"); + $active_comments = !$ilSetting->get("disable_comments"); + + if ($active_notes || $active_comments) { + include_once("./Services/Notes/classes/class.ilNote.php"); + } + + if ($active_comments) { + // needed for action + self::$comments_activation = ilNote::getRepObjActivation($a_obj_ids); + } + + // properties are optional + if ($ilSetting->get('comments_tagging_in_lists')) { + if ($active_notes || $active_comments) { + self::$cnt_notes = ilNote::_countNotesAndCommentsMultiple($a_obj_ids, true); + + $lng->loadLanguageModule("notes"); + } + + $tags_set = new ilSetting("tags"); + if ($tags_set->get("enable")) { + $all_users = $tags_set->get("enable_all_users"); + + include_once("./Services/Tagging/classes/class.ilTagging.php"); + if (!$ilSetting->get('comments_tagging_in_lists_tags')) { + self::$cnt_tags = ilTagging::_countTags($a_obj_ids, $all_users); + } else { + $tag_user_id = null; + if (!$all_users) { + $tag_user_id = $ilUser->getId(); + } + self::$tags = ilTagging::_getListTagsForObjects($a_obj_ids, $tag_user_id); + } + + $lng->loadLanguageModule("tagging"); + } + } + + $lng->loadLanguageModule("rating"); + } + + self::$preload_done = true; + } + + /** + * Check comments status against comments settings and context + * + * @param string $a_type + * @param int $a_ref_id + * @param int $a_obj_id + * @param bool $a_header_actions + * @param bool $a_check_write_access + * @return bool + */ + protected function isCommentsActivated($a_type, $a_ref_id, $a_obj_id, $a_header_actions, $a_check_write_access = true) + { + if ($this->comments_enabled) { + if (!$this->comments_settings_enabled) { + return true; + } + if ($a_check_write_access && $this->checkCommandAccess('write', '', $a_ref_id, $a_type)) { + return true; + } + // fallback to single object check if no preloaded data + // only the repository does preloadCommonProperties() yet + if (!$a_header_actions && self::$preload_done) { + if (self::$comments_activation[$a_obj_id][$a_type]) { + return true; + } + } else { + include_once("./Services/Notes/classes/class.ilNote.php"); + if (ilNote::commentsActivated($a_obj_id, 0, $a_type)) { + return true; + } + } + } + return false; + } + + /** + * enable timings link + * + * @access public + * @param bool + * @return + */ + public function enableTimings($a_status) + { + $this->timings_enabled = (bool) $a_status; + } + + /** + * Gets a value indicating whether file uploads to this object are allowed or not. + * + * @return bool true, if file upload is allowed; otherwise, false. + */ + public function isFileUploadAllowed() + { + // check if file upload allowed + include_once("./Services/FileUpload/classes/class.ilFileUploadUtil.php"); + return ilFileUploadUtil::isUploadAllowed($this->ref_id, $this->type); + } + + /** + * Inserts a file upload component + */ + public function insertFileUpload() + { + include_once("./Services/FileUpload/classes/class.ilFileUploadGUI.php"); + ilFileUploadGUI::initFileUpload(); + + $upload = new ilFileUploadGUI($this->getUniqueItemId(true), $this->ref_id); + + $this->tpl->setCurrentBlock("fileupload"); + $this->tpl->setVariable("FILE_UPLOAD", $upload->getHTML()); + $this->tpl->parseCurrentBlock(); + } } - -?> diff --git a/Services/Object/classes/class.ilObjectListGUIFactory.php b/Services/Object/classes/class.ilObjectListGUIFactory.php index fcd9e14287b3e548cabb1e553ac6ed405793f577..59b34c7e815100eb6c3ca9930d527bb9bdbac472 100644 --- a/Services/Object/classes/class.ilObjectListGUIFactory.php +++ b/Services/Object/classes/class.ilObjectListGUIFactory.php @@ -13,24 +13,21 @@ include_once './Services/Object/classes/class.ilObjectListGUI.php'; */ class ilObjectListGUIFactory { - static function _getListGUIByType($a_type, $a_context = ilObjectListGUI::CONTEXT_REPOSITORY) - { - global $DIC; + public static function _getListGUIByType($a_type, $a_context = ilObjectListGUI::CONTEXT_REPOSITORY) + { + global $DIC; - $objDefinition = $DIC["objDefinition"]; - - $class = $objDefinition->getClassName($a_type); - $location = $objDefinition->getLocation($a_type); - $full_class = "ilObj".$class."ListGUI"; - if(file_exists($location."/class.".$full_class.".php")) - { - include_once($location."/class.".$full_class.".php"); - return new $full_class($a_context); - } + $objDefinition = $DIC["objDefinition"]; + + $class = $objDefinition->getClassName($a_type); + $location = $objDefinition->getLocation($a_type); + $full_class = "ilObj" . $class . "ListGUI"; + if (file_exists($location . "/class." . $full_class . ".php")) { + include_once($location . "/class." . $full_class . ".php"); + return new $full_class($a_context); + } - // php7-todo JL: throw exception instead? - return new ilObjectListGUI($a_context); - } - + // php7-todo JL: throw exception instead? + return new ilObjectListGUI($a_context); + } } // END class.ilObjectListGUIFactory -?> diff --git a/Services/Object/classes/class.ilObjectListGUIPreloader.php b/Services/Object/classes/class.ilObjectListGUIPreloader.php index 830da3bb91e5bc4e61371e6f52942aaa54285b3d..a3007b82fc0609e02a42a7851d8490f306f6c278 100644 --- a/Services/Object/classes/class.ilObjectListGUIPreloader.php +++ b/Services/Object/classes/class.ilObjectListGUIPreloader.php @@ -1,164 +1,155 @@ - - * @version $Id: class.ilObject.php 46291 2013-11-19 15:09:45Z jluetzen $ - */ -class ilObjectListGUIPreloader -{ - /** - * @var ilObjectDefinition - */ - protected $obj_definition; - - /** - * @var ilTree - */ - protected $tree; - - /** - * @var ilObjectDataCache - */ - protected $obj_data_cache; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - protected $context; // [int] - protected $obj_ids; // [array] - protected $obj_ids_by_type; // [array] - protected $ref_ids; // [array] - protected $ref_ids_by_type; // [array] - protected $types; // [array] - - public function __construct($a_context) - { - global $DIC; - - $this->obj_definition = $DIC["objDefinition"]; - $this->tree = $DIC->repositoryTree(); - $this->obj_data_cache = $DIC["ilObjDataCache"]; - $this->user = $DIC->user(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->context = $a_context; - } - - public function addItem($a_obj_id, $a_type, $a_ref_id = null) - { - $this->obj_ids[] = $a_obj_id; - $this->obj_ids_by_type[$a_type][] = $a_obj_id; - $this->types[] = $a_type; - - if($a_ref_id) - { - $this->ref_ids[] = $a_ref_id; - $this->ref_ids_by_type[$a_type][] = $a_ref_id; - } - } - - public function preload() - { - $objDefinition = $this->obj_definition; - $tree = $this->tree; - $ilObjDataCache = $this->obj_data_cache; - $ilUser = $this->user; - $rbacsystem = $this->rbacsystem; - - if(!$this->obj_ids) - { - return; - } - - $this->obj_ids = array_unique($this->obj_ids); - $this->types = array_unique($this->types); - if($this->ref_ids) - { - $this->ref_ids = array_unique($this->ref_ids); - } - - // type specific preloads - include_once("./Services/Conditions/classes/class.ilConditionHandler.php"); - foreach ($this->types as $type) - { - $this->obj_ids_by_type[$type] = array_unique($this->obj_ids_by_type[$type]); - - if(is_array($this->ref_ids_by_type[$type])) - { - $this->ref_ids_by_type[$type] = array_unique($this->ref_ids_by_type[$type]); - } - - if($this->context == ilObjectListGUI::CONTEXT_REPOSITORY || - $this->context == ilObjectListGUI::CONTEXT_PERSONAL_DESKTOP || - $this->context == ilObjectListGUI::CONTEXT_SEARCH) - { - ilConditionHandler::preloadPersistedConditionsForTargetRecords($type, - $this->obj_ids_by_type[$type]); - } - - $class = $objDefinition->getClassName($type); - $location = $objDefinition->getLocation($type); - if($class && $location) // #12775 - { - $full_class = "ilObj".$class."Access"; - include_once($location."/class.".$full_class.".php"); - if(class_exists($full_class)) - { - call_user_func(array($full_class, "_preloadData"), - $this->obj_ids_by_type[$type], $this->ref_ids_by_type[$type]); - } - } - } - - if($this->ref_ids) - { - $tree->preloadDeleted($this->ref_ids); - $tree->preloadDepthParent($this->ref_ids); - $ilObjDataCache->preloadReferenceCache($this->ref_ids, false); - $rbacsystem->preloadRbacPaCache($this->ref_ids, $ilUser->getId()); - - if($ilUser->getId != ANONYMOUS_USER_ID && - $this->context != ilObjectListGUI::CONTEXT_PERSONAL_DESKTOP) - { - ilObjUser::preloadIsDesktopItem($ilUser->getId(), $this->ref_ids); - } - - include_once("./Services/Object/classes/class.ilObjectActivation.php"); - ilObjectActivation::preloadData($this->ref_ids); - } - - include_once("./Services/Object/classes/class.ilObjectListGUI.php"); - ilObjectListGUI::preloadCommonProperties($this->obj_ids, $this->context); - - if($this->context == ilObjectListGUI::CONTEXT_REPOSITORY) - { - include_once("./Services/Rating/classes/class.ilRating.php"); - include_once("./Services/Rating/classes/class.ilRatingGUI.php"); - ilRating::preloadListGUIData($this->obj_ids); - - include_once("./Services/AdvancedMetaData/classes/class.ilAdvancedMDValues.php"); - ilAdvancedMDValues::preloadByObjIds($this->obj_ids); - } - - if($this->context == ilObjectListGUI::CONTEXT_REPOSITORY || - $this->context == ilObjectListGUI::CONTEXT_PERSONAL_DESKTOP || - $this->context == ilObjectListGUI::CONTEXT_SEARCH) - { - include_once("./Services/Tracking/classes/class.ilLPStatus.php"); - ilLPStatus::preloadListGUIData($this->obj_ids); - } - } -} - -?> \ No newline at end of file + + * @version $Id: class.ilObject.php 46291 2013-11-19 15:09:45Z jluetzen $ + */ +class ilObjectListGUIPreloader +{ + /** + * @var ilObjectDefinition + */ + protected $obj_definition; + + /** + * @var ilTree + */ + protected $tree; + + /** + * @var ilObjectDataCache + */ + protected $obj_data_cache; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + protected $context; // [int] + protected $obj_ids; // [array] + protected $obj_ids_by_type; // [array] + protected $ref_ids; // [array] + protected $ref_ids_by_type; // [array] + protected $types; // [array] + + public function __construct($a_context) + { + global $DIC; + + $this->obj_definition = $DIC["objDefinition"]; + $this->tree = $DIC->repositoryTree(); + $this->obj_data_cache = $DIC["ilObjDataCache"]; + $this->user = $DIC->user(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->context = $a_context; + } + + public function addItem($a_obj_id, $a_type, $a_ref_id = null) + { + $this->obj_ids[] = $a_obj_id; + $this->obj_ids_by_type[$a_type][] = $a_obj_id; + $this->types[] = $a_type; + + if ($a_ref_id) { + $this->ref_ids[] = $a_ref_id; + $this->ref_ids_by_type[$a_type][] = $a_ref_id; + } + } + + public function preload() + { + $objDefinition = $this->obj_definition; + $tree = $this->tree; + $ilObjDataCache = $this->obj_data_cache; + $ilUser = $this->user; + $rbacsystem = $this->rbacsystem; + + if (!$this->obj_ids) { + return; + } + + $this->obj_ids = array_unique($this->obj_ids); + $this->types = array_unique($this->types); + if ($this->ref_ids) { + $this->ref_ids = array_unique($this->ref_ids); + } + + // type specific preloads + include_once("./Services/Conditions/classes/class.ilConditionHandler.php"); + foreach ($this->types as $type) { + $this->obj_ids_by_type[$type] = array_unique($this->obj_ids_by_type[$type]); + + if (is_array($this->ref_ids_by_type[$type])) { + $this->ref_ids_by_type[$type] = array_unique($this->ref_ids_by_type[$type]); + } + + if ($this->context == ilObjectListGUI::CONTEXT_REPOSITORY || + $this->context == ilObjectListGUI::CONTEXT_PERSONAL_DESKTOP || + $this->context == ilObjectListGUI::CONTEXT_SEARCH) { + ilConditionHandler::preloadPersistedConditionsForTargetRecords( + $type, + $this->obj_ids_by_type[$type] + ); + } + + $class = $objDefinition->getClassName($type); + $location = $objDefinition->getLocation($type); + if ($class && $location) { // #12775 + $full_class = "ilObj" . $class . "Access"; + include_once($location . "/class." . $full_class . ".php"); + if (class_exists($full_class)) { + call_user_func( + array($full_class, "_preloadData"), + $this->obj_ids_by_type[$type], + $this->ref_ids_by_type[$type] + ); + } + } + } + + if ($this->ref_ids) { + $tree->preloadDeleted($this->ref_ids); + $tree->preloadDepthParent($this->ref_ids); + $ilObjDataCache->preloadReferenceCache($this->ref_ids, false); + $rbacsystem->preloadRbacPaCache($this->ref_ids, $ilUser->getId()); + + if ($ilUser->getId != ANONYMOUS_USER_ID && + $this->context != ilObjectListGUI::CONTEXT_PERSONAL_DESKTOP) { + ilObjUser::preloadIsDesktopItem($ilUser->getId(), $this->ref_ids); + } + + include_once("./Services/Object/classes/class.ilObjectActivation.php"); + ilObjectActivation::preloadData($this->ref_ids); + } + + include_once("./Services/Object/classes/class.ilObjectListGUI.php"); + ilObjectListGUI::preloadCommonProperties($this->obj_ids, $this->context); + + if ($this->context == ilObjectListGUI::CONTEXT_REPOSITORY) { + include_once("./Services/Rating/classes/class.ilRating.php"); + include_once("./Services/Rating/classes/class.ilRatingGUI.php"); + ilRating::preloadListGUIData($this->obj_ids); + + include_once("./Services/AdvancedMetaData/classes/class.ilAdvancedMDValues.php"); + ilAdvancedMDValues::preloadByObjIds($this->obj_ids); + } + + if ($this->context == ilObjectListGUI::CONTEXT_REPOSITORY || + $this->context == ilObjectListGUI::CONTEXT_PERSONAL_DESKTOP || + $this->context == ilObjectListGUI::CONTEXT_SEARCH) { + include_once("./Services/Tracking/classes/class.ilLPStatus.php"); + ilLPStatus::preloadListGUIData($this->obj_ids); + } + } +} diff --git a/Services/Object/classes/class.ilObjectMetaDataBlockGUI.php b/Services/Object/classes/class.ilObjectMetaDataBlockGUI.php index da766002ea79fb7bf570b587713df029adb348eb..8ede3306f28a7f4c9afcf9f57c364d82c9a47142 100644 --- a/Services/Object/classes/class.ilObjectMetaDataBlockGUI.php +++ b/Services/Object/classes/class.ilObjectMetaDataBlockGUI.php @@ -16,136 +16,127 @@ include_once("Services/Block/classes/class.ilBlockGUI.php"); */ class ilObjectMetaDataBlockGUI extends ilBlockGUI { - static $block_type = "advmd"; - - protected $record; // [ilAdvancedMDRecord] - protected $values; // [ilAdvancedMDValues] - protected $callback; // [string] - - static protected $records = array(); // [array] - - /** - * Constructor - */ - function __construct(ilAdvancedMDRecord $a_record, $a_decorator_callback = null) - { - global $DIC; + public static $block_type = "advmd"; + + protected $record; // [ilAdvancedMDRecord] + protected $values; // [ilAdvancedMDValues] + protected $callback; // [string] + + protected static $records = array(); // [array] + + /** + * Constructor + */ + public function __construct(ilAdvancedMDRecord $a_record, $a_decorator_callback = null) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - parent::__construct(); - - $this->record = $a_record; - $this->callback = $a_decorator_callback; - - $this->setTitle($this->record->getTitle()); - $this->setBlockId("advmd_".$this->record->getRecordId()); - $this->setEnableNumInfo(false); - // $this->setAvailableDetailLevels(3); - $this->allow_moving = false; - } + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + parent::__construct(); + + $this->record = $a_record; + $this->callback = $a_decorator_callback; + + $this->setTitle($this->record->getTitle()); + $this->setBlockId("advmd_" . $this->record->getRecordId()); + $this->setEnableNumInfo(false); + // $this->setAvailableDetailLevels(3); + $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; - } - - public function setValues(ilAdvancedMDValues $a_values) - { - $this->values = $a_values; - } + /** + * @inheritdoc + */ + protected function isRepositoryObject() : bool + { + return false; + } + + /** + * Get Screen Mode for current command. + */ + public static function getScreenMode() + { + return IL_SCREEN_SIDE; + } + + public function setValues(ilAdvancedMDValues $a_values) + { + $this->values = $a_values; + } - /** - * 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(); + } + } - /** - * Fill data section - */ - function fillDataSection() - { - $lng = $this->lng; - - $btpl = new ilTemplate("tpl.advmd_block.html", true, true, "Services/Object"); - - // see ilAdvancedMDRecordGUI::parseInfoPage() - - $old_dt = ilDatePresentation::useRelativeDates(); - ilDatePresentation::setUseRelativeDates(false); - - include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDValues.php'); - include_once('Services/ADT/classes/class.ilADTFactory.php'); - - // this correctly binds group and definitions - $this->values->read(); + /** + * Fill data section + */ + public function fillDataSection() + { + $lng = $this->lng; + + $btpl = new ilTemplate("tpl.advmd_block.html", true, true, "Services/Object"); + + // see ilAdvancedMDRecordGUI::parseInfoPage() + + $old_dt = ilDatePresentation::useRelativeDates(); + ilDatePresentation::setUseRelativeDates(false); + + include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDValues.php'); + include_once('Services/ADT/classes/class.ilADTFactory.php'); + + // this correctly binds group and definitions + $this->values->read(); - $defs = $this->values->getDefinitions(); - foreach($this->values->getADTGroup()->getElements() as $element_id => $element) - { - $btpl->setCurrentBlock("item"); - $btpl->setVariable("CAPTION", $defs[$element_id]->getTitle()); - if($element->isNull()) - { - $value = "-"; - } - else - { - $value = ilADTFactory::getInstance()->getPresentationBridgeForInstance($element); + $defs = $this->values->getDefinitions(); + foreach ($this->values->getADTGroup()->getElements() as $element_id => $element) { + $btpl->setCurrentBlock("item"); + $btpl->setVariable("CAPTION", $defs[$element_id]->getTitle()); + if ($element->isNull()) { + $value = "-"; + } else { + $value = ilADTFactory::getInstance()->getPresentationBridgeForInstance($element); - if($element instanceof ilADTLocation) - { - $value->setSize("100%", "200px"); - } - - if(in_array($element->getType(), array("MultiEnum", "Enum", "Text"))) - { - $value->setDecoratorCallBack($this->callback); - } + if ($element instanceof ilADTLocation) { + $value->setSize("100%", "200px"); + } + + if (in_array($element->getType(), array("MultiEnum", "Enum", "Text"))) { + $value->setDecoratorCallBack($this->callback); + } - $value = $value->getHTML(); - } - $btpl->setVariable("VALUE", $value); - $btpl->parseCurrentBlock(); - } - - $this->setDataSection($btpl->get()); - - ilDatePresentation::setUseRelativeDates($old_dt); - - return; - } + $value = $value->getHTML(); + } + $btpl->setVariable("VALUE", $value); + $btpl->parseCurrentBlock(); + } + + $this->setDataSection($btpl->get()); + + ilDatePresentation::setUseRelativeDates($old_dt); + + return; + } } - -?> diff --git a/Services/Object/classes/class.ilObjectMetaDataGUI.php b/Services/Object/classes/class.ilObjectMetaDataGUI.php index 7985a5def0e845e0e2ae903af7fd9db83855a644..5e0fe64f1bd675e171cdf8eec93dbed7fed3b52f 100644 --- a/Services/Object/classes/class.ilObjectMetaDataGUI.php +++ b/Services/Object/classes/class.ilObjectMetaDataGUI.php @@ -6,703 +6,657 @@ * * @author Jörg Lützenkirchen * @version $Id$ -* +* * @ilCtrl_Calls ilObjectMetaDataGUI: ilMDEditorGUI, ilAdvancedMDSettingsGUI, ilPropertyFormGUI, ilTaxMDGUI, ilObjTaxonomyGUI */ class ilObjectMetaDataGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTemplate - */ - protected $tpl; - - protected $object; // [ilObject] - protected $ref_id; - protected $obj_id; // [int] - protected $obj_type; // [string] - protected $sub_type; // [string] - protected $sub_id; // [int] - protected $md_observers; // [array] - - /** - * @var ilLogger - */ - private $logger = null; - - protected $tax_md_gui = null; - protected $tax_obj_gui = null; - protected $taxonomy_settings_form_manipulator = null; - protected $taxonomy_settings_form_saver = null; - - // $adv_ref_id - $adv_type - $adv_subtype: - // Object, that defines the adv md records being used. Default is $this->object, but the - // context may set another object (e.g. media pool for media objects) - /** - * @var int - */ - protected $adv_ref_id = null; - /** - * @var string - */ - protected $adv_type = null; - /** - * @var string - */ - protected $adv_subtype = null; - - /** - * Construct - * - * @param ilObject $a_object - * @param string $a_sub_type - * @return self - */ - public function __construct(ilObject $a_object = null, $a_sub_type = null, $a_sub_id = null) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - $this->tabs = $DIC->tabs(); - - - $this->logger = $GLOBALS['DIC']->logger()->obj(); - - $this->in_workspace = (bool) $_REQUEST["wsp_id"]; - - $this->sub_type = $a_sub_type; - $this->sub_id = $a_sub_id; - - - - if(!$this->sub_type) - { - $this->sub_type = "-"; - } - - if($a_object) - { - $this->object = $a_object; - $this->obj_id = $a_object->getId(); - $this->obj_type = $a_object->getType(); - $this->ref_id = $a_object->getRefId(); - - if(!$a_object->withReferences()) - { - $this->logger->logStack(ilLogLevel::WARNING); - $this->logger->warning('ObjectMetaDataGUI called without valid reference id.'); - } - - if(!$this->ref_id) - { - $this->logger->logStack(ilLogLevel::WARNING); - $this->logger->warning('ObjectMetaDataGUI called without valid reference id.'); - } - - $this->md_obj = new ilMD((int)$this->obj_id, (int)$this->sub_id, $this->getLOMType()); - - if (!$this->in_workspace) - { - // (parent) container taxonomies? - include_once "Services/Taxonomy/classes/class.ilTaxMDGUI.php"; - $this->tax_md_gui = new ilTaxMDGUI($this->md_obj->getRBACId(),$this->md_obj->getObjId(),$this->md_obj->getObjType(),$this->ref_id); - $tax_ids = $this->tax_md_gui->getSelectableTaxonomies(); - if(!is_array($tax_ids) || count($tax_ids) == 0) - { - $this->tax_md_gui = null; - } - } - - } - - $this->lng->loadLanguageModule("meta"); - $this->lng->loadLanguageModule("tax"); - } - - public function executeCommand() - { - $ilCtrl = $this->ctrl; - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd("edit"); - - switch($next_class) - { - case 'ilmdeditorgui': - $this->setSubTabs("lom"); - include_once 'Services/MetaData/classes/class.ilMDEditorGUI.php'; - $md_gui = new ilMDEditorGUI((int)$this->obj_id, (int)$this->sub_id, $this->getLOMType()); - // custom observers? - if(is_array($this->md_observers)) - { - foreach($this->md_observers as $observer) - { - $md_gui->addObserver($observer["class"], $observer["method"], $observer["section"]); - } - } - // "default" repository object observer - else if(!$this->sub_id && - $this->object) - { - $md_gui->addObserver($this->object, 'MDUpdateListener', 'General'); - } - $ilCtrl->forwardCommand($md_gui); - break; - - case 'iladvancedmdsettingsgui': - $this->setSubTabs("advmddef"); - include_once 'Services/AdvancedMetaData/classes/class.ilAdvancedMDSettingsGUI.php'; - $advmdgui = new ilAdvancedMDSettingsGUI($this->ref_id, $this->obj_type, $this->sub_type); - $ilCtrl->forwardCommand($advmdgui); - break; - - case 'iltaxmdgui': - $this->setSubTabs("tax_assignment"); - $ilCtrl->forwardCommand($this->tax_md_gui); - break; - - case 'ilobjtaxonomygui': - $this->setSubTabs("tax_definition"); - include_once("./Services/Taxonomy/classes/class.ilObjTaxonomyGUI.php"); - $ilCtrl->forwardCommand($this->tax_obj_gui); - break; - - case "ilpropertyformgui": - // only case is currently adv metadata internal link in info settings, see #24497 - $form = $this->initEditForm(); - $ilCtrl->forwardCommand($form); - break; - - default: - $this->setSubTabs("advmd"); - $this->$cmd(); - break; - } - } - - /** - * Set taxonomy settings - * - * @param string $a_link link traget - */ - function setTaxonomySettings(closure $a_form_manipulator, closure $a_form_saver) - { - $this->taxonomy_settings_form_manipulator = $a_form_manipulator; - $this->taxonomy_settings_form_saver = $a_form_saver; - } - - /** - * Get taxonomy settings - * - * @return string link traget - */ - function getTaxonomySettings() - { - return $this->taxonomy_settings; - } - - /** - * Enable taxonomy definition - * - * @param - * @return - */ - function enableTaxonomyDefinition($a_enable) - { - if ($a_enable) - { - $this->tax_obj_gui = new ilObjTaxonomyGUI(); - $this->tax_obj_gui->setAssignedObject($this->object->getId()); - } - else - { - $this->tax_obj_gui = null; - } - } - - /** - * Get taxonomy obj gui - * - * @return ilObjTaxonomyGUI|null - */ - function getTaxonomyObjGUI() - { - return $this->tax_obj_gui; - } - - - public function addMDObserver($a_class, $a_method, $a_section) - { - $this->md_observers[] = array( - "class" => $a_class, - "method" => $a_method, - "section" => $a_section - ); - } - - protected function getLOMType() - { - if($this->sub_type != "-" && - $this->sub_id) - { - return $this->sub_type; - } - else - { - return $this->obj_type; - } - } - - /** - * Set object, that defines the adv md records being used. Default is $this->object, but the - * context may set another object (e.g. media pool for media objects) - * - * @param string $a_val adv type - */ - function setAdvMdRecordObject($a_adv_ref_id, $a_adv_type, $a_adv_subtype = "-") - { - $this->adv_ref_id = $a_adv_ref_id; - $this->adv_type = $a_adv_type; - $this->adv_subtype = $a_adv_subtype; - } - - /** - * Get adv md record type - * - * @return array adv type - */ - function getAdvMdRecordObject() - { - if ($this->adv_type == null) - { - return [$this->ref_id, $this->obj_type, $this->sub_type]; - } - return [$this->adv_ref_id, $this->adv_type, $this->adv_subtype]; - } - - - protected function isAdvMDAvailable() - { -// $this->setAdvMdRecordObject(70,"mep", "mob"); - include_once 'Services/AdvancedMetaData/classes/class.ilAdvancedMDRecord.php'; - foreach(ilAdvancedMDRecord::_getAssignableObjectTypes(false) as $item) - { - list ($adv_ref_id, $adv_type, $adv_subtype) = $this->getAdvMdRecordObject(); - -// echo ("
                  ".$item["obj_type"]."-".$adv_type."-".$adv_subtype); - if($item["obj_type"] == $adv_type) - { -// ("
                  -- ".$adv_type."-".$adv_subtype); -// exit; - return ((!$item["sub_type"] && $adv_subtype == "-") || - ($item["sub_type"] == $adv_subtype)); - } - } -// exit; - return false; - } - - protected function isLOMAvailable() - { - $type = $this->getLOMType(); - if($type == $this->sub_type) - { - $type = $this->obj_type.":".$type; - } - - return (($this->obj_id || !$this->obj_type) && - in_array($type, array( - "crs", - 'grp', - "file", - "glo", "glo:gdf", - "svy", "spl", - "tst", "qpl", - ":mob", - "webr", - "htlm", - "lm", "lm:st", "lm:pg", - "sahs", "sahs:sco", "sahs:page", - 'sess', "iass" - ))); - } - - protected function hasAdvancedMDSettings() - { - if($this->sub_id) - { - return false; - } - - include_once 'Services/Container/classes/class.ilContainer.php'; - include_once 'Services/Object/classes/class.ilObjectServiceSettingsGUI.php'; - - return ilContainer::_lookupContainerSetting( - $this->obj_id, - ilObjectServiceSettingsGUI::CUSTOM_METADATA, - false); - } - - /** - * check if active records exist in current path anf for object type - * @return type - */ - protected function hasActiveRecords() - { - include_once 'Services/AdvancedMetaData/classes/class.ilAdvancedMDRecord.php'; - - list ($adv_ref_id, $adv_type, $adv_subtype) = $this->getAdvMdRecordObject(); - - return - (bool) sizeof(ilAdvancedMDRecord::_getSelectedRecordsByObject( - $adv_type, - $adv_ref_id, - $adv_subtype)); - } - - protected function canEdit() - { -// if($this->hasActiveRecords() && -// $this->obj_id) -// { - if($this->hasActiveRecords()) - { - if($this->sub_type == "-" || - $this->sub_id) - { - return true; - } - } - return false; - } - - /** - * Get tab link if available - * - * @param null $a_base_class - * @return null|string - */ - public function getTab($a_base_class = null) - { - $ilCtrl = $this->ctrl; - - if(!$a_base_class) - { - $path = array(); - } - else - { - $path = array($a_base_class); - } - $path[] = "ilobjectmetadatagui"; - - $link = null; - if($this->isLOMAvailable()) - { - $path[] = "ilmdeditorgui"; - $link = $ilCtrl->getLinkTargetByClass($path, "listSection"); - } - else if($this->isAdvMDAvailable()) - { - if($this->canEdit()) - { - $link = $ilCtrl->getLinkTarget($this, "edit"); - } - else if($this->hasAdvancedMDSettings()) - { - $path[] = "iladvancedmdsettingsgui"; - $link = $ilCtrl->getLinkTargetByClass($path, "showRecords"); - } - } - if ($link == null && is_object($this->tax_obj_gui)) // taxonomy definition available? - { - $path[] = "ilobjtaxonomygui"; - $link = $ilCtrl->getLinkTargetByClass($path, ""); - } - return $link; - } - - public function setSubTabs($a_active) - { - $ilTabs = $this->tabs; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if($this->isLOMAvailable()) - { - $ilTabs->addSubTab("lom", - $lng->txt("meta_tab_lom"), - $ilCtrl->getLinkTargetByClass("ilmdeditorgui", "listSection") - ); - } - if($this->isAdvMDAvailable()) - { - if($this->canEdit()) - { - $ilTabs->addSubTab("advmd", - $lng->txt("meta_tab_advmd"), - $ilCtrl->getLinkTarget($this, "edit")); - } - if($this->hasAdvancedMDSettings()) - { - $ilTabs->addSubTab("advmddef", - $lng->txt("meta_tab_advmd_def"), - $ilCtrl->getLinkTargetByClass("iladvancedmdsettingsgui", "showRecords")); - - $ilTabs->addSubTab("md_adv_file_list", - $lng->txt("md_adv_file_list"), - $ilCtrl->getLinkTargetByClass("iladvancedmdsettingsgui", "showFiles")); - } - } - - if ($this->tax_md_gui != null) - { - $this->tax_md_gui->addSubTab(); - } - - if ($this->tax_obj_gui != null) - { - $ilTabs->addSubTab("tax_definition", $lng->txt("cntr_taxonomy_definitions"), - $ilCtrl->getLinkTargetByClass("ilobjtaxonomygui", "")); - } - - if ($this->taxonomy_settings_form_manipulator != null) - { - $ilTabs->addSubTab("tax_settings", $lng->txt("tax_tax_settings"), - $ilCtrl->getLinkTarget($this, "editTaxonomySettings")); - } - - $ilTabs->activateSubTab($a_active); - } - - - // - // (VALUES) EDITOR - // - - protected function initEditForm() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this, "update")); - $form->setTitle($lng->txt("meta_tab_advmd")); - - include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecordGUI.php'); - $this->record_gui = new ilAdvancedMDRecordGUI( - ilAdvancedMDRecordGUI::MODE_EDITOR, - $this->obj_type, - $this->obj_id, - $this->sub_type, - $this->sub_id - ); - - if ($this->adv_type != "") - { - $this->record_gui->setAdvMdRecordObject($this->adv_ref_id, $this->adv_type, $this->adv_subtype); - } - - $this->record_gui->setPropertyForm($form); - $this->record_gui->parse(); - - $form->addCommandButton("update", $lng->txt("save")); - - return $form; - } - - protected function edit(ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - - if(!$a_form) - { - $a_form = $this->initEditForm(); - } - - $tpl->setContent($a_form->getHTML()); - } - - protected function update() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $form = $this->initEditForm(); - if( - $form->checkInput() && - $this->record_gui->importEditFormPostValues()) - { - $this->record_gui->writeEditForm(); - - // Update ECS content - if($this->obj_type == "crs") - { - include_once "Modules/Course/classes/class.ilECSCourseSettings.php"; - $ecs = new ilECSCourseSettings($this->object); - $ecs->handleContentUpdate(); - } - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - $ilCtrl->redirect($this, "edit"); - } - - $form->setValuesByPost(); - $this->edit($form); - } - - - // - // BLOCK - // - - public function getBlockHTML(array $a_cmds = null, $a_callback = null) - { - $lng = $this->lng; - - $html = ""; - - include_once "Services/Object/classes/class.ilObjectMetaDataBlockGUI.php"; - include_once "Services/AdvancedMetaData/classes/class.ilAdvancedMDRecord.php"; - include_once "Services/AdvancedMetaData/classes/class.ilAdvancedMDValues.php"; - list ($adv_ref_id, $adv_type, $adv_subtype) = $this->getAdvMdRecordObject(); - foreach(ilAdvancedMDRecord::_getSelectedRecordsByObject($adv_type, $adv_ref_id, $adv_subtype) as $record) - { - $block = new ilObjectMetaDataBlockGUI($record, $a_callback); - $block->setValues(new ilAdvancedMDValues($record->getRecordId(), $this->obj_id, $this->sub_type, $this->sub_id)); - if($a_cmds) - { - foreach($a_cmds as $caption => $url) - { - $block->addBlockCommand($url, $lng->txt($caption), "_top"); - } - } - $html.= $block->getHTML(); - } - - return $html; - } - - - // - // Key/value list - // - - - public function getKeyValueList() - { - $html = ""; - $sep = ""; - - $old_dt = ilDatePresentation::useRelativeDates(); - ilDatePresentation::setUseRelativeDates(false); - - include_once "Services/AdvancedMetaData/classes/class.ilAdvancedMDRecord.php"; - include_once "Services/AdvancedMetaData/classes/class.ilAdvancedMDValues.php"; - list ($adv_ref_id, $adv_type, $adv_subtype) = $this->getAdvMdRecordObject(); - foreach(ilAdvancedMDRecord::_getSelectedRecordsByObject($adv_type, $adv_ref_id, $adv_subtype) as $record) - { - $vals = new ilAdvancedMDValues($record->getRecordId(), $this->obj_id, $this->sub_type, $this->sub_id); - - - include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDValues.php'); - include_once('Services/ADT/classes/class.ilADTFactory.php'); - - // this correctly binds group and definitions - $vals->read(); - - $defs = $vals->getDefinitions(); - foreach ($vals->getADTGroup()->getElements() as $element_id => $element) - { - if($element instanceof ilADTLocation) - { - continue; - } - - $html.= $sep.$defs[$element_id]->getTitle().": "; - - if($element->isNull()) - { - $value = "-"; - } - else - { - $value = ilADTFactory::getInstance()->getPresentationBridgeForInstance($element); - - $value = $value->getHTML(); - } - $html.= $value; - $sep = ",    "; - } - - } - - ilDatePresentation::setUseRelativeDates($old_dt); - - return $html; - } - - protected function editTaxonomySettings() - { - $this->tabs->activateSubTab("tax_settings"); - - $form = $this->initTaxonomySettingsForm(); - $this->tpl->setContent($form->getHTML()); - } - - /** - * Init taxonomy settings form. - */ - protected function initTaxonomySettingsForm() - { - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this), "saveTaxonomySettings"); - $form->setTitle($this->lng->txt("tax_tax_settings")); - $this->taxonomy_settings_form_manipulator->bindTo($this); - call_user_func_array($this->taxonomy_settings_form_manipulator, [$form]); - $form->addCommandButton("saveTaxonomySettings", $this->lng->txt("save")); - - return $form; - } - - /** - * Save taxonomy settings form - */ - protected function saveTaxonomySettings() - { - $form = $this->initTaxonomySettingsForm(); - if ($form->checkInput()) - { - $this->taxonomy_settings_form_saver->bindTo($this); - call_user_func_array($this->taxonomy_settings_form_saver, [$form]); - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "editTaxonomySettings"); - } - else - { - $form->setValuesByPost(); - $this->tpl->setContent($form->getHtml()); - } - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTemplate + */ + protected $tpl; + + protected $object; // [ilObject] + protected $ref_id; + protected $obj_id; // [int] + protected $obj_type; // [string] + protected $sub_type; // [string] + protected $sub_id; // [int] + protected $md_observers; // [array] + + /** + * @var ilLogger + */ + private $logger = null; + + protected $tax_md_gui = null; + protected $tax_obj_gui = null; + protected $taxonomy_settings_form_manipulator = null; + protected $taxonomy_settings_form_saver = null; + + // $adv_ref_id - $adv_type - $adv_subtype: + // Object, that defines the adv md records being used. Default is $this->object, but the + // context may set another object (e.g. media pool for media objects) + /** + * @var int + */ + protected $adv_ref_id = null; + /** + * @var string + */ + protected $adv_type = null; + /** + * @var string + */ + protected $adv_subtype = null; + + /** + * Construct + * + * @param ilObject $a_object + * @param string $a_sub_type + * @return self + */ + public function __construct(ilObject $a_object = null, $a_sub_type = null, $a_sub_id = null) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + $this->tabs = $DIC->tabs(); + + + $this->logger = $GLOBALS['DIC']->logger()->obj(); + + $this->in_workspace = (bool) $_REQUEST["wsp_id"]; + + $this->sub_type = $a_sub_type; + $this->sub_id = $a_sub_id; + + + + if (!$this->sub_type) { + $this->sub_type = "-"; + } + + if ($a_object) { + $this->object = $a_object; + $this->obj_id = $a_object->getId(); + $this->obj_type = $a_object->getType(); + $this->ref_id = $a_object->getRefId(); + + if (!$a_object->withReferences()) { + $this->logger->logStack(ilLogLevel::WARNING); + $this->logger->warning('ObjectMetaDataGUI called without valid reference id.'); + } + + if (!$this->ref_id) { + $this->logger->logStack(ilLogLevel::WARNING); + $this->logger->warning('ObjectMetaDataGUI called without valid reference id.'); + } + + $this->md_obj = new ilMD((int) $this->obj_id, (int) $this->sub_id, $this->getLOMType()); + + if (!$this->in_workspace) { + // (parent) container taxonomies? + include_once "Services/Taxonomy/classes/class.ilTaxMDGUI.php"; + $this->tax_md_gui = new ilTaxMDGUI($this->md_obj->getRBACId(), $this->md_obj->getObjId(), $this->md_obj->getObjType(), $this->ref_id); + $tax_ids = $this->tax_md_gui->getSelectableTaxonomies(); + if (!is_array($tax_ids) || count($tax_ids) == 0) { + $this->tax_md_gui = null; + } + } + } + + $this->lng->loadLanguageModule("meta"); + $this->lng->loadLanguageModule("tax"); + } + + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd("edit"); + + switch ($next_class) { + case 'ilmdeditorgui': + $this->setSubTabs("lom"); + include_once 'Services/MetaData/classes/class.ilMDEditorGUI.php'; + $md_gui = new ilMDEditorGUI((int) $this->obj_id, (int) $this->sub_id, $this->getLOMType()); + // custom observers? + if (is_array($this->md_observers)) { + foreach ($this->md_observers as $observer) { + $md_gui->addObserver($observer["class"], $observer["method"], $observer["section"]); + } + } + // "default" repository object observer + elseif (!$this->sub_id && + $this->object) { + $md_gui->addObserver($this->object, 'MDUpdateListener', 'General'); + } + $ilCtrl->forwardCommand($md_gui); + break; + + case 'iladvancedmdsettingsgui': + $this->setSubTabs("advmddef"); + include_once 'Services/AdvancedMetaData/classes/class.ilAdvancedMDSettingsGUI.php'; + $advmdgui = new ilAdvancedMDSettingsGUI($this->ref_id, $this->obj_type, $this->sub_type); + $ilCtrl->forwardCommand($advmdgui); + break; + + case 'iltaxmdgui': + $this->setSubTabs("tax_assignment"); + $ilCtrl->forwardCommand($this->tax_md_gui); + break; + + case 'ilobjtaxonomygui': + $this->setSubTabs("tax_definition"); + include_once("./Services/Taxonomy/classes/class.ilObjTaxonomyGUI.php"); + $ilCtrl->forwardCommand($this->tax_obj_gui); + break; + + case "ilpropertyformgui": + // only case is currently adv metadata internal link in info settings, see #24497 + $form = $this->initEditForm(); + $ilCtrl->forwardCommand($form); + break; + + default: + $this->setSubTabs("advmd"); + $this->$cmd(); + break; + } + } + + /** + * Set taxonomy settings + * + * @param string $a_link link traget + */ + public function setTaxonomySettings(closure $a_form_manipulator, closure $a_form_saver) + { + $this->taxonomy_settings_form_manipulator = $a_form_manipulator; + $this->taxonomy_settings_form_saver = $a_form_saver; + } + + /** + * Get taxonomy settings + * + * @return string link traget + */ + public function getTaxonomySettings() + { + return $this->taxonomy_settings; + } + + /** + * Enable taxonomy definition + * + * @param + * @return + */ + public function enableTaxonomyDefinition($a_enable) + { + if ($a_enable) { + $this->tax_obj_gui = new ilObjTaxonomyGUI(); + $this->tax_obj_gui->setAssignedObject($this->object->getId()); + } else { + $this->tax_obj_gui = null; + } + } + + /** + * Get taxonomy obj gui + * + * @return ilObjTaxonomyGUI|null + */ + public function getTaxonomyObjGUI() + { + return $this->tax_obj_gui; + } + + + public function addMDObserver($a_class, $a_method, $a_section) + { + $this->md_observers[] = array( + "class" => $a_class, + "method" => $a_method, + "section" => $a_section + ); + } + + protected function getLOMType() + { + if ($this->sub_type != "-" && + $this->sub_id) { + return $this->sub_type; + } else { + return $this->obj_type; + } + } + + /** + * Set object, that defines the adv md records being used. Default is $this->object, but the + * context may set another object (e.g. media pool for media objects) + * + * @param string $a_val adv type + */ + public function setAdvMdRecordObject($a_adv_ref_id, $a_adv_type, $a_adv_subtype = "-") + { + $this->adv_ref_id = $a_adv_ref_id; + $this->adv_type = $a_adv_type; + $this->adv_subtype = $a_adv_subtype; + } + + /** + * Get adv md record type + * + * @return array adv type + */ + public function getAdvMdRecordObject() + { + if ($this->adv_type == null) { + return [$this->ref_id, $this->obj_type, $this->sub_type]; + } + return [$this->adv_ref_id, $this->adv_type, $this->adv_subtype]; + } + + + protected function isAdvMDAvailable() + { + // $this->setAdvMdRecordObject(70,"mep", "mob"); + include_once 'Services/AdvancedMetaData/classes/class.ilAdvancedMDRecord.php'; + foreach (ilAdvancedMDRecord::_getAssignableObjectTypes(false) as $item) { + list($adv_ref_id, $adv_type, $adv_subtype) = $this->getAdvMdRecordObject(); + + // echo ("
                  ".$item["obj_type"]."-".$adv_type."-".$adv_subtype); + if ($item["obj_type"] == $adv_type) { + // ("
                  -- ".$adv_type."-".$adv_subtype); + // exit; + return ((!$item["sub_type"] && $adv_subtype == "-") || + ($item["sub_type"] == $adv_subtype)); + } + } + // exit; + return false; + } + + protected function isLOMAvailable() + { + $type = $this->getLOMType(); + if ($type == $this->sub_type) { + $type = $this->obj_type . ":" . $type; + } + + return (($this->obj_id || !$this->obj_type) && + in_array($type, array( + "crs", + 'grp', + "file", + "glo", "glo:gdf", + "svy", "spl", + "tst", "qpl", + ":mob", + "webr", + "htlm", + "lm", "lm:st", "lm:pg", + "sahs", "sahs:sco", "sahs:page", + 'sess', "iass" + ))); + } + + protected function hasAdvancedMDSettings() + { + if ($this->sub_id) { + return false; + } + + include_once 'Services/Container/classes/class.ilContainer.php'; + include_once 'Services/Object/classes/class.ilObjectServiceSettingsGUI.php'; + + return ilContainer::_lookupContainerSetting( + $this->obj_id, + ilObjectServiceSettingsGUI::CUSTOM_METADATA, + false + ); + } + + /** + * check if active records exist in current path anf for object type + * @return type + */ + protected function hasActiveRecords() + { + include_once 'Services/AdvancedMetaData/classes/class.ilAdvancedMDRecord.php'; + + list($adv_ref_id, $adv_type, $adv_subtype) = $this->getAdvMdRecordObject(); + + return + (bool) sizeof(ilAdvancedMDRecord::_getSelectedRecordsByObject( + $adv_type, + $adv_ref_id, + $adv_subtype + )); + } + + protected function canEdit() + { + // if($this->hasActiveRecords() && + // $this->obj_id) + // { + if ($this->hasActiveRecords()) { + if ($this->sub_type == "-" || + $this->sub_id) { + return true; + } + } + return false; + } + + /** + * Get tab link if available + * + * @param null $a_base_class + * @return null|string + */ + public function getTab($a_base_class = null) + { + $ilCtrl = $this->ctrl; + + if (!$a_base_class) { + $path = array(); + } else { + $path = array($a_base_class); + } + $path[] = "ilobjectmetadatagui"; + + $link = null; + if ($this->isLOMAvailable()) { + $path[] = "ilmdeditorgui"; + $link = $ilCtrl->getLinkTargetByClass($path, "listSection"); + } elseif ($this->isAdvMDAvailable()) { + if ($this->canEdit()) { + $link = $ilCtrl->getLinkTarget($this, "edit"); + } elseif ($this->hasAdvancedMDSettings()) { + $path[] = "iladvancedmdsettingsgui"; + $link = $ilCtrl->getLinkTargetByClass($path, "showRecords"); + } + } + if ($link == null && is_object($this->tax_obj_gui)) { // taxonomy definition available? + $path[] = "ilobjtaxonomygui"; + $link = $ilCtrl->getLinkTargetByClass($path, ""); + } + return $link; + } + + public function setSubTabs($a_active) + { + $ilTabs = $this->tabs; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if ($this->isLOMAvailable()) { + $ilTabs->addSubTab( + "lom", + $lng->txt("meta_tab_lom"), + $ilCtrl->getLinkTargetByClass("ilmdeditorgui", "listSection") + ); + } + if ($this->isAdvMDAvailable()) { + if ($this->canEdit()) { + $ilTabs->addSubTab( + "advmd", + $lng->txt("meta_tab_advmd"), + $ilCtrl->getLinkTarget($this, "edit") + ); + } + if ($this->hasAdvancedMDSettings()) { + $ilTabs->addSubTab( + "advmddef", + $lng->txt("meta_tab_advmd_def"), + $ilCtrl->getLinkTargetByClass("iladvancedmdsettingsgui", "showRecords") + ); + + $ilTabs->addSubTab( + "md_adv_file_list", + $lng->txt("md_adv_file_list"), + $ilCtrl->getLinkTargetByClass("iladvancedmdsettingsgui", "showFiles") + ); + } + } + + if ($this->tax_md_gui != null) { + $this->tax_md_gui->addSubTab(); + } + + if ($this->tax_obj_gui != null) { + $ilTabs->addSubTab( + "tax_definition", + $lng->txt("cntr_taxonomy_definitions"), + $ilCtrl->getLinkTargetByClass("ilobjtaxonomygui", "") + ); + } + + if ($this->taxonomy_settings_form_manipulator != null) { + $ilTabs->addSubTab( + "tax_settings", + $lng->txt("tax_tax_settings"), + $ilCtrl->getLinkTarget($this, "editTaxonomySettings") + ); + } + + $ilTabs->activateSubTab($a_active); + } + + + // + // (VALUES) EDITOR + // + + protected function initEditForm() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this, "update")); + $form->setTitle($lng->txt("meta_tab_advmd")); + + include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecordGUI.php'); + $this->record_gui = new ilAdvancedMDRecordGUI( + ilAdvancedMDRecordGUI::MODE_EDITOR, + $this->obj_type, + $this->obj_id, + $this->sub_type, + $this->sub_id + ); + + if ($this->adv_type != "") { + $this->record_gui->setAdvMdRecordObject($this->adv_ref_id, $this->adv_type, $this->adv_subtype); + } + + $this->record_gui->setPropertyForm($form); + $this->record_gui->parse(); + + $form->addCommandButton("update", $lng->txt("save")); + + return $form; + } + + protected function edit(ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + + if (!$a_form) { + $a_form = $this->initEditForm(); + } + + $tpl->setContent($a_form->getHTML()); + } + + protected function update() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $form = $this->initEditForm(); + if ( + $form->checkInput() && + $this->record_gui->importEditFormPostValues()) { + $this->record_gui->writeEditForm(); + + // Update ECS content + if ($this->obj_type == "crs") { + include_once "Modules/Course/classes/class.ilECSCourseSettings.php"; + $ecs = new ilECSCourseSettings($this->object); + $ecs->handleContentUpdate(); + } + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "edit"); + } + + $form->setValuesByPost(); + $this->edit($form); + } + + + // + // BLOCK + // + + public function getBlockHTML(array $a_cmds = null, $a_callback = null) + { + $lng = $this->lng; + + $html = ""; + + include_once "Services/Object/classes/class.ilObjectMetaDataBlockGUI.php"; + include_once "Services/AdvancedMetaData/classes/class.ilAdvancedMDRecord.php"; + include_once "Services/AdvancedMetaData/classes/class.ilAdvancedMDValues.php"; + list($adv_ref_id, $adv_type, $adv_subtype) = $this->getAdvMdRecordObject(); + foreach (ilAdvancedMDRecord::_getSelectedRecordsByObject($adv_type, $adv_ref_id, $adv_subtype) as $record) { + $block = new ilObjectMetaDataBlockGUI($record, $a_callback); + $block->setValues(new ilAdvancedMDValues($record->getRecordId(), $this->obj_id, $this->sub_type, $this->sub_id)); + if ($a_cmds) { + foreach ($a_cmds as $caption => $url) { + $block->addBlockCommand($url, $lng->txt($caption), "_top"); + } + } + $html.= $block->getHTML(); + } + + return $html; + } + + + // + // Key/value list + // + + + public function getKeyValueList() + { + $html = ""; + $sep = ""; + + $old_dt = ilDatePresentation::useRelativeDates(); + ilDatePresentation::setUseRelativeDates(false); + + include_once "Services/AdvancedMetaData/classes/class.ilAdvancedMDRecord.php"; + include_once "Services/AdvancedMetaData/classes/class.ilAdvancedMDValues.php"; + list($adv_ref_id, $adv_type, $adv_subtype) = $this->getAdvMdRecordObject(); + foreach (ilAdvancedMDRecord::_getSelectedRecordsByObject($adv_type, $adv_ref_id, $adv_subtype) as $record) { + $vals = new ilAdvancedMDValues($record->getRecordId(), $this->obj_id, $this->sub_type, $this->sub_id); + + + include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDValues.php'); + include_once('Services/ADT/classes/class.ilADTFactory.php'); + + // this correctly binds group and definitions + $vals->read(); + + $defs = $vals->getDefinitions(); + foreach ($vals->getADTGroup()->getElements() as $element_id => $element) { + if ($element instanceof ilADTLocation) { + continue; + } + + $html.= $sep . $defs[$element_id]->getTitle() . ": "; + + if ($element->isNull()) { + $value = "-"; + } else { + $value = ilADTFactory::getInstance()->getPresentationBridgeForInstance($element); + + $value = $value->getHTML(); + } + $html.= $value; + $sep = ",    "; + } + } + + ilDatePresentation::setUseRelativeDates($old_dt); + + return $html; + } + + protected function editTaxonomySettings() + { + $this->tabs->activateSubTab("tax_settings"); + + $form = $this->initTaxonomySettingsForm(); + $this->tpl->setContent($form->getHTML()); + } + + /** + * Init taxonomy settings form. + */ + protected function initTaxonomySettingsForm() + { + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this), "saveTaxonomySettings"); + $form->setTitle($this->lng->txt("tax_tax_settings")); + $this->taxonomy_settings_form_manipulator->bindTo($this); + call_user_func_array($this->taxonomy_settings_form_manipulator, [$form]); + $form->addCommandButton("saveTaxonomySettings", $this->lng->txt("save")); + + return $form; + } + + /** + * Save taxonomy settings form + */ + protected function saveTaxonomySettings() + { + $form = $this->initTaxonomySettingsForm(); + if ($form->checkInput()) { + $this->taxonomy_settings_form_saver->bindTo($this); + call_user_func_array($this->taxonomy_settings_form_saver, [$form]); + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "editTaxonomySettings"); + } else { + $form->setValuesByPost(); + $this->tpl->setContent($form->getHtml()); + } + } } - -?> \ No newline at end of file diff --git a/Services/Object/classes/class.ilObjectOwnershipManagementGUI.php b/Services/Object/classes/class.ilObjectOwnershipManagementGUI.php index 08e2b1a6d860ddcae575a599a736a6892bcf3b39..da23e47476a190ffdde44010f293ba990d6ca86a 100644 --- a/Services/Object/classes/class.ilObjectOwnershipManagementGUI.php +++ b/Services/Object/classes/class.ilObjectOwnershipManagementGUI.php @@ -11,248 +11,229 @@ require_once('./Services/Repository/classes/class.ilObjectPlugin.php'); * * @ilCtrl_Calls ilObjectOwnershipManagementGUI: */ -class ilObjectOwnershipManagementGUI +class ilObjectOwnershipManagementGUI { - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilObjectDefinition - */ - protected $obj_definition; - - /** - * @var ilTree - */ - protected $tree; - - protected $user_id; // [int] - - function __construct($a_user_id = null) - { - global $DIC; - - $this->user = $DIC->user(); - $this->ctrl = $DIC->ctrl(); - $this->tpl = $DIC["tpl"]; - $this->toolbar = $DIC->toolbar(); - $this->lng = $DIC->language(); - $this->obj_definition = $DIC["objDefinition"]; - $this->tree = $DIC->repositoryTree(); - $ilUser = $DIC->user(); - - if($a_user_id === null) - { - $a_user_id = $ilUser->getId(); - } - $this->user_id = (int)$a_user_id; - } - - function executeCommand() - { - $ilCtrl = $this->ctrl; - - $next_class =$ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd(); - - switch($next_class) - { - default: - if(!$cmd) - { - $cmd = "listObjects"; - } - $this->$cmd(); - break; - } - - return true; - } - - function listObjects() - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $objDefinition = $this->obj_definition; - - $sel_type = ''; - - $objects = ilObject::getAllOwnedRepositoryObjects($this->user_id); - - if(sizeof($objects)) - { - $ilToolbar->setFormAction($ilCtrl->getFormAction($this, "listObjects")); - - include_once "Services/Form/classes/class.ilSelectInputGUI.php"; - $sel = new ilSelectInputGUI($lng->txt("type"), "type"); - $ilToolbar->addStickyItem($sel, true); - - include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; - $button = ilSubmitButton::getInstance(); - $button->setCaption("ok"); - $button->setCommand("listObjects"); - $ilToolbar->addStickyItem($button); - - $options = array(); - foreach(array_keys($objects) as $type) - { - // #11050 - if(!$objDefinition->isPlugin($type)) - { - $options[$type] = $lng->txt("obj_".$type); - } - else - { - include_once("./Services/Component/classes/class.ilPlugin.php"); - $options[$type] = ilObjectPlugin::lookupTxtById($type, "obj_".$type); - } - } - asort($options); - $sel->setOptions($options); - - $sel_type = (string)$_REQUEST["type"]; - if($sel_type) - { - $sel->setValue($sel_type); - } - else - { - $sel_type = array_keys($options); - $sel_type = array_shift($sel_type); - } - $ilCtrl->setParameter($this, "type", $sel_type); - } - - // #17751 - if(is_array($objects[$sel_type]) && sizeof($objects[$sel_type])) - { - ilObject::fixMissingTitles($sel_type, $objects[$sel_type]); - } - - include_once "Services/Object/classes/class.ilObjectOwnershipManagementTableGUI.php"; - $tbl = new ilObjectOwnershipManagementTableGUI($this, "listObjects", $this->user_id, $objects[$sel_type]); - $tpl->setContent($tbl->getHTML()); - } - - function applyFilter() - { - include_once "Services/Object/classes/class.ilObjectOwnershipManagementTableGUI.php"; - $tbl = new ilObjectOwnershipManagementTableGUI($this, "listObjects", $this->user_id); - $tbl->resetOffset(); - $tbl->writeFilterToSession(); - $this->listObjects(); - } - - function resetFilter() - { - include_once "Services/Object/classes/class.ilObjectOwnershipManagementTableGUI.php"; - $tbl = new ilObjectOwnershipManagementTableGUI($this, "listObjects", $this->user_id); - $tbl->resetOffset(); - $tbl->resetFilter(); - $this->listObjects(); - } - - protected function redirectParentCmd($a_ref_id, $a_cmd) - { - $tree = $this->tree; - $ilCtrl = $this->ctrl; - - $parent = $tree->getParentId($a_ref_id); - $ilCtrl->setParameterByClass("ilRepositoryGUI", "ref_id", $parent); - $ilCtrl->setParameterByClass("ilRepositoryGUI", "item_ref_id", $a_ref_id); - $ilCtrl->setParameterByClass("ilRepositoryGUI", "cmd", $a_cmd); - $ilCtrl->redirectByClass("ilRepositoryGUI"); - } - - protected function redirectCmd($a_ref_id, $a_class, $a_cmd = null) - { - $ilCtrl = $this->ctrl; - $tree = $this->tree; - $objDefinition = $this->obj_definition; - - $node = $tree->getNodeData($a_ref_id); - $gui_class = "ilObj".$objDefinition->getClassName($node["type"])."GUI"; - $path = array("ilRepositoryGUI", $gui_class, $a_class); - - // #10495 - check if object type supports ilexportgui "directly" - if($a_class == "ilExportGUI") - { - try - { - $ilCtrl->getLinkTargetByClass($path); - } - catch(Exception $e) - { - switch($node["type"]) - { - case "glo": - $cmd = "exportList"; - $path = array("ilRepositoryGUI", "ilGlossaryEditorGUI", $gui_class); - break; - - default: - $cmd = "export"; - $path = array("ilRepositoryGUI", $gui_class); - break; - } - $ilCtrl->setParameterByClass($gui_class, "ref_id", $a_ref_id); - $ilCtrl->setParameterByClass($gui_class, "cmd", $cmd); - $ilCtrl->redirectByClass($path); - } - } - - $ilCtrl->setParameterByClass($a_class, "ref_id", $a_ref_id); - $ilCtrl->setParameterByClass($a_class, "cmd", $a_cmd); - $ilCtrl->redirectByClass($path); - } - - function delete() - { - $ref_id = (int)$_REQUEST["ownid"]; - $this->redirectParentCmd($ref_id, "delete"); - } - - function move() - { - $ref_id = (int)$_REQUEST["ownid"]; - $this->redirectParentCmd($ref_id, "cut"); - } - - function export() - { - $ref_id = (int)$_REQUEST["ownid"]; - $this->redirectCmd($ref_id, "ilExportGUI"); - } - - function changeOwner() - { - $ref_id = (int)$_REQUEST["ownid"]; - $this->redirectCmd($ref_id, "ilPermissionGUI", "owner"); - } + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilObjectDefinition + */ + protected $obj_definition; + + /** + * @var ilTree + */ + protected $tree; + + protected $user_id; // [int] + + public function __construct($a_user_id = null) + { + global $DIC; + + $this->user = $DIC->user(); + $this->ctrl = $DIC->ctrl(); + $this->tpl = $DIC["tpl"]; + $this->toolbar = $DIC->toolbar(); + $this->lng = $DIC->language(); + $this->obj_definition = $DIC["objDefinition"]; + $this->tree = $DIC->repositoryTree(); + $ilUser = $DIC->user(); + + if ($a_user_id === null) { + $a_user_id = $ilUser->getId(); + } + $this->user_id = (int) $a_user_id; + } + + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $next_class =$ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd(); + + switch ($next_class) { + default: + if (!$cmd) { + $cmd = "listObjects"; + } + $this->$cmd(); + break; + } + + return true; + } + + public function listObjects() + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $objDefinition = $this->obj_definition; + + $sel_type = ''; + + $objects = ilObject::getAllOwnedRepositoryObjects($this->user_id); + + if (sizeof($objects)) { + $ilToolbar->setFormAction($ilCtrl->getFormAction($this, "listObjects")); + + include_once "Services/Form/classes/class.ilSelectInputGUI.php"; + $sel = new ilSelectInputGUI($lng->txt("type"), "type"); + $ilToolbar->addStickyItem($sel, true); + + include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; + $button = ilSubmitButton::getInstance(); + $button->setCaption("ok"); + $button->setCommand("listObjects"); + $ilToolbar->addStickyItem($button); + + $options = array(); + foreach (array_keys($objects) as $type) { + // #11050 + if (!$objDefinition->isPlugin($type)) { + $options[$type] = $lng->txt("obj_" . $type); + } else { + include_once("./Services/Component/classes/class.ilPlugin.php"); + $options[$type] = ilObjectPlugin::lookupTxtById($type, "obj_" . $type); + } + } + asort($options); + $sel->setOptions($options); + + $sel_type = (string) $_REQUEST["type"]; + if ($sel_type) { + $sel->setValue($sel_type); + } else { + $sel_type = array_keys($options); + $sel_type = array_shift($sel_type); + } + $ilCtrl->setParameter($this, "type", $sel_type); + } + + // #17751 + if (is_array($objects[$sel_type]) && sizeof($objects[$sel_type])) { + ilObject::fixMissingTitles($sel_type, $objects[$sel_type]); + } + + include_once "Services/Object/classes/class.ilObjectOwnershipManagementTableGUI.php"; + $tbl = new ilObjectOwnershipManagementTableGUI($this, "listObjects", $this->user_id, $objects[$sel_type]); + $tpl->setContent($tbl->getHTML()); + } + + public function applyFilter() + { + include_once "Services/Object/classes/class.ilObjectOwnershipManagementTableGUI.php"; + $tbl = new ilObjectOwnershipManagementTableGUI($this, "listObjects", $this->user_id); + $tbl->resetOffset(); + $tbl->writeFilterToSession(); + $this->listObjects(); + } + + public function resetFilter() + { + include_once "Services/Object/classes/class.ilObjectOwnershipManagementTableGUI.php"; + $tbl = new ilObjectOwnershipManagementTableGUI($this, "listObjects", $this->user_id); + $tbl->resetOffset(); + $tbl->resetFilter(); + $this->listObjects(); + } + + protected function redirectParentCmd($a_ref_id, $a_cmd) + { + $tree = $this->tree; + $ilCtrl = $this->ctrl; + + $parent = $tree->getParentId($a_ref_id); + $ilCtrl->setParameterByClass("ilRepositoryGUI", "ref_id", $parent); + $ilCtrl->setParameterByClass("ilRepositoryGUI", "item_ref_id", $a_ref_id); + $ilCtrl->setParameterByClass("ilRepositoryGUI", "cmd", $a_cmd); + $ilCtrl->redirectByClass("ilRepositoryGUI"); + } + + protected function redirectCmd($a_ref_id, $a_class, $a_cmd = null) + { + $ilCtrl = $this->ctrl; + $tree = $this->tree; + $objDefinition = $this->obj_definition; + + $node = $tree->getNodeData($a_ref_id); + $gui_class = "ilObj" . $objDefinition->getClassName($node["type"]) . "GUI"; + $path = array("ilRepositoryGUI", $gui_class, $a_class); + + // #10495 - check if object type supports ilexportgui "directly" + if ($a_class == "ilExportGUI") { + try { + $ilCtrl->getLinkTargetByClass($path); + } catch (Exception $e) { + switch ($node["type"]) { + case "glo": + $cmd = "exportList"; + $path = array("ilRepositoryGUI", "ilGlossaryEditorGUI", $gui_class); + break; + + default: + $cmd = "export"; + $path = array("ilRepositoryGUI", $gui_class); + break; + } + $ilCtrl->setParameterByClass($gui_class, "ref_id", $a_ref_id); + $ilCtrl->setParameterByClass($gui_class, "cmd", $cmd); + $ilCtrl->redirectByClass($path); + } + } + + $ilCtrl->setParameterByClass($a_class, "ref_id", $a_ref_id); + $ilCtrl->setParameterByClass($a_class, "cmd", $a_cmd); + $ilCtrl->redirectByClass($path); + } + + public function delete() + { + $ref_id = (int) $_REQUEST["ownid"]; + $this->redirectParentCmd($ref_id, "delete"); + } + + public function move() + { + $ref_id = (int) $_REQUEST["ownid"]; + $this->redirectParentCmd($ref_id, "cut"); + } + + public function export() + { + $ref_id = (int) $_REQUEST["ownid"]; + $this->redirectCmd($ref_id, "ilExportGUI"); + } + + public function changeOwner() + { + $ref_id = (int) $_REQUEST["ownid"]; + $this->redirectCmd($ref_id, "ilPermissionGUI", "owner"); + } } - -?> \ No newline at end of file diff --git a/Services/Object/classes/class.ilObjectOwnershipManagementTableGUI.php b/Services/Object/classes/class.ilObjectOwnershipManagementTableGUI.php index ded79cf31e2a9310fec75304a781eb3d04ff3b73..dc9448c5530fcb95772b24d782f3ae41102df75f 100644 --- a/Services/Object/classes/class.ilObjectOwnershipManagementTableGUI.php +++ b/Services/Object/classes/class.ilObjectOwnershipManagementTableGUI.php @@ -1,7 +1,7 @@ ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $this->tree = $DIC->repositoryTree(); - $this->obj_definition = $DIC["objDefinition"]; - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->user_id = (int)$a_user_id; - $this->setId('objownmgmt'); // #16373 - - parent::__construct($a_parent_obj,$a_parent_cmd); - - $this->addColumn($lng->txt("title"), "title"); - $this->addColumn($lng->txt("path"), "path"); - $this->addColumn($lng->txt("action"), ""); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->tree = $DIC->repositoryTree(); + $this->obj_definition = $DIC["objDefinition"]; + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->user_id = (int) $a_user_id; + $this->setId('objownmgmt'); // #16373 + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->addColumn($lng->txt("title"), "title"); + $this->addColumn($lng->txt("path"), "path"); + $this->addColumn($lng->txt("action"), ""); - // $this->setTitle($this->lng->txt('')); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd)); - $this->setRowTemplate("tpl.obj_ownership_row.html", "Services/Object"); - $this->setDisableFilterHiding(true); - - $this->setDefaultOrderField("title"); - $this->setDefaultOrderDirection("asc"); - - $this->initItems($a_data); - } - - protected function initItems($a_data) - { - $ilAccess = $this->access; - $tree = $this->tree; - - $data = array(); - - if(is_array($a_data) && sizeof($a_data)) - { - if(!$this->user_id) - { - $is_admin = $ilAccess->checkAccess("visible", "", SYSTEM_FOLDER_ID); - } + // $this->setTitle($this->lng->txt('')); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd)); + $this->setRowTemplate("tpl.obj_ownership_row.html", "Services/Object"); + $this->setDisableFilterHiding(true); + + $this->setDefaultOrderField("title"); + $this->setDefaultOrderDirection("asc"); + + $this->initItems($a_data); + } + + protected function initItems($a_data) + { + $ilAccess = $this->access; + $tree = $this->tree; + + $data = array(); + + if (is_array($a_data) && sizeof($a_data)) { + if (!$this->user_id) { + $is_admin = $ilAccess->checkAccess("visible", "", SYSTEM_FOLDER_ID); + } - foreach($a_data as $id => $item) - { - // workspace objects won't have references - $refs = ilObject::_getAllReferences($id); - if($refs) - { - foreach($refs as $idx => $ref_id) - { - // objects in trash are hidden - if(!$tree->isDeleted($ref_id)) - { - if($this->user_id) - { - $readable = $ilAccess->checkAccessOfUser($this->user_id, "read", "", $ref_id, $a_type); - } - else - { - $readable = $is_admin; - } + foreach ($a_data as $id => $item) { + // workspace objects won't have references + $refs = ilObject::_getAllReferences($id); + if ($refs) { + foreach ($refs as $idx => $ref_id) { + // objects in trash are hidden + if (!$tree->isDeleted($ref_id)) { + if ($this->user_id) { + $readable = $ilAccess->checkAccessOfUser($this->user_id, "read", "", $ref_id, $a_type); + } else { + $readable = $is_admin; + } - $data[$ref_id] = array("obj_id" => $id, - "ref_id" => $ref_id, - "type" => ilObject::_lookupType($id), - "title" => $item, - "path" => $this->buildPath($ref_id), - "readable" => $readable); - } - } - } - } - } + $data[$ref_id] = array("obj_id" => $id, + "ref_id" => $ref_id, + "type" => ilObject::_lookupType($id), + "title" => $item, + "path" => $this->buildPath($ref_id), + "readable" => $readable); + } + } + } + } + } - $this->setData($data); - } - - public function fillRow($row) - { - $lng = $this->lng; - $objDefinition = $this->obj_definition; - - // #11050 - if(!$objDefinition->isPlugin($row["type"])) - { - $txt_type = $lng->txt("obj_".$row["type"]); - } - else - { - include_once("./Services/Component/classes/class.ilPlugin.php"); - $txt_type = ilObjectPlugin::lookupTxtById($row["type"], "obj_".$row["type"]); - } - - $this->tpl->setVariable("TITLE", $row["title"]); - $this->tpl->setVariable("ALT_ICON", $txt_type); - $this->tpl->setVariable("SRC_ICON", ilObject::_getIcon("", "tiny", $row["type"])); - $this->tpl->setVariable("PATH", $row["path"]); - - if($row["readable"]) - { - $this->tpl->setCurrentBlock("actions"); - $this->tpl->setVariable("ACTIONS", $this->buildActions($row["ref_id"], $row["type"])); - $this->tpl->parseCurrentBlock(); - } - } - - protected function buildActions($a_ref_id, $a_type) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $objDefinition = $this->obj_definition; - - include_once "Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"; - $agui = new ilAdvancedSelectionListGUI(); - $agui->setId($this->id."-".$a_ref_id); - $agui->setListTitle($lng->txt("actions")); - - $ilCtrl->setParameter($this->parent_obj, "ownid", $a_ref_id); - - include_once "Services/Link/classes/class.ilLink.php"; - $agui->addItem($lng->txt("show"), "", - ilLink::_getLink($a_ref_id, $a_type), - "", "", "_blank"); - - $agui->addItem($lng->txt("move"), "", - $ilCtrl->getLinkTarget($this->parent_obj, "move"), - "", "", ""); - - $agui->addItem($lng->txt("change_owner"), "", - $ilCtrl->getLinkTarget($this->parent_obj, "changeOwner"), - "", "", ""); - - if(!in_array($a_type, array("crsr", "catr", "grpr")) && $objDefinition->allowExport($a_type)) - { - $agui->addItem($lng->txt("export"), "", - $ilCtrl->getLinkTarget($this->parent_obj, "export"), - "", "", ""); - } - - $agui->addItem($lng->txt("delete"), "", - $ilCtrl->getLinkTarget($this->parent_obj, "delete"), - "", "", ""); - - $ilCtrl->setParameter($this->parent_obj, "ownid", ""); - - return $agui->getHTML(); - } - - protected function buildPath($a_ref_id) - { - $tree = $this->tree; + $this->setData($data); + } + + public function fillRow($row) + { + $lng = $this->lng; + $objDefinition = $this->obj_definition; + + // #11050 + if (!$objDefinition->isPlugin($row["type"])) { + $txt_type = $lng->txt("obj_" . $row["type"]); + } else { + include_once("./Services/Component/classes/class.ilPlugin.php"); + $txt_type = ilObjectPlugin::lookupTxtById($row["type"], "obj_" . $row["type"]); + } + + $this->tpl->setVariable("TITLE", $row["title"]); + $this->tpl->setVariable("ALT_ICON", $txt_type); + $this->tpl->setVariable("SRC_ICON", ilObject::_getIcon("", "tiny", $row["type"])); + $this->tpl->setVariable("PATH", $row["path"]); + + if ($row["readable"]) { + $this->tpl->setCurrentBlock("actions"); + $this->tpl->setVariable("ACTIONS", $this->buildActions($row["ref_id"], $row["type"])); + $this->tpl->parseCurrentBlock(); + } + } + + protected function buildActions($a_ref_id, $a_type) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $objDefinition = $this->obj_definition; + + include_once "Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php"; + $agui = new ilAdvancedSelectionListGUI(); + $agui->setId($this->id . "-" . $a_ref_id); + $agui->setListTitle($lng->txt("actions")); + + $ilCtrl->setParameter($this->parent_obj, "ownid", $a_ref_id); + + include_once "Services/Link/classes/class.ilLink.php"; + $agui->addItem( + $lng->txt("show"), + "", + ilLink::_getLink($a_ref_id, $a_type), + "", + "", + "_blank" + ); + + $agui->addItem( + $lng->txt("move"), + "", + $ilCtrl->getLinkTarget($this->parent_obj, "move"), + "", + "", + "" + ); + + $agui->addItem( + $lng->txt("change_owner"), + "", + $ilCtrl->getLinkTarget($this->parent_obj, "changeOwner"), + "", + "", + "" + ); + + if (!in_array($a_type, array("crsr", "catr", "grpr")) && $objDefinition->allowExport($a_type)) { + $agui->addItem( + $lng->txt("export"), + "", + $ilCtrl->getLinkTarget($this->parent_obj, "export"), + "", + "", + "" + ); + } + + $agui->addItem( + $lng->txt("delete"), + "", + $ilCtrl->getLinkTarget($this->parent_obj, "delete"), + "", + "", + "" + ); + + $ilCtrl->setParameter($this->parent_obj, "ownid", ""); + + return $agui->getHTML(); + } + + protected function buildPath($a_ref_id) + { + $tree = $this->tree; - $path = "..."; - $counter = 0; - $path_full = $tree->getPathFull($a_ref_id); - foreach($path_full as $data) - { - if(++$counter < (count($path_full)-2)) - { - continue; - } - if($a_ref_id != $data['ref_id']) - { - $path .= " » ".$data['title']; - } - } - - return $path; - } + $path = "..."; + $counter = 0; + $path_full = $tree->getPathFull($a_ref_id); + foreach ($path_full as $data) { + if (++$counter < (count($path_full)-2)) { + continue; + } + if ($a_ref_id != $data['ref_id']) { + $path .= " » " . $data['title']; + } + } + + return $path; + } } - -?> \ No newline at end of file diff --git a/Services/Object/classes/class.ilObjectServiceSettingsGUI.php b/Services/Object/classes/class.ilObjectServiceSettingsGUI.php index b3fe98906288c53f5235b97f65f659b1e7d46eb8..40e60909b69e9fd4b68956b53fca957c4277bcf1 100644 --- a/Services/Object/classes/class.ilObjectServiceSettingsGUI.php +++ b/Services/Object/classes/class.ilObjectServiceSettingsGUI.php @@ -7,485 +7,444 @@ * * @author Stefan Meyer * @version $Id$ - * - * @ilCtrl_Calls ilObjectServiceSettingsGUI: + * + * @ilCtrl_Calls ilObjectServiceSettingsGUI: * @ingroup ServicesObject */ -class ilObjectServiceSettingsGUI +class ilObjectServiceSettingsGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - // unfortunately the following constants are not stored - // in a non-GUI class, other classes are currently directly - // accessing these, see ilObjectDataSet (changes should be - // made there accordingly) + /** + * @var ilCtrl + */ + protected $ctrl; - const CALENDAR_VISIBILITY = 'cont_show_calendar'; - const NEWS_VISIBILITY = 'cont_show_news'; - const USE_NEWS = 'cont_use_news'; - const AUTO_RATING_NEW_OBJECTS = 'cont_auto_rate_new_obj'; - const INFO_TAB_VISIBILITY = 'cont_show_info_tab'; - const TAXONOMIES = 'cont_taxonomies'; - const TAG_CLOUD = 'cont_tag_cloud'; - const CUSTOM_METADATA = 'cont_custom_md'; - const BADGES = 'cont_badges'; - const ORGU_POSITION_ACCESS = 'obj_orgunit_positions'; - const SKILLS = 'cont_skills'; - - private $gui = null; - private $modes = array(); - private $obj_id = 0; - - /** - * Constructor - * @param type $a_parent_gui - */ - public function __construct($a_parent_gui, $a_obj_id, $a_modes) - { - global $DIC; + // unfortunately the following constants are not stored + // in a non-GUI class, other classes are currently directly + // accessing these, see ilObjectDataSet (changes should be + // made there accordingly) - $this->ctrl = $DIC->ctrl(); - $this->gui = $a_parent_gui; - $this->modes = $a_modes; - $this->obj_id = $a_obj_id; - } - - - - /** - * Control class handling - * @return - */ - public function executeCommand() - { - $ilCtrl = $this->ctrl; - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd('editSettings'); - - switch($next_class) - { - default: - $this->$cmd(); - break; - } - } - - /** - * Init service settings form - * @param ilPropertyFormGUI $form - * @param type $services - */ - public static function initServiceSettingsForm($a_obj_id, ilPropertyFormGUI $form, $services) - { - global $DIC; + const CALENDAR_VISIBILITY = 'cont_show_calendar'; + const NEWS_VISIBILITY = 'cont_show_news'; + const USE_NEWS = 'cont_use_news'; + const AUTO_RATING_NEW_OBJECTS = 'cont_auto_rate_new_obj'; + const INFO_TAB_VISIBILITY = 'cont_show_info_tab'; + const TAXONOMIES = 'cont_taxonomies'; + const TAG_CLOUD = 'cont_tag_cloud'; + const CUSTOM_METADATA = 'cont_custom_md'; + const BADGES = 'cont_badges'; + const ORGU_POSITION_ACCESS = 'obj_orgunit_positions'; + const SKILLS = 'cont_skills'; + + private $gui = null; + private $modes = array(); + private $obj_id = 0; + + /** + * Constructor + * @param type $a_parent_gui + */ + public function __construct($a_parent_gui, $a_obj_id, $a_modes) + { + global $DIC; - $ilSetting = $DIC->settings(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - // info tab - if(in_array(self::INFO_TAB_VISIBILITY, $services)) - { - $info = new ilCheckboxInputGUI($lng->txt('obj_tool_setting_info_tab'), self::INFO_TAB_VISIBILITY); - $info->setValue(1); - $info->setChecked(ilContainer::_lookupContainerSetting( - $a_obj_id, - self::INFO_TAB_VISIBILITY, - true - )); - //$info->setOptionTitle($lng->txt('obj_tool_setting_info_tab')); - $info->setInfo($lng->txt('obj_tool_setting_info_tab_info')); - $form->addItem($info); - } - - // calendar - if(in_array(self::CALENDAR_VISIBILITY, $services)) - { - include_once './Services/Calendar/classes/class.ilObjCalendarSettings.php'; - if(ilCalendarSettings::_getInstance()->isEnabled()) - { - // Container tools (calendar, news, ... activation) - $cal = new ilCheckboxInputGUI($lng->txt('obj_tool_setting_calendar'), self::CALENDAR_VISIBILITY); - $cal->setValue(1); - include_once './Services/Calendar/classes/class.ilObjCalendarSettings.php'; - $cal->setChecked(ilCalendarSettings::lookupCalendarActivated($a_obj_id)); - //$cal->setOptionTitle($lng->txt('obj_tool_setting_calendar')); - $cal->setInfo($lng->txt('obj_tool_setting_calendar_info')); - $form->addItem($cal); - } - } - - // news - if(in_array(self::USE_NEWS, $services)) - { - $news = new ilCheckboxInputGUI($lng->txt('obj_tool_setting_use_news'), self::USE_NEWS); - $news->setValue(1); - $checked = ilContainer::_lookupContainerSetting( - $a_obj_id, - self::USE_NEWS, - true - ); - $news->setChecked($checked); - $info = $lng->txt('obj_tool_setting_use_news_info'); - if ($checked) - { - $info.=" » ".$lng->txt('obj_tool_setting_use_news_open_settings').""; - } - $news->setInfo($info); - $form->addItem($news); + $this->ctrl = $DIC->ctrl(); + $this->gui = $a_parent_gui; + $this->modes = $a_modes; + $this->obj_id = $a_obj_id; + } + + + + /** + * Control class handling + * @return + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd('editSettings'); + + switch ($next_class) { + default: + $this->$cmd(); + break; + } + } + + /** + * Init service settings form + * @param ilPropertyFormGUI $form + * @param type $services + */ + public static function initServiceSettingsForm($a_obj_id, ilPropertyFormGUI $form, $services) + { + global $DIC; - } - if(in_array(self::NEWS_VISIBILITY, $services)) - { - if($ilSetting->get('block_activated_news')) - { - // Container tools (calendar, news, ... activation) - $news = new ilCheckboxInputGUI($lng->txt('obj_tool_setting_news'), self::NEWS_VISIBILITY); - $news->setValue(1); - $news->setChecked(ilContainer::_lookupContainerSetting( - $a_obj_id, - self::NEWS_VISIBILITY, - $ilSetting->get('block_activated_news',true) - )); - //$news->setOptionTitle($lng->txt('obj_tool_setting_news')); - $news->setInfo($lng->txt('obj_tool_setting_news_info')); - $form->addItem($news); - - if(in_array(ilObject::_lookupType($a_obj_id), array('crs', 'grp'))) - { - $ref_id = array_pop(ilObject::_getAllReferences($a_obj_id)); - - include_once 'Services/Membership/classes/class.ilMembershipNotifications.php'; - ilMembershipNotifications::addToSettingsForm($ref_id, null, $news); - } - } - } - - // (local) custom metadata - if(in_array(self::CUSTOM_METADATA, $services)) - { - $md = new ilCheckboxInputGUI($lng->txt('obj_tool_setting_custom_metadata'), self::CUSTOM_METADATA); - $md->setInfo($lng->txt('obj_tool_setting_custom_metadata_info')); - $md->setValue(1); - $md->setChecked(ilContainer::_lookupContainerSetting( - $a_obj_id, - self::CUSTOM_METADATA, - false - )); - $form->addItem($md); - } - - // tag cloud - if(in_array(self::TAG_CLOUD, $services)) - { - $tags_active = new ilSetting("tags"); - if($tags_active->get("enable", false)) - { - $tag = new ilCheckboxInputGUI($lng->txt('obj_tool_setting_tag_cloud'), self::TAG_CLOUD); - $tag->setInfo($lng->txt('obj_tool_setting_tag_cloud_info')); - $tag->setValue(1); - $tag->setChecked(ilContainer::_lookupContainerSetting( - $a_obj_id, - self::TAG_CLOUD, - false - )); - $form->addItem($tag); - } - } + $ilSetting = $DIC->settings(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + // info tab + if (in_array(self::INFO_TAB_VISIBILITY, $services)) { + $info = new ilCheckboxInputGUI($lng->txt('obj_tool_setting_info_tab'), self::INFO_TAB_VISIBILITY); + $info->setValue(1); + $info->setChecked(ilContainer::_lookupContainerSetting( + $a_obj_id, + self::INFO_TAB_VISIBILITY, + true + )); + //$info->setOptionTitle($lng->txt('obj_tool_setting_info_tab')); + $info->setInfo($lng->txt('obj_tool_setting_info_tab_info')); + $form->addItem($info); + } + + // calendar + if (in_array(self::CALENDAR_VISIBILITY, $services)) { + include_once './Services/Calendar/classes/class.ilObjCalendarSettings.php'; + if (ilCalendarSettings::_getInstance()->isEnabled()) { + // Container tools (calendar, news, ... activation) + $cal = new ilCheckboxInputGUI($lng->txt('obj_tool_setting_calendar'), self::CALENDAR_VISIBILITY); + $cal->setValue(1); + include_once './Services/Calendar/classes/class.ilObjCalendarSettings.php'; + $cal->setChecked(ilCalendarSettings::lookupCalendarActivated($a_obj_id)); + //$cal->setOptionTitle($lng->txt('obj_tool_setting_calendar')); + $cal->setInfo($lng->txt('obj_tool_setting_calendar_info')); + $form->addItem($cal); + } + } + + // news + if (in_array(self::USE_NEWS, $services)) { + $news = new ilCheckboxInputGUI($lng->txt('obj_tool_setting_use_news'), self::USE_NEWS); + $news->setValue(1); + $checked = ilContainer::_lookupContainerSetting( + $a_obj_id, + self::USE_NEWS, + true + ); + $news->setChecked($checked); + $info = $lng->txt('obj_tool_setting_use_news_info'); + if ($checked) { + $info.=" » " . $lng->txt('obj_tool_setting_use_news_open_settings') . ""; + } + $news->setInfo($info); + $form->addItem($news); + } + if (in_array(self::NEWS_VISIBILITY, $services)) { + if ($ilSetting->get('block_activated_news')) { + // Container tools (calendar, news, ... activation) + $news = new ilCheckboxInputGUI($lng->txt('obj_tool_setting_news'), self::NEWS_VISIBILITY); + $news->setValue(1); + $news->setChecked(ilContainer::_lookupContainerSetting( + $a_obj_id, + self::NEWS_VISIBILITY, + $ilSetting->get('block_activated_news', true) + )); + //$news->setOptionTitle($lng->txt('obj_tool_setting_news')); + $news->setInfo($lng->txt('obj_tool_setting_news_info')); + $form->addItem($news); + + if (in_array(ilObject::_lookupType($a_obj_id), array('crs', 'grp'))) { + $ref_id = array_pop(ilObject::_getAllReferences($a_obj_id)); + + include_once 'Services/Membership/classes/class.ilMembershipNotifications.php'; + ilMembershipNotifications::addToSettingsForm($ref_id, null, $news); + } + } + } + + // (local) custom metadata + if (in_array(self::CUSTOM_METADATA, $services)) { + $md = new ilCheckboxInputGUI($lng->txt('obj_tool_setting_custom_metadata'), self::CUSTOM_METADATA); + $md->setInfo($lng->txt('obj_tool_setting_custom_metadata_info')); + $md->setValue(1); + $md->setChecked(ilContainer::_lookupContainerSetting( + $a_obj_id, + self::CUSTOM_METADATA, + false + )); + $form->addItem($md); + } + + // tag cloud + if (in_array(self::TAG_CLOUD, $services)) { + $tags_active = new ilSetting("tags"); + if ($tags_active->get("enable", false)) { + $tag = new ilCheckboxInputGUI($lng->txt('obj_tool_setting_tag_cloud'), self::TAG_CLOUD); + $tag->setInfo($lng->txt('obj_tool_setting_tag_cloud_info')); + $tag->setValue(1); + $tag->setChecked(ilContainer::_lookupContainerSetting( + $a_obj_id, + self::TAG_CLOUD, + false + )); + $form->addItem($tag); + } + } - // taxonomies - if(in_array(self::TAXONOMIES, $services)) - { - $tax = new ilCheckboxInputGUI($lng->txt('obj_tool_setting_taxonomies'), self::TAXONOMIES); - $tax->setValue(1); - $tax->setChecked(ilContainer::_lookupContainerSetting( - $a_obj_id, - self::TAXONOMIES, - false - )); - $form->addItem($tax); - } - - // auto rating - if(in_array(self::AUTO_RATING_NEW_OBJECTS, $services)) - { - $lng->loadLanguageModule("rating"); - - // auto rating for new objects - $rate = new ilCheckboxInputGUI($lng->txt('rating_new_objects_auto'), self::AUTO_RATING_NEW_OBJECTS); - $rate->setValue(1); - //$rate->setOptionTitle($lng->txt('rating_new_objects_auto')); - $rate->setInfo($lng->txt('rating_new_objects_auto_info')); - $rate->setChecked(ilContainer::_lookupContainerSetting( - $a_obj_id, - self::AUTO_RATING_NEW_OBJECTS, - false - )); - $form->addItem($rate); - } - - // badges - if(in_array(self::BADGES, $services)) - { - include_once 'Services/Badge/classes/class.ilBadgeHandler.php'; - if(ilBadgeHandler::getInstance()->isActive()) - { - $bdg = new ilCheckboxInputGUI($lng->txt('obj_tool_setting_badges'), self::BADGES); - $bdg->setInfo($lng->txt('obj_tool_setting_badges_info')); - $bdg->setValue(1); - $bdg->setChecked(ilContainer::_lookupContainerSetting( - $a_obj_id, - self::BADGES, - false - )); - $form->addItem($bdg); - } - } - if(in_array(self::ORGU_POSITION_ACCESS, $services)) - { - $position_settings = ilOrgUnitGlobalSettings::getInstance()->getObjectPositionSettingsByType( - ilObject::_lookupType($a_obj_id) - ); - if( - $position_settings->isActive() - ) - { - $lia = new ilCheckboxInputGUI( - $GLOBALS['DIC']->language()->txt('obj_orgunit_positions'), - self::ORGU_POSITION_ACCESS - ); - $lia->setInfo($GLOBALS['DIC']->language()->txt('obj_orgunit_positions_info')); - $lia->setValue(1); - $lia->setChecked( - (bool) ilOrgUnitGlobalSettings::getInstance()->isPositionAccessActiveForObject($a_obj_id) - ); - if(!$position_settings->isChangeableForObject()) { - $lia->setDisabled(true); - } - $form->addItem($lia); - } - } + // taxonomies + if (in_array(self::TAXONOMIES, $services)) { + $tax = new ilCheckboxInputGUI($lng->txt('obj_tool_setting_taxonomies'), self::TAXONOMIES); + $tax->setValue(1); + $tax->setChecked(ilContainer::_lookupContainerSetting( + $a_obj_id, + self::TAXONOMIES, + false + )); + $form->addItem($tax); + } + + // auto rating + if (in_array(self::AUTO_RATING_NEW_OBJECTS, $services)) { + $lng->loadLanguageModule("rating"); + + // auto rating for new objects + $rate = new ilCheckboxInputGUI($lng->txt('rating_new_objects_auto'), self::AUTO_RATING_NEW_OBJECTS); + $rate->setValue(1); + //$rate->setOptionTitle($lng->txt('rating_new_objects_auto')); + $rate->setInfo($lng->txt('rating_new_objects_auto_info')); + $rate->setChecked(ilContainer::_lookupContainerSetting( + $a_obj_id, + self::AUTO_RATING_NEW_OBJECTS, + false + )); + $form->addItem($rate); + } + + // badges + if (in_array(self::BADGES, $services)) { + include_once 'Services/Badge/classes/class.ilBadgeHandler.php'; + if (ilBadgeHandler::getInstance()->isActive()) { + $bdg = new ilCheckboxInputGUI($lng->txt('obj_tool_setting_badges'), self::BADGES); + $bdg->setInfo($lng->txt('obj_tool_setting_badges_info')); + $bdg->setValue(1); + $bdg->setChecked(ilContainer::_lookupContainerSetting( + $a_obj_id, + self::BADGES, + false + )); + $form->addItem($bdg); + } + } + if (in_array(self::ORGU_POSITION_ACCESS, $services)) { + $position_settings = ilOrgUnitGlobalSettings::getInstance()->getObjectPositionSettingsByType( + ilObject::_lookupType($a_obj_id) + ); + if ( + $position_settings->isActive() + ) { + $lia = new ilCheckboxInputGUI( + $GLOBALS['DIC']->language()->txt('obj_orgunit_positions'), + self::ORGU_POSITION_ACCESS + ); + $lia->setInfo($GLOBALS['DIC']->language()->txt('obj_orgunit_positions_info')); + $lia->setValue(1); + $lia->setChecked( + (bool) ilOrgUnitGlobalSettings::getInstance()->isPositionAccessActiveForObject($a_obj_id) + ); + if (!$position_settings->isChangeableForObject()) { + $lia->setDisabled(true); + } + $form->addItem($lia); + } + } - // skills - if(in_array(self::SKILLS, $services)) - { - $skill = new ilCheckboxInputGUI($lng->txt('obj_tool_setting_skills'), self::SKILLS); - $skill->setInfo($lng->txt('obj_tool_setting_skills_info')); - $skill->setValue(1); - $skill->setChecked(ilContainer::_lookupContainerSetting( - $a_obj_id, - self::SKILLS, - false - )); - $form->addItem($skill); - } + // skills + if (in_array(self::SKILLS, $services)) { + $skill = new ilCheckboxInputGUI($lng->txt('obj_tool_setting_skills'), self::SKILLS); + $skill->setInfo($lng->txt('obj_tool_setting_skills_info')); + $skill->setValue(1); + $skill->setChecked(ilContainer::_lookupContainerSetting( + $a_obj_id, + self::SKILLS, + false + )); + $form->addItem($skill); + } - return $form; - } + return $form; + } - /** - * Update service settings - * - * @param int $a_obj_id - * @param ilPropertyFormGUI $form - * @param string[] $services - * - * @return bool - */ - public static function updateServiceSettingsForm($a_obj_id, ilPropertyFormGUI $form, $services) - { - // info - if(in_array(self::INFO_TAB_VISIBILITY, $services)) - { - include_once './Services/Container/classes/class.ilContainer.php'; - ilContainer::_writeContainerSetting($a_obj_id,self::INFO_TAB_VISIBILITY,(int) $form->getInput(self::INFO_TAB_VISIBILITY)); - } - - // calendar - if(in_array(self::CALENDAR_VISIBILITY, $services)) - { - include_once './Services/Calendar/classes/class.ilCalendarSettings.php'; - if(ilCalendarSettings::_getInstance()->isEnabled()) - { - include_once './Services/Container/classes/class.ilContainer.php'; - ilContainer::_writeContainerSetting($a_obj_id,self::CALENDAR_VISIBILITY,(int) $form->getInput(self::CALENDAR_VISIBILITY)); - } - } - - // news - if(in_array(self::USE_NEWS, $services)) - { - include_once './Services/Container/classes/class.ilContainer.php'; - ilContainer::_writeContainerSetting($a_obj_id,self::USE_NEWS,(int) $form->getInput(self::USE_NEWS)); - } - if(in_array(self::NEWS_VISIBILITY, $services)) - { - include_once './Services/Container/classes/class.ilContainer.php'; - ilContainer::_writeContainerSetting($a_obj_id,self::NEWS_VISIBILITY,(int) $form->getInput(self::NEWS_VISIBILITY)); - - if(in_array(ilObject::_lookupType($a_obj_id), array('crs', 'grp'))) - { - $ref_id = array_pop(ilObject::_getAllReferences($a_obj_id)); - - include_once "Services/Membership/classes/class.ilMembershipNotifications.php"; - ilMembershipNotifications::importFromForm($ref_id, $form); - } - } - - // rating - if(in_array(self::AUTO_RATING_NEW_OBJECTS, $services)) - { - include_once './Services/Container/classes/class.ilContainer.php'; - ilContainer::_writeContainerSetting($a_obj_id,self::AUTO_RATING_NEW_OBJECTS,(int) $form->getInput(self::AUTO_RATING_NEW_OBJECTS)); - } + /** + * Update service settings + * + * @param int $a_obj_id + * @param ilPropertyFormGUI $form + * @param string[] $services + * + * @return bool + */ + public static function updateServiceSettingsForm($a_obj_id, ilPropertyFormGUI $form, $services) + { + // info + if (in_array(self::INFO_TAB_VISIBILITY, $services)) { + include_once './Services/Container/classes/class.ilContainer.php'; + ilContainer::_writeContainerSetting($a_obj_id, self::INFO_TAB_VISIBILITY, (int) $form->getInput(self::INFO_TAB_VISIBILITY)); + } + + // calendar + if (in_array(self::CALENDAR_VISIBILITY, $services)) { + include_once './Services/Calendar/classes/class.ilCalendarSettings.php'; + if (ilCalendarSettings::_getInstance()->isEnabled()) { + include_once './Services/Container/classes/class.ilContainer.php'; + ilContainer::_writeContainerSetting($a_obj_id, self::CALENDAR_VISIBILITY, (int) $form->getInput(self::CALENDAR_VISIBILITY)); + } + } + + // news + if (in_array(self::USE_NEWS, $services)) { + include_once './Services/Container/classes/class.ilContainer.php'; + ilContainer::_writeContainerSetting($a_obj_id, self::USE_NEWS, (int) $form->getInput(self::USE_NEWS)); + } + if (in_array(self::NEWS_VISIBILITY, $services)) { + include_once './Services/Container/classes/class.ilContainer.php'; + ilContainer::_writeContainerSetting($a_obj_id, self::NEWS_VISIBILITY, (int) $form->getInput(self::NEWS_VISIBILITY)); + + if (in_array(ilObject::_lookupType($a_obj_id), array('crs', 'grp'))) { + $ref_id = array_pop(ilObject::_getAllReferences($a_obj_id)); + + include_once "Services/Membership/classes/class.ilMembershipNotifications.php"; + ilMembershipNotifications::importFromForm($ref_id, $form); + } + } + + // rating + if (in_array(self::AUTO_RATING_NEW_OBJECTS, $services)) { + include_once './Services/Container/classes/class.ilContainer.php'; + ilContainer::_writeContainerSetting($a_obj_id, self::AUTO_RATING_NEW_OBJECTS, (int) $form->getInput(self::AUTO_RATING_NEW_OBJECTS)); + } - // taxonomies - if(in_array(self::TAXONOMIES, $services)) - { - include_once './Services/Container/classes/class.ilContainer.php'; - ilContainer::_writeContainerSetting($a_obj_id,self::TAXONOMIES,(int) $form->getInput(self::TAXONOMIES)); - } + // taxonomies + if (in_array(self::TAXONOMIES, $services)) { + include_once './Services/Container/classes/class.ilContainer.php'; + ilContainer::_writeContainerSetting($a_obj_id, self::TAXONOMIES, (int) $form->getInput(self::TAXONOMIES)); + } - // tag cloud - if(in_array(self::TAG_CLOUD, $services)) - { - include_once './Services/Container/classes/class.ilContainer.php'; - ilContainer::_writeContainerSetting($a_obj_id,self::TAG_CLOUD,(int) $form->getInput(self::TAG_CLOUD)); - } - - // (local) custom metadata - if(in_array(self::CUSTOM_METADATA, $services)) - { - include_once './Services/Container/classes/class.ilContainer.php'; - ilContainer::_writeContainerSetting($a_obj_id,self::CUSTOM_METADATA,(int) $form->getInput(self::CUSTOM_METADATA)); - } - - // badges - if(in_array(self::BADGES, $services)) - { - include_once 'Services/Badge/classes/class.ilBadgeHandler.php'; - if(ilBadgeHandler::getInstance()->isActive()) - { - include_once './Services/Container/classes/class.ilContainer.php'; - ilContainer::_writeContainerSetting($a_obj_id,self::BADGES,(int) $form->getInput(self::BADGES)); - } - } - - // extended user access - if(in_array(self::ORGU_POSITION_ACCESS, $services)) - { - $position_settings = ilOrgUnitGlobalSettings::getInstance()->getObjectPositionSettingsByType( - ilObject::_lookupType($a_obj_id) - ); - - if( $position_settings->isActive() && $position_settings->isChangeableForObject() ) - { - $orgu_object_settings = new ilOrgUnitObjectPositionSetting($a_obj_id); - $orgu_object_settings->setActive( - (int) $form->getInput(self::ORGU_POSITION_ACCESS) - ); - $orgu_object_settings->update(); - } - } + // tag cloud + if (in_array(self::TAG_CLOUD, $services)) { + include_once './Services/Container/classes/class.ilContainer.php'; + ilContainer::_writeContainerSetting($a_obj_id, self::TAG_CLOUD, (int) $form->getInput(self::TAG_CLOUD)); + } + + // (local) custom metadata + if (in_array(self::CUSTOM_METADATA, $services)) { + include_once './Services/Container/classes/class.ilContainer.php'; + ilContainer::_writeContainerSetting($a_obj_id, self::CUSTOM_METADATA, (int) $form->getInput(self::CUSTOM_METADATA)); + } + + // badges + if (in_array(self::BADGES, $services)) { + include_once 'Services/Badge/classes/class.ilBadgeHandler.php'; + if (ilBadgeHandler::getInstance()->isActive()) { + include_once './Services/Container/classes/class.ilContainer.php'; + ilContainer::_writeContainerSetting($a_obj_id, self::BADGES, (int) $form->getInput(self::BADGES)); + } + } + + // extended user access + if (in_array(self::ORGU_POSITION_ACCESS, $services)) { + $position_settings = ilOrgUnitGlobalSettings::getInstance()->getObjectPositionSettingsByType( + ilObject::_lookupType($a_obj_id) + ); + + if ($position_settings->isActive() && $position_settings->isChangeableForObject()) { + $orgu_object_settings = new ilOrgUnitObjectPositionSetting($a_obj_id); + $orgu_object_settings->setActive( + (int) $form->getInput(self::ORGU_POSITION_ACCESS) + ); + $orgu_object_settings->update(); + } + } - // skills - if(in_array(self::SKILLS, $services)) - { - include_once './Services/Container/classes/class.ilContainer.php'; - ilContainer::_writeContainerSetting($a_obj_id,self::SKILLS,(int) $form->getInput(self::SKILLS)); - } + // skills + if (in_array(self::SKILLS, $services)) { + include_once './Services/Container/classes/class.ilContainer.php'; + ilContainer::_writeContainerSetting($a_obj_id, self::SKILLS, (int) $form->getInput(self::SKILLS)); + } - return true; - } + return true; + } - - /** - * Get active modes - * @return bool - */ - public function getModes() - { - return $this->modes; - } - - /** - * Get obj id - * @return type - */ - public function getObjId() - { - return $this->obj_id; - } - - protected function cancel() - { - $ilCtrl = $this->ctrl; - $ilCtrl->returnToParent($this); - } - - /** - * Edit tool settings (calendar, news, comments, ...) - * @param ilPropertyFormGUI $form - */ - protected function editSettings(ilPropertyFormGUI $form = null) - { - global $DIC; + + /** + * Get active modes + * @return bool + */ + public function getModes() + { + return $this->modes; + } + + /** + * Get obj id + * @return type + */ + public function getObjId() + { + return $this->obj_id; + } + + protected function cancel() + { + $ilCtrl = $this->ctrl; + $ilCtrl->returnToParent($this); + } + + /** + * Edit tool settings (calendar, news, comments, ...) + * @param ilPropertyFormGUI $form + */ + protected function editSettings(ilPropertyFormGUI $form = null) + { + global $DIC; - $tpl = $DIC->ui()->mainTemplate(); + $tpl = $DIC->ui()->mainTemplate(); - if(!$form instanceof ilPropertyFormGUI) - { - $form = $this->initSettingsForm(); - } - $tpl->setContent($form->getHTML()); - } - - - /** - * Update settings - */ - protected function updateToolSettings() - { - global $DIC; + if (!$form instanceof ilPropertyFormGUI) { + $form = $this->initSettingsForm(); + } + $tpl->setContent($form->getHTML()); + } + + + /** + * Update settings + */ + protected function updateToolSettings() + { + global $DIC; - $lng = $DIC->language(); - $ctrl = $this->ctrl; + $lng = $DIC->language(); + $ctrl = $this->ctrl; - $form = $this->initSettingsForm(); - if($form->checkInput()) - { - include_once './Services/Calendar/classes/class.ilCalendarSettings.php'; - if(ilCalendarSettings::_getInstance()->isEnabled()) - { - if($this->isModeActive(self::CALENDAR_VISIBILITY)) - { - ilContainer::_writeContainerSetting($this->getObjId(),'show_calendar',(int) $form->getInput('calendar')); - } - } - ilUtil::sendSuccess($lng->txt('settings_saved'),true); - $ctrl->redirect($this); - } - - ilUtil::sendFailure($lng->txt('err_check_input')); - $form->setValuesByPost(); - $this->editSettings($form); - } - - /** - * Check if specific mode is active - * @param type $a_mode - * @return type - */ - protected function isModeActive($a_mode) - { - return in_array($a_mode, $this->getModes()); - } - + $form = $this->initSettingsForm(); + if ($form->checkInput()) { + include_once './Services/Calendar/classes/class.ilCalendarSettings.php'; + if (ilCalendarSettings::_getInstance()->isEnabled()) { + if ($this->isModeActive(self::CALENDAR_VISIBILITY)) { + ilContainer::_writeContainerSetting($this->getObjId(), 'show_calendar', (int) $form->getInput('calendar')); + } + } + ilUtil::sendSuccess($lng->txt('settings_saved'), true); + $ctrl->redirect($this); + } + + ilUtil::sendFailure($lng->txt('err_check_input')); + $form->setValuesByPost(); + $this->editSettings($form); + } + + /** + * Check if specific mode is active + * @param type $a_mode + * @return type + */ + protected function isModeActive($a_mode) + { + return in_array($a_mode, $this->getModes()); + } } -?> diff --git a/Services/Object/classes/class.ilObjectSubItemListGUI.php b/Services/Object/classes/class.ilObjectSubItemListGUI.php index 309d3cd3b4e31defb55878a08b8e35ab419f27ca..0e0b1cd68be458f1692de0e36be16a1e4ceadb61 100644 --- a/Services/Object/classes/class.ilObjectSubItemListGUI.php +++ b/Services/Object/classes/class.ilObjectSubItemListGUI.php @@ -1,46 +1,45 @@ * @version $Id$ -* * -* @ingroup ServicesObject +* +* @ingroup ServicesObject */ class ilObjectSubItemListGUI extends ilSubItemListGUI { - /** - * get html - * @return - */ - public function getHTML() - { - return ''; - } + /** + * get html + * @return + */ + public function getHTML() + { + return ''; + } } -?> diff --git a/Services/Object/classes/class.ilObjectTableGUI.php b/Services/Object/classes/class.ilObjectTableGUI.php index e8626b42147f58a3843dbba49d81c5cad2811505..056709a4dddd397cfbef874464d07de0b9282051 100644 --- a/Services/Object/classes/class.ilObjectTableGUI.php +++ b/Services/Object/classes/class.ilObjectTableGUI.php @@ -3,172 +3,165 @@ /** * Settings for LO courses - * + * * @author Stefan Meyer * @version $Id$ */ class ilObjectTableGUI extends ilTable2GUI { - protected $objects = array(); - protected $show_path = FALSE; - protected $row_selection_input = FALSE; - - /** - * Constructor - * @param type $a_parent_obj - * @param type $a_parent_cmd - * @param type $a_id - */ - public function __construct($a_parent_obj, $a_parent_cmd, $a_id) - { - $this->setId('obj_table_'.$a_id); - parent::__construct($a_parent_obj, $a_parent_cmd, ''); - - } - - /** - * - * @param type $a_status - */ - public function enableObjectPath($a_status) - { - $this->show_path = $a_status; - } - - /** - * - * @return type - */ - public function enabledObjectPath() - { - return $this->show_path; - } - - /** - * Customize path instance - * @param ilPathGUI $path - * @return \ilPathGUI - */ - public function customizePath(ilPathGUI $path) - { - return $path; - } - - public function enableRowSelectionInput($a_stat) - { - $this->row_selection_input = $a_stat; - } - - /** - * @return type - */ - public function enabledRowSelectionInput() - { - return $this->row_selection_input; - } - - /** - * Fill row selection input - * @param type $set - */ - public function fillRowSelectionInput($set) - { - $this->tpl->setCurrentBlock('row_selection_input'); - $this->tpl->setVariable('OBJ_INPUT_TYPE','checkbox'); - $this->tpl->setVariable('OBJ_INPUT_NAME','id[]'); - $this->tpl->setVariable('OBJ_INPUT_VALUE',$set['ref_id']); - } + protected $objects = array(); + protected $show_path = false; + protected $row_selection_input = false; + + /** + * Constructor + * @param type $a_parent_obj + * @param type $a_parent_cmd + * @param type $a_id + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_id) + { + $this->setId('obj_table_' . $a_id); + parent::__construct($a_parent_obj, $a_parent_cmd, ''); + } + + /** + * + * @param type $a_status + */ + public function enableObjectPath($a_status) + { + $this->show_path = $a_status; + } + + /** + * + * @return type + */ + public function enabledObjectPath() + { + return $this->show_path; + } + + /** + * Customize path instance + * @param ilPathGUI $path + * @return \ilPathGUI + */ + public function customizePath(ilPathGUI $path) + { + return $path; + } + + public function enableRowSelectionInput($a_stat) + { + $this->row_selection_input = $a_stat; + } + + /** + * @return type + */ + public function enabledRowSelectionInput() + { + return $this->row_selection_input; + } + + /** + * Fill row selection input + * @param type $set + */ + public function fillRowSelectionInput($set) + { + $this->tpl->setCurrentBlock('row_selection_input'); + $this->tpl->setVariable('OBJ_INPUT_TYPE', 'checkbox'); + $this->tpl->setVariable('OBJ_INPUT_NAME', 'id[]'); + $this->tpl->setVariable('OBJ_INPUT_VALUE', $set['ref_id']); + } - - /** - * set table content objects - * @param array $a_ref_ids - */ - public function setObjects($a_ref_ids) - { - $this->objects = $a_ref_ids; - } - - /** - * get object ref_ids - * @return type - */ - public function getObjects() - { - return $this->objects; - } - - /** - * init table - */ - public function init() - { - if($this->enabledRowSelectionInput()) - { - $this->addColumn('','id','5px'); - } - - $this->addColumn($this->lng->txt('type'), 'type','30px'); - $this->addColumn($this->lng->txt('title'),'title'); - - $this->setOrderColumn('title'); - $this->setRowTemplate('tpl.object_table_row.html', 'Services/Object'); - - } - - /** - * fill table rows - * @param type $set - */ - public function fillRow($set) - { - include_once './Services/Link/classes/class.ilLink.php'; - - if($this->enabledRowSelectionInput()) - { - $this->fillRowSelectionInput($set); - } - - $this->tpl->setVariable('OBJ_LINK',ilLink::_getLink($set['ref_id'], $set['type'])); - $this->tpl->setVariable('OBJ_LINKED_TITLE',$set['title']); - $this->tpl->setVariable('TYPE_IMG',ilUtil::getTypeIconPath($set['type'], $set['obj_id'])); - $this->tpl->setVariable('TYPE_STR',$this->lng->txt('obj_'.$set['type'])); - - - if($this->enabledObjectPath()) - { - include_once './Services/Tree/classes/class.ilPathGUI.php'; - $path_gui = new ilPathGUI(); - $path_gui = $this->customizePath($path_gui); - - $this->tpl->setCurrentBlock('path'); - $this->tpl->setVariable('OBJ_PATH',$path_gui->getPath(ROOT_FOLDER_ID, $set['ref_id'])); - $this->tpl->parseCurrentBlock(); - } - } - - /** - * Parse objects - */ - public function parse() - { - $counter = 0; - $set = array(); - foreach($this->getObjects() as $ref_id) - { - $type = ilObject::_lookupType(ilObject::_lookupObjId($ref_id)); - if($type == 'rolf') - { - continue; - } - - $set[$counter]['ref_id'] = $ref_id; - $set[$counter]['obj_id'] = ilObject::_lookupObjId($ref_id); - $set[$counter]['type'] = ilObject::_lookupType(ilObject::_lookupObjId($ref_id)); - $set[$counter]['title'] = ilObject::_lookupTitle(ilObject::_lookupObjId($ref_id)); - $counter++; - } - $this->setData($set); - } -} \ No newline at end of file + + /** + * set table content objects + * @param array $a_ref_ids + */ + public function setObjects($a_ref_ids) + { + $this->objects = $a_ref_ids; + } + + /** + * get object ref_ids + * @return type + */ + public function getObjects() + { + return $this->objects; + } + + /** + * init table + */ + public function init() + { + if ($this->enabledRowSelectionInput()) { + $this->addColumn('', 'id', '5px'); + } + + $this->addColumn($this->lng->txt('type'), 'type', '30px'); + $this->addColumn($this->lng->txt('title'), 'title'); + + $this->setOrderColumn('title'); + $this->setRowTemplate('tpl.object_table_row.html', 'Services/Object'); + } + + /** + * fill table rows + * @param type $set + */ + public function fillRow($set) + { + include_once './Services/Link/classes/class.ilLink.php'; + + if ($this->enabledRowSelectionInput()) { + $this->fillRowSelectionInput($set); + } + + $this->tpl->setVariable('OBJ_LINK', ilLink::_getLink($set['ref_id'], $set['type'])); + $this->tpl->setVariable('OBJ_LINKED_TITLE', $set['title']); + $this->tpl->setVariable('TYPE_IMG', ilUtil::getTypeIconPath($set['type'], $set['obj_id'])); + $this->tpl->setVariable('TYPE_STR', $this->lng->txt('obj_' . $set['type'])); + + + if ($this->enabledObjectPath()) { + include_once './Services/Tree/classes/class.ilPathGUI.php'; + $path_gui = new ilPathGUI(); + $path_gui = $this->customizePath($path_gui); + + $this->tpl->setCurrentBlock('path'); + $this->tpl->setVariable('OBJ_PATH', $path_gui->getPath(ROOT_FOLDER_ID, $set['ref_id'])); + $this->tpl->parseCurrentBlock(); + } + } + + /** + * Parse objects + */ + public function parse() + { + $counter = 0; + $set = array(); + foreach ($this->getObjects() as $ref_id) { + $type = ilObject::_lookupType(ilObject::_lookupObjId($ref_id)); + if ($type == 'rolf') { + continue; + } + + $set[$counter]['ref_id'] = $ref_id; + $set[$counter]['obj_id'] = ilObject::_lookupObjId($ref_id); + $set[$counter]['type'] = ilObject::_lookupType(ilObject::_lookupObjId($ref_id)); + $set[$counter]['title'] = ilObject::_lookupTitle(ilObject::_lookupObjId($ref_id)); + $counter++; + } + $this->setData($set); + } +} diff --git a/Services/Object/classes/class.ilObjectTranslation.php b/Services/Object/classes/class.ilObjectTranslation.php index d53638ec7547bf3c08659f9cb5698f21afbd3c7e..586352f43df30f0b9ae8f22a962ab6b4c3cfa9c7 100644 --- a/Services/Object/classes/class.ilObjectTranslation.php +++ b/Services/Object/classes/class.ilObjectTranslation.php @@ -28,404 +28,374 @@ */ class ilObjectTranslation { - protected $db; - protected $obj_id; - protected $master_lang; - protected $languages = array(); - protected $content_activated = false; - static protected $instances = array(); - - /** - * Constructor - * - * @param int $a_obj_id object id - * @throws ilObjectException - */ - private function __construct($a_obj_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $this->db = $ilDB; - - $this->setObjId($a_obj_id); - - if ($this->getObjId() <= 0) - { - include_once("./Services/Object/exceptions/class.ilObjectException.php"); - throw new ilObjectException("ilObjectTranslation: No object ID passed."); - } - - $this->read(); - } - - /** - * Get instance - * - * @param integer $a_obj_id (repository) object id - * @return ilObjectTranslation translation object - */ - static function getInstance($a_obj_id) - { - if (!isset(self::$instances[$a_obj_id])) - { - self::$instances[$a_obj_id] = new ilObjectTranslation($a_obj_id); - } - - return self::$instances[$a_obj_id]; - } - - - /** - * Set object id - * - * @param int $a_val object id - */ - function setObjId($a_val) - { - $this->obj_id = $a_val; - } - - /** - * Get object id - * - * @return int object id - */ - function getObjId() - { - return $this->obj_id; - } - - /** - * Set master language - * - * @param string $a_val master language - */ - function setMasterLanguage($a_val) - { - $this->master_lang = $a_val; - } - - /** - * Get master language - * - * @return string master language - */ - function getMasterLanguage() - { - return $this->master_lang; - } - - /** - * Set languages - * - * @param array $a_val array of language codes - */ - function setLanguages(array $a_val) - { - $this->languages = $a_val; - } - - /** - * Get languages - * - * @return array array of language codes - */ - function getLanguages() - { - return $this->languages; - } - - /** - * Add language - * - * @param string $a_lang language - * @param string $a_title title - * @param string $a_description description - * @param bool $a_default default language? - */ - function addLanguage($a_lang, $a_title, $a_description, $a_default, $a_force = false) - { - if ($a_lang != "" && (!isset($this->languages[$a_lang]) || $a_force)) - { - if ($a_default) - { - foreach ($this->languages as $k => $l) - { - $this->languages[$k]["lang_default"] = false; - } - } - $this->languages[$a_lang] = array("lang_code" => $a_lang, "lang_default" => $a_default, - "title" => $a_title, "description" => $a_description); - } - } - - /** - * Get default title - * - * @return string title of default language - */ - function getDefaultTitle() - { - foreach ($this->languages as $l) - { - if ($l["lang_default"]) - { - return $l["title"]; - } - } - if (count($this->languages) == 0) - { - return ilObject::_lookupTitle($this->getObjId()); - } - return ""; - } - - /** - * Set default title - * - * @param string $a_title title - */ - function setDefaultTitle($a_title) - { - foreach ($this->languages as $k => $l) - { - if ($l["lang_default"]) - { - $this->languages[$k]["title"] = $a_title; - } - } - } - - /** - * Get default description - * - * @return string description of default language - */ - function getDefaultDescription() - { - foreach ($this->languages as $l) - { - if ($l["lang_default"]) - { - return $l["description"]; - } - } - if (count($this->languages) == 0) - { - return ilObject::_lookupDescription($this->getObjId()); - } - return ""; - } - - /** - * Set default description - * - * @param string $a_description description - */ - function setDefaultDescription($a_description) - { - foreach ($this->languages as $k => $l) - { - if ($l["lang_default"]) - { - $this->languages[$k]["description"] = $a_description; - } - } - } - - /** - * Get default language - * - * @return string default language - */ - function getDefaultLanguage() - { - foreach ($this->languages as $l) - { - if ($l["lang_default"]) - { - return $l["lang_code"]; - } - } - return ""; - } - - - /** - * Remove language - * - * @param string $a_lang language code - */ - function removeLanguage($a_lang) - { - if ($a_lang != $this->getMasterLanguage()) - { - unset($this->languages[$a_lang]); - } - } - - - /** - * Set activated for content - * - * @param bool $a_val activated for content? - */ - protected function setContentActivated($a_val) - { - $this->content_activated = $a_val; - } - - /** - * Get activated for content - * - * @return bool activated for content? - */ - function getContentActivated() - { - return $this->content_activated; - } - - /** - * Read - */ - function read() - { - $set = $this->db->query("SELECT * FROM obj_content_master_lng ". - " WHERE obj_id = ".$this->db->quote($this->getObjId(), "integer") - ); - if ($rec = $this->db->fetchAssoc($set)) - { - $this->setMasterLanguage($rec["master_lang"]); - $this->setContentActivated(true); - } - else - { - $this->setContentActivated(false); - } - - $this->setLanguages(array()); - $set = $this->db->query("SELECT * FROM object_translation ". - " WHERE obj_id = ".$this->db->quote($this->getObjId(), "integer") - ); - while ($rec = $this->db->fetchAssoc($set)) - { - $this->addLanguage($rec["lang_code"], $rec["title"], $rec["description"], $rec["lang_default"]); - } - } - - /** - * Delete - */ - function delete() - { - $this->db->manipulate("DELETE FROM obj_content_master_lng ". - " WHERE obj_id = ".$this->db->quote($this->getObjId(), "integer") - ); - $this->db->manipulate("DELETE FROM object_translation ". - " WHERE obj_id = ".$this->db->quote($this->getObjId(), "integer") - ); - } - - /** - * Deactivate content translation - */ - function deactivateContentTranslation() - { - $this->db->manipulate("DELETE FROM obj_content_master_lng ". - " WHERE obj_id = ".$this->db->quote($this->getObjId(), "integer") - ); - } - - /** - * Save - */ - function save() - { - $this->delete(); - - if ($this->getMasterLanguage() != "") - { - $this->db->manipulate("INSERT INTO obj_content_master_lng ". - "(obj_id, master_lang) VALUES (". - $this->db->quote($this->getObjId(), "integer").",". - $this->db->quote($this->getMasterLanguage(), "text"). - ")"); - - // ensure that an entry for the master language exists and is the default - if (!isset($this->languages[$this->getMasterLanguage()])) - { - $this->languages[$this->getMasterLanguage()] = array("title" => "", - "description" => "", "lang_code" => $this->getMasterLanguage(), "lang_default" => 1); - } - foreach ($this->languages as $l => $trans) - { - if ($l == $this->getMasterLanguage()) - { - $this->languages[$l]["lang_default"] = 1; - } - else - { - $this->languages[$l]["lang_default"] = 0; - } - } - } - - foreach ($this->getLanguages() as $l => $trans) - { - $this->db->manipulate($t = "INSERT INTO object_translation ". - "(obj_id, title, description, lang_code, lang_default) VALUES (". - $this->db->quote($this->getObjId(), "integer").",". - $this->db->quote($trans["title"], "text").",". - $this->db->quote($trans["description"], "text").",". - $this->db->quote($l, "text").",". - $this->db->quote($trans["lang_default"], "integer"). - ")"); - } - } - - /** - * Copy multilinguality settings - * - * @param string $a_target_parent_type parent object type - * @param int $a_target_parent_id parent object id - * @return ilObjectTranslation target multilang object - */ - function copy($a_obj_id) - { - $target_ml = new ilObjectTranslation($a_obj_id); - $target_ml->setMasterLanguage($this->getMasterLanguage()); - $target_ml->setLanguages($this->getLanguages()); - $target_ml->save(); - return $target_ml; - } - - - /** - * Get effective language for given language. This checks if - * - multilinguality is activated and - * - the given language is part of the available translations - * If not a "-" is returned (master language). - * - * @param string $a_lang language - * @param string $a_parent_type page parent type - * @return string effective language ("-" for master) - */ - function getEffectiveContentLang($a_lang, $a_parent_type) - { - $langs = $this->getLanguages(); - if ($this->getContentActivated() && - isset($langs[$a_lang]) && - ilPageObject::_exists($a_parent_type, $this->getObjId(), $a_lang)) - { - return $a_lang; - } - return "-"; - } - - - + protected $db; + protected $obj_id; + protected $master_lang; + protected $languages = array(); + protected $content_activated = false; + protected static $instances = array(); + + /** + * Constructor + * + * @param int $a_obj_id object id + * @throws ilObjectException + */ + private function __construct($a_obj_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $this->db = $ilDB; + + $this->setObjId($a_obj_id); + + if ($this->getObjId() <= 0) { + include_once("./Services/Object/exceptions/class.ilObjectException.php"); + throw new ilObjectException("ilObjectTranslation: No object ID passed."); + } + + $this->read(); + } + + /** + * Get instance + * + * @param integer $a_obj_id (repository) object id + * @return ilObjectTranslation translation object + */ + public static function getInstance($a_obj_id) + { + if (!isset(self::$instances[$a_obj_id])) { + self::$instances[$a_obj_id] = new ilObjectTranslation($a_obj_id); + } + + return self::$instances[$a_obj_id]; + } + + + /** + * Set object id + * + * @param int $a_val object id + */ + public function setObjId($a_val) + { + $this->obj_id = $a_val; + } + + /** + * Get object id + * + * @return int object id + */ + public function getObjId() + { + return $this->obj_id; + } + + /** + * Set master language + * + * @param string $a_val master language + */ + public function setMasterLanguage($a_val) + { + $this->master_lang = $a_val; + } + + /** + * Get master language + * + * @return string master language + */ + public function getMasterLanguage() + { + return $this->master_lang; + } + + /** + * Set languages + * + * @param array $a_val array of language codes + */ + public function setLanguages(array $a_val) + { + $this->languages = $a_val; + } + + /** + * Get languages + * + * @return array array of language codes + */ + public function getLanguages() + { + return $this->languages; + } + + /** + * Add language + * + * @param string $a_lang language + * @param string $a_title title + * @param string $a_description description + * @param bool $a_default default language? + */ + public function addLanguage($a_lang, $a_title, $a_description, $a_default, $a_force = false) + { + if ($a_lang != "" && (!isset($this->languages[$a_lang]) || $a_force)) { + if ($a_default) { + foreach ($this->languages as $k => $l) { + $this->languages[$k]["lang_default"] = false; + } + } + $this->languages[$a_lang] = array("lang_code" => $a_lang, "lang_default" => $a_default, + "title" => $a_title, "description" => $a_description); + } + } + + /** + * Get default title + * + * @return string title of default language + */ + public function getDefaultTitle() + { + foreach ($this->languages as $l) { + if ($l["lang_default"]) { + return $l["title"]; + } + } + if (count($this->languages) == 0) { + return ilObject::_lookupTitle($this->getObjId()); + } + return ""; + } + + /** + * Set default title + * + * @param string $a_title title + */ + public function setDefaultTitle($a_title) + { + foreach ($this->languages as $k => $l) { + if ($l["lang_default"]) { + $this->languages[$k]["title"] = $a_title; + } + } + } + + /** + * Get default description + * + * @return string description of default language + */ + public function getDefaultDescription() + { + foreach ($this->languages as $l) { + if ($l["lang_default"]) { + return $l["description"]; + } + } + if (count($this->languages) == 0) { + return ilObject::_lookupDescription($this->getObjId()); + } + return ""; + } + + /** + * Set default description + * + * @param string $a_description description + */ + public function setDefaultDescription($a_description) + { + foreach ($this->languages as $k => $l) { + if ($l["lang_default"]) { + $this->languages[$k]["description"] = $a_description; + } + } + } + + /** + * Get default language + * + * @return string default language + */ + public function getDefaultLanguage() + { + foreach ($this->languages as $l) { + if ($l["lang_default"]) { + return $l["lang_code"]; + } + } + return ""; + } + + + /** + * Remove language + * + * @param string $a_lang language code + */ + public function removeLanguage($a_lang) + { + if ($a_lang != $this->getMasterLanguage()) { + unset($this->languages[$a_lang]); + } + } + + + /** + * Set activated for content + * + * @param bool $a_val activated for content? + */ + protected function setContentActivated($a_val) + { + $this->content_activated = $a_val; + } + + /** + * Get activated for content + * + * @return bool activated for content? + */ + public function getContentActivated() + { + return $this->content_activated; + } + + /** + * Read + */ + public function read() + { + $set = $this->db->query( + "SELECT * FROM obj_content_master_lng " . + " WHERE obj_id = " . $this->db->quote($this->getObjId(), "integer") + ); + if ($rec = $this->db->fetchAssoc($set)) { + $this->setMasterLanguage($rec["master_lang"]); + $this->setContentActivated(true); + } else { + $this->setContentActivated(false); + } + + $this->setLanguages(array()); + $set = $this->db->query( + "SELECT * FROM object_translation " . + " WHERE obj_id = " . $this->db->quote($this->getObjId(), "integer") + ); + while ($rec = $this->db->fetchAssoc($set)) { + $this->addLanguage($rec["lang_code"], $rec["title"], $rec["description"], $rec["lang_default"]); + } + } + + /** + * Delete + */ + public function delete() + { + $this->db->manipulate( + "DELETE FROM obj_content_master_lng " . + " WHERE obj_id = " . $this->db->quote($this->getObjId(), "integer") + ); + $this->db->manipulate( + "DELETE FROM object_translation " . + " WHERE obj_id = " . $this->db->quote($this->getObjId(), "integer") + ); + } + + /** + * Deactivate content translation + */ + public function deactivateContentTranslation() + { + $this->db->manipulate( + "DELETE FROM obj_content_master_lng " . + " WHERE obj_id = " . $this->db->quote($this->getObjId(), "integer") + ); + } + + /** + * Save + */ + public function save() + { + $this->delete(); + + if ($this->getMasterLanguage() != "") { + $this->db->manipulate("INSERT INTO obj_content_master_lng " . + "(obj_id, master_lang) VALUES (" . + $this->db->quote($this->getObjId(), "integer") . "," . + $this->db->quote($this->getMasterLanguage(), "text") . + ")"); + + // ensure that an entry for the master language exists and is the default + if (!isset($this->languages[$this->getMasterLanguage()])) { + $this->languages[$this->getMasterLanguage()] = array("title" => "", + "description" => "", "lang_code" => $this->getMasterLanguage(), "lang_default" => 1); + } + foreach ($this->languages as $l => $trans) { + if ($l == $this->getMasterLanguage()) { + $this->languages[$l]["lang_default"] = 1; + } else { + $this->languages[$l]["lang_default"] = 0; + } + } + } + + foreach ($this->getLanguages() as $l => $trans) { + $this->db->manipulate($t = "INSERT INTO object_translation " . + "(obj_id, title, description, lang_code, lang_default) VALUES (" . + $this->db->quote($this->getObjId(), "integer") . "," . + $this->db->quote($trans["title"], "text") . "," . + $this->db->quote($trans["description"], "text") . "," . + $this->db->quote($l, "text") . "," . + $this->db->quote($trans["lang_default"], "integer") . + ")"); + } + } + + /** + * Copy multilinguality settings + * + * @param string $a_target_parent_type parent object type + * @param int $a_target_parent_id parent object id + * @return ilObjectTranslation target multilang object + */ + public function copy($a_obj_id) + { + $target_ml = new ilObjectTranslation($a_obj_id); + $target_ml->setMasterLanguage($this->getMasterLanguage()); + $target_ml->setLanguages($this->getLanguages()); + $target_ml->save(); + return $target_ml; + } + + + /** + * Get effective language for given language. This checks if + * - multilinguality is activated and + * - the given language is part of the available translations + * If not a "-" is returned (master language). + * + * @param string $a_lang language + * @param string $a_parent_type page parent type + * @return string effective language ("-" for master) + */ + public function getEffectiveContentLang($a_lang, $a_parent_type) + { + $langs = $this->getLanguages(); + if ($this->getContentActivated() && + isset($langs[$a_lang]) && + ilPageObject::_exists($a_parent_type, $this->getObjId(), $a_lang)) { + return $a_lang; + } + return "-"; + } } - -?> \ No newline at end of file diff --git a/Services/Object/classes/class.ilObjectTranslation2TableGUI.php b/Services/Object/classes/class.ilObjectTranslation2TableGUI.php index 14e29361e1e68d084a3efbea05c669fc636dabdf..6ae81b96dec102e188ab6e658f7e78f2f82faae5 100644 --- a/Services/Object/classes/class.ilObjectTranslation2TableGUI.php +++ b/Services/Object/classes/class.ilObjectTranslation2TableGUI.php @@ -13,121 +13,122 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilObjectTranslation2TableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilAccessHandler - */ - protected $access; - - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_incl_desc = true, $a_base_cmd = "HeaderTitle", - $a_master_lang = "") - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $ilCtrl = $DIC->ctrl(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->incl_desc = $a_incl_desc; - $this->base_cmd = $a_base_cmd; - $this->master_lang = $a_master_lang; - - $this->setLimit(9999); - - $this->addColumn("", "", "1"); - $this->addColumn($this->lng->txt("language"), "", ""); - $this->addColumn($this->lng->txt("default"), "", ""); - $this->addColumn($this->lng->txt("title"), "", ""); - if ($a_incl_desc) - { - $this->addColumn($this->lng->txt("description"), "", ""); - } - - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.obj_translation2_row.html", "Services/Object"); - $this->disable("footer"); - $this->setEnableTitle(true); - - $this->nr = 0; - } - - /** - * Prepare output - */ - function prepareOutput() - { - $lng = $this->lng; - - $this->addMultiCommand("delete".$this->base_cmd."s", $lng->txt("remove")); - if ($this->dataExists()) - { - $this->addCommandButton("save".$this->base_cmd."s", $lng->txt("save")); - } - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - - $this->nr++; - - - if (!$a_set["default"] && $a_set["lang"] != $this->master_lang) - { - $this->tpl->setCurrentBlock("cb"); - $this->tpl->setVariable("CB_NR", $this->nr); - $this->tpl->parseCurrentBlock(); - } - - if ($this->master_lang == "") - { - $this->tpl->setCurrentBlock("rb"); - $this->tpl->setVariable("RB_NR", $this->nr); - if ($a_set["default"]) - { - $this->tpl->setVariable("DEF_CHECKED", "checked=\"checked\""); - } - $this->tpl->parseCurrentBlock(); - } - else if ($a_set["lang"] == $this->master_lang) - { - $this->tpl->setVariable("MASTER_LANG", $lng->txt("obj_master_lang")); - } - - if ($this->incl_desc) - { - $this->tpl->setCurrentBlock("desc_row"); - $this->tpl->setVariable("VAL_DESC", ilUtil::prepareFormOutput($a_set["desc"])); - $this->tpl->setVariable("DNR", $this->nr); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setVariable("NR", $this->nr); - - // lang selection - include_once('Services/MetaData/classes/class.ilMDLanguageItem.php'); - $languages = ilMDLanguageItem::_getLanguages(); - $this->tpl->setVariable("LANG_SELECT", - ilUtil::formSelect($a_set["lang"], "lang[".$this->nr."]", $languages, - false, true)); - - - $this->tpl->setVariable("VAL_TITLE", ilUtil::prepareFormOutput($a_set["title"])); - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilAccessHandler + */ + protected $access; + + + /** + * Constructor + */ + public function __construct( + $a_parent_obj, + $a_parent_cmd, + $a_incl_desc = true, + $a_base_cmd = "HeaderTitle", + $a_master_lang = "" + ) { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $ilCtrl = $DIC->ctrl(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->incl_desc = $a_incl_desc; + $this->base_cmd = $a_base_cmd; + $this->master_lang = $a_master_lang; + + $this->setLimit(9999); + + $this->addColumn("", "", "1"); + $this->addColumn($this->lng->txt("language"), "", ""); + $this->addColumn($this->lng->txt("default"), "", ""); + $this->addColumn($this->lng->txt("title"), "", ""); + if ($a_incl_desc) { + $this->addColumn($this->lng->txt("description"), "", ""); + } + + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.obj_translation2_row.html", "Services/Object"); + $this->disable("footer"); + $this->setEnableTitle(true); + + $this->nr = 0; + } + + /** + * Prepare output + */ + public function prepareOutput() + { + $lng = $this->lng; + + $this->addMultiCommand("delete" . $this->base_cmd . "s", $lng->txt("remove")); + if ($this->dataExists()) { + $this->addCommandButton("save" . $this->base_cmd . "s", $lng->txt("save")); + } + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + + $this->nr++; + + + if (!$a_set["default"] && $a_set["lang"] != $this->master_lang) { + $this->tpl->setCurrentBlock("cb"); + $this->tpl->setVariable("CB_NR", $this->nr); + $this->tpl->parseCurrentBlock(); + } + + if ($this->master_lang == "") { + $this->tpl->setCurrentBlock("rb"); + $this->tpl->setVariable("RB_NR", $this->nr); + if ($a_set["default"]) { + $this->tpl->setVariable("DEF_CHECKED", "checked=\"checked\""); + } + $this->tpl->parseCurrentBlock(); + } elseif ($a_set["lang"] == $this->master_lang) { + $this->tpl->setVariable("MASTER_LANG", $lng->txt("obj_master_lang")); + } + + if ($this->incl_desc) { + $this->tpl->setCurrentBlock("desc_row"); + $this->tpl->setVariable("VAL_DESC", ilUtil::prepareFormOutput($a_set["desc"])); + $this->tpl->setVariable("DNR", $this->nr); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setVariable("NR", $this->nr); + + // lang selection + include_once('Services/MetaData/classes/class.ilMDLanguageItem.php'); + $languages = ilMDLanguageItem::_getLanguages(); + $this->tpl->setVariable( + "LANG_SELECT", + ilUtil::formSelect( + $a_set["lang"], + "lang[" . $this->nr . "]", + $languages, + false, + true + ) + ); + + + $this->tpl->setVariable("VAL_TITLE", ilUtil::prepareFormOutput($a_set["title"])); + } } -?> diff --git a/Services/Object/classes/class.ilObjectTranslationGUI.php b/Services/Object/classes/class.ilObjectTranslationGUI.php index e055970f94d7a5738242b202069cdbb493f87651..e0be99b2c21dacb30136f24896185f63f70bc831 100644 --- a/Services/Object/classes/class.ilObjectTranslationGUI.php +++ b/Services/Object/classes/class.ilObjectTranslationGUI.php @@ -11,535 +11,489 @@ */ class ilObjectTranslationGUI { - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilObjUser - */ - protected $user; - - protected $obj_trans; - protected $title_descr_only = true; - - /** - * Constructor - */ - function __construct($a_obj_gui) - { - global $DIC; - - $this->toolbar = $DIC->toolbar(); - $this->user = $DIC->user(); - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $tpl = $DIC["tpl"]; - - $this->lng = $lng; - $this->ctrl = $ilCtrl; - $this->tpl = $tpl; - $this->obj_gui = $a_obj_gui; - $this->obj = $a_obj_gui->object; - - include_once("./Services/Object/classes/class.ilObjectTranslation.php"); - $this->obj_trans = ilObjectTranslation::getInstance($this->obj->getId()); - } - - /** - * Set enable title/description only mode - * - * @param bool $a_val enable title/description only mode - */ - function setTitleDescrOnlyMode($a_val) - { - $this->title_descr_only = $a_val; - } - - /** - * Get enable title/description only mode - * - * @return bool enable title/description only mode - */ - function getTitleDescrOnlyMode() - { - return $this->title_descr_only; - } - - /** - * Execute command - */ - function executeCommand() - { - $next_class = $this->ctrl->getNextClass($this); - - switch ($next_class) - { - default: - $cmd = $this->ctrl->getCmd("listTranslations"); - if (in_array($cmd, array("listTranslations", "saveTranslations", - "addTranslation", "deleteTranslations", "activateContentMultilinguality", - "confirmRemoveLanguages", "removeLanguages", "confirmDeactivateContentMultiLang", "saveLanguages", - "saveContentTranslationActivation", "deactivateContentMultiLang", "addLanguages"))) - { - $this->$cmd(); - } - break; - } - } - - /** - * List translations - */ - function listTranslations($a_get_post_values = false, $a_add = false) - { - $ilToolbar = $this->toolbar; - - $this->lng->loadLanguageModule(ilObject::_lookupType($this->obj->getId())); - - - if ($this->getTitleDescrOnlyMode() || $this->obj_trans->getContentActivated()) - { - $ilToolbar->addButton($this->lng->txt("obj_add_languages"), - $this->ctrl->getLinkTarget($this, "addLanguages")); - } - - if ($this->getTitleDescrOnlyMode()) - { - if (!$this->obj_trans->getContentActivated()) - { - ilUtil::sendInfo($this->lng->txt("obj_multilang_title_descr_only")); - $ilToolbar->addButton($this->lng->txt("obj_activate_content_lang"), - $this->ctrl->getLinkTarget($this, "activateContentMultilinguality")); - } - else - { - $ilToolbar->addButton($this->lng->txt("obj_deactivate_content_lang"), - $this->ctrl->getLinkTarget($this, "confirmDeactivateContentMultiLang")); - } - } - else - { - - if ($this->obj_trans->getContentActivated()) - { - $ilToolbar->addButton($this->lng->txt("obj_deactivate_multilang"), - $this->ctrl->getLinkTarget($this, "confirmDeactivateContentMultiLang")); - } - else - { - $ilToolbar->addButton($this->lng->txt("obj_activate_multilang"), - $this->ctrl->getLinkTarget($this, "activateContentMultilinguality")); - return; - } - } - - include_once("./Services/Object/classes/class.ilObjectTranslation2TableGUI.php"); - $table = new ilObjectTranslation2TableGUI($this, "listTranslations", true, - "Translation", $this->obj_trans->getMasterLanguage()); - 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->obj_trans->getLanguages(); - foreach($data as $k => $v) - { - $data[$k]["default"] = $v["lang_default"]; - $data[$k]["desc"] = $v["description"]; - $data[$k]["lang"] = $v["lang_code"]; - } -/* if($a_add) - { - $data["Fobject"][++$k]["title"] = ""; - }*/ - $table->setData($data); - } - $this->tpl->setContent($table->getHTML()); - - } - - /** - * Save translations - */ - function saveTranslations() - { - // default language set? - if (!isset($_POST["default"]) && $this->obj_trans->getMasterLanguage() == "") - { - ilUtil::sendFailure($this->lng->txt("msg_no_default_language")); - $this->listTranslations(true); - return; - } - - // all languages set? - if (array_key_exists("",$_POST["lang"])) - { - ilUtil::sendFailure($this->lng->txt("msg_no_language_selected")); - $this->listTranslations(true); - return; - } - - // no single language is selected more than once? - if (count(array_unique($_POST["lang"])) < count($_POST["lang"])) - { - ilUtil::sendFailure($this->lng->txt("msg_multi_language_selected")); - $this->listTranslations(true); - return; - } - - // save the stuff - $this->obj_trans->setLanguages(array()); - - foreach($_POST["title"] as $k => $v) - { - // update object data if default - $is_default = ($_POST["default"] == $k); - - // ensure master language is set as default - if ($this->obj_trans->getMasterLanguage() != "") - { - $is_default = ($this->obj_trans->getMasterLanguage() == $_POST["lang"][$k]); - } - if($is_default) - { - $this->obj->setTitle(ilUtil::stripSlashes($v)); - $this->obj->setDescription(ilUtil::stripSlashes($_POST["desc"][$k])); - } - - $this->obj_trans->addLanguage(ilUtil::stripSlashes($_POST["lang"][$k]), - ilUtil::stripSlashes($v), - ilUtil::stripSlashes($_POST["desc"][$k]), - $is_default - ); - } - $this->obj_trans->save(); - if (method_exists($this->obj, "setObjectTranslation")) - { - $this->obj->setObjectTranslation($this->obj_trans); - } - $this->obj->update(); - - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "listTranslations"); - - } - - /** - * Remove translation - */ - function deleteTranslations() - { - foreach($_POST["title"] as $k => $v) - { - if ($_POST["check"][$k]) - { - // default translation cannot be deleted - if($k != $_POST["default"]) - { - unset($_POST["title"][$k]); - unset($_POST["desc"][$k]); - unset($_POST["lang"][$k]); - } - else - { - ilUtil::sendFailure($this->lng->txt("msg_no_default_language")); - $this->listTranslations(); - return; - } - } - } - $this->saveTranslations(); - } - - //// - //// Content translation - //// - - /** - * Activate multi language (-> master language selection) - */ - function activateContentMultilinguality() - { - $tpl = $this->tpl; - $lng = $this->lng; - - ilUtil::sendInfo($lng->txt("obj_select_master_lang")); - - $form = $this->getMultiLangForm(); - $tpl->setContent($form->getHTML()); - } - - /** - * Get multi language form - */ - function getMultiLangForm($a_add = false) - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - - // master language - if (!$a_add) - { - include_once("./Services/MetaData/classes/class.ilMDLanguageItem.php"); - $options = ilMDLanguageItem::_getLanguages(); - $si = new ilSelectInputGUI($lng->txt("obj_master_lang"), "master_lang"); - $si->setOptions($options); - $si->setValue($ilUser->getLanguage()); - $form->addItem($si); - } - - // additional languages - if ($a_add) - { - include_once("./Services/MetaData/classes/class.ilMDLanguageItem.php"); - $options = ilMDLanguageItem::_getLanguages(); - $options = array("" => $lng->txt("please_select")) + $options; - $si = new ilSelectInputGUI($lng->txt("obj_additional_langs"), "additional_langs"); - $si->setOptions($options); - $si->setMulti(true); - $form->addItem($si); - } - - if ($a_add) - { - $form->setTitle($lng->txt("obj_add_languages")); - $form->addCommandButton("saveLanguages", $lng->txt("save")); - $form->addCommandButton("listTranslations", $lng->txt("cancel")); - } - else - { - if ($this->getTitleDescrOnlyMode()) - { - $form->setTitle($lng->txt("obj_activate_content_lang")); - } - else - { - $form->setTitle($lng->txt("obj_activate_multilang")); - } - $form->addCommandButton("saveContentTranslationActivation", $lng->txt("save")); - $form->addCommandButton("listTranslations", $lng->txt("cancel")); - } - $form->setFormAction($ilCtrl->getFormAction($this)); - - return $form; - } - - /** - * Save content translation activation - */ - function saveContentTranslationActivation() - { - $ilCtrl = $this->ctrl; - -// include_once("./Services/COPage/classes/class.ilPageMultiLang.php"); - - $form = $this->getMultiLangForm(); - if ($form->checkInput()) - { - $ml = $form->getInput("master_lang"); - $this->obj_trans->setMasterLanguage($ml); - $this->obj_trans->addLanguage($ml, - $this->obj->getTitle(), - $this->obj->getDescription(), - true - ); - $this->obj_trans->setDefaultTitle($this->obj->getTitle()); - $this->obj_trans->setDefaultDescription($this->obj->getDescription()); - $this->obj_trans->save(); - } - - $ilCtrl->redirect($this, "listTranslations"); - } - - /** - * Confirm page translation creation - */ - function confirmDeactivateContentMultiLang() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - if ($this->getTitleDescrOnlyMode()) - { - $cgui->setHeaderText($lng->txt("obj_deactivate_content_transl_conf")); - } - else - { - $cgui->setHeaderText($lng->txt("obj_deactivate_multilang_conf")); - } - - $cgui->setCancel($lng->txt("cancel"), "listTranslations"); - $cgui->setConfirm($lng->txt("confirm"), "deactivateContentMultiLang"); - $tpl->setContent($cgui->getHTML()); - } - - /** - * Deactivate multilanguage - */ - function deactivateContentMultiLang() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if (!$this->getTitleDescrOnlyMode()) - { - $this->obj_trans->setMasterLanguage(""); - $this->obj_trans->setLanguages(array()); - $this->obj_trans->save(); - } - $this->obj_trans->deactivateContentTranslation(); - if ($this->getTitleDescrOnlyMode()) - { - ilUtil::sendSuccess($lng->txt("obj_cont_transl_deactivated"), true); - } - else - { - ilUtil::sendSuccess($lng->txt("obj_multilang_deactivated"), true); - } - - - $ilCtrl->redirect($this, "listTranslations"); - } - - /** - * Add language - */ - function addLanguages() - { - $tpl = $this->tpl; - - $form = $this->getMultiLangForm(true); - $tpl->setContent($form->getHTML()); - } - - /** - * Save languages - */ - function saveLanguages() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - - $form = $this->getMultiLangForm(true); - if($form->checkInput()) - { - $ad = $form->getInput("additional_langs"); - if (is_array($ad)) - { - $ml = $this->obj_trans->getMasterLanguage(); - foreach ($ad as $l) - { - if ($l != $ml && $l != "") - { - $this->obj_trans->addLanguage($l, false, "", ""); - } - } - } - $this->obj_trans->save(); - ilUtil::sendInfo($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "listTranslations"); - } - - ilUtil::sendFailure($this->lng->txt('err_check_input')); - $form->setValuesByPost(); - $tpl->setContent($form->getHTML()); - } - - /** - * Confirm remove languages - */ - function confirmRemoveLanguages() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - $lng->loadLanguageModule("meta"); - - if (!is_array($_POST["lang"]) || count($_POST["lang"]) == 0) - { - ilUtil::sendInfo($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "listTranslations"); - } - else - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("obj_conf_delete_lang")); - $cgui->setCancel($lng->txt("cancel"), "listTranslations"); - $cgui->setConfirm($lng->txt("remove"), "removeLanguages"); - - foreach ($_POST["lang"] as $i) - { - $cgui->addItem("lang[]", $i, $lng->txt("meta_l_".$i)); - } - - $tpl->setContent($cgui->getHTML()); - } - } - - /** - * Remove languages - */ - function removeLanguages() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if (is_array($_POST["lang"])) - { - $langs = $this->obj_trans->getLanguages(); - foreach ($langs as $k => $l) - { - if (in_array($l, $_POST["lang"])) - { - $this->obj_trans->removeLanguage(); - } - } - $this->obj_trans->save(); - ilUtil::sendInfo($lng->txt("msg_obj_modified"), true); - } - $ilCtrl->redirect($this, "listTranslations"); - } - - + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilObjUser + */ + protected $user; + + protected $obj_trans; + protected $title_descr_only = true; + + /** + * Constructor + */ + public function __construct($a_obj_gui) + { + global $DIC; + + $this->toolbar = $DIC->toolbar(); + $this->user = $DIC->user(); + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $tpl = $DIC["tpl"]; + + $this->lng = $lng; + $this->ctrl = $ilCtrl; + $this->tpl = $tpl; + $this->obj_gui = $a_obj_gui; + $this->obj = $a_obj_gui->object; + + include_once("./Services/Object/classes/class.ilObjectTranslation.php"); + $this->obj_trans = ilObjectTranslation::getInstance($this->obj->getId()); + } + + /** + * Set enable title/description only mode + * + * @param bool $a_val enable title/description only mode + */ + public function setTitleDescrOnlyMode($a_val) + { + $this->title_descr_only = $a_val; + } + + /** + * Get enable title/description only mode + * + * @return bool enable title/description only mode + */ + public function getTitleDescrOnlyMode() + { + return $this->title_descr_only; + } + + /** + * Execute command + */ + public function executeCommand() + { + $next_class = $this->ctrl->getNextClass($this); + + switch ($next_class) { + default: + $cmd = $this->ctrl->getCmd("listTranslations"); + if (in_array($cmd, array("listTranslations", "saveTranslations", + "addTranslation", "deleteTranslations", "activateContentMultilinguality", + "confirmRemoveLanguages", "removeLanguages", "confirmDeactivateContentMultiLang", "saveLanguages", + "saveContentTranslationActivation", "deactivateContentMultiLang", "addLanguages"))) { + $this->$cmd(); + } + break; + } + } + + /** + * List translations + */ + public function listTranslations($a_get_post_values = false, $a_add = false) + { + $ilToolbar = $this->toolbar; + + $this->lng->loadLanguageModule(ilObject::_lookupType($this->obj->getId())); + + + if ($this->getTitleDescrOnlyMode() || $this->obj_trans->getContentActivated()) { + $ilToolbar->addButton( + $this->lng->txt("obj_add_languages"), + $this->ctrl->getLinkTarget($this, "addLanguages") + ); + } + + if ($this->getTitleDescrOnlyMode()) { + if (!$this->obj_trans->getContentActivated()) { + ilUtil::sendInfo($this->lng->txt("obj_multilang_title_descr_only")); + $ilToolbar->addButton( + $this->lng->txt("obj_activate_content_lang"), + $this->ctrl->getLinkTarget($this, "activateContentMultilinguality") + ); + } else { + $ilToolbar->addButton( + $this->lng->txt("obj_deactivate_content_lang"), + $this->ctrl->getLinkTarget($this, "confirmDeactivateContentMultiLang") + ); + } + } else { + if ($this->obj_trans->getContentActivated()) { + $ilToolbar->addButton( + $this->lng->txt("obj_deactivate_multilang"), + $this->ctrl->getLinkTarget($this, "confirmDeactivateContentMultiLang") + ); + } else { + $ilToolbar->addButton( + $this->lng->txt("obj_activate_multilang"), + $this->ctrl->getLinkTarget($this, "activateContentMultilinguality") + ); + return; + } + } + + include_once("./Services/Object/classes/class.ilObjectTranslation2TableGUI.php"); + $table = new ilObjectTranslation2TableGUI( + $this, + "listTranslations", + true, + "Translation", + $this->obj_trans->getMasterLanguage() + ); + 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->obj_trans->getLanguages(); + foreach ($data as $k => $v) { + $data[$k]["default"] = $v["lang_default"]; + $data[$k]["desc"] = $v["description"]; + $data[$k]["lang"] = $v["lang_code"]; + } + /* if($a_add) + { + $data["Fobject"][++$k]["title"] = ""; + }*/ + $table->setData($data); + } + $this->tpl->setContent($table->getHTML()); + } + + /** + * Save translations + */ + public function saveTranslations() + { + // default language set? + if (!isset($_POST["default"]) && $this->obj_trans->getMasterLanguage() == "") { + ilUtil::sendFailure($this->lng->txt("msg_no_default_language")); + $this->listTranslations(true); + return; + } + + // all languages set? + if (array_key_exists("", $_POST["lang"])) { + ilUtil::sendFailure($this->lng->txt("msg_no_language_selected")); + $this->listTranslations(true); + return; + } + + // no single language is selected more than once? + if (count(array_unique($_POST["lang"])) < count($_POST["lang"])) { + ilUtil::sendFailure($this->lng->txt("msg_multi_language_selected")); + $this->listTranslations(true); + return; + } + + // save the stuff + $this->obj_trans->setLanguages(array()); + + foreach ($_POST["title"] as $k => $v) { + // update object data if default + $is_default = ($_POST["default"] == $k); + + // ensure master language is set as default + if ($this->obj_trans->getMasterLanguage() != "") { + $is_default = ($this->obj_trans->getMasterLanguage() == $_POST["lang"][$k]); + } + if ($is_default) { + $this->obj->setTitle(ilUtil::stripSlashes($v)); + $this->obj->setDescription(ilUtil::stripSlashes($_POST["desc"][$k])); + } + + $this->obj_trans->addLanguage( + ilUtil::stripSlashes($_POST["lang"][$k]), + ilUtil::stripSlashes($v), + ilUtil::stripSlashes($_POST["desc"][$k]), + $is_default + ); + } + $this->obj_trans->save(); + if (method_exists($this->obj, "setObjectTranslation")) { + $this->obj->setObjectTranslation($this->obj_trans); + } + $this->obj->update(); + + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "listTranslations"); + } + + /** + * Remove translation + */ + public function deleteTranslations() + { + foreach ($_POST["title"] as $k => $v) { + if ($_POST["check"][$k]) { + // default translation cannot be deleted + if ($k != $_POST["default"]) { + unset($_POST["title"][$k]); + unset($_POST["desc"][$k]); + unset($_POST["lang"][$k]); + } else { + ilUtil::sendFailure($this->lng->txt("msg_no_default_language")); + $this->listTranslations(); + return; + } + } + } + $this->saveTranslations(); + } + + //// + //// Content translation + //// + + /** + * Activate multi language (-> master language selection) + */ + public function activateContentMultilinguality() + { + $tpl = $this->tpl; + $lng = $this->lng; + + ilUtil::sendInfo($lng->txt("obj_select_master_lang")); + + $form = $this->getMultiLangForm(); + $tpl->setContent($form->getHTML()); + } + + /** + * Get multi language form + */ + public function getMultiLangForm($a_add = false) + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + + // master language + if (!$a_add) { + include_once("./Services/MetaData/classes/class.ilMDLanguageItem.php"); + $options = ilMDLanguageItem::_getLanguages(); + $si = new ilSelectInputGUI($lng->txt("obj_master_lang"), "master_lang"); + $si->setOptions($options); + $si->setValue($ilUser->getLanguage()); + $form->addItem($si); + } + + // additional languages + if ($a_add) { + include_once("./Services/MetaData/classes/class.ilMDLanguageItem.php"); + $options = ilMDLanguageItem::_getLanguages(); + $options = array("" => $lng->txt("please_select")) + $options; + $si = new ilSelectInputGUI($lng->txt("obj_additional_langs"), "additional_langs"); + $si->setOptions($options); + $si->setMulti(true); + $form->addItem($si); + } + + if ($a_add) { + $form->setTitle($lng->txt("obj_add_languages")); + $form->addCommandButton("saveLanguages", $lng->txt("save")); + $form->addCommandButton("listTranslations", $lng->txt("cancel")); + } else { + if ($this->getTitleDescrOnlyMode()) { + $form->setTitle($lng->txt("obj_activate_content_lang")); + } else { + $form->setTitle($lng->txt("obj_activate_multilang")); + } + $form->addCommandButton("saveContentTranslationActivation", $lng->txt("save")); + $form->addCommandButton("listTranslations", $lng->txt("cancel")); + } + $form->setFormAction($ilCtrl->getFormAction($this)); + + return $form; + } + + /** + * Save content translation activation + */ + public function saveContentTranslationActivation() + { + $ilCtrl = $this->ctrl; + + // include_once("./Services/COPage/classes/class.ilPageMultiLang.php"); + + $form = $this->getMultiLangForm(); + if ($form->checkInput()) { + $ml = $form->getInput("master_lang"); + $this->obj_trans->setMasterLanguage($ml); + $this->obj_trans->addLanguage( + $ml, + $this->obj->getTitle(), + $this->obj->getDescription(), + true + ); + $this->obj_trans->setDefaultTitle($this->obj->getTitle()); + $this->obj_trans->setDefaultDescription($this->obj->getDescription()); + $this->obj_trans->save(); + } + + $ilCtrl->redirect($this, "listTranslations"); + } + + /** + * Confirm page translation creation + */ + public function confirmDeactivateContentMultiLang() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + if ($this->getTitleDescrOnlyMode()) { + $cgui->setHeaderText($lng->txt("obj_deactivate_content_transl_conf")); + } else { + $cgui->setHeaderText($lng->txt("obj_deactivate_multilang_conf")); + } + + $cgui->setCancel($lng->txt("cancel"), "listTranslations"); + $cgui->setConfirm($lng->txt("confirm"), "deactivateContentMultiLang"); + $tpl->setContent($cgui->getHTML()); + } + + /** + * Deactivate multilanguage + */ + public function deactivateContentMultiLang() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if (!$this->getTitleDescrOnlyMode()) { + $this->obj_trans->setMasterLanguage(""); + $this->obj_trans->setLanguages(array()); + $this->obj_trans->save(); + } + $this->obj_trans->deactivateContentTranslation(); + if ($this->getTitleDescrOnlyMode()) { + ilUtil::sendSuccess($lng->txt("obj_cont_transl_deactivated"), true); + } else { + ilUtil::sendSuccess($lng->txt("obj_multilang_deactivated"), true); + } + + + $ilCtrl->redirect($this, "listTranslations"); + } + + /** + * Add language + */ + public function addLanguages() + { + $tpl = $this->tpl; + + $form = $this->getMultiLangForm(true); + $tpl->setContent($form->getHTML()); + } + + /** + * Save languages + */ + public function saveLanguages() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + + $form = $this->getMultiLangForm(true); + if ($form->checkInput()) { + $ad = $form->getInput("additional_langs"); + if (is_array($ad)) { + $ml = $this->obj_trans->getMasterLanguage(); + foreach ($ad as $l) { + if ($l != $ml && $l != "") { + $this->obj_trans->addLanguage($l, false, "", ""); + } + } + } + $this->obj_trans->save(); + ilUtil::sendInfo($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "listTranslations"); + } + + ilUtil::sendFailure($this->lng->txt('err_check_input')); + $form->setValuesByPost(); + $tpl->setContent($form->getHTML()); + } + + /** + * Confirm remove languages + */ + public function confirmRemoveLanguages() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + $lng->loadLanguageModule("meta"); + + if (!is_array($_POST["lang"]) || count($_POST["lang"]) == 0) { + ilUtil::sendInfo($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "listTranslations"); + } else { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("obj_conf_delete_lang")); + $cgui->setCancel($lng->txt("cancel"), "listTranslations"); + $cgui->setConfirm($lng->txt("remove"), "removeLanguages"); + + foreach ($_POST["lang"] as $i) { + $cgui->addItem("lang[]", $i, $lng->txt("meta_l_" . $i)); + } + + $tpl->setContent($cgui->getHTML()); + } + } + + /** + * Remove languages + */ + public function removeLanguages() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if (is_array($_POST["lang"])) { + $langs = $this->obj_trans->getLanguages(); + foreach ($langs as $k => $l) { + if (in_array($l, $_POST["lang"])) { + $this->obj_trans->removeLanguage(); + } + } + $this->obj_trans->save(); + ilUtil::sendInfo($lng->txt("msg_obj_modified"), true); + } + $ilCtrl->redirect($this, "listTranslations"); + } } - -?> \ No newline at end of file diff --git a/Services/Object/classes/class.ilObjectTranslationTableGUI.php b/Services/Object/classes/class.ilObjectTranslationTableGUI.php index 6620b25590194663e2b3066090d0425f5ff5cf57..8904106e615bc756039abb37030afa242fff5c7c 100644 --- a/Services/Object/classes/class.ilObjectTranslationTableGUI.php +++ b/Services/Object/classes/class.ilObjectTranslationTableGUI.php @@ -13,105 +13,106 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilObjectTranslationTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_incl_desc = true, $a_base_cmd = "HeaderTitle") - { - global $DIC; + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_incl_desc = true, $a_base_cmd = "HeaderTitle") + { + 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(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->incl_desc = $a_incl_desc; - $this->base_cmd = $a_base_cmd; - - $this->setLimit(9999); - - $this->addColumn("", "", "1"); - $this->addColumn($this->lng->txt("language"), "", ""); - $this->addColumn($this->lng->txt("default"), "", ""); - $this->addColumn($this->lng->txt("title"), "", ""); - if ($a_incl_desc) - { - $this->addColumn($this->lng->txt("description"), "", ""); - } -// $this->addColumn($this->lng->txt("actions"), "", ""); - - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.obj_translation_row.html", "Services/Object"); - $this->disable("footer"); - $this->setEnableTitle(true); + $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); + $this->incl_desc = $a_incl_desc; + $this->base_cmd = $a_base_cmd; + + $this->setLimit(9999); + + $this->addColumn("", "", "1"); + $this->addColumn($this->lng->txt("language"), "", ""); + $this->addColumn($this->lng->txt("default"), "", ""); + $this->addColumn($this->lng->txt("title"), "", ""); + if ($a_incl_desc) { + $this->addColumn($this->lng->txt("description"), "", ""); + } + // $this->addColumn($this->lng->txt("actions"), "", ""); + + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.obj_translation_row.html", "Services/Object"); + $this->disable("footer"); + $this->setEnableTitle(true); - $this->nr = 0; - } - - /** - * Prepare output - */ - function prepareOutput() - { - $lng = $this->lng; + $this->nr = 0; + } + + /** + * Prepare output + */ + public function prepareOutput() + { + $lng = $this->lng; - $this->addMultiCommand("delete".$this->base_cmd."s", $lng->txt("remove")); - if ($this->dataExists()) - { - $this->addCommandButton("save".$this->base_cmd."s", $lng->txt("save")); - } - $this->addCommandButton("add".$this->base_cmd, $lng->txt("add")); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; + $this->addMultiCommand("delete" . $this->base_cmd . "s", $lng->txt("remove")); + if ($this->dataExists()) { + $this->addCommandButton("save" . $this->base_cmd . "s", $lng->txt("save")); + } + $this->addCommandButton("add" . $this->base_cmd, $lng->txt("add")); + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; - $this->nr++; - - if ($this->incl_desc) - { - $this->tpl->setCurrentBlock("desc_row"); - $this->tpl->setVariable("VAL_DESC", ilUtil::prepareFormOutput($a_set["desc"])); - $this->tpl->setVariable("DNR", $this->nr); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setVariable("NR", $this->nr); - - // lang selection - include_once('Services/MetaData/classes/class.ilMDLanguageItem.php'); - $languages = ilMDLanguageItem::_getLanguages(); - $this->tpl->setVariable("LANG_SELECT", - ilUtil::formSelect($a_set["lang"], "lang[".$this->nr."]", $languages, - false, true)); + $this->nr++; + + if ($this->incl_desc) { + $this->tpl->setCurrentBlock("desc_row"); + $this->tpl->setVariable("VAL_DESC", ilUtil::prepareFormOutput($a_set["desc"])); + $this->tpl->setVariable("DNR", $this->nr); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setVariable("NR", $this->nr); + + // lang selection + include_once('Services/MetaData/classes/class.ilMDLanguageItem.php'); + $languages = ilMDLanguageItem::_getLanguages(); + $this->tpl->setVariable( + "LANG_SELECT", + ilUtil::formSelect( + $a_set["lang"], + "lang[" . $this->nr . "]", + $languages, + false, + true + ) + ); - if ($a_set["default"]) - { - $this->tpl->setVariable("DEF_CHECKED", "checked=\"checked\""); - } - - $this->tpl->setVariable("VAL_TITLE", ilUtil::prepareFormOutput($a_set["title"])); - } + if ($a_set["default"]) { + $this->tpl->setVariable("DEF_CHECKED", "checked=\"checked\""); + } + $this->tpl->setVariable("VAL_TITLE", ilUtil::prepareFormOutput($a_set["title"])); + } } -?> diff --git a/Services/Object/classes/class.ilPasteIntoMultipleItemsExplorer.php b/Services/Object/classes/class.ilPasteIntoMultipleItemsExplorer.php index 9eb91ed1206cdc218c22c364dfabfd7c78205d27..4268935ccc9dfed080efd8d7e28c020f492792a3 100644 --- a/Services/Object/classes/class.ilPasteIntoMultipleItemsExplorer.php +++ b/Services/Object/classes/class.ilPasteIntoMultipleItemsExplorer.php @@ -11,349 +11,325 @@ require_once 'Services/Repository/classes/class.ilRepositoryExplorer.php'; */ class ilPasteIntoMultipleItemsExplorer extends ilRepositoryExplorer { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilErrorHandling - */ - protected $error; + /** + * @var ilErrorHandling + */ + protected $error; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - const SEL_TYPE_CHECK = 1; - const SEL_TYPE_RADIO = 2; - - public $root_id = 0; - public $output = ''; - public $ctrl = null; - - private $checked_items = array(); - private $post_var = ''; - private $form_items = array(); - private $form_item_permission = 'read'; - private $type = 0; - - /** - * Constructor - * @access public - * @param string $a_target scriptname - * @param string $a_session_variable session_variable - */ - public function __construct($a_type, $a_target, $a_session_variable) - { - global $DIC; + const SEL_TYPE_CHECK = 1; + const SEL_TYPE_RADIO = 2; + + public $root_id = 0; + public $output = ''; + public $ctrl = null; + + private $checked_items = array(); + private $post_var = ''; + private $form_items = array(); + private $form_item_permission = 'read'; + private $type = 0; + + /** + * Constructor + * @access public + * @param string $a_target scriptname + * @param string $a_session_variable session_variable + */ + public function __construct($a_type, $a_target, $a_session_variable) + { + global $DIC; - $this->lng = $DIC->language(); - $this->error = $DIC["ilErr"]; - $this->access = $DIC->access(); - $tree = $DIC->repositoryTree(); - $ilCtrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->error = $DIC["ilErr"]; + $this->access = $DIC->access(); + $tree = $DIC->repositoryTree(); + $ilCtrl = $DIC->ctrl(); - $this->setId("cont_paste_explorer"); - - $this->ctrl = $ilCtrl; - $this->type = $a_type; + $this->setId("cont_paste_explorer"); + + $this->ctrl = $ilCtrl; + $this->type = $a_type; - parent::__construct($a_target); - $this->tree = $tree; - $this->root_id = $this->tree->readRootId(); - $this->order_column = 'title'; - $this->setSessionExpandVariable($a_session_variable); - - // reset filter - $this->filter = array(); - - $this->addFilter('root'); - $this->addFilter('crs'); - $this->addFilter('grp'); - $this->addFilter('cat'); - $this->addFilter('fold'); - - $this->addFormItemForType('root'); - $this->addFormItemForType('crs'); - $this->addFormItemForType('grp'); - $this->addFormItemForType('cat'); - $this->addFormItemForType('fold'); - - $this->setFiltered(true); - $this->setFilterMode(IL_FM_POSITIVE); - } - - public function isClickable($a_type, $a_ref_id = 0, $a_obj_id = 0) - { - return false; - } - - public function addFormItemForType($type) - { - $this->form_items[$type] = true; - } - public function removeFormItemForType($type) - { - $this->form_items[$type] = false; - } - public function setCheckedItems($a_checked_items = array()) - { - $this->checked_items = $a_checked_items; - } - public function isItemChecked($a_id) - { - return in_array($a_id, $this->checked_items) ? true : false; - } - public function setPostVar($a_post_var) - { - $this->post_var = $a_post_var; - } - public function getPostVar() - { - return $this->post_var; - } - - /** - * Set required perission for form item visibility - * @param type $a_node_id - * @param type $a_type - * @return string - */ - public function setRequiredFormItemPermission($a_form_item_permission) - { - $this->form_item_permission = $a_form_item_permission; - } - - /** - * Get required permission - * @return string - */ - public function getRequiredFormItemPermission() - { - return $this->form_item_permission; - } - - public function buildFormItem($a_node_id, $a_type) - { - $access = $this->access; + parent::__construct($a_target); + $this->tree = $tree; + $this->root_id = $this->tree->readRootId(); + $this->order_column = 'title'; + $this->setSessionExpandVariable($a_session_variable); + + // reset filter + $this->filter = array(); + + $this->addFilter('root'); + $this->addFilter('crs'); + $this->addFilter('grp'); + $this->addFilter('cat'); + $this->addFilter('fold'); + + $this->addFormItemForType('root'); + $this->addFormItemForType('crs'); + $this->addFormItemForType('grp'); + $this->addFormItemForType('cat'); + $this->addFormItemForType('fold'); + + $this->setFiltered(true); + $this->setFilterMode(IL_FM_POSITIVE); + } + + public function isClickable($a_type, $a_ref_id = 0, $a_obj_id = 0) + { + return false; + } + + public function addFormItemForType($type) + { + $this->form_items[$type] = true; + } + public function removeFormItemForType($type) + { + $this->form_items[$type] = false; + } + public function setCheckedItems($a_checked_items = array()) + { + $this->checked_items = $a_checked_items; + } + public function isItemChecked($a_id) + { + return in_array($a_id, $this->checked_items) ? true : false; + } + public function setPostVar($a_post_var) + { + $this->post_var = $a_post_var; + } + public function getPostVar() + { + return $this->post_var; + } + + /** + * Set required perission for form item visibility + * @param type $a_node_id + * @param type $a_type + * @return string + */ + public function setRequiredFormItemPermission($a_form_item_permission) + { + $this->form_item_permission = $a_form_item_permission; + } + + /** + * Get required permission + * @return string + */ + public function getRequiredFormItemPermission() + { + return $this->form_item_permission; + } + + public function buildFormItem($a_node_id, $a_type) + { + $access = $this->access; - // permission check - if(!$access->checkAccess($this->getRequiredFormItemPermission(),'',$a_node_id)) - { - return ''; - } - - if( - !array_key_exists($a_type, $this->form_items) || - !$this->form_items[$a_type] - ) - { - return ''; - } - - $disabled = false; - if(is_array($_SESSION["clipboard"]["ref_ids"])) - { - $disabled = in_array($a_node_id, $_SESSION["clipboard"]["ref_ids"]); - } - else if((int)$_SESSION["clipboard"]["ref_ids"]) - { - $disabled = $a_node_id == $_SESSION["clipboard"]["ref_ids"]; - } - else if($_SESSION["clipboard"]["cmd"] == 'copy' && $a_node_id == $_SESSION["clipboard"]["parent"]) - { - $disabled = true; - } + // permission check + if (!$access->checkAccess($this->getRequiredFormItemPermission(), '', $a_node_id)) { + return ''; + } + + if ( + !array_key_exists($a_type, $this->form_items) || + !$this->form_items[$a_type] + ) { + return ''; + } + + $disabled = false; + if (is_array($_SESSION["clipboard"]["ref_ids"])) { + $disabled = in_array($a_node_id, $_SESSION["clipboard"]["ref_ids"]); + } elseif ((int) $_SESSION["clipboard"]["ref_ids"]) { + $disabled = $a_node_id == $_SESSION["clipboard"]["ref_ids"]; + } elseif ($_SESSION["clipboard"]["cmd"] == 'copy' && $a_node_id == $_SESSION["clipboard"]["parent"]) { + $disabled = true; + } - switch($this->type) - { - case self::SEL_TYPE_CHECK: - return ilUtil::formCheckbox((int)$this->isItemChecked($a_node_id), $this->post_var, $a_node_id, $disabled); - break; - - case self::SEL_TYPE_RADIO: - return ilUtil::formRadioButton((int)$this->isItemChecked($a_node_id), $this->post_var, $a_node_id, '', $disabled); - break; - } - } - - function formatObject($tpl, $a_node_id, $a_option, $a_obj_id = 0) - { - $lng = $this->lng; - $ilErr = $this->error; - - if (!isset($a_node_id) or !is_array($a_option)) - { - $ilErr->raiseError(get_class($this)."::formatObject(): Missing parameter or wrong datatype! ". - "node_id: ".$a_node_id." options:".var_dump($a_option), $ilErr->WARNING); - } + switch ($this->type) { + case self::SEL_TYPE_CHECK: + return ilUtil::formCheckbox((int) $this->isItemChecked($a_node_id), $this->post_var, $a_node_id, $disabled); + break; + + case self::SEL_TYPE_RADIO: + return ilUtil::formRadioButton((int) $this->isItemChecked($a_node_id), $this->post_var, $a_node_id, '', $disabled); + break; + } + } + + public function formatObject($tpl, $a_node_id, $a_option, $a_obj_id = 0) + { + $lng = $this->lng; + $ilErr = $this->error; + + if (!isset($a_node_id) or !is_array($a_option)) { + $ilErr->raiseError(get_class($this) . "::formatObject(): Missing parameter or wrong datatype! " . + "node_id: " . $a_node_id . " options:" . var_dump($a_option), $ilErr->WARNING); + } - $pic = false; - foreach ($a_option["tab"] as $picture) - { - if ($picture == 'plus') - { - $tpl->setCurrentBlock("expander"); - $tpl->setVariable("EXP_DESC", $lng->txt("expand")); - $target = $this->createTarget('+',$a_node_id); - $tpl->setVariable("LINK_NAME", $a_node_id); - $tpl->setVariable("LINK_TARGET_EXPANDER", $target); - $tpl->setVariable("IMGPATH", $this->getImage("browser/plus.png")); - $tpl->parseCurrentBlock(); - $pic = true; - } + $pic = false; + foreach ($a_option["tab"] as $picture) { + if ($picture == 'plus') { + $tpl->setCurrentBlock("expander"); + $tpl->setVariable("EXP_DESC", $lng->txt("expand")); + $target = $this->createTarget('+', $a_node_id); + $tpl->setVariable("LINK_NAME", $a_node_id); + $tpl->setVariable("LINK_TARGET_EXPANDER", $target); + $tpl->setVariable("IMGPATH", $this->getImage("browser/plus.png")); + $tpl->parseCurrentBlock(); + $pic = true; + } - if ($picture == 'minus' && $this->show_minus) - { - $tpl->setCurrentBlock("expander"); - $tpl->setVariable("EXP_DESC", $lng->txt("collapse")); - $target = $this->createTarget('-',$a_node_id); - $tpl->setVariable("LINK_NAME", $a_node_id); - $tpl->setVariable("LINK_TARGET_EXPANDER", $target); - $tpl->setVariable("IMGPATH", $this->getImage("browser/minus.png")); - $tpl->parseCurrentBlock(); - $pic = true; - } - } - - if (!$pic) - { - $tpl->setCurrentBlock("blank"); - $tpl->setVariable("BLANK_PATH", $this->getImage("browser/blank.png")); - $tpl->parseCurrentBlock(); - } + if ($picture == 'minus' && $this->show_minus) { + $tpl->setCurrentBlock("expander"); + $tpl->setVariable("EXP_DESC", $lng->txt("collapse")); + $target = $this->createTarget('-', $a_node_id); + $tpl->setVariable("LINK_NAME", $a_node_id); + $tpl->setVariable("LINK_TARGET_EXPANDER", $target); + $tpl->setVariable("IMGPATH", $this->getImage("browser/minus.png")); + $tpl->parseCurrentBlock(); + $pic = true; + } + } + + if (!$pic) { + $tpl->setCurrentBlock("blank"); + $tpl->setVariable("BLANK_PATH", $this->getImage("browser/blank.png")); + $tpl->parseCurrentBlock(); + } - if ($this->output_icons) - { - $tpl->setCurrentBlock("icon"); - - $path = ilObject::_getIcon($a_obj_id, "tiny", $a_option["type"]); - $tpl->setVariable("ICON_IMAGE", $path); - - $tpl->setVariable("TARGET_ID" , "iconid_".$a_node_id); - $this->iconList[] = "iconid_".$a_node_id; - $tpl->setVariable("TXT_ALT_IMG", $lng->txt($a_option["desc"])); - $tpl->parseCurrentBlock(); - } - - if(strlen($formItem = $this->buildFormItem($a_node_id, $a_option['type']))) - { - $tpl->setCurrentBlock('check'); - $tpl->setVariable('OBJ_CHECK', $formItem); - $tpl->parseCurrentBlock(); - } + if ($this->output_icons) { + $tpl->setCurrentBlock("icon"); + + $path = ilObject::_getIcon($a_obj_id, "tiny", $a_option["type"]); + $tpl->setVariable("ICON_IMAGE", $path); + + $tpl->setVariable("TARGET_ID", "iconid_" . $a_node_id); + $this->iconList[] = "iconid_" . $a_node_id; + $tpl->setVariable("TXT_ALT_IMG", $lng->txt($a_option["desc"])); + $tpl->parseCurrentBlock(); + } + + if (strlen($formItem = $this->buildFormItem($a_node_id, $a_option['type']))) { + $tpl->setCurrentBlock('check'); + $tpl->setVariable('OBJ_CHECK', $formItem); + $tpl->parseCurrentBlock(); + } - if ($this->isClickable($a_option["type"], $a_node_id,$a_obj_id)) // output link - { - $tpl->setCurrentBlock("link"); - //$target = (strpos($this->target, "?") === false) ? - // $this->target."?" : $this->target."&"; - //$tpl->setVariable("LINK_TARGET", $target.$this->target_get."=".$a_node_id.$this->params_get); - $tpl->setVariable("LINK_TARGET", $this->buildLinkTarget($a_node_id, $a_option["type"])); - - $style_class = $this->getNodeStyleClass($a_node_id, $a_option["type"]); - - if ($style_class != "") - { - $tpl->setVariable("A_CLASS", ' class="'.$style_class.'" ' ); - } + if ($this->isClickable($a_option["type"], $a_node_id, $a_obj_id)) { // output link + $tpl->setCurrentBlock("link"); + //$target = (strpos($this->target, "?") === false) ? + // $this->target."?" : $this->target."&"; + //$tpl->setVariable("LINK_TARGET", $target.$this->target_get."=".$a_node_id.$this->params_get); + $tpl->setVariable("LINK_TARGET", $this->buildLinkTarget($a_node_id, $a_option["type"])); + + $style_class = $this->getNodeStyleClass($a_node_id, $a_option["type"]); + + if ($style_class != "") { + $tpl->setVariable("A_CLASS", ' class="' . $style_class . '" '); + } - if (($onclick = $this->buildOnClick($a_node_id, $a_option["type"], $a_option["title"])) != "") - { - $tpl->setVariable("ONCLICK", "onClick=\"$onclick\""); - } + if (($onclick = $this->buildOnClick($a_node_id, $a_option["type"], $a_option["title"])) != "") { + $tpl->setVariable("ONCLICK", "onClick=\"$onclick\""); + } - $tpl->setVariable("LINK_NAME", $a_node_id); - $tpl->setVariable("TITLE", $this->buildTitle($a_option["title"], $a_node_id, $a_option["type"])); - $tpl->setVariable("DESC", ilUtil::shortenText( - $this->buildDescription($a_option["description"], $a_node_id, $a_option["type"]), $this->textwidth, true)); - $frame_target = $this->buildFrameTarget($a_option["type"], $a_node_id, $a_option["obj_id"]); - if ($frame_target != "") - { - $tpl->setVariable("TARGET", " target=\"".$frame_target."\""); - } - $tpl->parseCurrentBlock(); - } - else // output text only - { - $obj_title = $this->buildTitle($a_option["title"], $a_node_id, $a_option["type"]); - - // highlight current node - if($a_node_id == $this->highlighted) - { - $obj_title = "".$obj_title.""; - } - - $tpl->setCurrentBlock("text"); - $tpl->setVariable("OBJ_TITLE", $obj_title); - $tpl->setVariable("OBJ_DESC", ilUtil::shortenText( - $this->buildDescription($a_option["desc"], $a_node_id, $a_option["type"]), $this->textwidth, true)); - $tpl->parseCurrentBlock(); - } + $tpl->setVariable("LINK_NAME", $a_node_id); + $tpl->setVariable("TITLE", $this->buildTitle($a_option["title"], $a_node_id, $a_option["type"])); + $tpl->setVariable("DESC", ilUtil::shortenText( + $this->buildDescription($a_option["description"], $a_node_id, $a_option["type"]), + $this->textwidth, + true + )); + $frame_target = $this->buildFrameTarget($a_option["type"], $a_node_id, $a_option["obj_id"]); + if ($frame_target != "") { + $tpl->setVariable("TARGET", " target=\"" . $frame_target . "\""); + } + $tpl->parseCurrentBlock(); + } else { // output text only + $obj_title = $this->buildTitle($a_option["title"], $a_node_id, $a_option["type"]); + + // highlight current node + if ($a_node_id == $this->highlighted) { + $obj_title = "" . $obj_title . ""; + } + + $tpl->setCurrentBlock("text"); + $tpl->setVariable("OBJ_TITLE", $obj_title); + $tpl->setVariable("OBJ_DESC", ilUtil::shortenText( + $this->buildDescription($a_option["desc"], $a_node_id, $a_option["type"]), + $this->textwidth, + true + )); + $tpl->parseCurrentBlock(); + } - $tpl->setCurrentBlock("list_item"); - $tpl->parseCurrentBlock(); - $tpl->touchBlock("element"); - } - - /* - * overwritten method from base class - * @access public - * @param integer obj_id - * @param integer array options - * @return string - */ - function formatHeader($tpl, $a_obj_id,$a_option) - { - $lng = $this->lng; - $tree = $this->tree; + $tpl->setCurrentBlock("list_item"); + $tpl->parseCurrentBlock(); + $tpl->touchBlock("element"); + } + + /* + * overwritten method from base class + * @access public + * @param integer obj_id + * @param integer array options + * @return string + */ + public function formatHeader($tpl, $a_obj_id, $a_option) + { + $lng = $this->lng; + $tree = $this->tree; - // custom icons - $path = ilObject::_getIcon($a_obj_id, "tiny", "root"); - + // custom icons + $path = ilObject::_getIcon($a_obj_id, "tiny", "root"); + - $tpl->setCurrentBlock("icon"); - $nd = $tree->getNodeData(ROOT_FOLDER_ID); - $title = $nd["title"]; - if ($title == "ILIAS") - { - $title = $lng->txt("repository"); - } + $tpl->setCurrentBlock("icon"); + $nd = $tree->getNodeData(ROOT_FOLDER_ID); + $title = $nd["title"]; + if ($title == "ILIAS") { + $title = $lng->txt("repository"); + } - $tpl->setVariable("ICON_IMAGE", $path); - $tpl->setVariable("TXT_ALT_IMG", $title); - $tpl->parseCurrentBlock(); + $tpl->setVariable("ICON_IMAGE", $path); + $tpl->setVariable("TXT_ALT_IMG", $title); + $tpl->parseCurrentBlock(); - if(strlen($formItem = $this->buildFormItem($a_obj_id, $a_option['type']))) - { - $tpl->setCurrentBlock('check'); - $tpl->setVariable('OBJ_CHECK', $formItem); - $tpl->parseCurrentBlock(); - } - - $tpl->setVariable('OBJ_TITLE', $title); - } - - function showChilds($a_ref_id,$a_obj_id = 0) - { - $ilAccess = $this->access; + if (strlen($formItem = $this->buildFormItem($a_obj_id, $a_option['type']))) { + $tpl->setCurrentBlock('check'); + $tpl->setVariable('OBJ_CHECK', $formItem); + $tpl->parseCurrentBlock(); + } + + $tpl->setVariable('OBJ_TITLE', $title); + } + + public function showChilds($a_ref_id, $a_obj_id = 0) + { + $ilAccess = $this->access; - if ($a_ref_id == 0) - { - return true; - } - // #11778 - ilAccessHandler::doConditionCheck() - if ($ilAccess->checkAccess("read", "", $a_ref_id)) - { - return true; - } - else - { - return false; - } - } + if ($a_ref_id == 0) { + return true; + } + // #11778 - ilAccessHandler::doConditionCheck() + if ($ilAccess->checkAccess("read", "", $a_ref_id)) { + return true; + } else { + return false; + } + } } - -?> \ No newline at end of file diff --git a/Services/Object/classes/class.ilSubItemListGUI.php b/Services/Object/classes/class.ilSubItemListGUI.php index 1583b31eebd48cd1b49fc187399c0e279627b138..89dcdfb8115be5da3ba8d12454758c4d6b323750 100644 --- a/Services/Object/classes/class.ilSubItemListGUI.php +++ b/Services/Object/classes/class.ilSubItemListGUI.php @@ -1,272 +1,263 @@ * @version $Id$ -* +* * * @ingroup ServicesObject */ abstract class ilSubItemListGUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - protected static $MAX_SUBITEMS = 5; - - protected $cmdClass = null; + protected static $MAX_SUBITEMS = 5; + + protected $cmdClass = null; - protected $tpl; - private $highlighter = null; - - private static $details = array(); - - private $subitem_ids = array(); - private $item_list_gui; - private $ref_id; - private $obj_id; - private $type; - - /** - * Constructor - * @param - * @return - */ - public function __construct($a_cmd_class) - { - global $DIC; + protected $tpl; + private $highlighter = null; + + private static $details = array(); + + private $subitem_ids = array(); + private $item_list_gui; + private $ref_id; + private $obj_id; + private $type; + + /** + * Constructor + * @param + * @return + */ + public function __construct($a_cmd_class) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - - $this->cmdClass = $a_cmd_class; - self::$MAX_SUBITEMS = ilSearchSettings::getInstance()->getMaxSubitems(); - } - - /** - * set show details. - * Show all subitem links for a specific object - * As long as static::setShowDetails is not possible this method is final - * - * @return - * @param int $a_obj_id object id - * @static - */ - public static final function setShowDetails($a_obj_id) - { - $_SESSION['lucene_search']['details'][$a_obj_id] = true; - } - - /** - * reset details - * As long as static::resetDetails is not possible this method is final - * - * @return - * @static - */ - public static final function resetDetails() - { - $_SESSION['lucene_search']['details'] = array(); - } - - /** - * enabled show details - * As long as static::enableDetails is not possible this method is final - * - * @param int $a_obj_id object id - * @return bool - * @static - */ - public static final function enabledDetails($a_obj_id) - { - return isset($_SESSION['lucene_search']['details'][$a_obj_id]) and $_SESSION['lucene_search']['details'][$a_obj_id]; - } - - /** - * get cmd class - * @return - */ - public function getCmdClass() - { - return $this->cmdClass; - } - + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + + $this->cmdClass = $a_cmd_class; + self::$MAX_SUBITEMS = ilSearchSettings::getInstance()->getMaxSubitems(); + } + + /** + * set show details. + * Show all subitem links for a specific object + * As long as static::setShowDetails is not possible this method is final + * + * @return + * @param int $a_obj_id object id + * @static + */ + final public static function setShowDetails($a_obj_id) + { + $_SESSION['lucene_search']['details'][$a_obj_id] = true; + } + + /** + * reset details + * As long as static::resetDetails is not possible this method is final + * + * @return + * @static + */ + final public static function resetDetails() + { + $_SESSION['lucene_search']['details'] = array(); + } + + /** + * enabled show details + * As long as static::enableDetails is not possible this method is final + * + * @param int $a_obj_id object id + * @return bool + * @static + */ + final public static function enabledDetails($a_obj_id) + { + return isset($_SESSION['lucene_search']['details'][$a_obj_id]) and $_SESSION['lucene_search']['details'][$a_obj_id]; + } + + /** + * get cmd class + * @return + */ + public function getCmdClass() + { + return $this->cmdClass; + } + - /** - * set highlighter - * @param - * @return - */ - public function setHighlighter($a_highlighter) - { - $this->highlighter = $a_highlighter; - } - - /** - * get highlighter - * @param - * @return - */ - public function getHighlighter() - { - return $this->highlighter; - } - - /** - * get ref id - * @return - */ - public function getRefId() - { - return $this->ref_id; - } - - /** - * get obj id - * @return - */ - public function getObjId() - { - return $this->obj_id; - } + /** + * set highlighter + * @param + * @return + */ + public function setHighlighter($a_highlighter) + { + $this->highlighter = $a_highlighter; + } + + /** + * get highlighter + * @param + * @return + */ + public function getHighlighter() + { + return $this->highlighter; + } + + /** + * get ref id + * @return + */ + public function getRefId() + { + return $this->ref_id; + } + + /** + * get obj id + * @return + */ + public function getObjId() + { + return $this->obj_id; + } - /** - * get type - * @return - */ - public function getType() - { - return $this->type; - } - - /** - * get sub item ids - * @param bool $a_limited - * @return - */ - public function getSubItemIds($a_limited = false) - { - if($a_limited and !self::enabledDetails($this->getObjId())) - { - return array_slice($this->subitem_ids,0,self::$MAX_SUBITEMS); - } - - return $this->subitem_ids; - } - - /** - * get item list gui - * @return - */ - public function getItemListGUI() - { - return $this->item_list_gui; - } + /** + * get type + * @return + */ + public function getType() + { + return $this->type; + } + + /** + * get sub item ids + * @param bool $a_limited + * @return + */ + public function getSubItemIds($a_limited = false) + { + if ($a_limited and !self::enabledDetails($this->getObjId())) { + return array_slice($this->subitem_ids, 0, self::$MAX_SUBITEMS); + } + + return $this->subitem_ids; + } + + /** + * get item list gui + * @return + */ + public function getItemListGUI() + { + return $this->item_list_gui; + } - /** - * init - * @param - * @return - */ - public function init($item_list_gui,$a_ref_id,$a_subitem_ids) - { - $this->tpl = new ilTemplate('tpl.subitem_list.html',true,true,'Services/Object'); - $this->item_list_gui = $item_list_gui; - $this->ref_id = $a_ref_id; - $this->obj_id = ilObject::_lookupObjId($this->getRefId()); - $this->type = ilObject::_lookupType($this->getObjId()); - - $this->subitem_ids = $a_subitem_ids; - } - - /** - * show details link - * @return - */ - protected function showDetailsLink() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if(count($this->getSubItemIds()) <= self::$MAX_SUBITEMS) - { - return; - } - if(self::enabledDetails($this->getObjId())) - { - return; - } + /** + * init + * @param + * @return + */ + public function init($item_list_gui, $a_ref_id, $a_subitem_ids) + { + $this->tpl = new ilTemplate('tpl.subitem_list.html', true, true, 'Services/Object'); + $this->item_list_gui = $item_list_gui; + $this->ref_id = $a_ref_id; + $this->obj_id = ilObject::_lookupObjId($this->getRefId()); + $this->type = ilObject::_lookupType($this->getObjId()); + + $this->subitem_ids = $a_subitem_ids; + } + + /** + * show details link + * @return + */ + protected function showDetailsLink() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if (count($this->getSubItemIds()) <= self::$MAX_SUBITEMS) { + return; + } + if (self::enabledDetails($this->getObjId())) { + return; + } - $additional = count($this->getSubItemIds()) - self::$MAX_SUBITEMS; - - $ilCtrl->setParameterByClass(get_class($this->getCmdClass()), 'details', (int) $this->getObjId()); - $link = $ilCtrl->getLinkTargetByClass(get_class($this->getCmdClass()),''); - $ilCtrl->clearParametersByClass(get_class($this->getCmdClass())); - - $this->tpl->setCurrentBlock('choose_details'); - $this->tpl->setVariable('LUC_DETAILS_LINK',$link); - $this->tpl->setVariable('LUC_NUM_HITS',sprintf($lng->txt('lucene_more_hits_link'),$additional)); - $this->tpl->parseCurrentBlock(); - - - } - - // begin-patch mime_filter - protected function parseRelevance($sub_item) - { - if(!ilSearchSettings::getInstance()->isSubRelevanceVisible() || - !ilSearchSettings::getInstance()->enabledLucene()) - { - return ''; - } - - $relevance = $this->getHighlighter()->getRelevance($this->getObjId(),$sub_item); - - //$this->tpl->addBlockFile('SUB_REL','sub_rel','tpl.lucene_sub_relevance.html','Services/Search'); - - include_once "Services/UIComponent/ProgressBar/classes/class.ilProgressBar.php"; - $pbar = ilProgressBar::getInstance(); - $pbar->setCurrent($relevance); - - $this->tpl->setVariable('REL_PBAR', $pbar->render()); - } - // end-patch mime_filter - - abstract public function getHTML(); - - + $additional = count($this->getSubItemIds()) - self::$MAX_SUBITEMS; + + $ilCtrl->setParameterByClass(get_class($this->getCmdClass()), 'details', (int) $this->getObjId()); + $link = $ilCtrl->getLinkTargetByClass(get_class($this->getCmdClass()), ''); + $ilCtrl->clearParametersByClass(get_class($this->getCmdClass())); + + $this->tpl->setCurrentBlock('choose_details'); + $this->tpl->setVariable('LUC_DETAILS_LINK', $link); + $this->tpl->setVariable('LUC_NUM_HITS', sprintf($lng->txt('lucene_more_hits_link'), $additional)); + $this->tpl->parseCurrentBlock(); + } + + // begin-patch mime_filter + protected function parseRelevance($sub_item) + { + if (!ilSearchSettings::getInstance()->isSubRelevanceVisible() || + !ilSearchSettings::getInstance()->enabledLucene()) { + return ''; + } + + $relevance = $this->getHighlighter()->getRelevance($this->getObjId(), $sub_item); + + //$this->tpl->addBlockFile('SUB_REL','sub_rel','tpl.lucene_sub_relevance.html','Services/Search'); + + include_once "Services/UIComponent/ProgressBar/classes/class.ilProgressBar.php"; + $pbar = ilProgressBar::getInstance(); + $pbar->setCurrent($relevance); + + $this->tpl->setVariable('REL_PBAR', $pbar->render()); + } + // end-patch mime_filter + + abstract public function getHTML(); } -?> \ No newline at end of file diff --git a/Services/Object/exceptions/class.ilObjectException.php b/Services/Object/exceptions/class.ilObjectException.php index ed481e023854f7f26ef670e824999be59f7de11c..1433ebaedf08e4cff11041c9f338769066a30763 100644 --- a/Services/Object/exceptions/class.ilObjectException.php +++ b/Services/Object/exceptions/class.ilObjectException.php @@ -1,27 +1,26 @@ - * @version $Id$ - * + * @version $Id$ + * */ class ilObjectException extends ilException { - /** - * Constructor - * - * A message is not optional as in build in class Exception - * - * @param string $a_message message - */ - public function __construct($a_message) - { - parent::__construct($a_message); - } + /** + * Constructor + * + * A message is not optional as in build in class Exception + * + * @param string $a_message message + */ + public function __construct($a_message) + { + parent::__construct($a_message); + } } -?> diff --git a/Services/Object/exceptions/class.ilObjectNotFoundException.php b/Services/Object/exceptions/class.ilObjectNotFoundException.php index 93dd200454b712dfea579448d482379244c08d75..6cebe8328622d3ebb7d306d452ad8106454df943 100644 --- a/Services/Object/exceptions/class.ilObjectNotFoundException.php +++ b/Services/Object/exceptions/class.ilObjectNotFoundException.php @@ -1,26 +1,25 @@ - * @version $Id$ + * @version $Id$ */ class ilObjectNotFoundException extends ilObjectException { - /** - * Constructor - * - * A message is not optional as in build in class Exception - * - * @param string $a_message message - */ - public function __construct($a_message) - { - parent::__construct($a_message); - } + /** + * Constructor + * + * A message is not optional as in build in class Exception + * + * @param string $a_message message + */ + public function __construct($a_message) + { + parent::__construct($a_message); + } } -?> diff --git a/Services/Object/exceptions/class.ilObjectTypeMismatchException.php b/Services/Object/exceptions/class.ilObjectTypeMismatchException.php index 777908b1ed3901e676dbb68bb438bdfc131eb8c8..dc2222a41619e3704ccc344a82b387c2c4bcfb81 100644 --- a/Services/Object/exceptions/class.ilObjectTypeMismatchException.php +++ b/Services/Object/exceptions/class.ilObjectTypeMismatchException.php @@ -1,26 +1,25 @@ - * @version $Id$ + * @version $Id$ */ class ilObjectTypeMismatchException extends ilObjectException { - /** - * Constructor - * - * A message is not optional as in build in class Exception - * - * @param string $a_message message - */ - public function __construct($a_message) - { - parent::__construct($a_message); - } + /** + * Constructor + * + * A message is not optional as in build in class Exception + * + * @param string $a_message message + */ + public function __construct($a_message) + { + parent::__construct($a_message); + } } -?> diff --git a/Services/Object/test/ilObjectDefinitionTest.php b/Services/Object/test/ilObjectDefinitionTest.php index 43d458eb74d3d13dc11a82002244b0aa6d240274..e4979c955332df04c6831e46d8020f23e6af31c5 100644 --- a/Services/Object/test/ilObjectDefinitionTest.php +++ b/Services/Object/test/ilObjectDefinitionTest.php @@ -2,32 +2,33 @@ /* Copyright (c) 1998-2009 ILIAS open source, Extended GPL, see docs/LICENSE */ /** - * @group needsInstalledILIAS + * @group needsInstalledILIAS */ class ilObjectDefinitionTest extends PHPUnit_Framework_TestCase { - protected $backupGlobals = FALSE; + protected $backupGlobals = false; - protected function setUp() - { - include_once("./Services/PHPUnit/classes/class.ilUnitUtil.php"); - ilUnitUtil::performInitialisation(); - } + protected function setUp() + { + include_once("./Services/PHPUnit/classes/class.ilUnitUtil.php"); + ilUnitUtil::performInitialisation(); + } - /** - * @group IL_Init - */ - public function testObjDefinitionReader() - { - - include_once("./setup/classes/class.ilObjDefReader.php"); - $def_reader = new ilObjDefReader("./Services/Object/test/testmodule.xml", - "DefinitionTest", "Modules"); - - $def_reader->deleteObjectDefinition("xx1"); - $def_reader->startParsing(); - - $this->assertEquals("", $result); - } + /** + * @group IL_Init + */ + public function testObjDefinitionReader() + { + include_once("./setup/classes/class.ilObjDefReader.php"); + $def_reader = new ilObjDefReader( + "./Services/Object/test/testmodule.xml", + "DefinitionTest", + "Modules" + ); + + $def_reader->deleteObjectDefinition("xx1"); + $def_reader->startParsing(); + + $this->assertEquals("", $result); + } } -?> diff --git a/Services/Object/test/ilObjectTest.php b/Services/Object/test/ilObjectTest.php index 12c3e1d68f87fcf32830ad47e1b0d1cee507a346..fb5fc5f499f5a9746d60c63bb6279ef427bbbf7c 100644 --- a/Services/Object/test/ilObjectTest.php +++ b/Services/Object/test/ilObjectTest.php @@ -5,281 +5,242 @@ */ class ilObjectTest extends PHPUnit_Framework_TestCase { - protected $backupGlobals = FALSE; + protected $backupGlobals = false; - protected function setUp() - { - include_once("./Services/PHPUnit/classes/class.ilUnitUtil.php"); - ilUnitUtil::performInitialisation(); - } + protected function setUp() + { + include_once("./Services/PHPUnit/classes/class.ilUnitUtil.php"); + ilUnitUtil::performInitialisation(); + } - /** - * @group IL_Init - */ - public function testCreationDeletion() - { - $obj = new ilObject(); - $obj->setType("xxx"); - $obj->create(); - $id = $obj->getId(); - - $obj2 = new ilObject(); - $obj2->setType("xxx"); - $obj2->create(); - $id2 = $obj2->getId(); - - if ($id2 == ($id + 1)) - { - $value.= "create1-"; - } - - if (ilObject::_exists($id)) - { - $value.= "create2-"; - } - - $obj->delete(); - $obj2->delete(); - - if (!ilObject::_exists($id)) - { - $value.= "create3-"; - } + /** + * @group IL_Init + */ + public function testCreationDeletion() + { + $obj = new ilObject(); + $obj->setType("xxx"); + $obj->create(); + $id = $obj->getId(); + + $obj2 = new ilObject(); + $obj2->setType("xxx"); + $obj2->create(); + $id2 = $obj2->getId(); + + if ($id2 == ($id + 1)) { + $value.= "create1-"; + } + + if (ilObject::_exists($id)) { + $value.= "create2-"; + } + + $obj->delete(); + $obj2->delete(); + + if (!ilObject::_exists($id)) { + $value.= "create3-"; + } - - $this->assertEquals("create1-create2-create3-", $value); - } + + $this->assertEquals("create1-create2-create3-", $value); + } - /** - * @group IL_Init - */ - public function testSetGetLookup() - { - global $DIC; - $ilUser = $DIC->user(); + /** + * @group IL_Init + */ + public function testSetGetLookup() + { + global $DIC; + $ilUser = $DIC->user(); - $obj = new ilObject(); - $obj->setType(""); // otherwise type check will fail - $obj->setTitle("TestObject"); - $obj->setDescription("TestDescription"); - $obj->setImportId("imp_44"); - $obj->create(); - $obj->createReference(); - $id = $obj->getId(); - $ref_id = $obj->getRefId(); - $obj = new ilObject($id, false); + $obj = new ilObject(); + $obj->setType(""); // otherwise type check will fail + $obj->setTitle("TestObject"); + $obj->setDescription("TestDescription"); + $obj->setImportId("imp_44"); + $obj->create(); + $obj->createReference(); + $id = $obj->getId(); + $ref_id = $obj->getRefId(); + $obj = new ilObject($id, false); - if ($obj->getType() == "") - { - $value.= "sg1-"; - } - if ($obj->getTitle() == "TestObject") - { - $value.= "sg2-"; - } - if ($obj->getDescription() == "TestDescription") - { - $value.= "sg3-"; - } - if ($obj->getImportId() == "imp_44") - { - $value.= "sg4-"; - } - if ($obj->getOwner() == $ilUser->getId()) - { - $value.= "sg5-"; - } - - $obj = new ilObject($ref_id); - if ($obj->getTitle() == "TestObject") - { - $value.= "sg6-"; - } - - if ($obj->getCreateDate() == ($lu = $obj->getLastUpdateDate())) - { - $value.= "sg7-"; - } - $obj->setTitle("TestObject2"); - sleep(2); // we want a different date here... - $obj->update(); - - $obj = new ilObject($ref_id); - if ($lu != ($lu2 = $obj->getLastUpdateDate())) - { - $value.= "up1-"; - } - if ($obj->getTitle() == "TestObject2") - { - $value.= "up2-"; - } + if ($obj->getType() == "") { + $value.= "sg1-"; + } + if ($obj->getTitle() == "TestObject") { + $value.= "sg2-"; + } + if ($obj->getDescription() == "TestDescription") { + $value.= "sg3-"; + } + if ($obj->getImportId() == "imp_44") { + $value.= "sg4-"; + } + if ($obj->getOwner() == $ilUser->getId()) { + $value.= "sg5-"; + } + + $obj = new ilObject($ref_id); + if ($obj->getTitle() == "TestObject") { + $value.= "sg6-"; + } + + if ($obj->getCreateDate() == ($lu = $obj->getLastUpdateDate())) { + $value.= "sg7-"; + } + $obj->setTitle("TestObject2"); + sleep(2); // we want a different date here... + $obj->update(); + + $obj = new ilObject($ref_id); + if ($lu != ($lu2 = $obj->getLastUpdateDate())) { + $value.= "up1-"; + } + if ($obj->getTitle() == "TestObject2") { + $value.= "up2-"; + } - if ($id == ilObject::_lookupObjIdByImportId("imp_44")) - { - $value.= "lu1-"; - } - - if ($ilUser->getFullname() == ilObject::_lookupOwnerName(ilObject::_lookupOwner($id))) - { - $value.= "lu2-"; - } - - if (ilObject::_lookupTitle($id) == "TestObject2") - { - $value.= "lu3-"; - } - if (ilObject::_lookupDescription($id) == "TestDescription") - { - $value.= "lu4-"; - } - if (ilObject::_lookupLastUpdate($id) == $lu2) - { - $value.= "lu5-"; - } - if (ilObject::_lookupObjId($ref_id) == $id) - { - $value.= "lu6-"; - } - if (ilObject::_lookupType($id) == "") - { - $value.= "lu7-"; - } - if (ilObject::_lookupObjectId($ref_id) == $id) - { - $value.= "lu8-"; - } - $ar = ilObject::_getAllReferences($id); - if (is_array($ar) && count($ar) == 1 && $ar[$ref_id] == $ref_id) - { - $value.= "lu9-"; - } - - $ids = ilObject::_getIdsForTitle("TestObject2"); - foreach ($ids as $i) - { - if ($i == $id) - { - $value.= "lu10-"; - } - } + if ($id == ilObject::_lookupObjIdByImportId("imp_44")) { + $value.= "lu1-"; + } + + if ($ilUser->getFullname() == ilObject::_lookupOwnerName(ilObject::_lookupOwner($id))) { + $value.= "lu2-"; + } + + if (ilObject::_lookupTitle($id) == "TestObject2") { + $value.= "lu3-"; + } + if (ilObject::_lookupDescription($id) == "TestDescription") { + $value.= "lu4-"; + } + if (ilObject::_lookupLastUpdate($id) == $lu2) { + $value.= "lu5-"; + } + if (ilObject::_lookupObjId($ref_id) == $id) { + $value.= "lu6-"; + } + if (ilObject::_lookupType($id) == "") { + $value.= "lu7-"; + } + if (ilObject::_lookupObjectId($ref_id) == $id) { + $value.= "lu8-"; + } + $ar = ilObject::_getAllReferences($id); + if (is_array($ar) && count($ar) == 1 && $ar[$ref_id] == $ref_id) { + $value.= "lu9-"; + } + + $ids = ilObject::_getIdsForTitle("TestObject2"); + foreach ($ids as $i) { + if ($i == $id) { + $value.= "lu10-"; + } + } - $obs = ilObject::_getObjectsByType("usr"); - foreach ($obs as $ob) - { - if ($ob["obj_id"] == $ilUser->getId()) - { - $value.= "lu11-"; - } - } - - $d1 = ilObject::_lookupDeletedDate($ref_id); - ilObject::_setDeletedDate($ref_id); - $d2 = ilObject::_lookupDeletedDate($ref_id); - ilObject::_resetDeletedDate($ref_id); - $d3 = ilObject::_lookupDeletedDate($ref_id); - if ($d1 != $d2 && $d1 == $d3 && $d3 == null) - { - $value.= "dd1-"; - } - - $obj->delete(); - - $this->assertEquals("sg1-sg2-sg3-sg4-sg5-sg6-sg7-up1-up2-". - "lu1-lu2-lu3-lu4-lu5-lu6-lu7-lu8-lu9-lu10-lu11-dd1-", $value); - } + $obs = ilObject::_getObjectsByType("usr"); + foreach ($obs as $ob) { + if ($ob["obj_id"] == $ilUser->getId()) { + $value.= "lu11-"; + } + } + + $d1 = ilObject::_lookupDeletedDate($ref_id); + ilObject::_setDeletedDate($ref_id); + $d2 = ilObject::_lookupDeletedDate($ref_id); + ilObject::_resetDeletedDate($ref_id); + $d3 = ilObject::_lookupDeletedDate($ref_id); + if ($d1 != $d2 && $d1 == $d3 && $d3 == null) { + $value.= "dd1-"; + } + + $obj->delete(); + + $this->assertEquals("sg1-sg2-sg3-sg4-sg5-sg6-sg7-up1-up2-" . + "lu1-lu2-lu3-lu4-lu5-lu6-lu7-lu8-lu9-lu10-lu11-dd1-", $value); + } - /** - * @group IL_Init - */ - public function testTreeTrash() - { - global $DIC; - $tree = $DIC->repositoryTree(); - - $obj = new ilObject(); - $obj->setType("xxx"); - $obj->setTitle("TestObject"); - $obj->setDescription("TestDescription"); - $obj->setImportId("imp_44"); - $obj->create(); - $obj->createReference(); - $id = $obj->getId(); - $ref_id = $obj->getRefId(); - $obj = new ilObject($ref_id); - - $obj->putInTree(ROOT_FOLDER_ID); - $obj->setPermissions(ROOT_FOLDER_ID); - if ($tree->isInTree($ref_id)) - { - $value.= "tree1-"; - } - if (ilObject::_hasUntrashedReference($id)) - { - $value.= "tree2-"; - } - - // isSaved() uses internal cache! - $tree->useCache(false); - - $tree->saveSubTree($ref_id, true); - if ($tree->isDeleted($ref_id)) - { - $value.= "tree3-"; - } - if ($tree->isSaved($ref_id)) - { - $value.= "tree4-"; - } - if (ilObject::_isInTrash($ref_id)) - { - $value.= "tree5-"; - } - if (!ilObject::_hasUntrashedReference($id)) - { - $value.= "tree6-"; - } - - $saved_tree = new ilTree(-(int)$ref_id); - $node_data = $saved_tree->getNodeData($ref_id); - $saved_tree->deleteTree($node_data); + /** + * @group IL_Init + */ + public function testTreeTrash() + { + global $DIC; + $tree = $DIC->repositoryTree(); + + $obj = new ilObject(); + $obj->setType("xxx"); + $obj->setTitle("TestObject"); + $obj->setDescription("TestDescription"); + $obj->setImportId("imp_44"); + $obj->create(); + $obj->createReference(); + $id = $obj->getId(); + $ref_id = $obj->getRefId(); + $obj = new ilObject($ref_id); + + $obj->putInTree(ROOT_FOLDER_ID); + $obj->setPermissions(ROOT_FOLDER_ID); + if ($tree->isInTree($ref_id)) { + $value.= "tree1-"; + } + if (ilObject::_hasUntrashedReference($id)) { + $value.= "tree2-"; + } + + // isSaved() uses internal cache! + $tree->useCache(false); + + $tree->saveSubTree($ref_id, true); + if ($tree->isDeleted($ref_id)) { + $value.= "tree3-"; + } + if ($tree->isSaved($ref_id)) { + $value.= "tree4-"; + } + if (ilObject::_isInTrash($ref_id)) { + $value.= "tree5-"; + } + if (!ilObject::_hasUntrashedReference($id)) { + $value.= "tree6-"; + } + + $saved_tree = new ilTree(-(int) $ref_id); + $node_data = $saved_tree->getNodeData($ref_id); + $saved_tree->deleteTree($node_data); - if (!ilObject::_isInTrash($ref_id)) - { - $value.= "tree7-"; - } - - $obs = ilUtil::_getObjectsByOperations("cat","read"); - foreach ($obs as $ob) - { - if (ilObject::_lookupType(ilObject::_lookupObjId($ob)) != "cat") - { - $value.= "nocat-"; - } - } + if (!ilObject::_isInTrash($ref_id)) { + $value.= "tree7-"; + } + + $obs = ilUtil::_getObjectsByOperations("cat", "read"); + foreach ($obs as $ob) { + if (ilObject::_lookupType(ilObject::_lookupObjId($ob)) != "cat") { + $value.= "nocat-"; + } + } - $obj->delete(); - - $this->assertEquals("tree1-tree2-tree3-tree4-tree5-tree6-tree7-", $value); - - } - - /** - * test object reference queries - * @group IL_Init - */ - public function testObjectReference() - { - include_once './Services/Object/classes/class.ilObject.php'; - - $ref_ids = ilObject::_getAllReferences(1); - $bool = ilObject::_setDeletedDate(1); - $bool = ilObject::_resetDeletedDate(1); - $date = ilObject::_lookupDeletedDate(1); - - $this->assertEquals($date, null); - - - } + $obj->delete(); + + $this->assertEquals("tree1-tree2-tree3-tree4-tree5-tree6-tree7-", $value); + } + + /** + * test object reference queries + * @group IL_Init + */ + public function testObjectReference() + { + include_once './Services/Object/classes/class.ilObject.php'; + + $ref_ids = ilObject::_getAllReferences(1); + $bool = ilObject::_setDeletedDate(1); + $bool = ilObject::_resetDeletedDate(1); + $date = ilObject::_lookupDeletedDate(1); + + $this->assertEquals($date, null); + } } -?> diff --git a/Services/Object/test/ilServicesObjectSuite.php b/Services/Object/test/ilServicesObjectSuite.php index 2f34e5d33618f28d0089ac76a42d9718d7b4d2a9..989cab7808e101b851fa3b3f81edbc200bab7c5e 100644 --- a/Services/Object/test/ilServicesObjectSuite.php +++ b/Services/Object/test/ilServicesObjectSuite.php @@ -5,15 +5,14 @@ class ilServicesObjectSuite extends PHPUnit_Framework_TestSuite { public static function suite() { - $suite = new ilServicesObjectSuite(); - - include_once("./Services/Object/test/ilObjectDefinitionTest.php"); - $suite->addTestSuite("ilObjectDefinitionTest"); + $suite = new ilServicesObjectSuite(); + + include_once("./Services/Object/test/ilObjectDefinitionTest.php"); + $suite->addTestSuite("ilObjectDefinitionTest"); - include_once("./Services/Object/test/ilObjectTest.php"); - $suite->addTestSuite("ilObjectTest"); - - return $suite; + include_once("./Services/Object/test/ilObjectTest.php"); + $suite->addTestSuite("ilObjectTest"); + + return $suite; } } -?> diff --git a/Services/PermanentLink/classes/class.ilPermanentLinkGUI.php b/Services/PermanentLink/classes/class.ilPermanentLinkGUI.php index 63caf404fb90101fffd84752cb7a951863d7472a..9da243dab5f8c9cc9bb6e7d37a2a70408eb69180 100644 --- a/Services/PermanentLink/classes/class.ilPermanentLinkGUI.php +++ b/Services/PermanentLink/classes/class.ilPermanentLinkGUI.php @@ -16,280 +16,288 @@ */ class ilPermanentLinkGUI { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilObjectDataCache - */ - protected $obj_data_cache; + /** + * @var ilObjectDataCache + */ + protected $obj_data_cache; - protected $align_center = true; - - /** - * Example: type = "wiki", id (ref_id) = "234", append = "_Start_Page" - */ - function __construct($a_type, $a_id, $a_append = "", $a_target = "") - { - global $DIC; + protected $align_center = true; + + /** + * Example: type = "wiki", id (ref_id) = "234", append = "_Start_Page" + */ + public function __construct($a_type, $a_id, $a_append = "", $a_target = "") + { + global $DIC; - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $this->obj_data_cache = $DIC["ilObjDataCache"]; - $this->setType($a_type); - $this->setId($a_id); - $this->setAppend($a_append); - $this->setIncludePermanentLinkText(true); - $this->setTarget($a_target); - } - - /** - * Set Include permanent link text. - * - * @param boolean $a_includepermanentlinktext Include permanent link text - */ - function setIncludePermanentLinkText($a_includepermanentlinktext) - { - $this->includepermanentlinktext = $a_includepermanentlinktext; - } + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->obj_data_cache = $DIC["ilObjDataCache"]; + $this->setType($a_type); + $this->setId($a_id); + $this->setAppend($a_append); + $this->setIncludePermanentLinkText(true); + $this->setTarget($a_target); + } + + /** + * Set Include permanent link text. + * + * @param boolean $a_includepermanentlinktext Include permanent link text + */ + public function setIncludePermanentLinkText($a_includepermanentlinktext) + { + $this->includepermanentlinktext = $a_includepermanentlinktext; + } - /** - * Get Include permanent link text. - * - * @return boolean Include permanent link text - */ - function getIncludePermanentLinkText() - { - return $this->includepermanentlinktext; - } + /** + * Get Include permanent link text. + * + * @return boolean Include permanent link text + */ + public function getIncludePermanentLinkText() + { + return $this->includepermanentlinktext; + } - /** - * Set Type. - * - * @param string $a_type Type - */ - function setType($a_type) - { - $this->type = $a_type; - } + /** + * Set Type. + * + * @param string $a_type Type + */ + public function setType($a_type) + { + $this->type = $a_type; + } - /** - * Get Type. - * - * @return string Type - */ - function getType() - { - return $this->type; - } + /** + * Get Type. + * + * @return string Type + */ + public function getType() + { + return $this->type; + } - /** - * Set Id. - * - * @param string $a_id Id - */ - function setId($a_id) - { - $this->id = $a_id; - } + /** + * Set Id. + * + * @param string $a_id Id + */ + public function setId($a_id) + { + $this->id = $a_id; + } - /** - * Get Id. - * - * @return string Id - */ - function getId() - { - return $this->id; - } + /** + * Get Id. + * + * @return string Id + */ + public function getId() + { + return $this->id; + } - /** - * Set Append. - * - * @param string $a_append Append - */ - function setAppend($a_append) - { - $this->append = $a_append; - } + /** + * Set Append. + * + * @param string $a_append Append + */ + public function setAppend($a_append) + { + $this->append = $a_append; + } - /** - * Get Append. - * - * @return string Append - */ - function getAppend() - { - return $this->append; - } + /** + * Get Append. + * + * @return string Append + */ + public function getAppend() + { + return $this->append; + } - /** - * Set Target. - * - * @param string $a_target Target - */ - function setTarget($a_target) - { - $this->target = $a_target; - } + /** + * Set Target. + * + * @param string $a_target Target + */ + public function setTarget($a_target) + { + $this->target = $a_target; + } - /** - * Get Target. - * - * @return string Target - */ - function getTarget() - { - return $this->target; - } + /** + * Get Target. + * + * @return string Target + */ + public function getTarget() + { + return $this->target; + } - /** - * Set title - * - * @param string title - */ - function setTitle($a_val) - { - $this->title = $a_val; - } - - /** - * Get title - * - * @return string title - */ - function getTitle() - { - return $this->title; - } - - /** - * Set center alignment - * - * @param boolean align the link at center - */ - function setAlignCenter($a_val) - { - $this->align_center = $a_val; - } - - /** - * Get center alignment - * - * @return boolean align the link at center - */ - function getAlignCenter() - { - return $this->align_center; - } + /** + * Set title + * + * @param string title + */ + public function setTitle($a_val) + { + $this->title = $a_val; + } + + /** + * Get title + * + * @return string title + */ + public function getTitle() + { + return $this->title; + } + + /** + * Set center alignment + * + * @param boolean align the link at center + */ + public function setAlignCenter($a_val) + { + $this->align_center = $a_val; + } + + /** + * Get center alignment + * + * @return boolean align the link at center + */ + public function getAlignCenter() + { + return $this->align_center; + } - /** - * Get HTML for link - */ - function getHTML() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilObjDataCache = $this->obj_data_cache; - - $tpl = new ilTemplate("tpl.permanent_link.html", true, true, - "Services/PermanentLink"); - - include_once('./Services/Link/classes/class.ilLink.php'); - $href = ilLink::_getStaticLink($this->getId(), $this->getType(), - true, $this->getAppend()); - if ($this->getIncludePermanentLinkText()) - { - $tpl->setVariable("TXT_PERMA", $lng->txt("perma_link").":"); - } + /** + * Get HTML for link + */ + public function getHTML() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilObjDataCache = $this->obj_data_cache; + + $tpl = new ilTemplate( + "tpl.permanent_link.html", + true, + true, + "Services/PermanentLink" + ); + + include_once('./Services/Link/classes/class.ilLink.php'); + $href = ilLink::_getStaticLink( + $this->getId(), + $this->getType(), + true, + $this->getAppend() + ); + if ($this->getIncludePermanentLinkText()) { + $tpl->setVariable("TXT_PERMA", $lng->txt("perma_link") . ":"); + } - $title = ''; - - // fetch default title for bookmark + $title = ''; + + // fetch default title for bookmark - if ($this->getTitle() != "") - { - $title = $this->getTitle(); - } - else if(is_numeric($this->getId())) - { - $obj_id = $ilObjDataCache->lookupObjId($this->getId()); - $title = $ilObjDataCache->lookupTitle($obj_id); - } - #if (!$title) - # $bookmark->setTitle("untitled"); + if ($this->getTitle() != "") { + $title = $this->getTitle(); + } elseif (is_numeric($this->getId())) { + $obj_id = $ilObjDataCache->lookupObjId($this->getId()); + $title = $ilObjDataCache->lookupTitle($obj_id); + } + #if (!$title) + # $bookmark->setTitle("untitled"); - $tpl->setVariable("TXT_BOOKMARK_DEFAULT", $title); + $tpl->setVariable("TXT_BOOKMARK_DEFAULT", $title); - $tpl->setVariable("LINK", $href); - - if ($this->getAlignCenter()) - { - $tpl->setVariable("ALIGN", "center"); - } - else - { - $tpl->setVariable("ALIGN", "left"); - } - - if ($this->getTarget() != "") - { - $tpl->setVariable("TARGET", 'target="'.$this->getTarget().'"'); - } + $tpl->setVariable("LINK", $href); + + if ($this->getAlignCenter()) { + $tpl->setVariable("ALIGN", "center"); + } else { + $tpl->setVariable("ALIGN", "left"); + } + + if ($this->getTarget() != "") { + $tpl->setVariable("TARGET", 'target="' . $this->getTarget() . '"'); + } - $bm_html = self::getBookmarksSelectionList($title, $href); - if($bm_html) - { - $tpl->setVariable('SELECTION_LIST', $bm_html); - } + $bm_html = self::getBookmarksSelectionList($title, $href); + if ($bm_html) { + $tpl->setVariable('SELECTION_LIST', $bm_html); + } - return $tpl->get(); - } - - /** - * @return string - */ - protected static function getBookmarksSelectionList($title, $href) - { - require_once 'Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php'; + return $tpl->get(); + } + + /** + * @return string + */ + protected static function getBookmarksSelectionList($title, $href) + { + require_once 'Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php'; - $current_selection_list = new ilAdvancedSelectionListGUI(); - $current_selection_list->setId('socialbm_actions_' . md5(uniqid(rand(), true))); + $current_selection_list = new ilAdvancedSelectionListGUI(); + $current_selection_list->setId('socialbm_actions_' . md5(uniqid(rand(), true))); - $html = ''; + $html = ''; - if(!$GLOBALS['DIC']['ilUser']->isAnonymous() && !$GLOBALS['DIC']['ilSetting']->get('disable_bookmarks')) - { - $GLOBALS['DIC']->ctrl()->setParameterByClass( - 'ilbookmarkadministrationgui', 'bmf_id', 1 - ); - $GLOBALS['DIC']->ctrl()->setParameterByClass( - 'ilbookmarkadministrationgui', 'return_to', 'true' - ); - $GLOBALS['DIC']->ctrl()->setParameterByClass( - 'ilbookmarkadministrationgui', 'bm_title', urlencode($title) - ); - $GLOBALS['DIC']->ctrl()->setParameterByClass( - 'ilbookmarkadministrationgui', 'bm_link', urlencode($href) - ); - $GLOBALS['DIC']->ctrl()->setParameterByClass( - 'ilbookmarkadministrationgui', 'return_to_url', urlencode($_SERVER['REQUEST_URI']) - ); - $link = $GLOBALS['DIC']->ctrl()->getLinkTargetByClass( - ['ilPersonalDesktopGUI', 'ilbookmarkadministrationgui'], - 'newFormBookmark' - ); - $current_selection_list->addItem($GLOBALS['DIC']['lng']->txt("bm_add_to_ilias"), '', $link, '' , $GLOBALS['DIC']['lng']->txt('bm_add_to_ilias'), '_top'); - $html = $current_selection_list->getHTML(); - } + if (!$GLOBALS['DIC']['ilUser']->isAnonymous() && !$GLOBALS['DIC']['ilSetting']->get('disable_bookmarks')) { + $GLOBALS['DIC']->ctrl()->setParameterByClass( + 'ilbookmarkadministrationgui', + 'bmf_id', + 1 + ); + $GLOBALS['DIC']->ctrl()->setParameterByClass( + 'ilbookmarkadministrationgui', + 'return_to', + 'true' + ); + $GLOBALS['DIC']->ctrl()->setParameterByClass( + 'ilbookmarkadministrationgui', + 'bm_title', + urlencode($title) + ); + $GLOBALS['DIC']->ctrl()->setParameterByClass( + 'ilbookmarkadministrationgui', + 'bm_link', + urlencode($href) + ); + $GLOBALS['DIC']->ctrl()->setParameterByClass( + 'ilbookmarkadministrationgui', + 'return_to_url', + urlencode($_SERVER['REQUEST_URI']) + ); + $link = $GLOBALS['DIC']->ctrl()->getLinkTargetByClass( + ['ilPersonalDesktopGUI', 'ilbookmarkadministrationgui'], + 'newFormBookmark' + ); + $current_selection_list->addItem($GLOBALS['DIC']['lng']->txt("bm_add_to_ilias"), '', $link, '', $GLOBALS['DIC']['lng']->txt('bm_add_to_ilias'), '_top'); + $html = $current_selection_list->getHTML(); + } - return $html; - } + return $html; + } } diff --git a/Services/PersonalDesktop/Achievements/classes/class.ilAchievements.php b/Services/PersonalDesktop/Achievements/classes/class.ilAchievements.php index 95de63672cf88136c1c4c96aa180f04fabb868bf..05389915967e49e2c876c54b66ef9c1428219055 100644 --- a/Services/PersonalDesktop/Achievements/classes/class.ilAchievements.php +++ b/Services/PersonalDesktop/Achievements/classes/class.ilAchievements.php @@ -12,103 +12,98 @@ */ class ilAchievements { - /** - * @var ilLearningHistoryService - */ - protected $learing_history; + /** + * @var ilLearningHistoryService + */ + protected $learing_history; - // all services being covered under the achievements menu item - const SERV_LEARNING_HISTORY = 1; - const SERV_COMPETENCES = 2; - const SERV_LEARNING_PROGRESS = 3; - const SERV_BADGES = 4; - const SERV_CERTIFICATES = 5; + // all services being covered under the achievements menu item + const SERV_LEARNING_HISTORY = 1; + const SERV_COMPETENCES = 2; + const SERV_LEARNING_PROGRESS = 3; + const SERV_BADGES = 4; + const SERV_CERTIFICATES = 5; - // this also determines the order of tabs - protected $services = [ - self::SERV_LEARNING_HISTORY, - self::SERV_COMPETENCES, - self::SERV_LEARNING_PROGRESS, - self::SERV_BADGES, - self::SERV_CERTIFICATES - ]; + // this also determines the order of tabs + protected $services = [ + self::SERV_LEARNING_HISTORY, + self::SERV_COMPETENCES, + self::SERV_LEARNING_PROGRESS, + self::SERV_BADGES, + self::SERV_CERTIFICATES + ]; - /** - * @var mixed - */ - protected $setting; + /** + * @var mixed + */ + protected $setting; - /** - * Constructor - */ - public function __construct() - { - global $DIC; + /** + * Constructor + */ + public function __construct() + { + global $DIC; - $this->setting = $DIC["ilSetting"]; - $this->learing_history = $DIC->learningHistory(); - $this->skmg_setting = new ilSetting("skmg"); - } + $this->setting = $DIC["ilSetting"]; + $this->learing_history = $DIC->learningHistory(); + $this->skmg_setting = new ilSetting("skmg"); + } - /** - * Is subservice active? - * - * @param int service - * @return bool - */ - public function isActive($service): bool - { - switch ($service) - { - case self::SERV_LEARNING_HISTORY: - return (bool) $this->learing_history->isActive(); - break; - case self::SERV_COMPETENCES: - return (bool) $this->skmg_setting->get("enable_skmg"); - break; - case self::SERV_LEARNING_PROGRESS: - return (bool) (ilObjUserTracking::_enabledLearningProgress() && - (ilObjUserTracking::_hasLearningProgressOtherUsers() || - ilObjUserTracking::_hasLearningProgressLearner())); - break; - case self::SERV_BADGES: - return (bool) ilBadgeHandler::getInstance()->isActive(); - break; - case self::SERV_CERTIFICATES: - return (bool) ilCertificate::isActive(); - break; - } - return false; - } - - /** - * Is any subservice active? - * - * @return bool - */ - public function isAnyActive(): bool - { - foreach ($this->services as $s) - { - if ($this->isActive($s)) - { - return true; - } - } - return false; - } - - /** - * Get active services - * - * @return int[] - */ - public function getActiveServices(): array - { - return array_filter($this->services, function ($s) { - return $this->isActive($s); - }); - } + /** + * Is subservice active? + * + * @param int service + * @return bool + */ + public function isActive($service) : bool + { + switch ($service) { + case self::SERV_LEARNING_HISTORY: + return (bool) $this->learing_history->isActive(); + break; + case self::SERV_COMPETENCES: + return (bool) $this->skmg_setting->get("enable_skmg"); + break; + case self::SERV_LEARNING_PROGRESS: + return (bool) (ilObjUserTracking::_enabledLearningProgress() && + (ilObjUserTracking::_hasLearningProgressOtherUsers() || + ilObjUserTracking::_hasLearningProgressLearner())); + break; + case self::SERV_BADGES: + return (bool) ilBadgeHandler::getInstance()->isActive(); + break; + case self::SERV_CERTIFICATES: + return (bool) ilCertificate::isActive(); + break; + } + return false; + } + /** + * Is any subservice active? + * + * @return bool + */ + public function isAnyActive() : bool + { + foreach ($this->services as $s) { + if ($this->isActive($s)) { + return true; + } + } + return false; + } + /** + * Get active services + * + * @return int[] + */ + public function getActiveServices() : array + { + return array_filter($this->services, function ($s) { + return $this->isActive($s); + }); + } } diff --git a/Services/PersonalDesktop/Achievements/classes/class.ilAchievementsGUI.php b/Services/PersonalDesktop/Achievements/classes/class.ilAchievementsGUI.php index 014a88ff1c98ecd35b740d248d036f721bc69bee..57d3db03a7ebcea8b7b48b7195fdd563bd06fa3f 100644 --- a/Services/PersonalDesktop/Achievements/classes/class.ilAchievementsGUI.php +++ b/Services/PersonalDesktop/Achievements/classes/class.ilAchievementsGUI.php @@ -12,193 +12,185 @@ */ class ilAchievementsGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilAchievements - */ - protected $achievements; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * Constructor - */ - public function __construct() - { - global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->achievements = new ilAchievements(); - $this->lng = $DIC->language(); - $this->tabs = $DIC->tabs(); - $this->main_tpl = $DIC->ui()->mainTemplate(); - - } - - /** - * Execute command - * @throws ilCtrlException - */ - function executeCommand() - { - $ctrl = $this->ctrl; - $main_tpl = $this->main_tpl; - $lng = $this->lng; - - $next_class = $ctrl->getNextClass($this); - $cmd = $ctrl->getCmd("show"); - - $main_tpl->setTitle($lng->txt("pd_achievements")); - $main_tpl->setTitleIcon(ilUtil::getImagePath("icon_lhist.svg")); // needs a final decision - - switch ($next_class) - { - case "illearningprogressgui": - $this->setTabs(ilAchievements::SERV_LEARNING_PROGRESS); - include_once './Services/Tracking/classes/class.ilLearningProgressGUI.php'; - $new_gui = new ilLearningProgressGUI(ilLearningProgressGUI::LP_CONTEXT_PERSONAL_DESKTOP,0); - $ctrl->forwardCommand($new_gui); - break; - - case 'illearninghistorygui': - $this->setTabs(ilAchievements::SERV_LEARNING_HISTORY); - $lhistgui = new ilLearningHistoryGUI(); - $ctrl->forwardCommand($lhistgui); - $this->main_tpl->show(); - break; - - case 'ilpersonalskillsgui': - $this->setTabs(ilAchievements::SERV_COMPETENCES); - include_once './Services/Skill/classes/class.ilPersonalSkillsGUI.php'; - $skgui = new ilPersonalSkillsGUI(); - $ctrl->forwardCommand($skgui); - $this->main_tpl->show(); - break; - - case 'ilbadgeprofilegui': - $this->setTabs(ilAchievements::SERV_BADGES); - include_once './Services/Badge/classes/class.ilBadgeProfileGUI.php'; - $bgui = new ilBadgeProfileGUI(); - $ctrl->forwardCommand($bgui); - $this->main_tpl->show(); - break; - - case 'ilusercertificategui': - $this->setTabs(ilAchievements::SERV_CERTIFICATES); - $cgui = new ilUserCertificateGUI(); - $ctrl->forwardCommand($cgui); - $this->main_tpl->show(); - break; - - default: - if (in_array($cmd, array("show"))) - { - $this->$cmd(); - } - $this->main_tpl->show(); - break; - } - } - - /** - * Show (redirects to first active service) - */ - protected function show() - { - $ctrl = $this->ctrl; - - $gui_classes = $this->getGUIClasses(); - $first_service = current($this->achievements->getActiveServices()); - if ($first_service) - { - $ctrl->redirectByClass(["ilpersonaldesktopgui", "ilachievementsgui", $gui_classes[$first_service]]); - } - } - - /** - * Set tabs - */ - protected function setTabs($activate) - { - $tabs = $this->tabs; - $links = $this->getLinks(); - - foreach($this->achievements->getActiveServices() as $s) - { - $tabs->addTab("achieve_".$s, $links[$s]["txt"], $links[$s]["link"]); - } - $tabs->activateTab("achieve_".$activate); - } - - /** - * Get link - * - * @param - * @return - */ - protected function getLinks() - { - $ctrl = $this->ctrl; - $lng = $this->lng; - - $lng->loadLanguageModule("lhist"); - $gui_classes = $this->getGUIClasses(); - - $links = [ - ilAchievements::SERV_LEARNING_HISTORY => [ - "txt" => $lng->txt("lhist_learning_history") - ], - ilAchievements::SERV_COMPETENCES => [ - "txt" => $lng->txt("skills") - ], - ilAchievements::SERV_LEARNING_PROGRESS => [ - "txt" => $lng->txt("learning_progress") - ], - ilAchievements::SERV_BADGES => [ - "txt" => $lng->txt('obj_bdga') - ], - ilAchievements::SERV_CERTIFICATES => [ - "txt" => $lng->txt("obj_cert") - ] - ]; - - foreach ($links as $k => $v) - { - $links[$k]["link"] = $ctrl->getLinkTargetByClass(["ilpersonaldesktopgui", "ilachievementsgui", $gui_classes[$k]]); - } - - return $links; - } - - /** - * Get GUI class - * - * @param - * @return - */ - protected function getGUIClasses() - { - $gui_classes = [ - ilAchievements::SERV_LEARNING_HISTORY => "ilLearningHistoryGUI", - ilAchievements::SERV_COMPETENCES => "ilpersonalskillsgui", - ilAchievements::SERV_LEARNING_PROGRESS => "illearningprogressgui", - ilAchievements::SERV_BADGES => "ilbadgeprofilegui", - ilAchievements::SERV_CERTIFICATES => "ilusercertificategui" - ]; - - return $gui_classes; - } - - -} \ No newline at end of file + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilAchievements + */ + protected $achievements; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + $this->ctrl = $DIC->ctrl(); + $this->achievements = new ilAchievements(); + $this->lng = $DIC->language(); + $this->tabs = $DIC->tabs(); + $this->main_tpl = $DIC->ui()->mainTemplate(); + } + + /** + * Execute command + * @throws ilCtrlException + */ + public function executeCommand() + { + $ctrl = $this->ctrl; + $main_tpl = $this->main_tpl; + $lng = $this->lng; + + $next_class = $ctrl->getNextClass($this); + $cmd = $ctrl->getCmd("show"); + + $main_tpl->setTitle($lng->txt("pd_achievements")); + $main_tpl->setTitleIcon(ilUtil::getImagePath("icon_lhist.svg")); // needs a final decision + + switch ($next_class) { + case "illearningprogressgui": + $this->setTabs(ilAchievements::SERV_LEARNING_PROGRESS); + include_once './Services/Tracking/classes/class.ilLearningProgressGUI.php'; + $new_gui = new ilLearningProgressGUI(ilLearningProgressGUI::LP_CONTEXT_PERSONAL_DESKTOP, 0); + $ctrl->forwardCommand($new_gui); + break; + + case 'illearninghistorygui': + $this->setTabs(ilAchievements::SERV_LEARNING_HISTORY); + $lhistgui = new ilLearningHistoryGUI(); + $ctrl->forwardCommand($lhistgui); + $this->main_tpl->show(); + break; + + case 'ilpersonalskillsgui': + $this->setTabs(ilAchievements::SERV_COMPETENCES); + include_once './Services/Skill/classes/class.ilPersonalSkillsGUI.php'; + $skgui = new ilPersonalSkillsGUI(); + $ctrl->forwardCommand($skgui); + $this->main_tpl->show(); + break; + + case 'ilbadgeprofilegui': + $this->setTabs(ilAchievements::SERV_BADGES); + include_once './Services/Badge/classes/class.ilBadgeProfileGUI.php'; + $bgui = new ilBadgeProfileGUI(); + $ctrl->forwardCommand($bgui); + $this->main_tpl->show(); + break; + + case 'ilusercertificategui': + $this->setTabs(ilAchievements::SERV_CERTIFICATES); + $cgui = new ilUserCertificateGUI(); + $ctrl->forwardCommand($cgui); + $this->main_tpl->show(); + break; + + default: + if (in_array($cmd, array("show"))) { + $this->$cmd(); + } + $this->main_tpl->show(); + break; + } + } + + /** + * Show (redirects to first active service) + */ + protected function show() + { + $ctrl = $this->ctrl; + + $gui_classes = $this->getGUIClasses(); + $first_service = current($this->achievements->getActiveServices()); + if ($first_service) { + $ctrl->redirectByClass(["ilpersonaldesktopgui", "ilachievementsgui", $gui_classes[$first_service]]); + } + } + + /** + * Set tabs + */ + protected function setTabs($activate) + { + $tabs = $this->tabs; + $links = $this->getLinks(); + + foreach ($this->achievements->getActiveServices() as $s) { + $tabs->addTab("achieve_" . $s, $links[$s]["txt"], $links[$s]["link"]); + } + $tabs->activateTab("achieve_" . $activate); + } + + /** + * Get link + * + * @param + * @return + */ + protected function getLinks() + { + $ctrl = $this->ctrl; + $lng = $this->lng; + + $lng->loadLanguageModule("lhist"); + $gui_classes = $this->getGUIClasses(); + + $links = [ + ilAchievements::SERV_LEARNING_HISTORY => [ + "txt" => $lng->txt("lhist_learning_history") + ], + ilAchievements::SERV_COMPETENCES => [ + "txt" => $lng->txt("skills") + ], + ilAchievements::SERV_LEARNING_PROGRESS => [ + "txt" => $lng->txt("learning_progress") + ], + ilAchievements::SERV_BADGES => [ + "txt" => $lng->txt('obj_bdga') + ], + ilAchievements::SERV_CERTIFICATES => [ + "txt" => $lng->txt("obj_cert") + ] + ]; + + foreach ($links as $k => $v) { + $links[$k]["link"] = $ctrl->getLinkTargetByClass(["ilpersonaldesktopgui", "ilachievementsgui", $gui_classes[$k]]); + } + + return $links; + } + + /** + * Get GUI class + * + * @param + * @return + */ + protected function getGUIClasses() + { + $gui_classes = [ + ilAchievements::SERV_LEARNING_HISTORY => "ilLearningHistoryGUI", + ilAchievements::SERV_COMPETENCES => "ilpersonalskillsgui", + ilAchievements::SERV_LEARNING_PROGRESS => "illearningprogressgui", + ilAchievements::SERV_BADGES => "ilbadgeprofilegui", + ilAchievements::SERV_CERTIFICATES => "ilusercertificategui" + ]; + + return $gui_classes; + } +} diff --git a/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockGUI.php b/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockGUI.php index 89c1721ec5a81ee169d9a477eba526941f3ff3f0..e3e6ddba6b0774ac079fc33bb8ce3d4c01fcae20 100755 --- a/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockGUI.php +++ b/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockGUI.php @@ -17,778 +17,747 @@ require_once('./Services/Repository/classes/class.ilObjectPlugin.php'); */ class ilPDSelectedItemsBlockGUI extends ilBlockGUI implements ilDesktopItemHandling { - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilSetting - */ - protected $settings; - - /** - * @var ilObjectDefinition - */ - protected $obj_definition; - - /** @var string */ - static $block_type = 'pditems'; - - /** @var ilPDSelectedItemsBlockViewSettings */ - protected $viewSettings; - - /** @var ilPDSelectedItemsBlockViewGUI */ - protected $view; - - /** @var bool */ - protected $manage = false; - - /** @var string */ - protected $content = ''; - - /** @var ilLanguage */ - protected $lng; - - /** @var ilCtrl */ - protected $ctrl; - - /** @var ilObjUser */ - protected $user; - - /** - * ilPDSelectedItemsBlockGUI constructor. - */ - public function __construct() - { - global $DIC; - $this->rbacsystem = $DIC->rbac()->system(); - $this->settings = $DIC->settings(); - $this->obj_definition = $DIC["objDefinition"]; - $this->access = $DIC->access(); - - parent::__construct(); - - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $this->user = $DIC->user(); - - $this->lng->loadLanguageModule('pd'); - $this->lng->loadLanguageModule('cntr'); // #14158 - - $this->setEnableNumInfo(false); - $this->setLimit(99999); - $this->setAvailableDetailLevels(3, 1); - $this->allow_moving = false; - - $this->initViewSettings(); - } - - /** - * - */ - protected function initViewSettings() - { - require_once 'Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockViewSettings.php'; - $this->viewSettings = new ilPDSelectedItemsBlockViewSettings($this->user, (int)$_GET['view']); - $this->viewSettings->parse(); - - require_once 'Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockViewGUI.php'; - $this->view = ilPDSelectedItemsBlockViewGUI::bySettings($this->viewSettings); - - $_GET['view'] = $this->viewSettings->getCurrentView(); - $this->ctrl->saveParameter($this, 'view'); - } - - /** - * @return ilPDSelectedItemsBlockViewSettings - */ - public function getViewSettings() - { - return $this->viewSettings; - } - - /** - * - */ - public function isManagedView() - { - return $this->manage; - } - - /** - * @inheritdoc - */ - public function fillDetailRow() - { -// $this->ctrl->setParameterByClass('ilpersonaldesktopgui', 'view', $this->viewSettings->getCurrentView()); - parent::fillDetailRow(); -// $this->ctrl->setParameterByClass('ilpersonaldesktopgui', 'view', ''); - } - - /** - * @inheritdoc - */ - public function addToDeskObject() - { - include_once './Services/PersonalDesktop/classes/class.ilDesktopItemGUI.php'; - ilDesktopItemGUI::addToDesktop(); - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->setParameterByClass('ilpersonaldesktopgui', 'view', $this->viewSettings->getCurrentView()); - $this->ctrl->redirectByClass('ilpersonaldesktopgui', 'show'); - } - - /** - * @inheritdoc - */ - public function removeFromDeskObject() - { - include_once './Services/PersonalDesktop/classes/class.ilDesktopItemGUI.php'; - ilDesktopItemGUI::removeFromDesktop(); - ilUtil::sendSuccess($this->lng->txt("removed_from_desktop"), true); - $this->ctrl->setParameterByClass('ilpersonaldesktopgui', 'view', $this->viewSettings->getCurrentView()); - $this->ctrl->redirectByClass('ilpersonaldesktopgui', 'show'); - } - - /** - * @inheritdoc - */ - public function getBlockType(): string - { - return self::$block_type; - } - - /** - * @inheritdoc - */ - public static function getScreenMode() - { - $cmd = $_GET['cmd']; - if($cmd == 'post') - { - $cmd = $_POST['cmd']; - $cmd = array_shift(array_keys($cmd)); - } - - switch($cmd) - { - case 'confirmRemove': - case 'manage': - return IL_SCREEN_FULL; - - default: - return IL_SCREEN_SIDE; - } - } - - /** - * @inheritdoc - */ - protected function isRepositoryObject(): bool - { - return false; - } - - /** - * @inheritdoc - */ - public function getHTML() - { - global $DIC; - - $DIC->database()->useSlave(true); - - // workaround to show details row - $this->setData(array('dummy')); - - require_once 'Services/Object/classes/class.ilObjectListGUI.php'; - ilObjectListGUI::prepareJSLinks('', - $this->ctrl->getLinkTargetByClass(array('ilcommonactiondispatchergui', 'ilnotegui'), '', '', true, false), - $this->ctrl->getLinkTargetByClass(array('ilcommonactiondispatchergui', 'iltagginggui'), '', '', true, false) - ); - - $DIC['ilHelp']->setDefaultScreenId(ilHelpGUI::ID_PART_SCREEN, $this->view->getScreenId()); - $this->setTitle($this->view->getTitle()); - $this->setContent($this->getViewBlockHtml()); - - if($this->getContent() == '') - { - $this->setEnableDetailRow(false); - } - -// $this->ctrl->clearParametersByClass('ilpersonaldesktopgui'); - $this->ctrl->clearParameters($this); - - $DIC->database()->useSlave(false); - - return parent::getHTML(); - } - - // Overwritten from ilBlockGUI as there seems to be no other possibility to - // not show Commands in the HEADER(!!!!) of a block in the VIEW_MY_STUDYPROGRAMME - // case... Sigh. - public function getFooterLinks() - { - if($this->viewSettings->isStudyProgrammeViewActive()) - { - return array(); - } - - return parent::getFooterLinks(); - } - - /** - * - */ - public function executeCommand() - { - $next_class = $this->ctrl->getNextClass(); - $cmd = $this->ctrl->getCmd('getHTML'); - - switch($next_class) - { - case 'ilcommonactiondispatchergui': - include_once('Services/Object/classes/class.ilCommonActionDispatcherGUI.php'); - $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); - $this->ctrl->forwardCommand($gui); - break; - - default: - if(method_exists($this, $cmd)) - { - return $this->$cmd(); - } - else - { - return $this->{$cmd . 'Object'}(); - } - } - } - - /** - * @return string - */ - protected function getContent() - { - return $this->content; - } - - /** - * @param string $a_content - */ - protected function setContent($a_content) - { - $this->content = $a_content; - } - - /** - * @inheritdoc - */ - public function fillDataSection() - { - if($this->getContent() == '') - { - $this->setDataSection($this->view->getIntroductionHtml()); - } - else - { - $this->tpl->setVariable('BLOCK_ROW', $this->getContent()); - } - } - - - /** - * @inheritdoc - */ - public function fillFooter() - { - $this->setFooterLinks(); - $this->fillFooterLinks(); - $this->tpl->setVariable('FCOLSPAN', $this->getColSpan()); - if($this->tpl->blockExists('block_footer')) - { - $this->tpl->setCurrentBlock('block_footer'); - $this->tpl->parseCurrentBlock(); - } - } - - /** - * - */ - protected function setFooterLinks() - { - if($this->getContent() == '') - { - $this->setEnableNumInfo(false); - return ''; - } - - if($this->manage) - { - return ''; - } - - $this->addFooterLink( - $this->lng->txt("pd_sort_by_type"), - $this->ctrl->getLinkTarget($this, "orderPDItemsByType"), - $this->ctrl->getLinkTarget($this, "orderPDItemsByType", "", true), - "block_".$this->getBlockType()."_".$this->block_id, - false, false, $this->viewSettings->isSortedByType() - ); - - $this->addFooterLink($this->lng->txt("pd_sort_by_location"), - $this->ctrl->getLinkTarget($this, "orderPDItemsByLocation"), - $this->ctrl->getLinkTarget($this, "orderPDItemsByLocation", "", true), - "block_".$this->getBlockType()."_".$this->block_id, - false, false, $this->viewSettings->isSortedByLocation() - ); - - if($this->viewSettings->isMembershipsViewActive()) - { - $this->addFooterLink($this->lng->txt("pd_sort_by_start_date"), - $this->ctrl->getLinkTarget($this, "orderPDItemsByStartDate"), - $this->ctrl->getLinkTarget($this, "orderPDItemsByStartDate", "", true), - "block_" . $this->getBlockType() . "_" . $this->block_id, - false, false, $this->viewSettings->isSortedByStartDate() - ); - } - - $this->addFooterLink($this->viewSettings->isSelectedItemsViewActive() ? - $this->lng->txt("pd_remove_multiple") : - $this->lng->txt("pd_unsubscribe_multiple_memberships"), - $this->ctrl->getLinkTarget($this, "manage"), - null, - "block_".$this->getBlockType()."_".$this->block_id - ); - } - - /** - * @param ilTemplate $tpl - * @param ilPDSelectedItemsBlockGroup[] $grouped_items - * @param bool $show_header - * @return bool - */ - protected function renderGroupedItems(ilTemplate $tpl, array $grouped_items, $show_header = false) - { - /** @var $rbacsystem ilRbacSystem */ - $rbacsystem = $this->rbacsystem; - - if(0 == count($grouped_items)) - { - return false; - } - - $output = false; - - require_once 'Services/Object/classes/class.ilObjectActivation.php'; - require_once 'Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockListGUIFactory.php'; - $list_factory = new ilPDSelectedItemsBlockListGUIFactory($this); - - foreach($grouped_items as $group) - { - $item_html = array(); - - foreach($group->getItems() as $item) - { - try - { - $item_list_gui = $list_factory->byType($item['type']); - ilObjectActivation::addListGUIActivationProperty($item_list_gui, $item); - - // #15232 - if($this->manage) - { - if($this->view->mayRemoveItem((int)$item['ref_id'])) - { - $item_list_gui->enableCheckbox(true); - } - else - { - $item_list_gui->enableCheckbox(false); - } - } - - $html = $item_list_gui->getListItemHTML($item['ref_id'], $item['obj_id'], $item['title'], $item['description']); - if($html != '') - { - $item_html[] = array( - 'html' => $html, - 'item_ref_id' => $item['ref_id'], - 'item_obj_id' => $item['obj_id'], - 'parent_ref' => $item['parent_ref'], - 'type' => $item['type'], - 'item_icon_image_type' => $item_list_gui->getIconImageType() - ); - } - } - catch(ilException $e) - { - continue; - } - } - - if(0 == count($item_html)) - { - continue; - } - - if($show_header) - { - $this->addSectionHeader($tpl, $group); - $this->resetRowType() ; - } - - foreach($item_html as $item) - { - $this->addStandardRow( - $tpl,$item['html'], $item['item_ref_id'],$item['item_obj_id'], - $item['item_icon_image_type'], - 'th_' . md5($group->getLabel()) - ); - $output = true; - } - } - - return $output; - } - - /** - * get selected item block - */ - protected function getViewBlockHtml() - { - $tpl = $this->newBlockTemplate(); - - $this->renderGroupedItems( - $tpl, $this->view->getItemGroups(), - ($this->getCurrentDetailLevel() >= $this->view->getMinimumDetailLevelForSection()) - ); - - if($this->manage && $this->view->supportsSelectAll()) - { - // #11355 - see ContainerContentGUI::renderSelectAllBlock() - $tpl->setCurrentBlock('select_all_row'); - $tpl->setVariable('CHECKBOXNAME', 'ilToolbarSelectAll'); - $tpl->setVariable('SEL_ALL_PARENT', 'ilToolbar'); - $tpl->setVariable('SEL_ALL_CB_NAME', 'id'); - $tpl->setVariable('TXT_SELECT_ALL', $this->lng->txt('select_all')); - $tpl->parseCurrentBlock(); - } - - return $tpl->get(); - } - - protected function resetRowType() - { - $this->cur_row_type = ""; - } - - /** - * returns a new list block template - * - * @access private - * @return object block template - */ - function newBlockTemplate() - { - $tpl = new ilTemplate("tpl.pd_list_block.html", true, true, "Services/PersonalDesktop"); - $this->cur_row_type = ""; - return $tpl; - } - - /** - * @param ilTemplate $a_tpl - * @param ilPDSelectedItemsBlockGroup $group - */ - protected function addSectionHeader(ilTemplate $a_tpl, ilPDSelectedItemsBlockGroup $group) - { - if($group->hasIcon()) - { - $a_tpl->setCurrentBlock('container_header_row_image'); - $a_tpl->setVariable('HEADER_IMG', $group->getIconPath()); - $a_tpl->setVariable('HEADER_ALT', $group->getLabel()); - } - else - { - $a_tpl->setCurrentBlock('container_header_row'); - } - - $a_tpl->setVariable('BLOCK_HEADER_CONTENT', $group->getLabel()); - $a_tpl->setVariable('BLOCK_HEADER_ID', 'th_' . md5($group->getLabel())); - $a_tpl->parseCurrentBlock(); - - $a_tpl->touchBlock('container_row'); - - $this->resetRowType(); - } - - /** - * adds a standard row to a block template - * - * @param object $a_tpl block template - * @param string $a_html html code - * @access private - */ - function addStandardRow(&$a_tpl, $a_html, $a_item_ref_id = "", $a_item_obj_id = "", - $a_image_type = "", $a_related_header = "") - { - $ilSetting = $this->settings; - - $this->cur_row_type = ($this->cur_row_type == "row_type_1") - ? "row_type_2" - : "row_type_1"; - $a_tpl->touchBlock($this->cur_row_type); - - if ($a_image_type != "") - { - if (!is_array($a_image_type) && !in_array($a_image_type, array("lm", "htlm", "sahs"))) - { - $icon = ilUtil::getImagePath("icon_".$a_image_type.".svg"); - $title = $this->lng->txt("obj_".$a_image_type); - } - else - { - $icon = ilUtil::getImagePath("icon_lm.svg"); - $title = $this->lng->txt("learning_module"); - } - - if ($ilSetting->get('custom_icons')) { - global $DIC; - /** @var \ilObjectCustomIconFactory $customIconFactory */ - $customIconFactory = $DIC['object.customicons.factory']; - $customIcon = $customIconFactory->getByObjId($a_item_obj_id, $a_image_type); - - if ($customIcon->exists()) { - $icon = $customIcon->getFullPath(); - } - } - - $a_tpl->setCurrentBlock("block_row_image"); - $a_tpl->setVariable("ROW_IMG", $icon); - $a_tpl->setVariable("ROW_ALT", $title); - $a_tpl->parseCurrentBlock(); - } - else - { - $a_tpl->setVariable("ROW_NBSP", " "); - } - $a_tpl->setCurrentBlock("container_standard_row"); - $a_tpl->setVariable("BLOCK_ROW_CONTENT", $a_html); - $rel_headers = ($a_related_header != "") - ? "th_selected_items ".$a_related_header - : "th_selected_items"; - $a_tpl->setVariable("BLOCK_ROW_HEADERS", $rel_headers); - $a_tpl->parseCurrentBlock(); - $a_tpl->touchBlock("container_row"); - } - - /** - * @param string $sort_type - */ - protected function changeSortMode($sort_type) - { - $this->user->writePref('pd_order_items', $sort_type); - $this->initViewSettings(); - - if($this->ctrl->isAsynch()) - { - echo $this->getHTML(); - exit; - } - - $this->ctrl->setParameterByClass('ilpersonaldesktopgui', 'view', $this->viewSettings->getCurrentView()); - $this->ctrl->redirectByClass('ilpersonaldesktopgui', 'show'); - } - - /** - * Sort desktop items by location - */ - public function orderPDItemsByLocation() - { - $this->changeSortMode($this->viewSettings->getSortByLocationMode()); - } - - /** - * Sort desktop items by Type - */ - public function orderPDItemsByType() - { - $this->changeSortMode($this->viewSettings->getSortByTypeMode()); - } - - /** - * Sort desktop items by start date - */ - public function orderPDItemsByStartDate() - { - $this->changeSortMode($this->viewSettings->getSortByStartDateMode()); - } - - function manageObject() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->manage = true; - $this->setAvailableDetailLevels(1, 1); - - $top_tb = new ilToolbarGUI(); - $top_tb->setFormAction($ilCtrl->getFormAction($this)); - $top_tb->setLeadingImage(ilUtil::getImagePath("arrow_upright.svg"), $lng->txt("actions")); - - $button = ilSubmitButton::getInstance(); - if($this->viewSettings->isSelectedItemsViewActive()) - { - $button->setCaption("remove"); - } - else - { - $button->setCaption("pd_unsubscribe_memberships"); - } - $button->setCommand("confirmRemove"); - $top_tb->addStickyItem($button); - - $button2 = ilSubmitButton::getInstance(); - $button2->setCaption("cancel"); - $button2->setCommand("getHTML"); - $top_tb->addStickyItem($button2); - - $top_tb->setCloseFormTag(false); - - $bot_tb = new ilToolbarGUI(); - $bot_tb->setLeadingImage(ilUtil::getImagePath("arrow_downright.svg"), $lng->txt("actions")); - $bot_tb->addStickyItem($button); - $bot_tb->addStickyItem($button2); - $bot_tb->setOpenFormTag(false); - return $top_tb->getHTML().$this->getHTML().$bot_tb->getHTML(); - } - - public function confirmRemoveObject() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameter($this, 'view', $this->viewSettings->getCurrentView()); - if(!sizeof($_POST["id"])) - { - ilUtil::sendFailure($this->lng->txt("select_one"), true); - $ilCtrl->redirect($this, "manage"); - } - - if($this->viewSettings->isSelectedItemsViewActive()) - { - $question = $this->lng->txt("pd_info_delete_sure_remove"); - $cmd = "confirmedRemove"; - } - else - { - $question = $this->lng->txt("pd_info_delete_sure_unsubscribe"); - $cmd = "confirmedUnsubscribe"; - } - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setHeaderText($question); - - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setCancel($this->lng->txt("cancel"), "manage"); - $cgui->setConfirm($this->lng->txt("confirm"), $cmd); - - foreach ($_POST["id"] as $ref_id) - { - $obj_id = ilObject::_lookupObjectId($ref_id); - $title = ilObject::_lookupTitle($obj_id); - $type = ilObject::_lookupType($obj_id); - - $cgui->addItem("ref_id[]", $ref_id, $title, - ilObject::_getIcon($obj_id, "small", $type), - $this->lng->txt("icon")." ".$this->lng->txt("obj_".$type)); - } - - return $cgui->getHTML(); - } - - public function confirmedRemove() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - if(!sizeof($_POST["ref_id"])) - { - $ilCtrl->redirect($this, "manage"); - } - - foreach($_POST["ref_id"] as $ref_id) - { - $type = ilObject::_lookupType($ref_id, true); - ilObjUser::_dropDesktopItem($ilUser->getId(), $ref_id, $type); - } - - // #12909 - ilUtil::sendSuccess($this->lng->txt("pd_remove_multi_confirm"), true); - $ilCtrl->setParameterByClass('ilpersonaldesktopgui', 'view', $this->viewSettings->getCurrentView()); - $ilCtrl->redirectByClass("ilpersonaldesktopgui", "show"); - } - - public function confirmedUnsubscribe() - { - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - $ilUser = $this->user; - - if(!sizeof($_POST["ref_id"])) - { - $ilCtrl->redirect($this, "manage"); - } - - foreach($_POST["ref_id"] as $ref_id) - { - if($ilAccess->checkAccess("leave", "", $ref_id)) - { - switch(ilObject::_lookupType($ref_id, true)) - { - case "crs": - // see ilObjCourseGUI:performUnsubscribeObject() - include_once "Modules/Course/classes/class.ilCourseParticipants.php"; - $members = new ilCourseParticipants(ilObject::_lookupObjId($ref_id)); - $members->delete($ilUser->getId()); - - $members->sendUnsubscribeNotificationToAdmins($ilUser->getId()); - $members->sendNotification( - $members->NOTIFY_UNSUBSCRIBE, - $ilUser->getId() - ); - break; - - case "grp": - // see ilObjGroupGUI:performUnsubscribeObject() - include_once "Modules/Group/classes/class.ilGroupParticipants.php"; - $members = new ilGroupParticipants(ilObject::_lookupObjId($ref_id)); - $members->delete($ilUser->getId()); - - include_once './Modules/Group/classes/class.ilGroupMembershipMailNotification.php'; - $members->sendNotification( - ilGroupMembershipMailNotification::TYPE_UNSUBSCRIBE_MEMBER, - $ilUser->getId() - ); - $members->sendNotification( - ilGroupMembershipMailNotification::TYPE_NOTIFICATION_UNSUBSCRIBE, - $ilUser->getId() - ); - break; - - default: - // do nothing - continue 2; - } - - include_once './Modules/Forum/classes/class.ilForumNotification.php'; - ilForumNotification::checkForumsExistsDelete($ref_id, $ilUser->getId()); - } - } - - - ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); - $ilCtrl->setParameterByClass('ilpersonaldesktopgui', 'view', $this->viewSettings->getCurrentView()); - $ilCtrl->redirectByClass("ilpersonaldesktopgui", "show"); - } -} \ No newline at end of file + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var ilObjectDefinition + */ + protected $obj_definition; + + /** @var string */ + public static $block_type = 'pditems'; + + /** @var ilPDSelectedItemsBlockViewSettings */ + protected $viewSettings; + + /** @var ilPDSelectedItemsBlockViewGUI */ + protected $view; + + /** @var bool */ + protected $manage = false; + + /** @var string */ + protected $content = ''; + + /** @var ilLanguage */ + protected $lng; + + /** @var ilCtrl */ + protected $ctrl; + + /** @var ilObjUser */ + protected $user; + + /** + * ilPDSelectedItemsBlockGUI constructor. + */ + public function __construct() + { + global $DIC; + $this->rbacsystem = $DIC->rbac()->system(); + $this->settings = $DIC->settings(); + $this->obj_definition = $DIC["objDefinition"]; + $this->access = $DIC->access(); + + parent::__construct(); + + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->user = $DIC->user(); + + $this->lng->loadLanguageModule('pd'); + $this->lng->loadLanguageModule('cntr'); // #14158 + + $this->setEnableNumInfo(false); + $this->setLimit(99999); + $this->setAvailableDetailLevels(3, 1); + $this->allow_moving = false; + + $this->initViewSettings(); + } + + /** + * + */ + protected function initViewSettings() + { + require_once 'Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockViewSettings.php'; + $this->viewSettings = new ilPDSelectedItemsBlockViewSettings($this->user, (int) $_GET['view']); + $this->viewSettings->parse(); + + require_once 'Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockViewGUI.php'; + $this->view = ilPDSelectedItemsBlockViewGUI::bySettings($this->viewSettings); + + $_GET['view'] = $this->viewSettings->getCurrentView(); + $this->ctrl->saveParameter($this, 'view'); + } + + /** + * @return ilPDSelectedItemsBlockViewSettings + */ + public function getViewSettings() + { + return $this->viewSettings; + } + + /** + * + */ + public function isManagedView() + { + return $this->manage; + } + + /** + * @inheritdoc + */ + public function fillDetailRow() + { + // $this->ctrl->setParameterByClass('ilpersonaldesktopgui', 'view', $this->viewSettings->getCurrentView()); + parent::fillDetailRow(); + // $this->ctrl->setParameterByClass('ilpersonaldesktopgui', 'view', ''); + } + + /** + * @inheritdoc + */ + public function addToDeskObject() + { + include_once './Services/PersonalDesktop/classes/class.ilDesktopItemGUI.php'; + ilDesktopItemGUI::addToDesktop(); + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->setParameterByClass('ilpersonaldesktopgui', 'view', $this->viewSettings->getCurrentView()); + $this->ctrl->redirectByClass('ilpersonaldesktopgui', 'show'); + } + + /** + * @inheritdoc + */ + public function removeFromDeskObject() + { + include_once './Services/PersonalDesktop/classes/class.ilDesktopItemGUI.php'; + ilDesktopItemGUI::removeFromDesktop(); + ilUtil::sendSuccess($this->lng->txt("removed_from_desktop"), true); + $this->ctrl->setParameterByClass('ilpersonaldesktopgui', 'view', $this->viewSettings->getCurrentView()); + $this->ctrl->redirectByClass('ilpersonaldesktopgui', 'show'); + } + + /** + * @inheritdoc + */ + public function getBlockType() : string + { + return self::$block_type; + } + + /** + * @inheritdoc + */ + public static function getScreenMode() + { + $cmd = $_GET['cmd']; + if ($cmd == 'post') { + $cmd = $_POST['cmd']; + $cmd = array_shift(array_keys($cmd)); + } + + switch ($cmd) { + case 'confirmRemove': + case 'manage': + return IL_SCREEN_FULL; + + default: + return IL_SCREEN_SIDE; + } + } + + /** + * @inheritdoc + */ + protected function isRepositoryObject() : bool + { + return false; + } + + /** + * @inheritdoc + */ + public function getHTML() + { + global $DIC; + + $DIC->database()->useSlave(true); + + // workaround to show details row + $this->setData(array('dummy')); + + require_once 'Services/Object/classes/class.ilObjectListGUI.php'; + ilObjectListGUI::prepareJSLinks( + '', + $this->ctrl->getLinkTargetByClass(array('ilcommonactiondispatchergui', 'ilnotegui'), '', '', true, false), + $this->ctrl->getLinkTargetByClass(array('ilcommonactiondispatchergui', 'iltagginggui'), '', '', true, false) + ); + + $DIC['ilHelp']->setDefaultScreenId(ilHelpGUI::ID_PART_SCREEN, $this->view->getScreenId()); + $this->setTitle($this->view->getTitle()); + $this->setContent($this->getViewBlockHtml()); + + if ($this->getContent() == '') { + $this->setEnableDetailRow(false); + } + + // $this->ctrl->clearParametersByClass('ilpersonaldesktopgui'); + $this->ctrl->clearParameters($this); + + $DIC->database()->useSlave(false); + + return parent::getHTML(); + } + + // Overwritten from ilBlockGUI as there seems to be no other possibility to + // not show Commands in the HEADER(!!!!) of a block in the VIEW_MY_STUDYPROGRAMME + // case... Sigh. + public function getFooterLinks() + { + if ($this->viewSettings->isStudyProgrammeViewActive()) { + return array(); + } + + return parent::getFooterLinks(); + } + + /** + * + */ + public function executeCommand() + { + $next_class = $this->ctrl->getNextClass(); + $cmd = $this->ctrl->getCmd('getHTML'); + + switch ($next_class) { + case 'ilcommonactiondispatchergui': + include_once('Services/Object/classes/class.ilCommonActionDispatcherGUI.php'); + $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); + $this->ctrl->forwardCommand($gui); + break; + + default: + if (method_exists($this, $cmd)) { + return $this->$cmd(); + } else { + return $this->{$cmd . 'Object'}(); + } + } + } + + /** + * @return string + */ + protected function getContent() + { + return $this->content; + } + + /** + * @param string $a_content + */ + protected function setContent($a_content) + { + $this->content = $a_content; + } + + /** + * @inheritdoc + */ + public function fillDataSection() + { + if ($this->getContent() == '') { + $this->setDataSection($this->view->getIntroductionHtml()); + } else { + $this->tpl->setVariable('BLOCK_ROW', $this->getContent()); + } + } + + + /** + * @inheritdoc + */ + public function fillFooter() + { + $this->setFooterLinks(); + $this->fillFooterLinks(); + $this->tpl->setVariable('FCOLSPAN', $this->getColSpan()); + if ($this->tpl->blockExists('block_footer')) { + $this->tpl->setCurrentBlock('block_footer'); + $this->tpl->parseCurrentBlock(); + } + } + + /** + * + */ + protected function setFooterLinks() + { + if ($this->getContent() == '') { + $this->setEnableNumInfo(false); + return ''; + } + + if ($this->manage) { + return ''; + } + + $this->addFooterLink( + $this->lng->txt("pd_sort_by_type"), + $this->ctrl->getLinkTarget($this, "orderPDItemsByType"), + $this->ctrl->getLinkTarget($this, "orderPDItemsByType", "", true), + "block_" . $this->getBlockType() . "_" . $this->block_id, + false, + false, + $this->viewSettings->isSortedByType() + ); + + $this->addFooterLink( + $this->lng->txt("pd_sort_by_location"), + $this->ctrl->getLinkTarget($this, "orderPDItemsByLocation"), + $this->ctrl->getLinkTarget($this, "orderPDItemsByLocation", "", true), + "block_" . $this->getBlockType() . "_" . $this->block_id, + false, + false, + $this->viewSettings->isSortedByLocation() + ); + + if ($this->viewSettings->isMembershipsViewActive()) { + $this->addFooterLink( + $this->lng->txt("pd_sort_by_start_date"), + $this->ctrl->getLinkTarget($this, "orderPDItemsByStartDate"), + $this->ctrl->getLinkTarget($this, "orderPDItemsByStartDate", "", true), + "block_" . $this->getBlockType() . "_" . $this->block_id, + false, + false, + $this->viewSettings->isSortedByStartDate() + ); + } + + $this->addFooterLink( + $this->viewSettings->isSelectedItemsViewActive() ? + $this->lng->txt("pd_remove_multiple") : + $this->lng->txt("pd_unsubscribe_multiple_memberships"), + $this->ctrl->getLinkTarget($this, "manage"), + null, + "block_" . $this->getBlockType() . "_" . $this->block_id + ); + } + + /** + * @param ilTemplate $tpl + * @param ilPDSelectedItemsBlockGroup[] $grouped_items + * @param bool $show_header + * @return bool + */ + protected function renderGroupedItems(ilTemplate $tpl, array $grouped_items, $show_header = false) + { + /** @var $rbacsystem ilRbacSystem */ + $rbacsystem = $this->rbacsystem; + + if (0 == count($grouped_items)) { + return false; + } + + $output = false; + + require_once 'Services/Object/classes/class.ilObjectActivation.php'; + require_once 'Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockListGUIFactory.php'; + $list_factory = new ilPDSelectedItemsBlockListGUIFactory($this); + + foreach ($grouped_items as $group) { + $item_html = array(); + + foreach ($group->getItems() as $item) { + try { + $item_list_gui = $list_factory->byType($item['type']); + ilObjectActivation::addListGUIActivationProperty($item_list_gui, $item); + + // #15232 + if ($this->manage) { + if ($this->view->mayRemoveItem((int) $item['ref_id'])) { + $item_list_gui->enableCheckbox(true); + } else { + $item_list_gui->enableCheckbox(false); + } + } + + $html = $item_list_gui->getListItemHTML($item['ref_id'], $item['obj_id'], $item['title'], $item['description']); + if ($html != '') { + $item_html[] = array( + 'html' => $html, + 'item_ref_id' => $item['ref_id'], + 'item_obj_id' => $item['obj_id'], + 'parent_ref' => $item['parent_ref'], + 'type' => $item['type'], + 'item_icon_image_type' => $item_list_gui->getIconImageType() + ); + } + } catch (ilException $e) { + continue; + } + } + + if (0 == count($item_html)) { + continue; + } + + if ($show_header) { + $this->addSectionHeader($tpl, $group); + $this->resetRowType() ; + } + + foreach ($item_html as $item) { + $this->addStandardRow( + $tpl, + $item['html'], + $item['item_ref_id'], + $item['item_obj_id'], + $item['item_icon_image_type'], + 'th_' . md5($group->getLabel()) + ); + $output = true; + } + } + + return $output; + } + + /** + * get selected item block + */ + protected function getViewBlockHtml() + { + $tpl = $this->newBlockTemplate(); + + $this->renderGroupedItems( + $tpl, + $this->view->getItemGroups(), + ($this->getCurrentDetailLevel() >= $this->view->getMinimumDetailLevelForSection()) + ); + + if ($this->manage && $this->view->supportsSelectAll()) { + // #11355 - see ContainerContentGUI::renderSelectAllBlock() + $tpl->setCurrentBlock('select_all_row'); + $tpl->setVariable('CHECKBOXNAME', 'ilToolbarSelectAll'); + $tpl->setVariable('SEL_ALL_PARENT', 'ilToolbar'); + $tpl->setVariable('SEL_ALL_CB_NAME', 'id'); + $tpl->setVariable('TXT_SELECT_ALL', $this->lng->txt('select_all')); + $tpl->parseCurrentBlock(); + } + + return $tpl->get(); + } + + protected function resetRowType() + { + $this->cur_row_type = ""; + } + + /** + * returns a new list block template + * + * @access private + * @return object block template + */ + public function newBlockTemplate() + { + $tpl = new ilTemplate("tpl.pd_list_block.html", true, true, "Services/PersonalDesktop"); + $this->cur_row_type = ""; + return $tpl; + } + + /** + * @param ilTemplate $a_tpl + * @param ilPDSelectedItemsBlockGroup $group + */ + protected function addSectionHeader(ilTemplate $a_tpl, ilPDSelectedItemsBlockGroup $group) + { + if ($group->hasIcon()) { + $a_tpl->setCurrentBlock('container_header_row_image'); + $a_tpl->setVariable('HEADER_IMG', $group->getIconPath()); + $a_tpl->setVariable('HEADER_ALT', $group->getLabel()); + } else { + $a_tpl->setCurrentBlock('container_header_row'); + } + + $a_tpl->setVariable('BLOCK_HEADER_CONTENT', $group->getLabel()); + $a_tpl->setVariable('BLOCK_HEADER_ID', 'th_' . md5($group->getLabel())); + $a_tpl->parseCurrentBlock(); + + $a_tpl->touchBlock('container_row'); + + $this->resetRowType(); + } + + /** + * adds a standard row to a block template + * + * @param object $a_tpl block template + * @param string $a_html html code + * @access private + */ + public function addStandardRow( + &$a_tpl, + $a_html, + $a_item_ref_id = "", + $a_item_obj_id = "", + $a_image_type = "", + $a_related_header = "" + ) { + $ilSetting = $this->settings; + + $this->cur_row_type = ($this->cur_row_type == "row_type_1") + ? "row_type_2" + : "row_type_1"; + $a_tpl->touchBlock($this->cur_row_type); + + if ($a_image_type != "") { + if (!is_array($a_image_type) && !in_array($a_image_type, array("lm", "htlm", "sahs"))) { + $icon = ilUtil::getImagePath("icon_" . $a_image_type . ".svg"); + $title = $this->lng->txt("obj_" . $a_image_type); + } else { + $icon = ilUtil::getImagePath("icon_lm.svg"); + $title = $this->lng->txt("learning_module"); + } + + if ($ilSetting->get('custom_icons')) { + global $DIC; + /** @var \ilObjectCustomIconFactory $customIconFactory */ + $customIconFactory = $DIC['object.customicons.factory']; + $customIcon = $customIconFactory->getByObjId($a_item_obj_id, $a_image_type); + + if ($customIcon->exists()) { + $icon = $customIcon->getFullPath(); + } + } + + $a_tpl->setCurrentBlock("block_row_image"); + $a_tpl->setVariable("ROW_IMG", $icon); + $a_tpl->setVariable("ROW_ALT", $title); + $a_tpl->parseCurrentBlock(); + } else { + $a_tpl->setVariable("ROW_NBSP", " "); + } + $a_tpl->setCurrentBlock("container_standard_row"); + $a_tpl->setVariable("BLOCK_ROW_CONTENT", $a_html); + $rel_headers = ($a_related_header != "") + ? "th_selected_items " . $a_related_header + : "th_selected_items"; + $a_tpl->setVariable("BLOCK_ROW_HEADERS", $rel_headers); + $a_tpl->parseCurrentBlock(); + $a_tpl->touchBlock("container_row"); + } + + /** + * @param string $sort_type + */ + protected function changeSortMode($sort_type) + { + $this->user->writePref('pd_order_items', $sort_type); + $this->initViewSettings(); + + if ($this->ctrl->isAsynch()) { + echo $this->getHTML(); + exit; + } + + $this->ctrl->setParameterByClass('ilpersonaldesktopgui', 'view', $this->viewSettings->getCurrentView()); + $this->ctrl->redirectByClass('ilpersonaldesktopgui', 'show'); + } + + /** + * Sort desktop items by location + */ + public function orderPDItemsByLocation() + { + $this->changeSortMode($this->viewSettings->getSortByLocationMode()); + } + + /** + * Sort desktop items by Type + */ + public function orderPDItemsByType() + { + $this->changeSortMode($this->viewSettings->getSortByTypeMode()); + } + + /** + * Sort desktop items by start date + */ + public function orderPDItemsByStartDate() + { + $this->changeSortMode($this->viewSettings->getSortByStartDateMode()); + } + + public function manageObject() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->manage = true; + $this->setAvailableDetailLevels(1, 1); + + $top_tb = new ilToolbarGUI(); + $top_tb->setFormAction($ilCtrl->getFormAction($this)); + $top_tb->setLeadingImage(ilUtil::getImagePath("arrow_upright.svg"), $lng->txt("actions")); + + $button = ilSubmitButton::getInstance(); + if ($this->viewSettings->isSelectedItemsViewActive()) { + $button->setCaption("remove"); + } else { + $button->setCaption("pd_unsubscribe_memberships"); + } + $button->setCommand("confirmRemove"); + $top_tb->addStickyItem($button); + + $button2 = ilSubmitButton::getInstance(); + $button2->setCaption("cancel"); + $button2->setCommand("getHTML"); + $top_tb->addStickyItem($button2); + + $top_tb->setCloseFormTag(false); + + $bot_tb = new ilToolbarGUI(); + $bot_tb->setLeadingImage(ilUtil::getImagePath("arrow_downright.svg"), $lng->txt("actions")); + $bot_tb->addStickyItem($button); + $bot_tb->addStickyItem($button2); + $bot_tb->setOpenFormTag(false); + return $top_tb->getHTML() . $this->getHTML() . $bot_tb->getHTML(); + } + + public function confirmRemoveObject() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameter($this, 'view', $this->viewSettings->getCurrentView()); + if (!sizeof($_POST["id"])) { + ilUtil::sendFailure($this->lng->txt("select_one"), true); + $ilCtrl->redirect($this, "manage"); + } + + if ($this->viewSettings->isSelectedItemsViewActive()) { + $question = $this->lng->txt("pd_info_delete_sure_remove"); + $cmd = "confirmedRemove"; + } else { + $question = $this->lng->txt("pd_info_delete_sure_unsubscribe"); + $cmd = "confirmedUnsubscribe"; + } + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setHeaderText($question); + + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setCancel($this->lng->txt("cancel"), "manage"); + $cgui->setConfirm($this->lng->txt("confirm"), $cmd); + + foreach ($_POST["id"] as $ref_id) { + $obj_id = ilObject::_lookupObjectId($ref_id); + $title = ilObject::_lookupTitle($obj_id); + $type = ilObject::_lookupType($obj_id); + + $cgui->addItem( + "ref_id[]", + $ref_id, + $title, + ilObject::_getIcon($obj_id, "small", $type), + $this->lng->txt("icon") . " " . $this->lng->txt("obj_" . $type) + ); + } + + return $cgui->getHTML(); + } + + public function confirmedRemove() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + if (!sizeof($_POST["ref_id"])) { + $ilCtrl->redirect($this, "manage"); + } + + foreach ($_POST["ref_id"] as $ref_id) { + $type = ilObject::_lookupType($ref_id, true); + ilObjUser::_dropDesktopItem($ilUser->getId(), $ref_id, $type); + } + + // #12909 + ilUtil::sendSuccess($this->lng->txt("pd_remove_multi_confirm"), true); + $ilCtrl->setParameterByClass('ilpersonaldesktopgui', 'view', $this->viewSettings->getCurrentView()); + $ilCtrl->redirectByClass("ilpersonaldesktopgui", "show"); + } + + public function confirmedUnsubscribe() + { + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + $ilUser = $this->user; + + if (!sizeof($_POST["ref_id"])) { + $ilCtrl->redirect($this, "manage"); + } + + foreach ($_POST["ref_id"] as $ref_id) { + if ($ilAccess->checkAccess("leave", "", $ref_id)) { + switch (ilObject::_lookupType($ref_id, true)) { + case "crs": + // see ilObjCourseGUI:performUnsubscribeObject() + include_once "Modules/Course/classes/class.ilCourseParticipants.php"; + $members = new ilCourseParticipants(ilObject::_lookupObjId($ref_id)); + $members->delete($ilUser->getId()); + + $members->sendUnsubscribeNotificationToAdmins($ilUser->getId()); + $members->sendNotification( + $members->NOTIFY_UNSUBSCRIBE, + $ilUser->getId() + ); + break; + + case "grp": + // see ilObjGroupGUI:performUnsubscribeObject() + include_once "Modules/Group/classes/class.ilGroupParticipants.php"; + $members = new ilGroupParticipants(ilObject::_lookupObjId($ref_id)); + $members->delete($ilUser->getId()); + + include_once './Modules/Group/classes/class.ilGroupMembershipMailNotification.php'; + $members->sendNotification( + ilGroupMembershipMailNotification::TYPE_UNSUBSCRIBE_MEMBER, + $ilUser->getId() + ); + $members->sendNotification( + ilGroupMembershipMailNotification::TYPE_NOTIFICATION_UNSUBSCRIBE, + $ilUser->getId() + ); + break; + + default: + // do nothing + continue 2; + } + + include_once './Modules/Forum/classes/class.ilForumNotification.php'; + ilForumNotification::checkForumsExistsDelete($ref_id, $ilUser->getId()); + } + } + + + ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); + $ilCtrl->setParameterByClass('ilpersonaldesktopgui', 'view', $this->viewSettings->getCurrentView()); + $ilCtrl->redirectByClass("ilpersonaldesktopgui", "show"); + } +} diff --git a/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockGroup.php b/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockGroup.php index 713c7b18eefd8da174f4d12a240824fa25afa753..0193f9f713fc61d2f8ba7287e4737f9f836703e5 100644 --- a/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockGroup.php +++ b/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockGroup.php @@ -6,95 +6,95 @@ */ class ilPDSelectedItemsBlockGroup { - /** - * @var bool - */ - protected $has_icon = false; + /** + * @var bool + */ + protected $has_icon = false; - /** - * @var string - */ - protected $icon_path = ''; + /** + * @var string + */ + protected $icon_path = ''; - /** - * @var string - */ - protected $label = ''; + /** + * @var string + */ + protected $label = ''; - /** - * @var array - */ - protected $items = array(); + /** + * @var array + */ + protected $items = array(); - /** - * @return string - */ - public function getLabel() - { - return $this->label; - } + /** + * @return string + */ + public function getLabel() + { + return $this->label; + } - /** - * @return boolean - */ - public function hasIcon() - { - return strlen($this->icon_path) > 0; - } + /** + * @return boolean + */ + public function hasIcon() + { + return strlen($this->icon_path) > 0; + } - /** - * @string - */ - public function getIconPath() - { - return $this->icon_path; - } + /** + * @string + */ + public function getIconPath() + { + return $this->icon_path; + } - /** - * @param array[] $items - */ - public function setItems(array $items) - { - $this->items = $items; - } + /** + * @param array[] $items + */ + public function setItems(array $items) + { + $this->items = $items; + } - /** - * @param array $item - */ - public function pushItem(array $item) - { - $this->items[] = $item; - } + /** + * @param array $item + */ + public function pushItem(array $item) + { + $this->items[] = $item; + } - /** - * @param bool $has_icon - */ - public function setHasIcon($has_icon) - { - $this->has_icon = $has_icon; - } + /** + * @param bool $has_icon + */ + public function setHasIcon($has_icon) + { + $this->has_icon = $has_icon; + } - /** - * @param string $icon_path - */ - public function setIconPath($icon_path) - { - $this->icon_path = $icon_path; - } + /** + * @param string $icon_path + */ + public function setIconPath($icon_path) + { + $this->icon_path = $icon_path; + } - /** - * @param string $label - */ - public function setLabel($label) - { - $this->label = $label; - } + /** + * @param string $label + */ + public function setLabel($label) + { + $this->label = $label; + } - /** - * @return array - */ - public function getItems() - { - return $this->items; - } -} \ No newline at end of file + /** + * @return array + */ + public function getItems() + { + return $this->items; + } +} diff --git a/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockListGUIFactory.php b/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockListGUIFactory.php index b742be6d07ca65d64bbbee4302267107295af148..06c9a8ee940a1d5061602e9c62fe623f80733f1a 100644 --- a/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockListGUIFactory.php +++ b/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockListGUIFactory.php @@ -6,88 +6,83 @@ */ class ilPDSelectedItemsBlockListGUIFactory { - /** - * @var ilObjectListGUI[] - */ - protected static $list_by_type = array(); + /** + * @var ilObjectListGUI[] + */ + protected static $list_by_type = array(); - /** - * @var ilObjectDefinition - */ - protected $objDefinition; + /** + * @var ilObjectDefinition + */ + protected $objDefinition; - /** - * @var ilPDSelectedItemsBlockGUI - */ - protected $block; + /** + * @var ilPDSelectedItemsBlockGUI + */ + protected $block; - /** - * ilPDSelectedItemsBlockListGUIFactory constructor. - * @param ilPDSelectedItemsBlockGUI $block - */ - public function __construct(ilPDSelectedItemsBlockGUI $block) - { - global $DIC; + /** + * ilPDSelectedItemsBlockListGUIFactory constructor. + * @param ilPDSelectedItemsBlockGUI $block + */ + public function __construct(ilPDSelectedItemsBlockGUI $block) + { + global $DIC; - $this->objDefinition = $DIC['objDefinition']; - $this->block = $block; - } + $this->objDefinition = $DIC['objDefinition']; + $this->block = $block; + } - /** - * @param string $a_type - * @return ilObjectListGUI - * @throws ilException - */ - public function byType($a_type) - { - /** @var $item_list_gui ilObjectListGUI */ - if(!array_key_exists($a_type, self::$list_by_type)) - { - $class = $this->objDefinition->getClassName($a_type); - if(!$class) - { - throw new ilException(sprintf("Could not find a class for object type: %s", $a_type)); - } + /** + * @param string $a_type + * @return ilObjectListGUI + * @throws ilException + */ + public function byType($a_type) + { + /** @var $item_list_gui ilObjectListGUI */ + if (!array_key_exists($a_type, self::$list_by_type)) { + $class = $this->objDefinition->getClassName($a_type); + if (!$class) { + throw new ilException(sprintf("Could not find a class for object type: %s", $a_type)); + } - $location = $this->objDefinition->getLocation($a_type); - if(!$location) - { - throw new ilException(sprintf("Could not find a class location for object type: %s", $a_type)); - } + $location = $this->objDefinition->getLocation($a_type); + if (!$location) { + throw new ilException(sprintf("Could not find a class location for object type: %s", $a_type)); + } - $full_class = 'ilObj' . $class . 'ListGUI'; - require_once $location . '/class.' . $full_class . '.php'; - $item_list_gui = new $full_class(); + $full_class = 'ilObj' . $class . 'ListGUI'; + require_once $location . '/class.' . $full_class . '.php'; + $item_list_gui = new $full_class(); - $item_list_gui->setContainerObject($this->block); - $item_list_gui->enableNotes(false); - $item_list_gui->enableComments(false); - $item_list_gui->enableTags(false); + $item_list_gui->setContainerObject($this->block); + $item_list_gui->enableNotes(false); + $item_list_gui->enableComments(false); + $item_list_gui->enableTags(false); - $item_list_gui->enableIcon(true); - $item_list_gui->enableDelete(false); - $item_list_gui->enableCut(false); - $item_list_gui->enableCopy(false); - $item_list_gui->enableLink(false); - $item_list_gui->enableInfoScreen(true); - $item_list_gui->enableSubscribe($this->block->getViewSettings()->enabledSelectedItems()); + $item_list_gui->enableIcon(true); + $item_list_gui->enableDelete(false); + $item_list_gui->enableCut(false); + $item_list_gui->enableCopy(false); + $item_list_gui->enableLink(false); + $item_list_gui->enableInfoScreen(true); + $item_list_gui->enableSubscribe($this->block->getViewSettings()->enabledSelectedItems()); - if($this->block->getCurrentDetailLevel() < 3 || $this->block->isManagedView()) - { - $item_list_gui->enableDescription(false); - $item_list_gui->enableProperties(false); - $item_list_gui->enablePreconditions(false); - $item_list_gui->enableNoticeProperties(false); - } + if ($this->block->getCurrentDetailLevel() < 3 || $this->block->isManagedView()) { + $item_list_gui->enableDescription(false); + $item_list_gui->enableProperties(false); + $item_list_gui->enablePreconditions(false); + $item_list_gui->enableNoticeProperties(false); + } - if($this->block->getCurrentDetailLevel() < 2 || $this->block->isManagedView()) - { - $item_list_gui->enableCommands(true, true); - } + if ($this->block->getCurrentDetailLevel() < 2 || $this->block->isManagedView()) { + $item_list_gui->enableCommands(true, true); + } - self::$list_by_type[$a_type] = $item_list_gui; - } + self::$list_by_type[$a_type] = $item_list_gui; + } - return (clone self::$list_by_type[$a_type]); - } -} \ No newline at end of file + return (clone self::$list_by_type[$a_type]); + } +} diff --git a/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockMembershipsProvider.php b/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockMembershipsProvider.php index 794fe11d2261368ef9e050e10fe93f95663668bb..d8cac0328183f9c9ab0d676b7d6ac73bf77046af 100644 --- a/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockMembershipsProvider.php +++ b/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockMembershipsProvider.php @@ -9,100 +9,92 @@ require_once 'Services/PersonalDesktop/ItemsBlock/interfaces/interface.ilPDSelec */ class ilPDSelectedItemsBlockMembershipsProvider implements ilPDSelectedItemsBlockProvider { - /** - * @var ilObjUser - */ - protected $actor; + /** + * @var ilObjUser + */ + protected $actor; - /** - * @var ilTree - */ - protected $tree; + /** + * @var ilTree + */ + protected $tree; - /** - * ilPDSelectedItemsBlockSelectedItemsProvider constructor. - * @param ilObjUser $actor - */ - public function __construct(ilObjUser $actor) - { - global $DIC; + /** + * ilPDSelectedItemsBlockSelectedItemsProvider constructor. + * @param ilObjUser $actor + */ + public function __construct(ilObjUser $actor) + { + global $DIC; - $this->actor = $actor; - $this->tree = $DIC->repositoryTree(); - } + $this->actor = $actor; + $this->tree = $DIC->repositoryTree(); + } - /** - * Gets all objects the current user is member of - * @param array $types - * @return array array of objects - */ - protected function getObjectsByMembership($types = array()) - { - $items = array(); + /** + * Gets all objects the current user is member of + * @param array $types + * @return array array of objects + */ + protected function getObjectsByMembership($types = array()) + { + $items = array(); - if(is_array($types) && count($types)) - { - foreach($types as $type) - { - switch($type) - { - case 'grp': - $items = array_merge(ilParticipants::_getMembershipByType($this->actor->getId(), 'grp'), $items); - break; - case 'crs': - $items = array_merge(ilParticipants::_getMembershipByType($this->actor->getId(), 'crs'), $items); - break; - default: - break; - } - } - } - else - { - $crs_mbs = ilParticipants::_getMembershipByType($this->actor->getId(), 'crs'); - $grp_mbs = ilParticipants::_getMembershipByType($this->actor->getId(), 'grp'); - $items = array_merge($crs_mbs, $grp_mbs); - } + if (is_array($types) && count($types)) { + foreach ($types as $type) { + switch ($type) { + case 'grp': + $items = array_merge(ilParticipants::_getMembershipByType($this->actor->getId(), 'grp'), $items); + break; + case 'crs': + $items = array_merge(ilParticipants::_getMembershipByType($this->actor->getId(), 'crs'), $items); + break; + default: + break; + } + } + } else { + $crs_mbs = ilParticipants::_getMembershipByType($this->actor->getId(), 'crs'); + $grp_mbs = ilParticipants::_getMembershipByType($this->actor->getId(), 'grp'); + $items = array_merge($crs_mbs, $grp_mbs); + } - $references = array(); + $references = array(); - foreach($items as $key => $obj_id) - { - $item_references = ilObject::_getAllReferences($obj_id); - foreach($item_references as $ref_id) - { - if($this->tree->isInTree($ref_id)) - { - $object = ilObjectFactory::getInstanceByRefId($ref_id); + foreach ($items as $key => $obj_id) { + $item_references = ilObject::_getAllReferences($obj_id); + foreach ($item_references as $ref_id) { + if ($this->tree->isInTree($ref_id)) { + $object = ilObjectFactory::getInstanceByRefId($ref_id); - $parent_ref_id = $this->tree->getParentId($ref_id); - $par_left = $this->tree->getLeftValue($parent_ref_id); - $par_left = sprintf("%010d", $par_left); + $parent_ref_id = $this->tree->getParentId($ref_id); + $par_left = $this->tree->getLeftValue($parent_ref_id); + $par_left = sprintf("%010d", $par_left); - $references[$par_left . $object->getTitle() . $ref_id] = array( - 'ref_id' => $ref_id, - 'obj_id' => $obj_id, - 'type' => $object->getType(), - 'title' => $object->getTitle(), - 'description' => $object->getDescription(), - 'parent_ref' => $parent_ref_id, - 'start' => $object->getType() == 'grp' ? $object->getStart() : $object->getCourseStart(), - 'end' => $object->getType() == 'grp' ? $object->getEnd() : $object->getCourseEnd() - ); - } - } - } + $references[$par_left . $object->getTitle() . $ref_id] = array( + 'ref_id' => $ref_id, + 'obj_id' => $obj_id, + 'type' => $object->getType(), + 'title' => $object->getTitle(), + 'description' => $object->getDescription(), + 'parent_ref' => $parent_ref_id, + 'start' => $object->getType() == 'grp' ? $object->getStart() : $object->getCourseStart(), + 'end' => $object->getType() == 'grp' ? $object->getEnd() : $object->getCourseEnd() + ); + } + } + } - ksort($references); + ksort($references); - return $references; - } + return $references; + } - /** - * @inheritdoc - */ - public function getItems($object_type_white_list = array()) - { - return $this->getObjectsByMembership($object_type_white_list); - } -} \ No newline at end of file + /** + * @inheritdoc + */ + public function getItems($object_type_white_list = array()) + { + return $this->getObjectsByMembership($object_type_white_list); + } +} diff --git a/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockMembershipsViewGUI.php b/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockMembershipsViewGUI.php index 45efd93c17ec0d6306b1f3f98a0f4a2bd44ab7e3..769926098a788dd10a68556e0e0619e311fc6b7c 100644 --- a/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockMembershipsViewGUI.php +++ b/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockMembershipsViewGUI.php @@ -8,65 +8,62 @@ require_once 'Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItem */ class ilPDSelectedItemsBlockMembershipsViewGUI extends ilPDSelectedItemsBlockViewGUI { - /** - * @inheritdoc - */ - public function getGroups() - { - if($this->viewSettings->isSortedByLocation()) - { - return $this->groupItemsByLocation(); - } - else if($this->viewSettings->isSortedByStartDate()) - { - return $this->groupItemsByStartDate(); - } + /** + * @inheritdoc + */ + public function getGroups() + { + if ($this->viewSettings->isSortedByLocation()) { + return $this->groupItemsByLocation(); + } elseif ($this->viewSettings->isSortedByStartDate()) { + return $this->groupItemsByStartDate(); + } - return $this->groupItemsByType(); - } + return $this->groupItemsByType(); + } - /** - * @inheritdoc - */ - public function getScreenId() - { - return 'crs_grp'; - } + /** + * @inheritdoc + */ + public function getScreenId() + { + return 'crs_grp'; + } - /** - * @inheritdoc - */ - public function getTitle() - { - return $this->lng->txt('pd_my_memberships'); - } + /** + * @inheritdoc + */ + public function getTitle() + { + return $this->lng->txt('pd_my_memberships'); + } - /** - * @inheritdoc - */ - public function supportsSelectAll() - { - return false; - } + /** + * @inheritdoc + */ + public function supportsSelectAll() + { + return false; + } - /** - * @inheritdoc - */ - public function mayRemoveItem($refId) - { - return $this->accessHandler->checkAccess('leave', $refId); - } + /** + * @inheritdoc + */ + public function mayRemoveItem($refId) + { + return $this->accessHandler->checkAccess('leave', $refId); + } - /** - * @inheritdoc - */ - public function getIntroductionHtml() - { - $tpl = new ilTemplate('tpl.pd_my_memberships_intro.html', true, true, 'Services/PersonalDesktop'); - $tpl->setVariable('IMG_PD_LARGE', ilObject::_getIcon('', 'big', 'pd')); - $tpl->setVariable('TXT_WELCOME', $this->lng->txt('pd_my_memberships_intro')); - $tpl->setVariable('TXT_INTRO_1', $this->lng->txt('pd_my_memberships_intro2')); + /** + * @inheritdoc + */ + public function getIntroductionHtml() + { + $tpl = new ilTemplate('tpl.pd_my_memberships_intro.html', true, true, 'Services/PersonalDesktop'); + $tpl->setVariable('IMG_PD_LARGE', ilObject::_getIcon('', 'big', 'pd')); + $tpl->setVariable('TXT_WELCOME', $this->lng->txt('pd_my_memberships_intro')); + $tpl->setVariable('TXT_INTRO_1', $this->lng->txt('pd_my_memberships_intro2')); - return $tpl->get(); - } -} \ No newline at end of file + return $tpl->get(); + } +} diff --git a/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockSelectedItemsProvider.php b/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockSelectedItemsProvider.php index 0f2fb6c3b7bc6fa82aa4ae91ed00b51cab036c2d..3b2c09ee94afd7cc8ee2a4e18b44fe93773ec749 100644 --- a/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockSelectedItemsProvider.php +++ b/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockSelectedItemsProvider.php @@ -8,25 +8,25 @@ require_once 'Services/PersonalDesktop/ItemsBlock/interfaces/interface.ilPDSelec */ class ilPDSelectedItemsBlockSelectedItemsProvider implements ilPDSelectedItemsBlockProvider { - /** - * @var ilObjUser - */ - protected $actor; + /** + * @var ilObjUser + */ + protected $actor; - /** - * ilPDSelectedItemsBlockSelectedItemsProvider constructor. - * @param ilObjUser $actor - */ - public function __construct(ilObjUser $actor) - { - $this->actor = $actor; - } + /** + * ilPDSelectedItemsBlockSelectedItemsProvider constructor. + * @param ilObjUser $actor + */ + public function __construct(ilObjUser $actor) + { + $this->actor = $actor; + } - /** - * @inheritdoc - */ - public function getItems($object_type_white_list = array()) - { - return $this->actor->getDesktopItems(count($object_type_white_list) > 0 ? $object_type_white_list : ''); - } -} \ No newline at end of file + /** + * @inheritdoc + */ + public function getItems($object_type_white_list = array()) + { + return $this->actor->getDesktopItems(count($object_type_white_list) > 0 ? $object_type_white_list : ''); + } +} diff --git a/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockSelectedItemsViewGUI.php b/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockSelectedItemsViewGUI.php index cd03ffe7922f972b935fdec5dfd3d786fd63cab4..98e3e8cce11eb9860e27c4f5b13a3e54a43d8ce3 100644 --- a/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockSelectedItemsViewGUI.php +++ b/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockSelectedItemsViewGUI.php @@ -8,60 +8,59 @@ require_once 'Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItem */ class ilPDSelectedItemsBlockSelectedItemsViewGUI extends ilPDSelectedItemsBlockViewGUI { - /** - * @inheritdoc - */ - public function getGroups() - { - if($this->viewSettings->isSortedByLocation()) - { - return $this->groupItemsByLocation(); - } + /** + * @inheritdoc + */ + public function getGroups() + { + if ($this->viewSettings->isSortedByLocation()) { + return $this->groupItemsByLocation(); + } - return $this->groupItemsByType(); - } + return $this->groupItemsByType(); + } - /** - * @inheritdoc - */ - public function getScreenId() - { - return 'sel_items'; - } + /** + * @inheritdoc + */ + public function getScreenId() + { + return 'sel_items'; + } - /** - * @inheritdoc - */ - public function getTitle() - { - return $this->lng->txt('pd_my_offers'); - } + /** + * @inheritdoc + */ + public function getTitle() + { + return $this->lng->txt('pd_my_offers'); + } - /** - * @inheritdoc - */ - public function supportsSelectAll() - { - return true; - } + /** + * @inheritdoc + */ + public function supportsSelectAll() + { + return true; + } - /** - * @inheritdoc - */ - public function getIntroductionHtml() - { - $tpl = new ilTemplate('tpl.pd_intro.html', true, true, 'Services/PersonalDesktop'); - $tpl->setVariable('IMG_PD_LARGE', ilObject::_getIcon('', 'big', 'pd')); - $tpl->setVariable('TXT_WELCOME', $this->lng->txt('pdesk_intro')); - $tpl->setVariable("TXT_INTRO_1", sprintf($this->lng->txt('pdesk_intro2'), $this->lng->txt('to_desktop'))); - - require_once 'Services/Link/classes/class.ilLink.php'; - $tpl->setVariable('TXT_INTRO_2', sprintf( - $this->lng->txt('pdesk_intro3'), - '' . $this->getRepositoryTitle() . '' - )); - $tpl->setVariable('TXT_INTRO_3', $this->lng->txt('pdesk_intro4')); + /** + * @inheritdoc + */ + public function getIntroductionHtml() + { + $tpl = new ilTemplate('tpl.pd_intro.html', true, true, 'Services/PersonalDesktop'); + $tpl->setVariable('IMG_PD_LARGE', ilObject::_getIcon('', 'big', 'pd')); + $tpl->setVariable('TXT_WELCOME', $this->lng->txt('pdesk_intro')); + $tpl->setVariable("TXT_INTRO_1", sprintf($this->lng->txt('pdesk_intro2'), $this->lng->txt('to_desktop'))); + + require_once 'Services/Link/classes/class.ilLink.php'; + $tpl->setVariable('TXT_INTRO_2', sprintf( + $this->lng->txt('pdesk_intro3'), + '' . $this->getRepositoryTitle() . '' + )); + $tpl->setVariable('TXT_INTRO_3', $this->lng->txt('pdesk_intro4')); - return $tpl->get(); - } -} \ No newline at end of file + return $tpl->get(); + } +} diff --git a/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockViewGUI.php b/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockViewGUI.php index 71e92cadf3c8766373bd3b2f5fb14862612f185d..c7310c0d2f83e1639ba30efc067b01052bccb5bc 100644 --- a/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockViewGUI.php +++ b/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockViewGUI.php @@ -8,365 +8,334 @@ require_once 'Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItem */ abstract class ilPDSelectedItemsBlockViewGUI { - /** - * @var ilPDSelectedItemsBlockViewSettings - */ - protected $viewSettings; - - /** - * @var ilPDSelectedItemsBlockProvider - */ - protected $provider; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var $tree ilTree - */ - protected $tree; - - /** - * @var ilObjectDataCache - */ - protected $object_cache; - - /** - * @var ilRbacSystem - */ - protected $accessHandler; - - /** - * ilPDSelectedItemsBlockViewGUI constructor. - * @param ilPDSelectedItemsBlockViewSettings $viewSettings - * @param ilPDSelectedItemsBlockProvider $provider - */ - final private function __construct(ilPDSelectedItemsBlockViewSettings $viewSettings, ilPDSelectedItemsBlockProvider $provider) - { - global $DIC; - - $this->lng = $DIC->language(); - $this->tree = $DIC->repositoryTree(); - $this->object_cache = $DIC['ilObjDataCache']; - $this->accessHandler = $DIC->rbac()->system(); - - $this->viewSettings = $viewSettings; - $this->provider = $provider; - } - - /** - * @return string - */ - abstract public function getScreenId(); - - /** - * @return string - */ - abstract public function getTitle(); - - /** - * @return int - */ - public function getMinimumDetailLevelForSection() - { - if($this->viewSettings->isSortedByLocation()) - { - return 1; - } - - return 3; - } - - /** - * @return boolean - */ - abstract public function supportsSelectAll(); - - /** - * @return string - */ - abstract function getIntroductionHtml(); - - /** - * @return ilPDSelectedItemsBlockGroup[] - */ - abstract function getGroups(); - - /** - * @param int $refId - * @return bool - */ - public function mayRemoveItem($refId) - { - return true; - } - - /** - * @return ilPDSelectedItemsBlockGroup[] - */ - public function getItemGroups() - { - $items_groups = $this->getGroups(); - - $this->preloadItemGroups($items_groups); - - return $items_groups; - } - - /** - * @param ilPDSelectedItemsBlockViewSettings $viewSettings - * @return self - */ - public static function bySettings(ilPDSelectedItemsBlockViewSettings $viewSettings) - { - if($viewSettings->isMembershipsViewActive()) - { - require_once 'Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockMembershipsViewGUI.php'; - require_once 'Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockMembershipsProvider.php'; - return new ilPDSelectedItemsBlockMembershipsViewGUI( - $viewSettings, new ilPDSelectedItemsBlockMembershipsProvider($viewSettings->getActor()) - ); - } - - require_once 'Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockSelectedItemsViewGUI.php'; - require_once 'Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockSelectedItemsProvider.php'; - return new ilPDSelectedItemsBlockSelectedItemsViewGUI( - $viewSettings, new ilPDSelectedItemsBlockSelectedItemsProvider($viewSettings->getActor()) - ); - } - - /** - * @param int $refId - * @return bool - */ - protected function isRootNode($refId) - { - return $this->tree->getRootId() == $refId; - } - - /** - * @return string - */ - protected function getRepositoryTitle() - { - $nd = $this->tree->getNodeData($this->tree->getRootId()); - $title = $nd['title']; - - if($title == 'ILIAS') - { - $title = $this->lng->txt('repository'); - } - - return $title; - } - - /** - * @param ilPDSelectedItemsBlockGroup[] $item_groups - */ - protected function preloadItemGroups(array $item_groups) - { - require_once 'Services/Object/classes/class.ilObjectListGUIPreloader.php'; - $listPreloader = new ilObjectListGUIPreloader(ilObjectListGUI::CONTEXT_PERSONAL_DESKTOP); - - $obj_ids = []; - foreach($item_groups as $item_group) - { - foreach($item_group->getItems() as $item) - { - $obj_ids[] = $item['obj_id']; - $listPreloader->addItem($item['obj_id'], $item['type'], $item['ref_id']); - } - } - - $listPreloader->preload(); - ilAdvancedMDValues::preloadByObjIds($obj_ids); - } - - /** - * @return ilPDSelectedItemsBlockGroup[] - */ - protected function groupItemsByType() - { - global $DIC; - - $objDefinition = $DIC["objDefinition"]; - - $object_types_by_container = $DIC['objDefinition']->getGroupedRepositoryObjectTypes(array('cat', 'crs', 'grp', 'fold')); - - $grouped_items = array(); - - foreach($object_types_by_container as $container_object_type => $container_data) - { - $group = new ilPDSelectedItemsBlockGroup(); - // Icons are currently not determined for section header objects - if (!$objDefinition->isPlugin($container_object_type)) - { - $title = $this->lng->txt('objs_'. $container_object_type); + /** + * @var ilPDSelectedItemsBlockViewSettings + */ + protected $viewSettings; + + /** + * @var ilPDSelectedItemsBlockProvider + */ + protected $provider; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var $tree ilTree + */ + protected $tree; + + /** + * @var ilObjectDataCache + */ + protected $object_cache; + + /** + * @var ilRbacSystem + */ + protected $accessHandler; + + /** + * ilPDSelectedItemsBlockViewGUI constructor. + * @param ilPDSelectedItemsBlockViewSettings $viewSettings + * @param ilPDSelectedItemsBlockProvider $provider + */ + final private function __construct(ilPDSelectedItemsBlockViewSettings $viewSettings, ilPDSelectedItemsBlockProvider $provider) + { + global $DIC; + + $this->lng = $DIC->language(); + $this->tree = $DIC->repositoryTree(); + $this->object_cache = $DIC['ilObjDataCache']; + $this->accessHandler = $DIC->rbac()->system(); + + $this->viewSettings = $viewSettings; + $this->provider = $provider; + } + + /** + * @return string + */ + abstract public function getScreenId(); + + /** + * @return string + */ + abstract public function getTitle(); + + /** + * @return int + */ + public function getMinimumDetailLevelForSection() + { + if ($this->viewSettings->isSortedByLocation()) { + return 1; + } + + return 3; + } + + /** + * @return boolean + */ + abstract public function supportsSelectAll(); + + /** + * @return string + */ + abstract public function getIntroductionHtml(); + + /** + * @return ilPDSelectedItemsBlockGroup[] + */ + abstract public function getGroups(); + + /** + * @param int $refId + * @return bool + */ + public function mayRemoveItem($refId) + { + return true; + } + + /** + * @return ilPDSelectedItemsBlockGroup[] + */ + public function getItemGroups() + { + $items_groups = $this->getGroups(); + + $this->preloadItemGroups($items_groups); + + return $items_groups; + } + + /** + * @param ilPDSelectedItemsBlockViewSettings $viewSettings + * @return self + */ + public static function bySettings(ilPDSelectedItemsBlockViewSettings $viewSettings) + { + if ($viewSettings->isMembershipsViewActive()) { + require_once 'Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockMembershipsViewGUI.php'; + require_once 'Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockMembershipsProvider.php'; + return new ilPDSelectedItemsBlockMembershipsViewGUI( + $viewSettings, + new ilPDSelectedItemsBlockMembershipsProvider($viewSettings->getActor()) + ); + } + + require_once 'Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockSelectedItemsViewGUI.php'; + require_once 'Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockSelectedItemsProvider.php'; + return new ilPDSelectedItemsBlockSelectedItemsViewGUI( + $viewSettings, + new ilPDSelectedItemsBlockSelectedItemsProvider($viewSettings->getActor()) + ); + } + + /** + * @param int $refId + * @return bool + */ + protected function isRootNode($refId) + { + return $this->tree->getRootId() == $refId; + } + + /** + * @return string + */ + protected function getRepositoryTitle() + { + $nd = $this->tree->getNodeData($this->tree->getRootId()); + $title = $nd['title']; + + if ($title == 'ILIAS') { + $title = $this->lng->txt('repository'); + } + + return $title; + } + + /** + * @param ilPDSelectedItemsBlockGroup[] $item_groups + */ + protected function preloadItemGroups(array $item_groups) + { + require_once 'Services/Object/classes/class.ilObjectListGUIPreloader.php'; + $listPreloader = new ilObjectListGUIPreloader(ilObjectListGUI::CONTEXT_PERSONAL_DESKTOP); + + $obj_ids = []; + foreach ($item_groups as $item_group) { + foreach ($item_group->getItems() as $item) { + $obj_ids[] = $item['obj_id']; + $listPreloader->addItem($item['obj_id'], $item['type'], $item['ref_id']); } - else - { + } + + $listPreloader->preload(); + ilAdvancedMDValues::preloadByObjIds($obj_ids); + } + + /** + * @return ilPDSelectedItemsBlockGroup[] + */ + protected function groupItemsByType() + { + global $DIC; + + $objDefinition = $DIC["objDefinition"]; + + $object_types_by_container = $DIC['objDefinition']->getGroupedRepositoryObjectTypes(array('cat', 'crs', 'grp', 'fold')); + + $grouped_items = array(); + + foreach ($object_types_by_container as $container_object_type => $container_data) { + $group = new ilPDSelectedItemsBlockGroup(); + // Icons are currently not determined for section header objects + if (!$objDefinition->isPlugin($container_object_type)) { + $title = $this->lng->txt('objs_' . $container_object_type); + } else { include_once("./Services/Component/classes/class.ilPlugin.php"); $pl = ilObjectPlugin::getPluginObjectByType($container_object_type); - $title= $pl->txt("objs_".$container_object_type); + $title= $pl->txt("objs_" . $container_object_type); } $group->setLabel($title); - $group->setItems($this->provider->getItems($container_data['objs'])); - - $grouped_items[] = $group; - } - - return $grouped_items; - } - - /** - * @return ilPDSelectedItemsBlockGroup[] - */ - protected function groupItemsByStartDate() - { - $items = $this->provider->getItems(); - - if(0 == count($items)) - { - return array(); - } - - $groups = array( - 'upcoming' => array(), - 'ongoing' => array(), - 'ended' => array(), - 'not_dated' => array() - ); - - foreach($items as $key => $item) - { - if($item['start'] && $item['start'] && $item['start'] instanceof ilDate) - { - if($item['start']->get(IL_CAL_UNIX) > time()) - { - $groups['upcoming'][] = $item; - } - else if($item['end']->get(IL_CAL_UNIX) > time()) - { - $groups['ongoing'][] = $item; - } - else - { - $groups['ended'][] = $item; - } - } - else - { - $groups['not_dated'][] = $item; - } - } - - uasort($groups['upcoming'], function($left, $right) { - if($left['start']->get(IL_CAL_UNIX) < $right['start']->get(IL_CAL_UNIX)) - { - return -1; - } - else if($left['start']->get(IL_CAL_UNIX) > $right['start']->get(IL_CAL_UNIX)) - { - return 1; - } - - return strcmp($left['title'], $right['title']); - }); - - uasort($groups['ongoing'], function($left, $right) { - if($left['start']->get(IL_CAL_UNIX) < $right['start']->get(IL_CAL_UNIX)) - { - return 1; - } - else if($left['start']->get(IL_CAL_UNIX) > $right['start']->get(IL_CAL_UNIX)) - { - return -1; - } - - return strcmp($left['title'], $right['title']); - }); - - uasort($groups['ended'], function($left, $right) { - if($left['start']->get(IL_CAL_UNIX) < $right['start']->get(IL_CAL_UNIX)) - { - return 1; - } - else if($left['start']->get(IL_CAL_UNIX) > $right['start']->get(IL_CAL_UNIX)) - { - return -1; - } - - return strcmp($left['title'], $right['title']); - }); - - uasort($groups['not_dated'], function($left, $right) { - return strcmp($left['title'], $right['title']); - }); - - $upcoming = new ilPDSelectedItemsBlockGroup(); - $upcoming->setLabel($this->lng->txt('pd_upcoming')); - $upcoming->setItems($groups['upcoming']); - - $ongoing = new ilPDSelectedItemsBlockGroup(); - $ongoing->setLabel($this->lng->txt('pd_ongoing')); - $ongoing->setItems($groups['ongoing']); - - $ended = new ilPDSelectedItemsBlockGroup(); - $ended->setLabel($this->lng->txt('pd_ended')); - $ended->setItems($groups['ended']); - - $not_dated = new ilPDSelectedItemsBlockGroup(); - $not_dated->setLabel($this->lng->txt('pd_not_date')); - $not_dated->setItems($groups['not_dated']); - - return array_filter([ - $upcoming, - $ongoing, - $ended, - $not_dated - ], function(ilPDSelectedItemsBlockGroup $group) { - return count($group->getItems()) > 0; - }); - } - - /** - * @return ilPDSelectedItemsBlockGroup[] - */ - protected function groupItemsByLocation() - { - $grouped_items = array(); - - $items = $this->provider->getItems(); - - $parent_ref_ids = array_values(array_unique(array_map(function($item) { - return $item['parent_ref']; - }, $items))); - $this->object_cache->preloadReferenceCache($parent_ref_ids); - - foreach($items as $key => $item) - { - if(!array_key_exists('grp_' . $item['parent_ref'], $grouped_items)) - { - $group = new ilPDSelectedItemsBlockGroup(); - /* The parent objects of items grouped by location do not need an image (per current concept), so - we do not determine images to reduced the runtime/memory */ - if($this->isRootNode($item['parent_ref'])) - { - $group->setLabel($this->getRepositoryTitle()); - } - else - { - $group->setLabel($this->object_cache->lookupTitle($this->object_cache->lookupObjId($item['parent_ref']))); - } - $grouped_items['grp_' . $item['parent_ref']] = $group; - } - - $grouped_items['grp_' . $item['parent_ref']]->pushItem($item); - } - - return $grouped_items; - } -} \ No newline at end of file + $group->setItems($this->provider->getItems($container_data['objs'])); + + $grouped_items[] = $group; + } + + return $grouped_items; + } + + /** + * @return ilPDSelectedItemsBlockGroup[] + */ + protected function groupItemsByStartDate() + { + $items = $this->provider->getItems(); + + if (0 == count($items)) { + return array(); + } + + $groups = array( + 'upcoming' => array(), + 'ongoing' => array(), + 'ended' => array(), + 'not_dated' => array() + ); + + foreach ($items as $key => $item) { + if ($item['start'] && $item['start'] && $item['start'] instanceof ilDate) { + if ($item['start']->get(IL_CAL_UNIX) > time()) { + $groups['upcoming'][] = $item; + } elseif ($item['end']->get(IL_CAL_UNIX) > time()) { + $groups['ongoing'][] = $item; + } else { + $groups['ended'][] = $item; + } + } else { + $groups['not_dated'][] = $item; + } + } + + uasort($groups['upcoming'], function ($left, $right) { + if ($left['start']->get(IL_CAL_UNIX) < $right['start']->get(IL_CAL_UNIX)) { + return -1; + } elseif ($left['start']->get(IL_CAL_UNIX) > $right['start']->get(IL_CAL_UNIX)) { + return 1; + } + + return strcmp($left['title'], $right['title']); + }); + + uasort($groups['ongoing'], function ($left, $right) { + if ($left['start']->get(IL_CAL_UNIX) < $right['start']->get(IL_CAL_UNIX)) { + return 1; + } elseif ($left['start']->get(IL_CAL_UNIX) > $right['start']->get(IL_CAL_UNIX)) { + return -1; + } + + return strcmp($left['title'], $right['title']); + }); + + uasort($groups['ended'], function ($left, $right) { + if ($left['start']->get(IL_CAL_UNIX) < $right['start']->get(IL_CAL_UNIX)) { + return 1; + } elseif ($left['start']->get(IL_CAL_UNIX) > $right['start']->get(IL_CAL_UNIX)) { + return -1; + } + + return strcmp($left['title'], $right['title']); + }); + + uasort($groups['not_dated'], function ($left, $right) { + return strcmp($left['title'], $right['title']); + }); + + $upcoming = new ilPDSelectedItemsBlockGroup(); + $upcoming->setLabel($this->lng->txt('pd_upcoming')); + $upcoming->setItems($groups['upcoming']); + + $ongoing = new ilPDSelectedItemsBlockGroup(); + $ongoing->setLabel($this->lng->txt('pd_ongoing')); + $ongoing->setItems($groups['ongoing']); + + $ended = new ilPDSelectedItemsBlockGroup(); + $ended->setLabel($this->lng->txt('pd_ended')); + $ended->setItems($groups['ended']); + + $not_dated = new ilPDSelectedItemsBlockGroup(); + $not_dated->setLabel($this->lng->txt('pd_not_date')); + $not_dated->setItems($groups['not_dated']); + + return array_filter([ + $upcoming, + $ongoing, + $ended, + $not_dated + ], function (ilPDSelectedItemsBlockGroup $group) { + return count($group->getItems()) > 0; + }); + } + + /** + * @return ilPDSelectedItemsBlockGroup[] + */ + protected function groupItemsByLocation() + { + $grouped_items = array(); + + $items = $this->provider->getItems(); + + $parent_ref_ids = array_values(array_unique(array_map(function ($item) { + return $item['parent_ref']; + }, $items))); + $this->object_cache->preloadReferenceCache($parent_ref_ids); + + foreach ($items as $key => $item) { + if (!array_key_exists('grp_' . $item['parent_ref'], $grouped_items)) { + $group = new ilPDSelectedItemsBlockGroup(); + /* The parent objects of items grouped by location do not need an image (per current concept), so + we do not determine images to reduced the runtime/memory */ + if ($this->isRootNode($item['parent_ref'])) { + $group->setLabel($this->getRepositoryTitle()); + } else { + $group->setLabel($this->object_cache->lookupTitle($this->object_cache->lookupObjId($item['parent_ref']))); + } + $grouped_items['grp_' . $item['parent_ref']] = $group; + } + + $grouped_items['grp_' . $item['parent_ref']]->pushItem($item); + } + + return $grouped_items; + } +} diff --git a/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockViewSettings.php b/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockViewSettings.php index 683a64b463a46765512d6fd056f21b64939ac073..ddfbbbe281c0d54ddec73742c74ad518addfe686 100644 --- a/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockViewSettings.php +++ b/Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockViewSettings.php @@ -8,335 +8,327 @@ require_once 'Services/PersonalDesktop/ItemsBlock/interfaces/interface.ilPDSelec */ class ilPDSelectedItemsBlockViewSettings implements ilPDSelectedItemsBlockConstants { - /** - * @var array - */ - protected static $availableViews = array( - self::VIEW_SELECTED_ITEMS, - self::VIEW_MY_MEMBERSHIPS, - self::VIEW_MY_STUDYPROGRAMME - ); - - /** - * @var array - */ - protected static $availableSortOptions = array( - self::SORT_BY_LOCATION, - self::SORT_BY_TYPE, - self::SORT_BY_START_DATE - ); - - /** - * @var array - */ - protected static $availableSortOptionsByView = array( - self::VIEW_SELECTED_ITEMS => array( - self::SORT_BY_LOCATION, - self::SORT_BY_TYPE - ), - self::VIEW_MY_MEMBERSHIPS => array( - self::SORT_BY_LOCATION, - self::SORT_BY_TYPE, - self::SORT_BY_START_DATE - ), - self::VIEW_MY_STUDYPROGRAMME => array( - ) - ); - - /** - * @var ilSetting - */ - protected $settings; - - /** - * @var ilObjUser - */ - protected $actor; - - /** - * @var array - */ - protected $validViews = array(); - - /** - * @var int - */ - protected $currentView = self::VIEW_SELECTED_ITEMS; - - /** - * @var int - */ - protected $currentSortOption = self::SORT_BY_LOCATION; - - /** - * ilPDSelectedItemsBlockViewSettings constructor. - * @param ilObjUser $actor - * @param int $view - */ - public function __construct($actor, $view = self::VIEW_SELECTED_ITEMS) - { - global $DIC; - - $ilSetting = $DIC->settings(); - - $this->settings = $ilSetting; - - $this->actor = $actor; - $this->currentView = $view; - } - - /** - * @return int - */ - public function getMembershipsView() - { - return self::VIEW_MY_MEMBERSHIPS; - } - - /** - * @return int - */ - public function getSelectedItemsView() - { - return self::VIEW_SELECTED_ITEMS; - } - - /** - * @return int - */ - public function getStudyProgrammeView() - { - return self::VIEW_MY_STUDYPROGRAMME; - } - - /** - * @return boolean - */ - public function isMembershipsViewActive() - { - return $this->currentView == $this->getMembershipsView(); - } - - /** - * @return boolean - */ - public function isSelectedItemsViewActive() - { - return $this->currentView == $this->getSelectedItemsView(); - } - - /** - * @return boolean - */ - public function isStudyProgrammeViewActive() - { - return $this->currentView == $this->getStudyProgrammeView(); - } - - /** - * @return string - */ - public function getSortByStartDateMode() - { - return self::SORT_BY_START_DATE; - } - - /** - * @return string - */ - public function getSortByLocationMode() - { - return self::SORT_BY_LOCATION; - } - - /** - * @return string - */ - public function getSortByTypeMode() - { - return self::SORT_BY_TYPE; - } - - /** - * @return string - */ - public function getDefaultSortType() - { - return $this->settings->get('my_memberships_def_sort', $this->getSortByLocationMode()); - } - - /** - * @return boolean - */ - public function isSortedByType() - { - return $this->currentSortOption == $this->getSortByTypeMode(); - } - - /** - * @return boolean - */ - public function isSortedByLocation() - { - return $this->currentSortOption == $this->getSortByLocationMode(); - } - - /** - * @return boolean - */ - public function isSortedByStartDate() - { - return $this->currentSortOption == $this->getSortByStartDateMode(); - } - - /** - * @param string $type - */ - public function storeDefaultSortType($type) - { - assert(in_array($type, self::$availableSortOptions)); - $this->settings->set('my_memberships_def_sort', $type); - } - - /** - * @return boolean - */ - public function enabledMemberships() - { - return $this->settings->get('disable_my_memberships', 0) == 0; - } - - /** - * @return boolean - */ - public function enabledSelectedItems() - { - return $this->settings->get('disable_my_offers', 0) == 0; - } - - /** - * @param $status boolean - */ - public function enableMemberships($status) - { - $this->settings->set('disable_my_memberships', (int)!$status); - } - - /** - * @param $status boolean - */ - public function enableSelectedItems($status) - { - $this->settings->set('disable_my_offers', (int)!$status); - } - - /** - * @return boolean - */ - public function allViewsEnabled() - { - return $this->enabledMemberships() && $this->enabledSelectedItems(); - } - - /** - * @return boolean - */ - protected function allViewsDisabled() - { - return !$this->enabledMemberships() && !$this->enabledSelectedItems(); - } - - /** - * @return int - */ - public function getDefaultView() - { - return (int)$this->settings->get('personal_items_default_view', $this->getSelectedItemsView()); - } - - /** - * @param $view int - */ - public function storeDefaultView($view) - { - assert(in_array($view, self::$availableViews)); - $this->settings->set('personal_items_default_view', $view); - } - - /** - * - */ - public function parse() - { - $this->validViews = self::$availableViews; - - foreach(array_filter([ - $this->getMembershipsView() => !$this->enabledMemberships(), - $this->getSelectedItemsView() => !$this->enabledSelectedItems() - ]) as $viewId => $status) - { - $key = array_search($viewId, $this->validViews); - if($key !== false) - { - unset($this->validViews[$key]); - } - } - - if(count($this->validViews) == 1) - { - $this->storeDefaultView($this->getSelectedItemsView()); - $this->validViews[] = $this->getSelectedItemsView(); - } - - if(!$this->isValidView($this->getCurrentView())) - { - $this->currentView = $this->getDefaultView(); - } - - $this->currentSortOption = $this->actor->getPref('pd_order_items'); - if(!in_array($this->currentSortOption, self::$availableSortOptionsByView[$this->currentView])) - { - if($this->isSelectedItemsViewActive()) - { - $this->currentSortOption = self::SORT_BY_LOCATION; - } - else if($this->isStudyProgrammeViewActive()) - { - $this->currentSortOption = $this->getDefaultSortType(); - } - } - } - - /** - * @return ilObjUser - */ - public function getActor() - { - return $this->actor; - } - - /** - * @return int - */ - public function getCurrentView() - { - return $this->currentView; - } - - /** - * @return int - */ - public function getCurrentSortOption() - { - return $this->currentSortOption; - } - - /** - * @param string $view - * @return boolean - */ - public function isValidView($view) - { - return in_array($view, $this->validViews); - } -} \ No newline at end of file + /** + * @var array + */ + protected static $availableViews = array( + self::VIEW_SELECTED_ITEMS, + self::VIEW_MY_MEMBERSHIPS, + self::VIEW_MY_STUDYPROGRAMME + ); + + /** + * @var array + */ + protected static $availableSortOptions = array( + self::SORT_BY_LOCATION, + self::SORT_BY_TYPE, + self::SORT_BY_START_DATE + ); + + /** + * @var array + */ + protected static $availableSortOptionsByView = array( + self::VIEW_SELECTED_ITEMS => array( + self::SORT_BY_LOCATION, + self::SORT_BY_TYPE + ), + self::VIEW_MY_MEMBERSHIPS => array( + self::SORT_BY_LOCATION, + self::SORT_BY_TYPE, + self::SORT_BY_START_DATE + ), + self::VIEW_MY_STUDYPROGRAMME => array( + ) + ); + + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var ilObjUser + */ + protected $actor; + + /** + * @var array + */ + protected $validViews = array(); + + /** + * @var int + */ + protected $currentView = self::VIEW_SELECTED_ITEMS; + + /** + * @var int + */ + protected $currentSortOption = self::SORT_BY_LOCATION; + + /** + * ilPDSelectedItemsBlockViewSettings constructor. + * @param ilObjUser $actor + * @param int $view + */ + public function __construct($actor, $view = self::VIEW_SELECTED_ITEMS) + { + global $DIC; + + $ilSetting = $DIC->settings(); + + $this->settings = $ilSetting; + + $this->actor = $actor; + $this->currentView = $view; + } + + /** + * @return int + */ + public function getMembershipsView() + { + return self::VIEW_MY_MEMBERSHIPS; + } + + /** + * @return int + */ + public function getSelectedItemsView() + { + return self::VIEW_SELECTED_ITEMS; + } + + /** + * @return int + */ + public function getStudyProgrammeView() + { + return self::VIEW_MY_STUDYPROGRAMME; + } + + /** + * @return boolean + */ + public function isMembershipsViewActive() + { + return $this->currentView == $this->getMembershipsView(); + } + + /** + * @return boolean + */ + public function isSelectedItemsViewActive() + { + return $this->currentView == $this->getSelectedItemsView(); + } + + /** + * @return boolean + */ + public function isStudyProgrammeViewActive() + { + return $this->currentView == $this->getStudyProgrammeView(); + } + + /** + * @return string + */ + public function getSortByStartDateMode() + { + return self::SORT_BY_START_DATE; + } + + /** + * @return string + */ + public function getSortByLocationMode() + { + return self::SORT_BY_LOCATION; + } + + /** + * @return string + */ + public function getSortByTypeMode() + { + return self::SORT_BY_TYPE; + } + + /** + * @return string + */ + public function getDefaultSortType() + { + return $this->settings->get('my_memberships_def_sort', $this->getSortByLocationMode()); + } + + /** + * @return boolean + */ + public function isSortedByType() + { + return $this->currentSortOption == $this->getSortByTypeMode(); + } + + /** + * @return boolean + */ + public function isSortedByLocation() + { + return $this->currentSortOption == $this->getSortByLocationMode(); + } + + /** + * @return boolean + */ + public function isSortedByStartDate() + { + return $this->currentSortOption == $this->getSortByStartDateMode(); + } + + /** + * @param string $type + */ + public function storeDefaultSortType($type) + { + assert(in_array($type, self::$availableSortOptions)); + $this->settings->set('my_memberships_def_sort', $type); + } + + /** + * @return boolean + */ + public function enabledMemberships() + { + return $this->settings->get('disable_my_memberships', 0) == 0; + } + + /** + * @return boolean + */ + public function enabledSelectedItems() + { + return $this->settings->get('disable_my_offers', 0) == 0; + } + + /** + * @param $status boolean + */ + public function enableMemberships($status) + { + $this->settings->set('disable_my_memberships', (int) !$status); + } + + /** + * @param $status boolean + */ + public function enableSelectedItems($status) + { + $this->settings->set('disable_my_offers', (int) !$status); + } + + /** + * @return boolean + */ + public function allViewsEnabled() + { + return $this->enabledMemberships() && $this->enabledSelectedItems(); + } + + /** + * @return boolean + */ + protected function allViewsDisabled() + { + return !$this->enabledMemberships() && !$this->enabledSelectedItems(); + } + + /** + * @return int + */ + public function getDefaultView() + { + return (int) $this->settings->get('personal_items_default_view', $this->getSelectedItemsView()); + } + + /** + * @param $view int + */ + public function storeDefaultView($view) + { + assert(in_array($view, self::$availableViews)); + $this->settings->set('personal_items_default_view', $view); + } + + /** + * + */ + public function parse() + { + $this->validViews = self::$availableViews; + + foreach (array_filter([ + $this->getMembershipsView() => !$this->enabledMemberships(), + $this->getSelectedItemsView() => !$this->enabledSelectedItems() + ]) as $viewId => $status) { + $key = array_search($viewId, $this->validViews); + if ($key !== false) { + unset($this->validViews[$key]); + } + } + + if (count($this->validViews) == 1) { + $this->storeDefaultView($this->getSelectedItemsView()); + $this->validViews[] = $this->getSelectedItemsView(); + } + + if (!$this->isValidView($this->getCurrentView())) { + $this->currentView = $this->getDefaultView(); + } + + $this->currentSortOption = $this->actor->getPref('pd_order_items'); + if (!in_array($this->currentSortOption, self::$availableSortOptionsByView[$this->currentView])) { + if ($this->isSelectedItemsViewActive()) { + $this->currentSortOption = self::SORT_BY_LOCATION; + } elseif ($this->isStudyProgrammeViewActive()) { + $this->currentSortOption = $this->getDefaultSortType(); + } + } + } + + /** + * @return ilObjUser + */ + public function getActor() + { + return $this->actor; + } + + /** + * @return int + */ + public function getCurrentView() + { + return $this->currentView; + } + + /** + * @return int + */ + public function getCurrentSortOption() + { + return $this->currentSortOption; + } + + /** + * @param string $view + * @return boolean + */ + public function isValidView($view) + { + return in_array($view, $this->validViews); + } +} diff --git a/Services/PersonalDesktop/ItemsBlock/interfaces/interface.ilPDSelectedItemsBlockConstants.php b/Services/PersonalDesktop/ItemsBlock/interfaces/interface.ilPDSelectedItemsBlockConstants.php index 8d8276378ebc61e2a1977bb425c8d4aa67038b86..68ea4c7a81e9126ebb529736b2be6a8699eb3115 100644 --- a/Services/PersonalDesktop/ItemsBlock/interfaces/interface.ilPDSelectedItemsBlockConstants.php +++ b/Services/PersonalDesktop/ItemsBlock/interfaces/interface.ilPDSelectedItemsBlockConstants.php @@ -6,11 +6,11 @@ */ interface ilPDSelectedItemsBlockConstants { - const VIEW_SELECTED_ITEMS = 0; - const VIEW_MY_MEMBERSHIPS = 1; - const VIEW_MY_STUDYPROGRAMME = 2; - - const SORT_BY_TYPE = 'type'; - const SORT_BY_LOCATION = 'location'; - const SORT_BY_START_DATE = 'start_date'; -} \ No newline at end of file + const VIEW_SELECTED_ITEMS = 0; + const VIEW_MY_MEMBERSHIPS = 1; + const VIEW_MY_STUDYPROGRAMME = 2; + + const SORT_BY_TYPE = 'type'; + const SORT_BY_LOCATION = 'location'; + const SORT_BY_START_DATE = 'start_date'; +} diff --git a/Services/PersonalDesktop/ItemsBlock/interfaces/interface.ilPDSelectedItemsBlockProvider.php b/Services/PersonalDesktop/ItemsBlock/interfaces/interface.ilPDSelectedItemsBlockProvider.php index 219dbcd098ddc8f8e85a52e55c077da5d31e27bb..73dcdf3d11d881e91e088d649614b855af955241 100644 --- a/Services/PersonalDesktop/ItemsBlock/interfaces/interface.ilPDSelectedItemsBlockProvider.php +++ b/Services/PersonalDesktop/ItemsBlock/interfaces/interface.ilPDSelectedItemsBlockProvider.php @@ -6,9 +6,9 @@ */ interface ilPDSelectedItemsBlockProvider { - /** - * @param array $object_type_white_list An optional array of object_types used for filter purposes - * @return array An array of repository items, each given as a structured array - */ - public function getItems($object_type_white_list = array()); -} \ No newline at end of file + /** + * @param array $object_type_white_list An optional array of object_types used for filter purposes + * @return array An array of repository items, each given as a structured array + */ + public function getItems($object_type_white_list = array()); +} diff --git a/Services/PersonalDesktop/classes/class.ilDesktopItemGUI.php b/Services/PersonalDesktop/classes/class.ilDesktopItemGUI.php index 457af57e3dac8741c5ad9c21f39e789c66444844..fe75ba98e3ce4eb985ddee5d03a5f644adbefb08 100644 --- a/Services/PersonalDesktop/classes/class.ilDesktopItemGUI.php +++ b/Services/PersonalDesktop/classes/class.ilDesktopItemGUI.php @@ -1,91 +1,80 @@ * @version $Id$ -* +* * * @ingroup ServicesPersonalDesktop */ class ilDesktopItemGUI { - /** - * Add desktop item - * @access public - */ - public static function addToDesktop() - { - global $DIC; + /** + * Add desktop item + * @access public + */ + public static function addToDesktop() + { + global $DIC; - $ilUser = $DIC->user(); - - if ($_GET["item_ref_id"] and $_GET["type"]) - { - ilObjUser::_addDesktopItem($ilUser->getId(),(int) $_GET['item_ref_id'], $_GET['type']); - } - else - { - if ($_POST["items"]) - { - foreach ($_POST["items"] as $item) - { - $type = ilObject::_lookupType($item, true); - ilObjUser::_addDesktopItem($ilUser->getId(),$item,$type); - } - } - } - return true; - } - - /** - * Remove item from personal desktop - * @access public - */ - public static function removeFromDesktop() - { - global $DIC; + $ilUser = $DIC->user(); + + if ($_GET["item_ref_id"] and $_GET["type"]) { + ilObjUser::_addDesktopItem($ilUser->getId(), (int) $_GET['item_ref_id'], $_GET['type']); + } else { + if ($_POST["items"]) { + foreach ($_POST["items"] as $item) { + $type = ilObject::_lookupType($item, true); + ilObjUser::_addDesktopItem($ilUser->getId(), $item, $type); + } + } + } + return true; + } + + /** + * Remove item from personal desktop + * @access public + */ + public static function removeFromDesktop() + { + global $DIC; - $ilUser = $DIC->user(); + $ilUser = $DIC->user(); - if ($_GET["item_ref_id"] and $_GET["type"]) - { - ilObjUser::_dropDesktopItem($ilUser->getId(),(int) $_GET['item_ref_id'], $_GET['type']); - } - else - { - if ($_POST["items"]) - { - foreach ($_POST["items"] as $item) - { - $type = ilObject::_lookupType($item, true); - ilObjUser::_dropDesktopItem($ilUser->getId(),$item,$type); - } - } - } - return true; - } + if ($_GET["item_ref_id"] and $_GET["type"]) { + ilObjUser::_dropDesktopItem($ilUser->getId(), (int) $_GET['item_ref_id'], $_GET['type']); + } else { + if ($_POST["items"]) { + foreach ($_POST["items"] as $item) { + $type = ilObject::_lookupType($item, true); + ilObjUser::_dropDesktopItem($ilUser->getId(), $item, $type); + } + } + } + return true; + } } -?> \ No newline at end of file diff --git a/Services/PersonalDesktop/classes/class.ilObjPersonalDesktopSettings.php b/Services/PersonalDesktop/classes/class.ilObjPersonalDesktopSettings.php index 4246635184997bcf89a63c6a32f59f3eedb55f03..0c1b08bfadce277335e8b9c68a3ef7bdd1d53f63 100755 --- a/Services/PersonalDesktop/classes/class.ilObjPersonalDesktopSettings.php +++ b/Services/PersonalDesktop/classes/class.ilObjPersonalDesktopSettings.php @@ -1,105 +1,100 @@ +* +* @author Alex Killing * @version $Id$ * * @ingroup ServicesPersonalDesktop */ class ilObjPersonalDesktopSettings extends ilObject { - - /** - * Constructor - * @access public - * @param integer reference_id or object_id - * @param boolean treat the id as reference_id (true) or object_id (false) - */ - function __construct($a_id = 0,$a_call_by_reference = true) - { - global $DIC; - - $this->db = $DIC->database(); - $this->type = "pdts"; - parent::__construct($a_id,$a_call_by_reference); - } - - /** - * update object data - * - * @access public - * @return boolean - */ - function update() - { - $ilDB = $this->db; - - if (!parent::update()) - { - return false; - } + + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + global $DIC; - return true; - } - - /** - * read style folder data - */ - function read() - { - $ilDB = $this->db; + $this->db = $DIC->database(); + $this->type = "pdts"; + parent::__construct($a_id, $a_call_by_reference); + } - parent::read(); + /** + * update object data + * + * @access public + * @return boolean + */ + public function update() + { + $ilDB = $this->db; + + if (!parent::update()) { + return false; + } - } - + return true; + } + + /** + * read style folder data + */ + public function read() + { + $ilDB = $this->db; - - + parent::read(); + } + - /** - * delete object and all related data - * - * @access public - * @return boolean true if all object data were removed; false if only a references were removed - */ - function delete() - { - // always call parent delete function first!! - if (!parent::delete()) - { - return false; - } - - //put here your module specific stuff - - return true; - } + + + /** + * delete object and all related data + * + * @access public + * @return boolean true if all object data were removed; false if only a references were removed + */ + public function delete() + { + // always call parent delete function first!! + if (!parent::delete()) { + return false; + } + + //put here your module specific stuff + + return true; + } } // END class.ilObjPersonalDesktopSettings -?> diff --git a/Services/PersonalDesktop/classes/class.ilObjPersonalDesktopSettingsAccess.php b/Services/PersonalDesktop/classes/class.ilObjPersonalDesktopSettingsAccess.php index c2c175229372b5ee679d07a490de5e9777dcdcdd..4b820763176fb25eb69b6f8167f27efb1e9c591c 100755 --- a/Services/PersonalDesktop/classes/class.ilObjPersonalDesktopSettingsAccess.php +++ b/Services/PersonalDesktop/classes/class.ilObjPersonalDesktopSettingsAccess.php @@ -1,24 +1,24 @@ diff --git a/Services/PersonalDesktop/classes/class.ilObjPersonalDesktopSettingsGUI.php b/Services/PersonalDesktop/classes/class.ilObjPersonalDesktopSettingsGUI.php index 01a73d1b52a1bcbcfd1b18857cf1f76952483dd1..aadde193be9d6a8fb89a1defca01aa1d79c29308 100755 --- a/Services/PersonalDesktop/classes/class.ilObjPersonalDesktopSettingsGUI.php +++ b/Services/PersonalDesktop/classes/class.ilObjPersonalDesktopSettingsGUI.php @@ -16,477 +16,465 @@ require_once 'Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItem */ class ilObjPersonalDesktopSettingsGUI extends ilObjectGUI { - /** - * @var ilRbacSystem - */ - protected $rbacsystem; + /** + * @var ilRbacSystem + */ + protected $rbacsystem; - /** - * @var ilErrorHandling - */ - protected $error; + /** + * @var ilErrorHandling + */ + protected $error; private static $ERROR_MESSAGE; - /** - * @var ilPDSelectedItemsBlockViewSettings - */ - protected $viewSettings; - /** - * Contructor - * - * @access public - */ - public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) - { - global $DIC; - - $this->lng = $DIC->language(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->error = $DIC["ilErr"]; - $this->access = $DIC->access(); - $this->ctrl = $DIC->ctrl(); - $this->settings = $DIC->settings(); - $lng = $DIC->language(); - $this->ui_factory = $DIC->ui()->factory(); - $this->ui_renderer = $DIC->ui()->renderer(); - - $this->type = 'pdts'; - parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); - - $lng->loadLanguageModule("pd"); - - $this->viewSettings = new ilPDSelectedItemsBlockViewSettings($GLOBALS['DIC']->user()); - } - - /** - * Execute command - * - * @access public - * - */ - public function executeCommand() - { - $rbacsystem = $this->rbacsystem; - $ilErr = $this->error; - $ilAccess = $this->access; - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - $this->prepareOutput(); - - if(!$ilAccess->checkAccess('read','',$this->object->getRefId())) - { - $ilErr->raiseError($this->lng->txt('no_permission'),$ilErr->WARNING); - } - - switch($next_class) - { - case 'ilpermissiongui': - $this->tabs_gui->setTabActive('perm_settings'); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $ret = $this->ctrl->forwardCommand($perm_gui); - break; - - default: - if(!$cmd || $cmd == 'view') - { - $cmd = "editSettings"; - } - - $this->$cmd(); - break; - } - return true; - } - - /** - * Get tabs - * - * @access public - * - */ - public function getAdminTabs() - { - $rbacsystem = $this->rbacsystem; - $ilAccess = $this->access; - - if ($rbacsystem->checkAccess("visible,read",$this->object->getRefId())) - { - $this->tabs_gui->addTarget("pd_settings", - $this->ctrl->getLinkTarget($this, "editSettings"), - array("editSettings", "view")); - - $this->tabs_gui->addTarget("pd_personal_workspace", - $this->ctrl->getLinkTarget($this, "editWsp"), - array("editWsp")); - } - - if ($rbacsystem->checkAccess('edit_permission',$this->object->getRefId())) - { - $this->tabs_gui->addTarget("perm_settings", - $this->ctrl->getLinkTargetByClass('ilpermissiongui',"perm"), - array(),'ilpermissiongui'); - } - } - - /** - * Edit personal desktop settings. - */ - public function editSettings() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilSetting = $this->settings; - $ilAccess = $this->access; - - $pd_set = new ilSetting("pd"); - - $enable_calendar = ilCalendarSettings::_getInstance()->isEnabled(); - #$enable_calendar = $ilSetting->get("enable_calendar"); - $enable_block_moving = $pd_set->get("enable_block_moving"); - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this)); - $form->setTitle($lng->txt("pd_settings")); - - // Enable calendar - $cb_prop = new ilCheckboxInputGUI($lng->txt("enable_calendar"), "enable_calendar"); - $cb_prop->setValue("1"); - //$cb_prop->setInfo($lng->txt("pd_enable_block_moving_info")); - $cb_prop->setChecked($enable_calendar); - $form->addItem($cb_prop); - - // Enable bookmarks - $cb_prop = new ilCheckboxInputGUI($lng->txt("pd_enable_bookmarks"), "enable_bookmarks"); - $cb_prop->setValue("1"); - $cb_prop->setChecked(($ilSetting->get("disable_bookmarks") ? "0" : "1")); - $form->addItem($cb_prop); - - // Enable notes - $cb_prop = new ilCheckboxInputGUI($lng->txt("pd_enable_notes"), "enable_notes"); - $cb_prop->setValue("1"); - $cb_prop->setChecked(($ilSetting->get("disable_notes") ? "0" : "1")); - $form->addItem($cb_prop); - - // Enable comments - $cb_prop = new ilCheckboxInputGUI($lng->txt("pd_enable_comments"), "enable_comments"); - $cb_prop->setValue("1"); - $cb_prop->setChecked(($ilSetting->get("disable_comments") ? "0" : "1")); - $form->addItem($cb_prop); - - $comm_del_user = new ilCheckboxInputGUI($lng->txt("pd_enable_comments_del_user"), "comm_del_user"); - $comm_del_user->setChecked($ilSetting->get("comments_del_user", 0)); - $cb_prop->addSubItem($comm_del_user); - - $comm_del_tutor = new ilCheckboxInputGUI($lng->txt("pd_enable_comments_del_tutor"), "comm_del_tutor"); - $comm_del_tutor->setInfo($lng->txt("pd_enable_comments_del_tutor_info")); - $comm_del_tutor->setChecked($ilSetting->get("comments_del_tutor", 1)); - $cb_prop->addSubItem($comm_del_tutor); - - $ti = new ilTextInputGUI($this->lng->txt("pd_comments_notification"), "comments_noti_recip"); - $ti->setValue($ilSetting->get("comments_noti_recip")); - $ti->setMaxLength(200); - $ti->setInfo($this->lng->txt("pd_comments_notification_info")); - $cb_prop->addSubItem($ti); - - // Enable learning history - $learn_hist = new ilCheckboxInputGUI($lng->txt("pd_enable_learning_history"), "enable_learning_history"); - $learn_hist->setValue("1"); - $learn_hist->setInfo($lng->txt("pd_enable_learning_history_info")); - $learn_hist->setChecked(($ilSetting->get("enable_learning_history") ? "1" : "0")); - $form->addItem($learn_hist); - - // Enable Chatviewer - $cb_prop = new ilCheckboxInputGUI($lng->txt("pd_enable_chatviewer"), "block_activated_chatviewer"); - $cb_prop->setValue("1"); - $cb_prop->setChecked(($ilSetting->get("block_activated_chatviewer"))); - $form->addItem($cb_prop); - - require_once 'Services/Mail/classes/class.ilObjMail.php'; - $pd_sys_msg = new ilRadioGroupInputGUI($lng->txt('show_system_messages'), 'pd_sys_msg_mode'); - - $sys_msg_own_block = new ilRadioOption($lng->txt('pd_sys_msg_own_block'), ilObjMail::PD_SYS_MSG_OWN_BLOCK); - $pd_sys_msg->addOption($sys_msg_own_block); - - $sys_msg_mail_block = new ilRadioOption($lng->txt('pd_sys_msg_mail_block'), ilObjMail::PD_SYS_MSG_MAIL_BLOCK); - $pd_sys_msg->addOption($sys_msg_mail_block); - - $sys_msg_own_block = new ilRadioOption($lng->txt('pd_sys_msg_no_block'), ilObjMail::PD_SYS_MSG_NO_BLOCK); - $pd_sys_msg->addOption($sys_msg_own_block); - - $pd_sys_msg->setValue((int)($ilSetting->get('pd_sys_msg_mode'))); - $form->addItem($pd_sys_msg); - - if($ilSetting->get('save_post_drafts', 0)) - { - $cb_prop = new ilCheckboxInputGUI($lng->txt('pd_enable_pdfrmpostdraft'), 'block_activated_pdfrmpostdraft'); - $cb_prop->setInfo($lng->txt('pd_enable_pdfrmpostdraft_info')); - $cb_prop->setValue(1); - $cb_prop->setChecked($ilSetting->get('block_activated_pdfrmpostdraft', 0)); - $form->addItem($cb_prop); - } - // Enable block moving - $cb_prop = new ilCheckboxInputGUI($lng->txt("pd_enable_block_moving"), - "enable_block_moving"); - $cb_prop->setValue("1"); - $cb_prop->setInfo($lng->txt("pd_enable_block_moving_info")); - $cb_prop->setChecked($enable_block_moving); - $form->addItem($cb_prop); - - // Enable 'My Offers' (default personal items) - $cb_prop = new ilCheckboxInputGUI($lng->txt('pd_enable_my_offers'), 'enable_my_offers'); - $cb_prop->setValue('1'); - $cb_prop->setInfo($lng->txt('pd_enable_my_offers_info')); - $cb_prop->setChecked($this->viewSettings->enabledSelectedItems()); - $form->addItem($cb_prop); - - // Enable 'My Memberships' - $cb_prop = new ilCheckboxInputGUI($lng->txt('pd_enable_my_memberships'), 'enable_my_memberships'); - $cb_prop->setValue('1'); - $cb_prop->setInfo($lng->txt('pd_enable_my_memberships_info')); - $cb_prop->setChecked($this->viewSettings->enabledMemberships()); - $form->addItem($cb_prop); - - $memberships_sort_defaults = new ilRadioGroupInputGUI($lng->txt('pd_my_memberships_sort_default'), 'my_memberships_sort_default'); - $memberships_sort_defaults->addOption(new ilRadioOption($lng->txt('pd_sort_by_location'), $this->viewSettings->getSortByLocationMode())); - $memberships_sort_defaults->addOption(new ilRadioOption($lng->txt('pd_sort_by_type'), $this->viewSettings->getSortByTypeMode())); - $memberships_sort_defaults->addOption(new ilRadioOption($lng->txt('pd_sort_by_start_date'), $this->viewSettings->getSortByStartDateMode())); - $memberships_sort_defaults->setRequired(true); - $memberships_sort_defaults->setValue($this->viewSettings->getDefaultSortType()); - $cb_prop->addSubItem($memberships_sort_defaults); - - #22357 - $this->ctrl->setParameterByClass("iluserstartingpointgui", "ref_id", USER_FOLDER_ID); - $url = $this->ctrl->getLinkTargetByClass(array("iladministrationgui","ilobjuserfoldergui", "iluserstartingpointgui"), "startingpoints"); - $this->ctrl->setParameterByClass("iluserstartingpointgui", "ref_id", $_GET['ref_id']); - - $lng->loadLanguageModule("user"); - $starting_point_button = $this->ui_factory->button()->shy($lng->txt("starting_points"), $url); - $button = new ilCustomInputGUI($lng->txt('pd_personal_items_default_view'),''); - $button->setHtml($this->ui_renderer->render($starting_point_button)); - $form->addItem($button); - - if($ilAccess->checkAccess('write','',$this->object->getRefId())) - { - // command buttons - $form->addCommandButton("saveSettings", $lng->txt("save")); - $form->addCommandButton("view", $lng->txt("cancel")); - } - - $this->tpl->setContent($form->getHTML()); - } - - /** - * Save personal desktop settings - */ - public function saveSettings() - { - $ilCtrl = $this->ctrl; - $ilSetting = $this->settings; - $ilAccess = $this->access; - - if(!$ilAccess->checkAccess('write','',$this->object->getRefId())) - { - $ilCtrl->redirect($this, "view"); - } - - $pd_set = new ilSetting("pd"); - - ilCalendarSettings::_getInstance()->setEnabled( $_POST["enable_calendar"]); - ilCalendarSettings::_getInstance()->save(); - - #$ilSetting->set("enable_calendar", $_POST["enable_calendar"]); - $ilSetting->set("disable_bookmarks", (int) ($_POST["enable_bookmarks"] ? 0 : 1)); - - $ilSetting->set("disable_notes", (int) ($_POST["enable_notes"] ? 0 : 1)); - $ilSetting->set("disable_comments", (int) ($_POST["enable_comments"] ? 0 : 1)); - - $ilSetting->set("enable_learning_history", (int) $_POST["enable_learning_history"]); - - $ilSetting->set("comments_del_user", (int) ($_POST["comm_del_user"] ? 1 : 0)); - $ilSetting->set("comments_del_tutor", (int) ($_POST["comm_del_tutor"] ? 1 : 0)); - $ilSetting->set("comments_noti_recip", ilUtil::stripSlashes($_POST["comments_noti_recip"])); - - $ilSetting->set("block_activated_chatviewer", (int) ($_POST["block_activated_chatviewer"])); - $ilSetting->set("pd_sys_msg_mode", (int) ($_POST["pd_sys_msg_mode"])); - if($ilSetting->get('save_post_drafts', 0)) - { - $ilSetting->set("block_activated_pdfrmpostdraft", (int)$_POST["block_activated_pdfrmpostdraft"]); - } - $pd_set->set("enable_block_moving", $_POST["enable_block_moving"]); -// $pd_set->set("user_activity_time", (int) $_POST["time_removal"]); - - // Validate personal desktop view - if(!(int)$_POST['enable_my_offers'] && !(int)$_POST['enable_my_memberships']) - { - ilUtil::sendFailure($this->lng->txt('pd_view_select_at_least_one'), true); - $ilCtrl->redirect($this, 'view'); - } - - $this->viewSettings->enableSelectedItems((int)($_POST['enable_my_offers'] ? 1 : 0)); - $this->viewSettings->enableMemberships((int)($_POST['enable_my_memberships'] ? 1 : 0)); - - if((int)$_POST['enable_my_offers'] && !(int)$_POST['enable_my_memberships']) - { - $this->viewSettings->storeDefaultView($this->viewSettings->getSelectedItemsView()); - } - else if(!(int)$_POST['enable_my_offers'] && (int)$_POST['enable_my_memberships']) - { - $this->viewSettings->storeDefaultView($this->viewSettings->getMembershipsView()); - } - else if(isset($_POST['personal_items_default_view'])) - { - $this->viewSettings->storeDefaultView((int)$_POST['personal_items_default_view']); - } - - $this->viewSettings->storeDefaultSortType(ilUtil::stripSlashes($_POST['my_memberships_sort_default'])); - - ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); - $ilCtrl->redirect($this, "view"); - } - - /** - * Edit personal workspace settings. - */ - public function editWsp() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilSetting = $this->settings; - $ilAccess = $this->access; - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this, "saveWsp")); - $form->setTitle($lng->txt("pd_personal_workspace")); - - // Enable 'Personal Workspace' - $wsp_prop = new ilCheckboxInputGUI($lng->txt('pd_enable_personal_workspace'), 'wsp'); - $wsp_prop->setValue('1'); - $wsp_prop->setChecked(($ilSetting->get('disable_personal_workspace') ? '0' : '1')); - $form->addItem($wsp_prop); - - // Enable 'Blogs' - $blog_prop = new ilCheckboxInputGUI($lng->txt('pd_enable_wsp_blogs'), 'blog'); - $blog_prop->setValue('1'); - $blog_prop->setChecked(($ilSetting->get('disable_wsp_blogs') ? '0' : '1')); - $wsp_prop->addSubItem($blog_prop); - - // Enable 'Files' - $file_prop = new ilCheckboxInputGUI($lng->txt('pd_enable_wsp_files'), 'file'); - $file_prop->setValue('1'); - $file_prop->setChecked(($ilSetting->get('disable_wsp_files') ? '0' : '1')); - $wsp_prop->addSubItem($file_prop); - - // Enable 'Certificates' - $cert_prop = new ilCheckboxInputGUI($lng->txt('pd_enable_wsp_certificates'), 'cert'); - $cert_prop->setValue('1'); - $cert_prop->setChecked(($ilSetting->get('disable_wsp_certificates') ? '0' : '1')); - $wsp_prop->addSubItem($cert_prop); - - // Enable 'Links' - $link_prop = new ilCheckboxInputGUI($lng->txt('pd_enable_wsp_links'), 'link'); - $link_prop->setValue('1'); - $link_prop->setChecked(($ilSetting->get('disable_wsp_links') ? '0' : '1')); - $wsp_prop->addSubItem($link_prop); - - /* - // Enable 'Portfolios' - $lng->loadLanguageModule('user'); - $prtf_prop = new ilCheckboxInputGUI($lng->txt('pd_enable_prtf'), 'prtf'); - $prtf_prop->setValue('1'); - $prtf_prop->setInfo($lng->txt('user_portfolios_desc')); - $prtf_prop->setChecked(($ilSetting->get('user_portfolios') ? '1' : '0')); - $form->addItem($prtf_prop); - */ - - // Load the disk quota settings object - require_once 'Services/WebDAV/classes/class.ilObjDiskQuotaSettings.php'; - $disk_quota_obj = ilObjDiskQuotaSettings::getInstance(); - - // Enable disk quota - $lng->loadLanguageModule("file"); - $cb_prop = new ilCheckboxInputGUI($lng->txt("personal_workspace_disk_quota"), "enable_personal_workspace_disk_quota"); - $cb_prop->setValue('1'); - $cb_prop->setChecked($disk_quota_obj->isPersonalWorkspaceDiskQuotaEnabled()); - $cb_prop->setInfo($lng->txt('enable_personal_workspace_disk_quota_info')); - $form->addItem($cb_prop); - - require_once 'Services/Administration/classes/class.ilAdministrationSettingsFormHandler.php'; - ilAdministrationSettingsFormHandler::addFieldsToForm( - ilAdministrationSettingsFormHandler::FORM_WSP, - $form, - $this - ); - - if($ilAccess->checkAccess('write','',$this->object->getRefId())) - { - // command buttons - $form->addCommandButton("saveWsp", $lng->txt("save")); - $form->addCommandButton("editWsp", $lng->txt("cancel")); - } - - $this->tpl->setContent($form->getHTML()); - } - - /** - * Save personal desktop settings - */ - public function saveWsp() - { - $ilCtrl = $this->ctrl; - $ilSetting = $this->settings; - $ilAccess = $this->access; - - if(!$ilAccess->checkAccess('write','',$this->object->getRefId())) - { - $ilCtrl->redirect($this, "view"); - } - - // without personal workspace we have to disable to sub-items - if(!$_POST["wsp"]) - { - $_POST["blog"] = 0; - $_POST["file"] = 0; - $_POST["cert"] = 0; - $_POST["link"] = 0; - } - - $ilSetting->set('disable_personal_workspace', (int)($_POST['wsp'] ? 0 : 1)); - $ilSetting->set('disable_wsp_blogs', (int)($_POST['blog'] ? 0 : 1)); - $ilSetting->set('disable_wsp_files', (int)($_POST['file'] ? 0 : 1)); - $ilSetting->set('disable_wsp_certificates', (int)($_POST['cert'] ? 0 : 1)); - $ilSetting->set('disable_wsp_links', (int)($_POST['link'] ? 0 : 1)); - // $ilSetting->set('user_portfolios', (int)($_POST['prtf'] ? 1 : 0)); - - // Load the disk quota settings object - require_once 'Services/WebDAV/classes/class.ilObjDiskQuotaSettings.php'; - $disk_quota_obj = ilObjDiskQuotaSettings::getInstance(); - $disk_quota_obj->setPersonalWorkspaceDiskQuotaEnabled($_POST['enable_personal_workspace_disk_quota'] == '1'); - $disk_quota_obj->update(); - - ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); - $ilCtrl->redirect($this, "editWsp"); - } - - public function addToExternalSettingsForm($a_form_id) - { - switch($a_form_id) - { - case ilAdministrationSettingsFormHandler::FORM_FILES_QUOTA: - - require_once 'Services/WebDAV/classes/class.ilObjDiskQuotaSettings.php'; - $disk_quota_obj = ilObjDiskQuotaSettings::getInstance(); - - $fields = array('personal_workspace_disk_quota' => array($disk_quota_obj->isPersonalWorkspaceDiskQuotaEnabled(), ilAdministrationSettingsFormHandler::VALUE_BOOL)); - - return array(array("editWsp", $fields)); - } - } + /** + * @var ilPDSelectedItemsBlockViewSettings + */ + protected $viewSettings; + /** + * Contructor + * + * @access public + */ + public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) + { + global $DIC; + + $this->lng = $DIC->language(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->error = $DIC["ilErr"]; + $this->access = $DIC->access(); + $this->ctrl = $DIC->ctrl(); + $this->settings = $DIC->settings(); + $lng = $DIC->language(); + $this->ui_factory = $DIC->ui()->factory(); + $this->ui_renderer = $DIC->ui()->renderer(); + + $this->type = 'pdts'; + parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); + + $lng->loadLanguageModule("pd"); + + $this->viewSettings = new ilPDSelectedItemsBlockViewSettings($GLOBALS['DIC']->user()); + } + + /** + * Execute command + * + * @access public + * + */ + public function executeCommand() + { + $rbacsystem = $this->rbacsystem; + $ilErr = $this->error; + $ilAccess = $this->access; + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + $this->prepareOutput(); + + if (!$ilAccess->checkAccess('read', '', $this->object->getRefId())) { + $ilErr->raiseError($this->lng->txt('no_permission'), $ilErr->WARNING); + } + + switch ($next_class) { + case 'ilpermissiongui': + $this->tabs_gui->setTabActive('perm_settings'); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $ret = $this->ctrl->forwardCommand($perm_gui); + break; + + default: + if (!$cmd || $cmd == 'view') { + $cmd = "editSettings"; + } + + $this->$cmd(); + break; + } + return true; + } + + /** + * Get tabs + * + * @access public + * + */ + public function getAdminTabs() + { + $rbacsystem = $this->rbacsystem; + $ilAccess = $this->access; + + if ($rbacsystem->checkAccess("visible,read", $this->object->getRefId())) { + $this->tabs_gui->addTarget( + "pd_settings", + $this->ctrl->getLinkTarget($this, "editSettings"), + array("editSettings", "view") + ); + + $this->tabs_gui->addTarget( + "pd_personal_workspace", + $this->ctrl->getLinkTarget($this, "editWsp"), + array("editWsp") + ); + } + + if ($rbacsystem->checkAccess('edit_permission', $this->object->getRefId())) { + $this->tabs_gui->addTarget( + "perm_settings", + $this->ctrl->getLinkTargetByClass('ilpermissiongui', "perm"), + array(), + 'ilpermissiongui' + ); + } + } + + /** + * Edit personal desktop settings. + */ + public function editSettings() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilSetting = $this->settings; + $ilAccess = $this->access; + + $pd_set = new ilSetting("pd"); + + $enable_calendar = ilCalendarSettings::_getInstance()->isEnabled(); + #$enable_calendar = $ilSetting->get("enable_calendar"); + $enable_block_moving = $pd_set->get("enable_block_moving"); + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this)); + $form->setTitle($lng->txt("pd_settings")); + + // Enable calendar + $cb_prop = new ilCheckboxInputGUI($lng->txt("enable_calendar"), "enable_calendar"); + $cb_prop->setValue("1"); + //$cb_prop->setInfo($lng->txt("pd_enable_block_moving_info")); + $cb_prop->setChecked($enable_calendar); + $form->addItem($cb_prop); + + // Enable bookmarks + $cb_prop = new ilCheckboxInputGUI($lng->txt("pd_enable_bookmarks"), "enable_bookmarks"); + $cb_prop->setValue("1"); + $cb_prop->setChecked(($ilSetting->get("disable_bookmarks") ? "0" : "1")); + $form->addItem($cb_prop); + + // Enable notes + $cb_prop = new ilCheckboxInputGUI($lng->txt("pd_enable_notes"), "enable_notes"); + $cb_prop->setValue("1"); + $cb_prop->setChecked(($ilSetting->get("disable_notes") ? "0" : "1")); + $form->addItem($cb_prop); + + // Enable comments + $cb_prop = new ilCheckboxInputGUI($lng->txt("pd_enable_comments"), "enable_comments"); + $cb_prop->setValue("1"); + $cb_prop->setChecked(($ilSetting->get("disable_comments") ? "0" : "1")); + $form->addItem($cb_prop); + + $comm_del_user = new ilCheckboxInputGUI($lng->txt("pd_enable_comments_del_user"), "comm_del_user"); + $comm_del_user->setChecked($ilSetting->get("comments_del_user", 0)); + $cb_prop->addSubItem($comm_del_user); + + $comm_del_tutor = new ilCheckboxInputGUI($lng->txt("pd_enable_comments_del_tutor"), "comm_del_tutor"); + $comm_del_tutor->setInfo($lng->txt("pd_enable_comments_del_tutor_info")); + $comm_del_tutor->setChecked($ilSetting->get("comments_del_tutor", 1)); + $cb_prop->addSubItem($comm_del_tutor); + + $ti = new ilTextInputGUI($this->lng->txt("pd_comments_notification"), "comments_noti_recip"); + $ti->setValue($ilSetting->get("comments_noti_recip")); + $ti->setMaxLength(200); + $ti->setInfo($this->lng->txt("pd_comments_notification_info")); + $cb_prop->addSubItem($ti); + + // Enable learning history + $learn_hist = new ilCheckboxInputGUI($lng->txt("pd_enable_learning_history"), "enable_learning_history"); + $learn_hist->setValue("1"); + $learn_hist->setInfo($lng->txt("pd_enable_learning_history_info")); + $learn_hist->setChecked(($ilSetting->get("enable_learning_history") ? "1" : "0")); + $form->addItem($learn_hist); + + // Enable Chatviewer + $cb_prop = new ilCheckboxInputGUI($lng->txt("pd_enable_chatviewer"), "block_activated_chatviewer"); + $cb_prop->setValue("1"); + $cb_prop->setChecked(($ilSetting->get("block_activated_chatviewer"))); + $form->addItem($cb_prop); + + require_once 'Services/Mail/classes/class.ilObjMail.php'; + $pd_sys_msg = new ilRadioGroupInputGUI($lng->txt('show_system_messages'), 'pd_sys_msg_mode'); + + $sys_msg_own_block = new ilRadioOption($lng->txt('pd_sys_msg_own_block'), ilObjMail::PD_SYS_MSG_OWN_BLOCK); + $pd_sys_msg->addOption($sys_msg_own_block); + + $sys_msg_mail_block = new ilRadioOption($lng->txt('pd_sys_msg_mail_block'), ilObjMail::PD_SYS_MSG_MAIL_BLOCK); + $pd_sys_msg->addOption($sys_msg_mail_block); + + $sys_msg_own_block = new ilRadioOption($lng->txt('pd_sys_msg_no_block'), ilObjMail::PD_SYS_MSG_NO_BLOCK); + $pd_sys_msg->addOption($sys_msg_own_block); + + $pd_sys_msg->setValue((int) ($ilSetting->get('pd_sys_msg_mode'))); + $form->addItem($pd_sys_msg); + + if ($ilSetting->get('save_post_drafts', 0)) { + $cb_prop = new ilCheckboxInputGUI($lng->txt('pd_enable_pdfrmpostdraft'), 'block_activated_pdfrmpostdraft'); + $cb_prop->setInfo($lng->txt('pd_enable_pdfrmpostdraft_info')); + $cb_prop->setValue(1); + $cb_prop->setChecked($ilSetting->get('block_activated_pdfrmpostdraft', 0)); + $form->addItem($cb_prop); + } + // Enable block moving + $cb_prop = new ilCheckboxInputGUI( + $lng->txt("pd_enable_block_moving"), + "enable_block_moving" + ); + $cb_prop->setValue("1"); + $cb_prop->setInfo($lng->txt("pd_enable_block_moving_info")); + $cb_prop->setChecked($enable_block_moving); + $form->addItem($cb_prop); + + // Enable 'My Offers' (default personal items) + $cb_prop = new ilCheckboxInputGUI($lng->txt('pd_enable_my_offers'), 'enable_my_offers'); + $cb_prop->setValue('1'); + $cb_prop->setInfo($lng->txt('pd_enable_my_offers_info')); + $cb_prop->setChecked($this->viewSettings->enabledSelectedItems()); + $form->addItem($cb_prop); + + // Enable 'My Memberships' + $cb_prop = new ilCheckboxInputGUI($lng->txt('pd_enable_my_memberships'), 'enable_my_memberships'); + $cb_prop->setValue('1'); + $cb_prop->setInfo($lng->txt('pd_enable_my_memberships_info')); + $cb_prop->setChecked($this->viewSettings->enabledMemberships()); + $form->addItem($cb_prop); + + $memberships_sort_defaults = new ilRadioGroupInputGUI($lng->txt('pd_my_memberships_sort_default'), 'my_memberships_sort_default'); + $memberships_sort_defaults->addOption(new ilRadioOption($lng->txt('pd_sort_by_location'), $this->viewSettings->getSortByLocationMode())); + $memberships_sort_defaults->addOption(new ilRadioOption($lng->txt('pd_sort_by_type'), $this->viewSettings->getSortByTypeMode())); + $memberships_sort_defaults->addOption(new ilRadioOption($lng->txt('pd_sort_by_start_date'), $this->viewSettings->getSortByStartDateMode())); + $memberships_sort_defaults->setRequired(true); + $memberships_sort_defaults->setValue($this->viewSettings->getDefaultSortType()); + $cb_prop->addSubItem($memberships_sort_defaults); + + #22357 + $this->ctrl->setParameterByClass("iluserstartingpointgui", "ref_id", USER_FOLDER_ID); + $url = $this->ctrl->getLinkTargetByClass(array("iladministrationgui","ilobjuserfoldergui", "iluserstartingpointgui"), "startingpoints"); + $this->ctrl->setParameterByClass("iluserstartingpointgui", "ref_id", $_GET['ref_id']); + + $lng->loadLanguageModule("user"); + $starting_point_button = $this->ui_factory->button()->shy($lng->txt("starting_points"), $url); + $button = new ilCustomInputGUI($lng->txt('pd_personal_items_default_view'), ''); + $button->setHtml($this->ui_renderer->render($starting_point_button)); + $form->addItem($button); + + if ($ilAccess->checkAccess('write', '', $this->object->getRefId())) { + // command buttons + $form->addCommandButton("saveSettings", $lng->txt("save")); + $form->addCommandButton("view", $lng->txt("cancel")); + } + + $this->tpl->setContent($form->getHTML()); + } + + /** + * Save personal desktop settings + */ + public function saveSettings() + { + $ilCtrl = $this->ctrl; + $ilSetting = $this->settings; + $ilAccess = $this->access; + + if (!$ilAccess->checkAccess('write', '', $this->object->getRefId())) { + $ilCtrl->redirect($this, "view"); + } + + $pd_set = new ilSetting("pd"); + + ilCalendarSettings::_getInstance()->setEnabled($_POST["enable_calendar"]); + ilCalendarSettings::_getInstance()->save(); + + #$ilSetting->set("enable_calendar", $_POST["enable_calendar"]); + $ilSetting->set("disable_bookmarks", (int) ($_POST["enable_bookmarks"] ? 0 : 1)); + + $ilSetting->set("disable_notes", (int) ($_POST["enable_notes"] ? 0 : 1)); + $ilSetting->set("disable_comments", (int) ($_POST["enable_comments"] ? 0 : 1)); + + $ilSetting->set("enable_learning_history", (int) $_POST["enable_learning_history"]); + + $ilSetting->set("comments_del_user", (int) ($_POST["comm_del_user"] ? 1 : 0)); + $ilSetting->set("comments_del_tutor", (int) ($_POST["comm_del_tutor"] ? 1 : 0)); + $ilSetting->set("comments_noti_recip", ilUtil::stripSlashes($_POST["comments_noti_recip"])); + + $ilSetting->set("block_activated_chatviewer", (int) ($_POST["block_activated_chatviewer"])); + $ilSetting->set("pd_sys_msg_mode", (int) ($_POST["pd_sys_msg_mode"])); + if ($ilSetting->get('save_post_drafts', 0)) { + $ilSetting->set("block_activated_pdfrmpostdraft", (int) $_POST["block_activated_pdfrmpostdraft"]); + } + $pd_set->set("enable_block_moving", $_POST["enable_block_moving"]); + // $pd_set->set("user_activity_time", (int) $_POST["time_removal"]); + + // Validate personal desktop view + if (!(int) $_POST['enable_my_offers'] && !(int) $_POST['enable_my_memberships']) { + ilUtil::sendFailure($this->lng->txt('pd_view_select_at_least_one'), true); + $ilCtrl->redirect($this, 'view'); + } + + $this->viewSettings->enableSelectedItems((int) ($_POST['enable_my_offers'] ? 1 : 0)); + $this->viewSettings->enableMemberships((int) ($_POST['enable_my_memberships'] ? 1 : 0)); + + if ((int) $_POST['enable_my_offers'] && !(int) $_POST['enable_my_memberships']) { + $this->viewSettings->storeDefaultView($this->viewSettings->getSelectedItemsView()); + } elseif (!(int) $_POST['enable_my_offers'] && (int) $_POST['enable_my_memberships']) { + $this->viewSettings->storeDefaultView($this->viewSettings->getMembershipsView()); + } elseif (isset($_POST['personal_items_default_view'])) { + $this->viewSettings->storeDefaultView((int) $_POST['personal_items_default_view']); + } + + $this->viewSettings->storeDefaultSortType(ilUtil::stripSlashes($_POST['my_memberships_sort_default'])); + + ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "view"); + } + + /** + * Edit personal workspace settings. + */ + public function editWsp() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilSetting = $this->settings; + $ilAccess = $this->access; + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this, "saveWsp")); + $form->setTitle($lng->txt("pd_personal_workspace")); + + // Enable 'Personal Workspace' + $wsp_prop = new ilCheckboxInputGUI($lng->txt('pd_enable_personal_workspace'), 'wsp'); + $wsp_prop->setValue('1'); + $wsp_prop->setChecked(($ilSetting->get('disable_personal_workspace') ? '0' : '1')); + $form->addItem($wsp_prop); + + // Enable 'Blogs' + $blog_prop = new ilCheckboxInputGUI($lng->txt('pd_enable_wsp_blogs'), 'blog'); + $blog_prop->setValue('1'); + $blog_prop->setChecked(($ilSetting->get('disable_wsp_blogs') ? '0' : '1')); + $wsp_prop->addSubItem($blog_prop); + + // Enable 'Files' + $file_prop = new ilCheckboxInputGUI($lng->txt('pd_enable_wsp_files'), 'file'); + $file_prop->setValue('1'); + $file_prop->setChecked(($ilSetting->get('disable_wsp_files') ? '0' : '1')); + $wsp_prop->addSubItem($file_prop); + + // Enable 'Certificates' + $cert_prop = new ilCheckboxInputGUI($lng->txt('pd_enable_wsp_certificates'), 'cert'); + $cert_prop->setValue('1'); + $cert_prop->setChecked(($ilSetting->get('disable_wsp_certificates') ? '0' : '1')); + $wsp_prop->addSubItem($cert_prop); + + // Enable 'Links' + $link_prop = new ilCheckboxInputGUI($lng->txt('pd_enable_wsp_links'), 'link'); + $link_prop->setValue('1'); + $link_prop->setChecked(($ilSetting->get('disable_wsp_links') ? '0' : '1')); + $wsp_prop->addSubItem($link_prop); + + /* + // Enable 'Portfolios' + $lng->loadLanguageModule('user'); + $prtf_prop = new ilCheckboxInputGUI($lng->txt('pd_enable_prtf'), 'prtf'); + $prtf_prop->setValue('1'); + $prtf_prop->setInfo($lng->txt('user_portfolios_desc')); + $prtf_prop->setChecked(($ilSetting->get('user_portfolios') ? '1' : '0')); + $form->addItem($prtf_prop); + */ + + // Load the disk quota settings object + require_once 'Services/WebDAV/classes/class.ilObjDiskQuotaSettings.php'; + $disk_quota_obj = ilObjDiskQuotaSettings::getInstance(); + + // Enable disk quota + $lng->loadLanguageModule("file"); + $cb_prop = new ilCheckboxInputGUI($lng->txt("personal_workspace_disk_quota"), "enable_personal_workspace_disk_quota"); + $cb_prop->setValue('1'); + $cb_prop->setChecked($disk_quota_obj->isPersonalWorkspaceDiskQuotaEnabled()); + $cb_prop->setInfo($lng->txt('enable_personal_workspace_disk_quota_info')); + $form->addItem($cb_prop); + + require_once 'Services/Administration/classes/class.ilAdministrationSettingsFormHandler.php'; + ilAdministrationSettingsFormHandler::addFieldsToForm( + ilAdministrationSettingsFormHandler::FORM_WSP, + $form, + $this + ); + + if ($ilAccess->checkAccess('write', '', $this->object->getRefId())) { + // command buttons + $form->addCommandButton("saveWsp", $lng->txt("save")); + $form->addCommandButton("editWsp", $lng->txt("cancel")); + } + + $this->tpl->setContent($form->getHTML()); + } + + /** + * Save personal desktop settings + */ + public function saveWsp() + { + $ilCtrl = $this->ctrl; + $ilSetting = $this->settings; + $ilAccess = $this->access; + + if (!$ilAccess->checkAccess('write', '', $this->object->getRefId())) { + $ilCtrl->redirect($this, "view"); + } + + // without personal workspace we have to disable to sub-items + if (!$_POST["wsp"]) { + $_POST["blog"] = 0; + $_POST["file"] = 0; + $_POST["cert"] = 0; + $_POST["link"] = 0; + } + + $ilSetting->set('disable_personal_workspace', (int) ($_POST['wsp'] ? 0 : 1)); + $ilSetting->set('disable_wsp_blogs', (int) ($_POST['blog'] ? 0 : 1)); + $ilSetting->set('disable_wsp_files', (int) ($_POST['file'] ? 0 : 1)); + $ilSetting->set('disable_wsp_certificates', (int) ($_POST['cert'] ? 0 : 1)); + $ilSetting->set('disable_wsp_links', (int) ($_POST['link'] ? 0 : 1)); + // $ilSetting->set('user_portfolios', (int)($_POST['prtf'] ? 1 : 0)); + + // Load the disk quota settings object + require_once 'Services/WebDAV/classes/class.ilObjDiskQuotaSettings.php'; + $disk_quota_obj = ilObjDiskQuotaSettings::getInstance(); + $disk_quota_obj->setPersonalWorkspaceDiskQuotaEnabled($_POST['enable_personal_workspace_disk_quota'] == '1'); + $disk_quota_obj->update(); + + ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "editWsp"); + } + + public function addToExternalSettingsForm($a_form_id) + { + switch ($a_form_id) { + case ilAdministrationSettingsFormHandler::FORM_FILES_QUOTA: + + require_once 'Services/WebDAV/classes/class.ilObjDiskQuotaSettings.php'; + $disk_quota_obj = ilObjDiskQuotaSettings::getInstance(); + + $fields = array('personal_workspace_disk_quota' => array($disk_quota_obj->isPersonalWorkspaceDiskQuotaEnabled(), ilAdministrationSettingsFormHandler::VALUE_BOOL)); + + return array(array("editWsp", $fields)); + } + } } - -?> diff --git a/Services/PersonalDesktop/classes/class.ilPDContentBlockGUI.php b/Services/PersonalDesktop/classes/class.ilPDContentBlockGUI.php index b01e0627874760e30c1c98f2e4e55588572cf854..bf69011c6ad027edc3557cfd2c4b14ccfc021aa0 100755 --- a/Services/PersonalDesktop/classes/class.ilPDContentBlockGUI.php +++ b/Services/PersonalDesktop/classes/class.ilPDContentBlockGUI.php @@ -1,24 +1,24 @@ ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->user = $DIC->user(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->user = $DIC->user(); - parent::__construct(); - - $this->setEnableNumInfo(false); - $this->setLimit(99999); - $this->setBigMode(true); - $this->allow_moving = false; - } + parent::__construct(); + + $this->setEnableNumInfo(false); + $this->setLimit(99999); + $this->setBigMode(true); + $this->allow_moving = false; + } - /** - * @inheritdoc - */ - public function getBlockType(): string - { - return self::$block_type; - } + /** + * @inheritdoc + */ + public function getBlockType() : string + { + return self::$block_type; + } - /** - * Set Current Item Number. - * - * @param int $a_currentitemnumber Current Item Number - */ - function setCurrentItemNumber($a_currentitemnumber) - { - $this->currentitemnumber = $a_currentitemnumber; - } + /** + * Set Current Item Number. + * + * @param int $a_currentitemnumber Current Item Number + */ + public function setCurrentItemNumber($a_currentitemnumber) + { + $this->currentitemnumber = $a_currentitemnumber; + } - /** - * Get Current Item Number. - * - * @return int Current Item Number - */ - function getCurrentItemNumber() - { - return $this->currentitemnumber; - } + /** + * Get Current Item Number. + * + * @return int Current Item Number + */ + public function getCurrentItemNumber() + { + return $this->currentitemnumber; + } - /** - * @inheritdoc - */ - protected function isRepositoryObject(): bool - { - return false; - } + /** + * @inheritdoc + */ + protected function isRepositoryObject() : bool + { + return false; + } - function getHTML() - { - return parent::getHTML(); - } - - function getContent() - { - return $this->content; - } - - function setContent($a_content) - { - $this->content = $a_content; - } - - /** - * Fill data section - */ - function fillDataSection() - { - $this->tpl->setVariable("BLOCK_ROW", $this->getContent()); - } + public function getHTML() + { + return parent::getHTML(); + } + + public function getContent() + { + return $this->content; + } + + public function setContent($a_content) + { + $this->content = $a_content; + } + + /** + * Fill data section + */ + public function fillDataSection() + { + $this->tpl->setVariable("BLOCK_ROW", $this->getContent()); + } - /** - * block footer - */ - function fillFooter() - { - //$this->fillFooterLinks(); - $lng = $this->lng; + /** + * block footer + */ + public function fillFooter() + { + //$this->fillFooterLinks(); + $lng = $this->lng; - if (is_array($this->data)) - { - $this->max_count = count($this->data); - } - - // table footer numinfo - if ($this->getEnableNumInfo()) - { - $numinfo = "(".$this->getCurrentItemNumber()." ". - strtolower($lng->txt("of"))." ".$this->max_count.")"; - - if ($this->max_count > 0) - { - $this->tpl->setVariable("NUMINFO", $numinfo); - } - $this->fillFooterLinks(true, $numinfo); - } - } - - function fillPreviousNext() - { - } + if (is_array($this->data)) { + $this->max_count = count($this->data); + } + + // table footer numinfo + if ($this->getEnableNumInfo()) { + $numinfo = "(" . $this->getCurrentItemNumber() . " " . + strtolower($lng->txt("of")) . " " . $this->max_count . ")"; + + if ($this->max_count > 0) { + $this->tpl->setVariable("NUMINFO", $numinfo); + } + $this->fillFooterLinks(true, $numinfo); + } + } + + public function fillPreviousNext() + { + } } - -?> diff --git a/Services/PersonalDesktop/classes/class.ilPDGlobalScreenProvider.php b/Services/PersonalDesktop/classes/class.ilPDGlobalScreenProvider.php index e40c93b30b8328fdad5401d2c2b799871b7c2894..ba6710eb768426f82a26ee0e0dc4de32a55c909a 100644 --- a/Services/PersonalDesktop/classes/class.ilPDGlobalScreenProvider.php +++ b/Services/PersonalDesktop/classes/class.ilPDGlobalScreenProvider.php @@ -8,112 +8,117 @@ use ILIAS\GlobalScreen\Scope\MainMenu\Provider\AbstractStaticMainMenuProvider; * * @author Fabian Schmid */ -class ilPDGlobalScreenProvider extends AbstractStaticMainMenuProvider { - - /** - * @var IdentificationInterface - */ - protected $top_item; - - - public function __construct(\ILIAS\DI\Container $dic) { - parent::__construct($dic); - $this->top_item = $this->if->identifier('desktop'); - } - - - /** - * Some other components want to provide Items for the main menu which are - * located at the PD TopTitem by default. Therefore we have to provide our - * TopTitem Identification for others - * - * @return IdentificationInterface - */ - public function getTopItem(): IdentificationInterface { - return $this->top_item; - } - - - /** - * @inheritDoc - */ - public function getStaticTopItems(): array { - $dic = $this->dic; - - // Personal Desktop TopParentItem - return [$this->mainmenu->topParentItem($this->getTopItem()) - ->withTitle($this->dic->language()->txt("personal_desktop")) - ->withPosition(1) - ->withVisibilityCallable( - function () use ($dic) { - return (bool)($dic->user()->getId() != ANONYMOUS_USER_ID); - } - )]; - } - - - /** - * @inheritDoc - */ - public function getStaticSubItems(): array { - $dic = $this->dic; - - $dic->language()->loadLanguageModule("pd"); - - // overview - $entries[] = $this->mainmenu->link($this->if->identifier('mm_pd_sel_items')) - ->withTitle($this->dic->language()->txt("overview")) - ->withAction("ilias.php?baseClass=ilPersonalDesktopGUI&cmd=jumpToSelectedItems") - ->withParent($this->getTopItem()) - ->withPosition(1) - ->withNonAvailableReason($this->dic->ui()->factory()->legacy("{$this->dic->language()->txt('component_not_active')}")) - ->withAvailableCallable( - function () use ($dic) { - return $dic->settings()->get('disable_my_offers', 0) == 0; - } - ) - ->withVisibilityCallable( - function () use ($dic) { - $pdItemsViewSettings = new ilPDSelectedItemsBlockViewSettings($dic->user()); - - return (bool)$pdItemsViewSettings->allViewsEnabled() || $pdItemsViewSettings->enabledSelectedItems(); - } - ); - - // my groups and courses, if both is available - $entries[] = $this->mainmenu->link($this->if->identifier('mm_pd_crs_grp')) - ->withTitle($this->dic->language()->txt("my_courses_groups")) - ->withAction("ilias.php?baseClass=ilPersonalDesktopGUI&cmd=jumpToMemberships") - ->withParent($this->getTopItem()) - ->withPosition(2) - ->withNonAvailableReason($this->dic->ui()->factory()->legacy("{$this->dic->language()->txt('component_not_active')}")) - ->withAvailableCallable( - function () use ($dic) { - return $dic->settings()->get('disable_my_memberships', 0) == 0; - } - ) - ->withVisibilityCallable( - function () use ($dic) { - $pdItemsViewSettings = new ilPDSelectedItemsBlockViewSettings($dic->user()); - - return (bool)$pdItemsViewSettings->allViewsEnabled() || $pdItemsViewSettings->enabledMemberships(); - } - ); - - // achievements - $entries[] = $this->mainmenu->link($this->if->identifier('mm_pd_achiev')) - ->withTitle($this->dic->language()->txt("pd_achievements")) - ->withAction($dic->ctrl()->getLinkTargetByClass(["ilPersonalDesktopGUI", "ilAchievementsGUI"], "")) - ->withParent($this->getTopItem()) - ->withPosition(7) - ->withAvailableCallable( - function () use ($dic) { - $achievements = new ilAchievements(); - - return (bool)$achievements->isAnyActive(); - } - ); - - return $entries; - } +class ilPDGlobalScreenProvider extends AbstractStaticMainMenuProvider +{ + + /** + * @var IdentificationInterface + */ + protected $top_item; + + + public function __construct(\ILIAS\DI\Container $dic) + { + parent::__construct($dic); + $this->top_item = $this->if->identifier('desktop'); + } + + + /** + * Some other components want to provide Items for the main menu which are + * located at the PD TopTitem by default. Therefore we have to provide our + * TopTitem Identification for others + * + * @return IdentificationInterface + */ + public function getTopItem() : IdentificationInterface + { + return $this->top_item; + } + + + /** + * @inheritDoc + */ + public function getStaticTopItems() : array + { + $dic = $this->dic; + + // Personal Desktop TopParentItem + return [$this->mainmenu->topParentItem($this->getTopItem()) + ->withTitle($this->dic->language()->txt("personal_desktop")) + ->withPosition(1) + ->withVisibilityCallable( + function () use ($dic) { + return (bool) ($dic->user()->getId() != ANONYMOUS_USER_ID); + } + )]; + } + + + /** + * @inheritDoc + */ + public function getStaticSubItems() : array + { + $dic = $this->dic; + + $dic->language()->loadLanguageModule("pd"); + + // overview + $entries[] = $this->mainmenu->link($this->if->identifier('mm_pd_sel_items')) + ->withTitle($this->dic->language()->txt("overview")) + ->withAction("ilias.php?baseClass=ilPersonalDesktopGUI&cmd=jumpToSelectedItems") + ->withParent($this->getTopItem()) + ->withPosition(1) + ->withNonAvailableReason($this->dic->ui()->factory()->legacy("{$this->dic->language()->txt('component_not_active')}")) + ->withAvailableCallable( + function () use ($dic) { + return $dic->settings()->get('disable_my_offers', 0) == 0; + } + ) + ->withVisibilityCallable( + function () use ($dic) { + $pdItemsViewSettings = new ilPDSelectedItemsBlockViewSettings($dic->user()); + + return (bool) $pdItemsViewSettings->allViewsEnabled() || $pdItemsViewSettings->enabledSelectedItems(); + } + ); + + // my groups and courses, if both is available + $entries[] = $this->mainmenu->link($this->if->identifier('mm_pd_crs_grp')) + ->withTitle($this->dic->language()->txt("my_courses_groups")) + ->withAction("ilias.php?baseClass=ilPersonalDesktopGUI&cmd=jumpToMemberships") + ->withParent($this->getTopItem()) + ->withPosition(2) + ->withNonAvailableReason($this->dic->ui()->factory()->legacy("{$this->dic->language()->txt('component_not_active')}")) + ->withAvailableCallable( + function () use ($dic) { + return $dic->settings()->get('disable_my_memberships', 0) == 0; + } + ) + ->withVisibilityCallable( + function () use ($dic) { + $pdItemsViewSettings = new ilPDSelectedItemsBlockViewSettings($dic->user()); + + return (bool) $pdItemsViewSettings->allViewsEnabled() || $pdItemsViewSettings->enabledMemberships(); + } + ); + + // achievements + $entries[] = $this->mainmenu->link($this->if->identifier('mm_pd_achiev')) + ->withTitle($this->dic->language()->txt("pd_achievements")) + ->withAction($dic->ctrl()->getLinkTargetByClass(["ilPersonalDesktopGUI", "ilAchievementsGUI"], "")) + ->withParent($this->getTopItem()) + ->withPosition(7) + ->withAvailableCallable( + function () use ($dic) { + $achievements = new ilAchievements(); + + return (bool) $achievements->isAnyActive(); + } + ); + + return $entries; + } } diff --git a/Services/PersonalDesktop/classes/class.ilPersonalDesktopGUI.php b/Services/PersonalDesktop/classes/class.ilPersonalDesktopGUI.php index 043e7e9eb3ba73c4345f6fe6f2d9db55b216b274..26d9613dc915cfd04bf89fbd9d0b3f9ae33251a8 100755 --- a/Services/PersonalDesktop/classes/class.ilPersonalDesktopGUI.php +++ b/Services/PersonalDesktop/classes/class.ilPersonalDesktopGUI.php @@ -25,813 +25,775 @@ include_once 'Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvance */ class ilPersonalDesktopGUI { - const CMD_JUMP_TO_MY_STAFF = "jumpToMyStaff"; - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilMainMenuGUI - */ - protected $main_menu; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * @var ilSetting - */ - protected $settings; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilPluginAdmin - */ - protected $plugin_admin; - - /** - * @var ilHelpGUI - */ - protected $help; - - var $tpl; - var $lng; - - var $cmdClass = ''; - - /** - * @var ilAdvancedSelectionListGUI - */ - protected $action_menu; - - /** - * constructor - */ - function __construct() - { - global $DIC; - - $this->main_menu = $DIC["ilMainMenu"]; - $this->user = $DIC->user(); - $this->error = $DIC["ilErr"]; - $this->settings = $DIC->settings(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->plugin_admin = $DIC["ilPluginAdmin"]; - $this->help = $DIC["ilHelp"]; - $tpl = $DIC["tpl"]; - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $ilMainMenu = $DIC["ilMainMenu"]; - $ilUser = $DIC->user(); - $ilErr = $DIC["ilErr"]; - - - $this->tpl = $tpl; - $this->lng = $lng; - $this->ctrl = $ilCtrl; - - $ilCtrl->setContext($ilUser->getId(), - "user"); - - $ilMainMenu->setActive("desktop"); - $this->lng->loadLanguageModule("pdesk"); - $this->lng->loadLanguageModule("pd"); // #16813 - - // catch hack attempts - if ($GLOBALS['DIC']['ilUser']->getId() == ANONYMOUS_USER_ID) - { - $ilErr->raiseError($this->lng->txt("msg_not_available_for_anon"), $ilErr->MESSAGE); - } - $this->cmdClass = $_GET['cmdClass']; - - $this->ctrl->saveParameter($this, array("view")); - - //$tree->useCache(false); - - $this->action_menu = new ilAdvancedSelectionListGUI(); - } - - /** - * execute command - */ - function executeCommand() - { - $ilSetting = $this->settings; - $rbacsystem = $this->rbacsystem; - $ilErr = $this->error; - - $next_class = $this->ctrl->getNextClass(); - $this->ctrl->setReturn($this, "show"); - - $this->tpl->addCss(ilUtil::getStyleSheetLocation('filesystem','delos.css','Services/Calendar')); - - // read last active subsection - if (isset($_GET['PDHistory']) && $_GET['PDHistory']) - { - $next_class = $this->__loadNextClass(); - } - $this->__storeLastClass($next_class); - - switch($next_class) - { - case "ilbookmarkadministrationgui": - if ($ilSetting->get('disable_bookmarks')) - { - ilUtil::sendFailure($this->lng->txt('permission_denied'), true); - ilUtil::redirect('ilias.php?baseClass=ilPersonalDesktopGUI'); - return; - } - include_once("./Services/Bookmarks/classes/class.ilBookmarkAdministrationGUI.php"); - $bookmark_gui = new ilBookmarkAdministrationGUI(); - $this->getStandardTemplates(); - $this->setTabs(); - $ret = $this->ctrl->forwardCommand($bookmark_gui); - break; - - // profile - case "ilpersonalprofilegui": - $this->getStandardTemplates(); - $this->setTabs(); - include_once("./Services/User/classes/class.ilPersonalProfileGUI.php"); - $profile_gui = new ilPersonalProfileGUI(); - $ret = $this->ctrl->forwardCommand($profile_gui); - break; - - // settings - case "ilpersonalsettingsgui": - $this->getStandardTemplates(); - $this->setTabs(); - include_once("./Services/User/classes/class.ilPersonalSettingsGUI.php"); - $settings_gui = new ilPersonalSettingsGUI(); - $ret = $this->ctrl->forwardCommand($settings_gui); - break; - - // profile - case "ilobjusergui": - include_once('./Services/User/classes/class.ilObjUserGUI.php'); - $user_gui = new ilObjUserGUI("",$_GET["user"], false, false); - $ret = $this->ctrl->forwardCommand($user_gui); - break; - - case 'ilcalendarpresentationgui': - $this->getStandardTemplates(); - $this->displayHeader(); - $this->tpl->setTitle($this->lng->txt("calendar")); - $this->setTabs(); - include_once('./Services/Calendar/classes/class.ilCalendarPresentationGUI.php'); - $cal = new ilCalendarPresentationGUI(); - $ret = $this->ctrl->forwardCommand($cal); - $this->tpl->show(); - break; - - // pd notes - case "ilpdnotesgui": - if ($ilSetting->get('disable_notes') && $ilSetting->get('disable_comments')) - { - ilUtil::sendFailure($this->lng->txt('permission_denied'), true); - ilUtil::redirect('ilias.php?baseClass=ilPersonalDesktopGUI'); - return; - } - - $this->getStandardTemplates(); - $this->setTabs(); - include_once("./Services/Notes/classes/class.ilPDNotesGUI.php"); - $pd_notes_gui = new ilPDNotesGUI(); - $ret = $this->ctrl->forwardCommand($pd_notes_gui); - break; - - // pd news - case "ilpdnewsgui": - $this->getStandardTemplates(); - $this->setTabs(); - include_once("./Services/News/classes/class.ilPDNewsGUI.php"); - $pd_news_gui = new ilPDNewsGUI(); - $ret = $this->ctrl->forwardCommand($pd_news_gui); - break; - - case "ilcolumngui": - $this->getStandardTemplates(); - $this->setTabs(); - include_once("./Services/Block/classes/class.ilColumnGUI.php"); - $column_gui = new ilColumnGUI("pd"); - $this->initColumn($column_gui); - $this->show(); - break; - - case 'ilcontactgui': - require_once 'Services/Contact/BuddySystem/classes/class.ilBuddySystem.php'; - if(!ilBuddySystem::getInstance()->isEnabled()) - { - $ilErr->raiseError($this->lng->txt('msg_no_perm_read'), $ilErr->MESSAGE); - } - - $this->getStandardTemplates(); - $this->setTabs(); - $this->tpl->setTitle($this->lng->txt('mail_addressbook')); - - require_once 'Services/Contact/classes/class.ilContactGUI.php'; - $this->ctrl->forwardCommand(new ilContactGUI()); - break; - - case 'ilpersonalworkspacegui': - // $this->getStandardTemplates(); - // $this->setTabs(); - include_once 'Services/PersonalWorkspace/classes/class.ilPersonalWorkspaceGUI.php'; - $wsgui = new ilPersonalWorkspaceGUI(); - $ret = $this->ctrl->forwardCommand($wsgui); - $this->tpl->show(); - break; - - case 'ilportfoliorepositorygui': - $this->getStandardTemplates(); - $this->setTabs(); - include_once 'Modules/Portfolio/classes/class.ilPortfolioRepositoryGUI.php'; - $pfgui = new ilPortfolioRepositoryGUI(); - $ret = $this->ctrl->forwardCommand($pfgui); - $this->tpl->show(); - break; - - case 'ilachievementsgui': - $this->getStandardTemplates(); - $this->setTabs(); - $achievegui = new ilAchievementsGUI(); - $ret = $this->ctrl->forwardCommand($achievegui); - break; - - case strtolower(ilMyStaffGUI::class): - $this->getStandardTemplates(); - $mstgui = new ilMyStaffGUI(); - $ret = $this->ctrl->forwardCommand($mstgui); - break; - case 'ilgroupuseractionsgui': - $this->getStandardTemplates(); - $this->setTabs(); - include_once './Modules/Group/UserActions/classes/class.ilGroupUserActionsGUI.php'; - $ggui = new ilGroupUserActionsGUI(); - $ret = $this->ctrl->forwardCommand($ggui); - $this->tpl->show(); - break; - case 'redirect': - $this->redirect(); - break; - - default: - $this->getStandardTemplates(); - $this->setTabs(); - $cmd = $this->ctrl->getCmd("show"); - $this->$cmd(); - break; - } - $ret = null; - return $ret; - } - - /** - * get standard templates - */ - function getStandardTemplates() - { - $this->tpl->getStandardTemplate(); - } - - /** - * show desktop - */ - function show() - { - // preload block settings - include_once("Services/Block/classes/class.ilBlockSetting.php"); - ilBlockSetting::preloadPDBlockSettings(); - - // add template for content - $this->pd_tpl = new ilTemplate("tpl.usr_personaldesktop.html", true, true, "Services/PersonalDesktop"); -// $this->tpl->getStandardTemplate(); - - // display infopanel if something happened - ilUtil::infoPanel(); - - $this->tpl->setTitle($this->lng->txt("overview")); - $this->tpl->setVariable("IMG_SPACE", ilUtil::getImagePath("spacer.png", false)); - - $this->tpl->setContent($this->getCenterColumnHTML()); - $this->tpl->setRightContent($this->getRightColumnHTML()); - $this->tpl->setLeftContent($this->getLeftColumnHTML()); - - if(count($this->action_menu->getItems())) - { - /** - * @var $tpl ilTemplate - * @var $lng ilLanguage - */ - $tpl = $this->tpl; - $lng = $this->lng; - - $this->action_menu->setAsynch(false); - $this->action_menu->setAsynchUrl(''); - $this->action_menu->setListTitle($lng->txt('actions')); - $this->action_menu->setId('act_pd'); - $this->action_menu->setSelectionHeaderClass('small'); - $this->action_menu->setItemLinkClass('xsmall'); - $this->action_menu->setLinksMode('il_ContainerItemCommand2'); - $this->action_menu->setHeaderIcon(ilAdvancedSelectionListGUI::DOWN_ARROW_DARK); - $this->action_menu->setUseImages(false); - - $htpl = new ilTemplate('tpl.header_action.html', true, true, 'Services/Repository'); - $htpl->setVariable('ACTION_DROP_DOWN', $this->action_menu->getHTML()); - - $tpl->setHeaderActionMenu($htpl->get()); - } - - $this->tpl->show(); - } - - - /** - * Display center column - */ - function getCenterColumnHTML() - { - $ilCtrl = $this->ctrl; - $ilPluginAdmin = $this->plugin_admin; - - include_once("Services/Block/classes/class.ilColumnGUI.php"); - $column_gui = new ilColumnGUI("pd", IL_COL_CENTER); - $this->initColumn($column_gui); - - if ($ilCtrl->getNextClass() == "ilcolumngui" && - $column_gui->getCmdSide() == IL_COL_CENTER) - { - $html = $ilCtrl->forwardCommand($column_gui); - } - else - { - if (!$ilCtrl->isAsynch()) - { - if ($column_gui->getScreenMode() != IL_SCREEN_SIDE) - { - // right column wants center - if ($column_gui->getCmdSide() == IL_COL_RIGHT) - { - $column_gui = new ilColumnGUI("pd", IL_COL_RIGHT); - $this->initColumn($column_gui); - $html = $ilCtrl->forwardCommand($column_gui); - } - // left column wants center - if ($column_gui->getCmdSide() == IL_COL_LEFT) - { - $column_gui = new ilColumnGUI("pd", IL_COL_LEFT); - $this->initColumn($column_gui); - $html = $ilCtrl->forwardCommand($column_gui); - } - } - else - { - $html = ""; - - // user interface plugin slot + default rendering - include_once("./Services/UIComponent/classes/class.ilUIHookProcessor.php"); - $uip = new ilUIHookProcessor("Services/PersonalDesktop", "center_column", - array("personal_desktop_gui" => $this)); - if (!$uip->replaced()) - { - $html = $ilCtrl->getHTML($column_gui); - } - $html = $uip->getHTML($html); - - } - } - } - return $html; - } - - /** - * Display right column - */ - function getRightColumnHTML() - { - $ilUser = $this->user; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilPluginAdmin = $this->plugin_admin; - - include_once("Services/Block/classes/class.ilColumnGUI.php"); - $column_gui = new ilColumnGUI("pd", IL_COL_RIGHT); - $this->initColumn($column_gui); - - if ($column_gui->getScreenMode() == IL_SCREEN_FULL) - { - return ""; - } - - if ($ilCtrl->getNextClass() == "ilcolumngui" && - $column_gui->getCmdSide() == IL_COL_RIGHT && - $column_gui->getScreenMode() == IL_SCREEN_SIDE) - { - $html = $ilCtrl->forwardCommand($column_gui); - } - else - { - if (!$ilCtrl->isAsynch()) - { - $html = ""; - - // user interface plugin slot + default rendering - include_once("./Services/UIComponent/classes/class.ilUIHookProcessor.php"); - $uip = new ilUIHookProcessor("Services/PersonalDesktop", "right_column", - array("personal_desktop_gui" => $this)); - if (!$uip->replaced()) - { - $html = $ilCtrl->getHTML($column_gui); - } - $html = $uip->getHTML($html); - } - } - - return $html; - } - - /** - * Display left column - */ - function getLeftColumnHTML() - { - $ilUser = $this->user; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilPluginAdmin = $this->plugin_admin; - - include_once("Services/Block/classes/class.ilColumnGUI.php"); - $column_gui = new ilColumnGUI("pd", IL_COL_LEFT); - $this->initColumn($column_gui); - - if ($column_gui->getScreenMode() == IL_SCREEN_FULL) - { - return ""; - } - - if ($ilCtrl->getNextClass() == "ilcolumngui" && - $column_gui->getCmdSide() == IL_COL_LEFT && - $column_gui->getScreenMode() == IL_SCREEN_SIDE) - { - $html = $ilCtrl->forwardCommand($column_gui); - } - else - { - if (!$ilCtrl->isAsynch()) - { - $html = ""; - - // user interface plugin slot + default rendering - include_once("./Services/UIComponent/classes/class.ilUIHookProcessor.php"); - $uip = new ilUIHookProcessor("Services/PersonalDesktop", "left_column", - array("personal_desktop_gui" => $this)); - if (!$uip->replaced()) - { - $html = $ilCtrl->getHTML($column_gui); - } - $html = $uip->getHTML($html); - } - } - - return $html; - } - - function prepareContentView() - { - // add template for content - $this->pd_tpl = new ilTemplate("tpl.usr_personaldesktop.html", true, true, "Services/PersonalDesktop"); - $this->tpl->getStandardTemplate(); - - // display infopanel if something happened - ilUtil::infoPanel(); - - $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_pd.svg")); - $this->tpl->setTitle($this->lng->txt("personal_desktop")); - $this->tpl->setVariable("IMG_SPACE", ilUtil::getImagePath("spacer.png", false)); - } - - /** - * Display system messages. - */ - function displaySystemMessages() - { - include_once("Services/Mail/classes/class.ilPDSysMessageBlockGUI.php"); - $sys_block = new ilPDSysMessageBlockGUI("ilpersonaldesktopgui", "show"); - return $sys_block->getHTML(); - } - - /** - * Returns the multidimenstional sorted array - * - * Returns the multidimenstional sorted array - * - * @author Muzaffar Altaf - * @param array $arrays The array to be sorted - * @param string $key_sort The keys on which array must be sorted - * @access public - */ - function multiarray_sort ($array, $key_sort) - { - if ($array) { - $key_sorta = explode(";", $key_sort); - - $multikeys = array_keys($array); - $keys = array_keys($array[$multikeys[0]]); - - for($m=0; $m < count($key_sorta); $m++) { - $nkeys[$m] = trim($key_sorta[$m]); - } - $n += count($key_sorta); - - for($i=0; $i < count($keys); $i++){ - if(!in_array($keys[$i], $key_sorta)) { - $nkeys[$n] = $keys[$i]; - $n += "1"; - } - } - - for($u=0;$uhelp; - - $ilHelp->setScreenIdComponent("pd"); - } - - /** - * Jump to memberships - */ - public function jumpToMemberships() - { - require_once 'Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockViewSettings.php'; - $viewSettings = new ilPDSelectedItemsBlockViewSettings($GLOBALS['DIC']->user(), (int)$_GET['view']); - if($viewSettings->enabledMemberships()) - { - $_GET['view'] = $viewSettings->getMembershipsView(); - $this->ctrl->setParameter($this, "view", $viewSettings->getMembershipsView()); - } - $this->show(); - } - - /** - * Jump to selected items - */ - public function jumpToSelectedItems() - { - require_once 'Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockViewSettings.php'; - $viewSettings = new ilPDSelectedItemsBlockViewSettings($GLOBALS['DIC']->user(), (int)$_GET['view']); - if($viewSettings->enabledSelectedItems()) - { - $_GET['view'] = $viewSettings->getSelectedItemsView(); - $this->ctrl->setParameter($this, "view", $viewSettings->getSelectedItemsView()); - } - $this->show(); - } - - /** - * workaround for menu in calendar only - */ - function jumpToProfile() - { - $this->ctrl->redirectByClass("ilpersonalprofilegui"); - } - - function jumpToPortfolio() - { - // incoming back link from shared resource - $cmd = ""; - if($_REQUEST["dsh"]) - { - $this->ctrl->setParameterByClass("ilportfoliorepositorygui", "shr_id", $_REQUEST["dsh"]); - $cmd = "showOther"; - } - - // used for goto links - if($_GET["prt_id"]) - { - $this->ctrl->setParameterByClass("ilobjportfoliogui", "prt_id", (int)$_GET["prt_id"]); - $this->ctrl->setParameterByClass("ilobjportfoliogui", "gtp", (int)$_GET["gtp"]); - $this->ctrl->redirectByClass(array("ilportfoliorepositorygui", "ilobjportfoliogui"), "preview"); - } - else - { - $this->ctrl->redirectByClass("ilportfoliorepositorygui", $cmd); - } - } - - /** - * workaround for menu in calendar only - */ - function jumpToSettings() - { - $this->ctrl->redirectByClass("ilpersonalsettingsgui"); - } - - /** - * workaround for menu in calendar only - */ - function jumpToBookmarks() - { - $ilSetting = $this->settings; - - if ($ilSetting->get("disable_bookmarks")) - { - ilUtil::sendFailure($this->lng->txt('permission_denied'), true); - ilUtil::redirect('ilias.php?baseClass=ilPersonalDesktopGUI'); - return; - } - - $this->ctrl->redirectByClass("ilbookmarkadministrationgui"); - } - - /** - * workaround for menu in calendar only - */ - function jumpToNotes() - { - $ilSetting = $this->settings; - - if ($ilSetting->get('disable_notes')) - { - ilUtil::sendFailure($this->lng->txt('permission_denied'), true); - ilUtil::redirect('ilias.php?baseClass=ilPersonalDesktopGUI'); - return; - } - - $this->ctrl->redirectByClass("ilpdnotesgui"); - } - - /** - * workaround for menu in calendar only - */ - function jumpToComments() - { - $ilSetting = $this->settings; - - if ($ilSetting->get('disable_comments')) - { - ilUtil::sendFailure($this->lng->txt('permission_denied'), true); - ilUtil::redirect('ilias.php?baseClass=ilPersonalDesktopGUI'); - return; - } - - $this->ctrl->redirectByClass("ilpdnotesgui", "showPublicComments"); - } - - /** - * workaround for menu in calendar only - */ - function jumpToNews() - { - $this->ctrl->redirectByClass("ilpdnewsgui"); - } - - /** - * workaround for menu in calendar only - */ - function jumpToLP() - { - $this->ctrl->redirectByClass("illearningprogressgui"); - } - - /** - * Jump to calendar - */ - function jumpToCalendar() - { - $this->ctrl->redirectByClass("ilcalendarpresentationgui"); - } - - /** - * Jump to contacts - */ - function jumpToContacts() - { - $this->ctrl->redirectByClass(array('ilpersonaldesktopgui', 'ilcontactgui')); - } - - /** - * Jump to personal workspace - */ - function jumpToWorkspace() - { - // incoming back link from shared resource - $cmd = ""; - if($_REQUEST["dsh"]) - { - $this->ctrl->setParameterByClass("ilpersonalworkspacegui", "shr_id", $_REQUEST["dsh"]); - $cmd = "share"; - } - - if($_REQUEST["wsp_id"]) - { - $this->ctrl->setParameterByClass("ilpersonalworkspacegui", "wsp_id", (int)$_REQUEST["wsp_id"]); - } - - if($_REQUEST["gtp"]) - { - $this->ctrl->setParameterByClass("ilpersonalworkspacegui", "gtp", (int)$_REQUEST["gtp"]); - } - - $this->ctrl->redirectByClass("ilpersonalworkspacegui", $cmd); - } - - /** - * - */ - protected function jumpToMyStaff() - { - $this->ctrl->redirectByClass(ilMyStaffGUI::class); - } - - /** - * Jump to badges - */ - function jumpToBadges() - { - $this->ctrl->redirectByClass(["ilAchievementsGUI", "ilbadgeprofilegui"]); - } - - /** - * Jump to personal skills - */ - function jumpToSkills() - { - $this->ctrl->redirectByClass("ilpersonalskillsgui"); - } - - function __loadNextClass() - { - $stored_classes = array('ilpersonaldesktopgui', - 'ilpersonalprofilegui', - 'ilpdnotesgui', - 'ilcalendarpresentationgui', - 'ilbookmarkadministrationgui', - 'illearningprogressgui'); - - if(isset($_SESSION['il_pd_history']) and in_array($_SESSION['il_pd_history'],$stored_classes)) - { - return $_SESSION['il_pd_history']; - } - else - { - $this->ctrl->getNextClass($this); - } - } - function __storeLastClass($a_class) - { - $_SESSION['il_pd_history'] = $a_class; - $this->cmdClass = $a_class; - } - - /** - * Init ilColumnGUI - * @var ilColumnGUI $a_column_gui - */ - function initColumn($a_column_gui) - { - $pd_set = new ilSetting("pd"); - if ($pd_set->get("enable_block_moving")) - { - $a_column_gui->setEnableMovement(true); - } - $a_column_gui->setActionMenu($this->action_menu); - } - - /** - * display header and locator - */ - function displayHeader() - { - $this->tpl->setTitle($this->lng->txt("personal_desktop")); - } - - + const CMD_JUMP_TO_MY_STAFF = "jumpToMyStaff"; + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilMainMenuGUI + */ + protected $main_menu; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilPluginAdmin + */ + protected $plugin_admin; + + /** + * @var ilHelpGUI + */ + protected $help; + + public $tpl; + public $lng; + + public $cmdClass = ''; + + /** + * @var ilAdvancedSelectionListGUI + */ + protected $action_menu; + + /** + * constructor + */ + public function __construct() + { + global $DIC; + + $this->main_menu = $DIC["ilMainMenu"]; + $this->user = $DIC->user(); + $this->error = $DIC["ilErr"]; + $this->settings = $DIC->settings(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->plugin_admin = $DIC["ilPluginAdmin"]; + $this->help = $DIC["ilHelp"]; + $tpl = $DIC["tpl"]; + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $ilMainMenu = $DIC["ilMainMenu"]; + $ilUser = $DIC->user(); + $ilErr = $DIC["ilErr"]; + + + $this->tpl = $tpl; + $this->lng = $lng; + $this->ctrl = $ilCtrl; + + $ilCtrl->setContext( + $ilUser->getId(), + "user" + ); + + $ilMainMenu->setActive("desktop"); + $this->lng->loadLanguageModule("pdesk"); + $this->lng->loadLanguageModule("pd"); // #16813 + + // catch hack attempts + if ($GLOBALS['DIC']['ilUser']->getId() == ANONYMOUS_USER_ID) { + $ilErr->raiseError($this->lng->txt("msg_not_available_for_anon"), $ilErr->MESSAGE); + } + $this->cmdClass = $_GET['cmdClass']; + + $this->ctrl->saveParameter($this, array("view")); + + //$tree->useCache(false); + + $this->action_menu = new ilAdvancedSelectionListGUI(); + } + + /** + * execute command + */ + public function executeCommand() + { + $ilSetting = $this->settings; + $rbacsystem = $this->rbacsystem; + $ilErr = $this->error; + + $next_class = $this->ctrl->getNextClass(); + $this->ctrl->setReturn($this, "show"); + + $this->tpl->addCss(ilUtil::getStyleSheetLocation('filesystem', 'delos.css', 'Services/Calendar')); + + // read last active subsection + if (isset($_GET['PDHistory']) && $_GET['PDHistory']) { + $next_class = $this->__loadNextClass(); + } + $this->__storeLastClass($next_class); + + switch ($next_class) { + case "ilbookmarkadministrationgui": + if ($ilSetting->get('disable_bookmarks')) { + ilUtil::sendFailure($this->lng->txt('permission_denied'), true); + ilUtil::redirect('ilias.php?baseClass=ilPersonalDesktopGUI'); + return; + } + include_once("./Services/Bookmarks/classes/class.ilBookmarkAdministrationGUI.php"); + $bookmark_gui = new ilBookmarkAdministrationGUI(); + $this->getStandardTemplates(); + $this->setTabs(); + $ret = $this->ctrl->forwardCommand($bookmark_gui); + break; + + // profile + case "ilpersonalprofilegui": + $this->getStandardTemplates(); + $this->setTabs(); + include_once("./Services/User/classes/class.ilPersonalProfileGUI.php"); + $profile_gui = new ilPersonalProfileGUI(); + $ret = $this->ctrl->forwardCommand($profile_gui); + break; + + // settings + case "ilpersonalsettingsgui": + $this->getStandardTemplates(); + $this->setTabs(); + include_once("./Services/User/classes/class.ilPersonalSettingsGUI.php"); + $settings_gui = new ilPersonalSettingsGUI(); + $ret = $this->ctrl->forwardCommand($settings_gui); + break; + + // profile + case "ilobjusergui": + include_once('./Services/User/classes/class.ilObjUserGUI.php'); + $user_gui = new ilObjUserGUI("", $_GET["user"], false, false); + $ret = $this->ctrl->forwardCommand($user_gui); + break; + + case 'ilcalendarpresentationgui': + $this->getStandardTemplates(); + $this->displayHeader(); + $this->tpl->setTitle($this->lng->txt("calendar")); + $this->setTabs(); + include_once('./Services/Calendar/classes/class.ilCalendarPresentationGUI.php'); + $cal = new ilCalendarPresentationGUI(); + $ret = $this->ctrl->forwardCommand($cal); + $this->tpl->show(); + break; + + // pd notes + case "ilpdnotesgui": + if ($ilSetting->get('disable_notes') && $ilSetting->get('disable_comments')) { + ilUtil::sendFailure($this->lng->txt('permission_denied'), true); + ilUtil::redirect('ilias.php?baseClass=ilPersonalDesktopGUI'); + return; + } + + $this->getStandardTemplates(); + $this->setTabs(); + include_once("./Services/Notes/classes/class.ilPDNotesGUI.php"); + $pd_notes_gui = new ilPDNotesGUI(); + $ret = $this->ctrl->forwardCommand($pd_notes_gui); + break; + + // pd news + case "ilpdnewsgui": + $this->getStandardTemplates(); + $this->setTabs(); + include_once("./Services/News/classes/class.ilPDNewsGUI.php"); + $pd_news_gui = new ilPDNewsGUI(); + $ret = $this->ctrl->forwardCommand($pd_news_gui); + break; + + case "ilcolumngui": + $this->getStandardTemplates(); + $this->setTabs(); + include_once("./Services/Block/classes/class.ilColumnGUI.php"); + $column_gui = new ilColumnGUI("pd"); + $this->initColumn($column_gui); + $this->show(); + break; + + case 'ilcontactgui': + require_once 'Services/Contact/BuddySystem/classes/class.ilBuddySystem.php'; + if (!ilBuddySystem::getInstance()->isEnabled()) { + $ilErr->raiseError($this->lng->txt('msg_no_perm_read'), $ilErr->MESSAGE); + } + + $this->getStandardTemplates(); + $this->setTabs(); + $this->tpl->setTitle($this->lng->txt('mail_addressbook')); + + require_once 'Services/Contact/classes/class.ilContactGUI.php'; + $this->ctrl->forwardCommand(new ilContactGUI()); + break; + + case 'ilpersonalworkspacegui': + // $this->getStandardTemplates(); + // $this->setTabs(); + include_once 'Services/PersonalWorkspace/classes/class.ilPersonalWorkspaceGUI.php'; + $wsgui = new ilPersonalWorkspaceGUI(); + $ret = $this->ctrl->forwardCommand($wsgui); + $this->tpl->show(); + break; + + case 'ilportfoliorepositorygui': + $this->getStandardTemplates(); + $this->setTabs(); + include_once 'Modules/Portfolio/classes/class.ilPortfolioRepositoryGUI.php'; + $pfgui = new ilPortfolioRepositoryGUI(); + $ret = $this->ctrl->forwardCommand($pfgui); + $this->tpl->show(); + break; + + case 'ilachievementsgui': + $this->getStandardTemplates(); + $this->setTabs(); + $achievegui = new ilAchievementsGUI(); + $ret = $this->ctrl->forwardCommand($achievegui); + break; + + case strtolower(ilMyStaffGUI::class): + $this->getStandardTemplates(); + $mstgui = new ilMyStaffGUI(); + $ret = $this->ctrl->forwardCommand($mstgui); + break; + case 'ilgroupuseractionsgui': + $this->getStandardTemplates(); + $this->setTabs(); + include_once './Modules/Group/UserActions/classes/class.ilGroupUserActionsGUI.php'; + $ggui = new ilGroupUserActionsGUI(); + $ret = $this->ctrl->forwardCommand($ggui); + $this->tpl->show(); + break; + case 'redirect': + $this->redirect(); + break; + + default: + $this->getStandardTemplates(); + $this->setTabs(); + $cmd = $this->ctrl->getCmd("show"); + $this->$cmd(); + break; + } + $ret = null; + return $ret; + } + + /** + * get standard templates + */ + public function getStandardTemplates() + { + $this->tpl->getStandardTemplate(); + } + + /** + * show desktop + */ + public function show() + { + // preload block settings + include_once("Services/Block/classes/class.ilBlockSetting.php"); + ilBlockSetting::preloadPDBlockSettings(); + + // add template for content + $this->pd_tpl = new ilTemplate("tpl.usr_personaldesktop.html", true, true, "Services/PersonalDesktop"); + // $this->tpl->getStandardTemplate(); + + // display infopanel if something happened + ilUtil::infoPanel(); + + $this->tpl->setTitle($this->lng->txt("overview")); + $this->tpl->setVariable("IMG_SPACE", ilUtil::getImagePath("spacer.png", false)); + + $this->tpl->setContent($this->getCenterColumnHTML()); + $this->tpl->setRightContent($this->getRightColumnHTML()); + $this->tpl->setLeftContent($this->getLeftColumnHTML()); + + if (count($this->action_menu->getItems())) { + /** + * @var $tpl ilTemplate + * @var $lng ilLanguage + */ + $tpl = $this->tpl; + $lng = $this->lng; + + $this->action_menu->setAsynch(false); + $this->action_menu->setAsynchUrl(''); + $this->action_menu->setListTitle($lng->txt('actions')); + $this->action_menu->setId('act_pd'); + $this->action_menu->setSelectionHeaderClass('small'); + $this->action_menu->setItemLinkClass('xsmall'); + $this->action_menu->setLinksMode('il_ContainerItemCommand2'); + $this->action_menu->setHeaderIcon(ilAdvancedSelectionListGUI::DOWN_ARROW_DARK); + $this->action_menu->setUseImages(false); + + $htpl = new ilTemplate('tpl.header_action.html', true, true, 'Services/Repository'); + $htpl->setVariable('ACTION_DROP_DOWN', $this->action_menu->getHTML()); + + $tpl->setHeaderActionMenu($htpl->get()); + } + + $this->tpl->show(); + } + + + /** + * Display center column + */ + public function getCenterColumnHTML() + { + $ilCtrl = $this->ctrl; + $ilPluginAdmin = $this->plugin_admin; + + include_once("Services/Block/classes/class.ilColumnGUI.php"); + $column_gui = new ilColumnGUI("pd", IL_COL_CENTER); + $this->initColumn($column_gui); + + if ($ilCtrl->getNextClass() == "ilcolumngui" && + $column_gui->getCmdSide() == IL_COL_CENTER) { + $html = $ilCtrl->forwardCommand($column_gui); + } else { + if (!$ilCtrl->isAsynch()) { + if ($column_gui->getScreenMode() != IL_SCREEN_SIDE) { + // right column wants center + if ($column_gui->getCmdSide() == IL_COL_RIGHT) { + $column_gui = new ilColumnGUI("pd", IL_COL_RIGHT); + $this->initColumn($column_gui); + $html = $ilCtrl->forwardCommand($column_gui); + } + // left column wants center + if ($column_gui->getCmdSide() == IL_COL_LEFT) { + $column_gui = new ilColumnGUI("pd", IL_COL_LEFT); + $this->initColumn($column_gui); + $html = $ilCtrl->forwardCommand($column_gui); + } + } else { + $html = ""; + + // user interface plugin slot + default rendering + include_once("./Services/UIComponent/classes/class.ilUIHookProcessor.php"); + $uip = new ilUIHookProcessor( + "Services/PersonalDesktop", + "center_column", + array("personal_desktop_gui" => $this) + ); + if (!$uip->replaced()) { + $html = $ilCtrl->getHTML($column_gui); + } + $html = $uip->getHTML($html); + } + } + } + return $html; + } + + /** + * Display right column + */ + public function getRightColumnHTML() + { + $ilUser = $this->user; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilPluginAdmin = $this->plugin_admin; + + include_once("Services/Block/classes/class.ilColumnGUI.php"); + $column_gui = new ilColumnGUI("pd", IL_COL_RIGHT); + $this->initColumn($column_gui); + + if ($column_gui->getScreenMode() == IL_SCREEN_FULL) { + return ""; + } + + if ($ilCtrl->getNextClass() == "ilcolumngui" && + $column_gui->getCmdSide() == IL_COL_RIGHT && + $column_gui->getScreenMode() == IL_SCREEN_SIDE) { + $html = $ilCtrl->forwardCommand($column_gui); + } else { + if (!$ilCtrl->isAsynch()) { + $html = ""; + + // user interface plugin slot + default rendering + include_once("./Services/UIComponent/classes/class.ilUIHookProcessor.php"); + $uip = new ilUIHookProcessor( + "Services/PersonalDesktop", + "right_column", + array("personal_desktop_gui" => $this) + ); + if (!$uip->replaced()) { + $html = $ilCtrl->getHTML($column_gui); + } + $html = $uip->getHTML($html); + } + } + + return $html; + } + + /** + * Display left column + */ + public function getLeftColumnHTML() + { + $ilUser = $this->user; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilPluginAdmin = $this->plugin_admin; + + include_once("Services/Block/classes/class.ilColumnGUI.php"); + $column_gui = new ilColumnGUI("pd", IL_COL_LEFT); + $this->initColumn($column_gui); + + if ($column_gui->getScreenMode() == IL_SCREEN_FULL) { + return ""; + } + + if ($ilCtrl->getNextClass() == "ilcolumngui" && + $column_gui->getCmdSide() == IL_COL_LEFT && + $column_gui->getScreenMode() == IL_SCREEN_SIDE) { + $html = $ilCtrl->forwardCommand($column_gui); + } else { + if (!$ilCtrl->isAsynch()) { + $html = ""; + + // user interface plugin slot + default rendering + include_once("./Services/UIComponent/classes/class.ilUIHookProcessor.php"); + $uip = new ilUIHookProcessor( + "Services/PersonalDesktop", + "left_column", + array("personal_desktop_gui" => $this) + ); + if (!$uip->replaced()) { + $html = $ilCtrl->getHTML($column_gui); + } + $html = $uip->getHTML($html); + } + } + + return $html; + } + + public function prepareContentView() + { + // add template for content + $this->pd_tpl = new ilTemplate("tpl.usr_personaldesktop.html", true, true, "Services/PersonalDesktop"); + $this->tpl->getStandardTemplate(); + + // display infopanel if something happened + ilUtil::infoPanel(); + + $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_pd.svg")); + $this->tpl->setTitle($this->lng->txt("personal_desktop")); + $this->tpl->setVariable("IMG_SPACE", ilUtil::getImagePath("spacer.png", false)); + } + + /** + * Display system messages. + */ + public function displaySystemMessages() + { + include_once("Services/Mail/classes/class.ilPDSysMessageBlockGUI.php"); + $sys_block = new ilPDSysMessageBlockGUI("ilpersonaldesktopgui", "show"); + return $sys_block->getHTML(); + } + + /** + * Returns the multidimenstional sorted array + * + * Returns the multidimenstional sorted array + * + * @author Muzaffar Altaf + * @param array $arrays The array to be sorted + * @param string $key_sort The keys on which array must be sorted + * @access public + */ + public function multiarray_sort($array, $key_sort) + { + if ($array) { + $key_sorta = explode(";", $key_sort); + + $multikeys = array_keys($array); + $keys = array_keys($array[$multikeys[0]]); + + for ($m=0; $m < count($key_sorta); $m++) { + $nkeys[$m] = trim($key_sorta[$m]); + } + $n += count($key_sorta); + + for ($i=0; $i < count($keys); $i++) { + if (!in_array($keys[$i], $key_sorta)) { + $nkeys[$n] = $keys[$i]; + $n += "1"; + } + } + + for ($u=0;$uhelp; + + $ilHelp->setScreenIdComponent("pd"); + } + + /** + * Jump to memberships + */ + public function jumpToMemberships() + { + require_once 'Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockViewSettings.php'; + $viewSettings = new ilPDSelectedItemsBlockViewSettings($GLOBALS['DIC']->user(), (int) $_GET['view']); + if ($viewSettings->enabledMemberships()) { + $_GET['view'] = $viewSettings->getMembershipsView(); + $this->ctrl->setParameter($this, "view", $viewSettings->getMembershipsView()); + } + $this->show(); + } + + /** + * Jump to selected items + */ + public function jumpToSelectedItems() + { + require_once 'Services/PersonalDesktop/ItemsBlock/classes/class.ilPDSelectedItemsBlockViewSettings.php'; + $viewSettings = new ilPDSelectedItemsBlockViewSettings($GLOBALS['DIC']->user(), (int) $_GET['view']); + if ($viewSettings->enabledSelectedItems()) { + $_GET['view'] = $viewSettings->getSelectedItemsView(); + $this->ctrl->setParameter($this, "view", $viewSettings->getSelectedItemsView()); + } + $this->show(); + } + + /** + * workaround for menu in calendar only + */ + public function jumpToProfile() + { + $this->ctrl->redirectByClass("ilpersonalprofilegui"); + } + + public function jumpToPortfolio() + { + // incoming back link from shared resource + $cmd = ""; + if ($_REQUEST["dsh"]) { + $this->ctrl->setParameterByClass("ilportfoliorepositorygui", "shr_id", $_REQUEST["dsh"]); + $cmd = "showOther"; + } + + // used for goto links + if ($_GET["prt_id"]) { + $this->ctrl->setParameterByClass("ilobjportfoliogui", "prt_id", (int) $_GET["prt_id"]); + $this->ctrl->setParameterByClass("ilobjportfoliogui", "gtp", (int) $_GET["gtp"]); + $this->ctrl->redirectByClass(array("ilportfoliorepositorygui", "ilobjportfoliogui"), "preview"); + } else { + $this->ctrl->redirectByClass("ilportfoliorepositorygui", $cmd); + } + } + + /** + * workaround for menu in calendar only + */ + public function jumpToSettings() + { + $this->ctrl->redirectByClass("ilpersonalsettingsgui"); + } + + /** + * workaround for menu in calendar only + */ + public function jumpToBookmarks() + { + $ilSetting = $this->settings; + + if ($ilSetting->get("disable_bookmarks")) { + ilUtil::sendFailure($this->lng->txt('permission_denied'), true); + ilUtil::redirect('ilias.php?baseClass=ilPersonalDesktopGUI'); + return; + } + + $this->ctrl->redirectByClass("ilbookmarkadministrationgui"); + } + + /** + * workaround for menu in calendar only + */ + public function jumpToNotes() + { + $ilSetting = $this->settings; + + if ($ilSetting->get('disable_notes')) { + ilUtil::sendFailure($this->lng->txt('permission_denied'), true); + ilUtil::redirect('ilias.php?baseClass=ilPersonalDesktopGUI'); + return; + } + + $this->ctrl->redirectByClass("ilpdnotesgui"); + } + + /** + * workaround for menu in calendar only + */ + public function jumpToComments() + { + $ilSetting = $this->settings; + + if ($ilSetting->get('disable_comments')) { + ilUtil::sendFailure($this->lng->txt('permission_denied'), true); + ilUtil::redirect('ilias.php?baseClass=ilPersonalDesktopGUI'); + return; + } + + $this->ctrl->redirectByClass("ilpdnotesgui", "showPublicComments"); + } + + /** + * workaround for menu in calendar only + */ + public function jumpToNews() + { + $this->ctrl->redirectByClass("ilpdnewsgui"); + } + + /** + * workaround for menu in calendar only + */ + public function jumpToLP() + { + $this->ctrl->redirectByClass("illearningprogressgui"); + } + + /** + * Jump to calendar + */ + public function jumpToCalendar() + { + $this->ctrl->redirectByClass("ilcalendarpresentationgui"); + } + + /** + * Jump to contacts + */ + public function jumpToContacts() + { + $this->ctrl->redirectByClass(array('ilpersonaldesktopgui', 'ilcontactgui')); + } + + /** + * Jump to personal workspace + */ + public function jumpToWorkspace() + { + // incoming back link from shared resource + $cmd = ""; + if ($_REQUEST["dsh"]) { + $this->ctrl->setParameterByClass("ilpersonalworkspacegui", "shr_id", $_REQUEST["dsh"]); + $cmd = "share"; + } + + if ($_REQUEST["wsp_id"]) { + $this->ctrl->setParameterByClass("ilpersonalworkspacegui", "wsp_id", (int) $_REQUEST["wsp_id"]); + } + + if ($_REQUEST["gtp"]) { + $this->ctrl->setParameterByClass("ilpersonalworkspacegui", "gtp", (int) $_REQUEST["gtp"]); + } + + $this->ctrl->redirectByClass("ilpersonalworkspacegui", $cmd); + } + + /** + * + */ + protected function jumpToMyStaff() + { + $this->ctrl->redirectByClass(ilMyStaffGUI::class); + } + + /** + * Jump to badges + */ + public function jumpToBadges() + { + $this->ctrl->redirectByClass(["ilAchievementsGUI", "ilbadgeprofilegui"]); + } + + /** + * Jump to personal skills + */ + public function jumpToSkills() + { + $this->ctrl->redirectByClass("ilpersonalskillsgui"); + } + + public function __loadNextClass() + { + $stored_classes = array('ilpersonaldesktopgui', + 'ilpersonalprofilegui', + 'ilpdnotesgui', + 'ilcalendarpresentationgui', + 'ilbookmarkadministrationgui', + 'illearningprogressgui'); + + if (isset($_SESSION['il_pd_history']) and in_array($_SESSION['il_pd_history'], $stored_classes)) { + return $_SESSION['il_pd_history']; + } else { + $this->ctrl->getNextClass($this); + } + } + public function __storeLastClass($a_class) + { + $_SESSION['il_pd_history'] = $a_class; + $this->cmdClass = $a_class; + } + + /** + * Init ilColumnGUI + * @var ilColumnGUI $a_column_gui + */ + public function initColumn($a_column_gui) + { + $pd_set = new ilSetting("pd"); + if ($pd_set->get("enable_block_moving")) { + $a_column_gui->setEnableMovement(true); + } + $a_column_gui->setActionMenu($this->action_menu); + } + + /** + * display header and locator + */ + public function displayHeader() + { + $this->tpl->setTitle($this->lng->txt("personal_desktop")); + } } -?> diff --git a/Services/PersonalDesktop/classes/class.ilPersonalDesktopHookPlugin.php b/Services/PersonalDesktop/classes/class.ilPersonalDesktopHookPlugin.php index 9da23219871bbae75ec2d26940a454521b520ff5..8f33b1cf1bee20e326eb824c35bc4263082c80a4 100755 --- a/Services/PersonalDesktop/classes/class.ilPersonalDesktopHookPlugin.php +++ b/Services/PersonalDesktop/classes/class.ilPersonalDesktopHookPlugin.php @@ -12,52 +12,51 @@ include_once("./Services/Component/classes/class.ilPlugin.php"); */ abstract class ilPersonalDesktopHookPlugin extends ilPlugin { - /** - * Get Component Type - * - * @return string Component Type - */ - final function getComponentType() - { - return IL_COMP_SERVICE; - } + /** + * Get Component Type + * + * @return string Component Type + */ + final public function getComponentType() + { + return IL_COMP_SERVICE; + } - /** - * Get Component Name. - * - * @return string Component Name - */ - final function getComponentName() - { - return "PersonalDesktop"; - } + /** + * Get Component Name. + * + * @return string Component Name + */ + final public function getComponentName() + { + return "PersonalDesktop"; + } - /** - * Get Slot Name. - * - * @return string Slot Name - */ - final function getSlot() - { - return "PersonalDesktopHook"; - } + /** + * Get Slot Name. + * + * @return string Slot Name + */ + final public function getSlot() + { + return "PersonalDesktopHook"; + } - /** - * Get Slot ID. - * - * @return string Slot Id - */ - final function getSlotId() - { - return "pdhk"; - } + /** + * Get Slot ID. + * + * @return string Slot Id + */ + final public function getSlotId() + { + return "pdhk"; + } - /** - * Object initialization done by slot. - */ - protected final function slotInit() - { - // nothing to do here - } + /** + * Object initialization done by slot. + */ + final protected function slotInit() + { + // nothing to do here + } } -?> \ No newline at end of file diff --git a/Services/PersonalDesktop/classes/class.ilPersonalDesktopService.php b/Services/PersonalDesktop/classes/class.ilPersonalDesktopService.php index 55f8db9085e888aa270c8fa2f26e005dae241f6c..f61edaa7db37ea537901e3131ce98410710ffbde 100644 --- a/Services/PersonalDesktop/classes/class.ilPersonalDesktopService.php +++ b/Services/PersonalDesktop/classes/class.ilPersonalDesktopService.php @@ -1,35 +1,35 @@ * @version $Id$ */ class ilPersonalDesktopService extends ilService -{ +{ /** * @see ilComponent::getVersion() */ @@ -45,5 +45,4 @@ class ilPersonalDesktopService extends ilService { return true; } - } diff --git a/Services/PersonalDesktop/interfaces/interface.ilDesktopItemHandling.php b/Services/PersonalDesktop/interfaces/interface.ilDesktopItemHandling.php index f25675cd9c5bf67e52fee4260128668853d1ba80..d1566e360826ee6153a38d46624bf9ea4a1a8202 100644 --- a/Services/PersonalDesktop/interfaces/interface.ilDesktopItemHandling.php +++ b/Services/PersonalDesktop/interfaces/interface.ilDesktopItemHandling.php @@ -1,47 +1,46 @@ * @version $Id$ -* +* * * @ingroup ServicesPersonalDesktop */ interface ilDesktopItemHandling { - /** - * Add desktop item - * @access public - */ - public function addToDeskObject(); - - /** - * Remove from desktop - * @access public - */ - public function removeFromDeskObject(); + /** + * Add desktop item + * @access public + */ + public function addToDeskObject(); + + /** + * Remove from desktop + * @access public + */ + public function removeFromDeskObject(); } -?> diff --git a/Services/PersonalWorkspace/classes/class.ilCronPersonalWorkspaceRecalculateQuota.php b/Services/PersonalWorkspace/classes/class.ilCronPersonalWorkspaceRecalculateQuota.php index 9fd23d65a6ce35c0646182e1f5496c48a2f5a0f8..4e3c7263f1bcd24004140c63c776a4d6594e34db 100644 --- a/Services/PersonalWorkspace/classes/class.ilCronPersonalWorkspaceRecalculateQuota.php +++ b/Services/PersonalWorkspace/classes/class.ilCronPersonalWorkspaceRecalculateQuota.php @@ -5,7 +5,7 @@ include_once "Services/Cron/classes/class.ilCronJob.php"; /** * Recalculate quota for personal workspace - * + * * @author Alex Killing * @version $Id$ * @@ -13,451 +13,420 @@ include_once "Services/Cron/classes/class.ilCronJob.php"; */ class ilCronPersonalWorkspaceRecalculateQuota extends ilCronJob { - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilDB - */ - protected $db; - - /** - * @var int - */ - protected $job_status; - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - $ilDB = $DIC->database(); - - $this->db = $ilDB; - } - - - /** - * @inheritdoc - */ - public function getId() - { - return "pwsp_recalc_quota"; - } - - /** - * @inheritdoc - */ - public function getTitle() - { - $lng = $this->lng; - - return $lng->txt("pwsp_recalculate_disk_quota"); - } - - /** - * @inheritdoc - */ - public function getDescription() - { - $lng = $this->lng; - - return $lng->txt("pwsp_recalculate_disk_quota_desc"); - } - - /** - * @inheritdoc - */ - public function getDefaultScheduleType() - { - return self::SCHEDULE_TYPE_DAILY; - } - - /** - * @inheritdoc - */ - public function getDefaultScheduleValue() - { - return; - } - - /** - * @inheritdoc - */ - public function hasAutoActivation() - { - return false; - } - - /** - * @inheritdoc - */ - public function hasFlexibleSchedule() - { - return true; - } - - /** - * @inheritdoc - */ - public function hasCustomSettings() - { - return true; - } - - /** - * @inheritdoc - */ - public function run() - { - $this->job_status = ilCronJobResult::STATUS_NO_ACTION; - - $this->recalculate(); - - $this->job_status = ilCronJobResult::STATUS_OK; - - $result = new ilCronJobResult(); - $result->setStatus($this->job_status); - return $result; - } - - /** - * Recalculate - */ - function recalculate() - { - $ilDB = $this->db; - - // - // Files (workspace, blogs and portfolios) - // - - $ilDB->manipulate("DELETE FROM il_disk_quota" . - " WHERE src_type = " . $ilDB->quote("file", "text")); - - $quota_done = array(); - - // get all workspace files - $set = $ilDB->query("SELECT od.owner, od.obj_id" . - " FROM object_data od" . - " JOIN object_reference_ws ref ON (ref.obj_id = od.obj_id)" . - " JOIN tree_workspace t ON (t.child = ref.wsp_id)" . - " WHERE od.type = " . $ilDB->quote("file", "text") . - " AND t.tree = od.owner"); - while ($row = $ilDB->fetchAssoc($set)) - { - $id = $row["owner"] . "-" . $row["obj_id"]; - if (!in_array($id, $quota_done)) - { - $this->quotaHandleFile($row["obj_id"], $row["owner"]); - $quota_done[] = $id; - } - } - - // get all file usage for workspace blogs - $set = $ilDB->query("SELECT od.owner, fu.id" . - " FROM object_data od" . - " JOIN object_reference_ws ref ON (ref.obj_id = od.obj_id)" . - " JOIN tree_workspace t ON (t.child = ref.wsp_id)" . - " JOIN il_blog_posting blp ON (blp.blog_id = od.obj_id)" . - " JOIN file_usage fu ON (fu.usage_id = blp.id)" . - " WHERE fu.usage_type = " . $ilDB->quote("blp:pg", "text") . - " AND fu.usage_hist_nr = " . $ilDB->quote(0, "integer")); - while ($row = $ilDB->fetchAssoc($set)) - { - $id = $row["owner"] . "-" . $row["id"]; - if (!in_array($id, $quota_done)) - { - $this->quotaHandleFile($row["id"], $row["owner"]); - $quota_done[] = $id; - } - } - - // get all file usage for portfolios - $set = $ilDB->query($q = "SELECT od.owner, fu.id" . - " FROM object_data od" . - " JOIN usr_portfolio_page prtf ON (prtf.portfolio_id = od.obj_id)" . - " JOIN file_usage fu ON (fu.usage_id = prtf.id)" . - " WHERE fu.usage_type = " . $ilDB->quote("prtf:pg", "text") . - " AND fu.usage_hist_nr = " . $ilDB->quote(0, "integer")); - - while ($row = $ilDB->fetchAssoc($set)) - { - $id = $row["owner"] . "-" . $row["id"]; - if (!in_array($id, $quota_done)) - { - $this->quotaHandleFile($row["id"], $row["owner"]); - $quota_done[] = $id; - } - } - - - // - // Media objects (blogs and portfolios) - // - - $ilDB->manipulate("DELETE FROM il_disk_quota" . - " WHERE src_type = " . $ilDB->quote("mob", "text")); - - $quota_done = array(); - - // get all mob usage for workspace blogs - $set = $ilDB->query("SELECT od.owner, mu.id" . - " FROM object_data od" . - " JOIN object_reference_ws ref ON (ref.obj_id = od.obj_id)" . - " JOIN tree_workspace t ON (t.child = ref.wsp_id)" . - " JOIN il_blog_posting blp ON (blp.blog_id = od.obj_id)" . - " JOIN mob_usage mu ON (mu.usage_id = blp.id)" . - " WHERE mu.usage_type = " . $ilDB->quote("blp:pg", "text") . - " AND mu.usage_hist_nr = " . $ilDB->quote(0, "integer")); - while ($row = $ilDB->fetchAssoc($set)) - { - $id = $row["owner"] . "-" . $row["id"]; - if (!in_array($id, $quota_done)) - { - $this->quotaHandleMob($row["id"], $row["owner"]); - $quota_done[] = $id; - } - } - - // get all mob usage for portfolios - $set = $ilDB->query("SELECT od.owner, mu.id" . - " FROM object_data od" . - " JOIN usr_portfolio_page prtf ON (prtf.portfolio_id = od.obj_id)" . - " JOIN mob_usage mu ON (mu.usage_id = prtf.id)" . - " WHERE mu.usage_type = " . $ilDB->quote("prtf:pg", "text") . - " AND mu.usage_hist_nr = " . $ilDB->quote(0, "integer")); - while ($row = $ilDB->fetchAssoc($set)) - { - $id = $row["owner"] . "-" . $row["id"]; - if (!in_array($id, $quota_done)) - { - $this->quotaHandleMob($row["id"], $row["owner"]); - $quota_done[] = $id; - } - } - - // - // Portfolio / Blog images - // - - $ilDB->manipulate("DELETE FROM il_disk_quota" . - " WHERE src_type = " . $ilDB->quote("prtf", "text")); - $ilDB->manipulate("DELETE FROM il_disk_quota" . - " WHERE src_type = " . $ilDB->quote("blog", "text")); - - // portfolios - $set = $ilDB->query("SELECT od.owner, od.obj_id" . - " FROM object_data od" . - " JOIN usr_portfolio prtf ON (prtf.id = od.obj_id)" . - " WHERE od.type = " . $ilDB->quote("prtf", "text") . - " AND prtf.img IS NOT NULL"); - while ($row = $ilDB->fetchAssoc($set)) - { - $this->quotaHandleFileStorage("prtf", $row["obj_id"], $row["owner"], "sec/ilPortfolio"); - } - - // (workspace) blogs - $set = $ilDB->query("SELECT od.owner, od.obj_id" . - " FROM object_data od" . - " JOIN object_reference_ws ref ON (ref.obj_id = od.obj_id)" . - " JOIN tree_workspace t ON (t.child = ref.wsp_id)" . - " JOIN il_blog blog ON (blog.id = od.obj_id)" . - " WHERE od.type = " . $ilDB->quote("blog", "text") . - " AND blog.img IS NOT NULL" . - " AND t.tree = od.owner"); - while ($row = $ilDB->fetchAssoc($set)) - { - $this->quotaHandleFileStorage("blog", $row["obj_id"], $row["owner"], "sec/ilBlog"); - } - - return; - - // - // Verifications - // - - $ilDB->manipulate("DELETE FROM il_disk_quota" . - " WHERE src_type = " . $ilDB->quote("tstv", "text")); - $ilDB->manipulate("DELETE FROM il_disk_quota" . - " WHERE src_type = " . $ilDB->quote("excv", "text")); - - // (workspace) verifications - $set = $ilDB->query("SELECT od.owner, od.obj_id, od.type" . - " FROM object_data od" . - " JOIN object_reference_ws ref ON (ref.obj_id = od.obj_id)" . - " JOIN tree_workspace t ON (t.child = ref.wsp_id)" . - " WHERE " . $ilDB->in("od.type", array("tstv", "excv"), "", "text") . - " AND t.tree = od.owner"); - while ($row = $ilDB->fetchAssoc($set)) - { - $this->quotaHandleVerification($row["type"], $row["obj_id"], $row["owner"]); - } - } - - /** - * @param int $a_obj_id - * @param int $a_owner_id - */ - function quotaHandleFile($a_obj_id, $a_owner_id) - { - $ilDB = $this->db; - - // see ilFileSystemStorage::_createPathFromId() - $tpath = array(); - $tfound = false; - $tnum = $a_obj_id; - for ($i = 3; $i > 0; $i--) - { - $factor = pow(100, $i); - if (($tmp = (int)($tnum / $factor)) or $tfound) - { - $tpath[] = $tmp; - $tnum = $tnum % $factor; - $tfound = true; - } - } - - $file_path = ilUtil::getDataDir() . "/ilFile/"; - if (count($tpath)) - { - $file_path .= (implode('/', $tpath) . '/'); - } - $file_path .= "file_" . $a_obj_id; - if (file_exists($file_path)) - { - $file_size = (int)ilUtil::dirsize($file_path); - if ($file_size > 0) - { - $ilDB->manipulate("INSERT INTO il_disk_quota" . - " (owner_id, src_type, src_obj_id, src_size)" . - " VALUES (" . $ilDB->quote($a_owner_id, "integer") . - ", " . $ilDB->quote("file", "text") . - ", " . $ilDB->quote($a_obj_id, "integer") . - ", " . $ilDB->quote($file_size, "integer") . ")"); - } - } - } - - /** - * @param int $a_obj_id - * @param int $a_owner_id - */ - function quotaHandleMob($a_obj_id, $a_owner_id) - { - $ilDB = $this->db; - - $file_path = CLIENT_WEB_DIR . "/mobs/mm_" . $a_obj_id; - if (file_exists($file_path)) - { - $file_size = (int)ilUtil::dirsize($file_path); - if ($file_size > 0) - { - $ilDB->manipulate("INSERT INTO il_disk_quota" . - " (owner_id, src_type, src_obj_id, src_size)" . - " VALUES (" . $ilDB->quote($a_owner_id, "integer") . - ", " . $ilDB->quote("mob", "text") . - ", " . $ilDB->quote($a_obj_id, "integer") . - ", " . $ilDB->quote($file_size, "integer") . ")"); - } - } - } - - /** - * @param string $a_type - * @param int $a_obj_id - * @param int $a_owner_id - * @param string $a_dir - */ - function quotaHandleFileStorage($a_type, $a_obj_id, $a_owner_id, $a_dir) - { - $ilDB = $this->db; - - // see ilFileSystemStorage::_createPathFromId() - $tpath = array(); - $tfound = false; - $tnum = $a_obj_id; - for ($i = 3; $i > 0; $i--) - { - $factor = pow(100, $i); - if (($tmp = (int)($tnum / $factor)) or $tfound) - { - $tpath[] = $tmp; - $tnum = $tnum % $factor; - $tfound = true; - } - } - - $file_path = CLIENT_WEB_DIR . "/" . $a_dir . "/"; - if (count($tpath)) - { - $file_path .= (implode('/', $tpath) . '/'); - } - $file_path .= $a_type . "_" . $a_obj_id; - - if (file_exists($file_path)) - { - $file_size = (int)ilUtil::dirsize($file_path); - if ($file_size > 0) - { - $ilDB->manipulate("INSERT INTO il_disk_quota" . - " (owner_id, src_type, src_obj_id, src_size)" . - " VALUES (" . $ilDB->quote($a_owner_id, "integer") . - ", " . $ilDB->quote($a_type, "text") . - ", " . $ilDB->quote($a_obj_id, "integer") . - ", " . $ilDB->quote($file_size, "integer") . ")"); - } - } - } - - /** - * @param strin $a_type - * @param int $a_obj_id - * @param int $a_owner_id - */ - function quotaHandleVerification($a_type, $a_obj_id, $a_owner_id) - { - $ilDB = $this->db; - - // see ilFileSystemStorage::_createPathFromId() - $tpath = array(); - $tfound = false; - $tnum = $a_obj_id; - for ($i = 3; $i > 0;$i--) - { - $factor = pow(100, $i); - if(($tmp = (int) ($tnum / $factor)) or $tfound) - { - $tpath[] = $tmp; - $tnum = $tnum % $factor; - $tfound = true; - } - } - - $file_path = ilUtil::getDataDir()."/ilVerification/"; - if(count($tpath)) - { - $file_path .= (implode('/',$tpath).'/'); - } - $file_path .= "vrfc_".$a_obj_id; - if(file_exists($file_path)) - { - $file_size = (int)ilUtil::dirsize($file_path); - if($file_size > 0) - { - $ilDB->manipulate("INSERT INTO il_disk_quota". - " (owner_id, src_type, src_obj_id, src_size)". - " VALUES (".$ilDB->quote($a_owner_id, "integer"). - ", ".$ilDB->quote($a_type, "text"). - ", ".$ilDB->quote($a_obj_id, "integer"). - ", ".$ilDB->quote($file_size, "integer").")"); - } - } - } - + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilDB + */ + protected $db; + + /** + * @var int + */ + protected $job_status; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + $ilDB = $DIC->database(); + + $this->db = $ilDB; + } + + + /** + * @inheritdoc + */ + public function getId() + { + return "pwsp_recalc_quota"; + } + + /** + * @inheritdoc + */ + public function getTitle() + { + $lng = $this->lng; + + return $lng->txt("pwsp_recalculate_disk_quota"); + } + + /** + * @inheritdoc + */ + public function getDescription() + { + $lng = $this->lng; + + return $lng->txt("pwsp_recalculate_disk_quota_desc"); + } + + /** + * @inheritdoc + */ + public function getDefaultScheduleType() + { + return self::SCHEDULE_TYPE_DAILY; + } + + /** + * @inheritdoc + */ + public function getDefaultScheduleValue() + { + return; + } + + /** + * @inheritdoc + */ + public function hasAutoActivation() + { + return false; + } + + /** + * @inheritdoc + */ + public function hasFlexibleSchedule() + { + return true; + } + + /** + * @inheritdoc + */ + public function hasCustomSettings() + { + return true; + } + + /** + * @inheritdoc + */ + public function run() + { + $this->job_status = ilCronJobResult::STATUS_NO_ACTION; + + $this->recalculate(); + + $this->job_status = ilCronJobResult::STATUS_OK; + + $result = new ilCronJobResult(); + $result->setStatus($this->job_status); + return $result; + } + + /** + * Recalculate + */ + public function recalculate() + { + $ilDB = $this->db; + + // + // Files (workspace, blogs and portfolios) + // + + $ilDB->manipulate("DELETE FROM il_disk_quota" . + " WHERE src_type = " . $ilDB->quote("file", "text")); + + $quota_done = array(); + + // get all workspace files + $set = $ilDB->query("SELECT od.owner, od.obj_id" . + " FROM object_data od" . + " JOIN object_reference_ws ref ON (ref.obj_id = od.obj_id)" . + " JOIN tree_workspace t ON (t.child = ref.wsp_id)" . + " WHERE od.type = " . $ilDB->quote("file", "text") . + " AND t.tree = od.owner"); + while ($row = $ilDB->fetchAssoc($set)) { + $id = $row["owner"] . "-" . $row["obj_id"]; + if (!in_array($id, $quota_done)) { + $this->quotaHandleFile($row["obj_id"], $row["owner"]); + $quota_done[] = $id; + } + } + + // get all file usage for workspace blogs + $set = $ilDB->query("SELECT od.owner, fu.id" . + " FROM object_data od" . + " JOIN object_reference_ws ref ON (ref.obj_id = od.obj_id)" . + " JOIN tree_workspace t ON (t.child = ref.wsp_id)" . + " JOIN il_blog_posting blp ON (blp.blog_id = od.obj_id)" . + " JOIN file_usage fu ON (fu.usage_id = blp.id)" . + " WHERE fu.usage_type = " . $ilDB->quote("blp:pg", "text") . + " AND fu.usage_hist_nr = " . $ilDB->quote(0, "integer")); + while ($row = $ilDB->fetchAssoc($set)) { + $id = $row["owner"] . "-" . $row["id"]; + if (!in_array($id, $quota_done)) { + $this->quotaHandleFile($row["id"], $row["owner"]); + $quota_done[] = $id; + } + } + + // get all file usage for portfolios + $set = $ilDB->query($q = "SELECT od.owner, fu.id" . + " FROM object_data od" . + " JOIN usr_portfolio_page prtf ON (prtf.portfolio_id = od.obj_id)" . + " JOIN file_usage fu ON (fu.usage_id = prtf.id)" . + " WHERE fu.usage_type = " . $ilDB->quote("prtf:pg", "text") . + " AND fu.usage_hist_nr = " . $ilDB->quote(0, "integer")); + + while ($row = $ilDB->fetchAssoc($set)) { + $id = $row["owner"] . "-" . $row["id"]; + if (!in_array($id, $quota_done)) { + $this->quotaHandleFile($row["id"], $row["owner"]); + $quota_done[] = $id; + } + } + + + // + // Media objects (blogs and portfolios) + // + + $ilDB->manipulate("DELETE FROM il_disk_quota" . + " WHERE src_type = " . $ilDB->quote("mob", "text")); + + $quota_done = array(); + + // get all mob usage for workspace blogs + $set = $ilDB->query("SELECT od.owner, mu.id" . + " FROM object_data od" . + " JOIN object_reference_ws ref ON (ref.obj_id = od.obj_id)" . + " JOIN tree_workspace t ON (t.child = ref.wsp_id)" . + " JOIN il_blog_posting blp ON (blp.blog_id = od.obj_id)" . + " JOIN mob_usage mu ON (mu.usage_id = blp.id)" . + " WHERE mu.usage_type = " . $ilDB->quote("blp:pg", "text") . + " AND mu.usage_hist_nr = " . $ilDB->quote(0, "integer")); + while ($row = $ilDB->fetchAssoc($set)) { + $id = $row["owner"] . "-" . $row["id"]; + if (!in_array($id, $quota_done)) { + $this->quotaHandleMob($row["id"], $row["owner"]); + $quota_done[] = $id; + } + } + + // get all mob usage for portfolios + $set = $ilDB->query("SELECT od.owner, mu.id" . + " FROM object_data od" . + " JOIN usr_portfolio_page prtf ON (prtf.portfolio_id = od.obj_id)" . + " JOIN mob_usage mu ON (mu.usage_id = prtf.id)" . + " WHERE mu.usage_type = " . $ilDB->quote("prtf:pg", "text") . + " AND mu.usage_hist_nr = " . $ilDB->quote(0, "integer")); + while ($row = $ilDB->fetchAssoc($set)) { + $id = $row["owner"] . "-" . $row["id"]; + if (!in_array($id, $quota_done)) { + $this->quotaHandleMob($row["id"], $row["owner"]); + $quota_done[] = $id; + } + } + + // + // Portfolio / Blog images + // + + $ilDB->manipulate("DELETE FROM il_disk_quota" . + " WHERE src_type = " . $ilDB->quote("prtf", "text")); + $ilDB->manipulate("DELETE FROM il_disk_quota" . + " WHERE src_type = " . $ilDB->quote("blog", "text")); + + // portfolios + $set = $ilDB->query("SELECT od.owner, od.obj_id" . + " FROM object_data od" . + " JOIN usr_portfolio prtf ON (prtf.id = od.obj_id)" . + " WHERE od.type = " . $ilDB->quote("prtf", "text") . + " AND prtf.img IS NOT NULL"); + while ($row = $ilDB->fetchAssoc($set)) { + $this->quotaHandleFileStorage("prtf", $row["obj_id"], $row["owner"], "sec/ilPortfolio"); + } + + // (workspace) blogs + $set = $ilDB->query("SELECT od.owner, od.obj_id" . + " FROM object_data od" . + " JOIN object_reference_ws ref ON (ref.obj_id = od.obj_id)" . + " JOIN tree_workspace t ON (t.child = ref.wsp_id)" . + " JOIN il_blog blog ON (blog.id = od.obj_id)" . + " WHERE od.type = " . $ilDB->quote("blog", "text") . + " AND blog.img IS NOT NULL" . + " AND t.tree = od.owner"); + while ($row = $ilDB->fetchAssoc($set)) { + $this->quotaHandleFileStorage("blog", $row["obj_id"], $row["owner"], "sec/ilBlog"); + } + + return; + + // + // Verifications + // + + $ilDB->manipulate("DELETE FROM il_disk_quota" . + " WHERE src_type = " . $ilDB->quote("tstv", "text")); + $ilDB->manipulate("DELETE FROM il_disk_quota" . + " WHERE src_type = " . $ilDB->quote("excv", "text")); + + // (workspace) verifications + $set = $ilDB->query("SELECT od.owner, od.obj_id, od.type" . + " FROM object_data od" . + " JOIN object_reference_ws ref ON (ref.obj_id = od.obj_id)" . + " JOIN tree_workspace t ON (t.child = ref.wsp_id)" . + " WHERE " . $ilDB->in("od.type", array("tstv", "excv"), "", "text") . + " AND t.tree = od.owner"); + while ($row = $ilDB->fetchAssoc($set)) { + $this->quotaHandleVerification($row["type"], $row["obj_id"], $row["owner"]); + } + } + + /** + * @param int $a_obj_id + * @param int $a_owner_id + */ + public function quotaHandleFile($a_obj_id, $a_owner_id) + { + $ilDB = $this->db; + + // see ilFileSystemStorage::_createPathFromId() + $tpath = array(); + $tfound = false; + $tnum = $a_obj_id; + for ($i = 3; $i > 0; $i--) { + $factor = pow(100, $i); + if (($tmp = (int) ($tnum / $factor)) or $tfound) { + $tpath[] = $tmp; + $tnum = $tnum % $factor; + $tfound = true; + } + } + + $file_path = ilUtil::getDataDir() . "/ilFile/"; + if (count($tpath)) { + $file_path .= (implode('/', $tpath) . '/'); + } + $file_path .= "file_" . $a_obj_id; + if (file_exists($file_path)) { + $file_size = (int) ilUtil::dirsize($file_path); + if ($file_size > 0) { + $ilDB->manipulate("INSERT INTO il_disk_quota" . + " (owner_id, src_type, src_obj_id, src_size)" . + " VALUES (" . $ilDB->quote($a_owner_id, "integer") . + ", " . $ilDB->quote("file", "text") . + ", " . $ilDB->quote($a_obj_id, "integer") . + ", " . $ilDB->quote($file_size, "integer") . ")"); + } + } + } + + /** + * @param int $a_obj_id + * @param int $a_owner_id + */ + public function quotaHandleMob($a_obj_id, $a_owner_id) + { + $ilDB = $this->db; + + $file_path = CLIENT_WEB_DIR . "/mobs/mm_" . $a_obj_id; + if (file_exists($file_path)) { + $file_size = (int) ilUtil::dirsize($file_path); + if ($file_size > 0) { + $ilDB->manipulate("INSERT INTO il_disk_quota" . + " (owner_id, src_type, src_obj_id, src_size)" . + " VALUES (" . $ilDB->quote($a_owner_id, "integer") . + ", " . $ilDB->quote("mob", "text") . + ", " . $ilDB->quote($a_obj_id, "integer") . + ", " . $ilDB->quote($file_size, "integer") . ")"); + } + } + } + + /** + * @param string $a_type + * @param int $a_obj_id + * @param int $a_owner_id + * @param string $a_dir + */ + public function quotaHandleFileStorage($a_type, $a_obj_id, $a_owner_id, $a_dir) + { + $ilDB = $this->db; + + // see ilFileSystemStorage::_createPathFromId() + $tpath = array(); + $tfound = false; + $tnum = $a_obj_id; + for ($i = 3; $i > 0; $i--) { + $factor = pow(100, $i); + if (($tmp = (int) ($tnum / $factor)) or $tfound) { + $tpath[] = $tmp; + $tnum = $tnum % $factor; + $tfound = true; + } + } + + $file_path = CLIENT_WEB_DIR . "/" . $a_dir . "/"; + if (count($tpath)) { + $file_path .= (implode('/', $tpath) . '/'); + } + $file_path .= $a_type . "_" . $a_obj_id; + + if (file_exists($file_path)) { + $file_size = (int) ilUtil::dirsize($file_path); + if ($file_size > 0) { + $ilDB->manipulate("INSERT INTO il_disk_quota" . + " (owner_id, src_type, src_obj_id, src_size)" . + " VALUES (" . $ilDB->quote($a_owner_id, "integer") . + ", " . $ilDB->quote($a_type, "text") . + ", " . $ilDB->quote($a_obj_id, "integer") . + ", " . $ilDB->quote($file_size, "integer") . ")"); + } + } + } + + /** + * @param strin $a_type + * @param int $a_obj_id + * @param int $a_owner_id + */ + public function quotaHandleVerification($a_type, $a_obj_id, $a_owner_id) + { + $ilDB = $this->db; + + // see ilFileSystemStorage::_createPathFromId() + $tpath = array(); + $tfound = false; + $tnum = $a_obj_id; + for ($i = 3; $i > 0;$i--) { + $factor = pow(100, $i); + if (($tmp = (int) ($tnum / $factor)) or $tfound) { + $tpath[] = $tmp; + $tnum = $tnum % $factor; + $tfound = true; + } + } + + $file_path = ilUtil::getDataDir() . "/ilVerification/"; + if (count($tpath)) { + $file_path .= (implode('/', $tpath) . '/'); + } + $file_path .= "vrfc_" . $a_obj_id; + if (file_exists($file_path)) { + $file_size = (int) ilUtil::dirsize($file_path); + if ($file_size > 0) { + $ilDB->manipulate("INSERT INTO il_disk_quota" . + " (owner_id, src_type, src_obj_id, src_size)" . + " VALUES (" . $ilDB->quote($a_owner_id, "integer") . + ", " . $ilDB->quote($a_type, "text") . + ", " . $ilDB->quote($a_obj_id, "integer") . + ", " . $ilDB->quote($file_size, "integer") . ")"); + } + } + } } diff --git a/Services/PersonalWorkspace/classes/class.ilPersonalWorkspaceGUI.php b/Services/PersonalWorkspace/classes/class.ilPersonalWorkspaceGUI.php index 53dd249d580430da48ce5c912453af399f8b7408..9c7d2bf6296ec1781455f69f8cb0e177e02c920d 100644 --- a/Services/PersonalWorkspace/classes/class.ilPersonalWorkspaceGUI.php +++ b/Services/PersonalWorkspace/classes/class.ilPersonalWorkspaceGUI.php @@ -18,257 +18,239 @@ */ class ilPersonalWorkspaceGUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilHelpGUI - */ - protected $help; + /** + * @var ilHelpGUI + */ + protected $help; - /** - * @var ilObjectDefinition - */ - protected $obj_definition; + /** + * @var ilObjectDefinition + */ + protected $obj_definition; - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilTemplate + */ + protected $tpl; - /** - * @var ilMainMenuGUI - */ - protected $main_menu; + /** + * @var ilMainMenuGUI + */ + protected $main_menu; - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - /** - * @var ilTabsGUI - */ - protected $tabs; + /** + * @var ilTabsGUI + */ + protected $tabs; - /** - * @var ilLocatorGUI - */ - protected $locator; + /** + * @var ilLocatorGUI + */ + protected $locator; - protected $tree; // [ilTree] - protected $node_id; // [int] - - /** - * constructor - */ - public function __construct() - { - global $DIC; + protected $tree; // [ilTree] + protected $node_id; // [int] + + /** + * constructor + */ + public function __construct() + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->help = $DIC["ilHelp"]; - $this->obj_definition = $DIC["objDefinition"]; - $this->tpl = $DIC["tpl"]; - $this->main_menu = $DIC["ilMainMenu"]; - $this->user = $DIC->user(); - $this->tabs = $DIC->tabs(); - $this->locator = $DIC["ilLocator"]; - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilHelp = $DIC["ilHelp"]; + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->help = $DIC["ilHelp"]; + $this->obj_definition = $DIC["objDefinition"]; + $this->tpl = $DIC["tpl"]; + $this->main_menu = $DIC["ilMainMenu"]; + $this->user = $DIC->user(); + $this->tabs = $DIC->tabs(); + $this->locator = $DIC["ilLocator"]; + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilHelp = $DIC["ilHelp"]; - $lng->loadLanguageModule("wsp"); + $lng->loadLanguageModule("wsp"); - $this->initTree(); + $this->initTree(); - $ilCtrl->saveParameter($this, "wsp_id"); + $ilCtrl->saveParameter($this, "wsp_id"); - $this->node_id = (int) $_REQUEST["wsp_id"]; - if(!$this->node_id) - { - $this->node_id = $this->tree->getRootId(); - } - } - - /** - * execute command - */ - public function executeCommand() - { - $ilCtrl = $this->ctrl; - $objDefinition = $this->obj_definition; - $tpl = $this->tpl; - $ilMainMenu = $this->main_menu; + $this->node_id = (int) $_REQUEST["wsp_id"]; + if (!$this->node_id) { + $this->node_id = $this->tree->getRootId(); + } + } + + /** + * execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $objDefinition = $this->obj_definition; + $tpl = $this->tpl; + $ilMainMenu = $this->main_menu; - $ilCtrl->setReturn($this, "render"); - $cmd = $ilCtrl->getCmd(); + $ilCtrl->setReturn($this, "render"); + $cmd = $ilCtrl->getCmd(); - // new type - if($_REQUEST["new_type"]) - { - $class_name = $objDefinition->getClassName($_REQUEST["new_type"]); + // new type + if ($_REQUEST["new_type"]) { + $class_name = $objDefinition->getClassName($_REQUEST["new_type"]); - // Only set the fixed cmdClass if the next class is different to - // the GUI class of the new object. - // An example: - // ilObjLinkResourceGUI tries to forward to ilLinkInputGUI (adding an internal link - // when creating a link resource) - // Without this fix, the cmdClass ilObjectCopyGUI would never be reached - if (strtolower($ilCtrl->getNextClass($this)) != strtolower("ilObj".$class_name."GUI")) - { - $ilCtrl->setCmdClass("ilObj".$class_name."GUI"); - } - } + // Only set the fixed cmdClass if the next class is different to + // the GUI class of the new object. + // An example: + // ilObjLinkResourceGUI tries to forward to ilLinkInputGUI (adding an internal link + // when creating a link resource) + // Without this fix, the cmdClass ilObjectCopyGUI would never be reached + if (strtolower($ilCtrl->getNextClass($this)) != strtolower("ilObj" . $class_name . "GUI")) { + $ilCtrl->setCmdClass("ilObj" . $class_name . "GUI"); + } + } - // root node - $next_class = $ilCtrl->getNextClass(); - if(!$next_class) - { - $node = $this->tree->getNodeData($this->node_id); - $next_class = "ilObj".$objDefinition->getClassName($node["type"])."GUI"; - $ilCtrl->setCmdClass($next_class); - } - - // if we do this here the object can still change the breadcrumb - $this->renderLocator(); - - // current node - $class_path = $ilCtrl->lookupClassPath($next_class); - include_once($class_path); - $class_name = $ilCtrl->getClassForClasspath($class_path); - if($_REQUEST["new_type"]) - { - $gui = new $class_name(null, ilObject2GUI::WORKSPACE_NODE_ID, $this->node_id); - $gui->setCreationMode(); - } - else - { - $gui = new $class_name($this->node_id, ilObject2GUI::WORKSPACE_NODE_ID, false); - } - $ilCtrl->forwardCommand($gui); - - if($ilMainMenu->getMode() == ilMainMenuGUI::MODE_FULL) - { - $this->renderBack(); - } - - $tpl->setLocator(); - } + // root node + $next_class = $ilCtrl->getNextClass(); + if (!$next_class) { + $node = $this->tree->getNodeData($this->node_id); + $next_class = "ilObj" . $objDefinition->getClassName($node["type"]) . "GUI"; + $ilCtrl->setCmdClass($next_class); + } + + // if we do this here the object can still change the breadcrumb + $this->renderLocator(); + + // current node + $class_path = $ilCtrl->lookupClassPath($next_class); + include_once($class_path); + $class_name = $ilCtrl->getClassForClasspath($class_path); + if ($_REQUEST["new_type"]) { + $gui = new $class_name(null, ilObject2GUI::WORKSPACE_NODE_ID, $this->node_id); + $gui->setCreationMode(); + } else { + $gui = new $class_name($this->node_id, ilObject2GUI::WORKSPACE_NODE_ID, false); + } + $ilCtrl->forwardCommand($gui); + + if ($ilMainMenu->getMode() == ilMainMenuGUI::MODE_FULL) { + $this->renderBack(); + } + + $tpl->setLocator(); + } - /** - * Init personal tree - */ - protected function initTree() - { - $ilUser = $this->user; + /** + * Init personal tree + */ + protected function initTree() + { + $ilUser = $this->user; - $user_id = $ilUser->getId(); + $user_id = $ilUser->getId(); - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - $this->tree = new ilWorkspaceTree($user_id); - if(!$this->tree->getRootId()) - { - $this->tree->createTreeForUser($user_id); - } - } + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + $this->tree = new ilWorkspaceTree($user_id); + if (!$this->tree->getRootId()) { + $this->tree->createTreeForUser($user_id); + } + } - protected function renderBack() - { - $lng = $this->lng; - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - $root = $this->tree->getNodeData($this->node_id); - if($root["type"] != "wfld" && $root["type"] != "wsrt") - { - // do not override existing back targets, e.g. public user profile gui - if(!$ilTabs->back_target) - { - $owner = $this->tree->lookupOwner($this->node_id); - // workspace - if($owner == $ilUser->getId()) - { - $parent = $this->tree->getParentNodeData($this->node_id); - if($parent["wsp_id"]) - { - if($parent["type"] == "wsrt") - { - $class = "ilobjworkspacerootfoldergui"; - } - else - { - $class = "ilobjworkspacefoldergui"; - } - $ilCtrl->setParameterByClass($class, "wsp_id", $parent["wsp_id"]); - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTargetByClass($class, "")); - } - } - // "shared by others" - else - { - $ilCtrl->setParameterByClass("ilobjworkspacerootfoldergui", "wsp_id", ""); - $ilCtrl->setParameterByClass("ilobjworkspacerootfoldergui", "user", $owner); - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTargetByClass("ilobjworkspacerootfoldergui", "share")); - } - } - } - } - - /** - * Build locator for current node - */ - protected function renderLocator() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilLocator = $this->locator; - $tpl = $this->tpl; - $objDefinition = $this->obj_definition; + protected function renderBack() + { + $lng = $this->lng; + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + $root = $this->tree->getNodeData($this->node_id); + if ($root["type"] != "wfld" && $root["type"] != "wsrt") { + // do not override existing back targets, e.g. public user profile gui + if (!$ilTabs->back_target) { + $owner = $this->tree->lookupOwner($this->node_id); + // workspace + if ($owner == $ilUser->getId()) { + $parent = $this->tree->getParentNodeData($this->node_id); + if ($parent["wsp_id"]) { + if ($parent["type"] == "wsrt") { + $class = "ilobjworkspacerootfoldergui"; + } else { + $class = "ilobjworkspacefoldergui"; + } + $ilCtrl->setParameterByClass($class, "wsp_id", $parent["wsp_id"]); + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTargetByClass($class, "") + ); + } + } + // "shared by others" + else { + $ilCtrl->setParameterByClass("ilobjworkspacerootfoldergui", "wsp_id", ""); + $ilCtrl->setParameterByClass("ilobjworkspacerootfoldergui", "user", $owner); + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTargetByClass("ilobjworkspacerootfoldergui", "share") + ); + } + } + } + } + + /** + * Build locator for current node + */ + protected function renderLocator() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilLocator = $this->locator; + $tpl = $this->tpl; + $objDefinition = $this->obj_definition; - $ilLocator->clearItems(); - - // we have no path if shared item - $path = $this->tree->getPathFull($this->node_id); - if($path) - { - foreach($path as $node) - { - $obj_class = "ilObj".$objDefinition->getClassName($node["type"])."GUI"; + $ilLocator->clearItems(); + + // we have no path if shared item + $path = $this->tree->getPathFull($this->node_id); + if ($path) { + foreach ($path as $node) { + $obj_class = "ilObj" . $objDefinition->getClassName($node["type"]) . "GUI"; - $ilCtrl->setParameter($this, "wsp_id", $node["wsp_id"]); + $ilCtrl->setParameter($this, "wsp_id", $node["wsp_id"]); - switch($node["type"]) - { - case "wsrt": - $ilLocator->addItem($lng->txt("wsp_personal_workspace"), $ilCtrl->getLinkTargetByClass($obj_class, "render")); - break; + switch ($node["type"]) { + case "wsrt": + $ilLocator->addItem($lng->txt("wsp_personal_workspace"), $ilCtrl->getLinkTargetByClass($obj_class, "render")); + break; - case "blog": - case $objDefinition->isContainer($node["type"]): - $ilLocator->addItem($node["title"], $ilCtrl->getLinkTargetByClass($obj_class, "render")); - break; + case "blog": + case $objDefinition->isContainer($node["type"]): + $ilLocator->addItem($node["title"], $ilCtrl->getLinkTargetByClass($obj_class, "render")); + break; - default: - $ilLocator->addItem($node["title"], $ilCtrl->getLinkTargetByClass($obj_class, "edit")); - break; - } - } - } + default: + $ilLocator->addItem($node["title"], $ilCtrl->getLinkTargetByClass($obj_class, "edit")); + break; + } + } + } - $ilCtrl->setParameter($this, "wsp_id", $this->node_id); - } + $ilCtrl->setParameter($this, "wsp_id", $this->node_id); + } } - -?> \ No newline at end of file diff --git a/Services/PersonalWorkspace/classes/class.ilSharedResourceGUI.php b/Services/PersonalWorkspace/classes/class.ilSharedResourceGUI.php index 7db2022affe60fc09e0f801436331737f97597de..5f0ff59233ea03a92a25f12ca699fe307bfc356d 100644 --- a/Services/PersonalWorkspace/classes/class.ilSharedResourceGUI.php +++ b/Services/PersonalWorkspace/classes/class.ilSharedResourceGUI.php @@ -6,7 +6,7 @@ * * @author Jörg Lützenkirchen * @version $Id$ - * + * * @ilCtrl_Calls ilSharedResourceGUI: ilObjBlogGUI, ilObjFileGUI, ilObjTestVerificationGUI * @ilCtrl_Calls ilSharedResourceGUI: ilObjExerciseVerificationGUI, ilObjLinkResourceGUI * @ilCtrl_Calls ilSharedResourceGUI: ilObjPortfolioGUI @@ -15,467 +15,416 @@ */ class ilSharedResourceGUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilTemplate + */ + protected $tpl; - /** - * @var ilMainMenuGUI - */ - protected $main_menu; + /** + * @var ilMainMenuGUI + */ + protected $main_menu; - /** - * @var ilLocatorGUI - */ - protected $locator; + /** + * @var ilLocatorGUI + */ + protected $locator; - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilObjectDefinition - */ - protected $obj_definition; + /** + * @var ilObjectDefinition + */ + protected $obj_definition; - /** - * @var ilTabsGUI - */ - protected $tabs; + /** + * @var ilTabsGUI + */ + protected $tabs; - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; - protected $node_id; - protected $portfolio_id; - protected $access_handler; + protected $node_id; + protected $portfolio_id; + protected $access_handler; - function __construct() - { - global $DIC; + public function __construct() + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->tpl = $DIC["tpl"]; - $this->main_menu = $DIC["ilMainMenu"]; - $this->locator = $DIC["ilLocator"]; - $this->user = $DIC->user(); - $this->lng = $DIC->language(); - $this->obj_definition = $DIC["objDefinition"]; - $this->tabs = $DIC->tabs(); - $this->db = $DIC->database(); - $ilCtrl = $DIC->ctrl(); - - $ilCtrl->saveParameter($this, "wsp_id"); - $ilCtrl->saveParameter($this, "prt_id"); - $this->node_id = (int) $_GET["wsp_id"]; - $this->portfolio_id = (int) $_GET["prt_id"]; - } - - function executeCommand() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $ilMainMenu = $this->main_menu; - $ilLocator = $this->locator; - $ilUser = $this->user; - $lng = $this->lng; - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd(); - - $tpl->getStandardTemplate(); - - // #8509 - $ilMainMenu->setActive("desktop"); - - // #12096 - if($ilUser->getId() != ANONYMOUS_USER_ID && - $next_class && - !in_array($next_class, array("ilobjbloggui", "ilobjportfoliogui"))) - { - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - $tree = new ilWorkspaceTree($ilUser->getId()); - $access_handler = new ilWorkspaceAccessHandler($tree); - $owner_id = $tree->lookupOwner($this->node_id); - $obj_id = $tree->lookupObjectId($this->node_id); - - $lng->loadLanguageModule("wsp"); + $this->ctrl = $DIC->ctrl(); + $this->tpl = $DIC["tpl"]; + $this->main_menu = $DIC["ilMainMenu"]; + $this->locator = $DIC["ilLocator"]; + $this->user = $DIC->user(); + $this->lng = $DIC->language(); + $this->obj_definition = $DIC["objDefinition"]; + $this->tabs = $DIC->tabs(); + $this->db = $DIC->database(); + $ilCtrl = $DIC->ctrl(); + + $ilCtrl->saveParameter($this, "wsp_id"); + $ilCtrl->saveParameter($this, "prt_id"); + $this->node_id = (int) $_GET["wsp_id"]; + $this->portfolio_id = (int) $_GET["prt_id"]; + } + + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $ilMainMenu = $this->main_menu; + $ilLocator = $this->locator; + $ilUser = $this->user; + $lng = $this->lng; + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd(); + + $tpl->getStandardTemplate(); + + // #8509 + $ilMainMenu->setActive("desktop"); + + // #12096 + if ($ilUser->getId() != ANONYMOUS_USER_ID && + $next_class && + !in_array($next_class, array("ilobjbloggui", "ilobjportfoliogui"))) { + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + $tree = new ilWorkspaceTree($ilUser->getId()); + $access_handler = new ilWorkspaceAccessHandler($tree); + $owner_id = $tree->lookupOwner($this->node_id); + $obj_id = $tree->lookupObjectId($this->node_id); + + $lng->loadLanguageModule("wsp"); - // see ilPersonalWorkspaceGUI - if($owner_id != $ilUser->getId()) - { - $ilCtrl->setParameterByClass("ilpersonaldesktopgui", "dsh", $owner_id); - $link = $ilCtrl->getLinkTargetByClass("ilpersonaldesktopgui", "jumptoworkspace"); - $ilLocator->addItem($lng->txt("wsp_tab_shared"), $link); + // see ilPersonalWorkspaceGUI + if ($owner_id != $ilUser->getId()) { + $ilCtrl->setParameterByClass("ilpersonaldesktopgui", "dsh", $owner_id); + $link = $ilCtrl->getLinkTargetByClass("ilpersonaldesktopgui", "jumptoworkspace"); + $ilLocator->addItem($lng->txt("wsp_tab_shared"), $link); - include_once "Services/User/classes/class.ilUserUtil.php"; - $ilLocator->addItem(ilUserUtil::getNamePresentation($owner_id), $link); - } - else - { - $link = $ilCtrl->getLinkTargetByClass("ilpersonaldesktopgui", "jumptoworkspace"); - $ilLocator->addItem($lng->txt("wsp_tab_personal"), $link); - } - - $link = $access_handler->getGotoLink($this->node_id, $obj_id); - $ilLocator->addItem(ilObject::_lookupTitle($obj_id), $link); - $tpl->setLocator($ilLocator); - } - - switch($next_class) - { - case "ilobjbloggui": - include_once "Modules/Blog/classes/class.ilObjBlogGUI.php"; - $bgui = new ilObjBlogGUI($this->node_id, ilObject2GUI::WORKSPACE_NODE_ID); - $ilCtrl->forwardCommand($bgui); - break; - - case "ilobjfilegui": - include_once "Modules/File/classes/class.ilObjFileGUI.php"; - $fgui = new ilObjFileGUI($this->node_id, ilObject2GUI::WORKSPACE_NODE_ID); - $ilCtrl->forwardCommand($fgui); - break; - - case "ilobjtestverificationgui": - include_once "Modules/Test/classes/class.ilObjTestVerificationGUI.php"; - $tgui = new ilObjTestVerificationGUI($this->node_id, ilObject2GUI::WORKSPACE_NODE_ID); - $ilCtrl->forwardCommand($tgui); - break; - - case "ilobjexerciseverificationgui": - include_once "Modules/Exercise/classes/class.ilObjExerciseVerificationGUI.php"; - $egui = new ilObjExerciseVerificationGUI($this->node_id, ilObject2GUI::WORKSPACE_NODE_ID); - $ilCtrl->forwardCommand($egui); - break; - - case "ilobjlinkresourcegui": - include_once "Modules/WebResource/classes/class.ilObjLinkResourceGUI.php"; - $lgui = new ilObjLinkResourceGUI($this->node_id, ilObject2GUI::WORKSPACE_NODE_ID); - $ilCtrl->forwardCommand($lgui); - break; - - case "ilobjportfoliogui": - include_once "Modules/Portfolio/classes/class.ilObjPortfolioGUI.php"; - $pgui = new ilObjPortfolioGUI($this->portfolio_id, ilObject2GUI::PORTFOLIO_OBJECT_ID); - $ilCtrl->forwardCommand($pgui); - break; - - default: - if(!$cmd) - { - $cmd = "process"; - } - $this->$cmd(); - } - - $tpl->show(); - } - - protected function process() - { - if(!$this->node_id && !$this->portfolio_id) - { - exit("invalid call"); - } - - // if already logged in, we need to re-check for public password - if($this->node_id) - { - if(!self::hasAccess($this->node_id)) - { - exit("no permission"); - } - $this->redirectToResource($this->node_id); - } - else - { - if(!self::hasAccess($this->portfolio_id, true)) - { - exit("no permission"); - } - $this->redirectToResource($this->portfolio_id, true); - } - } - - public static function hasAccess($a_node_id, $a_is_portfolio = false) - { - global $DIC; + include_once "Services/User/classes/class.ilUserUtil.php"; + $ilLocator->addItem(ilUserUtil::getNamePresentation($owner_id), $link); + } else { + $link = $ilCtrl->getLinkTargetByClass("ilpersonaldesktopgui", "jumptoworkspace"); + $ilLocator->addItem($lng->txt("wsp_tab_personal"), $link); + } + + $link = $access_handler->getGotoLink($this->node_id, $obj_id); + $ilLocator->addItem(ilObject::_lookupTitle($obj_id), $link); + $tpl->setLocator($ilLocator); + } + + switch ($next_class) { + case "ilobjbloggui": + include_once "Modules/Blog/classes/class.ilObjBlogGUI.php"; + $bgui = new ilObjBlogGUI($this->node_id, ilObject2GUI::WORKSPACE_NODE_ID); + $ilCtrl->forwardCommand($bgui); + break; + + case "ilobjfilegui": + include_once "Modules/File/classes/class.ilObjFileGUI.php"; + $fgui = new ilObjFileGUI($this->node_id, ilObject2GUI::WORKSPACE_NODE_ID); + $ilCtrl->forwardCommand($fgui); + break; + + case "ilobjtestverificationgui": + include_once "Modules/Test/classes/class.ilObjTestVerificationGUI.php"; + $tgui = new ilObjTestVerificationGUI($this->node_id, ilObject2GUI::WORKSPACE_NODE_ID); + $ilCtrl->forwardCommand($tgui); + break; + + case "ilobjexerciseverificationgui": + include_once "Modules/Exercise/classes/class.ilObjExerciseVerificationGUI.php"; + $egui = new ilObjExerciseVerificationGUI($this->node_id, ilObject2GUI::WORKSPACE_NODE_ID); + $ilCtrl->forwardCommand($egui); + break; + + case "ilobjlinkresourcegui": + include_once "Modules/WebResource/classes/class.ilObjLinkResourceGUI.php"; + $lgui = new ilObjLinkResourceGUI($this->node_id, ilObject2GUI::WORKSPACE_NODE_ID); + $ilCtrl->forwardCommand($lgui); + break; + + case "ilobjportfoliogui": + include_once "Modules/Portfolio/classes/class.ilObjPortfolioGUI.php"; + $pgui = new ilObjPortfolioGUI($this->portfolio_id, ilObject2GUI::PORTFOLIO_OBJECT_ID); + $ilCtrl->forwardCommand($pgui); + break; + + default: + if (!$cmd) { + $cmd = "process"; + } + $this->$cmd(); + } + + $tpl->show(); + } + + protected function process() + { + if (!$this->node_id && !$this->portfolio_id) { + exit("invalid call"); + } + + // if already logged in, we need to re-check for public password + if ($this->node_id) { + if (!self::hasAccess($this->node_id)) { + exit("no permission"); + } + $this->redirectToResource($this->node_id); + } else { + if (!self::hasAccess($this->portfolio_id, true)) { + exit("no permission"); + } + $this->redirectToResource($this->portfolio_id, true); + } + } + + public static function hasAccess($a_node_id, $a_is_portfolio = false) + { + global $DIC; - $ilUser = $DIC->user(); - $ilSetting = $DIC->settings(); - - // if we have current user - check with normal access handler - if($ilUser->getId() != ANONYMOUS_USER_ID) - { - if(!$a_is_portfolio) - { - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - $tree = new ilWorkspaceTree($ilUser->getId()); - $access_handler = new ilWorkspaceAccessHandler($tree); - } - else - { - include_once "Modules/Portfolio/classes/class.ilPortfolioAccessHandler.php"; - $access_handler = new ilPortfolioAccessHandler(); - } - if($access_handler->checkAccess("read", "", $a_node_id)) - { - return true; - } - } - - // not logged in yet or no read access - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessGUI.php"; - - if(!$a_is_portfolio) - { - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; - $shared = ilWorkspaceAccessHandler::_getPermissions($a_node_id); - } - else - { - // #12059 - if (!$ilSetting->get('user_portfolios')) - { - return false; - } - - // #12039 - include_once "Modules/Portfolio/classes/class.ilObjPortfolio.php"; - $prtf = new ilObjPortfolio($a_node_id, false); - if(!$prtf->isOnline()) - { - return false; - } - - include_once "Modules/Portfolio/classes/class.ilPortfolioAccessHandler.php"; - $shared = ilPortfolioAccessHandler::_getPermissions($a_node_id); - } - - // object is "public" - if(in_array(ilWorkspaceAccessGUI::PERMISSION_ALL, $shared)) - { - return true; - } + $ilUser = $DIC->user(); + $ilSetting = $DIC->settings(); + + // if we have current user - check with normal access handler + if ($ilUser->getId() != ANONYMOUS_USER_ID) { + if (!$a_is_portfolio) { + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + $tree = new ilWorkspaceTree($ilUser->getId()); + $access_handler = new ilWorkspaceAccessHandler($tree); + } else { + include_once "Modules/Portfolio/classes/class.ilPortfolioAccessHandler.php"; + $access_handler = new ilPortfolioAccessHandler(); + } + if ($access_handler->checkAccess("read", "", $a_node_id)) { + return true; + } + } + + // not logged in yet or no read access + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessGUI.php"; + + if (!$a_is_portfolio) { + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; + $shared = ilWorkspaceAccessHandler::_getPermissions($a_node_id); + } else { + // #12059 + if (!$ilSetting->get('user_portfolios')) { + return false; + } + + // #12039 + include_once "Modules/Portfolio/classes/class.ilObjPortfolio.php"; + $prtf = new ilObjPortfolio($a_node_id, false); + if (!$prtf->isOnline()) { + return false; + } + + include_once "Modules/Portfolio/classes/class.ilPortfolioAccessHandler.php"; + $shared = ilPortfolioAccessHandler::_getPermissions($a_node_id); + } + + // object is "public" + if (in_array(ilWorkspaceAccessGUI::PERMISSION_ALL, $shared)) { + return true; + } - // password protected - if(in_array(ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD, $shared)) - { - if(!$a_is_portfolio) - { - ilUtil::redirect("ilias.php?baseClass=ilSharedResourceGUI&cmd=passwordForm&wsp_id=".$a_node_id); - } - else - { - ilUtil::redirect("ilias.php?baseClass=ilSharedResourceGUI&cmd=passwordForm&prt_id=".$a_node_id); - } - } - - return false; - } - - protected function redirectToResource($a_node_id, $a_is_portfolio = false) - { - $ilCtrl = $this->ctrl; - $objDefinition = $this->obj_definition; - - if(!$a_is_portfolio) - { - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; - $object_data = ilWorkspaceAccessHandler::getObjectDataFromNode($a_node_id); - if(!$object_data["obj_id"]) - { - exit("invalid object"); - } - } - else - { - if(!ilObject::_lookupType($a_node_id, false)) - { - exit("invalid object"); - } - $object_data["obj_id"] = $a_node_id; - $object_data["type"] = "prtf"; - } - - $class = $objDefinition->getClassName($object_data["type"]); - $gui = "ilobj".$class."gui"; - - switch($object_data["type"]) - { - case "blog": - $ilCtrl->setParameterByClass($gui, "wsp_id", $a_node_id); - $ilCtrl->setParameterByClass($gui, "gtp", (int)$_GET["gtp"]); - $ilCtrl->redirectByClass($gui, "preview"); - - case "tstv": - case "excv": - case "crsv": - case "scov": - $ilCtrl->setParameterByClass($gui, "wsp_id", $a_node_id); - $ilCtrl->redirectByClass($gui, "deliver"); - - case "file": - case "webr": - $ilCtrl->setParameterByClass($gui, "wsp_id", $a_node_id); - $ilCtrl->redirectByClass($gui); - - case "prtf": - $ilCtrl->setParameterByClass($gui, "prt_id", $a_node_id); - $ilCtrl->setParameterByClass($gui, "gtp", (int)$_GET["gtp"]); - if($_GET["back_url"]) - { - $ilCtrl->setParameterByClass($gui, "back_url", rawurlencode($_GET["back_url"])); - } - $ilCtrl->redirectByClass($gui, "preview"); - - default: - exit("invalid object type"); - } - } - - protected function passwordForm($form = null) - { - $tpl = $this->tpl; - $lng = $this->lng; - - $lng->loadLanguageModule("wsp"); - - $tpl->setTitle($lng->txt("wsp_password_protected_resource")); - $tpl->setDescription($lng->txt("wsp_password_protected_resource_info")); - - if(!$form) - { - $form = $this->initPasswordForm(); - } - - $tpl->setContent($form->getHTML()); - } - - protected function initPasswordForm() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilUser = $this->user; - $ilTabs = $this->tabs; - - if($this->node_id) - { - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; - $object_data = ilWorkspaceAccessHandler::getObjectDataFromNode($this->node_id); - } - else - { - $object_data["title"] = ilObject::_lookupTitle($this->portfolio_id); - } - - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this, "checkPassword")); - $form->setTitle($lng->txt("wsp_password_for").": ".$object_data["title"]); - - $password = new ilPasswordInputGUI($lng->txt("password"), "password"); - $password->setRetype(false); - $password->setRequired(true); - $password->setSkipSyntaxCheck(true); // #17757 - $form->addItem($password); - - $form->addCommandButton("checkPassword", $lng->txt("submit")); - - if($ilUser->getId() && $ilUser->getId() != ANONYMOUS_USER_ID) - { - $ilTabs->setBackTarget($lng->txt("back"), $ilCtrl->getLinkTarget($this, "cancelPassword")); - $form->addCommandButton("cancelPassword", $lng->txt("cancel")); - } - - return $form; - } - - protected function cancelPassword() - { - $ilUser = $this->user; - - if($ilUser->getId() && $ilUser->getId() != ANONYMOUS_USER_ID) - { - if($this->node_id) - { - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - $tree = new ilWorkspaceTree($ilUser->getId()); - $owner = $tree->lookupOwner($this->node_id); - ilUtil::redirect("ilias.php?baseClass=ilPersonalDesktopGUI&cmd=jumpToWorkspace&dsh=".$owner); - } - else - { - include_once "Modules/Portfolio/classes/class.ilObjPortfolio.php"; - $prtf = new ilObjPortfolio($this->portfolio_id, false); - $owner = $prtf->getOwner(); - ilUtil::redirect("ilias.php?baseClass=ilPersonalDesktopGUI&cmd=jumpToPortfolio&dsh=".$owner); - } - } - } - - protected function checkPassword() - { - $ilDB = $this->db; - $lng = $this->lng; - - $lng->loadLanguageModule("wsp"); - - $form = $this->initPasswordForm(); - if($form->checkInput()) - { - $input = md5($form->getInput("password")); - if($this->node_id) - { - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; - $password = ilWorkspaceAccessHandler::getSharedNodePassword($this->node_id); - } - else - { - include_once "Modules/Portfolio/classes/class.ilPortfolioAccessHandler.php"; - $password = ilPortfolioAccessHandler::getSharedNodePassword($this->portfolio_id); - } - if($input == $password) - { - if($this->node_id) - { - ilWorkspaceAccessHandler::keepSharedSessionPassword($this->node_id, $input); - $this->redirectToResource($this->node_id); - } - else - { - ilPortfolioAccessHandler::keepSharedSessionPassword($this->portfolio_id, $input); - $this->redirectToResource($this->portfolio_id, true); - } - } - else - { - $item = $form->getItemByPostVar("password"); - $item->setAlert($lng->txt("wsp_invalid_password")); - ilUtil::sendFailure($lng->txt("form_input_not_valid")); - } - } - - $form->setValuesByPost(); - $this->passwordForm($form); - } + // password protected + if (in_array(ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD, $shared)) { + if (!$a_is_portfolio) { + ilUtil::redirect("ilias.php?baseClass=ilSharedResourceGUI&cmd=passwordForm&wsp_id=" . $a_node_id); + } else { + ilUtil::redirect("ilias.php?baseClass=ilSharedResourceGUI&cmd=passwordForm&prt_id=" . $a_node_id); + } + } + + return false; + } + + protected function redirectToResource($a_node_id, $a_is_portfolio = false) + { + $ilCtrl = $this->ctrl; + $objDefinition = $this->obj_definition; + + if (!$a_is_portfolio) { + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; + $object_data = ilWorkspaceAccessHandler::getObjectDataFromNode($a_node_id); + if (!$object_data["obj_id"]) { + exit("invalid object"); + } + } else { + if (!ilObject::_lookupType($a_node_id, false)) { + exit("invalid object"); + } + $object_data["obj_id"] = $a_node_id; + $object_data["type"] = "prtf"; + } + + $class = $objDefinition->getClassName($object_data["type"]); + $gui = "ilobj" . $class . "gui"; + + switch ($object_data["type"]) { + case "blog": + $ilCtrl->setParameterByClass($gui, "wsp_id", $a_node_id); + $ilCtrl->setParameterByClass($gui, "gtp", (int) $_GET["gtp"]); + $ilCtrl->redirectByClass($gui, "preview"); + + // no break + case "tstv": + case "excv": + case "crsv": + case "scov": + $ilCtrl->setParameterByClass($gui, "wsp_id", $a_node_id); + $ilCtrl->redirectByClass($gui, "deliver"); + + // no break + case "file": + case "webr": + $ilCtrl->setParameterByClass($gui, "wsp_id", $a_node_id); + $ilCtrl->redirectByClass($gui); + + // no break + case "prtf": + $ilCtrl->setParameterByClass($gui, "prt_id", $a_node_id); + $ilCtrl->setParameterByClass($gui, "gtp", (int) $_GET["gtp"]); + if ($_GET["back_url"]) { + $ilCtrl->setParameterByClass($gui, "back_url", rawurlencode($_GET["back_url"])); + } + $ilCtrl->redirectByClass($gui, "preview"); + + // no break + default: + exit("invalid object type"); + } + } + + protected function passwordForm($form = null) + { + $tpl = $this->tpl; + $lng = $this->lng; + + $lng->loadLanguageModule("wsp"); + + $tpl->setTitle($lng->txt("wsp_password_protected_resource")); + $tpl->setDescription($lng->txt("wsp_password_protected_resource_info")); + + if (!$form) { + $form = $this->initPasswordForm(); + } + + $tpl->setContent($form->getHTML()); + } + + protected function initPasswordForm() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilUser = $this->user; + $ilTabs = $this->tabs; + + if ($this->node_id) { + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; + $object_data = ilWorkspaceAccessHandler::getObjectDataFromNode($this->node_id); + } else { + $object_data["title"] = ilObject::_lookupTitle($this->portfolio_id); + } + + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this, "checkPassword")); + $form->setTitle($lng->txt("wsp_password_for") . ": " . $object_data["title"]); + + $password = new ilPasswordInputGUI($lng->txt("password"), "password"); + $password->setRetype(false); + $password->setRequired(true); + $password->setSkipSyntaxCheck(true); // #17757 + $form->addItem($password); + + $form->addCommandButton("checkPassword", $lng->txt("submit")); + + if ($ilUser->getId() && $ilUser->getId() != ANONYMOUS_USER_ID) { + $ilTabs->setBackTarget($lng->txt("back"), $ilCtrl->getLinkTarget($this, "cancelPassword")); + $form->addCommandButton("cancelPassword", $lng->txt("cancel")); + } + + return $form; + } + + protected function cancelPassword() + { + $ilUser = $this->user; + + if ($ilUser->getId() && $ilUser->getId() != ANONYMOUS_USER_ID) { + if ($this->node_id) { + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + $tree = new ilWorkspaceTree($ilUser->getId()); + $owner = $tree->lookupOwner($this->node_id); + ilUtil::redirect("ilias.php?baseClass=ilPersonalDesktopGUI&cmd=jumpToWorkspace&dsh=" . $owner); + } else { + include_once "Modules/Portfolio/classes/class.ilObjPortfolio.php"; + $prtf = new ilObjPortfolio($this->portfolio_id, false); + $owner = $prtf->getOwner(); + ilUtil::redirect("ilias.php?baseClass=ilPersonalDesktopGUI&cmd=jumpToPortfolio&dsh=" . $owner); + } + } + } + + protected function checkPassword() + { + $ilDB = $this->db; + $lng = $this->lng; + + $lng->loadLanguageModule("wsp"); + + $form = $this->initPasswordForm(); + if ($form->checkInput()) { + $input = md5($form->getInput("password")); + if ($this->node_id) { + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; + $password = ilWorkspaceAccessHandler::getSharedNodePassword($this->node_id); + } else { + include_once "Modules/Portfolio/classes/class.ilPortfolioAccessHandler.php"; + $password = ilPortfolioAccessHandler::getSharedNodePassword($this->portfolio_id); + } + if ($input == $password) { + if ($this->node_id) { + ilWorkspaceAccessHandler::keepSharedSessionPassword($this->node_id, $input); + $this->redirectToResource($this->node_id); + } else { + ilPortfolioAccessHandler::keepSharedSessionPassword($this->portfolio_id, $input); + $this->redirectToResource($this->portfolio_id, true); + } + } else { + $item = $form->getItemByPostVar("password"); + $item->setAlert($lng->txt("wsp_invalid_password")); + ilUtil::sendFailure($lng->txt("form_input_not_valid")); + } + } + + $form->setValuesByPost(); + $this->passwordForm($form); + } } - -?> \ No newline at end of file diff --git a/Services/PersonalWorkspace/classes/class.ilSingleUserShareGUI.php b/Services/PersonalWorkspace/classes/class.ilSingleUserShareGUI.php index f5352e02ba436f94a0f87a7bb6fc199bd90e7b03..09fb8bc0c318027b8adb0dfad04abe1165da452a 100644 --- a/Services/PersonalWorkspace/classes/class.ilSingleUserShareGUI.php +++ b/Services/PersonalWorkspace/classes/class.ilSingleUserShareGUI.php @@ -9,100 +9,90 @@ */ class ilSingleUserShareGUI { - protected $tpl; - protected $ctrl; - protected $lng; - - public function __construct($wsp_access_handler = null, $wsp_node_id = null) - { - global $DIC; - - $this->tpl = $DIC['tpl']; - $this->ctrl = $DIC['ilCtrl']; - $this->lng = $DIC['lng']; - - // personal workspace - $this->wsp_access_handler = $wsp_access_handler; - $this->wsp_node_id = $wsp_node_id; - } - - public function executeCommand() - { - $forward_class = $this->ctrl->getNextClass($this); - - switch($forward_class) - { - default: - if (!($cmd = $this->ctrl->getCmd())) - { - $cmd = "initShareForm"; - } - $this->$cmd(); - break; - } - return true; - } - - public function initShareForm(ilPropertyFormGUI $form = null) - { - if(!($form instanceof ilPropertyFormGUI)) - { - $form = $this->getShareForm(); - } - $this->tpl->setContent($form->getHTML()); - } - - public function getShareForm() - { - include_once './Services/Form/classes/class.ilPropertyFormGUI.php'; - $form = new ilPropertyFormGUI(); - - $form->setTitle($this->lng->txt("share_content")); - $form->setId('share_usr'); - - $form->setFormAction($this->ctrl->getFormAction($this, 'saveShare')); - - $inp = new ilTextInputGUI($this->lng->txt("share_with"), 'name'); - $inp->setSize(20); - $form->addItem($inp); - - $form->addCommandButton('saveShare', $this->lng->txt("share")); - $form->addCommandButton('cancel', $this->lng->txt("cancel")); - - return $form; - } - - protected function saveShare() - { - $form = $this->getShareForm(); - - if($form->checkInput()) - { - if($user_id = ilObjUser::_lookupId($form->getInput('name'))) - { - $existing = $this->wsp_access_handler->getPermissions($this->wsp_node_id); - - if(!in_array($user_id, $existing)) - { - $this->wsp_access_handler->addPermission($this->wsp_node_id, $user_id); - ilUtil::sendSuccess($this->lng->txt("element_shared"),true); - } - else - { - ilUtil::sendInfo($this->lng->txt("element_already_shared"),true); - } - $this->ctrl->returnToParent($this); - } - else - { - ilUtil::sendFailure($this->lng->txt('search_no_match'),true); - } - } - $this->ctrl->redirect($this); - } - - public function cancel() - { - $this->ctrl->returnToParent($this); - } -} \ No newline at end of file + protected $tpl; + protected $ctrl; + protected $lng; + + public function __construct($wsp_access_handler = null, $wsp_node_id = null) + { + global $DIC; + + $this->tpl = $DIC['tpl']; + $this->ctrl = $DIC['ilCtrl']; + $this->lng = $DIC['lng']; + + // personal workspace + $this->wsp_access_handler = $wsp_access_handler; + $this->wsp_node_id = $wsp_node_id; + } + + public function executeCommand() + { + $forward_class = $this->ctrl->getNextClass($this); + + switch ($forward_class) { + default: + if (!($cmd = $this->ctrl->getCmd())) { + $cmd = "initShareForm"; + } + $this->$cmd(); + break; + } + return true; + } + + public function initShareForm(ilPropertyFormGUI $form = null) + { + if (!($form instanceof ilPropertyFormGUI)) { + $form = $this->getShareForm(); + } + $this->tpl->setContent($form->getHTML()); + } + + public function getShareForm() + { + include_once './Services/Form/classes/class.ilPropertyFormGUI.php'; + $form = new ilPropertyFormGUI(); + + $form->setTitle($this->lng->txt("share_content")); + $form->setId('share_usr'); + + $form->setFormAction($this->ctrl->getFormAction($this, 'saveShare')); + + $inp = new ilTextInputGUI($this->lng->txt("share_with"), 'name'); + $inp->setSize(20); + $form->addItem($inp); + + $form->addCommandButton('saveShare', $this->lng->txt("share")); + $form->addCommandButton('cancel', $this->lng->txt("cancel")); + + return $form; + } + + protected function saveShare() + { + $form = $this->getShareForm(); + + if ($form->checkInput()) { + if ($user_id = ilObjUser::_lookupId($form->getInput('name'))) { + $existing = $this->wsp_access_handler->getPermissions($this->wsp_node_id); + + if (!in_array($user_id, $existing)) { + $this->wsp_access_handler->addPermission($this->wsp_node_id, $user_id); + ilUtil::sendSuccess($this->lng->txt("element_shared"), true); + } else { + ilUtil::sendInfo($this->lng->txt("element_already_shared"), true); + } + $this->ctrl->returnToParent($this); + } else { + ilUtil::sendFailure($this->lng->txt('search_no_match'), true); + } + } + $this->ctrl->redirect($this); + } + + public function cancel() + { + $this->ctrl->returnToParent($this); + } +} diff --git a/Services/PersonalWorkspace/classes/class.ilWorkspaceAccessGUI.php b/Services/PersonalWorkspace/classes/class.ilWorkspaceAccessGUI.php index cef8e7c368cfb7ef491ade6966928d2a98ffbe38..77e49eab741a8eb44295963c96f1a60085eff8d8 100644 --- a/Services/PersonalWorkspace/classes/class.ilWorkspaceAccessGUI.php +++ b/Services/PersonalWorkspace/classes/class.ilWorkspaceAccessGUI.php @@ -6,7 +6,7 @@ * * @author Jörg Lützenkirchen * @version $Id$ - * + * * @ilCtrl_Calls ilWorkspaceAccessGUI: ilMailSearchCoursesGUI, ilMailSearchGroupsGUI * @ilCtrl_Calls ilWorkspaceAccessGUI: ilMailSearchGUI, ilPublicUserProfileGUI, ilSingleUserShareGUI * @@ -14,351 +14,347 @@ */ class ilWorkspaceAccessGUI { - /** - * @var ilTabsGUI - */ - protected $tabs; + /** + * @var ilTabsGUI + */ + protected $tabs; - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilTemplate + */ + protected $tpl; - /** - * @var ilToolbarGUI - */ - protected $toolbar; + /** + * @var ilToolbarGUI + */ + protected $toolbar; - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - /** - * @var ilSetting - */ - protected $settings; + /** + * @var ilSetting + */ + protected $settings; - protected $ctrl; - protected $lng; - protected $node_id; - protected $access_handler; - protected $footer; - - const PERMISSION_REGISTERED = -1; - const PERMISSION_ALL_PASSWORD = -3; - const PERMISSION_ALL = -5; + protected $ctrl; + protected $lng; + protected $node_id; + protected $access_handler; + protected $footer; + + const PERMISSION_REGISTERED = -1; + const PERMISSION_ALL_PASSWORD = -3; + const PERMISSION_ALL = -5; - /** - * @var string - */ - protected $blocking_message = ""; + /** + * @var string + */ + protected $blocking_message = ""; - function __construct($a_node_id, $a_access_handler, $a_is_portfolio = false, $a_footer = null) - { - global $DIC; + public function __construct($a_node_id, $a_access_handler, $a_is_portfolio = false, $a_footer = null) + { + global $DIC; - $this->tabs = $DIC->tabs(); - $this->tpl = $DIC["tpl"]; - $this->toolbar = $DIC->toolbar(); - $this->user = $DIC->user(); - $this->settings = $DIC->settings(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->ctrl = $ilCtrl; - $this->lng = $lng; - $this->node_id = $a_node_id; - $this->access_handler = $a_access_handler; - $this->is_portfolio = (bool)$a_is_portfolio; - $this->footer = $a_footer; - } + $this->tabs = $DIC->tabs(); + $this->tpl = $DIC["tpl"]; + $this->toolbar = $DIC->toolbar(); + $this->user = $DIC->user(); + $this->settings = $DIC->settings(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->ctrl = $ilCtrl; + $this->lng = $lng; + $this->node_id = $a_node_id; + $this->access_handler = $a_access_handler; + $this->is_portfolio = (bool) $a_is_portfolio; + $this->footer = $a_footer; + } - /** - * Set blocking message - * - * @param string $a_val blocking message - */ - function setBlockingMessage($a_val) - { - $this->blocking_message = $a_val; - } + /** + * Set blocking message + * + * @param string $a_val blocking message + */ + public function setBlockingMessage($a_val) + { + $this->blocking_message = $a_val; + } - /** - * Get blocking message - * - * @return string blocking message - */ - function getBlockingMessage() - { - return $this->blocking_message; - } + /** + * Get blocking message + * + * @return string blocking message + */ + public function getBlockingMessage() + { + return $this->blocking_message; + } - - function executeCommand() - { - $ilTabs = $this->tabs; - $tpl = $this->tpl; + + public function executeCommand() + { + $ilTabs = $this->tabs; + $tpl = $this->tpl; - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - switch($next_class) - { - case "ilmailsearchcoursesgui"; - $ilTabs->setBackTarget($this->lng->txt("back"), - $this->ctrl->getLinkTarget($this, "share")); - include_once('Services/Contact/classes/class.ilMailSearchCoursesGUI.php'); - $csearch = new ilMailSearchCoursesGUI($this->access_handler, $this->node_id); - $this->ctrl->setReturn($this, 'share'); - $this->ctrl->forwardCommand($csearch); - - $this->setObjectTitle(); - break; - - case "ilmailsearchgroupsgui"; - $ilTabs->setBackTarget($this->lng->txt("back"), - $this->ctrl->getLinkTarget($this, "share")); - include_once('Services/Contact/classes/class.ilMailSearchGroupsGUI.php'); - $gsearch = new ilMailSearchGroupsGUI($this->access_handler, $this->node_id); - $this->ctrl->setReturn($this, 'share'); - $this->ctrl->forwardCommand($gsearch); - - $this->setObjectTitle(); - break; - - case "ilmailsearchgui"; - $ilTabs->setBackTarget($this->lng->txt("back"), - $this->ctrl->getLinkTarget($this, "share")); - include_once('Services/Contact/classes/class.ilMailSearchGUI.php'); - $usearch = new ilMailSearchGUI($this->access_handler, $this->node_id); - $this->ctrl->setReturn($this, 'share'); - $this->ctrl->forwardCommand($usearch); - - $this->setObjectTitle(); - break; + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + switch ($next_class) { + case "ilmailsearchcoursesgui": + $ilTabs->setBackTarget( + $this->lng->txt("back"), + $this->ctrl->getLinkTarget($this, "share") + ); + include_once('Services/Contact/classes/class.ilMailSearchCoursesGUI.php'); + $csearch = new ilMailSearchCoursesGUI($this->access_handler, $this->node_id); + $this->ctrl->setReturn($this, 'share'); + $this->ctrl->forwardCommand($csearch); + + $this->setObjectTitle(); + break; + + case "ilmailsearchgroupsgui": + $ilTabs->setBackTarget( + $this->lng->txt("back"), + $this->ctrl->getLinkTarget($this, "share") + ); + include_once('Services/Contact/classes/class.ilMailSearchGroupsGUI.php'); + $gsearch = new ilMailSearchGroupsGUI($this->access_handler, $this->node_id); + $this->ctrl->setReturn($this, 'share'); + $this->ctrl->forwardCommand($gsearch); + + $this->setObjectTitle(); + break; + + case "ilmailsearchgui": + $ilTabs->setBackTarget( + $this->lng->txt("back"), + $this->ctrl->getLinkTarget($this, "share") + ); + include_once('Services/Contact/classes/class.ilMailSearchGUI.php'); + $usearch = new ilMailSearchGUI($this->access_handler, $this->node_id); + $this->ctrl->setReturn($this, 'share'); + $this->ctrl->forwardCommand($usearch); + + $this->setObjectTitle(); + break; - case "ilsingleusersharegui"; - $ilTabs->setBackTarget($this->lng->txt("back"), - $this->ctrl->getLinkTarget($this, "share")); - include_once('Services/PersonalWorkspace/classes/class.ilSingleUserShareGUI.php'); - $ushare = new ilSingleUserShareGUI($this->access_handler, $this->node_id); - $this->ctrl->setReturn($this, 'share'); - $this->ctrl->forwardCommand($ushare); + case "ilsingleusersharegui": + $ilTabs->setBackTarget( + $this->lng->txt("back"), + $this->ctrl->getLinkTarget($this, "share") + ); + include_once('Services/PersonalWorkspace/classes/class.ilSingleUserShareGUI.php'); + $ushare = new ilSingleUserShareGUI($this->access_handler, $this->node_id); + $this->ctrl->setReturn($this, 'share'); + $this->ctrl->forwardCommand($ushare); - $this->setObjectTitle(); - break; + $this->setObjectTitle(); + break; - case "ilpublicuserprofilegui"; - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($this->lng->txt("back"), - $this->ctrl->getLinkTarget($this, "share")); - - include_once('./Services/User/classes/class.ilPublicUserProfileGUI.php'); - $prof = new ilPublicUserProfileGUI($_REQUEST["user"]); - $prof->setBackUrl($this->ctrl->getLinkTarget($this, "share")); - $tpl->setContent($prof->getHTML()); - break; + case "ilpublicuserprofilegui": + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $this->lng->txt("back"), + $this->ctrl->getLinkTarget($this, "share") + ); + + include_once('./Services/User/classes/class.ilPublicUserProfileGUI.php'); + $prof = new ilPublicUserProfileGUI($_REQUEST["user"]); + $prof->setBackUrl($this->ctrl->getLinkTarget($this, "share")); + $tpl->setContent($prof->getHTML()); + break; - default: - // $this->prepareOutput(); - if(!$cmd) - { - $cmd = "share"; - } - return $this->$cmd(); - } + default: + // $this->prepareOutput(); + if (!$cmd) { + $cmd = "share"; + } + return $this->$cmd(); + } - return true; - } - - /** - * restore object title - * - * @return string - */ - protected function setObjectTitle() - { - $tpl = $this->tpl; - - if(!$this->is_portfolio) - { - $obj_id = $this->access_handler->getTree()->lookupObjectId($this->node_id); - } - else - { - $obj_id = $this->node_id; - } - $tpl->setTitle(ilObject::_lookupTitle($obj_id)); - } - - protected function getAccessHandler() - { - return $this->access_handler; - } - - protected function share() - { - $ilToolbar = $this->toolbar; - $tpl = $this->tpl; - $ilUser = $this->user; - $ilSetting = $this->settings; + return true; + } + + /** + * restore object title + * + * @return string + */ + protected function setObjectTitle() + { + $tpl = $this->tpl; + + if (!$this->is_portfolio) { + $obj_id = $this->access_handler->getTree()->lookupObjectId($this->node_id); + } else { + $obj_id = $this->node_id; + } + $tpl->setTitle(ilObject::_lookupTitle($obj_id)); + } + + protected function getAccessHandler() + { + return $this->access_handler; + } + + protected function share() + { + $ilToolbar = $this->toolbar; + $tpl = $this->tpl; + $ilUser = $this->user; + $ilSetting = $this->settings; - // blocking message - if ($this->getBlockingMessage() != "") - { - $tpl->setContent($this->getBlockingMessage()); - return; - } - - $options = array(); - $options["user"] = $this->lng->txt("wsp_set_permission_single_user"); - - include_once 'Modules/Group/classes/class.ilGroupParticipants.php'; - $grp_ids = ilGroupParticipants::_getMembershipByType($ilUser->getId(), 'grp'); - if(sizeof($grp_ids)) - { - $options["group"] = $this->lng->txt("wsp_set_permission_group"); - } - - include_once 'Modules/Course/classes/class.ilCourseParticipants.php'; - $crs_ids = ilCourseParticipants::_getMembershipByType($ilUser->getId(), 'crs'); - if(sizeof($crs_ids)) - { - $options["course"] = $this->lng->txt("wsp_set_permission_course"); - } - - if(!$this->getAccessHandler()->hasRegisteredPermission($this->node_id)) - { - $options["registered"] = $this->lng->txt("wsp_set_permission_registered"); - } - - if($ilSetting->get("enable_global_profiles")) - { - if(!$this->getAccessHandler()->hasGlobalPasswordPermission($this->node_id)) - { - $options["password"] = $this->lng->txt("wsp_set_permission_all_password"); - } + // blocking message + if ($this->getBlockingMessage() != "") { + $tpl->setContent($this->getBlockingMessage()); + return; + } + + $options = array(); + $options["user"] = $this->lng->txt("wsp_set_permission_single_user"); + + include_once 'Modules/Group/classes/class.ilGroupParticipants.php'; + $grp_ids = ilGroupParticipants::_getMembershipByType($ilUser->getId(), 'grp'); + if (sizeof($grp_ids)) { + $options["group"] = $this->lng->txt("wsp_set_permission_group"); + } + + include_once 'Modules/Course/classes/class.ilCourseParticipants.php'; + $crs_ids = ilCourseParticipants::_getMembershipByType($ilUser->getId(), 'crs'); + if (sizeof($crs_ids)) { + $options["course"] = $this->lng->txt("wsp_set_permission_course"); + } + + if (!$this->getAccessHandler()->hasRegisteredPermission($this->node_id)) { + $options["registered"] = $this->lng->txt("wsp_set_permission_registered"); + } + + if ($ilSetting->get("enable_global_profiles")) { + if (!$this->getAccessHandler()->hasGlobalPasswordPermission($this->node_id)) { + $options["password"] = $this->lng->txt("wsp_set_permission_all_password"); + } - if(!$this->getAccessHandler()->hasGlobalPermission($this->node_id)) - { - $options["all"] = $this->lng->txt("wsp_set_permission_all"); - } - } - - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $actions = new ilSelectInputGUI("", "action"); - $actions->setOptions($options); - $ilToolbar->addStickyItem($actions); - - $ilToolbar->setFormAction($this->ctrl->getFormAction($this)); - - include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; - $button = ilSubmitButton::getInstance(); - $button->setCaption("add"); - $button->setCommand("addpermissionhandler"); - $ilToolbar->addStickyItem($button); - - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessTableGUI.php"; - $table = new ilWorkspaceAccessTableGUI($this, "share", $this->node_id, $this->getAccessHandler()); - $tpl->setContent($table->getHTML().$this->footer); - } - - public function addPermissionHandler() - { - switch($_REQUEST["action"]) - { - case "user": + if (!$this->getAccessHandler()->hasGlobalPermission($this->node_id)) { + $options["all"] = $this->lng->txt("wsp_set_permission_all"); + } + } + + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $actions = new ilSelectInputGUI("", "action"); + $actions->setOptions($options); + $ilToolbar->addStickyItem($actions); + + $ilToolbar->setFormAction($this->ctrl->getFormAction($this)); + + include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php"; + $button = ilSubmitButton::getInstance(); + $button->setCaption("add"); + $button->setCommand("addpermissionhandler"); + $ilToolbar->addStickyItem($button); + + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessTableGUI.php"; + $table = new ilWorkspaceAccessTableGUI($this, "share", $this->node_id, $this->getAccessHandler()); + $tpl->setContent($table->getHTML() . $this->footer); + } + + public function addPermissionHandler() + { + switch ($_REQUEST["action"]) { + case "user": - include_once './Services/User/classes/class.ilUserAccountSettings.php'; - if(ilUserAccountSettings::getInstance()->isUserAccessRestricted()) - { - $this->ctrl->redirectByClass("ilsingleusersharegui"); - } - else - { - $this->ctrl->setParameterByClass("ilmailsearchgui", "ref", "wsp"); - $this->ctrl->redirectByClass("ilmailsearchgui"); - } - - case "group": - $this->ctrl->setParameterByClass("ilmailsearchgroupsgui", "ref", "wsp"); - $this->ctrl->redirectByClass("ilmailsearchgroupsgui"); - - case "course": - $this->ctrl->setParameterByClass("ilmailsearchcoursesgui", "ref", "wsp"); - $this->ctrl->redirectByClass("ilmailsearchcoursesgui"); - - case "registered": - $this->getAccessHandler()->addPermission($this->node_id, self::PERMISSION_REGISTERED); - ilUtil::sendSuccess($this->lng->txt("wsp_permission_registered_info"), true); - $this->ctrl->redirect($this, "share"); - - case "password": - $this->showPasswordForm(); - break; - - case "all": - $this->getAccessHandler()->addPermission($this->node_id, self::PERMISSION_ALL); - ilUtil::sendSuccess($this->lng->txt("wsp_permission_all_info"), true); - $this->ctrl->redirect($this, "share"); - } - } - - public function removePermission() - { - if($_REQUEST["obj_id"]) - { - $this->getAccessHandler()->removePermission($this->node_id, (int)$_REQUEST["obj_id"]); - ilUtil::sendSuccess($this->lng->txt("wsp_permission_removed"), true); - } + include_once './Services/User/classes/class.ilUserAccountSettings.php'; + if (ilUserAccountSettings::getInstance()->isUserAccessRestricted()) { + $this->ctrl->redirectByClass("ilsingleusersharegui"); + } else { + $this->ctrl->setParameterByClass("ilmailsearchgui", "ref", "wsp"); + $this->ctrl->redirectByClass("ilmailsearchgui"); + } + + // no break + case "group": + $this->ctrl->setParameterByClass("ilmailsearchgroupsgui", "ref", "wsp"); + $this->ctrl->redirectByClass("ilmailsearchgroupsgui"); + + // no break + case "course": + $this->ctrl->setParameterByClass("ilmailsearchcoursesgui", "ref", "wsp"); + $this->ctrl->redirectByClass("ilmailsearchcoursesgui"); + + // no break + case "registered": + $this->getAccessHandler()->addPermission($this->node_id, self::PERMISSION_REGISTERED); + ilUtil::sendSuccess($this->lng->txt("wsp_permission_registered_info"), true); + $this->ctrl->redirect($this, "share"); + + // no break + case "password": + $this->showPasswordForm(); + break; + + case "all": + $this->getAccessHandler()->addPermission($this->node_id, self::PERMISSION_ALL); + ilUtil::sendSuccess($this->lng->txt("wsp_permission_all_info"), true); + $this->ctrl->redirect($this, "share"); + } + } + + public function removePermission() + { + if ($_REQUEST["obj_id"]) { + $this->getAccessHandler()->removePermission($this->node_id, (int) $_REQUEST["obj_id"]); + ilUtil::sendSuccess($this->lng->txt("wsp_permission_removed"), true); + } - $this->ctrl->redirect($this, "share"); - } - - protected function initPasswordForm() - { - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - $form->setTitle($this->lng->txt("wsp_set_permission_all_password")); - - $password = new ilPasswordInputGUI($this->lng->txt("password"), "password"); - $password->setRequired(true); - $form->addItem($password); - - $form->addCommandButton('savepasswordform', $this->lng->txt("save")); - $form->addCommandButton('share', $this->lng->txt("cancel")); - - return $form; - } - - protected function showPasswordForm(ilPropertyFormGUI $a_form = null) - { - $tpl = $this->tpl; - - if(!$a_form) - { - $a_form = $this->initPasswordForm(); - } - $tpl->setContent($a_form->getHTML()); - } - - protected function savePasswordForm() - { - $form = $this->initPasswordForm(); - if($form->checkInput()) - { - $this->getAccessHandler()->addPermission($this->node_id, - self::PERMISSION_ALL_PASSWORD, md5($form->getInput("password"))); - ilUtil::sendSuccess($this->lng->txt("wsp_permission_all_pw_info"), true); - $this->ctrl->redirect($this, "share"); - } - - $form->setValuesByPost(); - $this->showPasswordForm($form); - } + $this->ctrl->redirect($this, "share"); + } + + protected function initPasswordForm() + { + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this)); + $form->setTitle($this->lng->txt("wsp_set_permission_all_password")); + + $password = new ilPasswordInputGUI($this->lng->txt("password"), "password"); + $password->setRequired(true); + $form->addItem($password); + + $form->addCommandButton('savepasswordform', $this->lng->txt("save")); + $form->addCommandButton('share', $this->lng->txt("cancel")); + + return $form; + } + + protected function showPasswordForm(ilPropertyFormGUI $a_form = null) + { + $tpl = $this->tpl; + + if (!$a_form) { + $a_form = $this->initPasswordForm(); + } + $tpl->setContent($a_form->getHTML()); + } + + protected function savePasswordForm() + { + $form = $this->initPasswordForm(); + if ($form->checkInput()) { + $this->getAccessHandler()->addPermission( + $this->node_id, + self::PERMISSION_ALL_PASSWORD, + md5($form->getInput("password")) + ); + ilUtil::sendSuccess($this->lng->txt("wsp_permission_all_pw_info"), true); + $this->ctrl->redirect($this, "share"); + } + + $form->setValuesByPost(); + $this->showPasswordForm($form); + } } - -?> \ No newline at end of file diff --git a/Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php b/Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php index fd91313d443c95fcd0a33fc58c1d42cbfafcb5a1..887aef0bbb73e491d50bbd97ea4faab4c212b616 100644 --- a/Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php +++ b/Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php @@ -11,605 +11,559 @@ include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessGUI.php" * * @author Jörg Lützenkirchen * @version $Id: class.ilPersonalDesktopGUI.php 26976 2010-12-16 13:24:38Z akill $ - * + * * @ingroup ServicesPersonalWorkspace */ class ilWorkspaceAccessHandler { - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilRbacReview - */ - protected $rbacreview; - - /** - * @var ilSetting - */ - protected $settings; - - /** - * @var ilDB - */ - protected $db; - - protected $tree; // [ilTree] - - public function __construct(ilTree $a_tree = null) - { - global $DIC; - - $this->user = $DIC->user(); - $this->lng = $DIC->language(); - $this->rbacreview = $DIC->rbac()->review(); - $this->settings = $DIC->settings(); - $this->db = $DIC->database(); - $ilUser = $DIC->user(); - $lng = $DIC->language(); - - $lng->loadLanguageModule("wsp"); - - if(!$a_tree) - { - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - $a_tree = new ilWorkspaceTree($ilUser->getId()); - } - $this->tree = $a_tree; - } - - /** - * Get workspace tree - * - * @return ilWorkspaceTree - */ - public function getTree() - { - return $this->tree; - } - - /** - * check access for an object - * - * @param string $a_permission - * @param string $a_cmd - * @param int $a_node_id - * @param string $a_type (optional) - * @return bool - */ - public function checkAccess($a_permission, $a_cmd, $a_node_id, $a_type = "") - { - $ilUser = $this->user; - - return $this->checkAccessOfUser($this->tree, $ilUser->getId(),$a_permission, $a_cmd, $a_node_id, $a_type); - } - - /** - * check access for an object - * - * @param ilTree $a_tree - * @param integer $a_user_id - * @param string $a_permission - * @param string $a_cmd - * @param int $a_node_id - * @param string $a_type (optional) - * @return bool - */ - public function checkAccessOfUser(ilTree $a_tree, $a_user_id, $a_permission, $a_cmd, $a_node_id, $a_type = "") - { - $rbacreview = $this->rbacreview; - $ilUser = $this->user; - $ilSetting = $this->settings; - - // :TODO: create permission for parent node with type ?! - - // #20310 - if(!$ilSetting->get("enable_global_profiles") && $ilUser->getId() == ANONYMOUS_USER_ID) - { - return false; - } - - // tree root is read-only - if($a_permission == "write") - { - if($a_tree->readRootId() == $a_node_id) - { - return false; - } - } - - // node owner has all rights - if($a_tree->lookupOwner($a_node_id) == $a_user_id) - { - return true; - } - - // other users can only read - if($a_permission == "read" || $a_permission == "visible") - { - // get all objects with explicit permission - $objects = $this->getPermissions($a_node_id); - if($objects) - { - // check if given user is member of object or has role - foreach($objects as $obj_id) - { - switch($obj_id) - { - case ilWorkspaceAccessGUI::PERMISSION_ALL: - return true; - - case ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD: - // check against input kept in session - if(self::getSharedNodePassword($a_node_id) == self::getSharedSessionPassword($a_node_id) || - $a_permission == "visible") - { - return true; - } - break; - - case ilWorkspaceAccessGUI::PERMISSION_REGISTERED: - if($ilUser->getId() != ANONYMOUS_USER_ID) - { - return true; - } - break; - - default: - switch(ilObject::_lookupType($obj_id)) - { - case "grp": - // member of group? - if(ilGroupParticipants::_getInstanceByObjId($obj_id)->isAssigned($a_user_id)) - { - return true; - } - break; - - case "crs": - // member of course? - if(ilCourseParticipants::_getInstanceByObjId($obj_id)->isAssigned($a_user_id)) - { - return true; - } - break; - - case "role": - // has role? - if($rbacreview->isAssigned($a_user_id, $obj_id)) - { - return true; - } - break; - - case "usr": - // direct assignment - if($a_user_id == $obj_id) - { - return true; - } - break; - } - break; - } - } - } - } - - return false; - } - - /** - * Set permissions after creating node/object - * - * @param int $a_parent_node_id - * @param int $a_node_id - */ - public function setPermissions($a_parent_node_id, $a_node_id) - { - // nothing to do as owner has irrefutable rights to any workspace object - } - - /** - * Add permission to node for object - * - * @param int $a_node_id - * @param int $a_object_id - * @param string $a_extended_data - * @return bool - */ - public function addPermission($a_node_id, $a_object_id, $a_extended_data = null) - { - $ilDB = $this->db; - $ilUser = $this->user; - - // tree owner must not be added - if($this->tree->getTreeId() == $ilUser->getId() && - $a_object_id == $ilUser->getId()) - { - return false; - } - - $ilDB->manipulate("INSERT INTO acl_ws (node_id, object_id, extended_data, tstamp)". - " VALUES (".$ilDB->quote($a_node_id, "integer").", ". - $ilDB->quote($a_object_id, "integer").",". - $ilDB->quote($a_extended_data, "text").",". - $ilDB->quote(time(), "integer").")"); - return true; - } - - /** - * Remove permission[s] (for object) to node - * - * @param int $a_node_id - * @param int $a_object_id - */ - public function removePermission($a_node_id, $a_object_id = null) - { - $ilDB = $this->db; - - $query = "DELETE FROM acl_ws". - " WHERE node_id = ".$ilDB->quote($a_node_id, "integer"); - - if($a_object_id) - { - $query .= " AND object_id = ".$ilDB->quote($a_object_id, "integer"); - } - - return $ilDB->manipulate($query); - } - - /** - * Get all permissions to node - * - * @param int $a_node_id - * @return array - */ - public function getPermissions($a_node_id) - { - return self::_getPermissions($a_node_id); - } - - /** - * Get all permissions to node - * - * @param int $a_node_id - * @return array - */ - public static function _getPermissions($a_node_id) - { - global $DIC; - - $ilDB = $DIC->database(); - $ilSetting = $DIC->settings(); - - $publish_enabled = $ilSetting->get("enable_global_profiles"); - $publish_perm = array(ilWorkspaceAccessGUI::PERMISSION_ALL, - ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD); - - $set = $ilDB->query("SELECT object_id FROM acl_ws". - " WHERE node_id = ".$ilDB->quote($a_node_id, "integer")); - $res = array(); - while($row = $ilDB->fetchAssoc($set)) - { - if($publish_enabled || !in_array($row["object_id"], $publish_perm)) - { - $res[] = $row["object_id"]; - } - } - return $res; - } - - public function hasRegisteredPermission($a_node_id) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT object_id FROM acl_ws". - " WHERE node_id = ".$ilDB->quote($a_node_id, "integer"). - " AND object_id = ".$ilDB->quote(ilWorkspaceAccessGUI::PERMISSION_REGISTERED, "integer")); - return (bool)$ilDB->numRows($set); - } - - public function hasGlobalPermission($a_node_id) - { - $ilDB = $this->db; - $ilSetting = $this->settings; - - if(!$ilSetting->get("enable_global_profiles")) - { - return false; - } - - $set = $ilDB->query("SELECT object_id FROM acl_ws". - " WHERE node_id = ".$ilDB->quote($a_node_id, "integer"). - " AND object_id = ".$ilDB->quote(ilWorkspaceAccessGUI::PERMISSION_ALL, "integer")); - return (bool)$ilDB->numRows($set); - } - - public function hasGlobalPasswordPermission($a_node_id) - { - $ilDB = $this->db; - $ilSetting = $this->settings; - - if(!$ilSetting->get("enable_global_profiles")) - { - return false; - } - - $set = $ilDB->query("SELECT object_id FROM acl_ws". - " WHERE node_id = ".$ilDB->quote($a_node_id, "integer"). - " AND object_id = ".$ilDB->quote(ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD, "integer")); - return (bool)$ilDB->numRows($set); - } - - public static function getPossibleSharedTargets() - { - global $DIC; - - $ilUser = $DIC->user(); - $ilSetting = $DIC->settings(); - - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessGUI.php"; - include_once "Services/Membership/classes/class.ilParticipants.php"; - $grp_ids = ilParticipants::_getMembershipByType($ilUser->getId(), "grp"); - $crs_ids = ilParticipants::_getMembershipByType($ilUser->getId(), "crs"); - - $obj_ids = array_merge($grp_ids, $crs_ids); - $obj_ids[] = $ilUser->getId(); - $obj_ids[] = ilWorkspaceAccessGUI::PERMISSION_REGISTERED; - - if($ilSetting->get("enable_global_profiles")) - { - $obj_ids[] = ilWorkspaceAccessGUI::PERMISSION_ALL; - $obj_ids[] = ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD; - } - - return $obj_ids; - } - - public function getSharedOwners() - { - $ilUser = $this->user; - $ilDB = $this->db; - - $obj_ids = $this->getPossibleSharedTargets(); - - $user_ids = array(); - $set = $ilDB->query("SELECT DISTINCT(obj.owner), u.lastname, u.firstname, u.title". - " FROM object_data obj". - " JOIN object_reference_ws ref ON (obj.obj_id = ref.obj_id)". - " JOIN tree_workspace tree ON (tree.child = ref.wsp_id)". - " JOIN acl_ws acl ON (acl.node_id = tree.child)". - " JOIN usr_data u on (u.usr_id = obj.owner)". - " WHERE ".$ilDB->in("acl.object_id", $obj_ids, "", "integer"). - " AND obj.owner <> ".$ilDB->quote($ilUser->getId(), "integer"). - " ORDER BY u.lastname, u.firstname, u.title"); - while ($row = $ilDB->fetchAssoc($set)) - { - $user_ids[$row["owner"]] = $row["lastname"].", ".$row["firstname"]; - if($row["title"]) - { - $user_ids[$row["owner"]] .= ", ".$row["title"]; - } - } - - return $user_ids; - } - - public function getSharedObjects($a_owner_id) - { - $ilDB = $this->db; - - $obj_ids = $this->getPossibleSharedTargets(); - - $res = array(); - $set = $ilDB->query("SELECT ref.wsp_id,obj.obj_id". - " FROM object_data obj". - " JOIN object_reference_ws ref ON (obj.obj_id = ref.obj_id)". - " JOIN tree_workspace tree ON (tree.child = ref.wsp_id)". - " JOIN acl_ws acl ON (acl.node_id = tree.child)". - " WHERE ".$ilDB->in("acl.object_id", $obj_ids, "", "integer"). - " AND obj.owner = ".$ilDB->quote($a_owner_id, "integer")); - while ($row = $ilDB->fetchAssoc($set)) - { - $res[$row["wsp_id"]] = $row["obj_id"]; - } - - return $res; - } - - public function findSharedObjects(array $a_filter = null, array $a_crs_ids = null, array $a_grp_ids = null) - { - $ilDB = $this->db; - $ilUser = $this->user; - - if(!$a_filter["acl_type"]) - { - $obj_ids = $this->getPossibleSharedTargets(); - } - else - { - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessGUI.php"; - - switch($a_filter["acl_type"]) - { - case "all": - $obj_ids = array(ilWorkspaceAccessGUI::PERMISSION_ALL); - break; - - case "password": - $obj_ids = array(ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD); - break; - - case "registered": - $obj_ids = array(ilWorkspaceAccessGUI::PERMISSION_REGISTERED); - break; - - case "course": - $obj_ids = $a_crs_ids; - break; - - case "group": - $obj_ids = $a_grp_ids; - break; - - case "user": - $obj_ids = array($ilUser->getId()); - break; - } - } - - $res = array(); - - $sql = "SELECT ref.wsp_id,obj.obj_id,obj.type,obj.title,obj.owner,". - "acl.object_id acl_type, acl.tstamp acl_date". - " FROM object_data obj". - " JOIN object_reference_ws ref ON (obj.obj_id = ref.obj_id)". - " JOIN tree_workspace tree ON (tree.child = ref.wsp_id)". - " JOIN acl_ws acl ON (acl.node_id = tree.child)". - " WHERE ".$ilDB->in("acl.object_id", $obj_ids, "", "integer"). - " AND obj.owner <> ".$ilDB->quote($ilUser->getId(), "integer"); - - if($a_filter["obj_type"]) - { - $sql .= " AND obj.type = ".$ilDB->quote($a_filter["obj_type"], "text"); - } - if($a_filter["title"] && strlen($a_filter["title"]) >= 3) - { - $sql .= " AND ".$ilDB->like("obj.title", "text", "%".$a_filter["title"]."%"); - } - if($a_filter["user"] && strlen($a_filter["user"]) >= 3) - { - $usr_ids = array(); - $set = $ilDB->query("SELECT usr_id FROM usr_data". - " WHERE (".$ilDB->like("login", "text", "%".$a_filter["user"]."%")." ". - "OR ".$ilDB->like("firstname", "text", "%".$a_filter["user"]."%")." ". - "OR ".$ilDB->like("lastname", "text", "%".$a_filter["user"]."%")." ". - "OR ".$ilDB->like("email", "text", "%".$a_filter["user"]."%").")"); - while($row = $ilDB->fetchAssoc($set)) - { - $usr_ids[] = $row["usr_id"]; - } - if(!sizeof($usr_ids)) - { - return; - } - $sql .= " AND ".$ilDB->in("obj.owner", $usr_ids, "", "integer"); - } - - if($a_filter["acl_date"]) - { - $dt = $a_filter["acl_date"]->get(IL_CAL_DATE); - $dt = new ilDateTime($dt." 00:00:00", IL_CAL_DATETIME); - $sql .= " AND acl.tstamp > ".$ilDB->quote($dt->get(IL_CAL_UNIX), "integer"); - } - - if($a_filter["crsgrp"]) - { - include_once "Services/Membership/classes/class.ilParticipants.php"; - $part = ilParticipants::getInstanceByObjId($a_filter['crsgrp']); - $part = $part->getParticipants(); - if(!sizeof($part)) - { - return; - } - $sql .= " AND ".$ilDB->in("obj.owner", $part, "", "integer"); - } - - // we use the oldest share date - $sql .= " ORDER BY acl.tstamp"; - - $set = $ilDB->query($sql); - while ($row = $ilDB->fetchAssoc($set)) - { - if(!isset($res[$row["wsp_id"]])) - { - $row["acl_type"] = array($row["acl_type"]); - $res[$row["wsp_id"]] = $row; - } - else - { - $res[$row["wsp_id"]]["acl_type"][] = $row["acl_type"]; - } - } - - return $res; - } - - public static function getSharedNodePassword($a_node_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessGUI.php"; - - $set = $ilDB->query("SELECT * FROM acl_ws". - " WHERE node_id = ".$ilDB->quote($a_node_id, "integer"). - " AND object_id = ".$ilDB->quote(ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD, "integer")); - $res = $ilDB->fetchAssoc($set); - if($res) - { - return $res["extended_data"]; - } - } - - public static function keepSharedSessionPassword($a_node_id, $a_password) - { - $_SESSION["ilshpw_".$a_node_id] = $a_password; - } - - public static function getSharedSessionPassword($a_node_id) - { - return $_SESSION["ilshpw_".$a_node_id]; - } - - public static function getGotoLink($a_node_id, $a_obj_id, $a_additional = null) - { - include_once('./Services/Link/classes/class.ilLink.php'); - return ilLink::_getStaticLink($a_node_id, ilObject::_lookupType($a_obj_id), true, $a_additional."_wsp"); - } - - public function getObjectsIShare() - { - $ilDB = $this->db; - $ilUser = $this->user; - - $res = array(); - $set = $ilDB->query("SELECT ref.wsp_id,obj.obj_id". - " FROM object_data obj". - " JOIN object_reference_ws ref ON (obj.obj_id = ref.obj_id)". - " JOIN tree_workspace tree ON (tree.child = ref.wsp_id)". - " JOIN acl_ws acl ON (acl.node_id = tree.child)". - " WHERE obj.owner = ".$ilDB->quote($ilUser->getId(), "integer")); - while ($row = $ilDB->fetchAssoc($set)) - { - $res[$row["wsp_id"]] = $row["obj_id"]; - } - - return $res; - } - - public static function getObjectDataFromNode($a_node_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT obj.obj_id, obj.type, obj.title". - " FROM object_reference_ws ref". - " JOIN tree_workspace tree ON (tree.child = ref.wsp_id)". - " JOIN object_data obj ON (ref.obj_id = obj.obj_id)". - " WHERE ref.wsp_id = ".$ilDB->quote($a_node_id, "integer")); - return $ilDB->fetchAssoc($set); - } + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilRbacReview + */ + protected $rbacreview; + + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var ilDB + */ + protected $db; + + protected $tree; // [ilTree] + + public function __construct(ilTree $a_tree = null) + { + global $DIC; + + $this->user = $DIC->user(); + $this->lng = $DIC->language(); + $this->rbacreview = $DIC->rbac()->review(); + $this->settings = $DIC->settings(); + $this->db = $DIC->database(); + $ilUser = $DIC->user(); + $lng = $DIC->language(); + + $lng->loadLanguageModule("wsp"); + + if (!$a_tree) { + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + $a_tree = new ilWorkspaceTree($ilUser->getId()); + } + $this->tree = $a_tree; + } + + /** + * Get workspace tree + * + * @return ilWorkspaceTree + */ + public function getTree() + { + return $this->tree; + } + + /** + * check access for an object + * + * @param string $a_permission + * @param string $a_cmd + * @param int $a_node_id + * @param string $a_type (optional) + * @return bool + */ + public function checkAccess($a_permission, $a_cmd, $a_node_id, $a_type = "") + { + $ilUser = $this->user; + + return $this->checkAccessOfUser($this->tree, $ilUser->getId(), $a_permission, $a_cmd, $a_node_id, $a_type); + } + + /** + * check access for an object + * + * @param ilTree $a_tree + * @param integer $a_user_id + * @param string $a_permission + * @param string $a_cmd + * @param int $a_node_id + * @param string $a_type (optional) + * @return bool + */ + public function checkAccessOfUser(ilTree $a_tree, $a_user_id, $a_permission, $a_cmd, $a_node_id, $a_type = "") + { + $rbacreview = $this->rbacreview; + $ilUser = $this->user; + $ilSetting = $this->settings; + + // :TODO: create permission for parent node with type ?! + + // #20310 + if (!$ilSetting->get("enable_global_profiles") && $ilUser->getId() == ANONYMOUS_USER_ID) { + return false; + } + + // tree root is read-only + if ($a_permission == "write") { + if ($a_tree->readRootId() == $a_node_id) { + return false; + } + } + + // node owner has all rights + if ($a_tree->lookupOwner($a_node_id) == $a_user_id) { + return true; + } + + // other users can only read + if ($a_permission == "read" || $a_permission == "visible") { + // get all objects with explicit permission + $objects = $this->getPermissions($a_node_id); + if ($objects) { + // check if given user is member of object or has role + foreach ($objects as $obj_id) { + switch ($obj_id) { + case ilWorkspaceAccessGUI::PERMISSION_ALL: + return true; + + case ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD: + // check against input kept in session + if (self::getSharedNodePassword($a_node_id) == self::getSharedSessionPassword($a_node_id) || + $a_permission == "visible") { + return true; + } + break; + + case ilWorkspaceAccessGUI::PERMISSION_REGISTERED: + if ($ilUser->getId() != ANONYMOUS_USER_ID) { + return true; + } + break; + + default: + switch (ilObject::_lookupType($obj_id)) { + case "grp": + // member of group? + if (ilGroupParticipants::_getInstanceByObjId($obj_id)->isAssigned($a_user_id)) { + return true; + } + break; + + case "crs": + // member of course? + if (ilCourseParticipants::_getInstanceByObjId($obj_id)->isAssigned($a_user_id)) { + return true; + } + break; + + case "role": + // has role? + if ($rbacreview->isAssigned($a_user_id, $obj_id)) { + return true; + } + break; + + case "usr": + // direct assignment + if ($a_user_id == $obj_id) { + return true; + } + break; + } + break; + } + } + } + } + + return false; + } + + /** + * Set permissions after creating node/object + * + * @param int $a_parent_node_id + * @param int $a_node_id + */ + public function setPermissions($a_parent_node_id, $a_node_id) + { + // nothing to do as owner has irrefutable rights to any workspace object + } + + /** + * Add permission to node for object + * + * @param int $a_node_id + * @param int $a_object_id + * @param string $a_extended_data + * @return bool + */ + public function addPermission($a_node_id, $a_object_id, $a_extended_data = null) + { + $ilDB = $this->db; + $ilUser = $this->user; + + // tree owner must not be added + if ($this->tree->getTreeId() == $ilUser->getId() && + $a_object_id == $ilUser->getId()) { + return false; + } + + $ilDB->manipulate("INSERT INTO acl_ws (node_id, object_id, extended_data, tstamp)" . + " VALUES (" . $ilDB->quote($a_node_id, "integer") . ", " . + $ilDB->quote($a_object_id, "integer") . "," . + $ilDB->quote($a_extended_data, "text") . "," . + $ilDB->quote(time(), "integer") . ")"); + return true; + } + + /** + * Remove permission[s] (for object) to node + * + * @param int $a_node_id + * @param int $a_object_id + */ + public function removePermission($a_node_id, $a_object_id = null) + { + $ilDB = $this->db; + + $query = "DELETE FROM acl_ws" . + " WHERE node_id = " . $ilDB->quote($a_node_id, "integer"); + + if ($a_object_id) { + $query .= " AND object_id = " . $ilDB->quote($a_object_id, "integer"); + } + + return $ilDB->manipulate($query); + } + + /** + * Get all permissions to node + * + * @param int $a_node_id + * @return array + */ + public function getPermissions($a_node_id) + { + return self::_getPermissions($a_node_id); + } + + /** + * Get all permissions to node + * + * @param int $a_node_id + * @return array + */ + public static function _getPermissions($a_node_id) + { + global $DIC; + + $ilDB = $DIC->database(); + $ilSetting = $DIC->settings(); + + $publish_enabled = $ilSetting->get("enable_global_profiles"); + $publish_perm = array(ilWorkspaceAccessGUI::PERMISSION_ALL, + ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD); + + $set = $ilDB->query("SELECT object_id FROM acl_ws" . + " WHERE node_id = " . $ilDB->quote($a_node_id, "integer")); + $res = array(); + while ($row = $ilDB->fetchAssoc($set)) { + if ($publish_enabled || !in_array($row["object_id"], $publish_perm)) { + $res[] = $row["object_id"]; + } + } + return $res; + } + + public function hasRegisteredPermission($a_node_id) + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT object_id FROM acl_ws" . + " WHERE node_id = " . $ilDB->quote($a_node_id, "integer") . + " AND object_id = " . $ilDB->quote(ilWorkspaceAccessGUI::PERMISSION_REGISTERED, "integer")); + return (bool) $ilDB->numRows($set); + } + + public function hasGlobalPermission($a_node_id) + { + $ilDB = $this->db; + $ilSetting = $this->settings; + + if (!$ilSetting->get("enable_global_profiles")) { + return false; + } + + $set = $ilDB->query("SELECT object_id FROM acl_ws" . + " WHERE node_id = " . $ilDB->quote($a_node_id, "integer") . + " AND object_id = " . $ilDB->quote(ilWorkspaceAccessGUI::PERMISSION_ALL, "integer")); + return (bool) $ilDB->numRows($set); + } + + public function hasGlobalPasswordPermission($a_node_id) + { + $ilDB = $this->db; + $ilSetting = $this->settings; + + if (!$ilSetting->get("enable_global_profiles")) { + return false; + } + + $set = $ilDB->query("SELECT object_id FROM acl_ws" . + " WHERE node_id = " . $ilDB->quote($a_node_id, "integer") . + " AND object_id = " . $ilDB->quote(ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD, "integer")); + return (bool) $ilDB->numRows($set); + } + + public static function getPossibleSharedTargets() + { + global $DIC; + + $ilUser = $DIC->user(); + $ilSetting = $DIC->settings(); + + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessGUI.php"; + include_once "Services/Membership/classes/class.ilParticipants.php"; + $grp_ids = ilParticipants::_getMembershipByType($ilUser->getId(), "grp"); + $crs_ids = ilParticipants::_getMembershipByType($ilUser->getId(), "crs"); + + $obj_ids = array_merge($grp_ids, $crs_ids); + $obj_ids[] = $ilUser->getId(); + $obj_ids[] = ilWorkspaceAccessGUI::PERMISSION_REGISTERED; + + if ($ilSetting->get("enable_global_profiles")) { + $obj_ids[] = ilWorkspaceAccessGUI::PERMISSION_ALL; + $obj_ids[] = ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD; + } + + return $obj_ids; + } + + public function getSharedOwners() + { + $ilUser = $this->user; + $ilDB = $this->db; + + $obj_ids = $this->getPossibleSharedTargets(); + + $user_ids = array(); + $set = $ilDB->query("SELECT DISTINCT(obj.owner), u.lastname, u.firstname, u.title" . + " FROM object_data obj" . + " JOIN object_reference_ws ref ON (obj.obj_id = ref.obj_id)" . + " JOIN tree_workspace tree ON (tree.child = ref.wsp_id)" . + " JOIN acl_ws acl ON (acl.node_id = tree.child)" . + " JOIN usr_data u on (u.usr_id = obj.owner)" . + " WHERE " . $ilDB->in("acl.object_id", $obj_ids, "", "integer") . + " AND obj.owner <> " . $ilDB->quote($ilUser->getId(), "integer") . + " ORDER BY u.lastname, u.firstname, u.title"); + while ($row = $ilDB->fetchAssoc($set)) { + $user_ids[$row["owner"]] = $row["lastname"] . ", " . $row["firstname"]; + if ($row["title"]) { + $user_ids[$row["owner"]] .= ", " . $row["title"]; + } + } + + return $user_ids; + } + + public function getSharedObjects($a_owner_id) + { + $ilDB = $this->db; + + $obj_ids = $this->getPossibleSharedTargets(); + + $res = array(); + $set = $ilDB->query("SELECT ref.wsp_id,obj.obj_id" . + " FROM object_data obj" . + " JOIN object_reference_ws ref ON (obj.obj_id = ref.obj_id)" . + " JOIN tree_workspace tree ON (tree.child = ref.wsp_id)" . + " JOIN acl_ws acl ON (acl.node_id = tree.child)" . + " WHERE " . $ilDB->in("acl.object_id", $obj_ids, "", "integer") . + " AND obj.owner = " . $ilDB->quote($a_owner_id, "integer")); + while ($row = $ilDB->fetchAssoc($set)) { + $res[$row["wsp_id"]] = $row["obj_id"]; + } + + return $res; + } + + public function findSharedObjects(array $a_filter = null, array $a_crs_ids = null, array $a_grp_ids = null) + { + $ilDB = $this->db; + $ilUser = $this->user; + + if (!$a_filter["acl_type"]) { + $obj_ids = $this->getPossibleSharedTargets(); + } else { + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessGUI.php"; + + switch ($a_filter["acl_type"]) { + case "all": + $obj_ids = array(ilWorkspaceAccessGUI::PERMISSION_ALL); + break; + + case "password": + $obj_ids = array(ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD); + break; + + case "registered": + $obj_ids = array(ilWorkspaceAccessGUI::PERMISSION_REGISTERED); + break; + + case "course": + $obj_ids = $a_crs_ids; + break; + + case "group": + $obj_ids = $a_grp_ids; + break; + + case "user": + $obj_ids = array($ilUser->getId()); + break; + } + } + + $res = array(); + + $sql = "SELECT ref.wsp_id,obj.obj_id,obj.type,obj.title,obj.owner," . + "acl.object_id acl_type, acl.tstamp acl_date" . + " FROM object_data obj" . + " JOIN object_reference_ws ref ON (obj.obj_id = ref.obj_id)" . + " JOIN tree_workspace tree ON (tree.child = ref.wsp_id)" . + " JOIN acl_ws acl ON (acl.node_id = tree.child)" . + " WHERE " . $ilDB->in("acl.object_id", $obj_ids, "", "integer") . + " AND obj.owner <> " . $ilDB->quote($ilUser->getId(), "integer"); + + if ($a_filter["obj_type"]) { + $sql .= " AND obj.type = " . $ilDB->quote($a_filter["obj_type"], "text"); + } + if ($a_filter["title"] && strlen($a_filter["title"]) >= 3) { + $sql .= " AND " . $ilDB->like("obj.title", "text", "%" . $a_filter["title"] . "%"); + } + if ($a_filter["user"] && strlen($a_filter["user"]) >= 3) { + $usr_ids = array(); + $set = $ilDB->query("SELECT usr_id FROM usr_data" . + " WHERE (" . $ilDB->like("login", "text", "%" . $a_filter["user"] . "%") . " " . + "OR " . $ilDB->like("firstname", "text", "%" . $a_filter["user"] . "%") . " " . + "OR " . $ilDB->like("lastname", "text", "%" . $a_filter["user"] . "%") . " " . + "OR " . $ilDB->like("email", "text", "%" . $a_filter["user"] . "%") . ")"); + while ($row = $ilDB->fetchAssoc($set)) { + $usr_ids[] = $row["usr_id"]; + } + if (!sizeof($usr_ids)) { + return; + } + $sql .= " AND " . $ilDB->in("obj.owner", $usr_ids, "", "integer"); + } + + if ($a_filter["acl_date"]) { + $dt = $a_filter["acl_date"]->get(IL_CAL_DATE); + $dt = new ilDateTime($dt . " 00:00:00", IL_CAL_DATETIME); + $sql .= " AND acl.tstamp > " . $ilDB->quote($dt->get(IL_CAL_UNIX), "integer"); + } + + if ($a_filter["crsgrp"]) { + include_once "Services/Membership/classes/class.ilParticipants.php"; + $part = ilParticipants::getInstanceByObjId($a_filter['crsgrp']); + $part = $part->getParticipants(); + if (!sizeof($part)) { + return; + } + $sql .= " AND " . $ilDB->in("obj.owner", $part, "", "integer"); + } + + // we use the oldest share date + $sql .= " ORDER BY acl.tstamp"; + + $set = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($set)) { + if (!isset($res[$row["wsp_id"]])) { + $row["acl_type"] = array($row["acl_type"]); + $res[$row["wsp_id"]] = $row; + } else { + $res[$row["wsp_id"]]["acl_type"][] = $row["acl_type"]; + } + } + + return $res; + } + + public static function getSharedNodePassword($a_node_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessGUI.php"; + + $set = $ilDB->query("SELECT * FROM acl_ws" . + " WHERE node_id = " . $ilDB->quote($a_node_id, "integer") . + " AND object_id = " . $ilDB->quote(ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD, "integer")); + $res = $ilDB->fetchAssoc($set); + if ($res) { + return $res["extended_data"]; + } + } + + public static function keepSharedSessionPassword($a_node_id, $a_password) + { + $_SESSION["ilshpw_" . $a_node_id] = $a_password; + } + + public static function getSharedSessionPassword($a_node_id) + { + return $_SESSION["ilshpw_" . $a_node_id]; + } + + public static function getGotoLink($a_node_id, $a_obj_id, $a_additional = null) + { + include_once('./Services/Link/classes/class.ilLink.php'); + return ilLink::_getStaticLink($a_node_id, ilObject::_lookupType($a_obj_id), true, $a_additional . "_wsp"); + } + + public function getObjectsIShare() + { + $ilDB = $this->db; + $ilUser = $this->user; + + $res = array(); + $set = $ilDB->query("SELECT ref.wsp_id,obj.obj_id" . + " FROM object_data obj" . + " JOIN object_reference_ws ref ON (obj.obj_id = ref.obj_id)" . + " JOIN tree_workspace tree ON (tree.child = ref.wsp_id)" . + " JOIN acl_ws acl ON (acl.node_id = tree.child)" . + " WHERE obj.owner = " . $ilDB->quote($ilUser->getId(), "integer")); + while ($row = $ilDB->fetchAssoc($set)) { + $res[$row["wsp_id"]] = $row["obj_id"]; + } + + return $res; + } + + public static function getObjectDataFromNode($a_node_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query("SELECT obj.obj_id, obj.type, obj.title" . + " FROM object_reference_ws ref" . + " JOIN tree_workspace tree ON (tree.child = ref.wsp_id)" . + " JOIN object_data obj ON (ref.obj_id = obj.obj_id)" . + " WHERE ref.wsp_id = " . $ilDB->quote($a_node_id, "integer")); + return $ilDB->fetchAssoc($set); + } } - -?> \ No newline at end of file diff --git a/Services/PersonalWorkspace/classes/class.ilWorkspaceAccessTableGUI.php b/Services/PersonalWorkspace/classes/class.ilWorkspaceAccessTableGUI.php index 636e815215d81879f60d036e903afd9ef3bca1a6..64bbf8c7a244ef287af3fb8b358f0d4542305ee2 100644 --- a/Services/PersonalWorkspace/classes/class.ilWorkspaceAccessTableGUI.php +++ b/Services/PersonalWorkspace/classes/class.ilWorkspaceAccessTableGUI.php @@ -1,146 +1,138 @@ - - * @version $Id: class.adnCountryTableGUI.php 27876 2011-02-25 16:51:38Z jluetzen $ - * - * @ingroup ServicesPersonalWorkspace - */ -class ilWorkspaceAccessTableGUI extends ilTable2GUI -{ - /** - * @var ilCtrl - */ - protected $ctrl; +ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->node_id = $a_node_id; - $this->handler = $a_handler; - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setId("il_tbl_wsacl"); - - $this->setTitle($lng->txt("wsp_shared_table_title")); - - $this->addColumn($this->lng->txt("wsp_shared_with"), "title"); - $this->addColumn($this->lng->txt("details"), "type"); - $this->addColumn($this->lng->txt("actions")); - - $this->setDefaultOrderField("title"); - $this->setDefaultOrderDirection("asc"); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.access_row.html", "Services/PersonalWorkspace"); - - $this->importData(); - } - - /** - * Import data from DB - */ - protected function importData() - { - include_once("./Services/User/classes/class.ilUserUtil.php"); - - $data = array(); - foreach($this->handler->getPermissions($this->node_id) as $obj_id) - { - // title is needed for proper sorting - // special modes should always be on top! - $title = null; - - switch($obj_id) - { - case ilWorkspaceAccessGUI::PERMISSION_REGISTERED: - $caption = $this->lng->txt("wsp_set_permission_registered"); - $title = "0".$caption; - break; - - case ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD: - $caption = $this->lng->txt("wsp_set_permission_all_password"); - $title = "0".$caption; - break; - - case ilWorkspaceAccessGUI::PERMISSION_ALL: - $caption = $this->lng->txt("wsp_set_permission_all"); - $title = "0".$caption; - break; - - default: - $type = ilObject::_lookupType($obj_id); - $type_txt = $this->lng->txt("obj_".$type); - - if($type === null) - { - // invalid object/user - } - else if($type != "usr") - { - $title = $caption = ilObject::_lookupTitle($obj_id); - } - else - { - $caption = ilUserUtil::getNamePresentation($obj_id, false, true); - $title = strip_tags($caption); - } - break; - } - - if($title) - { - $data[] = array("id" => $obj_id, - "title" => $title, - "caption" => $caption, - "type" => $type_txt); - } - } - - $this->setData($data); - } - - /** - * Fill table row - * - * @param array $a_set data array - */ - protected function fillRow($a_set) - { - $ilCtrl = $this->ctrl; - - // properties - $this->tpl->setVariable("TITLE", $a_set["caption"]); - $this->tpl->setVariable("TYPE", $a_set["type"]); - - $ilCtrl->setParameter($this->parent_obj, "obj_id", $a_set["id"]); - $this->tpl->setVariable("HREF_CMD", - $ilCtrl->getLinkTarget($this->parent_obj, "removePermission")); - $this->tpl->setVariable("TXT_CMD", $this->lng->txt("remove")); - } -} - -?> \ No newline at end of file +/** + * Workspace access handler table GUI class + * + * @author Jörg Lützenkirchen + * @version $Id: class.adnCountryTableGUI.php 27876 2011-02-25 16:51:38Z jluetzen $ + * + * @ingroup ServicesPersonalWorkspace + */ +class ilWorkspaceAccessTableGUI extends ilTable2GUI +{ + /** + * @var ilCtrl + */ + protected $ctrl; + + protected $node_id; // [int] + protected $handler; // [ilWorkspaceAccessHandler] + + /** + * Constructor + * + * @param object $a_parent_obj parent gui object + * @param string $a_parent_cmd parent default command + * @param int $a_node_id current workspace object + * @param object $a_handler workspace access handler + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_node_id, $a_handler) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->node_id = $a_node_id; + $this->handler = $a_handler; + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setId("il_tbl_wsacl"); + + $this->setTitle($lng->txt("wsp_shared_table_title")); + + $this->addColumn($this->lng->txt("wsp_shared_with"), "title"); + $this->addColumn($this->lng->txt("details"), "type"); + $this->addColumn($this->lng->txt("actions")); + + $this->setDefaultOrderField("title"); + $this->setDefaultOrderDirection("asc"); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.access_row.html", "Services/PersonalWorkspace"); + + $this->importData(); + } + + /** + * Import data from DB + */ + protected function importData() + { + include_once("./Services/User/classes/class.ilUserUtil.php"); + + $data = array(); + foreach ($this->handler->getPermissions($this->node_id) as $obj_id) { + // title is needed for proper sorting + // special modes should always be on top! + $title = null; + + switch ($obj_id) { + case ilWorkspaceAccessGUI::PERMISSION_REGISTERED: + $caption = $this->lng->txt("wsp_set_permission_registered"); + $title = "0" . $caption; + break; + + case ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD: + $caption = $this->lng->txt("wsp_set_permission_all_password"); + $title = "0" . $caption; + break; + + case ilWorkspaceAccessGUI::PERMISSION_ALL: + $caption = $this->lng->txt("wsp_set_permission_all"); + $title = "0" . $caption; + break; + + default: + $type = ilObject::_lookupType($obj_id); + $type_txt = $this->lng->txt("obj_" . $type); + + if ($type === null) { + // invalid object/user + } elseif ($type != "usr") { + $title = $caption = ilObject::_lookupTitle($obj_id); + } else { + $caption = ilUserUtil::getNamePresentation($obj_id, false, true); + $title = strip_tags($caption); + } + break; + } + + if ($title) { + $data[] = array("id" => $obj_id, + "title" => $title, + "caption" => $caption, + "type" => $type_txt); + } + } + + $this->setData($data); + } + + /** + * Fill table row + * + * @param array $a_set data array + */ + protected function fillRow($a_set) + { + $ilCtrl = $this->ctrl; + + // properties + $this->tpl->setVariable("TITLE", $a_set["caption"]); + $this->tpl->setVariable("TYPE", $a_set["type"]); + + $ilCtrl->setParameter($this->parent_obj, "obj_id", $a_set["id"]); + $this->tpl->setVariable( + "HREF_CMD", + $ilCtrl->getLinkTarget($this->parent_obj, "removePermission") + ); + $this->tpl->setVariable("TXT_CMD", $this->lng->txt("remove")); + } +} diff --git a/Services/PersonalWorkspace/classes/class.ilWorkspaceExplorer.php b/Services/PersonalWorkspace/classes/class.ilWorkspaceExplorer.php index 438b5eaebc72239ac9c968abcadbed323278fb26..225ab5b58d6d99f5e3cbefad48e8ef19b6d7e47f 100644 --- a/Services/PersonalWorkspace/classes/class.ilWorkspaceExplorer.php +++ b/Services/PersonalWorkspace/classes/class.ilWorkspaceExplorer.php @@ -11,322 +11,311 @@ require_once 'Services/Repository/classes/class.ilRepositoryExplorer.php'; */ class ilWorkspaceExplorer extends ilRepositoryExplorer { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - const SEL_TYPE_CHECK = 1; - const SEL_TYPE_RADIO = 2; - - public $root_id = 0; - public $output = ''; - public $ctrl = null; - public $access = null; - - private $checked_items = array(); - private $post_var = ''; - private $form_items = array(); - private $type = 0; - - protected $clickable = array(); - protected $custom_link_target; - - /** - * Constructor - * @access public - * @param string $a_target scriptname - * @param string $a_session_variable session_variable - * @param ilWorkspaceTree $a_tree workspace tree - * @param ilWorkspaceAccessHandler $a_access_handler workspace access handler - * @deprecated use class ilWorkspaceExplorerGUI instead - */ - public function __construct($a_type, $a_target, $a_session_variable, ilWorkspaceTree $a_tree, ilWorkspaceAccessHandler $a_access_handler) - { - global $DIC; + const SEL_TYPE_CHECK = 1; + const SEL_TYPE_RADIO = 2; + + public $root_id = 0; + public $output = ''; + public $ctrl = null; + public $access = null; + + private $checked_items = array(); + private $post_var = ''; + private $form_items = array(); + private $type = 0; + + protected $clickable = array(); + protected $custom_link_target; + + /** + * Constructor + * @access public + * @param string $a_target scriptname + * @param string $a_session_variable session_variable + * @param ilWorkspaceTree $a_tree workspace tree + * @param ilWorkspaceAccessHandler $a_access_handler workspace access handler + * @deprecated use class ilWorkspaceExplorerGUI instead + */ + public function __construct($a_type, $a_target, $a_session_variable, ilWorkspaceTree $a_tree, ilWorkspaceAccessHandler $a_access_handler) + { + global $DIC; - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); - $this->ctrl = $ilCtrl; - $this->type = $a_type; - $this->access = $a_access_handler; + $this->ctrl = $ilCtrl; + $this->type = $a_type; + $this->access = $a_access_handler; - parent::__construct($a_target); - - // #11173 - if(!$a_tree->readRootId()) - { - // create (workspace) root folder - $root = ilObjectFactory::getClassByType("wsrt"); - $root = new $root(null); - $root->create(); + parent::__construct($a_target); + + // #11173 + if (!$a_tree->readRootId()) { + // create (workspace) root folder + $root = ilObjectFactory::getClassByType("wsrt"); + $root = new $root(null); + $root->create(); - $root_id = $a_tree->createReference($root->getId()); - $a_tree->addTree($a_tree->getTreeId(), $root_id); - $a_tree->setRootId($root_id); - } - $this->tree = $a_tree; - $this->root_id = $this->tree->readRootId(); - $this->order_column = 'title'; - $this->setSessionExpandVariable($a_session_variable); - - // reset filter - $this->filter = array(); - - $this->addFilter('wsrt'); - $this->addFilter('wfld'); - - $this->addFormItemForType('wsrt'); - $this->addFormItemForType('wfld'); - - $this->setFiltered(true); - $this->setFilterMode(IL_FM_POSITIVE); - } + $root_id = $a_tree->createReference($root->getId()); + $a_tree->addTree($a_tree->getTreeId(), $root_id); + $a_tree->setRootId($root_id); + } + $this->tree = $a_tree; + $this->root_id = $this->tree->readRootId(); + $this->order_column = 'title'; + $this->setSessionExpandVariable($a_session_variable); + + // reset filter + $this->filter = array(); + + $this->addFilter('wsrt'); + $this->addFilter('wfld'); + + $this->addFormItemForType('wsrt'); + $this->addFormItemForType('wfld'); + + $this->setFiltered(true); + $this->setFilterMode(IL_FM_POSITIVE); + } - public function showChilds($a_ref_id, $a_obj_id = 0) - { - if ($a_ref_id == 0 || - $this->access->checkAccess('read', '', $a_ref_id)) - { - return true; - } - return false; - } - - public function isVisible($a_ref_id,$a_type) - { - return true; - } + public function showChilds($a_ref_id, $a_obj_id = 0) + { + if ($a_ref_id == 0 || + $this->access->checkAccess('read', '', $a_ref_id)) { + return true; + } + return false; + } + + public function isVisible($a_ref_id, $a_type) + { + return true; + } - public function sortNodes($a_nodes,$a_parent_obj_id) - { - return $a_nodes; - } - - public function isClickable($a_type, $a_ref_id = 0, $a_obj_id = 0) - { - if(is_array($this->clickable) && in_array($a_type, $this->clickable) && - $a_ref_id) - { - return true; - } - return false; - } - - public function addFormItemForType($type) - { - $this->form_items[$type] = true; - } - public function removeFormItemForType($type) - { - $this->form_items[$type] = false; - } - public function removeAllFormItemTypes() - { - $this->form_items = array(); - } - public function setCheckedItems($a_checked_items = array()) - { - $this->checked_items = $a_checked_items; - } - public function isItemChecked($a_id) - { - return in_array($a_id, $this->checked_items) ? true : false; - } - public function setPostVar($a_post_var) - { - $this->post_var = $a_post_var; - } - public function getPostVar() - { - return $this->post_var; - } - - public function buildFormItem($a_node_id, $a_type) - { - if(!array_key_exists($a_type, $this->form_items) || !$this->form_items[$a_type]) - { - return; - } + public function sortNodes($a_nodes, $a_parent_obj_id) + { + return $a_nodes; + } + + public function isClickable($a_type, $a_ref_id = 0, $a_obj_id = 0) + { + if (is_array($this->clickable) && in_array($a_type, $this->clickable) && + $a_ref_id) { + return true; + } + return false; + } + + public function addFormItemForType($type) + { + $this->form_items[$type] = true; + } + public function removeFormItemForType($type) + { + $this->form_items[$type] = false; + } + public function removeAllFormItemTypes() + { + $this->form_items = array(); + } + public function setCheckedItems($a_checked_items = array()) + { + $this->checked_items = $a_checked_items; + } + public function isItemChecked($a_id) + { + return in_array($a_id, $this->checked_items) ? true : false; + } + public function setPostVar($a_post_var) + { + $this->post_var = $a_post_var; + } + public function getPostVar() + { + return $this->post_var; + } + + public function buildFormItem($a_node_id, $a_type) + { + if (!array_key_exists($a_type, $this->form_items) || !$this->form_items[$a_type]) { + return; + } - switch($this->type) - { - case self::SEL_TYPE_CHECK: - return ilUtil::formCheckbox((int)$this->isItemChecked($a_node_id), $this->post_var, $a_node_id); - - case self::SEL_TYPE_RADIO: - return ilUtil::formRadioButton((int)$this->isItemChecked($a_node_id), $this->post_var, $a_node_id); - } - } - - function formatObject($tpl, $a_node_id, $a_option, $a_obj_id = 0) - { - $lng = $this->lng; - - if (!isset($a_node_id) or !is_array($a_option)) - { - require_once './Services/Exceptions/classes/class.ilException.php'; - throw new ilException("Missing parameter or wrong datatype! ". - "node_id: ".$a_node_id." options:".var_dump($a_option)); - } + switch ($this->type) { + case self::SEL_TYPE_CHECK: + return ilUtil::formCheckbox((int) $this->isItemChecked($a_node_id), $this->post_var, $a_node_id); + + case self::SEL_TYPE_RADIO: + return ilUtil::formRadioButton((int) $this->isItemChecked($a_node_id), $this->post_var, $a_node_id); + } + } + + public function formatObject($tpl, $a_node_id, $a_option, $a_obj_id = 0) + { + $lng = $this->lng; + + if (!isset($a_node_id) or !is_array($a_option)) { + require_once './Services/Exceptions/classes/class.ilException.php'; + throw new ilException("Missing parameter or wrong datatype! " . + "node_id: " . $a_node_id . " options:" . var_dump($a_option)); + } - $pic = false; - foreach ($a_option["tab"] as $picture) - { - if ($picture == 'plus') - { - $tpl->setCurrentBlock("expander"); - $tpl->setVariable("EXP_DESC", $lng->txt("expand")); - $target = $this->createTarget('+',$a_node_id); - $tpl->setVariable("LINK_NAME", $a_node_id); - $tpl->setVariable("LINK_TARGET_EXPANDER", $target); - $tpl->setVariable("IMGPATH", $this->getImage("browser/plus.png")); - $tpl->parseCurrentBlock(); - $pic = true; - } + $pic = false; + foreach ($a_option["tab"] as $picture) { + if ($picture == 'plus') { + $tpl->setCurrentBlock("expander"); + $tpl->setVariable("EXP_DESC", $lng->txt("expand")); + $target = $this->createTarget('+', $a_node_id); + $tpl->setVariable("LINK_NAME", $a_node_id); + $tpl->setVariable("LINK_TARGET_EXPANDER", $target); + $tpl->setVariable("IMGPATH", $this->getImage("browser/plus.png")); + $tpl->parseCurrentBlock(); + $pic = true; + } - if ($picture == 'minus' && $this->show_minus) - { - $tpl->setCurrentBlock("expander"); - $tpl->setVariable("EXP_DESC", $lng->txt("collapse")); - $target = $this->createTarget('-',$a_node_id); - $tpl->setVariable("LINK_NAME", $a_node_id); - $tpl->setVariable("LINK_TARGET_EXPANDER", $target); - $tpl->setVariable("IMGPATH", $this->getImage("browser/minus.png")); - $tpl->parseCurrentBlock(); - $pic = true; - } - } - - if (!$pic) - { - $tpl->setCurrentBlock("blank"); - $tpl->setVariable("BLANK_PATH", $this->getImage("browser/blank.png")); - $tpl->parseCurrentBlock(); - } + if ($picture == 'minus' && $this->show_minus) { + $tpl->setCurrentBlock("expander"); + $tpl->setVariable("EXP_DESC", $lng->txt("collapse")); + $target = $this->createTarget('-', $a_node_id); + $tpl->setVariable("LINK_NAME", $a_node_id); + $tpl->setVariable("LINK_TARGET_EXPANDER", $target); + $tpl->setVariable("IMGPATH", $this->getImage("browser/minus.png")); + $tpl->parseCurrentBlock(); + $pic = true; + } + } + + if (!$pic) { + $tpl->setCurrentBlock("blank"); + $tpl->setVariable("BLANK_PATH", $this->getImage("browser/blank.png")); + $tpl->parseCurrentBlock(); + } - if ($this->output_icons) - { - $tpl->setCurrentBlock("icon"); - $tpl->setVariable("ICON_IMAGE" , $this->getImage("icon_".$a_option["type"].".svg", $a_option["type"], $a_obj_id)); - - $tpl->setVariable("TARGET_ID" , "iconid_".$a_node_id); - $this->iconList[] = "iconid_".$a_node_id; - $tpl->setVariable("TXT_ALT_IMG", $lng->txt($a_option["desc"])); - $tpl->parseCurrentBlock(); - } - - if(strlen($formItem = $this->buildFormItem($a_node_id, $a_option['type']))) - { - $tpl->setCurrentBlock('check'); - $tpl->setVariable('OBJ_CHECK', $formItem); - $tpl->parseCurrentBlock(); - } + if ($this->output_icons) { + $tpl->setCurrentBlock("icon"); + $tpl->setVariable("ICON_IMAGE", $this->getImage("icon_" . $a_option["type"] . ".svg", $a_option["type"], $a_obj_id)); + + $tpl->setVariable("TARGET_ID", "iconid_" . $a_node_id); + $this->iconList[] = "iconid_" . $a_node_id; + $tpl->setVariable("TXT_ALT_IMG", $lng->txt($a_option["desc"])); + $tpl->parseCurrentBlock(); + } + + if (strlen($formItem = $this->buildFormItem($a_node_id, $a_option['type']))) { + $tpl->setCurrentBlock('check'); + $tpl->setVariable('OBJ_CHECK', $formItem); + $tpl->parseCurrentBlock(); + } - if ($this->isClickable($a_option["type"], $a_node_id,$a_obj_id)) // output link - { - $tpl->setCurrentBlock("link"); - //$target = (strpos($this->target, "?") === false) ? - // $this->target."?" : $this->target."&"; - //$tpl->setVariable("LINK_TARGET", $target.$this->target_get."=".$a_node_id.$this->params_get); - $tpl->setVariable("LINK_TARGET", $this->buildLinkTarget($a_node_id, $a_option["type"])); - - $style_class = $this->getNodeStyleClass($a_node_id, $a_option["type"]); - - if ($style_class != "") - { - $tpl->setVariable("A_CLASS", ' class="'.$style_class.'" ' ); - } + if ($this->isClickable($a_option["type"], $a_node_id, $a_obj_id)) { // output link + $tpl->setCurrentBlock("link"); + //$target = (strpos($this->target, "?") === false) ? + // $this->target."?" : $this->target."&"; + //$tpl->setVariable("LINK_TARGET", $target.$this->target_get."=".$a_node_id.$this->params_get); + $tpl->setVariable("LINK_TARGET", $this->buildLinkTarget($a_node_id, $a_option["type"])); + + $style_class = $this->getNodeStyleClass($a_node_id, $a_option["type"]); + + if ($style_class != "") { + $tpl->setVariable("A_CLASS", ' class="' . $style_class . '" '); + } - if (($onclick = $this->buildOnClick($a_node_id, $a_option["type"], $a_option["title"])) != "") - { - $tpl->setVariable("ONCLICK", "onClick=\"$onclick\""); - } + if (($onclick = $this->buildOnClick($a_node_id, $a_option["type"], $a_option["title"])) != "") { + $tpl->setVariable("ONCLICK", "onClick=\"$onclick\""); + } - $tpl->setVariable("LINK_NAME", $a_node_id); - $tpl->setVariable("TITLE", ilUtil::shortenText( - $this->buildTitle($a_option["title"], $a_node_id, $a_option["type"]), - $this->textwidth, true)); - $tpl->setVariable("DESC", ilUtil::shortenText( - $this->buildDescription($a_option["description"], $a_node_id, $a_option["type"]), $this->textwidth, true)); - $frame_target = $this->buildFrameTarget($a_option["type"], $a_node_id, $a_option["obj_id"]); - if ($frame_target != "") - { - $tpl->setVariable("TARGET", " target=\"".$frame_target."\""); - } - $tpl->parseCurrentBlock(); - } - else // output text only - { - $tpl->setCurrentBlock("text"); - $tpl->setVariable("OBJ_TITLE", ilUtil::shortenText( - $this->buildTitle($a_option["title"], $a_node_id, $a_option["type"]), $this->textwidth, true)); - $tpl->setVariable("OBJ_DESC", ilUtil::shortenText( - $this->buildDescription($a_option["desc"], $a_node_id, $a_option["type"]), $this->textwidth, true)); - $tpl->parseCurrentBlock(); - } + $tpl->setVariable("LINK_NAME", $a_node_id); + $tpl->setVariable("TITLE", ilUtil::shortenText( + $this->buildTitle($a_option["title"], $a_node_id, $a_option["type"]), + $this->textwidth, + true + )); + $tpl->setVariable("DESC", ilUtil::shortenText( + $this->buildDescription($a_option["description"], $a_node_id, $a_option["type"]), + $this->textwidth, + true + )); + $frame_target = $this->buildFrameTarget($a_option["type"], $a_node_id, $a_option["obj_id"]); + if ($frame_target != "") { + $tpl->setVariable("TARGET", " target=\"" . $frame_target . "\""); + } + $tpl->parseCurrentBlock(); + } else { // output text only + $tpl->setCurrentBlock("text"); + $tpl->setVariable("OBJ_TITLE", ilUtil::shortenText( + $this->buildTitle($a_option["title"], $a_node_id, $a_option["type"]), + $this->textwidth, + true + )); + $tpl->setVariable("OBJ_DESC", ilUtil::shortenText( + $this->buildDescription($a_option["desc"], $a_node_id, $a_option["type"]), + $this->textwidth, + true + )); + $tpl->parseCurrentBlock(); + } - $tpl->setCurrentBlock("list_item"); - $tpl->parseCurrentBlock(); - $tpl->touchBlock("element"); - } - - /* - * overwritten method from base class - * @access public - * @param integer obj_id - * @param integer array options - * @return string - */ - function formatHeader($tpl, $a_obj_id,$a_option) - { - $lng = $this->lng; - - // custom icons - $path = ilObject::_getIcon($a_obj_id, "small", "wsrt"); + $tpl->setCurrentBlock("list_item"); + $tpl->parseCurrentBlock(); + $tpl->touchBlock("element"); + } + + /* + * overwritten method from base class + * @access public + * @param integer obj_id + * @param integer array options + * @return string + */ + public function formatHeader($tpl, $a_obj_id, $a_option) + { + $lng = $this->lng; + + // custom icons + $path = ilObject::_getIcon($a_obj_id, "small", "wsrt"); - $tpl->setCurrentBlock("icon"); - $title = $this->tree->getNodeData($this->root_id); - $title = $title["title"]; - if(!$title) - { - $title = $lng->txt("personal_workspace"); - } + $tpl->setCurrentBlock("icon"); + $title = $this->tree->getNodeData($this->root_id); + $title = $title["title"]; + if (!$title) { + $title = $lng->txt("personal_workspace"); + } - $tpl->setVariable("ICON_IMAGE", $path); - $tpl->setVariable("TXT_ALT_IMG", $title); - $tpl->parseCurrentBlock(); + $tpl->setVariable("ICON_IMAGE", $path); + $tpl->setVariable("TXT_ALT_IMG", $title); + $tpl->parseCurrentBlock(); - if(strlen($formItem = $this->buildFormItem($a_obj_id, $a_option['type']))) - { - $tpl->setCurrentBlock('check'); - $tpl->setVariable('OBJ_CHECK', $formItem); - $tpl->parseCurrentBlock(); - } - - $tpl->setVariable('OBJ_TITLE', $title); - } - - function setTypeClickable($a_type) - { - $this->clickable[] = $a_type; - } - - function setCustomLinkTarget($a_target) - { - $this->custom_link_target = $a_target; - } - - function buildLinkTarget($a_node_id, $a_type) - { - if(!$this->custom_link_target) - { - return parent::buildLinkTarget($a_node_id, $a_type); - } - - $link = $this->custom_link_target."&".$this->target_get."=".$a_node_id; - return $link; - } + if (strlen($formItem = $this->buildFormItem($a_obj_id, $a_option['type']))) { + $tpl->setCurrentBlock('check'); + $tpl->setVariable('OBJ_CHECK', $formItem); + $tpl->parseCurrentBlock(); + } + + $tpl->setVariable('OBJ_TITLE', $title); + } + + public function setTypeClickable($a_type) + { + $this->clickable[] = $a_type; + } + + public function setCustomLinkTarget($a_target) + { + $this->custom_link_target = $a_target; + } + + public function buildLinkTarget($a_node_id, $a_type) + { + if (!$this->custom_link_target) { + return parent::buildLinkTarget($a_node_id, $a_type); + } + + $link = $this->custom_link_target . "&" . $this->target_get . "=" . $a_node_id; + return $link; + } } -?> \ No newline at end of file diff --git a/Services/PersonalWorkspace/classes/class.ilWorkspaceExplorerGUI.php b/Services/PersonalWorkspace/classes/class.ilWorkspaceExplorerGUI.php index f9032329bc40bfa474f6d7af4c2932c02dcf0d3c..aeed32587ed2580b61b443165904ac979bde660e 100644 --- a/Services/PersonalWorkspace/classes/class.ilWorkspaceExplorerGUI.php +++ b/Services/PersonalWorkspace/classes/class.ilWorkspaceExplorerGUI.php @@ -13,281 +13,268 @@ include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); */ class ilWorkspaceExplorerGUI extends ilTreeExplorerGUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var bool - */ - protected $link_to_node_class = false; + /** + * @var bool + */ + protected $link_to_node_class = false; - /** - * @var string - */ - protected $custom_link_target = ""; + /** + * @var string + */ + protected $custom_link_target = ""; - /** - * @var null|object - */ - protected $select_gui = null; + /** + * @var null|object + */ + protected $select_gui = null; - /** - * @var string - */ - protected $select_cmd = ""; + /** + * @var string + */ + protected $select_cmd = ""; - /** - * @var string - */ - protected $select_par = ""; + /** + * @var string + */ + protected $select_par = ""; - /** - * @var array - */ - protected $selectable_types = array(); + /** + * @var array + */ + protected $selectable_types = array(); - /** - * @var bool - */ - protected $activate_highlighting = false; + /** + * @var bool + */ + protected $activate_highlighting = false; - /** - * Constructor - */ - public function __construct($a_user_id, $a_parent_obj, $a_parent_cmd, $a_select_gui, $a_select_cmd, $a_select_par = "sel_wsp_obj") - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_user_id, $a_parent_obj, $a_parent_cmd, $a_select_gui, $a_select_cmd, $a_select_par = "sel_wsp_obj") + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - - $this->select_gui = (is_object($a_select_gui)) - ? strtolower(get_class($a_select_gui)) - : $a_select_gui; - $this->select_cmd = $a_select_cmd; - $this->select_par = $a_select_par; + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + + $this->select_gui = (is_object($a_select_gui)) + ? strtolower(get_class($a_select_gui)) + : $a_select_gui; + $this->select_cmd = $a_select_cmd; + $this->select_par = $a_select_par; - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; - $this->tree = new ilWorkspaceTree($a_user_id); - $this->root_id = $this->tree->readRootId(); - $this->access_handler = new ilWorkspaceAccessHandler($this->tree); + $this->tree = new ilWorkspaceTree($a_user_id); + $this->root_id = $this->tree->readRootId(); + $this->access_handler = new ilWorkspaceAccessHandler($this->tree); - parent::__construct("wsp_sel", $a_parent_obj, $a_parent_cmd, $this->tree); - $this->setSkipRootNode(false); - $this->setAjax(true); - $this->setPathOpen($this->root_id); - - $this->setTypeWhiteList(array("wsrt", "wfld")); - } - - /** - * Set link to node class - * - * @param bool $a_val link to gui class of node - */ - function setLinkToNodeClass($a_val) - { - $this->link_to_node_class = $a_val; - } - - /** - * Get link to node class - * - * @return bool link to gui class of node - */ - function getLinkToNodeClass() - { - return $this->link_to_node_class; - } - - /** - * Set activate highlighting - * - * @param bool $a_val activate highlighting - */ - function setActivateHighlighting($a_val) - { - $this->activate_highlighting = $a_val; - } - - /** - * Get activate highlighting - * - * @return bool activate highlighting - */ - function getActivateHighlighting() - { - return $this->activate_highlighting; - } + parent::__construct("wsp_sel", $a_parent_obj, $a_parent_cmd, $this->tree); + $this->setSkipRootNode(false); + $this->setAjax(true); + $this->setPathOpen($this->root_id); + + $this->setTypeWhiteList(array("wsrt", "wfld")); + } + + /** + * Set link to node class + * + * @param bool $a_val link to gui class of node + */ + public function setLinkToNodeClass($a_val) + { + $this->link_to_node_class = $a_val; + } + + /** + * Get link to node class + * + * @return bool link to gui class of node + */ + public function getLinkToNodeClass() + { + return $this->link_to_node_class; + } + + /** + * Set activate highlighting + * + * @param bool $a_val activate highlighting + */ + public function setActivateHighlighting($a_val) + { + $this->activate_highlighting = $a_val; + } + + /** + * Get activate highlighting + * + * @return bool activate highlighting + */ + public function getActivateHighlighting() + { + return $this->activate_highlighting; + } - /** - * Set selectable types - * - * @param array $a_val selectable types - */ - function setSelectableTypes($a_val) - { - $this->selectable_types = $a_val; - } - - /** - * Get selectable types - * - * @return array selectable types - */ - function getSelectableTypes() - { - return $this->selectable_types; - } + /** + * Set selectable types + * + * @param array $a_val selectable types + */ + public function setSelectableTypes($a_val) + { + $this->selectable_types = $a_val; + } + + /** + * Get selectable types + * + * @return array selectable types + */ + public function getSelectableTypes() + { + return $this->selectable_types; + } - /** - * Set custom link target - * - * @param string $a_val custom link target - */ - function setCustomLinkTarget($a_val) - { - $this->custom_link_target = $a_val; - } + /** + * Set custom link target + * + * @param string $a_val custom link target + */ + public function setCustomLinkTarget($a_val) + { + $this->custom_link_target = $a_val; + } - /** - * Get custom link target - * - * @return string custom link target - */ - function getCustomLinkTarget() - { - return $this->custom_link_target; - } + /** + * Get custom link target + * + * @return string custom link target + */ + public function getCustomLinkTarget() + { + return $this->custom_link_target; + } - /** - * Get href for node - * - * @param mixed $a_node node object/array - * @return string href attribute - */ - function getNodeHref($a_node) - { - if ($this->select_postvar != "") - { - return ""; - } - if ($this->getCustomLinkTarget() != "") - { - return $this->getCustomLinkTarget()."&".$this->select_par."=".$a_node["child"]; - } + /** + * Get href for node + * + * @param mixed $a_node node object/array + * @return string href attribute + */ + public function getNodeHref($a_node) + { + if ($this->select_postvar != "") { + return ""; + } + if ($this->getCustomLinkTarget() != "") { + return $this->getCustomLinkTarget() . "&" . $this->select_par . "=" . $a_node["child"]; + } - $ilCtrl = $this->ctrl; + $ilCtrl = $this->ctrl; - $target_class = $this->select_gui; + $target_class = $this->select_gui; - if ($this->getLinkToNodeClass()) - { - switch ($a_node["type"]) - { - case "wsrt": - $target_class = "ilobjworkspacerootfoldergui"; - break; - case "wfld": - $target_class = "ilobjworkspacefoldergui"; - break; - } - } - - $ilCtrl->setParameterByClass($target_class, $this->select_par, $a_node["child"]); - $ret = $ilCtrl->getLinkTargetByClass($target_class, $this->select_cmd); - $ilCtrl->setParameterByClass($target_class, $this->select_par, $_GET[$this->select_par]); - - return $ret; - } + if ($this->getLinkToNodeClass()) { + switch ($a_node["type"]) { + case "wsrt": + $target_class = "ilobjworkspacerootfoldergui"; + break; + case "wfld": + $target_class = "ilobjworkspacefoldergui"; + break; + } + } + + $ilCtrl->setParameterByClass($target_class, $this->select_par, $a_node["child"]); + $ret = $ilCtrl->getLinkTargetByClass($target_class, $this->select_cmd); + $ilCtrl->setParameterByClass($target_class, $this->select_par, $_GET[$this->select_par]); + + return $ret; + } - /** - * Get node content - * - * @param array - * @return - */ - function getNodeContent($a_node) - { - $lng = $this->lng; + /** + * Get node content + * + * @param array + * @return + */ + public function getNodeContent($a_node) + { + $lng = $this->lng; - if ($a_node["child"] == $this->tree->getRootId()) - { - return $lng->txt("wsp_personal_workspace"); - } + if ($a_node["child"] == $this->tree->getRootId()) { + return $lng->txt("wsp_personal_workspace"); + } - return $a_node["title"]; - } - - /** - * Is clickable - * - * @param - * @return - */ - function isNodeClickable($a_node) - { - if (in_array($a_node["type"], $this->getSelectableTypes())) - { - return true; - } - return false; - } + return $a_node["title"]; + } + + /** + * Is clickable + * + * @param + * @return + */ + public function isNodeClickable($a_node) + { + if (in_array($a_node["type"], $this->getSelectableTypes())) { + return true; + } + return false; + } - /** - * Is selectable - * - * @param - * @return - */ - function isNodeSelectable($a_node) - { - if (in_array($a_node["type"], $this->getSelectableTypes())) - { - return true; - } - return false; - } - - /** - * get image path (may be overwritten by derived classes) - */ - function getNodeIcon($a_node) - { - $t = $a_node["type"]; - if (in_array($t, array("sktr"))) - { - return ilUtil::getImagePath("icon_skll.svg"); - } - return ilUtil::getImagePath("icon_".$t.".svg"); - } - - /** - * Is node highlighted? - * - * @param mixed $a_node node object/array - * @return boolean node highlighted true/false - */ - function isNodeHighlighted($a_node) - { - if ($this->getActivateHighlighting() && - ($a_node["child"] == $_GET["wsp_id"] || $_GET["wsp_id"] == "" && $a_node["child"] == $this->getRootId())) - { - return true; - } - return false; - } + /** + * Is selectable + * + * @param + * @return + */ + public function isNodeSelectable($a_node) + { + if (in_array($a_node["type"], $this->getSelectableTypes())) { + return true; + } + return false; + } + /** + * get image path (may be overwritten by derived classes) + */ + public function getNodeIcon($a_node) + { + $t = $a_node["type"]; + if (in_array($t, array("sktr"))) { + return ilUtil::getImagePath("icon_skll.svg"); + } + return ilUtil::getImagePath("icon_" . $t . ".svg"); + } + /** + * Is node highlighted? + * + * @param mixed $a_node node object/array + * @return boolean node highlighted true/false + */ + public function isNodeHighlighted($a_node) + { + if ($this->getActivateHighlighting() && + ($a_node["child"] == $_GET["wsp_id"] || $_GET["wsp_id"] == "" && $a_node["child"] == $this->getRootId())) { + return true; + } + return false; + } } - -?> diff --git a/Services/PersonalWorkspace/classes/class.ilWorkspaceGlobalScreenProvider.php b/Services/PersonalWorkspace/classes/class.ilWorkspaceGlobalScreenProvider.php index 8cc2ca780b5b858d17b2a25a95b92609ef434e7b..70753d07fcffb898d09e9d0f6e077920afdbae6d 100644 --- a/Services/PersonalWorkspace/classes/class.ilWorkspaceGlobalScreenProvider.php +++ b/Services/PersonalWorkspace/classes/class.ilWorkspaceGlobalScreenProvider.php @@ -8,56 +8,61 @@ use ILIAS\GlobalScreen\Scope\MainMenu\Provider\AbstractStaticMainMenuProvider; * * @author Fabian Schmid */ -class ilWorkspaceGlobalScreenProvider extends AbstractStaticMainMenuProvider { - - /** - * @var IdentificationInterface - */ - protected $top_item; - - - public function __construct(\ILIAS\DI\Container $dic) { - parent::__construct($dic); - $this->top_item = (new ilPDGlobalScreenProvider($dic))->getTopItem(); - } - - - /** - * Some other components want to provide Items for the main menu which are - * located at the PD TopTitem by default. Therefore we have to provide our - * TopTitem Identification for others - * - * @return IdentificationInterface - */ - public function getTopItem(): IdentificationInterface { - return $this->top_item; - } - - - /** - * @inheritDoc - */ - public function getStaticTopItems(): array { - return []; - } - - - /** - * @inheritDoc - */ - public function getStaticSubItems(): array { - $dic = $this->dic; - - return [$this->mainmenu->link($this->if->identifier('mm_pd_wsp')) - ->withTitle($this->dic->language()->txt("personal_workspace")) - ->withAction("ilias.php?baseClass=ilPersonalDesktopGUI&cmd=jumpToWorkspace") - ->withParent($this->getTopItem()) - ->withPosition(5) - ->withNonAvailableReason($this->dic->ui()->factory()->legacy("{$this->dic->language()->txt('component_not_active')}")) - ->withAvailableCallable( - function () use ($dic) { - return (bool)(!$dic->settings()->get("disable_personal_workspace")); - } - )]; - } +class ilWorkspaceGlobalScreenProvider extends AbstractStaticMainMenuProvider +{ + + /** + * @var IdentificationInterface + */ + protected $top_item; + + + public function __construct(\ILIAS\DI\Container $dic) + { + parent::__construct($dic); + $this->top_item = (new ilPDGlobalScreenProvider($dic))->getTopItem(); + } + + + /** + * Some other components want to provide Items for the main menu which are + * located at the PD TopTitem by default. Therefore we have to provide our + * TopTitem Identification for others + * + * @return IdentificationInterface + */ + public function getTopItem() : IdentificationInterface + { + return $this->top_item; + } + + + /** + * @inheritDoc + */ + public function getStaticTopItems() : array + { + return []; + } + + + /** + * @inheritDoc + */ + public function getStaticSubItems() : array + { + $dic = $this->dic; + + return [$this->mainmenu->link($this->if->identifier('mm_pd_wsp')) + ->withTitle($this->dic->language()->txt("personal_workspace")) + ->withAction("ilias.php?baseClass=ilPersonalDesktopGUI&cmd=jumpToWorkspace") + ->withParent($this->getTopItem()) + ->withPosition(5) + ->withNonAvailableReason($this->dic->ui()->factory()->legacy("{$this->dic->language()->txt('component_not_active')}")) + ->withAvailableCallable( + function () use ($dic) { + return (bool) (!$dic->settings()->get("disable_personal_workspace")); + } + )]; + } } diff --git a/Services/PersonalWorkspace/classes/class.ilWorkspaceShareTableGUI.php b/Services/PersonalWorkspace/classes/class.ilWorkspaceShareTableGUI.php index fb7592210a11f98de646c3eda14899e02a4d0dc4..fdd9b657e6a820b23d2d3e06f680d48628f6b84f 100644 --- a/Services/PersonalWorkspace/classes/class.ilWorkspaceShareTableGUI.php +++ b/Services/PersonalWorkspace/classes/class.ilWorkspaceShareTableGUI.php @@ -1,409 +1,375 @@ - - * @version $Id: class.adnCountryTableGUI.php 27876 2011-02-25 16:51:38Z jluetzen $ - * - * @ingroup ServicesPersonalWorkspace - */ -class ilWorkspaceShareTableGUI extends ilTable2GUI -{ - /** - * @var ilCtrl - */ - protected $ctrl; + + * @version $Id: class.adnCountryTableGUI.php 27876 2011-02-25 16:51:38Z jluetzen $ + * + * @ingroup ServicesPersonalWorkspace + */ +class ilWorkspaceShareTableGUI extends ilTable2GUI +{ + /** + * @var ilCtrl + */ + protected $ctrl; - protected $handler; // [ilWorkspaceAccessHandler] - protected $parent_node_id; // [int] - protected $filter; // [array] - protected $crs_ids; // [array] - protected $grp_ids; // [array] - protected $portfolio_mode = false; // [bool] - - /** - * Constructor - * - * @param object $a_parent_obj parent gui object - * @param string $a_parent_cmd parent default command - * @param object $a_handler workspace access handler - * @param bool $a_load_data - * @param int $a_parent_node_id - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_handler, $a_parent_node_id = null, $a_load_data = false) - { - global $DIC; + /** + * @var ilSetting + */ + protected $settings; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->settings = $DIC->settings(); - $this->user = $DIC->user(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->handler = $a_handler; - - if(stristr(get_class($a_parent_obj), "portfolio")) - { - $this->parent_node_id = $a_parent_node_id; - $this->portfolio_mode = true; - } - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setId("il_tbl_wspsh".(int)$this->portfolio_mode); - - $this->setTitle($lng->txt("wsp_shared_resources")); - - $this->addColumn($this->lng->txt("lastname"), "lastname"); - $this->addColumn($this->lng->txt("firstname"), "firstname"); - $this->addColumn($this->lng->txt("login"), "login"); - - if(!$this->portfolio_mode) - { - $this->addColumn($this->lng->txt("wsp_shared_object_type"), "obj_type"); - } - - $this->addColumn($this->lng->txt("wsp_shared_date"), "acl_date"); - $this->addColumn($this->lng->txt("wsp_shared_title"), "title"); - $this->addColumn($this->lng->txt("wsp_shared_type")); - - if(!$this->portfolio_mode) - { - $this->addColumn($this->lng->txt("action")); - } - - $this->setDefaultOrderField("acl_date"); - $this->setDefaultOrderDirection("desc"); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.shared_row.html", "Services/PersonalWorkspace"); - - $this->setDisableFilterHiding(true); - $this->setResetCommand("resetsharefilter", $this->lng->txt("wsp_shared_filter_reset_button")); - $this->setFilterCommand("applysharefilter", $this->lng->txt("wsp_shared_filter_button")); - - $this->initFilter(); - - // reset will remove all filters - if($this->portfolio_mode && - !$this->filter["obj_type"]) - { - $this->filter["obj_type"] = "prtf"; - } - - // incoming request: check for validity - if($a_load_data) - { - /* - if(($this->filter["user"] && strlen($this->filter["user"]) > 3) || - ($this->filter["title"] && strlen($this->filter["title"]) > 3) || - $this->filter["acl_date"] || - $this->filter["obj_type"] || - $this->filter["acl_type"] || - $this->filter["crsgrp"]) - { - */ - - // #16630 - $this->importData(); - include_once "Services/User/classes/class.ilUserUtil.php"; - return; - } - else - { - ilUtil::sendInfo($lng->txt("wsp_shared_mandatory_filter_info")); - } - - // initial state: show filters only - $this->disable("header"); - $this->disable("content"); - } - - public function initFilter() - { - $lng = $this->lng; - $ilSetting = $this->settings; - $ilUser = $this->user; - - include_once "Services/Membership/classes/class.ilParticipants.php"; - $this->crs_ids = ilParticipants::_getMembershipByType($ilUser->getId(), "crs"); - $this->grp_ids = ilParticipants::_getMembershipByType($ilUser->getId(), "grp"); - - $lng->loadLanguageModule("search"); - - $item = $this->addFilterItemByMetaType("user", self::FILTER_TEXT, false, $lng->txt("wsp_shared_user_filter")); - $this->filter["user"] = $item->getValue(); - - // incoming back link (shared) - if((int)$_REQUEST["shr_id"] && - !is_array($_SESSION["form_".$this->getId()]) && // #17747 - !$this->filter["user"]) - { - $this->filter["user"] = ilObjUser::_lookupName((int)$_REQUEST["shr_id"]); - $this->filter["user"] = $this->filter["user"]["login"]; - $item->setValue($this->filter["user"]); - } - - $item = $this->addFilterItemByMetaType("title", self::FILTER_TEXT, false, $lng->txt("wsp_shared_title")); - $this->filter["title"] = $item->getValue(); - - $item = $this->addFilterItemByMetaType("acl_date", self::FILTER_DATE, false, $lng->txt("wsp_shared_date_filter")); - $this->filter["acl_date"] = $item->getDate(); - - if(!$this->portfolio_mode) - { - // see ilPersonalWorkspaceGUI::renderToolbar - $options = array(""=>$lng->txt("search_any")); - $settings_map = array("blog" => "blogs", - "file" => "files"); - // see ilObjWorkspaceFolderTableGUI - foreach(array("file", "blog") as $type) - { - if(isset($settings_map[$type]) && $ilSetting->get("disable_wsp_".$settings_map[$type])) - { - continue; - } - $options[$type] = $lng->txt("wsp_type_".$type); - } - } - else - { - $options = array("prtf"=>$lng->txt("obj_prtf")); - } - if(sizeof($options)) - { - asort($options); - $item = $this->addFilterItemByMetaType("obj_type", self::FILTER_SELECT, false, $lng->txt("wsp_shared_object_type")); - $item->setOptions($options); - $this->filter["obj_type"] = $item->getValue(); - } - - // see ilWorkspaceAccessGUI::share - $options = array(); - $options["user"] = $lng->txt("wsp_set_permission_single_user"); - - if(sizeof($this->grp_ids)) - { - $options["group"] = $lng->txt("wsp_set_permission_group"); - } - - if(sizeof($this->crs_ids)) - { - $options["course"] = $lng->txt("wsp_set_permission_course"); - } - - if(!$this->handler->hasRegisteredPermission($this->parent_node_id)) - { - $options["registered"] = $lng->txt("wsp_set_permission_registered"); - } - - if($ilSetting->get("enable_global_profiles")) - { - if(!$this->handler->hasGlobalPasswordPermission($this->parent_node_id)) - { - $options["password"] = $this->lng->txt("wsp_set_permission_all_password"); - } - - if(!$this->handler->hasGlobalPermission($this->parent_node_id)) - { - $options["all"] = $this->lng->txt("wsp_set_permission_all"); - } - } - - if(sizeof($options)) - { - // asort($options); - $item = $this->addFilterItemByMetaType("acl_type", self::FILTER_SELECT, false, $lng->txt("wsp_shared_type")); - $item->setOptions(array(""=>$lng->txt("search_any"))+$options); - $this->filter["acl_type"] = $item->getValue(); - } - - if(sizeof($this->crs_ids) || sizeof($this->grp_ids)) - { - $options = array(); - foreach($this->crs_ids as $crs_id) - { - $options[$crs_id] = $lng->txt("obj_crs")." ".ilObject::_lookupTitle($crs_id); - } - foreach($this->grp_ids as $grp_id) - { - $options[$grp_id] = $lng->txt("obj_grp")." ".ilObject::_lookupTitle($grp_id); - } - asort($options); - $item = $this->addFilterItemByMetaType("crsgrp", self::FILTER_SELECT, false, $lng->txt("wsp_shared_member_filter")); - $item->setOptions(array(""=>$lng->txt("search_any"))+$options); - $this->filter["crsgrp"] = $item->getValue(); - } - } - - protected function importData() - { - $lng = $this->lng; - - $data = array(); - - $user_data = array(); - - $objects = $this->handler->findSharedObjects($this->filter, $this->crs_ids, $this->grp_ids); - if($objects) - { - foreach($objects as $wsp_id => $item) - { - if(!isset($user_data[$item["owner"]])) - { - $user_data[$item["owner"]] = ilObjUser::_lookupName($item["owner"]); - } - - // #18535 - deleted user? - if(!$user_data[$item["owner"]]["login"]) - { - continue; - } - - $data[] = array( - "wsp_id" => $wsp_id, - "obj_id" => $item["obj_id"], - "type" => $item["type"], - "obj_type" => $lng->txt("wsp_type_".$item["type"]), - "title" => $item["title"], - "owner_id" => $item["owner"], - "lastname" => $user_data[$item["owner"]]["lastname"], - "firstname" => $user_data[$item["owner"]]["firstname"], - "login" => $user_data[$item["owner"]]["login"], - "acl_type" => $item["acl_type"], - "acl_date" => $item["acl_date"] - ); - } - } - - $this->setData($data); - - include_once('./Services/Link/classes/class.ilLink.php'); - } - - /** - * Fill table row - * - * @param array $a_set data array - */ - protected function fillRow($node) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->tpl->setVariable("LASTNAME", $node["lastname"]); - $this->tpl->setVariable("FIRSTNAME", $node["firstname"]); - $this->tpl->setVariable("LOGIN", $node["login"]); - - $this->tpl->setVariable("TITLE", $node["title"]); - - if(!$this->portfolio_mode) - { - $this->tpl->setVariable("TYPE", $node["obj_type"]); - $this->tpl->setVariable("ICON_ALT", $node["obj_type"]); - $this->tpl->setVariable("ICON", ilObject::_getIcon("", "tiny", $node["type"])); - - $url = $this->handler->getGotoLink($node["wsp_id"], $node["obj_id"]); - } - else - { - $url = ilLink::_getStaticLink($node["obj_id"], "prtf", true); - } - $this->tpl->setVariable("URL_TITLE", $url); - - $this->tpl->setVariable("ACL_DATE", - ilDatePresentation::formatDate(new ilDateTime($node["acl_date"], IL_CAL_UNIX))); - - asort($node["acl_type"]); - foreach($node["acl_type"] as $obj_id) - { - // see ilWorkspaceAccessTableGUI - switch($obj_id) - { - case ilWorkspaceAccessGUI::PERMISSION_REGISTERED: - $title = $icon_alt = $this->lng->txt("wsp_set_permission_registered"); - $type = "registered"; - break; - - case ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD: - $title = $icon_alt = $this->lng->txt("wsp_set_permission_all_password"); - $type = "all_password"; - break; - - case ilWorkspaceAccessGUI::PERMISSION_ALL: - $title = $icon_alt = $this->lng->txt("wsp_set_permission_all"); - $type = "all_password"; - break; - - default: - $type = ilObject::_lookupType($obj_id); - /* - $icon = ilUtil::getTypeIconPath($type, null, "tiny"); - $icon_alt = $this->lng->txt("obj_".$type); - */ - if($type != "usr") - { - $title = ilObject::_lookupTitle($obj_id); - } - else - { - $title = ilUserUtil::getNamePresentation($obj_id, false, true); - } - break; - } - - /* #17758 - if($icon) - { - $this->tpl->setCurrentBlock("acl_type_icon_bl"); - $this->tpl->setVariable("ACL_ICON", $icon); - $this->tpl->setVariable("ACL_ICON_ALT", $icon_alt); - $this->tpl->parseCurrentBlock(); - } - */ - - $this->tpl->setCurrentBlock("acl_type_bl"); - $this->tpl->setVariable("ACL_TYPE", $title); - $this->tpl->parseCurrentBlock(); - } - - if(!$this->portfolio_mode) - { - // files may be copied to own workspace - if($node["type"] == "file") - { - $ilCtrl->setParameter($this->parent_obj, "wsp_id", - $this->parent_node_id); - $ilCtrl->setParameter($this->parent_obj, "item_ref_id", - $node["wsp_id"]); - $url = $ilCtrl->getLinkTarget($this->parent_obj, "copyshared"); - - $this->tpl->setCurrentBlock("action_bl"); - $this->tpl->setVariable("URL_ACTION", $url); - $this->tpl->setVariable("ACTION", $lng->txt("copy")); - $this->tpl->parseCurrentBlock(); - } - else - { - $this->tpl->touchBlock("action_col_bl"); - } - } - } -} - -?> \ No newline at end of file + /** + * @var ilObjUser + */ + protected $user; + + protected $handler; // [ilWorkspaceAccessHandler] + protected $parent_node_id; // [int] + protected $filter; // [array] + protected $crs_ids; // [array] + protected $grp_ids; // [array] + protected $portfolio_mode = false; // [bool] + + /** + * Constructor + * + * @param object $a_parent_obj parent gui object + * @param string $a_parent_cmd parent default command + * @param object $a_handler workspace access handler + * @param bool $a_load_data + * @param int $a_parent_node_id + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_handler, $a_parent_node_id = null, $a_load_data = false) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->settings = $DIC->settings(); + $this->user = $DIC->user(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->handler = $a_handler; + + if (stristr(get_class($a_parent_obj), "portfolio")) { + $this->parent_node_id = $a_parent_node_id; + $this->portfolio_mode = true; + } + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setId("il_tbl_wspsh" . (int) $this->portfolio_mode); + + $this->setTitle($lng->txt("wsp_shared_resources")); + + $this->addColumn($this->lng->txt("lastname"), "lastname"); + $this->addColumn($this->lng->txt("firstname"), "firstname"); + $this->addColumn($this->lng->txt("login"), "login"); + + if (!$this->portfolio_mode) { + $this->addColumn($this->lng->txt("wsp_shared_object_type"), "obj_type"); + } + + $this->addColumn($this->lng->txt("wsp_shared_date"), "acl_date"); + $this->addColumn($this->lng->txt("wsp_shared_title"), "title"); + $this->addColumn($this->lng->txt("wsp_shared_type")); + + if (!$this->portfolio_mode) { + $this->addColumn($this->lng->txt("action")); + } + + $this->setDefaultOrderField("acl_date"); + $this->setDefaultOrderDirection("desc"); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.shared_row.html", "Services/PersonalWorkspace"); + + $this->setDisableFilterHiding(true); + $this->setResetCommand("resetsharefilter", $this->lng->txt("wsp_shared_filter_reset_button")); + $this->setFilterCommand("applysharefilter", $this->lng->txt("wsp_shared_filter_button")); + + $this->initFilter(); + + // reset will remove all filters + if ($this->portfolio_mode && + !$this->filter["obj_type"]) { + $this->filter["obj_type"] = "prtf"; + } + + // incoming request: check for validity + if ($a_load_data) { + /* + if(($this->filter["user"] && strlen($this->filter["user"]) > 3) || + ($this->filter["title"] && strlen($this->filter["title"]) > 3) || + $this->filter["acl_date"] || + $this->filter["obj_type"] || + $this->filter["acl_type"] || + $this->filter["crsgrp"]) + { + */ + + // #16630 + $this->importData(); + include_once "Services/User/classes/class.ilUserUtil.php"; + return; + } else { + ilUtil::sendInfo($lng->txt("wsp_shared_mandatory_filter_info")); + } + + // initial state: show filters only + $this->disable("header"); + $this->disable("content"); + } + + public function initFilter() + { + $lng = $this->lng; + $ilSetting = $this->settings; + $ilUser = $this->user; + + include_once "Services/Membership/classes/class.ilParticipants.php"; + $this->crs_ids = ilParticipants::_getMembershipByType($ilUser->getId(), "crs"); + $this->grp_ids = ilParticipants::_getMembershipByType($ilUser->getId(), "grp"); + + $lng->loadLanguageModule("search"); + + $item = $this->addFilterItemByMetaType("user", self::FILTER_TEXT, false, $lng->txt("wsp_shared_user_filter")); + $this->filter["user"] = $item->getValue(); + + // incoming back link (shared) + if ((int) $_REQUEST["shr_id"] && + !is_array($_SESSION["form_" . $this->getId()]) && // #17747 + !$this->filter["user"]) { + $this->filter["user"] = ilObjUser::_lookupName((int) $_REQUEST["shr_id"]); + $this->filter["user"] = $this->filter["user"]["login"]; + $item->setValue($this->filter["user"]); + } + + $item = $this->addFilterItemByMetaType("title", self::FILTER_TEXT, false, $lng->txt("wsp_shared_title")); + $this->filter["title"] = $item->getValue(); + + $item = $this->addFilterItemByMetaType("acl_date", self::FILTER_DATE, false, $lng->txt("wsp_shared_date_filter")); + $this->filter["acl_date"] = $item->getDate(); + + if (!$this->portfolio_mode) { + // see ilPersonalWorkspaceGUI::renderToolbar + $options = array(""=>$lng->txt("search_any")); + $settings_map = array("blog" => "blogs", + "file" => "files"); + // see ilObjWorkspaceFolderTableGUI + foreach (array("file", "blog") as $type) { + if (isset($settings_map[$type]) && $ilSetting->get("disable_wsp_" . $settings_map[$type])) { + continue; + } + $options[$type] = $lng->txt("wsp_type_" . $type); + } + } else { + $options = array("prtf"=>$lng->txt("obj_prtf")); + } + if (sizeof($options)) { + asort($options); + $item = $this->addFilterItemByMetaType("obj_type", self::FILTER_SELECT, false, $lng->txt("wsp_shared_object_type")); + $item->setOptions($options); + $this->filter["obj_type"] = $item->getValue(); + } + + // see ilWorkspaceAccessGUI::share + $options = array(); + $options["user"] = $lng->txt("wsp_set_permission_single_user"); + + if (sizeof($this->grp_ids)) { + $options["group"] = $lng->txt("wsp_set_permission_group"); + } + + if (sizeof($this->crs_ids)) { + $options["course"] = $lng->txt("wsp_set_permission_course"); + } + + if (!$this->handler->hasRegisteredPermission($this->parent_node_id)) { + $options["registered"] = $lng->txt("wsp_set_permission_registered"); + } + + if ($ilSetting->get("enable_global_profiles")) { + if (!$this->handler->hasGlobalPasswordPermission($this->parent_node_id)) { + $options["password"] = $this->lng->txt("wsp_set_permission_all_password"); + } + + if (!$this->handler->hasGlobalPermission($this->parent_node_id)) { + $options["all"] = $this->lng->txt("wsp_set_permission_all"); + } + } + + if (sizeof($options)) { + // asort($options); + $item = $this->addFilterItemByMetaType("acl_type", self::FILTER_SELECT, false, $lng->txt("wsp_shared_type")); + $item->setOptions(array(""=>$lng->txt("search_any"))+$options); + $this->filter["acl_type"] = $item->getValue(); + } + + if (sizeof($this->crs_ids) || sizeof($this->grp_ids)) { + $options = array(); + foreach ($this->crs_ids as $crs_id) { + $options[$crs_id] = $lng->txt("obj_crs") . " " . ilObject::_lookupTitle($crs_id); + } + foreach ($this->grp_ids as $grp_id) { + $options[$grp_id] = $lng->txt("obj_grp") . " " . ilObject::_lookupTitle($grp_id); + } + asort($options); + $item = $this->addFilterItemByMetaType("crsgrp", self::FILTER_SELECT, false, $lng->txt("wsp_shared_member_filter")); + $item->setOptions(array(""=>$lng->txt("search_any"))+$options); + $this->filter["crsgrp"] = $item->getValue(); + } + } + + protected function importData() + { + $lng = $this->lng; + + $data = array(); + + $user_data = array(); + + $objects = $this->handler->findSharedObjects($this->filter, $this->crs_ids, $this->grp_ids); + if ($objects) { + foreach ($objects as $wsp_id => $item) { + if (!isset($user_data[$item["owner"]])) { + $user_data[$item["owner"]] = ilObjUser::_lookupName($item["owner"]); + } + + // #18535 - deleted user? + if (!$user_data[$item["owner"]]["login"]) { + continue; + } + + $data[] = array( + "wsp_id" => $wsp_id, + "obj_id" => $item["obj_id"], + "type" => $item["type"], + "obj_type" => $lng->txt("wsp_type_" . $item["type"]), + "title" => $item["title"], + "owner_id" => $item["owner"], + "lastname" => $user_data[$item["owner"]]["lastname"], + "firstname" => $user_data[$item["owner"]]["firstname"], + "login" => $user_data[$item["owner"]]["login"], + "acl_type" => $item["acl_type"], + "acl_date" => $item["acl_date"] + ); + } + } + + $this->setData($data); + + include_once('./Services/Link/classes/class.ilLink.php'); + } + + /** + * Fill table row + * + * @param array $a_set data array + */ + protected function fillRow($node) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->tpl->setVariable("LASTNAME", $node["lastname"]); + $this->tpl->setVariable("FIRSTNAME", $node["firstname"]); + $this->tpl->setVariable("LOGIN", $node["login"]); + + $this->tpl->setVariable("TITLE", $node["title"]); + + if (!$this->portfolio_mode) { + $this->tpl->setVariable("TYPE", $node["obj_type"]); + $this->tpl->setVariable("ICON_ALT", $node["obj_type"]); + $this->tpl->setVariable("ICON", ilObject::_getIcon("", "tiny", $node["type"])); + + $url = $this->handler->getGotoLink($node["wsp_id"], $node["obj_id"]); + } else { + $url = ilLink::_getStaticLink($node["obj_id"], "prtf", true); + } + $this->tpl->setVariable("URL_TITLE", $url); + + $this->tpl->setVariable( + "ACL_DATE", + ilDatePresentation::formatDate(new ilDateTime($node["acl_date"], IL_CAL_UNIX)) + ); + + asort($node["acl_type"]); + foreach ($node["acl_type"] as $obj_id) { + // see ilWorkspaceAccessTableGUI + switch ($obj_id) { + case ilWorkspaceAccessGUI::PERMISSION_REGISTERED: + $title = $icon_alt = $this->lng->txt("wsp_set_permission_registered"); + $type = "registered"; + break; + + case ilWorkspaceAccessGUI::PERMISSION_ALL_PASSWORD: + $title = $icon_alt = $this->lng->txt("wsp_set_permission_all_password"); + $type = "all_password"; + break; + + case ilWorkspaceAccessGUI::PERMISSION_ALL: + $title = $icon_alt = $this->lng->txt("wsp_set_permission_all"); + $type = "all_password"; + break; + + default: + $type = ilObject::_lookupType($obj_id); + /* + $icon = ilUtil::getTypeIconPath($type, null, "tiny"); + $icon_alt = $this->lng->txt("obj_".$type); + */ + if ($type != "usr") { + $title = ilObject::_lookupTitle($obj_id); + } else { + $title = ilUserUtil::getNamePresentation($obj_id, false, true); + } + break; + } + + /* #17758 + if($icon) + { + $this->tpl->setCurrentBlock("acl_type_icon_bl"); + $this->tpl->setVariable("ACL_ICON", $icon); + $this->tpl->setVariable("ACL_ICON_ALT", $icon_alt); + $this->tpl->parseCurrentBlock(); + } + */ + + $this->tpl->setCurrentBlock("acl_type_bl"); + $this->tpl->setVariable("ACL_TYPE", $title); + $this->tpl->parseCurrentBlock(); + } + + if (!$this->portfolio_mode) { + // files may be copied to own workspace + if ($node["type"] == "file") { + $ilCtrl->setParameter( + $this->parent_obj, + "wsp_id", + $this->parent_node_id + ); + $ilCtrl->setParameter( + $this->parent_obj, + "item_ref_id", + $node["wsp_id"] + ); + $url = $ilCtrl->getLinkTarget($this->parent_obj, "copyshared"); + + $this->tpl->setCurrentBlock("action_bl"); + $this->tpl->setVariable("URL_ACTION", $url); + $this->tpl->setVariable("ACTION", $lng->txt("copy")); + $this->tpl->parseCurrentBlock(); + } else { + $this->tpl->touchBlock("action_col_bl"); + } + } + } +} diff --git a/Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php b/Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php index 99a70d3ed791ea366d3888f957fdf6bc75aeea19..526e235536b497fde310189d3e80314cc9e56e94 100644 --- a/Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php +++ b/Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php @@ -12,200 +12,196 @@ include_once "Services/Tree/classes/class.ilTree.php"; */ class ilWorkspaceTree extends ilTree { - /** - * @var ilDB - */ - protected $db; - - public function __construct($a_tree_id, $a_root_id = 0) - { - global $DIC; - - $this->db = $DIC->database(); - parent::__construct($a_tree_id, $a_root_id); - - $this->setTableNames('tree_workspace', 'object_data', 'object_reference_ws'); - $this->setTreeTablePK('tree'); - $this->setObjectTablePK('obj_id'); - $this->setReferenceTablePK('wsp_id'); - - // ilTree sets it to ROOT_FOLDER_ID if not given... - if(!$a_root_id) - { - $this->readRootId(); - } - } - - /** - * Create workspace reference for object - * - * @param int $a_object_id - * @return int node id - */ - public function createReference($a_object_id) - { - $ilDB = $this->db; - - $next_id = $ilDB->nextId($this->table_obj_reference); - - $fields = array($this->ref_pk => array("integer", $next_id), - $this->obj_pk => array("integer", $a_object_id)); - - $ilDB->insert($this->table_obj_reference, $fields); - - return $next_id; - } - - /** - * Get object id for node id - * - * @param int $a_node_id - * @return int object id - */ - public function lookupObjectId($a_node_id) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT ".$this->obj_pk. - " FROM ".$this->table_obj_reference. - " WHERE ".$this->ref_pk." = ".$ilDB->quote($a_node_id, "integer")); - $res = $ilDB->fetchAssoc($set); - - return $res[$this->obj_pk]; - } - - - /** - * Get node id for object id - * - * As we do not allow references in workspace this should not be ambigious - * - * @param int $a_obj_id - * @return int node id - */ - public function lookupNodeId($a_obj_id) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT ".$this->ref_pk. - " FROM ".$this->table_obj_reference. - " WHERE ".$this->obj_pk." = ".$ilDB->quote($a_obj_id, "integer")); - $res = $ilDB->fetchAssoc($set); - - return $res[$this->ref_pk]; - } - - /** - * Get owner for node id - * - * @param int $a_node_id - * @return int object id - */ - public function lookupOwner($a_node_id) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT tree". - " FROM ".$this->table_obj_reference. - " JOIN ".$this->table_tree." ON (".$this->table_obj_reference.".".$this->ref_pk." = ".$this->table_tree.".child)". - " WHERE ".$this->ref_pk." = ".$ilDB->quote($a_node_id, "integer")); - $res = $ilDB->fetchAssoc($set); - - return $res["tree"]; - } - - /** - * Add object to tree - * - * @param int $a_parent_node_id - * @param int $a_object_id - * @return int node id - */ - public function insertObject($a_parent_node_id, $a_object_id) - { - $node_id = $this->createReference($a_object_id); - $this->insertNode($node_id, $a_parent_node_id); - return $node_id; - } - - /** - * Delete object from reference table - * - * @param int $a_node_id - * @return bool - */ - public function deleteReference($a_node_id) - { - $ilDB = $this->db; - - $query = "DELETE FROM ".$this->table_obj_reference. - " WHERE ".$this->ref_pk." = ".$ilDB->quote($a_node_id, "integer"); - return $ilDB->manipulate($query); - } - - /** - * Remove all tree and node data - */ - public function cascadingDelete() - { - $root_id = $this->readRootId(); - if(!$root_id) - { - return; - } - - $root = $this->getNodeData($root_id); - - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; - $access_handler = new ilWorkspaceAccessHandler($this); - - // delete node data - $nodes = $this->getSubTree($root); - foreach($nodes as $node) - { - $access_handler->removePermission($node["wsp_id"]); - - $object = ilObjectFactory::getInstanceByObjId($node["obj_id"], false); - if($object) - { - $object->delete(); - } - - $this->deleteReference($node["wsp_id"]); - } - - $this->deleteTree($root); - } - - /** - * Get all workspace objects of specific type - * - * @param string $a_type - * @param bool $a_with_data - * @return array - */ - public function getObjectsFromType($a_type, $a_with_data = false) - { - return $this->getSubTree( - $this->getNodeData($this->getRootId()), - $a_with_data, $a_type); - } - - /** - * Create personal workspace tree for user - * - * @param int $a_user_id - */ - public function createTreeForUser($a_user_id) - { - $root = ilObjectFactory::getClassByType("wsrt"); - $root = new $root(null); - $root->create(); - - $root_id = $this->createReference($root->getId()); - $this->addTree($a_user_id, $root_id); - $this->setRootId($root_id); - } + /** + * @var ilDB + */ + protected $db; + + public function __construct($a_tree_id, $a_root_id = 0) + { + global $DIC; + + $this->db = $DIC->database(); + parent::__construct($a_tree_id, $a_root_id); + + $this->setTableNames('tree_workspace', 'object_data', 'object_reference_ws'); + $this->setTreeTablePK('tree'); + $this->setObjectTablePK('obj_id'); + $this->setReferenceTablePK('wsp_id'); + + // ilTree sets it to ROOT_FOLDER_ID if not given... + if (!$a_root_id) { + $this->readRootId(); + } + } + + /** + * Create workspace reference for object + * + * @param int $a_object_id + * @return int node id + */ + public function createReference($a_object_id) + { + $ilDB = $this->db; + + $next_id = $ilDB->nextId($this->table_obj_reference); + + $fields = array($this->ref_pk => array("integer", $next_id), + $this->obj_pk => array("integer", $a_object_id)); + + $ilDB->insert($this->table_obj_reference, $fields); + + return $next_id; + } + + /** + * Get object id for node id + * + * @param int $a_node_id + * @return int object id + */ + public function lookupObjectId($a_node_id) + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT " . $this->obj_pk . + " FROM " . $this->table_obj_reference . + " WHERE " . $this->ref_pk . " = " . $ilDB->quote($a_node_id, "integer")); + $res = $ilDB->fetchAssoc($set); + + return $res[$this->obj_pk]; + } + + + /** + * Get node id for object id + * + * As we do not allow references in workspace this should not be ambigious + * + * @param int $a_obj_id + * @return int node id + */ + public function lookupNodeId($a_obj_id) + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT " . $this->ref_pk . + " FROM " . $this->table_obj_reference . + " WHERE " . $this->obj_pk . " = " . $ilDB->quote($a_obj_id, "integer")); + $res = $ilDB->fetchAssoc($set); + + return $res[$this->ref_pk]; + } + + /** + * Get owner for node id + * + * @param int $a_node_id + * @return int object id + */ + public function lookupOwner($a_node_id) + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT tree" . + " FROM " . $this->table_obj_reference . + " JOIN " . $this->table_tree . " ON (" . $this->table_obj_reference . "." . $this->ref_pk . " = " . $this->table_tree . ".child)" . + " WHERE " . $this->ref_pk . " = " . $ilDB->quote($a_node_id, "integer")); + $res = $ilDB->fetchAssoc($set); + + return $res["tree"]; + } + + /** + * Add object to tree + * + * @param int $a_parent_node_id + * @param int $a_object_id + * @return int node id + */ + public function insertObject($a_parent_node_id, $a_object_id) + { + $node_id = $this->createReference($a_object_id); + $this->insertNode($node_id, $a_parent_node_id); + return $node_id; + } + + /** + * Delete object from reference table + * + * @param int $a_node_id + * @return bool + */ + public function deleteReference($a_node_id) + { + $ilDB = $this->db; + + $query = "DELETE FROM " . $this->table_obj_reference . + " WHERE " . $this->ref_pk . " = " . $ilDB->quote($a_node_id, "integer"); + return $ilDB->manipulate($query); + } + + /** + * Remove all tree and node data + */ + public function cascadingDelete() + { + $root_id = $this->readRootId(); + if (!$root_id) { + return; + } + + $root = $this->getNodeData($root_id); + + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; + $access_handler = new ilWorkspaceAccessHandler($this); + + // delete node data + $nodes = $this->getSubTree($root); + foreach ($nodes as $node) { + $access_handler->removePermission($node["wsp_id"]); + + $object = ilObjectFactory::getInstanceByObjId($node["obj_id"], false); + if ($object) { + $object->delete(); + } + + $this->deleteReference($node["wsp_id"]); + } + + $this->deleteTree($root); + } + + /** + * Get all workspace objects of specific type + * + * @param string $a_type + * @param bool $a_with_data + * @return array + */ + public function getObjectsFromType($a_type, $a_with_data = false) + { + return $this->getSubTree( + $this->getNodeData($this->getRootId()), + $a_with_data, + $a_type + ); + } + + /** + * Create personal workspace tree for user + * + * @param int $a_user_id + */ + public function createTreeForUser($a_user_id) + { + $root = ilObjectFactory::getClassByType("wsrt"); + $root = new $root(null); + $root->create(); + + $root_id = $this->createReference($root->getId()); + $this->addTree($a_user_id, $root_id); + $this->setRootId($root_id); + } } - -?> \ No newline at end of file diff --git a/Services/Rating/classes/class.ilRating.php b/Services/Rating/classes/class.ilRating.php index 79458a906d723bc7f14c1281dcea691aef5c5338..a10ea67def8ebee7d01914a6ee564c33dba5da85 100644 --- a/Services/Rating/classes/class.ilRating.php +++ b/Services/Rating/classes/class.ilRating.php @@ -13,311 +13,293 @@ * @ingroup ServicesRating */ class ilRating -{ - protected static $list_data; // [array] - - /** - * Write rating for a user and an object. - * - * @param int $a_obj_id Object ID - * @param string $a_obj_type Object Type - * @param int $a_sub_obj_id Subobject ID - * @param string $a_sub_obj_type Subobject Type - * @param int $a_user_id User ID - * @param int $a_rating Rating - * @param int $a_category_id Category ID - */ - public static function writeRatingForUserAndObject($a_obj_id, $a_obj_type, $a_sub_obj_id, $a_sub_obj_type, - $a_user_id, $a_rating, $a_category_id = 0) - { - global $DIC; +{ + protected static $list_data; // [array] + + /** + * Write rating for a user and an object. + * + * @param int $a_obj_id Object ID + * @param string $a_obj_type Object Type + * @param int $a_sub_obj_id Subobject ID + * @param string $a_sub_obj_type Subobject Type + * @param int $a_user_id User ID + * @param int $a_rating Rating + * @param int $a_category_id Category ID + */ + public static function writeRatingForUserAndObject( + $a_obj_id, + $a_obj_type, + $a_sub_obj_id, + $a_sub_obj_type, + $a_user_id, + $a_rating, + $a_category_id = 0 + ) { + global $DIC; - $ilDB = $DIC->database(); + $ilDB = $DIC->database(); - if ($a_user_id == ANONYMOUS_USER_ID) - { - return; - } - - if($a_category_id) - { - $ilDB->manipulate("DELETE FROM il_rating WHERE ". - "user_id = ".$ilDB->quote($a_user_id, "integer")." AND ". - "obj_id = ".$ilDB->quote((int) $a_obj_id, "integer")." AND ". - "obj_type = ".$ilDB->quote($a_obj_type, "text")." AND ". - "sub_obj_id = ".$ilDB->quote((int) $a_sub_obj_id, "integer")." AND ". - $ilDB->equals("sub_obj_type", $a_sub_obj_type, "text", true)." AND ". - "category_id = ".$ilDB->quote(0, "integer")); - } - - $ilDB->manipulate("DELETE FROM il_rating WHERE ". - "user_id = ".$ilDB->quote($a_user_id, "integer")." AND ". - "obj_id = ".$ilDB->quote((int) $a_obj_id, "integer")." AND ". - "obj_type = ".$ilDB->quote($a_obj_type, "text")." AND ". - "sub_obj_id = ".$ilDB->quote((int) $a_sub_obj_id, "integer")." AND ". - $ilDB->equals("sub_obj_type", $a_sub_obj_type, "text", true)." AND ". - "category_id = ".$ilDB->quote((int) $a_category_id, "integer")); - - if((int)$a_rating) - { - $ilDB->manipulate("INSERT INTO il_rating (user_id, obj_id, obj_type,". - "sub_obj_id, sub_obj_type, category_id, rating, tstamp) VALUES (". - $ilDB->quote($a_user_id, "integer").",". - $ilDB->quote((int) $a_obj_id, "integer").",". - $ilDB->quote($a_obj_type, "text").",". - $ilDB->quote((int) $a_sub_obj_id, "integer").",". - $ilDB->quote($a_sub_obj_type, "text").",". - $ilDB->quote($a_category_id, "integer").",". - $ilDB->quote((int) $a_rating, "integer").",". - $ilDB->quote(time(), "integer").")"); - } - } - - /** - * Reset rating for a user and an object. - * - * @param int $a_obj_id Object ID - * @param string $a_obj_type Object Type - * @param int $a_sub_obj_id Subobject ID - * @param string $a_sub_obj_type Subobject Type - * @param int $a_user_id User ID - */ - public static function resetRatingForUserAndObject($a_obj_id, $a_obj_type, $a_sub_obj_id, $a_sub_obj_type, - $a_user_id) - { - global $DIC; + if ($a_user_id == ANONYMOUS_USER_ID) { + return; + } + + if ($a_category_id) { + $ilDB->manipulate("DELETE FROM il_rating WHERE " . + "user_id = " . $ilDB->quote($a_user_id, "integer") . " AND " . + "obj_id = " . $ilDB->quote((int) $a_obj_id, "integer") . " AND " . + "obj_type = " . $ilDB->quote($a_obj_type, "text") . " AND " . + "sub_obj_id = " . $ilDB->quote((int) $a_sub_obj_id, "integer") . " AND " . + $ilDB->equals("sub_obj_type", $a_sub_obj_type, "text", true) . " AND " . + "category_id = " . $ilDB->quote(0, "integer")); + } + + $ilDB->manipulate("DELETE FROM il_rating WHERE " . + "user_id = " . $ilDB->quote($a_user_id, "integer") . " AND " . + "obj_id = " . $ilDB->quote((int) $a_obj_id, "integer") . " AND " . + "obj_type = " . $ilDB->quote($a_obj_type, "text") . " AND " . + "sub_obj_id = " . $ilDB->quote((int) $a_sub_obj_id, "integer") . " AND " . + $ilDB->equals("sub_obj_type", $a_sub_obj_type, "text", true) . " AND " . + "category_id = " . $ilDB->quote((int) $a_category_id, "integer")); + + if ((int) $a_rating) { + $ilDB->manipulate("INSERT INTO il_rating (user_id, obj_id, obj_type," . + "sub_obj_id, sub_obj_type, category_id, rating, tstamp) VALUES (" . + $ilDB->quote($a_user_id, "integer") . "," . + $ilDB->quote((int) $a_obj_id, "integer") . "," . + $ilDB->quote($a_obj_type, "text") . "," . + $ilDB->quote((int) $a_sub_obj_id, "integer") . "," . + $ilDB->quote($a_sub_obj_type, "text") . "," . + $ilDB->quote($a_category_id, "integer") . "," . + $ilDB->quote((int) $a_rating, "integer") . "," . + $ilDB->quote(time(), "integer") . ")"); + } + } + + /** + * Reset rating for a user and an object. + * + * @param int $a_obj_id Object ID + * @param string $a_obj_type Object Type + * @param int $a_sub_obj_id Subobject ID + * @param string $a_sub_obj_type Subobject Type + * @param int $a_user_id User ID + */ + public static function resetRatingForUserAndObject( + $a_obj_id, + $a_obj_type, + $a_sub_obj_id, + $a_sub_obj_type, + $a_user_id + ) { + global $DIC; - $ilDB = $DIC->database(); - - $ilDB->manipulate("DELETE FROM il_rating WHERE ". - "user_id = ".$ilDB->quote($a_user_id, "integer")." AND ". - "obj_id = ".$ilDB->quote((int) $a_obj_id, "integer")." AND ". - "obj_type = ".$ilDB->quote($a_obj_type, "text")." AND ". - "sub_obj_id = ".$ilDB->quote((int) $a_sub_obj_id, "integer")." AND ". - $ilDB->equals("sub_obj_type", $a_sub_obj_type, "text", true)); - } - - - /** - * Get rating for a user and an object. - * - * @param int $a_obj_id Object ID - * @param string $a_obj_type Object Type - * @param int $a_sub_obj_id Subobject ID - * @param string $a_sub_obj_type Subobject Type - * @param int $a_user_id User ID - * @param int $a_category_id Category ID - */ - public static function getRatingForUserAndObject($a_obj_id, $a_obj_type, $a_sub_obj_id, $a_sub_obj_type, - $a_user_id, $a_category_id = null) - { - global $DIC; + $ilDB = $DIC->database(); + + $ilDB->manipulate("DELETE FROM il_rating WHERE " . + "user_id = " . $ilDB->quote($a_user_id, "integer") . " AND " . + "obj_id = " . $ilDB->quote((int) $a_obj_id, "integer") . " AND " . + "obj_type = " . $ilDB->quote($a_obj_type, "text") . " AND " . + "sub_obj_id = " . $ilDB->quote((int) $a_sub_obj_id, "integer") . " AND " . + $ilDB->equals("sub_obj_type", $a_sub_obj_type, "text", true)); + } + + + /** + * Get rating for a user and an object. + * + * @param int $a_obj_id Object ID + * @param string $a_obj_type Object Type + * @param int $a_sub_obj_id Subobject ID + * @param string $a_sub_obj_type Subobject Type + * @param int $a_user_id User ID + * @param int $a_category_id Category ID + */ + public static function getRatingForUserAndObject( + $a_obj_id, + $a_obj_type, + $a_sub_obj_id, + $a_sub_obj_type, + $a_user_id, + $a_category_id = null + ) { + global $DIC; - $ilDB = $DIC->database(); - - if(is_array(self::$list_data)) - { - return self::$list_data["user"][$a_obj_type."/".$a_obj_id]; - } - - $q = "SELECT AVG(rating) av FROM il_rating WHERE ". - "user_id = ".$ilDB->quote($a_user_id, "integer")." AND ". - "obj_id = ".$ilDB->quote((int) $a_obj_id, "integer")." AND ". - "obj_type = ".$ilDB->quote($a_obj_type, "text")." AND ". - "sub_obj_id = ".$ilDB->quote((int) $a_sub_obj_id, "integer")." AND ". - $ilDB->equals("sub_obj_type", $a_sub_obj_type, "text", true); - if ($a_category_id !== null) - { - $q .= " AND category_id = ".$ilDB->quote((int) $a_category_id, "integer"); - } - $set = $ilDB->query($q); - $rec = $ilDB->fetchAssoc($set); - return $rec["av"]; - } - - /** - * Get overall rating for an object. - * - * @param int $a_obj_id Object ID - * @param string $a_obj_type Object Type - * @param int $a_sub_obj_id Subobject ID - * @param string $a_sub_obj_type Subobject Type - * @param int $a_category_id Category ID - */ - public static function getOverallRatingForObject($a_obj_id, $a_obj_type, $a_sub_obj_id = null, $a_sub_obj_type = null, $a_category_id = null) - { - global $DIC; + $ilDB = $DIC->database(); + + if (is_array(self::$list_data)) { + return self::$list_data["user"][$a_obj_type . "/" . $a_obj_id]; + } + + $q = "SELECT AVG(rating) av FROM il_rating WHERE " . + "user_id = " . $ilDB->quote($a_user_id, "integer") . " AND " . + "obj_id = " . $ilDB->quote((int) $a_obj_id, "integer") . " AND " . + "obj_type = " . $ilDB->quote($a_obj_type, "text") . " AND " . + "sub_obj_id = " . $ilDB->quote((int) $a_sub_obj_id, "integer") . " AND " . + $ilDB->equals("sub_obj_type", $a_sub_obj_type, "text", true); + if ($a_category_id !== null) { + $q .= " AND category_id = " . $ilDB->quote((int) $a_category_id, "integer"); + } + $set = $ilDB->query($q); + $rec = $ilDB->fetchAssoc($set); + return $rec["av"]; + } + + /** + * Get overall rating for an object. + * + * @param int $a_obj_id Object ID + * @param string $a_obj_type Object Type + * @param int $a_sub_obj_id Subobject ID + * @param string $a_sub_obj_type Subobject Type + * @param int $a_category_id Category ID + */ + public static function getOverallRatingForObject($a_obj_id, $a_obj_type, $a_sub_obj_id = null, $a_sub_obj_type = null, $a_category_id = null) + { + global $DIC; - $ilDB = $DIC->database(); - - if(is_array(self::$list_data)) - { - return self::$list_data["all"][$a_obj_type."/".$a_obj_id]; - } - - $q = "SELECT AVG(rating) av FROM il_rating". - " WHERE obj_id = ".$ilDB->quote((int) $a_obj_id, "integer"). - " AND obj_type = ".$ilDB->quote($a_obj_type, "text"); - if($a_sub_obj_id) - { - $q .= " AND sub_obj_id = ".$ilDB->quote((int) $a_sub_obj_id, "integer"). - " AND ".$ilDB->equals("sub_obj_type", $a_sub_obj_type, "text", true); - } - else - { - $q .= " AND sub_obj_type = ".$ilDB->quote("-", "text"); // #13913 - } - - if ($a_category_id !== null) - { - $q .= " AND category_id = ".$ilDB->quote((int) $a_category_id, "integer"); - } - $q .= " GROUP BY user_id"; - $set = $ilDB->query($q); - $avg = $cnt = 0; - while($rec = $ilDB->fetchAssoc($set)) - { - $cnt++; - $avg += $rec["av"]; - } - if ($cnt > 0) - { - $avg = $avg/$cnt; - } - else - { - $avg = 0; - } - return array("cnt" => $cnt, "avg" => $avg); - } + $ilDB = $DIC->database(); + + if (is_array(self::$list_data)) { + return self::$list_data["all"][$a_obj_type . "/" . $a_obj_id]; + } + + $q = "SELECT AVG(rating) av FROM il_rating" . + " WHERE obj_id = " . $ilDB->quote((int) $a_obj_id, "integer") . + " AND obj_type = " . $ilDB->quote($a_obj_type, "text"); + if ($a_sub_obj_id) { + $q .= " AND sub_obj_id = " . $ilDB->quote((int) $a_sub_obj_id, "integer") . + " AND " . $ilDB->equals("sub_obj_type", $a_sub_obj_type, "text", true); + } else { + $q .= " AND sub_obj_type = " . $ilDB->quote("-", "text"); // #13913 + } + + if ($a_category_id !== null) { + $q .= " AND category_id = " . $ilDB->quote((int) $a_category_id, "integer"); + } + $q .= " GROUP BY user_id"; + $set = $ilDB->query($q); + $avg = $cnt = 0; + while ($rec = $ilDB->fetchAssoc($set)) { + $cnt++; + $avg += $rec["av"]; + } + if ($cnt > 0) { + $avg = $avg/$cnt; + } else { + $avg = 0; + } + return array("cnt" => $cnt, "avg" => $avg); + } - /** - * Get export data - * - * @param int $a_obj_id - * @param string $a_obj_type - * @param array $a_category_ids - * @return array - */ - public static function getExportData($a_obj_id, $a_obj_type, array $a_category_ids = null) - { - global $DIC; + /** + * Get export data + * + * @param int $a_obj_id + * @param string $a_obj_type + * @param array $a_category_ids + * @return array + */ + public static function getExportData($a_obj_id, $a_obj_type, array $a_category_ids = null) + { + global $DIC; - $ilDB = $DIC->database(); - - $res = array(); - $q = "SELECT sub_obj_id, sub_obj_type, rating, category_id, user_id, tstamp ". - "FROM il_rating WHERE ". - "obj_id = ".$ilDB->quote((int) $a_obj_id, "integer")." AND ". - "obj_type = ".$ilDB->quote($a_obj_type, "text"). - " ORDER BY tstamp"; - if($a_category_ids) - { - $q .= " AND ".$ilDB->in("category_id", $a_category_ids, "", "integer"); - } - $set = $ilDB->query($q); - while($row = $ilDB->fetchAssoc($set)) - { - $res[] = $row; - } - return $res; - } - - /** - * Preload rating data for list guis - * - * @param array $a_obj_ids - */ - public static function preloadListGUIData(array $a_obj_ids) - { - global $DIC; + $ilDB = $DIC->database(); + + $res = array(); + $q = "SELECT sub_obj_id, sub_obj_type, rating, category_id, user_id, tstamp " . + "FROM il_rating WHERE " . + "obj_id = " . $ilDB->quote((int) $a_obj_id, "integer") . " AND " . + "obj_type = " . $ilDB->quote($a_obj_type, "text") . + " ORDER BY tstamp"; + if ($a_category_ids) { + $q .= " AND " . $ilDB->in("category_id", $a_category_ids, "", "integer"); + } + $set = $ilDB->query($q); + while ($row = $ilDB->fetchAssoc($set)) { + $res[] = $row; + } + return $res; + } + + /** + * Preload rating data for list guis + * + * @param array $a_obj_ids + */ + public static function preloadListGUIData(array $a_obj_ids) + { + global $DIC; - $ilDB = $DIC->database(); - $ilUser = $DIC->user(); - - $tmp = $res = $tmp_user = $res_user = array(); - - // collapse by categories - $q = "SELECT obj_id, obj_type, user_id, AVG(rating) av". - " FROM il_rating". - " WHERE ".$ilDB->in("obj_id", $a_obj_ids, "", "integer"). - " AND sub_obj_id = ".$ilDB->quote(0, "integer"). - " GROUP BY obj_id, obj_type, user_id"; - $set = $ilDB->query($q); - while($rec = $ilDB->fetchAssoc($set)) - { - $tmp[$rec["obj_type"]."/".$rec["obj_id"]][$rec["user_id"]] = (float)$rec["av"]; - if($rec["user_id"] == $ilUser->getId()) - { - // add final average to user result (no sub-objects) - $res_user[$rec["obj_type"]."/".$rec["obj_id"]] = (float)$rec["av"]; - } - } - - // average for main objects without sub-objects - foreach($tmp as $obj_id => $votes) - { - $res[$obj_id] = array("avg"=>array_sum($votes)/sizeof($votes), - "cnt"=>sizeof($votes)); - } - - // file/wiki/lm rating toggles - - $set = $ilDB->query("SELECT file_id, rating". - " FROM file_data". - " WHERE ".$ilDB->in("file_id", $a_obj_ids, "", 'integer')); - while($row = $ilDB->fetchAssoc($set)) - { - $id = "file/".$row["file_id"]; - if($row["rating"] && !isset($res[$id])) - { - $res[$id] = array("avg"=>0, "cnt"=>0); - } - else if(!$row["rating"] && isset($res[$id])) - { - unset($res[$id]); - } - } - - $set = $ilDB->query("SELECT id, rating_overall". - " FROM il_wiki_data". - " WHERE ".$ilDB->in("id", $a_obj_ids, "", 'integer')); - while($row = $ilDB->fetchAssoc($set)) - { - $id = "wiki/".$row["id"]; - if($row["rating_overall"] && !isset($res[$id])) - { - $res[$id] = array("avg"=>0, "cnt"=>0); - } - else if(!$row["rating_overall"] && isset($res[$id])) - { - unset($res[$id]); - } - } - - $set = $ilDB->query("SELECT id, rating". - " FROM content_object". - " WHERE ".$ilDB->in("id", $a_obj_ids, "", 'integer')); - while($row = $ilDB->fetchAssoc($set)) - { - $id = "lm/".$row["id"]; - if($row["rating"] && !isset($res[$id])) - { - $res[$id] = array("avg"=>0, "cnt"=>0); - } - else if(!$row["rating"] && isset($res[$id])) - { - unset($res[$id]); - } - } - - self::$list_data = array("all"=>$res, "user"=>$res_user); - } - - public static function hasRatingInListGUI($a_obj_id, $a_obj_type) - { - return isset(self::$list_data["all"][$a_obj_type."/".$a_obj_id]); - } + $ilDB = $DIC->database(); + $ilUser = $DIC->user(); + + $tmp = $res = $tmp_user = $res_user = array(); + + // collapse by categories + $q = "SELECT obj_id, obj_type, user_id, AVG(rating) av" . + " FROM il_rating" . + " WHERE " . $ilDB->in("obj_id", $a_obj_ids, "", "integer") . + " AND sub_obj_id = " . $ilDB->quote(0, "integer") . + " GROUP BY obj_id, obj_type, user_id"; + $set = $ilDB->query($q); + while ($rec = $ilDB->fetchAssoc($set)) { + $tmp[$rec["obj_type"] . "/" . $rec["obj_id"]][$rec["user_id"]] = (float) $rec["av"]; + if ($rec["user_id"] == $ilUser->getId()) { + // add final average to user result (no sub-objects) + $res_user[$rec["obj_type"] . "/" . $rec["obj_id"]] = (float) $rec["av"]; + } + } + + // average for main objects without sub-objects + foreach ($tmp as $obj_id => $votes) { + $res[$obj_id] = array("avg"=>array_sum($votes)/sizeof($votes), + "cnt"=>sizeof($votes)); + } + + // file/wiki/lm rating toggles + + $set = $ilDB->query("SELECT file_id, rating" . + " FROM file_data" . + " WHERE " . $ilDB->in("file_id", $a_obj_ids, "", 'integer')); + while ($row = $ilDB->fetchAssoc($set)) { + $id = "file/" . $row["file_id"]; + if ($row["rating"] && !isset($res[$id])) { + $res[$id] = array("avg"=>0, "cnt"=>0); + } elseif (!$row["rating"] && isset($res[$id])) { + unset($res[$id]); + } + } + + $set = $ilDB->query("SELECT id, rating_overall" . + " FROM il_wiki_data" . + " WHERE " . $ilDB->in("id", $a_obj_ids, "", 'integer')); + while ($row = $ilDB->fetchAssoc($set)) { + $id = "wiki/" . $row["id"]; + if ($row["rating_overall"] && !isset($res[$id])) { + $res[$id] = array("avg"=>0, "cnt"=>0); + } elseif (!$row["rating_overall"] && isset($res[$id])) { + unset($res[$id]); + } + } + + $set = $ilDB->query("SELECT id, rating" . + " FROM content_object" . + " WHERE " . $ilDB->in("id", $a_obj_ids, "", 'integer')); + while ($row = $ilDB->fetchAssoc($set)) { + $id = "lm/" . $row["id"]; + if ($row["rating"] && !isset($res[$id])) { + $res[$id] = array("avg"=>0, "cnt"=>0); + } elseif (!$row["rating"] && isset($res[$id])) { + unset($res[$id]); + } + } + + self::$list_data = array("all"=>$res, "user"=>$res_user); + } + + public static function hasRatingInListGUI($a_obj_id, $a_obj_type) + { + return isset(self::$list_data["all"][$a_obj_type . "/" . $a_obj_id]); + } } - -?> \ No newline at end of file diff --git a/Services/Rating/classes/class.ilRatingCategory.php b/Services/Rating/classes/class.ilRatingCategory.php index 6a763882f08a29c10be17c05c63006582f974c56..d29de5a2761311aa439267a7e7352cbe690f721d 100644 --- a/Services/Rating/classes/class.ilRatingCategory.php +++ b/Services/Rating/classes/class.ilRatingCategory.php @@ -1,290 +1,284 @@ - -* @version $Id$ -* -* @ingroup ServicesRating -*/ -class ilRatingCategory -{ - /** - * @var ilDB - */ - protected $db; +db = $DIC->database(); - $this->read($a_id); - } - - /** - * Set id - * - * @param int $a_value - */ - public function setId($a_value) - { - $this->id = (int)$a_value; - } - - /** - * Get id - * - * @return int - */ - public function getId() - { - return $this->id; - } - - /** - * Set parent id - * - * @param int $a_value - */ - public function setParentId($a_value) - { - $this->parent_id = (int)$a_value; - } - - /** - * Get parent object id - * - * @return int - */ - public function getParentId() - { - return $this->parent_id; - } - - /** - * Set title - * - * @param string $a_value - */ - public function setTitle($a_value) - { - $this->title = (string)$a_value; - } - - /** - * Get title - * - * @return string - */ - public function getTitle() - { - return $this->title; - } - - /** - * Set description - * - * @param string $a_value - */ - public function setDescription($a_value) - { - $this->description = (string)$a_value; - } - - /** - * Get description - * - * @return string - */ - public function getDescription() - { - return $this->description; - } - - /** - * Set position - * - * @param int $a_value - */ - public function setPosition($a_value) - { - $this->pos = (int)$a_value; - } - - /** - * Get position - * - * @return int - */ - public function getPosition() - { - return $this->pos; - } - - /** - * Load db entry - * - * @param int $a_id - */ - protected function read($a_id) - { - $ilDB = $this->db; - - $a_id = (int)$a_id; - if($a_id) - { - $sql = "SELECT * FROM il_rating_cat". - " WHERE id = ".$ilDB->quote($a_id, "integer"); - $set = $ilDB->query($sql); - $row = $ilDB->fetchAssoc($set); - if($row["id"]) - { - $this->setId($row["id"]); - $this->setParentId($row["parent_id"]); - $this->setTitle($row["title"]); - $this->setDescription($row["description"]); - $this->setPosition($row["pos"]); - } - } - } - - /** - * Parse properties into db definition - * - * @return array - */ - protected function getDBProperties() - { - // parent id must not change - $fields = array("title" => array("text", $this->getTitle()), - "description" => array("text", $this->getDescription()), - "pos" => array("integer", $this->getPosition())); - - return $fields; - } - - /** - * Update db entry - */ - public function update() - { - $ilDB = $this->db; - - if($this->getId()) - { - $fields = $this->getDBProperties(); - - $ilDB->update("il_rating_cat", $fields, - array("id" => array("integer", $this->getId()))); - } - } - - /** - * Create db entry - */ - public function save() - { - $ilDB = $this->db; - - $id = $ilDB->nextId("il_rating_cat"); - $this->setId($id); - - // append - $sql = "SELECT max(pos) pos FROM il_rating_cat". - " WHERE parent_id = ".$ilDB->quote($this->getParentId(), "integer"); - $set = $ilDB->query($sql); - $pos = $ilDB->fetchAssoc($set); - $pos = $pos["pos"]; - $this->setPosition($pos+10); - - $fields = $this->getDBProperties(); - $fields["id"] = array("integer", $id); - $fields["parent_id"] = array("integer", $this->getParentId()); - - $ilDB->insert("il_rating_cat", $fields); - } - - /** - * Delete db entry - * - * @param int $a_id - */ - public static function delete($a_id) - { - global $DIC; +/** +* Class ilRatingCategory +* +* @author Jörg Lützenkirchen +* @version $Id$ +* +* @ingroup ServicesRating +*/ +class ilRatingCategory +{ + /** + * @var ilDB + */ + protected $db; - $ilDB = $DIC->database(); - - if((int)$a_id) - { - $sql = "DELETE FROM il_rating". - " WHERE category_id = ".$ilDB->quote($a_id, "integer"); - $ilDB->manipulate($sql); - - $sql = "DELETE FROM il_rating_cat". - " WHERE id = ".$ilDB->quote($a_id, "integer"); - $ilDB->manipulate($sql); - } - } - - /** - * Get all categories for object - * - * @param int $a_parent_obj_id - * @return array - */ - public static function getAllForObject($a_parent_obj_id) - { - global $DIC; + protected $id; // [int] sequence + protected $parent_id; // [int] parent object + protected $title; // [string] + protected $description; // [string] + protected $pos; // [int] order + + /** + * Constructor + * + * @param int $a_id + */ + public function __construct($a_id = null) + { + global $DIC; - $ilDB = $DIC->database(); - - $cats = array(); - - $sql = "SELECT * FROM il_rating_cat". - " WHERE parent_id = ".$ilDB->quote($a_parent_obj_id, "integer"). - " ORDER BY pos"; - $set = $ilDB->query($sql); - while($row = $ilDB->fetchAssoc($set)) - { - $cats[] = $row; - } - - return $cats; - } - - /** - * Delete all categories for object - * - * @param int $a_parent_obj_id - */ - public static function deleteForObject($a_parent_obj_id) - { - if((int)$a_parent_obj_id) - { - foreach(self::getAllForObject($a_parent_obj_id) as $item) - { - self::delete($item["id"]); - } - } - } -} - -?> \ No newline at end of file + $this->db = $DIC->database(); + $this->read($a_id); + } + + /** + * Set id + * + * @param int $a_value + */ + public function setId($a_value) + { + $this->id = (int) $a_value; + } + + /** + * Get id + * + * @return int + */ + public function getId() + { + return $this->id; + } + + /** + * Set parent id + * + * @param int $a_value + */ + public function setParentId($a_value) + { + $this->parent_id = (int) $a_value; + } + + /** + * Get parent object id + * + * @return int + */ + public function getParentId() + { + return $this->parent_id; + } + + /** + * Set title + * + * @param string $a_value + */ + public function setTitle($a_value) + { + $this->title = (string) $a_value; + } + + /** + * Get title + * + * @return string + */ + public function getTitle() + { + return $this->title; + } + + /** + * Set description + * + * @param string $a_value + */ + public function setDescription($a_value) + { + $this->description = (string) $a_value; + } + + /** + * Get description + * + * @return string + */ + public function getDescription() + { + return $this->description; + } + + /** + * Set position + * + * @param int $a_value + */ + public function setPosition($a_value) + { + $this->pos = (int) $a_value; + } + + /** + * Get position + * + * @return int + */ + public function getPosition() + { + return $this->pos; + } + + /** + * Load db entry + * + * @param int $a_id + */ + protected function read($a_id) + { + $ilDB = $this->db; + + $a_id = (int) $a_id; + if ($a_id) { + $sql = "SELECT * FROM il_rating_cat" . + " WHERE id = " . $ilDB->quote($a_id, "integer"); + $set = $ilDB->query($sql); + $row = $ilDB->fetchAssoc($set); + if ($row["id"]) { + $this->setId($row["id"]); + $this->setParentId($row["parent_id"]); + $this->setTitle($row["title"]); + $this->setDescription($row["description"]); + $this->setPosition($row["pos"]); + } + } + } + + /** + * Parse properties into db definition + * + * @return array + */ + protected function getDBProperties() + { + // parent id must not change + $fields = array("title" => array("text", $this->getTitle()), + "description" => array("text", $this->getDescription()), + "pos" => array("integer", $this->getPosition())); + + return $fields; + } + + /** + * Update db entry + */ + public function update() + { + $ilDB = $this->db; + + if ($this->getId()) { + $fields = $this->getDBProperties(); + + $ilDB->update( + "il_rating_cat", + $fields, + array("id" => array("integer", $this->getId())) + ); + } + } + + /** + * Create db entry + */ + public function save() + { + $ilDB = $this->db; + + $id = $ilDB->nextId("il_rating_cat"); + $this->setId($id); + + // append + $sql = "SELECT max(pos) pos FROM il_rating_cat" . + " WHERE parent_id = " . $ilDB->quote($this->getParentId(), "integer"); + $set = $ilDB->query($sql); + $pos = $ilDB->fetchAssoc($set); + $pos = $pos["pos"]; + $this->setPosition($pos+10); + + $fields = $this->getDBProperties(); + $fields["id"] = array("integer", $id); + $fields["parent_id"] = array("integer", $this->getParentId()); + + $ilDB->insert("il_rating_cat", $fields); + } + + /** + * Delete db entry + * + * @param int $a_id + */ + public static function delete($a_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + if ((int) $a_id) { + $sql = "DELETE FROM il_rating" . + " WHERE category_id = " . $ilDB->quote($a_id, "integer"); + $ilDB->manipulate($sql); + + $sql = "DELETE FROM il_rating_cat" . + " WHERE id = " . $ilDB->quote($a_id, "integer"); + $ilDB->manipulate($sql); + } + } + + /** + * Get all categories for object + * + * @param int $a_parent_obj_id + * @return array + */ + public static function getAllForObject($a_parent_obj_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $cats = array(); + + $sql = "SELECT * FROM il_rating_cat" . + " WHERE parent_id = " . $ilDB->quote($a_parent_obj_id, "integer") . + " ORDER BY pos"; + $set = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($set)) { + $cats[] = $row; + } + + return $cats; + } + + /** + * Delete all categories for object + * + * @param int $a_parent_obj_id + */ + public static function deleteForObject($a_parent_obj_id) + { + if ((int) $a_parent_obj_id) { + foreach (self::getAllForObject($a_parent_obj_id) as $item) { + self::delete($item["id"]); + } + } + } +} diff --git a/Services/Rating/classes/class.ilRatingCategoryGUI.php b/Services/Rating/classes/class.ilRatingCategoryGUI.php index 0abfdf1271cdf693ed944374ee31438f731331ab..41b4c10f826fa7cf422f3af18cad6f2748a5079e 100644 --- a/Services/Rating/classes/class.ilRatingCategoryGUI.php +++ b/Services/Rating/classes/class.ilRatingCategoryGUI.php @@ -1,347 +1,330 @@ - - * @version $Id$ - * - * @ingroup ServicesRating - */ -class ilRatingCategoryGUI -{ - /** - * @var ilLanguage - */ - protected $lng; + + * @version $Id$ + * + * @ingroup ServicesRating + */ +class ilRatingCategoryGUI +{ + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilToolbarGUI - */ - protected $toolbar; + /** + * @var ilCtrl + */ + protected $ctrl; - protected $parent_id; // [int] - protected $export_callback; // [string|array] - protected $export_subobj_title; // [string] - - function __construct($a_parent_id, $a_export_callback = null, $a_export_subobj_title = null) - { - global $DIC; + /** + * @var ilTemplate + */ + protected $tpl; - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $this->tpl = $DIC["tpl"]; - $this->toolbar = $DIC->toolbar(); - $lng = $DIC->language(); - - $this->parent_id = (int)$a_parent_id; - $this->export_callback = $a_export_callback; - $this->export_subobj_title = $a_export_subobj_title; - - $lng->loadLanguageModule("rating"); - - if($_REQUEST["cat_id"]) - { - $cat = new ilRatingCategory($_REQUEST["cat_id"]); - if($cat->getParentId() == $this->parent_id) - { - $this->cat_id = $cat->getId(); - } - } - } - - /** - * execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd("listCategories"); - - switch($next_class) - { - default: - return $this->$cmd(); - break; - } - } - - protected function listCategories() - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $ilToolbar->addButton($lng->txt("rating_add_category"), - $ilCtrl->getLinkTarget($this, "add")); - - $ilToolbar->addSeparator(); - - $ilToolbar->addButton($lng->txt("export"), - $ilCtrl->getLinkTarget($this, "export")); - - include_once "Services/Rating/classes/class.ilRatingCategoryTableGUI.php"; - $table = new ilRatingCategoryTableGUI($this, "listCategories", $this->parent_id); - $tpl->setContent($table->getHTML()); - } - - - protected function initCategoryForm($a_id = null) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setTarget("_top"); - $form->setFormAction($ilCtrl->getFormAction($this, "save")); - $form->setTitle($lng->txt("rating_category_".($a_id ? "edit" : "create"))); - - // title - $ti = new ilTextInputGUI($lng->txt("title"), "title"); - $ti->setMaxLength(128); - $ti->setSize(40); - $ti->setRequired(true); - $form->addItem($ti); - - // description - $ta = new ilTextAreaInputGUI($lng->txt("description"), "desc"); - $ta->setCols(40); - $ta->setRows(2); - $form->addItem($ta); - - if(!$a_id) - { - $form->addCommandButton("save", $lng->txt("rating_category_add")); - } - else - { - $cat = new ilRatingCategory($a_id); - $ti->setValue($cat->getTitle()); - $ta->setValue($cat->getDescription()); - - $form->addCommandButton("update", $lng->txt("rating_category_update")); - } - $form->addCommandButton("listCategories", $lng->txt("cancel")); - - return $form; - } - - protected function add($a_form = null) - { - $tpl = $this->tpl; - - if(!$a_form) - { - $a_form = $this->initCategoryForm(); - } - - $tpl->setContent($a_form->getHTML()); - } - - protected function save() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $form = $this->initCategoryForm("create"); - if($form->checkInput()) - { - include_once "Services/Rating/classes/class.ilRatingCategory.php"; - $cat = new ilRatingCategory(); - $cat->setParentId($this->parent_id); - $cat->setTitle($form->getInput("title")); - $cat->setDescription($form->getInput("desc")); - $cat->save(); - - ilUtil::sendSuccess($lng->txt("rating_category_created")); - $ilCtrl->redirect($this, "listCategories"); - } - - $form->setValuesByPost(); - $this->add($form); - } - - protected function edit($a_form = null) - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameter($this, "cat_id", $this->cat_id); - - if(!$a_form) - { - $a_form = $this->initCategoryForm($this->cat_id); - } - - $tpl->setContent($a_form->getHTML()); - } - - protected function update() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $form = $this->initCategoryForm($this->cat_id); - if($form->checkInput()) - { - include_once "Services/Rating/classes/class.ilRatingCategory.php"; - $cat = new ilRatingCategory($this->cat_id); - $cat->setTitle($form->getInput("title")); - $cat->setDescription($form->getInput("desc")); - $cat->update(); - - ilUtil::sendSuccess($lng->txt("rating_category_updated")); - $ilCtrl->redirect($this, "listCategories"); - } - - $form->setValuesByPost(); - $this->add($form); - } - - protected function updateOrder() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $order = $_POST["pos"]; - asort($order); - - $cnt = 0; - foreach($order as $id => $pos) - { - $cat = new ilRatingCategory($id); - if($cat->getParentId() == $this->parent_id) - { - $cnt += 10; - $cat->setPosition($cnt); - $cat->update(); - } - } - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - $ilCtrl->redirect($this, "listCategories"); - } - - protected function confirmDelete() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if(!$this->cat_id) - { - return $this->listCategories(); - } - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setHeaderText($lng->txt("rating_category_delete_sure")."
                  ". - $lng->txt("info_delete_warning_no_trash")); - - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setCancel($lng->txt("cancel"), "listCategories"); - $cgui->setConfirm($lng->txt("confirm"), "delete"); - - $cat = new ilRatingCategory($this->cat_id); - $cgui->addItem("cat_id", $this->cat_id, $cat->getTitle()); - - $tpl->setContent($cgui->getHTML()); - } - - protected function delete() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if($this->cat_id) - { - ilRatingCategory::delete($this->cat_id); - ilUtil::sendSuccess($lng->txt("rating_category_deleted"), true); - } - - // fix order - $cnt = 0; - foreach(ilRatingCategory::getAllForObject($this->parent_id) as $item) - { - $cnt += 10; - - $cat = new ilRatingCategory($item["id"]); - $cat->setPosition($cnt); - $cat->update(); - } - - $ilCtrl->redirect($this, "listCategories"); - } - - protected function export() - { - $lng = $this->lng; - - include_once "./Services/Excel/classes/class.ilExcel.php"; - $excel = new ilExcel(); - $excel->addSheet($lng->txt("rating_categories")); - - // restrict to currently active (probably not needed - see delete()) - $active = array(); - foreach(ilRatingCategory::getAllForObject($this->parent_id) as $item) - { - $active[$item["id"]] = $item["title"]; - } - - // title row - $row = 1; - $excel->setCell($row, 0, $this->export_subobj_title." (".$lng->txt("id").")"); - $excel->setCell($row, 1, $this->export_subobj_title); - $excel->setCell($row, 2, $lng->txt("rating_export_category")." (".$lng->txt("id").")"); - $excel->setCell($row, 3, $lng->txt("rating_export_category")); - $excel->setCell($row, 4, $lng->txt("rating_export_date")); - $excel->setCell($row, 5, $lng->txt("rating_export_rating")); - $excel->setBold("A1:F1"); - - // content rows - foreach(ilRating::getExportData($this->parent_id, ilObject::_lookupType($this->parent_id), array_keys($active)) as $item) - { - // overall rating? - if(!$item["sub_obj_id"]) - { - continue; - } - - $row++; - - $sub_obj_title = $item["sub_obj_type"]; - if($this->export_callback) - { - $sub_obj_title = call_user_func($this->export_callback, $item["sub_obj_id"], $item["sub_obj_type"]); - } - - $excel->setCell($row, 0, (int)$item["sub_obj_id"]); - $excel->setCell($row, 1, $sub_obj_title); - $excel->setCell($row, 2, (int)$item["category_id"]); - $excel->setCell($row, 3, $active[$item["category_id"]]); - $excel->setCell($row, 4, new ilDateTime($item["tstamp"], IL_CAL_UNIX)); - $excel->setCell($row, 5, $item["rating"]); - } - - $excel->sendToClient(ilObject::_lookupTitle($this->parent_id)); - } -} - -?> + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + protected $parent_id; // [int] + protected $export_callback; // [string|array] + protected $export_subobj_title; // [string] + + public function __construct($a_parent_id, $a_export_callback = null, $a_export_subobj_title = null) + { + global $DIC; + + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->tpl = $DIC["tpl"]; + $this->toolbar = $DIC->toolbar(); + $lng = $DIC->language(); + + $this->parent_id = (int) $a_parent_id; + $this->export_callback = $a_export_callback; + $this->export_subobj_title = $a_export_subobj_title; + + $lng->loadLanguageModule("rating"); + + if ($_REQUEST["cat_id"]) { + $cat = new ilRatingCategory($_REQUEST["cat_id"]); + if ($cat->getParentId() == $this->parent_id) { + $this->cat_id = $cat->getId(); + } + } + } + + /** + * execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd("listCategories"); + + switch ($next_class) { + default: + return $this->$cmd(); + break; + } + } + + protected function listCategories() + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $ilToolbar->addButton( + $lng->txt("rating_add_category"), + $ilCtrl->getLinkTarget($this, "add") + ); + + $ilToolbar->addSeparator(); + + $ilToolbar->addButton( + $lng->txt("export"), + $ilCtrl->getLinkTarget($this, "export") + ); + + include_once "Services/Rating/classes/class.ilRatingCategoryTableGUI.php"; + $table = new ilRatingCategoryTableGUI($this, "listCategories", $this->parent_id); + $tpl->setContent($table->getHTML()); + } + + + protected function initCategoryForm($a_id = null) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setTarget("_top"); + $form->setFormAction($ilCtrl->getFormAction($this, "save")); + $form->setTitle($lng->txt("rating_category_" . ($a_id ? "edit" : "create"))); + + // title + $ti = new ilTextInputGUI($lng->txt("title"), "title"); + $ti->setMaxLength(128); + $ti->setSize(40); + $ti->setRequired(true); + $form->addItem($ti); + + // description + $ta = new ilTextAreaInputGUI($lng->txt("description"), "desc"); + $ta->setCols(40); + $ta->setRows(2); + $form->addItem($ta); + + if (!$a_id) { + $form->addCommandButton("save", $lng->txt("rating_category_add")); + } else { + $cat = new ilRatingCategory($a_id); + $ti->setValue($cat->getTitle()); + $ta->setValue($cat->getDescription()); + + $form->addCommandButton("update", $lng->txt("rating_category_update")); + } + $form->addCommandButton("listCategories", $lng->txt("cancel")); + + return $form; + } + + protected function add($a_form = null) + { + $tpl = $this->tpl; + + if (!$a_form) { + $a_form = $this->initCategoryForm(); + } + + $tpl->setContent($a_form->getHTML()); + } + + protected function save() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $form = $this->initCategoryForm("create"); + if ($form->checkInput()) { + include_once "Services/Rating/classes/class.ilRatingCategory.php"; + $cat = new ilRatingCategory(); + $cat->setParentId($this->parent_id); + $cat->setTitle($form->getInput("title")); + $cat->setDescription($form->getInput("desc")); + $cat->save(); + + ilUtil::sendSuccess($lng->txt("rating_category_created")); + $ilCtrl->redirect($this, "listCategories"); + } + + $form->setValuesByPost(); + $this->add($form); + } + + protected function edit($a_form = null) + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameter($this, "cat_id", $this->cat_id); + + if (!$a_form) { + $a_form = $this->initCategoryForm($this->cat_id); + } + + $tpl->setContent($a_form->getHTML()); + } + + protected function update() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $form = $this->initCategoryForm($this->cat_id); + if ($form->checkInput()) { + include_once "Services/Rating/classes/class.ilRatingCategory.php"; + $cat = new ilRatingCategory($this->cat_id); + $cat->setTitle($form->getInput("title")); + $cat->setDescription($form->getInput("desc")); + $cat->update(); + + ilUtil::sendSuccess($lng->txt("rating_category_updated")); + $ilCtrl->redirect($this, "listCategories"); + } + + $form->setValuesByPost(); + $this->add($form); + } + + protected function updateOrder() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $order = $_POST["pos"]; + asort($order); + + $cnt = 0; + foreach ($order as $id => $pos) { + $cat = new ilRatingCategory($id); + if ($cat->getParentId() == $this->parent_id) { + $cnt += 10; + $cat->setPosition($cnt); + $cat->update(); + } + } + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "listCategories"); + } + + protected function confirmDelete() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if (!$this->cat_id) { + return $this->listCategories(); + } + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setHeaderText($lng->txt("rating_category_delete_sure") . "
                  " . + $lng->txt("info_delete_warning_no_trash")); + + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setCancel($lng->txt("cancel"), "listCategories"); + $cgui->setConfirm($lng->txt("confirm"), "delete"); + + $cat = new ilRatingCategory($this->cat_id); + $cgui->addItem("cat_id", $this->cat_id, $cat->getTitle()); + + $tpl->setContent($cgui->getHTML()); + } + + protected function delete() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if ($this->cat_id) { + ilRatingCategory::delete($this->cat_id); + ilUtil::sendSuccess($lng->txt("rating_category_deleted"), true); + } + + // fix order + $cnt = 0; + foreach (ilRatingCategory::getAllForObject($this->parent_id) as $item) { + $cnt += 10; + + $cat = new ilRatingCategory($item["id"]); + $cat->setPosition($cnt); + $cat->update(); + } + + $ilCtrl->redirect($this, "listCategories"); + } + + protected function export() + { + $lng = $this->lng; + + include_once "./Services/Excel/classes/class.ilExcel.php"; + $excel = new ilExcel(); + $excel->addSheet($lng->txt("rating_categories")); + + // restrict to currently active (probably not needed - see delete()) + $active = array(); + foreach (ilRatingCategory::getAllForObject($this->parent_id) as $item) { + $active[$item["id"]] = $item["title"]; + } + + // title row + $row = 1; + $excel->setCell($row, 0, $this->export_subobj_title . " (" . $lng->txt("id") . ")"); + $excel->setCell($row, 1, $this->export_subobj_title); + $excel->setCell($row, 2, $lng->txt("rating_export_category") . " (" . $lng->txt("id") . ")"); + $excel->setCell($row, 3, $lng->txt("rating_export_category")); + $excel->setCell($row, 4, $lng->txt("rating_export_date")); + $excel->setCell($row, 5, $lng->txt("rating_export_rating")); + $excel->setBold("A1:F1"); + + // content rows + foreach (ilRating::getExportData($this->parent_id, ilObject::_lookupType($this->parent_id), array_keys($active)) as $item) { + // overall rating? + if (!$item["sub_obj_id"]) { + continue; + } + + $row++; + + $sub_obj_title = $item["sub_obj_type"]; + if ($this->export_callback) { + $sub_obj_title = call_user_func($this->export_callback, $item["sub_obj_id"], $item["sub_obj_type"]); + } + + $excel->setCell($row, 0, (int) $item["sub_obj_id"]); + $excel->setCell($row, 1, $sub_obj_title); + $excel->setCell($row, 2, (int) $item["category_id"]); + $excel->setCell($row, 3, $active[$item["category_id"]]); + $excel->setCell($row, 4, new ilDateTime($item["tstamp"], IL_CAL_UNIX)); + $excel->setCell($row, 5, $item["rating"]); + } + + $excel->sendToClient(ilObject::_lookupTitle($this->parent_id)); + } +} diff --git a/Services/Rating/classes/class.ilRatingCategoryTableGUI.php b/Services/Rating/classes/class.ilRatingCategoryTableGUI.php index 9968bdf6415b84c16bc93c54d981bf9c5f0ec6f6..b2c5ab0ab3fbd033e58f39b3b20460fa468f3dc2 100644 --- a/Services/Rating/classes/class.ilRatingCategoryTableGUI.php +++ b/Services/Rating/classes/class.ilRatingCategoryTableGUI.php @@ -1,98 +1,95 @@ - - * @version $Id$ - * - * @ingroup ServicesRating - */ -class ilRatingCategoryTableGUI extends ilTable2GUI -{ - /** - * @var ilCtrl - */ - protected $ctrl; +ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->setId("rtgcat"); - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->addColumn($this->lng->txt("position")); - $this->addColumn($this->lng->txt("title"), "title"); - $this->addColumn($this->lng->txt("description"), "description"); - $this->addColumn($this->lng->txt("actions")); - - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd)); - $this->setRowTemplate("tpl.rating_category_row.html", "Services/Rating"); - - $this->addCommandButton("updateorder", $lng->txt("rating_update_positions")); - - $this->getItems($a_parent_id); - } - - /** - * Build item rows for given object and filter(s) - * - * @param int $a_parent_obj_id - */ - function getItems($a_parent_obj_id) - { - include_once "Services/Rating/classes/class.ilRatingCategory.php"; - $data = ilRatingCategory::getAllForObject($a_parent_obj_id); - - $this->setMaxCount(sizeof($data)); - $this->setData($data); - } - - /** - * Fill table row - * @param array $a_set - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->tpl->setVariable("VAL_ID", $a_set["id"]); - $this->tpl->setVariable("VAL_POS", $a_set["pos"]); - $this->tpl->setVariable("TXT_TITLE", $a_set["title"]); - $this->tpl->setVariable("TXT_DESCRIPTION", nl2br($a_set["description"])); - - $ilCtrl->setParameter($this->parent_obj, "cat_id", $a_set["id"]); - - $items = array(); - $items["edit"] = array($lng->txt("edit"), $ilCtrl->getLinkTarget($this->parent_obj, "edit")); - $items["delete"] = array($lng->txt("delete"), $ilCtrl->getLinkTarget($this->parent_obj, "confirmDelete")); - - $this->tpl->setCurrentBlock("actions"); - foreach($items as $item) - { - $this->tpl->setVariable("ACTION_CAPTION", $item[0]); - $this->tpl->setVariable("ACTION_LINK", $item[1]); - $this->tpl->parseCurrentBlock(); - } - } -} - -?> \ No newline at end of file +/** + * List rating categories + * + * @author Jörg Lützenkirchen + * @version $Id$ + * + * @ingroup ServicesRating + */ +class ilRatingCategoryTableGUI extends ilTable2GUI +{ + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * Constructor + * @param object $a_parent_obj + * @param string $a_parent_cmd + * @param int $a_parent_id + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_parent_id) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->setId("rtgcat"); + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->addColumn($this->lng->txt("position")); + $this->addColumn($this->lng->txt("title"), "title"); + $this->addColumn($this->lng->txt("description"), "description"); + $this->addColumn($this->lng->txt("actions")); + + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj, $a_parent_cmd)); + $this->setRowTemplate("tpl.rating_category_row.html", "Services/Rating"); + + $this->addCommandButton("updateorder", $lng->txt("rating_update_positions")); + + $this->getItems($a_parent_id); + } + + /** + * Build item rows for given object and filter(s) + * + * @param int $a_parent_obj_id + */ + public function getItems($a_parent_obj_id) + { + include_once "Services/Rating/classes/class.ilRatingCategory.php"; + $data = ilRatingCategory::getAllForObject($a_parent_obj_id); + + $this->setMaxCount(sizeof($data)); + $this->setData($data); + } + + /** + * Fill table row + * @param array $a_set + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $this->tpl->setVariable("VAL_ID", $a_set["id"]); + $this->tpl->setVariable("VAL_POS", $a_set["pos"]); + $this->tpl->setVariable("TXT_TITLE", $a_set["title"]); + $this->tpl->setVariable("TXT_DESCRIPTION", nl2br($a_set["description"])); + + $ilCtrl->setParameter($this->parent_obj, "cat_id", $a_set["id"]); + + $items = array(); + $items["edit"] = array($lng->txt("edit"), $ilCtrl->getLinkTarget($this->parent_obj, "edit")); + $items["delete"] = array($lng->txt("delete"), $ilCtrl->getLinkTarget($this->parent_obj, "confirmDelete")); + + $this->tpl->setCurrentBlock("actions"); + foreach ($items as $item) { + $this->tpl->setVariable("ACTION_CAPTION", $item[0]); + $this->tpl->setVariable("ACTION_LINK", $item[1]); + $this->tpl->parseCurrentBlock(); + } + } +} diff --git a/Services/Rating/classes/class.ilRatingDataSet.php b/Services/Rating/classes/class.ilRatingDataSet.php index 6e79a8f2ca7344cad4b5a1e84b7571819ddac7e5..b7f42ba99051e785b1a8c4e7f76b195a1996dd28 100644 --- a/Services/Rating/classes/class.ilRatingDataSet.php +++ b/Services/Rating/classes/class.ilRatingDataSet.php @@ -5,7 +5,7 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); /** * Rating Data set class - * + * * This class implements the following entities: * - rating_category: data from il_rating_cat * @@ -15,116 +15,108 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); */ class ilRatingDataSet extends ilDataSet { - /** - * Get supported versions - * - * @param - * @return - */ - public function getSupportedVersions() - { - return array("4.3.0"); - } - - /** - * Get xml namespace - * - * @param - * @return - */ - function getXmlNamespace($a_entity, $a_schema_version) - { - return "http://www.ilias.de/xml/Services/Rating/".$a_entity; - } - - /** - * Get field types for entity - * - * @param - * @return - */ - protected function getTypes($a_entity, $a_version) - { - if ($a_entity == "rating_category") - { - switch ($a_version) - { - case "4.3.0": - return array( - "Id" => "integer", - "ParentId" => "integer", - "Title" => "text", - "Description" => "text", - "Pos" => "integer"); - } - } - } + /** + * Get supported versions + * + * @param + * @return + */ + public function getSupportedVersions() + { + return array("4.3.0"); + } + + /** + * Get xml namespace + * + * @param + * @return + */ + public function getXmlNamespace($a_entity, $a_schema_version) + { + return "http://www.ilias.de/xml/Services/Rating/" . $a_entity; + } + + /** + * Get field types for entity + * + * @param + * @return + */ + protected function getTypes($a_entity, $a_version) + { + if ($a_entity == "rating_category") { + switch ($a_version) { + case "4.3.0": + return array( + "Id" => "integer", + "ParentId" => "integer", + "Title" => "text", + "Description" => "text", + "Pos" => "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 == "rating_category") - { - switch ($a_version) - { - case "4.3.0": - $this->getDirectDataFromQuery("SELECT id, parent_id, title,". - " description, pos". - " FROM il_rating_cat". - " WHERE ".$ilDB->in("parent_id", $a_ids, false, "integer")); - break; - } - } - } - - /** - * Determine the dependent sets of data - */ - protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) - { - return false; - } - - /** - * Import record - * - * @param - * @return - */ - function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) - { -//echo $a_entity; -//var_dump($a_rec); - - switch ($a_entity) - { - case "rating_category": - if($parent_id = $a_mapping->getMapping('Services/Rating', 'rating_category_parent_id', $a_rec['ParentId'])) - { - include_once("./Services/Rating/classes/class.ilRatingCategory.php"); - $newObj = new ilRatingCategory(); - $newObj->setParentId($parent_id); - $newObj->save(); - - $newObj->setTitle($a_rec["Title"]); - $newObj->setDescription($a_rec["Description"]); - $newObj->setPosition($a_rec["Pos"]); - $newObj->update(); - } - break; - } - } + if (!is_array($a_ids)) { + $a_ids = array($a_ids); + } + + if ($a_entity == "rating_category") { + switch ($a_version) { + case "4.3.0": + $this->getDirectDataFromQuery("SELECT id, parent_id, title," . + " description, pos" . + " FROM il_rating_cat" . + " WHERE " . $ilDB->in("parent_id", $a_ids, false, "integer")); + break; + } + } + } + + /** + * Determine the dependent sets of data + */ + protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) + { + return false; + } + + /** + * Import record + * + * @param + * @return + */ + public function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) + { + //echo $a_entity; + //var_dump($a_rec); + + switch ($a_entity) { + case "rating_category": + if ($parent_id = $a_mapping->getMapping('Services/Rating', 'rating_category_parent_id', $a_rec['ParentId'])) { + include_once("./Services/Rating/classes/class.ilRatingCategory.php"); + $newObj = new ilRatingCategory(); + $newObj->setParentId($parent_id); + $newObj->save(); + + $newObj->setTitle($a_rec["Title"]); + $newObj->setDescription($a_rec["Description"]); + $newObj->setPosition($a_rec["Pos"]); + $newObj->update(); + } + break; + } + } } -?> \ No newline at end of file diff --git a/Services/Rating/classes/class.ilRatingExporter.php b/Services/Rating/classes/class.ilRatingExporter.php index cf737fc4db1369cbdb01abdc0ed149b848ab327b..f6fd14db676485fd88a2621e6fe3dc20318faf36 100644 --- a/Services/Rating/classes/class.ilRatingExporter.php +++ b/Services/Rating/classes/class.ilRatingExporter.php @@ -12,51 +12,48 @@ include_once("./Services/Export/classes/class.ilXmlExporter.php"); */ class ilRatingExporter extends ilXmlExporter { - private $ds; + private $ds; - /** - * Initialisation - */ - function init() - { - include_once("./Services/Rating/classes/class.ilRatingDataSet.php"); - $this->ds = new ilRatingDataSet(); - $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); - $this->ds->setDSPrefix("ds"); - } + /** + * Initialisation + */ + public function init() + { + include_once("./Services/Rating/classes/class.ilRatingDataSet.php"); + $this->ds = new ilRatingDataSet(); + $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); + $this->ds->setDSPrefix("ds"); + } - /** - * Get xml representation - * - * @param string entity - * @param string target release - * @param string id - * @return string xml string - */ - public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) - { - return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); - } - - /** - * Returns schema versions that the component can export to. - * ILIAS chooses the first one, that has min/max constraints which - * fit to the target release. Please put the newest on top. - * - * @return - */ - function getValidSchemaVersions($a_entity) - { - return array ( - "4.3.0" => array( - "namespace" => "http://www.ilias.de/Services/Rating/rating_category/4_3", - "xsd_file" => "ilias_rating_4_3.xsd", - "uses_dataset" => true, - "min" => "4.3.0", - "max" => "") - ); - } + /** + * Get xml representation + * + * @param string entity + * @param string target release + * @param string id + * @return string xml string + */ + public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) + { + return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); + } + /** + * Returns schema versions that the component can export to. + * ILIAS chooses the first one, that has min/max constraints which + * fit to the target release. Please put the newest on top. + * + * @return + */ + public function getValidSchemaVersions($a_entity) + { + return array( + "4.3.0" => array( + "namespace" => "http://www.ilias.de/Services/Rating/rating_category/4_3", + "xsd_file" => "ilias_rating_4_3.xsd", + "uses_dataset" => true, + "min" => "4.3.0", + "max" => "") + ); + } } - -?> \ No newline at end of file diff --git a/Services/Rating/classes/class.ilRatingGUI.php b/Services/Rating/classes/class.ilRatingGUI.php index 9f3bfd73edec8aa8f2eb0e60390419f4840ac03d..ff78aa64cc76c478c67e7d8cec57e1ad4e860860 100644 --- a/Services/Rating/classes/class.ilRatingGUI.php +++ b/Services/Rating/classes/class.ilRatingGUI.php @@ -9,681 +9,674 @@ include_once("./Services/Rating/classes/class.ilRatingCategory.php"); * * @author Alex Killing * @version $Id$ - * + * * @ilCtrl_Calls ilRatingGUI: ilRatingCategoryGUI * * @ingroup ServicesRating */ class ilRatingGUI { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - protected $id = "rtg_"; - protected $export_callback; - protected $export_subobj_title; - protected $ctrl_path; + protected $id = "rtg_"; + protected $export_callback; + protected $export_subobj_title; + protected $ctrl_path; - function __construct() - { - global $DIC; + public function __construct() + { + global $DIC; - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $this->user = $DIC->user(); - $lng = $DIC->language(); - - $lng->loadLanguageModule("rating"); - } - - /** - * execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd(); - - switch($next_class) - { - case "ilratingcategorygui": - include_once("./Services/Rating/classes/class.ilRatingCategoryGUI.php"); - $gui = new ilRatingCategoryGUI($this->obj_id, $this->export_callback, $this->export_subobj_title); - $ilCtrl->forwardCommand($gui); - break; - - default: - return $this->$cmd(); - break; - } - } + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->user = $DIC->user(); + $lng = $DIC->language(); + + $lng->loadLanguageModule("rating"); + } + + /** + * execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd(); + + switch ($next_class) { + case "ilratingcategorygui": + include_once("./Services/Rating/classes/class.ilRatingCategoryGUI.php"); + $gui = new ilRatingCategoryGUI($this->obj_id, $this->export_callback, $this->export_subobj_title); + $ilCtrl->forwardCommand($gui); + break; + + default: + return $this->$cmd(); + break; + } + } - /** - * Set Object. - * - * @param int $a_obj_id Object ID - * @param string $a_obj_type Object Type - * @param int $a_sub_obj_id Subobject ID - * @param string $a_sub_obj_type Subobject Type - */ - function setObject($a_obj_id, $a_obj_type, $a_sub_obj_id = 0, $a_sub_obj_type = "") - { - $ilUser = $this->user; - - if(!trim($a_sub_obj_type)) - { - $a_sub_obj_type = "-"; - } + /** + * Set Object. + * + * @param int $a_obj_id Object ID + * @param string $a_obj_type Object Type + * @param int $a_sub_obj_id Subobject ID + * @param string $a_sub_obj_type Subobject Type + */ + public function setObject($a_obj_id, $a_obj_type, $a_sub_obj_id = 0, $a_sub_obj_type = "") + { + $ilUser = $this->user; + + if (!trim($a_sub_obj_type)) { + $a_sub_obj_type = "-"; + } - $this->obj_id = $a_obj_id; - $this->obj_type = $a_obj_type; - $this->sub_obj_id = $a_sub_obj_id; - $this->sub_obj_type = $a_sub_obj_type; - $this->id = "rtg_".$this->obj_id."_".$this->obj_type."_".$this->sub_obj_id."_". - $this->sub_obj_type; - - $this->setUserId($ilUser->getId()); - } - - /** - * Set User ID. - * - * @param int $a_userid User ID - */ - function setUserId($a_userid) - { - $this->userid = $a_userid; - } + $this->obj_id = $a_obj_id; + $this->obj_type = $a_obj_type; + $this->sub_obj_id = $a_sub_obj_id; + $this->sub_obj_type = $a_sub_obj_type; + $this->id = "rtg_" . $this->obj_id . "_" . $this->obj_type . "_" . $this->sub_obj_id . "_" . + $this->sub_obj_type; + + $this->setUserId($ilUser->getId()); + } + + /** + * Set User ID. + * + * @param int $a_userid User ID + */ + public function setUserId($a_userid) + { + $this->userid = $a_userid; + } - /** - * Get User ID. - * - * @return int User ID - */ - function getUserId() - { - return $this->userid; - } - - /** - * Set "Your Rating" text - * - * @param string $a_val text - */ - function setYourRatingText($a_val) - { - $this->your_rating_text = $a_val; - } - - /** - * Get "Your Rating" text - * - * @return string text - */ - function getYourRatingText() - { - return $this->your_rating_text; - } - - /** - * Toggle categories status - * - * @param bool $a_value - */ - function enableCategories($a_value) - { - $this->enable_categories = (bool)$a_value; - } - - /** - * ilCtrl path - * - * @param array $a_value - */ - public function setCtrlPath(array $a_value) - { - $this->ctrl_path = $a_value; - } - - /** - * Render rating details - * - * @param string $a_js_id - * @param bool $a_may_rate - * @param array $a_categories - * @param bool $a_onclick - * @param bool $a_average - * @return string - */ - protected function renderDetails($a_js_id, $a_may_rate, array $a_categories = null, $a_onclick = null, $a_average = false) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $ttpl = new ilTemplate("tpl.rating_details.html", true, true, "Services/Rating"); - - $rate_text = null; - if($this->getYourRatingText() != "#") - { - $rate_text = ($this->getYourRatingText() != "") - ? $this->getYourRatingText() - : $lng->txt("rating_your_rating"); - } - - // no categories: 1 simple rating (link) - if(!$a_categories) - { - if ($a_may_rate) - { - $rating = ilRating::getRatingForUserAndObject($this->obj_id, $this->obj_type, - $this->sub_obj_id, $this->sub_obj_type, $this->getUserId(), 0); - - if((bool)$a_average) - { - $overall_rating = ilRating::getOverallRatingForObject($this->obj_id, $this->obj_type, - $this->sub_obj_id, $this->sub_obj_type); - } + /** + * Get User ID. + * + * @return int User ID + */ + public function getUserId() + { + return $this->userid; + } + + /** + * Set "Your Rating" text + * + * @param string $a_val text + */ + public function setYourRatingText($a_val) + { + $this->your_rating_text = $a_val; + } + + /** + * Get "Your Rating" text + * + * @return string text + */ + public function getYourRatingText() + { + return $this->your_rating_text; + } + + /** + * Toggle categories status + * + * @param bool $a_value + */ + public function enableCategories($a_value) + { + $this->enable_categories = (bool) $a_value; + } + + /** + * ilCtrl path + * + * @param array $a_value + */ + public function setCtrlPath(array $a_value) + { + $this->ctrl_path = $a_value; + } + + /** + * Render rating details + * + * @param string $a_js_id + * @param bool $a_may_rate + * @param array $a_categories + * @param bool $a_onclick + * @param bool $a_average + * @return string + */ + protected function renderDetails($a_js_id, $a_may_rate, array $a_categories = null, $a_onclick = null, $a_average = false) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $ttpl = new ilTemplate("tpl.rating_details.html", true, true, "Services/Rating"); + + $rate_text = null; + if ($this->getYourRatingText() != "#") { + $rate_text = ($this->getYourRatingText() != "") + ? $this->getYourRatingText() + : $lng->txt("rating_your_rating"); + } + + // no categories: 1 simple rating (link) + if (!$a_categories) { + if ($a_may_rate) { + $rating = ilRating::getRatingForUserAndObject( + $this->obj_id, + $this->obj_type, + $this->sub_obj_id, + $this->sub_obj_type, + $this->getUserId(), + 0 + ); + + if ((bool) $a_average) { + $overall_rating = ilRating::getOverallRatingForObject( + $this->obj_id, + $this->obj_type, + $this->sub_obj_id, + $this->sub_obj_type + ); + } - // user rating links - for($i = 1; $i <= 5; $i++) - { - if ((bool)$a_average && - $i == $rating) - { - $ttpl->setCurrentBlock("rating_mark_simple"); - $ttpl->setVariable("SRC_MARK_SIMPLE", - ilUtil::getImagePath("icon_rate_marker.svg")); - $ttpl->parseCurrentBlock(); - } - - $ttpl->setCurrentBlock("rating_link_simple"); - if(stristr($a_onclick, "%rating%")) - { - $url_save = "#"; - } - else - { - $ilCtrl->setParameter($this, "rating", $i); - if(!$this->ctrl_path) - { - $url_save = $ilCtrl->getLinkTarget($this, "saveRating"); - } - else - { - $url_save = $ilCtrl->getLinkTargetByClass($this->ctrl_path, "saveRating"); - } - } - $ttpl->setVariable("HREF_RATING", $url_save); - - if($a_onclick) - { - $onclick = str_replace("%rating%", $i, $a_onclick); - $ttpl->setVariable("ONCLICK_RATING", ' onclick="'.$onclick.'"'); - } - - if((bool)$a_average) - { - $ref_rating = $overall_rating["avg"]; - } - else - { - $ref_rating = $rating; - } - - if ($ref_rating >= $i) - { - $ttpl->setVariable("SRC_ICON", - ilUtil::getImagePath("icon_rate_on.svg")); - } - else - { - $ttpl->setVariable("SRC_ICON", - ilUtil::getImagePath("icon_rate_off.svg")); - } - $ttpl->setVariable("ALT_ICON", "(".$i."/5)"); - $ttpl->parseCurrentBlock(); - } - - // remove - if($rating) - { - $ttpl->setCurrentBlock("rating_simple_del_bl"); - $ttpl->setVariable("CAPTION_RATING_DEL", $lng->txt("rating_remove")); - - if(stristr($a_onclick, "%rating%")) - { - $url_save = "#"; - } - else - { - $ilCtrl->setParameter($this, "rating", 0); - if(!$this->ctrl_path) - { - $url_save = $ilCtrl->getLinkTarget($this, "saveRating"); - } - else - { - $url_save = $ilCtrl->getLinkTargetByClass($this->ctrl_path, "saveRating"); - } - } - $ttpl->setVariable("HREF_RATING_DEL", $url_save); - - if($a_onclick) - { - $onclick = str_replace("%rating%", 0, $a_onclick); - $ttpl->setVariable("ONCLICK_RATING_DEL", ' onclick="'.$onclick.'"'); - } - - $ttpl->parseCurrentBlock(); - } - - if($rate_text) - { - $ttpl->setCurrentBlock("rating_simple_title"); - $ttpl->setVariable("TXT_RATING_SIMPLE", $rate_text); - $ttpl->parseCurrentBlock(); - } - - // user rating text - $ttpl->setCurrentBlock("user_rating_simple"); - - if((bool)$a_average && - $overall_rating["cnt"]) - { - $ttpl->setVariable("NUMBER_VOTES_SIMPLE", $overall_rating["cnt"]); - } + // user rating links + for ($i = 1; $i <= 5; $i++) { + if ((bool) $a_average && + $i == $rating) { + $ttpl->setCurrentBlock("rating_mark_simple"); + $ttpl->setVariable( + "SRC_MARK_SIMPLE", + ilUtil::getImagePath("icon_rate_marker.svg") + ); + $ttpl->parseCurrentBlock(); + } + + $ttpl->setCurrentBlock("rating_link_simple"); + if (stristr($a_onclick, "%rating%")) { + $url_save = "#"; + } else { + $ilCtrl->setParameter($this, "rating", $i); + if (!$this->ctrl_path) { + $url_save = $ilCtrl->getLinkTarget($this, "saveRating"); + } else { + $url_save = $ilCtrl->getLinkTargetByClass($this->ctrl_path, "saveRating"); + } + } + $ttpl->setVariable("HREF_RATING", $url_save); + + if ($a_onclick) { + $onclick = str_replace("%rating%", $i, $a_onclick); + $ttpl->setVariable("ONCLICK_RATING", ' onclick="' . $onclick . '"'); + } + + if ((bool) $a_average) { + $ref_rating = $overall_rating["avg"]; + } else { + $ref_rating = $rating; + } + + if ($ref_rating >= $i) { + $ttpl->setVariable( + "SRC_ICON", + ilUtil::getImagePath("icon_rate_on.svg") + ); + } else { + $ttpl->setVariable( + "SRC_ICON", + ilUtil::getImagePath("icon_rate_off.svg") + ); + } + $ttpl->setVariable("ALT_ICON", "(" . $i . "/5)"); + $ttpl->parseCurrentBlock(); + } + + // remove + if ($rating) { + $ttpl->setCurrentBlock("rating_simple_del_bl"); + $ttpl->setVariable("CAPTION_RATING_DEL", $lng->txt("rating_remove")); + + if (stristr($a_onclick, "%rating%")) { + $url_save = "#"; + } else { + $ilCtrl->setParameter($this, "rating", 0); + if (!$this->ctrl_path) { + $url_save = $ilCtrl->getLinkTarget($this, "saveRating"); + } else { + $url_save = $ilCtrl->getLinkTargetByClass($this->ctrl_path, "saveRating"); + } + } + $ttpl->setVariable("HREF_RATING_DEL", $url_save); + + if ($a_onclick) { + $onclick = str_replace("%rating%", 0, $a_onclick); + $ttpl->setVariable("ONCLICK_RATING_DEL", ' onclick="' . $onclick . '"'); + } + + $ttpl->parseCurrentBlock(); + } + + if ($rate_text) { + $ttpl->setCurrentBlock("rating_simple_title"); + $ttpl->setVariable("TXT_RATING_SIMPLE", $rate_text); + $ttpl->parseCurrentBlock(); + } + + // user rating text + $ttpl->setCurrentBlock("user_rating_simple"); + + if ((bool) $a_average && + $overall_rating["cnt"]) { + $ttpl->setVariable("NUMBER_VOTES_SIMPLE", $overall_rating["cnt"]); + } - $ttpl->parseCurrentBlock(); - } - } - // categories: overall & user (form) - else - { - $has_user_rating = false; - foreach($a_categories as $category) - { - $user_rating = round(ilRating::getRatingForUserAndObject($this->obj_id, $this->obj_type, - $this->sub_obj_id, $this->sub_obj_type, $this->getUserId(), $category["id"])); + $ttpl->parseCurrentBlock(); + } + } + // categories: overall & user (form) + else { + $has_user_rating = false; + foreach ($a_categories as $category) { + $user_rating = round(ilRating::getRatingForUserAndObject( + $this->obj_id, + $this->obj_type, + $this->sub_obj_id, + $this->sub_obj_type, + $this->getUserId(), + $category["id"] + )); - $overall_rating = ilRating::getOverallRatingForObject($this->obj_id, $this->obj_type, - $this->sub_obj_id, $this->sub_obj_type, $category["id"]); - - for($i = 1; $i <= 5; $i++) - { - if ($a_may_rate && $i == $user_rating) - { - $has_user_rating = true; - - $ttpl->setCurrentBlock("rating_mark"); - $ttpl->setVariable("SRC_MARK", - ilUtil::getImagePath("icon_rate_marker.svg")); - $ttpl->parseCurrentBlock(); - } - - $ttpl->setCurrentBlock("user_rating_icon"); - if ($overall_rating["avg"] >= $i) - { - $ttpl->setVariable("SRC_ICON", - ilUtil::getImagePath("icon_rate_on.svg")); - } - else if ($overall_rating["avg"] + 1 <= $i) - { - $ttpl->setVariable("SRC_ICON", - ilUtil::getImagePath("icon_rate_off.svg")); - } - else - { - $nr = round(($overall_rating["avg"] + 1 - $i) * 10); - $ttpl->setVariable("SRC_ICON", - ilUtil::getImagePath("icon_rate_$nr.svg")); - } - $ttpl->setVariable("ALT_ICON", "(".$i."/5)"); - - if ($a_may_rate) - { - $ttpl->setVariable("HREF_RATING", "il.Rating.setValue(".$category["id"].",".$i.", '".$a_js_id."')"); - $ttpl->setVariable("CATEGORY_ID", $category["id"]); - $ttpl->setVariable("ICON_VALUE", $i); - $ttpl->setVariable("JS_ID", $a_js_id); - $ttpl->setVariable("ICON_MOUSEACTION", " onmouseover=\"il.Rating.toggleIcon(this,".$i.")\"". - " onmouseout=\"il.Rating.toggleIcon(this,".$i.",1)\""); - } - - $ttpl->parseCurrentBlock(); - } - - if($a_may_rate) - { - $ttpl->setCurrentBlock("user_rating_category_column"); - $ttpl->setVariable("JS_ID", $a_js_id); - $ttpl->setVariable("CATEGORY_ID", $category["id"]); - $ttpl->setVariable("CATEGORY_VALUE", $user_rating); - $ttpl->parseCurrentBlock(); - } - - // category title - $ttpl->setCurrentBlock("user_rating_category"); - $ttpl->setVariable("TXT_RATING_CATEGORY", $category["title"]); - $ttpl->parseCurrentBlock(); - } - - if($overall_rating["cnt"]) - { - $ttpl->setCurrentBlock("votes_number_bl"); - $ttpl->setVariable("NUMBER_VOTES", sprintf($lng->txt("rating_number_votes"), $overall_rating["cnt"])); - $ttpl->parseCurrentBlock(); - } - - if($a_may_rate) - { - // remove - if($has_user_rating) - { - $ttpl->setCurrentBlock("user_rating_categories_del_bl"); - $ttpl->setVariable("CAPTION_RATING_DEL_CAT", $lng->txt("rating_remove")); - - $ilCtrl->setParameter($this, "rating", 0); - if(!$this->ctrl_path) - { - $url_save = $ilCtrl->getLinkTarget($this, "resetUserRating"); - } - else - { - $url_save = $ilCtrl->getLinkTargetByClass($this->ctrl_path, "resetUserRating"); - } - $ttpl->setVariable("HREF_RATING_DEL_CAT", $url_save); - - $ttpl->parseCurrentBlock(); - } - - if(!$this->ctrl_path) - { - $url_form = $ilCtrl->getFormAction($this, "saveRating"); - } - else - { - $url_form = $ilCtrl->getFormActionByClass($this->ctrl_path, "saveRating"); - } - $ttpl->setVariable("FORM_ACTION", $url_form); - $ttpl->setVariable("TXT_SUBMIT", $lng->txt("rating_overlay_submit")); - $ttpl->setVariable("CMD_SUBMIT", "saveRating"); - $ttpl->touchBlock("user_rating_categories_form_out"); - - // overall / user title - /* - $ttpl->setCurrentBlock("user_rating_categories"); - $ttpl->setVariable("TXT_RATING_OVERALL", $lng->txt("rating_overlay_title_overall")); - $ttpl->parseCurrentBlock(); - */ - } - } - - return $ttpl->get(); - } + $overall_rating = ilRating::getOverallRatingForObject( + $this->obj_id, + $this->obj_type, + $this->sub_obj_id, + $this->sub_obj_type, + $category["id"] + ); + + for ($i = 1; $i <= 5; $i++) { + if ($a_may_rate && $i == $user_rating) { + $has_user_rating = true; + + $ttpl->setCurrentBlock("rating_mark"); + $ttpl->setVariable( + "SRC_MARK", + ilUtil::getImagePath("icon_rate_marker.svg") + ); + $ttpl->parseCurrentBlock(); + } + + $ttpl->setCurrentBlock("user_rating_icon"); + if ($overall_rating["avg"] >= $i) { + $ttpl->setVariable( + "SRC_ICON", + ilUtil::getImagePath("icon_rate_on.svg") + ); + } elseif ($overall_rating["avg"] + 1 <= $i) { + $ttpl->setVariable( + "SRC_ICON", + ilUtil::getImagePath("icon_rate_off.svg") + ); + } else { + $nr = round(($overall_rating["avg"] + 1 - $i) * 10); + $ttpl->setVariable( + "SRC_ICON", + ilUtil::getImagePath("icon_rate_$nr.svg") + ); + } + $ttpl->setVariable("ALT_ICON", "(" . $i . "/5)"); + + if ($a_may_rate) { + $ttpl->setVariable("HREF_RATING", "il.Rating.setValue(" . $category["id"] . "," . $i . ", '" . $a_js_id . "')"); + $ttpl->setVariable("CATEGORY_ID", $category["id"]); + $ttpl->setVariable("ICON_VALUE", $i); + $ttpl->setVariable("JS_ID", $a_js_id); + $ttpl->setVariable("ICON_MOUSEACTION", " onmouseover=\"il.Rating.toggleIcon(this," . $i . ")\"" . + " onmouseout=\"il.Rating.toggleIcon(this," . $i . ",1)\""); + } + + $ttpl->parseCurrentBlock(); + } + + if ($a_may_rate) { + $ttpl->setCurrentBlock("user_rating_category_column"); + $ttpl->setVariable("JS_ID", $a_js_id); + $ttpl->setVariable("CATEGORY_ID", $category["id"]); + $ttpl->setVariable("CATEGORY_VALUE", $user_rating); + $ttpl->parseCurrentBlock(); + } + + // category title + $ttpl->setCurrentBlock("user_rating_category"); + $ttpl->setVariable("TXT_RATING_CATEGORY", $category["title"]); + $ttpl->parseCurrentBlock(); + } + + if ($overall_rating["cnt"]) { + $ttpl->setCurrentBlock("votes_number_bl"); + $ttpl->setVariable("NUMBER_VOTES", sprintf($lng->txt("rating_number_votes"), $overall_rating["cnt"])); + $ttpl->parseCurrentBlock(); + } + + if ($a_may_rate) { + // remove + if ($has_user_rating) { + $ttpl->setCurrentBlock("user_rating_categories_del_bl"); + $ttpl->setVariable("CAPTION_RATING_DEL_CAT", $lng->txt("rating_remove")); + + $ilCtrl->setParameter($this, "rating", 0); + if (!$this->ctrl_path) { + $url_save = $ilCtrl->getLinkTarget($this, "resetUserRating"); + } else { + $url_save = $ilCtrl->getLinkTargetByClass($this->ctrl_path, "resetUserRating"); + } + $ttpl->setVariable("HREF_RATING_DEL_CAT", $url_save); + + $ttpl->parseCurrentBlock(); + } + + if (!$this->ctrl_path) { + $url_form = $ilCtrl->getFormAction($this, "saveRating"); + } else { + $url_form = $ilCtrl->getFormActionByClass($this->ctrl_path, "saveRating"); + } + $ttpl->setVariable("FORM_ACTION", $url_form); + $ttpl->setVariable("TXT_SUBMIT", $lng->txt("rating_overlay_submit")); + $ttpl->setVariable("CMD_SUBMIT", "saveRating"); + $ttpl->touchBlock("user_rating_categories_form_out"); + + // overall / user title + /* + $ttpl->setCurrentBlock("user_rating_categories"); + $ttpl->setVariable("TXT_RATING_OVERALL", $lng->txt("rating_overlay_title_overall")); + $ttpl->parseCurrentBlock(); + */ + } + } + + return $ttpl->get(); + } - /** - * Get HTML for rating of an object (and a user) - * - * @param bool $a_show_overall - * @param bool $a_may_rate - * @param string $a_onclick - * @param string $a_additional_id - * @return string - */ - function getHTML($a_show_overall = true, $a_may_rate = true, $a_onclick = null, $a_additional_id = null) - { - $lng = $this->lng; - - $unique_id = $this->id; - if($a_additional_id) - { - $unique_id .= "_".$a_additional_id; - } - - $categories = array(); - if($this->enable_categories) - { - $categories = ilRatingCategory::getAllForObject($this->obj_id); - } - - $may_rate = ($this->getUserId() != ANONYMOUS_USER_ID); - if($may_rate && !$a_may_rate) - { - $may_rate = false; - } - - $has_overlay = false; - if($may_rate || $categories) - { - $has_overlay = true; - } + /** + * Get HTML for rating of an object (and a user) + * + * @param bool $a_show_overall + * @param bool $a_may_rate + * @param string $a_onclick + * @param string $a_additional_id + * @return string + */ + public function getHTML($a_show_overall = true, $a_may_rate = true, $a_onclick = null, $a_additional_id = null) + { + $lng = $this->lng; + + $unique_id = $this->id; + if ($a_additional_id) { + $unique_id .= "_" . $a_additional_id; + } + + $categories = array(); + if ($this->enable_categories) { + $categories = ilRatingCategory::getAllForObject($this->obj_id); + } + + $may_rate = ($this->getUserId() != ANONYMOUS_USER_ID); + if ($may_rate && !$a_may_rate) { + $may_rate = false; + } + + $has_overlay = false; + if ($may_rate || $categories) { + $has_overlay = true; + } - $ttpl = new ilTemplate("tpl.rating_input.html", true, true, "Services/Rating"); + $ttpl = new ilTemplate("tpl.rating_input.html", true, true, "Services/Rating"); - // user rating - $user_rating = 0; - if ($may_rate || !$a_show_overall) - { - $user_rating = round(ilRating::getRatingForUserAndObject($this->obj_id, $this->obj_type, - $this->sub_obj_id, $this->sub_obj_type, $this->getUserId())); - } - - // (1) overall rating - if($a_show_overall) - { - $rating = ilRating::getOverallRatingForObject($this->obj_id, $this->obj_type, - $this->sub_obj_id, $this->sub_obj_type); - } - else - { - $rating = array("avg"=>$user_rating); - } - - for($i = 1; $i <= 5; $i++) - { - if ($a_show_overall && - $i == $user_rating) - { - $ttpl->setCurrentBlock("rating_mark"); - $ttpl->setVariable("SRC_MARK", - ilUtil::getImagePath("icon_rate_marker.svg")); - $ttpl->parseCurrentBlock(); - } + // user rating + $user_rating = 0; + if ($may_rate || !$a_show_overall) { + $user_rating = round(ilRating::getRatingForUserAndObject( + $this->obj_id, + $this->obj_type, + $this->sub_obj_id, + $this->sub_obj_type, + $this->getUserId() + )); + } + + // (1) overall rating + if ($a_show_overall) { + $rating = ilRating::getOverallRatingForObject( + $this->obj_id, + $this->obj_type, + $this->sub_obj_id, + $this->sub_obj_type + ); + } else { + $rating = array("avg"=>$user_rating); + } + + for ($i = 1; $i <= 5; $i++) { + if ($a_show_overall && + $i == $user_rating) { + $ttpl->setCurrentBlock("rating_mark"); + $ttpl->setVariable( + "SRC_MARK", + ilUtil::getImagePath("icon_rate_marker.svg") + ); + $ttpl->parseCurrentBlock(); + } - $ttpl->setCurrentBlock("rating_icon"); - if ($rating["avg"] >= $i) - { - $ttpl->setVariable("SRC_ICON", - ilUtil::getImagePath("icon_rate_on.svg")); - } - else if ($rating["avg"] + 1 <= $i) - { - $ttpl->setVariable("SRC_ICON", - ilUtil::getImagePath("icon_rate_off.svg")); - } - else - { - $nr = round(($rating["avg"] + 1 - $i) * 10); - $ttpl->setVariable("SRC_ICON", - ilUtil::getImagePath("icon_rate_$nr.svg")); - } - $ttpl->setVariable("ALT_ICON", "(".$i."/5)"); - $ttpl->parseCurrentBlock(); - } - $ttpl->setCurrentBlock("rating_icon"); - - if($a_show_overall) - { - if ($rating["cnt"] == 0) - { - $tt = $lng->txt("rat_not_rated_yet"); - } - else if ($rating["cnt"] == 1) - { - $tt = $lng->txt("rat_one_rating"); - } - else - { - $tt = sprintf($lng->txt("rat_nr_ratings"), $rating["cnt"]); - } - include_once("./Services/UIComponent/Tooltip/classes/class.ilTooltipGUI.php"); - ilTooltipGUI::addTooltip($unique_id."_tt", $tt); + $ttpl->setCurrentBlock("rating_icon"); + if ($rating["avg"] >= $i) { + $ttpl->setVariable( + "SRC_ICON", + ilUtil::getImagePath("icon_rate_on.svg") + ); + } elseif ($rating["avg"] + 1 <= $i) { + $ttpl->setVariable( + "SRC_ICON", + ilUtil::getImagePath("icon_rate_off.svg") + ); + } else { + $nr = round(($rating["avg"] + 1 - $i) * 10); + $ttpl->setVariable( + "SRC_ICON", + ilUtil::getImagePath("icon_rate_$nr.svg") + ); + } + $ttpl->setVariable("ALT_ICON", "(" . $i . "/5)"); + $ttpl->parseCurrentBlock(); + } + $ttpl->setCurrentBlock("rating_icon"); + + if ($a_show_overall) { + if ($rating["cnt"] == 0) { + $tt = $lng->txt("rat_not_rated_yet"); + } elseif ($rating["cnt"] == 1) { + $tt = $lng->txt("rat_one_rating"); + } else { + $tt = sprintf($lng->txt("rat_nr_ratings"), $rating["cnt"]); + } + include_once("./Services/UIComponent/Tooltip/classes/class.ilTooltipGUI.php"); + ilTooltipGUI::addTooltip($unique_id . "_tt", $tt); - if ($rating["cnt"] > 0) - { - $ttpl->setCurrentBlock("rat_nr"); - $ttpl->setVariable("RT_NR", $rating["cnt"]); - $ttpl->parseCurrentBlock(); - } - } + if ($rating["cnt"] > 0) { + $ttpl->setCurrentBlock("rat_nr"); + $ttpl->setVariable("RT_NR", $rating["cnt"]); + $ttpl->parseCurrentBlock(); + } + } - // add overlay (trigger) - if ($has_overlay) - { - include_once("./Services/UIComponent/Overlay/classes/class.ilOverlayGUI.php"); - $ov = new ilOverlayGUI($unique_id); - $ov->setTrigger("tr_".$unique_id, "click", "tr_".$unique_id); - $ov->add(); - - $ttpl->setCurrentBlock("act_rat_start"); - $ttpl->setVariable("ID", $unique_id); - $ttpl->parseCurrentBlock(); + // add overlay (trigger) + if ($has_overlay) { + include_once("./Services/UIComponent/Overlay/classes/class.ilOverlayGUI.php"); + $ov = new ilOverlayGUI($unique_id); + $ov->setTrigger("tr_" . $unique_id, "click", "tr_" . $unique_id); + $ov->add(); + + $ttpl->setCurrentBlock("act_rat_start"); + $ttpl->setVariable("ID", $unique_id); + $ttpl->parseCurrentBlock(); - $ttpl->touchBlock("act_rat_end"); - } + $ttpl->touchBlock("act_rat_end"); + } - $ttpl->parseCurrentBlock(); - - - // (2) user rating - - if($has_overlay) - { - $ttpl->setVariable("RATING_DETAILS", - $this->renderDetails("rtov_", $may_rate, $categories, $a_onclick)); - - $ttpl->setCurrentBlock("user_rating"); - $ttpl->setVariable("ID", $unique_id); - $ttpl->parseCurrentBlock(); - } + $ttpl->parseCurrentBlock(); + + + // (2) user rating + + if ($has_overlay) { + $ttpl->setVariable( + "RATING_DETAILS", + $this->renderDetails("rtov_", $may_rate, $categories, $a_onclick) + ); + + $ttpl->setCurrentBlock("user_rating"); + $ttpl->setVariable("ID", $unique_id); + $ttpl->parseCurrentBlock(); + } - $ttpl->setVariable("TTID", $unique_id); + $ttpl->setVariable("TTID", $unique_id); - return $ttpl->get(); - } - - function getBlockHTML($a_title) - { - $categories = array(); - if($this->enable_categories) - { - $categories = ilRatingCategory::getAllForObject($this->obj_id); - } - - $may_rate = ($this->getUserId() != ANONYMOUS_USER_ID); - - $ttpl = new ilTemplate("tpl.rating_block.html", true, true, "Services/Rating"); - - $ttpl->setVariable("TITLE", $a_title); - - $ttpl->setVariable("RATING_DETAILS", - $this->renderDetails("rtsb_", $may_rate, $categories, null, true)); - - return $ttpl->get(); - } - - /** - * Save Rating - */ - function saveRating() - { - $ilCtrl = $this->ctrl; - - if(!is_array($_REQUEST["rating"])) - { - $rating = (int)ilUtil::stripSlashes($_GET["rating"]); - if(!$rating) - { - $this->resetUserRating(); - } - else - { - ilRating::writeRatingForUserAndObject($this->obj_id, $this->obj_type, - $this->sub_obj_id, $this->sub_obj_type, $this->getUserId(), - $rating); - } - } - else - { - foreach($_POST["rating"] as $cat_id => $rating) - { - ilRating::writeRatingForUserAndObject($this->obj_id, $this->obj_type, - $this->sub_obj_id, $this->sub_obj_type, $this->getUserId(), - $rating, $cat_id); - } - } - - if($this->update_callback) - { - call_user_func($this->update_callback, $this->obj_id, $this->obj_type, - $this->sub_obj_id, $this->sub_obj_type); - } - - if($ilCtrl->isAsynch()) - { - exit(); - } - } - - public function setUpdateCallback($a_callback) - { - $this->update_callback = $a_callback; - } - - /** - * Reset Rating - */ - function resetUserRating() - { - ilRating::resetRatingForUserAndObject($this->obj_id, $this->obj_type, - $this->sub_obj_id, $this->sub_obj_type, $this->getUserId()); - } - - function setExportCallback($a_callback, $a_subobj_title) - { - $this->export_callback = $a_callback; - $this->export_subobj_title = $a_subobj_title; - } - - /** - * Build list gui property for object - * - * @param int $a_ref_id - * @param bool $a_may_rate - * @param string $a_ajax_hash - * @param int $_parent_ref_id - * @return string - */ - public function getListGUIProperty($a_ref_id, $a_may_rate, $a_ajax_hash, $_parent_ref_id) - { - return $this->getHTML(true, $a_may_rate, - "il.Object.saveRatingFromListGUI(".$a_ref_id.", '".$a_ajax_hash."', %rating%);", - $_parent_ref_id); - } + return $ttpl->get(); + } + + public function getBlockHTML($a_title) + { + $categories = array(); + if ($this->enable_categories) { + $categories = ilRatingCategory::getAllForObject($this->obj_id); + } + + $may_rate = ($this->getUserId() != ANONYMOUS_USER_ID); + + $ttpl = new ilTemplate("tpl.rating_block.html", true, true, "Services/Rating"); + + $ttpl->setVariable("TITLE", $a_title); + + $ttpl->setVariable( + "RATING_DETAILS", + $this->renderDetails("rtsb_", $may_rate, $categories, null, true) + ); + + return $ttpl->get(); + } + + /** + * Save Rating + */ + public function saveRating() + { + $ilCtrl = $this->ctrl; + + if (!is_array($_REQUEST["rating"])) { + $rating = (int) ilUtil::stripSlashes($_GET["rating"]); + if (!$rating) { + $this->resetUserRating(); + } else { + ilRating::writeRatingForUserAndObject( + $this->obj_id, + $this->obj_type, + $this->sub_obj_id, + $this->sub_obj_type, + $this->getUserId(), + $rating + ); + } + } else { + foreach ($_POST["rating"] as $cat_id => $rating) { + ilRating::writeRatingForUserAndObject( + $this->obj_id, + $this->obj_type, + $this->sub_obj_id, + $this->sub_obj_type, + $this->getUserId(), + $rating, + $cat_id + ); + } + } + + if ($this->update_callback) { + call_user_func( + $this->update_callback, + $this->obj_id, + $this->obj_type, + $this->sub_obj_id, + $this->sub_obj_type + ); + } + + if ($ilCtrl->isAsynch()) { + exit(); + } + } + + public function setUpdateCallback($a_callback) + { + $this->update_callback = $a_callback; + } + + /** + * Reset Rating + */ + public function resetUserRating() + { + ilRating::resetRatingForUserAndObject( + $this->obj_id, + $this->obj_type, + $this->sub_obj_id, + $this->sub_obj_type, + $this->getUserId() + ); + } + + public function setExportCallback($a_callback, $a_subobj_title) + { + $this->export_callback = $a_callback; + $this->export_subobj_title = $a_subobj_title; + } + + /** + * Build list gui property for object + * + * @param int $a_ref_id + * @param bool $a_may_rate + * @param string $a_ajax_hash + * @param int $_parent_ref_id + * @return string + */ + public function getListGUIProperty($a_ref_id, $a_may_rate, $a_ajax_hash, $_parent_ref_id) + { + return $this->getHTML( + true, + $a_may_rate, + "il.Object.saveRatingFromListGUI(" . $a_ref_id . ", '" . $a_ajax_hash . "', %rating%);", + $_parent_ref_id + ); + } } - -?> diff --git a/Services/Rating/classes/class.ilRatingImporter.php b/Services/Rating/classes/class.ilRatingImporter.php index 8fb68a9c0b333723086f62757fc7a7f64e7d5050..560017c39fdf1dda2dfdb6ec7f00094f72563fea 100644 --- a/Services/Rating/classes/class.ilRatingImporter.php +++ b/Services/Rating/classes/class.ilRatingImporter.php @@ -13,29 +13,32 @@ include_once("./Services/Export/classes/class.ilXmlImporter.php"); class ilRatingImporter extends ilXmlImporter { - /** - * Initialisation - */ - function init() - { - include_once("./Services/Rating/classes/class.ilRatingDataSet.php"); - $this->ds = new ilRatingDataSet(); - $this->ds->setDSPrefix("ds"); - } + /** + * Initialisation + */ + public function init() + { + include_once("./Services/Rating/classes/class.ilRatingDataSet.php"); + $this->ds = new ilRatingDataSet(); + $this->ds->setDSPrefix("ds"); + } - /** - * Import XML - * - * @param - * @return - */ - function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) - { - include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); - $parser = new ilDataSetImportParser($a_entity, $this->getSchemaVersion(), - $a_xml, $this->ds, $a_mapping); - } + /** + * Import XML + * + * @param + * @return + */ + public function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) + { + include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); + $parser = new ilDataSetImportParser( + $a_entity, + $this->getSchemaVersion(), + $a_xml, + $this->ds, + $a_mapping + ); + } } - -?> \ No newline at end of file diff --git a/Services/Repository/classes/class.ilAdminSubItemsTableGUI.php b/Services/Repository/classes/class.ilAdminSubItemsTableGUI.php index 43f805b340ba81553e7214e4e832fa9492fd2d43..7474e7536dc495e176c5f6938f37365676fa4a43 100644 --- a/Services/Repository/classes/class.ilAdminSubItemsTableGUI.php +++ b/Services/Repository/classes/class.ilAdminSubItemsTableGUI.php @@ -14,240 +14,216 @@ require_once('./Services/Repository/classes/class.ilObjectPlugin.php'); */ class ilAdminSubItemsTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * @var ilRbacSystem - */ - protected $rbacsystem; + /** + * @var ilRbacSystem + */ + protected $rbacsystem; - /** - * @var ilObjectDefinition - */ - protected $obj_definition; + /** + * @var ilObjectDefinition + */ + protected $obj_definition; - /** - * @var ilTree - */ - protected $tree; - - /** - * @var bool - */ - protected $editable = false; + /** + * @var ilTree + */ + protected $tree; + + /** + * @var bool + */ + protected $editable = false; - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_ref_id, - $editable = false) - { - global $DIC; + + /** + * Constructor + */ + public function __construct( + $a_parent_obj, + $a_parent_cmd, + $a_ref_id, + $editable = false + ) { + global $DIC; - $this->editable = $editable; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->obj_definition = $DIC["objDefinition"]; - $this->tree = $DIC->repositoryTree(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilAccess = $DIC->access(); - $lng = $DIC->language(); - - $this->ref_id = $a_ref_id; - - $this->setId('recf_'. $a_ref_id); - parent::__construct($a_parent_obj, $a_parent_cmd); -// $this->setTitle($lng->txt("items")); - $this->setSelectAllCheckbox("id[]"); - - $this->addColumn("", "", "1", 1); - $this->addColumn($this->lng->txt("type"), "", "1"); - $this->addColumn($this->lng->txt("title"), "title"); - $this->addColumn($this->lng->txt("last_change"), "last_update", "25%"); - - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.admin_sub_items_row.html", "Services/Repository"); - //$this->disable("footer"); - $this->setEnableTitle(true); - $this->setDefaultOrderField("title"); - $this->setDefaultOrderDirection("asc"); - - // TODO: Needs other solution - if(ilObject::_lookupType((int) $_GET['ref_id'],true) == 'chac') - { - $this->getItems(); - return true; - } - + $this->editable = $editable; + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->obj_definition = $DIC["objDefinition"]; + $this->tree = $DIC->repositoryTree(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilAccess = $DIC->access(); + $lng = $DIC->language(); + + $this->ref_id = $a_ref_id; + + $this->setId('recf_' . $a_ref_id); + parent::__construct($a_parent_obj, $a_parent_cmd); + // $this->setTitle($lng->txt("items")); + $this->setSelectAllCheckbox("id[]"); + + $this->addColumn("", "", "1", 1); + $this->addColumn($this->lng->txt("type"), "", "1"); + $this->addColumn($this->lng->txt("title"), "title"); + $this->addColumn($this->lng->txt("last_change"), "last_update", "25%"); + + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.admin_sub_items_row.html", "Services/Repository"); + //$this->disable("footer"); + $this->setEnableTitle(true); + $this->setDefaultOrderField("title"); + $this->setDefaultOrderDirection("asc"); + + // TODO: Needs other solution + if (ilObject::_lookupType((int) $_GET['ref_id'], true) == 'chac') { + $this->getItems(); + return true; + } + - if (ilObject::_lookupType($_GET["ref_id"], true) != "recf") - { - if ($_SESSION["clipboard"]) - { - if($this->isEditable()) - { - $this->addCommandButton("paste", $lng->txt("paste")); - $this->addCommandButton("clear", $lng->txt("clear")); - } - } - else - { - if($this->isEditable()) - { - $this->addMultiCommand("cut", $lng->txt("cut")); - $this->addMultiCommand("delete", $lng->txt("delete")); - $this->addMultiCommand("link", $lng->txt("link")); - } - } - } - else - { - if ($_SESSION["clipboard"]) - { - if($this->isEditable()) - { - $this->addCommandButton("clear", $lng->txt("clear")); - } - } - else - { - if($this->isEditable()) - { - $this->addMultiCommand("cut", $lng->txt("cut")); - $this->addMultiCommand("removeFromSystem", $lng->txt("btn_remove_system")); - } - } - } - $this->getItems(); - } - - /** - * Check if table is editable (write permission granted) - * @return bool - */ - public function isEditable() - { - return $this->editable; - } - - /** - * Get items - */ - function getItems() - { - $rbacsystem = $this->rbacsystem; - $objDefinition = $this->obj_definition; - $tree = $this->tree; - - $items = array(); - $childs = $tree->getChilds($this->ref_id); - foreach ($childs as $key => $val) - { - // visible - if (!$rbacsystem->checkAccess("visible",$val["ref_id"])) - { - continue; - } - - // hide object types in devmode - if ($objDefinition->getDevMode($val["type"])) - { - continue; - } - - // don't show administration in root node list - if ($val["type"] == "adm") - { - continue; - } - if (!$this->parent_obj->isVisible($val["ref_id"], $val["type"])) - { - continue; - } - $items[] = $val; - } - $this->setData($items); - } - - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $objDefinition = $this->obj_definition; - $ilCtrl = $this->ctrl; + if (ilObject::_lookupType($_GET["ref_id"], true) != "recf") { + if ($_SESSION["clipboard"]) { + if ($this->isEditable()) { + $this->addCommandButton("paste", $lng->txt("paste")); + $this->addCommandButton("clear", $lng->txt("clear")); + } + } else { + if ($this->isEditable()) { + $this->addMultiCommand("cut", $lng->txt("cut")); + $this->addMultiCommand("delete", $lng->txt("delete")); + $this->addMultiCommand("link", $lng->txt("link")); + } + } + } else { + if ($_SESSION["clipboard"]) { + if ($this->isEditable()) { + $this->addCommandButton("clear", $lng->txt("clear")); + } + } else { + if ($this->isEditable()) { + $this->addMultiCommand("cut", $lng->txt("cut")); + $this->addMultiCommand("removeFromSystem", $lng->txt("btn_remove_system")); + } + } + } + $this->getItems(); + } + + /** + * Check if table is editable (write permission granted) + * @return bool + */ + public function isEditable() + { + return $this->editable; + } + + /** + * Get items + */ + public function getItems() + { + $rbacsystem = $this->rbacsystem; + $objDefinition = $this->obj_definition; + $tree = $this->tree; + + $items = array(); + $childs = $tree->getChilds($this->ref_id); + foreach ($childs as $key => $val) { + // visible + if (!$rbacsystem->checkAccess("visible", $val["ref_id"])) { + continue; + } + + // hide object types in devmode + if ($objDefinition->getDevMode($val["type"])) { + continue; + } + + // don't show administration in root node list + if ($val["type"] == "adm") { + continue; + } + if (!$this->parent_obj->isVisible($val["ref_id"], $val["type"])) { + continue; + } + $items[] = $val; + } + $this->setData($items); + } + + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $objDefinition = $this->obj_definition; + $ilCtrl = $this->ctrl; -// $this->tpl->setVariable("", ); - - // surpress checkbox for particular object types AND the system role - if (!$objDefinition->hasCheckbox($a_set["type"]) || - $a_set["obj_id"] == SYSTEM_ROLE_ID || - $a_set["obj_id"] == SYSTEM_USER_ID || - $a_set["obj_id"] == ANONYMOUS_ROLE_ID) - { - $this->tpl->touchBlock("no_checkbox"); - } - else - { - $this->tpl->setCurrentBlock("checkbox"); - $this->tpl->setVariable("ID", $a_set["ref_id"]); - $this->tpl->parseCurrentBlock(); - } - - //build link - $class_name = $objDefinition->getClassName($a_set["type"]); - $class = strtolower("ilObj".$class_name."GUI"); - $ilCtrl->setParameterByClass($class, "ref_id", $a_set["ref_id"]); - $this->tpl->setVariable("HREF_TITLE", $ilCtrl->getLinkTargetByClass($class, "view")); - $ilCtrl->setParameterByClass($class, "ref_id", $_GET["ref_id"]); - - // TODO: broken! fix me - $title = $a_set["title"]; - if (is_array($_SESSION["clipboard"]["ref_ids"])) - { - if (in_array($a_set["ref_id"], $_SESSION["clipboard"]["ref_ids"])) - { - switch($_SESSION["clipboard"]["cmd"]) - { - case "cut": - $title = "".$title.""; - break; - - case "copy": - $title = "+ ".$title; - break; - - case "link": - $title = "< ".$title; - break; - } - } - } - $this->tpl->setVariable("VAL_TITLE", $title); - $this->tpl->setVariable("VAL_DESC", ilUtil::shortenText($a_set["desc"] ,ilObject::DESC_LENGTH, true)); - $this->tpl->setVariable("VAL_LAST_CHANGE", ilDatePresentation::formatDate(new ilDateTime($a_set["last_update"],IL_CAL_DATETIME))); - $alt = ($objDefinition->isPlugin($a_set["type"])) - ? $lng->txt("icon")." ".ilObjectPlugin::lookupTxtById($a_set["type"], "obj_".$a_set["type"]) - : $lng->txt("icon")." ".$lng->txt("obj_".$a_set["type"]); - $this->tpl->setVariable("IMG_TYPE", ilUtil::img(ilObject::_getIcon($a_set["obj_id"], "small"), $alt)); - //$this->tpl->setVariable("IMG_TYPE", ilObject::_getIcon($a_set["obj_id"], "small", $this->getIconImageType()), - // $lng->txt("icon")." ".$lng->txt("obj_".$a_set["type"]))); - } + // $this->tpl->setVariable("", ); + + // surpress checkbox for particular object types AND the system role + if (!$objDefinition->hasCheckbox($a_set["type"]) || + $a_set["obj_id"] == SYSTEM_ROLE_ID || + $a_set["obj_id"] == SYSTEM_USER_ID || + $a_set["obj_id"] == ANONYMOUS_ROLE_ID) { + $this->tpl->touchBlock("no_checkbox"); + } else { + $this->tpl->setCurrentBlock("checkbox"); + $this->tpl->setVariable("ID", $a_set["ref_id"]); + $this->tpl->parseCurrentBlock(); + } + //build link + $class_name = $objDefinition->getClassName($a_set["type"]); + $class = strtolower("ilObj" . $class_name . "GUI"); + $ilCtrl->setParameterByClass($class, "ref_id", $a_set["ref_id"]); + $this->tpl->setVariable("HREF_TITLE", $ilCtrl->getLinkTargetByClass($class, "view")); + $ilCtrl->setParameterByClass($class, "ref_id", $_GET["ref_id"]); + + // TODO: broken! fix me + $title = $a_set["title"]; + if (is_array($_SESSION["clipboard"]["ref_ids"])) { + if (in_array($a_set["ref_id"], $_SESSION["clipboard"]["ref_ids"])) { + switch ($_SESSION["clipboard"]["cmd"]) { + case "cut": + $title = "" . $title . ""; + break; + + case "copy": + $title = "+ " . $title; + break; + + case "link": + $title = "< " . $title; + break; + } + } + } + $this->tpl->setVariable("VAL_TITLE", $title); + $this->tpl->setVariable("VAL_DESC", ilUtil::shortenText($a_set["desc"], ilObject::DESC_LENGTH, true)); + $this->tpl->setVariable("VAL_LAST_CHANGE", ilDatePresentation::formatDate(new ilDateTime($a_set["last_update"], IL_CAL_DATETIME))); + $alt = ($objDefinition->isPlugin($a_set["type"])) + ? $lng->txt("icon") . " " . ilObjectPlugin::lookupTxtById($a_set["type"], "obj_" . $a_set["type"]) + : $lng->txt("icon") . " " . $lng->txt("obj_" . $a_set["type"]); + $this->tpl->setVariable("IMG_TYPE", ilUtil::img(ilObject::_getIcon($a_set["obj_id"], "small"), $alt)); + //$this->tpl->setVariable("IMG_TYPE", ilObject::_getIcon($a_set["obj_id"], "small", $this->getIconImageType()), + // $lng->txt("icon")." ".$lng->txt("obj_".$a_set["type"]))); + } } -?> diff --git a/Services/Repository/classes/class.ilModulesTableGUI.php b/Services/Repository/classes/class.ilModulesTableGUI.php index 5e76275becfc7982623e1721e0f3485085d37c2a..a963e98b1277e3e27b0550f798ad8f0dc67b42e0 100644 --- a/Services/Repository/classes/class.ilModulesTableGUI.php +++ b/Services/Repository/classes/class.ilModulesTableGUI.php @@ -1,282 +1,271 @@ - - * @version $Id$ - * - * @ingroup ServicesRepository - */ -class ilModulesTableGUI extends ilTable2GUI -{ - /** - * @var ilCtrl - */ - protected $ctrl; + + * @version $Id$ + * + * @ingroup ServicesRepository + */ +class ilModulesTableGUI extends ilTable2GUI +{ + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilPluginAdmin - */ - protected $plugin_admin; + /** + * @var ilObjectDefinition + */ + protected $obj_definition; - protected $pos_group_options; // [array] - protected $old_grp_id; // [int] - - function __construct($a_parent_obj, $a_parent_cmd = "", $a_has_write = false) - { - global $DIC; + /** + * @var ilSetting + */ + protected $settings; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->obj_definition = $DIC["objDefinition"]; - $this->settings = $DIC->settings(); - $this->plugin_admin = $DIC["ilPluginAdmin"]; - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setId("repmodtbl"); - - $this->setTitle($lng->txt("cmps_repository_object_types")); - - $this->addColumn($lng->txt("cmps_add_new_rank"), ""); - $this->addColumn($lng->txt("cmps_rep_object"), ""); - $this->addColumn($lng->txt("cmps_module"), ""); - $this->addColumn($lng->txt("cmps_group"), ""); - $this->addColumn($lng->txt("cmps_enable_creation"), ""); - - if((bool)$a_has_write) - { - // save options command - $this->addCommandButton("saveModules", $lng->txt("cmps_save_options")); - } - - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.table_row_module.html", "Services/Repository"); - $this->setLimit(10000); - $this->setExternalSorting(true); - - $this->getComponents(); - - $this->old_grp_id = 0; - } - - /** - * Get pages for list. - */ - function getComponents() - { - $objDefinition = $this->obj_definition; - $ilSetting = $this->settings; - $lng = $this->lng; - $ilPluginAdmin = $this->plugin_admin; - - // unassigned objects should be last - $this->pos_group_options = array(0 => $lng->txt("rep_new_item_group_unassigned")); - $pos_group_map[0] = "9999"; - - include_once("Services/Repository/classes/class.ilObjRepositorySettings.php"); - foreach(ilObjRepositorySettings::getNewItemGroups() as $item) - { - // #12807 - if($item["type"] == ilObjRepositorySettings::NEW_ITEM_GROUP_TYPE_GROUP) - { - $this->pos_group_options[$item["id"]] = $item["title"]; - $pos_group_map[$item["id"]] = $item["pos"]; - } - } - - $obj_types = array(); - - // parse modules - include_once("./Services/Component/classes/class.ilModule.php"); - foreach(ilModule::getAvailableCoreModules() as $mod) - { - $has_repo = false; - $rep_types = - $objDefinition->getRepositoryObjectTypesForComponent(IL_COMP_MODULE, $mod["subdir"]); - if(sizeof($rep_types) > 0) - { - foreach($rep_types as $ridx => $rt) - { - // we only want to display repository modules - if($rt["repository"]) - { - $has_repo = true; - } - else - { - unset($rep_types[$ridx]); - } - } - } - if($has_repo) - { - foreach($rep_types as $rt) - { - $obj_types[$rt["id"]] = array( - "object" => $rt["class_name"], - "caption" => $lng->txt("obj_".$rt["id"]), - "subdir" => $mod["subdir"], - "grp" => $rt["grp"], - "default_pos" => $rt["default_pos"] - ); - } - } - } - - // parse plugins - $obj_types = $this->getPluginComponents($obj_types, IL_COMP_SERVICE, "Repository", "robj"); - $obj_types = $this->getPluginComponents($obj_types, IL_COMP_MODULE, "OrgUnit", "orguext"); - - // parse positions - $data = array(); - foreach($obj_types as $obj_type => $item) - { - $org_pos = $ilSetting->get("obj_add_new_pos_".$obj_type); - if(!(int)$org_pos) - { - // no setting yet, use default - $org_pos = $item["default_pos"]; - } - if(strlen($org_pos) < 8) - { - // "old" setting without group part, add "unassigned" group - $org_pos = $pos_group_map[0].str_pad($org_pos, 4, "0", STR_PAD_LEFT); - } - - $pos_grp_id = $ilSetting->get("obj_add_new_pos_grp_".$obj_type, 0); - - $group = null; - if ($item["grp"] != "") - { - $group = $objDefinition->getGroup($item["grp"]); - $group = $group["name"]; - } - - $data[] = array( - "id" => $obj_type, - "object" => $item["object"], - "caption" => $item["caption"], - "subdir" => $item["subdir"], - "pos" => (int)substr($org_pos, 4), - "pos_group" => $pos_grp_id, - "creation" => !(bool)$ilSetting->get("obj_dis_creation_".$obj_type, false), - "group_id" => $item["grp"], - "group" => $group, - "sort_key" => (int)$org_pos - ); - - } - - $data = ilUtil::sortArray($data, "sort_key", "asc", true); - - $this->setData($data); - } - - /** - * Standard Version of Fill Row. Most likely to - * be overwritten by derived class. - */ - protected function fillRow($a_set) - { - if($a_set["pos_group"] != $this->old_grp_id) - { - $this->tpl->setCurrentBlock("pos_grp_bl"); - $this->tpl->setVariable("TXT_POS_GRP", $this->pos_group_options[$a_set["pos_group"]]); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setCurrentBlock("tbl_content"); - $this->tpl->parseCurrentBlock(); - - $this->css_row = ($this->css_row != "tblrow1") - ? "tblrow1" - : "tblrow2"; - $this->tpl->setVariable("CSS_ROW", $this->css_row); - - $this->old_grp_id = $a_set["pos_group"]; - } - - // group - if ($a_set["group_id"] != "") - { - $this->tpl->setCurrentBlock("group"); - $this->tpl->setVariable("VAL_GROUP", $a_set["group"]); - $this->tpl->setVariable("VAL_GROUP_ID", $a_set["group_id"]); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setCurrentBlock("rep_object"); - // #11598 - using "caption" (from lng) instead of "object" - $this->tpl->setVariable("TXT_REP_OBJECT", $a_set["caption"]); - $this->tpl->setVariable("TXT_REP_OBJECT_ID", $a_set["id"]); - $this->tpl->setVariable("IMG_REP_OBJECT", - ilObject::_getIcon("", "tiny", $a_set["id"])); - - // grouping - $sel = ilUtil::formSelect($a_set["pos_group"], - "obj_grp[".$a_set["id"]."]", $this->pos_group_options, false, true); - $this->tpl->setVariable("GROUP_SEL", $sel); - - // position - $this->tpl->setVariable("VAR_POS", "obj_pos[".$a_set["id"]."]"); - $this->tpl->setVariable("VAL_POS", ilUtil::prepareFormOutput($a_set["pos"])); - - // enable creation - $this->tpl->setVariable("VAR_DISABLE_CREATION", "obj_enbl_creation[".$a_set["id"]."]"); - if ($a_set["creation"]) - { - $this->tpl->setVariable("CHECKED_DISABLE_CREATION", - ' checked="checked" '); - } - - $this->tpl->setVariable("TXT_MODULE_NAME", $a_set["subdir"]); - } - - /** - * @param $obj_types - * @param $component - * @param $slotName - * @param $slotId - * @return mixed - */ - protected function getPluginComponents($obj_types, $component, $slotName, $slotId) { - $ilPluginAdmin = $this->plugin_admin; - $lng = $this->lng; - include_once("./Services/Component/classes/class.ilPlugin.php"); - $pl_names = $ilPluginAdmin->getActivePluginsForSlot($component, $slotName, $slotId); - foreach ($pl_names as $pl_name) { - $pl_id = ilPlugin::lookupIdForName($component, $slotName, $slotId,$pl_name); - if ($pl_id) { - $obj_types[$pl_id] = array( - "object" => $pl_name, - "caption" => ilObjectPlugin::lookupTxtById($pl_id, "obj_" . $pl_id), - "subdir" => $lng->txt("cmps_plugin"), - "grp" => "", - "default_pos" => 2000 - ); - } - } - return $obj_types; - } -} - -?> \ No newline at end of file + /** + * @var ilPluginAdmin + */ + protected $plugin_admin; + + protected $pos_group_options; // [array] + protected $old_grp_id; // [int] + + public function __construct($a_parent_obj, $a_parent_cmd = "", $a_has_write = false) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->obj_definition = $DIC["objDefinition"]; + $this->settings = $DIC->settings(); + $this->plugin_admin = $DIC["ilPluginAdmin"]; + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setId("repmodtbl"); + + $this->setTitle($lng->txt("cmps_repository_object_types")); + + $this->addColumn($lng->txt("cmps_add_new_rank"), ""); + $this->addColumn($lng->txt("cmps_rep_object"), ""); + $this->addColumn($lng->txt("cmps_module"), ""); + $this->addColumn($lng->txt("cmps_group"), ""); + $this->addColumn($lng->txt("cmps_enable_creation"), ""); + + if ((bool) $a_has_write) { + // save options command + $this->addCommandButton("saveModules", $lng->txt("cmps_save_options")); + } + + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.table_row_module.html", "Services/Repository"); + $this->setLimit(10000); + $this->setExternalSorting(true); + + $this->getComponents(); + + $this->old_grp_id = 0; + } + + /** + * Get pages for list. + */ + public function getComponents() + { + $objDefinition = $this->obj_definition; + $ilSetting = $this->settings; + $lng = $this->lng; + $ilPluginAdmin = $this->plugin_admin; + + // unassigned objects should be last + $this->pos_group_options = array(0 => $lng->txt("rep_new_item_group_unassigned")); + $pos_group_map[0] = "9999"; + + include_once("Services/Repository/classes/class.ilObjRepositorySettings.php"); + foreach (ilObjRepositorySettings::getNewItemGroups() as $item) { + // #12807 + if ($item["type"] == ilObjRepositorySettings::NEW_ITEM_GROUP_TYPE_GROUP) { + $this->pos_group_options[$item["id"]] = $item["title"]; + $pos_group_map[$item["id"]] = $item["pos"]; + } + } + + $obj_types = array(); + + // parse modules + include_once("./Services/Component/classes/class.ilModule.php"); + foreach (ilModule::getAvailableCoreModules() as $mod) { + $has_repo = false; + $rep_types = + $objDefinition->getRepositoryObjectTypesForComponent(IL_COMP_MODULE, $mod["subdir"]); + if (sizeof($rep_types) > 0) { + foreach ($rep_types as $ridx => $rt) { + // we only want to display repository modules + if ($rt["repository"]) { + $has_repo = true; + } else { + unset($rep_types[$ridx]); + } + } + } + if ($has_repo) { + foreach ($rep_types as $rt) { + $obj_types[$rt["id"]] = array( + "object" => $rt["class_name"], + "caption" => $lng->txt("obj_" . $rt["id"]), + "subdir" => $mod["subdir"], + "grp" => $rt["grp"], + "default_pos" => $rt["default_pos"] + ); + } + } + } + + // parse plugins + $obj_types = $this->getPluginComponents($obj_types, IL_COMP_SERVICE, "Repository", "robj"); + $obj_types = $this->getPluginComponents($obj_types, IL_COMP_MODULE, "OrgUnit", "orguext"); + + // parse positions + $data = array(); + foreach ($obj_types as $obj_type => $item) { + $org_pos = $ilSetting->get("obj_add_new_pos_" . $obj_type); + if (!(int) $org_pos) { + // no setting yet, use default + $org_pos = $item["default_pos"]; + } + if (strlen($org_pos) < 8) { + // "old" setting without group part, add "unassigned" group + $org_pos = $pos_group_map[0] . str_pad($org_pos, 4, "0", STR_PAD_LEFT); + } + + $pos_grp_id = $ilSetting->get("obj_add_new_pos_grp_" . $obj_type, 0); + + $group = null; + if ($item["grp"] != "") { + $group = $objDefinition->getGroup($item["grp"]); + $group = $group["name"]; + } + + $data[] = array( + "id" => $obj_type, + "object" => $item["object"], + "caption" => $item["caption"], + "subdir" => $item["subdir"], + "pos" => (int) substr($org_pos, 4), + "pos_group" => $pos_grp_id, + "creation" => !(bool) $ilSetting->get("obj_dis_creation_" . $obj_type, false), + "group_id" => $item["grp"], + "group" => $group, + "sort_key" => (int) $org_pos + ); + } + + $data = ilUtil::sortArray($data, "sort_key", "asc", true); + + $this->setData($data); + } + + /** + * Standard Version of Fill Row. Most likely to + * be overwritten by derived class. + */ + protected function fillRow($a_set) + { + if ($a_set["pos_group"] != $this->old_grp_id) { + $this->tpl->setCurrentBlock("pos_grp_bl"); + $this->tpl->setVariable("TXT_POS_GRP", $this->pos_group_options[$a_set["pos_group"]]); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setCurrentBlock("tbl_content"); + $this->tpl->parseCurrentBlock(); + + $this->css_row = ($this->css_row != "tblrow1") + ? "tblrow1" + : "tblrow2"; + $this->tpl->setVariable("CSS_ROW", $this->css_row); + + $this->old_grp_id = $a_set["pos_group"]; + } + + // group + if ($a_set["group_id"] != "") { + $this->tpl->setCurrentBlock("group"); + $this->tpl->setVariable("VAL_GROUP", $a_set["group"]); + $this->tpl->setVariable("VAL_GROUP_ID", $a_set["group_id"]); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setCurrentBlock("rep_object"); + // #11598 - using "caption" (from lng) instead of "object" + $this->tpl->setVariable("TXT_REP_OBJECT", $a_set["caption"]); + $this->tpl->setVariable("TXT_REP_OBJECT_ID", $a_set["id"]); + $this->tpl->setVariable( + "IMG_REP_OBJECT", + ilObject::_getIcon("", "tiny", $a_set["id"]) + ); + + // grouping + $sel = ilUtil::formSelect( + $a_set["pos_group"], + "obj_grp[" . $a_set["id"] . "]", + $this->pos_group_options, + false, + true + ); + $this->tpl->setVariable("GROUP_SEL", $sel); + + // position + $this->tpl->setVariable("VAR_POS", "obj_pos[" . $a_set["id"] . "]"); + $this->tpl->setVariable("VAL_POS", ilUtil::prepareFormOutput($a_set["pos"])); + + // enable creation + $this->tpl->setVariable("VAR_DISABLE_CREATION", "obj_enbl_creation[" . $a_set["id"] . "]"); + if ($a_set["creation"]) { + $this->tpl->setVariable( + "CHECKED_DISABLE_CREATION", + ' checked="checked" ' + ); + } + + $this->tpl->setVariable("TXT_MODULE_NAME", $a_set["subdir"]); + } + + /** + * @param $obj_types + * @param $component + * @param $slotName + * @param $slotId + * @return mixed + */ + protected function getPluginComponents($obj_types, $component, $slotName, $slotId) + { + $ilPluginAdmin = $this->plugin_admin; + $lng = $this->lng; + include_once("./Services/Component/classes/class.ilPlugin.php"); + $pl_names = $ilPluginAdmin->getActivePluginsForSlot($component, $slotName, $slotId); + foreach ($pl_names as $pl_name) { + $pl_id = ilPlugin::lookupIdForName($component, $slotName, $slotId, $pl_name); + if ($pl_id) { + $obj_types[$pl_id] = array( + "object" => $pl_name, + "caption" => ilObjectPlugin::lookupTxtById($pl_id, "obj_" . $pl_id), + "subdir" => $lng->txt("cmps_plugin"), + "grp" => "", + "default_pos" => 2000 + ); + } + } + return $obj_types; + } +} diff --git a/Services/Repository/classes/class.ilNewItemGroupTableGUI.php b/Services/Repository/classes/class.ilNewItemGroupTableGUI.php index 0f47ea80650ef94316e82a753fbd5280e6d48ea7..5edfd5f08cd2a29d1f0425a21d6a1ccead03fc6d 100644 --- a/Services/Repository/classes/class.ilNewItemGroupTableGUI.php +++ b/Services/Repository/classes/class.ilNewItemGroupTableGUI.php @@ -1,137 +1,127 @@ - - * @version $Id$ - * - * @ingroup ServicesRepository - */ -class ilNewItemGroupTableGUI extends ilTable2GUI -{ - /** - * @var ilCtrl - */ - protected $ctrl; - - protected $has_write; // [bool] - - function __construct($a_parent_obj, $a_parent_cmd = "", $a_has_write = false) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->has_write = (bool)$a_has_write; - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setId("repnwitgrptbl"); - - $this->setTitle($lng->txt("rep_new_item_groups")); - - if($this->has_write) - { - $this->addColumn("", "", 1); - } - $this->addColumn($lng->txt("cmps_add_new_rank"), ""); - $this->addColumn($lng->txt("title"), ""); - $this->addColumn($lng->txt("rep_new_item_group_nr_subitems"), ""); - - if($this->has_write) - { - $this->addColumn($lng->txt("action"), ""); - } - - if($this->has_write) - { - $this->addCommandButton("saveNewItemGroupOrder", $lng->txt("cmps_save_options")); - $this->addMultiCommand("confirmDeleteNewItemGroup", $lng->txt("delete")); - } - - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.table_row_new_item_group.html", "Services/Repository"); - $this->setLimit(10000); - - $this->setExternalSorting(true); - $this->getGroups(); - } - - /** - * Get pages for list. - */ - function getGroups() - { - $lng = $this->lng; - - $data = array(); - - $subitems = ilObjRepositorySettings::getNewItemGroupSubItems(); - - if($subitems[0]) - { - ilUtil::sendInfo(sprintf( - $lng->txt("rep_new_item_group_unassigned_subitems"), - is_array($subitems[0]) ? sizeof($subitems[0]) : 0 - )); - unset($subitems[0]); - } - - foreach(ilObjRepositorySettings::getNewItemGroups() as $item) - { - $data[] = array( - "id" => $item["id"], - "pos" => $item["pos"], - "title" => $item["title"], - "type" => $item["type"], - "subitems" => is_array($subitems[$item["id"]]) ? sizeof($subitems[$item["id"]]) : 0 - ); - } - - $data = ilUtil::sortArray($data, "pos", "asc", true); - - $this->setData($data); - } - - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if($this->has_write) - { - $this->tpl->setVariable("VAR_MULTI", "grp_id[]"); - $this->tpl->setVariable("VAL_MULTI", $a_set["id"]); - } - - $this->tpl->setVariable("VAR_POS", "grp_order[".$a_set["id"]."]"); - $this->tpl->setVariable("VAL_POS", $a_set["pos"]); - $this->tpl->setVariable("TXT_TITLE", $a_set["title"]); - - if($a_set["type"] == ilObjRepositorySettings::NEW_ITEM_GROUP_TYPE_GROUP) - { - $this->tpl->setVariable("VAL_ITEMS", $a_set["subitems"]); - - if($this->has_write) - { - $ilCtrl->setParameter($this->parent_obj, "grp_id", $a_set["id"]); - $url = $ilCtrl->getLinkTarget($this->parent_obj, "editNewItemGroup"); - $ilCtrl->setParameter($this->parent_obj, "grp_id", ""); - - $this->tpl->setVariable("URL_EDIT", $url); - $this->tpl->setVariable("TXT_EDIT", $lng->txt("edit")); - } - } - } -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @ingroup ServicesRepository + */ +class ilNewItemGroupTableGUI extends ilTable2GUI +{ + /** + * @var ilCtrl + */ + protected $ctrl; + + protected $has_write; // [bool] + + public function __construct($a_parent_obj, $a_parent_cmd = "", $a_has_write = false) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->has_write = (bool) $a_has_write; + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setId("repnwitgrptbl"); + + $this->setTitle($lng->txt("rep_new_item_groups")); + + if ($this->has_write) { + $this->addColumn("", "", 1); + } + $this->addColumn($lng->txt("cmps_add_new_rank"), ""); + $this->addColumn($lng->txt("title"), ""); + $this->addColumn($lng->txt("rep_new_item_group_nr_subitems"), ""); + + if ($this->has_write) { + $this->addColumn($lng->txt("action"), ""); + } + + if ($this->has_write) { + $this->addCommandButton("saveNewItemGroupOrder", $lng->txt("cmps_save_options")); + $this->addMultiCommand("confirmDeleteNewItemGroup", $lng->txt("delete")); + } + + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.table_row_new_item_group.html", "Services/Repository"); + $this->setLimit(10000); + + $this->setExternalSorting(true); + $this->getGroups(); + } + + /** + * Get pages for list. + */ + public function getGroups() + { + $lng = $this->lng; + + $data = array(); + + $subitems = ilObjRepositorySettings::getNewItemGroupSubItems(); + + if ($subitems[0]) { + ilUtil::sendInfo(sprintf( + $lng->txt("rep_new_item_group_unassigned_subitems"), + is_array($subitems[0]) ? sizeof($subitems[0]) : 0 + )); + unset($subitems[0]); + } + + foreach (ilObjRepositorySettings::getNewItemGroups() as $item) { + $data[] = array( + "id" => $item["id"], + "pos" => $item["pos"], + "title" => $item["title"], + "type" => $item["type"], + "subitems" => is_array($subitems[$item["id"]]) ? sizeof($subitems[$item["id"]]) : 0 + ); + } + + $data = ilUtil::sortArray($data, "pos", "asc", true); + + $this->setData($data); + } + + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if ($this->has_write) { + $this->tpl->setVariable("VAR_MULTI", "grp_id[]"); + $this->tpl->setVariable("VAL_MULTI", $a_set["id"]); + } + + $this->tpl->setVariable("VAR_POS", "grp_order[" . $a_set["id"] . "]"); + $this->tpl->setVariable("VAL_POS", $a_set["pos"]); + $this->tpl->setVariable("TXT_TITLE", $a_set["title"]); + + if ($a_set["type"] == ilObjRepositorySettings::NEW_ITEM_GROUP_TYPE_GROUP) { + $this->tpl->setVariable("VAL_ITEMS", $a_set["subitems"]); + + if ($this->has_write) { + $ilCtrl->setParameter($this->parent_obj, "grp_id", $a_set["id"]); + $url = $ilCtrl->getLinkTarget($this->parent_obj, "editNewItemGroup"); + $ilCtrl->setParameter($this->parent_obj, "grp_id", ""); + + $this->tpl->setVariable("URL_EDIT", $url); + $this->tpl->setVariable("TXT_EDIT", $lng->txt("edit")); + } + } + } +} diff --git a/Services/Repository/classes/class.ilObjPluginDispatchGUI.php b/Services/Repository/classes/class.ilObjPluginDispatchGUI.php index 947e10ddd5bd3a81e4f6e8df8563349ea7e38303..45c3f3e216d24e3614643d515a3a21b8aef7f985 100644 --- a/Services/Repository/classes/class.ilObjPluginDispatchGUI.php +++ b/Services/Repository/classes/class.ilObjPluginDispatchGUI.php @@ -14,76 +14,68 @@ require_once('./Services/Repository/classes/class.ilObjectPlugin.php'); */ class ilObjPluginDispatchGUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * Constructor. - */ - function __construct() - { - global $DIC; + /** + * Constructor. + */ + public function __construct() + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - } - - function executeCommand() - { - $ilCtrl = $this->ctrl; - - $next_class = $ilCtrl->getNextClass(); - $cmd_class = $ilCtrl->getCmdClass(); + $this->ctrl = $DIC->ctrl(); + } + + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $next_class = $ilCtrl->getNextClass(); + $cmd_class = $ilCtrl->getCmdClass(); - if ($cmd_class != "ilobjplugindispatchgui" && $cmd_class != "") - { - $class_path = $ilCtrl->lookupClassPath($next_class); - include_once($class_path); - $class_name = $ilCtrl->getClassForClasspath($class_path); -//echo "-".$class_name."-".$class_path."-"; - $this->gui_obj = new $class_name($_GET["ref_id"]); - $ilCtrl->forwardCommand($this->gui_obj); - } - else - { - $this->processCommand($ilCtrl->getCmd()); - } - } - - /** - * Process command - */ - function processCommand($a_cmd) - { - switch ($a_cmd) - { - case "forward": - $this->forward(); - break; - } - } - - /** - * Forward command to plugin - */ - function forward() - { - $ilCtrl = $this->ctrl; - - $type = ilObject::_lookupType($_GET["ref_id"], true); - if ($type != "") - { - include_once("./Services/Component/classes/class.ilPlugin.php"); - $plugin = ilObjectPlugin::getPluginObjectByType($type); - if ($plugin) - { - $gui_cn = "ilObj".$plugin->getPluginName()."GUI"; - $ilCtrl->setParameterByClass($gui_cn, "ref_id", $_GET["ref_id"]); - $ilCtrl->redirectByClass($gui_cn, $_GET["forwardCmd"]); - } - } - } - - + if ($cmd_class != "ilobjplugindispatchgui" && $cmd_class != "") { + $class_path = $ilCtrl->lookupClassPath($next_class); + include_once($class_path); + $class_name = $ilCtrl->getClassForClasspath($class_path); + //echo "-".$class_name."-".$class_path."-"; + $this->gui_obj = new $class_name($_GET["ref_id"]); + $ilCtrl->forwardCommand($this->gui_obj); + } else { + $this->processCommand($ilCtrl->getCmd()); + } + } + + /** + * Process command + */ + public function processCommand($a_cmd) + { + switch ($a_cmd) { + case "forward": + $this->forward(); + break; + } + } + + /** + * Forward command to plugin + */ + public function forward() + { + $ilCtrl = $this->ctrl; + + $type = ilObject::_lookupType($_GET["ref_id"], true); + if ($type != "") { + include_once("./Services/Component/classes/class.ilPlugin.php"); + $plugin = ilObjectPlugin::getPluginObjectByType($type); + if ($plugin) { + $gui_cn = "ilObj" . $plugin->getPluginName() . "GUI"; + $ilCtrl->setParameterByClass($gui_cn, "ref_id", $_GET["ref_id"]); + $ilCtrl->redirectByClass($gui_cn, $_GET["forwardCmd"]); + } + } + } } diff --git a/Services/Repository/classes/class.ilObjRepositorySettings.php b/Services/Repository/classes/class.ilObjRepositorySettings.php index b095ecc8b1d522d9d3b7e4db5eafcb04bf50fd68..3982925ec7c21936c936875eb9ed33f57df9fe0f 100644 --- a/Services/Repository/classes/class.ilObjRepositorySettings.php +++ b/Services/Repository/classes/class.ilObjRepositorySettings.php @@ -1,326 +1,298 @@ - - * @version $Id: class.ilObjSystemFolder.php 33501 2012-03-03 11:11:05Z akill $ - * - * @ingroup ServicesRepository - */ -class ilObjRepositorySettings extends ilObject -{ - const NEW_ITEM_GROUP_TYPE_GROUP = 1; - const NEW_ITEM_GROUP_TYPE_SEPARATOR = 2; - - /** - * Constructor - * @access public - * @param integer reference_id or object_id - * @param boolean treat the id as reference_id (true) or object_id (false) - */ - function __construct($a_id,$a_call_by_reference = true) - { - $this->type = "reps"; - parent::__construct($a_id,$a_call_by_reference); - } - - function delete() - { - // DISABLED - return false; - } - - public static function addNewItemGroupSeparator() - { - global $DIC; - - $ilDB = $DIC->database(); - - // append - $pos = $ilDB->query("SELECT max(pos) mpos FROM il_new_item_grp"); - $pos = $ilDB->fetchAssoc($pos); - $pos = (int)$pos["mpos"]; - $pos += 10; - - $seq = $ilDB->nextID("il_new_item_grp"); - - $ilDB->manipulate("INSERT INTO il_new_item_grp". - " (id, pos, type) VALUES (". - $ilDB->quote($seq, "integer"). - ", ".$ilDB->quote($pos, "integer"). - ", ".$ilDB->quote(self::NEW_ITEM_GROUP_TYPE_SEPARATOR, "integer"). - ")"); - return true; - } - - public static function addNewItemGroup(array $a_titles) - { - global $DIC; - - $ilDB = $DIC->database(); - - // append - $pos = $ilDB->query("SELECT max(pos) mpos FROM il_new_item_grp"); - $pos = $ilDB->fetchAssoc($pos); - $pos = (int)$pos["mpos"]; - $pos += 10; - - $seq = $ilDB->nextID("il_new_item_grp"); - - $ilDB->manipulate("INSERT INTO il_new_item_grp". - " (id, titles, pos, type) VALUES (". - $ilDB->quote($seq, "integer"). - ", ".$ilDB->quote(serialize($a_titles), "text"). - ", ".$ilDB->quote($pos, "integer"). - ", ".$ilDB->quote(self::NEW_ITEM_GROUP_TYPE_GROUP, "integer"). - ")"); - return true; - } - - public static function updateNewItemGroup($a_id, array $a_titles) - { - global $DIC; - - $ilDB = $DIC->database(); - - $ilDB->manipulate("UPDATE il_new_item_grp". - " SET titles = ".$ilDB->quote(serialize($a_titles), "text"). - " WHERE id = ".$ilDB->quote($a_id, "integer")); - return true; - } - - public static function deleteNewItemGroup($a_id) - { - global $DIC; - - $ilDB = $DIC->database(); - $ilSetting = $DIC->settings(); - - // move subitems to unassigned - $sub_items = self::getNewItemGroupSubItems(); - $sub_items = $sub_items[$a_id]; - if($sub_items) - { - foreach($sub_items as $obj_type) - { - $old_pos = $ilSetting->get("obj_add_new_pos_".$obj_type); - if(strlen($old_pos) == 8) - { - $new_pos = "9999".substr($old_pos, 4); - $ilSetting->set("obj_add_new_pos_".$obj_type, $new_pos); - $ilSetting->set("obj_add_new_pos_grp_".$obj_type, 0); - } - } - } - - $ilDB->manipulate("DELETE FROM il_new_item_grp". - " WHERE id = ".$ilDB->quote($a_id, "integer")); - return true; - } - - public static function getNewItemGroups() - { - global $DIC; - - $ilDB = $DIC->database(); - $lng = $DIC->language(); - $ilUser = $DIC->user(); - - $def_lng = $lng->getDefaultLanguage(); - $usr_lng = $ilUser->getLanguage(); - - $res = array(); - - $set = $ilDB->query("SELECT * FROM il_new_item_grp ORDER BY pos"); - while($row = $ilDB->fetchAssoc($set)) - { - if($row["type"] == self::NEW_ITEM_GROUP_TYPE_GROUP) - { - $row["titles"] = unserialize($row["titles"]); - - $title = $row["titles"][$usr_lng]; - if(!$title) - { - $title = $row["titles"][$def_lng]; - } - if(!$title) - { - $title = array_shift($row["titles"]); - } - $row["title"] = $title; - } - else - { - $row["title"] = $lng->txt("rep_new_item_group_separator"); - } - - $res[$row["id"]] = $row; - } - - return $res; - } - - public static function updateNewItemGroupOrder(array $a_order) - { - global $DIC; - - $ilDB = $DIC->database(); - - asort($a_order); - $pos = 0; - foreach(array_keys($a_order) as $id) - { - $pos += 10; - - $ilDB->manipulate("UPDATE il_new_item_grp". - " SET pos = ".$ilDB->quote($pos, "integer"). - " WHERE id = ".$ilDB->quote($id, "integer")); - } - } - - protected static function getAllObjTypes() - { - global $DIC; - - $ilPluginAdmin = $DIC["ilPluginAdmin"]; - $objDefinition = $DIC["objDefinition"]; - - $res = array(); - - // parse modules - include_once("./Services/Component/classes/class.ilModule.php"); - foreach(ilModule::getAvailableCoreModules() as $mod) - { - $has_repo = false; - $rep_types = $objDefinition->getRepositoryObjectTypesForComponent(IL_COMP_MODULE, $mod["subdir"]); - if(sizeof($rep_types) > 0) - { - foreach($rep_types as $ridx => $rt) - { - // we only want to display repository modules - if($rt["repository"]) - { - $has_repo = true; - } - else - { - unset($rep_types[$ridx]); - } - } - } - if($has_repo) - { - foreach($rep_types as $rt) - { - $res[] = $rt["id"]; - } - } - } - - // parse plugins - include_once("./Services/Component/classes/class.ilPlugin.php"); - $pl_names = $ilPluginAdmin->getActivePluginsForSlot(IL_COMP_SERVICE, "Repository", "robj"); - foreach ($pl_names as $pl_name) - { - $pl_id = ilPlugin::lookupIdForName(IL_COMP_SERVICE, "Repository", "robj", $pl_name); - if($pl_id) - { - $res[] = $pl_id; - } - } - - return $res; - } - - public static function getNewItemGroupSubItems() - { - global $DIC; - - $ilSetting = $DIC->settings(); - - $res = array(); - - foreach(self::getAllObjTypes() as $type) - { - $pos_grp = $ilSetting->get("obj_add_new_pos_grp_".$type, 0); - $res[$pos_grp][] = $type; - } - - return $res; - } - - public static function getDefaultNewItemGrouping() - { - global $DIC; - - $lng = $DIC->language(); - - $res = array(); - - $groups = array( - "organisation" => array("fold", "sess", "cat", "catr", "crs", "crsr", "grp", "grpr", "itgr", "book", "prg"), - "communication" => array("frm", "chtr"), - "breaker1" => null, - "content" => array("file", "webr", "feed", "copa", "wiki", "blog", "lm", "htlm", "sahs", "lso", "glo", "dcl", "bibl", "mcst", "mep"), - "breaker2" => null, - "assessment" => array("exc", "tst", "qpl", "iass"), - "feedback" => array("poll", "svy", "spl"), - "templates" => array("prtt") - ); - - $pos = 0; - foreach($groups as $group => $items) - { - $pos += 10; - $grp_id = $pos/10; - - if(is_array($items)) - { - $title = $lng->txt("rep_add_new_def_grp_".$group); - - $res["groups"][$grp_id] = array("id" => $grp_id, - "titles" => array($lng->getUserLanguage() => $title), - "pos" => $pos, - "type" => self::NEW_ITEM_GROUP_TYPE_GROUP, - "title" => $title); - - foreach($items as $idx => $item) - { - $res["items"][$item] = $grp_id; - $res["sort"][$item] = str_pad($pos, 4, "0", STR_PAD_LEFT). - str_pad($idx+1, 4, "0", STR_PAD_LEFT); - } - } - else - { - $title = "COL_SEP"; - - $res["groups"][$grp_id] = array("id" => $grp_id, - "titles" => array($lng->getUserLanguage() => $title), - "pos" => $pos, - "type" => self::NEW_ITEM_GROUP_TYPE_SEPARATOR, - "title" => $title); - } - } - - return $res; - } - - public static function deleteObjectType($a_type) - { - global $DIC; - - $ilSetting = $DIC->settings(); - - // see ilObjRepositorySettingsGUI::saveModules() - $ilSetting->delete("obj_dis_creation_".$a_type); - $ilSetting->delete("obj_add_new_pos_".$a_type); - $ilSetting->delete("obj_add_new_pos_grp_".$a_type); - } -} - -?> \ No newline at end of file + + * @version $Id: class.ilObjSystemFolder.php 33501 2012-03-03 11:11:05Z akill $ + * + * @ingroup ServicesRepository + */ +class ilObjRepositorySettings extends ilObject +{ + const NEW_ITEM_GROUP_TYPE_GROUP = 1; + const NEW_ITEM_GROUP_TYPE_SEPARATOR = 2; + + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id, $a_call_by_reference = true) + { + $this->type = "reps"; + parent::__construct($a_id, $a_call_by_reference); + } + + public function delete() + { + // DISABLED + return false; + } + + public static function addNewItemGroupSeparator() + { + global $DIC; + + $ilDB = $DIC->database(); + + // append + $pos = $ilDB->query("SELECT max(pos) mpos FROM il_new_item_grp"); + $pos = $ilDB->fetchAssoc($pos); + $pos = (int) $pos["mpos"]; + $pos += 10; + + $seq = $ilDB->nextID("il_new_item_grp"); + + $ilDB->manipulate("INSERT INTO il_new_item_grp" . + " (id, pos, type) VALUES (" . + $ilDB->quote($seq, "integer") . + ", " . $ilDB->quote($pos, "integer") . + ", " . $ilDB->quote(self::NEW_ITEM_GROUP_TYPE_SEPARATOR, "integer") . + ")"); + return true; + } + + public static function addNewItemGroup(array $a_titles) + { + global $DIC; + + $ilDB = $DIC->database(); + + // append + $pos = $ilDB->query("SELECT max(pos) mpos FROM il_new_item_grp"); + $pos = $ilDB->fetchAssoc($pos); + $pos = (int) $pos["mpos"]; + $pos += 10; + + $seq = $ilDB->nextID("il_new_item_grp"); + + $ilDB->manipulate("INSERT INTO il_new_item_grp" . + " (id, titles, pos, type) VALUES (" . + $ilDB->quote($seq, "integer") . + ", " . $ilDB->quote(serialize($a_titles), "text") . + ", " . $ilDB->quote($pos, "integer") . + ", " . $ilDB->quote(self::NEW_ITEM_GROUP_TYPE_GROUP, "integer") . + ")"); + return true; + } + + public static function updateNewItemGroup($a_id, array $a_titles) + { + global $DIC; + + $ilDB = $DIC->database(); + + $ilDB->manipulate("UPDATE il_new_item_grp" . + " SET titles = " . $ilDB->quote(serialize($a_titles), "text") . + " WHERE id = " . $ilDB->quote($a_id, "integer")); + return true; + } + + public static function deleteNewItemGroup($a_id) + { + global $DIC; + + $ilDB = $DIC->database(); + $ilSetting = $DIC->settings(); + + // move subitems to unassigned + $sub_items = self::getNewItemGroupSubItems(); + $sub_items = $sub_items[$a_id]; + if ($sub_items) { + foreach ($sub_items as $obj_type) { + $old_pos = $ilSetting->get("obj_add_new_pos_" . $obj_type); + if (strlen($old_pos) == 8) { + $new_pos = "9999" . substr($old_pos, 4); + $ilSetting->set("obj_add_new_pos_" . $obj_type, $new_pos); + $ilSetting->set("obj_add_new_pos_grp_" . $obj_type, 0); + } + } + } + + $ilDB->manipulate("DELETE FROM il_new_item_grp" . + " WHERE id = " . $ilDB->quote($a_id, "integer")); + return true; + } + + public static function getNewItemGroups() + { + global $DIC; + + $ilDB = $DIC->database(); + $lng = $DIC->language(); + $ilUser = $DIC->user(); + + $def_lng = $lng->getDefaultLanguage(); + $usr_lng = $ilUser->getLanguage(); + + $res = array(); + + $set = $ilDB->query("SELECT * FROM il_new_item_grp ORDER BY pos"); + while ($row = $ilDB->fetchAssoc($set)) { + if ($row["type"] == self::NEW_ITEM_GROUP_TYPE_GROUP) { + $row["titles"] = unserialize($row["titles"]); + + $title = $row["titles"][$usr_lng]; + if (!$title) { + $title = $row["titles"][$def_lng]; + } + if (!$title) { + $title = array_shift($row["titles"]); + } + $row["title"] = $title; + } else { + $row["title"] = $lng->txt("rep_new_item_group_separator"); + } + + $res[$row["id"]] = $row; + } + + return $res; + } + + public static function updateNewItemGroupOrder(array $a_order) + { + global $DIC; + + $ilDB = $DIC->database(); + + asort($a_order); + $pos = 0; + foreach (array_keys($a_order) as $id) { + $pos += 10; + + $ilDB->manipulate("UPDATE il_new_item_grp" . + " SET pos = " . $ilDB->quote($pos, "integer") . + " WHERE id = " . $ilDB->quote($id, "integer")); + } + } + + protected static function getAllObjTypes() + { + global $DIC; + + $ilPluginAdmin = $DIC["ilPluginAdmin"]; + $objDefinition = $DIC["objDefinition"]; + + $res = array(); + + // parse modules + include_once("./Services/Component/classes/class.ilModule.php"); + foreach (ilModule::getAvailableCoreModules() as $mod) { + $has_repo = false; + $rep_types = $objDefinition->getRepositoryObjectTypesForComponent(IL_COMP_MODULE, $mod["subdir"]); + if (sizeof($rep_types) > 0) { + foreach ($rep_types as $ridx => $rt) { + // we only want to display repository modules + if ($rt["repository"]) { + $has_repo = true; + } else { + unset($rep_types[$ridx]); + } + } + } + if ($has_repo) { + foreach ($rep_types as $rt) { + $res[] = $rt["id"]; + } + } + } + + // parse plugins + include_once("./Services/Component/classes/class.ilPlugin.php"); + $pl_names = $ilPluginAdmin->getActivePluginsForSlot(IL_COMP_SERVICE, "Repository", "robj"); + foreach ($pl_names as $pl_name) { + $pl_id = ilPlugin::lookupIdForName(IL_COMP_SERVICE, "Repository", "robj", $pl_name); + if ($pl_id) { + $res[] = $pl_id; + } + } + + return $res; + } + + public static function getNewItemGroupSubItems() + { + global $DIC; + + $ilSetting = $DIC->settings(); + + $res = array(); + + foreach (self::getAllObjTypes() as $type) { + $pos_grp = $ilSetting->get("obj_add_new_pos_grp_" . $type, 0); + $res[$pos_grp][] = $type; + } + + return $res; + } + + public static function getDefaultNewItemGrouping() + { + global $DIC; + + $lng = $DIC->language(); + + $res = array(); + + $groups = array( + "organisation" => array("fold", "sess", "cat", "catr", "crs", "crsr", "grp", "grpr", "itgr", "book", "prg"), + "communication" => array("frm", "chtr"), + "breaker1" => null, + "content" => array("file", "webr", "feed", "copa", "wiki", "blog", "lm", "htlm", "sahs", "lso", "glo", "dcl", "bibl", "mcst", "mep"), + "breaker2" => null, + "assessment" => array("exc", "tst", "qpl", "iass"), + "feedback" => array("poll", "svy", "spl"), + "templates" => array("prtt") + ); + + $pos = 0; + foreach ($groups as $group => $items) { + $pos += 10; + $grp_id = $pos/10; + + if (is_array($items)) { + $title = $lng->txt("rep_add_new_def_grp_" . $group); + + $res["groups"][$grp_id] = array("id" => $grp_id, + "titles" => array($lng->getUserLanguage() => $title), + "pos" => $pos, + "type" => self::NEW_ITEM_GROUP_TYPE_GROUP, + "title" => $title); + + foreach ($items as $idx => $item) { + $res["items"][$item] = $grp_id; + $res["sort"][$item] = str_pad($pos, 4, "0", STR_PAD_LEFT) . + str_pad($idx+1, 4, "0", STR_PAD_LEFT); + } + } else { + $title = "COL_SEP"; + + $res["groups"][$grp_id] = array("id" => $grp_id, + "titles" => array($lng->getUserLanguage() => $title), + "pos" => $pos, + "type" => self::NEW_ITEM_GROUP_TYPE_SEPARATOR, + "title" => $title); + } + } + + return $res; + } + + public static function deleteObjectType($a_type) + { + global $DIC; + + $ilSetting = $DIC->settings(); + + // see ilObjRepositorySettingsGUI::saveModules() + $ilSetting->delete("obj_dis_creation_" . $a_type); + $ilSetting->delete("obj_add_new_pos_" . $a_type); + $ilSetting->delete("obj_add_new_pos_grp_" . $a_type); + } +} diff --git a/Services/Repository/classes/class.ilObjRepositorySettingsAccess.php b/Services/Repository/classes/class.ilObjRepositorySettingsAccess.php index 609031cc8e455db102bfbfa7d8e50dfcc40a7ad2..edf11d86d6a6544eeebf25b5c584dd35f280a3e0 100644 --- a/Services/Repository/classes/class.ilObjRepositorySettingsAccess.php +++ b/Services/Repository/classes/class.ilObjRepositorySettingsAccess.php @@ -1,20 +1,16 @@ - - * @version $Id$ - * - * @ingroup ServicesRepository - */ -class ilObjRepositorySettingsAccess extends ilObjectAccess -{ - - -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @ingroup ServicesRepository + */ +class ilObjRepositorySettingsAccess extends ilObjectAccess +{ +} diff --git a/Services/Repository/classes/class.ilObjRepositorySettingsGUI.php b/Services/Repository/classes/class.ilObjRepositorySettingsGUI.php index 9ef201903aede161b44e56d43729016ce79fc1eb..b6b99698b0c4e5df64b73fb9b4ca6238a5acd949 100644 --- a/Services/Repository/classes/class.ilObjRepositorySettingsGUI.php +++ b/Services/Repository/classes/class.ilObjRepositorySettingsGUI.php @@ -1,772 +1,735 @@ - - * @version $Id$ - * - * @ilCtrl_Calls ilObjRepositorySettingsGUI: ilPermissionGUI - * - * @ingroup ServicesRepository - */ -class ilObjRepositorySettingsGUI extends ilObjectGUI -{ - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) - { - global $DIC; - - $this->error = $DIC["ilErr"]; - $this->access = $DIC->access(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->settings = $DIC->settings(); - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->toolbar = $DIC->toolbar(); - parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); - - $this->type = 'reps'; - $this->lng->loadLanguageModule('rep'); - $this->lng->loadLanguageModule('cmps'); - } - - public function executeCommand() - { - $ilErr = $this->error; - $ilAccess = $this->access; - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - $this->prepareOutput(); - - if(!$ilAccess->checkAccess('read', '', $this->object->getRefId())) - { - $ilErr->raiseError($this->lng->txt('no_permission'), $ilErr->WARNING); - } - - switch($next_class) - { - case 'ilpermissiongui': - $this->tabs_gui->setTabActive('perm_settings'); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $this->ctrl->forwardCommand($perm_gui); - break; - - default: - $this->$cmd(); - break; - } - return true; - } - - public function getAdminTabs() - { - $rbacsystem = $this->rbacsystem; - - $this->tabs_gui->addTab("settings", - $this->lng->txt("settings"), - $this->ctrl->getLinkTarget($this, "view")); - - $this->tabs_gui->addTab("icons", - $this->lng->txt("rep_custom_icons"), - $this->ctrl->getLinkTarget($this, "customIcons")); - - $this->tabs_gui->addTab("modules", - $this->lng->txt("cmps_repository_object_types"), - $this->ctrl->getLinkTarget($this, "listModules")); - - if ($rbacsystem->checkAccess('edit_permission',$this->object->getRefId())) - { - $this->tabs_gui->addTab("perm_settings", - $this->lng->txt("perm_settings"), - $this->ctrl->getLinkTargetByClass('ilpermissiongui',"perm")); - } - } - - public function view(ilPropertyFormGUI $a_form = null) - { - $this->tabs_gui->activateTab("settings"); - - if(!$a_form) - { - $a_form = $this->initSettingsForm(); - } - - $this->tpl->setContent($a_form->getHTML()); - } - - protected function initSettingsForm() - { - $ilSetting = $this->settings; - $ilAccess = $this->access; - - include_once('Services/Form/classes/class.ilPropertyFormGUI.php'); - $form = new ilPropertyFormGUI(); - $form->setTitle($this->lng->txt("settings")); - $form->setFormAction($this->ctrl->getFormAction($this, 'saveSettings')); - - // default repository view - $options = array( - "flat" => $this->lng->txt("flatview"), - "tree" => $this->lng->txt("treeview") - ); - $si = new ilSelectInputGUI($this->lng->txt("def_repository_view"), "default_rep_view"); - $si->setOptions($options); - $si->setInfo($this->lng->txt("")); - if ($ilSetting->get("default_repository_view") == "tree") - { - $si->setValue("tree"); - } - else - { - $si->setValue("flat"); - } - $form->addItem($si); - - // - $options = array( - "" => $this->lng->txt("adm_rep_tree_only_container"), - "tree" => $this->lng->txt("adm_all_resource_types") - ); - - // repository tree - $radg = new ilRadioGroupInputGUI($this->lng->txt("adm_rep_tree_presentation"), "tree_pres"); - $radg->setValue($ilSetting->get("repository_tree_pres")); - $op1 = new ilRadioOption($this->lng->txt("adm_rep_tree_only_cntr"), "", - $this->lng->txt("adm_rep_tree_only_cntr_info")); - $radg->addOption($op1); - - $op2 = new ilRadioOption($this->lng->txt("adm_rep_tree_all_types"), "all_types", - $this->lng->txt("adm_rep_tree_all_types_info")); - - // limit tree in courses and groups - $cb = new ilCheckboxInputGUI($this->lng->txt("adm_rep_tree_limit_grp_crs"), "rep_tree_limit_grp_crs"); - $cb->setChecked($ilSetting->get("rep_tree_limit_grp_crs")); - $cb->setInfo($this->lng->txt("adm_rep_tree_limit_grp_crs_info")); - $op2->addSubItem($cb); - - $radg->addOption($op2); - - $form->addItem($radg); - - // limit items in tree - $tree_limit = new ilCheckboxInputGUI($this->lng->txt("rep_tree_limit"), "rep_tree_limit"); - $tree_limit->setChecked($ilSetting->get("rep_tree_limit_number") > 0); - $tree_limit->setInfo($this->lng->txt("rep_tree_limit_info")); - $form->addItem($tree_limit); - - // limit items in tree (number) - $tree_limit_number = new ilNumberInputGUI($this->lng->txt("rep_tree_limit_number"), "rep_tree_limit_number"); - $tree_limit_number->setMaxLength(3); - $tree_limit_number->setSize(3); - $tree_limit_number->setValue($ilSetting->get("rep_tree_limit_number")); - $tree_limit_number->setInfo($this->lng->txt("rep_tree_limit_number_info")); - $tree_limit->addSubItem($tree_limit_number); - - // breadcrumbs start with courses - $cb = new ilCheckboxInputGUI($this->lng->txt("rep_breadcr_crs"), "rep_breadcr_crs"); - $cb->setChecked((int) $ilSetting->get("rep_breadcr_crs")); - $form->addItem($cb); - - $radg = new ilRadioGroupInputGUI($this->lng->txt("rep_breadcr_crs"), "rep_breadcr_crs_overwrite"); - $radg->setValue((int) $ilSetting->get("rep_breadcr_crs_overwrite")); - - $op0 = new ilRadioOption($this->lng->txt("rep_breadcr_crs_overwrite"), 1); - $cb0 = new ilCheckboxInputGUI($this->lng->txt("rep_default"), "rep_breadcr_crs_default"); - $cb0->setChecked((int) $ilSetting->get("rep_breadcr_crs_default")); - $op0->addSubItem($cb0); - $radg->addOption($op0); - - $op1 = new ilRadioOption($this->lng->txt("rep_breadcr_crs_overwrite_not"), 0); - $radg->addOption($op1); - - - $cb->addSubItem($radg); - - - - // trash - $cb = new ilCheckboxInputGUI($this->lng->txt("enable_trash"), "enable_trash"); - $cb->setInfo($this->lng->txt("enable_trash_info")); - if ($ilSetting->get("enable_trash")) - { - $cb->setChecked(true); - } - $form->addItem($cb); - - // change event - require_once 'Services/Tracking/classes/class.ilChangeEvent.php'; - $this->lng->loadLanguageModule("trac"); - $event = new ilCheckboxInputGUI($this->lng->txt('trac_show_repository_views'), 'change_event_tracking'); - $event->setInfo($this->lng->txt("trac_show_repository_views_info")); - $event->setChecked(ilChangeEvent::_isActive()); - $form->addItem($event); - - - include_once "Services/Administration/classes/class.ilAdministrationSettingsFormHandler.php"; - ilAdministrationSettingsFormHandler::addFieldsToForm( - ilAdministrationSettingsFormHandler::FORM_REPOSITORY, - $form, - $this - ); - - - // object lists - - $lists = new ilFormSectionHeaderGUI(); - $lists->setTitle($this->lng->txt("rep_object_lists")); - $form->addItem($lists); - - $sdesc = new ilCheckboxInputGUI($this->lng->txt("adm_rep_shorten_description"), "rep_shorten_description"); - $sdesc->setInfo($this->lng->txt("adm_rep_shorten_description_info")); - $sdesc->setChecked($ilSetting->get("rep_shorten_description")); - $form->addItem($sdesc); - - $sdesclen = new ilNumberInputGUI($this->lng->txt("adm_rep_shorten_description_length"), "rep_shorten_description_length"); - $sdesclen->setValue($ilSetting->get("rep_shorten_description_length")); - $sdesclen->setSize(3); - $sdesc->addSubItem($sdesclen); - - // load action commands asynchronously - $cb = new ilCheckboxInputGUI($this->lng->txt("adm_item_cmd_asynch"), "item_cmd_asynch"); - $cb->setInfo($this->lng->txt("adm_item_cmd_asynch_info")); - $cb->setChecked($ilSetting->get("item_cmd_asynch")); - $form->addItem($cb); - - // notes/comments/tagging - $pl = new ilCheckboxInputGUI($this->lng->txt('adm_show_comments_tagging_in_lists'),'comments_tagging_in_lists'); - $pl->setValue(1); - $pl->setChecked($ilSetting->get('comments_tagging_in_lists')); - $form->addItem($pl); - - $pltags = new ilCheckboxInputGUI($this->lng->txt('adm_show_comments_tagging_in_lists_tags'),'comments_tagging_in_lists_tags'); - $pltags->setValue(1); - $pltags->setChecked($ilSetting->get('comments_tagging_in_lists_tags')); - $pl->addSubItem($pltags); - - if($ilAccess->checkAccess('write','',$this->object->getRefId())) - { - $form->addCommandButton('saveSettings', $this->lng->txt('save')); - } - - return $form; - } - - public function saveSettings() - { - $ilSetting = $this->settings; - $ilAccess = $this->access; - - if(!$ilAccess->checkAccess('write','',$this->object->getRefId())) - { - $this->ctrl->redirect($this, "view"); - } - - $form = $this->initSettingsForm(); - if ($form->checkInput()) - { - $ilSetting->set("default_repository_view", $_POST["default_rep_view"]); - - $ilSetting->set("repository_tree_pres", $_POST["tree_pres"]); - if ($_POST["tree_pres"] == "") - { - $_POST["rep_tree_limit_grp_crs"] = ""; - } - if ($_POST["rep_tree_limit_grp_crs"] && !$ilSetting->get("rep_tree_limit_grp_crs")) - { - $_POST["rep_tree_synchronize"] = true; - } - else if (!$_POST["rep_tree_synchronize"] && $ilSetting->get("rep_tree_synchronize")) - { - $_POST["rep_tree_limit_grp_crs"] = false; - } - $ilSetting->set("rep_tree_limit_grp_crs", $_POST["rep_tree_limit_grp_crs"]); - - // $ilSetting->set('rep_cache',(int) $_POST['rep_cache']); - // $ilSetting->set("rep_tree_synchronize", $_POST["rep_tree_synchronize"]); - - $ilSetting->set("enable_trash", $_POST["enable_trash"]); - - - $ilSetting->set("rep_breadcr_crs_overwrite", (int) $_POST["rep_breadcr_crs_overwrite"]); - $ilSetting->set("rep_breadcr_crs", (int) $_POST["rep_breadcr_crs"]); - $ilSetting->set("rep_breadcr_crs_default", (int) $_POST["rep_breadcr_crs_default"]); - - - $ilSetting->set("rep_shorten_description", $form->getInput('rep_shorten_description')); - $ilSetting->set("rep_shorten_description_length", (int)$form->getInput('rep_shorten_description_length')); - $ilSetting->set('item_cmd_asynch',(int) $_POST['item_cmd_asynch']); - $ilSetting->set('comments_tagging_in_lists',(int) $_POST['comments_tagging_in_lists']); - $ilSetting->set('comments_tagging_in_lists_tags',(int) $_POST['comments_tagging_in_lists_tags']); - - // repository tree limit of children - $limit_number = ($_POST['rep_tree_limit'] && $_POST['rep_tree_limit_number'] > 0) - ? (int) $_POST['rep_tree_limit_number'] - : 0; - $ilSetting->set('rep_tree_limit_number', $limit_number); - - require_once 'Services/Tracking/classes/class.ilChangeEvent.php'; - if ($form->getInput('change_event_tracking')) - { - ilChangeEvent::_activate(); - } - else - { - ilChangeEvent::_deactivate(); - } - - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "view"); - } - - $form->setValuesByPost(); - $this->view($form); - } - - public function customIcons(ilPropertyFormGUI $a_form = null) - { - $this->tabs_gui->activateTab("icons"); - - if(!$a_form) - { - $a_form = $this->initCustomIconsForm(); - } - - $this->tpl->setContent($a_form->getHTML()); - } - - protected function initCustomIconsForm() - { - $ilSetting = $this->settings; - $ilAccess = $this->access; - - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - include_once "Services/Form/classes/class.ilCombinationInputGUI.php"; - $form = new ilPropertyFormGUI(); - $form->setTitle($this->lng->txt("rep_custom_icons")); - $form->setFormAction($this->ctrl->getFormAction($this, 'saveCustomIcons')); - - $cb = new ilCheckboxInputGUI($this->lng->txt("enable_custom_icons"), "custom_icons"); - $cb->setInfo($this->lng->txt("enable_custom_icons_info")); - $cb->setChecked($ilSetting->get("custom_icons")); - $form->addItem($cb); - - if($ilAccess->checkAccess('write','',$this->object->getRefId())) - { - $form->addCommandButton('saveCustomIcons', $this->lng->txt('save')); - } - - return $form; - } - - public function saveCustomIcons() - { - $ilSetting = $this->settings; - $ilAccess = $this->access; - - if(!$ilAccess->checkAccess('write','',$this->object->getRefId())) - { - $this->ctrl->redirect($this, "customIcons"); - } - - $form = $this->initCustomIconsForm(); - if ($form->checkInput()) - { - $ilSetting->set("custom_icons", (int)$form->getInput("custom_icons")); - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "customIcons"); - } - - $form->setValuesByPost(); - $this->customIcons($form); - } - - protected function setModuleSubTabs($a_active) - { - $this->tabs_gui->activateTab('modules'); - - $this->tabs_gui->addSubTab("list_mods", - $this->lng->txt("rep_new_item_menu"), - $this->ctrl->getLinkTarget($this, "listModules")); - - $this->tabs_gui->addSubTab("new_item_groups", - $this->lng->txt("rep_new_item_groups"), - $this->ctrl->getLinkTarget($this, "listNewItemGroups")); - - $this->tabs_gui->activateSubTab($a_active); - } - - protected function listModules() - { - $ilAccess = $this->access; - - $this->setModuleSubTabs("list_mods"); - - $has_write = $ilAccess->checkAccess('write','',$this->object->getRefId()); - - include_once("./Services/Repository/classes/class.ilModulesTableGUI.php"); - $comp_table = new ilModulesTableGUI($this, "listModules", $has_write); - - $this->tpl->setContent($comp_table->getHTML()); - } - - protected function saveModules() - { - $ilSetting = $this->settings; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilAccess = $this->access; - - if(!is_array($_POST["obj_grp"]) || - !is_array($_POST["obj_pos"]) || - !$ilAccess->checkAccess('write','',$this->object->getRefId())) - { - $ilCtrl->redirect($this, "listModules"); - } - - $grp_pos_map = array(0 => 9999); - include_once("Services/Repository/classes/class.ilObjRepositorySettings.php"); - foreach(ilObjRepositorySettings::getNewItemGroups() as $item) - { - $grp_pos_map[$item["id"]] = $item["pos"]; - } - - $type_pos_map = array(); - foreach($_POST["obj_pos"] as $obj_type => $pos) - { - $grp_id = (int)$_POST["obj_grp"][$obj_type]; - $type_pos_map[$grp_id][$obj_type] = $pos; - - // enable creation? - $ilSetting->set("obj_dis_creation_".$obj_type, !(int)$_POST["obj_enbl_creation"][$obj_type]); - } - - foreach($type_pos_map as $grp_id => $obj_types) - { - $grp_pos = str_pad($grp_pos_map[$grp_id], 4, "0", STR_PAD_LEFT); - - asort($obj_types); - $pos = 0; - foreach(array_keys($obj_types) as $obj_type) - { - $pos += 10; - $type_pos = $grp_pos.str_pad($pos, 4, "0", STR_PAD_LEFT); - $ilSetting->set("obj_add_new_pos_".$obj_type, $type_pos); - $ilSetting->set("obj_add_new_pos_grp_".$obj_type, $grp_id); - } - } - - /* - if (count($double) == 0) - { - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - } - else - { - ilUtil::sendInfo($lng->txt("cmps_duplicate_positions")." ".implode($double, ", "), true); - } - */ - - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "listModules"); - } - - protected function listNewItemGroups() - { - $ilToolbar = $this->toolbar; - $ilAccess = $this->access; - - $this->setModuleSubTabs("new_item_groups"); - - $has_write = $ilAccess->checkAccess('write','',$this->object->getRefId()); - - if($has_write) - { - $ilToolbar->addButton($this->lng->txt("rep_new_item_group_add"), - $this->ctrl->getLinkTarget($this, "addNewItemGroup")); - - $ilToolbar->addButton($this->lng->txt("rep_new_item_group_add_separator"), - $this->ctrl->getLinkTarget($this, "addNewItemGroupSeparator")); - } - - include_once("./Services/Repository/classes/class.ilNewItemGroupTableGUI.php"); - $grp_table = new ilNewItemGroupTableGUI($this, "listNewItemGroups", $has_write); - - $this->tpl->setContent($grp_table->getHTML()); - } - - protected function initNewItemGroupForm($a_grp_id = false) - { - $this->setModuleSubTabs("new_item_groups"); - - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $form = new ilPropertyFormGUI(); - - $this->lng->loadLanguageModule("meta"); - $def_lng = $this->lng->getDefaultLanguage(); - - $title = new ilTextInputGUI($this->lng->txt("title"), "title_".$def_lng); - $title->setInfo($this->lng->txt("meta_l_".$def_lng). - " (".$this->lng->txt("default_language").")"); - $title->setRequired(true); - $form->addItem($title); - - foreach($this->lng->getInstalledLanguages() as $lang_id) - { - if($lang_id != $def_lng) - { - $title = new ilTextInputGUI($this->lng->txt("translation"), "title_".$lang_id); - $title->setInfo($this->lng->txt("meta_l_".$lang_id)); - $form->addItem($title); - } - } - - if(!$a_grp_id) - { - $form->setTitle($this->lng->txt("rep_new_item_group_add")); - $form->setFormAction($this->ctrl->getFormAction($this, "saveNewItemGroup")); - - $form->addCommandButton("saveNewItemGroup", $this->lng->txt("save")); - } - else - { - $form->setTitle($this->lng->txt("rep_new_item_group_edit")); - $form->setFormAction($this->ctrl->getFormAction($this, "updateNewItemGroup")); - - include_once("Services/Repository/classes/class.ilObjRepositorySettings.php"); - $grp = ilObjRepositorySettings::getNewItemGroups(); - $grp = $grp[$a_grp_id]; - - foreach($grp["titles"] as $id => $value) - { - $field = $form->getItemByPostVar("title_".$id); - if($field) - { - $field->setValue($value); - } - } - - $form->addCommandButton("updateNewItemGroup", $this->lng->txt("save")); - } - $form->addCommandButton("listNewItemGroups", $this->lng->txt("cancel")); - - return $form; - } - - protected function addNewItemGroup(ilPropertyFormGUI $a_form = null) - { - if(!$a_form) - { - $a_form = $this->initNewItemGroupForm(); - } - - $this->tpl->setContent($a_form->getHTML()); - } - - protected function saveNewItemGroup() - { - $form = $this->initNewItemGroupForm(); - if($form->checkInput()) - { - $titles = array(); - foreach($this->lng->getInstalledLanguages() as $lang_id) - { - $titles[$lang_id] = $form->getInput("title_".$lang_id); - } - - include_once("Services/Repository/classes/class.ilObjRepositorySettings.php"); - if(ilObjRepositorySettings::addNewItemGroup($titles)) - { - ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); - $this->ctrl->redirect($this, "listNewItemGroups"); - } - } - - $form->setValuesByPost(); - $this->addNewItemGroup($form); - } - - protected function editNewItemGroup(ilPropertyFormGUI $a_form = null) - { - $grp_id = (int)$_GET["grp_id"]; - if(!$grp_id) - { - $this->ctrl->redirect($this, "listNewItemGroups"); - } - - if(!$a_form) - { - $this->ctrl->setParameter($this, "grp_id", $grp_id); - $a_form = $this->initNewItemGroupForm($grp_id); - } - - $this->tpl->setContent($a_form->getHTML()); - } - - protected function updateNewItemGroup() - { - $grp_id = (int)$_GET["grp_id"]; - if(!$grp_id) - { - $this->ctrl->redirect($this, "listNewItemGroups"); - } - - $this->ctrl->setParameter($this, "grp_id", $grp_id); - - $form = $this->initNewItemGroupForm($grp_id); - if($form->checkInput()) - { - $titles = array(); - foreach($this->lng->getInstalledLanguages() as $lang_id) - { - $titles[$lang_id] = $form->getInput("title_".$lang_id); - } - - include_once("Services/Repository/classes/class.ilObjRepositorySettings.php"); - if(ilObjRepositorySettings::updateNewItemGroup($grp_id, $titles)) - { - ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); - $this->ctrl->redirect($this, "listNewItemGroups"); - } - } - - $form->setValuesByPost(); - $this->addNewItemGroup($form); - } - - protected function addNewItemGroupSeparator() - { - include_once("Services/Repository/classes/class.ilObjRepositorySettings.php"); - if(ilObjRepositorySettings::addNewItemGroupSeparator()) - { - ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); - } - $this->ctrl->redirect($this, "listNewItemGroups"); - } - - protected function saveNewItemGroupOrder() - { - $ilSetting = $this->settings; - - if(is_array($_POST["grp_order"])) - { - include_once("Services/Repository/classes/class.ilObjRepositorySettings.php"); - ilObjRepositorySettings::updateNewItemGroupOrder($_POST["grp_order"]); - - $grp_pos_map = array(); - include_once("Services/Repository/classes/class.ilObjRepositorySettings.php"); - foreach(ilObjRepositorySettings::getNewItemGroups() as $item) - { - $grp_pos_map[$item["id"]] = str_pad($item["pos"], 4, "0", STR_PAD_LEFT); - } - - // update order of assigned objects - foreach(ilObjRepositorySettings::getNewItemGroupSubItems() as $grp_id => $subitems) - { - // unassigned objects will always be last - if($grp_id) - { - foreach($subitems as $obj_type) - { - $old_pos = $ilSetting->get("obj_add_new_pos_".$obj_type); - if(strlen($old_pos) == 8) - { - $new_pos = $grp_pos_map[$grp_id].substr($old_pos, 4); - $ilSetting->set("obj_add_new_pos_".$obj_type, $new_pos); - } - } - } - } - - ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); - } - $this->ctrl->redirect($this, "listNewItemGroups"); - } - - protected function confirmDeleteNewItemGroup() - { - if(!is_array($_POST["grp_id"])) - { - ilUtil::sendFailure($this->lng->txt("select_one")); - return $this->listNewItemGroups(); - } - - $this->setModuleSubTabs("new_item_groups"); - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setHeaderText($this->lng->txt("rep_new_item_group_delete_sure")); - - $cgui->setFormAction($this->ctrl->getFormAction($this)); - $cgui->setCancel($this->lng->txt("cancel"), "listNewItemGroups"); - $cgui->setConfirm($this->lng->txt("confirm"), "deleteNewItemGroup"); - - include_once("Services/Repository/classes/class.ilObjRepositorySettings.php"); - $groups = ilObjRepositorySettings::getNewItemGroups(); - - foreach ($_POST["grp_id"] as $grp_id) - { - $cgui->addItem("grp_id[]", $grp_id, $groups[$grp_id]["title"]); - } - - $this->tpl->setContent($cgui->getHTML()); - } - - protected function deleteNewItemGroup() - { - if(!is_array($_POST["grp_id"])) - { - return $this->listNewItemGroups(); - } - - include_once("Services/Repository/classes/class.ilObjRepositorySettings.php"); - foreach($_POST["grp_id"] as $grp_id) - { - ilObjRepositorySettings::deleteNewItemGroup($grp_id); - } - - ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); - $this->ctrl->redirect($this, "listNewItemGroups"); - } - - public function addToExternalSettingsForm($a_form_id) - { - $ilSetting = $this->settings; - - switch($a_form_id) - { - case ilAdministrationSettingsFormHandler::FORM_LP: - - require_once 'Services/Tracking/classes/class.ilChangeEvent.php'; - $fields = array('trac_show_repository_views' => array(ilChangeEvent::_isActive(), ilAdministrationSettingsFormHandler::VALUE_BOOL)); - - return array(array("view", $fields)); - - - case ilAdministrationSettingsFormHandler::FORM_TAGGING: - - $fields = array( - 'adm_show_comments_tagging_in_lists' => array($ilSetting->get('comments_tagging_in_lists'), ilAdministrationSettingsFormHandler::VALUE_BOOL, - array('adm_show_comments_tagging_in_lists_tags' => array($ilSetting->get('comments_tagging_in_lists_tags'), ilAdministrationSettingsFormHandler::VALUE_BOOL)) - )); - - return array(array("view", $fields)); - } - } -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @ilCtrl_Calls ilObjRepositorySettingsGUI: ilPermissionGUI + * + * @ingroup ServicesRepository + */ +class ilObjRepositorySettingsGUI extends ilObjectGUI +{ + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) + { + global $DIC; + + $this->error = $DIC["ilErr"]; + $this->access = $DIC->access(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->settings = $DIC->settings(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->toolbar = $DIC->toolbar(); + parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); + + $this->type = 'reps'; + $this->lng->loadLanguageModule('rep'); + $this->lng->loadLanguageModule('cmps'); + } + + public function executeCommand() + { + $ilErr = $this->error; + $ilAccess = $this->access; + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + $this->prepareOutput(); + + if (!$ilAccess->checkAccess('read', '', $this->object->getRefId())) { + $ilErr->raiseError($this->lng->txt('no_permission'), $ilErr->WARNING); + } + + switch ($next_class) { + case 'ilpermissiongui': + $this->tabs_gui->setTabActive('perm_settings'); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $this->ctrl->forwardCommand($perm_gui); + break; + + default: + $this->$cmd(); + break; + } + return true; + } + + public function getAdminTabs() + { + $rbacsystem = $this->rbacsystem; + + $this->tabs_gui->addTab( + "settings", + $this->lng->txt("settings"), + $this->ctrl->getLinkTarget($this, "view") + ); + + $this->tabs_gui->addTab( + "icons", + $this->lng->txt("rep_custom_icons"), + $this->ctrl->getLinkTarget($this, "customIcons") + ); + + $this->tabs_gui->addTab( + "modules", + $this->lng->txt("cmps_repository_object_types"), + $this->ctrl->getLinkTarget($this, "listModules") + ); + + if ($rbacsystem->checkAccess('edit_permission', $this->object->getRefId())) { + $this->tabs_gui->addTab( + "perm_settings", + $this->lng->txt("perm_settings"), + $this->ctrl->getLinkTargetByClass('ilpermissiongui', "perm") + ); + } + } + + public function view(ilPropertyFormGUI $a_form = null) + { + $this->tabs_gui->activateTab("settings"); + + if (!$a_form) { + $a_form = $this->initSettingsForm(); + } + + $this->tpl->setContent($a_form->getHTML()); + } + + protected function initSettingsForm() + { + $ilSetting = $this->settings; + $ilAccess = $this->access; + + include_once('Services/Form/classes/class.ilPropertyFormGUI.php'); + $form = new ilPropertyFormGUI(); + $form->setTitle($this->lng->txt("settings")); + $form->setFormAction($this->ctrl->getFormAction($this, 'saveSettings')); + + // default repository view + $options = array( + "flat" => $this->lng->txt("flatview"), + "tree" => $this->lng->txt("treeview") + ); + $si = new ilSelectInputGUI($this->lng->txt("def_repository_view"), "default_rep_view"); + $si->setOptions($options); + $si->setInfo($this->lng->txt("")); + if ($ilSetting->get("default_repository_view") == "tree") { + $si->setValue("tree"); + } else { + $si->setValue("flat"); + } + $form->addItem($si); + + // + $options = array( + "" => $this->lng->txt("adm_rep_tree_only_container"), + "tree" => $this->lng->txt("adm_all_resource_types") + ); + + // repository tree + $radg = new ilRadioGroupInputGUI($this->lng->txt("adm_rep_tree_presentation"), "tree_pres"); + $radg->setValue($ilSetting->get("repository_tree_pres")); + $op1 = new ilRadioOption( + $this->lng->txt("adm_rep_tree_only_cntr"), + "", + $this->lng->txt("adm_rep_tree_only_cntr_info") + ); + $radg->addOption($op1); + + $op2 = new ilRadioOption( + $this->lng->txt("adm_rep_tree_all_types"), + "all_types", + $this->lng->txt("adm_rep_tree_all_types_info") + ); + + // limit tree in courses and groups + $cb = new ilCheckboxInputGUI($this->lng->txt("adm_rep_tree_limit_grp_crs"), "rep_tree_limit_grp_crs"); + $cb->setChecked($ilSetting->get("rep_tree_limit_grp_crs")); + $cb->setInfo($this->lng->txt("adm_rep_tree_limit_grp_crs_info")); + $op2->addSubItem($cb); + + $radg->addOption($op2); + + $form->addItem($radg); + + // limit items in tree + $tree_limit = new ilCheckboxInputGUI($this->lng->txt("rep_tree_limit"), "rep_tree_limit"); + $tree_limit->setChecked($ilSetting->get("rep_tree_limit_number") > 0); + $tree_limit->setInfo($this->lng->txt("rep_tree_limit_info")); + $form->addItem($tree_limit); + + // limit items in tree (number) + $tree_limit_number = new ilNumberInputGUI($this->lng->txt("rep_tree_limit_number"), "rep_tree_limit_number"); + $tree_limit_number->setMaxLength(3); + $tree_limit_number->setSize(3); + $tree_limit_number->setValue($ilSetting->get("rep_tree_limit_number")); + $tree_limit_number->setInfo($this->lng->txt("rep_tree_limit_number_info")); + $tree_limit->addSubItem($tree_limit_number); + + // breadcrumbs start with courses + $cb = new ilCheckboxInputGUI($this->lng->txt("rep_breadcr_crs"), "rep_breadcr_crs"); + $cb->setChecked((int) $ilSetting->get("rep_breadcr_crs")); + $form->addItem($cb); + + $radg = new ilRadioGroupInputGUI($this->lng->txt("rep_breadcr_crs"), "rep_breadcr_crs_overwrite"); + $radg->setValue((int) $ilSetting->get("rep_breadcr_crs_overwrite")); + + $op0 = new ilRadioOption($this->lng->txt("rep_breadcr_crs_overwrite"), 1); + $cb0 = new ilCheckboxInputGUI($this->lng->txt("rep_default"), "rep_breadcr_crs_default"); + $cb0->setChecked((int) $ilSetting->get("rep_breadcr_crs_default")); + $op0->addSubItem($cb0); + $radg->addOption($op0); + + $op1 = new ilRadioOption($this->lng->txt("rep_breadcr_crs_overwrite_not"), 0); + $radg->addOption($op1); + + + $cb->addSubItem($radg); + + + + // trash + $cb = new ilCheckboxInputGUI($this->lng->txt("enable_trash"), "enable_trash"); + $cb->setInfo($this->lng->txt("enable_trash_info")); + if ($ilSetting->get("enable_trash")) { + $cb->setChecked(true); + } + $form->addItem($cb); + + // change event + require_once 'Services/Tracking/classes/class.ilChangeEvent.php'; + $this->lng->loadLanguageModule("trac"); + $event = new ilCheckboxInputGUI($this->lng->txt('trac_show_repository_views'), 'change_event_tracking'); + $event->setInfo($this->lng->txt("trac_show_repository_views_info")); + $event->setChecked(ilChangeEvent::_isActive()); + $form->addItem($event); + + + include_once "Services/Administration/classes/class.ilAdministrationSettingsFormHandler.php"; + ilAdministrationSettingsFormHandler::addFieldsToForm( + ilAdministrationSettingsFormHandler::FORM_REPOSITORY, + $form, + $this + ); + + + // object lists + + $lists = new ilFormSectionHeaderGUI(); + $lists->setTitle($this->lng->txt("rep_object_lists")); + $form->addItem($lists); + + $sdesc = new ilCheckboxInputGUI($this->lng->txt("adm_rep_shorten_description"), "rep_shorten_description"); + $sdesc->setInfo($this->lng->txt("adm_rep_shorten_description_info")); + $sdesc->setChecked($ilSetting->get("rep_shorten_description")); + $form->addItem($sdesc); + + $sdesclen = new ilNumberInputGUI($this->lng->txt("adm_rep_shorten_description_length"), "rep_shorten_description_length"); + $sdesclen->setValue($ilSetting->get("rep_shorten_description_length")); + $sdesclen->setSize(3); + $sdesc->addSubItem($sdesclen); + + // load action commands asynchronously + $cb = new ilCheckboxInputGUI($this->lng->txt("adm_item_cmd_asynch"), "item_cmd_asynch"); + $cb->setInfo($this->lng->txt("adm_item_cmd_asynch_info")); + $cb->setChecked($ilSetting->get("item_cmd_asynch")); + $form->addItem($cb); + + // notes/comments/tagging + $pl = new ilCheckboxInputGUI($this->lng->txt('adm_show_comments_tagging_in_lists'), 'comments_tagging_in_lists'); + $pl->setValue(1); + $pl->setChecked($ilSetting->get('comments_tagging_in_lists')); + $form->addItem($pl); + + $pltags = new ilCheckboxInputGUI($this->lng->txt('adm_show_comments_tagging_in_lists_tags'), 'comments_tagging_in_lists_tags'); + $pltags->setValue(1); + $pltags->setChecked($ilSetting->get('comments_tagging_in_lists_tags')); + $pl->addSubItem($pltags); + + if ($ilAccess->checkAccess('write', '', $this->object->getRefId())) { + $form->addCommandButton('saveSettings', $this->lng->txt('save')); + } + + return $form; + } + + public function saveSettings() + { + $ilSetting = $this->settings; + $ilAccess = $this->access; + + if (!$ilAccess->checkAccess('write', '', $this->object->getRefId())) { + $this->ctrl->redirect($this, "view"); + } + + $form = $this->initSettingsForm(); + if ($form->checkInput()) { + $ilSetting->set("default_repository_view", $_POST["default_rep_view"]); + + $ilSetting->set("repository_tree_pres", $_POST["tree_pres"]); + if ($_POST["tree_pres"] == "") { + $_POST["rep_tree_limit_grp_crs"] = ""; + } + if ($_POST["rep_tree_limit_grp_crs"] && !$ilSetting->get("rep_tree_limit_grp_crs")) { + $_POST["rep_tree_synchronize"] = true; + } elseif (!$_POST["rep_tree_synchronize"] && $ilSetting->get("rep_tree_synchronize")) { + $_POST["rep_tree_limit_grp_crs"] = false; + } + $ilSetting->set("rep_tree_limit_grp_crs", $_POST["rep_tree_limit_grp_crs"]); + + // $ilSetting->set('rep_cache',(int) $_POST['rep_cache']); + // $ilSetting->set("rep_tree_synchronize", $_POST["rep_tree_synchronize"]); + + $ilSetting->set("enable_trash", $_POST["enable_trash"]); + + + $ilSetting->set("rep_breadcr_crs_overwrite", (int) $_POST["rep_breadcr_crs_overwrite"]); + $ilSetting->set("rep_breadcr_crs", (int) $_POST["rep_breadcr_crs"]); + $ilSetting->set("rep_breadcr_crs_default", (int) $_POST["rep_breadcr_crs_default"]); + + + $ilSetting->set("rep_shorten_description", $form->getInput('rep_shorten_description')); + $ilSetting->set("rep_shorten_description_length", (int) $form->getInput('rep_shorten_description_length')); + $ilSetting->set('item_cmd_asynch', (int) $_POST['item_cmd_asynch']); + $ilSetting->set('comments_tagging_in_lists', (int) $_POST['comments_tagging_in_lists']); + $ilSetting->set('comments_tagging_in_lists_tags', (int) $_POST['comments_tagging_in_lists_tags']); + + // repository tree limit of children + $limit_number = ($_POST['rep_tree_limit'] && $_POST['rep_tree_limit_number'] > 0) + ? (int) $_POST['rep_tree_limit_number'] + : 0; + $ilSetting->set('rep_tree_limit_number', $limit_number); + + require_once 'Services/Tracking/classes/class.ilChangeEvent.php'; + if ($form->getInput('change_event_tracking')) { + ilChangeEvent::_activate(); + } else { + ilChangeEvent::_deactivate(); + } + + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "view"); + } + + $form->setValuesByPost(); + $this->view($form); + } + + public function customIcons(ilPropertyFormGUI $a_form = null) + { + $this->tabs_gui->activateTab("icons"); + + if (!$a_form) { + $a_form = $this->initCustomIconsForm(); + } + + $this->tpl->setContent($a_form->getHTML()); + } + + protected function initCustomIconsForm() + { + $ilSetting = $this->settings; + $ilAccess = $this->access; + + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + include_once "Services/Form/classes/class.ilCombinationInputGUI.php"; + $form = new ilPropertyFormGUI(); + $form->setTitle($this->lng->txt("rep_custom_icons")); + $form->setFormAction($this->ctrl->getFormAction($this, 'saveCustomIcons')); + + $cb = new ilCheckboxInputGUI($this->lng->txt("enable_custom_icons"), "custom_icons"); + $cb->setInfo($this->lng->txt("enable_custom_icons_info")); + $cb->setChecked($ilSetting->get("custom_icons")); + $form->addItem($cb); + + if ($ilAccess->checkAccess('write', '', $this->object->getRefId())) { + $form->addCommandButton('saveCustomIcons', $this->lng->txt('save')); + } + + return $form; + } + + public function saveCustomIcons() + { + $ilSetting = $this->settings; + $ilAccess = $this->access; + + if (!$ilAccess->checkAccess('write', '', $this->object->getRefId())) { + $this->ctrl->redirect($this, "customIcons"); + } + + $form = $this->initCustomIconsForm(); + if ($form->checkInput()) { + $ilSetting->set("custom_icons", (int) $form->getInput("custom_icons")); + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "customIcons"); + } + + $form->setValuesByPost(); + $this->customIcons($form); + } + + protected function setModuleSubTabs($a_active) + { + $this->tabs_gui->activateTab('modules'); + + $this->tabs_gui->addSubTab( + "list_mods", + $this->lng->txt("rep_new_item_menu"), + $this->ctrl->getLinkTarget($this, "listModules") + ); + + $this->tabs_gui->addSubTab( + "new_item_groups", + $this->lng->txt("rep_new_item_groups"), + $this->ctrl->getLinkTarget($this, "listNewItemGroups") + ); + + $this->tabs_gui->activateSubTab($a_active); + } + + protected function listModules() + { + $ilAccess = $this->access; + + $this->setModuleSubTabs("list_mods"); + + $has_write = $ilAccess->checkAccess('write', '', $this->object->getRefId()); + + include_once("./Services/Repository/classes/class.ilModulesTableGUI.php"); + $comp_table = new ilModulesTableGUI($this, "listModules", $has_write); + + $this->tpl->setContent($comp_table->getHTML()); + } + + protected function saveModules() + { + $ilSetting = $this->settings; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilAccess = $this->access; + + if (!is_array($_POST["obj_grp"]) || + !is_array($_POST["obj_pos"]) || + !$ilAccess->checkAccess('write', '', $this->object->getRefId())) { + $ilCtrl->redirect($this, "listModules"); + } + + $grp_pos_map = array(0 => 9999); + include_once("Services/Repository/classes/class.ilObjRepositorySettings.php"); + foreach (ilObjRepositorySettings::getNewItemGroups() as $item) { + $grp_pos_map[$item["id"]] = $item["pos"]; + } + + $type_pos_map = array(); + foreach ($_POST["obj_pos"] as $obj_type => $pos) { + $grp_id = (int) $_POST["obj_grp"][$obj_type]; + $type_pos_map[$grp_id][$obj_type] = $pos; + + // enable creation? + $ilSetting->set("obj_dis_creation_" . $obj_type, !(int) $_POST["obj_enbl_creation"][$obj_type]); + } + + foreach ($type_pos_map as $grp_id => $obj_types) { + $grp_pos = str_pad($grp_pos_map[$grp_id], 4, "0", STR_PAD_LEFT); + + asort($obj_types); + $pos = 0; + foreach (array_keys($obj_types) as $obj_type) { + $pos += 10; + $type_pos = $grp_pos . str_pad($pos, 4, "0", STR_PAD_LEFT); + $ilSetting->set("obj_add_new_pos_" . $obj_type, $type_pos); + $ilSetting->set("obj_add_new_pos_grp_" . $obj_type, $grp_id); + } + } + + /* + if (count($double) == 0) + { + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + } + else + { + ilUtil::sendInfo($lng->txt("cmps_duplicate_positions")." ".implode($double, ", "), true); + } + */ + + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "listModules"); + } + + protected function listNewItemGroups() + { + $ilToolbar = $this->toolbar; + $ilAccess = $this->access; + + $this->setModuleSubTabs("new_item_groups"); + + $has_write = $ilAccess->checkAccess('write', '', $this->object->getRefId()); + + if ($has_write) { + $ilToolbar->addButton( + $this->lng->txt("rep_new_item_group_add"), + $this->ctrl->getLinkTarget($this, "addNewItemGroup") + ); + + $ilToolbar->addButton( + $this->lng->txt("rep_new_item_group_add_separator"), + $this->ctrl->getLinkTarget($this, "addNewItemGroupSeparator") + ); + } + + include_once("./Services/Repository/classes/class.ilNewItemGroupTableGUI.php"); + $grp_table = new ilNewItemGroupTableGUI($this, "listNewItemGroups", $has_write); + + $this->tpl->setContent($grp_table->getHTML()); + } + + protected function initNewItemGroupForm($a_grp_id = false) + { + $this->setModuleSubTabs("new_item_groups"); + + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $form = new ilPropertyFormGUI(); + + $this->lng->loadLanguageModule("meta"); + $def_lng = $this->lng->getDefaultLanguage(); + + $title = new ilTextInputGUI($this->lng->txt("title"), "title_" . $def_lng); + $title->setInfo($this->lng->txt("meta_l_" . $def_lng) . + " (" . $this->lng->txt("default_language") . ")"); + $title->setRequired(true); + $form->addItem($title); + + foreach ($this->lng->getInstalledLanguages() as $lang_id) { + if ($lang_id != $def_lng) { + $title = new ilTextInputGUI($this->lng->txt("translation"), "title_" . $lang_id); + $title->setInfo($this->lng->txt("meta_l_" . $lang_id)); + $form->addItem($title); + } + } + + if (!$a_grp_id) { + $form->setTitle($this->lng->txt("rep_new_item_group_add")); + $form->setFormAction($this->ctrl->getFormAction($this, "saveNewItemGroup")); + + $form->addCommandButton("saveNewItemGroup", $this->lng->txt("save")); + } else { + $form->setTitle($this->lng->txt("rep_new_item_group_edit")); + $form->setFormAction($this->ctrl->getFormAction($this, "updateNewItemGroup")); + + include_once("Services/Repository/classes/class.ilObjRepositorySettings.php"); + $grp = ilObjRepositorySettings::getNewItemGroups(); + $grp = $grp[$a_grp_id]; + + foreach ($grp["titles"] as $id => $value) { + $field = $form->getItemByPostVar("title_" . $id); + if ($field) { + $field->setValue($value); + } + } + + $form->addCommandButton("updateNewItemGroup", $this->lng->txt("save")); + } + $form->addCommandButton("listNewItemGroups", $this->lng->txt("cancel")); + + return $form; + } + + protected function addNewItemGroup(ilPropertyFormGUI $a_form = null) + { + if (!$a_form) { + $a_form = $this->initNewItemGroupForm(); + } + + $this->tpl->setContent($a_form->getHTML()); + } + + protected function saveNewItemGroup() + { + $form = $this->initNewItemGroupForm(); + if ($form->checkInput()) { + $titles = array(); + foreach ($this->lng->getInstalledLanguages() as $lang_id) { + $titles[$lang_id] = $form->getInput("title_" . $lang_id); + } + + include_once("Services/Repository/classes/class.ilObjRepositorySettings.php"); + if (ilObjRepositorySettings::addNewItemGroup($titles)) { + ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); + $this->ctrl->redirect($this, "listNewItemGroups"); + } + } + + $form->setValuesByPost(); + $this->addNewItemGroup($form); + } + + protected function editNewItemGroup(ilPropertyFormGUI $a_form = null) + { + $grp_id = (int) $_GET["grp_id"]; + if (!$grp_id) { + $this->ctrl->redirect($this, "listNewItemGroups"); + } + + if (!$a_form) { + $this->ctrl->setParameter($this, "grp_id", $grp_id); + $a_form = $this->initNewItemGroupForm($grp_id); + } + + $this->tpl->setContent($a_form->getHTML()); + } + + protected function updateNewItemGroup() + { + $grp_id = (int) $_GET["grp_id"]; + if (!$grp_id) { + $this->ctrl->redirect($this, "listNewItemGroups"); + } + + $this->ctrl->setParameter($this, "grp_id", $grp_id); + + $form = $this->initNewItemGroupForm($grp_id); + if ($form->checkInput()) { + $titles = array(); + foreach ($this->lng->getInstalledLanguages() as $lang_id) { + $titles[$lang_id] = $form->getInput("title_" . $lang_id); + } + + include_once("Services/Repository/classes/class.ilObjRepositorySettings.php"); + if (ilObjRepositorySettings::updateNewItemGroup($grp_id, $titles)) { + ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); + $this->ctrl->redirect($this, "listNewItemGroups"); + } + } + + $form->setValuesByPost(); + $this->addNewItemGroup($form); + } + + protected function addNewItemGroupSeparator() + { + include_once("Services/Repository/classes/class.ilObjRepositorySettings.php"); + if (ilObjRepositorySettings::addNewItemGroupSeparator()) { + ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); + } + $this->ctrl->redirect($this, "listNewItemGroups"); + } + + protected function saveNewItemGroupOrder() + { + $ilSetting = $this->settings; + + if (is_array($_POST["grp_order"])) { + include_once("Services/Repository/classes/class.ilObjRepositorySettings.php"); + ilObjRepositorySettings::updateNewItemGroupOrder($_POST["grp_order"]); + + $grp_pos_map = array(); + include_once("Services/Repository/classes/class.ilObjRepositorySettings.php"); + foreach (ilObjRepositorySettings::getNewItemGroups() as $item) { + $grp_pos_map[$item["id"]] = str_pad($item["pos"], 4, "0", STR_PAD_LEFT); + } + + // update order of assigned objects + foreach (ilObjRepositorySettings::getNewItemGroupSubItems() as $grp_id => $subitems) { + // unassigned objects will always be last + if ($grp_id) { + foreach ($subitems as $obj_type) { + $old_pos = $ilSetting->get("obj_add_new_pos_" . $obj_type); + if (strlen($old_pos) == 8) { + $new_pos = $grp_pos_map[$grp_id] . substr($old_pos, 4); + $ilSetting->set("obj_add_new_pos_" . $obj_type, $new_pos); + } + } + } + } + + ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); + } + $this->ctrl->redirect($this, "listNewItemGroups"); + } + + protected function confirmDeleteNewItemGroup() + { + if (!is_array($_POST["grp_id"])) { + ilUtil::sendFailure($this->lng->txt("select_one")); + return $this->listNewItemGroups(); + } + + $this->setModuleSubTabs("new_item_groups"); + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setHeaderText($this->lng->txt("rep_new_item_group_delete_sure")); + + $cgui->setFormAction($this->ctrl->getFormAction($this)); + $cgui->setCancel($this->lng->txt("cancel"), "listNewItemGroups"); + $cgui->setConfirm($this->lng->txt("confirm"), "deleteNewItemGroup"); + + include_once("Services/Repository/classes/class.ilObjRepositorySettings.php"); + $groups = ilObjRepositorySettings::getNewItemGroups(); + + foreach ($_POST["grp_id"] as $grp_id) { + $cgui->addItem("grp_id[]", $grp_id, $groups[$grp_id]["title"]); + } + + $this->tpl->setContent($cgui->getHTML()); + } + + protected function deleteNewItemGroup() + { + if (!is_array($_POST["grp_id"])) { + return $this->listNewItemGroups(); + } + + include_once("Services/Repository/classes/class.ilObjRepositorySettings.php"); + foreach ($_POST["grp_id"] as $grp_id) { + ilObjRepositorySettings::deleteNewItemGroup($grp_id); + } + + ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); + $this->ctrl->redirect($this, "listNewItemGroups"); + } + + public function addToExternalSettingsForm($a_form_id) + { + $ilSetting = $this->settings; + + switch ($a_form_id) { + case ilAdministrationSettingsFormHandler::FORM_LP: + + require_once 'Services/Tracking/classes/class.ilChangeEvent.php'; + $fields = array('trac_show_repository_views' => array(ilChangeEvent::_isActive(), ilAdministrationSettingsFormHandler::VALUE_BOOL)); + + return array(array("view", $fields)); + + + case ilAdministrationSettingsFormHandler::FORM_TAGGING: + + $fields = array( + 'adm_show_comments_tagging_in_lists' => array($ilSetting->get('comments_tagging_in_lists'), ilAdministrationSettingsFormHandler::VALUE_BOOL, + array('adm_show_comments_tagging_in_lists_tags' => array($ilSetting->get('comments_tagging_in_lists_tags'), ilAdministrationSettingsFormHandler::VALUE_BOOL)) + )); + + return array(array("view", $fields)); + } + } +} diff --git a/Services/Repository/classes/class.ilObjectPlugin.php b/Services/Repository/classes/class.ilObjectPlugin.php index b24d0b9c29c4eab1f30b1eb8513dfc952784c1ca..557ceb91df9574194068f6a063cc5e690c65c653 100644 --- a/Services/Repository/classes/class.ilObjectPlugin.php +++ b/Services/Repository/classes/class.ilObjectPlugin.php @@ -13,124 +13,131 @@ require_once('./Services/Component/classes/class.ilPlugin.php'); */ abstract class ilObjectPlugin extends ilObject2 { - private $object; - - protected $plugin; - - /** - * @var - */ - protected static $plugin_by_type = array(); - - - /** - * Constructor. - */ - function __construct($a_ref_id = 0) - { - $this->initType(); - parent::__construct($a_ref_id, true); - $this->plugin = $this->getPlugin(); - } - - - /** - * Return either a repoObject plugin or a orgunit extension plugin or null if the type is not a plugin. - * - * @param $type - * @return null | ilRepositoryObjectPlugin | ilOrgUnitExtensionPlugin - */ - public static function getPluginObjectByType($type) { - if (!self::$plugin_by_type[$type]) { - list($component, $component_name) = ilPlugin::lookupTypeInformationsForId($type); - if( - $component == IL_COMP_SERVICE && - $component_name == "Repository" - ) { - self::loadRepoPlugin($type); - } - - if( - $component == IL_COMP_MODULE && - $component_name == "OrgUnit" - ) { - self::loadOrgUnitPlugin($type); - } - } - - return self::$plugin_by_type[$type]; - } - - protected static function loadRepoPlugin(string $type_id) - { - $plugin = null; - $name = ilPlugin::lookupNameForId(IL_COMP_SERVICE, "Repository", "robj", $type_id); - - if(! is_null($name)) { - $plugin = ilPlugin::getPluginObject(IL_COMP_SERVICE, "Repository", "robj", $name); - } - - if (is_null($plugin)) { - ilLoggerFactory::getLogger("obj")->log("Try to get repo plugin obj by type: $type_id. No such type exists for Repository and Org Unit pluginss."); - } - self::$plugin_by_type[$type_id] = $plugin; - } - - protected static function loadOrgUnitPlugin(string $type_id) - { - $plugin = null; - $name = ilPlugin::lookupNameForId(IL_COMP_MODULE, "OrgUnit", "orguext", $type_id); - if(! is_null($name)) { - $plugin = ilPlugin::getPluginObject(IL_COMP_MODULE, "OrgUnit", "orguext", $name); - } - - if (is_null($plugin)) { - ilLoggerFactory::getLogger("obj")->log("Try to get repo plugin obj by type: $type_id. No such type exists for Repository and Org Unit pluginss."); - } - self::$plugin_by_type[$type_id] = $plugin; - } - - /** - * @param $plugin_id - * @param $lang_var - * @return string - */ - static function lookupTxtById($plugin_id, $lang_var) { - $pl = self::getPluginObjectByType($plugin_id); - return $pl->txt($lang_var); - } - - /** - * Get plugin object - * @return object plugin object - * @throws ilPluginException - */ - protected function getPlugin() - { - if(!$this->plugin) { - $this->plugin = - ilPlugin::getPluginObject(IL_COMP_SERVICE, "Repository", "robj", - ilPlugin::lookupNameForId(IL_COMP_SERVICE, "Repository", "robj", $this->getType())); - if (!is_object($this->plugin)) { - throw new ilPluginException("ilObjectPlugin: Could not instantiate plugin object for type " . $this->getType() . "."); - } - } - return $this->plugin; - } - - /** - * Wrapper for txt function - */ - final protected function txt($a_var) - { - return $this->getPlugin()->txt($a_var); - } - - /** - * returns a list of all repository object types which can be a parent of this type. - * @return string[] - */ - public function getParentTypes() { - return $this->plugin->getParentTypes(); - } + private $object; + + protected $plugin; + + /** + * @var + */ + protected static $plugin_by_type = array(); + + + /** + * Constructor. + */ + public function __construct($a_ref_id = 0) + { + $this->initType(); + parent::__construct($a_ref_id, true); + $this->plugin = $this->getPlugin(); + } + + + /** + * Return either a repoObject plugin or a orgunit extension plugin or null if the type is not a plugin. + * + * @param $type + * @return null | ilRepositoryObjectPlugin | ilOrgUnitExtensionPlugin + */ + public static function getPluginObjectByType($type) + { + if (!self::$plugin_by_type[$type]) { + list($component, $component_name) = ilPlugin::lookupTypeInformationsForId($type); + if ( + $component == IL_COMP_SERVICE && + $component_name == "Repository" + ) { + self::loadRepoPlugin($type); + } + + if ( + $component == IL_COMP_MODULE && + $component_name == "OrgUnit" + ) { + self::loadOrgUnitPlugin($type); + } + } + + return self::$plugin_by_type[$type]; + } + + protected static function loadRepoPlugin(string $type_id) + { + $plugin = null; + $name = ilPlugin::lookupNameForId(IL_COMP_SERVICE, "Repository", "robj", $type_id); + + if (!is_null($name)) { + $plugin = ilPlugin::getPluginObject(IL_COMP_SERVICE, "Repository", "robj", $name); + } + + if (is_null($plugin)) { + ilLoggerFactory::getLogger("obj")->log("Try to get repo plugin obj by type: $type_id. No such type exists for Repository and Org Unit pluginss."); + } + self::$plugin_by_type[$type_id] = $plugin; + } + + protected static function loadOrgUnitPlugin(string $type_id) + { + $plugin = null; + $name = ilPlugin::lookupNameForId(IL_COMP_MODULE, "OrgUnit", "orguext", $type_id); + if (!is_null($name)) { + $plugin = ilPlugin::getPluginObject(IL_COMP_MODULE, "OrgUnit", "orguext", $name); + } + + if (is_null($plugin)) { + ilLoggerFactory::getLogger("obj")->log("Try to get repo plugin obj by type: $type_id. No such type exists for Repository and Org Unit pluginss."); + } + self::$plugin_by_type[$type_id] = $plugin; + } + + /** + * @param $plugin_id + * @param $lang_var + * @return string + */ + public static function lookupTxtById($plugin_id, $lang_var) + { + $pl = self::getPluginObjectByType($plugin_id); + return $pl->txt($lang_var); + } + + /** + * Get plugin object + * @return object plugin object + * @throws ilPluginException + */ + protected function getPlugin() + { + if (!$this->plugin) { + $this->plugin = + ilPlugin::getPluginObject( + IL_COMP_SERVICE, + "Repository", + "robj", + ilPlugin::lookupNameForId(IL_COMP_SERVICE, "Repository", "robj", $this->getType()) + ); + if (!is_object($this->plugin)) { + throw new ilPluginException("ilObjectPlugin: Could not instantiate plugin object for type " . $this->getType() . "."); + } + } + return $this->plugin; + } + + /** + * Wrapper for txt function + */ + final protected function txt($a_var) + { + return $this->getPlugin()->txt($a_var); + } + + /** + * returns a list of all repository object types which can be a parent of this type. + * @return string[] + */ + public function getParentTypes() + { + return $this->plugin->getParentTypes(); + } } diff --git a/Services/Repository/classes/class.ilObjectPluginAccess.php b/Services/Repository/classes/class.ilObjectPluginAccess.php index 04f66bb15ab23f9f897d3e727abac858d7dc8527..83c08e1e05415594681bf575b16b06be56f25c11 100755 --- a/Services/Repository/classes/class.ilObjectPluginAccess.php +++ b/Services/Repository/classes/class.ilObjectPluginAccess.php @@ -1,24 +1,24 @@ user = $DIC->user(); - $this->access = $DIC->access(); - } - - /** - * Checks wether a user may invoke a command or not - * (this method is called by ilAccessHandler::checkAccess) - * - * Please do not check any preconditions handled by - * ilConditionHandler here. Also don't do any RBAC checks. - * - * @param string $a_cmd command (not permission!) - * @param string $a_permission permission - * @param int $a_ref_id reference id - * @param int $a_obj_id object id - * @param int $a_user_id user id (if not provided, current user is taken) - * - * @return boolean true, if everything is ok - */ - function _checkAccess($a_cmd, $a_permission, $a_ref_id, $a_obj_id, $a_user_id = "") - { - $ilUser = $this->user; - $ilAccess = $this->access; - - if ($a_user_id == "") - { - $a_user_id = $ilUser->getId(); - } - - // add no access info item and return false if access is not granted - // $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $a_text, $a_data = ""); - // - // for all RBAC checks use checkAccessOfUser instead the normal checkAccess-method: - // $ilAccess->checkAccessOfUser($a_user_id, $a_permission, $a_cmd, $a_ref_id) - - return true; - } - - /** - * check condition - * - * this method is called by ilConditionHandler - */ - function _checkCondition($a_obj_id, $a_operator, $a_value, $a_usr_id = 0) - { - return true; - } - - /** - * check whether goto script will succeed - */ - static function _checkGoto($a_target) - { - global $DIC; - - $ilAccess = $DIC->access(); - - $t_arr = explode("_", $a_target); - - if ($ilAccess->checkAccess("read", "", $t_arr[1])) - { - return true; - } - return false; - } - - // this is called by permission -> check permissions of user screen - static function _getCommands() - { - return array(); - } + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilAccessHandler + */ + protected $access; + + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->user = $DIC->user(); + $this->access = $DIC->access(); + } + + /** + * Checks wether a user may invoke a command or not + * (this method is called by ilAccessHandler::checkAccess) + * + * Please do not check any preconditions handled by + * ilConditionHandler here. Also don't do any RBAC checks. + * + * @param string $a_cmd command (not permission!) + * @param string $a_permission permission + * @param int $a_ref_id reference id + * @param int $a_obj_id object id + * @param int $a_user_id user id (if not provided, current user is taken) + * + * @return boolean true, if everything is ok + */ + public function _checkAccess($a_cmd, $a_permission, $a_ref_id, $a_obj_id, $a_user_id = "") + { + $ilUser = $this->user; + $ilAccess = $this->access; + + if ($a_user_id == "") { + $a_user_id = $ilUser->getId(); + } + + // add no access info item and return false if access is not granted + // $ilAccess->addInfoItem(IL_NO_OBJECT_ACCESS, $a_text, $a_data = ""); + // + // for all RBAC checks use checkAccessOfUser instead the normal checkAccess-method: + // $ilAccess->checkAccessOfUser($a_user_id, $a_permission, $a_cmd, $a_ref_id) + + return true; + } + + /** + * check condition + * + * this method is called by ilConditionHandler + */ + public function _checkCondition($a_obj_id, $a_operator, $a_value, $a_usr_id = 0) + { + return true; + } + + /** + * check whether goto script will succeed + */ + public static function _checkGoto($a_target) + { + global $DIC; + + $ilAccess = $DIC->access(); + + $t_arr = explode("_", $a_target); + + if ($ilAccess->checkAccess("read", "", $t_arr[1])) { + return true; + } + return false; + } + + // this is called by permission -> check permissions of user screen + public static function _getCommands() + { + return array(); + } } - -?> diff --git a/Services/Repository/classes/class.ilObjectPluginGUI.php b/Services/Repository/classes/class.ilObjectPluginGUI.php index 674c2d942bba83741db21d589929183c5c058d24..9efe4f9dc2bb82174471f41f3ebc139a65c4c71c 100644 --- a/Services/Repository/classes/class.ilObjectPluginGUI.php +++ b/Services/Repository/classes/class.ilObjectPluginGUI.php @@ -13,531 +13,530 @@ include_once("./Services/Component/classes/class.ilPlugin.php"); */ abstract class ilObjectPluginGUI extends ilObject2GUI { - /** - * @var ilNavigationHistory - */ - protected $nav_history; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilPluginAdmin - */ - protected $plugin_admin; - - - protected $plugin; - /** - * Constructor. - */ - function __construct($a_ref_id = 0, $a_id_type = self::REPOSITORY_NODE_ID, $a_parent_node_id = 0) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->tpl = $DIC["tpl"]; - $this->access = $DIC->access(); - $this->lng = $DIC->language(); - $this->nav_history = $DIC["ilNavigationHistory"]; - $this->tabs = $DIC->tabs(); - $this->locator = $DIC["ilLocator"]; - $this->plugin_admin = $DIC["ilPluginAdmin"]; - $this->user = $DIC->user(); - parent::__construct($a_ref_id, $a_id_type, $a_parent_node_id); - $this->plugin = $this->getPlugin(); - } - - /** - * execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $ilAccess = $this->access; - $lng = $this->lng; - $ilNavigationHistory = $this->nav_history; - $ilTabs = $this->tabs; - - // get standard template (includes main menu and general layout) - $tpl->getStandardTemplate(); - - // set title - if (!$this->getCreationMode()) - { - $tpl->setTitle($this->object->getTitle()); - $tpl->setTitleIcon(ilObject::_getIcon($this->object->getId())); - - // set tabs - if (strtolower($_GET["baseClass"]) != "iladministrationgui") - { - $this->setTabs(); - $this->setLocator(); - } - else - { - $this->addAdminLocatorItems(); - $tpl->setLocator(); - $this->setAdminTabs(); - } - - // add entry to navigation history - if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - $ilNavigationHistory->addItem($_GET["ref_id"], - $ilCtrl->getLinkTarget($this, $this->getStandardCmd()), $this->getType()); - } - - } - else - { - // show info of parent - $tpl->setTitle($this->lookupParentTitleInCreationMode()); - $tpl->setTitleIcon( - ilObject::_getIcon(ilObject::_lookupObjId($_GET["ref_id"]), "big"), - $lng->txt("obj_".ilObject::_lookupType($_GET["ref_id"], true))); - $this->setLocator(); - - } - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - switch($next_class) - { - case "ilinfoscreengui": - $this->checkPermission("visible"); - $this->infoScreen(); // forwards command - break; - - case 'ilpermissiongui': - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $ilTabs->setTabActive("perm_settings"); - $ilCtrl->forwardCommand($perm_gui); - break; - - case 'ilobjectcopygui': - include_once './Services/Object/classes/class.ilObjectCopyGUI.php'; - $cp = new ilObjectCopyGUI($this); - $cp->setType($this->getType()); - $this->ctrl->forwardCommand($cp); - break; - - case 'ilexportgui': - // only if plugin supports it? - $this->tabs->setTabActive("export"); - include_once './Services/Export/classes/class.ilExportGUI.php'; - $exp = new ilExportGUI($this); - $exp->addFormat('xml'); - $this->ctrl->forwardCommand($exp); - break; - - case 'illearningprogressgui': - $ilTabs->setTabActive("learning_progress"); - include_once './Services/Tracking/classes/class.ilLearningProgressGUI.php'; - $new_gui = new ilLearningProgressGUI(ilLearningProgressGUI::LP_CONTEXT_REPOSITORY, - $this->object->getRefId(), - $_GET['user_id'] ? $_GET['user_id'] : $GLOBALS['ilUser']->getId()); - $this->ctrl->forwardCommand($new_gui); - break; - case 'ilcommonactiondispatchergui': - include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); - $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); - $this->ctrl->forwardCommand($gui); - break; - default: - if ($this->getCreationMode() || $cmd == "save") - { - $this->$cmd(); - return; - } + /** + * @var ilNavigationHistory + */ + protected $nav_history; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilPluginAdmin + */ + protected $plugin_admin; + + + protected $plugin; + /** + * Constructor. + */ + public function __construct($a_ref_id = 0, $a_id_type = self::REPOSITORY_NODE_ID, $a_parent_node_id = 0) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->tpl = $DIC["tpl"]; + $this->access = $DIC->access(); + $this->lng = $DIC->language(); + $this->nav_history = $DIC["ilNavigationHistory"]; + $this->tabs = $DIC->tabs(); + $this->locator = $DIC["ilLocator"]; + $this->plugin_admin = $DIC["ilPluginAdmin"]; + $this->user = $DIC->user(); + parent::__construct($a_ref_id, $a_id_type, $a_parent_node_id); + $this->plugin = $this->getPlugin(); + } + + /** + * execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $ilAccess = $this->access; + $lng = $this->lng; + $ilNavigationHistory = $this->nav_history; + $ilTabs = $this->tabs; + + // get standard template (includes main menu and general layout) + $tpl->getStandardTemplate(); + + // set title + if (!$this->getCreationMode()) { + $tpl->setTitle($this->object->getTitle()); + $tpl->setTitleIcon(ilObject::_getIcon($this->object->getId())); + + // set tabs + if (strtolower($_GET["baseClass"]) != "iladministrationgui") { + $this->setTabs(); + $this->setLocator(); + } else { + $this->addAdminLocatorItems(); + $tpl->setLocator(); + $this->setAdminTabs(); + } + + // add entry to navigation history + if ($ilAccess->checkAccess("read", "", $_GET["ref_id"])) { + $ilNavigationHistory->addItem( + $_GET["ref_id"], + $ilCtrl->getLinkTarget($this, $this->getStandardCmd()), + $this->getType() + ); + } + } else { + // show info of parent + $tpl->setTitle($this->lookupParentTitleInCreationMode()); + $tpl->setTitleIcon( + ilObject::_getIcon(ilObject::_lookupObjId($_GET["ref_id"]), "big"), + $lng->txt("obj_" . ilObject::_lookupType($_GET["ref_id"], true)) + ); + $this->setLocator(); + } + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + switch ($next_class) { + case "ilinfoscreengui": + $this->checkPermission("visible"); + $this->infoScreen(); // forwards command + break; + + case 'ilpermissiongui': + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $ilTabs->setTabActive("perm_settings"); + $ilCtrl->forwardCommand($perm_gui); + break; + + case 'ilobjectcopygui': + include_once './Services/Object/classes/class.ilObjectCopyGUI.php'; + $cp = new ilObjectCopyGUI($this); + $cp->setType($this->getType()); + $this->ctrl->forwardCommand($cp); + break; + + case 'ilexportgui': + // only if plugin supports it? + $this->tabs->setTabActive("export"); + include_once './Services/Export/classes/class.ilExportGUI.php'; + $exp = new ilExportGUI($this); + $exp->addFormat('xml'); + $this->ctrl->forwardCommand($exp); + break; + + case 'illearningprogressgui': + $ilTabs->setTabActive("learning_progress"); + include_once './Services/Tracking/classes/class.ilLearningProgressGUI.php'; + $new_gui = new ilLearningProgressGUI( + ilLearningProgressGUI::LP_CONTEXT_REPOSITORY, + $this->object->getRefId(), + $_GET['user_id'] ? $_GET['user_id'] : $GLOBALS['ilUser']->getId() + ); + $this->ctrl->forwardCommand($new_gui); + break; + case 'ilcommonactiondispatchergui': + include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); + $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); + $this->ctrl->forwardCommand($gui); + break; + default: + if ($this->getCreationMode() || $cmd == "save") { + $this->$cmd(); + return; + } // if (strtolower($_GET["baseClass"]) == "iladministrationgui") // { // $this->viewObject(); // return; // } - if(!$cmd) - { - $cmd = $this->getStandardCmd(); - } - if ($cmd == "infoScreen") - { - $ilCtrl->setCmd("showSummary"); - $ilCtrl->setCmdClass("ilinfoscreengui"); - $this->infoScreen(); - } - else - { - $this->performCommand($cmd); - } - break; - } - - if (!$this->getCreationMode()) - { - $tpl->show(); - } - } - - /** - * Add object to locator - */ - function addLocatorItems() - { - $ilLocator = $this->locator; - - if (!$this->getCreationMode()) - { - $ilLocator->addItem($this->object->getTitle(), - $this->ctrl->getLinkTarget($this, $this->getStandardCmd()), "", $_GET["ref_id"]); - } - } - - /** - * Get plugin object - * @return object plugin object - * @throws ilPluginException - */ - protected function getPlugin() - { - if(!$this->plugin) { - $this->plugin = - ilPlugin::getPluginObject(IL_COMP_SERVICE, "Repository", "robj", - ilPlugin::lookupNameForId(IL_COMP_SERVICE, "Repository", "robj", $this->getType())); - if (!is_object($this->plugin)) { - throw new ilPluginException("ilObjectPluginGUI: Could not instantiate plugin object for type " . $this->getType() . "."); - } - } - return $this->plugin; - } - - /** - * Wrapper for txt function - */ - final protected function txt($a_var) - { - return $this->getPlugin()->txt($a_var); - } - - /** - * Use custom creation form titles - * - * @param string $a_form_type - * @return string - */ - protected function getCreationFormTitle($a_form_type) - { - switch($a_form_type) - { - case self::CFORM_NEW: - return $this->txt($this->getType()."_new"); - - case self::CFORM_IMPORT: - return $this->lng->txt("import"); - - case self::CFORM_CLONE: - return $this->txt("objs_".$this->getType()."_duplicate"); - } - } - - /** - * Init creation froms - * - * this will create the default creation forms: new, import, clone - * - * @param string $a_new_type - * @return array - */ - protected function initCreationForms($a_new_type) - { - $ilPluginAdmin = $this->plugin_admin; - - $forms = array(); - $forms[self::CFORM_NEW] = $this->initCreateForm($a_new_type); - - if($this->supportsExport()) - { - $forms[self::CFORM_IMPORT] = $this->initImportForm($a_new_type); - } - if($this->supportsCloning()) { - $forms[self::CFORM_CLONE] = $this->fillCloneTemplate(null, $a_new_type); - } - - return $forms; - } - - /** - * @return bool returns true iff this plugin object supports cloning - */ - protected function supportsCloning() { - return true; - } - - /** - * Init object creation form - * - * @param string $a_new_type - * @return ilPropertyFormGUI - */ - public function initCreateForm($a_new_type) - { - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setTarget("_top"); - $form->setFormAction($this->ctrl->getFormAction($this, "save")); - $form->setTitle($this->txt($a_new_type."_new")); - - // title - $ti = new ilTextInputGUI($this->lng->txt("title"), "title"); - $ti->setSize(min(40, ilObject::TITLE_LENGTH)); - $ti->setMaxLength(ilObject::TITLE_LENGTH); - $ti->setRequired(true); - $form->addItem($ti); - - // description - $ta = new ilTextAreaInputGUI($this->lng->txt("description"), "desc"); - $ta->setCols(40); - $ta->setRows(2); - $form->addItem($ta); - - $form->addCommandButton("save", $this->txt($a_new_type."_add")); - $form->addCommandButton("cancel", $this->lng->txt("cancel")); - - return $form; - } - - /** - * Init object update form - * - * @return ilPropertyFormGUI - */ - public function initEditForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setTarget("_top"); - $form->setFormAction($ilCtrl->getFormAction($this, "update")); - $form->setTitle($lng->txt("edit")); - - // title - $ti = new ilTextInputGUI($lng->txt("title"), "title"); - $ti->setSize(min(40, ilObject::TITLE_LENGTH)); - $ti->setMaxLength(ilObject::TITLE_LENGTH); - $ti->setRequired(true); - $form->addItem($ti); - - // description - $ta = new ilTextAreaInputGUI($lng->txt("description"), "desc"); - $ta->setCols(40); - $ta->setRows(2); - $form->addItem($ta); - - $form->addCommandButton("update", $lng->txt("save")); - // $this->form->addCommandButton("cancelUpdate", $lng->txt("cancel")); - - return $form; - } - - /** - * Init object import form - * - * @param string new type - * @return ilPropertyFormGUI - */ - protected function initImportForm($a_new_type) - { - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setTarget("_top"); - $form->setFormAction($this->ctrl->getFormAction($this, "importFile")); - $form->setTitle($this->lng->txt("import")); - - include_once("./Services/Form/classes/class.ilFileInputGUI.php"); - $fi = new ilFileInputGUI($this->lng->txt("import_file"), "importfile"); - $fi->setSuffixes(array("zip")); - $fi->setRequired(true); - $form->addItem($fi); - - $form->addCommandButton("importFile", $this->lng->txt("import")); - $form->addCommandButton("cancel", $this->lng->txt("cancel")); - - return $form; - } - - /** - * After saving - * @access public - */ - function afterSave(ilObject $newObj) - { - $ilCtrl = $this->ctrl; - // always send a message - ilUtil::sendSuccess($this->lng->txt("object_added"),true); - - $ilCtrl->initBaseClass("ilObjPluginDispatchGUI"); - $ilCtrl->getCallStructure(strtolower("ilObjPluginDispatchGUI")); - - $ilCtrl->setParameterByClass(get_class($this), "ref_id", $newObj->getRefId()); - $ilCtrl->redirectByClass(array("ilobjplugindispatchgui", get_class($this)), $this->getAfterCreationCmd()); - } - - /** - * Cmd that will be redirected to after creation of a new object. - */ - abstract function getAfterCreationCmd(); - - abstract function getStandardCmd(); - -// abstract function performCommand(); - - /** - * Add info screen tab - */ - function addInfoTab() - { - $ilAccess = $this->access; - $ilTabs = $this->tabs; - - // info screen - if ($ilAccess->checkAccess('visible', "", $this->object->getRefId())) - { - $ilTabs->addTarget("info_short", - $this->ctrl->getLinkTargetByClass( - "ilinfoscreengui", "showSummary"), - "showSummary"); - } - } - - /** - * Add permission tab - */ - function addPermissionTab() - { - $ilAccess = $this->access; - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - - // edit permissions - if($ilAccess->checkAccess('edit_permission', "", $this->object->getRefId())) - { - $ilTabs->addTarget("perm_settings", - $ilCtrl->getLinkTargetByClass("ilpermissiongui", "perm"), - array("perm","info","owner"), 'ilpermissiongui'); - } - } - - - /** - * Add export tab - */ - function addExportTab() - { - // write - if($this->access->checkAccess('write', "", $this->object->getRefId())) - { - $this->tabs->addTarget( - 'export', - $this->ctrl->getLinkTargetByClass("ilexportgui",''), - 'export', - 'ilexportgui' - ); - } - } - - /** - * show information screen - */ - function infoScreen() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - $ilTabs->activateTab("info_short"); - - $this->checkPermission("visible"); - - include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); - $info = new ilInfoScreenGUI($this); - $info->enablePrivateNotes(); - - // general information - $lng->loadLanguageModule("meta"); - - $this->addInfoItems($info); - - // forward the command - $ilCtrl->forwardCommand($info); - } + if (!$cmd) { + $cmd = $this->getStandardCmd(); + } + if ($cmd == "infoScreen") { + $ilCtrl->setCmd("showSummary"); + $ilCtrl->setCmdClass("ilinfoscreengui"); + $this->infoScreen(); + } else { + $this->performCommand($cmd); + } + break; + } + + if (!$this->getCreationMode()) { + $tpl->show(); + } + } + + /** + * Add object to locator + */ + public function addLocatorItems() + { + $ilLocator = $this->locator; + + if (!$this->getCreationMode()) { + $ilLocator->addItem( + $this->object->getTitle(), + $this->ctrl->getLinkTarget($this, $this->getStandardCmd()), + "", + $_GET["ref_id"] + ); + } + } + + /** + * Get plugin object + * @return object plugin object + * @throws ilPluginException + */ + protected function getPlugin() + { + if (!$this->plugin) { + $this->plugin = + ilPlugin::getPluginObject( + IL_COMP_SERVICE, + "Repository", + "robj", + ilPlugin::lookupNameForId(IL_COMP_SERVICE, "Repository", "robj", $this->getType()) + ); + if (!is_object($this->plugin)) { + throw new ilPluginException("ilObjectPluginGUI: Could not instantiate plugin object for type " . $this->getType() . "."); + } + } + return $this->plugin; + } + + /** + * Wrapper for txt function + */ + final protected function txt($a_var) + { + return $this->getPlugin()->txt($a_var); + } + + /** + * Use custom creation form titles + * + * @param string $a_form_type + * @return string + */ + protected function getCreationFormTitle($a_form_type) + { + switch ($a_form_type) { + case self::CFORM_NEW: + return $this->txt($this->getType() . "_new"); + + case self::CFORM_IMPORT: + return $this->lng->txt("import"); + + case self::CFORM_CLONE: + return $this->txt("objs_" . $this->getType() . "_duplicate"); + } + } + + /** + * Init creation froms + * + * this will create the default creation forms: new, import, clone + * + * @param string $a_new_type + * @return array + */ + protected function initCreationForms($a_new_type) + { + $ilPluginAdmin = $this->plugin_admin; + + $forms = array(); + $forms[self::CFORM_NEW] = $this->initCreateForm($a_new_type); + + if ($this->supportsExport()) { + $forms[self::CFORM_IMPORT] = $this->initImportForm($a_new_type); + } + if ($this->supportsCloning()) { + $forms[self::CFORM_CLONE] = $this->fillCloneTemplate(null, $a_new_type); + } + + return $forms; + } + + /** + * @return bool returns true iff this plugin object supports cloning + */ + protected function supportsCloning() + { + return true; + } + + /** + * Init object creation form + * + * @param string $a_new_type + * @return ilPropertyFormGUI + */ + public function initCreateForm($a_new_type) + { + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setTarget("_top"); + $form->setFormAction($this->ctrl->getFormAction($this, "save")); + $form->setTitle($this->txt($a_new_type . "_new")); + + // title + $ti = new ilTextInputGUI($this->lng->txt("title"), "title"); + $ti->setSize(min(40, ilObject::TITLE_LENGTH)); + $ti->setMaxLength(ilObject::TITLE_LENGTH); + $ti->setRequired(true); + $form->addItem($ti); + + // description + $ta = new ilTextAreaInputGUI($this->lng->txt("description"), "desc"); + $ta->setCols(40); + $ta->setRows(2); + $form->addItem($ta); + + $form->addCommandButton("save", $this->txt($a_new_type . "_add")); + $form->addCommandButton("cancel", $this->lng->txt("cancel")); + + return $form; + } + + /** + * Init object update form + * + * @return ilPropertyFormGUI + */ + public function initEditForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setTarget("_top"); + $form->setFormAction($ilCtrl->getFormAction($this, "update")); + $form->setTitle($lng->txt("edit")); + + // title + $ti = new ilTextInputGUI($lng->txt("title"), "title"); + $ti->setSize(min(40, ilObject::TITLE_LENGTH)); + $ti->setMaxLength(ilObject::TITLE_LENGTH); + $ti->setRequired(true); + $form->addItem($ti); + + // description + $ta = new ilTextAreaInputGUI($lng->txt("description"), "desc"); + $ta->setCols(40); + $ta->setRows(2); + $form->addItem($ta); + + $form->addCommandButton("update", $lng->txt("save")); + // $this->form->addCommandButton("cancelUpdate", $lng->txt("cancel")); + + return $form; + } + + /** + * Init object import form + * + * @param string new type + * @return ilPropertyFormGUI + */ + protected function initImportForm($a_new_type) + { + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setTarget("_top"); + $form->setFormAction($this->ctrl->getFormAction($this, "importFile")); + $form->setTitle($this->lng->txt("import")); + + include_once("./Services/Form/classes/class.ilFileInputGUI.php"); + $fi = new ilFileInputGUI($this->lng->txt("import_file"), "importfile"); + $fi->setSuffixes(array("zip")); + $fi->setRequired(true); + $form->addItem($fi); + + $form->addCommandButton("importFile", $this->lng->txt("import")); + $form->addCommandButton("cancel", $this->lng->txt("cancel")); + + return $form; + } + + /** + * After saving + * @access public + */ + public function afterSave(ilObject $newObj) + { + $ilCtrl = $this->ctrl; + // always send a message + ilUtil::sendSuccess($this->lng->txt("object_added"), true); + + $ilCtrl->initBaseClass("ilObjPluginDispatchGUI"); + $ilCtrl->getCallStructure(strtolower("ilObjPluginDispatchGUI")); + + $ilCtrl->setParameterByClass(get_class($this), "ref_id", $newObj->getRefId()); + $ilCtrl->redirectByClass(array("ilobjplugindispatchgui", get_class($this)), $this->getAfterCreationCmd()); + } + + /** + * Cmd that will be redirected to after creation of a new object. + */ + abstract public function getAfterCreationCmd(); + + abstract public function getStandardCmd(); + + // abstract function performCommand(); + + /** + * Add info screen tab + */ + public function addInfoTab() + { + $ilAccess = $this->access; + $ilTabs = $this->tabs; + + // info screen + if ($ilAccess->checkAccess('visible', "", $this->object->getRefId())) { + $ilTabs->addTarget( + "info_short", + $this->ctrl->getLinkTargetByClass( + "ilinfoscreengui", + "showSummary" + ), + "showSummary" + ); + } + } + + /** + * Add permission tab + */ + public function addPermissionTab() + { + $ilAccess = $this->access; + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + + // edit permissions + if ($ilAccess->checkAccess('edit_permission', "", $this->object->getRefId())) { + $ilTabs->addTarget( + "perm_settings", + $ilCtrl->getLinkTargetByClass("ilpermissiongui", "perm"), + array("perm","info","owner"), + 'ilpermissiongui' + ); + } + } + + + /** + * Add export tab + */ + public function addExportTab() + { + // write + if ($this->access->checkAccess('write', "", $this->object->getRefId())) { + $this->tabs->addTarget( + 'export', + $this->ctrl->getLinkTargetByClass("ilexportgui", ''), + 'export', + 'ilexportgui' + ); + } + } + + /** + * show information screen + */ + public function infoScreen() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + $ilTabs->activateTab("info_short"); + + $this->checkPermission("visible"); + + include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php"); + $info = new ilInfoScreenGUI($this); + $info->enablePrivateNotes(); + + // general information + $lng->loadLanguageModule("meta"); + + $this->addInfoItems($info); + + // forward the command + $ilCtrl->forwardCommand($info); + } /** * Add items to info screen * @param ilInfoScreenGUI $info */ - function addInfoItems($info) - { - } - - /** - * Goto redirection - */ - public static function _goto($a_target) - { - global $DIC; - - $ilCtrl = $DIC->ctrl(); - $ilAccess = $DIC->access(); - $lng = $DIC->language(); - - $t = explode("_", $a_target[0]); - $ref_id = (int) $t[0]; - $class_name = $a_target[1]; - - if ($ilAccess->checkAccess("read", "", $ref_id)) - { - $ilCtrl->initBaseClass("ilObjPluginDispatchGUI"); - $ilCtrl->getCallStructure(strtolower("ilObjPluginDispatchGUI")); - $ilCtrl->setParameterByClass($class_name, "ref_id", $ref_id); - $ilCtrl->redirectByClass(array("ilobjplugindispatchgui", $class_name), ""); - } - else if($ilAccess->checkAccess("visible", "", $ref_id)) - { - $ilCtrl->initBaseClass("ilObjPluginDispatchGUI"); - $ilCtrl->getCallStructure(strtolower("ilObjPluginDispatchGUI")); - $ilCtrl->setParameterByClass($class_name, "ref_id", $ref_id); - $ilCtrl->redirectByClass(array("ilobjplugindispatchgui", $class_name), "infoScreen"); - } - else if ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) - { - ilUtil::sendFailure(sprintf($lng->txt("msg_no_perm_read_item"), - ilObject::_lookupTitle(ilObject::_lookupObjId($ref_id)))); - include_once("./Services/Object/classes/class.ilObjectGUI.php"); - ilObjectGUI::_gotoRepositoryRoot(); - } - } - - - /** - * @return bool - */ - protected function supportsExport() { - $ilPluginAdmin = $this->plugin_admin; - - return $ilPluginAdmin->supportsExport(IL_COMP_SERVICE, "Repository", "robj", $this->getPlugin()->getPluginName()); - } - - - /** - * @return mixed - */ - protected function lookupParentTitleInCreationMode() { - return ilObject::_lookupTitle(ilObject::_lookupObjId($_GET["ref_id"])); - } + public function addInfoItems($info) + { + } + + /** + * Goto redirection + */ + public static function _goto($a_target) + { + global $DIC; + + $ilCtrl = $DIC->ctrl(); + $ilAccess = $DIC->access(); + $lng = $DIC->language(); + + $t = explode("_", $a_target[0]); + $ref_id = (int) $t[0]; + $class_name = $a_target[1]; + + if ($ilAccess->checkAccess("read", "", $ref_id)) { + $ilCtrl->initBaseClass("ilObjPluginDispatchGUI"); + $ilCtrl->getCallStructure(strtolower("ilObjPluginDispatchGUI")); + $ilCtrl->setParameterByClass($class_name, "ref_id", $ref_id); + $ilCtrl->redirectByClass(array("ilobjplugindispatchgui", $class_name), ""); + } elseif ($ilAccess->checkAccess("visible", "", $ref_id)) { + $ilCtrl->initBaseClass("ilObjPluginDispatchGUI"); + $ilCtrl->getCallStructure(strtolower("ilObjPluginDispatchGUI")); + $ilCtrl->setParameterByClass($class_name, "ref_id", $ref_id); + $ilCtrl->redirectByClass(array("ilobjplugindispatchgui", $class_name), "infoScreen"); + } elseif ($ilAccess->checkAccess("read", "", ROOT_FOLDER_ID)) { + ilUtil::sendFailure(sprintf( + $lng->txt("msg_no_perm_read_item"), + ilObject::_lookupTitle(ilObject::_lookupObjId($ref_id)) + )); + include_once("./Services/Object/classes/class.ilObjectGUI.php"); + ilObjectGUI::_gotoRepositoryRoot(); + } + } + + + /** + * @return bool + */ + protected function supportsExport() + { + $ilPluginAdmin = $this->plugin_admin; + + return $ilPluginAdmin->supportsExport(IL_COMP_SERVICE, "Repository", "robj", $this->getPlugin()->getPluginName()); + } + + + /** + * @return mixed + */ + protected function lookupParentTitleInCreationMode() + { + return ilObject::_lookupTitle(ilObject::_lookupObjId($_GET["ref_id"])); + } } diff --git a/Services/Repository/classes/class.ilObjectPluginListGUI.php b/Services/Repository/classes/class.ilObjectPluginListGUI.php index b600a4e36b1203eb1c410176d6092fd8856dba0a..8780582d0fea5cb4e738fdaad74f38d649d36b71 100755 --- a/Services/Repository/classes/class.ilObjectPluginListGUI.php +++ b/Services/Repository/classes/class.ilObjectPluginListGUI.php @@ -13,151 +13,156 @@ include_once "Services/Object/classes/class.ilObjectListGUI.php"; abstract class ilObjectPluginListGUI extends ilObjectListGUI { - /** - * Constructor - */ - function __construct($a_context = self::CONTEXT_REPOSITORY) - { - global $DIC; - - parent::__construct($a_context); - - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - } - - - /** - * @var ilRepositoryObjectPlugin - */ - protected $plugin; - - /** - * initialisation - */ - final function init() - { - $this->initListActions(); - $this->initType(); - $this->plugin = $this->getPlugin(); - $this->gui_class_name = $this->getGuiClass(); - $this->commands = $this->initCommands(); - } - - abstract function getGuiClass(); - abstract function initCommands(); - - /** - * Set - * - * @param - */ - function setType($a_val) - { - $this->type = $a_val; - } - - /** - * @return ilObjectPlugin|null - */ - protected function getPlugin() { - if(!$this->plugin) { - $this->plugin = - ilPlugin::getPluginObject(IL_COMP_SERVICE, "Repository", "robj", - ilPlugin::lookupNameForId(IL_COMP_SERVICE, "Repository", "robj", $this->getType())); - } - return $this->plugin; - } - - /** - * Get type - * - * @return type - */ - function getType() - { - return $this->type; - } - - abstract function initType(); - - /** - * txt - */ - function txt($a_str) - { - return $this->plugin->txt($a_str); - } - - - /** - * inititialize new item - * - * @param int $a_ref_id reference id - * @param int $a_obj_id object id - * @param string $a_title title - * @param string $a_description description - */ - function initItem($a_ref_id, $a_obj_id, $a_title = "", $a_description = "") - { - parent::initItem($a_ref_id, $a_obj_id, $a_title, $a_description); - } - - - /** - * Get command target frame - * - * @param string $a_cmd command - * - * @return string command target frame - */ - function getCommandFrame($a_cmd) - { - return ilFrameTargetInfo::_getFrame("MainContent"); - } - - /** - * Get item properties - * - * @return array array of property arrays: - * "alert" (boolean) => display as an alert property (usually in red) - * "property" (string) => property name - * "value" (string) => property value - */ - function getProperties() - { - $lng = $this->lng; - $ilUser = $this->user; - - $props = array(); - - return $props; - } - - - /** - * Get command link url. - * - * @param int $a_ref_id reference id - * @param string $a_cmd command - * - */ - function getCommandLink($a_cmd) - { - - // separate method for this line - $cmd_link = "ilias.php?baseClass=ilObjPluginDispatchGUI&". - "cmd=forward&ref_id=".$this->ref_id."&forwardCmd=".$a_cmd; - - return $cmd_link; - } - - protected function initListActions() { - $this->delete_enabled = true; - $this->cut_enabled = true; - $this->subscribe_enabled = true; - $this->link_enabled = true; - $this->info_screen_enabled = true; - } + /** + * Constructor + */ + public function __construct($a_context = self::CONTEXT_REPOSITORY) + { + global $DIC; + + parent::__construct($a_context); + + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + } + + + /** + * @var ilRepositoryObjectPlugin + */ + protected $plugin; + + /** + * initialisation + */ + final public function init() + { + $this->initListActions(); + $this->initType(); + $this->plugin = $this->getPlugin(); + $this->gui_class_name = $this->getGuiClass(); + $this->commands = $this->initCommands(); + } + + abstract public function getGuiClass(); + abstract public function initCommands(); + + /** + * Set + * + * @param + */ + public function setType($a_val) + { + $this->type = $a_val; + } + + /** + * @return ilObjectPlugin|null + */ + protected function getPlugin() + { + if (!$this->plugin) { + $this->plugin = + ilPlugin::getPluginObject( + IL_COMP_SERVICE, + "Repository", + "robj", + ilPlugin::lookupNameForId(IL_COMP_SERVICE, "Repository", "robj", $this->getType()) + ); + } + return $this->plugin; + } + + /** + * Get type + * + * @return type + */ + public function getType() + { + return $this->type; + } + + abstract public function initType(); + + /** + * txt + */ + public function txt($a_str) + { + return $this->plugin->txt($a_str); + } + + + /** + * inititialize new item + * + * @param int $a_ref_id reference id + * @param int $a_obj_id object id + * @param string $a_title title + * @param string $a_description description + */ + public function initItem($a_ref_id, $a_obj_id, $a_title = "", $a_description = "") + { + parent::initItem($a_ref_id, $a_obj_id, $a_title, $a_description); + } + + + /** + * Get command target frame + * + * @param string $a_cmd command + * + * @return string command target frame + */ + public function getCommandFrame($a_cmd) + { + return ilFrameTargetInfo::_getFrame("MainContent"); + } + + /** + * Get item properties + * + * @return array array of property arrays: + * "alert" (boolean) => display as an alert property (usually in red) + * "property" (string) => property name + * "value" (string) => property value + */ + public function getProperties() + { + $lng = $this->lng; + $ilUser = $this->user; + + $props = array(); + + return $props; + } + + + /** + * Get command link url. + * + * @param int $a_ref_id reference id + * @param string $a_cmd command + * + */ + public function getCommandLink($a_cmd) + { + + // separate method for this line + $cmd_link = "ilias.php?baseClass=ilObjPluginDispatchGUI&" . + "cmd=forward&ref_id=" . $this->ref_id . "&forwardCmd=" . $a_cmd; + + return $cmd_link; + } + + protected function initListActions() + { + $this->delete_enabled = true; + $this->cut_enabled = true; + $this->subscribe_enabled = true; + $this->link_enabled = true; + $this->info_screen_enabled = true; + } } -?> diff --git a/Services/Repository/classes/class.ilRepDependenciesTableGUI.php b/Services/Repository/classes/class.ilRepDependenciesTableGUI.php index c3d404fcc3f94120817cfa1c5fa5c0b0dc0c8e2d..4638800d097d0c6400a345f7bfd1f77d73b29001 100644 --- a/Services/Repository/classes/class.ilRepDependenciesTableGUI.php +++ b/Services/Repository/classes/class.ilRepDependenciesTableGUI.php @@ -1,4 +1,4 @@ -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(null, ""); - $lng->loadLanguageModule("rep"); + $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(null, ""); + $lng->loadLanguageModule("rep"); - $this->setTitle($lng->txt("rep_dependencies")); - $this->setLimit(9999); - - $this->addColumn($this->lng->txt("rep_object_to_delete")); - $this->addColumn($this->lng->txt("rep_dependent_object")); - $this->addColumn($this->lng->txt("rep_dependency")); - - $this->setEnableHeader(true); - //$this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.rep_dep_row.html", "Services/Repository"); - $this->disable("footer"); - $this->setEnableTitle(true); - - $deps = array(); - foreach ($a_deps as $id => $d) - { - foreach ($d as $id2 => $ms) - { - foreach ($ms as $m) - { - $deps[] = array("dep_obj" => $id2, "del_obj" => $id, "message" => $m); - } - } - } - $this->setData($deps); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $this->tpl->setVariable("TXT_DEP_OBJ", - $lng->txt("obj_".ilObject::_lookupType($a_set["dep_obj"])).": ".ilObject::_lookupTitle($a_set["dep_obj"])); - $this->tpl->setVariable("TXT_DEL_OBJ", - $lng->txt("obj_".ilObject::_lookupType($a_set["del_obj"])).": ".ilObject::_lookupTitle($a_set["del_obj"])); - $this->tpl->setVariable("TXT_MESS", $a_set["message"]); - } + $this->setTitle($lng->txt("rep_dependencies")); + $this->setLimit(9999); + + $this->addColumn($this->lng->txt("rep_object_to_delete")); + $this->addColumn($this->lng->txt("rep_dependent_object")); + $this->addColumn($this->lng->txt("rep_dependency")); + + $this->setEnableHeader(true); + //$this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.rep_dep_row.html", "Services/Repository"); + $this->disable("footer"); + $this->setEnableTitle(true); + $deps = array(); + foreach ($a_deps as $id => $d) { + foreach ($d as $id2 => $ms) { + foreach ($ms as $m) { + $deps[] = array("dep_obj" => $id2, "del_obj" => $id, "message" => $m); + } + } + } + $this->setData($deps); + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $this->tpl->setVariable( + "TXT_DEP_OBJ", + $lng->txt("obj_" . ilObject::_lookupType($a_set["dep_obj"])) . ": " . ilObject::_lookupTitle($a_set["dep_obj"]) + ); + $this->tpl->setVariable( + "TXT_DEL_OBJ", + $lng->txt("obj_" . ilObject::_lookupType($a_set["del_obj"])) . ": " . ilObject::_lookupTitle($a_set["del_obj"]) + ); + $this->tpl->setVariable("TXT_MESS", $a_set["message"]); + } } -?> \ No newline at end of file diff --git a/Services/Repository/classes/class.ilRepUtil.php b/Services/Repository/classes/class.ilRepUtil.php index 7198b1aacf0635e82f7b19f0f1b62c99f9b6b6ef..204cb552ea3053f9cbb30f919d4b81eb70e8d722 100644 --- a/Services/Repository/classes/class.ilRepUtil.php +++ b/Services/Repository/classes/class.ilRepUtil.php @@ -12,615 +12,573 @@ include_once("./Services/Object/classes/class.ilObjectFactory.php"); */ class ilRepUtil { - /** - * @var ilDB - */ - protected $db; - - /** - * @var ilTree - */ - protected $tree; - - /** - * @var ilSetting - */ - protected $settings; - - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->db = $DIC->database(); - $this->tree = $DIC->repositoryTree(); - $this->settings = $DIC->settings(); - } - - - /** - * Delete objects. Move them to trash (if trash feature is enabled). - * - * @param integer current ref id - * @param array array of ref(!) ids to be deleted - */ - static public function deleteObjects($a_cur_ref_id, $a_ids) - { - global $DIC; - - $ilAppEventHandler = $DIC["ilAppEventHandler"]; - $rbacsystem = $DIC->rbac()->system(); - $rbacadmin = $DIC->rbac()->admin(); - $ilLog = $DIC["ilLog"]; - $tree = $DIC->repositoryTree(); - $lng = $DIC->language(); - $ilSetting = $DIC->settings(); - - $log = $ilLog; - - include_once("./Services/Repository/exceptions/class.ilRepositoryException.php"); - - // Remove duplicate ids from array - $a_ids = array_unique((array) $a_ids); - - // FOR ALL SELECTED OBJECTS - $not_deletable = []; - foreach ($a_ids as $id) - { - if ($tree->isDeleted($id)) - { - $log->write(__METHOD__.': Object with ref_id: '.$id.' already deleted.'); - throw new ilRepositoryException($lng->txt("msg_obj_already_deleted")); - } - - // GET COMPLETE NODE_DATA OF ALL SUBTREE NODES - $node_data = $tree->getNodeData($id); - $subtree_nodes = $tree->getSubTree($node_data); - - $all_node_data[] = $node_data; - $all_subtree_nodes[] = $subtree_nodes; - - // CHECK DELETE PERMISSION OF ALL OBJECTS - foreach ($subtree_nodes as $node) - { - if($node['type'] == 'rolf') - { - continue; - } - if (!$rbacsystem->checkAccess('delete',$node["child"])) - { - $not_deletable[] = $node["child"]; - $perform_delete = false; - } - } - } - - // IF THERE IS ANY OBJECT WITH NO PERMISSION TO DELETE - if (is_array($not_deletable) && count($not_deletable) > 0) - { - $not_deletable_titles = array(); - foreach ($not_deletable as $key => $ref_id) { - $obj_id = ilObject::_lookupObjId($ref_id); - $not_deletable_titles[] = ilObject::_lookupTitle($obj_id); - } - - ilSession::clear("saved_post"); - throw new ilRepositoryException( - $lng->txt("msg_no_perm_delete")." ".implode(', ',$not_deletable_titles)."
                  ".$lng->txt("msg_cancel")); - } - - // DELETE THEM - if (!$all_node_data[0]["type"]) - { -// alex: this branch looks suspicious to me... I deactivate it for -// now. Objects that aren't in the tree should overwrite this method. -throw new ilRepositoryException($lng->txt("ilRepUtil::deleteObjects: Type information missing.")); - // OBJECTS ARE NO 'TREE OBJECTS' - if ($rbacsystem->checkAccess('delete', $a_cur_ref_id)) - { - foreach($a_ids as $id) - { - $obj = ilObjectFactory::getInstanceByObjId($id); - $obj->delete(); - - // write log entry - $log->write("ilObjectGUI::confirmedDeleteObject(), deleted obj_id ".$obj->getId(). - ", type: ".$obj->getType().", title: ".$obj->getTitle()); - } - } - else - { - throw new ilRepositoryException( - $lng->txt("no_perm_delete")."
                  ".$lng->txt("msg_cancel")); - } - } - else - { - // SAVE SUBTREE AND DELETE SUBTREE FROM TREE - $affected_ids = array(); - $affected_parents = array(); - foreach ($a_ids as $id) - { - if($tree->isDeleted($id)) - { - $log->write(__METHOD__.': Object with ref_id: '.$id.' already deleted.'); - throw new ilRepositoryException($lng->txt("msg_obj_already_deleted")); - } - - // DELETE OLD PERMISSION ENTRIES - $subnodes = $tree->getSubtree($tree->getNodeData($id)); - - foreach ($subnodes as $subnode) - { - $rbacadmin->revokePermission($subnode["child"]); - // remove item from all user desktops - $affected_users = ilUtil::removeItemFromDesktops($subnode["child"]); - - $affected_ids[$subnode["child"]] = $subnode["child"]; - $affected_parents[$subnode["child"]] = $subnode["parent"]; - - // TODO: inform users by mail that object $id was deleted - //$mail->sendMail($id,$msg,$affected_users); - // should go to appevents at the end - } - - // TODO: needs other handling - // This class shouldn't have to know anything about ECS - include_once('./Services/WebServices/ECS/classes/class.ilECSObjectSettings.php'); - ilECSObjectSettings::_handleDelete($subnodes); - - if(!$tree->saveSubTree($id, true)) - { - $log->write(__METHOD__.': Object with ref_id: '.$id.' already deleted.'); - throw new ilRepositoryException($lng->txt("msg_obj_already_deleted")); - } - - // write log entry - $log->write("ilObjectGUI::confirmedDeleteObject(), moved ref_id ".$id. - " to trash"); - - // remove item from all user desktops - $affected_users = ilUtil::removeItemFromDesktops($id); - - $affected_ids[$id] = $id; - - // TODO: inform users by mail that object $id was deleted - //$mail->sendMail($id,$msg,$affected_users); - } - - // send global events - foreach ($affected_ids as $aid) - { - $ilAppEventHandler->raise("Services/Object", "toTrash", - array( "obj_id" => ilObject::_lookupObjId($aid), - "ref_id" => $aid, - "old_parent_ref_id" => $affected_parents[$aid] - )); - } - } - - if (!$ilSetting->get('enable_trash')) - { - ilRepUtil::removeObjectsFromSystem($a_ids); - } - } - - /** - * remove objects from trash bin and all entries therefore every object needs a specific deleteObject() method - * - * @access public - */ - public static function removeObjectsFromSystem($a_ref_ids, $a_from_recovery_folder = false) - { - global $DIC; - - $ilLog = $DIC["ilLog"]; - $ilAppEventHandler = $DIC["ilAppEventHandler"]; - $tree = $DIC->repositoryTree(); - - $log = $ilLog; - - $affected_ids = array(); - - // DELETE THEM - foreach ($a_ref_ids as $id) - { - // GET COMPLETE NODE_DATA OF ALL SUBTREE NODES - if (!$a_from_recovery_folder) - { - $saved_tree = new ilTree(-(int)$id); - $node_data = $saved_tree->getNodeData($id); - $subtree_nodes = $saved_tree->getSubTree($node_data); - } - else - { - $node_data = $tree->getNodeData($id); - $subtree_nodes = $tree->getSubTree($node_data); - } - - // BEGIN ChangeEvent: Record remove from system. - require_once('Services/Tracking/classes/class.ilChangeEvent.php'); - // Record write event - global $DIC; - - $ilUser = $DIC->user(); - $tree = $DIC->repositoryTree(); - $parent_data = $tree->getParentNodeData($node_data['ref_id']); - ilChangeEvent::_recordWriteEvent($node_data['obj_id'], $ilUser->getId(), 'purge', - $parent_data['obj_id']); - // END ChangeEvent: Record remove from system. - - // remember already checked deleted node_ids - if (!$a_from_recovery_folder) - { - $checked[] = -(int) $id; - } - else - { - $checked[] = $id; - } - - // dive in recursive manner in each already deleted subtrees and remove these objects too - ilRepUtil::removeDeletedNodes($id, $checked, true, $affected_ids); - - foreach ($subtree_nodes as $node) - { - if(!$node_obj = ilObjectFactory::getInstanceByRefId($node["ref_id"],false)) - { - continue; - } - - // write log entry - $log->write("ilObjectGUI::removeFromSystemObject(), delete obj_id: ".$node_obj->getId(). - ", ref_id: ".$node_obj->getRefId().", type: ".$node_obj->getType().", ". - "title: ".$node_obj->getTitle()); - $affected_ids[$node["ref_id"]] = array( - "ref_id" => $node["ref_id"], - "obj_id" => $node_obj->getId(), - "type" => $node_obj->getType(), - "old_parent_ref_id" => $node["parent"]); - - // this is due to bug #1860 (even if this will not completely fix it) - // and the fact, that media pool folders may find their way into - // the recovery folder (what results in broken pools, if the are deleted) - // Alex, 2006-07-21 - if (!$a_from_recovery_folder || $node_obj->getType() != "fold") - { - $node_obj->delete(); - } - } - - // Use the saved tree object here (negative tree_id) - if (!$a_from_recovery_folder) - { - $saved_tree->deleteTree($node_data); - } - else - { - $tree->deleteTree($node_data); - } - - // write log entry - $log->write("ilObjectGUI::removeFromSystemObject(), deleted tree, tree_id: ".$node_data["tree"]. - ", child: ".$node_data["child"]); - - } - - // send global events - foreach ($affected_ids as $aid) - { - $ilAppEventHandler->raise("Services/Object", "delete", - array("obj_id" => $aid["obj_id"], - "ref_id" => $aid["ref_id"], - "type" => $aid["type"], - "old_parent_ref_id" => $aid["old_parent_ref_id"])); - } - } - - /** - * Remove already deleted objects within the objects in trash - */ - private static function removeDeletedNodes($a_node_id, $a_checked, $a_delete_objects, - &$a_affected_ids) - { - global $DIC; - - $ilLog = $DIC["ilLog"]; - $ilDB = $DIC->database(); - $tree = $DIC->repositoryTree(); - - $log = $ilLog; - - $q = "SELECT tree FROM tree WHERE parent= ". - $ilDB->quote($a_node_id, "integer")." AND tree < 0"; - - $r = $ilDB->query($q); - - while($row = $ilDB->fetchObject($r)) - { - // only continue recursion if fetched node wasn't touched already! - if (!in_array($row->tree,$a_checked)) - { - $deleted_tree = new ilTree($row->tree); - $a_checked[] = $row->tree; - - $row->tree = $row->tree * (-1); - $del_node_data = $deleted_tree->getNodeData($row->tree); - $del_subtree_nodes = $deleted_tree->getSubTree($del_node_data); - - ilRepUtil::removeDeletedNodes($row->tree,$a_checked, $a_delete_objects, $a_affected_ids); - - if ($a_delete_objects) - { - foreach ($del_subtree_nodes as $node) - { - $node_obj = ilObjectFactory::getInstanceByRefId($node["ref_id"]); - - // write log entry - $log->write("ilObjectGUI::removeDeletedNodes(), delete obj_id: ".$node_obj->getId(). - ", ref_id: ".$node_obj->getRefId().", type: ".$node_obj->getType().", ". - "title: ".$node_obj->getTitle()); - $a_affected_ids[$node["ref_id"]] = array( - "ref_id" => $node["ref_id"], - "obj_id" => $node_obj->getId(), - "type" => $node_obj->getType(), - "old_parent_ref_id" => $node["parent"]); - - $node_obj->delete(); - - } - } - - $tree->deleteTree($del_node_data); - - // write log entry - $log->write("ilObjectGUI::removeDeletedNodes(), deleted tree, tree_id: ".$del_node_data["tree"]. - ", child: ".$del_node_data["child"]); - } - } - - return true; - } - - /** - * Move objects from trash back to repository - */ - static public function restoreObjects($a_cur_ref_id, $a_ref_ids) - { - global $DIC; - - $rbacsystem = $DIC->rbac()->system(); - $ilAppEventHandler = $DIC["ilAppEventHandler"]; - $lng = $DIC->language(); - $tree = $DIC->repositoryTree(); - - $cur_obj_id = ilObject::_lookupObjId($a_cur_ref_id); - - $no_create = []; - - foreach ($a_ref_ids as $id) - { - $obj_data = ilObjectFactory::getInstanceByRefId($id); - - if (!$rbacsystem->checkAccess('create', $a_cur_ref_id, $obj_data->getType())) - { - $no_create[] = ilObject::_lookupTitle(ilObject::_lookupObjId($id)); - } - } - - if (count($no_create)) - { - include_once("./Services/Repository/exceptions/class.ilRepositoryException.php"); - throw new ilRepositoryException($lng->txt("msg_no_perm_paste")." ".implode(',',$no_create)); - } - - $affected_ids = array(); - - foreach ($a_ref_ids as $id) - { - $affected_ids[$id] = $id; - - // INSERT AND SET PERMISSIONS - try { - ilRepUtil::insertSavedNodes($id, $a_cur_ref_id, -(int) $id, $affected_ids); - } - catch (Exception $e) { - include_once("./Services/Repository/exceptions/class.ilRepositoryException.php"); - throw new ilRepositoryException('Restore from trash failed with message: ' . $e->getMessage()); - } - - - // BEGIN ChangeEvent: Record undelete. - require_once('Services/Tracking/classes/class.ilChangeEvent.php'); - global $DIC; - - $ilUser = $DIC->user(); - - - ilChangeEvent::_recordWriteEvent( - ilObject::_lookupObjId($id), - $ilUser->getId(), - 'undelete', - ilObject::_lookupObjId($tree->getParentId($id)) - ); - ilChangeEvent::_catchupWriteEvents( - $cur_obj_id, - $ilUser->getId()); - // END PATCH ChangeEvent: Record undelete. - - } - - // send events - foreach ($affected_ids as $id) - { - // send global event - $ilAppEventHandler->raise("Services/Object", "undelete", - array("obj_id" => ilObject::_lookupObjId($id), "ref_id" => $id)); - } - } - - /** - * Recursive method to insert all saved nodes of the clipboard - */ - private static function insertSavedNodes($a_source_id, $a_dest_id, $a_tree_id, &$a_affected_ids) - { - global $DIC; - - $tree = $DIC->repositoryTree(); - - ilLoggerFactory::getLogger('rep')->debug('Restoring from trash: source_id: '. $a_source_id.', dest_id: '. $a_dest_id.', tree_id:'. $a_tree_id); - ilLoggerFactory::getLogger('rep')->info('Restoring ref_id ' . $a_source_id . ' from trash.'); - - // read child of node - $saved_tree = new ilTree($a_tree_id); - $childs = $saved_tree->getChilds($a_source_id); - - // then delete node and put in tree - try { - $tree->insertNodeFromTrash($a_source_id, $a_dest_id, $a_tree_id, IL_LAST_NODE, true); - } - catch (Exception $e) { - ilLoggerFactory::getLogger('rep')->error('Restore from trash failed with message: ' . $e->getMessage()); - throw $e; - } - - include_once './Services/Object/classes/class.ilObjectFactory.php'; - $factory = new ilObjectFactory(); - $ref_obj = $factory->getInstanceByRefId($a_source_id,FALSE); - if($ref_obj instanceof ilObject) - { - $lroles = $GLOBALS['rbacreview']->getRolesOfRoleFolder($a_source_id,true); - foreach($lroles as $role_id) - { - include_once './Services/AccessControl/classes/class.ilObjRole.php'; - $role = new ilObjRole($role_id); - $role->setParent($a_source_id); - $role->delete(); - } - if($a_dest_id) - { - $ref_obj->setPermissions($a_dest_id); - } - } - foreach ($childs as $child) - { - ilRepUtil::insertSavedNodes($child["child"],$a_source_id,$a_tree_id,$a_affected_ids); - } - } - - - - // - // OBJECT TYPE HANDLING / REMOVAL - // - - protected function findTypeInTrash($a_type) - { - $ilDB = $this->db; - - $res = array(); - - $set = $ilDB->query("SELECT child". - " FROM tree". - " JOIN object_reference ref ON (tree.child = ref.ref_id)". - " JOIN object_data od ON (od.obj_id = ref.obj_id)". - " WHERE tree.tree < ".$ilDB->quote(0, "integer"). - " AND od.type = ".$ilDB->quote($a_type, "text")); - while($row = $ilDB->fetchAssoc($set)) - { - $res[] = $row["child"]; - } - - return $res; - } - - protected function getObjectTypeId($a_type) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT obj_id". - " FROM object_data ". - " WHERE type = ".$ilDB->quote("typ", "text"). - " AND title = ".$ilDB->quote($a_type, "text")); - $row = $ilDB->fetchAssoc($set); - return $row["obj_id"]; - } - - public function deleteObjectType($a_type) - { - $ilDB = $this->db; - $tree = $this->tree; - $ilSetting = $this->settings; - - // delete object instances (repository/trash) - - $ref_ids_in_tree = $tree->getSubTree($tree->getNodeData(ROOT_FOLDER_ID), false, $a_type); - if($ref_ids_in_tree) - { - $this->deleteObjects(null, $ref_ids_in_tree); - } - - if($ilSetting->get('enable_trash')) - { - $ref_ids_in_trash = $this->findTypeInTrash($a_type); - if($ref_ids_in_trash) - { - self::removeObjectsFromSystem($ref_ids_in_trash); - } - } - - // delete "component" - $type_id = $this->getObjectTypeId($a_type); - if($type_id) - { - // see ilRepositoryObjectPlugin::beforeActivation() - - $ilDB->manipulate("DELETE FROM object_data". - " WHERE obj_id = ".$ilDB->quote($type_id, "integer")); - - // RBAC - - // basic operations - $ilDB->manipulate("DELETE FROM rbac_ta". - " WHERE typ_id = ".$ilDB->quote($type_id, "integer") /*. - " AND ".$ilDB->in("ops_id", array(1, 2, 3, 4, 6), "", "integer") */); - - // creation operation - $set = $ilDB->query("SELECT ops_id". - " FROM rbac_operations ". - " WHERE class = ".$ilDB->quote("create", "text"). - " AND operation = ".$ilDB->quote("create_".$a_type, "text")); - $row = $ilDB->fetchAssoc($set); - $create_ops_id = $row["ops_id"]; - if($create_ops_id) - { - $ilDB->manipulate("DELETE FROM rbac_operations". - " WHERE ops_id = ".$ilDB->quote($create_ops_id, "integer")); - - $ilDB->manipulate("DELETE FROM rbac_templates". - " WHERE ops_id = ".$ilDB->quote($create_ops_id, "integer")); - - // container create - foreach(array("root", "cat", "crs", "grp", "fold") as $parent_type) - { - $parent_type_id = $this->getObjectTypeId($parent_type); - if($parent_type_id) - { - $ilDB->manipulate("DELETE FROM rbac_ta". - " WHERE typ_id = ".$ilDB->quote($parent_type_id, "integer"). - " AND ops_id = ".$ilDB->quote($create_ops_id, "integer")); - } - } - } - } - - // delete new item settings - include_once "Services/Repository/classes/class.ilObjRepositorySettings.php"; - ilObjRepositorySettings::deleteObjectType($a_type); - } - - + /** + * @var ilDB + */ + protected $db; + + /** + * @var ilTree + */ + protected $tree; + + /** + * @var ilSetting + */ + protected $settings; + + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->db = $DIC->database(); + $this->tree = $DIC->repositoryTree(); + $this->settings = $DIC->settings(); + } + + + /** + * Delete objects. Move them to trash (if trash feature is enabled). + * + * @param integer current ref id + * @param array array of ref(!) ids to be deleted + */ + public static function deleteObjects($a_cur_ref_id, $a_ids) + { + global $DIC; + + $ilAppEventHandler = $DIC["ilAppEventHandler"]; + $rbacsystem = $DIC->rbac()->system(); + $rbacadmin = $DIC->rbac()->admin(); + $ilLog = $DIC["ilLog"]; + $tree = $DIC->repositoryTree(); + $lng = $DIC->language(); + $ilSetting = $DIC->settings(); + + $log = $ilLog; + + include_once("./Services/Repository/exceptions/class.ilRepositoryException.php"); + + // Remove duplicate ids from array + $a_ids = array_unique((array) $a_ids); + + // FOR ALL SELECTED OBJECTS + $not_deletable = []; + foreach ($a_ids as $id) { + if ($tree->isDeleted($id)) { + $log->write(__METHOD__ . ': Object with ref_id: ' . $id . ' already deleted.'); + throw new ilRepositoryException($lng->txt("msg_obj_already_deleted")); + } + + // GET COMPLETE NODE_DATA OF ALL SUBTREE NODES + $node_data = $tree->getNodeData($id); + $subtree_nodes = $tree->getSubTree($node_data); + + $all_node_data[] = $node_data; + $all_subtree_nodes[] = $subtree_nodes; + + // CHECK DELETE PERMISSION OF ALL OBJECTS + foreach ($subtree_nodes as $node) { + if ($node['type'] == 'rolf') { + continue; + } + if (!$rbacsystem->checkAccess('delete', $node["child"])) { + $not_deletable[] = $node["child"]; + $perform_delete = false; + } + } + } + + // IF THERE IS ANY OBJECT WITH NO PERMISSION TO DELETE + if (is_array($not_deletable) && count($not_deletable) > 0) { + $not_deletable_titles = array(); + foreach ($not_deletable as $key => $ref_id) { + $obj_id = ilObject::_lookupObjId($ref_id); + $not_deletable_titles[] = ilObject::_lookupTitle($obj_id); + } + + ilSession::clear("saved_post"); + throw new ilRepositoryException( + $lng->txt("msg_no_perm_delete") . " " . implode(', ', $not_deletable_titles) . "
                  " . $lng->txt("msg_cancel") + ); + } + + // DELETE THEM + if (!$all_node_data[0]["type"]) { + // alex: this branch looks suspicious to me... I deactivate it for + // now. Objects that aren't in the tree should overwrite this method. + throw new ilRepositoryException($lng->txt("ilRepUtil::deleteObjects: Type information missing.")); + // OBJECTS ARE NO 'TREE OBJECTS' + if ($rbacsystem->checkAccess('delete', $a_cur_ref_id)) { + foreach ($a_ids as $id) { + $obj = ilObjectFactory::getInstanceByObjId($id); + $obj->delete(); + + // write log entry + $log->write("ilObjectGUI::confirmedDeleteObject(), deleted obj_id " . $obj->getId() . + ", type: " . $obj->getType() . ", title: " . $obj->getTitle()); + } + } else { + throw new ilRepositoryException( + $lng->txt("no_perm_delete") . "
                  " . $lng->txt("msg_cancel") + ); + } + } else { + // SAVE SUBTREE AND DELETE SUBTREE FROM TREE + $affected_ids = array(); + $affected_parents = array(); + foreach ($a_ids as $id) { + if ($tree->isDeleted($id)) { + $log->write(__METHOD__ . ': Object with ref_id: ' . $id . ' already deleted.'); + throw new ilRepositoryException($lng->txt("msg_obj_already_deleted")); + } + + // DELETE OLD PERMISSION ENTRIES + $subnodes = $tree->getSubtree($tree->getNodeData($id)); + + foreach ($subnodes as $subnode) { + $rbacadmin->revokePermission($subnode["child"]); + // remove item from all user desktops + $affected_users = ilUtil::removeItemFromDesktops($subnode["child"]); + + $affected_ids[$subnode["child"]] = $subnode["child"]; + $affected_parents[$subnode["child"]] = $subnode["parent"]; + + // TODO: inform users by mail that object $id was deleted + //$mail->sendMail($id,$msg,$affected_users); + // should go to appevents at the end + } + + // TODO: needs other handling + // This class shouldn't have to know anything about ECS + include_once('./Services/WebServices/ECS/classes/class.ilECSObjectSettings.php'); + ilECSObjectSettings::_handleDelete($subnodes); + + if (!$tree->saveSubTree($id, true)) { + $log->write(__METHOD__ . ': Object with ref_id: ' . $id . ' already deleted.'); + throw new ilRepositoryException($lng->txt("msg_obj_already_deleted")); + } + + // write log entry + $log->write("ilObjectGUI::confirmedDeleteObject(), moved ref_id " . $id . + " to trash"); + + // remove item from all user desktops + $affected_users = ilUtil::removeItemFromDesktops($id); + + $affected_ids[$id] = $id; + + // TODO: inform users by mail that object $id was deleted + //$mail->sendMail($id,$msg,$affected_users); + } + + // send global events + foreach ($affected_ids as $aid) { + $ilAppEventHandler->raise( + "Services/Object", + "toTrash", + array( "obj_id" => ilObject::_lookupObjId($aid), + "ref_id" => $aid, + "old_parent_ref_id" => $affected_parents[$aid] + ) + ); + } + } + + if (!$ilSetting->get('enable_trash')) { + ilRepUtil::removeObjectsFromSystem($a_ids); + } + } + + /** + * remove objects from trash bin and all entries therefore every object needs a specific deleteObject() method + * + * @access public + */ + public static function removeObjectsFromSystem($a_ref_ids, $a_from_recovery_folder = false) + { + global $DIC; + + $ilLog = $DIC["ilLog"]; + $ilAppEventHandler = $DIC["ilAppEventHandler"]; + $tree = $DIC->repositoryTree(); + + $log = $ilLog; + + $affected_ids = array(); + + // DELETE THEM + foreach ($a_ref_ids as $id) { + // GET COMPLETE NODE_DATA OF ALL SUBTREE NODES + if (!$a_from_recovery_folder) { + $saved_tree = new ilTree(-(int) $id); + $node_data = $saved_tree->getNodeData($id); + $subtree_nodes = $saved_tree->getSubTree($node_data); + } else { + $node_data = $tree->getNodeData($id); + $subtree_nodes = $tree->getSubTree($node_data); + } + + // BEGIN ChangeEvent: Record remove from system. + require_once('Services/Tracking/classes/class.ilChangeEvent.php'); + // Record write event + global $DIC; + + $ilUser = $DIC->user(); + $tree = $DIC->repositoryTree(); + $parent_data = $tree->getParentNodeData($node_data['ref_id']); + ilChangeEvent::_recordWriteEvent( + $node_data['obj_id'], + $ilUser->getId(), + 'purge', + $parent_data['obj_id'] + ); + // END ChangeEvent: Record remove from system. + + // remember already checked deleted node_ids + if (!$a_from_recovery_folder) { + $checked[] = -(int) $id; + } else { + $checked[] = $id; + } + + // dive in recursive manner in each already deleted subtrees and remove these objects too + ilRepUtil::removeDeletedNodes($id, $checked, true, $affected_ids); + + foreach ($subtree_nodes as $node) { + if (!$node_obj = ilObjectFactory::getInstanceByRefId($node["ref_id"], false)) { + continue; + } + + // write log entry + $log->write("ilObjectGUI::removeFromSystemObject(), delete obj_id: " . $node_obj->getId() . + ", ref_id: " . $node_obj->getRefId() . ", type: " . $node_obj->getType() . ", " . + "title: " . $node_obj->getTitle()); + $affected_ids[$node["ref_id"]] = array( + "ref_id" => $node["ref_id"], + "obj_id" => $node_obj->getId(), + "type" => $node_obj->getType(), + "old_parent_ref_id" => $node["parent"]); + + // this is due to bug #1860 (even if this will not completely fix it) + // and the fact, that media pool folders may find their way into + // the recovery folder (what results in broken pools, if the are deleted) + // Alex, 2006-07-21 + if (!$a_from_recovery_folder || $node_obj->getType() != "fold") { + $node_obj->delete(); + } + } + + // Use the saved tree object here (negative tree_id) + if (!$a_from_recovery_folder) { + $saved_tree->deleteTree($node_data); + } else { + $tree->deleteTree($node_data); + } + + // write log entry + $log->write("ilObjectGUI::removeFromSystemObject(), deleted tree, tree_id: " . $node_data["tree"] . + ", child: " . $node_data["child"]); + } + + // send global events + foreach ($affected_ids as $aid) { + $ilAppEventHandler->raise( + "Services/Object", + "delete", + array("obj_id" => $aid["obj_id"], + "ref_id" => $aid["ref_id"], + "type" => $aid["type"], + "old_parent_ref_id" => $aid["old_parent_ref_id"]) + ); + } + } + + /** + * Remove already deleted objects within the objects in trash + */ + private static function removeDeletedNodes( + $a_node_id, + $a_checked, + $a_delete_objects, + &$a_affected_ids + ) { + global $DIC; + + $ilLog = $DIC["ilLog"]; + $ilDB = $DIC->database(); + $tree = $DIC->repositoryTree(); + + $log = $ilLog; + + $q = "SELECT tree FROM tree WHERE parent= " . + $ilDB->quote($a_node_id, "integer") . " AND tree < 0"; + + $r = $ilDB->query($q); + + while ($row = $ilDB->fetchObject($r)) { + // only continue recursion if fetched node wasn't touched already! + if (!in_array($row->tree, $a_checked)) { + $deleted_tree = new ilTree($row->tree); + $a_checked[] = $row->tree; + + $row->tree = $row->tree * (-1); + $del_node_data = $deleted_tree->getNodeData($row->tree); + $del_subtree_nodes = $deleted_tree->getSubTree($del_node_data); + + ilRepUtil::removeDeletedNodes($row->tree, $a_checked, $a_delete_objects, $a_affected_ids); + + if ($a_delete_objects) { + foreach ($del_subtree_nodes as $node) { + $node_obj = ilObjectFactory::getInstanceByRefId($node["ref_id"]); + + // write log entry + $log->write("ilObjectGUI::removeDeletedNodes(), delete obj_id: " . $node_obj->getId() . + ", ref_id: " . $node_obj->getRefId() . ", type: " . $node_obj->getType() . ", " . + "title: " . $node_obj->getTitle()); + $a_affected_ids[$node["ref_id"]] = array( + "ref_id" => $node["ref_id"], + "obj_id" => $node_obj->getId(), + "type" => $node_obj->getType(), + "old_parent_ref_id" => $node["parent"]); + + $node_obj->delete(); + } + } + + $tree->deleteTree($del_node_data); + + // write log entry + $log->write("ilObjectGUI::removeDeletedNodes(), deleted tree, tree_id: " . $del_node_data["tree"] . + ", child: " . $del_node_data["child"]); + } + } + + return true; + } + + /** + * Move objects from trash back to repository + */ + public static function restoreObjects($a_cur_ref_id, $a_ref_ids) + { + global $DIC; + + $rbacsystem = $DIC->rbac()->system(); + $ilAppEventHandler = $DIC["ilAppEventHandler"]; + $lng = $DIC->language(); + $tree = $DIC->repositoryTree(); + + $cur_obj_id = ilObject::_lookupObjId($a_cur_ref_id); + + $no_create = []; + + foreach ($a_ref_ids as $id) { + $obj_data = ilObjectFactory::getInstanceByRefId($id); + + if (!$rbacsystem->checkAccess('create', $a_cur_ref_id, $obj_data->getType())) { + $no_create[] = ilObject::_lookupTitle(ilObject::_lookupObjId($id)); + } + } + + if (count($no_create)) { + include_once("./Services/Repository/exceptions/class.ilRepositoryException.php"); + throw new ilRepositoryException($lng->txt("msg_no_perm_paste") . " " . implode(',', $no_create)); + } + + $affected_ids = array(); + + foreach ($a_ref_ids as $id) { + $affected_ids[$id] = $id; + + // INSERT AND SET PERMISSIONS + try { + ilRepUtil::insertSavedNodes($id, $a_cur_ref_id, -(int) $id, $affected_ids); + } catch (Exception $e) { + include_once("./Services/Repository/exceptions/class.ilRepositoryException.php"); + throw new ilRepositoryException('Restore from trash failed with message: ' . $e->getMessage()); + } + + + // BEGIN ChangeEvent: Record undelete. + require_once('Services/Tracking/classes/class.ilChangeEvent.php'); + global $DIC; + + $ilUser = $DIC->user(); + + + ilChangeEvent::_recordWriteEvent( + ilObject::_lookupObjId($id), + $ilUser->getId(), + 'undelete', + ilObject::_lookupObjId($tree->getParentId($id)) + ); + ilChangeEvent::_catchupWriteEvents( + $cur_obj_id, + $ilUser->getId() + ); + // END PATCH ChangeEvent: Record undelete. + } + + // send events + foreach ($affected_ids as $id) { + // send global event + $ilAppEventHandler->raise( + "Services/Object", + "undelete", + array("obj_id" => ilObject::_lookupObjId($id), "ref_id" => $id) + ); + } + } + + /** + * Recursive method to insert all saved nodes of the clipboard + */ + private static function insertSavedNodes($a_source_id, $a_dest_id, $a_tree_id, &$a_affected_ids) + { + global $DIC; + + $tree = $DIC->repositoryTree(); + + ilLoggerFactory::getLogger('rep')->debug('Restoring from trash: source_id: ' . $a_source_id . ', dest_id: ' . $a_dest_id . ', tree_id:' . $a_tree_id); + ilLoggerFactory::getLogger('rep')->info('Restoring ref_id ' . $a_source_id . ' from trash.'); + + // read child of node + $saved_tree = new ilTree($a_tree_id); + $childs = $saved_tree->getChilds($a_source_id); + + // then delete node and put in tree + try { + $tree->insertNodeFromTrash($a_source_id, $a_dest_id, $a_tree_id, IL_LAST_NODE, true); + } catch (Exception $e) { + ilLoggerFactory::getLogger('rep')->error('Restore from trash failed with message: ' . $e->getMessage()); + throw $e; + } + + include_once './Services/Object/classes/class.ilObjectFactory.php'; + $factory = new ilObjectFactory(); + $ref_obj = $factory->getInstanceByRefId($a_source_id, false); + if ($ref_obj instanceof ilObject) { + $lroles = $GLOBALS['rbacreview']->getRolesOfRoleFolder($a_source_id, true); + foreach ($lroles as $role_id) { + include_once './Services/AccessControl/classes/class.ilObjRole.php'; + $role = new ilObjRole($role_id); + $role->setParent($a_source_id); + $role->delete(); + } + if ($a_dest_id) { + $ref_obj->setPermissions($a_dest_id); + } + } + foreach ($childs as $child) { + ilRepUtil::insertSavedNodes($child["child"], $a_source_id, $a_tree_id, $a_affected_ids); + } + } + + + + // + // OBJECT TYPE HANDLING / REMOVAL + // + + protected function findTypeInTrash($a_type) + { + $ilDB = $this->db; + + $res = array(); + + $set = $ilDB->query("SELECT child" . + " FROM tree" . + " JOIN object_reference ref ON (tree.child = ref.ref_id)" . + " JOIN object_data od ON (od.obj_id = ref.obj_id)" . + " WHERE tree.tree < " . $ilDB->quote(0, "integer") . + " AND od.type = " . $ilDB->quote($a_type, "text")); + while ($row = $ilDB->fetchAssoc($set)) { + $res[] = $row["child"]; + } + + return $res; + } + + protected function getObjectTypeId($a_type) + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT obj_id" . + " FROM object_data " . + " WHERE type = " . $ilDB->quote("typ", "text") . + " AND title = " . $ilDB->quote($a_type, "text")); + $row = $ilDB->fetchAssoc($set); + return $row["obj_id"]; + } + + public function deleteObjectType($a_type) + { + $ilDB = $this->db; + $tree = $this->tree; + $ilSetting = $this->settings; + + // delete object instances (repository/trash) + + $ref_ids_in_tree = $tree->getSubTree($tree->getNodeData(ROOT_FOLDER_ID), false, $a_type); + if ($ref_ids_in_tree) { + $this->deleteObjects(null, $ref_ids_in_tree); + } + + if ($ilSetting->get('enable_trash')) { + $ref_ids_in_trash = $this->findTypeInTrash($a_type); + if ($ref_ids_in_trash) { + self::removeObjectsFromSystem($ref_ids_in_trash); + } + } + + // delete "component" + $type_id = $this->getObjectTypeId($a_type); + if ($type_id) { + // see ilRepositoryObjectPlugin::beforeActivation() + + $ilDB->manipulate("DELETE FROM object_data" . + " WHERE obj_id = " . $ilDB->quote($type_id, "integer")); + + // RBAC + + // basic operations + $ilDB->manipulate("DELETE FROM rbac_ta" . + " WHERE typ_id = " . $ilDB->quote($type_id, "integer") /*. + " AND ".$ilDB->in("ops_id", array(1, 2, 3, 4, 6), "", "integer") */); + + // creation operation + $set = $ilDB->query("SELECT ops_id" . + " FROM rbac_operations " . + " WHERE class = " . $ilDB->quote("create", "text") . + " AND operation = " . $ilDB->quote("create_" . $a_type, "text")); + $row = $ilDB->fetchAssoc($set); + $create_ops_id = $row["ops_id"]; + if ($create_ops_id) { + $ilDB->manipulate("DELETE FROM rbac_operations" . + " WHERE ops_id = " . $ilDB->quote($create_ops_id, "integer")); + + $ilDB->manipulate("DELETE FROM rbac_templates" . + " WHERE ops_id = " . $ilDB->quote($create_ops_id, "integer")); + + // container create + foreach (array("root", "cat", "crs", "grp", "fold") as $parent_type) { + $parent_type_id = $this->getObjectTypeId($parent_type); + if ($parent_type_id) { + $ilDB->manipulate("DELETE FROM rbac_ta" . + " WHERE typ_id = " . $ilDB->quote($parent_type_id, "integer") . + " AND ops_id = " . $ilDB->quote($create_ops_id, "integer")); + } + } + } + } + + // delete new item settings + include_once "Services/Repository/classes/class.ilObjRepositorySettings.php"; + ilObjRepositorySettings::deleteObjectType($a_type); + } } diff --git a/Services/Repository/classes/class.ilRepUtilGUI.php b/Services/Repository/classes/class.ilRepUtilGUI.php index edb83691c21b12dc5f68225ccabeb59844ad7351..17b11affb86b0e35c3710350bc8c649528db2124 100644 --- a/Services/Repository/classes/class.ilRepUtilGUI.php +++ b/Services/Repository/classes/class.ilRepUtilGUI.php @@ -11,459 +11,416 @@ require_once('./Services/Repository/classes/class.ilObjectPlugin.php'); */ class ilRepUtilGUI { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilSetting - */ - protected $settings; + /** + * @var ilSetting + */ + protected $settings; - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilTemplate - */ - protected $tpl; + /** + * @var ilTemplate + */ + protected $tpl; - /** - * @var ilObjectDefinition - */ - protected $obj_definition; + /** + * @var ilObjectDefinition + */ + protected $obj_definition; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * @var ilTree - */ - protected $tree; + /** + * @var ilTree + */ + protected $tree; - /** - * Constructor - * - * @param object parent gui object - * @param string current parent command (like in table2gui) - */ - function __construct($a_parent_gui, $a_parent_cmd = "") - { - global $DIC; + /** + * Constructor + * + * @param object parent gui object + * @param string current parent command (like in table2gui) + */ + public function __construct($a_parent_gui, $a_parent_cmd = "") + { + global $DIC; - $this->lng = $DIC->language(); - $this->settings = $DIC->settings(); - $this->ctrl = $DIC->ctrl(); - $this->tpl = $DIC["tpl"]; - $this->obj_definition = $DIC["objDefinition"]; - $this->access = $DIC->access(); - $this->tree = $DIC->repositoryTree(); - $this->parent_gui = $a_parent_gui; - $this->parent_cmd = $a_parent_cmd; - } - - - /** - * Show delete confirmation table - */ - function showDeleteConfirmation($a_ids, $a_supress_message = false) - { - $lng = $this->lng; - $ilSetting = $this->settings; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $objDefinition = $this->obj_definition; + $this->lng = $DIC->language(); + $this->settings = $DIC->settings(); + $this->ctrl = $DIC->ctrl(); + $this->tpl = $DIC["tpl"]; + $this->obj_definition = $DIC["objDefinition"]; + $this->access = $DIC->access(); + $this->tree = $DIC->repositoryTree(); + $this->parent_gui = $a_parent_gui; + $this->parent_cmd = $a_parent_cmd; + } + + + /** + * Show delete confirmation table + */ + public function showDeleteConfirmation($a_ids, $a_supress_message = false) + { + $lng = $this->lng; + $ilSetting = $this->settings; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $objDefinition = $this->obj_definition; - if (!is_array($a_ids) || count($a_ids) == 0) - { - ilUtil::sendFailure($lng->txt("no_checkbox"), true); - return false; - } - - // Remove duplicate entries - $a_ids = array_unique((array) $a_ids); + if (!is_array($a_ids) || count($a_ids) == 0) { + ilUtil::sendFailure($lng->txt("no_checkbox"), true); + return false; + } + + // Remove duplicate entries + $a_ids = array_unique((array) $a_ids); - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); - if(!$a_supress_message) - { - $msg = $lng->txt("info_delete_sure"); - - if (!$ilSetting->get('enable_trash')) - { - $msg .= "
                  ".$lng->txt("info_delete_warning_no_trash"); - } - - $cgui->setHeaderText($msg); - } - $cgui->setFormAction($ilCtrl->getFormAction($this->parent_gui)); - $cgui->setCancel($lng->txt("cancel"), "cancelDelete"); - $cgui->setConfirm($lng->txt("confirm"), "confirmedDelete"); - - $form_name = "cgui_".md5(uniqid()); - $cgui->setFormName($form_name); + if (!$a_supress_message) { + $msg = $lng->txt("info_delete_sure"); + + if (!$ilSetting->get('enable_trash')) { + $msg .= "
                  " . $lng->txt("info_delete_warning_no_trash"); + } + + $cgui->setHeaderText($msg); + } + $cgui->setFormAction($ilCtrl->getFormAction($this->parent_gui)); + $cgui->setCancel($lng->txt("cancel"), "cancelDelete"); + $cgui->setConfirm($lng->txt("confirm"), "confirmedDelete"); + + $form_name = "cgui_" . md5(uniqid()); + $cgui->setFormName($form_name); - $deps = array(); - foreach ($a_ids as $ref_id) - { - $obj_id = ilObject::_lookupObjId($ref_id); - $type = ilObject::_lookupType($obj_id); - $title = call_user_func(array(ilObjectFactory::getClassByType($type),'_lookupTitle'),$obj_id); - $alt = ($objDefinition->isPlugin($type)) - ? $lng->txt("icon")." ".ilObjectPlugin::lookupTxtById($type, "obj_".$type) - : $lng->txt("icon")." ".$lng->txt("obj_".$type); - - $title .= $this->handleMultiReferences($obj_id, $ref_id, $form_name); - - $cgui->addItem("id[]", $ref_id, $title, - ilObject::_getIcon($obj_id, "small", $type), - $alt); + $deps = array(); + foreach ($a_ids as $ref_id) { + $obj_id = ilObject::_lookupObjId($ref_id); + $type = ilObject::_lookupType($obj_id); + $title = call_user_func(array(ilObjectFactory::getClassByType($type),'_lookupTitle'), $obj_id); + $alt = ($objDefinition->isPlugin($type)) + ? $lng->txt("icon") . " " . ilObjectPlugin::lookupTxtById($type, "obj_" . $type) + : $lng->txt("icon") . " " . $lng->txt("obj_" . $type); + + $title .= $this->handleMultiReferences($obj_id, $ref_id, $form_name); + + $cgui->addItem( + "id[]", + $ref_id, + $title, + ilObject::_getIcon($obj_id, "small", $type), + $alt + ); - ilObject::collectDeletionDependencies($deps, $ref_id, $obj_id, $type); - } - $deps_html = ""; + ilObject::collectDeletionDependencies($deps, $ref_id, $obj_id, $type); + } + $deps_html = ""; - if (is_array($deps) && count($deps) > 0) - { - include_once("./Services/Repository/classes/class.ilRepDependenciesTableGUI.php"); - $tab = new ilRepDependenciesTableGUI($deps); - $deps_html = "

                  ".$tab->getHTML(); - } - - $tpl->setContent($cgui->getHTML().$deps_html); - return true; - } - - /** - * Build subitem list for multiple references - * - * @param int $a_obj_id - * @param int $a_ref_id - * @param string $a_form_name - * @return string - */ - function handleMultiReferences($a_obj_id, $a_ref_id, $a_form_name) - { - $lng = $this->lng; - $ilAccess = $this->access; - $tree = $this->tree; - - // process - - $all_refs = ilObject::_getAllReferences($a_obj_id); - if(sizeof($all_refs) > 1) - { - $lng->loadLanguageModule("rep"); - - $may_delete_any = 0; - $counter = 0; - $items = array(); - foreach($all_refs as $mref_id) - { - // not the already selected reference, no refs from trash - if($mref_id != $a_ref_id && !$tree->isDeleted($mref_id)) - { - if($ilAccess->checkAccess("read", "", $mref_id)) - { - $may_delete = false; - if($ilAccess->checkAccess("delete", "", $mref_id)) - { - $may_delete = true; - $may_delete_any++; - } - - $items[] = array("id" => $mref_id, - "path" => array_shift($this->buildPath(array($mref_id))), - "delete" => $may_delete); - } - else - { - $counter++; - } - } - } + if (is_array($deps) && count($deps) > 0) { + include_once("./Services/Repository/classes/class.ilRepDependenciesTableGUI.php"); + $tab = new ilRepDependenciesTableGUI($deps); + $deps_html = "

                  " . $tab->getHTML(); + } + + $tpl->setContent($cgui->getHTML() . $deps_html); + return true; + } + + /** + * Build subitem list for multiple references + * + * @param int $a_obj_id + * @param int $a_ref_id + * @param string $a_form_name + * @return string + */ + public function handleMultiReferences($a_obj_id, $a_ref_id, $a_form_name) + { + $lng = $this->lng; + $ilAccess = $this->access; + $tree = $this->tree; + + // process + + $all_refs = ilObject::_getAllReferences($a_obj_id); + if (sizeof($all_refs) > 1) { + $lng->loadLanguageModule("rep"); + + $may_delete_any = 0; + $counter = 0; + $items = array(); + foreach ($all_refs as $mref_id) { + // not the already selected reference, no refs from trash + if ($mref_id != $a_ref_id && !$tree->isDeleted($mref_id)) { + if ($ilAccess->checkAccess("read", "", $mref_id)) { + $may_delete = false; + if ($ilAccess->checkAccess("delete", "", $mref_id)) { + $may_delete = true; + $may_delete_any++; + } + + $items[] = array("id" => $mref_id, + "path" => array_shift($this->buildPath(array($mref_id))), + "delete" => $may_delete); + } else { + $counter++; + } + } + } - - // render + + // render - $tpl = new ilTemplate("tpl.rep_multi_ref.html", true, true, "Services/Repository"); + $tpl = new ilTemplate("tpl.rep_multi_ref.html", true, true, "Services/Repository"); - $tpl->setVariable("TXT_INTRO", $lng->txt("rep_multiple_reference_deletion_intro")); - - if($may_delete_any) - { - $tpl->setVariable("TXT_INSTRUCTION", $lng->txt("rep_multiple_reference_deletion_instruction")); - } - - if($items) - { - $var_name = "mref_id[]"; - - foreach($items as $item) - { - if($item["delete"]) - { - $tpl->setCurrentBlock("cbox"); - $tpl->setVariable("ITEM_NAME", $var_name); - $tpl->setVariable("ITEM_VALUE", $item["id"]); - $tpl->parseCurrentBlock(); - } - else - { - $tpl->setCurrentBlock("item_info"); - $tpl->setVariable("TXT_ITEM_INFO", $lng->txt("rep_no_permission_to_delete")); - $tpl->parseCurrentBlock(); - } - - $tpl->setCurrentBlock("item"); - $tpl->setVariable("ITEM_TITLE", $item["path"]); - $tpl->parseCurrentBlock(); - } - - if($may_delete_any > 1) - { - $tpl->setCurrentBlock("cbox"); - $tpl->setVariable("ITEM_NAME", "sall_".$a_ref_id); - $tpl->setVariable("ITEM_VALUE", ""); - $tpl->setVariable("ITEM_ADD", " onclick=\"il.Util.setChecked('". - $a_form_name."', '".$var_name."', document.".$a_form_name. - ".sall_".$a_ref_id.".checked)\""); - $tpl->parseCurrentBlock(); - - $tpl->setCurrentBlock("item"); - $tpl->setVariable("ITEM_TITLE", $lng->txt("select_all")); - $tpl->parseCurrentBlock(); - } - } - - if($counter) - { - $tpl->setCurrentBlock("add_info"); - $tpl->setVariable("TXT_ADDITIONAL_INFO", - sprintf($lng->txt("rep_object_references_cannot_be_read"), $counter)); - $tpl->parseCurrentBlock(); - } + $tpl->setVariable("TXT_INTRO", $lng->txt("rep_multiple_reference_deletion_intro")); + + if ($may_delete_any) { + $tpl->setVariable("TXT_INSTRUCTION", $lng->txt("rep_multiple_reference_deletion_instruction")); + } + + if ($items) { + $var_name = "mref_id[]"; + + foreach ($items as $item) { + if ($item["delete"]) { + $tpl->setCurrentBlock("cbox"); + $tpl->setVariable("ITEM_NAME", $var_name); + $tpl->setVariable("ITEM_VALUE", $item["id"]); + $tpl->parseCurrentBlock(); + } else { + $tpl->setCurrentBlock("item_info"); + $tpl->setVariable("TXT_ITEM_INFO", $lng->txt("rep_no_permission_to_delete")); + $tpl->parseCurrentBlock(); + } + + $tpl->setCurrentBlock("item"); + $tpl->setVariable("ITEM_TITLE", $item["path"]); + $tpl->parseCurrentBlock(); + } + + if ($may_delete_any > 1) { + $tpl->setCurrentBlock("cbox"); + $tpl->setVariable("ITEM_NAME", "sall_" . $a_ref_id); + $tpl->setVariable("ITEM_VALUE", ""); + $tpl->setVariable("ITEM_ADD", " onclick=\"il.Util.setChecked('" . + $a_form_name . "', '" . $var_name . "', document." . $a_form_name . + ".sall_" . $a_ref_id . ".checked)\""); + $tpl->parseCurrentBlock(); + + $tpl->setCurrentBlock("item"); + $tpl->setVariable("ITEM_TITLE", $lng->txt("select_all")); + $tpl->parseCurrentBlock(); + } + } + + if ($counter) { + $tpl->setCurrentBlock("add_info"); + $tpl->setVariable( + "TXT_ADDITIONAL_INFO", + sprintf($lng->txt("rep_object_references_cannot_be_read"), $counter) + ); + $tpl->parseCurrentBlock(); + } - return $tpl->get(); - } - } - - /** - * Get trashed objects for a container - * - * @param interger ref id of container - */ - function showTrashTable($a_ref_id) - { - $tpl = $this->tpl; - $tree = $this->tree; - $lng = $this->lng; - - $objects = $tree->getSavedNodeData($a_ref_id); - - if (count($objects) == 0) - { - ilUtil::sendInfo($lng->txt("msg_trash_empty")); - return; - } - include_once("./Services/Repository/classes/class.ilTrashTableGUI.php"); - $ttab = new ilTrashTableGUI($this->parent_gui, "trash"); - $ttab->setData($objects); - - $tpl->setContent($ttab->getHTML()); - } - - /** - * Restore objects from trash - * - * @param integer current ref id - * @param array array of ref ids to be restored - */ - function restoreObjects($a_cur_ref_id, $a_ref_ids) - { - $lng = $this->lng; - - if (!is_array($a_ref_ids) || count($a_ref_ids) == 0) - { - ilUtil::sendFailure($lng->txt("no_checkbox"),true); - return false; - } - else - { - try - { - include_once("./Services/Repository/classes/class.ilRepUtil.php"); - ilRepUtil::restoreObjects($a_cur_ref_id, $a_ref_ids); - ilUtil::sendSuccess($lng->txt("msg_undeleted"),true); - } - catch (Exception $e) - { - ilUtil::sendFailure($e->getMessage(),true); - return false; - } - } - return true; - } - - /** - * Delete objects - */ - function deleteObjects($a_cur_ref_id, $a_ref_ids) - { - $ilSetting = $this->settings; - $lng = $this->lng; - - if (!is_array($a_ref_ids) || count($a_ref_ids) == 0) - { - ilUtil::sendFailure($lng->txt("no_checkbox"), true); - return false; - } - else - { - include_once("./Services/Repository/classes/class.ilRepUtil.php"); - try - { - ilRepUtil::deleteObjects($a_cur_ref_id, $a_ref_ids); - if ($ilSetting->get('enable_trash')) - { - ilUtil::sendSuccess($lng->txt("info_deleted"),true); - } - else - { - ilUtil::sendSuccess($lng->txt("msg_removed"),true); - } - } - catch (Exception $e) - { - ilUtil::sendFailure($e->getMessage(), true); - return false; - } - } - } - - /** - * Remove objects from system - */ - function removeObjectsFromSystem($a_ref_ids, $a_from_recovery_folder = false) - { - $lng = $this->lng; - - if (!is_array($a_ref_ids) || count($a_ref_ids) == 0) - { - ilUtil::sendFailure($lng->txt("no_checkbox"), true); - return false; - } - else - { - include_once("./Services/Repository/classes/class.ilRepUtil.php"); - try - { - ilRepUtil::removeObjectsFromSystem($a_ref_ids, $a_from_recovery_folder); - ilUtil::sendSuccess($lng->txt("msg_removed"),true); - } - catch (Exception $e) - { - ilUtil::sendFailure($e->getMessage(), true); - return false; - } - } + return $tpl->get(); + } + } + + /** + * Get trashed objects for a container + * + * @param interger ref id of container + */ + public function showTrashTable($a_ref_id) + { + $tpl = $this->tpl; + $tree = $this->tree; + $lng = $this->lng; + + $objects = $tree->getSavedNodeData($a_ref_id); + + if (count($objects) == 0) { + ilUtil::sendInfo($lng->txt("msg_trash_empty")); + return; + } + include_once("./Services/Repository/classes/class.ilTrashTableGUI.php"); + $ttab = new ilTrashTableGUI($this->parent_gui, "trash"); + $ttab->setData($objects); + + $tpl->setContent($ttab->getHTML()); + } + + /** + * Restore objects from trash + * + * @param integer current ref id + * @param array array of ref ids to be restored + */ + public function restoreObjects($a_cur_ref_id, $a_ref_ids) + { + $lng = $this->lng; + + if (!is_array($a_ref_ids) || count($a_ref_ids) == 0) { + ilUtil::sendFailure($lng->txt("no_checkbox"), true); + return false; + } else { + try { + include_once("./Services/Repository/classes/class.ilRepUtil.php"); + ilRepUtil::restoreObjects($a_cur_ref_id, $a_ref_ids); + ilUtil::sendSuccess($lng->txt("msg_undeleted"), true); + } catch (Exception $e) { + ilUtil::sendFailure($e->getMessage(), true); + return false; + } + } + return true; + } + + /** + * Delete objects + */ + public function deleteObjects($a_cur_ref_id, $a_ref_ids) + { + $ilSetting = $this->settings; + $lng = $this->lng; + + if (!is_array($a_ref_ids) || count($a_ref_ids) == 0) { + ilUtil::sendFailure($lng->txt("no_checkbox"), true); + return false; + } else { + include_once("./Services/Repository/classes/class.ilRepUtil.php"); + try { + ilRepUtil::deleteObjects($a_cur_ref_id, $a_ref_ids); + if ($ilSetting->get('enable_trash')) { + ilUtil::sendSuccess($lng->txt("info_deleted"), true); + } else { + ilUtil::sendSuccess($lng->txt("msg_removed"), true); + } + } catch (Exception $e) { + ilUtil::sendFailure($e->getMessage(), true); + return false; + } + } + } + + /** + * Remove objects from system + */ + public function removeObjectsFromSystem($a_ref_ids, $a_from_recovery_folder = false) + { + $lng = $this->lng; + + if (!is_array($a_ref_ids) || count($a_ref_ids) == 0) { + ilUtil::sendFailure($lng->txt("no_checkbox"), true); + return false; + } else { + include_once("./Services/Repository/classes/class.ilRepUtil.php"); + try { + ilRepUtil::removeObjectsFromSystem($a_ref_ids, $a_from_recovery_folder); + ilUtil::sendSuccess($lng->txt("msg_removed"), true); + } catch (Exception $e) { + ilUtil::sendFailure($e->getMessage(), true); + return false; + } + } - return true; - } - - /** - * Build path with deep-link - * - * @param array $ref_ids - * @return array - */ - protected function buildPath($ref_ids) - { - $tree = $this->tree; + return true; + } + + /** + * Build path with deep-link + * + * @param array $ref_ids + * @return array + */ + protected function buildPath($ref_ids) + { + $tree = $this->tree; - include_once 'Services/Link/classes/class.ilLink.php'; - - if(!count($ref_ids)) - { - return false; - } - - $result = array(); - foreach($ref_ids as $ref_id) - { - $path = ""; - $path_full = $tree->getPathFull($ref_id); - foreach($path_full as $idx => $data) - { - if($idx) - { - $path .= " » "; - } - if($ref_id != $data['ref_id']) - { - $path .= $data['title']; - } - else - { - $path .= (''. - $data['title'].''); - } - - } + include_once 'Services/Link/classes/class.ilLink.php'; + + if (!count($ref_ids)) { + return false; + } + + $result = array(); + foreach ($ref_ids as $ref_id) { + $path = ""; + $path_full = $tree->getPathFull($ref_id); + foreach ($path_full as $idx => $data) { + if ($idx) { + $path .= " » "; + } + if ($ref_id != $data['ref_id']) { + $path .= $data['title']; + } else { + $path .= ('' . + $data['title'] . ''); + } + } - $result[] = $path; - } - return $result; - } + $result[] = $path; + } + return $result; + } - /** - * Confirmation for trash - * - * @param array $a_ids ref_ids - */ - public function confirmRemoveFromSystemObject($a_ids) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $objDefinition = $this->obj_definition; - $tpl = $this->tpl; - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + /** + * Confirmation for trash + * + * @param array $a_ids ref_ids + */ + public function confirmRemoveFromSystemObject($a_ids) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $objDefinition = $this->obj_definition; + $tpl = $this->tpl; + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - if(!is_array($a_ids)) - { - $a_ids = array($a_ids); - } + if (!is_array($a_ids)) { + $a_ids = array($a_ids); + } - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this->parent_gui)); - $cgui->setCancel($lng->txt("cancel"), "trash"); - $cgui->setConfirm($lng->txt("confirm"), "removeFromSystem"); - $cgui->setFormName("trash_confirmation"); - $cgui->setHeaderText($lng->txt("info_delete_sure")); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this->parent_gui)); + $cgui->setCancel($lng->txt("cancel"), "trash"); + $cgui->setConfirm($lng->txt("confirm"), "removeFromSystem"); + $cgui->setFormName("trash_confirmation"); + $cgui->setHeaderText($lng->txt("info_delete_sure")); - foreach($a_ids as $id) - { - $obj_id = ilObject::_lookupObjId($id); - $type = ilObject::_lookupType($obj_id); - $title = call_user_func(array(ilObjectFactory::getClassByType($type),'_lookupTitle'),$obj_id); - $alt = ($objDefinition->isPlugin($type)) - ? $lng->txt("icon")." ".ilObjectPlugin::lookupTxtById($type, "obj_".$type) - : $lng->txt("icon")." ".$lng->txt("obj_".$type); + foreach ($a_ids as $id) { + $obj_id = ilObject::_lookupObjId($id); + $type = ilObject::_lookupType($obj_id); + $title = call_user_func(array(ilObjectFactory::getClassByType($type),'_lookupTitle'), $obj_id); + $alt = ($objDefinition->isPlugin($type)) + ? $lng->txt("icon") . " " . ilObjectPlugin::lookupTxtById($type, "obj_" . $type) + : $lng->txt("icon") . " " . $lng->txt("obj_" . $type); - $cgui->addItem("trash_id[]", $id, $title, - ilObject::_getIcon($obj_id, "small", $type), - $alt); - } + $cgui->addItem( + "trash_id[]", + $id, + $title, + ilObject::_getIcon($obj_id, "small", $type), + $alt + ); + } - $tpl->setContent($cgui->getHTML()); - } + $tpl->setContent($cgui->getHTML()); + } } -?> \ No newline at end of file diff --git a/Services/Repository/classes/class.ilRepositoryExplorer.php b/Services/Repository/classes/class.ilRepositoryExplorer.php index 8ddf4722f975dad588de83de659f0ea2277639b1..97aba553d06c2891dd0d1d96968aefa1ef3af6fc 100755 --- a/Services/Repository/classes/class.ilRepositoryExplorer.php +++ b/Services/Repository/classes/class.ilRepositoryExplorer.php @@ -13,555 +13,501 @@ require_once("./Services/UIComponent/Explorer/classes/class.ilExplorer.php"); */ class ilRepositoryExplorer extends ilExplorer { - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilSetting - */ - protected $settings; - - /** - * @var ilObjectDefinition - */ - protected $obj_definition; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilDB - */ - protected $db; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilAccessHandler - */ - protected $access; - - - /** - * id of root folder - * @var int root folder id - * @access private - */ - var $root_id; - var $output; - var $ctrl; - /** - * Constructor - * @access public - * @param string scriptname - * @param int user_id - */ - function __construct($a_target, $a_top_node = 0) - { - global $DIC; - - $this->lng = $DIC->language(); - $this->settings = $DIC->settings(); - $this->obj_definition = $DIC["objDefinition"]; - $this->rbacsystem = $DIC->rbac()->system(); - $this->db = $DIC->database(); - $this->user = $DIC->user(); - $this->access = $DIC->access(); - $tree = $DIC->repositoryTree(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilSetting = $DIC->settings(); - $objDefinition = $DIC["objDefinition"]; - - $this->ctrl = $ilCtrl; - - - $this->force_open_path = array(); - - - parent::__construct($a_target); - $this->tree = $tree; - $this->root_id = $this->tree->readRootId(); - $this->order_column = "title"; - $this->setSessionExpandVariable("repexpand"); - $this->setTitle($lng->txt("overview")); - - // please do not uncomment this - if ($ilSetting->get("repository_tree_pres") == "" || - ($ilSetting->get("rep_tree_limit_grp_crs") && $a_top_node == 0)) - { - foreach($objDefinition->getExplorerContainerTypes() as $type) - { - $this->addFilter($type); - } - $this->setFiltered(true); - $this->setFilterMode(IL_FM_POSITIVE); - } - else if ($ilSetting->get("repository_tree_pres") == "all_types") - { - foreach ($objDefinition->getAllRBACObjects() as $rtype) - { - $this->addFilter($rtype); - } - $this->setFiltered(true); - $this->setFilterMode(IL_FM_POSITIVE); - } - } - - /** - * set force open path - */ - function setForceOpenPath($a_path) - { - $this->force_open_path = $a_path; - } - - /** - * note: most of this stuff is used by ilCourseContentInterface too - */ - function buildLinkTarget($a_node_id, $a_type) - { - $ilCtrl = $this->ctrl; - - switch($a_type) - { - case "cat": - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $a_node_id); - $link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", ""); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - return $link; - - case "catr": - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $a_node_id); - $link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", "redirect"); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - return $link; - - case "grp": - $ilCtrl->setParameterByClass("ilobjgroupgui", "ref_id", $a_node_id); - $link = $ilCtrl->getLinkTargetByClass(array("ilrepositorygui", "ilobjgroupgui"), ""); - $ilCtrl->setParameterByClass("ilobjgroupgui", "ref_id", $_GET["ref_id"]); - return $link; - case "grpr": - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $a_node_id); - $link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", "redirect"); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - return $link; - - case "crs": - $ilCtrl->setParameterByClass("ilobjcoursegui", "ref_id", $a_node_id); - $link = $ilCtrl->getLinkTargetByClass(array("ilrepositorygui", "ilobjcoursegui"), "view"); - $ilCtrl->setParameterByClass("ilobjcoursegui", "ref_id", $_GET["ref_id"]); - return $link; - - case "crsr": - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $a_node_id); - $link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", "redirect"); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - return $link; - - case 'rcrs': - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $a_node_id); - $link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", "infoScreen"); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - return $link; - - case 'prg': - $ilCtrl->setParameterByClass("ilobjstudyprogrammegui", "ref_id", $a_node_id); - $link = $ilCtrl->getLinkTargetByClass("ilobjstudyprogrammegui", "view"); - $ilCtrl->setParameterByClass("ilobjstudyprogrammegui", "ref_id", $_GET["ref_id"]); - return $link; - - default: - include_once('./Services/Link/classes/class.ilLink.php'); - return ilLink::_getStaticLink($a_node_id, $a_type, true); - - } - } - - /** - * - * STATIC, do not use $this inside! - * - * Note: this is used by course interface !? - */ - function buildFrameTarget($a_type, $a_child = 0, $a_obj_id = 0) - { - switch($a_type) - { - case "cat": - $t_frame = ilFrameTargetInfo::_getFrame("RepositoryContent", "cat"); - return $t_frame; - - case "catr": - $t_frame = ilFrameTargetInfo::_getFrame("RepositoryContent", "catr"); - return $t_frame; - - case "grp": - $t_frame = ilFrameTargetInfo::_getFrame("RepositoryContent", "grp"); - return $t_frame; - - case "grpr": - $t_frame = ilFrameTargetInfo::_getFrame("RepositoryContent", "grpr"); - return $t_frame; - - case "crs": - $t_frame = ilFrameTargetInfo::_getFrame("RepositoryContent", "crs"); - return $t_frame; - - case "crsr": - $t_frame = ilFrameTargetInfo::_getFrame("RepositoryContent", "crsr"); - return $t_frame; - - case 'rcrs': - $t_frame = ilFrameTargetInfo::_getFrame("RepositoryContent",'rcrs'); - return $t_frame; - - case 'prg': - $t_frame = ilFrameTargetInfo::_getFrame("RepositoryContent",'prg'); - return $t_frame; - - default: - return "_top"; - } - } - - /** - * get image path - */ - function getImage($a_name, $a_type = "", $a_obj_id = "") - { - if ($a_type != "") - { - return ilObject::_getIcon($a_obj_id, "tiny", $a_type); - } - - return parent::getImage($a_name); - } - - function isClickable($a_type, $a_ref_id = 0,$a_obj_id = 0) - { - $rbacsystem = $this->rbacsystem; - $tree = $this->tree; - $ilDB = $this->db; - $ilUser = $this->user; - $ilAccess = $this->access; - - if(!ilConditionHandler::_checkAllConditionsOfTarget($a_ref_id,$a_obj_id)) - { - return false; - } - - switch ($a_type) - { - case 'tst': - if(!$rbacsystem->checkAccess("read", $a_ref_id)) - { - return false; - } - - $query = sprintf("SELECT * FROM tst_tests WHERE obj_fi=%s",$a_obj_id); - $res = $ilDB->query($query); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - return (bool) $row->complete; - } - return false; - - case 'svy': - if(!$rbacsystem->checkAccess("read", $a_ref_id)) - { - return false; - } - - $query = sprintf("SELECT * FROM svy_svy WHERE obj_fi=%s",$a_obj_id); - $res = $ilDB->query($query); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - return (bool) $row->complete; - } - return false; - - // media pools can only be edited - case "mep": - if ($rbacsystem->checkAccess("read", $a_ref_id)) - { - return true; - } - else - { - return false; - } - break; - case 'grpr': - case 'crsr': - case 'catr': - include_once('./Services/ContainerReference/classes/class.ilContainerReferenceAccess.php'); - return ilContainerReferenceAccess::_isAccessible($a_ref_id); - case 'prg': - return $rbacsystem->checkAccess("visible", $a_ref_id); - - - - // all other types are only clickable, if read permission is given - default: - if ($rbacsystem->checkAccess("read", $a_ref_id)) - { - // check if lm is online - if ($a_type == "lm") - { - include_once("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); - $lm_obj = new ilObjLearningModule($a_ref_id); - if(($lm_obj->getOfflineStatus()) && (!$rbacsystem->checkAccess('write',$a_ref_id))) - { - return false; - } - } - // check if fblm is online - if ($a_type == "htlm") - { - include_once("./Modules/HTMLLearningModule/classes/class.ilObjFileBasedLM.php"); - $lm_obj = new ilObjFileBasedLM($a_ref_id); - if(($lm_obj->getOfflineStatus()) && (!$rbacsystem->checkAccess('write',$a_ref_id))) - { - return false; - } - } - // check if fblm is online - if ($a_type == "sahs") - { - include_once("./Modules/ScormAicc/classes/class.ilObjSAHSLearningModule.php"); - $lm_obj = new ilObjSAHSLearningModule($a_ref_id); - if(($lm_obj->getOfflineStatus()) && (!$rbacsystem->checkAccess('write',$a_ref_id))) - { - return false; - } - } - // check if glossary is online - if ($a_type == "glo") - { - $obj_id = ilObject::_lookupObjectId($a_ref_id); - include_once("./Modules/Glossary/classes/class.ilObjGlossary.php"); - if((!ilObjGlossary::_lookupOnline($obj_id)) && - (!$rbacsystem->checkAccess('write',$a_ref_id))) - { - return false; - } - } - - return true; - } - else - { - return false; - } - break; - } - } - - function showChilds($a_ref_id,$a_obj_id = 0) - { - $rbacsystem = $this->rbacsystem; - $tree = $this->tree; -//vd($a_ref_id); - - if ($a_ref_id == 0) - { - return true; - } - if(!ilConditionHandler::_checkAllConditionsOfTarget($a_ref_id,$a_obj_id)) - { - return false; - } - if ($rbacsystem->checkAccess("read", $a_ref_id)) - { - return true; - } - else - { - return false; - } - } - - function isVisible($a_ref_id,$a_type) - { - $ilAccess = $this->access; - $tree = $this->tree; - $ilSetting = $this->settings; - - if(!$ilAccess->checkAccess('visible', '', $a_ref_id)) - { - return false; - } - - $is_course = false; - $container_parent_id = $tree->checkForParentType($a_ref_id,'grp'); - if(!$container_parent_id) - { - $is_course = true; - $container_parent_id = $tree->checkForParentType($a_ref_id,'crs'); - } - if($container_parent_id) - { - // do not display session materials for container course/group - if($ilSetting->get("repository_tree_pres") == "all_types" && $container_parent_id != $a_ref_id) - { - // get container event items only once - if(!isset($this->session_materials[$container_parent_id])) - { - include_once './Modules/Session/classes/class.ilEventItems.php'; - $this->session_materials[$container_parent_id] = ilEventItems::_getItemsOfContainer($container_parent_id); - } - // get item group items only once - if(!isset($this->item_group_items[$container_parent_id])) - { - include_once './Modules/ItemGroup/classes/class.ilItemGroupItems.php'; - $this->item_group_items[$container_parent_id] = ilItemGroupItems::_getItemsOfContainer($container_parent_id); - } - if(in_array($a_ref_id, $this->session_materials[$container_parent_id])) - { - return false; - } - if(in_array($a_ref_id, $this->item_group_items[$container_parent_id])) - { - return false; - } - } - } - - return true; - } - - - - /** - * overwritten method from base class - * @access public - * @param integer obj_id - * @param integer array options - * @return string - */ - function formatHeader($tpl, $a_obj_id,$a_option) - { - $lng = $this->lng; - $tree = $this->tree; - $ilCtrl = $this->ctrl; - - // custom icons - $path = ilObject::_getIcon($a_obj_id, "tiny", "root"); - - $tpl->setCurrentBlock("icon"); - $nd = $tree->getNodeData(ROOT_FOLDER_ID); - $title = $nd["title"]; - if ($title == "ILIAS") - { - $title = $lng->txt("repository"); - } - - $tpl->setVariable("ICON_IMAGE", $path); - $tpl->setVariable("TXT_ALT_IMG", $lng->txt("icon")." ".$title); - $tpl->parseCurrentBlock(); - - $tpl->setCurrentBlock("link"); - $tpl->setVariable("TITLE", $title); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", "1"); - $tpl->setVariable("LINK_TARGET", - $ilCtrl->getLinkTargetByClass("ilrepositorygui", "frameset")); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - $tpl->setVariable("TARGET", " target=\"_top\""); - $tpl->parseCurrentBlock(); - - $tpl->setCurrentBlock("element"); - $tpl->parseCurrentBlock(); - } - - /** - * sort nodes - * - * @access public - * @param - * @return - */ - public function sortNodes($a_nodes,$a_parent_obj_id) - { - $objDefinition = $this->obj_definition; - - if ($a_parent_obj_id > 0) - { - $parent_type = ilObject::_lookupType($a_parent_obj_id); - } - else - { - $parent_type = "dummy"; - $this->type_grps["dummy"] = array("root" => "dummy"); - } - - if (empty($this->type_grps[$parent_type])) - { - $this->type_grps[$parent_type] = - $objDefinition->getGroupedRepositoryObjectTypes($parent_type); - } - $group = array(); - - foreach ($a_nodes as $node) - { - $g = $objDefinition->getGroupOfObj($node["type"]); - if ($g == "") - { - $g = $node["type"]; - } - $group[$g][] = $node; - } - - $nodes = array(); - foreach ($this->type_grps[$parent_type] as $t => $g) - { - if (is_array($group[$t])) - { - // do we have to sort this group?? - include_once("./Services/Container/classes/class.ilContainer.php"); - include_once("./Services/Container/classes/class.ilContainerSorting.php"); - $sort = ilContainerSorting::_getInstance($a_parent_obj_id); - $group = $sort->sortItems($group); - - // need extra session sorting here - if ($t == "sess") - { - - } - - foreach ($group[$t] as $k => $item) - { - $nodes[] = $item; - } - } - } - - return $nodes; - //return parent::sortNodes($a_nodes,$a_parent_obj_id); - } - - /** - * Force expansion of node - * - * @param - * @return - */ - function forceExpanded($a_node) - { - if (in_array($a_node, $this->force_open_path)) - { - return true; - } - return false; - } - + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var ilObjectDefinition + */ + protected $obj_definition; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilDB + */ + protected $db; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilAccessHandler + */ + protected $access; + + + /** + * id of root folder + * @var int root folder id + * @access private + */ + public $root_id; + public $output; + public $ctrl; + /** + * Constructor + * @access public + * @param string scriptname + * @param int user_id + */ + public function __construct($a_target, $a_top_node = 0) + { + global $DIC; + + $this->lng = $DIC->language(); + $this->settings = $DIC->settings(); + $this->obj_definition = $DIC["objDefinition"]; + $this->rbacsystem = $DIC->rbac()->system(); + $this->db = $DIC->database(); + $this->user = $DIC->user(); + $this->access = $DIC->access(); + $tree = $DIC->repositoryTree(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilSetting = $DIC->settings(); + $objDefinition = $DIC["objDefinition"]; + + $this->ctrl = $ilCtrl; + + + $this->force_open_path = array(); + + + parent::__construct($a_target); + $this->tree = $tree; + $this->root_id = $this->tree->readRootId(); + $this->order_column = "title"; + $this->setSessionExpandVariable("repexpand"); + $this->setTitle($lng->txt("overview")); + + // please do not uncomment this + if ($ilSetting->get("repository_tree_pres") == "" || + ($ilSetting->get("rep_tree_limit_grp_crs") && $a_top_node == 0)) { + foreach ($objDefinition->getExplorerContainerTypes() as $type) { + $this->addFilter($type); + } + $this->setFiltered(true); + $this->setFilterMode(IL_FM_POSITIVE); + } elseif ($ilSetting->get("repository_tree_pres") == "all_types") { + foreach ($objDefinition->getAllRBACObjects() as $rtype) { + $this->addFilter($rtype); + } + $this->setFiltered(true); + $this->setFilterMode(IL_FM_POSITIVE); + } + } + + /** + * set force open path + */ + public function setForceOpenPath($a_path) + { + $this->force_open_path = $a_path; + } + + /** + * note: most of this stuff is used by ilCourseContentInterface too + */ + public function buildLinkTarget($a_node_id, $a_type) + { + $ilCtrl = $this->ctrl; + + switch ($a_type) { + case "cat": + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $a_node_id); + $link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", ""); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + return $link; + + case "catr": + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $a_node_id); + $link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", "redirect"); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + return $link; + + case "grp": + $ilCtrl->setParameterByClass("ilobjgroupgui", "ref_id", $a_node_id); + $link = $ilCtrl->getLinkTargetByClass(array("ilrepositorygui", "ilobjgroupgui"), ""); + $ilCtrl->setParameterByClass("ilobjgroupgui", "ref_id", $_GET["ref_id"]); + return $link; + case "grpr": + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $a_node_id); + $link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", "redirect"); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + return $link; + + case "crs": + $ilCtrl->setParameterByClass("ilobjcoursegui", "ref_id", $a_node_id); + $link = $ilCtrl->getLinkTargetByClass(array("ilrepositorygui", "ilobjcoursegui"), "view"); + $ilCtrl->setParameterByClass("ilobjcoursegui", "ref_id", $_GET["ref_id"]); + return $link; + + case "crsr": + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $a_node_id); + $link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", "redirect"); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + return $link; + + case 'rcrs': + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $a_node_id); + $link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", "infoScreen"); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + return $link; + + case 'prg': + $ilCtrl->setParameterByClass("ilobjstudyprogrammegui", "ref_id", $a_node_id); + $link = $ilCtrl->getLinkTargetByClass("ilobjstudyprogrammegui", "view"); + $ilCtrl->setParameterByClass("ilobjstudyprogrammegui", "ref_id", $_GET["ref_id"]); + return $link; + + default: + include_once('./Services/Link/classes/class.ilLink.php'); + return ilLink::_getStaticLink($a_node_id, $a_type, true); + + } + } + + /** + * + * STATIC, do not use $this inside! + * + * Note: this is used by course interface !? + */ + public function buildFrameTarget($a_type, $a_child = 0, $a_obj_id = 0) + { + switch ($a_type) { + case "cat": + $t_frame = ilFrameTargetInfo::_getFrame("RepositoryContent", "cat"); + return $t_frame; + + case "catr": + $t_frame = ilFrameTargetInfo::_getFrame("RepositoryContent", "catr"); + return $t_frame; + + case "grp": + $t_frame = ilFrameTargetInfo::_getFrame("RepositoryContent", "grp"); + return $t_frame; + + case "grpr": + $t_frame = ilFrameTargetInfo::_getFrame("RepositoryContent", "grpr"); + return $t_frame; + + case "crs": + $t_frame = ilFrameTargetInfo::_getFrame("RepositoryContent", "crs"); + return $t_frame; + + case "crsr": + $t_frame = ilFrameTargetInfo::_getFrame("RepositoryContent", "crsr"); + return $t_frame; + + case 'rcrs': + $t_frame = ilFrameTargetInfo::_getFrame("RepositoryContent", 'rcrs'); + return $t_frame; + + case 'prg': + $t_frame = ilFrameTargetInfo::_getFrame("RepositoryContent", 'prg'); + return $t_frame; + + default: + return "_top"; + } + } + + /** + * get image path + */ + public function getImage($a_name, $a_type = "", $a_obj_id = "") + { + if ($a_type != "") { + return ilObject::_getIcon($a_obj_id, "tiny", $a_type); + } + + return parent::getImage($a_name); + } + + public function isClickable($a_type, $a_ref_id = 0, $a_obj_id = 0) + { + $rbacsystem = $this->rbacsystem; + $tree = $this->tree; + $ilDB = $this->db; + $ilUser = $this->user; + $ilAccess = $this->access; + + if (!ilConditionHandler::_checkAllConditionsOfTarget($a_ref_id, $a_obj_id)) { + return false; + } + + switch ($a_type) { + case 'tst': + if (!$rbacsystem->checkAccess("read", $a_ref_id)) { + return false; + } + + $query = sprintf("SELECT * FROM tst_tests WHERE obj_fi=%s", $a_obj_id); + $res = $ilDB->query($query); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + return (bool) $row->complete; + } + return false; + + case 'svy': + if (!$rbacsystem->checkAccess("read", $a_ref_id)) { + return false; + } + + $query = sprintf("SELECT * FROM svy_svy WHERE obj_fi=%s", $a_obj_id); + $res = $ilDB->query($query); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + return (bool) $row->complete; + } + return false; + + // media pools can only be edited + case "mep": + if ($rbacsystem->checkAccess("read", $a_ref_id)) { + return true; + } else { + return false; + } + break; + case 'grpr': + case 'crsr': + case 'catr': + include_once('./Services/ContainerReference/classes/class.ilContainerReferenceAccess.php'); + return ilContainerReferenceAccess::_isAccessible($a_ref_id); + case 'prg': + return $rbacsystem->checkAccess("visible", $a_ref_id); + + + + // all other types are only clickable, if read permission is given + default: + if ($rbacsystem->checkAccess("read", $a_ref_id)) { + // check if lm is online + if ($a_type == "lm") { + include_once("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); + $lm_obj = new ilObjLearningModule($a_ref_id); + if (($lm_obj->getOfflineStatus()) && (!$rbacsystem->checkAccess('write', $a_ref_id))) { + return false; + } + } + // check if fblm is online + if ($a_type == "htlm") { + include_once("./Modules/HTMLLearningModule/classes/class.ilObjFileBasedLM.php"); + $lm_obj = new ilObjFileBasedLM($a_ref_id); + if (($lm_obj->getOfflineStatus()) && (!$rbacsystem->checkAccess('write', $a_ref_id))) { + return false; + } + } + // check if fblm is online + if ($a_type == "sahs") { + include_once("./Modules/ScormAicc/classes/class.ilObjSAHSLearningModule.php"); + $lm_obj = new ilObjSAHSLearningModule($a_ref_id); + if (($lm_obj->getOfflineStatus()) && (!$rbacsystem->checkAccess('write', $a_ref_id))) { + return false; + } + } + // check if glossary is online + if ($a_type == "glo") { + $obj_id = ilObject::_lookupObjectId($a_ref_id); + include_once("./Modules/Glossary/classes/class.ilObjGlossary.php"); + if ((!ilObjGlossary::_lookupOnline($obj_id)) && + (!$rbacsystem->checkAccess('write', $a_ref_id))) { + return false; + } + } + + return true; + } else { + return false; + } + break; + } + } + + public function showChilds($a_ref_id, $a_obj_id = 0) + { + $rbacsystem = $this->rbacsystem; + $tree = $this->tree; + //vd($a_ref_id); + + if ($a_ref_id == 0) { + return true; + } + if (!ilConditionHandler::_checkAllConditionsOfTarget($a_ref_id, $a_obj_id)) { + return false; + } + if ($rbacsystem->checkAccess("read", $a_ref_id)) { + return true; + } else { + return false; + } + } + + public function isVisible($a_ref_id, $a_type) + { + $ilAccess = $this->access; + $tree = $this->tree; + $ilSetting = $this->settings; + + if (!$ilAccess->checkAccess('visible', '', $a_ref_id)) { + return false; + } + + $is_course = false; + $container_parent_id = $tree->checkForParentType($a_ref_id, 'grp'); + if (!$container_parent_id) { + $is_course = true; + $container_parent_id = $tree->checkForParentType($a_ref_id, 'crs'); + } + if ($container_parent_id) { + // do not display session materials for container course/group + if ($ilSetting->get("repository_tree_pres") == "all_types" && $container_parent_id != $a_ref_id) { + // get container event items only once + if (!isset($this->session_materials[$container_parent_id])) { + include_once './Modules/Session/classes/class.ilEventItems.php'; + $this->session_materials[$container_parent_id] = ilEventItems::_getItemsOfContainer($container_parent_id); + } + // get item group items only once + if (!isset($this->item_group_items[$container_parent_id])) { + include_once './Modules/ItemGroup/classes/class.ilItemGroupItems.php'; + $this->item_group_items[$container_parent_id] = ilItemGroupItems::_getItemsOfContainer($container_parent_id); + } + if (in_array($a_ref_id, $this->session_materials[$container_parent_id])) { + return false; + } + if (in_array($a_ref_id, $this->item_group_items[$container_parent_id])) { + return false; + } + } + } + + return true; + } + + + + /** + * overwritten method from base class + * @access public + * @param integer obj_id + * @param integer array options + * @return string + */ + public function formatHeader($tpl, $a_obj_id, $a_option) + { + $lng = $this->lng; + $tree = $this->tree; + $ilCtrl = $this->ctrl; + + // custom icons + $path = ilObject::_getIcon($a_obj_id, "tiny", "root"); + + $tpl->setCurrentBlock("icon"); + $nd = $tree->getNodeData(ROOT_FOLDER_ID); + $title = $nd["title"]; + if ($title == "ILIAS") { + $title = $lng->txt("repository"); + } + + $tpl->setVariable("ICON_IMAGE", $path); + $tpl->setVariable("TXT_ALT_IMG", $lng->txt("icon") . " " . $title); + $tpl->parseCurrentBlock(); + + $tpl->setCurrentBlock("link"); + $tpl->setVariable("TITLE", $title); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", "1"); + $tpl->setVariable( + "LINK_TARGET", + $ilCtrl->getLinkTargetByClass("ilrepositorygui", "frameset") + ); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + $tpl->setVariable("TARGET", " target=\"_top\""); + $tpl->parseCurrentBlock(); + + $tpl->setCurrentBlock("element"); + $tpl->parseCurrentBlock(); + } + + /** + * sort nodes + * + * @access public + * @param + * @return + */ + public function sortNodes($a_nodes, $a_parent_obj_id) + { + $objDefinition = $this->obj_definition; + + if ($a_parent_obj_id > 0) { + $parent_type = ilObject::_lookupType($a_parent_obj_id); + } else { + $parent_type = "dummy"; + $this->type_grps["dummy"] = array("root" => "dummy"); + } + + if (empty($this->type_grps[$parent_type])) { + $this->type_grps[$parent_type] = + $objDefinition->getGroupedRepositoryObjectTypes($parent_type); + } + $group = array(); + + foreach ($a_nodes as $node) { + $g = $objDefinition->getGroupOfObj($node["type"]); + if ($g == "") { + $g = $node["type"]; + } + $group[$g][] = $node; + } + + $nodes = array(); + foreach ($this->type_grps[$parent_type] as $t => $g) { + if (is_array($group[$t])) { + // do we have to sort this group?? + include_once("./Services/Container/classes/class.ilContainer.php"); + include_once("./Services/Container/classes/class.ilContainerSorting.php"); + $sort = ilContainerSorting::_getInstance($a_parent_obj_id); + $group = $sort->sortItems($group); + + // need extra session sorting here + if ($t == "sess") { + } + + foreach ($group[$t] as $k => $item) { + $nodes[] = $item; + } + } + } + + return $nodes; + //return parent::sortNodes($a_nodes,$a_parent_obj_id); + } + + /** + * Force expansion of node + * + * @param + * @return + */ + public function forceExpanded($a_node) + { + if (in_array($a_node, $this->force_open_path)) { + return true; + } + return false; + } } // END class ilRepositoryExplorer -?> diff --git a/Services/Repository/classes/class.ilRepositoryExplorerGUI.php b/Services/Repository/classes/class.ilRepositoryExplorerGUI.php index 255d4e89aa81413a237c34cb1855f632f65900b7..3e969ca72c4b803774f88c0a6491baadd335444b 100644 --- a/Services/Repository/classes/class.ilRepositoryExplorerGUI.php +++ b/Services/Repository/classes/class.ilRepositoryExplorerGUI.php @@ -15,713 +15,633 @@ include_once("./Services/UIComponent/Explorer2/classes/class.ilTreeExplorerGUI.p */ class ilRepositoryExplorerGUI extends ilTreeExplorerGUI { - /** - * @var ilSetting - */ - protected $settings; - - /** - * @var ilObjectDefinition - */ - protected $obj_definition; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilDB - */ - protected $db; - - /** - * @var ilObjUser - */ - protected $user; - - protected $type_grps = array(); - protected $session_materials = array(); - - protected $parent_node_id = []; - protected $node_data = []; - - /** - * Constructor - */ - public function __construct($a_parent_obj, $a_parent_cmd) - { - global $DIC; - - $this->tree = $DIC->repositoryTree(); - $this->settings = $DIC->settings(); - $this->obj_definition = $DIC["objDefinition"]; - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $this->access = $DIC->access(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->db = $DIC->database(); - $this->user = $DIC->user(); - $tree = $DIC->repositoryTree(); - $ilSetting = $DIC->settings(); - $objDefinition = $DIC["objDefinition"]; - - $this->cur_ref_id = (int) $_GET["ref_id"]; - - $this->top_node_id = 0; - if ($ilSetting->get("rep_tree_limit_grp_crs") && $this->cur_ref_id > 0) - { - $path = $tree->getPathId($this->cur_ref_id); - foreach ($path as $n) - { - if ($top_node > 0) - { - break; - } - if (in_array(ilObject::_lookupType(ilObject::_lookupObjId($n)), - array("crs", "grp"))) - { - $this->top_node_id = $n; - } - } - - } - - parent::__construct("rep_exp", $a_parent_obj, $a_parent_cmd, $tree); - - $this->setSkipRootNode(false); - $this->setAjax(true); - $this->setOrderField("title"); - if ($ilSetting->get("repository_tree_pres") == "" || - ($ilSetting->get("rep_tree_limit_grp_crs") && $this->top_node_id == 0)) - { - $this->setTypeWhiteList($objDefinition->getExplorerContainerTypes()); - } - else if ($ilSetting->get("repository_tree_pres") == "all_types") - { - $white = array(); - foreach ($objDefinition->getSubObjectsRecursively("root") as $rtype) - { - if (/* $rtype["name"] != "itgr" && */ !$objDefinition->isSideBlock($rtype["name"])) - { - $white[] = $rtype["name"]; - } - } - $this->setTypeWhiteList($white); - } - if ((int) $_GET["ref_id"] > 0) - { - $this->setPathOpen((int) $_GET["ref_id"]); - } - - $this->setChildLimit((int) $ilSetting->get("rep_tree_limit_number")); - } - - /** - * Get root node - * - * @param - * @return - */ - function getRootNode() - { - if ($this->top_node_id > 0) - { - $root_node = $this->getTree()->getNodeData($this->top_node_id); - } - else - { - $root_node = parent::getRootNode(); - } - $this->node_data[$root_node["child"]] = $root_node; - return $root_node; - } - - /** - * Get node content - * - * @param array - * @return - */ - function getNodeContent($a_node) - { - $lng = $this->lng; - - $title = $a_node["title"]; - - if ($a_node["child"] == $this->getNodeId($this->getRootNode())) - { - if ($title == "ILIAS") - { - $title = $lng->txt("repository"); - } - } - else if($a_node["type"] == "sess" && - !trim($title)) - { - // #14367 - see ilObjSessionListGUI - include_once('./Modules/Session/classes/class.ilSessionAppointment.php'); - $app_info = ilSessionAppointment::_lookupAppointment($a_node["obj_id"]); - $title = ilSessionAppointment::_appointmentToString($app_info['start'], $app_info['end'],$app_info['fullday']); - } - - return $title; - } - - /** - * Get node icon - * - * @param array - * @return - */ - function getNodeIcon($a_node) - { - $obj_id = ilObject::_lookupObjId($a_node["child"]); - return ilObject::_getIcon($obj_id, "tiny", $a_node["type"]); - } - - /** - * Get node icon alt text - * - * @param array node array - * @return string alt text - */ - function getNodeIconAlt($a_node) - { - $lng = $this->lng; - - if ($a_node["child"] == $this->getNodeId($this->getRootNode())) - { - $title = $a_node["title"]; - if ($title == "ILIAS") - { - $title = $lng->txt("repository"); - } - return $lng->txt("icon")." ".$title; - } - - - return parent::getNodeIconAlt($a_node); - } - - /** - * Is node highlighted? - * - * @param mixed $a_node node object/array - * @return boolean node visible true/false - */ - function isNodeHighlighted($a_node) - { - if ($a_node["child"] == $_GET["ref_id"] || - ($_GET["ref_id"] == "" && $a_node["child"] == $this->getNodeId($this->getRootNode()))) - { - return true; - } - return false; - } - - /** - * Get href for node - * - * @param mixed $a_node node object/array - * @return string href attribute - */ - function getNodeHref($a_node) - { - $ilCtrl = $this->ctrl; - - switch($a_node["type"]) - { - case "root": - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $a_node["child"]); - $link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", ""); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - return $link; - - case "cat": - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $a_node["child"]); - $link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", ""); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - return $link; - - case "catr": - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $a_node["child"]); - $link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", "redirect"); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - return $link; - - case "grp": - $ilCtrl->setParameterByClass("ilobjgroupgui", "ref_id", $a_node["child"]); - $link = $ilCtrl->getLinkTargetByClass(array("ilrepositorygui", "ilobjgroupgui"), ""); - $ilCtrl->setParameterByClass("ilobjgroupgui", "ref_id", $_GET["ref_id"]); - return $link; - - case "grpr": - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $a_node["child"]); - $link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", "redirect"); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - return $link; - - case "crs": - $ilCtrl->setParameterByClass("ilobjcoursegui", "ref_id", $a_node["child"]); - $link = $ilCtrl->getLinkTargetByClass(array("ilrepositorygui", "ilobjcoursegui"), "view"); - $ilCtrl->setParameterByClass("ilobjcoursegui", "ref_id", $_GET["ref_id"]); - return $link; - - case "crsr": - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $a_node["child"]); - $link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", "redirect"); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - return $link; - - case 'rcrs': - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $a_node["child"]); - $link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", "infoScreen"); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - return $link; - - case 'prg': - $ilCtrl->setParameterByClass("ilobjstudyprogrammegui", "ref_id", $a_node["child"]); - $link = $ilCtrl->getLinkTargetByClass(array("ilrepositorygui", "ilobjstudyprogrammegui"), "view"); - $ilCtrl->setParameterByClass("ilobjstudyprogrammegui", "ref_id", $_GET["ref_id"]); - return $link; - - default: - include_once('./Services/Link/classes/class.ilLink.php'); - return ilLink::_getStaticLink($a_node["child"], $a_node["type"], true); - - } - } - - /** - * Is node visible - * - * @param - * @return - */ - function isNodeVisible($a_node) - { - $ilAccess = $this->access; - $tree = $this->tree; - $ilSetting = $this->settings; - - if (!$ilAccess->checkAccess('visible', '', $a_node["child"])) - { - return false; - } - - if ($ilSetting->get("repository_tree_pres") == "all_types") { - /*$container_parent_id = $tree->checkForParentType($a_node["child"], 'grp'); - if (!$container_parent_id) { - $container_parent_id = $tree->checkForParentType($a_node["child"], 'crs'); - }*/ - // see #21215 - $container_parent_id = $this->getParentCourseOrGroup($a_node["child"]); - if ($container_parent_id > 0) { - // do not display session materials for container course/group - if ($container_parent_id != $a_node["child"]) { - // get container event items only once - if (!isset($this->session_materials[$container_parent_id])) { - include_once './Modules/Session/classes/class.ilEventItems.php'; - $this->session_materials[$container_parent_id] = ilEventItems::_getItemsOfContainer($container_parent_id); - } - if (in_array($a_node["child"], $this->session_materials[$container_parent_id])) { - return false; - } - } - } - } - - return true; - } - - /** - * Get upper course or group - * - * @param int $node_id - * @return int - */ - protected function getParentCourseOrGroup($node_id) - { - $current_node_id = $node_id; - while (isset($this->parent_node_id[$current_node_id])) { - $parent_node_id = $this->parent_node_id[$current_node_id]; - if (isset($this->node_data[$parent_node_id]) && in_array($this->node_data[$parent_node_id]["type"], ["grp", "crs"])) { - return $parent_node_id; - } - $current_node_id = $parent_node_id; - } - return 0; - } - - - /** - * Sort childs - * - * @param array $a_childs array of child nodes - * @param mixed $a_parent_node parent node - * - * @return array array of childs nodes - */ - function sortChilds($a_childs, $a_parent_node_id) - { - $objDefinition = $this->obj_definition; - $ilAccess = $this->access; - - $parent_obj_id = ilObject::_lookupObjId($a_parent_node_id); - if ($parent_obj_id > 0) - { - $parent_type = ilObject::_lookupType($parent_obj_id); - } - else - { - $parent_type = "dummy"; - $this->type_grps["dummy"] = array("root" => "dummy"); - } - - // alex: if this is not initialized, things are messed up - // see bug 0015978 - $this->type_grps = array(); - - if (empty($this->type_grps[$parent_type])) - { - $this->type_grps[$parent_type] = - $objDefinition->getGroupedRepositoryObjectTypes($parent_type); - } - - // #14465 - item groups - include_once('./Services/Object/classes/class.ilObjectActivation.php'); - $group = array(); - $igroup = array(); // used for item groups, see bug #0015978 - $in_any_group = array(); - foreach ($a_childs as $child) - { - // item group: get childs - if ($child["type"] == "itgr") - { - $g = $child["child"]; - $items = ilObjectActivation::getItemsByItemGroup($g); - if ($items) - { - // add item group ref id to item group block - $this->type_grps[$parent_type]["itgr"]["ref_ids"][] = $g; - - // #16697 - check item group permissions - $may_read = $ilAccess->checkAccess('read', '', $g); - - // see bug #0015978 - if ($may_read) - { - include_once("./Services/Container/classes/class.ilContainerSorting.php"); - $items = ilContainerSorting::_getInstance($parent_obj_id)->sortSubItems('itgr', $child["obj_id"], $items); - } - - foreach($items as $item) - { - $in_any_group[] = $item["child"]; - - if ($may_read) - { - $igroup[$g][] = $item; - $group[$g][] = $item; - } - } - } - } - // type group - else - { - $g = $objDefinition->getGroupOfObj($child["type"]); - if ($g == "") - { - $g = $child["type"]; - } - $group[$g][] = $child; - } - } - - $in_any_group = array_unique($in_any_group); - - // custom block sorting? - include_once("./Services/Container/classes/class.ilContainerSorting.php"); - $sort = ilContainerSorting::_getInstance($parent_obj_id); - $block_pos = $sort->getBlockPositions(); - if (is_array($block_pos) && count($block_pos) > 0) - { - $tmp = $this->type_grps[$parent_type]; - - $this->type_grps[$parent_type] = array(); - foreach ($block_pos as $block_type) - { - // type group - if (!is_numeric($block_type) && - array_key_exists($block_type, $tmp)) - { - $this->type_grps[$parent_type][$block_type] = $tmp[$block_type]; - unset($tmp[$block_type]); - } - // item group - else - { - // using item group ref id directly - $this->type_grps[$parent_type][$block_type] = array(); - } - } - - // append missing - if (sizeof($tmp)) - { - foreach ($tmp as $block_type => $grp) - { - $this->type_grps[$parent_type][$block_type] = $grp; - } - } - - unset($tmp); - } - - $childs = array(); - $done = array(); - - foreach ($this->type_grps[$parent_type] as $t => $g) - { - // type group - if (is_array($group[$t])) - { - // see bug #0015978 - // custom sorted igroups - if (is_array($igroup[$t])) - { - foreach ($igroup[$t] as $k => $item) - { - if (!in_array($item["child"], $done)) - { - $childs[] = $item; - $done[] = $item["child"]; - } - } - } - else - { - // do we have to sort this group?? - include_once("./Services/Container/classes/class.ilContainer.php"); - include_once("./Services/Container/classes/class.ilContainerSorting.php"); - $sort = ilContainerSorting::_getInstance($parent_obj_id); - $group = $sort->sortItems($group); - - // need extra session sorting here - if ($t == "sess") - { - - } - - foreach ($group[$t] as $k => $item) - { - if (!in_array($item["child"], $done) && - !in_array($item["child"], $in_any_group)) // #16697 - { - $childs[] = $item; - $done[] = $item["child"]; - } - } - } - } - // item groups (if not custom block sorting) - else if ($t == "itgr" && - is_array($g["ref_ids"])) - { - foreach ($g["ref_ids"] as $ref_id) - { - if (isset($group[$ref_id])) - { - foreach ($group[$ref_id] as $k => $item) - { - if(!in_array($item["child"], $done)) - { - $childs[] = $item; - $done[] = $item["child"]; - } - } - } - } - } - } - - return $childs; - } - - /** - * Get childs of node - * - * @param - * @return - */ - function getChildsOfNode($a_parent_node_id) - { - $rbacsystem = $this->rbacsystem; - - if (!$rbacsystem->checkAccess("read", $a_parent_node_id)) - { - return array(); - } - - $obj_id = ilObject::_lookupObjId($a_parent_node_id); - if (!ilConditionHandler::_checkAllConditionsOfTarget($a_parent_node_id, $obj_id)) - { - return array(); - } - - $childs = parent::getChildsOfNode($a_parent_node_id); - - foreach ($childs as $c) { - $this->parent_node_id[$c["child"]] = $a_parent_node_id; - $this->node_data[$c["child"]] = $c; - } - - return $childs; - } - - /** - * Is node clickable? - * - * @param mixed $a_node node object/array - * @return boolean node clickable true/false - */ - function isNodeClickable($a_node) - { - $rbacsystem = $this->rbacsystem; - $tree = $this->tree; - $ilDB = $this->db; - $ilUser = $this->user; - $ilAccess = $this->access; - - $obj_id = ilObject::_lookupObjId($a_node["child"]); - if (!ilConditionHandler::_checkAllConditionsOfTarget($a_node["child"], $obj_id)) - { - return false; - } - - switch ($a_node["type"]) - { - case 'tst': - if(!$rbacsystem->checkAccess("read", $a_node["child"])) - { - return false; - } - - $query = sprintf("SELECT * FROM tst_tests WHERE obj_fi=%s", $obj_id); - $res = $ilDB->query($query); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - return (bool) $row->complete; - } - return false; - - case 'svy': - if(!$rbacsystem->checkAccess("read", $a_node["child"])) - { - return false; - } - - $query = sprintf("SELECT * FROM svy_svy WHERE obj_fi=%s", $obj_id); - $res = $ilDB->query($query); - while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - return (bool) $row->complete; - } - return false; - - // media pools can only be edited - case "mep": - if ($rbacsystem->checkAccess("read", $a_node["child"])) - { - return true; - } - else - { - return false; - } - break; - case 'grpr': - case 'crsr': - case 'catr': - include_once('./Services/ContainerReference/classes/class.ilContainerReferenceAccess.php'); - return ilContainerReferenceAccess::_isAccessible($a_node["child"]); - - case 'prg': - return $rbacsystem->checkAccess("read", $a_node["child"]); - - // all other types are only clickable, if read permission is given - default: - if ($rbacsystem->checkAccess("read", $a_node["child"])) - { - // check if lm is online - if ($a_node["type"] == "lm") - { - include_once("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); - $lm_obj = new ilObjLearningModule($a_node["child"]); - if(($lm_obj->getOfflineStatus()) && (!$rbacsystem->checkAccess('write', $a_node["child"]))) - { - return false; - } - } - // check if fblm is online - if ($a_node["type"] == "htlm") - { - include_once("./Modules/HTMLLearningModule/classes/class.ilObjFileBasedLM.php"); - $lm_obj = new ilObjFileBasedLM($a_node["child"]); - if(($lm_obj->getOfflineStatus()) && (!$rbacsystem->checkAccess('write', $a_node["child"]))) - { - return false; - } - } - // check if fblm is online - if ($a_node["type"] == "sahs") - { - include_once("./Modules/ScormAicc/classes/class.ilObjSAHSLearningModule.php"); - $lm_obj = new ilObjSAHSLearningModule($a_node["child"]); - if(($lm_obj->getOfflineStatus()) && (!$rbacsystem->checkAccess('write', $a_node["child"]))) - { - return false; - } - } - // check if glossary is online - if ($a_node["type"] == "glo") - { - $obj_id = ilObject::_lookupObjectId($a_node["child"]); - include_once("./Modules/Glossary/classes/class.ilObjGlossary.php"); - if((!ilObjGlossary::_lookupOnline($obj_id)) && - (!$rbacsystem->checkAccess('write', $a_node["child"]))) - { - return false; - } - } - - return true; - } - else - { - return false; - } - break; - } - } - + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var ilObjectDefinition + */ + protected $obj_definition; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilDB + */ + protected $db; + + /** + * @var ilObjUser + */ + protected $user; + + protected $type_grps = array(); + protected $session_materials = array(); + + protected $parent_node_id = []; + protected $node_data = []; + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd) + { + global $DIC; + + $this->tree = $DIC->repositoryTree(); + $this->settings = $DIC->settings(); + $this->obj_definition = $DIC["objDefinition"]; + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->access = $DIC->access(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->db = $DIC->database(); + $this->user = $DIC->user(); + $tree = $DIC->repositoryTree(); + $ilSetting = $DIC->settings(); + $objDefinition = $DIC["objDefinition"]; + + $this->cur_ref_id = (int) $_GET["ref_id"]; + + $this->top_node_id = 0; + if ($ilSetting->get("rep_tree_limit_grp_crs") && $this->cur_ref_id > 0) { + $path = $tree->getPathId($this->cur_ref_id); + foreach ($path as $n) { + if ($top_node > 0) { + break; + } + if (in_array( + ilObject::_lookupType(ilObject::_lookupObjId($n)), + array("crs", "grp") + )) { + $this->top_node_id = $n; + } + } + } + + parent::__construct("rep_exp", $a_parent_obj, $a_parent_cmd, $tree); + + $this->setSkipRootNode(false); + $this->setAjax(true); + $this->setOrderField("title"); + if ($ilSetting->get("repository_tree_pres") == "" || + ($ilSetting->get("rep_tree_limit_grp_crs") && $this->top_node_id == 0)) { + $this->setTypeWhiteList($objDefinition->getExplorerContainerTypes()); + } elseif ($ilSetting->get("repository_tree_pres") == "all_types") { + $white = array(); + foreach ($objDefinition->getSubObjectsRecursively("root") as $rtype) { + if (/* $rtype["name"] != "itgr" && */ !$objDefinition->isSideBlock($rtype["name"])) { + $white[] = $rtype["name"]; + } + } + $this->setTypeWhiteList($white); + } + if ((int) $_GET["ref_id"] > 0) { + $this->setPathOpen((int) $_GET["ref_id"]); + } + + $this->setChildLimit((int) $ilSetting->get("rep_tree_limit_number")); + } + + /** + * Get root node + * + * @param + * @return + */ + public function getRootNode() + { + if ($this->top_node_id > 0) { + $root_node = $this->getTree()->getNodeData($this->top_node_id); + } else { + $root_node = parent::getRootNode(); + } + $this->node_data[$root_node["child"]] = $root_node; + return $root_node; + } + + /** + * Get node content + * + * @param array + * @return + */ + public function getNodeContent($a_node) + { + $lng = $this->lng; + + $title = $a_node["title"]; + + if ($a_node["child"] == $this->getNodeId($this->getRootNode())) { + if ($title == "ILIAS") { + $title = $lng->txt("repository"); + } + } elseif ($a_node["type"] == "sess" && + !trim($title)) { + // #14367 - see ilObjSessionListGUI + include_once('./Modules/Session/classes/class.ilSessionAppointment.php'); + $app_info = ilSessionAppointment::_lookupAppointment($a_node["obj_id"]); + $title = ilSessionAppointment::_appointmentToString($app_info['start'], $app_info['end'], $app_info['fullday']); + } + + return $title; + } + + /** + * Get node icon + * + * @param array + * @return + */ + public function getNodeIcon($a_node) + { + $obj_id = ilObject::_lookupObjId($a_node["child"]); + return ilObject::_getIcon($obj_id, "tiny", $a_node["type"]); + } + + /** + * Get node icon alt text + * + * @param array node array + * @return string alt text + */ + public function getNodeIconAlt($a_node) + { + $lng = $this->lng; + + if ($a_node["child"] == $this->getNodeId($this->getRootNode())) { + $title = $a_node["title"]; + if ($title == "ILIAS") { + $title = $lng->txt("repository"); + } + return $lng->txt("icon") . " " . $title; + } + + + return parent::getNodeIconAlt($a_node); + } + + /** + * Is node highlighted? + * + * @param mixed $a_node node object/array + * @return boolean node visible true/false + */ + public function isNodeHighlighted($a_node) + { + if ($a_node["child"] == $_GET["ref_id"] || + ($_GET["ref_id"] == "" && $a_node["child"] == $this->getNodeId($this->getRootNode()))) { + return true; + } + return false; + } + + /** + * Get href for node + * + * @param mixed $a_node node object/array + * @return string href attribute + */ + public function getNodeHref($a_node) + { + $ilCtrl = $this->ctrl; + + switch ($a_node["type"]) { + case "root": + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $a_node["child"]); + $link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", ""); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + return $link; + + case "cat": + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $a_node["child"]); + $link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", ""); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + return $link; + + case "catr": + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $a_node["child"]); + $link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", "redirect"); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + return $link; + + case "grp": + $ilCtrl->setParameterByClass("ilobjgroupgui", "ref_id", $a_node["child"]); + $link = $ilCtrl->getLinkTargetByClass(array("ilrepositorygui", "ilobjgroupgui"), ""); + $ilCtrl->setParameterByClass("ilobjgroupgui", "ref_id", $_GET["ref_id"]); + return $link; + + case "grpr": + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $a_node["child"]); + $link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", "redirect"); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + return $link; + + case "crs": + $ilCtrl->setParameterByClass("ilobjcoursegui", "ref_id", $a_node["child"]); + $link = $ilCtrl->getLinkTargetByClass(array("ilrepositorygui", "ilobjcoursegui"), "view"); + $ilCtrl->setParameterByClass("ilobjcoursegui", "ref_id", $_GET["ref_id"]); + return $link; + + case "crsr": + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $a_node["child"]); + $link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", "redirect"); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + return $link; + + case 'rcrs': + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $a_node["child"]); + $link = $ilCtrl->getLinkTargetByClass("ilrepositorygui", "infoScreen"); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + return $link; + + case 'prg': + $ilCtrl->setParameterByClass("ilobjstudyprogrammegui", "ref_id", $a_node["child"]); + $link = $ilCtrl->getLinkTargetByClass(array("ilrepositorygui", "ilobjstudyprogrammegui"), "view"); + $ilCtrl->setParameterByClass("ilobjstudyprogrammegui", "ref_id", $_GET["ref_id"]); + return $link; + + default: + include_once('./Services/Link/classes/class.ilLink.php'); + return ilLink::_getStaticLink($a_node["child"], $a_node["type"], true); + + } + } + + /** + * Is node visible + * + * @param + * @return + */ + public function isNodeVisible($a_node) + { + $ilAccess = $this->access; + $tree = $this->tree; + $ilSetting = $this->settings; + + if (!$ilAccess->checkAccess('visible', '', $a_node["child"])) { + return false; + } + + if ($ilSetting->get("repository_tree_pres") == "all_types") { + /*$container_parent_id = $tree->checkForParentType($a_node["child"], 'grp'); + if (!$container_parent_id) { + $container_parent_id = $tree->checkForParentType($a_node["child"], 'crs'); + }*/ + // see #21215 + $container_parent_id = $this->getParentCourseOrGroup($a_node["child"]); + if ($container_parent_id > 0) { + // do not display session materials for container course/group + if ($container_parent_id != $a_node["child"]) { + // get container event items only once + if (!isset($this->session_materials[$container_parent_id])) { + include_once './Modules/Session/classes/class.ilEventItems.php'; + $this->session_materials[$container_parent_id] = ilEventItems::_getItemsOfContainer($container_parent_id); + } + if (in_array($a_node["child"], $this->session_materials[$container_parent_id])) { + return false; + } + } + } + } + + return true; + } + + /** + * Get upper course or group + * + * @param int $node_id + * @return int + */ + protected function getParentCourseOrGroup($node_id) + { + $current_node_id = $node_id; + while (isset($this->parent_node_id[$current_node_id])) { + $parent_node_id = $this->parent_node_id[$current_node_id]; + if (isset($this->node_data[$parent_node_id]) && in_array($this->node_data[$parent_node_id]["type"], ["grp", "crs"])) { + return $parent_node_id; + } + $current_node_id = $parent_node_id; + } + return 0; + } + + + /** + * Sort childs + * + * @param array $a_childs array of child nodes + * @param mixed $a_parent_node parent node + * + * @return array array of childs nodes + */ + public function sortChilds($a_childs, $a_parent_node_id) + { + $objDefinition = $this->obj_definition; + $ilAccess = $this->access; + + $parent_obj_id = ilObject::_lookupObjId($a_parent_node_id); + if ($parent_obj_id > 0) { + $parent_type = ilObject::_lookupType($parent_obj_id); + } else { + $parent_type = "dummy"; + $this->type_grps["dummy"] = array("root" => "dummy"); + } + + // alex: if this is not initialized, things are messed up + // see bug 0015978 + $this->type_grps = array(); + + if (empty($this->type_grps[$parent_type])) { + $this->type_grps[$parent_type] = + $objDefinition->getGroupedRepositoryObjectTypes($parent_type); + } + + // #14465 - item groups + include_once('./Services/Object/classes/class.ilObjectActivation.php'); + $group = array(); + $igroup = array(); // used for item groups, see bug #0015978 + $in_any_group = array(); + foreach ($a_childs as $child) { + // item group: get childs + if ($child["type"] == "itgr") { + $g = $child["child"]; + $items = ilObjectActivation::getItemsByItemGroup($g); + if ($items) { + // add item group ref id to item group block + $this->type_grps[$parent_type]["itgr"]["ref_ids"][] = $g; + + // #16697 - check item group permissions + $may_read = $ilAccess->checkAccess('read', '', $g); + + // see bug #0015978 + if ($may_read) { + include_once("./Services/Container/classes/class.ilContainerSorting.php"); + $items = ilContainerSorting::_getInstance($parent_obj_id)->sortSubItems('itgr', $child["obj_id"], $items); + } + + foreach ($items as $item) { + $in_any_group[] = $item["child"]; + + if ($may_read) { + $igroup[$g][] = $item; + $group[$g][] = $item; + } + } + } + } + // type group + else { + $g = $objDefinition->getGroupOfObj($child["type"]); + if ($g == "") { + $g = $child["type"]; + } + $group[$g][] = $child; + } + } + + $in_any_group = array_unique($in_any_group); + + // custom block sorting? + include_once("./Services/Container/classes/class.ilContainerSorting.php"); + $sort = ilContainerSorting::_getInstance($parent_obj_id); + $block_pos = $sort->getBlockPositions(); + if (is_array($block_pos) && count($block_pos) > 0) { + $tmp = $this->type_grps[$parent_type]; + + $this->type_grps[$parent_type] = array(); + foreach ($block_pos as $block_type) { + // type group + if (!is_numeric($block_type) && + array_key_exists($block_type, $tmp)) { + $this->type_grps[$parent_type][$block_type] = $tmp[$block_type]; + unset($tmp[$block_type]); + } + // item group + else { + // using item group ref id directly + $this->type_grps[$parent_type][$block_type] = array(); + } + } + + // append missing + if (sizeof($tmp)) { + foreach ($tmp as $block_type => $grp) { + $this->type_grps[$parent_type][$block_type] = $grp; + } + } + + unset($tmp); + } + + $childs = array(); + $done = array(); + + foreach ($this->type_grps[$parent_type] as $t => $g) { + // type group + if (is_array($group[$t])) { + // see bug #0015978 + // custom sorted igroups + if (is_array($igroup[$t])) { + foreach ($igroup[$t] as $k => $item) { + if (!in_array($item["child"], $done)) { + $childs[] = $item; + $done[] = $item["child"]; + } + } + } else { + // do we have to sort this group?? + include_once("./Services/Container/classes/class.ilContainer.php"); + include_once("./Services/Container/classes/class.ilContainerSorting.php"); + $sort = ilContainerSorting::_getInstance($parent_obj_id); + $group = $sort->sortItems($group); + + // need extra session sorting here + if ($t == "sess") { + } + + foreach ($group[$t] as $k => $item) { + if (!in_array($item["child"], $done) && + !in_array($item["child"], $in_any_group)) { // #16697 + $childs[] = $item; + $done[] = $item["child"]; + } + } + } + } + // item groups (if not custom block sorting) + elseif ($t == "itgr" && + is_array($g["ref_ids"])) { + foreach ($g["ref_ids"] as $ref_id) { + if (isset($group[$ref_id])) { + foreach ($group[$ref_id] as $k => $item) { + if (!in_array($item["child"], $done)) { + $childs[] = $item; + $done[] = $item["child"]; + } + } + } + } + } + } + + return $childs; + } + + /** + * Get childs of node + * + * @param + * @return + */ + public function getChildsOfNode($a_parent_node_id) + { + $rbacsystem = $this->rbacsystem; + + if (!$rbacsystem->checkAccess("read", $a_parent_node_id)) { + return array(); + } + + $obj_id = ilObject::_lookupObjId($a_parent_node_id); + if (!ilConditionHandler::_checkAllConditionsOfTarget($a_parent_node_id, $obj_id)) { + return array(); + } + + $childs = parent::getChildsOfNode($a_parent_node_id); + + foreach ($childs as $c) { + $this->parent_node_id[$c["child"]] = $a_parent_node_id; + $this->node_data[$c["child"]] = $c; + } + + return $childs; + } + + /** + * Is node clickable? + * + * @param mixed $a_node node object/array + * @return boolean node clickable true/false + */ + public function isNodeClickable($a_node) + { + $rbacsystem = $this->rbacsystem; + $tree = $this->tree; + $ilDB = $this->db; + $ilUser = $this->user; + $ilAccess = $this->access; + + $obj_id = ilObject::_lookupObjId($a_node["child"]); + if (!ilConditionHandler::_checkAllConditionsOfTarget($a_node["child"], $obj_id)) { + return false; + } + + switch ($a_node["type"]) { + case 'tst': + if (!$rbacsystem->checkAccess("read", $a_node["child"])) { + return false; + } + + $query = sprintf("SELECT * FROM tst_tests WHERE obj_fi=%s", $obj_id); + $res = $ilDB->query($query); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + return (bool) $row->complete; + } + return false; + + case 'svy': + if (!$rbacsystem->checkAccess("read", $a_node["child"])) { + return false; + } + + $query = sprintf("SELECT * FROM svy_svy WHERE obj_fi=%s", $obj_id); + $res = $ilDB->query($query); + while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + return (bool) $row->complete; + } + return false; + + // media pools can only be edited + case "mep": + if ($rbacsystem->checkAccess("read", $a_node["child"])) { + return true; + } else { + return false; + } + break; + case 'grpr': + case 'crsr': + case 'catr': + include_once('./Services/ContainerReference/classes/class.ilContainerReferenceAccess.php'); + return ilContainerReferenceAccess::_isAccessible($a_node["child"]); + + case 'prg': + return $rbacsystem->checkAccess("read", $a_node["child"]); + + // all other types are only clickable, if read permission is given + default: + if ($rbacsystem->checkAccess("read", $a_node["child"])) { + // check if lm is online + if ($a_node["type"] == "lm") { + include_once("./Modules/LearningModule/classes/class.ilObjLearningModule.php"); + $lm_obj = new ilObjLearningModule($a_node["child"]); + if (($lm_obj->getOfflineStatus()) && (!$rbacsystem->checkAccess('write', $a_node["child"]))) { + return false; + } + } + // check if fblm is online + if ($a_node["type"] == "htlm") { + include_once("./Modules/HTMLLearningModule/classes/class.ilObjFileBasedLM.php"); + $lm_obj = new ilObjFileBasedLM($a_node["child"]); + if (($lm_obj->getOfflineStatus()) && (!$rbacsystem->checkAccess('write', $a_node["child"]))) { + return false; + } + } + // check if fblm is online + if ($a_node["type"] == "sahs") { + include_once("./Modules/ScormAicc/classes/class.ilObjSAHSLearningModule.php"); + $lm_obj = new ilObjSAHSLearningModule($a_node["child"]); + if (($lm_obj->getOfflineStatus()) && (!$rbacsystem->checkAccess('write', $a_node["child"]))) { + return false; + } + } + // check if glossary is online + if ($a_node["type"] == "glo") { + $obj_id = ilObject::_lookupObjectId($a_node["child"]); + include_once("./Modules/Glossary/classes/class.ilObjGlossary.php"); + if ((!ilObjGlossary::_lookupOnline($obj_id)) && + (!$rbacsystem->checkAccess('write', $a_node["child"]))) { + return false; + } + } + + return true; + } else { + return false; + } + break; + } + } } - -?> diff --git a/Services/Repository/classes/class.ilRepositoryGUI.php b/Services/Repository/classes/class.ilRepositoryGUI.php index a03c21c132d94d2171edeeb2a37fea37252c1dc9..60a220eb9d8a1a34e98a334cf86f3b4a749ffa7d 100755 --- a/Services/Repository/classes/class.ilRepositoryGUI.php +++ b/Services/Repository/classes/class.ilRepositoryGUI.php @@ -28,526 +28,464 @@ include_once("./Services/Table/classes/class.ilTableGUI.php"); */ class ilRepositoryGUI { - /** - * @var ilObjectDefinition - */ - protected $objDefinition; - - /** - * @var Logger - */ - protected $log; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilSetting - */ - protected $settings; - - /** - * @var ilHelpGUI - */ - protected $help; - - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * @var ilAccessHandler - */ - protected $access; - - var $lng; - var $tpl; - var $tree; - var $rbacsystem; - var $cur_ref_id; - var $cmd; - var $mode; - var $ctrl; - - /** - * Constructor - * @access public - */ - function __construct() - { - global $DIC; - - $this->log = $DIC["ilLog"]; - $this->user = $DIC->user(); - $this->settings = $DIC->settings(); - $this->help = $DIC["ilHelp"]; - $this->error = $DIC["ilErr"]; - $this->access = $DIC->access(); - $lng = $DIC->language(); - $tpl = $DIC["tpl"]; - $tree = $DIC->repositoryTree(); - $rbacsystem = $DIC->rbac()->system(); - $objDefinition = $DIC["objDefinition"]; - $ilCtrl = $DIC->ctrl(); - $ilLog = $DIC["ilLog"]; - $ilUser = $DIC->user(); - $ilSetting = $DIC->settings(); - - $this->lng = $lng; - $this->tpl = $tpl; - $this->tree = $tree; - $this->rbacsystem = $rbacsystem; - $this->objDefinition = $objDefinition; - - $this->ctrl = $ilCtrl; - - $this->creation_mode = false; - - $this->ctrl->saveParameter($this, array("ref_id")); - if (!ilUtil::isAPICall()) - $this->ctrl->setReturn($this,""); - - // determine current ref id and mode - if (!empty($_GET["ref_id"]) || $this->ctrl->getCmd() == "showTree") - { - $this->cur_ref_id = $_GET["ref_id"]; - } - else - { -//echo "1-".$_SESSION["il_rep_ref_id"]."-"; - if (!empty($_SESSION["il_rep_ref_id"]) && !empty($_GET["getlast"])) - { - $this->cur_ref_id = $_SESSION["il_rep_ref_id"]; -//echo "2-".$this->cur_ref_id."-"; - } - else - { - $this->cur_ref_id = $this->tree->getRootId(); - - if ($_GET["cmd"] != "" && $_GET["cmd"] != "frameset") - { -//echo "hhh"; - $get_str = $post_str = ""; - foreach($_GET as $key => $value) - { - $get_str.= "-$key:$value"; - } - foreach($_POST as $key => $value) - { - $post_str.= "-$key:$value"; - } - $ilLog->write("Repository: command called without ref_id.". - "GET:".$get_str."-POST:".$post_str, $ilLog->WARNING); - } - // #10033 - $_GET = array("baseClass"=>"ilRepositoryGUI"); - $_POST = array(); - $this->ctrl->setCmd("frameset"); - } - } -//echo "
                  +".$_GET["ref_id"]."+"; - if (!$tree->isInTree($this->cur_ref_id) && $this->ctrl->getCmd() != "showTree") - { - $this->cur_ref_id = $this->tree->getRootId(); - - // check wether command has been called with - // item that is not in tree - if ($_GET["cmd"] != "" && $_GET["cmd"] != "frameset") - { - $get_str = $post_str = ""; - foreach($_GET as $key => $value) - { - $get_str.= "-$key:$value"; - } - foreach($_POST as $key => $value) - { - $post_str.= "-$key:$value"; - } - $ilLog->write("Repository: command called with ref_id that is not in tree.". - "GET:".$get_str."-POST:".$post_str, $ilLog->WARNING); - } - $_GET = array(); - $_POST = array(); - $this->ctrl->setCmd("frameset"); - } - - // set current repository view mode - if (!empty($_GET["set_mode"])) - { - $_SESSION["il_rep_mode"] = $_GET["set_mode"]; - if ($ilUser->getId() != ANONYMOUS_USER_ID) - { - $ilUser->writePref("il_rep_mode", $_GET["set_mode"]); - } - } - - // get user setting - if ($_SESSION["il_rep_mode"] == "") - { - if ($ilUser->getId() != ANONYMOUS_USER_ID) - { - $_SESSION["il_rep_mode"] = $ilUser->getPref("il_rep_mode"); - } - } - - // if nothing set, get default view - if ($_SESSION["il_rep_mode"] == "") - { - $_SESSION["il_rep_mode"] = $ilSetting->get("default_repository_view"); - } - - $this->mode = ($_SESSION["il_rep_mode"] != "") - ? $_SESSION["il_rep_mode"] - : "flat"; - - // store current ref id - if ($this->ctrl->getCmd() != "showTree" && - $rbacsystem->checkAccess("read", $this->cur_ref_id)) - { - $type = ilObject::_lookupType($this->cur_ref_id, true); - if ($type == "cat" || $type == "grp" || $type == "crs" - || $type == "root") - { - $_SESSION["il_rep_ref_id"] = $this->cur_ref_id; - } - } - - $_GET["ref_id"] = $this->cur_ref_id; - - } - - - /** - * execute command - */ - function executeCommand() - { - $rbacsystem = $this->rbacsystem; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilHelp = $this->help; - $ilErr = $this->error; - - // check creation mode - // determined by "new_type" parameter - $new_type = ($_POST["new_type"] != "" && $ilCtrl->getCmd() == "create") - ? $_POST["new_type"] - : $_GET["new_type"]; - - if ($new_type != "" && $new_type != "sty") - { - $this->creation_mode = true; - $ilHelp->setScreenIdComponent($new_type); - $ilHelp->setDefaultScreenId(ilHelpGUI::ID_PART_SCREEN, "create"); - } - - // handle frameset command - $cmd = $this->ctrl->getCmd(); - if (($cmd == "frameset" || $_GET["rep_frame"] == 1) && $_SESSION["il_rep_mode"] == "tree") - { - $next_class = ""; - $cmd = "frameset"; - } - else if ($cmd == "frameset" && $_SESSION["il_rep_mode"] != "tree") - { - $this->ctrl->setCmd(""); - $cmd = ""; - } - - // determine next class - if ($cmd != "frameset") - { - if ($this->creation_mode) - { - $obj_type = $new_type; - $class_name = $this->objDefinition->getClassName($obj_type); - if (strtolower($class_name) != "user") - { - $next_class = strtolower("ilObj".$class_name."GUI"); - } - else - { - $next_class = $this->ctrl->getNextClass(); - } - // Only set the fixed cmdClass if the next class is different to - // the GUI class of the new object. - // An example: - // Copy Category uses this call structure: - // RespositoryGUI -> CategoryGUI -> ilObjectCopyGUI - // Without this fix, the cmdClass ilObjectCopyGUI would never be reached - - ilLoggerFactory::getLogger('obj')->debug($this->ctrl->getNextClass().' <-> '. $class_name); - - if($this->ctrl->getNextClass() != strtolower('ilObj'.$class_name.'GUI')) - { - $this->ctrl->setCmdClass($next_class); - } - } - else if ((($next_class = $this->ctrl->getNextClass($this)) == "") - || ($next_class == "ilrepositorygui" && $this->ctrl->getCmd() == "return")) - { - if ($cmd != "frameset" && $cmd != "showTree") - { - // get GUI of current object - $obj_type = ilObject::_lookupType($this->cur_ref_id,true); - $class_name = $this->objDefinition->getClassName($obj_type); - $next_class = strtolower("ilObj".$class_name."GUI"); - - $this->ctrl->setCmdClass($next_class); - if ($this->ctrl->getCmd() == "return") - { - $this->ctrl->setCmd(""); - } - } - } - } - - // commands that are always handled by repository gui - // to do: move to container - if ($cmd == "showTree") - { - $next_class = ""; - } - - switch ($next_class) - { - default: - // forward all other classes to gui commands - if ($next_class != "" && $next_class != "ilrepositorygui") - { - $class_path = $this->ctrl->lookupClassPath($next_class); - // get gui class instance - require_once($class_path); - $class_name = $this->ctrl->getClassForClasspath($class_path); - if (!$this->creation_mode) - { - if(is_subclass_of($class_name, "ilObject2GUI")) - { - $this->gui_obj = new $class_name($this->cur_ref_id, ilObject2GUI::REPOSITORY_NODE_ID); - } - else - { - $this->gui_obj = new $class_name("", $this->cur_ref_id, true, false); - } - } - else - { - if(is_subclass_of($class_name, "ilObject2GUI")) - { - $this->gui_obj = new $class_name(null, ilObject2GUI::REPOSITORY_NODE_ID, $this->cur_ref_id); - } - else - { - $this->gui_obj = new $class_name("", 0, true, false); - } - } - //$this->gui_obj = new $class_name("", $this->cur_ref_id, true, false); - - - $tabs_out = ($new_type == "") - ? true - : false; - $this->gui_obj->setCreationMode($this->creation_mode); - $this->ctrl->setReturn($this, "return"); - - $this->show(); - } - else // - { - // process repository frameset - if ($cmd == "frameset") - { - if ($_SESSION["il_rep_mode"] == "tree") - { - $this->frameset(); - return; - } - $cmd = ""; - $this->ctrl->setCmd(""); - } - - // process tree command - if ($cmd == "showTree") - { - $this->showTree(); - return; - } - - $cmd = $this->ctrl->getCmd(""); - - // check read access for category - if ($this->cur_ref_id > 0 && !$rbacsystem->checkAccess("read", $this->cur_ref_id)) - { - $_SESSION["il_rep_ref_id"] = ""; - $ilErr->raiseError($lng->txt("permission_denied"), $ilErr->MESSAGE); - $this->tpl->show(); - } - else - { - $this->cmd = $cmd; - $this->$cmd(); - } - } - break; - } - } - - - function show() - { - // normal command processing - $ret = $this->ctrl->forwardCommand($this->gui_obj); - $this->tpl->setVariable("OBJECTS", $this->gui_obj->getHTML()); - - $this->tpl->show(); - } - - /** - * output tree frameset - */ - function frameset() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - - $ilCtrl->redirectByClass("ilrepositorygui", ""); - } - - - /** - * display tree view - */ - function showTree() - { - $ilCtrl = $this->ctrl; - $tree = $this->tree; - $ilSetting = $this->settings; - $lng = $this->lng; - - $ilCtrl->setParameter($this, "active_node", $_GET["active_node"]); - - $this->tpl = new ilTemplate("tpl.main.html", true, true); - $this->tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); - - $this->tpl->addBlockFile("CONTENT", "content", "tpl.explorer.html"); - - include_once ("./Services/Repository/classes/class.ilRepositoryExplorer.php"); - - $active_node = ($_GET["active_node"] > 1) - ? $_GET["active_node"] - : ($_GET["ref_id"] > 1) - ? $_GET["ref_id"] - : 0; - $top_node = 0; - if ($ilSetting->get("rep_tree_limit_grp_crs") && $active_node > 0) - { - $path = $tree->getPathId($active_node); - foreach ($path as $n) - { - if ($top_node > 0) - { - break; - } - if (in_array(ilObject::_lookupType(ilObject::_lookupObjId($n)), - array("crs", "grp"))) - { - $top_node = $n; - } - } - } - - $exp = new ilRepositoryExplorer("ilias.php?baseClass=ilRepositoryGUI&cmd=goto", $top_node); - $exp->setUseStandardFrame(false); - $exp->setExpandTarget($ilCtrl->getLinkTarget($this, "showTree")); - $exp->setFrameUpdater("tree", "updater"); - $exp->setTargetGet("ref_id"); - - if ($_GET["repexpand"] == "") - { - $expanded = $this->tree->readRootId(); - } - else - { - $expanded = $_GET["repexpand"]; - } - - $exp->setExpand($expanded); - - if ($active_node > 0) - { - $path = $tree->getPathId($active_node); - if ($top_node > 0) - { - $exp->setForceOpenPath($path); - $exp->setExpand($expanded); - } - else - { - $exp->setForceOpenPath($path + array($top_node)); - } - $exp->highlightNode($active_node); - } - - // build html-output - if ($top_node > 0) - { - $head_tpl = new ilTemplate("tpl.cont_tree_head.html", true, true, - "Services/Repository"); - $path = ilObject::_getIcon(ROOT_FOLDER_ID, "tiny", "root"); - $nd = $tree->getNodeData(ROOT_FOLDER_ID); - $title = $nd["title"]; - if ($title == "ILIAS") - { - $title = $lng->txt("repository"); - } - $head_tpl->setVariable("IMG_SRC", $path); - $head_tpl->setVariable("ALT_IMG", $lng->txt("icon")." ".$title); - $head_tpl->setVariable("LINK_TXT", $title); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", "1"); - $head_tpl->setVariable("LINK_HREF", - $ilCtrl->getLinkTargetByClass("ilrepositorygui", "frameset")); - $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); - $exp->setTreeLead($head_tpl->get()); - - $exp->initItemCounter(1); - $exp->setOutput($tree->getParentId($top_node), 1, - ilObject::_lookupObjId($tree->getParentId($top_node))); - } - else - { - $exp->setOutput(0); - } - $output = $exp->getOutput(false); - -//if ($GLOBALS["ilUser"]->getLogin() == "alex") echo "topnode:$top_node:activenode:$active_node:"; - - - // asynchronous output - if ($ilCtrl->isAsynch()) - { - echo $output; exit; - } - - $this->tpl->setCurrentBlock("content"); - $this->tpl->setVariable("TXT_EXPLORER_HEADER", $this->lng->txt("overview")); - $this->tpl->setVariable("EXP_REFRESH", $this->lng->txt("refresh")); - $this->tpl->setVariable("EXPLORER",$output); - $ilCtrl->setParameter($this, "repexpand", $_GET["repexpand"]); - $this->tpl->setVariable("ACTION", $ilCtrl->getLinkTarget($this, "showTree", "", false, false)); - $this->tpl->parseCurrentBlock(); - - include_once("./Services/jQuery/classes/class.iljQueryUtil.php"); - iljQueryUtil::initjQuery($this->tpl); - - $this->tpl->show(false); - exit; - } - + /** + * @var ilObjectDefinition + */ + protected $objDefinition; + + /** + * @var Logger + */ + protected $log; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilAccessHandler + */ + protected $access; + + public $lng; + public $tpl; + public $tree; + public $rbacsystem; + public $cur_ref_id; + public $cmd; + public $mode; + public $ctrl; + + /** + * Constructor + * @access public + */ + public function __construct() + { + global $DIC; + + $this->log = $DIC["ilLog"]; + $this->user = $DIC->user(); + $this->settings = $DIC->settings(); + $this->help = $DIC["ilHelp"]; + $this->error = $DIC["ilErr"]; + $this->access = $DIC->access(); + $lng = $DIC->language(); + $tpl = $DIC["tpl"]; + $tree = $DIC->repositoryTree(); + $rbacsystem = $DIC->rbac()->system(); + $objDefinition = $DIC["objDefinition"]; + $ilCtrl = $DIC->ctrl(); + $ilLog = $DIC["ilLog"]; + $ilUser = $DIC->user(); + $ilSetting = $DIC->settings(); + + $this->lng = $lng; + $this->tpl = $tpl; + $this->tree = $tree; + $this->rbacsystem = $rbacsystem; + $this->objDefinition = $objDefinition; + + $this->ctrl = $ilCtrl; + + $this->creation_mode = false; + + $this->ctrl->saveParameter($this, array("ref_id")); + if (!ilUtil::isAPICall()) { + $this->ctrl->setReturn($this, ""); + } + + // determine current ref id and mode + if (!empty($_GET["ref_id"]) || $this->ctrl->getCmd() == "showTree") { + $this->cur_ref_id = $_GET["ref_id"]; + } else { + //echo "1-".$_SESSION["il_rep_ref_id"]."-"; + if (!empty($_SESSION["il_rep_ref_id"]) && !empty($_GET["getlast"])) { + $this->cur_ref_id = $_SESSION["il_rep_ref_id"]; + //echo "2-".$this->cur_ref_id."-"; + } else { + $this->cur_ref_id = $this->tree->getRootId(); + + if ($_GET["cmd"] != "" && $_GET["cmd"] != "frameset") { + //echo "hhh"; + $get_str = $post_str = ""; + foreach ($_GET as $key => $value) { + $get_str.= "-$key:$value"; + } + foreach ($_POST as $key => $value) { + $post_str.= "-$key:$value"; + } + $ilLog->write("Repository: command called without ref_id." . + "GET:" . $get_str . "-POST:" . $post_str, $ilLog->WARNING); + } + // #10033 + $_GET = array("baseClass"=>"ilRepositoryGUI"); + $_POST = array(); + $this->ctrl->setCmd("frameset"); + } + } + //echo "
                  +".$_GET["ref_id"]."+"; + if (!$tree->isInTree($this->cur_ref_id) && $this->ctrl->getCmd() != "showTree") { + $this->cur_ref_id = $this->tree->getRootId(); + + // check wether command has been called with + // item that is not in tree + if ($_GET["cmd"] != "" && $_GET["cmd"] != "frameset") { + $get_str = $post_str = ""; + foreach ($_GET as $key => $value) { + $get_str.= "-$key:$value"; + } + foreach ($_POST as $key => $value) { + $post_str.= "-$key:$value"; + } + $ilLog->write("Repository: command called with ref_id that is not in tree." . + "GET:" . $get_str . "-POST:" . $post_str, $ilLog->WARNING); + } + $_GET = array(); + $_POST = array(); + $this->ctrl->setCmd("frameset"); + } + + // set current repository view mode + if (!empty($_GET["set_mode"])) { + $_SESSION["il_rep_mode"] = $_GET["set_mode"]; + if ($ilUser->getId() != ANONYMOUS_USER_ID) { + $ilUser->writePref("il_rep_mode", $_GET["set_mode"]); + } + } + + // get user setting + if ($_SESSION["il_rep_mode"] == "") { + if ($ilUser->getId() != ANONYMOUS_USER_ID) { + $_SESSION["il_rep_mode"] = $ilUser->getPref("il_rep_mode"); + } + } + + // if nothing set, get default view + if ($_SESSION["il_rep_mode"] == "") { + $_SESSION["il_rep_mode"] = $ilSetting->get("default_repository_view"); + } + + $this->mode = ($_SESSION["il_rep_mode"] != "") + ? $_SESSION["il_rep_mode"] + : "flat"; + + // store current ref id + if ($this->ctrl->getCmd() != "showTree" && + $rbacsystem->checkAccess("read", $this->cur_ref_id)) { + $type = ilObject::_lookupType($this->cur_ref_id, true); + if ($type == "cat" || $type == "grp" || $type == "crs" + || $type == "root") { + $_SESSION["il_rep_ref_id"] = $this->cur_ref_id; + } + } + + $_GET["ref_id"] = $this->cur_ref_id; + } + + + /** + * execute command + */ + public function executeCommand() + { + $rbacsystem = $this->rbacsystem; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilHelp = $this->help; + $ilErr = $this->error; + + // check creation mode + // determined by "new_type" parameter + $new_type = ($_POST["new_type"] != "" && $ilCtrl->getCmd() == "create") + ? $_POST["new_type"] + : $_GET["new_type"]; + + if ($new_type != "" && $new_type != "sty") { + $this->creation_mode = true; + $ilHelp->setScreenIdComponent($new_type); + $ilHelp->setDefaultScreenId(ilHelpGUI::ID_PART_SCREEN, "create"); + } + + // handle frameset command + $cmd = $this->ctrl->getCmd(); + if (($cmd == "frameset" || $_GET["rep_frame"] == 1) && $_SESSION["il_rep_mode"] == "tree") { + $next_class = ""; + $cmd = "frameset"; + } elseif ($cmd == "frameset" && $_SESSION["il_rep_mode"] != "tree") { + $this->ctrl->setCmd(""); + $cmd = ""; + } + + // determine next class + if ($cmd != "frameset") { + if ($this->creation_mode) { + $obj_type = $new_type; + $class_name = $this->objDefinition->getClassName($obj_type); + if (strtolower($class_name) != "user") { + $next_class = strtolower("ilObj" . $class_name . "GUI"); + } else { + $next_class = $this->ctrl->getNextClass(); + } + // Only set the fixed cmdClass if the next class is different to + // the GUI class of the new object. + // An example: + // Copy Category uses this call structure: + // RespositoryGUI -> CategoryGUI -> ilObjectCopyGUI + // Without this fix, the cmdClass ilObjectCopyGUI would never be reached + + ilLoggerFactory::getLogger('obj')->debug($this->ctrl->getNextClass() . ' <-> ' . $class_name); + + if ($this->ctrl->getNextClass() != strtolower('ilObj' . $class_name . 'GUI')) { + $this->ctrl->setCmdClass($next_class); + } + } elseif ((($next_class = $this->ctrl->getNextClass($this)) == "") + || ($next_class == "ilrepositorygui" && $this->ctrl->getCmd() == "return")) { + if ($cmd != "frameset" && $cmd != "showTree") { + // get GUI of current object + $obj_type = ilObject::_lookupType($this->cur_ref_id, true); + $class_name = $this->objDefinition->getClassName($obj_type); + $next_class = strtolower("ilObj" . $class_name . "GUI"); + + $this->ctrl->setCmdClass($next_class); + if ($this->ctrl->getCmd() == "return") { + $this->ctrl->setCmd(""); + } + } + } + } + + // commands that are always handled by repository gui + // to do: move to container + if ($cmd == "showTree") { + $next_class = ""; + } + + switch ($next_class) { + default: + // forward all other classes to gui commands + if ($next_class != "" && $next_class != "ilrepositorygui") { + $class_path = $this->ctrl->lookupClassPath($next_class); + // get gui class instance + require_once($class_path); + $class_name = $this->ctrl->getClassForClasspath($class_path); + if (!$this->creation_mode) { + if (is_subclass_of($class_name, "ilObject2GUI")) { + $this->gui_obj = new $class_name($this->cur_ref_id, ilObject2GUI::REPOSITORY_NODE_ID); + } else { + $this->gui_obj = new $class_name("", $this->cur_ref_id, true, false); + } + } else { + if (is_subclass_of($class_name, "ilObject2GUI")) { + $this->gui_obj = new $class_name(null, ilObject2GUI::REPOSITORY_NODE_ID, $this->cur_ref_id); + } else { + $this->gui_obj = new $class_name("", 0, true, false); + } + } + //$this->gui_obj = new $class_name("", $this->cur_ref_id, true, false); + + + $tabs_out = ($new_type == "") + ? true + : false; + $this->gui_obj->setCreationMode($this->creation_mode); + $this->ctrl->setReturn($this, "return"); + + $this->show(); + } else { // + // process repository frameset + if ($cmd == "frameset") { + if ($_SESSION["il_rep_mode"] == "tree") { + $this->frameset(); + return; + } + $cmd = ""; + $this->ctrl->setCmd(""); + } + + // process tree command + if ($cmd == "showTree") { + $this->showTree(); + return; + } + + $cmd = $this->ctrl->getCmd(""); + + // check read access for category + if ($this->cur_ref_id > 0 && !$rbacsystem->checkAccess("read", $this->cur_ref_id)) { + $_SESSION["il_rep_ref_id"] = ""; + $ilErr->raiseError($lng->txt("permission_denied"), $ilErr->MESSAGE); + $this->tpl->show(); + } else { + $this->cmd = $cmd; + $this->$cmd(); + } + } + break; + } + } + + + public function show() + { + // normal command processing + $ret = $this->ctrl->forwardCommand($this->gui_obj); + $this->tpl->setVariable("OBJECTS", $this->gui_obj->getHTML()); + + $this->tpl->show(); + } + + /** + * output tree frameset + */ + public function frameset() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + + $ilCtrl->redirectByClass("ilrepositorygui", ""); + } + + + /** + * display tree view + */ + public function showTree() + { + $ilCtrl = $this->ctrl; + $tree = $this->tree; + $ilSetting = $this->settings; + $lng = $this->lng; + + $ilCtrl->setParameter($this, "active_node", $_GET["active_node"]); + + $this->tpl = new ilTemplate("tpl.main.html", true, true); + $this->tpl->setVariable("LOCATION_STYLESHEET", ilUtil::getStyleSheetLocation()); + + $this->tpl->addBlockFile("CONTENT", "content", "tpl.explorer.html"); + + include_once("./Services/Repository/classes/class.ilRepositoryExplorer.php"); + + $active_node = ($_GET["active_node"] > 1) + ? $_GET["active_node"] + : ($_GET["ref_id"] > 1) + ? $_GET["ref_id"] + : 0; + $top_node = 0; + if ($ilSetting->get("rep_tree_limit_grp_crs") && $active_node > 0) { + $path = $tree->getPathId($active_node); + foreach ($path as $n) { + if ($top_node > 0) { + break; + } + if (in_array( + ilObject::_lookupType(ilObject::_lookupObjId($n)), + array("crs", "grp") + )) { + $top_node = $n; + } + } + } + + $exp = new ilRepositoryExplorer("ilias.php?baseClass=ilRepositoryGUI&cmd=goto", $top_node); + $exp->setUseStandardFrame(false); + $exp->setExpandTarget($ilCtrl->getLinkTarget($this, "showTree")); + $exp->setFrameUpdater("tree", "updater"); + $exp->setTargetGet("ref_id"); + + if ($_GET["repexpand"] == "") { + $expanded = $this->tree->readRootId(); + } else { + $expanded = $_GET["repexpand"]; + } + + $exp->setExpand($expanded); + + if ($active_node > 0) { + $path = $tree->getPathId($active_node); + if ($top_node > 0) { + $exp->setForceOpenPath($path); + $exp->setExpand($expanded); + } else { + $exp->setForceOpenPath($path + array($top_node)); + } + $exp->highlightNode($active_node); + } + + // build html-output + if ($top_node > 0) { + $head_tpl = new ilTemplate( + "tpl.cont_tree_head.html", + true, + true, + "Services/Repository" + ); + $path = ilObject::_getIcon(ROOT_FOLDER_ID, "tiny", "root"); + $nd = $tree->getNodeData(ROOT_FOLDER_ID); + $title = $nd["title"]; + if ($title == "ILIAS") { + $title = $lng->txt("repository"); + } + $head_tpl->setVariable("IMG_SRC", $path); + $head_tpl->setVariable("ALT_IMG", $lng->txt("icon") . " " . $title); + $head_tpl->setVariable("LINK_TXT", $title); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", "1"); + $head_tpl->setVariable( + "LINK_HREF", + $ilCtrl->getLinkTargetByClass("ilrepositorygui", "frameset") + ); + $ilCtrl->setParameterByClass("ilrepositorygui", "ref_id", $_GET["ref_id"]); + $exp->setTreeLead($head_tpl->get()); + + $exp->initItemCounter(1); + $exp->setOutput( + $tree->getParentId($top_node), + 1, + ilObject::_lookupObjId($tree->getParentId($top_node)) + ); + } else { + $exp->setOutput(0); + } + $output = $exp->getOutput(false); + + //if ($GLOBALS["ilUser"]->getLogin() == "alex") echo "topnode:$top_node:activenode:$active_node:"; + + + // asynchronous output + if ($ilCtrl->isAsynch()) { + echo $output; + exit; + } + + $this->tpl->setCurrentBlock("content"); + $this->tpl->setVariable("TXT_EXPLORER_HEADER", $this->lng->txt("overview")); + $this->tpl->setVariable("EXP_REFRESH", $this->lng->txt("refresh")); + $this->tpl->setVariable("EXPLORER", $output); + $ilCtrl->setParameter($this, "repexpand", $_GET["repexpand"]); + $this->tpl->setVariable("ACTION", $ilCtrl->getLinkTarget($this, "showTree", "", false, false)); + $this->tpl->parseCurrentBlock(); + + include_once("./Services/jQuery/classes/class.iljQueryUtil.php"); + iljQueryUtil::initjQuery($this->tpl); + + $this->tpl->show(false); + exit; + } } // END class.ilRepository - - -?> diff --git a/Services/Repository/classes/class.ilRepositoryGlobalScreenProvider.php b/Services/Repository/classes/class.ilRepositoryGlobalScreenProvider.php index b785ab664daa3f1c9002f257e9c7eebb5288ba33..95506f7888a68f540c296ed5201de51417809aa8 100644 --- a/Services/Repository/classes/class.ilRepositoryGlobalScreenProvider.php +++ b/Services/Repository/classes/class.ilRepositoryGlobalScreenProvider.php @@ -8,128 +8,132 @@ use ILIAS\GlobalScreen\Scope\MainMenu\Provider\AbstractStaticMainMenuProvider; * * @author Fabian Schmid */ -class ilRepositoryGlobalScreenProvider extends AbstractStaticMainMenuProvider { - - /** - * @var IdentificationInterface - */ - protected $top_item; - - - /** - * ilRepositoryGlobalScreenProvider constructor. - * - * @param \ILIAS\DI\Container $dic - */ - public function __construct(\ILIAS\DI\Container $dic) { - parent::__construct($dic); - $this->top_item = $this->if->identifier('rep'); - } - - - /** - * Some other components want to provide Items for the main menu which are - * located at the PD TopTitem by default. Therefore we have to provide our - * TopTitem Identification for others - * - * @return IdentificationInterface - */ - public function getTopItem(): IdentificationInterface { - return $this->top_item; - } - - - /** - * @inheritDoc - */ - public function getStaticTopItems(): array { - $dic = $this->dic; - - return [$this->mainmenu->topParentItem($this->getTopItem()) - ->withTitle($this->dic->language()->txt("repository")) - ->withPosition(2) - ->withVisibilityCallable( - function () use ($dic) { - return (bool)($dic->access()->checkAccess('visible', '', ROOT_FOLDER_ID)); - } - )]; - } - - - /** - * @inheritDoc - */ - public function getStaticSubItems(): array { - $dic = $this->dic; - - $title = function () use ($dic): string { - try { - $nd = $dic['tree']->getNodeData(ROOT_FOLDER_ID); - $title = ($nd["title"] === "ILIAS" ? $dic->language()->txt("repository") : $nd["title"]); - $icon = ilUtil::img(ilObject::_getIcon(ilObject::_lookupObjId(1), "tiny")); - } catch (InvalidArgumentException $e) { - return ""; - } - - return $title . " - " . $dic->language()->txt("rep_main_page"); - }; - - $action = function (): string { - try { - $static_link = ilLink::_getStaticLink(1, 'root', true); - } catch (InvalidArgumentException $e) { - return ""; - } - - return $static_link; - }; - - $entries[] = $this->mainmenu->link($this->if->identifier('rep_main_page')) - ->withTitle($title()) - ->withAction($action()) - ->withParent($this->getTopItem()); - - // LastVisited - $links = function (): array { - $items = []; - if (isset($this->dic['ilNavigationHistory'])) { - $items = $this->dic['ilNavigationHistory']->getItems(); - } - $links = []; - reset($items); - $cnt = 0; - $first = true; - - foreach ($items as $k => $item) { - if ($cnt >= 10) { - break; - } - - if (!isset($item["ref_id"]) || !isset($_GET["ref_id"]) - || ($item["ref_id"] != $_GET["ref_id"] || !$first) - ) // do not list current item - { - $obj_id = ilObject::_lookupObjId($item["ref_id"]); - $icon = ilUtil::img(ilObject::_getIcon($obj_id, "tiny")); - $ititle = ilUtil::shortenText(strip_tags($item["title"]), 50, true); // #11023 - $links[] = $this->mainmenu->link($this->if->identifier('last_visited_' . $obj_id)) - ->withTitle($icon . " " . $ititle) - ->withAction($item["link"]); - } - $first = false; - } - - return $links; - }; - $entries[] = $this->mainmenu->linkList($this->if->identifier('last_visited')) - ->withLinks($links) - ->withTitle($this->dic->language()->txt('last_visited')) - ->withParent($this->getTopItem())->withVisibilityCallable( - function () use ($dic) { - return ($dic->user()->getId() != ANONYMOUS_USER_ID); - } - ); - - return $entries; - } +class ilRepositoryGlobalScreenProvider extends AbstractStaticMainMenuProvider +{ + + /** + * @var IdentificationInterface + */ + protected $top_item; + + + /** + * ilRepositoryGlobalScreenProvider constructor. + * + * @param \ILIAS\DI\Container $dic + */ + public function __construct(\ILIAS\DI\Container $dic) + { + parent::__construct($dic); + $this->top_item = $this->if->identifier('rep'); + } + + + /** + * Some other components want to provide Items for the main menu which are + * located at the PD TopTitem by default. Therefore we have to provide our + * TopTitem Identification for others + * + * @return IdentificationInterface + */ + public function getTopItem() : IdentificationInterface + { + return $this->top_item; + } + + + /** + * @inheritDoc + */ + public function getStaticTopItems() : array + { + $dic = $this->dic; + + return [$this->mainmenu->topParentItem($this->getTopItem()) + ->withTitle($this->dic->language()->txt("repository")) + ->withPosition(2) + ->withVisibilityCallable( + function () use ($dic) { + return (bool) ($dic->access()->checkAccess('visible', '', ROOT_FOLDER_ID)); + } + )]; + } + + + /** + * @inheritDoc + */ + public function getStaticSubItems() : array + { + $dic = $this->dic; + + $title = function () use ($dic) : string { + try { + $nd = $dic['tree']->getNodeData(ROOT_FOLDER_ID); + $title = ($nd["title"] === "ILIAS" ? $dic->language()->txt("repository") : $nd["title"]); + $icon = ilUtil::img(ilObject::_getIcon(ilObject::_lookupObjId(1), "tiny")); + } catch (InvalidArgumentException $e) { + return ""; + } + + return $title . " - " . $dic->language()->txt("rep_main_page"); + }; + + $action = function () : string { + try { + $static_link = ilLink::_getStaticLink(1, 'root', true); + } catch (InvalidArgumentException $e) { + return ""; + } + + return $static_link; + }; + + $entries[] = $this->mainmenu->link($this->if->identifier('rep_main_page')) + ->withTitle($title()) + ->withAction($action()) + ->withParent($this->getTopItem()); + + // LastVisited + $links = function () : array { + $items = []; + if (isset($this->dic['ilNavigationHistory'])) { + $items = $this->dic['ilNavigationHistory']->getItems(); + } + $links = []; + reset($items); + $cnt = 0; + $first = true; + + foreach ($items as $k => $item) { + if ($cnt >= 10) { + break; + } + + if (!isset($item["ref_id"]) || !isset($_GET["ref_id"]) + || ($item["ref_id"] != $_GET["ref_id"] || !$first) + ) { // do not list current item + $obj_id = ilObject::_lookupObjId($item["ref_id"]); + $icon = ilUtil::img(ilObject::_getIcon($obj_id, "tiny")); + $ititle = ilUtil::shortenText(strip_tags($item["title"]), 50, true); // #11023 + $links[] = $this->mainmenu->link($this->if->identifier('last_visited_' . $obj_id)) + ->withTitle($icon . " " . $ititle) + ->withAction($item["link"]); + } + $first = false; + } + + return $links; + }; + $entries[] = $this->mainmenu->linkList($this->if->identifier('last_visited')) + ->withLinks($links) + ->withTitle($this->dic->language()->txt('last_visited')) + ->withParent($this->getTopItem())->withVisibilityCallable( + function () use ($dic) { + return ($dic->user()->getId() != ANONYMOUS_USER_ID); + } + ); + + return $entries; + } } diff --git a/Services/Repository/classes/class.ilRepositoryObjectPlugin.php b/Services/Repository/classes/class.ilRepositoryObjectPlugin.php index 942703752491f94c814c6c39b8d01e76cf008b3d..39408d5916de758bf5fee98ee84b6448f0e81280 100644 --- a/Services/Repository/classes/class.ilRepositoryObjectPlugin.php +++ b/Services/Repository/classes/class.ilRepositoryObjectPlugin.php @@ -12,255 +12,248 @@ include_once("./Services/Component/classes/class.ilPlugin.php"); */ abstract class ilRepositoryObjectPlugin extends ilPlugin { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; - /** - * Constructor - */ - function __construct() - { - global $DIC; - parent::__construct(); + /** + * Constructor + */ + public function __construct() + { + global $DIC; + parent::__construct(); - $this->db = $DIC->database(); - } + $this->db = $DIC->database(); + } - /** - * Get Component Type - * - * @return string Component Type - */ - function getComponentType() - { - return IL_COMP_SERVICE; - } - - /** - * Get Component Name. - * - * @return string Component Name - */ - function getComponentName() - { - return "Repository"; - } + /** + * Get Component Type + * + * @return string Component Type + */ + public function getComponentType() + { + return IL_COMP_SERVICE; + } + + /** + * Get Component Name. + * + * @return string Component Name + */ + public function getComponentName() + { + return "Repository"; + } - /** - * Get Slot Name. - * - * @return string Slot Name - */ - function getSlot() - { - return "RepositoryObject"; - } + /** + * Get Slot Name. + * + * @return string Slot Name + */ + public function getSlot() + { + return "RepositoryObject"; + } - /** - * Get Slot ID. - * - * @return string Slot Id - */ - function getSlotId() - { - return "robj"; - } + /** + * Get Slot ID. + * + * @return string Slot Id + */ + public function getSlotId() + { + return "robj"; + } - /** - * Object initialization done by slot. - */ - protected function slotInit() - { - // nothing to do here - } - - /** - * Get Icon - */ - static function _getIcon($a_type, $a_size) - { - return ilPlugin::_getImagePath(IL_COMP_SERVICE, "Repository", "robj", - ilPlugin::lookupNameForId(IL_COMP_SERVICE, "Repository", "robj",$a_type), - "icon_".$a_type.".svg"); - } - - /** - * Get class name - */ - static function _getName($a_id) - { - $name = ilPlugin::lookupNameForId(IL_COMP_SERVICE, "Repository", "robj",$a_id); - if ($name != "") - { - return $name; - } - } - - /** - * Before activation processing - */ - protected function beforeActivation() - { - $ilDB = $this->db; - - // before activating, we ensure, that the type exists in the ILIAS - // object database and that all permissions exist - $type = $this->getId(); - - if (substr($type, 0, 1) != "x") - { - throw new ilPluginException("Object plugin type must start with an x. Current type is ".$type."."); - } - - // check whether type exists in object data, if not, create the type - $set = $ilDB->query("SELECT * FROM object_data ". - " WHERE type = ".$ilDB->quote("typ", "text"). - " AND title = ".$ilDB->quote($type, "text") - ); - if ($rec = $ilDB->fetchAssoc($set)) - { - $t_id = $rec["obj_id"]; - } - else - { - $t_id = $ilDB->nextId("object_data"); - $ilDB->manipulate("INSERT INTO object_data ". - "(obj_id, type, title, description, owner, create_date, last_update) VALUES (". - $ilDB->quote($t_id, "integer").",". - $ilDB->quote("typ", "text").",". - $ilDB->quote($type, "text").",". - $ilDB->quote("Plugin ".$this->getPluginName(), "text").",". - $ilDB->quote(-1, "integer").",". - $ilDB->quote(ilUtil::now(), "timestamp").",". - $ilDB->quote(ilUtil::now(), "timestamp"). - ")"); - } + /** + * Object initialization done by slot. + */ + protected function slotInit() + { + // nothing to do here + } + + /** + * Get Icon + */ + public static function _getIcon($a_type, $a_size) + { + return ilPlugin::_getImagePath( + IL_COMP_SERVICE, + "Repository", + "robj", + ilPlugin::lookupNameForId(IL_COMP_SERVICE, "Repository", "robj", $a_type), + "icon_" . $a_type . ".svg" + ); + } + + /** + * Get class name + */ + public static function _getName($a_id) + { + $name = ilPlugin::lookupNameForId(IL_COMP_SERVICE, "Repository", "robj", $a_id); + if ($name != "") { + return $name; + } + } + + /** + * Before activation processing + */ + protected function beforeActivation() + { + $ilDB = $this->db; + + // before activating, we ensure, that the type exists in the ILIAS + // object database and that all permissions exist + $type = $this->getId(); + + if (substr($type, 0, 1) != "x") { + throw new ilPluginException("Object plugin type must start with an x. Current type is " . $type . "."); + } + + // check whether type exists in object data, if not, create the type + $set = $ilDB->query( + "SELECT * FROM object_data " . + " WHERE type = " . $ilDB->quote("typ", "text") . + " AND title = " . $ilDB->quote($type, "text") + ); + if ($rec = $ilDB->fetchAssoc($set)) { + $t_id = $rec["obj_id"]; + } else { + $t_id = $ilDB->nextId("object_data"); + $ilDB->manipulate("INSERT INTO object_data " . + "(obj_id, type, title, description, owner, create_date, last_update) VALUES (" . + $ilDB->quote($t_id, "integer") . "," . + $ilDB->quote("typ", "text") . "," . + $ilDB->quote($type, "text") . "," . + $ilDB->quote("Plugin " . $this->getPluginName(), "text") . "," . + $ilDB->quote(-1, "integer") . "," . + $ilDB->quote(ilUtil::now(), "timestamp") . "," . + $ilDB->quote(ilUtil::now(), "timestamp") . + ")"); + } - // add rbac operations - // 1: edit_permissions, 2: visible, 3: read, 4:write, 6:delete - $ops = array(1, 2, 3, 4, 6); - if ($this->allowCopy()) - { - $ops[] = ilRbacReview::_getOperationIdByName("copy"); - } - foreach ($ops as $op) - { - // check whether type exists in object data, if not, create the type - $set = $ilDB->query("SELECT * FROM rbac_ta ". - " WHERE typ_id = ".$ilDB->quote($t_id, "integer"). - " AND ops_id = ".$ilDB->quote($op, "integer") - ); - if (!$ilDB->fetchAssoc($set)) - { - $ilDB->manipulate("INSERT INTO rbac_ta ". - "(typ_id, ops_id) VALUES (". - $ilDB->quote($t_id, "integer").",". - $ilDB->quote($op, "integer"). - ")"); - } - } - - // now add creation permission, if not existing - $set = $ilDB->query("SELECT * FROM rbac_operations ". - " WHERE class = ".$ilDB->quote("create", "text"). - " AND operation = ".$ilDB->quote("create_".$type, "text") - ); - if ($rec = $ilDB->fetchAssoc($set)) - { - $create_ops_id = $rec["ops_id"]; - } - else - { - $create_ops_id = $ilDB->nextId("rbac_operations"); - $ilDB->manipulate("INSERT INTO rbac_operations ". - "(ops_id, operation, description, class) VALUES (". - $ilDB->quote($create_ops_id, "integer").",". - $ilDB->quote("create_".$type, "text").",". - $ilDB->quote("create ".$type, "text").",". - $ilDB->quote("create", "text"). - ")"); - } - - // assign creation operation to root, cat, crs, grp and fold - $par_types = $this->getParentTypes(); - foreach ($par_types as $par_type) - { - $set = $ilDB->query("SELECT obj_id FROM object_data ". - " WHERE type = ".$ilDB->quote("typ", "text"). - " AND title = ".$ilDB->quote($par_type, "text") - ); - if ($rec = $ilDB->fetchAssoc($set)) - { - if ($rec["obj_id"] > 0) - { - $set = $ilDB->query("SELECT * FROM rbac_ta ". - " WHERE typ_id = ".$ilDB->quote($rec["obj_id"], "integer"). - " AND ops_id = ".$ilDB->quote($create_ops_id, "integer") - ); - if (!$ilDB->fetchAssoc($set)) - { - $ilDB->manipulate("INSERT INTO rbac_ta ". - "(typ_id, ops_id) VALUES (". - $ilDB->quote($rec["obj_id"], "integer").",". - $ilDB->quote($create_ops_id, "integer"). - ")"); - } - } - } - } - - return true; - } - - protected function beforeUninstallCustom() - { - // plugin-specific - // false would indicate that anything went wrong - return true; - } - - abstract protected function uninstallCustom(); - - final protected function beforeUninstall() - { - if($this->beforeUninstallCustom()) - { - include_once "Services/Repository/classes/class.ilRepUtil.php"; - $rep_util = new ilRepUtil(); - $rep_util->deleteObjectType($this->getId()); - - // custom database tables may be needed by plugin repository object - $this->uninstallCustom(); + // add rbac operations + // 1: edit_permissions, 2: visible, 3: read, 4:write, 6:delete + $ops = array(1, 2, 3, 4, 6); + if ($this->allowCopy()) { + $ops[] = ilRbacReview::_getOperationIdByName("copy"); + } + foreach ($ops as $op) { + // check whether type exists in object data, if not, create the type + $set = $ilDB->query( + "SELECT * FROM rbac_ta " . + " WHERE typ_id = " . $ilDB->quote($t_id, "integer") . + " AND ops_id = " . $ilDB->quote($op, "integer") + ); + if (!$ilDB->fetchAssoc($set)) { + $ilDB->manipulate("INSERT INTO rbac_ta " . + "(typ_id, ops_id) VALUES (" . + $ilDB->quote($t_id, "integer") . "," . + $ilDB->quote($op, "integer") . + ")"); + } + } + + // now add creation permission, if not existing + $set = $ilDB->query( + "SELECT * FROM rbac_operations " . + " WHERE class = " . $ilDB->quote("create", "text") . + " AND operation = " . $ilDB->quote("create_" . $type, "text") + ); + if ($rec = $ilDB->fetchAssoc($set)) { + $create_ops_id = $rec["ops_id"]; + } else { + $create_ops_id = $ilDB->nextId("rbac_operations"); + $ilDB->manipulate("INSERT INTO rbac_operations " . + "(ops_id, operation, description, class) VALUES (" . + $ilDB->quote($create_ops_id, "integer") . "," . + $ilDB->quote("create_" . $type, "text") . "," . + $ilDB->quote("create " . $type, "text") . "," . + $ilDB->quote("create", "text") . + ")"); + } + + // assign creation operation to root, cat, crs, grp and fold + $par_types = $this->getParentTypes(); + foreach ($par_types as $par_type) { + $set = $ilDB->query( + "SELECT obj_id FROM object_data " . + " WHERE type = " . $ilDB->quote("typ", "text") . + " AND title = " . $ilDB->quote($par_type, "text") + ); + if ($rec = $ilDB->fetchAssoc($set)) { + if ($rec["obj_id"] > 0) { + $set = $ilDB->query( + "SELECT * FROM rbac_ta " . + " WHERE typ_id = " . $ilDB->quote($rec["obj_id"], "integer") . + " AND ops_id = " . $ilDB->quote($create_ops_id, "integer") + ); + if (!$ilDB->fetchAssoc($set)) { + $ilDB->manipulate("INSERT INTO rbac_ta " . + "(typ_id, ops_id) VALUES (" . + $ilDB->quote($rec["obj_id"], "integer") . "," . + $ilDB->quote($create_ops_id, "integer") . + ")"); + } + } + } + } + + return true; + } + + protected function beforeUninstallCustom() + { + // plugin-specific + // false would indicate that anything went wrong + return true; + } + + abstract protected function uninstallCustom(); + + final protected function beforeUninstall() + { + if ($this->beforeUninstallCustom()) { + include_once "Services/Repository/classes/class.ilRepUtil.php"; + $rep_util = new ilRepUtil(); + $rep_util->deleteObjectType($this->getId()); + + // custom database tables may be needed by plugin repository object + $this->uninstallCustom(); - return true; - } - return false; - } + return true; + } + return false; + } - /** - * @return string[] - */ - public function getParentTypes() { - $par_types = array("root", "cat", "crs", "grp", "fold"); - return $par_types; - } + /** + * @return string[] + */ + public function getParentTypes() + { + $par_types = array("root", "cat", "crs", "grp", "fold"); + return $par_types; + } - /** - * decides if this repository plugin can be copied - * - * @return bool - */ - public function allowCopy() - { - return false; - } + /** + * decides if this repository plugin can be copied + * + * @return bool + */ + public function allowCopy() + { + return false; + } } -?> diff --git a/Services/Repository/classes/class.ilRepositoryObjectPluginSlot.php b/Services/Repository/classes/class.ilRepositoryObjectPluginSlot.php index 94adad3bee0cb9fba5e5648b935db85682ea81a1..a8f783f608210d84affe7f435f4f0b73bf1829cf 100644 --- a/Services/Repository/classes/class.ilRepositoryObjectPluginSlot.php +++ b/Services/Repository/classes/class.ilRepositoryObjectPluginSlot.php @@ -10,85 +10,76 @@ */ class ilRepositoryObjectPluginSlot { - /** - * Adds objects that can be created to the add new object list array - */ - static function addCreatableSubObjects($a_obj_array) - { - global $DIC; + /** + * Adds objects that can be created to the add new object list array + */ + public static function addCreatableSubObjects($a_obj_array) + { + global $DIC; - $ilPluginAdmin = $DIC["ilPluginAdmin"]; - $pl_names = $ilPluginAdmin->getActivePluginsForSlot(IL_COMP_SERVICE, "Repository", "robj"); - foreach ($pl_names as $pl) - { - $pl_id = $ilPluginAdmin->getId(IL_COMP_SERVICE, "Repository", "robj", $pl); - if ($pl_id != "") - { - $a_obj_array[$pl_id] = array("name" => $pl_id, "lng" => $pl_id, "plugin" => true); - } - } + $ilPluginAdmin = $DIC["ilPluginAdmin"]; + $pl_names = $ilPluginAdmin->getActivePluginsForSlot(IL_COMP_SERVICE, "Repository", "robj"); + foreach ($pl_names as $pl) { + $pl_id = $ilPluginAdmin->getId(IL_COMP_SERVICE, "Repository", "robj", $pl); + if ($pl_id != "") { + $a_obj_array[$pl_id] = array("name" => $pl_id, "lng" => $pl_id, "plugin" => true); + } + } - return $a_obj_array; - } - - /** - * Checks whether a repository type is a plugin or not - */ - static function isTypePlugin($a_type, $a_active_status = true) - { - global $DIC; + return $a_obj_array; + } + + /** + * Checks whether a repository type is a plugin or not + */ + public static function isTypePlugin($a_type, $a_active_status = true) + { + global $DIC; - $ilPluginAdmin = $DIC["ilPluginAdmin"]; - - include_once("./Services/Component/classes/class.ilPlugin.php"); - $pname = ilPlugin::lookupNameForId(IL_COMP_SERVICE, "Repository", "robj", $a_type); - if ($pname == "") - { - return false; - } + $ilPluginAdmin = $DIC["ilPluginAdmin"]; + + include_once("./Services/Component/classes/class.ilPlugin.php"); + $pname = ilPlugin::lookupNameForId(IL_COMP_SERVICE, "Repository", "robj", $a_type); + if ($pname == "") { + return false; + } - if ($ilPluginAdmin->exists(IL_COMP_SERVICE, "Repository", "robj", $pname)) - { - if (!$a_active_status || - $ilPluginAdmin->isActive(IL_COMP_SERVICE, "Repository", "robj", $pname)) - { - return true; - } - } - return false; - } - - /** - * Check whether a repository type is a plugin which has active learning progress - * - * @param string $a_type - * @param bool $a_active_status - * @return boolean - */ - static function isTypePluginWithLP($a_type, $a_active_status = true) - { - global $DIC; + if ($ilPluginAdmin->exists(IL_COMP_SERVICE, "Repository", "robj", $pname)) { + if (!$a_active_status || + $ilPluginAdmin->isActive(IL_COMP_SERVICE, "Repository", "robj", $pname)) { + return true; + } + } + return false; + } + + /** + * Check whether a repository type is a plugin which has active learning progress + * + * @param string $a_type + * @param bool $a_active_status + * @return boolean + */ + public static function isTypePluginWithLP($a_type, $a_active_status = true) + { + global $DIC; - $ilPluginAdmin = $DIC["ilPluginAdmin"]; - - include_once("./Services/Component/classes/class.ilPlugin.php"); - $pname = ilPlugin::lookupNameForId(IL_COMP_SERVICE, "Repository", "robj", $a_type); - if ($pname == "") - { - return false; - } + $ilPluginAdmin = $DIC["ilPluginAdmin"]; + + include_once("./Services/Component/classes/class.ilPlugin.php"); + $pname = ilPlugin::lookupNameForId(IL_COMP_SERVICE, "Repository", "robj", $a_type); + if ($pname == "") { + return false; + } - if ($ilPluginAdmin->exists(IL_COMP_SERVICE, "Repository", "robj", $pname)) - { - if (!$a_active_status || - $ilPluginAdmin->isActive(IL_COMP_SERVICE, "Repository", "robj", $pname)) - { - if($ilPluginAdmin->hasLearningProgress(IL_COMP_SERVICE, "Repository", "robj", $pname)) - { - return true; - } - } - } - return false; - } + if ($ilPluginAdmin->exists(IL_COMP_SERVICE, "Repository", "robj", $pname)) { + if (!$a_active_status || + $ilPluginAdmin->isActive(IL_COMP_SERVICE, "Repository", "robj", $pname)) { + if ($ilPluginAdmin->hasLearningProgress(IL_COMP_SERVICE, "Repository", "robj", $pname)) { + return true; + } + } + } + return false; + } } diff --git a/Services/Repository/classes/class.ilRepositorySelectorExplorerGUI.php b/Services/Repository/classes/class.ilRepositorySelectorExplorerGUI.php index b702c7b2b6f3db91aca00e50f0639e7b0deb0758..e7954846db151766f0c195cf2f37e1499c3cfca3 100644 --- a/Services/Repository/classes/class.ilRepositorySelectorExplorerGUI.php +++ b/Services/Repository/classes/class.ilRepositorySelectorExplorerGUI.php @@ -17,488 +17,457 @@ include_once("./Services/UIComponent/Explorer2/classes/class.ilTreeExplorerGUI.p */ class ilRepositorySelectorExplorerGUI extends ilTreeExplorerGUI { - /** - * @var ilObjectDefinition - */ - protected $obj_definition; - - /** - * @var ilLanguage - */ - protected $lng; - - protected $type_grps = array(); - protected $session_materials = array(); - protected $highlighted_node = null; - protected $clickable_types = array(); - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var callable - */ - protected $nc_modifier = null; - - /** - * @var object - */ - protected $selection_gui = null; - - /** - * @var string - */ - protected $selection_par; - - /** - * @var string - */ - protected $selection_cmd; - - /** - * Constructor - * - * @param object $a_parent_obj parent gui object - * @param string $a_parent_cmd parent cmd that renders the explorer - * @param object/string $a_selection_gui gui class that should be called for the selection command - * @param string $a_selection_cmd selection command - * @param string $a_selection_par selection parameter - */ - public function __construct($a_parent_obj, $a_parent_cmd, $a_selection_gui = null, $a_selection_cmd = "selectObject", - $a_selection_par = "sel_ref_id", $a_id = "rep_exp_sel") - { - global $DIC; - - $this->tree = $DIC->repositoryTree(); - $this->obj_definition = $DIC["objDefinition"]; - $this->lng = $DIC->language(); - $tree = $DIC->repositoryTree(); - $ilSetting = $DIC->settings(); - $objDefinition = $DIC["objDefinition"]; - - $this->access = $DIC->access(); - $this->ctrl = $DIC->ctrl(); - - if (is_null($a_selection_gui)) - { - $a_selection_gui = $a_parent_obj; - } - - $this->selection_gui = is_object($a_selection_gui) - ? strtolower(get_class($a_selection_gui)) - : strtolower($a_selection_gui); - $this->selection_cmd = $a_selection_cmd; - $this->selection_par = $a_selection_par; - parent::__construct($a_id, $a_parent_obj, $a_parent_cmd, $tree); - - $this->setSkipRootNode(false); - $this->setAjax(true); - $this->setOrderField("title"); - - // per default: all object types, except item groups - $white = array(); - foreach ($objDefinition->getSubObjectsRecursively("root") as $rtype) - { - if ($rtype["name"] != "itgr" && !$objDefinition->isSideBlock($rtype["name"])) - { - $white[] = $rtype["name"]; - } - } - $this->setTypeWhiteList($white); - - // always open the path to the current ref id - $this->setPathOpen((int) $this->tree->readRootId()); - if ((int) $_GET["ref_id"] > 0) - { - $this->setPathOpen((int) $_GET["ref_id"]); - } - $this->setChildLimit((int) $ilSetting->get("rep_tree_limit_number")); - } - - /** - * Set node content modifier - * - * @param callable $a_val - */ - function setNodeContentModifier(callable $a_val) - { - $this->nc_modifier = $a_val; - } - - /** - * Get node content modifier - * - * @return callable - */ - function getNodeContentModifier() - { - return $this->nc_modifier; - } - - /** - * Get node content - * - * @param array $a_node node data - * @return string content - */ - function getNodeContent($a_node) - { - $lng = $this->lng; - - $c = $this->getNodeContentModifier(); - if (is_callable($c)) - { - return $c($a_node); - } - - $title = $a_node["title"]; - if ($a_node["child"] == $this->getNodeId($this->getRootNode())) - { - if ($title == "ILIAS") - { - $title = $lng->txt("repository"); - } - } - - return $title; - } - - /** - * Get node icon - * - * @param array $a_node node data - * @return string icon path - */ - function getNodeIcon($a_node) - { - $obj_id = ilObject::_lookupObjId($a_node["child"]); - return ilObject::_getIcon($obj_id, "tiny", $a_node["type"]); - } - - /** - * Get node icon alt text - * - * @param array $a_node node data - * @return string alt text - */ - function getNodeIconAlt($a_node) - { - $lng = $this->lng; - - if ($a_node["child"] == $this->getNodeId($this->getRootNode())) - { - $title = $a_node["title"]; - if ($title == "ILIAS") - { - $title = $lng->txt("repository"); - } - return $lng->txt("icon")." ".$title; - } - - - return parent::getNodeIconAlt($a_node); - } - - /** - * Is node highlighted? - * - * @param mixed $a_node node object/array - * @return boolean node visible true/false - */ - function isNodeHighlighted($a_node) - { - if($this->getHighlightedNode()) - { - if($this->getHighlightedNode() == $a_node["child"]) - { - return true; - } - return false; - } - - if ($a_node["child"] == $_GET["ref_id"] || - ($_GET["ref_id"] == "" && $a_node["child"] == $this->getNodeId($this->getRootNode()))) - { - return true; - } - return false; - } - - /** - * Get href for node - * - * @param mixed $a_node node object/array - * @return string href attribute - */ - function getNodeHref($a_node) - { - $ilCtrl = $this->ctrl; - - if ($this->select_postvar == "") - { - $ilCtrl->setParameterByClass($this->selection_gui, $this->selection_par, $a_node["child"]); - $link = $ilCtrl->getLinkTargetByClass($this->selection_gui, $this->selection_cmd); - $ilCtrl->setParameterByClass($this->selection_gui, $this->selection_par, ""); - } - else - { - return "#"; - } - - return $link; - } - - /** - * Is node visible - * - * @param array $a_node node data - * @return bool visible true/false - */ - function isNodeVisible($a_node) - { - $ilAccess = $this->access; - - if (!$ilAccess->checkAccess('visible', '', $a_node["child"])) - { - return false; - } - - return true; - } - - /** - * Sort childs - * - * @param array $a_childs array of child nodes - * @param int $a_parent_node_id parent node id - * @return array array of childs nodes - */ - function sortChilds($a_childs, $a_parent_node_id) - { - $objDefinition = $this->obj_definition; - - $parent_obj_id = ilObject::_lookupObjId($a_parent_node_id); - - if ($parent_obj_id > 0) - { - $parent_type = ilObject::_lookupType($parent_obj_id); - } - else - { - $parent_type = "dummy"; - $this->type_grps["dummy"] = array("root" => "dummy"); - } - - if (empty($this->type_grps[$parent_type])) - { - $this->type_grps[$parent_type] = - $objDefinition->getGroupedRepositoryObjectTypes($parent_type); - } - $group = array(); - - foreach ($a_childs as $child) - { - $g = $objDefinition->getGroupOfObj($child["type"]); - if ($g == "") - { - $g = $child["type"]; - } - $group[$g][] = $child; - } - - // #14587 - $objDefinition->getGroupedRepositoryObjectTypes does NOT include side blocks! - $wl = $this->getTypeWhiteList(); - if(is_array($wl) && in_array("poll", $wl)) - { - $this->type_grps[$parent_type]["poll"] = array(); - } - - $childs = array(); - foreach ($this->type_grps[$parent_type] as $t => $g) - { - if (is_array($group[$t])) - { - // do we have to sort this group?? - include_once("./Services/Container/classes/class.ilContainer.php"); - include_once("./Services/Container/classes/class.ilContainerSorting.php"); - $sort = ilContainerSorting::_getInstance($parent_obj_id); - $group = $sort->sortItems($group); - - // need extra session sorting here - if ($t == "sess") - { - - } - - foreach ($group[$t] as $k => $item) - { - $childs[] = $item; - } - } - } - - return $childs; - } - - /** - * Get childs of node - * - * @param int $a_parent_node_id node id - * @return array childs array - */ - function getChildsOfNode($a_parent_node_id) - { - $ilAccess = $this->access; - - if (!$ilAccess->checkAccess("read", "", $a_parent_node_id)) - { - return array(); - } - - return parent::getChildsOfNode($a_parent_node_id); - } - - /** - * Is node clickable? - * - * @param array $a_node node data - * @return boolean node clickable true/false - */ - function isNodeClickable($a_node) - { - $ilAccess = $this->access; - - if ($this->select_postvar != "") - { - // return false; #14354 - } - - if(!$ilAccess->hasUserRBACorAnyPositionAccess("read",$a_node["child"])) { - return false; - } - - if(is_array($this->getClickableTypes()) && count($this->getClickableTypes())>0) - { - return in_array($a_node["type"], $this->getClickableTypes()); - } - - return true; - } - - /** - * set an alternate highlighted node if $_GET["ref_id"] is not set or wrong - * - * @param int $a_value ref_id - */ - public function setHighlightedNode($a_value) - { - $this->highlighted_node = $a_value; - } - - /** - * get an alternate highlighted node if $_GET["ref_id"] is not set or wrong - * Returns null if not set - * - * @return mixed ref_id - */ - public function getHighlightedNode() - { - return $this->highlighted_node; - } - - /** - * set Whitelist for clickable items - * - * @param array/string $a_types array type - */ - function setClickableTypes($a_types) - { - if(!is_array($a_types)) - { - $a_types = array($a_types); - } - $this->clickable_types = $a_types; - } - - /** - * get whitelist for clickable items - * - * @return array types - */ - function getClickableTypes() - { - return (array)$this->clickable_types; - } - - /** - * Get HTML - * - * @param - * @return - */ - /* function getHTML() - { - global $ilCtrl, $tpl; - - $add = ""; - if ($ilCtrl->isAsynch()) - { - $add = $this->getOnLoadCode(); - } - else - { - $tpl->addOnloadCode($this->getOnLoadCode()); - } - - return parent::getHTML().$add; - } - */ - - /** - * set Whitelist for clickable items - * - * @param array/string $a_types array type - */ - function setSelectableTypes($a_types) - { - if(!is_array($a_types)) - { - $a_types = array($a_types); - } - $this->selectable_types = $a_types; - } - - /** - * get whitelist for clickable items - * - * @return array types - */ - function getSelectableTypes() - { - return (array)$this->selectable_types; - } - - /** - * Is node selectable? - * - * @param mixed $a_node node object/array - * @return boolean node selectable true/false - */ - protected function isNodeSelectable($a_node) - { - if(count($this->getSelectableTypes())) - { - return in_array($a_node['type'],$this->getSelectableTypes() ); - } - return true; - } + /** + * @var ilObjectDefinition + */ + protected $obj_definition; + + /** + * @var ilLanguage + */ + protected $lng; + + protected $type_grps = array(); + protected $session_materials = array(); + protected $highlighted_node = null; + protected $clickable_types = array(); + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var callable + */ + protected $nc_modifier = null; + + /** + * @var object + */ + protected $selection_gui = null; + + /** + * @var string + */ + protected $selection_par; + + /** + * @var string + */ + protected $selection_cmd; + + /** + * Constructor + * + * @param object $a_parent_obj parent gui object + * @param string $a_parent_cmd parent cmd that renders the explorer + * @param object/string $a_selection_gui gui class that should be called for the selection command + * @param string $a_selection_cmd selection command + * @param string $a_selection_par selection parameter + */ + public function __construct( + $a_parent_obj, + $a_parent_cmd, + $a_selection_gui = null, + $a_selection_cmd = "selectObject", + $a_selection_par = "sel_ref_id", + $a_id = "rep_exp_sel" + ) { + global $DIC; + + $this->tree = $DIC->repositoryTree(); + $this->obj_definition = $DIC["objDefinition"]; + $this->lng = $DIC->language(); + $tree = $DIC->repositoryTree(); + $ilSetting = $DIC->settings(); + $objDefinition = $DIC["objDefinition"]; + + $this->access = $DIC->access(); + $this->ctrl = $DIC->ctrl(); + + if (is_null($a_selection_gui)) { + $a_selection_gui = $a_parent_obj; + } + + $this->selection_gui = is_object($a_selection_gui) + ? strtolower(get_class($a_selection_gui)) + : strtolower($a_selection_gui); + $this->selection_cmd = $a_selection_cmd; + $this->selection_par = $a_selection_par; + parent::__construct($a_id, $a_parent_obj, $a_parent_cmd, $tree); + + $this->setSkipRootNode(false); + $this->setAjax(true); + $this->setOrderField("title"); + + // per default: all object types, except item groups + $white = array(); + foreach ($objDefinition->getSubObjectsRecursively("root") as $rtype) { + if ($rtype["name"] != "itgr" && !$objDefinition->isSideBlock($rtype["name"])) { + $white[] = $rtype["name"]; + } + } + $this->setTypeWhiteList($white); + + // always open the path to the current ref id + $this->setPathOpen((int) $this->tree->readRootId()); + if ((int) $_GET["ref_id"] > 0) { + $this->setPathOpen((int) $_GET["ref_id"]); + } + $this->setChildLimit((int) $ilSetting->get("rep_tree_limit_number")); + } + + /** + * Set node content modifier + * + * @param callable $a_val + */ + public function setNodeContentModifier(callable $a_val) + { + $this->nc_modifier = $a_val; + } + + /** + * Get node content modifier + * + * @return callable + */ + public function getNodeContentModifier() + { + return $this->nc_modifier; + } + + /** + * Get node content + * + * @param array $a_node node data + * @return string content + */ + public function getNodeContent($a_node) + { + $lng = $this->lng; + + $c = $this->getNodeContentModifier(); + if (is_callable($c)) { + return $c($a_node); + } + + $title = $a_node["title"]; + if ($a_node["child"] == $this->getNodeId($this->getRootNode())) { + if ($title == "ILIAS") { + $title = $lng->txt("repository"); + } + } + + return $title; + } + + /** + * Get node icon + * + * @param array $a_node node data + * @return string icon path + */ + public function getNodeIcon($a_node) + { + $obj_id = ilObject::_lookupObjId($a_node["child"]); + return ilObject::_getIcon($obj_id, "tiny", $a_node["type"]); + } + + /** + * Get node icon alt text + * + * @param array $a_node node data + * @return string alt text + */ + public function getNodeIconAlt($a_node) + { + $lng = $this->lng; + + if ($a_node["child"] == $this->getNodeId($this->getRootNode())) { + $title = $a_node["title"]; + if ($title == "ILIAS") { + $title = $lng->txt("repository"); + } + return $lng->txt("icon") . " " . $title; + } + + + return parent::getNodeIconAlt($a_node); + } + + /** + * Is node highlighted? + * + * @param mixed $a_node node object/array + * @return boolean node visible true/false + */ + public function isNodeHighlighted($a_node) + { + if ($this->getHighlightedNode()) { + if ($this->getHighlightedNode() == $a_node["child"]) { + return true; + } + return false; + } + + if ($a_node["child"] == $_GET["ref_id"] || + ($_GET["ref_id"] == "" && $a_node["child"] == $this->getNodeId($this->getRootNode()))) { + return true; + } + return false; + } + + /** + * Get href for node + * + * @param mixed $a_node node object/array + * @return string href attribute + */ + public function getNodeHref($a_node) + { + $ilCtrl = $this->ctrl; + + if ($this->select_postvar == "") { + $ilCtrl->setParameterByClass($this->selection_gui, $this->selection_par, $a_node["child"]); + $link = $ilCtrl->getLinkTargetByClass($this->selection_gui, $this->selection_cmd); + $ilCtrl->setParameterByClass($this->selection_gui, $this->selection_par, ""); + } else { + return "#"; + } + + return $link; + } + + /** + * Is node visible + * + * @param array $a_node node data + * @return bool visible true/false + */ + public function isNodeVisible($a_node) + { + $ilAccess = $this->access; + + if (!$ilAccess->checkAccess('visible', '', $a_node["child"])) { + return false; + } + + return true; + } + + /** + * Sort childs + * + * @param array $a_childs array of child nodes + * @param int $a_parent_node_id parent node id + * @return array array of childs nodes + */ + public function sortChilds($a_childs, $a_parent_node_id) + { + $objDefinition = $this->obj_definition; + + $parent_obj_id = ilObject::_lookupObjId($a_parent_node_id); + + if ($parent_obj_id > 0) { + $parent_type = ilObject::_lookupType($parent_obj_id); + } else { + $parent_type = "dummy"; + $this->type_grps["dummy"] = array("root" => "dummy"); + } + + if (empty($this->type_grps[$parent_type])) { + $this->type_grps[$parent_type] = + $objDefinition->getGroupedRepositoryObjectTypes($parent_type); + } + $group = array(); + + foreach ($a_childs as $child) { + $g = $objDefinition->getGroupOfObj($child["type"]); + if ($g == "") { + $g = $child["type"]; + } + $group[$g][] = $child; + } + + // #14587 - $objDefinition->getGroupedRepositoryObjectTypes does NOT include side blocks! + $wl = $this->getTypeWhiteList(); + if (is_array($wl) && in_array("poll", $wl)) { + $this->type_grps[$parent_type]["poll"] = array(); + } + + $childs = array(); + foreach ($this->type_grps[$parent_type] as $t => $g) { + if (is_array($group[$t])) { + // do we have to sort this group?? + include_once("./Services/Container/classes/class.ilContainer.php"); + include_once("./Services/Container/classes/class.ilContainerSorting.php"); + $sort = ilContainerSorting::_getInstance($parent_obj_id); + $group = $sort->sortItems($group); + + // need extra session sorting here + if ($t == "sess") { + } + + foreach ($group[$t] as $k => $item) { + $childs[] = $item; + } + } + } + + return $childs; + } + + /** + * Get childs of node + * + * @param int $a_parent_node_id node id + * @return array childs array + */ + public function getChildsOfNode($a_parent_node_id) + { + $ilAccess = $this->access; + + if (!$ilAccess->checkAccess("read", "", $a_parent_node_id)) { + return array(); + } + + return parent::getChildsOfNode($a_parent_node_id); + } + + /** + * Is node clickable? + * + * @param array $a_node node data + * @return boolean node clickable true/false + */ + public function isNodeClickable($a_node) + { + $ilAccess = $this->access; + + if ($this->select_postvar != "") { + // return false; #14354 + } + + if (!$ilAccess->hasUserRBACorAnyPositionAccess("read", $a_node["child"])) { + return false; + } + + if (is_array($this->getClickableTypes()) && count($this->getClickableTypes())>0) { + return in_array($a_node["type"], $this->getClickableTypes()); + } + + return true; + } + + /** + * set an alternate highlighted node if $_GET["ref_id"] is not set or wrong + * + * @param int $a_value ref_id + */ + public function setHighlightedNode($a_value) + { + $this->highlighted_node = $a_value; + } + + /** + * get an alternate highlighted node if $_GET["ref_id"] is not set or wrong + * Returns null if not set + * + * @return mixed ref_id + */ + public function getHighlightedNode() + { + return $this->highlighted_node; + } + + /** + * set Whitelist for clickable items + * + * @param array/string $a_types array type + */ + public function setClickableTypes($a_types) + { + if (!is_array($a_types)) { + $a_types = array($a_types); + } + $this->clickable_types = $a_types; + } + + /** + * get whitelist for clickable items + * + * @return array types + */ + public function getClickableTypes() + { + return (array) $this->clickable_types; + } + + /** + * Get HTML + * + * @param + * @return + */ + /* function getHTML() + { + global $ilCtrl, $tpl; + + $add = ""; + if ($ilCtrl->isAsynch()) + { + $add = $this->getOnLoadCode(); + } + else + { + $tpl->addOnloadCode($this->getOnLoadCode()); + } + + return parent::getHTML().$add; + } + */ + + /** + * set Whitelist for clickable items + * + * @param array/string $a_types array type + */ + public function setSelectableTypes($a_types) + { + if (!is_array($a_types)) { + $a_types = array($a_types); + } + $this->selectable_types = $a_types; + } + + /** + * get whitelist for clickable items + * + * @return array types + */ + public function getSelectableTypes() + { + return (array) $this->selectable_types; + } + + /** + * Is node selectable? + * + * @param mixed $a_node node object/array + * @return boolean node selectable true/false + */ + protected function isNodeSelectable($a_node) + { + if (count($this->getSelectableTypes())) { + return in_array($a_node['type'], $this->getSelectableTypes()); + } + return true; + } } - -?> \ No newline at end of file diff --git a/Services/Repository/classes/class.ilRepositoryService.php b/Services/Repository/classes/class.ilRepositoryService.php index a29e35107e0cf937d7d2e7c4933510c7487cd809..e7bdd19fadd9e9ff47f142169cc1812696e07bfc 100755 --- a/Services/Repository/classes/class.ilRepositoryService.php +++ b/Services/Repository/classes/class.ilRepositoryService.php @@ -1,24 +1,24 @@ diff --git a/Services/Repository/classes/class.ilTestQuestionPoolSelectorExplorer.php b/Services/Repository/classes/class.ilTestQuestionPoolSelectorExplorer.php index 6b9e33b52b9235aff413cbc6dceb57fa2d0be97b..639905220794d78a32e416db31498a807b075548 100644 --- a/Services/Repository/classes/class.ilTestQuestionPoolSelectorExplorer.php +++ b/Services/Repository/classes/class.ilTestQuestionPoolSelectorExplorer.php @@ -10,54 +10,52 @@ require_once 'Services/Repository/classes/class.ilRepositorySelectorExplorerGUI. */ class ilTestQuestionPoolSelectorExplorer extends ilRepositorySelectorExplorerGUI { - protected $availableQuestionPools = array(); - - public function __construct($targetGUI, $roundtripCMD, $selectCMD) - { - parent::__construct($targetGUI, $roundtripCMD, $targetGUI, $selectCMD); - - $this->setTypeWhiteList(array('grp', 'cat', 'crs', 'fold', 'qpl')); - $this->setClickableTypes(array('qpl')); - $this->setSelectMode('', false); - $this->selection_par = 'quest_pool_ref'; - } - - public function getAvailableQuestionPools() - { - return $this->availableQuestionPools; - } - - public function setAvailableQuestionPools($availableQuestionPools) - { - $this->availableQuestionPools = $availableQuestionPools; - } - - public function isAvailableQuestionPool($qplRefId) - { - /* @var ilObjectDataCache $objCache */ - $objCache = isset($GLOBALS['DIC']) ? $GLOBALS['DIC']['ilObjDataCache'] : $GLOBALS['ilObjDataCache']; + protected $availableQuestionPools = array(); + + public function __construct($targetGUI, $roundtripCMD, $selectCMD) + { + parent::__construct($targetGUI, $roundtripCMD, $targetGUI, $selectCMD); + + $this->setTypeWhiteList(array('grp', 'cat', 'crs', 'fold', 'qpl')); + $this->setClickableTypes(array('qpl')); + $this->setSelectMode('', false); + $this->selection_par = 'quest_pool_ref'; + } + + public function getAvailableQuestionPools() + { + return $this->availableQuestionPools; + } + + public function setAvailableQuestionPools($availableQuestionPools) + { + $this->availableQuestionPools = $availableQuestionPools; + } + + public function isAvailableQuestionPool($qplRefId) + { + /* @var ilObjectDataCache $objCache */ + $objCache = isset($GLOBALS['DIC']) ? $GLOBALS['DIC']['ilObjDataCache'] : $GLOBALS['ilObjDataCache']; - $qplObjId = $objCache->lookupObjId($qplRefId); - return in_array($qplObjId, $this->getAvailableQuestionPools()); - } - - public function isNodeClickable($a_node) - { - if( $a_node['type'] != 'qpl' ) - { - return parent::isNodeClickable($a_node); - } - - return $this->isAvailableQuestionPool($a_node['child']); - } - - public function isNodeVisible($a_node) - { - if( $a_node['type'] != 'qpl' ) - { - return parent::isNodeVisible($a_node); - } - - return $this->isAvailableQuestionPool($a_node['child']); - } -} \ No newline at end of file + $qplObjId = $objCache->lookupObjId($qplRefId); + return in_array($qplObjId, $this->getAvailableQuestionPools()); + } + + public function isNodeClickable($a_node) + { + if ($a_node['type'] != 'qpl') { + return parent::isNodeClickable($a_node); + } + + return $this->isAvailableQuestionPool($a_node['child']); + } + + public function isNodeVisible($a_node) + { + if ($a_node['type'] != 'qpl') { + return parent::isNodeVisible($a_node); + } + + return $this->isAvailableQuestionPool($a_node['child']); + } +} diff --git a/Services/Repository/classes/class.ilTrashTableGUI.php b/Services/Repository/classes/class.ilTrashTableGUI.php index 6d1ce58f4348677b6183b889a6ee5fcc4e7478e5..d399f071894b7dabcc0d0154b5a18777ebb047dc 100644 --- a/Services/Repository/classes/class.ilTrashTableGUI.php +++ b/Services/Repository/classes/class.ilTrashTableGUI.php @@ -5,7 +5,7 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); require_once('./Services/Repository/classes/class.ilObjectPlugin.php'); /** -* TableGUI class for +* TableGUI class for * * @author Alex Killing * @version $Id$ @@ -14,83 +14,80 @@ require_once('./Services/Repository/classes/class.ilObjectPlugin.php'); */ class ilTrashTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * @var ilObjectDefinition - */ - protected $obj_definition; + /** + * @var ilObjectDefinition + */ + protected $obj_definition; - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd) - { - global $DIC; + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $this->obj_definition = $DIC["objDefinition"]; - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilAccess = $DIC->access(); - $lng = $DIC->language(); - - $this->ref_id = $a_ref_id; - - parent::__construct($a_parent_obj, $a_parent_cmd); - //$this->setTitle($lng->txt("")); - - $this->addColumn($this->lng->txt(""), "", "1", 1); - $this->addColumn($this->lng->txt("type"), "", "1"); - $this->addColumn($this->lng->txt("title"), "title"); - $this->addColumn($this->lng->txt("last_change"), "last_update"); - $this->setDefaultOrderField("title"); - $this->setDefaultOrderDirection("asc"); - - - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.trash_list_row.html", "Services/Repository"); - //$this->disable("footer"); - $this->setEnableTitle(true); - $this->setSelectAllCheckbox("trash_id[]"); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->obj_definition = $DIC["objDefinition"]; + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilAccess = $DIC->access(); + $lng = $DIC->language(); + + $this->ref_id = $a_ref_id; + + parent::__construct($a_parent_obj, $a_parent_cmd); + //$this->setTitle($lng->txt("")); + + $this->addColumn($this->lng->txt(""), "", "1", 1); + $this->addColumn($this->lng->txt("type"), "", "1"); + $this->addColumn($this->lng->txt("title"), "title"); + $this->addColumn($this->lng->txt("last_change"), "last_update"); + $this->setDefaultOrderField("title"); + $this->setDefaultOrderDirection("asc"); + + + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.trash_list_row.html", "Services/Repository"); + //$this->disable("footer"); + $this->setEnableTitle(true); + $this->setSelectAllCheckbox("trash_id[]"); - $this->addMultiCommand("undelete",$lng->txt("btn_undelete")); - $this->addMultiCommand("confirmRemoveFromSystem", $lng->txt("btn_remove_system")); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $objDefinition = $this->obj_definition; + $this->addMultiCommand("undelete", $lng->txt("btn_undelete")); + $this->addMultiCommand("confirmRemoveFromSystem", $lng->txt("btn_remove_system")); + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $objDefinition = $this->obj_definition; - $img = ilObject::_getIcon($a_set["obj_id"], "small", $a_set["type"]); - if (strlen($img) > 0) - { - $alt = ($objDefinition->isPlugin($a_set["type"])) - ? $lng->txt("icon")." ".ilObjectPlugin::lookupTxtById($a_set["type"], "obj_".$a_set["type"]) - : $lng->txt("icon")." ".$lng->txt("obj_".$a_set["type"]); - - $this->tpl->setVariable("IMG_TYPE", ilUtil::img($img, $alt)); - } - $this->tpl->setVariable("ID", $a_set["ref_id"]); - $this->tpl->setVariable("VAL_TITLE", $a_set["title"]); - $this->tpl->setVariable("VAL_LAST_CHANGE", $a_set["last_update"]); - } + $img = ilObject::_getIcon($a_set["obj_id"], "small", $a_set["type"]); + if (strlen($img) > 0) { + $alt = ($objDefinition->isPlugin($a_set["type"])) + ? $lng->txt("icon") . " " . ilObjectPlugin::lookupTxtById($a_set["type"], "obj_" . $a_set["type"]) + : $lng->txt("icon") . " " . $lng->txt("obj_" . $a_set["type"]); + $this->tpl->setVariable("IMG_TYPE", ilUtil::img($img, $alt)); + } + $this->tpl->setVariable("ID", $a_set["ref_id"]); + $this->tpl->setVariable("VAL_TITLE", $a_set["title"]); + $this->tpl->setVariable("VAL_LAST_CHANGE", $a_set["last_update"]); + } } -?> diff --git a/Services/Repository/classes/class.ilValidator.php b/Services/Repository/classes/class.ilValidator.php index 0ea855746741ea7e4cf072b91299b4905dfed46b..b00f0f7dbfb09a6eb1d53bcbb17e6f949974295f 100644 --- a/Services/Repository/classes/class.ilValidator.php +++ b/Services/Repository/classes/class.ilValidator.php @@ -4,2620 +4,2418 @@ /** * ILIAS Data Validator & Recovery Tool * -* @author Sascha Hofmann +* @author Sascha Hofmann * @version $Id$ * */ class ilValidator { - /** - * @var ilObjectDefinition - */ - protected $obj_definition; - - /** - * @var ilDB - */ - protected $db; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var Logger - */ - protected $log; - - /** - * @var ilRbacAdmin - */ - protected $rbacadmin; - - /** - * @var ilTree - */ - protected $tree; - - /** - * @var ilObjUser - */ - protected $user; - - protected $media_pool_ids = null; - - /** - * all valid rbac object types - * @var string - */ - var $rbac_object_types = NULL; - - /** - * list of object types to exclude from recovering - * @var array - */ - // i added folder due to bug #1860 (even if this will not completely fix it) - // and the fact, that media pool folders may find their way into - // the recovery folder (what results in broken pools, if the are deleted) - // Alex, 2006-07-21 - // I removed file objects from this exclusion list, because file objects - // can be in the repository tree, and thus can suffer from data + /** + * @var ilObjectDefinition + */ + protected $obj_definition; + + /** + * @var ilDB + */ + protected $db; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var Logger + */ + protected $log; + + /** + * @var ilRbacAdmin + */ + protected $rbacadmin; + + /** + * @var ilTree + */ + protected $tree; + + /** + * @var ilObjUser + */ + protected $user; + + protected $media_pool_ids = null; + + /** + * all valid rbac object types + * @var string + */ + public $rbac_object_types = null; + + /** + * list of object types to exclude from recovering + * @var array + */ + // i added folder due to bug #1860 (even if this will not completely fix it) + // and the fact, that media pool folders may find their way into + // the recovery folder (what results in broken pools, if the are deleted) + // Alex, 2006-07-21 + // I removed file objects from this exclusion list, because file objects + // can be in the repository tree, and thus can suffer from data // inconsistencies as well. - // Werner, 2007-04-16 - var $object_types_exclude = array("adm","root","mail","usrf","objf","lngf", - "trac","taxf","auth","rolf","assf","svyf","extt","adve","fold"); - - /** - * set mode - * @var array - */ - var $mode = array( - "scan" => true, // gather information about corrupted entries - "dump_tree" => false, // dump tree - "clean" => false, // remove all unusable entries & renumber tree - "restore" => false, // restore objects with invalid parent to RecoveryFolder - "purge" => false, // delete all objects with invalid parent from system - "restore_trash" => false, // restore all objects in trash to RecoveryFolder - "purge_trash" => false // delete all objects in trash from system - ); - - /** - * invalid references - * @var array - */ - var $invalid_references = array(); - - /** - * invalid childs (tree entries) - * @var array - */ - var $invalid_childs = array(); - - /** - * missing objects - * @var array - */ - var $missing_objects = array(); - - /** - * unbound objects - * @var array - */ - var $unbound_objects = array(); - - /** - * objects in trash - * @var array - */ - var $deleted_objects = array(); - - /** - * contains missing objects that are rolefolders. found by this:: - * findMissingObjects()' these rolefolders must be removed before any - * restore operations - * @var array - */ - var $invalid_rolefolders = array(); - - /** - * contains correct registrated objects but data are corrupted (experimental) - * @var array - */ - var $invalid_objects = array(); - - /** - * true enables scan log - * @var boolean - */ - var $logging = false; - - /** - * contains ilLog object - * @var object - */ - var $scan_log; - - var $scan_log_file = "scanlog.log"; - - var $scan_log_separator = ""; - - /** - * Constructor - * - * @access public - * @param integer mode - */ - function __construct($a_log = false) - { - global $DIC; - - $this->obj_definition = $DIC["objDefinition"]; - $this->db = $DIC->database(); - $this->lng = $DIC->language(); - $this->log = $DIC["ilLog"]; - $this->rbacadmin = $DIC->rbac()->admin(); - $this->tree = $DIC->repositoryTree(); - $this->user = $DIC->user(); - $objDefinition = $DIC["objDefinition"]; - $ilDB = $DIC->database(); - - $this->db =& $ilDB; - $this->rbac_object_types = "'".implode("','",$objDefinition->getAllRBACObjects())."'"; - $this->rbac_object_types = $objDefinition->getAllRBACObjects(); - - if ($a_log === true) - { - $this->logging = true; - - // should be available thru inc.header.php - // TODO: move log functionality to new class ilScanLog - include_once "./Services/Logging/classes/class.ilLog.php"; - - // Delete old scan log - $this->deleteScanLog(); - - // create scan log - include_once './Services/Logging/classes/class.ilLog.php'; - $this->scan_log = new ilLog(CLIENT_DATA_DIR,"scanlog.log"); - $this->scan_log->setLogFormat(""); - $this->writeScanLogLine($this->scan_log_separator); - $this->writeScanLogLine("\n[Systemscan from ".date("y-m-d H:i]")); - } - } - - /** - * get possible ilValidator modes - * @access public - * @return array modes - */ - public function getPossibleModes() - { - return array_keys($this->mode); - } - - /** - * set mode of ilValidator - * Usage: setMode("restore",true) => enable object restorey - * setMode("all",true) => enable all features - * For all possible modes see variables declaration - * - * @access public - * @param string mode - * @param boolean value (true=enable/false=disable) - * @return boolean false on error - */ - function setMode($a_mode,$a_value) - { - if ((!in_array($a_mode,array_keys($this->mode)) and $a_mode != "all") or !is_bool($a_value)) - { - $this->throwError(INVALID_PARAM, FATAL, DEBUG); - return false; - } - - if ($a_mode == "all") - { - foreach ($this->mode as $mode => $value) - { - $this->mode[$mode] = $a_value; - } - } - else - { - $this->mode[$a_mode] = $a_value; - } - - // consider mode dependencies - $this->setModeDependencies(); - - return true; - } - - /** - * Is a particular mode enabled? - * - * @access public - * @param string mode to query - * @return boolean - * @see this::setMode() - */ - function isModeEnabled($a_mode) - { - if (!in_array($a_mode,array_keys($this->mode))) - { - $this->throwError(VALIDATER_UNKNOWN_MODE, WARNING, DEBUG); - return false; - } - - return $this->mode[$a_mode]; - } - - function isLogEnabled() - { - return $this->logging; - } - - /** - * Sets modes by considering mode dependencies; - * some modes require other modes to be activated. - * This functions set all modes that are required according to the current setting. - * - * @access private - * @see this::setMode() - */ - function setModeDependencies() - { - // DO NOT change the order - - if ($this->mode["restore"] === true) - { - $this->mode["scan"] = true; - $this->mode["purge"] = false; - } - - if ($this->mode["purge"] === true) - { - $this->mode["scan"] = true; - $this->mode["restore"] = false; - } - - if ($this->mode["restore_trash"] === true) - { - $this->mode["scan"] = true; - $this->mode["purge_trash"] = false; - } - - if ($this->mode["purge_trash"] === true) - { - $this->mode["scan"] = true; - $this->mode["restore_trash"] = false; - } - - if ($this->mode["clean"] === true) - { - $this->mode["scan"] = true; - } - } - - /** - * Performs the validation for each enabled mode. - * Returns a validation summary for display to the user. - * - * @return string Validation summary. - * @access public - * @see this::setMode() - */ - function validate() - { - $lng = $this->lng; - - // The validation summary. - $summary = ""; - - - // STEP 1: Scan - // ------------------- - $summary .= $lng->txt("scanning_system"); - if (!$this->isModeEnabled("scan")) - { - $summary .= $lng->txt("disabled"); - } - else - { - $summary .= "
                  ".$lng->txt("searching_invalid_refs"); - if ($this->findInvalidReferences()) - { - $summary .= count($this->getInvalidReferences())." ".$lng->txt("found"); - } - else - { - $summary .= $lng->txt("found_none"); - } - - $summary .= "
                  ".$lng->txt("searching_invalid_childs"); - if ($this->findInvalidChilds()) - { - $summary .= count($this->getInvalidChilds())." ".$lng->txt("found"); - - } - else - { - $summary .= $lng->txt("found_none"); - } - - $summary .= "
                  ".$lng->txt("searching_missing_objs"); - if ($this->findMissingObjects()) - { - $summary .= count($this->getMissingObjects())." ".$lng->txt("found"); - - } - else - { - $summary .= $lng->txt("found_none"); - } - - $summary .= "
                  ".$lng->txt("searching_unbound_objs"); - if ($this->findUnboundObjects()) - { - $summary .= count($this->getUnboundObjects())." ".$lng->txt("found"); - - } - else - { - $summary .= $lng->txt("found_none"); - } - - $summary .= "
                  ".$lng->txt("searching_deleted_objs"); - if ($this->findDeletedObjects()) - { - $summary .= count($this->getDeletedObjects())." ".$lng->txt("found"); - - } - else - { - $summary .= $lng->txt("found_none"); - } - - $summary .= "
                  ".$lng->txt("searching_invalid_rolfs"); - if ($this->findInvalidRolefolders()) - { - $summary .= count($this->getInvalidRolefolders())." ".$lng->txt("found"); - - } - else - { - $summary .= $lng->txt("found_none"); - } - - $summary .= "

                  ".$lng->txt("analyzing_tree_structure"); - if ($this->checkTreeStructure()) - { - $summary .= $lng->txt("tree_corrupt"); - } - else - { - $summary .= $lng->txt("done"); - } - } - - // STEP 2: Dump tree - // ------------------- - $summary .= "

                  ".$lng->txt("dumping_tree"); - if (!$this->isModeEnabled("dump_tree")) - { - $summary .= $lng->txt("disabled"); - } - else - { - $error_count = $this->dumpTree(); - if ($error_count > 0) - { - $summary .= $lng->txt("tree_corrupt"); - } - else - { - $summary .= $lng->txt("done"); - } - } - - // STEP 3: Clean Up - // ------------------- - $summary .= "

                  ".$lng->txt("cleaning"); - if (!$this->isModeEnabled("clean")) - { - $summary .= $lng->txt("disabled"); - } - else - { - $summary .= "
                  ".$lng->txt("removing_invalid_refs"); - if ($this->removeInvalidReferences()) - { - $summary .= strtolower($lng->txt("done")); - } - else - { - $summary .= $lng->txt("nothing_to_remove").$lng->txt("skipped"); - } - - $summary .= "
                  ".$lng->txt("removing_invalid_childs"); - if ($this->removeInvalidChilds()) - { - $summary .= strtolower($lng->txt("done")); - } - else - { - $summary .= $lng->txt("nothing_to_remove").$lng->txt("skipped"); - } - - $summary .= "
                  ".$lng->txt("removing_invalid_rolfs"); - if ($this->removeInvalidRolefolders()) - { - $summary .= strtolower($lng->txt("done")); - } - else - { - $summary .= $lng->txt("nothing_to_remove").$lng->txt("skipped"); - } - - // find unbound objects again AFTER cleaning process! - // This updates the array 'unboundobjects' required for the further steps - // There might be other objects unbounded now due to removal of object_data/reference entries. - $this->findUnboundObjects(); - } - - // STEP 4: Restore objects - $summary .= "

                  ".$lng->txt("restoring"); - - if (!$this->isModeEnabled("restore")) - { - $summary .= $lng->txt("disabled"); - } - else - { - $summary .= "
                  ".$lng->txt("restoring_missing_objs"); - if ($this->restoreMissingObjects()) - { - $summary .= strtolower($lng->txt("done")); - } - else - { - $summary .= $lng->txt("nothing_to_restore").$lng->txt("skipped"); - } - - $summary .= "
                  ".$lng->txt("restoring_unbound_objs"); - if ($this->restoreUnboundObjects()) - { - $summary .= strtolower($lng->txt("done")); - } - else - { - $summary .= $lng->txt("nothing_to_restore").$lng->txt("skipped"); - } - } - - // STEP 5: Restoring Trash - $summary .= "

                  ".$lng->txt("restoring_trash"); - - if (!$this->isModeEnabled("restore_trash")) - { - $summary .= $lng->txt("disabled"); - } - else - { - if ($this->restoreTrash()) - { - $summary .= strtolower($lng->txt("done")); - } - else - { - $summary .= $lng->txt("nothing_to_restore").$lng->txt("skipped"); - } - } - - // STEP 6: Purging... - $summary .= "

                  ".$lng->txt("purging"); - - if (!$this->isModeEnabled("purge")) - { - $summary .= $lng->txt("disabled"); - } - else - { - $summary .= "
                  ".$lng->txt("purging_missing_objs"); - if ($this->purgeMissingObjects()) - { - $summary .= strtolower($lng->txt("done")); - } - else - { - $summary .= $lng->txt("nothing_to_purge").$lng->txt("skipped"); - } - - $summary .= "
                  ".$lng->txt("purging_unbound_objs"); - if ($this->purgeUnboundObjects()) - { - $summary .= strtolower($lng->txt("done")); - } - else - { - $summary .= $lng->txt("nothing_to_purge").$lng->txt("skipped"); - } - } - - // STEP 7: Purging trash... - $summary .= "

                  ".$lng->txt("purging_trash"); - - if (!$this->isModeEnabled("purge_trash")) - { - $summary .= $lng->txt("disabled"); - } - else - { - if ($this->purgeTrash()) - { - $summary .= strtolower($lng->txt("done")); - } - else - { - $summary .= $lng->txt("nothing_to_purge").$lng->txt("skipped"); - } - } - - // STEP 8: Initialize gaps in tree - if ($this->isModeEnabled("clean")) - { - $summary .= "

                  ".$lng->txt("cleaning_final"); - if ($this->initGapsInTree()) - { - $summary .= "
                  ".$lng->txt("initializing_gaps")." ".strtolower($lng->txt("done")); - } - } - - // check RBAC starts here - // ... - - // le fin - foreach ($this->mode as $mode => $value) - { - $arr[] = $mode."[".(int)$value."]"; - } - - return $summary; - } - - - /** - * Search database for all object entries with missing reference and/or tree entry - * and stores result in $this->missing_objects - * - * @access public - * @return boolean false if analyze mode disabled or nothing found - * @see this::getMissingObjects() - * @see this::restoreMissingObjects() - */ - function findMissingObjects() - { - $ilDB = $this->db; - - // check mode: analyze - if ($this->mode["scan"] !== true) - { - return false; - } - - // init - $this->missing_objects = array(); - - $this->writeScanLogLine("\nfindMissingObjects:"); - - // Repair missing objects. - // We only repair file objects which have an entry in table object_reference. + // Werner, 2007-04-16 + public $object_types_exclude = array("adm","root","mail","usrf","objf","lngf", + "trac","taxf","auth","rolf","assf","svyf","extt","adve","fold"); + + /** + * set mode + * @var array + */ + public $mode = array( + "scan" => true, // gather information about corrupted entries + "dump_tree" => false, // dump tree + "clean" => false, // remove all unusable entries & renumber tree + "restore" => false, // restore objects with invalid parent to RecoveryFolder + "purge" => false, // delete all objects with invalid parent from system + "restore_trash" => false, // restore all objects in trash to RecoveryFolder + "purge_trash" => false // delete all objects in trash from system + ); + + /** + * invalid references + * @var array + */ + public $invalid_references = array(); + + /** + * invalid childs (tree entries) + * @var array + */ + public $invalid_childs = array(); + + /** + * missing objects + * @var array + */ + public $missing_objects = array(); + + /** + * unbound objects + * @var array + */ + public $unbound_objects = array(); + + /** + * objects in trash + * @var array + */ + public $deleted_objects = array(); + + /** + * contains missing objects that are rolefolders. found by this:: + * findMissingObjects()' these rolefolders must be removed before any + * restore operations + * @var array + */ + public $invalid_rolefolders = array(); + + /** + * contains correct registrated objects but data are corrupted (experimental) + * @var array + */ + public $invalid_objects = array(); + + /** + * true enables scan log + * @var boolean + */ + public $logging = false; + + /** + * contains ilLog object + * @var object + */ + public $scan_log; + + public $scan_log_file = "scanlog.log"; + + public $scan_log_separator = ""; + + /** + * Constructor + * + * @access public + * @param integer mode + */ + public function __construct($a_log = false) + { + global $DIC; + + $this->obj_definition = $DIC["objDefinition"]; + $this->db = $DIC->database(); + $this->lng = $DIC->language(); + $this->log = $DIC["ilLog"]; + $this->rbacadmin = $DIC->rbac()->admin(); + $this->tree = $DIC->repositoryTree(); + $this->user = $DIC->user(); + $objDefinition = $DIC["objDefinition"]; + $ilDB = $DIC->database(); + + $this->db =&$ilDB; + $this->rbac_object_types = "'" . implode("','", $objDefinition->getAllRBACObjects()) . "'"; + $this->rbac_object_types = $objDefinition->getAllRBACObjects(); + + if ($a_log === true) { + $this->logging = true; + + // should be available thru inc.header.php + // TODO: move log functionality to new class ilScanLog + include_once "./Services/Logging/classes/class.ilLog.php"; + + // Delete old scan log + $this->deleteScanLog(); + + // create scan log + include_once './Services/Logging/classes/class.ilLog.php'; + $this->scan_log = new ilLog(CLIENT_DATA_DIR, "scanlog.log"); + $this->scan_log->setLogFormat(""); + $this->writeScanLogLine($this->scan_log_separator); + $this->writeScanLogLine("\n[Systemscan from " . date("y-m-d H:i]")); + } + } + + /** + * get possible ilValidator modes + * @access public + * @return array modes + */ + public function getPossibleModes() + { + return array_keys($this->mode); + } + + /** + * set mode of ilValidator + * Usage: setMode("restore",true) => enable object restorey + * setMode("all",true) => enable all features + * For all possible modes see variables declaration + * + * @access public + * @param string mode + * @param boolean value (true=enable/false=disable) + * @return boolean false on error + */ + public function setMode($a_mode, $a_value) + { + if ((!in_array($a_mode, array_keys($this->mode)) and $a_mode != "all") or !is_bool($a_value)) { + $this->throwError(INVALID_PARAM, FATAL, DEBUG); + return false; + } + + if ($a_mode == "all") { + foreach ($this->mode as $mode => $value) { + $this->mode[$mode] = $a_value; + } + } else { + $this->mode[$a_mode] = $a_value; + } + + // consider mode dependencies + $this->setModeDependencies(); + + return true; + } + + /** + * Is a particular mode enabled? + * + * @access public + * @param string mode to query + * @return boolean + * @see this::setMode() + */ + public function isModeEnabled($a_mode) + { + if (!in_array($a_mode, array_keys($this->mode))) { + $this->throwError(VALIDATER_UNKNOWN_MODE, WARNING, DEBUG); + return false; + } + + return $this->mode[$a_mode]; + } + + public function isLogEnabled() + { + return $this->logging; + } + + /** + * Sets modes by considering mode dependencies; + * some modes require other modes to be activated. + * This functions set all modes that are required according to the current setting. + * + * @access private + * @see this::setMode() + */ + public function setModeDependencies() + { + // DO NOT change the order + + if ($this->mode["restore"] === true) { + $this->mode["scan"] = true; + $this->mode["purge"] = false; + } + + if ($this->mode["purge"] === true) { + $this->mode["scan"] = true; + $this->mode["restore"] = false; + } + + if ($this->mode["restore_trash"] === true) { + $this->mode["scan"] = true; + $this->mode["purge_trash"] = false; + } + + if ($this->mode["purge_trash"] === true) { + $this->mode["scan"] = true; + $this->mode["restore_trash"] = false; + } + + if ($this->mode["clean"] === true) { + $this->mode["scan"] = true; + } + } + + /** + * Performs the validation for each enabled mode. + * Returns a validation summary for display to the user. + * + * @return string Validation summary. + * @access public + * @see this::setMode() + */ + public function validate() + { + $lng = $this->lng; + + // The validation summary. + $summary = ""; + + + // STEP 1: Scan + // ------------------- + $summary .= $lng->txt("scanning_system"); + if (!$this->isModeEnabled("scan")) { + $summary .= $lng->txt("disabled"); + } else { + $summary .= "
                  " . $lng->txt("searching_invalid_refs"); + if ($this->findInvalidReferences()) { + $summary .= count($this->getInvalidReferences()) . " " . $lng->txt("found"); + } else { + $summary .= $lng->txt("found_none"); + } + + $summary .= "
                  " . $lng->txt("searching_invalid_childs"); + if ($this->findInvalidChilds()) { + $summary .= count($this->getInvalidChilds()) . " " . $lng->txt("found"); + } else { + $summary .= $lng->txt("found_none"); + } + + $summary .= "
                  " . $lng->txt("searching_missing_objs"); + if ($this->findMissingObjects()) { + $summary .= count($this->getMissingObjects()) . " " . $lng->txt("found"); + } else { + $summary .= $lng->txt("found_none"); + } + + $summary .= "
                  " . $lng->txt("searching_unbound_objs"); + if ($this->findUnboundObjects()) { + $summary .= count($this->getUnboundObjects()) . " " . $lng->txt("found"); + } else { + $summary .= $lng->txt("found_none"); + } + + $summary .= "
                  " . $lng->txt("searching_deleted_objs"); + if ($this->findDeletedObjects()) { + $summary .= count($this->getDeletedObjects()) . " " . $lng->txt("found"); + } else { + $summary .= $lng->txt("found_none"); + } + + $summary .= "
                  " . $lng->txt("searching_invalid_rolfs"); + if ($this->findInvalidRolefolders()) { + $summary .= count($this->getInvalidRolefolders()) . " " . $lng->txt("found"); + } else { + $summary .= $lng->txt("found_none"); + } + + $summary .= "

                  " . $lng->txt("analyzing_tree_structure"); + if ($this->checkTreeStructure()) { + $summary .= $lng->txt("tree_corrupt"); + } else { + $summary .= $lng->txt("done"); + } + } + + // STEP 2: Dump tree + // ------------------- + $summary .= "

                  " . $lng->txt("dumping_tree"); + if (!$this->isModeEnabled("dump_tree")) { + $summary .= $lng->txt("disabled"); + } else { + $error_count = $this->dumpTree(); + if ($error_count > 0) { + $summary .= $lng->txt("tree_corrupt"); + } else { + $summary .= $lng->txt("done"); + } + } + + // STEP 3: Clean Up + // ------------------- + $summary .= "

                  " . $lng->txt("cleaning"); + if (!$this->isModeEnabled("clean")) { + $summary .= $lng->txt("disabled"); + } else { + $summary .= "
                  " . $lng->txt("removing_invalid_refs"); + if ($this->removeInvalidReferences()) { + $summary .= strtolower($lng->txt("done")); + } else { + $summary .= $lng->txt("nothing_to_remove") . $lng->txt("skipped"); + } + + $summary .= "
                  " . $lng->txt("removing_invalid_childs"); + if ($this->removeInvalidChilds()) { + $summary .= strtolower($lng->txt("done")); + } else { + $summary .= $lng->txt("nothing_to_remove") . $lng->txt("skipped"); + } + + $summary .= "
                  " . $lng->txt("removing_invalid_rolfs"); + if ($this->removeInvalidRolefolders()) { + $summary .= strtolower($lng->txt("done")); + } else { + $summary .= $lng->txt("nothing_to_remove") . $lng->txt("skipped"); + } + + // find unbound objects again AFTER cleaning process! + // This updates the array 'unboundobjects' required for the further steps + // There might be other objects unbounded now due to removal of object_data/reference entries. + $this->findUnboundObjects(); + } + + // STEP 4: Restore objects + $summary .= "

                  " . $lng->txt("restoring"); + + if (!$this->isModeEnabled("restore")) { + $summary .= $lng->txt("disabled"); + } else { + $summary .= "
                  " . $lng->txt("restoring_missing_objs"); + if ($this->restoreMissingObjects()) { + $summary .= strtolower($lng->txt("done")); + } else { + $summary .= $lng->txt("nothing_to_restore") . $lng->txt("skipped"); + } + + $summary .= "
                  " . $lng->txt("restoring_unbound_objs"); + if ($this->restoreUnboundObjects()) { + $summary .= strtolower($lng->txt("done")); + } else { + $summary .= $lng->txt("nothing_to_restore") . $lng->txt("skipped"); + } + } + + // STEP 5: Restoring Trash + $summary .= "

                  " . $lng->txt("restoring_trash"); + + if (!$this->isModeEnabled("restore_trash")) { + $summary .= $lng->txt("disabled"); + } else { + if ($this->restoreTrash()) { + $summary .= strtolower($lng->txt("done")); + } else { + $summary .= $lng->txt("nothing_to_restore") . $lng->txt("skipped"); + } + } + + // STEP 6: Purging... + $summary .= "

                  " . $lng->txt("purging"); + + if (!$this->isModeEnabled("purge")) { + $summary .= $lng->txt("disabled"); + } else { + $summary .= "
                  " . $lng->txt("purging_missing_objs"); + if ($this->purgeMissingObjects()) { + $summary .= strtolower($lng->txt("done")); + } else { + $summary .= $lng->txt("nothing_to_purge") . $lng->txt("skipped"); + } + + $summary .= "
                  " . $lng->txt("purging_unbound_objs"); + if ($this->purgeUnboundObjects()) { + $summary .= strtolower($lng->txt("done")); + } else { + $summary .= $lng->txt("nothing_to_purge") . $lng->txt("skipped"); + } + } + + // STEP 7: Purging trash... + $summary .= "

                  " . $lng->txt("purging_trash"); + + if (!$this->isModeEnabled("purge_trash")) { + $summary .= $lng->txt("disabled"); + } else { + if ($this->purgeTrash()) { + $summary .= strtolower($lng->txt("done")); + } else { + $summary .= $lng->txt("nothing_to_purge") . $lng->txt("skipped"); + } + } + + // STEP 8: Initialize gaps in tree + if ($this->isModeEnabled("clean")) { + $summary .= "

                  " . $lng->txt("cleaning_final"); + if ($this->initGapsInTree()) { + $summary .= "
                  " . $lng->txt("initializing_gaps") . " " . strtolower($lng->txt("done")); + } + } + + // check RBAC starts here + // ... + + // le fin + foreach ($this->mode as $mode => $value) { + $arr[] = $mode . "[" . (int) $value . "]"; + } + + return $summary; + } + + + /** + * Search database for all object entries with missing reference and/or tree entry + * and stores result in $this->missing_objects + * + * @access public + * @return boolean false if analyze mode disabled or nothing found + * @see this::getMissingObjects() + * @see this::restoreMissingObjects() + */ + public function findMissingObjects() + { + $ilDB = $this->db; + + // check mode: analyze + if ($this->mode["scan"] !== true) { + return false; + } + + // init + $this->missing_objects = array(); + + $this->writeScanLogLine("\nfindMissingObjects:"); + + // Repair missing objects. + // We only repair file objects which have an entry in table object_reference. // XXX - We should check all references to file objects which don't // have an object_reference. If we can't find any reference to such // a file object, we should repair it too! - $q = "SELECT object_data.*, ref_id FROM object_data ". - "LEFT JOIN object_reference ON object_data.obj_id = object_reference.obj_id ". - "LEFT JOIN tree ON object_reference.ref_id = tree.child ". - "WHERE tree.child IS NULL ". - "AND (object_reference.obj_id IS NOT NULL ". - " OR object_data.type <> 'file' AND ". - $ilDB->in('object_data.type',$this->rbac_object_types,false,'text'). - ")"; - $r = $this->db->query($q); - - while ($row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - #if (!in_array($row->type,$this->object_types_exclude)) - if(!$this->isExcludedFromRecovery($row->type,$row->obj_id)) - { - $this->missing_objects[] = array( - "obj_id" => $row->obj_id, - "type" => $row->type, - "ref_id" => $row->ref_id, - "child" => $row->child, - "title" => $row->title, - "desc" => $row->description, - "owner" => $row->owner, - "create_date" => $row->create_date, - "last_update" => $row->last_update - ); - } - } - - $this->filterWorkspaceObjects($this->missing_objects); - if (count($this->missing_objects) > 0) - { - $this->writeScanLogLine("obj_id\ttype\tref_id\tchild\ttitle\tdesc\towner\tcreate_date\tlast_update"); - $this->writeScanLogArray($this->missing_objects); - return true; - } - - $this->writeScanLogLine("none"); - return false; - } - - /** - * Search database for all rolefolder object entries with missing reference - * entry. Furthermore gets all rolefolders that are placed accidently in - * RECOVERY_FOLDER from earlier versions of System check. - * Result is stored in $this->invalid_rolefolders - * - * @access public - * @return boolean false if analyze mode disabled or nothing found - * @see this::getInvalidRolefolders() - * @see this::removeInvalidRolefolders() - */ - function findInvalidRolefolders() - { - $ilDB = $this->db; - - // check mode: analyze - if ($this->mode["scan"] !== true) - { - return false; - } - - // init - $this->invalid_rolefolders = array(); - - $this->writeScanLogLine("\nfindInvalidRolefolders:"); - - // find rolfs without reference/tree entry - $q = "SELECT object_data.*, ref_id FROM object_data ". - "LEFT JOIN object_reference ON object_data.obj_id = object_reference.obj_id ". - "LEFT JOIN tree ON object_reference.ref_id = tree.child ". - "WHERE (object_reference.obj_id IS NULL OR tree.child IS NULL) ". - "AND object_data.type='rolf'"; - $r = $this->db->query($q); - - while ($row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - $this->invalid_rolefolders[] = array( - "obj_id" => $row->obj_id, - "type" => $row->type, - "ref_id" => $row->ref_id, - "child" => $row->child, - "title" => $row->title, - "desc" => $row->description, - "owner" => $row->owner, - "create_date" => $row->create_date, - "last_update" => $row->last_update - ); - } - - // find rolfs within RECOVERY FOLDER - $q = "SELECT object_data.*, ref_id FROM object_data ". - "LEFT JOIN object_reference ON object_data.obj_id = object_reference.obj_id ". - "LEFT JOIN tree ON object_reference.ref_id = tree.child ". - "WHERE object_reference.ref_id = ".$ilDB->quote(RECOVERY_FOLDER_ID,'integer')." ". - "AND object_data.type='rolf'"; - $r = $this->db->query($q); - - while ($row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - $this->invalid_rolefolders[] = array( - "obj_id" => $row->obj_id, - "type" => $row->type, - "ref_id" => $row->ref_id, - "child" => $row->child, - "title" => $row->title, - "desc" => $row->description, - "owner" => $row->owner, - "create_date" => $row->create_date, - "last_update" => $row->last_update - ); - } - - $this->filterWorkspaceObjects($this->invalid_rolefolders); - if (count($this->invalid_rolefolders) > 0) - { - $this->writeScanLogLine("obj_id\ttype\tref_id\tchild\ttitle\tdesc\towner\tcreate_date\tlast_update"); - $this->writeScanLogArray($this->invalid_rolefolders); - return true; - } - - $this->writeScanLogLine("none"); - return false; - } - - /** - * Search database for all role entries that are linked to invalid - * ref_ids - * - * @access public - * @return boolean false if analyze mode disabled or nothing found - * @see this::getInvalidRBACEntries() - * @see this::removeInvalidRBACEntries() - */ - function findInvalidRBACEntries() - { - $ilDB = $this->db; - - // check mode: analyze - if ($this->mode["scan"] !== true) - { - return false; - } - - // init - $this->invalid_rbac_entries = array(); - - $this->writeScanLogLine("\nfindInvalidRBACEntries:"); - - $q = "SELECT object_data.*, ref_id FROM object_data ". - "LEFT JOIN object_reference ON object_data.obj_id = object_reference.obj_id ". - "LEFT JOIN tree ON object_reference.ref_id = tree.child ". - "WHERE (object_reference.obj_id IS NULL OR tree.child IS NULL) ". - "AND object_data.type='rolf'"; - $r = $this->db->query($q); - - while ($row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - $this->invalid_rolefolders[] = array( - "obj_id" => $row->obj_id, - "type" => $row->type, - "ref_id" => $row->ref_id, - "child" => $row->child, - "title" => $row->title, - "desc" => $row->description, - "owner" => $row->owner, - "create_date" => $row->create_date, - "last_update" => $row->last_update - ); - } - - // find rolfs within RECOVERY FOLDER - $q = "SELECT object_data.*, ref_id FROM object_data ". - "LEFT JOIN object_reference ON object_data.obj_id = object_reference.obj_id ". - "LEFT JOIN tree ON object_reference.ref_id = tree.child ". - "WHERE object_reference.ref_id =".$ilDB->quote(RECOVERY_FOLDER_ID)." ". - "AND object_data.type='rolf'"; - $r = $this->db->query($q); - - while ($row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - $this->invalid_rolefolders[] = array( - "obj_id" => $row->obj_id, - "type" => $row->type, - "ref_id" => $row->ref_id, - "child" => $row->child, - "title" => $row->title, - "desc" => $row->description, - "owner" => $row->owner, - "create_date" => $row->create_date, - "last_update" => $row->last_update - ); - } - - $this->filterWorkspaceObjects($this->invalid_rolefolders); - if (count($this->invalid_rolefolders) > 0) - { - $this->writeScanLogLine("obj_id\ttype\tref_id\tchild\ttitle\tdesc\towner\tcreate_date\tlast_update"); - $this->writeScanLogArray($this->invalid_rolefolders); - return true; - } - - $this->writeScanLogLine("none"); - return false; - } - - /** - * Gets all object entries with missing reference and/or tree entry. - * Returns array with - * obj_id => actual object entry with missing reference or tree - * type => symbolic name of object type - * ref_id => reference entry of object (or NULL if missing) - * child => always NULL (only for debugging and verification) - * - * @access public - * @return array - * @see this::findMissingObjects() - * @see this::restoreMissingObjects() - */ - function getMissingObjects() - { - return $this->missing_objects; - } - - /** - * Search database for all reference entries that are not linked with a valid object id - * and stores result in $this->invalid_references - * - * @access public - * @return boolean false if analyze mode disabled or nothing found - * @see this::getInvalidReferences() - * @see this::removeInvalidReferences() - */ - function findInvalidReferences() - { - $ilDB = $this->db; - - // check mode: analyze - if ($this->mode["scan"] !== true) - { - return false; - } - - // init - $this->invalid_references = array(); - - $this->writeScanLogLine("\nfindInvalidReferences:"); - $q = "SELECT object_reference.* FROM object_reference ". - "LEFT JOIN object_data ON object_data.obj_id = object_reference.obj_id ". - "WHERE object_data.obj_id IS NULL ". - "OR ".$ilDB->in('object_data.type',$this->rbac_object_types,true,'text'); - $r = $this->db->query($q); - - while ($row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - $this->invalid_references[] = array( - "ref_id" => $row->ref_id, - "obj_id" => $row->obj_id, - "msg" => "Object does not exist." - ); - } - - $this->filterWorkspaceObjects($this->invalid_references); - if (count($this->invalid_references) > 0) - { - $this->writeScanLogLine("ref_id\t\tobj_id"); - $this->writeScanLogArray($this->invalid_references); - return true; - } - - $this->writeScanLogLine("none"); - return false; - } - - /** - * Gets all reference entries that are not linked with a valid object id. - * - * @access public - * @return array - * @see this::findInvalidReferences() - * @see this::removeInvalidReferences() - */ - function getInvalidReferences() - { - return $this->invalid_references; - } - - /** - * Search database for all tree entries without any link to a valid object - * and stores result in $this->invalid_childs - * - * @access public - * @return boolean false if analyze mode disabled or nothing found - * @see this::getInvalidChilds() - * @see this::removeInvalidChilds() - */ - function findInvalidChilds() - { - $ilDB = $this->db; - - // check mode: analyze - if ($this->mode["scan"] !== true) - { - return false; - } - - // init - $this->invalid_childs = array(); - - $this->writeScanLogLine("\nfindInvalidChilds:"); - - $q = "SELECT tree.*,object_reference.ref_id FROM tree ". - "LEFT JOIN object_reference ON tree.child = object_reference.ref_id ". - "LEFT JOIN object_data ON object_reference.obj_id = object_data.obj_id ". - "WHERE object_reference.ref_id IS NULL or object_data.obj_id IS NULL"; - $r = $this->db->query($q); - while ($row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - $this->invalid_childs[] = array( - "child" => $row->child, - "ref_id" => $row->ref_id, - "msg" => "No object found" - ); - } - - if (count($this->invalid_childs) > 0) - { - $this->writeScanLogLine("child\t\tref_id"); - $this->writeScanLogArray($this->invalid_childs); - return true; - } - - $this->writeScanLogLine("none"); - return false; - } - - /** - * Gets all tree entries without any link to a valid object - * - * @access public - * @return array - * @see this::findInvalidChilds() - * @see this::removeInvalidChilds() - */ - function getInvalidChilds() - { - return $this->invalid_childs; - } - - /** - * Search database for all tree entries having no valid parent (=> no valid path to root node) - * and stores result in $this->unbound_objects - * Result does not contain childs that are marked as deleted! Deleted childs - * have a negative number. - * - * @access public - * @return boolean false if analyze mode disabled or nothing found - * @see this::getUnboundObjects() - * @see this::restoreUnboundObjects() - */ - function findUnboundObjects() - { - // check mode: analyze - if ($this->mode["scan"] !== true) - { - return false; - } - - // init - $this->unbound_objects = array(); - - $this->writeScanLogLine("\nfindUnboundObjects:"); - - $q = "SELECT T1.tree,T1.child,T1.parent,". - "T2.tree deleted,T2.parent grandparent ". - "FROM tree T1 ". - "LEFT JOIN tree T2 ON T2.child=T1.parent ". - "WHERE (T2.tree!=1 OR T2.tree IS NULL) AND T1.parent!=0"; - $r = $this->db->query($q); - - while ($row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - // exclude deleted nodes - if ($row->deleted === NULL) - { - $this->unbound_objects[] = array( - "child" => $row->child, - "parent" => $row->parent, - "tree" => $row->tree, - "msg" => "No valid parent node found" - ); - } - } - - if (count($this->unbound_objects) > 0) - { - $this->writeScanLogLine("child\t\tparent\ttree"); - $this->writeScanLogArray($this->unbound_objects); - return true; - } - - $this->writeScanLogLine("none"); - return false; - } - - /** - * Search database for all tree entries having no valid parent (=> no valid path to root node) - * and stores result in $this->unbound_objects - * Result also contains childs that are marked as deleted! Deleted childs has - * a negative number in ["deleted"] otherwise NULL. - * - * @access public - * @return boolean false if analyze mode disabled or nothing found - * @see this::getUnboundObjects() - * @see this::restoreUnboundObjects() - */ - function findDeletedObjects() - { - // check mode: analyze - if ($this->mode["scan"] !== true) - { - return false; - } - - // init - $this->deleted_objects = array(); - - $this->writeScanLogLine("\nfindDeletedObjects:"); - - // Delete objects, start with the oldest objects first - $query = "SELECT object_data.*,tree.tree,tree.child,tree.parent,deleted ". - "FROM object_data ". - "LEFT JOIN object_reference ON object_data.obj_id=object_reference.obj_id ". - "LEFT JOIN tree ON tree.child=object_reference.ref_id ". - " WHERE tree != 1 ". - " ORDER BY deleted"; - $r = $this->db->query($query); - - include_once './Services/Calendar/classes/class.ilDateTime.php'; - while ($row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - $tmp_date = new ilDateTime($row->deleted,IL_CAL_DATETIME); - - $this->deleted_objects[] = array( - "child" => $row->child, - "parent" => $row->parent, - "tree" => $row->tree, - "type" => $row->type, - "title" => $row->title, - "desc" => $row->description, - "owner" => $row->owner, - "deleted" => $row->deleted, - "deleted_timestamp" => $tmp_date->get(IL_CAL_UNIX), - "create_date" => $row->create_date, - "last_update" => $row->last_update - ); - } - - if (count($this->deleted_objects) > 0) - { - $this->writeScanLogArray(array(array_keys($this->deleted_objects[0]))); - $this->writeScanLogArray($this->deleted_objects); - return true; - } - $this->writeScanLogLine("none"); - return false; - } - - - /** - * Gets all tree entries having no valid parent (=> no valid path to root node) - * Returns an array with - * child => actual entry with broken uplink to its parent - * parent => parent of child that does not exist - * grandparent => grandparent of child (where path to root node continues) - * deleted => containing a negative number (= parent in trash) or NULL (parent does not exist at all) - * - * @access public - * @return array - * @see this::findUnboundObjects() - * @see this::restoreUnboundObjects() - */ - function getUnboundObjects() - { - return $this->unbound_objects; - } - - /** - * Gets all object in trash - * - * @access public - * @return array objects in trash - */ - function getDeletedObjects() - { - return $this->deleted_objects; - } - - /** - * Gets invalid rolefolders (same as missing objects) - * - * @access public - * @return array - * @see this::findMissingObjects() - * @see this::removeInvalidRolefolders() - */ - function getInvalidRolefolders() - { - return $this->invalid_rolefolders; - } - - /** - * Removes all reference entries that are linked with invalid object IDs - * - * @access public - * @param array invalid IDs in object_reference (optional) - * @return boolean true if any ID were removed / false on error or clean mode disabled - * @see this::getInvalidReferences() - * @see this::findInvalidReferences() - */ - function removeInvalidReferences($a_invalid_refs = NULL) - { - $ilLog = $this->log; - $ilDB = $this->db; - - // check mode: clean - if ($this->mode["clean"] !== true) - { - return false; - } - - $this->writeScanLogLine("\nremoveInvalidReferences:"); - - if ($a_invalid_refs === NULL and isset($this->invalid_references)) - { - $a_invalid_refs =& $this->invalid_references; - } - - // handle wrong input - if (!is_array($a_invalid_refs)) - { - $this->throwError(INVALID_PARAM, WARNING, DEBUG); - return false; - } - // no unbound references found. do nothing - if (count($a_invalid_refs) == 0) - { - $this->writeScanLogLine("none"); - return false; - } - -/******************* -removal starts here -********************/ - - $message = sprintf('%s::removeInvalidReferences(): Started...', - get_class($this)); - $ilLog->write($message,$ilLog->WARNING); - - // to make sure - $this->filterWorkspaceObjects($a_invalid_refs); - - foreach ($a_invalid_refs as $entry) - { - $query = "DELETE FROM object_reference WHERE ref_id= ".$this->db->quote($entry["ref_id"],'integer'). - " AND obj_id = ".$this->db->quote($entry["obj_id"],'integer')." "; - $res = $ilDB->manipulate($query); - - $message = sprintf('%s::removeInvalidReferences(): Reference %s removed', - get_class($this), - $entry["ref_id"]); - $ilLog->write($message,$ilLog->WARNING); - - $this->writeScanLogLine("Entry ".$entry["ref_id"]." removed"); - } - - return true; - } - - /** - * Removes all tree entries without any link to a valid object - * - * @access public - * @param array invalid IDs in tree (optional) - * @return boolean true if any ID were removed / false on error or clean mode disabled - * @see this::getInvalidChilds() - * @see this::findInvalidChilds() - */ - function removeInvalidChilds($a_invalid_childs = NULL) - { - $ilLog = $this->log; - - // check mode: clean - if ($this->mode["clean"] !== true) - { - return false; - } - - $this->writeScanLogLine("\nremoveInvalidChilds:"); - - if ($a_invalid_childs === NULL and isset($this->invalid_childs)) - { - $a_invalid_childs =& $this->invalid_childs; - } - - // handle wrong input - if (!is_array($a_invalid_childs)) - { - $this->throwError(INVALID_PARAM, WARNING, DEBUG); - return false; - } - - // no unbound childs found. do nothing - if (count($a_invalid_childs) == 0) - { - $this->writeScanLogLine("none"); - return false; - } - -/******************* -removal starts here -********************/ - - $message = sprintf('%s::removeInvalidChilds(): Started...', - get_class($this)); - $ilLog->write($message,$ilLog->WARNING); - - foreach ($a_invalid_childs as $entry) - { - $q = "DELETE FROM tree WHERE child='".$entry["child"]."'"; - $this->db->query($q); - - $message = sprintf('%s::removeInvalidChilds(): Entry child=%s removed', - get_class($this), - $entry["child"]); - $ilLog->write($message,$ilLog->WARNING); - - $this->writeScanLogLine("Entry ".$entry["child"]." removed"); - } - - return true; - } - - /** - * Removes invalid rolefolders - * - * @access public - * @param array obj_ids of rolefolder objects (optional) - * @return boolean true if any object were removed / false on error or - * remove mode disabled - * @see this::getInvalidRolefolders() - * @see this::findMissingObjects() - */ - function removeInvalidRolefolders($a_invalid_rolefolders = NULL) - { - $ilLog = $this->log; - - // check mode: clean - if ($this->mode["clean"] !== true) - { - return false; - } - - $this->writeScanLogLine("\nremoveInvalidRolefolders:"); - - if ($a_invalid_rolefolders === NULL and isset($this->invalid_rolefolders)) - { - $a_invalid_rolefolders = $this->invalid_rolefolders; - } - - // handle wrong input - if (!is_array($a_invalid_rolefolders)) - { - $this->throwError(INVALID_PARAM, WARNING, DEBUG); - return false; - } - - // no invalid rolefolders found. do nothing - if (count($a_invalid_rolefolders) == 0) - { - $this->writeScanLogLine("none"); - return false; - } - -/******************* -removal starts here -********************/ - - $removed = false; - - $message = sprintf('%s::removeInvalidRolefolders(): Started...', - get_class($this)); - $ilLog->write($message,$ilLog->WARNING); - - // to make sure - $this->filterWorkspaceObjects($a_invalid_rolefolders); - - foreach ($a_invalid_rolefolders as $rolf) - { - // restore ref_id in case of missing - if ($rolf["ref_id"] === NULL) - { - $rolf["ref_id"] = $this->restoreReference($rolf["obj_id"]); - - $this->writeScanLogLine("Created missing reference '".$rolf["ref_id"]."' for rolefolder object '".$rolf["obj_id"]."'"); - } - - // now delete rolefolder - $obj_data = ilObjectFactory::getInstanceByRefId($rolf["ref_id"]); - $obj_data->delete(); - unset($obj_data); - $removed = true; - $this->writeScanLogLine("Removed invalid rolefolder '".$rolf["title"]."' (id=".$rolf["obj_id"].",ref=".$rolf["ref_id"].") from system"); - } - - return $removed; - } - - /** - * Restores missing reference and/or tree entry for all objects found by this::getMissingObjects() - * Restored object are placed in RecoveryFolder - * - * @access public - * @param array obj_ids of missing objects (optional) - * @return boolean true if any object were restored / false on error or restore mode disabled - * @see this::getMissingObjects() - * @see this::findMissingObjects() - */ - function restoreMissingObjects($a_missing_objects = NULL) - { - $rbacadmin = $this->rbacadmin; - $ilLog = $this->log; - - // check mode: restore - if ($this->mode["restore"] !== true) - { - return false; - } - - $this->writeScanLogLine("\nrestoreMissingObjects:"); - - if ($a_missing_objects === NULL and isset($this->missing_objects)) - { - $a_missing_objects = $this->missing_objects; - } - - // handle wrong input - if (!is_array($a_missing_objects)) - { - $this->throwError(INVALID_PARAM, WARNING, DEBUG); - return false; - } - - // no missing objects found. do nothing - if (count($a_missing_objects) == 0) - { - $this->writeScanLogLine("none"); - return false; - } - -/******************* -restore starts here -********************/ - - $restored = false; - - $message = sprintf('%s::restoreMissingObjects(): Started...', - get_class($this)); - $ilLog->write($message,$ilLog->WARNING); - - // to make sure - $this->filterWorkspaceObjects($a_missing_objects); - - foreach ($a_missing_objects as $missing_obj) - { - // restore ref_id in case of missing - if ($missing_obj["ref_id"] === NULL) - { - $missing_obj["ref_id"] = $this->restoreReference($missing_obj["obj_id"]); - - $this->writeScanLogLine("Created missing reference '".$missing_obj["ref_id"]."' for object '".$missing_obj["obj_id"]."'"); - } - - // put in tree under RecoveryFolder if not on exclude list - #if (!in_array($missing_obj["type"],$this->object_types_exclude)) - if(!$this->isExcludedFromRecovery($missing_obj['type'],$missing_obj['obj_id'])) - { - $rbacadmin->revokePermission($missing_obj["ref_id"]); - $obj_data = ilObjectFactory::getInstanceByRefId($missing_obj["ref_id"]); - $obj_data->putInTree(RECOVERY_FOLDER_ID); - $obj_data->setPermissions(RECOVERY_FOLDER_ID); - unset($obj_data); - //$tree->insertNode($missing_obj["ref_id"],RECOVERY_FOLDER_ID); - $restored = true; - $this->writeScanLogLine("Restored object '".$missing_obj["title"]."' (id=".$missing_obj["obj_id"].",ref=".$missing_obj["ref_id"].") in 'Restored objects folder'"); - } - - // TODO: process rolefolders - } - - return $restored; - } - - /** - * restore a reference for an object - * Creates a new reference entry in DB table object_reference for $a_obj_id - * - * @param integer obj_id - * @access private - * @return integer/boolean generated ref_id or false on error - * @see this::restoreMissingObjects() - */ - function restoreReference($a_obj_id) - { - $ilLog = $this->log; - $ilDB = $this->db; - - if (empty($a_obj_id)) - { - $this->throwError(INVALID_PARAM, WARNING, DEBUG); - return false; - } - - $query = "INSERT INTO object_reference (ref_id,obj_id) ". - "VALUES (".$next_id = $ilDB->nextId('object_reference').",".$this->db->quote($a_obj_id,'integer')." )"; - $res = $ilDB->manipulate($query); - - $message = sprintf('%s::restoreReference(): new reference %s for obj_id %s created', - get_class($this), - $next_id, - $a_obj_id); - $ilLog->write($message,$ilLog->WARNING); - - return $next_id; - } - - /** - * Restore objects (and their subobjects) to RecoveryFolder that are valid but not linked correctly - * in the hierarchy because they point to an invalid parent_id - * - * @access public - * @param array list of childs with invalid parents (optional) - * @return boolean false on error or restore mode disabled - * @see this::findUnboundObjects() - * @see this::restoreSubTrees() - */ - function restoreUnboundObjects($a_unbound_objects = NULL) - { - $ilLog = $this->log; - - // check mode: restore - if ($this->mode["restore"] !== true) - { - return false; - } - - $this->writeScanLogLine("\nrestoreUnboundObjects:"); - - if ($a_unbound_objects === NULL and isset($this->unbound_objects)) - { - $a_unbound_objects = $this->unbound_objects; - } - - // handle wrong input - if (!is_array($a_unbound_objects)) - { - $this->throwError(INVALID_PARAM, WARNING, DEBUG); - return false; - } - - $message = sprintf('%s::restoreUnboundObjects(): Started...', - get_class($this)); - $ilLog->write($message,$ilLog->WARNING); - - // start restore process - return $this->restoreSubTrees($a_unbound_objects); - } - - /** - * Restore all objects in trash to RecoveryFolder - * NOTE: All objects will be restored to top of RecoveryFolder regardless of existing hierarchical structure! - * - * @access public - * @param array list of deleted childs (optional) - * @return boolean false on error or restore mode disabled - * @see this::findDeletedObjects() - */ - function restoreTrash($a_deleted_objects = NULL) - { - $ilLog = $this->log; - - // check mode: restore - if ($this->mode["restore_trash"] !== true) - { - return false; - } - - $this->writeScanLogLine("\nrestoreTrash:"); - - if ($a_deleted_objects === NULL and isset($this->deleted_objects)) - { - $a_deleted_objects = $this->deleted_objects; - } - - // handle wrong input - if (!is_array($a_deleted_objects)) - { - $this->throwError(INVALID_PARAM, WARNING, DEBUG); - return false; - } - - $message = sprintf('%s::restoreTrash(): Started...', - get_class($this)); - $ilLog->write($message,$ilLog->WARNING); - - // start restore process - $restored = $this->restoreDeletedObjects($a_deleted_objects); - - if ($restored) - { - $q = "DELETE FROM tree WHERE tree!=1"; - $this->db->query($q); - - $message = sprintf('%s::restoreTrash(): Removed all trees with tree id <> 1', - get_class($this)); - $ilLog->write($message,$ilLog->WARNING); - - $this->writeScanLogLine("Old tree entries removed"); - } - - return $restored; - } - - /** - * Restore deleted objects (and their subobjects) to RecoveryFolder - * - * @access private - * @param array list of nodes - * @return boolean false on error or restore mode disabled - * @see this::restoreTrash() - */ - function restoreDeletedObjects($a_nodes) - { - $tree = $this->tree; - $rbacadmin = $this->rbacadmin; - $ilLog = $this->log; -//vd($a_nodes);exit; - // handle wrong input - if (!is_array($a_nodes)) - { - $this->throwError(INVALID_PARAM, WARNING, DEBUG); - return false; - } - - // no invalid parents found. do nothing - if (count($a_nodes) == 0) - { - $this->writeScanLogLine("none"); - return false; - } - - $message = sprintf('%s::restoreDeletedObjects()): Started...', - get_class($this)); - $ilLog->write($message,$ilLog->WARNING); - - // first delete all rolefolders - // don't save rolefolders, remove them - // TODO process ROLE_FOLDER_ID - foreach ($a_nodes as $key => $node) - { - if ($node["type"] == "rolf") - { - // delete old tree entries - $tree->deleteTree($node); - - $obj_data = ilObjectFactory::getInstanceByRefId($node["child"]); - $obj_data->delete(); - unset($a_nodes[$key]); - } - } - - // process move - foreach ($a_nodes as $node) - { - // delete old tree entries - $tree->deleteTree($node); - - $rbacadmin->revokePermission($node["child"]); - $obj_data = ilObjectFactory::getInstanceByRefId($node["child"]); - $obj_data->putInTree(RECOVERY_FOLDER_ID); - $obj_data->setPermissions(RECOVERY_FOLDER_ID); - } - - return true; - } - - /** - * Restore objects (and their subobjects) to RecoveryFolder - * - * @access private - * @param array list of nodes - * @return boolean false on error or restore mode disabled - * @see this::restoreUnboundObjects() - */ - function restoreSubTrees ($a_nodes) - { - $tree = $this->tree; - $rbacadmin = $this->rbacadmin; - $ilLog = $this->log; - - // handle wrong input - if (!is_array($a_nodes)) - { - $this->throwError(INVALID_PARAM, WARNING, DEBUG); - return false; - } - - // no invalid parents found. do nothing - if (count($a_nodes) == 0) - { - $this->writeScanLogLine("none"); - return false; - } - -/******************* -restore starts here -********************/ - - $subnodes = array(); - $topnode = array(); - - $message = sprintf('%s::restoreSubTrees(): Started...', - get_class($this)); - $ilLog->write($message,$ilLog->WARNING); - - // process move subtree - foreach ($a_nodes as $node) - { - // get node data - $topnode = $tree->getNodeData($node["child"], $node['tree']); - - // don't save rolefolders, remove them - // TODO process ROLE_FOLDER_ID - if ($topnode["type"] == "rolf") - { - $rolfObj = ilObjectFactory::getInstanceByRefId($topnode["child"]); - $rolfObj->delete(); - unset($top_node); - unset($rolfObj); - continue; - } - - // get subnodes of top nodes - $subnodes[$node["child"]] = $tree->getSubtree($topnode); - - // delete old tree entries - $tree->deleteTree($topnode); - } - - // now move all subtrees to new location - // TODO: this whole put in place again stuff needs revision. Permission settings get lost. - foreach ($subnodes as $key => $subnode) - { - - // first paste top_node ... - $rbacadmin->revokePermission($key); - $obj_data = ilObjectFactory::getInstanceByRefId($key); - $obj_data->putInTree(RECOVERY_FOLDER_ID); - $obj_data->setPermissions(RECOVERY_FOLDER_ID); - - $this->writeScanLogLine("Object '".$obj_data->getId()."' restored."); - - // ... remove top_node from list ... - array_shift($subnode); - - // ... insert subtree of top_node if any subnodes exist - if (count($subnode) > 0) - { - foreach ($subnode as $node) - { - $rbacadmin->revokePermission($node["child"]); - $obj_data = ilObjectFactory::getInstanceByRefId($node["child"]); - $obj_data->putInTree($node["parent"]); - $obj_data->setPermissions($node["parent"]); - - $this->writeScanLogLine("Object '".$obj_data->getId()."' restored."); - } - } - } - - // final clean up - $this->findInvalidChilds(); - $this->removeInvalidChilds(); - - return true; - } - - /** - * Removes all objects in trash from system - * - * @access public - * @param array list of nodes to delete - * @return boolean true on success - * @see this::purgeObjects() - * @see this::findDeletedObjects() - */ - function purgeTrash($a_nodes = NULL) - { - $ilLog = $this->log; - - // check mode: purge_trash - if ($this->mode["purge_trash"] !== true) - { - return false; - } - - $this->writeScanLogLine("\npurgeTrash:"); - - if ($a_nodes === NULL and isset($this->deleted_objects)) - { - - - $a_nodes = $this->deleted_objects; - } - $message = sprintf('%s::purgeTrash(): Started...', - get_class($this)); - $ilLog->write($message,$ilLog->WARNING); - - // start purge process - return $this->purgeObjects($a_nodes); - } - - /** - * Removes all invalid objects from system - * - * @access public - * @param array list of nodes to delete - * @return boolean true on success - * @see this::purgeObjects() - * @see this::findUnboundObjects() - */ - function purgeUnboundObjects($a_nodes = NULL) - { - $ilLog = $this->log; - - // check mode: purge - if ($this->mode["purge"] !== true) - { - return false; - } - - $this->writeScanLogLine("\npurgeUnboundObjects:"); - - if ($a_nodes === NULL and isset($this->unbound_objects)) - { - $a_nodes = $this->unbound_objects; - } - - $message = sprintf('%s::purgeUnboundObjects(): Started...', - get_class($this)); - $ilLog->write($message,$ilLog->WARNING); - - // start purge process - return $this->purgeObjects($a_nodes); - } - - /** - * Removes all missing objects from system - * - * @access public - * @param array list of nodes to delete - * @return boolean true on success - * @see this::purgeObjects() - * @see this::findMissingObjects() - */ - function purgeMissingObjects($a_nodes = NULL) - { - $ilLog = $this->log; - - // check mode: purge - if ($this->mode["purge"] !== true) - { - return false; - } - - $this->writeScanLogLine("\npurgeMissingObjects:"); - - if ($a_nodes === NULL and isset($this->missing_objects)) - { - $a_nodes = $this->missing_objects; - } - - $message = sprintf('%s::purgeMissingObjects(): Started...', - get_class($this)); - $ilLog->write($message,$ilLog->WARNING); - - // start purge process - return $this->purgeObjects($a_nodes); - } - - /** - * removes objects from system - * - * @access private - * @param array list of objects - * @return boolean - */ - function purgeObjects($a_nodes) - { - $ilLog = $this->log; - $ilUser = $this->user; - - // Get purge limits - $count_limit = $ilUser->getPref("systemcheck_count_limit"); - if (! is_numeric($count_limit) || $count_limit < 0) - { - $count_limit = count($a_nodes); - } - $timestamp_limit = time(); - $age_limit = $ilUser->getPref("systemcheck_age_limit"); - if (is_numeric($age_limit) && $age_limit > 0) - { - $timestamp_limit -= $age_limit * 60 * 60 * 24; - } - $type_limit = $ilUser->getPref("systemcheck_type_limit"); - if ($type_limit) - { - $type_limit = trim($type_limit); - if (strlen($type_limit) == 0) - { - $type_limit = null; - } - } - - // handle wrong input - if (!is_array($a_nodes)) - { - $this->throwError(INVALID_PARAM, WARNING, DEBUG); - return false; - } - - // start delete process - $this->writeScanLogLine("action\tref_id\tobj_id\ttype\telapsed\ttitle"); - $count = 0; - foreach ($a_nodes as $node) - { - if ($type_limit && $node['type'] != $type_limit) - { - $this->writeScanLogLine("skip\t". - $node['child']."\t\t".$node['type']."\t\t".$node['title'] - ); - continue; - } - - - $count++; - if ($count > $count_limit) - { - $this->writeScanLogLine("Stopped purging after ".($count - 1)." objects, because count limit was reached: ".$count_limit); - break; - } - if ($node["deleted_timestamp"] > $timestamp_limit) - { - $this->writeScanLogLine("Stopped purging after ".($count - 1)." objects, because timestamp limit was reached: ".date("c", $timestamp_limit)); - continue; - } - - $ref_id = ($node["child"]) ? $node["child"] : $node["ref_id"]; - $node_obj = ilObjectFactory::getInstanceByRefId($ref_id,false); - - if ($node_obj === false) - { - $this->invalid_objects[] = $node; - continue; - } - - $message = sprintf('%s::purgeObjects(): Removing object (id:%s ref:%s)', - get_class($this), - $ref_id, - $node_obj->getId()); - $ilLog->write($message,$ilLog->WARNING); - - $startTime = microtime(true); - $node_obj->delete(); - ilTree::_removeEntry($node["tree"],$ref_id); - $endTime = microtime(true); - - $this->writeScanLogLine("purged\t".$ref_id."\t".$node_obj->getId(). - "\t".$node['type']."\t".round($endTime-$startTime,1)."\t".$node['title']); - } - - $this->findInvalidChilds(); - $this->removeInvalidChilds(); - - return true; - } - - /** - * Initializes gaps in lft/rgt values of a tree. - * - * Depending on the value of the gap property of the tree, this function - * either closes all gaps in the tree, or equally distributes gaps all over + $q = "SELECT object_data.*, ref_id FROM object_data " . + "LEFT JOIN object_reference ON object_data.obj_id = object_reference.obj_id " . + "LEFT JOIN tree ON object_reference.ref_id = tree.child " . + "WHERE tree.child IS NULL " . + "AND (object_reference.obj_id IS NOT NULL " . + " OR object_data.type <> 'file' AND " . + $ilDB->in('object_data.type', $this->rbac_object_types, false, 'text') . + ")"; + $r = $this->db->query($q); + + while ($row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + #if (!in_array($row->type,$this->object_types_exclude)) + if (!$this->isExcludedFromRecovery($row->type, $row->obj_id)) { + $this->missing_objects[] = array( + "obj_id" => $row->obj_id, + "type" => $row->type, + "ref_id" => $row->ref_id, + "child" => $row->child, + "title" => $row->title, + "desc" => $row->description, + "owner" => $row->owner, + "create_date" => $row->create_date, + "last_update" => $row->last_update + ); + } + } + + $this->filterWorkspaceObjects($this->missing_objects); + if (count($this->missing_objects) > 0) { + $this->writeScanLogLine("obj_id\ttype\tref_id\tchild\ttitle\tdesc\towner\tcreate_date\tlast_update"); + $this->writeScanLogArray($this->missing_objects); + return true; + } + + $this->writeScanLogLine("none"); + return false; + } + + /** + * Search database for all rolefolder object entries with missing reference + * entry. Furthermore gets all rolefolders that are placed accidently in + * RECOVERY_FOLDER from earlier versions of System check. + * Result is stored in $this->invalid_rolefolders + * + * @access public + * @return boolean false if analyze mode disabled or nothing found + * @see this::getInvalidRolefolders() + * @see this::removeInvalidRolefolders() + */ + public function findInvalidRolefolders() + { + $ilDB = $this->db; + + // check mode: analyze + if ($this->mode["scan"] !== true) { + return false; + } + + // init + $this->invalid_rolefolders = array(); + + $this->writeScanLogLine("\nfindInvalidRolefolders:"); + + // find rolfs without reference/tree entry + $q = "SELECT object_data.*, ref_id FROM object_data " . + "LEFT JOIN object_reference ON object_data.obj_id = object_reference.obj_id " . + "LEFT JOIN tree ON object_reference.ref_id = tree.child " . + "WHERE (object_reference.obj_id IS NULL OR tree.child IS NULL) " . + "AND object_data.type='rolf'"; + $r = $this->db->query($q); + + while ($row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + $this->invalid_rolefolders[] = array( + "obj_id" => $row->obj_id, + "type" => $row->type, + "ref_id" => $row->ref_id, + "child" => $row->child, + "title" => $row->title, + "desc" => $row->description, + "owner" => $row->owner, + "create_date" => $row->create_date, + "last_update" => $row->last_update + ); + } + + // find rolfs within RECOVERY FOLDER + $q = "SELECT object_data.*, ref_id FROM object_data " . + "LEFT JOIN object_reference ON object_data.obj_id = object_reference.obj_id " . + "LEFT JOIN tree ON object_reference.ref_id = tree.child " . + "WHERE object_reference.ref_id = " . $ilDB->quote(RECOVERY_FOLDER_ID, 'integer') . " " . + "AND object_data.type='rolf'"; + $r = $this->db->query($q); + + while ($row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + $this->invalid_rolefolders[] = array( + "obj_id" => $row->obj_id, + "type" => $row->type, + "ref_id" => $row->ref_id, + "child" => $row->child, + "title" => $row->title, + "desc" => $row->description, + "owner" => $row->owner, + "create_date" => $row->create_date, + "last_update" => $row->last_update + ); + } + + $this->filterWorkspaceObjects($this->invalid_rolefolders); + if (count($this->invalid_rolefolders) > 0) { + $this->writeScanLogLine("obj_id\ttype\tref_id\tchild\ttitle\tdesc\towner\tcreate_date\tlast_update"); + $this->writeScanLogArray($this->invalid_rolefolders); + return true; + } + + $this->writeScanLogLine("none"); + return false; + } + + /** + * Search database for all role entries that are linked to invalid + * ref_ids + * + * @access public + * @return boolean false if analyze mode disabled or nothing found + * @see this::getInvalidRBACEntries() + * @see this::removeInvalidRBACEntries() + */ + public function findInvalidRBACEntries() + { + $ilDB = $this->db; + + // check mode: analyze + if ($this->mode["scan"] !== true) { + return false; + } + + // init + $this->invalid_rbac_entries = array(); + + $this->writeScanLogLine("\nfindInvalidRBACEntries:"); + + $q = "SELECT object_data.*, ref_id FROM object_data " . + "LEFT JOIN object_reference ON object_data.obj_id = object_reference.obj_id " . + "LEFT JOIN tree ON object_reference.ref_id = tree.child " . + "WHERE (object_reference.obj_id IS NULL OR tree.child IS NULL) " . + "AND object_data.type='rolf'"; + $r = $this->db->query($q); + + while ($row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + $this->invalid_rolefolders[] = array( + "obj_id" => $row->obj_id, + "type" => $row->type, + "ref_id" => $row->ref_id, + "child" => $row->child, + "title" => $row->title, + "desc" => $row->description, + "owner" => $row->owner, + "create_date" => $row->create_date, + "last_update" => $row->last_update + ); + } + + // find rolfs within RECOVERY FOLDER + $q = "SELECT object_data.*, ref_id FROM object_data " . + "LEFT JOIN object_reference ON object_data.obj_id = object_reference.obj_id " . + "LEFT JOIN tree ON object_reference.ref_id = tree.child " . + "WHERE object_reference.ref_id =" . $ilDB->quote(RECOVERY_FOLDER_ID) . " " . + "AND object_data.type='rolf'"; + $r = $this->db->query($q); + + while ($row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + $this->invalid_rolefolders[] = array( + "obj_id" => $row->obj_id, + "type" => $row->type, + "ref_id" => $row->ref_id, + "child" => $row->child, + "title" => $row->title, + "desc" => $row->description, + "owner" => $row->owner, + "create_date" => $row->create_date, + "last_update" => $row->last_update + ); + } + + $this->filterWorkspaceObjects($this->invalid_rolefolders); + if (count($this->invalid_rolefolders) > 0) { + $this->writeScanLogLine("obj_id\ttype\tref_id\tchild\ttitle\tdesc\towner\tcreate_date\tlast_update"); + $this->writeScanLogArray($this->invalid_rolefolders); + return true; + } + + $this->writeScanLogLine("none"); + return false; + } + + /** + * Gets all object entries with missing reference and/or tree entry. + * Returns array with + * obj_id => actual object entry with missing reference or tree + * type => symbolic name of object type + * ref_id => reference entry of object (or NULL if missing) + * child => always NULL (only for debugging and verification) + * + * @access public + * @return array + * @see this::findMissingObjects() + * @see this::restoreMissingObjects() + */ + public function getMissingObjects() + { + return $this->missing_objects; + } + + /** + * Search database for all reference entries that are not linked with a valid object id + * and stores result in $this->invalid_references + * + * @access public + * @return boolean false if analyze mode disabled or nothing found + * @see this::getInvalidReferences() + * @see this::removeInvalidReferences() + */ + public function findInvalidReferences() + { + $ilDB = $this->db; + + // check mode: analyze + if ($this->mode["scan"] !== true) { + return false; + } + + // init + $this->invalid_references = array(); + + $this->writeScanLogLine("\nfindInvalidReferences:"); + $q = "SELECT object_reference.* FROM object_reference " . + "LEFT JOIN object_data ON object_data.obj_id = object_reference.obj_id " . + "WHERE object_data.obj_id IS NULL " . + "OR " . $ilDB->in('object_data.type', $this->rbac_object_types, true, 'text'); + $r = $this->db->query($q); + + while ($row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + $this->invalid_references[] = array( + "ref_id" => $row->ref_id, + "obj_id" => $row->obj_id, + "msg" => "Object does not exist." + ); + } + + $this->filterWorkspaceObjects($this->invalid_references); + if (count($this->invalid_references) > 0) { + $this->writeScanLogLine("ref_id\t\tobj_id"); + $this->writeScanLogArray($this->invalid_references); + return true; + } + + $this->writeScanLogLine("none"); + return false; + } + + /** + * Gets all reference entries that are not linked with a valid object id. + * + * @access public + * @return array + * @see this::findInvalidReferences() + * @see this::removeInvalidReferences() + */ + public function getInvalidReferences() + { + return $this->invalid_references; + } + + /** + * Search database for all tree entries without any link to a valid object + * and stores result in $this->invalid_childs + * + * @access public + * @return boolean false if analyze mode disabled or nothing found + * @see this::getInvalidChilds() + * @see this::removeInvalidChilds() + */ + public function findInvalidChilds() + { + $ilDB = $this->db; + + // check mode: analyze + if ($this->mode["scan"] !== true) { + return false; + } + + // init + $this->invalid_childs = array(); + + $this->writeScanLogLine("\nfindInvalidChilds:"); + + $q = "SELECT tree.*,object_reference.ref_id FROM tree " . + "LEFT JOIN object_reference ON tree.child = object_reference.ref_id " . + "LEFT JOIN object_data ON object_reference.obj_id = object_data.obj_id " . + "WHERE object_reference.ref_id IS NULL or object_data.obj_id IS NULL"; + $r = $this->db->query($q); + while ($row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + $this->invalid_childs[] = array( + "child" => $row->child, + "ref_id" => $row->ref_id, + "msg" => "No object found" + ); + } + + if (count($this->invalid_childs) > 0) { + $this->writeScanLogLine("child\t\tref_id"); + $this->writeScanLogArray($this->invalid_childs); + return true; + } + + $this->writeScanLogLine("none"); + return false; + } + + /** + * Gets all tree entries without any link to a valid object + * + * @access public + * @return array + * @see this::findInvalidChilds() + * @see this::removeInvalidChilds() + */ + public function getInvalidChilds() + { + return $this->invalid_childs; + } + + /** + * Search database for all tree entries having no valid parent (=> no valid path to root node) + * and stores result in $this->unbound_objects + * Result does not contain childs that are marked as deleted! Deleted childs + * have a negative number. + * + * @access public + * @return boolean false if analyze mode disabled or nothing found + * @see this::getUnboundObjects() + * @see this::restoreUnboundObjects() + */ + public function findUnboundObjects() + { + // check mode: analyze + if ($this->mode["scan"] !== true) { + return false; + } + + // init + $this->unbound_objects = array(); + + $this->writeScanLogLine("\nfindUnboundObjects:"); + + $q = "SELECT T1.tree,T1.child,T1.parent," . + "T2.tree deleted,T2.parent grandparent " . + "FROM tree T1 " . + "LEFT JOIN tree T2 ON T2.child=T1.parent " . + "WHERE (T2.tree!=1 OR T2.tree IS NULL) AND T1.parent!=0"; + $r = $this->db->query($q); + + while ($row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + // exclude deleted nodes + if ($row->deleted === null) { + $this->unbound_objects[] = array( + "child" => $row->child, + "parent" => $row->parent, + "tree" => $row->tree, + "msg" => "No valid parent node found" + ); + } + } + + if (count($this->unbound_objects) > 0) { + $this->writeScanLogLine("child\t\tparent\ttree"); + $this->writeScanLogArray($this->unbound_objects); + return true; + } + + $this->writeScanLogLine("none"); + return false; + } + + /** + * Search database for all tree entries having no valid parent (=> no valid path to root node) + * and stores result in $this->unbound_objects + * Result also contains childs that are marked as deleted! Deleted childs has + * a negative number in ["deleted"] otherwise NULL. + * + * @access public + * @return boolean false if analyze mode disabled or nothing found + * @see this::getUnboundObjects() + * @see this::restoreUnboundObjects() + */ + public function findDeletedObjects() + { + // check mode: analyze + if ($this->mode["scan"] !== true) { + return false; + } + + // init + $this->deleted_objects = array(); + + $this->writeScanLogLine("\nfindDeletedObjects:"); + + // Delete objects, start with the oldest objects first + $query = "SELECT object_data.*,tree.tree,tree.child,tree.parent,deleted " . + "FROM object_data " . + "LEFT JOIN object_reference ON object_data.obj_id=object_reference.obj_id " . + "LEFT JOIN tree ON tree.child=object_reference.ref_id " . + " WHERE tree != 1 " . + " ORDER BY deleted"; + $r = $this->db->query($query); + + include_once './Services/Calendar/classes/class.ilDateTime.php'; + while ($row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + $tmp_date = new ilDateTime($row->deleted, IL_CAL_DATETIME); + + $this->deleted_objects[] = array( + "child" => $row->child, + "parent" => $row->parent, + "tree" => $row->tree, + "type" => $row->type, + "title" => $row->title, + "desc" => $row->description, + "owner" => $row->owner, + "deleted" => $row->deleted, + "deleted_timestamp" => $tmp_date->get(IL_CAL_UNIX), + "create_date" => $row->create_date, + "last_update" => $row->last_update + ); + } + + if (count($this->deleted_objects) > 0) { + $this->writeScanLogArray(array(array_keys($this->deleted_objects[0]))); + $this->writeScanLogArray($this->deleted_objects); + return true; + } + $this->writeScanLogLine("none"); + return false; + } + + + /** + * Gets all tree entries having no valid parent (=> no valid path to root node) + * Returns an array with + * child => actual entry with broken uplink to its parent + * parent => parent of child that does not exist + * grandparent => grandparent of child (where path to root node continues) + * deleted => containing a negative number (= parent in trash) or NULL (parent does not exist at all) + * + * @access public + * @return array + * @see this::findUnboundObjects() + * @see this::restoreUnboundObjects() + */ + public function getUnboundObjects() + { + return $this->unbound_objects; + } + + /** + * Gets all object in trash + * + * @access public + * @return array objects in trash + */ + public function getDeletedObjects() + { + return $this->deleted_objects; + } + + /** + * Gets invalid rolefolders (same as missing objects) + * + * @access public + * @return array + * @see this::findMissingObjects() + * @see this::removeInvalidRolefolders() + */ + public function getInvalidRolefolders() + { + return $this->invalid_rolefolders; + } + + /** + * Removes all reference entries that are linked with invalid object IDs + * + * @access public + * @param array invalid IDs in object_reference (optional) + * @return boolean true if any ID were removed / false on error or clean mode disabled + * @see this::getInvalidReferences() + * @see this::findInvalidReferences() + */ + public function removeInvalidReferences($a_invalid_refs = null) + { + $ilLog = $this->log; + $ilDB = $this->db; + + // check mode: clean + if ($this->mode["clean"] !== true) { + return false; + } + + $this->writeScanLogLine("\nremoveInvalidReferences:"); + + if ($a_invalid_refs === null and isset($this->invalid_references)) { + $a_invalid_refs =&$this->invalid_references; + } + + // handle wrong input + if (!is_array($a_invalid_refs)) { + $this->throwError(INVALID_PARAM, WARNING, DEBUG); + return false; + } + // no unbound references found. do nothing + if (count($a_invalid_refs) == 0) { + $this->writeScanLogLine("none"); + return false; + } + + /******************* + removal starts here + ********************/ + + $message = sprintf( + '%s::removeInvalidReferences(): Started...', + get_class($this) + ); + $ilLog->write($message, $ilLog->WARNING); + + // to make sure + $this->filterWorkspaceObjects($a_invalid_refs); + + foreach ($a_invalid_refs as $entry) { + $query = "DELETE FROM object_reference WHERE ref_id= " . $this->db->quote($entry["ref_id"], 'integer') . + " AND obj_id = " . $this->db->quote($entry["obj_id"], 'integer') . " "; + $res = $ilDB->manipulate($query); + + $message = sprintf( + '%s::removeInvalidReferences(): Reference %s removed', + get_class($this), + $entry["ref_id"] + ); + $ilLog->write($message, $ilLog->WARNING); + + $this->writeScanLogLine("Entry " . $entry["ref_id"] . " removed"); + } + + return true; + } + + /** + * Removes all tree entries without any link to a valid object + * + * @access public + * @param array invalid IDs in tree (optional) + * @return boolean true if any ID were removed / false on error or clean mode disabled + * @see this::getInvalidChilds() + * @see this::findInvalidChilds() + */ + public function removeInvalidChilds($a_invalid_childs = null) + { + $ilLog = $this->log; + + // check mode: clean + if ($this->mode["clean"] !== true) { + return false; + } + + $this->writeScanLogLine("\nremoveInvalidChilds:"); + + if ($a_invalid_childs === null and isset($this->invalid_childs)) { + $a_invalid_childs =&$this->invalid_childs; + } + + // handle wrong input + if (!is_array($a_invalid_childs)) { + $this->throwError(INVALID_PARAM, WARNING, DEBUG); + return false; + } + + // no unbound childs found. do nothing + if (count($a_invalid_childs) == 0) { + $this->writeScanLogLine("none"); + return false; + } + + /******************* + removal starts here + ********************/ + + $message = sprintf( + '%s::removeInvalidChilds(): Started...', + get_class($this) + ); + $ilLog->write($message, $ilLog->WARNING); + + foreach ($a_invalid_childs as $entry) { + $q = "DELETE FROM tree WHERE child='" . $entry["child"] . "'"; + $this->db->query($q); + + $message = sprintf( + '%s::removeInvalidChilds(): Entry child=%s removed', + get_class($this), + $entry["child"] + ); + $ilLog->write($message, $ilLog->WARNING); + + $this->writeScanLogLine("Entry " . $entry["child"] . " removed"); + } + + return true; + } + + /** + * Removes invalid rolefolders + * + * @access public + * @param array obj_ids of rolefolder objects (optional) + * @return boolean true if any object were removed / false on error or + * remove mode disabled + * @see this::getInvalidRolefolders() + * @see this::findMissingObjects() + */ + public function removeInvalidRolefolders($a_invalid_rolefolders = null) + { + $ilLog = $this->log; + + // check mode: clean + if ($this->mode["clean"] !== true) { + return false; + } + + $this->writeScanLogLine("\nremoveInvalidRolefolders:"); + + if ($a_invalid_rolefolders === null and isset($this->invalid_rolefolders)) { + $a_invalid_rolefolders = $this->invalid_rolefolders; + } + + // handle wrong input + if (!is_array($a_invalid_rolefolders)) { + $this->throwError(INVALID_PARAM, WARNING, DEBUG); + return false; + } + + // no invalid rolefolders found. do nothing + if (count($a_invalid_rolefolders) == 0) { + $this->writeScanLogLine("none"); + return false; + } + + /******************* + removal starts here + ********************/ + + $removed = false; + + $message = sprintf( + '%s::removeInvalidRolefolders(): Started...', + get_class($this) + ); + $ilLog->write($message, $ilLog->WARNING); + + // to make sure + $this->filterWorkspaceObjects($a_invalid_rolefolders); + + foreach ($a_invalid_rolefolders as $rolf) { + // restore ref_id in case of missing + if ($rolf["ref_id"] === null) { + $rolf["ref_id"] = $this->restoreReference($rolf["obj_id"]); + + $this->writeScanLogLine("Created missing reference '" . $rolf["ref_id"] . "' for rolefolder object '" . $rolf["obj_id"] . "'"); + } + + // now delete rolefolder + $obj_data = ilObjectFactory::getInstanceByRefId($rolf["ref_id"]); + $obj_data->delete(); + unset($obj_data); + $removed = true; + $this->writeScanLogLine("Removed invalid rolefolder '" . $rolf["title"] . "' (id=" . $rolf["obj_id"] . ",ref=" . $rolf["ref_id"] . ") from system"); + } + + return $removed; + } + + /** + * Restores missing reference and/or tree entry for all objects found by this::getMissingObjects() + * Restored object are placed in RecoveryFolder + * + * @access public + * @param array obj_ids of missing objects (optional) + * @return boolean true if any object were restored / false on error or restore mode disabled + * @see this::getMissingObjects() + * @see this::findMissingObjects() + */ + public function restoreMissingObjects($a_missing_objects = null) + { + $rbacadmin = $this->rbacadmin; + $ilLog = $this->log; + + // check mode: restore + if ($this->mode["restore"] !== true) { + return false; + } + + $this->writeScanLogLine("\nrestoreMissingObjects:"); + + if ($a_missing_objects === null and isset($this->missing_objects)) { + $a_missing_objects = $this->missing_objects; + } + + // handle wrong input + if (!is_array($a_missing_objects)) { + $this->throwError(INVALID_PARAM, WARNING, DEBUG); + return false; + } + + // no missing objects found. do nothing + if (count($a_missing_objects) == 0) { + $this->writeScanLogLine("none"); + return false; + } + + /******************* + restore starts here + ********************/ + + $restored = false; + + $message = sprintf( + '%s::restoreMissingObjects(): Started...', + get_class($this) + ); + $ilLog->write($message, $ilLog->WARNING); + + // to make sure + $this->filterWorkspaceObjects($a_missing_objects); + + foreach ($a_missing_objects as $missing_obj) { + // restore ref_id in case of missing + if ($missing_obj["ref_id"] === null) { + $missing_obj["ref_id"] = $this->restoreReference($missing_obj["obj_id"]); + + $this->writeScanLogLine("Created missing reference '" . $missing_obj["ref_id"] . "' for object '" . $missing_obj["obj_id"] . "'"); + } + + // put in tree under RecoveryFolder if not on exclude list + #if (!in_array($missing_obj["type"],$this->object_types_exclude)) + if (!$this->isExcludedFromRecovery($missing_obj['type'], $missing_obj['obj_id'])) { + $rbacadmin->revokePermission($missing_obj["ref_id"]); + $obj_data = ilObjectFactory::getInstanceByRefId($missing_obj["ref_id"]); + $obj_data->putInTree(RECOVERY_FOLDER_ID); + $obj_data->setPermissions(RECOVERY_FOLDER_ID); + unset($obj_data); + //$tree->insertNode($missing_obj["ref_id"],RECOVERY_FOLDER_ID); + $restored = true; + $this->writeScanLogLine("Restored object '" . $missing_obj["title"] . "' (id=" . $missing_obj["obj_id"] . ",ref=" . $missing_obj["ref_id"] . ") in 'Restored objects folder'"); + } + + // TODO: process rolefolders + } + + return $restored; + } + + /** + * restore a reference for an object + * Creates a new reference entry in DB table object_reference for $a_obj_id + * + * @param integer obj_id + * @access private + * @return integer/boolean generated ref_id or false on error + * @see this::restoreMissingObjects() + */ + public function restoreReference($a_obj_id) + { + $ilLog = $this->log; + $ilDB = $this->db; + + if (empty($a_obj_id)) { + $this->throwError(INVALID_PARAM, WARNING, DEBUG); + return false; + } + + $query = "INSERT INTO object_reference (ref_id,obj_id) " . + "VALUES (" . $next_id = $ilDB->nextId('object_reference') . "," . $this->db->quote($a_obj_id, 'integer') . " )"; + $res = $ilDB->manipulate($query); + + $message = sprintf( + '%s::restoreReference(): new reference %s for obj_id %s created', + get_class($this), + $next_id, + $a_obj_id + ); + $ilLog->write($message, $ilLog->WARNING); + + return $next_id; + } + + /** + * Restore objects (and their subobjects) to RecoveryFolder that are valid but not linked correctly + * in the hierarchy because they point to an invalid parent_id + * + * @access public + * @param array list of childs with invalid parents (optional) + * @return boolean false on error or restore mode disabled + * @see this::findUnboundObjects() + * @see this::restoreSubTrees() + */ + public function restoreUnboundObjects($a_unbound_objects = null) + { + $ilLog = $this->log; + + // check mode: restore + if ($this->mode["restore"] !== true) { + return false; + } + + $this->writeScanLogLine("\nrestoreUnboundObjects:"); + + if ($a_unbound_objects === null and isset($this->unbound_objects)) { + $a_unbound_objects = $this->unbound_objects; + } + + // handle wrong input + if (!is_array($a_unbound_objects)) { + $this->throwError(INVALID_PARAM, WARNING, DEBUG); + return false; + } + + $message = sprintf( + '%s::restoreUnboundObjects(): Started...', + get_class($this) + ); + $ilLog->write($message, $ilLog->WARNING); + + // start restore process + return $this->restoreSubTrees($a_unbound_objects); + } + + /** + * Restore all objects in trash to RecoveryFolder + * NOTE: All objects will be restored to top of RecoveryFolder regardless of existing hierarchical structure! + * + * @access public + * @param array list of deleted childs (optional) + * @return boolean false on error or restore mode disabled + * @see this::findDeletedObjects() + */ + public function restoreTrash($a_deleted_objects = null) + { + $ilLog = $this->log; + + // check mode: restore + if ($this->mode["restore_trash"] !== true) { + return false; + } + + $this->writeScanLogLine("\nrestoreTrash:"); + + if ($a_deleted_objects === null and isset($this->deleted_objects)) { + $a_deleted_objects = $this->deleted_objects; + } + + // handle wrong input + if (!is_array($a_deleted_objects)) { + $this->throwError(INVALID_PARAM, WARNING, DEBUG); + return false; + } + + $message = sprintf( + '%s::restoreTrash(): Started...', + get_class($this) + ); + $ilLog->write($message, $ilLog->WARNING); + + // start restore process + $restored = $this->restoreDeletedObjects($a_deleted_objects); + + if ($restored) { + $q = "DELETE FROM tree WHERE tree!=1"; + $this->db->query($q); + + $message = sprintf( + '%s::restoreTrash(): Removed all trees with tree id <> 1', + get_class($this) + ); + $ilLog->write($message, $ilLog->WARNING); + + $this->writeScanLogLine("Old tree entries removed"); + } + + return $restored; + } + + /** + * Restore deleted objects (and their subobjects) to RecoveryFolder + * + * @access private + * @param array list of nodes + * @return boolean false on error or restore mode disabled + * @see this::restoreTrash() + */ + public function restoreDeletedObjects($a_nodes) + { + $tree = $this->tree; + $rbacadmin = $this->rbacadmin; + $ilLog = $this->log; + //vd($a_nodes);exit; + // handle wrong input + if (!is_array($a_nodes)) { + $this->throwError(INVALID_PARAM, WARNING, DEBUG); + return false; + } + + // no invalid parents found. do nothing + if (count($a_nodes) == 0) { + $this->writeScanLogLine("none"); + return false; + } + + $message = sprintf( + '%s::restoreDeletedObjects()): Started...', + get_class($this) + ); + $ilLog->write($message, $ilLog->WARNING); + + // first delete all rolefolders + // don't save rolefolders, remove them + // TODO process ROLE_FOLDER_ID + foreach ($a_nodes as $key => $node) { + if ($node["type"] == "rolf") { + // delete old tree entries + $tree->deleteTree($node); + + $obj_data = ilObjectFactory::getInstanceByRefId($node["child"]); + $obj_data->delete(); + unset($a_nodes[$key]); + } + } + + // process move + foreach ($a_nodes as $node) { + // delete old tree entries + $tree->deleteTree($node); + + $rbacadmin->revokePermission($node["child"]); + $obj_data = ilObjectFactory::getInstanceByRefId($node["child"]); + $obj_data->putInTree(RECOVERY_FOLDER_ID); + $obj_data->setPermissions(RECOVERY_FOLDER_ID); + } + + return true; + } + + /** + * Restore objects (and their subobjects) to RecoveryFolder + * + * @access private + * @param array list of nodes + * @return boolean false on error or restore mode disabled + * @see this::restoreUnboundObjects() + */ + public function restoreSubTrees($a_nodes) + { + $tree = $this->tree; + $rbacadmin = $this->rbacadmin; + $ilLog = $this->log; + + // handle wrong input + if (!is_array($a_nodes)) { + $this->throwError(INVALID_PARAM, WARNING, DEBUG); + return false; + } + + // no invalid parents found. do nothing + if (count($a_nodes) == 0) { + $this->writeScanLogLine("none"); + return false; + } + + /******************* + restore starts here + ********************/ + + $subnodes = array(); + $topnode = array(); + + $message = sprintf( + '%s::restoreSubTrees(): Started...', + get_class($this) + ); + $ilLog->write($message, $ilLog->WARNING); + + // process move subtree + foreach ($a_nodes as $node) { + // get node data + $topnode = $tree->getNodeData($node["child"], $node['tree']); + + // don't save rolefolders, remove them + // TODO process ROLE_FOLDER_ID + if ($topnode["type"] == "rolf") { + $rolfObj = ilObjectFactory::getInstanceByRefId($topnode["child"]); + $rolfObj->delete(); + unset($top_node); + unset($rolfObj); + continue; + } + + // get subnodes of top nodes + $subnodes[$node["child"]] = $tree->getSubtree($topnode); + + // delete old tree entries + $tree->deleteTree($topnode); + } + + // now move all subtrees to new location + // TODO: this whole put in place again stuff needs revision. Permission settings get lost. + foreach ($subnodes as $key => $subnode) { + + // first paste top_node ... + $rbacadmin->revokePermission($key); + $obj_data = ilObjectFactory::getInstanceByRefId($key); + $obj_data->putInTree(RECOVERY_FOLDER_ID); + $obj_data->setPermissions(RECOVERY_FOLDER_ID); + + $this->writeScanLogLine("Object '" . $obj_data->getId() . "' restored."); + + // ... remove top_node from list ... + array_shift($subnode); + + // ... insert subtree of top_node if any subnodes exist + if (count($subnode) > 0) { + foreach ($subnode as $node) { + $rbacadmin->revokePermission($node["child"]); + $obj_data = ilObjectFactory::getInstanceByRefId($node["child"]); + $obj_data->putInTree($node["parent"]); + $obj_data->setPermissions($node["parent"]); + + $this->writeScanLogLine("Object '" . $obj_data->getId() . "' restored."); + } + } + } + + // final clean up + $this->findInvalidChilds(); + $this->removeInvalidChilds(); + + return true; + } + + /** + * Removes all objects in trash from system + * + * @access public + * @param array list of nodes to delete + * @return boolean true on success + * @see this::purgeObjects() + * @see this::findDeletedObjects() + */ + public function purgeTrash($a_nodes = null) + { + $ilLog = $this->log; + + // check mode: purge_trash + if ($this->mode["purge_trash"] !== true) { + return false; + } + + $this->writeScanLogLine("\npurgeTrash:"); + + if ($a_nodes === null and isset($this->deleted_objects)) { + $a_nodes = $this->deleted_objects; + } + $message = sprintf( + '%s::purgeTrash(): Started...', + get_class($this) + ); + $ilLog->write($message, $ilLog->WARNING); + + // start purge process + return $this->purgeObjects($a_nodes); + } + + /** + * Removes all invalid objects from system + * + * @access public + * @param array list of nodes to delete + * @return boolean true on success + * @see this::purgeObjects() + * @see this::findUnboundObjects() + */ + public function purgeUnboundObjects($a_nodes = null) + { + $ilLog = $this->log; + + // check mode: purge + if ($this->mode["purge"] !== true) { + return false; + } + + $this->writeScanLogLine("\npurgeUnboundObjects:"); + + if ($a_nodes === null and isset($this->unbound_objects)) { + $a_nodes = $this->unbound_objects; + } + + $message = sprintf( + '%s::purgeUnboundObjects(): Started...', + get_class($this) + ); + $ilLog->write($message, $ilLog->WARNING); + + // start purge process + return $this->purgeObjects($a_nodes); + } + + /** + * Removes all missing objects from system + * + * @access public + * @param array list of nodes to delete + * @return boolean true on success + * @see this::purgeObjects() + * @see this::findMissingObjects() + */ + public function purgeMissingObjects($a_nodes = null) + { + $ilLog = $this->log; + + // check mode: purge + if ($this->mode["purge"] !== true) { + return false; + } + + $this->writeScanLogLine("\npurgeMissingObjects:"); + + if ($a_nodes === null and isset($this->missing_objects)) { + $a_nodes = $this->missing_objects; + } + + $message = sprintf( + '%s::purgeMissingObjects(): Started...', + get_class($this) + ); + $ilLog->write($message, $ilLog->WARNING); + + // start purge process + return $this->purgeObjects($a_nodes); + } + + /** + * removes objects from system + * + * @access private + * @param array list of objects + * @return boolean + */ + public function purgeObjects($a_nodes) + { + $ilLog = $this->log; + $ilUser = $this->user; + + // Get purge limits + $count_limit = $ilUser->getPref("systemcheck_count_limit"); + if (!is_numeric($count_limit) || $count_limit < 0) { + $count_limit = count($a_nodes); + } + $timestamp_limit = time(); + $age_limit = $ilUser->getPref("systemcheck_age_limit"); + if (is_numeric($age_limit) && $age_limit > 0) { + $timestamp_limit -= $age_limit * 60 * 60 * 24; + } + $type_limit = $ilUser->getPref("systemcheck_type_limit"); + if ($type_limit) { + $type_limit = trim($type_limit); + if (strlen($type_limit) == 0) { + $type_limit = null; + } + } + + // handle wrong input + if (!is_array($a_nodes)) { + $this->throwError(INVALID_PARAM, WARNING, DEBUG); + return false; + } + + // start delete process + $this->writeScanLogLine("action\tref_id\tobj_id\ttype\telapsed\ttitle"); + $count = 0; + foreach ($a_nodes as $node) { + if ($type_limit && $node['type'] != $type_limit) { + $this->writeScanLogLine( + "skip\t" . + $node['child'] . "\t\t" . $node['type'] . "\t\t" . $node['title'] + ); + continue; + } + + + $count++; + if ($count > $count_limit) { + $this->writeScanLogLine("Stopped purging after " . ($count - 1) . " objects, because count limit was reached: " . $count_limit); + break; + } + if ($node["deleted_timestamp"] > $timestamp_limit) { + $this->writeScanLogLine("Stopped purging after " . ($count - 1) . " objects, because timestamp limit was reached: " . date("c", $timestamp_limit)); + continue; + } + + $ref_id = ($node["child"]) ? $node["child"] : $node["ref_id"]; + $node_obj = ilObjectFactory::getInstanceByRefId($ref_id, false); + + if ($node_obj === false) { + $this->invalid_objects[] = $node; + continue; + } + + $message = sprintf( + '%s::purgeObjects(): Removing object (id:%s ref:%s)', + get_class($this), + $ref_id, + $node_obj->getId() + ); + $ilLog->write($message, $ilLog->WARNING); + + $startTime = microtime(true); + $node_obj->delete(); + ilTree::_removeEntry($node["tree"], $ref_id); + $endTime = microtime(true); + + $this->writeScanLogLine("purged\t" . $ref_id . "\t" . $node_obj->getId() . + "\t" . $node['type'] . "\t" . round($endTime-$startTime, 1) . "\t" . $node['title']); + } + + $this->findInvalidChilds(); + $this->removeInvalidChilds(); + + return true; + } + + /** + * Initializes gaps in lft/rgt values of a tree. + * + * Depending on the value of the gap property of the tree, this function + * either closes all gaps in the tree, or equally distributes gaps all over * the tree. - * - * Wrapper for ilTree::renumber() - * - * @access public - * @return boolean false if clean mode disabled - * @see ilTree::renumber() - */ - function initGapsInTree() - { - $tree = $this->tree; - $ilLog = $this->log; - - $message = sprintf('%s::initGapsInTree(): Started...', - get_class($this)); - $ilLog->write($message,$ilLog->WARNING); - - // check mode: clean - if ($this->mode["clean"] !== true) - { - return false; - } - $this->writeScanLogLine("\nrenumberTree:"); - - $tree->renumber(ROOT_FOLDER_ID); - - $this->writeScanLogLine("done"); - - return true; - } - - /** - * Callback function - * handles PEAR_error and outputs detailed infos about error - * TODO: implement that in global errorhandler of ILIAS (via templates) - * - * @access private - * @param object PEAR_error - * @see PEAR::PEAR_error() - */ - function handleErr($error) - { - $call_loc = $error->backtrace[count($error->backtrace)-1]; - $num_args = count($call_loc["args"]); - - if ($num_args > 0) - { - foreach ($call_loc["args"] as $arg) - { - $type = gettype($arg); - - switch ($type) - { - case "string": - $value = strlen($arg); - break; - - case "array": - $value = count($arg); - break; - - case "object": - $value = get_class($arg); - break; - - case "boolean": - $value = ($arg) ? "true" : "false"; - break; - - default: - $value = $arg; - break; - } - - $arg_list[] = array( - "type" => $type, - "value" => "(".$value.")" - ); - } - - foreach ($arg_list as $arg) - { - $arg_str .= implode("",$arg)." "; - } - } - - $err_msg = "
                  ".$error->getCode().": ".$error->getMessage()." in ".$call_loc["class"].$call_loc["type"].$call_loc["function"]."()". - "
                  Called from: ".basename($call_loc["file"])." , line ".$call_loc["line"]. - "
                  Passed parameters: [".$num_args."] ".$arg_str."
                  "; - printf($err_msg); - - if ($error->getUserInfo()) - { - printf("
                  Parameter details:"); - echo "
                  ";
                  -			var_dump($call_loc["args"]);
                  -			echo "
                  "; - } - - if ($error->getCode() == FATAL) - { - exit(); - } - } - - function writeScanLogArray($a_arr) - { - if (!$this->isLogEnabled()) - { - return false; - } - - foreach ($a_arr as $entry) - { - $this->scan_log->write(implode("\t",$entry)); - } - } - - function writeScanLogLine($a_msg) - { - if (!$this->isLogEnabled()) - { - return false; - } - - $this->scan_log->write($a_msg); - } - - /** - * Quickly determine if there is a scan log - */ - function hasScanLog() - { - // file check - return is_file(CLIENT_DATA_DIR."/".$this->scan_log_file); - } - - /** - * Delete scan log. - */ - function deleteScanLog() - { - @unlink(CLIENT_DATA_DIR."/".$this->scan_log_file); - } - - function readScanLog() - { - // file check - if (! $this->hasScanLog()) - { - return false; - } - - $scanfile =& file(CLIENT_DATA_DIR."/".$this->scan_log_file); - if (!$scan_log =& $this->get_last_scan($scanfile)) - { - return false; - } - // Ensure that memory is freed - unset($scanfile); - - return $scan_log; - } - - function get_last_scan($a_scan_log) - { - $logs = array_keys($a_scan_log,$this->scan_log_separator."\n"); - - if (count($logs) > 0) - { - return array_slice($a_scan_log,array_pop($logs)+2); - } - - return false; - } - - function checkTreeStructure($a_startnode = null) - { - $tree = $this->tree; - - $this->writeScanLogLine("\nchecking tree structure is disabled"); - - return false; - } - - /** - * Dumps the Tree structure into the scan log - * - * @access public - * @return number of errors found while dumping tree - */ - function dumpTree() - { - $ilDB = $this->db; - - $this->writeScanLogLine("BEGIN dumpTree:"); - - // collect nodes with duplicate child Id's - // (We use this, to mark these nodes later in the output as being - // erroneous.). - $q = 'SELECT child FROM tree GROUP BY child HAVING COUNT(*) > 1'; - $r = $this->db->query($q); - $duplicateNodes = array(); - while ($row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - $duplicateNodes[] = $row->child; - } - - // dump tree - $q = "SELECT tree.*,ref.ref_id,dat.obj_id objobj_id,ref.obj_id refobj_id,ref.deleted,dat.* " - ."FROM tree " - ."RIGHT JOIN object_reference ref ON tree.child = ref.ref_id " - ."RIGHT JOIN object_data dat ON ref.obj_id = dat.obj_id " + * + * Wrapper for ilTree::renumber() + * + * @access public + * @return boolean false if clean mode disabled + * @see ilTree::renumber() + */ + public function initGapsInTree() + { + $tree = $this->tree; + $ilLog = $this->log; + + $message = sprintf( + '%s::initGapsInTree(): Started...', + get_class($this) + ); + $ilLog->write($message, $ilLog->WARNING); + + // check mode: clean + if ($this->mode["clean"] !== true) { + return false; + } + $this->writeScanLogLine("\nrenumberTree:"); + + $tree->renumber(ROOT_FOLDER_ID); + + $this->writeScanLogLine("done"); + + return true; + } + + /** + * Callback function + * handles PEAR_error and outputs detailed infos about error + * TODO: implement that in global errorhandler of ILIAS (via templates) + * + * @access private + * @param object PEAR_error + * @see PEAR::PEAR_error() + */ + public function handleErr($error) + { + $call_loc = $error->backtrace[count($error->backtrace)-1]; + $num_args = count($call_loc["args"]); + + if ($num_args > 0) { + foreach ($call_loc["args"] as $arg) { + $type = gettype($arg); + + switch ($type) { + case "string": + $value = strlen($arg); + break; + + case "array": + $value = count($arg); + break; + + case "object": + $value = get_class($arg); + break; + + case "boolean": + $value = ($arg) ? "true" : "false"; + break; + + default: + $value = $arg; + break; + } + + $arg_list[] = array( + "type" => $type, + "value" => "(" . $value . ")" + ); + } + + foreach ($arg_list as $arg) { + $arg_str .= implode("", $arg) . " "; + } + } + + $err_msg = "
                  " . $error->getCode() . ": " . $error->getMessage() . " in " . $call_loc["class"] . $call_loc["type"] . $call_loc["function"] . "()" . + "
                  Called from: " . basename($call_loc["file"]) . " , line " . $call_loc["line"] . + "
                  Passed parameters: [" . $num_args . "] " . $arg_str . "
                  "; + printf($err_msg); + + if ($error->getUserInfo()) { + printf("
                  Parameter details:"); + echo "
                  ";
                  +            var_dump($call_loc["args"]);
                  +            echo "
                  "; + } + + if ($error->getCode() == FATAL) { + exit(); + } + } + + public function writeScanLogArray($a_arr) + { + if (!$this->isLogEnabled()) { + return false; + } + + foreach ($a_arr as $entry) { + $this->scan_log->write(implode("\t", $entry)); + } + } + + public function writeScanLogLine($a_msg) + { + if (!$this->isLogEnabled()) { + return false; + } + + $this->scan_log->write($a_msg); + } + + /** + * Quickly determine if there is a scan log + */ + public function hasScanLog() + { + // file check + return is_file(CLIENT_DATA_DIR . "/" . $this->scan_log_file); + } + + /** + * Delete scan log. + */ + public function deleteScanLog() + { + @unlink(CLIENT_DATA_DIR . "/" . $this->scan_log_file); + } + + public function readScanLog() + { + // file check + if (!$this->hasScanLog()) { + return false; + } + + $scanfile =&file(CLIENT_DATA_DIR . "/" . $this->scan_log_file); + if (!$scan_log =&$this->get_last_scan($scanfile)) { + return false; + } + // Ensure that memory is freed + unset($scanfile); + + return $scan_log; + } + + public function get_last_scan($a_scan_log) + { + $logs = array_keys($a_scan_log, $this->scan_log_separator . "\n"); + + if (count($logs) > 0) { + return array_slice($a_scan_log, array_pop($logs)+2); + } + + return false; + } + + public function checkTreeStructure($a_startnode = null) + { + $tree = $this->tree; + + $this->writeScanLogLine("\nchecking tree structure is disabled"); + + return false; + } + + /** + * Dumps the Tree structure into the scan log + * + * @access public + * @return number of errors found while dumping tree + */ + public function dumpTree() + { + $ilDB = $this->db; + + $this->writeScanLogLine("BEGIN dumpTree:"); + + // collect nodes with duplicate child Id's + // (We use this, to mark these nodes later in the output as being + // erroneous.). + $q = 'SELECT child FROM tree GROUP BY child HAVING COUNT(*) > 1'; + $r = $this->db->query($q); + $duplicateNodes = array(); + while ($row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + $duplicateNodes[] = $row->child; + } + + // dump tree + $q = "SELECT tree.*,ref.ref_id,dat.obj_id objobj_id,ref.obj_id refobj_id,ref.deleted,dat.* " + . "FROM tree " + . "RIGHT JOIN object_reference ref ON tree.child = ref.ref_id " + . "RIGHT JOIN object_data dat ON ref.obj_id = dat.obj_id " // ."LEFT JOIN usr_data usr ON usr.usr_id = dat.owner " - ."ORDER BY tree, lft, type, dat.title"; - $r = $this->db->query($q); - - $this->writeScanLogLine( - '' - .'' - .'' - .'' - .'' - ); - - // We use a stack to represent the path to the current node. - // This allows us to do analyze the tree structure without having - // to implement a recursive algorithm. - $stack = array(); - $error_count = 0; - $repository_tree_count = 0; - $trash_trees_count = 0; - $other_trees_count = 0; - $not_in_tree_count = 0; - - // The previous number is used for gap checking - $previousNumber = 0; - - $this->initWorkspaceObjects(); - - while ($row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) - { - // workspace objects are not to be processed - if($this->workspace_object_ids && - in_array($row->objobj_id, $this->workspace_object_ids)) - { - continue; - } - - // If there is no entry in table tree for the object, we display it here - if (is_null($row->child)) - { - switch ($row->type) { - case 'crsg' : - case 'usr' : - case 'typ' : - case 'lng' : - case 'rolt' : - case 'role' : - case 'mob' : - case 'sty' : - case 'tax' : // #13798 - // We are not interested in dumping these object types. - continue 2; - //break; NOT REACHED - case 'file' : - if (is_null($row->ref_id)) { - // File objects can be part of a learning module. - // In this case, they do not have a row in table object_reference. - // We are not interested in dumping these file objects. - continue 2; - } else { - // File objects which have a row in table object_reference, but - // none in table tree are an error. - $error_count++; - $isRowOkay = false; - $isParentOkay = false; - $isLftOkay = false; - $isRgtOkay = false; - $isDepthOkay = false; - } - break; - - - case 'fold': - // ignore folders on media pools - if($this->isMediaFolder($row->obj_id)) - { - continue 2; - } - default : - $error_count++; - $isRowOkay = false; - $isParentOkay = false; - $isLftOkay = false; - $isRgtOkay = false; - $isDepthOkay = false; - break; - } - - // moved here (below continues in switch) - $not_in_tree_count++; - - $this->writeScanLogLine( - '' - .'' - .'' - ); - continue; - } - - // Update stack - // ------------------- - $indent = ""; - for ($i = 1; $i < $row->depth; $i++) - { - $indent .= ". "; - } - - // Initialize the stack and the previous number if we are in a new tree - if (count($stack) == 0 || $stack[0]->tree != $row->tree) - { - $stack = array(); - $previousNumber = $row->lft - 1; - $this->writeScanLogLine(''); - } - // Pop old stack entries - - - while (count($stack) > 0 && $stack[count($stack) - 1]->rgt < $row->lft) - { - $popped = array_pop($stack); - - // check for gap - $gap = $popped->rgt - $previousNumber - 1; - if ($gap > 0) - { - $poppedIndent = ""; - for ($i = 1; $i < $popped->depth; $i++) - { - $poppedIndent .= ". "; - } - $this->writeScanLogLine( - '' - .'' - .'' - .'' - ); - } - $previousNumber = $popped->rgt; - unset($popped); - } - - // Check row integrity - // ------------------- - $isRowOkay = true; - - // Check tree structure - $isChildOkay = true; - $isParentOkay = true; - $isLftOkay = true; - $isRgtOkay = true; - $isDepthOkay = true; - $isGap = false; - - if (count($stack) > 0) - { - $parent = $stack[count($stack) - 1]; - if ($parent->depth + 1 != $row->depth) - { - $isDepthOkay = false; - $isRowOkay = false; - } - if ($parent->child != $row->parent) - { - $isParentOkay = false; - $isRowOkay = false; - } - if($GLOBALS['ilSetting']->get('main_tree_impl','ns') == 'ns') - { - if ($parent->lft >= $row->lft) - { - $isLftOkay = false; - $isRowOkay = false; - } - if ($parent->rgt <= $row->rgt) - { - $isRgtOkay = false; - $isRowOkay = false; - } - } - } - - // Check lft rgt - if($GLOBALS['ilSetting']->get('main_tree_impl','ns') == 'ns') - { - if ($row->lft >= $row->rgt) - { - $isLftOkay = false; - $isRgtOkay = false; - $isRowOkay = false; - } - } - if (in_array($row->child, $duplicateNodes)) - { - $isChildOkay = false; - $isRowOkay = false; - } - - // Check object reference - $isRefRefOkay = true; - $isRefObjOkay = true; - if ($row->ref_id == null) - { - $isRefRefOkay = false; - $isRowOkay = false; - } - if ($row->obj_id == null) - { - $isRefObjOkay = false; - $isRowOkay = false; - } - - if (! $isRowOkay) - { - $error_count++; - } - - // Check for gap between siblings, - // and eventually write a log line - if($GLOBALS['ilSetting']->get('main_tree_impl','ns') == 'ns') - { - $gap = $row->lft - $previousNumber - 1; - $previousNumber = $row->lft; - if ($gap > 0) - { - $this->writeScanLogLine( - '' - .'' - .'' - .'' - ); - } - } - - // Write log line - // ------------------- - $this->writeScanLogLine( - '' - . '' - . '' - ); - - // Update stack - // ------------------- - // Push node on stack - $stack[] = $row; - - // Count nodes - // ----------------- - if ($row->tree == 1) - { - $repository_tree_count++; - } - else if ($row->tree < 0) - { - $trash_trees_count++; - } - else - { - $other_trees_count++; - } - } - // - // Pop remaining stack entries - - while (count($stack) > 0) - { - $popped = array_pop($stack); - - // check for gap - $gap = $popped->rgt - $previousNumber - 1; - if ($gap > 0) - { - $poppedIndent = ""; - for ($i = 1; $i < $popped->depth; $i++) - { - $poppedIndent .= ". "; - } - $this->writeScanLogLine( - '' - .'' - .'' - .'' - ); - } - $previousNumber = $popped->rgt; - unset($popped); - } - - // - $this->writeScanLogLine("
                  tree, child, parent, lft, rgt, depthref_id, ref.obj_id, deletedobj_id, type, owner, title
                  ' - .(($isRowOkay) ? '' : '') - .$row->tree.', ' - .$row->child.', ' - .(($isParentOkay) ? '' : 'parent:') - .$row->parent - .(($isParentOkay) ? '' : '') - .', ' - .(($isLftOkay) ? '' : 'lft:') - .$row->lft - .(($isLftOkay) ? '' : '') - .', ' - .(($isRgtOkay) ? '' : 'rgt:') - .$row->rgt - .(($isRgtOkay) ? '' : '') - .', ' - .(($isDepthOkay) ? '' : 'depth:') - .$row->depth - .(($isDepthOkay) ? '' : '') - .(($isRowOkay) ? '' : '') - .'' - .(($isRowOkay) ? '' : '') - .(($isRefRefOkay && $isChildOkay) ? '' : 'ref.ref_id:') - .$row->ref_id - .(($isRefRefOkay && $isChildOkay) ? '' : '') - .', ' - .(($isRefObjOkay) ? '' : 'ref.obj_id:') - .$row->refobj_id - .(($isRefObjOkay) ? '' : '') - .(($isRowOkay) ? '' : '') - .(($row->deleted != null) ? ', '.$row->deleted : '') - .'' - .(($isRowOkay) ? '' : '') - .$indent - .$row->obj_id.', ' - .$row->type.', ' - .$row->login.', ' - .$row->title - .(($isRowOkay) ? '' : ' *ERROR*') - .'
                   
                  ' - .'*gap* for '.($gap/2).' nodes at end of ' - .'
                  ' - .'' - .$poppedIndent - .$popped->obj_id.', ' - .$popped->type.', ' - .$popped->login.', ' - .$popped->title - .'' - .'
                  ' - .'*gap* for '.($gap/2).' nodes between ' - .'
                  ' - .'siblings' - .'
                  ' - . (($isRowOkay) ? '' : '') - . $row->tree . ', ' - . $row->child . ', ' - . (($isParentOkay) ? '' : 'parent:') - . $row->parent - . (($isParentOkay) ? '' : '') - . ', ' - . (($isLftOkay) ? '' : 'lft:') - . $row->lft - . (($isLftOkay) ? '' : '') - . ', ' - . (($isRgtOkay) ? '' : 'rgt:') - . $row->rgt - . (($isRgtOkay) ? '' : '') - . ', ' - . (($isDepthOkay) ? '' : 'depth:') - . $row->depth - . (($isDepthOkay) ? '' : '') - . (($isRowOkay) ? '' : '') - . '' - . (($isRowOkay) ? '' : '') - . (($isRefRefOkay && $isChildOkay) ? '' : 'ref.ref_id:') - . $row->ref_id - . (($isRefRefOkay && $isChildOkay) ? '' : '') - . ', ' - . (($isRefObjOkay) ? '' : 'ref.obj_id:') - . $row->refobj_id - . (($isRefObjOkay) ? '' : '') - . (($isRowOkay) ? '' : '') - . (($row->tree < 0) ? ', ' . $row->deleted : '') - . '' - . (($isRowOkay) ? '' : '') - . $indent - . $row->obj_id . ', ' - . $row->type . ', ' - . $row->login . ', ' - . $row->title - . (($isRowOkay) ? '' : ' *ERROR*') - . '
                  ' - .'*gap* for '.($gap/2).' nodes at end of ' - .'
                  ' - .'' - .$poppedIndent - .$popped->obj_id.', ' - .$popped->type.', ' - .$popped->login.', ' - .$popped->title - .'' - .'
                  "); - - if ($error_count > 0) - { - $this->writeScanLogLine(''.$error_count.' errors found while dumping tree.'); - } - else - { - $this->writeScanLogLine('No errors found while dumping tree.'); - } - $this->writeScanLogLine("$repository_tree_count nodes in repository tree"); - $this->writeScanLogLine("$trash_trees_count nodes in trash trees"); - $this->writeScanLogLine("$other_trees_count nodes in other trees"); - $this->writeScanLogLine("$not_in_tree_count nodes are not in a tree"); - $this->writeScanLogLine("END dumpTree"); - - return $error_count; - } - - protected function isMediaFolder($a_obj_id) - { - $ilDB = $this->db; - - if(!is_array($this->media_pool_ids)) - { - $this->media_pool_ids = array(); - $query = "SELECT child FROM mep_tree "; - $res = $ilDB->query($query); - while($row = $ilDB->fetchObject($res)) - { - $this->media_pool_ids[] = $row->child; - } - } - - return in_array($a_obj_id,$this->media_pool_ids) ? true : false; - } - - /** - * Check if type is excluded from recovery - * @param string $a_type - * @param int $a_obj_id - * @return bool - */ - protected function isExcludedFromRecovery($a_type,$a_obj_id) - { - switch($a_type) - { - case 'fold': - if(!$this->isMediaFolder($a_obj_id)) - { - return false; - } - } - return in_array($a_type,$this->object_types_exclude); - } - - protected function initWorkspaceObjects() - { - $ilDB = $this->db; - - if($this->workspace_object_ids === null) - { - $this->workspace_object_ids = array(); - - // workspace objects - $set = $ilDB->query("SELECT DISTINCT(obj_id) FROM object_reference_ws"); - while($row = $ilDB->fetchAssoc($set)) - { - $this->workspace_object_ids[] = $row["obj_id"]; - } - - // portfolios - $set = $ilDB->query("SELECT id FROM usr_portfolio"); - while($row = $ilDB->fetchAssoc($set)) - { - $this->workspace_object_ids[] = $row["id"]; - } - } - } - - protected function filterWorkspaceObjects(array &$a_data, $a_index = "obj_id") - { - if(sizeof($a_data)) - { - $this->initWorkspaceObjects(); - - // remove workspace objects from result objects - if(is_array($this->workspace_object_ids)) - { - foreach($a_data as $idx => $item) - { - if(in_array($item[$a_index], $this->workspace_object_ids)) - { - unset($a_data[$idx]); - } - } - } - } - } + . "ORDER BY tree, lft, type, dat.title"; + $r = $this->db->query($q); + + $this->writeScanLogLine( + '' + . '' + . '' + . '' + . '' + ); + + // We use a stack to represent the path to the current node. + // This allows us to do analyze the tree structure without having + // to implement a recursive algorithm. + $stack = array(); + $error_count = 0; + $repository_tree_count = 0; + $trash_trees_count = 0; + $other_trees_count = 0; + $not_in_tree_count = 0; + + // The previous number is used for gap checking + $previousNumber = 0; + + $this->initWorkspaceObjects(); + + while ($row = $r->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) { + // workspace objects are not to be processed + if ($this->workspace_object_ids && + in_array($row->objobj_id, $this->workspace_object_ids)) { + continue; + } + + // If there is no entry in table tree for the object, we display it here + if (is_null($row->child)) { + switch ($row->type) { + case 'crsg': + case 'usr': + case 'typ': + case 'lng': + case 'rolt': + case 'role': + case 'mob': + case 'sty': + case 'tax': // #13798 + // We are not interested in dumping these object types. + continue 2; + //break; NOT REACHED + case 'file': + if (is_null($row->ref_id)) { + // File objects can be part of a learning module. + // In this case, they do not have a row in table object_reference. + // We are not interested in dumping these file objects. + continue 2; + } else { + // File objects which have a row in table object_reference, but + // none in table tree are an error. + $error_count++; + $isRowOkay = false; + $isParentOkay = false; + $isLftOkay = false; + $isRgtOkay = false; + $isDepthOkay = false; + } + break; + + + case 'fold': + // ignore folders on media pools + if ($this->isMediaFolder($row->obj_id)) { + continue 2; + } + // no break + default: + $error_count++; + $isRowOkay = false; + $isParentOkay = false; + $isLftOkay = false; + $isRgtOkay = false; + $isDepthOkay = false; + break; + } + + // moved here (below continues in switch) + $not_in_tree_count++; + + $this->writeScanLogLine( + '' + . '' + . '' + ); + continue; + } + + // Update stack + // ------------------- + $indent = ""; + for ($i = 1; $i < $row->depth; $i++) { + $indent .= ". "; + } + + // Initialize the stack and the previous number if we are in a new tree + if (count($stack) == 0 || $stack[0]->tree != $row->tree) { + $stack = array(); + $previousNumber = $row->lft - 1; + $this->writeScanLogLine(''); + } + // Pop old stack entries + + + while (count($stack) > 0 && $stack[count($stack) - 1]->rgt < $row->lft) { + $popped = array_pop($stack); + + // check for gap + $gap = $popped->rgt - $previousNumber - 1; + if ($gap > 0) { + $poppedIndent = ""; + for ($i = 1; $i < $popped->depth; $i++) { + $poppedIndent .= ". "; + } + $this->writeScanLogLine( + '' + . '' + . '' + . '' + ); + } + $previousNumber = $popped->rgt; + unset($popped); + } + + // Check row integrity + // ------------------- + $isRowOkay = true; + + // Check tree structure + $isChildOkay = true; + $isParentOkay = true; + $isLftOkay = true; + $isRgtOkay = true; + $isDepthOkay = true; + $isGap = false; + + if (count($stack) > 0) { + $parent = $stack[count($stack) - 1]; + if ($parent->depth + 1 != $row->depth) { + $isDepthOkay = false; + $isRowOkay = false; + } + if ($parent->child != $row->parent) { + $isParentOkay = false; + $isRowOkay = false; + } + if ($GLOBALS['ilSetting']->get('main_tree_impl', 'ns') == 'ns') { + if ($parent->lft >= $row->lft) { + $isLftOkay = false; + $isRowOkay = false; + } + if ($parent->rgt <= $row->rgt) { + $isRgtOkay = false; + $isRowOkay = false; + } + } + } + + // Check lft rgt + if ($GLOBALS['ilSetting']->get('main_tree_impl', 'ns') == 'ns') { + if ($row->lft >= $row->rgt) { + $isLftOkay = false; + $isRgtOkay = false; + $isRowOkay = false; + } + } + if (in_array($row->child, $duplicateNodes)) { + $isChildOkay = false; + $isRowOkay = false; + } + + // Check object reference + $isRefRefOkay = true; + $isRefObjOkay = true; + if ($row->ref_id == null) { + $isRefRefOkay = false; + $isRowOkay = false; + } + if ($row->obj_id == null) { + $isRefObjOkay = false; + $isRowOkay = false; + } + + if (!$isRowOkay) { + $error_count++; + } + + // Check for gap between siblings, + // and eventually write a log line + if ($GLOBALS['ilSetting']->get('main_tree_impl', 'ns') == 'ns') { + $gap = $row->lft - $previousNumber - 1; + $previousNumber = $row->lft; + if ($gap > 0) { + $this->writeScanLogLine( + '' + . '' + . '' + . '' + ); + } + } + + // Write log line + // ------------------- + $this->writeScanLogLine( + '' + . '' + . '' + ); + + // Update stack + // ------------------- + // Push node on stack + $stack[] = $row; + + // Count nodes + // ----------------- + if ($row->tree == 1) { + $repository_tree_count++; + } elseif ($row->tree < 0) { + $trash_trees_count++; + } else { + $other_trees_count++; + } + } + // + // Pop remaining stack entries + + while (count($stack) > 0) { + $popped = array_pop($stack); + + // check for gap + $gap = $popped->rgt - $previousNumber - 1; + if ($gap > 0) { + $poppedIndent = ""; + for ($i = 1; $i < $popped->depth; $i++) { + $poppedIndent .= ". "; + } + $this->writeScanLogLine( + '' + . '' + . '' + . '' + ); + } + $previousNumber = $popped->rgt; + unset($popped); + } + + // + $this->writeScanLogLine("
                  tree, child, parent, lft, rgt, depthref_id, ref.obj_id, deletedobj_id, type, owner, title
                  ' + . (($isRowOkay) ? '' : '') + . $row->tree . ', ' + . $row->child . ', ' + . (($isParentOkay) ? '' : 'parent:') + . $row->parent + . (($isParentOkay) ? '' : '') + . ', ' + . (($isLftOkay) ? '' : 'lft:') + . $row->lft + . (($isLftOkay) ? '' : '') + . ', ' + . (($isRgtOkay) ? '' : 'rgt:') + . $row->rgt + . (($isRgtOkay) ? '' : '') + . ', ' + . (($isDepthOkay) ? '' : 'depth:') + . $row->depth + . (($isDepthOkay) ? '' : '') + . (($isRowOkay) ? '' : '') + . '' + . (($isRowOkay) ? '' : '') + . (($isRefRefOkay && $isChildOkay) ? '' : 'ref.ref_id:') + . $row->ref_id + . (($isRefRefOkay && $isChildOkay) ? '' : '') + . ', ' + . (($isRefObjOkay) ? '' : 'ref.obj_id:') + . $row->refobj_id + . (($isRefObjOkay) ? '' : '') + . (($isRowOkay) ? '' : '') + . (($row->deleted != null) ? ', ' . $row->deleted : '') + . '' + . (($isRowOkay) ? '' : '') + . $indent + . $row->obj_id . ', ' + . $row->type . ', ' + . $row->login . ', ' + . $row->title + . (($isRowOkay) ? '' : ' *ERROR*') + . '
                   
                  ' + . '*gap* for ' . ($gap/2) . ' nodes at end of ' + . '
                  ' + . '' + . $poppedIndent + . $popped->obj_id . ', ' + . $popped->type . ', ' + . $popped->login . ', ' + . $popped->title + . '' + . '
                  ' + . '*gap* for ' . ($gap/2) . ' nodes between ' + . '
                  ' + . 'siblings' + . '
                  ' + . (($isRowOkay) ? '' : '') + . $row->tree . ', ' + . $row->child . ', ' + . (($isParentOkay) ? '' : 'parent:') + . $row->parent + . (($isParentOkay) ? '' : '') + . ', ' + . (($isLftOkay) ? '' : 'lft:') + . $row->lft + . (($isLftOkay) ? '' : '') + . ', ' + . (($isRgtOkay) ? '' : 'rgt:') + . $row->rgt + . (($isRgtOkay) ? '' : '') + . ', ' + . (($isDepthOkay) ? '' : 'depth:') + . $row->depth + . (($isDepthOkay) ? '' : '') + . (($isRowOkay) ? '' : '') + . '' + . (($isRowOkay) ? '' : '') + . (($isRefRefOkay && $isChildOkay) ? '' : 'ref.ref_id:') + . $row->ref_id + . (($isRefRefOkay && $isChildOkay) ? '' : '') + . ', ' + . (($isRefObjOkay) ? '' : 'ref.obj_id:') + . $row->refobj_id + . (($isRefObjOkay) ? '' : '') + . (($isRowOkay) ? '' : '') + . (($row->tree < 0) ? ', ' . $row->deleted : '') + . '' + . (($isRowOkay) ? '' : '') + . $indent + . $row->obj_id . ', ' + . $row->type . ', ' + . $row->login . ', ' + . $row->title + . (($isRowOkay) ? '' : ' *ERROR*') + . '
                  ' + . '*gap* for ' . ($gap/2) . ' nodes at end of ' + . '
                  ' + . '' + . $poppedIndent + . $popped->obj_id . ', ' + . $popped->type . ', ' + . $popped->login . ', ' + . $popped->title + . '' + . '
                  "); + + if ($error_count > 0) { + $this->writeScanLogLine('' . $error_count . ' errors found while dumping tree.'); + } else { + $this->writeScanLogLine('No errors found while dumping tree.'); + } + $this->writeScanLogLine("$repository_tree_count nodes in repository tree"); + $this->writeScanLogLine("$trash_trees_count nodes in trash trees"); + $this->writeScanLogLine("$other_trees_count nodes in other trees"); + $this->writeScanLogLine("$not_in_tree_count nodes are not in a tree"); + $this->writeScanLogLine("END dumpTree"); + + return $error_count; + } + + protected function isMediaFolder($a_obj_id) + { + $ilDB = $this->db; + + if (!is_array($this->media_pool_ids)) { + $this->media_pool_ids = array(); + $query = "SELECT child FROM mep_tree "; + $res = $ilDB->query($query); + while ($row = $ilDB->fetchObject($res)) { + $this->media_pool_ids[] = $row->child; + } + } + + return in_array($a_obj_id, $this->media_pool_ids) ? true : false; + } + + /** + * Check if type is excluded from recovery + * @param string $a_type + * @param int $a_obj_id + * @return bool + */ + protected function isExcludedFromRecovery($a_type, $a_obj_id) + { + switch ($a_type) { + case 'fold': + if (!$this->isMediaFolder($a_obj_id)) { + return false; + } + } + return in_array($a_type, $this->object_types_exclude); + } + + protected function initWorkspaceObjects() + { + $ilDB = $this->db; + + if ($this->workspace_object_ids === null) { + $this->workspace_object_ids = array(); + + // workspace objects + $set = $ilDB->query("SELECT DISTINCT(obj_id) FROM object_reference_ws"); + while ($row = $ilDB->fetchAssoc($set)) { + $this->workspace_object_ids[] = $row["obj_id"]; + } + + // portfolios + $set = $ilDB->query("SELECT id FROM usr_portfolio"); + while ($row = $ilDB->fetchAssoc($set)) { + $this->workspace_object_ids[] = $row["id"]; + } + } + } + + protected function filterWorkspaceObjects(array &$a_data, $a_index = "obj_id") + { + if (sizeof($a_data)) { + $this->initWorkspaceObjects(); + + // remove workspace objects from result objects + if (is_array($this->workspace_object_ids)) { + foreach ($a_data as $idx => $item) { + if (in_array($item[$a_index], $this->workspace_object_ids)) { + unset($a_data[$idx]); + } + } + } + } + } } // END class.ilValidator -?> diff --git a/Services/Repository/exceptions/class.ilRepositoryException.php b/Services/Repository/exceptions/class.ilRepositoryException.php index 501cd9eb0a29f081192d9f5159fe0a15b3c21447..90d677d08f582f6e26cfa4768830507c59eb9999 100644 --- a/Services/Repository/exceptions/class.ilRepositoryException.php +++ b/Services/Repository/exceptions/class.ilRepositoryException.php @@ -5,15 +5,13 @@ include_once('Services/Exceptions/classes/class.ilException.php'); /** * @author Alex Killing * @version $Id$ -* +* * @ingroup ServicesRepository */ class ilRepositoryException extends ilException { - public function __construct($a_message,$a_code = 0) - { - parent::__construct($a_message,$a_code); - } + public function __construct($a_message, $a_code = 0) + { + parent::__construct($a_message, $a_code); + } } - -?> diff --git a/Services/Skill/LearningHistory/classes/class.ilSkillLearningHistoryProvider.php b/Services/Skill/LearningHistory/classes/class.ilSkillLearningHistoryProvider.php index 82e5e4da389a8425e9d43c8aab47b9892c4d6258..bbe015547f76c962e421560f67fcbeb4d808378b 100644 --- a/Services/Skill/LearningHistory/classes/class.ilSkillLearningHistoryProvider.php +++ b/Services/Skill/LearningHistory/classes/class.ilSkillLearningHistoryProvider.php @@ -11,79 +11,78 @@ class ilSkillLearningHistoryProvider extends ilAbstractLearningHistoryProvider implements ilLearningHistoryProviderInterface { - /** - * @inheritdoc - */ - public function isActive() - { - $skmg_set = new ilSetting("skmg"); - if ($skmg_set->get("enable_skmg")) - { - return true; - } - return false; - } + /** + * @inheritdoc + */ + public function isActive() + { + $skmg_set = new ilSetting("skmg"); + if ($skmg_set->get("enable_skmg")) { + return true; + } + return false; + } - /** - * @inheritdoc - */ - public function getEntries($ts_start, $ts_end) - { - $lng = $this->getLanguage(); - $lng->loadLanguageModule("skll"); - $from = new ilDateTime($ts_start, IL_CAL_UNIX); - $to = new ilDateTime($ts_end, IL_CAL_UNIX); + /** + * @inheritdoc + */ + public function getEntries($ts_start, $ts_end) + { + $lng = $this->getLanguage(); + $lng->loadLanguageModule("skll"); + $from = new ilDateTime($ts_start, IL_CAL_UNIX); + $to = new ilDateTime($ts_end, IL_CAL_UNIX); - // achievements - $completions = ilBasicSkill::getNewAchievementsPerUser($from->get(IL_CAL_DATETIME), $to->get(IL_CAL_DATETIME), $this->getUserId()); + // achievements + $completions = ilBasicSkill::getNewAchievementsPerUser($from->get(IL_CAL_DATETIME), $to->get(IL_CAL_DATETIME), $this->getUserId()); - $entries = []; - if (is_array($completions[$this->getUserId()])) - { - foreach ($completions[$this->getUserId()] as $c) - { + $entries = []; + if (is_array($completions[$this->getUserId()])) { + foreach ($completions[$this->getUserId()] as $c) { + $ts = new ilDateTime($c["status_date"], IL_CAL_DATETIME); + $text = str_replace("$3$", $this->getEmphasizedTitle(ilBasicSkill::_lookupTitle($c["skill_id"], $c["tref_id"])), $lng->txt("skll_lhist_skill_achieved")); + $text = str_replace("$4$", $this->getEmphasizedTitle(ilBasicSkill::lookupLevelTitle($c["level_id"])), $text); + $entries[] = $this->getFactory()->entry( + $text, + $text, + ilUtil::getImagePath("icon_skmg.svg"), + $ts->get(IL_CAL_UNIX), + $c["trigger_obj_id"] + ); + } + } - $ts = new ilDateTime($c["status_date"], IL_CAL_DATETIME); - $text = str_replace("$3$", $this->getEmphasizedTitle(ilBasicSkill::_lookupTitle($c["skill_id"], $c["tref_id"])), $lng->txt("skll_lhist_skill_achieved")); - $text = str_replace("$4$", $this->getEmphasizedTitle(ilBasicSkill::lookupLevelTitle($c["level_id"])), $text); - $entries[] = $this->getFactory()->entry($text, $text, - ilUtil::getImagePath("icon_skmg.svg"), - $ts->get(IL_CAL_UNIX), - $c["trigger_obj_id"]); - } - } + // self evaluations + $completions = ilBasicSkill::getNewAchievementsPerUser($from->get(IL_CAL_DATETIME), $to->get(IL_CAL_DATETIME), $this->getUserId(), 1); - // self evaluations - $completions = ilBasicSkill::getNewAchievementsPerUser($from->get(IL_CAL_DATETIME), $to->get(IL_CAL_DATETIME), $this->getUserId(), 1); + if (is_array($completions[$this->getUserId()])) { + foreach ($completions[$this->getUserId()] as $c) { + $txt = ($c["trigger_obj_id"] > 0) + ? $lng->txt("skll_lhist_skill_self_eval_in") + : $lng->txt("skll_lhist_skill_self_eval"); + $ts = new ilDateTime($c["status_date"], IL_CAL_DATETIME); + $text1 = str_replace("$3$", $this->getEmphasizedTitle(ilBasicSkill::_lookupTitle($c["skill_id"], $c["tref_id"])), $txt); + $text1 = str_replace("$4$", $this->getEmphasizedTitle(ilBasicSkill::lookupLevelTitle($c["level_id"])), $text1); + $entries[] = $this->getFactory()->entry( + $text1, + $text1, + ilUtil::getImagePath("icon_skmg.svg"), + $ts->get(IL_CAL_UNIX), + $c["trigger_obj_id"] + ); + } + } + return $entries; + } - if (is_array($completions[$this->getUserId()])) - { - foreach ($completions[$this->getUserId()] as $c) - { - $txt = ($c["trigger_obj_id"] > 0) - ? $lng->txt("skll_lhist_skill_self_eval_in") - : $lng->txt("skll_lhist_skill_self_eval"); - $ts = new ilDateTime($c["status_date"], IL_CAL_DATETIME); - $text1 = str_replace("$3$", $this->getEmphasizedTitle(ilBasicSkill::_lookupTitle($c["skill_id"], $c["tref_id"])), $txt); - $text1 = str_replace("$4$", $this->getEmphasizedTitle(ilBasicSkill::lookupLevelTitle($c["level_id"])), $text1); - $entries[] = $this->getFactory()->entry($text1, $text1, - ilUtil::getImagePath("icon_skmg.svg"), - $ts->get(IL_CAL_UNIX), - $c["trigger_obj_id"]); - } - } - return $entries; - } + /** + * @inheritdoc + */ + public function getName() : string + { + $lng = $this->getLanguage(); + $lng->loadLanguageModule("skmg"); - /** - * @inheritdoc - */ - public function getName(): string - { - $lng = $this->getLanguage(); - $lng->loadLanguageModule("skmg"); - - return $lng->txt("skills"); - } - -} \ No newline at end of file + return $lng->txt("skills"); + } +} diff --git a/Services/Skill/classes/class.ilBasicSkill.php b/Services/Skill/classes/class.ilBasicSkill.php index 9567b49c1513cf530b1bf2471d5038067adb01b0..45c879cfac11d7e107ab2351318d9e752b082491 100644 --- a/Services/Skill/classes/class.ilBasicSkill.php +++ b/Services/Skill/classes/class.ilBasicSkill.php @@ -15,1179 +15,1148 @@ include_once("./Services/Skill/interfaces/interface.ilSkillUsageInfo.php"); */ class ilBasicSkill extends ilSkillTreeNode implements ilSkillUsageInfo { - /** - * @var ilDB - */ - protected $db; - - /** - * @var ilObjUser - */ - protected $user; - - const ACHIEVED = 1; - const NOT_ACHIEVED = 0; - - const EVAL_BY_OTHERS_= 0; - const EVAL_BY_SELF = 1; - const EVAL_BY_ALL = 2; - - var $id; - - /** - * Constructor - * @access public - */ - function __construct($a_id = 0) - { - global $DIC; - - $this->db = $DIC->database(); - $this->user = $DIC->user(); - parent::__construct($a_id); - $this->setType("skll"); - } - - /** - * Read data from database - */ - function read() - { - parent::read(); - } - - /** - * Create skill - * - */ - function create() - { - parent::create(); - } - - /** - * Delete skill - */ - function delete() - { - $ilDB = $this->db; - - $ilDB->manipulate("DELETE FROM skl_level WHERE " - ." skill_id = ".$ilDB->quote($this->getId(), "integer") - ); - - $ilDB->manipulate("DELETE FROM skl_user_has_level WHERE " - ." skill_id = ".$ilDB->quote($this->getId(), "integer") - ); - - parent::delete(); - } - - /** - * Copy basic skill - */ - function copy() - { - $skill = new ilBasicSkill(); - $skill->setTitle($this->getTitle()); - $skill->setType($this->getType()); - $skill->setSelfEvaluation($this->getSelfEvaluation()); - $skill->setOrderNr($this->getOrderNr()); - $skill->create(); - - $levels = $this->getLevelData(); - if (sizeof($levels)) - { - foreach($levels as $item) - { - $skill->addLevel($item["title"], $item["description"]); - } - } - $skill->update(); - - return $skill; - } - - // - // - // Skill level related methods - // - // - - /** - * Add new level - * - * @param string title - * @param string description - */ - function addLevel($a_title, $a_description, $a_import_id = "") - { - $ilDB = $this->db; - - $nr = $this->getMaxLevelNr(); - $nid = $ilDB->nextId("skl_level"); - $ilDB->insert("skl_level", array( - "id" => array("integer", $nid), - "skill_id" => array("integer", $this->getId()), - "nr" => array("integer", $nr+1), - "title" => array("text", $a_title), - "description" => array("clob", $a_description), - "import_id" => array("text", $a_import_id), - "creation_date" => array("timestamp", ilUtil::now()) - )); - - } - - /** - * Get maximum level nr - * - * @return int maximum level nr of skill - */ - function getMaxLevelNr() - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT MAX(nr) mnr FROM skl_level WHERE ". - " skill_id = ".$ilDB->quote($this->getId(), "integer") - ); - $rec = $ilDB->fetchAssoc($set); - return (int) $rec["mnr"]; - } - - /** - * Get level data - * - * @return array level data - */ - function getLevelData($a_id = 0) - { - $ilDB = $this->db; - - if ($a_id > 0) - { - $and = " AND id = ".$ilDB->quote($a_id, "integer"); - } - - $set = $ilDB->query("SELECT * FROM skl_level WHERE ". - " skill_id = ".$ilDB->quote($this->getId(), "integer"). - $and. - " ORDER BY nr" - ); - $levels = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - if ($a_id > 0) - { - return $rec; - } - $levels[] = $rec; - } - return $levels; - } - - /** - * Lookup level property - * - * @param id level id - * @return mixed property value - */ - protected static function lookupLevelProperty($a_id, $a_prop) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT $a_prop FROM skl_level WHERE ". - " id = ".$ilDB->quote($a_id, "integer") - ); - $rec = $ilDB->fetchAssoc($set); - return $rec[$a_prop]; - } - - /** - * Lookup level title - * - * @param int level id - * @return string level title - */ - static function lookupLevelTitle($a_id) - { - return ilBasicSkill::lookupLevelProperty($a_id, "title"); - } - - /** - * Lookup level description - * - * @param int level id - * @return string level description - */ - static function lookupLevelDescription($a_id) - { - return ilBasicSkill::lookupLevelProperty($a_id, "description"); - } - - /** - * Lookup level skill id - * - * @param int level id - * @return string skill id - */ - static function lookupLevelSkillId($a_id) - { - return ilBasicSkill::lookupLevelProperty($a_id, "skill_id"); - } - - /** - * Write level property - * - * @param - * @return - */ - static protected function writeLevelProperty($a_id, $a_prop, $a_value, $a_type) - { - global $DIC; - - $ilDB = $DIC->database(); - - $ilDB->update("skl_level", array( - $a_prop => array($a_type, $a_value), - ), array( - "id" => array("integer", $a_id), - )); - } - - /** - * Write level title - * - * @param int level id - * @param text level title - */ - static function writeLevelTitle($a_id, $a_title) - { - ilBasicSkill::writeLevelProperty($a_id, "title", $a_title, "text"); - } - - /** - * Write level description - * - * @param int level id - * @param text level description - */ - static function writeLevelDescription($a_id, $a_description) - { - ilBasicSkill::writeLevelProperty($a_id, "description", $a_description, "clob"); - } - - /** - * Update level order - * - * @param - * @return - */ - function updateLevelOrder($order) - { - $ilDB = $this->db; - - asort($order); - - $cnt = 1; - foreach ($order as $id => $o) - { - $ilDB->manipulate("UPDATE skl_level SET ". - " nr = ".$ilDB->quote($cnt, "integer"). - " WHERE id = ".$ilDB->quote($id, "integer") - ); - $cnt++; - } - } - - /** - * Delete level - * - * @param - * @return - */ - function deleteLevel($a_id) - { - $ilDB = $this->db; - - $ilDB->manipulate("DELETE FROM skl_level WHERE " - ." id = ".$ilDB->quote($a_id, "integer") - ); - - } - - /** - * Fix level numbering - * - * @param - * @return - */ - function fixLevelNumbering() - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT id, nr FROM skl_level WHERE ". - " skill_id = ".$ilDB->quote($this->getId(), "integer"). - " ORDER BY nr ASC" - ); - $cnt = 1; - while ($rec = $ilDB->fetchAssoc($set)) - { - $ilDB->manipulate("UPDATE skl_level SET ". - " nr = ".$ilDB->quote($cnt, "integer"). - " WHERE id = ".$ilDB->quote($rec["id"], "integer") - ); - $cnt++; - } - } - - /** - * Get skill for level id - * - * @param - * @return - */ - function getSkillForLevelId($a_level_id) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT * FROM skl_level WHERE ". - " id = ".$ilDB->quote($a_level_id, "integer") - ); - $skill = null; - if ($rec = $ilDB->fetchAssoc($set)) - { - if (ilSkillTreeNode::isInTree($rec["skill_id"])) - { - $skill = new ilBasicSkill($rec["skill_id"]); - } - } - return $skill; - } - - // - // - // User skill (level) related methods - // - // - - - /** - * Reset skill level status. This is currently only used for self evaluations with a "no competence" level. - * It has to be discussed, how this should be provided for non-self-evaluations. - * - * @param int $a_user_id user id - * @param int $a_skill_id skill id - * @param int $a_tref_id skill tref id - * @param int $a_trigger_ref_id triggering repository object ref id - * @param bool $a_self_eval currently needs to be set to true - * - * @throws ilSkillException - */ - static function resetUserSkillLevelStatus($a_user_id, $a_skill_id, $a_tref_id = 0, $a_trigger_ref_id = 0, $a_self_eval = false) - { - global $DIC; - - $db = $DIC->database(); - - if (!$a_self_eval) - { - include_once("./Services/Skill/exceptions/class.ilSkillException.php"); - throw new ilSkillException("resetUserSkillLevelStatus currently only provided for self evaluations."); - } - - $trigger_obj_id = ($a_trigger_ref_id > 0) - ? ilObject::_lookupObjId($a_trigger_ref_id) - : 0; - - $update = false; - $status_date = self::hasRecentSelfEvaluation($a_user_id, $a_skill_id, $a_tref_id, $a_trigger_ref_id); - if ($status_date != "") - { - $update = true; - } - - if ($update) - { - // this will only be set in self eval case, means this will always have a $rec - $now = ilUtil::now(); - $db->manipulate("UPDATE skl_user_skill_level SET ". - " level_id = ".$db->quote(0, "integer").",". - " status_date = ".$db->quote($now, "timestamp"). - " WHERE user_id = ".$db->quote($a_user_id, "integer"). - " AND status_date = ".$db->quote($status_date, "timestamp"). - " AND skill_id = ".$db->quote($a_skill_id, "integer"). - " AND status = ".$db->quote(self::ACHIEVED, "integer"). - " AND trigger_obj_id = ".$db->quote($trigger_obj_id, "integer"). - " AND tref_id = ".$db->quote((int) $a_tref_id, "integer"). - " AND self_eval = ".$db->quote($a_self_eval, "integer") - ); - } - else - { - $now = ilUtil::now(); - $db->manipulate("INSERT INTO skl_user_skill_level ". - "(level_id, user_id, tref_id, status_date, skill_id, status, valid, trigger_ref_id,". - "trigger_obj_id, trigger_obj_type, trigger_title, self_eval, unique_identifier) VALUES (". - $db->quote(0, "integer").",". - $db->quote($a_user_id, "integer").",". - $db->quote((int) $a_tref_id, "integer").",". - $db->quote($now, "timestamp").",". - $db->quote($a_skill_id, "integer").",". - $db->quote(self::ACHIEVED, "integer").",". - $db->quote(1, "integer").",". - $db->quote($a_trigger_ref_id, "integer").",". - $db->quote($trigger_obj_id, "integer").",". - $db->quote("", "text").",". - $db->quote("", "text").",". - $db->quote($a_self_eval, "integer").",". - $db->quote("", "text"). - ")"); - } - - $db->manipulate("DELETE FROM skl_user_has_level WHERE " - ." user_id = ".$db->quote($a_user_id, "integer") - ." AND skill_id = ".$db->quote($a_skill_id, "integer") - ." AND tref_id = ".$db->quote((int) $a_tref_id, "integer") - ." AND trigger_obj_id = ".$db->quote($trigger_obj_id, "integer") - ." AND self_eval = ".$db->quote($a_self_eval, "integer") - ); - - } - - /** - * Has recent self evaluation. Check if self evaluation for user/object has been done on the same day - * already - * - * @param - * @return - */ - protected static function hasRecentSelfEvaluation($a_user_id, $a_skill_id, $a_tref_id = 0, $a_trigger_ref_id = 0) - { - global $DIC; - - $db = $DIC->database(); - - $trigger_obj_id = ($a_trigger_ref_id > 0) - ? ilObject::_lookupObjId($a_trigger_ref_id) - : 0; - - $recent = ""; - - $db->setLimit(1); - $set = $db->query("SELECT * FROM skl_user_skill_level WHERE ". - "skill_id = ".$db->quote($a_skill_id, "integer")." AND ". - "user_id = ".$db->quote($a_user_id, "integer")." AND ". - "tref_id = ".$db->quote((int) $a_tref_id, "integer")." AND ". - "trigger_obj_id = ".$db->quote($trigger_obj_id, "integer")." AND ". - "self_eval = ".$db->quote(1, "integer"). - " ORDER BY status_date DESC" - ); - $rec = $db->fetchAssoc($set); - $status_day = substr($rec["status_date"], 0, 10); - $today = substr(ilUtil::now(), 0, 10); - if ($rec["valid"] && $rec["status"] == ilBasicSkill::ACHIEVED && $status_day == $today) - { - $recent = $rec["status_date"]; - } - - return $recent; - } - - /** - * Get new achievements - * - * @param string $a_timestamp - * @return array - */ - static function getNewAchievementsPerUser($a_timestamp, $a_timestamp_to = null, $a_user_id = 0, $a_self_eval = 0) - { - global $DIC; - - $db = $DIC->database(); - - $to = (!is_null($a_timestamp_to)) - ? " AND status_date <= ".$db->quote($a_timestamp_to, "timestamp") - : ""; - - $user = ($a_user_id > 0) - ? " AND user_id = ".$db->quote($a_user_id, "integer") - : ""; - - $set = $db->query("SELECT * FROM skl_user_skill_level ". - " WHERE status_date >= ".$db->quote($a_timestamp, "timestamp"). - " AND valid = ".$db->quote(1, "integer"). - " AND status = ".$db->quote(ilBasicSkill::ACHIEVED, "integer"). - " AND self_eval = ".$db->quote($a_self_eval, "integer"). - $to. - $user. - " ORDER BY user_id, status_date ASC "); - $achievments = array(); - while ($rec = $db->fetchAssoc($set)) - { - $achievments[$rec["user_id"]][] = $rec; - } - - return $achievments; - } - - - /** - * Write skill level status - * - * @param int $a_level_id skill level id - * @param int $a_user_id user id - * @param int $a_trigger_ref_id trigger repository object ref id - * @param int $a_tref_id skill tref id - * @param int $a_status DEPRECATED, always use ilBasicSkill::ACHIEVED - * @param bool $a_force DEPRECATED - * @param bool $a_self_eval self evaluation - * @param string $a_unique_identifier a unique identifier (should be used with trigger_ref_id > 0) - */ - static function writeUserSkillLevelStatus($a_level_id, $a_user_id, - $a_trigger_ref_id, $a_tref_id = 0, $a_status = ilBasicSkill::ACHIEVED, $a_force = false, - $a_self_eval = false, $a_unique_identifier = "") - { - global $DIC; - - $ilDB = $DIC->database(); - - $skill_id = ilBasicSkill::lookupLevelSkillId($a_level_id); - $trigger_ref_id = $a_trigger_ref_id; - $trigger_obj_id = ilObject::_lookupObjId($trigger_ref_id); - $trigger_title = ilObject::_lookupTitle($trigger_obj_id); - $trigger_type = ilObject::_lookupType($trigger_obj_id); - - $update = false; - - // self evaluations will update, if the last self evaluation is on the same day - if ($a_self_eval && self::hasRecentSelfEvaluation($a_user_id, $skill_id, $a_tref_id, $trigger_ref_id)) - { - $status_date = self::hasRecentSelfEvaluation($a_user_id, $skill_id, $a_tref_id, $trigger_ref_id); - if ($status_date != "") - { - $update = true; - } - } - - if ($update) - { - // this will only be set in self eval case, means this will always have a $rec - $now = ilUtil::now(); - $ilDB->manipulate("UPDATE skl_user_skill_level SET ". - " level_id = ".$ilDB->quote($a_level_id, "integer").",". - " status_date = ".$ilDB->quote($now, "timestamp"). - " WHERE user_id = ".$ilDB->quote($a_user_id, "integer"). - " AND status_date = ".$ilDB->quote($status_date, "timestamp"). - " AND skill_id = ".$ilDB->quote($skill_id, "integer"). - " AND status = ".$ilDB->quote($a_status, "integer"). - " AND trigger_obj_id = ".$ilDB->quote($trigger_obj_id, "integer"). - " AND tref_id = ".$ilDB->quote((int) $a_tref_id, "integer"). - " AND self_eval = ".$ilDB->quote($a_self_eval, "integer") - ); - } - else - { - if ($a_unique_identifier != "") - { - $ilDB->manipulate("DELETE FROM skl_user_skill_level WHERE ". - " user_id = ".$ilDB->quote($a_user_id, "integer"). - " AND tref_id = ".$ilDB->quote($a_tref_id, "integer"). - " AND skill_id = ".$ilDB->quote($skill_id, "integer"). - " AND trigger_ref_id = ".$ilDB->quote($trigger_ref_id, "integer"). - " AND trigger_obj_id = ".$ilDB->quote($trigger_obj_id, "integer"). - " AND self_eval = ".$ilDB->quote($a_self_eval, "integer"). - " AND unique_identifier = ".$ilDB->quote($a_unique_identifier, "text") - ); - } - - $now = ilUtil::now(); - $ilDB->manipulate("INSERT INTO skl_user_skill_level ". - "(level_id, user_id, tref_id, status_date, skill_id, status, valid, trigger_ref_id,". - "trigger_obj_id, trigger_obj_type, trigger_title, self_eval, unique_identifier) VALUES (". - $ilDB->quote($a_level_id, "integer").",". - $ilDB->quote($a_user_id, "integer").",". - $ilDB->quote((int) $a_tref_id, "integer").",". - $ilDB->quote($now, "timestamp").",". - $ilDB->quote($skill_id, "integer").",". - $ilDB->quote($a_status, "integer").",". - $ilDB->quote(1, "integer").",". - $ilDB->quote($trigger_ref_id, "integer").",". - $ilDB->quote($trigger_obj_id, "integer").",". - $ilDB->quote($trigger_type, "text").",". - $ilDB->quote($trigger_title, "text").",". - $ilDB->quote($a_self_eval, "integer").",". - $ilDB->quote($a_unique_identifier, "text"). - ")"); - } - - // fix (removed level_id and added skill id, since table should hold only - // one entry per skill) - $ilDB->manipulate("DELETE FROM skl_user_has_level WHERE " - ." user_id = ".$ilDB->quote($a_user_id, "integer") - ." AND skill_id = ".$ilDB->quote($skill_id, "integer") - ." AND tref_id = ".$ilDB->quote((int) $a_tref_id, "integer") - ." AND trigger_obj_id = ".$ilDB->quote($trigger_obj_id, "integer") - ." AND self_eval = ".$ilDB->quote($a_self_eval, "integer") - ); - - if ($a_status == ilBasicSkill::ACHIEVED) - { - $ilDB->manipulate("INSERT INTO skl_user_has_level ". - "(level_id, user_id, tref_id, status_date, skill_id, trigger_ref_id, trigger_obj_id, trigger_obj_type, trigger_title, self_eval) VALUES (". - $ilDB->quote($a_level_id, "integer").",". - $ilDB->quote($a_user_id, "integer").",". - $ilDB->quote($a_tref_id, "integer").",". - $ilDB->quote($now, "timestamp").",". - $ilDB->quote($skill_id, "integer").",". - $ilDB->quote($trigger_ref_id, "integer").",". - $ilDB->quote($trigger_obj_id, "integer").",". - $ilDB->quote($trigger_type, "text").",". - $ilDB->quote($trigger_title, "text").",". - $ilDB->quote($a_self_eval, "integer"). - ")"); - } - } - - /** - * Remove a user skill completely - * - * @param int $a_user_id user id - * @param int $a_trigger_obj_id triggering repository object obj id - * @param bool $a_self_eval currently needs to be set to true - * @param string $a_unique_identifier unique identifier string - * @return bool true, if entries have been deleted, otherwise false - */ - static function removeAllUserSkillLevelStatusOfObject($a_user_id, $a_trigger_obj_id, $a_self_eval = false, $a_unique_identifier = "") - { - global $DIC; - - $db = $DIC->database(); - - if ($a_trigger_obj_id == 0) - { - return false; - } - - $changed = false; - - $aff_rows = $db->manipulate("DELETE FROM skl_user_skill_level WHERE " - ." user_id = ".$db->quote($a_user_id, "integer") - ." AND trigger_obj_id = ".$db->quote($a_trigger_obj_id, "integer") - ." AND self_eval = ".$db->quote($a_self_eval, "integer") - ." AND unique_identifier = ".$db->quote($a_unique_identifier, "text") - ); - if ($aff_rows > 0) - { - $changed = true; - } - - $aff_rows = $db->manipulate("DELETE FROM skl_user_has_level WHERE " - ." user_id = ".$db->quote($a_user_id, "integer") - ." AND trigger_obj_id = ".$db->quote($a_trigger_obj_id, "integer") - ." AND self_eval = ".$db->quote($a_self_eval, "integer") - ); - if ($aff_rows > 0) - { - $changed = true; - } - return $changed; - } - - /** - * Remove all data of a user - * - * @param int $a_user_id - */ - static function removeAllUserData($a_user_id) - { - global $DIC; - - $db = $DIC->database(); - - $db->manipulate("DELETE FROM skl_user_skill_level WHERE " - ." user_id = ".$db->quote($a_user_id, "integer") - ); - $db->manipulate("DELETE FROM skl_user_has_level WHERE " - ." user_id = ".$db->quote($a_user_id, "integer") - ); - } - - - /** - * Get max levels per type - * - * @param - * @return - */ - function getMaxLevelPerType($a_tref_id, $a_type, $a_user_id = 0, $a_self_eval = 0) - { - $ilDB = $this->db; - $ilUser = $this->user; - - if ($a_user_id == 0) - { - $a_user_id = $ilUser->getId(); - } - - $set = $ilDB->query($q = "SELECT level_id FROM skl_user_has_level ". - " WHERE trigger_obj_type = ".$ilDB->quote($a_type, "text"). - " AND skill_id = ".$ilDB->quote($this->getId(), "integer"). - " AND tref_id = ".$ilDB->quote((int) $a_tref_id, "integer"). - " AND user_id = ".$ilDB->quote($a_user_id, "integer"). - " AND self_eval = ".$ilDB->quote($a_self_eval, "integer") - ); - - $has_level = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $has_level[$rec["level_id"]] = true; - } - $max_level = 0; - foreach ($this->getLevelData() as $l) - { - if (isset($has_level[$l["id"]])) - { - $max_level = $l["id"]; - } - } - return $max_level; - } - - /** - * Get all level entries - * - * @param - * @return - */ - function getAllLevelEntriesOfUser($a_tref_id, $a_user_id = 0, $a_self_eval = 0) - { - $ilDB = $this->db; - $ilUser = $this->user; - - if ($a_user_id == 0) - { - $a_user_id = $ilUser->getId(); - } - - $set = $ilDB->query($q = "SELECT * FROM skl_user_has_level ". - " WHERE skill_id = ".$ilDB->quote($this->getId(), "integer"). - " AND tref_id = ".$ilDB->quote((int) $a_tref_id, "integer"). - " AND user_id = ".$ilDB->quote($a_user_id, "integer"). - " AND self_eval = ".$ilDB->quote($a_self_eval, "integer"). - " ORDER BY status_date DESC" - ); - - $levels = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $levels[] = $rec; - } - return $levels; - } - - /** - * Get all historic level entries - * - * @param - * @return - */ - function getAllHistoricLevelEntriesOfUser($a_tref_id, $a_user_id = 0, $a_eval_by = 0) - { - $ilDB = $this->db; - $ilUser = $this->user; - - if ($a_user_id == 0) - { - $a_user_id = $ilUser->getId(); - } - - $by = ($a_eval_by != self::EVAL_BY_ALL) - ? " AND self_eval = ".$ilDB->quote($a_self_eval, "integer") - : ""; - - $set = $ilDB->query($q = "SELECT * FROM skl_user_skill_level ". - " WHERE skill_id = ".$ilDB->quote($this->getId(), "integer"). - " AND tref_id = ".$ilDB->quote((int) $a_tref_id, "integer"). - " AND user_id = ".$ilDB->quote($a_user_id, "integer"). - $by. - " ORDER BY status_date DESC" - ); - $levels = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $levels[] = $rec; - } - return $levels; - } - - - /** - * Get max levels per object - * - * @param - * @return - */ - function getMaxLevelPerObject($a_tref_id, $a_object_id, $a_user_id = 0, $a_self_eval = 0) - { - $ilDB = $this->db; - $ilUser = $this->user; - - if ($a_user_id == 0) - { - $a_user_id = $ilUser->getId(); - } - - $set = $ilDB->query($q = "SELECT level_id FROM skl_user_has_level ". - " WHERE trigger_obj_id = ".$ilDB->quote($a_object_id, "integer"). - " AND skill_id = ".$ilDB->quote($this->getId(), "integer"). - " AND tref_id = ".$ilDB->quote((int) $a_tref_id, "integer"). - " AND user_id = ".$ilDB->quote($a_user_id, "integer"). - " AND self_eval = ".$ilDB->quote($a_self_eval, "integer") - ); - - $has_level = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $has_level[$rec["level_id"]] = true; - } - $max_level = 0; - foreach ($this->getLevelData() as $l) - { - if (isset($has_level[$l["id"]])) - { - $max_level = $l["id"]; - } - } - return $max_level; - } - - /** - * Get max levels per object - * - * @param - * @return - */ - function getMaxLevel($a_tref_id, $a_user_id = 0, $a_self_eval = 0) - { - $ilDB = $this->db; - $ilUser = $this->user; - - if ($a_user_id == 0) - { - $a_user_id = $ilUser->getId(); - } - - $set = $ilDB->query($q = "SELECT level_id FROM skl_user_has_level ". - " WHERE skill_id = ".$ilDB->quote($this->getId(), "integer"). - " AND tref_id = ".$ilDB->quote((int) $a_tref_id, "integer"). - " AND user_id = ".$ilDB->quote($a_user_id, "integer"). - " AND self_eval = ".$ilDB->quote($a_self_eval, "integer") - ); - - $has_level = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $has_level[$rec["level_id"]] = true; - } - $max_level = 0; - foreach ($this->getLevelData() as $l) - { - if (isset($has_level[$l["id"]])) - { - $max_level = $l["id"]; - } - } - return $max_level; - } - - - /** - * Has use self evaluated a skill? - * - * @param int $a_user_id - * @param int $a_skill_id - * @param int $a_tref_id - * @return bool - */ - static function hasSelfEvaluated($a_user_id, $a_skill_id, $a_tref_id) - { - global $DIC; - - $db = $DIC->database(); - - $set = $db->query($q = "SELECT level_id FROM skl_user_has_level ". - " WHERE skill_id = ".$db->quote((int) $a_skill_id, "integer"). - " AND tref_id = ".$db->quote((int) $a_tref_id, "integer"). - " AND user_id = ".$db->quote($a_user_id, "integer"). - " AND self_eval = ".$db->quote(1, "integer") - ); - - if ($rec = $db->fetchAssoc($set)) - { - return true; - } - return false; - } - - /** - * Get last level set per object - * - * @param - * @return - */ - function getLastLevelPerObject($a_tref_id, $a_object_id, $a_user_id = 0, $a_self_eval = 0) - { - $ilDB = $this->db; - $ilUser = $this->user; - - if ($a_user_id == 0) - { - $a_user_id = $ilUser->getId(); - } - - $ilDB->setLimit(1); - $set = $ilDB->query($q = "SELECT level_id FROM skl_user_has_level ". - " WHERE trigger_obj_id = ".$ilDB->quote($a_object_id, "integer"). - " AND skill_id = ".$ilDB->quote($this->getId(), "integer"). - " AND tref_id = ".$ilDB->quote((int) $a_tref_id, "integer"). - " AND user_id = ".$ilDB->quote($a_user_id, "integer"). - " AND self_eval = ".$ilDB->quote($a_self_eval, "integer"). - " ORDER BY status_date DESC" - ); - - $rec = $ilDB->fetchAssoc($set); - - return $rec["level_id"]; - } - - /** - * Get last update per object - * - * @param - * @return - */ - function getLastUpdatePerObject($a_tref_id, $a_object_id, $a_user_id = 0, $a_self_eval = 0) - { - $ilDB = $this->db; - $ilUser = $this->user; - - if ($a_user_id == 0) - { - $a_user_id = $ilUser->getId(); - } - - $ilDB->setLimit(1); - $set = $ilDB->query($q = "SELECT status_date FROM skl_user_has_level ". - " WHERE trigger_obj_id = ".$ilDB->quote($a_object_id, "integer"). - " AND skill_id = ".$ilDB->quote($this->getId(), "integer"). - " AND tref_id = ".$ilDB->quote((int) $a_tref_id, "integer"). - " AND user_id = ".$ilDB->quote($a_user_id, "integer"). - " AND self_eval = ".$ilDB->quote($a_self_eval, "integer"). - " ORDER BY status_date DESC" - ); - - $rec = $ilDB->fetchAssoc($set); - - return $rec["status_date"]; - } - - // - // - // Certificate related methods - // - // - - /** - * Get title for certificate - * - * @param - * @return - */ - function getTitleForCertificate() - { - return $this->getTitle(); - } - - /** - * Get short title for certificate - * - * @param - * @return - */ - function getShortTitleForCertificate() - { - return "Skill"; - } - - /** - * Checks whether a skill level has a certificate or not - * @param int skill id - * @param int skill level id - * @return true/false - */ - public static function _lookupCertificate($a_skill_id, $a_skill_level_id) - { - $certificatefile = CLIENT_WEB_DIR."/certificates/skill/". - ((int)$a_skill_id)."/".((int) $a_skill_level_id)."/certificate.xml"; - if (@file_exists($certificatefile)) - { - return true; - } - else - { - return false; - } - } - - /** - * Get usage info - * - * @param - * @return - */ - static public function getUsageInfo($a_cskill_ids, &$a_usages) - { - global $DIC; - - $ilDB = $DIC->database(); - - include_once("./Services/Skill/classes/class.ilSkillUsage.php"); - ilSkillUsage::getUsageInfoGeneric($a_cskill_ids, $a_usages, ilSkillUsage::USER_ASSIGNED, - "skl_user_skill_level", "user_id"); - } - - /** - * Get common skill ids for import IDs (newest first) - * - * @param int $a_source_inst_id source installation id, must be <>0 - * @param int $a_skill_import_id source skill id (type basic skill ("skll") or basic skill template ("sktp")) - * @param int $a_tref_import_id source template reference id (if > 0 skill_import_id will be of type "sktp") - * @return array array of common skill ids, keys are "skill_id", "tref_id", "creation_date" - */ - static function getCommonSkillIdForImportId($a_source_inst_id, $a_skill_import_id, $a_tref_import_id = 0) - { - global $DIC; - - $ilDB = $DIC->database(); - - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); - $tree = new ilSkillTree(); - - if ($a_source_inst_id == 0) - { - return array(); - } - - $template_ids = array(); - if ($a_tref_import_id > 0) - { - $skill_node_type = "sktp"; - - // get all matching tref nodes - $set = $ilDB->query("SELECT * FROM skl_tree_node n JOIN skl_tree t ON (n.obj_id = t.child) ". - " WHERE n.import_id = ".$ilDB->quote("il_".((int)$a_source_inst_id)."_sktr_".$a_tref_import_id, "text"). - " ORDER BY n.creation_date DESC "); - while ($rec = $ilDB->fetchAssoc($set)) - { - if (($t = ilSkillTemplateReference::_lookupTemplateId($rec["obj_id"])) > 0) - { - $template_ids[$t] = $rec["obj_id"]; - } - } - } - else - { - $skill_node_type = "skll"; - } - $set = $ilDB->query("SELECT * FROM skl_tree_node n JOIN skl_tree t ON (n.obj_id = t.child) ". - " WHERE n.import_id = ".$ilDB->quote("il_".((int)$a_source_inst_id)."_".$skill_node_type."_".$a_skill_import_id, "text"). - " ORDER BY n.creation_date DESC "); - $results = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $matching_trefs = array(); - if ($a_tref_import_id > 0) - { - $skill_template_id = $tree->getTopParentNodeId($rec["obj_id"]); - - // check of skill is in template - foreach ($template_ids as $templ => $tref) - { - if ($skill_template_id == $templ) - { - $matching_trefs[] = $tref; - } - } - } - else - { - $matching_trefs = array(0); - } - - foreach ($matching_trefs as $t) - { - $results[] = array("skill_id" => $rec["obj_id"], "tref_id" => $t, "creation_date" => $rec["creation_date"]); - } - } - return $results; - } - - /** - * Get level ids for import IDs (newest first) - * - * @param int $a_source_inst_id source installation id, must be <>0 - * @param int $a_skill_import_id source skill id (type basic skill ("skll") or basic skill template ("sktp")) - * @return array array of common skill ids, keys are "level_id", "creation_date" - */ - static function getLevelIdForImportId($a_source_inst_id, $a_level_import_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT * FROM skl_level l JOIN skl_tree t ON (l.skill_id = t.child) " . - " WHERE l.import_id = " . $ilDB->quote("il_" . ((int)$a_source_inst_id) . "_sklv_" . $a_level_import_id, "text") . - " ORDER BY l.creation_date DESC "); - $results = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $results[] = array("level_id" => $rec["id"], "creation_date" => $rec["creation_date"]); - } - return $results; - } - - /** - * Get level ids for import Ids matching common skills - * - * @param - * @return - */ - static function getLevelIdForImportIdMatchSkill($a_source_inst_id, $a_level_import_id, $a_skill_import_id, $a_tref_import_id = 0) - { - $level_id_data = self::getLevelIdForImportId($a_source_inst_id, $a_level_import_id); - $skill_data = self::getCommonSkillIdForImportId($a_source_inst_id, $a_skill_import_id, $a_tref_import_id); - $matches = array(); - foreach($level_id_data as $l) - { - reset($skill_data); - foreach ($skill_data as $s) - { - if (ilBasicSkill::lookupLevelSkillId($l["level_id"]) == $s["skill_id"]) - { - $matches[] = array( - "level_id" => $l["level_id"], - "creation_date" => $l["creation_date"], - "skill_id" => $s["skill_id"], - "tref_id" => $s["tref_id"] - ); - } - } - } - return $matches; - } - + /** + * @var ilDB + */ + protected $db; + + /** + * @var ilObjUser + */ + protected $user; + + const ACHIEVED = 1; + const NOT_ACHIEVED = 0; + + const EVAL_BY_OTHERS_= 0; + const EVAL_BY_SELF = 1; + const EVAL_BY_ALL = 2; + + public $id; + + /** + * Constructor + * @access public + */ + public function __construct($a_id = 0) + { + global $DIC; + + $this->db = $DIC->database(); + $this->user = $DIC->user(); + parent::__construct($a_id); + $this->setType("skll"); + } + + /** + * Read data from database + */ + public function read() + { + parent::read(); + } + + /** + * Create skill + * + */ + public function create() + { + parent::create(); + } + + /** + * Delete skill + */ + public function delete() + { + $ilDB = $this->db; + + $ilDB->manipulate( + "DELETE FROM skl_level WHERE " + . " skill_id = " . $ilDB->quote($this->getId(), "integer") + ); + + $ilDB->manipulate( + "DELETE FROM skl_user_has_level WHERE " + . " skill_id = " . $ilDB->quote($this->getId(), "integer") + ); + + parent::delete(); + } + + /** + * Copy basic skill + */ + public function copy() + { + $skill = new ilBasicSkill(); + $skill->setTitle($this->getTitle()); + $skill->setType($this->getType()); + $skill->setSelfEvaluation($this->getSelfEvaluation()); + $skill->setOrderNr($this->getOrderNr()); + $skill->create(); + + $levels = $this->getLevelData(); + if (sizeof($levels)) { + foreach ($levels as $item) { + $skill->addLevel($item["title"], $item["description"]); + } + } + $skill->update(); + + return $skill; + } + + // + // + // Skill level related methods + // + // + + /** + * Add new level + * + * @param string title + * @param string description + */ + public function addLevel($a_title, $a_description, $a_import_id = "") + { + $ilDB = $this->db; + + $nr = $this->getMaxLevelNr(); + $nid = $ilDB->nextId("skl_level"); + $ilDB->insert("skl_level", array( + "id" => array("integer", $nid), + "skill_id" => array("integer", $this->getId()), + "nr" => array("integer", $nr+1), + "title" => array("text", $a_title), + "description" => array("clob", $a_description), + "import_id" => array("text", $a_import_id), + "creation_date" => array("timestamp", ilUtil::now()) + )); + } + + /** + * Get maximum level nr + * + * @return int maximum level nr of skill + */ + public function getMaxLevelNr() + { + $ilDB = $this->db; + + $set = $ilDB->query( + "SELECT MAX(nr) mnr FROM skl_level WHERE " . + " skill_id = " . $ilDB->quote($this->getId(), "integer") + ); + $rec = $ilDB->fetchAssoc($set); + return (int) $rec["mnr"]; + } + + /** + * Get level data + * + * @return array level data + */ + public function getLevelData($a_id = 0) + { + $ilDB = $this->db; + + if ($a_id > 0) { + $and = " AND id = " . $ilDB->quote($a_id, "integer"); + } + + $set = $ilDB->query( + "SELECT * FROM skl_level WHERE " . + " skill_id = " . $ilDB->quote($this->getId(), "integer") . + $and . + " ORDER BY nr" + ); + $levels = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + if ($a_id > 0) { + return $rec; + } + $levels[] = $rec; + } + return $levels; + } + + /** + * Lookup level property + * + * @param id level id + * @return mixed property value + */ + protected static function lookupLevelProperty($a_id, $a_prop) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT $a_prop FROM skl_level WHERE " . + " id = " . $ilDB->quote($a_id, "integer") + ); + $rec = $ilDB->fetchAssoc($set); + return $rec[$a_prop]; + } + + /** + * Lookup level title + * + * @param int level id + * @return string level title + */ + public static function lookupLevelTitle($a_id) + { + return ilBasicSkill::lookupLevelProperty($a_id, "title"); + } + + /** + * Lookup level description + * + * @param int level id + * @return string level description + */ + public static function lookupLevelDescription($a_id) + { + return ilBasicSkill::lookupLevelProperty($a_id, "description"); + } + + /** + * Lookup level skill id + * + * @param int level id + * @return string skill id + */ + public static function lookupLevelSkillId($a_id) + { + return ilBasicSkill::lookupLevelProperty($a_id, "skill_id"); + } + + /** + * Write level property + * + * @param + * @return + */ + protected static function writeLevelProperty($a_id, $a_prop, $a_value, $a_type) + { + global $DIC; + + $ilDB = $DIC->database(); + + $ilDB->update("skl_level", array( + $a_prop => array($a_type, $a_value), + ), array( + "id" => array("integer", $a_id), + )); + } + + /** + * Write level title + * + * @param int level id + * @param text level title + */ + public static function writeLevelTitle($a_id, $a_title) + { + ilBasicSkill::writeLevelProperty($a_id, "title", $a_title, "text"); + } + + /** + * Write level description + * + * @param int level id + * @param text level description + */ + public static function writeLevelDescription($a_id, $a_description) + { + ilBasicSkill::writeLevelProperty($a_id, "description", $a_description, "clob"); + } + + /** + * Update level order + * + * @param + * @return + */ + public function updateLevelOrder($order) + { + $ilDB = $this->db; + + asort($order); + + $cnt = 1; + foreach ($order as $id => $o) { + $ilDB->manipulate( + "UPDATE skl_level SET " . + " nr = " . $ilDB->quote($cnt, "integer") . + " WHERE id = " . $ilDB->quote($id, "integer") + ); + $cnt++; + } + } + + /** + * Delete level + * + * @param + * @return + */ + public function deleteLevel($a_id) + { + $ilDB = $this->db; + + $ilDB->manipulate( + "DELETE FROM skl_level WHERE " + . " id = " . $ilDB->quote($a_id, "integer") + ); + } + + /** + * Fix level numbering + * + * @param + * @return + */ + public function fixLevelNumbering() + { + $ilDB = $this->db; + + $set = $ilDB->query( + "SELECT id, nr FROM skl_level WHERE " . + " skill_id = " . $ilDB->quote($this->getId(), "integer") . + " ORDER BY nr ASC" + ); + $cnt = 1; + while ($rec = $ilDB->fetchAssoc($set)) { + $ilDB->manipulate( + "UPDATE skl_level SET " . + " nr = " . $ilDB->quote($cnt, "integer") . + " WHERE id = " . $ilDB->quote($rec["id"], "integer") + ); + $cnt++; + } + } + + /** + * Get skill for level id + * + * @param + * @return + */ + public function getSkillForLevelId($a_level_id) + { + $ilDB = $this->db; + + $set = $ilDB->query( + "SELECT * FROM skl_level WHERE " . + " id = " . $ilDB->quote($a_level_id, "integer") + ); + $skill = null; + if ($rec = $ilDB->fetchAssoc($set)) { + if (ilSkillTreeNode::isInTree($rec["skill_id"])) { + $skill = new ilBasicSkill($rec["skill_id"]); + } + } + return $skill; + } + + // + // + // User skill (level) related methods + // + // + + + /** + * Reset skill level status. This is currently only used for self evaluations with a "no competence" level. + * It has to be discussed, how this should be provided for non-self-evaluations. + * + * @param int $a_user_id user id + * @param int $a_skill_id skill id + * @param int $a_tref_id skill tref id + * @param int $a_trigger_ref_id triggering repository object ref id + * @param bool $a_self_eval currently needs to be set to true + * + * @throws ilSkillException + */ + public static function resetUserSkillLevelStatus($a_user_id, $a_skill_id, $a_tref_id = 0, $a_trigger_ref_id = 0, $a_self_eval = false) + { + global $DIC; + + $db = $DIC->database(); + + if (!$a_self_eval) { + include_once("./Services/Skill/exceptions/class.ilSkillException.php"); + throw new ilSkillException("resetUserSkillLevelStatus currently only provided for self evaluations."); + } + + $trigger_obj_id = ($a_trigger_ref_id > 0) + ? ilObject::_lookupObjId($a_trigger_ref_id) + : 0; + + $update = false; + $status_date = self::hasRecentSelfEvaluation($a_user_id, $a_skill_id, $a_tref_id, $a_trigger_ref_id); + if ($status_date != "") { + $update = true; + } + + if ($update) { + // this will only be set in self eval case, means this will always have a $rec + $now = ilUtil::now(); + $db->manipulate( + "UPDATE skl_user_skill_level SET " . + " level_id = " . $db->quote(0, "integer") . "," . + " status_date = " . $db->quote($now, "timestamp") . + " WHERE user_id = " . $db->quote($a_user_id, "integer") . + " AND status_date = " . $db->quote($status_date, "timestamp") . + " AND skill_id = " . $db->quote($a_skill_id, "integer") . + " AND status = " . $db->quote(self::ACHIEVED, "integer") . + " AND trigger_obj_id = " . $db->quote($trigger_obj_id, "integer") . + " AND tref_id = " . $db->quote((int) $a_tref_id, "integer") . + " AND self_eval = " . $db->quote($a_self_eval, "integer") + ); + } else { + $now = ilUtil::now(); + $db->manipulate("INSERT INTO skl_user_skill_level " . + "(level_id, user_id, tref_id, status_date, skill_id, status, valid, trigger_ref_id," . + "trigger_obj_id, trigger_obj_type, trigger_title, self_eval, unique_identifier) VALUES (" . + $db->quote(0, "integer") . "," . + $db->quote($a_user_id, "integer") . "," . + $db->quote((int) $a_tref_id, "integer") . "," . + $db->quote($now, "timestamp") . "," . + $db->quote($a_skill_id, "integer") . "," . + $db->quote(self::ACHIEVED, "integer") . "," . + $db->quote(1, "integer") . "," . + $db->quote($a_trigger_ref_id, "integer") . "," . + $db->quote($trigger_obj_id, "integer") . "," . + $db->quote("", "text") . "," . + $db->quote("", "text") . "," . + $db->quote($a_self_eval, "integer") . "," . + $db->quote("", "text") . + ")"); + } + + $db->manipulate( + "DELETE FROM skl_user_has_level WHERE " + . " user_id = " . $db->quote($a_user_id, "integer") + . " AND skill_id = " . $db->quote($a_skill_id, "integer") + . " AND tref_id = " . $db->quote((int) $a_tref_id, "integer") + . " AND trigger_obj_id = " . $db->quote($trigger_obj_id, "integer") + . " AND self_eval = " . $db->quote($a_self_eval, "integer") + ); + } + + /** + * Has recent self evaluation. Check if self evaluation for user/object has been done on the same day + * already + * + * @param + * @return + */ + protected static function hasRecentSelfEvaluation($a_user_id, $a_skill_id, $a_tref_id = 0, $a_trigger_ref_id = 0) + { + global $DIC; + + $db = $DIC->database(); + + $trigger_obj_id = ($a_trigger_ref_id > 0) + ? ilObject::_lookupObjId($a_trigger_ref_id) + : 0; + + $recent = ""; + + $db->setLimit(1); + $set = $db->query( + "SELECT * FROM skl_user_skill_level WHERE " . + "skill_id = " . $db->quote($a_skill_id, "integer") . " AND " . + "user_id = " . $db->quote($a_user_id, "integer") . " AND " . + "tref_id = " . $db->quote((int) $a_tref_id, "integer") . " AND " . + "trigger_obj_id = " . $db->quote($trigger_obj_id, "integer") . " AND " . + "self_eval = " . $db->quote(1, "integer") . + " ORDER BY status_date DESC" + ); + $rec = $db->fetchAssoc($set); + $status_day = substr($rec["status_date"], 0, 10); + $today = substr(ilUtil::now(), 0, 10); + if ($rec["valid"] && $rec["status"] == ilBasicSkill::ACHIEVED && $status_day == $today) { + $recent = $rec["status_date"]; + } + + return $recent; + } + + /** + * Get new achievements + * + * @param string $a_timestamp + * @return array + */ + public static function getNewAchievementsPerUser($a_timestamp, $a_timestamp_to = null, $a_user_id = 0, $a_self_eval = 0) + { + global $DIC; + + $db = $DIC->database(); + + $to = (!is_null($a_timestamp_to)) + ? " AND status_date <= " . $db->quote($a_timestamp_to, "timestamp") + : ""; + + $user = ($a_user_id > 0) + ? " AND user_id = " . $db->quote($a_user_id, "integer") + : ""; + + $set = $db->query("SELECT * FROM skl_user_skill_level " . + " WHERE status_date >= " . $db->quote($a_timestamp, "timestamp") . + " AND valid = " . $db->quote(1, "integer") . + " AND status = " . $db->quote(ilBasicSkill::ACHIEVED, "integer") . + " AND self_eval = " . $db->quote($a_self_eval, "integer") . + $to . + $user . + " ORDER BY user_id, status_date ASC "); + $achievments = array(); + while ($rec = $db->fetchAssoc($set)) { + $achievments[$rec["user_id"]][] = $rec; + } + + return $achievments; + } + + + /** + * Write skill level status + * + * @param int $a_level_id skill level id + * @param int $a_user_id user id + * @param int $a_trigger_ref_id trigger repository object ref id + * @param int $a_tref_id skill tref id + * @param int $a_status DEPRECATED, always use ilBasicSkill::ACHIEVED + * @param bool $a_force DEPRECATED + * @param bool $a_self_eval self evaluation + * @param string $a_unique_identifier a unique identifier (should be used with trigger_ref_id > 0) + */ + public static function writeUserSkillLevelStatus( + $a_level_id, + $a_user_id, + $a_trigger_ref_id, + $a_tref_id = 0, + $a_status = ilBasicSkill::ACHIEVED, + $a_force = false, + $a_self_eval = false, + $a_unique_identifier = "" + ) { + global $DIC; + + $ilDB = $DIC->database(); + + $skill_id = ilBasicSkill::lookupLevelSkillId($a_level_id); + $trigger_ref_id = $a_trigger_ref_id; + $trigger_obj_id = ilObject::_lookupObjId($trigger_ref_id); + $trigger_title = ilObject::_lookupTitle($trigger_obj_id); + $trigger_type = ilObject::_lookupType($trigger_obj_id); + + $update = false; + + // self evaluations will update, if the last self evaluation is on the same day + if ($a_self_eval && self::hasRecentSelfEvaluation($a_user_id, $skill_id, $a_tref_id, $trigger_ref_id)) { + $status_date = self::hasRecentSelfEvaluation($a_user_id, $skill_id, $a_tref_id, $trigger_ref_id); + if ($status_date != "") { + $update = true; + } + } + + if ($update) { + // this will only be set in self eval case, means this will always have a $rec + $now = ilUtil::now(); + $ilDB->manipulate( + "UPDATE skl_user_skill_level SET " . + " level_id = " . $ilDB->quote($a_level_id, "integer") . "," . + " status_date = " . $ilDB->quote($now, "timestamp") . + " WHERE user_id = " . $ilDB->quote($a_user_id, "integer") . + " AND status_date = " . $ilDB->quote($status_date, "timestamp") . + " AND skill_id = " . $ilDB->quote($skill_id, "integer") . + " AND status = " . $ilDB->quote($a_status, "integer") . + " AND trigger_obj_id = " . $ilDB->quote($trigger_obj_id, "integer") . + " AND tref_id = " . $ilDB->quote((int) $a_tref_id, "integer") . + " AND self_eval = " . $ilDB->quote($a_self_eval, "integer") + ); + } else { + if ($a_unique_identifier != "") { + $ilDB->manipulate( + "DELETE FROM skl_user_skill_level WHERE " . + " user_id = " . $ilDB->quote($a_user_id, "integer") . + " AND tref_id = " . $ilDB->quote($a_tref_id, "integer") . + " AND skill_id = " . $ilDB->quote($skill_id, "integer") . + " AND trigger_ref_id = " . $ilDB->quote($trigger_ref_id, "integer") . + " AND trigger_obj_id = " . $ilDB->quote($trigger_obj_id, "integer") . + " AND self_eval = " . $ilDB->quote($a_self_eval, "integer") . + " AND unique_identifier = " . $ilDB->quote($a_unique_identifier, "text") + ); + } + + $now = ilUtil::now(); + $ilDB->manipulate("INSERT INTO skl_user_skill_level " . + "(level_id, user_id, tref_id, status_date, skill_id, status, valid, trigger_ref_id," . + "trigger_obj_id, trigger_obj_type, trigger_title, self_eval, unique_identifier) VALUES (" . + $ilDB->quote($a_level_id, "integer") . "," . + $ilDB->quote($a_user_id, "integer") . "," . + $ilDB->quote((int) $a_tref_id, "integer") . "," . + $ilDB->quote($now, "timestamp") . "," . + $ilDB->quote($skill_id, "integer") . "," . + $ilDB->quote($a_status, "integer") . "," . + $ilDB->quote(1, "integer") . "," . + $ilDB->quote($trigger_ref_id, "integer") . "," . + $ilDB->quote($trigger_obj_id, "integer") . "," . + $ilDB->quote($trigger_type, "text") . "," . + $ilDB->quote($trigger_title, "text") . "," . + $ilDB->quote($a_self_eval, "integer") . "," . + $ilDB->quote($a_unique_identifier, "text") . + ")"); + } + + // fix (removed level_id and added skill id, since table should hold only + // one entry per skill) + $ilDB->manipulate( + "DELETE FROM skl_user_has_level WHERE " + . " user_id = " . $ilDB->quote($a_user_id, "integer") + . " AND skill_id = " . $ilDB->quote($skill_id, "integer") + . " AND tref_id = " . $ilDB->quote((int) $a_tref_id, "integer") + . " AND trigger_obj_id = " . $ilDB->quote($trigger_obj_id, "integer") + . " AND self_eval = " . $ilDB->quote($a_self_eval, "integer") + ); + + if ($a_status == ilBasicSkill::ACHIEVED) { + $ilDB->manipulate("INSERT INTO skl_user_has_level " . + "(level_id, user_id, tref_id, status_date, skill_id, trigger_ref_id, trigger_obj_id, trigger_obj_type, trigger_title, self_eval) VALUES (" . + $ilDB->quote($a_level_id, "integer") . "," . + $ilDB->quote($a_user_id, "integer") . "," . + $ilDB->quote($a_tref_id, "integer") . "," . + $ilDB->quote($now, "timestamp") . "," . + $ilDB->quote($skill_id, "integer") . "," . + $ilDB->quote($trigger_ref_id, "integer") . "," . + $ilDB->quote($trigger_obj_id, "integer") . "," . + $ilDB->quote($trigger_type, "text") . "," . + $ilDB->quote($trigger_title, "text") . "," . + $ilDB->quote($a_self_eval, "integer") . + ")"); + } + } + + /** + * Remove a user skill completely + * + * @param int $a_user_id user id + * @param int $a_trigger_obj_id triggering repository object obj id + * @param bool $a_self_eval currently needs to be set to true + * @param string $a_unique_identifier unique identifier string + * @return bool true, if entries have been deleted, otherwise false + */ + public static function removeAllUserSkillLevelStatusOfObject($a_user_id, $a_trigger_obj_id, $a_self_eval = false, $a_unique_identifier = "") + { + global $DIC; + + $db = $DIC->database(); + + if ($a_trigger_obj_id == 0) { + return false; + } + + $changed = false; + + $aff_rows = $db->manipulate( + "DELETE FROM skl_user_skill_level WHERE " + . " user_id = " . $db->quote($a_user_id, "integer") + . " AND trigger_obj_id = " . $db->quote($a_trigger_obj_id, "integer") + . " AND self_eval = " . $db->quote($a_self_eval, "integer") + . " AND unique_identifier = " . $db->quote($a_unique_identifier, "text") + ); + if ($aff_rows > 0) { + $changed = true; + } + + $aff_rows = $db->manipulate( + "DELETE FROM skl_user_has_level WHERE " + . " user_id = " . $db->quote($a_user_id, "integer") + . " AND trigger_obj_id = " . $db->quote($a_trigger_obj_id, "integer") + . " AND self_eval = " . $db->quote($a_self_eval, "integer") + ); + if ($aff_rows > 0) { + $changed = true; + } + return $changed; + } + + /** + * Remove all data of a user + * + * @param int $a_user_id + */ + public static function removeAllUserData($a_user_id) + { + global $DIC; + + $db = $DIC->database(); + + $db->manipulate( + "DELETE FROM skl_user_skill_level WHERE " + . " user_id = " . $db->quote($a_user_id, "integer") + ); + $db->manipulate( + "DELETE FROM skl_user_has_level WHERE " + . " user_id = " . $db->quote($a_user_id, "integer") + ); + } + + + /** + * Get max levels per type + * + * @param + * @return + */ + public function getMaxLevelPerType($a_tref_id, $a_type, $a_user_id = 0, $a_self_eval = 0) + { + $ilDB = $this->db; + $ilUser = $this->user; + + if ($a_user_id == 0) { + $a_user_id = $ilUser->getId(); + } + + $set = $ilDB->query( + $q = "SELECT level_id FROM skl_user_has_level " . + " WHERE trigger_obj_type = " . $ilDB->quote($a_type, "text") . + " AND skill_id = " . $ilDB->quote($this->getId(), "integer") . + " AND tref_id = " . $ilDB->quote((int) $a_tref_id, "integer") . + " AND user_id = " . $ilDB->quote($a_user_id, "integer") . + " AND self_eval = " . $ilDB->quote($a_self_eval, "integer") + ); + + $has_level = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $has_level[$rec["level_id"]] = true; + } + $max_level = 0; + foreach ($this->getLevelData() as $l) { + if (isset($has_level[$l["id"]])) { + $max_level = $l["id"]; + } + } + return $max_level; + } + + /** + * Get all level entries + * + * @param + * @return + */ + public function getAllLevelEntriesOfUser($a_tref_id, $a_user_id = 0, $a_self_eval = 0) + { + $ilDB = $this->db; + $ilUser = $this->user; + + if ($a_user_id == 0) { + $a_user_id = $ilUser->getId(); + } + + $set = $ilDB->query( + $q = "SELECT * FROM skl_user_has_level " . + " WHERE skill_id = " . $ilDB->quote($this->getId(), "integer") . + " AND tref_id = " . $ilDB->quote((int) $a_tref_id, "integer") . + " AND user_id = " . $ilDB->quote($a_user_id, "integer") . + " AND self_eval = " . $ilDB->quote($a_self_eval, "integer") . + " ORDER BY status_date DESC" + ); + + $levels = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $levels[] = $rec; + } + return $levels; + } + + /** + * Get all historic level entries + * + * @param + * @return + */ + public function getAllHistoricLevelEntriesOfUser($a_tref_id, $a_user_id = 0, $a_eval_by = 0) + { + $ilDB = $this->db; + $ilUser = $this->user; + + if ($a_user_id == 0) { + $a_user_id = $ilUser->getId(); + } + + $by = ($a_eval_by != self::EVAL_BY_ALL) + ? " AND self_eval = " . $ilDB->quote($a_self_eval, "integer") + : ""; + + $set = $ilDB->query( + $q = "SELECT * FROM skl_user_skill_level " . + " WHERE skill_id = " . $ilDB->quote($this->getId(), "integer") . + " AND tref_id = " . $ilDB->quote((int) $a_tref_id, "integer") . + " AND user_id = " . $ilDB->quote($a_user_id, "integer") . + $by . + " ORDER BY status_date DESC" + ); + $levels = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $levels[] = $rec; + } + return $levels; + } + + + /** + * Get max levels per object + * + * @param + * @return + */ + public function getMaxLevelPerObject($a_tref_id, $a_object_id, $a_user_id = 0, $a_self_eval = 0) + { + $ilDB = $this->db; + $ilUser = $this->user; + + if ($a_user_id == 0) { + $a_user_id = $ilUser->getId(); + } + + $set = $ilDB->query( + $q = "SELECT level_id FROM skl_user_has_level " . + " WHERE trigger_obj_id = " . $ilDB->quote($a_object_id, "integer") . + " AND skill_id = " . $ilDB->quote($this->getId(), "integer") . + " AND tref_id = " . $ilDB->quote((int) $a_tref_id, "integer") . + " AND user_id = " . $ilDB->quote($a_user_id, "integer") . + " AND self_eval = " . $ilDB->quote($a_self_eval, "integer") + ); + + $has_level = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $has_level[$rec["level_id"]] = true; + } + $max_level = 0; + foreach ($this->getLevelData() as $l) { + if (isset($has_level[$l["id"]])) { + $max_level = $l["id"]; + } + } + return $max_level; + } + + /** + * Get max levels per object + * + * @param + * @return + */ + public function getMaxLevel($a_tref_id, $a_user_id = 0, $a_self_eval = 0) + { + $ilDB = $this->db; + $ilUser = $this->user; + + if ($a_user_id == 0) { + $a_user_id = $ilUser->getId(); + } + + $set = $ilDB->query( + $q = "SELECT level_id FROM skl_user_has_level " . + " WHERE skill_id = " . $ilDB->quote($this->getId(), "integer") . + " AND tref_id = " . $ilDB->quote((int) $a_tref_id, "integer") . + " AND user_id = " . $ilDB->quote($a_user_id, "integer") . + " AND self_eval = " . $ilDB->quote($a_self_eval, "integer") + ); + + $has_level = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $has_level[$rec["level_id"]] = true; + } + $max_level = 0; + foreach ($this->getLevelData() as $l) { + if (isset($has_level[$l["id"]])) { + $max_level = $l["id"]; + } + } + return $max_level; + } + + + /** + * Has use self evaluated a skill? + * + * @param int $a_user_id + * @param int $a_skill_id + * @param int $a_tref_id + * @return bool + */ + public static function hasSelfEvaluated($a_user_id, $a_skill_id, $a_tref_id) + { + global $DIC; + + $db = $DIC->database(); + + $set = $db->query( + $q = "SELECT level_id FROM skl_user_has_level " . + " WHERE skill_id = " . $db->quote((int) $a_skill_id, "integer") . + " AND tref_id = " . $db->quote((int) $a_tref_id, "integer") . + " AND user_id = " . $db->quote($a_user_id, "integer") . + " AND self_eval = " . $db->quote(1, "integer") + ); + + if ($rec = $db->fetchAssoc($set)) { + return true; + } + return false; + } + + /** + * Get last level set per object + * + * @param + * @return + */ + public function getLastLevelPerObject($a_tref_id, $a_object_id, $a_user_id = 0, $a_self_eval = 0) + { + $ilDB = $this->db; + $ilUser = $this->user; + + if ($a_user_id == 0) { + $a_user_id = $ilUser->getId(); + } + + $ilDB->setLimit(1); + $set = $ilDB->query( + $q = "SELECT level_id FROM skl_user_has_level " . + " WHERE trigger_obj_id = " . $ilDB->quote($a_object_id, "integer") . + " AND skill_id = " . $ilDB->quote($this->getId(), "integer") . + " AND tref_id = " . $ilDB->quote((int) $a_tref_id, "integer") . + " AND user_id = " . $ilDB->quote($a_user_id, "integer") . + " AND self_eval = " . $ilDB->quote($a_self_eval, "integer") . + " ORDER BY status_date DESC" + ); + + $rec = $ilDB->fetchAssoc($set); + + return $rec["level_id"]; + } + + /** + * Get last update per object + * + * @param + * @return + */ + public function getLastUpdatePerObject($a_tref_id, $a_object_id, $a_user_id = 0, $a_self_eval = 0) + { + $ilDB = $this->db; + $ilUser = $this->user; + + if ($a_user_id == 0) { + $a_user_id = $ilUser->getId(); + } + + $ilDB->setLimit(1); + $set = $ilDB->query( + $q = "SELECT status_date FROM skl_user_has_level " . + " WHERE trigger_obj_id = " . $ilDB->quote($a_object_id, "integer") . + " AND skill_id = " . $ilDB->quote($this->getId(), "integer") . + " AND tref_id = " . $ilDB->quote((int) $a_tref_id, "integer") . + " AND user_id = " . $ilDB->quote($a_user_id, "integer") . + " AND self_eval = " . $ilDB->quote($a_self_eval, "integer") . + " ORDER BY status_date DESC" + ); + + $rec = $ilDB->fetchAssoc($set); + + return $rec["status_date"]; + } + + // + // + // Certificate related methods + // + // + + /** + * Get title for certificate + * + * @param + * @return + */ + public function getTitleForCertificate() + { + return $this->getTitle(); + } + + /** + * Get short title for certificate + * + * @param + * @return + */ + public function getShortTitleForCertificate() + { + return "Skill"; + } + + /** + * Checks whether a skill level has a certificate or not + * @param int skill id + * @param int skill level id + * @return true/false + */ + public static function _lookupCertificate($a_skill_id, $a_skill_level_id) + { + $certificatefile = CLIENT_WEB_DIR . "/certificates/skill/" . + ((int) $a_skill_id) . "/" . ((int) $a_skill_level_id) . "/certificate.xml"; + if (@file_exists($certificatefile)) { + return true; + } else { + return false; + } + } + + /** + * Get usage info + * + * @param + * @return + */ + public static function getUsageInfo($a_cskill_ids, &$a_usages) + { + global $DIC; + + $ilDB = $DIC->database(); + + include_once("./Services/Skill/classes/class.ilSkillUsage.php"); + ilSkillUsage::getUsageInfoGeneric( + $a_cskill_ids, + $a_usages, + ilSkillUsage::USER_ASSIGNED, + "skl_user_skill_level", + "user_id" + ); + } + + /** + * Get common skill ids for import IDs (newest first) + * + * @param int $a_source_inst_id source installation id, must be <>0 + * @param int $a_skill_import_id source skill id (type basic skill ("skll") or basic skill template ("sktp")) + * @param int $a_tref_import_id source template reference id (if > 0 skill_import_id will be of type "sktp") + * @return array array of common skill ids, keys are "skill_id", "tref_id", "creation_date" + */ + public static function getCommonSkillIdForImportId($a_source_inst_id, $a_skill_import_id, $a_tref_import_id = 0) + { + global $DIC; + + $ilDB = $DIC->database(); + + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); + $tree = new ilSkillTree(); + + if ($a_source_inst_id == 0) { + return array(); + } + + $template_ids = array(); + if ($a_tref_import_id > 0) { + $skill_node_type = "sktp"; + + // get all matching tref nodes + $set = $ilDB->query("SELECT * FROM skl_tree_node n JOIN skl_tree t ON (n.obj_id = t.child) " . + " WHERE n.import_id = " . $ilDB->quote("il_" . ((int) $a_source_inst_id) . "_sktr_" . $a_tref_import_id, "text") . + " ORDER BY n.creation_date DESC "); + while ($rec = $ilDB->fetchAssoc($set)) { + if (($t = ilSkillTemplateReference::_lookupTemplateId($rec["obj_id"])) > 0) { + $template_ids[$t] = $rec["obj_id"]; + } + } + } else { + $skill_node_type = "skll"; + } + $set = $ilDB->query("SELECT * FROM skl_tree_node n JOIN skl_tree t ON (n.obj_id = t.child) " . + " WHERE n.import_id = " . $ilDB->quote("il_" . ((int) $a_source_inst_id) . "_" . $skill_node_type . "_" . $a_skill_import_id, "text") . + " ORDER BY n.creation_date DESC "); + $results = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $matching_trefs = array(); + if ($a_tref_import_id > 0) { + $skill_template_id = $tree->getTopParentNodeId($rec["obj_id"]); + + // check of skill is in template + foreach ($template_ids as $templ => $tref) { + if ($skill_template_id == $templ) { + $matching_trefs[] = $tref; + } + } + } else { + $matching_trefs = array(0); + } + + foreach ($matching_trefs as $t) { + $results[] = array("skill_id" => $rec["obj_id"], "tref_id" => $t, "creation_date" => $rec["creation_date"]); + } + } + return $results; + } + + /** + * Get level ids for import IDs (newest first) + * + * @param int $a_source_inst_id source installation id, must be <>0 + * @param int $a_skill_import_id source skill id (type basic skill ("skll") or basic skill template ("sktp")) + * @return array array of common skill ids, keys are "level_id", "creation_date" + */ + public static function getLevelIdForImportId($a_source_inst_id, $a_level_import_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query("SELECT * FROM skl_level l JOIN skl_tree t ON (l.skill_id = t.child) " . + " WHERE l.import_id = " . $ilDB->quote("il_" . ((int) $a_source_inst_id) . "_sklv_" . $a_level_import_id, "text") . + " ORDER BY l.creation_date DESC "); + $results = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $results[] = array("level_id" => $rec["id"], "creation_date" => $rec["creation_date"]); + } + return $results; + } + + /** + * Get level ids for import Ids matching common skills + * + * @param + * @return + */ + public static function getLevelIdForImportIdMatchSkill($a_source_inst_id, $a_level_import_id, $a_skill_import_id, $a_tref_import_id = 0) + { + $level_id_data = self::getLevelIdForImportId($a_source_inst_id, $a_level_import_id); + $skill_data = self::getCommonSkillIdForImportId($a_source_inst_id, $a_skill_import_id, $a_tref_import_id); + $matches = array(); + foreach ($level_id_data as $l) { + reset($skill_data); + foreach ($skill_data as $s) { + if (ilBasicSkill::lookupLevelSkillId($l["level_id"]) == $s["skill_id"]) { + $matches[] = array( + "level_id" => $l["level_id"], + "creation_date" => $l["creation_date"], + "skill_id" => $s["skill_id"], + "tref_id" => $s["tref_id"] + ); + } + } + } + return $matches; + } } -?> diff --git a/Services/Skill/classes/class.ilBasicSkillGUI.php b/Services/Skill/classes/class.ilBasicSkillGUI.php index 0726c3dfba77a6b5bf307d99e188529d95a32dd7..0a48d4e40aea8c66df5b9ad31039346f02d49d81 100644 --- a/Services/Skill/classes/class.ilBasicSkillGUI.php +++ b/Services/Skill/classes/class.ilBasicSkillGUI.php @@ -17,950 +17,927 @@ include_once("./Services/Skill/classes/class.ilBasicSkill.php"); */ class ilBasicSkillGUI extends ilSkillTreeNodeGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilHelpGUI - */ - protected $help; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTree - */ - protected $tree; - - protected $tref_id = 0; - protected $base_skill_id; - - /** - * Constructor - */ - function __construct($a_node_id = 0) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->tpl = $DIC["tpl"]; - $this->tabs = $DIC->tabs(); - $this->help = $DIC["ilHelp"]; - $this->toolbar = $DIC->toolbar(); - $this->lng = $DIC->language(); - $this->tree = $DIC->repositoryTree(); - $ilCtrl = $DIC->ctrl(); - - $ilCtrl->saveParameter($this, array("obj_id", "level_id")); - $this->base_skill_id = $a_node_id; - - parent::__construct($a_node_id); - } - - /** - * Get Node Type - */ - function getType() - { - return "skll"; - } - - /** - * Execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - //$tpl->getStandardTemplate(); - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd(); - switch($next_class) - { - case "ilcertificategui": - $this->setLevelHead(); - $ilTabs->activateTab("level_certificate"); - - $skillLevelId = (int)$_GET["level_id"]; - - $output_gui = new ilCertificateGUI( - new ilSkillCertificateAdapter($this->node_object, $skillLevelId), - new ilDefaultPlaceholderDescription(), - new ilDefaultPlaceholderValues(), - $this->node_object->getId(), - ilCertificatePathConstants::SKILL_PATH . $this->node_object->getId() . '/' . $skillLevelId - ); - - $ret = $ilCtrl->forwardCommand($output_gui); - break; - - default: - $ret = $this->$cmd(); - break; - } - } - - /** - * Show properties - */ - function showProperties() - { - $tpl = $this->tpl; - - $this->setTabs(); - $this->setLocator(); - - $tpl->setContent("Properties"); - } - - /** - * Save item - */ - function saveItem() - { - if (!$this->checkPermissionBool("write")) - { - return; - } - - $it = new ilBasicSkill(); - $it->setTitle($this->form->getInput("title")); - $it->setOrderNr($this->form->getInput("order_nr")); - $it->setStatus($this->form->getInput("status")); - $it->setSelfEvaluation($_POST["self_eval"]); - $it->create(); - ilSkillTreeNode::putInTree($it, (int) $_GET["obj_id"], IL_LAST_NODE); - $this->node_object = $it; - } - - /** - * After saving - */ - function afterSave() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameterByClass("ilbasicskillgui", "obj_id", - $this->node_object->getId()); - $ilCtrl->redirectByClass("ilbasicskillgui", "edit"); - } - - /** - * Update item - */ - function updateItem() - { - if (!$this->checkPermissionBool("write")) - { - return; - } - - $this->node_object->setTitle($this->form->getInput("title")); - $this->node_object->setOrderNr($this->form->getInput("order_nr")); - $this->node_object->setSelfEvaluation($_POST["self_eval"]); - $this->node_object->setStatus($_POST["status"]); - $this->node_object->update(); - } - - /** - * Edit skill - */ - function edit() - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->setTabs("levels"); - - if ($this->isInUse()) - { - ilUtil::sendInfo($lng->txt("skmg_skill_in_use")); - } - else - { - if ($this->checkPermissionBool("write")) - { - $ilToolbar->addButton($lng->txt("skmg_add_level"), - $ilCtrl->getLinkTarget($this, "addLevel")); - } - } - - include_once("./Services/Skill/classes/class.ilSkillLevelTableGUI.php"); - $table = new ilSkillLevelTableGUI($this->base_skill_id, $this, "edit", 0, $this->isInUse()); - $tpl->setContent($table->getHTML()); - } - - /** - * Init form. - * - * @param int $a_mode Edit Mode - */ - public function initForm($a_mode = "edit") - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - // title - $ti = new ilTextInputGUI($lng->txt("title"), "title"); - $ti->setMaxLength(200); - $ti->setSize(50); - $ti->setRequired(true); - $this->form->addItem($ti); - - // order nr - $ni = new ilNumberInputGUI($lng->txt("skmg_order_nr"), "order_nr"); - $ni->setInfo($lng->txt("skmg_order_nr_info")); - $ni->setMaxLength(6); - $ni->setSize(6); - $ni->setRequired(true); - if ($a_mode == "create") - { - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $tree = new ilSkillTree(); - $max = $tree->getMaxOrderNr((int)$_GET["obj_id"]); - $ni->setValue($max + 10); - } - $this->form->addItem($ni); - - // status - $this->addStatusInput($this->form); - - // selectable - $cb = new ilCheckboxInputGUI($lng->txt("skmg_selectable"), "self_eval"); - $cb->setInfo($lng->txt("skmg_selectable_info")); - $this->form->addItem($cb); - - // save and cancel commands - if ($this->checkPermissionBool("write")) - { - if ($a_mode == "create") - { - $this->form->addCommandButton("save", $lng->txt("save")); - $this->form->addCommandButton("cancelSave", $lng->txt("cancel")); - $this->form->setTitle($lng->txt("skmg_create_skll")); - } else - { - $this->form->addCommandButton("update", $lng->txt("save")); - $this->form->setTitle($lng->txt("skmg_edit_skll")); - } - } - - $ilCtrl->setParameter($this, "obj_id", $_GET["obj_id"]); - $this->form->setFormAction($ilCtrl->getFormAction($this)); - } - - /** - * Edit properties - */ - function editProperties() - { - $this->setTabs("properties"); - parent::editProperties(); - } - - - // - // - // Skill level related methods - // - // - - /** - * Add new level - */ - function addLevel() - { - $tpl = $this->tpl; - - $this->initLevelForm("create"); - $tpl->setContent($this->form->getHTML()); - } - - /** - * Edit level - */ - function editLevel() - { - $tpl = $this->tpl; - $lng = $this->lng; - - if ($this->isInUse()) - { - ilUtil::sendInfo($lng->txt("skmg_skill_in_use")); - } - - $this->initLevelForm(); - $this->getLevelValues(); - $tpl->setContent($this->form->getHTML()); - } - - /** - * Save level form - */ - public function saveLevel() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if (!$this->checkPermissionBool("write")) - { - return; - } - - $this->initLevelForm("create"); - if ($this->form->checkInput()) - { - // perform save - $this->node_object->addLevel( - $this->form->getInput("title"), - $this->form->getInput("description")); - - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "edit"); - } - - $this->form->setValuesByPost(); - $tpl->setContent($this->form->getHtml()); - } - - /** - * Update level form - */ - function updateLevel() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - - if (!$this->checkPermissionBool("write")) - { - return; - } - - $this->initLevelForm("edit"); - if ($this->form->checkInput()) - { - $this->node_object->writeLevelTitle( - (int) $_GET["level_id"], - $this->form->getInput("title")); - $this->node_object->writeLevelDescription( - (int) $_GET["level_id"], - $this->form->getInput("description")); - - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "edit"); - } - - $this->form->setValuesByPost(); - $tpl->setContent($this->form->getHtml()); - } - - /** - * Init level form. - * - * @param string $a_mode form mode - */ - public function initLevelForm($a_mode = "edit") - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - $ilCtrl->saveParameter($this, "level_id"); - $this->setLevelHead(); - $ilTabs->activateTab("level_settings"); - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - // title - $ti = new ilTextInputGUI($lng->txt("title"), "title"); - $ti->setMaxLength(200); - $ti->setRequired(true); - $this->form->addItem($ti); - - // description - $ta = new ilTextAreaInputGUI($lng->txt("description"), "description"); - $ta->setCols(50); - $ta->setRows(5); - $this->form->addItem($ta); - - // save and cancel commands - if ($this->checkPermissionBool("write")) - { - if ($a_mode == "create") - { - $this->form->addCommandButton("saveLevel", $lng->txt("save")); - $this->form->addCommandButton("edit", $lng->txt("cancel")); - $this->form->setTitle($lng->txt("skmg_new_level")); - } else - { - $this->form->addCommandButton("updateLevel", $lng->txt("save")); - $this->form->addCommandButton("edit", $lng->txt("cancel")); - $this->form->setTitle($lng->txt("skmg_edit_level")); - } - } - - $this->form->setFormAction($ilCtrl->getFormAction($this)); - } - - /** - * Get current values for level from - */ - public function getLevelValues() - { - $values = array(); - - $data = $this->node_object->getLevelData((int) $_GET["level_id"]); - $values["title"] = $data["title"]; - $values["description"] = $data["description"]; - $this->form->setValuesByArray($values); - } - - /** - * Update level order - */ - function updateLevelOrder() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if (!$this->checkPermissionBool("write")) - { - return; - } - - $order = ilUtil::stripSlashesArray($_POST["order"]); - $this->node_object->updateLevelOrder($order); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "edit"); - } - - /** - * Confirm level deletion - */ - function confirmLevelDeletion() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - if (!$this->checkPermissionBool("write")) - { - return; - } - - $this->setTabs("levels"); - - if (!is_array($_POST["id"]) || count($_POST["id"]) == 0) - { - ilUtil::sendInfo($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "edit"); - } - else - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("skmg_really_delete_levels")); - $cgui->setCancel($lng->txt("cancel"), "edit"); - $cgui->setConfirm($lng->txt("delete"), "deleteLevel"); - - foreach ($_POST["id"] as $i) - { - $cgui->addItem("id[]", $i, ilBasicSkill::lookupLevelTitle($i)); - } - - $tpl->setContent($cgui->getHTML()); - } - } - - /** - * Delete levels - */ - function deleteLevel() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if (!$this->checkPermissionBool("write")) - { - return; - } - - if (is_array($_POST["id"])) - { - foreach ($_POST["id"] as $id) - { - $this->node_object->deleteLevel((int) $id); - } - $this->node_object->fixLevelNumbering(); - } - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "edit"); - } - - /** - * Set header for level - */ - function setLevelHead() - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - $ilHelp = $this->help; - - // tabs - $ilTabs->clearTargets(); - $ilHelp->setScreenIdComponent("skmg_lev"); - - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTarget($this, "edit")); - - if ($_GET["level_id"] > 0) - { - $ilTabs->addTab("level_settings", - $lng->txt("settings"), - $ilCtrl->getLinkTarget($this, "editLevel")); - -/* $ilTabs->addTab("level_trigger", - $lng->txt("skmg_trigger"), - $ilCtrl->getLinkTarget($this, "editLevelTrigger"));*/ - - $ilTabs->addTab("level_resources", - $lng->txt("skmg_resources"), - $ilCtrl->getLinkTarget($this, "showLevelResources")); -/* - $ilTabs->addTab("level_certificate", - $lng->txt("certificate"), - $ilCtrl->getLinkTargetByClass("ilcertificategui", "certificateEditor"));*/ - - } - - // title - if ($_GET["level_id"] > 0) - { - $tpl->setTitle($lng->txt("skmg_skill_level").": ". - ilBasicSkill::lookupLevelTitle((int) $_GET["level_id"])); - } - else - { - $tpl->setTitle($lng->txt("skmg_skill_level")); - } - - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $tree = new ilSkillTree(); - $path = $tree->getPathFull($this->node_object->getId()); - $desc = ""; - foreach ($path as $p) - { - if (in_array($p["type"], array("scat", "skll"))) - { - $desc.= $sep.$p["title"]; - $sep = " > "; - } - } - $tpl->setDescription($desc); - } - - /** - * Set header for skill - * - * @param string $a_tab active tab - */ - function setTabs($a_tab = "levels") - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - $ilHelp = $this->help; - - $ilTabs->clearTargets(); - $ilHelp->setScreenIdComponent("skmg_skll"); -// $ilTabs->setBackTarget($lng->txt("skmg_skill_hierarchie"), -// $ilCtrl->getLinkTargetByClass("ilobjskillmanagementgui", "editSkills")); - - if (is_object($this->node_object)) - { - - // levels - $ilTabs->addTab("levels", $lng->txt("skmg_skill_levels"), - $ilCtrl->getLinkTarget($this, 'edit')); - - // properties - $ilTabs->addTab("properties", $lng->txt("settings"), - $ilCtrl->getLinkTarget($this, 'editProperties')); - - // usage - $this->addUsageTab($ilTabs); - - $ilCtrl->setParameterByClass("ilskillrootgui", "obj_id", - $this->node_object->skill_tree->getRootId()); - $ilTabs->setBackTarget($lng->txt("obj_skmg"), - $ilCtrl->getLinkTargetByClass("ilskillrootgui", "listSkills")); - $ilCtrl->setParameterByClass("ilskillrootgui", "obj_id", - $_GET["obj_id"]); - - $ilTabs->activateTab($a_tab); - - $tpl->setTitle($lng->txt("skmg_skill").": ". - $this->node_object->getTitle()); - - $this->setSkillNodeDescription(); - } - else - { - $tpl->setTitle($lng->txt("skmg_skill")); - $tpl->setDescription(""); - } - parent::setTitleIcon(); - } - - /** - * Edit level trigger - */ - function editLevelTrigger() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - $this->setLevelHead(); - $ilTabs->activateTab("level_trigger"); - - $trigger = ilBasicSkill::lookupLevelTrigger((int) $_GET["level_id"]); - if (ilObject::_lookupType($trigger["obj_id"]) != "crs" || - ilObject::_isInTrash($trigger["ref_id"])) - { - $trigger = array(); - } - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - // trigger - $ne = new ilNonEditableValueGUI($lng->txt("skmg_trigger"), "trigger"); - if ($trigger["obj_id"] > 0) - { - $ne->setValue(ilObject::_lookupTitle($trigger["obj_id"])); - } - else - { - $ne->setValue($lng->txt("skmg_no_trigger")); - } - $this->form->addItem($ne); - - if ($trigger["obj_id"] > 0) - { - $this->form->addCommandButton("removeLevelTrigger", $lng->txt("skmg_remove_trigger")); - } - $this->form->addCommandButton("selectLevelTrigger", $lng->txt("skmg_select_trigger")); - - $this->form->setTitle($lng->txt("skmg_skill_level_trigger")); - $this->form->setFormAction($ilCtrl->getFormAction($this)); - - $tpl->setContent($this->form->getHTML()); - } - - /** - * Select skill level trigger - */ - function selectLevelTrigger() - { - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - $lng = $this->lng; - $tree = $this->tree; - $tpl = $this->tpl; - - if (!$this->checkPermissionBool("write")) - { - return; - } - - $this->setLevelHead(); - $ilTabs->activateTab("level_trigger"); - - include_once 'Services/Search/classes/class.ilSearchRootSelector.php'; - $exp = new ilSearchRootSelector( - $ilCtrl->getLinkTarget($this,'showRepositorySelection')); - $exp->setExpand($_GET["search_root_expand"] ? $_GET["search_root_expand"] : $tree->readRootId()); - $exp->setExpandTarget($ilCtrl->getLinkTarget($this,'selectLevelTrigger')); - $exp->setTargetClass(get_class($this)); - $exp->setCmd('saveLevelTrigger'); - $exp->setClickableTypes(array("crs")); - - // build html-output - $exp->setOutput(0); - $tpl->setContent($exp->getOutput()); - - } - - /** - * Save level trigger - */ - function saveLevelTrigger() - { - $ilCtrl = $this->ctrl; - - if (!$this->checkPermissionBool("write")) - { - return; - } - - ilBasicSkill::writeLevelTrigger((int) $_GET["level_id"], (int) $_GET["root_id"]); - $ilCtrl->redirect($this, "editLevelTrigger"); - } - - /** - * Remove trigger - */ - function removeLevelTrigger() - { - $ilCtrl = $this->ctrl; - - ilBasicSkill::writeLevelTrigger((int) $_GET["level_id"], 0); - $ilCtrl->redirect($this, "editLevelTrigger"); - } - - /** - * Redirect to parent (identified by current obj_id) - */ - function redirectToParent($a_tmp_mode = false) - { - $ilCtrl = $this->ctrl; - - $t = ilSkillTreeNode::_lookupType((int) $_GET["obj_id"]); - - switch ($t) - { - case "skrt": - $ilCtrl->setParameterByClass("ilskillrootgui", "obj_id", (int) $_GET["obj_id"]); - $ilCtrl->redirectByClass("ilskillrootgui", "listSkills"); - break; - } - - parent::redirectToParent(); - } - - - //// - //// Level resources - //// - - /** - * Show level resources - */ - function showLevelResources() - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; - $ilToolbar = $this->toolbar; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if ($this->checkPermissionBool("write")) - { - $ilToolbar->addButton( - $lng->txt("skmg_add_resource"), - $ilCtrl->getLinkTarget($this, "addLevelResource")); - } - - $this->setLevelHead(); - $ilTabs->activateTab("level_resources"); - - include_once("./Services/Skill/classes/class.ilSkillLevelResourcesTableGUI.php"); - $tab = new ilSkillLevelResourcesTableGUI($this, "showLevelResources", - $this->base_skill_id, $this->tref_id, (int) $_GET["level_id"], - $this->checkPermissionBool("write")); - - $tpl->setContent($tab->getHTML()); - } - - /** - * Add level resource - */ - function addLevelResource() - { - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - $lng = $this->lng; - $tree = $this->tree; - $tpl = $this->tpl; - - $this->setLevelHead(); - $ilTabs->activateTab("level_resources"); - - include_once("./Services/Repository/classes/class.ilRepositorySelectorExplorerGUI.php"); - $exp = new ilRepositorySelectorExplorerGUI($this, "addLevelResource", - $this, "saveLevelResource", "root_id"); - if (!$exp->handleCommand()) - { - $tpl->setContent($exp->getHTML()); - } - } - - /** - * Save level resource - */ - function saveLevelResource() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $ref_id = (int) $_GET["root_id"]; - - if (!$this->checkPermissionBool("write")) - { - return; - } - - if ($ref_id > 0) - { - include_once("./Services/Skill/classes/class.ilSkillResources.php"); - $sres = new ilSkillResources($this->base_skill_id, $this->tref_id); - $sres->setResourceAsImparting((int) $_GET["level_id"], $ref_id); - $sres->save(); - - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - } - - $ilCtrl->redirect($this, "showLevelResources"); - } - - /** - * Confirm level resources removal - */ - function confirmLevelResourcesRemoval() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - $ilTabs = $this->tabs; - - if (!$this->checkPermissionBool("write")) - { - return; - } - - $this->setLevelHead(); - $ilTabs->activateTab("level_resources"); - - if (!is_array($_POST["id"]) || count($_POST["id"]) == 0) - { - ilUtil::sendInfo($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "showLevelResources"); - } - else - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("skmg_confirm_level_resources_removal")); - $cgui->setCancel($lng->txt("cancel"), "showLevelResources"); - $cgui->setConfirm($lng->txt("remove"), "removeLevelResources"); - - foreach ($_POST["id"] as $i) - { - $title = ilObject::_lookupTitle(ilObject::_lookupObjId($i)); - $cgui->addItem("id[]", $i, $title); - } - - $tpl->setContent($cgui->getHTML()); - } - } - - /** - * Remove level resource - */ - function removeLevelResources() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if (!$this->checkPermissionBool("write")) - { - return; - } - - if (is_array($_POST["id"])) - { - include_once("./Services/Skill/classes/class.ilSkillResources.php"); - $sres = new ilSkillResources($this->base_skill_id, $this->tref_id); - foreach ($_POST["id"] as $i) - { - $sres->setResourceAsImparting((int) $_GET["level_id"], $i, false); - $sres->setResourceAsTrigger((int) $_GET["level_id"], $i, false); - } - $sres->save(); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - } - - $ilCtrl->redirect($this, "showLevelResources"); - } - - /** - * Save resource settings - * - * @param - * @return - */ - function saveResourceSettings() - { - $ilCtrl = $this->ctrl; - - include_once("./Services/Skill/classes/class.ilSkillResources.php"); - $resources = new ilSkillResources($this->base_skill_id, $this->tref_id); - - foreach ($resources->getResourcesOfLevel((int) $_GET["level_id"]) as $r) - { - $imparting = false; - if (is_array($_POST["suggested"]) && isset($_POST["suggested"][$r["rep_ref_id"]]) && $_POST["suggested"][$r["rep_ref_id"]]) - { - $imparting = true; - } - $trigger = false; - if (is_array($_POST["trigger"]) && isset($_POST["trigger"][$r["rep_ref_id"]]) && $_POST["trigger"][$r["rep_ref_id"]]) - { - $trigger = true; - } - $resources->setResourceAsImparting((int) $_GET["level_id"], $r["rep_ref_id"], $imparting); - $resources->setResourceAsTrigger((int) $_GET["level_id"], $r["rep_ref_id"], $trigger); - } - $resources->save(); - - $ilCtrl->redirect($this, "showLevelResources"); - } + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTree + */ + protected $tree; + + protected $tref_id = 0; + protected $base_skill_id; + + /** + * Constructor + */ + public function __construct($a_node_id = 0) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->tpl = $DIC["tpl"]; + $this->tabs = $DIC->tabs(); + $this->help = $DIC["ilHelp"]; + $this->toolbar = $DIC->toolbar(); + $this->lng = $DIC->language(); + $this->tree = $DIC->repositoryTree(); + $ilCtrl = $DIC->ctrl(); + + $ilCtrl->saveParameter($this, array("obj_id", "level_id")); + $this->base_skill_id = $a_node_id; + + parent::__construct($a_node_id); + } + + /** + * Get Node Type + */ + public function getType() + { + return "skll"; + } + + /** + * Execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + //$tpl->getStandardTemplate(); + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd(); + switch ($next_class) { + case "ilcertificategui": + $this->setLevelHead(); + $ilTabs->activateTab("level_certificate"); + + $skillLevelId = (int) $_GET["level_id"]; + + $output_gui = new ilCertificateGUI( + new ilSkillCertificateAdapter($this->node_object, $skillLevelId), + new ilDefaultPlaceholderDescription(), + new ilDefaultPlaceholderValues(), + $this->node_object->getId(), + ilCertificatePathConstants::SKILL_PATH . $this->node_object->getId() . '/' . $skillLevelId + ); + + $ret = $ilCtrl->forwardCommand($output_gui); + break; + + default: + $ret = $this->$cmd(); + break; + } + } + + /** + * Show properties + */ + public function showProperties() + { + $tpl = $this->tpl; + + $this->setTabs(); + $this->setLocator(); + + $tpl->setContent("Properties"); + } + + /** + * Save item + */ + public function saveItem() + { + if (!$this->checkPermissionBool("write")) { + return; + } + + $it = new ilBasicSkill(); + $it->setTitle($this->form->getInput("title")); + $it->setOrderNr($this->form->getInput("order_nr")); + $it->setStatus($this->form->getInput("status")); + $it->setSelfEvaluation($_POST["self_eval"]); + $it->create(); + ilSkillTreeNode::putInTree($it, (int) $_GET["obj_id"], IL_LAST_NODE); + $this->node_object = $it; + } + + /** + * After saving + */ + public function afterSave() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameterByClass( + "ilbasicskillgui", + "obj_id", + $this->node_object->getId() + ); + $ilCtrl->redirectByClass("ilbasicskillgui", "edit"); + } + + /** + * Update item + */ + public function updateItem() + { + if (!$this->checkPermissionBool("write")) { + return; + } + + $this->node_object->setTitle($this->form->getInput("title")); + $this->node_object->setOrderNr($this->form->getInput("order_nr")); + $this->node_object->setSelfEvaluation($_POST["self_eval"]); + $this->node_object->setStatus($_POST["status"]); + $this->node_object->update(); + } + + /** + * Edit skill + */ + public function edit() + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $this->setTabs("levels"); + + if ($this->isInUse()) { + ilUtil::sendInfo($lng->txt("skmg_skill_in_use")); + } else { + if ($this->checkPermissionBool("write")) { + $ilToolbar->addButton( + $lng->txt("skmg_add_level"), + $ilCtrl->getLinkTarget($this, "addLevel") + ); + } + } + + include_once("./Services/Skill/classes/class.ilSkillLevelTableGUI.php"); + $table = new ilSkillLevelTableGUI($this->base_skill_id, $this, "edit", 0, $this->isInUse()); + $tpl->setContent($table->getHTML()); + } + + /** + * Init form. + * + * @param int $a_mode Edit Mode + */ + public function initForm($a_mode = "edit") + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + // title + $ti = new ilTextInputGUI($lng->txt("title"), "title"); + $ti->setMaxLength(200); + $ti->setSize(50); + $ti->setRequired(true); + $this->form->addItem($ti); + + // order nr + $ni = new ilNumberInputGUI($lng->txt("skmg_order_nr"), "order_nr"); + $ni->setInfo($lng->txt("skmg_order_nr_info")); + $ni->setMaxLength(6); + $ni->setSize(6); + $ni->setRequired(true); + if ($a_mode == "create") { + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $tree = new ilSkillTree(); + $max = $tree->getMaxOrderNr((int) $_GET["obj_id"]); + $ni->setValue($max + 10); + } + $this->form->addItem($ni); + + // status + $this->addStatusInput($this->form); + + // selectable + $cb = new ilCheckboxInputGUI($lng->txt("skmg_selectable"), "self_eval"); + $cb->setInfo($lng->txt("skmg_selectable_info")); + $this->form->addItem($cb); + + // save and cancel commands + if ($this->checkPermissionBool("write")) { + if ($a_mode == "create") { + $this->form->addCommandButton("save", $lng->txt("save")); + $this->form->addCommandButton("cancelSave", $lng->txt("cancel")); + $this->form->setTitle($lng->txt("skmg_create_skll")); + } else { + $this->form->addCommandButton("update", $lng->txt("save")); + $this->form->setTitle($lng->txt("skmg_edit_skll")); + } + } + + $ilCtrl->setParameter($this, "obj_id", $_GET["obj_id"]); + $this->form->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * Edit properties + */ + public function editProperties() + { + $this->setTabs("properties"); + parent::editProperties(); + } + + + // + // + // Skill level related methods + // + // + + /** + * Add new level + */ + public function addLevel() + { + $tpl = $this->tpl; + + $this->initLevelForm("create"); + $tpl->setContent($this->form->getHTML()); + } + + /** + * Edit level + */ + public function editLevel() + { + $tpl = $this->tpl; + $lng = $this->lng; + + if ($this->isInUse()) { + ilUtil::sendInfo($lng->txt("skmg_skill_in_use")); + } + + $this->initLevelForm(); + $this->getLevelValues(); + $tpl->setContent($this->form->getHTML()); + } + + /** + * Save level form + */ + public function saveLevel() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if (!$this->checkPermissionBool("write")) { + return; + } + + $this->initLevelForm("create"); + if ($this->form->checkInput()) { + // perform save + $this->node_object->addLevel( + $this->form->getInput("title"), + $this->form->getInput("description") + ); + + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "edit"); + } + + $this->form->setValuesByPost(); + $tpl->setContent($this->form->getHtml()); + } + + /** + * Update level form + */ + public function updateLevel() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + + if (!$this->checkPermissionBool("write")) { + return; + } + + $this->initLevelForm("edit"); + if ($this->form->checkInput()) { + $this->node_object->writeLevelTitle( + (int) $_GET["level_id"], + $this->form->getInput("title") + ); + $this->node_object->writeLevelDescription( + (int) $_GET["level_id"], + $this->form->getInput("description") + ); + + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "edit"); + } + + $this->form->setValuesByPost(); + $tpl->setContent($this->form->getHtml()); + } + + /** + * Init level form. + * + * @param string $a_mode form mode + */ + public function initLevelForm($a_mode = "edit") + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + $ilCtrl->saveParameter($this, "level_id"); + $this->setLevelHead(); + $ilTabs->activateTab("level_settings"); + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + // title + $ti = new ilTextInputGUI($lng->txt("title"), "title"); + $ti->setMaxLength(200); + $ti->setRequired(true); + $this->form->addItem($ti); + + // description + $ta = new ilTextAreaInputGUI($lng->txt("description"), "description"); + $ta->setCols(50); + $ta->setRows(5); + $this->form->addItem($ta); + + // save and cancel commands + if ($this->checkPermissionBool("write")) { + if ($a_mode == "create") { + $this->form->addCommandButton("saveLevel", $lng->txt("save")); + $this->form->addCommandButton("edit", $lng->txt("cancel")); + $this->form->setTitle($lng->txt("skmg_new_level")); + } else { + $this->form->addCommandButton("updateLevel", $lng->txt("save")); + $this->form->addCommandButton("edit", $lng->txt("cancel")); + $this->form->setTitle($lng->txt("skmg_edit_level")); + } + } + + $this->form->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * Get current values for level from + */ + public function getLevelValues() + { + $values = array(); + + $data = $this->node_object->getLevelData((int) $_GET["level_id"]); + $values["title"] = $data["title"]; + $values["description"] = $data["description"]; + $this->form->setValuesByArray($values); + } + + /** + * Update level order + */ + public function updateLevelOrder() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if (!$this->checkPermissionBool("write")) { + return; + } + + $order = ilUtil::stripSlashesArray($_POST["order"]); + $this->node_object->updateLevelOrder($order); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "edit"); + } + + /** + * Confirm level deletion + */ + public function confirmLevelDeletion() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + if (!$this->checkPermissionBool("write")) { + return; + } + + $this->setTabs("levels"); + + if (!is_array($_POST["id"]) || count($_POST["id"]) == 0) { + ilUtil::sendInfo($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "edit"); + } else { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("skmg_really_delete_levels")); + $cgui->setCancel($lng->txt("cancel"), "edit"); + $cgui->setConfirm($lng->txt("delete"), "deleteLevel"); + + foreach ($_POST["id"] as $i) { + $cgui->addItem("id[]", $i, ilBasicSkill::lookupLevelTitle($i)); + } + + $tpl->setContent($cgui->getHTML()); + } + } + + /** + * Delete levels + */ + public function deleteLevel() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if (!$this->checkPermissionBool("write")) { + return; + } + + if (is_array($_POST["id"])) { + foreach ($_POST["id"] as $id) { + $this->node_object->deleteLevel((int) $id); + } + $this->node_object->fixLevelNumbering(); + } + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "edit"); + } + + /** + * Set header for level + */ + public function setLevelHead() + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + $ilHelp = $this->help; + + // tabs + $ilTabs->clearTargets(); + $ilHelp->setScreenIdComponent("skmg_lev"); + + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, "edit") + ); + + if ($_GET["level_id"] > 0) { + $ilTabs->addTab( + "level_settings", + $lng->txt("settings"), + $ilCtrl->getLinkTarget($this, "editLevel") + ); + + /* $ilTabs->addTab("level_trigger", + $lng->txt("skmg_trigger"), + $ilCtrl->getLinkTarget($this, "editLevelTrigger"));*/ + + $ilTabs->addTab( + "level_resources", + $lng->txt("skmg_resources"), + $ilCtrl->getLinkTarget($this, "showLevelResources") + ); + /* + $ilTabs->addTab("level_certificate", + $lng->txt("certificate"), + $ilCtrl->getLinkTargetByClass("ilcertificategui", "certificateEditor"));*/ + } + + // title + if ($_GET["level_id"] > 0) { + $tpl->setTitle($lng->txt("skmg_skill_level") . ": " . + ilBasicSkill::lookupLevelTitle((int) $_GET["level_id"])); + } else { + $tpl->setTitle($lng->txt("skmg_skill_level")); + } + + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $tree = new ilSkillTree(); + $path = $tree->getPathFull($this->node_object->getId()); + $desc = ""; + foreach ($path as $p) { + if (in_array($p["type"], array("scat", "skll"))) { + $desc.= $sep . $p["title"]; + $sep = " > "; + } + } + $tpl->setDescription($desc); + } + + /** + * Set header for skill + * + * @param string $a_tab active tab + */ + public function setTabs($a_tab = "levels") + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + $ilHelp = $this->help; + + $ilTabs->clearTargets(); + $ilHelp->setScreenIdComponent("skmg_skll"); + // $ilTabs->setBackTarget($lng->txt("skmg_skill_hierarchie"), + // $ilCtrl->getLinkTargetByClass("ilobjskillmanagementgui", "editSkills")); + + if (is_object($this->node_object)) { + + // levels + $ilTabs->addTab( + "levels", + $lng->txt("skmg_skill_levels"), + $ilCtrl->getLinkTarget($this, 'edit') + ); + + // properties + $ilTabs->addTab( + "properties", + $lng->txt("settings"), + $ilCtrl->getLinkTarget($this, 'editProperties') + ); + + // usage + $this->addUsageTab($ilTabs); + + $ilCtrl->setParameterByClass( + "ilskillrootgui", + "obj_id", + $this->node_object->skill_tree->getRootId() + ); + $ilTabs->setBackTarget( + $lng->txt("obj_skmg"), + $ilCtrl->getLinkTargetByClass("ilskillrootgui", "listSkills") + ); + $ilCtrl->setParameterByClass( + "ilskillrootgui", + "obj_id", + $_GET["obj_id"] + ); + + $ilTabs->activateTab($a_tab); + + $tpl->setTitle($lng->txt("skmg_skill") . ": " . + $this->node_object->getTitle()); + + $this->setSkillNodeDescription(); + } else { + $tpl->setTitle($lng->txt("skmg_skill")); + $tpl->setDescription(""); + } + parent::setTitleIcon(); + } + + /** + * Edit level trigger + */ + public function editLevelTrigger() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + $this->setLevelHead(); + $ilTabs->activateTab("level_trigger"); + + $trigger = ilBasicSkill::lookupLevelTrigger((int) $_GET["level_id"]); + if (ilObject::_lookupType($trigger["obj_id"]) != "crs" || + ilObject::_isInTrash($trigger["ref_id"])) { + $trigger = array(); + } + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + // trigger + $ne = new ilNonEditableValueGUI($lng->txt("skmg_trigger"), "trigger"); + if ($trigger["obj_id"] > 0) { + $ne->setValue(ilObject::_lookupTitle($trigger["obj_id"])); + } else { + $ne->setValue($lng->txt("skmg_no_trigger")); + } + $this->form->addItem($ne); + + if ($trigger["obj_id"] > 0) { + $this->form->addCommandButton("removeLevelTrigger", $lng->txt("skmg_remove_trigger")); + } + $this->form->addCommandButton("selectLevelTrigger", $lng->txt("skmg_select_trigger")); + + $this->form->setTitle($lng->txt("skmg_skill_level_trigger")); + $this->form->setFormAction($ilCtrl->getFormAction($this)); + + $tpl->setContent($this->form->getHTML()); + } + + /** + * Select skill level trigger + */ + public function selectLevelTrigger() + { + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + $lng = $this->lng; + $tree = $this->tree; + $tpl = $this->tpl; + + if (!$this->checkPermissionBool("write")) { + return; + } + + $this->setLevelHead(); + $ilTabs->activateTab("level_trigger"); + + include_once 'Services/Search/classes/class.ilSearchRootSelector.php'; + $exp = new ilSearchRootSelector( + $ilCtrl->getLinkTarget($this, 'showRepositorySelection') + ); + $exp->setExpand($_GET["search_root_expand"] ? $_GET["search_root_expand"] : $tree->readRootId()); + $exp->setExpandTarget($ilCtrl->getLinkTarget($this, 'selectLevelTrigger')); + $exp->setTargetClass(get_class($this)); + $exp->setCmd('saveLevelTrigger'); + $exp->setClickableTypes(array("crs")); + + // build html-output + $exp->setOutput(0); + $tpl->setContent($exp->getOutput()); + } + + /** + * Save level trigger + */ + public function saveLevelTrigger() + { + $ilCtrl = $this->ctrl; + + if (!$this->checkPermissionBool("write")) { + return; + } + + ilBasicSkill::writeLevelTrigger((int) $_GET["level_id"], (int) $_GET["root_id"]); + $ilCtrl->redirect($this, "editLevelTrigger"); + } + + /** + * Remove trigger + */ + public function removeLevelTrigger() + { + $ilCtrl = $this->ctrl; + + ilBasicSkill::writeLevelTrigger((int) $_GET["level_id"], 0); + $ilCtrl->redirect($this, "editLevelTrigger"); + } + + /** + * Redirect to parent (identified by current obj_id) + */ + public function redirectToParent($a_tmp_mode = false) + { + $ilCtrl = $this->ctrl; + + $t = ilSkillTreeNode::_lookupType((int) $_GET["obj_id"]); + + switch ($t) { + case "skrt": + $ilCtrl->setParameterByClass("ilskillrootgui", "obj_id", (int) $_GET["obj_id"]); + $ilCtrl->redirectByClass("ilskillrootgui", "listSkills"); + break; + } + + parent::redirectToParent(); + } + + + //// + //// Level resources + //// + + /** + * Show level resources + */ + public function showLevelResources() + { + $tpl = $this->tpl; + $ilTabs = $this->tabs; + $ilToolbar = $this->toolbar; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if ($this->checkPermissionBool("write")) { + $ilToolbar->addButton( + $lng->txt("skmg_add_resource"), + $ilCtrl->getLinkTarget($this, "addLevelResource") + ); + } + + $this->setLevelHead(); + $ilTabs->activateTab("level_resources"); + + include_once("./Services/Skill/classes/class.ilSkillLevelResourcesTableGUI.php"); + $tab = new ilSkillLevelResourcesTableGUI( + $this, + "showLevelResources", + $this->base_skill_id, + $this->tref_id, + (int) $_GET["level_id"], + $this->checkPermissionBool("write") + ); + + $tpl->setContent($tab->getHTML()); + } + + /** + * Add level resource + */ + public function addLevelResource() + { + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + $lng = $this->lng; + $tree = $this->tree; + $tpl = $this->tpl; + + $this->setLevelHead(); + $ilTabs->activateTab("level_resources"); + + include_once("./Services/Repository/classes/class.ilRepositorySelectorExplorerGUI.php"); + $exp = new ilRepositorySelectorExplorerGUI( + $this, + "addLevelResource", + $this, + "saveLevelResource", + "root_id" + ); + if (!$exp->handleCommand()) { + $tpl->setContent($exp->getHTML()); + } + } + + /** + * Save level resource + */ + public function saveLevelResource() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $ref_id = (int) $_GET["root_id"]; + + if (!$this->checkPermissionBool("write")) { + return; + } + + if ($ref_id > 0) { + include_once("./Services/Skill/classes/class.ilSkillResources.php"); + $sres = new ilSkillResources($this->base_skill_id, $this->tref_id); + $sres->setResourceAsImparting((int) $_GET["level_id"], $ref_id); + $sres->save(); + + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + } + + $ilCtrl->redirect($this, "showLevelResources"); + } + + /** + * Confirm level resources removal + */ + public function confirmLevelResourcesRemoval() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + $ilTabs = $this->tabs; + + if (!$this->checkPermissionBool("write")) { + return; + } + + $this->setLevelHead(); + $ilTabs->activateTab("level_resources"); + + if (!is_array($_POST["id"]) || count($_POST["id"]) == 0) { + ilUtil::sendInfo($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "showLevelResources"); + } else { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("skmg_confirm_level_resources_removal")); + $cgui->setCancel($lng->txt("cancel"), "showLevelResources"); + $cgui->setConfirm($lng->txt("remove"), "removeLevelResources"); + + foreach ($_POST["id"] as $i) { + $title = ilObject::_lookupTitle(ilObject::_lookupObjId($i)); + $cgui->addItem("id[]", $i, $title); + } + + $tpl->setContent($cgui->getHTML()); + } + } + + /** + * Remove level resource + */ + public function removeLevelResources() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if (!$this->checkPermissionBool("write")) { + return; + } + + if (is_array($_POST["id"])) { + include_once("./Services/Skill/classes/class.ilSkillResources.php"); + $sres = new ilSkillResources($this->base_skill_id, $this->tref_id); + foreach ($_POST["id"] as $i) { + $sres->setResourceAsImparting((int) $_GET["level_id"], $i, false); + $sres->setResourceAsTrigger((int) $_GET["level_id"], $i, false); + } + $sres->save(); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + } + + $ilCtrl->redirect($this, "showLevelResources"); + } + + /** + * Save resource settings + * + * @param + * @return + */ + public function saveResourceSettings() + { + $ilCtrl = $this->ctrl; + + include_once("./Services/Skill/classes/class.ilSkillResources.php"); + $resources = new ilSkillResources($this->base_skill_id, $this->tref_id); + + foreach ($resources->getResourcesOfLevel((int) $_GET["level_id"]) as $r) { + $imparting = false; + if (is_array($_POST["suggested"]) && isset($_POST["suggested"][$r["rep_ref_id"]]) && $_POST["suggested"][$r["rep_ref_id"]]) { + $imparting = true; + } + $trigger = false; + if (is_array($_POST["trigger"]) && isset($_POST["trigger"][$r["rep_ref_id"]]) && $_POST["trigger"][$r["rep_ref_id"]]) { + $trigger = true; + } + $resources->setResourceAsImparting((int) $_GET["level_id"], $r["rep_ref_id"], $imparting); + $resources->setResourceAsTrigger((int) $_GET["level_id"], $r["rep_ref_id"], $trigger); + } + $resources->save(); + + $ilCtrl->redirect($this, "showLevelResources"); + } } -?> diff --git a/Services/Skill/classes/class.ilBasicSkillTemplate.php b/Services/Skill/classes/class.ilBasicSkillTemplate.php index a7211fcd8eee0d99721e3445cadb8ef2ec36e460..c0c67ce7fddf053559f5317c65d4fd6c1aa4e86a 100644 --- a/Services/Skill/classes/class.ilBasicSkillTemplate.php +++ b/Services/Skill/classes/class.ilBasicSkillTemplate.php @@ -14,40 +14,37 @@ include_once("./Services/Skill/classes/class.ilBasicSkill.php"); */ class ilBasicSkillTemplate extends ilBasicSkill { - var $id; + public $id; - /** - * Constructor - * @access public - */ - function __construct($a_id = 0) - { - parent::__construct($a_id); - $this->setType("sktp"); - } + /** + * Constructor + * @access public + */ + public function __construct($a_id = 0) + { + parent::__construct($a_id); + $this->setType("sktp"); + } - /** - * Copy basic skill template - */ - function copy() - { - $skill = new ilBasicSkillTemplate(); - $skill->setTitle($this->getTitle()); - $skill->setType($this->getType()); - $skill->setOrderNr($this->getOrderNr()); - $skill->create(); + /** + * Copy basic skill template + */ + public function copy() + { + $skill = new ilBasicSkillTemplate(); + $skill->setTitle($this->getTitle()); + $skill->setType($this->getType()); + $skill->setOrderNr($this->getOrderNr()); + $skill->create(); - $levels = $this->getLevelData(); - if (sizeof($levels)) - { - foreach($levels as $item) - { - $skill->addLevel($item["title"], $item["description"]); - } - } - $skill->update(); + $levels = $this->getLevelData(); + if (sizeof($levels)) { + foreach ($levels as $item) { + $skill->addLevel($item["title"], $item["description"]); + } + } + $skill->update(); - return $skill; - } + return $skill; + } } -?> diff --git a/Services/Skill/classes/class.ilBasicSkillTemplateGUI.php b/Services/Skill/classes/class.ilBasicSkillTemplateGUI.php index 41c2e05dab653a97a2dc976d64aaa4f9498abafa..0a9c23d04fecfc15bc505c3697d1e5301e34f3e1 100644 --- a/Services/Skill/classes/class.ilBasicSkillTemplateGUI.php +++ b/Services/Skill/classes/class.ilBasicSkillTemplateGUI.php @@ -16,358 +16,350 @@ include_once("./Services/Skill/classes/class.ilBasicSkillGUI.php"); */ class ilBasicSkillTemplateGUI extends ilBasicSkillGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilHelpGUI - */ - protected $help; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - - /** - * Constructor - */ - function __construct($a_node_id = 0, $a_tref_id = 0) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->tabs = $DIC->tabs(); - $this->tpl = $DIC["tpl"]; - $this->help = $DIC["ilHelp"]; - $this->toolbar = $DIC->toolbar(); - $ilCtrl = $DIC->ctrl(); - - $this->tref_id = $a_tref_id; - - $ilCtrl->saveParameter($this, array("obj_id", "level_id")); - - parent::__construct($a_node_id); - } - - /** - * Get Node Type - */ - function getType() - { - return "sktp"; - } - - /** - * Init form. - * - * @param string $a_mode edit mode - */ - public function initForm($a_mode = "edit") - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - // title - $ti = new ilTextInputGUI($lng->txt("title"), "title"); - $ti->setMaxLength(200); - $ti->setSize(50); - $ti->setRequired(true); - $this->form->addItem($ti); - - // order nr - $ni = new ilNumberInputGUI($lng->txt("skmg_order_nr"), "order_nr"); - $ni->setInfo($lng->txt("skmg_order_nr_info")); - $ni->setMaxLength(6); - $ni->setSize(6); - $ni->setRequired(true); - if ($a_mode == "create") - { - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $tree = new ilSkillTree(); - $max = $tree->getMaxOrderNr((int)$_GET["obj_id"], true); - $ni->setValue($max + 10); - } - $this->form->addItem($ni); - - // save and cancel commands - if ($this->checkPermissionBool("write")) - { - if ($a_mode == "create") - { - $this->form->addCommandButton("save", $lng->txt("save")); - $this->form->addCommandButton("cancelSave", $lng->txt("cancel")); - $this->form->setTitle($lng->txt("skmg_create_skll")); - } else - { - $this->form->addCommandButton("update", $lng->txt("save")); - $this->form->setTitle($lng->txt("skmg_edit_skll")); - } - } - - $ilCtrl->setParameter($this, "obj_id", $_GET["obj_id"]); - $this->form->setFormAction($ilCtrl->getFormAction($this)); - } - - /** - * Set header for level - */ - function setLevelHead() - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - $ilHelp = $this->help; - - // tabs - $ilTabs->clearTargets(); - $ilHelp->setScreenIdComponent("skmg_lev"); - $ilTabs->setBackTarget($lng->txt("skmg_skill_levels"), - $ilCtrl->getLinkTarget($this, "edit")); - - if ($_GET["level_id"] > 0) - { - if ($this->tref_id == 0) - { - $ilTabs->addTab("level_settings", - $lng->txt("settings"), - $ilCtrl->getLinkTarget($this, "editLevel")); - } - else - { - $ilTabs->addTab("level_resources", - $lng->txt("skmg_resources"), - $ilCtrl->getLinkTarget($this, "showLevelResources")); - } - -/* $ilTabs->addTab("level_trigger", - $lng->txt("skmg_trigger"), - $ilCtrl->getLinkTarget($this, "editLevelTrigger")); - - $ilTabs->addTab("level_certificate", - $lng->txt("certificate"), - $ilCtrl->getLinkTargetByClass("ilcertificategui", "certificateEditor"));*/ - } - - // title - if ($_GET["level_id"] > 0) - { - $tpl->setTitle($lng->txt("skmg_skill_level").": ". - ilBasicSkill::lookupLevelTitle((int) $_GET["level_id"])); - } - else - { - $tpl->setTitle($lng->txt("skmg_skill_level")); - } - - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $tree = new ilSkillTree(); - $path = $tree->getPathFull($this->node_object->getId()); - $desc = ""; - foreach ($path as $p) - { - if (in_array($p["type"], array("scat", "skll"))) - { - $desc.= $sep.$p["title"]; - $sep = " > "; - } - } - $tpl->setDescription($desc); - - $tpl->setTitleIcon( - ilSkillTreeNode::getIconPath( - 0, "sktp", "", false)); - - } - - /** - * Set header for skill - * - * @param - * @return - */ - function setTabs($a_tab = "") - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - $ilHelp = $this->help; - - $ilTabs->clearTargets(); - $ilHelp->setScreenIdComponent("skmg_sktp"); - - if ($this->tref_id == 0) - { - $ilTabs->setBackTarget($lng->txt("skmg_skill_templates"), - $ilCtrl->getLinkTargetByClass("ilobjskillmanagementgui", "editSkillTemplates")); - } - - if (is_object($this->node_object)) - { - if ($this->tref_id == 0) - { - $tpl->setTitle($lng->txt("skmg_skill_template").": ". - $this->node_object->getTitle()); - } - else - { - $tpl->setTitle( - $this->node_object->getTitle()); - } - - // levels - $ilTabs->addTab("levels", $lng->txt("skmg_skill_levels"), - $ilCtrl->getLinkTarget($this, 'edit')); - - // properties - if ($this->tref_id == 0) - { - $ilTabs->addTab("properties", $lng->txt("settings"), - $ilCtrl->getLinkTarget($this, 'editProperties')); - } - - // if ($this->tref_id > 0) -// { - // usage - $this->addUsageTab($ilTabs); -// } - - $ilTabs->activateTab($a_tab); - - parent::setTitleIcon(); - - $this->setSkillNodeDescription(); - } - else - { - $tpl->setTitle($lng->txt("skmg_skill")); - $tpl->setDescription(""); - } - } - - /** - * Save item - */ - function saveItem() - { - if (!$this->checkPermissionBool("write")) - { - return; - } - - $it = new ilBasicSkillTemplate(); - $it->setTitle($this->form->getInput("title")); - $it->setOrderNr($this->form->getInput("order_nr")); - $it->create(); - ilSkillTreeNode::putInTree($it, (int) $_GET["obj_id"], IL_LAST_NODE); - $this->node_object = $it; - } - - /** - * After saving - */ - function afterSave() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameterByClass("ilbasicskilltemplategui", "obj_id", - $this->node_object->getId()); - $ilCtrl->redirectByClass("ilbasicskilltemplategui", "edit"); - } - - /** - * Edit skill - * - * @param - * @return - */ - function edit() - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->setTabs("levels"); - - if ($this->isInUse()) - { - ilUtil::sendInfo($lng->txt("skmg_skill_in_use")); - } - else - { - - if ($this->checkPermissionBool("write")) - { - if ($this->tref_id == 0) - { - $ilToolbar->addButton($lng->txt("skmg_add_level"), - $ilCtrl->getLinkTarget($this, "addLevel")); - } - } - } - - include_once("./Services/Skill/classes/class.ilSkillLevelTableGUI.php"); - $table = new ilSkillLevelTableGUI((int) $_GET["obj_id"], $this, "edit", $this->tref_id, $this->isInUse()); - $tpl->setContent($table->getHTML()); - } - - /** - * Show skill usage - */ - function showUsage() - { - $tpl = $this->tpl; - - - // (a) referenced skill template in main tree - if ($this->tref_id > 0) - { - return parent::showUsage(); - } - - // (b) skill template in templates view - - $this->setTabs("usage"); - - include_once("./Services/Skill/classes/class.ilSkillUsage.php"); - $usage_info = new ilSkillUsage(); - $usages = $usage_info->getAllUsagesOfTemplate($this->base_skill_id); - - $html = ""; - include_once("./Services/Skill/classes/class.ilSkillUsageTableGUI.php"); - foreach ($usages as $k => $usage) - { - $tab = new ilSkillUsageTableGUI($this, "showUsage", $k, $usage); - $html.= $tab->getHTML()."

                  "; - } - - $tpl->setContent($html); - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + + /** + * Constructor + */ + public function __construct($a_node_id = 0, $a_tref_id = 0) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->tabs = $DIC->tabs(); + $this->tpl = $DIC["tpl"]; + $this->help = $DIC["ilHelp"]; + $this->toolbar = $DIC->toolbar(); + $ilCtrl = $DIC->ctrl(); + + $this->tref_id = $a_tref_id; + + $ilCtrl->saveParameter($this, array("obj_id", "level_id")); + + parent::__construct($a_node_id); + } + + /** + * Get Node Type + */ + public function getType() + { + return "sktp"; + } + + /** + * Init form. + * + * @param string $a_mode edit mode + */ + public function initForm($a_mode = "edit") + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + // title + $ti = new ilTextInputGUI($lng->txt("title"), "title"); + $ti->setMaxLength(200); + $ti->setSize(50); + $ti->setRequired(true); + $this->form->addItem($ti); + + // order nr + $ni = new ilNumberInputGUI($lng->txt("skmg_order_nr"), "order_nr"); + $ni->setInfo($lng->txt("skmg_order_nr_info")); + $ni->setMaxLength(6); + $ni->setSize(6); + $ni->setRequired(true); + if ($a_mode == "create") { + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $tree = new ilSkillTree(); + $max = $tree->getMaxOrderNr((int) $_GET["obj_id"], true); + $ni->setValue($max + 10); + } + $this->form->addItem($ni); + + // save and cancel commands + if ($this->checkPermissionBool("write")) { + if ($a_mode == "create") { + $this->form->addCommandButton("save", $lng->txt("save")); + $this->form->addCommandButton("cancelSave", $lng->txt("cancel")); + $this->form->setTitle($lng->txt("skmg_create_skll")); + } else { + $this->form->addCommandButton("update", $lng->txt("save")); + $this->form->setTitle($lng->txt("skmg_edit_skll")); + } + } + + $ilCtrl->setParameter($this, "obj_id", $_GET["obj_id"]); + $this->form->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * Set header for level + */ + public function setLevelHead() + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + $ilHelp = $this->help; + + // tabs + $ilTabs->clearTargets(); + $ilHelp->setScreenIdComponent("skmg_lev"); + $ilTabs->setBackTarget( + $lng->txt("skmg_skill_levels"), + $ilCtrl->getLinkTarget($this, "edit") + ); + + if ($_GET["level_id"] > 0) { + if ($this->tref_id == 0) { + $ilTabs->addTab( + "level_settings", + $lng->txt("settings"), + $ilCtrl->getLinkTarget($this, "editLevel") + ); + } else { + $ilTabs->addTab( + "level_resources", + $lng->txt("skmg_resources"), + $ilCtrl->getLinkTarget($this, "showLevelResources") + ); + } + + /* $ilTabs->addTab("level_trigger", + $lng->txt("skmg_trigger"), + $ilCtrl->getLinkTarget($this, "editLevelTrigger")); + + $ilTabs->addTab("level_certificate", + $lng->txt("certificate"), + $ilCtrl->getLinkTargetByClass("ilcertificategui", "certificateEditor"));*/ + } + + // title + if ($_GET["level_id"] > 0) { + $tpl->setTitle($lng->txt("skmg_skill_level") . ": " . + ilBasicSkill::lookupLevelTitle((int) $_GET["level_id"])); + } else { + $tpl->setTitle($lng->txt("skmg_skill_level")); + } + + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $tree = new ilSkillTree(); + $path = $tree->getPathFull($this->node_object->getId()); + $desc = ""; + foreach ($path as $p) { + if (in_array($p["type"], array("scat", "skll"))) { + $desc.= $sep . $p["title"]; + $sep = " > "; + } + } + $tpl->setDescription($desc); + + $tpl->setTitleIcon( + ilSkillTreeNode::getIconPath( + 0, + "sktp", + "", + false + ) + ); + } + + /** + * Set header for skill + * + * @param + * @return + */ + public function setTabs($a_tab = "") + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + $ilHelp = $this->help; + + $ilTabs->clearTargets(); + $ilHelp->setScreenIdComponent("skmg_sktp"); + + if ($this->tref_id == 0) { + $ilTabs->setBackTarget( + $lng->txt("skmg_skill_templates"), + $ilCtrl->getLinkTargetByClass("ilobjskillmanagementgui", "editSkillTemplates") + ); + } + + if (is_object($this->node_object)) { + if ($this->tref_id == 0) { + $tpl->setTitle($lng->txt("skmg_skill_template") . ": " . + $this->node_object->getTitle()); + } else { + $tpl->setTitle( + $this->node_object->getTitle() + ); + } + + // levels + $ilTabs->addTab( + "levels", + $lng->txt("skmg_skill_levels"), + $ilCtrl->getLinkTarget($this, 'edit') + ); + + // properties + if ($this->tref_id == 0) { + $ilTabs->addTab( + "properties", + $lng->txt("settings"), + $ilCtrl->getLinkTarget($this, 'editProperties') + ); + } + + // if ($this->tref_id > 0) + // { + // usage + $this->addUsageTab($ilTabs); + // } + + $ilTabs->activateTab($a_tab); + + parent::setTitleIcon(); + + $this->setSkillNodeDescription(); + } else { + $tpl->setTitle($lng->txt("skmg_skill")); + $tpl->setDescription(""); + } + } + + /** + * Save item + */ + public function saveItem() + { + if (!$this->checkPermissionBool("write")) { + return; + } + + $it = new ilBasicSkillTemplate(); + $it->setTitle($this->form->getInput("title")); + $it->setOrderNr($this->form->getInput("order_nr")); + $it->create(); + ilSkillTreeNode::putInTree($it, (int) $_GET["obj_id"], IL_LAST_NODE); + $this->node_object = $it; + } + + /** + * After saving + */ + public function afterSave() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameterByClass( + "ilbasicskilltemplategui", + "obj_id", + $this->node_object->getId() + ); + $ilCtrl->redirectByClass("ilbasicskilltemplategui", "edit"); + } + + /** + * Edit skill + * + * @param + * @return + */ + public function edit() + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $this->setTabs("levels"); + + if ($this->isInUse()) { + ilUtil::sendInfo($lng->txt("skmg_skill_in_use")); + } else { + if ($this->checkPermissionBool("write")) { + if ($this->tref_id == 0) { + $ilToolbar->addButton( + $lng->txt("skmg_add_level"), + $ilCtrl->getLinkTarget($this, "addLevel") + ); + } + } + } + + include_once("./Services/Skill/classes/class.ilSkillLevelTableGUI.php"); + $table = new ilSkillLevelTableGUI((int) $_GET["obj_id"], $this, "edit", $this->tref_id, $this->isInUse()); + $tpl->setContent($table->getHTML()); + } + + /** + * Show skill usage + */ + public function showUsage() + { + $tpl = $this->tpl; + + + // (a) referenced skill template in main tree + if ($this->tref_id > 0) { + return parent::showUsage(); + } + + // (b) skill template in templates view + + $this->setTabs("usage"); + + include_once("./Services/Skill/classes/class.ilSkillUsage.php"); + $usage_info = new ilSkillUsage(); + $usages = $usage_info->getAllUsagesOfTemplate($this->base_skill_id); + + $html = ""; + include_once("./Services/Skill/classes/class.ilSkillUsageTableGUI.php"); + foreach ($usages as $k => $usage) { + $tab = new ilSkillUsageTableGUI($this, "showUsage", $k, $usage); + $html.= $tab->getHTML() . "

                  "; + } + + $tpl->setContent($html); + } } -?> diff --git a/Services/Skill/classes/class.ilObjSkillManagement.php b/Services/Skill/classes/class.ilObjSkillManagement.php index 1d63ab88545df9ee1d748cf5939deb8398a052a6..854376c913f3706ef7f2491577fc80e50872f33e 100644 --- a/Services/Skill/classes/class.ilObjSkillManagement.php +++ b/Services/Skill/classes/class.ilObjSkillManagement.php @@ -14,194 +14,168 @@ require_once "./Services/Object/classes/class.ilObject.php"; */ class ilObjSkillManagement extends ilObject { - - /** - * Constructor - * @access public - * @param integer reference_id or object_id - * @param boolean treat the id as reference_id (true) or object_id (false) - */ - function __construct($a_id = 0,$a_call_by_reference = true) - { - global $DIC; - - $this->db = $DIC->database(); - $this->type = "skmg"; - parent::__construct($a_id,$a_call_by_reference); - } - - /** - * update object data - * - * @access public - * @return boolean - */ - function update() - { - $ilDB = $this->db; - - if (!parent::update()) - { - return false; - } - - return true; - } - - /** - * read style folder data - */ - function read() - { - $ilDB = $this->db; - - parent::read(); - - } - - /** - * delete object and all related data - * - * @access public - * @return boolean true if all object data were removed; false if only a references were removed - */ - function delete() - { - // always call parent delete function first!! - if (!parent::delete()) - { - return false; - } - - //put here your module specific stuff - - return true; - } - - /** - * Execute Drag Drop Action - * - * @param string $source_id Source element ID - * @param string $target_id Target element ID - * @param string $first_child Insert as first child of target - * @param string $movecopy Position ("move" | "copy") - */ - function executeDragDrop($source_id, $target_id, $first_child, $as_subitem = false, $movecopy = "move") - { - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $tree = new ilSkillTree(); - - include_once("./Services/Skill/classes/class.ilSkillTreeNodeFactory.php"); - - $source_obj = ilSkillTreeNodeFactory::getInstance($source_id); - - if (!$first_child) - { - $target_obj = ilSkillTreeNodeFactory::getInstance($target_id); - $target_parent = $tree->getParentId($target_id); - } - // handle skills - if ($source_obj->getType() == "skll") - { - if ($tree->isInTree($source_obj->getId())) - { - $node_data = $tree->getNodeData($source_obj->getId()); - - // cut on move - if ($movecopy == "move") - { - $parent_id = $tree->getParentId($source_obj->getId()); - $tree->deleteTree($node_data); - - } - - // paste page - if(!$tree->isInTree($source_obj->getId())) - { - if ($first_child) // as first child - { - $target_pos = IL_FIRST_NODE; - $parent = $target_id; - } - else if ($as_subitem) // as last child - { - $parent = $target_id; - $target_pos = IL_FIRST_NODE; - $childs = $tree->getChildsByType($parent, array("skll", "scat")); - if (count($childs) != 0) - { - $target_pos = $childs[count($childs) - 1]["obj_id"]; - } - } - else // at position - { - $target_pos = $target_id; - $parent = $target_parent; - } - // insert skill into tree - $tree->insertNode($source_obj->getId(), - $parent, $target_pos); - } - } - } - - // handle skil categories - if ($source_obj->getType() == "scat") - { - $source_node = $tree->getNodeData($source_id); - $subnodes = $tree->getSubtree($source_node); - - // check, if target is within subtree - foreach ($subnodes as $subnode) - { - if($subnode["obj_id"] == $target_id) - { - return; - } - } - - $target_pos = $target_id; - - if ($first_child) // as first node - { - $target_pos = IL_FIRST_NODE; - $target_parent = $target_id; - } - else if ($as_subitem) // as last node - { - $target_parent = $target_id; - $target_pos = IL_FIRST_NODE; - $childs = $tree->getChilds($target_parent); - if (count($childs) != 0) - { - $target_pos = $childs[count($childs) - 1]["obj_id"]; - } - } - - // delete source tree - if ($movecopy == "move") - { - $tree->deleteTree($source_node); - } - - if (!$tree->isInTree($source_id)) - { - $tree->insertNode($source_id, $target_parent, $target_pos); - - // insert moved tree - if ($movecopy == "move") - { - foreach ($subnodes as $node) - { - if($node["obj_id"] != $source_id) - { - $tree->insertNode($node["obj_id"], $node["parent"]); - } - } - } - } - } - - } + + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id = 0, $a_call_by_reference = true) + { + global $DIC; + + $this->db = $DIC->database(); + $this->type = "skmg"; + parent::__construct($a_id, $a_call_by_reference); + } + + /** + * update object data + * + * @access public + * @return boolean + */ + public function update() + { + $ilDB = $this->db; + + if (!parent::update()) { + return false; + } + + return true; + } + + /** + * read style folder data + */ + public function read() + { + $ilDB = $this->db; + + parent::read(); + } + + /** + * delete object and all related data + * + * @access public + * @return boolean true if all object data were removed; false if only a references were removed + */ + public function delete() + { + // always call parent delete function first!! + if (!parent::delete()) { + return false; + } + + //put here your module specific stuff + + return true; + } + + /** + * Execute Drag Drop Action + * + * @param string $source_id Source element ID + * @param string $target_id Target element ID + * @param string $first_child Insert as first child of target + * @param string $movecopy Position ("move" | "copy") + */ + public function executeDragDrop($source_id, $target_id, $first_child, $as_subitem = false, $movecopy = "move") + { + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $tree = new ilSkillTree(); + + include_once("./Services/Skill/classes/class.ilSkillTreeNodeFactory.php"); + + $source_obj = ilSkillTreeNodeFactory::getInstance($source_id); + + if (!$first_child) { + $target_obj = ilSkillTreeNodeFactory::getInstance($target_id); + $target_parent = $tree->getParentId($target_id); + } + // handle skills + if ($source_obj->getType() == "skll") { + if ($tree->isInTree($source_obj->getId())) { + $node_data = $tree->getNodeData($source_obj->getId()); + + // cut on move + if ($movecopy == "move") { + $parent_id = $tree->getParentId($source_obj->getId()); + $tree->deleteTree($node_data); + } + + // paste page + if (!$tree->isInTree($source_obj->getId())) { + if ($first_child) { // as first child + $target_pos = IL_FIRST_NODE; + $parent = $target_id; + } elseif ($as_subitem) { // as last child + $parent = $target_id; + $target_pos = IL_FIRST_NODE; + $childs = $tree->getChildsByType($parent, array("skll", "scat")); + if (count($childs) != 0) { + $target_pos = $childs[count($childs) - 1]["obj_id"]; + } + } else { // at position + $target_pos = $target_id; + $parent = $target_parent; + } + // insert skill into tree + $tree->insertNode( + $source_obj->getId(), + $parent, + $target_pos + ); + } + } + } + + // handle skil categories + if ($source_obj->getType() == "scat") { + $source_node = $tree->getNodeData($source_id); + $subnodes = $tree->getSubtree($source_node); + + // check, if target is within subtree + foreach ($subnodes as $subnode) { + if ($subnode["obj_id"] == $target_id) { + return; + } + } + + $target_pos = $target_id; + + if ($first_child) { // as first node + $target_pos = IL_FIRST_NODE; + $target_parent = $target_id; + } elseif ($as_subitem) { // as last node + $target_parent = $target_id; + $target_pos = IL_FIRST_NODE; + $childs = $tree->getChilds($target_parent); + if (count($childs) != 0) { + $target_pos = $childs[count($childs) - 1]["obj_id"]; + } + } + + // delete source tree + if ($movecopy == "move") { + $tree->deleteTree($source_node); + } + + if (!$tree->isInTree($source_id)) { + $tree->insertNode($source_id, $target_parent, $target_pos); + + // insert moved tree + if ($movecopy == "move") { + foreach ($subnodes as $node) { + if ($node["obj_id"] != $source_id) { + $tree->insertNode($node["obj_id"], $node["parent"]); + } + } + } + } + } + } } -?> diff --git a/Services/Skill/classes/class.ilObjSkillManagementAccess.php b/Services/Skill/classes/class.ilObjSkillManagementAccess.php index bfc485df528d86ba247fdd224f5b2f2896b2a756..e338cea8022be87d93373b0e3cc26095beae138a 100644 --- a/Services/Skill/classes/class.ilObjSkillManagementAccess.php +++ b/Services/Skill/classes/class.ilObjSkillManagementAccess.php @@ -14,8 +14,4 @@ include_once("./Services/Object/classes/class.ilObjectAccess.php"); */ class ilObjSkillManagementAccess extends ilObjectAccess { - - } - -?> diff --git a/Services/Skill/classes/class.ilObjSkillManagementGUI.php b/Services/Skill/classes/class.ilObjSkillManagementGUI.php index 35b85a03182afbcba11fb34bc2e3aa78de355495..16fdd692a76ca2af1b4f80451c206a0295238568 100644 --- a/Services/Skill/classes/class.ilObjSkillManagementGUI.php +++ b/Services/Skill/classes/class.ilObjSkillManagementGUI.php @@ -17,897 +17,857 @@ include_once("./Services/Object/classes/class.ilObjectGUI.php"); */ class ilObjSkillManagementGUI extends ilObjectGUI { - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - protected $skill_tree; - - /** - * Contructor - * - * @access public - */ - public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->error = $DIC["ilErr"]; - $this->access = $DIC->access(); - $this->tabs = $DIC->tabs(); - $this->lng = $DIC->language(); - $this->settings = $DIC->settings(); - $this->tpl = $DIC["tpl"]; - $this->toolbar = $DIC->toolbar(); - $this->user = $DIC->user(); - $ilCtrl = $DIC->ctrl(); - - $this->type = 'skmg'; - parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); - - $this->lng->loadLanguageModule('skmg'); - - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $this->skill_tree = new ilSkillTree(); - - $ilCtrl->saveParameter($this, "obj_id"); - } - - /** - * Execute command - * - * @access public - * - */ - public function executeCommand() - { - $rbacsystem = $this->rbacsystem; - $ilErr = $this->error; - $ilAccess = $this->access; - $ilTabs = $this->tabs; - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd(); - - $this->prepareOutput(); - - if(!$ilAccess->checkAccess('read','',$this->object->getRefId())) - { - $ilErr->raiseError($this->lng->txt('no_permission'),$ilErr->WARNING); - } - - switch($next_class) - { - case 'ilskillrootgui': - include_once("./Services/Skill/classes/class.ilSkillRootGUI.php"); - $skrt_gui = new ilSkillRootGUI((int) $_GET["obj_id"], $this); - $skrt_gui->setParentGUI($this); - $ret = $this->ctrl->forwardCommand($skrt_gui); - break; - - case 'ilskillcategorygui': - $this->tabs_gui->activateTab("skills"); - include_once("./Services/Skill/classes/class.ilSkillCategoryGUI.php"); - $scat_gui = new ilSkillCategoryGUI((int) $_GET["obj_id"]); - $scat_gui->setParentGUI($this); - $this->showTree(false, $scat_gui, "listItems"); - $ret = $this->ctrl->forwardCommand($scat_gui); - break; - - case 'ilbasicskillgui': - $this->tabs_gui->activateTab("skills"); - include_once("./Services/Skill/classes/class.ilBasicSkillGUI.php"); - $skill_gui = new ilBasicSkillGUI((int) $_GET["obj_id"]); - $skill_gui->setParentGUI($this); - $this->showTree(false, $skill_gui, "edit"); - $ret = $this->ctrl->forwardCommand($skill_gui); - break; - - case 'ilskilltemplatecategorygui': - $this->tabs_gui->activateTab("skill_templates"); - include_once("./Services/Skill/classes/class.ilSkillTemplateCategoryGUI.php"); - $sctp_gui = new ilSkillTemplateCategoryGUI((int) $_GET["obj_id"], (int) $_GET["tref_id"]); - $sctp_gui->setParentGUI($this); - $this->showTree(((int) $_GET["tref_id"] == 0), $sctp_gui, "listItems"); - $ret = $this->ctrl->forwardCommand($sctp_gui); - break; - - case 'ilbasicskilltemplategui': - $this->tabs_gui->activateTab("skill_templates"); - include_once("./Services/Skill/classes/class.ilBasicSkillTemplateGUI.php"); - $sktp_gui = new ilBasicSkillTemplateGUI((int) $_GET["obj_id"], (int) $_GET["tref_id"]); - $sktp_gui->setParentGUI($this); - $this->showTree(((int) $_GET["tref_id"] == 0), $sktp_gui, "edit"); - $ret = $this->ctrl->forwardCommand($sktp_gui); - break; - - case 'ilskilltemplatereferencegui': - $this->tabs_gui->activateTab("skills"); - include_once("./Services/Skill/classes/class.ilSkillTemplateReferenceGUI.php"); - $sktr_gui = new ilSkillTemplateReferenceGUI((int) $_GET["tref_id"]); - $sktr_gui->setParentGUI($this); - $this->showTree(false, $sktr_gui, "listItems"); - $ret = $this->ctrl->forwardCommand($sktr_gui); - break; - - case "ilskillprofilegui": - $ilTabs->activateTab("profiles"); - include_once("./Services/Skill/classes/class.ilSkillProfileGUI.php"); - $skprof_gui = new ilSkillProfileGUI(); - $ret = $this->ctrl->forwardCommand($skprof_gui); - break; - - case 'ilpermissiongui': - $this->tabs_gui->activateTab('permissions'); - include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); - $perm_gui = new ilPermissionGUI($this); - $ret = $this->ctrl->forwardCommand($perm_gui); - break; - - case "ilexportgui": - $this->tabs_gui->activateTab('export'); - include_once("./Services/Export/classes/class.ilExportGUI.php"); - $exp_gui = new ilExportGUI($this); - $exp_gui->addFormat("xml"); - //$exp_gui->addFormat("html", "", $this, "exportHTML"); - $ret = $this->ctrl->forwardCommand($exp_gui); - break; - - default: - if(!$cmd || $cmd == 'view') - { - $cmd = "editSkills"; - } - - if ($cmd == "showTree") - { - $this->showTree($_GET["templates_tree"]); - } - else - { - $this->$cmd(); - } - break; - } - return true; - } - - /** - * Get tabs - * - * @access public - * - */ - public function getAdminTabs() - { - $rbacsystem = $this->rbacsystem; - $ilAccess = $this->access; - $lng = $this->lng; - - if ($rbacsystem->checkAccess("visible,read",$this->object->getRefId())) - { - $this->tabs_gui->addTab("skills", - $lng->txt("skmg_skills"), - $this->ctrl->getLinkTarget($this, "editSkills")); - - $this->tabs_gui->addTab("skill_templates", - $lng->txt("skmg_skill_templates"), - $this->ctrl->getLinkTarget($this, "editSkillTemplates")); - - $this->tabs_gui->addTab("settings", - $lng->txt("settings"), - $this->ctrl->getLinkTarget($this, "editSettings")); - - $this->tabs_gui->addTab("profiles", - $lng->txt("skmg_skill_profiles"), - $this->ctrl->getLinkTargetByClass("ilskillprofilegui")); - - if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) - { - $this->tabs_gui->addTab("export", - $lng->txt("export"), - $this->ctrl->getLinkTargetByClass("ilexportgui", "")); - } - - if (DEVMODE == 1) - { - $this->tabs_gui->addTab("test", - "Test (DEVMODE)", - $this->ctrl->getLinkTarget($this, "test")); - } - } - - if ($rbacsystem->checkAccess('edit_permission',$this->object->getRefId())) - { - $this->tabs_gui->addTab("permissions", - $lng->txt("perm_settings"), - $this->ctrl->getLinkTargetByClass('ilpermissiongui',"perm")); - } - } - - /** - * Edit news settings. - */ - public function editSettings() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilSetting = $this->settings; - $ilTabs = $this->tabs; - - $ilTabs->activateTab("settings"); - - include_once("./Services/Skill/classes/class.ilSkillManagementSettings.php"); - $skmg_set = new ilSkillManagementSettings(); - $enable_skmg = $skmg_set->isActivated(); - - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this)); - $form->setTitle($lng->txt("skmg_settings")); - - // Enable skill management - $cb_prop = new ilCheckboxInputGUI($lng->txt("skmg_enable_skmg"), - "enable_skmg"); - $cb_prop->setValue("1"); - $cb_prop->setChecked($enable_skmg); - $form->addItem($cb_prop); - - // Hide Competence Profile Data before Self-Assessment - $cb_prop = new ilCheckboxInputGUI($lng->txt("skmg_hide_profile_self_eval"), - "hide_profile_self_eval"); - $cb_prop->setValue("1"); - $cb_prop->setInfo($lng->txt("skmg_hide_profile_self_eval_info")); - $cb_prop->setChecked($skmg_set->getHideProfileBeforeSelfEval()); - $form->addItem($cb_prop); - - // command buttons - if ($this->checkPermissionBool("write")) - { - $form->addCommandButton("saveSettings", $lng->txt("save")); - } - - $this->tpl->setContent($form->getHTML()); - } - - /** - * Save skill management settings - */ - public function saveSettings() - { - $ilCtrl = $this->ctrl; - $ilSetting = $this->settings; - - if (!$this->checkPermissionBool("write")) - { - return; - } - - include_once("./Services/Skill/classes/class.ilSkillManagementSettings.php"); - $skmg_set = new ilSkillManagementSettings(); - $skmg_set->activate((int) $_POST["enable_skmg"]); - $skmg_set->setHideProfileBeforeSelfEval((int) $_POST["hide_profile_self_eval"]); - - ilUtil::sendSuccess($this->lng->txt("settings_saved"),true); - - $ilCtrl->redirect($this, "editSettings"); - } - - /** - * Edit skills - */ - function editSkills() - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $ilTabs->activateTab("skills"); - - $ilCtrl->setParameterByClass("ilobjskillmanagementgui", "obj_id", $this->skill_tree->getRootId()); - $ilCtrl->redirectByClass("ilskillrootgui", "listSkills"); - - } - - - /** - * Save all titles of chapters/scos/pages - */ - function saveAllTitles($a_succ_mess = true) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if (is_array($_POST["title"])) - { - include_once("./Services/Skill/classes/class.ilSkillTreeNodeFactory.php"); - foreach($_POST["title"] as $id => $title) - { - $node_obj = ilSkillTreeNodeFactory::getInstance($id); - if (is_object($node_obj)) - { - // update title - ilSkillTreeNode::_writeTitle($id, ilUtil::stripSlashes($title)); - } - } - if ($a_succ_mess) - { - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - } - } - $ilCtrl->redirect($this, "editSkills"); - } - - /** - * Save all titles of chapters/scos/pages - */ - function saveAllTemplateTitles($a_succ_mess = true) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if (is_array($_POST["title"])) - { - include_once("./Services/Skill/classes/class.ilSkillTreeNodeFactory.php"); - foreach($_POST["title"] as $id => $title) - { - $node_obj = ilSkillTreeNodeFactory::getInstance($id); - if (is_object($node_obj)) - { - // update title - ilSkillTreeNode::_writeTitle($id, ilUtil::stripSlashes($title)); - } - } - if ($a_succ_mess) - { - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - } - } - $ilCtrl->redirect($this, "editSkillTemplates"); - } - - - /** - * Expand all - */ - function expandAll($a_redirect = true) - { - $_GET["skexpand"] = ""; - $n_id = ($_GET["obj_id"] > 0) - ? $_GET["obj_id"] - : $this->skill_tree->readRootId(); - $stree = $this->skill_tree->getSubTree($this->skill_tree->getNodeData($n_id)); - $n_arr = array(); - foreach ($stree as $n) - { - $n_arr[] = $n["child"]; - $_SESSION["skexpand"] = $n_arr; - } - $this->saveAllTitles(false); - } - - /** - * Collapse all - */ - function collapseAll($a_redirect = true) - { - $_GET["skexpand"] = ""; - $n_id = ($_GET["obj_id"] > 0) - ? $_GET["obj_id"] - : $this->skill_tree->readRootId(); - $stree = $this->skill_tree->getSubTree($this->skill_tree->getNodeData($n_id)); - $old = $_SESSION["skexpand"]; - foreach ($stree as $n) - { - if (in_array($n["child"], $old) && $n["child"] != $n_id) - { - $k = array_search($n["child"], $old); - unset($old[$k]); - } - } - $_SESSION["skexpand"] = $old; - $this->saveAllTitles(false); - } - - /** - * confirm deletion screen of skill tree nodes - */ - function deleteNodes($a_gui) - { - $lng = $this->lng; - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - $ilToolbar = $this->toolbar; - - if(!isset($_POST["id"])) - { - $this->ilias->raiseError($this->lng->txt("no_checkbox"),$this->ilias->error_obj->MESSAGE); - } - - $ilTabs->clearTargets(); - - // check usages - $mode = ""; - $cskill_ids = array(); - foreach($_POST["id"] as $id) - { - if (in_array(ilSkillTreeNode::_lookupType($id), array("skll", "scat", "sktr"))) - { - if ($mode == "templates") - { - $this->ilias->raiseError("Skill Deletion - type mismatch.",$this->ilias->error_obj->MESSAGE); - } - $mode = "basic"; - $skill_id = $id; - $tref_id = 0; - if (ilSkillTreeNode::_lookupType($id) == "sktr") - { - include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); - $skill_id = ilSkillTemplateReference::_lookupTemplateId($id); - $tref_id = $id; - } - $cskill_ids[] = array("skill_id" => $skill_id, "tref_id" => $tref_id); - } - if (in_array(ilSkillTreeNode::_lookupType($id), array("sktp", "sctp"))) - { - if ($mode == "basic") - { - $this->ilias->raiseError("Skill Deletion - type mismatch.",$this->ilias->error_obj->MESSAGE); - } - $mode = "templates"; - - foreach (ilSkillTemplateReference::_lookupTrefIdsForTemplateId($id) as $tref_id) - { - $cskill_ids[] = array("skill_id" => $id, "tref_id" => $tref_id); - } - } - // for cats, skills and template references, get "real" usages - // for skill and category templates check usage in references - } - - if ($mode == "basic" || $mode == "templates") - { - include_once("./Services/Skill/classes/class.ilSkillUsage.php"); - $u = new ilSkillUsage(); - $usages = $u->getAllUsagesInfoOfSubtrees($cskill_ids); - if (count($usages) > 0) - { - $html = ""; - foreach ($usages as $k => $usage) - { - include_once("./Services/Skill/classes/class.ilSkillUsageTableGUI.php"); - $tab = new ilSkillUsageTableGUI($this, "showUsage", $k, $usage); - $html.= $tab->getHTML()."

                  "; - } - $tpl->setContent($html); - $ilCtrl->saveParameter($a_gui, "tmpmode"); - $ilToolbar->addButton($lng->txt("back"), - $ilCtrl->getLinkTarget($a_gui, "cancelDelete")); - ilUtil::sendFailure($lng->txt("skmg_cannot_delete_nodes_in_use")); - return; - } - } - else - { - $this->ilias->raiseError("Skill Deletion - type mismatch.",$this->ilias->error_obj->MESSAGE); - } - - // SAVE POST VALUES - $_SESSION["saved_post"] = $_POST["id"]; - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $confirmation_gui = new ilConfirmationGUI(); - - $ilCtrl->setParameter($a_gui, "tmpmode", $_GET["tmpmode"]); - $a_form_action = $this->ctrl->getFormAction($a_gui); - $confirmation_gui->setFormAction($a_form_action); - $confirmation_gui->setHeaderText($this->lng->txt("info_delete_sure")); - - // Add items to delete - include_once("./Services/Skill/classes/class.ilSkillTreeNodeFactory.php"); - foreach($_POST["id"] as $id) - { - if ($id != IL_FIRST_NODE) - { - $node_obj = ilSkillTreeNodeFactory::getInstance($id); - $confirmation_gui->addItem("id[]", $node_obj->getId(), - $node_obj->getTitle(), ilUtil::getImagePath("icon_".$node_obj->getType().".svg")); - } - } - - $confirmation_gui->setCancel($lng->txt("cancel"), "cancelDelete"); - $confirmation_gui->setConfirm($lng->txt("confirm"), "confirmedDelete"); - - $tpl->setContent($confirmation_gui->getHTML()); - } - - /** - * cancel delete - */ - function cancelDelete() - { - $this->ctrl->redirect($this, "editSkills"); - } - - /** - * Delete chapters/scos/pages - */ - function confirmedDelete() - { - $ilCtrl = $this->ctrl; - - // delete all selected objects - include_once("./Services/Skill/classes/class.ilSkillTreeNodeFactory.php"); - foreach ($_POST["id"] as $id) - { - if ($id != IL_FIRST_NODE) - { - $obj = ilSkillTreeNodeFactory::getInstance($id); - $node_data = $this->skill_tree->getNodeData($id); - if (is_object($obj)) - { - $obj->delete(); - } - if($this->skill_tree->isInTree($id)) - { - $this->skill_tree->deleteTree($node_data); - } - } - } - - // feedback - ilUtil::sendInfo($this->lng->txt("info_deleted"),true); - } - - // - // - // Test - // - // - - /** - * Test getCompletionDateForTriggerRefId - * - * @param - * @return - */ - function test() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - $this->setTestSubTabs("test"); - - $ilTabs->activateTab("test"); - - include_once("./Services/Skill/classes/class.ilBasicSkill.php"); - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - $this->form->addCommandButton("test", $lng->txt("execute")); - - $this->form->setTitle("getCompletionDateForTriggerRefId()"); - $this->form->setFormAction($ilCtrl->getFormAction($this)); - - // user id - $ti = new ilTextInputGUI("User ID(s)", "user_id"); - $ti->setMaxLength(200); - $ti->setInfo("Separate multiple IDs by :"); - $ti->setValue($_POST["user_id"]); - $this->form->addItem($ti); - - // ref id - $ti = new ilTextInputGUI("Ref ID(s)", "ref_id"); - $ti->setMaxLength(200); - $ti->setInfo("Separate multiple IDs by :"); - $ti->setValue($_POST["ref_id"]); - $this->form->addItem($ti); - - $result = ""; - if (isset($_POST["user_id"])) - { - $user_ids = explode(":", $_POST["user_id"]); - $ref_ids = explode(":", $_POST["ref_id"]); - if (count($user_ids) <= 1) - { - $user_ids = $user_ids[0]; - } - if (count($ref_ids) == 1) - { - $ref_ids = $ref_ids[0]; - } - else if (count($ref_ids) == 0) - { - $ref_ids = null; - } - - $result = ilBasicSkill::getCompletionDateForTriggerRefId($user_ids, $ref_ids); - $result = "
                  Result:
                  ".var_export($result, true); - } - - $tpl->setContent($this->form->getHTML().$result); - - } - - /** - * Test checkUserCertificateForTriggerRefId - * - * @param - * @return - */ - function testCert() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - $this->setTestSubTabs("cert"); - $ilTabs->activateTab("test"); - - include_once("./Services/Skill/classes/class.ilBasicSkill.php"); - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - $this->form->addCommandButton("testCert", $lng->txt("execute")); - - $this->form->setTitle("checkUserCertificateForTriggerRefId()"); - $this->form->setFormAction($ilCtrl->getFormAction($this)); - - // user id - $ti = new ilTextInputGUI("User ID(s)", "user_id"); - $ti->setMaxLength(200); - $ti->setInfo("Separate multiple IDs by :"); - $ti->setValue($_POST["user_id"]); - $this->form->addItem($ti); - - // ref id - $ti = new ilTextInputGUI("Ref ID(s)", "ref_id"); - $ti->setMaxLength(200); - $ti->setInfo("Separate multiple IDs by :"); - $ti->setValue($_POST["ref_id"]); - $this->form->addItem($ti); - - $result = ""; - if (isset($_POST["user_id"])) - { - $user_ids = explode(":", $_POST["user_id"]); - $ref_ids = explode(":", $_POST["ref_id"]); - if (count($user_ids) <= 1) - { - $user_ids = $user_ids[0]; - } - if (count($ref_ids) == 1) - { - $ref_ids = $ref_ids[0]; - } - else if (count($ref_ids) == 0) - { - $ref_ids = null; - } - - $result = ilBasicSkill::checkUserCertificateForTriggerRefId($user_ids, $ref_ids); - $result = "
                  Result:
                  ".var_export($result, true); - } - - $tpl->setContent($this->form->getHTML().$result); - - } - - /** - * Test getTriggerOfAllCertificates - * - * @param - * @return - */ - function testAllCert() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - $this->setTestSubTabs("all_cert"); - $ilTabs->activateTab("test"); - - include_once("./Services/Skill/classes/class.ilBasicSkill.php"); - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - $this->form->addCommandButton("testAllCert", $lng->txt("execute")); - - $this->form->setTitle("getTriggerOfAllCertificates()"); - $this->form->setFormAction($ilCtrl->getFormAction($this)); - - // user id - $ti = new ilTextInputGUI("User ID(s)", "user_id"); - $ti->setMaxLength(200); - $ti->setInfo("Separate multiple IDs by :"); - $ti->setValue($_POST["user_id"]); - $this->form->addItem($ti); - - $result = ""; - if (isset($_POST["user_id"])) - { - $user_ids = explode(":", $_POST["user_id"]); - $ref_ids = explode(":", $_POST["ref_id"]); - if (count($user_ids) <= 1) - { - $user_ids = $user_ids[0]; - } - - $result = ilBasicSkill::getTriggerOfAllCertificates($user_ids); - $result = "
                  Result:
                  ".var_export($result, true); - } - - $tpl->setContent($this->form->getHTML().$result); - - } - - /** - * Test getSkillLevelsForTrigger - * - * @param - * @return - */ - function testLevels() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - $this->setTestSubTabs("levels"); - $ilTabs->activateTab("test"); - - include_once("./Services/Skill/classes/class.ilBasicSkill.php"); - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - $this->form->addCommandButton("testLevels", $lng->txt("execute")); - - $this->form->setTitle("getTriggerOfAllCertificates()"); - $this->form->setFormAction($ilCtrl->getFormAction($this)); - - // user id - $ti = new ilTextInputGUI("Ref ID", "ref_id"); - $ti->setMaxLength(200); - $ti->setValue($_POST["ref_id"]); - $this->form->addItem($ti); - - $result = ""; - if (isset($_POST["ref_id"])) - { - $result = ilBasicSkill::getSkillLevelsForTrigger($_POST["ref_id"]); - $result = "
                  Result:
                  ".var_export($result, true); - } - - $tpl->setContent($this->form->getHTML().$result); - - } - - - /** - * Set test subtabs - * - * @param - * @return - */ - function setTestSubtabs($a_act) - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - - $ilTabs->addSubtab("test", - "getCompletionDateForTriggerRefId", - $ilCtrl->getLinkTarget($this, "test")); - - $ilTabs->addSubtab("cert", - "checkUserCertificateForTriggerRefId", - $ilCtrl->getLinkTarget($this, "testCert")); - - $ilTabs->addSubtab("all_cert", - "getTriggerOfAllCertificates", - $ilCtrl->getLinkTarget($this, "testAllCert")); - - $ilTabs->addSubtab("levels", - "getSkillLevelsForTrigger", - $ilCtrl->getLinkTarget($this, "testLevels")); - - $ilTabs->activateSubtab($a_act); - - } - - // - // Skill Templates - // - - /** - * Edit skill templates - */ - function editSkillTemplates() - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $ilTabs->activateTab("skill_templates"); - $ilCtrl->setParameterByClass("ilobjskillmanagementgui", "obj_id", $this->skill_tree->getRootId()); - $ilCtrl->redirectByClass("ilskillrootgui", "listTemplates"); - - } - - // - // Tree - // - - /** - * Show Editing Tree - */ - function showTree($a_templates, $a_gui = "", $a_gui_cmd = "") - { - $ilUser = $this->user; - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if ($a_templates) - { - if ($_GET["obj_id"] == "" || $_GET["obj_id"] == 1) - { - return; - } - - if ($_GET["obj_id"] > 1) - { - $path = $this->skill_tree->getPathId($_GET["obj_id"]); - include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); - if (ilSkillTreeNode::_lookupType($path[1]) == "sktp") - { - return; - } - } - } - - $ilCtrl->setParameter($this, "templates_tree", $a_templates); - - if ($a_templates) - { - include_once("./Services/Skill/classes/class.ilSkillTemplateTreeExplorerGUI.php"); - $exp = new ilSkillTemplateTreeExplorerGUI($this, "showTree"); - } - else - { - include_once("./Services/Skill/classes/class.ilSkillTreeExplorerGUI.php"); - $exp = new ilSkillTreeExplorerGUI($this, "showTree", $a_templates); - } - if (!$exp->handleCommand()) - { - $tpl->setLeftNavContent($exp->getHTML()); - } - } - + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilErrorHandling + */ + protected $error; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + protected $skill_tree; + + /** + * Contructor + * + * @access public + */ + public function __construct($a_data, $a_id, $a_call_by_reference = true, $a_prepare_output = true) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->error = $DIC["ilErr"]; + $this->access = $DIC->access(); + $this->tabs = $DIC->tabs(); + $this->lng = $DIC->language(); + $this->settings = $DIC->settings(); + $this->tpl = $DIC["tpl"]; + $this->toolbar = $DIC->toolbar(); + $this->user = $DIC->user(); + $ilCtrl = $DIC->ctrl(); + + $this->type = 'skmg'; + parent::__construct($a_data, $a_id, $a_call_by_reference, $a_prepare_output); + + $this->lng->loadLanguageModule('skmg'); + + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $this->skill_tree = new ilSkillTree(); + + $ilCtrl->saveParameter($this, "obj_id"); + } + + /** + * Execute command + * + * @access public + * + */ + public function executeCommand() + { + $rbacsystem = $this->rbacsystem; + $ilErr = $this->error; + $ilAccess = $this->access; + $ilTabs = $this->tabs; + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + $this->prepareOutput(); + + if (!$ilAccess->checkAccess('read', '', $this->object->getRefId())) { + $ilErr->raiseError($this->lng->txt('no_permission'), $ilErr->WARNING); + } + + switch ($next_class) { + case 'ilskillrootgui': + include_once("./Services/Skill/classes/class.ilSkillRootGUI.php"); + $skrt_gui = new ilSkillRootGUI((int) $_GET["obj_id"], $this); + $skrt_gui->setParentGUI($this); + $ret = $this->ctrl->forwardCommand($skrt_gui); + break; + + case 'ilskillcategorygui': + $this->tabs_gui->activateTab("skills"); + include_once("./Services/Skill/classes/class.ilSkillCategoryGUI.php"); + $scat_gui = new ilSkillCategoryGUI((int) $_GET["obj_id"]); + $scat_gui->setParentGUI($this); + $this->showTree(false, $scat_gui, "listItems"); + $ret = $this->ctrl->forwardCommand($scat_gui); + break; + + case 'ilbasicskillgui': + $this->tabs_gui->activateTab("skills"); + include_once("./Services/Skill/classes/class.ilBasicSkillGUI.php"); + $skill_gui = new ilBasicSkillGUI((int) $_GET["obj_id"]); + $skill_gui->setParentGUI($this); + $this->showTree(false, $skill_gui, "edit"); + $ret = $this->ctrl->forwardCommand($skill_gui); + break; + + case 'ilskilltemplatecategorygui': + $this->tabs_gui->activateTab("skill_templates"); + include_once("./Services/Skill/classes/class.ilSkillTemplateCategoryGUI.php"); + $sctp_gui = new ilSkillTemplateCategoryGUI((int) $_GET["obj_id"], (int) $_GET["tref_id"]); + $sctp_gui->setParentGUI($this); + $this->showTree(((int) $_GET["tref_id"] == 0), $sctp_gui, "listItems"); + $ret = $this->ctrl->forwardCommand($sctp_gui); + break; + + case 'ilbasicskilltemplategui': + $this->tabs_gui->activateTab("skill_templates"); + include_once("./Services/Skill/classes/class.ilBasicSkillTemplateGUI.php"); + $sktp_gui = new ilBasicSkillTemplateGUI((int) $_GET["obj_id"], (int) $_GET["tref_id"]); + $sktp_gui->setParentGUI($this); + $this->showTree(((int) $_GET["tref_id"] == 0), $sktp_gui, "edit"); + $ret = $this->ctrl->forwardCommand($sktp_gui); + break; + + case 'ilskilltemplatereferencegui': + $this->tabs_gui->activateTab("skills"); + include_once("./Services/Skill/classes/class.ilSkillTemplateReferenceGUI.php"); + $sktr_gui = new ilSkillTemplateReferenceGUI((int) $_GET["tref_id"]); + $sktr_gui->setParentGUI($this); + $this->showTree(false, $sktr_gui, "listItems"); + $ret = $this->ctrl->forwardCommand($sktr_gui); + break; + + case "ilskillprofilegui": + $ilTabs->activateTab("profiles"); + include_once("./Services/Skill/classes/class.ilSkillProfileGUI.php"); + $skprof_gui = new ilSkillProfileGUI(); + $ret = $this->ctrl->forwardCommand($skprof_gui); + break; + + case 'ilpermissiongui': + $this->tabs_gui->activateTab('permissions'); + include_once("Services/AccessControl/classes/class.ilPermissionGUI.php"); + $perm_gui = new ilPermissionGUI($this); + $ret = $this->ctrl->forwardCommand($perm_gui); + break; + + case "ilexportgui": + $this->tabs_gui->activateTab('export'); + include_once("./Services/Export/classes/class.ilExportGUI.php"); + $exp_gui = new ilExportGUI($this); + $exp_gui->addFormat("xml"); + //$exp_gui->addFormat("html", "", $this, "exportHTML"); + $ret = $this->ctrl->forwardCommand($exp_gui); + break; + + default: + if (!$cmd || $cmd == 'view') { + $cmd = "editSkills"; + } + + if ($cmd == "showTree") { + $this->showTree($_GET["templates_tree"]); + } else { + $this->$cmd(); + } + break; + } + return true; + } + + /** + * Get tabs + * + * @access public + * + */ + public function getAdminTabs() + { + $rbacsystem = $this->rbacsystem; + $ilAccess = $this->access; + $lng = $this->lng; + + if ($rbacsystem->checkAccess("visible,read", $this->object->getRefId())) { + $this->tabs_gui->addTab( + "skills", + $lng->txt("skmg_skills"), + $this->ctrl->getLinkTarget($this, "editSkills") + ); + + $this->tabs_gui->addTab( + "skill_templates", + $lng->txt("skmg_skill_templates"), + $this->ctrl->getLinkTarget($this, "editSkillTemplates") + ); + + $this->tabs_gui->addTab( + "settings", + $lng->txt("settings"), + $this->ctrl->getLinkTarget($this, "editSettings") + ); + + $this->tabs_gui->addTab( + "profiles", + $lng->txt("skmg_skill_profiles"), + $this->ctrl->getLinkTargetByClass("ilskillprofilegui") + ); + + if ($ilAccess->checkAccess("write", "", $this->object->getRefId())) { + $this->tabs_gui->addTab( + "export", + $lng->txt("export"), + $this->ctrl->getLinkTargetByClass("ilexportgui", "") + ); + } + + if (DEVMODE == 1) { + $this->tabs_gui->addTab( + "test", + "Test (DEVMODE)", + $this->ctrl->getLinkTarget($this, "test") + ); + } + } + + if ($rbacsystem->checkAccess('edit_permission', $this->object->getRefId())) { + $this->tabs_gui->addTab( + "permissions", + $lng->txt("perm_settings"), + $this->ctrl->getLinkTargetByClass('ilpermissiongui', "perm") + ); + } + } + + /** + * Edit news settings. + */ + public function editSettings() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilSetting = $this->settings; + $ilTabs = $this->tabs; + + $ilTabs->activateTab("settings"); + + include_once("./Services/Skill/classes/class.ilSkillManagementSettings.php"); + $skmg_set = new ilSkillManagementSettings(); + $enable_skmg = $skmg_set->isActivated(); + + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this)); + $form->setTitle($lng->txt("skmg_settings")); + + // Enable skill management + $cb_prop = new ilCheckboxInputGUI( + $lng->txt("skmg_enable_skmg"), + "enable_skmg" + ); + $cb_prop->setValue("1"); + $cb_prop->setChecked($enable_skmg); + $form->addItem($cb_prop); + + // Hide Competence Profile Data before Self-Assessment + $cb_prop = new ilCheckboxInputGUI( + $lng->txt("skmg_hide_profile_self_eval"), + "hide_profile_self_eval" + ); + $cb_prop->setValue("1"); + $cb_prop->setInfo($lng->txt("skmg_hide_profile_self_eval_info")); + $cb_prop->setChecked($skmg_set->getHideProfileBeforeSelfEval()); + $form->addItem($cb_prop); + + // command buttons + if ($this->checkPermissionBool("write")) { + $form->addCommandButton("saveSettings", $lng->txt("save")); + } + + $this->tpl->setContent($form->getHTML()); + } + + /** + * Save skill management settings + */ + public function saveSettings() + { + $ilCtrl = $this->ctrl; + $ilSetting = $this->settings; + + if (!$this->checkPermissionBool("write")) { + return; + } + + include_once("./Services/Skill/classes/class.ilSkillManagementSettings.php"); + $skmg_set = new ilSkillManagementSettings(); + $skmg_set->activate((int) $_POST["enable_skmg"]); + $skmg_set->setHideProfileBeforeSelfEval((int) $_POST["hide_profile_self_eval"]); + + ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); + + $ilCtrl->redirect($this, "editSettings"); + } + + /** + * Edit skills + */ + public function editSkills() + { + $tpl = $this->tpl; + $ilTabs = $this->tabs; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $ilTabs->activateTab("skills"); + + $ilCtrl->setParameterByClass("ilobjskillmanagementgui", "obj_id", $this->skill_tree->getRootId()); + $ilCtrl->redirectByClass("ilskillrootgui", "listSkills"); + } + + + /** + * Save all titles of chapters/scos/pages + */ + public function saveAllTitles($a_succ_mess = true) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if (is_array($_POST["title"])) { + include_once("./Services/Skill/classes/class.ilSkillTreeNodeFactory.php"); + foreach ($_POST["title"] as $id => $title) { + $node_obj = ilSkillTreeNodeFactory::getInstance($id); + if (is_object($node_obj)) { + // update title + ilSkillTreeNode::_writeTitle($id, ilUtil::stripSlashes($title)); + } + } + if ($a_succ_mess) { + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + } + } + $ilCtrl->redirect($this, "editSkills"); + } + + /** + * Save all titles of chapters/scos/pages + */ + public function saveAllTemplateTitles($a_succ_mess = true) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if (is_array($_POST["title"])) { + include_once("./Services/Skill/classes/class.ilSkillTreeNodeFactory.php"); + foreach ($_POST["title"] as $id => $title) { + $node_obj = ilSkillTreeNodeFactory::getInstance($id); + if (is_object($node_obj)) { + // update title + ilSkillTreeNode::_writeTitle($id, ilUtil::stripSlashes($title)); + } + } + if ($a_succ_mess) { + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + } + } + $ilCtrl->redirect($this, "editSkillTemplates"); + } + + + /** + * Expand all + */ + public function expandAll($a_redirect = true) + { + $_GET["skexpand"] = ""; + $n_id = ($_GET["obj_id"] > 0) + ? $_GET["obj_id"] + : $this->skill_tree->readRootId(); + $stree = $this->skill_tree->getSubTree($this->skill_tree->getNodeData($n_id)); + $n_arr = array(); + foreach ($stree as $n) { + $n_arr[] = $n["child"]; + $_SESSION["skexpand"] = $n_arr; + } + $this->saveAllTitles(false); + } + + /** + * Collapse all + */ + public function collapseAll($a_redirect = true) + { + $_GET["skexpand"] = ""; + $n_id = ($_GET["obj_id"] > 0) + ? $_GET["obj_id"] + : $this->skill_tree->readRootId(); + $stree = $this->skill_tree->getSubTree($this->skill_tree->getNodeData($n_id)); + $old = $_SESSION["skexpand"]; + foreach ($stree as $n) { + if (in_array($n["child"], $old) && $n["child"] != $n_id) { + $k = array_search($n["child"], $old); + unset($old[$k]); + } + } + $_SESSION["skexpand"] = $old; + $this->saveAllTitles(false); + } + + /** + * confirm deletion screen of skill tree nodes + */ + public function deleteNodes($a_gui) + { + $lng = $this->lng; + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + $ilToolbar = $this->toolbar; + + if (!isset($_POST["id"])) { + $this->ilias->raiseError($this->lng->txt("no_checkbox"), $this->ilias->error_obj->MESSAGE); + } + + $ilTabs->clearTargets(); + + // check usages + $mode = ""; + $cskill_ids = array(); + foreach ($_POST["id"] as $id) { + if (in_array(ilSkillTreeNode::_lookupType($id), array("skll", "scat", "sktr"))) { + if ($mode == "templates") { + $this->ilias->raiseError("Skill Deletion - type mismatch.", $this->ilias->error_obj->MESSAGE); + } + $mode = "basic"; + $skill_id = $id; + $tref_id = 0; + if (ilSkillTreeNode::_lookupType($id) == "sktr") { + include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); + $skill_id = ilSkillTemplateReference::_lookupTemplateId($id); + $tref_id = $id; + } + $cskill_ids[] = array("skill_id" => $skill_id, "tref_id" => $tref_id); + } + if (in_array(ilSkillTreeNode::_lookupType($id), array("sktp", "sctp"))) { + if ($mode == "basic") { + $this->ilias->raiseError("Skill Deletion - type mismatch.", $this->ilias->error_obj->MESSAGE); + } + $mode = "templates"; + + foreach (ilSkillTemplateReference::_lookupTrefIdsForTemplateId($id) as $tref_id) { + $cskill_ids[] = array("skill_id" => $id, "tref_id" => $tref_id); + } + } + // for cats, skills and template references, get "real" usages + // for skill and category templates check usage in references + } + + if ($mode == "basic" || $mode == "templates") { + include_once("./Services/Skill/classes/class.ilSkillUsage.php"); + $u = new ilSkillUsage(); + $usages = $u->getAllUsagesInfoOfSubtrees($cskill_ids); + if (count($usages) > 0) { + $html = ""; + foreach ($usages as $k => $usage) { + include_once("./Services/Skill/classes/class.ilSkillUsageTableGUI.php"); + $tab = new ilSkillUsageTableGUI($this, "showUsage", $k, $usage); + $html.= $tab->getHTML() . "

                  "; + } + $tpl->setContent($html); + $ilCtrl->saveParameter($a_gui, "tmpmode"); + $ilToolbar->addButton( + $lng->txt("back"), + $ilCtrl->getLinkTarget($a_gui, "cancelDelete") + ); + ilUtil::sendFailure($lng->txt("skmg_cannot_delete_nodes_in_use")); + return; + } + } else { + $this->ilias->raiseError("Skill Deletion - type mismatch.", $this->ilias->error_obj->MESSAGE); + } + + // SAVE POST VALUES + $_SESSION["saved_post"] = $_POST["id"]; + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $confirmation_gui = new ilConfirmationGUI(); + + $ilCtrl->setParameter($a_gui, "tmpmode", $_GET["tmpmode"]); + $a_form_action = $this->ctrl->getFormAction($a_gui); + $confirmation_gui->setFormAction($a_form_action); + $confirmation_gui->setHeaderText($this->lng->txt("info_delete_sure")); + + // Add items to delete + include_once("./Services/Skill/classes/class.ilSkillTreeNodeFactory.php"); + foreach ($_POST["id"] as $id) { + if ($id != IL_FIRST_NODE) { + $node_obj = ilSkillTreeNodeFactory::getInstance($id); + $confirmation_gui->addItem( + "id[]", + $node_obj->getId(), + $node_obj->getTitle(), + ilUtil::getImagePath("icon_" . $node_obj->getType() . ".svg") + ); + } + } + + $confirmation_gui->setCancel($lng->txt("cancel"), "cancelDelete"); + $confirmation_gui->setConfirm($lng->txt("confirm"), "confirmedDelete"); + + $tpl->setContent($confirmation_gui->getHTML()); + } + + /** + * cancel delete + */ + public function cancelDelete() + { + $this->ctrl->redirect($this, "editSkills"); + } + + /** + * Delete chapters/scos/pages + */ + public function confirmedDelete() + { + $ilCtrl = $this->ctrl; + + // delete all selected objects + include_once("./Services/Skill/classes/class.ilSkillTreeNodeFactory.php"); + foreach ($_POST["id"] as $id) { + if ($id != IL_FIRST_NODE) { + $obj = ilSkillTreeNodeFactory::getInstance($id); + $node_data = $this->skill_tree->getNodeData($id); + if (is_object($obj)) { + $obj->delete(); + } + if ($this->skill_tree->isInTree($id)) { + $this->skill_tree->deleteTree($node_data); + } + } + } + + // feedback + ilUtil::sendInfo($this->lng->txt("info_deleted"), true); + } + + // + // + // Test + // + // + + /** + * Test getCompletionDateForTriggerRefId + * + * @param + * @return + */ + public function test() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + $this->setTestSubTabs("test"); + + $ilTabs->activateTab("test"); + + include_once("./Services/Skill/classes/class.ilBasicSkill.php"); + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + $this->form->addCommandButton("test", $lng->txt("execute")); + + $this->form->setTitle("getCompletionDateForTriggerRefId()"); + $this->form->setFormAction($ilCtrl->getFormAction($this)); + + // user id + $ti = new ilTextInputGUI("User ID(s)", "user_id"); + $ti->setMaxLength(200); + $ti->setInfo("Separate multiple IDs by :"); + $ti->setValue($_POST["user_id"]); + $this->form->addItem($ti); + + // ref id + $ti = new ilTextInputGUI("Ref ID(s)", "ref_id"); + $ti->setMaxLength(200); + $ti->setInfo("Separate multiple IDs by :"); + $ti->setValue($_POST["ref_id"]); + $this->form->addItem($ti); + + $result = ""; + if (isset($_POST["user_id"])) { + $user_ids = explode(":", $_POST["user_id"]); + $ref_ids = explode(":", $_POST["ref_id"]); + if (count($user_ids) <= 1) { + $user_ids = $user_ids[0]; + } + if (count($ref_ids) == 1) { + $ref_ids = $ref_ids[0]; + } elseif (count($ref_ids) == 0) { + $ref_ids = null; + } + + $result = ilBasicSkill::getCompletionDateForTriggerRefId($user_ids, $ref_ids); + $result = "
                  Result:
                  " . var_export($result, true); + } + + $tpl->setContent($this->form->getHTML() . $result); + } + + /** + * Test checkUserCertificateForTriggerRefId + * + * @param + * @return + */ + public function testCert() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + $this->setTestSubTabs("cert"); + $ilTabs->activateTab("test"); + + include_once("./Services/Skill/classes/class.ilBasicSkill.php"); + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + $this->form->addCommandButton("testCert", $lng->txt("execute")); + + $this->form->setTitle("checkUserCertificateForTriggerRefId()"); + $this->form->setFormAction($ilCtrl->getFormAction($this)); + + // user id + $ti = new ilTextInputGUI("User ID(s)", "user_id"); + $ti->setMaxLength(200); + $ti->setInfo("Separate multiple IDs by :"); + $ti->setValue($_POST["user_id"]); + $this->form->addItem($ti); + + // ref id + $ti = new ilTextInputGUI("Ref ID(s)", "ref_id"); + $ti->setMaxLength(200); + $ti->setInfo("Separate multiple IDs by :"); + $ti->setValue($_POST["ref_id"]); + $this->form->addItem($ti); + + $result = ""; + if (isset($_POST["user_id"])) { + $user_ids = explode(":", $_POST["user_id"]); + $ref_ids = explode(":", $_POST["ref_id"]); + if (count($user_ids) <= 1) { + $user_ids = $user_ids[0]; + } + if (count($ref_ids) == 1) { + $ref_ids = $ref_ids[0]; + } elseif (count($ref_ids) == 0) { + $ref_ids = null; + } + + $result = ilBasicSkill::checkUserCertificateForTriggerRefId($user_ids, $ref_ids); + $result = "
                  Result:
                  " . var_export($result, true); + } + + $tpl->setContent($this->form->getHTML() . $result); + } + + /** + * Test getTriggerOfAllCertificates + * + * @param + * @return + */ + public function testAllCert() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + $this->setTestSubTabs("all_cert"); + $ilTabs->activateTab("test"); + + include_once("./Services/Skill/classes/class.ilBasicSkill.php"); + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + $this->form->addCommandButton("testAllCert", $lng->txt("execute")); + + $this->form->setTitle("getTriggerOfAllCertificates()"); + $this->form->setFormAction($ilCtrl->getFormAction($this)); + + // user id + $ti = new ilTextInputGUI("User ID(s)", "user_id"); + $ti->setMaxLength(200); + $ti->setInfo("Separate multiple IDs by :"); + $ti->setValue($_POST["user_id"]); + $this->form->addItem($ti); + + $result = ""; + if (isset($_POST["user_id"])) { + $user_ids = explode(":", $_POST["user_id"]); + $ref_ids = explode(":", $_POST["ref_id"]); + if (count($user_ids) <= 1) { + $user_ids = $user_ids[0]; + } + + $result = ilBasicSkill::getTriggerOfAllCertificates($user_ids); + $result = "
                  Result:
                  " . var_export($result, true); + } + + $tpl->setContent($this->form->getHTML() . $result); + } + + /** + * Test getSkillLevelsForTrigger + * + * @param + * @return + */ + public function testLevels() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + $this->setTestSubTabs("levels"); + $ilTabs->activateTab("test"); + + include_once("./Services/Skill/classes/class.ilBasicSkill.php"); + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + $this->form->addCommandButton("testLevels", $lng->txt("execute")); + + $this->form->setTitle("getTriggerOfAllCertificates()"); + $this->form->setFormAction($ilCtrl->getFormAction($this)); + + // user id + $ti = new ilTextInputGUI("Ref ID", "ref_id"); + $ti->setMaxLength(200); + $ti->setValue($_POST["ref_id"]); + $this->form->addItem($ti); + + $result = ""; + if (isset($_POST["ref_id"])) { + $result = ilBasicSkill::getSkillLevelsForTrigger($_POST["ref_id"]); + $result = "
                  Result:
                  " . var_export($result, true); + } + + $tpl->setContent($this->form->getHTML() . $result); + } + + + /** + * Set test subtabs + * + * @param + * @return + */ + public function setTestSubtabs($a_act) + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + + $ilTabs->addSubtab( + "test", + "getCompletionDateForTriggerRefId", + $ilCtrl->getLinkTarget($this, "test") + ); + + $ilTabs->addSubtab( + "cert", + "checkUserCertificateForTriggerRefId", + $ilCtrl->getLinkTarget($this, "testCert") + ); + + $ilTabs->addSubtab( + "all_cert", + "getTriggerOfAllCertificates", + $ilCtrl->getLinkTarget($this, "testAllCert") + ); + + $ilTabs->addSubtab( + "levels", + "getSkillLevelsForTrigger", + $ilCtrl->getLinkTarget($this, "testLevels") + ); + + $ilTabs->activateSubtab($a_act); + } + + // + // Skill Templates + // + + /** + * Edit skill templates + */ + public function editSkillTemplates() + { + $tpl = $this->tpl; + $ilTabs = $this->tabs; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $ilTabs->activateTab("skill_templates"); + $ilCtrl->setParameterByClass("ilobjskillmanagementgui", "obj_id", $this->skill_tree->getRootId()); + $ilCtrl->redirectByClass("ilskillrootgui", "listTemplates"); + } + + // + // Tree + // + + /** + * Show Editing Tree + */ + public function showTree($a_templates, $a_gui = "", $a_gui_cmd = "") + { + $ilUser = $this->user; + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if ($a_templates) { + if ($_GET["obj_id"] == "" || $_GET["obj_id"] == 1) { + return; + } + + if ($_GET["obj_id"] > 1) { + $path = $this->skill_tree->getPathId($_GET["obj_id"]); + include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); + if (ilSkillTreeNode::_lookupType($path[1]) == "sktp") { + return; + } + } + } + + $ilCtrl->setParameter($this, "templates_tree", $a_templates); + + if ($a_templates) { + include_once("./Services/Skill/classes/class.ilSkillTemplateTreeExplorerGUI.php"); + $exp = new ilSkillTemplateTreeExplorerGUI($this, "showTree"); + } else { + include_once("./Services/Skill/classes/class.ilSkillTreeExplorerGUI.php"); + $exp = new ilSkillTreeExplorerGUI($this, "showTree", $a_templates); + } + if (!$exp->handleCommand()) { + $tpl->setLeftNavContent($exp->getHTML()); + } + } } -?> \ No newline at end of file diff --git a/Services/Skill/classes/class.ilPersonalSkill.php b/Services/Skill/classes/class.ilPersonalSkill.php index 5609562e6db09e4293cd04358a276023495f6ddd..75c3bb6be9fc7ff01c29c7dd54087c92fd51b4ee 100644 --- a/Services/Skill/classes/class.ilPersonalSkill.php +++ b/Services/Skill/classes/class.ilPersonalSkill.php @@ -9,350 +9,353 @@ include_once("./Services/Skill/interfaces/interface.ilSkillUsageInfo.php"); * * @author Alex Killing * @version $Id$ - * @ingroup + * @ingroup */ class ilPersonalSkill implements ilSkillUsageInfo { - /** - * Get personal selected user skills - * - * @param int $a_user_id user id - * @return array - */ - static function getSelectedUserSkills($a_user_id) - { - global $DIC; + /** + * Get personal selected user skills + * + * @param int $a_user_id user id + * @return array + */ + public static function getSelectedUserSkills($a_user_id) + { + global $DIC; - $ilDB = $DIC->database(); - - include_once "Services/Skill/classes/class.ilSkillTreeNode.php"; - - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $stree = new ilSkillTree(); + $ilDB = $DIC->database(); + + include_once "Services/Skill/classes/class.ilSkillTreeNode.php"; + + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $stree = new ilSkillTree(); - $set = $ilDB->query("SELECT * FROM skl_personal_skill ". - " WHERE user_id = ".$ilDB->quote($a_user_id, "integer") - ); - $pskills = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - if ($stree->isInTree($rec["skill_node_id"])) - { - $pskills[$rec["skill_node_id"]] = array("skill_node_id" => $rec["skill_node_id"], - "title" => ilSkillTreeNode::_lookupTitle($rec["skill_node_id"])); - } - } - return $pskills; - } - - /** - * Add personal skill - * - * @param int $a_user_id - * @param int $a_skill_node_id - */ - static function addPersonalSkill($a_user_id, $a_skill_node_id) - { - global $DIC; + $set = $ilDB->query( + "SELECT * FROM skl_personal_skill " . + " WHERE user_id = " . $ilDB->quote($a_user_id, "integer") + ); + $pskills = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + if ($stree->isInTree($rec["skill_node_id"])) { + $pskills[$rec["skill_node_id"]] = array("skill_node_id" => $rec["skill_node_id"], + "title" => ilSkillTreeNode::_lookupTitle($rec["skill_node_id"])); + } + } + return $pskills; + } + + /** + * Add personal skill + * + * @param int $a_user_id + * @param int $a_skill_node_id + */ + public static function addPersonalSkill($a_user_id, $a_skill_node_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT * FROM skl_personal_skill ". - " WHERE user_id = ".$ilDB->quote($a_user_id, "integer"). - " AND skill_node_id = ".$ilDB->quote($a_skill_node_id, "integer") - ); - if (!$ilDB->fetchAssoc($set)) - { - $ilDB->manipulate("INSERT INTO skl_personal_skill ". - "(user_id, skill_node_id) VALUES (". - $ilDB->quote($a_user_id, "integer").",". - $ilDB->quote($a_skill_node_id, "integer"). - ")"); - } - } - - /** - * Remove personal skill - * - * @param int $a_user_id user id - * @param int $a_skill_node_id the "selectable" top skill - */ - static function removeSkill($a_user_id, $a_skill_node_id) - { - global $DIC; + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT * FROM skl_personal_skill " . + " WHERE user_id = " . $ilDB->quote($a_user_id, "integer") . + " AND skill_node_id = " . $ilDB->quote($a_skill_node_id, "integer") + ); + if (!$ilDB->fetchAssoc($set)) { + $ilDB->manipulate("INSERT INTO skl_personal_skill " . + "(user_id, skill_node_id) VALUES (" . + $ilDB->quote($a_user_id, "integer") . "," . + $ilDB->quote($a_skill_node_id, "integer") . + ")"); + } + } + + /** + * Remove personal skill + * + * @param int $a_user_id user id + * @param int $a_skill_node_id the "selectable" top skill + */ + public static function removeSkill($a_user_id, $a_skill_node_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $ilDB->manipulate("DELETE FROM skl_personal_skill WHERE ". - " user_id = ".$ilDB->quote($a_user_id, "integer"). - " AND skill_node_id = ".$ilDB->quote($a_skill_node_id, "integer") - ); - } + $ilDB = $DIC->database(); + + $ilDB->manipulate( + "DELETE FROM skl_personal_skill WHERE " . + " user_id = " . $ilDB->quote($a_user_id, "integer") . + " AND skill_node_id = " . $ilDB->quote($a_skill_node_id, "integer") + ); + } - /** - * Remove personal skills of user - * - * @param int $a_user_id user id - */ - static function removeSkills($a_user_id) - { - global $DIC; + /** + * Remove personal skills of user + * + * @param int $a_user_id user id + */ + public static function removeSkills($a_user_id) + { + global $DIC; - $ilDB = $DIC->database(); + $ilDB = $DIC->database(); - $ilDB->manipulate("DELETE FROM skl_personal_skill WHERE ". - " user_id = ".$ilDB->quote($a_user_id, "integer") - ); - } + $ilDB->manipulate( + "DELETE FROM skl_personal_skill WHERE " . + " user_id = " . $ilDB->quote($a_user_id, "integer") + ); + } - - // - // Assigned materials - // - - /** - * Assign material to skill level - * - * @param int $a_user_id user id - * @param int $a_top_skill the "selectable" top skill - * @param int $a_tref_id template reference id - * @param int $a_basic_skill the basic skill the level belongs to - * @param int $a_level level id - * @param int $a_wsp_id workspace object - */ - static function assignMaterial($a_user_id, $a_top_skill, $a_tref_id, $a_basic_skill, $a_level, $a_wsp_id) - { - global $DIC; + + // + // Assigned materials + // + + /** + * Assign material to skill level + * + * @param int $a_user_id user id + * @param int $a_top_skill the "selectable" top skill + * @param int $a_tref_id template reference id + * @param int $a_basic_skill the basic skill the level belongs to + * @param int $a_level level id + * @param int $a_wsp_id workspace object + */ + public static function assignMaterial($a_user_id, $a_top_skill, $a_tref_id, $a_basic_skill, $a_level, $a_wsp_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT * FROM skl_assigned_material ". - " WHERE user_id = ".$ilDB->quote($a_user_id, "integer"). - " AND top_skill_id = ".$ilDB->quote($a_top_skill, "integer"). - " AND tref_id = ".$ilDB->quote((int) $a_tref_id, "integer"). - " AND skill_id = ".$ilDB->quote($a_basic_skill, "integer"). - " AND level_id = ".$ilDB->quote($a_level, "integer"). - " AND wsp_id = ".$ilDB->quote($a_wsp_id, "integer") - ); - if (!$ilDB->fetchAssoc($set)) - { - $ilDB->manipulate("INSERT INTO skl_assigned_material ". - "(user_id, top_skill_id, tref_id, skill_id, level_id, wsp_id) VALUES (". - $ilDB->quote($a_user_id, "integer").",". - $ilDB->quote($a_top_skill, "integer").",". - $ilDB->quote((int) $a_tref_id, "integer").",". - $ilDB->quote($a_basic_skill, "integer").",". - $ilDB->quote($a_level, "integer").",". - $ilDB->quote($a_wsp_id, "integer"). - ")"); - } - } - - /** - * Get assigned material (for a skill level and user) - * - * @param int $a_user_id user id - * @param int $a_tref_id template reference id - * @param int $a_level level id - */ - static function getAssignedMaterial($a_user_id, $a_tref_id, $a_level) - { - global $DIC; + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT * FROM skl_assigned_material " . + " WHERE user_id = " . $ilDB->quote($a_user_id, "integer") . + " AND top_skill_id = " . $ilDB->quote($a_top_skill, "integer") . + " AND tref_id = " . $ilDB->quote((int) $a_tref_id, "integer") . + " AND skill_id = " . $ilDB->quote($a_basic_skill, "integer") . + " AND level_id = " . $ilDB->quote($a_level, "integer") . + " AND wsp_id = " . $ilDB->quote($a_wsp_id, "integer") + ); + if (!$ilDB->fetchAssoc($set)) { + $ilDB->manipulate("INSERT INTO skl_assigned_material " . + "(user_id, top_skill_id, tref_id, skill_id, level_id, wsp_id) VALUES (" . + $ilDB->quote($a_user_id, "integer") . "," . + $ilDB->quote($a_top_skill, "integer") . "," . + $ilDB->quote((int) $a_tref_id, "integer") . "," . + $ilDB->quote($a_basic_skill, "integer") . "," . + $ilDB->quote($a_level, "integer") . "," . + $ilDB->quote($a_wsp_id, "integer") . + ")"); + } + } + + /** + * Get assigned material (for a skill level and user) + * + * @param int $a_user_id user id + * @param int $a_tref_id template reference id + * @param int $a_level level id + */ + public static function getAssignedMaterial($a_user_id, $a_tref_id, $a_level) + { + global $DIC; - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT * FROM skl_assigned_material ". - " WHERE level_id = ".$ilDB->quote($a_level, "integer"). - " AND tref_id = ".$ilDB->quote((int) $a_tref_id, "integer"). - " AND user_id = ".$ilDB->quote($a_user_id, "integer") - ); - $mat = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $mat[] = $rec; - } - return $mat; - } - - /** - * Get assigned material (for a skill level and user) - * - * @param int $a_user_id user id - * @param int $a_tref_id template reference id - * @param int $a_level level id - */ - static function countAssignedMaterial($a_user_id, $a_tref_id, $a_level) - { - global $DIC; + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT * FROM skl_assigned_material " . + " WHERE level_id = " . $ilDB->quote($a_level, "integer") . + " AND tref_id = " . $ilDB->quote((int) $a_tref_id, "integer") . + " AND user_id = " . $ilDB->quote($a_user_id, "integer") + ); + $mat = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $mat[] = $rec; + } + return $mat; + } + + /** + * Get assigned material (for a skill level and user) + * + * @param int $a_user_id user id + * @param int $a_tref_id template reference id + * @param int $a_level level id + */ + public static function countAssignedMaterial($a_user_id, $a_tref_id, $a_level) + { + global $DIC; - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT count(*) as cnt FROM skl_assigned_material ". - " WHERE level_id = ".$ilDB->quote($a_level, "integer"). - " AND tref_id = ".$ilDB->quote((int) $a_tref_id, "integer"). - " AND user_id = ".$ilDB->quote($a_user_id, "integer") - ); - $rec = $ilDB->fetchAssoc($set); - return $rec["cnt"]; - } - - /** - * Remove material - * - * @param - * @return - */ - static function removeMaterial($a_user_id, $a_tref_id, $a_level_id, $a_wsp_id) - { - global $DIC; + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT count(*) as cnt FROM skl_assigned_material " . + " WHERE level_id = " . $ilDB->quote($a_level, "integer") . + " AND tref_id = " . $ilDB->quote((int) $a_tref_id, "integer") . + " AND user_id = " . $ilDB->quote($a_user_id, "integer") + ); + $rec = $ilDB->fetchAssoc($set); + return $rec["cnt"]; + } + + /** + * Remove material + * + * @param + * @return + */ + public static function removeMaterial($a_user_id, $a_tref_id, $a_level_id, $a_wsp_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $t = "DELETE FROM skl_assigned_material WHERE ". - " user_id = ".$ilDB->quote($a_user_id, "integer"). - " AND tref_id = ".$ilDB->quote((int) $a_tref_id, "integer"). - " AND level_id = ".$ilDB->quote($a_level_id, "integer"). - " AND wsp_id = ".$ilDB->quote($a_wsp_id, "integer"); + $ilDB = $DIC->database(); + + $t = "DELETE FROM skl_assigned_material WHERE " . + " user_id = " . $ilDB->quote($a_user_id, "integer") . + " AND tref_id = " . $ilDB->quote((int) $a_tref_id, "integer") . + " AND level_id = " . $ilDB->quote($a_level_id, "integer") . + " AND wsp_id = " . $ilDB->quote($a_wsp_id, "integer"); - $ilDB->manipulate($t); - } + $ilDB->manipulate($t); + } - /** - * Remove materials of user - * - * @param int $a_user_id - */ - static function removeMaterials($a_user_id) - { - global $DIC; + /** + * Remove materials of user + * + * @param int $a_user_id + */ + public static function removeMaterials($a_user_id) + { + global $DIC; - $ilDB = $DIC->database(); + $ilDB = $DIC->database(); - $t = "DELETE FROM skl_assigned_material WHERE ". - " user_id = ".$ilDB->quote($a_user_id, "integer"); - $ilDB->manipulate($t); - } + $t = "DELETE FROM skl_assigned_material WHERE " . + " user_id = " . $ilDB->quote($a_user_id, "integer"); + $ilDB->manipulate($t); + } - // - // Self evaluation - // - - /** - * Save self evaluation - * - * @param int $a_user_id user id - * @param int $a_top_skill the "selectable" top skill - * @param int $a_tref_id template reference id - * @param int $a_basic_skill the basic skill the level belongs to - * @param int $a_level level id - */ - static function saveSelfEvaluation($a_user_id, $a_top_skill, $a_tref_id, $a_basic_skill, $a_level) - { - include_once("./Services/Skill/classes/class.ilBasicSkill.php"); - if ($a_level > 0) - { - ilBasicSkill::writeUserSkillLevelStatus($a_level, $a_user_id, - 0, $a_tref_id, ilBasicSkill::ACHIEVED, false, - 1); - } - else - { - ilBasicSkill::resetUserSkillLevelStatus($a_user_id, $a_basic_skill, $a_tref_id, 0, true); - } + // + // Self evaluation + // + + /** + * Save self evaluation + * + * @param int $a_user_id user id + * @param int $a_top_skill the "selectable" top skill + * @param int $a_tref_id template reference id + * @param int $a_basic_skill the basic skill the level belongs to + * @param int $a_level level id + */ + public static function saveSelfEvaluation($a_user_id, $a_top_skill, $a_tref_id, $a_basic_skill, $a_level) + { + include_once("./Services/Skill/classes/class.ilBasicSkill.php"); + if ($a_level > 0) { + ilBasicSkill::writeUserSkillLevelStatus( + $a_level, + $a_user_id, + 0, + $a_tref_id, + ilBasicSkill::ACHIEVED, + false, + 1 + ); + } else { + ilBasicSkill::resetUserSkillLevelStatus($a_user_id, $a_basic_skill, $a_tref_id, 0, true); + } + } - } + /** + * Get self evaluation + * + * @param int $a_user_id user id + * @param int $a_top_skill the "selectable" top skill + * @param int $a_tref_id template reference id + * @param int $a_basic_skill the basic skill the level belongs to + * @return int level id + */ + public static function getSelfEvaluation($a_user_id, $a_top_skill, $a_tref_id, $a_basic_skill) + { + include_once("./Services/Skill/classes/class.ilBasicSkill.php"); + $bs = new ilBasicSkill($a_basic_skill); + return $bs->getLastLevelPerObject($a_tref_id, 0, $a_user_id, 1); + } - /** - * Get self evaluation - * - * @param int $a_user_id user id - * @param int $a_top_skill the "selectable" top skill - * @param int $a_tref_id template reference id - * @param int $a_basic_skill the basic skill the level belongs to - * @return int level id - */ - static function getSelfEvaluation($a_user_id, $a_top_skill, $a_tref_id, $a_basic_skill) - { - include_once("./Services/Skill/classes/class.ilBasicSkill.php"); - $bs = new ilBasicSkill($a_basic_skill); - return $bs->getLastLevelPerObject($a_tref_id, 0, $a_user_id, 1); - } + /** + * Get self evaluation + * + * @param int $a_user_id user id + * @param int $a_top_skill the "selectable" top skill + * @param int $a_tref_id template reference id + * @param int $a_basic_skill the basic skill the level belongs to + * @return int level id + */ + public static function getSelfEvaluationDate($a_user_id, $a_top_skill, $a_tref_id, $a_basic_skill) + { + include_once("./Services/Skill/classes/class.ilBasicSkill.php"); + $bs = new ilBasicSkill($a_basic_skill); + return $bs->getLastUpdatePerObject($a_tref_id, 0, $a_user_id, 1); + } - /** - * Get self evaluation - * - * @param int $a_user_id user id - * @param int $a_top_skill the "selectable" top skill - * @param int $a_tref_id template reference id - * @param int $a_basic_skill the basic skill the level belongs to - * @return int level id - */ - static function getSelfEvaluationDate($a_user_id, $a_top_skill, $a_tref_id, $a_basic_skill) - { - include_once("./Services/Skill/classes/class.ilBasicSkill.php"); - $bs = new ilBasicSkill($a_basic_skill); - return $bs->getLastUpdatePerObject($a_tref_id, 0, $a_user_id, 1); - } + /** + * Get usage info + * + * @param array $a_cskill_ids skill ids + * @param array $a_usages usages array + */ + public static function getUsageInfo($a_cskill_ids, &$a_usages) + { + global $DIC; - /** - * Get usage info - * - * @param array $a_cskill_ids skill ids - * @param array $a_usages usages array - */ - static public function getUsageInfo($a_cskill_ids, &$a_usages) - { - global $DIC; + $ilDB = $DIC->database(); - $ilDB = $DIC->database(); + // material + include_once("./Services/Skill/classes/class.ilSkillUsage.php"); + ilSkillUsage::getUsageInfoGeneric( + $a_cskill_ids, + $a_usages, + ilSkillUsage::USER_MATERIAL, + "skl_assigned_material", + "user_id" + ); - // material - include_once("./Services/Skill/classes/class.ilSkillUsage.php"); - ilSkillUsage::getUsageInfoGeneric($a_cskill_ids, $a_usages, ilSkillUsage::USER_MATERIAL, - "skl_assigned_material", "user_id"); - - // self evaluations - ilSkillUsage::getUsageInfoGeneric($a_cskill_ids, $a_usages, ilSkillUsage::SELF_EVAL, - "skl_self_eval_level", "user_id"); - - // users that use the skills as personal skills - $pskill_ids = array(); - $tref_ids = array(); - foreach ($a_cskill_ids as $cs) - { - if ($cs["tref_id"] > 0) - { - include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); - if (ilSkillTemplateReference::_lookupTemplateId($cs["tref_id"]) == $cs["skill_id"]) - { - $pskill_ids[$cs["tref_id"]] = $cs["tref_id"]; - $tref_ids[(int) $cs["tref_id"]] = $cs["skill_id"]; - } - } - else - { - $pskill_ids[$cs["skill_id"]] = $cs["skill_id"]; - } - } - $set = $ilDB->query("SELECT skill_node_id, user_id FROM skl_personal_skill ". - " WHERE ".$ilDB->in("skill_node_id", $pskill_ids, false, "integer"). - " GROUP BY skill_node_id, user_id" - ); - while ($rec = $ilDB->fetchAssoc($set)) - { - if (isset($tref_ids[(int) $rec["skill_node_id"]])) - { - $a_usages[$tref_ids[$rec["skill_node_id"]].":".$rec["skill_node_id"]][ilSkillUsage::PERSONAL_SKILL][] = - array("key" => $rec["user_id"]); - } - else - { - $a_usages[$rec["skill_node_id"].":0"][ilSkillUsage::PERSONAL_SKILL][] = - array("key" => $rec["user_id"]); - } - } - } + // self evaluations + ilSkillUsage::getUsageInfoGeneric( + $a_cskill_ids, + $a_usages, + ilSkillUsage::SELF_EVAL, + "skl_self_eval_level", + "user_id" + ); + // users that use the skills as personal skills + $pskill_ids = array(); + $tref_ids = array(); + foreach ($a_cskill_ids as $cs) { + if ($cs["tref_id"] > 0) { + include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); + if (ilSkillTemplateReference::_lookupTemplateId($cs["tref_id"]) == $cs["skill_id"]) { + $pskill_ids[$cs["tref_id"]] = $cs["tref_id"]; + $tref_ids[(int) $cs["tref_id"]] = $cs["skill_id"]; + } + } else { + $pskill_ids[$cs["skill_id"]] = $cs["skill_id"]; + } + } + $set = $ilDB->query( + "SELECT skill_node_id, user_id FROM skl_personal_skill " . + " WHERE " . $ilDB->in("skill_node_id", $pskill_ids, false, "integer") . + " GROUP BY skill_node_id, user_id" + ); + while ($rec = $ilDB->fetchAssoc($set)) { + if (isset($tref_ids[(int) $rec["skill_node_id"]])) { + $a_usages[$tref_ids[$rec["skill_node_id"]] . ":" . $rec["skill_node_id"]][ilSkillUsage::PERSONAL_SKILL][] = + array("key" => $rec["user_id"]); + } else { + $a_usages[$rec["skill_node_id"] . ":0"][ilSkillUsage::PERSONAL_SKILL][] = + array("key" => $rec["user_id"]); + } + } + } } - -?> diff --git a/Services/Skill/classes/class.ilPersonalSkillExplorerGUI.php b/Services/Skill/classes/class.ilPersonalSkillExplorerGUI.php index 28e31a3eceb2f6ce560b27cc0705da4a8521dff2..3b87285958cb3d3c28248df6eef6224cacfedc99 100644 --- a/Services/Skill/classes/class.ilPersonalSkillExplorerGUI.php +++ b/Services/Skill/classes/class.ilPersonalSkillExplorerGUI.php @@ -14,210 +14,197 @@ include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); */ class ilPersonalSkillExplorerGUI extends ilTreeExplorerGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - protected $selectable = array(); - protected $selectable_child_nodes = array(); - protected $has_selectable_nodes = false; - - /** - * Constructor - */ - public function __construct($a_parent_obj, $a_parent_cmd, $a_select_gui, $a_select_cmd, $a_select_par = "obj_id") - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - - $this->select_gui = (is_object($a_select_gui)) - ? strtolower(get_class($a_select_gui)) - : $a_select_gui; - $this->select_cmd = $a_select_cmd; - $this->select_par = $a_select_par; - - - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $this->tree = new ilSkillTree(); - $this->root_id = $this->tree->readRootId(); - - parent::__construct("pskill_sel", $a_parent_obj, $a_parent_cmd, $this->tree); - $this->setSkipRootNode(true); - - $this->all_nodes = $this->tree->getSubTree($this->tree->getNodeData($this->root_id)); - foreach ($this->all_nodes as $n) - { - $this->node[$n["child"]] = $n; - $this->child_nodes[$n["parent"]][] = $n; - $this->parent[$n["child"]] = $n["parent"]; -//echo "-$k-"; var_dump($n); - } - - -// $this->setTypeWhiteList(array("skrt", "skll", "scat", "sktr")); - $this->buildSelectableTree($this->tree->readRootId()); - } - - /** - * Set selectable nodes exist? - * - * @param bool $a_val selectable nodes exist - */ - protected function setHasSelectableNodes($a_val) - { - $this->has_selectable_nodes = $a_val; - } - - /** - * Get selectable nodes exist? - * - * @return bool selectable nodes exist - */ - function getHasSelectableNodes() - { - return $this->has_selectable_nodes; - } - - /** - * Build selectable tree - * - * @param int $a_node_id tree id - */ - function buildSelectableTree($a_node_id) - { -//echo "
                  -$a_node_id-"; - if (in_array(ilSkillTreeNode::_lookupStatus($a_node_id), array(ilSkillTreeNode::STATUS_DRAFT, ilSkillTreeNode::STATUS_OUTDATED))) - { - return; - } - - if (ilSkillTreeNode::_lookupSelfEvaluation($a_node_id)) - { - $this->selectable[$a_node_id] = true; - $cid = $a_node_id; - //$this->selectable[$this->parent[$a_node_id]] = true; - while(isset($this->parent[$cid])) - { - $this->selectable[$this->parent[$cid]] = true; - $cid = $this->parent[$cid]; - } - } - foreach ($this->getOriginalChildsOfNode($a_node_id) as $n) - { -//echo "+".$n["child"]."+"; - $this->buildSelectableTree($n["child"]); - } - if ($this->selectable[$a_node_id]) - { - $this->setHasSelectableNodes(true); - $this->selectable_child_nodes[$this->node[$a_node_id]["parent"]][] = - $this->node[$a_node_id]; - } - } - - /** - * Get childs of node (selectable tree) - * - * @param int $a_parent_id parent id - * @return array childs - */ - function getChildsOfNode($a_parent_id) - { - if (is_array($this->selectable_child_nodes[$a_parent_id])) - { - $childs = $this->selectable_child_nodes[$a_parent_id]; - $childs = ilUtil::sortArray($childs, "order_nr", "asc", true); - return $childs; - } - return array(); - } - - /** - * Get original childs of node (whole tree) - * - * @param int $a_parent_id parent id - * @return array childs - */ - function getOriginalChildsOfNode($a_parent_id) - { - if (is_array($this->child_nodes[$a_parent_id])) - { - return $this->child_nodes[$a_parent_id]; - } - return array(); - } - - /** - * Get href for node - * - * @param mixed $a_node node object/array - * @return string href attribute - */ - function getNodeHref($a_node) - { - $ilCtrl = $this->ctrl; - - $skill_id = $a_node["child"]; - - $ilCtrl->setParameterByClass($this->select_gui, $this->select_par, $skill_id); - $ret = $ilCtrl->getLinkTargetByClass($this->select_gui, $this->select_cmd); - $ilCtrl->setParameterByClass($this->select_gui, $this->select_par, ""); - - return $ret; - } - - /** - * Get node content - * - * @param array - * @return - */ - function getNodeContent($a_node) - { - $lng = $this->lng; - - // title - $title = $a_node["title"]; - - return $title; - } - - /** - * Is clickable - * - * @param - * @return - */ - function isNodeClickable($a_node) - { - if (!ilSkillTreeNode::_lookupSelfEvaluation($a_node["child"])) - { - return false; - } - return true; - } - - /** - * get image path (may be overwritten by derived classes) - */ - function getNodeIcon($a_node) - { - $t = $a_node["type"]; - if (in_array($t, array("sktr"))) - { - return ilUtil::getImagePath("icon_skll.svg"); - } - return ilUtil::getImagePath("icon_".$t.".svg"); - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + protected $selectable = array(); + protected $selectable_child_nodes = array(); + protected $has_selectable_nodes = false; + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_select_gui, $a_select_cmd, $a_select_par = "obj_id") + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + + $this->select_gui = (is_object($a_select_gui)) + ? strtolower(get_class($a_select_gui)) + : $a_select_gui; + $this->select_cmd = $a_select_cmd; + $this->select_par = $a_select_par; + + + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $this->tree = new ilSkillTree(); + $this->root_id = $this->tree->readRootId(); + + parent::__construct("pskill_sel", $a_parent_obj, $a_parent_cmd, $this->tree); + $this->setSkipRootNode(true); + + $this->all_nodes = $this->tree->getSubTree($this->tree->getNodeData($this->root_id)); + foreach ($this->all_nodes as $n) { + $this->node[$n["child"]] = $n; + $this->child_nodes[$n["parent"]][] = $n; + $this->parent[$n["child"]] = $n["parent"]; + //echo "-$k-"; var_dump($n); + } + + + // $this->setTypeWhiteList(array("skrt", "skll", "scat", "sktr")); + $this->buildSelectableTree($this->tree->readRootId()); + } + + /** + * Set selectable nodes exist? + * + * @param bool $a_val selectable nodes exist + */ + protected function setHasSelectableNodes($a_val) + { + $this->has_selectable_nodes = $a_val; + } + + /** + * Get selectable nodes exist? + * + * @return bool selectable nodes exist + */ + public function getHasSelectableNodes() + { + return $this->has_selectable_nodes; + } + + /** + * Build selectable tree + * + * @param int $a_node_id tree id + */ + public function buildSelectableTree($a_node_id) + { + //echo "
                  -$a_node_id-"; + if (in_array(ilSkillTreeNode::_lookupStatus($a_node_id), array(ilSkillTreeNode::STATUS_DRAFT, ilSkillTreeNode::STATUS_OUTDATED))) { + return; + } + + if (ilSkillTreeNode::_lookupSelfEvaluation($a_node_id)) { + $this->selectable[$a_node_id] = true; + $cid = $a_node_id; + //$this->selectable[$this->parent[$a_node_id]] = true; + while (isset($this->parent[$cid])) { + $this->selectable[$this->parent[$cid]] = true; + $cid = $this->parent[$cid]; + } + } + foreach ($this->getOriginalChildsOfNode($a_node_id) as $n) { + //echo "+".$n["child"]."+"; + $this->buildSelectableTree($n["child"]); + } + if ($this->selectable[$a_node_id]) { + $this->setHasSelectableNodes(true); + $this->selectable_child_nodes[$this->node[$a_node_id]["parent"]][] = + $this->node[$a_node_id]; + } + } + + /** + * Get childs of node (selectable tree) + * + * @param int $a_parent_id parent id + * @return array childs + */ + public function getChildsOfNode($a_parent_id) + { + if (is_array($this->selectable_child_nodes[$a_parent_id])) { + $childs = $this->selectable_child_nodes[$a_parent_id]; + $childs = ilUtil::sortArray($childs, "order_nr", "asc", true); + return $childs; + } + return array(); + } + + /** + * Get original childs of node (whole tree) + * + * @param int $a_parent_id parent id + * @return array childs + */ + public function getOriginalChildsOfNode($a_parent_id) + { + if (is_array($this->child_nodes[$a_parent_id])) { + return $this->child_nodes[$a_parent_id]; + } + return array(); + } + + /** + * Get href for node + * + * @param mixed $a_node node object/array + * @return string href attribute + */ + public function getNodeHref($a_node) + { + $ilCtrl = $this->ctrl; + + $skill_id = $a_node["child"]; + + $ilCtrl->setParameterByClass($this->select_gui, $this->select_par, $skill_id); + $ret = $ilCtrl->getLinkTargetByClass($this->select_gui, $this->select_cmd); + $ilCtrl->setParameterByClass($this->select_gui, $this->select_par, ""); + + return $ret; + } + + /** + * Get node content + * + * @param array + * @return + */ + public function getNodeContent($a_node) + { + $lng = $this->lng; + + // title + $title = $a_node["title"]; + + return $title; + } + + /** + * Is clickable + * + * @param + * @return + */ + public function isNodeClickable($a_node) + { + if (!ilSkillTreeNode::_lookupSelfEvaluation($a_node["child"])) { + return false; + } + return true; + } + + /** + * get image path (may be overwritten by derived classes) + */ + public function getNodeIcon($a_node) + { + $t = $a_node["type"]; + if (in_array($t, array("sktr"))) { + return ilUtil::getImagePath("icon_skll.svg"); + } + return ilUtil::getImagePath("icon_" . $t . ".svg"); + } } - -?> diff --git a/Services/Skill/classes/class.ilPersonalSkillTableGUI.php b/Services/Skill/classes/class.ilPersonalSkillTableGUI.php index 1d196eae318215a87a35261814620bf491fecaf3..1efdc1c988e2c15f8ab8617855c49ce4d922380d 100644 --- a/Services/Skill/classes/class.ilPersonalSkillTableGUI.php +++ b/Services/Skill/classes/class.ilPersonalSkillTableGUI.php @@ -14,76 +14,76 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilPersonalSkillTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $this->user = $DIC->user(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilAccess = $DIC->access(); - $lng = $DIC->language(); - $ilUser = $DIC->user(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - - include_once("./Services/Skill/classes/class.ilPersonalSkill.php"); - $this->setData(ilPersonalSkill::getSelectedUserSkills($ilUser->getId())); - $this->setTitle($lng->txt("skills")); - - $this->addColumn("", "", "1", true); - $this->addColumn($this->lng->txt("title"), "title"); - $this->addColumn($this->lng->txt("skmg_materials")); - $this->addColumn($this->lng->txt("actions")); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.personal_skill_row.html", "Services/Skill"); - - $this->addMultiCommand("confirmSkillRemove", $lng->txt("skmg_remove_skills")); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - // assign materials - $ilCtrl->setParameterByClass("ilpersonalskillsgui", "skill_id", $a_set["skill_node_id"]); - $this->tpl->setCurrentBlock("cmd"); - $this->tpl->setVariable("TXT_CMD", $lng->txt("skmg_assign_materials")); - $this->tpl->setVariable("HREF_CMD", - $ilCtrl->getLinkTargetByClass("ilpersonalskillsgui", "assignMaterials")); - $this->tpl->parseCurrentBlock(); - $ilCtrl->setParameterByClass("ilpersonalskillsgui", "skill_id", ""); - -//var_dump($a_set); - $this->tpl->setVariable("SKL_NODE_ID", $a_set["skill_node_id"]); - $this->tpl->setVariable("TITLE", $a_set["title"]); - } + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->user = $DIC->user(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilAccess = $DIC->access(); + $lng = $DIC->language(); + $ilUser = $DIC->user(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + + include_once("./Services/Skill/classes/class.ilPersonalSkill.php"); + $this->setData(ilPersonalSkill::getSelectedUserSkills($ilUser->getId())); + $this->setTitle($lng->txt("skills")); + + $this->addColumn("", "", "1", true); + $this->addColumn($this->lng->txt("title"), "title"); + $this->addColumn($this->lng->txt("skmg_materials")); + $this->addColumn($this->lng->txt("actions")); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.personal_skill_row.html", "Services/Skill"); + $this->addMultiCommand("confirmSkillRemove", $lng->txt("skmg_remove_skills")); + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + // assign materials + $ilCtrl->setParameterByClass("ilpersonalskillsgui", "skill_id", $a_set["skill_node_id"]); + $this->tpl->setCurrentBlock("cmd"); + $this->tpl->setVariable("TXT_CMD", $lng->txt("skmg_assign_materials")); + $this->tpl->setVariable( + "HREF_CMD", + $ilCtrl->getLinkTargetByClass("ilpersonalskillsgui", "assignMaterials") + ); + $this->tpl->parseCurrentBlock(); + $ilCtrl->setParameterByClass("ilpersonalskillsgui", "skill_id", ""); + + //var_dump($a_set); + $this->tpl->setVariable("SKL_NODE_ID", $a_set["skill_node_id"]); + $this->tpl->setVariable("TITLE", $a_set["title"]); + } } -?> diff --git a/Services/Skill/classes/class.ilPersonalSkillsFilterGUI.php b/Services/Skill/classes/class.ilPersonalSkillsFilterGUI.php index 7fa1e6797a2f0b7924eacd8643a206ec4c851d65..4b7ce951c1370793e12d16fb34970f174ffb25a9 100644 --- a/Services/Skill/classes/class.ilPersonalSkillsFilterGUI.php +++ b/Services/Skill/classes/class.ilPersonalSkillsFilterGUI.php @@ -10,161 +10,148 @@ */ class ilPersonalSkillsFilterGUI { - /** - * Constructor - */ - public function __construct() - { - global $DIC; - $this->lng = $DIC->language(); - - } - - /** - * Add to toolbar - */ - public function addToToolbar(ilToolbarGUI $toolbar, $a_include_target = true) - { - $lng = $this->lng; - - // type of formation - $options = array( - 0 => $lng->txt("skmg_all"), - ilSkillEval::TYPE_APPRAISAL => $lng->txt("skmg_eval_type_1"), - ilSkillEval::TYPE_MEASUREMENT => $lng->txt("skmg_eval_type_2"), - ilSkillEval::TYPE_SELF_EVAL => $lng->txt("skmg_eval_type_3"), - ); - $si = new ilSelectInputGUI($lng->txt("skmg_type_of_formation"), "type_of_formation"); - $si->setOptions($options); - $si->setValue(ilSession::get("skmg_pf_type_of_formation")); - $toolbar->addInputItem($si, true); - - if ($a_include_target) - { - // target level - $options = array( - 0 => $lng->txt("show"), - 1 => $lng->txt("hide") - ); - $si = new ilSelectInputGUI($lng->txt("skmg_target_level"), "target_level"); - $si->setOptions($options); - $si->setValue(ilSession::get("skmg_pf_target_level")); - $toolbar->addInputItem($si, true); - } - - // materials/ressources - $options = array( - 0 => $lng->txt("show"), - 1 => $lng->txt("hide") - ); - $si = new ilSelectInputGUI($lng->txt("skmg_materials_ressources"), "mat_res"); - $si->setOptions($options); - $si->setValue(ilSession::get("skmg_pf_mat_res")); - $toolbar->addInputItem($si, true); - - // from - $from = new ilDateTimeInputGUI($lng->txt("from"), "from"); - if (ilSession::get("skmg_pf_from") != "") - { - $from->setDate(new ilDateTime(ilSession::get("skmg_pf_from"), IL_CAL_DATETIME)); - } - $toolbar->addInputItem($from, true); - - // to - $to = new ilDateTimeInputGUI($lng->txt("to"), "to"); - if (ilSession::get("skmg_pf_to") != "") - { - $to->setDate(new ilDateTime(ilSession::get("skmg_pf_to"), IL_CAL_DATETIME)); - } - $toolbar->addInputItem($to, true); - } - - /** - * Save filter values to session - */ - public function save() - { - $from = new ilDateTimeInputGUI("", "from"); - $from->checkInput(); - $f = (is_null($from->getDate())) - ? "" - : $from->getDate()->get(IL_CAL_DATETIME); - $to = new ilDateTimeInputGUI("", "to"); - $to->checkInput(); - $t = (is_null($to->getDate())) - ? "" - : $to->getDate()->get(IL_CAL_DATETIME); - ilSession::set("skmg_pf_type_of_formation", ilUtil::stripSlashes($_POST["type_of_formation"])); - ilSession::set("skmg_pf_target_level", ilUtil::stripSlashes($_POST["target_level"])); - ilSession::set("skmg_pf_mat_res", ilUtil::stripSlashes($_POST["mat_res"])); - ilSession::set("skmg_pf_from", $f); - ilSession::set("skmg_pf_to", $t); - } - - /** - * Is entry in range? - * @param array $level_data - * @param array $level_entry - * @return bool - */ - public function isInRange($level_data, $level_entry) - { - // from - if (ilSession::get("skmg_pf_from") != "") - { - if ($level_entry["status_date"] < ilSession::get("skmg_pf_from")) - { - return false; - } - } - - // to - if (ilSession::get("skmg_pf_to") != "") - { - if ($level_entry["status_date"] > ilSession::get("skmg_pf_to")) - { - return false; - } - } - - // type - $type = ilSkillEval::TYPE_APPRAISAL; - if ($level_entry["self_eval"] == 1) - { - $type = ilSkillEval::TYPE_SELF_EVAL; - } - if ($level_entry["trigger_obj_type"] == "tst") - { - $type = ilSkillEval::TYPE_MEASUREMENT; - } - if (ilSession::get("skmg_pf_type_of_formation") > 0 && ilSession::get("skmg_pf_type_of_formation") != $type) - { - return false; - } - - - //var_dump($level_data); - //var_dump($level_entry); exit; - return true; - } - - /** - * Show target level? - * @return bool - */ - public function showTargetLevel() - { - return (int) !ilSession::get("skmg_pf_target_level"); - } - - /** - * Show materials and ressources? - * @return bool - */ - public function showMaterialsRessources() - { - return (int) !ilSession::get("skmg_pf_mat_res"); - } - - -} \ No newline at end of file + /** + * Constructor + */ + public function __construct() + { + global $DIC; + $this->lng = $DIC->language(); + } + + /** + * Add to toolbar + */ + public function addToToolbar(ilToolbarGUI $toolbar, $a_include_target = true) + { + $lng = $this->lng; + + // type of formation + $options = array( + 0 => $lng->txt("skmg_all"), + ilSkillEval::TYPE_APPRAISAL => $lng->txt("skmg_eval_type_1"), + ilSkillEval::TYPE_MEASUREMENT => $lng->txt("skmg_eval_type_2"), + ilSkillEval::TYPE_SELF_EVAL => $lng->txt("skmg_eval_type_3"), + ); + $si = new ilSelectInputGUI($lng->txt("skmg_type_of_formation"), "type_of_formation"); + $si->setOptions($options); + $si->setValue(ilSession::get("skmg_pf_type_of_formation")); + $toolbar->addInputItem($si, true); + + if ($a_include_target) { + // target level + $options = array( + 0 => $lng->txt("show"), + 1 => $lng->txt("hide") + ); + $si = new ilSelectInputGUI($lng->txt("skmg_target_level"), "target_level"); + $si->setOptions($options); + $si->setValue(ilSession::get("skmg_pf_target_level")); + $toolbar->addInputItem($si, true); + } + + // materials/ressources + $options = array( + 0 => $lng->txt("show"), + 1 => $lng->txt("hide") + ); + $si = new ilSelectInputGUI($lng->txt("skmg_materials_ressources"), "mat_res"); + $si->setOptions($options); + $si->setValue(ilSession::get("skmg_pf_mat_res")); + $toolbar->addInputItem($si, true); + + // from + $from = new ilDateTimeInputGUI($lng->txt("from"), "from"); + if (ilSession::get("skmg_pf_from") != "") { + $from->setDate(new ilDateTime(ilSession::get("skmg_pf_from"), IL_CAL_DATETIME)); + } + $toolbar->addInputItem($from, true); + + // to + $to = new ilDateTimeInputGUI($lng->txt("to"), "to"); + if (ilSession::get("skmg_pf_to") != "") { + $to->setDate(new ilDateTime(ilSession::get("skmg_pf_to"), IL_CAL_DATETIME)); + } + $toolbar->addInputItem($to, true); + } + + /** + * Save filter values to session + */ + public function save() + { + $from = new ilDateTimeInputGUI("", "from"); + $from->checkInput(); + $f = (is_null($from->getDate())) + ? "" + : $from->getDate()->get(IL_CAL_DATETIME); + $to = new ilDateTimeInputGUI("", "to"); + $to->checkInput(); + $t = (is_null($to->getDate())) + ? "" + : $to->getDate()->get(IL_CAL_DATETIME); + ilSession::set("skmg_pf_type_of_formation", ilUtil::stripSlashes($_POST["type_of_formation"])); + ilSession::set("skmg_pf_target_level", ilUtil::stripSlashes($_POST["target_level"])); + ilSession::set("skmg_pf_mat_res", ilUtil::stripSlashes($_POST["mat_res"])); + ilSession::set("skmg_pf_from", $f); + ilSession::set("skmg_pf_to", $t); + } + + /** + * Is entry in range? + * @param array $level_data + * @param array $level_entry + * @return bool + */ + public function isInRange($level_data, $level_entry) + { + // from + if (ilSession::get("skmg_pf_from") != "") { + if ($level_entry["status_date"] < ilSession::get("skmg_pf_from")) { + return false; + } + } + + // to + if (ilSession::get("skmg_pf_to") != "") { + if ($level_entry["status_date"] > ilSession::get("skmg_pf_to")) { + return false; + } + } + + // type + $type = ilSkillEval::TYPE_APPRAISAL; + if ($level_entry["self_eval"] == 1) { + $type = ilSkillEval::TYPE_SELF_EVAL; + } + if ($level_entry["trigger_obj_type"] == "tst") { + $type = ilSkillEval::TYPE_MEASUREMENT; + } + if (ilSession::get("skmg_pf_type_of_formation") > 0 && ilSession::get("skmg_pf_type_of_formation") != $type) { + return false; + } + + + //var_dump($level_data); + //var_dump($level_entry); exit; + return true; + } + + /** + * Show target level? + * @return bool + */ + public function showTargetLevel() + { + return (int) !ilSession::get("skmg_pf_target_level"); + } + + /** + * Show materials and ressources? + * @return bool + */ + public function showMaterialsRessources() + { + return (int) !ilSession::get("skmg_pf_mat_res"); + } +} diff --git a/Services/Skill/classes/class.ilPersonalSkillsGUI.php b/Services/Skill/classes/class.ilPersonalSkillsGUI.php index b8cbbcf08d4280fdeef20be499d1480359a11bbe..33bfd93d7a754caed568273e7f290824ea971a29 100644 --- a/Services/Skill/classes/class.ilPersonalSkillsGUI.php +++ b/Services/Skill/classes/class.ilPersonalSkillsGUI.php @@ -20,379 +20,375 @@ class ilPersonalSkillsGUI const LIST_SELECTED = ""; const LIST_PROFILES = "profiles"; - protected $offline_mode; - protected $skill_tree; - static $skill_tt_cnt = 1; - protected $actual_levels = array(); - protected $gap_self_eval_levels = array(); - protected $mode = ""; - protected $history_view = false; - protected $trigger_objects_filter = array(); - protected $intro_text = ""; - protected $hidden_skills = array(); - - /** - * @var \ILIAS\DI\UIServices - */ - protected $ui; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var mixed - */ - protected $help; - - /** - * @var mixed - */ - protected $setting; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var mixed - */ - protected $tpl; - - /** - * @var ilLanguage - */ - protected $tabs; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var \ILIAS\UI\Factory - */ - protected $ui_fac; - - /** - * @var \ILIAS\UI\Renderer - */ - protected $ui_ren; - protected $obj_id = 0; - protected $obj_skills = array(); - - /** - * @var ilPersonalSkillsFilterGUI - */ - protected $filter; + protected $offline_mode; + protected $skill_tree; + public static $skill_tt_cnt = 1; + protected $actual_levels = array(); + protected $gap_self_eval_levels = array(); + protected $mode = ""; + protected $history_view = false; + protected $trigger_objects_filter = array(); + protected $intro_text = ""; + protected $hidden_skills = array(); + + /** + * @var \ILIAS\DI\UIServices + */ + protected $ui; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var mixed + */ + protected $help; + + /** + * @var mixed + */ + protected $setting; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var mixed + */ + protected $tpl; + + /** + * @var ilLanguage + */ + protected $tabs; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var \ILIAS\UI\Factory + */ + protected $ui_fac; + + /** + * @var \ILIAS\UI\Renderer + */ + protected $ui_ren; + protected $obj_id = 0; + protected $obj_skills = array(); + + /** + * @var ilPersonalSkillsFilterGUI + */ + protected $filter; /** * @var string */ - protected $list_mode = self::LIST_SELECTED; - - /** - * Contructor - * - * @access public - */ - public function __construct() - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->help = $DIC["ilHelp"]; - $this->setting = $DIC["ilSetting"]; - $this->user = $DIC->user(); - $this->tpl = $DIC["tpl"]; - $this->tabs = $DIC->tabs(); - $this->toolbar = $DIC->toolbar(); - $this->access = $DIC->access(); - $this->ui_fac = $DIC->ui()->factory(); - $this->ui_ren = $DIC->ui()->renderer(); - $this->ui = $DIC->ui(); - - $ilCtrl = $this->ctrl; - $ilHelp = $this->help; - $lng = $this->lng; - $ilSetting = $this->setting; - - - $lng->loadLanguageModule('skmg'); - $ilHelp->setScreenIdComponent("skill"); - - $ilCtrl->saveParameter($this, "skill_id"); - $ilCtrl->saveParameter($this, "tref_id"); - $ilCtrl->saveParameter($this, "profile_id"); - $ilCtrl->saveParameter($this, "list_mode"); - - $this->list_mode = $_GET["list_mode"]; - - $this->user_profiles = ilSkillProfile::getProfilesOfUser($this->user->getId()); - - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $this->skill_tree = new ilSkillTree(); - - $this->use_materials = !$ilSetting->get("disable_personal_workspace"); - - include_once("./Services/Skill/classes/class.ilSkillManagementSettings.php"); - $this->skmg_settings = new ilSkillManagementSettings(); - - $this->filter = new ilPersonalSkillsFilterGUI(); - - } - - /** - * Get filter - * - * @return ilPersonalSkillsFilterGUI - */ - protected function getFilter() - { - return $this->filter; - } - - - /** - * Set profile id - * - * @param $a_val - */ - function setProfileId($a_val) - { - $this->profile_id = $a_val; - } - - /** - * Get profile id - * - * @return - */ - function getProfileId() - { - return $this->profile_id; - } - - /** - * Set self evaluation levels for gap analysis - * - * @param array $a_val self evaluation values key1: base_skill_id, key2: tref_id: value: level id - */ - function setGapAnalysisSelfEvalLevels(array $a_val) - { - $this->gap_self_eval_levels = $a_val; - } - - /** - * Get self evaluation levels for gap analysis - * - * @return array self evaluation values key1: base_skill_id, key2: tref_id: value: level id - */ - function getGapAnalysisSelfEvalLevels() - { - return $this->gap_self_eval_levels; - } - - /** - * Set history view - * - * @param bool $a_val history view - */ - function setHistoryView($a_val) - { - $this->history_view = $a_val; - } - - /** - * Get history view - * - * @return bool history view - */ - function getHistoryView() - { - return $this->history_view; - } - - /** - * @return array - */ - public function getTriggerObjectsFilter() - { - return $this->trigger_objects_filter; - } - - /** - * @param array $trigger_objects_filter - */ - public function setTriggerObjectsFilter($trigger_objects_filter) - { - $this->trigger_objects_filter = $trigger_objects_filter; - } - - /** - * Set intro text - * - * @param string $a_val intro text html - */ - function setIntroText($a_val) - { - $this->intro_text = $a_val; - } - - /** - * Get intro text - * - * @return string intro text html - */ - function getIntroText() - { - return $this->intro_text; - } - - /** - * Hide skill - * - * @param - * @return - */ - function hideSkill($a_skill_id, $a_tref_id = 0) - { - $this->hidden_skills[] = $a_skill_id.":".$a_tref_id; - } - - /** - * Determine current profile id - * - * @param - * @return - */ - function determineCurrentProfile() - { - $ilCtrl = $this->ctrl; - - if (count($this->user_profiles) == 0) - { - return; - } - $current_prof_id = 0; - if ((int) $_GET["profile_id"] > 0) - { - foreach ($this->user_profiles as $p) - { - if ($p["id"] == (int) $_GET["profile_id"]) - { - $current_prof_id = (int) $_GET["profile_id"]; - } - } - } - - if ($current_prof_id == 0 && !(is_array($this->obj_skills) && $this->obj_id > 0)) - { - $current_prof_id = $this->user_profiles[0]["id"]; - } - $ilCtrl->setParameter($this, "profile_id", $current_prof_id); - $this->setProfileId($current_prof_id); - } - - /** - * Set object skills - * - * @param int $a_obj_id object id - * @param array $a_skills skills array - */ - function setObjectSkills($a_obj_id, $a_skills = null) - { - $this->obj_id = $a_obj_id; - $this->obj_skills = $a_skills; - } - - /** - * Execute command - * - * @access public - * - */ - public function executeCommand() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - $lng = $this->lng; - $tpl = $this->tpl; - - $next_class = $ilCtrl->getNextClass($this); - - - // determin standard command - $std_cmd = "listSkills"; - - $cmd = $ilCtrl->getCmd($std_cmd); - - //$tpl->setTitle($lng->txt("skills")); - //$tpl->setTitleIcon(ilUtil::getImagePath("icon_skmg.svg")); - - switch($next_class) - { - default: - $this->$cmd(); - break; - } - return true; - } - - /** - * Set tabs - */ - function setTabs($a_activate) - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilTabs = $this->tabs; - - // list skills + protected $list_mode = self::LIST_SELECTED; + + /** + * Contructor + * + * @access public + */ + public function __construct() + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->help = $DIC["ilHelp"]; + $this->setting = $DIC["ilSetting"]; + $this->user = $DIC->user(); + $this->tpl = $DIC["tpl"]; + $this->tabs = $DIC->tabs(); + $this->toolbar = $DIC->toolbar(); + $this->access = $DIC->access(); + $this->ui_fac = $DIC->ui()->factory(); + $this->ui_ren = $DIC->ui()->renderer(); + $this->ui = $DIC->ui(); + + $ilCtrl = $this->ctrl; + $ilHelp = $this->help; + $lng = $this->lng; + $ilSetting = $this->setting; + + + $lng->loadLanguageModule('skmg'); + $ilHelp->setScreenIdComponent("skill"); + + $ilCtrl->saveParameter($this, "skill_id"); + $ilCtrl->saveParameter($this, "tref_id"); + $ilCtrl->saveParameter($this, "profile_id"); + $ilCtrl->saveParameter($this, "list_mode"); + + $this->list_mode = $_GET["list_mode"]; + + $this->user_profiles = ilSkillProfile::getProfilesOfUser($this->user->getId()); + + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $this->skill_tree = new ilSkillTree(); + + $this->use_materials = !$ilSetting->get("disable_personal_workspace"); + + include_once("./Services/Skill/classes/class.ilSkillManagementSettings.php"); + $this->skmg_settings = new ilSkillManagementSettings(); + + $this->filter = new ilPersonalSkillsFilterGUI(); + } + + /** + * Get filter + * + * @return ilPersonalSkillsFilterGUI + */ + protected function getFilter() + { + return $this->filter; + } + + + /** + * Set profile id + * + * @param $a_val + */ + public function setProfileId($a_val) + { + $this->profile_id = $a_val; + } + + /** + * Get profile id + * + * @return + */ + public function getProfileId() + { + return $this->profile_id; + } + + /** + * Set self evaluation levels for gap analysis + * + * @param array $a_val self evaluation values key1: base_skill_id, key2: tref_id: value: level id + */ + public function setGapAnalysisSelfEvalLevels(array $a_val) + { + $this->gap_self_eval_levels = $a_val; + } + + /** + * Get self evaluation levels for gap analysis + * + * @return array self evaluation values key1: base_skill_id, key2: tref_id: value: level id + */ + public function getGapAnalysisSelfEvalLevels() + { + return $this->gap_self_eval_levels; + } + + /** + * Set history view + * + * @param bool $a_val history view + */ + public function setHistoryView($a_val) + { + $this->history_view = $a_val; + } + + /** + * Get history view + * + * @return bool history view + */ + public function getHistoryView() + { + return $this->history_view; + } + + /** + * @return array + */ + public function getTriggerObjectsFilter() + { + return $this->trigger_objects_filter; + } + + /** + * @param array $trigger_objects_filter + */ + public function setTriggerObjectsFilter($trigger_objects_filter) + { + $this->trigger_objects_filter = $trigger_objects_filter; + } + + /** + * Set intro text + * + * @param string $a_val intro text html + */ + public function setIntroText($a_val) + { + $this->intro_text = $a_val; + } + + /** + * Get intro text + * + * @return string intro text html + */ + public function getIntroText() + { + return $this->intro_text; + } + + /** + * Hide skill + * + * @param + * @return + */ + public function hideSkill($a_skill_id, $a_tref_id = 0) + { + $this->hidden_skills[] = $a_skill_id . ":" . $a_tref_id; + } + + /** + * Determine current profile id + * + * @param + * @return + */ + public function determineCurrentProfile() + { + $ilCtrl = $this->ctrl; + + if (count($this->user_profiles) == 0) { + return; + } + $current_prof_id = 0; + if ((int) $_GET["profile_id"] > 0) { + foreach ($this->user_profiles as $p) { + if ($p["id"] == (int) $_GET["profile_id"]) { + $current_prof_id = (int) $_GET["profile_id"]; + } + } + } + + if ($current_prof_id == 0 && !(is_array($this->obj_skills) && $this->obj_id > 0)) { + $current_prof_id = $this->user_profiles[0]["id"]; + } + $ilCtrl->setParameter($this, "profile_id", $current_prof_id); + $this->setProfileId($current_prof_id); + } + + /** + * Set object skills + * + * @param int $a_obj_id object id + * @param array $a_skills skills array + */ + public function setObjectSkills($a_obj_id, $a_skills = null) + { + $this->obj_id = $a_obj_id; + $this->obj_skills = $a_skills; + } + + /** + * Execute command + * + * @access public + * + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + $lng = $this->lng; + $tpl = $this->tpl; + + $next_class = $ilCtrl->getNextClass($this); + + + // determin standard command + $std_cmd = "listSkills"; + + $cmd = $ilCtrl->getCmd($std_cmd); + + //$tpl->setTitle($lng->txt("skills")); + //$tpl->setTitleIcon(ilUtil::getImagePath("icon_skmg.svg")); + + switch ($next_class) { + default: + $this->$cmd(); + break; + } + return true; + } + + /** + * Set tabs + */ + public function setTabs($a_activate) + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilTabs = $this->tabs; + + // list skills $ilCtrl->setParameter($this, "list_mode", self::LIST_SELECTED); - $ilTabs->addSubTab("list_skills", - $lng->txt("skmg_selected_skills"), - $ilCtrl->getLinkTarget($this, "render")); + $ilTabs->addSubTab( + "list_skills", + $lng->txt("skmg_selected_skills"), + $ilCtrl->getLinkTarget($this, "render") + ); - if (count($this->user_profiles) > 0) - { + if (count($this->user_profiles) > 0) { $ilCtrl->setParameter($this, "list_mode", self::LIST_PROFILES); - $ilTabs->addSubTab("profile", - $lng->txt("skmg_assigned_profiles"), - $ilCtrl->getLinkTarget($this, "render")); - } + $ilTabs->addSubTab( + "profile", + $lng->txt("skmg_assigned_profiles"), + $ilCtrl->getLinkTarget($this, "render") + ); + } $ilCtrl->clearParameterByClass(get_class($this), "list_mode"); - // assign materials + // assign materials - $ilTabs->activateSubTab($a_activate); - } - - function setOfflineMode($a_file_path) - { - $this->offline_mode = $a_file_path; - } + $ilTabs->activateSubTab($a_activate); + } + + public function setOfflineMode($a_file_path) + { + $this->offline_mode = $a_file_path; + } /** * Render */ protected function render() { - switch($this->list_mode) { + switch ($this->list_mode) { case self::LIST_PROFILES: $this->listAssignedProfile(); break; @@ -404,1648 +400,1530 @@ class ilPersonalSkillsGUI } - /** - * List skills - */ - function listSkills() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - $lng = $this->lng; - $main_tpl = $this->tpl; - $ilToolbar = $this->toolbar; - - $tpl = new ilTemplate("tpl.skill_filter.html", true, true, "Services/Skill"); - - $this->setTabs("list_skills"); - - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $stree = new ilSkillTree(); - - // skill selection / add new personal skill - $ilToolbar->addFormButton($lng->txt("skmg_add_skill"), - "listSkillsForAdd"); - $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); - - $filter_toolbar = new ilToolbarGUI(); - $filter_toolbar->setFormAction($ilCtrl->getFormAction($this)); - $this->getFilter()->addToToolbar($filter_toolbar, false); - - $skills = ilPersonalSkill::getSelectedUserSkills($ilUser->getId()); - $html = ""; - foreach ($skills as $s) - { - $path = $stree->getSkillTreePath($s["skill_node_id"]); - - // check draft - foreach ($path as $p) - { - if ($p["status"] == ilSkillTreeNode::STATUS_DRAFT) - { - continue(2); - } - } - $html.= $this->getSkillHTML($s["skill_node_id"], 0, true); - } - - // list skills -// include_once("./Services/Skill/classes/class.ilPersonalSkillTableGUI.php"); -// $sktab = new ilPersonalSkillTableGUI($this, "listSkills"); - - if ($html != "") - { - $filter_toolbar->addFormButton($this->lng->txt("skmg_refresh_view"), "applyFilter"); - $tpl->setVariable("FILTER", $filter_toolbar->getHTML()); - $html = $tpl->get().$html; - } - - $main_tpl->setContent($html); - - } - - /** - * Apply filter - */ - protected function applyFilter() - { - $this->getFilter()->save(); - $this->ctrl->redirect($this, "listSkills"); - } - - /** - * Apply filter for profiles view - */ - protected function applyFilterAssignedProfiles() - { - $this->getFilter()->save(); - $this->ctrl->redirect($this, "listAssignedProfile"); - } - - - /** - * Get skill presentation HTML - * - * $a_top_skill_id is a node of the skill "main tree", it can be a tref id! - * - called in listSkills (this class) -> $a_top_skill is the selected user skill (main tree node id), tref_id not set - * - called in ilPortfolioPage -> $a_top_skill is the selected user skill (main tree node id), tref_id not set - * - called in getGapAnalysis (this class) -> $a_top_skill id is the (basic) skill_id, tref_id may be set - */ - function getSkillHTML($a_top_skill_id, $a_user_id = 0, $a_edit = false, $a_tref_id = 0) - { - // user interface plugin slot + default rendering - include_once("./Services/UIComponent/classes/class.ilUIHookProcessor.php"); - $uip = new ilUIHookProcessor("Services/Skill", "personal_skill_html", - array("personal_skills_gui" => $this, "top_skill_id" => $a_top_skill_id, "user_id" => $a_user_id, - "edit" => $a_edit, "tref_id" => $a_tref_id)); - if (!$uip->replaced()) - { - $skill_html = $this->renderSkillHTML($a_top_skill_id, $a_user_id, $a_edit, $a_tref_id); - } - $skill_html = $uip->getHTML($skill_html); - - return $skill_html; - } - - /** - * Render skill html - * - * @param - * @return - */ - function renderSkillHTML($a_top_skill_id, $a_user_id = 0, $a_edit = false, $a_tref_id = 0) - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - $lng = $this->lng; - - $sub_panels = array(); - - if ($a_user_id == 0) - { - $user = $ilUser; - } - else - { - $user = new ilObjUser($a_user_id); - } - - $tpl = new ilTemplate("tpl.skill_pres.html", true, true, "Services/Skill"); - - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $stree = new ilSkillTree(); - - include_once("./Services/Skill/classes/class.ilVirtualSkillTree.php"); - $vtree = new ilVirtualSkillTree(); - $tref_id = $a_tref_id; - $skill_id = $a_top_skill_id; - if (ilSkillTreeNode::_lookupType($a_top_skill_id) == "sktr") - { - include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); - $tref_id = $a_top_skill_id; - $skill_id = ilSkillTemplateReference::_lookupTemplateId($a_top_skill_id); - } - $b_skills = $vtree->getSubTreeForCSkillId($skill_id.":".$tref_id, true); - - foreach ($b_skills as $bs) - { - $bs["id"] = $bs["skill_id"]; - $bs["tref"] = $bs["tref_id"]; - - $path = $stree->getSkillTreePath($bs["id"], $bs["tref"]); - - $panel_comps = array(); - - - // check draft - foreach ($path as $p) - { - if ($p["status"] == ilSkillTreeNode::STATUS_DRAFT) - { - continue(2); - } - } - reset($path); - - $skill = ilSkillTreeNodeFactory::getInstance($bs["id"]); - $level_data = $skill->getLevelData(); - - - // skill description - $panel_comps[] = $this->ui_fac->legacy($this->getSkillDescription($skill)); - - - if ($this->getProfileId() > 0) - { - if (!$this->skmg_settings->getHideProfileBeforeSelfEval() || - ilBasicSkill::hasSelfEvaluated($user->getId(), $bs["id"], $bs["tref"])) - { - if ($this->getFilter()->showTargetLevel()) - { - $panel_comps[] = $this->ui_fac->legacy($this->getProfileTargetItem($this->getProfileId(), $level_data, $bs["tref"])); - } - } - } - - if ($this->mode == "gap" && !$this->history_view) - { - $panel_comps[] = $this->ui_fac->legacy($this->getActualGapItem($level_data, $bs["tref"]).""); - $panel_comps[] = $this->ui_fac->legacy($this->getSelfEvalGapItem($level_data, $bs["tref"]).""); - } - else - { - // get date of self evaluation - $se_date = ilPersonalSkill::getSelfEvaluationDate($user->getId(), $a_top_skill_id, $bs["tref"], $bs["id"]); - $se_rendered = ($se_date == "") - ? true - : false; - - // get all object triggered entries and render them - foreach ($skill->getAllHistoricLevelEntriesOfUser($bs["tref"] , $user->getId(), ilBasicSkill::EVAL_BY_ALL) as $level_entry) - { - if( count($this->getTriggerObjectsFilter()) && !in_array($level_entry['trigger_obj_id'], $this->getTriggerObjectsFilter()) ) - { - continue; - } - - // render the self evaluation at the correct position within the list of object triggered entries - if ($se_date > $level_entry["status_date"] && !$se_rendered) - { - $se_rendered = true; - } - if ($this->getFilter()->isInRange($level_data, $level_entry)) - { - $panel_comps[] = $this->ui_fac->legacy($this->getEvalItem($level_data, $level_entry)); - } - } - - } - - // materials (new) - if ($this->mode != "gap") - { - if ($this->getFilter()->showMaterialsRessources() && $this->use_materials) - { - $mat = $this->getMaterials($level_data, $bs["tref"], $user->getId()); - } - if ($mat != "") - { - $panel_comps[] = $this->ui_fac->legacy($mat); - } - } - - // suggested resources - if ($this->getFilter()->showMaterialsRessources()) - { - $sugg = $this->getSuggestedResources($this->getProfileId(), $level_data, $bs["id"], $bs["tref"]); - } - if ($sugg != "") - { - $panel_comps[] = $this->ui_fac->legacy($sugg); - } - - $title = $sep = ""; - $found = false; - foreach ($path as $p) - { - if ($found) - { - $title.= $sep.$p["title"]; - $sep = " > "; - } - if ($a_top_skill_id == $p["child"]) - { - $found = true; - } - } - - $sub = $this->ui_fac->panel()->sub((string) $title, $panel_comps); - if ($a_edit) - { - $actions = array(); - $ilCtrl->setParameterByClass("ilpersonalskillsgui", "skill_id", $a_top_skill_id); - $ilCtrl->setParameterByClass("ilpersonalskillsgui", "tref_id", $bs["tref"]); - $ilCtrl->setParameterByClass("ilpersonalskillsgui", "basic_skill_id", $bs["id"]); - if ($this->use_materials) - { - $actions[] = $this->ui_fac->button()->shy($lng->txt('skmg_assign_materials'), - $ilCtrl->getLinkTargetByClass("ilpersonalskillsgui", "assignMaterials")); - } - $actions[] = $this->ui_fac->button()->shy($lng->txt('skmg_self_evaluation'), - $ilCtrl->getLinkTargetByClass("ilpersonalskillsgui", "selfEvaluation")); - $sub = $sub->withActions($this->ui_fac->dropdown()->standard($actions)->withLabel($lng->txt("actions"))); - } - - $sub_panels[] = $sub; - - $tpl->parseCurrentBlock(); - - } - - $panel = $this->ui_fac->panel()->standard((string) ilSkillTreeNode::_lookupTitle($skill_id, $tref_id), - $sub_panels); - - if ($a_edit && $this->getProfileId() == 0) - { - $actions = array(); - - $ilCtrl->setParameterByClass("ilpersonalskillsgui", "skill_id", $a_top_skill_id); - $actions[] = $this->ui_fac->button()->shy($lng->txt('skmg_remove_skill'), - $ilCtrl->getLinkTargetByClass("ilpersonalskillsgui", "confirmSkillRemove")); - - $panel = $panel->withActions($this->ui_fac->dropdown()->standard($actions)->withLabel($lng->txt("actions"))); - } - - return $this->ui_ren->render($panel); - } - - - /** - * Get material file name and goto url - * - * @param int $a_wsp_id - * @return array caption, url - */ - function getMaterialInfo($a_wsp_id, $a_user_id) - { - if(!$this->ws_tree) - { - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; - $this->ws_tree = new ilWorkspaceTree($a_user_id); - $this->ws_access = new ilWorkspaceAccessHandler($caption); - } - - $obj_id = $this->ws_tree->lookupObjectId($a_wsp_id); - $caption = ilObject::_lookupTitle($obj_id); - - if(!$this->offline_mode) - { - $url = $this->ws_access->getGotoLink($a_wsp_id, $obj_id); - } - else - { - $url = $this->offline_mode."file_".$obj_id."/"; - - // all possible material types for now - switch(ilObject::_lookupType($obj_id)) - { - case "tstv": - include_once "Modules/Test/classes/class.ilObjTestVerification.php"; - $obj = new ilObjTestVerification($obj_id, false); - $url .= $obj->getOfflineFilename(); - break; - - case "excv": - include_once "Modules/Exercise/classes/class.ilObjExerciseVerification.php"; - $obj = new ilObjExerciseVerification($obj_id, false); - $url .= $obj->getOfflineFilename(); - break; - - case "crsv": - include_once "Modules/Course/classes/Verification/class.ilObjCourseVerification.php"; - $obj = new ilObjCourseVerification($obj_id, false); - $url .= $obj->getOfflineFilename(); - break; - - case "scov": - include_once "Modules/ScormAicc/classes/Verification/class.ilObjSCORMVerification.php"; - $obj = new ilObjSCORMVerification($obj_id, false); - $url .= $obj->getOfflineFilename(); - break; - - case "file": - $file = new ilObjFile($obj_id, false); - $url .= $file->getFilename(); - break; - } - } - - return array($caption, $url); - } - - /** - * Add personal skill - */ - function addSkill() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - $lng = $this->lng; - - ilPersonalSkill::addPersonalSkill($ilUser->getId(), (int) $_GET["obj_id"]); - - ilUtil::sendSuccess($lng->txt("msg_object_modified")); - $ilCtrl->redirect($this, "listSkills"); - } - - - - /** - * Confirm skill remove - */ - function confirmSkillRemove() - { - $lng = $this->lng; - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - - include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); - if ($_GET["skill_id"] > 0) - { - $_POST["id"][] = $_GET["skill_id"]; - } - if (!is_array($_POST["id"]) || count($_POST["id"]) == 0) - { - ilUtil::sendInfo($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "listSkills"); - } - else - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("skmg_really_remove_skills")); - $cgui->setCancel($lng->txt("cancel"), "listSkills"); - $cgui->setConfirm($lng->txt("remove"), "removeSkills"); - - foreach ($_POST["id"] as $i) - { - $cgui->addItem("id[]", $i, ilSkillTreeNode::_lookupTitle($i)); - } - - $tpl->setContent($cgui->getHTML()); - } - } - - /** - * Remove skills - */ - function removeSkills() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - $lng = $this->lng; - - if (is_array($_POST["id"])) - { - foreach ($_POST["id"] as $n_id) - { - ilPersonalSkill::removeSkill($ilUser->getId(), $n_id); - } - } - - ilUtil::sendSuccess($lng->txt("msg_object_modified")); - $ilCtrl->redirect($this, "listSkills"); - } - - - // - // Materials assignments - // - - /** - * Assign materials to skill levels - * - * @param - * @return - */ - function assignMaterials() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $ilTabs = $this->tabs; - - - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTarget($this, "render")); - - $ilCtrl->saveParameter($this, "skill_id"); - $ilCtrl->saveParameter($this, "basic_skill_id"); - $ilCtrl->saveParameter($this, "tref_id"); - - include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); - $tpl->setTitle(ilSkillTreeNode::_lookupTitle((int) $_GET["skill_id"])); - $tpl->setTitleIcon(ilUtil::getImagePath("icon_". - ilSkillTreeNode::_lookupType((int) $_GET["skill_id"]). - ".svg")); - - // basic skill selection - include_once("./Services/Skill/classes/class.ilVirtualSkillTree.php"); - $vtree = new ilVirtualSkillTree(); - $tref_id = 0; - $skill_id = (int) $_GET["skill_id"]; - if (ilSkillTreeNode::_lookupType((int) $_GET["skill_id"]) == "sktr") - { - include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); - $tref_id = $_GET["skill_id"]; - $skill_id = ilSkillTemplateReference::_lookupTemplateId($_GET["skill_id"]); - } - $bs = $vtree->getSubTreeForCSkillId($skill_id.":".$tref_id, true); - - $options = array(); - foreach ($bs as $b) - { - //$options[$b["id"]] = ilSkillTreeNode::_lookupTitle($b["id"]); - $options[$b["skill_id"]] = ilSkillTreeNode::_lookupTitle($b["skill_id"]); - } - - $cur_basic_skill_id = ((int) $_POST["basic_skill_id"] > 0) - ? (int) $_POST["basic_skill_id"] - : (((int) $_GET["basic_skill_id"] > 0) - ? (int) $_GET["basic_skill_id"] - : key($options)); - - $ilCtrl->setParameter($this, "basic_skill_id", $cur_basic_skill_id); - - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $si = new ilSelectInputGUI($lng->txt("skmg_skill"), "basic_skill_id"); - $si->setOptions($options); - $si->setValue($cur_basic_skill_id); - $ilToolbar->addInputItem($si, true); - $ilToolbar->addFormButton($lng->txt("select"), - "assignMaterials"); - - $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); - - // table - include_once("./Services/Skill/classes/class.ilSkillAssignMaterialsTableGUI.php"); - $tab = new ilSkillAssignMaterialsTableGUI($this, "assignMaterials", - (int) $_GET["skill_id"], (int) $_GET["tref_id"], $cur_basic_skill_id); - - $tpl->setContent($tab->getHTML()); - - } - - - /** - * Assign materials to skill level - * - * @param - * @return - */ - function assignMaterial() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - $lng = $this->lng; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - $ilSetting = $this->setting; - $ui = $this->ui; - - if(!$ilSetting->get("disable_personal_workspace")) - { - $url = 'ilias.php?baseClass=ilPersonalDesktopGUI&cmd=jumpToWorkspace'; - $mbox = $ui->factory()->messageBox()->info($lng->txt("skmg_ass_materials_from_workspace")) - ->withLinks([$ui->factory()->link()->standard($lng->txt("personal_workspace"), - $url)]); - $message = $ui->renderer()->render($mbox); - } - - $ilCtrl->saveParameter($this, "skill_id"); - $ilCtrl->saveParameter($this, "level_id"); - $ilCtrl->saveParameter($this, "tref_id"); - $ilCtrl->saveParameter($this, "basic_skill_id"); - - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTarget($this, "assignMaterials")); - - - include_once("./Services/PersonalWorkspace/classes/class.ilWorkspaceExplorerGUI.php"); - $exp = new ilWorkspaceExplorerGUI($ilUser->getId(), $this, "assignMaterial", $this, ""); - $exp->setTypeWhiteList(array("blog", "wsrt", "wfld", "file", "tstv", "excv")); - $exp->setSelectableTypes(array("file", "tstv", "excv")); - $exp->setSelectMode("wsp_id", true); - if ($exp->handleCommand()) - { - return; - } - - // fill template - $mtpl = new ilTemplate("tpl.materials_selection.html", true, true, "Services/Skill"); - $mtpl->setVariable("EXP", $exp->getHTML()); - - // toolbars - $tb = new ilToolbarGUI(); - $tb->addFormButton($lng->txt("select"), - "selectMaterial"); - $tb->setFormAction($ilCtrl->getFormAction($this)); - $tb->setOpenFormTag(true); - $tb->setCloseFormTag(false); - $mtpl->setVariable("TOOLBAR1", $tb->getHTML()); - $tb->setOpenFormTag(false); - $tb->setCloseFormTag(true); - $mtpl->setVariable("TOOLBAR2", $tb->getHTML()); - - $tpl->setContent($message.$mtpl->get()); - } - - /** - * Select material - */ - function selectMaterial() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - $lng = $this->lng; - - - include_once("./Services/Skill/classes/class.ilPersonalSkill.php"); - if (is_array($_POST["wsp_id"])) - { - foreach ($_POST["wsp_id"] as $w) - { - ilPersonalSkill::assignMaterial($ilUser->getId(), (int) $_GET["skill_id"], - (int) $_GET["tref_id"], - (int) $_GET["basic_skill_id"], (int) $_GET["level_id"], (int) $w); - } - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - } - - $ilCtrl->saveParameter($this, "skill_id"); - $ilCtrl->saveParameter($this, "level_id"); - $ilCtrl->saveParameter($this, "tref_id"); - $ilCtrl->saveParameter($this, "basic_skill_id"); - - $ilCtrl->redirect($this, "assignMaterials"); - } - - - /** - * Remove material - */ - function removeMaterial() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - $lng = $this->lng; - - - ilPersonalSkill::removeMaterial($ilUser->getId(), (int) $_GET["tref_id"], - (int) $_GET["level_id"], - (int) $_GET["wsp_id"]); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "assignMaterials"); - } - - - // - // Self evaluation - // - - /** - * Assign materials to skill levels - * - * @param - * @return - */ - function selfEvaluation() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $ilTabs = $this->tabs; - - - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTarget($this, "render")); - - $ilCtrl->saveParameter($this, "skill_id"); - $ilCtrl->saveParameter($this, "basic_skill_id"); - $ilCtrl->saveParameter($this, "tref_id"); - - include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); - $tpl->setTitle(ilSkillTreeNode::_lookupTitle((int) $_GET["skill_id"])); - $tpl->setTitleIcon(ilUtil::getImagePath("icon_". - ilSkillTreeNode::_lookupType((int) $_GET["skill_id"]). - ".svg")); - - // basic skill selection - include_once("./Services/Skill/classes/class.ilVirtualSkillTree.php"); - $vtree = new ilVirtualSkillTree(); - $tref_id = 0; - $skill_id = (int) $_GET["skill_id"]; - if (ilSkillTreeNode::_lookupType((int) $_GET["skill_id"]) == "sktr") - { - include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); - $tref_id = $_GET["skill_id"]; - $skill_id = ilSkillTemplateReference::_lookupTemplateId($_GET["skill_id"]); - } - $bs = $vtree->getSubTreeForCSkillId($skill_id.":".$tref_id, true); - - - $options = array(); - foreach ($bs as $b) - { - $options[$b["skill_id"]] = ilSkillTreeNode::_lookupTitle($b["skill_id"]); - } - - $cur_basic_skill_id = ((int) $_POST["basic_skill_id"] > 0) - ? (int) $_POST["basic_skill_id"] - : (((int) $_GET["basic_skill_id"] > 0) - ? (int) $_GET["basic_skill_id"] - : key($options)); - - $ilCtrl->setParameter($this, "basic_skill_id", $cur_basic_skill_id); - - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $si = new ilSelectInputGUI($lng->txt("skmg_skill"), "basic_skill_id"); - $si->setOptions($options); - $si->setValue($cur_basic_skill_id); - $ilToolbar->addInputItem($si, true); - $ilToolbar->addFormButton($lng->txt("select"), - "selfEvaluation"); - - $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); - - // table - include_once("./Services/Skill/classes/class.ilSelfEvaluationSimpleTableGUI.php"); - $tab = new ilSelfEvaluationSimpleTableGUI($this, "selfEvaluation", - (int) $_GET["skill_id"], (int) $_GET["tref_id"], $cur_basic_skill_id); - - $tpl->setContent($tab->getHTML()); - - } - - /** - * Save self evaluation - */ - function saveSelfEvaluation() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - $lng = $this->lng; - - ilPersonalSkill::saveSelfEvaluation($ilUser->getId(), (int) $_GET["skill_id"], - (int) $_GET["tref_id"], (int) $_GET["basic_skill_id"], (int) $_POST["se"]); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - -/* $ilCtrl->saveParameter($this, "skill_id"); - $ilCtrl->saveParameter($this, "level_id"); - $ilCtrl->saveParameter($this, "tref_id"); - $ilCtrl->saveParameter($this, "basic_skill_id");*/ - - $ilCtrl->redirect($this, "render"); - - } - - /** - * LIst skills for adding - * - * @param - * @return - */ - function listSkillsForAdd() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTarget($this, "")); - - include_once("./Services/Skill/classes/class.ilPersonalSkillExplorerGUI.php"); - $exp = new ilPersonalSkillExplorerGUI($this, "listSkillsForAdd", $this, "addSkill"); - if ($exp->getHasSelectableNodes()) - { - if (!$exp->handleCommand()) - { - $tpl->setContent($exp->getHTML()); - } - ilUtil::sendInfo($lng->txt("skmg_select_skill")); - } - else - { - ilUtil::sendInfo($lng->txt("skmg_no_nodes_selectable")); - } - } - - /** - * List profiles - * - * @param - */ - function listProfilesForGap() - { - $tpl = $this->tpl; - - //$a_user_id = $ilUser->getId(); - - //$profiles = ilSkillProfile::getProfilesOfUser($a_user_id); - - if (count($this->user_profiles) == 0 && $this->obj_skills == null) - { - return; - } - - $this->determineCurrentProfile(); - $this->showProfileSelectorToolbar(); - - $tpl->setContent($this->getGapAnalysisHTML()); - } - - - - /** - * Show profile selector toolbar - */ - function showProfileSelectorToolbar() - { - $ilToolbar = $this->toolbar; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $options = array(); - if (is_array($this->obj_skills) && $this->obj_id > 0) - { - $options[0] = $lng->txt("obj_".ilObject::_lookupType($this->obj_id)).": ".ilObject::_lookupTitle($this->obj_id); - } - - foreach ($this->user_profiles as $p) - { - $options[$p["id"]] = $lng->txt("skmg_profile").": ".$p["title"]; - } - - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $si = new ilSelectInputGUI($lng->txt("skmg_profile"), "profile_id"); - $si->setOptions($options); - $si->setValue($this->getProfileId()); - $ilToolbar->addInputItem($si, true); - $ilToolbar->addFormButton($lng->txt("select"), - "selectProfile"); - $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); - - } - - - /** - * Set gap analysis actual status mode "per type" - * - * @param string $a_type type - */ - function setGapAnalysisActualStatusModePerType($a_type, $a_cat_title = "") - { - $this->gap_mode = "max_per_type"; - $this->gap_mode_type = $a_type; - $this->gap_cat_title = $a_cat_title; - $this->mode = "gap"; - } - - /** - * Set gap analysis actual status mode "per object" - * - * @param integer $a_obj_id object id - */ - function setGapAnalysisActualStatusModePerObject($a_obj_id, $a_cat_title = "") - { - $this->gap_mode = "max_per_object"; - $this->gap_mode_obj_id = $a_obj_id; - $this->gap_cat_title = $a_cat_title; - $this->mode = "gap"; - } - - /** - * Get actual levels - * - * @param array $skills - * @param int $user_id - */ - protected function getActualLevels($skills, $user_id) - { - // get actual levels for gap analysis - $this->actual_levels = array(); - include_once("./Services/Skill/classes/class.ilBasicSkill.php"); - foreach ($skills as $sk) - { - $bs = new ilBasicSkill($sk["base_skill_id"]); - if ($this->gap_mode == "max_per_type") - { - $max = $bs->getMaxLevelPerType($sk["tref_id"], $this->gap_mode_type, $user_id); - $this->actual_levels[$sk["base_skill_id"]][$sk["tref_id"]] = $max; - } - else if ($this->gap_mode == "max_per_object") - { - $max = $bs->getMaxLevelPerObject($sk["tref_id"], $this->gap_mode_obj_id, $user_id); - $this->actual_levels[$sk["base_skill_id"]][$sk["tref_id"]] = $max; - } - else - { - $max = $bs->getMaxLevel($sk["tref_id"], $user_id); - $this->actual_levels[$sk["base_skill_id"]][$sk["tref_id"]] = $max; - } - } - } - - - /** - * Get gap analysis html - * - * @param - * @param array $a_skills deprecated, use setObjectSkills and listProfiles instead - * @return - */ - function getGapAnalysisHTML($a_user_id = 0, $a_skills = null) - { - $ilUser = $this->user; - $lng = $this->lng; - - - if ($a_skills == null) - { - $a_skills = $this->obj_skills; - } - - include_once("./Services/UIComponent/Panel/classes/class.ilPanelGUI.php"); - - if ($this->getIntroText() != "") - { - $pan = ilPanelGUI::getInstance(); - $pan->setPanelStyle(ilPanelGUI::PANEL_STYLE_PRIMARY); - $pan->setBody($this->getIntroText()); - $intro_html = $pan->getHTML(); - } - -// $this->setTabs("list_skills"); - - if ($a_user_id == 0) - { - $user_id = $ilUser->getId(); - } - else - { - $user_id = $a_user_id; - } - - $skills = array(); - if ($this->getProfileId() > 0) - { - $profile = new ilSkillProfile($this->getProfileId()); - $this->profile_levels = $profile->getSkillLevels(); - - foreach ($this->profile_levels as $l) - { - $skills[] = array( - "base_skill_id" => $l["base_skill_id"], - "tref_id" => $l["tref_id"], - "level_id" => $l["level_id"] - ); - } - } - else if (is_array($a_skills)) - { - $skills = $a_skills; - } - - // get actual levels for gap analysis - $this->getActualLevels($skills, $user_id); - - $incl_self_eval = false; - if (count($this->getGapAnalysisSelfEvalLevels()) > 0) - { - $incl_self_eval = true; - $self_vals = $this->getGapAnalysisSelfEvalLevels(); - } - - // output spider stuff - $all_chart_html = ""; - - // determine skills that should be shown in the spider web - $sw_skills = array(); - foreach ($skills as $sk) - { - if (!in_array($sk["base_skill_id"].":".$sk["tref_id"], $this->hidden_skills)) - { - $sw_skills[] = $sk; - } - } - - if (count($sw_skills) >= 3) - { - $skill_packages = array(); - - if (count($sw_skills) < 8) - { - $skill_packages[1] = $sw_skills; - } - else - { - $mod = count($sw_skills) % 7; - $pkg_num = floor((count($sw_skills) - 1) / 7) + 1; - $cpkg = 1; - foreach ($sw_skills as $k => $s) - { - $skill_packages[$cpkg][$k] = $s; - if ($mod < 3 && count($skill_packages) == ($pkg_num - 1) && count($skill_packages[$cpkg]) == 3+$mod) - { - $cpkg+=1; - } - else if (count($skill_packages[$cpkg]) == 7) - { - $cpkg+=1; - } - } - } - - $pkg_cnt = 0; - foreach ($skill_packages as $pskills) - { - $pkg_cnt++; - $max_cnt = 0; - $leg_labels = array(); - //var_dump($this->profile_levels); - //foreach ($this->profile_levels as $k => $l) - - // write target, actual and self counter to skill array - foreach ($pskills as $k => $l) - { - //$bs = new ilBasicSkill($l["base_skill_id"]); - $bs = new ilBasicSkill($l["base_skill_id"]); - $leg_labels[] = ilBasicSkill::_lookupTitle($l["base_skill_id"] , $l["tref_id"]); - $levels = $bs->getLevelData(); - $cnt = 0; - foreach ($levels as $lv) - { - $cnt++; - if ($l["level_id"] == $lv["id"]) - { - $pskills[$k]["target_cnt"] = $cnt; - } - if ($this->actual_levels[$l["base_skill_id"]][$l["tref_id"]] == $lv["id"]) - { - $pskills[$k]["actual_cnt"] = $cnt; - } - if ($incl_self_eval) - { - if ($self_vals[$l["base_skill_id"]][$l["tref_id"]] == $lv["id"]) - { - $pskills[$k]["self_cnt"] = $cnt; - } - } - $max_cnt = max($max_cnt, $cnt); - } - } - - include_once("./Services/Chart/classes/class.ilChart.php"); - $chart = ilChart::getInstanceByType(ilChart::TYPE_SPIDER, "gap_chart".$pkg_cnt); - $chart->setsize(800, 300); - $chart->setYAxisMax($max_cnt); - $chart->setLegLabels($leg_labels); - - // target level - $cd = $chart->getDataInstance(); - $cd->setLabel($lng->txt("skmg_target_level")); - $cd->setFill(true, "#A0A0A0"); - - // other users - $cd2 = $chart->getDataInstance(); - if ($this->gap_cat_title != "") - { - $cd2->setLabel($this->gap_cat_title); - } - else if ($this->gap_mode == "max_per_type") - { - $cd2->setLabel($lng->txt("objs_".$this->gap_mode_type)); - } - else if ($this->gap_mode == "max_per_object") - { - $cd2->setLabel(ilObject::_lookupTitle($this->gap_mode_obj_id)); - } - //$cd2->setFill(true, "#dcb496"); - $cd2->setFill(true, "#FF8080"); - $cd2->setFill(true, "#cc8466"); - - // self evaluation - if ($incl_self_eval) - { - $cd3 = $chart->getDataInstance(); - $cd3->setLabel($lng->txt("skmg_self_evaluation")); - $cd3->setFill(true, "#6ea03c"); - } - - // fill in data - $cnt = 0; - foreach ($pskills as $pl) - { - $cd->addPoint($cnt, (int) $pl["target_cnt"]); - $cd2->addPoint($cnt, (int) $pl["actual_cnt"]); - if ($incl_self_eval) - { - $cd3->addPoint($cnt, (int) $pl["self_cnt"]); - } - $cnt++; - } - - // add data to chart - if ($this->getProfileId() > 0) - { - $chart->addData($cd); - } - $chart->addData($cd2); - if ($incl_self_eval && count($this->getGapAnalysisSelfEvalLevels()) > 0) - { - $chart->addData($cd3); - } - - if ($pkg_cnt == 1) - { - $lg = new ilChartLegend(); - $chart->setLegend($lg); - } - - $chart_html = $chart->getHTML(); - $all_chart_html.= $chart_html; - } - - $pan = ilPanelGUI::getInstance(); - $pan->setPanelStyle(ilPanelGUI::PANEL_STYLE_PRIMARY); - $pan->setBody($all_chart_html); - $all_chart_html = $pan->getHTML(); - } - - $stree = new ilSkillTree(); - $html = ""; - - // order skills per virtual skill tree - include_once("./Services/Skill/classes/class.ilVirtualSkillTree.php"); - $vtree = new ilVirtualSkillTree(); - $skills = $vtree->getOrderedNodeset($skills, "base_skill_id", "tref_id"); - foreach ($skills as $s) - { - $path = $stree->getSkillTreePath($s["base_skill_id"]); - - // check draft - foreach ($path as $p) - { - if ($p["status"] == ilSkillTreeNode::STATUS_DRAFT) - { - continue(2); - } - } - $html.= $this->getSkillHTML($s["base_skill_id"], $user_id, false, $s["tref_id"]); - } - - // list skills -// include_once("./Services/Skill/classes/class.ilPersonalSkillTableGUI.php"); -// $sktab = new ilPersonalSkillTableGUI($this, "listSkills"); - - return $intro_html.$all_chart_html.$html; - } - - /** - * Select profile - * - * @param - */ - function selectProfile() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameter($this, "profile_id", $_POST["profile_id"]); - if ($this->mode == "gap") - { - $ilCtrl->redirect($this, "listProfilesForGap"); - } - else - { - $ilCtrl->redirect($this, "listAssignedProfile"); - } - } - - /** - * Get materials - * - * @param - * @return string - */ - function getMaterials($a_levels, $a_tref_id = 0, $a_user_id = 0) - { - $ilUser = $this->user; - $lng = $this->lng; - - if ($a_user_id == 0) - { - $a_user_id = $ilUser->getId(); - } - - // only render, if materials given - $got_mat = false; - foreach ($a_levels as $v) - { - $mat_cnt = ilPersonalSkill::countAssignedMaterial($a_user_id, - $a_tref_id, $v["id"]); - if ($mat_cnt > 0) - { - $got_mat = true; - } - } - if (!$got_mat) - { - return ""; - } - - $tpl = new ilTemplate("tpl.skill_materials.html", true, true, "Services/Skill"); - foreach ($a_levels as $k => $v) - { - $got_mat = false; - foreach(ilPersonalSkill::getAssignedMaterial($a_user_id, - $a_tref_id, $v["id"]) as $item) - { - $tpl->setCurrentBlock("material"); - $mat_data = $this->getMaterialInfo($item["wsp_id"], $a_user_id); - $tpl->setVariable("HREF_LINK", $mat_data[1]); - $tpl->setVariable("TXT_LINK", $mat_data[0]); - $tpl->parseCurrentBlock(); - $got_mat = true; - } - if ($got_mat) - { - $tpl->setCurrentBlock("level"); - $tpl->setVariable("LEVEL_VAL", $v["title"]); - $tpl->parseCurrentBlock(); - } - } - $tpl->setVariable("TXT_MATERIAL", $lng->txt("skmg_materials")); - - return $tpl->get(); - } - - /** - * Get profile target item - * - * @param - * @return - */ - function getProfileTargetItem($a_profile_id, $a_levels, $a_tref_id = 0) - { - $lng = $this->lng; - - $profile = new ilSkillProfile($a_profile_id); - $profile_levels = $profile->getSkillLevels(); - - $a_activated_levels = array(); - - foreach ($a_levels as $k => $v) - { - foreach ($profile_levels as $pl) - { - if ($pl["level_id"] == $v["id"] && - $pl["base_skill_id"] == $v["skill_id"] && - $a_tref_id == $pl["tref_id"]) - { - $a_activated_levels[] = $pl["level_id"]; - } - } - } - - $tpl = new ilTemplate("tpl.skill_eval_item.html", true, true, "Services/Skill"); - $tpl->setVariable("SCALE_BAR", $this->getScaleBar($a_levels, $a_activated_levels)); - - $tpl->setVariable("TYPE", $lng->txt("skmg_target_level")); - $tpl->setVariable("TITLE", ""); - - return $tpl->get(); - } - - /** - * - * - * @param - * @return - */ - function getActualGapItem($a_levels, $a_tref_id = 0) - { - $lng = $this->lng; - - $a_activated_levels = array(); - foreach ($a_levels as $k => $v) - { - if ($this->actual_levels[$v["skill_id"]][$a_tref_id] == $v["id"]) - { - $a_activated_levels[] = $v["id"]; - } - } - - if ($this->gap_cat_title != "") - { - $title = $this->gap_cat_title; - } - else if ($this->gap_mode == "max_per_type") - { - $title = $lng->txt("objs_".$this->gap_mode_type); - } - else if ($this->gap_mode == "max_per_object") - { - $title = ilObject::_lookupTitle($this->gap_mode_obj_id); - } - - $tpl = new ilTemplate("tpl.skill_eval_item.html", true, true, "Services/Skill"); - $tpl->setVariable("SCALE_BAR", $this->getScaleBar($a_levels, $a_activated_levels)); - - $type = 1; - $tpl->setVariable("TYPE", $lng->txt("skmg_eval_type_".$type)); - if ($type > 0) - { - $tpl->touchBlock("st".$type); - $tpl->touchBlock("stb".$type); - } - - if ($title != $lng->txt("skmg_eval_type_".$type)) - { - $tpl->setVariable("TITLE", $title); - } - - return $tpl->get(); - } - - /** - * - * - * @param - * @return - */ - function getSelfEvalGapItem($a_levels, $a_tref_id = 0) - { - $lng = $this->lng; - - $self_vals = $this->getGapAnalysisSelfEvalLevels(); - if (count($self_vals) == 0) - { - return; - } - - $a_activated_levels = array(); - foreach ($a_levels as $k => $v) - { - if ($self_vals[$v["skill_id"]][$a_tref_id] == $v["id"]) - { - $a_activated_levels[] = $v["id"]; - } - } - - $tpl = new ilTemplate("tpl.skill_eval_item.html", true, true, "Services/Skill"); - $tpl->setVariable("SCALE_BAR", $this->getScaleBar($a_levels, $a_activated_levels)); - - $type = 3; - $tpl->setVariable("TYPE", $lng->txt("skmg_eval_type_".$type)); - if ($type > 0) - { - $tpl->touchBlock("st".$type); - $tpl->touchBlock("stb".$type); - } - - return $tpl->get(); - - } - - - /** - * Get scale bar - * - * @param - * @return - */ - function getScaleBar($a_levels, $a_activated_levels) - { - $vals = array(); - - if (!is_array($a_activated_levels)) - { - $a_activated_levels = array($a_activated_levels); - } - - foreach ($a_levels as $level) - { - $vals[$level["title"]] = (in_array($level["id"], $a_activated_levels)); - } - $scale_bar = $this->ui_fac->chart()->scaleBar($vals); - - return $this->ui_ren->render($scale_bar); - } - - /** - * Get eval item - * - * @param - * @return - */ - function getEvalItem($a_levels, $a_level_entry) - { - $lng = $this->lng; - $ilAccess = $this->access; - - $tpl = new ilTemplate("tpl.skill_eval_item.html", true, true, "Services/Skill"); - $tpl->setVariable("SCALE_BAR", $this->getScaleBar($a_levels, $a_level_entry["level_id"])); - - include_once("./Services/Skill/classes/class.ilSkillEval.php"); - $type = ilSkillEval::TYPE_APPRAISAL; - - if ($a_level_entry["self_eval"] == 1) - { - $type = ilSkillEval::TYPE_SELF_EVAL; - } - - if ($a_level_entry["trigger_obj_type"] == "tst") - { - $type = ilSkillEval::TYPE_MEASUREMENT; - } - - ilDatePresentation::setUseRelativeDates(false); - $title = ($a_level_entry["trigger_obj_id"] > 0) - ? $a_level_entry["trigger_title"] - : ""; - - if ($a_level_entry["trigger_ref_id"] > 0 - && $ilAccess->checkAccess("read", "", $a_level_entry["trigger_ref_id"])) - { - include_once("./Services/Link/classes/class.ilLink.php"); - $title = "".$title.""; - } - - $tpl->setVariable("TYPE", $lng->txt("skmg_eval_type_".$type)); - if ($type > 0) - { - $tpl->touchBlock("st".$type); - $tpl->touchBlock("stb".$type); - } - $tpl->setVariable("TITLE", $title); - $tpl->setVariable("DATE", - ilDatePresentation::formatDate(new ilDate($a_level_entry["status_date"], IL_CAL_DATETIME))); - - ilDatePresentation::setUseRelativeDates(true); - - return $tpl->get(); - } - - /** - * Get level description - * - * @param - * @return - */ - function getSkillDescription($skill) - { - $level_data = $skill->getLevelData(); - $tpl = new ilTemplate("tpl.skill_desc.html", true, true, "Services/Skill"); - - $desc_exists = false; - foreach ($level_data as $l) - { - if ($l["description"] != "") - { - $desc_exists = true; - } - } - reset($level_data); - if ($desc_exists) - { - foreach ($level_data as $l) - { - $tpl->setCurrentBlock("level"); - $tpl->setVariable("LEVEL_VAL", $l["title"]); - $tpl->setVariable("LEVEL_DESC", $l["description"]); - $tpl->parseCurrentBlock(); - } - } - - return $tpl->get(); - } - - /** - * Render suggested resources - * - * @param - * @return - */ - function getSuggestedResources($a_profile_id, $a_levels, $a_base_skill, $a_tref_id) - { - $lng = $this->lng; - - $tpl = new ilTemplate("tpl.suggested_resources.html", true, true, "Services/Skill"); - - // use a profile - if ($a_profile_id > 0) - { - $too_low = true; - $current_target_level = 0; - - foreach ($a_levels as $k => $v) - { - foreach ($this->profile_levels as $pl) - { - if ($pl["level_id"] == $v["id"] && - $pl["base_skill_id"] == $v["skill_id"]) - { - $too_low = true; - $current_target_level = $v["id"]; - } - } - - if ($this->actual_levels[$v["skill_id"]][$a_tref_id] == $v["id"]) - { - $too_low = false; - } - } - - // suggested resources - if ($too_low) - { - include_once("./Services/Skill/classes/class.ilSkillResources.php"); - $skill_res = new ilSkillResources($a_base_skill, $a_tref_id); - $res = $skill_res->getResources(); - $imp_resources = array(); - foreach ($res as $level) - { - foreach($level as $r) - { - if ($r["imparting"] == true && - $current_target_level == $r["level_id"]) - { - $imp_resources[] = $r; - } - } - } - foreach($imp_resources as $r) - { - $ref_id = $r["rep_ref_id"]; - $obj_id = ilObject::_lookupObjId($ref_id); - $title = ilObject::_lookupTitle($obj_id); - include_once("./Services/Link/classes/class.ilLink.php"); - $tpl->setCurrentBlock("resource_item"); - $tpl->setVariable("TXT_RES", $title); - $tpl->setVariable("HREF_RES", ilLink::_getLink($ref_id)); - $tpl->parseCurrentBlock(); - } - if (count($imp_resources) > 0) - { - $tpl->touchBlock("resources_list"); - $tpl->setVariable("SUGGESTED_MAT_MESS", $lng->txt("skmg_skill_needs_impr_res")); - return $tpl->get(); - } - else - { - $tpl->setVariable("SUGGESTED_MAT_MESS", $lng->txt("skmg_skill_needs_impr_no_res")); - return $tpl->get(); - } - } - else - { - $tpl->setVariable("SUGGESTED_MAT_MESS", $lng->txt("skmg_skill_no_needs_impr")); - return $tpl->get(); - } - } - else - { - // no profile, just list all resources - include_once("./Services/Skill/classes/class.ilSkillResources.php"); - $skill_res = new ilSkillResources($a_base_skill, $a_tref_id); - $res = $skill_res->getResources(); - // add $r["level_id"] info - $any = false; - foreach ($res as $level) - { - $available = false; - $cl = 0; - foreach($level as $r) - { - if ($r["imparting"]) - { - $ref_id = $r["rep_ref_id"]; - $obj_id = ilObject::_lookupObjId($ref_id); - $title = ilObject::_lookupTitle($obj_id); - include_once("./Services/Link/classes/class.ilLink.php"); - $tpl->setCurrentBlock("resource_item"); - $tpl->setVariable("TXT_RES", $title); - $tpl->setVariable("HREF_RES", ilLink::_getLink($ref_id)); - $tpl->parseCurrentBlock(); - $available = true; - $any = true; - $cl = $r["level_id"]; - } - } - if ($available) - { - $tpl->setCurrentBlock("resources_list_level"); - $tpl->setVariable("TXT_LEVEL", $lng->txt("skmg_level")); - $tpl->setVariable("LEVEL_NAME", ilBasicSkill::lookupLevelTitle($cl)); - $tpl->parseCurrentBlock(); - $tpl->touchBlock("resources_list"); - } - } - if ($any) - { - $tpl->setVariable("SUGGESTED_MAT_MESS", $lng->txt("skmg_suggested_resources")); - return $tpl->get(); - } - } - return ""; - } - - /** - * List profile - * - * @param - * @return - */ - function listAssignedProfile() - { - $ilCtrl = $this->ctrl; - - $main_tpl = $this->tpl; - - $tpl = new ilTemplate("tpl.skill_filter.html", true, true, "Services/Skill"); - - $this->setTabs("profile"); - - $this->determineCurrentProfile(); - $this->showProfileSelectorToolbar(); - - $filter_toolbar = new ilToolbarGUI(); - $filter_toolbar->setFormAction($ilCtrl->getFormAction($this)); - $this->getFilter()->addToToolbar($filter_toolbar, true); - - $skills = array(); - if ($this->getProfileId() > 0) - { - $profile = new ilSkillProfile($this->getProfileId()); - $this->profile_levels = $profile->getSkillLevels(); - - foreach ($this->profile_levels as $l) - { - $skills[] = array( - "base_skill_id" => $l["base_skill_id"], - "tref_id" => $l["tref_id"], - "level_id" => $l["level_id"] - ); - } - } - - $this->getActualLevels($skills, $this->user->getId()); - - // render - $html = ""; - foreach ($skills as $s) - { - // todo draft check - $html.= $this->getSkillHTML($s["base_skill_id"], 0, true, $s["tref_id"]); - } - - if ($html != "") - { - $filter_toolbar->addFormButton($this->lng->txt("skmg_refresh_view"), "applyFilterAssignedProfiles"); - - $tpl->setVariable("FILTER", $filter_toolbar->getHTML()); - - $html = $tpl->get().$html; - } - - $main_tpl->setContent($html); - } - - + /** + * List skills + */ + public function listSkills() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + $lng = $this->lng; + $main_tpl = $this->tpl; + $ilToolbar = $this->toolbar; + + $tpl = new ilTemplate("tpl.skill_filter.html", true, true, "Services/Skill"); + + $this->setTabs("list_skills"); + + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $stree = new ilSkillTree(); + + // skill selection / add new personal skill + $ilToolbar->addFormButton( + $lng->txt("skmg_add_skill"), + "listSkillsForAdd" + ); + $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); + + $filter_toolbar = new ilToolbarGUI(); + $filter_toolbar->setFormAction($ilCtrl->getFormAction($this)); + $this->getFilter()->addToToolbar($filter_toolbar, false); + + $skills = ilPersonalSkill::getSelectedUserSkills($ilUser->getId()); + $html = ""; + foreach ($skills as $s) { + $path = $stree->getSkillTreePath($s["skill_node_id"]); + + // check draft + foreach ($path as $p) { + if ($p["status"] == ilSkillTreeNode::STATUS_DRAFT) { + continue(2); + } + } + $html.= $this->getSkillHTML($s["skill_node_id"], 0, true); + } + + // list skills + // include_once("./Services/Skill/classes/class.ilPersonalSkillTableGUI.php"); + // $sktab = new ilPersonalSkillTableGUI($this, "listSkills"); + + if ($html != "") { + $filter_toolbar->addFormButton($this->lng->txt("skmg_refresh_view"), "applyFilter"); + $tpl->setVariable("FILTER", $filter_toolbar->getHTML()); + $html = $tpl->get() . $html; + } + + $main_tpl->setContent($html); + } + + /** + * Apply filter + */ + protected function applyFilter() + { + $this->getFilter()->save(); + $this->ctrl->redirect($this, "listSkills"); + } + + /** + * Apply filter for profiles view + */ + protected function applyFilterAssignedProfiles() + { + $this->getFilter()->save(); + $this->ctrl->redirect($this, "listAssignedProfile"); + } + + + /** + * Get skill presentation HTML + * + * $a_top_skill_id is a node of the skill "main tree", it can be a tref id! + * - called in listSkills (this class) -> $a_top_skill is the selected user skill (main tree node id), tref_id not set + * - called in ilPortfolioPage -> $a_top_skill is the selected user skill (main tree node id), tref_id not set + * - called in getGapAnalysis (this class) -> $a_top_skill id is the (basic) skill_id, tref_id may be set + */ + public function getSkillHTML($a_top_skill_id, $a_user_id = 0, $a_edit = false, $a_tref_id = 0) + { + // user interface plugin slot + default rendering + include_once("./Services/UIComponent/classes/class.ilUIHookProcessor.php"); + $uip = new ilUIHookProcessor( + "Services/Skill", + "personal_skill_html", + array("personal_skills_gui" => $this, "top_skill_id" => $a_top_skill_id, "user_id" => $a_user_id, + "edit" => $a_edit, "tref_id" => $a_tref_id) + ); + if (!$uip->replaced()) { + $skill_html = $this->renderSkillHTML($a_top_skill_id, $a_user_id, $a_edit, $a_tref_id); + } + $skill_html = $uip->getHTML($skill_html); + + return $skill_html; + } + + /** + * Render skill html + * + * @param + * @return + */ + public function renderSkillHTML($a_top_skill_id, $a_user_id = 0, $a_edit = false, $a_tref_id = 0) + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + $lng = $this->lng; + + $sub_panels = array(); + + if ($a_user_id == 0) { + $user = $ilUser; + } else { + $user = new ilObjUser($a_user_id); + } + + $tpl = new ilTemplate("tpl.skill_pres.html", true, true, "Services/Skill"); + + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $stree = new ilSkillTree(); + + include_once("./Services/Skill/classes/class.ilVirtualSkillTree.php"); + $vtree = new ilVirtualSkillTree(); + $tref_id = $a_tref_id; + $skill_id = $a_top_skill_id; + if (ilSkillTreeNode::_lookupType($a_top_skill_id) == "sktr") { + include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); + $tref_id = $a_top_skill_id; + $skill_id = ilSkillTemplateReference::_lookupTemplateId($a_top_skill_id); + } + $b_skills = $vtree->getSubTreeForCSkillId($skill_id . ":" . $tref_id, true); + + foreach ($b_skills as $bs) { + $bs["id"] = $bs["skill_id"]; + $bs["tref"] = $bs["tref_id"]; + + $path = $stree->getSkillTreePath($bs["id"], $bs["tref"]); + + $panel_comps = array(); + + + // check draft + foreach ($path as $p) { + if ($p["status"] == ilSkillTreeNode::STATUS_DRAFT) { + continue(2); + } + } + reset($path); + + $skill = ilSkillTreeNodeFactory::getInstance($bs["id"]); + $level_data = $skill->getLevelData(); + + + // skill description + $panel_comps[] = $this->ui_fac->legacy($this->getSkillDescription($skill)); + + + if ($this->getProfileId() > 0) { + if (!$this->skmg_settings->getHideProfileBeforeSelfEval() || + ilBasicSkill::hasSelfEvaluated($user->getId(), $bs["id"], $bs["tref"])) { + if ($this->getFilter()->showTargetLevel()) { + $panel_comps[] = $this->ui_fac->legacy($this->getProfileTargetItem($this->getProfileId(), $level_data, $bs["tref"])); + } + } + } + + if ($this->mode == "gap" && !$this->history_view) { + $panel_comps[] = $this->ui_fac->legacy($this->getActualGapItem($level_data, $bs["tref"]) . ""); + $panel_comps[] = $this->ui_fac->legacy($this->getSelfEvalGapItem($level_data, $bs["tref"]) . ""); + } else { + // get date of self evaluation + $se_date = ilPersonalSkill::getSelfEvaluationDate($user->getId(), $a_top_skill_id, $bs["tref"], $bs["id"]); + $se_rendered = ($se_date == "") + ? true + : false; + + // get all object triggered entries and render them + foreach ($skill->getAllHistoricLevelEntriesOfUser($bs["tref"], $user->getId(), ilBasicSkill::EVAL_BY_ALL) as $level_entry) { + if (count($this->getTriggerObjectsFilter()) && !in_array($level_entry['trigger_obj_id'], $this->getTriggerObjectsFilter())) { + continue; + } + + // render the self evaluation at the correct position within the list of object triggered entries + if ($se_date > $level_entry["status_date"] && !$se_rendered) { + $se_rendered = true; + } + if ($this->getFilter()->isInRange($level_data, $level_entry)) { + $panel_comps[] = $this->ui_fac->legacy($this->getEvalItem($level_data, $level_entry)); + } + } + } + + // materials (new) + if ($this->mode != "gap") { + if ($this->getFilter()->showMaterialsRessources() && $this->use_materials) { + $mat = $this->getMaterials($level_data, $bs["tref"], $user->getId()); + } + if ($mat != "") { + $panel_comps[] = $this->ui_fac->legacy($mat); + } + } + + // suggested resources + if ($this->getFilter()->showMaterialsRessources()) { + $sugg = $this->getSuggestedResources($this->getProfileId(), $level_data, $bs["id"], $bs["tref"]); + } + if ($sugg != "") { + $panel_comps[] = $this->ui_fac->legacy($sugg); + } + + $title = $sep = ""; + $found = false; + foreach ($path as $p) { + if ($found) { + $title.= $sep . $p["title"]; + $sep = " > "; + } + if ($a_top_skill_id == $p["child"]) { + $found = true; + } + } + + $sub = $this->ui_fac->panel()->sub((string) $title, $panel_comps); + if ($a_edit) { + $actions = array(); + $ilCtrl->setParameterByClass("ilpersonalskillsgui", "skill_id", $a_top_skill_id); + $ilCtrl->setParameterByClass("ilpersonalskillsgui", "tref_id", $bs["tref"]); + $ilCtrl->setParameterByClass("ilpersonalskillsgui", "basic_skill_id", $bs["id"]); + if ($this->use_materials) { + $actions[] = $this->ui_fac->button()->shy( + $lng->txt('skmg_assign_materials'), + $ilCtrl->getLinkTargetByClass("ilpersonalskillsgui", "assignMaterials") + ); + } + $actions[] = $this->ui_fac->button()->shy( + $lng->txt('skmg_self_evaluation'), + $ilCtrl->getLinkTargetByClass("ilpersonalskillsgui", "selfEvaluation") + ); + $sub = $sub->withActions($this->ui_fac->dropdown()->standard($actions)->withLabel($lng->txt("actions"))); + } + + $sub_panels[] = $sub; + + $tpl->parseCurrentBlock(); + } + + $panel = $this->ui_fac->panel()->standard( + (string) ilSkillTreeNode::_lookupTitle($skill_id, $tref_id), + $sub_panels + ); + + if ($a_edit && $this->getProfileId() == 0) { + $actions = array(); + + $ilCtrl->setParameterByClass("ilpersonalskillsgui", "skill_id", $a_top_skill_id); + $actions[] = $this->ui_fac->button()->shy( + $lng->txt('skmg_remove_skill'), + $ilCtrl->getLinkTargetByClass("ilpersonalskillsgui", "confirmSkillRemove") + ); + + $panel = $panel->withActions($this->ui_fac->dropdown()->standard($actions)->withLabel($lng->txt("actions"))); + } + + return $this->ui_ren->render($panel); + } + + + /** + * Get material file name and goto url + * + * @param int $a_wsp_id + * @return array caption, url + */ + public function getMaterialInfo($a_wsp_id, $a_user_id) + { + if (!$this->ws_tree) { + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; + $this->ws_tree = new ilWorkspaceTree($a_user_id); + $this->ws_access = new ilWorkspaceAccessHandler($caption); + } + + $obj_id = $this->ws_tree->lookupObjectId($a_wsp_id); + $caption = ilObject::_lookupTitle($obj_id); + + if (!$this->offline_mode) { + $url = $this->ws_access->getGotoLink($a_wsp_id, $obj_id); + } else { + $url = $this->offline_mode . "file_" . $obj_id . "/"; + + // all possible material types for now + switch (ilObject::_lookupType($obj_id)) { + case "tstv": + include_once "Modules/Test/classes/class.ilObjTestVerification.php"; + $obj = new ilObjTestVerification($obj_id, false); + $url .= $obj->getOfflineFilename(); + break; + + case "excv": + include_once "Modules/Exercise/classes/class.ilObjExerciseVerification.php"; + $obj = new ilObjExerciseVerification($obj_id, false); + $url .= $obj->getOfflineFilename(); + break; + + case "crsv": + include_once "Modules/Course/classes/Verification/class.ilObjCourseVerification.php"; + $obj = new ilObjCourseVerification($obj_id, false); + $url .= $obj->getOfflineFilename(); + break; + + case "scov": + include_once "Modules/ScormAicc/classes/Verification/class.ilObjSCORMVerification.php"; + $obj = new ilObjSCORMVerification($obj_id, false); + $url .= $obj->getOfflineFilename(); + break; + + case "file": + $file = new ilObjFile($obj_id, false); + $url .= $file->getFilename(); + break; + } + } + + return array($caption, $url); + } + + /** + * Add personal skill + */ + public function addSkill() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + $lng = $this->lng; + + ilPersonalSkill::addPersonalSkill($ilUser->getId(), (int) $_GET["obj_id"]); + + ilUtil::sendSuccess($lng->txt("msg_object_modified")); + $ilCtrl->redirect($this, "listSkills"); + } + + + + /** + * Confirm skill remove + */ + public function confirmSkillRemove() + { + $lng = $this->lng; + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + + include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); + if ($_GET["skill_id"] > 0) { + $_POST["id"][] = $_GET["skill_id"]; + } + if (!is_array($_POST["id"]) || count($_POST["id"]) == 0) { + ilUtil::sendInfo($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "listSkills"); + } else { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("skmg_really_remove_skills")); + $cgui->setCancel($lng->txt("cancel"), "listSkills"); + $cgui->setConfirm($lng->txt("remove"), "removeSkills"); + + foreach ($_POST["id"] as $i) { + $cgui->addItem("id[]", $i, ilSkillTreeNode::_lookupTitle($i)); + } + + $tpl->setContent($cgui->getHTML()); + } + } + + /** + * Remove skills + */ + public function removeSkills() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + $lng = $this->lng; + + if (is_array($_POST["id"])) { + foreach ($_POST["id"] as $n_id) { + ilPersonalSkill::removeSkill($ilUser->getId(), $n_id); + } + } + + ilUtil::sendSuccess($lng->txt("msg_object_modified")); + $ilCtrl->redirect($this, "listSkills"); + } + + + // + // Materials assignments + // + + /** + * Assign materials to skill levels + * + * @param + * @return + */ + public function assignMaterials() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $ilTabs = $this->tabs; + + + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, "render") + ); + + $ilCtrl->saveParameter($this, "skill_id"); + $ilCtrl->saveParameter($this, "basic_skill_id"); + $ilCtrl->saveParameter($this, "tref_id"); + + include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); + $tpl->setTitle(ilSkillTreeNode::_lookupTitle((int) $_GET["skill_id"])); + $tpl->setTitleIcon(ilUtil::getImagePath("icon_" . + ilSkillTreeNode::_lookupType((int) $_GET["skill_id"]) . + ".svg")); + + // basic skill selection + include_once("./Services/Skill/classes/class.ilVirtualSkillTree.php"); + $vtree = new ilVirtualSkillTree(); + $tref_id = 0; + $skill_id = (int) $_GET["skill_id"]; + if (ilSkillTreeNode::_lookupType((int) $_GET["skill_id"]) == "sktr") { + include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); + $tref_id = $_GET["skill_id"]; + $skill_id = ilSkillTemplateReference::_lookupTemplateId($_GET["skill_id"]); + } + $bs = $vtree->getSubTreeForCSkillId($skill_id . ":" . $tref_id, true); + + $options = array(); + foreach ($bs as $b) { + //$options[$b["id"]] = ilSkillTreeNode::_lookupTitle($b["id"]); + $options[$b["skill_id"]] = ilSkillTreeNode::_lookupTitle($b["skill_id"]); + } + + $cur_basic_skill_id = ((int) $_POST["basic_skill_id"] > 0) + ? (int) $_POST["basic_skill_id"] + : (((int) $_GET["basic_skill_id"] > 0) + ? (int) $_GET["basic_skill_id"] + : key($options)); + + $ilCtrl->setParameter($this, "basic_skill_id", $cur_basic_skill_id); + + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $si = new ilSelectInputGUI($lng->txt("skmg_skill"), "basic_skill_id"); + $si->setOptions($options); + $si->setValue($cur_basic_skill_id); + $ilToolbar->addInputItem($si, true); + $ilToolbar->addFormButton( + $lng->txt("select"), + "assignMaterials" + ); + + $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); + + // table + include_once("./Services/Skill/classes/class.ilSkillAssignMaterialsTableGUI.php"); + $tab = new ilSkillAssignMaterialsTableGUI( + $this, + "assignMaterials", + (int) $_GET["skill_id"], + (int) $_GET["tref_id"], + $cur_basic_skill_id + ); + + $tpl->setContent($tab->getHTML()); + } + + + /** + * Assign materials to skill level + * + * @param + * @return + */ + public function assignMaterial() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + $lng = $this->lng; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + $ilSetting = $this->setting; + $ui = $this->ui; + + if (!$ilSetting->get("disable_personal_workspace")) { + $url = 'ilias.php?baseClass=ilPersonalDesktopGUI&cmd=jumpToWorkspace'; + $mbox = $ui->factory()->messageBox()->info($lng->txt("skmg_ass_materials_from_workspace")) + ->withLinks([$ui->factory()->link()->standard( + $lng->txt("personal_workspace"), + $url + )]); + $message = $ui->renderer()->render($mbox); + } + + $ilCtrl->saveParameter($this, "skill_id"); + $ilCtrl->saveParameter($this, "level_id"); + $ilCtrl->saveParameter($this, "tref_id"); + $ilCtrl->saveParameter($this, "basic_skill_id"); + + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, "assignMaterials") + ); + + + include_once("./Services/PersonalWorkspace/classes/class.ilWorkspaceExplorerGUI.php"); + $exp = new ilWorkspaceExplorerGUI($ilUser->getId(), $this, "assignMaterial", $this, ""); + $exp->setTypeWhiteList(array("blog", "wsrt", "wfld", "file", "tstv", "excv")); + $exp->setSelectableTypes(array("file", "tstv", "excv")); + $exp->setSelectMode("wsp_id", true); + if ($exp->handleCommand()) { + return; + } + + // fill template + $mtpl = new ilTemplate("tpl.materials_selection.html", true, true, "Services/Skill"); + $mtpl->setVariable("EXP", $exp->getHTML()); + + // toolbars + $tb = new ilToolbarGUI(); + $tb->addFormButton( + $lng->txt("select"), + "selectMaterial" + ); + $tb->setFormAction($ilCtrl->getFormAction($this)); + $tb->setOpenFormTag(true); + $tb->setCloseFormTag(false); + $mtpl->setVariable("TOOLBAR1", $tb->getHTML()); + $tb->setOpenFormTag(false); + $tb->setCloseFormTag(true); + $mtpl->setVariable("TOOLBAR2", $tb->getHTML()); + + $tpl->setContent($message . $mtpl->get()); + } + + /** + * Select material + */ + public function selectMaterial() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + $lng = $this->lng; + + + include_once("./Services/Skill/classes/class.ilPersonalSkill.php"); + if (is_array($_POST["wsp_id"])) { + foreach ($_POST["wsp_id"] as $w) { + ilPersonalSkill::assignMaterial( + $ilUser->getId(), + (int) $_GET["skill_id"], + (int) $_GET["tref_id"], + (int) $_GET["basic_skill_id"], + (int) $_GET["level_id"], + (int) $w + ); + } + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + } + + $ilCtrl->saveParameter($this, "skill_id"); + $ilCtrl->saveParameter($this, "level_id"); + $ilCtrl->saveParameter($this, "tref_id"); + $ilCtrl->saveParameter($this, "basic_skill_id"); + + $ilCtrl->redirect($this, "assignMaterials"); + } + + + /** + * Remove material + */ + public function removeMaterial() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + $lng = $this->lng; + + + ilPersonalSkill::removeMaterial( + $ilUser->getId(), + (int) $_GET["tref_id"], + (int) $_GET["level_id"], + (int) $_GET["wsp_id"] + ); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "assignMaterials"); + } + + + // + // Self evaluation + // + + /** + * Assign materials to skill levels + * + * @param + * @return + */ + public function selfEvaluation() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $ilTabs = $this->tabs; + + + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, "render") + ); + + $ilCtrl->saveParameter($this, "skill_id"); + $ilCtrl->saveParameter($this, "basic_skill_id"); + $ilCtrl->saveParameter($this, "tref_id"); + + include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); + $tpl->setTitle(ilSkillTreeNode::_lookupTitle((int) $_GET["skill_id"])); + $tpl->setTitleIcon(ilUtil::getImagePath("icon_" . + ilSkillTreeNode::_lookupType((int) $_GET["skill_id"]) . + ".svg")); + + // basic skill selection + include_once("./Services/Skill/classes/class.ilVirtualSkillTree.php"); + $vtree = new ilVirtualSkillTree(); + $tref_id = 0; + $skill_id = (int) $_GET["skill_id"]; + if (ilSkillTreeNode::_lookupType((int) $_GET["skill_id"]) == "sktr") { + include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); + $tref_id = $_GET["skill_id"]; + $skill_id = ilSkillTemplateReference::_lookupTemplateId($_GET["skill_id"]); + } + $bs = $vtree->getSubTreeForCSkillId($skill_id . ":" . $tref_id, true); + + + $options = array(); + foreach ($bs as $b) { + $options[$b["skill_id"]] = ilSkillTreeNode::_lookupTitle($b["skill_id"]); + } + + $cur_basic_skill_id = ((int) $_POST["basic_skill_id"] > 0) + ? (int) $_POST["basic_skill_id"] + : (((int) $_GET["basic_skill_id"] > 0) + ? (int) $_GET["basic_skill_id"] + : key($options)); + + $ilCtrl->setParameter($this, "basic_skill_id", $cur_basic_skill_id); + + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $si = new ilSelectInputGUI($lng->txt("skmg_skill"), "basic_skill_id"); + $si->setOptions($options); + $si->setValue($cur_basic_skill_id); + $ilToolbar->addInputItem($si, true); + $ilToolbar->addFormButton( + $lng->txt("select"), + "selfEvaluation" + ); + + $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); + + // table + include_once("./Services/Skill/classes/class.ilSelfEvaluationSimpleTableGUI.php"); + $tab = new ilSelfEvaluationSimpleTableGUI( + $this, + "selfEvaluation", + (int) $_GET["skill_id"], + (int) $_GET["tref_id"], + $cur_basic_skill_id + ); + + $tpl->setContent($tab->getHTML()); + } + + /** + * Save self evaluation + */ + public function saveSelfEvaluation() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + $lng = $this->lng; + + ilPersonalSkill::saveSelfEvaluation( + $ilUser->getId(), + (int) $_GET["skill_id"], + (int) $_GET["tref_id"], + (int) $_GET["basic_skill_id"], + (int) $_POST["se"] + ); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + + /* $ilCtrl->saveParameter($this, "skill_id"); + $ilCtrl->saveParameter($this, "level_id"); + $ilCtrl->saveParameter($this, "tref_id"); + $ilCtrl->saveParameter($this, "basic_skill_id");*/ + + $ilCtrl->redirect($this, "render"); + } + + /** + * LIst skills for adding + * + * @param + * @return + */ + public function listSkillsForAdd() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, "") + ); + + include_once("./Services/Skill/classes/class.ilPersonalSkillExplorerGUI.php"); + $exp = new ilPersonalSkillExplorerGUI($this, "listSkillsForAdd", $this, "addSkill"); + if ($exp->getHasSelectableNodes()) { + if (!$exp->handleCommand()) { + $tpl->setContent($exp->getHTML()); + } + ilUtil::sendInfo($lng->txt("skmg_select_skill")); + } else { + ilUtil::sendInfo($lng->txt("skmg_no_nodes_selectable")); + } + } + + /** + * List profiles + * + * @param + */ + public function listProfilesForGap() + { + $tpl = $this->tpl; + + //$a_user_id = $ilUser->getId(); + + //$profiles = ilSkillProfile::getProfilesOfUser($a_user_id); + + if (count($this->user_profiles) == 0 && $this->obj_skills == null) { + return; + } + + $this->determineCurrentProfile(); + $this->showProfileSelectorToolbar(); + + $tpl->setContent($this->getGapAnalysisHTML()); + } + + + + /** + * Show profile selector toolbar + */ + public function showProfileSelectorToolbar() + { + $ilToolbar = $this->toolbar; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $options = array(); + if (is_array($this->obj_skills) && $this->obj_id > 0) { + $options[0] = $lng->txt("obj_" . ilObject::_lookupType($this->obj_id)) . ": " . ilObject::_lookupTitle($this->obj_id); + } + + foreach ($this->user_profiles as $p) { + $options[$p["id"]] = $lng->txt("skmg_profile") . ": " . $p["title"]; + } + + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $si = new ilSelectInputGUI($lng->txt("skmg_profile"), "profile_id"); + $si->setOptions($options); + $si->setValue($this->getProfileId()); + $ilToolbar->addInputItem($si, true); + $ilToolbar->addFormButton( + $lng->txt("select"), + "selectProfile" + ); + $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); + } + + + /** + * Set gap analysis actual status mode "per type" + * + * @param string $a_type type + */ + public function setGapAnalysisActualStatusModePerType($a_type, $a_cat_title = "") + { + $this->gap_mode = "max_per_type"; + $this->gap_mode_type = $a_type; + $this->gap_cat_title = $a_cat_title; + $this->mode = "gap"; + } + + /** + * Set gap analysis actual status mode "per object" + * + * @param integer $a_obj_id object id + */ + public function setGapAnalysisActualStatusModePerObject($a_obj_id, $a_cat_title = "") + { + $this->gap_mode = "max_per_object"; + $this->gap_mode_obj_id = $a_obj_id; + $this->gap_cat_title = $a_cat_title; + $this->mode = "gap"; + } + + /** + * Get actual levels + * + * @param array $skills + * @param int $user_id + */ + protected function getActualLevels($skills, $user_id) + { + // get actual levels for gap analysis + $this->actual_levels = array(); + include_once("./Services/Skill/classes/class.ilBasicSkill.php"); + foreach ($skills as $sk) { + $bs = new ilBasicSkill($sk["base_skill_id"]); + if ($this->gap_mode == "max_per_type") { + $max = $bs->getMaxLevelPerType($sk["tref_id"], $this->gap_mode_type, $user_id); + $this->actual_levels[$sk["base_skill_id"]][$sk["tref_id"]] = $max; + } elseif ($this->gap_mode == "max_per_object") { + $max = $bs->getMaxLevelPerObject($sk["tref_id"], $this->gap_mode_obj_id, $user_id); + $this->actual_levels[$sk["base_skill_id"]][$sk["tref_id"]] = $max; + } else { + $max = $bs->getMaxLevel($sk["tref_id"], $user_id); + $this->actual_levels[$sk["base_skill_id"]][$sk["tref_id"]] = $max; + } + } + } + + + /** + * Get gap analysis html + * + * @param + * @param array $a_skills deprecated, use setObjectSkills and listProfiles instead + * @return + */ + public function getGapAnalysisHTML($a_user_id = 0, $a_skills = null) + { + $ilUser = $this->user; + $lng = $this->lng; + + + if ($a_skills == null) { + $a_skills = $this->obj_skills; + } + + include_once("./Services/UIComponent/Panel/classes/class.ilPanelGUI.php"); + + if ($this->getIntroText() != "") { + $pan = ilPanelGUI::getInstance(); + $pan->setPanelStyle(ilPanelGUI::PANEL_STYLE_PRIMARY); + $pan->setBody($this->getIntroText()); + $intro_html = $pan->getHTML(); + } + + // $this->setTabs("list_skills"); + + if ($a_user_id == 0) { + $user_id = $ilUser->getId(); + } else { + $user_id = $a_user_id; + } + + $skills = array(); + if ($this->getProfileId() > 0) { + $profile = new ilSkillProfile($this->getProfileId()); + $this->profile_levels = $profile->getSkillLevels(); + + foreach ($this->profile_levels as $l) { + $skills[] = array( + "base_skill_id" => $l["base_skill_id"], + "tref_id" => $l["tref_id"], + "level_id" => $l["level_id"] + ); + } + } elseif (is_array($a_skills)) { + $skills = $a_skills; + } + + // get actual levels for gap analysis + $this->getActualLevels($skills, $user_id); + + $incl_self_eval = false; + if (count($this->getGapAnalysisSelfEvalLevels()) > 0) { + $incl_self_eval = true; + $self_vals = $this->getGapAnalysisSelfEvalLevels(); + } + + // output spider stuff + $all_chart_html = ""; + + // determine skills that should be shown in the spider web + $sw_skills = array(); + foreach ($skills as $sk) { + if (!in_array($sk["base_skill_id"] . ":" . $sk["tref_id"], $this->hidden_skills)) { + $sw_skills[] = $sk; + } + } + + if (count($sw_skills) >= 3) { + $skill_packages = array(); + + if (count($sw_skills) < 8) { + $skill_packages[1] = $sw_skills; + } else { + $mod = count($sw_skills) % 7; + $pkg_num = floor((count($sw_skills) - 1) / 7) + 1; + $cpkg = 1; + foreach ($sw_skills as $k => $s) { + $skill_packages[$cpkg][$k] = $s; + if ($mod < 3 && count($skill_packages) == ($pkg_num - 1) && count($skill_packages[$cpkg]) == 3+$mod) { + $cpkg+=1; + } elseif (count($skill_packages[$cpkg]) == 7) { + $cpkg+=1; + } + } + } + + $pkg_cnt = 0; + foreach ($skill_packages as $pskills) { + $pkg_cnt++; + $max_cnt = 0; + $leg_labels = array(); + //var_dump($this->profile_levels); + //foreach ($this->profile_levels as $k => $l) + + // write target, actual and self counter to skill array + foreach ($pskills as $k => $l) { + //$bs = new ilBasicSkill($l["base_skill_id"]); + $bs = new ilBasicSkill($l["base_skill_id"]); + $leg_labels[] = ilBasicSkill::_lookupTitle($l["base_skill_id"], $l["tref_id"]); + $levels = $bs->getLevelData(); + $cnt = 0; + foreach ($levels as $lv) { + $cnt++; + if ($l["level_id"] == $lv["id"]) { + $pskills[$k]["target_cnt"] = $cnt; + } + if ($this->actual_levels[$l["base_skill_id"]][$l["tref_id"]] == $lv["id"]) { + $pskills[$k]["actual_cnt"] = $cnt; + } + if ($incl_self_eval) { + if ($self_vals[$l["base_skill_id"]][$l["tref_id"]] == $lv["id"]) { + $pskills[$k]["self_cnt"] = $cnt; + } + } + $max_cnt = max($max_cnt, $cnt); + } + } + + include_once("./Services/Chart/classes/class.ilChart.php"); + $chart = ilChart::getInstanceByType(ilChart::TYPE_SPIDER, "gap_chart" . $pkg_cnt); + $chart->setsize(800, 300); + $chart->setYAxisMax($max_cnt); + $chart->setLegLabels($leg_labels); + + // target level + $cd = $chart->getDataInstance(); + $cd->setLabel($lng->txt("skmg_target_level")); + $cd->setFill(true, "#A0A0A0"); + + // other users + $cd2 = $chart->getDataInstance(); + if ($this->gap_cat_title != "") { + $cd2->setLabel($this->gap_cat_title); + } elseif ($this->gap_mode == "max_per_type") { + $cd2->setLabel($lng->txt("objs_" . $this->gap_mode_type)); + } elseif ($this->gap_mode == "max_per_object") { + $cd2->setLabel(ilObject::_lookupTitle($this->gap_mode_obj_id)); + } + //$cd2->setFill(true, "#dcb496"); + $cd2->setFill(true, "#FF8080"); + $cd2->setFill(true, "#cc8466"); + + // self evaluation + if ($incl_self_eval) { + $cd3 = $chart->getDataInstance(); + $cd3->setLabel($lng->txt("skmg_self_evaluation")); + $cd3->setFill(true, "#6ea03c"); + } + + // fill in data + $cnt = 0; + foreach ($pskills as $pl) { + $cd->addPoint($cnt, (int) $pl["target_cnt"]); + $cd2->addPoint($cnt, (int) $pl["actual_cnt"]); + if ($incl_self_eval) { + $cd3->addPoint($cnt, (int) $pl["self_cnt"]); + } + $cnt++; + } + + // add data to chart + if ($this->getProfileId() > 0) { + $chart->addData($cd); + } + $chart->addData($cd2); + if ($incl_self_eval && count($this->getGapAnalysisSelfEvalLevels()) > 0) { + $chart->addData($cd3); + } + + if ($pkg_cnt == 1) { + $lg = new ilChartLegend(); + $chart->setLegend($lg); + } + + $chart_html = $chart->getHTML(); + $all_chart_html.= $chart_html; + } + + $pan = ilPanelGUI::getInstance(); + $pan->setPanelStyle(ilPanelGUI::PANEL_STYLE_PRIMARY); + $pan->setBody($all_chart_html); + $all_chart_html = $pan->getHTML(); + } + + $stree = new ilSkillTree(); + $html = ""; + + // order skills per virtual skill tree + include_once("./Services/Skill/classes/class.ilVirtualSkillTree.php"); + $vtree = new ilVirtualSkillTree(); + $skills = $vtree->getOrderedNodeset($skills, "base_skill_id", "tref_id"); + foreach ($skills as $s) { + $path = $stree->getSkillTreePath($s["base_skill_id"]); + + // check draft + foreach ($path as $p) { + if ($p["status"] == ilSkillTreeNode::STATUS_DRAFT) { + continue(2); + } + } + $html.= $this->getSkillHTML($s["base_skill_id"], $user_id, false, $s["tref_id"]); + } + + // list skills + // include_once("./Services/Skill/classes/class.ilPersonalSkillTableGUI.php"); + // $sktab = new ilPersonalSkillTableGUI($this, "listSkills"); + + return $intro_html . $all_chart_html . $html; + } + + /** + * Select profile + * + * @param + */ + public function selectProfile() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameter($this, "profile_id", $_POST["profile_id"]); + if ($this->mode == "gap") { + $ilCtrl->redirect($this, "listProfilesForGap"); + } else { + $ilCtrl->redirect($this, "listAssignedProfile"); + } + } + + /** + * Get materials + * + * @param + * @return string + */ + public function getMaterials($a_levels, $a_tref_id = 0, $a_user_id = 0) + { + $ilUser = $this->user; + $lng = $this->lng; + + if ($a_user_id == 0) { + $a_user_id = $ilUser->getId(); + } + + // only render, if materials given + $got_mat = false; + foreach ($a_levels as $v) { + $mat_cnt = ilPersonalSkill::countAssignedMaterial( + $a_user_id, + $a_tref_id, + $v["id"] + ); + if ($mat_cnt > 0) { + $got_mat = true; + } + } + if (!$got_mat) { + return ""; + } + + $tpl = new ilTemplate("tpl.skill_materials.html", true, true, "Services/Skill"); + foreach ($a_levels as $k => $v) { + $got_mat = false; + foreach (ilPersonalSkill::getAssignedMaterial( + $a_user_id, + $a_tref_id, + $v["id"] + ) as $item) { + $tpl->setCurrentBlock("material"); + $mat_data = $this->getMaterialInfo($item["wsp_id"], $a_user_id); + $tpl->setVariable("HREF_LINK", $mat_data[1]); + $tpl->setVariable("TXT_LINK", $mat_data[0]); + $tpl->parseCurrentBlock(); + $got_mat = true; + } + if ($got_mat) { + $tpl->setCurrentBlock("level"); + $tpl->setVariable("LEVEL_VAL", $v["title"]); + $tpl->parseCurrentBlock(); + } + } + $tpl->setVariable("TXT_MATERIAL", $lng->txt("skmg_materials")); + + return $tpl->get(); + } + + /** + * Get profile target item + * + * @param + * @return + */ + public function getProfileTargetItem($a_profile_id, $a_levels, $a_tref_id = 0) + { + $lng = $this->lng; + + $profile = new ilSkillProfile($a_profile_id); + $profile_levels = $profile->getSkillLevels(); + + $a_activated_levels = array(); + + foreach ($a_levels as $k => $v) { + foreach ($profile_levels as $pl) { + if ($pl["level_id"] == $v["id"] && + $pl["base_skill_id"] == $v["skill_id"] && + $a_tref_id == $pl["tref_id"]) { + $a_activated_levels[] = $pl["level_id"]; + } + } + } + + $tpl = new ilTemplate("tpl.skill_eval_item.html", true, true, "Services/Skill"); + $tpl->setVariable("SCALE_BAR", $this->getScaleBar($a_levels, $a_activated_levels)); + + $tpl->setVariable("TYPE", $lng->txt("skmg_target_level")); + $tpl->setVariable("TITLE", ""); + + return $tpl->get(); + } + + /** + * + * + * @param + * @return + */ + public function getActualGapItem($a_levels, $a_tref_id = 0) + { + $lng = $this->lng; + + $a_activated_levels = array(); + foreach ($a_levels as $k => $v) { + if ($this->actual_levels[$v["skill_id"]][$a_tref_id] == $v["id"]) { + $a_activated_levels[] = $v["id"]; + } + } + + if ($this->gap_cat_title != "") { + $title = $this->gap_cat_title; + } elseif ($this->gap_mode == "max_per_type") { + $title = $lng->txt("objs_" . $this->gap_mode_type); + } elseif ($this->gap_mode == "max_per_object") { + $title = ilObject::_lookupTitle($this->gap_mode_obj_id); + } + + $tpl = new ilTemplate("tpl.skill_eval_item.html", true, true, "Services/Skill"); + $tpl->setVariable("SCALE_BAR", $this->getScaleBar($a_levels, $a_activated_levels)); + + $type = 1; + $tpl->setVariable("TYPE", $lng->txt("skmg_eval_type_" . $type)); + if ($type > 0) { + $tpl->touchBlock("st" . $type); + $tpl->touchBlock("stb" . $type); + } + + if ($title != $lng->txt("skmg_eval_type_" . $type)) { + $tpl->setVariable("TITLE", $title); + } + + return $tpl->get(); + } + + /** + * + * + * @param + * @return + */ + public function getSelfEvalGapItem($a_levels, $a_tref_id = 0) + { + $lng = $this->lng; + + $self_vals = $this->getGapAnalysisSelfEvalLevels(); + if (count($self_vals) == 0) { + return; + } + + $a_activated_levels = array(); + foreach ($a_levels as $k => $v) { + if ($self_vals[$v["skill_id"]][$a_tref_id] == $v["id"]) { + $a_activated_levels[] = $v["id"]; + } + } + + $tpl = new ilTemplate("tpl.skill_eval_item.html", true, true, "Services/Skill"); + $tpl->setVariable("SCALE_BAR", $this->getScaleBar($a_levels, $a_activated_levels)); + + $type = 3; + $tpl->setVariable("TYPE", $lng->txt("skmg_eval_type_" . $type)); + if ($type > 0) { + $tpl->touchBlock("st" . $type); + $tpl->touchBlock("stb" . $type); + } + + return $tpl->get(); + } + + + /** + * Get scale bar + * + * @param + * @return + */ + public function getScaleBar($a_levels, $a_activated_levels) + { + $vals = array(); + + if (!is_array($a_activated_levels)) { + $a_activated_levels = array($a_activated_levels); + } + + foreach ($a_levels as $level) { + $vals[$level["title"]] = (in_array($level["id"], $a_activated_levels)); + } + $scale_bar = $this->ui_fac->chart()->scaleBar($vals); + + return $this->ui_ren->render($scale_bar); + } + + /** + * Get eval item + * + * @param + * @return + */ + public function getEvalItem($a_levels, $a_level_entry) + { + $lng = $this->lng; + $ilAccess = $this->access; + + $tpl = new ilTemplate("tpl.skill_eval_item.html", true, true, "Services/Skill"); + $tpl->setVariable("SCALE_BAR", $this->getScaleBar($a_levels, $a_level_entry["level_id"])); + + include_once("./Services/Skill/classes/class.ilSkillEval.php"); + $type = ilSkillEval::TYPE_APPRAISAL; + + if ($a_level_entry["self_eval"] == 1) { + $type = ilSkillEval::TYPE_SELF_EVAL; + } + + if ($a_level_entry["trigger_obj_type"] == "tst") { + $type = ilSkillEval::TYPE_MEASUREMENT; + } + + ilDatePresentation::setUseRelativeDates(false); + $title = ($a_level_entry["trigger_obj_id"] > 0) + ? $a_level_entry["trigger_title"] + : ""; + + if ($a_level_entry["trigger_ref_id"] > 0 + && $ilAccess->checkAccess("read", "", $a_level_entry["trigger_ref_id"])) { + include_once("./Services/Link/classes/class.ilLink.php"); + $title = "" . $title . ""; + } + + $tpl->setVariable("TYPE", $lng->txt("skmg_eval_type_" . $type)); + if ($type > 0) { + $tpl->touchBlock("st" . $type); + $tpl->touchBlock("stb" . $type); + } + $tpl->setVariable("TITLE", $title); + $tpl->setVariable( + "DATE", + ilDatePresentation::formatDate(new ilDate($a_level_entry["status_date"], IL_CAL_DATETIME)) + ); + + ilDatePresentation::setUseRelativeDates(true); + + return $tpl->get(); + } + + /** + * Get level description + * + * @param + * @return + */ + public function getSkillDescription($skill) + { + $level_data = $skill->getLevelData(); + $tpl = new ilTemplate("tpl.skill_desc.html", true, true, "Services/Skill"); + + $desc_exists = false; + foreach ($level_data as $l) { + if ($l["description"] != "") { + $desc_exists = true; + } + } + reset($level_data); + if ($desc_exists) { + foreach ($level_data as $l) { + $tpl->setCurrentBlock("level"); + $tpl->setVariable("LEVEL_VAL", $l["title"]); + $tpl->setVariable("LEVEL_DESC", $l["description"]); + $tpl->parseCurrentBlock(); + } + } + + return $tpl->get(); + } + + /** + * Render suggested resources + * + * @param + * @return + */ + public function getSuggestedResources($a_profile_id, $a_levels, $a_base_skill, $a_tref_id) + { + $lng = $this->lng; + + $tpl = new ilTemplate("tpl.suggested_resources.html", true, true, "Services/Skill"); + + // use a profile + if ($a_profile_id > 0) { + $too_low = true; + $current_target_level = 0; + + foreach ($a_levels as $k => $v) { + foreach ($this->profile_levels as $pl) { + if ($pl["level_id"] == $v["id"] && + $pl["base_skill_id"] == $v["skill_id"]) { + $too_low = true; + $current_target_level = $v["id"]; + } + } + + if ($this->actual_levels[$v["skill_id"]][$a_tref_id] == $v["id"]) { + $too_low = false; + } + } + + // suggested resources + if ($too_low) { + include_once("./Services/Skill/classes/class.ilSkillResources.php"); + $skill_res = new ilSkillResources($a_base_skill, $a_tref_id); + $res = $skill_res->getResources(); + $imp_resources = array(); + foreach ($res as $level) { + foreach ($level as $r) { + if ($r["imparting"] == true && + $current_target_level == $r["level_id"]) { + $imp_resources[] = $r; + } + } + } + foreach ($imp_resources as $r) { + $ref_id = $r["rep_ref_id"]; + $obj_id = ilObject::_lookupObjId($ref_id); + $title = ilObject::_lookupTitle($obj_id); + include_once("./Services/Link/classes/class.ilLink.php"); + $tpl->setCurrentBlock("resource_item"); + $tpl->setVariable("TXT_RES", $title); + $tpl->setVariable("HREF_RES", ilLink::_getLink($ref_id)); + $tpl->parseCurrentBlock(); + } + if (count($imp_resources) > 0) { + $tpl->touchBlock("resources_list"); + $tpl->setVariable("SUGGESTED_MAT_MESS", $lng->txt("skmg_skill_needs_impr_res")); + return $tpl->get(); + } else { + $tpl->setVariable("SUGGESTED_MAT_MESS", $lng->txt("skmg_skill_needs_impr_no_res")); + return $tpl->get(); + } + } else { + $tpl->setVariable("SUGGESTED_MAT_MESS", $lng->txt("skmg_skill_no_needs_impr")); + return $tpl->get(); + } + } else { + // no profile, just list all resources + include_once("./Services/Skill/classes/class.ilSkillResources.php"); + $skill_res = new ilSkillResources($a_base_skill, $a_tref_id); + $res = $skill_res->getResources(); + // add $r["level_id"] info + $any = false; + foreach ($res as $level) { + $available = false; + $cl = 0; + foreach ($level as $r) { + if ($r["imparting"]) { + $ref_id = $r["rep_ref_id"]; + $obj_id = ilObject::_lookupObjId($ref_id); + $title = ilObject::_lookupTitle($obj_id); + include_once("./Services/Link/classes/class.ilLink.php"); + $tpl->setCurrentBlock("resource_item"); + $tpl->setVariable("TXT_RES", $title); + $tpl->setVariable("HREF_RES", ilLink::_getLink($ref_id)); + $tpl->parseCurrentBlock(); + $available = true; + $any = true; + $cl = $r["level_id"]; + } + } + if ($available) { + $tpl->setCurrentBlock("resources_list_level"); + $tpl->setVariable("TXT_LEVEL", $lng->txt("skmg_level")); + $tpl->setVariable("LEVEL_NAME", ilBasicSkill::lookupLevelTitle($cl)); + $tpl->parseCurrentBlock(); + $tpl->touchBlock("resources_list"); + } + } + if ($any) { + $tpl->setVariable("SUGGESTED_MAT_MESS", $lng->txt("skmg_suggested_resources")); + return $tpl->get(); + } + } + return ""; + } + + /** + * List profile + * + * @param + * @return + */ + public function listAssignedProfile() + { + $ilCtrl = $this->ctrl; + + $main_tpl = $this->tpl; + + $tpl = new ilTemplate("tpl.skill_filter.html", true, true, "Services/Skill"); + + $this->setTabs("profile"); + + $this->determineCurrentProfile(); + $this->showProfileSelectorToolbar(); + + $filter_toolbar = new ilToolbarGUI(); + $filter_toolbar->setFormAction($ilCtrl->getFormAction($this)); + $this->getFilter()->addToToolbar($filter_toolbar, true); + + $skills = array(); + if ($this->getProfileId() > 0) { + $profile = new ilSkillProfile($this->getProfileId()); + $this->profile_levels = $profile->getSkillLevels(); + + foreach ($this->profile_levels as $l) { + $skills[] = array( + "base_skill_id" => $l["base_skill_id"], + "tref_id" => $l["tref_id"], + "level_id" => $l["level_id"] + ); + } + } + + $this->getActualLevels($skills, $this->user->getId()); + + // render + $html = ""; + foreach ($skills as $s) { + // todo draft check + $html.= $this->getSkillHTML($s["base_skill_id"], 0, true, $s["tref_id"]); + } + + if ($html != "") { + $filter_toolbar->addFormButton($this->lng->txt("skmg_refresh_view"), "applyFilterAssignedProfiles"); + + $tpl->setVariable("FILTER", $filter_toolbar->getHTML()); + + $html = $tpl->get() . $html; + } + + $main_tpl->setContent($html); + } } -?> \ No newline at end of file diff --git a/Services/Skill/classes/class.ilSelfEvaluationSimpleTableGUI.php b/Services/Skill/classes/class.ilSelfEvaluationSimpleTableGUI.php index 6e22600a2f41b2694021b7df4da0e2153a1ee8d2..d5a979c3c4156af64e7ec9716e2dca204c3f37ff 100644 --- a/Services/Skill/classes/class.ilSelfEvaluationSimpleTableGUI.php +++ b/Services/Skill/classes/class.ilSelfEvaluationSimpleTableGUI.php @@ -14,121 +14,125 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilSelfEvaluationSimpleTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_top_skill_id, $a_tref_id, - $a_basic_skill_id) - { - global $DIC; + + /** + * Constructor + */ + public function __construct( + $a_parent_obj, + $a_parent_cmd, + $a_top_skill_id, + $a_tref_id, + $a_basic_skill_id + ) { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $this->user = $DIC->user(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->user = $DIC->user(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilUser = $DIC->user(); - - $this->top_skill_id = $a_top_skill_id; - $this->tref_id = (int) $a_tref_id; - $this->basic_skill_id = $a_basic_skill_id; + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilUser = $DIC->user(); + + $this->top_skill_id = $a_top_skill_id; + $this->tref_id = (int) $a_tref_id; + $this->basic_skill_id = $a_basic_skill_id; - $this->cur_level_id = ilPersonalSkill::getSelfEvaluation($ilUser->getId(), - $this->top_skill_id, $this->tref_id, $this->basic_skill_id); - - // build title - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $stree = new ilSkillTree(); - $path = $stree->getPathFull($this->basic_skill_id); - $title = $sep = ""; - foreach ($path as $p) - { - if ($p["type"] != "skrt") - { - $title.= $sep.$p["title"]; - $sep = " > "; - } - } + $this->cur_level_id = ilPersonalSkill::getSelfEvaluation( + $ilUser->getId(), + $this->top_skill_id, + $this->tref_id, + $this->basic_skill_id + ); + + // build title + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $stree = new ilSkillTree(); + $path = $stree->getPathFull($this->basic_skill_id); + $title = $sep = ""; + foreach ($path as $p) { + if ($p["type"] != "skrt") { + $title.= $sep . $p["title"]; + $sep = " > "; + } + } - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setData($this->getLevels()); - $this->setTitle($title); - $this->setLimit(9999); - - $this->addColumn("", "", "", true); - $this->addColumn($this->lng->txt("skmg_skill_level")); - $this->addColumn($this->lng->txt("description")); - - $this->setEnableHeader(true); - $this->setRowTemplate("tpl.simple_self_eval.html", "Services/Skill"); - $this->disable("footer"); - $this->setEnableTitle(true); - - $this->addCommandButton("saveSelfEvaluation", - $lng->txt("save")); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - } + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setData($this->getLevels()); + $this->setTitle($title); + $this->setLimit(9999); + + $this->addColumn("", "", "", true); + $this->addColumn($this->lng->txt("skmg_skill_level")); + $this->addColumn($this->lng->txt("description")); + + $this->setEnableHeader(true); + $this->setRowTemplate("tpl.simple_self_eval.html", "Services/Skill"); + $this->disable("footer"); + $this->setEnableTitle(true); + + $this->addCommandButton( + "saveSelfEvaluation", + $lng->txt("save") + ); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + } - /** - * Get levels - * - * @param - * @return - */ - function getLevels() - { - $lng = $this->lng; - - include_once("./Services/Skill/classes/class.ilSkillTreeNodeFactory.php"); - $this->skill = ilSkillTreeNodeFactory::getInstance($this->basic_skill_id); - $levels[] = array("id" => 0, "description" => $lng->txt("skmg_no_skills")); - foreach ($this->skill->getLevelData() as $k => $v) - { - $levels[] = $v; - } + /** + * Get levels + * + * @param + * @return + */ + public function getLevels() + { + $lng = $this->lng; + + include_once("./Services/Skill/classes/class.ilSkillTreeNodeFactory.php"); + $this->skill = ilSkillTreeNodeFactory::getInstance($this->basic_skill_id); + $levels[] = array("id" => 0, "description" => $lng->txt("skmg_no_skills")); + foreach ($this->skill->getLevelData() as $k => $v) { + $levels[] = $v; + } - return $levels; - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilUser = $this->user; + return $levels; + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilUser = $this->user; - include_once("./Services/Skill/classes/class.ilPersonalSkill.php"); + include_once("./Services/Skill/classes/class.ilPersonalSkill.php"); - if ($this->cur_level_id == $a_set["id"]) - { - $this->tpl->setVariable("CHECKED", "checked='checked'"); - } - - $this->tpl->setVariable("LEVEL_ID", $a_set["id"]); - $this->tpl->setVariable("SKILL_ID", $this->basic_skill_id); - $this->tpl->setVariable("TXT_SKILL", $a_set["title"]); - $this->tpl->setVariable("TXT_SKILL_DESC", $a_set["description"]); - } - + if ($this->cur_level_id == $a_set["id"]) { + $this->tpl->setVariable("CHECKED", "checked='checked'"); + } + + $this->tpl->setVariable("LEVEL_ID", $a_set["id"]); + $this->tpl->setVariable("SKILL_ID", $this->basic_skill_id); + $this->tpl->setVariable("TXT_SKILL", $a_set["title"]); + $this->tpl->setVariable("TXT_SKILL_DESC", $a_set["description"]); + } } -?> diff --git a/Services/Skill/classes/class.ilSelfEvaluationTableGUI.php b/Services/Skill/classes/class.ilSelfEvaluationTableGUI.php index 65492da24086da640fa6a68c03ca00f9b4dd7e68..7bd4f4361b760081dec818f47f5d5e6197f0a7c1 100644 --- a/Services/Skill/classes/class.ilSelfEvaluationTableGUI.php +++ b/Services/Skill/classes/class.ilSelfEvaluationTableGUI.php @@ -15,77 +15,79 @@ include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); */ class ilSelfEvaluationTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd) - { - global $DIC; + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $this->user = $DIC->user(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilAccess = $DIC->access(); - $lng = $DIC->language(); - $ilUser = $DIC->user(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - include_once("./Services/Skill/classes/class.ilSkillSelfEvaluation.php"); - $this->setData(ilSkillSelfEvaluation::getAllSelfEvaluationsOfUser($ilUser->getId())); - $this->setTitle($lng->txt("skmg_self_evaluations")); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->user = $DIC->user(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilAccess = $DIC->access(); + $lng = $DIC->language(); + $ilUser = $DIC->user(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + include_once("./Services/Skill/classes/class.ilSkillSelfEvaluation.php"); + $this->setData(ilSkillSelfEvaluation::getAllSelfEvaluationsOfUser($ilUser->getId())); + $this->setTitle($lng->txt("skmg_self_evaluations")); - $this->addColumn("", "", 1); - $this->addColumn($this->lng->txt("created")); - $this->addColumn($this->lng->txt("last_update")); - $this->addColumn($this->lng->txt("skmg_skill")); - $this->addColumn($this->lng->txt("actions")); - - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.self_eval_overview_row.html", "Services/Skill"); - $this->setEnableTitle(true); - - $this->addMultiCommand("confirmSelfEvaluationDeletion", $lng->txt("delete")); - //$this->addCommandButton("", $lng->txt("")); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; + $this->addColumn("", "", 1); + $this->addColumn($this->lng->txt("created")); + $this->addColumn($this->lng->txt("last_update")); + $this->addColumn($this->lng->txt("skmg_skill")); + $this->addColumn($this->lng->txt("actions")); + + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.self_eval_overview_row.html", "Services/Skill"); + $this->setEnableTitle(true); + + $this->addMultiCommand("confirmSelfEvaluationDeletion", $lng->txt("delete")); + //$this->addCommandButton("", $lng->txt("")); + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; - $this->tpl->setVariable("SE_ID", $a_set["id"]); - $this->tpl->setVariable("VAL_CREATED", $a_set["created"]); - $this->tpl->setVariable("VAL_LAST_UPDATE", $a_set["last_update"]); - $this->tpl->setVariable("VAL_SKILL", - ilSkillTreeNode::_lookupTitle($a_set["top_skill_id"])); - $this->tpl->setVariable("TXT_CMD", $lng->txt("edit")); - $ilCtrl->setParameter($this->parent_obj, "se_id", $a_set["id"]); - $this->tpl->setVariable("HREF_CMD", - $ilCtrl->getLinkTarget($this->parent_obj, "editSelfEvaluation")); - } - + $this->tpl->setVariable("SE_ID", $a_set["id"]); + $this->tpl->setVariable("VAL_CREATED", $a_set["created"]); + $this->tpl->setVariable("VAL_LAST_UPDATE", $a_set["last_update"]); + $this->tpl->setVariable( + "VAL_SKILL", + ilSkillTreeNode::_lookupTitle($a_set["top_skill_id"]) + ); + $this->tpl->setVariable("TXT_CMD", $lng->txt("edit")); + $ilCtrl->setParameter($this->parent_obj, "se_id", $a_set["id"]); + $this->tpl->setVariable( + "HREF_CMD", + $ilCtrl->getLinkTarget($this->parent_obj, "editSelfEvaluation") + ); + } } -?> diff --git a/Services/Skill/classes/class.ilSkillAppEventListener.php b/Services/Skill/classes/class.ilSkillAppEventListener.php index 524ca1a4935545b2981c19d8ccbdb7e3d02a642a..1c11e05a36ae6e833ad56f637c666aaaeb751258 100644 --- a/Services/Skill/classes/class.ilSkillAppEventListener.php +++ b/Services/Skill/classes/class.ilSkillAppEventListener.php @@ -1,66 +1,62 @@ - - * @version $Id$ - * - * @ingroup ServicesTracking - */ -class ilSkillAppEventListener implements ilAppEventListener -{ - /** - * Handle an event in a listener. - * - * @param string $a_component component, e.g. "Modules/Forum" or "Services/User" - * @param string $a_event event e.g. "createUser", "updateUser", "deleteUser", ... - * @param array $a_parameter parameter array (assoc), array("name" => ..., "phone_office" => ...) - */ - public static function handleEvent($a_component, $a_event, $a_params) - { - switch($a_component) - { - case 'Services/Tracking': - switch($a_event) - { - case 'updateStatus': - if ($a_params["status"] == ilLPStatus::LP_STATUS_COMPLETED_NUM) - { - $obj_id = $a_params["obj_id"]; - $usr_id = $a_params["usr_id"]; - include_once("./Services/Skill/classes/class.ilSkillResources.php"); - include_once("./Services/Skill/classes/class.ilBasicSkill.php"); - foreach (ilObject::_getAllReferences($obj_id) as $ref_id) - { - foreach (ilSkillResources::getTriggerLevelsForRefId($ref_id) as $sk) - { - ilBasicSkill::writeUserSkillLevelStatus($sk["level_id"], $usr_id, - $ref_id, $sk["tref_id"]); - } - } - } - break; - } - break; - - case "Services/Object": - switch ($a_event) - { - case "beforeDeletion": - $handler = new ilSkillObjDeletionHandler($a_params["object"]->getId(), $a_params["object"]->getType()); - $handler->processDeletion(); - break; - } - break; - - } - - return true; - } -} - -?> \ No newline at end of file + + * @version $Id$ + * + * @ingroup ServicesTracking + */ +class ilSkillAppEventListener implements ilAppEventListener +{ + /** + * Handle an event in a listener. + * + * @param string $a_component component, e.g. "Modules/Forum" or "Services/User" + * @param string $a_event event e.g. "createUser", "updateUser", "deleteUser", ... + * @param array $a_parameter parameter array (assoc), array("name" => ..., "phone_office" => ...) + */ + public static function handleEvent($a_component, $a_event, $a_params) + { + switch ($a_component) { + case 'Services/Tracking': + switch ($a_event) { + case 'updateStatus': + if ($a_params["status"] == ilLPStatus::LP_STATUS_COMPLETED_NUM) { + $obj_id = $a_params["obj_id"]; + $usr_id = $a_params["usr_id"]; + include_once("./Services/Skill/classes/class.ilSkillResources.php"); + include_once("./Services/Skill/classes/class.ilBasicSkill.php"); + foreach (ilObject::_getAllReferences($obj_id) as $ref_id) { + foreach (ilSkillResources::getTriggerLevelsForRefId($ref_id) as $sk) { + ilBasicSkill::writeUserSkillLevelStatus( + $sk["level_id"], + $usr_id, + $ref_id, + $sk["tref_id"] + ); + } + } + } + break; + } + break; + + case "Services/Object": + switch ($a_event) { + case "beforeDeletion": + $handler = new ilSkillObjDeletionHandler($a_params["object"]->getId(), $a_params["object"]->getType()); + $handler->processDeletion(); + break; + } + break; + + } + + return true; + } +} diff --git a/Services/Skill/classes/class.ilSkillAssignMaterialsTableGUI.php b/Services/Skill/classes/class.ilSkillAssignMaterialsTableGUI.php index 134b315551fb8ebe367e55c12f4cc8fdd24b434a..28807e3d293244e929e21e0b4f8e2382aa3e6139 100644 --- a/Services/Skill/classes/class.ilSkillAssignMaterialsTableGUI.php +++ b/Services/Skill/classes/class.ilSkillAssignMaterialsTableGUI.php @@ -14,138 +14,142 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilSkillAssignMaterialsTableGUI extends ilTable2GUI { - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_top_skill_id, $a_tref_id, - $a_basic_skill_id) - { - global $DIC; + + /** + * Constructor + */ + public function __construct( + $a_parent_obj, + $a_parent_cmd, + $a_top_skill_id, + $a_tref_id, + $a_basic_skill_id + ) { + global $DIC; - $this->user = $DIC->user(); - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - $ilUser = $DIC->user(); + $this->user = $DIC->user(); + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $ilUser = $DIC->user(); - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; - $this->ws_tree = new ilWorkspaceTree($ilUser->getId()); - $this->ws_access = new ilWorkspaceAccessHandler(); + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; + $this->ws_tree = new ilWorkspaceTree($ilUser->getId()); + $this->ws_access = new ilWorkspaceAccessHandler(); - $this->top_skill_id = $a_top_skill_id; - $this->tref_id = (int) $a_tref_id; - $this->basic_skill_id = $a_basic_skill_id; - - // workspace tree - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - $this->ws_tree = new ilWorkspaceTree($ilUser->getId()); + $this->top_skill_id = $a_top_skill_id; + $this->tref_id = (int) $a_tref_id; + $this->basic_skill_id = $a_basic_skill_id; + + // workspace tree + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + $this->ws_tree = new ilWorkspaceTree($ilUser->getId()); - // build title - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $stree = new ilSkillTree(); - $path = $stree->getPathFull($this->basic_skill_id); - $title = $sep = ""; - foreach ($path as $p) - { - if ($p["type"] != "skrt") - { - $title.= $sep.$p["title"]; - $sep = " > "; - } - } + // build title + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $stree = new ilSkillTree(); + $path = $stree->getPathFull($this->basic_skill_id); + $title = $sep = ""; + foreach ($path as $p) { + if ($p["type"] != "skrt") { + $title.= $sep . $p["title"]; + $sep = " > "; + } + } - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setData($this->getLevels()); - $this->setTitle($title); - $this->setLimit(9999); - - $this->addColumn($this->lng->txt("skmg_skill_level")); - $this->addColumn($this->lng->txt("description")); - $this->addColumn($this->lng->txt("skmg_materials")); - $this->addColumn($this->lng->txt("actions")); - - $this->setEnableHeader(true); -// $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.skill_materials_row.html", "Services/Skill"); - $this->disable("footer"); - $this->setEnableTitle(true); - -// $this->addMultiCommand("", $lng->txt("")); + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setData($this->getLevels()); + $this->setTitle($title); + $this->setLimit(9999); + + $this->addColumn($this->lng->txt("skmg_skill_level")); + $this->addColumn($this->lng->txt("description")); + $this->addColumn($this->lng->txt("skmg_materials")); + $this->addColumn($this->lng->txt("actions")); + + $this->setEnableHeader(true); + // $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.skill_materials_row.html", "Services/Skill"); + $this->disable("footer"); + $this->setEnableTitle(true); + + // $this->addMultiCommand("", $lng->txt("")); // $this->addCommandButton("", $lng->txt("")); - } + } - /** - * Get levels - * - * @param - * @return - */ - function getLevels() - { - include_once("./Services/Skill/classes/class.ilSkillTreeNodeFactory.php"); - $this->skill = ilSkillTreeNodeFactory::getInstance($this->basic_skill_id); - foreach ($this->skill->getLevelData() as $k => $v) - { - $levels[] = $v; - } + /** + * Get levels + * + * @param + * @return + */ + public function getLevels() + { + include_once("./Services/Skill/classes/class.ilSkillTreeNodeFactory.php"); + $this->skill = ilSkillTreeNodeFactory::getInstance($this->basic_skill_id); + foreach ($this->skill->getLevelData() as $k => $v) { + $levels[] = $v; + } - return $levels; - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilUser = $this->user; + return $levels; + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilUser = $this->user; - include_once("./Services/Skill/classes/class.ilPersonalSkill.php"); - $mat = ilPersonalSkill::getAssignedMaterial($ilUser->getId(), $this->tref_id, $a_set["id"]); - $ilCtrl->setParameter($this->parent_obj, "level_id", $a_set["id"]); - foreach ($mat as $m) - { - $this->tpl->setCurrentBlock("mat"); - $obj_id = $this->ws_tree->lookupObjectId($m["wsp_id"]); - $this->tpl->setVariable("MAT_TITLE", - ilObject::_lookupTitle($obj_id)); - $this->tpl->setVariable("MAT_IMG", - ilUtil::img(ilUtil::getImagePath("icon_".ilObject::_lookupType($obj_id).".svg"))); - $this->tpl->setVariable("TXT_REMOVE", $lng->txt("remove")); - $ilCtrl->setParameter($this->parent_obj, "wsp_id", $m["wsp_id"]); - $this->tpl->setVariable("HREF_REMOVE", $ilCtrl->getLinkTarget($this->parent_obj, "removeMaterial")); + include_once("./Services/Skill/classes/class.ilPersonalSkill.php"); + $mat = ilPersonalSkill::getAssignedMaterial($ilUser->getId(), $this->tref_id, $a_set["id"]); + $ilCtrl->setParameter($this->parent_obj, "level_id", $a_set["id"]); + foreach ($mat as $m) { + $this->tpl->setCurrentBlock("mat"); + $obj_id = $this->ws_tree->lookupObjectId($m["wsp_id"]); + $this->tpl->setVariable( + "MAT_TITLE", + ilObject::_lookupTitle($obj_id) + ); + $this->tpl->setVariable( + "MAT_IMG", + ilUtil::img(ilUtil::getImagePath("icon_" . ilObject::_lookupType($obj_id) . ".svg")) + ); + $this->tpl->setVariable("TXT_REMOVE", $lng->txt("remove")); + $ilCtrl->setParameter($this->parent_obj, "wsp_id", $m["wsp_id"]); + $this->tpl->setVariable("HREF_REMOVE", $ilCtrl->getLinkTarget($this->parent_obj, "removeMaterial")); - $obj_id = $this->ws_tree->lookupObjectId($m["wsp_id"]); - $url = $this->ws_access->getGotoLink($m["wsp_id"], $obj_id); - $this->tpl->setVariable("HREF_MAT", $url); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setCurrentBlock("cmd"); - $this->tpl->setVariable("HREF_CMD", $ilCtrl->getLinkTarget($this->parent_obj, - "assignMaterial")); - $this->tpl->setVariable("TXT_CMD", $lng->txt("skmg_assign_materials")); - $this->tpl->parseCurrentBlock(); - $ilCtrl->setParameter($this->parent_obj, "level_id", ""); - - $this->tpl->setVariable("LEVEL_ID", $a_set["id"]); - $this->tpl->setVariable("SKILL_ID", $this->basic_skill_id); - $this->tpl->setVariable("TXT_SKILL", $a_set["title"]); - $this->tpl->setVariable("TXT_SKILL_DESC", $a_set["description"]); - } - + $obj_id = $this->ws_tree->lookupObjectId($m["wsp_id"]); + $url = $this->ws_access->getGotoLink($m["wsp_id"], $obj_id); + $this->tpl->setVariable("HREF_MAT", $url); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setCurrentBlock("cmd"); + $this->tpl->setVariable("HREF_CMD", $ilCtrl->getLinkTarget( + $this->parent_obj, + "assignMaterial" + )); + $this->tpl->setVariable("TXT_CMD", $lng->txt("skmg_assign_materials")); + $this->tpl->parseCurrentBlock(); + $ilCtrl->setParameter($this->parent_obj, "level_id", ""); + + $this->tpl->setVariable("LEVEL_ID", $a_set["id"]); + $this->tpl->setVariable("SKILL_ID", $this->basic_skill_id); + $this->tpl->setVariable("TXT_SKILL", $a_set["title"]); + $this->tpl->setVariable("TXT_SKILL_DESC", $a_set["description"]); + } } -?> diff --git a/Services/Skill/classes/class.ilSkillCatTableGUI.php b/Services/Skill/classes/class.ilSkillCatTableGUI.php index 69de83b058ee5fc6da8593342dfa759222ae6b5a..3c7cc3ff1ce45d4ca940bdf11a1fb8b515175295 100644 --- a/Services/Skill/classes/class.ilSkillCatTableGUI.php +++ b/Services/Skill/classes/class.ilSkillCatTableGUI.php @@ -5,7 +5,7 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); /** - * TableGUI class for + * TableGUI class for * * @author Alex Killing * @version $Id$ @@ -14,163 +14,163 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilSkillCatTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - const MODE_SCAT = 0; - const MODE_SCTP = 1; - protected $tref_id = 0; + const MODE_SCAT = 0; + const MODE_SCTP = 1; + protected $tref_id = 0; - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_obj_id, - $a_mode = self::MODE_SCAT, $a_tref_id = 0) - { - global $DIC; + /** + * Constructor + */ + public function __construct( + $a_parent_obj, + $a_parent_cmd, + $a_obj_id, + $a_mode = self::MODE_SCAT, + $a_tref_id = 0 + ) { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->tref_id = $a_tref_id; - $ilCtrl->setParameter($a_parent_obj, "tmpmode", $a_mode); - - $this->mode = $a_mode; - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $this->skill_tree = new ilSkillTree(); - $this->obj_id = $a_obj_id; + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->tref_id = $a_tref_id; + $ilCtrl->setParameter($a_parent_obj, "tmpmode", $a_mode); + + $this->mode = $a_mode; + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $this->skill_tree = new ilSkillTree(); + $this->obj_id = $a_obj_id; - parent::__construct($a_parent_obj, $a_parent_cmd); - - if ($this->mode == self::MODE_SCAT) - { - $childs = $this->skill_tree->getChildsByTypeFilter($a_obj_id, - array("skrt", "skll", "scat", "sktr")); - $childs = ilUtil::sortArray($childs, "order_nr", "asc", true); - $this->setData($childs); - } - else if ($this->mode == self::MODE_SCTP) - { - $childs = $this->skill_tree->getChildsByTypeFilter($a_obj_id, - array("skrt", "sktp", "sctp")); - $childs = ilUtil::sortArray($childs, "order_nr", "asc", true); - $this->setData($childs); - } - - if ($this->obj_id != $this->skill_tree->readRootId()) - { -// $this->setTitle(ilSkillTreeNode::_lookupTitle($this->obj_id)); - } - $this->setTitle($lng->txt("skmg_items")); - - if ($this->tref_id == 0) - { - $this->addColumn($this->lng->txt(""), "", "1px", true); - } - $this->addColumn($this->lng->txt("type"), "", "1px"); - if ($this->tref_id == 0) - { - $this->addColumn($this->lng->txt("skmg_order"), "", "1px"); - } - $this->addColumn($this->lng->txt("title")); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.skill_cat_row.html", "Services/Skill"); + parent::__construct($a_parent_obj, $a_parent_cmd); + + if ($this->mode == self::MODE_SCAT) { + $childs = $this->skill_tree->getChildsByTypeFilter( + $a_obj_id, + array("skrt", "skll", "scat", "sktr") + ); + $childs = ilUtil::sortArray($childs, "order_nr", "asc", true); + $this->setData($childs); + } elseif ($this->mode == self::MODE_SCTP) { + $childs = $this->skill_tree->getChildsByTypeFilter( + $a_obj_id, + array("skrt", "sktp", "sctp") + ); + $childs = ilUtil::sortArray($childs, "order_nr", "asc", true); + $this->setData($childs); + } + + if ($this->obj_id != $this->skill_tree->readRootId()) { + // $this->setTitle(ilSkillTreeNode::_lookupTitle($this->obj_id)); + } + $this->setTitle($lng->txt("skmg_items")); + + if ($this->tref_id == 0) { + $this->addColumn($this->lng->txt(""), "", "1px", true); + } + $this->addColumn($this->lng->txt("type"), "", "1px"); + if ($this->tref_id == 0) { + $this->addColumn($this->lng->txt("skmg_order"), "", "1px"); + } + $this->addColumn($this->lng->txt("title")); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.skill_cat_row.html", "Services/Skill"); - if ($this->tref_id == 0 && $this->parent_obj->checkPermissionBool("write")) - { - $this->addMultiCommand("cutItems", $lng->txt("cut")); - $this->addMultiCommand("copyItems", $lng->txt("copy")); - $this->addMultiCommand("deleteNodes", $lng->txt("delete")); - if ($a_mode == self::MODE_SCAT) - { - $this->addMultiCommand("exportSelectedNodes", $lng->txt("export")); - } - $this->addCommandButton("saveOrder", $lng->txt("skmg_save_order")); - } - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; + if ($this->tref_id == 0 && $this->parent_obj->checkPermissionBool("write")) { + $this->addMultiCommand("cutItems", $lng->txt("cut")); + $this->addMultiCommand("copyItems", $lng->txt("copy")); + $this->addMultiCommand("deleteNodes", $lng->txt("delete")); + if ($a_mode == self::MODE_SCAT) { + $this->addMultiCommand("exportSelectedNodes", $lng->txt("export")); + } + $this->addCommandButton("saveOrder", $lng->txt("skmg_save_order")); + } + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; - switch($a_set["type"]) - { - // category - case "scat": - $ilCtrl->setParameterByClass("ilskillcategorygui", "obj_id", $a_set["child"]); - $ret = $ilCtrl->getLinkTargetByClass("ilskillcategorygui", "listItems"); - $ilCtrl->setParameterByClass("ilskillcategorygui", "obj_id", $_GET["obj_id"]); - break; - - // skill template reference - case "sktr": - $tid = ilSkillTemplateReference::_lookupTemplateId($a_set["child"]); - $ilCtrl->setParameterByClass("ilskilltemplatereferencegui", "tref_id", $a_set["child"]); - $ilCtrl->setParameterByClass("ilskilltemplatereferencegui", "obj_id", $tid); - $ret = $ilCtrl->getLinkTargetByClass("ilskilltemplatereferencegui", "listItems"); - $ilCtrl->setParameterByClass("ilskilltemplatereferencegui", "obj_id", $_GET["obj_id"]); - $ilCtrl->setParameterByClass("ilskilltemplatereferencegui", "tref_id", $_GET["tref_id"]); - break; - - // skill - case "skll": - $ilCtrl->setParameterByClass("ilbasicskillgui", "obj_id", $a_set["child"]); - $ret = $ilCtrl->getLinkTargetByClass("ilbasicskillgui", "edit"); - $ilCtrl->setParameterByClass("ilbasicskillgui", "obj_id", $_GET["obj_id"]); - break; - - // -------- - - // template - case "sktp": - $ilCtrl->setParameterByClass("ilbasicskilltemplategui", "obj_id", $a_set["child"]); - $ret = $ilCtrl->getLinkTargetByClass("ilbasicskilltemplategui", "edit"); - $ilCtrl->setParameterByClass("ilbasicskilltemplategui", "obj_id", $_GET["obj_id"]); - break; + switch ($a_set["type"]) { + // category + case "scat": + $ilCtrl->setParameterByClass("ilskillcategorygui", "obj_id", $a_set["child"]); + $ret = $ilCtrl->getLinkTargetByClass("ilskillcategorygui", "listItems"); + $ilCtrl->setParameterByClass("ilskillcategorygui", "obj_id", $_GET["obj_id"]); + break; + + // skill template reference + case "sktr": + $tid = ilSkillTemplateReference::_lookupTemplateId($a_set["child"]); + $ilCtrl->setParameterByClass("ilskilltemplatereferencegui", "tref_id", $a_set["child"]); + $ilCtrl->setParameterByClass("ilskilltemplatereferencegui", "obj_id", $tid); + $ret = $ilCtrl->getLinkTargetByClass("ilskilltemplatereferencegui", "listItems"); + $ilCtrl->setParameterByClass("ilskilltemplatereferencegui", "obj_id", $_GET["obj_id"]); + $ilCtrl->setParameterByClass("ilskilltemplatereferencegui", "tref_id", $_GET["tref_id"]); + break; + + // skill + case "skll": + $ilCtrl->setParameterByClass("ilbasicskillgui", "obj_id", $a_set["child"]); + $ret = $ilCtrl->getLinkTargetByClass("ilbasicskillgui", "edit"); + $ilCtrl->setParameterByClass("ilbasicskillgui", "obj_id", $_GET["obj_id"]); + break; + + // -------- + + // template + case "sktp": + $ilCtrl->setParameterByClass("ilbasicskilltemplategui", "obj_id", $a_set["child"]); + $ret = $ilCtrl->getLinkTargetByClass("ilbasicskilltemplategui", "edit"); + $ilCtrl->setParameterByClass("ilbasicskilltemplategui", "obj_id", $_GET["obj_id"]); + break; - // template category - case "sctp": - $ilCtrl->setParameterByClass("ilskilltemplatecategorygui", "obj_id", $a_set["child"]); - $ret = $ilCtrl->getLinkTargetByClass("ilskilltemplatecategorygui", "listItems"); - $ilCtrl->setParameterByClass("ilskilltemplatecategorygui", "obj_id", $_GET["obj_id"]); - break; - } + // template category + case "sctp": + $ilCtrl->setParameterByClass("ilskilltemplatecategorygui", "obj_id", $a_set["child"]); + $ret = $ilCtrl->getLinkTargetByClass("ilskilltemplatecategorygui", "listItems"); + $ilCtrl->setParameterByClass("ilskilltemplatecategorygui", "obj_id", $_GET["obj_id"]); + break; + } - if ($this->tref_id == 0) - { - $this->tpl->setCurrentBlock("cb"); - $this->tpl->setVariable("CB_ID", $a_set["child"]); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setCurrentBlock("nr"); - $this->tpl->setVariable("OBJ_ID", $a_set["child"]); - $this->tpl->setVariable("ORDER_NR", $a_set["order_nr"]); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setVariable("HREF_TITLE", $ret); - - $this->tpl->setVariable("TITLE", $a_set["title"]); - $icon = ilSkillTreeNode::getIconPath($a_set["child"], - $a_set["type"], "", ilSkillTreeNode::_lookupStatus($a_set["child"])); - $this->tpl->setVariable("ICON", ilUtil::img($icon, "")); - } + if ($this->tref_id == 0) { + $this->tpl->setCurrentBlock("cb"); + $this->tpl->setVariable("CB_ID", $a_set["child"]); + $this->tpl->parseCurrentBlock(); + $this->tpl->setCurrentBlock("nr"); + $this->tpl->setVariable("OBJ_ID", $a_set["child"]); + $this->tpl->setVariable("ORDER_NR", $a_set["order_nr"]); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setVariable("HREF_TITLE", $ret); + + $this->tpl->setVariable("TITLE", $a_set["title"]); + $icon = ilSkillTreeNode::getIconPath( + $a_set["child"], + $a_set["type"], + "", + ilSkillTreeNode::_lookupStatus($a_set["child"]) + ); + $this->tpl->setVariable("ICON", ilUtil::img($icon, "")); + } } -?> diff --git a/Services/Skill/classes/class.ilSkillCategory.php b/Services/Skill/classes/class.ilSkillCategory.php index ce8fbb165b91509f2199cba2a789d903b2410597..8157fa0fad9bdc39af3fa7f29236a6952114ab6f 100644 --- a/Services/Skill/classes/class.ilSkillCategory.php +++ b/Services/Skill/classes/class.ilSkillCategory.php @@ -14,57 +14,55 @@ include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); */ class ilSkillCategory extends ilSkillTreeNode { - var $id; + public $id; - /** - * Constructor - * @access public - */ - function __construct($a_id = 0) - { - parent::__construct($a_id); - $this->setType("scat"); - } + /** + * Constructor + * @access public + */ + public function __construct($a_id = 0) + { + parent::__construct($a_id); + $this->setType("scat"); + } - /** - * Read data from database - */ - function read() - { - parent::read(); - } + /** + * Read data from database + */ + public function read() + { + parent::read(); + } - /** - * Create skill - * - */ - function create() - { - parent::create(); - } + /** + * Create skill + * + */ + public function create() + { + parent::create(); + } - /** - * Delete skill - */ - function delete() - { - parent::delete(); - } + /** + * Delete skill + */ + public function delete() + { + parent::delete(); + } - /** - * Copy skill category - */ - function copy() - { - $scat = new ilSkillCategory(); - $scat->setTitle($this->getTitle()); - $scat->setType($this->getType()); - $scat->setSelfEvaluation($this->getSelfEvaluation()); - $scat->setOrderNr($this->getOrderNr()); - $scat->create(); - - return $scat; - } + /** + * Copy skill category + */ + public function copy() + { + $scat = new ilSkillCategory(); + $scat->setTitle($this->getTitle()); + $scat->setType($this->getType()); + $scat->setSelfEvaluation($this->getSelfEvaluation()); + $scat->setOrderNr($this->getOrderNr()); + $scat->create(); + return $scat; + } } -?> diff --git a/Services/Skill/classes/class.ilSkillCategoryGUI.php b/Services/Skill/classes/class.ilSkillCategoryGUI.php index b5aac04d386a66a795474364b074be92d4c61f94..abc8cfa3b0cba88a156e73b8c77a1c88e71d1ea1 100644 --- a/Services/Skill/classes/class.ilSkillCategoryGUI.php +++ b/Services/Skill/classes/class.ilSkillCategoryGUI.php @@ -15,430 +15,452 @@ include_once("./Services/Skill/classes/class.ilSkillTreeNodeGUI.php"); */ class ilSkillCategoryGUI extends ilSkillTreeNodeGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilHelpGUI - */ - protected $help; - - - /** - * Constructor - */ - function __construct($a_node_id = 0) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->tpl = $DIC["tpl"]; - $this->tabs = $DIC->tabs(); - $this->lng = $DIC->language(); - $this->help = $DIC["ilHelp"]; - $ilCtrl = $DIC->ctrl(); - - $ilCtrl->saveParameter($this, "obj_id"); - - parent::__construct($a_node_id); - } - - /** - * Get Node Type - */ - function getType() - { - return "scat"; - } - - /** - * Execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - //$tpl->getStandardTemplate(); - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd(); - - switch($next_class) - { - default: - $ret = $this->$cmd(); - break; - } - } - - /** - * output tabs - */ - function setTabs($a_tab) - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - $ilHelp = $this->help; - - $ilTabs->clearTargets(); - $ilHelp->setScreenIdComponent("skmg_scat"); - - // content - $ilTabs->addTab("content", $lng->txt("content"), - $ilCtrl->getLinkTarget($this, 'listItems')); - - // properties - $ilTabs->addTab("properties", $lng->txt("settings"), - $ilCtrl->getLinkTarget($this, 'editProperties')); - - // usage - $this->addUsageTab($ilTabs); - - // back link - $ilCtrl->setParameterByClass("ilskillrootgui", "obj_id", - $this->node_object->skill_tree->getRootId()); - $ilTabs->setBackTarget($lng->txt("obj_skmg"), - $ilCtrl->getLinkTargetByClass("ilskillrootgui", "listSkills")); - $ilCtrl->setParameterByClass("ilskillrootgui", "obj_id", - $_GET["obj_id"]); - - - parent::setTitleIcon(); - $tpl->setTitle( - $lng->txt("scat").": ".$this->node_object->getTitle()); - $this->setSkillNodeDescription(); - - $ilTabs->activateTab($a_tab); - } - - /** - * Edit properties - */ - function editProperties() - { - $tpl = $this->tpl; - - $this->setTabs("properties"); - parent::editProperties(); - } - - /** - * Perform drag and drop action - */ - function proceedDragDrop() - { - $ilCtrl = $this->ctrl; - -// $this->slm_object->executeDragDrop($_POST["il_hform_source_id"], $_POST["il_hform_target_id"], + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilHelpGUI + */ + protected $help; + + + /** + * Constructor + */ + public function __construct($a_node_id = 0) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->tpl = $DIC["tpl"]; + $this->tabs = $DIC->tabs(); + $this->lng = $DIC->language(); + $this->help = $DIC["ilHelp"]; + $ilCtrl = $DIC->ctrl(); + + $ilCtrl->saveParameter($this, "obj_id"); + + parent::__construct($a_node_id); + } + + /** + * Get Node Type + */ + public function getType() + { + return "scat"; + } + + /** + * Execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + //$tpl->getStandardTemplate(); + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd(); + + switch ($next_class) { + default: + $ret = $this->$cmd(); + break; + } + } + + /** + * output tabs + */ + public function setTabs($a_tab) + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + $ilHelp = $this->help; + + $ilTabs->clearTargets(); + $ilHelp->setScreenIdComponent("skmg_scat"); + + // content + $ilTabs->addTab( + "content", + $lng->txt("content"), + $ilCtrl->getLinkTarget($this, 'listItems') + ); + + // properties + $ilTabs->addTab( + "properties", + $lng->txt("settings"), + $ilCtrl->getLinkTarget($this, 'editProperties') + ); + + // usage + $this->addUsageTab($ilTabs); + + // back link + $ilCtrl->setParameterByClass( + "ilskillrootgui", + "obj_id", + $this->node_object->skill_tree->getRootId() + ); + $ilTabs->setBackTarget( + $lng->txt("obj_skmg"), + $ilCtrl->getLinkTargetByClass("ilskillrootgui", "listSkills") + ); + $ilCtrl->setParameterByClass( + "ilskillrootgui", + "obj_id", + $_GET["obj_id"] + ); + + + parent::setTitleIcon(); + $tpl->setTitle( + $lng->txt("scat") . ": " . $this->node_object->getTitle() + ); + $this->setSkillNodeDescription(); + + $ilTabs->activateTab($a_tab); + } + + /** + * Edit properties + */ + public function editProperties() + { + $tpl = $this->tpl; + + $this->setTabs("properties"); + parent::editProperties(); + } + + /** + * Perform drag and drop action + */ + public function proceedDragDrop() + { + $ilCtrl = $this->ctrl; + + // $this->slm_object->executeDragDrop($_POST["il_hform_source_id"], $_POST["il_hform_target_id"], // $_POST["il_hform_fc"], $_POST["il_hform_as_subitem"]); // $ilCtrl->redirect($this, "showOrganization"); - } - - /** - * Edit - */ - function edit() - { - $tpl = $this->tpl; - - $this->initForm(); - $this->getValues(); - $tpl->setContent($this->form->getHTML()); - } - - /** - * Init form. - * - * @param int $a_mode Edit Mode - */ - public function initForm($a_mode = "edit") - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - // title - $ti = new ilTextInputGUI($lng->txt("title"), "title"); - $ti->setMaxLength(200); - $ti->setSize(50); - $ti->setRequired(true); - $this->form->addItem($ti); - - // order nr - $ni = new ilNumberInputGUI($lng->txt("skmg_order_nr"), "order_nr"); - $ni->setInfo($lng->txt("skmg_order_nr_info")); - $ni->setMaxLength(6); - $ni->setSize(6); - $ni->setRequired(true); - if ($a_mode == "create") - { - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $tree = new ilSkillTree(); - $max = $tree->getMaxOrderNr((int)$_GET["obj_id"]); - $ni->setValue($max + 10); - } - $this->form->addItem($ni); - - // status - $this->addStatusInput($this->form); - - // selectable - $cb = new ilCheckboxInputGUI($lng->txt("skmg_selectable"), "self_eval"); - $cb->setInfo($lng->txt("skmg_selectable_info")); - $this->form->addItem($cb); - - // save and cancel commands - if ($this->checkPermissionBool("write")) - { - if ($a_mode == "create") - { - $this->form->addCommandButton("save", $lng->txt("save")); - $this->form->addCommandButton("cancelSave", $lng->txt("cancel")); - $this->form->setTitle($lng->txt("skmg_create_skill_category")); - } else - { - $this->form->addCommandButton("update", $lng->txt("save")); - $this->form->setTitle($lng->txt("skmg_edit_scat")); - } - } - - $ilCtrl->setParameter($this, "obj_id", $_GET["obj_id"]); - $this->form->setFormAction($ilCtrl->getFormAction($this)); - } - - /** - * Save item - */ - function saveItem() - { - if (!$this->checkPermissionBool("write")) - { - return; - } - include_once "Services/Skill/classes/class.ilSkillCategory.php"; - $it = new ilSkillCategory(); - $it->setTitle($this->form->getInput("title")); - $it->setOrderNr($this->form->getInput("order_nr")); - $it->setSelfEvaluation($_POST["self_eval"]); - $it->setStatus($_POST["status"]); - $it->create(); - ilSkillTreeNode::putInTree($it, (int) $_GET["obj_id"], IL_LAST_NODE); - } - - /** - * Get current values for from - */ - public function getValues() - { - $values = array(); - $values["title"] = $this->node_object->getTitle(); - $values["order_nr"] = $this->node_object->getOrderNr(); - $values["self_eval"] = $this->node_object->getSelfEvaluation(); - $values["status"] = $this->node_object->getStatus(); - $this->form->setValuesByArray($values); - } - - /** - * Update item - */ - function updateItem() - { - if (!$this->checkPermissionBool("write")) - { - return; - } - - $this->node_object->setTitle($this->form->getInput("title")); - $this->node_object->setOrderNr($this->form->getInput("order_nr")); - $this->node_object->setSelfEvaluation($_POST["self_eval"]); - $this->node_object->setStatus($_POST["status"]); - $this->node_object->update(); - } - - /** - * Update form - */ -/* function updateSkillCategory() - { - global $lng, $ilCtrl, $tpl; - - $this->initForm("edit"); - if ($this->form->checkInput()) - { - // perform update - $this->node_object->setSelfEvaluation($_POST["self_eval"]); - $this->node_object->update(); - - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "edit"); - } - - $this->form->setValuesByPost(); - $tpl->setContent($this->form->getHtml()); - }*/ - - /** - * List items - * - * @param - * @return - */ - function listItems() - { - $tpl = $this->tpl; - $lng = $this->lng; - - if ($this->isInUse()) - { - ilUtil::sendInfo($lng->txt("skmg_skill_in_use")); - } - - if ($this->checkPermissionBool("write")) - { - self::addCreationButtons(); - } - $this->setTabs("content"); - - include_once("./Services/Skill/classes/class.ilSkillCatTableGUI.php"); - $table = new ilSkillCatTableGUI($this, "listItems", (int) $_GET["obj_id"], - ilSkillCatTableGUI::MODE_SCAT); - - $tpl->setContent($table->getHTML()); - } - - /** - * Add creation buttons - * - * @param - * @return - */ - static function addCreationButtons() - { - global $DIC; - - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilToolbar = $DIC->toolbar(); - $ilUser = $DIC->user(); - - // skill - $ilCtrl->setParameterByClass("ilbasicskillgui", - "obj_id", (int) $_GET["obj_id"]); - $ilToolbar->addButton($lng->txt("skmg_create_skll"), - $ilCtrl->getLinkTargetByClass("ilbasicskillgui", "create")); - - // skill category - $ilCtrl->setParameterByClass("ilskillcategorygui", - "obj_id", (int) $_GET["obj_id"]); - $ilToolbar->addButton($lng->txt("skmg_create_skill_category"), - $ilCtrl->getLinkTargetByClass("ilskillcategorygui", "create")); - - // skill template reference - $ilCtrl->setParameterByClass("ilskilltemplatereferencegui", - "obj_id", (int) $_GET["obj_id"]); - $ilToolbar->addButton($lng->txt("skmg_create_skill_template_reference"), - $ilCtrl->getLinkTargetByClass("ilskilltemplatereferencegui", "create")); - - // skills from clipboard - $sep = false; - if ($ilUser->clipboardHasObjectsOfType("skll")) - { - $ilToolbar->addSeparator(); - $sep = true; - $ilToolbar->addButton($lng->txt("skmg_insert_basic_skill_from_clip"), - $ilCtrl->getLinkTargetByClass("ilskillcategorygui", "insertBasicSkillClip")); - } - - // skills from clipboard - if ($ilUser->clipboardHasObjectsOfType("scat")) - { - if (!$sep) - { - $ilToolbar->addSeparator(); - $sep = true; - } - $ilToolbar->addButton($lng->txt("skmg_insert_skill_category_from_clip"), - $ilCtrl->getLinkTargetByClass("ilskillcategorygui", "insertSkillCategoryClip")); - } - - // skills from clipboard - if ($ilUser->clipboardHasObjectsOfType("sktr")) - { - if (!$sep) - { - $ilToolbar->addSeparator(); - $sep = true; - } - $ilToolbar->addButton($lng->txt("skmg_insert_skill_template_reference_from_clip"), - $ilCtrl->getLinkTargetByClass("ilskillcategorygui", "insertTemplateReferenceClip")); - } - - // skill template reference - $ilToolbar->addButton($lng->txt("skmg_import_skills"), - $ilCtrl->getLinkTargetByClass("ilskillrootgui", "showImportForm")); - - } - - /** - * Cancel - * - * @param - * @return - */ - function cancel() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirectByClass("ilobjskillmanagementgui", "editSkills"); - } - - /** - * Redirect to parent (identified by current obj_id) - * - * @param - * @return - */ - function redirectToParent($a_tmp_mode = false) - { - $ilCtrl = $this->ctrl; - - $t = ilSkillTreeNode::_lookupType((int) $_GET["obj_id"]); - - switch ($t) - { - case "skrt": - $ilCtrl->setParameterByClass("ilskillrootgui", "obj_id", (int) $_GET["obj_id"]); - $ilCtrl->redirectByClass("ilskillrootgui", "listSkills"); - break; - } - - parent::redirectToParent(); - } - - + } + + /** + * Edit + */ + public function edit() + { + $tpl = $this->tpl; + + $this->initForm(); + $this->getValues(); + $tpl->setContent($this->form->getHTML()); + } + + /** + * Init form. + * + * @param int $a_mode Edit Mode + */ + public function initForm($a_mode = "edit") + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + // title + $ti = new ilTextInputGUI($lng->txt("title"), "title"); + $ti->setMaxLength(200); + $ti->setSize(50); + $ti->setRequired(true); + $this->form->addItem($ti); + + // order nr + $ni = new ilNumberInputGUI($lng->txt("skmg_order_nr"), "order_nr"); + $ni->setInfo($lng->txt("skmg_order_nr_info")); + $ni->setMaxLength(6); + $ni->setSize(6); + $ni->setRequired(true); + if ($a_mode == "create") { + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $tree = new ilSkillTree(); + $max = $tree->getMaxOrderNr((int) $_GET["obj_id"]); + $ni->setValue($max + 10); + } + $this->form->addItem($ni); + + // status + $this->addStatusInput($this->form); + + // selectable + $cb = new ilCheckboxInputGUI($lng->txt("skmg_selectable"), "self_eval"); + $cb->setInfo($lng->txt("skmg_selectable_info")); + $this->form->addItem($cb); + + // save and cancel commands + if ($this->checkPermissionBool("write")) { + if ($a_mode == "create") { + $this->form->addCommandButton("save", $lng->txt("save")); + $this->form->addCommandButton("cancelSave", $lng->txt("cancel")); + $this->form->setTitle($lng->txt("skmg_create_skill_category")); + } else { + $this->form->addCommandButton("update", $lng->txt("save")); + $this->form->setTitle($lng->txt("skmg_edit_scat")); + } + } + + $ilCtrl->setParameter($this, "obj_id", $_GET["obj_id"]); + $this->form->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * Save item + */ + public function saveItem() + { + if (!$this->checkPermissionBool("write")) { + return; + } + include_once "Services/Skill/classes/class.ilSkillCategory.php"; + $it = new ilSkillCategory(); + $it->setTitle($this->form->getInput("title")); + $it->setOrderNr($this->form->getInput("order_nr")); + $it->setSelfEvaluation($_POST["self_eval"]); + $it->setStatus($_POST["status"]); + $it->create(); + ilSkillTreeNode::putInTree($it, (int) $_GET["obj_id"], IL_LAST_NODE); + } + + /** + * Get current values for from + */ + public function getValues() + { + $values = array(); + $values["title"] = $this->node_object->getTitle(); + $values["order_nr"] = $this->node_object->getOrderNr(); + $values["self_eval"] = $this->node_object->getSelfEvaluation(); + $values["status"] = $this->node_object->getStatus(); + $this->form->setValuesByArray($values); + } + + /** + * Update item + */ + public function updateItem() + { + if (!$this->checkPermissionBool("write")) { + return; + } + + $this->node_object->setTitle($this->form->getInput("title")); + $this->node_object->setOrderNr($this->form->getInput("order_nr")); + $this->node_object->setSelfEvaluation($_POST["self_eval"]); + $this->node_object->setStatus($_POST["status"]); + $this->node_object->update(); + } + + /** + * Update form + */ + /* function updateSkillCategory() + { + global $lng, $ilCtrl, $tpl; + + $this->initForm("edit"); + if ($this->form->checkInput()) + { + // perform update + $this->node_object->setSelfEvaluation($_POST["self_eval"]); + $this->node_object->update(); + + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "edit"); + } + + $this->form->setValuesByPost(); + $tpl->setContent($this->form->getHtml()); + }*/ + + /** + * List items + * + * @param + * @return + */ + public function listItems() + { + $tpl = $this->tpl; + $lng = $this->lng; + + if ($this->isInUse()) { + ilUtil::sendInfo($lng->txt("skmg_skill_in_use")); + } + + if ($this->checkPermissionBool("write")) { + self::addCreationButtons(); + } + $this->setTabs("content"); + + include_once("./Services/Skill/classes/class.ilSkillCatTableGUI.php"); + $table = new ilSkillCatTableGUI( + $this, + "listItems", + (int) $_GET["obj_id"], + ilSkillCatTableGUI::MODE_SCAT + ); + + $tpl->setContent($table->getHTML()); + } + + /** + * Add creation buttons + * + * @param + * @return + */ + public static function addCreationButtons() + { + global $DIC; + + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilToolbar = $DIC->toolbar(); + $ilUser = $DIC->user(); + + // skill + $ilCtrl->setParameterByClass( + "ilbasicskillgui", + "obj_id", + (int) $_GET["obj_id"] + ); + $ilToolbar->addButton( + $lng->txt("skmg_create_skll"), + $ilCtrl->getLinkTargetByClass("ilbasicskillgui", "create") + ); + + // skill category + $ilCtrl->setParameterByClass( + "ilskillcategorygui", + "obj_id", + (int) $_GET["obj_id"] + ); + $ilToolbar->addButton( + $lng->txt("skmg_create_skill_category"), + $ilCtrl->getLinkTargetByClass("ilskillcategorygui", "create") + ); + + // skill template reference + $ilCtrl->setParameterByClass( + "ilskilltemplatereferencegui", + "obj_id", + (int) $_GET["obj_id"] + ); + $ilToolbar->addButton( + $lng->txt("skmg_create_skill_template_reference"), + $ilCtrl->getLinkTargetByClass("ilskilltemplatereferencegui", "create") + ); + + // skills from clipboard + $sep = false; + if ($ilUser->clipboardHasObjectsOfType("skll")) { + $ilToolbar->addSeparator(); + $sep = true; + $ilToolbar->addButton( + $lng->txt("skmg_insert_basic_skill_from_clip"), + $ilCtrl->getLinkTargetByClass("ilskillcategorygui", "insertBasicSkillClip") + ); + } + + // skills from clipboard + if ($ilUser->clipboardHasObjectsOfType("scat")) { + if (!$sep) { + $ilToolbar->addSeparator(); + $sep = true; + } + $ilToolbar->addButton( + $lng->txt("skmg_insert_skill_category_from_clip"), + $ilCtrl->getLinkTargetByClass("ilskillcategorygui", "insertSkillCategoryClip") + ); + } + + // skills from clipboard + if ($ilUser->clipboardHasObjectsOfType("sktr")) { + if (!$sep) { + $ilToolbar->addSeparator(); + $sep = true; + } + $ilToolbar->addButton( + $lng->txt("skmg_insert_skill_template_reference_from_clip"), + $ilCtrl->getLinkTargetByClass("ilskillcategorygui", "insertTemplateReferenceClip") + ); + } + + // skill template reference + $ilToolbar->addButton( + $lng->txt("skmg_import_skills"), + $ilCtrl->getLinkTargetByClass("ilskillrootgui", "showImportForm") + ); + } + + /** + * Cancel + * + * @param + * @return + */ + public function cancel() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirectByClass("ilobjskillmanagementgui", "editSkills"); + } + + /** + * Redirect to parent (identified by current obj_id) + * + * @param + * @return + */ + public function redirectToParent($a_tmp_mode = false) + { + $ilCtrl = $this->ctrl; + + $t = ilSkillTreeNode::_lookupType((int) $_GET["obj_id"]); + + switch ($t) { + case "skrt": + $ilCtrl->setParameterByClass("ilskillrootgui", "obj_id", (int) $_GET["obj_id"]); + $ilCtrl->redirectByClass("ilskillrootgui", "listSkills"); + break; + } + + parent::redirectToParent(); + } } - -?> \ No newline at end of file diff --git a/Services/Skill/classes/class.ilSkillCertificateAdapter.php b/Services/Skill/classes/class.ilSkillCertificateAdapter.php index 84a30e28d01d89cd1ba2a0137e337d0124c4bbac..04b9674e082bed47acd75ce5e2f83d142518bbd0 100644 --- a/Services/Skill/classes/class.ilSkillCertificateAdapter.php +++ b/Services/Skill/classes/class.ilSkillCertificateAdapter.php @@ -13,234 +13,223 @@ include_once "./Services/Certificate/classes/class.ilCertificateAdapter.php"; */ class ilSkillCertificateAdapter extends ilCertificateAdapter { - protected $object; - private $skill; - private $skill_level_id; - - /** - * Contructor - * - * @param object skill object - * @param object skill level id - */ - function __construct($a_skill, $a_skill_level_id) - { - $this->skill = $a_skill; - $this->skill_level_id = $a_skill_level_id; - parent::__construct(); - $this->lng->loadLanguageModule('skmg'); - } + protected $object; + private $skill; + private $skill_level_id; + + /** + * Contructor + * + * @param object skill object + * @param object skill level id + */ + public function __construct($a_skill, $a_skill_level_id) + { + $this->skill = $a_skill; + $this->skill_level_id = $a_skill_level_id; + parent::__construct(); + $this->lng->loadLanguageModule('skmg'); + } - /** - * Returns the certificate path (with a trailing path separator) - * - * @return string The certificate path - */ - public function getCertificatePath() - { - return CLIENT_WEB_DIR."/certificates/skill/".$this->skill->getId(). - "/".$this->skill_level_id."/"; - } - - /** - * Returns an array containing all variables and values which can be exchanged in the certificate. - * The values will be taken for the certificate preview. - * - * @return array The certificate variables - */ - public function getCertificateVariablesForPreview() - { - $old = ilDatePresentation::useRelativeDates(); - ilDatePresentation::setUseRelativeDates(false); - - $vars = $this->getBaseVariablesForPreview(); - $vars["SKILL_TITLE"] = ilUtil::prepareFormOutput($this->skill->getTitleForCertificate()); - $vars["SKILL_LEVEL_TITLE"] = ilUtil::prepareFormOutput($this->skill->getLevelTitleForCertificate($this->skill_level_id)); - $vars["SKILL_TRIGGER_TITLE"] = ilUtil::prepareFormOutput($this->skill->getTriggerTitleForCertificate($this->skill_level_id)); - - ilDatePresentation::setUseRelativeDates($old); - - $insert_tags = array(); - foreach($vars as $id => $caption) - { - $insert_tags["[".$id."]"] = $caption; - } - return $insert_tags; - } + /** + * Returns the certificate path (with a trailing path separator) + * + * @return string The certificate path + */ + public function getCertificatePath() + { + return CLIENT_WEB_DIR . "/certificates/skill/" . $this->skill->getId() . + "/" . $this->skill_level_id . "/"; + } + + /** + * Returns an array containing all variables and values which can be exchanged in the certificate. + * The values will be taken for the certificate preview. + * + * @return array The certificate variables + */ + public function getCertificateVariablesForPreview() + { + $old = ilDatePresentation::useRelativeDates(); + ilDatePresentation::setUseRelativeDates(false); + + $vars = $this->getBaseVariablesForPreview(); + $vars["SKILL_TITLE"] = ilUtil::prepareFormOutput($this->skill->getTitleForCertificate()); + $vars["SKILL_LEVEL_TITLE"] = ilUtil::prepareFormOutput($this->skill->getLevelTitleForCertificate($this->skill_level_id)); + $vars["SKILL_TRIGGER_TITLE"] = ilUtil::prepareFormOutput($this->skill->getTriggerTitleForCertificate($this->skill_level_id)); + + ilDatePresentation::setUseRelativeDates($old); + + $insert_tags = array(); + foreach ($vars as $id => $caption) { + $insert_tags["[" . $id . "]"] = $caption; + } + return $insert_tags; + } - /** - * Returns an array containing all variables and values which can be exchanged in the certificate - * The values should be calculated from real data. The $params parameter array should contain all - * necessary information to calculate the values. - * - * @param array $params An array of parameters to calculate the certificate parameter values - * @return array The certificate variables - */ - public function getCertificateVariablesForPresentation($params = array()) - { - $this->lng->loadLanguageModule('certificate'); - - $user_data = $params["user_data"]; - - $vars = $this->getBaseVariablesForPresentation($user_data, $params["last_access"], null); - $vars["SKILL_TITLE"] = ilUtil::prepareFormOutput($this->skill->getTitleForCertificate()); - $vars["SKILL_LEVEL_TITLE"] = ilUtil::prepareFormOutput($this->skill->getLevelTitleForCertificate($this->skill_level_id)); - $vars["SKILL_TRIGGER_TITLE"] = ilUtil::prepareFormOutput($this->skill->getTriggerTitleForCertificate($this->skill_level_id)); - - // custom completion date - $achievement_date = ilBasicSkill::lookupLevelAchievementDate($user_data["usr_id"], $this->skill_level_id); - if ($achievement_date !== false) - { - $old = ilDatePresentation::useRelativeDates(); - ilDatePresentation::setUseRelativeDates(false); - - $vars["DATE_COMPLETED"] = ilDatePresentation::formatDate(new ilDate($achievement_date, IL_CAL_DATETIME)); - $vars["DATETIME_COMPLETED"] = ilDatePresentation::formatDate(new ilDateTime($achievement_date, IL_CAL_DATETIME)); - - ilDatePresentation::setUseRelativeDates($old); - } - else - { - $vars["DATE_COMPLETED"] = ""; - $vars["DATETIME_COMPLETED"] = ""; - } - - foreach($vars as $id => $caption) - { - $insert_tags["[".$id."]"] = $caption; - } - return $insert_tags; - } - - /** - * Returns a description of the available certificate parameters. The description will be shown at - * the bottom of the certificate editor text area. - * - * @return string The certificate parameters description - */ - public function getCertificateVariablesDescription() - { - $this->lng->loadLanguageModule("skmg"); - - $vars = $this->getBaseVariablesDescription(); - $vars["SKILL_TITLE"] = $this->lng->txt("skmg_cert_skill_title"); - $vars["SKILL_LEVEL_TITLE"] = $this->lng->txt("skmg_cert_skill_level_title"); - $vars["SKILL_TRIGGER_TITLE"] = $this->lng->txt("skmg_cert_skill_trigger_title"); - - $template = new ilTemplate("tpl.certificate_edit.html", TRUE, TRUE, "Services/Skill"); - $template->setCurrentBlock("items"); - foreach($vars as $id => $caption) - { - $template->setVariable("ID", $id); - $template->setVariable("TXT", $caption); - $template->parseCurrentBlock(); - } + /** + * Returns an array containing all variables and values which can be exchanged in the certificate + * The values should be calculated from real data. The $params parameter array should contain all + * necessary information to calculate the values. + * + * @param array $params An array of parameters to calculate the certificate parameter values + * @return array The certificate variables + */ + public function getCertificateVariablesForPresentation($params = array()) + { + $this->lng->loadLanguageModule('certificate'); + + $user_data = $params["user_data"]; + + $vars = $this->getBaseVariablesForPresentation($user_data, $params["last_access"], null); + $vars["SKILL_TITLE"] = ilUtil::prepareFormOutput($this->skill->getTitleForCertificate()); + $vars["SKILL_LEVEL_TITLE"] = ilUtil::prepareFormOutput($this->skill->getLevelTitleForCertificate($this->skill_level_id)); + $vars["SKILL_TRIGGER_TITLE"] = ilUtil::prepareFormOutput($this->skill->getTriggerTitleForCertificate($this->skill_level_id)); + + // custom completion date + $achievement_date = ilBasicSkill::lookupLevelAchievementDate($user_data["usr_id"], $this->skill_level_id); + if ($achievement_date !== false) { + $old = ilDatePresentation::useRelativeDates(); + ilDatePresentation::setUseRelativeDates(false); + + $vars["DATE_COMPLETED"] = ilDatePresentation::formatDate(new ilDate($achievement_date, IL_CAL_DATETIME)); + $vars["DATETIME_COMPLETED"] = ilDatePresentation::formatDate(new ilDateTime($achievement_date, IL_CAL_DATETIME)); + + ilDatePresentation::setUseRelativeDates($old); + } else { + $vars["DATE_COMPLETED"] = ""; + $vars["DATETIME_COMPLETED"] = ""; + } + + foreach ($vars as $id => $caption) { + $insert_tags["[" . $id . "]"] = $caption; + } + return $insert_tags; + } + + /** + * Returns a description of the available certificate parameters. The description will be shown at + * the bottom of the certificate editor text area. + * + * @return string The certificate parameters description + */ + public function getCertificateVariablesDescription() + { + $this->lng->loadLanguageModule("skmg"); + + $vars = $this->getBaseVariablesDescription(); + $vars["SKILL_TITLE"] = $this->lng->txt("skmg_cert_skill_title"); + $vars["SKILL_LEVEL_TITLE"] = $this->lng->txt("skmg_cert_skill_level_title"); + $vars["SKILL_TRIGGER_TITLE"] = $this->lng->txt("skmg_cert_skill_trigger_title"); + + $template = new ilTemplate("tpl.certificate_edit.html", true, true, "Services/Skill"); + $template->setCurrentBlock("items"); + foreach ($vars as $id => $caption) { + $template->setVariable("ID", $id); + $template->setVariable("TXT", $caption); + $template->parseCurrentBlock(); + } - $template->setVariable("PH_INTRODUCTION", $this->lng->txt("certificate_ph_introduction")); + $template->setVariable("PH_INTRODUCTION", $this->lng->txt("certificate_ph_introduction")); - return $template->get(); - } + return $template->get(); + } - /** - * Allows to add additional form fields to the certificate editor form - * This method will be called when the certificate editor form will built - * using the ilPropertyFormGUI class. Additional fields will be added at the - * bottom of the form. - * - * @param object $form An ilPropertyFormGUI instance - * @param array $form_fields An array containing the form values. The array keys are the names of the form fields - */ - public function addAdditionalFormElements(&$form, $form_fields) - { - } - - /** - * Allows to add additional form values to the array of form values evaluating a - * HTTP POST action. - * This method will be called when the certificate editor form will be saved using - * the form save button. - * - * @param array $form_fields A reference to the array of form values - */ - public function addFormFieldsFromPOST(&$form_fields) - { - } + /** + * Allows to add additional form fields to the certificate editor form + * This method will be called when the certificate editor form will built + * using the ilPropertyFormGUI class. Additional fields will be added at the + * bottom of the form. + * + * @param object $form An ilPropertyFormGUI instance + * @param array $form_fields An array containing the form values. The array keys are the names of the form fields + */ + public function addAdditionalFormElements(&$form, $form_fields) + { + } + + /** + * Allows to add additional form values to the array of form values evaluating a + * HTTP POST action. + * This method will be called when the certificate editor form will be saved using + * the form save button. + * + * @param array $form_fields A reference to the array of form values + */ + public function addFormFieldsFromPOST(&$form_fields) + { + } - /** - * Allows to add additional form values to the array of form values evaluating the - * associated adapter class if one exists - * This method will be called when the certificate editor form will be shown and the - * content of the form has to be retrieved from wherever the form values are saved. - * - * @param array $form_fields A reference to the array of form values - */ - public function addFormFieldsFromObject(&$form_fields) - { - } - - /** - * Allows to save additional adapter form fields - * This method will be called when the certificate editor form is complete and the - * form values will be saved. - * - * @param array $form_fields A reference to the array of form values - */ - public function saveFormFields(&$form_fields) - { - } + /** + * Allows to add additional form values to the array of form values evaluating the + * associated adapter class if one exists + * This method will be called when the certificate editor form will be shown and the + * content of the form has to be retrieved from wherever the form values are saved. + * + * @param array $form_fields A reference to the array of form values + */ + public function addFormFieldsFromObject(&$form_fields) + { + } + + /** + * Allows to save additional adapter form fields + * This method will be called when the certificate editor form is complete and the + * form values will be saved. + * + * @param array $form_fields A reference to the array of form values + */ + public function saveFormFields(&$form_fields) + { + } - /** - * Returns the adapter type - * This value will be used to generate file names for the certificates - * - * @return string A string value to represent the adapter type - */ - public function getAdapterType() - { - return "skill"; - } + /** + * Returns the adapter type + * This value will be used to generate file names for the certificates + * + * @return string A string value to represent the adapter type + */ + public function getAdapterType() + { + return "skill"; + } - /** - * Returns a certificate ID - * This value will be used to generate unique file names for the certificates - * - * @return mixed A unique ID which represents a certificate - */ - public function getCertificateID() - { - return $this->skill_level_id; - } + /** + * Returns a certificate ID + * This value will be used to generate unique file names for the certificates + * + * @return mixed A unique ID which represents a certificate + */ + public function getCertificateID() + { + return $this->skill_level_id; + } - /** - * Set the name of the certificate file - * This method will be called when the certificate will be generated - * - * @return string The certificate file name - */ - public function getCertificateFilename($params = array()) - { - $basename = parent::getCertificateFilename($params); - - $user_data = $params["user_data"]; - if (!is_array($user_data)) - { - $short_title = $this->skill->getShortTitleForCertificate(); - return strftime("%y%m%d", time()) . "_" . $this->lng->txt("certificate_var_user_lastname") . "_" . $short_title . "_" . $basename; - } - else - { - return strftime("%y%m%d", time()) . "_" . $user_data["lastname"] . "_" . $params["short_title"] . "_" . $basename; - } - } + /** + * Set the name of the certificate file + * This method will be called when the certificate will be generated + * + * @return string The certificate file name + */ + public function getCertificateFilename($params = array()) + { + $basename = parent::getCertificateFilename($params); + + $user_data = $params["user_data"]; + if (!is_array($user_data)) { + $short_title = $this->skill->getShortTitleForCertificate(); + return strftime("%y%m%d", time()) . "_" . $this->lng->txt("certificate_var_user_lastname") . "_" . $short_title . "_" . $basename; + } else { + return strftime("%y%m%d", time()) . "_" . $user_data["lastname"] . "_" . $params["short_title"] . "_" . $basename; + } + } - /** - * Is called when the certificate is deleted - * Add some adapter specific code if more work has to be done when the - * certificate file was deleted - */ - public function deleteCertificate() - { - } + /** + * Is called when the certificate is deleted + * Add some adapter specific code if more work has to be done when the + * certificate file was deleted + */ + public function deleteCertificate() + { + } } - -?> diff --git a/Services/Skill/classes/class.ilSkillDataSet.php b/Services/Skill/classes/class.ilSkillDataSet.php index 6111d75609930d5846f7679d0000ee2c068788cd..b3975294a38360d888d6ffeef219de22e193822c 100644 --- a/Services/Skill/classes/class.ilSkillDataSet.php +++ b/Services/Skill/classes/class.ilSkillDataSet.php @@ -5,7 +5,7 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); /** * Skill Data set class - * + * * This class implements the following entities: * - skmg: Skill management top entity (no data, only dependecies) * - skl_subtree: Skill subtree (includes data of skl_tree, skl_tree_node and skl_templ_ref) @@ -19,625 +19,559 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php"); */ class ilSkillDataSet extends ilDataSet { - const MODE_SKILLS = ""; - const MODE_PROFILES = "prof"; - - /** - * @var ilSkillTree - */ - protected $skill_tree; - protected $init_order_nr; - protected $selected_nodes = false; - protected $selected_profiles = false; - protected $mode = ""; - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->db = $DIC->database(); - parent::__construct(); - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $this->skill_tree = new ilSkillTree(); - $this->skill_tree_root_id = $this->skill_tree->readRootId(); - - $this->init_top_order_nr = $this->skill_tree->getMaxOrderNr($this->skill_tree_root_id); - $this->init_templ_top_order_nr = $this->skill_tree->getMaxOrderNr($this->skill_tree_root_id, true); - } - - /** - * Set mode - * - * @param string $a_val mode - */ - function setMode($a_val) - { - $this->mode = $a_val; - } - - /** - * Get mode - * - * @return string mode - */ - function getMode() - { - return $this->mode; - } - - /** - * Set export selected nodes - * - * @param array $a_val array of int - */ - function setSelectedNodes($a_val) - { - $this->selected_nodes = $a_val; - } - - /** - * Get export selected nodes - * - * @return array array of int - */ - function getSelectedNodes() - { - return $this->selected_nodes; - } - - /** - * Set selected profiles - * - * @param array $a_val array of int (profile ids) - */ - function setSelectedProfiles($a_val) - { - $this->selected_profiles = $a_val; - } - - /** - * Get selected profiles - * - * @return array array of int (profile ids) - */ - function getSelectedProfiles() - { - return $this->selected_profiles; - } - - /** - * Get supported versions - * - * @return array of version strings - */ - public function getSupportedVersions() - { - return array("5.1.0"); - } - - /** - * Get xml namespace - * - * @param - * @return - */ - function getXmlNamespace($a_entity, $a_schema_version) - { - return "http://www.ilias.de/xml/Services/Skill/".$a_entity; - } - - /** - * Get field types for entity - * - * @param - * @return - */ - protected function getTypes($a_entity, $a_version) - { - if ($a_entity == "skmg") - { - switch ($a_version) - { - case "5.1.0": - return array( - "Mode" => "text" - ); - } - } - if ($a_entity == "skl_subtree") - { - switch ($a_version) - { - case "5.1.0": - return array( - "SklTreeId" => "integer", - "TopNode" => "integer", - "Child" => "integer", - "Parent" => "integer", - "Depth" => "integer", - "Type" => "text", - "Title" => "text", - "SelfEval" => "integer", - "OrderNr" => "integer", - "Status" => "integer", - "TemplateId" => "integer" - ); - } - } - if ($a_entity == "skl_templ_subtree") - { - switch ($a_version) - { - case "5.1.0": - return array( - "SklTreeId" => "integer", - "TopNode" => "integer", - "Child" => "integer", - "Parent" => "integer", - "Depth" => "integer", - "Type" => "text", - "Title" => "text", - "SelfEval" => "integer", - "OrderNr" => "integer", - "Status" => "integer" - ); - } - } - if ($a_entity == "skl_level") - { - switch ($a_version) - { - case "5.1.0": - return array( - "LevelId" => "integer", - "SkillId" => "integer", - "Nr" => "integer", - "Title" => "text", - "Description" => "text" - ); - } - } - if ($a_entity == "skl_prof") - { - switch ($a_version) - { - case "5.1.0": - return array( - "Id" => "integer", - "Title" => "text", - "Description" => "text" - ); - } - } - if ($a_entity == "skl_prof_level") - { - switch ($a_version) - { - case "5.1.0": - return array( - "ProfileId" => "integer", - "BaseSkillId" => "integer", - "TrefId" => "integer", - "LevelId" => "integer" - ); - } - } - return array(); - } - - /** - * Read data - * - * @param - * @return - */ - function readData($a_entity, $a_version, $a_ids, $a_field = "") - { - $ilDB = $this->db; - - $this->data = array(); - - if (!is_array($a_ids)) - { - $a_ids = array($a_ids); - } - if ($a_entity == "skmg") // dummy node - { - switch ($a_version) - { - case "5.1.0": - if ($this->getMode() == self::MODE_SKILLS) - { - $this->data[] = array("Mode" => "Skills"); - } - else if ($this->getMode() == self::MODE_PROFILES) - { - $this->data[] = array("Mode" => "Profiles"); - } - break; - - } - } - if ($a_entity == "skl_subtree") // get subtree for top node - { - switch ($a_version) - { - case "5.1.0": - foreach ($a_ids as $id) - { - $sub = $this->skill_tree->getSubTree($this->skill_tree->getNodeData($id)); - foreach ($sub as $s) - { - $set = $ilDB->query("SELECT * FROM skl_templ_ref ". - " WHERE skl_node_id = ".$ilDB->quote($s["child"], "integer") - ); - $rec = $ilDB->fetchAssoc($set); - - $top_node = ($s["child"] == $id) - ? 1 - : 0; - $this->data[] = array( - "SklTreeId" => $s["skl_tree_id"], - "TopNode" => $top_node, - "Child" => $s["child"], - "Parent" => $s["parent"], - "Depth" => $s["depth"], - "Type" => $s["type"], - "Title" => $s["title"], - "SelfEval" => $s["self_eval"], - "OrderNr" => $s["order_nr"], - "Status" => $s["status"], - "TemplateId" => (int) $rec["templ_id"] - ); - } - } - break; - - } - } - - if ($a_entity == "skl_templ_subtree") // get template subtree for template id - { - switch ($a_version) - { - case "5.1.0": - foreach ($a_ids as $id) - { - $sub = $this->skill_tree->getSubTree($this->skill_tree->getNodeData($id)); - foreach ($sub as $s) - { - $top_node = ($s["child"] == $id) - ? 1 - : 0; - $this->data[] = array( - "SklTreeId" => $s["skl_tree_id"], - "TopNode" => $top_node, - "Child" => $s["child"], - "Parent" => $s["parent"], - "Depth" => $s["depth"], - "Type" => $s["type"], - "Title" => $s["title"], - "SelfEval" => $s["self_eval"], - "OrderNr" => $s["order_nr"], - "Status" => $s["status"] - ); - } - } - break; - - } - } - - if ($a_entity == "skl_level") - { - switch ($a_version) - { - case "5.1.0": - $this->getDirectDataFromQuery("SELECT id level_id, skill_id, nr, title, description". - " FROM skl_level WHERE ". - $ilDB->in("skill_id", $a_ids, false, "integer")." ORDER BY skill_id ASC, nr ASC"); - break; - - } - } - - if ($a_entity == "skl_prof") - { - switch ($a_version) - { - case "5.1.0": - $this->getDirectDataFromQuery("SELECT id, title, description". - " FROM skl_profile WHERE ". - $ilDB->in("id", $a_ids, false, "integer")); - break; - - } - } - - if ($a_entity == "skl_prof_level") - { - switch ($a_version) - { - case "5.1.0": - $this->getDirectDataFromQuery("SELECT profile_id, base_skill_id, tref_id, level_id". - " FROM skl_profile_level WHERE ". - $ilDB->in("profile_id", $a_ids, false, "integer")); - break; - - } - } - - } - - /** - * Determine the dependent sets of data - */ - protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) - { - $ilDB = $this->db; - - include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); - - switch ($a_entity) - { - case "skmg": - - if ($this->getMode() == self::MODE_SKILLS) - { - // determine top nodes of main tree to be exported and all referenced template nodes - $sel_nodes = $this->getSelectedNodes(); - $exp_types = array("skll", "scat", "sctr", "sktr"); - if (!is_array($sel_nodes)) - { - $childs = $this->skill_tree->getChildsByTypeFilter($this->skill_tree->readRootId(), $exp_types); - $deps = array(); - $skl_subtree_deps = array(); - foreach ($childs as $c) - { - $skl_subtree_deps[] = $c["child"]; - } - } else - { - foreach ($sel_nodes as $n) - { - if (in_array(ilSkillTreeNode::_lookupType((int)$n), $exp_types)) - { - $skl_subtree_deps[] = $n; - } - } - } - - // determine template subtrees - $ref_nodes = array(); - if (is_array($skl_subtree_deps)) - { - foreach ($skl_subtree_deps as $id) - { - if (ilSkillTreeNode::_lookupType($id) == "sktr") - { - $ref_nodes[$id] = $id; - } else - { - $sub = $this->skill_tree->getSubTree($this->skill_tree->getNodeData($id), true, "sktr"); - foreach ($sub as $s) - { - $ref_nodes[$s["child"]] = $s["child"]; - } - } - } - } - - $set = $ilDB->query("SELECT DISTINCT(templ_id) FROM skl_templ_ref " . - " WHERE " . $ilDB->in("skl_node_id", $ref_nodes, false, "integer")); - while ($rec = $ilDB->fetchAssoc($set)) - { - $deps["skl_templ_subtree"]["ids"][] = $rec["templ_id"]; - } - - // export subtree after templates - $deps["skl_subtree"]["ids"] = $skl_subtree_deps; - } - else if ($this->getMode() == self::MODE_PROFILES) - { - foreach ($this->getSelectedProfiles() as $p_id) - { - $deps["skl_prof"]["ids"][] = $p_id; - } - } - - return $deps; - - case "skl_subtree": - case "skl_templ_subtree": - $deps = array(); - if (in_array($a_rec["Type"], array("skll", "sktp"))) - { - $deps["skl_level"]["ids"][] = $a_rec["Child"]; - } - return $deps; - - case "skl_prof": - $deps["skl_prof_level"]["ids"][] = $a_rec["Id"]; - return $deps; - } - - return false; - } - - - /** - * Import record - * - * @param - * @return - */ - function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) - { - $source_inst_id = $a_mapping->getInstallId(); - switch ($a_entity) - { - case "skl_subtree": - if ($a_rec["TopNode"] == 1) - { - $parent = $this->skill_tree_root_id; - $status = ilSkillTreeNode::STATUS_DRAFT; - $order = $a_rec["OrderNr"] + $this->init_top_order_nr; - } else - { - $parent = (int)$a_mapping->getMapping("Services/Skill", "skl_tree", $a_rec["Parent"]); - $status = $a_rec["Status"]; - $order = $a_rec["OrderNr"]; - } - switch ($a_rec["Type"]) - { - case "scat": - include_once("./Services/Skill/classes/class.ilSkillCategory.php"); - $scat = new ilSkillCategory(); - $scat->setTitle($a_rec["Title"]); - $scat->setImportId("il_" . $source_inst_id . "_scat_" . $a_rec["Child"]); - $scat->setSelfEvaluation($a_rec["SelfEval"]); - $scat->setOrderNr($order); - $scat->setStatus($status); - $scat->create(); - ilSkillTreeNode::putInTree($scat, $parent); - $a_mapping->addMapping("Services/Skill", "skl_tree", $a_rec["Child"], $scat->getId()); - break; - - case "skll": - include_once("./Services/Skill/classes/class.ilBasicSkill.php"); - $skll = new ilBasicSkill(); - $skll->setTitle($a_rec["Title"]); - $skll->setImportId("il_" . $source_inst_id . "_skll_" . $a_rec["Child"]); - $skll->setSelfEvaluation($a_rec["SelfEval"]); - $skll->setOrderNr($order); - $skll->setStatus($status); - $skll->create(); - ilSkillTreeNode::putInTree($skll, $parent); - $a_mapping->addMapping("Services/Skill", "skl_tree", $a_rec["Child"], $skll->getId()); - break; - - case "sktr": - $template_id = (int)$a_mapping->getMapping("Services/Skill", "skl_tree", $a_rec["TemplateId"]); - // only create template references, if referenced template is found (template trees are imported first) - if ($template_id > 0) - { - include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); - $sktr = new ilSkillTemplateReference(); - $sktr->setTitle($a_rec["Title"]); - $sktr->setImportId("il_" . $source_inst_id . "_sktr_" . $a_rec["Child"]); - $sktr->setSelfEvaluation($a_rec["SelfEval"]); - $sktr->setOrderNr($order); - $sktr->setSkillTemplateId($template_id); - $sktr->setStatus($status); - $sktr->create(); - ilSkillTreeNode::putInTree($sktr, $parent); - $a_mapping->addMapping("Services/Skill", "skl_tree", $a_rec["Child"], $sktr->getId()); - } - break; - - } - break; - - case "skl_templ_subtree": - if ($a_rec["TopNode"] == 1) - { - $parent = $this->skill_tree_root_id; - $order = $a_rec["OrderNr"] + $this->init_templ_top_order_nr; - } else - { - $parent = (int)$a_mapping->getMapping("Services/Skill", "skl_tree", $a_rec["Parent"]); - $order = $a_rec["OrderNr"]; - } - switch ($a_rec["Type"]) - { - case "sctp": - include_once("./Services/Skill/classes/class.ilSkillTemplateCategory.php"); - $sctp = new ilSkillTemplateCategory(); - $sctp->setTitle($a_rec["Title"]); - $sctp->setImportId("il_" . $source_inst_id . "_sctp_" . $a_rec["Child"]); - $sctp->setOrderNr($order); - $sctp->create(); - ilSkillTreeNode::putInTree($sctp, $parent); - $a_mapping->addMapping("Services/Skill", "skl_tree", $a_rec["Child"], $sctp->getId()); - break; - - case "sktp": - include_once("./Services/Skill/classes/class.ilBasicSkillTemplate.php"); - $sktp = new ilBasicSkillTemplate(); - $sktp->setTitle($a_rec["Title"]); - $sktp->setImportId("il_" . $source_inst_id . "_sktp_" . $a_rec["Child"]); - $sktp->setOrderNr($order); - $sktp->create(); - ilSkillTreeNode::putInTree($sktp, $parent); - $a_mapping->addMapping("Services/Skill", "skl_tree", $a_rec["Child"], $sktp->getId()); - break; - } - break; - - case "skl_level": - $skill_id = (int)$a_mapping->getMapping("Services/Skill", "skl_tree", $a_rec["SkillId"]); - $type = ilSkillTreeNode::_lookupType($skill_id); - if (in_array($type, array("skll", "sktp"))) - { - if ($type == "skll") - { - $skill = new ilBasicSkill($skill_id); - } else - { - $skill = new ilBasicSkillTemplate($skill_id); - } - $skill->addLevel($a_rec["Title"], $a_rec["Description"], "il_" . $source_inst_id . "_sklv_" . $a_rec["LevelId"]); - $skill->update(); - } - break; - - case "skl_prof": - include_once("./Services/Skill/classes/class.ilSkillProfile.php"); - $prof = new ilSkillProfile(); - $prof->setTitle($a_rec["Title"]); - $prof->setDescription($a_rec["Description"]); - $prof->create(); - $a_mapping->addMapping("Services/Skill", "skl_prof", $a_rec["Id"], $prof->getId()); - break; - - case "skl_prof_level": - $profile_id = (int)$a_mapping->getMapping("Services/Skill", "skl_prof", $a_rec["ProfileId"]); - if ($profile_id > 0) - { - include_once("./Services/Skill/classes/class.ilSkillProfile.php"); - include_once("./Services/Skill/classes/class.ilBasicSkill.php"); - $prof = new ilSkillProfile($profile_id); - $level_id_data = ilBasicSkill::getLevelIdForImportId($this->getCurrentInstallationId(), $a_rec["LevelId"]); - $skill_data = ilBasicSkill::getCommonSkillIdForImportId($this->getCurrentInstallationId(), $a_rec["BaseSkillId"], $a_rec["TrefId"]); - //var_dump($level_id_data); - //var_dump($skill_data); - $level_id = $tref_id = $base_skill = 0; - foreach($level_id_data as $l) - { - reset($skill_data); - foreach ($skill_data as $s) - { - // echo "
                  =".ilBasicSkill::lookupLevelSkillId($l["level_id"])."=".$s["skill_id"]."="; - - if ($level_id == 0 && ilBasicSkill::lookupLevelSkillId($l["level_id"]) == $s["skill_id"]) - { - $level_id = $l["level_id"]; - $base_skill = $s["skill_id"]; - $tref_id = $s["tref_id"]; - } - } - } - if ($level_id > 0) - { - $prof->addSkillLevel($base_skill, $tref_id, $level_id); - } - $prof->update(); - } - break; - } - } + const MODE_SKILLS = ""; + const MODE_PROFILES = "prof"; + + /** + * @var ilSkillTree + */ + protected $skill_tree; + protected $init_order_nr; + protected $selected_nodes = false; + protected $selected_profiles = false; + protected $mode = ""; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->db = $DIC->database(); + parent::__construct(); + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $this->skill_tree = new ilSkillTree(); + $this->skill_tree_root_id = $this->skill_tree->readRootId(); + + $this->init_top_order_nr = $this->skill_tree->getMaxOrderNr($this->skill_tree_root_id); + $this->init_templ_top_order_nr = $this->skill_tree->getMaxOrderNr($this->skill_tree_root_id, true); + } + + /** + * Set mode + * + * @param string $a_val mode + */ + public function setMode($a_val) + { + $this->mode = $a_val; + } + + /** + * Get mode + * + * @return string mode + */ + public function getMode() + { + return $this->mode; + } + + /** + * Set export selected nodes + * + * @param array $a_val array of int + */ + public function setSelectedNodes($a_val) + { + $this->selected_nodes = $a_val; + } + + /** + * Get export selected nodes + * + * @return array array of int + */ + public function getSelectedNodes() + { + return $this->selected_nodes; + } + + /** + * Set selected profiles + * + * @param array $a_val array of int (profile ids) + */ + public function setSelectedProfiles($a_val) + { + $this->selected_profiles = $a_val; + } + + /** + * Get selected profiles + * + * @return array array of int (profile ids) + */ + public function getSelectedProfiles() + { + return $this->selected_profiles; + } + + /** + * Get supported versions + * + * @return array of version strings + */ + public function getSupportedVersions() + { + return array("5.1.0"); + } + + /** + * Get xml namespace + * + * @param + * @return + */ + public function getXmlNamespace($a_entity, $a_schema_version) + { + return "http://www.ilias.de/xml/Services/Skill/" . $a_entity; + } + + /** + * Get field types for entity + * + * @param + * @return + */ + protected function getTypes($a_entity, $a_version) + { + if ($a_entity == "skmg") { + switch ($a_version) { + case "5.1.0": + return array( + "Mode" => "text" + ); + } + } + if ($a_entity == "skl_subtree") { + switch ($a_version) { + case "5.1.0": + return array( + "SklTreeId" => "integer", + "TopNode" => "integer", + "Child" => "integer", + "Parent" => "integer", + "Depth" => "integer", + "Type" => "text", + "Title" => "text", + "SelfEval" => "integer", + "OrderNr" => "integer", + "Status" => "integer", + "TemplateId" => "integer" + ); + } + } + if ($a_entity == "skl_templ_subtree") { + switch ($a_version) { + case "5.1.0": + return array( + "SklTreeId" => "integer", + "TopNode" => "integer", + "Child" => "integer", + "Parent" => "integer", + "Depth" => "integer", + "Type" => "text", + "Title" => "text", + "SelfEval" => "integer", + "OrderNr" => "integer", + "Status" => "integer" + ); + } + } + if ($a_entity == "skl_level") { + switch ($a_version) { + case "5.1.0": + return array( + "LevelId" => "integer", + "SkillId" => "integer", + "Nr" => "integer", + "Title" => "text", + "Description" => "text" + ); + } + } + if ($a_entity == "skl_prof") { + switch ($a_version) { + case "5.1.0": + return array( + "Id" => "integer", + "Title" => "text", + "Description" => "text" + ); + } + } + if ($a_entity == "skl_prof_level") { + switch ($a_version) { + case "5.1.0": + return array( + "ProfileId" => "integer", + "BaseSkillId" => "integer", + "TrefId" => "integer", + "LevelId" => "integer" + ); + } + } + return array(); + } + + /** + * Read data + * + * @param + * @return + */ + public function readData($a_entity, $a_version, $a_ids, $a_field = "") + { + $ilDB = $this->db; + + $this->data = array(); + + if (!is_array($a_ids)) { + $a_ids = array($a_ids); + } + if ($a_entity == "skmg") { // dummy node + switch ($a_version) { + case "5.1.0": + if ($this->getMode() == self::MODE_SKILLS) { + $this->data[] = array("Mode" => "Skills"); + } elseif ($this->getMode() == self::MODE_PROFILES) { + $this->data[] = array("Mode" => "Profiles"); + } + break; + + } + } + if ($a_entity == "skl_subtree") { // get subtree for top node + switch ($a_version) { + case "5.1.0": + foreach ($a_ids as $id) { + $sub = $this->skill_tree->getSubTree($this->skill_tree->getNodeData($id)); + foreach ($sub as $s) { + $set = $ilDB->query( + "SELECT * FROM skl_templ_ref " . + " WHERE skl_node_id = " . $ilDB->quote($s["child"], "integer") + ); + $rec = $ilDB->fetchAssoc($set); + + $top_node = ($s["child"] == $id) + ? 1 + : 0; + $this->data[] = array( + "SklTreeId" => $s["skl_tree_id"], + "TopNode" => $top_node, + "Child" => $s["child"], + "Parent" => $s["parent"], + "Depth" => $s["depth"], + "Type" => $s["type"], + "Title" => $s["title"], + "SelfEval" => $s["self_eval"], + "OrderNr" => $s["order_nr"], + "Status" => $s["status"], + "TemplateId" => (int) $rec["templ_id"] + ); + } + } + break; + + } + } + + if ($a_entity == "skl_templ_subtree") { // get template subtree for template id + switch ($a_version) { + case "5.1.0": + foreach ($a_ids as $id) { + $sub = $this->skill_tree->getSubTree($this->skill_tree->getNodeData($id)); + foreach ($sub as $s) { + $top_node = ($s["child"] == $id) + ? 1 + : 0; + $this->data[] = array( + "SklTreeId" => $s["skl_tree_id"], + "TopNode" => $top_node, + "Child" => $s["child"], + "Parent" => $s["parent"], + "Depth" => $s["depth"], + "Type" => $s["type"], + "Title" => $s["title"], + "SelfEval" => $s["self_eval"], + "OrderNr" => $s["order_nr"], + "Status" => $s["status"] + ); + } + } + break; + + } + } + + if ($a_entity == "skl_level") { + switch ($a_version) { + case "5.1.0": + $this->getDirectDataFromQuery("SELECT id level_id, skill_id, nr, title, description" . + " FROM skl_level WHERE " . + $ilDB->in("skill_id", $a_ids, false, "integer") . " ORDER BY skill_id ASC, nr ASC"); + break; + + } + } + + if ($a_entity == "skl_prof") { + switch ($a_version) { + case "5.1.0": + $this->getDirectDataFromQuery("SELECT id, title, description" . + " FROM skl_profile WHERE " . + $ilDB->in("id", $a_ids, false, "integer")); + break; + + } + } + + if ($a_entity == "skl_prof_level") { + switch ($a_version) { + case "5.1.0": + $this->getDirectDataFromQuery("SELECT profile_id, base_skill_id, tref_id, level_id" . + " FROM skl_profile_level WHERE " . + $ilDB->in("profile_id", $a_ids, false, "integer")); + break; + + } + } + } + + /** + * Determine the dependent sets of data + */ + protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids) + { + $ilDB = $this->db; + + include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); + + switch ($a_entity) { + case "skmg": + + if ($this->getMode() == self::MODE_SKILLS) { + // determine top nodes of main tree to be exported and all referenced template nodes + $sel_nodes = $this->getSelectedNodes(); + $exp_types = array("skll", "scat", "sctr", "sktr"); + if (!is_array($sel_nodes)) { + $childs = $this->skill_tree->getChildsByTypeFilter($this->skill_tree->readRootId(), $exp_types); + $deps = array(); + $skl_subtree_deps = array(); + foreach ($childs as $c) { + $skl_subtree_deps[] = $c["child"]; + } + } else { + foreach ($sel_nodes as $n) { + if (in_array(ilSkillTreeNode::_lookupType((int) $n), $exp_types)) { + $skl_subtree_deps[] = $n; + } + } + } + + // determine template subtrees + $ref_nodes = array(); + if (is_array($skl_subtree_deps)) { + foreach ($skl_subtree_deps as $id) { + if (ilSkillTreeNode::_lookupType($id) == "sktr") { + $ref_nodes[$id] = $id; + } else { + $sub = $this->skill_tree->getSubTree($this->skill_tree->getNodeData($id), true, "sktr"); + foreach ($sub as $s) { + $ref_nodes[$s["child"]] = $s["child"]; + } + } + } + } + + $set = $ilDB->query("SELECT DISTINCT(templ_id) FROM skl_templ_ref " . + " WHERE " . $ilDB->in("skl_node_id", $ref_nodes, false, "integer")); + while ($rec = $ilDB->fetchAssoc($set)) { + $deps["skl_templ_subtree"]["ids"][] = $rec["templ_id"]; + } + + // export subtree after templates + $deps["skl_subtree"]["ids"] = $skl_subtree_deps; + } elseif ($this->getMode() == self::MODE_PROFILES) { + foreach ($this->getSelectedProfiles() as $p_id) { + $deps["skl_prof"]["ids"][] = $p_id; + } + } + + return $deps; + + case "skl_subtree": + case "skl_templ_subtree": + $deps = array(); + if (in_array($a_rec["Type"], array("skll", "sktp"))) { + $deps["skl_level"]["ids"][] = $a_rec["Child"]; + } + return $deps; + + case "skl_prof": + $deps["skl_prof_level"]["ids"][] = $a_rec["Id"]; + return $deps; + } + + return false; + } + + + /** + * Import record + * + * @param + * @return + */ + public function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version) + { + $source_inst_id = $a_mapping->getInstallId(); + switch ($a_entity) { + case "skl_subtree": + if ($a_rec["TopNode"] == 1) { + $parent = $this->skill_tree_root_id; + $status = ilSkillTreeNode::STATUS_DRAFT; + $order = $a_rec["OrderNr"] + $this->init_top_order_nr; + } else { + $parent = (int) $a_mapping->getMapping("Services/Skill", "skl_tree", $a_rec["Parent"]); + $status = $a_rec["Status"]; + $order = $a_rec["OrderNr"]; + } + switch ($a_rec["Type"]) { + case "scat": + include_once("./Services/Skill/classes/class.ilSkillCategory.php"); + $scat = new ilSkillCategory(); + $scat->setTitle($a_rec["Title"]); + $scat->setImportId("il_" . $source_inst_id . "_scat_" . $a_rec["Child"]); + $scat->setSelfEvaluation($a_rec["SelfEval"]); + $scat->setOrderNr($order); + $scat->setStatus($status); + $scat->create(); + ilSkillTreeNode::putInTree($scat, $parent); + $a_mapping->addMapping("Services/Skill", "skl_tree", $a_rec["Child"], $scat->getId()); + break; + + case "skll": + include_once("./Services/Skill/classes/class.ilBasicSkill.php"); + $skll = new ilBasicSkill(); + $skll->setTitle($a_rec["Title"]); + $skll->setImportId("il_" . $source_inst_id . "_skll_" . $a_rec["Child"]); + $skll->setSelfEvaluation($a_rec["SelfEval"]); + $skll->setOrderNr($order); + $skll->setStatus($status); + $skll->create(); + ilSkillTreeNode::putInTree($skll, $parent); + $a_mapping->addMapping("Services/Skill", "skl_tree", $a_rec["Child"], $skll->getId()); + break; + + case "sktr": + $template_id = (int) $a_mapping->getMapping("Services/Skill", "skl_tree", $a_rec["TemplateId"]); + // only create template references, if referenced template is found (template trees are imported first) + if ($template_id > 0) { + include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); + $sktr = new ilSkillTemplateReference(); + $sktr->setTitle($a_rec["Title"]); + $sktr->setImportId("il_" . $source_inst_id . "_sktr_" . $a_rec["Child"]); + $sktr->setSelfEvaluation($a_rec["SelfEval"]); + $sktr->setOrderNr($order); + $sktr->setSkillTemplateId($template_id); + $sktr->setStatus($status); + $sktr->create(); + ilSkillTreeNode::putInTree($sktr, $parent); + $a_mapping->addMapping("Services/Skill", "skl_tree", $a_rec["Child"], $sktr->getId()); + } + break; + + } + break; + + case "skl_templ_subtree": + if ($a_rec["TopNode"] == 1) { + $parent = $this->skill_tree_root_id; + $order = $a_rec["OrderNr"] + $this->init_templ_top_order_nr; + } else { + $parent = (int) $a_mapping->getMapping("Services/Skill", "skl_tree", $a_rec["Parent"]); + $order = $a_rec["OrderNr"]; + } + switch ($a_rec["Type"]) { + case "sctp": + include_once("./Services/Skill/classes/class.ilSkillTemplateCategory.php"); + $sctp = new ilSkillTemplateCategory(); + $sctp->setTitle($a_rec["Title"]); + $sctp->setImportId("il_" . $source_inst_id . "_sctp_" . $a_rec["Child"]); + $sctp->setOrderNr($order); + $sctp->create(); + ilSkillTreeNode::putInTree($sctp, $parent); + $a_mapping->addMapping("Services/Skill", "skl_tree", $a_rec["Child"], $sctp->getId()); + break; + + case "sktp": + include_once("./Services/Skill/classes/class.ilBasicSkillTemplate.php"); + $sktp = new ilBasicSkillTemplate(); + $sktp->setTitle($a_rec["Title"]); + $sktp->setImportId("il_" . $source_inst_id . "_sktp_" . $a_rec["Child"]); + $sktp->setOrderNr($order); + $sktp->create(); + ilSkillTreeNode::putInTree($sktp, $parent); + $a_mapping->addMapping("Services/Skill", "skl_tree", $a_rec["Child"], $sktp->getId()); + break; + } + break; + + case "skl_level": + $skill_id = (int) $a_mapping->getMapping("Services/Skill", "skl_tree", $a_rec["SkillId"]); + $type = ilSkillTreeNode::_lookupType($skill_id); + if (in_array($type, array("skll", "sktp"))) { + if ($type == "skll") { + $skill = new ilBasicSkill($skill_id); + } else { + $skill = new ilBasicSkillTemplate($skill_id); + } + $skill->addLevel($a_rec["Title"], $a_rec["Description"], "il_" . $source_inst_id . "_sklv_" . $a_rec["LevelId"]); + $skill->update(); + } + break; + + case "skl_prof": + include_once("./Services/Skill/classes/class.ilSkillProfile.php"); + $prof = new ilSkillProfile(); + $prof->setTitle($a_rec["Title"]); + $prof->setDescription($a_rec["Description"]); + $prof->create(); + $a_mapping->addMapping("Services/Skill", "skl_prof", $a_rec["Id"], $prof->getId()); + break; + + case "skl_prof_level": + $profile_id = (int) $a_mapping->getMapping("Services/Skill", "skl_prof", $a_rec["ProfileId"]); + if ($profile_id > 0) { + include_once("./Services/Skill/classes/class.ilSkillProfile.php"); + include_once("./Services/Skill/classes/class.ilBasicSkill.php"); + $prof = new ilSkillProfile($profile_id); + $level_id_data = ilBasicSkill::getLevelIdForImportId($this->getCurrentInstallationId(), $a_rec["LevelId"]); + $skill_data = ilBasicSkill::getCommonSkillIdForImportId($this->getCurrentInstallationId(), $a_rec["BaseSkillId"], $a_rec["TrefId"]); + //var_dump($level_id_data); + //var_dump($skill_data); + $level_id = $tref_id = $base_skill = 0; + foreach ($level_id_data as $l) { + reset($skill_data); + foreach ($skill_data as $s) { + // echo "
                  =".ilBasicSkill::lookupLevelSkillId($l["level_id"])."=".$s["skill_id"]."="; + + if ($level_id == 0 && ilBasicSkill::lookupLevelSkillId($l["level_id"]) == $s["skill_id"]) { + $level_id = $l["level_id"]; + $base_skill = $s["skill_id"]; + $tref_id = $s["tref_id"]; + } + } + } + if ($level_id > 0) { + $prof->addSkillLevel($base_skill, $tref_id, $level_id); + } + $prof->update(); + } + break; + } + } } -?> \ No newline at end of file diff --git a/Services/Skill/classes/class.ilSkillEval.php b/Services/Skill/classes/class.ilSkillEval.php index f335a6611063d0494be3eadf2b1ad786e2dffd97..126b003865b8a9e5dcce455d90eb7148785e350e 100644 --- a/Services/Skill/classes/class.ilSkillEval.php +++ b/Services/Skill/classes/class.ilSkillEval.php @@ -15,7 +15,7 @@ include_once("./Services/Skill/classes/class.ilSkillProfile.php"); */ class ilSkillEval { - const TYPE_APPRAISAL = 1; - const TYPE_MEASUREMENT = 2; - const TYPE_SELF_EVAL = 3; -} \ No newline at end of file + const TYPE_APPRAISAL = 1; + const TYPE_MEASUREMENT = 2; + const TYPE_SELF_EVAL = 3; +} diff --git a/Services/Skill/classes/class.ilSkillExportConfig.php b/Services/Skill/classes/class.ilSkillExportConfig.php index 0256d7ff98b5d3ec9ff0378d5aaed33d8ebef13a..5792b2305baab4861bfb661b1a7517afc5c55d7a 100644 --- a/Services/Skill/classes/class.ilSkillExportConfig.php +++ b/Services/Skill/classes/class.ilSkillExportConfig.php @@ -12,71 +12,69 @@ include_once("./Services/Export/classes/class.ilExportConfig.php"); */ class ilSkillExportConfig extends ilExportConfig { - const MODE_SKILLS = ""; - const MODE_PROFILES = "prof"; - protected $selected_nodes = false; - protected $selected_profiles = false; - protected $mode = ""; + const MODE_SKILLS = ""; + const MODE_PROFILES = "prof"; + protected $selected_nodes = false; + protected $selected_profiles = false; + protected $mode = ""; - /** - * Set mode - * - * @param string $a_val mode - */ - function setMode($a_val) - { - $this->mode = $a_val; - } - - /** - * Get mode - * - * @return string mode - */ - function getMode() - { - return $this->mode; - } - - /** - * Set export selected nodes - * - * @param array $a_val array of int - */ - function setSelectedNodes($a_val) - { - $this->selected_nodes = $a_val; - } + /** + * Set mode + * + * @param string $a_val mode + */ + public function setMode($a_val) + { + $this->mode = $a_val; + } + + /** + * Get mode + * + * @return string mode + */ + public function getMode() + { + return $this->mode; + } + + /** + * Set export selected nodes + * + * @param array $a_val array of int + */ + public function setSelectedNodes($a_val) + { + $this->selected_nodes = $a_val; + } - /** - * Get export selected nodes - * - * @return array array of int - */ - function getSelectedNodes() - { - return $this->selected_nodes; - } + /** + * Get export selected nodes + * + * @return array array of int + */ + public function getSelectedNodes() + { + return $this->selected_nodes; + } - /** - * Set selected profiles - * - * @param array $a_val array of int (profile ids) - */ - function setSelectedProfiles($a_val) - { - $this->selected_profiles = $a_val; - } + /** + * Set selected profiles + * + * @param array $a_val array of int (profile ids) + */ + public function setSelectedProfiles($a_val) + { + $this->selected_profiles = $a_val; + } - /** - * Get selected profiles - * - * @return array array of int (profile ids) - */ - function getSelectedProfiles() - { - return $this->selected_profiles; - } + /** + * Get selected profiles + * + * @return array array of int (profile ids) + */ + public function getSelectedProfiles() + { + return $this->selected_profiles; + } } - -?> \ No newline at end of file diff --git a/Services/Skill/classes/class.ilSkillExporter.php b/Services/Skill/classes/class.ilSkillExporter.php index 6a61136ff367966e6554499fbe94c5c3cda7c5f5..0b5efc89e187fcf42936582c0ce097799099de60 100644 --- a/Services/Skill/classes/class.ilSkillExporter.php +++ b/Services/Skill/classes/class.ilSkillExporter.php @@ -12,82 +12,79 @@ include_once("./Services/Export/classes/class.ilXmlExporter.php"); */ class ilSkillExporter extends ilXmlExporter { - private $ds; + private $ds; - /** - * Initialisation - */ - function init() - { - include_once("./Services/Skill/classes/class.ilSkillDataSet.php"); - $this->ds = new ilSkillDataSet(); - $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); - $this->ds->setDSPrefix("ds"); - $this->config = $this->getExport()->getConfig("Services/Skill"); - $this->ds->setSelectedNodes($this->config->getSelectedNodes()); - $this->ds->setSelectedProfiles($this->config->getSelectedProfiles()); - $this->ds->setMode($this->config->getMode()); - } + /** + * Initialisation + */ + public function init() + { + include_once("./Services/Skill/classes/class.ilSkillDataSet.php"); + $this->ds = new ilSkillDataSet(); + $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute); + $this->ds->setDSPrefix("ds"); + $this->config = $this->getExport()->getConfig("Services/Skill"); + $this->ds->setSelectedNodes($this->config->getSelectedNodes()); + $this->ds->setSelectedProfiles($this->config->getSelectedProfiles()); + $this->ds->setMode($this->config->getMode()); + } - /** - * Get tail dependencies - * - * @param string entity - * @param string target release - * @param array ids - * @return array array of array with keys "component", entity", "ids" - */ - function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) - { - $deps = array(); - /*$deps = array ( - array( - "component" => "Services/COPage", - "entity" => "pg", - "ids" => $pg_ids), - array( - "component" => "Services/Rating", - "entity" => "rating_category", - "ids" => $a_ids - ) - );*/ + /** + * Get tail dependencies + * + * @param string entity + * @param string target release + * @param array ids + * @return array array of array with keys "component", entity", "ids" + */ + public function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids) + { + $deps = array(); + /*$deps = array ( + array( + "component" => "Services/COPage", + "entity" => "pg", + "ids" => $pg_ids), + array( + "component" => "Services/Rating", + "entity" => "rating_category", + "ids" => $a_ids + ) + );*/ - return $deps; - } - - /** - * Get xml representation - * - * @param string entity - * @param string target release - * @param string id - * @return string xml string - */ - public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) - { - return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); - } - - /** - * Returns schema versions that the component can export to. - * ILIAS chooses the first one, that has min/max constraints which - * fit to the target release. Please put the newest on top. - * - * @return - */ - function getValidSchemaVersions($a_entity) - { - return array ( - "5.1.0" => array( - "namespace" => "http://www.ilias.de/Services/Skill/skll/5_1", - "xsd_file" => "ilias_skll_5_1.xsd", - "uses_dataset" => true, - "min" => "5.1.0", - "max" => "") - ); - } + return $deps; + } + + /** + * Get xml representation + * + * @param string entity + * @param string target release + * @param string id + * @return string xml string + */ + public function getXmlRepresentation($a_entity, $a_schema_version, $a_id) + { + return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true); + } + /** + * Returns schema versions that the component can export to. + * ILIAS chooses the first one, that has min/max constraints which + * fit to the target release. Please put the newest on top. + * + * @return + */ + public function getValidSchemaVersions($a_entity) + { + return array( + "5.1.0" => array( + "namespace" => "http://www.ilias.de/Services/Skill/skll/5_1", + "xsd_file" => "ilias_skll_5_1.xsd", + "uses_dataset" => true, + "min" => "5.1.0", + "max" => "") + ); + } } - -?> \ No newline at end of file diff --git a/Services/Skill/classes/class.ilSkillGlobalScreenProvider.php b/Services/Skill/classes/class.ilSkillGlobalScreenProvider.php index ab896933dbab190435274e3e8653553e89a58d91..49d60c8a8dd00abc9da404994c0ab4bbb26ae2ec 100644 --- a/Services/Skill/classes/class.ilSkillGlobalScreenProvider.php +++ b/Services/Skill/classes/class.ilSkillGlobalScreenProvider.php @@ -8,57 +8,62 @@ use ILIAS\GlobalScreen\Scope\MainMenu\Provider\AbstractStaticMainMenuProvider; * * @author Fabian Schmid */ -class ilSkillGlobalScreenProvider extends AbstractStaticMainMenuProvider { +class ilSkillGlobalScreenProvider extends AbstractStaticMainMenuProvider +{ - /** - * @var IdentificationInterface - */ - protected $top_item; + /** + * @var IdentificationInterface + */ + protected $top_item; - public function __construct(\ILIAS\DI\Container $dic) { - parent::__construct($dic); - $this->top_item = (new ilPDGlobalScreenProvider($dic))->getTopItem(); - } + public function __construct(\ILIAS\DI\Container $dic) + { + parent::__construct($dic); + $this->top_item = (new ilPDGlobalScreenProvider($dic))->getTopItem(); + } - /** - * Some other components want to provide Items for the main menu which are - * located at the PD TopTitem by default. Therefore we have to provide our - * TopTitem Identification for others - * - * @return IdentificationInterface - */ - public function getTopItem(): IdentificationInterface { - return $this->top_item; - } + /** + * Some other components want to provide Items for the main menu which are + * located at the PD TopTitem by default. Therefore we have to provide our + * TopTitem Identification for others + * + * @return IdentificationInterface + */ + public function getTopItem() : IdentificationInterface + { + return $this->top_item; + } - /** - * @inheritDoc - */ - public function getStaticTopItems(): array { - return []; - } + /** + * @inheritDoc + */ + public function getStaticTopItems() : array + { + return []; + } - /** - * @inheritDoc - */ - public function getStaticSubItems(): array { - return []; - /* - return [$this->mainmenu->link($this->if->identifier('mm_pd_skill')) - ->withTitle($this->dic->language()->txt("skills")) - ->withAction("ilias.php?baseClass=ilPersonalDesktopGUI&cmd=jumpToSkills") - ->withParent($this->getTopItem()) - ->withNonAvailableReason($this->dic->ui()->factory()->legacy("{$this->dic->language()->txt('component_not_active')}")) - ->withAvailableCallable( - function () { - $skmg_set = new ilSetting("skmg"); + /** + * @inheritDoc + */ + public function getStaticSubItems() : array + { + return []; + /* + return [$this->mainmenu->link($this->if->identifier('mm_pd_skill')) + ->withTitle($this->dic->language()->txt("skills")) + ->withAction("ilias.php?baseClass=ilPersonalDesktopGUI&cmd=jumpToSkills") + ->withParent($this->getTopItem()) + ->withNonAvailableReason($this->dic->ui()->factory()->legacy("{$this->dic->language()->txt('component_not_active')}")) + ->withAvailableCallable( + function () { + $skmg_set = new ilSetting("skmg"); - return (bool)($skmg_set->get("enable_skmg")); - } - )];*/ - } + return (bool)($skmg_set->get("enable_skmg")); + } + )];*/ + } } diff --git a/Services/Skill/classes/class.ilSkillImporter.php b/Services/Skill/classes/class.ilSkillImporter.php index 32a05d5abe3cba19ae04dbde9cb6efec5a0db7a5..8a81318e8bca570a9ab3d6387afb0607b2f56cfc 100644 --- a/Services/Skill/classes/class.ilSkillImporter.php +++ b/Services/Skill/classes/class.ilSkillImporter.php @@ -13,58 +13,58 @@ include_once("./Services/Export/classes/class.ilXmlImporter.php"); class ilSkillImporter extends ilXmlImporter { - /** - * Initialisation - */ - function init() - { - include_once("./Services/Skill/classes/class.ilSkillDataSet.php"); - $this->ds = new ilSkillDataSet(); - $this->ds->setDSPrefix("ds"); + /** + * Initialisation + */ + public function init() + { + include_once("./Services/Skill/classes/class.ilSkillDataSet.php"); + $this->ds = new ilSkillDataSet(); + $this->ds->setDSPrefix("ds"); - /*$this->config = $this->getImport()->getConfig("Modules/MediaPool"); - if ($this->config->getTranslationImportMode()) - { - $this->ds->setTranslationImportMode( - $this->config->getTranslationLM(), - $this->config->getTranslationLang()); - $cop_config = $this->getImport()->getConfig("Services/COPage"); - $cop_config->setUpdateIfExists(true); - $cop_config->setForceLanguage($this->config->getTranslationLang()); - $cop_config->setReuseOriginallyExportedMedia(true); - $cop_config->setSkipInternalLinkResolve(true); + /*$this->config = $this->getImport()->getConfig("Modules/MediaPool"); + if ($this->config->getTranslationImportMode()) + { + $this->ds->setTranslationImportMode( + $this->config->getTranslationLM(), + $this->config->getTranslationLang()); + $cop_config = $this->getImport()->getConfig("Services/COPage"); + $cop_config->setUpdateIfExists(true); + $cop_config->setForceLanguage($this->config->getTranslationLang()); + $cop_config->setReuseOriginallyExportedMedia(true); + $cop_config->setSkipInternalLinkResolve(true); - $mob_config = $this->getImport()->getConfig("Services/MediaObjects"); - $mob_config->setUsePreviousImportIds(true); - }*/ + $mob_config = $this->getImport()->getConfig("Services/MediaObjects"); + $mob_config->setUsePreviousImportIds(true); + }*/ + } - } + /** + * Import XML + * + * @param + * @return + */ + public function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) + { + include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); + $parser = new ilDataSetImportParser( + $a_entity, + $this->getSchemaVersion(), + $a_xml, + $this->ds, + $a_mapping + ); + } - /** - * Import XML - * - * @param - * @return - */ - function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) - { - 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) - { - //$pg_map = $a_mapping->getMappingsOfEntity("Modules/MediaPool", "pg"); - - } - + /** + * Final processing + * + * @param array mapping array + */ + public function finalProcessing($a_mapping) + { + //$pg_map = $a_mapping->getMappingsOfEntity("Modules/MediaPool", "pg"); + } } - -?> \ No newline at end of file diff --git a/Services/Skill/classes/class.ilSkillLevelProfileAssignmentTableGUI.php b/Services/Skill/classes/class.ilSkillLevelProfileAssignmentTableGUI.php index f432cb8c3fedc4c2a1d5706d5c0548045cae6e13..6c5f2b4d26d052e23d2570660859b67003a695bd 100644 --- a/Services/Skill/classes/class.ilSkillLevelProfileAssignmentTableGUI.php +++ b/Services/Skill/classes/class.ilSkillLevelProfileAssignmentTableGUI.php @@ -14,60 +14,60 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilSkillLevelProfileAssignmentTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_cskill_id) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_cskill_id) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - include_once("./Services/Skill/classes/class.ilBasicSkill.php"); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + include_once("./Services/Skill/classes/class.ilBasicSkill.php"); - $parts = explode(":", $a_cskill_id); - $this->skill_id = (int) $parts[0]; - $this->tref_id = (int) $parts[1]; + $parts = explode(":", $a_cskill_id); + $this->skill_id = (int) $parts[0]; + $this->tref_id = (int) $parts[1]; - $this->skill = new ilBasicSkill($this->skill_id); - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setData($this->skill->getLevelData()); - $this->setTitle($this->skill->getTitle().", ". - $lng->txt("skmg_skill_levels")); - - $this->addColumn($this->lng->txt("title")); - $this->addColumn($this->lng->txt("actions")); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.skill_level_profile_assignment_row.html", "Services/Skill"); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->tpl->setCurrentBlock("cmd"); - $this->tpl->setVariable("CMD", $lng->txt("skmg_assign_level")); - $ilCtrl->setParameter($this->parent_obj, "level_id", (int) $a_set["id"]); - $this->tpl->setVariable("CMD_HREF", $ilCtrl->getLinkTarget($this->parent_obj, - "assignLevelToProfile")); - $ilCtrl->setParameter($this->parent_obj, "level_id", $_GET["level_id"]); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setVariable("TITLE", $a_set["title"]); - } + $this->skill = new ilBasicSkill($this->skill_id); + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setData($this->skill->getLevelData()); + $this->setTitle($this->skill->getTitle() . ", " . + $lng->txt("skmg_skill_levels")); + + $this->addColumn($this->lng->txt("title")); + $this->addColumn($this->lng->txt("actions")); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.skill_level_profile_assignment_row.html", "Services/Skill"); + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $this->tpl->setCurrentBlock("cmd"); + $this->tpl->setVariable("CMD", $lng->txt("skmg_assign_level")); + $ilCtrl->setParameter($this->parent_obj, "level_id", (int) $a_set["id"]); + $this->tpl->setVariable("CMD_HREF", $ilCtrl->getLinkTarget( + $this->parent_obj, + "assignLevelToProfile" + )); + $ilCtrl->setParameter($this->parent_obj, "level_id", $_GET["level_id"]); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setVariable("TITLE", $a_set["title"]); + } } -?> diff --git a/Services/Skill/classes/class.ilSkillLevelResourcesTableGUI.php b/Services/Skill/classes/class.ilSkillLevelResourcesTableGUI.php index 79a3012b385005757eab65a1a2e48898ef76e984..b8fc7bc7e68192345e35b88860a1b0c80dd7a8c6 100644 --- a/Services/Skill/classes/class.ilSkillLevelResourcesTableGUI.php +++ b/Services/Skill/classes/class.ilSkillLevelResourcesTableGUI.php @@ -14,107 +14,104 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilSkillLevelResourcesTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * @var ilTree - */ - protected $tree; + /** + * @var ilTree + */ + protected $tree; - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_skill_id, $a_tref_id, - $a_level_id, $a_write_permission = false) - { - global $DIC; + /** + * Constructor + */ + public function __construct( + $a_parent_obj, + $a_parent_cmd, + $a_skill_id, + $a_tref_id, + $a_level_id, + $a_write_permission = false + ) { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $this->tree = $DIC->repositoryTree(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->tree = $DIC->repositoryTree(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->level_id = $a_level_id; - - include_once("./Services/Skill/classes/class.ilSkillResources.php"); - $this->resources = new ilSkillResources($a_skill_id, $a_tref_id); - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setData($this->resources->getResourcesOfLevel($a_level_id)); - $this->setTitle($lng->txt("resources")); - - $this->addColumn("", "", "1px", true); - $this->addColumn($this->lng->txt("type"), "", "1px"); - $this->addColumn($this->lng->txt("title"), ""); - $this->addColumn($this->lng->txt("path")); - $this->addColumn($this->lng->txt("skmg_suggested")); - $this->addColumn($this->lng->txt("skmg_lp_triggers_level")); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.level_resources_row.html", "Services/Skill"); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->level_id = $a_level_id; + + include_once("./Services/Skill/classes/class.ilSkillResources.php"); + $this->resources = new ilSkillResources($a_skill_id, $a_tref_id); + + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setData($this->resources->getResourcesOfLevel($a_level_id)); + $this->setTitle($lng->txt("resources")); + + $this->addColumn("", "", "1px", true); + $this->addColumn($this->lng->txt("type"), "", "1px"); + $this->addColumn($this->lng->txt("title"), ""); + $this->addColumn($this->lng->txt("path")); + $this->addColumn($this->lng->txt("skmg_suggested")); + $this->addColumn($this->lng->txt("skmg_lp_triggers_level")); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.level_resources_row.html", "Services/Skill"); - if ($a_write_permission) - { - $this->addMultiCommand("confirmLevelResourcesRemoval", $lng->txt("remove")); - $this->addCommandButton("saveResourceSettings", $lng->txt("skmg_save_settings")); - } - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $tree = $this->tree; + if ($a_write_permission) { + $this->addMultiCommand("confirmLevelResourcesRemoval", $lng->txt("remove")); + $this->addCommandButton("saveResourceSettings", $lng->txt("skmg_save_settings")); + } + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $tree = $this->tree; - $ref_id = $a_set["rep_ref_id"]; - $obj_id = ilObject::_lookupObjId($ref_id); - $obj_type = ilObject::_lookupType($obj_id); + $ref_id = $a_set["rep_ref_id"]; + $obj_id = ilObject::_lookupObjId($ref_id); + $obj_type = ilObject::_lookupType($obj_id); - if ($a_set["imparting"]) - { - $this->tpl->touchBlock("sugg_checked"); - } + if ($a_set["imparting"]) { + $this->tpl->touchBlock("sugg_checked"); + } - include_once "Services/Object/classes/class.ilObjectLP.php"; - if (ilObjectLP::isSupportedObjectType($obj_type)) - { - if ($a_set["trigger"]) - { - $this->tpl->touchBlock("trig_checked"); - } - $this->tpl->setCurrentBlock("trigger_checkbox"); - $this->tpl->setVariable("TR_ID", $ref_id); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setVariable("TITLE", ilObject::_lookupTitle($obj_id)); - $this->tpl->setVariable("IMG", ilUtil::img(ilObject::_getIcon($obj_id, "tiny"))); - $this->tpl->setVariable("ID", $ref_id); - - $path = $tree->getPathFull($ref_id); - $path_items = array(); - foreach ($path as $p) - { - if ($p["type"] != "root" && $p["child"] != $ref_id) - { - $path_items[] = $p["title"]; - } - } - $this->tpl->setVariable("PATH", implode($path_items, " > ")); - } + include_once "Services/Object/classes/class.ilObjectLP.php"; + if (ilObjectLP::isSupportedObjectType($obj_type)) { + if ($a_set["trigger"]) { + $this->tpl->touchBlock("trig_checked"); + } + $this->tpl->setCurrentBlock("trigger_checkbox"); + $this->tpl->setVariable("TR_ID", $ref_id); + $this->tpl->parseCurrentBlock(); + } + $this->tpl->setVariable("TITLE", ilObject::_lookupTitle($obj_id)); + $this->tpl->setVariable("IMG", ilUtil::img(ilObject::_getIcon($obj_id, "tiny"))); + $this->tpl->setVariable("ID", $ref_id); + + $path = $tree->getPathFull($ref_id); + $path_items = array(); + foreach ($path as $p) { + if ($p["type"] != "root" && $p["child"] != $ref_id) { + $path_items[] = $p["title"]; + } + } + $this->tpl->setVariable("PATH", implode($path_items, " > ")); + } } -?> diff --git a/Services/Skill/classes/class.ilSkillLevelTableGUI.php b/Services/Skill/classes/class.ilSkillLevelTableGUI.php index a9bff8653d1883c2db7fbdf9789c712a0fa1db9f..5af502d7f0a51c80bc6be6fa4b91583dc4e88c47 100644 --- a/Services/Skill/classes/class.ilSkillLevelTableGUI.php +++ b/Services/Skill/classes/class.ilSkillLevelTableGUI.php @@ -15,192 +15,180 @@ include_once("./Services/Link/classes/class.ilLink.php"); */ class ilSkillLevelTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var bool - */ - protected $in_use = false; - - /** - * Constructor - */ - function __construct($a_skill_id, $a_parent_obj, $a_parent_cmd, $a_tref_id = 0, $a_in_use = 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(); - - include_once("./Services/Skill/classes/class.ilBasicSkill.php"); - $this->skill_id = $a_skill_id; - $this->skill = new ilBasicSkill($a_skill_id); - $this->tref_id = $a_tref_id; - $this->in_use = $a_in_use; - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setLimit(9999); - $this->setData($this->getSkillLevelData()); - $this->setTitle($lng->txt("skmg_skill_levels")); - if ($this->tref_id == 0) - { - $this->setDescription($lng->txt("skmg_from_lower_to_higher_levels")); - } - - if ($this->tref_id == 0 && !$this->in_use) - { - $this->addColumn("", "", "1", true); - $this->addColumn($this->lng->txt("skmg_nr")); - } - $this->addColumn($this->lng->txt("title")); - $this->addColumn($this->lng->txt("description")); -// $this->addColumn($this->lng->txt("skmg_trigger")); -// $this->addColumn($this->lng->txt("skmg_certificate")) - $this->addColumn($this->lng->txt("resources")); - $this->addColumn($this->lng->txt("actions")); - $this->setDefaultOrderField("nr"); - $this->setDefaultOrderDirection("asc"); - - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.skill_level_row.html", "Services/Skill"); - $this->setEnableTitle(true); - - if ($this->tref_id == 0 && !$this->in_use && $a_parent_obj->checkPermissionBool("write")) - { - $this->addMultiCommand("confirmLevelDeletion", $lng->txt("delete")); - if (count($this->getData()) > 0) - { - $this->addCommandButton("updateLevelOrder", $lng->txt("skmg_update_order")); - } - } - } - - /** - * Should this field be sorted numeric? - * - * @return boolean numeric ordering; default is false - */ - function numericOrdering($a_field) - { - if ($a_field == "nr") - { - return true; - } - return false; - } - - /** - * Get skill level data - * - * @param - * @return - */ - function getSkillLevelData() - { - $levels = $this->skill->getLevelData(); - - // add ressource data - $res = array(); - include_once("./Services/Skill/classes/class.ilSkillResources.php"); - $resources = new ilSkillResources($this->skill_id, $this->tref_id); - foreach($resources->getResources() as $level_id => $item) - { - $res[$level_id] = array_keys($item); - } - - foreach($levels as $idx => $item) - { - $levels[$idx]["ressources"] = $res[$item["id"]]; - } - - return $levels; - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if ($this->tref_id == 0 && !$this->in_use) - { - $this->tpl->setCurrentBlock("cb"); - $this->tpl->setVariable("CB_ID", $a_set["id"]); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setCurrentBlock("nr"); - $this->tpl->setVariable("ORD_ID", $a_set["id"]); - $this->tpl->setVariable("VAL_NR", ((int) $a_set["nr"]) * 10); - $this->tpl->parseCurrentBlock(); - - } - - $this->tpl->setCurrentBlock("cmd"); - $this->tpl->setVariable("TXT_CMD", $lng->txt("edit")); - $ilCtrl->setParameter($this->parent_obj, "level_id", $a_set["id"]); - if ($this->tref_id == 0) - { - $this->tpl->setVariable("HREF_CMD", - $ilCtrl->getLinkTarget($this->parent_obj, "editLevel")); - } - else - { - $this->tpl->setVariable("HREF_CMD", - $ilCtrl->getLinkTarget($this->parent_obj, "showLevelResources")); - } - $this->tpl->parseCurrentBlock(); - - $this->tpl->setVariable("TXT_TITLE", $a_set["title"]); - $this->tpl->setVariable("TXT_DESCRIPTION", $a_set["description"]); -/* $this->tpl->setVariable("TXT_CERTIFICATE", - ilBasicSkill::_lookupCertificate($this->skill->getId(), - $a_set["id"]) - ? $lng->txt("yes") - : $lng->txt("no"));*/ - -/* $trigger = ilBasicSkill::lookupLevelTrigger((int) $a_set["id"]); - if (ilObject::_lookupType($trigger["obj_id"]) != "crs" || - ilObject::_isInTrash($trigger["ref_id"])) - { - $trigger = array(); - } - - // trigger - if ($trigger["obj_id"] > 0) - { - $this->tpl->setVariable("TXT_TRIGGER", - ilObject::_lookupTitle($trigger["obj_id"])); - }*/ - - if(is_array($a_set["ressources"])) - { - $this->tpl->setCurrentBlock("ressource_bl"); - foreach($a_set["ressources"] as $rref_id) - { - $robj_id = ilObject::_lookupObjId($rref_id); - $this->tpl->setVariable("RSRC_IMG", ilUtil::img(ilObject::_getIcon($robj_id, "tiny"))); - $this->tpl->setVariable("RSRC_TITLE", ilObject::_lookupTitle($robj_id)); - $this->tpl->setVariable("RSRC_URL", ilLink::_getStaticLink($rref_id)); - $this->tpl->parseCurrentBlock(); - } - } - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var bool + */ + protected $in_use = false; + + /** + * Constructor + */ + public function __construct($a_skill_id, $a_parent_obj, $a_parent_cmd, $a_tref_id = 0, $a_in_use = 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(); + + include_once("./Services/Skill/classes/class.ilBasicSkill.php"); + $this->skill_id = $a_skill_id; + $this->skill = new ilBasicSkill($a_skill_id); + $this->tref_id = $a_tref_id; + $this->in_use = $a_in_use; + + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setLimit(9999); + $this->setData($this->getSkillLevelData()); + $this->setTitle($lng->txt("skmg_skill_levels")); + if ($this->tref_id == 0) { + $this->setDescription($lng->txt("skmg_from_lower_to_higher_levels")); + } + + if ($this->tref_id == 0 && !$this->in_use) { + $this->addColumn("", "", "1", true); + $this->addColumn($this->lng->txt("skmg_nr")); + } + $this->addColumn($this->lng->txt("title")); + $this->addColumn($this->lng->txt("description")); + // $this->addColumn($this->lng->txt("skmg_trigger")); + // $this->addColumn($this->lng->txt("skmg_certificate")) + $this->addColumn($this->lng->txt("resources")); + $this->addColumn($this->lng->txt("actions")); + $this->setDefaultOrderField("nr"); + $this->setDefaultOrderDirection("asc"); + + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.skill_level_row.html", "Services/Skill"); + $this->setEnableTitle(true); + + if ($this->tref_id == 0 && !$this->in_use && $a_parent_obj->checkPermissionBool("write")) { + $this->addMultiCommand("confirmLevelDeletion", $lng->txt("delete")); + if (count($this->getData()) > 0) { + $this->addCommandButton("updateLevelOrder", $lng->txt("skmg_update_order")); + } + } + } + + /** + * Should this field be sorted numeric? + * + * @return boolean numeric ordering; default is false + */ + public function numericOrdering($a_field) + { + if ($a_field == "nr") { + return true; + } + return false; + } + + /** + * Get skill level data + * + * @param + * @return + */ + public function getSkillLevelData() + { + $levels = $this->skill->getLevelData(); + + // add ressource data + $res = array(); + include_once("./Services/Skill/classes/class.ilSkillResources.php"); + $resources = new ilSkillResources($this->skill_id, $this->tref_id); + foreach ($resources->getResources() as $level_id => $item) { + $res[$level_id] = array_keys($item); + } + + foreach ($levels as $idx => $item) { + $levels[$idx]["ressources"] = $res[$item["id"]]; + } + + return $levels; + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if ($this->tref_id == 0 && !$this->in_use) { + $this->tpl->setCurrentBlock("cb"); + $this->tpl->setVariable("CB_ID", $a_set["id"]); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setCurrentBlock("nr"); + $this->tpl->setVariable("ORD_ID", $a_set["id"]); + $this->tpl->setVariable("VAL_NR", ((int) $a_set["nr"]) * 10); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setCurrentBlock("cmd"); + $this->tpl->setVariable("TXT_CMD", $lng->txt("edit")); + $ilCtrl->setParameter($this->parent_obj, "level_id", $a_set["id"]); + if ($this->tref_id == 0) { + $this->tpl->setVariable( + "HREF_CMD", + $ilCtrl->getLinkTarget($this->parent_obj, "editLevel") + ); + } else { + $this->tpl->setVariable( + "HREF_CMD", + $ilCtrl->getLinkTarget($this->parent_obj, "showLevelResources") + ); + } + $this->tpl->parseCurrentBlock(); + + $this->tpl->setVariable("TXT_TITLE", $a_set["title"]); + $this->tpl->setVariable("TXT_DESCRIPTION", $a_set["description"]); + /* $this->tpl->setVariable("TXT_CERTIFICATE", + ilBasicSkill::_lookupCertificate($this->skill->getId(), + $a_set["id"]) + ? $lng->txt("yes") + : $lng->txt("no"));*/ + + /* $trigger = ilBasicSkill::lookupLevelTrigger((int) $a_set["id"]); + if (ilObject::_lookupType($trigger["obj_id"]) != "crs" || + ilObject::_isInTrash($trigger["ref_id"])) + { + $trigger = array(); + } + + // trigger + if ($trigger["obj_id"] > 0) + { + $this->tpl->setVariable("TXT_TRIGGER", + ilObject::_lookupTitle($trigger["obj_id"])); + }*/ + + if (is_array($a_set["ressources"])) { + $this->tpl->setCurrentBlock("ressource_bl"); + foreach ($a_set["ressources"] as $rref_id) { + $robj_id = ilObject::_lookupObjId($rref_id); + $this->tpl->setVariable("RSRC_IMG", ilUtil::img(ilObject::_getIcon($robj_id, "tiny"))); + $this->tpl->setVariable("RSRC_TITLE", ilObject::_lookupTitle($robj_id)); + $this->tpl->setVariable("RSRC_URL", ilLink::_getStaticLink($rref_id)); + $this->tpl->parseCurrentBlock(); + } + } + } } -?> diff --git a/Services/Skill/classes/class.ilSkillManagementSettings.php b/Services/Skill/classes/class.ilSkillManagementSettings.php index e982eefe68f7f6875805483bbcf1a576ea8c7dd9..19df92b5fcaea668aa846f282a002f30b2620fc5 100644 --- a/Services/Skill/classes/class.ilSkillManagementSettings.php +++ b/Services/Skill/classes/class.ilSkillManagementSettings.php @@ -7,57 +7,55 @@ * * @author Alex Killing * @version $Id$ - * @ingroup + * @ingroup */ class ilSkillManagementSettings extends ilSetting { - /** - * Constructor - */ - function __construct() - { - parent::__construct("skmg"); - } - - /** - * Activate skill management - * - * @param - * @return - */ - function activate($a_active) - { - $this->set("enable_skmg", (int) $a_active); - } - - - /** - * Is activated - */ - function isActivated() - { - return $this->get("enable_skmg"); - } - - /** - * Set hide profile values before self evaluations - * - * @param bool $a_val hide profile - */ - function setHideProfileBeforeSelfEval($a_val) - { - $this->set("hide_profile_self_eval", (int) $a_val); - } - - /** - * Get hide profile values before self evaluations - * - * @return bool hide profile - */ - function getHideProfileBeforeSelfEval() - { - return $this->get("hide_profile_self_eval"); - } + /** + * Constructor + */ + public function __construct() + { + parent::__construct("skmg"); + } + + /** + * Activate skill management + * + * @param + * @return + */ + public function activate($a_active) + { + $this->set("enable_skmg", (int) $a_active); + } + + + /** + * Is activated + */ + public function isActivated() + { + return $this->get("enable_skmg"); + } + + /** + * Set hide profile values before self evaluations + * + * @param bool $a_val hide profile + */ + public function setHideProfileBeforeSelfEval($a_val) + { + $this->set("hide_profile_self_eval", (int) $a_val); + } + + /** + * Get hide profile values before self evaluations + * + * @return bool hide profile + */ + public function getHideProfileBeforeSelfEval() + { + return $this->get("hide_profile_self_eval"); + } } - -?> diff --git a/Services/Skill/classes/class.ilSkillNotifications.php b/Services/Skill/classes/class.ilSkillNotifications.php index 2761826fbff89c53b6909f39a9d349e7460105f0..3eabb9b37746c95023ddbf34e7a3d3634bcc1033 100644 --- a/Services/Skill/classes/class.ilSkillNotifications.php +++ b/Services/Skill/classes/class.ilSkillNotifications.php @@ -11,259 +11,249 @@ include_once "Services/Cron/classes/class.ilCronJob.php"; */ class ilSkillNotifications extends ilCronJob { - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilIniFile - */ - protected $client_ini; - - /** - * @var ilTree - */ - protected $tree; - - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - if (isset($DIC["ilUser"])) - { - $this->user = $DIC->user(); - } - if (isset($DIC["ilClientIniFile"])) - { - $this->client_ini = $DIC["ilClientIniFile"]; - } - if (isset($DIC["tree"])) - { - $this->tree = $DIC->repositoryTree(); - } - } - - public function getId() - { - return "skll_notification"; - } - - public function getTitle() - { - $lng = $this->lng; - $lng->loadLanguageModule("skll"); - return $lng->txt("skll_skill_notification"); - } - - public function getDescription() - { - $lng = $this->lng; - $lng->loadLanguageModule("skll"); - return $lng->txt("skll_skill_notification_desc"); - } - - public function getDefaultScheduleType() - { - return self::SCHEDULE_TYPE_DAILY; - } - - public function getDefaultScheduleValue() - { - return; - } - - public function hasAutoActivation() - { - return false; - } - - public function hasFlexibleSchedule() - { - return true; - } - - public function run() - { - global $DIC; - - $lng = $DIC->language(); - - $log = ilLoggerFactory::getLogger("skll"); - $log->debug("===Skill Notifications=== start"); - - $status = ilCronJobResult::STATUS_NO_ACTION; - $status_details = null; - - $setting = new ilSetting("cron"); - $last_run = $setting->get(get_class($this)); - - // no last run? - if (!$last_run) - { - $last_run = date("Y-m-d H:i:s", strtotime("yesterday")); - - $status_details = "No previous run found - starting from yesterday."; - } // migration: used to be date-only value - else if (strlen($last_run) == 10) - { - $last_run .= " 00:00:00"; - - $status_details = "Switched from daily runs to open schedule."; - } - - // init language/date - $old_lng = $lng; - $old_dt = ilDatePresentation::useRelativeDates(); - ilDatePresentation::setUseRelativeDates(false); - - -// $last_run = "2017-07-20 12:00:00"; - - // get latest course/group skill changes per user - include_once("./Services/Skill/classes/class.ilBasicSkill.php"); - $achievements = ilBasicSkill::getNewAchievementsPerUser($last_run); - - foreach ($achievements as $user_id => $a) - { - $this->sendMail($user_id, $a, $last_run); - } - - // mails were sent - set cron job status accordingly - $status = ilCronJobResult::STATUS_OK; - - // reset language/date - ilDatePresentation::setUseRelativeDates($old_dt); - $lng = $old_lng; - - $log->debug("save run"); - - // save last run - $setting->set(get_class($this), date("Y-m-d H:i:s")); - - $result = new ilCronJobResult(); - $result->setStatus($status); - - if($status_details) - { - $result->setMessage($status_details); - } - - $log->debug("===Skill Notifications=== done"); - - return $result; - } - - - /** - * Send news mail for 1 user and n objects - * - * @param int $a_user_id - * @param array $a_objects - * @param string $a_last_run - */ - protected function sendMail($a_user_id, array $a_achievements, $a_last_run) - { - $lng = $this->lng; - $ilUser = $this->user; - $ilClientIniFile = $this->client_ini; - $tree = $this->tree; - - include_once "./Services/Notification/classes/class.ilSystemNotification.php"; - $ntf = new ilSystemNotification(); - $ntf->setLangModules(array("skll")); - - // user specific language - $lng = $ntf->getUserLanguage($a_user_id); - - include_once './Services/Locator/classes/class.ilLocatorGUI.php'; - require_once "./Services/UICore/classes/class.ilTemplate.php"; - require_once "./Services/Link/classes/class.ilLink.php"; - - - $tmp = array(); - $txt = ""; - $last_obj_id = 0; - - // order skill achievements per virtual skill tree - include_once("./Services/Skill/classes/class.ilVirtualSkillTree.php"); - $vtree = new ilVirtualSkillTree(); - $a_achievements = $vtree->getOrderedNodeset($a_achievements, "skill_id", "tref_id"); - - foreach($a_achievements as $skill_level) - { - $parent = array(); - - // path - $path = array(); - foreach($tree->getPathId($skill_level["trigger_ref_id"]) as $node) - { - $path[] = $node; - } - $path = implode("-", $path); - - $ref_id = $skill_level["trigger_ref_id"]; - $obj_id = $skill_level["trigger_obj_id"]; - $type = $skill_level["trigger_obj_type"]; - $title = $skill_level["trigger_title"]; - - if ($skill_level["trigger_obj_id"] != $last_obj_id) - { - $last_obj_id = $skill_level["trigger_obj_id"]; - $txt .= "\n\n" . $lng->txt("obj_" . $type) . ": " . $title; - if ($tree->isInTree($ref_id)) - { - $txt .= "\n".ilLink::_getStaticLink($ref_id); - } - } - - $date = ilDatePresentation::formatDate(new ilDateTime($skill_level["status_date"], IL_CAL_DATETIME)); - $txt.= "\n $date, ".ilBasicSkill::_lookupTitle($skill_level["skill_id"], $skill_level["tref_id"]).": ". - ilBasicSkill::lookupLevelTitle($skill_level["level_id"]); - } - - $ntf->setIntroductionLangId("skll_intro_skill_notification_for"); - - // index - $period = sprintf( - $lng->txt("skll_new_skill_achievements"), - ilDatePresentation::formatDate(new ilDateTime($a_last_run, IL_CAL_DATETIME)), - ilDatePresentation::formatDate(new ilDateTime(time(), IL_CAL_UNIX)) - ); - - // text - $ntf->addAdditionalInfo("", - trim($txt), - true); - - // :TODO: does it make sense to add client to subject? - $client = $ilClientIniFile->readVariable('client', 'name'); - $subject = sprintf($lng->txt("skll_competence_achievements"), $client); - -//die($ntf->composeAndGetMessage($a_user_id, null, "read", true)); - - // #10044 - $mail = new ilMail(ANONYMOUS_USER_ID); - $mail->enableSOAP(false); // #10410 - $mail->sendMail(ilObjUser::_lookupLogin($a_user_id), - null, - null, - $subject, - $ntf->composeAndGetMessage($a_user_id, null, "read", true), - null, - array("system")); - } - + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilIniFile + */ + protected $client_ini; + + /** + * @var ilTree + */ + protected $tree; + + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + if (isset($DIC["ilUser"])) { + $this->user = $DIC->user(); + } + if (isset($DIC["ilClientIniFile"])) { + $this->client_ini = $DIC["ilClientIniFile"]; + } + if (isset($DIC["tree"])) { + $this->tree = $DIC->repositoryTree(); + } + } + + public function getId() + { + return "skll_notification"; + } + + public function getTitle() + { + $lng = $this->lng; + $lng->loadLanguageModule("skll"); + return $lng->txt("skll_skill_notification"); + } + + public function getDescription() + { + $lng = $this->lng; + $lng->loadLanguageModule("skll"); + return $lng->txt("skll_skill_notification_desc"); + } + + public function getDefaultScheduleType() + { + return self::SCHEDULE_TYPE_DAILY; + } + + public function getDefaultScheduleValue() + { + return; + } + + public function hasAutoActivation() + { + return false; + } + + public function hasFlexibleSchedule() + { + return true; + } + + public function run() + { + global $DIC; + + $lng = $DIC->language(); + + $log = ilLoggerFactory::getLogger("skll"); + $log->debug("===Skill Notifications=== start"); + + $status = ilCronJobResult::STATUS_NO_ACTION; + $status_details = null; + + $setting = new ilSetting("cron"); + $last_run = $setting->get(get_class($this)); + + // no last run? + if (!$last_run) { + $last_run = date("Y-m-d H:i:s", strtotime("yesterday")); + + $status_details = "No previous run found - starting from yesterday."; + } // migration: used to be date-only value + elseif (strlen($last_run) == 10) { + $last_run .= " 00:00:00"; + + $status_details = "Switched from daily runs to open schedule."; + } + + // init language/date + $old_lng = $lng; + $old_dt = ilDatePresentation::useRelativeDates(); + ilDatePresentation::setUseRelativeDates(false); + + + // $last_run = "2017-07-20 12:00:00"; + + // get latest course/group skill changes per user + include_once("./Services/Skill/classes/class.ilBasicSkill.php"); + $achievements = ilBasicSkill::getNewAchievementsPerUser($last_run); + + foreach ($achievements as $user_id => $a) { + $this->sendMail($user_id, $a, $last_run); + } + + // mails were sent - set cron job status accordingly + $status = ilCronJobResult::STATUS_OK; + + // reset language/date + ilDatePresentation::setUseRelativeDates($old_dt); + $lng = $old_lng; + + $log->debug("save run"); + + // save last run + $setting->set(get_class($this), date("Y-m-d H:i:s")); + + $result = new ilCronJobResult(); + $result->setStatus($status); + + if ($status_details) { + $result->setMessage($status_details); + } + + $log->debug("===Skill Notifications=== done"); + + return $result; + } + + + /** + * Send news mail for 1 user and n objects + * + * @param int $a_user_id + * @param array $a_objects + * @param string $a_last_run + */ + protected function sendMail($a_user_id, array $a_achievements, $a_last_run) + { + $lng = $this->lng; + $ilUser = $this->user; + $ilClientIniFile = $this->client_ini; + $tree = $this->tree; + + include_once "./Services/Notification/classes/class.ilSystemNotification.php"; + $ntf = new ilSystemNotification(); + $ntf->setLangModules(array("skll")); + + // user specific language + $lng = $ntf->getUserLanguage($a_user_id); + + include_once './Services/Locator/classes/class.ilLocatorGUI.php'; + require_once "./Services/UICore/classes/class.ilTemplate.php"; + require_once "./Services/Link/classes/class.ilLink.php"; + + + $tmp = array(); + $txt = ""; + $last_obj_id = 0; + + // order skill achievements per virtual skill tree + include_once("./Services/Skill/classes/class.ilVirtualSkillTree.php"); + $vtree = new ilVirtualSkillTree(); + $a_achievements = $vtree->getOrderedNodeset($a_achievements, "skill_id", "tref_id"); + + foreach ($a_achievements as $skill_level) { + $parent = array(); + + // path + $path = array(); + foreach ($tree->getPathId($skill_level["trigger_ref_id"]) as $node) { + $path[] = $node; + } + $path = implode("-", $path); + + $ref_id = $skill_level["trigger_ref_id"]; + $obj_id = $skill_level["trigger_obj_id"]; + $type = $skill_level["trigger_obj_type"]; + $title = $skill_level["trigger_title"]; + + if ($skill_level["trigger_obj_id"] != $last_obj_id) { + $last_obj_id = $skill_level["trigger_obj_id"]; + $txt .= "\n\n" . $lng->txt("obj_" . $type) . ": " . $title; + if ($tree->isInTree($ref_id)) { + $txt .= "\n" . ilLink::_getStaticLink($ref_id); + } + } + + $date = ilDatePresentation::formatDate(new ilDateTime($skill_level["status_date"], IL_CAL_DATETIME)); + $txt.= "\n $date, " . ilBasicSkill::_lookupTitle($skill_level["skill_id"], $skill_level["tref_id"]) . ": " . + ilBasicSkill::lookupLevelTitle($skill_level["level_id"]); + } + + $ntf->setIntroductionLangId("skll_intro_skill_notification_for"); + + // index + $period = sprintf( + $lng->txt("skll_new_skill_achievements"), + ilDatePresentation::formatDate(new ilDateTime($a_last_run, IL_CAL_DATETIME)), + ilDatePresentation::formatDate(new ilDateTime(time(), IL_CAL_UNIX)) + ); + + // text + $ntf->addAdditionalInfo( + "", + trim($txt), + true + ); + + // :TODO: does it make sense to add client to subject? + $client = $ilClientIniFile->readVariable('client', 'name'); + $subject = sprintf($lng->txt("skll_competence_achievements"), $client); + + //die($ntf->composeAndGetMessage($a_user_id, null, "read", true)); + + // #10044 + $mail = new ilMail(ANONYMOUS_USER_ID); + $mail->enableSOAP(false); // #10410 + $mail->sendMail( + ilObjUser::_lookupLogin($a_user_id), + null, + null, + $subject, + $ntf->composeAndGetMessage($a_user_id, null, "read", true), + null, + array("system") + ); + } } - -?> \ No newline at end of file diff --git a/Services/Skill/classes/class.ilSkillObjDeletionHandler.php b/Services/Skill/classes/class.ilSkillObjDeletionHandler.php index 9c9bd20a5a677c144e89653ed332a4a2279bb9be..b75ec35a70f6711e5016c383f10d4c3f17494669 100644 --- a/Services/Skill/classes/class.ilSkillObjDeletionHandler.php +++ b/Services/Skill/classes/class.ilSkillObjDeletionHandler.php @@ -10,37 +10,35 @@ */ class ilSkillObjDeletionHandler { - /** - * @var int - */ - protected $obj_id; + /** + * @var int + */ + protected $obj_id; - /** - * @var string - */ - protected $obj_type; + /** + * @var string + */ + protected $obj_type; - /** - * Constructor - */ - public function __construct($obj_id, $obj_type) - { - $this->obj_type = $obj_type; - $this->obj_id = $obj_id; - } + /** + * Constructor + */ + public function __construct($obj_id, $obj_type) + { + $this->obj_type = $obj_type; + $this->obj_id = $obj_id; + } - /** - * Process deletion - */ - public function processDeletion() - { - if ($this->obj_type == "usr" && ilObject::_lookupType($this->obj_id) == "usr") - { - ilPersonalSkill::removeSkills($this->obj_id); - ilPersonalSkill::removeMaterials($this->obj_id); - ilSkillProfile::removeUserFromAllProfiles($this->obj_id); - ilBasicSkill::removeAllUserData($this->obj_id); - } - } - -} \ No newline at end of file + /** + * Process deletion + */ + public function processDeletion() + { + if ($this->obj_type == "usr" && ilObject::_lookupType($this->obj_id) == "usr") { + ilPersonalSkill::removeSkills($this->obj_id); + ilPersonalSkill::removeMaterials($this->obj_id); + ilSkillProfile::removeUserFromAllProfiles($this->obj_id); + ilBasicSkill::removeAllUserData($this->obj_id); + } + } +} diff --git a/Services/Skill/classes/class.ilSkillProfile.php b/Services/Skill/classes/class.ilSkillProfile.php index cfd00c06ba49e666a0bf976b807cb7fec2bda0c5..87248e023b3d144313cae4a17ab32953fd31e027 100644 --- a/Services/Skill/classes/class.ilSkillProfile.php +++ b/Services/Skill/classes/class.ilSkillProfile.php @@ -5,7 +5,7 @@ include_once("./Services/Skill/interfaces/interface.ilSkillUsageInfo.php"); /** - * Skill profile + * Skill profile * * @author Alex Killing * @version $Id$ @@ -13,440 +13,451 @@ include_once("./Services/Skill/interfaces/interface.ilSkillUsageInfo.php"); */ class ilSkillProfile implements ilSkillUsageInfo { - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; - protected $id; - protected $title; - protected $description; - protected $skill_level = array(); - - /** - * Constructor - * - * @param int $a_id profile id - */ - function __construct($a_id = 0) - { - global $DIC; + protected $id; + protected $title; + protected $description; + protected $skill_level = array(); + + /** + * Constructor + * + * @param int $a_id profile id + */ + public function __construct($a_id = 0) + { + global $DIC; - $this->db = $DIC->database(); - if ($a_id > 0) - { - $this->setId($a_id); - $this->read(); - } - } - - /** - * Set id - * - * @param int $a_val id - */ - function setId($a_val) - { - $this->id = $a_val; - } - - /** - * Get id - * - * @return int id - */ - function getId() - { - return $this->id; - } - - /** - * Set title - * - * @param string $a_val title - */ - function setTitle($a_val) - { - $this->title = $a_val; - } - - /** - * Get title - * - * @return string title - */ - function getTitle() - { - return $this->title; - } - - /** - * Set description - * - * @param string $a_val description - */ - function setDescription($a_val) - { - $this->description = $a_val; - } - - /** - * Get description - * - * @return string description - */ - function getDescription() - { - return $this->description; - } - - /** - * Add skill level - * - * @param - * @return - */ - function addSkillLevel($a_base_skill_id, $a_tref_id, $a_level_id) - { -//echo "-".$a_base_skill_id."-"; - $this->skill_level[] = array( - "base_skill_id" => $a_base_skill_id, - "tref_id" => $a_tref_id, - "level_id" => $a_level_id - ); - } - - /** - * Remove skill level - * - * @param - * @return - */ - function removeSkillLevel($a_base_skill_id, $a_tref_id, $a_level_id) - { - foreach ($this->skill_level as $k => $sl) - { - if ((int) $sl["base_skill_id"] == (int) $a_base_skill_id && - (int) $sl["tref_id"] == (int) $a_tref_id && - (int) $sl["level_id"] == (int) $a_level_id) - { - unset($this->skill_level[$k]); - } - } - } + $this->db = $DIC->database(); + if ($a_id > 0) { + $this->setId($a_id); + $this->read(); + } + } + + /** + * Set id + * + * @param int $a_val id + */ + public function setId($a_val) + { + $this->id = $a_val; + } + + /** + * Get id + * + * @return int id + */ + public function getId() + { + return $this->id; + } + + /** + * Set title + * + * @param string $a_val title + */ + public function setTitle($a_val) + { + $this->title = $a_val; + } + + /** + * Get title + * + * @return string title + */ + public function getTitle() + { + return $this->title; + } + + /** + * Set description + * + * @param string $a_val description + */ + public function setDescription($a_val) + { + $this->description = $a_val; + } + + /** + * Get description + * + * @return string description + */ + public function getDescription() + { + return $this->description; + } + + /** + * Add skill level + * + * @param + * @return + */ + public function addSkillLevel($a_base_skill_id, $a_tref_id, $a_level_id) + { + //echo "-".$a_base_skill_id."-"; + $this->skill_level[] = array( + "base_skill_id" => $a_base_skill_id, + "tref_id" => $a_tref_id, + "level_id" => $a_level_id + ); + } + + /** + * Remove skill level + * + * @param + * @return + */ + public function removeSkillLevel($a_base_skill_id, $a_tref_id, $a_level_id) + { + foreach ($this->skill_level as $k => $sl) { + if ((int) $sl["base_skill_id"] == (int) $a_base_skill_id && + (int) $sl["tref_id"] == (int) $a_tref_id && + (int) $sl["level_id"] == (int) $a_level_id) { + unset($this->skill_level[$k]); + } + } + } - /** - * Get skill levels - * - * @param - * @return - */ - function getSkillLevels() - { - return $this->skill_level; - } - - /** - * Read skill profile from db - * - * @param - * @return - */ - function read() - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT * FROM skl_profile ". - " WHERE id = ".$ilDB->quote($this->getId(), "integer") - ); - $rec = $ilDB->fetchAssoc($set); - $this->setTitle($rec["title"]); - $this->setDescription($rec["description"]); - - $set = $ilDB->query("SELECT * FROM skl_profile_level ". - " WHERE profile_id = ".$ilDB->quote($this->getId(), "integer") - ); - while ($rec = $ilDB->fetchAssoc($set)) - { - $this->addSkillLevel((int) $rec["base_skill_id"], (int) $rec["tref_id"], - (int) $rec["level_id"]); - } - } - - /** - * Create skill profile - */ - function create() - { - $ilDB = $this->db; - - // profile - $this->setId($ilDB->nextId("skl_profile")); - $ilDB->manipulate("INSERT INTO skl_profile ". - "(id, title, description) VALUES (". - $ilDB->quote($this->getId(), "integer").",". - $ilDB->quote($this->getTitle(), "text").",". - $ilDB->quote($this->getDescription(), "text"). - ")"); - - // profile levels - foreach ($this->skill_level as $level) - { - $ilDB->replace("skl_profile_level", - array("profile_id" => array("integer", $this->getId()), - "tref_id" => array("integer", (int) $level["tref_id"]), - "base_skill_id" => array("integer", (int) $level["base_skill_id"]) - ), - array("level_id" => array("integer", (int) $level["level_id"])) - ); - } - } - - /** - * Update skill profile - */ - function update() - { - $ilDB = $this->db; - - // profile - $ilDB->manipulate("UPDATE skl_profile SET ". - " title = ".$ilDB->quote($this->getTitle(), "text").",". - " description = ".$ilDB->quote($this->getDescription(), "text"). - " WHERE id = ".$ilDB->quote($this->getId(), "integer") - ); - - // profile levels - $ilDB->manipulate("DELETE FROM skl_profile_level WHERE ". - " profile_id = ".$ilDB->quote($this->getId(), "integer") - ); - foreach ($this->skill_level as $level) - { - $ilDB->replace("skl_profile_level", - array("profile_id" => array("integer", $this->getId()), - "tref_id" => array("integer", (int) $level["tref_id"]), - "base_skill_id" => array("integer", (int) $level["base_skill_id"]) - ), - array("level_id" => array("integer", (int) $level["level_id"])) - ); - - /*$ilDB->manipulate("INSERT INTO skl_profile_level ". - "(profile_id, base_skill_id, tref_id, level_id) VALUES (". - $ilDB->quote($this->getId(), "integer").",". - $ilDB->quote((int) $level["base_skill_id"], "integer").",". - $ilDB->quote((int) $level["tref_id"], "integer").",". - $ilDB->quote((int) $level["level_id"], "integer"). - ")");*/ - } - } - - /** - * Delete skill profile - */ - function delete() - { - $ilDB = $this->db; - - // profile levels - $ilDB->manipulate("DELETE FROM skl_profile_level WHERE ". - " profile_id = ".$ilDB->quote($this->getId(), "integer") - ); - - // profile - $ilDB->manipulate("DELETE FROM skl_profile WHERE ". - " id = ".$ilDB->quote($this->getId(), "integer") - ); - - } - - /** - * Get profiles - * - * @param - * @return - */ - static function getProfiles() - { - global $DIC; + /** + * Get skill levels + * + * @param + * @return + */ + public function getSkillLevels() + { + return $this->skill_level; + } + + /** + * Read skill profile from db + * + * @param + * @return + */ + public function read() + { + $ilDB = $this->db; + + $set = $ilDB->query( + "SELECT * FROM skl_profile " . + " WHERE id = " . $ilDB->quote($this->getId(), "integer") + ); + $rec = $ilDB->fetchAssoc($set); + $this->setTitle($rec["title"]); + $this->setDescription($rec["description"]); + + $set = $ilDB->query( + "SELECT * FROM skl_profile_level " . + " WHERE profile_id = " . $ilDB->quote($this->getId(), "integer") + ); + while ($rec = $ilDB->fetchAssoc($set)) { + $this->addSkillLevel( + (int) $rec["base_skill_id"], + (int) $rec["tref_id"], + (int) $rec["level_id"] + ); + } + } + + /** + * Create skill profile + */ + public function create() + { + $ilDB = $this->db; + + // profile + $this->setId($ilDB->nextId("skl_profile")); + $ilDB->manipulate("INSERT INTO skl_profile " . + "(id, title, description) VALUES (" . + $ilDB->quote($this->getId(), "integer") . "," . + $ilDB->quote($this->getTitle(), "text") . "," . + $ilDB->quote($this->getDescription(), "text") . + ")"); + + // profile levels + foreach ($this->skill_level as $level) { + $ilDB->replace( + "skl_profile_level", + array("profile_id" => array("integer", $this->getId()), + "tref_id" => array("integer", (int) $level["tref_id"]), + "base_skill_id" => array("integer", (int) $level["base_skill_id"]) + ), + array("level_id" => array("integer", (int) $level["level_id"])) + ); + } + } + + /** + * Update skill profile + */ + public function update() + { + $ilDB = $this->db; + + // profile + $ilDB->manipulate( + "UPDATE skl_profile SET " . + " title = " . $ilDB->quote($this->getTitle(), "text") . "," . + " description = " . $ilDB->quote($this->getDescription(), "text") . + " WHERE id = " . $ilDB->quote($this->getId(), "integer") + ); + + // profile levels + $ilDB->manipulate( + "DELETE FROM skl_profile_level WHERE " . + " profile_id = " . $ilDB->quote($this->getId(), "integer") + ); + foreach ($this->skill_level as $level) { + $ilDB->replace( + "skl_profile_level", + array("profile_id" => array("integer", $this->getId()), + "tref_id" => array("integer", (int) $level["tref_id"]), + "base_skill_id" => array("integer", (int) $level["base_skill_id"]) + ), + array("level_id" => array("integer", (int) $level["level_id"])) + ); + + /*$ilDB->manipulate("INSERT INTO skl_profile_level ". + "(profile_id, base_skill_id, tref_id, level_id) VALUES (". + $ilDB->quote($this->getId(), "integer").",". + $ilDB->quote((int) $level["base_skill_id"], "integer").",". + $ilDB->quote((int) $level["tref_id"], "integer").",". + $ilDB->quote((int) $level["level_id"], "integer"). + ")");*/ + } + } + + /** + * Delete skill profile + */ + public function delete() + { + $ilDB = $this->db; + + // profile levels + $ilDB->manipulate( + "DELETE FROM skl_profile_level WHERE " . + " profile_id = " . $ilDB->quote($this->getId(), "integer") + ); + + // profile + $ilDB->manipulate( + "DELETE FROM skl_profile WHERE " . + " id = " . $ilDB->quote($this->getId(), "integer") + ); + } + + /** + * Get profiles + * + * @param + * @return + */ + public static function getProfiles() + { + global $DIC; - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT * FROM skl_profile ". - " ORDER BY title " - ); - $profiles = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $profiles[$rec["id"]] = $rec; - } - - return $profiles; - } - - /** - * Lookup - * - * @param - * @return - */ - static protected function lookup($a_id, $a_field) - { - global $DIC; + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT * FROM skl_profile " . + " ORDER BY title " + ); + $profiles = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $profiles[$rec["id"]] = $rec; + } + + return $profiles; + } + + /** + * Lookup + * + * @param + * @return + */ + protected static function lookup($a_id, $a_field) + { + global $DIC; - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT ".$a_field." FROM skl_profile ". - " WHERE id = ".$ilDB->quote($a_id, "integer") - ); - $rec = $ilDB->fetchAssoc($set); - return $rec[$a_field]; - } - - /** - * Lookup title - * - * @param - * @return - */ - static function lookupTitle($a_id) - { - return self::lookup($a_id, "title"); - } - - //// - //// Skill user assignment - //// - - /** - * Get assigned users - */ - function getAssignedUsers() - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT * FROM skl_profile_user ". - " WHERE profile_id = ".$ilDB->quote($this->getId(), "integer") - ); - $users = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $name = ilObjUser::_lookupName($rec["user_id"]); - $users[$rec["user_id"]] = array( - "lastname" => $name["lastname"], - "firstname" => $name["firstname"], - "login" => $name["login"], - "id" => $name["user_id"] - ); - } - return $users; - } - - /** - * Add user to profile - * - * @param int $a_user_id user id - */ - function addUserToProfile($a_user_id) - { - $ilDB = $this->db; - - $ilDB->replace("skl_profile_user", - array("profile_id" => array("integer", $this->getId()), - "user_id" => array("integer", (int) $a_user_id), - ), - array() - ); - } - - /** - * Remove user from profile - * - * @param int $a_user_id user id - */ - function removeUserFromProfile($a_user_id) - { - $ilDB = $this->db; - - $ilDB->manipulate("DELETE FROM skl_profile_user WHERE ". - " profile_id = ".$ilDB->quote($this->getId(), "integer"). - " AND user_id = ".$ilDB->quote($a_user_id, "integer") - ); - } + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT " . $a_field . " FROM skl_profile " . + " WHERE id = " . $ilDB->quote($a_id, "integer") + ); + $rec = $ilDB->fetchAssoc($set); + return $rec[$a_field]; + } + + /** + * Lookup title + * + * @param + * @return + */ + public static function lookupTitle($a_id) + { + return self::lookup($a_id, "title"); + } + + //// + //// Skill user assignment + //// + + /** + * Get assigned users + */ + public function getAssignedUsers() + { + $ilDB = $this->db; + + $set = $ilDB->query( + "SELECT * FROM skl_profile_user " . + " WHERE profile_id = " . $ilDB->quote($this->getId(), "integer") + ); + $users = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $name = ilObjUser::_lookupName($rec["user_id"]); + $users[$rec["user_id"]] = array( + "lastname" => $name["lastname"], + "firstname" => $name["firstname"], + "login" => $name["login"], + "id" => $name["user_id"] + ); + } + return $users; + } + + /** + * Add user to profile + * + * @param int $a_user_id user id + */ + public function addUserToProfile($a_user_id) + { + $ilDB = $this->db; + + $ilDB->replace( + "skl_profile_user", + array("profile_id" => array("integer", $this->getId()), + "user_id" => array("integer", (int) $a_user_id), + ), + array() + ); + } + + /** + * Remove user from profile + * + * @param int $a_user_id user id + */ + public function removeUserFromProfile($a_user_id) + { + $ilDB = $this->db; + + $ilDB->manipulate( + "DELETE FROM skl_profile_user WHERE " . + " profile_id = " . $ilDB->quote($this->getId(), "integer") . + " AND user_id = " . $ilDB->quote($a_user_id, "integer") + ); + } - /** - * Remove user from all profiles - * - * @param int $a_user_id - */ - public static function removeUserFromAllProfiles($a_user_id) - { - global $DIC; - $ilDB = $DIC->database(); + /** + * Remove user from all profiles + * + * @param int $a_user_id + */ + public static function removeUserFromAllProfiles($a_user_id) + { + global $DIC; + $ilDB = $DIC->database(); - $ilDB->manipulate("DELETE FROM skl_profile_user WHERE ". - " user_id = ".$ilDB->quote($a_user_id, "integer") - ); - } + $ilDB->manipulate( + "DELETE FROM skl_profile_user WHERE " . + " user_id = " . $ilDB->quote($a_user_id, "integer") + ); + } - - /** - * Get profiles of a user - * - * @param int $a_user_id user id - */ - static function getProfilesOfUser($a_user_id) - { - global $DIC; + + /** + * Get profiles of a user + * + * @param int $a_user_id user id + */ + public static function getProfilesOfUser($a_user_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $profiles = array(); - $set = $ilDB->query("SELECT p.id, p.title FROM skl_profile_user u JOIN skl_profile p ". - " ON (u.profile_id = p.id) ". - " WHERE user_id = ".$ilDB->quote($a_user_id, "integer"). - " ORDER BY p.title ASC" - ); - while ($rec = $ilDB->fetchAssoc($set)) - { - $profiles[] = $rec; - } - return $profiles; - } + $ilDB = $DIC->database(); + + $profiles = array(); + $set = $ilDB->query( + "SELECT p.id, p.title FROM skl_profile_user u JOIN skl_profile p " . + " ON (u.profile_id = p.id) " . + " WHERE user_id = " . $ilDB->quote($a_user_id, "integer") . + " ORDER BY p.title ASC" + ); + while ($rec = $ilDB->fetchAssoc($set)) { + $profiles[] = $rec; + } + return $profiles; + } - /** - * Get assigned users - */ - static function countUsers($a_profile_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT count(*) ucnt FROM skl_profile_user ". - " WHERE profile_id = ".$ilDB->quote($a_profile_id, "integer") - ); - $rec = $ilDB->fetchAssoc($set); - return (int) $rec["ucnt"]; - } - - /** - * Get usage info - * - * @param - * @return - */ - static public function getUsageInfo($a_cskill_ids, &$a_usages) - { - global $DIC; - - $ilDB = $DIC->database(); - - include_once("./Services/Skill/classes/class.ilSkillUsage.php"); - ilSkillUsage::getUsageInfoGeneric($a_cskill_ids, $a_usages, ilSkillUsage::PROFILE, - "skl_profile_level", "profile_id", "base_skill_id"); - } + /** + * Get assigned users + */ + public static function countUsers($a_profile_id) + { + global $DIC; + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT count(*) ucnt FROM skl_profile_user " . + " WHERE profile_id = " . $ilDB->quote($a_profile_id, "integer") + ); + $rec = $ilDB->fetchAssoc($set); + return (int) $rec["ucnt"]; + } + + /** + * Get usage info + * + * @param + * @return + */ + public static function getUsageInfo($a_cskill_ids, &$a_usages) + { + global $DIC; + $ilDB = $DIC->database(); + + include_once("./Services/Skill/classes/class.ilSkillUsage.php"); + ilSkillUsage::getUsageInfoGeneric( + $a_cskill_ids, + $a_usages, + ilSkillUsage::PROFILE, + "skl_profile_level", + "profile_id", + "base_skill_id" + ); + } } - -?> diff --git a/Services/Skill/classes/class.ilSkillProfileGUI.php b/Services/Skill/classes/class.ilSkillProfileGUI.php index 3262e6eb1b1f9e53c46e4eda999a280ff931453c..09f04afb8362def8f5d9697d89eaa9045a85be43 100644 --- a/Services/Skill/classes/class.ilSkillProfileGUI.php +++ b/Services/Skill/classes/class.ilSkillProfileGUI.php @@ -14,786 +14,771 @@ include_once("./Services/Skill/classes/class.ilSkillProfile.php"); */ class ilSkillProfileGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilHelpGUI - */ - protected $help; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - protected $profile = null; - /** - * @var ilAccessHandler - */ - var $access; - /** - * @var int - */ - var $ref_id; - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->tabs = $DIC->tabs(); - $this->tpl = $DIC["tpl"]; - $this->help = $DIC["ilHelp"]; - $this->toolbar = $DIC->toolbar(); - $ilCtrl = $DIC->ctrl(); - $ilAccess = $DIC->access(); - - $ilCtrl->saveParameter($this, "sprof_id"); - $this->access = $ilAccess; - $this->ref_id = (int) $_GET["ref_id"]; - - if ((int) $_GET["sprof_id"] > 0) - { - $this->id = (int) $_GET["sprof_id"]; - } - - if ($this->id > 0) - { - $this->profile = new ilSkillProfile($this->id); - } - } - - /** - * Check permission pool - * - * @param string $a_perm - * @return bool - */ - function checkPermissionBool($a_perm) - { - return $this->access->checkAccess($a_perm, "", $this->ref_id); - } - - /** - * Execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $cmd = $ilCtrl->getCmd("listProfiles"); - $next_class = $ilCtrl->getNextClass(); - switch($next_class) - { - case 'ilrepositorysearchgui': - include_once('./Services/Search/classes/class.ilRepositorySearchGUI.php'); - $user_search = new ilRepositorySearchGUI(); - $user_search->setTitle($lng->txt('skmg_add_user_to_profile')); - $user_search->setCallback($this, 'assignUser'); - - // Set tabs - //$this->tabs_gui->setTabActive('user_assignment'); - $ilCtrl->setReturn($this, 'listUsers'); - $ret = $ilCtrl->forwardCommand($user_search); - break; - - default: - if (in_array($cmd, array("listProfiles", "create", "edit", "save", "update", - "confirmDeleteProfiles", "deleteProfiles", "showLevels", "assignLevel", - "assignLevelSelectSkill", "assignLevelToProfile", - "confirmLevelAssignmentRemoval", "removeLevelAssignments", - "showUsers", "assignUser", - "confirmUserRemoval", "removeUsers", "exportProfiles", "showImportForm", "importProfiles"))) - { - $this->$cmd(); - } - break; - } - } - - /** - * Set tabs - * - * @param - * @return - */ - function setTabs($a_active) - { - $ilTabs = $this->tabs; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $ilHelp = $this->help; - - $tpl->setTitle($lng->txt("skmg_profile").": ". - $this->profile->getTitle()); - $tpl->setDescription(""); - - $ilTabs->clearTargets(); - $ilHelp->setScreenIdComponent("skmg_prof"); - - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTarget($this, "")); - - // users - $ilTabs->addTab("users", - $lng->txt("skmg_assigned_users"), - $ilCtrl->getLinkTarget($this, "showUsers")); - - // levels - $ilTabs->addTab("levels", - $lng->txt("skmg_assigned_skill_levels"), - $ilCtrl->getLinkTarget($this, "showLevels")); - - // settings - $ilTabs->addTab("settings", - $lng->txt("settings"), - $ilCtrl->getLinkTarget($this, "edit")); - - $ilTabs->activateTab($a_active); - } - - - /** - * List profiles - */ - function listProfiles() - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if ($this->checkPermissionBool("write")) - { - $ilToolbar->addButton($lng->txt("skmg_add_profile"), - $ilCtrl->getLinkTarget($this, "create")); - - $ilToolbar->addButton($lng->txt("import"), - $ilCtrl->getLinkTarget($this, "showImportForm")); - } - - include_once("./Services/Skill/classes/class.ilSkillProfileTableGUI.php"); - $tab = new ilSkillProfileTableGUI($this, "listProfiles", $this->checkPermissionBool("write")); - - $tpl->setContent($tab->getHTML()); - } - - /** - * Create - */ - function create() - { - $tpl = $this->tpl; - - $form = $this->initProfileForm("create"); - $tpl->setContent($form->getHTML()); - } - - /** - * Edit - */ - function edit() - { - $tpl = $this->tpl; - - $this->setTabs("settings"); - $form = $this->initProfileForm("edit"); - $tpl->setContent($form->getHTML()); - } - - - /** - * Init profile form. - * - * @param string $a_mode edit mode - */ - public function initProfileForm($a_mode = "edit") - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - - // title - $ti = new ilTextInputGUI($lng->txt("title"), "title"); - $ti->setMaxLength(200); - $ti->setSize(40); - $ti->setRequired(true); - $form->addItem($ti); - - // description - $desc = new ilTextAreaInputGUI($lng->txt("description"), "description"); - $desc->setCols(40); - $desc->setRows(4); - $form->addItem($desc); - - // save and cancel commands - if ($this->checkPermissionBool("write")) - { - if ($a_mode == "create") - { - $form->addCommandButton("save", $lng->txt("save")); - $form->addCommandButton("listProfiles", $lng->txt("cancel")); - $form->setTitle($lng->txt("skmg_add_profile")); - } else - { - // set values - $ti->setValue($this->profile->getTitle()); - $desc->setValue($this->profile->getDescription()); - - $form->addCommandButton("update", $lng->txt("save")); - $form->addCommandButton("listProfiles", $lng->txt("cancel")); - $form->setTitle($lng->txt("skmg_edit_profile")); - } - } - - $form->setFormAction($ilCtrl->getFormAction($this)); - - return $form; - } - - /** - * Save profile form - */ - public function save() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if (!$this->checkPermissionBool("write")) - { - return; - } - - $form = $this->initProfileForm("create"); - if ($form->checkInput()) - { - $prof = new ilSkillProfile(); - $prof->setTitle($form->getInput("title")); - $prof->setDescription($form->getInput("description")); - $prof->create(); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "listProfiles"); - } - else - { - $form->setValuesByPost(); - $tpl->setContent($form->getHtml()); - } - } - - /** - * Update - */ - function update() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - - if (!$this->checkPermissionBool("write")) - { - return; - } - - $form = $this->initProfileForm("edit"); - if ($form->checkInput()) - { - $this->profile->setTitle($form->getInput("title")); - $this->profile->setDescription($form->getInput("description")); - $this->profile->update(); - - ilUtil::sendInfo($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "listProfiles"); - } - else - { - $form->setValuesByPost(); - $tpl->setContent($form->getHtml()); - } - } - - /** - * Confirm profile deletion - */ - function confirmDeleteProfiles() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - if (!is_array($_POST["id"]) || count($_POST["id"]) == 0) - { - ilUtil::sendInfo($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "listProfiles"); - } - else - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("skmg_delete_profiles")); - $cgui->setCancel($lng->txt("cancel"), "listProfiles"); - $cgui->setConfirm($lng->txt("delete"), "deleteProfiles"); - - foreach ($_POST["id"] as $i) - { - $cgui->addItem("id[]", $i, ilSkillProfile::lookupTitle($i)); - } - - $tpl->setContent($cgui->getHTML()); - } - } - - /** - * Delete profiles - */ - function deleteProfiles() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - if (!$this->checkPermissionBool("write")) - { - return; - } - - if (is_array($_POST["id"])) - { - foreach ($_POST["id"] as $i) - { - $prof = new ilSkillProfile($i); - $prof->delete(); - } - ilUtil::sendInfo($lng->txt("msg_obj_modified"), true); - } - - $ilCtrl->redirect($this, "listProfiles"); - } - - //// - //// skill profile levels - //// - - /** - * Show skill levels - * - * @param - * @return - */ - function showLevels() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilToolbar = $this->toolbar; - - $this->setTabs("levels"); - - if ($this->checkPermissionBool("write")) - { - $ilToolbar->addButton($lng->txt("skmg_assign_level"), - $ilCtrl->getLinkTarget($this, "assignLevel") - ); - } - - include_once("./Services/Skill/classes/class.ilSkillProfileLevelsTableGUI.php"); - $tab = new ilSkillProfileLevelsTableGUI($this, "showLevels", $this->profile, - $this->checkPermissionBool("write")); - $tpl->setContent($tab->getHTML()); - } - - /** - * Assign Level - */ - function assignLevel() - { - $lng = $this->lng; - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - - $tpl->setTitle($lng->txt("skmg_profile").": ". - $this->profile->getTitle()); - $tpl->setDescription(""); - - //$this->setTabs("levels"); - - ilUtil::sendInfo($lng->txt("skmg_select_skill_level_assign")); - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTarget($this, "showLevels")); - - include_once("./Services/Skill/classes/class.ilSkillSelectorGUI.php"); - $exp = new ilSkillSelectorGUI($this, "assignLevel", $this, "assignLevelSelectSkill", "cskill_id"); - if (!$exp->handleCommand()) - { - $tpl->setContent($exp->getHTML()); - } - } - - /** - * Output level table for profile assignment - */ - function assignLevelSelectSkill() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - $ilCtrl->saveParameter($this, "cskill_id"); - - $tpl->setTitle($lng->txt("skmg_profile").": ". - $this->profile->getTitle()); - $tpl->setDescription(""); - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTarget($this, "showLevels")); - - include_once("./Services/Skill/classes/class.ilSkillLevelProfileAssignmentTableGUI.php"); - $tab = new ilSkillLevelProfileAssignmentTableGUI($this, "assignLevelSelectSkill", - $_GET["cskill_id"]); - $tpl->setContent($tab->getHTML()); - } - - /** - * Assign level to profile - */ - function assignLevelToProfile() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if (!$this->checkPermissionBool("write")) - { - return; - } - - - $parts = explode(":", $_GET["cskill_id"]); - - $this->profile->addSkillLevel((int) $parts[0], - (int) $parts[1], (int) $_GET["level_id"]); - $this->profile->update(); - - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "showLevels"); - } - - /** - * Confirm level assignment removal - */ - function confirmLevelAssignmentRemoval() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - $this->setTabs("levels"); - - if (!is_array($_POST["ass_id"]) || count($_POST["ass_id"]) == 0) - { - ilUtil::sendInfo($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "showLevels"); - } - else - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("skmg_confirm_remove_level_ass")); - $cgui->setCancel($lng->txt("cancel"), "showLevels"); - $cgui->setConfirm($lng->txt("remove"), "removeLevelAssignments"); - - include_once("./Services/Skill/classes/class.ilBasicSkill.php"); - foreach ($_POST["ass_id"] as $i) - { - $id_arr = explode(":", $i); - $cgui->addItem("ass_id[]", $i, - ilBasicSkill::_lookupTitle($id_arr[0]).": ". - ilBasicSkill::lookupLevelTitle($id_arr[2])); - } - - $tpl->setContent($cgui->getHTML()); - } - } - - /** - * Remove level assignment - * - * @param - * @return - */ - function removeLevelAssignments() - { - $ilCtrl = $this->ctrl; - - if (!$this->checkPermissionBool("write")) - { - return; - } - - if (is_array($_POST["ass_id"])) - { - foreach ($_POST["ass_id"] as $i) - { - $id_arr = explode(":", $i); - $this->profile->removeSkillLevel($id_arr[0], $id_arr[1], $id_arr[2]); - } - $this->profile->update(); - } - - $ilCtrl->redirect($this, "showLevels"); - } - - /** - * Show users - */ - function showUsers() - { - $lng = $this->lng; - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - - // add member - if ($this->checkPermissionBool("write")) - { - include_once './Services/Search/classes/class.ilRepositorySearchGUI.php'; - ilRepositorySearchGUI::fillAutoCompleteToolbar( - $this, - $ilToolbar, - array( - 'auto_complete_name' => $lng->txt('user'), - 'submit_name' => $lng->txt('skmg_assign_user') - ) - ); - } - - $this->setTabs("users"); - - include_once("./Services/Skill/classes/class.ilSkillProfileUserTableGUI.php"); - $tab = new ilSkillProfileUserTableGUI($this, "showUsers", - $this->profile, $this->checkPermissionBool("write")); - $tpl->setContent($tab->getHTML()); - } - - /** - * Assign user - * - * @param - * @return - */ - function assignUser() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if (!$this->checkPermissionBool("write")) - { - return; - } - - $user_id = ilObjUser::_lookupId(ilUtil::stripSlashes($_POST["user_login"])); - if ($user_id > 0) - { - $this->profile->addUserToProfile($user_id); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - } - - $ilCtrl->redirect($this, "showUsers"); - } - - /** - * Confirm user removal - */ - function confirmUserRemoval() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - if (!$this->checkPermissionBool("write")) - { - return; - } - - $this->setTabs("users"); - - if (!is_array($_POST["id"]) || count($_POST["id"]) == 0) - { - ilUtil::sendInfo($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "showUsers"); - } - else - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("skmg_confirm_user_removal")); - $cgui->setCancel($lng->txt("cancel"), "showUsers"); - $cgui->setConfirm($lng->txt("remove"), "removeUsers"); - - foreach ($_POST["id"] as $i) - { - $name = ilObjUser::_lookupName($i); - $cgui->addItem("id[]", $i, - $name["lastname"].", ".$name["firstname"]. - " [".$name["login"]."]"); - } - - $tpl->setContent($cgui->getHTML()); - } - } - - /** - * Remove users - */ - function removeUsers() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if (!$this->checkPermissionBool("write")) - { - return; - } - - if (is_array($_POST["id"])) - { - foreach ($_POST["id"] as $i) - { - $this->profile->removeUserFromProfile((int) $i); - } - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - } - $ilCtrl->redirect($this, "showUsers"); - } - - /** - * Export profiles - * - * @param - * @return - */ - function exportProfiles() - { - $ilCtrl = $this->ctrl; - - if (!is_array($_POST["id"]) || count($_POST["id"]) == 0) - { - $ilCtrl->redirect($this, ""); - } - - include_once("./Services/Export/classes/class.ilExport.php"); - $exp = new ilExport(); - $conf = $exp->getConfig("Services/Skill"); - $conf->setMode(ilSkillExportConfig::MODE_PROFILES); - $conf->setSelectedProfiles($_POST["id"]); - $exp->exportObject("skmg", ilObject::_lookupObjId((int) $_GET["ref_id"])); - - //ilExport::_createExportDirectory(0, "xml", ""); - //$export_dir = ilExport::_getExportDirectory($a_id, "xml", $a_type); - //$exp->exportEntity("skprof", $_POST["id"], "", "Services/Skill", $a_title, $a_export_dir, "skprof"); - - $ilCtrl->redirectByClass(array("iladministrationgui", "ilobjskillmanagementgui", "ilexportgui"), ""); - } - - /** - * Show import form - */ - function showImportForm() - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - $tpl->setContent($this->initInputForm()->getHTML()); - } - - /** - * Init input form. - */ - public function initInputForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - - include_once("./Services/Form/classes/class.ilFileInputGUI.php"); - $fi = new ilFileInputGUI($lng->txt("skmg_input_file"), "import_file"); - $fi->setSuffixes(array("zip")); - $fi->setRequired(true); - $form->addItem($fi); - - // save and cancel commands - $form->addCommandButton("importProfiles", $lng->txt("import")); - $form->addCommandButton("", $lng->txt("cancel")); - - $form->setTitle($lng->txt("import")); - $form->setFormAction($ilCtrl->getFormAction($this)); - - return $form; - } - - /** - * Import profiles - */ - public function importProfiles() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - $form = $this->initInputForm(); - if ($form->checkInput()) - { - include_once("./Services/Export/classes/class.ilImport.php"); - $imp = new ilImport(); - $imp->importEntity($_FILES["import_file"]["tmp_name"], $_FILES["import_file"]["name"], "skmg", "Services/Skill"); - - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, ""); - } - else - { - $form->setValuesByPost(); - $tpl->setContent($form->getHtml()); - } - } - - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + protected $profile = null; + /** + * @var ilAccessHandler + */ + public $access; + /** + * @var int + */ + public $ref_id; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->tabs = $DIC->tabs(); + $this->tpl = $DIC["tpl"]; + $this->help = $DIC["ilHelp"]; + $this->toolbar = $DIC->toolbar(); + $ilCtrl = $DIC->ctrl(); + $ilAccess = $DIC->access(); + + $ilCtrl->saveParameter($this, "sprof_id"); + $this->access = $ilAccess; + $this->ref_id = (int) $_GET["ref_id"]; + + if ((int) $_GET["sprof_id"] > 0) { + $this->id = (int) $_GET["sprof_id"]; + } + + if ($this->id > 0) { + $this->profile = new ilSkillProfile($this->id); + } + } + + /** + * Check permission pool + * + * @param string $a_perm + * @return bool + */ + public function checkPermissionBool($a_perm) + { + return $this->access->checkAccess($a_perm, "", $this->ref_id); + } + + /** + * Execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $cmd = $ilCtrl->getCmd("listProfiles"); + $next_class = $ilCtrl->getNextClass(); + switch ($next_class) { + case 'ilrepositorysearchgui': + include_once('./Services/Search/classes/class.ilRepositorySearchGUI.php'); + $user_search = new ilRepositorySearchGUI(); + $user_search->setTitle($lng->txt('skmg_add_user_to_profile')); + $user_search->setCallback($this, 'assignUser'); + + // Set tabs + //$this->tabs_gui->setTabActive('user_assignment'); + $ilCtrl->setReturn($this, 'listUsers'); + $ret = $ilCtrl->forwardCommand($user_search); + break; + + default: + if (in_array($cmd, array("listProfiles", "create", "edit", "save", "update", + "confirmDeleteProfiles", "deleteProfiles", "showLevels", "assignLevel", + "assignLevelSelectSkill", "assignLevelToProfile", + "confirmLevelAssignmentRemoval", "removeLevelAssignments", + "showUsers", "assignUser", + "confirmUserRemoval", "removeUsers", "exportProfiles", "showImportForm", "importProfiles"))) { + $this->$cmd(); + } + break; + } + } + + /** + * Set tabs + * + * @param + * @return + */ + public function setTabs($a_active) + { + $ilTabs = $this->tabs; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $ilHelp = $this->help; + + $tpl->setTitle($lng->txt("skmg_profile") . ": " . + $this->profile->getTitle()); + $tpl->setDescription(""); + + $ilTabs->clearTargets(); + $ilHelp->setScreenIdComponent("skmg_prof"); + + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, "") + ); + + // users + $ilTabs->addTab( + "users", + $lng->txt("skmg_assigned_users"), + $ilCtrl->getLinkTarget($this, "showUsers") + ); + + // levels + $ilTabs->addTab( + "levels", + $lng->txt("skmg_assigned_skill_levels"), + $ilCtrl->getLinkTarget($this, "showLevels") + ); + + // settings + $ilTabs->addTab( + "settings", + $lng->txt("settings"), + $ilCtrl->getLinkTarget($this, "edit") + ); + + $ilTabs->activateTab($a_active); + } + + + /** + * List profiles + */ + public function listProfiles() + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if ($this->checkPermissionBool("write")) { + $ilToolbar->addButton( + $lng->txt("skmg_add_profile"), + $ilCtrl->getLinkTarget($this, "create") + ); + + $ilToolbar->addButton( + $lng->txt("import"), + $ilCtrl->getLinkTarget($this, "showImportForm") + ); + } + + include_once("./Services/Skill/classes/class.ilSkillProfileTableGUI.php"); + $tab = new ilSkillProfileTableGUI($this, "listProfiles", $this->checkPermissionBool("write")); + + $tpl->setContent($tab->getHTML()); + } + + /** + * Create + */ + public function create() + { + $tpl = $this->tpl; + + $form = $this->initProfileForm("create"); + $tpl->setContent($form->getHTML()); + } + + /** + * Edit + */ + public function edit() + { + $tpl = $this->tpl; + + $this->setTabs("settings"); + $form = $this->initProfileForm("edit"); + $tpl->setContent($form->getHTML()); + } + + + /** + * Init profile form. + * + * @param string $a_mode edit mode + */ + public function initProfileForm($a_mode = "edit") + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + + // title + $ti = new ilTextInputGUI($lng->txt("title"), "title"); + $ti->setMaxLength(200); + $ti->setSize(40); + $ti->setRequired(true); + $form->addItem($ti); + + // description + $desc = new ilTextAreaInputGUI($lng->txt("description"), "description"); + $desc->setCols(40); + $desc->setRows(4); + $form->addItem($desc); + + // save and cancel commands + if ($this->checkPermissionBool("write")) { + if ($a_mode == "create") { + $form->addCommandButton("save", $lng->txt("save")); + $form->addCommandButton("listProfiles", $lng->txt("cancel")); + $form->setTitle($lng->txt("skmg_add_profile")); + } else { + // set values + $ti->setValue($this->profile->getTitle()); + $desc->setValue($this->profile->getDescription()); + + $form->addCommandButton("update", $lng->txt("save")); + $form->addCommandButton("listProfiles", $lng->txt("cancel")); + $form->setTitle($lng->txt("skmg_edit_profile")); + } + } + + $form->setFormAction($ilCtrl->getFormAction($this)); + + return $form; + } + + /** + * Save profile form + */ + public function save() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if (!$this->checkPermissionBool("write")) { + return; + } + + $form = $this->initProfileForm("create"); + if ($form->checkInput()) { + $prof = new ilSkillProfile(); + $prof->setTitle($form->getInput("title")); + $prof->setDescription($form->getInput("description")); + $prof->create(); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "listProfiles"); + } else { + $form->setValuesByPost(); + $tpl->setContent($form->getHtml()); + } + } + + /** + * Update + */ + public function update() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + + if (!$this->checkPermissionBool("write")) { + return; + } + + $form = $this->initProfileForm("edit"); + if ($form->checkInput()) { + $this->profile->setTitle($form->getInput("title")); + $this->profile->setDescription($form->getInput("description")); + $this->profile->update(); + + ilUtil::sendInfo($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "listProfiles"); + } else { + $form->setValuesByPost(); + $tpl->setContent($form->getHtml()); + } + } + + /** + * Confirm profile deletion + */ + public function confirmDeleteProfiles() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + if (!is_array($_POST["id"]) || count($_POST["id"]) == 0) { + ilUtil::sendInfo($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "listProfiles"); + } else { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("skmg_delete_profiles")); + $cgui->setCancel($lng->txt("cancel"), "listProfiles"); + $cgui->setConfirm($lng->txt("delete"), "deleteProfiles"); + + foreach ($_POST["id"] as $i) { + $cgui->addItem("id[]", $i, ilSkillProfile::lookupTitle($i)); + } + + $tpl->setContent($cgui->getHTML()); + } + } + + /** + * Delete profiles + */ + public function deleteProfiles() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + if (!$this->checkPermissionBool("write")) { + return; + } + + if (is_array($_POST["id"])) { + foreach ($_POST["id"] as $i) { + $prof = new ilSkillProfile($i); + $prof->delete(); + } + ilUtil::sendInfo($lng->txt("msg_obj_modified"), true); + } + + $ilCtrl->redirect($this, "listProfiles"); + } + + //// + //// skill profile levels + //// + + /** + * Show skill levels + * + * @param + * @return + */ + public function showLevels() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilToolbar = $this->toolbar; + + $this->setTabs("levels"); + + if ($this->checkPermissionBool("write")) { + $ilToolbar->addButton( + $lng->txt("skmg_assign_level"), + $ilCtrl->getLinkTarget($this, "assignLevel") + ); + } + + include_once("./Services/Skill/classes/class.ilSkillProfileLevelsTableGUI.php"); + $tab = new ilSkillProfileLevelsTableGUI( + $this, + "showLevels", + $this->profile, + $this->checkPermissionBool("write") + ); + $tpl->setContent($tab->getHTML()); + } + + /** + * Assign Level + */ + public function assignLevel() + { + $lng = $this->lng; + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + + $tpl->setTitle($lng->txt("skmg_profile") . ": " . + $this->profile->getTitle()); + $tpl->setDescription(""); + + //$this->setTabs("levels"); + + ilUtil::sendInfo($lng->txt("skmg_select_skill_level_assign")); + + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, "showLevels") + ); + + include_once("./Services/Skill/classes/class.ilSkillSelectorGUI.php"); + $exp = new ilSkillSelectorGUI($this, "assignLevel", $this, "assignLevelSelectSkill", "cskill_id"); + if (!$exp->handleCommand()) { + $tpl->setContent($exp->getHTML()); + } + } + + /** + * Output level table for profile assignment + */ + public function assignLevelSelectSkill() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + $ilCtrl->saveParameter($this, "cskill_id"); + + $tpl->setTitle($lng->txt("skmg_profile") . ": " . + $this->profile->getTitle()); + $tpl->setDescription(""); + + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, "showLevels") + ); + + include_once("./Services/Skill/classes/class.ilSkillLevelProfileAssignmentTableGUI.php"); + $tab = new ilSkillLevelProfileAssignmentTableGUI( + $this, + "assignLevelSelectSkill", + $_GET["cskill_id"] + ); + $tpl->setContent($tab->getHTML()); + } + + /** + * Assign level to profile + */ + public function assignLevelToProfile() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if (!$this->checkPermissionBool("write")) { + return; + } + + + $parts = explode(":", $_GET["cskill_id"]); + + $this->profile->addSkillLevel( + (int) $parts[0], + (int) $parts[1], + (int) $_GET["level_id"] + ); + $this->profile->update(); + + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "showLevels"); + } + + /** + * Confirm level assignment removal + */ + public function confirmLevelAssignmentRemoval() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + $this->setTabs("levels"); + + if (!is_array($_POST["ass_id"]) || count($_POST["ass_id"]) == 0) { + ilUtil::sendInfo($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "showLevels"); + } else { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("skmg_confirm_remove_level_ass")); + $cgui->setCancel($lng->txt("cancel"), "showLevels"); + $cgui->setConfirm($lng->txt("remove"), "removeLevelAssignments"); + + include_once("./Services/Skill/classes/class.ilBasicSkill.php"); + foreach ($_POST["ass_id"] as $i) { + $id_arr = explode(":", $i); + $cgui->addItem( + "ass_id[]", + $i, + ilBasicSkill::_lookupTitle($id_arr[0]) . ": " . + ilBasicSkill::lookupLevelTitle($id_arr[2]) + ); + } + + $tpl->setContent($cgui->getHTML()); + } + } + + /** + * Remove level assignment + * + * @param + * @return + */ + public function removeLevelAssignments() + { + $ilCtrl = $this->ctrl; + + if (!$this->checkPermissionBool("write")) { + return; + } + + if (is_array($_POST["ass_id"])) { + foreach ($_POST["ass_id"] as $i) { + $id_arr = explode(":", $i); + $this->profile->removeSkillLevel($id_arr[0], $id_arr[1], $id_arr[2]); + } + $this->profile->update(); + } + + $ilCtrl->redirect($this, "showLevels"); + } + + /** + * Show users + */ + public function showUsers() + { + $lng = $this->lng; + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + + // add member + if ($this->checkPermissionBool("write")) { + include_once './Services/Search/classes/class.ilRepositorySearchGUI.php'; + ilRepositorySearchGUI::fillAutoCompleteToolbar( + $this, + $ilToolbar, + array( + 'auto_complete_name' => $lng->txt('user'), + 'submit_name' => $lng->txt('skmg_assign_user') + ) + ); + } + + $this->setTabs("users"); + + include_once("./Services/Skill/classes/class.ilSkillProfileUserTableGUI.php"); + $tab = new ilSkillProfileUserTableGUI( + $this, + "showUsers", + $this->profile, + $this->checkPermissionBool("write") + ); + $tpl->setContent($tab->getHTML()); + } + + /** + * Assign user + * + * @param + * @return + */ + public function assignUser() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if (!$this->checkPermissionBool("write")) { + return; + } + + $user_id = ilObjUser::_lookupId(ilUtil::stripSlashes($_POST["user_login"])); + if ($user_id > 0) { + $this->profile->addUserToProfile($user_id); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + } + + $ilCtrl->redirect($this, "showUsers"); + } + + /** + * Confirm user removal + */ + public function confirmUserRemoval() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + if (!$this->checkPermissionBool("write")) { + return; + } + + $this->setTabs("users"); + + if (!is_array($_POST["id"]) || count($_POST["id"]) == 0) { + ilUtil::sendInfo($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "showUsers"); + } else { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("skmg_confirm_user_removal")); + $cgui->setCancel($lng->txt("cancel"), "showUsers"); + $cgui->setConfirm($lng->txt("remove"), "removeUsers"); + + foreach ($_POST["id"] as $i) { + $name = ilObjUser::_lookupName($i); + $cgui->addItem( + "id[]", + $i, + $name["lastname"] . ", " . $name["firstname"] . + " [" . $name["login"] . "]" + ); + } + + $tpl->setContent($cgui->getHTML()); + } + } + + /** + * Remove users + */ + public function removeUsers() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if (!$this->checkPermissionBool("write")) { + return; + } + + if (is_array($_POST["id"])) { + foreach ($_POST["id"] as $i) { + $this->profile->removeUserFromProfile((int) $i); + } + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + } + $ilCtrl->redirect($this, "showUsers"); + } + + /** + * Export profiles + * + * @param + * @return + */ + public function exportProfiles() + { + $ilCtrl = $this->ctrl; + + if (!is_array($_POST["id"]) || count($_POST["id"]) == 0) { + $ilCtrl->redirect($this, ""); + } + + include_once("./Services/Export/classes/class.ilExport.php"); + $exp = new ilExport(); + $conf = $exp->getConfig("Services/Skill"); + $conf->setMode(ilSkillExportConfig::MODE_PROFILES); + $conf->setSelectedProfiles($_POST["id"]); + $exp->exportObject("skmg", ilObject::_lookupObjId((int) $_GET["ref_id"])); + + //ilExport::_createExportDirectory(0, "xml", ""); + //$export_dir = ilExport::_getExportDirectory($a_id, "xml", $a_type); + //$exp->exportEntity("skprof", $_POST["id"], "", "Services/Skill", $a_title, $a_export_dir, "skprof"); + + $ilCtrl->redirectByClass(array("iladministrationgui", "ilobjskillmanagementgui", "ilexportgui"), ""); + } + + /** + * Show import form + */ + public function showImportForm() + { + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + $tpl->setContent($this->initInputForm()->getHTML()); + } + + /** + * Init input form. + */ + public function initInputForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + + include_once("./Services/Form/classes/class.ilFileInputGUI.php"); + $fi = new ilFileInputGUI($lng->txt("skmg_input_file"), "import_file"); + $fi->setSuffixes(array("zip")); + $fi->setRequired(true); + $form->addItem($fi); + + // save and cancel commands + $form->addCommandButton("importProfiles", $lng->txt("import")); + $form->addCommandButton("", $lng->txt("cancel")); + + $form->setTitle($lng->txt("import")); + $form->setFormAction($ilCtrl->getFormAction($this)); + + return $form; + } + + /** + * Import profiles + */ + public function importProfiles() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + $form = $this->initInputForm(); + if ($form->checkInput()) { + include_once("./Services/Export/classes/class.ilImport.php"); + $imp = new ilImport(); + $imp->importEntity($_FILES["import_file"]["tmp_name"], $_FILES["import_file"]["name"], "skmg", "Services/Skill"); + + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, ""); + } else { + $form->setValuesByPost(); + $tpl->setContent($form->getHtml()); + } + } } - -?> diff --git a/Services/Skill/classes/class.ilSkillProfileLevelsTableGUI.php b/Services/Skill/classes/class.ilSkillProfileLevelsTableGUI.php index 188297384f154c8411640584ebd9268db78fcee8..3af9de1a031749e5bda6ef6b30131305fa524fc5 100644 --- a/Services/Skill/classes/class.ilSkillProfileLevelsTableGUI.php +++ b/Services/Skill/classes/class.ilSkillProfileLevelsTableGUI.php @@ -11,81 +11,82 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); * @version $Id$ * * @ingroup Services/Skill - */ + */ class ilSkillProfileLevelsTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_profile, $a_write_permission = false) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_profile, $a_write_permission = 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(); - - include_once("./Services/Skill/classes/class.ilBasicSkill.php"); - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $this->tree = new ilSkillTree(); - - $this->profile = $a_profile; - parent::__construct($a_parent_obj, $a_parent_cmd); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilAccess = $DIC->access(); + $lng = $DIC->language(); + + include_once("./Services/Skill/classes/class.ilBasicSkill.php"); + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $this->tree = new ilSkillTree(); + + $this->profile = $a_profile; + parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setData($this->profile->getSkillLevels()); - $this->setTitle($lng->txt("skmg_skill_levels")); - - $this->addColumn("", "", "1", true); - $this->addColumn($this->lng->txt("skmg_skill")); - $this->addColumn($this->lng->txt("skmg_level")); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.skill_profile_level_row.html", "Services/Skill"); - - if ($a_write_permission) - { - $this->addMultiCommand("confirmLevelAssignmentRemoval", $lng->txt("skmg_remove_levels")); - } - //$this->addCommandButton("", $lng->txt("")); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $path = $this->tree->getSkillTreePath($a_set["base_skill_id"], - $a_set["tref_id"]); - $path_items = array(); - foreach ($path as $p) - { - if ($p["type"] != "skrt") - { - $path_items[] = $p["title"]; - } - } - $this->tpl->setVariable("SKILL_TITLE", - implode($path_items, " > ")); - - $this->tpl->setVariable("LEVEL_TITLE", ilBasicSkill::lookupLevelTitle($a_set["level_id"])); - - $this->tpl->setVariable("ID", - ((int) $a_set["base_skill_id"]).":".((int) $a_set["tref_id"]).":".((int) $a_set["level_id"])); - } + $this->setData($this->profile->getSkillLevels()); + $this->setTitle($lng->txt("skmg_skill_levels")); + + $this->addColumn("", "", "1", true); + $this->addColumn($this->lng->txt("skmg_skill")); + $this->addColumn($this->lng->txt("skmg_level")); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.skill_profile_level_row.html", "Services/Skill"); + if ($a_write_permission) { + $this->addMultiCommand("confirmLevelAssignmentRemoval", $lng->txt("skmg_remove_levels")); + } + //$this->addCommandButton("", $lng->txt("")); + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $path = $this->tree->getSkillTreePath( + $a_set["base_skill_id"], + $a_set["tref_id"] + ); + $path_items = array(); + foreach ($path as $p) { + if ($p["type"] != "skrt") { + $path_items[] = $p["title"]; + } + } + $this->tpl->setVariable( + "SKILL_TITLE", + implode($path_items, " > ") + ); + + $this->tpl->setVariable("LEVEL_TITLE", ilBasicSkill::lookupLevelTitle($a_set["level_id"])); + + $this->tpl->setVariable( + "ID", + ((int) $a_set["base_skill_id"]) . ":" . ((int) $a_set["tref_id"]) . ":" . ((int) $a_set["level_id"]) + ); + } } -?> diff --git a/Services/Skill/classes/class.ilSkillProfileTableGUI.php b/Services/Skill/classes/class.ilSkillProfileTableGUI.php index 229eff93858a786c61d118b4274b1c72a2bbe26a..63688522d4178e52634327c67b4a47529983214e 100644 --- a/Services/Skill/classes/class.ilSkillProfileTableGUI.php +++ b/Services/Skill/classes/class.ilSkillProfileTableGUI.php @@ -14,82 +14,79 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilSkillProfileTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_write_permission = false) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_write_permission = 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->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); - $this->setData($this->getProfiles()); - $this->setTitle($lng->txt("skmg_skill_profiles")); + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setData($this->getProfiles()); + $this->setTitle($lng->txt("skmg_skill_profiles")); - $this->addColumn("", "", "1px", true); - $this->addColumn($this->lng->txt("title"), "title"); - $this->addColumn($this->lng->txt("users")); - $this->addColumn($this->lng->txt("actions")); + $this->addColumn("", "", "1px", true); + $this->addColumn($this->lng->txt("title"), "title"); + $this->addColumn($this->lng->txt("users")); + $this->addColumn($this->lng->txt("actions")); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.skill_profile_row.html", "Services/Skill"); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.skill_profile_row.html", "Services/Skill"); - $this->addMultiCommand("exportProfiles", $lng->txt("export")); - if ($a_write_permission) - { - $this->addMultiCommand("confirmDeleteProfiles", $lng->txt("delete")); - } - //$this->addCommandButton("", $lng->txt("")); - } - - /** - * Get profiles - * - * @return array array of skill profiles - */ - function getProfiles() - { - include_once("./Services/Skill/classes/class.ilSkillProfile.php"); - return ilSkillProfile::getProfiles(); - } - - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->tpl->setCurrentBlock("cmd"); - $this->tpl->setVariable("CMD", $lng->txt("edit")); - $ilCtrl->setParameter($this->parent_obj, "sprof_id", $a_set["id"]); - $this->tpl->setVariable("CMD_HREF", $ilCtrl->getLinkTarget($this->parent_obj, "showUsers")); - $ilCtrl->setParameter($this->parent_obj, "sprof_id", $_GET["sprof_id"]); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setVariable("ID", $a_set["id"]); - $this->tpl->setVariable("TITLE", $a_set["title"]); - $this->tpl->setVariable("NUM_USERS", ilSkillProfile::countUsers($a_set["id"])); - } + $this->addMultiCommand("exportProfiles", $lng->txt("export")); + if ($a_write_permission) { + $this->addMultiCommand("confirmDeleteProfiles", $lng->txt("delete")); + } + //$this->addCommandButton("", $lng->txt("")); + } + + /** + * Get profiles + * + * @return array array of skill profiles + */ + public function getProfiles() + { + include_once("./Services/Skill/classes/class.ilSkillProfile.php"); + return ilSkillProfile::getProfiles(); + } + + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $this->tpl->setCurrentBlock("cmd"); + $this->tpl->setVariable("CMD", $lng->txt("edit")); + $ilCtrl->setParameter($this->parent_obj, "sprof_id", $a_set["id"]); + $this->tpl->setVariable("CMD_HREF", $ilCtrl->getLinkTarget($this->parent_obj, "showUsers")); + $ilCtrl->setParameter($this->parent_obj, "sprof_id", $_GET["sprof_id"]); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setVariable("ID", $a_set["id"]); + $this->tpl->setVariable("TITLE", $a_set["title"]); + $this->tpl->setVariable("NUM_USERS", ilSkillProfile::countUsers($a_set["id"])); + } } -?> diff --git a/Services/Skill/classes/class.ilSkillProfileUserTableGUI.php b/Services/Skill/classes/class.ilSkillProfileUserTableGUI.php index 563f780f9fbb50b798abb1b19e13dfe98ce4973c..fca4e908e23cc82df3225b2053fac0e3442cfe7c 100644 --- a/Services/Skill/classes/class.ilSkillProfileUserTableGUI.php +++ b/Services/Skill/classes/class.ilSkillProfileUserTableGUI.php @@ -14,64 +14,61 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilSkillProfileUserTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_profile, $a_write_permission = false) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_profile, $a_write_permission = 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->profile = $a_profile; - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setData($this->profile->getAssignedUsers()); - $this->setTitle($lng->txt("skmg_assigned_users")); - - $this->addColumn("", "", "1px", true); - $this->addColumn($this->lng->txt("lastname"), "lastname"); - $this->addColumn($this->lng->txt("firstname"), "firstname"); - $this->addColumn($this->lng->txt("login"), "login"); -// $this->addColumn($this->lng->txt("actions")); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.profile_user_row.html", "Services/Skill"); + $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->profile = $a_profile; + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setData($this->profile->getAssignedUsers()); + $this->setTitle($lng->txt("skmg_assigned_users")); + + $this->addColumn("", "", "1px", true); + $this->addColumn($this->lng->txt("lastname"), "lastname"); + $this->addColumn($this->lng->txt("firstname"), "firstname"); + $this->addColumn($this->lng->txt("login"), "login"); + // $this->addColumn($this->lng->txt("actions")); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.profile_user_row.html", "Services/Skill"); - if ($a_write_permission) - { - $this->addMultiCommand("confirmUserRemoval", $lng->txt("remove")); - } - //$this->addCommandButton("", $lng->txt("")); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - - $this->tpl->setVariable("LASTNAME", $a_set["lastname"]); - $this->tpl->setVariable("FIRSTNAME", $a_set["firstname"]); - $this->tpl->setVariable("LOGIN", $a_set["login"]); - $this->tpl->setVariable("ID", $a_set["id"]); - } + if ($a_write_permission) { + $this->addMultiCommand("confirmUserRemoval", $lng->txt("remove")); + } + //$this->addCommandButton("", $lng->txt("")); + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $this->tpl->setVariable("LASTNAME", $a_set["lastname"]); + $this->tpl->setVariable("FIRSTNAME", $a_set["firstname"]); + $this->tpl->setVariable("LOGIN", $a_set["login"]); + $this->tpl->setVariable("ID", $a_set["id"]); + } } -?> diff --git a/Services/Skill/classes/class.ilSkillResources.php b/Services/Skill/classes/class.ilSkillResources.php index 58ff7d47446bfd0e98fd461d1d45b635bc72f529..c8b95972b94dbf69125e55a55f7283a006123bd9 100644 --- a/Services/Skill/classes/class.ilSkillResources.php +++ b/Services/Skill/classes/class.ilSkillResources.php @@ -20,264 +20,257 @@ include_once("./Services/Skill/interfaces/interface.ilSkillUsageInfo.php"); */ class ilSkillResources implements ilSkillUsageInfo { - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; - /** - * @var ilTree - */ - protected $tree; + /** + * @var ilTree + */ + protected $tree; - protected $base_skill_id; // base skill id - protected $tref_id; // template reference id (if no template involved: 0) - - // The resources array has the following keys (int) - // first dimension is "level_id" (int): the skill level id - // second dimension is "rep_ref_id" (int): the ref id of the repository resource - // - // The values of the array are associatives arrays with the following key value pairs: - // level_id (int): the skill level id - // rep_ref_id (int): the ref id of the repository resource - // trigger: 1, if the resource triggers the skill level (0 otherwise) - // imparting: 1, if the resource imparts knowledge of the skill level (0 otherwise) - protected $resources = array(); - - /** - * Constructor - * - * @param int $a_skill_id base skill id - * @param int $a_tref_id template reference id (0, if no template is involved) - */ - function __construct($a_skill_id = 0, $a_tref_id = 0) - { - global $DIC; + protected $base_skill_id; // base skill id + protected $tref_id; // template reference id (if no template involved: 0) + + // The resources array has the following keys (int) + // first dimension is "level_id" (int): the skill level id + // second dimension is "rep_ref_id" (int): the ref id of the repository resource + // + // The values of the array are associatives arrays with the following key value pairs: + // level_id (int): the skill level id + // rep_ref_id (int): the ref id of the repository resource + // trigger: 1, if the resource triggers the skill level (0 otherwise) + // imparting: 1, if the resource imparts knowledge of the skill level (0 otherwise) + protected $resources = array(); + + /** + * Constructor + * + * @param int $a_skill_id base skill id + * @param int $a_tref_id template reference id (0, if no template is involved) + */ + public function __construct($a_skill_id = 0, $a_tref_id = 0) + { + global $DIC; - $this->db = $DIC->database(); - $this->tree = $DIC->repositoryTree(); - $this->setBaseSkillId($a_skill_id); - $this->setTemplateRefId($a_tref_id); - - if ($a_skill_id > 0) - { - $this->readResources(); - } - } - - /** - * Set base skill id - * - * @param int $a_val base skill id - */ - function setBaseSkillId($a_val) - { - $this->base_skill_id = (int) $a_val; - } - - /** - * Get base skill id - * - * @return int base skill id - */ - function getBaseSkillId() - { - return $this->base_skill_id; - } - - /** - * Set template reference id - * - * @param int $a_val template reference id - */ - function setTemplateRefId($a_val) - { - $this->tref_id = (int) $a_val; - } - - /** - * Get template reference id - * - * @return int template reference id - */ - function getTemplateRefId() - { - return $this->tref_id; - } - - /** - * Read resources - * - * @param - * @return - */ - function readResources() - { - $ilDB = $this->db; - $tree = $this->tree; - - $set = $ilDB->query("SELECT * FROM skl_skill_resource ". - " WHERE base_skill_id = ".$ilDB->quote($this->getBaseSkillId(), "integer"). - " AND tref_id = ".$ilDB->quote($this->getTemplateRefId(), "integer") - ); - while ($rec = $ilDB->fetchAssoc($set)) - { - if ($tree->isInTree($rec["rep_ref_id"])) - { - $this->resources[$rec["level_id"]][$rec["rep_ref_id"]] = array( - "level_id" => $rec["level_id"], - "rep_ref_id" => $rec["rep_ref_id"], - "trigger" => $rec["ltrigger"], - "imparting" => $rec["imparting"] - ); - } - } - } - - /** - * Save resources - */ - function save() - { - $ilDB = $this->db; - - $ilDB->manipulate("DELETE FROM skl_skill_resource WHERE ". - " base_skill_id = ".$ilDB->quote((int) $this->getBaseSkillId(), "integer"). - " AND tref_id = ".$ilDB->quote((int) $this->getTemplateRefId(), "integer") - ); - foreach ($this->getResources() as $level_id => $l) - { - foreach ($l as $ref_id => $r) - { - if ($r["imparting"] || $r["trigger"]) - { - $ilDB->manipulate("INSERT INTO skl_skill_resource ". - "(base_skill_id, tref_id, level_id, rep_ref_id, imparting, ltrigger) VALUES (". - $ilDB->quote((int) $this->getBaseSkillId(), "integer").",". - $ilDB->quote((int) $this->getTemplateRefId(), "integer").",". - $ilDB->quote((int) $level_id, "integer").",". - $ilDB->quote((int) $ref_id, "integer").",". - $ilDB->quote((int) $r["imparting"], "integer").",". - $ilDB->quote((int) $r["trigger"], "integer"). - ")"); - } - } - } - } - - /** - * Get resources - * - * @return - */ - function getResources() - { - return $this->resources; - } - - /** - * Get resoures for level id - * - * @param int $a_level_id level id - * @return array array of resources - */ - function getResourcesOfLevel($a_level_id) - { - $ret = (is_array($this->resources[$a_level_id])) - ? $this->resources[$a_level_id] - : array(); - - return $ret; - } - - /** - * Set resource as trigger - * - * @param int $a_level_id level id - * @param int $a_rep_ref_id repository resource ref id - * @param bool $a_trigger trigger true/false - */ - function setResourceAsTrigger($a_level_id, $a_rep_ref_id, $a_trigger = true) - { - if (!is_array($this->resources[$a_level_id])) - { - $this->resources[$a_level_id] = array(); - } - if (!is_array($this->resources[$a_level_id][$a_rep_ref_id])) - { - $this->resources[$a_level_id][$a_rep_ref_id] = array(); - } - - $this->resources[$a_level_id][$a_rep_ref_id]["trigger"] = $a_trigger; - } + $this->db = $DIC->database(); + $this->tree = $DIC->repositoryTree(); + $this->setBaseSkillId($a_skill_id); + $this->setTemplateRefId($a_tref_id); + + if ($a_skill_id > 0) { + $this->readResources(); + } + } + + /** + * Set base skill id + * + * @param int $a_val base skill id + */ + public function setBaseSkillId($a_val) + { + $this->base_skill_id = (int) $a_val; + } + + /** + * Get base skill id + * + * @return int base skill id + */ + public function getBaseSkillId() + { + return $this->base_skill_id; + } + + /** + * Set template reference id + * + * @param int $a_val template reference id + */ + public function setTemplateRefId($a_val) + { + $this->tref_id = (int) $a_val; + } + + /** + * Get template reference id + * + * @return int template reference id + */ + public function getTemplateRefId() + { + return $this->tref_id; + } + + /** + * Read resources + * + * @param + * @return + */ + public function readResources() + { + $ilDB = $this->db; + $tree = $this->tree; + + $set = $ilDB->query( + "SELECT * FROM skl_skill_resource " . + " WHERE base_skill_id = " . $ilDB->quote($this->getBaseSkillId(), "integer") . + " AND tref_id = " . $ilDB->quote($this->getTemplateRefId(), "integer") + ); + while ($rec = $ilDB->fetchAssoc($set)) { + if ($tree->isInTree($rec["rep_ref_id"])) { + $this->resources[$rec["level_id"]][$rec["rep_ref_id"]] = array( + "level_id" => $rec["level_id"], + "rep_ref_id" => $rec["rep_ref_id"], + "trigger" => $rec["ltrigger"], + "imparting" => $rec["imparting"] + ); + } + } + } + + /** + * Save resources + */ + public function save() + { + $ilDB = $this->db; + + $ilDB->manipulate( + "DELETE FROM skl_skill_resource WHERE " . + " base_skill_id = " . $ilDB->quote((int) $this->getBaseSkillId(), "integer") . + " AND tref_id = " . $ilDB->quote((int) $this->getTemplateRefId(), "integer") + ); + foreach ($this->getResources() as $level_id => $l) { + foreach ($l as $ref_id => $r) { + if ($r["imparting"] || $r["trigger"]) { + $ilDB->manipulate("INSERT INTO skl_skill_resource " . + "(base_skill_id, tref_id, level_id, rep_ref_id, imparting, ltrigger) VALUES (" . + $ilDB->quote((int) $this->getBaseSkillId(), "integer") . "," . + $ilDB->quote((int) $this->getTemplateRefId(), "integer") . "," . + $ilDB->quote((int) $level_id, "integer") . "," . + $ilDB->quote((int) $ref_id, "integer") . "," . + $ilDB->quote((int) $r["imparting"], "integer") . "," . + $ilDB->quote((int) $r["trigger"], "integer") . + ")"); + } + } + } + } + + /** + * Get resources + * + * @return + */ + public function getResources() + { + return $this->resources; + } + + /** + * Get resoures for level id + * + * @param int $a_level_id level id + * @return array array of resources + */ + public function getResourcesOfLevel($a_level_id) + { + $ret = (is_array($this->resources[$a_level_id])) + ? $this->resources[$a_level_id] + : array(); + + return $ret; + } + + /** + * Set resource as trigger + * + * @param int $a_level_id level id + * @param int $a_rep_ref_id repository resource ref id + * @param bool $a_trigger trigger true/false + */ + public function setResourceAsTrigger($a_level_id, $a_rep_ref_id, $a_trigger = true) + { + if (!is_array($this->resources[$a_level_id])) { + $this->resources[$a_level_id] = array(); + } + if (!is_array($this->resources[$a_level_id][$a_rep_ref_id])) { + $this->resources[$a_level_id][$a_rep_ref_id] = array(); + } + + $this->resources[$a_level_id][$a_rep_ref_id]["trigger"] = $a_trigger; + } - /** - * Set resource as imparting resource - * - * @param int $a_level_id level id - * @param int $a_rep_ref_id repository resource ref id - * @param bool $a_imparting imparting knowledge true/false - */ - function setResourceAsImparting($a_level_id, $a_rep_ref_id, $a_imparting = true) - { - if (!is_array($this->resources[$a_level_id])) - { - $this->resources[$a_level_id] = array(); - } - if (!is_array($this->resources[$a_level_id][$a_rep_ref_id])) - { - $this->resources[$a_level_id][$a_rep_ref_id] = array(); - } - - $this->resources[$a_level_id][$a_rep_ref_id]["imparting"] = $a_imparting; - } + /** + * Set resource as imparting resource + * + * @param int $a_level_id level id + * @param int $a_rep_ref_id repository resource ref id + * @param bool $a_imparting imparting knowledge true/false + */ + public function setResourceAsImparting($a_level_id, $a_rep_ref_id, $a_imparting = true) + { + if (!is_array($this->resources[$a_level_id])) { + $this->resources[$a_level_id] = array(); + } + if (!is_array($this->resources[$a_level_id][$a_rep_ref_id])) { + $this->resources[$a_level_id][$a_rep_ref_id] = array(); + } + + $this->resources[$a_level_id][$a_rep_ref_id]["imparting"] = $a_imparting; + } - /** - * Get usage info - * - * @param - * @return - */ - static public function getUsageInfo($a_cskill_ids, &$a_usages) - { - global $DIC; + /** + * Get usage info + * + * @param + * @return + */ + public static function getUsageInfo($a_cskill_ids, &$a_usages) + { + global $DIC; - $ilDB = $DIC->database(); - - include_once("./Services/Skill/classes/class.ilSkillUsage.php"); - ilSkillUsage::getUsageInfoGeneric($a_cskill_ids, $a_usages, ilSkillUsage::RESOURCE, - "skl_skill_resource", "rep_ref_id", "base_skill_id"); - } + $ilDB = $DIC->database(); + + include_once("./Services/Skill/classes/class.ilSkillUsage.php"); + ilSkillUsage::getUsageInfoGeneric( + $a_cskill_ids, + $a_usages, + ilSkillUsage::RESOURCE, + "skl_skill_resource", + "rep_ref_id", + "base_skill_id" + ); + } - /** - * Get levels for trigger per ref id - * - * @param int $a_ref_id - * @return array skill levels - */ - static function getTriggerLevelsForRefId($a_ref_id) - { - global $DIC; + /** + * Get levels for trigger per ref id + * + * @param int $a_ref_id + * @return array skill levels + */ + public static function getTriggerLevelsForRefId($a_ref_id) + { + global $DIC; - $db = $DIC->database(); - - $set = $db->query("SELECT * FROM skl_skill_resource ". - " WHERE rep_ref_id = ".$db->quote($a_ref_id, "integer"). - " AND ltrigger = ".$db->quote(1, "integer")); - - $skill_levels = array(); - while ($rec = $db->fetchAssoc($set)) - { - $skill_levels[] = array( - "base_skill_id" => $rec["base_skill_id"], - "tref_id" => $rec["tref_id"], - "level_id" => $rec["level_id"] - ); - } - return $skill_levels; - } + $db = $DIC->database(); + $set = $db->query("SELECT * FROM skl_skill_resource " . + " WHERE rep_ref_id = " . $db->quote($a_ref_id, "integer") . + " AND ltrigger = " . $db->quote(1, "integer")); + $skill_levels = array(); + while ($rec = $db->fetchAssoc($set)) { + $skill_levels[] = array( + "base_skill_id" => $rec["base_skill_id"], + "tref_id" => $rec["tref_id"], + "level_id" => $rec["level_id"] + ); + } + return $skill_levels; + } } - -?> diff --git a/Services/Skill/classes/class.ilSkillRoot.php b/Services/Skill/classes/class.ilSkillRoot.php index e56487f3b08df895a5cbbc38662621413a703177..28ecf513765d8cc1c98b990dc48deca9bd46a38e 100644 --- a/Services/Skill/classes/class.ilSkillRoot.php +++ b/Services/Skill/classes/class.ilSkillRoot.php @@ -14,42 +14,40 @@ include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); */ class ilSkillRoot extends ilSkillTreeNode { - var $id; - - /** - * Constructor - * @access public - */ - function __construct($a_id = 0) - { - parent::__construct($a_id); - $this->setType("skrt"); - } - - /** - * Read data from database - */ - function read() - { - parent::read(); - } - - /** - * Create skill - * - */ - function create() - { - parent::create(); - } - - /** - * Delete skill - */ - function delete() - { - parent::delete(); - } - + public $id; + + /** + * Constructor + * @access public + */ + public function __construct($a_id = 0) + { + parent::__construct($a_id); + $this->setType("skrt"); + } + + /** + * Read data from database + */ + public function read() + { + parent::read(); + } + + /** + * Create skill + * + */ + public function create() + { + parent::create(); + } + + /** + * Delete skill + */ + public function delete() + { + parent::delete(); + } } -?> diff --git a/Services/Skill/classes/class.ilSkillRootGUI.php b/Services/Skill/classes/class.ilSkillRootGUI.php index 2b2d6a3a9b775d7046984e0bf942472d7c503ef4..85260f351c8d4322cc213d66f0f7e75d3fc529f2 100644 --- a/Services/Skill/classes/class.ilSkillRootGUI.php +++ b/Services/Skill/classes/class.ilSkillRootGUI.php @@ -15,231 +15,225 @@ include_once("./Services/Skill/classes/class.ilSkillTreeNodeGUI.php"); */ class ilSkillRootGUI extends ilSkillTreeNodeGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilLanguage - */ - protected $lng; - - - /** - * Constructor - */ - function __construct($a_node_id = 0) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->tpl = $DIC["tpl"]; - $this->tabs = $DIC->tabs(); - $this->toolbar = $DIC->toolbar(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - - $ilCtrl->saveParameter($this, "obj_id"); - - parent::__construct($a_node_id); - } - - /** - * Get Node Type - */ - function getType() - { - return "skrt"; - } - - /** - * Execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd(); - - switch($next_class) - { - default: - $ret = $this->$cmd(); - break; - } - } - - /** - * List templates - */ - function listTemplates() - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilTabs = $this->tabs; - - $skmg_set = new ilSetting("skmg"); - $enable_skmg = $skmg_set->get("enable_skmg"); - if (!$enable_skmg) - { - ilUtil::sendInfo($lng->txt("skmg_skill_management_deactivated")); - } - - $this->getParentGUI()->showTree(true, $this, "listTemplates"); - $ilTabs->activateTab("skill_templates"); - - include_once("./Services/Skill/classes/class.ilSkillTemplateCategoryGUI.php"); - if ($this->checkPermissionBool("write")) - { - ilSkillTemplateCategoryGUI::addCreationButtons(); - } - - include_once("./Services/Skill/classes/class.ilSkillCatTableGUI.php"); - $table = new ilSkillCatTableGUI($this, "listTemplates", (int) $_GET["obj_id"], - ilSkillCatTableGUI::MODE_SCTP); - - $tpl->setContent($table->getHTML()); - } - - /** - * List skills - */ - function listSkills() - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilTabs = $this->tabs; - - $skmg_set = new ilSetting("skmg"); - $enable_skmg = $skmg_set->get("enable_skmg"); - if (!$enable_skmg) - { - ilUtil::sendInfo($lng->txt("skmg_skill_management_deactivated")); - } - - $this->getParentGUI()->showTree(false, $this, "listSkills"); - $ilTabs->activateTab("skills"); - - include_once("./Services/Skill/classes/class.ilSkillCategoryGUI.php"); - if ($this->checkPermissionBool("write")) - { - ilSkillCategoryGUI::addCreationButtons(); - } - - include_once("./Services/Skill/classes/class.ilSkillCatTableGUI.php"); - $table = new ilSkillCatTableGUI($this, "listSkills", (int) $_GET["obj_id"], - ilSkillCatTableGUI::MODE_SCAT); - - $tpl->setContent($table->getHTML()); - } - - /** - * cancel delete - */ - function cancelDelete() - { - $ilCtrl = $this->ctrl; - - if ($_GET["tmpmode"]) - { - $ilCtrl->redirect($this, "listTemplates"); - } - else - { - $ilCtrl->redirect($this, "listSkills"); - } - } - - /** - * Show import form - */ - function showImportForm() - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - $ilTabs->activateTab("skills"); - $tpl->setContent($this->initInputForm()->getHTML()); - } - - /** - * Init input form. - */ - public function initInputForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - - include_once("./Services/Form/classes/class.ilFileInputGUI.php"); - $fi = new ilFileInputGUI($lng->txt("skmg_input_file"), "import_file"); - $fi->setSuffixes(array("zip")); - $fi->setRequired(true); - $form->addItem($fi); - - // save and cancel commands - $form->addCommandButton("importSkills", $lng->txt("import")); - $form->addCommandButton("listSkills", $lng->txt("cancel")); - - $form->setTitle($lng->txt("skmg_import_skills")); - $form->setFormAction($ilCtrl->getFormAction($this)); - - return $form; - } - - /** - * Import skills - */ - public function importSkills() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - - $form = $this->initInputForm(); - if ($form->checkInput()) - { - include_once("./Services/Export/classes/class.ilImport.php"); - $imp = new ilImport(); - $imp->importEntity($_FILES["import_file"]["tmp_name"], $_FILES["import_file"]["name"], "skmg", "Services/Skill"); - - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "listSkills"); - } - else - { - $ilTabs->activateTab("skills"); - $form->setValuesByPost(); - $tpl->setContent($form->getHtml()); - } - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilLanguage + */ + protected $lng; + + + /** + * Constructor + */ + public function __construct($a_node_id = 0) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->tpl = $DIC["tpl"]; + $this->tabs = $DIC->tabs(); + $this->toolbar = $DIC->toolbar(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + + $ilCtrl->saveParameter($this, "obj_id"); + + parent::__construct($a_node_id); + } + + /** + * Get Node Type + */ + public function getType() + { + return "skrt"; + } + + /** + * Execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd(); + + switch ($next_class) { + default: + $ret = $this->$cmd(); + break; + } + } + + /** + * List templates + */ + public function listTemplates() + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilTabs = $this->tabs; + + $skmg_set = new ilSetting("skmg"); + $enable_skmg = $skmg_set->get("enable_skmg"); + if (!$enable_skmg) { + ilUtil::sendInfo($lng->txt("skmg_skill_management_deactivated")); + } + + $this->getParentGUI()->showTree(true, $this, "listTemplates"); + $ilTabs->activateTab("skill_templates"); + + include_once("./Services/Skill/classes/class.ilSkillTemplateCategoryGUI.php"); + if ($this->checkPermissionBool("write")) { + ilSkillTemplateCategoryGUI::addCreationButtons(); + } + + include_once("./Services/Skill/classes/class.ilSkillCatTableGUI.php"); + $table = new ilSkillCatTableGUI( + $this, + "listTemplates", + (int) $_GET["obj_id"], + ilSkillCatTableGUI::MODE_SCTP + ); + + $tpl->setContent($table->getHTML()); + } + + /** + * List skills + */ + public function listSkills() + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilTabs = $this->tabs; + + $skmg_set = new ilSetting("skmg"); + $enable_skmg = $skmg_set->get("enable_skmg"); + if (!$enable_skmg) { + ilUtil::sendInfo($lng->txt("skmg_skill_management_deactivated")); + } + + $this->getParentGUI()->showTree(false, $this, "listSkills"); + $ilTabs->activateTab("skills"); + + include_once("./Services/Skill/classes/class.ilSkillCategoryGUI.php"); + if ($this->checkPermissionBool("write")) { + ilSkillCategoryGUI::addCreationButtons(); + } + + include_once("./Services/Skill/classes/class.ilSkillCatTableGUI.php"); + $table = new ilSkillCatTableGUI( + $this, + "listSkills", + (int) $_GET["obj_id"], + ilSkillCatTableGUI::MODE_SCAT + ); + + $tpl->setContent($table->getHTML()); + } + + /** + * cancel delete + */ + public function cancelDelete() + { + $ilCtrl = $this->ctrl; + + if ($_GET["tmpmode"]) { + $ilCtrl->redirect($this, "listTemplates"); + } else { + $ilCtrl->redirect($this, "listSkills"); + } + } + + /** + * Show import form + */ + public function showImportForm() + { + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + $ilTabs->activateTab("skills"); + $tpl->setContent($this->initInputForm()->getHTML()); + } + + /** + * Init input form. + */ + public function initInputForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + + include_once("./Services/Form/classes/class.ilFileInputGUI.php"); + $fi = new ilFileInputGUI($lng->txt("skmg_input_file"), "import_file"); + $fi->setSuffixes(array("zip")); + $fi->setRequired(true); + $form->addItem($fi); + + // save and cancel commands + $form->addCommandButton("importSkills", $lng->txt("import")); + $form->addCommandButton("listSkills", $lng->txt("cancel")); + + $form->setTitle($lng->txt("skmg_import_skills")); + $form->setFormAction($ilCtrl->getFormAction($this)); + + return $form; + } + + /** + * Import skills + */ + public function importSkills() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + + $form = $this->initInputForm(); + if ($form->checkInput()) { + include_once("./Services/Export/classes/class.ilImport.php"); + $imp = new ilImport(); + $imp->importEntity($_FILES["import_file"]["tmp_name"], $_FILES["import_file"]["name"], "skmg", "Services/Skill"); + + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "listSkills"); + } else { + $ilTabs->activateTab("skills"); + $form->setValuesByPost(); + $tpl->setContent($form->getHtml()); + } + } } - -?> \ No newline at end of file diff --git a/Services/Skill/classes/class.ilSkillSelectorGUI.php b/Services/Skill/classes/class.ilSkillSelectorGUI.php index 7bad59a89f4cd13efc94e970b6637ef5c0bd6214..ac89d861f22c5061b2ccad4483c4dc711d021a66 100644 --- a/Services/Skill/classes/class.ilSkillSelectorGUI.php +++ b/Services/Skill/classes/class.ilSkillSelectorGUI.php @@ -13,122 +13,112 @@ include_once("./Services/Skill/classes/class.ilVirtualSkillTreeExplorerGUI.php") */ class ilSkillSelectorGUI extends ilVirtualSkillTreeExplorerGUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * Constructor - */ - public function __construct($a_parent_obj, $a_parent_cmd, $a_select_gui, $a_select_cmd, $a_select_par = "selected_skill") - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_select_gui, $a_select_cmd, $a_select_par = "selected_skill") + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - parent::__construct("skill_sel", $a_parent_obj, $a_parent_cmd); - $this->select_gui = (is_object($a_select_gui)) - ? strtolower(get_class($a_select_gui)) - : $a_select_gui; - $this->select_cmd = $a_select_cmd; - $this->select_par = $a_select_par; - $this->setSkipRootNode(true); - } + $this->ctrl = $DIC->ctrl(); + parent::__construct("skill_sel", $a_parent_obj, $a_parent_cmd); + $this->select_gui = (is_object($a_select_gui)) + ? strtolower(get_class($a_select_gui)) + : $a_select_gui; + $this->select_cmd = $a_select_cmd; + $this->select_par = $a_select_par; + $this->setSkipRootNode(true); + } - /** - * Set skill to be opened - * - * @param - */ - function setSkillSelected($a_id) - { - $this->setNodeSelected($this->vtree->getCSkillIdForVTreeId($a_id)); - } + /** + * Set skill to be opened + * + * @param + */ + public function setSkillSelected($a_id) + { + $this->setNodeSelected($this->vtree->getCSkillIdForVTreeId($a_id)); + } - /** - * Get selected skills (from POST) - */ - function getSelectedSkills() - { - $skills = array(); - $pa = $_POST[$this->select_postvar]; - if (is_array($pa)) - { - foreach ($pa as $p) - { - $skills[] = $this->vtree->getCSkillIdForVTreeId($p); - } - } - return $skills; - } - - /** - * Get href for node - * - * @param mixed $a_node node object/array - * @return string href attribute - */ - function getNodeHref($a_node) - { - if ($this->select_multi) - { - return "#"; - } + /** + * Get selected skills (from POST) + */ + public function getSelectedSkills() + { + $skills = array(); + $pa = $_POST[$this->select_postvar]; + if (is_array($pa)) { + foreach ($pa as $p) { + $skills[] = $this->vtree->getCSkillIdForVTreeId($p); + } + } + return $skills; + } + + /** + * Get href for node + * + * @param mixed $a_node node object/array + * @return string href attribute + */ + public function getNodeHref($a_node) + { + if ($this->select_multi) { + return "#"; + } - $ilCtrl = $this->ctrl; - - // we have a tree id like : - // and make a "common" skill id in format : - - $id_parts = explode(":", $a_node["id"]); - if ($id_parts[1] == 0) - { - // skill in main tree - $skill_id = $a_node["id"]; - } - else - { - // skill in template - $skill_id = $id_parts[1].":".$id_parts[0]; - } - - $ilCtrl->setParameterByClass($this->select_gui, $this->select_par, $skill_id); - $ret = $ilCtrl->getLinkTargetByClass($this->select_gui, $this->select_cmd); - $ilCtrl->setParameterByClass($this->select_gui, $this->select_par, ""); - - return $ret; - } + $ilCtrl = $this->ctrl; + + // we have a tree id like : + // and make a "common" skill id in format : + + $id_parts = explode(":", $a_node["id"]); + if ($id_parts[1] == 0) { + // skill in main tree + $skill_id = $a_node["id"]; + } else { + // skill in template + $skill_id = $id_parts[1] . ":" . $id_parts[0]; + } + + $ilCtrl->setParameterByClass($this->select_gui, $this->select_par, $skill_id); + $ret = $ilCtrl->getLinkTargetByClass($this->select_gui, $this->select_cmd); + $ilCtrl->setParameterByClass($this->select_gui, $this->select_par, ""); + + return $ret; + } - /** - * Is clickable - * - * @param - * @return - */ - function isNodeClickable($a_node) - { - return $this->nodeHasAction($a_node); - } - - protected function isNodeSelectable($a_node) - { - return $this->nodeHasAction($a_node); - } - - private function nodeHasAction($a_node) - { - if (in_array($a_node["type"], array("skll", "sktp"))) - { - return true; - } - // references that refer directly to a (basic) skill template - if ($a_node["type"] == "sktr" && ilSkillTreeNode::_lookupType($a_node["skill_id"]) == "sktp") - { - return true; - } + /** + * Is clickable + * + * @param + * @return + */ + public function isNodeClickable($a_node) + { + return $this->nodeHasAction($a_node); + } + + protected function isNodeSelectable($a_node) + { + return $this->nodeHasAction($a_node); + } + + private function nodeHasAction($a_node) + { + if (in_array($a_node["type"], array("skll", "sktp"))) { + return true; + } + // references that refer directly to a (basic) skill template + if ($a_node["type"] == "sktr" && ilSkillTreeNode::_lookupType($a_node["skill_id"]) == "sktp") { + return true; + } - return false; - } + return false; + } } - -?> diff --git a/Services/Skill/classes/class.ilSkillSelfEvalSkillTableGUI.php b/Services/Skill/classes/class.ilSkillSelfEvalSkillTableGUI.php index 3bfdb13d5cfa5ed2a6db9d869a7d3a872530415b..fa245d83075111d7742e2c7f1245255bcbbf31c1 100644 --- a/Services/Skill/classes/class.ilSkillSelfEvalSkillTableGUI.php +++ b/Services/Skill/classes/class.ilSkillSelfEvalSkillTableGUI.php @@ -13,127 +13,112 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilSkillSelfEvalSkillTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_sn_id, $a_se = null) - { - global $DIC; + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_sn_id, $a_se = null) + { + 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->sn_id = $a_sn_id; - if ($a_se != null) - { - $this->se = $a_se; - $this->levels = $this->se->getLevels(); - } + $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->sn_id = $a_sn_id; + if ($a_se != null) { + $this->se = $a_se; + $this->levels = $this->se->getLevels(); + } - // build title - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $stree = new ilSkillTree(); - $path = $stree->getPathFull($this->sn_id); - $title = $sep = ""; - foreach ($path as $p) - { - if ($p["type"] != "skrt") - { - $title.= $sep.$p["title"]; - $sep = " > "; - } - } + // build title + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $stree = new ilSkillTree(); + $path = $stree->getPathFull($this->sn_id); + $title = $sep = ""; + foreach ($path as $p) { + if ($p["type"] != "skrt") { + $title.= $sep . $p["title"]; + $sep = " > "; + } + } - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setData($this->getLevels()); - $this->setTitle($title); - $this->setLimit(9999); - - $this->addColumn($this->lng->txt("skmg_your_self_evaluation")); - $this->addColumn($this->lng->txt("skmg_skill_level")); - - $this->setEnableHeader(true); -// $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.self_eval_row.html", "Services/Skill"); - $this->disable("footer"); - $this->setEnableTitle(true); - -// $this->addMultiCommand("", $lng->txt("")); + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setData($this->getLevels()); + $this->setTitle($title); + $this->setLimit(9999); + + $this->addColumn($this->lng->txt("skmg_your_self_evaluation")); + $this->addColumn($this->lng->txt("skmg_skill_level")); + + $this->setEnableHeader(true); + // $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.self_eval_row.html", "Services/Skill"); + $this->disable("footer"); + $this->setEnableTitle(true); + + // $this->addMultiCommand("", $lng->txt("")); // $this->addCommandButton("", $lng->txt("")); - } + } - /** - * Get levels - * - * @param - * @return - */ - function getLevels() - { - include_once("./Services/Skill/classes/class.ilBasicSkill.php"); - $this->skill = new ilBasicSkill($this->sn_id); - $levels = array(array("id" => 0)); - foreach ($this->skill->getLevelData() as $k => $v) - { - $levels[] = $v; - } + /** + * Get levels + * + * @param + * @return + */ + public function getLevels() + { + include_once("./Services/Skill/classes/class.ilBasicSkill.php"); + $this->skill = new ilBasicSkill($this->sn_id); + $levels = array(array("id" => 0)); + foreach ($this->skill->getLevelData() as $k => $v) { + $levels[] = $v; + } - return $levels; - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; + return $levels; + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; -//var_dump($a_set); - if ($a_set["id"] == 0) - { - $this->tpl->setVariable("LEVEL_ID", $a_set["id"]); - $this->tpl->setVariable("SKILL_ID", $this->sn_id); - $this->tpl->setVariable("TXT_SKILL", $lng->txt("skmg_no_skills")); - } - else - { - $this->tpl->setVariable("LEVEL_ID", $a_set["id"]); - $this->tpl->setVariable("SKILL_ID", $this->sn_id); - $this->tpl->setVariable("TXT_SKILL", $a_set["title"].": ".$a_set["description"]); - } + //var_dump($a_set); + if ($a_set["id"] == 0) { + $this->tpl->setVariable("LEVEL_ID", $a_set["id"]); + $this->tpl->setVariable("SKILL_ID", $this->sn_id); + $this->tpl->setVariable("TXT_SKILL", $lng->txt("skmg_no_skills")); + } else { + $this->tpl->setVariable("LEVEL_ID", $a_set["id"]); + $this->tpl->setVariable("SKILL_ID", $this->sn_id); + $this->tpl->setVariable("TXT_SKILL", $a_set["title"] . ": " . $a_set["description"]); + } - if ($this->se != null) - { - if ($this->levels[$this->sn_id] == $a_set["id"]) - { - $this->tpl->setVariable("CHECKED", " checked='checked' "); - } - } - else - { - if ($a_set["id"] == 0) - { - $this->tpl->setVariable("CHECKED", " checked='checked' "); - } - } - - } - + if ($this->se != null) { + if ($this->levels[$this->sn_id] == $a_set["id"]) { + $this->tpl->setVariable("CHECKED", " checked='checked' "); + } + } else { + if ($a_set["id"] == 0) { + $this->tpl->setVariable("CHECKED", " checked='checked' "); + } + } + } } -?> diff --git a/Services/Skill/classes/class.ilSkillSelfEvaluation.php b/Services/Skill/classes/class.ilSkillSelfEvaluation.php index e536c83d21dc0823164b3e2c4099d6b64ff7c15b..cafa65390bc8e775b565fb9bc5cbdd7a2078b7db 100644 --- a/Services/Skill/classes/class.ilSkillSelfEvaluation.php +++ b/Services/Skill/classes/class.ilSkillSelfEvaluation.php @@ -6,429 +6,404 @@ * * @author Alex Killing * @version $Id$ - * + * * @ingroup ServicesSkill */ class ilSkillSelfEvaluation { - /** - * @var ilDB - */ - protected $db; - - /** - * Constructor - * - * @param - */ - function __construct($a_id = 0) - { - global $DIC; - - $this->db = $DIC->database(); - if ($a_id > 0) - { - $this->setId($a_id); - $this->read(); - } - } - - /** - * Set id - * - * @param integer id - */ - function setId($a_val) - { - $this->id = $a_val; - } - - /** - * Get id - * - * @return integer id - */ - function getId() - { - return $this->id; - } - - /** - * Set user id - * - * @param integer user id - */ - function setUserId($a_val) - { - $this->user_id = $a_val; - } - - /** - * Get user id - * - * @return integer user id - */ - function getUserId() - { - return $this->user_id; - } - - /** - * Set top skill id - * - * @param integer top skill id - */ - function setTopSkillId($a_val) - { - $this->top_skill_id = $a_val; - } - - /** - * Get top skill id - * - * @return integer top skill id - */ - function getTopSkillId() - { - return $this->top_skill_id; - } - - /** - * Set created at - * - * @param timestamp created at - */ - function setCreated($a_val) - { - $this->created = $a_val; - } - - /** - * Get created at - * - * @return timestamp created at - */ - function getCreated() - { - return $this->created; - } - - /** - * Set last update - * - * @param timestamp last update - */ - function setLastUpdate($a_val) - { - $this->last_update = $a_val; - } - - /** - * Get last update - * - * @return timestamp last update - */ - function getLastUpdate() - { - return $this->last_update; - } - - /** - * Set level - * - * @param array level; index: skill id, value: level id (or 0 for no skills) - */ - function setLevels($a_val, $a_keep_existing = false) - { - if (!$a_keep_existing) - { - $this->levels = $a_val; - } - else - { - if (is_array($a_val)) - { - foreach ($a_val as $k => $v) - { - $this->levels[$k] = $v; - } - } - } - } - - /** - * Get level - * - * @return array level - */ - function getLevels() - { - return $this->levels; - } - - /** - * Read - * - * @param - * @return - */ - function read() - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT * FROM skl_self_eval WHERE ". - " id = ".$ilDB->quote($this->getId(), "integer") - ); - if ($rec = $ilDB->fetchAssoc($set)) - { - $this->setUserId($rec["user_id"]); - $this->setTopSkillId($rec["top_skill_id"]); - $this->setCreated($rec["created"]); - $this->setLastUpdate($rec["last_update"]); - } - - // levels - $set = $ilDB->query("SELECT * FROM skl_self_eval_level WHERE ". - " self_eval_id = ".$ilDB->quote($this->getId(), "integer") - ); - $levels = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $levels[$rec["skill_id"]] = $rec["level_id"]; - } - $this->setLevels($levels); - - } - - /** - * Create self evaluation - */ - function create() - { - $ilDB = $this->db; - - $this->setId($ilDB->nextId("skl_self_eval")); - - $ilDB->manipulate("INSERT INTO skl_self_eval ". - "(id, user_id, top_skill_id, created, last_update) VALUES (". - $ilDB->quote($this->getId(), "integer").",". - $ilDB->quote($this->getUserId(), "integer").",". - $ilDB->quote($this->getTopSkillId(), "integer").",". - $ilDB->now().",". - $ilDB->now(). - ")"); - - $levels = $this->getLevels(); - if (is_array($levels)) - { - foreach ($levels as $skill_id => $level_id) - { - $ilDB->manipulate("INSERT INTO skl_self_eval_level ". - "(self_eval_id, skill_id, level_id) VALUES (". - $ilDB->quote($this->getId(), "integer").",". - $ilDB->quote($skill_id, "integer").",". - $ilDB->quote($level_id, "integer"). - ")"); - } - } - } - - /** - * Update self evaluation - */ - function update() - { - $ilDB = $this->db; - - $ilDB->manipulate("UPDATE skl_self_eval SET ". - " user_id = ".$ilDB->quote($this->getUserId(), "integer"). - ", top_skill_id = ".$ilDB->quote($this->getTopSkillId(), "integer"). - ", last_update = ".$ilDB->now(). - " WHERE id = ".$ilDB->quote($this->getId(), "integer") - ); - - $ilDB->manipulate("DELETE FROM skl_self_eval_level WHERE " - ." self_eval_id = ".$ilDB->quote($this->getId(), "integer") - ); - - $levels = $this->getLevels(); - if (is_array($levels)) - { - foreach ($levels as $skill_id => $level_id) - { - $ilDB->manipulate("INSERT INTO skl_self_eval_level ". - "(self_eval_id, skill_id, level_id) VALUES (". - $ilDB->quote($this->getId(), "integer").",". - $ilDB->quote($skill_id, "integer").",". - $ilDB->quote($level_id, "integer"). - ")"); - } - } - } - - /** - * Delete self evaluation - */ - function delete() - { - $ilDB = $this->db; - - $ilDB->manipulate("DELETE FROM skl_self_eval WHERE " - ." id = ".$ilDB->quote($this->getId(), "integer") - ); - - $ilDB->manipulate("DELETE FROM skl_self_eval_level WHERE " - ." self_eval_id = ".$ilDB->quote($this->getId(), "integer") - ); - } - - /** - * Get all self evaluations - */ - static function getAllSelfEvaluationsOfUser($a_user, $a_one_per_top_skill = false) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT * FROM skl_self_eval WHERE user_id = ". - $ilDB->quote($a_user, "integer")." ". - "ORDER BY last_update DESC" - ); - - $self_evaluation = array(); - - $top_skills = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - if (!$a_one_per_top_skill || !in_array($rec["top_skill_id"], $top_skills)) - { - $self_evaluation[] = $rec; - $top_skills[] = $rec["top_skill_id"]; - } - } - - return $self_evaluation; - } - - /** - * Lookup property - * - * @param id level id - * @return mixed property value - */ - protected static function lookupProperty($a_id, $a_prop) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT $a_prop FROM skl_self_eval WHERE ". - " id = ".$ilDB->quote($a_id, "integer") - ); - $rec = $ilDB->fetchAssoc($set); - return $rec[$a_prop]; - } - - /** - * Get average level of user self evaluation - * - * Note: this method does not make much sense in general, since it - * assumes that all basic skills have the same level - */ - static function getAverageLevel($a_se_id, $a_user_id, $a_top_skill_id) - { - global $DIC; - - $lng = $DIC->language(); - - $lng->loadLanguageModule("skmg"); - - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - include_once("./Services/Skill/classes/class.ilBasicSkill.php"); - $stree = new ilSkillTree(); - $cnt = 0; - $sum = 0; - if ($stree->isInTree($a_top_skill_id)) - { - $se = new ilSkillSelfEvaluation($a_se_id); - $levels = $se->getLevels(); - - $cnode = $stree->getNodeData($a_top_skill_id); - $childs = $stree->getSubTree($cnode); - - foreach ($childs as $child) - { - if ($child["type"] == "skll") - { - $sk = new ilBasicSkill($child["child"]); - $ls = $sk->getLevelData(); - $ord = array(); - foreach ($ls as $k => $l) - { - $ord[$l["id"]] = $k + 1; - } - reset($ls); - foreach ($ls as $ld) - { - if ($ld["id"] == $levels[$child["child"]]) - { - $sum+= $ord[$ld["id"]]; - } - } - $cnt+= 1; - } - } - } - if ($cnt > 0) - { - $avg = round($sum/$cnt); - if ($avg > 0) - { - return (array("skill_title" => $cnode["title"], - "ord" => $avg, "avg_title" => $ls[$avg - 1]["title"])); - } - else - { - return (array("skill_title" => $cnode["title"], - "ord" => $avg, "avg_title" => $lng->txt("skmg_no_skills"))); - } - } - return null; - } - - /** - * Determine steps - * - * @param - * @return - */ - static function determineSteps($a_sn_id) - { - $steps = array(); - if ($a_sn_id > 0 ) - { - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - include_once("./Services/Skill/classes/class.ilSkillSelfEvalSkillTableGUI.php"); - $stree = new ilSkillTree(); - - if ($stree->isInTree($a_sn_id)) - { - $cnode = $stree->getNodeData($a_sn_id); - $childs = $stree->getSubTree($cnode); - foreach ($childs as $child) - { - if ($child["type"] == "skll") - { - $steps[] = $child["child"]; - } - } - } - } - return $steps; - } - - + /** + * @var ilDB + */ + protected $db; + + /** + * Constructor + * + * @param + */ + public function __construct($a_id = 0) + { + global $DIC; + + $this->db = $DIC->database(); + if ($a_id > 0) { + $this->setId($a_id); + $this->read(); + } + } + + /** + * Set id + * + * @param integer id + */ + public function setId($a_val) + { + $this->id = $a_val; + } + + /** + * Get id + * + * @return integer id + */ + public function getId() + { + return $this->id; + } + + /** + * Set user id + * + * @param integer user id + */ + public function setUserId($a_val) + { + $this->user_id = $a_val; + } + + /** + * Get user id + * + * @return integer user id + */ + public function getUserId() + { + return $this->user_id; + } + + /** + * Set top skill id + * + * @param integer top skill id + */ + public function setTopSkillId($a_val) + { + $this->top_skill_id = $a_val; + } + + /** + * Get top skill id + * + * @return integer top skill id + */ + public function getTopSkillId() + { + return $this->top_skill_id; + } + + /** + * Set created at + * + * @param timestamp created at + */ + public function setCreated($a_val) + { + $this->created = $a_val; + } + + /** + * Get created at + * + * @return timestamp created at + */ + public function getCreated() + { + return $this->created; + } + + /** + * Set last update + * + * @param timestamp last update + */ + public function setLastUpdate($a_val) + { + $this->last_update = $a_val; + } + + /** + * Get last update + * + * @return timestamp last update + */ + public function getLastUpdate() + { + return $this->last_update; + } + + /** + * Set level + * + * @param array level; index: skill id, value: level id (or 0 for no skills) + */ + public function setLevels($a_val, $a_keep_existing = false) + { + if (!$a_keep_existing) { + $this->levels = $a_val; + } else { + if (is_array($a_val)) { + foreach ($a_val as $k => $v) { + $this->levels[$k] = $v; + } + } + } + } + + /** + * Get level + * + * @return array level + */ + public function getLevels() + { + return $this->levels; + } + + /** + * Read + * + * @param + * @return + */ + public function read() + { + $ilDB = $this->db; + + $set = $ilDB->query( + "SELECT * FROM skl_self_eval WHERE " . + " id = " . $ilDB->quote($this->getId(), "integer") + ); + if ($rec = $ilDB->fetchAssoc($set)) { + $this->setUserId($rec["user_id"]); + $this->setTopSkillId($rec["top_skill_id"]); + $this->setCreated($rec["created"]); + $this->setLastUpdate($rec["last_update"]); + } + + // levels + $set = $ilDB->query( + "SELECT * FROM skl_self_eval_level WHERE " . + " self_eval_id = " . $ilDB->quote($this->getId(), "integer") + ); + $levels = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $levels[$rec["skill_id"]] = $rec["level_id"]; + } + $this->setLevels($levels); + } + + /** + * Create self evaluation + */ + public function create() + { + $ilDB = $this->db; + + $this->setId($ilDB->nextId("skl_self_eval")); + + $ilDB->manipulate("INSERT INTO skl_self_eval " . + "(id, user_id, top_skill_id, created, last_update) VALUES (" . + $ilDB->quote($this->getId(), "integer") . "," . + $ilDB->quote($this->getUserId(), "integer") . "," . + $ilDB->quote($this->getTopSkillId(), "integer") . "," . + $ilDB->now() . "," . + $ilDB->now() . + ")"); + + $levels = $this->getLevels(); + if (is_array($levels)) { + foreach ($levels as $skill_id => $level_id) { + $ilDB->manipulate("INSERT INTO skl_self_eval_level " . + "(self_eval_id, skill_id, level_id) VALUES (" . + $ilDB->quote($this->getId(), "integer") . "," . + $ilDB->quote($skill_id, "integer") . "," . + $ilDB->quote($level_id, "integer") . + ")"); + } + } + } + + /** + * Update self evaluation + */ + public function update() + { + $ilDB = $this->db; + + $ilDB->manipulate( + "UPDATE skl_self_eval SET " . + " user_id = " . $ilDB->quote($this->getUserId(), "integer") . + ", top_skill_id = " . $ilDB->quote($this->getTopSkillId(), "integer") . + ", last_update = " . $ilDB->now() . + " WHERE id = " . $ilDB->quote($this->getId(), "integer") + ); + + $ilDB->manipulate( + "DELETE FROM skl_self_eval_level WHERE " + . " self_eval_id = " . $ilDB->quote($this->getId(), "integer") + ); + + $levels = $this->getLevels(); + if (is_array($levels)) { + foreach ($levels as $skill_id => $level_id) { + $ilDB->manipulate("INSERT INTO skl_self_eval_level " . + "(self_eval_id, skill_id, level_id) VALUES (" . + $ilDB->quote($this->getId(), "integer") . "," . + $ilDB->quote($skill_id, "integer") . "," . + $ilDB->quote($level_id, "integer") . + ")"); + } + } + } + + /** + * Delete self evaluation + */ + public function delete() + { + $ilDB = $this->db; + + $ilDB->manipulate( + "DELETE FROM skl_self_eval WHERE " + . " id = " . $ilDB->quote($this->getId(), "integer") + ); + + $ilDB->manipulate( + "DELETE FROM skl_self_eval_level WHERE " + . " self_eval_id = " . $ilDB->quote($this->getId(), "integer") + ); + } + + /** + * Get all self evaluations + */ + public static function getAllSelfEvaluationsOfUser($a_user, $a_one_per_top_skill = false) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT * FROM skl_self_eval WHERE user_id = " . + $ilDB->quote($a_user, "integer") . " " . + "ORDER BY last_update DESC" + ); + + $self_evaluation = array(); + + $top_skills = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + if (!$a_one_per_top_skill || !in_array($rec["top_skill_id"], $top_skills)) { + $self_evaluation[] = $rec; + $top_skills[] = $rec["top_skill_id"]; + } + } + + return $self_evaluation; + } + + /** + * Lookup property + * + * @param id level id + * @return mixed property value + */ + protected static function lookupProperty($a_id, $a_prop) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT $a_prop FROM skl_self_eval WHERE " . + " id = " . $ilDB->quote($a_id, "integer") + ); + $rec = $ilDB->fetchAssoc($set); + return $rec[$a_prop]; + } + + /** + * Get average level of user self evaluation + * + * Note: this method does not make much sense in general, since it + * assumes that all basic skills have the same level + */ + public static function getAverageLevel($a_se_id, $a_user_id, $a_top_skill_id) + { + global $DIC; + + $lng = $DIC->language(); + + $lng->loadLanguageModule("skmg"); + + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + include_once("./Services/Skill/classes/class.ilBasicSkill.php"); + $stree = new ilSkillTree(); + $cnt = 0; + $sum = 0; + if ($stree->isInTree($a_top_skill_id)) { + $se = new ilSkillSelfEvaluation($a_se_id); + $levels = $se->getLevels(); + + $cnode = $stree->getNodeData($a_top_skill_id); + $childs = $stree->getSubTree($cnode); + + foreach ($childs as $child) { + if ($child["type"] == "skll") { + $sk = new ilBasicSkill($child["child"]); + $ls = $sk->getLevelData(); + $ord = array(); + foreach ($ls as $k => $l) { + $ord[$l["id"]] = $k + 1; + } + reset($ls); + foreach ($ls as $ld) { + if ($ld["id"] == $levels[$child["child"]]) { + $sum+= $ord[$ld["id"]]; + } + } + $cnt+= 1; + } + } + } + if ($cnt > 0) { + $avg = round($sum/$cnt); + if ($avg > 0) { + return (array("skill_title" => $cnode["title"], + "ord" => $avg, "avg_title" => $ls[$avg - 1]["title"])); + } else { + return (array("skill_title" => $cnode["title"], + "ord" => $avg, "avg_title" => $lng->txt("skmg_no_skills"))); + } + } + return null; + } + + /** + * Determine steps + * + * @param + * @return + */ + public static function determineSteps($a_sn_id) + { + $steps = array(); + if ($a_sn_id > 0) { + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + include_once("./Services/Skill/classes/class.ilSkillSelfEvalSkillTableGUI.php"); + $stree = new ilSkillTree(); + + if ($stree->isInTree($a_sn_id)) { + $cnode = $stree->getNodeData($a_sn_id); + $childs = $stree->getSubTree($cnode); + foreach ($childs as $child) { + if ($child["type"] == "skll") { + $steps[] = $child["child"]; + } + } + } + } + return $steps; + } } - -?> \ No newline at end of file diff --git a/Services/Skill/classes/class.ilSkillSelfEvaluationGUI.php b/Services/Skill/classes/class.ilSkillSelfEvaluationGUI.php index 6ff5e2272d0841b0f249e0a8bbfa18cd5740f79a..3b00cf847d333eb994e68ed62f961188d9007f2e 100644 --- a/Services/Skill/classes/class.ilSkillSelfEvaluationGUI.php +++ b/Services/Skill/classes/class.ilSkillSelfEvaluationGUI.php @@ -11,462 +11,428 @@ */ class ilSkillSelfEvaluationGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * Constructor - * - * @param - * @return - */ - function __construct() - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - $this->toolbar = $DIC->toolbar(); - $this->user = $DIC->user(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $ilCtrl->saveParameter($this, array("se_id", "sn_id")); - $lng->loadLanguageModule("skmg"); - - $this->readSelfEvaluation(); - - $this->se_id = (int) $_GET["se_id"]; - $this->sn_id = ((int) $_POST["sn_id"] > 0) - ? (int) $_POST["sn_id"] - : (int) $_GET["sn_id"]; - $ilCtrl->setParameter($this, "sn_id", $this->sn_id); - } - - /** - * Execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - - $cmd = $ilCtrl->getCmd("listSelfEvaluations"); - $this->$cmd(); - } - - /** - * Read self_evaluation - * - * @param - * @return - */ - function readSelfEvaluation() - { -// $this->self_evaluation = new ilSelfEvaluation((int) $_GET[save_param]); - } - - /** - * List all self evaluations - */ - function listSelfEvaluations() - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); - - // desc - /*$ne = new ilNonEditableValueGUI($lng->txt("lang"), var); - $ne->setValue(); - $ne->setInfo(); - $this->form->addItem($ne);*/ - - // select skill for self evaluation - include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); - $se_nodes = ilSkillTreeNode::getAllSelfEvaluationNodes(); - foreach ($se_nodes as $n_id => $title) - { - - $options[$n_id] = $title; - } - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $si = new ilSelectInputGUI($lng->txt("skmg_please_select_self_skill"), "sn_id"); - $si->setOptions($options); - - //$si->setInfo($lng->txt("")); - $ilToolbar->addInputItem($si, true); - - $ilToolbar->addFormButton($lng->txt("skmg_execute_self_evaluation"), "startSelfEvaluation"); - - include_once("./Services/Skill/classes/class.ilSelfEvaluationTableGUI.php"); - $table = new ilSelfEvaluationTableGUI($this, "listSelfEvaluations"); - - $tpl->setContent($table->getHTML()); - } - - - /** - * Confirm self_evaluation deletion - */ - function confirmSelfEvaluationDeletion() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - if (!is_array($_POST["id"]) || count($_POST["id"]) == 0) - { - ilUtil::sendInfo($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "listSelfEvaluations"); - } - else - { - include_once("./Services/Skill/classes/class.ilSkillSelfEvaluation.php"); - include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("skmg_sure_delete_self_evaluation")); - $cgui->setCancel($lng->txt("cancel"), "listSelfEvaluations"); - $cgui->setConfirm($lng->txt("delete"), "deleteSelfEvaluation"); - - foreach ($_POST["id"] as $i) - { - $se = new ilSkillSelfEvaluation((int) $i); - $se_title = - ilSkillTreeNode::_lookupTitle($se->getTopSkillId()); - $cgui->addItem("id[]", $i, $se_title.", ".$lng->txt("created").": ". - $se->getCreated().", ".$lng->txt("last_update").": ".$se->getLastUpdate()); - } - - $tpl->setContent($cgui->getHTML()); - } - } - - /** - * Delete self_evaluation - * - * @param - * @return - */ - function deleteSelfEvaluation() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilUser = $this->user; - - include_once("./Services/Skill/classes/class.ilSkillSelfEvaluation.php"); - if (is_array($_POST["id"])) - { - foreach ($_POST["id"] as $i) - { - $se = new ilSkillSelfEvaluation((int) $i); - if ($se->getUserId() == $ilUser->getId()) - { - $se->delete(); - } - } - } - ilUtil::sendSuccess("msg_obj_modified"); - $ilCtrl->redirect($this, "listSelfEvaluations"); - } - - - /** - * startSelfEvaluation - * - * @param - * @return - */ - function startSelfEvaluation($a_mode = "create") - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $se = null; - if ($a_mode == "edit") - { - include_once("./Services/Skill/classes/class.ilSkillSelfEvaluation.php"); - $se = new ilSkillSelfEvaluation((int) $_GET["se_id"]); - $this->sn_id = $se->getTopSkillId(); - } - ilUtil::sendInfo($lng->txt("skmg_please_select_your_skill_levels")); - - $se_tpl = new ilTemplate("tpl.self_evaluation.html", true, true, "Services/Skill"); - include_once("./Services/Skill/classes/class.ilSkillSelfEvaluation.php"); - - $steps = ilSkillSelfEvaluation::determineSteps($this->sn_id); - $cstep = (int) $_GET["step"]; - $ilCtrl->setParameter($this, "step", $cstep); - include_once("./Services/Skill/classes/class.ilSkillSelfEvalSkillTableGUI.php"); - $table = new ilSkillSelfEvalSkillTableGUI($this, "startSelfEvaluation", - $steps[$cstep], $se); - - $se_tpl->setCurrentBlock("se_table"); - $se_tpl->setVariable("SE_TABLE", $table->getHTML()); - $se_tpl->parseCurrentBlock(); - - include_once("./Services/UIComponent/Toolbar/classes/class.ilToolbarGUI.php"); - $tb = new ilToolbarGUI(); - if ($a_mode == "edit") - { - if ($cstep > 0) - { - $tb->addFormButton("< ".$lng->txt("skmg_previous_step"), "updateBackSelfEvaluation"); - } - if ($cstep < count($steps) - 1) - { - $tb->addFormButton($lng->txt("skmg_next_step")." >", "updateSelfEvaluation"); - } - else if ($cstep == count($steps) - 1) - { - $tb->addFormButton($lng->txt("skmg_save_self_evaluation"), "updateSelfEvaluation"); - } - } - else - { - if ($cstep < count($steps) - 1) - { - $tb->addFormButton($lng->txt("skmg_next_step")." >", "saveSelfEvaluation"); - } - else if ($cstep == count($steps) - 1) - { - $tb->addFormButton($lng->txt("skmg_save_self_evaluation"), "saveSelfEvaluation"); - } - } - $se_tpl->setVariable("FORM_ACTION", $ilCtrl->getFormAction($this)); - $se_tpl->setVariable("TOOLBAR", $tb->getHTML()); - $tpl->setContent($se_tpl->get()); - } - - /** - * Save self evaluation - * - * @param - * @return - */ - function saveSelfEvaluation() - { - $ilUser = $this->user; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("./Services/Skill/classes/class.ilSkillSelfEvaluation.php"); - - $se = new ilSkillSelfEvaluation(); - $se->setUserId($ilUser->getId()); - $se->setTopSkillId($_GET["sn_id"]); - if (is_array($_POST["se_sk"])) - { - $se->setLevels($_POST["se_sk"]); - } - $se->create(); - - $steps = ilSkillSelfEvaluation::determineSteps($this->sn_id); - $cstep = (int) $_GET["step"]; - - if (count($steps)) - { - $ilCtrl->setParameter($this, "step", 1); - $ilCtrl->setParameter($this, "se_id", $se->getId()); - $ilCtrl->redirect($this, "editSelfEvaluation"); - } - - ilUtil::sendInfo($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, ""); - } - - /** - * Edit self evaluation - * - * @param - * @return - */ - function editSelfEvaluation() - { - $this->startSelfEvaluation("edit"); - } - - /** - * Update self evaluation and go one step back - * - * @param - * @return - */ - function updateBackSelfEvaluation() - { - $this->updateSelfEvaluation(true); - } - - - - /** - * Update self evaluation - * - * @param - * @return - */ - function updateSelfEvaluation($a_back = false) - { - $ilUser = $this->user; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("./Services/Skill/classes/class.ilSkillSelfEvaluation.php"); - $se = new ilSkillSelfEvaluation((int) $_GET["se_id"]); - - if ($se->getUserId() == $ilUser->getId()) - { - $steps = ilSkillSelfEvaluation::determineSteps($this->sn_id); - $cstep = (int) $_GET["step"]; - - if (is_array($_POST["se_sk"])) - { - $se->setLevels($_POST["se_sk"], true); - } - $se->update(); - - if ($a_back) - { - $ilCtrl->setParameter($this, "step", (int) $_GET["step"] - 1); - $ilCtrl->setParameter($this, "se_id", $se->getId()); - $ilCtrl->redirect($this, "editSelfEvaluation"); - } - else if (count($steps) - 1 > $cstep) - { - $ilCtrl->setParameter($this, "step", (int) $_GET["step"] + 1); - $ilCtrl->setParameter($this, "se_id", $se->getId()); - $ilCtrl->redirect($this, "editSelfEvaluation"); - } - - ilUtil::sendInfo($lng->txt("msg_obj_modified"), true); - } - - $ilCtrl->redirect($this, ""); - } - - //// - //// Presentation view - //// - - /** - * Get presentation view - * - * @param - * @return - */ - function getPresentationView($a_user_id) - { - include_once("./Services/Skill/classes/class.ilSkillSelfEvaluation.php"); - $ses = ilSkillSelfEvaluation::getAllSelfEvaluationsOfUser($a_user_id); - - $html = ""; - foreach ($ses as $se) - { - $this->setSelfEvaluationPresentationForm($se); - $html.= $this->form->getHTML()."

                  "; - } - - return $html; - } - - /** - * Set self evaluation presentation form - */ - public function setSelfEvaluationPresentationForm($se) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - ilDatePresentation::setUseRelativeDates(false); - $dates = ", ". - $lng->txt("created").": ". - ilDatePresentation::formatDate( - new ilDateTime($se["created"], IL_CAL_DATETIME)); - if ($se["created"] != $se["last_update"]) - { - $dates.= ", ".$lng->txt("last_update").": ". - ilDatePresentation::formatDate( - new ilDateTime($se["last_update"], IL_CAL_DATETIME)); - } - ilDatePresentation::setUseRelativeDates(true); - - $se = new ilSkillSelfEvaluation($se["id"]); - $levels = $se->getLevels(); - - $this->form->setTitle($lng->txt("skmg_self_evaluation").$dates); - - include_once("./Services/Skill/classes/class.ilBasicSkill.php"); - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $stree = new ilSkillTree(); - - if ($stree->isInTree($se->getTopSkillId())) - { - $cnode = $stree->getNodeData($se->getTopSkillId()); - $childs = $stree->getSubTree($cnode); - foreach ($childs as $child) - { - if ($child["type"] == "skll") - { - // build title - $path = $stree->getPathFull($child["child"]); - $title = $sep = ""; - foreach ($path as $p) - { - if ($p["type"] != "skrt") - { - $title.= $sep.$p["title"]; - $sep = " > "; - } - } - - $sk = new ilBasicSkill($child["child"]); - $ls = $sk->getLevelData(); - - $ne = new ilNonEditableValueGUI($title, ""); - foreach ($ls as $ld) - { - if ($ld["id"] == $levels[$child["child"]]) - { - $ne->setValue($ld["title"]); - } - } - $this->form->addItem($ne); - } - } - } - - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilObjUser + */ + protected $user; + + /** + * Constructor + * + * @param + * @return + */ + public function __construct() + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + $this->toolbar = $DIC->toolbar(); + $this->user = $DIC->user(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $ilCtrl->saveParameter($this, array("se_id", "sn_id")); + $lng->loadLanguageModule("skmg"); + + $this->readSelfEvaluation(); + + $this->se_id = (int) $_GET["se_id"]; + $this->sn_id = ((int) $_POST["sn_id"] > 0) + ? (int) $_POST["sn_id"] + : (int) $_GET["sn_id"]; + $ilCtrl->setParameter($this, "sn_id", $this->sn_id); + } + + /** + * Execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $cmd = $ilCtrl->getCmd("listSelfEvaluations"); + $this->$cmd(); + } + + /** + * Read self_evaluation + * + * @param + * @return + */ + public function readSelfEvaluation() + { + // $this->self_evaluation = new ilSelfEvaluation((int) $_GET[save_param]); + } + + /** + * List all self evaluations + */ + public function listSelfEvaluations() + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); + + // desc + /*$ne = new ilNonEditableValueGUI($lng->txt("lang"), var); + $ne->setValue(); + $ne->setInfo(); + $this->form->addItem($ne);*/ + + // select skill for self evaluation + include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); + $se_nodes = ilSkillTreeNode::getAllSelfEvaluationNodes(); + foreach ($se_nodes as $n_id => $title) { + $options[$n_id] = $title; + } + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $si = new ilSelectInputGUI($lng->txt("skmg_please_select_self_skill"), "sn_id"); + $si->setOptions($options); + + //$si->setInfo($lng->txt("")); + $ilToolbar->addInputItem($si, true); + + $ilToolbar->addFormButton($lng->txt("skmg_execute_self_evaluation"), "startSelfEvaluation"); + + include_once("./Services/Skill/classes/class.ilSelfEvaluationTableGUI.php"); + $table = new ilSelfEvaluationTableGUI($this, "listSelfEvaluations"); + + $tpl->setContent($table->getHTML()); + } + + + /** + * Confirm self_evaluation deletion + */ + public function confirmSelfEvaluationDeletion() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + if (!is_array($_POST["id"]) || count($_POST["id"]) == 0) { + ilUtil::sendInfo($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "listSelfEvaluations"); + } else { + include_once("./Services/Skill/classes/class.ilSkillSelfEvaluation.php"); + include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("skmg_sure_delete_self_evaluation")); + $cgui->setCancel($lng->txt("cancel"), "listSelfEvaluations"); + $cgui->setConfirm($lng->txt("delete"), "deleteSelfEvaluation"); + + foreach ($_POST["id"] as $i) { + $se = new ilSkillSelfEvaluation((int) $i); + $se_title = + ilSkillTreeNode::_lookupTitle($se->getTopSkillId()); + $cgui->addItem("id[]", $i, $se_title . ", " . $lng->txt("created") . ": " . + $se->getCreated() . ", " . $lng->txt("last_update") . ": " . $se->getLastUpdate()); + } + + $tpl->setContent($cgui->getHTML()); + } + } + + /** + * Delete self_evaluation + * + * @param + * @return + */ + public function deleteSelfEvaluation() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilUser = $this->user; + + include_once("./Services/Skill/classes/class.ilSkillSelfEvaluation.php"); + if (is_array($_POST["id"])) { + foreach ($_POST["id"] as $i) { + $se = new ilSkillSelfEvaluation((int) $i); + if ($se->getUserId() == $ilUser->getId()) { + $se->delete(); + } + } + } + ilUtil::sendSuccess("msg_obj_modified"); + $ilCtrl->redirect($this, "listSelfEvaluations"); + } + + + /** + * startSelfEvaluation + * + * @param + * @return + */ + public function startSelfEvaluation($a_mode = "create") + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $se = null; + if ($a_mode == "edit") { + include_once("./Services/Skill/classes/class.ilSkillSelfEvaluation.php"); + $se = new ilSkillSelfEvaluation((int) $_GET["se_id"]); + $this->sn_id = $se->getTopSkillId(); + } + ilUtil::sendInfo($lng->txt("skmg_please_select_your_skill_levels")); + + $se_tpl = new ilTemplate("tpl.self_evaluation.html", true, true, "Services/Skill"); + include_once("./Services/Skill/classes/class.ilSkillSelfEvaluation.php"); + + $steps = ilSkillSelfEvaluation::determineSteps($this->sn_id); + $cstep = (int) $_GET["step"]; + $ilCtrl->setParameter($this, "step", $cstep); + include_once("./Services/Skill/classes/class.ilSkillSelfEvalSkillTableGUI.php"); + $table = new ilSkillSelfEvalSkillTableGUI( + $this, + "startSelfEvaluation", + $steps[$cstep], + $se + ); + + $se_tpl->setCurrentBlock("se_table"); + $se_tpl->setVariable("SE_TABLE", $table->getHTML()); + $se_tpl->parseCurrentBlock(); + + include_once("./Services/UIComponent/Toolbar/classes/class.ilToolbarGUI.php"); + $tb = new ilToolbarGUI(); + if ($a_mode == "edit") { + if ($cstep > 0) { + $tb->addFormButton("< " . $lng->txt("skmg_previous_step"), "updateBackSelfEvaluation"); + } + if ($cstep < count($steps) - 1) { + $tb->addFormButton($lng->txt("skmg_next_step") . " >", "updateSelfEvaluation"); + } elseif ($cstep == count($steps) - 1) { + $tb->addFormButton($lng->txt("skmg_save_self_evaluation"), "updateSelfEvaluation"); + } + } else { + if ($cstep < count($steps) - 1) { + $tb->addFormButton($lng->txt("skmg_next_step") . " >", "saveSelfEvaluation"); + } elseif ($cstep == count($steps) - 1) { + $tb->addFormButton($lng->txt("skmg_save_self_evaluation"), "saveSelfEvaluation"); + } + } + $se_tpl->setVariable("FORM_ACTION", $ilCtrl->getFormAction($this)); + $se_tpl->setVariable("TOOLBAR", $tb->getHTML()); + $tpl->setContent($se_tpl->get()); + } + + /** + * Save self evaluation + * + * @param + * @return + */ + public function saveSelfEvaluation() + { + $ilUser = $this->user; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("./Services/Skill/classes/class.ilSkillSelfEvaluation.php"); + + $se = new ilSkillSelfEvaluation(); + $se->setUserId($ilUser->getId()); + $se->setTopSkillId($_GET["sn_id"]); + if (is_array($_POST["se_sk"])) { + $se->setLevels($_POST["se_sk"]); + } + $se->create(); + + $steps = ilSkillSelfEvaluation::determineSteps($this->sn_id); + $cstep = (int) $_GET["step"]; + + if (count($steps)) { + $ilCtrl->setParameter($this, "step", 1); + $ilCtrl->setParameter($this, "se_id", $se->getId()); + $ilCtrl->redirect($this, "editSelfEvaluation"); + } + + ilUtil::sendInfo($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, ""); + } + + /** + * Edit self evaluation + * + * @param + * @return + */ + public function editSelfEvaluation() + { + $this->startSelfEvaluation("edit"); + } + + /** + * Update self evaluation and go one step back + * + * @param + * @return + */ + public function updateBackSelfEvaluation() + { + $this->updateSelfEvaluation(true); + } + + + + /** + * Update self evaluation + * + * @param + * @return + */ + public function updateSelfEvaluation($a_back = false) + { + $ilUser = $this->user; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("./Services/Skill/classes/class.ilSkillSelfEvaluation.php"); + $se = new ilSkillSelfEvaluation((int) $_GET["se_id"]); + + if ($se->getUserId() == $ilUser->getId()) { + $steps = ilSkillSelfEvaluation::determineSteps($this->sn_id); + $cstep = (int) $_GET["step"]; + + if (is_array($_POST["se_sk"])) { + $se->setLevels($_POST["se_sk"], true); + } + $se->update(); + + if ($a_back) { + $ilCtrl->setParameter($this, "step", (int) $_GET["step"] - 1); + $ilCtrl->setParameter($this, "se_id", $se->getId()); + $ilCtrl->redirect($this, "editSelfEvaluation"); + } elseif (count($steps) - 1 > $cstep) { + $ilCtrl->setParameter($this, "step", (int) $_GET["step"] + 1); + $ilCtrl->setParameter($this, "se_id", $se->getId()); + $ilCtrl->redirect($this, "editSelfEvaluation"); + } + + ilUtil::sendInfo($lng->txt("msg_obj_modified"), true); + } + + $ilCtrl->redirect($this, ""); + } + + //// + //// Presentation view + //// + + /** + * Get presentation view + * + * @param + * @return + */ + public function getPresentationView($a_user_id) + { + include_once("./Services/Skill/classes/class.ilSkillSelfEvaluation.php"); + $ses = ilSkillSelfEvaluation::getAllSelfEvaluationsOfUser($a_user_id); + + $html = ""; + foreach ($ses as $se) { + $this->setSelfEvaluationPresentationForm($se); + $html.= $this->form->getHTML() . "

                  "; + } + + return $html; + } + + /** + * Set self evaluation presentation form + */ + public function setSelfEvaluationPresentationForm($se) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + ilDatePresentation::setUseRelativeDates(false); + $dates = ", " . + $lng->txt("created") . ": " . + ilDatePresentation::formatDate( + new ilDateTime($se["created"], IL_CAL_DATETIME) + ); + if ($se["created"] != $se["last_update"]) { + $dates.= ", " . $lng->txt("last_update") . ": " . + ilDatePresentation::formatDate( + new ilDateTime($se["last_update"], IL_CAL_DATETIME) + ); + } + ilDatePresentation::setUseRelativeDates(true); + + $se = new ilSkillSelfEvaluation($se["id"]); + $levels = $se->getLevels(); + + $this->form->setTitle($lng->txt("skmg_self_evaluation") . $dates); + + include_once("./Services/Skill/classes/class.ilBasicSkill.php"); + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $stree = new ilSkillTree(); + + if ($stree->isInTree($se->getTopSkillId())) { + $cnode = $stree->getNodeData($se->getTopSkillId()); + $childs = $stree->getSubTree($cnode); + foreach ($childs as $child) { + if ($child["type"] == "skll") { + // build title + $path = $stree->getPathFull($child["child"]); + $title = $sep = ""; + foreach ($path as $p) { + if ($p["type"] != "skrt") { + $title.= $sep . $p["title"]; + $sep = " > "; + } + } + + $sk = new ilBasicSkill($child["child"]); + $ls = $sk->getLevelData(); + + $ne = new ilNonEditableValueGUI($title, ""); + foreach ($ls as $ld) { + if ($ld["id"] == $levels[$child["child"]]) { + $ne->setValue($ld["title"]); + } + } + $this->form->addItem($ne); + } + } + } + } } - -?> diff --git a/Services/Skill/classes/class.ilSkillTemplateCategory.php b/Services/Skill/classes/class.ilSkillTemplateCategory.php index 7920411478dfa40a83e9aeae42bd1b9af034f98d..a448547b4bdf0aacc9ffb1cf537fc0c272b901b9 100644 --- a/Services/Skill/classes/class.ilSkillTemplateCategory.php +++ b/Services/Skill/classes/class.ilSkillTemplateCategory.php @@ -14,31 +14,29 @@ include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); */ class ilSkillTemplateCategory extends ilSkillTreeNode { - var $id; + public $id; - /** - * Constructor - * @access public - */ - function __construct($a_id = 0) - { - parent::__construct($a_id); - $this->setType("sctp"); - } + /** + * Constructor + * @access public + */ + public function __construct($a_id = 0) + { + parent::__construct($a_id); + $this->setType("sctp"); + } - /** - * Copy skill category - */ - function copy() - { - $sctp = new ilSkillTemplateCategory(); - $sctp->setTitle($this->getTitle()); - $sctp->setType($this->getType()); - $sctp->setOrderNr($this->getOrderNr()); - $sctp->create(); - - return $sctp; - } + /** + * Copy skill category + */ + public function copy() + { + $sctp = new ilSkillTemplateCategory(); + $sctp->setTitle($this->getTitle()); + $sctp->setType($this->getType()); + $sctp->setOrderNr($this->getOrderNr()); + $sctp->create(); + return $sctp; + } } -?> diff --git a/Services/Skill/classes/class.ilSkillTemplateCategoryGUI.php b/Services/Skill/classes/class.ilSkillTemplateCategoryGUI.php index 20bebae0c2f3563398427355f6be19753af5932a..c806f6ef7de17a4f37ff3fdabb6d0fcd292d9a16 100644 --- a/Services/Skill/classes/class.ilSkillTemplateCategoryGUI.php +++ b/Services/Skill/classes/class.ilSkillTemplateCategoryGUI.php @@ -16,317 +16,331 @@ include_once("./Services/Skill/classes/class.ilSkillTemplateCategory.php"); */ class ilSkillTemplateCategoryGUI extends ilSkillTreeNodeGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilHelpGUI - */ - protected $help; - - - /** - * Constructor - */ - function __construct($a_node_id = 0, $a_tref_id) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->tpl = $DIC["tpl"]; - $this->tabs = $DIC->tabs(); - $this->lng = $DIC->language(); - $this->help = $DIC["ilHelp"]; - $ilCtrl = $DIC->ctrl(); - - $ilCtrl->saveParameter($this, "obj_id"); - $this->tref_id = $a_tref_id; - - parent::__construct($a_node_id); - } - - /** - * Get Node Type - */ - function getType() - { - return "sctp"; - } - - /** - * Execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - //$tpl->getStandardTemplate(); - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd(); - - switch($next_class) - { - default: - $ret = $this->$cmd(); - break; - } - } - - /** - * output tabs - */ - function setTabs($a_tab) - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - $ilHelp = $this->help; - - $ilTabs->clearTargets(); - $ilHelp->setScreenIdComponent("skmg_sctp"); - - // content - $ilTabs->addTab("content", $lng->txt("content"), - $ilCtrl->getLinkTarget($this, 'listItems')); - - - // properties - if ($this->tref_id == 0) - { - $ilTabs->addTab("properties", $lng->txt("settings"), - $ilCtrl->getLinkTarget($this, 'editProperties')); - } - - // usage - $this->addUsageTab($ilTabs); - - // back link - if ($this->tref_id == 0) - { - $ilCtrl->setParameterByClass("ilskillrootgui", "obj_id", - $this->node_object->skill_tree->getRootId()); - $ilTabs->setBackTarget($lng->txt("skmg_skill_templates"), - $ilCtrl->getLinkTargetByClass("ilskillrootgui", "listTemplates")); - $ilCtrl->setParameterByClass("ilskillrootgui", "obj_id", - $_GET["obj_id"]); - } + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilHelpGUI + */ + protected $help; + + + /** + * Constructor + */ + public function __construct($a_node_id = 0, $a_tref_id) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->tpl = $DIC["tpl"]; + $this->tabs = $DIC->tabs(); + $this->lng = $DIC->language(); + $this->help = $DIC["ilHelp"]; + $ilCtrl = $DIC->ctrl(); + + $ilCtrl->saveParameter($this, "obj_id"); + $this->tref_id = $a_tref_id; + + parent::__construct($a_node_id); + } + + /** + * Get Node Type + */ + public function getType() + { + return "sctp"; + } + + /** + * Execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + //$tpl->getStandardTemplate(); + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd(); + + switch ($next_class) { + default: + $ret = $this->$cmd(); + break; + } + } + + /** + * output tabs + */ + public function setTabs($a_tab) + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + $ilHelp = $this->help; + + $ilTabs->clearTargets(); + $ilHelp->setScreenIdComponent("skmg_sctp"); + + // content + $ilTabs->addTab( + "content", + $lng->txt("content"), + $ilCtrl->getLinkTarget($this, 'listItems') + ); + + + // properties + if ($this->tref_id == 0) { + $ilTabs->addTab( + "properties", + $lng->txt("settings"), + $ilCtrl->getLinkTarget($this, 'editProperties') + ); + } + + // usage + $this->addUsageTab($ilTabs); + + // back link + if ($this->tref_id == 0) { + $ilCtrl->setParameterByClass( + "ilskillrootgui", + "obj_id", + $this->node_object->skill_tree->getRootId() + ); + $ilTabs->setBackTarget( + $lng->txt("skmg_skill_templates"), + $ilCtrl->getLinkTargetByClass("ilskillrootgui", "listTemplates") + ); + $ilCtrl->setParameterByClass( + "ilskillrootgui", + "obj_id", + $_GET["obj_id"] + ); + } - parent::setTitleIcon(); - $tpl->setTitle( - $lng->txt("skmg_sctp").": ".$this->node_object->getTitle()); - $this->setSkillNodeDescription(); - - $ilTabs->activateTab($a_tab); - - } - - /** - * Init form. - * - * @param string $a_mode edit mode - */ - public function initForm($a_mode = "edit") - { - $r = parent::initForm($a_mode); - if ($a_mode == "create") - { - $ni = $this->form->getItemByPostVar("order_nr"); - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $tree = new ilSkillTree(); - $max = $tree->getMaxOrderNr((int)$_GET["obj_id"], true); - $ni->setValue($max + 10); - } - return $r; - } - - /** - * List items - * - * @param - * @return - */ - function listItems() - { - $tpl = $this->tpl; - $lng = $this->lng; - - if ($this->isInUse()) - { - ilUtil::sendInfo($lng->txt("skmg_skill_in_use")); - } - - if ($this->checkPermissionBool("write")) - { - if ($this->tref_id == 0) - { - self::addCreationButtons(); - } - } - - $this->setTabs("content"); - - include_once("./Services/Skill/classes/class.ilSkillCatTableGUI.php"); - $table = new ilSkillCatTableGUI($this, "listItems", (int) $_GET["obj_id"], - ilSkillCatTableGUI::MODE_SCTP, $this->tref_id); - - $tpl->setContent($table->getHTML()); - } - - /** - * Add creation buttons - * - * @param - * @return - */ - static function addCreationButtons() - { - global $DIC; - - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilToolbar = $DIC->toolbar(); - $ilUser = $DIC->user(); - - $ilCtrl->setParameterByClass("ilobjskillmanagementgui", "tmpmode", 1); - - $ilCtrl->setParameterByClass("ilbasicskilltemplategui", - "obj_id", (int) $_GET["obj_id"]); - $ilToolbar->addButton($lng->txt("skmg_create_skill_template"), - $ilCtrl->getLinkTargetByClass("ilbasicskilltemplategui", "create")); - $ilCtrl->setParameterByClass("ilskilltemplatecategorygui", - "obj_id", (int) $_GET["obj_id"]); - $ilToolbar->addButton($lng->txt("skmg_create_skill_template_category"), - $ilCtrl->getLinkTargetByClass("ilskilltemplatecategorygui", "create")); - - // skill templates from clipboard - $sep = false; - if ($ilUser->clipboardHasObjectsOfType("sktp")) - { - $ilToolbar->addSeparator(); - $sep = true; - $ilToolbar->addButton($lng->txt("skmg_insert_skill_template_from_clip"), - $ilCtrl->getLinkTargetByClass("ilskilltemplatecategorygui", "insertSkillTemplateClip")); - } - - // template categories from clipboard - if ($ilUser->clipboardHasObjectsOfType("sctp")) - { - if (!$sep) - { - $ilToolbar->addSeparator(); - $sep = true; - } - $ilToolbar->addButton($lng->txt("skmg_insert_template_category_from_clip"), - $ilCtrl->getLinkTargetByClass("ilskilltemplatecategorygui", "insertTemplateCategoryClip")); - } - - } - - /** - * Edit properties - */ - function editProperties() - { - $this->setTabs("properties"); - parent::editProperties(); - } - - - /** - * Save item - */ - function saveItem() - { - if (!$this->checkPermissionBool("write")) - { - return; - } - - $it = new ilSkillTemplateCategory(); - $it->setTitle($this->form->getInput("title")); - $it->setOrderNr($this->form->getInput("order_nr")); - $it->create(); - ilSkillTreeNode::putInTree($it, (int) $_GET["obj_id"], IL_LAST_NODE); - } - - /** - * Update item - */ - function updateItem() - { - if (!$this->checkPermissionBool("write")) - { - return; - } - - $this->node_object->setTitle($this->form->getInput("title")); - $this->node_object->setOrderNr($this->form->getInput("order_nr")); - $this->node_object->setSelfEvaluation($_POST["self_eval"]); - $this->node_object->update(); - } - - /** - * After saving - */ - function afterSave() - { - $this->redirectToParent(true); - } - - /** - * Show skill usage - */ - function showUsage() - { - $tpl = $this->tpl; - - // (a) referenced skill template category in main tree - if ($this->tref_id > 0) - { - return parent::showUsage(); - } - - // (b) skill template category in templates view - - $this->setTabs("usage"); - - include_once("./Services/Skill/classes/class.ilSkillUsage.php"); - $usage_info = new ilSkillUsage(); - $usages = $usage_info->getAllUsagesOfTemplate((int) $_GET["obj_id"]); - - $html = ""; - include_once("./Services/Skill/classes/class.ilSkillUsageTableGUI.php"); - foreach ($usages as $k => $usage) - { - $tab = new ilSkillUsageTableGUI($this, "showUsage", $k, $usage); - $html.= $tab->getHTML()."

                  "; - } - - $tpl->setContent($html); - } - - + parent::setTitleIcon(); + $tpl->setTitle( + $lng->txt("skmg_sctp") . ": " . $this->node_object->getTitle() + ); + $this->setSkillNodeDescription(); + + $ilTabs->activateTab($a_tab); + } + + /** + * Init form. + * + * @param string $a_mode edit mode + */ + public function initForm($a_mode = "edit") + { + $r = parent::initForm($a_mode); + if ($a_mode == "create") { + $ni = $this->form->getItemByPostVar("order_nr"); + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $tree = new ilSkillTree(); + $max = $tree->getMaxOrderNr((int) $_GET["obj_id"], true); + $ni->setValue($max + 10); + } + return $r; + } + + /** + * List items + * + * @param + * @return + */ + public function listItems() + { + $tpl = $this->tpl; + $lng = $this->lng; + + if ($this->isInUse()) { + ilUtil::sendInfo($lng->txt("skmg_skill_in_use")); + } + + if ($this->checkPermissionBool("write")) { + if ($this->tref_id == 0) { + self::addCreationButtons(); + } + } + + $this->setTabs("content"); + + include_once("./Services/Skill/classes/class.ilSkillCatTableGUI.php"); + $table = new ilSkillCatTableGUI( + $this, + "listItems", + (int) $_GET["obj_id"], + ilSkillCatTableGUI::MODE_SCTP, + $this->tref_id + ); + + $tpl->setContent($table->getHTML()); + } + + /** + * Add creation buttons + * + * @param + * @return + */ + public static function addCreationButtons() + { + global $DIC; + + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilToolbar = $DIC->toolbar(); + $ilUser = $DIC->user(); + + $ilCtrl->setParameterByClass("ilobjskillmanagementgui", "tmpmode", 1); + + $ilCtrl->setParameterByClass( + "ilbasicskilltemplategui", + "obj_id", + (int) $_GET["obj_id"] + ); + $ilToolbar->addButton( + $lng->txt("skmg_create_skill_template"), + $ilCtrl->getLinkTargetByClass("ilbasicskilltemplategui", "create") + ); + $ilCtrl->setParameterByClass( + "ilskilltemplatecategorygui", + "obj_id", + (int) $_GET["obj_id"] + ); + $ilToolbar->addButton( + $lng->txt("skmg_create_skill_template_category"), + $ilCtrl->getLinkTargetByClass("ilskilltemplatecategorygui", "create") + ); + + // skill templates from clipboard + $sep = false; + if ($ilUser->clipboardHasObjectsOfType("sktp")) { + $ilToolbar->addSeparator(); + $sep = true; + $ilToolbar->addButton( + $lng->txt("skmg_insert_skill_template_from_clip"), + $ilCtrl->getLinkTargetByClass("ilskilltemplatecategorygui", "insertSkillTemplateClip") + ); + } + + // template categories from clipboard + if ($ilUser->clipboardHasObjectsOfType("sctp")) { + if (!$sep) { + $ilToolbar->addSeparator(); + $sep = true; + } + $ilToolbar->addButton( + $lng->txt("skmg_insert_template_category_from_clip"), + $ilCtrl->getLinkTargetByClass("ilskilltemplatecategorygui", "insertTemplateCategoryClip") + ); + } + } + + /** + * Edit properties + */ + public function editProperties() + { + $this->setTabs("properties"); + parent::editProperties(); + } + + + /** + * Save item + */ + public function saveItem() + { + if (!$this->checkPermissionBool("write")) { + return; + } + + $it = new ilSkillTemplateCategory(); + $it->setTitle($this->form->getInput("title")); + $it->setOrderNr($this->form->getInput("order_nr")); + $it->create(); + ilSkillTreeNode::putInTree($it, (int) $_GET["obj_id"], IL_LAST_NODE); + } + + /** + * Update item + */ + public function updateItem() + { + if (!$this->checkPermissionBool("write")) { + return; + } + + $this->node_object->setTitle($this->form->getInput("title")); + $this->node_object->setOrderNr($this->form->getInput("order_nr")); + $this->node_object->setSelfEvaluation($_POST["self_eval"]); + $this->node_object->update(); + } + + /** + * After saving + */ + public function afterSave() + { + $this->redirectToParent(true); + } + + /** + * Show skill usage + */ + public function showUsage() + { + $tpl = $this->tpl; + + // (a) referenced skill template category in main tree + if ($this->tref_id > 0) { + return parent::showUsage(); + } + + // (b) skill template category in templates view + + $this->setTabs("usage"); + + include_once("./Services/Skill/classes/class.ilSkillUsage.php"); + $usage_info = new ilSkillUsage(); + $usages = $usage_info->getAllUsagesOfTemplate((int) $_GET["obj_id"]); + + $html = ""; + include_once("./Services/Skill/classes/class.ilSkillUsageTableGUI.php"); + foreach ($usages as $k => $usage) { + $tab = new ilSkillUsageTableGUI($this, "showUsage", $k, $usage); + $html.= $tab->getHTML() . "

                  "; + } + + $tpl->setContent($html); + } } - -?> \ No newline at end of file diff --git a/Services/Skill/classes/class.ilSkillTemplateGUI.php b/Services/Skill/classes/class.ilSkillTemplateGUI.php index 514bd251379a0344b56b327e70c516f2c725397a..d825592e4cbbb2efe66aab6a3bf863342770b15d 100644 --- a/Services/Skill/classes/class.ilSkillTemplateGUI.php +++ b/Services/Skill/classes/class.ilSkillTemplateGUI.php @@ -15,103 +15,100 @@ include_once("./Services/Skill/classes/class.ilSkillTreeNodeGUI.php"); */ class ilSkillTemplateGUI extends ilSkillTreeNodeGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilLanguage - */ - protected $lng; - - - /** - * Constructor - */ - function __construct($a_node_id = 0) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->tpl = $DIC["tpl"]; - $this->tabs = $DIC->tabs(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - - $ilCtrl->saveParameter($this, "obj_id"); - - parent::__construct($a_node_id); - } - - /** - * Get Node Type - */ - function getType() - { - return "stmp"; - } - - /** - * Execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - //$tpl->getStandardTemplate(); - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd(); - - switch($next_class) - { - default: - $ret = $this->$cmd(); - break; - } - } - - /** - * output tabs - */ - function setTabs() - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - $tpl->setTitleIcon(ilUtil::getImagePath("icon_skmg.svg")); - $tpl->setTitle( - $lng->txt("skmg_skill_template").": ".$this->node_object->getTitle()); - } - - - /** - * Perform drag and drop action - */ - function proceedDragDrop() - { - $ilCtrl = $this->ctrl; - -// $this->slm_object->executeDragDrop($_POST["il_hform_source_id"], $_POST["il_hform_target_id"], + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilLanguage + */ + protected $lng; + + + /** + * Constructor + */ + public function __construct($a_node_id = 0) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->tpl = $DIC["tpl"]; + $this->tabs = $DIC->tabs(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + + $ilCtrl->saveParameter($this, "obj_id"); + + parent::__construct($a_node_id); + } + + /** + * Get Node Type + */ + public function getType() + { + return "stmp"; + } + + /** + * Execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + //$tpl->getStandardTemplate(); + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd(); + + switch ($next_class) { + default: + $ret = $this->$cmd(); + break; + } + } + + /** + * output tabs + */ + public function setTabs() + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + $tpl->setTitleIcon(ilUtil::getImagePath("icon_skmg.svg")); + $tpl->setTitle( + $lng->txt("skmg_skill_template") . ": " . $this->node_object->getTitle() + ); + } + + + /** + * Perform drag and drop action + */ + public function proceedDragDrop() + { + $ilCtrl = $this->ctrl; + + // $this->slm_object->executeDragDrop($_POST["il_hform_source_id"], $_POST["il_hform_target_id"], // $_POST["il_hform_fc"], $_POST["il_hform_as_subitem"]); // $ilCtrl->redirect($this, "showOrganization"); - } - + } } - -?> \ No newline at end of file diff --git a/Services/Skill/classes/class.ilSkillTemplateReference.php b/Services/Skill/classes/class.ilSkillTemplateReference.php index a3c9656fb2dfffc524c4bae6d3cb28ce3dc83b91..9781972ce24914ff5d7191a18c47b7e6273f01fc 100644 --- a/Services/Skill/classes/class.ilSkillTemplateReference.php +++ b/Services/Skill/classes/class.ilSkillTemplateReference.php @@ -14,181 +14,182 @@ include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); */ class ilSkillTemplateReference extends ilSkillTreeNode { - /** - * @var ilDB - */ - protected $db; - - var $id; - - /** - * Constructor - * @access public - */ - function __construct($a_id = 0) - { - global $DIC; - - $this->db = $DIC->database(); - parent::__construct($a_id); - $this->setType("sktr"); - } - - /** - * Set skill template id - * - * @param int $a_val skill template id - */ - function setSkillTemplateId($a_val) - { - $this->skill_template_id = $a_val; - } - - /** - * Get skill template id - * - * @return int skill template id - */ - function getSkillTemplateId() - { - return $this->skill_template_id; - } - - /** - * Read data from database - */ - function read() - { - $ilDB = $this->db; - - parent::read(); - - $set = $ilDB->query("SELECT * FROM skl_templ_ref ". - " WHERE skl_node_id = ".$ilDB->quote($this->getId(), "integer") - ); - $rec = $ilDB->fetchAssoc($set); - $this->setSkillTemplateId((int) $rec["templ_id"]); - } - - /** - * Create skill template reference - */ - function create() - { - $ilDB = $this->db; - - parent::create(); - - $ilDB->manipulate("INSERT INTO skl_templ_ref ". - "(skl_node_id, templ_id) VALUES (". - $ilDB->quote($this->getId(), "integer").",". - $ilDB->quote($this->getSkillTemplateId(), "integer"). - ")"); - } - - /** - * Update node - */ - function update() - { - $ilDB = $this->db; - - parent::update(); - - $ilDB->manipulate("UPDATE skl_templ_ref SET ". - " templ_id = ".$ilDB->quote($this->getSkillTemplateId(), "integer"). - " WHERE skl_node_id = ".$ilDB->quote($this->getId(), "integer") - ); - } - - - /** - * Delete skill - */ - function delete() - { - $ilDB = $this->db; - - $ilDB->manipulate("DELETE FROM skl_templ_ref WHERE " - ." skl_node_id = ".$ilDB->quote($this->getId(), "integer") - ); - - parent::delete(); - } - - /** - * Copy basic skill template - */ - function copy() - { - $sktr = new ilSkillTemplateReference(); - $sktr->setTitle($this->getTitle()); - $sktr->setType($this->getType()); - $sktr->setSkillTemplateId($this->getSkillTemplateId()); - $sktr->setSelfEvaluation($this->getSelfEvaluation()); - $sktr->setOrderNr($this->getOrderNr()); - $sktr->create(); - - return $sktr; - } - - /** - * Lookup template ID - * - * @param int node ID - * @return string template ID - */ - static function _lookupTemplateId($a_obj_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT templ_id FROM skl_templ_ref WHERE skl_node_id = ". - $ilDB->quote($a_obj_id, "integer"); - $obj_set = $ilDB->query($query); - $obj_rec = $ilDB->fetchAssoc($obj_set); - - return $obj_rec["templ_id"]; - } - - /** - * Lookup tref ids for template id - * - * @param $a_template_id (top) template node id - * @return array array of integer tref ids - */ - static function _lookupTrefIdsForTopTemplateId($a_template_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT * FROM skl_templ_ref ". - " WHERE templ_id = ".$ilDB->quote($a_template_id, "integer") - ); - $trefs = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $trefs[] = $rec["skl_node_id"]; - } - return $trefs; - } - - - /** - * Get all tref ids for a template id - * - * @param int $a_tid template node id (node id in template tree) - * @return array of ids - */ - static function _lookupTrefIdsForTemplateId($a_tid) - { - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $tree = new ilSkillTree(); - $top_template_id = $tree->getTopParentNodeId($a_tid); - return self::_lookupTrefIdsForTopTemplateId($top_template_id); - } - + /** + * @var ilDB + */ + protected $db; + + public $id; + + /** + * Constructor + * @access public + */ + public function __construct($a_id = 0) + { + global $DIC; + + $this->db = $DIC->database(); + parent::__construct($a_id); + $this->setType("sktr"); + } + + /** + * Set skill template id + * + * @param int $a_val skill template id + */ + public function setSkillTemplateId($a_val) + { + $this->skill_template_id = $a_val; + } + + /** + * Get skill template id + * + * @return int skill template id + */ + public function getSkillTemplateId() + { + return $this->skill_template_id; + } + + /** + * Read data from database + */ + public function read() + { + $ilDB = $this->db; + + parent::read(); + + $set = $ilDB->query( + "SELECT * FROM skl_templ_ref " . + " WHERE skl_node_id = " . $ilDB->quote($this->getId(), "integer") + ); + $rec = $ilDB->fetchAssoc($set); + $this->setSkillTemplateId((int) $rec["templ_id"]); + } + + /** + * Create skill template reference + */ + public function create() + { + $ilDB = $this->db; + + parent::create(); + + $ilDB->manipulate("INSERT INTO skl_templ_ref " . + "(skl_node_id, templ_id) VALUES (" . + $ilDB->quote($this->getId(), "integer") . "," . + $ilDB->quote($this->getSkillTemplateId(), "integer") . + ")"); + } + + /** + * Update node + */ + public function update() + { + $ilDB = $this->db; + + parent::update(); + + $ilDB->manipulate( + "UPDATE skl_templ_ref SET " . + " templ_id = " . $ilDB->quote($this->getSkillTemplateId(), "integer") . + " WHERE skl_node_id = " . $ilDB->quote($this->getId(), "integer") + ); + } + + + /** + * Delete skill + */ + public function delete() + { + $ilDB = $this->db; + + $ilDB->manipulate( + "DELETE FROM skl_templ_ref WHERE " + . " skl_node_id = " . $ilDB->quote($this->getId(), "integer") + ); + + parent::delete(); + } + + /** + * Copy basic skill template + */ + public function copy() + { + $sktr = new ilSkillTemplateReference(); + $sktr->setTitle($this->getTitle()); + $sktr->setType($this->getType()); + $sktr->setSkillTemplateId($this->getSkillTemplateId()); + $sktr->setSelfEvaluation($this->getSelfEvaluation()); + $sktr->setOrderNr($this->getOrderNr()); + $sktr->create(); + + return $sktr; + } + + /** + * Lookup template ID + * + * @param int node ID + * @return string template ID + */ + public static function _lookupTemplateId($a_obj_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT templ_id FROM skl_templ_ref WHERE skl_node_id = " . + $ilDB->quote($a_obj_id, "integer"); + $obj_set = $ilDB->query($query); + $obj_rec = $ilDB->fetchAssoc($obj_set); + + return $obj_rec["templ_id"]; + } + + /** + * Lookup tref ids for template id + * + * @param $a_template_id (top) template node id + * @return array array of integer tref ids + */ + public static function _lookupTrefIdsForTopTemplateId($a_template_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT * FROM skl_templ_ref " . + " WHERE templ_id = " . $ilDB->quote($a_template_id, "integer") + ); + $trefs = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $trefs[] = $rec["skl_node_id"]; + } + return $trefs; + } + + + /** + * Get all tref ids for a template id + * + * @param int $a_tid template node id (node id in template tree) + * @return array of ids + */ + public static function _lookupTrefIdsForTemplateId($a_tid) + { + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $tree = new ilSkillTree(); + $top_template_id = $tree->getTopParentNodeId($a_tid); + return self::_lookupTrefIdsForTopTemplateId($top_template_id); + } } -?> diff --git a/Services/Skill/classes/class.ilSkillTemplateReferenceGUI.php b/Services/Skill/classes/class.ilSkillTemplateReferenceGUI.php index 19f3605d4868c61eaaaac62f1383d5124806aa2b..f4c2a4df8b9413cb2909302e9e315e8980320090 100644 --- a/Services/Skill/classes/class.ilSkillTemplateReferenceGUI.php +++ b/Services/Skill/classes/class.ilSkillTemplateReferenceGUI.php @@ -16,366 +16,363 @@ include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); class ilSkillTemplateReferenceGUI extends ilBasicSkillTemplateGUI { - /** - * Constructor - */ - function __construct($a_tref_id = 0) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->tpl = $DIC["tpl"]; - $this->tabs = $DIC->tabs(); - $this->lng = $DIC->language(); - $this->help = $DIC["ilHelp"]; - $ilCtrl = $DIC->ctrl(); - - $ilCtrl->saveParameter($this, "obj_id"); - $ilCtrl->saveParameter($this, "tref_id"); - - parent::__construct($a_tref_id); - - $this->tref_id = $a_tref_id; - if (is_object($this->node_object)) - { - $this->base_skill_id = $this->node_object->getSkillTemplateId(); - } - } - - /** - * Get Node Type - */ - function getType() - { - return "sktr"; - } - - /** - * Execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - //$tpl->getStandardTemplate(); - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd(); - - switch($next_class) - { - default: - $ret = $this->$cmd(); - break; - } - } - - /** - * output tabs - */ - function setTabs($a_tab = "") - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - $ilHelp = $this->help; - - $ilTabs->clearTargets(); - $ilHelp->setScreenIdComponent("skmg_sktr"); - - if (is_object($this->node_object)) - { - $sk_id = $this->node_object->getSkillTemplateId(); - $obj_type = ilSkillTreeNode::_lookupType($sk_id); - - if ($obj_type == "sctp") - { - // content - $ilTabs->addTab("content", $lng->txt("content"), - $ilCtrl->getLinkTarget($this, 'listItems')); - } - else - { - // content - $ilTabs->addTab("content", $lng->txt("skmg_skill_levels"), - $ilCtrl->getLinkTarget($this, 'listItems')); - } - - // properties - $ilTabs->addTab("properties", $lng->txt("settings"), - $ilCtrl->getLinkTarget($this, 'editProperties')); - - // usage - $this->addUsageTab($ilTabs); - - // back link -/* - $ilCtrl->setParameterByClass("ilskillrootgui", "obj_id", - $this->node_object->skill_tree->getRootId()); - $ilTabs->setBackTarget($lng->txt("obj_skmg"), - $ilCtrl->getLinkTargetByClass("ilskillrootgui", "listSkills")); - $ilCtrl->setParameterByClass("ilskillrootgui", "obj_id", - $_GET["obj_id"]);*/ - - $tid = ilSkillTemplateReference::_lookupTemplateId($this->node_object->getId()); - $add = " (".ilSkillTreeNode::_lookupTitle($tid).")"; - - parent::setTitleIcon(); - $tpl->setTitle( - $lng->txt("skmg_sktr").": ".$this->node_object->getTitle().$add); - $this->setSkillNodeDescription(); - - $ilTabs->activateTab($a_tab); - } - } - - /** - * Insert - * - * @param - * @return - */ - function insert() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - - $ilCtrl->saveParameter($this, "parent_id"); - $ilCtrl->saveParameter($this, "target"); - $this->initForm("create"); - $tpl->setContent($this->form->getHTML()); - } - - - /** - * Edit properties - */ - function editProperties() - { - $tpl = $this->tpl; - - $this->setTabs("properties"); - - $this->initForm(); - $this->getValues(); - $tpl->setContent($this->form->getHTML()); - } - - /** - * Init form. - * - * @param int $a_mode Edit Mode - */ - public function initForm($a_mode = "edit") - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - // select skill template - include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); - $tmplts = ilSkillTreeNode::getTopTemplates(); - - // title - $ti = new ilTextInputGUI($lng->txt("title"), "title"); - $ti->setRequired(true); - $this->form->addItem($ti); - - // order nr - $ni = new ilNumberInputGUI($lng->txt("skmg_order_nr"), "order_nr"); - $ni->setInfo($lng->txt("skmg_order_nr_info")); - $ni->setMaxLength(6); - $ni->setSize(6); - $ni->setRequired(true); - if ($a_mode == "create") - { - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $tree = new ilSkillTree(); - $max = $tree->getMaxOrderNr((int)$_GET["obj_id"]); - $ni->setValue($max + 10); - } - $this->form->addItem($ni); - - // template - $options = array( - "" => $lng->txt("please_select"), - ); - foreach ($tmplts as $tmplt) - { - $options[$tmplt["child"]] = $tmplt["title"]; - } - if ($a_mode != "edit") - { - $si = new ilSelectInputGUI($lng->txt("skmg_skill_template"), "skill_template_id"); - $si->setOptions($options); - $si->setRequired(true); - $this->form->addItem($si); - } - else - { - $ne = new ilNonEditableValueGUI($lng->txt("skmg_skill_template"), ""); - $ne->setValue($options[$this->node_object->getSkillTemplateId()]); - $this->form->addItem($ne); - } - - // status - $this->addStatusInput($this->form); - - // selectable - $cb = new ilCheckboxInputGUI($lng->txt("skmg_selectable"), "selectable"); - $cb->setInfo($lng->txt("skmg_selectable_info")); - $this->form->addItem($cb); - - if ($this->checkPermissionBool("write")) - { - if ($a_mode == "create") - { - $this->form->addCommandButton("save", $lng->txt("save")); - $this->form->addCommandButton("cancel", $lng->txt("cancel")); - $this->form->setTitle($lng->txt("skmg_new_sktr")); - } else - { - $this->form->addCommandButton("updateSkillTemplateReference", $lng->txt("save")); - $this->form->setTitle($lng->txt("skmg_edit_sktr")); - } - } - - $this->form->setFormAction($ilCtrl->getFormAction($this)); - } - - /** - * Get current values for from - */ - public function getValues() - { - $values = array(); - $values["skill_template_id"] = $this->node_object->getSkillTemplateId(); - $values["title"] = $this->node_object->getTitle(); - $values["selectable"] = $this->node_object->getSelfEvaluation(); - $values["status"] = $this->node_object->getStatus(); - $values["order_nr"] = $this->node_object->getOrderNr(); - $this->form->setValuesByArray($values); - } - - /** - * Save item - */ - function saveItem() - { - if (!$this->checkPermissionBool("write")) - { - return; - } - - $sktr = new ilSkillTemplateReference(); - $sktr->setTitle($_POST["title"]); - $sktr->setSkillTemplateId($_POST["skill_template_id"]); - $sktr->setSelfEvaluation($_POST["selectable"]); - $sktr->setOrderNr($_POST["order_nr"]); - $sktr->setStatus($_POST["status"]); - $sktr->create(); - ilSkillTreeNode::putInTree($sktr, (int) $_GET["obj_id"], IL_LAST_NODE); - $this->node_object = $sktr; - } - - /** - * After saving - */ - function afterSave() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameterByClass("ilskilltemplatereferencegui", "tref_id", - $this->node_object->getId()); - $ilCtrl->setParameterByClass("ilskilltemplatereferencegui", "obj_id", - $this->node_object->getSkillTemplateId()); - $ilCtrl->redirectByClass("ilskilltemplatereferencegui", "listItems"); - } - - /** - * Update form - */ - function updateSkillTemplateReference() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - - if (!$this->checkPermissionBool("write")) - { - return; - } - - $this->initForm("edit"); - if ($this->form->checkInput()) - { - // perform update -// $this->node_object->setSkillTemplateId($_POST["skill_template_id"]); - $this->node_object->setTitle($_POST["title"]); - $this->node_object->setSelfEvaluation($_POST["selectable"]); - $this->node_object->setOrderNr($_POST["order_nr"]); - $this->node_object->setStatus($_POST["status"]); - $this->node_object->update(); - - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "editProperties"); - } - - $this->form->setValuesByPost(); - $tpl->setContent($this->form->getHtml()); - } - - /** - * Cancel - * - * @param - * @return - */ - function cancel() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirectByClass("ilobjskillmanagementgui", "editSkills"); - } - - /** - * List items - */ - function listItems() - { - $tpl = $this->tpl; - $lng = $this->lng; - - if ($this->isInUse()) - { - ilUtil::sendInfo($lng->txt("skmg_skill_in_use")); - } - - $this->setTabs("content"); - - $sk_id = $this->node_object->getSkillTemplateId(); - $obj_type = ilSkillTreeNode::_lookupType($sk_id); - - if ($obj_type == "sctp") - { - include_once("./Services/Skill/classes/class.ilSkillCatTableGUI.php"); - $table = new ilSkillCatTableGUI($this, "listItems", (int) $sk_id, - ilSkillCatTableGUI::MODE_SCTP, $this->node_object->getId()); - $tpl->setContent($table->getHTML()); - } - else if ($obj_type == "sktp") - { - include_once("./Services/Skill/classes/class.ilSkillLevelTableGUI.php"); - $table = new ilSkillLevelTableGUI((int) $sk_id, $this, "edit", $this->node_object->getId()); - $tpl->setContent($table->getHTML()); - } - } - + /** + * Constructor + */ + public function __construct($a_tref_id = 0) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->tpl = $DIC["tpl"]; + $this->tabs = $DIC->tabs(); + $this->lng = $DIC->language(); + $this->help = $DIC["ilHelp"]; + $ilCtrl = $DIC->ctrl(); + + $ilCtrl->saveParameter($this, "obj_id"); + $ilCtrl->saveParameter($this, "tref_id"); + + parent::__construct($a_tref_id); + + $this->tref_id = $a_tref_id; + if (is_object($this->node_object)) { + $this->base_skill_id = $this->node_object->getSkillTemplateId(); + } + } + + /** + * Get Node Type + */ + public function getType() + { + return "sktr"; + } + + /** + * Execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + //$tpl->getStandardTemplate(); + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd(); + + switch ($next_class) { + default: + $ret = $this->$cmd(); + break; + } + } + + /** + * output tabs + */ + public function setTabs($a_tab = "") + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + $ilHelp = $this->help; + + $ilTabs->clearTargets(); + $ilHelp->setScreenIdComponent("skmg_sktr"); + + if (is_object($this->node_object)) { + $sk_id = $this->node_object->getSkillTemplateId(); + $obj_type = ilSkillTreeNode::_lookupType($sk_id); + + if ($obj_type == "sctp") { + // content + $ilTabs->addTab( + "content", + $lng->txt("content"), + $ilCtrl->getLinkTarget($this, 'listItems') + ); + } else { + // content + $ilTabs->addTab( + "content", + $lng->txt("skmg_skill_levels"), + $ilCtrl->getLinkTarget($this, 'listItems') + ); + } + + // properties + $ilTabs->addTab( + "properties", + $lng->txt("settings"), + $ilCtrl->getLinkTarget($this, 'editProperties') + ); + + // usage + $this->addUsageTab($ilTabs); + + // back link + /* + $ilCtrl->setParameterByClass("ilskillrootgui", "obj_id", + $this->node_object->skill_tree->getRootId()); + $ilTabs->setBackTarget($lng->txt("obj_skmg"), + $ilCtrl->getLinkTargetByClass("ilskillrootgui", "listSkills")); + $ilCtrl->setParameterByClass("ilskillrootgui", "obj_id", + $_GET["obj_id"]);*/ + + $tid = ilSkillTemplateReference::_lookupTemplateId($this->node_object->getId()); + $add = " (" . ilSkillTreeNode::_lookupTitle($tid) . ")"; + + parent::setTitleIcon(); + $tpl->setTitle( + $lng->txt("skmg_sktr") . ": " . $this->node_object->getTitle() . $add + ); + $this->setSkillNodeDescription(); + + $ilTabs->activateTab($a_tab); + } + } + + /** + * Insert + * + * @param + * @return + */ + public function insert() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + + $ilCtrl->saveParameter($this, "parent_id"); + $ilCtrl->saveParameter($this, "target"); + $this->initForm("create"); + $tpl->setContent($this->form->getHTML()); + } + + + /** + * Edit properties + */ + public function editProperties() + { + $tpl = $this->tpl; + + $this->setTabs("properties"); + + $this->initForm(); + $this->getValues(); + $tpl->setContent($this->form->getHTML()); + } + + /** + * Init form. + * + * @param int $a_mode Edit Mode + */ + public function initForm($a_mode = "edit") + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + // select skill template + include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); + $tmplts = ilSkillTreeNode::getTopTemplates(); + + // title + $ti = new ilTextInputGUI($lng->txt("title"), "title"); + $ti->setRequired(true); + $this->form->addItem($ti); + + // order nr + $ni = new ilNumberInputGUI($lng->txt("skmg_order_nr"), "order_nr"); + $ni->setInfo($lng->txt("skmg_order_nr_info")); + $ni->setMaxLength(6); + $ni->setSize(6); + $ni->setRequired(true); + if ($a_mode == "create") { + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $tree = new ilSkillTree(); + $max = $tree->getMaxOrderNr((int) $_GET["obj_id"]); + $ni->setValue($max + 10); + } + $this->form->addItem($ni); + + // template + $options = array( + "" => $lng->txt("please_select"), + ); + foreach ($tmplts as $tmplt) { + $options[$tmplt["child"]] = $tmplt["title"]; + } + if ($a_mode != "edit") { + $si = new ilSelectInputGUI($lng->txt("skmg_skill_template"), "skill_template_id"); + $si->setOptions($options); + $si->setRequired(true); + $this->form->addItem($si); + } else { + $ne = new ilNonEditableValueGUI($lng->txt("skmg_skill_template"), ""); + $ne->setValue($options[$this->node_object->getSkillTemplateId()]); + $this->form->addItem($ne); + } + + // status + $this->addStatusInput($this->form); + + // selectable + $cb = new ilCheckboxInputGUI($lng->txt("skmg_selectable"), "selectable"); + $cb->setInfo($lng->txt("skmg_selectable_info")); + $this->form->addItem($cb); + + if ($this->checkPermissionBool("write")) { + if ($a_mode == "create") { + $this->form->addCommandButton("save", $lng->txt("save")); + $this->form->addCommandButton("cancel", $lng->txt("cancel")); + $this->form->setTitle($lng->txt("skmg_new_sktr")); + } else { + $this->form->addCommandButton("updateSkillTemplateReference", $lng->txt("save")); + $this->form->setTitle($lng->txt("skmg_edit_sktr")); + } + } + + $this->form->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * Get current values for from + */ + public function getValues() + { + $values = array(); + $values["skill_template_id"] = $this->node_object->getSkillTemplateId(); + $values["title"] = $this->node_object->getTitle(); + $values["selectable"] = $this->node_object->getSelfEvaluation(); + $values["status"] = $this->node_object->getStatus(); + $values["order_nr"] = $this->node_object->getOrderNr(); + $this->form->setValuesByArray($values); + } + + /** + * Save item + */ + public function saveItem() + { + if (!$this->checkPermissionBool("write")) { + return; + } + + $sktr = new ilSkillTemplateReference(); + $sktr->setTitle($_POST["title"]); + $sktr->setSkillTemplateId($_POST["skill_template_id"]); + $sktr->setSelfEvaluation($_POST["selectable"]); + $sktr->setOrderNr($_POST["order_nr"]); + $sktr->setStatus($_POST["status"]); + $sktr->create(); + ilSkillTreeNode::putInTree($sktr, (int) $_GET["obj_id"], IL_LAST_NODE); + $this->node_object = $sktr; + } + + /** + * After saving + */ + public function afterSave() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameterByClass( + "ilskilltemplatereferencegui", + "tref_id", + $this->node_object->getId() + ); + $ilCtrl->setParameterByClass( + "ilskilltemplatereferencegui", + "obj_id", + $this->node_object->getSkillTemplateId() + ); + $ilCtrl->redirectByClass("ilskilltemplatereferencegui", "listItems"); + } + + /** + * Update form + */ + public function updateSkillTemplateReference() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + + if (!$this->checkPermissionBool("write")) { + return; + } + + $this->initForm("edit"); + if ($this->form->checkInput()) { + // perform update + // $this->node_object->setSkillTemplateId($_POST["skill_template_id"]); + $this->node_object->setTitle($_POST["title"]); + $this->node_object->setSelfEvaluation($_POST["selectable"]); + $this->node_object->setOrderNr($_POST["order_nr"]); + $this->node_object->setStatus($_POST["status"]); + $this->node_object->update(); + + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "editProperties"); + } + + $this->form->setValuesByPost(); + $tpl->setContent($this->form->getHtml()); + } + + /** + * Cancel + * + * @param + * @return + */ + public function cancel() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirectByClass("ilobjskillmanagementgui", "editSkills"); + } + + /** + * List items + */ + public function listItems() + { + $tpl = $this->tpl; + $lng = $this->lng; + + if ($this->isInUse()) { + ilUtil::sendInfo($lng->txt("skmg_skill_in_use")); + } + + $this->setTabs("content"); + + $sk_id = $this->node_object->getSkillTemplateId(); + $obj_type = ilSkillTreeNode::_lookupType($sk_id); + + if ($obj_type == "sctp") { + include_once("./Services/Skill/classes/class.ilSkillCatTableGUI.php"); + $table = new ilSkillCatTableGUI( + $this, + "listItems", + (int) $sk_id, + ilSkillCatTableGUI::MODE_SCTP, + $this->node_object->getId() + ); + $tpl->setContent($table->getHTML()); + } elseif ($obj_type == "sktp") { + include_once("./Services/Skill/classes/class.ilSkillLevelTableGUI.php"); + $table = new ilSkillLevelTableGUI((int) $sk_id, $this, "edit", $this->node_object->getId()); + $tpl->setContent($table->getHTML()); + } + } } - -?> \ No newline at end of file diff --git a/Services/Skill/classes/class.ilSkillTemplateTreeExplorerGUI.php b/Services/Skill/classes/class.ilSkillTemplateTreeExplorerGUI.php index 0fb2babf5525d17925339b5c0ab539a45f3d02f1..5784f95c7ce39fe8449360cee7a7c53bae5d7e2c 100644 --- a/Services/Skill/classes/class.ilSkillTemplateTreeExplorerGUI.php +++ b/Services/Skill/classes/class.ilSkillTemplateTreeExplorerGUI.php @@ -13,196 +13,180 @@ include_once("./Services/UIComponent/Explorer2/classes/class.ilTreeExplorerGUI.p */ class ilSkillTemplateTreeExplorerGUI extends ilTreeExplorerGUI { - /** - * @var ilLanguage - */ - protected $lng; + /** + * @var ilLanguage + */ + protected $lng; - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * Constructor - * - * @param object $a_parent_obj parent gui object - * @param string $a_parent_cmd parent command - */ - public function __construct($a_parent_obj, $a_parent_cmd) - { - global $DIC; + /** + * Constructor + * + * @param object $a_parent_obj parent gui object + * @param string $a_parent_cmd parent command + */ + public function __construct($a_parent_obj, $a_parent_cmd) + { + global $DIC; - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $tree = new ilSkillTree(); - parent::__construct("skill_exp", $a_parent_obj, $a_parent_cmd, $tree); + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $tree = new ilSkillTree(); + parent::__construct("skill_exp", $a_parent_obj, $a_parent_cmd, $tree); - $this->setTypeWhiteList(array("skrt", "sktp", "sctp")); - - $this->setSkipRootNode(false); - $this->setAjax(true); - $this->setOrderField("order_nr"); - } - - /** - * Get root node - * - * @return array node data - */ - function getRootNode() - { - $path = $this->getTree()->getPathId($_GET["obj_id"]); - return $this->getTree()->getNodeData($path[1]); - } + $this->setTypeWhiteList(array("skrt", "sktp", "sctp")); + + $this->setSkipRootNode(false); + $this->setAjax(true); + $this->setOrderField("order_nr"); + } + + /** + * Get root node + * + * @return array node data + */ + public function getRootNode() + { + $path = $this->getTree()->getPathId($_GET["obj_id"]); + return $this->getTree()->getNodeData($path[1]); + } - - /** - * Get childs of node - * - * @param int $a_parent_id parent id - * @return array childs - */ - function getChildsOfNode($a_parent_id) - { - $childs = parent::getChildsOfNode($a_parent_id); - - include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); - foreach ($childs as $c) - { - $this->parent[$c["child"]] = $c["parent"]; - if ($this->draft[$c["parent"]]) - { - $this->draft[$c["child"]] = true; - } - else - { - $this->draft[$c["child"]] = (ilSkillTreeNode::_lookupStatus($c["child"]) == ilSkillTreeNode::STATUS_DRAFT); - } - } - return $childs; - } + + /** + * Get childs of node + * + * @param int $a_parent_id parent id + * @return array childs + */ + public function getChildsOfNode($a_parent_id) + { + $childs = parent::getChildsOfNode($a_parent_id); + + include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); + foreach ($childs as $c) { + $this->parent[$c["child"]] = $c["parent"]; + if ($this->draft[$c["parent"]]) { + $this->draft[$c["child"]] = true; + } else { + $this->draft[$c["child"]] = (ilSkillTreeNode::_lookupStatus($c["child"]) == ilSkillTreeNode::STATUS_DRAFT); + } + } + return $childs; + } - /** - * Get node content - * - * @param array - * @return - */ - function getNodeContent($a_node) - { - $lng = $this->lng; - - // title - $title = $a_node["title"]; - - // root? - if ($a_node["type"] == "skrt") - { - $title = $lng->txt("skmg_skill_templates"); - } - else - { - if ($a_node["type"] == "sktr") - { - include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); - $tid = ilSkillTemplateReference::_lookupTemplateId($a_node["child"]); - $title.= " (".ilSkillTreeNode::_lookupTitle($tid).")"; - } - if (ilSkillTreeNode::_lookupSelfEvaluation($a_node["child"])) - { - $title = "".$title.""; - } - } - - return $title; - } - - /** - * Get node content - * - * @param array - * @return - */ - function getNodeIcon($a_node) - { - // root? - if ($a_node["type"] == "skrt") - { - $icon = ilUtil::getImagePath("icon_sctp.svg"); - } - else - { - if (in_array($a_node["type"], array("skll", "scat", "sctr", "sktr"))) - { - $icon = ilSkillTreeNode::getIconPath($a_node["child"], $a_node["type"], "", - $this->draft[$a_node["child"]]); - } - else - { - $icon = ilUtil::getImagePath("icon_".$a_node["type"].".svg"); - } - } - - return $icon; - } + /** + * Get node content + * + * @param array + * @return + */ + public function getNodeContent($a_node) + { + $lng = $this->lng; + + // title + $title = $a_node["title"]; + + // root? + if ($a_node["type"] == "skrt") { + $title = $lng->txt("skmg_skill_templates"); + } else { + if ($a_node["type"] == "sktr") { + include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); + $tid = ilSkillTemplateReference::_lookupTemplateId($a_node["child"]); + $title.= " (" . ilSkillTreeNode::_lookupTitle($tid) . ")"; + } + if (ilSkillTreeNode::_lookupSelfEvaluation($a_node["child"])) { + $title = "" . $title . ""; + } + } + + return $title; + } + + /** + * Get node content + * + * @param array + * @return + */ + public function getNodeIcon($a_node) + { + // root? + if ($a_node["type"] == "skrt") { + $icon = ilUtil::getImagePath("icon_sctp.svg"); + } else { + if (in_array($a_node["type"], array("skll", "scat", "sctr", "sktr"))) { + $icon = ilSkillTreeNode::getIconPath( + $a_node["child"], + $a_node["type"], + "", + $this->draft[$a_node["child"]] + ); + } else { + $icon = ilUtil::getImagePath("icon_" . $a_node["type"] . ".svg"); + } + } + + return $icon; + } - /** - * Is node highlighted? - * - * @param mixed $a_node node object/array - * @return boolean node visible true/false - */ - function isNodeHighlighted($a_node) - { - if ($a_node["child"] == $_GET["obj_id"] || - ($_GET["obj_id"] == "" && $a_node["type"] == "skrt")) - { - return true; - } - return false; - } - - /** - * Get href for node - * - * @param mixed $a_node node object/array - * @return string href attribute - */ - function getNodeHref($a_node) - { - $ilCtrl = $this->ctrl; + /** + * Is node highlighted? + * + * @param mixed $a_node node object/array + * @return boolean node visible true/false + */ + public function isNodeHighlighted($a_node) + { + if ($a_node["child"] == $_GET["obj_id"] || + ($_GET["obj_id"] == "" && $a_node["type"] == "skrt")) { + return true; + } + return false; + } + + /** + * Get href for node + * + * @param mixed $a_node node object/array + * @return string href attribute + */ + public function getNodeHref($a_node) + { + $ilCtrl = $this->ctrl; - switch($a_node["type"]) - { - // root - case "skrt": - $ilCtrl->setParameterByClass("ilskillrootgui", "obj_id", $a_node["child"]); - $ret = $ilCtrl->getLinkTargetByClass("ilskillrootgui", "listTemplates"); - $ilCtrl->setParameterByClass("ilskillrootgui", "obj_id", $_GET["obj_id"]); - return $ret; - break; + switch ($a_node["type"]) { + // root + case "skrt": + $ilCtrl->setParameterByClass("ilskillrootgui", "obj_id", $a_node["child"]); + $ret = $ilCtrl->getLinkTargetByClass("ilskillrootgui", "listTemplates"); + $ilCtrl->setParameterByClass("ilskillrootgui", "obj_id", $_GET["obj_id"]); + return $ret; + break; - // template - case "sktp": - $ilCtrl->setParameterByClass("ilbasicskilltemplategui", "obj_id", $a_node["child"]); - $ret = $ilCtrl->getLinkTargetByClass("ilbasicskilltemplategui", "edit"); - $ilCtrl->setParameterByClass("ilbasicskilltemplategui", "obj_id", $_GET["obj_id"]); - return $ret; - break; - - // template category - case "sctp": - $ilCtrl->setParameterByClass("ilskilltemplatecategorygui", "obj_id", $a_node["child"]); - $ret = $ilCtrl->getLinkTargetByClass("ilskilltemplatecategorygui", "listItems"); - $ilCtrl->setParameterByClass("ilskilltemplatecategorygui", "obj_id", $_GET["obj_id"]); - return $ret; - break; - - } - } + // template + case "sktp": + $ilCtrl->setParameterByClass("ilbasicskilltemplategui", "obj_id", $a_node["child"]); + $ret = $ilCtrl->getLinkTargetByClass("ilbasicskilltemplategui", "edit"); + $ilCtrl->setParameterByClass("ilbasicskilltemplategui", "obj_id", $_GET["obj_id"]); + return $ret; + break; + // template category + case "sctp": + $ilCtrl->setParameterByClass("ilskilltemplatecategorygui", "obj_id", $a_node["child"]); + $ret = $ilCtrl->getLinkTargetByClass("ilskilltemplatecategorygui", "listItems"); + $ilCtrl->setParameterByClass("ilskilltemplatecategorygui", "obj_id", $_GET["obj_id"]); + return $ret; + break; + + } + } } - -?> diff --git a/Services/Skill/classes/class.ilSkillTree.php b/Services/Skill/classes/class.ilSkillTree.php index 839dae7e737817a13ac838dccbf79b59daf7351a..98bbd1a2607a78b308c5b7c6527a72cffacef23f 100644 --- a/Services/Skill/classes/class.ilSkillTree.php +++ b/Services/Skill/classes/class.ilSkillTree.php @@ -13,153 +13,129 @@ include_once("./Services/Tree/classes/class.ilTree.php"); */ class ilSkillTree extends ilTree { - function __construct() - { - parent::__construct(1); // only one skill tree, with ID 1 - $this->setTreeTablePK("skl_tree_id"); - $this->setTableNames('skl_tree', 'skl_tree_node'); - } + public function __construct() + { + parent::__construct(1); // only one skill tree, with ID 1 + $this->setTreeTablePK("skl_tree_id"); + $this->setTableNames('skl_tree', 'skl_tree_node'); + } - /** - * Get skill tree path - * - * @param int $a_base_skill_id base skill id - * @param int $a_tref_id template reference id - * @return array path - */ - function getSkillTreePath($a_base_skill_id, $a_tref_id = 0) - { - if ($a_tref_id > 0) - { - include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); - $path = $this->getPathFull($a_tref_id); - $sub_path = $this->getPathFull($a_base_skill_id); - if (is_array($path)) - { - foreach ($path as $k => $v) - { - if ($v["child"] != $a_tref_id) - { - $path[$k]["skill_id"] = $v["child"]; - $path[$k]["tref_id"] = 0; - } - else - { - $path[$k]["skill_id"] = ilSkillTemplateReference::_lookupTemplateId($a_tref_id); - $path[$k]["tref_id"] = $a_tref_id; - } - } - } - $found = false; - if (is_array($sub_path)) - { - foreach ($sub_path as $s) - { - if ($found) - { - $s["skill_id"] = $s["child"]; - $s["tref_id"] = $a_tref_id; - $path[] = $s; - } - if ($s["child"] == ilSkillTemplateReference::_lookupTemplateId($a_tref_id)) - { - $found = true; - } - } - } - } - else - { - $path = $this->getPathFull($a_base_skill_id); - if (is_array($path)) - { - foreach ($path as $k => $v) - { - $path[$k]["skill_id"] = $v["child"]; - $path[$k]["tref_id"] = 0; - } - } - } + /** + * Get skill tree path + * + * @param int $a_base_skill_id base skill id + * @param int $a_tref_id template reference id + * @return array path + */ + public function getSkillTreePath($a_base_skill_id, $a_tref_id = 0) + { + if ($a_tref_id > 0) { + include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); + $path = $this->getPathFull($a_tref_id); + $sub_path = $this->getPathFull($a_base_skill_id); + if (is_array($path)) { + foreach ($path as $k => $v) { + if ($v["child"] != $a_tref_id) { + $path[$k]["skill_id"] = $v["child"]; + $path[$k]["tref_id"] = 0; + } else { + $path[$k]["skill_id"] = ilSkillTemplateReference::_lookupTemplateId($a_tref_id); + $path[$k]["tref_id"] = $a_tref_id; + } + } + } + $found = false; + if (is_array($sub_path)) { + foreach ($sub_path as $s) { + if ($found) { + $s["skill_id"] = $s["child"]; + $s["tref_id"] = $a_tref_id; + $path[] = $s; + } + if ($s["child"] == ilSkillTemplateReference::_lookupTemplateId($a_tref_id)) { + $found = true; + } + } + } + } else { + $path = $this->getPathFull($a_base_skill_id); + if (is_array($path)) { + foreach ($path as $k => $v) { + $path[$k]["skill_id"] = $v["child"]; + $path[$k]["tref_id"] = 0; + } + } + } - if (is_array($path)) - { - return $path; - } - return array(); - } + if (is_array($path)) { + return $path; + } + return array(); + } - /** - * Get skill tree path as string - * - * @param int $a_base_skill_id base skill id - * @param int $a_tref_id template reference id - * @return string path - */ - function getSkillTreePathAsString($a_base_skill_id, $a_tref_id = 0) - { - $path = $this->getSkillTreePath($a_base_skill_id, $a_tref_id); - $str = ""; - $sep = ""; - foreach ($path as $p) - { - if ($p["type"] != "skrt" && $p["child"] != $a_base_skill_id) - { - $str.= $sep.$p["title"]; - $sep = " > "; - } - } - return $str; - } + /** + * Get skill tree path as string + * + * @param int $a_base_skill_id base skill id + * @param int $a_tref_id template reference id + * @return string path + */ + public function getSkillTreePathAsString($a_base_skill_id, $a_tref_id = 0) + { + $path = $this->getSkillTreePath($a_base_skill_id, $a_tref_id); + $str = ""; + $sep = ""; + foreach ($path as $p) { + if ($p["type"] != "skrt" && $p["child"] != $a_base_skill_id) { + $str.= $sep . $p["title"]; + $sep = " > "; + } + } + return $str; + } - /** - * Get top parent node id for a node - * - * @param int $a_node_id - * @return int top parent node id - */ - function getTopParentNodeId($a_node_id) - { - $path = $this->getPathId($a_node_id); - return (int) $path[1]; - } + /** + * Get top parent node id for a node + * + * @param int $a_node_id + * @return int top parent node id + */ + public function getTopParentNodeId($a_node_id) + { + $path = $this->getPathId($a_node_id); + return (int) $path[1]; + } - /** - * Get max order nr - * - * @param int $a_par_id parent id - * @param bool $a_templates templates? true/false - * @return int max order nr - */ - function getMaxOrderNr($a_par_id, $a_templates = false) - { - if ($a_par_id != $this->readRootId()) - { - $childs = $this->getChilds($a_par_id); - } - else - { - if ($a_templates) - { - $childs = $this->getChildsByTypeFilter($a_par_id, - array("skrt", "sktp", "sctp")); - } - else - { - $childs = $this->getChildsByTypeFilter($a_par_id, - array("skrt", "skll", "scat", "sktr")); - } - } - - $max = 0; - foreach ($childs as $k => $c) - { - $max = max(array($c["order_nr"], $max)); - } - - return $max; - } + /** + * Get max order nr + * + * @param int $a_par_id parent id + * @param bool $a_templates templates? true/false + * @return int max order nr + */ + public function getMaxOrderNr($a_par_id, $a_templates = false) + { + if ($a_par_id != $this->readRootId()) { + $childs = $this->getChilds($a_par_id); + } else { + if ($a_templates) { + $childs = $this->getChildsByTypeFilter( + $a_par_id, + array("skrt", "sktp", "sctp") + ); + } else { + $childs = $this->getChildsByTypeFilter( + $a_par_id, + array("skrt", "skll", "scat", "sktr") + ); + } + } + $max = 0; + foreach ($childs as $k => $c) { + $max = max(array($c["order_nr"], $max)); + } + return $max; + } } - -?> diff --git a/Services/Skill/classes/class.ilSkillTreeExplorerGUI.php b/Services/Skill/classes/class.ilSkillTreeExplorerGUI.php index d47ce1402f542ee7c249272726cbf3b551958f3f..71548c201201b38fbf930a76712ad5c2b322597d 100644 --- a/Services/Skill/classes/class.ilSkillTreeExplorerGUI.php +++ b/Services/Skill/classes/class.ilSkillTreeExplorerGUI.php @@ -13,217 +13,197 @@ include_once("./Services/Skill/classes/class.ilVirtualSkillTreeExplorerGUI.php") */ class ilSkillTreeExplorerGUI extends ilVirtualSkillTreeExplorerGUI { - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * Constructor - */ - public function __construct($a_parent_obj, $a_parent_cmd) - { - global $DIC; - - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - parent::__construct("skill_exp", $a_parent_obj, $a_parent_cmd); - - $this->setSkipRootNode(false); - $this->setAjax(false); - $this->setShowDraftNodes(true); - $this->setShowOutdatedNodes(true); - } - - - /** - * Get node content - * - * @param array $a_node node data - * @return string content - */ - function getNodeContent($a_node) - { - $lng = $this->lng; - - $a_parent_id_parts = explode(":", $a_node["id"]); - $a_parent_skl_tree_id = $a_parent_id_parts[0]; - $a_parent_skl_template_tree_id = $a_parent_id_parts[1]; - - // title - $title = $a_node["title"]; - - // root? - if ($a_node["type"] == "skrt") - { - $title = $lng->txt("skmg_skills"); - } - else - { - if ($a_node["type"] == "sktr") - { - include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); - $tid = ilSkillTemplateReference::_lookupTemplateId($a_parent_skl_tree_id); - $title.= " (".ilSkillTreeNode::_lookupTitle($tid).")"; - } - - // @todo: fix this if possible for skill/tref_id combination - if (ilSkillTreeNode::_lookupSelfEvaluation($a_parent_skl_tree_id)) - { - if ($a_parent_skl_template_tree_id == 0 || $a_node["type"] == "sktr") - { - $title = "".$title.""; - } - } - } - - if ($this->vtree->isOutdated($a_node["id"])) - { - $title = "".$title.""; - } - - return $title; - } - - /** - * Get node content - * - * @param array $a_node node data - * @return string icon path - */ - function getNodeIcon($a_node) - { - $a_parent_id_parts = explode(":", $a_node["id"]); - $a_parent_skl_tree_id = $a_parent_id_parts[0]; - $a_parent_skl_template_tree_id = $a_parent_id_parts[1]; - - - // root? - if ($a_node["type"] == "skrt") - { - $icon = ilUtil::getImagePath("icon_scat.svg"); - } - else - { - if (in_array($a_node["type"], array("skll", "scat", "sctr", "sktr", "sctp", "sktp"))) - { - $icon = ilSkillTreeNode::getIconPath($a_parent_skl_tree_id, $a_node["type"], "", - ($this->vtree->isDraft($a_node["id"]) || $this->vtree->isOutdated($a_node["id"]))); - } - else - { - $icon = ilUtil::getImagePath("icon_".$a_node["type"].".svg"); - } - } - - return $icon; - } - - /** - * Is node highlighted? - * - * @param mixed $a_node node object/array - * @return boolean node visible true/false - */ - function isNodeHighlighted($a_node) - { - $id_parts = explode(":", $a_node["id"]); - if ($id_parts[1] == 0) - { - // skill in main tree - $skill_id = $a_node["id"]; - $tref_id = 0; - } - else - { - // skill in template - $tref_id = $id_parts[0]; - $skill_id = $id_parts[1]; - } - - if ($_GET["obj_id"] == "" && $a_node["type"] == "skrt") - { - return true; - } - - if ($skill_id == $_GET["obj_id"] && - ($_GET["tref_id"] == $tref_id)) - { - return true; - } - return false; - } - - /** - * Get href for node - * - * @param mixed $a_node node object/array - * @return string href attribute - */ - function getNodeHref($a_node) - { - $ilCtrl = $this->ctrl; - - $id_parts = explode(":", $a_node["id"]); - if ($id_parts[1] == 0) - { - // skill in main tree - $skill_id = $a_node["id"]; - $tref_id = 0; - } - else - { - // skill in template - $tref_id = $id_parts[0]; - $skill_id = $id_parts[1]; - } - - $gui_class = array( - "skrt" => "ilskillrootgui", - "scat" => "ilskillcategorygui", - "sktr" => "ilskilltemplatereferencegui", - "skll" => "ilbasicskillgui", - "sktp" => "ilbasicskilltemplategui", - "sctp" => "ilskilltemplatecategorygui" - ); - - $cmd = array( - "skrt" => "listSkills", - "scat" => "listItems", - "sktr" => "listItems", - "skll" => "edit", - "sktp" => "edit", - "sctp" => "listItems" - ); - - $gui_class = $gui_class[$a_node["type"]]; - $cmd = $cmd[$a_node["type"]]; - - $ilCtrl->setParameterByClass($gui_class, "tref_id", $tref_id); - $ilCtrl->setParameterByClass($gui_class, "obj_id", $skill_id); - $ret = $ilCtrl->getLinkTargetByClass($gui_class, $cmd); - $ilCtrl->setParameterByClass($gui_class, "obj_id", $_GET["obj_id"]); - $ilCtrl->setParameterByClass($gui_class, "tref_id", $_GET["tref_id"]); - - return $ret; - } - - /** - * Is clickable - * - * @param array $a_node node data - * @return bool clickable true/false - */ - function isNodeClickable($a_node) - { - return true; - } - + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd) + { + global $DIC; + + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + parent::__construct("skill_exp", $a_parent_obj, $a_parent_cmd); + + $this->setSkipRootNode(false); + $this->setAjax(false); + $this->setShowDraftNodes(true); + $this->setShowOutdatedNodes(true); + } + + + /** + * Get node content + * + * @param array $a_node node data + * @return string content + */ + public function getNodeContent($a_node) + { + $lng = $this->lng; + + $a_parent_id_parts = explode(":", $a_node["id"]); + $a_parent_skl_tree_id = $a_parent_id_parts[0]; + $a_parent_skl_template_tree_id = $a_parent_id_parts[1]; + + // title + $title = $a_node["title"]; + + // root? + if ($a_node["type"] == "skrt") { + $title = $lng->txt("skmg_skills"); + } else { + if ($a_node["type"] == "sktr") { + include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); + $tid = ilSkillTemplateReference::_lookupTemplateId($a_parent_skl_tree_id); + $title.= " (" . ilSkillTreeNode::_lookupTitle($tid) . ")"; + } + + // @todo: fix this if possible for skill/tref_id combination + if (ilSkillTreeNode::_lookupSelfEvaluation($a_parent_skl_tree_id)) { + if ($a_parent_skl_template_tree_id == 0 || $a_node["type"] == "sktr") { + $title = "" . $title . ""; + } + } + } + + if ($this->vtree->isOutdated($a_node["id"])) { + $title = "" . $title . ""; + } + + return $title; + } + + /** + * Get node content + * + * @param array $a_node node data + * @return string icon path + */ + public function getNodeIcon($a_node) + { + $a_parent_id_parts = explode(":", $a_node["id"]); + $a_parent_skl_tree_id = $a_parent_id_parts[0]; + $a_parent_skl_template_tree_id = $a_parent_id_parts[1]; + + + // root? + if ($a_node["type"] == "skrt") { + $icon = ilUtil::getImagePath("icon_scat.svg"); + } else { + if (in_array($a_node["type"], array("skll", "scat", "sctr", "sktr", "sctp", "sktp"))) { + $icon = ilSkillTreeNode::getIconPath( + $a_parent_skl_tree_id, + $a_node["type"], + "", + ($this->vtree->isDraft($a_node["id"]) || $this->vtree->isOutdated($a_node["id"])) + ); + } else { + $icon = ilUtil::getImagePath("icon_" . $a_node["type"] . ".svg"); + } + } + + return $icon; + } + + /** + * Is node highlighted? + * + * @param mixed $a_node node object/array + * @return boolean node visible true/false + */ + public function isNodeHighlighted($a_node) + { + $id_parts = explode(":", $a_node["id"]); + if ($id_parts[1] == 0) { + // skill in main tree + $skill_id = $a_node["id"]; + $tref_id = 0; + } else { + // skill in template + $tref_id = $id_parts[0]; + $skill_id = $id_parts[1]; + } + + if ($_GET["obj_id"] == "" && $a_node["type"] == "skrt") { + return true; + } + + if ($skill_id == $_GET["obj_id"] && + ($_GET["tref_id"] == $tref_id)) { + return true; + } + return false; + } + + /** + * Get href for node + * + * @param mixed $a_node node object/array + * @return string href attribute + */ + public function getNodeHref($a_node) + { + $ilCtrl = $this->ctrl; + + $id_parts = explode(":", $a_node["id"]); + if ($id_parts[1] == 0) { + // skill in main tree + $skill_id = $a_node["id"]; + $tref_id = 0; + } else { + // skill in template + $tref_id = $id_parts[0]; + $skill_id = $id_parts[1]; + } + + $gui_class = array( + "skrt" => "ilskillrootgui", + "scat" => "ilskillcategorygui", + "sktr" => "ilskilltemplatereferencegui", + "skll" => "ilbasicskillgui", + "sktp" => "ilbasicskilltemplategui", + "sctp" => "ilskilltemplatecategorygui" + ); + + $cmd = array( + "skrt" => "listSkills", + "scat" => "listItems", + "sktr" => "listItems", + "skll" => "edit", + "sktp" => "edit", + "sctp" => "listItems" + ); + + $gui_class = $gui_class[$a_node["type"]]; + $cmd = $cmd[$a_node["type"]]; + + $ilCtrl->setParameterByClass($gui_class, "tref_id", $tref_id); + $ilCtrl->setParameterByClass($gui_class, "obj_id", $skill_id); + $ret = $ilCtrl->getLinkTargetByClass($gui_class, $cmd); + $ilCtrl->setParameterByClass($gui_class, "obj_id", $_GET["obj_id"]); + $ilCtrl->setParameterByClass($gui_class, "tref_id", $_GET["tref_id"]); + + return $ret; + } + + /** + * Is clickable + * + * @param array $a_node node data + * @return bool clickable true/false + */ + public function isNodeClickable($a_node) + { + return true; + } } - -?> diff --git a/Services/Skill/classes/class.ilSkillTreeNode.php b/Services/Skill/classes/class.ilSkillTreeNode.php index e853964d42219180687e19b829ebdc1328f53ab3..dc9e08339a68d885596e458230a312af8630279f 100644 --- a/Services/Skill/classes/class.ilSkillTreeNode.php +++ b/Services/Skill/classes/class.ilSkillTreeNode.php @@ -14,1057 +14,1009 @@ include_once("./Services/Skill/classes/class.ilSkillTree.php"); */ class ilSkillTreeNode { - /** - * @var ilDB - */ - protected $db; - - const STATUS_PUBLISH = 0; - const STATUS_DRAFT = 1; - const STATUS_OUTDATED = 2; - var $type; - var $id; - var $title; - - /** - * @param int node id - */ - function __construct($a_id = 0) - { - global $DIC; - - $this->db = $DIC->database(); - $this->id = $a_id; - - $this->skill_tree = new ilSkillTree(); - - if($a_id != 0) - { - $this->read(); - } - } - - /** - * Set title - * - * @param string $a_title title - */ - function setTitle($a_title) - { - $this->title = $a_title; - } - - /** - * Get title - * - * @return string title - */ - function getTitle() - { - return $this->title; - } - - /** - * Set type - * - * @param string Type - */ - function setType($a_type) - { - $this->type = $a_type; - } - - /** - * Get type - * - * @return string Type - */ - function getType() - { - return $this->type; - } - - /** - * Set Node ID - * - * @param int Node ID - */ - function setId($a_id) - { - $this->id = $a_id; - } - - /** - * Get Node ID - * - * @param int Node ID - */ - function getId() - { - return $this->id; - } - - /** - * Set self evaluation - * - * @param boolean self evaluation - */ - function setSelfEvaluation($a_val) - { - $this->self_eval = $a_val; - } - - /** - * Get self evaluation - * - * @return boolean self evaluation - */ - function getSelfEvaluation() - { - return $this->self_eval; - } - - /** - * Set order nr - * - * @param int $a_val 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 import id - * - * @param string $a_val import id - */ - public function setImportId($a_val) - { - $this->import_id = $a_val; - } - - /** - * Get import id - * - * @return string import id - */ - public function getImportId() - { - return $this->import_id; - } - - /** - * Set creation date - * - * @param string $a_val creation date - */ - protected function setCreationDate($a_val) - { - $this->creation_date = $a_val; - } - - /** - * Get creation date - * - * @return string creation date - */ - public function getCreationDate() - { - return $this->creation_date; - } - - /** - * Get all status - * - * @return array array of status, key is value, value is lang text - */ - static function getAllStatus() - { - global $DIC; - - $lng = $DIC->language(); - - return array( - self::STATUS_DRAFT => $lng->txt("skmg_status_draft"), - self::STATUS_PUBLISH => $lng->txt("skmg_status_publish"), - self::STATUS_OUTDATED => $lng->txt("skmg_status_outdated") - ); - } - - /** - * Get status info - * - * @param int $a_status status - * @return string info text - */ - static function getStatusInfo($a_status) - { - global $DIC; - - $lng = $DIC->language(); - - switch($a_status) - { - case self::STATUS_PUBLISH: return $lng->txt("skmg_status_publish_info"); - case self::STATUS_DRAFT: return $lng->txt("skmg_status_draft_info"); - case self::STATUS_OUTDATED: return $lng->txt("skmg_status_outdated_info"); - } - return ""; - } - - /** - * Read Data of Node - */ - function read() - { - $ilDB = $this->db; - - if(!isset($this->data_record)) - { - $query = "SELECT * FROM skl_tree_node WHERE obj_id = ". - $ilDB->quote($this->id, "integer"); - $obj_set = $ilDB->query($query); - $this->data_record = $ilDB->fetchAssoc($obj_set); - } - $this->setType($this->data_record["type"]); - $this->setTitle($this->data_record["title"]); - $this->setOrderNr($this->data_record["order_nr"]); - $this->setSelfEvaluation($this->data_record["self_eval"]); - $this->setStatus($this->data_record["status"]); - $this->setImportId($this->data_record["import_id"]); - $this->setCreationDate($this->data_record["creation_date"]); - } - - /** - * this method should only be called by class ilSCORM2004NodeFactory - */ - function setDataRecord($a_record) - { - $this->data_record = $a_record; - } - - /** - * Lookup Title - * - * @param int Node ID - * @return string Title - */ - protected static function _lookup($a_obj_id, $a_field) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT $a_field FROM skl_tree_node WHERE obj_id = ". - $ilDB->quote($a_obj_id, "integer"); - $obj_set = $ilDB->query($query); - $obj_rec = $ilDB->fetchAssoc($obj_set); - - return $obj_rec[$a_field]; - } - - /** - * Lookup Title - * - * @param int node ID - * @return string title - */ - static function _lookupTitle($a_obj_id, $a_tref_id = 0) - { - global $DIC; - - $ilDB = $DIC->database(); - - include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); - if ($a_tref_id > 0 && ilSkillTemplateReference::_lookupTemplateId($a_tref_id) == $a_obj_id) - { - return self::_lookup($a_tref_id, "title"); - } - return self::_lookup($a_obj_id, "title"); - } - - /** - * Lookup self evaluation - * - * @param int node ID - * @return boolean selectable? (self evaluation= - */ - static function _lookupSelfEvaluation($a_obj_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - return self::_lookup($a_obj_id, "self_eval"); - } - - /** - * Lookup Status - * - * @param int $a_obj_id node ID - * @return int status - */ - static function _lookupStatus($a_obj_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - return self::_lookup($a_obj_id, "status"); - } - - /** - * Lookup Type - * - * @param int Node ID - * @return string Type - */ - static function _lookupType($a_obj_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "SELECT * FROM skl_tree_node WHERE obj_id = ". - $ilDB->quote($a_obj_id, "integer"); - $obj_set = $ilDB->query($query); - $obj_rec = $ilDB->fetchAssoc($obj_set); - - return $obj_rec["type"]; - } - - /** - * Set status - * - * @param boolean $a_val status - */ - function setStatus($a_val) - { - $this->status = $a_val; - } - - /** - * Get status - * - * @return int status - */ - function getStatus() - { - return $this->status; - } - - /** - * Write Title - * - * @param int Node ID - * @param string Title - */ - static function _writeTitle($a_obj_id, $a_title) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "UPDATE skl_tree_node SET ". - " title = ".$ilDB->quote($a_title, "text"). - " WHERE obj_id = ".$ilDB->quote($a_obj_id, "integer"); - - $ilDB->manipulate($query); - } - - /** - * Write Order Nr - * - * @param int Node ID - * @param string Order Nr - */ - static function _writeOrderNr($a_obj_id, $a_nr) - { - global $DIC; - - $ilDB = $DIC->database(); - - $query = "UPDATE skl_tree_node SET ". - " order_nr = ".$ilDB->quote($a_nr, "integer"). - " WHERE obj_id = ".$ilDB->quote($a_obj_id, "integer"); - $ilDB->manipulate($query); - } - - /** - * Create Node - * - * @param boolean Upload Mode - */ - function create() - { - $ilDB = $this->db; - - // insert object data - $id = $ilDB->nextId("skl_tree_node"); - $query = "INSERT INTO skl_tree_node (obj_id, title, type, create_date, self_eval, order_nr, status, creation_date, import_id) ". - "VALUES (". - $ilDB->quote($id, "integer").",". - $ilDB->quote($this->getTitle(), "text").",". - $ilDB->quote($this->getType(), "text").", ". - $ilDB->now().", ". - $ilDB->quote((int) $this->getSelfEvaluation(), "integer").", ". - $ilDB->quote((int) $this->getOrderNr(), "integer").", ". - $ilDB->quote((int) $this->getStatus(), "integer").", ". - $ilDB->now().", ". - $ilDB->quote($this->getImportId(), "text"). - ")"; - $ilDB->manipulate($query); - $this->setId($id); - } - - /** - * Update Node - */ - function update() - { - $ilDB = $this->db; - - $query = "UPDATE skl_tree_node SET ". - " title = ".$ilDB->quote($this->getTitle(), "text"). - " ,self_eval = ".$ilDB->quote((int) $this->getSelfEvaluation(), "integer"). - " ,order_nr = ".$ilDB->quote((int) $this->getOrderNr(), "integer"). - " ,status = ".$ilDB->quote((int) $this->getStatus(), "integer"). - " ,import_id = ".$ilDB->quote($this->getImportId(), "text"). - " WHERE obj_id = ".$ilDB->quote($this->getId(), "integer"); - - $ilDB->manipulate($query); - } - - /** - * Delete Node - */ - function delete() - { - $ilDB = $this->db; - - $query = "DELETE FROM skl_tree_node WHERE obj_id= ". - $ilDB->quote($this->getId(), "integer"); - $ilDB->manipulate($query); - } - - /** - * Put this object into the skill tree - */ - static function putInTree($a_obj, $a_parent_id = "", $a_target_node_id = "") - { - $skill_tree = new ilSkillTree(); - - // determine parent - $parent_id = ($a_parent_id != "") - ? $a_parent_id - : $skill_tree->getRootId(); - - // make a check, whether the type of object is allowed under - // the parent - $allowed = array( - "skrt" => array("skll", "scat", "sktr", "sktp", "sctp"), - "scat" => array("skll", "scat", "sktr"), - "sctp" => array("sktp", "sctp")); - $par_type = self::_lookupType($parent_id); - if (!is_array($allowed[$par_type]) || - !in_array($a_obj->getType(), $allowed[$par_type])) - { - return; - } - - // determine target - if ($a_target_node_id != "") - { - $target = $a_target_node_id; - } - else - { - // determine last child that serves as predecessor - $childs = $skill_tree->getChilds($parent_id); - - if (count($childs) == 0) - { - $target = IL_FIRST_NODE; - } - else - { - $target = $childs[count($childs) - 1]["obj_id"]; - } - } - - if ($skill_tree->isInTree($parent_id) && !$skill_tree->isInTree($a_obj->getId())) - { - $skill_tree->insertNode($a_obj->getId(), $parent_id, $target); - } - } - - /** - * Get scorm module editing tree - * - * @param int scorm module object id - * - * @return object tree object - */ - static function getTree($a_slm_obj_id) - { - $tree = new ilSkillTree(); - - return $tree; - } - - /** - * Check for unique types - */ - static function uniqueTypesCheck($a_items) - { - $types = array(); - if (is_array($a_items)) - { - foreach($a_items as $item) - { - $type = ilSkillTreeNode::_lookupType($item); - $types[$type] = $type; - } - } - - if (count($types) > 1) - { - return false; - } - return true; - } - - /** - * Cut and copy a set of skills/skill categories into the clipboard - */ - static function clipboardCut($a_tree_id, $a_ids) - { - self::clearClipboard(); - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $tree = new ilSkillTree(); - - if (!is_array($a_ids)) - { - return false; - } - else - { - // get all "top" ids, i.e. remove ids, that have a selected parent - foreach($a_ids as $id) - { - $path = $tree->getPathId($id); - $take = true; - foreach($path as $path_id) - { - if ($path_id != $id && in_array($path_id, $a_ids)) - { - $take = false; - } - } - if ($take) - { - $cut_ids[] = $id; - } - } - } - - ilSkillTreeNode::clipboardCopy($a_tree_id, $cut_ids); - - // remove the objects from the tree - // note: we are getting skills/categories which are *not* in the tree - // we do not delete any pages/chapters here - foreach ($cut_ids as $id) - { - $curnode = $tree->getNodeData($id); - if ($tree->isInTree($id)) - { - $tree->deleteTree($curnode); - } - } - - } - - - /** - * Copy a set of skills/skill categories into the clipboard - */ - static function clipboardCopy($a_tree_id, $a_ids) - { - global $DIC; - - $ilUser = $DIC->user(); - - self::clearClipboard(); - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $tree = new ilSkillTree(); - - // put them into the clipboard - $time = date("Y-m-d H:i:s", time()); - foreach ($a_ids as $id) - { - $curnode = ""; - if ($tree->isInTree($id)) - { - $curnode = $tree->getNodeData($id); - $subnodes = $tree->getSubTree($curnode); - foreach($subnodes as $subnode) - { - if ($subnode["child"] != $id) - { - $ilUser->addObjectToClipboard($subnode["child"], - $subnode["type"], $subnode["title"], - $subnode["parent"], $time, $subnode["lft"]); - } - } - } - $order = ($curnode["lft"] > 0) - ? $curnode["lft"] - : (int) ($order + 1); - $ilUser->addObjectToClipboard($id, - ilSkillTreeNode::_lookupType($id), ilSkillTreeNode::_lookupTitle($id), 0, $time, - $order); - } - } - - - /** - * Insert basic skills from clipboard - */ - static function insertItemsFromClip($a_type, $a_obj_id) - { - global $DIC; - - $ilCtrl = $DIC->ctrl(); - $ilUser = $DIC->user(); - - // @todo: move this to a service since it can be used here, too - include_once("./Modules/LearningModule/classes/class.ilEditClipboard.php"); - - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $tree = new ilSkillTree(); - - $parent_id = $a_obj_id; - $target = IL_LAST_NODE; - - // cut and paste - $skills = $ilUser->getClipboardObjects($a_type); // this will get all skills _regardless_ of level - $copied_nodes = array(); - foreach ($skills as $skill) - { - // if skill was already copied as part of tree - do not copy it again - if(!in_array($skill["id"], array_keys($copied_nodes))) - { - $cid = ilSkillTreeNode::pasteTree($skill["id"], $parent_id, $target, - $skill["insert_time"], $copied_nodes, - (ilEditClipboard::getAction() == "copy"), true); -// $target = $cid; - } - } - -// if (ilEditClipboard::getAction() == "cut") -// { - self::clearClipboard(); -// } - - ilSkillTreeNode::saveChildsOrder($a_obj_id, array(), - in_array($a_type, array("sktp", "sctp"))); - - return $copied_nodes; - } - - /** - * Remove all skill items from clipboard - * - * @param - * @return - */ - static function clearClipboard() - { - global $DIC; - - $ilUser = $DIC->user(); - - $ilUser->clipboardDeleteObjectsOfType("skll"); - $ilUser->clipboardDeleteObjectsOfType("scat"); - $ilUser->clipboardDeleteObjectsOfType("sktr"); - $ilUser->clipboardDeleteObjectsOfType("sktp"); - $ilUser->clipboardDeleteObjectsOfType("sctp"); - include_once("./Modules/LearningModule/classes/class.ilEditClipboard.php"); - ilEditClipboard::clear(); - } - - - /** - * Paste item (tree) from clipboard to skill tree - */ - static function pasteTree($a_item_id, $a_parent_id, $a_target, $a_insert_time, - &$a_copied_nodes, $a_as_copy = false, $a_add_suffix = false) - { - global $DIC; - - $ilUser = $DIC->user(); - $ilLog = $DIC["ilLog"]; - $lng = $DIC->language(); - - $item_type = ilSkillTreeNode::_lookupType($a_item_id); - - if ($item_type == "scat") - { - include_once("./Services/Skill/classes/class.ilSkillCategory.php"); - $item = new ilSkillCategory($a_item_id); - } - else if ($item_type == "skll") - { - include_once("./Services/Skill/classes/class.ilBasicSkill.php"); - $item = new ilBasicSkill($a_item_id); - } - else if ($item_type == "sktr") - { - include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); - $item = new ilSkillTemplateReference($a_item_id); - } - else if ($item_type == "sktp") - { - include_once("./Services/Skill/classes/class.ilBasicSkillTemplate.php"); - $item = new ilBasicSkillTemplate($a_item_id); - } - else if ($item_type == "sctp") - { - include_once("./Services/Skill/classes/class.ilSkillTemplateCategory.php"); - $item = new ilSkillTemplateCategory($a_item_id); - } - - $ilLog->write("Getting from clipboard type ".$item_type.", ". - "Item ID: ".$a_item_id); - - if ($a_as_copy) - { - $target_item = $item->copy(); - if($a_add_suffix) - { - $target_item->setTitle($target_item->getTitle()." ".$lng->txt("copy_of_suffix")); - $target_item->update(); - } - $a_copied_nodes[$item->getId()] = $target_item->getId(); - } - else - { - $target_item = $item; - } - - $ilLog->write("Putting into skill tree type ".$target_item->getType(). - "Item ID: ".$target_item->getId().", Parent: ".$a_parent_id.", ". - "Target: ".$a_target); - - ilSkillTreeNode::putInTree($target_item, $a_parent_id, $a_target); - - $childs = $ilUser->getClipboardChilds($item->getId(), $a_insert_time); - - foreach($childs as $child) - { - ilSkillTreeNode::pasteTree($child["id"], $target_item->getId(), - IL_LAST_NODE, $a_insert_time, $a_copied_nodes, $a_as_copy); - } - - return $target_item->getId(); - } - - /** - * Is id in tree? - * - * @param - * @return - */ - static function isInTree($a_id) - { - $skill_tree = new ilSkillTree(); - if ($skill_tree->isInTree($a_id)) - { - return true; - } - return false; - } - - /** - * Get all self evaluation nodes - * - * @param - * @return - */ - static function getAllSelfEvaluationNodes() - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT obj_id, title FROM skl_tree_node WHERE ". - " self_eval = ".$ilDB->quote(true, "integer")." ORDER BY TITLE " - ); - $nodes = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $nodes[$rec["obj_id"]] = $rec["title"]; - } - return $nodes; - } - - /** - * Get top skill templates and template categories - * - * @param - * @return - */ - static function getTopTemplates() - { - $tr = new ilSkillTree(); - $childs = $tr->getChildsByTypeFilter($tr->getRootId(), array("sktp", "sctp")); - - return $childs; - } - - /** - * Get selectable skills - * - * @param - * @return - */ - static function getSelectableSkills() - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT * FROM skl_tree_node ". - " WHERE self_eval = ".$ilDB->quote(1, "integer") - ); - - $sel_skills = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $sel_skills[] = $rec; - } - - return $sel_skills; - } - - /** - * Save childs order - * - * @param - * @return - */ - static function saveChildsOrder($a_par_id, $a_childs_order, $a_templates = false) - { - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $skill_tree = new ilSkillTree(); - - if ($a_par_id != $skill_tree->readRootId()) - { - $childs = $skill_tree->getChilds($a_par_id); - } - else - { - if ($a_templates) - { - $childs = $skill_tree->getChildsByTypeFilter($a_par_id, - array("skrt", "sktp", "sctp")); - } - else - { - $childs = $skill_tree->getChildsByTypeFilter($a_par_id, - array("skrt", "skll", "scat", "sktr")); - } - } - - foreach ($childs as $k => $c) - { - if (isset($a_childs_order[$c["child"]])) - { - $childs[$k]["order_nr"] = (int) $a_childs_order[$c["child"]]; - } - } - - $childs = ilUtil::sortArray($childs, "order_nr", "asc", true); - - $cnt = 10; - foreach ($childs as $c) - { - ilSkillTreeNode::_writeOrderNr($c["child"], $cnt); - $cnt += 10; - } - } - - /** - * Get icon path - * - * @param int $a_obj_id node id - * @param string $a_type node type - * @param string $a_size size - * @param int $a_status status - * @return string icon path - */ - static function getIconPath($a_obj_id, $a_type, $a_size = "", $a_status = 0) - { - if ($a_status == self::STATUS_DRAFT && $a_type == "sctp") - { - $a_type = "scat"; - } - if ($a_status == self::STATUS_DRAFT && $a_type == "sktp") - { - $a_type = "skll"; - } - - $off = ($a_status == self::STATUS_DRAFT) - ? "_off" - : ""; - - $a_name = "icon_".$a_type.$a_size.$off.".svg"; - if ($a_type == "sktr") - { - include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); - $tid = ilSkillTemplateReference::_lookupTemplateId($a_obj_id); - $type = ilSkillTreeNode::_lookupType($tid); - if ($type == "sctp") - { - $a_name = "icon_sctr".$a_size.$off.".svg"; - } - } - $vers = "vers=".str_replace(array(".", " "), "-", ILIAS_VERSION); - return ilUtil::getImagePath($a_name)."?".$vers; - } - - /** - * Find skills - * - * @param - * @return - */ - public static function findSkills($a_term) - { - global $DIC; - - $ilDB = $DIC->database(); - - $res = array(); - $candidates = array(); - - $skill_tree = new ilSkillTree(); - - $sql = "SELECT * ". - " FROM skl_tree_node". - " WHERE ".$ilDB->like("title", "text", "%".$a_term."%"); - $sql .= " ORDER BY title"; - $set = $ilDB->query($sql); - include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); - while($row = $ilDB->fetchAssoc($set)) - { - if (in_array($row["type"], array("sctp", "sktp"))) - { - // need to get "top template" first! (if it is already the top level, do not use it!) - $path = $skill_tree->getSkillTreePath($row["obj_id"]); - if ($path[1]["child"] != $row["obj_id"]) - { - $trefs = ilSkillTemplateReference::_lookupTrefIdsForTopTemplateId($path[1]["child"]); - foreach ($trefs as $tref) - { - $candidates[] = array("tref_id" => $tref, "skill_id" => $row["obj_id"], "title" => $row["title"]); - } - } - } - else if ($row["type"] == "sktr") - { - // works - $candidates[] = array("tref_id" => $row["obj_id"], "skill_id" => ilSkillTemplateReference::_lookupTemplateId($row["obj_id"]), "title" => $row["title"]); - } - else - { - // works - $candidates[] = array("tref_id" => 0, "skill_id" => $row["obj_id"], "title" => $row["title"]); - } - } - - foreach ($candidates as $c) - { - // if we get a path array, and the array has items try to use the data - $path = $skill_tree->getSkillTreePath($c["skill_id"], $c["tref_id"]); - $use = false; - if (is_array($path) && count($path) > 0) - { - $use = true; - } - - // if any inactive/outdated -> do not use the data - if (is_array($path)) - { - foreach ($path as $p) - { - if ($p["status"] > 0) - { - $use = false; - } - } - } - if ($use) - { - if (!in_array($c["title"], $res)) - { - $res[] = $c["title"]; - } - } - } - - - return $res; - } - - /** - * Get all possible common skill IDs for node IDs - * - * @param array $a_node_ids array of node ids - * @return array array of skill ids - */ - static function getAllCSkillIdsForNodeIds(array $a_node_ids) - { - include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); - $cskill_ids = array(); - foreach($a_node_ids as $id) - { - if (in_array(self::_lookupType($id), array("skll", "scat", "sktr"))) - { - $skill_id = $id; - $tref_id = 0; - if (ilSkillTreeNode::_lookupType($id) == "sktr") - { - $skill_id = ilSkillTemplateReference::_lookupTemplateId($id); - $tref_id = $id; - } - $cskill_ids[] = array("skill_id" => $skill_id, "tref_id" => $tref_id); - } - if (in_array(ilSkillTreeNode::_lookupType($id), array("sktp", "sctp"))) - { - foreach (ilSkillTemplateReference::_lookupTrefIdsForTemplateId($id) as $tref_id) - { - $cskill_ids[] = array("skill_id" => $id, "tref_id" => $tref_id); - } - } - // for cats, skills and template references, get "real" usages - // for skill and category templates check usage in references - } - return $cskill_ids; - } - - - + /** + * @var ilDB + */ + protected $db; + + const STATUS_PUBLISH = 0; + const STATUS_DRAFT = 1; + const STATUS_OUTDATED = 2; + public $type; + public $id; + public $title; + + /** + * @param int node id + */ + public function __construct($a_id = 0) + { + global $DIC; + + $this->db = $DIC->database(); + $this->id = $a_id; + + $this->skill_tree = new ilSkillTree(); + + if ($a_id != 0) { + $this->read(); + } + } + + /** + * Set title + * + * @param string $a_title title + */ + public function setTitle($a_title) + { + $this->title = $a_title; + } + + /** + * Get title + * + * @return string title + */ + public function getTitle() + { + return $this->title; + } + + /** + * Set type + * + * @param string Type + */ + public function setType($a_type) + { + $this->type = $a_type; + } + + /** + * Get type + * + * @return string Type + */ + public function getType() + { + return $this->type; + } + + /** + * Set Node ID + * + * @param int Node ID + */ + public function setId($a_id) + { + $this->id = $a_id; + } + + /** + * Get Node ID + * + * @param int Node ID + */ + public function getId() + { + return $this->id; + } + + /** + * Set self evaluation + * + * @param boolean self evaluation + */ + public function setSelfEvaluation($a_val) + { + $this->self_eval = $a_val; + } + + /** + * Get self evaluation + * + * @return boolean self evaluation + */ + public function getSelfEvaluation() + { + return $this->self_eval; + } + + /** + * Set order nr + * + * @param int $a_val order nr + */ + public function setOrderNr($a_val) + { + $this->order_nr = $a_val; + } + + /** + * Get order nr + * + * @return int order nr + */ + public function getOrderNr() + { + return $this->order_nr; + } + + /** + * Set import id + * + * @param string $a_val import id + */ + public function setImportId($a_val) + { + $this->import_id = $a_val; + } + + /** + * Get import id + * + * @return string import id + */ + public function getImportId() + { + return $this->import_id; + } + + /** + * Set creation date + * + * @param string $a_val creation date + */ + protected function setCreationDate($a_val) + { + $this->creation_date = $a_val; + } + + /** + * Get creation date + * + * @return string creation date + */ + public function getCreationDate() + { + return $this->creation_date; + } + + /** + * Get all status + * + * @return array array of status, key is value, value is lang text + */ + public static function getAllStatus() + { + global $DIC; + + $lng = $DIC->language(); + + return array( + self::STATUS_DRAFT => $lng->txt("skmg_status_draft"), + self::STATUS_PUBLISH => $lng->txt("skmg_status_publish"), + self::STATUS_OUTDATED => $lng->txt("skmg_status_outdated") + ); + } + + /** + * Get status info + * + * @param int $a_status status + * @return string info text + */ + public static function getStatusInfo($a_status) + { + global $DIC; + + $lng = $DIC->language(); + + switch ($a_status) { + case self::STATUS_PUBLISH: return $lng->txt("skmg_status_publish_info"); + case self::STATUS_DRAFT: return $lng->txt("skmg_status_draft_info"); + case self::STATUS_OUTDATED: return $lng->txt("skmg_status_outdated_info"); + } + return ""; + } + + /** + * Read Data of Node + */ + public function read() + { + $ilDB = $this->db; + + if (!isset($this->data_record)) { + $query = "SELECT * FROM skl_tree_node WHERE obj_id = " . + $ilDB->quote($this->id, "integer"); + $obj_set = $ilDB->query($query); + $this->data_record = $ilDB->fetchAssoc($obj_set); + } + $this->setType($this->data_record["type"]); + $this->setTitle($this->data_record["title"]); + $this->setOrderNr($this->data_record["order_nr"]); + $this->setSelfEvaluation($this->data_record["self_eval"]); + $this->setStatus($this->data_record["status"]); + $this->setImportId($this->data_record["import_id"]); + $this->setCreationDate($this->data_record["creation_date"]); + } + + /** + * this method should only be called by class ilSCORM2004NodeFactory + */ + public function setDataRecord($a_record) + { + $this->data_record = $a_record; + } + + /** + * Lookup Title + * + * @param int Node ID + * @return string Title + */ + protected static function _lookup($a_obj_id, $a_field) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT $a_field FROM skl_tree_node WHERE obj_id = " . + $ilDB->quote($a_obj_id, "integer"); + $obj_set = $ilDB->query($query); + $obj_rec = $ilDB->fetchAssoc($obj_set); + + return $obj_rec[$a_field]; + } + + /** + * Lookup Title + * + * @param int node ID + * @return string title + */ + public static function _lookupTitle($a_obj_id, $a_tref_id = 0) + { + global $DIC; + + $ilDB = $DIC->database(); + + include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); + if ($a_tref_id > 0 && ilSkillTemplateReference::_lookupTemplateId($a_tref_id) == $a_obj_id) { + return self::_lookup($a_tref_id, "title"); + } + return self::_lookup($a_obj_id, "title"); + } + + /** + * Lookup self evaluation + * + * @param int node ID + * @return boolean selectable? (self evaluation= + */ + public static function _lookupSelfEvaluation($a_obj_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + return self::_lookup($a_obj_id, "self_eval"); + } + + /** + * Lookup Status + * + * @param int $a_obj_id node ID + * @return int status + */ + public static function _lookupStatus($a_obj_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + return self::_lookup($a_obj_id, "status"); + } + + /** + * Lookup Type + * + * @param int Node ID + * @return string Type + */ + public static function _lookupType($a_obj_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "SELECT * FROM skl_tree_node WHERE obj_id = " . + $ilDB->quote($a_obj_id, "integer"); + $obj_set = $ilDB->query($query); + $obj_rec = $ilDB->fetchAssoc($obj_set); + + return $obj_rec["type"]; + } + + /** + * Set status + * + * @param boolean $a_val status + */ + public function setStatus($a_val) + { + $this->status = $a_val; + } + + /** + * Get status + * + * @return int status + */ + public function getStatus() + { + return $this->status; + } + + /** + * Write Title + * + * @param int Node ID + * @param string Title + */ + public static function _writeTitle($a_obj_id, $a_title) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "UPDATE skl_tree_node SET " . + " title = " . $ilDB->quote($a_title, "text") . + " WHERE obj_id = " . $ilDB->quote($a_obj_id, "integer"); + + $ilDB->manipulate($query); + } + + /** + * Write Order Nr + * + * @param int Node ID + * @param string Order Nr + */ + public static function _writeOrderNr($a_obj_id, $a_nr) + { + global $DIC; + + $ilDB = $DIC->database(); + + $query = "UPDATE skl_tree_node SET " . + " order_nr = " . $ilDB->quote($a_nr, "integer") . + " WHERE obj_id = " . $ilDB->quote($a_obj_id, "integer"); + $ilDB->manipulate($query); + } + + /** + * Create Node + * + * @param boolean Upload Mode + */ + public function create() + { + $ilDB = $this->db; + + // insert object data + $id = $ilDB->nextId("skl_tree_node"); + $query = "INSERT INTO skl_tree_node (obj_id, title, type, create_date, self_eval, order_nr, status, creation_date, import_id) " . + "VALUES (" . + $ilDB->quote($id, "integer") . "," . + $ilDB->quote($this->getTitle(), "text") . "," . + $ilDB->quote($this->getType(), "text") . ", " . + $ilDB->now() . ", " . + $ilDB->quote((int) $this->getSelfEvaluation(), "integer") . ", " . + $ilDB->quote((int) $this->getOrderNr(), "integer") . ", " . + $ilDB->quote((int) $this->getStatus(), "integer") . ", " . + $ilDB->now() . ", " . + $ilDB->quote($this->getImportId(), "text") . + ")"; + $ilDB->manipulate($query); + $this->setId($id); + } + + /** + * Update Node + */ + public function update() + { + $ilDB = $this->db; + + $query = "UPDATE skl_tree_node SET " . + " title = " . $ilDB->quote($this->getTitle(), "text") . + " ,self_eval = " . $ilDB->quote((int) $this->getSelfEvaluation(), "integer") . + " ,order_nr = " . $ilDB->quote((int) $this->getOrderNr(), "integer") . + " ,status = " . $ilDB->quote((int) $this->getStatus(), "integer") . + " ,import_id = " . $ilDB->quote($this->getImportId(), "text") . + " WHERE obj_id = " . $ilDB->quote($this->getId(), "integer"); + + $ilDB->manipulate($query); + } + + /** + * Delete Node + */ + public function delete() + { + $ilDB = $this->db; + + $query = "DELETE FROM skl_tree_node WHERE obj_id= " . + $ilDB->quote($this->getId(), "integer"); + $ilDB->manipulate($query); + } + + /** + * Put this object into the skill tree + */ + public static function putInTree($a_obj, $a_parent_id = "", $a_target_node_id = "") + { + $skill_tree = new ilSkillTree(); + + // determine parent + $parent_id = ($a_parent_id != "") + ? $a_parent_id + : $skill_tree->getRootId(); + + // make a check, whether the type of object is allowed under + // the parent + $allowed = array( + "skrt" => array("skll", "scat", "sktr", "sktp", "sctp"), + "scat" => array("skll", "scat", "sktr"), + "sctp" => array("sktp", "sctp")); + $par_type = self::_lookupType($parent_id); + if (!is_array($allowed[$par_type]) || + !in_array($a_obj->getType(), $allowed[$par_type])) { + return; + } + + // determine target + if ($a_target_node_id != "") { + $target = $a_target_node_id; + } else { + // determine last child that serves as predecessor + $childs = $skill_tree->getChilds($parent_id); + + if (count($childs) == 0) { + $target = IL_FIRST_NODE; + } else { + $target = $childs[count($childs) - 1]["obj_id"]; + } + } + + if ($skill_tree->isInTree($parent_id) && !$skill_tree->isInTree($a_obj->getId())) { + $skill_tree->insertNode($a_obj->getId(), $parent_id, $target); + } + } + + /** + * Get scorm module editing tree + * + * @param int scorm module object id + * + * @return object tree object + */ + public static function getTree($a_slm_obj_id) + { + $tree = new ilSkillTree(); + + return $tree; + } + + /** + * Check for unique types + */ + public static function uniqueTypesCheck($a_items) + { + $types = array(); + if (is_array($a_items)) { + foreach ($a_items as $item) { + $type = ilSkillTreeNode::_lookupType($item); + $types[$type] = $type; + } + } + + if (count($types) > 1) { + return false; + } + return true; + } + + /** + * Cut and copy a set of skills/skill categories into the clipboard + */ + public static function clipboardCut($a_tree_id, $a_ids) + { + self::clearClipboard(); + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $tree = new ilSkillTree(); + + if (!is_array($a_ids)) { + return false; + } else { + // get all "top" ids, i.e. remove ids, that have a selected parent + foreach ($a_ids as $id) { + $path = $tree->getPathId($id); + $take = true; + foreach ($path as $path_id) { + if ($path_id != $id && in_array($path_id, $a_ids)) { + $take = false; + } + } + if ($take) { + $cut_ids[] = $id; + } + } + } + + ilSkillTreeNode::clipboardCopy($a_tree_id, $cut_ids); + + // remove the objects from the tree + // note: we are getting skills/categories which are *not* in the tree + // we do not delete any pages/chapters here + foreach ($cut_ids as $id) { + $curnode = $tree->getNodeData($id); + if ($tree->isInTree($id)) { + $tree->deleteTree($curnode); + } + } + } + + + /** + * Copy a set of skills/skill categories into the clipboard + */ + public static function clipboardCopy($a_tree_id, $a_ids) + { + global $DIC; + + $ilUser = $DIC->user(); + + self::clearClipboard(); + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $tree = new ilSkillTree(); + + // put them into the clipboard + $time = date("Y-m-d H:i:s", time()); + foreach ($a_ids as $id) { + $curnode = ""; + if ($tree->isInTree($id)) { + $curnode = $tree->getNodeData($id); + $subnodes = $tree->getSubTree($curnode); + foreach ($subnodes as $subnode) { + if ($subnode["child"] != $id) { + $ilUser->addObjectToClipboard( + $subnode["child"], + $subnode["type"], + $subnode["title"], + $subnode["parent"], + $time, + $subnode["lft"] + ); + } + } + } + $order = ($curnode["lft"] > 0) + ? $curnode["lft"] + : (int) ($order + 1); + $ilUser->addObjectToClipboard( + $id, + ilSkillTreeNode::_lookupType($id), + ilSkillTreeNode::_lookupTitle($id), + 0, + $time, + $order + ); + } + } + + + /** + * Insert basic skills from clipboard + */ + public static function insertItemsFromClip($a_type, $a_obj_id) + { + global $DIC; + + $ilCtrl = $DIC->ctrl(); + $ilUser = $DIC->user(); + + // @todo: move this to a service since it can be used here, too + include_once("./Modules/LearningModule/classes/class.ilEditClipboard.php"); + + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $tree = new ilSkillTree(); + + $parent_id = $a_obj_id; + $target = IL_LAST_NODE; + + // cut and paste + $skills = $ilUser->getClipboardObjects($a_type); // this will get all skills _regardless_ of level + $copied_nodes = array(); + foreach ($skills as $skill) { + // if skill was already copied as part of tree - do not copy it again + if (!in_array($skill["id"], array_keys($copied_nodes))) { + $cid = ilSkillTreeNode::pasteTree( + $skill["id"], + $parent_id, + $target, + $skill["insert_time"], + $copied_nodes, + (ilEditClipboard::getAction() == "copy"), + true + ); + // $target = $cid; + } + } + + // if (ilEditClipboard::getAction() == "cut") + // { + self::clearClipboard(); + // } + + ilSkillTreeNode::saveChildsOrder( + $a_obj_id, + array(), + in_array($a_type, array("sktp", "sctp")) + ); + + return $copied_nodes; + } + + /** + * Remove all skill items from clipboard + * + * @param + * @return + */ + public static function clearClipboard() + { + global $DIC; + + $ilUser = $DIC->user(); + + $ilUser->clipboardDeleteObjectsOfType("skll"); + $ilUser->clipboardDeleteObjectsOfType("scat"); + $ilUser->clipboardDeleteObjectsOfType("sktr"); + $ilUser->clipboardDeleteObjectsOfType("sktp"); + $ilUser->clipboardDeleteObjectsOfType("sctp"); + include_once("./Modules/LearningModule/classes/class.ilEditClipboard.php"); + ilEditClipboard::clear(); + } + + + /** + * Paste item (tree) from clipboard to skill tree + */ + public static function pasteTree( + $a_item_id, + $a_parent_id, + $a_target, + $a_insert_time, + &$a_copied_nodes, + $a_as_copy = false, + $a_add_suffix = false + ) { + global $DIC; + + $ilUser = $DIC->user(); + $ilLog = $DIC["ilLog"]; + $lng = $DIC->language(); + + $item_type = ilSkillTreeNode::_lookupType($a_item_id); + + if ($item_type == "scat") { + include_once("./Services/Skill/classes/class.ilSkillCategory.php"); + $item = new ilSkillCategory($a_item_id); + } elseif ($item_type == "skll") { + include_once("./Services/Skill/classes/class.ilBasicSkill.php"); + $item = new ilBasicSkill($a_item_id); + } elseif ($item_type == "sktr") { + include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); + $item = new ilSkillTemplateReference($a_item_id); + } elseif ($item_type == "sktp") { + include_once("./Services/Skill/classes/class.ilBasicSkillTemplate.php"); + $item = new ilBasicSkillTemplate($a_item_id); + } elseif ($item_type == "sctp") { + include_once("./Services/Skill/classes/class.ilSkillTemplateCategory.php"); + $item = new ilSkillTemplateCategory($a_item_id); + } + + $ilLog->write("Getting from clipboard type " . $item_type . ", " . + "Item ID: " . $a_item_id); + + if ($a_as_copy) { + $target_item = $item->copy(); + if ($a_add_suffix) { + $target_item->setTitle($target_item->getTitle() . " " . $lng->txt("copy_of_suffix")); + $target_item->update(); + } + $a_copied_nodes[$item->getId()] = $target_item->getId(); + } else { + $target_item = $item; + } + + $ilLog->write("Putting into skill tree type " . $target_item->getType() . + "Item ID: " . $target_item->getId() . ", Parent: " . $a_parent_id . ", " . + "Target: " . $a_target); + + ilSkillTreeNode::putInTree($target_item, $a_parent_id, $a_target); + + $childs = $ilUser->getClipboardChilds($item->getId(), $a_insert_time); + + foreach ($childs as $child) { + ilSkillTreeNode::pasteTree( + $child["id"], + $target_item->getId(), + IL_LAST_NODE, + $a_insert_time, + $a_copied_nodes, + $a_as_copy + ); + } + + return $target_item->getId(); + } + + /** + * Is id in tree? + * + * @param + * @return + */ + public static function isInTree($a_id) + { + $skill_tree = new ilSkillTree(); + if ($skill_tree->isInTree($a_id)) { + return true; + } + return false; + } + + /** + * Get all self evaluation nodes + * + * @param + * @return + */ + public static function getAllSelfEvaluationNodes() + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT obj_id, title FROM skl_tree_node WHERE " . + " self_eval = " . $ilDB->quote(true, "integer") . " ORDER BY TITLE " + ); + $nodes = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $nodes[$rec["obj_id"]] = $rec["title"]; + } + return $nodes; + } + + /** + * Get top skill templates and template categories + * + * @param + * @return + */ + public static function getTopTemplates() + { + $tr = new ilSkillTree(); + $childs = $tr->getChildsByTypeFilter($tr->getRootId(), array("sktp", "sctp")); + + return $childs; + } + + /** + * Get selectable skills + * + * @param + * @return + */ + public static function getSelectableSkills() + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT * FROM skl_tree_node " . + " WHERE self_eval = " . $ilDB->quote(1, "integer") + ); + + $sel_skills = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $sel_skills[] = $rec; + } + + return $sel_skills; + } + + /** + * Save childs order + * + * @param + * @return + */ + public static function saveChildsOrder($a_par_id, $a_childs_order, $a_templates = false) + { + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $skill_tree = new ilSkillTree(); + + if ($a_par_id != $skill_tree->readRootId()) { + $childs = $skill_tree->getChilds($a_par_id); + } else { + if ($a_templates) { + $childs = $skill_tree->getChildsByTypeFilter( + $a_par_id, + array("skrt", "sktp", "sctp") + ); + } else { + $childs = $skill_tree->getChildsByTypeFilter( + $a_par_id, + array("skrt", "skll", "scat", "sktr") + ); + } + } + + foreach ($childs as $k => $c) { + if (isset($a_childs_order[$c["child"]])) { + $childs[$k]["order_nr"] = (int) $a_childs_order[$c["child"]]; + } + } + + $childs = ilUtil::sortArray($childs, "order_nr", "asc", true); + + $cnt = 10; + foreach ($childs as $c) { + ilSkillTreeNode::_writeOrderNr($c["child"], $cnt); + $cnt += 10; + } + } + + /** + * Get icon path + * + * @param int $a_obj_id node id + * @param string $a_type node type + * @param string $a_size size + * @param int $a_status status + * @return string icon path + */ + public static function getIconPath($a_obj_id, $a_type, $a_size = "", $a_status = 0) + { + if ($a_status == self::STATUS_DRAFT && $a_type == "sctp") { + $a_type = "scat"; + } + if ($a_status == self::STATUS_DRAFT && $a_type == "sktp") { + $a_type = "skll"; + } + + $off = ($a_status == self::STATUS_DRAFT) + ? "_off" + : ""; + + $a_name = "icon_" . $a_type . $a_size . $off . ".svg"; + if ($a_type == "sktr") { + include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); + $tid = ilSkillTemplateReference::_lookupTemplateId($a_obj_id); + $type = ilSkillTreeNode::_lookupType($tid); + if ($type == "sctp") { + $a_name = "icon_sctr" . $a_size . $off . ".svg"; + } + } + $vers = "vers=" . str_replace(array(".", " "), "-", ILIAS_VERSION); + return ilUtil::getImagePath($a_name) . "?" . $vers; + } + + /** + * Find skills + * + * @param + * @return + */ + public static function findSkills($a_term) + { + global $DIC; + + $ilDB = $DIC->database(); + + $res = array(); + $candidates = array(); + + $skill_tree = new ilSkillTree(); + + $sql = "SELECT * " . + " FROM skl_tree_node" . + " WHERE " . $ilDB->like("title", "text", "%" . $a_term . "%"); + $sql .= " ORDER BY title"; + $set = $ilDB->query($sql); + include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); + while ($row = $ilDB->fetchAssoc($set)) { + if (in_array($row["type"], array("sctp", "sktp"))) { + // need to get "top template" first! (if it is already the top level, do not use it!) + $path = $skill_tree->getSkillTreePath($row["obj_id"]); + if ($path[1]["child"] != $row["obj_id"]) { + $trefs = ilSkillTemplateReference::_lookupTrefIdsForTopTemplateId($path[1]["child"]); + foreach ($trefs as $tref) { + $candidates[] = array("tref_id" => $tref, "skill_id" => $row["obj_id"], "title" => $row["title"]); + } + } + } elseif ($row["type"] == "sktr") { + // works + $candidates[] = array("tref_id" => $row["obj_id"], "skill_id" => ilSkillTemplateReference::_lookupTemplateId($row["obj_id"]), "title" => $row["title"]); + } else { + // works + $candidates[] = array("tref_id" => 0, "skill_id" => $row["obj_id"], "title" => $row["title"]); + } + } + + foreach ($candidates as $c) { + // if we get a path array, and the array has items try to use the data + $path = $skill_tree->getSkillTreePath($c["skill_id"], $c["tref_id"]); + $use = false; + if (is_array($path) && count($path) > 0) { + $use = true; + } + + // if any inactive/outdated -> do not use the data + if (is_array($path)) { + foreach ($path as $p) { + if ($p["status"] > 0) { + $use = false; + } + } + } + if ($use) { + if (!in_array($c["title"], $res)) { + $res[] = $c["title"]; + } + } + } + + + return $res; + } + + /** + * Get all possible common skill IDs for node IDs + * + * @param array $a_node_ids array of node ids + * @return array array of skill ids + */ + public static function getAllCSkillIdsForNodeIds(array $a_node_ids) + { + include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); + $cskill_ids = array(); + foreach ($a_node_ids as $id) { + if (in_array(self::_lookupType($id), array("skll", "scat", "sktr"))) { + $skill_id = $id; + $tref_id = 0; + if (ilSkillTreeNode::_lookupType($id) == "sktr") { + $skill_id = ilSkillTemplateReference::_lookupTemplateId($id); + $tref_id = $id; + } + $cskill_ids[] = array("skill_id" => $skill_id, "tref_id" => $tref_id); + } + if (in_array(ilSkillTreeNode::_lookupType($id), array("sktp", "sctp"))) { + foreach (ilSkillTemplateReference::_lookupTrefIdsForTemplateId($id) as $tref_id) { + $cskill_ids[] = array("skill_id" => $id, "tref_id" => $tref_id); + } + } + // for cats, skills and template references, get "real" usages + // for skill and category templates check usage in references + } + return $cskill_ids; + } } -?> \ No newline at end of file diff --git a/Services/Skill/classes/class.ilSkillTreeNodeFactory.php b/Services/Skill/classes/class.ilSkillTreeNodeFactory.php index 02842f592ebaf1c13138703a471a05ca8c011227..4d34876113bf64120a55754fbf7f20abe14e057e 100644 --- a/Services/Skill/classes/class.ilSkillTreeNodeFactory.php +++ b/Services/Skill/classes/class.ilSkillTreeNodeFactory.php @@ -19,64 +19,61 @@ include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); */ class ilSkillTreeNodeFactory { - static function getInstance($a_id = 0) - { - global $DIC; + public static function getInstance($a_id = 0) + { + global $DIC; - $ilDB = $DIC->database(); + $ilDB = $DIC->database(); - $query = "SELECT * FROM skl_tree_node WHERE obj_id = ". - $ilDB->quote($a_id, "integer"); - $obj_set = $ilDB->query($query); - $obj_rec = $ilDB->fetchAssoc($obj_set); - $obj = null; + $query = "SELECT * FROM skl_tree_node WHERE obj_id = " . + $ilDB->quote($a_id, "integer"); + $obj_set = $ilDB->query($query); + $obj_rec = $ilDB->fetchAssoc($obj_set); + $obj = null; - switch($obj_rec["type"]) - { - case "skll": - $obj = new ilBasicSkill(); - $obj->setId($obj_rec["obj_id"]); - $obj->setDataRecord($obj_rec); - $obj->read(); - break; + switch ($obj_rec["type"]) { + case "skll": + $obj = new ilBasicSkill(); + $obj->setId($obj_rec["obj_id"]); + $obj->setDataRecord($obj_rec); + $obj->read(); + break; - case "scat": - $obj = new ilSkillCategory(); - $obj->setId($obj_rec["obj_id"]); - $obj->setDataRecord($obj_rec); - $obj->read(); - break; + case "scat": + $obj = new ilSkillCategory(); + $obj->setId($obj_rec["obj_id"]); + $obj->setDataRecord($obj_rec); + $obj->read(); + break; - case "sktp": - $obj = new ilBasicSkillTemplate(); - $obj->setId($obj_rec["obj_id"]); - $obj->setDataRecord($obj_rec); - $obj->read(); - break; + case "sktp": + $obj = new ilBasicSkillTemplate(); + $obj->setId($obj_rec["obj_id"]); + $obj->setDataRecord($obj_rec); + $obj->read(); + break; - case "sctp": - $obj = new ilSkillTemplateCategory(); - $obj->setId($obj_rec["obj_id"]); - $obj->setDataRecord($obj_rec); - $obj->read(); - break; + case "sctp": + $obj = new ilSkillTemplateCategory(); + $obj->setId($obj_rec["obj_id"]); + $obj->setDataRecord($obj_rec); + $obj->read(); + break; - case "skrt": - $obj = new ilSkillRoot(); - $obj->setId($obj_rec["obj_id"]); - $obj->setDataRecord($obj_rec); - $obj->read(); - break; - - case "sktr": - $obj = new ilSkillTemplateReference(); - $obj->setId($obj_rec["obj_id"]); - $obj->setDataRecord($obj_rec); - $obj->read(); - break; - } - return $obj; - } + case "skrt": + $obj = new ilSkillRoot(); + $obj->setId($obj_rec["obj_id"]); + $obj->setDataRecord($obj_rec); + $obj->read(); + break; + case "sktr": + $obj = new ilSkillTemplateReference(); + $obj->setId($obj_rec["obj_id"]); + $obj->setDataRecord($obj_rec); + $obj->read(); + break; + } + return $obj; + } } -?> diff --git a/Services/Skill/classes/class.ilSkillTreeNodeGUI.php b/Services/Skill/classes/class.ilSkillTreeNodeGUI.php index 11fdc668aa0cc01b412dd129d3535aca8bfdb53b..b15d18e3999cdf22a711348962f4fbb81f0c3b3e 100644 --- a/Services/Skill/classes/class.ilSkillTreeNodeGUI.php +++ b/Services/Skill/classes/class.ilSkillTreeNodeGUI.php @@ -14,776 +14,767 @@ include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); */ class ilSkillTreeNodeGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilLocatorGUI - */ - protected $locator; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilObjUser - */ - protected $user; - - var $node_object; - var $in_use = false; - var $use_checked = false; - /** - * @var ilAccessHandler - */ - var $access; - /** - * @var int - */ - var $ref_id; - - /** - * constructor - * - * @param object $a_content_obj node object - */ - function __construct($a_node_id = 0) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->locator = $DIC["ilLocator"]; - $this->tpl = $DIC["tpl"]; - $this->user = $DIC->user(); - $ilAccess = $DIC->access(); - - $this->node_object = null; - $this->access = $ilAccess; - $this->ref_id = (int) $_GET["ref_id"]; - - if ($a_node_id > 0 && - $this->getType() == ilSkillTreeNode::_lookupType($a_node_id)) - { - $this->readNodeObject((int) $a_node_id); - } - } - - /** - * Is in use? - * - * @param - * @return - */ - function isInUse() - { - if (!is_object($this->node_object)) - { - return false; - } - if ($this->use_checked) - { - return $this->in_use; - } - $cskill_ids = ilSkillTreeNode::getAllCSkillIdsForNodeIds(array($this->node_object->getId())); - include_once("./Services/Skill/classes/class.ilSkillUsage.php"); - $u = new ilSkillUsage(); - $usages = $u->getAllUsagesInfoOfSubtrees($cskill_ids); - if (count($usages) > 0) - { - $this->in_use = true; - } else - { - $this->in_use = false; - } - return $this->in_use; - } - - /** - * Check permission pool - * - * @param string $a_perm - * @return bool - */ - function checkPermissionBool($a_perm) - { - return $this->access->checkAccess($a_perm, "", $this->ref_id); - } - - - /** - * Set Parent GUI class - * - * @param object $a_parentgui Parent GUI class - */ - function setParentGUI($a_parentgui) - { - $this->parentgui = $a_parentgui; - } - - /** - * Get Parent GUI class (ilObjSCORM2004LearningModuleGUI). - * - * @return object Parent GUI class - */ - function getParentGUI() - { - return $this->parentgui; - } - - /** - * Get node object instance - */ - function readNodeObject($a_node_id) - { - include_once("./Services/Skill/classes/class.ilSkillTreeNodeFactory.php"); - $this->node_object = ilSkillTreeNodeFactory::getInstance($a_node_id); - } - - /** - * Save Titles - */ - function saveAllTitles() - { - $ilCtrl = $this->ctrl; - - $this->getParentGUI()->saveAllTitles(false); - $ilCtrl->redirect($this, "showOrganization"); - } - - /** - * Delete nodes in the hierarchy - */ - function deleteNodes() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameter($this, "backcmd", $_GET["backcmd"]); - $this->getParentGUI()->deleteNodes($this); - } - - /** - * Copy items to clipboard, then cut them from the current tree - */ - function cutItems() - { - $lng = $this->lng; - - include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); - - if (!is_array($_POST["id"]) || count($_POST["id"]) == 0) - { - $this->redirectToParent(); - } - - $items = ilUtil::stripSlashesArray($_POST["id"]); - $todel = array(); // delete IDs < 0 (needed for non-js editing) - foreach($items as $k => $item) - { - if ($item < 0) - { - $todel[] = $k; - } - } - foreach($todel as $k) - { - unset($items[$k]); - } - - if (!ilSkillTreeNode::uniqueTypesCheck($items)) - { - ilUtil::sendInfo($lng->txt("skmg_insert_please_choose_one_type_only"), true); - $this->redirectToParent(); - } - - ilSkillTreeNode::clipboardCut(1, $items); - - include_once("./Modules/LearningModule/classes/class.ilEditClipboard.php"); - ilEditClipboard::setAction("cut"); - - ilUtil::sendInfo($lng->txt("skmg_selected_items_have_been_cut"), true); - - ilSkillTreeNode::saveChildsOrder((int) $_GET["obj_id"], array(), - $_GET["tmpmode"]); - - $this->redirectToParent(); - } - - /** - * Copy items to clipboard - */ - function copyItems() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if (!is_array($_POST["id"]) || count($_POST["id"]) == 0) - { - $this->redirectToParent(); - } - - include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); - - $items = ilUtil::stripSlashesArray($_POST["id"]); - $todel = array(); // delete IDs < 0 (needed for non-js editing) - foreach($items as $k => $item) - { - if ($item < 0) - { - $todel[] = $k; - } - } - foreach($todel as $k) - { - unset($items[$k]); - } - if (!ilSkillTreeNode::uniqueTypesCheck($items)) - { - ilUtil::sendInfo($lng->txt("skmg_insert_please_choose_one_type_only"), true); - $this->redirectToParent(); - } - ilSkillTreeNode::clipboardCopy(1, $items); - - // @todo: move this to a service since it can be used here, too - include_once("./Modules/LearningModule/classes/class.ilEditClipboard.php"); - ilEditClipboard::setAction("copy"); - ilUtil::sendInfo($lng->txt("skmg_selected_items_have_been_copied"), true); - - $this->redirectToParent(); - } - - /** - * cancel delete - */ - function cancelDelete() - { - $ilCtrl = $this->ctrl; - - $this->redirectToParent(); - } - - /** - * confirmed delete - */ - function confirmedDelete() - { - $ilCtrl = $this->ctrl; - - if (!$this->checkPermissionBool("write")) - { - return; - } - - $this->getParentGUI()->confirmedDelete(false); - ilSkillTreeNode::saveChildsOrder((int) $_GET["obj_id"], array(), - $_GET["tmpmode"]); - - $this->redirectToParent(); - } - - /** - * Set Locator Items - */ - function setLocator() - { - $ilLocator = $this->locator; - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - - $ilLocator->addRepositoryItems($_GET["ref_id"]); - $this->getParentGUI()->addLocatorItems(); - - if ($_GET["obj_id"] > 0) - { - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $tree = new ilSkillTree(); - $path = $tree->getPathFull($_GET["obj_id"]); - for( $i = 1; $i < count($path); $i++) - { - switch($path[$i]["type"]) - { - case "scat": - $ilCtrl->setParameterByClass("ilskillcategorygui", "obj_id", - $path[$i]["child"]); - $ilLocator->addItem($path[$i]["title"], - $ilCtrl->getLinkTargetByClass("ilskillmanagementgui", - "ilskillcategorygui"), "", 0, $path[$i]["type"], - ilUtil::getImagePath("icon_skmg.svg")); - break; - - case "skll": - $ilCtrl->setParameterByClass("ilbasicskillgui", "obj_id", - $path[$i]["child"]); - $ilLocator->addItem($path[$i]["title"], - $ilCtrl->getLinkTargetByClass("ilskillmanagementgui", - "ilbasicskillgui"), "", 0, $path[$i]["type"], - ilUtil::getImagePath("icon_skmg.svg")); - break; - - } - } - } - $ilCtrl->setParameter($this, "obj_id", $_GET["obj_id"]); - - $tpl->setLocator(); - } - - /** - * Set skill node description - */ - function setSkillNodeDescription() - { - $tpl = $this->tpl; - - if (is_object($this->node_object)) - { - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $tree = new ilSkillTree(); - $path = $this->node_object->skill_tree->getSkillTreePath($this->node_object->getId(), - $this->tref_id); - $desc = ""; - foreach ($path as $p) - { - if (in_array($p["type"], array("scat", "skll", "sktr"))) - { - $desc.= $sep.$p["title"]; - $sep = " > "; - } - } - } - $tpl->setDescription($desc); - } - - /** - * Create skill tree node - */ - function create() - { - $tpl = $this->tpl; - - $this->initForm("create"); - $tpl->setContent($this->form->getHTML()); - } - - /** - * Add status input - * - * @param ilPropertyFormGUI $a_form form - */ - function addStatusInput(ilPropertyFormGUI $a_form) - { - $lng = $this->lng; - - // status - $radg = new ilRadioGroupInputGUI($lng->txt("skmg_status"), "status"); - foreach (ilSkillTreeNode::getAllStatus() as $k => $op) - { - $op = new ilRadioOption($op, $k, ilSkillTreeNode::getStatusInfo($k)); - $radg->addOption($op); - } - $a_form->addItem($radg); - } - - /** - * Edit properties form - */ - function editProperties() - { - $tpl = $this->tpl; - $lng = $this->lng; - - if ($this->isInUse()) - { - ilUtil::sendInfo($lng->txt("skmg_skill_in_use")); - } - - $this->initForm("edit"); - $this->getPropertyValues(); - $tpl->setContent($this->form->getHTML()); - } - - /** - * Get property values for edit form - */ - function getPropertyValues() - { - $values = array(); - - $values["title"] = $this->node_object->getTitle(); - $values["order_nr"] = $this->node_object->getOrderNr(); - $values["self_eval"] = $this->node_object->getSelfEvaluation(); - $values["status"] = $this->node_object->getStatus(); - - $this->form->setValuesByArray($values); + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilLocatorGUI + */ + protected $locator; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilObjUser + */ + protected $user; + + public $node_object; + public $in_use = false; + public $use_checked = false; + /** + * @var ilAccessHandler + */ + public $access; + /** + * @var int + */ + public $ref_id; + + /** + * constructor + * + * @param object $a_content_obj node object + */ + public function __construct($a_node_id = 0) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->locator = $DIC["ilLocator"]; + $this->tpl = $DIC["tpl"]; + $this->user = $DIC->user(); + $ilAccess = $DIC->access(); + + $this->node_object = null; + $this->access = $ilAccess; + $this->ref_id = (int) $_GET["ref_id"]; + + if ($a_node_id > 0 && + $this->getType() == ilSkillTreeNode::_lookupType($a_node_id)) { + $this->readNodeObject((int) $a_node_id); + } + } + + /** + * Is in use? + * + * @param + * @return + */ + public function isInUse() + { + if (!is_object($this->node_object)) { + return false; + } + if ($this->use_checked) { + return $this->in_use; + } + $cskill_ids = ilSkillTreeNode::getAllCSkillIdsForNodeIds(array($this->node_object->getId())); + include_once("./Services/Skill/classes/class.ilSkillUsage.php"); + $u = new ilSkillUsage(); + $usages = $u->getAllUsagesInfoOfSubtrees($cskill_ids); + if (count($usages) > 0) { + $this->in_use = true; + } else { + $this->in_use = false; + } + return $this->in_use; + } + + /** + * Check permission pool + * + * @param string $a_perm + * @return bool + */ + public function checkPermissionBool($a_perm) + { + return $this->access->checkAccess($a_perm, "", $this->ref_id); + } + + + /** + * Set Parent GUI class + * + * @param object $a_parentgui Parent GUI class + */ + public function setParentGUI($a_parentgui) + { + $this->parentgui = $a_parentgui; + } + + /** + * Get Parent GUI class (ilObjSCORM2004LearningModuleGUI). + * + * @return object Parent GUI class + */ + public function getParentGUI() + { + return $this->parentgui; + } + + /** + * Get node object instance + */ + public function readNodeObject($a_node_id) + { + include_once("./Services/Skill/classes/class.ilSkillTreeNodeFactory.php"); + $this->node_object = ilSkillTreeNodeFactory::getInstance($a_node_id); + } + + /** + * Save Titles + */ + public function saveAllTitles() + { + $ilCtrl = $this->ctrl; + + $this->getParentGUI()->saveAllTitles(false); + $ilCtrl->redirect($this, "showOrganization"); + } + + /** + * Delete nodes in the hierarchy + */ + public function deleteNodes() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameter($this, "backcmd", $_GET["backcmd"]); + $this->getParentGUI()->deleteNodes($this); + } + + /** + * Copy items to clipboard, then cut them from the current tree + */ + public function cutItems() + { + $lng = $this->lng; + + include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); + + if (!is_array($_POST["id"]) || count($_POST["id"]) == 0) { + $this->redirectToParent(); + } + + $items = ilUtil::stripSlashesArray($_POST["id"]); + $todel = array(); // delete IDs < 0 (needed for non-js editing) + foreach ($items as $k => $item) { + if ($item < 0) { + $todel[] = $k; + } + } + foreach ($todel as $k) { + unset($items[$k]); + } + + if (!ilSkillTreeNode::uniqueTypesCheck($items)) { + ilUtil::sendInfo($lng->txt("skmg_insert_please_choose_one_type_only"), true); + $this->redirectToParent(); + } + + ilSkillTreeNode::clipboardCut(1, $items); + + include_once("./Modules/LearningModule/classes/class.ilEditClipboard.php"); + ilEditClipboard::setAction("cut"); + + ilUtil::sendInfo($lng->txt("skmg_selected_items_have_been_cut"), true); + + ilSkillTreeNode::saveChildsOrder( + (int) $_GET["obj_id"], + array(), + $_GET["tmpmode"] + ); + + $this->redirectToParent(); + } + + /** + * Copy items to clipboard + */ + public function copyItems() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if (!is_array($_POST["id"]) || count($_POST["id"]) == 0) { + $this->redirectToParent(); + } + + include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); + + $items = ilUtil::stripSlashesArray($_POST["id"]); + $todel = array(); // delete IDs < 0 (needed for non-js editing) + foreach ($items as $k => $item) { + if ($item < 0) { + $todel[] = $k; + } + } + foreach ($todel as $k) { + unset($items[$k]); + } + if (!ilSkillTreeNode::uniqueTypesCheck($items)) { + ilUtil::sendInfo($lng->txt("skmg_insert_please_choose_one_type_only"), true); + $this->redirectToParent(); + } + ilSkillTreeNode::clipboardCopy(1, $items); + + // @todo: move this to a service since it can be used here, too + include_once("./Modules/LearningModule/classes/class.ilEditClipboard.php"); + ilEditClipboard::setAction("copy"); + ilUtil::sendInfo($lng->txt("skmg_selected_items_have_been_copied"), true); + + $this->redirectToParent(); + } + + /** + * cancel delete + */ + public function cancelDelete() + { + $ilCtrl = $this->ctrl; + + $this->redirectToParent(); + } + + /** + * confirmed delete + */ + public function confirmedDelete() + { + $ilCtrl = $this->ctrl; + + if (!$this->checkPermissionBool("write")) { + return; + } + + $this->getParentGUI()->confirmedDelete(false); + ilSkillTreeNode::saveChildsOrder( + (int) $_GET["obj_id"], + array(), + $_GET["tmpmode"] + ); + + $this->redirectToParent(); + } + + /** + * Set Locator Items + */ + public function setLocator() + { + $ilLocator = $this->locator; + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + + $ilLocator->addRepositoryItems($_GET["ref_id"]); + $this->getParentGUI()->addLocatorItems(); + + if ($_GET["obj_id"] > 0) { + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $tree = new ilSkillTree(); + $path = $tree->getPathFull($_GET["obj_id"]); + for ($i = 1; $i < count($path); $i++) { + switch ($path[$i]["type"]) { + case "scat": + $ilCtrl->setParameterByClass( + "ilskillcategorygui", + "obj_id", + $path[$i]["child"] + ); + $ilLocator->addItem( + $path[$i]["title"], + $ilCtrl->getLinkTargetByClass( + "ilskillmanagementgui", + "ilskillcategorygui" + ), + "", + 0, + $path[$i]["type"], + ilUtil::getImagePath("icon_skmg.svg") + ); + break; + + case "skll": + $ilCtrl->setParameterByClass( + "ilbasicskillgui", + "obj_id", + $path[$i]["child"] + ); + $ilLocator->addItem( + $path[$i]["title"], + $ilCtrl->getLinkTargetByClass( + "ilskillmanagementgui", + "ilbasicskillgui" + ), + "", + 0, + $path[$i]["type"], + ilUtil::getImagePath("icon_skmg.svg") + ); + break; + + } + } + } + $ilCtrl->setParameter($this, "obj_id", $_GET["obj_id"]); + + $tpl->setLocator(); + } + + /** + * Set skill node description + */ + public function setSkillNodeDescription() + { + $tpl = $this->tpl; + + if (is_object($this->node_object)) { + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $tree = new ilSkillTree(); + $path = $this->node_object->skill_tree->getSkillTreePath( + $this->node_object->getId(), + $this->tref_id + ); + $desc = ""; + foreach ($path as $p) { + if (in_array($p["type"], array("scat", "skll", "sktr"))) { + $desc.= $sep . $p["title"]; + $sep = " > "; + } + } + } + $tpl->setDescription($desc); + } + + /** + * Create skill tree node + */ + public function create() + { + $tpl = $this->tpl; + + $this->initForm("create"); + $tpl->setContent($this->form->getHTML()); + } + + /** + * Add status input + * + * @param ilPropertyFormGUI $a_form form + */ + public function addStatusInput(ilPropertyFormGUI $a_form) + { + $lng = $this->lng; + + // status + $radg = new ilRadioGroupInputGUI($lng->txt("skmg_status"), "status"); + foreach (ilSkillTreeNode::getAllStatus() as $k => $op) { + $op = new ilRadioOption($op, $k, ilSkillTreeNode::getStatusInfo($k)); + $radg->addOption($op); + } + $a_form->addItem($radg); + } + + /** + * Edit properties form + */ + public function editProperties() + { + $tpl = $this->tpl; + $lng = $this->lng; + + if ($this->isInUse()) { + ilUtil::sendInfo($lng->txt("skmg_skill_in_use")); + } + + $this->initForm("edit"); + $this->getPropertyValues(); + $tpl->setContent($this->form->getHTML()); + } + + /** + * Get property values for edit form + */ + public function getPropertyValues() + { + $values = array(); + + $values["title"] = $this->node_object->getTitle(); + $values["order_nr"] = $this->node_object->getOrderNr(); + $values["self_eval"] = $this->node_object->getSelfEvaluation(); + $values["status"] = $this->node_object->getStatus(); + + $this->form->setValuesByArray($values); + } + + /** + * Save skill tree node + * + */ + public function save() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if (!$this->checkPermissionBool("write")) { + return; + } + + $this->initForm("create"); + if ($this->form->checkInput()) { + $this->saveItem(); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + ilSkillTreeNode::saveChildsOrder( + (int) $_GET["obj_id"], + array(), + in_array($this->getType(), array("sktp", "sctp")) + ); + $this->afterSave(); + } else { + $this->form->setValuesByPost(); + $tpl->setContent($this->form->getHtml()); + } } - /** - * Save skill tree node - * - */ - public function save() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if (!$this->checkPermissionBool("write")) - { - return; - } - - $this->initForm("create"); - if ($this->form->checkInput()) - { - $this->saveItem(); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - ilSkillTreeNode::saveChildsOrder((int) $_GET["obj_id"], array(), - in_array($this->getType(), array("sktp", "sctp"))); - $this->afterSave(); - } - else - { - $this->form->setValuesByPost(); - $tpl->setContent($this->form->getHtml()); - } - } - - /** - * After saving - */ - function afterSave() - { - $this->redirectToParent(); - } - - - /** - * Update skill tree node - * - */ - public function update() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if (!$this->checkPermissionBool("write")) - { - return; - } - - $this->initForm("edit"); - if ($this->form->checkInput()) - { - $this->updateItem(); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $this->afterUpdate(); - } - else - { - $this->form->setValuesByPost(); - $tpl->setContent($this->form->getHtml()); - } - } - - /** - * After update - */ - function afterUpdate() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirect($this, "editProperties"); - } - - /** - * Init form. - * - * @param int $a_mode Edit Mode - */ - public function initForm($a_mode = "edit") - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - // title - $ti = new ilTextInputGUI($lng->txt("title"), "title"); - $ti->setMaxLength(200); - $ti->setSize(50); - $ti->setRequired(true); - $this->form->addItem($ti); - - // order nr - $ni = new ilNumberInputGUI($lng->txt("skmg_order_nr"), "order_nr"); - $ni->setInfo($lng->txt("skmg_order_nr_info")); - $ni->setMaxLength(6); - $ni->setSize(6); - $ni->setRequired(true); - if ($a_mode == "create") - { - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $tree = new ilSkillTree(); - $max = $tree->getMaxOrderNr((int)$_GET["obj_id"]); - $ni->setValue($max + 10); - } - $this->form->addItem($ni); - - // save and cancel commands - if ($this->checkPermissionBool("write")) - { - if ($a_mode == "create") - { - $this->form->addCommandButton("save", $lng->txt("save")); - $this->form->addCommandButton("cancelSave", $lng->txt("cancel")); - $this->form->setTitle($lng->txt("skmg_create_" . $this->getType())); - } else - { - $this->form->addCommandButton("update", $lng->txt("save")); - $this->form->setTitle($lng->txt("skmg_edit_" . $this->getType())); - } - } - - $ilCtrl->setParameter($this, "obj_id", $_GET["obj_id"]); - $this->form->setFormAction($ilCtrl->getFormAction($this)); - - } - - /** - * Cancel saving - * - * @param - * @return - */ - function cancelSave() - { - $this->redirectToParent(); - } - - /** - * Redirect to parent (identified by current obj_id) - * - * @param - * @return - */ - function redirectToParent($a_tmp_mode = false) - { - $ilCtrl = $this->ctrl; - - if ($_GET["tmpmode"]) - { - $a_tmp_mode = true; - } - - $t = ilSkillTreeNode::_lookupType((int) $_GET["obj_id"]); - - switch ($t) - { - case "skrt": - $ilCtrl->setParameterByClass("ilskillrootgui", "obj_id", (int) $_GET["obj_id"]); - if ($a_tmp_mode) - { - $ilCtrl->redirectByClass("ilskillrootgui", "listTemplates"); - } - else - { - $ilCtrl->redirectByClass("ilskillrootgui", "listSkills"); - } - break; - - case "sctp": - $ilCtrl->setParameterByClass("ilskilltemplatecategorygui", "obj_id", (int) $_GET["obj_id"]); - $ilCtrl->redirectByClass("ilskilltemplatecategorygui", "listItems"); - break; - - case "scat": - $ilCtrl->setParameterByClass("ilskillcategorygui", "obj_id", (int) $_GET["obj_id"]); - $ilCtrl->redirectByClass("ilskillcategorygui", "listItems"); - break; - } - - } - - /** - * Save order - */ - function saveOrder() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if (!$this->checkPermissionBool("write")) - { - return; - } - - ilSkillTreeNode::saveChildsOrder((int) $_GET["obj_id"], $_POST["order"], - (int) $_GET["tmpmode"]); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $this->redirectToParent((int) $_GET["tmpmode"]); - } - - /** - * Insert basic skills from clipboard - */ - function insertBasicSkillClip() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); - $nodes = ilSkillTreeNode::insertItemsFromClip("skll", (int) $_GET["obj_id"]); - $this->redirectToParent(); - } - - /** - * Insert skill categories from clipboard - */ - function insertSkillCategoryClip() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); - $nodes = ilSkillTreeNode::insertItemsFromClip("scat", (int) $_GET["obj_id"]); - $this->redirectToParent(); - } - - /** - * Insert skill template references from clipboard - */ - function insertTemplateReferenceClip() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); - $nodes = ilSkillTreeNode::insertItemsFromClip("sktr", (int) $_GET["obj_id"]); - $this->redirectToParent(); - } - - /** - * Insert skill template from clipboard - */ - function insertSkillTemplateClip() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); - $nodes = ilSkillTreeNode::insertItemsFromClip("sktp", (int) $_GET["obj_id"]); - $this->redirectToParent(); - } - - /** - * Insert skill template category from clipboard - */ - function insertTemplateCategoryClip() - { - $ilCtrl = $this->ctrl; - $ilUser = $this->user; - - include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); - $nodes = ilSkillTreeNode::insertItemsFromClip("sctp", (int) $_GET["obj_id"]); - $this->redirectToParent(); - } - - /** - * Set title icon - */ - function setTitleIcon() - { - $tpl = $this->tpl; - - $obj_id = (is_object($this->node_object)) - ? $this->node_object->getId() - :0; - $tpl->setTitleIcon( - ilSkillTreeNode::getIconPath( - $obj_id, $this->getType(), "", - (ilSkillTreeNode::_lookupStatus($obj_id) == ilSkillTreeNode::STATUS_DRAFT))); - } - - //// - //// Usage - //// - - /** - * Add usage tab - * - * @param - * @return - */ - function addUsageTab($a_tabs) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $a_tabs->addTab("usage", - $lng->txt("skmg_usage"), - $ilCtrl->getLinkTarget($this, "showUsage")); - } - - - /** - * Show skill usage - */ - function showUsage() - { - $tpl = $this->tpl; - - $this->setTabs("usage"); - - include_once("./Services/Skill/classes/class.ilSkillUsage.php"); - $usage_info = new ilSkillUsage(); - $base_skill_id = ($this->base_skill_id > 0) - ? $this->base_skill_id - : $this->node_object->getId(); - $usages = $usage_info->getAllUsagesInfoOfSubtree($base_skill_id.":".$this->tref_id); - - $html = ""; - include_once("./Services/Skill/classes/class.ilSkillUsageTableGUI.php"); - foreach ($usages as $k => $usage) - { - $tab = new ilSkillUsageTableGUI($this, "showUsage", $k, $usage); - $html.= $tab->getHTML()."

                  "; - } - - $tpl->setContent($html); - } - - /** - * Export seleced nodes - */ - function exportSelectedNodes() - { - $ilCtrl = $this->ctrl; - - if (!is_array($_POST["id"]) || count($_POST["id"]) == 0) - { - $this->redirectToParent(); - } - - include_once("./Services/Export/classes/class.ilExport.php"); - $exp = new ilExport(); - $conf = $exp->getConfig("Services/Skill"); - $conf->setSelectedNodes($_POST["id"]); - $exp->exportObject("skmg", ilObject::_lookupObjId((int) $_GET["ref_id"])); - - $ilCtrl->redirectByClass(array("iladministrationgui", "ilobjskillmanagementgui", "ilexportgui"), ""); - } - + /** + * After saving + */ + public function afterSave() + { + $this->redirectToParent(); + } + + + /** + * Update skill tree node + * + */ + public function update() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if (!$this->checkPermissionBool("write")) { + return; + } + + $this->initForm("edit"); + if ($this->form->checkInput()) { + $this->updateItem(); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $this->afterUpdate(); + } else { + $this->form->setValuesByPost(); + $tpl->setContent($this->form->getHtml()); + } + } + + /** + * After update + */ + public function afterUpdate() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirect($this, "editProperties"); + } + + /** + * Init form. + * + * @param int $a_mode Edit Mode + */ + public function initForm($a_mode = "edit") + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + // title + $ti = new ilTextInputGUI($lng->txt("title"), "title"); + $ti->setMaxLength(200); + $ti->setSize(50); + $ti->setRequired(true); + $this->form->addItem($ti); + + // order nr + $ni = new ilNumberInputGUI($lng->txt("skmg_order_nr"), "order_nr"); + $ni->setInfo($lng->txt("skmg_order_nr_info")); + $ni->setMaxLength(6); + $ni->setSize(6); + $ni->setRequired(true); + if ($a_mode == "create") { + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $tree = new ilSkillTree(); + $max = $tree->getMaxOrderNr((int) $_GET["obj_id"]); + $ni->setValue($max + 10); + } + $this->form->addItem($ni); + + // save and cancel commands + if ($this->checkPermissionBool("write")) { + if ($a_mode == "create") { + $this->form->addCommandButton("save", $lng->txt("save")); + $this->form->addCommandButton("cancelSave", $lng->txt("cancel")); + $this->form->setTitle($lng->txt("skmg_create_" . $this->getType())); + } else { + $this->form->addCommandButton("update", $lng->txt("save")); + $this->form->setTitle($lng->txt("skmg_edit_" . $this->getType())); + } + } + + $ilCtrl->setParameter($this, "obj_id", $_GET["obj_id"]); + $this->form->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * Cancel saving + * + * @param + * @return + */ + public function cancelSave() + { + $this->redirectToParent(); + } + + /** + * Redirect to parent (identified by current obj_id) + * + * @param + * @return + */ + public function redirectToParent($a_tmp_mode = false) + { + $ilCtrl = $this->ctrl; + + if ($_GET["tmpmode"]) { + $a_tmp_mode = true; + } + + $t = ilSkillTreeNode::_lookupType((int) $_GET["obj_id"]); + + switch ($t) { + case "skrt": + $ilCtrl->setParameterByClass("ilskillrootgui", "obj_id", (int) $_GET["obj_id"]); + if ($a_tmp_mode) { + $ilCtrl->redirectByClass("ilskillrootgui", "listTemplates"); + } else { + $ilCtrl->redirectByClass("ilskillrootgui", "listSkills"); + } + break; + + case "sctp": + $ilCtrl->setParameterByClass("ilskilltemplatecategorygui", "obj_id", (int) $_GET["obj_id"]); + $ilCtrl->redirectByClass("ilskilltemplatecategorygui", "listItems"); + break; + + case "scat": + $ilCtrl->setParameterByClass("ilskillcategorygui", "obj_id", (int) $_GET["obj_id"]); + $ilCtrl->redirectByClass("ilskillcategorygui", "listItems"); + break; + } + } + + /** + * Save order + */ + public function saveOrder() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if (!$this->checkPermissionBool("write")) { + return; + } + + ilSkillTreeNode::saveChildsOrder( + (int) $_GET["obj_id"], + $_POST["order"], + (int) $_GET["tmpmode"] + ); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $this->redirectToParent((int) $_GET["tmpmode"]); + } + + /** + * Insert basic skills from clipboard + */ + public function insertBasicSkillClip() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); + $nodes = ilSkillTreeNode::insertItemsFromClip("skll", (int) $_GET["obj_id"]); + $this->redirectToParent(); + } + + /** + * Insert skill categories from clipboard + */ + public function insertSkillCategoryClip() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); + $nodes = ilSkillTreeNode::insertItemsFromClip("scat", (int) $_GET["obj_id"]); + $this->redirectToParent(); + } + + /** + * Insert skill template references from clipboard + */ + public function insertTemplateReferenceClip() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); + $nodes = ilSkillTreeNode::insertItemsFromClip("sktr", (int) $_GET["obj_id"]); + $this->redirectToParent(); + } + + /** + * Insert skill template from clipboard + */ + public function insertSkillTemplateClip() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); + $nodes = ilSkillTreeNode::insertItemsFromClip("sktp", (int) $_GET["obj_id"]); + $this->redirectToParent(); + } + /** + * Insert skill template category from clipboard + */ + public function insertTemplateCategoryClip() + { + $ilCtrl = $this->ctrl; + $ilUser = $this->user; + + include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); + $nodes = ilSkillTreeNode::insertItemsFromClip("sctp", (int) $_GET["obj_id"]); + $this->redirectToParent(); + } + + /** + * Set title icon + */ + public function setTitleIcon() + { + $tpl = $this->tpl; + + $obj_id = (is_object($this->node_object)) + ? $this->node_object->getId() + :0; + $tpl->setTitleIcon( + ilSkillTreeNode::getIconPath( + $obj_id, + $this->getType(), + "", + (ilSkillTreeNode::_lookupStatus($obj_id) == ilSkillTreeNode::STATUS_DRAFT) + ) + ); + } + + //// + //// Usage + //// + + /** + * Add usage tab + * + * @param + * @return + */ + public function addUsageTab($a_tabs) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $a_tabs->addTab( + "usage", + $lng->txt("skmg_usage"), + $ilCtrl->getLinkTarget($this, "showUsage") + ); + } + + + /** + * Show skill usage + */ + public function showUsage() + { + $tpl = $this->tpl; + + $this->setTabs("usage"); + + include_once("./Services/Skill/classes/class.ilSkillUsage.php"); + $usage_info = new ilSkillUsage(); + $base_skill_id = ($this->base_skill_id > 0) + ? $this->base_skill_id + : $this->node_object->getId(); + $usages = $usage_info->getAllUsagesInfoOfSubtree($base_skill_id . ":" . $this->tref_id); + + $html = ""; + include_once("./Services/Skill/classes/class.ilSkillUsageTableGUI.php"); + foreach ($usages as $k => $usage) { + $tab = new ilSkillUsageTableGUI($this, "showUsage", $k, $usage); + $html.= $tab->getHTML() . "

                  "; + } + + $tpl->setContent($html); + } + + /** + * Export seleced nodes + */ + public function exportSelectedNodes() + { + $ilCtrl = $this->ctrl; + + if (!is_array($_POST["id"]) || count($_POST["id"]) == 0) { + $this->redirectToParent(); + } + + include_once("./Services/Export/classes/class.ilExport.php"); + $exp = new ilExport(); + $conf = $exp->getConfig("Services/Skill"); + $conf->setSelectedNodes($_POST["id"]); + $exp->exportObject("skmg", ilObject::_lookupObjId((int) $_GET["ref_id"])); + + $ilCtrl->redirectByClass(array("iladministrationgui", "ilobjskillmanagementgui", "ilexportgui"), ""); + } } -?> diff --git a/Services/Skill/classes/class.ilSkillUsage.php b/Services/Skill/classes/class.ilSkillUsage.php index ca23a68715e078e851381e978c192bd227459581..987b86e16b63f0d733003bc90c0a6cbe56f930c9 100644 --- a/Services/Skill/classes/class.ilSkillUsage.php +++ b/Services/Skill/classes/class.ilSkillUsage.php @@ -17,7 +17,7 @@ include_once("./Services/Skill/interfaces/interface.ilSkillUsageInfo.php"); * - USER_MATERIAL: User has assigned material to the skill * - SELF_EVAL: User has self evaluated (may be USER_ASSIGNED in the future) * - PROFILE: Skill is used in skill profile (table "skl_profile_level") - * - RESOURCE: A resource is assigned to a skill level (table "skl_skill_resource") + * - RESOURCE: A resource is assigned to a skill level (table "skl_skill_resource") * * @author Alex Killing * @version $Id$ @@ -25,274 +25,273 @@ include_once("./Services/Skill/interfaces/interface.ilSkillUsageInfo.php"); */ class ilSkillUsage implements ilSkillUsageInfo { - const TYPE_GENERAL = "gen"; - const USER_ASSIGNED = "user"; - const PERSONAL_SKILL = "pers"; - const USER_MATERIAL = "mat"; - const SELF_EVAL = "seval"; - const PROFILE = "prof"; - const RESOURCE = "res"; - - // these classes implement the ilSkillUsageInfo interface - // currently this array is ok, we do not need any subscription model here - /*protected $classes = array("ilBasicSkill", "ilPersonalSkill", - "ilSkillSelfEvaluation", "ilSkillProfile", "ilSkillResources", "ilSkillUsage");*/ - protected $classes = array("ilBasicSkill", "ilPersonalSkill", "ilSkillProfile", "ilSkillResources", "ilSkillUsage"); - - /** - * Set usage - * - * @param int $a_obj_id object id - * @param int $a_skill_id skill id - * @param int $a_tref_id tref id - * @param bool $a_use in use true/false - */ - static function setUsage($a_obj_id, $a_skill_id, $a_tref_id, $a_use = true) - { - global $DIC; + const TYPE_GENERAL = "gen"; + const USER_ASSIGNED = "user"; + const PERSONAL_SKILL = "pers"; + const USER_MATERIAL = "mat"; + const SELF_EVAL = "seval"; + const PROFILE = "prof"; + const RESOURCE = "res"; + + // these classes implement the ilSkillUsageInfo interface + // currently this array is ok, we do not need any subscription model here + /*protected $classes = array("ilBasicSkill", "ilPersonalSkill", + "ilSkillSelfEvaluation", "ilSkillProfile", "ilSkillResources", "ilSkillUsage");*/ + protected $classes = array("ilBasicSkill", "ilPersonalSkill", "ilSkillProfile", "ilSkillResources", "ilSkillUsage"); + + /** + * Set usage + * + * @param int $a_obj_id object id + * @param int $a_skill_id skill id + * @param int $a_tref_id tref id + * @param bool $a_use in use true/false + */ + public static function setUsage($a_obj_id, $a_skill_id, $a_tref_id, $a_use = true) + { + global $DIC; - $ilDB = $DIC->database(); - - if ($a_use) - { - $ilDB->replace("skl_usage", - array( - "obj_id" => array("integer", $a_obj_id), - "skill_id" => array("integer", $a_skill_id), - "tref_id" => array("integer", $a_tref_id) - ), - array() - ); - } - else - { - $ilDB->manipulate($q = "DELETE FROM skl_usage WHERE ". - " obj_id = ".$ilDB->quote($a_obj_id, "integer"). - " AND skill_id = ".$ilDB->quote($a_skill_id, "integer"). - " AND tref_id = ".$ilDB->quote($a_tref_id, "integer") - ); -//echo $q; exit; - } - } - - /** - * Get usages - * - * @param int $a_skill_id skill id - * @param int $a_tref_id tref id - * @return array of int object ids - */ - static function getUsages($a_skill_id, $a_tref_id) - { - global $DIC; + $ilDB = $DIC->database(); + + if ($a_use) { + $ilDB->replace( + "skl_usage", + array( + "obj_id" => array("integer", $a_obj_id), + "skill_id" => array("integer", $a_skill_id), + "tref_id" => array("integer", $a_tref_id) + ), + array() + ); + } else { + $ilDB->manipulate( + $q = "DELETE FROM skl_usage WHERE " . + " obj_id = " . $ilDB->quote($a_obj_id, "integer") . + " AND skill_id = " . $ilDB->quote($a_skill_id, "integer") . + " AND tref_id = " . $ilDB->quote($a_tref_id, "integer") + ); + //echo $q; exit; + } + } + + /** + * Get usages + * + * @param int $a_skill_id skill id + * @param int $a_tref_id tref id + * @return array of int object ids + */ + public static function getUsages($a_skill_id, $a_tref_id) + { + global $DIC; - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT obj_id FROM skl_usage ". - " WHERE skill_id = ".$ilDB->quote($a_skill_id, "integer"). - " AND tref_id = ".$ilDB->quote($a_tref_id, "integer") - ); - $obj_ids = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $obj_ids[] = $rec["obj_id"]; - } - - return $obj_ids; - } - - /** - * Get usage info - * - * @param array $a_cskill_ids skill ids - * @param array $a_usages usages array - */ - static public function getUsageInfo($a_cskill_ids, &$a_usages) - { - global $DIC; + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT obj_id FROM skl_usage " . + " WHERE skill_id = " . $ilDB->quote($a_skill_id, "integer") . + " AND tref_id = " . $ilDB->quote($a_tref_id, "integer") + ); + $obj_ids = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $obj_ids[] = $rec["obj_id"]; + } + + return $obj_ids; + } + + /** + * Get usage info + * + * @param array $a_cskill_ids skill ids + * @param array $a_usages usages array + */ + public static function getUsageInfo($a_cskill_ids, &$a_usages) + { + global $DIC; - $ilDB = $DIC->database(); - - self::getUsageInfoGeneric($a_cskill_ids, $a_usages, ilSkillUsage::TYPE_GENERAL, - "skl_usage", "obj_id"); - } - - /** - * Get standard usage query - * - * @param array $a_cskill_ids skill ids - * @param array $a_usages usages array - */ - static function getUsageInfoGeneric($a_cskill_ids, &$a_usages, $a_usage_type, $a_table, $a_key_field, - $a_skill_field = "skill_id", $a_tref_field = "tref_id") - { - global $DIC; + $ilDB = $DIC->database(); + + self::getUsageInfoGeneric( + $a_cskill_ids, + $a_usages, + ilSkillUsage::TYPE_GENERAL, + "skl_usage", + "obj_id" + ); + } + + /** + * Get standard usage query + * + * @param array $a_cskill_ids skill ids + * @param array $a_usages usages array + */ + public static function getUsageInfoGeneric( + $a_cskill_ids, + &$a_usages, + $a_usage_type, + $a_table, + $a_key_field, + $a_skill_field = "skill_id", + $a_tref_field = "tref_id" + ) { + global $DIC; - $ilDB = $DIC->database(); + $ilDB = $DIC->database(); - if (count($a_cskill_ids) == 0) - { - return; - } + if (count($a_cskill_ids) == 0) { + return; + } - $w = "WHERE"; - $q = "SELECT ".$a_key_field.", ".$a_skill_field.", ".$a_tref_field." FROM ".$a_table." "; - foreach ($a_cskill_ids as $sk) - { - $q.= $w." (".$a_skill_field." = ".$ilDB->quote($sk["skill_id"], "integer"). - " AND ".$a_tref_field." = ".$ilDB->quote($sk["tref_id"], "integer").") "; - $w = "OR"; - } - $q.= " GROUP BY ".$a_key_field.", ".$a_skill_field.", ".$a_tref_field; + $w = "WHERE"; + $q = "SELECT " . $a_key_field . ", " . $a_skill_field . ", " . $a_tref_field . " FROM " . $a_table . " "; + foreach ($a_cskill_ids as $sk) { + $q.= $w . " (" . $a_skill_field . " = " . $ilDB->quote($sk["skill_id"], "integer") . + " AND " . $a_tref_field . " = " . $ilDB->quote($sk["tref_id"], "integer") . ") "; + $w = "OR"; + } + $q.= " GROUP BY " . $a_key_field . ", " . $a_skill_field . ", " . $a_tref_field; - $set = $ilDB->query($q); - while ($rec = $ilDB->fetchAssoc($set)) - { - $a_usages[$rec[$a_skill_field].":".$rec[$a_tref_field]][$a_usage_type][] = - array("key" => $rec[$a_key_field]); - } - } + $set = $ilDB->query($q); + while ($rec = $ilDB->fetchAssoc($set)) { + $a_usages[$rec[$a_skill_field] . ":" . $rec[$a_tref_field]][$a_usage_type][] = + array("key" => $rec[$a_key_field]); + } + } - - /** - * Get all usages info - * - * @param array of common skill ids ("skill_id" => skill_id, "tref_id" => tref_id) - * @return array usages - */ - function getAllUsagesInfo($a_cskill_ids) - { - $classes = $this->classes; - - $usages = array(); - foreach ($classes as $class) - { - // make static call - include_once("./Services/Skill/classes/class.".$class.".php"); - //call_user_func($class.'::getUsageInfo', $a_cskill_ids, $usages); - $class::getUsageInfo($a_cskill_ids, $usages); - } - return $usages; - } + + /** + * Get all usages info + * + * @param array of common skill ids ("skill_id" => skill_id, "tref_id" => tref_id) + * @return array usages + */ + public function getAllUsagesInfo($a_cskill_ids) + { + $classes = $this->classes; + + $usages = array(); + foreach ($classes as $class) { + // make static call + include_once("./Services/Skill/classes/class." . $class . ".php"); + //call_user_func($class.'::getUsageInfo', $a_cskill_ids, $usages); + $class::getUsageInfo($a_cskill_ids, $usages); + } + return $usages; + } - /** - * Get all usages info of subtree - * - * @param int $a_skill_id skill node id - * @param int $a_tref_id tref id - * @return array usages - */ - function getAllUsagesInfoOfSubtree($a_skill_id, $a_tref_id = 0) - { - // get nodes - include_once("./Services/Skill/classes/class.ilVirtualSkillTree.php"); - $vtree = new ilVirtualSkillTree(); - $nodes = $vtree->getSubTreeForCSkillId($a_skill_id.":".$a_tref_id); + /** + * Get all usages info of subtree + * + * @param int $a_skill_id skill node id + * @param int $a_tref_id tref id + * @return array usages + */ + public function getAllUsagesInfoOfSubtree($a_skill_id, $a_tref_id = 0) + { + // get nodes + include_once("./Services/Skill/classes/class.ilVirtualSkillTree.php"); + $vtree = new ilVirtualSkillTree(); + $nodes = $vtree->getSubTreeForCSkillId($a_skill_id . ":" . $a_tref_id); - return $this->getAllUsagesInfo($nodes); - } + return $this->getAllUsagesInfo($nodes); + } - /** - * Get all usages info of subtree - * - * @param array $a_cskill_ids array of common skill ids ("skill_id" => skill_id, "tref_id" => tref_id) - * @return array usages - */ - function getAllUsagesInfoOfSubtrees($a_cskill_ids) - { - // get nodes - include_once("./Services/Skill/classes/class.ilVirtualSkillTree.php"); - $vtree = new ilVirtualSkillTree(); - $allnodes = array(); - foreach ($a_cskill_ids as $s) - { - $nodes = $vtree->getSubTreeForCSkillId($s["skill_id"].":".$s["tref_id"]); - foreach ($nodes as $n) - { - $allnodes[] = $n; - } - } + /** + * Get all usages info of subtree + * + * @param array $a_cskill_ids array of common skill ids ("skill_id" => skill_id, "tref_id" => tref_id) + * @return array usages + */ + public function getAllUsagesInfoOfSubtrees($a_cskill_ids) + { + // get nodes + include_once("./Services/Skill/classes/class.ilVirtualSkillTree.php"); + $vtree = new ilVirtualSkillTree(); + $allnodes = array(); + foreach ($a_cskill_ids as $s) { + $nodes = $vtree->getSubTreeForCSkillId($s["skill_id"] . ":" . $s["tref_id"]); + foreach ($nodes as $n) { + $allnodes[] = $n; + } + } - return $this->getAllUsagesInfo($allnodes); - } + return $this->getAllUsagesInfo($allnodes); + } - /** - * Get all usages of template - * - * @param int $a_tempate_id template - * @return array usages array - */ - function getAllUsagesOfTemplate($a_tempate_id) - { - $skill_logger = ilLoggerFactory::getLogger('skll'); - $skill_logger->debug("ilSkillUsage: getAllUsagesOfTemplate(".$a_tempate_id.")"); + /** + * Get all usages of template + * + * @param int $a_tempate_id template + * @return array usages array + */ + public function getAllUsagesOfTemplate($a_tempate_id) + { + $skill_logger = ilLoggerFactory::getLogger('skll'); + $skill_logger->debug("ilSkillUsage: getAllUsagesOfTemplate(" . $a_tempate_id . ")"); - // get all trefs for template id - include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); - $trefs = ilSkillTemplateReference::_lookupTrefIdsForTemplateId($a_tempate_id); + // get all trefs for template id + include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); + $trefs = ilSkillTemplateReference::_lookupTrefIdsForTemplateId($a_tempate_id); - // get all usages of subtrees of template_id:tref - $cskill_ids = array(); - foreach ($trefs as $tref) - { - $cskill_ids[] = array("skill_id" => $a_tempate_id, "tref_id" => $tref); - $skill_logger->debug("ilSkillUsage: ... skill_id: ".$a_tempate_id.", tref_id: ".$tref."."); - } + // get all usages of subtrees of template_id:tref + $cskill_ids = array(); + foreach ($trefs as $tref) { + $cskill_ids[] = array("skill_id" => $a_tempate_id, "tref_id" => $tref); + $skill_logger->debug("ilSkillUsage: ... skill_id: " . $a_tempate_id . ", tref_id: " . $tref . "."); + } - $skill_logger->debug("ilSkillUsage: ... count cskill_ids: ".count($cskill_ids)."."); + $skill_logger->debug("ilSkillUsage: ... count cskill_ids: " . count($cskill_ids) . "."); - return $this->getAllUsagesInfoOfSubtrees($cskill_ids); - } + return $this->getAllUsagesInfoOfSubtrees($cskill_ids); + } - /** - * Get type info string - * - * @param string $a_type usage type - * @return string lang string - */ - static function getTypeInfoString($a_type) - { - global $DIC; + /** + * Get type info string + * + * @param string $a_type usage type + * @return string lang string + */ + public static function getTypeInfoString($a_type) + { + global $DIC; - $lng = $DIC->language(); - - return $lng->txt("skmg_usage_type_info_".$a_type); - } + $lng = $DIC->language(); + + return $lng->txt("skmg_usage_type_info_" . $a_type); + } - /** - * Get type info string - * - * @param - * @return - */ - static function getObjTypeString($a_type) - { - global $DIC; + /** + * Get type info string + * + * @param + * @return + */ + public static function getObjTypeString($a_type) + { + global $DIC; - $lng = $DIC->language(); - - switch ($a_type) - { - case self::TYPE_GENERAL: - case self::RESOURCE: - return $lng->txt("skmg_usage_obj_objects"); - break; - - case self::USER_ASSIGNED: - case self::PERSONAL_SKILL: - case self::USER_MATERIAL: - case self::SELF_EVAL: - return $lng->txt("skmg_usage_obj_users"); - break; - - case self::PROFILE: - return $lng->txt("skmg_usage_obj_profiles"); - break; - } - - return $lng->txt("skmg_usage_type_info_".$a_type); - } + $lng = $DIC->language(); + + switch ($a_type) { + case self::TYPE_GENERAL: + case self::RESOURCE: + return $lng->txt("skmg_usage_obj_objects"); + break; + + case self::USER_ASSIGNED: + case self::PERSONAL_SKILL: + case self::USER_MATERIAL: + case self::SELF_EVAL: + return $lng->txt("skmg_usage_obj_users"); + break; + case self::PROFILE: + return $lng->txt("skmg_usage_obj_profiles"); + break; + } + + return $lng->txt("skmg_usage_type_info_" . $a_type); + } } - -?> diff --git a/Services/Skill/classes/class.ilSkillUsageTableGUI.php b/Services/Skill/classes/class.ilSkillUsageTableGUI.php index b1653746984e33b4e431e27af73c9aa0155090a7..2990cd10a66024465bac2908e428fed84dd00fdc 100644 --- a/Services/Skill/classes/class.ilSkillUsageTableGUI.php +++ b/Services/Skill/classes/class.ilSkillUsageTableGUI.php @@ -14,74 +14,71 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilSkillUsageTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilAccessHandler - */ - protected $access; - - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_cskill_id, $a_usage) - { - 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(); - - $id_parts = explode(":", $a_cskill_id); - $this->skill_id = $id_parts[0]; - $this->tref_id = $id_parts[1]; - - $data = array(); - foreach ($a_usage as $k => $v) - { - $data[] = array("type" => $k, "usages" => $v); - } - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setData($data); - $this->setTitle(ilSkillTreeNode::_lookupTitle($this->skill_id, $this->tref_id)); - - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $tree = new ilSkillTree(); - $path = $tree->getSkillTreePathAsString($this->skill_id, $this->tref_id); - $this->setDescription($path); - - $this->addColumn($this->lng->txt("skmg_type"), "", "50%"); - $this->addColumn($this->lng->txt("skmg_number"), "", "50%"); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.skill_usage_row.html", "Services/Skill"); - $this->setEnableNumInfo(false); - -// $this->addMultiCommand("", $lng->txt("")); + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilAccessHandler + */ + protected $access; + + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_cskill_id, $a_usage) + { + 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(); + + $id_parts = explode(":", $a_cskill_id); + $this->skill_id = $id_parts[0]; + $this->tref_id = $id_parts[1]; + + $data = array(); + foreach ($a_usage as $k => $v) { + $data[] = array("type" => $k, "usages" => $v); + } + + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setData($data); + $this->setTitle(ilSkillTreeNode::_lookupTitle($this->skill_id, $this->tref_id)); + + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $tree = new ilSkillTree(); + $path = $tree->getSkillTreePathAsString($this->skill_id, $this->tref_id); + $this->setDescription($path); + + $this->addColumn($this->lng->txt("skmg_type"), "", "50%"); + $this->addColumn($this->lng->txt("skmg_number"), "", "50%"); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.skill_usage_row.html", "Services/Skill"); + $this->setEnableNumInfo(false); + + // $this->addMultiCommand("", $lng->txt("")); // $this->addCommandButton("", $lng->txt("")); - } - - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; -//var_dump($a_set); - $this->tpl->setVariable("TYPE_INFO", ilSkillUsage::getTypeInfoString($a_set["type"])); - $this->tpl->setVariable("NUMBER", count($a_set["usages"])); - $this->tpl->setVariable("OBJ_TYPE", ilSkillUsage::getObjTypeString($a_set["type"])); - } - + } + + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + //var_dump($a_set); + $this->tpl->setVariable("TYPE_INFO", ilSkillUsage::getTypeInfoString($a_set["type"])); + $this->tpl->setVariable("NUMBER", count($a_set["usages"])); + $this->tpl->setVariable("OBJ_TYPE", ilSkillUsage::getObjTypeString($a_set["type"])); + } } -?> \ No newline at end of file diff --git a/Services/Skill/classes/class.ilVirtualSkillTree.php b/Services/Skill/classes/class.ilVirtualSkillTree.php index c0fc09201d242e64baa6b7867574ccf9053b8e2c..9145b00b793257254f58a8db66250c1db0232f48 100644 --- a/Services/Skill/classes/class.ilVirtualSkillTree.php +++ b/Services/Skill/classes/class.ilVirtualSkillTree.php @@ -12,491 +12,440 @@ */ class ilVirtualSkillTree { - /** - * @var ilLanguage - */ - protected $lng; - - protected static $order_node_data = null; - protected $include_drafts = false; - protected $drafts = array(); - protected $include_outdated = false; - protected $outdated = array(); - - /** - * Constructor - */ - public function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - include_once("./Services/Skill/classes/class.ilSkillTree.php"); - $this->tree = new ilSkillTree(); - } - - /** - * Get root node - * - * @return array root node array - */ - function getRootNode() - { - $root_id = $this->tree->readRootId(); - $root_node = $this->tree->getNodeData($root_id); - unset($root_node["child"]); - $root_node["id"] = $root_id.":0"; - $root_node["cskill_id"] = $root_id.":0"; - - return $root_node; - } - - /** - * Set include drafts - * - * @param bool $a_val include drafts - */ - function setIncludeDrafts($a_val) - { - $this->include_drafts = $a_val; - } - - /** - * Get include drafts - * - * @return bool include drafts - */ - function getIncludeDrafts() - { - return $this->include_drafts; - } - - /** - * Set include outdated - * - * @param bool $a_val include outdated - */ - function setIncludeOutdated($a_val) - { - $this->include_outdated = $a_val; - } - - /** - * Get include outdated - * - * @return bool include outdated - */ - function getIncludeOutdated() - { - return $this->include_outdated; - } - - /** - * Get node - * - * @param string $a_id vtree id - * @return array node array - */ - function getNode($a_id) - { - $id_parts = explode(":", $a_id); - $skl_tree_id = $id_parts[0]; - $skl_template_tree_id = $id_parts[1]; - - if ($skl_template_tree_id == 0 || (ilSkillTemplateReference::_lookupTemplateId($skl_tree_id) - == $skl_template_tree_id)) - { - $node_data = $this->tree->getNodeData($skl_tree_id); - $node_data["parent"] = $node_data["parent"].":0"; - } - else - { - $node_data = $this->tree->getNodeData($skl_template_tree_id); - $node_data["parent"] = $skl_tree_id.":".$node_data["parent"]; - } - - unset($node_data["child"]); - unset($node_data["skl_tree_id"]); - unset($node_data["lft"]); - unset($node_data["rgt"]); - unset($node_data["depth"]); - - $node_data["id"] = $a_id; - $cid = $this->getCSkillIdForVTreeId($a_id); - $cid_parts = explode(":", $cid); - $node_data["skill_id"] = $cid_parts[0]; - $node_data["tref_id"] = $cid_parts[1]; - $node_data["cskill_id"] = $cid; - - - return $node_data; - } - - - /** - * Get childs of node - * - * @param string $a_parent_id parent id - * @return array childs - */ - function getChildsOfNode($a_parent_id) - { - $a_parent_id_parts = explode(":", $a_parent_id); - $a_parent_skl_tree_id = $a_parent_id_parts[0]; - $a_parent_skl_template_tree_id = $a_parent_id_parts[1]; - - if ($a_parent_skl_template_tree_id == 0) - { - $childs = $this->tree->getChildsByTypeFilter($a_parent_skl_tree_id, array("scat", "skll", "sktr"), "order_nr"); - } - else - { - $childs = $this->tree->getChildsByTypeFilter($a_parent_skl_template_tree_id, array("sktp", "sctp"), "order_nr"); - } - - include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); - $drafts = array(); - $outdated = array(); - foreach ($childs as $k => $c) - { - if ($a_parent_skl_template_tree_id > 0) - { - // we are in template tree only - $child_id = $a_parent_skl_tree_id.":".$c["child"]; - } - else if (!in_array($c["type"], array("sktr", "sctr"))) - { - // we are in main tree only - $child_id = $c["child"].":0"; - } - else - { - // get template id for references - include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); - $child_id = $c["child"].":".ilSkillTemplateReference::_lookupTemplateId($c["child"]); - } - unset($childs[$k]["child"]); - unset($childs[$k]["skl_tree_id"]); - unset($childs[$k]["lft"]); - unset($childs[$k]["rgt"]); - unset($childs[$k]["depth"]); - $childs[$k]["id"] = $child_id; -//echo "-".$child_id."-"; - $cid = $this->getCSkillIdForVTreeId($child_id); -//echo "-".$cid."-"; - $cid_parts = explode(":", $cid); - $childs[$k]["skill_id"] = $cid_parts[0]; - $childs[$k]["tref_id"] = $cid_parts[1]; - $childs[$k]["cskill_id"] = $cid; - $childs[$k]["parent"] = $a_parent_id; - - $this->parent[$c["id"]] = $a_parent_id; - - // @todo: prepare this for tref id? - if (ilSkillTreeNode::_lookupStatus($c["child"]) == ilSkillTreeNode::STATUS_DRAFT || - in_array($a_parent_id, $this->drafts)) - { - $this->drafts[] = $child_id; - $drafts[] = $k; - } - if (ilSkillTreeNode::_lookupStatus($c["child"]) == ilSkillTreeNode::STATUS_OUTDATED || - in_array($a_parent_id, $this->outdated)) - { - $this->outdated[] = $child_id; - $outdated[] = $k; - } - } - if (!$this->getIncludeDrafts()) - { - foreach ($drafts as $d) - { - unset($childs[$d]); - } - } - if (!$this->getIncludeOutdated()) - { - foreach ($outdated as $d) - { - unset($childs[$d]); - } - } - - return $childs; - } - - /** - * Get childs of node for cskill id - * - * @param string $a_cskill_id common skill id : - * @return array array of childs - */ - function getChildsOfNodeForCSkillId($a_cskill_id) - { - $id_parts = explode(":", $a_cskill_id); - if ($id_parts[1] == 0) - { - $id = $id_parts[0].":0"; - } - else - { - $id = $id_parts[1].":".$id_parts[0]; - } - return $this->getChildsOfNode($id); - } - - /** - * Get common skill id for tree id - * - * @param string $a_vtree_id vtree id - * @return string cskill id - */ - function getCSkillIdForVTreeId($a_vtree_id) - { - $id_parts = explode(":", $a_vtree_id); - if ($id_parts[1] == 0) - { - // skill in main tree - $skill_id = $id_parts[0]; - $tref_id = 0; - } - else - { - // skill in template - $tref_id = $id_parts[0]; - $skill_id = $id_parts[1]; - } - return $skill_id.":".$tref_id; - } - - /** - * Get tree id for common skill id - * - * @param - * @return - */ - function getVTreeIdForCSkillId($a_cskill_id) - { - $id_parts = explode(":", $a_cskill_id); - if ($id_parts[1] == 0) - { - $id = $id_parts[0].":0"; - } - else - { - $id = $id_parts[1].":".$id_parts[0]; - } - return $id; - } - - - - /** - * Get node content - * - * @param array $a_node node data - * @return string title - */ - function getNodeTitle($a_node) - { - $lng = $this->lng; - - $a_parent_id_parts = explode(":", $a_node["id"]); - $a_parent_skl_tree_id = $a_parent_id_parts[0]; - $a_parent_skl_template_tree_id = $a_parent_id_parts[1]; - - // title - $title = $a_node["title"]; - - // root? - if ($a_node["type"] == "skrt") - { - $lng->txt("skmg_skills"); - } - else - { - if ($a_node["type"] == "sktr") - { -// include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); + /** + * @var ilLanguage + */ + protected $lng; + + protected static $order_node_data = null; + protected $include_drafts = false; + protected $drafts = array(); + protected $include_outdated = false; + protected $outdated = array(); + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + include_once("./Services/Skill/classes/class.ilSkillTree.php"); + $this->tree = new ilSkillTree(); + } + + /** + * Get root node + * + * @return array root node array + */ + public function getRootNode() + { + $root_id = $this->tree->readRootId(); + $root_node = $this->tree->getNodeData($root_id); + unset($root_node["child"]); + $root_node["id"] = $root_id . ":0"; + $root_node["cskill_id"] = $root_id . ":0"; + + return $root_node; + } + + /** + * Set include drafts + * + * @param bool $a_val include drafts + */ + public function setIncludeDrafts($a_val) + { + $this->include_drafts = $a_val; + } + + /** + * Get include drafts + * + * @return bool include drafts + */ + public function getIncludeDrafts() + { + return $this->include_drafts; + } + + /** + * Set include outdated + * + * @param bool $a_val include outdated + */ + public function setIncludeOutdated($a_val) + { + $this->include_outdated = $a_val; + } + + /** + * Get include outdated + * + * @return bool include outdated + */ + public function getIncludeOutdated() + { + return $this->include_outdated; + } + + /** + * Get node + * + * @param string $a_id vtree id + * @return array node array + */ + public function getNode($a_id) + { + $id_parts = explode(":", $a_id); + $skl_tree_id = $id_parts[0]; + $skl_template_tree_id = $id_parts[1]; + + if ($skl_template_tree_id == 0 || (ilSkillTemplateReference::_lookupTemplateId($skl_tree_id) + == $skl_template_tree_id)) { + $node_data = $this->tree->getNodeData($skl_tree_id); + $node_data["parent"] = $node_data["parent"] . ":0"; + } else { + $node_data = $this->tree->getNodeData($skl_template_tree_id); + $node_data["parent"] = $skl_tree_id . ":" . $node_data["parent"]; + } + + unset($node_data["child"]); + unset($node_data["skl_tree_id"]); + unset($node_data["lft"]); + unset($node_data["rgt"]); + unset($node_data["depth"]); + + $node_data["id"] = $a_id; + $cid = $this->getCSkillIdForVTreeId($a_id); + $cid_parts = explode(":", $cid); + $node_data["skill_id"] = $cid_parts[0]; + $node_data["tref_id"] = $cid_parts[1]; + $node_data["cskill_id"] = $cid; + + + return $node_data; + } + + + /** + * Get childs of node + * + * @param string $a_parent_id parent id + * @return array childs + */ + public function getChildsOfNode($a_parent_id) + { + $a_parent_id_parts = explode(":", $a_parent_id); + $a_parent_skl_tree_id = $a_parent_id_parts[0]; + $a_parent_skl_template_tree_id = $a_parent_id_parts[1]; + + if ($a_parent_skl_template_tree_id == 0) { + $childs = $this->tree->getChildsByTypeFilter($a_parent_skl_tree_id, array("scat", "skll", "sktr"), "order_nr"); + } else { + $childs = $this->tree->getChildsByTypeFilter($a_parent_skl_template_tree_id, array("sktp", "sctp"), "order_nr"); + } + + include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); + $drafts = array(); + $outdated = array(); + foreach ($childs as $k => $c) { + if ($a_parent_skl_template_tree_id > 0) { + // we are in template tree only + $child_id = $a_parent_skl_tree_id . ":" . $c["child"]; + } elseif (!in_array($c["type"], array("sktr", "sctr"))) { + // we are in main tree only + $child_id = $c["child"] . ":0"; + } else { + // get template id for references + include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); + $child_id = $c["child"] . ":" . ilSkillTemplateReference::_lookupTemplateId($c["child"]); + } + unset($childs[$k]["child"]); + unset($childs[$k]["skl_tree_id"]); + unset($childs[$k]["lft"]); + unset($childs[$k]["rgt"]); + unset($childs[$k]["depth"]); + $childs[$k]["id"] = $child_id; + //echo "-".$child_id."-"; + $cid = $this->getCSkillIdForVTreeId($child_id); + //echo "-".$cid."-"; + $cid_parts = explode(":", $cid); + $childs[$k]["skill_id"] = $cid_parts[0]; + $childs[$k]["tref_id"] = $cid_parts[1]; + $childs[$k]["cskill_id"] = $cid; + $childs[$k]["parent"] = $a_parent_id; + + $this->parent[$c["id"]] = $a_parent_id; + + // @todo: prepare this for tref id? + if (ilSkillTreeNode::_lookupStatus($c["child"]) == ilSkillTreeNode::STATUS_DRAFT || + in_array($a_parent_id, $this->drafts)) { + $this->drafts[] = $child_id; + $drafts[] = $k; + } + if (ilSkillTreeNode::_lookupStatus($c["child"]) == ilSkillTreeNode::STATUS_OUTDATED || + in_array($a_parent_id, $this->outdated)) { + $this->outdated[] = $child_id; + $outdated[] = $k; + } + } + if (!$this->getIncludeDrafts()) { + foreach ($drafts as $d) { + unset($childs[$d]); + } + } + if (!$this->getIncludeOutdated()) { + foreach ($outdated as $d) { + unset($childs[$d]); + } + } + + return $childs; + } + + /** + * Get childs of node for cskill id + * + * @param string $a_cskill_id common skill id : + * @return array array of childs + */ + public function getChildsOfNodeForCSkillId($a_cskill_id) + { + $id_parts = explode(":", $a_cskill_id); + if ($id_parts[1] == 0) { + $id = $id_parts[0] . ":0"; + } else { + $id = $id_parts[1] . ":" . $id_parts[0]; + } + return $this->getChildsOfNode($id); + } + + /** + * Get common skill id for tree id + * + * @param string $a_vtree_id vtree id + * @return string cskill id + */ + public function getCSkillIdForVTreeId($a_vtree_id) + { + $id_parts = explode(":", $a_vtree_id); + if ($id_parts[1] == 0) { + // skill in main tree + $skill_id = $id_parts[0]; + $tref_id = 0; + } else { + // skill in template + $tref_id = $id_parts[0]; + $skill_id = $id_parts[1]; + } + return $skill_id . ":" . $tref_id; + } + + /** + * Get tree id for common skill id + * + * @param + * @return + */ + public function getVTreeIdForCSkillId($a_cskill_id) + { + $id_parts = explode(":", $a_cskill_id); + if ($id_parts[1] == 0) { + $id = $id_parts[0] . ":0"; + } else { + $id = $id_parts[1] . ":" . $id_parts[0]; + } + return $id; + } + + + + /** + * Get node content + * + * @param array $a_node node data + * @return string title + */ + public function getNodeTitle($a_node) + { + $lng = $this->lng; + + $a_parent_id_parts = explode(":", $a_node["id"]); + $a_parent_skl_tree_id = $a_parent_id_parts[0]; + $a_parent_skl_template_tree_id = $a_parent_id_parts[1]; + + // title + $title = $a_node["title"]; + + // root? + if ($a_node["type"] == "skrt") { + $lng->txt("skmg_skills"); + } else { + if ($a_node["type"] == "sktr") { + // include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); // $title.= " (".ilSkillTreeNode::_lookupTitle($a_parent_skl_template_tree_id).")"; - } - } - - return $title; - } - - /** - * Get sub tree - * - * @param string $a_cskill_id cskill id - * @param bool $a_only_basic return only basic skills (and basic skill templates) - * @return array node array - */ - function getSubTreeForCSkillId($a_cskill_id, $a_only_basic = false) - { - $id_parts = explode(":", $a_cskill_id); - if ($id_parts[1] == 0) - { - $id = $id_parts[0].":0"; - } - else - { - $id = $id_parts[1].":".$id_parts[0]; - } - - $result = array(); - - $node = $this->getNode($id); - if (!$a_only_basic || in_array($node["type"], array("skll", "sktp")) || - ($node["type"] == "sktr" && ilSkillTreeNode::_lookupType($node["skill_id"]) == "sktp")) - { - $result[] = $node; - } - $this->__getSubTreeRec($id, $result, $a_only_basic); - - return $result; - } - - /** - * Get subtree, internal - * - * @param string $id vtree id - * @param array $result node array (called by reference) - * @param bool $a_only_basic return only basic skills (and basic skill templates) - */ - private function __getSubTreeRec($id, &$result, $a_only_basic) - { - $childs = $this->getChildsOfNode($id); - foreach ($childs as $c) - { - if (!$a_only_basic || in_array($c["type"], array("skll", "sktp")) || - ($c["type"] == "sktr" && ilSkillTreeNode::_lookupType($c["skill_id"]) == "sktp")) - { - $result[] = $c; - } - $this->__getSubTreeRec($c["id"], $result, $a_only_basic); - } - } - - /** - * Is draft - * - * @param int $a_node_id node id - * @return bool is draft true/false - */ - function isDraft($a_node_id) - { - return in_array($a_node_id, $this->drafts); - } - - /** - * Is outdated - * - * @param int $a_node_id node id - * @return bool is outdated true/false - */ - function isOutdated($a_node_id) - { - return in_array($a_node_id, $this->outdated); - } - - /** - * Get ordererd nodeset for common skill ids - * - * @param string[]|array[] $c_skill_ids string of "skill_id:tref_id" skill ids or an array - * @param string $a_skill_id_key if first parameter is array[], this string identifies the key of the basic skill id - * @param string $a_tref_id_key if first parameter is array[], this string identifies the key of the tref id - * @return string[]|array[] - */ - function getOrderedNodeset($c_skill_ids, $a_skill_id_key = "", $a_tref_id_key = "") - { - global $DIC; - - $db = $DIC->database(); - - if (self::$order_node_data == null) - { - $node_data = array(); - $set = $db->query("SELECT t.child, t.parent, t.lft, n.order_nr FROM skl_tree t JOIN skl_tree_node n ON (t.child = n.obj_id)"); - while ($rec = $db->fetchAssoc($set)) - { - $node_data[$rec["child"]] = array( - "parent" => $rec["parent"], - "lft" => $rec["lft"], - "order_nr" => $rec["order_nr"], - ); - } - self::$order_node_data = $node_data; - } - else - { - $node_data = self::$order_node_data; - } - - uasort($c_skill_ids, function ($a, $b) use ($node_data, $a_skill_id_key, $a_tref_id_key) { - - // normalize to cskill strings - if (is_array($a)) - { - $cskilla = $a[$a_skill_id_key].":".$a[$a_tref_id_key]; - $cskillb = $b[$a_skill_id_key].":".$b[$a_tref_id_key]; - } - else - { - $cskilla = $a; - $cskillb = $b; - } - - // get vtree ids - $vida = explode(":", $this->getVTreeIdForCSkillId($cskilla)); - $vidb = explode(":", $this->getVTreeIdForCSkillId($cskillb)); - - $ua = $this->getFirstUncommonAncestors($vida[0], $vidb[0], $node_data); - if (is_array($ua)) - { - return ($node_data[$ua[0]]["order_nr"] - $node_data[$ua[1]]["order_nr"]); - } - // if we did not find a first uncommon ancestor, we are in the same node in the - // main tree, here, if we have tref ids, we let the template tree decide - if ($vida[1] > 0 && $vidb[1] > 0) - { - $ua = $this->getFirstUncommonAncestors($vida[1], $vidb[1], $node_data); - if (is_array($ua)) - { - return ($node_data[$ua[0]]["order_nr"] - $node_data[$ua[1]]["order_nr"]); - } - } - - return 0; - }); - - return $c_skill_ids; - } - - // get path in node data - protected function getPath($a, $node_data) { - $path[] = $a; - while($node_data[$a]["parent"] != 0) - { - $a = $node_data[$a]["parent"]; - $path[] = $a; - } - return array_reverse($path); - } - - // get first uncommon ancestors of $a and $b in $node_data - protected function getFirstUncommonAncestors($a, $b, $node_data) { - $path_a = $this->getPath($a, $node_data); - $path_b = $this->getPath($b, $node_data); - foreach ($path_a as $k => $v) - { - if ($v != $path_b[$k]) - { - return array($v, $path_b[$k]); - } - } - return false; - } - + } + } + + return $title; + } + + /** + * Get sub tree + * + * @param string $a_cskill_id cskill id + * @param bool $a_only_basic return only basic skills (and basic skill templates) + * @return array node array + */ + public function getSubTreeForCSkillId($a_cskill_id, $a_only_basic = false) + { + $id_parts = explode(":", $a_cskill_id); + if ($id_parts[1] == 0) { + $id = $id_parts[0] . ":0"; + } else { + $id = $id_parts[1] . ":" . $id_parts[0]; + } + + $result = array(); + + $node = $this->getNode($id); + if (!$a_only_basic || in_array($node["type"], array("skll", "sktp")) || + ($node["type"] == "sktr" && ilSkillTreeNode::_lookupType($node["skill_id"]) == "sktp")) { + $result[] = $node; + } + $this->__getSubTreeRec($id, $result, $a_only_basic); + + return $result; + } + + /** + * Get subtree, internal + * + * @param string $id vtree id + * @param array $result node array (called by reference) + * @param bool $a_only_basic return only basic skills (and basic skill templates) + */ + private function __getSubTreeRec($id, &$result, $a_only_basic) + { + $childs = $this->getChildsOfNode($id); + foreach ($childs as $c) { + if (!$a_only_basic || in_array($c["type"], array("skll", "sktp")) || + ($c["type"] == "sktr" && ilSkillTreeNode::_lookupType($c["skill_id"]) == "sktp")) { + $result[] = $c; + } + $this->__getSubTreeRec($c["id"], $result, $a_only_basic); + } + } + + /** + * Is draft + * + * @param int $a_node_id node id + * @return bool is draft true/false + */ + public function isDraft($a_node_id) + { + return in_array($a_node_id, $this->drafts); + } + + /** + * Is outdated + * + * @param int $a_node_id node id + * @return bool is outdated true/false + */ + public function isOutdated($a_node_id) + { + return in_array($a_node_id, $this->outdated); + } + + /** + * Get ordererd nodeset for common skill ids + * + * @param string[]|array[] $c_skill_ids string of "skill_id:tref_id" skill ids or an array + * @param string $a_skill_id_key if first parameter is array[], this string identifies the key of the basic skill id + * @param string $a_tref_id_key if first parameter is array[], this string identifies the key of the tref id + * @return string[]|array[] + */ + public function getOrderedNodeset($c_skill_ids, $a_skill_id_key = "", $a_tref_id_key = "") + { + global $DIC; + + $db = $DIC->database(); + + if (self::$order_node_data == null) { + $node_data = array(); + $set = $db->query("SELECT t.child, t.parent, t.lft, n.order_nr FROM skl_tree t JOIN skl_tree_node n ON (t.child = n.obj_id)"); + while ($rec = $db->fetchAssoc($set)) { + $node_data[$rec["child"]] = array( + "parent" => $rec["parent"], + "lft" => $rec["lft"], + "order_nr" => $rec["order_nr"], + ); + } + self::$order_node_data = $node_data; + } else { + $node_data = self::$order_node_data; + } + + uasort($c_skill_ids, function ($a, $b) use ($node_data, $a_skill_id_key, $a_tref_id_key) { + + // normalize to cskill strings + if (is_array($a)) { + $cskilla = $a[$a_skill_id_key] . ":" . $a[$a_tref_id_key]; + $cskillb = $b[$a_skill_id_key] . ":" . $b[$a_tref_id_key]; + } else { + $cskilla = $a; + $cskillb = $b; + } + + // get vtree ids + $vida = explode(":", $this->getVTreeIdForCSkillId($cskilla)); + $vidb = explode(":", $this->getVTreeIdForCSkillId($cskillb)); + + $ua = $this->getFirstUncommonAncestors($vida[0], $vidb[0], $node_data); + if (is_array($ua)) { + return ($node_data[$ua[0]]["order_nr"] - $node_data[$ua[1]]["order_nr"]); + } + // if we did not find a first uncommon ancestor, we are in the same node in the + // main tree, here, if we have tref ids, we let the template tree decide + if ($vida[1] > 0 && $vidb[1] > 0) { + $ua = $this->getFirstUncommonAncestors($vida[1], $vidb[1], $node_data); + if (is_array($ua)) { + return ($node_data[$ua[0]]["order_nr"] - $node_data[$ua[1]]["order_nr"]); + } + } + + return 0; + }); + + return $c_skill_ids; + } + + // get path in node data + protected function getPath($a, $node_data) + { + $path[] = $a; + while ($node_data[$a]["parent"] != 0) { + $a = $node_data[$a]["parent"]; + $path[] = $a; + } + return array_reverse($path); + } + + // get first uncommon ancestors of $a and $b in $node_data + protected function getFirstUncommonAncestors($a, $b, $node_data) + { + $path_a = $this->getPath($a, $node_data); + $path_b = $this->getPath($b, $node_data); + foreach ($path_a as $k => $v) { + if ($v != $path_b[$k]) { + return array($v, $path_b[$k]); + } + } + return false; + } } - -?> diff --git a/Services/Skill/classes/class.ilVirtualSkillTreeExplorerGUI.php b/Services/Skill/classes/class.ilVirtualSkillTreeExplorerGUI.php index b7376a2d1a4ad4b5808137e09af8ac6bdcca477c..5e14bb85553ef7bba6adeb5677f45052c4b4cbe0 100644 --- a/Services/Skill/classes/class.ilVirtualSkillTreeExplorerGUI.php +++ b/Services/Skill/classes/class.ilVirtualSkillTreeExplorerGUI.php @@ -4,7 +4,7 @@ include_once("./Services/UIComponent/Explorer2/classes/class.ilExplorerBaseGUI.php"); /** - * Virtual skill tree explorer + * Virtual skill tree explorer * * @author Alex Killing * @version $Id$ @@ -13,239 +13,223 @@ include_once("./Services/UIComponent/Explorer2/classes/class.ilExplorerBaseGUI.p */ class ilVirtualSkillTreeExplorerGUI extends ilExplorerBaseGUI { - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilCtrl - */ - protected $ctrl; - - protected $show_draft_nodes = false; - protected $show_outdated_nodes = false; - - /** - * Constructor - */ - public function __construct($a_id, $a_parent_obj, $a_parent_cmd) - { - global $DIC; - - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - parent::__construct($a_id, $a_parent_obj, $a_parent_cmd); - - include_once("./Services/Skill/classes/class.ilVirtualSkillTree.php"); - $this->vtree = new ilVirtualSkillTree(); - - $this->setSkipRootNode(false); - $this->setAjax(false); - } - - /** - * Set show draft nodes - * - * @param boolean $a_val show draft nodes - */ - function setShowDraftNodes($a_val) - { - $this->show_draft_nodes = $a_val; - $this->vtree->setIncludeDrafts($a_val); - } - - /** - * Get show draft nodes - * - * @return boolean show draft nodes - */ - function getShowDraftNodes() - { - return $this->show_draft_nodes; - } - - /** - * Set show outdated nodes - * - * @param boolean $a_val show outdated notes - */ - function setShowOutdatedNodes($a_val) - { - $this->show_outdated_nodes = $a_val; - $this->vtree->setIncludeOutdated($a_val); - } - - /** - * Get show outdated nodes - * - * @return boolean show outdated notes - */ - function getShowOutdatedNodes() - { - return $this->show_outdated_nodes; - } - - /** - * Get root node - * - * @return array root node data - */ - function getRootNode() - { - return $this->vtree->getRootNode(); - } - - /** - * Get node id - * - * @param array $a_node node data - * @return string node id - */ - function getNodeId($a_node) - { - return $a_node["id"]; - } - - /** - * @inheritdoc - */ - public function getDomNodeIdForNodeId($node_id) - { - return parent::getDomNodeIdForNodeId(str_replace(":", "_", $node_id)); - } - - /** - * @inheritdoc - */ - function getNodeIdForDomNodeId($a_dom_node_id) - { - $id = parent::getNodeIdForDomNodeId($a_dom_node_id); - return str_replace("_", ":", $id); - } - - - /** - * Get childs of node - * - * @param int $a_parent_id parent id - * @return array childs - */ - function getChildsOfNode($a_parent_id) - { - return $this->vtree->getChildsOfNode($a_parent_id); - } - - /** - * Get node content - * - * @param array - * @return - */ - function getNodeContent($a_node) - { - $lng = $this->lng; - - $a_parent_id_parts = explode(":", $a_node["id"]); - $a_parent_skl_tree_id = $a_parent_id_parts[0]; - $a_parent_skl_template_tree_id = $a_parent_id_parts[1]; - - // title - $title = $a_node["title"]; - - // root? - if ($a_node["type"] == "skrt") - { - $lng->txt("skmg_skills"); - } - else - { - if ($a_node["type"] == "sktr") - { -// include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilCtrl + */ + protected $ctrl; + + protected $show_draft_nodes = false; + protected $show_outdated_nodes = false; + + /** + * Constructor + */ + public function __construct($a_id, $a_parent_obj, $a_parent_cmd) + { + global $DIC; + + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + parent::__construct($a_id, $a_parent_obj, $a_parent_cmd); + + include_once("./Services/Skill/classes/class.ilVirtualSkillTree.php"); + $this->vtree = new ilVirtualSkillTree(); + + $this->setSkipRootNode(false); + $this->setAjax(false); + } + + /** + * Set show draft nodes + * + * @param boolean $a_val show draft nodes + */ + public function setShowDraftNodes($a_val) + { + $this->show_draft_nodes = $a_val; + $this->vtree->setIncludeDrafts($a_val); + } + + /** + * Get show draft nodes + * + * @return boolean show draft nodes + */ + public function getShowDraftNodes() + { + return $this->show_draft_nodes; + } + + /** + * Set show outdated nodes + * + * @param boolean $a_val show outdated notes + */ + public function setShowOutdatedNodes($a_val) + { + $this->show_outdated_nodes = $a_val; + $this->vtree->setIncludeOutdated($a_val); + } + + /** + * Get show outdated nodes + * + * @return boolean show outdated notes + */ + public function getShowOutdatedNodes() + { + return $this->show_outdated_nodes; + } + + /** + * Get root node + * + * @return array root node data + */ + public function getRootNode() + { + return $this->vtree->getRootNode(); + } + + /** + * Get node id + * + * @param array $a_node node data + * @return string node id + */ + public function getNodeId($a_node) + { + return $a_node["id"]; + } + + /** + * @inheritdoc + */ + public function getDomNodeIdForNodeId($node_id) + { + return parent::getDomNodeIdForNodeId(str_replace(":", "_", $node_id)); + } + + /** + * @inheritdoc + */ + public function getNodeIdForDomNodeId($a_dom_node_id) + { + $id = parent::getNodeIdForDomNodeId($a_dom_node_id); + return str_replace("_", ":", $id); + } + + + /** + * Get childs of node + * + * @param int $a_parent_id parent id + * @return array childs + */ + public function getChildsOfNode($a_parent_id) + { + return $this->vtree->getChildsOfNode($a_parent_id); + } + + /** + * Get node content + * + * @param array + * @return + */ + public function getNodeContent($a_node) + { + $lng = $this->lng; + + $a_parent_id_parts = explode(":", $a_node["id"]); + $a_parent_skl_tree_id = $a_parent_id_parts[0]; + $a_parent_skl_template_tree_id = $a_parent_id_parts[1]; + + // title + $title = $a_node["title"]; + + // root? + if ($a_node["type"] == "skrt") { + $lng->txt("skmg_skills"); + } else { + if ($a_node["type"] == "sktr") { + // include_once("./Services/Skill/classes/class.ilSkillTemplateReference.php"); // $title.= " (".ilSkillTreeNode::_lookupTitle($a_parent_skl_template_tree_id).")"; - } - } - - return $title; - } - - /** - * Get node icon - * - * @param array - * @return - */ - function getNodeIcon($a_node) - { - $a_id_parts = explode(":", $a_node["id"]); - $a_skl_template_tree_id = $a_id_parts[1]; - - // root? - if ($a_node["type"] == "skrt") - { - $icon = ilUtil::getImagePath("icon_scat.svg"); - } - else - { - $type = $a_node["type"]; - if ($type == "sktr") - { - include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); - $type = ilSkillTreeNode::_lookupType($a_skl_template_tree_id); - } - if ($type == "sktp") - { - $type = "skll"; - } - if ($type == "sctp") - { - $type = "scat"; - } - $icon = ilUtil::getImagePath("icon_".$type.".svg"); - } - - return $icon; - } - - /** - * Get href for node - * - * @param mixed $a_node node object/array - * @return string href attribute - */ - function getNodeHref($a_node) - { - $ilCtrl = $this->ctrl; - - // we have a tree id like : here - // use this, if you want a "common" skill id in format : - $id_parts = explode(":", $a_node["id"]); - if ($id_parts[1] == 0) - { - // skill in main tree - $skill_id = $a_node["id"]; - } - else - { - // skill in template - $skill_id = $id_parts[1].":".$id_parts[0]; - } - - return ""; - } - - /** - * Is clickable - * - * @param - * @return - */ - function isNodeClickable($a_node) - { - return false; - } - + } + } + + return $title; + } + + /** + * Get node icon + * + * @param array + * @return + */ + public function getNodeIcon($a_node) + { + $a_id_parts = explode(":", $a_node["id"]); + $a_skl_template_tree_id = $a_id_parts[1]; + + // root? + if ($a_node["type"] == "skrt") { + $icon = ilUtil::getImagePath("icon_scat.svg"); + } else { + $type = $a_node["type"]; + if ($type == "sktr") { + include_once("./Services/Skill/classes/class.ilSkillTreeNode.php"); + $type = ilSkillTreeNode::_lookupType($a_skl_template_tree_id); + } + if ($type == "sktp") { + $type = "skll"; + } + if ($type == "sctp") { + $type = "scat"; + } + $icon = ilUtil::getImagePath("icon_" . $type . ".svg"); + } + + return $icon; + } + + /** + * Get href for node + * + * @param mixed $a_node node object/array + * @return string href attribute + */ + public function getNodeHref($a_node) + { + $ilCtrl = $this->ctrl; + + // we have a tree id like : here + // use this, if you want a "common" skill id in format : + $id_parts = explode(":", $a_node["id"]); + if ($id_parts[1] == 0) { + // skill in main tree + $skill_id = $a_node["id"]; + } else { + // skill in template + $skill_id = $id_parts[1] . ":" . $id_parts[0]; + } + + return ""; + } + + /** + * Is clickable + * + * @param + * @return + */ + public function isNodeClickable($a_node) + { + return false; + } } - -?> diff --git a/Services/Skill/exceptions/class.ilSkillException.php b/Services/Skill/exceptions/class.ilSkillException.php index 04325f9de4b6e2482dc7777b19fa5bc0374a8388..797e3196be9f9f336119077e1c69a8b7eb223e95 100644 --- a/Services/Skill/exceptions/class.ilSkillException.php +++ b/Services/Skill/exceptions/class.ilSkillException.php @@ -13,6 +13,4 @@ include_once './Services/Exceptions/classes/class.ilException.php'; */ class ilSkillException extends ilException { - } -?> \ No newline at end of file diff --git a/Services/Skill/interfaces/interface.ilSkillUsageInfo.php b/Services/Skill/interfaces/interface.ilSkillUsageInfo.php index c1655e1c1777ed137c268943469e5f654803db4a..c1ffe4199bda29f6719306d69898b2e1a620dee8 100644 --- a/Services/Skill/interfaces/interface.ilSkillUsageInfo.php +++ b/Services/Skill/interfaces/interface.ilSkillUsageInfo.php @@ -12,11 +12,10 @@ */ interface ilSkillUsageInfo { - /** - * Get title of an assigned item - * - * @param array of common skill ids ("skill_id" => skill_id, "tref_id" => tref_id) - */ - static public function getUsageInfo($a_cskill_ids, &$a_usages); + /** + * Get title of an assigned item + * + * @param array of common skill ids ("skill_id" => skill_id, "tref_id" => tref_id) + */ + public static function getUsageInfo($a_cskill_ids, &$a_usages); } -?> \ No newline at end of file diff --git a/Services/Style/Content/classes/class.ilBackgroundImageInputGUI.php b/Services/Style/Content/classes/class.ilBackgroundImageInputGUI.php index 7181ccfa76c4913c1fe537456c1818cc49198991..679c521ced97db184b79608b891b3060b71a0cd1 100755 --- a/Services/Style/Content/classes/class.ilBackgroundImageInputGUI.php +++ b/Services/Style/Content/classes/class.ilBackgroundImageInputGUI.php @@ -1,192 +1,180 @@ +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilBackgroundImageInputGUI extends ilFormPropertyGUI { - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - protected $value; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + protected $value; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - parent::__construct($a_title, $a_postvar); - $this->setType("background_image"); - } + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + parent::__construct($a_title, $a_postvar); + $this->setType("background_image"); + } - /** - * Set Value. - * - * @param string $a_value Value - */ - function setValue($a_value) - { - $this->value = $a_value; - } + /** + * Set Value. + * + * @param string $a_value Value + */ + public function setValue($a_value) + { + $this->value = $a_value; + } - /** - * Get Value. - * - * @return string Value - */ - function getValue() - { - return $this->value; - } - - /** - * Set Images. - * - * @param array $a_images Images - */ - function setImages($a_images) - { - $this->images = $a_images; - } + /** + * Get Value. + * + * @return string Value + */ + public function getValue() + { + return $this->value; + } + + /** + * Set Images. + * + * @param array $a_images Images + */ + public function setImages($a_images) + { + $this->images = $a_images; + } - /** - * Get Images. - * - * @return array Images - */ - function getImages() - { - return $this->images; - } + /** + * Get Images. + * + * @return array Images + */ + public function getImages() + { + return $this->images; + } - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - $type = $_POST[$this->getPostVar()]["type"] = - ilUtil::stripSlashes($_POST[$this->getPostVar()]["type"]); - $int_value = $_POST[$this->getPostVar()]["int_value"] = - ilUtil::stripSlashes($_POST[$this->getPostVar()]["int_value"]); - $ext_value = $_POST[$this->getPostVar()]["ext_value"] = - ilUtil::stripSlashes($_POST[$this->getPostVar()]["ext_value"]); - - if ($this->getRequired() && $type == "ext" && trim($ext_value) == "") - { - $this->setAlert($lng->txt("msg_input_is_required")); + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + $type = $_POST[$this->getPostVar()]["type"] = + ilUtil::stripSlashes($_POST[$this->getPostVar()]["type"]); + $int_value = $_POST[$this->getPostVar()]["int_value"] = + ilUtil::stripSlashes($_POST[$this->getPostVar()]["int_value"]); + $ext_value = $_POST[$this->getPostVar()]["ext_value"] = + ilUtil::stripSlashes($_POST[$this->getPostVar()]["ext_value"]); + + if ($this->getRequired() && $type == "ext" && trim($ext_value) == "") { + $this->setAlert($lng->txt("msg_input_is_required")); - return false; - } + return false; + } - if ($type == "external") - { - $this->setValue($ext_value); - } - else - { - $this->setValue($int_value); - } - - return true; - } + if ($type == "external") { + $this->setValue($ext_value); + } else { + $this->setValue($int_value); + } + + return true; + } - /** - * Insert property html - */ - function insert(&$a_tpl) - { - $tpl = new ilTemplate("tpl.prop_background_image.html", true, true, "Services/Style/Content"); + /** + * Insert property html + */ + public function insert(&$a_tpl) + { + $tpl = new ilTemplate("tpl.prop_background_image.html", true, true, "Services/Style/Content"); - $tpl->setVariable("POSTVAR", $this->getPostVar()); - - $int_options = array_merge(array("" => ""), $this->getImages()); - - $value = trim($this->getValue()); + $tpl->setVariable("POSTVAR", $this->getPostVar()); + + $int_options = array_merge(array("" => ""), $this->getImages()); + + $value = trim($this->getValue()); - if (is_int(strpos($value, "/"))) - { - $current_type = "ext"; - $tpl->setVariable("EXTERNAL_SELECTED", 'checked="checked"'); - $tpl->setVariable("VAL_EXT", ilUtil::prepareFormOutput($value)); - } - else - { - $current_type = "int"; - $tpl->setVariable("INTERNAL_SELECTED", 'checked="checked"'); - } - - foreach ($int_options as $option) - { - $tpl->setCurrentBlock("int_option"); - $tpl->setVariable("VAL_INT", $option); - $tpl->setVariable("TXT_INT", $option); + if (is_int(strpos($value, "/"))) { + $current_type = "ext"; + $tpl->setVariable("EXTERNAL_SELECTED", 'checked="checked"'); + $tpl->setVariable("VAL_EXT", ilUtil::prepareFormOutput($value)); + } else { + $current_type = "int"; + $tpl->setVariable("INTERNAL_SELECTED", 'checked="checked"'); + } + + foreach ($int_options as $option) { + $tpl->setCurrentBlock("int_option"); + $tpl->setVariable("VAL_INT", $option); + $tpl->setVariable("TXT_INT", $option); - if ($current_type == "int" && $value == $option) - { - $tpl->setVariable("INT_SELECTED", 'selected="selected"'); - } - $tpl->parseCurrentBlock(); - } + if ($current_type == "int" && $value == $option) { + $tpl->setVariable("INT_SELECTED", 'selected="selected"'); + } + $tpl->parseCurrentBlock(); + } - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $tpl->get()); - $a_tpl->parseCurrentBlock(); - } + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $tpl->get()); + $a_tpl->parseCurrentBlock(); + } - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $ilUser = $this->user; - - if ($a_values[$this->getPostVar()]["type"] == "internal") - { - $this->setValue($a_values[$this->getPostVar()]["int_value"]); - } - else - { - $this->setValue($a_values[$this->getPostVar()]["ext_value"]); - } - } + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $ilUser = $this->user; + + if ($a_values[$this->getPostVar()]["type"] == "internal") { + $this->setValue($a_values[$this->getPostVar()]["int_value"]); + } else { + $this->setValue($a_values[$this->getPostVar()]["ext_value"]); + } + } } diff --git a/Services/Style/Content/classes/class.ilBackgroundPositionInputGUI.php b/Services/Style/Content/classes/class.ilBackgroundPositionInputGUI.php index 4eb6a89d8fac239dd0f74bf3c7d33a28fb1b0ed6..2181456fd07529823dc848fafeb74c023ee58bf8 100755 --- a/Services/Style/Content/classes/class.ilBackgroundPositionInputGUI.php +++ b/Services/Style/Content/classes/class.ilBackgroundPositionInputGUI.php @@ -1,314 +1,278 @@ +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilBackgroundPositionInputGUI extends ilFormPropertyGUI { - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - protected $value; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + protected $value; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - parent::__construct($a_title, $a_postvar); - $this->setType("border_width"); - $this->dirs = array("horizontal", "vertical"); - } + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + parent::__construct($a_title, $a_postvar); + $this->setType("border_width"); + $this->dirs = array("horizontal", "vertical"); + } - /** - * Set Horizontal Value. - * - * @param string $a_horizontalvalue Horizontal Value - */ - function setHorizontalValue($a_horizontalvalue) - { - $this->horizontalvalue = $a_horizontalvalue; - } + /** + * Set Horizontal Value. + * + * @param string $a_horizontalvalue Horizontal Value + */ + public function setHorizontalValue($a_horizontalvalue) + { + $this->horizontalvalue = $a_horizontalvalue; + } - /** - * Get Horizontal Value. - * - * @return string Horizontal Value - */ - function getHorizontalValue() - { - return $this->horizontalvalue; - } + /** + * Get Horizontal Value. + * + * @return string Horizontal Value + */ + public function getHorizontalValue() + { + return $this->horizontalvalue; + } - /** - * Set Vertical Value. - * - * @param string $a_verticalvalue Vertical Value - */ - function setVerticalValue($a_verticalvalue) - { - $this->verticalvalue = $a_verticalvalue; - } + /** + * Set Vertical Value. + * + * @param string $a_verticalvalue Vertical Value + */ + public function setVerticalValue($a_verticalvalue) + { + $this->verticalvalue = $a_verticalvalue; + } - /** - * Get Vertical Value. - * - * @return string Vertical Value - */ - function getVerticalValue() - { - return $this->verticalvalue; - } + /** + * Get Vertical Value. + * + * @return string Vertical Value + */ + public function getVerticalValue() + { + return $this->verticalvalue; + } - /** - * Get value - */ - function getValue() - { - if ($this->getHorizontalValue() != "") - { - if ($this->getVerticalValue() != "") - { - return $this->getHorizontalValue()." ".$this->getVerticalValue(); - } - else - { - return $this->getHorizontalValue(); - } - } - else - { - if ($this->getVerticalValue() != "") - { - return "left ".$this->getVerticalValue(); - } - } - return ""; - } - - /** - * Set value - */ - function setValue($a_val) - { - $a_val = trim($a_val); - $a_val_arr = explode(" ", $a_val); - $hor = trim($a_val_arr[0]); - $ver = trim($a_val_arr[1]); - if ($hor == "center" && $ver == "") - { - $ver = "center"; - } - $this->setHorizontalValue($hor); - $this->setVerticalValue($ver); - } - - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - foreach ($this->dirs as $dir) - { - $type = $_POST[$this->getPostVar()][$dir]["type"] = - ilUtil::stripSlashes($_POST[$this->getPostVar()][$dir]["type"]); - $num_value = $_POST[$this->getPostVar()][$dir]["num_value"] = - trim(ilUtil::stripSlashes($_POST[$this->getPostVar()][$dir]["num_value"])); - $num_unit = $_POST[$this->getPostVar()][$dir]["num_unit"] = - trim(ilUtil::stripSlashes($_POST[$this->getPostVar()][$dir]["num_unit"])); - $pre_value = $_POST[$this->getPostVar()][$dir]["pre_calue"] = - ilUtil::stripSlashes($_POST[$this->getPostVar()][$dir]["pre_value"]); - - /* - if ($this->getRequired() && trim($num_value) == "") - { - $this->setAlert($lng->txt("msg_input_is_required")); - - return false; - }*/ - - if (!is_numeric($num_value) && trim($num_value) != "") - { - $this->setAlert($lng->txt("sty_msg_input_must_be_numeric")); - return false; - } - - $value = ""; - if ($type == "numeric") - { - if ($num_value != "") - { - $value = $num_value.$num_unit; - } - } - else - { - $value = $pre_value; - } - - if (trim($value) != "") - { - switch ($dir) - { - case "horizontal": $this->setHorizontalValue($value); break; - case "vertical": $this->setVerticalValue($value); break; - } - } - - } - - return true; - } + /** + * Get value + */ + public function getValue() + { + if ($this->getHorizontalValue() != "") { + if ($this->getVerticalValue() != "") { + return $this->getHorizontalValue() . " " . $this->getVerticalValue(); + } else { + return $this->getHorizontalValue(); + } + } else { + if ($this->getVerticalValue() != "") { + return "left " . $this->getVerticalValue(); + } + } + return ""; + } + + /** + * Set value + */ + public function setValue($a_val) + { + $a_val = trim($a_val); + $a_val_arr = explode(" ", $a_val); + $hor = trim($a_val_arr[0]); + $ver = trim($a_val_arr[1]); + if ($hor == "center" && $ver == "") { + $ver = "center"; + } + $this->setHorizontalValue($hor); + $this->setVerticalValue($ver); + } + + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + foreach ($this->dirs as $dir) { + $type = $_POST[$this->getPostVar()][$dir]["type"] = + ilUtil::stripSlashes($_POST[$this->getPostVar()][$dir]["type"]); + $num_value = $_POST[$this->getPostVar()][$dir]["num_value"] = + trim(ilUtil::stripSlashes($_POST[$this->getPostVar()][$dir]["num_value"])); + $num_unit = $_POST[$this->getPostVar()][$dir]["num_unit"] = + trim(ilUtil::stripSlashes($_POST[$this->getPostVar()][$dir]["num_unit"])); + $pre_value = $_POST[$this->getPostVar()][$dir]["pre_calue"] = + ilUtil::stripSlashes($_POST[$this->getPostVar()][$dir]["pre_value"]); + + /* + if ($this->getRequired() && trim($num_value) == "") + { + $this->setAlert($lng->txt("msg_input_is_required")); - /** - * Insert property html - */ - function insert(&$a_tpl) - { - $lng = $this->lng; - - $layout_tpl = new ilTemplate("tpl.prop_hv_layout.html", true, true, "Services/Style/Content"); - - foreach ($this->dirs as $dir) - { - $tpl = new ilTemplate("tpl.prop_background_position.html", true, true, "Services/Style/Content"); - $unit_options = ilObjStyleSheet::_getStyleParameterNumericUnits(); - $pre_options = ilObjStyleSheet::_getStyleParameterValues("background-position"); - $pre_options = $pre_options[$dir]; - switch($dir) - { - case "horizontal": $value = strtolower(trim($this->getHorizontalValue())); break; - case "vertical": $value = strtolower(trim($this->getVerticalValue())); break; - } - - if (in_array($value, $pre_options)) - { - $current_type = "pre"; - $tpl->setVariable("PREDEFINED_SELECTED", 'checked="checked"'); - } - else - { - $current_type = "unit"; - $tpl->setVariable("NUMERIC_SELECTED", 'checked="checked"'); + return false; + }*/ + + if (!is_numeric($num_value) && trim($num_value) != "") { + $this->setAlert($lng->txt("sty_msg_input_must_be_numeric")); + return false; + } + + $value = ""; + if ($type == "numeric") { + if ($num_value != "") { + $value = $num_value . $num_unit; + } + } else { + $value = $pre_value; + } + + if (trim($value) != "") { + switch ($dir) { + case "horizontal": $this->setHorizontalValue($value); break; + case "vertical": $this->setVerticalValue($value); break; + } + } + } + + return true; + } - $current_unit = ""; - foreach ($unit_options as $u) - { - if (substr($value, strlen($value) - strlen($u)) == $u) - { - $current_unit = $u; - } - } - $disp_val = substr($value, 0, strlen($value) - strlen($current_unit)); - if ($current_unit == "") - { - $current_unit = "px"; - } - $tpl->setVariable("VAL_NUM", $disp_val); - } - - foreach ($unit_options as $option) - { - $tpl->setCurrentBlock("unit_option"); - $tpl->setVariable("VAL_UNIT", $option); - $tpl->setVariable("TXT_UNIT", $option); - if ($current_type == "unit" && $current_unit == $option) - { - $tpl->setVariable("UNIT_SELECTED", 'selected="selected"'); - } - $tpl->parseCurrentBlock(); - } - - foreach ($pre_options as $option) - { - $tpl->setCurrentBlock("pre_option"); - $tpl->setVariable("VAL_PRE", $option); - $tpl->setVariable("TXT_PRE", $option); - if ($current_type == "pre" && $value == $option) - { - $tpl->setVariable("PRE_SELECTED", 'selected="selected"'); - } - $tpl->parseCurrentBlock(); - } + /** + * Insert property html + */ + public function insert(&$a_tpl) + { + $lng = $this->lng; + + $layout_tpl = new ilTemplate("tpl.prop_hv_layout.html", true, true, "Services/Style/Content"); + + foreach ($this->dirs as $dir) { + $tpl = new ilTemplate("tpl.prop_background_position.html", true, true, "Services/Style/Content"); + $unit_options = ilObjStyleSheet::_getStyleParameterNumericUnits(); + $pre_options = ilObjStyleSheet::_getStyleParameterValues("background-position"); + $pre_options = $pre_options[$dir]; + switch ($dir) { + case "horizontal": $value = strtolower(trim($this->getHorizontalValue())); break; + case "vertical": $value = strtolower(trim($this->getVerticalValue())); break; + } + + if (in_array($value, $pre_options)) { + $current_type = "pre"; + $tpl->setVariable("PREDEFINED_SELECTED", 'checked="checked"'); + } else { + $current_type = "unit"; + $tpl->setVariable("NUMERIC_SELECTED", 'checked="checked"'); - $tpl->setVariable("POSTVAR", $this->getPostVar()); - $tpl->setVariable("TXT_DIR", $lng->txt("sty_$dir")); - $tpl->setVariable("DIR", $dir); - - $layout_tpl->setVariable(strtoupper($dir), $tpl->get()); - } - $layout_tpl->setVariable("COLSPAN", "2"); - - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $layout_tpl->get()); - $a_tpl->parseCurrentBlock(); - } + $current_unit = ""; + foreach ($unit_options as $u) { + if (substr($value, strlen($value) - strlen($u)) == $u) { + $current_unit = $u; + } + } + $disp_val = substr($value, 0, strlen($value) - strlen($current_unit)); + if ($current_unit == "") { + $current_unit = "px"; + } + $tpl->setVariable("VAL_NUM", $disp_val); + } + + foreach ($unit_options as $option) { + $tpl->setCurrentBlock("unit_option"); + $tpl->setVariable("VAL_UNIT", $option); + $tpl->setVariable("TXT_UNIT", $option); + if ($current_type == "unit" && $current_unit == $option) { + $tpl->setVariable("UNIT_SELECTED", 'selected="selected"'); + } + $tpl->parseCurrentBlock(); + } + + foreach ($pre_options as $option) { + $tpl->setCurrentBlock("pre_option"); + $tpl->setVariable("VAL_PRE", $option); + $tpl->setVariable("TXT_PRE", $option); + if ($current_type == "pre" && $value == $option) { + $tpl->setVariable("PRE_SELECTED", 'selected="selected"'); + } + $tpl->parseCurrentBlock(); + } - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $ilUser = $this->user; - - if ($a_values[$this->getPostVar()]["horizontal"]["type"] == "predefined") - { - $this->setHorizontalValue($a_values[$this->getPostVar()]["horizontal"]["pre_value"]); - } - else - { - $this->setHorizontalValue($a_values[$this->getPostVar()]["horizontal"]["num_value"]. - $a_values[$this->getPostVar()]["horizontal"]["num_unit"]); - } - if ($a_values[$this->getPostVar()]["vertical"]["type"] == "predefined") - { - $this->setVerticalValue($a_values[$this->getPostVar()]["vertical"]["pre_value"]); - } - else - { - $this->setVerticalValue($a_values[$this->getPostVar()]["vertical"]["num_value"]. - $a_values[$this->getPostVar()]["vertical"]["num_unit"]); - } - } + $tpl->setVariable("POSTVAR", $this->getPostVar()); + $tpl->setVariable("TXT_DIR", $lng->txt("sty_$dir")); + $tpl->setVariable("DIR", $dir); + + $layout_tpl->setVariable(strtoupper($dir), $tpl->get()); + } + $layout_tpl->setVariable("COLSPAN", "2"); + + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $layout_tpl->get()); + $a_tpl->parseCurrentBlock(); + } + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $ilUser = $this->user; + + if ($a_values[$this->getPostVar()]["horizontal"]["type"] == "predefined") { + $this->setHorizontalValue($a_values[$this->getPostVar()]["horizontal"]["pre_value"]); + } else { + $this->setHorizontalValue($a_values[$this->getPostVar()]["horizontal"]["num_value"] . + $a_values[$this->getPostVar()]["horizontal"]["num_unit"]); + } + if ($a_values[$this->getPostVar()]["vertical"]["type"] == "predefined") { + $this->setVerticalValue($a_values[$this->getPostVar()]["vertical"]["pre_value"]); + } else { + $this->setVerticalValue($a_values[$this->getPostVar()]["vertical"]["num_value"] . + $a_values[$this->getPostVar()]["vertical"]["num_unit"]); + } + } } diff --git a/Services/Style/Content/classes/class.ilContentStyleSettings.php b/Services/Style/Content/classes/class.ilContentStyleSettings.php index 6d9e8157255ed90c90cd59c505425c6e46281587..7f2325e4b0ff1bcd4fc1301e8511041dab377ffe 100644 --- a/Services/Style/Content/classes/class.ilContentStyleSettings.php +++ b/Services/Style/Content/classes/class.ilContentStyleSettings.php @@ -11,104 +11,100 @@ */ class ilContentStyleSettings { - /** - * @var ilDB - */ - protected $db; - - var $styles = array(); - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->db = $DIC->database(); - $this->read(); - } - - /** - * Add style to style folder - * - * @param int $a_style_id style id - */ - public function addStyle($a_style_id) - { - $this->styles[$a_style_id] = - array("id" => $a_style_id, - "title" => ilObject::_lookupTitle($a_style_id)); - } - - - /** - * remove Style from style list - */ - public function removeStyle($a_id) - { - unset($this->styles[$a_id]); - } - - - /** - * update object data - * - * @return boolean - */ - public function update() - { - $ilDB = $this->db; - - // save styles of style folder - // note: there are no different style folders in ILIAS, only the one in the settings - $q = "DELETE FROM style_folder_styles"; - $ilDB->manipulate($q); - foreach($this->styles as $style) - { - $q = "INSERT INTO style_folder_styles (folder_id, style_id) VALUES". - "(".$ilDB->quote((int) 0, "integer").", ". - $ilDB->quote((int) $style["id"], "integer").")"; - $ilDB->manipulate($q); - } - - return true; - } - - /** - * read style folder data - */ - function read() - { - $ilDB = $this->db; - - // get styles of style folder - $q = "SELECT * FROM style_folder_styles JOIN style_data ON (style_id = style_data.id)"; - - $style_set = $ilDB->query($q); - $this->styles = array(); - while ($style_rec = $ilDB->fetchAssoc($style_set)) - { - $this->styles[$style_rec["style_id"]] = - array("id" => $style_rec["style_id"], - "title" => ilObject::_lookupTitle($style_rec["style_id"]), - "category" => $style_rec["category"]); - } - - $this->styles = - ilUtil::sortArray($this->styles, "title", "asc", false, true); - } - - - /** - * get style ids - * - * @return array ids - */ - function getStyles() - { - return $this->styles; - } - + /** + * @var ilDB + */ + protected $db; + + public $styles = array(); + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->db = $DIC->database(); + $this->read(); + } + + /** + * Add style to style folder + * + * @param int $a_style_id style id + */ + public function addStyle($a_style_id) + { + $this->styles[$a_style_id] = + array("id" => $a_style_id, + "title" => ilObject::_lookupTitle($a_style_id)); + } + + + /** + * remove Style from style list + */ + public function removeStyle($a_id) + { + unset($this->styles[$a_id]); + } + + + /** + * update object data + * + * @return boolean + */ + public function update() + { + $ilDB = $this->db; + + // save styles of style folder + // note: there are no different style folders in ILIAS, only the one in the settings + $q = "DELETE FROM style_folder_styles"; + $ilDB->manipulate($q); + foreach ($this->styles as $style) { + $q = "INSERT INTO style_folder_styles (folder_id, style_id) VALUES" . + "(" . $ilDB->quote((int) 0, "integer") . ", " . + $ilDB->quote((int) $style["id"], "integer") . ")"; + $ilDB->manipulate($q); + } + + return true; + } + + /** + * read style folder data + */ + public function read() + { + $ilDB = $this->db; + + // get styles of style folder + $q = "SELECT * FROM style_folder_styles JOIN style_data ON (style_id = style_data.id)"; + + $style_set = $ilDB->query($q); + $this->styles = array(); + while ($style_rec = $ilDB->fetchAssoc($style_set)) { + $this->styles[$style_rec["style_id"]] = + array("id" => $style_rec["style_id"], + "title" => ilObject::_lookupTitle($style_rec["style_id"]), + "category" => $style_rec["category"]); + } + + $this->styles = + ilUtil::sortArray($this->styles, "title", "asc", false, true); + } + + + /** + * get style ids + * + * @return array ids + */ + public function getStyles() + { + return $this->styles; + } } -?> \ No newline at end of file diff --git a/Services/Style/Content/classes/class.ilContentStyleSettingsGUI.php b/Services/Style/Content/classes/class.ilContentStyleSettingsGUI.php index 7129cffddb7c60b39da4d6a14c7132105660ee95..01392ec260c7d63b5689dbe3343f42ca70024f60 100644 --- a/Services/Style/Content/classes/class.ilContentStyleSettingsGUI.php +++ b/Services/Style/Content/classes/class.ilContentStyleSettingsGUI.php @@ -12,504 +12,476 @@ */ class ilContentStyleSettingsGUI { - /** - * @var ilSetting - */ - protected $settings; - - /** - * @var ilTree - */ - protected $tree; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ILIAS\DI\Container - */ - protected $DIC; - - /** - * @var int - */ - protected $ref_id; - - /** - * Constructor - */ - function __construct(ilObjStyleSettingsGUI $a_parent_gui) - { - global $DIC; - - $this->tree = $DIC->repositoryTree(); - $this->settings = $DIC->settings(); - - $this->parent_gui = $a_parent_gui; - $this->dic = $DIC; - $this->ctrl = $DIC->ctrl(); - $this->rbacsystem = $DIC->rbac()->system(); - $this->toolbar = $DIC->toolbar(); - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - $this->ref_id = (int) $_GET["ref_id"]; - $this->obj_id = (int) $_GET["obj_id"]; // note that reference ID is the id of the style settings node and object ID may be a style sheet object ID - - - include_once("./Services/Style/Content/classes/class.ilContentStyleSettings.php"); - $this->cs_settings = new ilContentStyleSettings(); - } - - /** - * Execute command - */ - function executeCommand() - { - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd("edit"); - - switch ($next_class) - { - case "ilobjstylesheetgui": - $this->ctrl->setReturn($this, "edit"); - include_once("./Services/Style/Content/classes/class.ilObjStyleSheetGUI.php"); - $style_gui = new ilObjStyleSheetGUI("", $this->obj_id, false, false); - $this->ctrl->forwardCommand($style_gui); - break; - - default: - $this->parent_gui->prepareOutput(); - if (in_array($cmd, array("edit", "delete", "toggleGlobalDefault", "toggleGlobalFixed", "setScope", "saveScope", "saveActiveStyles", - "createStyle", "moveLMStyles", "moveIndividualStyles", "deleteStyle", "cancelDelete", "confirmedDelete"))) - { - $this->$cmd(); - } - else - { - die("Unknown command ".$cmd); - } - } - } - - /** - * Check permission - * - * @param string $a_perm permission(s) - * @return bool - * @throws ilObjectException - */ - function checkPermission($a_perm, $a_throw_exc = true) - { - if (!$this->rbacsystem->checkAccess($a_perm, $this->ref_id)) - { - if ($a_throw_exc) - { - include_once "Services/Object/exceptions/class.ilObjectException.php"; - throw new ilObjectException($this->lng->txt("permission_denied")); - } - return false; - } - return true; - } - - /** - * Create new style - */ - function createStyle() - { - $ilCtrl = $this->ctrl; - - // $ilCtrl->setParameterByClass("ilobjstylesheetgui", "new_type", "sty"); - $ilCtrl->redirectByClass("ilobjstylesheetgui", "create"); - } - - /** - * Show styles - */ - function edit() - { - $this->checkPermission("visible,read"); - - // this may not be cool, if styles are organised as (independent) Service - include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - - $from_styles = $to_styles = $data = array(); - $styles = $this->cs_settings->getStyles(); - foreach($styles as $style) - { - $style["active"] = ilObjStyleSheet::_lookupActive($style["id"]); - $style["lm_nr"] = ilObjContentObject::_getNrOfAssignedLMs($style["id"]); - $data[$style["title"].":".$style["id"]] - = $style; - if ($style["lm_nr"] > 0) - { - $from_styles[$style["id"]] = $style["title"]; - } - if ($style["active"] > 0) - { - $to_styles[$style["id"]] = $style["title"]; - } - } - - // number of individual styles - if ($fixed_style <= 0) - { - $data[-1] = - array("title" => $this->lng->txt("sty_individual_styles"), - "id" => 0, "lm_nr" => ilObjContentObject::_getNrLMsIndividualStyles()); - $from_styles[-1] = $this->lng->txt("sty_individual_styles"); - } - - // number of default style (fallback default style) - if ($default_style <= 0 && $fixed_style <= 0) - { - $data[0] = - array("title" => $this->lng->txt("sty_default_style"), - "id" => 0, "lm_nr" => ilObjContentObject::_getNrLMsNoStyle()); - $from_styles[0] = $this->lng->txt("sty_default_style"); - $to_styles[0] = $this->lng->txt("sty_default_style"); - } - - if ($this->checkPermission("sty_write_content", false)) - { - $this->toolbar->addButton($this->lng->txt("sty_add_content_style"), - $this->ctrl->getLinkTarget($this, "createStyle")); - $this->toolbar->addSeparator(); - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - - // from styles selector - $si = new ilSelectInputGUI($this->lng->txt("sty_move_lm_styles").": ".$this->lng->txt("sty_from"), "from_style"); - $si->setOptions($from_styles); - $this->toolbar->addInputItem($si, true); - - // from styles selector - $si = new ilSelectInputGUI($this->lng->txt("sty_to"), "to_style"); - $si->setOptions($to_styles); - $this->toolbar->addInputItem($si, true); - $this->toolbar->addFormButton($this->lng->txt("sty_move_style"), "moveLMStyles"); - - $this->toolbar->setFormAction($this->ctrl->getFormAction($this)); - } - - include_once("./Services/Style/Content/classes/class.ilContentStylesTableGUI.php"); - $table = new ilContentStylesTableGUI($this, "edit", $data, $this->cs_settings); - $this->tpl->setContent($table->getHTML()); - - } - - /** - * move learning modules from one style to another - */ - function moveLMStyles() - { - $this->checkPermission("sty_write_content"); - - if ($_POST["from_style"] == -1) - { - $this->confirmDeleteIndividualStyles(); - return; - } - - include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); - ilObjContentObject::_moveLMStyles($_POST["from_style"], $_POST["to_style"]); - $this->ctrl->redirect($this, "edit"); - } - - - /** - * move all learning modules with individual styles to new style - */ - function moveIndividualStyles() - { - $this->checkPermission("sty_write_content"); - - include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); - ilObjContentObject::_moveLMStyles(-1, $_GET["to_style"]); - $this->ctrl->redirect($this, "edit"); - } - - /** - * - */ - function confirmDeleteIndividualStyles() - { - $this->checkPermission("sty_write_content"); - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - - $this->ctrl->setParameter($this, "to_style", $_POST["to_style"]); - - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($this->ctrl->getFormAction($this)); - $cgui->setHeaderText($this->lng->txt("sty_confirm_del_ind_styles").": ". - sprintf($this->lng->txt("sty_confirm_del_ind_styles_desc"), - ilObject::_lookupTitle($_POST["to_style"]))); - $cgui->setCancel($this->lng->txt("cancel"), "edit"); - $cgui->setConfirm($this->lng->txt("ok"), "moveIndividualStyles"); - $this->tpl->setContent($cgui->getHTML()); - } - - - - /** - * display deletion confirmation screen - */ - function deleteStyle() - { - $this->checkPermission("sty_write_content"); - - if (!isset($_POST["id"])) - { - ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); - $this->ctrl->redirect($this, "edit"); - } - - // display confirmation message - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($this->ctrl->getFormAction($this)); - $cgui->setHeaderText($this->lng->txt("info_delete_sure")); - $cgui->setCancel($this->lng->txt("cancel"), "cancelDelete"); - $cgui->setConfirm($this->lng->txt("confirm"), "confirmedDelete"); - - foreach ($_POST["id"] as $id) - { - $caption = ilUtil::getImageTagByType("sty", $this->tpl->tplPath). - " ".ilObject::_lookupTitle($id); - - $cgui->addItem("id[]", $id, $caption); - } - - $this->tpl->setContent($cgui->getHTML()); - } - - - /** - * delete selected style objects - */ - function confirmedDelete() - { - $this->checkPermission("sty_write_content"); - - foreach($_POST["id"] as $id) - { - include_once("./Services/Style/Content/classes/class.ilContentStyleSettings.php"); - $set = new ilContentStyleSettings(); - $set->removeStyle($id); - $set->update(); - - $style_obj = ilObjectFactory::getInstanceByObjId($id); - $style_obj->delete(); - } - - $this->ctrl->redirect($this, "edit"); - } - - - /** - * Toggle global default style - */ - function toggleGlobalDefault() - { - $ilSetting = $this->settings; - $lng = $this->lng; - - $this->checkPermission("sty_write_content"); - - if ($_GET["id"] > 0) - { - $ilSetting->delete("fixed_content_style_id"); - $def_style = $ilSetting->get("default_content_style_id"); - - if ($def_style != $_GET["id"]) - { - $ilSetting->set("default_content_style_id", (int) $_GET["id"]); - } - else - { - $ilSetting->delete("default_content_style_id"); - } - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - } - ilUtil::redirect($this->ctrl->getLinkTarget($this, "edit", "", false, false)); - } - - /** - * Toggle global fixed style - */ - function toggleGlobalFixed() - { - $ilSetting = $this->settings; - $lng = $this->lng; - - $this->checkPermission("sty_write_content"); - - if ($_GET["id"] > 0) - { - $ilSetting->delete("default_content_style_id"); - $fixed_style = $ilSetting->get("fixed_content_style_id"); - if ($fixed_style == (int) $_GET["id"]) - { - $ilSetting->delete("fixed_content_style_id"); - } - else - { - $ilSetting->set("fixed_content_style_id", (int) $_GET["id"]); - } - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - } - ilUtil::redirect($this->ctrl->getLinkTarget($this, "edit", "", false, false)); - } - - - /** - * Save active styles - */ - function saveActiveStyles() - { - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $styles = $this->cs_settings->getStyles(); - foreach($styles as $style) - { - if ($_POST["std_".$style["id"]] == 1) - { - ilObjStyleSheet::_writeActive((int) $style["id"], 1); - } - else - { - ilObjStyleSheet::_writeActive((int) $style["id"], 0); - } - } - ilUtil::redirect($this->ctrl->getLinkTarget($this, "edit", "", false, false)); - } - - /** - * show possible action (form buttons) - * - * @param boolean - * @access public - */ - function showActions($with_subobjects = false) - { - - // delete - $this->tpl->setCurrentBlock("tbl_action_btn"); - $this->tpl->setVariable("BTN_NAME", "deleteStyle"); - $this->tpl->setVariable("BTN_VALUE", $this->lng->txt("delete")); - $this->tpl->parseCurrentBlock(); - - // set global default - $this->tpl->setCurrentBlock("tbl_action_btn"); - $this->tpl->setVariable("BTN_NAME", "toggleGlobalDefault"); - $this->tpl->setVariable("BTN_VALUE", $this->lng->txt("toggleGlobalDefault")); - $this->tpl->parseCurrentBlock(); - - // set global default - $this->tpl->setCurrentBlock("tbl_action_btn"); - $this->tpl->setVariable("BTN_NAME", "toggleGlobalFixed"); - $this->tpl->setVariable("BTN_VALUE", $this->lng->txt("toggleGlobalFixed")); - $this->tpl->parseCurrentBlock(); - - // set global default - $this->tpl->setCurrentBlock("tbl_action_btn"); - $this->tpl->setVariable("BTN_NAME", "setScope"); - $this->tpl->setVariable("BTN_VALUE", $this->lng->txt("sty_set_scope")); - $this->tpl->parseCurrentBlock(); - - // save active styles - $this->tpl->setCurrentBlock("tbl_action_btn"); - $this->tpl->setVariable("BTN_NAME", "saveActiveStyles"); - $this->tpl->setVariable("BTN_VALUE", $this->lng->txt("sty_save_active_styles")); - $this->tpl->parseCurrentBlock(); - - if ($with_subobjects === true) - { - $this->showPossibleSubObjects(); - } - - $this->tpl->setCurrentBlock("tbl_action_row"); - $this->tpl->setVariable("IMG_ARROW", ilUtil::getImagePath("arrow_downright.svg")); - $this->tpl->parseCurrentBlock(); - } - - /** - * cancel deletion of object - * - * @access public - */ - function cancelDelete() - { - ilUtil::sendInfo($this->lng->txt("msg_cancel"),true); - $this->ctrl->redirect($this, "edit"); - - } - - /** - * Set scope - */ - function setScope() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - - $this->checkPermission("sty_write_content"); - - $ilCtrl->saveParameter($this, "id"); - include_once("./Services/Repository/classes/class.ilRepositorySelectorExplorerGUI.php"); - $exp = new ilRepositorySelectorExplorerGUI($this, "setScope", - $this, "saveScope", "cat"); - $exp->setTypeWhiteList(array("root", "cat")); - if (!$exp->handleCommand()) - { - $tpl->setContent($exp->getHTML()); - } - } - - /** - * Save scope for style - */ - function saveScope() - { - $tree = $this->tree; - - $this->checkPermission("sty_write_content"); - - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - if ($_GET["cat"] == $tree->readRootId()) - { - $_GET["cat"] = ""; - } - ilObjStyleSheet::_writeScope($_GET["id"], $_GET["cat"]); - - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - - ilUtil::redirect($this->ctrl->getLinkTarget($this, "edit", "", false, false)); - } - - + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var ilTree + */ + protected $tree; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ILIAS\DI\Container + */ + protected $DIC; + + /** + * @var int + */ + protected $ref_id; + + /** + * Constructor + */ + public function __construct(ilObjStyleSettingsGUI $a_parent_gui) + { + global $DIC; + + $this->tree = $DIC->repositoryTree(); + $this->settings = $DIC->settings(); + + $this->parent_gui = $a_parent_gui; + $this->dic = $DIC; + $this->ctrl = $DIC->ctrl(); + $this->rbacsystem = $DIC->rbac()->system(); + $this->toolbar = $DIC->toolbar(); + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + $this->ref_id = (int) $_GET["ref_id"]; + $this->obj_id = (int) $_GET["obj_id"]; // note that reference ID is the id of the style settings node and object ID may be a style sheet object ID + + + include_once("./Services/Style/Content/classes/class.ilContentStyleSettings.php"); + $this->cs_settings = new ilContentStyleSettings(); + } + + /** + * Execute command + */ + public function executeCommand() + { + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd("edit"); + + switch ($next_class) { + case "ilobjstylesheetgui": + $this->ctrl->setReturn($this, "edit"); + include_once("./Services/Style/Content/classes/class.ilObjStyleSheetGUI.php"); + $style_gui = new ilObjStyleSheetGUI("", $this->obj_id, false, false); + $this->ctrl->forwardCommand($style_gui); + break; + + default: + $this->parent_gui->prepareOutput(); + if (in_array($cmd, array("edit", "delete", "toggleGlobalDefault", "toggleGlobalFixed", "setScope", "saveScope", "saveActiveStyles", + "createStyle", "moveLMStyles", "moveIndividualStyles", "deleteStyle", "cancelDelete", "confirmedDelete"))) { + $this->$cmd(); + } else { + die("Unknown command " . $cmd); + } + } + } + + /** + * Check permission + * + * @param string $a_perm permission(s) + * @return bool + * @throws ilObjectException + */ + public function checkPermission($a_perm, $a_throw_exc = true) + { + if (!$this->rbacsystem->checkAccess($a_perm, $this->ref_id)) { + if ($a_throw_exc) { + include_once "Services/Object/exceptions/class.ilObjectException.php"; + throw new ilObjectException($this->lng->txt("permission_denied")); + } + return false; + } + return true; + } + + /** + * Create new style + */ + public function createStyle() + { + $ilCtrl = $this->ctrl; + + // $ilCtrl->setParameterByClass("ilobjstylesheetgui", "new_type", "sty"); + $ilCtrl->redirectByClass("ilobjstylesheetgui", "create"); + } + + /** + * Show styles + */ + public function edit() + { + $this->checkPermission("visible,read"); + + // this may not be cool, if styles are organised as (independent) Service + include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + + $from_styles = $to_styles = $data = array(); + $styles = $this->cs_settings->getStyles(); + foreach ($styles as $style) { + $style["active"] = ilObjStyleSheet::_lookupActive($style["id"]); + $style["lm_nr"] = ilObjContentObject::_getNrOfAssignedLMs($style["id"]); + $data[$style["title"] . ":" . $style["id"]] + = $style; + if ($style["lm_nr"] > 0) { + $from_styles[$style["id"]] = $style["title"]; + } + if ($style["active"] > 0) { + $to_styles[$style["id"]] = $style["title"]; + } + } + + // number of individual styles + if ($fixed_style <= 0) { + $data[-1] = + array("title" => $this->lng->txt("sty_individual_styles"), + "id" => 0, "lm_nr" => ilObjContentObject::_getNrLMsIndividualStyles()); + $from_styles[-1] = $this->lng->txt("sty_individual_styles"); + } + + // number of default style (fallback default style) + if ($default_style <= 0 && $fixed_style <= 0) { + $data[0] = + array("title" => $this->lng->txt("sty_default_style"), + "id" => 0, "lm_nr" => ilObjContentObject::_getNrLMsNoStyle()); + $from_styles[0] = $this->lng->txt("sty_default_style"); + $to_styles[0] = $this->lng->txt("sty_default_style"); + } + + if ($this->checkPermission("sty_write_content", false)) { + $this->toolbar->addButton( + $this->lng->txt("sty_add_content_style"), + $this->ctrl->getLinkTarget($this, "createStyle") + ); + $this->toolbar->addSeparator(); + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + + // from styles selector + $si = new ilSelectInputGUI($this->lng->txt("sty_move_lm_styles") . ": " . $this->lng->txt("sty_from"), "from_style"); + $si->setOptions($from_styles); + $this->toolbar->addInputItem($si, true); + + // from styles selector + $si = new ilSelectInputGUI($this->lng->txt("sty_to"), "to_style"); + $si->setOptions($to_styles); + $this->toolbar->addInputItem($si, true); + $this->toolbar->addFormButton($this->lng->txt("sty_move_style"), "moveLMStyles"); + + $this->toolbar->setFormAction($this->ctrl->getFormAction($this)); + } + + include_once("./Services/Style/Content/classes/class.ilContentStylesTableGUI.php"); + $table = new ilContentStylesTableGUI($this, "edit", $data, $this->cs_settings); + $this->tpl->setContent($table->getHTML()); + } + + /** + * move learning modules from one style to another + */ + public function moveLMStyles() + { + $this->checkPermission("sty_write_content"); + + if ($_POST["from_style"] == -1) { + $this->confirmDeleteIndividualStyles(); + return; + } + + include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); + ilObjContentObject::_moveLMStyles($_POST["from_style"], $_POST["to_style"]); + $this->ctrl->redirect($this, "edit"); + } + + + /** + * move all learning modules with individual styles to new style + */ + public function moveIndividualStyles() + { + $this->checkPermission("sty_write_content"); + + include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); + ilObjContentObject::_moveLMStyles(-1, $_GET["to_style"]); + $this->ctrl->redirect($this, "edit"); + } + + /** + * + */ + public function confirmDeleteIndividualStyles() + { + $this->checkPermission("sty_write_content"); + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + + $this->ctrl->setParameter($this, "to_style", $_POST["to_style"]); + + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($this->ctrl->getFormAction($this)); + $cgui->setHeaderText($this->lng->txt("sty_confirm_del_ind_styles") . ": " . + sprintf( + $this->lng->txt("sty_confirm_del_ind_styles_desc"), + ilObject::_lookupTitle($_POST["to_style"]) + )); + $cgui->setCancel($this->lng->txt("cancel"), "edit"); + $cgui->setConfirm($this->lng->txt("ok"), "moveIndividualStyles"); + $this->tpl->setContent($cgui->getHTML()); + } + + + + /** + * display deletion confirmation screen + */ + public function deleteStyle() + { + $this->checkPermission("sty_write_content"); + + if (!isset($_POST["id"])) { + ilUtil::sendFailure($this->lng->txt("no_checkbox"), true); + $this->ctrl->redirect($this, "edit"); + } + + // display confirmation message + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($this->ctrl->getFormAction($this)); + $cgui->setHeaderText($this->lng->txt("info_delete_sure")); + $cgui->setCancel($this->lng->txt("cancel"), "cancelDelete"); + $cgui->setConfirm($this->lng->txt("confirm"), "confirmedDelete"); + + foreach ($_POST["id"] as $id) { + $caption = ilUtil::getImageTagByType("sty", $this->tpl->tplPath) . + " " . ilObject::_lookupTitle($id); + + $cgui->addItem("id[]", $id, $caption); + } + + $this->tpl->setContent($cgui->getHTML()); + } + + + /** + * delete selected style objects + */ + public function confirmedDelete() + { + $this->checkPermission("sty_write_content"); + + foreach ($_POST["id"] as $id) { + include_once("./Services/Style/Content/classes/class.ilContentStyleSettings.php"); + $set = new ilContentStyleSettings(); + $set->removeStyle($id); + $set->update(); + + $style_obj = ilObjectFactory::getInstanceByObjId($id); + $style_obj->delete(); + } + + $this->ctrl->redirect($this, "edit"); + } + + + /** + * Toggle global default style + */ + public function toggleGlobalDefault() + { + $ilSetting = $this->settings; + $lng = $this->lng; + + $this->checkPermission("sty_write_content"); + + if ($_GET["id"] > 0) { + $ilSetting->delete("fixed_content_style_id"); + $def_style = $ilSetting->get("default_content_style_id"); + + if ($def_style != $_GET["id"]) { + $ilSetting->set("default_content_style_id", (int) $_GET["id"]); + } else { + $ilSetting->delete("default_content_style_id"); + } + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + } + ilUtil::redirect($this->ctrl->getLinkTarget($this, "edit", "", false, false)); + } + + /** + * Toggle global fixed style + */ + public function toggleGlobalFixed() + { + $ilSetting = $this->settings; + $lng = $this->lng; + + $this->checkPermission("sty_write_content"); + + if ($_GET["id"] > 0) { + $ilSetting->delete("default_content_style_id"); + $fixed_style = $ilSetting->get("fixed_content_style_id"); + if ($fixed_style == (int) $_GET["id"]) { + $ilSetting->delete("fixed_content_style_id"); + } else { + $ilSetting->set("fixed_content_style_id", (int) $_GET["id"]); + } + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + } + ilUtil::redirect($this->ctrl->getLinkTarget($this, "edit", "", false, false)); + } + + + /** + * Save active styles + */ + public function saveActiveStyles() + { + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $styles = $this->cs_settings->getStyles(); + foreach ($styles as $style) { + if ($_POST["std_" . $style["id"]] == 1) { + ilObjStyleSheet::_writeActive((int) $style["id"], 1); + } else { + ilObjStyleSheet::_writeActive((int) $style["id"], 0); + } + } + ilUtil::redirect($this->ctrl->getLinkTarget($this, "edit", "", false, false)); + } + + /** + * show possible action (form buttons) + * + * @param boolean + * @access public + */ + public function showActions($with_subobjects = false) + { + + // delete + $this->tpl->setCurrentBlock("tbl_action_btn"); + $this->tpl->setVariable("BTN_NAME", "deleteStyle"); + $this->tpl->setVariable("BTN_VALUE", $this->lng->txt("delete")); + $this->tpl->parseCurrentBlock(); + + // set global default + $this->tpl->setCurrentBlock("tbl_action_btn"); + $this->tpl->setVariable("BTN_NAME", "toggleGlobalDefault"); + $this->tpl->setVariable("BTN_VALUE", $this->lng->txt("toggleGlobalDefault")); + $this->tpl->parseCurrentBlock(); + + // set global default + $this->tpl->setCurrentBlock("tbl_action_btn"); + $this->tpl->setVariable("BTN_NAME", "toggleGlobalFixed"); + $this->tpl->setVariable("BTN_VALUE", $this->lng->txt("toggleGlobalFixed")); + $this->tpl->parseCurrentBlock(); + + // set global default + $this->tpl->setCurrentBlock("tbl_action_btn"); + $this->tpl->setVariable("BTN_NAME", "setScope"); + $this->tpl->setVariable("BTN_VALUE", $this->lng->txt("sty_set_scope")); + $this->tpl->parseCurrentBlock(); + + // save active styles + $this->tpl->setCurrentBlock("tbl_action_btn"); + $this->tpl->setVariable("BTN_NAME", "saveActiveStyles"); + $this->tpl->setVariable("BTN_VALUE", $this->lng->txt("sty_save_active_styles")); + $this->tpl->parseCurrentBlock(); + + if ($with_subobjects === true) { + $this->showPossibleSubObjects(); + } + + $this->tpl->setCurrentBlock("tbl_action_row"); + $this->tpl->setVariable("IMG_ARROW", ilUtil::getImagePath("arrow_downright.svg")); + $this->tpl->parseCurrentBlock(); + } + + /** + * cancel deletion of object + * + * @access public + */ + public function cancelDelete() + { + ilUtil::sendInfo($this->lng->txt("msg_cancel"), true); + $this->ctrl->redirect($this, "edit"); + } + + /** + * Set scope + */ + public function setScope() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + + $this->checkPermission("sty_write_content"); + + $ilCtrl->saveParameter($this, "id"); + include_once("./Services/Repository/classes/class.ilRepositorySelectorExplorerGUI.php"); + $exp = new ilRepositorySelectorExplorerGUI( + $this, + "setScope", + $this, + "saveScope", + "cat" + ); + $exp->setTypeWhiteList(array("root", "cat")); + if (!$exp->handleCommand()) { + $tpl->setContent($exp->getHTML()); + } + } + + /** + * Save scope for style + */ + public function saveScope() + { + $tree = $this->tree; + + $this->checkPermission("sty_write_content"); + + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + if ($_GET["cat"] == $tree->readRootId()) { + $_GET["cat"] = ""; + } + ilObjStyleSheet::_writeScope($_GET["id"], $_GET["cat"]); + + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + + ilUtil::redirect($this->ctrl->getLinkTarget($this, "edit", "", false, false)); + } } - -?> \ No newline at end of file diff --git a/Services/Style/Content/classes/class.ilContentStylesTableGUI.php b/Services/Style/Content/classes/class.ilContentStylesTableGUI.php index 0fee529a66db58b9aafa5aec49ea231ada309078..3c7e4a4b027ef160a71c87d98eb342d11c994ca0 100644 --- a/Services/Style/Content/classes/class.ilContentStylesTableGUI.php +++ b/Services/Style/Content/classes/class.ilContentStylesTableGUI.php @@ -14,155 +14,154 @@ include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvan */ class ilContentStylesTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilSetting - */ - protected $settings; - - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * Constructor - */ - function __construct(ilContentStyleSettingsGUI $a_parent_obj, $a_parent_cmd, $a_data, $a_style_settings) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->settings = $DIC->settings(); - $this->rbacsystem = $DIC->rbac()->system(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilSetting = $DIC->settings(); - - $this->fixed_style = $ilSetting->get("fixed_content_style_id"); - $this->default_style = $ilSetting->get("default_content_style_id"); - - $this->setId("sty_cs"); - $this->sty_settings = $a_style_settings; - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->setData($a_data); - $this->setTitle($lng->txt("content_styles")); - - $this->addColumn("", "", "1", true); - $this->addColumn($this->lng->txt("title")); - $this->addColumn($this->lng->txt("sty_nr_learning_modules")); - $this->addColumn($this->lng->txt("purpose")); - $this->addColumn($this->lng->txt("sty_scope")); - $this->addColumn($this->lng->txt("active")); - $this->addColumn($this->lng->txt("actions")); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.content_style_row.html", "Services/Style/Content"); - if ($this->parent_obj->checkPermission("sty_write_content", false)) - { - $this->addMultiCommand("deleteStyle", $lng->txt("delete")); - $this->addCommandButton("saveActiveStyles", $lng->txt("sty_save_active_styles")); - } - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $rbacsystem = $this->rbacsystem; - - if ($a_set["id"] > 0) - { - $this->tpl->setCurrentBlock("cb"); - $this->tpl->setVariable("ID", $a_set["id"]); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setCurrentBlock("cb_act"); - if ($a_set["active"]) - { - $this->tpl->setVariable("ACT_CHECKED", "checked='checked'"); - } - $this->tpl->setVariable("ID", $a_set["id"]); - $this->tpl->parseCurrentBlock(); - - $this->tpl->setCurrentBlock("edit_link"); - $ilCtrl->setParameterByClass("ilobjstylesheetgui", "obj_id", $a_set["id"]); - $this->tpl->setVariable("EDIT_LINK", $ilCtrl->getLinkTargetByClass("ilobjstylesheetgui", "")); - $ilCtrl->setParameterByClass("ilobjstylesheetgui", "obj_id", ""); - $this->tpl->setVariable("EDIT_TITLE", $a_set["title"]); - $this->tpl->parseCurrentBlock(); - } - else - { - $this->tpl->setVariable("TITLE", $a_set["title"]); - } - - $ilCtrl->setParameter($this->parent_obj, "id", $a_set["id"]); - if ($a_set["id"] > 0 && $this->parent_obj->checkPermission("sty_write_content", false)) - { - $list = new ilAdvancedSelectionListGUI(); - $list->setListTitle($lng->txt("actions")); - $list->setId("sty_act_".$a_set["id"]); - - // default style - if ($this->default_style == $a_set["id"]) - { - $list->addItem($lng->txt("sty_remove_global_default_state"), "", - $ilCtrl->getLinkTarget($this->parent_obj, "toggleGlobalDefault")); - } - else if ($a_set["active"]) - { - $list->addItem($lng->txt("sty_make_global_default"), "", - $ilCtrl->getLinkTarget($this->parent_obj, "toggleGlobalDefault")); - } - - // fixed style - if ($this->fixed_style == $a_set["id"]) - { - $list->addItem($lng->txt("sty_remove_global_fixed_state"), "", - $ilCtrl->getLinkTarget($this->parent_obj, "toggleGlobalFixed")); - } - else if ($a_set["active"]) - { - $list->addItem($lng->txt("sty_make_global_fixed"), "", - $ilCtrl->getLinkTarget($this->parent_obj, "toggleGlobalFixed")); - } - $list->addItem($lng->txt("sty_set_scope"), "", - $ilCtrl->getLinkTarget($this->parent_obj, "setScope")); - - $this->tpl->setVariable("ACTIONS", $list->getHTML()); - - if ($a_set["id"] == $this->fixed_style) - { - $this->tpl->setVariable("PURPOSE", $lng->txt("global_fixed")); - } - if ($a_set["id"] == $this->default_style) - { - $this->tpl->setVariable("PURPOSE", $lng->txt("global_default")); - } - - } - $ilCtrl->setParameter($this->parent_obj, "id", ""); - - $this->tpl->setVariable("NR_LM", $a_set["lm_nr"]); - - if ($a_set["category"] > 0) - { - $this->tpl->setVariable("SCOPE", - ilObject::_lookupTitle( - ilObject::_lookupObjId($a_set["category"]) - )); - } - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilSetting + */ + protected $settings; + + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * Constructor + */ + public function __construct(ilContentStyleSettingsGUI $a_parent_obj, $a_parent_cmd, $a_data, $a_style_settings) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->settings = $DIC->settings(); + $this->rbacsystem = $DIC->rbac()->system(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilSetting = $DIC->settings(); + + $this->fixed_style = $ilSetting->get("fixed_content_style_id"); + $this->default_style = $ilSetting->get("default_content_style_id"); + + $this->setId("sty_cs"); + $this->sty_settings = $a_style_settings; + + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setData($a_data); + $this->setTitle($lng->txt("content_styles")); + + $this->addColumn("", "", "1", true); + $this->addColumn($this->lng->txt("title")); + $this->addColumn($this->lng->txt("sty_nr_learning_modules")); + $this->addColumn($this->lng->txt("purpose")); + $this->addColumn($this->lng->txt("sty_scope")); + $this->addColumn($this->lng->txt("active")); + $this->addColumn($this->lng->txt("actions")); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.content_style_row.html", "Services/Style/Content"); + if ($this->parent_obj->checkPermission("sty_write_content", false)) { + $this->addMultiCommand("deleteStyle", $lng->txt("delete")); + $this->addCommandButton("saveActiveStyles", $lng->txt("sty_save_active_styles")); + } + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $rbacsystem = $this->rbacsystem; + + if ($a_set["id"] > 0) { + $this->tpl->setCurrentBlock("cb"); + $this->tpl->setVariable("ID", $a_set["id"]); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setCurrentBlock("cb_act"); + if ($a_set["active"]) { + $this->tpl->setVariable("ACT_CHECKED", "checked='checked'"); + } + $this->tpl->setVariable("ID", $a_set["id"]); + $this->tpl->parseCurrentBlock(); + + $this->tpl->setCurrentBlock("edit_link"); + $ilCtrl->setParameterByClass("ilobjstylesheetgui", "obj_id", $a_set["id"]); + $this->tpl->setVariable("EDIT_LINK", $ilCtrl->getLinkTargetByClass("ilobjstylesheetgui", "")); + $ilCtrl->setParameterByClass("ilobjstylesheetgui", "obj_id", ""); + $this->tpl->setVariable("EDIT_TITLE", $a_set["title"]); + $this->tpl->parseCurrentBlock(); + } else { + $this->tpl->setVariable("TITLE", $a_set["title"]); + } + + $ilCtrl->setParameter($this->parent_obj, "id", $a_set["id"]); + if ($a_set["id"] > 0 && $this->parent_obj->checkPermission("sty_write_content", false)) { + $list = new ilAdvancedSelectionListGUI(); + $list->setListTitle($lng->txt("actions")); + $list->setId("sty_act_" . $a_set["id"]); + + // default style + if ($this->default_style == $a_set["id"]) { + $list->addItem( + $lng->txt("sty_remove_global_default_state"), + "", + $ilCtrl->getLinkTarget($this->parent_obj, "toggleGlobalDefault") + ); + } elseif ($a_set["active"]) { + $list->addItem( + $lng->txt("sty_make_global_default"), + "", + $ilCtrl->getLinkTarget($this->parent_obj, "toggleGlobalDefault") + ); + } + + // fixed style + if ($this->fixed_style == $a_set["id"]) { + $list->addItem( + $lng->txt("sty_remove_global_fixed_state"), + "", + $ilCtrl->getLinkTarget($this->parent_obj, "toggleGlobalFixed") + ); + } elseif ($a_set["active"]) { + $list->addItem( + $lng->txt("sty_make_global_fixed"), + "", + $ilCtrl->getLinkTarget($this->parent_obj, "toggleGlobalFixed") + ); + } + $list->addItem( + $lng->txt("sty_set_scope"), + "", + $ilCtrl->getLinkTarget($this->parent_obj, "setScope") + ); + + $this->tpl->setVariable("ACTIONS", $list->getHTML()); + + if ($a_set["id"] == $this->fixed_style) { + $this->tpl->setVariable("PURPOSE", $lng->txt("global_fixed")); + } + if ($a_set["id"] == $this->default_style) { + $this->tpl->setVariable("PURPOSE", $lng->txt("global_default")); + } + } + $ilCtrl->setParameter($this->parent_obj, "id", ""); + + $this->tpl->setVariable("NR_LM", $a_set["lm_nr"]); + + if ($a_set["category"] > 0) { + $this->tpl->setVariable( + "SCOPE", + ilObject::_lookupTitle( + ilObject::_lookupObjId($a_set["category"]) + ) + ); + } + } } -?> diff --git a/Services/Style/Content/classes/class.ilFontSizeInputGUI.php b/Services/Style/Content/classes/class.ilFontSizeInputGUI.php index d9c8df3eafee0bd9ab9e4cfc834fd3d9fac06e93..de890297379e79dfa5bb5d22fa37875b4449e728 100755 --- a/Services/Style/Content/classes/class.ilFontSizeInputGUI.php +++ b/Services/Style/Content/classes/class.ilFontSizeInputGUI.php @@ -1,211 +1,193 @@ +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilFontSizeInputGUI extends ilFormPropertyGUI { - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - protected $value; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + protected $value; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - parent::__construct($a_title, $a_postvar); - $this->setType("fontsize"); - } + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + parent::__construct($a_title, $a_postvar); + $this->setType("fontsize"); + } - /** - * Set Value. - * - * @param string $a_value Value - */ - function setValue($a_value) - { - $this->value = $a_value; - } + /** + * Set Value. + * + * @param string $a_value Value + */ + public function setValue($a_value) + { + $this->value = $a_value; + } - /** - * Get Value. - * - * @return string Value - */ - function getValue() - { - return $this->value; - } - - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - $type = $_POST[$this->getPostVar()]["type"] = - ilUtil::stripSlashes($_POST[$this->getPostVar()]["type"]); - $num_value = $_POST[$this->getPostVar()]["num_value"] = - ilUtil::stripSlashes($_POST[$this->getPostVar()]["num_value"]); - $num_unit = $_POST[$this->getPostVar()]["num_unit"] = - ilUtil::stripSlashes($_POST[$this->getPostVar()]["num_unit"]); - $pre_value = $_POST[$this->getPostVar()]["pre_value"] = - ilUtil::stripSlashes($_POST[$this->getPostVar()]["pre_value"]); - - if ($this->getRequired() && $type == "numeric" && trim($num_value) == "") - { - $this->setAlert($lng->txt("msg_input_is_required")); + /** + * Get Value. + * + * @return string Value + */ + public function getValue() + { + return $this->value; + } + + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + $type = $_POST[$this->getPostVar()]["type"] = + ilUtil::stripSlashes($_POST[$this->getPostVar()]["type"]); + $num_value = $_POST[$this->getPostVar()]["num_value"] = + ilUtil::stripSlashes($_POST[$this->getPostVar()]["num_value"]); + $num_unit = $_POST[$this->getPostVar()]["num_unit"] = + ilUtil::stripSlashes($_POST[$this->getPostVar()]["num_unit"]); + $pre_value = $_POST[$this->getPostVar()]["pre_value"] = + ilUtil::stripSlashes($_POST[$this->getPostVar()]["pre_value"]); + + if ($this->getRequired() && $type == "numeric" && trim($num_value) == "") { + $this->setAlert($lng->txt("msg_input_is_required")); - return false; - } - - if ($type == "numeric") - { - if (!is_numeric($num_value) && $num_value != "") - { - $this->setAlert($lng->txt("sty_msg_input_must_be_numeric")); - - return false; - } - - if (trim($num_value) != "") - { - $this->setValue($num_value.$num_unit); - } - } - else - { - $this->setValue($pre_value); - } - - return true; - } + return false; + } + + if ($type == "numeric") { + if (!is_numeric($num_value) && $num_value != "") { + $this->setAlert($lng->txt("sty_msg_input_must_be_numeric")); + + return false; + } + + if (trim($num_value) != "") { + $this->setValue($num_value . $num_unit); + } + } else { + $this->setValue($pre_value); + } + + return true; + } - /** - * Insert property html - */ - function insert(&$a_tpl) - { - $tpl = new ilTemplate("tpl.prop_fontsize.html", true, true, "Services/Style/Content"); - - $tpl->setVariable("POSTVAR", $this->getPostVar()); - - $unit_options = ilObjStyleSheet::_getStyleParameterNumericUnits(); - $pre_options = ilObjStyleSheet::_getStyleParameterValues("font-size"); - - $value = strtolower(trim($this->getValue())); + /** + * Insert property html + */ + public function insert(&$a_tpl) + { + $tpl = new ilTemplate("tpl.prop_fontsize.html", true, true, "Services/Style/Content"); + + $tpl->setVariable("POSTVAR", $this->getPostVar()); + + $unit_options = ilObjStyleSheet::_getStyleParameterNumericUnits(); + $pre_options = ilObjStyleSheet::_getStyleParameterValues("font-size"); + + $value = strtolower(trim($this->getValue())); - if (in_array($value, $pre_options)) - { - $current_type = "pre"; - $tpl->setVariable("PREDEFINED_SELECTED", 'checked="checked"'); - } - else - { - $current_type = "unit"; - $tpl->setVariable("NUMERIC_SELECTED", 'checked="checked"'); - $current_unit = ""; - foreach ($unit_options as $u) - { - if (substr($value, strlen($value) - strlen($u)) == $u) - { - $current_unit = $u; - } - } - $tpl->setVariable("VAL_NUM", - substr($value, 0, strlen($value) - strlen($current_unit))); - if ($current_unit == "") - { - $current_unit = "px"; - } - } - - foreach ($unit_options as $option) - { - $tpl->setCurrentBlock("unit_option"); - $tpl->setVariable("VAL_UNIT", $option); - $tpl->setVariable("TXT_UNIT", $option); - if ($current_type == "unit" && $current_unit == $option) - { - $tpl->setVariable("UNIT_SELECTED", 'selected="selected"'); - } - $tpl->parseCurrentBlock(); - } - - foreach ($pre_options as $option) - { - $tpl->setCurrentBlock("pre_option"); - $tpl->setVariable("VAL_PRE", $option); - $tpl->setVariable("TXT_PRE", $option); - if ($current_type == "pre" && $value == $option) - { - $tpl->setVariable("PRE_SELECTED", 'selected="selected"'); - } - $tpl->parseCurrentBlock(); - } + if (in_array($value, $pre_options)) { + $current_type = "pre"; + $tpl->setVariable("PREDEFINED_SELECTED", 'checked="checked"'); + } else { + $current_type = "unit"; + $tpl->setVariable("NUMERIC_SELECTED", 'checked="checked"'); + $current_unit = ""; + foreach ($unit_options as $u) { + if (substr($value, strlen($value) - strlen($u)) == $u) { + $current_unit = $u; + } + } + $tpl->setVariable( + "VAL_NUM", + substr($value, 0, strlen($value) - strlen($current_unit)) + ); + if ($current_unit == "") { + $current_unit = "px"; + } + } + + foreach ($unit_options as $option) { + $tpl->setCurrentBlock("unit_option"); + $tpl->setVariable("VAL_UNIT", $option); + $tpl->setVariable("TXT_UNIT", $option); + if ($current_type == "unit" && $current_unit == $option) { + $tpl->setVariable("UNIT_SELECTED", 'selected="selected"'); + } + $tpl->parseCurrentBlock(); + } + + foreach ($pre_options as $option) { + $tpl->setCurrentBlock("pre_option"); + $tpl->setVariable("VAL_PRE", $option); + $tpl->setVariable("TXT_PRE", $option); + if ($current_type == "pre" && $value == $option) { + $tpl->setVariable("PRE_SELECTED", 'selected="selected"'); + } + $tpl->parseCurrentBlock(); + } - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $tpl->get()); - $a_tpl->parseCurrentBlock(); - } - - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $ilUser = $this->user; - - if ($a_values[$this->getPostVar()]["type"] == "predefined") - { - $this->setValue($a_values[$this->getPostVar()]["pre_value"]); - } - else - { - $this->setValue($a_values[$this->getPostVar()]["num_value"]. - $a_values[$this->getPostVar()]["num_unit"]); - } - } + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $tpl->get()); + $a_tpl->parseCurrentBlock(); + } + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $ilUser = $this->user; + + if ($a_values[$this->getPostVar()]["type"] == "predefined") { + $this->setValue($a_values[$this->getPostVar()]["pre_value"]); + } else { + $this->setValue($a_values[$this->getPostVar()]["num_value"] . + $a_values[$this->getPostVar()]["num_unit"]); + } + } } diff --git a/Services/Style/Content/classes/class.ilNumericStyleValueInputGUI.php b/Services/Style/Content/classes/class.ilNumericStyleValueInputGUI.php index 993ec34f0b4948ce60c7c116adb5b3fe97f619e5..85e7349658ff833bdb0de3088b7cb864911b4c98 100755 --- a/Services/Style/Content/classes/class.ilNumericStyleValueInputGUI.php +++ b/Services/Style/Content/classes/class.ilNumericStyleValueInputGUI.php @@ -1,192 +1,184 @@ +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilNumericStyleValueInputGUI extends ilFormPropertyGUI { - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - protected $value; - protected $allowpercentage = true; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + protected $value; + protected $allowpercentage = true; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - parent::__construct($a_title, $a_postvar); - $this->setType("style_numeric"); - - } + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + parent::__construct($a_title, $a_postvar); + $this->setType("style_numeric"); + } - /** - * Set Value. - * - * @param string $a_value Value - */ - function setValue($a_value) - { - $this->value = $a_value; - } + /** + * Set Value. + * + * @param string $a_value Value + */ + public function setValue($a_value) + { + $this->value = $a_value; + } - /** - * Get Value. - * - * @return string Value - */ - function getValue() - { - return $this->value; - } - - /** - * Set Allow Percentage. - * - * @param boolean $a_allowpercentage Allow Percentage - */ - function setAllowPercentage($a_allowpercentage) - { - $this->allowpercentage = $a_allowpercentage; - } + /** + * Get Value. + * + * @return string Value + */ + public function getValue() + { + return $this->value; + } + + /** + * Set Allow Percentage. + * + * @param boolean $a_allowpercentage Allow Percentage + */ + public function setAllowPercentage($a_allowpercentage) + { + $this->allowpercentage = $a_allowpercentage; + } - /** - * Get Allow Percentage. - * - * @return boolean Allow Percentage - */ - function getAllowPercentage() - { - return $this->allowpercentage; - } + /** + * Get Allow Percentage. + * + * @return boolean Allow Percentage + */ + public function getAllowPercentage() + { + return $this->allowpercentage; + } - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - $num_value = $_POST[$this->getPostVar()]["num_value"] = - trim(ilUtil::stripSlashes($_POST[$this->getPostVar()]["num_value"])); - $num_unit = $_POST[$this->getPostVar()]["num_unit"] = - trim(ilUtil::stripSlashes($_POST[$this->getPostVar()]["num_unit"])); - - if ($this->getRequired() && trim($num_value) == "") - { - $this->setAlert($lng->txt("msg_input_is_required")); + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + $num_value = $_POST[$this->getPostVar()]["num_value"] = + trim(ilUtil::stripSlashes($_POST[$this->getPostVar()]["num_value"])); + $num_unit = $_POST[$this->getPostVar()]["num_unit"] = + trim(ilUtil::stripSlashes($_POST[$this->getPostVar()]["num_unit"])); + + if ($this->getRequired() && trim($num_value) == "") { + $this->setAlert($lng->txt("msg_input_is_required")); - return false; - } - - if (!is_numeric($num_value) && $num_value != "") - { - $this->setAlert($lng->txt("sty_msg_input_must_be_numeric")); + return false; + } + + if (!is_numeric($num_value) && $num_value != "") { + $this->setAlert($lng->txt("sty_msg_input_must_be_numeric")); - return false; - } - - if (trim($num_value) != "") - { - $this->setValue($num_value.$num_unit); - } - - return true; - } + return false; + } + + if (trim($num_value) != "") { + $this->setValue($num_value . $num_unit); + } + + return true; + } - /** - * Insert property html - */ - function insert(&$a_tpl) - { - $tpl = new ilTemplate("tpl.prop_style_numeric.html", true, true, "Services/Style/Content"); - - $tpl->setVariable("POSTVAR", $this->getPostVar()); - - $unit_options = ilObjStyleSheet::_getStyleParameterNumericUnits(!$this->getAllowPercentage()); - - $value = strtolower(trim($this->getValue())); + /** + * Insert property html + */ + public function insert(&$a_tpl) + { + $tpl = new ilTemplate("tpl.prop_style_numeric.html", true, true, "Services/Style/Content"); + + $tpl->setVariable("POSTVAR", $this->getPostVar()); + + $unit_options = ilObjStyleSheet::_getStyleParameterNumericUnits(!$this->getAllowPercentage()); + + $value = strtolower(trim($this->getValue())); - $current_unit = ""; - foreach ($unit_options as $u) - { - if (substr($value, strlen($value) - strlen($u)) == $u) - { - $current_unit = $u; - } - } - $tpl->setVariable("VAL_NUM", - substr($value, 0, strlen($value) - strlen($current_unit))); - if ($current_unit == "") - { - $current_unit = "px"; - } - - foreach ($unit_options as $option) - { - $tpl->setCurrentBlock("unit_option"); - $tpl->setVariable("VAL_UNIT", $option); - $tpl->setVariable("TXT_UNIT", $option); - if ($current_unit == $option) - { - $tpl->setVariable("UNIT_SELECTED", 'selected="selected"'); - } - $tpl->parseCurrentBlock(); - } + $current_unit = ""; + foreach ($unit_options as $u) { + if (substr($value, strlen($value) - strlen($u)) == $u) { + $current_unit = $u; + } + } + $tpl->setVariable( + "VAL_NUM", + substr($value, 0, strlen($value) - strlen($current_unit)) + ); + if ($current_unit == "") { + $current_unit = "px"; + } + + foreach ($unit_options as $option) { + $tpl->setCurrentBlock("unit_option"); + $tpl->setVariable("VAL_UNIT", $option); + $tpl->setVariable("TXT_UNIT", $option); + if ($current_unit == $option) { + $tpl->setVariable("UNIT_SELECTED", 'selected="selected"'); + } + $tpl->parseCurrentBlock(); + } - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $tpl->get()); - $a_tpl->parseCurrentBlock(); - } - - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $ilUser = $this->user; - - $this->setValue($a_values[$this->getPostVar()]["num_value"]. - $a_values[$this->getPostVar()]["num_unit"]); - } + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $tpl->get()); + $a_tpl->parseCurrentBlock(); + } + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $ilUser = $this->user; + + $this->setValue($a_values[$this->getPostVar()]["num_value"] . + $a_values[$this->getPostVar()]["num_unit"]); + } } diff --git a/Services/Style/Content/classes/class.ilObjStyleSheet.php b/Services/Style/Content/classes/class.ilObjStyleSheet.php index 65e8b10f796240f0a3617c45e6929620f3f8a8ab..5221e57d2f1658b68f52b8f49461f94fb7b48e7d 100755 --- a/Services/Style/Content/classes/class.ilObjStyleSheet.php +++ b/Services/Style/Content/classes/class.ilObjStyleSheet.php @@ -14,3872 +14,3685 @@ require_once "./Services/Object/classes/class.ilObject.php"; */ class ilObjStyleSheet extends ilObject { - var $style; - - public static $num_unit = array("px", "em", "ex", "%", "pt", "pc", "in", "mm", "cm"); - public static $num_unit_no_perc = array("px", "em", "ex", "pt", "pc", "in", "mm", "cm"); - - // css parameters and their attribute values, input type and group - public static $parameter = array( - "font-size" => array( - "values" => array("xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large", "smaller", "larger"), - "input" => "fontsize", - "group" => "text"), - "font-family" => array( - "values" => array(), - "input" => "text", - "group" => "text"), - "font-style" => array( - "values" => array("italic", "oblique", "normal"), - "input" => "select", - "group" => "text"), - "font-weight" => array( - "values" => array("bold", "normal", "bolder", "lighter"), - "input" => "select", - "group" => "text"), - "font-variant" => array( - "values" => array("small-caps", "normal"), - "input" => "select", - "group" => "text"), - "word-spacing" => array( - "values" => array(), - "input" => "numeric_no_perc", - "group" => "text"), - "letter-spacing" => array( - "values" => array(), - "input" => "numeric_no_perc", - "group" => "text"), - "text-decoration" => array( - "values" => array("underline", "overline", "line-through", "blink", "none"), - "input" => "select", - "group" => "text"), - "text-transform" => array( - "values" => array("capitalize", "uppercase", "lowercase", "none"), - "input" => "select", - "group" => "text"), - "color" => array( - "values" => array(), - "input" => "color", - "group" => "text"), - "text-indent" => array( - "values" => array(), - "input" => "numeric", - "group" => "text"), - "line-height" => array( - "values" => array(), - "input" => "numeric", - "group" => "text"), - "vertical-align" => array( - "values" => array("top", "middle", "bottom", "baseline", "sub", "super", - "text-top", "text-bottom"), - "input" => "select", - "group" => "text"), - "text-align" => array( - "values" => array("left", "center", "right", "justify"), - "input" => "select", - "group" => "text"), - "white-space" => array( - "values" => array("normal", "pre", "nowrap"), - "input" => "select", - "group" => "text"), - "margin" => array( - "values" => array(), - "input" => "trbl_numeric", - "subpar" => array("margin", "margin-top", "margin-right", - "margin-bottom", "margin-left"), - "group" => "margin_and_padding"), - "padding" => array( - "values" => array(), - "input" => "trbl_numeric", - "subpar" => array("padding", "padding-top", "padding-right", - "padding-bottom", "padding-left"), - "group" => "margin_and_padding"), - "border-width" => array( - "values" => array("thin", "medium", "thick"), - "input" => "border_width", - "subpar" => array("border-width", "border-top-width", "border-right-width", - "border-bottom-width", "border-left-width"), - "group" => "border"), - "border-color" => array( - "values" => array(), - "input" => "trbl_color", - "subpar" => array("border-color", "border-top-color", "border-right-color", - "border-bottom-color", "border-left-color"), - "group" => "border"), - "border-style" => array( - "values" => array("none", "hidden", "dotted", "dashed", "solid", "double", - "groove", "ridge", "inset", "outset"), - "input" => "border_style", - "subpar" => array("border-style", "border-top-style", "border-right-style", - "border-bottom-style", "border-left-style"), - "group" => "border"), - - "background-color" => array( - "values" => array(), - "input" => "color", - "group" => "background"), - "background-image" => array( - "values" => array(), - "input" => "background_image", - "group" => "background"), - "background-repeat" => array( - "values" => array("repeat", "repeat-x", "repeat-y", "no-repeat"), - "input" => "select", - "group" => "background"), - "background-attachment" => array( - "values" => array("fixed", "scroll"), - "input" => "select", - "group" => "background"), - "background-position" => array( - "values" => array("horizontal" => array("left", "center", "right"), - "vertical" => array("top", "center", "bottom")), - "input" => "background_position", - "group" => "background"), - - "position" => array( - "values" => array("absolute", "fixed", "relative", "static"), - "input" => "select", - "group" => "positioning"), - "top" => array( - "values" => array(), - "input" => "numeric", - "group" => "positioning"), - "bottom" => array( - "values" => array(), - "input" => "numeric", - "group" => "positioning"), - "left" => array( - "values" => array(), - "input" => "numeric", - "group" => "positioning"), - "right" => array( - "values" => array(), - "input" => "numeric", - "group" => "positioning"), - "width" => array( - "values" => array(), - "input" => "numeric", - "group" => "positioning"), - "height" => array( - "values" => array(), - "input" => "numeric", - "group" => "positioning"), - "min-height" => array( - "values" => array(), - "input" => "numeric", - "group" => "positioning"), - "float" => array( - "values" => array("left", "right", "none"), - "input" => "select", - "group" => "positioning"), - "overflow" => array( - "values" => array("visible", "hidden", "scroll", "auto"), - "input" => "select", - "group" => "positioning"), - "opacity" => array( - "values" => array(), - "input" => "percentage", - "group" => "special"), - "transform" => array( - "values" => array("rotate(90deg)", "rotate(180deg)", "rotate(270deg)"), - "input" => "select", - "group" => "special"), - "transform-origin" => array( - "values" => array( "horizontal" => array("left", "center", "right"), - "vertical" => array("top", "center", "bottom")), - "input" => "background_position", - "group" => "special"), - "cursor" => array( - "values" => array("auto", "default", "crosshair", "pointer", "move", - "n-resize", "ne-resize", "e-resize", "se-resize", "s-resize", "sw-resize", - "w-resize", "nw-resize", "text", "wait", "help"), - "input" => "select", - "group" => "special"), - "clear" => array( - "values" => array ("both","left","right","none"), - "input" => "select", - "group" => "special"), - - "list-style-type.ol" => array( - "values" => array ("decimal","lower-roman","upper-roman", - "lower-alpha", "upper-alpha", "lower-greek", "hebrew", - "decimal-leading-zero", "cjk-ideographic", "hiragana", - "katakana", "hiragana-iroha", "katakana-iroha", "none"), - "input" => "select", - "group" => "ol"), - "list-style-type.ul" => array( - "values" => array ("disc","circle","square", - "none"), - "input" => "select", - "group" => "ul"), - "list-style-image.ul" => array( - "values" => array(), - "input" => "background_image", - "group" => "ul"), - "list-style-position.ol" => array( - "values" => array ("inside","outside"), - "input" => "select", - "group" => "ol"), - "list-style-position.ul" => array( - "values" => array ("inside","outside"), - "input" => "select", - "group" => "ul" - ), - "border-collapse" => array( - "values" => array ("collapse","separate"), - "input" => "select", - "group" => "table" - ), - "caption-side" => array( - "values" => array ("top","bottom","left","right"), - "input" => "select", - "group" => "table" - ) - ); - - // filter groups of properties that should only be - // displayed with matching tag (group -> tags) - public static $filtered_groups = - array("ol" => array("ol"), "ul" => array("ul"), - "table" => array("table"), "positioning" => array("h1", "h2", "h3", "div", "img", "table", "a", "figure")); - - // style types and their super type - public static $style_super_types = array( - "text_block" => array("text_block", "heading1", "heading2", "heading3", "code_block"), - "text_inline" => array("text_inline", "sub", "sup", "code_inline"), - "section" => array("section"), - "link" => array("link"), - "table" => array("table", "table_cell", "table_caption"), - "list" => array("list_o", "list_u", "list_item"), - "flist" => array("flist_cont", "flist_head", "flist", "flist_li", "flist_a"), - "media" => array("media_cont", "media_caption", "iim", "marker"), - "tabs" => array("va_cntr", "va_icntr", "va_ihead", "va_iheada", "va_ihcap", "va_icont", - "ha_cntr", "ha_icntr", "ha_ihead", "ha_iheada", "ha_ihcap", "ha_icont", "ca_cntr", "ca_icntr", "ca_ihead", "ca_icont"), - "question" => array("question", "qtitle", "qanswer", "qinput", "qlinput", "qsubmit", "qfeedr", "qfeedw", - "qimg", "qordul", "qordli", "qimgd", "qetitem", "qetcorr", "qover"), - "page" => array("page_frame", "page_cont", "page_title", "page_fn", - "page_tnav", "page_bnav", "page_lnav", "page_rnav", "page_lnavlink", "page_rnavlink", - "page_lnavimage", "page_rnavimage"), - "glo" => array("glo_overlay", "glo_ovtitle", "glo_ovclink", "glo_ovuglink", "glo_ovuglistlink"), - "sco" => array("sco_title", "sco_keyw", "sco_desc", "sco_desct", "sco_obj", "sco_objt", "sco_fmess"), - "rte" => array("rte_menu", "rte_mlink", "rte_tree", "rte_node", "rte_tlink","rte_status", - "rte_tul", "rte_tli", "rte_texp", "rte_tclink", "rte_drag") - ); - - // these types are expandable, i.e. the user can define new style classes - public static $expandable_types = array ( - "text_block", "text_inline", "section", "media_cont", "table", "table_cell", "flist_li", "table_caption", - "list_o", "list_u", - "va_cntr", "va_icntr", "va_ihead", "va_iheada", "va_ihcap", "va_icont", - "ha_cntr", "ha_icntr", "ha_ihead", "ha_iheada", "ha_ihcap", "ha_icont", - "ca_cntr", "ca_icntr", "ca_ihead", "ca_icont" - ); - - // these types can be hidden in the content editor - public static $hideable_types = array ( - "table", "table_cell" - ); - - // tag that are used by style types - public static $assigned_tags = array ( - "text_block" => "div", - "heading1" => "h1", - "heading2" => "h2", - "heading3" => "h3", - "code_block" => "pre", - "text_inline" => "span", - "code_inline" => "code", - "sup" => "sup", - "sub" => "sub", - "section" => "div", - "link" => "a", - "table" => "table", - "table_cell" => "td", - "table_caption" => "caption", - "media_cont" => "figure", - "media_caption" => "div", - "iim" => "div", - "marker" => "a", - "glo_overlay" => "div", - "glo_ovtitle" => "h1", - "glo_ovclink" => "a", - "glo_ovuglink" => "a", - "glo_ovuglistlink" => "a", - "sco_title" => "div", - "sco_keyw" => "div", - "sco_desc" => "div", - "sco_obj" => "div", - "sco_desct" => "div", - "sco_objt" => "div", - "sco_fmess" => "div", - "rte_menu" => "div", - "rte_mlink" => "a", - "rte_tree" => "div", - "rte_tclink" => "a", - "rte_drag" => "div", - "rte_node" => "div", - "rte_status" => "div", - "rte_tlink" => "a", - "rte_tul" => "div", - "rte_tli" => "div", - "rte_texp" => "a", - "list_o" => "ol", - "list_u" => "ul", - "list_item" => "li", - "flist_cont" => "div", - "flist_head" => "div", - "flist" => "ul", - "flist_li" => "li", - "flist_a" => "a", - "question" => "div", - "qtitle" => "div", - "qanswer" => "div", - "qimg" => "img", - "qimgd" => "a", - "qordul" => "ul", - "qordli" => "li", - "qetitem" => "a", - "qetcorr" => "span", - "qinput" => "input", - "qlinput" => "textarea", - "qsubmit" => "input", - "qfeedr" => "div", - "qfeedw" => "div", - "qover" => "div", - "page_frame" => "div", - "page_cont" => "div", - "page_fn" => "div", - "page" => "div", - "page_tnav" => "div", - "page_bnav" => "div", - "page_lnav" => "div", - "page_rnav" => "div", - "page_lnavlink" => "a", - "page_rnavlink" => "a", - "page_lnavimage" => "img", - "page_rnavimage" => "img", - "page_title" => "h1", - "va_cntr" => "div", - "va_icntr" => "div", - "va_icont" => "div", - "va_ihead" => "div", - "va_iheada" => "div", - "va_ihcap" => "div", - "ha_cntr" => "div", - "ha_icntr" => "div", - "ha_icont" => "div", - "ha_iheada" => "div", - "ha_ihcap" => "div", - "ha_ihead" => "div", - "ca_cntr" => "div", - "ca_icntr" => "div", - "ca_ihead" => "div", - "ca_icont" => "div" - ); - - // pseudo classes - public static $pseudo_classes = - array ("a" => array("hover"), "div" => array("hover"), "img" => array("hover")); - - // core styles these styles MUST exists -> see also basic_style/style.xml - public static $core_styles = array( - array("type" => "text_block", "class" => "Standard"), - array("type" => "text_block", "class" => "List"), - array("type" => "text_block", "class" => "TableContent"), - array("type" => "code_block", "class" => "Code"), - array("type" => "heading1", "class" => "Headline1"), - array("type" => "heading2", "class" => "Headline2"), - array("type" => "heading3", "class" => "Headline3"), - array("type" => "text_inline", "class" => "Comment"), - array("type" => "text_inline", "class" => "Emph"), - array("type" => "text_inline", "class" => "Quotation"), - array("type" => "text_inline", "class" => "Strong"), - array("type" => "text_inline", "class" => "Accent"), - array("type" => "text_inline", "class" => "Important"), - array("type" => "code_inline", "class" => "CodeInline"), - array("type" => "sup", "class" => "Sup"), - array("type" => "sub", "class" => "Sub"), - array("type" => "link", "class" => "IntLink"), - array("type" => "link", "class" => "ExtLink"), - array("type" => "link", "class" => "FootnoteLink"), - array("type" => "link", "class" => "FileLink"), - array("type" => "link", "class" => "GlossaryLink"), - array("type" => "media_cont", "class" => "MediaContainer"), - array("type" => "media_cont", "class" => "MediaContainerMax50"), - array("type" => "media_cont", "class" => "MediaContainerFull100"), - array("type" => "table", "class" => "StandardTable"), - array("type" => "media_caption", "class" => "MediaCaption"), - array("type" => "iim", "class" => "ContentPopup"), - array("type" => "marker", "class" => "Marker"), - array("type" => "page_frame", "class" => "PageFrame"), - array("type" => "page_cont", "class" => "PageContainer"), - array("type" => "page", "class" => "Page"), - array("type" => "page_tnav", "class" => "TopNavigation"), - array("type" => "page_bnav", "class" => "BottomNavigation"), - array("type" => "page_lnav", "class" => "LeftNavigation"), - array("type" => "page_rnav", "class" => "RightNavigation"), - array("type" => "page_lnavlink", "class" => "LeftNavigationLink"), - array("type" => "page_rnavlink", "class" => "RightNavigationLink"), - array("type" => "page_lnavimage", "class" => "LeftNavigationImage"), - array("type" => "page_rnavimage", "class" => "RightNavigationImage"), - array("type" => "page_fn", "class" => "Footnote"), - array("type" => "page_title", "class" => "PageTitle"), - array("type" => "glo_overlay", "class" => "GlossaryOverlay"), - array("type" => "glo_ovtitle", "class" => "GlossaryOvTitle"), - array("type" => "glo_ovclink", "class" => "GlossaryOvCloseLink"), - array("type" => "glo_ovuglink", "class" => "GlossaryOvUnitGloLink"), - array("type" => "glo_ovuglistlink", "class" => "GlossaryOvUGListLink"), - array("type" => "sco_title", "class" => "Title"), - array("type" => "sco_desc", "class" => "Description"), - array("type" => "sco_desct", "class" => "DescriptionTop"), - array("type" => "sco_keyw", "class" => "Keywords"), - array("type" => "sco_obj", "class" => "Objective"), - array("type" => "sco_objt", "class" => "ObjectiveTop"), - array("type" => "sco_fmess", "class" => "FinalMessage"), - array("type" => "rte_menu", "class" => "RTEMenu"), - array("type" => "rte_menu", "class" => "RTELogo"), - array("type" => "rte_menu", "class" => "RTELinkBar"), - array("type" => "rte_mlink", "class" => "RTELink"), - array("type" => "rte_mlink", "class" => "RTELinkDisabled"), - array("type" => "rte_tree", "class" => "RTETree"), - array("type" => "rte_node", "class" => "RTECourse"), - array("type" => "rte_node", "class" => "RTEChapter"), - array("type" => "rte_node", "class" => "RTESco"), - array("type" => "rte_node", "class" => "RTEAsset"), - array("type" => "rte_node", "class" => "RTECourseDisabled"), - array("type" => "rte_node", "class" => "RTEChapterDisabled"), - array("type" => "rte_node", "class" => "RTEScoDisabled"), - array("type" => "rte_node", "class" => "RTEAssetDisabled"), - array("type" => "rte_status", "class" => "RTEAsset"), - array("type" => "rte_status", "class" => "RTECompleted"), - array("type" => "rte_status", "class" => "RTENotAttempted"), - array("type" => "rte_status", "class" => "RTERunning"), - array("type" => "rte_status", "class" => "RTEIncomplete"), - array("type" => "rte_status", "class" => "RTEPassed"), - array("type" => "rte_status", "class" => "RTEFailed"), - array("type" => "rte_status", "class" => "RTEBrowsed"), - array("type" => "rte_tlink", "class" => "RTETreeLink"), - array("type" => "rte_tlink", "class" => "RTETreeLinkDisabled"), - array("type" => "rte_tlink", "class" => "RTETreeCurrent"), - array("type" => "rte_tul", "class" => "RTETreeList"), - array("type" => "rte_tli", "class" => "RTETreeItem"), - array("type" => "rte_texp", "class" => "RTETreeExpanded"), - array("type" => "rte_texp", "class" => "RTETreeCollapsed"), - array("type" => "rte_tree", "class" => "RTETreeControl"), - array("type" => "rte_tclink", "class" => "RTETreeControlLink"), - array("type" => "rte_drag", "class" => "RTEDragBar"), - array("type" => "list_o", "class" => "NumberedList"), - array("type" => "list_u", "class" => "BulletedList"), - array("type" => "list_item", "class" => "StandardListItem"), - array("type" => "question", "class" => "Standard"), - array("type" => "question", "class" => "SingleChoice"), - array("type" => "question", "class" => "MultipleChoice"), - array("type" => "question", "class" => "TextQuestion"), - array("type" => "question", "class" => "OrderingQuestion"), - array("type" => "question", "class" => "MatchingQuestion"), - array("type" => "question", "class" => "ImagemapQuestion"), - array("type" => "question", "class" => "ErrorText"), - array("type" => "question", "class" => "TextSubset"), - array("type" => "question", "class" => "ClozeTest"), - array("type" => "qtitle", "class" => "Title"), - array("type" => "qanswer", "class" => "Answer"), - array("type" => "qimg", "class" => "QuestionImage"), - array("type" => "qimgd", "class" => "ImageDetailsLink"), - array("type" => "qordul", "class" => "OrderList"), - array("type" => "qordli", "class" => "OrderListItem"), - array("type" => "qordul", "class" => "OrderListHorizontal"), - array("type" => "qordli", "class" => "OrderListItemHorizontal"), - array("type" => "qetitem", "class" => "ErrorTextItem"), - array("type" => "qetitem", "class" => "ErrorTextSelected"), - array("type" => "qetcorr", "class" => "ErrorTextCorrected"), - array("type" => "qinput", "class" => "TextInput"), - array("type" => "qlinput", "class" => "LongTextInput"), - array("type" => "qsubmit", "class" => "Submit"), - array("type" => "qfeedr", "class" => "FeedbackRight"), - array("type" => "qfeedw", "class" => "FeedbackWrong"), - array("type" => "qover", "class" => "Correct"), - array("type" => "qover", "class" => "Inorrect"), - array("type" => "qover", "class" => "StatusMessage"), - array("type" => "qover", "class" => "WrongAnswersMessage"), - array("type" => "flist_cont", "class" => "FileListContainer"), - array("type" => "flist_head", "class" => "FileListHeading"), - array("type" => "flist", "class" => "FileList"), - array("type" => "flist_li", "class" => "FileListItem"), - array("type" => "flist_a", "class" => "FileListItemLink") - ); - - public static $templates = array( - "table" => array( - "table" => "table", - "caption" => "table_caption", - "row_head" => "table_cell", - "row_foot" => "table_cell", - "col_head" => "table_cell", - "col_foot" => "table_cell", - "odd_row" => "table_cell", - "even_row" => "table_cell", - "odd_col" => "table_cell", - "even_col" => "table_cell"), - "vaccordion" => array( - "va_cntr" => "va_cntr", - "va_icntr" => "va_icntr", - "va_ihead" => "va_ihead", - "va_iheada" => "va_iheada", - "va_ihcap" => "va_ihcap", - "va_icont" => "va_icont" - ), - "haccordion" => array( - "ha_cntr" => "ha_cntr", - "ha_icntr" => "ha_icntr", - "ha_ihead" => "ha_ihead", - "ha_iheada" => "ha_iheada", - "ha_ihcap" => "ha_ihcap", - "ha_icont" => "ha_icont" - ), - "carousel" => array( - "ca_cntr" => "ca_cntr", - "ca_icntr" => "ca_icntr", - "ca_ihead" => "ca_ihead", - "ca_icont" => "ca_icont" - ) - ); - - // basic style xml file, image directory and dom - protected static $basic_style_file = "./libs/ilias/Style/basic_style/style.xml"; - protected static $basic_style_zip = "./libs/ilias/Style/basic_style/style.zip"; - protected static $basic_style_image_dir = "./libs/ilias/Style/basic_style/images"; - protected static $basic_style_dom; - - /** - * Constructor - * @access public - * @param integer reference_id or object_id - * @param boolean treat the id as reference_id (true) or object_id (false) - */ - function __construct($a_id = 0, $a_call_by_reference = false) - { - global $DIC; - - $this->db = $DIC->database(); - $this->lng = $DIC->language(); - $this->type = "sty"; - $this->style = array(); - if($a_call_by_reference) - { - $this->ilias->raiseError("Can't instantiate style object via reference id.",$this->ilias->error_obj->FATAL); - } - - parent::__construct($a_id, false); - } - - /** - * Get basic zip path - * - * @return string - */ - static public function getBasicZipPath(): string - { - return self::$basic_style_zip; - } - - /** - * Set ref id (show error message, since styles do not use ref ids) - */ - function setRefId($a_ref_id) - { - $this->ilias->raiseError("Operation ilObjStyleSheet::setRefId() not allowed.",$this->ilias->error_obj->FATAL); - } - - /** - * Get ref id (show error message, since styles do not use ref ids) - */ - function getRefId() - { - return ""; - //$this->ilias->raiseError("Operation ilObjStyleSheet::getRefId() not allowed.",$this->ilias->error_obj->FATAL); - } - - /** - * Put in tree (show error message, since styles do not use ref ids) - */ - function putInTree($a_parent_ref) - { - $this->ilias->raiseError("Operation ilObjStyleSheet::putInTree() not allowed.",$this->ilias->error_obj->FATAL); - } - - /** - * Create a reference (show error message, since styles do not use ref ids) - */ - function createReference() - { - $this->ilias->raiseError("Operation ilObjStyleSheet::createReference() not allowed.",$this->ilias->error_obj->FATAL); - } - - /** - * Set style up to date (false + update will trigger css generation next time) - */ - function setUpToDate($a_up_to_date = true) - { - $this->up_to_date = $a_up_to_date; - } - - /** - * Get up to date - */ - function getUpToDate() - { - return $this->up_to_date; - } - - /** - * Set scope - */ - function setScope($a_scope) - { - $this->scope = $a_scope; - } - - /** - * Get scope - */ - function getScope() - { - return $this->scope; - } - - /** - * Write up to date - */ - static function _writeUpToDate($a_id, $a_up_to_date) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "UPDATE style_data SET uptodate = ". - $ilDB->quote((int) $a_up_to_date, "integer"). - " WHERE id = ".$ilDB->quote($a_id, "integer"); - $ilDB->manipulate($q); - } - - /** - * Looup up to date - */ - static function _lookupUpToDate($a_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "SELECT uptodate FROM style_data ". - " WHERE id = ".$ilDB->quote($a_id, "integer"); - $res = $ilDB->query($q); - $sty = $ilDB->fetchAssoc($res); - - return (boolean) $sty["uptodate"]; - } - - /** - * Write standard flag - */ - static function _writeStandard($a_id, $a_std) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "UPDATE style_data SET standard = ". - $ilDB->quote((int) $a_std, "integer"). - " WHERE id = ".$ilDB->quote($a_id, "integer"); - $ilDB->manipulate($q); - } - - /** - * Write scope - */ - static function _writeScope($a_id, $a_scope) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "UPDATE style_data SET category = ". - $ilDB->quote((int) $a_scope, "integer"). - " WHERE id = ".$ilDB->quote($a_id, "integer"); - $ilDB->manipulate($q); - } - - /** - * Lookup standard flag - */ - static function _lookupStandard($a_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "SELECT * FROM style_data ". - " WHERE id = ".$ilDB->quote($a_id, "integer"); - $res = $ilDB->query($q); - $sty = $ilDB->fetchAssoc($res); - - return (boolean) $sty["standard"]; - } - - /** - * Write active flag - */ - static function _writeActive($a_id, $a_active) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "UPDATE style_data SET active = ". - $ilDB->quote((int) $a_active, "integer"). - " WHERE id = ".$ilDB->quote($a_id, "integer"); - $ilDB->manipulate($q); - } - - /** - * Lookup active flag - */ - static function _lookupActive($a_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "SELECT * FROM style_data ". - " WHERE id = ".$ilDB->quote($a_id, "integer"); - $res = $ilDB->query($q); - $sty = $ilDB->fetchAssoc($res); - - return (boolean) $sty["active"]; - } - - /** - * Get standard styles - */ - static function _getStandardStyles($a_exclude_default_style = false, - $a_include_deactivated = false, $a_scope = 0) - { - global $DIC; - - $ilDB = $DIC->database(); - $ilSetting = $DIC->settings(); - $tree = $DIC->repositoryTree(); - - $default_style = $ilSetting->get("default_content_style_id"); - - $and_str = ""; - if (!$a_include_deactivated) - { - $and_str = " AND active = 1"; - } - - $q = "SELECT * FROM style_data ". - " WHERE standard = 1".$and_str; - $res = $ilDB->query($q); - $styles = array(); - while($sty = $ilDB->fetchAssoc($res)) - { - if (!$a_exclude_default_style || $default_style != $sty["id"]) - { - // check scope - if ($a_scope > 0 && $sty["category"] > 0) - { - if ($tree->isInTree($sty["category"]) && - $tree->isInTree($a_scope)) - { - $path = $tree->getPathId($a_scope); - if (!in_array($sty["category"], $path)) - { - continue; - } - } - } - $styles[$sty["id"]] = ilObject::_lookupTitle($sty["id"]); - } - } - - return $styles; - } - - - /** - * Get all clonable styles (active standard styles and individual learning - * module styles with write permission). - */ - static function _getClonableContentStyles() - { - global $DIC; - - $ilAccess = $DIC->access(); - $ilDB = $DIC->database(); - - $clonable_styles = array(); - - $q = "SELECT * FROM style_data"; - $style_set = $ilDB->query($q); - while($style_rec = $ilDB->fetchAssoc($style_set)) - { - $clonable = false; - if ($style_rec["standard"] == 1) - { - if ($style_rec["active"] == 1) - { - $clonable = true; - } - } - else - { - include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); - $obj_ids = ilObjContentObject::_lookupContObjIdByStyleId($style_rec["id"]); - if (count($obj_ids) == 0) - { - $obj_ids = self::lookupObjectForStyle($style_rec["id"]); - } - foreach($obj_ids as $id) - { - $ref = ilObject::_getAllReferences($id); - foreach($ref as $ref_id) - { - if ($ilAccess->checkAccess("write", "", $ref_id)) - { - $clonable = true; - } - } - } - } - if ($clonable) - { - $clonable_styles[$style_rec["id"]] = - ilObject::_lookupTitle($style_rec["id"]); - } - } - - asort($clonable_styles); - - return $clonable_styles; - } - - /** - * assign meta data object - */ - function assignMetaData(&$a_meta_data) - { - $this->meta_data = $a_meta_data; - } - - /** - * Get basic style dom - */ - static function _getBasicStyleDom() - { - if (!is_object(self::$basic_style_dom)) - { - self::$basic_style_dom = new DOMDocument(); - self::$basic_style_dom->load(self::$basic_style_file); - } - - return self::$basic_style_dom; - } - - /** - * get meta data object - */ - function &getMetaData() - { - return $this->meta_data; - } - - /** - * Create a new style - */ - function create($a_from_style = 0, $a_import_mode = false) - { - $ilDB = $this->db; - - parent::create(); - - if ($a_from_style == 0) - { - if (!$a_import_mode) - { - // copy styles from basic style - $this->createFromXMLFile(self::$basic_style_file, true); - - // copy images from basic style - $this->createImagesDirectory(); - ilUtil::rCopy(self::$basic_style_image_dir, - $this->getImagesDirectory()); - } - else - { - // add style_data record - $q = "INSERT INTO style_data (id, uptodate, category) VALUES ". - "(".$ilDB->quote($this->getId(), "integer").", 0,". - $ilDB->quote((int) $this->getScope(), "integer").")"; - $ilDB->manipulate($q); - ilObjStyleSheet::_createImagesDirectory($this->getId()); - } - } - else - { - // get style parameter records - $def = array(); - $q = "SELECT * FROM style_parameter WHERE style_id = ". - $ilDB->quote($a_from_style, "integer"); - $par_set = $ilDB->query($q); - while($par_rec = $ilDB->fetchAssoc($par_set)) - { - $def[] = array("tag" => $par_rec["tag"], "class" => $par_rec["class"], - "parameter" => $par_rec["parameter"], "value" => $par_rec["value"], - "type" => $par_rec["type"], "mq_id" => $par_rec["mq_id"], "custom" => $par_rec["custom"]); - } - - // get style characteristics records - $chars = array(); - $q = "SELECT * FROM style_char WHERE style_id = ". - $ilDB->quote($a_from_style, "integer"); - $par_set = $ilDB->query($q); - while($par_rec = $ilDB->fetchAssoc($par_set)) - { - $chars[] = array("type" => $par_rec["type"], "characteristic" => $par_rec["characteristic"]); - } - - - // copy media queries - $from_style = new ilObjStyleSheet($a_from_style); - $mqs = $from_style->getMediaQueries(); - $mq_mapping = array(); - foreach ($mqs as $mq) - { - $nid = $this->addMediaQuery($mq["mquery"]); - $mq_mapping[$mq["id"]] = $nid; - } - - // default style settings - foreach ($def as $sty) - { - $id = $ilDB->nextId("style_parameter"); - $q = "INSERT INTO style_parameter (id, style_id, tag, class, parameter, value, type, mq_id, custom) VALUES ". - "(". - $ilDB->quote($id, "integer").",". - $ilDB->quote($this->getId(), "integer").",". - $ilDB->quote($sty["tag"], "text").",". - $ilDB->quote($sty["class"], "text").",". - $ilDB->quote($sty["parameter"], "text").",". - $ilDB->quote($sty["value"], "text").",". - $ilDB->quote($sty["type"], "text").",". - $ilDB->quote((int) $mq_mapping[$sty["mq_id"]], "integer").",". - $ilDB->quote($sty["custom"], "integer"). - ")"; - $ilDB->manipulate($q); - } - - // insert style characteristics - foreach ($chars as $char) - { - $q = "INSERT INTO style_char (style_id, type, characteristic) VALUES ". - "(".$ilDB->quote($this->getId(), "integer").",". - $ilDB->quote($char["type"], "text").",". - $ilDB->quote($char["characteristic"], "text").")"; - $ilDB->manipulate($q); - } - - // add style_data record - $q = "INSERT INTO style_data (id, uptodate, category) VALUES ". - "(".$ilDB->quote($this->getId(), "integer").", 0,". - $ilDB->quote((int) $this->getScope(), "integer").")"; - $ilDB->manipulate($q); - - // copy images - $this->createImagesDirectory(); - ilUtil::rCopy($from_style->getImagesDirectory(), - $this->getImagesDirectory()); - - // copy colors - $colors = $from_style->getColors(); - foreach ($colors as $c) - { - $this->addColor($c["name"], $c["code"]); - } - - // copy templates - $tcts = ilObjStyleSheet::_getTemplateClassTypes(); - foreach ($tcts as $tct => $v) - { - $templates = $from_style->getTemplates($tct); - foreach ($templates as $t) - { - $this->addTemplate($tct, $t["name"], $t["classes"]); - } - } - - } - - $this->read(); - if (!$a_import_mode) - { - $this->writeCSSFile(); - } - } - - /** - * Delete Characteristic - */ - function deleteCharacteristic($a_type, $a_tag, $a_class) - { - $ilDB = $this->db; - - // check, if characteristic is not a core style - $core_styles = ilObjStyleSheet::_getCoreStyles(); - if (empty($core_styles[$a_type.".".$a_tag.".".$a_class])) - { - // delete characteristic record - $st = $ilDB->manipulateF( - "DELETE FROM style_char WHERE style_id = %s AND type = %s AND characteristic = %s", - array("integer", "text", "text"), - array($this->getId(), $a_type, $a_class)); - - // delete parameter records - $st = $ilDB->manipulateF("DELETE FROM style_parameter WHERE style_id = %s AND tag = %s AND type = %s AND class = %s", - array("integer", "text", "text", "text"), - array($this->getId(), $a_tag, $a_type, $a_class)); - } - - $this->setUpToDate(false); - $this->_writeUpToDate($this->getId(), false); - } - - /** - * Check whether characteristic exists - */ - function characteristicExists($a_char, $a_style_type) - { - $ilDB = $this->db; - - $set = $ilDB->queryF( - "SELECT style_id FROM style_char WHERE style_id = %s AND characteristic = %s AND type = %s", - array("integer", "text", "text"), - array($this->getId(), $a_char, $a_style_type)); - if ($rec = $ilDB->fetchAssoc($set)) - { - return true; - } - return false; - } - - /** - * Add characteristic - */ - function addCharacteristic($a_type, $a_char, $a_hidden = false) - { - $ilDB = $this->db; - - // delete characteristic record - $ilDB->manipulateF("INSERT INTO style_char (style_id, type, characteristic, hide)". - " VALUES (%s,%s,%s,%s) ", - array("integer", "text", "text", "integer"), - array($this->getId(), $a_type, $a_char, $a_hidden)); - - $this->setUpToDate(false); - $this->_writeUpToDate($this->getId(), false); - } - - /** - * Copy characteristic - * - * @param - * @return - */ - function copyCharacteristic($a_from_style_id, - $a_from_type, $a_from_char, $a_to_char) - { - $ilDB = $this->db; - - if (!$this->characteristicExists($a_to_char, $a_from_type)) - { - $this->addCharacteristic($a_from_type, $a_to_char); - } - $this->deleteStyleParOfChar($a_from_type, $a_to_char); - - $from_style = new ilObjStyleSheet($a_from_style_id); - - // todo fix using mq_id - $pars = $from_style->getParametersOfClass($a_from_type, $a_from_char); - - $colors = array(); - foreach ($pars as $p => $v) - { - if (substr($v, 0, 1) == "!") - { - $colors[] = substr($v, 1); - } - $this->replaceStylePar(ilObjStyleSheet::_determineTag($a_from_type), - $a_to_char, $p, $v, $a_from_type); - } - - // copy colors - foreach ($colors as $c) - { - if (!$this->colorExists($c)) - { - $this->addColor($c, $from_style->getColorCodeForName($c)); - } - } - } - - /** - * Get characteristics - */ - function getCharacteristics($a_type = "", $a_no_hidden = false, $a_include_core = true) - { - $chars = array(); - - if ($a_type == "") - { - $chars = $this->chars; - } - if (is_array($this->chars_by_type[$a_type])) - { - foreach ($this->chars_by_type[$a_type] as $c) - { - if ($a_include_core || !self::isCoreStyle($a_type, $c)) - { - $chars[] = $c; - } - } - } - - if ($a_no_hidden) - { - foreach ($chars as $k => $char) - { - if ($a_type == "" && $this->hidden_chars[$char["type"].":".$char["class"]]) - { - unset($chars[$k]); - } - else if ($this->hidden_chars[$a_type.":".$char]) - { - unset($chars[$k]); - } - } - } - - return $chars; - } - - /** - * Set characteristics - */ - function setCharacteristics($a_chars) - { - $this->chars = $a_chars; - // $this->chars_by_type[$a_type]; - } - - /** - * Save characteristic hide status - */ - function saveHideStatus($a_type, $a_char, $a_hide) - { - $ilDB = $this->db; - - $ilDB->manipulate("UPDATE style_char SET ". - " hide = ".$ilDB->quote((int) $a_hide, "integer"). - " WHERE style_id = ".$ilDB->quote($this->getId(), "integer")." AND ". - " type = ".$ilDB->quote($a_type, "text")." AND ". - " characteristic = ".$ilDB->quote($a_char, "text") - ); - } - - /** - * Get characteristic hide status - */ - function getHideStatus($a_type, $a_char) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT hide FROM style_char ". - " WHERE style_id = ".$ilDB->quote($this->getId(), "integer")." AND ". - " type = ".$ilDB->quote($a_type, "text")." AND ". - " characteristic = ".$ilDB->quote($a_char, "text") - ); - $rec = $ilDB->fetchAssoc($set); - - return $rec["hide"]; - } - - /** - * clone style sheet (note: styles have no ref ids and return an object id) - * - * @access public - * @return integer new obj id - */ - function ilClone() - { - $lng = $this->lng; - - $lng->loadLanguageModule("style"); - - $new_obj = new ilObjStyleSheet(); - $new_obj->setTitle($this->getTitle()." (".$lng->txt("sty_acopy").")"); - $new_obj->setType($this->getType()); - $new_obj->setDescription($this->getDescription()); - $new_obj->create($this->getId()); - - $new_obj->writeStyleSetting("disable_auto_margins", - $this->lookupStyleSetting("disable_auto_margins")); - - return $new_obj->getId(); - } - - /** - * Copy images to directory - */ - function copyImagesToDir($a_target) - { - ilUtil::rCopy($this->getImagesDirectory(), $a_target); - } - - /** - * write style parameter to db - * - * todo check usages add mq_id - * - * @param string $a_tag tag name (tag.class, e.g. "div.Mnemonic") - * @param string $a_par tag parameter (e.g. "margin-left") - * @param string $a_type style type (e.g. "section") - */ - function addParameter($a_tag, $a_par, $a_type, $a_mq_id = 0, $a_custom = false) - { - $ilDB = $this->db; - - $avail_params = $this->getAvailableParameters(); - $tag = explode(".", $a_tag); - $value = $avail_params[$a_par][0]; - $id = $ilDB->nextId("style_parameter"); - $q = "INSERT INTO style_parameter (id,style_id, type, tag, class, parameter, value, mq_id, custom) VALUES ". - "(". - $ilDB->quote($id, "integer").",". - $ilDB->quote($this->getId(), "integer").",". - $ilDB->quote($a_type, "text").",". - $ilDB->quote($tag[0], "text").",". - $ilDB->quote($tag[1], "text").",". - $ilDB->quote($a_par, "text").",". - $ilDB->quote($value, "text").",". - $ilDB->quote($a_mq_id, "integer").",". - $ilDB->quote($a_custom, "integer"). - ")"; - $ilDB->manipulate($q); - $this->read(); - $this->writeCSSFile(); - } - - /** - * Create images directory - * /sty/sty_/images - */ - function createImagesDirectory() - { - return ilObjStyleSheet::_createImagesDirectory($this->getId()); - } - - /** - * Create images directory - * /sty/sty_/images - */ - static function _createImagesDirectory($a_style_id) - { - global $DIC; - - $ilErr = $DIC["ilErr"]; - - $sty_data_dir = ilUtil::getWebspaceDir()."/sty"; - ilUtil::makeDir($sty_data_dir); - if(!is_writable($sty_data_dir)) - { - $ilErr->raiseError("Style data directory (".$sty_data_dir - .") not writeable.", $ilErr->FATAL); - } + public $style; + + public static $num_unit = array("px", "em", "ex", "%", "pt", "pc", "in", "mm", "cm"); + public static $num_unit_no_perc = array("px", "em", "ex", "pt", "pc", "in", "mm", "cm"); + + // css parameters and their attribute values, input type and group + public static $parameter = array( + "font-size" => array( + "values" => array("xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large", "smaller", "larger"), + "input" => "fontsize", + "group" => "text"), + "font-family" => array( + "values" => array(), + "input" => "text", + "group" => "text"), + "font-style" => array( + "values" => array("italic", "oblique", "normal"), + "input" => "select", + "group" => "text"), + "font-weight" => array( + "values" => array("bold", "normal", "bolder", "lighter"), + "input" => "select", + "group" => "text"), + "font-variant" => array( + "values" => array("small-caps", "normal"), + "input" => "select", + "group" => "text"), + "word-spacing" => array( + "values" => array(), + "input" => "numeric_no_perc", + "group" => "text"), + "letter-spacing" => array( + "values" => array(), + "input" => "numeric_no_perc", + "group" => "text"), + "text-decoration" => array( + "values" => array("underline", "overline", "line-through", "blink", "none"), + "input" => "select", + "group" => "text"), + "text-transform" => array( + "values" => array("capitalize", "uppercase", "lowercase", "none"), + "input" => "select", + "group" => "text"), + "color" => array( + "values" => array(), + "input" => "color", + "group" => "text"), + "text-indent" => array( + "values" => array(), + "input" => "numeric", + "group" => "text"), + "line-height" => array( + "values" => array(), + "input" => "numeric", + "group" => "text"), + "vertical-align" => array( + "values" => array("top", "middle", "bottom", "baseline", "sub", "super", + "text-top", "text-bottom"), + "input" => "select", + "group" => "text"), + "text-align" => array( + "values" => array("left", "center", "right", "justify"), + "input" => "select", + "group" => "text"), + "white-space" => array( + "values" => array("normal", "pre", "nowrap"), + "input" => "select", + "group" => "text"), + "margin" => array( + "values" => array(), + "input" => "trbl_numeric", + "subpar" => array("margin", "margin-top", "margin-right", + "margin-bottom", "margin-left"), + "group" => "margin_and_padding"), + "padding" => array( + "values" => array(), + "input" => "trbl_numeric", + "subpar" => array("padding", "padding-top", "padding-right", + "padding-bottom", "padding-left"), + "group" => "margin_and_padding"), + "border-width" => array( + "values" => array("thin", "medium", "thick"), + "input" => "border_width", + "subpar" => array("border-width", "border-top-width", "border-right-width", + "border-bottom-width", "border-left-width"), + "group" => "border"), + "border-color" => array( + "values" => array(), + "input" => "trbl_color", + "subpar" => array("border-color", "border-top-color", "border-right-color", + "border-bottom-color", "border-left-color"), + "group" => "border"), + "border-style" => array( + "values" => array("none", "hidden", "dotted", "dashed", "solid", "double", + "groove", "ridge", "inset", "outset"), + "input" => "border_style", + "subpar" => array("border-style", "border-top-style", "border-right-style", + "border-bottom-style", "border-left-style"), + "group" => "border"), + + "background-color" => array( + "values" => array(), + "input" => "color", + "group" => "background"), + "background-image" => array( + "values" => array(), + "input" => "background_image", + "group" => "background"), + "background-repeat" => array( + "values" => array("repeat", "repeat-x", "repeat-y", "no-repeat"), + "input" => "select", + "group" => "background"), + "background-attachment" => array( + "values" => array("fixed", "scroll"), + "input" => "select", + "group" => "background"), + "background-position" => array( + "values" => array("horizontal" => array("left", "center", "right"), + "vertical" => array("top", "center", "bottom")), + "input" => "background_position", + "group" => "background"), + + "position" => array( + "values" => array("absolute", "fixed", "relative", "static"), + "input" => "select", + "group" => "positioning"), + "top" => array( + "values" => array(), + "input" => "numeric", + "group" => "positioning"), + "bottom" => array( + "values" => array(), + "input" => "numeric", + "group" => "positioning"), + "left" => array( + "values" => array(), + "input" => "numeric", + "group" => "positioning"), + "right" => array( + "values" => array(), + "input" => "numeric", + "group" => "positioning"), + "width" => array( + "values" => array(), + "input" => "numeric", + "group" => "positioning"), + "height" => array( + "values" => array(), + "input" => "numeric", + "group" => "positioning"), + "min-height" => array( + "values" => array(), + "input" => "numeric", + "group" => "positioning"), + "float" => array( + "values" => array("left", "right", "none"), + "input" => "select", + "group" => "positioning"), + "overflow" => array( + "values" => array("visible", "hidden", "scroll", "auto"), + "input" => "select", + "group" => "positioning"), + "opacity" => array( + "values" => array(), + "input" => "percentage", + "group" => "special"), + "transform" => array( + "values" => array("rotate(90deg)", "rotate(180deg)", "rotate(270deg)"), + "input" => "select", + "group" => "special"), + "transform-origin" => array( + "values" => array( "horizontal" => array("left", "center", "right"), + "vertical" => array("top", "center", "bottom")), + "input" => "background_position", + "group" => "special"), + "cursor" => array( + "values" => array("auto", "default", "crosshair", "pointer", "move", + "n-resize", "ne-resize", "e-resize", "se-resize", "s-resize", "sw-resize", + "w-resize", "nw-resize", "text", "wait", "help"), + "input" => "select", + "group" => "special"), + "clear" => array( + "values" => array("both","left","right","none"), + "input" => "select", + "group" => "special"), + + "list-style-type.ol" => array( + "values" => array("decimal","lower-roman","upper-roman", + "lower-alpha", "upper-alpha", "lower-greek", "hebrew", + "decimal-leading-zero", "cjk-ideographic", "hiragana", + "katakana", "hiragana-iroha", "katakana-iroha", "none"), + "input" => "select", + "group" => "ol"), + "list-style-type.ul" => array( + "values" => array("disc","circle","square", + "none"), + "input" => "select", + "group" => "ul"), + "list-style-image.ul" => array( + "values" => array(), + "input" => "background_image", + "group" => "ul"), + "list-style-position.ol" => array( + "values" => array("inside","outside"), + "input" => "select", + "group" => "ol"), + "list-style-position.ul" => array( + "values" => array("inside","outside"), + "input" => "select", + "group" => "ul" + ), + "border-collapse" => array( + "values" => array("collapse","separate"), + "input" => "select", + "group" => "table" + ), + "caption-side" => array( + "values" => array("top","bottom","left","right"), + "input" => "select", + "group" => "table" + ) + ); + + // filter groups of properties that should only be + // displayed with matching tag (group -> tags) + public static $filtered_groups = + array("ol" => array("ol"), "ul" => array("ul"), + "table" => array("table"), "positioning" => array("h1", "h2", "h3", "div", "img", "table", "a", "figure")); + + // style types and their super type + public static $style_super_types = array( + "text_block" => array("text_block", "heading1", "heading2", "heading3", "code_block"), + "text_inline" => array("text_inline", "sub", "sup", "code_inline"), + "section" => array("section"), + "link" => array("link"), + "table" => array("table", "table_cell", "table_caption"), + "list" => array("list_o", "list_u", "list_item"), + "flist" => array("flist_cont", "flist_head", "flist", "flist_li", "flist_a"), + "media" => array("media_cont", "media_caption", "iim", "marker"), + "tabs" => array("va_cntr", "va_icntr", "va_ihead", "va_iheada", "va_ihcap", "va_icont", + "ha_cntr", "ha_icntr", "ha_ihead", "ha_iheada", "ha_ihcap", "ha_icont", "ca_cntr", "ca_icntr", "ca_ihead", "ca_icont"), + "question" => array("question", "qtitle", "qanswer", "qinput", "qlinput", "qsubmit", "qfeedr", "qfeedw", + "qimg", "qordul", "qordli", "qimgd", "qetitem", "qetcorr", "qover"), + "page" => array("page_frame", "page_cont", "page_title", "page_fn", + "page_tnav", "page_bnav", "page_lnav", "page_rnav", "page_lnavlink", "page_rnavlink", + "page_lnavimage", "page_rnavimage"), + "glo" => array("glo_overlay", "glo_ovtitle", "glo_ovclink", "glo_ovuglink", "glo_ovuglistlink"), + "sco" => array("sco_title", "sco_keyw", "sco_desc", "sco_desct", "sco_obj", "sco_objt", "sco_fmess"), + "rte" => array("rte_menu", "rte_mlink", "rte_tree", "rte_node", "rte_tlink","rte_status", + "rte_tul", "rte_tli", "rte_texp", "rte_tclink", "rte_drag") + ); + + // these types are expandable, i.e. the user can define new style classes + public static $expandable_types = array( + "text_block", "text_inline", "section", "media_cont", "table", "table_cell", "flist_li", "table_caption", + "list_o", "list_u", + "va_cntr", "va_icntr", "va_ihead", "va_iheada", "va_ihcap", "va_icont", + "ha_cntr", "ha_icntr", "ha_ihead", "ha_iheada", "ha_ihcap", "ha_icont", + "ca_cntr", "ca_icntr", "ca_ihead", "ca_icont" + ); + + // these types can be hidden in the content editor + public static $hideable_types = array( + "table", "table_cell" + ); + + // tag that are used by style types + public static $assigned_tags = array( + "text_block" => "div", + "heading1" => "h1", + "heading2" => "h2", + "heading3" => "h3", + "code_block" => "pre", + "text_inline" => "span", + "code_inline" => "code", + "sup" => "sup", + "sub" => "sub", + "section" => "div", + "link" => "a", + "table" => "table", + "table_cell" => "td", + "table_caption" => "caption", + "media_cont" => "figure", + "media_caption" => "div", + "iim" => "div", + "marker" => "a", + "glo_overlay" => "div", + "glo_ovtitle" => "h1", + "glo_ovclink" => "a", + "glo_ovuglink" => "a", + "glo_ovuglistlink" => "a", + "sco_title" => "div", + "sco_keyw" => "div", + "sco_desc" => "div", + "sco_obj" => "div", + "sco_desct" => "div", + "sco_objt" => "div", + "sco_fmess" => "div", + "rte_menu" => "div", + "rte_mlink" => "a", + "rte_tree" => "div", + "rte_tclink" => "a", + "rte_drag" => "div", + "rte_node" => "div", + "rte_status" => "div", + "rte_tlink" => "a", + "rte_tul" => "div", + "rte_tli" => "div", + "rte_texp" => "a", + "list_o" => "ol", + "list_u" => "ul", + "list_item" => "li", + "flist_cont" => "div", + "flist_head" => "div", + "flist" => "ul", + "flist_li" => "li", + "flist_a" => "a", + "question" => "div", + "qtitle" => "div", + "qanswer" => "div", + "qimg" => "img", + "qimgd" => "a", + "qordul" => "ul", + "qordli" => "li", + "qetitem" => "a", + "qetcorr" => "span", + "qinput" => "input", + "qlinput" => "textarea", + "qsubmit" => "input", + "qfeedr" => "div", + "qfeedw" => "div", + "qover" => "div", + "page_frame" => "div", + "page_cont" => "div", + "page_fn" => "div", + "page" => "div", + "page_tnav" => "div", + "page_bnav" => "div", + "page_lnav" => "div", + "page_rnav" => "div", + "page_lnavlink" => "a", + "page_rnavlink" => "a", + "page_lnavimage" => "img", + "page_rnavimage" => "img", + "page_title" => "h1", + "va_cntr" => "div", + "va_icntr" => "div", + "va_icont" => "div", + "va_ihead" => "div", + "va_iheada" => "div", + "va_ihcap" => "div", + "ha_cntr" => "div", + "ha_icntr" => "div", + "ha_icont" => "div", + "ha_iheada" => "div", + "ha_ihcap" => "div", + "ha_ihead" => "div", + "ca_cntr" => "div", + "ca_icntr" => "div", + "ca_ihead" => "div", + "ca_icont" => "div" + ); + + // pseudo classes + public static $pseudo_classes = + array("a" => array("hover"), "div" => array("hover"), "img" => array("hover")); + + // core styles these styles MUST exists -> see also basic_style/style.xml + public static $core_styles = array( + array("type" => "text_block", "class" => "Standard"), + array("type" => "text_block", "class" => "List"), + array("type" => "text_block", "class" => "TableContent"), + array("type" => "code_block", "class" => "Code"), + array("type" => "heading1", "class" => "Headline1"), + array("type" => "heading2", "class" => "Headline2"), + array("type" => "heading3", "class" => "Headline3"), + array("type" => "text_inline", "class" => "Comment"), + array("type" => "text_inline", "class" => "Emph"), + array("type" => "text_inline", "class" => "Quotation"), + array("type" => "text_inline", "class" => "Strong"), + array("type" => "text_inline", "class" => "Accent"), + array("type" => "text_inline", "class" => "Important"), + array("type" => "code_inline", "class" => "CodeInline"), + array("type" => "sup", "class" => "Sup"), + array("type" => "sub", "class" => "Sub"), + array("type" => "link", "class" => "IntLink"), + array("type" => "link", "class" => "ExtLink"), + array("type" => "link", "class" => "FootnoteLink"), + array("type" => "link", "class" => "FileLink"), + array("type" => "link", "class" => "GlossaryLink"), + array("type" => "media_cont", "class" => "MediaContainer"), + array("type" => "media_cont", "class" => "MediaContainerMax50"), + array("type" => "media_cont", "class" => "MediaContainerFull100"), + array("type" => "table", "class" => "StandardTable"), + array("type" => "media_caption", "class" => "MediaCaption"), + array("type" => "iim", "class" => "ContentPopup"), + array("type" => "marker", "class" => "Marker"), + array("type" => "page_frame", "class" => "PageFrame"), + array("type" => "page_cont", "class" => "PageContainer"), + array("type" => "page", "class" => "Page"), + array("type" => "page_tnav", "class" => "TopNavigation"), + array("type" => "page_bnav", "class" => "BottomNavigation"), + array("type" => "page_lnav", "class" => "LeftNavigation"), + array("type" => "page_rnav", "class" => "RightNavigation"), + array("type" => "page_lnavlink", "class" => "LeftNavigationLink"), + array("type" => "page_rnavlink", "class" => "RightNavigationLink"), + array("type" => "page_lnavimage", "class" => "LeftNavigationImage"), + array("type" => "page_rnavimage", "class" => "RightNavigationImage"), + array("type" => "page_fn", "class" => "Footnote"), + array("type" => "page_title", "class" => "PageTitle"), + array("type" => "glo_overlay", "class" => "GlossaryOverlay"), + array("type" => "glo_ovtitle", "class" => "GlossaryOvTitle"), + array("type" => "glo_ovclink", "class" => "GlossaryOvCloseLink"), + array("type" => "glo_ovuglink", "class" => "GlossaryOvUnitGloLink"), + array("type" => "glo_ovuglistlink", "class" => "GlossaryOvUGListLink"), + array("type" => "sco_title", "class" => "Title"), + array("type" => "sco_desc", "class" => "Description"), + array("type" => "sco_desct", "class" => "DescriptionTop"), + array("type" => "sco_keyw", "class" => "Keywords"), + array("type" => "sco_obj", "class" => "Objective"), + array("type" => "sco_objt", "class" => "ObjectiveTop"), + array("type" => "sco_fmess", "class" => "FinalMessage"), + array("type" => "rte_menu", "class" => "RTEMenu"), + array("type" => "rte_menu", "class" => "RTELogo"), + array("type" => "rte_menu", "class" => "RTELinkBar"), + array("type" => "rte_mlink", "class" => "RTELink"), + array("type" => "rte_mlink", "class" => "RTELinkDisabled"), + array("type" => "rte_tree", "class" => "RTETree"), + array("type" => "rte_node", "class" => "RTECourse"), + array("type" => "rte_node", "class" => "RTEChapter"), + array("type" => "rte_node", "class" => "RTESco"), + array("type" => "rte_node", "class" => "RTEAsset"), + array("type" => "rte_node", "class" => "RTECourseDisabled"), + array("type" => "rte_node", "class" => "RTEChapterDisabled"), + array("type" => "rte_node", "class" => "RTEScoDisabled"), + array("type" => "rte_node", "class" => "RTEAssetDisabled"), + array("type" => "rte_status", "class" => "RTEAsset"), + array("type" => "rte_status", "class" => "RTECompleted"), + array("type" => "rte_status", "class" => "RTENotAttempted"), + array("type" => "rte_status", "class" => "RTERunning"), + array("type" => "rte_status", "class" => "RTEIncomplete"), + array("type" => "rte_status", "class" => "RTEPassed"), + array("type" => "rte_status", "class" => "RTEFailed"), + array("type" => "rte_status", "class" => "RTEBrowsed"), + array("type" => "rte_tlink", "class" => "RTETreeLink"), + array("type" => "rte_tlink", "class" => "RTETreeLinkDisabled"), + array("type" => "rte_tlink", "class" => "RTETreeCurrent"), + array("type" => "rte_tul", "class" => "RTETreeList"), + array("type" => "rte_tli", "class" => "RTETreeItem"), + array("type" => "rte_texp", "class" => "RTETreeExpanded"), + array("type" => "rte_texp", "class" => "RTETreeCollapsed"), + array("type" => "rte_tree", "class" => "RTETreeControl"), + array("type" => "rte_tclink", "class" => "RTETreeControlLink"), + array("type" => "rte_drag", "class" => "RTEDragBar"), + array("type" => "list_o", "class" => "NumberedList"), + array("type" => "list_u", "class" => "BulletedList"), + array("type" => "list_item", "class" => "StandardListItem"), + array("type" => "question", "class" => "Standard"), + array("type" => "question", "class" => "SingleChoice"), + array("type" => "question", "class" => "MultipleChoice"), + array("type" => "question", "class" => "TextQuestion"), + array("type" => "question", "class" => "OrderingQuestion"), + array("type" => "question", "class" => "MatchingQuestion"), + array("type" => "question", "class" => "ImagemapQuestion"), + array("type" => "question", "class" => "ErrorText"), + array("type" => "question", "class" => "TextSubset"), + array("type" => "question", "class" => "ClozeTest"), + array("type" => "qtitle", "class" => "Title"), + array("type" => "qanswer", "class" => "Answer"), + array("type" => "qimg", "class" => "QuestionImage"), + array("type" => "qimgd", "class" => "ImageDetailsLink"), + array("type" => "qordul", "class" => "OrderList"), + array("type" => "qordli", "class" => "OrderListItem"), + array("type" => "qordul", "class" => "OrderListHorizontal"), + array("type" => "qordli", "class" => "OrderListItemHorizontal"), + array("type" => "qetitem", "class" => "ErrorTextItem"), + array("type" => "qetitem", "class" => "ErrorTextSelected"), + array("type" => "qetcorr", "class" => "ErrorTextCorrected"), + array("type" => "qinput", "class" => "TextInput"), + array("type" => "qlinput", "class" => "LongTextInput"), + array("type" => "qsubmit", "class" => "Submit"), + array("type" => "qfeedr", "class" => "FeedbackRight"), + array("type" => "qfeedw", "class" => "FeedbackWrong"), + array("type" => "qover", "class" => "Correct"), + array("type" => "qover", "class" => "Inorrect"), + array("type" => "qover", "class" => "StatusMessage"), + array("type" => "qover", "class" => "WrongAnswersMessage"), + array("type" => "flist_cont", "class" => "FileListContainer"), + array("type" => "flist_head", "class" => "FileListHeading"), + array("type" => "flist", "class" => "FileList"), + array("type" => "flist_li", "class" => "FileListItem"), + array("type" => "flist_a", "class" => "FileListItemLink") + ); + + public static $templates = array( + "table" => array( + "table" => "table", + "caption" => "table_caption", + "row_head" => "table_cell", + "row_foot" => "table_cell", + "col_head" => "table_cell", + "col_foot" => "table_cell", + "odd_row" => "table_cell", + "even_row" => "table_cell", + "odd_col" => "table_cell", + "even_col" => "table_cell"), + "vaccordion" => array( + "va_cntr" => "va_cntr", + "va_icntr" => "va_icntr", + "va_ihead" => "va_ihead", + "va_iheada" => "va_iheada", + "va_ihcap" => "va_ihcap", + "va_icont" => "va_icont" + ), + "haccordion" => array( + "ha_cntr" => "ha_cntr", + "ha_icntr" => "ha_icntr", + "ha_ihead" => "ha_ihead", + "ha_iheada" => "ha_iheada", + "ha_ihcap" => "ha_ihcap", + "ha_icont" => "ha_icont" + ), + "carousel" => array( + "ca_cntr" => "ca_cntr", + "ca_icntr" => "ca_icntr", + "ca_ihead" => "ca_ihead", + "ca_icont" => "ca_icont" + ) + ); + + // basic style xml file, image directory and dom + protected static $basic_style_file = "./libs/ilias/Style/basic_style/style.xml"; + protected static $basic_style_zip = "./libs/ilias/Style/basic_style/style.zip"; + protected static $basic_style_image_dir = "./libs/ilias/Style/basic_style/images"; + protected static $basic_style_dom; + + /** + * Constructor + * @access public + * @param integer reference_id or object_id + * @param boolean treat the id as reference_id (true) or object_id (false) + */ + public function __construct($a_id = 0, $a_call_by_reference = false) + { + global $DIC; + + $this->db = $DIC->database(); + $this->lng = $DIC->language(); + $this->type = "sty"; + $this->style = array(); + if ($a_call_by_reference) { + $this->ilias->raiseError("Can't instantiate style object via reference id.", $this->ilias->error_obj->FATAL); + } + + parent::__construct($a_id, false); + } + + /** + * Get basic zip path + * + * @return string + */ + public static function getBasicZipPath() : string + { + return self::$basic_style_zip; + } + + /** + * Set ref id (show error message, since styles do not use ref ids) + */ + public function setRefId($a_ref_id) + { + $this->ilias->raiseError("Operation ilObjStyleSheet::setRefId() not allowed.", $this->ilias->error_obj->FATAL); + } + + /** + * Get ref id (show error message, since styles do not use ref ids) + */ + public function getRefId() + { + return ""; + //$this->ilias->raiseError("Operation ilObjStyleSheet::getRefId() not allowed.",$this->ilias->error_obj->FATAL); + } + + /** + * Put in tree (show error message, since styles do not use ref ids) + */ + public function putInTree($a_parent_ref) + { + $this->ilias->raiseError("Operation ilObjStyleSheet::putInTree() not allowed.", $this->ilias->error_obj->FATAL); + } + + /** + * Create a reference (show error message, since styles do not use ref ids) + */ + public function createReference() + { + $this->ilias->raiseError("Operation ilObjStyleSheet::createReference() not allowed.", $this->ilias->error_obj->FATAL); + } + + /** + * Set style up to date (false + update will trigger css generation next time) + */ + public function setUpToDate($a_up_to_date = true) + { + $this->up_to_date = $a_up_to_date; + } + + /** + * Get up to date + */ + public function getUpToDate() + { + return $this->up_to_date; + } + + /** + * Set scope + */ + public function setScope($a_scope) + { + $this->scope = $a_scope; + } + + /** + * Get scope + */ + public function getScope() + { + return $this->scope; + } + + /** + * Write up to date + */ + public static function _writeUpToDate($a_id, $a_up_to_date) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "UPDATE style_data SET uptodate = " . + $ilDB->quote((int) $a_up_to_date, "integer") . + " WHERE id = " . $ilDB->quote($a_id, "integer"); + $ilDB->manipulate($q); + } + + /** + * Looup up to date + */ + public static function _lookupUpToDate($a_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "SELECT uptodate FROM style_data " . + " WHERE id = " . $ilDB->quote($a_id, "integer"); + $res = $ilDB->query($q); + $sty = $ilDB->fetchAssoc($res); + + return (boolean) $sty["uptodate"]; + } + + /** + * Write standard flag + */ + public static function _writeStandard($a_id, $a_std) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "UPDATE style_data SET standard = " . + $ilDB->quote((int) $a_std, "integer") . + " WHERE id = " . $ilDB->quote($a_id, "integer"); + $ilDB->manipulate($q); + } + + /** + * Write scope + */ + public static function _writeScope($a_id, $a_scope) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "UPDATE style_data SET category = " . + $ilDB->quote((int) $a_scope, "integer") . + " WHERE id = " . $ilDB->quote($a_id, "integer"); + $ilDB->manipulate($q); + } + + /** + * Lookup standard flag + */ + public static function _lookupStandard($a_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "SELECT * FROM style_data " . + " WHERE id = " . $ilDB->quote($a_id, "integer"); + $res = $ilDB->query($q); + $sty = $ilDB->fetchAssoc($res); + + return (boolean) $sty["standard"]; + } + + /** + * Write active flag + */ + public static function _writeActive($a_id, $a_active) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "UPDATE style_data SET active = " . + $ilDB->quote((int) $a_active, "integer") . + " WHERE id = " . $ilDB->quote($a_id, "integer"); + $ilDB->manipulate($q); + } + + /** + * Lookup active flag + */ + public static function _lookupActive($a_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "SELECT * FROM style_data " . + " WHERE id = " . $ilDB->quote($a_id, "integer"); + $res = $ilDB->query($q); + $sty = $ilDB->fetchAssoc($res); + + return (boolean) $sty["active"]; + } + + /** + * Get standard styles + */ + public static function _getStandardStyles( + $a_exclude_default_style = false, + $a_include_deactivated = false, + $a_scope = 0 + ) { + global $DIC; + + $ilDB = $DIC->database(); + $ilSetting = $DIC->settings(); + $tree = $DIC->repositoryTree(); + + $default_style = $ilSetting->get("default_content_style_id"); + + $and_str = ""; + if (!$a_include_deactivated) { + $and_str = " AND active = 1"; + } + + $q = "SELECT * FROM style_data " . + " WHERE standard = 1" . $and_str; + $res = $ilDB->query($q); + $styles = array(); + while ($sty = $ilDB->fetchAssoc($res)) { + if (!$a_exclude_default_style || $default_style != $sty["id"]) { + // check scope + if ($a_scope > 0 && $sty["category"] > 0) { + if ($tree->isInTree($sty["category"]) && + $tree->isInTree($a_scope)) { + $path = $tree->getPathId($a_scope); + if (!in_array($sty["category"], $path)) { + continue; + } + } + } + $styles[$sty["id"]] = ilObject::_lookupTitle($sty["id"]); + } + } + + return $styles; + } + + + /** + * Get all clonable styles (active standard styles and individual learning + * module styles with write permission). + */ + public static function _getClonableContentStyles() + { + global $DIC; + + $ilAccess = $DIC->access(); + $ilDB = $DIC->database(); + + $clonable_styles = array(); + + $q = "SELECT * FROM style_data"; + $style_set = $ilDB->query($q); + while ($style_rec = $ilDB->fetchAssoc($style_set)) { + $clonable = false; + if ($style_rec["standard"] == 1) { + if ($style_rec["active"] == 1) { + $clonable = true; + } + } else { + include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); + $obj_ids = ilObjContentObject::_lookupContObjIdByStyleId($style_rec["id"]); + if (count($obj_ids) == 0) { + $obj_ids = self::lookupObjectForStyle($style_rec["id"]); + } + foreach ($obj_ids as $id) { + $ref = ilObject::_getAllReferences($id); + foreach ($ref as $ref_id) { + if ($ilAccess->checkAccess("write", "", $ref_id)) { + $clonable = true; + } + } + } + } + if ($clonable) { + $clonable_styles[$style_rec["id"]] = + ilObject::_lookupTitle($style_rec["id"]); + } + } + + asort($clonable_styles); + + return $clonable_styles; + } + + /** + * assign meta data object + */ + public function assignMetaData(&$a_meta_data) + { + $this->meta_data = $a_meta_data; + } + + /** + * Get basic style dom + */ + public static function _getBasicStyleDom() + { + if (!is_object(self::$basic_style_dom)) { + self::$basic_style_dom = new DOMDocument(); + self::$basic_style_dom->load(self::$basic_style_file); + } + + return self::$basic_style_dom; + } + + /** + * get meta data object + */ + public function &getMetaData() + { + return $this->meta_data; + } + + /** + * Create a new style + */ + public function create($a_from_style = 0, $a_import_mode = false) + { + $ilDB = $this->db; + + parent::create(); + + if ($a_from_style == 0) { + if (!$a_import_mode) { + // copy styles from basic style + $this->createFromXMLFile(self::$basic_style_file, true); + + // copy images from basic style + $this->createImagesDirectory(); + ilUtil::rCopy( + self::$basic_style_image_dir, + $this->getImagesDirectory() + ); + } else { + // add style_data record + $q = "INSERT INTO style_data (id, uptodate, category) VALUES " . + "(" . $ilDB->quote($this->getId(), "integer") . ", 0," . + $ilDB->quote((int) $this->getScope(), "integer") . ")"; + $ilDB->manipulate($q); + ilObjStyleSheet::_createImagesDirectory($this->getId()); + } + } else { + // get style parameter records + $def = array(); + $q = "SELECT * FROM style_parameter WHERE style_id = " . + $ilDB->quote($a_from_style, "integer"); + $par_set = $ilDB->query($q); + while ($par_rec = $ilDB->fetchAssoc($par_set)) { + $def[] = array("tag" => $par_rec["tag"], "class" => $par_rec["class"], + "parameter" => $par_rec["parameter"], "value" => $par_rec["value"], + "type" => $par_rec["type"], "mq_id" => $par_rec["mq_id"], "custom" => $par_rec["custom"]); + } + + // get style characteristics records + $chars = array(); + $q = "SELECT * FROM style_char WHERE style_id = " . + $ilDB->quote($a_from_style, "integer"); + $par_set = $ilDB->query($q); + while ($par_rec = $ilDB->fetchAssoc($par_set)) { + $chars[] = array("type" => $par_rec["type"], "characteristic" => $par_rec["characteristic"]); + } + + + // copy media queries + $from_style = new ilObjStyleSheet($a_from_style); + $mqs = $from_style->getMediaQueries(); + $mq_mapping = array(); + foreach ($mqs as $mq) { + $nid = $this->addMediaQuery($mq["mquery"]); + $mq_mapping[$mq["id"]] = $nid; + } + + // default style settings + foreach ($def as $sty) { + $id = $ilDB->nextId("style_parameter"); + $q = "INSERT INTO style_parameter (id, style_id, tag, class, parameter, value, type, mq_id, custom) VALUES " . + "(" . + $ilDB->quote($id, "integer") . "," . + $ilDB->quote($this->getId(), "integer") . "," . + $ilDB->quote($sty["tag"], "text") . "," . + $ilDB->quote($sty["class"], "text") . "," . + $ilDB->quote($sty["parameter"], "text") . "," . + $ilDB->quote($sty["value"], "text") . "," . + $ilDB->quote($sty["type"], "text") . "," . + $ilDB->quote((int) $mq_mapping[$sty["mq_id"]], "integer") . "," . + $ilDB->quote($sty["custom"], "integer") . + ")"; + $ilDB->manipulate($q); + } + + // insert style characteristics + foreach ($chars as $char) { + $q = "INSERT INTO style_char (style_id, type, characteristic) VALUES " . + "(" . $ilDB->quote($this->getId(), "integer") . "," . + $ilDB->quote($char["type"], "text") . "," . + $ilDB->quote($char["characteristic"], "text") . ")"; + $ilDB->manipulate($q); + } + + // add style_data record + $q = "INSERT INTO style_data (id, uptodate, category) VALUES " . + "(" . $ilDB->quote($this->getId(), "integer") . ", 0," . + $ilDB->quote((int) $this->getScope(), "integer") . ")"; + $ilDB->manipulate($q); + + // copy images + $this->createImagesDirectory(); + ilUtil::rCopy( + $from_style->getImagesDirectory(), + $this->getImagesDirectory() + ); + + // copy colors + $colors = $from_style->getColors(); + foreach ($colors as $c) { + $this->addColor($c["name"], $c["code"]); + } + + // copy templates + $tcts = ilObjStyleSheet::_getTemplateClassTypes(); + foreach ($tcts as $tct => $v) { + $templates = $from_style->getTemplates($tct); + foreach ($templates as $t) { + $this->addTemplate($tct, $t["name"], $t["classes"]); + } + } + } + + $this->read(); + if (!$a_import_mode) { + $this->writeCSSFile(); + } + } + + /** + * Delete Characteristic + */ + public function deleteCharacteristic($a_type, $a_tag, $a_class) + { + $ilDB = $this->db; + + // check, if characteristic is not a core style + $core_styles = ilObjStyleSheet::_getCoreStyles(); + if (empty($core_styles[$a_type . "." . $a_tag . "." . $a_class])) { + // delete characteristic record + $st = $ilDB->manipulateF( + "DELETE FROM style_char WHERE style_id = %s AND type = %s AND characteristic = %s", + array("integer", "text", "text"), + array($this->getId(), $a_type, $a_class) + ); + + // delete parameter records + $st = $ilDB->manipulateF( + "DELETE FROM style_parameter WHERE style_id = %s AND tag = %s AND type = %s AND class = %s", + array("integer", "text", "text", "text"), + array($this->getId(), $a_tag, $a_type, $a_class) + ); + } + + $this->setUpToDate(false); + $this->_writeUpToDate($this->getId(), false); + } + + /** + * Check whether characteristic exists + */ + public function characteristicExists($a_char, $a_style_type) + { + $ilDB = $this->db; + + $set = $ilDB->queryF( + "SELECT style_id FROM style_char WHERE style_id = %s AND characteristic = %s AND type = %s", + array("integer", "text", "text"), + array($this->getId(), $a_char, $a_style_type) + ); + if ($rec = $ilDB->fetchAssoc($set)) { + return true; + } + return false; + } + + /** + * Add characteristic + */ + public function addCharacteristic($a_type, $a_char, $a_hidden = false) + { + $ilDB = $this->db; + + // delete characteristic record + $ilDB->manipulateF( + "INSERT INTO style_char (style_id, type, characteristic, hide)" . + " VALUES (%s,%s,%s,%s) ", + array("integer", "text", "text", "integer"), + array($this->getId(), $a_type, $a_char, $a_hidden) + ); + + $this->setUpToDate(false); + $this->_writeUpToDate($this->getId(), false); + } + + /** + * Copy characteristic + * + * @param + * @return + */ + public function copyCharacteristic( + $a_from_style_id, + $a_from_type, + $a_from_char, + $a_to_char + ) { + $ilDB = $this->db; + + if (!$this->characteristicExists($a_to_char, $a_from_type)) { + $this->addCharacteristic($a_from_type, $a_to_char); + } + $this->deleteStyleParOfChar($a_from_type, $a_to_char); + + $from_style = new ilObjStyleSheet($a_from_style_id); + + // todo fix using mq_id + $pars = $from_style->getParametersOfClass($a_from_type, $a_from_char); + + $colors = array(); + foreach ($pars as $p => $v) { + if (substr($v, 0, 1) == "!") { + $colors[] = substr($v, 1); + } + $this->replaceStylePar( + ilObjStyleSheet::_determineTag($a_from_type), + $a_to_char, + $p, + $v, + $a_from_type + ); + } + + // copy colors + foreach ($colors as $c) { + if (!$this->colorExists($c)) { + $this->addColor($c, $from_style->getColorCodeForName($c)); + } + } + } + + /** + * Get characteristics + */ + public function getCharacteristics($a_type = "", $a_no_hidden = false, $a_include_core = true) + { + $chars = array(); + + if ($a_type == "") { + $chars = $this->chars; + } + if (is_array($this->chars_by_type[$a_type])) { + foreach ($this->chars_by_type[$a_type] as $c) { + if ($a_include_core || !self::isCoreStyle($a_type, $c)) { + $chars[] = $c; + } + } + } + + if ($a_no_hidden) { + foreach ($chars as $k => $char) { + if ($a_type == "" && $this->hidden_chars[$char["type"] . ":" . $char["class"]]) { + unset($chars[$k]); + } elseif ($this->hidden_chars[$a_type . ":" . $char]) { + unset($chars[$k]); + } + } + } + + return $chars; + } + + /** + * Set characteristics + */ + public function setCharacteristics($a_chars) + { + $this->chars = $a_chars; + // $this->chars_by_type[$a_type]; + } + + /** + * Save characteristic hide status + */ + public function saveHideStatus($a_type, $a_char, $a_hide) + { + $ilDB = $this->db; + + $ilDB->manipulate( + "UPDATE style_char SET " . + " hide = " . $ilDB->quote((int) $a_hide, "integer") . + " WHERE style_id = " . $ilDB->quote($this->getId(), "integer") . " AND " . + " type = " . $ilDB->quote($a_type, "text") . " AND " . + " characteristic = " . $ilDB->quote($a_char, "text") + ); + } + + /** + * Get characteristic hide status + */ + public function getHideStatus($a_type, $a_char) + { + $ilDB = $this->db; + + $set = $ilDB->query( + "SELECT hide FROM style_char " . + " WHERE style_id = " . $ilDB->quote($this->getId(), "integer") . " AND " . + " type = " . $ilDB->quote($a_type, "text") . " AND " . + " characteristic = " . $ilDB->quote($a_char, "text") + ); + $rec = $ilDB->fetchAssoc($set); + + return $rec["hide"]; + } + + /** + * clone style sheet (note: styles have no ref ids and return an object id) + * + * @access public + * @return integer new obj id + */ + public function ilClone() + { + $lng = $this->lng; + + $lng->loadLanguageModule("style"); + + $new_obj = new ilObjStyleSheet(); + $new_obj->setTitle($this->getTitle() . " (" . $lng->txt("sty_acopy") . ")"); + $new_obj->setType($this->getType()); + $new_obj->setDescription($this->getDescription()); + $new_obj->create($this->getId()); + + $new_obj->writeStyleSetting( + "disable_auto_margins", + $this->lookupStyleSetting("disable_auto_margins") + ); + + return $new_obj->getId(); + } + + /** + * Copy images to directory + */ + public function copyImagesToDir($a_target) + { + ilUtil::rCopy($this->getImagesDirectory(), $a_target); + } + + /** + * write style parameter to db + * + * todo check usages add mq_id + * + * @param string $a_tag tag name (tag.class, e.g. "div.Mnemonic") + * @param string $a_par tag parameter (e.g. "margin-left") + * @param string $a_type style type (e.g. "section") + */ + public function addParameter($a_tag, $a_par, $a_type, $a_mq_id = 0, $a_custom = false) + { + $ilDB = $this->db; + + $avail_params = $this->getAvailableParameters(); + $tag = explode(".", $a_tag); + $value = $avail_params[$a_par][0]; + $id = $ilDB->nextId("style_parameter"); + $q = "INSERT INTO style_parameter (id,style_id, type, tag, class, parameter, value, mq_id, custom) VALUES " . + "(" . + $ilDB->quote($id, "integer") . "," . + $ilDB->quote($this->getId(), "integer") . "," . + $ilDB->quote($a_type, "text") . "," . + $ilDB->quote($tag[0], "text") . "," . + $ilDB->quote($tag[1], "text") . "," . + $ilDB->quote($a_par, "text") . "," . + $ilDB->quote($value, "text") . "," . + $ilDB->quote($a_mq_id, "integer") . "," . + $ilDB->quote($a_custom, "integer") . + ")"; + $ilDB->manipulate($q); + $this->read(); + $this->writeCSSFile(); + } + + /** + * Create images directory + * /sty/sty_/images + */ + public function createImagesDirectory() + { + return ilObjStyleSheet::_createImagesDirectory($this->getId()); + } + + /** + * Create images directory + * /sty/sty_/images + */ + public static function _createImagesDirectory($a_style_id) + { + global $DIC; + + $ilErr = $DIC["ilErr"]; + + $sty_data_dir = ilUtil::getWebspaceDir() . "/sty"; + ilUtil::makeDir($sty_data_dir); + if (!is_writable($sty_data_dir)) { + $ilErr->raiseError("Style data directory (" . $sty_data_dir + . ") not writeable.", $ilErr->FATAL); + } - $style_dir = $sty_data_dir."/sty_".$a_style_id; - ilUtil::makeDir($style_dir); - if(!@is_dir($style_dir)) - { - $ilErr->raiseError("Creation of style directory failed (". - $style_dir.").",$ilErr->FATAL); - } - - // create images subdirectory - $im_dir = $style_dir."/images"; - ilUtil::makeDir($im_dir); - if(!@is_dir($im_dir)) - { - $ilErr->raiseError("Creation of Import Directory failed (". - $im_dir.").", $ilErr->FATAL); - } - - // create thumbnails directory - $thumb_dir = $style_dir."/images/thumbnails"; - ilUtil::makeDir($thumb_dir); - if(!@is_dir($thumb_dir)) - { - $ilErr->raiseError("Creation of Import Directory failed (". - $thumb_dir.").", $ilErr->FATAL); - } - } - - /** - * Get images directory - */ - function getImagesDirectory() - { - return ilObjStyleSheet::_getImagesDirectory($this->getId()); - } - - /** - * Get images directory - */ - static function _getImagesDirectory($a_style_id) - { - return ilUtil::getWebspaceDir()."/sty/sty_".$a_style_id. - "/images"; - } - - /** - * Get thumbnails directory - */ - function getThumbnailsDirectory() - { - return $this->getImagesDirectory(). - "/thumbnails"; - } - - /** - * Get images of style - */ - function getImages() - { - $dir = $this->getImagesDirectory(); - $images = array(); - if (is_dir($dir)) - { - $entries = ilUtil::getDir($dir); - foreach($entries as $entry) - { - if (substr($entry["entry"],0,1) == ".") - { - continue; - } - if ($entry["type"] != "dir") - { - $images[] = $entry; - } - } - } - - return $images; - } - - /** - * Upload image - */ - function uploadImage($a_file) - { - $this->createImagesDirectory(); - @ilUtil::moveUploadedFile($a_file["tmp_name"], $a_file["name"], - $this->getImagesDirectory()."/".$a_file["name"]); - @ilUtil::resizeImage($this->getImagesDirectory()."/".$a_file["name"], - $this->getThumbnailsDirectory()."/".$a_file["name"], 75, 75); - } - - /** - * Delete an image - */ - function deleteImage($a_file) - { - if (is_file($this->getImagesDirectory()."/".$a_file)) - { - unlink($this->getImagesDirectory()."/".$a_file); - } - if (is_file($this->getThumbnailsDirectory()."/".$a_file)) - { - unlink($this->getThumbnailsDirectory()."/".$a_file); - } - } - - /** - * delete style parameter - * - * @param int $a_id style parameter id - */ - function deleteParameter($a_id) - { - $ilDB = $this->db; - - $q = "DELETE FROM style_parameter WHERE id = ". - $ilDB->quote($a_id, "integer"); - $ilDB->query($q); - } - - /** - * Delete style parameter by tag/class/parameter - * - * @param string $a_tag tag - * @param string $a_class class - * @param string $a_par parameter - * @param string $a_type type - * @param string $a_mq_id media query id - */ - function deleteStylePar($a_tag, $a_class, $a_par, $a_type, $a_mq_id = 0, $a_custom = false) - { - $ilDB = $this->db; - - $q = "DELETE FROM style_parameter WHERE ". - " style_id = ".$ilDB->quote($this->getId(), "integer")." AND ". - " tag = ".$ilDB->quote($a_tag, "text")." AND ". - " class = ".$ilDB->quote($a_class, "text")." AND ". - " mq_id = ".$ilDB->quote($a_mq_id, "integer")." AND ". - " custom = ".$ilDB->quote($a_custom, "integer")." AND ". - " ".$ilDB->equals("type", $a_type, "text", true)." AND ". - " parameter = ".$ilDB->quote($a_par, "text"); - - $ilDB->manipulate($q); - } - - /** - * Delete style parameter by tag/class/parameter - * - * @param string $a_tag tag - * @param string $a_class class - * @param string $a_par parameter - * @param string $a_type type - * @param string $a_mq_id media query id - */ - function deleteCustomStylePars($a_tag, $a_class, $a_type, $a_mq_id = 0) - { - $ilDB = $this->db; - - $q = "DELETE FROM style_parameter WHERE ". - " style_id = ".$ilDB->quote($this->getId(), "integer")." AND ". - " tag = ".$ilDB->quote($a_tag, "text")." AND ". - " class = ".$ilDB->quote($a_class, "text")." AND ". - " mq_id = ".$ilDB->quote($a_mq_id, "integer")." AND ". - " custom = ".$ilDB->quote(1, "integer")." AND ". - " ".$ilDB->equals("type", $a_type, "text", true); - - $ilDB->manipulate($q); - } - - /** - * Delete style parameters of characteristic - * - * @param string tag - * @param string class - * @param string parameter - * @param string type - */ - function deleteStyleParOfChar($a_type, $a_class) - { - $ilDB = $this->db; - - $q = "DELETE FROM style_parameter WHERE ". - " style_id = ".$ilDB->quote($this->getId(), "integer")." AND ". - " class = ".$ilDB->quote($a_class, "text")." AND ". - " ".$ilDB->equals("type", $a_type, "text", true); - - $ilDB->manipulate($q); - } - - - /** - * delete style object - */ - function delete() - { - $ilDB = $this->db; - - // delete object - parent::delete(); - - // check whether this style is global default - $def_style = $this->ilias->getSetting("default_content_style_id"); - if ($def_style == $this->getId()) - { - $this->ilias->deleteSetting("default_content_style_id"); - } - - // check whether this style is global fixed - $fixed_style = $this->ilias->getSetting("fixed_content_style_id"); - if ($fixed_style == $this->getId()) - { - $this->ilias->deleteSetting("fixed_content_style_id"); - } - - // delete style parameter - $q = "DELETE FROM style_parameter WHERE style_id = ". - $ilDB->quote($this->getId(), "integer"); - $ilDB->manipulate($q); - - // delete style file - $css_file_name = ilUtil::getWebspaceDir()."/css/style_".$this->getId().".css"; - if (is_file($css_file_name)) - { - unlink($css_file_name); - } - - // delete media queries - $ilDB->manipulate("DELETE FROM sty_media_query WHERE ". - " style_id = ".$ilDB->quote($this->getId(), "integer") - ); - - // delete entries in learning modules - include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); - ilObjContentObject::_deleteStyleAssignments($this->getId()); - - // delete style data record - $q = "DELETE FROM style_data WHERE id = ". - $ilDB->quote($this->getId(), "integer"); - $ilDB->manipulate($q); - - } - - - /** - * read style properties - */ - function read() - { - $ilDB = $this->db; - - parent::read(); - - $q = "SELECT * FROM style_parameter WHERE style_id = ". - $ilDB->quote($this->getId(), "integer")." ORDER BY tag, class, type, mq_id "; - $style_set = $ilDB->query($q); - $ctag = ""; - $cclass = ""; - $ctype = ""; - $cmq_id = 0; - $this->style = array(); - // workaround for bug #17586, see also http://stackoverflow.com/questions/3066356/multiple-css-classes-properties-overlapping-based-on-the-order-defined - // e.g. ha_iheada must be written after ha_ihead, since they are acting on the same dom node - // styles that must be added at the end - $this->end_styles = array(); - while($style_rec = $ilDB->fetchAssoc($style_set)) - { - if ($style_rec["tag"] != $ctag || $style_rec["class"] != $cclass - || $style_rec["type"] != $ctype || $style_rec["mq_id"] != $cmq_id) - { - // add current tag array to style array - if(is_array($tag)) - { - if (in_array($ctype, array("ha_iheada", "va_iheada"))) - { - $this->end_styles[] = $tag; - } - else - { - $this->style[] = $tag; - } - } - $tag = array(); - } - $ctag = $style_rec["tag"]; - $cclass = $style_rec["class"]; - $ctype = $style_rec["type"]; - $cmq_id = $style_rec["mq_id"]; - $tag[] = $style_rec; - // added $cmq_id - $this->style_class[$ctype][$cclass][$cmq_id][$style_rec["parameter"]] = $style_rec["value"]; - } - if(is_array($tag)) - { - $this->style[] = $tag; - } - foreach ($this->end_styles as $s) - { - $this->style[] = $s; - } -//var_dump($this->style_class); - $q = "SELECT * FROM style_data WHERE id = ". - $ilDB->quote($this->getId(), "integer"); - $res = $ilDB->query($q); - $sty = $ilDB->fetchAssoc($res); - $this->setUpToDate((boolean) $sty["uptodate"]); - $this->setScope($sty["category"]); - - // get style characteristics records - $this->chars = array(); - $this->chars_by_type = array(); - $q = "SELECT * FROM style_char WHERE style_id = ". - $ilDB->quote($this->getId(), "integer"). - " ORDER BY type ASC, characteristic ASC"; - $par_set = $ilDB->query($q); - while($par_rec = $ilDB->fetchAssoc($par_set)) - { - $this->chars[] = array("type" => $par_rec["type"], "class" => $par_rec["characteristic"], "hide" => $par_rec["hide"]); - $this->chars_by_type[$par_rec["type"]][] = $par_rec["characteristic"]; - if ($par_rec["hide"]) - { - $this->hidden_chars[$par_rec["type"].":".$par_rec["characteristic"]] = true; - } - } -// var_dump($this->style); exit; - } - - /** - * write css file to webspace directory - */ - function writeCSSFile($a_target_file = "", $a_image_dir = "") - { - $style = $this->getStyle(); - - if ($a_target_file == "") - { - $css_file_name = ilUtil::getWebspaceDir()."/css/style_".$this->getId().".css"; - } - else - { - $css_file_name = $a_target_file; - } - $css_file = fopen($css_file_name, "w"); - - $page_background = ""; - - $mqs = array(array("mquery" => "", "id" => 0)); - foreach ($this->getMediaQueries() as $mq) - { - $mqs[] = $mq; - } - - // iterate all media queries - foreach ($mqs as $mq) - { - if ($mq["id"] > 0) - { - fwrite ($css_file, "@media ".$mq["mquery"]." {\n"); - } - reset($style); - foreach ($style as $tag) - { - if ($tag[0]["mq_id"] != $mq["id"]) - { - continue; - } - fwrite ($css_file, $tag[0]["tag"].".ilc_".$tag[0]["type"]."_".$tag[0]["class"]."\n"); -// echo "
                  "; -// var_dump($tag[0]["type"]); - if ($tag[0]["tag"] == "td") - { - fwrite ($css_file, ",th".".ilc_".$tag[0]["type"]."_".$tag[0]["class"]."\n"); - } - if (in_array($tag[0]["tag"], array("h1", "h2", "h3"))) - { - fwrite ($css_file, ",div.ilc_text_block_".$tag[0]["class"]."\n"); - fwrite ($css_file, ",body.ilc_text_block_".$tag[0]["class"]."\n"); - } - if ($tag[0]["type"] == "section") // sections can use a tags, if links are used - { - fwrite ($css_file, ",a.ilc_".$tag[0]["type"]."_".$tag[0]["class"]."\n"); - } - if ($tag[0]["type"] == "text_block") - { - fwrite ($css_file, ",body.ilc_text_block_".$tag[0]["class"]."\n"); - } - fwrite ($css_file, "{\n"); - - // collect table border attributes - $t_border = array(); - - foreach($tag as $par) - { - $cur_par = $par["parameter"]; - $cur_val = $par["value"]; - - // replace named colors - if (is_int(strpos($cur_par, "color")) && substr(trim($cur_val), 0, 1) == "!") - { - $cur_val = $this->getColorCodeForName(substr($cur_val, 1)); - } - - if ($tag[0]["type"] == "table" && is_int(strpos($par["parameter"], "border"))) - { - $t_border[$cur_par] = $cur_val; - } - - if (in_array($cur_par, array("background-image", "list-style-image"))) - { - if (is_int(strpos($cur_val, "/"))) // external - { - $cur_val = "url(".$cur_val.")"; - } - else // internal - { - if ($a_image_dir == "") - { - $cur_val = "url(../sty/sty_".$this->getId()."/images/".$cur_val.")"; - } - else - { - $cur_val = "url(".$a_image_dir."/".$cur_val.")"; - } - } - } - - if ($cur_par == "opacity") - { - $cur_val = ((int) $cur_val) / 100; - } - - fwrite ($css_file, "\t".$cur_par.": ".$cur_val.";\n"); - - // IE6 fix for minimum height - if ($cur_par == "min-height") - { - fwrite ($css_file, "\t"."height".": "."auto !important".";\n"); - fwrite ($css_file, "\t"."height".": ".$cur_val.";\n"); - } - - // opacity fix - if ($cur_par == "opacity") - { - fwrite ($css_file, "\t".'-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity='.($cur_val * 100).')"'.";\n"); - fwrite ($css_file, "\t".'filter: alpha(opacity='.($cur_val * 100).')'.";\n"); - fwrite ($css_file, "\t".'-moz-opacity: '.$cur_val.";\n"); - } - - // transform fix - if ($cur_par == "transform") - { - fwrite ($css_file, "\t".'-webkit-transform: '.$cur_val.";\n"); - fwrite ($css_file, "\t".'-moz-transform: '.$cur_val.";\n"); - fwrite ($css_file, "\t".'-ms-transform: '.$cur_val.";\n"); - } - - // transform-origin fix - if ($cur_par == "transform-origin") - { - fwrite ($css_file, "\t".'-webkit-transform-origin: '.$cur_val.";\n"); - fwrite ($css_file, "\t".'-moz-transform-origin: '.$cur_val.";\n"); - fwrite ($css_file, "\t".'-ms-transform-origin: '.$cur_val.";\n"); - } - - // save page background - if ($tag[0]["tag"] == "div" && $tag[0]["class"] == "Page" - && $cur_par == "background-color") - { - $page_background = $cur_val; - } - } - fwrite ($css_file, "}\n"); - fwrite ($css_file, "\n"); - - // use table border attributes for th td as well - /* if ($tag[0]["type"] == "table") - { - if (count($t_border) > 0) - { - fwrite ($css_file, $tag[0]["tag"].".ilc_".$tag[0]["type"]."_".$tag[0]["class"]." th,". - $tag[0]["tag"].".ilc_".$tag[0]["type"]."_".$tag[0]["class"]." td\n"); - fwrite ($css_file, "{\n"); - foreach ($t_border as $p => $v) - { - // fwrite ($css_file, "\t".$p.": ".$v.";\n"); - } - fwrite ($css_file, "}\n"); - fwrite ($css_file, "\n"); - } - }*/ - } - - if ($page_background != "") - { - fwrite ($css_file, "td.ilc_Page\n"); - fwrite ($css_file, "{\n"); - fwrite ($css_file, "\t"."background-color: ".$page_background.";\n"); - fwrite ($css_file, "}\n"); - } - if ($mq["id"] > 0) - { - fwrite ($css_file, "}\n"); - } - } - fclose($css_file); -// exit; - $this->setUpToDate(true); - $this->_writeUpToDate($this->getId(), true); - } - - /** - * Get effective Style Id - * - * @param integer style id that may be set in object - * @param string object type - */ - static function getEffectiveContentStyleId($a_style_id, $a_type = "") - { - global $DIC; - - $ilSetting = $DIC->settings(); - - // check global fixed content style - $fixed_style = $ilSetting->get("fixed_content_style_id"); - if ($fixed_style > 0) - { - $a_style_id = $fixed_style; - } - - // check global default style - if ($a_style_id <= 0) - { - $a_style_id = $ilSetting->get("default_content_style_id"); - } - - if ($a_style_id > 0 && ilObject::_lookupType($a_style_id) == "sty") - { - return $a_style_id; - } - - return 0; - } - - /** - * Get parameters of class - * - * @param - * @return - */ - function getParametersOfClass($a_type, $a_class, $a_mq_id = 0) - { - if (is_array($this->style_class[$a_type][$a_class][$a_mq_id])) - { - return $this->style_class[$a_type][$a_class][$a_mq_id]; - } - return array(); - } - - /** - * get content style path - * - * static (to avoid full reading) - */ - static function getContentStylePath($a_style_id, $add_random = true) - { - global $DIC; - - $ilSetting = $DIC->settings(); - - $rand = rand(1,999999); - - - // check global fixed content style - $fixed_style = $ilSetting->get("fixed_content_style_id"); - if ($fixed_style > 0) - { - $a_style_id = $fixed_style; - } - - // check global default style - if ($a_style_id <= 0) - { - $a_style_id = $ilSetting->get("default_content_style_id"); - } - - if ($a_style_id > 0 && ilObject::_exists($a_style_id)) - { - // check whether file is up to date - if (!ilObjStyleSheet::_lookupUpToDate($a_style_id)) - { - $style = new ilObjStyleSheet($a_style_id); - $style->writeCSSFile(); - } - - $path = ilUtil::getWebspaceDir("output") . "/css/style_" . $a_style_id . ".css"; - if ($add_random) - { - $path .= "?dummy=$rand"; - } - require_once('./Services/WebAccessChecker/classes/class.ilWACSignedPath.php'); - $path = ilWACSignedPath::signFile($path); - - return $path; - } - else // todo: work this out - { - return "./Services/COPage/css/content.css"; - } - } - - /** - * get content print style - * - * static - */ - static function getContentPrintStyle() - { - return "./Services/COPage/css/print_content.css"; - } - - /** - * get syntax style path - * - * static - */ - static function getSyntaxStylePath() - { - return "./Services/COPage/css/syntaxhighlight.css"; - } - - /** - * get placeholder style path (for Page Layouts) - * - * static - */ - static function getPlaceHolderStylePath() - { - return "./Services/COPage/css/placeholder.css"; - } - - function update() - { - $ilDB = $this->db; - - parent::update(); - $this->read(); // this could be done better - $this->writeCSSFile(); - - $q = "UPDATE style_data ". - "SET category = ".$ilDB->quote((int) $this->getScope(), "integer"). - " WHERE id = ".$ilDB->quote($this->getId(), "integer"); - $ilDB->manipulate($q); - } - - /** - * update style parameter per id - * - * @param int $a_id style parameter id - * @param int $a_id style parameter value - */ - function updateStyleParameter($a_id, $a_value) - { - $ilDB = $this->db; - - $q = "UPDATE style_parameter SET VALUE = ". - $ilDB->quote($a_value, "text")." WHERE id = ". - $ilDB->quote($a_id, "integer"); - $style_set = $ilDB->manipulate($q); - } - - /** - * Set style parameter per tag/class/parameter - * - */ - // todo: search for usages, add mq_id - function replaceStylePar($a_tag, $a_class, $a_par, $a_val, $a_type, $a_mq_id = 0, $a_custom = false) - { - ilObjStyleSheet::_replaceStylePar($this->getId(), $a_tag, $a_class, $a_par, $a_val, $a_type, $a_mq_id, $a_custom); - } - - static function _replaceStylePar($style_id, $a_tag, $a_class, $a_par, $a_val, $a_type, $a_mq_id = 0, $a_custom = false) - { - global $DIC; - - $ilDB = $DIC->database(); - - $q = "SELECT * FROM style_parameter WHERE ". - " style_id = ".$ilDB->quote($style_id, "integer")." AND ". - " tag = ".$ilDB->quote($a_tag, "text")." AND ". - " class = ".$ilDB->quote($a_class, "text")." AND ". - " mq_id = ".$ilDB->quote($a_mq_id, "integer")." AND ". - " custom = ".$ilDB->quote($a_custom, "integer")." AND ". - " ".$ilDB->equals("type", $a_type, "text", true)." AND ". - " parameter = ".$ilDB->quote($a_par, "text"); - - $set = $ilDB->query($q); - - if ($rec = $set->fetchRow()) - { - $q = "UPDATE style_parameter SET ". - " value = ".$ilDB->quote($a_val, "text")." WHERE ". - " style_id = ".$ilDB->quote($style_id, "integer")." AND ". - " tag = ".$ilDB->quote($a_tag, "text")." AND ". - " class = ".$ilDB->quote($a_class, "text")." AND ". - " mq_id = ".$ilDB->quote($a_mq_id, "integer")." AND ". - " custom = ".$ilDB->quote($a_custom, "integer")." AND ". - " ".$ilDB->equals("type", $a_type, "text", true)." AND ". - " parameter = ".$ilDB->quote($a_par, "text"); - - $ilDB->manipulate($q); - } - else - { - $id = $ilDB->nextId("style_parameter"); - $q = "INSERT INTO style_parameter (id, value, style_id, tag, class, type, parameter, mq_id, custom) VALUES ". - " (". - $ilDB->quote($id, "integer").",". - $ilDB->quote($a_val, "text").",". - " ".$ilDB->quote($style_id, "integer").",". - " ".$ilDB->quote($a_tag, "text").",". - " ".$ilDB->quote($a_class, "text").",". - " ".$ilDB->quote($a_type, "text").",". - " ".$ilDB->quote($a_par, "text").",". - " ".$ilDB->quote($a_mq_id, "integer").",". - " ".$ilDB->quote($a_custom, "integer"). - ")"; - - $ilDB->manipulate($q); - } - } - - - /** - * todo: bad style! should return array of objects, not multi-dim-arrays - */ - function getStyle() - { - return $this->style; - } - - /** - * set styles - */ - function setStyle($a_style) - { - $this->style = $a_style; - } - - - /** - * Handle xml strin - * - * @param - * @return - */ - function handleXmlString($a_str) - { - return str_replace("&", "&", $a_str); - } - - /** - * get xml representation of style object - * todo: add mq_id - */ - function getXML() - { - $xml.= "\n"; - - // title and description - $xml.= "".$this->handleXmlString($this->getTitle()).""; - $xml.= "".$this->handleXmlString($this->getDescription())."\n"; - - // style classes - foreach($this->chars as $char) - { - $xml.= "\n"; - } - - // colors - foreach($this->getColors() as $color) - { - $xml.="\n"; - } - - // templates - $tcts = ilObjStyleSheet::_getTemplateClassTypes(); - foreach ($tcts as $tct => $v) - { - $ts = $this->getTemplates($tct); - - foreach ($ts as $t) - { - $xml.="\n"; - foreach ($t["classes"] as $ct => $c) - { - if ($c != "") - { - $xml.="\n"; - } - } - $xml.="\n"; - } - } - - - $xml.= ""; -//echo "
                  ".htmlentities($xml)."
                  "; exit; - return $xml; - } - - - /** - * Create export directory - */ - function createExportDirectory() - { - $sty_data_dir = ilUtil::getDataDir()."/sty"; - ilUtil::makeDir($sty_data_dir); - if(!is_writable($sty_data_dir)) - { - $this->ilias->raiseError("Style data directory (".$sty_data_dir - .") not writeable.",$this->ilias->error_obj->FATAL); - } + $style_dir = $sty_data_dir . "/sty_" . $a_style_id; + ilUtil::makeDir($style_dir); + if (!@is_dir($style_dir)) { + $ilErr->raiseError("Creation of style directory failed (" . + $style_dir . ").", $ilErr->FATAL); + } + + // create images subdirectory + $im_dir = $style_dir . "/images"; + ilUtil::makeDir($im_dir); + if (!@is_dir($im_dir)) { + $ilErr->raiseError("Creation of Import Directory failed (" . + $im_dir . ").", $ilErr->FATAL); + } + + // create thumbnails directory + $thumb_dir = $style_dir . "/images/thumbnails"; + ilUtil::makeDir($thumb_dir); + if (!@is_dir($thumb_dir)) { + $ilErr->raiseError("Creation of Import Directory failed (" . + $thumb_dir . ").", $ilErr->FATAL); + } + } + + /** + * Get images directory + */ + public function getImagesDirectory() + { + return ilObjStyleSheet::_getImagesDirectory($this->getId()); + } + + /** + * Get images directory + */ + public static function _getImagesDirectory($a_style_id) + { + return ilUtil::getWebspaceDir() . "/sty/sty_" . $a_style_id . + "/images"; + } + + /** + * Get thumbnails directory + */ + public function getThumbnailsDirectory() + { + return $this->getImagesDirectory() . + "/thumbnails"; + } + + /** + * Get images of style + */ + public function getImages() + { + $dir = $this->getImagesDirectory(); + $images = array(); + if (is_dir($dir)) { + $entries = ilUtil::getDir($dir); + foreach ($entries as $entry) { + if (substr($entry["entry"], 0, 1) == ".") { + continue; + } + if ($entry["type"] != "dir") { + $images[] = $entry; + } + } + } + + return $images; + } + + /** + * Upload image + */ + public function uploadImage($a_file) + { + $this->createImagesDirectory(); + @ilUtil::moveUploadedFile( + $a_file["tmp_name"], + $a_file["name"], + $this->getImagesDirectory() . "/" . $a_file["name"] + ); + @ilUtil::resizeImage( + $this->getImagesDirectory() . "/" . $a_file["name"], + $this->getThumbnailsDirectory() . "/" . $a_file["name"], + 75, + 75 + ); + } + + /** + * Delete an image + */ + public function deleteImage($a_file) + { + if (is_file($this->getImagesDirectory() . "/" . $a_file)) { + unlink($this->getImagesDirectory() . "/" . $a_file); + } + if (is_file($this->getThumbnailsDirectory() . "/" . $a_file)) { + unlink($this->getThumbnailsDirectory() . "/" . $a_file); + } + } + + /** + * delete style parameter + * + * @param int $a_id style parameter id + */ + public function deleteParameter($a_id) + { + $ilDB = $this->db; + + $q = "DELETE FROM style_parameter WHERE id = " . + $ilDB->quote($a_id, "integer"); + $ilDB->query($q); + } + + /** + * Delete style parameter by tag/class/parameter + * + * @param string $a_tag tag + * @param string $a_class class + * @param string $a_par parameter + * @param string $a_type type + * @param string $a_mq_id media query id + */ + public function deleteStylePar($a_tag, $a_class, $a_par, $a_type, $a_mq_id = 0, $a_custom = false) + { + $ilDB = $this->db; + + $q = "DELETE FROM style_parameter WHERE " . + " style_id = " . $ilDB->quote($this->getId(), "integer") . " AND " . + " tag = " . $ilDB->quote($a_tag, "text") . " AND " . + " class = " . $ilDB->quote($a_class, "text") . " AND " . + " mq_id = " . $ilDB->quote($a_mq_id, "integer") . " AND " . + " custom = " . $ilDB->quote($a_custom, "integer") . " AND " . + " " . $ilDB->equals("type", $a_type, "text", true) . " AND " . + " parameter = " . $ilDB->quote($a_par, "text"); + + $ilDB->manipulate($q); + } + + /** + * Delete style parameter by tag/class/parameter + * + * @param string $a_tag tag + * @param string $a_class class + * @param string $a_par parameter + * @param string $a_type type + * @param string $a_mq_id media query id + */ + public function deleteCustomStylePars($a_tag, $a_class, $a_type, $a_mq_id = 0) + { + $ilDB = $this->db; + + $q = "DELETE FROM style_parameter WHERE " . + " style_id = " . $ilDB->quote($this->getId(), "integer") . " AND " . + " tag = " . $ilDB->quote($a_tag, "text") . " AND " . + " class = " . $ilDB->quote($a_class, "text") . " AND " . + " mq_id = " . $ilDB->quote($a_mq_id, "integer") . " AND " . + " custom = " . $ilDB->quote(1, "integer") . " AND " . + " " . $ilDB->equals("type", $a_type, "text", true); + + $ilDB->manipulate($q); + } + + /** + * Delete style parameters of characteristic + * + * @param string tag + * @param string class + * @param string parameter + * @param string type + */ + public function deleteStyleParOfChar($a_type, $a_class) + { + $ilDB = $this->db; + + $q = "DELETE FROM style_parameter WHERE " . + " style_id = " . $ilDB->quote($this->getId(), "integer") . " AND " . + " class = " . $ilDB->quote($a_class, "text") . " AND " . + " " . $ilDB->equals("type", $a_type, "text", true); + + $ilDB->manipulate($q); + } + + + /** + * delete style object + */ + public function delete() + { + $ilDB = $this->db; + + // delete object + parent::delete(); + + // check whether this style is global default + $def_style = $this->ilias->getSetting("default_content_style_id"); + if ($def_style == $this->getId()) { + $this->ilias->deleteSetting("default_content_style_id"); + } + + // check whether this style is global fixed + $fixed_style = $this->ilias->getSetting("fixed_content_style_id"); + if ($fixed_style == $this->getId()) { + $this->ilias->deleteSetting("fixed_content_style_id"); + } + + // delete style parameter + $q = "DELETE FROM style_parameter WHERE style_id = " . + $ilDB->quote($this->getId(), "integer"); + $ilDB->manipulate($q); + + // delete style file + $css_file_name = ilUtil::getWebspaceDir() . "/css/style_" . $this->getId() . ".css"; + if (is_file($css_file_name)) { + unlink($css_file_name); + } + + // delete media queries + $ilDB->manipulate( + "DELETE FROM sty_media_query WHERE " . + " style_id = " . $ilDB->quote($this->getId(), "integer") + ); + + // delete entries in learning modules + include_once("./Modules/LearningModule/classes/class.ilObjContentObject.php"); + ilObjContentObject::_deleteStyleAssignments($this->getId()); + + // delete style data record + $q = "DELETE FROM style_data WHERE id = " . + $ilDB->quote($this->getId(), "integer"); + $ilDB->manipulate($q); + } + + + /** + * read style properties + */ + public function read() + { + $ilDB = $this->db; + + parent::read(); + + $q = "SELECT * FROM style_parameter WHERE style_id = " . + $ilDB->quote($this->getId(), "integer") . " ORDER BY tag, class, type, mq_id "; + $style_set = $ilDB->query($q); + $ctag = ""; + $cclass = ""; + $ctype = ""; + $cmq_id = 0; + $this->style = array(); + // workaround for bug #17586, see also http://stackoverflow.com/questions/3066356/multiple-css-classes-properties-overlapping-based-on-the-order-defined + // e.g. ha_iheada must be written after ha_ihead, since they are acting on the same dom node + // styles that must be added at the end + $this->end_styles = array(); + while ($style_rec = $ilDB->fetchAssoc($style_set)) { + if ($style_rec["tag"] != $ctag || $style_rec["class"] != $cclass + || $style_rec["type"] != $ctype || $style_rec["mq_id"] != $cmq_id) { + // add current tag array to style array + if (is_array($tag)) { + if (in_array($ctype, array("ha_iheada", "va_iheada"))) { + $this->end_styles[] = $tag; + } else { + $this->style[] = $tag; + } + } + $tag = array(); + } + $ctag = $style_rec["tag"]; + $cclass = $style_rec["class"]; + $ctype = $style_rec["type"]; + $cmq_id = $style_rec["mq_id"]; + $tag[] = $style_rec; + // added $cmq_id + $this->style_class[$ctype][$cclass][$cmq_id][$style_rec["parameter"]] = $style_rec["value"]; + } + if (is_array($tag)) { + $this->style[] = $tag; + } + foreach ($this->end_styles as $s) { + $this->style[] = $s; + } + //var_dump($this->style_class); + $q = "SELECT * FROM style_data WHERE id = " . + $ilDB->quote($this->getId(), "integer"); + $res = $ilDB->query($q); + $sty = $ilDB->fetchAssoc($res); + $this->setUpToDate((boolean) $sty["uptodate"]); + $this->setScope($sty["category"]); + + // get style characteristics records + $this->chars = array(); + $this->chars_by_type = array(); + $q = "SELECT * FROM style_char WHERE style_id = " . + $ilDB->quote($this->getId(), "integer") . + " ORDER BY type ASC, characteristic ASC"; + $par_set = $ilDB->query($q); + while ($par_rec = $ilDB->fetchAssoc($par_set)) { + $this->chars[] = array("type" => $par_rec["type"], "class" => $par_rec["characteristic"], "hide" => $par_rec["hide"]); + $this->chars_by_type[$par_rec["type"]][] = $par_rec["characteristic"]; + if ($par_rec["hide"]) { + $this->hidden_chars[$par_rec["type"] . ":" . $par_rec["characteristic"]] = true; + } + } + // var_dump($this->style); exit; + } + + /** + * write css file to webspace directory + */ + public function writeCSSFile($a_target_file = "", $a_image_dir = "") + { + $style = $this->getStyle(); + + if ($a_target_file == "") { + $css_file_name = ilUtil::getWebspaceDir() . "/css/style_" . $this->getId() . ".css"; + } else { + $css_file_name = $a_target_file; + } + $css_file = fopen($css_file_name, "w"); + + $page_background = ""; + + $mqs = array(array("mquery" => "", "id" => 0)); + foreach ($this->getMediaQueries() as $mq) { + $mqs[] = $mq; + } + + // iterate all media queries + foreach ($mqs as $mq) { + if ($mq["id"] > 0) { + fwrite($css_file, "@media " . $mq["mquery"] . " {\n"); + } + reset($style); + foreach ($style as $tag) { + if ($tag[0]["mq_id"] != $mq["id"]) { + continue; + } + fwrite($css_file, $tag[0]["tag"] . ".ilc_" . $tag[0]["type"] . "_" . $tag[0]["class"] . "\n"); + // echo "
                  "; + // var_dump($tag[0]["type"]); + if ($tag[0]["tag"] == "td") { + fwrite($css_file, ",th" . ".ilc_" . $tag[0]["type"] . "_" . $tag[0]["class"] . "\n"); + } + if (in_array($tag[0]["tag"], array("h1", "h2", "h3"))) { + fwrite($css_file, ",div.ilc_text_block_" . $tag[0]["class"] . "\n"); + fwrite($css_file, ",body.ilc_text_block_" . $tag[0]["class"] . "\n"); + } + if ($tag[0]["type"] == "section") { // sections can use a tags, if links are used + fwrite($css_file, ",a.ilc_" . $tag[0]["type"] . "_" . $tag[0]["class"] . "\n"); + } + if ($tag[0]["type"] == "text_block") { + fwrite($css_file, ",body.ilc_text_block_" . $tag[0]["class"] . "\n"); + } + fwrite($css_file, "{\n"); + + // collect table border attributes + $t_border = array(); + + foreach ($tag as $par) { + $cur_par = $par["parameter"]; + $cur_val = $par["value"]; + + // replace named colors + if (is_int(strpos($cur_par, "color")) && substr(trim($cur_val), 0, 1) == "!") { + $cur_val = $this->getColorCodeForName(substr($cur_val, 1)); + } + + if ($tag[0]["type"] == "table" && is_int(strpos($par["parameter"], "border"))) { + $t_border[$cur_par] = $cur_val; + } + + if (in_array($cur_par, array("background-image", "list-style-image"))) { + if (is_int(strpos($cur_val, "/"))) { // external + $cur_val = "url(" . $cur_val . ")"; + } else { // internal + if ($a_image_dir == "") { + $cur_val = "url(../sty/sty_" . $this->getId() . "/images/" . $cur_val . ")"; + } else { + $cur_val = "url(" . $a_image_dir . "/" . $cur_val . ")"; + } + } + } + + if ($cur_par == "opacity") { + $cur_val = ((int) $cur_val) / 100; + } + + fwrite($css_file, "\t" . $cur_par . ": " . $cur_val . ";\n"); + + // IE6 fix for minimum height + if ($cur_par == "min-height") { + fwrite($css_file, "\t" . "height" . ": " . "auto !important" . ";\n"); + fwrite($css_file, "\t" . "height" . ": " . $cur_val . ";\n"); + } + + // opacity fix + if ($cur_par == "opacity") { + fwrite($css_file, "\t" . '-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=' . ($cur_val * 100) . ')"' . ";\n"); + fwrite($css_file, "\t" . 'filter: alpha(opacity=' . ($cur_val * 100) . ')' . ";\n"); + fwrite($css_file, "\t" . '-moz-opacity: ' . $cur_val . ";\n"); + } + + // transform fix + if ($cur_par == "transform") { + fwrite($css_file, "\t" . '-webkit-transform: ' . $cur_val . ";\n"); + fwrite($css_file, "\t" . '-moz-transform: ' . $cur_val . ";\n"); + fwrite($css_file, "\t" . '-ms-transform: ' . $cur_val . ";\n"); + } + + // transform-origin fix + if ($cur_par == "transform-origin") { + fwrite($css_file, "\t" . '-webkit-transform-origin: ' . $cur_val . ";\n"); + fwrite($css_file, "\t" . '-moz-transform-origin: ' . $cur_val . ";\n"); + fwrite($css_file, "\t" . '-ms-transform-origin: ' . $cur_val . ";\n"); + } + + // save page background + if ($tag[0]["tag"] == "div" && $tag[0]["class"] == "Page" + && $cur_par == "background-color") { + $page_background = $cur_val; + } + } + fwrite($css_file, "}\n"); + fwrite($css_file, "\n"); + + // use table border attributes for th td as well + /* if ($tag[0]["type"] == "table") + { + if (count($t_border) > 0) + { + fwrite ($css_file, $tag[0]["tag"].".ilc_".$tag[0]["type"]."_".$tag[0]["class"]." th,". + $tag[0]["tag"].".ilc_".$tag[0]["type"]."_".$tag[0]["class"]." td\n"); + fwrite ($css_file, "{\n"); + foreach ($t_border as $p => $v) + { + // fwrite ($css_file, "\t".$p.": ".$v.";\n"); + } + fwrite ($css_file, "}\n"); + fwrite ($css_file, "\n"); + } + }*/ + } + + if ($page_background != "") { + fwrite($css_file, "td.ilc_Page\n"); + fwrite($css_file, "{\n"); + fwrite($css_file, "\t" . "background-color: " . $page_background . ";\n"); + fwrite($css_file, "}\n"); + } + if ($mq["id"] > 0) { + fwrite($css_file, "}\n"); + } + } + fclose($css_file); + // exit; + $this->setUpToDate(true); + $this->_writeUpToDate($this->getId(), true); + } + + /** + * Get effective Style Id + * + * @param integer style id that may be set in object + * @param string object type + */ + public static function getEffectiveContentStyleId($a_style_id, $a_type = "") + { + global $DIC; + + $ilSetting = $DIC->settings(); + + // check global fixed content style + $fixed_style = $ilSetting->get("fixed_content_style_id"); + if ($fixed_style > 0) { + $a_style_id = $fixed_style; + } + + // check global default style + if ($a_style_id <= 0) { + $a_style_id = $ilSetting->get("default_content_style_id"); + } + + if ($a_style_id > 0 && ilObject::_lookupType($a_style_id) == "sty") { + return $a_style_id; + } + + return 0; + } + + /** + * Get parameters of class + * + * @param + * @return + */ + public function getParametersOfClass($a_type, $a_class, $a_mq_id = 0) + { + if (is_array($this->style_class[$a_type][$a_class][$a_mq_id])) { + return $this->style_class[$a_type][$a_class][$a_mq_id]; + } + return array(); + } + + /** + * get content style path + * + * static (to avoid full reading) + */ + public static function getContentStylePath($a_style_id, $add_random = true) + { + global $DIC; + + $ilSetting = $DIC->settings(); + + $rand = rand(1, 999999); + + + // check global fixed content style + $fixed_style = $ilSetting->get("fixed_content_style_id"); + if ($fixed_style > 0) { + $a_style_id = $fixed_style; + } + + // check global default style + if ($a_style_id <= 0) { + $a_style_id = $ilSetting->get("default_content_style_id"); + } + + if ($a_style_id > 0 && ilObject::_exists($a_style_id)) { + // check whether file is up to date + if (!ilObjStyleSheet::_lookupUpToDate($a_style_id)) { + $style = new ilObjStyleSheet($a_style_id); + $style->writeCSSFile(); + } + + $path = ilUtil::getWebspaceDir("output") . "/css/style_" . $a_style_id . ".css"; + if ($add_random) { + $path .= "?dummy=$rand"; + } + require_once('./Services/WebAccessChecker/classes/class.ilWACSignedPath.php'); + $path = ilWACSignedPath::signFile($path); + + return $path; + } else { // todo: work this out + return "./Services/COPage/css/content.css"; + } + } + + /** + * get content print style + * + * static + */ + public static function getContentPrintStyle() + { + return "./Services/COPage/css/print_content.css"; + } + + /** + * get syntax style path + * + * static + */ + public static function getSyntaxStylePath() + { + return "./Services/COPage/css/syntaxhighlight.css"; + } + + /** + * get placeholder style path (for Page Layouts) + * + * static + */ + public static function getPlaceHolderStylePath() + { + return "./Services/COPage/css/placeholder.css"; + } + + public function update() + { + $ilDB = $this->db; + + parent::update(); + $this->read(); // this could be done better + $this->writeCSSFile(); + + $q = "UPDATE style_data " . + "SET category = " . $ilDB->quote((int) $this->getScope(), "integer") . + " WHERE id = " . $ilDB->quote($this->getId(), "integer"); + $ilDB->manipulate($q); + } + + /** + * update style parameter per id + * + * @param int $a_id style parameter id + * @param int $a_id style parameter value + */ + public function updateStyleParameter($a_id, $a_value) + { + $ilDB = $this->db; + + $q = "UPDATE style_parameter SET VALUE = " . + $ilDB->quote($a_value, "text") . " WHERE id = " . + $ilDB->quote($a_id, "integer"); + $style_set = $ilDB->manipulate($q); + } + + /** + * Set style parameter per tag/class/parameter + * + */ + // todo: search for usages, add mq_id + public function replaceStylePar($a_tag, $a_class, $a_par, $a_val, $a_type, $a_mq_id = 0, $a_custom = false) + { + ilObjStyleSheet::_replaceStylePar($this->getId(), $a_tag, $a_class, $a_par, $a_val, $a_type, $a_mq_id, $a_custom); + } + + public static function _replaceStylePar($style_id, $a_tag, $a_class, $a_par, $a_val, $a_type, $a_mq_id = 0, $a_custom = false) + { + global $DIC; + + $ilDB = $DIC->database(); + + $q = "SELECT * FROM style_parameter WHERE " . + " style_id = " . $ilDB->quote($style_id, "integer") . " AND " . + " tag = " . $ilDB->quote($a_tag, "text") . " AND " . + " class = " . $ilDB->quote($a_class, "text") . " AND " . + " mq_id = " . $ilDB->quote($a_mq_id, "integer") . " AND " . + " custom = " . $ilDB->quote($a_custom, "integer") . " AND " . + " " . $ilDB->equals("type", $a_type, "text", true) . " AND " . + " parameter = " . $ilDB->quote($a_par, "text"); + + $set = $ilDB->query($q); + + if ($rec = $set->fetchRow()) { + $q = "UPDATE style_parameter SET " . + " value = " . $ilDB->quote($a_val, "text") . " WHERE " . + " style_id = " . $ilDB->quote($style_id, "integer") . " AND " . + " tag = " . $ilDB->quote($a_tag, "text") . " AND " . + " class = " . $ilDB->quote($a_class, "text") . " AND " . + " mq_id = " . $ilDB->quote($a_mq_id, "integer") . " AND " . + " custom = " . $ilDB->quote($a_custom, "integer") . " AND " . + " " . $ilDB->equals("type", $a_type, "text", true) . " AND " . + " parameter = " . $ilDB->quote($a_par, "text"); + + $ilDB->manipulate($q); + } else { + $id = $ilDB->nextId("style_parameter"); + $q = "INSERT INTO style_parameter (id, value, style_id, tag, class, type, parameter, mq_id, custom) VALUES " . + " (" . + $ilDB->quote($id, "integer") . "," . + $ilDB->quote($a_val, "text") . "," . + " " . $ilDB->quote($style_id, "integer") . "," . + " " . $ilDB->quote($a_tag, "text") . "," . + " " . $ilDB->quote($a_class, "text") . "," . + " " . $ilDB->quote($a_type, "text") . "," . + " " . $ilDB->quote($a_par, "text") . "," . + " " . $ilDB->quote($a_mq_id, "integer") . "," . + " " . $ilDB->quote($a_custom, "integer") . + ")"; + + $ilDB->manipulate($q); + } + } + + + /** + * todo: bad style! should return array of objects, not multi-dim-arrays + */ + public function getStyle() + { + return $this->style; + } + + /** + * set styles + */ + public function setStyle($a_style) + { + $this->style = $a_style; + } + + + /** + * Handle xml strin + * + * @param + * @return + */ + public function handleXmlString($a_str) + { + return str_replace("&", "&", $a_str); + } + + /** + * get xml representation of style object + * todo: add mq_id + */ + public function getXML() + { + $xml.= "\n"; + + // title and description + $xml.= "" . $this->handleXmlString($this->getTitle()) . ""; + $xml.= "" . $this->handleXmlString($this->getDescription()) . "\n"; + + // style classes + foreach ($this->chars as $char) { + $xml.= "\n"; + } + + // colors + foreach ($this->getColors() as $color) { + $xml.="\n"; + } + + // templates + $tcts = ilObjStyleSheet::_getTemplateClassTypes(); + foreach ($tcts as $tct => $v) { + $ts = $this->getTemplates($tct); + + foreach ($ts as $t) { + $xml.="\n"; + foreach ($t["classes"] as $ct => $c) { + if ($c != "") { + $xml.="\n"; + } + } + $xml.="\n"; + } + } + + + $xml.= ""; + //echo "
                  ".htmlentities($xml)."
                  "; exit; + return $xml; + } + + + /** + * Create export directory + */ + public function createExportDirectory() + { + $sty_data_dir = ilUtil::getDataDir() . "/sty"; + ilUtil::makeDir($sty_data_dir); + if (!is_writable($sty_data_dir)) { + $this->ilias->raiseError("Style data directory (" . $sty_data_dir + . ") not writeable.", $this->ilias->error_obj->FATAL); + } - $style_dir = $sty_data_dir."/sty_".$this->getId(); - ilUtil::makeDir($style_dir); - if(!@is_dir($style_dir)) - { - $this->ilias->raiseError("Creation of style directory failed (". - $style_dir.").",$this->ilias->error_obj->FATAL); - } - - // create export subdirectory - $ex_dir = $style_dir."/export"; - ilUtil::makeDir($ex_dir); - if(!@is_dir($ex_dir)) - { - $this->ilias->raiseError("Creation of Import Directory failed (". - $ex_dir.").",$this->ilias->error_obj->FATAL); - } - - return $ex_dir; - } - - /** - * Clear export directory - */ - function cleanExportDirectory() - { - $sty_data_dir = ilUtil::getDataDir()."/sty"; - $style_dir = $sty_data_dir."/sty_".$this->getId(); - // create export subdirectory - $ex_dir = $style_dir."/export"; - - if (is_dir($ex_dir)) - { - ilUtil::delDir($ex_dir, true); - } - } - - - /** - * Create export directory - */ - function createExportSubDirectory() - { - $ex_dir = $this->createExportDirectory(); - $ex_sub_dir = $ex_dir."/".$this->getExportSubDir(); - ilUtil::makeDir($ex_sub_dir); - if(!is_writable($ex_sub_dir)) - { - $this->ilias->raiseError("Style data directory (".$ex_sub_dir - .") not writeable.",$this->ilias->error_obj->FATAL); - } - $ex_sub_images_dir = $ex_sub_dir."/images"; - ilUtil::makeDir($ex_sub_images_dir); - if(!is_writable($ex_sub_images_dir)) - { - $this->ilias->raiseError("Style data directory (".$ex_sub_images_dir - .") not writeable.",$this->ilias->error_obj->FATAL); - } - } - - /** - * Set local directory, that will be included within the zip file - */ - function setExportSubDir($a_dir) - { - $this->export_sub_dir = $a_dir; - } - - /** - * The local directory, that will be included within the zip file - */ - function getExportSubDir() - { - if ($this->export_sub_dir == "") - { - return "sty_".$this->getId(); - } - else - { - return $this->export_sub_dir; - } - } - - /** - * Create export file - * - * @return string local file name of export file - */ - function export() - { - $this->cleanExportDirectory(); - $ex_dir = $this->createExportDirectory(); - $this->createExportSubDirectory(); - $this->exportXML($ex_dir."/".$this->getExportSubDir()); -//echo "-".$this->getImagesDirectory()."-".$ex_dir."/".$this->getExportSubDir()."/images"."-"; - ilUtil::rCopy($this->getImagesDirectory(), - $ex_dir."/".$this->getExportSubDir()."/images"); - if (is_file($ex_dir."/".$this->getExportSubDir().".zip")) - { - unlink($ex_dir."/".$this->getExportSubDir().".zip"); - } - ilUtil::zip($ex_dir."/".$this->getExportSubDir(), - $ex_dir."/".$this->getExportSubDir().".zip"); - - return $ex_dir."/".$this->getExportSubDir().".zip"; - } - - /** - * export style xml file to directory - */ - function exportXML($a_dir) - { - $file = $a_dir."/style.xml"; - - // open file - if (!($fp = @fopen($file,"w"))) - { - die ("Error: Could not open \"".$file."\" for writing". - " in ".__FILE__." on line ".__LINE__."
                  "); - } - - // set file permissions - chmod($file, 0770); - - // write xml data into the file - fwrite($fp, $this->getXML()); - - // close file - fclose($fp); - - } - - /** - * Create import directory - */ - function createImportDirectory() - { - $sty_data_dir = ilUtil::getDataDir()."/sty"; - ilUtil::makeDir($sty_data_dir); - if(!is_writable($sty_data_dir)) - { - $this->ilias->raiseError("Style data directory (".$sty_data_dir - .") not writeable.",$this->ilias->error_obj->FATAL); - } + $style_dir = $sty_data_dir . "/sty_" . $this->getId(); + ilUtil::makeDir($style_dir); + if (!@is_dir($style_dir)) { + $this->ilias->raiseError("Creation of style directory failed (" . + $style_dir . ").", $this->ilias->error_obj->FATAL); + } + + // create export subdirectory + $ex_dir = $style_dir . "/export"; + ilUtil::makeDir($ex_dir); + if (!@is_dir($ex_dir)) { + $this->ilias->raiseError("Creation of Import Directory failed (" . + $ex_dir . ").", $this->ilias->error_obj->FATAL); + } + + return $ex_dir; + } + + /** + * Clear export directory + */ + public function cleanExportDirectory() + { + $sty_data_dir = ilUtil::getDataDir() . "/sty"; + $style_dir = $sty_data_dir . "/sty_" . $this->getId(); + // create export subdirectory + $ex_dir = $style_dir . "/export"; + + if (is_dir($ex_dir)) { + ilUtil::delDir($ex_dir, true); + } + } + + + /** + * Create export directory + */ + public function createExportSubDirectory() + { + $ex_dir = $this->createExportDirectory(); + $ex_sub_dir = $ex_dir . "/" . $this->getExportSubDir(); + ilUtil::makeDir($ex_sub_dir); + if (!is_writable($ex_sub_dir)) { + $this->ilias->raiseError("Style data directory (" . $ex_sub_dir + . ") not writeable.", $this->ilias->error_obj->FATAL); + } + $ex_sub_images_dir = $ex_sub_dir . "/images"; + ilUtil::makeDir($ex_sub_images_dir); + if (!is_writable($ex_sub_images_dir)) { + $this->ilias->raiseError("Style data directory (" . $ex_sub_images_dir + . ") not writeable.", $this->ilias->error_obj->FATAL); + } + } + + /** + * Set local directory, that will be included within the zip file + */ + public function setExportSubDir($a_dir) + { + $this->export_sub_dir = $a_dir; + } + + /** + * The local directory, that will be included within the zip file + */ + public function getExportSubDir() + { + if ($this->export_sub_dir == "") { + return "sty_" . $this->getId(); + } else { + return $this->export_sub_dir; + } + } + + /** + * Create export file + * + * @return string local file name of export file + */ + public function export() + { + $this->cleanExportDirectory(); + $ex_dir = $this->createExportDirectory(); + $this->createExportSubDirectory(); + $this->exportXML($ex_dir . "/" . $this->getExportSubDir()); + //echo "-".$this->getImagesDirectory()."-".$ex_dir."/".$this->getExportSubDir()."/images"."-"; + ilUtil::rCopy( + $this->getImagesDirectory(), + $ex_dir . "/" . $this->getExportSubDir() . "/images" + ); + if (is_file($ex_dir . "/" . $this->getExportSubDir() . ".zip")) { + unlink($ex_dir . "/" . $this->getExportSubDir() . ".zip"); + } + ilUtil::zip( + $ex_dir . "/" . $this->getExportSubDir(), + $ex_dir . "/" . $this->getExportSubDir() . ".zip" + ); + + return $ex_dir . "/" . $this->getExportSubDir() . ".zip"; + } + + /** + * export style xml file to directory + */ + public function exportXML($a_dir) + { + $file = $a_dir . "/style.xml"; + + // open file + if (!($fp = @fopen($file, "w"))) { + die("Error: Could not open \"" . $file . "\" for writing" . + " in " . __FILE__ . " on line " . __LINE__ . "
                  "); + } + + // set file permissions + chmod($file, 0770); + + // write xml data into the file + fwrite($fp, $this->getXML()); + + // close file + fclose($fp); + } + + /** + * Create import directory + */ + public function createImportDirectory() + { + $sty_data_dir = ilUtil::getDataDir() . "/sty"; + ilUtil::makeDir($sty_data_dir); + if (!is_writable($sty_data_dir)) { + $this->ilias->raiseError("Style data directory (" . $sty_data_dir + . ") not writeable.", $this->ilias->error_obj->FATAL); + } - $style_dir = $sty_data_dir."/sty_".$this->getId(); - ilUtil::makeDir($style_dir); - if(!@is_dir($style_dir)) - { - $this->ilias->raiseError("Creation of style directory failed (". - $style_dir.").",$this->ilias->error_obj->FATAL); - } - - // create import subdirectory - $im_dir = $style_dir."/import"; - ilUtil::makeDir($im_dir); - if(!@is_dir($im_dir)) - { - $this->ilias->raiseError("Creation of Import Directory failed (". - $im_dir.").",$this->ilias->error_obj->FATAL); - } - - return $im_dir; - } - - /** - * Import - */ - function import($a_file) - { - parent::create(); - - $im_dir = $this->createImportDirectory(); - - // handle uploaded files - if (is_array($a_file)) - { - ilUtil::moveUploadedFile($a_file["tmp_name"], - $a_file["name"], $im_dir."/".$a_file["name"]); - $file_name = $a_file["name"]; - } - else // handle not directly uploaded files - { - $pi = pathinfo($a_file); - $file_name = $pi["basename"]; - copy($a_file, $im_dir."/".$file_name); - } - $file = pathinfo($file_name); - - // unzip file - if (strtolower($file["extension"] == "zip")) - { - ilUtil::unzip($im_dir."/".$file_name); - $subdir = basename($file["basename"],".".$file["extension"]); - if (!is_dir($im_dir."/".$subdir)) - { - $subdir = "style"; // check style subdir - } - $xml_file = $im_dir."/".$subdir."/style.xml"; - } - else // handle xml file directly (old style) - { - $xml_file = $im_dir."/".$file_name; - } - - // load information from xml file -//echo "-$xml_file-"; - $this->createFromXMLFile($xml_file, true); - - // copy images - $this->createImagesDirectory(); - if (is_dir($im_dir."/".$subdir."/images")) - { - ilUtil::rCopy($im_dir."/".$subdir."/images", - $this->getImagesDirectory()); - } - - ilObjStyleSheet::_addMissingStyleClassesToStyle($this->getId()); - $this->read(); - $this->writeCSSFile(); - } - - /** - * create style from xml file - * todo: add mq_id and custom - */ - function createFromXMLFile($a_file, $a_skip_parent_create = false) - { - $ilDB = $this->db; - - $this->is_3_10_skin = false; - - if (!$a_skip_parent_create) - { - parent::create(); - } - include_once("./Services/Style/Content/classes/class.ilStyleImportParser.php"); - $importParser = new ilStyleImportParser($a_file, $this); - $importParser->startParsing(); - - // store style parameter - foreach ($this->style as $style) - { - foreach($style as $tag) - { - $id = $ilDB->nextId("style_parameter"); - - // migrate old table PageFrame/PageContainer to div - if (in_array($tag["class"], array("PageFrame", "PageContainer")) && - $tag["tag"] == "table") - { - $tag["tag"] = "div"; - if ($tag["parameter"] == "width" && $tag["value"] == "100%") - { - continue; - } - } - - $q = "INSERT INTO style_parameter (id,style_id, tag, class, parameter, type, value, custom) VALUES ". - "(". - $ilDB->quote($id, "integer").",". - $ilDB->quote($this->getId(), "integer").",". - $ilDB->quote($tag["tag"], "text").",". - $ilDB->quote($tag["class"], "text").",". - $ilDB->quote($tag["parameter"], "text").",". - $ilDB->quote($tag["type"], "text").",". - $ilDB->quote($tag["value"], "text").",". - $ilDB->quote((bool) $tag["custom"], "integer"). - ")"; - $ilDB->manipulate($q); - } - } - - // store characteristics - $this->is_3_10_skin = true; - if (is_array($this->chars)) - { - foreach ($this->chars as $char) - { - if ($char["type"] != "") - { - $s = substr($char["class"], strlen($char["class"]) - 6); - if ($s != ":hover") - { - $ilDB->replace("style_char", - array( - "style_id" => array("integer", $this->getId()), - "type" => array("text", $char["type"]), - "characteristic" => array("text", $char["class"])), - array("hide" => array("integer", 0)) - ); - /* - $q = "INSERT INTO style_char (style_id, type, characteristic) VALUES ". - "(".$ilDB->quote($this->getId(), "integer").",". - $ilDB->quote($char["type"], "text").",". - $ilDB->quote($char["class"], "text").")"; - $ilDB->manipulate($q);*/ - $this->is_3_10_skin = false; - } - } - } - } - - // add style_data record - $q = "INSERT INTO style_data (id, uptodate) VALUES ". - "(".$ilDB->quote($this->getId(), "integer").", 0)"; - $ilDB->manipulate($q); - - $this->update(); - $this->read(); - - if ($this->is_3_10_skin) - { - $this->do_3_10_Migration(); - } - //$this->writeCSSFile(); - } - - /** - * Get grouped parameter - */ - function getStyleParameterGroups() - { - $groups = array(); - - foreach (self::$parameter as $parameter => $props) - { - $groups[$props["group"]][] = $parameter; - } - return $groups; - } - - static function _getStyleParameterInputType($par) - { - $input = self::$parameter[$par]["input"]; - return $input; - } - - static function _getStyleParameterSubPar($par) - { - $subpar = self::$parameter[$par]["subpar"]; - return $subpar; - } - - static function _getStyleParameters($a_tag = "") - { - if ($a_tag == "") - { - return self::$parameter; - } - $par = array(); - foreach (self::$parameter as $k => $v) - { - if (is_array(self::$filtered_groups[$v["group"]]) && - !in_array($a_tag, self::$filtered_groups[$v["group"]])) - { - continue; - } - $par[$k] = $v; - } - return $par; - } - - static function _getFilteredGroups() - { - return self::$filtered_groups; - } - - static function _getStyleParameterNumericUnits($a_no_percentage = false) - { - if ($a_no_percentage) - { - return self::$num_unit_no_perc; - } - return self::$num_unit; - } - - static function _getStyleParameterValues($par) - { - return self::$parameter[$par]["values"]; - } - - /*static function _getStyleTypes() - { - return self::$style_types; - }*/ - - static function _getStyleSuperTypes() - { - return self::$style_super_types; - } - - static function _isExpandable($a_type) - { - return in_array($a_type, self::$expandable_types); - } - - static function _isHideable($a_type) - { - return in_array($a_type, self::$hideable_types); - } - - static function _getStyleSuperTypeForType($a_type) - { - foreach (self::$style_super_types as $s => $t) - { - if (in_array($a_type, $t)) - { - return $s; - } - if ($a_type == $s) - { - return $s; - } - } - } - - /** - * Get core styles - */ - static function _getCoreStyles() - { - $c_styles = array(); - foreach (self::$core_styles as $cstyle) - { - $c_styles[$cstyle["type"].".".ilObjStyleSheet::_determineTag($cstyle["type"]).".".$cstyle["class"]] - = array("type" => $cstyle["type"], - "tag" => ilObjStyleSheet::_determineTag($cstyle["type"]), - "class" => $cstyle["class"]); - } - return $c_styles; - } - - /** - * Is core style - * - * @param - * @return - */ - static function isCoreStyle($a_type, $a_class) - { - foreach (self::$core_styles as $s) - { - if ($s["type"] == $a_type && $s["class"] == $a_class) - { - return true; - } - } - return false; - } - - - /** - * Get template class types - */ - static function _getTemplateClassTypes($a_template_type = "") - { - if ($a_template_type == "") - { - return self::$templates; - } - - return self::$templates[$a_template_type]; - } - - - static function _getPseudoClasses($tag) - { - return self::$pseudo_classes[$tag]; - } - - function determineTemplateStyleClassType($t, $k) - { - return self::$templates[$t][$k]; - } - - static function _determineTag($a_type) - { - return self::$assigned_tags[$a_type]; - } - - /** - * Get available parameters - */ - static function getAvailableParameters() - { - $pars = array(); - foreach(self::$parameter as $p => $v) - { - $pars[$p] = $v["values"]; - } - - return $pars; - } - - - /** - * Add missing style classes to all styles - */ - static function _addMissingStyleClassesToStyle($a_id) - { - $styles = array(array("id" => $a_id)); - ilObjStyleSheet::_addMissingStyleClassesToAllStyles($styles); - } - - /** - * Add missing style classes to all styles - * todo: add mq_id and custom handling - */ - static function _addMissingStyleClassesToAllStyles($a_styles = "") - { - global $DIC; - - $ilDB = $DIC->database(); - - if ($a_styles == "") - { - $styles = ilObject::_getObjectsDataForType("sty"); - } - else - { - $styles = $a_styles; - } - $core_styles = ilObjStyleSheet::_getCoreStyles(); - $bdom = ilObjStyleSheet::_getBasicStyleDom(); - - // get all core image files - $core_images = array(); - $core_dir = self::$basic_style_image_dir; - if (is_dir($core_dir)) - { - $dir = opendir($core_dir); - while($file = readdir($dir)) - { - if (substr($file, 0, 1) != "." && is_file($core_dir."/".$file)) - { - $core_images[] = $file; - } - } - } - - foreach ($styles as $style) - { - $id = $style["id"]; - - foreach($core_styles as $cs) - { - // check, whether core style class exists - $set = $ilDB->queryF("SELECT * FROM style_char WHERE style_id = %s ". - "AND type = %s AND characteristic = %s", - array("integer", "text", "text"), - array($id, $cs["type"], $cs["class"])); - - // if not, add core style class - if (!($rec = $ilDB->fetchAssoc($set))) - { - $ilDB->manipulateF( - "INSERT INTO style_char (style_id, type, characteristic) ". - " VALUES (%s,%s,%s) ", - array("integer", "text", "text"), - array($id, $cs["type"], $cs["class"])); - - $xpath = new DOMXPath($bdom); - $par_nodes = $xpath->query("/StyleSheet/Style[@Tag = '".$cs["tag"]."' and @Type='". - $cs["type"]."' and @Class='".$cs["class"]."']/StyleParameter"); - foreach ($par_nodes as $par_node) - { - // check whether style parameter exists - $set = $ilDB->queryF("SELECT * FROM style_parameter WHERE style_id = %s ". - "AND type = %s AND class = %s AND tag = %s AND parameter = %s", - array("integer", "text", "text", "text", "text"), - array($id, $cs["type"], $cs["class"], - $cs["tag"], $par_node->getAttribute("Name"))); - - // if not, create style parameter - if (!($rec = $ilDB->fetchAssoc($set))) - { - $spid = $ilDB->nextId("style_parameter"); - $st = $ilDB->manipulateF("INSERT INTO style_parameter (id, style_id, type, class, tag, parameter, value) ". - " VALUES (%s,%s,%s,%s,%s,%s,%s)", - array("integer", "integer", "text", "text", "text", "text", "text"), - array($spid, $id, $cs["type"], $cs["class"], $cs["tag"], - $par_node->getAttribute("Name"), $par_node->getAttribute("Value"))); - } - } - } - } - - // now check, whether some core image files are missing - ilObjStyleSheet::_createImagesDirectory($id); - $imdir = ilObjStyleSheet::_getImagesDirectory($id); - reset($core_images); - foreach($core_images as $cim) - { - if (!is_file($imdir."/".$cim)) - { - copy($core_dir."/".$cim, $imdir."/".$cim); - } - } - } - } - - // - // Color management - // - - /** - * Migrates 3.10 style to 3.11 style - */ - function do_3_10_Migration() - { - $ilDB = $this->db; - - $this->do_3_9_Migration($this->getId()); - - //include_once("./Services/Migration/DBUpdate_1385/classes/class.ilStyleMigration.php"); - //ilStyleMigration::addMissingStyleCharacteristics($this->getId()); - - $this->do_3_10_CharMigration($this->getId()); - - // style_char: type for characteristic - $st = $ilDB->prepareManip("UPDATE style_char SET type = ? WHERE characteristic = ?". - " AND style_id = ? ", array("text", "text", "integer")); - $ilDB->execute($st, array("media_cont", "Media", $this->getId())); - $ilDB->execute($st, array("media_caption", "MediaCaption", $this->getId())); - $ilDB->execute($st, array("page_fn", "Footnote", $this->getId())); - $ilDB->execute($st, array("page_nav", "LMNavigation", $this->getId())); - $ilDB->execute($st, array("page_title", "PageTitle", $this->getId())); - $ilDB->execute($st, array("page_cont", "Page", $this->getId())); - - // style_parameter: type for class - $st = $ilDB->prepareManip("UPDATE style_parameter SET type = ? WHERE class = ?". - " AND style_id = ? ", array("text", "text", "integer")); - $ilDB->execute($st, array("media_cont", "Media", $this->getId())); - $ilDB->execute($st, array("media_caption", "MediaCaption", $this->getId())); - $ilDB->execute($st, array("page_fn", "Footnote", $this->getId())); - $ilDB->execute($st, array("page_nav", "LMNavigation", $this->getId())); - $ilDB->execute($st, array("page_title", "PageTitle", $this->getId())); - $ilDB->execute($st, array("table", "Page", $this->getId())); - - $st = $ilDB->prepareManip("UPDATE style_parameter SET tag = ? WHERE class = ?". - " AND style_id = ? ", array("text", "text", "integer")); - $ilDB->execute($st, array("div", "MediaCaption", $this->getId())); - - // style_char: characteristic for characteristic - $st = $ilDB->prepareManip("UPDATE style_char SET characteristic = ? WHERE characteristic = ?". - " AND style_id = ? ", array("text", "text", "integer")); - $ilDB->execute($st, array("MediaContainer", "Media", $this->getId())); - $ilDB->execute($st, array("PageContainer", "Page", $this->getId())); - - // style_parameter: class for class - $st = $ilDB->prepareManip("UPDATE style_parameter SET class = ? WHERE class = ?". - " AND style_id = ? ", array("text", "text", "integer")); - $ilDB->execute($st, array("MediaContainer", "Media", $this->getId())); - $ilDB->execute($st, array("PageContainer", "Page", $this->getId())); - - // force rewriting of container style - $st = $ilDB->prepareManip("DELETE FROM style_char WHERE type = ?". - " AND style_id = ? ", array("text", "integer")); - $ilDB->execute($st, array("page_cont", $this->getId())); - $st = $ilDB->prepareManip("DELETE FROM style_parameter WHERE type = ?". - " AND style_id = ? ", array("text", "integer")); - $ilDB->execute($st, array("page_cont", $this->getId())); - - } - - /** - * This is more or less a copy of Services/Migration/DBUpdate_1385/classes - * ilStyleMigration->addMissingStyleCharacteristics() - * - * Any changes here may also be interesting there. - */ - function do_3_10_CharMigration($a_id = "") - { - $ilDB = $this->db; - - $add_str = ""; - if ($a_id != "") - { - $add_str = " AND style_id = ".$ilDB->quote($a_id, "integer"); - } - - $set = $ilDB->query($q = "SELECT DISTINCT style_id, tag, class FROM style_parameter WHERE ". - $ilDB->equals("type", "", "text", true)." ".$add_str); - - while ($rec = $ilDB->fetchAssoc($set)) - { - // derive types from tag - $types = array(); - switch ($rec["tag"]) - { - case "div": - case "p": - if (in_array($rec["class"], array("Headline3", "Headline1", - "Headline2", "TableContent", "List", "Standard", "Remark", - "Additional", "Mnemonic", "Citation", "Example"))) - { - $types[] = "text_block"; - } - if (in_array($rec["class"], array("Block", "Remark", - "Additional", "Mnemonic", "Example", "Excursus", "Special"))) - { - $types[] = "section"; - } - if (in_array($rec["class"], array("Page", "Footnote", "PageTitle", "LMNavigation"))) - { - $types[] = "page"; - } - break; - - case "td": - $types[] = "table_cell"; - break; - - case "a": - if (in_array($rec["class"], array("ExtLink", "IntLink", "FootnoteLink"))) - { - $types[] = "link"; - } - break; - - case "span": - $types[] = "text_inline"; - break; - - case "table": - $types[] = "table"; - break; - } - - // check if style_char set exists - foreach ($types as $t) - { - // check if second type already exists - $set4 = $ilDB->queryF("SELECT * FROM style_char ". - " WHERE style_id = %s AND type = %s AND characteristic = %s", - array("integer", "text", "text"), - array($rec["style_id"], $t, $rec["class"])); - if ($rec4 = $ilDB->fetchAssoc($set4)) - { - // ok - } - else - { -//echo "
                  1-".$rec["style_id"]."-".$t."-".$rec["class"]."-"; - $ilDB->manipulateF("INSERT INTO style_char ". - " (style_id, type, characteristic) VALUES ". - " (%s,%s,%s) ", - array("integer", "text", "text"), - array($rec["style_id"], $t, $rec["class"])); - } - } - - // update types - if ($rec["type"] == "") - { - if (count($types) > 0) - { - $ilDB->manipulateF("UPDATE style_parameter SET type = %s ". - " WHERE style_id = %s AND class = %s AND ".$ilDB->equals("type", "", "text", true), - array("text", "integer", "text"), - array($types[0], $rec["style_id"], $rec["class"])); -//echo "
                  3-".$types[0]."-".$rec["style_id"]."-".$rec["class"]."-"; - - // links extra handling - if ($types[0] == "link") - { - $ilDB->manipulateF("UPDATE style_parameter SET type = %s ". - " WHERE style_id = %s AND (class = %s OR class = %s) AND ".$ilDB->equals("type", "", "text", true), - array("text", "integer", "text", "text"), - array($types[0], $rec["style_id"], $rec["class"].":visited", - $rec["class"].":hover")); - } - } - - if (count($types) == 2) - { - // select all records of first type and add second type - // records if necessary. - $set2 = $ilDB->queryF("SELECT * FROM style_parameter ". - " WHERE style_id = %s AND class = %s AND type = %s", - array("integer", "text", "text"), - array($rec["style_id"], $rec["class"], $types[0])); - while ($rec2 = $ilDB->fetchAssoc($set2)) - { - // check if second type already exists - $set3 = $ilDB->queryF("SELECT * FROM style_parameter ". - " WHERE style_id = %s AND tag = %s AND class = %s AND type = %s AND parameter = %s", - array("integer", "text", "text", "text", "text"), - array($rec["style_id"], $rec["tag"], $rec["class"], $types[1], $rec["parameter"])); - if ($rec3 = $ilDB->fetchAssoc($set3)) - { - // ok - } - else - { - $nid = $ilDB->nextId("style_parameter"); - $ilDB->manipulateF("INSERT INTO style_parameter ". - " (id, style_id, tag, class, parameter, value, type) VALUES ". - " (%s, %s,%s,%s,%s,%s,%s) ", - array("integer", "integer", "text", "text", "text", "text", "text"), - array($nid, $rec2["style_id"], $rec2["tag"], $rec2["class"], - $rec2["parameter"], $rec2["value"], $types[1])); - } - } - } - } - } - } - - /** - * Migrate old 3.9 styles - */ - function do_3_9_Migration($a_id) - { - $ilDB = $this->db; - - $classes = array("Example", "Additional", "Citation", "Mnemonic", "Remark"); - $pars = array("margin-top", "margin-bottom"); - - foreach ($classes as $curr_class) - { - foreach ($pars as $curr_par) - { - $res2 = $ilDB->queryF("SELECT id FROM style_parameter WHERE style_id = %s". - " AND tag = %s AND class= %s AND parameter = %s", - array("integer", "text", "text", "text"), - array($a_id, "p", $curr_class, $curr_par)); - if ($row2 = $ilDB->fetchAssoc($res2)) - { - $ilDB->manipulateF("UPDATE style_parameter SET value= %s WHERE id = %s", - array("text", "integer"), - array("10px", $row2["id"])); - } - else - { - $nid = $ilDB->nextId("style_parameter"); - $ilDB->manipulateF("INSERT INTO style_parameter ". - "(id, style_id, tag, class, parameter,value) VALUES (%s,%s,%s,%s,%s,%s)", - array("integer", "integer", "text", "text", "text", "text"), - array($nid, $a_id, "div", $curr_class, $curr_par, "10px")); - } - } - } - - $ilDB->manipulateF("UPDATE style_parameter SET tag = %s WHERE tag = %s and style_id = %s", - array("text", "text", "integer"), - array("div", "p", $a_id)); - - } - - //// - //// Colors - //// - - /** - * Get colors of style - */ - function getColors() - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT * FROM style_color WHERE ". - "style_id = ".$ilDB->quote($this->getId(), "integer")." ". - "ORDER BY color_name"); - - $colors = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $colors[] = array( - "name" => $rec["color_name"], - "code" => $rec["color_code"] - ); - } - - return $colors; - } - - /** - * Add color - */ - function addColor($a_name, $a_code) - { - $ilDB = $this->db; - - $ilDB->manipulate("INSERT INTO style_color (style_id, color_name, color_code)". - " VALUES (". - $ilDB->quote($this->getId(), "integer").",". - $ilDB->quote($a_name, "text").",". - $ilDB->quote($a_code, "text"). - ")"); - } - - /** - * Update color - */ - function updateColor($a_name, $a_new_name, $a_code) - { - $ilDB = $this->db; - - // todo: update names in parameters as well - - $ilDB->manipulate("UPDATE style_color SET ". - "color_name = ".$ilDB->quote($a_new_name, "text").", ". - "color_code = ".$ilDB->quote($a_code, "text"). - " WHERE style_id = ".$ilDB->quote($this->getId(), "integer"). - " AND color_name = ".$ilDB->quote($a_name, "text")); - ilObjStyleSheet::_writeUpToDate($this->getId(), false); - - // rename also the name in the style parameter values - if ($a_name != $a_new_name) - { - $set = $ilDB->query("SELECT * FROM style_parameter ". - " WHERE style_id = ".$ilDB->quote($this->getId(), "integer"). - " AND (". - " parameter = ".$ilDB->quote("background-color", "text"). " OR ". - " parameter = ".$ilDB->quote("color", "text"). " OR ". - " parameter = ".$ilDB->quote("border-color", "text"). " OR ". - " parameter = ".$ilDB->quote("border-top-color", "text"). " OR ". - " parameter = ".$ilDB->quote("border-bottom-color", "text"). " OR ". - " parameter = ".$ilDB->quote("border-left-color", "text"). " OR ". - " parameter = ".$ilDB->quote("border-right-color", "text"). - ")"); - while ($rec = $ilDB->fetchAssoc($set)) - { - if ($rec["value"] == "!".$a_name || - is_int(strpos($rec["value"], "!".$a_name."("))) - { - // parameter is based on color -> rename it - $this->replaceStylePar($rec["tag"], $rec["class"], - $rec["parameter"], str_replace($a_name, $a_new_name, $rec["value"]), $rec["type"], $rec["mq_id"], $rec["custom"]); - } - } - } - } - - /** - * Remove a color - */ - function removeColor($a_name) - { - $ilDB = $this->db; - - $ilDB->manipulate("DELETE FROM style_color WHERE ". - " style_id = ".$ilDB->quote($this->getId(), "integer")." AND ". - " color_name = ".$ilDB->quote($a_name, "text")); - } - - /** - * Check whether color exists - */ - function colorExists($a_color_name) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT * FROM style_color WHERE ". - "style_id = ".$ilDB->quote($this->getId(), "integer")." AND ". - "color_name = ".$ilDB->quote($a_color_name, "text")); - if ($rec = $ilDB->fetchAssoc($set)) - { - return true; - } - return false; - } - - /** - * Remove a color - */ - function getColorCodeForName($a_name) - { - $ilDB = $this->db; - - $pos = strpos($a_name, "("); - if ($pos > 0) - { - $a_i = substr($a_name, $pos + 1); - $a_i = str_replace(")", "", $a_i); - $a_name = substr($a_name, 0, $pos); - } - - $set = $ilDB->query("SELECT color_code FROM style_color WHERE ". - " style_id = ".$ilDB->quote($this->getId(), "integer")." AND ". - " color_name = ".$ilDB->quote($a_name, "text")); - if ($rec = $ilDB->fetchAssoc($set)) - { - if ($a_i == "") - { - return "#".$rec["color_code"]; - } - else - { - return "#".ilObjStyleSheet::_getColorFlavor($rec["color_code"], - (int) $a_i); - } - } - } - - /** - * Get color flavor - */ - static function _getColorFlavor($a_rgb, $a_i) - { - $rgb = ilObjStyleSheet::_explodeRGB($a_rgb, true); - $hls = ilObjStyleSheet::_RGBToHLS($rgb); - - if ($a_i > 0) - { - $hls["l"] = $hls["l"] + ((255 - $hls["l"]) * ($a_i / 100)); - } - if ($a_i < 0) - { - $hls["l"] = $hls["l"] - (($hls["l"]) * (-$a_i / 100)); - } - - $rgb = ilObjStyleSheet::_HLSToRGB($hls); - - foreach ($rgb as $k => $v) - { - $rgb[$k] = str_pad(dechex($v), 2, "0", STR_PAD_LEFT); - } - - return $rgb["r"].$rgb["g"].$rgb["b"]; - } - - /** - * Explode an RGB string into an array - */ - static function _explodeRGB($a_rgb, $as_dec = false) - { - $r["r"] = substr($a_rgb, 0, 2); - $r["g"] = substr($a_rgb, 2, 2); - $r["b"] = substr($a_rgb, 4, 2); - - if ($as_dec) - { - $r["r"] = (int) hexdec($r["r"]); - $r["g"] = (int) hexdec($r["g"]); - $r["b"] = (int) hexdec($r["b"]); - } - - return $r; - } - - /** - * RGB to HLS (both arrays, 0..255) - */ - static function _RGBToHLS($a_rgb) - { - $r = $a_rgb["r"] / 255; - $g = $a_rgb["g"] / 255; - $b = $a_rgb["b"] / 255; - - // max / min - $max = max($r,$g,$b); - $min = min($r,$g,$b); - - //lightness - $l = ($max + $min) / 2; - - if ($max == $min) - { - $s = 0; - $h = 0; - } - else - { - if ($l < 0.5) - { - $s = ($max - $min) / ($max + $min); - } - else - { - $s = ($max - $min) / (2.0 - $max - $min); - } - - if ($r == $max) - { - $h = ($g - $b) / ($max - $min); - } - else if ($g == $max) - { - $h = 2.0 + ($b - $r) / ($max - $min); - } - else if ($b == $max) - { - $h = 4.0 + ($r - $g) / ($max - $min); - } - } - - $hls["h"] = round(($h / 6) * 255); - $hls["l"] = round($l * 255); - $hls["s"] = round($s * 255); - - return $hls; - } - - /** - * HLS to RGB (both arrays, 0..255) - */ - static function _HLSToRGB($a_hls) - { - $h = $a_hls["h"] / 255; - $l = $a_hls["l"] / 255; - $s = $a_hls["s"] / 255; - - $rgb["r"] = $rgb["g"] = $rgb["b"] = 0; - - // If S=0, define R, G, and B all to L - if ($s == 0) - { - $rgb["r"] = $rgb["g"] = $rgb["b"] = $l; - } - else - { - - if ($l < 0.5) - { - $temp2 = $l * (1.0 + $s); - } - else - { - $temp2 = $l + $s - $l * $s; - } - - $temp1 = 2.0 * $l - $temp2; - - - # For each of R, G, B, compute another temporary value, temp3, as follows: - foreach ($rgb as $k => $v) - { - switch ($k) - { - case "r": - $temp3 = $h + 1.0 / 3.0; - break; - - case "g": - $temp3 = $h; - break; - - case "b": - $temp3 = $h - 1.0/3.0; - break; - } - if ($temp3 < 0) - { - $temp3 = $temp3 + 1.0; - } - if ($temp3 > 1) - { - $temp3 = $temp3 - 1.0; - } - - if (6.0 * $temp3 < 1) - { - $rgb[$k] = $temp1 + ($temp2 - $temp1) * 6.0 * $temp3; - } - else if (2.0 * $temp3 < 1) - { - $rgb[$k] = $temp2; - } - else if (3.0 * $temp3 < 2) - { - $rgb[$k] = $temp1 + ($temp2 - $temp1) * ((2.0/3.0) - $temp3) * 6.0; - } - else - { - $rgb[$k] = $temp1; - } - } - } - - $rgb["r"] = round($rgb["r"] * 255); - $rgb["g"] = round($rgb["g"] * 255); - $rgb["b"] = round($rgb["b"] * 255); - - return $rgb; - } - - // - // Media queries - // - - //// - //// Colors - //// - - /** - * Get colors of style - */ - function getMediaQueries() - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT * FROM sty_media_query WHERE ". - "style_id = ".$ilDB->quote($this->getId(), "integer")." ". - "ORDER BY order_nr"); - - $mq = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $mq[] = $rec; - } - - return $mq; - } - - /** - * Add media query - * @param string $a_mquery media query - */ - function addMediaQuery($a_mquery, $order_nr = 0) - { - $ilDB = $this->db; - - $id = $ilDB->nextId("sty_media_query"); - if ($order_nr == 0) - { - $order_nr = $this->getMaxMQueryOrderNr() + 10; - } - - $ilDB->manipulate("INSERT INTO sty_media_query (id, style_id, mquery, order_nr)". - " VALUES (". - $ilDB->quote($id, "integer").",". - $ilDB->quote($this->getId(), "integer").",". - $ilDB->quote($a_mquery, "text").",". - $ilDB->quote($order_nr, "integer"). - ")"); - - return $id; - } - - /** - * Get maximum media query order nr - * - */ - function getMaxMQueryOrderNr() - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT max(order_nr) mnr FROM sty_media_query ". - " WHERE style_id = ".$ilDB->quote($this->getId(), "integer") - ); - $rec = $ilDB->fetchAssoc($set); - - return (int) $rec["mnr"]; - } - - /** - * Update media query - * - * @param int $a_id id - * @param string $a_mquery media query - */ - function updateMediaQuery($a_id, $a_mquery) - { - $ilDB = $this->db; - - $ilDB->manipulate("UPDATE sty_media_query SET ". - " mquery = ".$ilDB->quote($a_mquery, "text"). - " WHERE id = ".$ilDB->quote($a_id, "integer") - ); - } - - /** - * Get media query for id - * - * @param - * @return - */ - function getMediaQueryForId($a_id) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT * FROM sty_media_query ". - " WHERE id = ".$ilDB->quote($a_id, "integer") - ); - return $ilDB->fetchAssoc($set); - } - - /** - * Delete media query - * - * @param int $a_id media query id - */ - function deleteMediaQuery($a_id) - { - $ilDB = $this->db; - - $ilDB->manipulate("DELETE FROM sty_media_query WHERE ". - " style_id = ".$ilDB->quote($this->getId(), "integer"). - " AND id = ".$ilDB->quote($a_id, "integer") - ); - $this->saveMediaQueryOrder(); - } - - /** - * Save media query order - * - * @param int $a_order_nr order nr - */ - function saveMediaQueryOrder($a_order_nr = null) - { - $ilDB = $this->db; - - $mqueries = $this->getMediaQueries(); - if (is_array ($a_order_nr)) - { - foreach ($mqueries as $k => $mq) - { - $mqueries[$k]["order_nr"] = $a_order_nr[$mq["id"]]; - } - $mqueries = ilUtil::sortArray($mqueries, "order_nr", "", true); - } - $cnt = 10; - foreach ($mqueries as $mq) - { - $ilDB->manipulate("UPDATE sty_media_query SET ". - " order_nr = ".$ilDB->quote($cnt, "integer"). - " WHERE id = ".$ilDB->quote($mq["id"], "integer") - ); - $cnt+= 10; - } - } - - - // - // Table template management - // - - /** - * Get table templates of style - */ - function getTemplates($a_type) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT * FROM style_template WHERE ". - "style_id = ".$ilDB->quote($this->getId(), "integer")." AND ". - "temp_type = ".$ilDB->quote($a_type, "text")." ". - "ORDER BY name"); - - $templates = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $rec["classes"] = $this->getTemplateClasses($rec["id"]); - $templates[] = $rec; - } - - return $templates; - } - - /** - * Get template classes - */ - function getTemplateClasses($a_tid) - { - $ilDB = $this->db; - $set = $ilDB->query("SELECT * FROM style_template_class WHERE ". - "template_id = ".$ilDB->quote($a_tid, "integer")); - - $class = array(); - while ($rec = $ilDB->fetchAssoc($set)) - { - $key = $rec["class_type"]; - $class[$key] = $rec["class"]; - } - - return $class; - } - - - /** - * Add table template - */ - function addTemplate($a_type, $a_name, $a_classes) - { - $ilDB = $this->db; - - $tid = $ilDB->nextId("style_template"); - $ilDB->manipulate($q = "INSERT INTO style_template ". - "(id, style_id, name, temp_type)". - " VALUES (". - $ilDB->quote($tid, "integer").",". - $ilDB->quote($this->getId(), "integer").",". - $ilDB->quote($a_name, "text").",". - $ilDB->quote($a_type, "text"). - ")"); - - foreach ($a_classes as $t => $c) - { - $ilDB->manipulate($q = "INSERT INTO style_template_class ". - "(template_id, class_type, class)". - " VALUES (". - $ilDB->quote($tid, "integer").",". - $ilDB->quote($t, "text").",". - $ilDB->quote($c, "text"). - ")"); - } - - include_once("./Services/Style/Content/classes/class.ilObjStyleSheetGUI.php"); - $this->writeTemplatePreview($tid, - ilObjStyleSheetGUI::_getTemplatePreview($this, $a_type, $tid, true)); - - return $tid; - } - - /** - * Update table template - */ - function updateTemplate($a_t_id, $a_name, $a_classes) - { - $ilDB = $this->db; - - $ilDB->manipulate("UPDATE style_template SET ". - "name = ".$ilDB->quote($a_name, "text"). - " WHERE id = ".$ilDB->quote($a_t_id, "integer")); - - $ilDB->manipulate("DELETE FROM style_template_class WHERE ". - "template_id = ".$ilDB->quote($a_t_id, "integer") - ); - foreach ($a_classes as $t => $c) - { - $ilDB->manipulate($q = "INSERT INTO style_template_class ". - "(template_id, class_type, class)". - " VALUES (". - $ilDB->quote($a_t_id, "integer").",". - $ilDB->quote($t, "text").",". - $ilDB->quote($c, "text"). - ")"); - } - - } - - /** - * Update table template - */ - function addTemplateClass($a_t_id, $a_type, $a_class) - { - $ilDB = $this->db; - - $ilDB->manipulate($q = "INSERT INTO style_template_class ". - "(template_id, class_type, class)". - " VALUES (". - $ilDB->quote($a_t_id, "integer").",". - $ilDB->quote($a_type, "text").",". - $ilDB->quote($a_class, "text"). - ")"); - } - - - /** - * Check whether template exists - */ - function templateExists($a_template_name) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT * FROM style_template WHERE ". - "style_id = ".$ilDB->quote($this->getId(), "integer")." AND ". - "name = ".$ilDB->quote($a_template_name, "text")); - if ($rec = $ilDB->fetchAssoc($set)) - { - return true; - } - return false; - } - - /** - * Get template - */ - function getTemplate($a_t_id) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT * FROM style_template WHERE ". - "style_id = ".$ilDB->quote($this->getId(), "integer")." ". - " AND id = ".$ilDB->quote($a_t_id, "integer")); - - if ($rec = $ilDB->fetchAssoc($set)) - { - $rec["classes"] = $this->getTemplateClasses($rec["id"]); - - $template = $rec; - return $template; - } - return array(); - } - - /** - * Lookup table template name for template ID - */ - function lookupTemplateName($a_t_id) - { - return self::_lookupTemplateName($a_t_id); - } - - /** - * Lookup table template name for template ID - */ - static function _lookupTemplateName($a_t_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT name FROM style_template WHERE ". - " id = ".$ilDB->quote($a_t_id, "integer")); - - if ($rec = $ilDB->fetchAssoc($set)) - { - return $rec["name"]; - } - - return false; - } - - /** - * Get table template xml - */ - function getTemplateXML() - { - $ilDB = $this->db; - - $tag = ""; - - $ttypes = array("table", "vaccordion", "haccordion", "carousel"); - - foreach ($ttypes as $ttype) - { - $ts = $this->getTemplates($ttype); - - foreach($ts as $t) - { - $atts = ilObjStyleSheet::_getTemplateClassTypes($ttype); - /*$atts = array("table" => "TableClass", - "caption" => "CaptionClass", - "row_head" => "RowHeadClass", - "row_foot" => "RowFootClass", - "col_head" => "ColHeadClass", - "col_foot" => "ColFootClass", - "odd_row" => "OddRowClass", - "even_row" => "EvenRowClass", - "odd_col" => "OddColClass", - "even_col" => "EvenColClass");*/ - $c = $t["classes"]; - - $tag.= ''; - - foreach ($atts as $type => $t) - { - if ($c[$type] != "") - { - $tag.= ''; - } - } - - $tag.= ""; - } - } - - $tag.= ""; - -//echo htmlentities($tag); - return $tag; - } - - /** - * Write table template preview - */ - function writeTemplatePreview($a_t_id, $a_preview_html) - { - $ilDB = $this->db; - $a_preview_html = str_replace(' width=""', "", $a_preview_html); - $a_preview_html = str_replace(' valign="top"', "", $a_preview_html); - $a_preview_html = str_replace('
                  ', "
                  ", $a_preview_html); -//echo "1-".strlen($a_preview_html)."-"; -//echo htmlentities($a_preview_html); - if (strlen($a_preview_html) > 4000) - { -//echo "2"; - $a_preview_html = ""; - } - $ilDB->manipulate("UPDATE style_template SET ". - "preview = ".$ilDB->quote($a_preview_html, "text"). - " WHERE id = ".$ilDB->quote($a_t_id, "integer")); - } - - /** - * Lookup table template preview - */ - function lookupTemplatePreview($a_t_id) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT preview FROM style_template ". - " WHERE id = ".$ilDB->quote($a_t_id, "integer")); - if ($rec = $ilDB->fetchAssoc($set)) - { - return $rec["preview"]; - } - - return ""; - } - - /** - * Lookup table template preview - */ - static function _lookupTemplateIdByName($a_style_id, $a_name) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT id FROM style_template ". - " WHERE style_id = ".$ilDB->quote($a_style_id, "integer"). - " AND name = ".$ilDB->quote($a_name, "text")); - if ($rec = $ilDB->fetchAssoc($set)) - { - return $rec["id"]; - } - - return false; - } - - /** - * Remove table template - */ - function removeTemplate($a_t_id) - { - $ilDB = $this->db; - - $ilDB->manipulate("DELETE FROM style_template WHERE ". - " style_id = ".$ilDB->quote($this->getId(), "integer")." AND ". - " id = ".$ilDB->quote($a_t_id, "integer")); - - $ilDB->manipulate("DELETE FROM style_template_class WHERE ". - "template_id = ".$ilDB->quote($a_t_id, "integer") - ); - - } - - /** - * Write Style Setting - */ - function writeStyleSetting($a_name, $a_value) - { - $ilDB = $this->db; - - $ilDB->manipulate("DELETE FROM style_setting WHERE ". - " style_id = ".$ilDB->quote($this->getId(), "integer"). - " AND name = ".$ilDB->quote($a_name, "text") - ); - - $ilDB->manipulate("INSERT INTO style_setting ". - "(style_id, name, value) VALUES (". - $ilDB->quote($this->getId(), "integer").",". - $ilDB->quote($a_name, "text").",". - $ilDB->quote($a_value, "text"). - ")"); - } - - /** - * Lookup style setting - */ - function lookupStyleSetting($a_name) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT value FROM style_setting ". - " WHERE style_id = ".$ilDB->quote($this->getId(), "integer"). - " AND name = ".$ilDB->quote($a_name, "text") - ); - $rec = $ilDB->fetchAssoc($set); - - return $rec["value"]; - } - - /** - * Write style usage - */ - static function writeStyleUsage($a_obj_id, $a_style_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $ilDB->replace("style_usage", array( - "obj_id" => array("integer", (int) $a_obj_id)), - array( - "style_id" => array("integer", (int) $a_style_id)) - ); - } - - /** - * Lookup object style - */ - static function lookupObjectStyle($a_obj_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT style_id FROM style_usage ". - " WHERE obj_id = ".$ilDB->quote($a_obj_id, "integer") - ); - $rec = $ilDB->fetchAssoc($set); - - if (ilObject::_lookupType($rec["style_id"]) == "sty") - { - return (int) $rec["style_id"]; - } - - return 0; - } - - /** - * Lookup object style - */ - static function lookupObjectForStyle($a_style_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $obj_ids = array(); - if (ilObject::_lookupType($a_style_id) == "sty") - { - $set = $ilDB->query("SELECT DISTINCT obj_id FROM style_usage " . - " WHERE style_id = " . $ilDB->quote($a_style_id, "integer") - ); - - while ($rec = $ilDB->fetchAssoc($set)) - { - $obj_ids[] = $rec["obj_id"]; - } - } - return $obj_ids; - } - - + $style_dir = $sty_data_dir . "/sty_" . $this->getId(); + ilUtil::makeDir($style_dir); + if (!@is_dir($style_dir)) { + $this->ilias->raiseError("Creation of style directory failed (" . + $style_dir . ").", $this->ilias->error_obj->FATAL); + } + + // create import subdirectory + $im_dir = $style_dir . "/import"; + ilUtil::makeDir($im_dir); + if (!@is_dir($im_dir)) { + $this->ilias->raiseError("Creation of Import Directory failed (" . + $im_dir . ").", $this->ilias->error_obj->FATAL); + } + + return $im_dir; + } + + /** + * Import + */ + public function import($a_file) + { + parent::create(); + + $im_dir = $this->createImportDirectory(); + + // handle uploaded files + if (is_array($a_file)) { + ilUtil::moveUploadedFile( + $a_file["tmp_name"], + $a_file["name"], + $im_dir . "/" . $a_file["name"] + ); + $file_name = $a_file["name"]; + } else { // handle not directly uploaded files + $pi = pathinfo($a_file); + $file_name = $pi["basename"]; + copy($a_file, $im_dir . "/" . $file_name); + } + $file = pathinfo($file_name); + + // unzip file + if (strtolower($file["extension"] == "zip")) { + ilUtil::unzip($im_dir . "/" . $file_name); + $subdir = basename($file["basename"], "." . $file["extension"]); + if (!is_dir($im_dir . "/" . $subdir)) { + $subdir = "style"; // check style subdir + } + $xml_file = $im_dir . "/" . $subdir . "/style.xml"; + } else { // handle xml file directly (old style) + $xml_file = $im_dir . "/" . $file_name; + } + + // load information from xml file + //echo "-$xml_file-"; + $this->createFromXMLFile($xml_file, true); + + // copy images + $this->createImagesDirectory(); + if (is_dir($im_dir . "/" . $subdir . "/images")) { + ilUtil::rCopy( + $im_dir . "/" . $subdir . "/images", + $this->getImagesDirectory() + ); + } + + ilObjStyleSheet::_addMissingStyleClassesToStyle($this->getId()); + $this->read(); + $this->writeCSSFile(); + } + + /** + * create style from xml file + * todo: add mq_id and custom + */ + public function createFromXMLFile($a_file, $a_skip_parent_create = false) + { + $ilDB = $this->db; + + $this->is_3_10_skin = false; + + if (!$a_skip_parent_create) { + parent::create(); + } + include_once("./Services/Style/Content/classes/class.ilStyleImportParser.php"); + $importParser = new ilStyleImportParser($a_file, $this); + $importParser->startParsing(); + + // store style parameter + foreach ($this->style as $style) { + foreach ($style as $tag) { + $id = $ilDB->nextId("style_parameter"); + + // migrate old table PageFrame/PageContainer to div + if (in_array($tag["class"], array("PageFrame", "PageContainer")) && + $tag["tag"] == "table") { + $tag["tag"] = "div"; + if ($tag["parameter"] == "width" && $tag["value"] == "100%") { + continue; + } + } + + $q = "INSERT INTO style_parameter (id,style_id, tag, class, parameter, type, value, custom) VALUES " . + "(" . + $ilDB->quote($id, "integer") . "," . + $ilDB->quote($this->getId(), "integer") . "," . + $ilDB->quote($tag["tag"], "text") . "," . + $ilDB->quote($tag["class"], "text") . "," . + $ilDB->quote($tag["parameter"], "text") . "," . + $ilDB->quote($tag["type"], "text") . "," . + $ilDB->quote($tag["value"], "text") . "," . + $ilDB->quote((bool) $tag["custom"], "integer") . + ")"; + $ilDB->manipulate($q); + } + } + + // store characteristics + $this->is_3_10_skin = true; + if (is_array($this->chars)) { + foreach ($this->chars as $char) { + if ($char["type"] != "") { + $s = substr($char["class"], strlen($char["class"]) - 6); + if ($s != ":hover") { + $ilDB->replace( + "style_char", + array( + "style_id" => array("integer", $this->getId()), + "type" => array("text", $char["type"]), + "characteristic" => array("text", $char["class"])), + array("hide" => array("integer", 0)) + ); + /* + $q = "INSERT INTO style_char (style_id, type, characteristic) VALUES ". + "(".$ilDB->quote($this->getId(), "integer").",". + $ilDB->quote($char["type"], "text").",". + $ilDB->quote($char["class"], "text").")"; + $ilDB->manipulate($q);*/ + $this->is_3_10_skin = false; + } + } + } + } + + // add style_data record + $q = "INSERT INTO style_data (id, uptodate) VALUES " . + "(" . $ilDB->quote($this->getId(), "integer") . ", 0)"; + $ilDB->manipulate($q); + + $this->update(); + $this->read(); + + if ($this->is_3_10_skin) { + $this->do_3_10_Migration(); + } + //$this->writeCSSFile(); + } + + /** + * Get grouped parameter + */ + public function getStyleParameterGroups() + { + $groups = array(); + + foreach (self::$parameter as $parameter => $props) { + $groups[$props["group"]][] = $parameter; + } + return $groups; + } + + public static function _getStyleParameterInputType($par) + { + $input = self::$parameter[$par]["input"]; + return $input; + } + + public static function _getStyleParameterSubPar($par) + { + $subpar = self::$parameter[$par]["subpar"]; + return $subpar; + } + + public static function _getStyleParameters($a_tag = "") + { + if ($a_tag == "") { + return self::$parameter; + } + $par = array(); + foreach (self::$parameter as $k => $v) { + if (is_array(self::$filtered_groups[$v["group"]]) && + !in_array($a_tag, self::$filtered_groups[$v["group"]])) { + continue; + } + $par[$k] = $v; + } + return $par; + } + + public static function _getFilteredGroups() + { + return self::$filtered_groups; + } + + public static function _getStyleParameterNumericUnits($a_no_percentage = false) + { + if ($a_no_percentage) { + return self::$num_unit_no_perc; + } + return self::$num_unit; + } + + public static function _getStyleParameterValues($par) + { + return self::$parameter[$par]["values"]; + } + + /*static function _getStyleTypes() + { + return self::$style_types; + }*/ + + public static function _getStyleSuperTypes() + { + return self::$style_super_types; + } + + public static function _isExpandable($a_type) + { + return in_array($a_type, self::$expandable_types); + } + + public static function _isHideable($a_type) + { + return in_array($a_type, self::$hideable_types); + } + + public static function _getStyleSuperTypeForType($a_type) + { + foreach (self::$style_super_types as $s => $t) { + if (in_array($a_type, $t)) { + return $s; + } + if ($a_type == $s) { + return $s; + } + } + } + + /** + * Get core styles + */ + public static function _getCoreStyles() + { + $c_styles = array(); + foreach (self::$core_styles as $cstyle) { + $c_styles[$cstyle["type"] . "." . ilObjStyleSheet::_determineTag($cstyle["type"]) . "." . $cstyle["class"]] + = array("type" => $cstyle["type"], + "tag" => ilObjStyleSheet::_determineTag($cstyle["type"]), + "class" => $cstyle["class"]); + } + return $c_styles; + } + + /** + * Is core style + * + * @param + * @return + */ + public static function isCoreStyle($a_type, $a_class) + { + foreach (self::$core_styles as $s) { + if ($s["type"] == $a_type && $s["class"] == $a_class) { + return true; + } + } + return false; + } + + + /** + * Get template class types + */ + public static function _getTemplateClassTypes($a_template_type = "") + { + if ($a_template_type == "") { + return self::$templates; + } + + return self::$templates[$a_template_type]; + } + + + public static function _getPseudoClasses($tag) + { + return self::$pseudo_classes[$tag]; + } + + public function determineTemplateStyleClassType($t, $k) + { + return self::$templates[$t][$k]; + } + + public static function _determineTag($a_type) + { + return self::$assigned_tags[$a_type]; + } + + /** + * Get available parameters + */ + public static function getAvailableParameters() + { + $pars = array(); + foreach (self::$parameter as $p => $v) { + $pars[$p] = $v["values"]; + } + + return $pars; + } + + + /** + * Add missing style classes to all styles + */ + public static function _addMissingStyleClassesToStyle($a_id) + { + $styles = array(array("id" => $a_id)); + ilObjStyleSheet::_addMissingStyleClassesToAllStyles($styles); + } + + /** + * Add missing style classes to all styles + * todo: add mq_id and custom handling + */ + public static function _addMissingStyleClassesToAllStyles($a_styles = "") + { + global $DIC; + + $ilDB = $DIC->database(); + + if ($a_styles == "") { + $styles = ilObject::_getObjectsDataForType("sty"); + } else { + $styles = $a_styles; + } + $core_styles = ilObjStyleSheet::_getCoreStyles(); + $bdom = ilObjStyleSheet::_getBasicStyleDom(); + + // get all core image files + $core_images = array(); + $core_dir = self::$basic_style_image_dir; + if (is_dir($core_dir)) { + $dir = opendir($core_dir); + while ($file = readdir($dir)) { + if (substr($file, 0, 1) != "." && is_file($core_dir . "/" . $file)) { + $core_images[] = $file; + } + } + } + + foreach ($styles as $style) { + $id = $style["id"]; + + foreach ($core_styles as $cs) { + // check, whether core style class exists + $set = $ilDB->queryF( + "SELECT * FROM style_char WHERE style_id = %s " . + "AND type = %s AND characteristic = %s", + array("integer", "text", "text"), + array($id, $cs["type"], $cs["class"]) + ); + + // if not, add core style class + if (!($rec = $ilDB->fetchAssoc($set))) { + $ilDB->manipulateF( + "INSERT INTO style_char (style_id, type, characteristic) " . + " VALUES (%s,%s,%s) ", + array("integer", "text", "text"), + array($id, $cs["type"], $cs["class"]) + ); + + $xpath = new DOMXPath($bdom); + $par_nodes = $xpath->query("/StyleSheet/Style[@Tag = '" . $cs["tag"] . "' and @Type='" . + $cs["type"] . "' and @Class='" . $cs["class"] . "']/StyleParameter"); + foreach ($par_nodes as $par_node) { + // check whether style parameter exists + $set = $ilDB->queryF( + "SELECT * FROM style_parameter WHERE style_id = %s " . + "AND type = %s AND class = %s AND tag = %s AND parameter = %s", + array("integer", "text", "text", "text", "text"), + array($id, $cs["type"], $cs["class"], + $cs["tag"], $par_node->getAttribute("Name")) + ); + + // if not, create style parameter + if (!($rec = $ilDB->fetchAssoc($set))) { + $spid = $ilDB->nextId("style_parameter"); + $st = $ilDB->manipulateF( + "INSERT INTO style_parameter (id, style_id, type, class, tag, parameter, value) " . + " VALUES (%s,%s,%s,%s,%s,%s,%s)", + array("integer", "integer", "text", "text", "text", "text", "text"), + array($spid, $id, $cs["type"], $cs["class"], $cs["tag"], + $par_node->getAttribute("Name"), $par_node->getAttribute("Value")) + ); + } + } + } + } + + // now check, whether some core image files are missing + ilObjStyleSheet::_createImagesDirectory($id); + $imdir = ilObjStyleSheet::_getImagesDirectory($id); + reset($core_images); + foreach ($core_images as $cim) { + if (!is_file($imdir . "/" . $cim)) { + copy($core_dir . "/" . $cim, $imdir . "/" . $cim); + } + } + } + } + + // + // Color management + // + + /** + * Migrates 3.10 style to 3.11 style + */ + public function do_3_10_Migration() + { + $ilDB = $this->db; + + $this->do_3_9_Migration($this->getId()); + + //include_once("./Services/Migration/DBUpdate_1385/classes/class.ilStyleMigration.php"); + //ilStyleMigration::addMissingStyleCharacteristics($this->getId()); + + $this->do_3_10_CharMigration($this->getId()); + + // style_char: type for characteristic + $st = $ilDB->prepareManip("UPDATE style_char SET type = ? WHERE characteristic = ?" . + " AND style_id = ? ", array("text", "text", "integer")); + $ilDB->execute($st, array("media_cont", "Media", $this->getId())); + $ilDB->execute($st, array("media_caption", "MediaCaption", $this->getId())); + $ilDB->execute($st, array("page_fn", "Footnote", $this->getId())); + $ilDB->execute($st, array("page_nav", "LMNavigation", $this->getId())); + $ilDB->execute($st, array("page_title", "PageTitle", $this->getId())); + $ilDB->execute($st, array("page_cont", "Page", $this->getId())); + + // style_parameter: type for class + $st = $ilDB->prepareManip("UPDATE style_parameter SET type = ? WHERE class = ?" . + " AND style_id = ? ", array("text", "text", "integer")); + $ilDB->execute($st, array("media_cont", "Media", $this->getId())); + $ilDB->execute($st, array("media_caption", "MediaCaption", $this->getId())); + $ilDB->execute($st, array("page_fn", "Footnote", $this->getId())); + $ilDB->execute($st, array("page_nav", "LMNavigation", $this->getId())); + $ilDB->execute($st, array("page_title", "PageTitle", $this->getId())); + $ilDB->execute($st, array("table", "Page", $this->getId())); + + $st = $ilDB->prepareManip("UPDATE style_parameter SET tag = ? WHERE class = ?" . + " AND style_id = ? ", array("text", "text", "integer")); + $ilDB->execute($st, array("div", "MediaCaption", $this->getId())); + + // style_char: characteristic for characteristic + $st = $ilDB->prepareManip("UPDATE style_char SET characteristic = ? WHERE characteristic = ?" . + " AND style_id = ? ", array("text", "text", "integer")); + $ilDB->execute($st, array("MediaContainer", "Media", $this->getId())); + $ilDB->execute($st, array("PageContainer", "Page", $this->getId())); + + // style_parameter: class for class + $st = $ilDB->prepareManip("UPDATE style_parameter SET class = ? WHERE class = ?" . + " AND style_id = ? ", array("text", "text", "integer")); + $ilDB->execute($st, array("MediaContainer", "Media", $this->getId())); + $ilDB->execute($st, array("PageContainer", "Page", $this->getId())); + + // force rewriting of container style + $st = $ilDB->prepareManip("DELETE FROM style_char WHERE type = ?" . + " AND style_id = ? ", array("text", "integer")); + $ilDB->execute($st, array("page_cont", $this->getId())); + $st = $ilDB->prepareManip("DELETE FROM style_parameter WHERE type = ?" . + " AND style_id = ? ", array("text", "integer")); + $ilDB->execute($st, array("page_cont", $this->getId())); + } + + /** + * This is more or less a copy of Services/Migration/DBUpdate_1385/classes + * ilStyleMigration->addMissingStyleCharacteristics() + * + * Any changes here may also be interesting there. + */ + public function do_3_10_CharMigration($a_id = "") + { + $ilDB = $this->db; + + $add_str = ""; + if ($a_id != "") { + $add_str = " AND style_id = " . $ilDB->quote($a_id, "integer"); + } + + $set = $ilDB->query($q = "SELECT DISTINCT style_id, tag, class FROM style_parameter WHERE " . + $ilDB->equals("type", "", "text", true) . " " . $add_str); + + while ($rec = $ilDB->fetchAssoc($set)) { + // derive types from tag + $types = array(); + switch ($rec["tag"]) { + case "div": + case "p": + if (in_array($rec["class"], array("Headline3", "Headline1", + "Headline2", "TableContent", "List", "Standard", "Remark", + "Additional", "Mnemonic", "Citation", "Example"))) { + $types[] = "text_block"; + } + if (in_array($rec["class"], array("Block", "Remark", + "Additional", "Mnemonic", "Example", "Excursus", "Special"))) { + $types[] = "section"; + } + if (in_array($rec["class"], array("Page", "Footnote", "PageTitle", "LMNavigation"))) { + $types[] = "page"; + } + break; + + case "td": + $types[] = "table_cell"; + break; + + case "a": + if (in_array($rec["class"], array("ExtLink", "IntLink", "FootnoteLink"))) { + $types[] = "link"; + } + break; + + case "span": + $types[] = "text_inline"; + break; + + case "table": + $types[] = "table"; + break; + } + + // check if style_char set exists + foreach ($types as $t) { + // check if second type already exists + $set4 = $ilDB->queryF( + "SELECT * FROM style_char " . + " WHERE style_id = %s AND type = %s AND characteristic = %s", + array("integer", "text", "text"), + array($rec["style_id"], $t, $rec["class"]) + ); + if ($rec4 = $ilDB->fetchAssoc($set4)) { + // ok + } else { + //echo "
                  1-".$rec["style_id"]."-".$t."-".$rec["class"]."-"; + $ilDB->manipulateF( + "INSERT INTO style_char " . + " (style_id, type, characteristic) VALUES " . + " (%s,%s,%s) ", + array("integer", "text", "text"), + array($rec["style_id"], $t, $rec["class"]) + ); + } + } + + // update types + if ($rec["type"] == "") { + if (count($types) > 0) { + $ilDB->manipulateF( + "UPDATE style_parameter SET type = %s " . + " WHERE style_id = %s AND class = %s AND " . $ilDB->equals("type", "", "text", true), + array("text", "integer", "text"), + array($types[0], $rec["style_id"], $rec["class"]) + ); + //echo "
                  3-".$types[0]."-".$rec["style_id"]."-".$rec["class"]."-"; + + // links extra handling + if ($types[0] == "link") { + $ilDB->manipulateF( + "UPDATE style_parameter SET type = %s " . + " WHERE style_id = %s AND (class = %s OR class = %s) AND " . $ilDB->equals("type", "", "text", true), + array("text", "integer", "text", "text"), + array($types[0], $rec["style_id"], $rec["class"] . ":visited", + $rec["class"] . ":hover") + ); + } + } + + if (count($types) == 2) { + // select all records of first type and add second type + // records if necessary. + $set2 = $ilDB->queryF( + "SELECT * FROM style_parameter " . + " WHERE style_id = %s AND class = %s AND type = %s", + array("integer", "text", "text"), + array($rec["style_id"], $rec["class"], $types[0]) + ); + while ($rec2 = $ilDB->fetchAssoc($set2)) { + // check if second type already exists + $set3 = $ilDB->queryF( + "SELECT * FROM style_parameter " . + " WHERE style_id = %s AND tag = %s AND class = %s AND type = %s AND parameter = %s", + array("integer", "text", "text", "text", "text"), + array($rec["style_id"], $rec["tag"], $rec["class"], $types[1], $rec["parameter"]) + ); + if ($rec3 = $ilDB->fetchAssoc($set3)) { + // ok + } else { + $nid = $ilDB->nextId("style_parameter"); + $ilDB->manipulateF( + "INSERT INTO style_parameter " . + " (id, style_id, tag, class, parameter, value, type) VALUES " . + " (%s, %s,%s,%s,%s,%s,%s) ", + array("integer", "integer", "text", "text", "text", "text", "text"), + array($nid, $rec2["style_id"], $rec2["tag"], $rec2["class"], + $rec2["parameter"], $rec2["value"], $types[1]) + ); + } + } + } + } + } + } + + /** + * Migrate old 3.9 styles + */ + public function do_3_9_Migration($a_id) + { + $ilDB = $this->db; + + $classes = array("Example", "Additional", "Citation", "Mnemonic", "Remark"); + $pars = array("margin-top", "margin-bottom"); + + foreach ($classes as $curr_class) { + foreach ($pars as $curr_par) { + $res2 = $ilDB->queryF( + "SELECT id FROM style_parameter WHERE style_id = %s" . + " AND tag = %s AND class= %s AND parameter = %s", + array("integer", "text", "text", "text"), + array($a_id, "p", $curr_class, $curr_par) + ); + if ($row2 = $ilDB->fetchAssoc($res2)) { + $ilDB->manipulateF( + "UPDATE style_parameter SET value= %s WHERE id = %s", + array("text", "integer"), + array("10px", $row2["id"]) + ); + } else { + $nid = $ilDB->nextId("style_parameter"); + $ilDB->manipulateF( + "INSERT INTO style_parameter " . + "(id, style_id, tag, class, parameter,value) VALUES (%s,%s,%s,%s,%s,%s)", + array("integer", "integer", "text", "text", "text", "text"), + array($nid, $a_id, "div", $curr_class, $curr_par, "10px") + ); + } + } + } + + $ilDB->manipulateF( + "UPDATE style_parameter SET tag = %s WHERE tag = %s and style_id = %s", + array("text", "text", "integer"), + array("div", "p", $a_id) + ); + } + + //// + //// Colors + //// + + /** + * Get colors of style + */ + public function getColors() + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT * FROM style_color WHERE " . + "style_id = " . $ilDB->quote($this->getId(), "integer") . " " . + "ORDER BY color_name"); + + $colors = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $colors[] = array( + "name" => $rec["color_name"], + "code" => $rec["color_code"] + ); + } + + return $colors; + } + + /** + * Add color + */ + public function addColor($a_name, $a_code) + { + $ilDB = $this->db; + + $ilDB->manipulate("INSERT INTO style_color (style_id, color_name, color_code)" . + " VALUES (" . + $ilDB->quote($this->getId(), "integer") . "," . + $ilDB->quote($a_name, "text") . "," . + $ilDB->quote($a_code, "text") . + ")"); + } + + /** + * Update color + */ + public function updateColor($a_name, $a_new_name, $a_code) + { + $ilDB = $this->db; + + // todo: update names in parameters as well + + $ilDB->manipulate("UPDATE style_color SET " . + "color_name = " . $ilDB->quote($a_new_name, "text") . ", " . + "color_code = " . $ilDB->quote($a_code, "text") . + " WHERE style_id = " . $ilDB->quote($this->getId(), "integer") . + " AND color_name = " . $ilDB->quote($a_name, "text")); + ilObjStyleSheet::_writeUpToDate($this->getId(), false); + + // rename also the name in the style parameter values + if ($a_name != $a_new_name) { + $set = $ilDB->query("SELECT * FROM style_parameter " . + " WHERE style_id = " . $ilDB->quote($this->getId(), "integer") . + " AND (" . + " parameter = " . $ilDB->quote("background-color", "text") . " OR " . + " parameter = " . $ilDB->quote("color", "text") . " OR " . + " parameter = " . $ilDB->quote("border-color", "text") . " OR " . + " parameter = " . $ilDB->quote("border-top-color", "text") . " OR " . + " parameter = " . $ilDB->quote("border-bottom-color", "text") . " OR " . + " parameter = " . $ilDB->quote("border-left-color", "text") . " OR " . + " parameter = " . $ilDB->quote("border-right-color", "text") . + ")"); + while ($rec = $ilDB->fetchAssoc($set)) { + if ($rec["value"] == "!" . $a_name || + is_int(strpos($rec["value"], "!" . $a_name . "("))) { + // parameter is based on color -> rename it + $this->replaceStylePar( + $rec["tag"], + $rec["class"], + $rec["parameter"], + str_replace($a_name, $a_new_name, $rec["value"]), + $rec["type"], + $rec["mq_id"], + $rec["custom"] + ); + } + } + } + } + + /** + * Remove a color + */ + public function removeColor($a_name) + { + $ilDB = $this->db; + + $ilDB->manipulate("DELETE FROM style_color WHERE " . + " style_id = " . $ilDB->quote($this->getId(), "integer") . " AND " . + " color_name = " . $ilDB->quote($a_name, "text")); + } + + /** + * Check whether color exists + */ + public function colorExists($a_color_name) + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT * FROM style_color WHERE " . + "style_id = " . $ilDB->quote($this->getId(), "integer") . " AND " . + "color_name = " . $ilDB->quote($a_color_name, "text")); + if ($rec = $ilDB->fetchAssoc($set)) { + return true; + } + return false; + } + + /** + * Remove a color + */ + public function getColorCodeForName($a_name) + { + $ilDB = $this->db; + + $pos = strpos($a_name, "("); + if ($pos > 0) { + $a_i = substr($a_name, $pos + 1); + $a_i = str_replace(")", "", $a_i); + $a_name = substr($a_name, 0, $pos); + } + + $set = $ilDB->query("SELECT color_code FROM style_color WHERE " . + " style_id = " . $ilDB->quote($this->getId(), "integer") . " AND " . + " color_name = " . $ilDB->quote($a_name, "text")); + if ($rec = $ilDB->fetchAssoc($set)) { + if ($a_i == "") { + return "#" . $rec["color_code"]; + } else { + return "#" . ilObjStyleSheet::_getColorFlavor( + $rec["color_code"], + (int) $a_i + ); + } + } + } + + /** + * Get color flavor + */ + public static function _getColorFlavor($a_rgb, $a_i) + { + $rgb = ilObjStyleSheet::_explodeRGB($a_rgb, true); + $hls = ilObjStyleSheet::_RGBToHLS($rgb); + + if ($a_i > 0) { + $hls["l"] = $hls["l"] + ((255 - $hls["l"]) * ($a_i / 100)); + } + if ($a_i < 0) { + $hls["l"] = $hls["l"] - (($hls["l"]) * (-$a_i / 100)); + } + + $rgb = ilObjStyleSheet::_HLSToRGB($hls); + + foreach ($rgb as $k => $v) { + $rgb[$k] = str_pad(dechex($v), 2, "0", STR_PAD_LEFT); + } + + return $rgb["r"] . $rgb["g"] . $rgb["b"]; + } + + /** + * Explode an RGB string into an array + */ + public static function _explodeRGB($a_rgb, $as_dec = false) + { + $r["r"] = substr($a_rgb, 0, 2); + $r["g"] = substr($a_rgb, 2, 2); + $r["b"] = substr($a_rgb, 4, 2); + + if ($as_dec) { + $r["r"] = (int) hexdec($r["r"]); + $r["g"] = (int) hexdec($r["g"]); + $r["b"] = (int) hexdec($r["b"]); + } + + return $r; + } + + /** + * RGB to HLS (both arrays, 0..255) + */ + public static function _RGBToHLS($a_rgb) + { + $r = $a_rgb["r"] / 255; + $g = $a_rgb["g"] / 255; + $b = $a_rgb["b"] / 255; + + // max / min + $max = max($r, $g, $b); + $min = min($r, $g, $b); + + //lightness + $l = ($max + $min) / 2; + + if ($max == $min) { + $s = 0; + $h = 0; + } else { + if ($l < 0.5) { + $s = ($max - $min) / ($max + $min); + } else { + $s = ($max - $min) / (2.0 - $max - $min); + } + + if ($r == $max) { + $h = ($g - $b) / ($max - $min); + } elseif ($g == $max) { + $h = 2.0 + ($b - $r) / ($max - $min); + } elseif ($b == $max) { + $h = 4.0 + ($r - $g) / ($max - $min); + } + } + + $hls["h"] = round(($h / 6) * 255); + $hls["l"] = round($l * 255); + $hls["s"] = round($s * 255); + + return $hls; + } + + /** + * HLS to RGB (both arrays, 0..255) + */ + public static function _HLSToRGB($a_hls) + { + $h = $a_hls["h"] / 255; + $l = $a_hls["l"] / 255; + $s = $a_hls["s"] / 255; + + $rgb["r"] = $rgb["g"] = $rgb["b"] = 0; + + // If S=0, define R, G, and B all to L + if ($s == 0) { + $rgb["r"] = $rgb["g"] = $rgb["b"] = $l; + } else { + if ($l < 0.5) { + $temp2 = $l * (1.0 + $s); + } else { + $temp2 = $l + $s - $l * $s; + } + + $temp1 = 2.0 * $l - $temp2; + + + # For each of R, G, B, compute another temporary value, temp3, as follows: + foreach ($rgb as $k => $v) { + switch ($k) { + case "r": + $temp3 = $h + 1.0 / 3.0; + break; + + case "g": + $temp3 = $h; + break; + + case "b": + $temp3 = $h - 1.0/3.0; + break; + } + if ($temp3 < 0) { + $temp3 = $temp3 + 1.0; + } + if ($temp3 > 1) { + $temp3 = $temp3 - 1.0; + } + + if (6.0 * $temp3 < 1) { + $rgb[$k] = $temp1 + ($temp2 - $temp1) * 6.0 * $temp3; + } elseif (2.0 * $temp3 < 1) { + $rgb[$k] = $temp2; + } elseif (3.0 * $temp3 < 2) { + $rgb[$k] = $temp1 + ($temp2 - $temp1) * ((2.0/3.0) - $temp3) * 6.0; + } else { + $rgb[$k] = $temp1; + } + } + } + + $rgb["r"] = round($rgb["r"] * 255); + $rgb["g"] = round($rgb["g"] * 255); + $rgb["b"] = round($rgb["b"] * 255); + + return $rgb; + } + + // + // Media queries + // + + //// + //// Colors + //// + + /** + * Get colors of style + */ + public function getMediaQueries() + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT * FROM sty_media_query WHERE " . + "style_id = " . $ilDB->quote($this->getId(), "integer") . " " . + "ORDER BY order_nr"); + + $mq = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $mq[] = $rec; + } + + return $mq; + } + + /** + * Add media query + * @param string $a_mquery media query + */ + public function addMediaQuery($a_mquery, $order_nr = 0) + { + $ilDB = $this->db; + + $id = $ilDB->nextId("sty_media_query"); + if ($order_nr == 0) { + $order_nr = $this->getMaxMQueryOrderNr() + 10; + } + + $ilDB->manipulate("INSERT INTO sty_media_query (id, style_id, mquery, order_nr)" . + " VALUES (" . + $ilDB->quote($id, "integer") . "," . + $ilDB->quote($this->getId(), "integer") . "," . + $ilDB->quote($a_mquery, "text") . "," . + $ilDB->quote($order_nr, "integer") . + ")"); + + return $id; + } + + /** + * Get maximum media query order nr + * + */ + public function getMaxMQueryOrderNr() + { + $ilDB = $this->db; + + $set = $ilDB->query( + "SELECT max(order_nr) mnr FROM sty_media_query " . + " WHERE style_id = " . $ilDB->quote($this->getId(), "integer") + ); + $rec = $ilDB->fetchAssoc($set); + + return (int) $rec["mnr"]; + } + + /** + * Update media query + * + * @param int $a_id id + * @param string $a_mquery media query + */ + public function updateMediaQuery($a_id, $a_mquery) + { + $ilDB = $this->db; + + $ilDB->manipulate( + "UPDATE sty_media_query SET " . + " mquery = " . $ilDB->quote($a_mquery, "text") . + " WHERE id = " . $ilDB->quote($a_id, "integer") + ); + } + + /** + * Get media query for id + * + * @param + * @return + */ + public function getMediaQueryForId($a_id) + { + $ilDB = $this->db; + + $set = $ilDB->query( + "SELECT * FROM sty_media_query " . + " WHERE id = " . $ilDB->quote($a_id, "integer") + ); + return $ilDB->fetchAssoc($set); + } + + /** + * Delete media query + * + * @param int $a_id media query id + */ + public function deleteMediaQuery($a_id) + { + $ilDB = $this->db; + + $ilDB->manipulate( + "DELETE FROM sty_media_query WHERE " . + " style_id = " . $ilDB->quote($this->getId(), "integer") . + " AND id = " . $ilDB->quote($a_id, "integer") + ); + $this->saveMediaQueryOrder(); + } + + /** + * Save media query order + * + * @param int $a_order_nr order nr + */ + public function saveMediaQueryOrder($a_order_nr = null) + { + $ilDB = $this->db; + + $mqueries = $this->getMediaQueries(); + if (is_array($a_order_nr)) { + foreach ($mqueries as $k => $mq) { + $mqueries[$k]["order_nr"] = $a_order_nr[$mq["id"]]; + } + $mqueries = ilUtil::sortArray($mqueries, "order_nr", "", true); + } + $cnt = 10; + foreach ($mqueries as $mq) { + $ilDB->manipulate( + "UPDATE sty_media_query SET " . + " order_nr = " . $ilDB->quote($cnt, "integer") . + " WHERE id = " . $ilDB->quote($mq["id"], "integer") + ); + $cnt+= 10; + } + } + + + // + // Table template management + // + + /** + * Get table templates of style + */ + public function getTemplates($a_type) + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT * FROM style_template WHERE " . + "style_id = " . $ilDB->quote($this->getId(), "integer") . " AND " . + "temp_type = " . $ilDB->quote($a_type, "text") . " " . + "ORDER BY name"); + + $templates = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $rec["classes"] = $this->getTemplateClasses($rec["id"]); + $templates[] = $rec; + } + + return $templates; + } + + /** + * Get template classes + */ + public function getTemplateClasses($a_tid) + { + $ilDB = $this->db; + $set = $ilDB->query("SELECT * FROM style_template_class WHERE " . + "template_id = " . $ilDB->quote($a_tid, "integer")); + + $class = array(); + while ($rec = $ilDB->fetchAssoc($set)) { + $key = $rec["class_type"]; + $class[$key] = $rec["class"]; + } + + return $class; + } + + + /** + * Add table template + */ + public function addTemplate($a_type, $a_name, $a_classes) + { + $ilDB = $this->db; + + $tid = $ilDB->nextId("style_template"); + $ilDB->manipulate($q = "INSERT INTO style_template " . + "(id, style_id, name, temp_type)" . + " VALUES (" . + $ilDB->quote($tid, "integer") . "," . + $ilDB->quote($this->getId(), "integer") . "," . + $ilDB->quote($a_name, "text") . "," . + $ilDB->quote($a_type, "text") . + ")"); + + foreach ($a_classes as $t => $c) { + $ilDB->manipulate($q = "INSERT INTO style_template_class " . + "(template_id, class_type, class)" . + " VALUES (" . + $ilDB->quote($tid, "integer") . "," . + $ilDB->quote($t, "text") . "," . + $ilDB->quote($c, "text") . + ")"); + } + + include_once("./Services/Style/Content/classes/class.ilObjStyleSheetGUI.php"); + $this->writeTemplatePreview( + $tid, + ilObjStyleSheetGUI::_getTemplatePreview($this, $a_type, $tid, true) + ); + + return $tid; + } + + /** + * Update table template + */ + public function updateTemplate($a_t_id, $a_name, $a_classes) + { + $ilDB = $this->db; + + $ilDB->manipulate("UPDATE style_template SET " . + "name = " . $ilDB->quote($a_name, "text") . + " WHERE id = " . $ilDB->quote($a_t_id, "integer")); + + $ilDB->manipulate( + "DELETE FROM style_template_class WHERE " . + "template_id = " . $ilDB->quote($a_t_id, "integer") + ); + foreach ($a_classes as $t => $c) { + $ilDB->manipulate($q = "INSERT INTO style_template_class " . + "(template_id, class_type, class)" . + " VALUES (" . + $ilDB->quote($a_t_id, "integer") . "," . + $ilDB->quote($t, "text") . "," . + $ilDB->quote($c, "text") . + ")"); + } + } + + /** + * Update table template + */ + public function addTemplateClass($a_t_id, $a_type, $a_class) + { + $ilDB = $this->db; + + $ilDB->manipulate($q = "INSERT INTO style_template_class " . + "(template_id, class_type, class)" . + " VALUES (" . + $ilDB->quote($a_t_id, "integer") . "," . + $ilDB->quote($a_type, "text") . "," . + $ilDB->quote($a_class, "text") . + ")"); + } + + + /** + * Check whether template exists + */ + public function templateExists($a_template_name) + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT * FROM style_template WHERE " . + "style_id = " . $ilDB->quote($this->getId(), "integer") . " AND " . + "name = " . $ilDB->quote($a_template_name, "text")); + if ($rec = $ilDB->fetchAssoc($set)) { + return true; + } + return false; + } + + /** + * Get template + */ + public function getTemplate($a_t_id) + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT * FROM style_template WHERE " . + "style_id = " . $ilDB->quote($this->getId(), "integer") . " " . + " AND id = " . $ilDB->quote($a_t_id, "integer")); + + if ($rec = $ilDB->fetchAssoc($set)) { + $rec["classes"] = $this->getTemplateClasses($rec["id"]); + + $template = $rec; + return $template; + } + return array(); + } + + /** + * Lookup table template name for template ID + */ + public function lookupTemplateName($a_t_id) + { + return self::_lookupTemplateName($a_t_id); + } + + /** + * Lookup table template name for template ID + */ + public static function _lookupTemplateName($a_t_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query("SELECT name FROM style_template WHERE " . + " id = " . $ilDB->quote($a_t_id, "integer")); + + if ($rec = $ilDB->fetchAssoc($set)) { + return $rec["name"]; + } + + return false; + } + + /** + * Get table template xml + */ + public function getTemplateXML() + { + $ilDB = $this->db; + + $tag = ""; + + $ttypes = array("table", "vaccordion", "haccordion", "carousel"); + + foreach ($ttypes as $ttype) { + $ts = $this->getTemplates($ttype); + + foreach ($ts as $t) { + $atts = ilObjStyleSheet::_getTemplateClassTypes($ttype); + /*$atts = array("table" => "TableClass", + "caption" => "CaptionClass", + "row_head" => "RowHeadClass", + "row_foot" => "RowFootClass", + "col_head" => "ColHeadClass", + "col_foot" => "ColFootClass", + "odd_row" => "OddRowClass", + "even_row" => "EvenRowClass", + "odd_col" => "OddColClass", + "even_col" => "EvenColClass");*/ + $c = $t["classes"]; + + $tag.= ''; + + foreach ($atts as $type => $t) { + if ($c[$type] != "") { + $tag.= ''; + } + } + + $tag.= ""; + } + } + + $tag.= ""; + + //echo htmlentities($tag); + return $tag; + } + + /** + * Write table template preview + */ + public function writeTemplatePreview($a_t_id, $a_preview_html) + { + $ilDB = $this->db; + $a_preview_html = str_replace(' width=""', "", $a_preview_html); + $a_preview_html = str_replace(' valign="top"', "", $a_preview_html); + $a_preview_html = str_replace('
                  ', "
                  ", $a_preview_html); + //echo "1-".strlen($a_preview_html)."-"; + //echo htmlentities($a_preview_html); + if (strlen($a_preview_html) > 4000) { + //echo "2"; + $a_preview_html = ""; + } + $ilDB->manipulate("UPDATE style_template SET " . + "preview = " . $ilDB->quote($a_preview_html, "text") . + " WHERE id = " . $ilDB->quote($a_t_id, "integer")); + } + + /** + * Lookup table template preview + */ + public function lookupTemplatePreview($a_t_id) + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT preview FROM style_template " . + " WHERE id = " . $ilDB->quote($a_t_id, "integer")); + if ($rec = $ilDB->fetchAssoc($set)) { + return $rec["preview"]; + } + + return ""; + } + + /** + * Lookup table template preview + */ + public static function _lookupTemplateIdByName($a_style_id, $a_name) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query("SELECT id FROM style_template " . + " WHERE style_id = " . $ilDB->quote($a_style_id, "integer") . + " AND name = " . $ilDB->quote($a_name, "text")); + if ($rec = $ilDB->fetchAssoc($set)) { + return $rec["id"]; + } + + return false; + } + + /** + * Remove table template + */ + public function removeTemplate($a_t_id) + { + $ilDB = $this->db; + + $ilDB->manipulate("DELETE FROM style_template WHERE " . + " style_id = " . $ilDB->quote($this->getId(), "integer") . " AND " . + " id = " . $ilDB->quote($a_t_id, "integer")); + + $ilDB->manipulate( + "DELETE FROM style_template_class WHERE " . + "template_id = " . $ilDB->quote($a_t_id, "integer") + ); + } + + /** + * Write Style Setting + */ + public function writeStyleSetting($a_name, $a_value) + { + $ilDB = $this->db; + + $ilDB->manipulate( + "DELETE FROM style_setting WHERE " . + " style_id = " . $ilDB->quote($this->getId(), "integer") . + " AND name = " . $ilDB->quote($a_name, "text") + ); + + $ilDB->manipulate("INSERT INTO style_setting " . + "(style_id, name, value) VALUES (" . + $ilDB->quote($this->getId(), "integer") . "," . + $ilDB->quote($a_name, "text") . "," . + $ilDB->quote($a_value, "text") . + ")"); + } + + /** + * Lookup style setting + */ + public function lookupStyleSetting($a_name) + { + $ilDB = $this->db; + + $set = $ilDB->query( + "SELECT value FROM style_setting " . + " WHERE style_id = " . $ilDB->quote($this->getId(), "integer") . + " AND name = " . $ilDB->quote($a_name, "text") + ); + $rec = $ilDB->fetchAssoc($set); + + return $rec["value"]; + } + + /** + * Write style usage + */ + public static function writeStyleUsage($a_obj_id, $a_style_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $ilDB->replace( + "style_usage", + array( + "obj_id" => array("integer", (int) $a_obj_id)), + array( + "style_id" => array("integer", (int) $a_style_id)) + ); + } + + /** + * Lookup object style + */ + public static function lookupObjectStyle($a_obj_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT style_id FROM style_usage " . + " WHERE obj_id = " . $ilDB->quote($a_obj_id, "integer") + ); + $rec = $ilDB->fetchAssoc($set); + + if (ilObject::_lookupType($rec["style_id"]) == "sty") { + return (int) $rec["style_id"]; + } + + return 0; + } + + /** + * Lookup object style + */ + public static function lookupObjectForStyle($a_style_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $obj_ids = array(); + if (ilObject::_lookupType($a_style_id) == "sty") { + $set = $ilDB->query( + "SELECT DISTINCT obj_id FROM style_usage " . + " WHERE style_id = " . $ilDB->quote($a_style_id, "integer") + ); + + while ($rec = $ilDB->fetchAssoc($set)) { + $obj_ids[] = $rec["obj_id"]; + } + } + return $obj_ids; + } } -?> diff --git a/Services/Style/Content/classes/class.ilObjStyleSheetGUI.php b/Services/Style/Content/classes/class.ilObjStyleSheetGUI.php index 94ff4f4108ec3833acf43f13d1c34db1d5c751d5..6984b37e79a17f794e4e43fcb1f15e287017a1aa 100755 --- a/Services/Style/Content/classes/class.ilObjStyleSheetGUI.php +++ b/Services/Style/Content/classes/class.ilObjStyleSheetGUI.php @@ -15,3070 +15,3055 @@ require_once "./Services/Style/Content/classes/class.ilObjStyleSheet.php"; */ class ilObjStyleSheetGUI extends ilObjectGUI { - /** - * @var ilRbacSystem - */ - protected $rbacsystem; - - /** - * @var ilHelpGUI - */ - protected $help; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * @var ilObjectDefinition - */ - protected $obj_definition; - - var $cmd_update; - var $cmd_new_par; - var $cmd_refresh; - var $cmd_delete; - - /** - * Constructor - * @access public - */ - function __construct($a_data,$a_id,$a_call_by_reference, $a_prep = true) - { - global $DIC; - - $this->tpl = $DIC["tpl"]; - $this->rbacsystem = $DIC->rbac()->system(); - $this->help = $DIC["ilHelp"]; - $this->tabs = $DIC->tabs(); - $this->toolbar = $DIC->toolbar(); - $this->locator = $DIC["ilLocator"]; - $this->tree = $DIC->repositoryTree(); - $this->obj_definition = $DIC["objDefinition"]; - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $tpl = $DIC["tpl"]; - - $this->ctrl = $ilCtrl; - $this->lng = $lng; - $this->lng->loadLanguageModule("style"); - $ilCtrl->saveParameter($this, array("tag", "style_type", "temp_type")); - if ($_GET["style_type"] != "") - { - $this->super_type = ilObjStyleSheet::_getStyleSuperTypeForType($_GET["style_type"]); - } - - $this->type = "sty"; - parent::__construct($a_data,$a_id,$a_call_by_reference, false); - } - - /** - * execute command - */ - function executeCommand() - { - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd("edit"); - - // #9440/#9489: prepareOutput will fail if not set properly - if(!$this->object) - { - $this->setCreationMode(true); - } - - $this->prepareOutput(); - switch($next_class) - { - default: - $cmd.= "Object"; - $ret = $this->$cmd(); - break; - } - - return $ret; - } - - function viewObject() - { - $this->editObject(); - } - - /** - * create - */ - function createObject() - { - $rbacsystem = $this->rbacsystem; - $lng = $this->lng; - $tpl = $this->tpl; - $ilHelp = $this->help; - - $forms = array(); - - - $ilHelp->setScreenIdComponent("sty"); - $ilHelp->setDefaultScreenId(ilHelpGUI::ID_PART_SCREEN, "create"); - - // --- create - - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - $form->setTitle($this->lng->txt("sty_create_new_stylesheet")); - - // title - $ti = new ilTextInputGUI($this->lng->txt("title"), "style_title"); - $ti->setMaxLength(128); - $ti->setSize(40); - $ti->setRequired(true); - $form->addItem($ti); - - // description - $ta = new ilTextAreaInputGUI($this->lng->txt("description"), "style_description"); - $ta->setCols(40); - $ta->setRows(2); - $form->addItem($ta); - - $form->addCommandButton("save", $this->lng->txt("save")); - $form->addCommandButton("cancel", $this->lng->txt("cancel")); - - $forms[] = $form; - - - // --- import - - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - $form->setTitle($this->lng->txt("sty_import_stylesheet")); - - // title - $ti = new ilFileInputGUI($this->lng->txt("import_file"), "importfile"); - $ti->setRequired(true); - $form->addItem($ti); - - $form->addCommandButton("importStyle", $this->lng->txt("import")); - $form->addCommandButton("cancel", $this->lng->txt("cancel")); - - $forms[] = $form; - - - // --- clone - - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - $form->setTitle($this->lng->txt("sty_copy_other_stylesheet")); - - // source - $ti = new ilSelectInputGUI($this->lng->txt("sty_source"), "source_style"); - $ti->setRequired(true); - $ti->setOptions(ilObjStyleSheet::_getClonableContentStyles()); - $form->addItem($ti); - - $form->addCommandButton("copyStyle", $this->lng->txt("copy")); - $form->addCommandButton("cancel", $this->lng->txt("cancel")); - - $forms[] = $form; - - - $this->tpl->setContent($this->getCreationFormsHTML($forms)); - } - - /** - * Include CSS in output - */ - function includeCSS() - { - // set style sheet - $this->tpl->setCurrentBlock("ContentStyle"); - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->object->getId())); - $this->tpl->parseCurrentBlock(); - } - - - /** - * Check write - * - * @param - * @return - */ - public function checkWrite() - { - $rbacsystem = $this->rbacsystem; - - return ($rbacsystem->checkAccess("write", (int) $_GET["ref_id"]) - || $rbacsystem->checkAccess("sty_write_content", (int) $_GET["ref_id"])); - } - - - /** - * edit style sheet - */ - function editObject() - { - $rbacsystem = $this->rbacsystem; - $lng = $this->lng; - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $ilToolbar = $this->toolbar; - $tpl = $this->tpl; - - $this->setSubTabs(); - - $this->includeCSS(); - - $ctpl = new ilTemplate("tpl.sty_classes.html", true, true, "Services/Style/Content"); - - // output characteristics - $chars = $this->object->getCharacteristics(); - - $style_type = ($this->super_type != "") - ? $this->super_type - : "text_block"; - $ilCtrl->setParameter($this, "style_type", $style_type); - $ilTabs->setSubTabActive("sty_".$style_type."_char"); - - // workaround to include default rte styles - if ($this->super_type == "rte") - { - $tpl->addCss("Modules/Scorm2004/templates/default/player.css"); - include_once("./Modules/Scorm2004/classes/ilSCORM13Player.php"); - $tpl->addInlineCss(ilSCORM13Player::getInlineCss()); - } - - // add new style? - $all_super_types = ilObjStyleSheet::_getStyleSuperTypes(); - $subtypes = $all_super_types[$style_type]; - $expandable = false; - foreach ($subtypes as $t) - { - if (ilObjStyleSheet::_isExpandable($t)) - { - $expandable = true; - } - } - if ($expandable && $this->checkWrite()) - { - $ilToolbar->addButton($lng->txt("sty_add_characteristic"), - $ilCtrl->getLinkTarget($this, "addCharacteristicForm")); - } - - if ($_SESSION["sty_copy"] != "") - { - $style_cp = explode(":::", $_SESSION["sty_copy"]); - if ($style_cp[1] == $style_type) - { - if ($expandable) - { - $ilToolbar->addSeparator(); - } - $ilToolbar->addButton($lng->txt("sty_paste_style_classes"), - $ilCtrl->getLinkTarget($this, "pasteCharacteristicsOverview")); - } - } - - include_once("./Services/Style/Content/classes/class.ilStyleTableGUI.php"); - $table_gui = new ilStyleTableGUI($this, "edit", $chars, $style_type, - $this->object); - - $ctpl->setCurrentBlock("style_table"); - $ctpl->setVariable("STYLE_TABLE", $table_gui->getHTML()); - $ctpl->parseCurrentBlock(); - - $this->tpl->setContent($ctpl->get()); - } - - /** - * Properties - */ - function propertiesObject() - { - $rbacsystem = $this->rbacsystem; - $lng = $this->lng; - $ilToolbar = $this->toolbar; - - // set style sheet - $this->tpl->setCurrentBlock("ContentStyle"); - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->object->getId())); - $this->tpl->parseCurrentBlock(); - - // export button - $ilToolbar->addButton($this->lng->txt("export"), - $this->ctrl->getLinkTarget($this, "exportStyle")); - - $this->initPropertiesForm(); - $this->getPropertiesValues(); - $this->tpl->setContent($this->form->getHTML()); - } - - /** - * Get current values for properties from - * - */ - public function getPropertiesValues() - { - $values = array(); - - $values["style_title"] = $this->object->getTitle(); - $values["style_description"] = $this->object->getDescription(); - $values["disable_auto_margins"] = (int) $this->object->lookupStyleSetting("disable_auto_margins"); - - $this->form->setValuesByArray($values); - } - - /** - * FORM: Init properties form. - * - * @param int $a_mode Edit Mode - */ - public function initPropertiesForm($a_mode = "edit") - { - $lng = $this->lng; - $rbacsystem = $this->rbacsystem; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - // title - $ti = new ilTextInputGUI($this->lng->txt("title"), "style_title"); - $ti->setMaxLength(128); - $ti->setSize(40); - $ti->setRequired(true); - $this->form->addItem($ti); - - // description - $ta = new ilTextAreaInputGUI($this->lng->txt("description"), "style_description"); - //$ta->setCols(); - //$ta->setRows(); - $this->form->addItem($ta); - - // disable automatic margins for left/right alignment - $cb = new ilCheckboxInputGUI($this->lng->txt("sty_disable_auto_margins"), "disable_auto_margins"); - $cb->setInfo($this->lng->txt("sty_disable_auto_margins_info")); - $this->form->addItem($cb); - - // save and cancel commands - - if ($a_mode == "create") - { - $this->form->addCommandButton("save", $lng->txt("save")); - $this->form->addCommandButton("cancelSave", $lng->txt("cancel")); - } - else - { - if ($this->checkWrite()) - { - $this->form->addCommandButton("update", $lng->txt("save")); - } - } - - $this->form->setTitle($lng->txt("edit_stylesheet")); - $this->form->setFormAction($this->ctrl->getFormAction($this)); - - } - - /** - * Update properties - */ - function updateObject() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - - $this->initPropertiesForm("edit"); - if ($this->form->checkInput()) - { - $this->object->setTitle($this->form->getInput("style_title")); - $this->object->setDescription($this->form->getInput("style_description")); - $this->object->writeStyleSetting("disable_auto_margins", - $this->form->getInput("disable_auto_margins")); - $this->object->update(); - ilUtil::sendInfo($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "properties"); - } - else - { - $this->form->setValuesByPost(); - $tpl->setContent($this->form->getHtml()); - } - } - - /** - * save and refresh tag editing - */ - function refreshTagStyleObject() - { - $ilCtrl = $this->ctrl; - - $cur = explode(".",$_GET["tag"]); - $cur_tag = $cur[0]; - $cur_class = $cur[1]; - - $this->initTagStyleForm("edit", $cur_tag); - - if ($this->form_gui->checkInput()) - { - $this->saveTagStyle(); - $ilCtrl->redirect($this, "editTagStyle"); - } - else - { - $this->form_gui->setValuesByPost(); - $this->outputTagStyleEditScreen(); - } - } - - /** - * save and refresh tag editing - */ - function updateTagStyleObject() - { - $ilCtrl = $this->ctrl; - - $cur = explode(".",$_GET["tag"]); - $cur_tag = $cur[0]; - $cur_class = $cur[1]; - - $this->initTagStyleForm("edit", $cur_tag); - if ($this->form_gui->checkInput()) - { - $this->saveTagStyle(); - $ilCtrl->redirect($this, "edit"); - } - else - { - $this->form_gui->setValuesByPost(); - $this->outputTagStyleEditScreen(); - } - } - - /** - * Save tag style. - */ - function saveTagStyle() - { - $cur = explode(".", $_GET["tag"]); - $cur_tag = $cur[0]; - $cur_class = $cur[1]; - $avail_pars = ilObjStyleSheet::_getStyleParameters($cur_tag); - foreach ($avail_pars as $par => $v) - { - $var = str_replace("-", "_", $par); - $basepar_arr = explode(".", $par); - $basepar = $basepar_arr[0]; - if ($basepar_arr[1] != "" && $basepar_arr[1] != $cur_tag) - { - continue; - } - - switch ($v["input"]) - { - case "fontsize": - case "numeric_no_perc": - case "numeric": - case "background_image": - $in = $this->form_gui->getItemByPostVar($basepar); + /** + * @var ilRbacSystem + */ + protected $rbacsystem; + + /** + * @var ilHelpGUI + */ + protected $help; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * @var ilObjectDefinition + */ + protected $obj_definition; + + public $cmd_update; + public $cmd_new_par; + public $cmd_refresh; + public $cmd_delete; + + /** + * Constructor + * @access public + */ + public function __construct($a_data, $a_id, $a_call_by_reference, $a_prep = true) + { + global $DIC; + + $this->tpl = $DIC["tpl"]; + $this->rbacsystem = $DIC->rbac()->system(); + $this->help = $DIC["ilHelp"]; + $this->tabs = $DIC->tabs(); + $this->toolbar = $DIC->toolbar(); + $this->locator = $DIC["ilLocator"]; + $this->tree = $DIC->repositoryTree(); + $this->obj_definition = $DIC["objDefinition"]; + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $tpl = $DIC["tpl"]; + + $this->ctrl = $ilCtrl; + $this->lng = $lng; + $this->lng->loadLanguageModule("style"); + $ilCtrl->saveParameter($this, array("tag", "style_type", "temp_type")); + if ($_GET["style_type"] != "") { + $this->super_type = ilObjStyleSheet::_getStyleSuperTypeForType($_GET["style_type"]); + } + + $this->type = "sty"; + parent::__construct($a_data, $a_id, $a_call_by_reference, false); + } + + /** + * execute command + */ + public function executeCommand() + { + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd("edit"); + + // #9440/#9489: prepareOutput will fail if not set properly + if (!$this->object) { + $this->setCreationMode(true); + } + + $this->prepareOutput(); + switch ($next_class) { + default: + $cmd.= "Object"; + $ret = $this->$cmd(); + break; + } + + return $ret; + } + + public function viewObject() + { + $this->editObject(); + } + + /** + * create + */ + public function createObject() + { + $rbacsystem = $this->rbacsystem; + $lng = $this->lng; + $tpl = $this->tpl; + $ilHelp = $this->help; + + $forms = array(); + + + $ilHelp->setScreenIdComponent("sty"); + $ilHelp->setDefaultScreenId(ilHelpGUI::ID_PART_SCREEN, "create"); + + // --- create + + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this)); + $form->setTitle($this->lng->txt("sty_create_new_stylesheet")); + + // title + $ti = new ilTextInputGUI($this->lng->txt("title"), "style_title"); + $ti->setMaxLength(128); + $ti->setSize(40); + $ti->setRequired(true); + $form->addItem($ti); + + // description + $ta = new ilTextAreaInputGUI($this->lng->txt("description"), "style_description"); + $ta->setCols(40); + $ta->setRows(2); + $form->addItem($ta); + + $form->addCommandButton("save", $this->lng->txt("save")); + $form->addCommandButton("cancel", $this->lng->txt("cancel")); + + $forms[] = $form; + + + // --- import + + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this)); + $form->setTitle($this->lng->txt("sty_import_stylesheet")); + + // title + $ti = new ilFileInputGUI($this->lng->txt("import_file"), "importfile"); + $ti->setRequired(true); + $form->addItem($ti); + + $form->addCommandButton("importStyle", $this->lng->txt("import")); + $form->addCommandButton("cancel", $this->lng->txt("cancel")); + + $forms[] = $form; + + + // --- clone + + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this)); + $form->setTitle($this->lng->txt("sty_copy_other_stylesheet")); + + // source + $ti = new ilSelectInputGUI($this->lng->txt("sty_source"), "source_style"); + $ti->setRequired(true); + $ti->setOptions(ilObjStyleSheet::_getClonableContentStyles()); + $form->addItem($ti); + + $form->addCommandButton("copyStyle", $this->lng->txt("copy")); + $form->addCommandButton("cancel", $this->lng->txt("cancel")); + + $forms[] = $form; + + + $this->tpl->setContent($this->getCreationFormsHTML($forms)); + } + + /** + * Include CSS in output + */ + public function includeCSS() + { + // set style sheet + $this->tpl->setCurrentBlock("ContentStyle"); + $this->tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath($this->object->getId()) + ); + $this->tpl->parseCurrentBlock(); + } + + + /** + * Check write + * + * @param + * @return + */ + public function checkWrite() + { + $rbacsystem = $this->rbacsystem; + + return ($rbacsystem->checkAccess("write", (int) $_GET["ref_id"]) + || $rbacsystem->checkAccess("sty_write_content", (int) $_GET["ref_id"])); + } + + + /** + * edit style sheet + */ + public function editObject() + { + $rbacsystem = $this->rbacsystem; + $lng = $this->lng; + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $ilToolbar = $this->toolbar; + $tpl = $this->tpl; + + $this->setSubTabs(); + + $this->includeCSS(); + + $ctpl = new ilTemplate("tpl.sty_classes.html", true, true, "Services/Style/Content"); + + // output characteristics + $chars = $this->object->getCharacteristics(); + + $style_type = ($this->super_type != "") + ? $this->super_type + : "text_block"; + $ilCtrl->setParameter($this, "style_type", $style_type); + $ilTabs->setSubTabActive("sty_" . $style_type . "_char"); + + // workaround to include default rte styles + if ($this->super_type == "rte") { + $tpl->addCss("Modules/Scorm2004/templates/default/player.css"); + include_once("./Modules/Scorm2004/classes/ilSCORM13Player.php"); + $tpl->addInlineCss(ilSCORM13Player::getInlineCss()); + } + + // add new style? + $all_super_types = ilObjStyleSheet::_getStyleSuperTypes(); + $subtypes = $all_super_types[$style_type]; + $expandable = false; + foreach ($subtypes as $t) { + if (ilObjStyleSheet::_isExpandable($t)) { + $expandable = true; + } + } + if ($expandable && $this->checkWrite()) { + $ilToolbar->addButton( + $lng->txt("sty_add_characteristic"), + $ilCtrl->getLinkTarget($this, "addCharacteristicForm") + ); + } + + if ($_SESSION["sty_copy"] != "") { + $style_cp = explode(":::", $_SESSION["sty_copy"]); + if ($style_cp[1] == $style_type) { + if ($expandable) { + $ilToolbar->addSeparator(); + } + $ilToolbar->addButton( + $lng->txt("sty_paste_style_classes"), + $ilCtrl->getLinkTarget($this, "pasteCharacteristicsOverview") + ); + } + } + + include_once("./Services/Style/Content/classes/class.ilStyleTableGUI.php"); + $table_gui = new ilStyleTableGUI( + $this, + "edit", + $chars, + $style_type, + $this->object + ); + + $ctpl->setCurrentBlock("style_table"); + $ctpl->setVariable("STYLE_TABLE", $table_gui->getHTML()); + $ctpl->parseCurrentBlock(); + + $this->tpl->setContent($ctpl->get()); + } + + /** + * Properties + */ + public function propertiesObject() + { + $rbacsystem = $this->rbacsystem; + $lng = $this->lng; + $ilToolbar = $this->toolbar; + + // set style sheet + $this->tpl->setCurrentBlock("ContentStyle"); + $this->tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath($this->object->getId()) + ); + $this->tpl->parseCurrentBlock(); + + // export button + $ilToolbar->addButton( + $this->lng->txt("export"), + $this->ctrl->getLinkTarget($this, "exportStyle") + ); + + $this->initPropertiesForm(); + $this->getPropertiesValues(); + $this->tpl->setContent($this->form->getHTML()); + } + + /** + * Get current values for properties from + * + */ + public function getPropertiesValues() + { + $values = array(); + + $values["style_title"] = $this->object->getTitle(); + $values["style_description"] = $this->object->getDescription(); + $values["disable_auto_margins"] = (int) $this->object->lookupStyleSetting("disable_auto_margins"); + + $this->form->setValuesByArray($values); + } + + /** + * FORM: Init properties form. + * + * @param int $a_mode Edit Mode + */ + public function initPropertiesForm($a_mode = "edit") + { + $lng = $this->lng; + $rbacsystem = $this->rbacsystem; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + // title + $ti = new ilTextInputGUI($this->lng->txt("title"), "style_title"); + $ti->setMaxLength(128); + $ti->setSize(40); + $ti->setRequired(true); + $this->form->addItem($ti); + + // description + $ta = new ilTextAreaInputGUI($this->lng->txt("description"), "style_description"); + //$ta->setCols(); + //$ta->setRows(); + $this->form->addItem($ta); + + // disable automatic margins for left/right alignment + $cb = new ilCheckboxInputGUI($this->lng->txt("sty_disable_auto_margins"), "disable_auto_margins"); + $cb->setInfo($this->lng->txt("sty_disable_auto_margins_info")); + $this->form->addItem($cb); + + // save and cancel commands + + if ($a_mode == "create") { + $this->form->addCommandButton("save", $lng->txt("save")); + $this->form->addCommandButton("cancelSave", $lng->txt("cancel")); + } else { + if ($this->checkWrite()) { + $this->form->addCommandButton("update", $lng->txt("save")); + } + } + + $this->form->setTitle($lng->txt("edit_stylesheet")); + $this->form->setFormAction($this->ctrl->getFormAction($this)); + } + + /** + * Update properties + */ + public function updateObject() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + + $this->initPropertiesForm("edit"); + if ($this->form->checkInput()) { + $this->object->setTitle($this->form->getInput("style_title")); + $this->object->setDescription($this->form->getInput("style_description")); + $this->object->writeStyleSetting( + "disable_auto_margins", + $this->form->getInput("disable_auto_margins") + ); + $this->object->update(); + ilUtil::sendInfo($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "properties"); + } else { + $this->form->setValuesByPost(); + $tpl->setContent($this->form->getHtml()); + } + } + + /** + * save and refresh tag editing + */ + public function refreshTagStyleObject() + { + $ilCtrl = $this->ctrl; + + $cur = explode(".", $_GET["tag"]); + $cur_tag = $cur[0]; + $cur_class = $cur[1]; + + $this->initTagStyleForm("edit", $cur_tag); + + if ($this->form_gui->checkInput()) { + $this->saveTagStyle(); + $ilCtrl->redirect($this, "editTagStyle"); + } else { + $this->form_gui->setValuesByPost(); + $this->outputTagStyleEditScreen(); + } + } + + /** + * save and refresh tag editing + */ + public function updateTagStyleObject() + { + $ilCtrl = $this->ctrl; + + $cur = explode(".", $_GET["tag"]); + $cur_tag = $cur[0]; + $cur_class = $cur[1]; + + $this->initTagStyleForm("edit", $cur_tag); + if ($this->form_gui->checkInput()) { + $this->saveTagStyle(); + $ilCtrl->redirect($this, "edit"); + } else { + $this->form_gui->setValuesByPost(); + $this->outputTagStyleEditScreen(); + } + } + + /** + * Save tag style. + */ + public function saveTagStyle() + { + $cur = explode(".", $_GET["tag"]); + $cur_tag = $cur[0]; + $cur_class = $cur[1]; + $avail_pars = ilObjStyleSheet::_getStyleParameters($cur_tag); + foreach ($avail_pars as $par => $v) { + $var = str_replace("-", "_", $par); + $basepar_arr = explode(".", $par); + $basepar = $basepar_arr[0]; + if ($basepar_arr[1] != "" && $basepar_arr[1] != $cur_tag) { + continue; + } + + switch ($v["input"]) { + case "fontsize": + case "numeric_no_perc": + case "numeric": + case "background_image": + $in = $this->form_gui->getItemByPostVar($basepar); //echo "
                  -".$cur_tag."-".$cur_class."-".$basepar."-".$_GET["style_type"]."-"; - $this->writeStylePar($cur_tag, $cur_class, $basepar, $in->getValue(), $_GET["style_type"], (int) $_GET["mq_id"]); - break; - - case "color": - $color = trim($_POST[$basepar]); - if ($color != "" && trim(substr($color,0,1) != "!")) - { - $color = "#".$color; - } - $this->writeStylePar($cur_tag, $cur_class, $basepar, $color, $_GET["style_type"], (int) $_GET["mq_id"]); - break; - - case "trbl_numeric": - case "border_width": - case "border_style": - $in = $this->form_gui->getItemByPostVar($basepar); - $this->writeStylePar($cur_tag, $cur_class, $v["subpar"][0], $in->getAllValue(), $_GET["style_type"], (int) $_GET["mq_id"]); - $this->writeStylePar($cur_tag, $cur_class, $v["subpar"][1], $in->getTopValue(), $_GET["style_type"], (int) $_GET["mq_id"]); - $this->writeStylePar($cur_tag, $cur_class, $v["subpar"][2], $in->getRightValue(), $_GET["style_type"], (int) $_GET["mq_id"]); - $this->writeStylePar($cur_tag, $cur_class, $v["subpar"][3], $in->getBottomValue(), $_GET["style_type"], (int) $_GET["mq_id"]); - $this->writeStylePar($cur_tag, $cur_class, $v["subpar"][4], $in->getLeftValue(), $_GET["style_type"], (int) $_GET["mq_id"]); - break; - - case "trbl_color": - $in = $this->form_gui->getItemByPostVar($basepar); - $tblr_p = array (0 => "getAllValue", 1 => "getTopValue", 2 => "getRightValue", - 3 => "getBottomValue", 4 => "getLeftValue"); - foreach ($tblr_p as $k => $func) - { - $val = trim($in->$func()); - $val = (($in->getAcceptNamedColors() && substr($val, 0, 1) == "!") - || $val == "") - ? $val - : "#".$val; - $this->writeStylePar($cur_tag, $cur_class, $v["subpar"][$k], $val, $_GET["style_type"], (int) $_GET["mq_id"]); - } - break; - - case "background_position": - $in = $this->form_gui->getItemByPostVar($basepar); - $this->writeStylePar($cur_tag, $cur_class, $basepar, $in->getValue(), $_GET["style_type"], (int) $_GET["mq_id"]); - break; - - default: - $this->writeStylePar($cur_tag, $cur_class, $basepar, $_POST[$basepar], $_GET["style_type"], (int) $_GET["mq_id"]); - break; - } - } - - // write custom parameter - $this->object->deleteCustomStylePars($cur_tag, $cur_class, $_GET["style_type"], (int) $_GET["mq_id"]); - if (is_array($_POST["custom_par"])) - { - foreach ($_POST["custom_par"] as $cpar) - { - $par_arr = explode(":", $cpar); - if (count($par_arr) == 2) - { - $par = trim($par_arr[0]); - $val = trim(str_replace(";", "", $par_arr[1])); - $this->writeStylePar($cur_tag, $cur_class, $par, $val, $_GET["style_type"], (int) $_GET["mq_id"], true); - } - } - } - - $this->object->update(); - } - - function writeStylePar($cur_tag, $cur_class, $par, $value, $a_type, $a_mq_id, $a_custom = false) - { -// echo $_GET["mq_id"]."-"; -// echo $a_mq_id."-"; exit; - if ($a_type == "") - { - return; - } - - if ($value != "") - { - $this->object->replaceStylePar($cur_tag, $cur_class, $par, $value, $a_type, $a_mq_id, $a_custom); - } - else - { - $this->object->deleteStylePar($cur_tag, $cur_class, $par, $a_type, $a_mq_id, $a_custom); - } - } - - /** - * Edit tag style. - * - */ - function editTagStyleObject() - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - // media query selector - $mqs = $this->object->getMediaQueries(); - if (count($mqs) > 0) - { - // - $options = array( - "" => $lng->txt("sty_default"), - ); - foreach ($mqs as $mq) - { - $options[$mq["id"]] = $mq["mquery"]; - } - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $si = new ilSelectInputGUI("@media", "mq_id"); - $si->setOptions($options); - $si->setValue((int) $_GET["mq_id"]); - $ilToolbar->addInputItem($si, true); - $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); - $ilToolbar->addFormButton($lng->txt("sty_switch"), "switchMQuery"); - } - - // workaround to include default rte styles - //if (in_array($_GET["style_type"], array("rte_menu"))) - if ($this->super_type == "rte") - { - $tpl->addCss("Modules/Scorm2004/templates/default/player.css"); - include_once("./Modules/Scorm2004/classes/ilSCORM13Player.php"); - $tpl->addInlineCss(ilSCORM13Player::getInlineCss()); - } - - $cur = explode(".",$_GET["tag"]); - $cur_tag = $cur[0]; - $cur_class = $cur[1]; - - $this->initTagStyleForm("edit", $cur_tag); - $this->getValues(); - $this->outputTagStyleEditScreen(); - } - - /** - * Switch media query - * - * @param - * @return - */ - function switchMQueryObject() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameter($this, "mq_id", (int) $_POST["mq_id"]); - $ilCtrl->redirect($this, "editTagStyle"); - } - - - /** - * Output tag style edit screen. - */ - function outputTagStyleEditScreen() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - // set style sheet - $tpl->setCurrentBlock("ContentStyle"); - $tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->object->getId())); - - $ts_tpl = new ilTemplate("tpl.style_tag_edit.html", true, true, "Services/Style/Content"); - - $cur = explode(".",$_GET["tag"]); - $cur_tag = $cur[0]; - $cur_class = $cur[1]; - - $ts_tpl->setVariable("EXAMPLE", - ilObjStyleSheetGUI::getStyleExampleHTML($_GET["style_type"], $cur_class)); - - $ts_tpl->setVariable("FORM", - $this->form_gui->getHtml()); - - $tpl->setTitle($cur_class." (".$lng->txt("sty_type_".$_GET["style_type"]).")"); - - $tpl->setContent($ts_tpl->get()); - } - - - /** - * Init tag style editing form - * - * @param int $a_mode Form Edit Mode (IL_FORM_EDIT | IL_FORM_CREATE) - */ - public function initTagStyleForm($a_mode, $a_cur_tag) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $ilCtrl->saveParameter($this, array("mq_id")); - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form_gui = new ilPropertyFormGUI(); - - $avail_pars = $this->object->getAvailableParameters(); - $groups = $this->object->getStyleParameterGroups(); - - // output select lists - foreach ($groups as $k => $group) - { - // filter groups of properties that should only be - // displayed with matching tag - $filtered_groups = ilObjStyleSheet::_getFilteredGroups(); - if (is_array($filtered_groups[$k]) && !in_array($a_cur_tag, $filtered_groups[$k])) - { - continue; - } - - $sh = new ilFormSectionHeaderGUI(); - $sh->setTitle($lng->txt("sty_".$k)); - $this->form_gui->addItem($sh); - - foreach ($group as $par) - { - $basepar = explode(".", $par); - $basepar = $basepar[0]; - - $var = str_replace("-", "_", $basepar); - $up_par = strtoupper($var); - - switch (ilObjStyleSheet::_getStyleParameterInputType($par)) - { - case "select": - $sel_input = new ilSelectInputGUI($lng->txt("sty_".$var), $basepar); - $options = array("" => ""); - foreach ($avail_pars[$par] as $p) - { - $options[$p] = $p; - } - $sel_input->setOptions($options); - $this->form_gui->addItem($sel_input); - break; - - case "text": - $text_input = new ilTextInputGUI($lng->txt("sty_".$var), $basepar); - $text_input->setMaxLength(200); - $text_input->setSize(20); - $this->form_gui->addItem($text_input); - break; - - case "fontsize": - include_once("./Services/Style/Content/classes/class.ilFontSizeInputGUI.php"); - $fs_input = new ilFontSizeInputGUI($lng->txt("sty_".$var), $basepar); - $this->form_gui->addItem($fs_input); - break; - - case "numeric_no_perc": - case "numeric": - include_once("./Services/Style/Content/classes/class.ilNumericStyleValueInputGUI.php"); - $num_input = new ilNumericStyleValueInputGUI($lng->txt("sty_".$var), $basepar); - if (ilObjStyleSheet::_getStyleParameterInputType($par) == "numeric_no_perc") - { - $num_input->setAllowPercentage(false); - } - $this->form_gui->addItem($num_input); - break; - - case "percentage": - $per_input = new ilNumberInputGUI($lng->txt("sty_".$var), $basepar); - $per_input->setMinValue(0); - $per_input->setMaxValue(100); - $per_input->setMaxLength(3); - $per_input->setSize(3); - $this->form_gui->addItem($per_input); - break; - - case "color": - //include_once("./Services/Style/classes/class.ilNumericStyleValueInputGUI.php"); - $col_input = new ilColorPickerInputGUI($lng->txt("sty_".$var), $basepar); - $col_input->setDefaultColor(""); - $col_input->setAcceptNamedColors(true); - $this->form_gui->addItem($col_input); - break; - - case "trbl_numeric": - include_once("./Services/Style/Content/classes/class.ilTRBLNumericStyleValueInputGUI.php"); - $num_input = new ilTRBLNumericStyleValueInputGUI($lng->txt("sty_".$var), $basepar); - if (ilObjStyleSheet::_getStyleParameterInputType($par) == "trbl_numeric_no_perc") - { - $num_input->setAllowPercentage(false); - } - $this->form_gui->addItem($num_input); - break; - - case "border_width": - include_once("./Services/Style/Content/classes/class.ilTRBLBorderWidthInputGUI.php"); - $bw_input = new ilTRBLBorderWidthInputGUI($lng->txt("sty_".$var), $basepar); - $this->form_gui->addItem($bw_input); - break; - - case "border_style": - include_once("./Services/Style/Content/classes/class.ilTRBLBorderStyleInputGUI.php"); - $bw_input = new ilTRBLBorderStyleInputGUI($lng->txt("sty_".$var), $basepar); - $this->form_gui->addItem($bw_input); - break; - - case "trbl_color": - include_once("./Services/Style/Content/classes/class.ilTRBLColorPickerInputGUI.php"); - $col_input = new ilTRBLColorPickerInputGUI($lng->txt("sty_".$var), $basepar); - $col_input->setAcceptNamedColors(true); - $this->form_gui->addItem($col_input); - break; - - case "background_image": - include_once("./Services/Style/Content/classes/class.ilBackgroundImageInputGUI.php"); - $im_input = new ilBackgroundImageInputGUI($lng->txt("sty_".$var), $basepar); - $imgs = array(); - foreach ($this->object->getImages() as $entry) - { - $imgs[] = $entry["entry"]; - } - $im_input->setImages($imgs); - $this->form_gui->addItem($im_input); - break; - - case "background_position": - include_once("./Services/Style/Content/classes/class.ilBackgroundPositionInputGUI.php"); - $im_input = new ilBackgroundPositionInputGUI($lng->txt("sty_".$var), $basepar); - $this->form_gui->addItem($im_input); - break; - } - } - } - - // custom parameters - $sh = new ilFormSectionHeaderGUI(); - $sh->setTitle($lng->txt("sty_custom")); - $this->form_gui->addItem($sh); - - // custom parameters - $ti = new ilTextInputGUI($this->lng->txt("sty_custom_par"), "custom_par"); - $ti->setMaxLength(300); - $ti->setSize(80); - $ti->setMulti(true); - $ti->setInfo($this->lng->txt("sty_custom_par_info")); - $this->form_gui->addItem($ti); - - - // save and cancel commands - $this->form_gui->addCommandButton("updateTagStyle", $lng->txt("save_return")); - $this->form_gui->addCommandButton("refreshTagStyle", $lng->txt("save_refresh")); - -// $this->form_gui->setTitle($lng->txt("edit")); - $this->form_gui->setFormAction($this->ctrl->getFormAction($this)); - } - - /** - * FORM: Get current values from persistent object. - * - */ - public function getValues() - { - $style = $this->object->getStyle(); - $cur = explode(".",$_GET["tag"]); - $cur_tag = $cur[0]; - $cur_class = $cur[1]; - $cur_parameters = $this->extractParametersOfTag($cur_tag, $cur_class, $style, $_GET["style_type"], - (int) $_GET["mq_id"], false); - $parameters = ilObjStyleSheet::_getStyleParameters(); - foreach($parameters as $p => $v) - { - $filtered_groups = ilObjStyleSheet::_getFilteredGroups(); - if (is_array($filtered_groups[$v["group"]]) && !in_array($cur_tag, $filtered_groups[$v["group"]])) - { - continue; - } - $p = explode(".", $p); - $p = $p[0]; - $input = $this->form_gui->getItemByPostVar($p); - switch ($v["input"]) - { - case "": - break; - - case "trbl_numeric": - case "border_width": - case "border_style": - case "trbl_color": - $input->setAllValue($cur_parameters[$v["subpar"][0]]); - $input->setTopValue($cur_parameters[$v["subpar"][1]]); - $input->setRightValue($cur_parameters[$v["subpar"][2]]); - $input->setBottomValue($cur_parameters[$v["subpar"][3]]); - $input->setLeftValue($cur_parameters[$v["subpar"][4]]); - break; - - default: - $input->setValue($cur_parameters[$p]); - break; - } - } - - $cust_parameters = $this->extractParametersOfTag($cur_tag, $cur_class, $style, $_GET["style_type"], - (int) $_GET["mq_id"], true); - $vals = array(); - foreach ($cust_parameters as $k => $c) - { - $vals[] = $k.": ".$c; - } - $input = $this->form_gui->getItemByPostVar("custom_par"); - $input->setValue($vals); - } - - /** - * export style - */ - function exportStyleObject() - { - include_once("./Services/Export/classes/class.ilExport.php"); - $exp = new ilExport(); - $r = $exp->exportObject($this->object->getType(),$this->object->getId()); - - ilUtil::deliverFile($r["directory"]."/".$r["file"], $r["file"], '', false, true); - } - - function extractParametersOfTag($a_tag, $a_class, $a_style, $a_type, $a_mq_id = 0, $a_custom = false) - { - $parameters = array(); - foreach($a_style as $tag) - { - foreach($tag as $par) - { - if ($par["tag"] == $a_tag && $par["class"] == $a_class - && $par["type"] == $a_type && (int) $a_mq_id == (int) $par["mq_id"] - && (int) $a_custom == (int) $par["custom"]) - { - $parameters[$par["parameter"]] = $par["value"]; - } - } - } - return $parameters; - } - - /** - * add style parameter - */ - function newStyleParameterObject() - { - $this->object->addParameter($_POST["tag"], $_POST["parameter"]); - $this->editObject(); - } - - /** - * refresh style sheet - */ - function refreshObject() - { - $this->object->setTitle($_POST["style_title"]); - $this->object->setDescription($_POST["style_description"]); - - foreach($_POST["styval"] as $id => $value) - { - $this->object->updateStyleParameter($id, $value); - } - $this->object->update(); - $this->editObject(); - } - - /** - * display deletion confirmation screen - * - * @access public - */ - function deleteObject($a_error = false) - { - //$this->setTabs(); - - // display confirmation message - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($this->ctrl->getFormAction($this)); - $cgui->setHeaderText($this->lng->txt("info_delete_sure")); - $cgui->setCancel($this->lng->txt("cancel"), "cancelDelete"); - $cgui->setConfirm($this->lng->txt("confirm"), "confirmedDelete"); - - $caption = ilUtil::getImageTagByType("sty", $this->tpl->tplPath). - " ".ilObject::_lookupTitle($this->object->getId()); - - $cgui->addItem("id[]", "", $caption); - - $this->tpl->setContent($cgui->getHTML()); - } - - - /** - * cancel oobject deletion - */ - function cancelDeleteObject() - { - $this->ctrl->returnToParent($this); - } - - /** - * delete selected style objects - */ - function confirmedDeleteObject() - { - $this->object->delete(); - - $this->ctrl->returnToParent($this); - } - - /** - * delete style parameters - */ - function deleteStyleParameterObject() - { - if (is_array($_POST["sty_select"])) - { - foreach($_POST["sty_select"] as $id => $dummy) - { - $this->object->deleteParameter($id); - } - } - $this->object->read(); - $this->object->writeCSSFile(); - $this->editObject(); - } - - /** - * save style sheet - */ - function saveObject() - { - if(!trim($_POST["style_title"])) - { - $this->ctrl->redirect($this, "create"); - } - - // import from basic zip file - $imp = new ilImport(); - $style_id = $imp->importObject(null, ilObjStyleSheet::getBasicZipPath(), "style.zip", "sty", - $a_comp = "Services/Style", true); - - require_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $newObj = new ilObjStyleSheet($style_id); - //$newObj->create(); - $newObj->setTitle(ilUtil::stripSlashes($_POST["style_title"])); - $newObj->setDescription(ilUtil::stripSlashes($_POST["style_description"])); - $newObj->update(); - - ilObjStyleSheet::_addMissingStyleClassesToStyle($newObj->getId()); - - // assign style to style sheet folder, - // if parent is style sheet folder - if ($_GET["ref_id"] > 0) - { - - $fold = ilObjectFactory::getInstanceByRefId($_GET["ref_id"]); - if ($fold->getType() == "stys") - { - include_once("./Services/Style/Content/classes/class.ilContentStyleSettings.php"); - $cont_style_settings = new ilContentStyleSettings(); - $cont_style_settings->addStyle($newObj->getId()); - $cont_style_settings->update(); - - ilObjStyleSheet::_writeStandard($newObj->getId(), "1"); - $this->ctrl->returnToParent($this); - } - } - - return $newObj->getId(); - } - - /** - * save style sheet - */ - function copyStyleObject() - { - if ($_POST["source_style"] > 0) - { - $style_obj = ilObjectFactory::getInstanceByObjId($_POST["source_style"]); - $new_id = $style_obj->ilClone(); - } - - // assign style to style sheet folder, - // if parent is style sheet folder - if ($_GET["ref_id"] > 0) - { - - $fold = ilObjectFactory::getInstanceByRefId($_GET["ref_id"]); - if ($fold->getType() == "stys") - { - include_once("./Services/Style/Content/classes/class.ilContentStyleSettings.php"); - $cont_style_settings = new ilContentStyleSettings(); - $cont_style_settings->addStyle($new_id); - $cont_style_settings->update(); - ilObjStyleSheet::_writeStandard($new_id, "1"); - $this->ctrl->returnToParent($this); - } - } - - return $new_id; - } - - /** - * import style sheet - */ - function importStyleObject() - { - // check file - $source = $_FILES["importfile"]["tmp_name"]; - if (($source == 'none') || (!$source)) - { - $this->ilias->raiseError("No file selected!",$this->ilias->error_obj->MESSAGE); - } - - // check correct file type - $info = pathinfo($_FILES["importfile"]["name"]); - if (strtolower($info["extension"]) != "zip" && strtolower($info["extension"]) != "xml") - { - $this->ilias->raiseError("File must be a zip or xml file!",$this->ilias->error_obj->MESSAGE); - } - - // new import - $fname = explode("_", $_FILES["importfile"]["name"]); - if (strtolower($info["extension"]) == "zip" && $fname[4] == "sty") - { - include_once("./Services/Export/classes/class.ilImport.php"); - $imp = new ilImport(); - $new_id = $imp->importObject(null, $_FILES["importfile"]["tmp_name"], - $_FILES["importfile"]["name"], "sty"); - if ($new_id > 0) - { - $newObj = ilObjectFactory::getInstanceByObjId($new_id); - } - } - else // old import - { - require_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); - $newObj = new ilObjStyleSheet(); - $newObj->import($_FILES["importfile"]); - } - - // assign style to style sheet folder, - // if parent is style sheet folder - if ($_GET["ref_id"] > 0) - { - $fold = ilObjectFactory::getInstanceByRefId($_GET["ref_id"]); - if ($fold->getType() == "stys") - { - include_once("./Services/Style/Content/classes/class.ilContentStyleSettings.php"); - $cont_style_settings = new ilContentStyleSettings(); - $cont_style_settings->addStyle($newObj->getId()); - $cont_style_settings->update(); - ilObjStyleSheet::_writeStandard($newObj->getId(), "1"); - $this->ctrl->returnToParent($this); - } - } - return $newObj->getId(); - } - - /** - * After import - * - * @param - * @return - */ - function afterImport(ilObject $a_new_obj) - { - - } - - - /** - * update style sheet - */ - function cancelObject() - { - $lng = $this->lng; - - ilUtil::sendInfo($lng->txt("msg_cancel"), true); - $this->ctrl->returnToParent($this); - } - - /** - * admin and normal tabs are equal for roles - */ - function getAdminTabs() - { - $this->getTabs(); - } - - /** - * output tabs - */ - function setTabs() - { - $lng = $this->lng; - - $this->getTabs($this->tabs_gui); - - if (strtolower(get_class($this->object)) == "ilobjstylesheet") - { - $this->tpl->setVariable("HEADER", $this->object->getTitle()); - } - else - { - $this->tpl->setVariable("HEADER", $lng->txt("create_stylesheet")); - } - } - - /** - * adds tabs to tab gui object - * - * @param object $tabs_gui ilTabsGUI object - */ - function getTabs() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs; - $ilHelp = $this->help; - - $ilHelp->setScreenIdComponent("sty"); - - if ($ilCtrl->getCmd() == "editTagStyle") - { - // back to upper context - $this->tabs_gui->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTarget($this, "edit")); - - $t = explode(".", $_GET["tag"]); - $t2 = explode(":", $t[1]); - $pc = $this->object->_getPseudoClasses($t[0]); - if (is_array($pc) && count($pc) > 0) - { - // style classes - $ilCtrl->setParameter($this, "tag", $t[0].".".$t2[0]); - $this->tabs_gui->addTarget("sty_tag_normal", - $this->ctrl->getLinkTarget($this, "editTagStyle"), array("editTagStyle", ""), - get_class($this)); - if ($t2[1] == "") - { - $ilTabs->setTabActive("sty_tag_normal"); - } - - foreach ($pc as $p) - { - // style classes - $ilCtrl->setParameter($this, "tag", $t[0].".".$t2[0].":".$p); - $this->tabs_gui->addTarget("sty_tag_".$p, - $this->ctrl->getLinkTarget($this, "editTagStyle"), array("editTagStyle", ""), - get_class($this)); - if ($t2[1] == $p) - { - $ilTabs->setTabActive("sty_tag_".$p); - } - } - $ilCtrl->setParameter($this, "tag", $_GET["tag"]); - } - } - else - { - // back to upper context - $this->tabs_gui->setBackTarget($lng->txt("back"), - $this->ctrl->getLinkTarget($this, "returnToUpperContext")); - - // style classes - $this->tabs_gui->addTarget("sty_style_chars", - $this->ctrl->getLinkTarget($this, "edit"), array("edit", ""), - get_class($this)); - - // colors - $this->tabs_gui->addTarget("sty_colors", - $this->ctrl->getLinkTarget($this, "listColors"), "listColors", - get_class($this)); - - // media queries - $this->tabs_gui->addTarget("sty_media_queries", - $this->ctrl->getLinkTarget($this, "listMediaQueries"), "listMediaQueries", - get_class($this)); - - // images - $this->tabs_gui->addTarget("sty_images", - $this->ctrl->getLinkTarget($this, "listImages"), "listImages", - get_class($this)); - - // table templates - $this->tabs_gui->addTarget("sty_templates", - $this->ctrl->getLinkTarget($this, "listTemplates"), "listTemplates", - get_class($this)); - - // settings - $this->tabs_gui->addTarget("settings", - $this->ctrl->getLinkTarget($this, "properties"), "properties", - get_class($this)); - - // accordiontest + $this->writeStylePar($cur_tag, $cur_class, $basepar, $in->getValue(), $_GET["style_type"], (int) $_GET["mq_id"]); + break; + + case "color": + $color = trim($_POST[$basepar]); + if ($color != "" && trim(substr($color, 0, 1) != "!")) { + $color = "#" . $color; + } + $this->writeStylePar($cur_tag, $cur_class, $basepar, $color, $_GET["style_type"], (int) $_GET["mq_id"]); + break; + + case "trbl_numeric": + case "border_width": + case "border_style": + $in = $this->form_gui->getItemByPostVar($basepar); + $this->writeStylePar($cur_tag, $cur_class, $v["subpar"][0], $in->getAllValue(), $_GET["style_type"], (int) $_GET["mq_id"]); + $this->writeStylePar($cur_tag, $cur_class, $v["subpar"][1], $in->getTopValue(), $_GET["style_type"], (int) $_GET["mq_id"]); + $this->writeStylePar($cur_tag, $cur_class, $v["subpar"][2], $in->getRightValue(), $_GET["style_type"], (int) $_GET["mq_id"]); + $this->writeStylePar($cur_tag, $cur_class, $v["subpar"][3], $in->getBottomValue(), $_GET["style_type"], (int) $_GET["mq_id"]); + $this->writeStylePar($cur_tag, $cur_class, $v["subpar"][4], $in->getLeftValue(), $_GET["style_type"], (int) $_GET["mq_id"]); + break; + + case "trbl_color": + $in = $this->form_gui->getItemByPostVar($basepar); + $tblr_p = array(0 => "getAllValue", 1 => "getTopValue", 2 => "getRightValue", + 3 => "getBottomValue", 4 => "getLeftValue"); + foreach ($tblr_p as $k => $func) { + $val = trim($in->$func()); + $val = (($in->getAcceptNamedColors() && substr($val, 0, 1) == "!") + || $val == "") + ? $val + : "#" . $val; + $this->writeStylePar($cur_tag, $cur_class, $v["subpar"][$k], $val, $_GET["style_type"], (int) $_GET["mq_id"]); + } + break; + + case "background_position": + $in = $this->form_gui->getItemByPostVar($basepar); + $this->writeStylePar($cur_tag, $cur_class, $basepar, $in->getValue(), $_GET["style_type"], (int) $_GET["mq_id"]); + break; + + default: + $this->writeStylePar($cur_tag, $cur_class, $basepar, $_POST[$basepar], $_GET["style_type"], (int) $_GET["mq_id"]); + break; + } + } + + // write custom parameter + $this->object->deleteCustomStylePars($cur_tag, $cur_class, $_GET["style_type"], (int) $_GET["mq_id"]); + if (is_array($_POST["custom_par"])) { + foreach ($_POST["custom_par"] as $cpar) { + $par_arr = explode(":", $cpar); + if (count($par_arr) == 2) { + $par = trim($par_arr[0]); + $val = trim(str_replace(";", "", $par_arr[1])); + $this->writeStylePar($cur_tag, $cur_class, $par, $val, $_GET["style_type"], (int) $_GET["mq_id"], true); + } + } + } + + $this->object->update(); + } + + public function writeStylePar($cur_tag, $cur_class, $par, $value, $a_type, $a_mq_id, $a_custom = false) + { + // echo $_GET["mq_id"]."-"; + // echo $a_mq_id."-"; exit; + if ($a_type == "") { + return; + } + + if ($value != "") { + $this->object->replaceStylePar($cur_tag, $cur_class, $par, $value, $a_type, $a_mq_id, $a_custom); + } else { + $this->object->deleteStylePar($cur_tag, $cur_class, $par, $a_type, $a_mq_id, $a_custom); + } + } + + /** + * Edit tag style. + * + */ + public function editTagStyleObject() + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + // media query selector + $mqs = $this->object->getMediaQueries(); + if (count($mqs) > 0) { + // + $options = array( + "" => $lng->txt("sty_default"), + ); + foreach ($mqs as $mq) { + $options[$mq["id"]] = $mq["mquery"]; + } + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $si = new ilSelectInputGUI("@media", "mq_id"); + $si->setOptions($options); + $si->setValue((int) $_GET["mq_id"]); + $ilToolbar->addInputItem($si, true); + $ilToolbar->setFormAction($ilCtrl->getFormAction($this)); + $ilToolbar->addFormButton($lng->txt("sty_switch"), "switchMQuery"); + } + + // workaround to include default rte styles + //if (in_array($_GET["style_type"], array("rte_menu"))) + if ($this->super_type == "rte") { + $tpl->addCss("Modules/Scorm2004/templates/default/player.css"); + include_once("./Modules/Scorm2004/classes/ilSCORM13Player.php"); + $tpl->addInlineCss(ilSCORM13Player::getInlineCss()); + } + + $cur = explode(".", $_GET["tag"]); + $cur_tag = $cur[0]; + $cur_class = $cur[1]; + + $this->initTagStyleForm("edit", $cur_tag); + $this->getValues(); + $this->outputTagStyleEditScreen(); + } + + /** + * Switch media query + * + * @param + * @return + */ + public function switchMQueryObject() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameter($this, "mq_id", (int) $_POST["mq_id"]); + $ilCtrl->redirect($this, "editTagStyle"); + } + + + /** + * Output tag style edit screen. + */ + public function outputTagStyleEditScreen() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + // set style sheet + $tpl->setCurrentBlock("ContentStyle"); + $tpl->setVariable( + "LOCATION_CONTENT_STYLESHEET", + ilObjStyleSheet::getContentStylePath($this->object->getId()) + ); + + $ts_tpl = new ilTemplate("tpl.style_tag_edit.html", true, true, "Services/Style/Content"); + + $cur = explode(".", $_GET["tag"]); + $cur_tag = $cur[0]; + $cur_class = $cur[1]; + + $ts_tpl->setVariable( + "EXAMPLE", + ilObjStyleSheetGUI::getStyleExampleHTML($_GET["style_type"], $cur_class) + ); + + $ts_tpl->setVariable( + "FORM", + $this->form_gui->getHtml() + ); + + $tpl->setTitle($cur_class . " (" . $lng->txt("sty_type_" . $_GET["style_type"]) . ")"); + + $tpl->setContent($ts_tpl->get()); + } + + + /** + * Init tag style editing form + * + * @param int $a_mode Form Edit Mode (IL_FORM_EDIT | IL_FORM_CREATE) + */ + public function initTagStyleForm($a_mode, $a_cur_tag) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $ilCtrl->saveParameter($this, array("mq_id")); + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form_gui = new ilPropertyFormGUI(); + + $avail_pars = $this->object->getAvailableParameters(); + $groups = $this->object->getStyleParameterGroups(); + + // output select lists + foreach ($groups as $k => $group) { + // filter groups of properties that should only be + // displayed with matching tag + $filtered_groups = ilObjStyleSheet::_getFilteredGroups(); + if (is_array($filtered_groups[$k]) && !in_array($a_cur_tag, $filtered_groups[$k])) { + continue; + } + + $sh = new ilFormSectionHeaderGUI(); + $sh->setTitle($lng->txt("sty_" . $k)); + $this->form_gui->addItem($sh); + + foreach ($group as $par) { + $basepar = explode(".", $par); + $basepar = $basepar[0]; + + $var = str_replace("-", "_", $basepar); + $up_par = strtoupper($var); + + switch (ilObjStyleSheet::_getStyleParameterInputType($par)) { + case "select": + $sel_input = new ilSelectInputGUI($lng->txt("sty_" . $var), $basepar); + $options = array("" => ""); + foreach ($avail_pars[$par] as $p) { + $options[$p] = $p; + } + $sel_input->setOptions($options); + $this->form_gui->addItem($sel_input); + break; + + case "text": + $text_input = new ilTextInputGUI($lng->txt("sty_" . $var), $basepar); + $text_input->setMaxLength(200); + $text_input->setSize(20); + $this->form_gui->addItem($text_input); + break; + + case "fontsize": + include_once("./Services/Style/Content/classes/class.ilFontSizeInputGUI.php"); + $fs_input = new ilFontSizeInputGUI($lng->txt("sty_" . $var), $basepar); + $this->form_gui->addItem($fs_input); + break; + + case "numeric_no_perc": + case "numeric": + include_once("./Services/Style/Content/classes/class.ilNumericStyleValueInputGUI.php"); + $num_input = new ilNumericStyleValueInputGUI($lng->txt("sty_" . $var), $basepar); + if (ilObjStyleSheet::_getStyleParameterInputType($par) == "numeric_no_perc") { + $num_input->setAllowPercentage(false); + } + $this->form_gui->addItem($num_input); + break; + + case "percentage": + $per_input = new ilNumberInputGUI($lng->txt("sty_" . $var), $basepar); + $per_input->setMinValue(0); + $per_input->setMaxValue(100); + $per_input->setMaxLength(3); + $per_input->setSize(3); + $this->form_gui->addItem($per_input); + break; + + case "color": + //include_once("./Services/Style/classes/class.ilNumericStyleValueInputGUI.php"); + $col_input = new ilColorPickerInputGUI($lng->txt("sty_" . $var), $basepar); + $col_input->setDefaultColor(""); + $col_input->setAcceptNamedColors(true); + $this->form_gui->addItem($col_input); + break; + + case "trbl_numeric": + include_once("./Services/Style/Content/classes/class.ilTRBLNumericStyleValueInputGUI.php"); + $num_input = new ilTRBLNumericStyleValueInputGUI($lng->txt("sty_" . $var), $basepar); + if (ilObjStyleSheet::_getStyleParameterInputType($par) == "trbl_numeric_no_perc") { + $num_input->setAllowPercentage(false); + } + $this->form_gui->addItem($num_input); + break; + + case "border_width": + include_once("./Services/Style/Content/classes/class.ilTRBLBorderWidthInputGUI.php"); + $bw_input = new ilTRBLBorderWidthInputGUI($lng->txt("sty_" . $var), $basepar); + $this->form_gui->addItem($bw_input); + break; + + case "border_style": + include_once("./Services/Style/Content/classes/class.ilTRBLBorderStyleInputGUI.php"); + $bw_input = new ilTRBLBorderStyleInputGUI($lng->txt("sty_" . $var), $basepar); + $this->form_gui->addItem($bw_input); + break; + + case "trbl_color": + include_once("./Services/Style/Content/classes/class.ilTRBLColorPickerInputGUI.php"); + $col_input = new ilTRBLColorPickerInputGUI($lng->txt("sty_" . $var), $basepar); + $col_input->setAcceptNamedColors(true); + $this->form_gui->addItem($col_input); + break; + + case "background_image": + include_once("./Services/Style/Content/classes/class.ilBackgroundImageInputGUI.php"); + $im_input = new ilBackgroundImageInputGUI($lng->txt("sty_" . $var), $basepar); + $imgs = array(); + foreach ($this->object->getImages() as $entry) { + $imgs[] = $entry["entry"]; + } + $im_input->setImages($imgs); + $this->form_gui->addItem($im_input); + break; + + case "background_position": + include_once("./Services/Style/Content/classes/class.ilBackgroundPositionInputGUI.php"); + $im_input = new ilBackgroundPositionInputGUI($lng->txt("sty_" . $var), $basepar); + $this->form_gui->addItem($im_input); + break; + } + } + } + + // custom parameters + $sh = new ilFormSectionHeaderGUI(); + $sh->setTitle($lng->txt("sty_custom")); + $this->form_gui->addItem($sh); + + // custom parameters + $ti = new ilTextInputGUI($this->lng->txt("sty_custom_par"), "custom_par"); + $ti->setMaxLength(300); + $ti->setSize(80); + $ti->setMulti(true); + $ti->setInfo($this->lng->txt("sty_custom_par_info")); + $this->form_gui->addItem($ti); + + + // save and cancel commands + $this->form_gui->addCommandButton("updateTagStyle", $lng->txt("save_return")); + $this->form_gui->addCommandButton("refreshTagStyle", $lng->txt("save_refresh")); + + // $this->form_gui->setTitle($lng->txt("edit")); + $this->form_gui->setFormAction($this->ctrl->getFormAction($this)); + } + + /** + * FORM: Get current values from persistent object. + * + */ + public function getValues() + { + $style = $this->object->getStyle(); + $cur = explode(".", $_GET["tag"]); + $cur_tag = $cur[0]; + $cur_class = $cur[1]; + $cur_parameters = $this->extractParametersOfTag( + $cur_tag, + $cur_class, + $style, + $_GET["style_type"], + (int) $_GET["mq_id"], + false + ); + $parameters = ilObjStyleSheet::_getStyleParameters(); + foreach ($parameters as $p => $v) { + $filtered_groups = ilObjStyleSheet::_getFilteredGroups(); + if (is_array($filtered_groups[$v["group"]]) && !in_array($cur_tag, $filtered_groups[$v["group"]])) { + continue; + } + $p = explode(".", $p); + $p = $p[0]; + $input = $this->form_gui->getItemByPostVar($p); + switch ($v["input"]) { + case "": + break; + + case "trbl_numeric": + case "border_width": + case "border_style": + case "trbl_color": + $input->setAllValue($cur_parameters[$v["subpar"][0]]); + $input->setTopValue($cur_parameters[$v["subpar"][1]]); + $input->setRightValue($cur_parameters[$v["subpar"][2]]); + $input->setBottomValue($cur_parameters[$v["subpar"][3]]); + $input->setLeftValue($cur_parameters[$v["subpar"][4]]); + break; + + default: + $input->setValue($cur_parameters[$p]); + break; + } + } + + $cust_parameters = $this->extractParametersOfTag( + $cur_tag, + $cur_class, + $style, + $_GET["style_type"], + (int) $_GET["mq_id"], + true + ); + $vals = array(); + foreach ($cust_parameters as $k => $c) { + $vals[] = $k . ": " . $c; + } + $input = $this->form_gui->getItemByPostVar("custom_par"); + $input->setValue($vals); + } + + /** + * export style + */ + public function exportStyleObject() + { + include_once("./Services/Export/classes/class.ilExport.php"); + $exp = new ilExport(); + $r = $exp->exportObject($this->object->getType(), $this->object->getId()); + + ilUtil::deliverFile($r["directory"] . "/" . $r["file"], $r["file"], '', false, true); + } + + public function extractParametersOfTag($a_tag, $a_class, $a_style, $a_type, $a_mq_id = 0, $a_custom = false) + { + $parameters = array(); + foreach ($a_style as $tag) { + foreach ($tag as $par) { + if ($par["tag"] == $a_tag && $par["class"] == $a_class + && $par["type"] == $a_type && (int) $a_mq_id == (int) $par["mq_id"] + && (int) $a_custom == (int) $par["custom"]) { + $parameters[$par["parameter"]] = $par["value"]; + } + } + } + return $parameters; + } + + /** + * add style parameter + */ + public function newStyleParameterObject() + { + $this->object->addParameter($_POST["tag"], $_POST["parameter"]); + $this->editObject(); + } + + /** + * refresh style sheet + */ + public function refreshObject() + { + $this->object->setTitle($_POST["style_title"]); + $this->object->setDescription($_POST["style_description"]); + + foreach ($_POST["styval"] as $id => $value) { + $this->object->updateStyleParameter($id, $value); + } + $this->object->update(); + $this->editObject(); + } + + /** + * display deletion confirmation screen + * + * @access public + */ + public function deleteObject($a_error = false) + { + //$this->setTabs(); + + // display confirmation message + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($this->ctrl->getFormAction($this)); + $cgui->setHeaderText($this->lng->txt("info_delete_sure")); + $cgui->setCancel($this->lng->txt("cancel"), "cancelDelete"); + $cgui->setConfirm($this->lng->txt("confirm"), "confirmedDelete"); + + $caption = ilUtil::getImageTagByType("sty", $this->tpl->tplPath) . + " " . ilObject::_lookupTitle($this->object->getId()); + + $cgui->addItem("id[]", "", $caption); + + $this->tpl->setContent($cgui->getHTML()); + } + + + /** + * cancel oobject deletion + */ + public function cancelDeleteObject() + { + $this->ctrl->returnToParent($this); + } + + /** + * delete selected style objects + */ + public function confirmedDeleteObject() + { + $this->object->delete(); + + $this->ctrl->returnToParent($this); + } + + /** + * delete style parameters + */ + public function deleteStyleParameterObject() + { + if (is_array($_POST["sty_select"])) { + foreach ($_POST["sty_select"] as $id => $dummy) { + $this->object->deleteParameter($id); + } + } + $this->object->read(); + $this->object->writeCSSFile(); + $this->editObject(); + } + + /** + * save style sheet + */ + public function saveObject() + { + if (!trim($_POST["style_title"])) { + $this->ctrl->redirect($this, "create"); + } + + // import from basic zip file + $imp = new ilImport(); + $style_id = $imp->importObject( + null, + ilObjStyleSheet::getBasicZipPath(), + "style.zip", + "sty", + $a_comp = "Services/Style", + true + ); + + require_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $newObj = new ilObjStyleSheet($style_id); + //$newObj->create(); + $newObj->setTitle(ilUtil::stripSlashes($_POST["style_title"])); + $newObj->setDescription(ilUtil::stripSlashes($_POST["style_description"])); + $newObj->update(); + + ilObjStyleSheet::_addMissingStyleClassesToStyle($newObj->getId()); + + // assign style to style sheet folder, + // if parent is style sheet folder + if ($_GET["ref_id"] > 0) { + $fold = ilObjectFactory::getInstanceByRefId($_GET["ref_id"]); + if ($fold->getType() == "stys") { + include_once("./Services/Style/Content/classes/class.ilContentStyleSettings.php"); + $cont_style_settings = new ilContentStyleSettings(); + $cont_style_settings->addStyle($newObj->getId()); + $cont_style_settings->update(); + + ilObjStyleSheet::_writeStandard($newObj->getId(), "1"); + $this->ctrl->returnToParent($this); + } + } + + return $newObj->getId(); + } + + /** + * save style sheet + */ + public function copyStyleObject() + { + if ($_POST["source_style"] > 0) { + $style_obj = ilObjectFactory::getInstanceByObjId($_POST["source_style"]); + $new_id = $style_obj->ilClone(); + } + + // assign style to style sheet folder, + // if parent is style sheet folder + if ($_GET["ref_id"] > 0) { + $fold = ilObjectFactory::getInstanceByRefId($_GET["ref_id"]); + if ($fold->getType() == "stys") { + include_once("./Services/Style/Content/classes/class.ilContentStyleSettings.php"); + $cont_style_settings = new ilContentStyleSettings(); + $cont_style_settings->addStyle($new_id); + $cont_style_settings->update(); + ilObjStyleSheet::_writeStandard($new_id, "1"); + $this->ctrl->returnToParent($this); + } + } + + return $new_id; + } + + /** + * import style sheet + */ + public function importStyleObject() + { + // check file + $source = $_FILES["importfile"]["tmp_name"]; + if (($source == 'none') || (!$source)) { + $this->ilias->raiseError("No file selected!", $this->ilias->error_obj->MESSAGE); + } + + // check correct file type + $info = pathinfo($_FILES["importfile"]["name"]); + if (strtolower($info["extension"]) != "zip" && strtolower($info["extension"]) != "xml") { + $this->ilias->raiseError("File must be a zip or xml file!", $this->ilias->error_obj->MESSAGE); + } + + // new import + $fname = explode("_", $_FILES["importfile"]["name"]); + if (strtolower($info["extension"]) == "zip" && $fname[4] == "sty") { + include_once("./Services/Export/classes/class.ilImport.php"); + $imp = new ilImport(); + $new_id = $imp->importObject( + null, + $_FILES["importfile"]["tmp_name"], + $_FILES["importfile"]["name"], + "sty" + ); + if ($new_id > 0) { + $newObj = ilObjectFactory::getInstanceByObjId($new_id); + } + } else { // old import + require_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $newObj = new ilObjStyleSheet(); + $newObj->import($_FILES["importfile"]); + } + + // assign style to style sheet folder, + // if parent is style sheet folder + if ($_GET["ref_id"] > 0) { + $fold = ilObjectFactory::getInstanceByRefId($_GET["ref_id"]); + if ($fold->getType() == "stys") { + include_once("./Services/Style/Content/classes/class.ilContentStyleSettings.php"); + $cont_style_settings = new ilContentStyleSettings(); + $cont_style_settings->addStyle($newObj->getId()); + $cont_style_settings->update(); + ilObjStyleSheet::_writeStandard($newObj->getId(), "1"); + $this->ctrl->returnToParent($this); + } + } + return $newObj->getId(); + } + + /** + * After import + * + * @param + * @return + */ + public function afterImport(ilObject $a_new_obj) + { + } + + + /** + * update style sheet + */ + public function cancelObject() + { + $lng = $this->lng; + + ilUtil::sendInfo($lng->txt("msg_cancel"), true); + $this->ctrl->returnToParent($this); + } + + /** + * admin and normal tabs are equal for roles + */ + public function getAdminTabs() + { + $this->getTabs(); + } + + /** + * output tabs + */ + public function setTabs() + { + $lng = $this->lng; + + $this->getTabs($this->tabs_gui); + + if (strtolower(get_class($this->object)) == "ilobjstylesheet") { + $this->tpl->setVariable("HEADER", $this->object->getTitle()); + } else { + $this->tpl->setVariable("HEADER", $lng->txt("create_stylesheet")); + } + } + + /** + * adds tabs to tab gui object + * + * @param object $tabs_gui ilTabsGUI object + */ + public function getTabs() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + $ilHelp = $this->help; + + $ilHelp->setScreenIdComponent("sty"); + + if ($ilCtrl->getCmd() == "editTagStyle") { + // back to upper context + $this->tabs_gui->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, "edit") + ); + + $t = explode(".", $_GET["tag"]); + $t2 = explode(":", $t[1]); + $pc = $this->object->_getPseudoClasses($t[0]); + if (is_array($pc) && count($pc) > 0) { + // style classes + $ilCtrl->setParameter($this, "tag", $t[0] . "." . $t2[0]); + $this->tabs_gui->addTarget( + "sty_tag_normal", + $this->ctrl->getLinkTarget($this, "editTagStyle"), + array("editTagStyle", ""), + get_class($this) + ); + if ($t2[1] == "") { + $ilTabs->setTabActive("sty_tag_normal"); + } + + foreach ($pc as $p) { + // style classes + $ilCtrl->setParameter($this, "tag", $t[0] . "." . $t2[0] . ":" . $p); + $this->tabs_gui->addTarget( + "sty_tag_" . $p, + $this->ctrl->getLinkTarget($this, "editTagStyle"), + array("editTagStyle", ""), + get_class($this) + ); + if ($t2[1] == $p) { + $ilTabs->setTabActive("sty_tag_" . $p); + } + } + $ilCtrl->setParameter($this, "tag", $_GET["tag"]); + } + } else { + // back to upper context + $this->tabs_gui->setBackTarget( + $lng->txt("back"), + $this->ctrl->getLinkTarget($this, "returnToUpperContext") + ); + + // style classes + $this->tabs_gui->addTarget( + "sty_style_chars", + $this->ctrl->getLinkTarget($this, "edit"), + array("edit", ""), + get_class($this) + ); + + // colors + $this->tabs_gui->addTarget( + "sty_colors", + $this->ctrl->getLinkTarget($this, "listColors"), + "listColors", + get_class($this) + ); + + // media queries + $this->tabs_gui->addTarget( + "sty_media_queries", + $this->ctrl->getLinkTarget($this, "listMediaQueries"), + "listMediaQueries", + get_class($this) + ); + + // images + $this->tabs_gui->addTarget( + "sty_images", + $this->ctrl->getLinkTarget($this, "listImages"), + "listImages", + get_class($this) + ); + + // table templates + $this->tabs_gui->addTarget( + "sty_templates", + $this->ctrl->getLinkTarget($this, "listTemplates"), + "listTemplates", + get_class($this) + ); + + // settings + $this->tabs_gui->addTarget( + "settings", + $this->ctrl->getLinkTarget($this, "properties"), + "properties", + get_class($this) + ); + + // accordiontest /* - $this->tabs_gui->addTarget("accordiontest", - $this->ctrl->getLinkTarget($this, "accordiontest"), "accordiontest", - get_class($this));*/ - } - - } - - /** - * adds tabs to tab gui object - * - * @param object $tabs_gui ilTabsGUI object - */ - function setSubTabs() - { - $lng = $this->lng; - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - - $types = ilObjStyleSheet::_getStyleSuperTypes(); - - foreach ($types as $super_type => $types) - { - // text block characteristics - $ilCtrl->setParameter($this, "style_type", $super_type); - $ilTabs->addSubTabTarget("sty_".$super_type."_char", - $this->ctrl->getLinkTarget($this, "edit"), array("edit", ""), - get_class($this)); - } - - $ilCtrl->setParameter($this, "style_type", $_GET["style_type"]); - } - - /** - * adds tabs to tab gui object - * - * @param object $tabs_gui ilTabsGUI object - */ - function setTemplatesSubTabs() - { - $lng = $this->lng; - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - - $types = ilObjStyleSheet::_getTemplateClassTypes(); - - foreach ($types as $t => $c) - { - $ilCtrl->setParameter($this, "temp_type", $t); - $ilTabs->addSubTabTarget("sty_".$t."_templates", - $this->ctrl->getLinkTarget($this, "listTemplates"), array("listTemplates", ""), - get_class($this)); - } - - $ilCtrl->setParameter($this, "temp_type", $_GET["temp_type"]); - } - - /** - * should be overwritten to add object specific items - * (repository items are preloaded) - */ - function addAdminLocatorItems($a_do_not_add_object = false) - { - $ilLocator = $this->locator; - - if ($_GET["admin_mode"] == "settings") // system settings - { - parent::addAdminLocatorItems(true); - - $ilLocator->addItem(ilObject::_lookupTitle( - ilObject::_lookupObjId($_GET["ref_id"])), - $this->ctrl->getLinkTargetByClass("ilobjstylesettingsgui", "")); - - if ($_GET["obj_id"] > 0) - { - $ilLocator->addItem($this->object->getTitle(), - $this->ctrl->getLinkTarget($this, "edit")); - } - } - else // repository administration - { - //? - } - - } - - function showUpperIcon() - { - $tree = $this->tree; - $tpl = $this->tpl; - $objDefinition = $this->obj_definition; - - if (strtolower($_GET["baseClass"]) == "iladministrationgui") - { - $tpl->setUpperIcon( - $this->ctrl->getLinkTargetByClass("ilcontentstylesettings", - "edit")); - } - else - { - // ? - } - } - - /** - * List images of style - */ - function listImagesObject() - { - $tpl = $this->tpl; - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $rbacsystem = $this->rbacsystem; - - if ($this->checkWrite()) - { - $ilToolbar->addButton($lng->txt("sty_add_image"), - $ilCtrl->getLinkTarget($this, "addImage")); - } - - include_once("./Services/Style/Content/classes/class.ilStyleImageTableGUI.php"); - $table_gui = new ilStyleImageTableGUI($this, "listImages", - $this->object); - $tpl->setContent($table_gui->getHTML()); - - } - - /** - * Add an image - */ - function addImageObject() - { - $tpl = $this->tpl; - - $this->initImageForm(); - $tpl->setContent($this->form_gui->getHTML()); - } - - /** - * Cancel Upload - */ - function cancelUploadObject() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirect($this, "listImages"); - } - - /** - * Upload image - */ - function uploadImageObject() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - - $this->initImageForm(); - - if ($this->form_gui->checkInput()) - { - $this->object->uploadImage($_FILES["image_file"]); - $ilCtrl->redirect($this, "listImages"); - } - else - { - //$this->form_gui->setImageFormValuesByPost(); - $tpl->setContent($this->form_gui->getHTML()); - } - - } - - /** - * Init image form - */ - function initImageForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form_gui = new ilPropertyFormGUI(); - - $this->form_gui->setTitle($lng->txt("sty_add_image")); - - $file_input = new ilImageFileInputGUI($lng->txt("sty_image_file"), "image_file"); - $file_input->setRequired(true); - $this->form_gui->addItem($file_input); - - $this->form_gui->addCommandButton("uploadImage", $lng->txt("upload")); - $this->form_gui->addCommandButton("cancelUpload", $lng->txt("cancel")); - $this->form_gui->setFormAction($ilCtrl->getFormAction($this)); - } - - /** - * Delete images - */ - function deleteImageObject() - { - $ilCtrl = $this->ctrl; - - $images = $this->object->getImages(); - - foreach ($images as $image) - { - if (is_array($_POST["file"]) && in_array($image["entry"], $_POST["file"])) - { - $this->object->deleteImage($image["entry"]); - } - } - $ilCtrl->redirect($this, "listImages"); - } - - /** - * Characteristic deletion confirmation screen - */ - function deleteCharacteristicConfirmationObject() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - -//var_dump($_POST); - - if (!is_array($_POST["char"]) || count($_POST["char"]) == 0) - { - ilUtil::sendInfo($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "edit"); - } - else - { - // check whether there are any core style classes included - $core_styles = ilObjStyleSheet::_getCoreStyles(); - foreach ($_POST["char"] as $char) - { - if (!empty($core_styles[$char])) - { - $this->deleteCoreCharMessage(); - return; - } - } - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("sty_confirm_char_deletion")); - $cgui->setCancel($lng->txt("cancel"), "cancelCharacteristicDeletion"); - $cgui->setConfirm($lng->txt("delete"), "deleteCharacteristic"); - - foreach ($_POST["char"] as $char) - { - $char_comp = explode(".", $char); - $cgui->addItem("char[]", $char, $char_comp[2]); - } - - $tpl->setContent($cgui->getHTML()); - } - } - - /** - * Message that appears, when user tries to delete core characteristics - * - * @param - * @return - */ - function deleteCoreCharMessage() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - - - $core_styles = ilObjStyleSheet::_getCoreStyles(); - $cnt = 0; - foreach ($_POST["char"] as $char) - { - if (!empty($core_styles[$char])) - { - $cnt++; - $char_comp = explode(".", $char); - $cgui->addItem("", "", $char_comp[2]); - } - else - { - $cgui->addHiddenItem("char[]", $char); - } - } - $all_core_styles = ($cnt == count($_POST["char"])) - ? true - : false; - - if ($all_core_styles) - { - $cgui->setHeaderText($lng->txt("sty_all_styles_obligatory")); - $cgui->setCancel($lng->txt("back"), "cancelCharacteristicDeletion"); - } - else - { - $cgui->setHeaderText($lng->txt("sty_some_styles_obligatory_delete_rest")); - $cgui->setCancel($lng->txt("cancel"), "cancelCharacteristicDeletion"); - $cgui->setConfirm($lng->txt("sty_delete_other_selected"), "deleteCharacteristicConfirmation"); - } - - $tpl->setContent($cgui->getHTML()); - } - - /** - * Cancel characteristic deletion - */ - function cancelCharacteristicDeletionObject() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - ilUtil::sendInfo($lng->txt("action_aborted"), true); - $ilCtrl->redirect($this, "edit"); - } - - /** - * Delete one or multiple style characteristic - */ - function deleteCharacteristicObject() - { - $ilCtrl = $this->ctrl; - - if (is_array($_POST["char"])) - { - foreach($_POST["char"] as $char) - { - $char_comp = explode(".", $char); - $type = $char_comp[0]; - $tag = $char_comp[1]; - $class = $char_comp[2]; - - $this->object->deleteCharacteristic($type, $tag, $class); - } - } - - $ilCtrl->redirect($this, "edit"); - } - - /** - * Add characteristic - */ - function addCharacteristicFormObject() - { - $tpl = $this->tpl; - - $this->initCharacteristicForm("create"); - $tpl->setContent($this->form_gui->getHTML()); - } - - /** - * Save Characteristic - */ - function saveCharacteristicObject() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - $this->initCharacteristicForm("create"); - - if ($this->form_gui->checkInput()) - { - if ($this->object->characteristicExists($_POST["new_characteristic"], $_GET["style_type"])) - { - $char_input = $this->form_gui->getItemByPostVar("new_characteristic"); - $char_input->setAlert($lng->txt("sty_characteristic_already_exists")); - } - else - { - $this->object->addCharacteristic($_POST["type"], $_POST["new_characteristic"]); - ilUtil::sendInfo($lng->txt("sty_added_characteristic"), true); - $ilCtrl->setParameter($this, "tag", - ilObjStyleSheet::_determineTag($_POST["type"]).".".$_POST["new_characteristic"]); - $ilCtrl->setParameter($this, "style_type", $_POST["type"]); - $ilCtrl->redirect($this, "editTagStyle"); - } - } - $this->form_gui->setValuesByPost(); - $tpl->setContent($this->form_gui->getHTML()); - } - - /** - * Init tag style editing form - * - * @param int $a_mode Form Edit Mode (IL_FORM_EDIT | IL_FORM_CREATE) - */ - public function initCharacteristicForm($a_mode) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form_gui = new ilPropertyFormGUI(); - - // title - $txt_input = new ilRegExpInputGUI($lng->txt("title"), "new_characteristic"); - $txt_input->setPattern("/^[a-zA-Z]+[a-zA-Z0-9]*$/"); - $txt_input->setNoMatchMessage($lng->txt("sty_msg_characteristic_must_only_include")." A-Z, a-z, 0-9"); - $txt_input->setRequired(true); - $this->form_gui->addItem($txt_input); - - // type - $all_super_types = ilObjStyleSheet::_getStyleSuperTypes(); - $types = $all_super_types[$this->super_type]; - $exp_types = array(); - foreach($types as $t) - { - if (ilObjStyleSheet::_isExpandable($t)) - { - $exp_types[$t] = $lng->txt("sty_type_".$t); - } - } - if (count($exp_types) > 1) - { - $type_input = new ilSelectInputGUI($lng->txt("sty_type"), "type"); - $type_input->setOptions($exp_types); - $type_input->setValue(key($exp_types)); - $this->form_gui->addItem($type_input); - } - else if (count($exp_types) == 1) - { - $hid_input = new ilHiddenInputGUI("type"); - $hid_input->setValue(key($exp_types)); - $this->form_gui->addItem($hid_input); - } - - $this->form_gui->setTitle($lng->txt("sty_add_characteristic")); - $this->form_gui->addCommandButton("saveCharacteristic", $lng->txt("save")); - $this->form_gui->addCommandButton("edit", $lng->txt("cancel")); - $this->form_gui->setFormAction($ilCtrl->getFormAction($this)); - } - - /** - * Get style example HTML - */ - static function getStyleExampleHTML($a_type, $a_class) - { - global $DIC; - - $lng = $DIC->language(); - - $c = explode(":", $a_class); - $a_class = $c[0]; - - $ex_tpl = new ilTemplate("tpl.style_example.html", true, true, "Services/Style/Content"); - - if ($ex_tpl->blockExists("Example_".$a_type)) - { - $ex_tpl->setCurrentBlock("Example_".$a_type); - } - else - { - $ex_tpl->setCurrentBlock("Example_default"); - } - $ex_tpl->setVariable("EX_CLASS", "ilc_".$a_type."_".$a_class); - $ex_tpl->setVariable("EX_TEXT", "ABC abc 123"); - if (in_array($a_type, array("media_cont", "qimg"))) - { - // - } - if (in_array($a_type, array("table", "table_caption"))) - { - $ex_tpl->setVariable("TXT_CAPTION", $lng->txt("sty_caption")); - } - if (in_array($a_class, array("OrderListItemHorizontal", "OrderListHorizontal"))) - { - $ex_tpl->setVariable("HOR", "Horizontal"); - } - $ex_tpl->parseCurrentBlock(); - - return $ex_tpl->get(); - } - - /** - * Save hide status for characteristics - */ - function saveHideStatusObject() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - //var_dump($_POST); - - foreach ($_POST["all_chars"] as $char) - { - $ca = explode(".", $char); - $this->object->saveHideStatus($ca[0], $ca[2], - (is_array($_POST["hide"]) && in_array($char, $_POST["hide"]))); - } - - ilUtil::sendInfo($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "edit"); - } - - /** - * Copy style classes - * - * @param - * @return - */ - function copyCharacteristicsObject() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if (!is_array($_POST["char"]) || count($_POST["char"]) == 0) - { - ilUtil::sendFailure($lng->txt("no_checkbox"), true); - } - else - { - $style_cp = implode("::", $_POST["char"]); - $style_cp = $this->object->getId().":::".$_GET["style_type"].":::".$style_cp; - $_SESSION["sty_copy"] = $style_cp; - ilUtil::sendSuccess($lng->txt("sty_copied_please_select_target"), true); - } - $ilCtrl->redirect($this, "edit"); - } - - /** - * Paste characteristics overview - * - * @param - * @return - */ - function pasteCharacteristicsOverviewObject() - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; - - $ilTabs->clearTargets(); - - include_once("./Services/Style/Content/classes/class.ilPasteStyleCharacteristicTableGUI.php"); - $table = new ilPasteStyleCharacteristicTableGUI($this, "pasteCharacteristicsOverview"); - - $tpl->setContent($table->getHTML()); - } - - /** - * Paste characteristics - * - * @param - * @return - */ - function pasteCharacteristicsObject() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if (is_array($_POST["title"])) - { - foreach ($_POST["title"] as $from_char => $to_title) - { - $fc = explode(".", $from_char); - - if ($_POST["conflict_action"][$from_char] == "overwrite" || - !$this->object->characteristicExists($to_title, $fc[0])) - { - $this->object->copyCharacteristic($_POST["from_style_id"], - $fc[0], $fc[2], $to_title); - } - } - ilObjStyleSheet::_writeUpToDate($this->object->getId(), false); - unset($_SESSION["sty_copy"]); - ilUtil::sendSuccess($lng->txt("sty_style_classes_copied"), true); - } - - $ilCtrl->redirect($this, "edit"); - } - - // - // Color management - // - - /** - * List colors of style - */ - function listColorsObject() - { - $tpl = $this->tpl; - $rbacsystem = $this->rbacsystem; - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - - if ($this->checkWrite()) - { - $ilToolbar->addButton($this->lng->txt("sty_add_color"), - $ilCtrl->getLinkTarget($this, "addColor")); - } - - include_once("./Services/Style/Content/classes/class.ilStyleColorTableGUI.php"); - $table_gui = new ilStyleColorTableGUI($this, "listColors", - $this->object); - $tpl->setContent($table_gui->getHTML()); - - } - - /** - * Add a color - */ - function addColorObject() - { - $tpl = $this->tpl; - - $this->initColorForm(); - $tpl->setContent($this->form_gui->getHTML()); - } - - /** - * Edit color - */ - function editColorObject() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameter($this, "c_name", $_GET["c_name"]); - $this->initColorForm("edit"); - $this->getColorFormValues(); - $tpl->setContent($this->form_gui->getHTML()); - } - - - /** - * Init color form - */ - function initColorForm($a_mode = "create") - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form_gui = new ilPropertyFormGUI(); - - $this->form_gui->setTitle($lng->txt("sty_add_color")); - - // name - $name_input = new ilRegExpInputGUI($lng->txt("sty_color_name"), "color_name"); - $name_input->setPattern("/^[a-zA-Z]+[a-zA-Z0-9]*$/"); - $name_input->setNoMatchMessage($lng->txt("sty_msg_color_must_only_include")." A-Z, a-z, 1-9"); - $name_input->setRequired(true); - $name_input->setSize(15); - $name_input->setMaxLength(15); - $this->form_gui->addItem($name_input); - - // code - $color_input = new ilColorPickerInputGUI($lng->txt("sty_color_code"), "color_code"); - $color_input->setRequired(true); - $color_input->setDefaultColor(""); - $this->form_gui->addItem($color_input); - - if ($a_mode == "create") - { - $this->form_gui->addCommandButton("saveColor", $lng->txt("save")); - $this->form_gui->addCommandButton("cancelColorSaving", $lng->txt("cancel")); - } - else - { - $this->form_gui->addCommandButton("updateColor", $lng->txt("save")); - $this->form_gui->addCommandButton("cancelColorSaving", $lng->txt("cancel")); - } - $this->form_gui->setFormAction($ilCtrl->getFormAction($this)); - } - - /** - * Set values for color editing - */ - function getColorFormValues() - { - if ($_GET["c_name"] != "") - { - $values["color_name"] = $_GET["c_name"]; - $values["color_code"] = $this->object->getColorCodeForName($_GET["c_name"]); - $this->form_gui->setValuesByArray($values); - } - } - - /** - * Cancel color saving - */ - function cancelColorSavingObject() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirect($this, "listColors"); - } - - /** - * Save color - */ - function saveColorObject() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->initColorForm(); - - if ($this->form_gui->checkInput()) - { - if ($this->object->colorExists($_POST["color_name"])) - { - $col_input = $this->form_gui->getItemByPostVar("color_name"); - $col_input->setAlert($lng->txt("sty_color_already_exists")); - } - else - { - $this->object->addColor($_POST["color_name"], - $_POST["color_code"]); - $ilCtrl->redirect($this, "listColors"); - } - } - $this->form_gui->setValuesByPost(); - $tpl->setContent($this->form_gui->getHTML()); - } - - /** - * Update color - */ - function updateColorObject() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->initColorForm("edit"); - - if ($this->form_gui->checkInput()) - { - if ($this->object->colorExists($_POST["color_name"]) && - $_POST["color_name"] != $_GET["c_name"]) - { - $col_input = $this->form_gui->getItemByPostVar("color_name"); - $col_input->setAlert($lng->txt("sty_color_already_exists")); - } - else - { - $this->object->updateColor($_GET["c_name"], $_POST["color_name"], - $_POST["color_code"]); - $ilCtrl->redirect($this, "listColors"); - } - } - $ilCtrl->setParameter($this, "c_name", $_GET["c_name"]); - $this->form_gui->setValuesByPost(); - $tpl->setContent($this->form_gui->getHTML()); - } - - /** - * Delete color confirmation - */ - function deleteColorConfirmationObject() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - if (!is_array($_POST["color"]) || count($_POST["color"]) == 0) - { - ilUtil::sendInfo($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "listColors"); - } - else - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("sty_confirm_color_deletion")); - $cgui->setCancel($lng->txt("cancel"), "cancelColorDeletion"); - $cgui->setConfirm($lng->txt("delete"), "deleteColor"); - - foreach ($_POST["color"] as $c) - { - $cgui->addItem("color[]", ilUtil::prepareFormOutput($c), $c); - } - - $tpl->setContent($cgui->getHTML()); - } - } - - /** - * Cancel color deletion - */ - function cancelColorDeletionObject() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirect($this, "listColors"); - } - - /** - * Delete colors - */ - function deleteColorObject() - { - $ilCtrl = $this->ctrl; - - if (is_array($_POST["color"])) - { - foreach ($_POST["color"] as $c) - { - $this->object->removeColor($c); - } - } - - $ilCtrl->redirect($this, "listColors"); - } - - // - // Media query management - // - - /** - * List media queries of style - */ - function listMediaQueriesObject() - { - $tpl = $this->tpl; - $rbacsystem = $this->rbacsystem; - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - - if ($this->checkWrite()) - { - $ilToolbar->addButton($this->lng->txt("sty_add_media_query"), - $ilCtrl->getLinkTarget($this, "addMediaQuery")); - } - - include_once("./Services/Style/Content/classes/class.ilStyleMediaQueryTableGUI.php"); - $table_gui = new ilStyleMediaQueryTableGUI($this, "listMediaQueries", - $this->object); - $tpl->setContent($table_gui->getHTML()); - } - - /** - * Add a media query - */ - function addMediaQueryObject() - { - $tpl = $this->tpl; - - $this->initMediaQueryForm(); - $tpl->setContent($this->form_gui->getHTML()); - } - - /** - * Edit media query - */ - function editMediaQueryObject() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameter($this, "mq_id", $_GET["mq_id"]); - $this->initMediaQueryForm("edit"); - $this->getMediaQueryFormValues(); - $tpl->setContent($this->form_gui->getHTML()); - } - - - /** - * Init media query form - */ - function initMediaQueryForm($a_mode = "create") - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form_gui = new ilPropertyFormGUI(); - - $this->form_gui->setTitle($lng->txt("sty_add_media_query")); - - // media query - $ti = new ilTextInputGUI("@media", "mquery"); - $ti->setMaxLength(2000); - $this->form_gui->addItem($ti); - - - if ($a_mode == "create") - { - $this->form_gui->addCommandButton("saveMediaQuery", $lng->txt("save")); - $this->form_gui->addCommandButton("listMediaQueries", $lng->txt("cancel")); - } - else - { - $this->form_gui->addCommandButton("updateMediaQuery", $lng->txt("save")); - $this->form_gui->addCommandButton("listMediaQueries", $lng->txt("cancel")); - } - $this->form_gui->setFormAction($ilCtrl->getFormAction($this)); - } - - /** - * Set values for media query editing - */ - function getMediaQueryFormValues() - { - if ($_GET["mq_id"] != "") - { - foreach ($this->object->getMediaQueries() as $mq) - { - if ($mq["id"] == (int) $_GET["mq_id"]) - { - $values["mquery"] = $mq["mquery"]; - } - } - $this->form_gui->setValuesByArray($values); - } - } - - /** - * Save media query - */ - function saveMediaQueryObject() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->initMediaQueryForm(); - - if ($this->form_gui->checkInput()) - { - $this->object->addMediaQuery($_POST["mquery"]); - $ilCtrl->redirect($this, "listMediaQueries"); - } - $this->form_gui->setValuesByPost(); - $tpl->setContent($this->form_gui->getHTML()); - } - - /** - * Update media query - */ - function updateMediaQueryObject() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->initMediaQueryForm("edit"); - - if ($this->form_gui->checkInput()) - { - $this->object->updateMediaQuery((int) $_GET["mq_id"], $_POST["mquery"]); - $ilCtrl->redirect($this, "listMediaQueries"); - } - $ilCtrl->setParameter($this, "mq_id", $_GET["mq_id"]); - $this->form_gui->setValuesByPost(); - $tpl->setContent($this->form_gui->getHTML()); - } - - /** - * Confirm media query deletion - */ - function deleteMediaQueryConfirmationObject() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - if (!is_array($_POST["mq_id"]) || count($_POST["mq_id"]) == 0) - { - ilUtil::sendInfo($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "listMediaQueries"); - } - else - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("sty_sure_del_mqueries")); - $cgui->setCancel($lng->txt("cancel"), "listMediaQueries"); - $cgui->setConfirm($lng->txt("delete"), "deleteMediaQueries"); - - foreach ($_POST["mq_id"] as $i) - { - $mq = $this->object->getMediaQueryForId($i); - $cgui->addItem("mq_id[]", $i, $mq["mquery"]); - } - - $tpl->setContent($cgui->getHTML()); - } - } - - /** - * Delete Media Queries - * - * @param - * @return - */ - function deleteMediaQueriesObject() - { - $ilCtrl = $this->ctrl; - $rbacsystem = $this->rbacsystem; - - if ($this->checkWrite() && is_array($_POST["mq_id"])) - { - foreach ($_POST["mq_id"] as $id) - { - $this->object->deleteMediaQuery($id); - } - } - $ilCtrl->redirect($this, "listMediaQueries"); - } - - /** - * Save media query order - * - * @param - * @return - */ - function saveMediaQueryOrderObject() - { - $ilCtrl = $this->ctrl; - - if (is_array($_POST["order"])) - { - $this->object->saveMediaQueryOrder($_POST["order"]); - } - $ilCtrl->redirect($this, "listMediaQueries"); - } - - - // - // Templates management - // - - /** - * List templates - */ - function listTemplatesObject() - { - $tpl = $this->tpl; - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $ilToolbar = $this->toolbar; - - $ctype = $_GET["temp_type"]; - if ($ctype == "") - { - $ctype = "table"; - $ilCtrl->setParameter($this, "temp_type", $ctype); - $_GET["temp_type"] = $ctype; - } - - $this->setTemplatesSubTabs(); - $ilTabs->setSubTabActive("sty_".$ctype."_templates"); - - // action commands - if ($this->checkWrite()) - { - if ($ctype == "table") - { - $ilToolbar->addButton($this->lng->txt("sty_generate_template"), - $ilCtrl->getLinkTarget($this, "generateTemplate")); - } - $ilToolbar->addButton($this->lng->txt("sty_add_template"), - $ilCtrl->getLinkTarget($this, "addTemplate")); - } - - - - $this->includeCSS(); - include_once("./Services/Style/Content/classes/class.ilTableTemplatesTableGUI.php"); - $table_gui = new ilTableTemplatesTableGUI($ctype, $this, "listTemplates", - $this->object); - $tpl->setContent($table_gui->getHTML()); - - } - - /** - * Add template - */ - function addTemplateObject() - { - $tpl = $this->tpl; - - $this->initTemplateForm(); - $tpl->setContent($this->form_gui->getHTML()); - } - - /** - * Edit table template - */ - function editTemplateObject() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - - $ilCtrl->setParameter($this, "t_id", $_GET["t_id"]); - $this->initTemplateForm("edit"); - $this->getTemplateFormValues(); - - $this->displayTemplateEditForm(); - } - - /** - * Get table template preview - */ - function getTemplatePreview($a_type, $a_t_id, $a_small_mode = false) - { - return $this->_getTemplatePreview( - $this->object, $a_type, $a_t_id, $a_small_mode); - } - - /** - * Get table template preview - */ - static function _getTemplatePreview($a_style, $a_type, $a_t_id, $a_small_mode = false) - { - global $DIC; - - $lng = $DIC->language(); - $tpl = $DIC["tpl"]; - - $kr = $kc = 7; - if ($a_small_mode) - { - $kr = 6; - $kc = 5; - } - - $ts = $a_style->getTemplate($a_t_id); - $t = $ts["classes"]; - - // preview - if ($a_type == "table") - { - $p_content = 'lookupTemplateName($a_t_id).'">'; - if (!$a_small_mode) - { - $p_content.= ''; - } - for($i = 1; $i<=$kr; $i++) - { - $p_content.= ''; - for($j = 1; $j<=$kc; $j++) - { - if ($a_small_mode) - { - $cell = '<div style="height:2px;"></div>'; - } - else - { - $cell = 'xxx'; - } - $p_content.= ''.$cell.''; - } - $p_content.= ''; - } - $p_content.= '
                  '.$lng->txt("sty_caption").'
                  '; - } - - if ($a_type == "vaccordion" || $a_type == "haccordion" || $a_type == "carousel") - { - include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); - ilAccordionGUI::addCss(); - - if ($a_small_mode) - { - $c = '&nbsp;'; - $h = '&nbsp;'; - } - else - { - $c = 'xxx'; - $h = 'head'; - } - if ($a_type == "vaccordion") - { - $p_content = 'lookupTemplateName($a_t_id).'">'; - $p_content.= ''.$c.''; - $p_content.= ''.$h.''; - $p_content.= ''; - $p_content.= ''; - } -//echo htmlentities($p_content); - $txml = $a_style->getTemplateXML(); -//echo htmlentities($txml); exit; - $p_content.= $txml; - include_once("./Services/COPage/classes/class.ilPCTableGUI.php"); - $r_content = ilPCTableGUI::_renderTable($p_content, ""); - - // fix carousel template visibility - if($a_type == "carousel") - { - $r_content.= ""; - } - -//echo htmlentities($r_content); exit; - return $r_content; - } - - /** - * Init table template form - */ - function initTemplateForm($a_mode = "create") - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form_gui = new ilPropertyFormGUI(); - - if ($a_mode == "create") - { - $this->form_gui->setTitle($lng->txt("sty_add_template")); - } - else - { - $this->form_gui->setTitle($lng->txt("sty_edit_template")); - } - - // name - $name_input = new ilRegExpInputGUI($lng->txt("sty_template_name"), "name"); - $name_input->setPattern("/^[a-zA-Z]+[a-zA-Z0-9]*$/"); - $name_input->setNoMatchMessage($lng->txt("sty_msg_color_must_only_include")." A-Z, a-z, 1-9"); - $name_input->setRequired(true); - $name_input->setSize(30); - $name_input->setMaxLength(30); - $this->form_gui->addItem($name_input); - - // template style classes - $scs = ilObjStyleSheet::_getTemplateClassTypes($_GET["temp_type"]); - foreach ($scs as $sc => $st) - { - $sc_input = new ilSelectInputGUI($lng->txt("sty_".$sc."_class"), $sc."_class"); - $chars = $this->object->getCharacteristics($st); - $options = array("" => ""); - foreach($chars as $char) - { - $options[$char] = $char; - } - $sc_input->setOptions($options); - $this->form_gui->addItem($sc_input); - } - - if ($a_mode == "create") - { - $this->form_gui->addCommandButton("saveTemplate", $lng->txt("save")); - $this->form_gui->addCommandButton("cancelTemplateSaving", $lng->txt("cancel")); - } - else - { - $this->form_gui->addCommandButton("refreshTemplate", $lng->txt("save_refresh")); - $this->form_gui->addCommandButton("updateTemplate", $lng->txt("save_return")); - $this->form_gui->addCommandButton("cancelTemplateSaving", $lng->txt("cancel")); - } - $this->form_gui->setFormAction($ilCtrl->getFormAction($this)); - } - - /** - * Cancel color saving - */ - function cancelTemplateSavingObject() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirect($this, "listTemplates"); - } - - - /** - * Save table template - */ - function saveTemplateObject() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->initTemplateForm(); - - if ($this->form_gui->checkInput()) - { - if ($this->object->templateExists($_POST["name"])) - { - $name_input = $this->form_gui->getItemByPostVar("name"); - $name_input->setAlert($lng->txt("sty_table_template_already_exists")); - } - else - { - $classes = array(); - foreach (ilObjStyleSheet::_getTemplateClassTypes($_GET["temp_type"]) as $tct => $ct) - { - $classes[$tct] = $_POST[$tct."_class"]; - } - $t_id = $this->object->addTemplate($_GET["temp_type"], $_POST["name"], $classes); - $this->object->writeTemplatePreview($t_id, - $this->getTemplatePreview($_GET["temp_type"], $t_id, true)); - $ilCtrl->redirect($this, "listTemplates"); - } - } - $this->form_gui->setValuesByPost(); - $tpl->setContent($this->form_gui->getHTML()); - } - - /** - * Update table template - */ - function updateTemplateObject($a_refresh = false) - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $ilCtrl->setParameter($this, "t_id", $_GET["t_id"]); - $this->initTemplateForm("edit"); - - if ($this->form_gui->checkInput()) - { - if ($this->object->templateExists($_POST["name"]) && - $_POST["name"] != ilObjStyleSheet::_lookupTemplateName($_GET["t_id"])) - { - $name_input = $this->form_gui->getItemByPostVar("name"); - $name_input->setAlert($lng->txt("sty_template_already_exists")); - } - else - { - $classes = array(); - foreach (ilObjStyleSheet::_getTemplateClassTypes($_GET["temp_type"]) as $tct => $ct) - { - $classes[$tct] = $_POST[$tct."_class"]; - } - - $this->object->updateTemplate($_GET["t_id"], - $_POST["name"], $classes); - $this->object->writeTemplatePreview($_GET["t_id"], - $this->getTemplatePreview($_GET["temp_type"], $_GET["t_id"], true)); - if(!$a_refresh) - { - $ilCtrl->redirect($this, "listTemplates"); - } - } - } - - $this->form_gui->setValuesByPost(); - $this->displayTemplateEditForm(); - } - - /** - * Display table tempalte edit form - */ - function displayTemplateEditForm() - { - $tpl = $this->tpl; - - $a_tpl = new ilTemplate("tpl.template_edit.html", true, true, - "Services/Style/Content"); - $this->includeCSS(); - $a_tpl->setVariable("FORM", $this->form_gui->getHTML()); - $a_tpl->setVariable("PREVIEW", $this->getTemplatePreview($_GET["temp_type"], $_GET["t_id"])); - $tpl->setContent($a_tpl->get()); - } - - /** - * Refresh table template - */ - function refreshTemplateObject() - { - $this->updateTemplateObject(true); - } - - /** - * Set values for table template editing - */ - function getTemplateFormValues() - { - if ($_GET["t_id"] > 0) - { - $t = $this->object->getTemplate($_GET["t_id"]); - - $values["name"] = $t["name"]; - $scs = ilObjStyleSheet::_getTemplateClassTypes($_GET["temp_type"]); - foreach ($scs as $k => $type) - { - $values[$k."_class"] = $t["classes"][$k]; - } - $this->form_gui->setValuesByArray($values); - } - } - - /** - * Delete table template confirmation - */ - function deleteTemplateConfirmationObject() - { - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $lng = $this->lng; - - if (!is_array($_POST["tid"]) || count($_POST["tid"]) == 0) - { - ilUtil::sendInfo($lng->txt("no_checkbox"), true); - $ilCtrl->redirect($this, "listTemplates"); - } - else - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $cgui = new ilConfirmationGUI(); - $cgui->setFormAction($ilCtrl->getFormAction($this)); - $cgui->setHeaderText($lng->txt("sty_confirm_template_deletion")); - $cgui->setCancel($lng->txt("cancel"), "cancelTemplateDeletion"); - $cgui->setConfirm($lng->txt("sty_del_template"), "deleteTemplate"); - - foreach ($_POST["tid"] as $tid) - { - $classes = $this->object->getTemplateClasses($tid); - $cl_str = ""; - $listed = array(); - foreach ($classes as $cl) - { - if ($cl != "" && !$listed[$cl]) - { - $cl_str.= '
                  - '. - $cl."
                  "; - $listed[$cl] = true; - } - } - if ($cl_str != "") - { - $cl_str = '
                  '. - "
                  ".$lng->txt("sty_style_class")."
                  ".$cl_str."
                  "; - } - $cgui->addItem("tid[]", $tid, $this->object->lookupTemplateName($tid).$cl_str); - } - - $cgui->addButton($lng->txt("sty_del_template_keep_classes"), "deleteTemplateKeepClasses"); - - $tpl->setContent($cgui->getHTML()); - } - } - - /** - * Cancel table template deletion - */ - function cancelTemplateDeletionObject() - { - $ilCtrl = $this->ctrl; - - $ilCtrl->redirect($this, "listTemplates"); - } - - /** - * Delete table template - */ - function deleteTemplateKeepClassesObject() - { - $ilCtrl = $this->ctrl; - - if (is_array($_POST["tid"])) - { - foreach ($_POST["tid"] as $tid) - { - $this->object->removeTemplate($tid); - } - } - - $ilCtrl->redirect($this, "listTemplates"); - } - - /** - * Delete table template - */ - function deleteTemplateObject() - { - $ilCtrl = $this->ctrl; - - if (is_array($_POST["tid"])) - { - foreach ($_POST["tid"] as $tid) - { - $cls = $this->object->getTemplateClasses($tid); - foreach ($cls as $k => $cls) - { - $ty = $this->object->determineTemplateStyleClassType($_GET["temp_type"], $k); - $ta = ilObjStyleSheet::_determineTag($ty); - $this->object->deleteCharacteristic($ty, $ta, $cls); - } - $this->object->removeTemplate($tid); - } - } - - $ilCtrl->redirect($this, "listTemplates"); - } - - /** - * Generate table template - */ - function generateTemplateObject() - { - $tpl = $this->tpl; - - $this->initTemplateGenerationForm(); - $tpl->setContent($this->form_gui->getHTML()); - } - - /** - * Init table template generation form - */ - function initTemplateGenerationForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form_gui = new ilPropertyFormGUI(); - - $this->form_gui->setTitle($lng->txt("sty_generate_template")); - - // name - $name_input = new ilRegExpInputGUI($lng->txt("sty_template_name"), "name"); - $name_input->setPattern("/^[a-zA-Z]+[a-zA-Z0-9]*$/"); - $name_input->setNoMatchMessage($lng->txt("sty_msg_color_must_only_include")." A-Z, a-z, 1-9"); - $name_input->setRequired(true); - $name_input->setSize(30); - $name_input->setMaxLength(30); - $this->form_gui->addItem($name_input); - - // basic layout - $bl_input = new ilSelectInputGUI($lng->txt("sty_template_layout"), "layout"); - $options = array( - "coloredZebra" => $lng->txt("sty_table_template_colored_zebra"), - "bwZebra" => $lng->txt("sty_table_template_bw_zebra"), - "noZebra" => $lng->txt("sty_table_template_no_zebra") - ); - $bl_input->setOptions($options); - $this->form_gui->addItem($bl_input); - - // top bottom padding - include_once("./Services/Style/Content/classes/class.ilNumericStyleValueInputGUI.php"); - $num_input = new ilNumericStyleValueInputGUI($lng->txt("sty_top_bottom_padding"), "tb_padding"); - $num_input->setAllowPercentage(false); - $num_input->setValue("3px"); - $this->form_gui->addItem($num_input); - - // left right padding - $num_input = new ilNumericStyleValueInputGUI($lng->txt("sty_left_right_padding"), "lr_padding"); - $num_input->setAllowPercentage(false); - $num_input->setValue("10px"); - $this->form_gui->addItem($num_input); - - // base color - $bc_input = new ilSelectInputGUI($lng->txt("sty_base_color"), "base_color"); - $cs = $this->object->getColors(); - $options = array(); - foreach ($cs as $c) - { - $options[$c["name"]] = $c["name"]; - } - $bc_input->setOptions($options); - $this->form_gui->addItem($bc_input); - - // Lightness Settings - $lss = array("border" => 90, "header_text" => 70, "header_bg" => 0, - "cell1_text" => -60, "cell1_bg" => 90, "cell2_text" => -60, "cell2_bg" => 75); - foreach ($lss as $ls => $v) - { - $l_input = new ilNumberInputGUI($lng->txt("sty_lightness_".$ls), "lightness_".$ls); - $l_input->setMaxValue(100); - $l_input->setMinValue(-100); - $l_input->setValue($v); - $l_input->setSize(4); - $l_input->setMaxLength(4); - $this->form_gui->addItem($l_input); - } - - $this->form_gui->addCommandButton("templateGeneration", $lng->txt("generate")); - $this->form_gui->addCommandButton("cancelTemplateSaving", $lng->txt("cancel")); - $this->form_gui->setFormAction($ilCtrl->getFormAction($this)); - } - - /** - * Table template generation - */ - function templateGenerationObject() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $this->initTemplateGenerationForm(); - - if ($this->form_gui->checkInput()) - { - if ($this->object->templateExists($_POST["name"])) - { - $name_input = $this->form_gui->getItemByPostVar("name"); - $name_input->setAlert($lng->txt("sty_table_template_already_exists")); - } - else - { - // -> move to application class! - - // cell classes - $cells = array("H" => "header", "C1" => "cell1", "C2" => "cell2"); - $tb_p = $this->form_gui->getItemByPostVar("tb_padding"); - $tb_padding = $tb_p->getValue(); - $lr_p = $this->form_gui->getItemByPostVar("lr_padding"); - $lr_padding = $lr_p->getValue(); - $cell_color = $_POST["base_color"]; - - // use mid gray as cell color for bw zebra - if ($_POST["layout"] == "bwZebra") - { - $cell_color = "MidGray"; - if (!$this->object->colorExists($cell_color)) - { - $this->object->addColor($cell_color, "7F7F7F"); - } - $this->object->updateColor($cell_color, $cell_color, "7F7F7F"); - } - - foreach ($cells as $k => $cell) - { - $cell_class[$k] = $_POST["name"].$k; - if (!$this->object->characteristicExists($cell_class[$k], "table_cell")) - { - $this->object->addCharacteristic("table_cell", $cell_class[$k], true); - } - if ($_POST["layout"] == "bwZebra" && $k == "H") - { - $this->object->replaceStylePar("td", $cell_class[$k], "color", - "!".$_POST["base_color"]."(".$_POST["lightness_".$cell."_text"].")", "table_cell"); - $this->object->replaceStylePar("td", $cell_class[$k], "background-color", - "!".$_POST["base_color"]."(".$_POST["lightness_".$cell."_bg"].")", "table_cell"); - } - else - { - $this->object->replaceStylePar("td", $cell_class[$k], "color", - "!".$cell_color."(".$_POST["lightness_".$cell."_text"].")", "table_cell"); - $this->object->replaceStylePar("td", $cell_class[$k], "background-color", - "!".$cell_color."(".$_POST["lightness_".$cell."_bg"].")", "table_cell"); - } - $this->object->replaceStylePar("td", $cell_class[$k], "padding-top", - $tb_padding, "table_cell"); - $this->object->replaceStylePar("td", $cell_class[$k], "padding-bottom", - $tb_padding, "table_cell"); - $this->object->replaceStylePar("td", $cell_class[$k], "padding-left", - $lr_padding, "table_cell"); - $this->object->replaceStylePar("td", $cell_class[$k], "padding-right", - $lr_padding, "table_cell"); - $this->object->replaceStylePar("td", $cell_class[$k], "border-width", - "1px", "table_cell"); - $this->object->replaceStylePar("td", $cell_class[$k], "border-style", - "solid", "table_cell"); - $this->object->replaceStylePar("td", $cell_class[$k], "border-color", - "!".$cell_color."(".$_POST["lightness_border"].")", "table_cell"); - $this->object->replaceStylePar("td", $cell_class[$k], "font-weight", - "normal", "table_cell"); - } - - // table class - $classes["table"] = $_POST["name"]."T"; - if (!$this->object->characteristicExists($classes["table"], "table")) - { - $this->object->addCharacteristic("table", $classes["table"], true); - } - $this->object->replaceStylePar("table", $classes["table"], "caption-side", - "bottom", "table"); - $this->object->replaceStylePar("table", $classes["table"], "border-collapse", - "collapse", "table"); - $this->object->replaceStylePar("table", $classes["table"], "margin-top", - "5px", "table"); - $this->object->replaceStylePar("table", $classes["table"], "margin-bottom", - "5px", "table"); - if ($_POST["layout"] == "bwZebra") - { - $this->object->replaceStylePar("table", $classes["table"], "border-bottom-color", - "!".$_POST["base_color"], "table"); - $this->object->replaceStylePar("table", $classes["table"], "border-bottom-style", - "solid", "table"); - $this->object->replaceStylePar("table", $classes["table"], "border-bottom-width", - "3px", "table"); - $sb = array("left", "right", "top"); - foreach ($sb as $b) - { - $this->object->replaceStylePar("table", $classes["table"], "border-".$b."-width", - "0px", "table"); - } - } - - switch ($_POST["layout"]) - { - case "coloredZebra": - $classes["row_head"] = $cell_class["H"]; - $classes["odd_row"] = $cell_class["C1"]; - $classes["even_row"] = $cell_class["C2"]; - break; - - case "bwZebra": - $classes["row_head"] = $cell_class["H"]; - $classes["odd_row"] = $cell_class["C1"]; - $classes["even_row"] = $cell_class["C2"]; - break; - - case "noZebra": - $classes["row_head"] = $cell_class["H"]; - $classes["odd_row"] = $cell_class["C1"]; - $classes["even_row"] = $cell_class["C1"]; - $classes["col_head"] = $cell_class["C2"]; - break; - } - - - $t_id = $this->object->addTemplate($_GET["temp_type"], - $_POST["name"], $classes); - $this->object->writeTemplatePreview($t_id, - $this->getTemplatePreview($_GET["temp_type"], $t_id, true)); - $ilCtrl->redirect($this, "listTemplates"); - } - } - $this->form_gui->setValuesByPost(); - $tpl->setContent($this->form_gui->getHTML()); - } - - function accordiontestObject() - { - $tpl = $this->tpl; - - include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); - - $acc = new ilAccordionGUI(); - $acc->addItem("Header 1", str_repeat("bla bla bla bla bla bla", 30)); - $acc->addItem("Header 2", str_repeat("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xx x xx x xx", 30)); - $acc->setOrientation(ilAccordionGUI::HORIZONTAL); - - $ac2 = new ilAccordionGUI(); - $ac2->addItem("Header 1", str_repeat("bla bla bla bla bla bla", 30)); - $ac2->addItem("Header 2", $acc->getHTML()); - $ac2->setOrientation(ilAccordionGUI::VERTICAL); - - $tpl->setContent($ac2->getHTML()); - } - - /** - * return to upper context - */ - function returnToUpperContextObject() - { - $ilCtrl = $this->ctrl; - - /*if ($_GET["baseClass"] == "ilAdministrationGUI") - { - $ilCtrl->redirectByClass("ilcontentstylesettingsgui", "edit"); - }*/ - $ilCtrl->returnToParent($this); - } - - + $this->tabs_gui->addTarget("accordiontest", + $this->ctrl->getLinkTarget($this, "accordiontest"), "accordiontest", + get_class($this));*/ + } + } + + /** + * adds tabs to tab gui object + * + * @param object $tabs_gui ilTabsGUI object + */ + public function setSubTabs() + { + $lng = $this->lng; + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + + $types = ilObjStyleSheet::_getStyleSuperTypes(); + + foreach ($types as $super_type => $types) { + // text block characteristics + $ilCtrl->setParameter($this, "style_type", $super_type); + $ilTabs->addSubTabTarget( + "sty_" . $super_type . "_char", + $this->ctrl->getLinkTarget($this, "edit"), + array("edit", ""), + get_class($this) + ); + } + + $ilCtrl->setParameter($this, "style_type", $_GET["style_type"]); + } + + /** + * adds tabs to tab gui object + * + * @param object $tabs_gui ilTabsGUI object + */ + public function setTemplatesSubTabs() + { + $lng = $this->lng; + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + + $types = ilObjStyleSheet::_getTemplateClassTypes(); + + foreach ($types as $t => $c) { + $ilCtrl->setParameter($this, "temp_type", $t); + $ilTabs->addSubTabTarget( + "sty_" . $t . "_templates", + $this->ctrl->getLinkTarget($this, "listTemplates"), + array("listTemplates", ""), + get_class($this) + ); + } + + $ilCtrl->setParameter($this, "temp_type", $_GET["temp_type"]); + } + + /** + * should be overwritten to add object specific items + * (repository items are preloaded) + */ + public function addAdminLocatorItems($a_do_not_add_object = false) + { + $ilLocator = $this->locator; + + if ($_GET["admin_mode"] == "settings") { // system settings + parent::addAdminLocatorItems(true); + + $ilLocator->addItem( + ilObject::_lookupTitle( + ilObject::_lookupObjId($_GET["ref_id"]) + ), + $this->ctrl->getLinkTargetByClass("ilobjstylesettingsgui", "") + ); + + if ($_GET["obj_id"] > 0) { + $ilLocator->addItem( + $this->object->getTitle(), + $this->ctrl->getLinkTarget($this, "edit") + ); + } + } else { // repository administration + //? + } + } + + public function showUpperIcon() + { + $tree = $this->tree; + $tpl = $this->tpl; + $objDefinition = $this->obj_definition; + + if (strtolower($_GET["baseClass"]) == "iladministrationgui") { + $tpl->setUpperIcon( + $this->ctrl->getLinkTargetByClass( + "ilcontentstylesettings", + "edit" + ) + ); + } else { + // ? + } + } + + /** + * List images of style + */ + public function listImagesObject() + { + $tpl = $this->tpl; + $ilToolbar = $this->toolbar; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $rbacsystem = $this->rbacsystem; + + if ($this->checkWrite()) { + $ilToolbar->addButton( + $lng->txt("sty_add_image"), + $ilCtrl->getLinkTarget($this, "addImage") + ); + } + + include_once("./Services/Style/Content/classes/class.ilStyleImageTableGUI.php"); + $table_gui = new ilStyleImageTableGUI( + $this, + "listImages", + $this->object + ); + $tpl->setContent($table_gui->getHTML()); + } + + /** + * Add an image + */ + public function addImageObject() + { + $tpl = $this->tpl; + + $this->initImageForm(); + $tpl->setContent($this->form_gui->getHTML()); + } + + /** + * Cancel Upload + */ + public function cancelUploadObject() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirect($this, "listImages"); + } + + /** + * Upload image + */ + public function uploadImageObject() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + + $this->initImageForm(); + + if ($this->form_gui->checkInput()) { + $this->object->uploadImage($_FILES["image_file"]); + $ilCtrl->redirect($this, "listImages"); + } else { + //$this->form_gui->setImageFormValuesByPost(); + $tpl->setContent($this->form_gui->getHTML()); + } + } + + /** + * Init image form + */ + public function initImageForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form_gui = new ilPropertyFormGUI(); + + $this->form_gui->setTitle($lng->txt("sty_add_image")); + + $file_input = new ilImageFileInputGUI($lng->txt("sty_image_file"), "image_file"); + $file_input->setRequired(true); + $this->form_gui->addItem($file_input); + + $this->form_gui->addCommandButton("uploadImage", $lng->txt("upload")); + $this->form_gui->addCommandButton("cancelUpload", $lng->txt("cancel")); + $this->form_gui->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * Delete images + */ + public function deleteImageObject() + { + $ilCtrl = $this->ctrl; + + $images = $this->object->getImages(); + + foreach ($images as $image) { + if (is_array($_POST["file"]) && in_array($image["entry"], $_POST["file"])) { + $this->object->deleteImage($image["entry"]); + } + } + $ilCtrl->redirect($this, "listImages"); + } + + /** + * Characteristic deletion confirmation screen + */ + public function deleteCharacteristicConfirmationObject() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + //var_dump($_POST); + + if (!is_array($_POST["char"]) || count($_POST["char"]) == 0) { + ilUtil::sendInfo($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "edit"); + } else { + // check whether there are any core style classes included + $core_styles = ilObjStyleSheet::_getCoreStyles(); + foreach ($_POST["char"] as $char) { + if (!empty($core_styles[$char])) { + $this->deleteCoreCharMessage(); + return; + } + } + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("sty_confirm_char_deletion")); + $cgui->setCancel($lng->txt("cancel"), "cancelCharacteristicDeletion"); + $cgui->setConfirm($lng->txt("delete"), "deleteCharacteristic"); + + foreach ($_POST["char"] as $char) { + $char_comp = explode(".", $char); + $cgui->addItem("char[]", $char, $char_comp[2]); + } + + $tpl->setContent($cgui->getHTML()); + } + } + + /** + * Message that appears, when user tries to delete core characteristics + * + * @param + * @return + */ + public function deleteCoreCharMessage() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + + + $core_styles = ilObjStyleSheet::_getCoreStyles(); + $cnt = 0; + foreach ($_POST["char"] as $char) { + if (!empty($core_styles[$char])) { + $cnt++; + $char_comp = explode(".", $char); + $cgui->addItem("", "", $char_comp[2]); + } else { + $cgui->addHiddenItem("char[]", $char); + } + } + $all_core_styles = ($cnt == count($_POST["char"])) + ? true + : false; + + if ($all_core_styles) { + $cgui->setHeaderText($lng->txt("sty_all_styles_obligatory")); + $cgui->setCancel($lng->txt("back"), "cancelCharacteristicDeletion"); + } else { + $cgui->setHeaderText($lng->txt("sty_some_styles_obligatory_delete_rest")); + $cgui->setCancel($lng->txt("cancel"), "cancelCharacteristicDeletion"); + $cgui->setConfirm($lng->txt("sty_delete_other_selected"), "deleteCharacteristicConfirmation"); + } + + $tpl->setContent($cgui->getHTML()); + } + + /** + * Cancel characteristic deletion + */ + public function cancelCharacteristicDeletionObject() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + ilUtil::sendInfo($lng->txt("action_aborted"), true); + $ilCtrl->redirect($this, "edit"); + } + + /** + * Delete one or multiple style characteristic + */ + public function deleteCharacteristicObject() + { + $ilCtrl = $this->ctrl; + + if (is_array($_POST["char"])) { + foreach ($_POST["char"] as $char) { + $char_comp = explode(".", $char); + $type = $char_comp[0]; + $tag = $char_comp[1]; + $class = $char_comp[2]; + + $this->object->deleteCharacteristic($type, $tag, $class); + } + } + + $ilCtrl->redirect($this, "edit"); + } + + /** + * Add characteristic + */ + public function addCharacteristicFormObject() + { + $tpl = $this->tpl; + + $this->initCharacteristicForm("create"); + $tpl->setContent($this->form_gui->getHTML()); + } + + /** + * Save Characteristic + */ + public function saveCharacteristicObject() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + $this->initCharacteristicForm("create"); + + if ($this->form_gui->checkInput()) { + if ($this->object->characteristicExists($_POST["new_characteristic"], $_GET["style_type"])) { + $char_input = $this->form_gui->getItemByPostVar("new_characteristic"); + $char_input->setAlert($lng->txt("sty_characteristic_already_exists")); + } else { + $this->object->addCharacteristic($_POST["type"], $_POST["new_characteristic"]); + ilUtil::sendInfo($lng->txt("sty_added_characteristic"), true); + $ilCtrl->setParameter( + $this, + "tag", + ilObjStyleSheet::_determineTag($_POST["type"]) . "." . $_POST["new_characteristic"] + ); + $ilCtrl->setParameter($this, "style_type", $_POST["type"]); + $ilCtrl->redirect($this, "editTagStyle"); + } + } + $this->form_gui->setValuesByPost(); + $tpl->setContent($this->form_gui->getHTML()); + } + + /** + * Init tag style editing form + * + * @param int $a_mode Form Edit Mode (IL_FORM_EDIT | IL_FORM_CREATE) + */ + public function initCharacteristicForm($a_mode) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form_gui = new ilPropertyFormGUI(); + + // title + $txt_input = new ilRegExpInputGUI($lng->txt("title"), "new_characteristic"); + $txt_input->setPattern("/^[a-zA-Z]+[a-zA-Z0-9]*$/"); + $txt_input->setNoMatchMessage($lng->txt("sty_msg_characteristic_must_only_include") . " A-Z, a-z, 0-9"); + $txt_input->setRequired(true); + $this->form_gui->addItem($txt_input); + + // type + $all_super_types = ilObjStyleSheet::_getStyleSuperTypes(); + $types = $all_super_types[$this->super_type]; + $exp_types = array(); + foreach ($types as $t) { + if (ilObjStyleSheet::_isExpandable($t)) { + $exp_types[$t] = $lng->txt("sty_type_" . $t); + } + } + if (count($exp_types) > 1) { + $type_input = new ilSelectInputGUI($lng->txt("sty_type"), "type"); + $type_input->setOptions($exp_types); + $type_input->setValue(key($exp_types)); + $this->form_gui->addItem($type_input); + } elseif (count($exp_types) == 1) { + $hid_input = new ilHiddenInputGUI("type"); + $hid_input->setValue(key($exp_types)); + $this->form_gui->addItem($hid_input); + } + + $this->form_gui->setTitle($lng->txt("sty_add_characteristic")); + $this->form_gui->addCommandButton("saveCharacteristic", $lng->txt("save")); + $this->form_gui->addCommandButton("edit", $lng->txt("cancel")); + $this->form_gui->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * Get style example HTML + */ + public static function getStyleExampleHTML($a_type, $a_class) + { + global $DIC; + + $lng = $DIC->language(); + + $c = explode(":", $a_class); + $a_class = $c[0]; + + $ex_tpl = new ilTemplate("tpl.style_example.html", true, true, "Services/Style/Content"); + + if ($ex_tpl->blockExists("Example_" . $a_type)) { + $ex_tpl->setCurrentBlock("Example_" . $a_type); + } else { + $ex_tpl->setCurrentBlock("Example_default"); + } + $ex_tpl->setVariable("EX_CLASS", "ilc_" . $a_type . "_" . $a_class); + $ex_tpl->setVariable("EX_TEXT", "ABC abc 123"); + if (in_array($a_type, array("media_cont", "qimg"))) { + // + } + if (in_array($a_type, array("table", "table_caption"))) { + $ex_tpl->setVariable("TXT_CAPTION", $lng->txt("sty_caption")); + } + if (in_array($a_class, array("OrderListItemHorizontal", "OrderListHorizontal"))) { + $ex_tpl->setVariable("HOR", "Horizontal"); + } + $ex_tpl->parseCurrentBlock(); + + return $ex_tpl->get(); + } + + /** + * Save hide status for characteristics + */ + public function saveHideStatusObject() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + //var_dump($_POST); + + foreach ($_POST["all_chars"] as $char) { + $ca = explode(".", $char); + $this->object->saveHideStatus( + $ca[0], + $ca[2], + (is_array($_POST["hide"]) && in_array($char, $_POST["hide"])) + ); + } + + ilUtil::sendInfo($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "edit"); + } + + /** + * Copy style classes + * + * @param + * @return + */ + public function copyCharacteristicsObject() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if (!is_array($_POST["char"]) || count($_POST["char"]) == 0) { + ilUtil::sendFailure($lng->txt("no_checkbox"), true); + } else { + $style_cp = implode("::", $_POST["char"]); + $style_cp = $this->object->getId() . ":::" . $_GET["style_type"] . ":::" . $style_cp; + $_SESSION["sty_copy"] = $style_cp; + ilUtil::sendSuccess($lng->txt("sty_copied_please_select_target"), true); + } + $ilCtrl->redirect($this, "edit"); + } + + /** + * Paste characteristics overview + * + * @param + * @return + */ + public function pasteCharacteristicsOverviewObject() + { + $tpl = $this->tpl; + $ilTabs = $this->tabs; + + $ilTabs->clearTargets(); + + include_once("./Services/Style/Content/classes/class.ilPasteStyleCharacteristicTableGUI.php"); + $table = new ilPasteStyleCharacteristicTableGUI($this, "pasteCharacteristicsOverview"); + + $tpl->setContent($table->getHTML()); + } + + /** + * Paste characteristics + * + * @param + * @return + */ + public function pasteCharacteristicsObject() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if (is_array($_POST["title"])) { + foreach ($_POST["title"] as $from_char => $to_title) { + $fc = explode(".", $from_char); + + if ($_POST["conflict_action"][$from_char] == "overwrite" || + !$this->object->characteristicExists($to_title, $fc[0])) { + $this->object->copyCharacteristic( + $_POST["from_style_id"], + $fc[0], + $fc[2], + $to_title + ); + } + } + ilObjStyleSheet::_writeUpToDate($this->object->getId(), false); + unset($_SESSION["sty_copy"]); + ilUtil::sendSuccess($lng->txt("sty_style_classes_copied"), true); + } + + $ilCtrl->redirect($this, "edit"); + } + + // + // Color management + // + + /** + * List colors of style + */ + public function listColorsObject() + { + $tpl = $this->tpl; + $rbacsystem = $this->rbacsystem; + $ilToolbar = $this->toolbar; + $ilCtrl = $this->ctrl; + + if ($this->checkWrite()) { + $ilToolbar->addButton( + $this->lng->txt("sty_add_color"), + $ilCtrl->getLinkTarget($this, "addColor") + ); + } + + include_once("./Services/Style/Content/classes/class.ilStyleColorTableGUI.php"); + $table_gui = new ilStyleColorTableGUI( + $this, + "listColors", + $this->object + ); + $tpl->setContent($table_gui->getHTML()); + } + + /** + * Add a color + */ + public function addColorObject() + { + $tpl = $this->tpl; + + $this->initColorForm(); + $tpl->setContent($this->form_gui->getHTML()); + } + + /** + * Edit color + */ + public function editColorObject() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameter($this, "c_name", $_GET["c_name"]); + $this->initColorForm("edit"); + $this->getColorFormValues(); + $tpl->setContent($this->form_gui->getHTML()); + } + + + /** + * Init color form + */ + public function initColorForm($a_mode = "create") + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form_gui = new ilPropertyFormGUI(); + + $this->form_gui->setTitle($lng->txt("sty_add_color")); + + // name + $name_input = new ilRegExpInputGUI($lng->txt("sty_color_name"), "color_name"); + $name_input->setPattern("/^[a-zA-Z]+[a-zA-Z0-9]*$/"); + $name_input->setNoMatchMessage($lng->txt("sty_msg_color_must_only_include") . " A-Z, a-z, 1-9"); + $name_input->setRequired(true); + $name_input->setSize(15); + $name_input->setMaxLength(15); + $this->form_gui->addItem($name_input); + + // code + $color_input = new ilColorPickerInputGUI($lng->txt("sty_color_code"), "color_code"); + $color_input->setRequired(true); + $color_input->setDefaultColor(""); + $this->form_gui->addItem($color_input); + + if ($a_mode == "create") { + $this->form_gui->addCommandButton("saveColor", $lng->txt("save")); + $this->form_gui->addCommandButton("cancelColorSaving", $lng->txt("cancel")); + } else { + $this->form_gui->addCommandButton("updateColor", $lng->txt("save")); + $this->form_gui->addCommandButton("cancelColorSaving", $lng->txt("cancel")); + } + $this->form_gui->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * Set values for color editing + */ + public function getColorFormValues() + { + if ($_GET["c_name"] != "") { + $values["color_name"] = $_GET["c_name"]; + $values["color_code"] = $this->object->getColorCodeForName($_GET["c_name"]); + $this->form_gui->setValuesByArray($values); + } + } + + /** + * Cancel color saving + */ + public function cancelColorSavingObject() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirect($this, "listColors"); + } + + /** + * Save color + */ + public function saveColorObject() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->initColorForm(); + + if ($this->form_gui->checkInput()) { + if ($this->object->colorExists($_POST["color_name"])) { + $col_input = $this->form_gui->getItemByPostVar("color_name"); + $col_input->setAlert($lng->txt("sty_color_already_exists")); + } else { + $this->object->addColor( + $_POST["color_name"], + $_POST["color_code"] + ); + $ilCtrl->redirect($this, "listColors"); + } + } + $this->form_gui->setValuesByPost(); + $tpl->setContent($this->form_gui->getHTML()); + } + + /** + * Update color + */ + public function updateColorObject() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->initColorForm("edit"); + + if ($this->form_gui->checkInput()) { + if ($this->object->colorExists($_POST["color_name"]) && + $_POST["color_name"] != $_GET["c_name"]) { + $col_input = $this->form_gui->getItemByPostVar("color_name"); + $col_input->setAlert($lng->txt("sty_color_already_exists")); + } else { + $this->object->updateColor( + $_GET["c_name"], + $_POST["color_name"], + $_POST["color_code"] + ); + $ilCtrl->redirect($this, "listColors"); + } + } + $ilCtrl->setParameter($this, "c_name", $_GET["c_name"]); + $this->form_gui->setValuesByPost(); + $tpl->setContent($this->form_gui->getHTML()); + } + + /** + * Delete color confirmation + */ + public function deleteColorConfirmationObject() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + if (!is_array($_POST["color"]) || count($_POST["color"]) == 0) { + ilUtil::sendInfo($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "listColors"); + } else { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("sty_confirm_color_deletion")); + $cgui->setCancel($lng->txt("cancel"), "cancelColorDeletion"); + $cgui->setConfirm($lng->txt("delete"), "deleteColor"); + + foreach ($_POST["color"] as $c) { + $cgui->addItem("color[]", ilUtil::prepareFormOutput($c), $c); + } + + $tpl->setContent($cgui->getHTML()); + } + } + + /** + * Cancel color deletion + */ + public function cancelColorDeletionObject() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirect($this, "listColors"); + } + + /** + * Delete colors + */ + public function deleteColorObject() + { + $ilCtrl = $this->ctrl; + + if (is_array($_POST["color"])) { + foreach ($_POST["color"] as $c) { + $this->object->removeColor($c); + } + } + + $ilCtrl->redirect($this, "listColors"); + } + + // + // Media query management + // + + /** + * List media queries of style + */ + public function listMediaQueriesObject() + { + $tpl = $this->tpl; + $rbacsystem = $this->rbacsystem; + $ilToolbar = $this->toolbar; + $ilCtrl = $this->ctrl; + + if ($this->checkWrite()) { + $ilToolbar->addButton( + $this->lng->txt("sty_add_media_query"), + $ilCtrl->getLinkTarget($this, "addMediaQuery") + ); + } + + include_once("./Services/Style/Content/classes/class.ilStyleMediaQueryTableGUI.php"); + $table_gui = new ilStyleMediaQueryTableGUI( + $this, + "listMediaQueries", + $this->object + ); + $tpl->setContent($table_gui->getHTML()); + } + + /** + * Add a media query + */ + public function addMediaQueryObject() + { + $tpl = $this->tpl; + + $this->initMediaQueryForm(); + $tpl->setContent($this->form_gui->getHTML()); + } + + /** + * Edit media query + */ + public function editMediaQueryObject() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameter($this, "mq_id", $_GET["mq_id"]); + $this->initMediaQueryForm("edit"); + $this->getMediaQueryFormValues(); + $tpl->setContent($this->form_gui->getHTML()); + } + + + /** + * Init media query form + */ + public function initMediaQueryForm($a_mode = "create") + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form_gui = new ilPropertyFormGUI(); + + $this->form_gui->setTitle($lng->txt("sty_add_media_query")); + + // media query + $ti = new ilTextInputGUI("@media", "mquery"); + $ti->setMaxLength(2000); + $this->form_gui->addItem($ti); + + + if ($a_mode == "create") { + $this->form_gui->addCommandButton("saveMediaQuery", $lng->txt("save")); + $this->form_gui->addCommandButton("listMediaQueries", $lng->txt("cancel")); + } else { + $this->form_gui->addCommandButton("updateMediaQuery", $lng->txt("save")); + $this->form_gui->addCommandButton("listMediaQueries", $lng->txt("cancel")); + } + $this->form_gui->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * Set values for media query editing + */ + public function getMediaQueryFormValues() + { + if ($_GET["mq_id"] != "") { + foreach ($this->object->getMediaQueries() as $mq) { + if ($mq["id"] == (int) $_GET["mq_id"]) { + $values["mquery"] = $mq["mquery"]; + } + } + $this->form_gui->setValuesByArray($values); + } + } + + /** + * Save media query + */ + public function saveMediaQueryObject() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->initMediaQueryForm(); + + if ($this->form_gui->checkInput()) { + $this->object->addMediaQuery($_POST["mquery"]); + $ilCtrl->redirect($this, "listMediaQueries"); + } + $this->form_gui->setValuesByPost(); + $tpl->setContent($this->form_gui->getHTML()); + } + + /** + * Update media query + */ + public function updateMediaQueryObject() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->initMediaQueryForm("edit"); + + if ($this->form_gui->checkInput()) { + $this->object->updateMediaQuery((int) $_GET["mq_id"], $_POST["mquery"]); + $ilCtrl->redirect($this, "listMediaQueries"); + } + $ilCtrl->setParameter($this, "mq_id", $_GET["mq_id"]); + $this->form_gui->setValuesByPost(); + $tpl->setContent($this->form_gui->getHTML()); + } + + /** + * Confirm media query deletion + */ + public function deleteMediaQueryConfirmationObject() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + if (!is_array($_POST["mq_id"]) || count($_POST["mq_id"]) == 0) { + ilUtil::sendInfo($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "listMediaQueries"); + } else { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("sty_sure_del_mqueries")); + $cgui->setCancel($lng->txt("cancel"), "listMediaQueries"); + $cgui->setConfirm($lng->txt("delete"), "deleteMediaQueries"); + + foreach ($_POST["mq_id"] as $i) { + $mq = $this->object->getMediaQueryForId($i); + $cgui->addItem("mq_id[]", $i, $mq["mquery"]); + } + + $tpl->setContent($cgui->getHTML()); + } + } + + /** + * Delete Media Queries + * + * @param + * @return + */ + public function deleteMediaQueriesObject() + { + $ilCtrl = $this->ctrl; + $rbacsystem = $this->rbacsystem; + + if ($this->checkWrite() && is_array($_POST["mq_id"])) { + foreach ($_POST["mq_id"] as $id) { + $this->object->deleteMediaQuery($id); + } + } + $ilCtrl->redirect($this, "listMediaQueries"); + } + + /** + * Save media query order + * + * @param + * @return + */ + public function saveMediaQueryOrderObject() + { + $ilCtrl = $this->ctrl; + + if (is_array($_POST["order"])) { + $this->object->saveMediaQueryOrder($_POST["order"]); + } + $ilCtrl->redirect($this, "listMediaQueries"); + } + + + // + // Templates management + // + + /** + * List templates + */ + public function listTemplatesObject() + { + $tpl = $this->tpl; + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $ilToolbar = $this->toolbar; + + $ctype = $_GET["temp_type"]; + if ($ctype == "") { + $ctype = "table"; + $ilCtrl->setParameter($this, "temp_type", $ctype); + $_GET["temp_type"] = $ctype; + } + + $this->setTemplatesSubTabs(); + $ilTabs->setSubTabActive("sty_" . $ctype . "_templates"); + + // action commands + if ($this->checkWrite()) { + if ($ctype == "table") { + $ilToolbar->addButton( + $this->lng->txt("sty_generate_template"), + $ilCtrl->getLinkTarget($this, "generateTemplate") + ); + } + $ilToolbar->addButton( + $this->lng->txt("sty_add_template"), + $ilCtrl->getLinkTarget($this, "addTemplate") + ); + } + + + + $this->includeCSS(); + include_once("./Services/Style/Content/classes/class.ilTableTemplatesTableGUI.php"); + $table_gui = new ilTableTemplatesTableGUI( + $ctype, + $this, + "listTemplates", + $this->object + ); + $tpl->setContent($table_gui->getHTML()); + } + + /** + * Add template + */ + public function addTemplateObject() + { + $tpl = $this->tpl; + + $this->initTemplateForm(); + $tpl->setContent($this->form_gui->getHTML()); + } + + /** + * Edit table template + */ + public function editTemplateObject() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + + $ilCtrl->setParameter($this, "t_id", $_GET["t_id"]); + $this->initTemplateForm("edit"); + $this->getTemplateFormValues(); + + $this->displayTemplateEditForm(); + } + + /** + * Get table template preview + */ + public function getTemplatePreview($a_type, $a_t_id, $a_small_mode = false) + { + return $this->_getTemplatePreview( + $this->object, + $a_type, + $a_t_id, + $a_small_mode + ); + } + + /** + * Get table template preview + */ + public static function _getTemplatePreview($a_style, $a_type, $a_t_id, $a_small_mode = false) + { + global $DIC; + + $lng = $DIC->language(); + $tpl = $DIC["tpl"]; + + $kr = $kc = 7; + if ($a_small_mode) { + $kr = 6; + $kc = 5; + } + + $ts = $a_style->getTemplate($a_t_id); + $t = $ts["classes"]; + + // preview + if ($a_type == "table") { + $p_content = 'lookupTemplateName($a_t_id) . '">'; + if (!$a_small_mode) { + $p_content.= ''; + } + for ($i = 1; $i<=$kr; $i++) { + $p_content.= ''; + for ($j = 1; $j<=$kc; $j++) { + if ($a_small_mode) { + $cell = '<div style="height:2px;"></div>'; + } else { + $cell = 'xxx'; + } + $p_content.= '' . $cell . ''; + } + $p_content.= ''; + } + $p_content.= '
                  ' . $lng->txt("sty_caption") . '
                  '; + } + + if ($a_type == "vaccordion" || $a_type == "haccordion" || $a_type == "carousel") { + include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); + ilAccordionGUI::addCss(); + + if ($a_small_mode) { + $c = '&nbsp;'; + $h = '&nbsp;'; + } else { + $c = 'xxx'; + $h = 'head'; + } + if ($a_type == "vaccordion") { + $p_content = 'lookupTemplateName($a_t_id) . '">'; + $p_content.= '' . $c . ''; + $p_content.= '' . $h . ''; + $p_content.= ''; + $p_content.= ''; + } + //echo htmlentities($p_content); + $txml = $a_style->getTemplateXML(); + //echo htmlentities($txml); exit; + $p_content.= $txml; + include_once("./Services/COPage/classes/class.ilPCTableGUI.php"); + $r_content = ilPCTableGUI::_renderTable($p_content, ""); + + // fix carousel template visibility + if ($a_type == "carousel") { + $r_content.= ""; + } + + //echo htmlentities($r_content); exit; + return $r_content; + } + + /** + * Init table template form + */ + public function initTemplateForm($a_mode = "create") + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form_gui = new ilPropertyFormGUI(); + + if ($a_mode == "create") { + $this->form_gui->setTitle($lng->txt("sty_add_template")); + } else { + $this->form_gui->setTitle($lng->txt("sty_edit_template")); + } + + // name + $name_input = new ilRegExpInputGUI($lng->txt("sty_template_name"), "name"); + $name_input->setPattern("/^[a-zA-Z]+[a-zA-Z0-9]*$/"); + $name_input->setNoMatchMessage($lng->txt("sty_msg_color_must_only_include") . " A-Z, a-z, 1-9"); + $name_input->setRequired(true); + $name_input->setSize(30); + $name_input->setMaxLength(30); + $this->form_gui->addItem($name_input); + + // template style classes + $scs = ilObjStyleSheet::_getTemplateClassTypes($_GET["temp_type"]); + foreach ($scs as $sc => $st) { + $sc_input = new ilSelectInputGUI($lng->txt("sty_" . $sc . "_class"), $sc . "_class"); + $chars = $this->object->getCharacteristics($st); + $options = array("" => ""); + foreach ($chars as $char) { + $options[$char] = $char; + } + $sc_input->setOptions($options); + $this->form_gui->addItem($sc_input); + } + + if ($a_mode == "create") { + $this->form_gui->addCommandButton("saveTemplate", $lng->txt("save")); + $this->form_gui->addCommandButton("cancelTemplateSaving", $lng->txt("cancel")); + } else { + $this->form_gui->addCommandButton("refreshTemplate", $lng->txt("save_refresh")); + $this->form_gui->addCommandButton("updateTemplate", $lng->txt("save_return")); + $this->form_gui->addCommandButton("cancelTemplateSaving", $lng->txt("cancel")); + } + $this->form_gui->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * Cancel color saving + */ + public function cancelTemplateSavingObject() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirect($this, "listTemplates"); + } + + + /** + * Save table template + */ + public function saveTemplateObject() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->initTemplateForm(); + + if ($this->form_gui->checkInput()) { + if ($this->object->templateExists($_POST["name"])) { + $name_input = $this->form_gui->getItemByPostVar("name"); + $name_input->setAlert($lng->txt("sty_table_template_already_exists")); + } else { + $classes = array(); + foreach (ilObjStyleSheet::_getTemplateClassTypes($_GET["temp_type"]) as $tct => $ct) { + $classes[$tct] = $_POST[$tct . "_class"]; + } + $t_id = $this->object->addTemplate($_GET["temp_type"], $_POST["name"], $classes); + $this->object->writeTemplatePreview( + $t_id, + $this->getTemplatePreview($_GET["temp_type"], $t_id, true) + ); + $ilCtrl->redirect($this, "listTemplates"); + } + } + $this->form_gui->setValuesByPost(); + $tpl->setContent($this->form_gui->getHTML()); + } + + /** + * Update table template + */ + public function updateTemplateObject($a_refresh = false) + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $ilCtrl->setParameter($this, "t_id", $_GET["t_id"]); + $this->initTemplateForm("edit"); + + if ($this->form_gui->checkInput()) { + if ($this->object->templateExists($_POST["name"]) && + $_POST["name"] != ilObjStyleSheet::_lookupTemplateName($_GET["t_id"])) { + $name_input = $this->form_gui->getItemByPostVar("name"); + $name_input->setAlert($lng->txt("sty_template_already_exists")); + } else { + $classes = array(); + foreach (ilObjStyleSheet::_getTemplateClassTypes($_GET["temp_type"]) as $tct => $ct) { + $classes[$tct] = $_POST[$tct . "_class"]; + } + + $this->object->updateTemplate( + $_GET["t_id"], + $_POST["name"], + $classes + ); + $this->object->writeTemplatePreview( + $_GET["t_id"], + $this->getTemplatePreview($_GET["temp_type"], $_GET["t_id"], true) + ); + if (!$a_refresh) { + $ilCtrl->redirect($this, "listTemplates"); + } + } + } + + $this->form_gui->setValuesByPost(); + $this->displayTemplateEditForm(); + } + + /** + * Display table tempalte edit form + */ + public function displayTemplateEditForm() + { + $tpl = $this->tpl; + + $a_tpl = new ilTemplate( + "tpl.template_edit.html", + true, + true, + "Services/Style/Content" + ); + $this->includeCSS(); + $a_tpl->setVariable("FORM", $this->form_gui->getHTML()); + $a_tpl->setVariable("PREVIEW", $this->getTemplatePreview($_GET["temp_type"], $_GET["t_id"])); + $tpl->setContent($a_tpl->get()); + } + + /** + * Refresh table template + */ + public function refreshTemplateObject() + { + $this->updateTemplateObject(true); + } + + /** + * Set values for table template editing + */ + public function getTemplateFormValues() + { + if ($_GET["t_id"] > 0) { + $t = $this->object->getTemplate($_GET["t_id"]); + + $values["name"] = $t["name"]; + $scs = ilObjStyleSheet::_getTemplateClassTypes($_GET["temp_type"]); + foreach ($scs as $k => $type) { + $values[$k . "_class"] = $t["classes"][$k]; + } + $this->form_gui->setValuesByArray($values); + } + } + + /** + * Delete table template confirmation + */ + public function deleteTemplateConfirmationObject() + { + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $lng = $this->lng; + + if (!is_array($_POST["tid"]) || count($_POST["tid"]) == 0) { + ilUtil::sendInfo($lng->txt("no_checkbox"), true); + $ilCtrl->redirect($this, "listTemplates"); + } else { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $cgui = new ilConfirmationGUI(); + $cgui->setFormAction($ilCtrl->getFormAction($this)); + $cgui->setHeaderText($lng->txt("sty_confirm_template_deletion")); + $cgui->setCancel($lng->txt("cancel"), "cancelTemplateDeletion"); + $cgui->setConfirm($lng->txt("sty_del_template"), "deleteTemplate"); + + foreach ($_POST["tid"] as $tid) { + $classes = $this->object->getTemplateClasses($tid); + $cl_str = ""; + $listed = array(); + foreach ($classes as $cl) { + if ($cl != "" && !$listed[$cl]) { + $cl_str.= '
                  - ' . + $cl . "
                  "; + $listed[$cl] = true; + } + } + if ($cl_str != "") { + $cl_str = '
                  ' . + "
                  " . $lng->txt("sty_style_class") . "
                  " . $cl_str . "
                  "; + } + $cgui->addItem("tid[]", $tid, $this->object->lookupTemplateName($tid) . $cl_str); + } + + $cgui->addButton($lng->txt("sty_del_template_keep_classes"), "deleteTemplateKeepClasses"); + + $tpl->setContent($cgui->getHTML()); + } + } + + /** + * Cancel table template deletion + */ + public function cancelTemplateDeletionObject() + { + $ilCtrl = $this->ctrl; + + $ilCtrl->redirect($this, "listTemplates"); + } + + /** + * Delete table template + */ + public function deleteTemplateKeepClassesObject() + { + $ilCtrl = $this->ctrl; + + if (is_array($_POST["tid"])) { + foreach ($_POST["tid"] as $tid) { + $this->object->removeTemplate($tid); + } + } + + $ilCtrl->redirect($this, "listTemplates"); + } + + /** + * Delete table template + */ + public function deleteTemplateObject() + { + $ilCtrl = $this->ctrl; + + if (is_array($_POST["tid"])) { + foreach ($_POST["tid"] as $tid) { + $cls = $this->object->getTemplateClasses($tid); + foreach ($cls as $k => $cls) { + $ty = $this->object->determineTemplateStyleClassType($_GET["temp_type"], $k); + $ta = ilObjStyleSheet::_determineTag($ty); + $this->object->deleteCharacteristic($ty, $ta, $cls); + } + $this->object->removeTemplate($tid); + } + } + + $ilCtrl->redirect($this, "listTemplates"); + } + + /** + * Generate table template + */ + public function generateTemplateObject() + { + $tpl = $this->tpl; + + $this->initTemplateGenerationForm(); + $tpl->setContent($this->form_gui->getHTML()); + } + + /** + * Init table template generation form + */ + public function initTemplateGenerationForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form_gui = new ilPropertyFormGUI(); + + $this->form_gui->setTitle($lng->txt("sty_generate_template")); + + // name + $name_input = new ilRegExpInputGUI($lng->txt("sty_template_name"), "name"); + $name_input->setPattern("/^[a-zA-Z]+[a-zA-Z0-9]*$/"); + $name_input->setNoMatchMessage($lng->txt("sty_msg_color_must_only_include") . " A-Z, a-z, 1-9"); + $name_input->setRequired(true); + $name_input->setSize(30); + $name_input->setMaxLength(30); + $this->form_gui->addItem($name_input); + + // basic layout + $bl_input = new ilSelectInputGUI($lng->txt("sty_template_layout"), "layout"); + $options = array( + "coloredZebra" => $lng->txt("sty_table_template_colored_zebra"), + "bwZebra" => $lng->txt("sty_table_template_bw_zebra"), + "noZebra" => $lng->txt("sty_table_template_no_zebra") + ); + $bl_input->setOptions($options); + $this->form_gui->addItem($bl_input); + + // top bottom padding + include_once("./Services/Style/Content/classes/class.ilNumericStyleValueInputGUI.php"); + $num_input = new ilNumericStyleValueInputGUI($lng->txt("sty_top_bottom_padding"), "tb_padding"); + $num_input->setAllowPercentage(false); + $num_input->setValue("3px"); + $this->form_gui->addItem($num_input); + + // left right padding + $num_input = new ilNumericStyleValueInputGUI($lng->txt("sty_left_right_padding"), "lr_padding"); + $num_input->setAllowPercentage(false); + $num_input->setValue("10px"); + $this->form_gui->addItem($num_input); + + // base color + $bc_input = new ilSelectInputGUI($lng->txt("sty_base_color"), "base_color"); + $cs = $this->object->getColors(); + $options = array(); + foreach ($cs as $c) { + $options[$c["name"]] = $c["name"]; + } + $bc_input->setOptions($options); + $this->form_gui->addItem($bc_input); + + // Lightness Settings + $lss = array("border" => 90, "header_text" => 70, "header_bg" => 0, + "cell1_text" => -60, "cell1_bg" => 90, "cell2_text" => -60, "cell2_bg" => 75); + foreach ($lss as $ls => $v) { + $l_input = new ilNumberInputGUI($lng->txt("sty_lightness_" . $ls), "lightness_" . $ls); + $l_input->setMaxValue(100); + $l_input->setMinValue(-100); + $l_input->setValue($v); + $l_input->setSize(4); + $l_input->setMaxLength(4); + $this->form_gui->addItem($l_input); + } + + $this->form_gui->addCommandButton("templateGeneration", $lng->txt("generate")); + $this->form_gui->addCommandButton("cancelTemplateSaving", $lng->txt("cancel")); + $this->form_gui->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * Table template generation + */ + public function templateGenerationObject() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $this->initTemplateGenerationForm(); + + if ($this->form_gui->checkInput()) { + if ($this->object->templateExists($_POST["name"])) { + $name_input = $this->form_gui->getItemByPostVar("name"); + $name_input->setAlert($lng->txt("sty_table_template_already_exists")); + } else { + // -> move to application class! + + // cell classes + $cells = array("H" => "header", "C1" => "cell1", "C2" => "cell2"); + $tb_p = $this->form_gui->getItemByPostVar("tb_padding"); + $tb_padding = $tb_p->getValue(); + $lr_p = $this->form_gui->getItemByPostVar("lr_padding"); + $lr_padding = $lr_p->getValue(); + $cell_color = $_POST["base_color"]; + + // use mid gray as cell color for bw zebra + if ($_POST["layout"] == "bwZebra") { + $cell_color = "MidGray"; + if (!$this->object->colorExists($cell_color)) { + $this->object->addColor($cell_color, "7F7F7F"); + } + $this->object->updateColor($cell_color, $cell_color, "7F7F7F"); + } + + foreach ($cells as $k => $cell) { + $cell_class[$k] = $_POST["name"] . $k; + if (!$this->object->characteristicExists($cell_class[$k], "table_cell")) { + $this->object->addCharacteristic("table_cell", $cell_class[$k], true); + } + if ($_POST["layout"] == "bwZebra" && $k == "H") { + $this->object->replaceStylePar( + "td", + $cell_class[$k], + "color", + "!" . $_POST["base_color"] . "(" . $_POST["lightness_" . $cell . "_text"] . ")", + "table_cell" + ); + $this->object->replaceStylePar( + "td", + $cell_class[$k], + "background-color", + "!" . $_POST["base_color"] . "(" . $_POST["lightness_" . $cell . "_bg"] . ")", + "table_cell" + ); + } else { + $this->object->replaceStylePar( + "td", + $cell_class[$k], + "color", + "!" . $cell_color . "(" . $_POST["lightness_" . $cell . "_text"] . ")", + "table_cell" + ); + $this->object->replaceStylePar( + "td", + $cell_class[$k], + "background-color", + "!" . $cell_color . "(" . $_POST["lightness_" . $cell . "_bg"] . ")", + "table_cell" + ); + } + $this->object->replaceStylePar( + "td", + $cell_class[$k], + "padding-top", + $tb_padding, + "table_cell" + ); + $this->object->replaceStylePar( + "td", + $cell_class[$k], + "padding-bottom", + $tb_padding, + "table_cell" + ); + $this->object->replaceStylePar( + "td", + $cell_class[$k], + "padding-left", + $lr_padding, + "table_cell" + ); + $this->object->replaceStylePar( + "td", + $cell_class[$k], + "padding-right", + $lr_padding, + "table_cell" + ); + $this->object->replaceStylePar( + "td", + $cell_class[$k], + "border-width", + "1px", + "table_cell" + ); + $this->object->replaceStylePar( + "td", + $cell_class[$k], + "border-style", + "solid", + "table_cell" + ); + $this->object->replaceStylePar( + "td", + $cell_class[$k], + "border-color", + "!" . $cell_color . "(" . $_POST["lightness_border"] . ")", + "table_cell" + ); + $this->object->replaceStylePar( + "td", + $cell_class[$k], + "font-weight", + "normal", + "table_cell" + ); + } + + // table class + $classes["table"] = $_POST["name"] . "T"; + if (!$this->object->characteristicExists($classes["table"], "table")) { + $this->object->addCharacteristic("table", $classes["table"], true); + } + $this->object->replaceStylePar( + "table", + $classes["table"], + "caption-side", + "bottom", + "table" + ); + $this->object->replaceStylePar( + "table", + $classes["table"], + "border-collapse", + "collapse", + "table" + ); + $this->object->replaceStylePar( + "table", + $classes["table"], + "margin-top", + "5px", + "table" + ); + $this->object->replaceStylePar( + "table", + $classes["table"], + "margin-bottom", + "5px", + "table" + ); + if ($_POST["layout"] == "bwZebra") { + $this->object->replaceStylePar( + "table", + $classes["table"], + "border-bottom-color", + "!" . $_POST["base_color"], + "table" + ); + $this->object->replaceStylePar( + "table", + $classes["table"], + "border-bottom-style", + "solid", + "table" + ); + $this->object->replaceStylePar( + "table", + $classes["table"], + "border-bottom-width", + "3px", + "table" + ); + $sb = array("left", "right", "top"); + foreach ($sb as $b) { + $this->object->replaceStylePar( + "table", + $classes["table"], + "border-" . $b . "-width", + "0px", + "table" + ); + } + } + + switch ($_POST["layout"]) { + case "coloredZebra": + $classes["row_head"] = $cell_class["H"]; + $classes["odd_row"] = $cell_class["C1"]; + $classes["even_row"] = $cell_class["C2"]; + break; + + case "bwZebra": + $classes["row_head"] = $cell_class["H"]; + $classes["odd_row"] = $cell_class["C1"]; + $classes["even_row"] = $cell_class["C2"]; + break; + + case "noZebra": + $classes["row_head"] = $cell_class["H"]; + $classes["odd_row"] = $cell_class["C1"]; + $classes["even_row"] = $cell_class["C1"]; + $classes["col_head"] = $cell_class["C2"]; + break; + } + + + $t_id = $this->object->addTemplate( + $_GET["temp_type"], + $_POST["name"], + $classes + ); + $this->object->writeTemplatePreview( + $t_id, + $this->getTemplatePreview($_GET["temp_type"], $t_id, true) + ); + $ilCtrl->redirect($this, "listTemplates"); + } + } + $this->form_gui->setValuesByPost(); + $tpl->setContent($this->form_gui->getHTML()); + } + + public function accordiontestObject() + { + $tpl = $this->tpl; + + include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); + + $acc = new ilAccordionGUI(); + $acc->addItem("Header 1", str_repeat("bla bla bla bla bla bla", 30)); + $acc->addItem("Header 2", str_repeat("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xx x xx x xx", 30)); + $acc->setOrientation(ilAccordionGUI::HORIZONTAL); + + $ac2 = new ilAccordionGUI(); + $ac2->addItem("Header 1", str_repeat("bla bla bla bla bla bla", 30)); + $ac2->addItem("Header 2", $acc->getHTML()); + $ac2->setOrientation(ilAccordionGUI::VERTICAL); + + $tpl->setContent($ac2->getHTML()); + } + + /** + * return to upper context + */ + public function returnToUpperContextObject() + { + $ilCtrl = $this->ctrl; + + /*if ($_GET["baseClass"] == "ilAdministrationGUI") + { + $ilCtrl->redirectByClass("ilcontentstylesettingsgui", "edit"); + }*/ + $ilCtrl->returnToParent($this); + } } -?> diff --git a/Services/Style/Content/classes/class.ilPasteStyleCharacteristicTableGUI.php b/Services/Style/Content/classes/class.ilPasteStyleCharacteristicTableGUI.php index 332469f7710157bc30f1097605fe30d224e4325b..2e87e6627d5315afe98788bd74ca091569f6e177 100644 --- a/Services/Style/Content/classes/class.ilPasteStyleCharacteristicTableGUI.php +++ b/Services/Style/Content/classes/class.ilPasteStyleCharacteristicTableGUI.php @@ -13,71 +13,68 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilPasteStyleCharacteristicTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd) + { + 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); - $this->setTitle($lng->txt("sty_paste_characteristics")); - $this->setLimit(9999); - $st_c = explode(":::", $_SESSION["sty_copy"]); - $this->from_style_id = $st_c[0]; - $this->from_style_type = $st_c[1]; - $this->setData(explode("::",$st_c[2])); - $this->addColumn($this->lng->txt("name")); - $this->addColumn($this->lng->txt("type")); - $this->addColumn($this->lng->txt("sty_if_style_class_already_exists")); + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->setTitle($lng->txt("sty_paste_characteristics")); + $this->setLimit(9999); + $st_c = explode(":::", $_SESSION["sty_copy"]); + $this->from_style_id = $st_c[0]; + $this->from_style_type = $st_c[1]; + $this->setData(explode("::", $st_c[2])); + $this->addColumn($this->lng->txt("name")); + $this->addColumn($this->lng->txt("type")); + $this->addColumn($this->lng->txt("sty_if_style_class_already_exists")); - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.paste_style_row.html", "Services/Style/Content"); - $this->disable("footer"); - $this->setEnableTitle(true); + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.paste_style_row.html", "Services/Style/Content"); + $this->disable("footer"); + $this->setEnableTitle(true); - //$this->addMultiCommand("", $lng->txt("")); - $this->addCommandButton("pasteCharacteristics", $lng->txt("paste")); - $this->addCommandButton("edit", $lng->txt("cancel")); - $this->addHiddenInput("from_style_id", $this->from_style_id); - } + //$this->addMultiCommand("", $lng->txt("")); + $this->addCommandButton("pasteCharacteristics", $lng->txt("paste")); + $this->addCommandButton("edit", $lng->txt("cancel")); + $this->addHiddenInput("from_style_id", $this->from_style_id); + } - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - - $char = explode(".", $a_set); - $this->tpl->setVariable("CHAR", $a_set); - $this->tpl->setVariable("SEL_OVERWRITE", 'checked="checked"'); - $this->tpl->setVariable("VAL_TYPE", $lng->txt("sty_type_".$char[0])); - $this->tpl->setVariable("VAL_TITLE", $char[2]); - $this->tpl->setVariable("TXT_OVERWRITE", $lng->txt("sty_overwrite")); - $this->tpl->setVariable("TXT_IGNORE", $lng->txt("sty_keep_existing")); - - } + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $char = explode(".", $a_set); + $this->tpl->setVariable("CHAR", $a_set); + $this->tpl->setVariable("SEL_OVERWRITE", 'checked="checked"'); + $this->tpl->setVariable("VAL_TYPE", $lng->txt("sty_type_" . $char[0])); + $this->tpl->setVariable("VAL_TITLE", $char[2]); + $this->tpl->setVariable("TXT_OVERWRITE", $lng->txt("sty_overwrite")); + $this->tpl->setVariable("TXT_IGNORE", $lng->txt("sty_keep_existing")); + } } -?> diff --git a/Services/Style/Content/classes/class.ilStyleColorTableGUI.php b/Services/Style/Content/classes/class.ilStyleColorTableGUI.php index 456637b8b86e45d598eac6cf225f9ca2f5a81dbe..f0391a7a9cc1b4498a7d5407686d4375ea37e259 100755 --- a/Services/Style/Content/classes/class.ilStyleColorTableGUI.php +++ b/Services/Style/Content/classes/class.ilStyleColorTableGUI.php @@ -1,24 +1,24 @@ ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $this->rbacsystem = $DIC->rbac()->system(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilAccess = $DIC->access(); - $lng = $DIC->language(); - $rbacsystem = $DIC->rbac()->system(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setTitle($lng->txt("sty_colors")); - $this->setDescription($lng->txt("sty_color_info")); - $this->style_obj = $a_style_obj; - - $this->addColumn("", "", "1"); // checkbox - $this->addColumn($this->lng->txt("sty_color_name"), ""); - $this->addColumn($this->lng->txt("sty_color_code"), ""); - $this->addColumn($this->lng->txt("sty_color"), ""); - $this->addColumn($this->lng->txt("sty_color_flavors"), ""); - $this->addColumn($this->lng->txt("sty_commands"), "", "1"); - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.style_color_row.html", "Services/Style/Content"); - //$this->setSelectAllCheckbox("file"); - $this->getItems(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->rbacsystem = $DIC->rbac()->system(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilAccess = $DIC->access(); + $lng = $DIC->language(); + $rbacsystem = $DIC->rbac()->system(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setTitle($lng->txt("sty_colors")); + $this->setDescription($lng->txt("sty_color_info")); + $this->style_obj = $a_style_obj; + + $this->addColumn("", "", "1"); // checkbox + $this->addColumn($this->lng->txt("sty_color_name"), ""); + $this->addColumn($this->lng->txt("sty_color_code"), ""); + $this->addColumn($this->lng->txt("sty_color"), ""); + $this->addColumn($this->lng->txt("sty_color_flavors"), ""); + $this->addColumn($this->lng->txt("sty_commands"), "", "1"); + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.style_color_row.html", "Services/Style/Content"); + //$this->setSelectAllCheckbox("file"); + $this->getItems(); - // action commands - if ($this->parent_obj->checkWrite()) - { - $this->addMultiCommand("deleteColorConfirmation", $lng->txt("delete")); - } - - $this->setEnableTitle(true); - } + // action commands + if ($this->parent_obj->checkWrite()) { + $this->addMultiCommand("deleteColorConfirmation", $lng->txt("delete")); + } + + $this->setEnableTitle(true); + } - /** - * Get items of current folder - */ - function getItems() - { - $this->setData($this->style_obj->getColors()); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - $rbacsystem = $this->rbacsystem; - - for ($i = -80; $i<=80; $i+=20) - { - $this->tpl->setCurrentBlock("flavor"); - $this->tpl->setVariable("FLAVOR_NAME", "(".$i.")"); - $this->tpl->setVariable("FLAVOR_CODE", - ilObjStyleSheet::_getColorFlavor($a_set["code"], $i)); - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setVariable("COLOR_NAME_ENC", ilUtil::prepareFormOutput($a_set["name"])); - $this->tpl->setVariable("COLOR_NAME", $a_set["name"]); - $this->tpl->setVariable("COLOR_CODE", $a_set["code"]); - - if ($this->parent_obj->checkWrite()) - { - $this->tpl->setVariable("TXT_EDIT", $lng->txt("edit")); - $ilCtrl->setParameter($this->parent_obj, "c_name", rawurlencode($a_set["name"])); - $this->tpl->setVariable("LINK_EDIT_COLOR", - $ilCtrl->getLinkTarget($this->parent_obj, "editColor")); - } - } + /** + * Get items of current folder + */ + public function getItems() + { + $this->setData($this->style_obj->getColors()); + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + $rbacsystem = $this->rbacsystem; + + for ($i = -80; $i<=80; $i+=20) { + $this->tpl->setCurrentBlock("flavor"); + $this->tpl->setVariable("FLAVOR_NAME", "(" . $i . ")"); + $this->tpl->setVariable( + "FLAVOR_CODE", + ilObjStyleSheet::_getColorFlavor($a_set["code"], $i) + ); + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setVariable("COLOR_NAME_ENC", ilUtil::prepareFormOutput($a_set["name"])); + $this->tpl->setVariable("COLOR_NAME", $a_set["name"]); + $this->tpl->setVariable("COLOR_CODE", $a_set["code"]); + + if ($this->parent_obj->checkWrite()) { + $this->tpl->setVariable("TXT_EDIT", $lng->txt("edit")); + $ilCtrl->setParameter($this->parent_obj, "c_name", rawurlencode($a_set["name"])); + $this->tpl->setVariable( + "LINK_EDIT_COLOR", + $ilCtrl->getLinkTarget($this->parent_obj, "editColor") + ); + } + } } -?> diff --git a/Services/Style/Content/classes/class.ilStyleImageTableGUI.php b/Services/Style/Content/classes/class.ilStyleImageTableGUI.php index 19e12c46351f8feeb9f8524ac5ded378db9c8b68..e65cdb2f02883e99f026814e2428eb7093360628 100755 --- a/Services/Style/Content/classes/class.ilStyleImageTableGUI.php +++ b/Services/Style/Content/classes/class.ilStyleImageTableGUI.php @@ -14,104 +14,102 @@ include_once("Services/Table/classes/class.ilTable2GUI.php"); */ class ilStyleImageTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * @var ilRbacSystem - */ - protected $rbacsystem; + /** + * @var ilRbacSystem + */ + protected $rbacsystem; - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_style_obj) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_style_obj) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $this->rbacsystem = $DIC->rbac()->system(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilAccess = $DIC->access(); - $lng = $DIC->language(); - $rbacsystem = $DIC->rbac()->system(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setTitle($lng->txt("sty_images")); - $this->style_obj = $a_style_obj; - - $this->addColumn("", "", "1"); // checkbox - $this->addColumn($this->lng->txt("thumbnail"), "", "1"); - $this->addColumn($this->lng->txt("file"), "", "33%"); - $this->addColumn($this->lng->txt("sty_width_height"), "", "33%"); - $this->addColumn($this->lng->txt("size"), "", "33%"); - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.style_image_row.html", "Services/Style/Content"); - $this->setSelectAllCheckbox("file"); - $this->getItems(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->rbacsystem = $DIC->rbac()->system(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilAccess = $DIC->access(); + $lng = $DIC->language(); + $rbacsystem = $DIC->rbac()->system(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setTitle($lng->txt("sty_images")); + $this->style_obj = $a_style_obj; + + $this->addColumn("", "", "1"); // checkbox + $this->addColumn($this->lng->txt("thumbnail"), "", "1"); + $this->addColumn($this->lng->txt("file"), "", "33%"); + $this->addColumn($this->lng->txt("sty_width_height"), "", "33%"); + $this->addColumn($this->lng->txt("size"), "", "33%"); + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.style_image_row.html", "Services/Style/Content"); + $this->setSelectAllCheckbox("file"); + $this->getItems(); - // action commands - if ($this->parent_obj->checkWrite()) - { - $this->addMultiCommand("deleteImage", $lng->txt("delete")); - } - - //$this->addMultiCommand("editLink", $lng->txt("cont_set_link")); - //$this->addCommandButton("addImage", $this->lng->txt("sty_add_image")); - - $this->setEnableTitle(true); - } + // action commands + if ($this->parent_obj->checkWrite()) { + $this->addMultiCommand("deleteImage", $lng->txt("delete")); + } + + //$this->addMultiCommand("editLink", $lng->txt("cont_set_link")); + //$this->addCommandButton("addImage", $this->lng->txt("sty_add_image")); + + $this->setEnableTitle(true); + } - /** - * Get items of current folder - */ - function getItems() - { - $this->setData($this->style_obj->getImages()); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; + /** + * Get items of current folder + */ + public function getItems() + { + $this->setData($this->style_obj->getImages()); + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; - $thumbfile = $this->style_obj->getThumbnailsDirectory()."/".$a_set["entry"]; - if (is_file($thumbfile)) - { - $this->tpl->setCurrentBlock("thumbnail"); - $this->tpl->setVariable("IMG_ALT", $a_set["entry"]); - $this->tpl->setVariable("IMG_SRC", $thumbfile); - $this->tpl->parseCurrentBlock(); - } - $image_file = $this->style_obj->getImagesDirectory()."/".$a_set["entry"]; - $image_size = @getimagesize($image_file); - { - if ($image_size[0] > 0 && $image_size[1] > 0) - { - $this->tpl->setVariable("VAL_WIDTH_HEIGHT", - $image_size[0]."px x ".$image_size[1]."px"); - } - } - - $this->tpl->setVariable("VAL_FILENAME", $a_set["entry"]); - $this->tpl->setVariable("VAL_SIZE", $a_set["size"]); - $this->tpl->setVariable("FILE", $a_set["entry"]); - } + $thumbfile = $this->style_obj->getThumbnailsDirectory() . "/" . $a_set["entry"]; + if (is_file($thumbfile)) { + $this->tpl->setCurrentBlock("thumbnail"); + $this->tpl->setVariable("IMG_ALT", $a_set["entry"]); + $this->tpl->setVariable("IMG_SRC", $thumbfile); + $this->tpl->parseCurrentBlock(); + } + $image_file = $this->style_obj->getImagesDirectory() . "/" . $a_set["entry"]; + $image_size = @getimagesize($image_file); + { + if ($image_size[0] > 0 && $image_size[1] > 0) { + $this->tpl->setVariable( + "VAL_WIDTH_HEIGHT", + $image_size[0] . "px x " . $image_size[1] . "px" + ); + } + } + + $this->tpl->setVariable("VAL_FILENAME", $a_set["entry"]); + $this->tpl->setVariable("VAL_SIZE", $a_set["size"]); + $this->tpl->setVariable("FILE", $a_set["entry"]); + } } -?> diff --git a/Services/Style/Content/classes/class.ilStyleImportParser.php b/Services/Style/Content/classes/class.ilStyleImportParser.php index dbcb026feadb63498e4b59f9a6c211c3ca18f884..ad177cfac3e9692a736f03bf0f35a834c33badcc 100755 --- a/Services/Style/Content/classes/class.ilStyleImportParser.php +++ b/Services/Style/Content/classes/class.ilStyleImportParser.php @@ -15,172 +15,165 @@ require_once("./Services/Xml/classes/class.ilSaxParser.php"); */ class ilStyleImportParser extends ilSaxParser { - /** - * @var ilTree - */ - protected $tree; - - - /** - * Constructor - * - * @param string $a_xml_file xml file - * @param int $a_mode IL_EXTRACT_ROLES | IL_USER_IMPORT - * - * @access public - */ - function __construct($a_xml_file, &$a_style_obj) - { - global $DIC; - - $this->lng = $DIC->language(); - $this->tree = $DIC->repositoryTree(); - $lng = $DIC->language(); - $tree = $DIC->repositoryTree(); - - $this->style_obj = $a_style_obj; - - parent::__construct($a_xml_file); - } - - - /** - * set event handler - * should be overwritten by inherited class - * @access private - */ - 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 - */ - function startParsing() - { - $this->styles = array(); - parent::startParsing(); - $this->style_obj->setStyle($this->styles); - $this->style_obj->setCharacteristics($this->chars); - } - - - /** - * handler for begin of element - */ - function handlerBeginTag($a_xml_parser, $a_name, $a_attribs) - { - - switch($a_name) - { - case "Style": - $this->current_tag = $a_attribs["Tag"]; - $this->current_class = $a_attribs["Class"]; - $this->current_type = $a_attribs["Type"]; - if ($this->current_class == "PageTitle" && $this->current_type == "page_title" && $this->current_tag == "div") - { - $this->current_tag = "h1"; - } - if ($this->current_class == "Headline1" && $this->current_tag == "div") - { - $this->current_tag = "h1"; - $this->current_type = "heading1"; - } - if ($this->current_class == "Headline2" && $this->current_tag == "div") - { - $this->current_tag = "h2"; - $this->current_type = "heading2"; - } - if ($this->current_class == "Headline3" && $this->current_tag == "div") - { - $this->current_tag = "h3"; - $this->current_type = "heading3"; - } - $this->current_tags = array(); - $this->chars[] = array("type" => $this->current_type, - "class" => $this->current_class); - break; - - case "StyleParameter": - $this->current_tags[] = array( - "tag" => $this->current_tag, - "class" => $this->current_class, - "parameter" => $a_attribs["Name"], - "type" => $this->current_type, - "value" => $a_attribs["Value"], - "custom" => $a_attribs["Custom"]); - break; - - case "StyleColor": - $this->style_obj->addColor($a_attribs["Name"], $a_attribs["Code"]); - break; - - case "StyleTemplate": - $this->cur_template = array("type" => $a_attribs["Type"], - "name" => $a_attribs["Name"]); - $this->cur_template_classes = array(); - break; - - case "StyleTemplateClass": - $this->cur_template_classes[$a_attribs["ClassType"]] = - $a_attribs["Class"]; - break; - - } - $this->cdata = ""; - } - - - /** - * handler for end of element - */ - function handlerEndTag($a_xml_parser, $a_name) - { - switch($a_name) - { - case "Title": - $this->style_obj->setTitle($this->cdata); - break; - - case "Description": - $this->style_obj->setDescription($this->cdata); - break; - - case "Style": - $this->styles[] = $this->current_tags; - break; - - case "StyleTemplate": - $this->style_obj->addTemplate($this->cur_template["type"], - $this->cur_template["name"], $this->cur_template_classes); - break; - - } - } - - /** - * handler for character data - */ - function handlerCharacterData($a_xml_parser, $a_data) - { - // i don't know why this is necessary, but - // the parser seems to convert ">" to ">" and "<" to "<" - // in character data, but we don't want that, because it's the - // way we mask user html in our content, so we convert back... - $a_data = str_replace("<","<",$a_data); - $a_data = str_replace(">",">",$a_data); - - // DELETE WHITESPACES AND NEWLINES OF CHARACTER DATA - $a_data = preg_replace("/\n/","",$a_data); - $a_data = preg_replace("/\t+/","",$a_data); - if(!empty($a_data)) - { - $this->cdata .= $a_data; - } - } - + /** + * @var ilTree + */ + protected $tree; + + + /** + * Constructor + * + * @param string $a_xml_file xml file + * @param int $a_mode IL_EXTRACT_ROLES | IL_USER_IMPORT + * + * @access public + */ + public function __construct($a_xml_file, &$a_style_obj) + { + global $DIC; + + $this->lng = $DIC->language(); + $this->tree = $DIC->repositoryTree(); + $lng = $DIC->language(); + $tree = $DIC->repositoryTree(); + + $this->style_obj = $a_style_obj; + + parent::__construct($a_xml_file); + } + + + /** + * 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() + { + $this->styles = array(); + parent::startParsing(); + $this->style_obj->setStyle($this->styles); + $this->style_obj->setCharacteristics($this->chars); + } + + + /** + * handler for begin of element + */ + public function handlerBeginTag($a_xml_parser, $a_name, $a_attribs) + { + switch ($a_name) { + case "Style": + $this->current_tag = $a_attribs["Tag"]; + $this->current_class = $a_attribs["Class"]; + $this->current_type = $a_attribs["Type"]; + if ($this->current_class == "PageTitle" && $this->current_type == "page_title" && $this->current_tag == "div") { + $this->current_tag = "h1"; + } + if ($this->current_class == "Headline1" && $this->current_tag == "div") { + $this->current_tag = "h1"; + $this->current_type = "heading1"; + } + if ($this->current_class == "Headline2" && $this->current_tag == "div") { + $this->current_tag = "h2"; + $this->current_type = "heading2"; + } + if ($this->current_class == "Headline3" && $this->current_tag == "div") { + $this->current_tag = "h3"; + $this->current_type = "heading3"; + } + $this->current_tags = array(); + $this->chars[] = array("type" => $this->current_type, + "class" => $this->current_class); + break; + + case "StyleParameter": + $this->current_tags[] = array( + "tag" => $this->current_tag, + "class" => $this->current_class, + "parameter" => $a_attribs["Name"], + "type" => $this->current_type, + "value" => $a_attribs["Value"], + "custom" => $a_attribs["Custom"]); + break; + + case "StyleColor": + $this->style_obj->addColor($a_attribs["Name"], $a_attribs["Code"]); + break; + + case "StyleTemplate": + $this->cur_template = array("type" => $a_attribs["Type"], + "name" => $a_attribs["Name"]); + $this->cur_template_classes = array(); + break; + + case "StyleTemplateClass": + $this->cur_template_classes[$a_attribs["ClassType"]] = + $a_attribs["Class"]; + break; + + } + $this->cdata = ""; + } + + + /** + * handler for end of element + */ + public function handlerEndTag($a_xml_parser, $a_name) + { + switch ($a_name) { + case "Title": + $this->style_obj->setTitle($this->cdata); + break; + + case "Description": + $this->style_obj->setDescription($this->cdata); + break; + + case "Style": + $this->styles[] = $this->current_tags; + break; + + case "StyleTemplate": + $this->style_obj->addTemplate( + $this->cur_template["type"], + $this->cur_template["name"], + $this->cur_template_classes + ); + break; + + } + } + + /** + * handler for character data + */ + public function handlerCharacterData($a_xml_parser, $a_data) + { + // i don't know why this is necessary, but + // the parser seems to convert ">" to ">" and "<" to "<" + // in character data, but we don't want that, because it's the + // way we mask user html in our content, so we convert back... + $a_data = str_replace("<", "<", $a_data); + $a_data = str_replace(">", ">", $a_data); + + // DELETE WHITESPACES AND NEWLINES OF CHARACTER DATA + $a_data = preg_replace("/\n/", "", $a_data); + $a_data = preg_replace("/\t+/", "", $a_data); + if (!empty($a_data)) { + $this->cdata .= $a_data; + } + } } -?> diff --git a/Services/Style/Content/classes/class.ilStyleMediaQueryTableGUI.php b/Services/Style/Content/classes/class.ilStyleMediaQueryTableGUI.php index 33bf40f2fcbf2462725599984ce101db186dcb50..961bf688fd98ab5394d82f0e6fe52b30a49156b1 100755 --- a/Services/Style/Content/classes/class.ilStyleMediaQueryTableGUI.php +++ b/Services/Style/Content/classes/class.ilStyleMediaQueryTableGUI.php @@ -1,24 +1,24 @@ ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $this->rbacsystem = $DIC->rbac()->system(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilAccess = $DIC->access(); - $lng = $DIC->language(); - $rbacsystem = $DIC->rbac()->system(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - - $this->setTitle($lng->txt("sty_media_queries")); - $this->setDescription($lng->txt("sty_media_query_info")); - $this->style_obj = $a_style_obj; - - $this->addColumn("", "", "1"); // checkbox - $this->addColumn($this->lng->txt("sty_order")); - $this->addColumn($this->lng->txt("sty_query"), ""); - $this->addColumn($this->lng->txt("actions"), ""); - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.style_media_query_row.html", "Services/Style/Content"); - //$this->setSelectAllCheckbox("file"); - $this->getItems(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->rbacsystem = $DIC->rbac()->system(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilAccess = $DIC->access(); + $lng = $DIC->language(); + $rbacsystem = $DIC->rbac()->system(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + + $this->setTitle($lng->txt("sty_media_queries")); + $this->setDescription($lng->txt("sty_media_query_info")); + $this->style_obj = $a_style_obj; + + $this->addColumn("", "", "1"); // checkbox + $this->addColumn($this->lng->txt("sty_order")); + $this->addColumn($this->lng->txt("sty_query"), ""); + $this->addColumn($this->lng->txt("actions"), ""); + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.style_media_query_row.html", "Services/Style/Content"); + //$this->setSelectAllCheckbox("file"); + $this->getItems(); - // action commands - if ($this->parent_obj->checkWrite()) - { - $this->addCommandButton("saveMediaQueryOrder", $lng->txt("sty_save_order")); - $this->addMultiCommand("deleteMediaQueryConfirmation", $lng->txt("delete")); - } - - $this->setEnableTitle(true); - } + // action commands + if ($this->parent_obj->checkWrite()) { + $this->addCommandButton("saveMediaQueryOrder", $lng->txt("sty_save_order")); + $this->addMultiCommand("deleteMediaQueryConfirmation", $lng->txt("delete")); + } + + $this->setEnableTitle(true); + } - /** - * Get items of current folder - */ - function getItems() - { - $this->setData($this->style_obj->getMediaQueries()); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - $rbacsystem = $this->rbacsystem; - - $this->tpl->setVariable("MQUERY", $a_set["mquery"]); - $this->tpl->setVariable("MQID", $a_set["id"]); - $this->tpl->setVariable("ORDER_NR", $a_set["order_nr"]); + /** + * Get items of current folder + */ + public function getItems() + { + $this->setData($this->style_obj->getMediaQueries()); + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + $rbacsystem = $this->rbacsystem; + + $this->tpl->setVariable("MQUERY", $a_set["mquery"]); + $this->tpl->setVariable("MQID", $a_set["id"]); + $this->tpl->setVariable("ORDER_NR", $a_set["order_nr"]); - if ($this->parent_obj->checkWrite()) - { - $this->tpl->setVariable("TXT_EDIT", $lng->txt("edit")); - $ilCtrl->setParameter($this->parent_obj, "mq_id", $a_set["id"]); - $this->tpl->setVariable("LINK_EDIT_MQUERY", - $ilCtrl->getLinkTarget($this->parent_obj, "editMediaQuery")); - } - } + if ($this->parent_obj->checkWrite()) { + $this->tpl->setVariable("TXT_EDIT", $lng->txt("edit")); + $ilCtrl->setParameter($this->parent_obj, "mq_id", $a_set["id"]); + $this->tpl->setVariable( + "LINK_EDIT_MQUERY", + $ilCtrl->getLinkTarget($this->parent_obj, "editMediaQuery") + ); + } + } } -?> diff --git a/Services/Style/Content/classes/class.ilStyleTableGUI.php b/Services/Style/Content/classes/class.ilStyleTableGUI.php index da72151a2344b39910a50b5c75e777407081f3a8..d1db2ab47465484b064d5a2e8c1d3398346f045d 100755 --- a/Services/Style/Content/classes/class.ilStyleTableGUI.php +++ b/Services/Style/Content/classes/class.ilStyleTableGUI.php @@ -14,180 +14,168 @@ include_once("Services/Table/classes/class.ilTable2GUI.php"); */ class ilStyleTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; + /** + * @var ilCtrl + */ + protected $ctrl; - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * @var ilRbacSystem - */ - protected $rbacsystem; + /** + * @var ilRbacSystem + */ + protected $rbacsystem; - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_chars, $a_super_type, $a_style) - { - global $DIC; + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_chars, $a_super_type, $a_style) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $this->rbacsystem = $DIC->rbac()->system(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilAccess = $DIC->access(); - $lng = $DIC->language(); - $rbacsystem = $DIC->rbac()->system(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->media_object = $a_media_object; - $this->super_type = $a_super_type; - $this->style = $a_style; - $all_super_types = ilObjStyleSheet::_getStyleSuperTypes(); - $this->types = $all_super_types[$this->super_type]; - $this->core_styles = ilObjStyleSheet::_getCoreStyles(); - $this->setData($a_chars); - $this->setTitle($lng->txt("sty_".$a_super_type."_char")); - $this->setLimit(9999); - - // check, whether any of the types is expandable - $this->expandable = false; - $this->hideable = false; - foreach ($this->types as $t) - { - if (ilObjStyleSheet::_isExpandable($t)) - { - $this->expandable = true; - } - if (ilObjStyleSheet::_isHideable($t)) - { - $this->hideable = true; - } - } + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->rbacsystem = $DIC->rbac()->system(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilAccess = $DIC->access(); + $lng = $DIC->language(); + $rbacsystem = $DIC->rbac()->system(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->media_object = $a_media_object; + $this->super_type = $a_super_type; + $this->style = $a_style; + $all_super_types = ilObjStyleSheet::_getStyleSuperTypes(); + $this->types = $all_super_types[$this->super_type]; + $this->core_styles = ilObjStyleSheet::_getCoreStyles(); + $this->setData($a_chars); + $this->setTitle($lng->txt("sty_" . $a_super_type . "_char")); + $this->setLimit(9999); + + // check, whether any of the types is expandable + $this->expandable = false; + $this->hideable = false; + foreach ($this->types as $t) { + if (ilObjStyleSheet::_isExpandable($t)) { + $this->expandable = true; + } + if (ilObjStyleSheet::_isHideable($t)) { + $this->hideable = true; + } + } -// if ($this->expandable) + // if ($this->expandable) // { - $this->addColumn("", "", "1"); // checkbox + $this->addColumn("", "", "1"); // checkbox // } - $this->addColumn($this->lng->txt("sty_name"), "", "1"); - $this->addColumn($this->lng->txt("sty_type"), "", ""); - $this->addColumn($this->lng->txt("sty_example"), "", ""); - if ($this->hideable) - { - $this->addColumn($this->lng->txt("sty_hide"), "", ""); // hide checkbox - } - $this->addColumn($this->lng->txt("sty_commands"), "", "1"); - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.style_row.html", "Services/Style/Content"); - $this->disable("footer"); + $this->addColumn($this->lng->txt("sty_name"), "", "1"); + $this->addColumn($this->lng->txt("sty_type"), "", ""); + $this->addColumn($this->lng->txt("sty_example"), "", ""); + if ($this->hideable) { + $this->addColumn($this->lng->txt("sty_hide"), "", ""); // hide checkbox + } + $this->addColumn($this->lng->txt("sty_commands"), "", "1"); + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.style_row.html", "Services/Style/Content"); + $this->disable("footer"); - if ($this->parent_obj->checkWrite()) - { - // action commands - if ($this->hideable) - { - $this->addCommandButton("saveHideStatus", $lng->txt("sty_save_hide_status")); - } - - $this->addMultiCommand("copyCharacteristics", $lng->txt("copy")); - - // action commands - if ($this->expandable) - { - $this->addMultiCommand("deleteCharacteristicConfirmation", $lng->txt("delete")); - //$this->addCommandButton("addCharacteristicForm", $lng->txt("sty_add_characteristic")); - } - } - - $this->setEnableTitle(true); - } - - /** - * Standard Version of Fill Row. Most likely to - * be overwritten by derived class. - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - $rbacsystem = $this->rbacsystem; + if ($this->parent_obj->checkWrite()) { + // action commands + if ($this->hideable) { + $this->addCommandButton("saveHideStatus", $lng->txt("sty_save_hide_status")); + } + + $this->addMultiCommand("copyCharacteristics", $lng->txt("copy")); + + // action commands + if ($this->expandable) { + $this->addMultiCommand("deleteCharacteristicConfirmation", $lng->txt("delete")); + //$this->addCommandButton("addCharacteristicForm", $lng->txt("sty_add_characteristic")); + } + } + + $this->setEnableTitle(true); + } + + /** + * Standard Version of Fill Row. Most likely to + * be overwritten by derived class. + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + $rbacsystem = $this->rbacsystem; - $stypes = ilObjStyleSheet::_getStyleSuperTypes(); - $types = $stypes[$this->super_type]; - - if (!in_array($a_set["type"], $types)) - { - return; - } -//var_dump($a_set); - // checkbox row -/* if ($this->expandable) - { - if (!empty($this->core_styles[$a_set["type"].".". - ilObjStyleSheet::_determineTag($a_set["type"]). - ".".$a_set["class"]])) - { - $this->tpl->touchBlock("no_checkbox"); - } - else - {*/ - $this->tpl->setCurrentBlock("checkbox"); - $this->tpl->setVariable("CHAR", $a_set["type"].".". - ilObjStyleSheet::_determineTag($a_set["type"]). - ".".$a_set["class"]); - $this->tpl->parseCurrentBlock(); -/* } - }*/ - - if ($this->hideable) - { - if (!ilObjStyleSheet::_isHideable($a_set["type"]) || - (!empty($this->core_styles[$a_set["type"].".". - ilObjStyleSheet::_determineTag($a_set["type"]). - ".".$a_set["class"]]))) - { - $this->tpl->touchBlock("no_hide_checkbox"); - } - else - { - $this->tpl->setCurrentBlock("hide_checkbox"); - $this->tpl->setVariable("CHAR", $a_set["type"].".". - ilObjStyleSheet::_determineTag($a_set["type"]). - ".".$a_set["class"]); - if ($this->style->getHideStatus($a_set["type"], $a_set["class"])) - { - $this->tpl->setVariable("CHECKED", "checked='checked'"); - } - $this->tpl->parseCurrentBlock(); - } - } - - // example - $this->tpl->setVariable("EXAMPLE", - ilObjStyleSheetGUI::getStyleExampleHTML($a_set["type"], $a_set["class"])); - $tag_str = ilObjStyleSheet::_determineTag($a_set["type"]).".".$a_set["class"]; - $this->tpl->setVariable("TXT_TAG", $a_set["class"]); - $this->tpl->setVariable("TXT_TYPE", $lng->txt("sty_type_".$a_set["type"])); - - if ($this->parent_obj->checkWrite()) - { - $this->tpl->setVariable("TXT_EDIT", $this->lng->txt("edit")); - $ilCtrl->setParameter($this->parent_obj, "tag", $tag_str); - $ilCtrl->setParameter($this->parent_obj, "style_type", $a_set["type"]); - $this->tpl->setVariable("LINK_EDIT_TAG_STYLE", - $ilCtrl->getLinkTarget($this->parent_obj, "editTagStyle")); - } - } + $stypes = ilObjStyleSheet::_getStyleSuperTypes(); + $types = $stypes[$this->super_type]; + + if (!in_array($a_set["type"], $types)) { + return; + } + //var_dump($a_set); + // checkbox row + /* if ($this->expandable) + { + if (!empty($this->core_styles[$a_set["type"].".". + ilObjStyleSheet::_determineTag($a_set["type"]). + ".".$a_set["class"]])) + { + $this->tpl->touchBlock("no_checkbox"); + } + else + {*/ + $this->tpl->setCurrentBlock("checkbox"); + $this->tpl->setVariable("CHAR", $a_set["type"] . "." . + ilObjStyleSheet::_determineTag($a_set["type"]) . + "." . $a_set["class"]); + $this->tpl->parseCurrentBlock(); + /* } + }*/ + if ($this->hideable) { + if (!ilObjStyleSheet::_isHideable($a_set["type"]) || + (!empty($this->core_styles[$a_set["type"] . "." . + ilObjStyleSheet::_determineTag($a_set["type"]) . + "." . $a_set["class"]]))) { + $this->tpl->touchBlock("no_hide_checkbox"); + } else { + $this->tpl->setCurrentBlock("hide_checkbox"); + $this->tpl->setVariable("CHAR", $a_set["type"] . "." . + ilObjStyleSheet::_determineTag($a_set["type"]) . + "." . $a_set["class"]); + if ($this->style->getHideStatus($a_set["type"], $a_set["class"])) { + $this->tpl->setVariable("CHECKED", "checked='checked'"); + } + $this->tpl->parseCurrentBlock(); + } + } + + // example + $this->tpl->setVariable( + "EXAMPLE", + ilObjStyleSheetGUI::getStyleExampleHTML($a_set["type"], $a_set["class"]) + ); + $tag_str = ilObjStyleSheet::_determineTag($a_set["type"]) . "." . $a_set["class"]; + $this->tpl->setVariable("TXT_TAG", $a_set["class"]); + $this->tpl->setVariable("TXT_TYPE", $lng->txt("sty_type_" . $a_set["type"])); + + if ($this->parent_obj->checkWrite()) { + $this->tpl->setVariable("TXT_EDIT", $this->lng->txt("edit")); + $ilCtrl->setParameter($this->parent_obj, "tag", $tag_str); + $ilCtrl->setParameter($this->parent_obj, "style_type", $a_set["type"]); + $this->tpl->setVariable( + "LINK_EDIT_TAG_STYLE", + $ilCtrl->getLinkTarget($this->parent_obj, "editTagStyle") + ); + } + } } -?> diff --git a/Services/Style/Content/classes/class.ilTRBLBorderStyleInputGUI.php b/Services/Style/Content/classes/class.ilTRBLBorderStyleInputGUI.php index ff40084c85f993a48d3e1bb58cd6efef93ca8c7e..3182cbf1011d4b27cebd05fdf479816b512ac23c 100755 --- a/Services/Style/Content/classes/class.ilTRBLBorderStyleInputGUI.php +++ b/Services/Style/Content/classes/class.ilTRBLBorderStyleInputGUI.php @@ -5,239 +5,232 @@ /** * This class represents a border style with all/top/right/bottom/left in a property form. * -* @author Alex Killing +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilTRBLBorderStyleInputGUI extends ilFormPropertyGUI { - /** - * @var ilObjUser - */ - protected $user; - - protected $value; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; - - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - parent::__construct($a_title, $a_postvar); - $this->setType("border_style"); - $this->dirs = array("all", "top", "bottom", "left", "right"); - } - - /** - * Set All Value. - * - * @param string $a_allvalue All Value - */ - function setAllValue($a_allvalue) - { - $this->allvalue = $a_allvalue; - } - - /** - * Get All Value. - * - * @return string All Value - */ - function getAllValue() - { - return $this->allvalue; - } - - /** - * Set Top Value. - * - * @param string $a_topvalue Top Value - */ - function setTopValue($a_topvalue) - { - $this->topvalue = $a_topvalue; - } - - /** - * Get Top Value. - * - * @return string Top Value - */ - function getTopValue() - { - return $this->topvalue; - } - - /** - * Set Bottom Value. - * - * @param string $a_bottomvalue Bottom Value - */ - function setBottomValue($a_bottomvalue) - { - $this->bottomvalue = $a_bottomvalue; - } - - /** - * Get Bottom Value. - * - * @return string Bottom Value - */ - function getBottomValue() - { - return $this->bottomvalue; - } - - /** - * Set Left Value. - * - * @param string $a_leftvalue Left Value - */ - function setLeftValue($a_leftvalue) - { - $this->leftvalue = $a_leftvalue; - } - - /** - * Get Left Value. - * - * @return string Left Value - */ - function getLeftValue() - { - return $this->leftvalue; - } - - /** - * Set Right Value. - * - * @param string $a_rightvalue Right Value - */ - function setRightValue($a_rightvalue) - { - $this->rightvalue = $a_rightvalue; - } - - /** - * Get Right Value. - * - * @return string Right Value - */ - function getRightValue() - { - return $this->rightvalue; - } - - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - foreach ($this->dirs as $dir) - { - $pre_value = $_POST[$this->getPostVar()][$dir]["pre_value"] = - ilUtil::stripSlashes($_POST[$this->getPostVar()][$dir]["pre_value"]); - - /* - if ($this->getRequired() && trim($num_value) == "") - { - $this->setAlert($lng->txt("msg_input_is_required")); - - return false; - }*/ - - $value = $pre_value; - - if (trim($value) != "") - { - switch ($dir) - { - case "all": $this->setAllValue($value); break; - case "top": $this->setTopValue($value); break; - case "bottom": $this->setBottomValue($value); break; - case "left": $this->setLeftValue($value); break; - case "right": $this->setRightValue($value); break; - } - } - - } - - return true; - } - - /** - * Insert property html - */ - function insert(&$a_tpl) - { - $lng = $this->lng; - - $layout_tpl = new ilTemplate("tpl.prop_trbl_layout.html", true, true, "Services/Style/Content"); - - foreach ($this->dirs as $dir) - { - $tpl = new ilTemplate("tpl.prop_trbl_select.html", true, true, "Services/Style/Content"); - $pre_options = array_merge(array("" => ""), - ilObjStyleSheet::_getStyleParameterValues("border-style")); - - switch($dir) - { - case "all": $value = strtolower(trim($this->getAllValue())); break; - case "top": $value = strtolower(trim($this->getTopValue())); break; - case "bottom": $value = strtolower(trim($this->getBottomValue())); break; - case "left": $value = strtolower(trim($this->getLeftValue())); break; - case "right": $value = strtolower(trim($this->getRightValue())); break; - } - - foreach ($pre_options as $option) - { - $tpl->setCurrentBlock("pre_option"); - $tpl->setVariable("VAL_PRE", $option); - $tpl->setVariable("TXT_PRE", $option); - if ($value == $option) - { - $tpl->setVariable("PRE_SELECTED", 'selected="selected"'); - } - $tpl->parseCurrentBlock(); - } - - $tpl->setVariable("POSTVAR", $this->getPostVar()); - $tpl->setVariable("TXT_DIR", $lng->txt("sty_$dir")); - $tpl->setVariable("DIR", $dir); - - $layout_tpl->setVariable(strtoupper($dir), $tpl->get()); - } - - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $layout_tpl->get()); - $a_tpl->parseCurrentBlock(); - } - - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $ilUser = $this->user; - - $this->setAllValue($a_values[$this->getPostVar()]["all"]["pre_value"]); - $this->setBottomValue($a_values[$this->getPostVar()]["bottom"]["pre_value"]); - $this->setTopValue($a_values[$this->getPostVar()]["top"]["pre_value"]); - $this->setLeftValue($a_values[$this->getPostVar()]["left"]["pre_value"]); - $this->setRightValue($a_values[$this->getPostVar()]["right"]["pre_value"]); - } - + /** + * @var ilObjUser + */ + protected $user; + + protected $value; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; + + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + parent::__construct($a_title, $a_postvar); + $this->setType("border_style"); + $this->dirs = array("all", "top", "bottom", "left", "right"); + } + + /** + * Set All Value. + * + * @param string $a_allvalue All Value + */ + public function setAllValue($a_allvalue) + { + $this->allvalue = $a_allvalue; + } + + /** + * Get All Value. + * + * @return string All Value + */ + public function getAllValue() + { + return $this->allvalue; + } + + /** + * Set Top Value. + * + * @param string $a_topvalue Top Value + */ + public function setTopValue($a_topvalue) + { + $this->topvalue = $a_topvalue; + } + + /** + * Get Top Value. + * + * @return string Top Value + */ + public function getTopValue() + { + return $this->topvalue; + } + + /** + * Set Bottom Value. + * + * @param string $a_bottomvalue Bottom Value + */ + public function setBottomValue($a_bottomvalue) + { + $this->bottomvalue = $a_bottomvalue; + } + + /** + * Get Bottom Value. + * + * @return string Bottom Value + */ + public function getBottomValue() + { + return $this->bottomvalue; + } + + /** + * Set Left Value. + * + * @param string $a_leftvalue Left Value + */ + public function setLeftValue($a_leftvalue) + { + $this->leftvalue = $a_leftvalue; + } + + /** + * Get Left Value. + * + * @return string Left Value + */ + public function getLeftValue() + { + return $this->leftvalue; + } + + /** + * Set Right Value. + * + * @param string $a_rightvalue Right Value + */ + public function setRightValue($a_rightvalue) + { + $this->rightvalue = $a_rightvalue; + } + + /** + * Get Right Value. + * + * @return string Right Value + */ + public function getRightValue() + { + return $this->rightvalue; + } + + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + foreach ($this->dirs as $dir) { + $pre_value = $_POST[$this->getPostVar()][$dir]["pre_value"] = + ilUtil::stripSlashes($_POST[$this->getPostVar()][$dir]["pre_value"]); + + /* + if ($this->getRequired() && trim($num_value) == "") + { + $this->setAlert($lng->txt("msg_input_is_required")); + + return false; + }*/ + + $value = $pre_value; + + if (trim($value) != "") { + switch ($dir) { + case "all": $this->setAllValue($value); break; + case "top": $this->setTopValue($value); break; + case "bottom": $this->setBottomValue($value); break; + case "left": $this->setLeftValue($value); break; + case "right": $this->setRightValue($value); break; + } + } + } + + return true; + } + + /** + * Insert property html + */ + public function insert(&$a_tpl) + { + $lng = $this->lng; + + $layout_tpl = new ilTemplate("tpl.prop_trbl_layout.html", true, true, "Services/Style/Content"); + + foreach ($this->dirs as $dir) { + $tpl = new ilTemplate("tpl.prop_trbl_select.html", true, true, "Services/Style/Content"); + $pre_options = array_merge( + array("" => ""), + ilObjStyleSheet::_getStyleParameterValues("border-style") + ); + + switch ($dir) { + case "all": $value = strtolower(trim($this->getAllValue())); break; + case "top": $value = strtolower(trim($this->getTopValue())); break; + case "bottom": $value = strtolower(trim($this->getBottomValue())); break; + case "left": $value = strtolower(trim($this->getLeftValue())); break; + case "right": $value = strtolower(trim($this->getRightValue())); break; + } + + foreach ($pre_options as $option) { + $tpl->setCurrentBlock("pre_option"); + $tpl->setVariable("VAL_PRE", $option); + $tpl->setVariable("TXT_PRE", $option); + if ($value == $option) { + $tpl->setVariable("PRE_SELECTED", 'selected="selected"'); + } + $tpl->parseCurrentBlock(); + } + + $tpl->setVariable("POSTVAR", $this->getPostVar()); + $tpl->setVariable("TXT_DIR", $lng->txt("sty_$dir")); + $tpl->setVariable("DIR", $dir); + + $layout_tpl->setVariable(strtoupper($dir), $tpl->get()); + } + + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $layout_tpl->get()); + $a_tpl->parseCurrentBlock(); + } + + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $ilUser = $this->user; + + $this->setAllValue($a_values[$this->getPostVar()]["all"]["pre_value"]); + $this->setBottomValue($a_values[$this->getPostVar()]["bottom"]["pre_value"]); + $this->setTopValue($a_values[$this->getPostVar()]["top"]["pre_value"]); + $this->setLeftValue($a_values[$this->getPostVar()]["left"]["pre_value"]); + $this->setRightValue($a_values[$this->getPostVar()]["right"]["pre_value"]); + } } diff --git a/Services/Style/Content/classes/class.ilTRBLBorderWidthInputGUI.php b/Services/Style/Content/classes/class.ilTRBLBorderWidthInputGUI.php index 69c32fd3fcbba46d31b97695aa4e2b1cf964d3fe..187287264d30d1307fda6397b623a3c0372a2579 100755 --- a/Services/Style/Content/classes/class.ilTRBLBorderWidthInputGUI.php +++ b/Services/Style/Content/classes/class.ilTRBLBorderWidthInputGUI.php @@ -1,364 +1,327 @@ +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilTRBLBorderWidthInputGUI extends ilFormPropertyGUI { - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - protected $value; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + protected $value; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - parent::__construct($a_title, $a_postvar); - $this->setType("border_width"); - $this->dirs = array("all", "top", "bottom", "left", "right"); - } + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + parent::__construct($a_title, $a_postvar); + $this->setType("border_width"); + $this->dirs = array("all", "top", "bottom", "left", "right"); + } - /** - * Set All Value. - * - * @param string $a_allvalue All Value - */ - function setAllValue($a_allvalue) - { - $this->allvalue = $a_allvalue; - } + /** + * Set All Value. + * + * @param string $a_allvalue All Value + */ + public function setAllValue($a_allvalue) + { + $this->allvalue = $a_allvalue; + } - /** - * Get All Value. - * - * @return string All Value - */ - function getAllValue() - { - return $this->allvalue; - } + /** + * Get All Value. + * + * @return string All Value + */ + public function getAllValue() + { + return $this->allvalue; + } - /** - * Set Top Value. - * - * @param string $a_topvalue Top Value - */ - function setTopValue($a_topvalue) - { - $this->topvalue = $a_topvalue; - } + /** + * Set Top Value. + * + * @param string $a_topvalue Top Value + */ + public function setTopValue($a_topvalue) + { + $this->topvalue = $a_topvalue; + } - /** - * Get Top Value. - * - * @return string Top Value - */ - function getTopValue() - { - return $this->topvalue; - } + /** + * Get Top Value. + * + * @return string Top Value + */ + public function getTopValue() + { + return $this->topvalue; + } - /** - * Set Bottom Value. - * - * @param string $a_bottomvalue Bottom Value - */ - function setBottomValue($a_bottomvalue) - { - $this->bottomvalue = $a_bottomvalue; - } + /** + * Set Bottom Value. + * + * @param string $a_bottomvalue Bottom Value + */ + public function setBottomValue($a_bottomvalue) + { + $this->bottomvalue = $a_bottomvalue; + } - /** - * Get Bottom Value. - * - * @return string Bottom Value - */ - function getBottomValue() - { - return $this->bottomvalue; - } + /** + * Get Bottom Value. + * + * @return string Bottom Value + */ + public function getBottomValue() + { + return $this->bottomvalue; + } - /** - * Set Left Value. - * - * @param string $a_leftvalue Left Value - */ - function setLeftValue($a_leftvalue) - { - $this->leftvalue = $a_leftvalue; - } + /** + * Set Left Value. + * + * @param string $a_leftvalue Left Value + */ + public function setLeftValue($a_leftvalue) + { + $this->leftvalue = $a_leftvalue; + } - /** - * Get Left Value. - * - * @return string Left Value - */ - function getLeftValue() - { - return $this->leftvalue; - } + /** + * Get Left Value. + * + * @return string Left Value + */ + public function getLeftValue() + { + return $this->leftvalue; + } - /** - * Set Right Value. - * - * @param string $a_rightvalue Right Value - */ - function setRightValue($a_rightvalue) - { - $this->rightvalue = $a_rightvalue; - } + /** + * Set Right Value. + * + * @param string $a_rightvalue Right Value + */ + public function setRightValue($a_rightvalue) + { + $this->rightvalue = $a_rightvalue; + } - /** - * Get Right Value. - * - * @return string Right Value - */ - function getRightValue() - { - return $this->rightvalue; - } + /** + * Get Right Value. + * + * @return string Right Value + */ + public function getRightValue() + { + return $this->rightvalue; + } - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - foreach ($this->dirs as $dir) - { - $type = $_POST[$this->getPostVar()][$dir]["type"] = - ilUtil::stripSlashes($_POST[$this->getPostVar()][$dir]["type"]); - $num_value = $_POST[$this->getPostVar()][$dir]["num_value"] = - trim(ilUtil::stripSlashes($_POST[$this->getPostVar()][$dir]["num_value"])); - $num_unit = $_POST[$this->getPostVar()][$dir]["num_unit"] = - trim(ilUtil::stripSlashes($_POST[$this->getPostVar()][$dir]["num_unit"])); - $pre_value = $_POST[$this->getPostVar()][$dir]["pre_calue"] = - ilUtil::stripSlashes($_POST[$this->getPostVar()][$dir]["pre_value"]); - - /* - if ($this->getRequired() && trim($num_value) == "") - { - $this->setAlert($lng->txt("msg_input_is_required")); - - return false; - }*/ - - if (!is_numeric($num_value) && $num_value != "") - { - $this->setAlert($lng->txt("sty_msg_input_must_be_numeric")); - return false; - } - - $value = ""; - if ($type == "numeric") - { - if ($num_value != "") - { - $value = $num_value.$num_unit; - } - } - else - { - $value = $pre_value; - } - - if (trim($value) != "") - { - switch ($dir) - { - case "all": $this->setAllValue($value); break; - case "top": $this->setTopValue($value); break; - case "bottom": $this->setBottomValue($value); break; - case "left": $this->setLeftValue($value); break; - case "right": $this->setRightValue($value); break; - } - } - - } - - return true; - } + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + foreach ($this->dirs as $dir) { + $type = $_POST[$this->getPostVar()][$dir]["type"] = + ilUtil::stripSlashes($_POST[$this->getPostVar()][$dir]["type"]); + $num_value = $_POST[$this->getPostVar()][$dir]["num_value"] = + trim(ilUtil::stripSlashes($_POST[$this->getPostVar()][$dir]["num_value"])); + $num_unit = $_POST[$this->getPostVar()][$dir]["num_unit"] = + trim(ilUtil::stripSlashes($_POST[$this->getPostVar()][$dir]["num_unit"])); + $pre_value = $_POST[$this->getPostVar()][$dir]["pre_calue"] = + ilUtil::stripSlashes($_POST[$this->getPostVar()][$dir]["pre_value"]); + + /* + if ($this->getRequired() && trim($num_value) == "") + { + $this->setAlert($lng->txt("msg_input_is_required")); - /** - * Insert property html - */ - function insert(&$a_tpl) - { - $lng = $this->lng; - - $layout_tpl = new ilTemplate("tpl.prop_trbl_layout.html", true, true, "Services/Style/Content"); - - foreach ($this->dirs as $dir) - { - $tpl = new ilTemplate("tpl.prop_trbl_border_width.html", true, true, "Services/Style/Content"); - $unit_options = ilObjStyleSheet::_getStyleParameterNumericUnits(); - $pre_options = ilObjStyleSheet::_getStyleParameterValues("border-width"); - - switch($dir) - { - case "all": $value = strtolower(trim($this->getAllValue())); break; - case "top": $value = strtolower(trim($this->getTopValue())); break; - case "bottom": $value = strtolower(trim($this->getBottomValue())); break; - case "left": $value = strtolower(trim($this->getLeftValue())); break; - case "right": $value = strtolower(trim($this->getRightValue())); break; - } - - if (in_array($value, $pre_options)) - { - $current_type = "pre"; - $tpl->setVariable("PREDEFINED_SELECTED", 'checked="checked"'); - } - else - { - $current_type = "unit"; - $tpl->setVariable("NUMERIC_SELECTED", 'checked="checked"'); + return false; + }*/ + + if (!is_numeric($num_value) && $num_value != "") { + $this->setAlert($lng->txt("sty_msg_input_must_be_numeric")); + return false; + } + + $value = ""; + if ($type == "numeric") { + if ($num_value != "") { + $value = $num_value . $num_unit; + } + } else { + $value = $pre_value; + } + + if (trim($value) != "") { + switch ($dir) { + case "all": $this->setAllValue($value); break; + case "top": $this->setTopValue($value); break; + case "bottom": $this->setBottomValue($value); break; + case "left": $this->setLeftValue($value); break; + case "right": $this->setRightValue($value); break; + } + } + } + + return true; + } - $current_unit = ""; - foreach ($unit_options as $u) - { - if (substr($value, strlen($value) - strlen($u)) == $u) - { - $current_unit = $u; - } - } - $disp_val = substr($value, 0, strlen($value) - strlen($current_unit)); - if ($current_unit == "") - { - $current_unit = "px"; - } - $tpl->setVariable("VAL_NUM", $disp_val); - } - - foreach ($unit_options as $option) - { - $tpl->setCurrentBlock("unit_option"); - $tpl->setVariable("VAL_UNIT", $option); - $tpl->setVariable("TXT_UNIT", $option); - if ($current_type == "unit" && $current_unit == $option) - { - $tpl->setVariable("UNIT_SELECTED", 'selected="selected"'); - } - $tpl->parseCurrentBlock(); - } - - foreach ($pre_options as $option) - { - $tpl->setCurrentBlock("pre_option"); - $tpl->setVariable("VAL_PRE", $option); - $tpl->setVariable("TXT_PRE", $option); - if ($current_type == "pre" && $value == $option) - { - $tpl->setVariable("PRE_SELECTED", 'selected="selected"'); - } - $tpl->parseCurrentBlock(); - } + /** + * Insert property html + */ + public function insert(&$a_tpl) + { + $lng = $this->lng; + + $layout_tpl = new ilTemplate("tpl.prop_trbl_layout.html", true, true, "Services/Style/Content"); + + foreach ($this->dirs as $dir) { + $tpl = new ilTemplate("tpl.prop_trbl_border_width.html", true, true, "Services/Style/Content"); + $unit_options = ilObjStyleSheet::_getStyleParameterNumericUnits(); + $pre_options = ilObjStyleSheet::_getStyleParameterValues("border-width"); + + switch ($dir) { + case "all": $value = strtolower(trim($this->getAllValue())); break; + case "top": $value = strtolower(trim($this->getTopValue())); break; + case "bottom": $value = strtolower(trim($this->getBottomValue())); break; + case "left": $value = strtolower(trim($this->getLeftValue())); break; + case "right": $value = strtolower(trim($this->getRightValue())); break; + } + + if (in_array($value, $pre_options)) { + $current_type = "pre"; + $tpl->setVariable("PREDEFINED_SELECTED", 'checked="checked"'); + } else { + $current_type = "unit"; + $tpl->setVariable("NUMERIC_SELECTED", 'checked="checked"'); - $tpl->setVariable("POSTVAR", $this->getPostVar()); - $tpl->setVariable("TXT_DIR", $lng->txt("sty_$dir")); - $tpl->setVariable("DIR", $dir); - - $layout_tpl->setVariable(strtoupper($dir), $tpl->get()); - } - $layout_tpl->setVariable("COLSPAN", "2"); - - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $layout_tpl->get()); - $a_tpl->parseCurrentBlock(); - } + $current_unit = ""; + foreach ($unit_options as $u) { + if (substr($value, strlen($value) - strlen($u)) == $u) { + $current_unit = $u; + } + } + $disp_val = substr($value, 0, strlen($value) - strlen($current_unit)); + if ($current_unit == "") { + $current_unit = "px"; + } + $tpl->setVariable("VAL_NUM", $disp_val); + } + + foreach ($unit_options as $option) { + $tpl->setCurrentBlock("unit_option"); + $tpl->setVariable("VAL_UNIT", $option); + $tpl->setVariable("TXT_UNIT", $option); + if ($current_type == "unit" && $current_unit == $option) { + $tpl->setVariable("UNIT_SELECTED", 'selected="selected"'); + } + $tpl->parseCurrentBlock(); + } + + foreach ($pre_options as $option) { + $tpl->setCurrentBlock("pre_option"); + $tpl->setVariable("VAL_PRE", $option); + $tpl->setVariable("TXT_PRE", $option); + if ($current_type == "pre" && $value == $option) { + $tpl->setVariable("PRE_SELECTED", 'selected="selected"'); + } + $tpl->parseCurrentBlock(); + } - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $ilUser = $this->user; - - if ($a_values[$this->getPostVar()]["all"]["type"] == "predefined") - { - $this->setAllValue($a_values[$this->getPostVar()]["all"]["pre_value"]); - } - else - { - $this->setAllValue($a_values[$this->getPostVar()]["all"]["num_value"]. - $a_values[$this->getPostVar()]["all"]["num_unit"]); - } - if ($a_values[$this->getPostVar()]["bottom"]["type"] == "predefined") - { - $this->setBottomValue($a_values[$this->getPostVar()]["bottom"]["pre_value"]); - } - else - { - $this->setBottomValue($a_values[$this->getPostVar()]["bottom"]["num_value"]. - $a_values[$this->getPostVar()]["bottom"]["num_unit"]); - } - if ($a_values[$this->getPostVar()]["top"]["type"] == "predefined") - { - $this->setTopValue($a_values[$this->getPostVar()]["top"]["pre_value"]); - } - else - { - $this->setTopValue($a_values[$this->getPostVar()]["top"]["num_value"]. - $a_values[$this->getPostVar()]["top"]["num_unit"]); - } - if ($a_values[$this->getPostVar()]["left"]["type"] == "predefined") - { - $this->setLeftValue($a_values[$this->getPostVar()]["left"]["pre_value"]); - } - else - { - $this->setLeftValue($a_values[$this->getPostVar()]["left"]["num_value"]. - $a_values[$this->getPostVar()]["left"]["num_unit"]); - } - if ($a_values[$this->getPostVar()]["right"]["type"] == "predefined") - { - $this->setRightValue($a_values[$this->getPostVar()]["right"]["pre_value"]); - } - else - { - $this->setRightValue($a_values[$this->getPostVar()]["right"]["num_value"]. - $a_values[$this->getPostVar()]["right"]["num_unit"]); - } - } + $tpl->setVariable("POSTVAR", $this->getPostVar()); + $tpl->setVariable("TXT_DIR", $lng->txt("sty_$dir")); + $tpl->setVariable("DIR", $dir); + + $layout_tpl->setVariable(strtoupper($dir), $tpl->get()); + } + $layout_tpl->setVariable("COLSPAN", "2"); + + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $layout_tpl->get()); + $a_tpl->parseCurrentBlock(); + } + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $ilUser = $this->user; + + if ($a_values[$this->getPostVar()]["all"]["type"] == "predefined") { + $this->setAllValue($a_values[$this->getPostVar()]["all"]["pre_value"]); + } else { + $this->setAllValue($a_values[$this->getPostVar()]["all"]["num_value"] . + $a_values[$this->getPostVar()]["all"]["num_unit"]); + } + if ($a_values[$this->getPostVar()]["bottom"]["type"] == "predefined") { + $this->setBottomValue($a_values[$this->getPostVar()]["bottom"]["pre_value"]); + } else { + $this->setBottomValue($a_values[$this->getPostVar()]["bottom"]["num_value"] . + $a_values[$this->getPostVar()]["bottom"]["num_unit"]); + } + if ($a_values[$this->getPostVar()]["top"]["type"] == "predefined") { + $this->setTopValue($a_values[$this->getPostVar()]["top"]["pre_value"]); + } else { + $this->setTopValue($a_values[$this->getPostVar()]["top"]["num_value"] . + $a_values[$this->getPostVar()]["top"]["num_unit"]); + } + if ($a_values[$this->getPostVar()]["left"]["type"] == "predefined") { + $this->setLeftValue($a_values[$this->getPostVar()]["left"]["pre_value"]); + } else { + $this->setLeftValue($a_values[$this->getPostVar()]["left"]["num_value"] . + $a_values[$this->getPostVar()]["left"]["num_unit"]); + } + if ($a_values[$this->getPostVar()]["right"]["type"] == "predefined") { + $this->setRightValue($a_values[$this->getPostVar()]["right"]["pre_value"]); + } else { + $this->setRightValue($a_values[$this->getPostVar()]["right"]["num_value"] . + $a_values[$this->getPostVar()]["right"]["num_unit"]); + } + } } diff --git a/Services/Style/Content/classes/class.ilTRBLColorPickerInputGUI.php b/Services/Style/Content/classes/class.ilTRBLColorPickerInputGUI.php index a1a29e9dab26d14736ed046853da412b781f1f04..ceeb5ab1aaca427592afcf40dc5eb2a27a2525c5 100644 --- a/Services/Style/Content/classes/class.ilTRBLColorPickerInputGUI.php +++ b/Services/Style/Content/classes/class.ilTRBLColorPickerInputGUI.php @@ -32,309 +32,282 @@ class ilTRBLColorPickerInputGUI extends ilTextInputGUI { - protected $hex; + protected $hex; - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - public function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - parent::__construct($a_title, $a_postvar); - $this->setType("trbl_color"); - $this->dirs = array("all", "top", "bottom", "left", "right"); - } - - /** - * Set All Value. - * - * @param string $a_allvalue All Value - */ - function setAllValue($a_allvalue) - { - $a_allvalue = trim($a_allvalue); - if ($this->getAcceptNamedColors() && substr($a_allvalue, 0, 1) == "!") - { - $this->allvalue = $a_allvalue; - } - else - { - $this->allvalue = ilColorPickerInputGUI::determineHexcode($a_allvalue); - } - } + $this->lng = $DIC->language(); + parent::__construct($a_title, $a_postvar); + $this->setType("trbl_color"); + $this->dirs = array("all", "top", "bottom", "left", "right"); + } + + /** + * Set All Value. + * + * @param string $a_allvalue All Value + */ + public function setAllValue($a_allvalue) + { + $a_allvalue = trim($a_allvalue); + if ($this->getAcceptNamedColors() && substr($a_allvalue, 0, 1) == "!") { + $this->allvalue = $a_allvalue; + } else { + $this->allvalue = ilColorPickerInputGUI::determineHexcode($a_allvalue); + } + } - /** - * Get All Value. - * - * @return string All Value - */ - function getAllValue() - { - return $this->allvalue; - } + /** + * Get All Value. + * + * @return string All Value + */ + public function getAllValue() + { + return $this->allvalue; + } - /** - * Set Top Value. - * - * @param string $a_topvalue Top Value - */ - function setTopValue($a_topvalue) - { - $a_topvalue = trim($a_topvalue); - if ($this->getAcceptNamedColors() && substr($a_topvalue, 0, 1) == "!") - { - $this->topvalue = $a_topvalue; - } - else - { - $this->topvalue = ilColorPickerInputGUI::determineHexcode($a_topvalue); - } - } + /** + * Set Top Value. + * + * @param string $a_topvalue Top Value + */ + public function setTopValue($a_topvalue) + { + $a_topvalue = trim($a_topvalue); + if ($this->getAcceptNamedColors() && substr($a_topvalue, 0, 1) == "!") { + $this->topvalue = $a_topvalue; + } else { + $this->topvalue = ilColorPickerInputGUI::determineHexcode($a_topvalue); + } + } - /** - * Get Top Value. - * - * @return string Top Value - */ - function getTopValue() - { - return $this->topvalue; - } + /** + * Get Top Value. + * + * @return string Top Value + */ + public function getTopValue() + { + return $this->topvalue; + } - /** - * Set Bottom Value. - * - * @param string $a_bottomvalue Bottom Value - */ - function setBottomValue($a_bottomvalue) - { - $a_bottomvalue = trim($a_bottomvalue); - if ($this->getAcceptNamedColors() && substr($a_bottomvalue, 0, 1) == "!") - { - $this->bottomvalue = $a_bottomvalue; - } - else - { - $this->bottomvalue = ilColorPickerInputGUI::determineHexcode($a_bottomvalue); - } - } + /** + * Set Bottom Value. + * + * @param string $a_bottomvalue Bottom Value + */ + public function setBottomValue($a_bottomvalue) + { + $a_bottomvalue = trim($a_bottomvalue); + if ($this->getAcceptNamedColors() && substr($a_bottomvalue, 0, 1) == "!") { + $this->bottomvalue = $a_bottomvalue; + } else { + $this->bottomvalue = ilColorPickerInputGUI::determineHexcode($a_bottomvalue); + } + } - /** - * Get Bottom Value. - * - * @return string Bottom Value - */ - function getBottomValue() - { - return $this->bottomvalue; - } + /** + * Get Bottom Value. + * + * @return string Bottom Value + */ + public function getBottomValue() + { + return $this->bottomvalue; + } - /** - * Set Left Value. - * - * @param string $a_leftvalue Left Value - */ - function setLeftValue($a_leftvalue) - { - $a_leftvalue = trim($a_leftvalue); - if ($this->getAcceptNamedColors() && substr($a_leftvalue, 0, 1) == "!") - { - $this->leftvalue = $a_leftvalue; - } - else - { - $this->leftvalue = ilColorPickerInputGUI::determineHexcode($a_leftvalue); - } - } + /** + * Set Left Value. + * + * @param string $a_leftvalue Left Value + */ + public function setLeftValue($a_leftvalue) + { + $a_leftvalue = trim($a_leftvalue); + if ($this->getAcceptNamedColors() && substr($a_leftvalue, 0, 1) == "!") { + $this->leftvalue = $a_leftvalue; + } else { + $this->leftvalue = ilColorPickerInputGUI::determineHexcode($a_leftvalue); + } + } - /** - * Get Left Value. - * - * @return string Left Value - */ - function getLeftValue() - { - return $this->leftvalue; - } + /** + * Get Left Value. + * + * @return string Left Value + */ + public function getLeftValue() + { + return $this->leftvalue; + } - /** - * Set Right Value. - * - * @param string $a_rightvalue Right Value - */ - function setRightValue($a_rightvalue) - { - $a_rightvalue = trim($a_rightvalue); - if ($this->getAcceptNamedColors() && substr($a_rightvalue, 0, 1) == "!") - { - $this->rightvalue = $a_rightvalue; - } - else - { - $this->rightvalue = ilColorPickerInputGUI::determineHexcode($a_rightvalue); - } - } + /** + * Set Right Value. + * + * @param string $a_rightvalue Right Value + */ + public function setRightValue($a_rightvalue) + { + $a_rightvalue = trim($a_rightvalue); + if ($this->getAcceptNamedColors() && substr($a_rightvalue, 0, 1) == "!") { + $this->rightvalue = $a_rightvalue; + } else { + $this->rightvalue = ilColorPickerInputGUI::determineHexcode($a_rightvalue); + } + } - /** - * Get Right Value. - * - * @return string Right Value - */ - function getRightValue() - { - return $this->rightvalue; - } + /** + * Get Right Value. + * + * @return string Right Value + */ + public function getRightValue() + { + return $this->rightvalue; + } - /** - * Set Default Color. - * - * @param mixed $a_defaultcolor Default Color - */ - function setDefaultColor($a_defaultcolor) - { - $this->defaultcolor = $a_defaultcolor; - } + /** + * Set Default Color. + * + * @param mixed $a_defaultcolor Default Color + */ + public function setDefaultColor($a_defaultcolor) + { + $this->defaultcolor = $a_defaultcolor; + } - /** - * Get Default Color. - * - * @return mixed Default Color - */ - function getDefaultColor() - { - return $this->defaultcolor; - } + /** + * Get Default Color. + * + * @return mixed Default Color + */ + public function getDefaultColor() + { + return $this->defaultcolor; + } - /** - * Set Accept Named Colors (Leading '!'). - * - * @param boolean $a_acceptnamedcolors Accept Named Colors (Leading '!') - */ - function setAcceptNamedColors($a_acceptnamedcolors) - { - $this->acceptnamedcolors = $a_acceptnamedcolors; - } + /** + * Set Accept Named Colors (Leading '!'). + * + * @param boolean $a_acceptnamedcolors Accept Named Colors (Leading '!') + */ + public function setAcceptNamedColors($a_acceptnamedcolors) + { + $this->acceptnamedcolors = $a_acceptnamedcolors; + } - /** - * Get Accept Named Colors (Leading '!'). - * - * @return boolean Accept Named Colors (Leading '!') - */ - function getAcceptNamedColors() - { - return $this->acceptnamedcolors; - } + /** + * Get Accept Named Colors (Leading '!'). + * + * @return boolean Accept Named Colors (Leading '!') + */ + public function getAcceptNamedColors() + { + return $this->acceptnamedcolors; + } - /** - * check input - * - * @access public - * @return - */ - public function checkInput() - { - foreach ($this->dirs as $dir) - { - $value = $_POST[$this->getPostVar()][$dir]["value"] = - ilUtil::stripSlashes($_POST[$this->getPostVar()][$dir]["value"]); + /** + * check input + * + * @access public + * @return + */ + public function checkInput() + { + foreach ($this->dirs as $dir) { + $value = $_POST[$this->getPostVar()][$dir]["value"] = + ilUtil::stripSlashes($_POST[$this->getPostVar()][$dir]["value"]); - if (trim($value) != "") - { - switch ($dir) - { - case "all": $this->setAllValue($value); break; - case "top": $this->setTopValue($value); break; - case "bottom": $this->setBottomValue($value); break; - case "left": $this->setLeftValue($value); break; - case "right": $this->setRightValue($value); break; - } - } - } - return true; - } - - /** - * Insert property html - * - * @return int Size - */ - function insert($a_tpl) - { - $lng = $this->lng; - - include_once('./Services/YUI/classes/class.ilYuiUtil.php'); - ilYuiUtil::initColorPicker(); - - $layout_tpl = new ilTemplate("tpl.prop_trbl_layout.html", true, true, "Services/Style/Content"); - - $funcs = array( - "all" => "getAllValue", "top" => "getTopValue", - "bottom" => "getBottomValue", "left" => "getLeftValue", - "right" => "getRightValue"); - - foreach ($this->dirs as $dir) - { - /*switch($dir) - { - case "all": $value = strtoupper(trim($this->getAllValue())); break; - case "top": $value = strtoupper(trim($this->getTopValue())); break; - case "bottom": $value = strtoupper(trim($this->getBottomValue())); break; - case "left": $value = strtoupper(trim($this->getLeftValue())); break; - case "right": $value = strtoupper(trim($this->getRightValue())); break; - }*/ - $f = $funcs[$dir]; - $value = trim($this->$f()); - if (!$this->getAcceptNamedColors() || substr($value, 0, 1) != "!") - { - $value = strtoupper($value); - } + if (trim($value) != "") { + switch ($dir) { + case "all": $this->setAllValue($value); break; + case "top": $this->setTopValue($value); break; + case "bottom": $this->setBottomValue($value); break; + case "left": $this->setLeftValue($value); break; + case "right": $this->setRightValue($value); break; + } + } + } + return true; + } + + /** + * Insert property html + * + * @return int Size + */ + public function insert($a_tpl) + { + $lng = $this->lng; + + include_once('./Services/YUI/classes/class.ilYuiUtil.php'); + ilYuiUtil::initColorPicker(); + + $layout_tpl = new ilTemplate("tpl.prop_trbl_layout.html", true, true, "Services/Style/Content"); + + $funcs = array( + "all" => "getAllValue", "top" => "getTopValue", + "bottom" => "getBottomValue", "left" => "getLeftValue", + "right" => "getRightValue"); + + foreach ($this->dirs as $dir) { + /*switch($dir) + { + case "all": $value = strtoupper(trim($this->getAllValue())); break; + case "top": $value = strtoupper(trim($this->getTopValue())); break; + case "bottom": $value = strtoupper(trim($this->getBottomValue())); break; + case "left": $value = strtoupper(trim($this->getLeftValue())); break; + case "right": $value = strtoupper(trim($this->getRightValue())); break; + }*/ + $f = $funcs[$dir]; + $value = trim($this->$f()); + if (!$this->getAcceptNamedColors() || substr($value, 0, 1) != "!") { + $value = strtoupper($value); + } - $ctpl = new ilTemplate("tpl.prop_trbl_color.html", true, true, "Services/Style/Content"); + $ctpl = new ilTemplate("tpl.prop_trbl_color.html", true, true, "Services/Style/Content"); - $js_tpl = new ilTemplate('tpl.trbl_color_picker.js',true,true,'Services/Style/Content'); - $js_tpl->setVariable('THUMB_PATH',ilUtil::getImagePath('color_picker_thumb.png','Services/Form')); - $js_tpl->setVariable('HUE_THUMB_PATH',ilUtil::getImagePath('color_picker_hue_thumb.png','Services/Form')); - $js_tpl->setVariable('COLOR_ID',$this->getFieldId()."_".$dir); - $ic = ilColorPickerInputGUI::determineHexcode($value); - if ($ic == "") - { - $ic = "FFFFFF"; - } - $js_tpl->setVariable('INIT_COLOR_SHORT',$ic); - $js_tpl->setVariable('INIT_COLOR','#'.$value); - $js_tpl->setVariable('POST_VAR', $this->getPostVar()); - $js_tpl->setVariable('DIR', $dir); - - - if($this->getDisabled()) - { - $ctpl->setVariable('COLOR_DISABLED','disabled="disabled"'); - } - else - { - $ctpl->setVariable('PROP_COLOR_JS',$js_tpl->get()); - } - $ctpl->setVariable("POST_VAR", $this->getPostVar()); - $ctpl->setVariable("PROP_COLOR_ID", $this->getFieldId()."_".$dir); - - $ctpl->setVariable("PROPERTY_VALUE_COLOR", $value); - $ctpl->setVariable("DIR", $dir); - $ctpl->setVariable("TXT_DIR", $lng->txt("sty_$dir")); - - $layout_tpl->setVariable(strtoupper($dir), $ctpl->get()); - } + $js_tpl = new ilTemplate('tpl.trbl_color_picker.js', true, true, 'Services/Style/Content'); + $js_tpl->setVariable('THUMB_PATH', ilUtil::getImagePath('color_picker_thumb.png', 'Services/Form')); + $js_tpl->setVariable('HUE_THUMB_PATH', ilUtil::getImagePath('color_picker_hue_thumb.png', 'Services/Form')); + $js_tpl->setVariable('COLOR_ID', $this->getFieldId() . "_" . $dir); + $ic = ilColorPickerInputGUI::determineHexcode($value); + if ($ic == "") { + $ic = "FFFFFF"; + } + $js_tpl->setVariable('INIT_COLOR_SHORT', $ic); + $js_tpl->setVariable('INIT_COLOR', '#' . $value); + $js_tpl->setVariable('POST_VAR', $this->getPostVar()); + $js_tpl->setVariable('DIR', $dir); + + + if ($this->getDisabled()) { + $ctpl->setVariable('COLOR_DISABLED', 'disabled="disabled"'); + } else { + $ctpl->setVariable('PROP_COLOR_JS', $js_tpl->get()); + } + $ctpl->setVariable("POST_VAR", $this->getPostVar()); + $ctpl->setVariable("PROP_COLOR_ID", $this->getFieldId() . "_" . $dir); + + $ctpl->setVariable("PROPERTY_VALUE_COLOR", $value); + $ctpl->setVariable("DIR", $dir); + $ctpl->setVariable("TXT_DIR", $lng->txt("sty_$dir")); + + $layout_tpl->setVariable(strtoupper($dir), $ctpl->get()); + } - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $layout_tpl->get()); - $a_tpl->parseCurrentBlock(); - - } - + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $layout_tpl->get()); + $a_tpl->parseCurrentBlock(); + } } -?> \ No newline at end of file diff --git a/Services/Style/Content/classes/class.ilTRBLNumericStyleValueInputGUI.php b/Services/Style/Content/classes/class.ilTRBLNumericStyleValueInputGUI.php index af0baf73d398243228284dfedb55ffcde9633fbb..e28991e0689b34d25e9d146b3c1b009dde50f536 100755 --- a/Services/Style/Content/classes/class.ilTRBLNumericStyleValueInputGUI.php +++ b/Services/Style/Content/classes/class.ilTRBLNumericStyleValueInputGUI.php @@ -1,307 +1,295 @@ +* @author Alex Killing * @version $Id$ * @ingroup ServicesForm */ class ilTRBLNumericStyleValueInputGUI extends ilFormPropertyGUI { - /** - * @var ilObjUser - */ - protected $user; + /** + * @var ilObjUser + */ + protected $user; - protected $value; - protected $allowpercentage = true; - - /** - * Constructor - * - * @param string $a_title Title - * @param string $a_postvar Post Variable - */ - function __construct($a_title = "", $a_postvar = "") - { - global $DIC; + protected $value; + protected $allowpercentage = true; + + /** + * Constructor + * + * @param string $a_title Title + * @param string $a_postvar Post Variable + */ + public function __construct($a_title = "", $a_postvar = "") + { + global $DIC; - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - parent::__construct($a_title, $a_postvar); - $this->setType("style_numeric"); - $this->dirs = array("all", "top", "bottom", "left", "right"); - } + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + parent::__construct($a_title, $a_postvar); + $this->setType("style_numeric"); + $this->dirs = array("all", "top", "bottom", "left", "right"); + } - /** - * Set All Value. - * - * @param string $a_allvalue All Value - */ - function setAllValue($a_allvalue) - { - $this->allvalue = $a_allvalue; - } + /** + * Set All Value. + * + * @param string $a_allvalue All Value + */ + public function setAllValue($a_allvalue) + { + $this->allvalue = $a_allvalue; + } - /** - * Get All Value. - * - * @return string All Value - */ - function getAllValue() - { - return $this->allvalue; - } + /** + * Get All Value. + * + * @return string All Value + */ + public function getAllValue() + { + return $this->allvalue; + } - /** - * Set Top Value. - * - * @param string $a_topvalue Top Value - */ - function setTopValue($a_topvalue) - { - $this->topvalue = $a_topvalue; - } + /** + * Set Top Value. + * + * @param string $a_topvalue Top Value + */ + public function setTopValue($a_topvalue) + { + $this->topvalue = $a_topvalue; + } - /** - * Get Top Value. - * - * @return string Top Value - */ - function getTopValue() - { - return $this->topvalue; - } + /** + * Get Top Value. + * + * @return string Top Value + */ + public function getTopValue() + { + return $this->topvalue; + } - /** - * Set Bottom Value. - * - * @param string $a_bottomvalue Bottom Value - */ - function setBottomValue($a_bottomvalue) - { - $this->bottomvalue = $a_bottomvalue; - } + /** + * Set Bottom Value. + * + * @param string $a_bottomvalue Bottom Value + */ + public function setBottomValue($a_bottomvalue) + { + $this->bottomvalue = $a_bottomvalue; + } - /** - * Get Bottom Value. - * - * @return string Bottom Value - */ - function getBottomValue() - { - return $this->bottomvalue; - } + /** + * Get Bottom Value. + * + * @return string Bottom Value + */ + public function getBottomValue() + { + return $this->bottomvalue; + } - /** - * Set Left Value. - * - * @param string $a_leftvalue Left Value - */ - function setLeftValue($a_leftvalue) - { - $this->leftvalue = $a_leftvalue; - } + /** + * Set Left Value. + * + * @param string $a_leftvalue Left Value + */ + public function setLeftValue($a_leftvalue) + { + $this->leftvalue = $a_leftvalue; + } - /** - * Get Left Value. - * - * @return string Left Value - */ - function getLeftValue() - { - return $this->leftvalue; - } + /** + * Get Left Value. + * + * @return string Left Value + */ + public function getLeftValue() + { + return $this->leftvalue; + } - /** - * Set Right Value. - * - * @param string $a_rightvalue Right Value - */ - function setRightValue($a_rightvalue) - { - $this->rightvalue = $a_rightvalue; - } + /** + * Set Right Value. + * + * @param string $a_rightvalue Right Value + */ + public function setRightValue($a_rightvalue) + { + $this->rightvalue = $a_rightvalue; + } - /** - * Get Right Value. - * - * @return string Right Value - */ - function getRightValue() - { - return $this->rightvalue; - } - - /** - * Set Allow Percentage. - * - * @param boolean $a_allowpercentage Allow Percentage - */ - function setAllowPercentage($a_allowpercentage) - { - $this->allowpercentage = $a_allowpercentage; - } + /** + * Get Right Value. + * + * @return string Right Value + */ + public function getRightValue() + { + return $this->rightvalue; + } + + /** + * Set Allow Percentage. + * + * @param boolean $a_allowpercentage Allow Percentage + */ + public function setAllowPercentage($a_allowpercentage) + { + $this->allowpercentage = $a_allowpercentage; + } - /** - * Get Allow Percentage. - * - * @return boolean Allow Percentage - */ - function getAllowPercentage() - { - return $this->allowpercentage; - } + /** + * Get Allow Percentage. + * + * @return boolean Allow Percentage + */ + public function getAllowPercentage() + { + return $this->allowpercentage; + } - /** - * Check input, strip slashes etc. set alert, if input is not ok. - * - * @return boolean Input ok, true/false - */ - function checkInput() - { - $lng = $this->lng; - - foreach ($this->dirs as $dir) - { - $num_value = $_POST[$this->getPostVar()][$dir]["num_value"] = - trim(ilUtil::stripSlashes($_POST[$this->getPostVar()][$dir]["num_value"])); - $num_unit = $_POST[$this->getPostVar()][$dir]["num_unit"] = - trim(ilUtil::stripSlashes($_POST[$this->getPostVar()][$dir]["num_unit"])); - - /* - if ($this->getRequired() && trim($num_value) == "") - { - $this->setAlert($lng->txt("msg_input_is_required")); - - return false; - }*/ - - if (!is_numeric($num_value) && $num_value != "") - { - $this->setAlert($lng->txt("sty_msg_input_must_be_numeric")); - return false; - } - - if (trim($num_value) != "") - { - switch ($dir) - { - case "all": $this->setAllValue($num_value.$num_unit); break; - case "top": $this->setTopValue($num_value.$num_unit); break; - case "bottom": $this->setBottomValue($num_value.$num_unit); break; - case "left": $this->setLeftValue($num_value.$num_unit); break; - case "right": $this->setRightValue($num_value.$num_unit); break; - } - } - } - - return true; - } + /** + * Check input, strip slashes etc. set alert, if input is not ok. + * + * @return boolean Input ok, true/false + */ + public function checkInput() + { + $lng = $this->lng; + + foreach ($this->dirs as $dir) { + $num_value = $_POST[$this->getPostVar()][$dir]["num_value"] = + trim(ilUtil::stripSlashes($_POST[$this->getPostVar()][$dir]["num_value"])); + $num_unit = $_POST[$this->getPostVar()][$dir]["num_unit"] = + trim(ilUtil::stripSlashes($_POST[$this->getPostVar()][$dir]["num_unit"])); + + /* + if ($this->getRequired() && trim($num_value) == "") + { + $this->setAlert($lng->txt("msg_input_is_required")); - /** - * Insert property html - */ - function insert(&$a_tpl) - { - $lng = $this->lng; - - $layout_tpl = new ilTemplate("tpl.prop_trbl_layout.html", true, true, "Services/Style/Content"); - - foreach ($this->dirs as $dir) - { - $tpl = new ilTemplate("tpl.prop_trbl_style_numeric.html", true, true, "Services/Style/Content"); - $unit_options = ilObjStyleSheet::_getStyleParameterNumericUnits(!$this->getAllowPercentage()); - - switch($dir) - { - case "all": $value = strtolower(trim($this->getAllValue())); break; - case "top": $value = strtolower(trim($this->getTopValue())); break; - case "bottom": $value = strtolower(trim($this->getBottomValue())); break; - case "left": $value = strtolower(trim($this->getLeftValue())); break; - case "right": $value = strtolower(trim($this->getRightValue())); break; - } - - $current_unit = ""; - foreach ($unit_options as $u) - { - if (substr($value, strlen($value) - strlen($u)) == $u) - { - $current_unit = $u; - } - } - $disp_val = substr($value, 0, strlen($value) - strlen($current_unit)); - if ($current_unit == "") - { - $current_unit = "px"; - } - - foreach ($unit_options as $option) - { - $tpl->setCurrentBlock("unit_option"); - $tpl->setVariable("VAL_UNIT", $option); - $tpl->setVariable("TXT_UNIT", $option); - if ($current_unit == $option) - { - $tpl->setVariable("UNIT_SELECTED", 'selected="selected"'); - } - $tpl->parseCurrentBlock(); - } - - $tpl->setVariable("POSTVAR", $this->getPostVar()); - $tpl->setVariable("VAL_NUM", $disp_val); - $tpl->setVariable("TXT_DIR", $lng->txt("sty_$dir")); - $tpl->setVariable("DIR", $dir); - - $layout_tpl->setVariable(strtoupper($dir), $tpl->get()); - } - - $a_tpl->setCurrentBlock("prop_generic"); - $a_tpl->setVariable("PROP_GENERIC", $layout_tpl->get()); - $a_tpl->parseCurrentBlock(); - } + return false; + }*/ + + if (!is_numeric($num_value) && $num_value != "") { + $this->setAlert($lng->txt("sty_msg_input_must_be_numeric")); + return false; + } + + if (trim($num_value) != "") { + switch ($dir) { + case "all": $this->setAllValue($num_value . $num_unit); break; + case "top": $this->setTopValue($num_value . $num_unit); break; + case "bottom": $this->setBottomValue($num_value . $num_unit); break; + case "left": $this->setLeftValue($num_value . $num_unit); break; + case "right": $this->setRightValue($num_value . $num_unit); break; + } + } + } + + return true; + } - /** - * Set value by array - * - * @param array $a_values value array - */ - function setValueByArray($a_values) - { - $ilUser = $this->user; - - $this->setAllValue($a_values[$this->getPostVar()]["all"]["num_value"]. - $a_values[$this->getPostVar()]["all"]["num_unit"]); - $this->setBottomValue($a_values[$this->getPostVar()]["bottom"]["num_value"]. - $a_values[$this->getPostVar()]["bottom"]["num_unit"]); - $this->setTopValue($a_values[$this->getPostVar()]["top"]["num_value"]. - $a_values[$this->getPostVar()]["top"]["num_unit"]); - $this->setLeftValue($a_values[$this->getPostVar()]["left"]["num_value"]. - $a_values[$this->getPostVar()]["left"]["num_unit"]); - $this->setRightValue($a_values[$this->getPostVar()]["right"]["num_value"]. - $a_values[$this->getPostVar()]["right"]["num_unit"]); - } + /** + * Insert property html + */ + public function insert(&$a_tpl) + { + $lng = $this->lng; + + $layout_tpl = new ilTemplate("tpl.prop_trbl_layout.html", true, true, "Services/Style/Content"); + + foreach ($this->dirs as $dir) { + $tpl = new ilTemplate("tpl.prop_trbl_style_numeric.html", true, true, "Services/Style/Content"); + $unit_options = ilObjStyleSheet::_getStyleParameterNumericUnits(!$this->getAllowPercentage()); + + switch ($dir) { + case "all": $value = strtolower(trim($this->getAllValue())); break; + case "top": $value = strtolower(trim($this->getTopValue())); break; + case "bottom": $value = strtolower(trim($this->getBottomValue())); break; + case "left": $value = strtolower(trim($this->getLeftValue())); break; + case "right": $value = strtolower(trim($this->getRightValue())); break; + } + + $current_unit = ""; + foreach ($unit_options as $u) { + if (substr($value, strlen($value) - strlen($u)) == $u) { + $current_unit = $u; + } + } + $disp_val = substr($value, 0, strlen($value) - strlen($current_unit)); + if ($current_unit == "") { + $current_unit = "px"; + } + + foreach ($unit_options as $option) { + $tpl->setCurrentBlock("unit_option"); + $tpl->setVariable("VAL_UNIT", $option); + $tpl->setVariable("TXT_UNIT", $option); + if ($current_unit == $option) { + $tpl->setVariable("UNIT_SELECTED", 'selected="selected"'); + } + $tpl->parseCurrentBlock(); + } + + $tpl->setVariable("POSTVAR", $this->getPostVar()); + $tpl->setVariable("VAL_NUM", $disp_val); + $tpl->setVariable("TXT_DIR", $lng->txt("sty_$dir")); + $tpl->setVariable("DIR", $dir); + + $layout_tpl->setVariable(strtoupper($dir), $tpl->get()); + } + + $a_tpl->setCurrentBlock("prop_generic"); + $a_tpl->setVariable("PROP_GENERIC", $layout_tpl->get()); + $a_tpl->parseCurrentBlock(); + } + /** + * Set value by array + * + * @param array $a_values value array + */ + public function setValueByArray($a_values) + { + $ilUser = $this->user; + + $this->setAllValue($a_values[$this->getPostVar()]["all"]["num_value"] . + $a_values[$this->getPostVar()]["all"]["num_unit"]); + $this->setBottomValue($a_values[$this->getPostVar()]["bottom"]["num_value"] . + $a_values[$this->getPostVar()]["bottom"]["num_unit"]); + $this->setTopValue($a_values[$this->getPostVar()]["top"]["num_value"] . + $a_values[$this->getPostVar()]["top"]["num_unit"]); + $this->setLeftValue($a_values[$this->getPostVar()]["left"]["num_value"] . + $a_values[$this->getPostVar()]["left"]["num_unit"]); + $this->setRightValue($a_values[$this->getPostVar()]["right"]["num_value"] . + $a_values[$this->getPostVar()]["right"]["num_unit"]); + } } diff --git a/Services/Style/Content/classes/class.ilTableTemplatesTableGUI.php b/Services/Style/Content/classes/class.ilTableTemplatesTableGUI.php index 5ab3189e60c7369b719aaaa2b2fed1e8b801ae10..e7792a6ebf02f851cfd57e32db0cf55b4cafe831 100755 --- a/Services/Style/Content/classes/class.ilTableTemplatesTableGUI.php +++ b/Services/Style/Content/classes/class.ilTableTemplatesTableGUI.php @@ -1,24 +1,24 @@ ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $this->rbacsystem = $DIC->rbac()->system(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $this->rbacsystem = $DIC->rbac()->system(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); - parent::__construct($a_parent_obj, $a_parent_cmd); - + parent::__construct($a_parent_obj, $a_parent_cmd); + - include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); - ilAccordionGUI::addCss(); + include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); + ilAccordionGUI::addCss(); - $this->setTitle($lng->txt("sty_templates")); - $this->style_obj = $a_style_obj; - $this->temp_type = $a_temp_type; - - $this->addColumn("", "", "1"); // checkbox - $this->addColumn($this->lng->txt("sty_template_name"), ""); - $this->addColumn($this->lng->txt("sty_preview"), ""); - $this->addColumn($this->lng->txt("sty_commands"), "", "1"); - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.style_template_row.html", "Services/Style/Content"); - $this->getItems(); + $this->setTitle($lng->txt("sty_templates")); + $this->style_obj = $a_style_obj; + $this->temp_type = $a_temp_type; + + $this->addColumn("", "", "1"); // checkbox + $this->addColumn($this->lng->txt("sty_template_name"), ""); + $this->addColumn($this->lng->txt("sty_preview"), ""); + $this->addColumn($this->lng->txt("sty_commands"), "", "1"); + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.style_template_row.html", "Services/Style/Content"); + $this->getItems(); - // action commands - if ($this->parent_obj->checkWrite()) - { - $this->addMultiCommand("deleteTemplateConfirmation", $lng->txt("delete")); - } + // action commands + if ($this->parent_obj->checkWrite()) { + $this->addMultiCommand("deleteTemplateConfirmation", $lng->txt("delete")); + } - $this->setEnableTitle(true); - } + $this->setEnableTitle(true); + } - /** - * Get items of current folder - */ - function getItems() - { - $this->setData($this->style_obj->getTemplates($this->temp_type)); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; + /** + * Get items of current folder + */ + public function getItems() + { + $this->setData($this->style_obj->getTemplates($this->temp_type)); + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; - $this->tpl->setVariable("T_PREVIEW", - $this->style_obj->lookupTemplatePreview($a_set["id"])); - $this->tpl->setVariable("TID", $a_set["id"]); - $this->tpl->setVariable("TEMPLATE_NAME", $a_set["name"]); - $ilCtrl->setParameter($this->parent_obj, "t_id", $a_set["id"]); - - if ($this->parent_obj->checkWrite()) - { - $this->tpl->setVariable("LINK_EDIT_TEMPLATE", - $ilCtrl->getLinkTarget($this->parent_obj, "editTemplate")); - $this->tpl->setVariable("TXT_EDIT", $lng->txt("edit")); - } - } + $this->tpl->setVariable( + "T_PREVIEW", + $this->style_obj->lookupTemplatePreview($a_set["id"]) + ); + $this->tpl->setVariable("TID", $a_set["id"]); + $this->tpl->setVariable("TEMPLATE_NAME", $a_set["name"]); + $ilCtrl->setParameter($this->parent_obj, "t_id", $a_set["id"]); + + if ($this->parent_obj->checkWrite()) { + $this->tpl->setVariable( + "LINK_EDIT_TEMPLATE", + $ilCtrl->getLinkTarget($this->parent_obj, "editTemplate") + ); + $this->tpl->setVariable("TXT_EDIT", $lng->txt("edit")); + } + } } -?> diff --git a/Services/Style/System/classes/Documentation/class.ilKSDocumentationEntryGUI.php b/Services/Style/System/classes/Documentation/class.ilKSDocumentationEntryGUI.php index de3bfa3294b781da53e9fd96e1e5565786ffa3f6..13368c14cf356ea4ae0912f68c5cb4bd31daa4c6 100644 --- a/Services/Style/System/classes/Documentation/class.ilKSDocumentationEntryGUI.php +++ b/Services/Style/System/classes/Documentation/class.ilKSDocumentationEntryGUI.php @@ -1,7 +1,7 @@ f = $DIC->ui()->factory(); - $this->r = $DIC->ui()->renderer(); - - $this->setEntry($entry); - $this->setEntries($entries); - $this->setParent($parent); - $this->ctrl = $DIC->ctrl(); - - } - - /** - * @return string - */ - public function renderEntry(){ - - $sub_panels = array(); - - $feature_wiki_links = array(); - foreach($this->entry->getFeatureWikiReferences()as $href){ - $feature_wiki_links[] = $href; - } - - $sub_panels[] = $this->f->panel()->sub("Description", - array( - $this->f->listing()->descriptive( - array( - "Purpose" => $this->entry->getDescription()->getProperty("purpose"), - "Composition" => $this->entry->getDescription()->getProperty("composition"), - "Effect" => $this->entry->getDescription()->getProperty("effect"), - - ) - ), - $this->f->listing()->descriptive( - array( - "Background" => $this->entry->getBackground(), + /** + * @var Entry\ComponentEntry + */ + protected $entry = null; + + /** + * @var Entry\ComponentEntries + */ + protected $entries = null; + + /** + * @var ilCtrl $ctrl + */ + protected $ctrl; + + /** + * @var ilSystemStyleDocumentationGUI + */ + protected $parent; + + /** + * @var ILIAS\UI\Factory + */ + protected $f = null; + + /** + * @var ILIAS\UI\Renderer + */ + protected $r = null; + + /** + * ilKSDocumentationEntryGUI constructor. + * @param ilSystemStyleDocumentationGUI $parent + * @param Entry\ComponentEntry $entry + * @param Entry\ComponentEntries $entries + */ + public function __construct(ilSystemStyleDocumentationGUI $parent, Entry\ComponentEntry $entry, Entry\ComponentEntries $entries) + { + global $DIC; + + $this->f = $DIC->ui()->factory(); + $this->r = $DIC->ui()->renderer(); + + $this->setEntry($entry); + $this->setEntries($entries); + $this->setParent($parent); + $this->ctrl = $DIC->ctrl(); + } + + /** + * @return string + */ + public function renderEntry() + { + $sub_panels = array(); + + $feature_wiki_links = array(); + foreach ($this->entry->getFeatureWikiReferences()as $href) { + $feature_wiki_links[] = $href; + } + + $sub_panels[] = $this->f->panel()->sub( + "Description", + array( + $this->f->listing()->descriptive( + array( + "Purpose" => $this->entry->getDescription()->getProperty("purpose"), + "Composition" => $this->entry->getDescription()->getProperty("composition"), + "Effect" => $this->entry->getDescription()->getProperty("effect"), + + ) + ), + $this->f->listing()->descriptive( + array( + "Background" => $this->entry->getBackground(), "Context" => $this->f->listing()->ordered($this->entry->getContext()), - "Feature Wiki References" => $this->f->listing()->ordered($feature_wiki_links) - ) - ) - ) - ); - - if(sizeof($this->entry->getDescription()->getProperty("rivals"))){ - $sub_panels[] = $this->f->panel()->sub("Rivals", + "Feature Wiki References" => $this->f->listing()->ordered($feature_wiki_links) + ) + ) + ) + ); + + if (sizeof($this->entry->getDescription()->getProperty("rivals"))) { + $sub_panels[] = $this->f->panel()->sub( + "Rivals", $this->f->listing()->descriptive( $this->entry->getDescription()->getProperty("rivals") - )); + ) + ); } - if($this->entry->getRules()->hasRules()){ + if ($this->entry->getRules()->hasRules()) { $rule_listings = array(); - foreach($this->entry->getRulesAsArray() as $categoery => $category_rules){ + foreach ($this->entry->getRulesAsArray() as $categoery => $category_rules) { $rule_listings[ucfirst($categoery)] = $this->f->listing()->ordered($category_rules); } - $sub_panels[] = $this->f->panel()->sub("Rules", + $sub_panels[] = $this->f->panel()->sub( + "Rules", $this->f->listing()->descriptive($rule_listings) ); } - if($this->entry->getExamples()){ - $nr = 1; - foreach($this->entry->getExamples() as $name => $path){ - include_once($path); - $title = "Example ".$nr.": ".ucfirst(str_replace("_"," ",$name)); - $nr++; - $example = "
                  ".$name()."
                  "; //Executes function loaded in file indicated by 'path' - $content_part_1 = $this->f->legacy($example); - $code = str_replace("f->legacy($geshi->parse_code()); - $content = array($content_part_1,$content_part_2); - $sub_panels[] = $this->f->panel()->sub($title, $content); - } - } - - $sub_panels[] = $this->f->panel()->sub("Relations", - $this->f->listing()->descriptive( - array( - "Parents" => $this->f->listing()->ordered( - $this->entries->getParentsOfEntryTitles($this->entry->getId()) - ), - "Descendants" => $this->f->listing()->unordered( - $this->entries->getDescendantsOfEntryTitles($this->entry->getId()) - ) - ) - ) - ); - - $report = $this->f->panel()->report($this->entry->getTitle(),$sub_panels); - - return $this->r->render($report); - } - - - /** - * @return Entry\ComponentEntry - */ - public function getEntry() - { - return $this->entry; - } - - /** - * @param Entry\ComponentEntry $entry - */ - public function setEntry(Entry\ComponentEntry $entry) - { - $this->entry = $entry; - } - - /** - * @return Entry\ComponentEntries - */ - public function getEntries() - { - return $this->entries; - } - - /** - * @param Entry\ComponentEntries $entries - */ - public function setEntries(Entry\ComponentEntries $entries) - { - $this->entries = $entries; - } - - /** - * @return ilSystemStyleDocumentationGUI - */ - public function getParent() - { - return $this->parent; - } - - /** - * @param ilSystemStyleDocumentationGUI $parent - */ - public function setParent($parent) - { - $this->parent = $parent; - } + if ($this->entry->getExamples()) { + $nr = 1; + foreach ($this->entry->getExamples() as $name => $path) { + include_once($path); + $title = "Example " . $nr . ": " . ucfirst(str_replace("_", " ", $name)); + $nr++; + $example = "
                  " . $name() . "
                  "; //Executes function loaded in file indicated by 'path' + $content_part_1 = $this->f->legacy($example); + $code = str_replace("f->legacy($geshi->parse_code()); + $content = array($content_part_1,$content_part_2); + $sub_panels[] = $this->f->panel()->sub($title, $content); + } + } + + $sub_panels[] = $this->f->panel()->sub( + "Relations", + $this->f->listing()->descriptive( + array( + "Parents" => $this->f->listing()->ordered( + $this->entries->getParentsOfEntryTitles($this->entry->getId()) + ), + "Descendants" => $this->f->listing()->unordered( + $this->entries->getDescendantsOfEntryTitles($this->entry->getId()) + ) + ) + ) + ); + + $report = $this->f->panel()->report($this->entry->getTitle(), $sub_panels); + + return $this->r->render($report); + } + + + /** + * @return Entry\ComponentEntry + */ + public function getEntry() + { + return $this->entry; + } + + /** + * @param Entry\ComponentEntry $entry + */ + public function setEntry(Entry\ComponentEntry $entry) + { + $this->entry = $entry; + } + + /** + * @return Entry\ComponentEntries + */ + public function getEntries() + { + return $this->entries; + } + + /** + * @param Entry\ComponentEntries $entries + */ + public function setEntries(Entry\ComponentEntries $entries) + { + $this->entries = $entries; + } + + /** + * @return ilSystemStyleDocumentationGUI + */ + public function getParent() + { + return $this->parent; + } + + /** + * @param ilSystemStyleDocumentationGUI $parent + */ + public function setParent($parent) + { + $this->parent = $parent; + } } diff --git a/Services/Style/System/classes/Documentation/class.ilKSDocumentationExplorerGUI.php b/Services/Style/System/classes/Documentation/class.ilKSDocumentationExplorerGUI.php index 8f7d7fabbf634a1c8b052f083774ea858aa4f045..afd4769f4781eef6a22ac8285282f2ea98257785 100644 --- a/Services/Style/System/classes/Documentation/class.ilKSDocumentationExplorerGUI.php +++ b/Services/Style/System/classes/Documentation/class.ilKSDocumentationExplorerGUI.php @@ -10,200 +10,199 @@ use ILIAS\UI\Implementation\Crawler\Entry as Entry; */ class ilKSDocumentationExplorerGUI extends ilExplorerBaseGUI { - /** - * @var ilCtrl $ctrl - */ - protected $ctrl; - - /** - * - */ - protected $id = "ksDocumentationExplorer"; - - /** - * @var string - */ - protected $parentLink = ""; - - /** - * @var Entry\ComponentEntries - */ - protected $entries = null; - - /** - * @var string - */ - protected $current_opened_node_id = ""; - - /** - * ilKSDocumentationExplorerGUI constructor. - * @param ilSystemStyleDocumentationGUI $a_parent_obj - * @param $a_parent_cmd - * @param Entry\ComponentEntries $entries - * @param $current_opened_node_id - */ - public function __construct(ilSystemStyleDocumentationGUI $a_parent_obj, $a_parent_cmd, Entry\ComponentEntries $entries, $current_opened_node_id) - { - global $DIC; - $this->ctrl = $DIC->ctrl(); - - parent::__construct($this->id, $a_parent_obj, $a_parent_cmd); - - $this->setParentLink($this->ctrl->getLinkTarget($this->parent_obj, $this->parent_cmd)); - - $this->setEntries($entries); - $this->setOfflineMode(true); - - if(!$current_opened_node_id){ - $this->setCurrentOpenedNodeId($this->getEntries()->getRootEntryId()); - }else{ - $this->setCurrentOpenedNodeId($current_opened_node_id); - } - - $this->openNodesRecursively($this->getCurrentOpenedNodeId()); - } - - /** - * @param $id - * @throws \ILIAS\UI\Implementation\Crawler\Exception\CrawlerException - */ - protected function openNodesRecursively($id){ - $this->setNodeOpen($id); - $parent_id = $this->getEntries()->getEntryById($id)->getParent(); - - if($parent_id){ - $this->openNodesRecursively($parent_id); - } - } - /** - * Get root node. - * - * @return mixed root node object/array - */ - function getRootNode() - { - return $this->getEntries()->getRootEntry(); - } - - /** - * @param $a_parent_node_id - * @return Entry\ComponentEntry[] - */ - function getChildsOfNode($a_parent_node_id) - { - - $entry = $this->getEntries()->getEntryById($a_parent_node_id); - - /** - * @var Entry\ComponentEntry[] - */ - $children = array(); - foreach ($entry->getChildren() as $child_id) - { - $children[$child_id] = $this->getEntries()->getEntryById($child_id); - } - return $children; - } - - /** - * @param $a_entry_id - * @return Entry\ComponentEntry - * @throws \ILIAS\UI\Implementation\Crawler\Exception\CrawlerException - */ - function getNodeById($a_entry_id) - { - return $this->getEntries()->getEntryById($a_entry_id); - } - - /** - * @param mixed $entry - * @return Entry\ComponentEntry - */ - function getNodeContent($entry) - { - return $entry->getTitle(); - } - - /** - * @param Entry\ComponentEntry $entry - * @return string - */ - function getNodeHref($entry) - { - return $this->getParentLink()."&node_id=".$entry->getId(); - } - - /** - * @param Entry\ComponentEntry $entry - * @return bool - */ - function isNodeHighlighted($entry) - { - return $entry->getId() == $this->getCurrentOpenedNode()->getId(); - } - /** - * @param Entry\ComponentEntry $entry - * @return mixed - */ - function getNodeId($entry) - { - return $entry->getId(); - } - - /** - * @return string - */ - public function getParentLink() - { - return $this->parentLink; - } - - /** - * @param string $parentLink - */ - public function setParentLink($parentLink) - { - $this->parentLink = $parentLink; - } - - /** - * @return Entry\ComponentEntries - */ - public function getEntries() - { - return $this->entries; - } - - /** - * @param Entry\ComponentEntries $entries - */ - public function setEntries($entries) - { - $this->entries = $entries; - } - - /** - * @return string - */ - public function getCurrentOpenedNodeId() - { - return $this->current_opened_node_id; - } - - /** - * @param string $current_opened_node_id - */ - public function setCurrentOpenedNodeId($current_opened_node_id) - { - $this->current_opened_node_id = $current_opened_node_id; - } - - /** - * @return Entry\ComponentEntry - * @throws ilSystemStyleException - */ - public function getCurrentOpenedNode(){ - return $this->getEntries()->getEntryById($this->getCurrentOpenedNodeId()); - } - -} \ No newline at end of file + /** + * @var ilCtrl $ctrl + */ + protected $ctrl; + + /** + * + */ + protected $id = "ksDocumentationExplorer"; + + /** + * @var string + */ + protected $parentLink = ""; + + /** + * @var Entry\ComponentEntries + */ + protected $entries = null; + + /** + * @var string + */ + protected $current_opened_node_id = ""; + + /** + * ilKSDocumentationExplorerGUI constructor. + * @param ilSystemStyleDocumentationGUI $a_parent_obj + * @param $a_parent_cmd + * @param Entry\ComponentEntries $entries + * @param $current_opened_node_id + */ + public function __construct(ilSystemStyleDocumentationGUI $a_parent_obj, $a_parent_cmd, Entry\ComponentEntries $entries, $current_opened_node_id) + { + global $DIC; + $this->ctrl = $DIC->ctrl(); + + parent::__construct($this->id, $a_parent_obj, $a_parent_cmd); + + $this->setParentLink($this->ctrl->getLinkTarget($this->parent_obj, $this->parent_cmd)); + + $this->setEntries($entries); + $this->setOfflineMode(true); + + if (!$current_opened_node_id) { + $this->setCurrentOpenedNodeId($this->getEntries()->getRootEntryId()); + } else { + $this->setCurrentOpenedNodeId($current_opened_node_id); + } + + $this->openNodesRecursively($this->getCurrentOpenedNodeId()); + } + + /** + * @param $id + * @throws \ILIAS\UI\Implementation\Crawler\Exception\CrawlerException + */ + protected function openNodesRecursively($id) + { + $this->setNodeOpen($id); + $parent_id = $this->getEntries()->getEntryById($id)->getParent(); + + if ($parent_id) { + $this->openNodesRecursively($parent_id); + } + } + /** + * Get root node. + * + * @return mixed root node object/array + */ + public function getRootNode() + { + return $this->getEntries()->getRootEntry(); + } + + /** + * @param $a_parent_node_id + * @return Entry\ComponentEntry[] + */ + public function getChildsOfNode($a_parent_node_id) + { + $entry = $this->getEntries()->getEntryById($a_parent_node_id); + + /** + * @var Entry\ComponentEntry[] + */ + $children = array(); + foreach ($entry->getChildren() as $child_id) { + $children[$child_id] = $this->getEntries()->getEntryById($child_id); + } + return $children; + } + + /** + * @param $a_entry_id + * @return Entry\ComponentEntry + * @throws \ILIAS\UI\Implementation\Crawler\Exception\CrawlerException + */ + public function getNodeById($a_entry_id) + { + return $this->getEntries()->getEntryById($a_entry_id); + } + + /** + * @param mixed $entry + * @return Entry\ComponentEntry + */ + public function getNodeContent($entry) + { + return $entry->getTitle(); + } + + /** + * @param Entry\ComponentEntry $entry + * @return string + */ + public function getNodeHref($entry) + { + return $this->getParentLink() . "&node_id=" . $entry->getId(); + } + + /** + * @param Entry\ComponentEntry $entry + * @return bool + */ + public function isNodeHighlighted($entry) + { + return $entry->getId() == $this->getCurrentOpenedNode()->getId(); + } + /** + * @param Entry\ComponentEntry $entry + * @return mixed + */ + public function getNodeId($entry) + { + return $entry->getId(); + } + + /** + * @return string + */ + public function getParentLink() + { + return $this->parentLink; + } + + /** + * @param string $parentLink + */ + public function setParentLink($parentLink) + { + $this->parentLink = $parentLink; + } + + /** + * @return Entry\ComponentEntries + */ + public function getEntries() + { + return $this->entries; + } + + /** + * @param Entry\ComponentEntries $entries + */ + public function setEntries($entries) + { + $this->entries = $entries; + } + + /** + * @return string + */ + public function getCurrentOpenedNodeId() + { + return $this->current_opened_node_id; + } + + /** + * @param string $current_opened_node_id + */ + public function setCurrentOpenedNodeId($current_opened_node_id) + { + $this->current_opened_node_id = $current_opened_node_id; + } + + /** + * @return Entry\ComponentEntry + * @throws ilSystemStyleException + */ + public function getCurrentOpenedNode() + { + return $this->getEntries()->getEntryById($this->getCurrentOpenedNodeId()); + } +} diff --git a/Services/Style/System/classes/Documentation/class.ilSystemStyleDocumentationGUI.php b/Services/Style/System/classes/Documentation/class.ilSystemStyleDocumentationGUI.php index b55dc6dd31e1bfe3ac9ecf62870b806f5a2404d6..d06522bee3a02ea159be6dbafcb301abfac53c41 100644 --- a/Services/Style/System/classes/Documentation/class.ilSystemStyleDocumentationGUI.php +++ b/Services/Style/System/classes/Documentation/class.ilSystemStyleDocumentationGUI.php @@ -5,6 +5,7 @@ require_once("libs/composer/vendor/geshi/geshi/src/geshi.php"); use ILIAS\UI\Implementation\Crawler as Crawler; + /** * * @author Timon Amstutz @@ -12,182 +13,185 @@ use ILIAS\UI\Implementation\Crawler as Crawler; */ class ilSystemStyleDocumentationGUI { - /** - * @var ilTemplate - */ - protected $tpl; - /** - * @var ilCtrl $ctrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var bool - */ - protected $is_read_only = false; - - const ROOT_FACTORY_PATH = "./Services/Style/System/data/abstractDataFactory.php"; - const DATA_DIRECTORY = "./Services/Style/System/data"; - const DATA_FILE = "data.json"; - public static $DATA_PATH; - - /** - * ilSystemStyleDocumentationGUI constructor. - * @param bool|false $read_only - */ - function __construct($read_only = false) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - - $this->setIsReadOnly($read_only); - - self::$DATA_PATH= self::DATA_DIRECTORY."/".self::DATA_FILE; - - } - - /** - * Execute command - */ - function executeCommand() - { - $cmd = $this->ctrl->getCmd(); - - switch ($cmd) - { - case 'parseEntries': - $this->$cmd(); - $this->show(); - break; - default: - if($this->is_read_only){ - $this->resetForReadOnly(); - } - $this->addGotoLink(); - $this->show(); - break; - } - } - - public function show(){ - $entries = $this->readEntries(); - $content = ""; - - //The button to parse the entries from code should only be shown in DEVMODE. Other users do not need that. - if(DEVMODE == 1 && !$this->isReadOnly()){ - $toolbar = new ilToolbarGUI(); - $reload_btn = ilLinkButton::getInstance(); - $reload_btn->setCaption($this->lng->txt('refresh_entries'),false); - if($_GET["node_id"]){ - $this->ctrl->saveParameter($this,"node_id"); - } - $reload_btn->setUrl($this->ctrl->getLinkTarget($this, 'parseEntries')); - $toolbar->addButtonInstance($reload_btn); - $content .= $toolbar->getHTML(); - } - - $explorer = new ilKSDocumentationExplorerGUI($this, "entries", $entries, $_GET["node_id"]); - $this->tpl->setLeftNavContent($explorer->getHTML()); - $entry_gui = new ilKSDocumentationEntryGUI($this,$explorer->getCurrentOpenedNode(), $entries); - $content .= $entry_gui->renderEntry(); - - $this->tpl->setContent($content); - } - - protected function resetForReadOnly(){ - /** - * @var ILIAS\DI\Container $DIC - */ - global $DIC; - - $DIC->tabs()->clearTargets(); - - /** - * Since clearTargets also clears the help screen ids - */ - $DIC->help()->setScreenIdComponent("sty"); - $DIC->help()->setScreenId("system_styles"); - - $skin_id = $_GET["skin_id"]; - $style_id = $_GET["style_id"]; - - $skin = ilSystemStyleSkinContainer::generateFromId($skin_id)->getSkin(); - $style = $skin->getStyle($style_id); - - $DIC["tpl"]->setTitle($DIC->language()->txt("documentation")); - - if($style->isSubstyle()){ - $DIC["tpl"]->setDescription($this->lng->txt("ks_documentation_of_substyle") - ." '" - .$style->getName()."' ". - $this->lng->txt("of_parent")." '".$skin->getStyle($style->getSubstyleOf())->getName()."' ". - $this->lng->txt("from_skin")." ".$skin->getName() - ); - }else{ - $DIC["tpl"]->setDescription($this->lng->txt("ks_documentation_of_style")." '".$style->getName()."' ". - $this->lng->txt("from_skin")." '".$skin->getName()."'" - ); - } - - $DIC["ilLocator"]->clearItems(); - $DIC["tpl"]->setLocator(); - - - } - - protected function addGotoLink(){ - $this->tpl->setPermanentLink("stys", $_GET["ref_id"], "_".$_GET["node_id"]. "_" - .$_GET["skin_id"]. "_" .$_GET["style_id"]); - } - - /** - * @return Crawler\Entry\ComponentEntries - * @throws Crawler\Exception\CrawlerException - */ - protected function parseEntries(){ - $crawler = new Crawler\FactoriesCrawler(); - $entries = $crawler->crawlFactory(self::ROOT_FACTORY_PATH); - file_put_contents(self::$DATA_PATH, json_encode($entries)); - ilUtil::sendSuccess($this->lng->txt("entries_reloaded"),true); - return $entries; - } - - /** - * @return Crawler\Entry\ComponentEntries - */ - protected function readEntries(){ - $entries_array = json_decode(file_get_contents(self::$DATA_PATH),true); - - $entries = new Crawler\Entry\ComponentEntries(); - foreach($entries_array as $entry_array){ - $entry = new Crawler\Entry\ComponentEntry($entry_array); - $entries->addEntry($entry); - } - - return $entries; - } - - /** - * @return bool - */ - public function isReadOnly() - { - return $this->is_read_only; - } - - /** - * @param bool $is_read_only - */ - public function setIsReadOnly($is_read_only) - { - $this->is_read_only = $is_read_only; - } -} \ No newline at end of file + /** + * @var ilTemplate + */ + protected $tpl; + /** + * @var ilCtrl $ctrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var bool + */ + protected $is_read_only = false; + + const ROOT_FACTORY_PATH = "./Services/Style/System/data/abstractDataFactory.php"; + const DATA_DIRECTORY = "./Services/Style/System/data"; + const DATA_FILE = "data.json"; + public static $DATA_PATH; + + /** + * ilSystemStyleDocumentationGUI constructor. + * @param bool|false $read_only + */ + public function __construct($read_only = false) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + + $this->setIsReadOnly($read_only); + + self::$DATA_PATH= self::DATA_DIRECTORY . "/" . self::DATA_FILE; + } + + /** + * Execute command + */ + public function executeCommand() + { + $cmd = $this->ctrl->getCmd(); + + switch ($cmd) { + case 'parseEntries': + $this->$cmd(); + $this->show(); + break; + default: + if ($this->is_read_only) { + $this->resetForReadOnly(); + } + $this->addGotoLink(); + $this->show(); + break; + } + } + + public function show() + { + $entries = $this->readEntries(); + $content = ""; + + //The button to parse the entries from code should only be shown in DEVMODE. Other users do not need that. + if (DEVMODE == 1 && !$this->isReadOnly()) { + $toolbar = new ilToolbarGUI(); + $reload_btn = ilLinkButton::getInstance(); + $reload_btn->setCaption($this->lng->txt('refresh_entries'), false); + if ($_GET["node_id"]) { + $this->ctrl->saveParameter($this, "node_id"); + } + $reload_btn->setUrl($this->ctrl->getLinkTarget($this, 'parseEntries')); + $toolbar->addButtonInstance($reload_btn); + $content .= $toolbar->getHTML(); + } + + $explorer = new ilKSDocumentationExplorerGUI($this, "entries", $entries, $_GET["node_id"]); + $this->tpl->setLeftNavContent($explorer->getHTML()); + $entry_gui = new ilKSDocumentationEntryGUI($this, $explorer->getCurrentOpenedNode(), $entries); + $content .= $entry_gui->renderEntry(); + + $this->tpl->setContent($content); + } + + protected function resetForReadOnly() + { + /** + * @var ILIAS\DI\Container $DIC + */ + global $DIC; + + $DIC->tabs()->clearTargets(); + + /** + * Since clearTargets also clears the help screen ids + */ + $DIC->help()->setScreenIdComponent("sty"); + $DIC->help()->setScreenId("system_styles"); + + $skin_id = $_GET["skin_id"]; + $style_id = $_GET["style_id"]; + + $skin = ilSystemStyleSkinContainer::generateFromId($skin_id)->getSkin(); + $style = $skin->getStyle($style_id); + + $DIC["tpl"]->setTitle($DIC->language()->txt("documentation")); + + if ($style->isSubstyle()) { + $DIC["tpl"]->setDescription( + $this->lng->txt("ks_documentation_of_substyle") + . " '" + . $style->getName() . "' " . + $this->lng->txt("of_parent") . " '" . $skin->getStyle($style->getSubstyleOf())->getName() . "' " . + $this->lng->txt("from_skin") . " " . $skin->getName() + ); + } else { + $DIC["tpl"]->setDescription( + $this->lng->txt("ks_documentation_of_style") . " '" . $style->getName() . "' " . + $this->lng->txt("from_skin") . " '" . $skin->getName() . "'" + ); + } + + $DIC["ilLocator"]->clearItems(); + $DIC["tpl"]->setLocator(); + } + + protected function addGotoLink() + { + $this->tpl->setPermanentLink("stys", $_GET["ref_id"], "_" . $_GET["node_id"] . "_" + . $_GET["skin_id"] . "_" . $_GET["style_id"]); + } + + /** + * @return Crawler\Entry\ComponentEntries + * @throws Crawler\Exception\CrawlerException + */ + protected function parseEntries() + { + $crawler = new Crawler\FactoriesCrawler(); + $entries = $crawler->crawlFactory(self::ROOT_FACTORY_PATH); + file_put_contents(self::$DATA_PATH, json_encode($entries)); + ilUtil::sendSuccess($this->lng->txt("entries_reloaded"), true); + return $entries; + } + + /** + * @return Crawler\Entry\ComponentEntries + */ + protected function readEntries() + { + $entries_array = json_decode(file_get_contents(self::$DATA_PATH), true); + + $entries = new Crawler\Entry\ComponentEntries(); + foreach ($entries_array as $entry_array) { + $entry = new Crawler\Entry\ComponentEntry($entry_array); + $entries->addEntry($entry); + } + + return $entries; + } + + /** + * @return bool + */ + public function isReadOnly() + { + return $this->is_read_only; + } + + /** + * @param bool $is_read_only + */ + public function setIsReadOnly($is_read_only) + { + $this->is_read_only = $is_read_only; + } +} diff --git a/Services/Style/System/classes/Exceptions/class.ilSystemStyleColorException.php b/Services/Style/System/classes/Exceptions/class.ilSystemStyleColorException.php index 866b8a087f7070feb1ebcc3e6e882c1be8c44fc5..411b3c557d7609d6650fbb73b956bfa5c51c2906 100644 --- a/Services/Style/System/classes/Exceptions/class.ilSystemStyleColorException.php +++ b/Services/Style/System/classes/Exceptions/class.ilSystemStyleColorException.php @@ -12,20 +12,18 @@ require_once 'class.ilSystemStyleExceptionBase.php'; */ class ilSystemStyleColorException extends ilSystemStyleExceptionBase { - const INVALID_COLOR_EXCEPTION = 1001; + const INVALID_COLOR_EXCEPTION = 1001; - protected function assignMessageToCode() - { - switch ($this->code) - { - case self::INVALID_COLOR_EXCEPTION: - $this->message = "Invalid Color value"; - break; - default: - $this->message = "Unknown Exception " . $this->add_info; - break; - } - } - -} \ No newline at end of file + protected function assignMessageToCode() + { + switch ($this->code) { + case self::INVALID_COLOR_EXCEPTION: + $this->message = "Invalid Color value"; + break; + default: + $this->message = "Unknown Exception " . $this->add_info; + break; + } + } +} diff --git a/Services/Style/System/classes/Exceptions/class.ilSystemStyleException.php b/Services/Style/System/classes/Exceptions/class.ilSystemStyleException.php index b3202751bcc02e0ad29940b88ef3ec1b224245b3..be20aa3d665a92d5fdd9f074f862a15648762eed 100644 --- a/Services/Style/System/classes/Exceptions/class.ilSystemStyleException.php +++ b/Services/Style/System/classes/Exceptions/class.ilSystemStyleException.php @@ -13,120 +13,119 @@ require_once 'class.ilSystemStyleExceptionBase.php'; */ class ilSystemStyleException extends ilSystemStyleExceptionBase { - const PARSING_JSON_FAILED = 1; + const PARSING_JSON_FAILED = 1; - const EMPTY_ENTRY = 1001; - const INVALID_MANDATORY_ENTRY_ATTRIBUTE = 1002; - const DUPLICATE_ENTRY = 1003; - const DUPLICATE_ROOT_ENTRY = 1004; - const INVALID_ID = 1005; - const INVALID_FILE_PATH = 1006; - const INVALID_RULES_ENTRY = 1007; - const INVALID_CHARACTERS_IN_ID = 1008; + const EMPTY_ENTRY = 1001; + const INVALID_MANDATORY_ENTRY_ATTRIBUTE = 1002; + const DUPLICATE_ENTRY = 1003; + const DUPLICATE_ROOT_ENTRY = 1004; + const INVALID_ID = 1005; + const INVALID_FILE_PATH = 1006; + const INVALID_RULES_ENTRY = 1007; + const INVALID_CHARACTERS_IN_ID = 1008; - const FILE_CREATION_FAILED = 2001; - const FOLDER_CREATION_FAILED = 2002; - const FILE_OPENING_FAILED = 2003; - const LESS_COMPILE_FAILED = 2004; - const FOLDER_DELETION_FAILED = 2005; - const FILE_DELETION_FAILED = 2006; - const LESSC_NOT_INSTALLED = 2007; + const FILE_CREATION_FAILED = 2001; + const FOLDER_CREATION_FAILED = 2002; + const FILE_OPENING_FAILED = 2003; + const LESS_COMPILE_FAILED = 2004; + const FOLDER_DELETION_FAILED = 2005; + const FILE_DELETION_FAILED = 2006; + const LESSC_NOT_INSTALLED = 2007; - const SKIN_FOLDER_DOES_NOT_EXIST = 3001; - const SKIN_CSS_DOES_NOT_EXIST = 3002; + const SKIN_FOLDER_DOES_NOT_EXIST = 3001; + const SKIN_CSS_DOES_NOT_EXIST = 3002; - const NO_STYLE_ID = 5001; - const NO_SKIN_ID = 5002; - const NO_PARENT_STYLE = 5003; - const NOT_EXISTING_STYLE = 5004; - const NOT_EXISTING_SKIN = 5005; + const NO_STYLE_ID = 5001; + const NO_SKIN_ID = 5002; + const NO_PARENT_STYLE = 5003; + const NOT_EXISTING_STYLE = 5004; + const NOT_EXISTING_SKIN = 5005; - const SKIN_ALREADY_EXISTS = 6001; + const SKIN_ALREADY_EXISTS = 6001; - const SUBSTYLE_ASSIGNMENT_EXISTS = 7001; + const SUBSTYLE_ASSIGNMENT_EXISTS = 7001; - protected function assignMessageToCode() - { - switch ($this->code) - { - case self::EMPTY_ENTRY: - $this->message = "Empty Entry " . $this->add_info; - break; - case self::PARSING_JSON_FAILED: - $this->message = "Parsing JSON Failed " . $this->add_info; - break; - case self::INVALID_MANDATORY_ENTRY_ATTRIBUTE: - $this->message = "Invalid mandatory entry Attribute: " . $this->add_info; - break; - case self::DUPLICATE_ENTRY: - $this->message = "There are entries with the same ID. Duplicate: " . $this->add_info; - break; - case self::DUPLICATE_ROOT_ENTRY: - $this->message = "There are multiple root entry. Duplicate: " . $this->add_info; - break; - case self::INVALID_ID: - $this->message = "No such ID found in list or tree: " . $this->add_info; - break; - case self::INVALID_CHARACTERS_IN_ID: - $this->message = "The ID given contains invalid characters: " . $this->add_info; - break; - case self::INVALID_FILE_PATH: - $this->message = "Invalid file path or file not readable: " . $this->add_info; - break; - case self::FILE_CREATION_FAILED: - $this->message = "File creation failed, path: " . $this->add_info; - break; - case self::FOLDER_CREATION_FAILED: - $this->message = "Folder creation failed, path: " . $this->add_info; - break; - case self::FOLDER_DELETION_FAILED: - $this->message = "Folder delation failed, path: " . $this->add_info; - break; - case self::FILE_DELETION_FAILED: - $this->message = "File delation failed, path: " . $this->add_info; - break; - case self::LESS_COMPILE_FAILED: - $this->message = "Compilation of less failed: " . $this->add_info; - break; - case self::FILE_OPENING_FAILED: - $this->message = "Failed to open file : " . $this->add_info; - break; - case self::SKIN_CSS_DOES_NOT_EXIST: - $this->message = "Skin CSS does not exist: " . $this->add_info; - break; - case self::SKIN_FOLDER_DOES_NOT_EXIST: - $this->message = "Skin folder does not exist: " . $this->add_info; - break; - case self::INVALID_RULES_ENTRY: - $this->message = "Invalid rules entry: " . $this->add_info; - break; - case self::NO_STYLE_ID: - $this->message = "No Style ID is given."; - break; - case self::NO_SKIN_ID: - $this->message = "No Skin ID is given."; - break; - case self::NOT_EXISTING_SKIN: - $this->message = "Skin does not exist: " . $this->add_info; - break; - case self::NOT_EXISTING_STYLE: - $this->message = "Style does not exist: " . $this->add_info; - break; - case self::SKIN_ALREADY_EXISTS: - $this->message = "Skin already exists: ".$this->add_info; - break; - case self::NO_PARENT_STYLE: - $this->message = "No parent style defined for style: ".$this->add_info; - break; - case self::SUBSTYLE_ASSIGNMENT_EXISTS: - $this->message = "The assignment of this substyle already exists: ".$this->add_info; - break; - case self::LESSC_NOT_INSTALLED: - $this->message = "No less compiler is installed"; - break; - default: - $this->message = "Unknown Exception " . $this->add_info; - break; - } - } -} \ No newline at end of file + protected function assignMessageToCode() + { + switch ($this->code) { + case self::EMPTY_ENTRY: + $this->message = "Empty Entry " . $this->add_info; + break; + case self::PARSING_JSON_FAILED: + $this->message = "Parsing JSON Failed " . $this->add_info; + break; + case self::INVALID_MANDATORY_ENTRY_ATTRIBUTE: + $this->message = "Invalid mandatory entry Attribute: " . $this->add_info; + break; + case self::DUPLICATE_ENTRY: + $this->message = "There are entries with the same ID. Duplicate: " . $this->add_info; + break; + case self::DUPLICATE_ROOT_ENTRY: + $this->message = "There are multiple root entry. Duplicate: " . $this->add_info; + break; + case self::INVALID_ID: + $this->message = "No such ID found in list or tree: " . $this->add_info; + break; + case self::INVALID_CHARACTERS_IN_ID: + $this->message = "The ID given contains invalid characters: " . $this->add_info; + break; + case self::INVALID_FILE_PATH: + $this->message = "Invalid file path or file not readable: " . $this->add_info; + break; + case self::FILE_CREATION_FAILED: + $this->message = "File creation failed, path: " . $this->add_info; + break; + case self::FOLDER_CREATION_FAILED: + $this->message = "Folder creation failed, path: " . $this->add_info; + break; + case self::FOLDER_DELETION_FAILED: + $this->message = "Folder delation failed, path: " . $this->add_info; + break; + case self::FILE_DELETION_FAILED: + $this->message = "File delation failed, path: " . $this->add_info; + break; + case self::LESS_COMPILE_FAILED: + $this->message = "Compilation of less failed: " . $this->add_info; + break; + case self::FILE_OPENING_FAILED: + $this->message = "Failed to open file : " . $this->add_info; + break; + case self::SKIN_CSS_DOES_NOT_EXIST: + $this->message = "Skin CSS does not exist: " . $this->add_info; + break; + case self::SKIN_FOLDER_DOES_NOT_EXIST: + $this->message = "Skin folder does not exist: " . $this->add_info; + break; + case self::INVALID_RULES_ENTRY: + $this->message = "Invalid rules entry: " . $this->add_info; + break; + case self::NO_STYLE_ID: + $this->message = "No Style ID is given."; + break; + case self::NO_SKIN_ID: + $this->message = "No Skin ID is given."; + break; + case self::NOT_EXISTING_SKIN: + $this->message = "Skin does not exist: " . $this->add_info; + break; + case self::NOT_EXISTING_STYLE: + $this->message = "Style does not exist: " . $this->add_info; + break; + case self::SKIN_ALREADY_EXISTS: + $this->message = "Skin already exists: " . $this->add_info; + break; + case self::NO_PARENT_STYLE: + $this->message = "No parent style defined for style: " . $this->add_info; + break; + case self::SUBSTYLE_ASSIGNMENT_EXISTS: + $this->message = "The assignment of this substyle already exists: " . $this->add_info; + break; + case self::LESSC_NOT_INSTALLED: + $this->message = "No less compiler is installed"; + break; + default: + $this->message = "Unknown Exception " . $this->add_info; + break; + } + } +} diff --git a/Services/Style/System/classes/Exceptions/class.ilSystemStyleExceptionBase.php b/Services/Style/System/classes/Exceptions/class.ilSystemStyleExceptionBase.php index 76157242d1778b202316dc516628afce25a8a05c..e87fb3e81ec6ba7d8bae928aa254d2271a09af83 100644 --- a/Services/Style/System/classes/Exceptions/class.ilSystemStyleExceptionBase.php +++ b/Services/Style/System/classes/Exceptions/class.ilSystemStyleExceptionBase.php @@ -12,45 +12,44 @@ require_once 'Services/Exceptions/classes/class.ilException.php'; */ abstract class ilSystemStyleExceptionBase extends ilException { - const UNKNONW_EXCEPTION = -1; - - /** - * @var string - */ - protected $message = ""; - - /** - * @var int - */ - protected $code = -1; - - /** - * @var string - */ - protected $add_info = ""; - - /** - * ilSystemStyleException constructor. - * @param int $exception_code - * @param string $exception_info - */ - public function __construct($exception_code = -1, $exception_info = "") - { - $this->code = $exception_code; - $this->add_info = $exception_info; - $this->assignMessageToCode(); - parent::__construct($this->message, $this->code); - - } - - abstract protected function assignMessageToCode(); - - /** - * @return string - */ - public function __toString() - { - return get_class($this) . " '{$this->message}' in {$this->file}({$this->line})\n" - . "{$this->getTraceAsString()}"; - } -} \ No newline at end of file + const UNKNONW_EXCEPTION = -1; + + /** + * @var string + */ + protected $message = ""; + + /** + * @var int + */ + protected $code = -1; + + /** + * @var string + */ + protected $add_info = ""; + + /** + * ilSystemStyleException constructor. + * @param int $exception_code + * @param string $exception_info + */ + public function __construct($exception_code = -1, $exception_info = "") + { + $this->code = $exception_code; + $this->add_info = $exception_info; + $this->assignMessageToCode(); + parent::__construct($this->message, $this->code); + } + + abstract protected function assignMessageToCode(); + + /** + * @return string + */ + public function __toString() + { + return get_class($this) . " '{$this->message}' in {$this->file}({$this->line})\n" + . "{$this->getTraceAsString()}"; + } +} diff --git a/Services/Style/System/classes/Exceptions/class.ilSystemStyleIconException.php b/Services/Style/System/classes/Exceptions/class.ilSystemStyleIconException.php index 3e31065df3980a483d4902e8eddc0440a775d742..71ce81d4c29df5d866b813df7d7eddf44a0f12f1 100644 --- a/Services/Style/System/classes/Exceptions/class.ilSystemStyleIconException.php +++ b/Services/Style/System/classes/Exceptions/class.ilSystemStyleIconException.php @@ -12,23 +12,21 @@ require_once 'class.ilSystemStyleExceptionBase.php'; */ class ilSystemStyleIconException extends ilSystemStyleExceptionBase { - const IMAGES_FOLDER_DOES_NOT_EXIST = 1001; - const ICON_DOES_NOT_EXIST = 1002; + const IMAGES_FOLDER_DOES_NOT_EXIST = 1001; + const ICON_DOES_NOT_EXIST = 1002; - protected function assignMessageToCode() - { - switch ($this->code) - { - case self::IMAGES_FOLDER_DOES_NOT_EXIST: - $this->message = "Images folder set for this style does not exist or can not be read: " . $this->add_info; - break; - case self::ICON_DOES_NOT_EXIST: - $this->message = "The selected Icon does not exit: " . $this->add_info; - break; - default: - $this->message = "Unknown Exception " . $this->add_info; - break; - } - } - -} \ No newline at end of file + protected function assignMessageToCode() + { + switch ($this->code) { + case self::IMAGES_FOLDER_DOES_NOT_EXIST: + $this->message = "Images folder set for this style does not exist or can not be read: " . $this->add_info; + break; + case self::ICON_DOES_NOT_EXIST: + $this->message = "The selected Icon does not exit: " . $this->add_info; + break; + default: + $this->message = "Unknown Exception " . $this->add_info; + break; + } + } +} diff --git a/Services/Style/System/classes/Exceptions/class.ilSystemStyleMessageStackException.php b/Services/Style/System/classes/Exceptions/class.ilSystemStyleMessageStackException.php index 27d9f32d32e3455cba6e4677f6724ea31a79daf0..b86962523cb75e6a5afc5f0392f3cdacd0dbc1d5 100644 --- a/Services/Style/System/classes/Exceptions/class.ilSystemStyleMessageStackException.php +++ b/Services/Style/System/classes/Exceptions/class.ilSystemStyleMessageStackException.php @@ -12,20 +12,18 @@ require_once 'class.ilSystemStyleExceptionBase.php'; */ class ilSystemStyleMessageStackException extends ilSystemStyleExceptionBase { - const MESSAGE_STACK_TYPE_ID_DOES_NOT_EXIST = 1001; + const MESSAGE_STACK_TYPE_ID_DOES_NOT_EXIST = 1001; - protected function assignMessageToCode() - { - switch ($this->code) - { - case self::MESSAGE_STACK_TYPE_ID_DOES_NOT_EXIST: - $this->message = "Type id does not exist in message stack"; - break; - default: - $this->message = "Unknown Exception " . $this->add_info; - break; - } - } - -} \ No newline at end of file + protected function assignMessageToCode() + { + switch ($this->code) { + case self::MESSAGE_STACK_TYPE_ID_DOES_NOT_EXIST: + $this->message = "Type id does not exist in message stack"; + break; + default: + $this->message = "Unknown Exception " . $this->add_info; + break; + } + } +} diff --git a/Services/Style/System/classes/Icons/class.ilSystemStyleIcon.php b/Services/Style/System/classes/Icons/class.ilSystemStyleIcon.php index 989787a8a4dd8351c4b9075eb86e3a23f0ec0e02..8c2f1a85f4736e538ef9aa44c843df1bc475fd81 100644 --- a/Services/Style/System/classes/Icons/class.ilSystemStyleIcon.php +++ b/Services/Style/System/classes/Icons/class.ilSystemStyleIcon.php @@ -11,170 +11,175 @@ include_once("Services/Style/System/classes/Icons/class.ilSystemStyleIconColorSe class ilSystemStyleIcon { - /** - * Path to the icon including name and extension - * @var string - */ - protected $path = ""; - - /** - * Name of the Icon - * @var string - */ - protected $name = ""; - - /** - * Extension of the icon - * @var string - */ - protected $type = ""; - - /** - * Color set extracted from the icon - * - * @var ilSystemStyleIconColorSet - */ - protected $color_set = null; - - /** - * ilSystemStyleIcon constructor. - * @param $name - * @param $path - * @param $type - */ - public function __construct($name, $path, $type) - { - $this->setName($name); - $this->setType($type); - $this->setPath($path); - } - - - /** - * Changes colors in the svg file of the icon and updates the icon abstraction by extracting the colors again. - * @param array $color_changes - */ - public function changeColors(array $color_changes){ - if($this->getType() == "svg"){ - $icon = file_get_contents($this->getPath()); - foreach($color_changes as $old_color => $new_color){ - $icon = preg_replace ( '/'.$old_color.'/i' , $new_color, $icon, -1 ); - } - file_put_contents ($this->getPath(),$icon); - } - $this->extractColorSet(); - } - - /** - * @return string - */ - public function getType() - { - return $this->type; - } - - /** - * @param string $type - */ - public function setType($type) - { - $this->type = $type; - } - - /** - * @return string - */ - public function getName() - { - return $this->name; - } - - /** - * @param string $name - */ - public function setName($name) - { - $this->name = $name; - } - - - /** - * @return mixed - */ - public function __toString() - { - return $this->getName(); - } - - /** - * @return string - */ - public function getPath() - { - return $this->path; - } - - /** - * @param string $path - */ - public function setPath($path) - { - $this->path = $path; - } + /** + * Path to the icon including name and extension + * @var string + */ + protected $path = ""; + + /** + * Name of the Icon + * @var string + */ + protected $name = ""; + + /** + * Extension of the icon + * @var string + */ + protected $type = ""; + + /** + * Color set extracted from the icon + * + * @var ilSystemStyleIconColorSet + */ + protected $color_set = null; + + /** + * ilSystemStyleIcon constructor. + * @param $name + * @param $path + * @param $type + */ + public function __construct($name, $path, $type) + { + $this->setName($name); + $this->setType($type); + $this->setPath($path); + } + + + /** + * Changes colors in the svg file of the icon and updates the icon abstraction by extracting the colors again. + * @param array $color_changes + */ + public function changeColors(array $color_changes) + { + if ($this->getType() == "svg") { + $icon = file_get_contents($this->getPath()); + foreach ($color_changes as $old_color => $new_color) { + $icon = preg_replace('/' . $old_color . '/i', $new_color, $icon, -1); + } + file_put_contents($this->getPath(), $icon); + } + $this->extractColorSet(); + } + + /** + * @return string + */ + public function getType() + { + return $this->type; + } + + /** + * @param string $type + */ + public function setType($type) + { + $this->type = $type; + } + + /** + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * @param string $name + */ + public function setName($name) + { + $this->name = $name; + } + + + /** + * @return mixed + */ + public function __toString() + { + return $this->getName(); + } + + /** + * @return string + */ + public function getPath() + { + return $this->path; + } + + /** + * @param string $path + */ + public function setPath($path) + { + $this->path = $path; + } /** * Only get dir rel to the Customizing dir * without name and extension from * @return string */ - public function getDirRelToCustomizing(){ + public function getDirRelToCustomizing() + { return dirname(strstr($this->getPath(), 'global/skin')); } - /** - * @return ilSystemStyleIconColorSet - */ - public function getColorSet() - { - if(!$this->color_set){ - $this->extractColorSet(); - } - return $this->color_set; - } - - /** - * Extracts all colors from the icon by parsing the svg file for a regular expresion. - */ - protected function extractColorSet(){ - $regex_for_extracting_color = '/(?<=#)[\dabcdef]{6}/i'; - - $this->color_set = new ilSystemStyleIconColorSet(); - if($this->getType() == "svg"){ - $icon_content = file_get_contents($this->getPath()); - $color_matches = []; - preg_match_all ($regex_for_extracting_color ,$icon_content,$color_matches); - if(is_array($color_matches) && is_array($color_matches[0])) - foreach($color_matches[0] as $color_value){ - $numeric = strtoupper(str_replace("#","",$color_value)); - $color = new ilSystemStyleIconColor($numeric,$color_value,$numeric,$color_value); - $this->getColorSet()->addColor($color); - } - } - } - - /** - * @param ilSystemStyleIconColorSet $color_set - */ - public function setColorSet($color_set) - { - $this->color_set = $color_set; - } - - /** - * @param $color_id - * @return bool - */ - public function usesColor($color_id){ - return $this->getColorSet()->doesColorExist($color_id); - } -} \ No newline at end of file + /** + * @return ilSystemStyleIconColorSet + */ + public function getColorSet() + { + if (!$this->color_set) { + $this->extractColorSet(); + } + return $this->color_set; + } + + /** + * Extracts all colors from the icon by parsing the svg file for a regular expresion. + */ + protected function extractColorSet() + { + $regex_for_extracting_color = '/(?<=#)[\dabcdef]{6}/i'; + + $this->color_set = new ilSystemStyleIconColorSet(); + if ($this->getType() == "svg") { + $icon_content = file_get_contents($this->getPath()); + $color_matches = []; + preg_match_all($regex_for_extracting_color, $icon_content, $color_matches); + if (is_array($color_matches) && is_array($color_matches[0])) { + foreach ($color_matches[0] as $color_value) { + $numeric = strtoupper(str_replace("#", "", $color_value)); + $color = new ilSystemStyleIconColor($numeric, $color_value, $numeric, $color_value); + $this->getColorSet()->addColor($color); + } + } + } + } + + /** + * @param ilSystemStyleIconColorSet $color_set + */ + public function setColorSet($color_set) + { + $this->color_set = $color_set; + } + + /** + * @param $color_id + * @return bool + */ + public function usesColor($color_id) + { + return $this->getColorSet()->doesColorExist($color_id); + } +} diff --git a/Services/Style/System/classes/Icons/class.ilSystemStyleIconColor.php b/Services/Style/System/classes/Icons/class.ilSystemStyleIconColor.php index 32b5cf58366581dff4be8d00e24b1b54e73ae6ee..c97e12f75c24a487eb65010a972dee2e258ee83a 100644 --- a/Services/Style/System/classes/Icons/class.ilSystemStyleIconColor.php +++ b/Services/Style/System/classes/Icons/class.ilSystemStyleIconColor.php @@ -10,215 +10,222 @@ include_once("Services/Style/System/classes/Exceptions/class.ilSystemStyleColorE */ class ilSystemStyleIconColor { - const GREY = 0; - const RED = 1; - const GREEN = 2; - const BLUE = 3; - - /** - * Unique ID to identify the color by (currently same as color) - * - * @var string - */ - protected $id = ""; - - /** - * Value of the color - * - * @var string - */ - protected $color = ""; - - /** - * Name of the color in text - * - * @var string - */ - protected $name = ""; - - /** - * Description of the color - * - * @var string - */ - protected $description = ""; - - /** - * Calculated brightness - * - * @var null - */ - protected $brightness = null; - - /** - * ilSystemStyleIconColor constructor. - * @param $id - * @param $name - * @param $color - * @param $description - */ - public function __construct($id, $name, $color, $description = "") - { - $this->setId($id); - $this->setColor($color); - $this->setName($name); - $this->setDescription($description); - } - - /** - * @return string - */ - public function getId() - { - return $this->id; - } - - /** - * @param string $id - */ - public function setId($id) - { - $this->id = $id; - } - - /** - * @return string - */ - public function getColor() - { - return $this->color; - } - - /** - * @param $color - * @throws ilSystemStyleColorException - */ - public function setColor($color) - { - $color = strtoupper ($color); - - if(!ctype_xdigit ($color) || strlen($color)!=6){ - throw new ilSystemStyleColorException(ilSystemStyleColorException::INVALID_COLOR_EXCEPTION,$color); - } - - $this->color = $color; - } - - /** - * @return string - */ - public function getName() - { - return $this->name; - } - - /** - * @param string $name - */ - public function setName($name) - { - $this->name = $name; - } - - /** - * @return string - */ - public function getDescription() - { - return $this->description; - } - - /** - * @param string $description - */ - public function setDescription($description) - { - $this->description = $description; - } - - /** - * Used to order the colors according to their dominant aspect. Due to the vast numbers of colors to be displayed - * to the user, they must be ordered in some fashion, dominant aspect and brightness are possible values. - * @return int - */ - public function getDominatAspect(){ - $r = $this->getRedAspect(); - $g = $this->getGreenAspect(); - $b = $this->getBlueAspect(); - - if($r == $g && $r==$b && $g==$b){ - return self::GREY; - }else if($r > $g && $r > $b){ - return self::RED; - }else if($g > $r && $g > $b){ - return self::GREEN; - }else{ - return self::BLUE; - } - } - - /** - * Get red aspect from a color in hex format - * - * @return number - */ - public function getRedAspect(){ - return hexdec(substr($this->getColor(),0,2)); - } - - /** - * Get green aspect from a color in hex format - * - * @return number - */ - public function getGreenAspect(){ - return hexdec(substr($this->getColor(),2,2)); - } - - /** - * Get blue aspect from a color in hex format - * - * @return number - */ - public function getBlueAspect(){ - return hexdec(substr($this->getColor(),4,2)); - } - - /** - * Used to sort the colors according to their brightness. Due to the vast numbers of colors to be displayed - * to the user, they must be ordered in some fashion, dominant aspect and brightness are possible values. - * See: https://en.wikipedia.org/wiki/YIQ - * - * @return float|null - */ - public function getPerceivedBrightness(){ - if($this->brightness === null){ - $r = $this->getRedAspect(); - $g = $this->getGreenAspect(); - $b = $this->getBlueAspect(); - - $this->brightness = sqrt( - $r * $r * .299 + - $g * $g * .587 + - $b * $b * .114); - } - return $this->brightness; - } - - /** - * Used to sort colors according to their brightness - * - * @param ilSystemStyleIconColor $color1 - * @param ilSystemStyleIconColor $color2 - * @return int - */ - static function compareColors(ilSystemStyleIconColor $color1, ilSystemStyleIconColor $color2){ - $value1 = $color1->getPerceivedBrightness(); - $value2 = $color2->getPerceivedBrightness(); - - if ($value1 == $value2) { - return 0; - } - return ($value1 > $value2) ? +1 : -1; - } -} \ No newline at end of file + const GREY = 0; + const RED = 1; + const GREEN = 2; + const BLUE = 3; + + /** + * Unique ID to identify the color by (currently same as color) + * + * @var string + */ + protected $id = ""; + + /** + * Value of the color + * + * @var string + */ + protected $color = ""; + + /** + * Name of the color in text + * + * @var string + */ + protected $name = ""; + + /** + * Description of the color + * + * @var string + */ + protected $description = ""; + + /** + * Calculated brightness + * + * @var null + */ + protected $brightness = null; + + /** + * ilSystemStyleIconColor constructor. + * @param $id + * @param $name + * @param $color + * @param $description + */ + public function __construct($id, $name, $color, $description = "") + { + $this->setId($id); + $this->setColor($color); + $this->setName($name); + $this->setDescription($description); + } + + /** + * @return string + */ + public function getId() + { + return $this->id; + } + + /** + * @param string $id + */ + public function setId($id) + { + $this->id = $id; + } + + /** + * @return string + */ + public function getColor() + { + return $this->color; + } + + /** + * @param $color + * @throws ilSystemStyleColorException + */ + public function setColor($color) + { + $color = strtoupper($color); + + if (!ctype_xdigit($color) || strlen($color)!=6) { + throw new ilSystemStyleColorException(ilSystemStyleColorException::INVALID_COLOR_EXCEPTION, $color); + } + + $this->color = $color; + } + + /** + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * @param string $name + */ + public function setName($name) + { + $this->name = $name; + } + + /** + * @return string + */ + public function getDescription() + { + return $this->description; + } + + /** + * @param string $description + */ + public function setDescription($description) + { + $this->description = $description; + } + + /** + * Used to order the colors according to their dominant aspect. Due to the vast numbers of colors to be displayed + * to the user, they must be ordered in some fashion, dominant aspect and brightness are possible values. + * @return int + */ + public function getDominatAspect() + { + $r = $this->getRedAspect(); + $g = $this->getGreenAspect(); + $b = $this->getBlueAspect(); + + if ($r == $g && $r==$b && $g==$b) { + return self::GREY; + } elseif ($r > $g && $r > $b) { + return self::RED; + } elseif ($g > $r && $g > $b) { + return self::GREEN; + } else { + return self::BLUE; + } + } + + /** + * Get red aspect from a color in hex format + * + * @return number + */ + public function getRedAspect() + { + return hexdec(substr($this->getColor(), 0, 2)); + } + + /** + * Get green aspect from a color in hex format + * + * @return number + */ + public function getGreenAspect() + { + return hexdec(substr($this->getColor(), 2, 2)); + } + + /** + * Get blue aspect from a color in hex format + * + * @return number + */ + public function getBlueAspect() + { + return hexdec(substr($this->getColor(), 4, 2)); + } + + /** + * Used to sort the colors according to their brightness. Due to the vast numbers of colors to be displayed + * to the user, they must be ordered in some fashion, dominant aspect and brightness are possible values. + * See: https://en.wikipedia.org/wiki/YIQ + * + * @return float|null + */ + public function getPerceivedBrightness() + { + if ($this->brightness === null) { + $r = $this->getRedAspect(); + $g = $this->getGreenAspect(); + $b = $this->getBlueAspect(); + + $this->brightness = sqrt( + $r * $r * .299 + + $g * $g * .587 + + $b * $b * .114 + ); + } + return $this->brightness; + } + + /** + * Used to sort colors according to their brightness + * + * @param ilSystemStyleIconColor $color1 + * @param ilSystemStyleIconColor $color2 + * @return int + */ + public static function compareColors(ilSystemStyleIconColor $color1, ilSystemStyleIconColor $color2) + { + $value1 = $color1->getPerceivedBrightness(); + $value2 = $color2->getPerceivedBrightness(); + + if ($value1 == $value2) { + return 0; + } + return ($value1 > $value2) ? +1 : -1; + } +} diff --git a/Services/Style/System/classes/Icons/class.ilSystemStyleIconColorSet.php b/Services/Style/System/classes/Icons/class.ilSystemStyleIconColorSet.php index 61ebba2fd9356b3f3d89c840befbefa23db494aa..c9db7d2ced01ba1dca6ed30fd7752bab4420250d 100644 --- a/Services/Style/System/classes/Icons/class.ilSystemStyleIconColorSet.php +++ b/Services/Style/System/classes/Icons/class.ilSystemStyleIconColorSet.php @@ -11,109 +11,116 @@ include_once("Services/Style/System/classes/Icons/class.ilSystemStyleIconColor.p */ class ilSystemStyleIconColorSet { - /** - * Set of colors used in this set. - * - * @var ilSystemStyleIconColor[] - */ - protected $colors = []; + /** + * Set of colors used in this set. + * + * @var ilSystemStyleIconColor[] + */ + protected $colors = []; - /** - * @param ilSystemStyleIconColor $color - */ - public function addColor(ilSystemStyleIconColor $color){ - $this->colors[$color->getId()] = $color; - } + /** + * @param ilSystemStyleIconColor $color + */ + public function addColor(ilSystemStyleIconColor $color) + { + $this->colors[$color->getId()] = $color; + } - /** - * @return ilSystemStyleIconColor[] - */ - public function getColors() - { - return $this->colors; - } + /** + * @return ilSystemStyleIconColor[] + */ + public function getColors() + { + return $this->colors; + } - /** - * @param ilSystemStyleIconColor[] $colors - */ - public function setColors(array $colors) - { - $this->colors = $colors; - } + /** + * @param ilSystemStyleIconColor[] $colors + */ + public function setColors(array $colors) + { + $this->colors = $colors; + } - /** - * @param string $id - * @return ilSystemStyleIconColor - * @throws ilSystemStyleException - */ - public function getColorById($id = ""){ - if(!array_key_exists($id,$this->colors)){ - throw new ilSystemStyleException(ilSystemStyleException::INVALID_ID,$id); - } - return $this->colors[$id]; - } + /** + * @param string $id + * @return ilSystemStyleIconColor + * @throws ilSystemStyleException + */ + public function getColorById($id = "") + { + if (!array_key_exists($id, $this->colors)) { + throw new ilSystemStyleException(ilSystemStyleException::INVALID_ID, $id); + } + return $this->colors[$id]; + } - /** - * @param string $id - * @return bool - */ - public function doesColorExist($id){ - return array_key_exists($id,$this->colors); - } + /** + * @param string $id + * @return bool + */ + public function doesColorExist($id) + { + return array_key_exists($id, $this->colors); + } - /** - * Merges an other colorset into this one - * - * @param ilSystemStyleIconColorSet $color_set - */ - public function mergeColorSet(ilSystemStyleIconColorSet $color_set){ - foreach($color_set->getColors() as $color){ - if(!$this->doesColorExist($color->getId())){ - $this->addColor($color); - } - } - } + /** + * Merges an other colorset into this one + * + * @param ilSystemStyleIconColorSet $color_set + */ + public function mergeColorSet(ilSystemStyleIconColorSet $color_set) + { + foreach ($color_set->getColors() as $color) { + if (!$this->doesColorExist($color->getId())) { + $this->addColor($color); + } + } + } - /** - * Orders and sorts the colors to be displayed in GUI (form) - * @return array [CategoryOfColor][color] - */ - public function getColorsSortedAsArray(){ - $colors_categories = []; - foreach($this->getColors() as $color){ - $colors_categories[$color->getDominatAspect()][] = $color; - } - ksort($colors_categories); - foreach($colors_categories as $category => $colors){ - usort($colors_categories[$category],array("ilSystemStyleIconColor","compareColors")); - } + /** + * Orders and sorts the colors to be displayed in GUI (form) + * @return array [CategoryOfColor][color] + */ + public function getColorsSortedAsArray() + { + $colors_categories = []; + foreach ($this->getColors() as $color) { + $colors_categories[$color->getDominatAspect()][] = $color; + } + ksort($colors_categories); + foreach ($colors_categories as $category => $colors) { + usort($colors_categories[$category], array("ilSystemStyleIconColor","compareColors")); + } - return $colors_categories; - } + return $colors_categories; + } - /** - * Returns the ids of the colors of this color set as array - * - * @return array [color_id] - */ - public function asArray(){ - $colors = []; - foreach($this->getColors() as $color){ - $colors[] = $color->getId(); - } - return $colors; - } + /** + * Returns the ids of the colors of this color set as array + * + * @return array [color_id] + */ + public function asArray() + { + $colors = []; + foreach ($this->getColors() as $color) { + $colors[] = $color->getId(); + } + return $colors; + } - /** - * Returns the ids of the colors of this color set as string - * - * @return array - */ - public function asString(){ - $colors = ""; - foreach($this->getColors() as $color){ - $colors .= $color->getId()."; "; - } - return $colors; - } -} \ No newline at end of file + /** + * Returns the ids of the colors of this color set as string + * + * @return array + */ + public function asString() + { + $colors = ""; + foreach ($this->getColors() as $color) { + $colors .= $color->getId() . "; "; + } + return $colors; + } +} diff --git a/Services/Style/System/classes/Icons/class.ilSystemStyleIconFolder.php b/Services/Style/System/classes/Icons/class.ilSystemStyleIconFolder.php index 3cb3cede641f40102e9d15f28cf85e6c185628b0..99c593300c92e7413c166c4ea7251d6f8bb515af 100644 --- a/Services/Style/System/classes/Icons/class.ilSystemStyleIconFolder.php +++ b/Services/Style/System/classes/Icons/class.ilSystemStyleIconFolder.php @@ -14,244 +14,250 @@ require_once("./Services/Style/System/classes/Exceptions/class.ilSystemStyleIcon */ class ilSystemStyleIconFolder { - /** - * Icons a folder contains - * - * @var ilSystemStyleIcon[] - */ - protected $icons = []; + /** + * Icons a folder contains + * + * @var ilSystemStyleIcon[] + */ + protected $icons = []; - /** - * Path to the root of the folder - * - * @var string - */ - protected $path = ""; + /** + * Path to the root of the folder + * + * @var string + */ + protected $path = ""; - /** - * Complete color set of all icons contained in this folder - * - * @var ilSystemStyleIconColorSet - */ - protected $color_set = null; + /** + * Complete color set of all icons contained in this folder + * + * @var ilSystemStyleIconColorSet + */ + protected $color_set = null; - /** - * ilSystemStyleIconFolder constructor. - * @param string $path - */ - public function __construct($path) - { - $this->setPath($path); - $this->read(); - } + /** + * ilSystemStyleIconFolder constructor. + * @param string $path + */ + public function __construct($path) + { + $this->setPath($path); + $this->read(); + } - /** - * Reads the folder recursively and sorts the icons by name and type - * - * @throws ilSystemStyleException - */ - public function read(){ - $this->xRead($this->getPath(),""); - $this->sortIcons(); - } + /** + * Reads the folder recursively and sorts the icons by name and type + * + * @throws ilSystemStyleException + */ + public function read() + { + $this->xRead($this->getPath(), ""); + $this->sortIcons(); + } - /** - * Sorts the Icons by name and type - */ - protected function sortIcons(){ - usort($this->icons, function(ilSystemStyleIcon $a, ilSystemStyleIcon $b){ - if($a->getType() == $b->getType()){ - return strcmp($a->getName(),$b->getName()); - } - else{ - if($a->getType() == "svg"){ - return false; - }else if($b->getType() == "svg"){ - return true; - }else{ - return strcmp($a->getType(),$b->getType()); - } - } - }); - } + /** + * Sorts the Icons by name and type + */ + protected function sortIcons() + { + usort($this->icons, function (ilSystemStyleIcon $a, ilSystemStyleIcon $b) { + if ($a->getType() == $b->getType()) { + return strcmp($a->getName(), $b->getName()); + } else { + if ($a->getType() == "svg") { + return false; + } elseif ($b->getType() == "svg") { + return true; + } else { + return strcmp($a->getType(), $b->getType()); + } + } + }); + } - /** - * @param string $src - * @param string $rel_path - * @throws ilSystemStyleException - * @throws ilSystemStyleIconException - */ - protected function xRead($src = "",$rel_path=""){ - if(!is_dir($src)){ - throw new ilSystemStyleIconException(ilSystemStyleIconException::IMAGES_FOLDER_DOES_NOT_EXIST,$src); - } - foreach (scandir($src) as $file) { - $src_file = rtrim($src, '/') . '/' . $file; - if (!is_readable($src_file)) { - throw new ilSystemStyleException(ilSystemStyleException::FILE_OPENING_FAILED, $src_file); - } - if (substr($file, 0, 1) != ".") { - if (is_dir($src_file)) { - self::xRead($src_file,$rel_path."/".$file); - } else { - $info = new SplFileInfo($src_file); - $extension = $info->getExtension(); - if($extension == "gif" || $extension == "svg" || $extension == "png"){ - $this->addIcon(new ilSystemStyleIcon($file,$this->getPath().$rel_path."/".$file,$extension)); - } - } - } - } - } + /** + * @param string $src + * @param string $rel_path + * @throws ilSystemStyleException + * @throws ilSystemStyleIconException + */ + protected function xRead($src = "", $rel_path="") + { + if (!is_dir($src)) { + throw new ilSystemStyleIconException(ilSystemStyleIconException::IMAGES_FOLDER_DOES_NOT_EXIST, $src); + } + foreach (scandir($src) as $file) { + $src_file = rtrim($src, '/') . '/' . $file; + if (!is_readable($src_file)) { + throw new ilSystemStyleException(ilSystemStyleException::FILE_OPENING_FAILED, $src_file); + } + if (substr($file, 0, 1) != ".") { + if (is_dir($src_file)) { + self::xRead($src_file, $rel_path . "/" . $file); + } else { + $info = new SplFileInfo($src_file); + $extension = $info->getExtension(); + if ($extension == "gif" || $extension == "svg" || $extension == "png") { + $this->addIcon(new ilSystemStyleIcon($file, $this->getPath() . $rel_path . "/" . $file, $extension)); + } + } + } + } + } - /** - * Changes a set of colors in all icons contained in the folder - * - * @param array $color_changes - */ - public function changeIconColors(array $color_changes){ - foreach($this->getIcons() as $icon){ - $icon->changeColors($color_changes); - } - } + /** + * Changes a set of colors in all icons contained in the folder + * + * @param array $color_changes + */ + public function changeIconColors(array $color_changes) + { + foreach ($this->getIcons() as $icon) { + $icon->changeColors($color_changes); + } + } - /** - * Adds an icon to the folders abstraction - * - * @param ilSystemStyleIcon $icon - */ - public function addIcon(ilSystemStyleIcon $icon){ - $this->icons[] = $icon; - } + /** + * Adds an icon to the folders abstraction + * + * @param ilSystemStyleIcon $icon + */ + public function addIcon(ilSystemStyleIcon $icon) + { + $this->icons[] = $icon; + } - /** - * Gets an Icon from the folders abstraction - * - * @return ilSystemStyleIcon[] - */ - public function getIcons() - { - return $this->icons; - } + /** + * Gets an Icon from the folders abstraction + * + * @return ilSystemStyleIcon[] + */ + public function getIcons() + { + return $this->icons; + } - /** - * @param $name - * @return ilSystemStyleIcon - * @throws ilSystemStyleIconException - */ - public function getIconByName($name){ - foreach($this->icons as $icon){ - if($icon->getName() == $name){ - return $icon; - } - } - throw new ilSystemStyleIconException(ilSystemStyleIconException::ICON_DOES_NOT_EXIST,$name); - } + /** + * @param $name + * @return ilSystemStyleIcon + * @throws ilSystemStyleIconException + */ + public function getIconByName($name) + { + foreach ($this->icons as $icon) { + if ($icon->getName() == $name) { + return $icon; + } + } + throw new ilSystemStyleIconException(ilSystemStyleIconException::ICON_DOES_NOT_EXIST, $name); + } - /** - * Sorts all icons by their occurrence in folders - * - * @return array array(folder_path_name => [$icons]) - */ - public function getIconsSortedByFolder(){ - $folders = []; + /** + * Sorts all icons by their occurrence in folders + * + * @return array array(folder_path_name => [$icons]) + */ + public function getIconsSortedByFolder() + { + $folders = []; - foreach($this->getIcons() as $icon){ - $folders[dirname($icon->getPath())][] = $icon; - } + foreach ($this->getIcons() as $icon) { + $folders[dirname($icon->getPath())][] = $icon; + } - ksort($folders); + ksort($folders); - foreach($folders as $id => $folder){ - ksort($folders[$id]); - } + foreach ($folders as $id => $folder) { + ksort($folders[$id]); + } - return $folders; - } - /** - * @param ilSystemStyleIcon[] $icons - */ - public function setIcons($icons) - { - $this->icons = $icons; - } + return $folders; + } + /** + * @param ilSystemStyleIcon[] $icons + */ + public function setIcons($icons) + { + $this->icons = $icons; + } - /** - * @return string - */ - public function getPath() - { - return $this->path; - } + /** + * @return string + */ + public function getPath() + { + return $this->path; + } - /** - * @param string $path - */ - public function setPath($path) - { - $this->path = $path; - } + /** + * @param string $path + */ + public function setPath($path) + { + $this->path = $path; + } - /** - * @return ilSystemStyleIconColorSet - */ - public function getColorSet() - { - if(!$this->color_set){ - $this->extractColorSet(); - } - return $this->color_set; - } + /** + * @return ilSystemStyleIconColorSet + */ + public function getColorSet() + { + if (!$this->color_set) { + $this->extractColorSet(); + } + return $this->color_set; + } - /** - * Gets the color sets of all icons an merges them into one - */ - protected function extractColorSet(){ - $this->color_set = new ilSystemStyleIconColorSet(); - foreach($this->getIcons() as $icon){ - $this->color_set->mergeColorSet($icon->getColorSet()); - } - } + /** + * Gets the color sets of all icons an merges them into one + */ + protected function extractColorSet() + { + $this->color_set = new ilSystemStyleIconColorSet(); + foreach ($this->getIcons() as $icon) { + $this->color_set->mergeColorSet($icon->getColorSet()); + } + } - /** - * Gets the usages of a certain color - * - * @param $color_id - * @return ilSystemStyleIcon[] - */ - public function getUsagesOfColor($color_id){ - $icons = []; - foreach($this->getIcons() as $icon){ - if($icon->usesColor($color_id)){ - $icons[] = $icon; - } - } - return $icons; - } + /** + * Gets the usages of a certain color + * + * @param $color_id + * @return ilSystemStyleIcon[] + */ + public function getUsagesOfColor($color_id) + { + $icons = []; + foreach ($this->getIcons() as $icon) { + if ($icon->usesColor($color_id)) { + $icons[] = $icon; + } + } + return $icons; + } - /** - * Gets the usages of a color as string - * - * @param $color_id - * @return string - */ - public function getUsagesOfColorAsString($color_id) - { - $usage_string = ""; - foreach($this->getUsagesOfColor($color_id) as $icon){ - $usage_string .= rtrim($icon->getName(),".svg")."; "; - } - return $usage_string; - } + /** + * Gets the usages of a color as string + * + * @param $color_id + * @return string + */ + public function getUsagesOfColorAsString($color_id) + { + $usage_string = ""; + foreach ($this->getUsagesOfColor($color_id) as $icon) { + $usage_string .= rtrim($icon->getName(), ".svg") . "; "; + } + return $usage_string; + } - /** - * @param $color_set - */ - public function setColorSet($color_set) - { - $this->color_set = $color_set; - } - - -} \ No newline at end of file + /** + * @param $color_set + */ + public function setColorSet($color_set) + { + $this->color_set = $color_set; + } +} diff --git a/Services/Style/System/classes/Icons/class.ilSystemStyleIconsGUI.php b/Services/Style/System/classes/Icons/class.ilSystemStyleIconsGUI.php index 93359ad3a9151f8b2dd987ecf9ef6ed1206594e3..106074ca30bedd2619d9d01e2541c821e289c29b 100644 --- a/Services/Style/System/classes/Icons/class.ilSystemStyleIconsGUI.php +++ b/Services/Style/System/classes/Icons/class.ilSystemStyleIconsGUI.php @@ -13,437 +13,445 @@ use ILIAS\FileUpload\Location; * * @ilCtrl_Calls ilSystemStyleIconsGUI: */ -class ilSystemStyleIconsGUI +class ilSystemStyleIconsGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilSystemStyleSkinContainer - */ - protected $style_container; - - /** - * @var ilSystemStyleIconFolder - */ - protected $icon_folder = null; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * ilSystemStyleIconsGUI constructor. - * @param string $skin_id - * @param string $style_id - */ - function __construct($skin_id = "",$style_id = "") - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - $this->tabs = $DIC->tabs(); - - if($skin_id == ""){ - $skin_id = $_GET["skin_id"]; - } - if($style_id == ""){ - $style_id = $_GET["style_id"]; - } - $this->setStyleContainer(ilSystemStyleSkinContainer::generateFromId($skin_id)); - if($this->ctrl->getCmd() != "reset"){ - try{ - $this->setIconFolder(new ilSystemStyleIconFolder($this->getStyleContainer()->getImagesSkinPath($style_id))); - }catch(ilSystemStyleExceptionBase $e){ - ilUtil::sendFailure($e->getMessage()); - $this->ctrl->setCmd("fail"); - } - } - - } - - /** - * Execute command - */ - function executeCommand() - { - $cmd = $this->ctrl->getCmd(); - $this->setSubStyleSubTabs($cmd); - - switch ($cmd) - { - case "fail": - $this->fail(); - break; - case "cancelIcon": - $this->editIcon(); - break; - case "save": - case "edit": - case "editIcon": - case "update": - case "reset": - case "preview": - case "updateIcon": - $this->$cmd(); - break; - default: - $this->edit(); - break; - } - } - - protected function fail(){ - $form = $this->initByColorForm(); - $this->tpl->setContent($form->getHTML()); - } - - /** - * @param string $active - */ - protected function setSubStyleSubTabs($active = "") { - $this->tabs->addSubTab('edit', $this->lng->txt('edit_by_color'), $this->ctrl->getLinkTarget($this,'edit')); - $this->tabs->addSubTab('editIcon', $this->lng->txt('edit_by_icon'), $this->ctrl->getLinkTarget($this,'editIcon')); - $this->tabs->addSubTab('preview', $this->lng->txt('icons_gallery'), $this->ctrl->getLinkTarget($this,"preview")); - - if($active == "preview"){ - $this->tabs->activateSubTab($active); - }else if($active == "cancelIcon"|| $active == "editIcon"){ - $this->tabs->activateSubTab("editIcon"); - } - else{ - $this->tabs->activateSubTab("edit"); - } - - } - - protected function edit(){ - $form = $this->initByColorForm(); - $this->getByColorValues($form); - $this->tpl->setContent($form->getHTML()); - } - - protected function preview(){ - $this->tpl->setContent($this->renderIconsPreviews()); - } - /** - * @return ilPropertyFormGUI - */ - public function initByColorForm() - { - $form = new ilPropertyFormGUI(); - - $form->setTitle($this->lng->txt("adapt_icons")); - $form->setDescription($this->lng->txt("adapt_icons_description")); - - $color_set = []; - - if($this->getIconFolder()){ - try{ - $color_set = $this->getIconFolder()->getColorSet()->getColorsSortedAsArray(); - }catch(ilSystemStyleExceptionBase $e) { - ilUtil::sendFailure($e->getMessage()); - } - } - - foreach($color_set as $type => $colors){ - $section = new ilFormSectionHeaderGUI(); - $title = ""; - - if($type == ilSystemStyleIconColor::GREY){ - $title = $this->lng->txt("grey_color"); - $section->setTitle($this->lng->txt("grey_colors")); - $section->setInfo($this->lng->txt("grey_colors_description")); - $section->setSectionAnchor($this->lng->txt("grey_colors")); - } - if($type == ilSystemStyleIconColor::RED){ - $title = $this->lng->txt("red_color"); - $section->setTitle($this->lng->txt("red_colors")); - $section->setInfo($this->lng->txt("red_colors_description")); - $section->setSectionAnchor($this->lng->txt("red_colors")); - } - if($type == ilSystemStyleIconColor::GREEN){ - $title = $this->lng->txt("green_color"); - $section->setTitle($this->lng->txt("green_colors")); - $section->setInfo($this->lng->txt("green_colors_description")); - $section->setSectionAnchor($this->lng->txt("green_colors")); - } - if($type == ilSystemStyleIconColor::BLUE){ - $title = $this->lng->txt("blue_color"); - $section->setTitle($this->lng->txt("blue_colors")); - $section->setInfo($this->lng->txt("blue_colors_description")); - $section->setSectionAnchor($this->lng->txt("blue_colors")); - } - $form->addItem($section); - - foreach($colors as $id => $color){ - /** - * @var ilSystemStyleIconColor $color - */ - $input = new ilColorPickerInputGUI($title." ".($id+1),$color->getId()); - $input->setRequired(true); - $input->setInfo("Usages: ".$this->getIconFolder()->getUsagesOfColorAsString($color->getId())); - $form->addItem($input); - } - } - - $has_icons = $this->getIconFolder() && count($this->getIconFolder()->getIcons()) > 0; - - if($has_icons){ - $form->addCommandButton("update", $this->lng->txt("update_colors")); - } - $form->addCommandButton("reset", $this->lng->txt("reset_icons")); - if($has_icons){ - $form->addCommandButton("cancel", $this->lng->txt("cancel")); - } - - - - - $form->setFormAction($this->ctrl->getFormAction($this)); - - return $form; - } - - - /** - * @param ilPropertyFormGUI $form - */ - function getByColorValues(ilPropertyFormGUI $form) - { - $values = []; - - if($this->getIconFolder()){ - $colors = $this->getIconFolder()->getColorSet()->getColors(); - foreach($colors as $color){ - $id = $color->getId(); - if($colors[$color->getId()]){ - $values[$id] = $colors[$color->getId()]->getColor(); - }else{ - $values[$id] = $color->getColor(); - } - } - } - - - $form->setValuesByArray($values); - } - - public function reset() - { - $style = $this->getStyleContainer()->getSkin()->getStyle($_GET["style_id"]); - $this->getStyleContainer()->resetImages($style); - $this->setIconFolder(new ilSystemStyleIconFolder($this->getStyleContainer()->getImagesSkinPath($style->getId()))); - $message_stack = new ilSystemStyleMessageStack(); - $message_stack->addMessage(new ilSystemStyleMessage( - $this->lng->txt("color_reset"), - ilSystemStyleMessage::TYPE_SUCCESS)); + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilSystemStyleSkinContainer + */ + protected $style_container; + + /** + * @var ilSystemStyleIconFolder + */ + protected $icon_folder = null; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * ilSystemStyleIconsGUI constructor. + * @param string $skin_id + * @param string $style_id + */ + public function __construct($skin_id = "", $style_id = "") + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + $this->tabs = $DIC->tabs(); + + if ($skin_id == "") { + $skin_id = $_GET["skin_id"]; + } + if ($style_id == "") { + $style_id = $_GET["style_id"]; + } + $this->setStyleContainer(ilSystemStyleSkinContainer::generateFromId($skin_id)); + if ($this->ctrl->getCmd() != "reset") { + try { + $this->setIconFolder(new ilSystemStyleIconFolder($this->getStyleContainer()->getImagesSkinPath($style_id))); + } catch (ilSystemStyleExceptionBase $e) { + ilUtil::sendFailure($e->getMessage()); + $this->ctrl->setCmd("fail"); + } + } + } + + /** + * Execute command + */ + public function executeCommand() + { + $cmd = $this->ctrl->getCmd(); + $this->setSubStyleSubTabs($cmd); + + switch ($cmd) { + case "fail": + $this->fail(); + break; + case "cancelIcon": + $this->editIcon(); + break; + case "save": + case "edit": + case "editIcon": + case "update": + case "reset": + case "preview": + case "updateIcon": + $this->$cmd(); + break; + default: + $this->edit(); + break; + } + } + + protected function fail() + { + $form = $this->initByColorForm(); + $this->tpl->setContent($form->getHTML()); + } + + /** + * @param string $active + */ + protected function setSubStyleSubTabs($active = "") + { + $this->tabs->addSubTab('edit', $this->lng->txt('edit_by_color'), $this->ctrl->getLinkTarget($this, 'edit')); + $this->tabs->addSubTab('editIcon', $this->lng->txt('edit_by_icon'), $this->ctrl->getLinkTarget($this, 'editIcon')); + $this->tabs->addSubTab('preview', $this->lng->txt('icons_gallery'), $this->ctrl->getLinkTarget($this, "preview")); + + if ($active == "preview") { + $this->tabs->activateSubTab($active); + } elseif ($active == "cancelIcon"|| $active == "editIcon") { + $this->tabs->activateSubTab("editIcon"); + } else { + $this->tabs->activateSubTab("edit"); + } + } + + protected function edit() + { + $form = $this->initByColorForm(); + $this->getByColorValues($form); + $this->tpl->setContent($form->getHTML()); + } + + protected function preview() + { + $this->tpl->setContent($this->renderIconsPreviews()); + } + /** + * @return ilPropertyFormGUI + */ + public function initByColorForm() + { + $form = new ilPropertyFormGUI(); + + $form->setTitle($this->lng->txt("adapt_icons")); + $form->setDescription($this->lng->txt("adapt_icons_description")); + + $color_set = []; + + if ($this->getIconFolder()) { + try { + $color_set = $this->getIconFolder()->getColorSet()->getColorsSortedAsArray(); + } catch (ilSystemStyleExceptionBase $e) { + ilUtil::sendFailure($e->getMessage()); + } + } + + foreach ($color_set as $type => $colors) { + $section = new ilFormSectionHeaderGUI(); + $title = ""; + + if ($type == ilSystemStyleIconColor::GREY) { + $title = $this->lng->txt("grey_color"); + $section->setTitle($this->lng->txt("grey_colors")); + $section->setInfo($this->lng->txt("grey_colors_description")); + $section->setSectionAnchor($this->lng->txt("grey_colors")); + } + if ($type == ilSystemStyleIconColor::RED) { + $title = $this->lng->txt("red_color"); + $section->setTitle($this->lng->txt("red_colors")); + $section->setInfo($this->lng->txt("red_colors_description")); + $section->setSectionAnchor($this->lng->txt("red_colors")); + } + if ($type == ilSystemStyleIconColor::GREEN) { + $title = $this->lng->txt("green_color"); + $section->setTitle($this->lng->txt("green_colors")); + $section->setInfo($this->lng->txt("green_colors_description")); + $section->setSectionAnchor($this->lng->txt("green_colors")); + } + if ($type == ilSystemStyleIconColor::BLUE) { + $title = $this->lng->txt("blue_color"); + $section->setTitle($this->lng->txt("blue_colors")); + $section->setInfo($this->lng->txt("blue_colors_description")); + $section->setSectionAnchor($this->lng->txt("blue_colors")); + } + $form->addItem($section); + + foreach ($colors as $id => $color) { + /** + * @var ilSystemStyleIconColor $color + */ + $input = new ilColorPickerInputGUI($title . " " . ($id+1), $color->getId()); + $input->setRequired(true); + $input->setInfo("Usages: " . $this->getIconFolder()->getUsagesOfColorAsString($color->getId())); + $form->addItem($input); + } + } + + $has_icons = $this->getIconFolder() && count($this->getIconFolder()->getIcons()) > 0; + + if ($has_icons) { + $form->addCommandButton("update", $this->lng->txt("update_colors")); + } + $form->addCommandButton("reset", $this->lng->txt("reset_icons")); + if ($has_icons) { + $form->addCommandButton("cancel", $this->lng->txt("cancel")); + } + + + + + $form->setFormAction($this->ctrl->getFormAction($this)); + + return $form; + } + + + /** + * @param ilPropertyFormGUI $form + */ + public function getByColorValues(ilPropertyFormGUI $form) + { + $values = []; + + if ($this->getIconFolder()) { + $colors = $this->getIconFolder()->getColorSet()->getColors(); + foreach ($colors as $color) { + $id = $color->getId(); + if ($colors[$color->getId()]) { + $values[$id] = $colors[$color->getId()]->getColor(); + } else { + $values[$id] = $color->getColor(); + } + } + } + + + $form->setValuesByArray($values); + } + + public function reset() + { + $style = $this->getStyleContainer()->getSkin()->getStyle($_GET["style_id"]); + $this->getStyleContainer()->resetImages($style); + $this->setIconFolder(new ilSystemStyleIconFolder($this->getStyleContainer()->getImagesSkinPath($style->getId()))); + $message_stack = new ilSystemStyleMessageStack(); + $message_stack->addMessage(new ilSystemStyleMessage( + $this->lng->txt("color_reset"), + ilSystemStyleMessage::TYPE_SUCCESS + )); $message_stack->sendMessages(true); - $this->ctrl->redirect($this,"edit"); - } - - public function update() - { - $form = $this->initByColorForm(); - if ($form->checkInput()) - { - $message_stack = new ilSystemStyleMessageStack(); - - $color_changes = []; - foreach($this->getIconFolder()->getColorSet()->getColors() as $old_color){ - $new_color = $form->getInput($old_color->getId()); - if(!preg_match("/[\dabcdef]{6}/i",$new_color)){ - $message_stack->addMessage(new ilSystemStyleMessage($this->lng->txt("invalid_color").$new_color, - ilSystemStyleMessage::TYPE_ERROR)); - }else if($new_color != $old_color->getId()){ - $color_changes[$old_color->getId()] = $new_color; - $message_stack->addMessage(new ilSystemStyleMessage( - $this->lng->txt("color_changed_from")." ".$old_color->getId()." ". - $this->lng->txt("color_changed_to")." ".$new_color, - ilSystemStyleMessage::TYPE_SUCCESS)); - } - } - $this->getIconFolder()->changeIconColors($color_changes); - $this->setIconFolder(new ilSystemStyleIconFolder($this->getStyleContainer()->getImagesSkinPath($_GET["style_id"]))); + $this->ctrl->redirect($this, "edit"); + } + + public function update() + { + $form = $this->initByColorForm(); + if ($form->checkInput()) { + $message_stack = new ilSystemStyleMessageStack(); + + $color_changes = []; + foreach ($this->getIconFolder()->getColorSet()->getColors() as $old_color) { + $new_color = $form->getInput($old_color->getId()); + if (!preg_match("/[\dabcdef]{6}/i", $new_color)) { + $message_stack->addMessage(new ilSystemStyleMessage( + $this->lng->txt("invalid_color") . $new_color, + ilSystemStyleMessage::TYPE_ERROR + )); + } elseif ($new_color != $old_color->getId()) { + $color_changes[$old_color->getId()] = $new_color; + $message_stack->addMessage(new ilSystemStyleMessage( + $this->lng->txt("color_changed_from") . " " . $old_color->getId() . " " . + $this->lng->txt("color_changed_to") . " " . $new_color, + ilSystemStyleMessage::TYPE_SUCCESS + )); + } + } + $this->getIconFolder()->changeIconColors($color_changes); + $this->setIconFolder(new ilSystemStyleIconFolder($this->getStyleContainer()->getImagesSkinPath($_GET["style_id"]))); $skin = $this->getStyleContainer()->getSkin(); $skin->getVersionStep($skin->getVersion()); $this->getStyleContainer()->updateSkin($skin); - $message_stack->addMessage(new ilSystemStyleMessage($this->lng->txt("color_update"), - ilSystemStyleMessage::TYPE_SUCCESS)); + $message_stack->addMessage(new ilSystemStyleMessage( + $this->lng->txt("color_update"), + ilSystemStyleMessage::TYPE_SUCCESS + )); $message_stack->sendMessages(true); - $this->ctrl->redirect($this,"edit"); - } - $form->setValuesByPost(); - $this->tpl->setContent($form->getHTML()); - } + $this->ctrl->redirect($this, "edit"); + } + $form->setValuesByPost(); + $this->tpl->setContent($form->getHTML()); + } + + + protected function editIcon() + { + $icon_name = $_POST['selected_icon']?$_POST['selected_icon']:$_GET['selected_icon']; + + $this->addSelectIconToolbar($icon_name); + + if ($icon_name) { + $icon = $this->getIconFolder()->getIconByName($icon_name); + $form = $this->initByIconForm($icon); + $this->getByIconValues($form, $icon); + $this->tpl->setContent($form->getHTML() . $this->renderIconPreview($icon)); + } + } + + /** + * @param $icon_name + */ + protected function addSelectIconToolbar($icon_name) + { + global $DIC; + + $toolbar = $DIC->toolbar(); + + $si = new ilSelectInputGUI($this->lng->txt("select_icon"), "selected_icon"); + + $options = array(); + foreach ($this->getIconFolder()->getIcons() as $icon) { + if ($icon->getType()=="svg") { + $options[$icon->getName()] = $icon->getName(); + } + } + + $si->setOptions($options); + + $si->setValue($icon_name); + + $toolbar->addInputItem($si, true); + + $select_btn = ilSubmitButton::getInstance(); + $select_btn->setCaption($this->lng->txt("select"), false); + $toolbar->addButtonInstance($select_btn); + $toolbar->setFormAction($this->ctrl->getLinkTarget($this, 'editIcon')); + } + + /** + * @param $icon + * @return ilPropertyFormGUI + */ + public function initByIconForm(ilSystemStyleIcon $icon) + { + $form = new ilPropertyFormGUI(); + $form->setTitle($this->lng->txt("adapt_icon") . " " . $icon->getName()); + $form->setDescription($this->lng->txt("adapt_icon_description")); - protected function editIcon(){ - $icon_name = $_POST['selected_icon']?$_POST['selected_icon']:$_GET['selected_icon']; + $color_set = []; - $this->addSelectIconToolbar($icon_name); + if ($this->getIconFolder()) { + try { + $color_set = $icon->getColorSet()->getColorsSortedAsArray(); + } catch (ilSystemStyleExceptionBase $e) { + ilUtil::sendFailure($e->getMessage()); + } + } + + foreach ($color_set as $type => $colors) { + $title = $this->lng->txt("color"); + + foreach ($colors as $id => $color) { + /** + * @var ilSystemStyleIconColor $color + */ + $input = new ilColorPickerInputGUI($title . " " . ($id+1), $color->getId()); + $input->setRequired(true); + $form->addItem($input); + } + } + + $upload = new ilFileInputGUI($this->lng->txt("change_icon"), "changed_icon"); + $upload->setSuffixes(["svg"]); + $form->addItem($upload); + + $hidden_name = new ilHiddenInputGUI("selected_icon"); + + $form->addItem($hidden_name); + + if ($this->getIconFolder() && count($this->getIconFolder()->getIcons()) > 0) { + $form->addCommandButton("updateIcon", $this->lng->txt("update_icon")); + $form->addCommandButton("cancelIcon", $this->lng->txt("cancel")); + } - if($icon_name){ - $icon = $this->getIconFolder()->getIconByName($icon_name); - $form = $this->initByIconForm($icon); - $this->getByIconValues($form, $icon); - $this->tpl->setContent($form->getHTML().$this->renderIconPreview($icon)); - } - } - - /** - * @param $icon_name - */ - protected function addSelectIconToolbar($icon_name){ - global $DIC; - - $toolbar = $DIC->toolbar(); - - $si = new ilSelectInputGUI($this->lng->txt("select_icon"), "selected_icon"); - - $options = array(); - foreach($this->getIconFolder()->getIcons() as $icon) { - if($icon->getType()=="svg"){ - $options[$icon->getName()] = $icon->getName(); - } - } - - $si->setOptions($options); - - $si->setValue($icon_name); - - $toolbar->addInputItem($si, true); - - $select_btn = ilSubmitButton::getInstance(); - $select_btn->setCaption($this->lng->txt("select"),false); - $toolbar->addButtonInstance($select_btn); - $toolbar->setFormAction($this->ctrl->getLinkTarget($this, 'editIcon')); - } - - /** - * @param $icon - * @return ilPropertyFormGUI - */ - public function initByIconForm(ilSystemStyleIcon $icon) - { - $form = new ilPropertyFormGUI(); - - $form->setTitle($this->lng->txt("adapt_icon")." ".$icon->getName()); - $form->setDescription($this->lng->txt("adapt_icon_description")); - - $color_set = []; - - if($this->getIconFolder()){ - try{ - $color_set = $icon->getColorSet()->getColorsSortedAsArray(); - }catch(ilSystemStyleExceptionBase $e) { - ilUtil::sendFailure($e->getMessage()); - } - } - - foreach($color_set as $type => $colors){ - - $title = $this->lng->txt("color"); - - foreach($colors as $id => $color){ - /** - * @var ilSystemStyleIconColor $color - */ - $input = new ilColorPickerInputGUI($title." ".($id+1),$color->getId()); - $input->setRequired(true); - $form->addItem($input); - } - } - - $upload = new ilFileInputGUI($this->lng->txt("change_icon"),"changed_icon"); - $upload->setSuffixes(["svg"]); - $form->addItem($upload); - - $hidden_name = new ilHiddenInputGUI("selected_icon"); - - $form->addItem($hidden_name); - - if($this->getIconFolder() && count($this->getIconFolder()->getIcons()) > 0){ - $form->addCommandButton("updateIcon", $this->lng->txt("update_icon")); - $form->addCommandButton("cancelIcon", $this->lng->txt("cancel")); - } - - $form->setFormAction($this->ctrl->getFormAction($this)); - - return $form; - } - - - /** - * @param ilPropertyFormGUI $form - * @param ilSystemStyleIcon $icon - */ - function getByIconValues(ilPropertyFormGUI $form, ilSystemStyleIcon $icon) - { - $values = []; - - $colors = $this->getIconFolder()->getColorSet()->getColors(); - foreach($icon-> getColorSet()->getColors() as $color){ - $id = $color->getId(); - if($colors[$color->getId()]){ - $values[$id] = $colors[$color->getId()]->getColor(); - }else{ - $values[$id] = $color->getColor(); - } - } - $values["selected_icon"] = $icon->getName(); - - $form->setValuesByArray($values); - } + $form->setFormAction($this->ctrl->getFormAction($this)); - public function updateIcon() - { + return $form; + } + + + /** + * @param ilPropertyFormGUI $form + * @param ilSystemStyleIcon $icon + */ + public function getByIconValues(ilPropertyFormGUI $form, ilSystemStyleIcon $icon) + { + $values = []; + + $colors = $this->getIconFolder()->getColorSet()->getColors(); + foreach ($icon-> getColorSet()->getColors() as $color) { + $id = $color->getId(); + if ($colors[$color->getId()]) { + $values[$id] = $colors[$color->getId()]->getColor(); + } else { + $values[$id] = $color->getColor(); + } + } + $values["selected_icon"] = $icon->getName(); + + $form->setValuesByArray($values); + } + + public function updateIcon() + { global $DIC; - $icon_name = $_POST['selected_icon']; - $icon = $this->getIconFolder()->getIconByName($icon_name); + $icon_name = $_POST['selected_icon']; + $icon = $this->getIconFolder()->getIconByName($icon_name); - $form = $this->initByIconForm($icon); + $form = $this->initByIconForm($icon); - if ($form->checkInput()) - { - $message_stack = new ilSystemStyleMessageStack(); + if ($form->checkInput()) { + $message_stack = new ilSystemStyleMessageStack(); - $color_changes = []; - foreach($icon->getColorSet()->getColors() as $old_color){ - $new_color = $form->getInput($old_color->getId()); - if(!preg_match("/[\dabcdef]{6}/i",$new_color)){ - $message_stack->addMessage(new ilSystemStyleMessage($this->lng->txt("invalid_color").$new_color, - ilSystemStyleMessage::TYPE_ERROR)); - }else if($new_color != $old_color->getId()){ - $color_changes[$old_color->getId()] = $new_color; + $color_changes = []; + foreach ($icon->getColorSet()->getColors() as $old_color) { + $new_color = $form->getInput($old_color->getId()); + if (!preg_match("/[\dabcdef]{6}/i", $new_color)) { + $message_stack->addMessage(new ilSystemStyleMessage( + $this->lng->txt("invalid_color") . $new_color, + ilSystemStyleMessage::TYPE_ERROR + )); + } elseif ($new_color != $old_color->getId()) { + $color_changes[$old_color->getId()] = $new_color; - $message_stack->addMessage(new ilSystemStyleMessage( - $this->lng->txt("color_changed_from")." ".$old_color->getId()." ". - $this->lng->txt("color_changed_to")." ".$new_color, - ilSystemStyleMessage::TYPE_SUCCESS)); - } - } - $icon->changeColors($color_changes); + $message_stack->addMessage(new ilSystemStyleMessage( + $this->lng->txt("color_changed_from") . " " . $old_color->getId() . " " . + $this->lng->txt("color_changed_to") . " " . $new_color, + ilSystemStyleMessage::TYPE_SUCCESS + )); + } + } + $icon->changeColors($color_changes); - if($_POST["changed_icon"]){ + if ($_POST["changed_icon"]) { /** * @var \ILIAS\FileUpload\FileUpload $upload */ @@ -451,121 +459,124 @@ class ilSystemStyleIconsGUI $upload->process(); $old_icon = $this->getIconFolder()->getIconByName($icon_name); - $upload->moveOneFileTo(array_pop($upload->getResults()), + $upload->moveOneFileTo( + array_pop($upload->getResults()), $old_icon->getDirRelToCustomizing(), Location::CUSTOMIZING, $old_icon->getName(), true ); - } + } - $message_stack->addMessage(new ilSystemStyleMessage($this->lng->txt("color_update"),ilSystemStyleMessage::TYPE_SUCCESS)); + $message_stack->addMessage(new ilSystemStyleMessage($this->lng->txt("color_update"), ilSystemStyleMessage::TYPE_SUCCESS)); - foreach ($message_stack->getJoinedMessages() as $type => $message) { - if($type == ilSystemStyleMessage::TYPE_SUCCESS) { + foreach ($message_stack->getJoinedMessages() as $type => $message) { + if ($type == ilSystemStyleMessage::TYPE_SUCCESS) { $skin = $this->getStyleContainer()->getSkin(); $skin->getVersionStep($skin->getVersion()); $this->getStyleContainer()->updateSkin($skin); - continue; + continue; + } + } + $message_stack->sendMessages(true); + $this->ctrl->setParameter($this, "selected_icon", $icon->getName()); + $this->ctrl->redirect($this, "editIcon"); + } + $form->setValuesByPost(); + $this->tpl->setContent($form->getHTML()); + } + + /** + * @param ilSystemStyleIcon $icon + * @return string + */ + protected function renderIconPreview(ilSystemStyleIcon $icon) + { + global $DIC; + + $f = $DIC->ui()->factory(); + + $icon_image = $f->image()->standard($icon->getPath(), $icon->getName()); + + $card = $f->card()->standard( + $icon->getName(), + $icon_image + ); + + $report = $f->panel()->standard($this->lng->txt("preview"), $f->deck([$card])); + + return $DIC->ui()->renderer()->render($report); + } + + + /** + * @return string + */ + protected function renderIconsPreviews() + { + global $DIC; + + $f = $DIC->ui()->factory(); + + + $sub_panels = []; + foreach ($this->getIconFolder()->getIconsSortedByFolder() as $folder_name => $icons) { + $cards = []; + + foreach ($icons as $icon) { + /** + * @var ilSystemStyleIcon $icon + */ + $icon_image = $f->image()->standard($icon->getPath(), $icon->getName()); + $card = $f->card()->standard( + $icon->getName(), + $icon_image + ); + $colors = $icon->getColorSet()->asString(); + if ($colors) { + $card = $card->withSections(array( + $f->listing()->descriptive(array($this->lng->txt("used_colors")=>$colors)) + )); } + $cards[] = $card; } - $message_stack->sendMessages(true); - $this->ctrl->setParameter($this,"selected_icon",$icon->getName()); - $this->ctrl->redirect($this,"editIcon"); - } - $form->setValuesByPost(); - $this->tpl->setContent($form->getHTML()); - } - - /** - * @param ilSystemStyleIcon $icon - * @return string - */ - protected function renderIconPreview(ilSystemStyleIcon $icon){ - global $DIC; - - $f = $DIC->ui()->factory(); - - $icon_image = $f->image()->standard($icon->getPath(),$icon->getName()); - - $card = $f->card()->standard( - $icon->getName(), - $icon_image - ); - - $report = $f->panel()->standard($this->lng->txt("preview"),$f->deck([$card])); - - return $DIC->ui()->renderer()->render($report); - } - - - /** - * @return string - */ - protected function renderIconsPreviews(){ - global $DIC; - - $f = $DIC->ui()->factory(); - - - $sub_panels = []; - foreach($this->getIconFolder()->getIconsSortedByFolder() as $folder_name => $icons){ - $cards = []; - - foreach($icons as $icon){ - /** - * @var ilSystemStyleIcon $icon - */ - $icon_image = $f->image()->standard($icon->getPath(),$icon->getName()); - $card = $f->card()->standard( - $icon->getName(), - $icon_image - ); - $colors = $icon->getColorSet()->asString(); - if($colors){ - $card = $card->withSections(array( - $f->listing()->descriptive(array($this->lng->txt("used_colors")=>$colors)) - )); - } - $cards[] = $card; - } - $sub_panels[] = $f->panel()->sub($folder_name,$f->deck($cards)); - } - - $report = $f->panel()->report($this->lng->txt("icons"),$sub_panels); - - return $DIC->ui()->renderer()->render($report); - } - - /** - * @return ilSystemStyleSkinContainer - */ - public function getStyleContainer() - { - return $this->style_container; - } - - /** - * @param ilSystemStyleSkinContainer $style_container - */ - public function setStyleContainer($style_container) - { - $this->style_container = $style_container; - } - - /** - * @return ilSystemStyleIconFolder - */ - public function getIconFolder() - { - return $this->icon_folder; - } - - /** - * @param ilSystemStyleIconFolder $icon_folder - */ - public function setIconFolder($icon_folder) - { - $this->icon_folder = $icon_folder; - } -} \ No newline at end of file + $sub_panels[] = $f->panel()->sub($folder_name, $f->deck($cards)); + } + + $report = $f->panel()->report($this->lng->txt("icons"), $sub_panels); + + return $DIC->ui()->renderer()->render($report); + } + + /** + * @return ilSystemStyleSkinContainer + */ + public function getStyleContainer() + { + return $this->style_container; + } + + /** + * @param ilSystemStyleSkinContainer $style_container + */ + public function setStyleContainer($style_container) + { + $this->style_container = $style_container; + } + + /** + * @return ilSystemStyleIconFolder + */ + public function getIconFolder() + { + return $this->icon_folder; + } + + /** + * @param ilSystemStyleIconFolder $icon_folder + */ + public function setIconFolder($icon_folder) + { + $this->icon_folder = $icon_folder; + } +} diff --git a/Services/Style/System/classes/Less/class.ilSystemStyleLessCategory.php b/Services/Style/System/classes/Less/class.ilSystemStyleLessCategory.php index a9134e6b0b7731e42b2b9319bb424c0159219fa0..e666393f33c14e2cd150984c055a133b16654f3d 100644 --- a/Services/Style/System/classes/Less/class.ilSystemStyleLessCategory.php +++ b/Services/Style/System/classes/Less/class.ilSystemStyleLessCategory.php @@ -15,79 +15,77 @@ require_once("./Services/Style/System/classes/Less/class.ilSystemStyleLessItem.p */ class ilSystemStyleLessCategory extends ilSystemStyleLessItem { - /** - * Name of the category - * - * @var string - */ - protected $name = ""; + /** + * Name of the category + * + * @var string + */ + protected $name = ""; - /** - * Comment to describe what this category is about - * - * @var string - */ - protected $comment = ""; + /** + * Comment to describe what this category is about + * + * @var string + */ + protected $comment = ""; - /** - * ilSystemStyleLessCategory constructor. - * @param string $name - * @param string $comment - */ - public function __construct($name, $comment = "") - { - $this->setName($name); - $this->setComment($comment); - } + /** + * ilSystemStyleLessCategory constructor. + * @param string $name + * @param string $comment + */ + public function __construct($name, $comment = "") + { + $this->setName($name); + $this->setComment($comment); + } - /** - * @return string - */ - public function getName() - { - return $this->name; - } + /** + * @return string + */ + public function getName() + { + return $this->name; + } - /** - * @param string $name - */ - public function setName($name) - { - $name = str_replace(PHP_EOL, '', $name); + /** + * @param string $name + */ + public function setName($name) + { + $name = str_replace(PHP_EOL, '', $name); $this->name = str_replace("\n", '', $name); } - /** - * @return string - */ - public function getComment() - { - return $this->comment; - } + /** + * @return string + */ + public function getComment() + { + return $this->comment; + } - /** - * @param string $comment - */ - public function setComment($comment) - { + /** + * @param string $comment + */ + public function setComment($comment) + { $comment = str_replace(PHP_EOL, '', $comment); $this->comment = str_replace("\n", '', $comment); - } - - /** - * This function will be needed to write the category back to the less file and restore it's initial structure - * in less. - * - * @return string - */ - public function __toString() - { - if($this->getComment()){ - return "//== ".$this->getName()."\n//\n//## ".$this->getComment()."\n"; - }else{ - return "//== ".$this->getName()."\n//\n//##\n"; - - } + } - } -} \ No newline at end of file + /** + * This function will be needed to write the category back to the less file and restore it's initial structure + * in less. + * + * @return string + */ + public function __toString() + { + if ($this->getComment()) { + return "//== " . $this->getName() . "\n//\n//## " . $this->getComment() . "\n"; + } else { + return "//== " . $this->getName() . "\n//\n//##\n"; + } + } +} diff --git a/Services/Style/System/classes/Less/class.ilSystemStyleLessComment.php b/Services/Style/System/classes/Less/class.ilSystemStyleLessComment.php index 5c568281f6628b7dc80c2ec02c19dd1e1d681156..0d41223a4d2b92793462d1c4de0626b73a76a92c 100644 --- a/Services/Style/System/classes/Less/class.ilSystemStyleLessComment.php +++ b/Services/Style/System/classes/Less/class.ilSystemStyleLessComment.php @@ -15,48 +15,47 @@ require_once("./Services/Style/System/classes/Less/class.ilSystemStyleLessItem.p class ilSystemStyleLessComment extends ilSystemStyleLessItem { - /** - * Random content of the less file being neither part of a variable or category - * - * @var string - */ - protected $comment = ""; + /** + * Random content of the less file being neither part of a variable or category + * + * @var string + */ + protected $comment = ""; - /** - * ilSystemStyleLessComment constructor. - * @param string $comment - */ - public function __construct($comment) - { - $this->setComment($comment); - } + /** + * ilSystemStyleLessComment constructor. + * @param string $comment + */ + public function __construct($comment) + { + $this->setComment($comment); + } - /** - * @return string - */ - public function getComment() - { - return $this->comment; - } + /** + * @return string + */ + public function getComment() + { + return $this->comment; + } - /** - * @param string $comment - */ - public function setComment($comment) - { + /** + * @param string $comment + */ + public function setComment($comment) + { $comment = str_replace(PHP_EOL, '', $comment); $this->comment = str_replace("\n", '', $comment); - } + } - /** - * This function will be needed to write the comment back to the less file and restore it's initial structure - * in less. - * - * @return string - */ - public function __toString() - { - return $this->getComment()."\n"; - } - -} \ No newline at end of file + /** + * This function will be needed to write the comment back to the less file and restore it's initial structure + * in less. + * + * @return string + */ + public function __toString() + { + return $this->getComment() . "\n"; + } +} diff --git a/Services/Style/System/classes/Less/class.ilSystemStyleLessFile.php b/Services/Style/System/classes/Less/class.ilSystemStyleLessFile.php index 40744b00656b1126240b6ab10c9fd84df3150a59..bcf0e33c78eedce965e316d0912283c60dd4ad94 100644 --- a/Services/Style/System/classes/Less/class.ilSystemStyleLessFile.php +++ b/Services/Style/System/classes/Less/class.ilSystemStyleLessFile.php @@ -15,300 +15,309 @@ require_once("./Services/Style/System/classes/Less/class.ilSystemStyleLessVariab */ class ilSystemStyleLessFile { - /** - * List of items (variabe, category or comment) this file contains - * - * @var ilSystemStyleLessVariable[] - */ - protected $items = array(); - - /** - * Separated array with all comments ids (performance reasons) - * - * @var array - */ - protected $comments_ids = array(); - - /** - * Separated array with all variable ids (performance reasons) - * - * @var array - */ - protected $variables_ids= array(); - - /** - * Separated array with all category ids (performance reasons) - * - * @var array - */ - protected $categories_ids = array(); - - /** - * Complete path the the variables file on the file system - * - * @var string - */ - protected $less_variables_file_path = ""; - - /** - * KitchenSinkLessFile constructor. - * @param string $less_variables_file - */ - public function __construct($less_variables_file) - { - $this->less_variables_file = $less_variables_file; - $this->read(); - } - - /** - * Reads the file from the file system - * - * @throws ilSystemStyleException - */ - public function read(){ - $last_variable_comment = null; - $last_category_id = null; - $last_category_name = null; - - $regex_category = '/\/\/==\s(.*)/'; //Matches //== Category Name - $regex_category_by_line = '/^\/\/[\s]?$/'; //Matches // at the end of the line with not comment - $regex_category_comment = '/\/\/##\s(.*)/'; //Matches Matches //## Category Description - $regex_variable = '/^@(.*)/'; //Matches @VariableName value; - $regex_variable_comment = '/\/\/\*\*\s(.*)/'; //Matches //** Variable Comment - $regex_variable_name = '/(?:@)(.*)(?:\:)/'; //Matches @variableName - $regex_variable_value = '/(?::)(.*)(?:;)/'; //Matches value; - $regex_variable_references = '/(?:@)([a-zA-Z0-9_-]*)/'; //Matches references in value - - try{ - $handle = fopen($this->getLessVariablesFile(), "r"); - }catch(Exception $e){ - throw new ilSystemStyleException(ilSystemStyleException::FILE_OPENING_FAILED, $this->getLessVariablesFile()); - } - - - if ($handle) { - $line_number = 1; - $last_line_is_category = false; - //Reads file line by line - while (($line = fgets($handle)) !== false) { - //This might be part of the categories structure, if so, ignore - if($last_line_is_category && preg_match($regex_category_by_line, $line, $out)){ - $line = fgets($handle); - } - $last_line_is_category = false; - if(preg_match($regex_category, $line, $out)){ - //Check Category - $last_category_id = $this->addItem(new ilSystemStyleLessCategory($out[1])); - $last_category_name = $out[1]; - $last_line_is_category = true; - } else if(preg_match($regex_category_comment, $line, $out)){ - //Check Comment Category - $last_category = $this->getItemById($last_category_id); - $last_category->setComment($out[1]); - } else if(preg_match($regex_variable_comment, $line, $out)){ - //Check Variables Comment - $last_variable_comment = $out[1]; - } else if(preg_match($regex_variable, $line, $out)){ - //Check Variables - - //Name - preg_match($regex_variable_name, $out[0], $variable); - - //Value - preg_match($regex_variable_value, $line, $value); - - //References - $temp_value = $value[0]; - $references = array(); - while(preg_match($regex_variable_references,$temp_value,$reference)){ - $references[] = $reference[1]; - $temp_value = str_replace($reference,"",$temp_value); - } - - $this->addItem(new ilSystemStyleLessVariable( - $variable[1], - ltrim ( $value[1] ," \t\n\r\0\x0B" ), - $last_variable_comment, - $last_category_name, - $references)); - $last_variable_comment = ""; - - }else{ - $this->addItem(new ilSystemStyleLessComment($line)); - } - - - $line_number++; - } - fclose($handle); - } else { - throw new ilSystemStyleException(ilSystemStyleException::FILE_OPENING_FAILED); - } - } - - /** - * Write the complete file back to the file system (including comments and random content) - */ - public function write(){ - file_put_contents($this->getLessVariablesFile(),$this->getContent()); - } - - /** - * @return string - */ - public function getContent(){ - $output = ""; - - foreach($this->items as $item){ - $output .= $item->__toString(); - } - return $output; - } - - /** - * @param ilSystemStyleLessItem $item - * @return int - */ - public function addItem(ilSystemStyleLessItem $item){ - $id = array_push($this->items,$item)-1; - - - if(get_class($item)=="ilSystemStyleLessComment"){ - $this->comments_ids[] = $id; - }else if(get_class($item)=="ilSystemStyleLessCategory"){ - $this->categories_ids[] = $id; - }else if(get_class($item)=="ilSystemStyleLessVariable"){ - $this->variables_ids[] = $id; - } - - return $id; - } - - /** - * @return ilSystemStyleLessCategory[] - */ - public function getCategories(){ - $categories = array(); - - foreach($this->categories_ids as $category_id){ - $categories[] = $this->items[$category_id]; - } - - return $categories; - - } - - /** - * @param string $category - * @return ilSystemStyleLessVariable[]|null - */ - public function getVariablesPerCategory($category = ""){ - $variables = array(); - - foreach($this->variables_ids as $variables_id){ - if(!$category || $this->items[$variables_id]->getCategoryName() == $category){ - $variables[] = $this->items[$variables_id]; - } - } - - return $variables; - } - - /** - * @param $id - * @return ilSystemStyleLessVariable - */ - public function getItemById($id){ - return $this->items[$id]; - } - - /** - * @param string $name - * @return ilSystemStyleLessVariable|null - */ - public function getVariableByName($name = ""){ - foreach($this->variables_ids as $variables_id){ - if($this->items[$variables_id]->getName() == $name){ - return $this->items[$variables_id]; - } - } - return null; - - } - - /** - * @param $variable_name - * @return array - */ - public function getReferencesToVariable($variable_name){ - $references = []; - - foreach($this->variables_ids as $id){ - foreach($this->items[$id]->getReferences() as $reference){ - if($variable_name == $reference) - $references[] = $this->items[$id]->getName(); - } - } - return $references; - } - - /** - * @param $variable_name - * @return string - */ - public function getReferencesToVariableAsString($variable_name){ - $references_string = ""; - foreach($this->getReferencesToVariable($variable_name) as $reference){ - $references_string .= "$reference; "; - } - return $references_string; - } - - /** - * @return string - */ - public function getLessVariablesFile() - { - return $this->less_variables_file; - } - - /** - * @param string $less_variables_file - */ - public function setLessVariablesFile($less_variables_file) - { - $this->less_variables_file = $less_variables_file; - } - - /** - * @return ilSystemStyleLessVariable[] - */ - public function getItems() - { - return $this->items; - } - - /** - * @return array - */ - public function getCommentsIds() - { - return $this->comments_ids; - } - - /** - * @return array - */ - public function getVariablesIds() - { - return $this->variables_ids; - } - - /** - * @return array - */ - public function getCategoriesIds() - { - return $this->categories_ids; - } -} \ No newline at end of file + /** + * List of items (variabe, category or comment) this file contains + * + * @var ilSystemStyleLessVariable[] + */ + protected $items = array(); + + /** + * Separated array with all comments ids (performance reasons) + * + * @var array + */ + protected $comments_ids = array(); + + /** + * Separated array with all variable ids (performance reasons) + * + * @var array + */ + protected $variables_ids= array(); + + /** + * Separated array with all category ids (performance reasons) + * + * @var array + */ + protected $categories_ids = array(); + + /** + * Complete path the the variables file on the file system + * + * @var string + */ + protected $less_variables_file_path = ""; + + /** + * KitchenSinkLessFile constructor. + * @param string $less_variables_file + */ + public function __construct($less_variables_file) + { + $this->less_variables_file = $less_variables_file; + $this->read(); + } + + /** + * Reads the file from the file system + * + * @throws ilSystemStyleException + */ + public function read() + { + $last_variable_comment = null; + $last_category_id = null; + $last_category_name = null; + + $regex_category = '/\/\/==\s(.*)/'; //Matches //== Category Name + $regex_category_by_line = '/^\/\/[\s]?$/'; //Matches // at the end of the line with not comment + $regex_category_comment = '/\/\/##\s(.*)/'; //Matches Matches //## Category Description + $regex_variable = '/^@(.*)/'; //Matches @VariableName value; + $regex_variable_comment = '/\/\/\*\*\s(.*)/'; //Matches //** Variable Comment + $regex_variable_name = '/(?:@)(.*)(?:\:)/'; //Matches @variableName + $regex_variable_value = '/(?::)(.*)(?:;)/'; //Matches value; + $regex_variable_references = '/(?:@)([a-zA-Z0-9_-]*)/'; //Matches references in value + + try { + $handle = fopen($this->getLessVariablesFile(), "r"); + } catch (Exception $e) { + throw new ilSystemStyleException(ilSystemStyleException::FILE_OPENING_FAILED, $this->getLessVariablesFile()); + } + + + if ($handle) { + $line_number = 1; + $last_line_is_category = false; + //Reads file line by line + while (($line = fgets($handle)) !== false) { + //This might be part of the categories structure, if so, ignore + if ($last_line_is_category && preg_match($regex_category_by_line, $line, $out)) { + $line = fgets($handle); + } + $last_line_is_category = false; + if (preg_match($regex_category, $line, $out)) { + //Check Category + $last_category_id = $this->addItem(new ilSystemStyleLessCategory($out[1])); + $last_category_name = $out[1]; + $last_line_is_category = true; + } elseif (preg_match($regex_category_comment, $line, $out)) { + //Check Comment Category + $last_category = $this->getItemById($last_category_id); + $last_category->setComment($out[1]); + } elseif (preg_match($regex_variable_comment, $line, $out)) { + //Check Variables Comment + $last_variable_comment = $out[1]; + } elseif (preg_match($regex_variable, $line, $out)) { + //Check Variables + + //Name + preg_match($regex_variable_name, $out[0], $variable); + + //Value + preg_match($regex_variable_value, $line, $value); + + //References + $temp_value = $value[0]; + $references = array(); + while (preg_match($regex_variable_references, $temp_value, $reference)) { + $references[] = $reference[1]; + $temp_value = str_replace($reference, "", $temp_value); + } + + $this->addItem(new ilSystemStyleLessVariable( + $variable[1], + ltrim($value[1], " \t\n\r\0\x0B"), + $last_variable_comment, + $last_category_name, + $references + )); + $last_variable_comment = ""; + } else { + $this->addItem(new ilSystemStyleLessComment($line)); + } + + + $line_number++; + } + fclose($handle); + } else { + throw new ilSystemStyleException(ilSystemStyleException::FILE_OPENING_FAILED); + } + } + + /** + * Write the complete file back to the file system (including comments and random content) + */ + public function write() + { + file_put_contents($this->getLessVariablesFile(), $this->getContent()); + } + + /** + * @return string + */ + public function getContent() + { + $output = ""; + + foreach ($this->items as $item) { + $output .= $item->__toString(); + } + return $output; + } + + /** + * @param ilSystemStyleLessItem $item + * @return int + */ + public function addItem(ilSystemStyleLessItem $item) + { + $id = array_push($this->items, $item)-1; + + + if (get_class($item)=="ilSystemStyleLessComment") { + $this->comments_ids[] = $id; + } elseif (get_class($item)=="ilSystemStyleLessCategory") { + $this->categories_ids[] = $id; + } elseif (get_class($item)=="ilSystemStyleLessVariable") { + $this->variables_ids[] = $id; + } + + return $id; + } + + /** + * @return ilSystemStyleLessCategory[] + */ + public function getCategories() + { + $categories = array(); + + foreach ($this->categories_ids as $category_id) { + $categories[] = $this->items[$category_id]; + } + + return $categories; + } + + /** + * @param string $category + * @return ilSystemStyleLessVariable[]|null + */ + public function getVariablesPerCategory($category = "") + { + $variables = array(); + + foreach ($this->variables_ids as $variables_id) { + if (!$category || $this->items[$variables_id]->getCategoryName() == $category) { + $variables[] = $this->items[$variables_id]; + } + } + + return $variables; + } + + /** + * @param $id + * @return ilSystemStyleLessVariable + */ + public function getItemById($id) + { + return $this->items[$id]; + } + + /** + * @param string $name + * @return ilSystemStyleLessVariable|null + */ + public function getVariableByName($name = "") + { + foreach ($this->variables_ids as $variables_id) { + if ($this->items[$variables_id]->getName() == $name) { + return $this->items[$variables_id]; + } + } + return null; + } + + /** + * @param $variable_name + * @return array + */ + public function getReferencesToVariable($variable_name) + { + $references = []; + + foreach ($this->variables_ids as $id) { + foreach ($this->items[$id]->getReferences() as $reference) { + if ($variable_name == $reference) { + $references[] = $this->items[$id]->getName(); + } + } + } + return $references; + } + + /** + * @param $variable_name + * @return string + */ + public function getReferencesToVariableAsString($variable_name) + { + $references_string = ""; + foreach ($this->getReferencesToVariable($variable_name) as $reference) { + $references_string .= "$reference; "; + } + return $references_string; + } + + /** + * @return string + */ + public function getLessVariablesFile() + { + return $this->less_variables_file; + } + + /** + * @param string $less_variables_file + */ + public function setLessVariablesFile($less_variables_file) + { + $this->less_variables_file = $less_variables_file; + } + + /** + * @return ilSystemStyleLessVariable[] + */ + public function getItems() + { + return $this->items; + } + + /** + * @return array + */ + public function getCommentsIds() + { + return $this->comments_ids; + } + + /** + * @return array + */ + public function getVariablesIds() + { + return $this->variables_ids; + } + + /** + * @return array + */ + public function getCategoriesIds() + { + return $this->categories_ids; + } +} diff --git a/Services/Style/System/classes/Less/class.ilSystemStyleLessGUI.php b/Services/Style/System/classes/Less/class.ilSystemStyleLessGUI.php index b9a46551d78b385202655506c475e737ef12e7ed..45a974ba42f84d46702f7ae5d9d964bcc8c9338e 100644 --- a/Services/Style/System/classes/Less/class.ilSystemStyleLessGUI.php +++ b/Services/Style/System/classes/Less/class.ilSystemStyleLessGUI.php @@ -12,369 +12,360 @@ include_once("Services/Style/System/classes/Utilities/class.ilSystemStyleMessage */ class ilSystemStyleLessGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilSystemStyleSkinContainer - */ - protected $style_container; - - /** - * @var ilSystemStyleLessFile - */ - protected $less_file; - - /** - * @var ilSystemStyleMessageStack - */ - protected $message_stack; - - - /** - * ilSystemStyleLessGUI constructor. - * @param string $skin_id - * @param string $style_id - */ - function __construct($skin_id = "",$style_id = "") - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - - $this->setMessageStack(new ilSystemStyleMessageStack()); - - if($skin_id == ""){ - $skin_id = $_GET["skin_id"]; - } - if($style_id == ""){ - $style_id = $_GET["style_id"]; - } - - try{ - $this->setStyleContainer(ilSystemStyleSkinContainer::generateFromId($skin_id)); - $less_file = new ilSystemStyleLessFile($this->getStyleContainer()->getLessVariablesFilePath($style_id)); - $this->setLessFile($less_file); - }catch(ilSystemStyleException $e){ - $this->getMessageStack()->addMessage( - new ilSystemStyleMessage($e->getMessage(),ilSystemStyleMessage::TYPE_ERROR) - ); - } - - - } - - /** - * Execute command - */ - function executeCommand() - { - $cmd = $this->ctrl->getCmd(); - - switch ($cmd) - { - case "save": - case "edit": - case "reset": - case "update": - $this->$cmd(); - break; - default: - $this->edit(); - break; - } - } - - - /** - * @return bool - */ - protected function checkRequirements(){ - $style_id = $_GET['style_id']; - $less_path = $this->getStyleContainer()->getLessFilePath($style_id); - - $pass = $this->checkLessInstallation(); - - if(file_exists($less_path)){ - $less_variables_name = $this->getStyleContainer()->getLessVariablesName($style_id); - $content = ""; - try{ - $content = file_get_contents($less_path); - }catch(Exception $e){ - $this->getMessageStack()->addMessage( - new ilSystemStyleMessage($this->lng->txt("can_not_read_less_file")." ".$less_path,ilSystemStyleMessage::TYPE_ERROR) - ); - $pass = false; - } - if($content){ - $reg_exp = "/".preg_quote ($less_variables_name,"/")."/"; - - if(!preg_match($reg_exp,$content)){ - $this->getMessageStack()->addMessage( - new ilSystemStyleMessage($this->lng->txt("less_variables_file_not_included")." ".$less_variables_name - ." ".$this->lng->txt("in_main_less_file")." ".$less_path,ilSystemStyleMessage::TYPE_ERROR) - ); - $pass = false; - } - } - - - }else{ - $this->getMessageStack()->addMessage( - new ilSystemStyleMessage($this->lng->txt("less_file_does_not_exist").$less_path,ilSystemStyleMessage::TYPE_ERROR) - ); - $pass = false; - } - return $pass; - } - - /** - * @return bool - */ - protected function checkLessInstallation(){ - $pass = true; - - if(!PATH_TO_LESSC){ - $this->getMessageStack()->addMessage( - new ilSystemStyleMessage($this->lng->txt("no_less_path_set"),ilSystemStyleMessage::TYPE_ERROR) - ); - $pass = false; - }else if(!shell_exec(PATH_TO_LESSC)){ - $this->getMessageStack()->addMessage( - new ilSystemStyleMessage($this->lng->txt("invalid_less_path"),ilSystemStyleMessage::TYPE_ERROR) - ); - $this->getMessageStack()->addMessage( - new ilSystemStyleMessage($this->lng->txt("provided_less_path")." ".PATH_TO_LESSC,ilSystemStyleMessage::TYPE_ERROR) - ); - $pass = false; - } - - if(!$pass && shell_exec("which lessc")){ - $this->getMessageStack()->addMessage( - new ilSystemStyleMessage($this->lng->txt("less_less_installation_detected").shell_exec("which lessc"),ilSystemStyleMessage::TYPE_ERROR) - ); - } - - return $pass; - } - - - protected function edit(){ - - $modify = true; - - if(!$this->checkRequirements()){ - $this->getMessageStack()->prependMessage( - new ilSystemStyleMessage($this->lng->txt("less_can_not_be_modified"), ilSystemStyleMessage::TYPE_ERROR)); - $modify = false; - } - - if($this->getLessFile()){ - $form = $this->initSystemStyleLessForm($modify); - $this->getVariablesValues($form); - $this->tpl->setContent($form->getHTML()); - } - - $this->getMessageStack()->sendMessages(true); - - - } - - /** - * @param bool|true $modify - * @return ilPropertyFormGUI - */ - public function initSystemStyleLessForm($modify = true) - { - $form = new ilPropertyFormGUI(); - - $form->setTitle($this->lng->txt("adapt_less")); - $form->setDescription($this->lng->txt("adapt_less_description")); - $focus_variable = $_GET['id_less_variable']; - if($focus_variable){ - $this->tpl->addOnLoadCode("setTimeout(function() { $('#".$focus_variable."').focus();}, 100);"); - } - - foreach($this->getLessFile()->getCategories() as $category){ - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($category->getName()); - $section->setInfo($category->getComment()); - //$section->setSectionAnchor($category->getName()); - $form->addItem($section); - foreach($this->getLessFile()->getVariablesPerCategory($category->getName()) as $variable){ - $input = new ilTextInputGUI($variable->getName(), $variable->getName()); - $input->setRequired(true); - $input->setDisabled(!$modify); - - $references = $this->getLessFile()->getReferencesToVariableAsString($variable->getName()); - - if($references != ""){ - if($variable->getComment()){ - $info = $variable->getComment()."
                  ".$this->lng->txt("usages")." ".$references; - }else{ - $info = $this->lng->txt("usages")." ".$references; - } - }else{ - $info = $variable->getComment(); - } - $input->setInfo($info); - - $form->addItem($input); - - } - } - - if($modify){ - $form->addCommandButton("update", $this->lng->txt("update_variables")); - $form->addCommandButton("reset", $this->lng->txt("reset_variables")); - $form->addCommandButton("cancel", $this->lng->txt("cancel")); - } - - - $form->setFormAction($this->ctrl->getFormAction($this)); - - return $form; - } - - - /** - * @param ilPropertyFormGUI $form - */ - function getVariablesValues(ilPropertyFormGUI $form) - { - $values = []; - foreach($this->getLessFile()->getCategories() as $category){ - foreach($this->getLessFile()->getVariablesPerCategory($category->getName()) as $variable){ - $values[$variable->getName()] = $variable->getValue(); - } - } - - $form->setValuesByArray($values); - } - - /** - * - */ - public function reset() - { - $style = $this->getStyleContainer()->getSkin()->getStyle($_GET["style_id"]); - $this->setLessFile($this->getStyleContainer()->copyVariablesFromDefault($style)); - try{ + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilSystemStyleSkinContainer + */ + protected $style_container; + + /** + * @var ilSystemStyleLessFile + */ + protected $less_file; + + /** + * @var ilSystemStyleMessageStack + */ + protected $message_stack; + + + /** + * ilSystemStyleLessGUI constructor. + * @param string $skin_id + * @param string $style_id + */ + public function __construct($skin_id = "", $style_id = "") + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + + $this->setMessageStack(new ilSystemStyleMessageStack()); + + if ($skin_id == "") { + $skin_id = $_GET["skin_id"]; + } + if ($style_id == "") { + $style_id = $_GET["style_id"]; + } + + try { + $this->setStyleContainer(ilSystemStyleSkinContainer::generateFromId($skin_id)); + $less_file = new ilSystemStyleLessFile($this->getStyleContainer()->getLessVariablesFilePath($style_id)); + $this->setLessFile($less_file); + } catch (ilSystemStyleException $e) { + $this->getMessageStack()->addMessage( + new ilSystemStyleMessage($e->getMessage(), ilSystemStyleMessage::TYPE_ERROR) + ); + } + } + + /** + * Execute command + */ + public function executeCommand() + { + $cmd = $this->ctrl->getCmd(); + + switch ($cmd) { + case "save": + case "edit": + case "reset": + case "update": + $this->$cmd(); + break; + default: + $this->edit(); + break; + } + } + + + /** + * @return bool + */ + protected function checkRequirements() + { + $style_id = $_GET['style_id']; + $less_path = $this->getStyleContainer()->getLessFilePath($style_id); + + $pass = $this->checkLessInstallation(); + + if (file_exists($less_path)) { + $less_variables_name = $this->getStyleContainer()->getLessVariablesName($style_id); + $content = ""; + try { + $content = file_get_contents($less_path); + } catch (Exception $e) { + $this->getMessageStack()->addMessage( + new ilSystemStyleMessage($this->lng->txt("can_not_read_less_file") . " " . $less_path, ilSystemStyleMessage::TYPE_ERROR) + ); + $pass = false; + } + if ($content) { + $reg_exp = "/" . preg_quote($less_variables_name, "/") . "/"; + + if (!preg_match($reg_exp, $content)) { + $this->getMessageStack()->addMessage( + new ilSystemStyleMessage($this->lng->txt("less_variables_file_not_included") . " " . $less_variables_name + . " " . $this->lng->txt("in_main_less_file") . " " . $less_path, ilSystemStyleMessage::TYPE_ERROR) + ); + $pass = false; + } + } + } else { + $this->getMessageStack()->addMessage( + new ilSystemStyleMessage($this->lng->txt("less_file_does_not_exist") . $less_path, ilSystemStyleMessage::TYPE_ERROR) + ); + $pass = false; + } + return $pass; + } + + /** + * @return bool + */ + protected function checkLessInstallation() + { + $pass = true; + + if (!PATH_TO_LESSC) { + $this->getMessageStack()->addMessage( + new ilSystemStyleMessage($this->lng->txt("no_less_path_set"), ilSystemStyleMessage::TYPE_ERROR) + ); + $pass = false; + } elseif (!shell_exec(PATH_TO_LESSC)) { + $this->getMessageStack()->addMessage( + new ilSystemStyleMessage($this->lng->txt("invalid_less_path"), ilSystemStyleMessage::TYPE_ERROR) + ); + $this->getMessageStack()->addMessage( + new ilSystemStyleMessage($this->lng->txt("provided_less_path") . " " . PATH_TO_LESSC, ilSystemStyleMessage::TYPE_ERROR) + ); + $pass = false; + } + + if (!$pass && shell_exec("which lessc")) { + $this->getMessageStack()->addMessage( + new ilSystemStyleMessage($this->lng->txt("less_less_installation_detected") . shell_exec("which lessc"), ilSystemStyleMessage::TYPE_ERROR) + ); + } + + return $pass; + } + + + protected function edit() + { + $modify = true; + + if (!$this->checkRequirements()) { + $this->getMessageStack()->prependMessage( + new ilSystemStyleMessage($this->lng->txt("less_can_not_be_modified"), ilSystemStyleMessage::TYPE_ERROR) + ); + $modify = false; + } + + if ($this->getLessFile()) { + $form = $this->initSystemStyleLessForm($modify); + $this->getVariablesValues($form); + $this->tpl->setContent($form->getHTML()); + } + + $this->getMessageStack()->sendMessages(true); + } + + /** + * @param bool|true $modify + * @return ilPropertyFormGUI + */ + public function initSystemStyleLessForm($modify = true) + { + $form = new ilPropertyFormGUI(); + + $form->setTitle($this->lng->txt("adapt_less")); + $form->setDescription($this->lng->txt("adapt_less_description")); + $focus_variable = $_GET['id_less_variable']; + if ($focus_variable) { + $this->tpl->addOnLoadCode("setTimeout(function() { $('#" . $focus_variable . "').focus();}, 100);"); + } + + foreach ($this->getLessFile()->getCategories() as $category) { + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($category->getName()); + $section->setInfo($category->getComment()); + //$section->setSectionAnchor($category->getName()); + $form->addItem($section); + foreach ($this->getLessFile()->getVariablesPerCategory($category->getName()) as $variable) { + $input = new ilTextInputGUI($variable->getName(), $variable->getName()); + $input->setRequired(true); + $input->setDisabled(!$modify); + + $references = $this->getLessFile()->getReferencesToVariableAsString($variable->getName()); + + if ($references != "") { + if ($variable->getComment()) { + $info = $variable->getComment() . "
                  " . $this->lng->txt("usages") . " " . $references; + } else { + $info = $this->lng->txt("usages") . " " . $references; + } + } else { + $info = $variable->getComment(); + } + $input->setInfo($info); + + $form->addItem($input); + } + } + + if ($modify) { + $form->addCommandButton("update", $this->lng->txt("update_variables")); + $form->addCommandButton("reset", $this->lng->txt("reset_variables")); + $form->addCommandButton("cancel", $this->lng->txt("cancel")); + } + + + $form->setFormAction($this->ctrl->getFormAction($this)); + + return $form; + } + + + /** + * @param ilPropertyFormGUI $form + */ + public function getVariablesValues(ilPropertyFormGUI $form) + { + $values = []; + foreach ($this->getLessFile()->getCategories() as $category) { + foreach ($this->getLessFile()->getVariablesPerCategory($category->getName()) as $variable) { + $values[$variable->getName()] = $variable->getValue(); + } + } + + $form->setValuesByArray($values); + } + + /** + * + */ + public function reset() + { + $style = $this->getStyleContainer()->getSkin()->getStyle($_GET["style_id"]); + $this->setLessFile($this->getStyleContainer()->copyVariablesFromDefault($style)); + try { ilUtil::sendSuccess($this->lng->txt("less_file_reset")); $this->getStyleContainer()->compileLess($style->getId()); - }catch(ilSystemStyleException $e){ - ilUtil::sendFailure($this->lng->txt($e->getMessage()),true); - } - - $this->edit(); - } - - public function update() - { - $form = $this->initSystemStyleLessForm(); - if(!$form->checkInput()){ - $empty_fields = []; - foreach($this->getLessFile()->getCategories() as $category){ - foreach($this->getLessFile()->getVariablesPerCategory($category->getName()) as $variable){ - if($form->getInput($variable->getName()) == ""){ + } catch (ilSystemStyleException $e) { + ilUtil::sendFailure($this->lng->txt($e->getMessage()), true); + } + + $this->edit(); + } + + public function update() + { + $form = $this->initSystemStyleLessForm(); + if (!$form->checkInput()) { + $empty_fields = []; + foreach ($this->getLessFile()->getCategories() as $category) { + foreach ($this->getLessFile()->getVariablesPerCategory($category->getName()) as $variable) { + if ($form->getInput($variable->getName()) == "") { $empty_fields[$variable->getName()] = $this->getLessFile()->getVariableByName($variable->getName())->getValue(); $item = $form->getItemByPostVar($variable->getName()); $item->setAlert($this->lng->txt("less_variable_empty")); } } } - if(!empty($empty_fields)){ + if (!empty($empty_fields)) { $form->setValuesByPost(); - $form->setValuesByArray($empty_fields,true); - ilUtil::sendFailure($this->lng->txt("less_variables_empty_might_have_changed"),true); + $form->setValuesByArray($empty_fields, true); + ilUtil::sendFailure($this->lng->txt("less_variables_empty_might_have_changed"), true); $this->tpl->setContent($form->getHTML()); return; } + } else { + foreach ($this->getLessFile()->getCategories() as $category) { + foreach ($this->getLessFile()->getVariablesPerCategory($category->getName()) as $variable) { + $variable->setValue($form->getInput($variable->getName())); + } + } + try { + $this->getLessFile()->write(); + $this->getStyleContainer()->compileLess($_GET["style_id"]); + $skin = $this->getStyleContainer()->getSkin(); + $skin->getVersionStep($skin->getVersion()); + $this->getStyleContainer()->updateSkin($skin); + ilUtil::sendSuccess($this->lng->txt("less_file_updated")); + } catch (Exception $e) { + ilUtil::sendFailure($this->lng->txt($e->getMessage()), true); + } } - else - { - foreach($this->getLessFile()->getCategories() as $category){ - foreach($this->getLessFile()->getVariablesPerCategory($category->getName()) as $variable){ - $variable->setValue($form->getInput($variable->getName())); - } - } - try{ - $this->getLessFile()->write(); - $this->getStyleContainer()->compileLess($_GET["style_id"]); - $skin = $this->getStyleContainer()->getSkin(); - $skin->getVersionStep($skin->getVersion()); - $this->getStyleContainer()->updateSkin($skin); - ilUtil::sendSuccess($this->lng->txt("less_file_updated")); - }catch(Exception $e){ - ilUtil::sendFailure($this->lng->txt($e->getMessage()),true); - } - } - - $form->setValuesByPost(); - $this->tpl->setContent($form->getHTML()); - - } - - /** - * @return ilSystemStyleSkinContainer - */ - public function getStyleContainer() - { - return $this->style_container; - } - - /** - * @param ilSystemStyleSkinContainer $style_container - */ - public function setStyleContainer($style_container) - { - $this->style_container = $style_container; - } - - /** - * @return ilSystemStyleLessFile - */ - public function getLessFile() - { - return $this->less_file; - } - - /** - * @param ilSystemStyleLessFile $less_file - */ - public function setLessFile($less_file) - { - $this->less_file = $less_file; - } - - /** - * @return ilSystemStyleMessageStack - */ - public function getMessageStack() - { - return $this->message_stack; - } - - /** - * @param ilSystemStyleMessageStack $message_stack - */ - public function setMessageStack($message_stack) - { - $this->message_stack = $message_stack; - } - -} \ No newline at end of file + + $form->setValuesByPost(); + $this->tpl->setContent($form->getHTML()); + } + + /** + * @return ilSystemStyleSkinContainer + */ + public function getStyleContainer() + { + return $this->style_container; + } + + /** + * @param ilSystemStyleSkinContainer $style_container + */ + public function setStyleContainer($style_container) + { + $this->style_container = $style_container; + } + + /** + * @return ilSystemStyleLessFile + */ + public function getLessFile() + { + return $this->less_file; + } + + /** + * @param ilSystemStyleLessFile $less_file + */ + public function setLessFile($less_file) + { + $this->less_file = $less_file; + } + + /** + * @return ilSystemStyleMessageStack + */ + public function getMessageStack() + { + return $this->message_stack; + } + + /** + * @param ilSystemStyleMessageStack $message_stack + */ + public function setMessageStack($message_stack) + { + $this->message_stack = $message_stack; + } +} diff --git a/Services/Style/System/classes/Less/class.ilSystemStyleLessItem.php b/Services/Style/System/classes/Less/class.ilSystemStyleLessItem.php index 009157dd898f3ed4fb4366020f5efeb1a5ee358b..52d7ce23aa0543446fddee28210fc2ca6b5f68f5 100644 --- a/Services/Style/System/classes/Less/class.ilSystemStyleLessItem.php +++ b/Services/Style/System/classes/Less/class.ilSystemStyleLessItem.php @@ -8,5 +8,5 @@ */ abstract class ilSystemStyleLessItem { - abstract function __toString(); -} \ No newline at end of file + abstract public function __toString(); +} diff --git a/Services/Style/System/classes/Less/class.ilSystemStyleLessVariable.php b/Services/Style/System/classes/Less/class.ilSystemStyleLessVariable.php index b057bcb07bab82e0324a7945d32d9b981c53ce9f..6eb95e88176b6727135de310081c9b635c0d29fb 100644 --- a/Services/Style/System/classes/Less/class.ilSystemStyleLessVariable.php +++ b/Services/Style/System/classes/Less/class.ilSystemStyleLessVariable.php @@ -15,95 +15,96 @@ require_once("./Services/Style/System/classes/Less/class.ilSystemStyleLessItem.p class ilSystemStyleLessVariable extends ilSystemStyleLessItem { - /** - * Name of the variable - * - * @var string - */ - protected $name = ""; - - /** - * Value of the variable as set in the less file - * - * @var string - */ - protected $value = ""; - - /** - * Comment to the variable as in the less file - * - * @var string - */ - protected $comment = ""; - - /** - * Less Category which encloses this variable - * @var string - */ - protected $category_name = ""; - - /** - * Set references to other variables that are used by this exact variable - * - * @var array - */ - protected $references = array(); - - /** - * ilSystemStyleLessVariable constructor. - * @param $name - * @param $value - * @param $comment - * @param $category_name - * @param $references - */ - public function __construct($name, $value, $comment,$category_name, $references) - { - $this->setName($name); + /** + * Name of the variable + * + * @var string + */ + protected $name = ""; + + /** + * Value of the variable as set in the less file + * + * @var string + */ + protected $value = ""; + + /** + * Comment to the variable as in the less file + * + * @var string + */ + protected $comment = ""; + + /** + * Less Category which encloses this variable + * @var string + */ + protected $category_name = ""; + + /** + * Set references to other variables that are used by this exact variable + * + * @var array + */ + protected $references = array(); + + /** + * ilSystemStyleLessVariable constructor. + * @param $name + * @param $value + * @param $comment + * @param $category_name + * @param $references + */ + public function __construct($name, $value, $comment, $category_name, $references) + { + $this->setName($name); $this->setValue($value); $this->setCategoryName($category_name); $this->setComment($comment); - $this->setReferences($references); - } - - /** - * @return string - */ - public function getName() - { - return $this->name; - } - - /** - * @param string $name - */ - public function setName($name) - { - $this->name = $name; - } - - /** - * @return string - */ - public function getValue() - { - return $this->value; - } - - /** - * @param string $value - */ - public function setValue($value) - { - if($this->getName() == "icon-font-path"){ - if($value[0] != "\""){ - $value = "\"".$value;; + $this->setReferences($references); + } + + /** + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * @param string $name + */ + public function setName($name) + { + $this->name = $name; + } + + /** + * @return string + */ + public function getValue() + { + return $this->value; + } + + /** + * @param string $value + */ + public function setValue($value) + { + if ($this->getName() == "icon-font-path") { + if ($value[0] != "\"") { + $value = "\"" . $value; + ; } - if(substr($value,-1,1) != "\""){ + if (substr($value, -1, 1) != "\"") { $value .= "\""; } - if($value == "\"../../libs/bower/bower_components/bootstrap/fonts/\""){ + if ($value == "\"../../libs/bower/bower_components/bootstrap/fonts/\"") { $value = "\"../../../../libs/bower/bower_components/bootstrap/fonts/\""; } } @@ -112,69 +113,69 @@ class ilSystemStyleLessVariable extends ilSystemStyleLessItem $this->value = str_replace("\n", '', $value); } - /** - * @return string - */ - public function getComment() - { - return $this->comment; - } - - /** - * @param string $comment - */ - public function setComment($comment) - { + /** + * @return string + */ + public function getComment() + { + return $this->comment; + } + + /** + * @param string $comment + */ + public function setComment($comment) + { $comment = str_replace(PHP_EOL, '', $comment); $this->comment = str_replace("\n", '', $comment); - } - - /** - * @return string - */ - public function getCategoryName() - { - return $this->category_name; - } - - /** - * @param string $category_name - */ - public function setCategoryName($category_name) - { - $this->category_name = $category_name; - } - - /** - * @return array - */ - public function getReferences() - { - return $this->references; - } - - /** - * @param array $references - */ - public function setReferences($references) - { - $this->references = $references; - } - - - /** - * This function will be needed to write the variable back to the less file and restore it's initial structure - * in less. - * - * @return string - */ - public function __toString() - { - $content = ""; - if($this->getComment()){ - $content .= "//** ".$this->getComment()."\n"; - } - $content .= "@".$this->getName().":\t\t". $this->getValue().";\n"; - return $content; - } -} \ No newline at end of file + } + + /** + * @return string + */ + public function getCategoryName() + { + return $this->category_name; + } + + /** + * @param string $category_name + */ + public function setCategoryName($category_name) + { + $this->category_name = $category_name; + } + + /** + * @return array + */ + public function getReferences() + { + return $this->references; + } + + /** + * @param array $references + */ + public function setReferences($references) + { + $this->references = $references; + } + + + /** + * This function will be needed to write the variable back to the less file and restore it's initial structure + * in less. + * + * @return string + */ + public function __toString() + { + $content = ""; + if ($this->getComment()) { + $content .= "//** " . $this->getComment() . "\n"; + } + $content .= "@" . $this->getName() . ":\t\t" . $this->getValue() . ";\n"; + return $content; + } +} diff --git a/Services/Style/System/classes/Overview/class.ilSystemStyleDeleteGUI.php b/Services/Style/System/classes/Overview/class.ilSystemStyleDeleteGUI.php index 010d13cac24beff9d7847f9c083835e8e5d69917..772e0716e0c32ca91477f0ecb3344ac43fabe24e 100644 --- a/Services/Style/System/classes/Overview/class.ilSystemStyleDeleteGUI.php +++ b/Services/Style/System/classes/Overview/class.ilSystemStyleDeleteGUI.php @@ -10,77 +10,76 @@ include_once("Services/Utilities/classes/class.ilConfirmationTableGUI.php"); class ilSystemStyleDeleteGUI { - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var array - */ - protected $styles = array(); - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->lng = $DIC->language(); - $this->ctrl = $DIC->ctrl(); - } - - /** - * @param ilSkinXML $skin - * @param ilSkinStyleXML $style - */ - function addStyle(ilSkinXML $skin,ilSkinStyleXML $style){ - $this->styles[] = array( - "var" => "style_".$skin->getId().":".$style->getId(), - "id" => $skin->getId().":".$style->getId(), - "text" => $skin->getName()." / ".$style->getName(), - "img" => ilUtil::getImagePath('icon_stys.svg') - ); - } - - /** - * @return string - */ - public function getDeleteStyleFormHTML() { - ilUtil::sendQuestion($this->lng->txt("info_delete_sure"),true); - - $table_form = new ilConfirmationTableGUI(true); - $table_form->setFormName("delete_style"); - - $table_form->addCommandButton('confirmDelete', $this->lng->txt('confirm')); - $table_form->addCommandButton('cancel', $this->lng->txt('cancel')); - $table_form->setFormAction($this->ctrl->getFormActionByClass("ilSystemStyleOverviewGUI")); - $table_form->setData($this->getStyles()); - return $table_form->getHTML(); - - } - - /** - * @return array - */ - public function getStyles() - { - return $this->styles; - } - - /** - * @param array $styles - */ - public function setStyles($styles) - { - $this->styles = $styles; - } - - -} \ No newline at end of file + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var array + */ + protected $styles = array(); + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + } + + /** + * @param ilSkinXML $skin + * @param ilSkinStyleXML $style + */ + public function addStyle(ilSkinXML $skin, ilSkinStyleXML $style) + { + $this->styles[] = array( + "var" => "style_" . $skin->getId() . ":" . $style->getId(), + "id" => $skin->getId() . ":" . $style->getId(), + "text" => $skin->getName() . " / " . $style->getName(), + "img" => ilUtil::getImagePath('icon_stys.svg') + ); + } + + /** + * @return string + */ + public function getDeleteStyleFormHTML() + { + ilUtil::sendQuestion($this->lng->txt("info_delete_sure"), true); + + $table_form = new ilConfirmationTableGUI(true); + $table_form->setFormName("delete_style"); + + $table_form->addCommandButton('confirmDelete', $this->lng->txt('confirm')); + $table_form->addCommandButton('cancel', $this->lng->txt('cancel')); + $table_form->setFormAction($this->ctrl->getFormActionByClass("ilSystemStyleOverviewGUI")); + $table_form->setData($this->getStyles()); + return $table_form->getHTML(); + } + + /** + * @return array + */ + public function getStyles() + { + return $this->styles; + } + + /** + * @param array $styles + */ + public function setStyles($styles) + { + $this->styles = $styles; + } +} diff --git a/Services/Style/System/classes/Overview/class.ilSystemStyleOverviewGUI.php b/Services/Style/System/classes/Overview/class.ilSystemStyleOverviewGUI.php index 0205fe59f07a7fcb485bb07c8608542401aaad2d..676f56fbe70d68256f372bafc6abe5298fb4f4a9 100644 --- a/Services/Style/System/classes/Overview/class.ilSystemStyleOverviewGUI.php +++ b/Services/Style/System/classes/Overview/class.ilSystemStyleOverviewGUI.php @@ -19,725 +19,703 @@ include_once("Services/Object/exceptions/class.ilObjectException.php"); */ class ilSystemStyleOverviewGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ILIAS\DI\Container - */ - protected $DIC; - - /** - * @var int - */ - protected $ref_id; - - /** - * @var bool - */ - protected $read_only = true; - - /** - * @var bool - */ - protected $management_enabled = false; - - - /** - * Constructor - */ - function __construct($read_only,$management_enabled) - { - global $DIC; - - $this->ilias = $DIC["ilias"]; - $this->dic = $DIC; - $this->ctrl = $DIC->ctrl(); - $this->toolbar = $DIC->toolbar(); - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - - $this->ref_id = (int) $_GET["ref_id"]; - - $this->setReadOnly($read_only); - $this->setManagementEnabled($management_enabled); - } - - /** - * Execute command - */ - function executeCommand() - { - $cmd = $this->ctrl->getCmd(); - - if($cmd == ""){ - $cmd = $this->isReadOnly()?"view":"edit"; - } - - - switch ($cmd) - { - case "addSystemStyle": - case "addSubStyle": - case "saveNewSystemStyle": - case "saveNewSubStyle": - case "copyStyle": - case "importStyle": - case "deleteStyles": - case "deleteStyle": - case "confirmDelete": - if(!$this->isManagementEnabled()){ - throw new ilObjectException($this->lng->txt("permission_denied")); - } - $this->$cmd(); - return; - case "cancel": - case "edit": - case "export": - case "moveUserStyles": - case "saveStyleSettings": - if($this->isReadOnly()){ - throw new ilObjectException($this->lng->txt("permission_denied")); - } - $this->$cmd(); - return; - case "view": - $this->$cmd(); - return; - - } - } - - protected function view(){ - $table = new ilSystemStylesTableGUI($this, "edit",true); - $this->tpl->setContent($table->getHTML()); - } - - protected function cancel(){ - $this->edit(); - } - /** - * Edit - */ - function edit() - { - - if($this->isManagementEnabled()){ - // Add Button for adding skins - $add_skin_btn = ilLinkButton::getInstance(); - $add_skin_btn->setCaption($this->lng->txt("add_system_style"),false); - $add_skin_btn->setUrl($this->ctrl->getLinkTarget($this, 'addSystemStyle')); - $this->toolbar->addButtonInstance($add_skin_btn); - - // Add Button for adding skins - $add_substyle_btn = ilLinkButton::getInstance(); - $add_substyle_btn->setCaption($this->lng->txt("add_substyle"),false); - $add_substyle_btn->setUrl($this->ctrl->getLinkTarget($this, 'addSubStyle')); - if(count(ilStyleDefinition::getAllSkins()) ==1){ - $add_substyle_btn->setDisabled(true); - } - $this->toolbar->addButtonInstance($add_substyle_btn); - - $this->toolbar->addSeparator(); - } - - // from styles selector - $si = new ilSelectInputGUI($this->lng->txt("sty_move_user_styles").": ".$this->lng->txt("sty_from"), "from_style"); - - $options = array(); - foreach(ilStyleDefinition::getAllSkinStyles() as $id => $skin_style) { - if(!$skin_style['substyle_of']){ - $options[$id] = $skin_style['title']; - } - } - $si->setOptions($options + array("other" => $this->lng->txt("other"))); - - $this->toolbar->addInputItem($si, true); - - // from styles selector - $si = new ilSelectInputGUI($this->lng->txt("sty_to"), "to_style"); - $si->setOptions($options); - $this->toolbar->addInputItem($si, true); - // Add Button for adding skins - $move_skin_btn = ilSubmitButton::getInstance(); - $move_skin_btn->setCaption($this->lng->txt("sty_move_style"),false); - $this->toolbar->addButtonInstance($move_skin_btn); - $this->toolbar->setFormAction($this->ctrl->getLinkTarget($this, 'moveUserStyles')); - - $table = new ilSystemStylesTableGUI($this, "edit"); - $table->addActions($this->isManagementEnabled()); - $this->tpl->setContent($table->getHTML()); - - } - - /** - * Move user styles - */ - function moveUserStyles() - { - $to = explode(":", $_POST["to_style"]); - - if ($_POST["from_style"] == "other") - { - // get all user assigned styles - $all_user_styles = ilObjUser::_getAllUserAssignedStyles(); - - // move users that are not assigned to - // currently existing style - foreach($all_user_styles as $style) - { - if (!ilStyleDefinition::styleExists($style)) - { - $style_arr = explode(":", $style); - ilObjUser::_moveUsersToStyle($style_arr[0],$style_arr[1],$to[0],$to[1]); - } - } - } - else - { - $from = explode(":", $_POST["from_style"]); - ilObjUser::_moveUsersToStyle($from[0],$from[1],$to[0],$to[1]); - } - - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this , "edit"); - } - - - /** - * Save skin and style settings - */ - function saveStyleSettings() - { - $message_stack = new ilSystemStyleMessageStack(); - - if($this->checkStyleSettings($message_stack)){ - $all_styles = ilStyleDefinition::getAllSkinStyles(); - foreach ($all_styles as $st) - { - if (!isset($_POST["st_act"][$st["id"]])) - { - ilSystemStyleSettings::_deactivateStyle($st["template_id"], $st["style_id"]); - } - else - { - ilSystemStyleSettings::_activateStyle($st["template_id"], $st["style_id"]); - } - } - - //set default skin and style - if ($_POST["default_skin_style"] != "") - { - $sknst = explode(":", $_POST["default_skin_style"]); - ilSystemStyleSettings::setCurrentDefaultStyle($sknst[0],$sknst[1]); - } - $message_stack->addMessage(new ilSystemStyleMessage($this->lng->txt("msg_obj_modified"),ilSystemStyleMessage::TYPE_SUCCESS)); - } - $message_stack->sendMessages(true); - $this->ctrl->redirect($this , "edit"); - } - - /** - * @param ilSystemStyleMessageStack $message_stack - * @return bool - */ - protected function checkStyleSettings(ilSystemStyleMessageStack $message_stack){ - - $passed = true; - - if (count($_POST["st_act"]) < 1) - { - $passed = false; - $message_stack->addMessage(new ilSystemStyleMessage($this->lng->txt("at_least_one_style"),ilSystemStyleMessage::TYPE_ERROR)); - } - - if (!isset($_POST["st_act"][$_POST["default_skin_style"]])) - { - $passed = false; - $message_stack->addMessage(new ilSystemStyleMessage($this->lng->txt("cant_deactivate_default_style"),ilSystemStyleMessage::TYPE_ERROR)); - } - - // check if a style should be deactivated, that still has - // a user assigned to - $all_styles = ilStyleDefinition::getAllSkinStyles(); - - foreach ($all_styles as $st) - { - if (!isset($_POST["st_act"][$st["id"]])) - { - if (ilObjUser::_getNumberOfUsersForStyle($st["template_id"], $st["style_id"]) > 0) - { - $passed = false; - $message_stack->addMessage(new ilSystemStyleMessage($st["style_name"].": ".$this->lng->txt("cant_deactivate_if_users_assigned"),ilSystemStyleMessage::TYPE_ERROR)); - } - } - } - return $passed; - } - - - /** - * create - */ - protected function addSystemStyle() - { - $this->addSystemStyleForms(); - } - - - protected function saveNewSystemStyle(){ - $form = $this->createSystemStyleForm(); - - if ($form->checkInput() ) - { - $message_stack = new ilSystemStyleMessageStack(); - if(ilStyleDefinition::skinExists($_POST["skin_id"])){ - ilUtil::sendFailure($this->lng->txt("skin_id_exists")); - } - else{ - try{ - $skin = new ilSkinXML($_POST["skin_id"],$_POST["skin_name"]); - $style = new ilSkinStyleXML($_POST["style_id"],$_POST["style_name"]); - $skin->addStyle($style); - $container = new ilSystemStyleSkinContainer($skin); - $container->create($message_stack); - $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI','skin_id',$skin->getId()); - $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI','style_id',$style->getId()); - if($message_stack->hasMessages()){ - $message_stack->sendMessages(true); - }else{ - ilUtil::sendSuccess($this->lng->txt("msg_sys_style_created"), true); - } - $this->ctrl->redirectByClass("ilSystemStyleSettingsGUI"); - }catch(ilSystemStyleException $e){ - $message_stack->addMessage(new ilSystemStyleMessage($e->getMessage(),ilSystemStyleMessage::TYPE_ERROR)); - } - } - $message_stack->sendMessages(); - } - - // display only this form to correct input - $form->setValuesByPost(); - $this->tpl->setContent($form->getHTML()); - } - - /** - * create - */ - protected function addSystemStyleForms() - { - global $DIC; - - $DIC->tabs()->clearTargets(); - /** - * Since clearTargets also clears the help screen ids - */ - $DIC->help()->setScreenIdComponent("sty"); - $DIC->help()->setScreenId("system_styles"); - $DIC->help()->setSubScreenId("create"); - - $forms = array(); - - $forms[] = $this->createSystemStyleForm(); - $forms[] = $this->importSystemStyleForm(); - $forms[] = $this->cloneSystemStyleForm(); - - $this->tpl->setContent($this->getCreationFormsHTML($forms)); - } - - /** - * @return ilPropertyFormGUI - */ - protected function createSystemStyleForm(){ - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - $form->setTitle($this->lng->txt("sty_create_new_system_style")); - - $ti = new ilTextInputGUI($this->lng->txt("skin_id"), "skin_id"); - $ti->setInfo($this->lng->txt("skin_id_description")); - $ti->setMaxLength(128); - $ti->setSize(40); - $ti->setRequired(true); - $form->addItem($ti); - - $ti = new ilTextInputGUI($this->lng->txt("skin_name"), "skin_name"); - $ti->setInfo($this->lng->txt("skin_name_description")); - $ti->setMaxLength(128); - $ti->setSize(40); - $ti->setRequired(true); - $form->addItem($ti); - - $ti = new ilTextInputGUI($this->lng->txt("style_id"), "style_id"); - $ti->setInfo($this->lng->txt("style_id_description")); - $ti->setMaxLength(128); - $ti->setSize(40); - $ti->setRequired(true); - $form->addItem($ti); - - $ti = new ilTextInputGUI($this->lng->txt("style_name"), "style_name"); - $ti->setInfo($this->lng->txt("style_name_description")); - $ti->setMaxLength(128); - $ti->setSize(40); - $ti->setRequired(true); - $form->addItem($ti); - - $form->addCommandButton("saveNewSystemStyle", $this->lng->txt("save")); - $form->addCommandButton("cancel", $this->lng->txt("cancel")); - - return $form; - } - - /** - * @return ilPropertyFormGUI - */ - protected function importSystemStyleForm(){ - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - $form->setTitle($this->lng->txt("sty_import_system_style")); - - // title - $file_input = new ilFileInputGUI($this->lng->txt("import_file"), "importfile"); - $file_input->setRequired(true); - $file_input->setSuffixes(array("zip")); - $form->addItem($file_input); - - $form->addCommandButton("importStyle", $this->lng->txt("import")); - $form->addCommandButton("cancel", $this->lng->txt("cancel")); - - return $form; - } - - /** - * @return ilPropertyFormGUI - */ - protected function cloneSystemStyleForm(){ - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - $form->setTitle($this->lng->txt("sty_copy_other_system_style")); - - // source - $ti = new ilSelectInputGUI($this->lng->txt("sty_source"), "source_style"); - $ti->setRequired(true); - $styles = ilStyleDefinition::getAllSkinStyles(); - $options = array(); - foreach($styles as $id => $style){ - $system_style_conf = new ilSystemStyleConfig(); - if($style["skin_id"]!=$system_style_conf->getDefaultSkinId()){ - $options[$id] = $style['title']; - } - } - $ti->setOptions($options); - - $form->addItem($ti); - - $form->addCommandButton("copyStyle", $this->lng->txt("copy")); - $form->addCommandButton("cancel", $this->lng->txt("cancel")); - - return $form; - } - - /** - * @param array $a_forms - * @return string - */ - protected function getCreationFormsHTML(array $a_forms) - { - include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); - - $acc = new ilAccordionGUI(); - $acc->setBehaviour(ilAccordionGUI::FIRST_OPEN); - $cnt = 1; - foreach ($a_forms as $form_type => $cf) - { - /** - * @var ilPropertyFormGUI $cf - */ - $htpl = new ilTemplate("tpl.creation_acc_head.html", true, true, "Services/Object"); - - // using custom form titles (used for repository plugins) - $form_title = ""; - if(method_exists($this, "getCreationFormTitle")) - { - $form_title = $this->getCreationFormTitle($form_type); - } - if(!$form_title) - { - $form_title = $cf->getTitle(); - } - - // move title from form to accordion - $htpl->setVariable("TITLE", $this->lng->txt("option")." ".$cnt.": ". - $form_title); - $cf->setTitle(null); - $cf->setTitleIcon(null); - $cf->setTableWidth("100%"); - - $acc->addItem($htpl->get(), $cf->getHTML()); - - $cnt++; - } - - return "
                  ".$acc->getHTML()."
                  "; - } - - protected function copyStyle(){ - $message_stack = new ilSystemStyleMessageStack(); - - $imploded_skin_style_id = explode(":", $_POST['source_style']); - $skin_id = $imploded_skin_style_id[0]; - $style_id = $imploded_skin_style_id[1]; - - try{ - $container = ilSystemStyleSkinContainer::generateFromId($skin_id,$message_stack); - $new_container = $container->copy(); - $message_stack->prependMessage(new ilSystemStyleMessage($this->lng->txt("style_copied"),ilSystemStyleMessage::TYPE_SUCCESS)); - $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI','skin_id',$new_container->getSkin()->getId()); - $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI','style_id',$new_container->getSkin()->getStyle($style_id)->getId()); - }catch(Exception $e){ - $message_stack->addMessage(new ilSystemStyleMessage($e->getMessage(),ilSystemStyleMessage::TYPE_ERROR)); - } - - - $message_stack->sendMessages(true); - $this->ctrl->redirectByClass("ilSystemStyleSettingsGUI"); - } - - protected function deleteStyle(){ - $skin_id = $_GET["skin_id"]; - $style_id = $_GET["style_id"]; - $message_stack = new ilSystemStyleMessageStack(); - - if($this->checkDeletable($skin_id,$style_id,$message_stack)){ - $delete_form_table = new ilSystemStyleDeleteGUI(); - $container = ilSystemStyleSkinContainer::generateFromId($skin_id); - $delete_form_table->addStyle($container->getSkin(),$container->getSkin()->getStyle($style_id)); - $this->tpl->setContent($delete_form_table->getDeleteStyleFormHTML()); - }else{ - $message_stack->prependMessage(new ilSystemStyleMessage($this->lng->txt("style_not_deleted"),ilSystemStyleMessage::TYPE_ERROR)); - $message_stack->sendMessages(true); - $this->edit(); - } - - - } - protected function deleteStyles(){ - $delete_form_table = new ilSystemStyleDeleteGUI(); - $message_stack = new ilSystemStyleMessageStack(); - - $all_deletable = true; - foreach($_POST['id'] as $skin_style_id){ - $imploded_skin_style_id = explode(":", $skin_style_id); - $skin_id = $imploded_skin_style_id[0]; - $style_id = $imploded_skin_style_id[1]; - if(!$this->checkDeletable($skin_id,$style_id,$message_stack)){ - $all_deletable = false; - } - } - if($all_deletable){ - foreach($_POST['id'] as $skin_style_id){ - $imploded_skin_style_id = explode(":", $skin_style_id); - $skin_id = $imploded_skin_style_id[0]; - $style_id = $imploded_skin_style_id[1]; - $container = ilSystemStyleSkinContainer::generateFromId($skin_id); - $delete_form_table->addStyle($container->getSkin(),$container->getSkin()->getStyle($style_id)); - } - $this->tpl->setContent($delete_form_table->getDeleteStyleFormHTML()); - }else{ - $message_stack->prependMessage(new ilSystemStyleMessage($this->lng->txt("styles_not_deleted"),ilSystemStyleMessage::TYPE_ERROR)); - $message_stack->sendMessages(true); - $this->edit(); - } - - - } - - /** - * @param $skin_id - * @param $style_id - * @param ilSystemStyleMessageStack $message_stack - * @return bool - * @throws ilSystemStyleException - */ - protected function checkDeletable($skin_id,$style_id, ilSystemStyleMessageStack $message_stack){ - $passed = true; - if (ilObjUser::_getNumberOfUsersForStyle($skin_id, $style_id) > 0) - { - $message_stack->addMessage(new ilSystemStyleMessage($style_id.": ".$this->lng->txt("cant_delete_if_users_assigned"),ilSystemStyleMessage::TYPE_ERROR)); - $passed = false; - } - if (ilSystemStyleSettings::_lookupActivatedStyle($skin_id, $style_id) > 0) - { - $message_stack->addMessage(new ilSystemStyleMessage($style_id.": ".$this->lng->txt("cant_delete_activated_style"),ilSystemStyleMessage::TYPE_ERROR)); - $passed = false; - } - if (ilSystemStyleSettings::getCurrentDefaultSkin() == $skin_id && ilSystemStyleSettings::getCurrentDefaultSkin() == $style_id) - { - $message_stack->addMessage(new ilSystemStyleMessage($style_id.": ".$this->lng->txt("cant_delete_default_style"),ilSystemStyleMessage::TYPE_ERROR)); - $passed = false; - } - - if (ilSystemStyleSkinContainer::generateFromId($skin_id)->getSkin()->getSubstylesOfStyle($style_id)) - { - $message_stack->addMessage(new ilSystemStyleMessage($style_id.": ".$this->lng->txt("cant_delete_style_with_substyles"),ilSystemStyleMessage::TYPE_ERROR)); - $passed = false; - } - return $passed; - } - - protected function confirmDelete(){ - $message_stack = new ilSystemStyleMessageStack(); - - foreach($_POST as $key => $skin_style_id){ - if(is_string($skin_style_id) && strpos($key, 'style') !== false){ - try{ - $imploded_skin_style_id = explode(":", $skin_style_id); - $container = ilSystemStyleSkinContainer::generateFromId($imploded_skin_style_id[0],$message_stack); - $syle = $container->getSkin()->getStyle($imploded_skin_style_id[1]); - $container->deleteStyle($syle); - if(!$container->getSkin()->hasStyles()){ - $container->delete(); - } - }catch(Exception $e){ - $message_stack->addMessage(new ilSystemStyleMessage($e->getMessage(),ilSystemStyleMessage::TYPE_ERROR)); - } - - } - } - $message_stack->sendMessages(true); - $this->ctrl->redirect($this); - } - - /** - * - */ - protected function importStyle(){ - $form = $this->importSystemStyleForm(); - - if ($form->checkInput() ) - { - $message_stack = new ilSystemStyleMessageStack(); - $imported_container = ilSystemStyleSkinContainer::import($_POST['importfile']['tmp_name'],$_POST['importfile']['name'],$message_stack); - $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI','skin_id',$imported_container->getSkin()->getId()); - $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI','style_id',$imported_container->getSkin()->getDefaultStyle()->getId()); - $message_stack->addMessage(new ilSystemStyleMessage($this->lng->txt("style_imported") . " " . $imported_container->getSkinDirectory(),ilSystemStyleMessage::TYPE_SUCCESS)); - - $message_stack->sendMessages(true); - $this->ctrl->redirectByClass("ilSystemStyleSettingsGUI"); - } - - // display only this form to correct input - $form->setValuesByPost(); - $this->tpl->setContent($form->getHTML()); - } - protected function export(){ - $skin_id = $_GET["skin_id"]; - $container = ilSystemStyleSkinContainer::generateFromId($skin_id); - try{ - $container->export(); - }catch(Exception $e){ - ilUtil::sendFailure($this->lng->txt("zip_export_failed")." ".$e->getMessage()); - } - - } - - - /** - * - */ - protected function addSubStyle() - { - global $DIC; - - $DIC->tabs()->clearTargets(); - /** - * Since clearTargets also clears the help screen ids - */ - $DIC->help()->setScreenIdComponent("sty"); - $DIC->help()->setScreenId("system_styles"); - $DIC->help()->setSubScreenId("create_sub"); - - $form = $this->addSubStyleForms(); - - $this->tpl->setContent($form->getHTML()); - - } - - /** - * @return ilPropertyFormGUI - */ - protected function addSubStyleForms( ) - { - $form = new ilPropertyFormGUI(); - $form->setFormAction($this->ctrl->getFormAction($this)); - $form->setTitle($this->lng->txt("sty_create_new_system_sub_style")); - - - $ti = new ilTextInputGUI($this->lng->txt("sub_style_id"), "sub_style_id"); - $ti->setInfo($this->lng->txt("sub_style_id_description")); - $ti->setMaxLength(128); - $ti->setSize(40); - $ti->setRequired(true); - $form->addItem($ti); - - $ti = new ilTextInputGUI($this->lng->txt("sub_style_name"), "sub_style_name"); - $ti->setInfo($this->lng->txt("sub_style_name_description")); - $ti->setMaxLength(128); - $ti->setSize(40); - $ti->setRequired(true); - $form->addItem($ti); - - // source - $ti = new ilSelectInputGUI($this->lng->txt("parent"), "parent_style"); - $ti->setRequired(true); - $ti->setInfo($this->lng->txt("sub_style_parent_style_description")); - $styles = ilStyleDefinition::getAllSkinStyles(); - $options = array(); - foreach($styles as $id => $style){ - $system_style_conf = new ilSystemStyleConfig(); - if($style["skin_id"]!=$system_style_conf->getDefaultSkinId() && !$style["substyle_of"]){ - $options[$id] = $style['title']; - } - } - $ti->setOptions($options); - - $form->addItem($ti); - $form->addCommandButton("saveNewSubStyle", $this->lng->txt("save")); - $form->addCommandButton("cancel", $this->lng->txt("cancel")); - - return $form; - } - - protected function saveNewSubStyle(){ - $form = $this->addSubStyleForms(); - - if ($form->checkInput() ) - { - try{ - $imploded_parent_skin_style_id = explode(":", $_POST['parent_style']); - $parent_skin_id = $imploded_parent_skin_style_id[0]; - $parent_style_id = $imploded_parent_skin_style_id[1]; - - $container = ilSystemStyleSkinContainer::generateFromId($parent_skin_id); - - if(array_key_exists($_POST['sub_style_id'],$container->getSkin()->getSubstylesOfStyle($parent_style_id))){ - throw new ilSystemStyleException(ilSystemStyleException::SUBSTYLE_ASSIGNMENT_EXISTS,$_POST['sub_style_id']); + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ILIAS\DI\Container + */ + protected $DIC; + + /** + * @var int + */ + protected $ref_id; + + /** + * @var bool + */ + protected $read_only = true; + + /** + * @var bool + */ + protected $management_enabled = false; + + + /** + * Constructor + */ + public function __construct($read_only, $management_enabled) + { + global $DIC; + + $this->ilias = $DIC["ilias"]; + $this->dic = $DIC; + $this->ctrl = $DIC->ctrl(); + $this->toolbar = $DIC->toolbar(); + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + + $this->ref_id = (int) $_GET["ref_id"]; + + $this->setReadOnly($read_only); + $this->setManagementEnabled($management_enabled); + } + + /** + * Execute command + */ + public function executeCommand() + { + $cmd = $this->ctrl->getCmd(); + + if ($cmd == "") { + $cmd = $this->isReadOnly()?"view":"edit"; + } + + + switch ($cmd) { + case "addSystemStyle": + case "addSubStyle": + case "saveNewSystemStyle": + case "saveNewSubStyle": + case "copyStyle": + case "importStyle": + case "deleteStyles": + case "deleteStyle": + case "confirmDelete": + if (!$this->isManagementEnabled()) { + throw new ilObjectException($this->lng->txt("permission_denied")); + } + $this->$cmd(); + return; + case "cancel": + case "edit": + case "export": + case "moveUserStyles": + case "saveStyleSettings": + if ($this->isReadOnly()) { + throw new ilObjectException($this->lng->txt("permission_denied")); + } + $this->$cmd(); + return; + case "view": + $this->$cmd(); + return; + + } + } + + protected function view() + { + $table = new ilSystemStylesTableGUI($this, "edit", true); + $this->tpl->setContent($table->getHTML()); + } + + protected function cancel() + { + $this->edit(); + } + /** + * Edit + */ + public function edit() + { + if ($this->isManagementEnabled()) { + // Add Button for adding skins + $add_skin_btn = ilLinkButton::getInstance(); + $add_skin_btn->setCaption($this->lng->txt("add_system_style"), false); + $add_skin_btn->setUrl($this->ctrl->getLinkTarget($this, 'addSystemStyle')); + $this->toolbar->addButtonInstance($add_skin_btn); + + // Add Button for adding skins + $add_substyle_btn = ilLinkButton::getInstance(); + $add_substyle_btn->setCaption($this->lng->txt("add_substyle"), false); + $add_substyle_btn->setUrl($this->ctrl->getLinkTarget($this, 'addSubStyle')); + if (count(ilStyleDefinition::getAllSkins()) ==1) { + $add_substyle_btn->setDisabled(true); + } + $this->toolbar->addButtonInstance($add_substyle_btn); + + $this->toolbar->addSeparator(); + } + + // from styles selector + $si = new ilSelectInputGUI($this->lng->txt("sty_move_user_styles") . ": " . $this->lng->txt("sty_from"), "from_style"); + + $options = array(); + foreach (ilStyleDefinition::getAllSkinStyles() as $id => $skin_style) { + if (!$skin_style['substyle_of']) { + $options[$id] = $skin_style['title']; + } + } + $si->setOptions($options + array("other" => $this->lng->txt("other"))); + + $this->toolbar->addInputItem($si, true); + + // from styles selector + $si = new ilSelectInputGUI($this->lng->txt("sty_to"), "to_style"); + $si->setOptions($options); + $this->toolbar->addInputItem($si, true); + // Add Button for adding skins + $move_skin_btn = ilSubmitButton::getInstance(); + $move_skin_btn->setCaption($this->lng->txt("sty_move_style"), false); + $this->toolbar->addButtonInstance($move_skin_btn); + $this->toolbar->setFormAction($this->ctrl->getLinkTarget($this, 'moveUserStyles')); + + $table = new ilSystemStylesTableGUI($this, "edit"); + $table->addActions($this->isManagementEnabled()); + $this->tpl->setContent($table->getHTML()); + } + + /** + * Move user styles + */ + public function moveUserStyles() + { + $to = explode(":", $_POST["to_style"]); + + if ($_POST["from_style"] == "other") { + // get all user assigned styles + $all_user_styles = ilObjUser::_getAllUserAssignedStyles(); + + // move users that are not assigned to + // currently existing style + foreach ($all_user_styles as $style) { + if (!ilStyleDefinition::styleExists($style)) { + $style_arr = explode(":", $style); + ilObjUser::_moveUsersToStyle($style_arr[0], $style_arr[1], $to[0], $to[1]); + } + } + } else { + $from = explode(":", $_POST["from_style"]); + ilObjUser::_moveUsersToStyle($from[0], $from[1], $to[0], $to[1]); + } + + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "edit"); + } + + + /** + * Save skin and style settings + */ + public function saveStyleSettings() + { + $message_stack = new ilSystemStyleMessageStack(); + + if ($this->checkStyleSettings($message_stack)) { + $all_styles = ilStyleDefinition::getAllSkinStyles(); + foreach ($all_styles as $st) { + if (!isset($_POST["st_act"][$st["id"]])) { + ilSystemStyleSettings::_deactivateStyle($st["template_id"], $st["style_id"]); + } else { + ilSystemStyleSettings::_activateStyle($st["template_id"], $st["style_id"]); + } + } + + //set default skin and style + if ($_POST["default_skin_style"] != "") { + $sknst = explode(":", $_POST["default_skin_style"]); + ilSystemStyleSettings::setCurrentDefaultStyle($sknst[0], $sknst[1]); + } + $message_stack->addMessage(new ilSystemStyleMessage($this->lng->txt("msg_obj_modified"), ilSystemStyleMessage::TYPE_SUCCESS)); + } + $message_stack->sendMessages(true); + $this->ctrl->redirect($this, "edit"); + } + + /** + * @param ilSystemStyleMessageStack $message_stack + * @return bool + */ + protected function checkStyleSettings(ilSystemStyleMessageStack $message_stack) + { + $passed = true; + + if (count($_POST["st_act"]) < 1) { + $passed = false; + $message_stack->addMessage(new ilSystemStyleMessage($this->lng->txt("at_least_one_style"), ilSystemStyleMessage::TYPE_ERROR)); + } + + if (!isset($_POST["st_act"][$_POST["default_skin_style"]])) { + $passed = false; + $message_stack->addMessage(new ilSystemStyleMessage($this->lng->txt("cant_deactivate_default_style"), ilSystemStyleMessage::TYPE_ERROR)); + } + + // check if a style should be deactivated, that still has + // a user assigned to + $all_styles = ilStyleDefinition::getAllSkinStyles(); + + foreach ($all_styles as $st) { + if (!isset($_POST["st_act"][$st["id"]])) { + if (ilObjUser::_getNumberOfUsersForStyle($st["template_id"], $st["style_id"]) > 0) { + $passed = false; + $message_stack->addMessage(new ilSystemStyleMessage($st["style_name"] . ": " . $this->lng->txt("cant_deactivate_if_users_assigned"), ilSystemStyleMessage::TYPE_ERROR)); + } + } + } + return $passed; + } + + + /** + * create + */ + protected function addSystemStyle() + { + $this->addSystemStyleForms(); + } + + + protected function saveNewSystemStyle() + { + $form = $this->createSystemStyleForm(); + + if ($form->checkInput()) { + $message_stack = new ilSystemStyleMessageStack(); + if (ilStyleDefinition::skinExists($_POST["skin_id"])) { + ilUtil::sendFailure($this->lng->txt("skin_id_exists")); + } else { + try { + $skin = new ilSkinXML($_POST["skin_id"], $_POST["skin_name"]); + $style = new ilSkinStyleXML($_POST["style_id"], $_POST["style_name"]); + $skin->addStyle($style); + $container = new ilSystemStyleSkinContainer($skin); + $container->create($message_stack); + $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI', 'skin_id', $skin->getId()); + $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI', 'style_id', $style->getId()); + if ($message_stack->hasMessages()) { + $message_stack->sendMessages(true); + } else { + ilUtil::sendSuccess($this->lng->txt("msg_sys_style_created"), true); + } + $this->ctrl->redirectByClass("ilSystemStyleSettingsGUI"); + } catch (ilSystemStyleException $e) { + $message_stack->addMessage(new ilSystemStyleMessage($e->getMessage(), ilSystemStyleMessage::TYPE_ERROR)); + } + } + $message_stack->sendMessages(); + } + + // display only this form to correct input + $form->setValuesByPost(); + $this->tpl->setContent($form->getHTML()); + } + + /** + * create + */ + protected function addSystemStyleForms() + { + global $DIC; + + $DIC->tabs()->clearTargets(); + /** + * Since clearTargets also clears the help screen ids + */ + $DIC->help()->setScreenIdComponent("sty"); + $DIC->help()->setScreenId("system_styles"); + $DIC->help()->setSubScreenId("create"); + + $forms = array(); + + $forms[] = $this->createSystemStyleForm(); + $forms[] = $this->importSystemStyleForm(); + $forms[] = $this->cloneSystemStyleForm(); + + $this->tpl->setContent($this->getCreationFormsHTML($forms)); + } + + /** + * @return ilPropertyFormGUI + */ + protected function createSystemStyleForm() + { + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this)); + $form->setTitle($this->lng->txt("sty_create_new_system_style")); + + $ti = new ilTextInputGUI($this->lng->txt("skin_id"), "skin_id"); + $ti->setInfo($this->lng->txt("skin_id_description")); + $ti->setMaxLength(128); + $ti->setSize(40); + $ti->setRequired(true); + $form->addItem($ti); + + $ti = new ilTextInputGUI($this->lng->txt("skin_name"), "skin_name"); + $ti->setInfo($this->lng->txt("skin_name_description")); + $ti->setMaxLength(128); + $ti->setSize(40); + $ti->setRequired(true); + $form->addItem($ti); + + $ti = new ilTextInputGUI($this->lng->txt("style_id"), "style_id"); + $ti->setInfo($this->lng->txt("style_id_description")); + $ti->setMaxLength(128); + $ti->setSize(40); + $ti->setRequired(true); + $form->addItem($ti); + + $ti = new ilTextInputGUI($this->lng->txt("style_name"), "style_name"); + $ti->setInfo($this->lng->txt("style_name_description")); + $ti->setMaxLength(128); + $ti->setSize(40); + $ti->setRequired(true); + $form->addItem($ti); + + $form->addCommandButton("saveNewSystemStyle", $this->lng->txt("save")); + $form->addCommandButton("cancel", $this->lng->txt("cancel")); + + return $form; + } + + /** + * @return ilPropertyFormGUI + */ + protected function importSystemStyleForm() + { + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this)); + $form->setTitle($this->lng->txt("sty_import_system_style")); + + // title + $file_input = new ilFileInputGUI($this->lng->txt("import_file"), "importfile"); + $file_input->setRequired(true); + $file_input->setSuffixes(array("zip")); + $form->addItem($file_input); + + $form->addCommandButton("importStyle", $this->lng->txt("import")); + $form->addCommandButton("cancel", $this->lng->txt("cancel")); + + return $form; + } + + /** + * @return ilPropertyFormGUI + */ + protected function cloneSystemStyleForm() + { + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this)); + $form->setTitle($this->lng->txt("sty_copy_other_system_style")); + + // source + $ti = new ilSelectInputGUI($this->lng->txt("sty_source"), "source_style"); + $ti->setRequired(true); + $styles = ilStyleDefinition::getAllSkinStyles(); + $options = array(); + foreach ($styles as $id => $style) { + $system_style_conf = new ilSystemStyleConfig(); + if ($style["skin_id"]!=$system_style_conf->getDefaultSkinId()) { + $options[$id] = $style['title']; + } + } + $ti->setOptions($options); + + $form->addItem($ti); + + $form->addCommandButton("copyStyle", $this->lng->txt("copy")); + $form->addCommandButton("cancel", $this->lng->txt("cancel")); + + return $form; + } + + /** + * @param array $a_forms + * @return string + */ + protected function getCreationFormsHTML(array $a_forms) + { + include_once("./Services/Accordion/classes/class.ilAccordionGUI.php"); + + $acc = new ilAccordionGUI(); + $acc->setBehaviour(ilAccordionGUI::FIRST_OPEN); + $cnt = 1; + foreach ($a_forms as $form_type => $cf) { + /** + * @var ilPropertyFormGUI $cf + */ + $htpl = new ilTemplate("tpl.creation_acc_head.html", true, true, "Services/Object"); + + // using custom form titles (used for repository plugins) + $form_title = ""; + if (method_exists($this, "getCreationFormTitle")) { + $form_title = $this->getCreationFormTitle($form_type); + } + if (!$form_title) { + $form_title = $cf->getTitle(); + } + + // move title from form to accordion + $htpl->setVariable("TITLE", $this->lng->txt("option") . " " . $cnt . ": " . + $form_title); + $cf->setTitle(null); + $cf->setTitleIcon(null); + $cf->setTableWidth("100%"); + + $acc->addItem($htpl->get(), $cf->getHTML()); + + $cnt++; + } + + return "
                  " . $acc->getHTML() . "
                  "; + } + + protected function copyStyle() + { + $message_stack = new ilSystemStyleMessageStack(); + + $imploded_skin_style_id = explode(":", $_POST['source_style']); + $skin_id = $imploded_skin_style_id[0]; + $style_id = $imploded_skin_style_id[1]; + + try { + $container = ilSystemStyleSkinContainer::generateFromId($skin_id, $message_stack); + $new_container = $container->copy(); + $message_stack->prependMessage(new ilSystemStyleMessage($this->lng->txt("style_copied"), ilSystemStyleMessage::TYPE_SUCCESS)); + $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI', 'skin_id', $new_container->getSkin()->getId()); + $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI', 'style_id', $new_container->getSkin()->getStyle($style_id)->getId()); + } catch (Exception $e) { + $message_stack->addMessage(new ilSystemStyleMessage($e->getMessage(), ilSystemStyleMessage::TYPE_ERROR)); + } + + + $message_stack->sendMessages(true); + $this->ctrl->redirectByClass("ilSystemStyleSettingsGUI"); + } + + protected function deleteStyle() + { + $skin_id = $_GET["skin_id"]; + $style_id = $_GET["style_id"]; + $message_stack = new ilSystemStyleMessageStack(); + + if ($this->checkDeletable($skin_id, $style_id, $message_stack)) { + $delete_form_table = new ilSystemStyleDeleteGUI(); + $container = ilSystemStyleSkinContainer::generateFromId($skin_id); + $delete_form_table->addStyle($container->getSkin(), $container->getSkin()->getStyle($style_id)); + $this->tpl->setContent($delete_form_table->getDeleteStyleFormHTML()); + } else { + $message_stack->prependMessage(new ilSystemStyleMessage($this->lng->txt("style_not_deleted"), ilSystemStyleMessage::TYPE_ERROR)); + $message_stack->sendMessages(true); + $this->edit(); + } + } + protected function deleteStyles() + { + $delete_form_table = new ilSystemStyleDeleteGUI(); + $message_stack = new ilSystemStyleMessageStack(); + + $all_deletable = true; + foreach ($_POST['id'] as $skin_style_id) { + $imploded_skin_style_id = explode(":", $skin_style_id); + $skin_id = $imploded_skin_style_id[0]; + $style_id = $imploded_skin_style_id[1]; + if (!$this->checkDeletable($skin_id, $style_id, $message_stack)) { + $all_deletable = false; + } + } + if ($all_deletable) { + foreach ($_POST['id'] as $skin_style_id) { + $imploded_skin_style_id = explode(":", $skin_style_id); + $skin_id = $imploded_skin_style_id[0]; + $style_id = $imploded_skin_style_id[1]; + $container = ilSystemStyleSkinContainer::generateFromId($skin_id); + $delete_form_table->addStyle($container->getSkin(), $container->getSkin()->getStyle($style_id)); + } + $this->tpl->setContent($delete_form_table->getDeleteStyleFormHTML()); + } else { + $message_stack->prependMessage(new ilSystemStyleMessage($this->lng->txt("styles_not_deleted"), ilSystemStyleMessage::TYPE_ERROR)); + $message_stack->sendMessages(true); + $this->edit(); + } + } + + /** + * @param $skin_id + * @param $style_id + * @param ilSystemStyleMessageStack $message_stack + * @return bool + * @throws ilSystemStyleException + */ + protected function checkDeletable($skin_id, $style_id, ilSystemStyleMessageStack $message_stack) + { + $passed = true; + if (ilObjUser::_getNumberOfUsersForStyle($skin_id, $style_id) > 0) { + $message_stack->addMessage(new ilSystemStyleMessage($style_id . ": " . $this->lng->txt("cant_delete_if_users_assigned"), ilSystemStyleMessage::TYPE_ERROR)); + $passed = false; + } + if (ilSystemStyleSettings::_lookupActivatedStyle($skin_id, $style_id) > 0) { + $message_stack->addMessage(new ilSystemStyleMessage($style_id . ": " . $this->lng->txt("cant_delete_activated_style"), ilSystemStyleMessage::TYPE_ERROR)); + $passed = false; + } + if (ilSystemStyleSettings::getCurrentDefaultSkin() == $skin_id && ilSystemStyleSettings::getCurrentDefaultSkin() == $style_id) { + $message_stack->addMessage(new ilSystemStyleMessage($style_id . ": " . $this->lng->txt("cant_delete_default_style"), ilSystemStyleMessage::TYPE_ERROR)); + $passed = false; + } + + if (ilSystemStyleSkinContainer::generateFromId($skin_id)->getSkin()->getSubstylesOfStyle($style_id)) { + $message_stack->addMessage(new ilSystemStyleMessage($style_id . ": " . $this->lng->txt("cant_delete_style_with_substyles"), ilSystemStyleMessage::TYPE_ERROR)); + $passed = false; + } + return $passed; + } + + protected function confirmDelete() + { + $message_stack = new ilSystemStyleMessageStack(); + + foreach ($_POST as $key => $skin_style_id) { + if (is_string($skin_style_id) && strpos($key, 'style') !== false) { + try { + $imploded_skin_style_id = explode(":", $skin_style_id); + $container = ilSystemStyleSkinContainer::generateFromId($imploded_skin_style_id[0], $message_stack); + $syle = $container->getSkin()->getStyle($imploded_skin_style_id[1]); + $container->deleteStyle($syle); + if (!$container->getSkin()->hasStyles()) { + $container->delete(); + } + } catch (Exception $e) { + $message_stack->addMessage(new ilSystemStyleMessage($e->getMessage(), ilSystemStyleMessage::TYPE_ERROR)); + } + } + } + $message_stack->sendMessages(true); + $this->ctrl->redirect($this); + } + + /** + * + */ + protected function importStyle() + { + $form = $this->importSystemStyleForm(); + + if ($form->checkInput()) { + $message_stack = new ilSystemStyleMessageStack(); + $imported_container = ilSystemStyleSkinContainer::import($_POST['importfile']['tmp_name'], $_POST['importfile']['name'], $message_stack); + $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI', 'skin_id', $imported_container->getSkin()->getId()); + $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI', 'style_id', $imported_container->getSkin()->getDefaultStyle()->getId()); + $message_stack->addMessage(new ilSystemStyleMessage($this->lng->txt("style_imported") . " " . $imported_container->getSkinDirectory(), ilSystemStyleMessage::TYPE_SUCCESS)); + + $message_stack->sendMessages(true); + $this->ctrl->redirectByClass("ilSystemStyleSettingsGUI"); + } + + // display only this form to correct input + $form->setValuesByPost(); + $this->tpl->setContent($form->getHTML()); + } + protected function export() + { + $skin_id = $_GET["skin_id"]; + $container = ilSystemStyleSkinContainer::generateFromId($skin_id); + try { + $container->export(); + } catch (Exception $e) { + ilUtil::sendFailure($this->lng->txt("zip_export_failed") . " " . $e->getMessage()); + } + } + + + /** + * + */ + protected function addSubStyle() + { + global $DIC; + + $DIC->tabs()->clearTargets(); + /** + * Since clearTargets also clears the help screen ids + */ + $DIC->help()->setScreenIdComponent("sty"); + $DIC->help()->setScreenId("system_styles"); + $DIC->help()->setSubScreenId("create_sub"); + + $form = $this->addSubStyleForms(); + + $this->tpl->setContent($form->getHTML()); + } + + /** + * @return ilPropertyFormGUI + */ + protected function addSubStyleForms() + { + $form = new ilPropertyFormGUI(); + $form->setFormAction($this->ctrl->getFormAction($this)); + $form->setTitle($this->lng->txt("sty_create_new_system_sub_style")); + + + $ti = new ilTextInputGUI($this->lng->txt("sub_style_id"), "sub_style_id"); + $ti->setInfo($this->lng->txt("sub_style_id_description")); + $ti->setMaxLength(128); + $ti->setSize(40); + $ti->setRequired(true); + $form->addItem($ti); + + $ti = new ilTextInputGUI($this->lng->txt("sub_style_name"), "sub_style_name"); + $ti->setInfo($this->lng->txt("sub_style_name_description")); + $ti->setMaxLength(128); + $ti->setSize(40); + $ti->setRequired(true); + $form->addItem($ti); + + // source + $ti = new ilSelectInputGUI($this->lng->txt("parent"), "parent_style"); + $ti->setRequired(true); + $ti->setInfo($this->lng->txt("sub_style_parent_style_description")); + $styles = ilStyleDefinition::getAllSkinStyles(); + $options = array(); + foreach ($styles as $id => $style) { + $system_style_conf = new ilSystemStyleConfig(); + if ($style["skin_id"]!=$system_style_conf->getDefaultSkinId() && !$style["substyle_of"]) { + $options[$id] = $style['title']; + } + } + $ti->setOptions($options); + + $form->addItem($ti); + $form->addCommandButton("saveNewSubStyle", $this->lng->txt("save")); + $form->addCommandButton("cancel", $this->lng->txt("cancel")); + + return $form; + } + + protected function saveNewSubStyle() + { + $form = $this->addSubStyleForms(); + + if ($form->checkInput()) { + try { + $imploded_parent_skin_style_id = explode(":", $_POST['parent_style']); + $parent_skin_id = $imploded_parent_skin_style_id[0]; + $parent_style_id = $imploded_parent_skin_style_id[1]; + + $container = ilSystemStyleSkinContainer::generateFromId($parent_skin_id); + + if (array_key_exists($_POST['sub_style_id'], $container->getSkin()->getSubstylesOfStyle($parent_style_id))) { + throw new ilSystemStyleException(ilSystemStyleException::SUBSTYLE_ASSIGNMENT_EXISTS, $_POST['sub_style_id']); } $sub_style_id = $_POST['sub_style_id']; @@ -746,51 +724,49 @@ class ilSystemStyleOverviewGUI $style->setSubstyleOf($parent_style_id); $container->addStyle($style); - $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI','skin_id',$parent_skin_id); - $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI','style_id',$sub_style_id); + $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI', 'skin_id', $parent_skin_id); + $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI', 'style_id', $sub_style_id); ilUtil::sendSuccess($this->lng->txt("msg_sub_style_created"), true); $this->ctrl->redirectByClass("ilSystemStyleSettingsGUI"); - }catch(ilSystemStyleException $e){ - ilUtil::sendFailure($e->getMessage(), true); - } - } - - // display only this form to correct input - $form->setValuesByPost(); - $this->tpl->setContent($form->getHTML()); - } - - /** - * @return boolean - */ - public function isReadOnly() - { - return $this->read_only; - } - - /** - * @param boolean $read_only - */ - public function setReadOnly($read_only) - { - $this->read_only = $read_only; - } - - /** - * @return boolean - */ - public function isManagementEnabled() - { - return $this->management_enabled; - } - - /** - * @param boolean $management_enabled - */ - public function setManagementEnabled($management_enabled) - { - $this->management_enabled = $management_enabled; - } - - -} \ No newline at end of file + } catch (ilSystemStyleException $e) { + ilUtil::sendFailure($e->getMessage(), true); + } + } + + // display only this form to correct input + $form->setValuesByPost(); + $this->tpl->setContent($form->getHTML()); + } + + /** + * @return boolean + */ + public function isReadOnly() + { + return $this->read_only; + } + + /** + * @param boolean $read_only + */ + public function setReadOnly($read_only) + { + $this->read_only = $read_only; + } + + /** + * @return boolean + */ + public function isManagementEnabled() + { + return $this->management_enabled; + } + + /** + * @param boolean $management_enabled + */ + public function setManagementEnabled($management_enabled) + { + $this->management_enabled = $management_enabled; + } +} diff --git a/Services/Style/System/classes/Overview/class.ilSystemStylesTableGUI.php b/Services/Style/System/classes/Overview/class.ilSystemStylesTableGUI.php index 837faa07eefef0efee5ce48dd3d4b7fbdbfed824..1dae55e8eacc9688b50c498b04e9bfe0f337d01a 100644 --- a/Services/Style/System/classes/Overview/class.ilSystemStylesTableGUI.php +++ b/Services/Style/System/classes/Overview/class.ilSystemStylesTableGUI.php @@ -17,306 +17,304 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilSystemStylesTableGUI extends ilTable2GUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var bool - */ - protected $with_actions = false; - - /** - * @var bool - */ - protected $management_enabled = false; - - /** - * @var bool - */ - protected $read_documentation = true; - - /** - * ilSystemStylesTableGUI constructor. - * @param int $a_parent_obj - * @param string $a_parent_cmd - */ - function __construct($a_parent_obj, $a_parent_cmd) - { - - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->getStyles(); - - $this->setLimit(9999); - $this->setTitle($this->lng->txt("manage_system_styles")); - $this->addColumn($this->lng->txt("")); - $this->addColumn($this->lng->txt("style_name"),"style_name"); - $this->addColumn($this->lng->txt("skin_name"),"skin_name"); - $this->addColumn($this->lng->txt("sty_substyle_of")); - $this->addColumn($this->lng->txt("scope")); - $this->addColumn($this->lng->txt("default")); - $this->addColumn($this->lng->txt("active")); - $this->addColumn($this->lng->txt("users"),"users"); - $this->setRowTemplate("tpl.sys_styles_row.html", "Services/Style/System"); - $this->setEnableHeader(true); - - - } - - /** - * @param $management_enabled - * @param bool|true $read_documentation - */ - public function addActions($management_enabled, $read_documentation = true){ - $this->setManagementEnabled($management_enabled); - $this->setReadDocumentation($read_documentation); - - $this->setFormAction($this->ctrl->getFormAction($this->getParentObject())); - $this->addCommandButton("saveStyleSettings", $this->lng->txt("save")); - $this->setRowTemplate("tpl.sys_styles_row_with_actions.html", "Services/Style/System"); - - if($read_documentation || $management_enabled){ - $this->setWithActions(true); - - $this->addColumn($this->lng->txt("actions")); - } - if($management_enabled){ - $this->addMultiCommand("deleteStyles",$this->lng->txt("delete")); - } - } - - /** - * - */ - function getStyles() - { - // get all user assigned styles - $all_user_styles = ilObjUser::_getAllUserAssignedStyles(); - - // output "other" row for all users, that are not assigned to - // any existing style - $users_missing_styles = 0; - foreach($all_user_styles as $skin_style_id) - { - $style_arr = explode(":", $skin_style_id); - if (!ilStyleDefinition::styleExists($style_arr[1])) - { - - $users_missing_styles += ilObjUser::_getNumberOfUsersForStyle($style_arr[0], $style_arr[1]); - } - } - $all_styles = ilStyleDefinition::getAllSkinStyles(); - if ($users_missing_styles > 0) - { - $all_styles["other"] = - array ( - "title" => $this->lng->txt("other"), - "id" => "other", - "template_id" => "", - "skin_id" => "other", - "style_id" => "", - "skin_name" => "other", - "style_name" => "", - "users" => $users_missing_styles - ); - } - - $this->setData($all_styles); - } - - - /** - * @param array $a_set - */ - protected function fillRow($a_set) - { - global $DIC; - - $this->tpl->setVariable("STYLE_NAME", $a_set["style_name"]); - $this->tpl->setVariable("SKIN_NAME", $a_set["skin_name"]); - $is_substyle = $a_set["substyle_of"] != ""; - - if(!$is_substyle) { - $this->tpl->setVariable("USERS", $a_set["users"]); - }else{ - $this->tpl->setVariable("USERS", "-"); - } - - if($a_set["id"] != "other"){ - $this->tpl->setCurrentBlock("default_input"); - - if(!$is_substyle) { - $this->tpl->setVariable("DEFAULT_ID", $a_set["id"]); - if (ilSystemStyleSettings::getCurrentDefaultSkin() == $a_set["skin_id"] && - ilSystemStyleSettings::getCurrentDefaultStyle() == $a_set["style_id"] - ) { - $this->tpl->setVariable("CHECKED_DEFAULT", ' checked="checked" '); - } else { - $this->tpl->setVariable("CHECKED_DEFAULT", ''); - } - $this->tpl->parseCurrentBlock(); - } - - $this->tpl->setCurrentBlock("active_input"); - $this->tpl->setVariable("ACTIVE_ID", $a_set["id"]); - - if($is_substyle){ - $this->tpl->setVariable("DISABLED_ACTIVE", 'disabled'); - - if (ilSystemStyleSettings::_lookupActivatedStyle($a_set["skin_id"], $a_set["substyle_of"])){ - $this->tpl->setVariable("CHECKED_ACTIVE", ' checked="checked" '); - }else{ - $this->tpl->setVariable("CHECKED_ACTIVE", ''); - } - }else{ - if (ilSystemStyleSettings::_lookupActivatedStyle($a_set["skin_id"], $a_set["style_id"])){ - $this->tpl->setVariable("CHECKED_ACTIVE", ' checked="checked" '); - }else{ - $this->tpl->setVariable("CHECKED_ACTIVE", ''); - } - } - - $this->tpl->parseCurrentBlock(); - - } - - if($is_substyle){ - $this->tpl->setVariable("SUB_STYLE_OF", $a_set["substyle_of_name"]); - - $assignments = ilSystemStyleSettings::getSubStyleCategoryAssignments( - $a_set["skin_id"], - $a_set["substyle_of"], - $a_set["style_id"] - ); - - $categories = []; - - foreach($assignments as $assignment) { - $category_title = ilObject::_lookupTitle(ilObject::_lookupObjId($assignment["ref_id"])); - if($category_title){ - $categories[] = $category_title; - } - } - - $listing = $DIC->ui()->factory()->listing()->unordered($categories); - $this->tpl->setVariable("CATEGORIES", - $this->lng->txt("local").$DIC->ui()->renderer()->render($listing)); - }else{ - $this->tpl->setVariable("SUB_STYLE_OF", ""); - $this->tpl->setVariable("CATEGORIES", $this->lng->txt("global")); - } - - if($this->isWithActions()){ - if($a_set["skin_id"]=="other"){ - $this->tpl->setCurrentBlock("actions"); - $this->tpl->setVariable("ACTIONS", ""); - $this->tpl->parseCurrentBlock(); - } - else { - $action_list = new ilAdvancedSelectionListGUI(); - $action_list->setId("id_action_list_" . $a_set["id"]); - $action_list->setListTitle($this->lng->txt("actions")); - - if($this->isReadDocumentation()){ - $DIC->ctrl()->setParameterByClass('ilSystemStyleDocumentationGUI','skin_id', $a_set["skin_id"]); - $DIC->ctrl()->setParameterByClass('ilSystemStyleDocumentationGUI','style_id', $a_set["style_id"]); - $action_list->addItem($this->lng->txt('open_documentation'), - 'documentation', $this->ctrl->getLinkTargetByClass('ilSystemStyleDocumentationGUI', 'entries')); - } - - if ($this->isManagementEnabled()) { - - $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI', 'skin_id', $a_set["skin_id"]); - $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI', 'style_id', $a_set["style_id"]); - - $this->ctrl->setParameterByClass('ilSystemStyleOverviewGUI', 'skin_id', $a_set["skin_id"]); - $this->ctrl->setParameterByClass('ilSystemStyleOverviewGUI', 'style_id', $a_set["style_id"]); + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var bool + */ + protected $with_actions = false; + + /** + * @var bool + */ + protected $management_enabled = false; + + /** + * @var bool + */ + protected $read_documentation = true; + + /** + * ilSystemStylesTableGUI constructor. + * @param int $a_parent_obj + * @param string $a_parent_cmd + */ + public function __construct($a_parent_obj, $a_parent_cmd) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->getStyles(); + + $this->setLimit(9999); + $this->setTitle($this->lng->txt("manage_system_styles")); + $this->addColumn($this->lng->txt("")); + $this->addColumn($this->lng->txt("style_name"), "style_name"); + $this->addColumn($this->lng->txt("skin_name"), "skin_name"); + $this->addColumn($this->lng->txt("sty_substyle_of")); + $this->addColumn($this->lng->txt("scope")); + $this->addColumn($this->lng->txt("default")); + $this->addColumn($this->lng->txt("active")); + $this->addColumn($this->lng->txt("users"), "users"); + $this->setRowTemplate("tpl.sys_styles_row.html", "Services/Style/System"); + $this->setEnableHeader(true); + } + + /** + * @param $management_enabled + * @param bool|true $read_documentation + */ + public function addActions($management_enabled, $read_documentation = true) + { + $this->setManagementEnabled($management_enabled); + $this->setReadDocumentation($read_documentation); + + $this->setFormAction($this->ctrl->getFormAction($this->getParentObject())); + $this->addCommandButton("saveStyleSettings", $this->lng->txt("save")); + $this->setRowTemplate("tpl.sys_styles_row_with_actions.html", "Services/Style/System"); + + if ($read_documentation || $management_enabled) { + $this->setWithActions(true); + + $this->addColumn($this->lng->txt("actions")); + } + if ($management_enabled) { + $this->addMultiCommand("deleteStyles", $this->lng->txt("delete")); + } + } + + /** + * + */ + public function getStyles() + { + // get all user assigned styles + $all_user_styles = ilObjUser::_getAllUserAssignedStyles(); + + // output "other" row for all users, that are not assigned to + // any existing style + $users_missing_styles = 0; + foreach ($all_user_styles as $skin_style_id) { + $style_arr = explode(":", $skin_style_id); + if (!ilStyleDefinition::styleExists($style_arr[1])) { + $users_missing_styles += ilObjUser::_getNumberOfUsersForStyle($style_arr[0], $style_arr[1]); + } + } + $all_styles = ilStyleDefinition::getAllSkinStyles(); + if ($users_missing_styles > 0) { + $all_styles["other"] = + array( + "title" => $this->lng->txt("other"), + "id" => "other", + "template_id" => "", + "skin_id" => "other", + "style_id" => "", + "skin_name" => "other", + "style_name" => "", + "users" => $users_missing_styles + ); + } + + $this->setData($all_styles); + } + + + /** + * @param array $a_set + */ + protected function fillRow($a_set) + { + global $DIC; + + $this->tpl->setVariable("STYLE_NAME", $a_set["style_name"]); + $this->tpl->setVariable("SKIN_NAME", $a_set["skin_name"]); + $is_substyle = $a_set["substyle_of"] != ""; + + if (!$is_substyle) { + $this->tpl->setVariable("USERS", $a_set["users"]); + } else { + $this->tpl->setVariable("USERS", "-"); + } + + if ($a_set["id"] != "other") { + $this->tpl->setCurrentBlock("default_input"); + + if (!$is_substyle) { + $this->tpl->setVariable("DEFAULT_ID", $a_set["id"]); + if (ilSystemStyleSettings::getCurrentDefaultSkin() == $a_set["skin_id"] && + ilSystemStyleSettings::getCurrentDefaultStyle() == $a_set["style_id"] + ) { + $this->tpl->setVariable("CHECKED_DEFAULT", ' checked="checked" '); + } else { + $this->tpl->setVariable("CHECKED_DEFAULT", ''); + } + $this->tpl->parseCurrentBlock(); + } + + $this->tpl->setCurrentBlock("active_input"); + $this->tpl->setVariable("ACTIVE_ID", $a_set["id"]); + + if ($is_substyle) { + $this->tpl->setVariable("DISABLED_ACTIVE", 'disabled'); + + if (ilSystemStyleSettings::_lookupActivatedStyle($a_set["skin_id"], $a_set["substyle_of"])) { + $this->tpl->setVariable("CHECKED_ACTIVE", ' checked="checked" '); + } else { + $this->tpl->setVariable("CHECKED_ACTIVE", ''); + } + } else { + if (ilSystemStyleSettings::_lookupActivatedStyle($a_set["skin_id"], $a_set["style_id"])) { + $this->tpl->setVariable("CHECKED_ACTIVE", ' checked="checked" '); + } else { + $this->tpl->setVariable("CHECKED_ACTIVE", ''); + } + } + + $this->tpl->parseCurrentBlock(); + } + + if ($is_substyle) { + $this->tpl->setVariable("SUB_STYLE_OF", $a_set["substyle_of_name"]); + + $assignments = ilSystemStyleSettings::getSubStyleCategoryAssignments( + $a_set["skin_id"], + $a_set["substyle_of"], + $a_set["style_id"] + ); + + $categories = []; + + foreach ($assignments as $assignment) { + $category_title = ilObject::_lookupTitle(ilObject::_lookupObjId($assignment["ref_id"])); + if ($category_title) { + $categories[] = $category_title; + } + } + + $listing = $DIC->ui()->factory()->listing()->unordered($categories); + $this->tpl->setVariable( + "CATEGORIES", + $this->lng->txt("local") . $DIC->ui()->renderer()->render($listing) + ); + } else { + $this->tpl->setVariable("SUB_STYLE_OF", ""); + $this->tpl->setVariable("CATEGORIES", $this->lng->txt("global")); + } + + if ($this->isWithActions()) { + if ($a_set["skin_id"]=="other") { + $this->tpl->setCurrentBlock("actions"); + $this->tpl->setVariable("ACTIONS", ""); + $this->tpl->parseCurrentBlock(); + } else { + $action_list = new ilAdvancedSelectionListGUI(); + $action_list->setId("id_action_list_" . $a_set["id"]); + $action_list->setListTitle($this->lng->txt("actions")); + + if ($this->isReadDocumentation()) { + $DIC->ctrl()->setParameterByClass('ilSystemStyleDocumentationGUI', 'skin_id', $a_set["skin_id"]); + $DIC->ctrl()->setParameterByClass('ilSystemStyleDocumentationGUI', 'style_id', $a_set["style_id"]); + $action_list->addItem( + $this->lng->txt('open_documentation'), + 'documentation', + $this->ctrl->getLinkTargetByClass('ilSystemStyleDocumentationGUI', 'entries') + ); + } + + if ($this->isManagementEnabled()) { + $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI', 'skin_id', $a_set["skin_id"]); + $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI', 'style_id', $a_set["style_id"]); + + $this->ctrl->setParameterByClass('ilSystemStyleOverviewGUI', 'skin_id', $a_set["skin_id"]); + $this->ctrl->setParameterByClass('ilSystemStyleOverviewGUI', 'style_id', $a_set["style_id"]); $config = new ilSystemStyleConfig(); if ($a_set["skin_id"] != $config->getDefaultSkinId()) { - $this->addManagementActionsToList($action_list); - $this->addMultiActions($a_set["id"]); - } - if (!$is_substyle && $a_set["skin_id"] != "default") { - $action_list->addItem($this->lng->txt('export'), 'export', $this->ctrl->getLinkTargetByClass('ilSystemStyleOverviewGUI', 'export')); - } - } - - - $this->tpl->setCurrentBlock("actions"); - $this->tpl->setVariable("ACTIONS", $action_list->getHTML()); - $this->tpl->parseCurrentBlock(); - } - } - } - - protected function addManagementActionsToList(ilAdvancedSelectionListGUI $action_list){ - $action_list->addItem($this->lng->txt('edit'),'edit',$this->ctrl->getLinkTargetByClass('ilSystemStyleSettingsGUI')); - $action_list->addItem($this->lng->txt('delete'),'delete',$this->ctrl->getLinkTargetByClass('ilSystemStyleOverviewGUI','deleteStyle')); - } - - protected function addMultiActions($id){ - $this->tpl->setCurrentBlock("multi_actions"); - $this->tpl->setVariable("MULTI_ACTIONS_ID", $id); - $this->tpl->parseCurrentBlock(); - } - - /** - * @return boolean - */ - public function isWithActions() - { - return $this->with_actions; - } - - /** - * @param boolean $with_actions - */ - public function setWithActions($with_actions) - { - $this->with_actions = $with_actions; - } - - /** - * @return boolean - */ - public function isManagementEnabled() - { - return $this->management_enabled; - } - - /** - * @param boolean $management_enabled - */ - public function setManagementEnabled($management_enabled) - { - $this->management_enabled = $management_enabled; - } - - /** - * @return boolean - */ - public function isReadDocumentation() - { - return $this->read_documentation; - } - - /** - * @param boolean $read_documentation - */ - public function setReadDocumentation($read_documentation) - { - $this->read_documentation = $read_documentation; - } + $this->addManagementActionsToList($action_list); + $this->addMultiActions($a_set["id"]); + } + if (!$is_substyle && $a_set["skin_id"] != "default") { + $action_list->addItem($this->lng->txt('export'), 'export', $this->ctrl->getLinkTargetByClass('ilSystemStyleOverviewGUI', 'export')); + } + } + + + $this->tpl->setCurrentBlock("actions"); + $this->tpl->setVariable("ACTIONS", $action_list->getHTML()); + $this->tpl->parseCurrentBlock(); + } + } + } + + protected function addManagementActionsToList(ilAdvancedSelectionListGUI $action_list) + { + $action_list->addItem($this->lng->txt('edit'), 'edit', $this->ctrl->getLinkTargetByClass('ilSystemStyleSettingsGUI')); + $action_list->addItem($this->lng->txt('delete'), 'delete', $this->ctrl->getLinkTargetByClass('ilSystemStyleOverviewGUI', 'deleteStyle')); + } + + protected function addMultiActions($id) + { + $this->tpl->setCurrentBlock("multi_actions"); + $this->tpl->setVariable("MULTI_ACTIONS_ID", $id); + $this->tpl->parseCurrentBlock(); + } + + /** + * @return boolean + */ + public function isWithActions() + { + return $this->with_actions; + } + + /** + * @param boolean $with_actions + */ + public function setWithActions($with_actions) + { + $this->with_actions = $with_actions; + } + + /** + * @return boolean + */ + public function isManagementEnabled() + { + return $this->management_enabled; + } + + /** + * @param boolean $management_enabled + */ + public function setManagementEnabled($management_enabled) + { + $this->management_enabled = $management_enabled; + } + + /** + * @return boolean + */ + public function isReadDocumentation() + { + return $this->read_documentation; + } + + /** + * @param boolean $read_documentation + */ + public function setReadDocumentation($read_documentation) + { + $this->read_documentation = $read_documentation; + } } diff --git a/Services/Style/System/classes/Settings/class.ilSubStyleAssignmentGUI.php b/Services/Style/System/classes/Settings/class.ilSubStyleAssignmentGUI.php index b92e576323b43c4e9b96e92f4afa73a5e789c9ab..b328702e2496a70c897980282517b2dac088fff5 100644 --- a/Services/Style/System/classes/Settings/class.ilSubStyleAssignmentGUI.php +++ b/Services/Style/System/classes/Settings/class.ilSubStyleAssignmentGUI.php @@ -16,52 +16,51 @@ include_once("Services/Style/System/classes/Settings/class.ilSysStyleCatAssignme */ class ilSubStyleAssignmentGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilSystemStyleSettingsGUI - */ - protected $parent_gui; - - /** - * @var ilTree - */ - protected $tree; - - - /** - * Constructor - */ - function __construct(ilSystemStyleSettingsGUI $parent_gui) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->toolbar = $DIC->toolbar(); - $this->tpl = $DIC["tpl"]; - $this->parent_gui = $parent_gui; - $this->tree = $DIC["tree"]; - - } + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilSystemStyleSettingsGUI + */ + protected $parent_gui; + + /** + * @var ilTree + */ + protected $tree; + + + /** + * Constructor + */ + public function __construct(ilSystemStyleSettingsGUI $parent_gui) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->toolbar = $DIC->toolbar(); + $this->tpl = $DIC["tpl"]; + $this->parent_gui = $parent_gui; + $this->tree = $DIC["tree"]; + } /** * Assign styles to categories @@ -70,104 +69,112 @@ class ilSubStyleAssignmentGUI * @param ilSkinStyleXML $substyle * @throws ilSystemStyleException */ - function assignStyle(ilSkinXML $skin,ilSkinStyleXML $substyle) - { - $style = $skin->getStyle($substyle->getSubstyleOf()); - - $this->toolbar->addFormButton($this->lng->txt("sty_add_assignment"), "addAssignment"); - $this->toolbar->setFormAction($this->ctrl->getFormAction($this->getParentGui())); - - $tab = new ilSysStyleCatAssignmentTableGUI($this->getParentGui(), "assignStyleToCat",$skin->getId(), $style->getId(), - $substyle->getId()); - - $this->tpl->setContent($tab->getHTML()); - } - - - /** - * Add style category assignment - */ - function addAssignment() - { - - include_once 'Services/Search/classes/class.ilSearchRootSelector.php'; - $exp = new ilSearchRootSelector( - $this->ctrl->getLinkTarget($this->getParentGui(),'addStyleCatAssignment')); - $exp->setExpand($_GET["search_root_expand"] ? $_GET["search_root_expand"] : $this->tree->readRootId()); - $exp->setExpandTarget($this->ctrl->getLinkTarget($this->getParentGui(),'addAssignment')); - $exp->setTargetClass(get_class($this->getParentGui())); - $exp->setCmd('saveAssignment'); - $exp->setClickableTypes(["cat"]); - - $exp->setOutput(0); - $this->tpl->setContent($exp->getOutput()); - } - - - /** - * Save style category assignment - * - * @param ilSkinXML $skin - * @param ilSkinStyleXML $substyle - */ - function saveAssignment(ilSkinXML $skin,ilSkinStyleXML $substyle) - { - $style = $skin->getStyle($substyle->getSubstyleOf()); - try{ - ilSystemStyleSettings::writeSystemStyleCategoryAssignment($skin->getId(), $style->getId(), - $substyle->getId(), $_GET["root_id"]); - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - }catch(ilSystemStyleException $e){ - ilUtil::sendFailure($this->lng->txt("msg_assignment_failed").$e->getMessage(), true); - - } - - - $this->ctrl->redirect($this->getParentGui(), "assignStyle"); - } - - /** - * Delete system style to category assignments - * - * @param ilSkinXML $skin - * @param ilSkinStyleXML $substyle - */ - function deleteAssignments(ilSkinXML $skin,ilSkinStyleXML $substyle) - { - $style = $skin->getStyle($substyle->getSubstyleOf()); - - - if (is_array($_POST["id"])) - { - foreach ($_POST["id"] as $id) - { - $id_arr = explode(":", $id); - ilSystemStyleSettings::deleteSystemStyleCategoryAssignment($skin->getId(), $style->getId(), - $substyle->getId(), $id_arr[1]); - } - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - }else{ - ilUtil::sendFailure($this->lng->txt("no_style_selected"), true); - } - - $this->ctrl->redirect($this->getParentGui(), "assignStyle"); - } - - /** - * @return ilSystemStyleSettingsGUI - */ - public function getParentGui() - { - return $this->parent_gui; - } - - /** - * @param ilSystemStyleSettingsGUI $parent_gui - */ - public function setParentGui($parent_gui) - { - $this->parent_gui = $parent_gui; - } - - -} \ No newline at end of file + public function assignStyle(ilSkinXML $skin, ilSkinStyleXML $substyle) + { + $style = $skin->getStyle($substyle->getSubstyleOf()); + + $this->toolbar->addFormButton($this->lng->txt("sty_add_assignment"), "addAssignment"); + $this->toolbar->setFormAction($this->ctrl->getFormAction($this->getParentGui())); + + $tab = new ilSysStyleCatAssignmentTableGUI( + $this->getParentGui(), + "assignStyleToCat", + $skin->getId(), + $style->getId(), + $substyle->getId() + ); + + $this->tpl->setContent($tab->getHTML()); + } + + + /** + * Add style category assignment + */ + public function addAssignment() + { + include_once 'Services/Search/classes/class.ilSearchRootSelector.php'; + $exp = new ilSearchRootSelector( + $this->ctrl->getLinkTarget($this->getParentGui(), 'addStyleCatAssignment') + ); + $exp->setExpand($_GET["search_root_expand"] ? $_GET["search_root_expand"] : $this->tree->readRootId()); + $exp->setExpandTarget($this->ctrl->getLinkTarget($this->getParentGui(), 'addAssignment')); + $exp->setTargetClass(get_class($this->getParentGui())); + $exp->setCmd('saveAssignment'); + $exp->setClickableTypes(["cat"]); + + $exp->setOutput(0); + $this->tpl->setContent($exp->getOutput()); + } + + + /** + * Save style category assignment + * + * @param ilSkinXML $skin + * @param ilSkinStyleXML $substyle + */ + public function saveAssignment(ilSkinXML $skin, ilSkinStyleXML $substyle) + { + $style = $skin->getStyle($substyle->getSubstyleOf()); + try { + ilSystemStyleSettings::writeSystemStyleCategoryAssignment( + $skin->getId(), + $style->getId(), + $substyle->getId(), + $_GET["root_id"] + ); + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + } catch (ilSystemStyleException $e) { + ilUtil::sendFailure($this->lng->txt("msg_assignment_failed") . $e->getMessage(), true); + } + + + $this->ctrl->redirect($this->getParentGui(), "assignStyle"); + } + + /** + * Delete system style to category assignments + * + * @param ilSkinXML $skin + * @param ilSkinStyleXML $substyle + */ + public function deleteAssignments(ilSkinXML $skin, ilSkinStyleXML $substyle) + { + $style = $skin->getStyle($substyle->getSubstyleOf()); + + + if (is_array($_POST["id"])) { + foreach ($_POST["id"] as $id) { + $id_arr = explode(":", $id); + ilSystemStyleSettings::deleteSystemStyleCategoryAssignment( + $skin->getId(), + $style->getId(), + $substyle->getId(), + $id_arr[1] + ); + } + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + } else { + ilUtil::sendFailure($this->lng->txt("no_style_selected"), true); + } + + $this->ctrl->redirect($this->getParentGui(), "assignStyle"); + } + + /** + * @return ilSystemStyleSettingsGUI + */ + public function getParentGui() + { + return $this->parent_gui; + } + + /** + * @param ilSystemStyleSettingsGUI $parent_gui + */ + public function setParentGui($parent_gui) + { + $this->parent_gui = $parent_gui; + } +} diff --git a/Services/Style/System/classes/Settings/class.ilSysStyleCatAssignmentTableGUI.php b/Services/Style/System/classes/Settings/class.ilSysStyleCatAssignmentTableGUI.php index 6388ac430d26307076ba403b16150082d2a2e914..cfae2038c106d5d00fd436bdd90c5afd25cd32a5 100644 --- a/Services/Style/System/classes/Settings/class.ilSysStyleCatAssignmentTableGUI.php +++ b/Services/Style/System/classes/Settings/class.ilSysStyleCatAssignmentTableGUI.php @@ -14,53 +14,53 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilSysStyleCatAssignmentTableGUI extends ilTable2GUI { - /** - * ilSysStyleCatAssignmentTableGUI constructor. - * @param int $a_parent_obj - * @param string $a_parent_cmd - * @param string $skin_id - * @param $style_id - * @param $sub_style_id - */ - function __construct($a_parent_obj, $a_parent_cmd,$skin_id,$style_id, $sub_style_id) - { - global $DIC; - - parent::__construct($a_parent_obj, $a_parent_cmd); + /** + * ilSysStyleCatAssignmentTableGUI constructor. + * @param int $a_parent_obj + * @param string $a_parent_cmd + * @param string $skin_id + * @param $style_id + * @param $sub_style_id + */ + public function __construct($a_parent_obj, $a_parent_cmd, $skin_id, $style_id, $sub_style_id) + { + global $DIC; + + parent::__construct($a_parent_obj, $a_parent_cmd); - $this->skin_id = $skin_id; - $this->style_id = $style_id; - $this->sub_style_id = $sub_style_id; + $this->skin_id = $skin_id; + $this->style_id = $style_id; + $this->sub_style_id = $sub_style_id; - - $this->getStyleCatAssignments(); - $this->setTitle($this->lng->txt("sty_cat_assignments")); - - $this->addColumn("", "", "1"); - $this->addColumn($this->lng->txt("obj_cat")); + + $this->getStyleCatAssignments(); + $this->setTitle($this->lng->txt("sty_cat_assignments")); + + $this->addColumn("", "", "1"); + $this->addColumn($this->lng->txt("obj_cat")); - $this->setFormAction($DIC->ctrl()->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.sty_cat_ass_row.html", "Services/Style/System"); + $this->setFormAction($DIC->ctrl()->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.sty_cat_ass_row.html", "Services/Style/System"); - $this->addMultiCommand("deleteAssignments", $DIC->language()->txt("remove_assignment")); - } + $this->addMultiCommand("deleteAssignments", $DIC->language()->txt("remove_assignment")); + } - function getStyleCatAssignments() - { - $this->setData(ilSystemStyleSettings::getSubStyleCategoryAssignments($this->skin_id, $this->style_id,$this->sub_style_id)); - } - - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - - $this->tpl->setVariable("REF_ID", $a_set["ref_id"]); - $this->tpl->setVariable("CATEGORY", - ilObject::_lookupTitle(ilObject::_lookupObjId($a_set["ref_id"]))); - } - + public function getStyleCatAssignments() + { + $this->setData(ilSystemStyleSettings::getSubStyleCategoryAssignments($this->skin_id, $this->style_id, $this->sub_style_id)); + } + + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $this->tpl->setVariable("REF_ID", $a_set["ref_id"]); + $this->tpl->setVariable( + "CATEGORY", + ilObject::_lookupTitle(ilObject::_lookupObjId($a_set["ref_id"])) + ); + } } diff --git a/Services/Style/System/classes/Settings/class.ilSystemStyleSettingsGUI.php b/Services/Style/System/classes/Settings/class.ilSystemStyleSettingsGUI.php index 5f7ae069f0069450bced0782ae996e0bb9cffadf..f872ffba262cb713b5f52e1d464efaad509cf21c 100644 --- a/Services/Style/System/classes/Settings/class.ilSystemStyleSettingsGUI.php +++ b/Services/Style/System/classes/Settings/class.ilSystemStyleSettingsGUI.php @@ -16,381 +16,388 @@ include_once("Services/Style/System/classes/Settings/class.ilSubStyleAssignmentG class ilSystemStyleSettingsGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLanguage - */ - protected $lng; - - /** - * @var ilTemplate - */ - protected $tpl; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->tabs = $DIC->tabs(); - - $this->tpl = $DIC["tpl"]; - } - - - /** - * Execute command - */ - function executeCommand() - { - $cmd = $this->ctrl->getCmd() ? $this->ctrl->getCmd():"edit"; - $system_style_conf = new ilSystemStyleConfig(); - $skin = ilSkinXML::parseFromXML($system_style_conf->getCustomizingSkinPath().$_GET["skin_id"]."/template.xml"); - $style = $skin->getStyle($_GET["style_id"]); - - if($style->isSubstyle()){ - if($cmd == "edit"|| $cmd == "view"){ - $this->setSubStyleSubTabs("edit"); - }else{ - $this->setSubStyleSubTabs("assignStyle"); - } - - } - - switch ($cmd) - { - case "deleteAssignments": - $assign_gui = new ilSubStyleAssignmentGUI($this); - $assign_gui->deleteAssignments($skin,$style); - break; - case "saveAssignment": - $assign_gui = new ilSubStyleAssignmentGUI($this); - $assign_gui->saveAssignment($skin,$style); - break; - case "addAssignment": - $assign_gui = new ilSubStyleAssignmentGUI($this); - $assign_gui->addAssignment($skin,$style); - break; - case "assignStyle": - $assign_gui = new ilSubStyleAssignmentGUI($this); - $assign_gui->assignStyle($skin,$style); - break; - case "save": - case "edit": - $this->$cmd(); - break; - default: - $this->edit(); - break; - } - } - - /** - * @param string $active - */ - protected function setSubStyleSubTabs($active = "") { - - $this->tabs->addSubTab('edit', $this->lng->txt('settings'), $this->ctrl->getLinkTargetByClass('ilsystemstylesettingsgui')); - $this->tabs->addSubTab('assignStyle', $this->lng->txt('assignment'), $this->ctrl->getLinkTargetByClass('ilsystemstylesettingsgui',"assignStyle")); - - $this->tabs->activateSubTab($active); - } - - protected function edit(){ - $form = $this->editSystemStyleForm(); - $this->getPropertiesValues($form); - $this->tpl->setContent($form->getHTML()); - - } - - /** - * Get values for edit properties form - */ - function getPropertiesValues($form) - { - global $DIC; - - if(!$_GET["skin_id"]){ - throw new ilSystemStyleException(ilSystemStyleException::NO_SKIN_ID); - } - if(!$_GET["style_id"]){ - throw new ilSystemStyleException(ilSystemStyleException::NO_STYLE_ID); - } - $system_style_config = new ilSystemStyleConfig(); - $skin = ilSkinXML::parseFromXML($system_style_config->getCustomizingSkinPath().$_GET["skin_id"]."/template.xml"); - $style = $skin->getStyle($_GET["style_id"]); - $values["skin_id"] = $skin->getId(); - $values["skin_name"] = $skin->getName(); - $values["style_id"] = $style->getId(); - $values["style_name"] = $style->getName(); - $values["image_dir"] = $style->getImageDirectory(); - $values["font_dir"] = $style->getFontDirectory(); - $values["sound_dir"] = $style->getSoundDirectory(); - - - if($style->isSubstyle()){ - $values["parent_style"] = $style->getSubstyleOf(); - }else{ - $values["active"] = ilSystemStyleSettings::_lookupActivatedStyle($skin->getId(),$style->getId()); - $is_personal_style = $DIC->user()->getPref("skin")==$skin->getId() && $DIC->user()->getPref("style") == $style->getId(); - $values["personal"] = $is_personal_style; - $is_default_style = ilSystemStyleSettings::getCurrentDefaultSkin()==$skin->getId() && ilSystemStyleSettings::getCurrentDefaultStyle() == $style->getId(); - $values["default"] = $is_default_style; - } - - $form->setValuesByArray($values); - } - - - protected function save(){ - $form = $this->editSystemStyleForm(); - - $message_stack = new ilSystemStyleMessageStack(); - if ($form->checkInput()) - { - - try{ - $system_style_conf = new ilSystemStyleConfig(); - $skin = ilSkinXML::parseFromXML($system_style_conf->getCustomizingSkinPath().$_GET["skin_id"]."/template.xml"); - $style = $skin->getStyle($_GET["style_id"]); - - if($style->isSubstyle()){ - $this->saveSubStyle($message_stack); - }else{ - $this->saveStyle($message_stack); - } - - $message_stack->prependMessage(new ilSystemStyleMessage($this->lng->txt("msg_sys_style_update"),ilSystemStyleMessage::TYPE_SUCCESS)); - $message_stack->sendMessages(true); - $this->ctrl->redirectByClass("ilSystemStyleSettingsGUI"); - }catch(ilSystemStyleException $e){ - ilUtil::sendFailure($e->getMessage(), true); - } - }else - - $message_stack->sendMessages(); - - $form->setValuesByPost(); - $this->tpl->setContent($form->getHTML()); - } - - - /** - * @param ilSystemStyleMessageStack $message_stack - * @throws ilSystemStyleException - */ - protected function saveStyle(ilSystemStyleMessageStack $message_stack){ - global $DIC; - - $container = ilSystemStyleSkinContainer::generateFromId($_GET['skin_id'],$message_stack); - $old_skin = clone $container->getSkin(); - $old_style = clone $old_skin->getStyle($_GET["style_id"]); - - $new_skin = $container->getSkin(); - $new_skin->setId($_POST["skin_id"]); - $new_skin->setName($_POST["skin_name"]); - $new_skin->getVersionStep($_POST['skin_version']); - - $new_style = $new_skin->getStyle($_GET["style_id"]); - $new_style->setId($_POST["style_id"]); - $new_style->setName($_POST["style_name"]); - $new_style->setCssFile($_POST["style_id"]); - $new_style->setImageDirectory($_POST["image_dir"]); - $new_style->setSoundDirectory($_POST["sound_dir"]); - $new_style->setFontDirectory($_POST["font_dir"]); - - $container->updateSkin($old_skin); - $container->updateStyle($new_style->getId(),$old_style); - - - if($_POST["active"] == 1){ - ilSystemStyleSettings::_activateStyle($new_skin->getId(),$new_style->getId()); - if($_POST["personal"]==1){ - ilSystemStyleSettings::setCurrentUserPrefStyle($new_skin->getId(),$new_style->getId()); - } - if($_POST["default"]==1){ - ilSystemStyleSettings::setCurrentDefaultStyle($new_skin->getId(),$new_style->getId()); - } - }else{ - ilSystemStyleSettings::_deactivateStyle($new_skin->getId(),$new_style->getId()); - $_POST["personal"] = 0; - $_POST["default"] = 0; - } - - $system_style_conf = new ilSystemStyleConfig(); - - //If style has been unset as personal style - if(!$_POST["personal"] && $DIC->user()->getPref("skin") == $new_skin->getId()){ - //Reset to default if possible, else change to delos - if(!$_POST["default"] ){ - ilSystemStyleSettings::setCurrentUserPrefStyle( - ilSystemStyleSettings::getCurrentDefaultSkin(),ilSystemStyleSettings::getCurrentDefaultStyle() - ); - }else{ - ilSystemStyleSettings::setCurrentUserPrefStyle( - $system_style_conf->getDefaultSkinId(),$system_style_conf->getDefaultStyleId() - ); - } - $message_stack->addMessage(new ilSystemStyleMessage( - $this->lng->txt("personal_style_set_to")." ".ilSystemStyleSettings::getCurrentUserPrefSkin().":".ilSystemStyleSettings::getCurrentUserPrefStyle(), - ilSystemStyleMessage::TYPE_SUCCESS) - ); - } - if(!$_POST["default"] && ilSystemStyleSettings::getCurrentDefaultSkin() == $new_skin->getId()){ - ilSystemStyleSettings::setCurrentDefaultStyle( - $system_style_conf->getDefaultSkinId(),$system_style_conf->getDefaultStyleId() - ); - $message_stack->addMessage(new ilSystemStyleMessage( - $this->lng->txt("default_style_set_to")." ".$system_style_conf->getDefaultSkinId().": ".$system_style_conf->getDefaultStyleId(), - ilSystemStyleMessage::TYPE_SUCCESS) - ); - } - $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI','skin_id',$new_skin->getId()); - $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI','style_id',$new_style->getId()); - } - - /** - * @param $message_stack - * @throws ilSystemStyleException - */ - protected function saveSubStyle(ilSystemStyleMessageStack $message_stack){ - $container = ilSystemStyleSkinContainer::generateFromId($_GET['skin_id'],$message_stack); - $skin = $container->getSkin(); + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTemplate + */ + protected $tpl; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->tabs = $DIC->tabs(); + + $this->tpl = $DIC["tpl"]; + } + + + /** + * Execute command + */ + public function executeCommand() + { + $cmd = $this->ctrl->getCmd() ? $this->ctrl->getCmd():"edit"; + $system_style_conf = new ilSystemStyleConfig(); + $skin = ilSkinXML::parseFromXML($system_style_conf->getCustomizingSkinPath() . $_GET["skin_id"] . "/template.xml"); + $style = $skin->getStyle($_GET["style_id"]); + + if ($style->isSubstyle()) { + if ($cmd == "edit"|| $cmd == "view") { + $this->setSubStyleSubTabs("edit"); + } else { + $this->setSubStyleSubTabs("assignStyle"); + } + } + + switch ($cmd) { + case "deleteAssignments": + $assign_gui = new ilSubStyleAssignmentGUI($this); + $assign_gui->deleteAssignments($skin, $style); + break; + case "saveAssignment": + $assign_gui = new ilSubStyleAssignmentGUI($this); + $assign_gui->saveAssignment($skin, $style); + break; + case "addAssignment": + $assign_gui = new ilSubStyleAssignmentGUI($this); + $assign_gui->addAssignment($skin, $style); + break; + case "assignStyle": + $assign_gui = new ilSubStyleAssignmentGUI($this); + $assign_gui->assignStyle($skin, $style); + break; + case "save": + case "edit": + $this->$cmd(); + break; + default: + $this->edit(); + break; + } + } + + /** + * @param string $active + */ + protected function setSubStyleSubTabs($active = "") + { + $this->tabs->addSubTab('edit', $this->lng->txt('settings'), $this->ctrl->getLinkTargetByClass('ilsystemstylesettingsgui')); + $this->tabs->addSubTab('assignStyle', $this->lng->txt('assignment'), $this->ctrl->getLinkTargetByClass('ilsystemstylesettingsgui', "assignStyle")); + + $this->tabs->activateSubTab($active); + } + + protected function edit() + { + $form = $this->editSystemStyleForm(); + $this->getPropertiesValues($form); + $this->tpl->setContent($form->getHTML()); + } + + /** + * Get values for edit properties form + */ + public function getPropertiesValues($form) + { + global $DIC; + + if (!$_GET["skin_id"]) { + throw new ilSystemStyleException(ilSystemStyleException::NO_SKIN_ID); + } + if (!$_GET["style_id"]) { + throw new ilSystemStyleException(ilSystemStyleException::NO_STYLE_ID); + } + $system_style_config = new ilSystemStyleConfig(); + $skin = ilSkinXML::parseFromXML($system_style_config->getCustomizingSkinPath() . $_GET["skin_id"] . "/template.xml"); + $style = $skin->getStyle($_GET["style_id"]); + $values["skin_id"] = $skin->getId(); + $values["skin_name"] = $skin->getName(); + $values["style_id"] = $style->getId(); + $values["style_name"] = $style->getName(); + $values["image_dir"] = $style->getImageDirectory(); + $values["font_dir"] = $style->getFontDirectory(); + $values["sound_dir"] = $style->getSoundDirectory(); + + + if ($style->isSubstyle()) { + $values["parent_style"] = $style->getSubstyleOf(); + } else { + $values["active"] = ilSystemStyleSettings::_lookupActivatedStyle($skin->getId(), $style->getId()); + $is_personal_style = $DIC->user()->getPref("skin")==$skin->getId() && $DIC->user()->getPref("style") == $style->getId(); + $values["personal"] = $is_personal_style; + $is_default_style = ilSystemStyleSettings::getCurrentDefaultSkin()==$skin->getId() && ilSystemStyleSettings::getCurrentDefaultStyle() == $style->getId(); + $values["default"] = $is_default_style; + } + + $form->setValuesByArray($values); + } + + + protected function save() + { + $form = $this->editSystemStyleForm(); + + $message_stack = new ilSystemStyleMessageStack(); + if ($form->checkInput()) { + try { + $system_style_conf = new ilSystemStyleConfig(); + $skin = ilSkinXML::parseFromXML($system_style_conf->getCustomizingSkinPath() . $_GET["skin_id"] . "/template.xml"); + $style = $skin->getStyle($_GET["style_id"]); + + if ($style->isSubstyle()) { + $this->saveSubStyle($message_stack); + } else { + $this->saveStyle($message_stack); + } + + $message_stack->prependMessage(new ilSystemStyleMessage($this->lng->txt("msg_sys_style_update"), ilSystemStyleMessage::TYPE_SUCCESS)); + $message_stack->sendMessages(true); + $this->ctrl->redirectByClass("ilSystemStyleSettingsGUI"); + } catch (ilSystemStyleException $e) { + ilUtil::sendFailure($e->getMessage(), true); + } + } else { + $message_stack->sendMessages(); + } + + $form->setValuesByPost(); + $this->tpl->setContent($form->getHTML()); + } + + + /** + * @param ilSystemStyleMessageStack $message_stack + * @throws ilSystemStyleException + */ + protected function saveStyle(ilSystemStyleMessageStack $message_stack) + { + global $DIC; + + $container = ilSystemStyleSkinContainer::generateFromId($_GET['skin_id'], $message_stack); + $old_skin = clone $container->getSkin(); + $old_style = clone $old_skin->getStyle($_GET["style_id"]); + + $new_skin = $container->getSkin(); + $new_skin->setId($_POST["skin_id"]); + $new_skin->setName($_POST["skin_name"]); + $new_skin->getVersionStep($_POST['skin_version']); + + $new_style = $new_skin->getStyle($_GET["style_id"]); + $new_style->setId($_POST["style_id"]); + $new_style->setName($_POST["style_name"]); + $new_style->setCssFile($_POST["style_id"]); + $new_style->setImageDirectory($_POST["image_dir"]); + $new_style->setSoundDirectory($_POST["sound_dir"]); + $new_style->setFontDirectory($_POST["font_dir"]); + + $container->updateSkin($old_skin); + $container->updateStyle($new_style->getId(), $old_style); + + + if ($_POST["active"] == 1) { + ilSystemStyleSettings::_activateStyle($new_skin->getId(), $new_style->getId()); + if ($_POST["personal"]==1) { + ilSystemStyleSettings::setCurrentUserPrefStyle($new_skin->getId(), $new_style->getId()); + } + if ($_POST["default"]==1) { + ilSystemStyleSettings::setCurrentDefaultStyle($new_skin->getId(), $new_style->getId()); + } + } else { + ilSystemStyleSettings::_deactivateStyle($new_skin->getId(), $new_style->getId()); + $_POST["personal"] = 0; + $_POST["default"] = 0; + } + + $system_style_conf = new ilSystemStyleConfig(); + + //If style has been unset as personal style + if (!$_POST["personal"] && $DIC->user()->getPref("skin") == $new_skin->getId()) { + //Reset to default if possible, else change to delos + if (!$_POST["default"]) { + ilSystemStyleSettings::setCurrentUserPrefStyle( + ilSystemStyleSettings::getCurrentDefaultSkin(), + ilSystemStyleSettings::getCurrentDefaultStyle() + ); + } else { + ilSystemStyleSettings::setCurrentUserPrefStyle( + $system_style_conf->getDefaultSkinId(), + $system_style_conf->getDefaultStyleId() + ); + } + $message_stack->addMessage( + new ilSystemStyleMessage( + $this->lng->txt("personal_style_set_to") . " " . ilSystemStyleSettings::getCurrentUserPrefSkin() . ":" . ilSystemStyleSettings::getCurrentUserPrefStyle(), + ilSystemStyleMessage::TYPE_SUCCESS + ) + ); + } + if (!$_POST["default"] && ilSystemStyleSettings::getCurrentDefaultSkin() == $new_skin->getId()) { + ilSystemStyleSettings::setCurrentDefaultStyle( + $system_style_conf->getDefaultSkinId(), + $system_style_conf->getDefaultStyleId() + ); + $message_stack->addMessage( + new ilSystemStyleMessage( + $this->lng->txt("default_style_set_to") . " " . $system_style_conf->getDefaultSkinId() . ": " . $system_style_conf->getDefaultStyleId(), + ilSystemStyleMessage::TYPE_SUCCESS + ) + ); + } + $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI', 'skin_id', $new_skin->getId()); + $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI', 'style_id', $new_style->getId()); + } + + /** + * @param $message_stack + * @throws ilSystemStyleException + */ + protected function saveSubStyle(ilSystemStyleMessageStack $message_stack) + { + $container = ilSystemStyleSkinContainer::generateFromId($_GET['skin_id'], $message_stack); + $skin = $container->getSkin(); $old_substyle = clone $skin->getStyle($_GET["style_id"]); - if(array_key_exists($_POST['style_id'],$skin->getSubstylesOfStyle($old_substyle->getSubstyleOf()))){ - throw new ilSystemStyleException(ilSystemStyleException::SUBSTYLE_ASSIGNMENT_EXISTS,$_POST['style_id']); + if (array_key_exists($_POST['style_id'], $skin->getSubstylesOfStyle($old_substyle->getSubstyleOf()))) { + throw new ilSystemStyleException(ilSystemStyleException::SUBSTYLE_ASSIGNMENT_EXISTS, $_POST['style_id']); } - $new_substyle = $skin->getStyle($_GET["style_id"]); - $new_substyle->setId($_POST["style_id"]); - $new_substyle->setName($_POST["style_name"]); - $new_substyle->setCssFile($_POST["style_id"]); - $new_substyle->setImageDirectory($_POST["image_dir"]); - $new_substyle->setSoundDirectory($_POST["sound_dir"]); - $new_substyle->setFontDirectory($_POST["font_dir"]); - $new_substyle->setSubstyleOf($old_substyle->getSubstyleOf()); - - $container->updateSkin($skin); - $container->updateStyle($new_substyle->getId(),$old_substyle); - - $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI','skin_id',$skin->getId()); - $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI','style_id',$new_substyle->getId()); - } - - /** - * @return ilPropertyFormGUI - * @throws ilSystemStyleException - */ - protected function editSystemStyleForm(){ - $form = new ilPropertyFormGUI(); - $system_style_conf = new ilSystemStyleConfig(); - - $skin = ilSkinXML::parseFromXML($system_style_conf->getCustomizingSkinPath().$_GET["skin_id"]."/template.xml"); - $style = $skin->getStyle($_GET["style_id"]); - - $form->setFormAction($this->ctrl->getFormActionByClass("ilsystemstylesettingsgui")); - - - if(!$style->isSubstyle()){ - $form->setTitle($this->lng->txt("skin")); - - $ti = new ilTextInputGUI($this->lng->txt("skin_id"), "skin_id"); - $ti->setMaxLength(128); - $ti->setSize(40); - $ti->setRequired(true); - $ti->setInfo($this->lng->txt("skin_id_description")); - $form->addItem($ti); - - $ti = new ilTextInputGUI($this->lng->txt("skin_name"), "skin_name"); - $ti->setInfo($this->lng->txt("skin_name_description")); - $ti->setMaxLength(128); - $ti->setSize(40); - $ti->setRequired(true); - $form->addItem($ti); - - if($skin->isVersionChangeable()) { + $new_substyle = $skin->getStyle($_GET["style_id"]); + $new_substyle->setId($_POST["style_id"]); + $new_substyle->setName($_POST["style_name"]); + $new_substyle->setCssFile($_POST["style_id"]); + $new_substyle->setImageDirectory($_POST["image_dir"]); + $new_substyle->setSoundDirectory($_POST["sound_dir"]); + $new_substyle->setFontDirectory($_POST["font_dir"]); + $new_substyle->setSubstyleOf($old_substyle->getSubstyleOf()); + + $container->updateSkin($skin); + $container->updateStyle($new_substyle->getId(), $old_substyle); + + $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI', 'skin_id', $skin->getId()); + $this->ctrl->setParameterByClass('ilSystemStyleSettingsGUI', 'style_id', $new_substyle->getId()); + } + + /** + * @return ilPropertyFormGUI + * @throws ilSystemStyleException + */ + protected function editSystemStyleForm() + { + $form = new ilPropertyFormGUI(); + $system_style_conf = new ilSystemStyleConfig(); + + $skin = ilSkinXML::parseFromXML($system_style_conf->getCustomizingSkinPath() . $_GET["skin_id"] . "/template.xml"); + $style = $skin->getStyle($_GET["style_id"]); + + $form->setFormAction($this->ctrl->getFormActionByClass("ilsystemstylesettingsgui")); + + + if (!$style->isSubstyle()) { + $form->setTitle($this->lng->txt("skin")); + + $ti = new ilTextInputGUI($this->lng->txt("skin_id"), "skin_id"); + $ti->setMaxLength(128); + $ti->setSize(40); + $ti->setRequired(true); + $ti->setInfo($this->lng->txt("skin_id_description")); + $form->addItem($ti); + + $ti = new ilTextInputGUI($this->lng->txt("skin_name"), "skin_name"); + $ti->setInfo($this->lng->txt("skin_name_description")); + $ti->setMaxLength(128); + $ti->setSize(40); + $ti->setRequired(true); + $form->addItem($ti); + + if ($skin->isVersionChangeable()) { $ti = new ilNonEditableValueGUI($this->lng->txt("skin_version"), "skin_version"); $ti->setInfo($this->lng->txt("skin_version_description")); $ti->setValue($skin->getVersion()); $form->addItem($ti); } - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($this->lng->txt("style")); - $form->addItem($section); - }else{ - $form->setTitle($this->lng->txt("sub_style")); - } - - $ti = new ilTextInputGUI($this->lng->txt("style_id"), "style_id"); - $ti->setMaxLength(128); - $ti->setSize(40); - $ti->setRequired(true); - $ti->setInfo($this->lng->txt("style_id_description")); - $form->addItem($ti); - - $ti = new ilTextInputGUI($this->lng->txt("style_name"), "style_name"); - $ti->setMaxLength(128); - $ti->setSize(40); - $ti->setRequired(true); - $ti->setInfo($this->lng->txt("style_name_description")); - $form->addItem($ti); - - $ti = new ilTextInputGUI($this->lng->txt("image_dir"), "image_dir"); - $ti->setMaxLength(128); - $ti->setSize(40); - $ti->setInfo($this->lng->txt("image_dir_description")); - $form->addItem($ti); - - $ti = new ilTextInputGUI($this->lng->txt("font_dir"), "font_dir"); - $ti->setMaxLength(128); - $ti->setSize(40); - $ti->setInfo($this->lng->txt("font_dir_description")); - $form->addItem($ti); - - $ti = new ilTextInputGUI($this->lng->txt("sound_dir"), "sound_dir"); - $ti->setMaxLength(128); - $ti->setSize(40); - $ti->setInfo($this->lng->txt("sound_dir_description")); - $form->addItem($ti); - - if(!$style->isSubstyle()){ - $section = new ilFormSectionHeaderGUI(); - $section->setTitle($this->lng->txt("system_style_activation")); - $form->addItem($section); - - $active = new ilCheckboxInputGUI($this->lng->txt("system_style_activation"), "active"); - $active->setInfo($this->lng->txt("system_style_activation_description")); - - $set_default = new ilCheckboxInputGUI($this->lng->txt("default"), "default"); - $set_default->setInfo($this->lng->txt("system_style_default_description")); - $active->addSubItem($set_default); - - $set_personal = new ilCheckboxInputGUI($this->lng->txt("personal"), "personal"); - $set_personal->setInfo($this->lng->txt("system_style_personal_description")); - $active->addSubItem($set_personal); - - - $form->addItem($active); - } - - $form->addCommandButton("save", $this->lng->txt("save")); - $form->addCommandButton("cancel", $this->lng->txt("cancel")); - - return $form; - } -} \ No newline at end of file + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($this->lng->txt("style")); + $form->addItem($section); + } else { + $form->setTitle($this->lng->txt("sub_style")); + } + + $ti = new ilTextInputGUI($this->lng->txt("style_id"), "style_id"); + $ti->setMaxLength(128); + $ti->setSize(40); + $ti->setRequired(true); + $ti->setInfo($this->lng->txt("style_id_description")); + $form->addItem($ti); + + $ti = new ilTextInputGUI($this->lng->txt("style_name"), "style_name"); + $ti->setMaxLength(128); + $ti->setSize(40); + $ti->setRequired(true); + $ti->setInfo($this->lng->txt("style_name_description")); + $form->addItem($ti); + + $ti = new ilTextInputGUI($this->lng->txt("image_dir"), "image_dir"); + $ti->setMaxLength(128); + $ti->setSize(40); + $ti->setInfo($this->lng->txt("image_dir_description")); + $form->addItem($ti); + + $ti = new ilTextInputGUI($this->lng->txt("font_dir"), "font_dir"); + $ti->setMaxLength(128); + $ti->setSize(40); + $ti->setInfo($this->lng->txt("font_dir_description")); + $form->addItem($ti); + + $ti = new ilTextInputGUI($this->lng->txt("sound_dir"), "sound_dir"); + $ti->setMaxLength(128); + $ti->setSize(40); + $ti->setInfo($this->lng->txt("sound_dir_description")); + $form->addItem($ti); + + if (!$style->isSubstyle()) { + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($this->lng->txt("system_style_activation")); + $form->addItem($section); + + $active = new ilCheckboxInputGUI($this->lng->txt("system_style_activation"), "active"); + $active->setInfo($this->lng->txt("system_style_activation_description")); + + $set_default = new ilCheckboxInputGUI($this->lng->txt("default"), "default"); + $set_default->setInfo($this->lng->txt("system_style_default_description")); + $active->addSubItem($set_default); + + $set_personal = new ilCheckboxInputGUI($this->lng->txt("personal"), "personal"); + $set_personal->setInfo($this->lng->txt("system_style_personal_description")); + $active->addSubItem($set_personal); + + + $form->addItem($active); + } + + $form->addCommandButton("save", $this->lng->txt("save")); + $form->addCommandButton("cancel", $this->lng->txt("cancel")); + + return $form; + } +} diff --git a/Services/Style/System/classes/Utilities/class.ilSkinStyleXML.php b/Services/Style/System/classes/Utilities/class.ilSkinStyleXML.php index ef2db09b92ae66dedfd69b50d9b5eb091ab14812..86f71f5189039065e7e466f0925c237992b8f805 100644 --- a/Services/Style/System/classes/Utilities/class.ilSkinStyleXML.php +++ b/Services/Style/System/classes/Utilities/class.ilSkinStyleXML.php @@ -6,53 +6,53 @@ */ class ilSkinStyleXML { - /** - * Id of the skin. Currently css and less files are named accordingely - * @var string - */ - protected $id = ""; - - /** - * Name of the style visible in all UI elements - * - * @var string - */ - protected $name = ""; - - /** - * Directory to store sound files into - * - * @var string - */ - protected $sound_directory = ""; - - /** - * Directory to store image files into - * - * @var string - */ - protected $image_directory = ""; - - /** - * Directory to store fonts into - * - * @var string - */ - protected $font_directory = ""; - - /** - * Css file name of the skin - * - * @var string - */ - protected $css_file = ""; - - /** - * Parent of the skin if set - * - * @var string - */ - protected $substyle_of = ""; + /** + * Id of the skin. Currently css and less files are named accordingely + * @var string + */ + protected $id = ""; + + /** + * Name of the style visible in all UI elements + * + * @var string + */ + protected $name = ""; + + /** + * Directory to store sound files into + * + * @var string + */ + protected $sound_directory = ""; + + /** + * Directory to store image files into + * + * @var string + */ + protected $image_directory = ""; + + /** + * Directory to store fonts into + * + * @var string + */ + protected $font_directory = ""; + + /** + * Css file name of the skin + * + * @var string + */ + protected $css_file = ""; + + /** + * Parent of the skin if set + * + * @var string + */ + protected $substyle_of = ""; /** * ilSkinStyleXML constructor. @@ -65,190 +65,194 @@ class ilSkinStyleXML * @param string $parent_style * @throws ilSystemStyleException */ - public function __construct($id, $name, $css_file = "", $image_directory = "", $font_directory = "", $sound_directory = "",$parent_style = "") - { - $this->setId($id); - $this->setName($name); + public function __construct($id, $name, $css_file = "", $image_directory = "", $font_directory = "", $sound_directory = "", $parent_style = "") + { + $this->setId($id); + $this->setName($name); - if($css_file == ""){ - $css_file = $this->getId(); - } + if ($css_file == "") { + $css_file = $this->getId(); + } - if($image_directory == ""){ - $image_directory = "images"; - } + if ($image_directory == "") { + $image_directory = "images"; + } - if($font_directory == ""){ - $font_directory = "fonts"; - } + if ($font_directory == "") { + $font_directory = "fonts"; + } - if($sound_directory == ""){ - $sound_directory = "sound"; - } + if ($sound_directory == "") { + $sound_directory = "sound"; + } - $this->setCssFile($css_file); - $this->setImageDirectory($image_directory); - $this->setFontDirectory($font_directory); - $this->setSoundDirectory($sound_directory); - $this->setSubstyleOf($parent_style); - } + $this->setCssFile($css_file); + $this->setImageDirectory($image_directory); + $this->setFontDirectory($font_directory); + $this->setSoundDirectory($sound_directory); + $this->setSubstyleOf($parent_style); + } /** * @param SimpleXMLElement $xml_element * @return ilSkinStyleXML * @throws ilSystemStyleException */ - static function parseFromXMLElement(SimpleXMLElement $xml_element){ - $style = new self((string)$xml_element->attributes()["id"], - (string)$xml_element->attributes()["name"], - (string)$xml_element->attributes()["css_file"], - (string)$xml_element->attributes()["image_directory"], - (string)$xml_element->attributes()["font_directory"], - (string)$xml_element->attributes()["sound_directory"] - - ); - return $style; - } - - /** - * @return string - */ - public function getId() - { - return $this->id; - } - - /** - * @param $id - * @throws ilSystemStyleException - */ - public function setId($id) - { - if (strpos($id, ' ') !== false) { - throw new ilSystemStyleException(ilSystemStyleException::INVALID_CHARACTERS_IN_ID, $id); - } - $this->id = str_replace(" ","_",$id); - } - - /** - * @return string - */ - public function getName() - { - return $this->name; - } - - /** - * @param string $name - */ - public function setName($name) - { - $this->name = $name; - } - - /** - * @return string - */ - public function getSoundDirectory() - { - return $this->sound_directory; - } - - /** - * @param string $sound_directory - */ - public function setSoundDirectory($sound_directory) - { - $this->sound_directory = $sound_directory; - } - - /** - * @return string - */ - public function getImageDirectory() - { - return $this->image_directory; - } - - /** - * @param string $image_directory - */ - public function setImageDirectory($image_directory) - { - $this->image_directory = $image_directory; - } - - /** - * @return string - */ - public function getCssFile() - { - return $this->css_file; - } - - /** - * @param string $css_file - */ - public function setCssFile($css_file) - { - $this->css_file = $css_file; - } - - /** - * @return string - */ - public function getFontDirectory() - { - return $this->font_directory; - } - - /** - * @param string $font_directory - */ - public function setFontDirectory($font_directory) - { - $this->font_directory = $font_directory; - } - - /** - * Returns the parent style of this style if set - * - * @return string - */ - public function getSubstyleOf() - { - return $this->substyle_of; - } - - /** - * Sets style as sub style of another - * - * @param string $substyle_of - */ - public function setSubstyleOf($substyle_of) - { - $this->substyle_of = $substyle_of; - } - - /** - * Return wheter this style is a substyle of another - * - * @return bool - */ - public function isSubstyle(){ - return $this->getSubstyleOf() != ""; - } - - /** - * Checks if a resource (folder) relative to the style is referenced by this style. Used to decide if folder can be deleted. - * - * @param $resource - * @return bool - */ - public function referencesResource($resource){ - return $this->getCssFile() == $resource - || $this->getImageDirectory() == $resource - || $this->getFontDirectory() == $resource - || $this->getSoundDirectory()== $resource; - } -} \ No newline at end of file + public static function parseFromXMLElement(SimpleXMLElement $xml_element) + { + $style = new self( + (string) $xml_element->attributes()["id"], + (string) $xml_element->attributes()["name"], + (string) $xml_element->attributes()["css_file"], + (string) $xml_element->attributes()["image_directory"], + (string) $xml_element->attributes()["font_directory"], + (string) $xml_element->attributes()["sound_directory"] + + ); + return $style; + } + + /** + * @return string + */ + public function getId() + { + return $this->id; + } + + /** + * @param $id + * @throws ilSystemStyleException + */ + public function setId($id) + { + if (strpos($id, ' ') !== false) { + throw new ilSystemStyleException(ilSystemStyleException::INVALID_CHARACTERS_IN_ID, $id); + } + $this->id = str_replace(" ", "_", $id); + } + + /** + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * @param string $name + */ + public function setName($name) + { + $this->name = $name; + } + + /** + * @return string + */ + public function getSoundDirectory() + { + return $this->sound_directory; + } + + /** + * @param string $sound_directory + */ + public function setSoundDirectory($sound_directory) + { + $this->sound_directory = $sound_directory; + } + + /** + * @return string + */ + public function getImageDirectory() + { + return $this->image_directory; + } + + /** + * @param string $image_directory + */ + public function setImageDirectory($image_directory) + { + $this->image_directory = $image_directory; + } + + /** + * @return string + */ + public function getCssFile() + { + return $this->css_file; + } + + /** + * @param string $css_file + */ + public function setCssFile($css_file) + { + $this->css_file = $css_file; + } + + /** + * @return string + */ + public function getFontDirectory() + { + return $this->font_directory; + } + + /** + * @param string $font_directory + */ + public function setFontDirectory($font_directory) + { + $this->font_directory = $font_directory; + } + + /** + * Returns the parent style of this style if set + * + * @return string + */ + public function getSubstyleOf() + { + return $this->substyle_of; + } + + /** + * Sets style as sub style of another + * + * @param string $substyle_of + */ + public function setSubstyleOf($substyle_of) + { + $this->substyle_of = $substyle_of; + } + + /** + * Return wheter this style is a substyle of another + * + * @return bool + */ + public function isSubstyle() + { + return $this->getSubstyleOf() != ""; + } + + /** + * Checks if a resource (folder) relative to the style is referenced by this style. Used to decide if folder can be deleted. + * + * @param $resource + * @return bool + */ + public function referencesResource($resource) + { + return $this->getCssFile() == $resource + || $this->getImageDirectory() == $resource + || $this->getFontDirectory() == $resource + || $this->getSoundDirectory()== $resource; + } +} diff --git a/Services/Style/System/classes/Utilities/class.ilSkinXML.php b/Services/Style/System/classes/Utilities/class.ilSkinXML.php index 12c5714f46008b53840752acb8903fd741df6c43..0dce1aa44e7a3d0796c2367b92797a91f7677c4a 100644 --- a/Services/Style/System/classes/Utilities/class.ilSkinXML.php +++ b/Services/Style/System/classes/Utilities/class.ilSkinXML.php @@ -11,290 +11,303 @@ include_once("Services/Style/System/classes/Utilities/class.ilSkinStyleXML.php") * @author Timon Amstutz * @version $Id$* */ -class ilSkinXML implements \Iterator, \Countable{ +class ilSkinXML implements \Iterator, \Countable +{ - /** - * ID of the skin, equals the name of the folder this skin is stored in - * @var string - */ - protected $id = ""; + /** + * ID of the skin, equals the name of the folder this skin is stored in + * @var string + */ + protected $id = ""; - /** - * Name of the skin, as provided in the template - * @var string - */ - protected $name = ""; + /** + * Name of the skin, as provided in the template + * @var string + */ + protected $name = ""; - /** - * Styles that the xml of this string provides. - * - * @var ilSkinStyleXML[] - */ - protected $styles = array(); + /** + * Styles that the xml of this string provides. + * + * @var ilSkinStyleXML[] + */ + protected $styles = array(); /** * Version of skin, as provided by the template * * @var string */ - protected $version = "0.1"; - - - /** - * ilSkinXML constructor. - * @param string $name - */ - public function __construct($id, $name) - { - $this->setId($id); - $this->setName($name); - } - - /** - * @param string $path - * @return ilSkinXML - * @throws ilSystemStyleException - */ - public static function parseFromXML($path = ""){ - try{ - $xml = new SimpleXMLElement(file_get_contents($path)); - }catch(Exception $e){ - throw new ilSystemStyleException(ilSystemStyleException::FILE_OPENING_FAILED, $path); - } - - $id = basename (dirname($path)); - $skin = new self($id,(string)$xml->attributes()["name"]); - $skin->setVersion((string)$xml->attributes()["version"]); - - /** - * @var ilSkinStyleXML $last_style - */ - $last_style = null; - - - foreach($xml->children() as $style_xml){ - - $style = ilSkinStyleXML::parseFromXMLElement($style_xml); - - /** - * @var SimpleXMLElement $style_xml - */ - if($style_xml->getName() == "substyle") { - if(!$last_style){ - throw new ilSystemStyleException(ilSystemStyleException::NO_PARENT_STYLE, $style->getId()); - } - $style->setSubstyleOf($last_style->getId()); - }else{ - $last_style = $style; - } - $skin->addStyle($style); - - } - return $skin; - } - - /** - * Stores the skin and all it's styles as xml. - * - * @return string - */ - public function asXML(){ - $xml = new SimpleXMLElement('